SET NOCOUNT ON




IF NOT EXISTS (SELECT * FROM [SysDataDB].dbo.sysobjects WHERE id = OBJECT_ID(N'[SysDataDB].[dbo].[AccountDbList]') AND type in (N'U'))
    BEGIN
        CREATE TABLE [SysDataDB].[dbo].[AccountDbList] 
            (
			  [DbName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '' ) ,		--数据库名称
              [ZTCode] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '' ) ,		--账套编号
              [ZTName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '' ) ,		--账套名称
              [Version] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '' ) ,		--大版本信息              
              [mVersion] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '' ) ,		--小版本信息
              [Display] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '1' ) ,		--是否显示
              [Deleted] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '0' ) ,		--是否删除
              [DispOrder] [int] NULL DEFAULT (0) ,											--显示顺序
              [Actived] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '0' ),		--是否激活
              [isretail] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '0' ),		--是否启用POS
              [productName] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ( '' ),	--产品标示 A8 V3
            )
        ON  [PRIMARY]
    END	
GO
IF NOT EXISTS(
	SELECT a.Name FROM [SysDataDB].dbo.syscolumns a
	INNER JOIN [SysDataDB].dbo.sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountDbList' AND a.Name='dogno'
)
BEGIN
	ALTER TABLE [SysDataDB].[dbo].[AccountDbList] 
		ADD dogno VARCHAR(50) DEFAULT('') NULL
END
GO
UPDATE [SysDataDB].[dbo].[AccountDbList] SET dogno = '' WHERE dogno IS NULL
GO



SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

--drop table AfterSendSMS

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AfterSendSMS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [AfterSendSMS](
	    [id]                int identity(1,1) NOT NULL,
		[mobile]            [varchar](500)  NULL,
		[content]           [varchar](500)  NULL,
		[nick]              [varchar](500)  NULL,
		[msg]               [varchar](500)  NULL
	) ON [PRIMARY]

	-- ********	处理 AfterSendSMS	********
	DELETE FROM AfterSendSMS
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AfterSendSMS' AND a.Name='isgroup'
)
BEGIN
	ALTER TABLE AfterSendSMS ADD isgroup VARCHAR(50) DEFAULT '0' NULL	
END
GO



SET ANSI_NULLS ON


SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'[BeforeSendSMS]',N'U'))
BEGIN
	CREATE TABLE [BeforeSendSMS](
	    [id]                int identity(1,1) NOT NULL,
		[mobile]            [varchar](500)  NULL,
		[content]           [varchar](500)  NULL,
		[nick]              [varchar](500)  NULL,
		[apikey]            [varchar](500)  NULL,
		[msg]               [varchar](500)  NULL
	) ON [PRIMARY]

	-- ********	处理 [BeforeSendSMS]	********
	DELETE FROM [BeforeSendSMS]
END
GO



SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'[BeforeSendSMSForBirthday]',N'U'))
BEGIN
	CREATE TABLE [BeforeSendSMSForBirthday](
	    [id]                int identity(1,1) NOT NULL,
		[mobile]            [varchar](500)  NULL,
		[content]           [varchar](500)  NULL,
		[nick]              [varchar](500)  NULL,
		[apikey]            [varchar](500)  NULL,
		[msg]               [varchar](500)  NULL,
		[birthday]          [varchar](500)  NULL
	) ON [PRIMARY]

	-- ********	处理 [BeforeSendSMS]	********
	DELETE FROM [BeforeSendSMSForBirthday]
END
GO




/****** 对象: 单据表头控制 Table [dbo].[BillHeadControlField]    脚本日期: 2013-11-25  By：duguolei ******/


IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillHeadControlField]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillHeadControlField](
		[ID]			DECIMAL(18,0) Identity(1,1),
		[NameField]		VARCHAR(200)  NOT NULL,     --控制Filed表头名称
		[FullName]		VARCHAR(200),				--名称
		[num]			DECIMAL(18,0) DEFAULT (0),	--序号			
		[BillType]		VARCHAR(10),				--单据billtype
		[tabtype]       VARCHAR(100),				--tab归类
		[isShow]		VARCHAR(10)					--是否显示该列  1显示 0不显示
	)
END


--单据表头配置
IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 184 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','184','priceResponseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 184 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','184','priceResponseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 184 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','184','priceResponseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 184 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','184','priceResponseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 184 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','184','priceResponseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 184 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','184','priceResponseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 305 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','305','retailBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 305 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','305','retailBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 305 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','305','retailBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 305 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','305','retailBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 305 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','305','retailBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 305 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','305','retailBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 215 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','215','retailBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 215 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','215','retailBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 215 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','215','retailBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 215 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','215','retailBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 215 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','215','retailBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 215 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','215','retailBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','300','saleOrderBillHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'ReachDate') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','交货时间','5','300','saleOrderBillHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'ReachDate' 

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'Tel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','6','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'GoodsNumber') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'PackWay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'WayBillcode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','9','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','10','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','11','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','12','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 300 AND NameField = 'preTotal') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','18','300','saleOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'WayBillcode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'GoodsNumber') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'PackWay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'Tel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'edAddress') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'Contrast') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','13','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 11 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','14','11','saleOutStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'Contrast') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 45 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','45','saleBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'entryCodeOut') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 160 AND NameField = 'entryCodeIn') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','160','saleGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 139 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','139','giveBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 139 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','139','giveBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 139 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','139','giveBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 139 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','139','giveBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 139 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','139','giveBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 139 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','139','giveBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 139 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','139','giveBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 140 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','140','wtSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 140 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','140','wtSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 140 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','140','wtSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 140 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','140','wtSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 140 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','140','wtSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 140 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','140','wtSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 140 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','140','wtSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 142 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','142','wtBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 142 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','142','wtBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 142 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','142','wtBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 142 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','142','wtBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 142 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','142','wtBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 142 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','142','wtBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 142 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','142','wtBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 143 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','143','wtChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 143 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','143','wtChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 143 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','143','wtChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 143 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','143','wtChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 143 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','143','wtChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 143 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','143','wtChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 143 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','143','wtChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 141 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','141','wtGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 141 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','141','wtGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 141 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','141','wtGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 141 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','141','wtGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 141 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','141','wtGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 141 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','141','wtGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 141 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','141','wtGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 141 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','141','wtGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'Tel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','5','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'GoodsNumber') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','6','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'PackWay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','7','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'WayBillcode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','8','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','9','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','10','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','11','313','combinationSaleOrderHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'preTotal') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','12','313','combinationSaleOrderHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'ReachDate') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','交货时间','13','313','combinationSaleOrderHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 313 AND NameField = 'ReachDate' 

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'WayBillcode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'GoodsNumber') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'PackWay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'Tel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'edAddress') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'Contrast') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','14','12','combinationSaleHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','15','12','combinationSaleHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'AfterPreference') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','16','12','combinationSaleHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 12 AND NameField = 'AfterPreference'


IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','46','combinationSaleBackHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','46','combinationSaleBackHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','46','combinationSaleBackHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','46','combinationSaleBackHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','46','combinationSaleBackHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','46','combinationSaleBackHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','46','combinationSaleBackHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','46','combinationSaleBackHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'StockInDeadline') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('StockInDeadline','入库期限','9','46','combinationSaleBackHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'AfterPreference') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','46','combinationSaleBackHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 46 AND NameField = 'AfterPreference'

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'WayBillcode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'GoodsNumber') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'PackWay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'Tel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'edAddress') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'Contrast') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','13','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 402 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','14','402','sendPtypeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 403 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','403','sendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 403 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','403','sendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 403 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','403','sendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 403 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','403','sendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 403 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','403','sendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 403 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','403','sendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 403 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','7','403','sendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 204 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','204','buyRequestBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 204 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','204','buyRequestBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 204 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','204','buyRequestBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 204 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','204','buyRequestBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 204 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','204','buyRequestBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 185 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','185','priceQueryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 185 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','185','priceQueryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 185 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','185','priceQueryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 185 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','185','priceQueryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 185 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','185','priceQueryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 185 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','185','priceQueryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','301','buyOrderBillHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'ReachDate') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','到货时间','3','301','buyOrderBillHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'ReachDate' 

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'WayBillcode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','4','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'Tel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','4','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'GoodsNumber') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','5','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'PackWay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','7','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','8','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','9','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'preTotal') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','10','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','11','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 301 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','12','301','buyOrderBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','34','buyInStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','34','buyInStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','34','buyInStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','34','buyInStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','34','buyInStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','34','buyInStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','34','buyInStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'Contrast') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','34','buyInStockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','34','buyInStockBillHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'AfterPreference') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','34','buyInStockBillHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 34 AND NameField = 'AfterPreference'

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','6','buyBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','6','buyBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','6','buyBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','6','buyBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','6','buyBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','6','buyBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','6','buyBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','6','buyBackBillHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'AfterPreference') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','9','6','buyBackBillHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'AfterPreference'

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 6 AND NameField = 'warehouseoutday') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','11','6','buyBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'entryCodeOut') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'entryCodeIn') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','161','buyGoodsExchangeBillHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'AfterPreference') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','161','buyGoodsExchangeBillHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'AfterPreference'

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 161 AND NameField = 'warehouseoutday') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','12','161','buyGoodsExchangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 126 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','126','giveMeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 126 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','126','giveMeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 126 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','126','giveMeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 126 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','126','giveMeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 126 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','126','giveMeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 126 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','126','giveMeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 126 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','126','giveMeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 144 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','144','stSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 144 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','144','stSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 144 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','144','stSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 144 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','144','stSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 144 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','144','stSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 144 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','144','stSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 144 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','144','stSendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 146 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','146','stBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 146 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','146','stBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 146 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','146','stBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 146 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','146','stBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 146 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','146','stBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 146 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','146','stBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 146 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','146','stBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 147 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','147','stChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 147 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','147','stChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 147 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','147','stChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 147 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','147','stChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 147 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','147','stChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 147 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','147','stChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 147 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','147','stChangePriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 145 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','145','stGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 145 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','145','stGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 145 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','145','stGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 145 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','145','stGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 145 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','145','stGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 145 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','145','stGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 145 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','145','stGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 145 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','145','stGatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'Contrast') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 400 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','400','appraisalInstockBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 401 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','401','appraisalBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 401 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','401','appraisalBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 401 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','401','appraisalBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 401 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','401','appraisalBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 401 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','401','appraisalBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 401 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','401','appraisalBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 17 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','17','allotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 17 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','17','allotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 17 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','17','allotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 17 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','17','allotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 17 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','17','allotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 17 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','17','allotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 21 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','21','allotPriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 21 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','21','allotPriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 21 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','21','allotPriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 21 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','21','allotPriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 21 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','21','allotPriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 21 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','21','allotPriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 187 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','187','innerStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 187 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','187','innerStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 187 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','187','innerStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 187 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','187','innerStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 187 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','187','innerStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 187 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','187','innerStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 188 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','188','innerInStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 188 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','188','innerInStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 188 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','188','innerInStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 188 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','188','innerInStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 188 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','188','innerInStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 188 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','188','innerInStockTranBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 201 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','201','otherInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 201 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','201','otherInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 201 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','201','otherInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 201 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','201','otherInBillHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 201 AND NameField = 'OtherOperationSort') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('OtherOperationSort','业务类别','5','201','otherInBillHead','1')
--END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 201 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','201','otherInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 201 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','201','otherInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 201 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','201','otherInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 202 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','202','otherOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 202 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','202','otherOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 202 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','202','otherOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 202 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','202','otherOutBillHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 202 AND NameField = 'OtherOperationSort') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('OtherOperationSort','业务类别','5','202','otherOutBillHead','1')
--END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 202 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','202','otherOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 202 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','202','otherOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 202 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','202','otherOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 306 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','1','306','doStockCheckBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 306 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','2','306','doStockCheckBillHead','1')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 306 AND NameField = 'StockQtyEndDate') 
--BEGIN
--	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('StockQtyEndDate','账面数截止时间','3','306','doStockCheckBillHead','1')
--END
DELETE FROM BillHeadControlField WHERE BillType = 306 AND NameField = 'StockQtyEndDate'


IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 9 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','9','loseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 9 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','9','loseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 9 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','9','loseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 9 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','9','loseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 9 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','9','loseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 9 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','9','loseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 14 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','14','overFlowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 14 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','14','overFlowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 14 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','14','overFlowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 14 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','14','overFlowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 14 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','14','overFlowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 14 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','14','overFlowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 87 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','87','lendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 87 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','87','lendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 87 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','87','lendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 87 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','87','lendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 87 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','87','lendBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 71 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','71','borrowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 71 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','71','borrowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 71 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','71','borrowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 71 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','71','borrowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 71 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','71','borrowBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 88 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','88','lendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 88 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','88','lendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 88 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','88','lendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 88 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','88','lendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 88 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','88','lendBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 72 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','72','BorrowBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 72 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','72','BorrowBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 72 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','72','BorrowBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 72 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','72','BorrowBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 72 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','72','BorrowBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 16 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','16','disassembleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 16 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','16','disassembleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 16 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','16','disassembleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 16 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','16','disassembleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 16 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','16','disassembleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 16 AND NameField = 'entryCodeOut') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','6','16','disassembleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 16 AND NameField = 'entryCodeIn') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','7','16','disassembleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 203 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','203','serialEdiBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 203 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','203','serialEdiBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 203 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','203','serialEdiBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 203 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','203','serialEdiBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 203 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','203','serialEdiBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 22 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','申请部门','1','22','posAllotApplyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 22 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','22','posAllotApplyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 22 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','22','posAllotApplyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 22 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','22','posAllotApplyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 412 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','412','stockUpShelvesBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 412 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','412','stockUpShelvesBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 413 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','413','stockPickBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 413 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','413','stockPickBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'freightperson') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('freightperson','司机','2','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'freighttel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('freighttel','联系电话','3','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'shipperfullname') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shipperfullname','托运方','4','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'shipperperson') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shipperperson','托运联系人','5','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'shippertel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shippertel','托运联系电话','6','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'totalfreight') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('totalfreight','合计运费','7','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'tax') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('tax','税率','8','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'Atype') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atype','付款账户','9','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'TotalInmoney') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('TotalInmoney','付款金额','10','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'transportno') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('transportno','承运商运单号','11','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','12','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 414 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','13','414','stockTransportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 418 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','418','stockImportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 418 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','418','stockImportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 418 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','418','stockImportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 418 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','418','stockImportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 419 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','419','stockExmportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 419 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','419','stockExmportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 419 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','419','stockExmportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 419 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','419','stockExmportBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 420 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','420','stockAllotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 420 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','420','stockAllotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 420 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','420','stockAllotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 420 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','420','stockAllotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 165 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','165','RepairReceiveBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 165 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','165','RepairReceiveBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 165 AND NameField = 'LinkMan') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','165','RepairReceiveBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 165 AND NameField = 'LinkTel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','165','RepairReceiveBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 165 AND NameField = 'LinkAddr') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','165','RepairReceiveBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 165 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','165','RepairReceiveBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 165 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','165','RepairReceiveBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 166 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','166','RepairSelfBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 166 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','166','RepairSelfBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 166 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','166','RepairSelfBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 166 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','166','RepairSelfBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 166 AND NameField = 'entryCodeOut') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','5','166','RepairSelfBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 166 AND NameField = 'entryCodeIn') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','6','166','RepairSelfBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 167 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','167','RepairGetBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 167 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','167','RepairGetBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 167 AND NameField = 'LinkMan') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','167','RepairGetBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 167 AND NameField = 'LinkTel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','167','RepairGetBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 167 AND NameField = 'LinkAddr') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','167','RepairGetBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 167 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','167','RepairGetBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 167 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','167','RepairGetBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 168 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','168','RepairChangeBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 168 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','168','RepairChangeBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 168 AND NameField = 'LinkMan') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','168','RepairChangeBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 168 AND NameField = 'LinkTel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','168','RepairChangeBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 168 AND NameField = 'LinkAddr') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','168','RepairChangeBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 168 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','168','RepairChangeBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 168 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','168','RepairChangeBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 169 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','169','RepairSendBil','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 169 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','169','RepairSendBil','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 169 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','169','RepairSendBil','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 169 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','169','RepairSendBil','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 169 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','169','RepairSendBil','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 170 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','170','RepairSendBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 170 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','170','RepairSendBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 170 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','170','RepairSendBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 170 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','170','RepairSendBackBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 171 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','171','RepairCallBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 171 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','171','RepairCallBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 171 AND NameField = 'LinkMan') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','171','RepairCallBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 171 AND NameField = 'LinkTel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','171','RepairCallBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 171 AND NameField = 'LinkAddr') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','171','RepairCallBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 171 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','171','RepairCallBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 171 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','171','RepairCallBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'LinkMan') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'LinkTel') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'LinkAddr') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'entryCodeOut') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 172 AND NameField = 'entryCodeIn') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','172','RepairGoToBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 173 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','173','RepairAllotInBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 173 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','173','RepairAllotInBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 173 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','173','RepairAllotInBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 173 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','173','RepairAllotInBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 173 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','173','RepairAllotInBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 174 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','174','RepairAllotOutBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 174 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','174','RepairAllotOutBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 174 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','174','RepairAllotOutBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 174 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','174','RepairAllotOutBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 174 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','174','RepairAllotOutBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 175 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','175','RepairAllotBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 175 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','175','RepairAllotBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 175 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','175','RepairAllotBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 175 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','175','RepairAllotBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 175 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','175','RepairAllotBill','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 116 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','116','gatheraddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 116 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','116','gatheraddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 116 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','116','gatheraddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 116 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','116','gatheraddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 116 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','116','gatheraddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 115 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','115','gatherReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 115 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','115','gatherReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 115 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','115','gatherReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 115 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','115','gatherReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 115 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','115','gatherReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 128 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','128','payAddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 128 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','128','payAddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 128 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','128','payAddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 128 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','128','payAddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 128 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','128','payAddBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 129 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','129','payReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 129 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','129','payReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 129 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','129','payReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 129 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','129','payReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 129 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','129','payReduceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 4 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','4','gatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 4 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','4','gatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 4 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','4','gatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 4 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','4','gatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 4 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','4','gatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 4 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','4','gatherBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 189 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','189','preSettleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 189 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','189','preSettleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 189 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','189','preSettleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 189 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','189','preSettleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 189 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','189','preSettleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 189 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','189','preSettleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 66 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','66','payBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 66 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','66','payBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 66 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','66','payBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 66 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','66','payBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 66 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','66','payBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 66 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','66','payBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 190 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','190','preSettlePayBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 190 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','190','preSettlePayBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 190 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','190','preSettlePayBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 190 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','190','preSettlePayBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 190 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','190','preSettlePayBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 190 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','190','preSettlePayBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 148 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','148','advantageBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 148 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','148','advantageBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 148 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','148','advantageBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 148 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','148','advantageBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 148 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','148','advantageBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 148 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','148','advantageBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 148 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','148','advantageBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 150 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','150','advantageGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 150 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','150','advantageGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 150 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','150','advantageGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 150 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','150','advantageGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 150 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','150','advantageGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 150 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','150','advantageGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 150 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','150','advantageGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 149 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','149','priceProtectBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 149 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','149','priceProtectBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 149 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','149','priceProtectBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 149 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','149','priceProtectBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 149 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','149','priceProtectBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 149 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','149','priceProtectBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 149 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','149','priceProtectBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 151 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','151','priceProtectGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 151 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','151','priceProtectGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 151 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','151','priceProtectGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 151 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','151','priceProtectGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 151 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','151','priceProtectGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 151 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','151','priceProtectGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 151 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','151','priceProtectGetBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 450 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','450','wLCancelAfterVerificationBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 450 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','450','wLCancelAfterVerificationBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 450 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','450','wLCancelAfterVerificationBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 450 AND NameField = 'Alertday') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Alertday','收付款期限','4','450','wLCancelAfterVerificationBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 450 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','450','wLCancelAfterVerificationBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 450 AND NameField = 'TotalMoney') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('TotalMoney','本单核销金额','6','450','wLCancelAfterVerificationBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 162 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','162','saleInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 162 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','162','saleInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 162 AND NameField = 'FaPiaoCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','162','saleInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 162 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','162','saleInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 162 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','162','saleInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 162 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','162','saleInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 162 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','162','saleInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 163 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','163','buyInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 163 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','163','buyInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 163 AND NameField = 'FaPiaoCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','163','buyInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 163 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','163','buyInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 163 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','163','buyInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 163 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','163','buyInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 163 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','163','buyInvoiceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 404 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','404','receiptForBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 404 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','404','receiptForBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 404 AND NameField = 'FaPiaoCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','404','receiptForBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 404 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','404','receiptForBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 404 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','404','receiptForBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 404 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','404','receiptForBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 404 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','404','receiptForBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 404 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','10','404','receiptForBuyBillHead','1')
END
UPDATE BillHeadControlField SET FullName = '付款期限' WHERE FullName = '收款期限' AND  BillType = 404 AND NameField = 'AlertDay'

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 405 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','405','receiptForSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 405 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','405','receiptForSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 405 AND NameField = 'FaPiaoCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','405','receiptForSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 405 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','405','receiptForSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 405 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','405','receiptForSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 405 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','405','receiptForSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 405 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','405','receiptForSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 405 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','9','405','receiptForSaleBillHead','1')
END
UPDATE BillHeadControlField SET FullName = '收款期限' WHERE FullName = '付款期限' AND  BillType = 405 AND NameField = 'AlertDay'

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 36 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','36','expenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 36 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','36','expenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 36 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','36','expenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 36 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','36','expenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 36 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收付款期限','5','36','expenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 36 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','36','expenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 36 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','36','expenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 158 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','158','cachExpenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 158 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','158','cachExpenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 158 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','158','cachExpenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 158 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','158','cachExpenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 158 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','158','cachExpenseBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 77 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','77','moneyChangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 77 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','77','moneyChangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 77 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','77','moneyChangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 77 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','77','moneyChangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 77 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','77','moneyChangeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 93 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','93','inComeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 93 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','93','inComeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 93 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','93','inComeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 93 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','93','inComeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 93 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','93','inComeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 93 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','93','inComeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 93 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','93','inComeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 5 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','5','ExpenseHappenBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 5 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','5','ExpenseHappenBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 5 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','5','ExpenseHappenBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 5 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','5','ExpenseHappenBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 5 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','5','ExpenseHappenBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 10 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','10','expenseAllocateBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 10 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','10','expenseAllocateBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 10 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','10','expenseAllocateBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 10 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','10','expenseAllocateBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 10 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','10','expenseAllocateBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 84 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','84','fixedBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 84 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','84','fixedBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 84 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','84','fixedBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 84 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','84','fixedBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 84 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','84','fixedBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 84 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','84','fixedBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 84 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','84','fixedBuyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 85 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','85','fixedSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 85 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','85','fixedSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 85 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','85','fixedSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 85 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','85','fixedSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 85 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','85','fixedSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 85 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','85','fixedSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 85 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','85','fixedSaleBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 78 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','78','depBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 78 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','78','depBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 78 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','78','depBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 78 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','78','depBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 78 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','78','depBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 57 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','57','adpriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 57 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','57','adpriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 57 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','57','adpriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 57 AND NameField = 'warehouseoutday') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','4','57','adpriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 57 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','57','adpriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 57 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','57','adpriceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 159 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','159','accountCredenceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 159 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','159','accountCredenceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 159 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','159','accountCredenceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 159 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','159','accountCredenceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 159 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','159','accountCredenceBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 205 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','205','buyExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 205 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','205','buyExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 205 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','205','buyExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 205 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','205','buyExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 205 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','205','buyExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 206 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','206','saleExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 206 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','206','saleExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 206 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','206','saleExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 206 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','206','saleExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 206 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','206','saleExpenseAmortizeBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 312 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','312','vipPlAddMoneyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 312 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','312','vipPlAddMoneyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 312 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','312','vipPlAddMoneyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 312 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','312','vipPlAddMoneyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 312 AND NameField = 'AlertDay') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','312','vipPlAddMoneyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 312 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','312','vipPlAddMoneyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 312 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','312','vipPlAddMoneyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 423 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','423','CouponInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 423 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','423','CouponInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 423 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','423','CouponInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 423 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','423','CouponInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 423 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','423','CouponInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 424 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','424','CouponOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 424 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','424','CouponOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 424 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','424','CouponOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 424 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','424','CouponOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 424 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','424','CouponOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 425 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','425','CouponAllotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 425 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','425','CouponAllotBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 426 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','426','CouponBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 426 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','426','CouponBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 426 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','426','CouponBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 426 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','426','CouponBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 426 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','426','CouponBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 183 AND NameField = 'Denominated') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','183','qp_CentChange_BillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 183 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','183','qp_CentChange_BillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 183 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','183','qp_CentChange_BillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 183 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','183','qp_CentChange_BillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 183 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','183','qp_CentChange_BillHead','1')
END


IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 428 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','428','CouponStypeInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 428 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','428','CouponStypeInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 428 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','428','CouponStypeInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 428 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','428','CouponStypeInBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 428 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','428','CouponStypeInBillHead','1')
END


IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 429 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','429','CouponStypeOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 429 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','429','CouponStypeOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 429 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','429','CouponStypeOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 429 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','429','CouponStypeOutBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 429 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','429','CouponStypeOutBillHead','1')
END









IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 326 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','5','326','DeliveryApplyBillHead','1')
END


IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 326 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','326','DeliveryApplyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 326 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','326','DeliveryApplyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 326 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','326','DeliveryApplyBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 327 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','5','327','DeliveryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 327 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','5','327','DeliveryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 327 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','327','DeliveryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 327 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','327','DeliveryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 327 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','327','DeliveryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 327 AND NameField = 'entryCode') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','327','DeliveryBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 328 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','5','328','DeliveryBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 328 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','5','328','DeliveryBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 328 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','328','DeliveryBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 328 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','328','DeliveryBackBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 328 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','328','DeliveryBackBillHead','1')
END


IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 329 AND NameField = 'Department') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','5','329','DeliveryCheckBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 329 AND NameField = 'Currency') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','5','329','DeliveryCheckBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 329 AND NameField = 'ExchangeRate') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','329','DeliveryCheckBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 329 AND NameField = 'Explain') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','329','DeliveryCheckBillHead','1')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillHeadControlField WHERE BillType = 329 AND NameField = 'Comment') 
BEGIN
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','329','DeliveryCheckBillHead','1')
END



---------------------------------------------单据表头控制END ------------------------------------------------------


------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------


------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




GO

/****** Object:  Table [dbo].[DDingInfo]    Script Date: 11/25/2015 10:23:33 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF NOT EXISTS(SELECT 1 FROM [SysDataDB]..SysObjects WHERE ID=OBJECT_ID(N'[SysDataDB]..[DDingInfo]',N'U'))
BEGIN
CREATE TABLE [SysDataDB]..[DDingInfo](
	[CorpID] [varchar](500) NULL,
	[CorpSecrect] [varchar](500) NULL,
	[ServerIP] [varchar](50) NULL,
	[ServerPort] [int] NULL,
	[AppID] [varchar](50) NULL,
	[GUID] [nvarchar](50) NULL
) ON [PRIMARY]
END

GO

SET ANSI_PADDING OFF
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_split]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_split]
GO












--实现split功能 的函数
--date    :2003-10-14
CREATE FUNCTION f_split
(
	@SourceSql varchar(MAX),
	@StrSeprate varchar(10)
)
returns @temp TABLE(a varchar(MAX))
AS 
BEGIN
    DECLARE @i int
    SET @SourceSql=RTRIM(LTRIM(@SourceSql))
    SET @i=charindex(@StrSeprate,@SourceSql)
    WHILE @i>=1
	    BEGIN
	        INSERT @temp VALUES(LEFT(@SourceSql,@i-1))
	        SET @SourceSql=SUBSTRING(@SourceSql,@i+1,len(@SourceSql)-@i)
	        SET @i=charindex(@StrSeprate,@SourceSql)
	    END
    IF @SourceSql<>'' 
       INSERT @temp VALUES(@SourceSql)
    RETURN 
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM SysDataDB..sysobjects WHERE id = OBJECT_ID(N'[SysDataDB]..[Fx_OnlineUser]') AND type in (N'U'))
BEGIN
	CREATE TABLE [SysDataDB].[dbo].Fx_OnlineUser(
		[ID]					[int] IDENTITY(1,1) NOT NULL,
		[DbName]				VARCHAR(100) NULL DEFAULT(''),
		[DogNo]					VARCHAR(100) NULL DEFAULT(''),
		[ETypeID_UserTypeID]	[varchar](50),
		[LatestConnectTime]		[datetime] NULL DEFAULT(''),
		[LoginTime]				[datetime] NULL DEFAULT(''),
		[UserName]				[varchar](66) NULL DEFAULT(''),
		[IP]					[varchar](30) NULL DEFAULT(''),
		[Status]				[varchar](20) NULL DEFAULT(''),
		[IPLocal]				[varchar](50) NULL DEFAULT(''),
		[clientFlag]			[varchar](500) NULL  DEFAULT(''),	--客户端标识
		[PollineTime]			INT DEFAULT(0)						--轮询时间
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO



/****** 对象:  Table [dbo].[ptype]    脚本日期: 05/05/2010 14:48:55 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM SysDataDB..sysobjects WHERE id = OBJECT_ID(N'[SysDataDB]..[posBindingTerminal]') AND type in (N'U'))
BEGIN
	CREATE TABLE [SysDataDB]..posBindingTerminal(
		id     INT IDENTITY(1,1),
		posdno	VARCHAR(200),
		posid  INT,
		uuid   VARCHAR(200),
		DataBaseName VARCHAR(200),
		ktypeid	  VARCHAR(50),
		desStr	VARCHAR(2000)
) 

END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='VirtualDirectory' AND b.Name='posBindingTerminal'
)
BEGIN
	ALTER TABLE [SysDataDB]..posBindingTerminal 
		ADD VirtualDirectory	VARCHAR(200) NOT NULL DEFAULT('')
END
GO
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[POSBtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE POSBtype(
		Id INT  PRIMARY KEY IDENTITY(1,1) ,	
		typeid VARCHAR(50), --客户typeid
		bid    INT,		--客户ID			
		Fullname VARCHAR(200), --客户姓名
		Usercode VARCHAR(200),--客户编号
		Comment VARCHAR(500),    --备注
		[Address] VARCHAR(1000) --地址
	)
END
GO


------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='POSBtype' AND a.Name='Posid'
)
BEGIN
	ALTER TABLE POSBtype 
		ADD Posid INT NULL DEFAULT(1)
END
GO


IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSBtype',N'U') AND Name='Usercode')
BEGIN
	ALTER TABLE POSBtype 
		DROP COLUMN Usercode
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSBtype',N'U') AND Name='Fullname')
BEGIN
	ALTER TABLE POSBtype 
		DROP COLUMN Fullname
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSBtype',N'U') AND Name='Comment')
BEGIN
	ALTER TABLE POSBtype 
		DROP COLUMN Comment
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSBtype',N'U') AND Name='Address')
BEGIN
	ALTER TABLE POSBtype 
		DROP COLUMN [Address]
END
GO

------------------------------------------表修改区域结束-------------------------------------------------



/****** 对象:  Table [dbo].[Sys_BaseInfoUsing_Tables]    脚本日期: 05/05/2010 14:49:32 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Sys_BaseInfoUsing_Tables]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Sys_BaseInfoUsing_Tables](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[tblName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[fldName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[basType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]
END
GO
-- 在数据表 Sys_BaseInfoUsing_Tables 中，增加相关的数据搬移备案字段记录
DELETE FROM Sys_BaseInfoUsing_Tables
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('gp_inoutPtypeSerial','InKtypeID','KtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('gp_inoutPtypeSerial','OutKtyeID','KtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('GuestBackIndex','checke','EtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('GuestGetIndex','checke','EtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('GuestPayIndex','checke','EtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('HotList','Operator','EtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LendIndex','checke','EtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('StockCheckIndex','checke','EtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerBTypeID','BTypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerPTypeID ','PTypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerBTypeID2','BTypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerETypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerKTypeID','KTypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerATypeID','ATypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerExpense','ATypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerIncome','ATypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('ManageBType','ManageBTypeID','BTypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Msg_MessageList','SendEmployeeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Msg_MessageList','GetEmployeeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Msg_Online','ConnectID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('News','nAuthorID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Attachment','ETypeID_CreatorTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Message','ETypeID_SenderTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Message','ETypeID_ReceiverTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Message','ETypeID_CreatorTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Message_Bak','ETypeID_SenderTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Message_Bak','ETypeID_ReceiverTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Message_Bak','ETypeID_CreatorTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_OnlineUser','ETypeID_UserTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PersonalDesktop','ETypeID_CreatorTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PersonalMsgNotify_AND','ETypeID_CreatorTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PersonalMsgNotify_AND','PublisherTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PersonalMsgNotify_OR','ETypeID_CreatorTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PersonalMsgNotify_OR','PublisherTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PrivateDB','ETypeID_SenderTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PrivateDB','ETypeID_ReceiverTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PublicDB','ETypeID_CreatorTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PublicDB','ETypeID_ModifierTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Right','ETypeID_EmployeeTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Right','ETypeID_ModifierTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_RightTemplateType','ETypeID_CreatorTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Subscibe','ETypeID_SubsciberTypeID','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Offline_BillIndex','Checke','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Offline_BillIndex','StockID ','KTypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Offline_BillIndex','Assessor','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Offline_Task','StockID','KTypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OrderIndex','Checke','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceProtect','writeid','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('UserGridConfig','employeeid ','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('tmpGain','TypeID','ATypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('ZLCY_luntan','author','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndex','checke','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndex','Assessor','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_PrivateDB','ETypeID_CreatorTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_Product','ETypeID_OpeatorID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('OA_UserInformation','ETypeID_UserTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LocalIndex','Assessor','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('RepairDeal','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('RepairEngage','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CPCX_luntan','OpeatorID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('retailconfig','loginuserid','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_schedule','CreatorTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_Message','SenderTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_Message','ReceiverTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_Message','CreatorTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_MessageNoread','SenderTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_MessageNoread','ReceiverTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_MessageNoread','CreatorTypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('sms_BaseInfoMobile','TypeId','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('sms_BaseInfoMobile','TypeId','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('sms_Log','OperID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('sms_signature','employee','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('DBCONFIG','STOCKID','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('nVipAdjust','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LoginUser','MangerCpaital','ATypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('AccountCredence','ATypeID','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('FaPiaoBillIndex','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('FaPiaoBillIndex','Assessor','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('TCBillindex','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Billindex','KTypeID3','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Billindex','wxManID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('wx_Bill_JieJian','SendBackPTypeID','PTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('wx_Bill_GetBack','JieJianPTypeID','PTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('wx_Bill_Replace','JieJianPTypeID','PTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('wx_Bill_Send','JieJianPTypeID','PTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('wx_Bill_SendBack','SendPTypeID','PTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_btype','createor','EtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('crm_linkman','createor','EtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Stype','BTypeID1','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Stype','BTypeID2','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('SType_InnerARTotal','STypeId2','STypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('STypeMoveBill','KTypeId2','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('AccountCredence','ATypeID','STypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PerformanceDistribution','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindex','updatee','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('SerialAdjustIndex','KTypeId2','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('SerialAdjustIndex','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('SerialAdjustIndex','Poster','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('SerialAdjustBill','BTypeId1','BTypeId')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('SerialAdjustBill','BTypeId2','BTypeId')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('DiyIndex','checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('RequestBill','BTypeId2','BTypeId')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommonPosSaleindex','branchid','STypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommonPosSaleindex','cashier','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommonPosSaleindex','salesman','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('commonposinfo','branchid','STypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('commonposinfo','stockid','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('commonposinfo','etypeid1','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('posretailcash','bankatypeid','ATypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CX_SaleStocksArea','ktypeid','STypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommonPosPtypeCheckNdx','operatorid','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CX_LargessBill','largessptypeid','PTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CX_SalePlanIndex','jtypeid','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('IM_Message_Nosocket','SenderID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('IM_Message_Nosocket','ReceiverID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CM_CarInfo','Driver','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CM_CarUseBill','Driver','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('qp_repairautoinfo','BaoXianBtypeid','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('movebill','KTypeId2','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindex','Poster','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('btype','denominatedid','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindex','dealbtypeid','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindex','tallyid','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindex','atypeid1','ATypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Areatype_CustomColumns','TypeID','AreaTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Btype_CustomColumns','TypeID','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('GBtype_CustomColumns','TypeID','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Dtype_CustomColumns','TypeID','DTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Etype_CustomColumns','TypeID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ktype_CustomColumns','TypeID','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ptype_CustomColumns','TypeID','PTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Stype_CustomColumns','TypeID','STypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('SType','VerifyID','STypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ac_MulColumnAccount','Creator','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ac_MulColumnAccount','CreatorStypeId','STypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('orderindex','dealbtypeid','BTypeID')

--价格体系和促销 start
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceBillIndex','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceDetail','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceDetail','Checker','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceDetail','DeletedR','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceDetailDeleted','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceDetailDeleted','Checker','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceDetailDeleted','DeletedR','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceRule','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceRule','Checker','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceRule','DeletedR','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PromoRule','Checke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PromoRule','Checker','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PromoRule','DeletedR','ETypeID')
--价格体系和促销 end

--凭证
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ac_Voucher','AuditId','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ac_Voucher','teller','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ac_Voucher','recheckid','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ac_Voucher','TallyId','ETypeID')

INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CapitalTransfer_Bill','BankAccountOut','ATypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CapitalTransfer_Bill','BankAccountIn','ATypeID')

--借欠中往来单位
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('LendIndex','dealbtypeid','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PosInfo','dealbtypeid','BTypeID')

--暂估类
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('ReceiptBillIndex','dealbtypeid','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('FaPiaoBillIndex','DealBTypeID','BTypeID')


INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndex','ChargeOffBtypeid','BTypeID')

--促销政策 买够商品，捆绑销售模式 捆绑商品id
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PromoRule_Detail_PromotConfig','bindptypeid','PTypeID')

--调拨申请单 入库仓库ID
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PosAllotApplyBill','InKtypeId','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PosAllotApplyBillIndex','InKtypeId','KTypeID')

--IM消息备份
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('IM_Message_Nosocket_Bak','SenderID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('IM_Message_Nosocket_Bak','ReceiverID','ETypeID')

--网店单据的表
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('WdOrder','employeeid','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('WdOrder','whs_erpid','KtypeID')

--优惠券
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_TypeInfo','Maker','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','OutKTypeId','KtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','InKTypeId','KtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','DealBTypeId','BtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','Poster','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','Maker','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','Checker','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','ATypeId1','ATypeId')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','TallyId','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Coupon_BillIndex','checke','EtypeID')

--会员
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('nVipCardSign','jkstypeid','STypeID')

--WMS新增
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('WmsErpStockContrastSetting','ERP_TypeId','KtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('WmsErpBTypeContrastSetting','ERP_TypeId','btypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('WmsErpEmployeeContrastSetting','ERP_TypeId','etypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('WmsErpPtypeContrastSetting','ERP_TypeId','PtypeID') 


INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('POSEmployee','etypeid','etypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('POSAccount','ntypeid','ntypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('POSBtype','TypeId','btypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('POSPtype','PTypeId','PtypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('POSOperator','etypeid','etypeid') 

INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndex','cwchecker','EtypeID')

--实物库存
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('factindex','KTypeId2','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('factindex','checke','EtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('factindex','updateE','EtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('factindex','Poster','EtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('factindex','DealBTypeID','BtypeID')

--财务反审核人、价格表档案反审核人、促销政策反审核人、提成规则反审核人、经营历程反审核人
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('Ac_Voucher','RChecker','etypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceDetail','RChecker','etypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PromoRule','RChecker','etypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PriceDetailDeleted','RChecker','etypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndex','RChecker','etypeID') 

--审核列表制单人判断
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('AuditingBill','Checke','etypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('TCBillindex','unChecke','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PosAllotApplyBillIndex','ApplyEtypeId','ETypeID')

--门店配送单
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('PosAllotApplyBillIndex','ApplyEtypeId','ETypeID')


--自动存草稿需要搬移的数据
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndexAutoDraft','checke','ETypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndexAutoDraft','Assessor','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillindexAutoDraft','KTypeID3','KTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillindexAutoDraft','wxManID','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindexAutoDraft','updatee','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindexAutoDraft','Poster','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindexAutoDraft','dealbtypeid','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindexAutoDraft','tallyid','ETypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindexAutoDraft','atypeid1','ATypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindexAutoDraft','ChargeOffBtypeid','BTypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindexAutoDraft','cwchecker','EtypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('billindexAutoDraft','RChecker','etypeID') 
--V992补漏数据
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('onShelvespickIndex','checke','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('onShelvespickIndex','updatee','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('onShelvespickIndex','poster','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('AssetIncSplit','checke','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('AssetIncSplit','checker','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommissionBillNew','checke','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommissionBillNew','checker','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommissionBillNew','poster','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommissionBillNew','fchecker','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('CommissionBillNew','fposter','etypeID')
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndex','ktypeid2','ktypeID') 
INSERT INTO Sys_BaseInfoUsing_Tables (tblName,fldName,basType)VALUES ('BillIndexAutoDraft','ktypeid2','ktypeID')

--End 数据搬移	




GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始----------------------------------------------- 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sysdata]    脚本日期: 05/05/2010 14:49:33 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*
	说明：
		  802~997
	      1000~9998
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sysdata]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sysdata](
		[SubNo] [numeric](4, 0) NOT NULL,
		[SubName] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[SubValue] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[SubComment] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]
	
	-- ********	处理 SysData	********
	DELETE FROM SysData
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (1,'period','1','期号')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (2,'costing','0','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (5,'SaleCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (7,'StockBackCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (9,'PayCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (11,'OverFlowCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (13,'MoveBjCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (15,'LoseCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (17,'ChangeAccountCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (19,'CanAuditing','1','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (4,'inicanmodify','T','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (6,'StockCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (8,'SaleBackCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (10,'ReceiverCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (12,'AllotCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (14,'ChangePriceCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (16,'MoveMoneyCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (18,'RemoveCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (20,'GridCount','80','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (27,'SaleOrderCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (29,'CommissionCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (21,'Name','','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (22,'FullName','','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (23,'Tel','','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (24,'Address','','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (25,'TaxNO','','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (26,'BankNO','','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (28,'BuyOrderCode','0000000000','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (38,'FxOrNet','1','')
	-- ======================================= 注意版本信息
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (30,'Version','2.0-2010.11.26','版本信息')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (31,'AllowNegativeStock','0','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (32,'Edition','1','版本情况')  	--基础版(汽配默认只能是基础版)
	-- =================================== End 注意版本信息
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (33,'AssessType','0','')
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (34,'NeedAssessMoney','','') 
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (35,'CRMURL','http://127.0.0.1/crm','') 
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (36,'OperatorBaseRange','500','操作员基本信息最大数') 

	--高级价格体系中使用
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (733,'IsCombinePrice','0','')	--对符合要求的价格表合并取价	1合并取价
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (734,'IsUnifiedPriority','1','')	--取价规则排序管理模式 1=统一排优先级
	
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (800,'IfQP','0','')				--SysData表中的IfQP为1，代表为汽配版(没有这条记录，或该值不为1，则非汽配产品)		
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (801,'QPEdition','2','')	
	
	
	
	--1 - 美容快修 2 - 2s版 3 - 3s版 4 - 4s版	
	-- =================================== 840 开始预留20个占位置 ==========================================
	-- 840 -> ProInfo
	-- =================================== 840 开始预留20个占位置 ==========================================
END
GO
------------------------------------------------修改表-------------------------------------------------
IF EXISTS(SELECT * FROM sysobjects WHERE XTYPE = 'pk' AND parent_obj IN (SELECT [ID] FROM sysobjects WHERE name = 'Sysdata') AND name='PK_sysdata')
BEGIN
	BEGIN TRANSACTION
	SET QUOTED_IDENTIFIER ON
	SET ARITHABORT ON
	SET NUMERIC_ROUNDABORT OFF
	SET CONCAT_NULL_YIELDS_NULL ON
	SET ANSI_NULLS ON
	SET ANSI_PADDING ON
	SET ANSI_WARNINGS ON
	COMMIT
	BEGIN TRANSACTION

	ALTER TABLE dbo.sysdata
		DROP CONSTRAINT PK_sysdata

	ALTER TABLE dbo.sysdata SET (LOCK_ESCALATION = TABLE)

	COMMIT
END

GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Sysdata]') and  name = 'SubNo' and length=5)
BEGIN
	 ALTER TABLE Sysdata
	    ALTER COLUMN SubNo NUMERIC(10,0) NOT NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Sysdata]') and  name = 'SubValue' and Length=50)
BEGIN
	 ALTER TABLE Sysdata
	    ALTER COLUMN SubValue VARCHAR(500) NOT NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Sysdata]') and  name = 'SubValue' and Length=500)
BEGIN
	 ALTER TABLE Sysdata
	    ALTER COLUMN SubValue VARCHAR(5000) NOT NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Sysdata]') and  name = 'SubComment' and Length=30)
BEGIN
	 ALTER TABLE Sysdata
	    ALTER COLUMN SubComment VARCHAR(500) NULL
END
GO

IF NOT EXISTS(SELECT * FROM sysobjects WHERE XTYPE = 'pk' AND parent_obj IN (SELECT [ID] FROM sysobjects WHERE name = 'Sysdata'))
BEGIN
	ALTER TABLE dbo.sysdata
		ADD CONSTRAINT PK_sysdata Primary KEY (SubNo)
END	
GO	
--操作员多级权限范围基本信息最大数
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'OperatorBaseRange')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (36,'OperatorBaseRange','500','操作员基本信息最大数') 
END
GO
---------------------------------------------------修改表----------------------------------------------------------------
--升级包增加预制数据
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'IfQP')
BEGIN
	INSERT INTO Sysdata(SubNo,SubName,SubValue,SubComment)VALUES(800,'IfQP','1','')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'QPEdition')
BEGIN
	INSERT INTO Sysdata(SubNo,SubName,SubValue,SubComment)VALUES(801,'QPEdition','2','')
END
GO

--电账通版本升级 该条数据不再需要 modify by dongzhan 2013.4.9
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'eshop_productId')
BEGIN
		DELETE Sysdata WHERE SubName='eshop_productId'
END
GO
 ------------自定义字段配置
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubNo=9999)
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) VALUES(9999,'ifmovebilluserdefined',0,'')
END

 ---处理系统重建标志
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubNo=999)
BEGIN
	insert into sysdata values('999','sysbuild by','',null)
END
DELETE sysdata WHERE SubName='sysbuild by' AND SubNo<>999
GO

--启用会计科目的账套参数
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='IsInvocation')
BEGIN
	INSERT INTO sysdata values('700','IsInvocation','0',null)
END
GO

--财务会计期间
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='FPeriod')
BEGIN
	INSERT INTO sysdata values('701','FPeriod','1',null)
END
GO

--财务会计启用月度
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='fmonth')
BEGIN
	INSERT INTO sysdata values('702','fmonth','1',null)
END
GO

--是否启用总账系统
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='IsUseAcSystem')
BEGIN
	INSERT INTO sysdata values('703','IsUseAcSystem','0',null)
END
GO

--凭证过账前必须审核
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='acvhrchk')
BEGIN
	INSERT INTO sysdata values('704','acvhrchk','1',null)
END
GO

--结账时要求损益类科目余额为0
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='acbalanceiszero')
BEGIN
	INSERT INTO sysdata values('705','acbalanceiszero','1',null)
END
GO

--自动继承上一条分录摘要
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='acbfsummary')
BEGIN
	INSERT INTO sysdata values('706','acbfsummary','1',null)
END
GO

--记账本位币
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='bwbcode')
BEGIN
	INSERT INTO sysdata values('707','bwbcode','RMB',null)
END
GO

--记账本位币
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='bwbcodefullname')
BEGIN
	INSERT INTO sysdata values('708','bwbcodefullname','人民币',null)
END
GO

--0.业务单据即时过账，1.代表业务单据财务过账
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='PostingParameter')
BEGIN
	INSERT INTO sysdata values('709','PostingParameter','0',null)
END
GO

--自由项
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='isfreeitem')
BEGIN
	INSERT INTO sysdata values('710','isfreeitem','0',null)
END
GO

--外币核算
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='isforeigncurrency')
BEGIN
	INSERT INTO sysdata values('711','isforeigncurrency','0',null)
END
GO

--新软件狗版本标识
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='newEdition')
BEGIN
	INSERT INTO sysdata values('712','newEdition','10',null)
END
GO

--手机版预留标识
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='isusemobile')
BEGIN
	INSERT INTO sysdata values('713','isusemobile','0',null)
END
GO

--独立使用业务系统
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='aloneusebsys')
BEGIN
	INSERT INTO sysdata values('714','aloneusebsys','0',null)
END
GO 

--系统初始化 导航默认选中
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='setsysnavigation')
	INSERT INTO sysdata values('715','setsysnavigation','1',null)
GO

--系统初始化首页设置 默认选中
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='setsyshomepage')
	INSERT INTO sysdata values('716','setsyshomepage','0',null)
GO

--系统初始化 个人桌面
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='setsysdesktop')
	INSERT INTO sysdata values('717','setsysdesktop','0',null)
GO

--财务年度
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='fyear')
BEGIN
	INSERT INTO sysdata values('718','fyear','',null)
END
GO

--当前日期
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='curdate')
BEGIN
	INSERT INTO sysdata values('719','curdate','',null)
END
GO

--当前标识
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='curflag')
BEGIN
	INSERT INTO sysdata values('720','curflag','',null)
END
GO

--当前信息
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='curinfo')
BEGIN
	INSERT INTO sysdata values('721','curinfo','',null)
END
GO

--IP地址
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'wsd')
BEGIN
	INSERT INTO sysdata values('722','wsd','120.26.200.120','')
END
GO

--方法名称
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'wsf')
BEGIN
	INSERT INTO sysdata values('723','wsf','upCustomerData1','')
END
GO
--小版本
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'mVersion')
BEGIN
	INSERT INTO sysdata values('724','mVersion','','')
END
GO
--动态SQL
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'dsql')
BEGIN
	INSERT INTO sysdata values('725','dsql','','')
END
GO
--年中使用总账标识
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'museacflag')
BEGIN
	INSERT INTO sysdata values('726','museacflag','0','')
END
GO
--自动验证类型
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'validatetype')
BEGIN
	INSERT INTO sysdata values('727','validatetype','0','')
END
GO
--自动验证的内容
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'validateinfo')
BEGIN
	INSERT INTO sysdata values('728','validateinfo','','')
END
GO
--凭证日期生成方式,默认为1“按单据日期生成”
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'voucherdatetype')
BEGIN
	INSERT INTO sysdata values('729','voucherdatetype','1','')
END
GO
--敏捷预留
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'packno')
BEGIN
	INSERT INTO sysdata values('730','packno','','')
END
GO

--代理商定制接口
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'dlinfo')
BEGIN
	INSERT INTO sysdata values('731','dlinfo','','')
END
GO
--固定资产管理模式
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'assets')
BEGIN
	INSERT INTO sysdata values('732','assets','0','')
END
GO

--对符合要求的价格表合并取价
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'IsCombinePrice')
BEGIN
	INSERT INTO sysdata values('733','IsCombinePrice','0','')
END
GO

--取价规则排序管理模式
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'IsUnifiedPriority')
BEGIN
	INSERT INTO sysdata values('734','IsUnifiedPriority','1','')
END
GO

--能够选择多少张凭证进行生成或者过账
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'SelectedVoucherCount')
BEGIN
	INSERT INTO sysdata values('735','SelectedVoucherCount','100','')
END
GO

--独立分支间只允许存在买卖关系
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'innerstypesaleralation')
BEGIN
	INSERT INTO sysdata values('736','innerstypesaleralation','0','')
END
GO

IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'v31')
BEGIN
	INSERT INTO sysdata values('737','v31','568582410','')
END
GO

IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'v32')
BEGIN
	INSERT INTO sysdata values('738','v32','15861456','')
END
GO

IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'a81')
BEGIN
	INSERT INTO sysdata values('739','a81','566730325','')
END
GO

IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'a82')
BEGIN
	INSERT INTO sysdata values('740','a82','36383440','')
END
GO

IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'TbCount')
BEGIN
	INSERT INTO sysdata values('741','TbCount','0','')
END
GO


--ifuseentrycodeext
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'ifuseentrycodeext')
BEGIN
	INSERT INTO sysdata values('746','ifuseentrycodeext','0','')
END
GO



--Pos用户数
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'PosDefine')
BEGIN
	INSERT INTO sysdata values('750','PosDefine','0','')
END
GO

--搜索网址
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'defaultQueryWeb')
BEGIN
	INSERT INTO sysdata values('751','defaultQueryWeb','www.baidu.com','')
END
GO

--启用店账通
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'IsDzt')
BEGIN
	INSERT INTO sysdata values('752','IsDzt','0','')
END
GO

--启用云分销
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'IsCloud')
BEGIN
	INSERT INTO sysdata values('753','IsCloud','0','')
END
GO
--客户服务器是否有互联网
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'IsIntelnet')
BEGIN
	INSERT INTO sysdata values('754','IsIntelnet','0','')
END
GO
--互联网网络检测日期
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'IsIntelnetCheckDate')
BEGIN
	INSERT INTO sysdata values('755','IsIntelnetCheckDate',CONVERT(VARCHAR(10),GETDATE(),120),'')
END
GO

--互联网网络检测日期
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'IsIntelnetCheckDays')
BEGIN
	INSERT INTO sysdata values('756','IsIntelnetCheckDays','10','')
END
GO
UPDATE sysdata SET SubValue = '99999' WHERE SubName = 'IsIntelnetCheckDays'
GO

--分期字符串
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'SstagesValid')
BEGIN
	INSERT INTO sysdata values('757','SstagesValid','','')
END
GO

--出纳签字配置
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'actellersign')
BEGIN
	INSERT INTO sysdata values('758','actellersign','0','')
END
GO

--服务器互联网IP地址
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'internetaddr')
BEGIN
	INSERT INTO sysdata values('759','internetaddr','localhost','')
END
GO

--凭证 连续打印模板id
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'voucherreportindex')
BEGIN
	
	DECLARE @I VARCHAR(2)=''
	SELECT @I=ISNULL(SubValue,0) FROM sysdata WHERE SubName='newvouchershow'
	IF(@I=1)
		SET @I=1
	ELSE 
		SET @I=2
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values('760','voucherreportindex',@I,'')
END
GO
--预制数据
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'lbcount')
BEGIN
	INSERT INTO sysdata values('761','lbcount','5000','')
END
GO
--是否显示广告
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'isshowbanner')
BEGIN
	INSERT INTO sysdata values('762','isshowbanner','1','')
END
GO
--广告自动关闭时间(秒)
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'closebannertime')
BEGIN
	INSERT INTO sysdata values('763','closebannertime','90','')
END
GO
--销售订单自动弹出批次选择界面
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'allowpopbatch')
BEGIN
	INSERT INTO sysdata values('764','allowpopbatch','1','')
END
GO
--拷贝关闭广告的值
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'beforeisshowbanner')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)SELECT '765' AS SubNo,'beforeisshowbanner' AS SubName,SubValue,'' AS SubComment FROM dbo.sysdata WHERE SubNo = 762
END
GO
--找狗日志
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'ifdogLog')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('766' ,'ifdogLog','0','')
END
GO
--系统标识
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'fxsysflag')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('767' ,'fxsysflag','','')
END
GO
--扫描期间
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'rgday')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('768' ,'rgday','0','')
END
GO
--扫描日期
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'rgcheckdate')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('769' ,'rgcheckdate','','')
END
GO

--年结存财务结存方式记录
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'YearProcRecord')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('770' ,'YearProcRecord','','年结存记录')
END
ELSE
BEGIN
	UPDATE sysdata SET SubNo='770' WHERE SubName='YearProcRecord'
END
GO
--凭证记账前必须复核
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'actellerchk')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('771' ,'actellerchk',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='771' WHERE SubName='actellerchk'
END
GO
--凭证审核人与制单人可为同一人
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'acallowthesame')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('772' ,'acallowthesame',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='772' WHERE SubName='acallowthesame'
END
GO
--允许修改业务系统凭证
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'aceditsysvoucher')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('773' ,'aceditsysvoucher',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='773' WHERE SubName='aceditsysvoucher'
END
GO
--允许修改他人制单凭证
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'aceditothervoucher')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('774' ,'aceditothervoucher',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='774' WHERE SubName='aceditothervoucher'
END
GO
--每条凭证分录必须要有摘要
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'acsummary')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('775' ,'acsummary',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='775' WHERE SubName='acsummary'
END
GO
--录入凭证时指定现金流量项目
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'acpitdataflow')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('776' ,'acpitdataflow',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='776' WHERE SubName='acpitdataflow'
END
GO
--禁止成批审核凭证
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'acnobatchchk')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('777' ,'acnobatchchk',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='777' WHERE SubName='acnobatchchk'
END
GO
--不允许手工修改凭证号
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'acnomodno')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('778' ,'acnomodno',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='778' WHERE SubName='acnomodno'
END
GO
--新增凭证自动填补断号
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'acvhflowno')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('779' ,'acvhflowno',0,'')
END
ELSE 
BEGIN
	UPDATE sysdata SET SubNo='779' WHERE SubName='acvhflowno'
END
GO

--是否使用单据上原币金额
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'usebillmoneydate')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES ('780' ,'usebillmoneydate','','是否使用单据上原币金额')
END
ELSE
BEGIN
	UPDATE sysdata SET SubNo='780' WHERE SubName='usebillmoneydate'
END
GO

--损益类科目在科目方向的反向结转损益
--IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'carrylossonreversefdc')
--BEGIN
--	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment)VALUES (796 ,'carrylossonreversefdc',0,'在科目反方向结转损益')
--END
--ELSE
--BEGIN
--	UPDATE sysdata SET SubNo=796 WHERE SubName='carrylossonreversefdc'
--END
--GO
/*
移动一下位置，否则每次修改麻烦
*/
--补以前的占用
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'dbGuid')
BEGIN
	INSERT INTO sysdata values('998','dbGuid',NEWID(),'')
END
GO
------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[sysdata]') AND name = N'PK_sysdata')
ALTER TABLE [dbo].[sysdata] DROP CONSTRAINT [PK_sysdata]
GO

------------------------------------------删除索引区域结束-----------------------------------------------

GO
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'wsf' AND SubValue = 'upCustomerData')
BEGIN
	UPDATE sysdata SET SubValue = 'upCustomerData1' WHERE SubName = 'wsf'
END
go
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'wsf' AND SubValue = 'upCustomerData1')
BEGIN
	UPDATE sysdata SET SubValue = 'upCustomerData2' WHERE SubName = 'wsf'
END
GO
UPDATE dbo.sysdata SET SubName = 'internetaddr' WHERE SubNo = 759
GO


------------------1000~1300 POS、 OM占用开始------------------------------------
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'IsOM')
BEGIN
	INSERT [dbo].[sysdata] ([SubNo], [SubName], [SubValue], [SubComment]) VALUES (CAST(1000 AS Numeric(10, 0)), N'IsOM', N'0', N'')
END 
GO

IF EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'OMVersion')
BEGIN
	delete from sysdata WHERE SubName = 'OMVersion'
END 
GO

IF EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'OmDefine')
BEGIN
	delete from sysdata WHERE SubName = 'OmDefine'
END 
GO

IF EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'OMUsers')
BEGIN
	delete from sysdata WHERE SubName = 'OMUsers'
END 
GO

IF EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'BannerPath')
BEGIN
	delete from sysdata WHERE SubName = 'BannerPath'
END 
GO


INSERT [dbo].[sysdata] ([SubNo], [SubName], [SubValue], [SubComment]) VALUES (CAST(1001 AS Numeric(10, 0)), N'OMVersion', N'2.0', N'')
INSERT [dbo].[sysdata] ([SubNo], [SubName], [SubValue], [SubComment]) VALUES (CAST(1002 AS Numeric(10, 0)), N'OmDefine', N'10', N'')
INSERT [dbo].[sysdata] ([SubNo], [SubName], [SubValue], [SubComment]) VALUES (CAST(1003 AS Numeric(10, 0)), N'OMUsers', N'1', N'')
INSERT [dbo].[sysdata] ([SubNo], [SubName], [SubValue], [SubComment]) VALUES (CAST(1004 AS Numeric(10, 0)), N'BannerPath', N'F:\A8_OM\(2013-10-21)OM\OrderManager.Web\Images\Home\HomePage', NULL)
GO

--版本号
IF  EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'PosVersion')
BEGIN
	DELETE FROM dbo.sysdata WHERE SubName = 'PosVersion'
END
GO
--Guid
IF  EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'PosGuid')
BEGIN
	DELETE FROM dbo.sysdata WHERE SubName = 'PosGuid'
END
GO

--修订号
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'PosVersionSuffix')
BEGIN
	DELETE FROM dbo.sysdata WHERE SubName = 'PosVersionSuffix'
END
GO

--POSLiveUpdate
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'POSLiveUpdate')
BEGIN
	DELETE FROM dbo.sysdata WHERE SubName = 'POSLiveUpdate'
END
GO
INSERT INTO sysdata values('1005','PosVersion','1.0','')
INSERT INTO sysdata values('1006','PosGuid','e1899e3e-5cb3-4001-9478-84282a812d0b','')
INSERT INTO sysdata values('1007','PosVersionSuffix','0.8','')
INSERT INTO sysdata values('1008','PosLiveUpdate','1.8','')
/*
移动位置结束
*/

/********************************软件安全相关***********************************/
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'LinkDate')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (781,'LinkDate',GETDATE(),'') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'DogInfo')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (782,'DogInfo','','') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'LoginCheck')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (783,'LoginCheck',GETDATE(),GETDATE()) 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'PassVchCheck')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (784,'PassVchCheck',GETDATE(),GETDATE()) 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'ControlFlag')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (785,'ControlFlag','','') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'NetLevel')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (786,'NetLevel','103','') 
END
GO
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'LastUpdateTime')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (787,'LastUpdateTime',GETDATE(),GETDATE()) 
END
GO
--============================个人首页配置788-792[]===============================
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'frequencytype')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (789,'frequencytype',0,'') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'day_indexpagereftime')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (790,'day_indexpagereftime',24,'') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'time_indexpagereftime')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (791,'time_indexpagereftime',1,'') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'indexpagelastreftime')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (792,'indexpagelastreftime',GETDATE(),'') 
END
GO

-------------查询条件最大支持个数-------------------
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'SchemeCount')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (793,'SchemeCount',20,'') 
END
GO
--财务期初及凭证保存资金科目出现赤字
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'financeisred')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (794,'financeisred',0,'') 
END
GO
--财务期初及凭证保存资金科目出现赤字0:仅提示 1:不能保存
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'financeisredsavetype')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (795,'financeisredsavetype',0,'') 
END
GO
--启用实物库存
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'isphysicalsstock')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (796,'isphysicalsstock',0,'') 
END
GO
--启用组合品销售
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'combinationproduct')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (1009,'combinationproduct',0,'') 
END
GO
--启用上架
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'useonshelves')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (798,'useonshelves',0,'') 
END
GO
--启用拣货
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'usepickgoods')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (799,'usepickgoods',0,'') 
END
GO
--启用运输配送	 --802有客户数据被占用了
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'usetransport')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (804,'usetransport',0,'') 
END
GO
--启用存货类型核算
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'useatypefrom')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (803,'useatypefrom',0,'') 
END
GO
--启用分支机构独立开账
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'stypeindependentopen')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (805,'stypeindependentopen',0,'') 
END
GO
--版本信息备注
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'vercomment')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (806,'vercomment','','') 
END
GO
--错误级别控制
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'ERROR')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (807,'ERROR','1','') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'WARN')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (808,'WARN','0','') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'INFO')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (809,'INFO','0','') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'DEBUG')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (810,'DEBUG','0','') 
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'FATAL')
BEGIN
	INSERT INTO sysdata (SubNo,SubName,SubValue,SubComment) VALUES (811,'FATAL','1','') 
END
GO
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'posvernum')  --如果posvernum不存在，那么插入一条数据
BEGIN
	INSERT INTO sysdata values(812,'posvernum','1','') --
END
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'pospackcount')  --插入一条pos下载数据分包的条数
BEGIN
	INSERT INTO sysdata values(813,'pospackcount','50000','') --默认5w
END
GO

--全渠道配置地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wdshopurl')  
BEGIN
	INSERT INTO sysdata values(814,'wdshopurl','https://openapi.gjpqqd.com/Service/ERPService.asmx/ERPApi?','') 
END
ELSE
BEGIN 
	UPDATE dbo.sysdata SET SubValue = 'https://openapi.gjpqqd.com/Service/ERPService.asmx/ERPApi?' WHERE SubNo = '814'
END 
GO

IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'isShowFinancingServices')  --【管金所】菜单是否显示
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(815,'isShowFinancingServices','1','')
END
GO
--是否Beta版本标示
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'isBeta')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(816,'isBeta','0','')
END
GO
--启用品牌应收功能
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'usebrandartype')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(817,'usebrandartype','0','')
END
GO
----启用销售类型核算功能
--IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'usesaletype')
--BEGIN
--	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(818,'usesaletype','0','')
--END
--全渠道登陆配置地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wdloginshopurl')  
BEGIN
	INSERT INTO sysdata values(819,'wdloginshopurl','https://www.gjpqqd.com/ERPLogin.gspx?','')
END
--记忆开单商品选择时候的选项
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'recordmulptypeselector')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(820,'recordmulptypeselector','0','')
END
GO
--批量过账张数限制（含全渠道）
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'draftpassbillcount')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(821,'draftpassbillcount','100','')
END
GO
--表头自动控制高度的单据类型，默认订单、采购、销售、退货
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'controlautorankbilltype')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(822,'controlautorankbilltype','300,301,11,45,34','')
END
GO
--费用分摊调入单据明细
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'expenseloadbillcount')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(823,'expenseloadbillcount','150','')
END
GO
--支付宝支付方式
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'alipaysigntype')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(824,'alipaysigntype','1','')
END
GO
--管家婆云广告显示
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'isshowgjpyun')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(825,'isshowgjpyun','1','')
END
GO
--所有广告显示
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'isshowallgg')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(826,'isshowallgg','0','')
END
GO

--误差数值
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'differencetotal')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(827,'differencetotal','5','单位是%')
END
GO

--凭证应收选往来单位
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'auxiliarybtype')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(828,'auxiliarybtype','0','')
END
GO

--备份IM消息的周期
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'moveimmesagedays')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(829,'moveimmesagedays','1','')
END
GO

--快递鸟账号
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'kdbirdaccountno')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(830,'kdbirdaccountno','','')
END
GO
--快递鸟密匙
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'kdbirdaccountkey')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(831,'kdbirdaccountkey','','')
END
GO
--快递鸟地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'kdbirdaccounturl')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(832,'kdbirdaccounturl','http://api.kdniao.com/api/Eorderservice','')
END
GO
IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'kdbirdaccounturl')
BEGIN
	UPDATE dbo.sysdata SET SubValue = 'http://api.kdniao.com/api/Eorderservice' WHERE SubName = 'kdbirdaccounturl'
END
GO
--快递鸟密匙是否按操作员
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'kdbirdaccountforuser')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(833,'kdbirdaccountforuser','0','')
END
GO
--新增会员卡强制输入密码
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'newcardneedpassword')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(834,'newcardneedpassword','0','')
END
GO
--导入数据单据行控制
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'maxdetailcount')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(835,'maxdetailcount','500','')
END
GO
--987版本 章鱼侠云WMS及网店解决方案 启动云WMS及网店解决方案0
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'usewms')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(836,'usewms','0','')
END
GO

IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_CompanyName')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(837,'wms_CompanyName','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_UserName')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(838,'wms_UserName','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_Password')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(839,'wms_Password','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_appkey')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(840,'wms_appkey','58167722057100255608145170167805','85789290707490729074707632907470')
END
GO

--授权token
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_authtoken')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(841,'wms_authtoken','','')
END
GO

--刷新token
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_refreshtoken')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(842,'wms_refreshtoken','','')
END
GO

--授权token过期时间
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_expiresin')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(843,'wms_expiresin','','')
END
GO

--刷新token过期时间
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_reexpiresin')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(844,'wms_reexpiresin','','')
END
GO
--章鱼侠登陆配置地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'WMSLoginUrl')  
BEGIN
	INSERT INTO sysdata values(845,'wmsloginurl','http://ca.mygjp.com:8016/UserLogin.gspx?','')
END

--appsecret
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_appsecret')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(846,'wms_appsecret','wE707xrcikBmdivWCN8fKP1pG50253r6','xpfbiDn7i6lpIZkIETMU0JMDjY2c7HJH')
END
GO

--signkey
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_signkey')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(847,'wms_signkey','#1$3E5r5p0Z3y0x7W0m2s0>','123456789')
END
GO

--token过期日期
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_expiresdate')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(848,'wms_expiresdate','','')
END
GO
--一键清除WMS分销数据
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_rebuilt')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(849,'wms_rebuilt','0','')
END
GO
--章鱼侠获取authCode地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_loginurl')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(850,'wms_loginurl','http://zyxdztapigateway.zhangyuxia.com.cn/api/login','http://ca.mygjp.com:10002/api/login')
END
GO

--章鱼侠获取token地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_tokenurl')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(851,'wms_tokenurl','http://zyxdztapigateway.zhangyuxia.com.cn/api/token','http://ca.mygjp.com:10002/api/token')
END
GO

--章鱼侠api地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_apiurl')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(852,'wms_apiurl','http://zyxdztapigateway.zhangyuxia.com.cn/api/','http://ca.mygjp.com:10002/api/')
END
GO

--章鱼侠日志记录开关，日志用的subvalue，切换正式和测试地址用的subcomment,subcomment='test'为测试地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'wms_logswitch')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(853,'wms_logswitch','0','')
END
GO
--行业云短信账号
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'hyyunsms_usercode')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(854,'hyyunsms_usercode','','')
END
GO
--行业云短信密码 
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'hyyunsms_password')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(855,'hyyunsms_password','','')
END
GO
--行业云短信appKey
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'hyyunsms_appkey')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(856,'hyyunsms_appkey','','')
END
GO
--天通眼演示地址
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'ttydemourl')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(857,'ttydemourl','http://tty.ttgrasp.com.cn','')
END
GO
--普通发票税率
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'normaltax')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(858,'normaltax','3','')
END

--序列号扫描 销售出库单需要弹提示框不，默认弹出提示框 为1 则不弹提示框，文本框记录
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'salebillserialalert')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(859,'salebillserialalert','0','')
END

GO

--是否启用计算公式计算采购/销售数量
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'calcmqty')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(860,'calcmqty','0','')
END

GO

--显示 【更改价税合计/含税单价，反算税率】 配置
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'showbillcalculatetax')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(861,'showbillcalculatetax','0','')
END

GO

--打印记录日志
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'printlog')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(862,'printlog','0','')
END

GO

--短信电话取值
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'smssendmobile')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(863,'smssendmobile','0','')
END
ELSE IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'smssendmobile' AND SubNo = 863 )
BEGIN
	UPDATE dbo.sysdata SET SubNo = 863 WHERE SubName = 'smssendmobile'
END

GO
--记录单据日期变更后台开关
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'writebilldatechangelog')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(864,'writebilldatechangelog','0','')
END
GO

--企业财报是否升级
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'IsUpdateThreeFinancial')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(865,'IsUpdateThreeFinancial','0','')
END
GO

--打印记录日志
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'printlog')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(866,'printlog','0','')
END

GO
--启用品牌应收功能 按 品牌=0 结算单位=1 控制信用额度
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'brandarcontrollineofcredit')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(867,'brandarcontrollineofcredit','1','')
END
GO
--在线并发用户数日志控制开关
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'onlineusercontrol')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(868,'onlineusercontrol','0','')
END
GO

--发短信定时轮询账套开关
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'sendsmslogflag')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(869,'sendsmslogflag','0','')
END
GO

--管鑫所的广告开关
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'gxs')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(870,'gxs','0','')
END
GO

--商品图片大小限制
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'ptypepicmaxlength')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(871,'ptypepicmaxlength','500','')
END
GO

--POS在ERP的日志
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'writeposlog')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(872,'writeposlog','0','')
END
GO

--序列号开单选择的个数判定
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'bilselectserialcount')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(873,'bilselectserialcount','50','')
END
GO

--单据提交人和审核人为同一人时，自动审核通过【移动到UserConfig中了】
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'samepersonchecked')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(874,'samepersonchecked','0','')
END
GO
DELETE FROM dbo.sysdata WHERE SubName = 'samepersonchecked'
GO

--商品图片格式限制
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'ptypepictype')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(875,'ptypepictype','0','')
END
GO

--菜单日志标识日期
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'uploadmenueventlogdate')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(876,'uploadmenueventlogdate','','')
END
GO

--序列号最大长度
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'serialmaxcount')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(877,'serialmaxcount','50','')
END
GO

--是否启用自动保存单据
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'isuseautosavebill')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(878,'isuseautosavebill','0','')
END
GO

--自动保存单据的周期
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'autosavebilltime')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(879,'autosavebilltime','60','')
END
GO

--商品基本信息焦点
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'ptypefilterfocus')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(882,'ptypefilterfocus','usercode','')
END
GO

--今天的日期，用来判断系统不符合当天日期处理数据
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'todaydate')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(883,'todaydate','','')
END
GO
--每张单据限制的最大序列号个数
IF NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'billmaxserial')
BEGIN
	INSERT INTO sysdata(SubNo,SubName,SubValue,SubComment) values(916,'billmaxserial','5000','每张单据限制的最大序列号个数')
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------

------------------1000~1300 POS、 OM占用结束------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束----------------------------------------------- 


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SYSDATA') AND name = 'NCIX_SYSDATA_SubNo')
--DROP INDEX NCIX_SYSDATA_SubNo ON SYSDATA 
CREATE NONCLUSTERED INDEX NCIX_SYSDATA_SubNo ON SYSDATA(SubNo) 
------------------------------------------创建索引区域结束【如果特殊处理，请注意用700号段】-----------------------------------------------


GO



SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(SELECT 1 FROM [SysDataDB]..SysObjects WHERE ID=OBJECT_ID(N'[SysDataDB]..[UserDataBaseToSendSMS]',N'U'))
BEGIN
	CREATE TABLE [SysDataDB]..[UserDataBaseToSendSMS](
	    [id]                int identity(1,1) NOT NULL,
		[dataname]            [varchar](500)  NULL,
		[apikey]            [varchar](500)  NULL
		
	) ON [PRIMARY]

	-- ********	处理 UserDataBaseToSendSMS	********
	DELETE FROM [SysDataDB]..UserDataBaseToSendSMS
END
GO









------------------------网店基本信息表------------------------

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WMSBaseInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].WMSBaseInfo
		(
			[Id]			INT	IDENTITY(1,1),
			[Field]			VARCHAR(200),
			[Value]			VARCHAR(500)
		) ON [PRIMARY]
	 END
GO

--===========================预制数据==========================
IF NOT EXISTS(SELECT TOP 1 1 FROM WMSBaseInfo)
BEGIN
	--上传
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('BaseInfoRule','0')--基础资料上传规则 手工上传=0 即时上传=1
	
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('UploadRule','0')--单据上传规则 0=手工上传 1=保存时自动上传 2=过账后自动上传 3=每xx分钟自动上传一次
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('UploadBillRefreshTime','10')--单据上传规则  3=每xx分钟自动上传一次
	
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('UpStockRule','0')--库存数量上传 0=账面库存 1=虚拟库存
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('Refreshstock','0')--实时更新库存
	
	--下载
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('DownRule','0')--单据下载规则 0=手工上传 1=每xx分钟自动上传一次
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('DownBillRefreshTime','10')--单据下载规则 1=每xx分钟自动上传一次
	
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('summary','0')--网店单据摘要
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('message','0')--买家留言
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('comment','0')--买家备注
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('address','0')--收货人地址
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('link','0')--联系方式
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('name','0')--收货人姓名
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('account','0')--买家账号
	
	INSERT INTO WMSBaseInfo(Field,Value)VALUES('autodraftbill','1')--生成ERP单据规则 1=生成草稿单据 0=生成过账单据
	
END



/****** 对象:  Table [dbo].[AuditingFlowSet]    脚本日期: 05/05/2010 14:46:39 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AuditingFlowSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AuditingFlowSet](
		[AuditingID] [int] IDENTITY(1,1) NOT NULL,
		[BillType] [int] NOT NULL,
		[AuditingType] [int] NOT NULL,
		[AuditingLevel] [int] NOT NULL,
		[IfUse] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_AuditingFlowSet_IfUse]  DEFAULT (1),
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[AuditingReason] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[AuditingDate] [datetime] NOT NULL,
		[AuditingLevel1] [int] NOT NULL CONSTRAINT [DF_AuditingFlowSet_AuditingLevel1]  DEFAULT (1),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AuditingFlowSet' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE AuditingFlowSet ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE AuditingFlowSet SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

--最后停用
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AuditingFlowSet',N'U') AND Name='LastStopETypeID')
BEGIN
	ALTER TABLE AuditingFlowSet
	ADD LastStopETypeID VARCHAR(100) DEFAULT('')	
END
GO
	UPDATE AuditingFlowSet SET LastStopETypeID='' WHERE LastStopETypeID IS NULL
GO

--最后启用人
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AuditingFlowSet',N'U') AND Name='LastStartETypeID')
BEGIN
	ALTER TABLE AuditingFlowSet
	ADD LastStartETypeID VARCHAR(100) DEFAULT('')	
END

GO
	UPDATE AuditingFlowSet SET LastStartETypeID='' WHERE LastStartETypeID IS NULL
GO

--最后停用时间
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AuditingFlowSet',N'U') AND Name='LastStopTime')
BEGIN
	ALTER TABLE AuditingFlowSet
	ADD LastStopTime DATETIME
END

GO

--最后启用时间
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AuditingFlowSet',N'U') AND Name='LastStartTime')
BEGIN
	ALTER TABLE AuditingFlowSet
	ADD LastStartTime DATETIME
END

GO

--停用
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AuditingFlowSet',N'U') AND Name='Stoped')
BEGIN
	ALTER TABLE AuditingFlowSet
	ADD Stoped BIT DEFAULT(0)
END

GO
	UPDATE AuditingFlowSet SET Stoped=0 WHERE Stoped IS NULL
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/************************************************* 
对    象: Table [dbo].[CombinationOrderBill]   
描    述：组合品销售订单明细表
脚本日期: 2016-07-07 
创 建 人：罗淮文
*************************************************/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CombinationOrderBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CombinationOrderBill](
	[billNumberID] [numeric](18, 0) NOT NULL,
	[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CombinationOrderBill_ptypeid]  DEFAULT ('0'),
	[qty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_CombinationOrderBill_qty]  DEFAULT (0),
	[price] [numeric](24, 10) NULL CONSTRAINT [DF_CombinationOrderBill_price]  DEFAULT (0),
	[total] [numeric](24, 10) NULL CONSTRAINT [DF_CombinationOrderBill_total]  DEFAULT (0),
	[ReachQty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_CombinationOrderBill_ReachQty]  DEFAULT (0),
	[comment] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CombinationOrderBill_comment]  DEFAULT (''),
	[OrderID] [int] IDENTITY(1,1) NOT NULL,
	[Checked] [bit] NOT NULL CONSTRAINT [DF_CombinationOrderBill_Checked]  DEFAULT (0),
	[TeamNO1] [int] NULL,
	[PassQty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_CombinationOrderBill_PassQty]  DEFAULT (0),
	[IsUnit2] [bit] NOT NULL CONSTRAINT [DF_CombinationOrderBill_IsUnit2]  DEFAULT (0),
	[Discount] [numeric](24, 10) NULL CONSTRAINT [DF_CombinationOrderBill_Discount]  DEFAULT (1),
	[DiscountPrice] [numeric](24, 10) NULL CONSTRAINT [DF_CombinationOrderBill_DiscountPrice]  DEFAULT (0),
	[TaxPrice] [numeric](24, 10) NULL CONSTRAINT [DF_CombinationOrderBill_TaxPrice]  DEFAULT (0),
	[TaxTotal] [numeric](24, 10) NULL CONSTRAINT [DF_CombinationOrderBill_TaxTotal]  DEFAULT (0),
	[SaleTotal] [numeric](24, 10) NULL CONSTRAINT [DF_CombinationOrderBill_SaleTotal]  DEFAULT (0),
	[Tax] [numeric](24, 10) NULL CONSTRAINT [DF_CombinationOrderBill_Tax]  DEFAULT (0),
	[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
	[FromBillNumberID] [numeric](10, 0) NULL,
	[entrycode] [varchar](max) NULL,
	[FromBillID] [numeric](10, 0) NULL,
	[ReachTotal] [numeric](24, 10) NULL Default (0),
	[ReachTaxTotal] [numeric](24, 10) NULL Default (0),
	[RequestBillNumberID] [numeric](10, 0) NULL Default (0),
	[RequestBillID] [numeric](10, 0) NULL Default (0),
	[AskBillNumberID] [numeric](10, 0) NULL Default (0),
	[AskBillID] [numeric](10, 0) NULL Default (0),
	[TaxMoney] [numeric](24, 10) NULL Default(0),
	[NSalePrice] [numeric](24, 10) NULL Default(0),
	[NSaleTotal] [numeric](24, 10) NULL Default(0),
	[NDiscountPrice] [numeric](24, 10) NULL Default(0),
	[NTotal] [numeric](24, 10) NULL Default(0),
	[NTaxPrice] [numeric](24, 10) NULL Default(0),
	[NTaxTotal] [numeric](24, 10) NULL Default(0),
	[NTaxMoney] [numeric](24, 10) NULL Default(0),
	[UnitID] [int] NULL Default(0),
	[NUnitID] [int] NULL Default(0),
	[NQty] [numeric](24, 10) NULL Default(0),
	[UnitRate] [numeric](24, 10) NULL Default(0),
	[NUnitMsg] [varchar](50) NULL,
	[MUnitID] [int] NULL Default(0),
	[MQty] [numeric](24, 10) NULL Default(0),
	[MUnitRate] [numeric](24, 10) NULL Default(1),
	[MUnitMsg] [varchar](50) NULL,
	[MSalePrice] [numeric](24, 10) NULL Default(0),
	[MDiscountPrice] [numeric](24, 10) NULL Default(0),
	[MTaxPrice] [numeric](24, 10) NULL Default(0),
	[CurMSalePrice] [numeric](24, 10) NULL Default(0),
	[CurMDiscountPrice] [numeric](24, 10) NULL Default(0),
	[CurMTaxPrice] [numeric](24, 10) NULL Default(0),
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[GoodsCostPrice] [numeric](24, 10) NULL Default(0),
	[GoodsOrder] [int] NULL DEFAULT ('-1'),
	[ProduceDate] [varchar](50) NULL DEFAULT (''),
	[ValidDate] [varchar](50) NULL DEFAULT (''),
	[IsGift] [int] NOT NULL DEFAULT(0),
	[YapiID] [varchar](20) NULL DEFAULT(''),
	[PriceSource] [varchar](200) NOT NULL DEFAULT(''),
	[Id] [int] NOT NULL DEFAULT(0),
	[PromoType] [int] NOT NULL DEFAULT(0),
	[ShowOrder] [int] NULL DEFAULT(0),
	[WaitQty] [numeric](24, 10) NULL Default (0),
	[BillOver] [bit] NULL DEFAULT(0),
	[GoodsNumber] [varchar](100) NULL DEFAULT(''),
	[CargoID] [int] NULL,
	[stopreason] [varchar](max) NULL,
	[LockNumber] [numeric](24, 10) NULL DEFAULT(0),
	[pindexid]	VARCHAR(300) NULL DEFAULT('')
) ON [PRIMARY]
END



DECLARE @SQL VARCHAR(8000),@DB VARCHAR(50)

SET @DB= (SELECT db_name())

SET @SQL= 'ALTER DATABASE ['+@DB+'] SET COMPATIBILITY_LEVEL = 100'


EXEC(@SQL)

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[QP_QuickRepairBill_PType]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[IntegralExchangeBill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[IntegralExchangeBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[ID] INT IDENTITY(1,1) NOT NULL,
		[KTypeID] [varchar](50) NOT NULL,
		[PTypeID] [varchar](50) NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[Price] [numeric](22, 8) NOT NULL,
		[total] [numeric](18, 4) NOT NULL,
		[Comment] [varchar](250) NULL,
		[IsUnit2] INT NOT NULL,
		InputCostPrice	NUMERIC(22,8) NOT NULL DEFAULT(0),
		GoodsCostPrice	NUMERIC(22,8)	NOT NULL DEFAULT(0),
		GoodsCostTotal	NUMERIC(18,4)	NOT NULL DEFAULT(0),
		HandZeroCost	INT NOT NULL DEFAULT(0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[Serial] [text] DEFAULT (''),
		[GoodsNumber] [varchar](100) NULL  DEFAULT (''),
		[ProduceDate] [varchar](50) NULL  DEFAULT (''),
		[ValidDate] [varchar](50) NULL  DEFAULT (''),
		NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1),
		CargoID INT NULL DEFAULT(0),
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    ShowOrder INT DEFAULT(0)
	    ,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
	    ,PickedQty NUMERIC(24,10) NULL DEFAULT(0)  --拣货数量
	    ,OutFactQty NUMERIC(24,10) NULL DEFAULT(0)
	    ,[DraftFlag] [bit] NOT NULL DEFAULT(1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'integralexchangebill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.integralexchangebill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'integralexchangebill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.integralexchangebill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'integralexchangebill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.integralexchangebill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.integralexchangebill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'integralexchangebill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.IntegralExchangeBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.IntegralExchangeBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'integralexchangebill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE integralexchangebill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE integralexchangebill SET PickedQty=0 WHERE PickedQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE IntegralExchangeBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='Serial'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD Serial [text] DEFAULT ('')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD GoodsNumber [varchar](100) NULL  DEFAULT ('')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='ProduceDate'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD ProduceDate [varchar](50) NULL  DEFAULT ('')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='ValidDate'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD ValidDate [varchar](50) NULL  DEFAULT ('')
END

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='IntegralExchangeBill' AND a.Name='CargoID')
BEGIN
	ALTER TABLE IntegralExchangeBill ADD CargoID INT NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE IntegralExchangeBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0)
END
GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CargoSpace'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='IntegralExchangeBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INTEGRALEXCHANGEBILL') AND name = 'CIX_INTEGRALEXCHANGEBILL_BillNumberID')
--DROP INDEX CIX_INTEGRALEXCHANGEBILL_BillNumberID ON INTEGRALEXCHANGEBILL 
CREATE CLUSTERED INDEX CIX_INTEGRALEXCHANGEBILL_BillNumberID ON INTEGRALEXCHANGEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INTEGRALEXCHANGEBILL') AND name = 'NCIX_INTEGRALEXCHANGEBILL_Ktypeid')
--DROP INDEX NCIX_INTEGRALEXCHANGEBILL_Ktypeid ON INTEGRALEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_INTEGRALEXCHANGEBILL_Ktypeid ON INTEGRALEXCHANGEBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INTEGRALEXCHANGEBILL') AND name = 'NCIX_INTEGRALEXCHANGEBILL_Ptypeid')
--DROP INDEX NCIX_INTEGRALEXCHANGEBILL_Ptypeid ON INTEGRALEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_INTEGRALEXCHANGEBILL_Ptypeid ON INTEGRALEXCHANGEBILL(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE IntegralExchangeBill SET Serial = '' WHERE DATALENGTH(Serial) = 0
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IntegralExchangeBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IntegralExchangeBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IntegralExchangeBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IntegralExchangeBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IntegralExchangeBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IntegralExchangeBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IntegralExchangeBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IntegralExchangeBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IntegralExchangeBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[loginuser]    脚本日期: 05/05/2010 14:48:00 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[loginuser]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[loginuser](
		[etypeid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[sysid] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[MangerBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerBTypeID]  DEFAULT ('00001'),
		[MangerPTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerPTypeID]  DEFAULT ('00000'),
		[MangerBTypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerBTypeID2]  DEFAULT ('00002'),
		[MangerETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerETypeID]  DEFAULT ('00001'),
		[MangerKTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerKTypeID]  DEFAULT ('00000'),
		[LogNum] [int] NULL,
		[password] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[MangerATypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerATypeID]  DEFAULT ('0000'),
		[MangerExpense] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerExpense]  DEFAULT ('0000'),
		[MangerIncome] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerIncome]  DEFAULT ('0000'),
		[MangerCpaital] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerCpaital]  DEFAULT ('0000'),
		[MangerSTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerSTypeID]  DEFAULT ('00000'),
		[MangerOtherCpaital] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL   DEFAULT ('0000'),
		[MangerLiabilities] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL   DEFAULT ('0000'),
		[MangerRevenue] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT ('0000'),
		[MangerPay] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL   DEFAULT ('0000'),
		[IpAddr] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[IpMax] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[InfoFixUp] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_loginuser_InfoFixUp]  DEFAULT (''),
		[MangerDTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_loginuser_MangerDTypeID]  DEFAULT ('00000'),
		[LockNum] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[OpenLock] [bit] NULL CONSTRAINT [DF__Loginuser__OpenL__5390856F]  DEFAULT ((0)),
		[UserRank] [int] NULL CONSTRAINT [DF__Loginuser__UserR__5484A9A8]  DEFAULT ((0)),
		[LockRank] [int] NULL CONSTRAINT [DF__Loginuser__LockR__5578CDE1]  DEFAULT ((0)),
		[SmsSendID] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF__Loginuser__UseSm__30123F08]  DEFAULT (''),
		[UserDeRowCount] [int] NULL CONSTRAINT [DF__loginuser__UserD__332EA2D5]  DEFAULT ('14'),
		[ValidateLogin]	[int] NULL DEFAULT 0,
		[MacAddress] [VARCHAR] (100) DEFAULT '',
		[HardDiskNo] [VARCHAR] (100) DEFAULT '',
		[IsLoadPage] int DEFAULT 0,
		[isPosLogin] int DEFAULT 0,
		[LastLoginTime] DATETIME NULL,
		[lim] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_loginuser_lim]  DEFAULT (' ')
	) ON [PRIMARY]

	-- ********	处理 LoginUser	********
	DELETE FROM loginuser
	/*
	INSERT INTO loginuser ([ETypeID],[SysID],[Lim],[BTypeID],[MangerBTypeID],[MangerPTypeID],[MangerBTypeID2],[MangerETypeID],[MangerKTypeID],[LogNum],[password],[MangerATypeID],[MangerExpense],[MangerIncome],[MangerCpaital],[MangerDTypeID],[LockNum],[OpenLock],[UserRank],[LockRank],[SmsSendId])
	VALUES ('00001',1,'0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101
	01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101
	01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101
	010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101','00000','00001','00000','00002','00001','00000',1,'','0000','0000','0000','0000','00000','',0,1,0,0)
	*/
	INSERT INTO dbo.loginuser (etypeid, sysid, BTypeID, MangerBTypeID, MangerPTypeID, MangerBTypeID2, MangerETypeID, MangerKTypeID, LogNum, password, MangerATypeID, MangerExpense, MangerIncome, MangerCpaital, MangerSTypeID, MangerOtherCpaital, MangerLiabilities, MangerRevenue, MangerPay, IpAddr, IpMax, InfoFixUp, MangerDTypeID, LockNum, OpenLock, UserRank, LockRank, SmsSendID, UserDeRowCount, ValidateLogin, MacAddress, HardDiskNo, IsLoadPage, isPosLogin, LastLoginTime, lim)
	VALUES ('00001', '1', '00000', '00001', '00000', '00002', '00001', '00000', 23, '', '0000', '0000', '0000', '0000', '00000', '0000', '0000', '0000', '0000', NULL, NULL, '', '00000', '', 0, 1, 0, '0', 14, 0, '', '', 0, 0, NULL, ' ')

	INSERT INTO dbo.loginuser (etypeid, sysid, BTypeID, MangerBTypeID, MangerPTypeID, MangerBTypeID2, MangerETypeID, MangerKTypeID, LogNum, password, MangerATypeID, MangerExpense, MangerIncome, MangerCpaital, MangerSTypeID, MangerOtherCpaital, MangerLiabilities, MangerRevenue, MangerPay, IpAddr, IpMax, InfoFixUp, MangerDTypeID, LockNum, OpenLock, UserRank, LockRank, SmsSendID, UserDeRowCount, ValidateLogin, MacAddress, HardDiskNo, IsLoadPage, isPosLogin, LastLoginTime, lim)
	VALUES ('0000100001', '0', '00000', '00001', '00000', '00002', '00001', '00000', 0, NULL, '0000', '0000', '0000', '0000', '00000', '0000', '0000', '0000', '0000', NULL, NULL, '', '00000', NULL, 0, 0, 0, '', 14, 0, NULL, NULL, 0, 0, NULL, ' ')
	
	EXEC('UPDATE LoginUser SET MangerSTypeID=''00000''')
	
	--极简模式的输入录入
	TRUNCATE TABLE BillHeadControlField
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','184','priceResponseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','184','priceResponseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','184','priceResponseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','184','priceResponseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','184','priceResponseBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','184','priceResponseBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','305','retailBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','305','retailBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','305','retailBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','305','retailBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','305','retailBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','305','retailBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','215','retailBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','215','retailBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','215','retailBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','215','retailBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','215','retailBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','215','retailBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','交货时间','5','300','saleOrderBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','6','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','9','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','10','300','saleOrderBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','11','300','saleOrderBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','12','300','saleOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','18','300','saleOrderBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','11','saleOutStockBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','11','saleOutStockBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','13','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','14','11','saleOutStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','45','saleBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','45','saleBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','45','saleBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','45','saleBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','45','saleBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','45','saleBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','45','saleBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','45','saleBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','45','saleBackBillHead','0')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','160','saleGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','160','saleGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','160','saleGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','160','saleGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','160','saleGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','160','saleGoodsExchangeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','160','saleGoodsExchangeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','160','saleGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','160','saleGoodsExchangeBillHead','0')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','139','giveBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','139','giveBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','139','giveBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','139','giveBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','139','giveBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','139','giveBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','139','giveBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','140','wtSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','140','wtSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','140','wtSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','140','wtSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','140','wtSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','140','wtSendBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','140','wtSendBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','142','wtBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','142','wtBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','142','wtBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','142','wtBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','142','wtBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','142','wtBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','142','wtBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','143','wtChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','143','wtChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','143','wtChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','143','wtChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','143','wtChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','143','wtChangePriceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','143','wtChangePriceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','141','wtGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','141','wtGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','141','wtGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','141','wtGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','141','wtGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','141','wtGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','141','wtGatherBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','141','wtGatherBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','5','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','6','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','7','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','8','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','9','313','combinationSaleOrderHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','10','313','combinationSaleOrderHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','11','313','combinationSaleOrderHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','12','313','combinationSaleOrderHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','交货时间','13','313','combinationSaleOrderHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','12','combinationSaleHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','12','combinationSaleHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','14','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','15','12','combinationSaleHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','16','12','combinationSaleHead','0')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','46','combinationSaleBackHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','46','combinationSaleBackHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','46','combinationSaleBackHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','46','combinationSaleBackHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','46','combinationSaleBackHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','46','combinationSaleBackHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','46','combinationSaleBackHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','46','combinationSaleBackHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('StockInDeadline','入库期限','9','46','combinationSaleBackHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','46','combinationSaleBackHead','0')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','402','sendPtypeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','402','sendPtypeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','13','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','14','402','sendPtypeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','403','sendBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','403','sendBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','403','sendBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','403','sendBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','403','sendBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','403','sendBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','7','403','sendBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','204','buyRequestBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','204','buyRequestBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','204','buyRequestBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','204','buyRequestBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','204','buyRequestBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','185','priceQueryBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','185','priceQueryBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','185','priceQueryBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','185','priceQueryBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','185','priceQueryBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','185','priceQueryBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','301','buyOrderBillHead','0')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','到货时间','3','301','buyOrderBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','4','301','buyOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','4','301','buyOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','5','301','buyOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','301','buyOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','7','301','buyOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','8','301','buyOrderBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','9','301','buyOrderBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','10','301','buyOrderBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','11','301','buyOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','12','301','buyOrderBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','34','buyInStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','34','buyInStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','34','buyInStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','34','buyInStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','34','buyInStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','34','buyInStockBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','34','buyInStockBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','34','buyInStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','34','buyInStockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','34','buyInStockBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','6','buyBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','6','buyBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','6','buyBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','6','buyBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','6','buyBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','6','buyBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','6','buyBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','6','buyBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','9','6','buyBackBillHead','0')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','11','6','buyBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','161','buyGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','161','buyGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','161','buyGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','161','buyGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','161','buyGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','161','buyGoodsExchangeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','161','buyGoodsExchangeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','161','buyGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','161','buyGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','161','buyGoodsExchangeBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','12','161','buyGoodsExchangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','126','giveMeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','126','giveMeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','126','giveMeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','126','giveMeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','126','giveMeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','126','giveMeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','126','giveMeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','144','stSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','144','stSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','144','stSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','144','stSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','144','stSendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','144','stSendBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','144','stSendBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','146','stBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','146','stBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','146','stBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','146','stBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','146','stBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','146','stBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','146','stBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','147','stChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','147','stChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','147','stChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','147','stChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','147','stChangePriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','147','stChangePriceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','147','stChangePriceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','145','stGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','145','stGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','145','stGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','145','stGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','145','stGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','145','stGatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','145','stGatherBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','145','stGatherBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','400','appraisalInstockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','400','appraisalInstockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','400','appraisalInstockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','400','appraisalInstockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','400','appraisalInstockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','400','appraisalInstockBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','400','appraisalInstockBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','400','appraisalInstockBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','400','appraisalInstockBillHead','0')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','401','appraisalBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','401','appraisalBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','401','appraisalBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','401','appraisalBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','401','appraisalBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','401','appraisalBackBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','17','allotBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','17','allotBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','17','allotBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','17','allotBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','17','allotBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','17','allotBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','21','allotPriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','21','allotPriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','21','allotPriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','21','allotPriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','21','allotPriceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','21','allotPriceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','187','innerStockTranBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','187','innerStockTranBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','187','innerStockTranBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','187','innerStockTranBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','187','innerStockTranBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','187','innerStockTranBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','188','innerInStockTranBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','188','innerInStockTranBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','188','innerInStockTranBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','188','innerInStockTranBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','188','innerInStockTranBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','188','innerInStockTranBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','201','otherInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','201','otherInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','201','otherInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','201','otherInBillHead','0')
	--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('OtherOperationSort','业务类别','5','201','otherInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','201','otherInBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','201','otherInBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','201','otherInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','202','otherOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','202','otherOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','202','otherOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','202','otherOutBillHead','0')
	--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('OtherOperationSort','业务类别','5','202','otherOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','202','otherOutBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','202','otherOutBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','202','otherOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','1','306','doStockCheckBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','2','306','doStockCheckBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('StockQtyEndDate','账面数截止时间','3','306','doStockCheckBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','9','loseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','9','loseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','9','loseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','9','loseBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','9','loseBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','9','loseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','14','overFlowBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','14','overFlowBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','14','overFlowBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','14','overFlowBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','14','overFlowBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','14','overFlowBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','87','lendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','87','lendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','87','lendBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','87','lendBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','87','lendBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','71','borrowBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','71','borrowBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','71','borrowBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','71','borrowBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','71','borrowBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','88','lendBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','88','lendBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','88','lendBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','88','lendBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','88','lendBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','72','BorrowBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','72','BorrowBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','72','BorrowBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','72','BorrowBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','72','BorrowBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','16','disassembleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','16','disassembleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','16','disassembleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','16','disassembleBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','16','disassembleBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','6','16','disassembleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','7','16','disassembleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','203','serialEdiBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','203','serialEdiBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','203','serialEdiBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','203','serialEdiBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','203','serialEdiBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','申请部门','1','22','posAllotApplyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','22','posAllotApplyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','22','posAllotApplyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','22','posAllotApplyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','412','stockUpShelvesBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','412','stockUpShelvesBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','413','stockPickBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','413','stockPickBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','414','stockTransportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('freightperson','司机','2','414','stockTransportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('freighttel','联系电话','3','414','stockTransportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shipperfullname','托运方','4','414','stockTransportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shipperperson','托运联系人','5','414','stockTransportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shippertel','托运联系电话','6','414','stockTransportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('totalfreight','合计运费','7','414','stockTransportBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('tax','税率','8','414','stockTransportBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atype','付款账户','9','414','stockTransportBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('TotalInmoney','付款金额','10','414','stockTransportBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('transportno','承运商运单号','11','414','stockTransportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','12','414','stockTransportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','13','414','stockTransportBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','418','stockImportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','418','stockImportBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','418','stockImportBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','418','stockImportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','419','stockExmportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','419','stockExmportBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','419','stockExmportBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','419','stockExmportBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','420','stockAllotBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','420','stockAllotBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','420','stockAllotBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','420','stockAllotBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','165','RepairReceiveBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','165','RepairReceiveBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','165','RepairReceiveBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','165','RepairReceiveBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','165','RepairReceiveBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','165','RepairReceiveBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','165','RepairReceiveBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','166','RepairSelfBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','166','RepairSelfBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','166','RepairSelfBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','166','RepairSelfBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','5','166','RepairSelfBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','6','166','RepairSelfBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','167','RepairGetBackBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','167','RepairGetBackBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','167','RepairGetBackBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','167','RepairGetBackBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','167','RepairGetBackBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','167','RepairGetBackBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','167','RepairGetBackBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','168','RepairChangeBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','168','RepairChangeBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','168','RepairChangeBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','168','RepairChangeBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','168','RepairChangeBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','168','RepairChangeBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','168','RepairChangeBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','169','RepairSendBil','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','169','RepairSendBil','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','169','RepairSendBil','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','169','RepairSendBil','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','169','RepairSendBil','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','170','RepairSendBackBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','170','RepairSendBackBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','170','RepairSendBackBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','170','RepairSendBackBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','171','RepairCallBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','171','RepairCallBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','171','RepairCallBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','171','RepairCallBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','171','RepairCallBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','171','RepairCallBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','171','RepairCallBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','172','RepairGoToBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','172','RepairGoToBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','172','RepairGoToBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','172','RepairGoToBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','172','RepairGoToBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','172','RepairGoToBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','172','RepairGoToBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','172','RepairGoToBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','172','RepairGoToBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','173','RepairAllotInBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','173','RepairAllotInBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','173','RepairAllotInBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','173','RepairAllotInBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','173','RepairAllotInBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','174','RepairAllotOutBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','174','RepairAllotOutBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','174','RepairAllotOutBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','174','RepairAllotOutBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','174','RepairAllotOutBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','175','RepairAllotBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','175','RepairAllotBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','175','RepairAllotBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','175','RepairAllotBill','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','175','RepairAllotBill','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','116','gatheraddBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','116','gatheraddBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','116','gatheraddBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','116','gatheraddBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','116','gatheraddBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','115','gatherReduceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','115','gatherReduceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','115','gatherReduceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','115','gatherReduceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','115','gatherReduceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','128','payAddBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','128','payAddBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','128','payAddBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','128','payAddBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','128','payAddBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','129','payReduceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','129','payReduceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','129','payReduceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','129','payReduceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','129','payReduceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','4','gatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','4','gatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','4','gatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','4','gatherBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','4','gatherBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','4','gatherBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','189','preSettleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','189','preSettleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','189','preSettleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','189','preSettleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','189','preSettleBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','189','preSettleBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','66','payBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','66','payBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','66','payBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','66','payBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','66','payBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','66','payBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','190','preSettlePayBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','190','preSettlePayBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','190','preSettlePayBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','190','preSettlePayBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','190','preSettlePayBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','190','preSettlePayBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','148','advantageBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','148','advantageBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','148','advantageBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','148','advantageBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','148','advantageBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','148','advantageBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','148','advantageBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','150','advantageGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','150','advantageGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','150','advantageGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','150','advantageGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','150','advantageGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','150','advantageGetBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','150','advantageGetBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','149','priceProtectBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','149','priceProtectBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','149','priceProtectBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','149','priceProtectBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','149','priceProtectBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','149','priceProtectBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','149','priceProtectBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','151','priceProtectGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','151','priceProtectGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','151','priceProtectGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','151','priceProtectGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','151','priceProtectGetBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','151','priceProtectGetBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','151','priceProtectGetBillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','450','wLCancelAfterVerificationBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','450','wLCancelAfterVerificationBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','450','wLCancelAfterVerificationBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Alertday','收付款期限','4','450','wLCancelAfterVerificationBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','450','wLCancelAfterVerificationBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('TotalMoney','本单核销金额','6','450','wLCancelAfterVerificationBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','162','saleInvoiceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','162','saleInvoiceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','162','saleInvoiceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','162','saleInvoiceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','162','saleInvoiceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','162','saleInvoiceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','162','saleInvoiceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','163','buyInvoiceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','163','buyInvoiceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','163','buyInvoiceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','163','buyInvoiceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','163','buyInvoiceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','163','buyInvoiceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','163','buyInvoiceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','404','receiptForBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','404','receiptForBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','404','receiptForBuyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','404','receiptForBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','404','receiptForBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','404','receiptForBuyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','404','receiptForBuyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','10','404','receiptForBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','405','receiptForSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','405','receiptForSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','405','receiptForSaleBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','405','receiptForSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','405','receiptForSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','405','receiptForSaleBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','405','receiptForSaleBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','9','405','receiptForSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','36','expenseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','36','expenseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','36','expenseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','36','expenseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收付款期限','5','36','expenseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','36','expenseBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','36','expenseBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','158','cachExpenseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','158','cachExpenseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','158','cachExpenseBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','158','cachExpenseBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','158','cachExpenseBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','77','moneyChangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','77','moneyChangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','77','moneyChangeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','77','moneyChangeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','77','moneyChangeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','93','inComeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','93','inComeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','93','inComeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','93','inComeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','93','inComeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','93','inComeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','93','inComeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','5','ExpenseHappenBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','5','ExpenseHappenBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','5','ExpenseHappenBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','5','ExpenseHappenBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','5','ExpenseHappenBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','10','expenseAllocateBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','10','expenseAllocateBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','10','expenseAllocateBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','10','expenseAllocateBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','10','expenseAllocateBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','84','fixedBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','84','fixedBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','84','fixedBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','84','fixedBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','84','fixedBuyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','84','fixedBuyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','84','fixedBuyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','85','fixedSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','85','fixedSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','85','fixedSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','85','fixedSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','85','fixedSaleBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','85','fixedSaleBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','85','fixedSaleBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','78','depBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','78','depBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','78','depBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','78','depBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','78','depBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','57','adpriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','57','adpriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','57','adpriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','4','57','adpriceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','57','adpriceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','57','adpriceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','159','accountCredenceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','159','accountCredenceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','159','accountCredenceBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','159','accountCredenceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','159','accountCredenceBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','205','buyExpenseAmortizeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','205','buyExpenseAmortizeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','205','buyExpenseAmortizeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','205','buyExpenseAmortizeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','205','buyExpenseAmortizeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','206','saleExpenseAmortizeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','206','saleExpenseAmortizeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','206','saleExpenseAmortizeBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','206','saleExpenseAmortizeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','206','saleExpenseAmortizeBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','312','vipPlAddMoneyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','312','vipPlAddMoneyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','312','vipPlAddMoneyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','312','vipPlAddMoneyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','312','vipPlAddMoneyBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','312','vipPlAddMoneyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','312','vipPlAddMoneyBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','423','CouponInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','423','CouponInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','423','CouponInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','423','CouponInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','423','CouponInBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','424','CouponOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','424','CouponOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','424','CouponOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','424','CouponOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','424','CouponOutBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','425','CouponAllotBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','425','CouponAllotBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','426','CouponBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','426','CouponBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','426','CouponBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','426','CouponBackBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','426','CouponBackBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','183','qp_CentChange_BillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','183','qp_CentChange_BillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','183','qp_CentChange_BillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','183','qp_CentChange_BillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','183','qp_CentChange_BillHead','1')	
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','428','CouponStypeInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','428','CouponStypeInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','428','CouponStypeInBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','428','CouponStypeInBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','428','CouponStypeInBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','429','CouponStypeOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','429','CouponStypeOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','429','CouponStypeOutBillHead','0')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','429','CouponStypeOutBillHead','1')
	INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','429','CouponStypeOutBillHead','1')
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MangerSTypeID'
)
BEGIN
	ALTER TABLE loginuser ADD MangerSTypeID VARCHAR(50) DEFAULT '00000' NULL	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MangerBankID'
)
BEGIN
	ALTER TABLE loginuser ADD MangerBankID VARCHAR(50) DEFAULT '00000' NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='ValidateLogin'
)
BEGIN
	ALTER TABLE loginuser ADD ValidateLogin	int DEFAULT 0 NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MacAddress'
)
BEGIN
	ALTER TABLE loginuser ADD MacAddress VARCHAR(100) DEFAULT '' NULL
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='HardDiskNo'
)
BEGIN
	ALTER TABLE loginuser ADD HardDiskNo VARCHAR(100) DEFAULT '' NULL
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='IsLoadPage'
)
BEGIN
	ALTER TABLE loginuser ADD IsLoadPage INT DEFAULT 0 NULL	
END

GO

--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('loginuser') and name='WdSyncFlag')
BEGIN
	ALTER TABLE loginuser ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End
GO

/*
   作者：张陈仁
   日期：2011-7-29
   描述：增加用户打印次数控制和解锁密码字段
*/
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='userPrintCount'
)
BEGIN
	ALTER TABLE loginuser ADD userPrintCount INT DEFAULT 0 NULL	
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='userPrintPassword'
)
BEGIN
	ALTER TABLE loginuser ADD userPrintPassword varchar(50) DEFAULT '' NULL	
END
--IM是否自动弹出消息窗口
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='AutoWindow'
)
BEGIN
	ALTER TABLE loginuser ADD AutoWindow INT DEFAULT 1 NULL	
END
--IM是否自动播放消息声音
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='playmsg'
)
BEGIN
	ALTER TABLE loginuser ADD playmsg INT DEFAULT 1 NULL	
END
--用户登录时间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='loginTime'
)
BEGIN
	ALTER TABLE loginuser ADD loginTime dateTime DEFAULT NULL	
END
--用户离线时间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='logoutTime'
)
BEGIN
	ALTER TABLE loginuser ADD logoutTime dateTime DEFAULT NULL	
END

GO

/*
	作者：陈守川
	日期：2012-02-03
	描述：增加当前操作员所在用户组字段
*/
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='belongToGroup'
)
BEGIN
	ALTER TABLE loginuser ADD belongToGroup INT DEFAULT 0 NULL	
END
GO

IF NOT EXISTS(SELECT * FROM syscolumns where id = object_id(N'[dbo].[LoginUser]') and  name = 'Lim' AND length = 8000)
	BEGIN
		 ALTER TABLE LoginUser
			ALTER COLUMN Lim varchar(8000) 
	END
GO

--是否ERP操作员
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='isErp'
)
BEGIN
	ALTER TABLE loginuser ADD isErp INT DEFAULT 1 NULL	
END
GO

--是否手机版操作员
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='isMobile'
)
BEGIN
	ALTER TABLE loginuser ADD isMobile INT DEFAULT 0 NULL	
END
GO

--是否POS版操作员
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='isPos'
)
BEGIN
	ALTER TABLE loginuser ADD isPos INT DEFAULT 0 NULL	
END
GO

--修改admin为pos操作员
UPDATE loginuser SET isPos=1 WHERE etypeid='00001'

--是否登陆Pos
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='isPosLogin'
)
BEGIN
	ALTER TABLE loginuser ADD isPosLogin INT DEFAULT 0 NULL	
END
GO

--是否登陆Pos
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='LastLoginTime'
)
BEGIN
	ALTER TABLE loginuser ADD LastLoginTime datetime NULL	
END
GO

--是否登陆Pos
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='IsDownLoad'
)
BEGIN
	ALTER TABLE loginuser ADD IsDownLoad bit null DEFAULT(0)	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MangerOtherCpaital'
)
BEGIN
	ALTER TABLE loginuser ADD MangerOtherCpaital VARCHAR(50) DEFAULT '0000' NOT NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MangerLiabilities'
)
BEGIN
	ALTER TABLE loginuser ADD MangerLiabilities VARCHAR(50) DEFAULT '0000' NOT NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MangerRevenue'
)
BEGIN
	ALTER TABLE loginuser ADD MangerRevenue VARCHAR(50) DEFAULT '0000' NOT NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MangerPay'
)
BEGIN
	ALTER TABLE loginuser ADD MangerPay VARCHAR(50) DEFAULT '0000' NOT NULL 
END
GO


--添加所有者权益字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MangerOwnerEquity'
)
BEGIN
	ALTER TABLE loginuser ADD MangerOwnerEquity VARCHAR(50) DEFAULT '0000' NOT NULL 
END
GO

--添加锁屏时间字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='LockScreenTime'
)
BEGIN
	ALTER TABLE loginuser ADD LockScreenTime INT DEFAULT 0 NOT NULL 
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[loginuser]') AND name = N'PK_loginuser')
ALTER TABLE [dbo].[loginuser] DROP CONSTRAINT [PK_loginuser]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LOGINUSER') AND name = 'CIX_LOGINUSER_etypeid')
--DROP INDEX CIX_LOGINUSER_etypeid ON LOGINUSER 
CREATE CLUSTERED INDEX CIX_LOGINUSER_etypeid ON LOGINUSER(etypeid) 
GO
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE LoginUser SET MangerSTypeID = '00000' WHERE MangerSTypeID IS NULL
GO
UPDATE loginuser SET MangerBankID = '00000' WHERE MangerBankID IS NULL
GO
UPDATE LoginUser SET ValidateLogin = 0 WHERE ValidateLogin IS NULL
GO
UPDATE LoginUser SET MacAddress = '' WHERE MacAddress IS NULL
GO
UPDATE LoginUser SET HardDiskNo = '' WHERE HardDiskNo IS NULL
GO
UPDATE LoginUser SET IsLoadPage = 0 WHERE IsLoadPage IS NULL
GO
UPDATE LoginUser SET userPrintCount = 0 WHERE userPrintCount IS NULL
GO
UPDATE LoginUser SET AutoWindow = 1 WHERE AutoWindow IS NULL
GO
UPDATE LoginUser SET playmsg = 1 WHERE playmsg IS NULL
GO
UPDATE LoginUser SET userPrintPassword = '' WHERE userPrintPassword IS NULL
GO
UPDATE LoginUser SET IsErp = 1 WHERE IsErp IS NULL
GO
UPDATE LoginUser SET IsPos = 0 WHERE IsPos IS NULL
GO
UPDATE LoginUser SET IsMobile = 0 WHERE IsMobile IS NULL
GO
UPDATE LoginUser SET belongToGroup = 0 WHERE belongToGroup IS NULL
GO
UPDATE LoginUser SET isPosLogin = 0 WHERE isPosLogin IS NULL
GO
UPDATE LoginUser SET IsDownLoad=0 WHERE IsDownLoad IS NULL
GO
UPDATE LoginUser SET lim+=REPLICATE('0',8000-LEN(lim)) WHERE LEN(lim)<8000
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='MacAddress'
)
BEGIN
 DECLARE @name VARCHAR(50)
 SELECT @name = b.name
 FROM   sysobjects b
        JOIN syscolumns a ON b.id = a.cdefault
 WHERE  a.id = OBJECT_ID('loginuser')
        AND a.name = 'MacAddress'
 IF @name != '' 
    EXEC('alter table loginuser drop constraint ' + @name)
 ALTER TABLE loginuser ALTER COLUMN MacAddress VARCHAR(MAX)
END

GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='HardDiskNo'
)
BEGIN
 DECLARE @name VARCHAR(50)
 SELECT @name = b.name
 FROM   sysobjects b
        JOIN syscolumns a ON b.id = a.cdefault
 WHERE  a.id = OBJECT_ID('loginuser')
        AND a.name = 'HardDiskNo'
 IF @name != '' 
    EXEC('alter table loginuser drop constraint ' + @name)
 ALTER TABLE loginuser ALTER COLUMN HardDiskNo VARCHAR(MAX)
END
GO


IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='loginuser' AND a.Name='password'
)
BEGIN
 DECLARE @name VARCHAR(100)
 SELECT @name = b.name
 FROM   sysobjects b
        JOIN syscolumns a ON b.id = a.cdefault
 WHERE  a.id = OBJECT_ID('loginuser')
        AND a.name = 'password'
 IF @name != '' 
    EXEC('alter table loginuser drop constraint ' + @name)
 ALTER TABLE loginuser ALTER COLUMN password VARCHAR(32)     
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------




/****** 对象:  Table [dbo].[OrderBill]    脚本日期: 05/05/2010 14:48:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OrderBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OrderBill](
		[billNumberID] [numeric](18, 0) NOT NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderBill_ptypeid]  DEFAULT ('0'),
		[qty] [numeric](18, 4) NOT NULL CONSTRAINT [DF_OrderBill_qty]  DEFAULT (0),
		[price] [numeric](18, 4) NULL CONSTRAINT [DF_OrderBill_price]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_OrderBill_total]  DEFAULT (0),
		[ReachQty] [numeric](18, 4) NOT NULL CONSTRAINT [DF_OrderBill_ReachQty]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderBill_comment]  DEFAULT (''),
		[OrderID] [int] IDENTITY(1,1) NOT NULL,
		[Checked] [bit] NOT NULL CONSTRAINT [DF_OrderBill_Checked]  DEFAULT (0),
		[TeamNO1] [int] NULL,
		[PassQty] [numeric](18, 4) NOT NULL CONSTRAINT [DF_OrderBill_PassQty]  DEFAULT (0),
		[IsUnit2] [bit] NOT NULL CONSTRAINT [DF_OrderBill_IsUnit2]  DEFAULT (0),
		[Discount] [numeric](18, 4) NULL CONSTRAINT [DF_OrderBill_Discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_OrderBill_DiscountPrice]  DEFAULT (0),
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_OrderBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_OrderBill_TaxTotal]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_orderbill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_orderbill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[entrycode]           varchar(max)        null,
		[FromBillID] [numeric](10, 0)  NULL,
		[ReachTotal] [numeric](18, 4) NULL Default (0),
		[ReachTaxTotal] [numeric](18, 4) NULL Default (0),
		[RequestBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[RequestBillID] [numeric](10, 0)  NULL DEFAULT (0),
		[AskBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[AskBillID] [numeric](10, 0)  NULL DEFAULT (0),
		TaxMoney             numeric(22,10)		NULL Default(0),
		NSalePrice           numeric(22,10)		NULL Default(0),
		NSaleTotal           numeric(22,10)		NULL Default(0),
		NDiscountPrice       numeric(22,10)		NULL Default(0),
		NTotal               numeric(22,10)		NULL Default(0),
		NTaxPrice            numeric(22,10)		NULL Default(0),
		NTaxTotal            numeric(22,10)		NULL Default(0),
		NTaxMoney            numeric(22,10)		NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        NULL,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        NULL,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		[GoodsCostPrice] [numeric](18, 4) NULL  DEFAULT (0),
		[GoodsOrder] [int] NULL  DEFAULT ('-1'),
		[ProduceDate] [varchar](50) NULL  DEFAULT (''),
		[ValidDate] [varchar](50) NULL DEFAULT (''),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		YapiID VARCHAR(20) NULL DEFAULT(''),
		PriceSource varchar(200) NOT NULL DEFAULT('') --价格信息
		,Id INT NOT NULL DEFAULT(0) --同一订单内排序字段 order by id,orderid 这样处理
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,ShowOrder INT DEFAULT(0)
		,LockNumber Numeric(24,10)NULL DEFAULT(0)--锁定基本数量
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[OrderBill]') and name = 'KTypeID' )
BEGIN
	
	ALTER TABLE dbo.OrderBill ADD
		KTypeID varchar(50) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[OrderBill]') and name = 'WaitQty' )
BEGIN
	ALTER TABLE dbo.OrderBill ADD WaitQty [numeric](18, 4) NULL Default (0)
END
GO

--V35明细未填SaleTotal,Tax,且Total填的是普通金额
UPDATE OrderBill
SET SaleTotal=Total,Total=DiscountPrice*Qty
WHERE SaleTotal=0 OR SaleTotal IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE OrderBill ADD STypeID VARCHAR(50) DEFAULT('')
		
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE OrderBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE OrderBill ADD FromBillNumberID  [numeric](10, 0)  NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='FromBillID'
)
BEGIN
	ALTER TABLE OrderBill ADD FromBillID  [numeric](10, 0)  NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='isrequest'
)
BEGIN
	ALTER TABLE OrderBill ADD isrequest  int  NULL
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='oldcurmtaxprice'
)
BEGIN
	ALTER TABLE OrderBill ADD oldcurmtaxprice  [numeric](18, 4) NULL Default (0)
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='oldqty'
)
BEGIN
	ALTER TABLE OrderBill ADD oldqty  [numeric](18, 4) NULL Default (0)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='ReachTotal'
)
BEGIN
		ALTER TABLE OrderBill ADD ReachTotal [numeric](18, 4) NULL Default (0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='ReachTaxTotal'
)
BEGIN
		ALTER TABLE OrderBill ADD ReachTaxTotal [numeric](18, 4) NULL Default (0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='RequestBillNumberID'
)
BEGIN
	ALTER TABLE OrderBill ADD RequestBillNumberID  [numeric](10, 0)  NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='RequestBillID'
)
BEGIN
	ALTER TABLE OrderBill ADD RequestBillID  [numeric](10, 0)  NULL
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='AskBillNumberID'
)
BEGIN
	ALTER TABLE OrderBill ADD AskBillNumberID  [numeric](10, 0)  NULL DEFAULT (0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='AskBillID'
)
BEGIN
	ALTER TABLE OrderBill ADD AskBillID  [numeric](10, 0)  NULL  DEFAULT (0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE OrderBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE OrderBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE OrderBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE OrderBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE OrderBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE OrderBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE OrderBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE OrderBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE OrderBill ADD UnitID  INT  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE OrderBill ADD NUnitID INT  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE OrderBill ADD NQty   numeric(22,10)    NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE OrderBill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE OrderBill ADD NUnitMsg   varchar(50)  NULL  
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE OrderBill ADD MUnitID  INT  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE OrderBill ADD MQty   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE OrderBill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE OrderBill ADD MUnitMsg   varchar(50)  NULL  
END
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE OrderBill ADD MSalePrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE OrderBill ADD MDiscountPrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE OrderBill ADD MTaxPrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE OrderBill ADD CurMSalePrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE OrderBill ADD CurMDiscountPrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE OrderBill ADD CurMTaxPrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE OrderBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE OrderBill ADD IsCombined   INT
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='BillOver'
)
BEGIN
		ALTER TABLE OrderBill ADD BillOver   BIT DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE OrderBill ADD GoodsNumber   VARCHAR(100) DEFAULT('')
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE OrderBill ADD CargoID   INT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='entrycode'
)
BEGIN
		ALTER TABLE OrderBill ADD entrycode   VARCHAR(max) null
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='GoodsCostPrice'
)
BEGIN
		ALTER TABLE OrderBill ADD 
		[GoodsCostPrice] [numeric](18, 4) NULL  DEFAULT (0),
		[GoodsOrder] [int] NULL  DEFAULT ('-1'),
		[ProduceDate] [varchar](50) NULL  DEFAULT (''),
		[ValidDate] [varchar](50) NULL DEFAULT ('')		
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='IsGift'
)
BEGIN
	ALTER TABLE OrderBill ADD  IsGift INT NOT NULL DEFAULT(0) -- 0不是，1是赠品
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='YapiID'
)
BEGIN
		ALTER TABLE OrderBill ADD YapiID VARCHAR(20) NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE OrderBill ADD PriceSource VARCHAR(200) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='Id'
)
BEGIN
		ALTER TABLE OrderBill ADD Id INT NOT NULL DEFAULT(0) --同一订单内排序字段
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='PromoType'
)
BEGIN
		ALTER TABLE OrderBill ADD PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='LockNumber'
)
BEGIN
		ALTER TABLE OrderBill ADD LockNumber Numeric(24,10) NULL DEFAULT(0) --锁定基本数量
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'OrderBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.OrderBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.OrderBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

--组合品销售订单（PT_Combin_OrderBillDetail）明细ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='PTCombinOrderBillDetailID'
)
BEGIN
		ALTER TABLE OrderBill ADD PTCombinOrderBillDetailID INT NOT NULL DEFAULT(-1) 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='SaleOrderID'
)
BEGIN
	ALTER TABLE OrderBill 
		ADD SaleOrderID  [int] NULL DEFAULT(-1)
END
GO
UPDATE OrderBill SET SaleOrderID = -1 WHERE isnull(SaleOrderID ,0)=0
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CurRate'
UNION ALL SELECT 'GiftFlag';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='OrderBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------

--------------------------------------------删除索引区域开始-----------------------------------------------
--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderBill]') AND name = N'CIX_BID')
--	DROP INDEX [dbo].[OrderBill].CIX_BID
	
--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderBill]') AND name = N'NCIX_KTYPEID')
--	DROP INDEX [dbo].[OrderBill].NCIX_KTYPEID
	
--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderBill]') AND name = N'NCIX_FROMID')
--	DROP INDEX [dbo].[OrderBill].NCIX_FROMID

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderBill]') AND name = N'IX_OrderBill')
--DROP INDEX [IX_OrderBill] ON [dbo].[OrderBill] 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderBill]') AND name = N'IX_OrderBill_BillNumberId')
--DROP INDEX [IX_OrderBill_BillNumberId] ON [dbo].[OrderBill] 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderBill]') AND name = N'IX_OrderBill_PTypeID')
--DROP INDEX [IX_OrderBill_PTypeID] ON [dbo].[OrderBill] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERBILL') AND name = 'CIX_ORDERBILL_BillNumberID')
--DROP INDEX CIX_ORDERBILL_BillNumberID ON ORDERBILL 
CREATE CLUSTERED INDEX CIX_ORDERBILL_BillNumberID ON ORDERBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERBILL') AND name = 'NCIX_ORDERBILL_Ptypeid')
--DROP INDEX NCIX_ORDERBILL_Ptypeid ON ORDERBILL 
CREATE NONCLUSTERED INDEX NCIX_ORDERBILL_Ptypeid ON ORDERBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERBILL') AND name = 'NCIX_ORDERBILL_Ktypeid')
--DROP INDEX NCIX_ORDERBILL_Ktypeid ON ORDERBILL 
CREATE NONCLUSTERED INDEX NCIX_ORDERBILL_Ktypeid ON ORDERBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERBILL') AND name = 'NCIX_ORDERBILL_Orderid')
--DROP INDEX NCIX_ORDERBILL_Orderid ON ORDERBILL 
CREATE NONCLUSTERED INDEX NCIX_ORDERBILL_Orderid ON ORDERBILL(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERBILL') AND name = 'NCIX_ORDERBILL_FromBillNumberID')
--DROP INDEX NCIX_ORDERBILL_FromBillNumberID ON ORDERBILL 
CREATE NONCLUSTERED INDEX NCIX_ORDERBILL_FromBillNumberID ON ORDERBILL(FromBillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERBILL') AND name = 'NCIX_ORDERBILL_WD')
CREATE NONCLUSTERED INDEX NCIX_ORDERBILL_WD ON ORDERBILL(ptypeid,ktypeid,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID) 


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERBILL') AND name = 'NCIX_ORDERBILL_SaleOrderID')
	CREATE NONCLUSTERED INDEX NCIX_ORDERBILL_SaleOrderID ON ORDERBILL(OrderID,SaleOrderID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='ReachQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN ReachQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='PassQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN PassQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='ReachTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN ReachTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='ReachTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN ReachTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='WaitQty' AND  (a.xscale<>10 or xprec<>24)
)
BEGIN
	ALTER TABLE OrderBill 
	ALTER COLUMN WaitQty NUMERIC(24,10)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='stopreason'
)
BEGIN
	ALTER TABLE OrderBill ADD stopreason VARCHAR(max) DEFAULT ''
END  

--组合品关联ID，与CombinationOrderBill中的pindexid关联
IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[OrderBill]') and name = 'pindexid' )
BEGIN
	ALTER TABLE dbo.OrderBill ADD pindexid VARCHAR(300) NULL DEFAULT('')
END

--组合品编号
IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[OrderBill]') and name = 'combinationptypeid' )
BEGIN
	ALTER TABLE dbo.OrderBill ADD combinationptypeid VARCHAR(200) NULL DEFAULT(0)
END
GO
UPDATE OrderBill SET combinationptypeid = 0 WHERE combinationptypeid IS NULL                                       
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO 
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[OrderBill]') and  name = 'comment' and Length=250)
BEGIN
	 ALTER TABLE OrderBill
	    ALTER COLUMN comment VARCHAR(255) NULL
END
GO
UPDATE OrderBill SET comment = '' WHERE comment IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderBill' AND a.Name='SaleOrderReachQty'
)
BEGIN
	ALTER TABLE OrderBill 
		ADD SaleOrderReachQty  [numeric](24, 10) NULL DEFAULT(0)
END
GO
UPDATE OrderBill SET SaleOrderReachQty = 0 WHERE SaleOrderReachQty IS NULL
GO
UPDATE dbo.OrderBill SET ProduceDate = '' WHERE ProduceDate IS NULL
GO
UPDATE dbo.OrderBill SET ValidDate = '' WHERE ValidDate IS NULL
GO





/****** 对象:  Table [dbo].[PT_Combin_OrderBill]    脚本日期: 05/05/2010 14:48:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PT_Combin_OrderBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PT_Combin_OrderBill](
		[billNumberID] [numeric](18, 0) NOT NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_OrderBill_ptypeid]  DEFAULT ('0'),
		[qty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_OrderBill_qty]  DEFAULT (0),
		[price] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBill_price]  DEFAULT (0),
		[total] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBill_total]  DEFAULT (0),
		[ReachQty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_OrderBill_ReachQty]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_OrderBill_comment]  DEFAULT (''),
		[OrderID] [int] IDENTITY(1,1) NOT NULL,
		[Checked] [bit] NOT NULL CONSTRAINT [DF_PT_Combin_OrderBill_Checked]  DEFAULT (0),
		[TeamNO1] [int] NULL,
		[PassQty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_OrderBill_PassQty]  DEFAULT (0),
		[IsUnit2] [bit] NOT NULL CONSTRAINT [DF_PT_Combin_OrderBill_IsUnit2]  DEFAULT (0),
		[Discount] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBill_Discount]  DEFAULT (1),
		[DiscountPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBill_DiscountPrice]  DEFAULT (0),
		[TaxPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBill_TaxTotal]  DEFAULT (0),
		[SaleTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[entrycode]           varchar(max)        null,
		[FromBillID] [numeric](10, 0)  NULL,
		[ReachTotal] [numeric](24, 10) NULL Default (0),
		[ReachTaxTotal] [numeric](24, 10) NULL Default (0),
		[RequestBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[RequestBillID] [numeric](10, 0)  NULL DEFAULT (0),
		[AskBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[AskBillID] [numeric](10, 0)  NULL DEFAULT (0),
		TaxMoney             numeric(24, 10)		NULL Default(0),
		NSalePrice           numeric(24, 10)		NULL Default(0),
		NSaleTotal           numeric(24, 10)		NULL Default(0),
		NDiscountPrice       numeric(24, 10)		NULL Default(0),
		NTotal               numeric(24, 10)		NULL Default(0),
		NTaxPrice            numeric(24, 10)		NULL Default(0),
		NTaxTotal            numeric(24, 10)		NULL Default(0),
		NTaxMoney            numeric(24, 10)		NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(24, 10)     NULL Default(0),
		UnitRate             numeric(24, 10)     NULL Default(0),
		NUnitMsg             varchar(50)        NULL,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(24, 10)     NULL Default(0),
		MUnitRate            numeric(24, 10)     NULL Default(1),
		MUnitMsg             varchar(50)        NULL,
		MSalePrice           numeric(24, 10)     NULL Default(0),
		MDiscountPrice       numeric(24, 10)     NULL Default(0),
		MTaxPrice            numeric(24, 10)     NULL Default(0),
		CurMSalePrice        numeric(24, 10)     NULL Default(0),
		CurMDiscountPrice    numeric(24, 10)     NULL Default(0),
		CurMTaxPrice         numeric(24, 10)     NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL  DEFAULT (0),
		[GoodsOrder] [int] NULL  DEFAULT ('-1'),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		YapiID VARCHAR(20) NULL DEFAULT(''),
		WaitQty [numeric](24, 10) NULL Default (0),
		BillOver   BIT DEFAULT(0),
		CargoID   INT DEFAULT(0),
		PriceSource varchar(200) NOT NULL DEFAULT('') --价格信息
		,Id INT NOT NULL DEFAULT(0) --同一订单内排序字段 order by id,orderid 这样处理
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,ShowOrder INT DEFAULT(0)
		,stopreason VARCHAR(max) DEFAULT ''
		,pindexid VARCHAR(300) NULL DEFAULT('')--组合品单据表体关联ID
	) ON [PRIMARY]


END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBill') AND name = 'CIX_PT_Combin_OrderBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_PT_Combin_OrderBill_BillNumberID ON PT_Combin_OrderBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBill') AND name = 'NCIX_PT_Combin_OrderBill_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBill_Ptypeid ON PT_Combin_OrderBill(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBill') AND name = 'NCIX_PT_Combin_OrderBill_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBill_Ktypeid ON PT_Combin_OrderBill(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBill') AND name = 'NCIX_PT_Combin_OrderBill_Orderid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBill_Orderid ON PT_Combin_OrderBill(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBill') AND name = 'NCIX_PT_Combin_OrderBill_FromBillNumberID')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBill_FromBillNumberID ON PT_Combin_OrderBill(FromBillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBill') AND name = 'NCIX_PT_Combin_OrderBill_pindexid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBill_pindexid ON PT_Combin_OrderBill(pindexid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------

------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PT_Combin_OrderBill]') and  name = 'comment' and Length=250)
BEGIN
	 ALTER TABLE PT_Combin_OrderBill
	    ALTER COLUMN comment VARCHAR(255) NULL
END
GO
UPDATE PT_Combin_OrderBill SET comment = '' WHERE comment IS NULL
GO



/****** 对象:  Table [dbo].[PT_Combin_OrderBillDetail]    脚本日期: 05/05/2010 14:48:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PT_Combin_OrderBillDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PT_Combin_OrderBillDetail](
		[billNumberID] [numeric](18, 0) NOT NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_ptypeid]  DEFAULT ('0'),
		[qty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_qty]  DEFAULT (0),
		[price] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_price]  DEFAULT (0),
		[total] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_total]  DEFAULT (0),
		[ReachQty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_ReachQty]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_comment]  DEFAULT (''),
		[OrderID] [int] IDENTITY(1,1) NOT NULL,
		[Checked] [bit] NOT NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_Checked]  DEFAULT (0),
		[TeamNO1] [int] NULL,
		[PassQty] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_PassQty]  DEFAULT (0),
		[IsUnit2] [bit] NOT NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_IsUnit2]  DEFAULT (0),
		[Discount] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_Discount]  DEFAULT (1),
		[DiscountPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_DiscountPrice]  DEFAULT (0),
		[TaxPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_TaxTotal]  DEFAULT (0),
		[SaleTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_OrderBillDetail_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[entrycode]           varchar(max)        null,
		[FromBillID] [numeric](10, 0)  NULL,
		[ReachTotal] [numeric](24, 10) NULL Default (0),
		[ReachTaxTotal] [numeric](24, 10) NULL Default (0),
		[RequestBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[RequestBillID] [numeric](10, 0)  NULL DEFAULT (0),
		[AskBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[AskBillID] [numeric](10, 0)  NULL DEFAULT (0),
		TaxMoney             numeric(24, 10)		NULL Default(0),
		NSalePrice           numeric(24, 10)		NULL Default(0),
		NSaleTotal           numeric(24, 10)		NULL Default(0),
		NDiscountPrice       numeric(24, 10)		NULL Default(0),
		NTotal               numeric(24, 10)		NULL Default(0),
		NTaxPrice            numeric(24, 10)		NULL Default(0),
		NTaxTotal            numeric(24, 10)		NULL Default(0),
		NTaxMoney            numeric(24, 10)		NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(24, 10)     NULL Default(0),
		UnitRate             numeric(24, 10)     NULL Default(0),
		NUnitMsg             varchar(50)        NULL,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(24, 10)     NULL Default(0),
		MUnitRate            numeric(24, 10)     NULL Default(1),
		MUnitMsg             varchar(50)        NULL,
		MSalePrice           numeric(24, 10)     NULL Default(0),
		MDiscountPrice       numeric(24, 10)     NULL Default(0),
		MTaxPrice            numeric(24, 10)     NULL Default(0),
		CurMSalePrice        numeric(24, 10)     NULL Default(0),
		CurMDiscountPrice    numeric(24, 10)     NULL Default(0),
		CurMTaxPrice         numeric(24, 10)     NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL  DEFAULT (0),
		[GoodsOrder] [int] NULL  DEFAULT ('-1'),	
		[ProduceDate] [varchar](50) NULL  DEFAULT (''),
		[ValidDate] [varchar](50) NULL DEFAULT (''),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		YapiID VARCHAR(20) NULL DEFAULT(''),
		WaitQty [numeric](24, 10) NULL Default (0),
		BillOver   BIT DEFAULT(0),
		GoodsNumber   VARCHAR(100) DEFAULT(''),
		CargoID   INT DEFAULT(0),
		PriceSource varchar(200) NOT NULL DEFAULT('') --价格信息
		,Id INT NOT NULL DEFAULT(0) --同一订单内排序字段 order by id,orderid 这样处理
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,ShowOrder INT DEFAULT(0)
		,stopreason VARCHAR(max) DEFAULT ''
		,pindexid VARCHAR(300) NULL DEFAULT('')--组合品单据表体关联ID
		,combinationptypeid VARCHAR(200) NULL DEFAULT('')
		,LockNumber Numeric(24,10)NULL DEFAULT(0)--锁定基本数量
	) ON [PRIMARY]


END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_OrderBillDetail' AND a.Name='LockNumber'
)
BEGIN
		ALTER TABLE PT_Combin_OrderBillDetail ADD LockNumber Numeric(24,10) NULL DEFAULT(0) --锁定基本数量
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_OrderBillDetail' AND a.Name='SaleOrderReachQty'
)
BEGIN
	ALTER TABLE PT_Combin_OrderBillDetail 
		ADD SaleOrderReachQty  [numeric](24, 10) NOT NULL DEFAULT(0)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBillDetail') AND name = 'CIX_PT_Combin_OrderBillDetail_BillNumberID')
CREATE CLUSTERED INDEX CIX_PT_Combin_OrderBillDetail_BillNumberID ON PT_Combin_OrderBillDetail(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBillDetail') AND name = 'NCIX_PT_Combin_OrderBillDetail_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBillDetail_Ptypeid ON PT_Combin_OrderBillDetail(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBillDetail') AND name = 'NCIX_PT_Combin_OrderBillDetail_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBillDetail_Ktypeid ON PT_Combin_OrderBillDetail(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBillDetail') AND name = 'NCIX_PT_Combin_OrderBillDetail_Orderid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBillDetail_Orderid ON PT_Combin_OrderBillDetail(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBillDetail') AND name = 'NCIX_PT_Combin_OrderBillDetail_FromBillNumberID')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBillDetail_FromBillNumberID ON PT_Combin_OrderBillDetail(FromBillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_OrderBillDetail') AND name = 'NCIX_PT_Combin_OrderBillDetail_pindexid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_OrderBillDetail_pindexid ON PT_Combin_OrderBillDetail(pindexid)
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------

------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PT_Combin_OrderBillDetail]') and  name = 'comment' and Length=250)
BEGIN
	 ALTER TABLE PT_Combin_OrderBillDetail
	    ALTER COLUMN comment VARCHAR(255) NULL
END
GO
UPDATE PT_Combin_OrderBillDetail SET comment = '' WHERE comment IS NULL
GO



/****** 对象:  Table [dbo].[PT_SaleOrderLockDetail]    脚本日期: 2016-05-24 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PT_SaleOrderLockDetail]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[PT_SaleOrderLockDetail](
		[ID]	INT	IDENTITY(1,1), 
		[BillNumberId]	NUMERIC(10,0)	NOT NULL,
		[OrderID]	INT	NOT NULL,
		[Ptypeid]	VARCHAR(50)	COLLATE Chinese_PRC_CI_AS NULL,
		[Etypeid]	VARCHAR(50)	COLLATE Chinese_PRC_CI_AS NULL,
		[KTypeID]	VARCHAR(50)	COLLATE Chinese_PRC_CI_AS NULL,
		[CargoID]	INT	NULL	DEFAULT(0),
		[UnitID]	INT	NULL	Default(0),
		[GoodsOrder]	INT	NULL	DEFAULT ('-1'),
		[GoodsNumber]   VARCHAR(100)	DEFAULT(''),
		[GoodsCostPrice] NUMERIC(24,10) NOT NULL DEFAULT(0),
		[ItemID]	BIGINT	NULL,
		[IsCombined]	INT	NULL,
		[ProduceDate]	VARCHAR(50)	NULL	DEFAULT (''),
		[ValidDate]	VARCHAR(50)	NULL	DEFAULT (''),
		[LockNumber]	NUMERIC(24,10) NOT NULL DEFAULT(0),
		[OrderType]		INT NULL DEFAULT(0)			--订单类型：0 销售订单； 1 组合品订单
	) ON [PRIMARY]

END
GO


------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_SaleOrderLockDetail' AND a.Name='Ptypeid'
)
BEGIN
	ALTER TABLE PT_SaleOrderLockDetail 
		ADD Ptypeid	VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_SaleOrderLockDetail' AND a.Name='GoodsCostPrice'
)
BEGIN
	ALTER TABLE PT_SaleOrderLockDetail 
		ADD GoodsCostPrice	VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_SaleOrderLockDetail' AND a.Name='OrderType'
)
BEGIN
	ALTER TABLE PT_SaleOrderLockDetail 
		ADD OrderType INT DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_SaleOrderLockDetail') AND name = 'CIX_PT_SaleOrderLockDetail_BillNumberId')
CREATE CLUSTERED INDEX CIX_PT_SaleOrderLockDetail_BillNumberId ON PT_SaleOrderLockDetail(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_SaleOrderLockDetail') AND name = 'NCIX_PT_SaleOrderLockDetail_OrderID')
CREATE NONCLUSTERED INDEX NCIX_PT_SaleOrderLockDetail_OrderID ON PT_SaleOrderLockDetail(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_SaleOrderLockDetail') AND name = 'NCIX_PT_SaleOrderLockDetail_OrderID')
CREATE NONCLUSTERED INDEX NCIX_PT_SaleOrderLockDetail_OrderID ON PT_SaleOrderLockDetail(OrderID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_SaleOrderLockDetail') AND name = 'NCIX_PT_SaleOrderLockDetail_KTypeID')
CREATE NONCLUSTERED INDEX NCIX_PT_SaleOrderLockDetail_KTypeID ON PT_SaleOrderLockDetail(KTypeID) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON


IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PType_AuxiliaryUnits_Ext]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[PType_AuxiliaryUnits_Ext](
	[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
	[SaleUnitID1] [int] NULL,
	[SaleUnitRate1] [decimal](18, 0) NULL,
	[SaleUnitID2] [int] NULL,
	[SaleUnitRate2] [decimal](18, 0) NULL,
	[SaleUnitID3] [int] NULL,
	[SaleUnitRate3] [decimal](18, 0) NULL
) ON [PRIMARY]
END
GO

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PType_AuxiliaryUnits_Ext') AND name = 'CIX_PType_AuxiliaryUnits_Ext_Ptypeid')
DROP INDEX CIX_PType_AuxiliaryUnits_Ext_Ptypeid ON PType_AuxiliaryUnits_Ext 
CREATE CLUSTERED INDEX CIX_PType_AuxiliaryUnits_Ext_Ptypeid ON PType_AuxiliaryUnits_Ext(PtypeID)

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType_AuxiliaryUnits_Ext]') and  name = 'SaleUnitRate1')
BEGIN
     ALTER TABLE PType_AuxiliaryUnits_Ext
	    ALTER COLUMN SaleUnitRate1 [decimal](24, 10) NULL
END
GO 

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType_AuxiliaryUnits_Ext]') and  name = 'SaleUnitRate2')
BEGIN
     ALTER TABLE PType_AuxiliaryUnits_Ext
	    ALTER COLUMN SaleUnitRate2 [decimal](24, 10) NULL
END
GO 

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType_AuxiliaryUnits_Ext]') and  name = 'SaleUnitRate3')
BEGIN
     ALTER TABLE PType_AuxiliaryUnits_Ext
	    ALTER COLUMN SaleUnitRate3 [decimal](24, 10) NULL
END
GO 


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ptype]    脚本日期: 05/05/2010 14:48:55 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM SysDataDB..sysobjects WHERE id = OBJECT_ID(N'[SysDataDB]..[RWXsysadmin]') AND type in (N'U'))
BEGIN
	CREATE TABLE [SysDataDB]..[RWXsysadmin](
		[Password] [varchar](100) NULL,
		[Version] [varchar](100) NULL,
		[loginMode] [int] NULL,
		[Verification] [int] NULL,
		[logoimg] [image] NULL,
		[logoposition] [varchar](max) NULL,
		[logosize] [varchar](max) NULL,
		[logotype] [varchar](max) NULL
) 

END
GO
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='forcemodifypwd' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD forcemodifypwd INT NOT NULL DEFAULT(0)
END
GO

--狗号
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='dognumber' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD dognumber VARCHAR(20) NOT NULL DEFAULT('')
END
GO
--注册码
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='registercode' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD registercode VARCHAR(40) NOT NULL DEFAULT('')
END
GO
--是否总账
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='isfinance' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD isfinance INT NOT NULL DEFAULT 0
END
GO
--截止日期
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='endDate' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD endDate DATETIME NOT NULL DEFAULT ''
END
GO
--是否使用网络狗
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='isUse' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD isUse INT NOT NULL DEFAULT 0
END
GO
--强行调整注册码长度
IF EXISTS(select * from syscolumns where id = object_id(N'[RWXsysadmin]') and  name = 'registercode' and LENGTH<>40)
BEGIN
	 ALTER TABLE RWXsysadmin
	    ALTER COLUMN registercode VARCHAR(40) NULL
END
GO

---------以下是9.6文档【A8-V3登陆主页面信息调整】添加功能----------
--联系电话 1
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='ContactNumber1' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD ContactNumber1 VARCHAR(200) NULL
END
GO

--联系电话 2
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='ContactNumber2' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD ContactNumber2  VARCHAR(200) NULL
END
GO

--联系电话 3
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='ContactNumber3' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD ContactNumber3  VARCHAR(200) NULL
END
GO

--网站地址 1
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='WebSiteAddress1' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD WebSiteAddress1 VARCHAR(200) NULL
END
GO

--网站地址 2
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='WebSiteAddress2' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD WebSiteAddress2 VARCHAR(200) NULL
END
GO

--网站地址 3
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='WebSiteAddress3' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD WebSiteAddress3 VARCHAR(200) NULL
END
GO

---------以上是9.6文档【A8-V3登陆主页面信息调整】添加功能----------

--狗校验周期，0为一直校验
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='rgday' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD rgday INT NOT NULL DEFAULT(0)
END
GO

--狗最近一次校验日期
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='rgcheckdate' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD rgcheckdate DATETIME DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desrgday' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD desrgday VARCHAR(1000) DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='Wsd' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD Wsd VARCHAR(100) NOT NULL DEFAULT('120.26.200.120')
END
GO

--服务器取限制用户的标识
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='islimlogin' AND b.Name='RWXsysadmin'
)
BEGIN
	ALTER TABLE [SysDataDB]..[RWXsysadmin] 
		ADD islimlogin VARCHAR(10) NULL DEFAULT('0')
END
GO
UPDATE [SysDataDB].DBO.[RWXsysadmin] SET islimlogin = 0 WHERE islimlogin IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

	CREATE TABLE [dbo].[SType] (
		[TypeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[parid] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[leveal] [smallint] NOT NULL ,
		[sonnum] [int] NOT NULL ,
		[soncount] [int] NOT NULL ,
		[FullName] [varchar] (66) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('') ,
		[Name] [varchar] (30) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT ('') ,
		[UserCode] [varchar] (26) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT ('') ,
		[Comment] [varchar] (256) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT ('') ,
		[LinkMan] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT ('') ,
		[Address] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT ('') ,
		[Tel] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT ('') ,
		[PostCode] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT ('') ,
		[TaxNo] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT ('') ,
		[Bank] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT ('') ,
		[Account] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[deleted] [bit] NOT NULL  DEFAULT (0),
		[PyCode] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT ('') ,
		[BTypeID1] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[BTypeID2] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[PriceType] [TinyInt] NULL DEFAULT(0),
		[XiWaMaxNumber] [numeric](18, 0) NULL  DEFAULT (0),
		[ATypeID]		[VARCHAR](50) NULL DEFAULT(''),
		[ATypeID2]		[VARCHAR](50) NULL DEFAULT(''),
		[IfAssetsIni] [INT] NOT NULL DEFAULT(0),
		IsUpLoad INT NULL DEFAULT(0)
	) ON [PRIMARY]


	DELETE FROM SType
	INSERT INTO [SType] ([FullName], [UserCode], [PyCode], [deleted], [TypeID], [parid], [leveal], [soncount], [sonnum], [Name], [Comment],  [LinkMan], [Address], [Tel], [PostCode], [TaxNo], [Bank], [Account],[XiWaMaxNumber])
	VALUES ( '总部', 'ZB', 'ZB', 0, '00000', 'root', 0, 1, 1, '', '', '', '', '', '', '', '', '',1)

	INSERT INTO [SType] ([FullName], [UserCode], [PyCode], [deleted], [TypeID], [parid], [leveal], [soncount], [sonnum], [Name], [Comment],  [LinkMan], [Address], [Tel], [PostCode], [TaxNo], [Bank], [Account],[XiWaMaxNumber])
	VALUES ( '默认分支机构', 'MRFZJG', 'MRFZJG', 0, '00001', '00000', 1, 0, 0, '', '', '', '', '', '', '', '', '',2)
END

GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[SType]') and name = 'PriceType' )
BEGIN
	
	ALTER TABLE dbo.SType ADD PriceType [TinyInt] NULL DEFAULT(0)
		
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType' AND a.Name='ATypeID'
)
BEGIN
	ALTER TABLE SType ADD ATypeID VARCHAR(50) NULL DEFAULT('')
	
	EXEC('UPDATE SType SET ATypeID=''''')
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType' AND a.Name='ATypeID2'
)
BEGIN
	ALTER TABLE SType ADD ATypeID2 VARCHAR(50) NULL DEFAULT('')
	
	EXEC('UPDATE SType SET ATypeID2='''' ')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType' AND a.Name='ATypeID3'
)
BEGIN
	ALTER TABLE SType ADD ATypeID3 VARCHAR(50) NULL DEFAULT('')
	
	EXEC('UPDATE SType SET ATypeID3='''' ')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType' AND a.Name='IsSelfVerify'
)
BEGIN
	ALTER TABLE SType ADD IsSelfVerify INT NOT NULL default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType' AND a.Name='VerifyID'
)
BEGIN
	ALTER TABLE SType ADD VerifyID VARCHAR(50) NULL DEFAULT('')
	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType' AND a.Name='ATypeID4'
)
BEGIN
	ALTER TABLE SType ADD ATypeID4 VARCHAR(50) DEFAULT('')

END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType' AND a.Name='calcFullName'
)
BEGIN
	ALTER TABLE SType ADD calcFullName VARCHAR(100) NULL DEFAULT('')
	
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='SType' AND a.Name='Sid')
BEGIN
	ALTER TABLE SType ADD Sid INT identity(1,1)
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='SType' AND a.Name='IfAssetsIni')
BEGIN
	ALTER TABLE SType ADD IfAssetsIni INT NOT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='SType' AND a.Name='IsUpLoad')
BEGIN
	ALTER TABLE SType ADD IsUpLoad INT NULL DEFAULT(0)
END
GO


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[SType]') AND name = N'IX_Stype_TypeID')
--DROP  INDEX [IX_Stype_TypeID] ON [dbo].[Stype]
------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STYPE') AND name = 'CIX_STYPE_Typeid')
--DROP INDEX CIX_STYPE_Typeid ON STYPE 
CREATE CLUSTERED INDEX CIX_STYPE_Typeid ON STYPE(Typeid) 

------------------------------------------创建索引区域结束-----------------------------------------------



GO
UPDATE dbo.SType SET calcFullName='默认分支机构核算' WHERE TypeId='00001'
GO
UPDATE dbo.SType SET VerifyID='00001' WHERE TypeId='00001'
GO

UPDATE dbo.SType SET calcFullName='总部' WHERE TypeId='00000'
GO
UPDATE dbo.SType SET VerifyID='00000' WHERE TypeId='00000'
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[WebMenu]    脚本日期: 05/05/2010 14:49:53 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WebMenu]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WebMenu](
		[SysID] [int] NOT NULL,
		[MenuID] [int] NOT NULL,
		[ParentID] [int] NULL,
		[IsRoot] [bit] NOT NULL CONSTRAINT [DF_WebMenu_IsRoot]  DEFAULT (0),
		[IsSubMenu] [bit] NOT NULL CONSTRAINT [DF_WebMenu_IsSubMenu]  DEFAULT (0),
		[Tabord] [int] NOT NULL,
		[Caption] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[AllUser] [bit] NOT NULL CONSTRAINT [DF_WebMenu_AllUser]  DEFAULT (0),
		[CallType] [int] NOT NULL CONSTRAINT [DF_WebMenu_CallType]  DEFAULT (0),
		[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Offset] [int] NOT NULL CONSTRAINT [DF_WebMenu_Offset]  DEFAULT ((-1)),
		[img] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]	
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WebMenu' AND a.Name='ShortCut'
)
BEGIN
	ALTER TABLE WebMenu ADD ShortCut VARCHAR(100) NULL DEFAULT('')
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WebMenu]') AND name = N'PK_WebMenu')
ALTER TABLE [dbo].[WebMenu] DROP CONSTRAINT [PK_WebMenu]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WEBMENU') AND name = 'NCIX_WEBMENU_MenuID')
--BEGIN
--	DROP INDEX NCIX_WEBMENU_MenuID ON WEBMENU 
--END
CREATE NONCLUSTERED INDEX NCIX_WEBMENU_MenuID ON WEBMENU(MenuID) 
------------------------------------------创建索引区域结束-----------------------------------------------
DELETE FROM WebMenu

BEGIN --销售管理菜单
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,510,500,0,1,10,'销售管理','limit_menu_sale',0,1,'',-1,'',''),	
		(0,511060,510,0,1,10,'销售计划','vr',0,0,'',-1,'',''),
			(0,51106010,511060,0,0,10,'销售计划一览表',		'LIMIT_SALE_PLAN_QUERY',			0,0,'',1577,'viewTxt.gif',''),
			(0,51106020,511060,0,0,20,'销售计划执行情况',	'LIMIT_SALE_PLAN_EXEC_QUERY',		0,0,'',1579,'viewTxt.gif',''),
			(0,51106030,511060,0,0,30,'计划时段划分',		'LIMIT_SALE_PLAN_DATERANGE_QUERY',	0,0,'1',1581,'viewTxt.gif',''),
			(0,51106040,511060,0,0,40,'分支机构销售计划',	'LIMIT_STYPE_SALE_INFO_QUERY',		0,0,'1',1583,'viewTxt.gif',''),
			(0,51106050,511060,0,0,50,'部门销售计划',		'LIMIT_DTYPE_SALE_INFO_QUERY',		0,0,'',1585,'viewTxt.gif',''),
			(0,51106060,511060,0,0,60,'职员销售计划',		'LIMIT_ETYPE_SALE_INFO_QUERY',		0,0,'',1587,'viewTxt.gif',''),
		(0,511010,510,0,1,20,'价格策略','vr',0,0,'',-1,'',''),
			(0,5110102,511010,0,1,10,'高级价格策略','vr',0,0,'',-1,'',''),
				(0,51101021,5110102,0,0,10,'高级价格选项',	'LIMIT_PRICE_CHOICERULESET',		0,0,'',2519,'viewTxt.gif',''),
				(0,510341,5110102,0,0,20,'价格表档案',		'LIMIT_PRICE_BASEINFO',				0,0,'',2461,'viewTxt.gif',''),
				(0,510342,5110102,0,0,30,'价格表查询',		'LIMIT_PRICE_DATASEARCH_SEARCH',	0,0,'',2506,'viewTxt.gif',''),
				(0,510343,5110102,0,0,40,'取价规则设置',	'LIMIT_PRICE_RULESET',				0,0,'',2462,'viewTxt.gif',''),
				(0,510344,5110102,0,0,50,'取价规则查询',	'LIMIT_PRICE_RULELIST',				0,0,'',2557,'viewTxt.gif',''),
				(0,510346,5110102,0,0,70,'规则优先级设置',	'LIMIT_PRICE_RULEPRIORITYSEARCH',	0,0,'',2517,'viewTxt.gif',''),
			(0,51101010,511010,0,1,30,'基础价格策略','vr',0,0,'',-1,'',''),
				(0,510310,51101010,0,0,10,'物价信息',		'LIMIT_PRICE_MANAGE_INFO',			0,0,'',248,'viewTxt.gif','CtrlW'),
				(0,510311,51101010,0,0,20,'分支机构物价信息','LIMIT_STYPE_PRICE_MANAGE_INFO',	0,0,'',724,'viewTxt.gif',''),
				(0,510320,51101010,0,0,30,'价格跟踪选项',	'LIMIT_PRICE_TRACK_OPTIONS',		0,0,'',2961,'viewTxt.gif',''),
				(0,510321,51101010,0,0,40,'价格跟踪查询',	'LIMIT_PRICE_TRACK_SEARCH',			0,0,'',158,'viewTxt.gif','CtrlJ'),
				(0,510330,51101010,0,0,50,'简易促销价格管理','LIMIT_SALE_PROMOTION_PRICE',		0,0,'',275,'viewTxt.gif',''),
			(0,51101030,511010,0,1,20,'促销策略','vr',0,0,'',-1,'',''),
				(0,510350,51101030,0,0,10,'促销政策新增','LIMIT_PRICE_PROMOTIONALRULEADD',		0,0,'',2465,'viewTxt.gif',''),
				(0,510351,51101030,0,0,20,'促销政策查询','LIMIT_PRICE_PROMOTIONALRULESEARCH',	0,0,'',2466,'viewTxt.gif',''),
			(0,5110104,511010,0,1,40,'价格带出策略','vr',0,0,'',-1,'',''),
				(0,511010410,5110104,0,0,10,'售价带出策略','LIMIT_SALEPRICETACTICS_QUERY',		0,0,'',5017,'viewTxt.gif',''),
				(0,511010420,5110104,0,0,20,'进价带出策略','LIMIT_BUYPRICETACTICS_QUERY',	0,0,'',5019,'viewTxt.gif',''),
		(0,511020,510,0,1,30,'报价管理','vr',0,0,'',-1,'',''),
			(0,51001,511020,0,0,10,'报价单',				'LIMIT_PRICERESPONSE_BILL',			0,0,'',1363,'viewTxt.gif',''),
			(0,51002,511020,0,0,20,'报价单查询',			'LIMIT_PRICERESPONSE_BILL_QUERY',	0,0,'',1365,'',''),
		(0,51010,510,0,1,40,'零售管理','vr',0,0,'',-1,'',''),			
			(0,505,51010,0,0,10,	'零售单',		'LIMIT_RETAILSALE_VCHTYPE',		0,0,'0',151,'_txt.gif','CtrlL'),
			(0,5101020,51010,0,0,20,'零售退货单',	'LIMIT_RETAILSALEBACK',			0,0,'',2586,'',''),	
			(0,5101070,51010,0,1,30,'POS小票统计','vr',0,0,'1',-1,'',''),
				(0,510107001,5101070,0,0,10,'POS小票流水',	'LIMIT_NPOS_FLOWDATA',			0,0,'1',2610,'',''),
				(0,510107002,5101070,0,0,20,'POS小票流水明细','LIMIT_NPOS_FLOWDATA_DETAIL',	0,0,'',2611,'',''),
				(0,510107003,5101070,0,0,90,'POS终端销售统计表','LIMIT_SALE_POSSALESTATISTICS',0,0,'',4110,'',''),	
			(0,5101071,51010,0,1,40,'门店销售统计','vr',0,0,'',-1,'',''),
				(0,510107101,5101071,0,0,10,'门店销售统计表','LIMIT_SALE_STORESALESTATISTICS',0,0,'',4107,'',''),
				(0,510107102,5101071,0,0,20,'门店销售明细统计表','LIMIT_SALE_STORESALESTATISTICSDETAIL',0,0,'',4116,'',''),			
				(0,510107103,5101071,0,0,30,'门店月销售分析报表','LIMIT_STOREMONTHLYSALESANALYSISREPORT_QUERY',0,0,'',4972,'',''),
				(0,510107104,5101071,0,0,40,'门店商品销售统计表','LIMIT_POS_STOCK_PTYPE_SALE_INFO',0,0,'',5273,'',''),
			(0,5101053,51010,0,0,50,'收银员统计表','LIMIT_SALE_CASHIERSALESTATISTICS',0,0,'',4113,'',''),				
			(0,5101057,51010,0,0,60,'门店寄存取货统计表','LIMIT_STOREDEPOSITSTATISTICS_QUERY',0,0,'',4990,'',''),
			(0,5101060,51010,0,1,70,'电子秤','vr',0,0,'',-1,'',''),
				(0,5101061,5101060,0,0,10,'电子秤接口配置','LIMIT_NPOS_RELECTRONWEIGH_INTERFACESET',0,0,'',2612,'',''),
				(0,5101062,5101060,0,0,20,'电子秤模板配置','LIMIT_NPOS_RELECTRONWEIGH_TEMPSET',		0,0,'',2613,'',''),
				(0,5101063,5101060,0,0,30,'电子秤直连接口','LIMIT_NPOS_ERECTCONNECTION_INTERFACESET',0,0,'',4147,'',''),
			(0,5101030,51010,0,0,80,'POS终端管理',	'LIMIT_NPOS_TERMINALMANAGE',	0,0,'1',2601,'',''),
			(0,5101070,51010,0,0,90,'系统公告','LIMIT_SYSTEM_PUBLICANNOUNCEMENT',0,0,'',4989,'',''),
		(0,511030,510,0,1,50,'订单管理','vr',0,0,'',-1,'',''),
			(0,511,511030,0,0,10,	'销售订单',				'LIMIT_SALEORDER',				0,0,'',132,'_txt.gif','AltZ'),
			(0,555,511030,0,0,20,	'销售订单查询',			'LIMIT_SALEORDER_SEARCH',		0,0,'1',159,'search.gif',''),
			(0,510995,511030,0,0,30,'未完成销售订单查询',	'LIMIT_NOTCOMPLETE_ORDER_QUERY',0,0,'',2039,'_stat.gif',''),
			(0,5106,511030,0,0,40,	'销售订单到期报警',		'LIMIT_SALE_ORDER_ALERM',		0,0,'',534,'search.gif',''),
			(0,510993,511030,0,0,50,'销售订单汇总表',		'SALE_ORDER_SUMINFO',			0,0,'',731,'_stat.gif',''),
			(0,510994,511030,0,0,60,'销售订单分组明细表',	'SALE_ORDER_GROUPMX',			0,0,'',732,'_stat.gif',''),
			(0,5110309,511030,0,0,70,'销售订单采购查询报表','SALE_ORDER_BUYQUERY',			0,0,'',5013,'_stat.gif',''),
		(0,511040,510,0,1,60,'出货管理','vr',0,0,'',-1,'',''),
			(0,511041,511040,0,0,10,'销售出库单',	'LIMIT_SALE_VCHTYPE',		0,0,'',51,'_txt.gif','Ctrl1'),
			(0,511042,511040,0,0,20,'销售退货单',	'LIMIT_SALE_BACK_VCHTYPE',	0,0,'',52,'_txt.gif','AltQ'),
			(0,511043,511040,0,0,30,'销售换货单',	'LIMIT_SALE_GOODSEXCHANGE',	0,0,'',580,'_txt.gif','AltA'),
			(0,511044,511040,0,0,40,'赠送单',		'LIMIT_GIVE_VCHTYPE',		0,0,'',171,'_txt.gif',''),
		(0,5108,510,0,1,70,'委托代销','vr',0,0,'',-1,'_txt.gif',''),
			(0,510801,5108,0,0,10,'委托代销发货',	'LIMIT_COMMISSION_SALE_SEND_VCHTYPE',			0,0,'',210,'_txt.gif',''),
			(0,510863,5108,0,0,20,'委托代销退货',	'LIMIT_COMMISSION_SALE_BACK_VCHTYPE',			0,0,'',212,'_txt.gif',''),
			(0,510862,5108,0,0,30,'委托代销结算',	'LIMIT_COMMISSION_SALE_GATHERING_VCHTYPE',		0,0,'',211,'_txt.gif',''),
			(0,510804,5108,0,0,40,'委托代销调价',	'LIMIT_COMMISSION_SALE_CHANGE_PRICE_VCHTYPE',	0,0,'',213,'_txt.gif',''),
			(0,510807,5108,0,0,50,'委托库存查询',	'LIMIT_COMMISSION_WK_STAT',						0,0,'1',237,'search.gif',''),
			(0,510806,5108,0,0,60,'委托客户查询',	'LIMIT_COMMISSION_WB_STAT',						0,0,'',230,'search.gif',''),
			(0,510809,5108,0,0,70,'委托客户商品',	'LIMIT_COMMISSION_WBP_STAT',					0,0,'',586,'_txt.gif',''),
			(0,510808,5108,0,0,80,'委托结算查询',	'LIMIT_COMMISSION_WJ_STAT',						0,0,'',238,'search.gif',''),
			(0,510810,5108,0,0,90,'委托结算明细查询','LIMIT_COMMISSIONSALEGATHERING_DETAIL_SEARCH',	0,0,'',2932,'search.gif',''),
		(0,51020,510,0,1,80,'电脑装机配置','vr',0,0,'',-1,'_txt.gif',''),
			(0,5102010,51020,0,0,10,'电脑装机配置单',		'LIMIT_DIYPEIZHI_BILL',			0,0,'',1929,'_txt.gif',''),
			(0,5102020,51020,0,0,20,'电脑装机商品设置',		'LIMIT_DIYPEIZHI_BILL_SET',		0,0,'',1930,'_txt.gif',''),
			(0,5102030,51020,0,0,30,'电脑装机配置单查询',	'LIMIT_DIYPEIZHI_BILL_QUERY',	0,0,'',1931,'_txt.gif',''),
		(0,51021,510,0,1,90,'发出商品管理','vr',0,0,'',-1,'_txt.gif',''),
			(0,5102110,51021,0,0,10,'发出商品出库单',		'LIMIT_SALEBILL_SENDPTYPEOUTBILL',		0,0,'',4595,'_txt.gif',''),
			(0,5102120,51021,0,0,20,'发出商品退货单',		'LIMIT_SALEBILL_SENDPTYPEBACKBILL',		0,0,'',4604,'_txt.gif',''),
			(0,5102130,51021,0,0,30,'发出商品统计',			'LIMIT_SALEREPORT_SENDPTYPESTATISTICS_QUERY',	0,0,'',4613,'search.gif',''),
		(0,511070,510,0,1,100,'组合品管理','vr',0,0,'',-1,'',''),
			(0,51107001,511070,0,0,10,'组合品设置','LIMIT_COMBINATION_PRODUCT_SETBILL_QUERY',0,0,'',4132,'',''),
			(0,51107002,511070,0,0,20,'组合品销售订单','LIMIT_COMBSET_ORDERBILL_INPUT',0,0,'',4739,'',''),
			(0,51107003,511070,0,0,30,'组合品销售出库单','LIMIT_COMBSET_OUTORDERBILL_INPUT',0,0,'',4747,'',''),
			(0,51107004,511070,0,0,40,'组合品销售退货单','LIMIT_COMBSET_RETURNORDERBILL_INPUT',0,0,'',4755,'',''),			
			(0,51107005,511070,0,0,50,'组合品销售订单查询','LIMIT_REPORTCOMBSET_ORDERBILL_QUERY',0,0,'1',4763,'',''),
			(0,51107010,511070,0,0,51,'组合品销售订单采购查询','LIMIT_COMBINATION_SALEORDERBILL_QUERY',0,0,'',5153,'',''),
			(0,51107006,511070,0,0,60,'组合品销售订单汇总表','LIMIT_REPORTCOMBSET_SUMORDERBILL_QUERY',0,0,'',4766,'',''),
			(0,51107007,511070,0,0,70,'组合品销售统计表','LIMIT_REPORTCOMBSET_STATISTICS_QUERY',0,0,'',4769,'',''),
			(0,51107008,511070,0,0,80,'组合品销售统计明细表','LIMIT_REPORTCOMBSET_STATISTICSDETAILS_QUERY',0,0,'',4772,'',''),
			(0,51107009,511070,0,0,90,'组合品库存查询','LIMIT_REPORTCOMBSET_STOCK_QUERY',0,0,'',4775,'',''),
		(0,511050,510,0,1,101,'报    表','vr',0,0,'',-1,'',''),
			(0,515,511050,0,1,10,'查询统计','vr',0,0,'',-1,'viewTxt.gif',''),
				(0,51501,515,0,0,10,	'销售日报',			'LIMIT_SALE_DAY',				0,0,'',1541,'search.gif',''),
				(0,51502,515,0,0,20,	'销售月报',			'LIMIT_SALE_MOTH',				0,0,'',1542,'search.gif',''),
				(0,51530,515,0,0,30,	'销售报表',			'LIMIT_SALE_REPORT',			0,0,'',54,'ViewTxt.gif',''),
				(0,51540,515,0,0,40,	'商品销售统计',		'LIMIT_GOODS_SALE_STAT',		0,0,'1',55,'viewTxt.gif','CtrlAltS'),
				(0,51541,515,0,0,41,	'商品类别销售统计',	'LIMIT_GOODSCATEGORY_SALE_STAT',0,0,'',5160,'viewTxt.gif',''),
				(0,51550,515,0,0,50,	'客户销售统计',		'LIMIT_CLIENT_SALE_STAT',		0,0,'',56,'viewTxt.gif',''),
				(0,51560,515,0,0,60,	'职员销售统计',		'LIMIT_EMPLOYEE_SALE_STAT',		0,0,'',57,'viewTxt.gif',''),
				(0,51561,515,0,0,61,	'部门销售统计',		'LIMIT_DTYPE_SALE_STAT',		0,0,'',5178,'viewTxt.gif',''),
				(0,51570,515,0,0,70,	'仓库销售统计',		'LIMIT_STOCK_SALE_STAT',		0,0,'',58,'viewTxt.gif',''),
				(0,595,515,0,0,80,		'地区销售统计',		'LIMIT_AREA_SALE_STAT',			0,0,'',1801,'viewTxt.gif',''),
				(0,502081,515,0,0,81,  '业务员销售统计',	'LIMIT_SALESMAN_SEARCH',		0,0,'',4124,'search.gif',''),
				--(0,59518,515,0,0,81,	'商品销售类型统计',	'LIMIT_SALETYPE_STAT',			0,0,'',5009,'viewTxt.gif',''),
				(0,51505,515,0,0,90,	'销售抹零统计',		'LIMIT_SALEPREFER_STAT_QUERY',	0,0,'1',1569,'viewTxt.gif',''),
				(0,51503,515,0,0,100,	'商品销售退货统计',	'LIMIT_PTYPE_SALE_SUM_QUERY',	0,0,'',1565,'viewTxt.gif',''),
				(0,51504,515,0,0,110,	'客户销售退货统计',	'LIMIT_BTYPE_SALE_SUM_QUERY',	0,0,'',1567,'viewTxt.gif',''),
				(0,502010,515,0,0,120,	'商品赠送查询',		'LIMIT_GIVE_P_VCHTYPE',			0,0,'1',232,'search.gif',''),
				(0,502020,515,0,0,130,	'单位赠送查询',		'LIMIT_GIVE_B_VCHTYPE',			0,0,'',233,'search.gif',''),
				(0,502030,515,0,0,140,	'职员赠送查询',		'LIMIT_GIVE_E_VCHTYPE',			0,0,'',234,'search.gif',''),
				(0,502070,515,0,0,150,	'赠送获赠关联单',	'LIMIT_GIVEME_LINK_VCHBILL',	0,0,'',421,'search.gif',''),
				(0,502080,515,0,0,160,	'商品自由项销售查询','LIMIT_FREEITEM_SALE_SEARCH',	0,0,'1',2400,'search.gif',''),
				(0,502082,515,0,0,170,  '序列号销售统计','LIMIT_SERIAL_SALESSTATISTICS_SEARCH',0,0,'1',4952,'search.gif',''),
				(0,502083,515,0,0,171,  '商品销售草稿统计','LIMIT_PTYPESALEDRAFT_QUERY',0,0,'',5184,'search.gif',''),
		(0,5109,511050,0,1,20,'分析报表','vr',0,0,'',-1,'',''),
				(0,510910,5109,0,0,10,	'商品销售月分析',	'LIMIT_SALE_PTYPEMONTH_QUERY',		0,0,'',636,'viewTxt.gif',''),
				(0,510920,5109,0,0,20,	'单位销售月分析',	'LIMIT_SALE_BTYPEMONTH_QUERY',		0,0,'',637,'viewTxt.gif',''),
				(0,510930,5109,0,0,30,	'销售成本分析',		'LIMIT_SALE_COST_ASSAY',			0,0,'',60,'_stat.gif',''),
				(0,510940,5109,0,0,40,	'销售汇总分析',		'LIMIT_SALE_DISTRIBUTING_STAT',		0,0,'',59,'_stat.gif',''),
				(0,510950,5109,0,0,50,	'商品销售走势图',	'LIMIT_SALE_CURRENT_CHART',			0,0,'',348,'_stat.gif',''),
				(0,510960,5109,0,0,60,	'畅销商品分析',		'LIMIT_SALABLE_PTYPE',				0,0,'',405,'_stat.gif',''),
				(0,510970,5109,0,0,70,	'滞销商品分析',		'LIMIT_UNSALABLE_PTYPE',			0,0,'',406,'_stat.gif',''),
				(0,510980,5109,0,0,80,	'单品分析',			'LIMIT_SINGLE_PRODUCT_ANALYSE',		0,0,'',539,'_stat.gif',''),
				(0,510990,5109,0,0,90,	'流失客户统计',		'LIMIT_QP_LOSEBTYPEANSI',			0,0,'',1340,'',''),
				(0,5109100,5109,0,0,100,'商品销售存货分析',	'LIMIT_SALE_STAT_STOCKQUERY',		0,0,'',1350,'',''),
				(0,5109111,5109,0,0,111,'职员销售考评',		'LIMIT_EMPLOYEE_SALE_REVIEW',		0,0,'',1354,'_stat.gif',''),
				(0,5109120,5109,0,0,120,'职员销售类型分析',	'LIMIT_EMPLOYEE_SALETYPE_FX_QUERY',	0,0,'',2154,'_stat.gif',''),
				(0,5109121,5109,0,0,121,'商品销售类型分析',	'LIMIT_PTYPE_SALETYPE_FX_QUERY',	0,0,'',2151,'_stat.gif',''),
				(0,5109130,5109,0,0,130,'单品销售分析',		'LIMIT_SINGLE_PTYPE_ANLI_QUERY',	0,0,'',2148,'_stat.gif',''),
			(0,51105010,511050,0,1,30,'销售排行','vr',0,0,'',-1,'',''),
				(0,511050101,51105010,0,0,10,'商品销售排行','LIMIT_PRODUCT_SALE_SORT',	0,0,'',252,'_stat.gif',''),
				(0,511050102,51105010,0,0,20,'客户销售排行','LIMIT_CLIENT_SALE_SORT',	0,0,'',253,'_stat.gif',''),
				(0,511050103,51105010,0,0,30,'仓库销售排行','LIMIT_STOCK_SALE_SORT',	0,0,'',254,'_stat.gif',''),
				(0,511050104,51105010,0,0,40,'职员销售排行','LIMIT_EMPLOYEE_SALE_SORT',	0,0,'',255,'_stat.gif',''),
				(0,511050105,51105010,0,0,50,'部门销售排行','LIMIT_DEP_SALE_SORT',		0,0,'',525,'_stat.gif',''),
				(0,510988,51105010,0,0,60,	 '地区销售排行','LIMIT_AREA_SALE_SORT',		0,0,'',526,'_stat.gif',''),
			(0,5110,511050,0,1,40,'销售分布','vr',0,0,'',-1,'',''),
				(0,511001,5110,0,0,10,'部门销售分布','LIMIT_DEPARTMENT_SALE_DIST',	0,0,'',529,'search.gif',''),
				(0,511002,5110,0,0,20,'单位销售分布','LIMIT_BTYPE_SALE_DIST',		0,0,'',530,'search.gif',''),
				(0,511003,5110,0,0,30,'职员销售分布','LIMIT_EMPLOYEE_SALE_DIST',	0,0,'',531,'search.gif',''),
				(0,511004,5110,0,0,40,'仓库销售分布','LIMIT_KTYPE_SALE_DIST',		0,0,'',532,'search.gif',''),
				(0,511005,5110,0,0,50,'地区销售分布','LIMIT_AREATYPE_SALE_DIST',	0,0,'',2467,'search.gif','')
END;

BEGIN --采购管理
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,520,500,0,1,20,'采购管理','limit_menu_buy',0,1,'',-1,'',''),
		(0,62010,520,0,1,10,'请购管理','vr',0,0,'',-1,'viewTxt.gif',''),
			(0,6201010,62010,0,0,10,'请购单',		'LIMIT_BUYREQUESTBILL',				0,0,'',1962,'viewTxt.gif',''),
			(0,6201020,62010,0,0,20,'请购单查询',	'LIMIT_BUYREQUESTBILL_QUERY',		0,0,'1',1963,'viewTxt.gif',''),
			(0,6201030,62010,0,0,30,'请购计划处理',	'LIMIT_BUYREQUESTBILL_PLAN',		0,0,'',1964,'viewTxt.gif',''),
			(0,6201040,62010,0,0,40,'请购比价生单',	'LIMIT_BUYREQUESTBILL_REQUESTBILL',	0,0,'',1965,'viewTxt.gif',''),
			(0,6201050,62010,0,0,50,'请购状态查询',	'LIMIT_BUYREQUESTBILL_STATE_QUERY',	0,0,'',1966,'viewTxt.gif',''),
		(0,62020,520,0,1,20,'询价管理','vr',0,0,'',-1,'viewTxt.gif',''),
			(0,622,62020,0,0,10, '询价单',		'LIMIT_PRICEQUERY_BILL',		0,0,'',1362,'_txt.gif',''),
			(0,6210,62020,0,0,20,'询价单查询',	'LIMIT_PRICEQUERY_BILL_QUERY',	0,0,'',1364,'',''),
		(0,798,520,0,0,30,'库存商品智能补货','LIMIT_QP_STOCKPTYPEBUY',0,0,'',1335,'',''),	
		(0,62030,520,0,1,40,'订单管理','vr',0,0,'',-1,'viewTxt.gif',''),
		(0,621,62030,0,0,10,'采购订单','LIMIT_BUYORDER',0,0,'',133,'_txt.gif','AltD'),
			(0,665,62030,0,0,10,	'采购订单查询',		'LIMIT_BUYORDER_SEARCH',	0,0,'1',160,'search.gif',''),
			(0,510995,62030,0,0,20,'未完成采购订单查询',	'LIMIT_NOTCOMPLETE_BUY_ORDER_QUERY',0,0,'',5276,'_stat.gif',''),
			(0,621104,62030,0,0,30,	'采购订单到期报警',	'LIMIT_BUY_ORDER_ALERM',	0,0,'',536,'search.gif',''),
			(0,621101,62030,0,0,40,	'采购订单汇总表',	'LIMIT_BUYORDER_SUMINFO',	0,0,'',737,'search.gif',''),
			(0,621102,62030,0,0,50,	'采购订单分组明细表','LIMIT_BUYORDER_MXINFO',	0,0,'',738,'search.gif',''),						
		(0,62040,520,0,1,50,'收货管理','vr',0,0,'',-1,'viewTxt.gif',''),
			(0,6204010,62040,0,0,10,'采购入库单',	'LIMIT_BUY_VCHTYPE',		0,0,'',62,'_txt.gif','Ctrl2'),
			(0,6204020,62040,0,0,20,'采购退货单',	'LIMIT_BUY_BACK_VCHTYPE',	0,0,'',63,'_txt.gif','AltW'),
			(0,6204030,62040,0,0,30,'采购换货单',	'LIMIT_BUY_GOODSEXCHANGE',	0,0,'',581,'_txt.gif','AltS'),
			(0,620401,62040,0,0,40,'获赠单',		'LIMIT_GIVEME_VCHTYPE',		0,0,'',172,'_txt.gif',''),
		(0,6209,520,0,1,60,'受托代销','vr',0,0,'',-1,'_txt.gif',''),
			(0,620901,6209,0,0,10,'受托代销收货','LIMIT_COMMISSION_BUY_SEND_VCHTYPE',			0,0,'',214,'_txt.gif',''),
			(0,620903,6209,0,0,20,'受托代销退货','LIMIT_COMMISSION_BUY_BACK_VCHTYPE',			0,0,'',216,'_txt.gif',''),
			(0,620902,6209,0,0,30,'受托代销结算','LIMIT_COMMISSION_BUY_GATHERING_VCHTYPE',		0,0,'',215,'_txt.gif',''),
			(0,620904,6209,0,0,40,'受托代销调价','LIMIT_COMMISSION_BUY_CHANGE_PRICE_VCHTYPE',	0,0,'',217,'_txt.gif',''),
			(0,620907,6209,0,0,60,'受托客户查询','LIMIT_COMMISSION_SB_STAT',					0,0,'',239,'search.gif',''),
			(0,620908,6209,0,0,50,'受托库存查询','LIMIT_COMMISSION_SK_STAT',					0,0,'1',240,'search.gif',''),
			(0,620910,6209,0,0,70,'受托客户商品','LIMIT_COMMISSION_SGP_STAT',					0,0,'',587,'_txt.gif',''),
			(0,620909,6209,0,0,80,'受托结算查询','LIMIT_COMMISSION_SJ_STAT',					0,0,'',241,'search.gif',''),
		(0,52061,520,0,1,61,'暂估管理','vr',0,0,'',-1,'viewTxt.gif',''),
			(0,5206110,52061,0,0,10,'暂估入库单',	'LIMIT_BUYBILL_TEMPESSTORAGEBILL',		0,0,'',4574,'_txt.gif',''),
			(0,5206120,52061,0,0,20,'暂估退货单',	'LIMIT_BUYBILL_TEMPESBACKBILL',	0,0,'',4583,'_txt.gif',''),
			(0,5206130,52061,0,0,30,'采购暂估统计','LIMIT_BUYREPORT_TEMPESSTATISTICS_QUERY',0,0,'',4592,'search.gif',''),
		(0,62050,520,0,1,70,'报    表','vr',0,0,'',-1,'_txt.gif',''),
			(0,6205010,62050,0,1,10,'查询统计','vr',0,0,'',-1,'_txt.gif',''),
				(0,660,6205010,0,0,10,			'采购报表',			'LIMIT_BUY_REPORT',			0,0,'',65,'ViewTxt.gif',''),
					(0,670,6205010,0,0,20,		'商品采购统计',		'LIMIT_GOODS_BUY_STAT',		0,0,'',66,'viewTxt.gif',''),
					(0,680,6205010,0,0,30,		'供货商采购统计',	'LIMIT_SUPPLY_BUY_STAT',	0,0,'',67,'viewTxt.gif',''),					
					(0,620501010,6205010,0,0,40,'部门采购统计',		'LIMIT_DEPARTMENT_BUYQUERY',0,0,'',642,'search.gif',''),
					(0,620501011,6205010,0,0,50,'商品采购退货统计',	'LIMIT_PTYPE_BUYBACK_QUERY',0,0,'1',2043,'search.gif',''),
					(0,620501012,6205010,0,0,60,'供货商采购退货统计','LIMIT_BTYPE_BUYBACK_QUERY',0,0,'',2046,'search.gif',''),
					(0,502040,6205010,0,0,70,	'商品获赠查询',		'LIMIT_GIVEME_P_VCHTYPE',	0,0,'1',235,'search.gif',''),
					(0,502050,6205010,0,0,80,	'单位获赠查询',		'LIMIT_GIVEME_B_VCHTYPE',	0,0,'',236,'search.gif',''),
					(0,502060,6205010,0,0,90,	'赠送获赠关联单',	'LIMIT_GIVEME_LINK_VCHBILL',0,0,'',421,'search.gif',''),
					(0,502090,6205010,0,0,100,	'商品自由项采购查询','LIMIT_FREEITEM_BUY_SEARCH',0,0,'1',2397,'search.gif',''),
					(0,502091,6205010,0,0,100,	'商品采购草稿统计','LIMIT_PTYPEBUYDRAFT_QUERY',0,0,'',5181,'search.gif',''),
			(0,6205020,62050,0,1,20,'分析报表','vr',0,0,'',-1,'_txt.gif',''),
				(0,684,6205020,0,0,10,'供货商采购排行榜',	'LIMIT_BTYPE_BUY_SORT',0,0,'',1353,'viewTxt.gif',''),
				(0,683,6205020,0,0,20,'供货商销售情况分析',	'LIMIT_QP_BTYPESALEANSI',0,0,'',1339,'viewTxt.gif',''),
				(0,681,6205020,0,0,30,'商品采购月分析',		'LIMIT_BUY_PTYPEMONTH_QUERY',0,0,'',638,'viewTxt.gif',''),
				(0,682,6205020,0,0,40,'单位采购月分析',		'LIMIT_BUY_BTYPEMONTH_QUERY',0,0,'',639,'viewTxt.gif',''),
				(0,685,6205020,0,0,50,'单品进货分析',		'LIMIT_SINGLE_PTYPE_ANLI_BUY_QUERY',0,0,'',2157,'viewTxt.gif','')
END;

BEGIN --仓储运输管理
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,530,500,0,1,30,'仓储运输管理','limit_menu_stock',0,1,'',-1,'',''),
		(0,110040,530,0,1,10,'条码管理','vr',0,0,'',-1,'',''),
			(0,11004010,110040,0,0,10,'单商品打印',		'LIMIT_BARCODES_PRINT',	0,0,'',470,'viewTxt.gif',''),
			(0,11004020,110040,0,0,20,'多商品条码打印',		'LIMIT_BARCODEM_PRINT',	0,0,'',471,'viewTxt.gif',''),
			(0,11004030,110040,0,0,30,'条形码规则设置',	'LIMIT_BARCODEM_RULE',	0,0,'',2209,'viewTxt.gif',''),
			(0,11004040,110040,0,0,40,'条形码单据关联',	'LIMIT_BARCODEM_BILL',	0,0,'',2236,'viewTxt.gif',''),
		(0,975,530,0,1,20,'序列号管理','vr',0,1,'',-1,'',''),
			(0,9753,975,0,0,10,'序列号调整单',	'LIMIT_SERIALEDIVILL_VCHTYPE_BILL',	0,0,'',1547,'viewTxt.gif',''),
			(0,9751,975,0,0,20,'序列号跟踪',	'LIMIT_SERIAL_SEARCH',				0,0,'1',227,'viewTxt.gif',''),
			(0,9752,975,0,0,30,'序列号处理',	'LIMIT_SERIAL_DEAL',				0,0,'',228,'viewTxt.gif',''),
			(0,1255,975,0,0,40,'借欠序列号查询','LIMIT_BORROWLENDSERIAL_SEARCH',	0,1,'',427,'viewTxt.gif',''),
			(0,9754,975,0,0,50,'序列号库存查询','LIMIT_SERIALSTOCK_SEARCH',			0,0,'',2301,'viewTxt.gif',''),		
		(0,69010,530,0,1,30,'调拨管理','vr',0,1,'',-1,'',''),
			(0,700,69010,0,0,10,	'同价调拨单',	'LIMIT_ALLOT_VCHTYPE',		0,0,'',69,'_txt.gif','Ctrl3'),
			(0,710,69010,0,0,20,	'变价调拨单',	'LIMIT_PRICE_ALLOT_VCHTYPE',0,0,'',70,'_txt.gif','AltI'),
			(0,711,69010,0,0,21,'调货申请单','LIMIT_PRICE_POS_ALLOTAPPLY_VCHTYPE',0,0,'',4904,'_txt.gif',''),
			(0,6901401,69010,0,0,30,'商品调拨查询',	'LIMIT_ALLOT_QUERY',		0,0,'',288,'search.gif',''),
			(0,6901402,69010,0,0,40,'调拨分布',		'LIMIT_DIAOBO_FENBU',		0,0,'',591,'search.gif',''),
		(0,69050,530,0,1,40,'分支机构调拨管理','vr',0,0,'',-1,'',''),	
			(0,784,69050,0,0,10,	'分支机构调拨出库单','STYPE_ALLOTOUT_VCHTYPE',			0,0,'',716,'',''),
			(0,785,69050,0,0,10,	'分支机构调拨入库单','STYPE_ALLOTIN_VCHTYPE',			0,0,'',719,'',''),
			(0,6901403,69050,0,0,30,'分支机构调拨发货查询','STYPE_ALLOTOUT_VCHTYPE_QUERY',	0,0,'',722,'search.gif',''),
			(0,6901404,69050,0,0,40,'分支机构调拨收货查询','STYPE_ALLOTIN_VCHTYPE_QUERY',	0,0,'',723,'search.gif',''),
		(0,69015,530,0,1,41,'门店配送管理','vr',0,0,'',-1,'',''),	
			(0,6901501,69015,0,0,1,	'要货申请单','LIMIT_ERP_GETGOODS_BILL',			0,0,'',5228,'',''),
			(0,6901502,69015,0,0,2,	'门店配送单','LIMIT_ERP_POS_TRANS_BILL',			0,0,'',5237,'',''),
			(0,6901503,69015,0,0,3,	'门店配送退货单','LIMIT_ERP_POS_TRANS_BACK_BILL',			0,0,'',5246,'',''),
			(0,6901504,69015,0,0,4,	'配送验收单','LIMIT_ERP_POS_TRANS_CHECK_BILL_PASS',			0,0,'',5256,'',''),			
			(0,6901505,69015,0,0,5,	'商品配送统计','LIMIT_ERP_POS_TRANS_PTYPE_QUERY',			0,0,'1',5267,'',''),
			(0,6901506,69015,0,0,6,	'商品配送明细查询','LIMIT_ERP_POS_TRANS_DETAIL_QUERY',			0,0,'',5270,'',''),
			(0,6901507,69015,0,0,7,	'门店配送单据查询','LIMIT_USETRANSPOS_BILL_QUERY',			0,0,'',5293,'',''),
		(0,69014,530,0,1,50,'其他出入库管理','vr',0,1,'',-1,'',''),
			(0,6901409,69014,0,0,10,'其他入库单',	'LIMIT_OTHERINBILLL_VCHTYPE_BILL',		0,1,'',1551,'','AltU'),
			(0,6901405,69014,0,0,20,'其他出库单',	'LIMIT_OTHEROUTBILL_VCHTYPE',			0,1,'',1555,'','AltJ'),
			(0,6901406,69014,0,0,30,'其他入库查询',	'LIMIT_OTHERINBILLL_VCHTYPE_QUERY',		0,1,'1',1559,'',''),
			(0,6901407,69014,0,0,40,'其他出库查询',	'LIMIT_OTHEROUTBILLL_VCHTYPE_QUERY',	0,1,'',1560,'',''),
			(0,6901408,69014,0,0,50,'其他出入库查询','LIMIT_OTHERINOUTBILLL_VCHTYPE_QUERY',	0,1,'',1561,'',''),
		(0,69030,530,0,1,60,'盘点管理','vr',0,1,'',-1,'',''),
			(0,797,69030,0,0,10,'库存盘点','LIMIT_STOCKCHECK',0,0,'',152,'stock.gif',''),
			(0,720,69030,0,0,20,'报损单','LIMIT_LOSE_VCHTYPE',0,0,'',71,'_txt.gif','AltM'),
			(0,730,69030,0,0,30,'报溢单','LIMIT_GET_VCHTYPE',0,0,'',72,'_txt.gif','AltN'),
		(0,1250,530,0,1,70,'借欠管理','vr',0,1,'',-1,'',''),
			(0,1260,1250,0,0,10,'借出开单',		'LIMIT_LEND',				0,0,'',140,'_txt.gif',''),
			(0,1270,1250,0,0,20,'借进开单',		'LIMIT_BORROW',				0,0,'',139,'_txt.gif',''),
			(0,1280,1250,0,0,30,'借出还回',		'LIMIT_LENDBACK',			0,0,'',142,'_txt.gif',''),
			(0,1290,1250,0,0,40,'借进还出',		'LIMIT_BORROWBACK',			0,0,'',141,'_txt.gif',''),
			(0,1300,1250,0,0,50,'借出查询',		'LIMIT_LEND_SEARCH',		0,0,'1',143,'search.gif',''),
			(0,1310,1250,0,0,60,'借进查询',		'LIMIT_BORROW_SEARCH',		0,0,'',144,'search.gif',''),
			(0,125061,1250,0,0,61,'借欠单据草稿',	'LIMIT_STOCKREPORT_LENDBILLDRAFT_QUERY',	0,0,'',4633,'viewTxt.gif',''),
			(0,1330,1250,0,0,70,'借欠单据历程',	'LIMIT_LENDBORROW_SEARCH',	0,0,'',161,'viewTxt.gif',''),
			(0,125010,1250,0,0,80,'借欠商品汇总表','LIMIT_STOCKREPORT_BORROWLESSPTYPESUMMARYLIST',0,0,'',4568,'viewTxt.gif',''),
		(0,69040,530,0,1,80,'组装生产管理','vr',0,1,'',-1,'',''),
			(0,796,69040,0,0,10,'生产模板',		'LIMIT_PRODUCEMODEL',	0,0,'',150,'product.gif',''),
			(0,750,69040,0,0,20,'生产拆装单',	'LIMIT_PRODUCT',		0,0,'',122,'_txt.gif',''),
			(0,783,69040,0,0,30,'生产拆装统计',	'LIMIT_QP_PACKAGESTAT',	0,0,'',1342,'',''),
		(0,782,530,0,1,90,'库存预警','vr',0,0,'',-1,'',''),
			(0,7824,782,0,0,10,'库存报警设置智能分析',	'LIMIT_QP_STOCKPTYPEANSI',	0,0,'',1336,'',''),
			(0,7821,782,0,0,20,'库存预警设置',			'LIMIT_QP_STOCKALERM_SET',	0,0,'',1347,'',''),
			(0,7822,782,0,0,30,'库存上限报警',			'LIMIT_QP_STOCKALERM_UP',	0,0,'',1348,'',''),
			(0,7823,782,0,0,40,'库存下限报警',			'LIMIT_QP_STOCKALERM_DOWN',	0,0,'',1349,'',''),	
		(0,53010,530,0,1,100,'实物库存管理','vr',0,0,'',-1,'',''),
			(0,5301010,53010,0,0,10,'仓库入库单',	'LIMIT_STORAGE_STOCKINBILL_VCHTYPE',	0,0,'',4830,'',''),
			(0,5301020,53010,0,0,20,'仓库出库单',	'LIMIT_STORAGE_STOCKOUTBILL_VCHTYPE',	0,0,'',4838,'',''),
			(0,5301030,53010,0,0,30,'仓库调拨单',	'LIMIT_STORAGE_ALLOTBILL_VCHTYPE',	0,0,'',4846,'',''),
			(0,5301040,53010,0,0,40,'仓库单据草稿中心',	'LIMIT_STORAGE_DRAFTCENTER',	0,0,'1',4853,'viewTxt.gif',''),
			(0,5301050,53010,0,0,50,'仓库单据历程',	'LIMIT_STORAGE_PROGRESS',	0,0,'',4856,'',''),
			(0,5301060,53010,0,0,60,'实物库存余量表',	'LIMIT_STORAGE_BALANCE',	0,0,'1',4859,'viewTxt.gif',''),
			(0,5301070,53010,0,0,70,'实物库存分布表',	'LIMIT_STORAGE_DISTRIBUTE',	0,0,'',4862,'',''),
			(0,5301080,53010,0,0,80,'实物库存货位分布表',	'LIMIT_STORAGE_SPACEDISTRIBUTION',	0,0,'',4865,'',''),
			(0,5301090,53010,0,0,90,'仓库账面实物差异表',	'LIMIT_STORAGE_ENTITYDIFFERENCE',	0,0,'',4868,'',''),
			(0,53010100,53010,0,0,100,'实物库存序列号处理',	'LIMIT_STORAGE_SERIESNUMBERDISPOSE',	0,0,'1',4871,'viewTxt.gif',''),
			(0,53010110,53010,0,0,110,'实物库存序列号跟踪',	'LIMIT_STORAGE_SERIESNUMBERTRACE',	0,0,'',4874,'',''),	
			(0,53010120,53010,0,0,120,'实物库存出入库汇总表','LIMIT_PHYSICALINVENTORYOUTPUTSUMMARYSHEET_QUERY',	0,0,'1',4955,'',''),		(0,53010130,53010,0,0,130,'实物库存出入库汇总明细表','LIMIT_PHYSICALINVENTORYOUTPUTSUMMARYDETAILS_QUERY',	0,0,'',4958,'',''),	
		(0,53003,530,0,1,110,'仓储管理','vr',0,1,'',-1,'',''),
			(0,5300301,53003,0,0,10,'拣货',	'LIMIT_STOCK_PICKING_VCHTYPE',	0,0,'',4796,'',''),
			(0,5300302,53003,0,0,20,'上架',	'LIMIT_STOCK_UPSHELVES_VCHTYPE',	0,0,'',4804,'',''),
			(0,5300303,53003,0,0,30,'拣货草稿单据处理中心',	'LIMIT_STOCK_PICKINGDRAFT_QUERY',	0,0,'1',4812,'',''),
			(0,5300304,53003,0,0,40,'上架草稿单据处理中心',	'LIMIT_STOCK_UPSHELVESDRAFT_QUERY',	0,0,'',4811,'',''),			
		(0,53012,530,0,1,120,'运输配送管理','vr',0,0,'',-1,'search.gif',''),
			(0,5301201,53012,0,0,10,'运输配送单',		'LIMIT_STOCK_DISTRIBUTION_VCHTYPE',			0,0,'',4818,'',''),
			(0,5301202,53012,0,0,20,'运输配送单草稿单据处理中心','LIMIT_STOCK_DISTRIBUTIONDRAFT_QUERY',	0,0,'',4813,'viewTxt.gif',''),
		(0,69013,530,0,1,130,'报    表','vr',0,0,'',-1,'search.gif',''),
			(0,760,69013,0,0,10,'库存状况表',			'LIMIT_GOODS_SEARCH',					0,0,'',74,'viewTxt.gif','CtrlAltK'),			
			(0,761,69013,0,0,30,'虚拟库存状况',			'LIMIT_VIRTUALSTOCKSTATUS',				0,0,'',209,'viewTxt.gif',''),
			(0,762,69013,0,0,40,'多级库存状况表',		'LIMIT_MUTI_GOODS_SEAL',				0,0,'',402,'viewTxt.gif',''),
			(0,770,69013,0,0,50,'库存分布表',			'LIMIT_GOODS_DISTRIBUTING_SEARCH',		0,0,'',75,'viewTxt.gif',''),
			(0,6901304,69013,0,0,60,'货位分布表',		'LIMIT_DEPOSITORY_DISTRIBUTING_SEARCH',	0,0,'',2304,'viewTxt.gif',''),
			(0,6901308,69013,0,0,70,'多仓库库存查询',	'LIMIT_MULTISTOCK_SEARCH',				0,0,'',2450,'viewTxt.gif',''),
			(0,780,69013,0,0,80,'进销存汇总表',			'LIMIT_GOODS_COLLECT_SEARCH',			0,0,'',76,'viewTxt.gif','CtrlAltQ'),			
			(0,790,69013,0,0,90,'出入库汇总表',			'LIMIT_GOODS_InOutStock_SEARCH',		0,0,'',126,'viewTxt.gif',''),
			(0,6901307,69013,0,0,100,'报损报溢汇总查询',	'LIMIT_LOSTOVERFLOW_GATHER_SEARCH',		0,0,'',2394,'viewTxt.gif',''),
			(0,781,69013,0,0,110,'库存商品流量统计分析',	'LIMIT_QP_STOCKFLOW',					0,0,'',1338,'',''),
			(0,6901303,69013,0,0,120,'库存积压统计',		'LIMIT_STOCK_JY_SUM_QUERY',				0,0,'',2160,'',''),	
			(0,6901322,69013,0,0,121,'出库单处理进度查询','LIMIT_STOCK_CK_BILL',0,0,'',4901,'search.gif',''),		
			(0,6901306,69013,0,0,130,'商品自由项查询表',	'LIMIT_GOODSFREEITEM_QUERY',			0,0,'',2322,'',''),
			(0,6901301,69013,0,0,140,'库龄分析',		'LIMIT_STOCKAGE_ANALYSE_QUERY',			0,0,'1',1571,'',''),
			(0,6901302,69013,0,0,150,'库龄分布区间表',	'LIMIT_STOCKAGE_ANALYSE_DATARANGE_QUERY',0,0,'',1573,'',''),
			(0,764,69013,0,0,160,'商品批次跟踪',		'LIMIT_GOODSNUMBER_TRACK',				0,0,'1',608,'viewTxt.gif',''),
			(0,765,69013,0,0,170,'商品近效期查询',		'LIMIT_NEAR_VALIDDATE_QUERY',			0,0,'',611,'viewTxt.gif',''),
			(0,6901305,69013,0,0,180,'库存批号明细表',	'LIMIT_STOCKBATCH_QUERY',				0,0,'',2305,'viewTxt.gif',''),
			(0,766,69013,0,0,190,'商品库存批次详情',	'LIMIT_STOCKREPORT_GOODSNUMBERDETAIL',	0,0,'',2568,'viewTxt.gif',''),
			(0,763,69013,0,0,200,'商品保质期查询',		'LIMIT_GOODSVALIDDATE_QUERY',			0,0,'',607,'viewTxt.gif',''),
			(0,6901321,69013,0,1,210,'职员KPI统计','vr',0,0,'',-1,'search.gif',''),
				(0,690132110,6901321,0,0,10,'职员拣货KPI统计','LIMIT_STORAGE_KPIPICKING_QUERY',0,0,'',4883,'viewTxt.gif',''),
				(0,690132120,6901321,0,0,20,'职员上架KPI统计','LIMIT_STORAGE_KPIUPSHELVES_QUERY',0,0,'',4886,'viewTxt.gif',''),
				(0,690132130,6901321,0,0,30,'职员装车KPI统计','LIMIT_STOCK_EMPLOYEE_ZC_KPI',0,0,'',4898,'viewTxt.gif','')			
END;

BEGIN --往来管理
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,540,500,0,1,40,'往来管理','limit_menu_come',0,1,'',-1,'',''),
		(0,88016,540,0,1,10,'发票管理','vr',0,0,'',-1,'search.gif',''),
			(0,880161,88016,0,0,10,'销售发票',		'LIMIT_INVOICE_SALEBILL',		0,0,'',621,'viewTxt.gif',''),			
			(0,880162,88016,0,0,30,'销售发票查询',	'LIMIT_INVOICE_SALEQUERY',		0,0,'',622,'viewTxt.gif',''),
			(0,880163,88016,0,0,40,'销售开票统计',	'LIMIT_INVOICE_SALEBILLQUERY',	0,0,'',623,'viewTxt.gif',''),
			(0,880164,88016,0,0,50,'发票回款分析',	'LIMIT_INVOICE_SALEMONEYQUERY',	0,0,'',624,'viewTxt.gif',''),
			(0,880165,88016,0,0,60,'采购发票',		'LIMIT_INVOICE_BUYBILL',		0,0,'1',625,'viewTxt.gif',''),
			(0,880166,88016,0,0,70,'采购发票查询',	'LIMIT_INVOICE_BUYQUERY',		0,0,'',626,'viewTxt.gif',''),
			(0,880167,88016,0,0,80,'采购开票统计',	'LIMIT_INVOICE_BUYBILLQUERY',	0,0,'',627,'viewTxt.gif',''),
			(0,880168,88016,0,0,90,'发票付款分析',	'LIMIT_INVOICE_BUYMONEYQUERY',	0,0,'',628,'viewTxt.gif',''),
			(0,8801691,88016,0,0,91,'采购暂估开票',	'LIMIT_BTYPEBILL_BUYTEMPESINVOICEBILL',	0,0,'1',4616,'viewTxt.gif',''),
			(0,8801792,88016,0,0,92,'销售发货开票',	'LIMIT_BTYPEBILL_SALESENDPTYPEINVOICEBILL',	0,0,'',4624,'viewTxt.gif',''),
		(0,80010,540,0,1,20,'往来处理','vr',0,0,'',-1,'search.gif',''),
			(0,8001009,80010,0,0,10,'往来对账表',		'LIMIT_BTYPERECONCILIATION_SEARCH',	0,0,'',2925,'',''),
			(0,62924,80010,0,0,11,	'往来综合分析',		'LIMIT_QPBINTEANSI_QUERY',			0,0,'',1503,'',''),
			(0,8001001,80010,0,0,20,'预收预付查询',		'LIMIT_YSYF_TOTAL_QUERY',			0,0,'',2163,'',''),
			(0,810,80010,0,0,30,	'应收款增加',		'LIMIT_GATHERING_ADD_VCHTYPE',		0,0,'1',78,'_txt.gif',''),
			(0,820,80010,0,0,40,	'应收款减少',		'LIMIT_GATHERING_REDUCE_VCHTYPE',	0,0,'',79,'_txt.gif',''),
			(0,850,80010,0,0,50,	'应收查询',			'LIMIT_GATHERING_SEARCH',			0,0,'',83,'search.gif',''),
			(0,883,80010,0,0,60,	'内部应收查询',		'LIMIE_STYPE_INNERARQUERY',			0,0,'',715,'base04.gif',''),
			(0,881,80010,0,0,70,	'往来单位应收分布',	'LIMIT_GATHERING_SEARCH_STYPE',		0,0,'',713,'base04.gif',''),
			(0,138010,80010,0,0,80,	'超期应收款',		'LIMIT_OUTDATE_GATHERING',			0,0,'',163,'viewTxt.gif',''),
			(0,830,80010,0,0,90,	'应付款增加',		'LIMIT_PAY_ADD_VCHTYPE',			0,0,'1',80,'_txt.gif',''),
			(0,840,80010,0,0,100,	'应付款减少',		'LIMIT_PAY_REDUCE_VCHTYPE',			0,0,'',81,'_txt.gif',''),
			(0,860,80010,0,0,110,	'应付查询',			'LIMIT_PAY_SEARCH',					0,0,'',84,'search.gif',''),
			(0,882,80010,0,0,120,	'往来单位应付分布',	'LIMIT_PAY_SEARCH_STYPE',			0,0,'',714,'base04.gif',''),
			(0,138020,80010,0,0,130,'超期应付款',		'LIMIT_OUTDATE_PAYHERING',			0,0,'',472,'viewTxt.gif',''),
			(0,138030,80010,0,0,140,'往来核销单',		'LIMIT_AUDITEDSALEBILL',			0,0,'',4675,'viewTxt.gif',''),
			(0,138040,80010,0,0,150,'往来单位品牌预收查询','LIMIT_BTYPEBRANDAR_ANTICIPATED_SEARCH',	0,0,'1',4966,'search.gif',''),
			(0,138050,80010,0,0,160,'往来单位品牌应收查询','LIMIT_BTYPEBRANDAR_PAYABLE_SEARCH',	0,0,'',5091,'search.gif',''),
			
		(0,80020,540,0,1,30,'收付款处理','vr',0,0,'',-1,'search.gif',''),
			(0,8002010,80020,0,0,10,'收款单',					'LIMIT_GATHERING_VCHTYPE',				0,0,'',53,'_txt.gif','Ctrl4'),
			(0,8002020,80020,0,0,30,'付款单',					'LIMIT_PAY_VCHTYPE',					0,0,'1',64,'_txt.gif','Ctrl5'),
			(0,8002030,80020,0,0,20,'预收款单',					'PREGATHER_VCHTYPE',					0,0,'',725,'_txt.gif',''),
			(0,8002040,80020,0,0,40,'预付款单',					'PREPAY_VCHTYPE',						0,0,'',728,'_txt.gif',''),
			(0,8002050,80020,0,0,50,'未完全结算收付款单查询',	'LIIMIT_NOTCOMPLETE_ARAP',				0,0,'1',2365,'_txt.gif',''),
			(0,8002060,80020,0,0,60,'收付款结算明细表查询',		'LIMIT_ARAPCOMMISSION_DETAILT_SEARCH',	0,0,'',2663,'_txt.gif',''),
		(0,5095,540,0,1,40,'获返利管理','vr',0,0,'',-1,'search.gif',''),
			(0,509510,5095,0,0,10,'返利核算执行',	'LIMIT_ADVANTAGE_VCH',					0,0,'',245,'_txt.gif',''),
			(0,509520,5095,0,0,20,'返利标准',		'LIMIT_ADVANTAGE_SET',					0,0,'',243,'sys_00.gif',''),
			(0,509530,5095,0,0,30,'返利查询',		'LIMIT_ADVANTAGE_SEARCH',				0,0,'',244,'search.gif',''),
			(0,509531,5095,0,0,31,'返利明细查询',	'LIMIT_ADVANTAGE_DETAILT_SEARCH',		0,0,'',3020,'search.gif',''),
			(0,509540,5095,0,0,40,'获利核算执行',	'LIMIT_ADVANTAGE_GET_VCH',				0,0,'',276,'_txt.gif',''),
			(0,509550,5095,0,0,50,'获利查询',		'LIMIT_ADVANTAGE_GET_SEARCH',			0,0,'',277,'search.gif',''),
			(0,509560,5095,0,0,60,'获利明细查询',	'LIMIT_ADVANTAGE_GET_DETAILT_SEARCH',	0,0,'',3023,'search.gif',''),
		(0,5096,540,0,1,50,'价格保护','vr',0,0,'',-1,'',''),
			(0,509610,5096,0,0,10,'价保通知','LIMIT_PRICEPROTECT_NOTICE',	0,0,'',246,'viewTxt.gif',''),
			(0,509620,5096,0,0,20,'价保执行','LIMIT_PRICEPROTECT_VCH',		0,0,'',247,'_txt.gif',''),
			(0,509630,5096,0,0,30,'价保查询','LIMIT_PRICEPROTECT_SEARCH',	0,0,'',249,'search.gif',''),
			(0,509640,5096,0,0,40,'获得价保','LIMIT_PRICEPROTECT_GET',		0,0,'',403,'viewTxt.gif',''),
		(0,80070,540,0,0,61,'往来预警设置','LIMIT_INTERCOURSE_EARLYWARNING',0,0,'',2376,'search.gif',''),
		(0,80062,540,0,0,62,'期末汇差处理','LIMIT_BTYPE_HANDLEFINALRATE',0,0,'',2996,'search.gif',''),
		(0,80050,540,0,1,70,'报     表','vr',0,0,'',-1,'search.gif',''),
			(0,1395,80050,0,1,20,'结算分析','vr',0,0,'',-1,'viewTxt.gif',''),
				(0,876,1395,0,0,10,		'单据结算分析','LIMIT_COMPLETE_ASSAY',		0,0,'',479,'search.gif',''),
				(0,139501,1395,0,0,20,	'商品收款结算','LIMIT_PTYP_SKJSFX',			0,0,'',592,'viewTxt.gif',''),
				(0,139502,1395,0,0,30,	'商品付款结算','LIMIT_PTYP_FKJSFX',			0,0,'',593,'viewTxt.gif',''),
				(0,1401,1395,0,0,40,	'销售对账查询','LIMIT_SALE_QUERYACCOUNT',	0,0,'',633,'search.gif',''),
				(0,1402,1395,0,0,50,	'采购对账查询','LIMIT_BUY_QUERYACCOUNT',	0,0,'',634,'search.gif',''),
			(0,8005010,80050,0,1,10,'查询统计','vr',0,0,'',-1,'search.gif',''),
				(0,1391,8005010,0,0,10,	'部门应收查询',		'LIMIT_BATCH_GETQUERY',		0,0,'',482,'search.gif',''),
				(0,1392,8005010,0,0,20,	'部门应付查询',		'LIMIT_BATCH_PAYQUERY',		0,0,'',483,'search.gif',''),
				(0,879,8005010,0,0,30,	'职员往来查询',		'LIMIT_EMPLOYEEWLDZ_QUERY',	0,0,'',504,'search.gif',''),
				(0,1400,8005010,0,0,40,	'制单人收款统计',	'LIMIT_BILLCHECKE_ARAP',	0,0,'',528,'search.gif',''),
				(0,870,8005010,0,0,50,	'回款分析',			'LIMIT_BANKMONEY',			0,0,'',120,'search.gif',''),
				(0,875,8005010,0,0,60,	'账龄分析',			'LIMIT_ACCOUNT_TIME_QUERY',	0,0,'',347,'search.gif','')				
END;
 
BEGIN --成本费用管理
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,550,500,0,1,50,'成本费用管理','limit_menu_finance',0,1,'',-1,'',''),	
		(0,88010,550,0,1,10,'现金费用','vr',0,0,'',-1,'search.gif',''),
			(0,890,88010,0,0,10,'费用单',		'LIMIT_EXPENSE',				0,0,'',123,'_txt.gif','AltY'),
			(0,895,88010,0,0,20,'现金费用单',	'LIMIT_CASH_EXPENSE',			0,0,'',499,'_txt.gif','Ctrl6'),
			(0,910,88010,0,0,30,'转款单',		'LIMIT_MONEY_CHANGE',			0,0,'',125,'_txt.gif',''),
			(0,900,88010,0,0,40,'其他收入单',	'LIMIT_OTHER_INCOME',			0,0,'',124,'_txt.gif',''),
			(0,914,88010,0,0,50,'待摊费用发生',	'LIMIT_EXPENSE_HAPPEN_VCHTYPE',	0,0,'',192,'_txt.gif',''),
			(0,915,88010,0,0,60,'待摊费用摊销',	'LIMIT_EXPENSE_ALLOCATE_VCHTYPE',0,0,'',193,'_txt.gif',''),
		(0,88020,550,0,1,20,'固定资产','vr',0,0,'',-1,'search.gif',''),
			(0,911,88020,0,0,10,'固定资产购买','LIMIT_FIXED_BUY_VCHTYPE',			0,0,'',194,'_txt.gif',''),
			(0,912,88020,0,0,20,'固定资产变卖','LIMIT_FIXED_SALE_VCHTYPE',			0,0,'',195,'_txt.gif',''),
			(0,913,88020,0,0,30,'固定资产折旧','LIMIT_FIXED_DEPRECIATION_VCHTYPE',	0,0,'',196,'_txt.gif',''),
		(0,88040,550,0,1,30,'费用分摊','vr',0,0,'',-1,'search.gif',''),
			(0,8804010,88040,0,0,10,'入库费用分摊','LIMIT_BUYSHAREFEEBILL_VCHTYPE_BILL',	0,0,'',1939,'search.gif',''),
			(0,8804020,88040,0,0,20,'销售费用分摊','LIMIT_SALESHAREFEEBILL_VCHTYPE_BILL',	0,0,'',1944,'search.gif',''),
			--(0,8804030,88040,0,0,30,'运输费用分摊','LIMIT_YFFYSHAREFEEBILL_VCHTYPE',	0,0,'',4927,'search.gif',''),
			(0,8804040,88040,0,0,40,'入库费用分摊单查询','LIMIT_BUYSHAREFEEBILL_QUERY',0,0,'1',5140,'viewTxt.gif',''),
			(0,8804050,88040,0,0,50,'销售费用分摊单查询','LIMIT_SALESHAREFEEBILL_QUERY',0,0,'',5143,'viewTxt.gif',''),
			
		(0,5107,550,0,1,40,'提成管理','vr',0,0,'',-1,'',''),
			(0,510710,5107,0,1,10,'业务分配','vr',0,0,'',-1,'',''),
				(0,51071010,510710,0,0,10,'业绩分配',				'LIMIT_YEJI_FENPEI',						0,0,'',1543,'',''),
				(0,51071020,510710,0,0,20,'业务员回款统计汇总表',	'LIMIT_YEJI_FENPEI_SUM',					0,0,'1',1544,'viewTxt.gif',''),
				(0,51071030,510710,0,0,30,'业绩分配查询统计',		'LIMIT_INCENTIVE_PERFORMANCEALLOTMENTQUERY',0,0,'',2966,'viewTxt.gif',''),
			(0,510720,5107,0,1,20,'基础提成','vr',0,0,'',-1,'',''),
				(0,51072001,510720,0,0,10,'提成公式',		'LIMIT_EMPLOYEE_LIFT_SET',		0,0,'',615,'viewTxt.gif',''),
				(0,51072002,510720,0,0,20,'提成规则',		'LIMIT_EMPLOYEE_LIFT_RULE',		0,0,'',616,'viewTxt.gif',''),
				(0,51072003,510720,0,0,30,'提成统计',		'LIMIT_EMPLOYEE_LIFT_QUERY',	0,0,'',617,'viewTxt.gif',''),
				(0,51072004,510720,0,0,40,'职员提成参考',	'LIMIT_EMPLOYEELIFT_REFERENCE',	0,0,'',2597,'viewTxt.gif',''),
			(0,510730,5107,0,1,30,'高级提成','vr',0,0,'',-1,'',''),
				(0,51073001,510730,0,0,10,'业务级别',				'LIMIT_INCENTIVE_BUSINESSLEVELSET',		0,0,'',2969,'viewTxt.gif',''),
				(0,51073002,510730,0,0,20,'提成规则设置',			'LIMIT_INCENTIVE_RULE',					0,0,'',2977,'viewTxt.gif',''),
				(0,51073003,510730,0,0,30,'参照计划提成',			'LIMIT_INCENTIVE_ACCORDINGPLAN_VIEW',	0,0,'',4370,'viewTxt.gif',''),
				(0,51073004,510730,0,0,40,'提成方案',				'LIMIT_INCENTIVE_COMMISSIONSCHEME_VIEW',0,0,'1',4378,'viewTxt.gif',''),
				(0,51073005,510730,0,0,50,'提成计算（提成规则）',	'LIMIT_INCENTIVE_ACCOUNT',				0,0,'',4387,'viewTxt.gif',''),
				(0,51073006,510730,0,0,60,'提成计算（参照计划）',	'LIMIT_INCENTIVE_ACCOUNTBYPLAN',		0,0,'',4470,'viewTxt.gif',''),
				(0,51073007,510730,0,0,70,'提成单查询',				'LIMIT_INCENTIVEBILL_VIEW',				0,0,'',2988,'viewTxt.gif',''),
				(0,51073008,510730,0,0,80,'提成报表统计',			'LIMIT_INCENTIVE_COMMISSION_QUERY',		1,0,'1',2992,'viewTxt.gif',''),
		(0,916,550,0,0,50,'业务凭证','LIMIT_ACCOUNT_CREDENCE',0,0,'',515,'_txt.gif','AltK'),
		(0,110020,550,0,1,60,'财务接口','vr',0,0,'',-1,'',''),
			(0,11002010,110020,0,0,10,'凭证查询','LIMIT_ACCOUNT_INTERFACE_QUERY',			0,0,'',425,'',''),
			(0,11002020,110020,0,0,20,'凭证下载','LIMIT_ACCOUNT_INTERFACE_FILE_DOWNLOAD',	0,0,'',426,'',''),
		(0,740,550,0,0,70,'成本调价单','LIMIT_CHANGE_PRICE_VCHTYPE',0,0,'',73,'_txt.gif','AltO'),
		(0,55008,550,0,1,80,'成本核算','vr',0,0,'',-1,'',''),
			(0,741,55008,0,0,10,'成本计算','LIMIT_COSTCALCULATION',0,0,'',4672,'_txt.gif',''),
			(0,5500802,55008,0,0,20,'结转成本','LIMIT_CARRY_COST',0,0,'',4785,'_txt.gif',''),
		(0,88030,550,0,1,90,'报    表','vr',0,0,'',-1,'search.gif',''),
			(0,8803010,88030,0,1,10,'收入查询','vr',0,0,'',-1,'search.gif',''),
				(0,920,8803010,0,0,10,'收入报表',	 'LIMIT_INCOME_SEARCH',				0,0,'',127,'search.gif',''),
				(0,925,8803010,0,0,20,'职员收入报表','LIMIT_INCOME_EMPLOYEE_SEARCH',	0,0,'',345,'search.gif',''),
				(0,926,8803010,0,0,30,'部门收入报表','LIMIT_INCOME_DEPARTMENT_SEARCH',	0,0,'',609,'viewTxt.gif',''),
			(0,8803020,88030,0,1,20,'费用查询','vr',0,0,'',-1,'search.gif',''),
				(0,930,8803020,0,0,10,'费用支出',	 'LIMIT_EXPENSE_SEARCH',			0,0,'',128,'search.gif',''),
				(0,931,8803020,0,0,20,'职员费用报表','LIMIT_EXPENSE_EMPLOYEE_SEARCH',	0,0,'',346,'search.gif',''),
				(0,961,8803020,0,0,30,'单位费用报表','LIMIT_BTYPE_DWFYBB',				0,0,'',590,'viewTxt.gif',''),
				(0,880302007,8803020,0,0,31,'单位品牌费用报表','LIMIT_EXPENSE_COMPANYBRAND_QUERY',0,0,'',4234,'viewTxt.gif',''),
				(0,932,8803020,0,0,40,'部门费用报表','LIMIT_DEPARTMENT_EXPENSE_QUERY',	0,0,'',547,'search.gif',''),
				(0,933,8803020,0,0,50,'地区费用报表','LIMIT_AREA_EXPENSE_QUERY',		0,0,'',548,'search.gif',''),
				(0,936,8803020,0,0,60,'待摊费用报表','LIMIT_EXPENSE_ALLOCATE_SEARCH',	0,0,'',197,'search.gif',''),
			(0,88015,88030,0,1,30,'财务查询','vr',0,0,'',-1,'search.gif',''),
				(0,940,88015,0,0,10,	'现金银行查询',	'LIMIT_CASH_BANK_SEARCH',				0,0,'',82,'search.gif',''),
				(0,941,88015,0,0,10,	'现金银行汇总统计','LIMIT_CASHBANKCOMB_SEARCH',	0,0,'',5129,'search.gif',''),
				(0,945,88015,0,0,20,	'现金银行报表',	'LIMIT_ACCOUNT_CASHBANK_REPORT',		0,0,'',440,'search.gif',''),
				(0,946,88015,0,0,30,	'职员创利报表',	'LIMIT_EMPINC_QUERY',					0,0,'',451,'viewTxt.gif',''),
				(0,947,88015,0,0,40,	'客户业务分析',	'LIMIT_BTYPE_ANALYSE_QUERY',			0,0,'',614,'viewTxt.gif',''),
				(0,950,88015,0,0,50,	'损益表',		'LIMIT_PROFIT_SEARCH',					0,0,'1',85,'viewTxt.gif','CtrlAltY'),
				(0,960,88015,0,0,60,	'资产负债表',	'LIMIT_ASSET_SEARCH',					0,0,'',86,'viewTxt.gif',''),
				(0,8801501,88015,0,0,11,'现金银行日报表','LIMIT_ACCOUNT_CASHBANK_DAIRY_REPORT',	0,0,'',2406,'search.gif',''),
			(0,88018,88030,0,1,40,'部门核算','vr',0,0,'',-1,'search.gif',''),
				(0,880183,88018,0,0,10,'部门销售分布','LIMIT_DEPARTMENT_SALE_DIST',		0,0,'',529,'search.gif',''),
				(0,880184,88018,0,0,20,'部门销售排行','LIMIT_DEP_SALE_SORT',			0,0,'',525,'search.gif',''),
				(0,880181,88018,0,0,30,'部门采购统计','LIMIT_DEPARTMENT_BUYQUERY',		0,0,'',642,'search.gif',''),
				(0,880187,88018,0,0,40,'部门应收查询','LIMIT_BATCH_GETQUERY',			0,0,'',482,'search.gif',''),
				(0,880188,88018,0,0,50,'部门应付查询','LIMIT_BATCH_PAYQUERY',			0,0,'',483,'search.gif',''),
				(0,880185,88018,0,0,60,'部门收入报表','LIMIT_INCOME_DEPARTMENT_SEARCH',	0,0,'',609,'search.gif',''),
				(0,880186,88018,0,0,70,'部门费用报表','LIMIT_DEPARTMENT_EXPENSE_QUERY',	0,0,'',547,'search.gif',''),
				(0,880182,88018,0,0,80,'部门损益表',  'LIMIT_DEPARTMENT_SYBQUERY',		0,0,'1',643,'search.gif','')
END;

BEGIN --总账管理
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES		
	(0,560,500,0,1,60,'总账管理','limit_menu_ac',0,0,'',-1,'search.gif',''),
		(0,56090,560,0,1,9,'基础资料','vr',0,0,'',-1,'search.gif',''),
			(0,10102002,56090,0,0,10,	'凭证字',		'LIMIT_VOUCHER_BASE',					0,0,'1',2187,'',''),				
			(0,10102004,56090,0,0,20,	'结算方式',			'LIMIT_BALANCETYPE_BASE',				0,0,'',2189,'',''),
			(0,10102001,56090,0,0,30,	'现金流量项目',		'LIMIT_CASHFLOW_BASE',					0,0,'',2184,'',''),			
			(0,10102010,56090,0,0,40,	'自定义辅助核算',	'LIMIT_ASSISTCHECKITEMS_BASE',			0,0,'',4654,'',''),			
			(0,10102006,56090,0,0,50,	'科 目 表',		'LIMIT_ACCOUNT_BASE',					0,0,'1',2191,'',''),
			(0,1096,56090,0,0,60,		'会计科目',			'LIMIT_ATYPE_BASE',						0,0,'',508,'base_stock.gif','CtrlA'),
			(0,1097,56090,0,0,70,		'会计科目多级权限',	'LIMIT_ATYPE_MULLEVEL_QUERY',			0,0,'',4503,'base_stock.gif',''), 				
			(0,10102005,56090,0,0,80,	'凭证模板',			'LIMIT_AUDITTEMPLATE_BASE',				0,0,'1',2190,'',''),			
			(0,880501009,56090,0,0,90, '常用凭证模板',			'LIMIT_ACCOUNT_COMMONTEMPLATES_VIEW',0,0,'0','4364','',''),
		(0,56010,560,0,1,10,'凭证处理','vr',0,0,'',-1,'search.gif',''),			
			(0,880501010,56010,0,0,10,'会计凭证录入',			'LIMIT_VOURCH_BILL',				0,0,'',2206,'search.gif',''),
			(0,880501020,56010,0,0,20,'会计凭证查询',			'LIMIT_VOURCH_SEARCH',				0,0,'1',2207,'search.gif',''),
			(0,880501030,56010,0,0,30,'作废凭证清理',			'LIMIT_AC_CANCELVOUCHERCLEAR',		0,0,'',2636,'search.gif',''),
			(0,880501080,56010,0,0,31,'凭证断号检查调整',		'LIMIT_AC_VOUCHERFAULTNOADJUST',	0,0,'',4663,'search.gif',''),
			(0,880501040,56010,0,0,40,'重排会计凭证号',			'LIMIT_AC_RECOMPOSITIONVOUCHERNUM',	0,0,'',2639,'search.gif',''),
			(0,880501050,56010,0,0,50,'单据逐张批量生成凭证',	'LIMIT_BILLTOVOUCH_BATCHBYONE',		0,0,'',3026,'search.gif',''),
			(0,880501060,56010,0,0,60,'出纳签字',				'LIMIT_CASHIERSIGNATURESEARCH_QUERY',0,0,'',2954,'search.gif',''),
			(0,880501070,56010,0,0,70,'现金流量查询',			'LIMIT_ACREPORT_CASHFLOW'			,0,0,'',4556,'search.gif',''),
		(0,56020,560,0,1,20,'账    簿','vr',0,0,'',-1,'search.gif',''),
			(0,880502010,56020,0,0,10,'总分类账',		'LIMIT_GENERAL_LEDGER',			0,0,'',2210,'search.gif',''),
			(0,880502020,56020,0,0,20,'明细分类账',		'LIMIT_DETAIL_LEDGER',			0,0,'',2211,'search.gif',''),
			(0,880502030,56020,0,0,30,'辅助核算总账',	'LIMIT_CHECK_GENERAL_LEDGER',	0,0,'1',2212,'search.gif',''),
			(0,880502040,56020,0,0,40,'辅助核算明细账',	'LIMIT_CHECK_DETAIL_LEDGER',	0,0,'',2213,'search.gif',''),
			(0,880502050,56020,0,0,50,'多栏账查询',		'LIMIT_MULTICOLUMN_LEDGER',		0,0,'1',2214,'search.gif',''),
			(0,880502060,56020,0,0,60,'多栏账设计',		'LIMIT_MULTICOLUMN_DESIGN',		0,0,'',2310,'search.gif',''),
			(0,880502070,56020,0,0,60,'科目汇总表',		'LIMIT_SUBJECT_GATHER',			0,0,'1',2311,'search.gif',''),
		(0,56030,560,0,1,30,'财务报表','vr',0,0,'',-1,'search.gif',''),
			(0,880503010,56030,0,0,10,'科目余额表',			'LIMIT_SUBJECT_BALANCE',			0,0,'',2215,'search.gif',''),
			(0,880503011,56030,0,0,20,'科目余额汇总表',		'LIMIT_ACCOUNTBALANCESUM_QUERY',	0,0,'',4478,'search.gif',''),
			(0,880503020,56030,0,0,30,'辅助核算余额表',		'LIMIT_PROJECT_BALANCE',			0,0,'1',2218,'search.gif',''),
			(0,880503030,56030,0,0,40,'辅助核算组合表',		'LIMIT_PROJECT_COMBINATION',		0,0,'',2220,'search.gif',''),
			(0,880503031,56030,0,0,50,'科目核算项目组合表',	'LIMIT_PROJECT_ACITEMCOMBINATION',	0,0,'',4415,'search.gif',''),
			(0,56030060,56030,0,0,60, '企业财报',			'LIMIT_AC_THREEFINANCIALSUMMARY_QUERY',	0,0,'1',4894,'search.gif',''),
			(0,880503040,56030,0,0,70,'自定义报表设计',		'LIMIT_CUSTOM_REPORT_DESIGN',		0,0,'',2343,'search.gif',''),
			(0,880503050,56030,0,0,80,'自定义报表查询',		'LIMIT_CUSTOM_REPORT',				0,0,'',2227,'search.gif',''),
		(0,56040,560,0,1,40,'结    账','vr',0,0,'',-1,'search.gif',''),
			(0,880504010,56040,0,0,10,'期末调汇','LIMIT_TERMINAL_ADJUST',0,0,'',2222,'search.gif',''),
			(0,880504020,56040,0,0,20,'结转损益','LIMIT_CARRY_PROFIT',0,0,'',2223,'search.gif',''),
			(0,880504030,56040,0,0,30,'期末结账','LIMIT_TERMINAL_SETTLE',0,0,'',2224,'search.gif',''),
		(0,56041,560,0,1,41,'出纳管理','limit_menu_te',0,0,'0',-1,'',''),
			(0,560411,56041,0,1,10,'基础设置','vr',0,0,'0',-1,'',''),
				(0,5604111,560411,0,0,10,'设置启用期间','LIMIT_TELLER_FPERIODSET',0,0,'0',4347,'',''),
				(0,10102092,560411,0,0,20,	'银行账户','LIMIT_TELLER_BANKACCOUNT_VIEW',0,0,'0','4301','',''),
				(0,10102091,560411,0,0,300,	'金融机构','LIMIT_TELLER_FINANCIALINSTITUTION_VIEW',0,0,'0','4308','',''),
			(0,560412,56041,0,1,20,'系统初始化','vr',0,0,'0','-1','',''),
				(0,5604121,560412,0,0,10,'出纳初始化数据',	'LIMIT_TELLER_INIDATA_VIEW',0,0,'0',4314,'',''),
				(0,5604122,560412,0,0,20,'结束初始化',		'LIMIT_TELLER_SYSINI',		0,0,'0',4348,'',''),
			(0,560413,56041,0,1,30,'业务处理','vr',0,0,'0','-1','',''),
				(0,5604131,560413,0,0,10,'资金调拨单',	'LIMIT_TELLER_FUNDSMOVEBILL_ADD',			0,0,'0',4319,'',''),
				(0,5604132,560413,0,0,20,'现金日记账',	'LIMIT_TELLER_CASHJOURNAL_VIEW',			0,0,'0',4323,'',''),
				(0,5604133,560413,0,0,30,'银行日记账',	'LIMIT_TELLER_BANKJOURNAL_VIEW',			0,0,'0',4328,'',''),
				(0,5604134,560413,0,0,40,'银行对账单',	'LIMIT_TELLER_BANKSTATEMENT_VIEW',			0,0,'0',4333,'',''),
				(0,5604135,560413,0,0,50,'银行存款对账','LIMIT_TELLER_BANKDEPOSITRECONCILIATION',	0,0,'0',4350,'',''),
				(0,5604136,560413,0,0,60,'银行存款余额调节表',	'LIMIT_TELLER_BALANCEADJUSTMENT_VIEW',		0,0,'0',4338,'',''),
				(0,5604137,560413,0,0,70,'出纳日结',	'LIMIT_TELLER_CASHIER',						0,0,'0',4351,'',''),
			(0,56044,56041,0,1,40,'期末处理','vr',0,0,'0','-1','',''),
				(0,560441,56044,0,0,10,'期末对账',		'LIMIT_TELLER_FINALRECONCILIATION',	0,0,'0',4352,'',''),
				(0,560442,56044,0,0,20,'出纳期末结账',	'LIMIT_TELLER_FINALCHECKOUT',		0,0,'0',4353,'',''),
			(0,56045,56041,0,1,50,'报表管理','vr',0,0,'0','-1','',''),
				(0,560451,56045,0,0,10,'资金日报表',	'LIMIT_TELLER_DAILYCASHREPORT_QUERY',		0,0,'0',4344,'',''),
				(0,560452,56045,0,0,20,'资金汇总表',	'LIMIT_TELLER_CASHSUMMARYTABLE_QUERY',		0,0,'0',4356,'',''),
		(0,56050,560,0,1,50,'固定资产','vr',0,0,'',-1,'search.gif',''),
			(0,5605010,56050,0,1,10,'基础数据','vr',0,0,'',-1,'search.gif',''),
				(0,56050101,5605010,0,0,10,'资产类别','LIMIT_FIXED_TYPE',			0,0,'',2470,'base05.gif',''),
				(0,56050102,5605010,0,0,20,'存放地点','LIMIT_FIXED_LACATION',		0,0,'',2477,'base05.gif',''),
				(0,56050103,5605010,0,0,30,'使用状况','LIMIT_FIXED_USED',			0,0,'',2484,'base05.gif',''),
				(0,56050104,5605010,0,0,40,'业务类型','LIMIT_FIXED_BUSINESSTYPE',	0,0,'',2491,'base05.gif',''),
				--(0,56050105,5605010,0,0,50,'变更原因','LIMIT_FIXED_REASONSFORCHANGE',	0,0,'',4695,'base05.gif',''),
			(0,5605020,56050,0,1,20,'固定资产初始化','vr',0,0,'',-1,'search.gif',''),
				(0,560502010,5605020,0,0,10,'初始数据录入',	'LIMIT_FIXED_CARD_INIADD',	0,0,'',2640,'search.gif',''),
				(0,560502020,5605020,0,0,20,'初始化',		'LIMIT_PRICE_INI',			0,0,'',2560,'search.gif',''),
				(0,560502030,5605020,0,0,30,'反初始化',		'LIMIT_PRICE_UNINI',		0,0,'',2591,'search.gif',''),
			(0,5605030,56050,0,1,30,'业务处理','vr',0,0,'',-1,'search.gif',''),
				(0,56050301,5605030,0,0,10,'固定资产卡片',		'LIMIT_FIXED_CARD_ADD',			0,0,'',2523,'search.gif',''),
				(0,56050302,5605030,0,0,20,'固定资产卡片清单',	'LIMIT_FIXED_CARDLIST_SEARCH',	0,0,'',2545,'search.gif',''),
				(0,56050303,5605030,0,0,30,'固定资产增加单',	'LIMIT_FIXED_ADDBILL',			0,0,'1',2530,'search.gif',''),
				(0,56050304,5605030,0,0,40,'固定资产减少单',	'LIMIT_FIXED_REDUCEBILL',		0,0,'',2535,'search.gif',''),
				(0,56050305,5605030,0,1,50,'固定资产变更','vr',0,0,'',-1,'search.gif',''),
					(0,560503051,56050305,0,0,10,'部门转移',	'LIMIT_PRICE_DEPARTMENTCHANGE',	0,0,'',2561,'search.gif',''),
					(0,560503052,56050305,0,0,20,'计提减值准备','LIMIT_PRICE_IMPAIRMENT',		0,0,'',2562,'search.gif',''),
					(0,560503053,56050305,0,0,30,'折旧方式变更','LIMIT_DEPRECIATION_TYPECHANGE',0,0,'',2592,'search.gif',''),
					--(0,560503054,56050305,0,0,40,'卡片原值变更','LIMIT_FIXED_CARDSNETVALUECHANGE',0,0,'',4701,'search.gif',''),
				--(0,56050306,5605030,0,0,60,'固定资产拆分','LIMIT_FIXED_SPLITASSETSCARDS',0,0,'',4717,'search.gif',''),
				(0,56050307,5605030,0,0,70,'固定资产变更查询','LIMIT_FIXED_CHANGE_SEARCH',0,0,'',2548,'search.gif',''),
			(0,5605050,56050,0,0,40,'固定资产条码打印','LIMIT_FIXED_ENTRYCODE_PRINT',0,0,'',2942,'search.gif',''),
			(0,5605060,56050,0,0,60,'固定资产盘点查询','LIMIT_FIXED_INVENTORYBILLSEARCH_QUERY',0,0,'',2943,'search.gif',''),
			(0,5605070,56050,0,1,70,'折旧管理','vr',0,0,'',-1,'search.gif',''),
				(0,560507001,5605070,0,0,10,'年度折旧计划表查询',	'LIMIT_FIXED_DEPRECIATIONPLAN_SEARCH',		0,0,'',2551,'search.gif',''),
				(0,560507002,5605070,0,0,20,'月度折旧计划表查询',	'LIMIT_FIXED_DEPRECIATIONPLANMONTH_SEARCH',	0,0,'',2594,'search.gif',''),
				(0,560507003,5605070,0,0,30,'固定资产折旧',			'LIMIT_FIXED_DEPRECIATIONBILL',				0,0,'',2540,'search.gif',''),
			(0,5605080,56050,0,1,80,'报表查询','vr',0,0,'',-1,'search.gif',''),
				(0,560508001,5605080,0,0,10,'固定资产卡片历史查询','LIMIT_FIXED_HISTORY_SEARCH',0,0,'',2554,'search.gif',''),
		(0,56060,560,0,0,60,'财务业务对账','LIMIT_AC_ACCOUNTBAKABCEBUSINES',0,0,'',2641,'',''),
		(0,56070,560,0,0,70,'财务参数','LIMIT_FINANCIAL_PARAMETES',0,0,'1',5147,'',''),
		(0,56080,560,0,0,80,'单据往来科目设置','LIMIT_FINANCIAL_BILL_PARAMETES',0,0,'',5148,'','')
END;

BEGIN --固定资产管理
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
		(0,561,500,0,1,61,'固定资产','limit_menu_fixe',0,1,'',-1,'',''),
			(0,56110,561,0,1,10,'基础数据','vr',0,0,'',-1,'search.gif',''),
				(0,5611001,56110,0,0,10,'资产类别','LIMIT_FIXED_TYPE',			0,0,'',2470,'base05.gif',''),
				(0,5611002,56110,0,0,20,'存放地点','LIMIT_FIXED_LACATION',		0,0,'',2477,'base05.gif',''),
				(0,5611003,56110,0,0,30,'使用状况','LIMIT_FIXED_USED',			0,0,'',2484,'base05.gif',''),
				(0,5611004,56110,0,0,40,'业务类型','LIMIT_FIXED_BUSINESSTYPE',	0,0,'',2491,'base05.gif',''),
				--(0,5611005,56110,0,0,50,'变更原因','LIMIT_FIXED_REASONSFORCHANGE',	0,0,'',4695,'base05.gif',''),
			(0,56120,561,0,1,20,'固定资产初始化','vr',0,0,'',-1,'search.gif',''),
				(0,5612010,56120,0,0,10,'初始数据录入',	'LIMIT_FIXED_CARD_INIADD',	0,0,'',2640,'search.gif',''),
				(0,5612020,56120,0,0,20,'初始化',		'LIMIT_PRICE_INI',			0,0,'',2560,'search.gif',''),
				(0,5612030,56120,0,0,30,'反初始化',		'LIMIT_PRICE_UNINI',		0,0,'',2591,'search.gif',''),
			(0,56130,561,0,1,30,'业务处理','vr',0,0,'',-1,'search.gif',''),
				(0,5613001,56130,0,0,10,'固定资产卡片',		'LIMIT_FIXED_CARD_ADD',			0,0,'',2523,'search.gif',''),
				(0,5613002,56130,0,0,20,'固定资产卡片清单',	'LIMIT_FIXED_CARDLIST_SEARCH',	0,0,'',2545,'search.gif',''),
				(0,5613003,56130,0,0,30,'固定资产增加单',	'LIMIT_FIXED_ADDBILL',			0,0,'1',2530,'search.gif',''),
				(0,5613004,56130,0,0,40,'固定资产减少单',	'LIMIT_FIXED_REDUCEBILL',		0,0,'',2535,'search.gif',''),
				(0,5613005,56130,0,1,50,'固定资产变更','vr',0,0,'',-1,'search.gif',''),
					(0,561300501,5613005,0,0,10,'部门转移',		'LIMIT_PRICE_DEPARTMENTCHANGE',	0,0,'',2561,'search.gif',''),
					(0,561300502,5613005,0,0,20,'计提减值准备',	'LIMIT_PRICE_IMPAIRMENT',		0,0,'',2562,'search.gif',''),
					(0,561300503,5613005,0,0,30,'折旧方式变更',	'LIMIT_DEPRECIATION_TYPECHANGE',0,0,'',2592,'search.gif',''),
					--(0,561300504,5613005,0,0,40,'卡片原值变更','LIMIT_FIXED_CARDSNETVALUECHANGE',0,0,'',4701,'search.gif',''),
				--(0,5613006,56130,0,0,50,'固定资产拆分','LIMIT_FIXED_SPLITASSETSCARDS',0,0,'',4717,'search.gif',''),
				(0,5613007,56130,0,0,60,'固定资产变更查询',	'LIMIT_FIXED_CHANGE_SEARCH',		0,0,'',2548,'search.gif',''),
			(0,56140,561,0,0,40,'固定资产条码打印','LIMIT_FIXED_ENTRYCODE_PRINT',			0,0,'',2942,'search.gif',''),
			(0,56160,561,0,0,60,'固定资产盘点查询','LIMIT_FIXED_INVENTORYBILLSEARCH_QUERY',	0,0,'',2943,'search.gif',''),
			(0,56170,561,0,1,70,'折旧管理','vr',0,0,'',-1,'search.gif',''),
				(0,5617001,56170,0,0,10,'年度折旧计划表查询','LIMIT_FIXED_DEPRECIATIONPLAN_SEARCH',		0,0,'',2551,'search.gif',''),
				(0,5617002,56170,0,0,20,'月度折旧计划表查询','LIMIT_FIXED_DEPRECIATIONPLANMONTH_SEARCH',0,0,'',2594,'search.gif',''),
				(0,5617003,56170,0,0,30,'固定资产折旧',		 'LIMIT_FIXED_DEPRECIATIONBILL',			0,0,'',2540,'search.gif',''),
			(0,56180,561,0,1,80,'报表查询','vr',0,0,'',-1,'search.gif',''),
				(0,561801,56180,0,0,10,'固定资产卡片历史查询','LIMIT_FIXED_HISTORY_SEARCH',0,0,'',2554,'search.gif',''),
			(0,56190,561,0,0,90,'期末结账','LIMIT_FIXED_TERMINAL_SETTLE',0,0,'',2941,'search.gif','')
END;

BEGIN --会员管理相关菜单
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,570,500,0,1,70,'会员卡券管理','limit_menu_vip',0,1,'',-1,'',''),
		(0,57010,570,0,1,10,'会员管理','vr',0,0,'1',-1,'',''),
			(0,5701001,57010,0,0,10, '会员参数设置',      'LIMIT_QP_NIVP_PARAMETERSET',		0,0,'',	1326,'',''),
			(0,5701002,57010,0,0,20, '会员卡积分设置',    'LIMIT_VIPJFSET_MANAGE',			0,0,'',	595,'viewTxt.gif',''),
			(0,5701003,57010,0,0,30, '商品会员信息设置',  'LIMIT_VIPGOODSSIGN_MANAGE',		0,0,'',	594,'viewTxt.gif',''),
			(0,5701004,57010,0,0,40, '会员卡类型管理',    'LIMIT_VIPCARD_TYPE_MANAGE',		0,0,'1',459,'ViewTxt.gif',''),
			(0,5701005,57010,0,0,50, '会员卡类型变更查询','LIMIT_QP_NIVP_CHANGE_TYPE',		0,0,'',	2049,'',''),
			(0,5701006,57010,0,0,60, '会员卡信息管理',    'LIMIT_QP_VIPCARDSET',			0,0,'',	1322,'','CtrlAltV'),
			(0,5701007,57010,0,0,70, '会员期初储值维护',  'LIMIT_INI_STORED',			0,0,'',	4986,'',''),
			(0,5701008,57010,0,0,80, '职员发卡统计',      'LIMIT_EMPLOYEE_DISCARID_SUM',	0,0,'',	2052,'',''),
			(0,5701009,57010,0,0,90, '会员储值充值单',    'LIMIT_QP_VIPCZ_BILL_ADD',		0,0,'1',4477,'',''),
			(0,5701010,57010,0,0,100, '会员批量储值充值单','LIMIT_MEMBERSHIP_BATCHSTOREDBILL',0,0,'',4495,'',''),
			(0,5701011,57010,0,0,110, '会员充值查询',      'LIMIT_QP_VIPCZ_SEARCH',			0,0,'',	1360,'viewTxt.gif',''),
			(0,5701012,57010,0,0,120, '会员业务明细查询',  'LIMIT_QP_NVIP_VIPDETAILQUERY',	0,0,'',	1329,'',''),
			(0,5701013,57010,0,0,130, '会员消费管理',      'LIMIT_VIPCARD_CONSUME_MANAGE',	0,0,'',	462,'viewTxt.gif',''),
			--(0,5701014,57010,0,0,140, '会员充值查询',      'LIMIT_VIP_QUERYCZ',				0,0,'',	635,'viewTxt.gif',''),
			(0,5701015,57010,0,0,150, '积分调整单',        'LIMIT_VIP_JFCL_BILL',			0,0,'',	1345,'',''),	
			(0,5701022,57010,0,0,151, '积分转储值单',      'LIMIT_VIP_JFTOSTORED_BILL',		0,0,'',	4213,'',''),	
			(0,5701016,57010,0,0,160, '积分兑换单',        'LIMIT_QP_CENTCHANGE_BILL',		0,0,'',	1359,'viewTxt.gif',''),
			(0,5701017,57010,0,0,170, '积分兑换查询',      'LIMIT_QP_JFDHCX',				0,0,'',	1361,'',''),
			(0,5701018,57010,0,0,180, '消费调整单',        'LIMIT_VIP_XFTZ_BILL',			0,0,'1',1346,'',''),
			(0,5701019,57010,0,0,190,'会员销售统计',      'LIMIT_NVIP_SALEINFO_SUM',		0,0,'1',2124,'',''),
			(0,5701020,57010,0,0,200,'会员生日提醒',      'LIMIT_NVIP_BIRTHDAY',			0,0,'',	2166,'',''),
			(0,5701021,57010,0,0,210,'会员机构储值消费统计','LIMIT_NVIP_STOREDREPORT',		0,0,'',	4210,'',''),
		(0,57020,570,0,1,20,'优惠券管理','vr',0,0,'',-1,'',''),
			(0,5702001,57020,0,0,10, '优惠券名称','LIMIT_COUPON_TYPEINFO',	0,0,'',	5082,'',''),
			(0,5702002,57020,0,0,20, '优惠券入库','LIMIT_COUPON_INBILL',	0,0,'1',5032,'ViewTxt.gif',''),
			(0,5702003,57020,0,0,30, '优惠券出库','LIMIT_COUPON_OUTBILL',	0,0,'',	5040,'',''),
			(0,5702004,57020,0,0,40, '优惠券调拨','LIMIT_COUPON_ALLOTBILL',0,0,'',	5048,'',''),
			(0,5702005,57020,0,0,50, '优惠券退货','LIMIT_COUPON_BACKBILL',	0,0,'',	5056,'',''),			
			(0,5702011,57020,0,1,51,'优惠券分支机构调拨管理','vr',0,0,'',-1,'',''),	
				(0,570201101,5702011,0,0,10, '优惠券分支机构调拨出库单','LIMIT_COUPON_STYPE_ALLOT_CK_VCHTYPE',	0,0,'',	5198,'ViewTxt.gif',''),
				(0,570201102,5702011,0,0,20, '优惠券分支机构调拨入库单','LIMIT_COUPON_STYPE_ALLOT_RK_VCHTYPE',	0,0,'',	5203,'ViewTxt.gif',''),
				(0,570201103,5702011,0,0,30, '优惠券分支机构调拨发货查询','LIMIT_COUPON_STYPE_ALLOT_CK_QUERY',	0,0,'',	5208,'ViewTxt.gif',''),
				(0,570201104,5702011,0,0,40, '优惠券分支机构调拨收货查询','LIMIT_COUPON_STYPE_ALLOT_RK_QUERY',	0,0,'',	5211,'ViewTxt.gif',''),			
			(0,5702006,57020,0,0,60, '优惠券跟踪','LIMIT_COUPON_TRACKS',	0,0,'1',5064,'ViewTxt.gif',''),
			(0,57020011,57020,0,0,61, '优惠券调拨查询','LIMIT_COUPON_ALLOTBILLS_QUERY',	0,0,'',5100,'',''),
			(0,5702007,57020,0,0,70, '券出库消费明细','LIMIT_COUPON_DETAILS_QUERY',	0,0,'',	5067,'',''),
			(0,5702008,57020,0,0,80, '优惠券消费报表','LIMIT_COUPON_CONSUME_QUERY',	0,0,'',	5070,'',''),
			(0,5702009,57020,0,0,90, '优惠券统计报表','LIMIT_COUPON_STATISTICS_QUERY',0,0,'',5073,'',''),
			(0,5702010,57020,0,0,100, '优惠券单据查询','LIMIT_COUPON_BILL_QUERY',	0,0,'',	5076,'','')

END;

BEGIN --维修管理
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,580,500,0,1,80,'维修管理','limit_menu_repair',0,1,'',-1,'',''),
		(0,11003060,580,0,0,60, '维修故障设置',	'LIMIT_WX_BUG_QUERY',		0,0,'',646,'',''),
		(0,11003070,580,0,0,70, '维修接件单',	'LIMIT_WX_ENGAGE_BILL',		0,0,'',647,'',''),
		(0,11003080,580,0,0,80, '维修单',		'LIMIT_WX_SELF_BILL',		0,0,'',649,'',''),
		(0,11003090,580,0,0,90, '维修取件单',	'LIMIT_WX_GETBACK_BILL',	0,0,'',651,'',''),
		(0,11003100,580,0,0,100,'整机更换单',	'LIMIT_WX_REPLACE_BILL',	0,0,'',653,'',''),
		(0,11003110,580,0,0,110,'送修单',		'LIMIT_WX_SEND_BILL',		0,0,'1',655,'',''),
		(0,11003120,580,0,0,120,'送修返回单',	'LIMIT_WX_SENDBACK_BILL',	0,0,'',657,'',''),
		(0,11003130,580,0,0,130,'报修单',		'LIMIT_WX_CALL_BILL',		0,0,'1',659,'',''),
		(0,11003140,580,0,0,140,'上门维修单',	'LIMIT_WX_GOTO_BILL',		0,0,'',661,'',''),
		(0,11003150,580,0,0,150,'维修品调入单',	'LIMIT_WX_IN_BILL',			0,0,'1',663,'',''),
		(0,11003160,580,0,0,160,'维修品调出单',	'LIMIT_WX_OUT_BILL',		0,0,'',665,'',''),
		(0,11003170,580,0,0,170,'维修品调拨单',	'LIMIT_WX_MOVE_BILL',		0,0,'',667,'',''),
		(0,11003280,580,0,1,280,'维修类报表','vr',0,0,'1',-1,'',''),
			(0,11003180,11003280,0,0,180,'维修库存状况表',		'LIMIT_WX_GOOSSTOCKS_QUERY',	0,0,'',669,'',''),
			(0,11003190,11003280,0,0,190,'维修库存分布表',		'LIMIT_WX_DISTRIBUTING_QUERY',	0,0,'',670,'',''),
			(0,11003200,11003280,0,0,200,'维修品进销存汇总表',	'LIMIT_WX_JXC_QUERY',			0,0,'',671,'',''),
			(0,11003210,11003280,0,0,210,'接件商品查询',		'LIMIT_WX_ENGAGE_QUERY',		0,0,'1',672,'',''),
			(0,11003230,11003280,0,0,230,'商品送修未返回统计',	'LIMIT_WX_SEND_QUERY',			0,0,'1',673,'',''),
			(0,11003240,11003280,0,0,240,'维修业务对账查询',	'LIMIT_WX_ACCOUNT_QUERY',		0,0,'1',674,'',''),
			(0,11003250,11003280,0,0,250,'送修业务对账查询',	'LIMIT_WX_SEND_ACCOUNT_QUERY',	0,0,'',675,'',''),
			(0,11003255,11003280,0,0,220,'报修商品查询',		'LIMIT_WX_BX_QUERY',			0,0,'',677,'','')


END;

BEGIN --单据中心
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,590,500,0,1,110,'单据中心','limit_menu_bill',0,1,'',-1,'',''),
		(0,980,590,0,0,10, '业务草稿',		'LIMIT_VCH_DRAFT',		0,0,'',88,'viewTxt.gif','CtrlAltC'),
		(0,990,590,0,0,20, '经营历程',		'LIMIT_VCH_SEARCH',		0,0,'',89,'viewTxt.gif','CtrlAltJ'),
		(0,1003,590,0,0,30,'经营日报',		'LIMIT_SALE_DAYREPORT',	0,0,'',443,'viewTxt.gif',''),
		(0,1000,590,0,0,40,'单据统计',		'LIMIT_VCH_STAT',		0,0,'',90,'viewTxt.gif',''),
		(0,1001,590,0,1,50,'审核列表',		'LIMIT_VCH_CHECKBILL',	0,1,'1',-1,'viewTxt.gif',''),		
		(0,100101,1001,0,0,01,'我的待审核列表','LIMIT_AUDITING_QUERY',	0,0,'',400,'viewTxt.gif',''),
		(0,100002,1001,0,0,02,'我的已审核列表','LIMIT_BILLCENTER_MYAUDITEDLIST_QUERY',0,0,'0',4518,'viewTxt.gif',''),
		(0,100003,1001,0,0,03,'单据审核列表','LIMIT_BILLCENTER_OWNER_QUERY',0,0,'0',5192,'viewTxt.gif',''),
		(0,100004,1001,0,0,04,'我的知会流程','LIMIT_BILLCENTER_MYKNOWBILL_QUERY',0,0,'0',5195,'viewTxt.gif','')
END;

BEGIN --基础资料
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
		(0,600,500,0,1,120,'基础资料','limit_menu_baseinfo',0,1,'',-1,'',''),
			(0,101020,600,0,1,10,'基本信息','vr',0,0,'',-1,'',''),
				(0,1020,101020,0,0,10,		'商品档案','LIMIT_GOODS_BASE',	0,0,'',92,'product.gif','CtrlB'),		
				(0,10102012,101020,0,0,20,	'商品类别',	'LIMIT_BASE_GOODSTYPE',0,0,'',4786,'product.gif',''),	
				(0,10102036,101020,0,0,21,	'商品品牌',	'LIMIT_BASE_BRANDARCOMMODITY',0,0,'',5026,'product.gif',''),
				(0,10102008,101020,0,0,30,	'商品计量单位',	'LIMIT_PTYPE_UNIT',	0,0,'',2295,'',''),
				(0,10102034,101020,0,0,40,	'商品多单位信息','LIMIT_PTYPE_MULUNITINFO',0,0,'',4692,'',''),
				(0,510340,101020,0,0,50,	'商品多编码设置','LIMIT_PTYPE_MULTICODE',0,0,'',588,'viewTxt.gif',''),
				(0,10102040,101020,0,0,60,	'价格名称设置','LIMIT_PRICENAMESET',0,0,'',2666,'viewTxt.gif',''),
				(0,1030,101020,0,0,70,		'客户档案','LIMIT_CLIENT_BASE',0,0,'1',93,'base04.gif','CtrlQ'),
				(0,1040,101020,0,0,80,		'供货商档案','LIMIT_SUPPLY_BASE',0,0,'',94,'base04.gif',''),
				--(0,1041,101020,0,0,90,		'往来单位计量单位跟踪',	'LIMIT_BTYPE_UNIT',	0,0,'',4726,'base04.gif',''),
				(0,101002,101020,0,0,100,	'信用额度管理',	'LIMIT_CREDIT_MANAGE',0,0,'',712,'base04.gif',''),
				(0,10102026,101020,0,0,101,	'品牌信用额度管理',	'LIMIT_BRANDARCREDIT_MANAGE',0,0,'',5149,'base04.gif',''),
				(0,101001,101020,0,0,110,	'分支机构档案','LIMIT_STYPE_BASE',0,0,'',690,'base04.gif',''),
				(0,1072,101020,0,0,120,		'地区档案','LIMIT_AREA_BASE',0,0,'',518,'base04.gif','CtrlR'),
				(0,1236,101020,0,0,130,		'部门档案','LIMIT_DEPARTMENT_BASE',0,0,'1',487,'base04.gif','CtrlI'),
				(0,1050,101020,0,0,140,		'职员档案','LIMIT_EMPLOYEE_BASE',0,0,'',95,'base04.gif','CtrlE'),
				(0,1051,101020,0,0,150,		'角色管理','LIMIT_EMPLOYEE_GROUP_MANAGE',0,0,'',2115,'base04.gif',''),								
				(0,1070,101020,0,0,180,		'存货仓库','LIMIT_STOCK_BASE',0,0,'1',97,'stock.gif','CtrlK'),
				(0,10102007,101020,0,0,190,	'货位档案','LIMIT_DEPOSITORY_BASE',0,0,'',2280,'stock.gif',''),
				(0,10102011,101020,0,0,200,	'存货类型','LIMIT_BASE_INVENTORYTYPE',0,0,'',4720,'stock.gif',''),
				--(0,10102035,101020,0,0,201,	'销售类型','LIMIT_BASE_SALETYPE',0,0,'',5003,'base04.gif',''),
				(0,10102003,101020,0,0,210,	'币    种',		'LIMIT_CURRENCY_BASE',					0,0,'',2188,'',''),
				(0,10102009,101020,0,1,240,	'项目管理',	'vr',0,0,'',-1,'base04.gif',''),
					(0,1010200901,10102009,0,0,10,'资金类',	'LIMIT_BANK_BASE',0,0,'1',96,'base05.gif','CtrlY'),
					(0,1010200902,10102009,0,0,20,'其他收入','LIMIT_INCOME_BASE',0,0,'',129,'base05.gif','CtrlU'),
					(0,1010200903,10102009,0,0,30,'费用类型','LIMIT_EXPENSE_BASE',0,0,'',130,'base05.gif','CtrlF'),
					(0,1010200904,10102009,0,0,40,'固定资产','LIMIT_FIXED_BASE',0,0,'',191,'base_stock.gif','CtrlG'),
					(0,1010200905,10102009,0,0,50,'资产项','LIMIT_FIXED_ZC',0,0,'',2344,'base_stock.gif',''),
					(0,1010200906,10102009,0,0,60,'负债项','LIMIT_FIXED_FZ',0,0,'',2345,'base_stock.gif',''),
					(0,1010200907,10102009,0,0,70,'所有项目','LIMIT_ITEMS_SUMMARY',0,0,'',2438,'stock.gif',''),
				(0,1230,101020,0,0,220,		'公司信息',	'LIMIT_CO_INFO',0,0,'1',108,'base04.gif',''),				
				--(0,1238,101020,0,0,320,		'商品货位档案',		'LIMIT_QP_CARGOSPACESET',				0,0,'1',1302,'',''), --汽配菜单
				(0,1274,101020,0,0,330,		'常用摘要',			'LIMIT_COMMON_EXPANDCOM_COM',			0,0,'1',1370,'',''),
				(0,1275,101020,0,0,340,		'常用说明',			'LIMIT_COMMON_EXPANDCOM_EXP',			0,0,'',1371,'',''),
				(0,1276,101020,0,0,350,		'常用承运单位',		'LIMIT_COMMON_EXPANDCOM_CARRIAGE',		0,0,'',4647,'',''),
				(0,1277,101020,0,0,360,		'快递公司管理',		'LIMIT_EXPRESS_MANAGE',		0,0,'',4228,'',''),
			
			--(0,101041,600,0,1,11,'基本信息覆盖导入','vr',0,0,'',-1,'',''),
			--	(0,10104101,101041,0,0,10,	'商品档案覆盖导入','LIMIT_PTYPECOVER_QUERY',0,0,'',5281,'product.gif',''),		
			--	(0,10104102,101041,0,0,20,	'客户档案覆盖导入',	'LIMIT_BTYPEKCOVER_QUERY',0,0,'',5285,'product.gif',''),	
			--	(0,10104103,101041,0,0,30,	'供货商档案覆盖导入','LIMIT_BTYPEGCOVER_QUERY',0,0,'',5289,'product.gif',''),
			
			
			(0,110010,600,0,1,30,'数据搬移','vr',0,0,'',-1,'',''),
				(0,11001005,110010,0,0,40, '分支机构档案',		'LIMIT_STYPE_MOVE',					0,0,'',711,'base04.gif',''),
				(0,11001010,110010,0,0,10, '商品档案',			'LIMIT_NORMAL_OPERATOR_PTYPE_MOVE',				0,0,'',5166,'',''),
				(0,11001020,110010,0,0,20, '客户档案',			'LIMIT_NORMAL_OPERATOR_KH_MOVE',			0,0,'1',5167,'',''),
				(0,11001030,110010,0,0,30, '供货商档案',		'LIMIT_NORMAL_OPERATOR_GHS_MOVE',			0,0,'',5168,'',''),
				(0,11001040,110010,0,0,70, '职员档案',			'LIMIT_NORMAL_OPERATOR_EMPLOYEE_MOVE',				0,0,'',5171,'',''),
				(0,11001050,110010,0,0,80, '存货仓库',			'LIMIT_NORMAL_OPERATOR_CHCK_MOVE',				0,0,'1',5172,'',''),
				(0,11001051,110010,0,0,81, '现金账户',			'LIMIT_NORMAL_OPERATOR_XJZH_MOVE',				0,0,'1',5173,'',''),
				(0,11001060,110010,0,0,90, '资金类',			'LIMIT_NORMAL_OPERATOR_ZJL_MOVE',				0,0,'0',5174,'',''),
				(0,11001070,110010,0,0,100,'其他收入',			'LIMIT_NORMAL_OPERATOR_QTSR_MOVE',			0,0,'',5175,'',''),
				(0,11001080,110010,0,0,110,'费用类型',			'LIMIT_NORMAL_OPERATOR_FYLX_MOVE',			0,0,'',5176,'',''),
				(0,11001090,110010,0,0,120,'固定资产',			'LIMIT_NORMAL_OPERATOR_GDZC_MOVE',				0,0,'',5177,'',''),
				(0,11001100,110010,0,0,50, '地区档案',			'LIMIT_NORMAL_OPERATOR_AREA_MOVE',				0,0,'',5169,'',''),
				(0,11001110,110010,0,0,60, '部门档案',			'LIMIT_NORMAL_OPERATOR_DTYPE_MOVE',		0,0,'1',5170,'',''),				
			(0,5010,600,0,1,40,'业务期初','vr',0,1,'1',-1,'',''),
				(0,1110,5010,0,0,10,	'账面库存期初',		'LIMIT_INI_GOODS',					0,0,'',99,'_txt.gif',''),
				(0,1111,5010,0,0,10,	'实物库存期初',		'LIMIT_INI_ENTITYGOODS',			0,0,'',4825,'_txt.gif',''),
				(0,1120,5010,0,0,20,	'应收期初查询',		'LIMIT_INI_AR',						0,0,'1',100,'_txt.gif',''),
				(0,501014,5010,0,0,89,	'优惠券期初',		'LIMIT_INI_COUPON',					0,0,'1',5079,'_txt.gif',''),
				(0,1133,5010,0,0,90,	'固定资产期初',		'LIMIT_INI_FIXED',					0,0,'1',198,'_txt.gif',''),
				(0,1136,5010,0,0,100,	'其他业务期初',		'LIMIT_INI_EXPENSE_ALLOCATE',		0,0,'',199,'_txt.gif',''),
				(0,1140,5010,0,0,110,	'现金银行期初',		'LIMIT_INI_BANK',					0,0,'',102,'_txt.gif',''),
				(0,1320,5010,0,0,70,	'借欠期初',			'LIMIT_LENDSTAR',					0,0,'1',146,'_txt.gif',''),
				(0,65501,5010,0,0,50,	'委托库存期初',		'LIMIT_COMMISSION_STOCK_WT_START',	0,0,'1',229,'_txt.gif',''),
				(0,65503,5010,0,0,60,	'受托库存期初',		'LIMIT_COMMISSION_STOCK_ST_START',	0,0,'',231,'_txt.gif',''),
				(0,65588,5010,0,0,130,	'期初资产负债表',	'LIMIT_INI_ACCOUNT_REPORT',			0,0,'',538,'_txt.gif',''),				
				(0,501030,5010,0,0,30,	'应付期初查询',		'LIMIT_INI_AP',						0,0,'',101,'_txt.gif',''),
				(0,501040,5010,0,0,40,	'内部应收期初',		'LIMIT_INI_INNERAR',				0,0,'',2457,'_txt.gif',''),
				(0,11003260,5010,0,0,80,'维修品库存期初',	'LIMIT_WX_INI_GOODSSTOCKS_QUERY',	0,0,'',676,'',''),
			(0,101030,600,0,1,41,'期初单据','vr',0,1,'',-1,'',''),
				(0,10103010,101030,0,1,10,'销售管理','vr',0,1,'',-1,'',''),
					(0,1010301010,10103010,0,0,10,'期初未结算销售出库单',	 'LIMIT_INI_NOSETTLE_SALEBILL',			0,0,'',-1,'',''),
					(0,1010301020,10103010,0,0,20,'期初未结算销售退货单',	 'LIMIT_INI_NOSETTLE_SALEBACKBILL',		0,0,'',-1,'',''),
					(0,1010301030,10103010,0,0,30,'期初未结算销售换货单',	 'LIMIT_INI_NOSETTLE_SALEEXCHANGEBILL',	0,0,'',-1,'',''),
					(0,1010301040,10103010,0,0,40,'期初未结算委托代销结算单','LIMIT_INI_NOSETTLE_WTGATHERBILL',		0,0,'',-1,'',''),
					(0,1010301050,10103010,0,0,50,'期初未开票发出商品出库单','LIMIT_INI_SENDPTYPE_BILL',		0,0,'',-1,'',''),
					(0,1010301060,10103010,0,0,60,'期初未开票发出商品退货单','LIMIT_INI_SENDPTYPE_BACKBILL',		0,0,'',-1,'',''),
					(0,1010301070,10103010,0,0,70,'期初未结算组合品销售出库单','LIMIT_INI_NOSETTLE_OUTORDERBILL',		0,0,'',-1,'',''),
					(0,1010301080,10103010,0,0,80,'期初未结算组合品销售退货单','LIMIT_INI_NOSETTLE_RETURNORDERBILL',	0,0,'',-1,'',''),
				(0,10103020,101030,0,1,20,'采购管理','vr',0,1,'',-1,'',''),
					(0,1010302010,10103020,0,0,10,'期初未结算采购入库单',	'LIMIT_INI_NOSETTLE_BUYBILL',			0,0,'',-1,'',''),
					(0,1010302020,10103020,0,0,20,'期初未结算采购退货单',	'LIMIT_INI_NOSETTLE_BUYBACKBILL',		0,0,'',-1,'',''),
					(0,1010302030,10103020,0,0,30,'期初未结算采购换货单',	'LIMIT_INI_NOSETTLE_BUYEXHANGECBILL',	0,0,'',-1,'',''),
					(0,1010302040,10103020,0,0,40,'期初未结算受托代销结算单','LIMIT_INI_NOSETTLE_STGATHERBILL',		0,0,'',-1,'',''),
					(0,1010302050,10103020,0,0,50,'期初未开票暂估入库单','LIMIT_INI_TEMPES_BILL',		0,0,'',-1,'',''),
					(0,1010302060,10103020,0,0,60,'期初未开票暂估退货单','LIMIT_INI_TEMPES_BACKBILL',		0,0,'',-1,'',''),
				--(0,10103060,101030,0,1,30,'仓储管理','vr',0,1,'',-1,'',''),
				--	(0,1010306010,10103060,0,0,10,'期初未实物入库单',	'LIMIT_INI_ENTITYPUTINSTORAGE',	0,0,'',-1,'',''),
				--	(0,1010306020,10103060,0,0,20,'期初未实物出库单',	'LIMIT_INI_ENTITYSTOCKOUT',	0,0,'',-1,'',''),					
				(0,10103030,101030,0,1,40,'维修管理','vr',0,1,'',-1,'',''),
					(0,1010303010,10103030,0,0,10,'期初维修取件单','LIMIT_INI_REPAIRGETBACKBILL',	0,0,'',-1,'',''),
					(0,1010303020,10103030,0,0,20,'期初整机更换单','LIMIT_INI_REPAIRCHANGEBILL',	0,0,'',-1,'',''),
					(0,1010303030,10103030,0,0,30,'期初送修返回单','LIMIT_INI_REPAIRSENDBACKBILL',	0,0,'',-1,'',''),
					(0,1010303040,10103030,0,0,40,'期初上门维修单','LIMIT_INI_REPAIRGOTOBILL',		0,0,'',-1,'',''),
				(0,10103040,101030,0,1,50,'往来管理','vr',0,1,'',-1,'',''),
					(0,1010304010,10103040,0,0,10,'期初应收增加单','LIMIT_INI_GATHERADDBILL',		0,0,'',-1,'',''),
					(0,1010304020,10103040,0,0,20,'期初应收减少单','LIMIT_INI_GATHERREDUCEBILL',	0,0,'',-1,'',''),
					(0,1010304030,10103040,0,0,30,'期初应付增加单','LIMIT_INI_PAYADDBILL',			0,0,'',-1,'',''),
					(0,1010304040,10103040,0,0,40,'期初应付减少单','LIMIT_INI_PAYREDUCEBILL',		0,0,'',-1,'',''),
					(0,1010304050,10103040,0,0,50,'期初预收单',		'LIMIT_INI_PRESETTLEBILL',		0,0,'',-1,'',''),
					(0,1010304060,10103040,0,0,60,'期初预付单',		'LIMIT_INI_PRESETTLEPAYBILL',	0,0,'',-1,'',''),
					(0,1010304070,10103040,0,0,70,'期初返利执行单','LIMIT_INI_ADVANTAGEBILL',		0,0,'',-1,'',''),
					(0,1010304080,10103040,0,0,80,'期初价保执行单','LIMIT_INI_PRICEPROTECTBILL',	0,0,'',-1,'',''),
					(0,1010304090,10103040,0,0,90,'期初获利执行单','LIMIT_INI_ADVANTAGEGETBILL',	0,0,'',-1,'',''),
					(0,1010304091,10103040,0,0,91,'期初获得价保单','LIMIT_INI_PRICEPROTECTGETBILL',	0,0,'',-1,'',''),
					(0,1010304092,10103040,0,0,92,'期初未结算采购暂估开票','LIMIT_INI_BUYINVOICEBILL',	0,0,'',-1,'',''),
					(0,1010304093,10103040,0,0,93,'期初未结算销售发货开票','LIMIT_INI_SALEINVOICEBILL',	0,0,'',-1,'',''),
				(0,10103050,101030,0,1,60,'成本费用管理','vr',0,1,'',-1,'',''),
					(0,1010305010,10103050,0,0,10,'期初费用单',			'LIMIT_INI_EXPENSEBILL',	0,0,'',-1,'',''),
					(0,1010305020,10103050,0,0,20,'期初其他收入单',		'LIMIT_INI_INCOMEBILL',		0,0,'',-1,'',''),
					(0,1010305030,10103050,0,0,30,'期初固定资产购买',	'LIMIT_INI_FIXEDBUYBILL',	0,0,'',-1,'',''),
					(0,1010305040,10103050,0,0,40,'期初固定资产变卖',	'LIMIT_INI_FIXEDSALEBILL',	0,0,'',-1,'',''),
				(0,10103070,101030,0,0,70,'期初单据查询','LIMIT_INI_BILLSEARCH',0,0,'1',2360,'_txt.gif',''),
				--(0,10103080,101030,0,1,80,'期初未完成仓储运输单据','vr',0,1,'',-1,'',''),
				--	(0,1010308001,10103080,0,0,10,'期初未完成入库单',	'LIMIT_INI_NOTCOMPLETESTORAGEBILL',	0,0,'',-1,'',''),
				--	(0,1010308002,10103080,0,0,20,'期初未完成出库单',	'LIMIT_INI_NOTCOMPLETEBACKSTORAGEBILL',	0,0,'',-1,'',''),
				(0,101040,600,0,0,42,	'账务期初',			'LIMIT_INI_ZWINI',					0,0,'1',546,'_txt.gif','')

END;

BEGIN --系统管理
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,610,500,0,1,130,'系统管理','limit_menu_system',0,1,'',-1,'',''),
		(0,61001,610,0,1,10,'系统期间设置','vr',0,0,'',-1,'',''),
			(0,6100101,61001,0,0,10,'会计期间维护','LIMIT_FPERIODSET',0,0,'',4793,'',''),
			(0,6100102,61001,0,0,20,'启用期间设置','LIMIT_FPERIODSTARTSET',0,0,'',4794,'',''),
		(0,110070,610,0,1,20,'系统启用','vr',0,0,'',-1,'',''),
			(0,1196,110070,0,0,10,'开账向导',		'GUIDE',		0,0,'',-1,'viewTxt.gif',''),
			(0,1190,110070,0,0,20,'系统配置',		'LIMIT_USERCONFIGE',				0,0,'',121,'sys_00.gif',''),
			(0,1150,110070,0,0,30,'系统开账',		'LIMIT_START',	0,0,'',103,'sys_01.gif',''),
			(0,1100703,110070,0,0,40,'系统反开账',	'LIMIT_RESTART',0,0,'',2454,'sys_01.gif',''),
			(0,1200,110070,0,0,50,'系统重建',		'LIMIT_RESET',						0,0,'',107,'sys_00.gif',''),
		(0,110080,610,0,1,30,'数据导入','vr',0,0,'',-1,'',''),						
			(0,1210,110080,0,0,30,'预置数据导入',	'LIMIT_SYSTEMSET_PREDATAINEXPORT',	0,0,'',2567,'sys_00.gif',''),
			(0,61071,110080,0,0,40,'数据导入平台',	'LIMIT_SYSMENU_DATAINOUT',		0,0,'',4414,'_txt.gif',''),
		(0,110090,610,0,1,40,'安全设置','vr',0,0,'',-1,'',''),
			(0,110060,110090,0,0,10,'安全钥匙管理',	'LIMIT_DOUBLE_REASON',	0,0,'',-1,'_txt.gif',''),
			(0,1180,110090,0,0,30,'操作员权限',		'LIMIT_LIMIT',			0,0,'1',106,'lock.gif',''),
			(0,1360,110090,0,0,40,'操作日志',		'LIMIT_EVENTLOG',		0,0,'',162,'viewTxt.gif',''),
			(0,1221,110090,0,0,50,'操作员登录率',	'LIMIT_LOGNUM',			0,0,'',165,'viewTxt.gif',''),	
			(0,1222,110090,0,0,60,'修改密码',	'LIMIT_MODIFY_OPERATOR_PASSWORD',0,0,'',4685,'_txt.gif',''),
		(0,1100100,610,0,1,50,'单据设置','vr',0,0,'',-1,'',''),
			(0,1185,1100100,0,0,10,'单据审核设置',	'LIMIT_AUDITING_SET',	0,0,'',401,'viewTxt.gif',''),
			(0,1188,1100100,0,0,20,'单据编号设置',	'LIMIT_BillCode_Config',0,0,'',481,'sys_01.gif',''),
			--(0,1188,1100100,0,0,30,'单据格式设置',	'LIMIT_BILL_GS_SET',0,0,'',5146,'sys_01.gif',''),			
			(0,1189,1100100,0,0,40,'单据自定义设置',	'LIMIT_BILL_CUSTOMSETTINGS',0,0,'',4684,'sys_01.gif',''),
		(0,1100110,610,0,1,60,'结    存','vr',0,0,'',-1,'',''),
			(0,1160,1100110,0,0,10,'月结存','LIMIT_MONTH_CLOSE',0,0,'',104,'sysimg.gif','CtrlM'),
			(0,1170,1100110,0,0,20,'年结存','LIMIT_YEAR_CLOSE',	0,0,'',105,'sysimg.gif',''),
		(0,1100120,610,0,1,70,'检测中心','vr',0,0,'',-1,'',''),
			(0,11001201,1100120,0,1,10,'基本信息检测','vr',0,0,'',-1,'',''),
				(0,1100120110,11001201,0,0,10,'会计科目检查',			'LIMIT_CHECK_ACACCOUNT',			0,0,'',2460,'',''),
				(0,1100120120,11001201,0,0,20,'商品使用情况检查',		'LIMIT_SYSTEM_PTYPEUSER_CHECK',		0,0,'',4484,'',''),
				(0,1100120130,11001201,0,0,30,'职员使用情况检查',		'LIMIT_SYSTEM_ETYPEUSER_CHECK',		0,0,'',4485,'',''),
				(0,1100120140,11001201,0,0,40,'往来单位使用情况检查',	'LIMIT_SYSTEM_BTYPEUSER_CHECK',		0,0,'',4486,'',''),
				(0,1100120150,11001201,0,0,50,'分支机构使用情况检查',	'LIMIT_SYSTEM_STYPEUSER_CHECK',		0,0,'',4487,'',''),
				(0,1100120160,11001201,0,0,60,'地区使用情况检查',		'LIMIT_SYSTEM_AREATYPEUSER_CHECK',	0,0,'',4488,'',''),
				(0,1100120170,11001201,0,0,70,'仓库使用情况检查',		'LIMIT_SYSTEM_STOCKUSER_CHECK',		0,0,'',4489,'',''),
				(0,1100120180,11001201,0,0,80,'部门使用情况检查',		'LIMIT_SYSTEM_DTYPEUSER_CHECK',		0,0,'',4490,'',''),
			(0,11001202,1100120,0,0,20,'单据合法性检查',		'LIMIT_SYSTEM_BILLVALIDITYCHECK',	0,0,'',2647,'',''),
			(0,11001203,1100120,0,1,30,'批量删除基础资料','vr',0,0,'',-1,'',''),
				(0,1100120310,11001203,0,0,10,'批量删除商品档案',		'LIMIT_SYSMENU_BATCHDELPTYPE',		0,0,'',4524,'',''),
				(0,1100120320,11001203,0,0,20,'批量删除往来单位资料',	'LIMIT_SYSMENU_BATCHDELBTYPE',		0,0,'',4525,'',''),
		(0,1100130,610,0,1,80,'支付设置','vr',0,0,'',-1,'',''),
			(0,11001301,1100130,0,0,10,'支付宝结算设置','LIMIT_ALIPAYSET',0,0,'',4258,'',''),
			(0,11001302,1100130,0,0,20,'微信结算设置','LIMIT_WECHATPAYMENTSETUP',0,0,'',4259,'',''),
			(0,11001303,1100130,0,0,30,'易支付结算设置','LIMIT_ALLINPAYSET',0,0,'',5135,'',''),
		(0,610100,610,0,1,90,'短信平台配置',	'LIMIT_SMS_MANAGER',			0,0,'',-1,'_txt.gif',''),
		   (0,610101,610100,0,0,1010,'短信账户绑定',	'LIMIT_SMSCONFIG',			0,0,'',4890,'_txt.gif',''),
		   (0,610102,610100,0,0,1020,'短信模板设置',	'LIMIT_SMSTEMPLATE',			0,0,'',4891,'_txt.gif',''),
		   (0,610103,610100,0,0,1030,'自动发送设置',	'LIMIT_SMSAUTOSEND',			0,0,'',4892,'_txt.gif',''),
		   (0,610107,610100,0,0,1031,'会员短信模板设置','LIMIT_VIPSMSTEMPLATE',			0,0,'',5016,'_txt.gif',''),
		   (0,610104,610100,0,0,1040,'短信发送记录查询','LIMIT_SMSSENDREPORT',			0,0,'',4893,'_txt.gif',''),	
		(0,61070,610,0,0,100,'业务日期冻结',	'LIMIT_FROZEBUSINESS',			0,0,'',2585,'_txt.gif',''),		
		(0,61072,610,0,0,110,'账套设置',	'LIMIT_SYSTEM_SETACCOUNTACTIVATED',		0,0,'',4666,'_txt.gif',''),
		(0,5104,610,0,0,120,'报警簿',		'LIMIT_SYSTEM_AUTO_ALERM_MENU',	0,1,'',517,'search.gif',''),
		--(0,510160,610,0,0,130,'系统公告',	'LIMIT_SYSTEM_PUBLICANNOUNCEMENT',	0,1,'',4989,'search.gif',''),
		(0,11009010,610,0,0,140,'本机信息',	'LIMIT_LOCALMATHINE',			0,0,'',739,'_txt.gif',''),		
		(0,1240,610,0,0,150,'版本信息',		'LIMIT_ABOUT',					1,1,'',111,'_version.gif','')		
END;

BEGIN --决策支持
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,620,500,0,1,140,'决策支持','limit_menu_mgr',0,1,'',-1,'',''),
		(0,15004,620,0,0,10,'老板一张表','LIMIT_QP_BOSSLIST',0,0,'',1334,'',''),
		(0,15005,620,0,0,20,'销售经营情况日统计','LIMIT_SALEINFO_DAYFX',0,0,'1',1351,'',''),
		(0,15006,620,0,0,30,'销售经营情况月统计','LIMIT_SALEINFO_MONTHFX',0,0,'',1352,'',''),
		(0,15001,620,0,0,40,'营业日报表','LIMIT_QP_YYDAYREPORT',0,0,'1',1330,'',''),
		(0,15002,620,0,0,50,'营业月报表','LIMIT_QP_YYMONTHREPORT',0,0,'',1331,'',''),
		(0,15003,620,0,0,60,'营业任意时间段报表','LIMIT_QP_YYYEARREPORT',0,0,'',1332,'',''),
		(0,15007,620,0,1,70,'跨账套查询','vr',0,0,'0','-1','',''),
			(0,1500710,15007,0,0,10,'查询方案配置','LIMIT_CROSSACCOUNT_QUERYSET_QUERY',0,0,'0','4426','',''),
			(0,1500720,15007,0,1,20,'采购管理','vr',0,0,'0','-1','',''),
				(0,150072010,1500720,0,0,10,'跨账套商品采购统计','LIMIT_CROSSACCOUNT_PTYPEBUYCOUNT_QUERY',0,0,'0','4427','',''),
				(0,150072020,1500720,0,0,20,'跨账套供货商采购统计','LIMIT_CROSSACCOUNT_BTYPEBUYCOUNT_QUERY',0,0,'0','4430','',''),
			(0,1500740,15007,0,1,40,'销售管理','vr',0,0,'0','-1','',''),
				(0,150074010,1500740,0,0,10,'跨账套商品销售统计','LIMIT_CROSSACCOUNT_PTYPESALECOUNT_QUERY',0,0,'0','4436','',''),
				(0,150074020,1500740,0,0,20,'跨账套客户销售统计','LIMIT_CROSSACCOUNT_BTYPESALECOUNT_QUERY',0,0,'0','4439','',''),
			(0,1500750,15007,0,1,50,'总账管理','vr',0,0,'0','-1','',''),
				(0,150075010,1500750,0,0,10,'跨账套科目余额表','LIMIT_CROSSACCOUNT_ACCOUNTBALANCE_QUERY',0,0,'0','4442','','')
END;

BEGIN --更多应用
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	VALUES
	(0,1700,500,0,1,150,'更多应用','limit_menu_crm',0,1,'',-1,'',''),
	(0,1215,1700,0,1,10,'CRM 管理','vr',0,1,'',-1,'',''),
		(0,1216,1215,0,0,10,'日程管理','LIMIT_CRM_DATE_MANAGE',0,0,'',553,'search.gif',''),
		(0,1217,1215,0,0,20,'客户管理','LIMIT_CRM_CLIENT_MANAGE',0,0,'',554,'search.gif',''),
		(0,1218,1215,0,0,30,'联系人管理','LIMIT_CRM_LINKMAN_MANAGE',0,0,'',555,'search.gif',''),
	(0,170001,1700,0,1,20,'OA 管理','vr',0,1,'',-1,'',''),
		(0,17000101,170001,0,0,10,'个人桌面','LIMIT_OA_PERSONDESKTOP',0,1,'',2055,'',''),
		(0,17000102,170001,0,0,20,'公司桌面','LIMIT_OA_COMPANYDESKTOP',0,1,'',2056,'',''),
		(0,17000103,170001,0,0,30,'个人邮箱','LIMIT_OA_PERSONMAIL',0,1,'',2057,'',''),
		(0,17000104,170001,0,0,40,'栏目管理','LIMIT_OA_COLUMN_MANAGE',0,1,'',118,'',''),
	(0,170002,1700,0,1,30,'考勤管理','vr',0,1,'',-1,'',''),
		(0,17000201,170002,0,0,10,'考勤规则设置','LIMIT_TIMEWORK_SET',0,1,'',2058,'',''),
		(0,17000202,170002,0,0,20,'节假日信息','LIMIT_TIMEWORK_HOLODY_SET',0,1,'',2059,'',''),
		(0,17000203,170002,0,0,30,'考勤登录信息绑定设置','LIMIT_TIMEWORK_DATABIND_SET',0,1,'',2060,'',''),
		(0,17000204,170002,0,0,40,'考勤数据清理','LIMIT_TIMEWORK_DATACLEAR',0,1,'',2061,'',''),
		(0,17000205,170002,0,0,50,'考勤数据汇总','LIMIT_TIMEWORK_DATASUM',0,1,'',2065,'',''),
		(0,17000206,170002,0,0,60,'缺勤处理查询','LIMT_TIMEWORK_LEVEALDATA',0,1,'',2071,'',''),
	(0,170003,1700,0,1,40,'车辆管理','vr',0,1,'',-1,'',''),
		(0,17000301,170003,0,0,10,'使用登记单','LIMIT_AUTO_USEBILL',0,1,'',2074,'',''),
		(0,17000302,170003,0,0,20,'车辆费用单','LIMIT_AUTO_EXPENSE_BILL',0,1,'',2078,'',''),
		(0,17000303,170003,0,0,30,'车辆信息','LIMIT_AUTO_CARINFO',0,1,'',2082,'',''),
		(0,17000304,170003,0,0,40,'车辆费用类型','LIMIT_AUTO_CAREXPENSE_TYPE',0,1,'',2088,'',''),
		(0,17000305,170003,0,0,50,'车辆使用情况','LIMIT_AUTO_USE_INFO',0,1,'',2094,'',''),
		(0,17000306,170003,0,0,60,'车辆费用信息','LIMIT_AUTO_EXPENSE_INFO',0,1,'',2097,'',''),
	(0,170011,1700,0,1,50,'云WMS','vr',0,1,'',-1,'',''),
		(0,17001101,170011,0,0,10,'云WMS账户绑定','LIMIT_WMS_USERINFOSET',0,1,'',5110,'search.gif',''),
		(0,17001102,170011,0,0,20,'选项配置','LIMIT_WMS_CONFIGSET',0,1,'',5111,'search.gif',''),
		(0,17001103,170011,0,0,30,'云WMS登录','LIMIT_WMS_LOGIN',0,1,'',5112,'search.gif',''),
		(0,17001104,170011,0,1,40,'资料对照设置','vr',0,1,'',-1,'',''),
			(0,1700110401,17001104,0,0,10,'商品SKU设置','LIMIT_WMS_PTYPESET',0,1,'',5113,'search.gif',''),
			(0,1700110402,17001104,0,0,20,'仓库信息设置','LIMIT_WMS_STOCKSET',0,1,'',5114,'search.gif',''),
			(0,1700110403,17001104,0,0,30,'往来单位信息设置','LIMIT_WMS_CONSUMERSET',0,1,'',5115,'search.gif',''),
			--(0,1700110404,17001104,0,0,40,'供货商信息设置','LIMIT_WMS_SUPPLIERSET',0,1,'',5116,'search.gif',''),
			(0,1700110405,17001104,0,0,50,'职员信息设置','LIMIT_WMS_EMPLOYEESET',0,1,'',5117,'search.gif',''),
			(0,1700110406,17001104,0,0,60,'项目信息设置','LIMIT_WMS_ITEMSSET',0,1,'',5118,'search.gif',''),
		(0,17001105,170011,0,1,50,'基本信息同步','vr',0,1,'',-1,'',''),
			(0,1700110401,17001105,0,0,10,'商品信息同步','LIMIT_WMS_PTYPESYN',0,1,'',5119,'search.gif',''),
			(0,1700110405,17001105,0,0,20,'仓库信息同步','LIMIT_WMS_STOCKSYN',0,1,'',5120,'search.gif',''),
			(0,1700110402,17001105,0,0,30,'客户信息同步','LIMIT_WMS_CONSUMERSYN',0,1,'',5121,'search.gif',''),
			(0,1700110403,17001105,0,0,40,'供货商信息同步','LIMIT_WMS_SUPPLIERSYN',0,1,'',5122,'search.gif',''),
			(0,1700110404,17001105,0,0,50,'职员信息同步','LIMIT_WMS_EMPLOYEESYN',0,1,'',5123,'search.gif',''),
			--(0,1700110406,17001105,0,0,60,'账户信息同步','LIMIT_WMS_ACCOUNTSYN',0,1,'',5124,'search.gif',''),
		(0,17001106,170011,0,1,60,'单据同步','vr',0,0,'',-1,'',''),
			(0,1700110601,17001106,0,0,10,'单据上传','LIMIT_WMS_BILLUPSYN',0,1,'',5125,'search.gif',''),
			(0,1700110602,17001106,0,0,20,'单据下载','LIMIT_WMS_BILLDOWNSYN',0,1,'',5126,'search.gif',''),	
	--(0,170012,1700,0,1,60,'易聚客解决方案管理','vr',0,1,'',-1,'',''),
	--	(0,170012001,170012,0,0,10,'易聚客解决方案配置','LIMIT_YJK_CONFIG',0,0,'',5322,'',''),
	--	(0,170012002,170012,0,0,20,'易聚客商品销售明细表','LIMIT_YJK_PTYPE_SALE_DETAIL',0,0,'',5323,'',''),
	(0,170005,1700,0,0,70,'批量打印快递单','LIMIT_MOREAPP_BATCHPRINTEXPRESSBILL',0,1,'',4388,'',''),
	(0,1800,1700,0,1,80,'分销订货','vr',0,1,'',-1,'',''),
		(0,180001,1800,0,0,10,'平台账号管理','LIMIT_YAPI_ACCOUNT_MANAGE',0,0,'',3920,'',''),
		(0,180010,1800,0,1,20,'我是供货商（卖家）','vr',0,1,'',-1,'',''),
			(0,18001001,180010,0,0,10,'管理分销后台','LIMIT_YAPI_BACKGROUND_MANAGE',0,1,'',3901,'',''),
			(0,18001002,180010,0,0,20,'上传分支机构','LIMIT_YAPI_UPLOADSTYPE',0,1,'',3913,'',''),
			(0,18001003,180010,0,0,30,'发布商品','LIMIT_YAPI_PTYPE_UPLOAD',0,1,'',3902,'',''),
			(0,18001004,180010,0,0,40,'订货商管理','LIMIT_YAPI_BUYER_MANAGE',0,1,'',3903,'',''),
			(0,18001005,180010,0,0,50,'销售订单管理','LIMIT_YAPI_SALEORDERBILL_MANAGE',0,1,'',3904,'',''),
			(0,18001006,180010,0,0,60,'销售退货申请管理','LIMIT_YAPI_SALEBACKAPPLY_MANAGE',0,1,'',3914,'',''),
		(0,180020,1800,0,1,30,'我是订货商（买家）','vr',0,1,'',-1,'',''),
			(0,18002002,180020,0,0,10,'我要订货','LIMIT_YAPI_BUY',0,1,'',3908,'',''),
			(0,18002001,180020,0,0,20,'供货商对应关系管理','LIMIT_YAPI_SUPPLIER_MANAGE',0,1,'',3907,'',''),
			(0,18002003,180020,0,0,30,'商品对应关系管理','LIMIT_YAPI_PTYPE_MANAGE',0,1,'',3909,'',''),
			(0,18002004,180020,0,0,40,'进货单管理','LIMIT_YAPI_BUYORDERBILL_MANAGE',0,1,'',3910,'',''),
			(0,18002005,180020,0,0,50,'进货退货申请管理','LIMIT_YAPI_BUYBACKAPPLY_MANAGE',0,1,'',3917,'',''),					
	--(0,170004,1700,0,1,50,'店账通','vr',0,1,'',-1,'',''),
	--	(0,17000410,170004,0,0,10,'新手导航','LIMIT_ESHOP_INIT',0,1,'',3602,'',''),
	--	(0,17000420,170004,0,0,20,'登录店账通','LIMIT_ESHOP_LOGIN',0,1,'',3604,'',''),
	--	(0,17000430,170004,0,0,30,'网店单据下载','LIMIT_ESHOP_DOWNBILL',0,1,'',3603,'',''),
	--	(0,17000440,170004,0,0,40,'网店库存更新','LIMIT_ESHOP_UPDATESTOCK',0,1,'',3606,'',''),		
	--	(0,17000450,170004,0,0,50,'账号绑定','LIMIT_ESHOP_REGISTER',0,1,'',3601,'',''),
	--	(0,17000460,170004,0,0,60,'基本信息同步','LIMIT_ESHOP_SYNCBASEINFO',0,1,'',3607,'',''),	
	--	(0,17000470,170004,0,0,70,'充值续费','LIMIT_ESHOP_RECHARGE',0,1,'',3608,'',''),
	--	(0,17000480,170004,0,0,80,'关于店账通','LIMIT_ESHOP_ABOUT',0,1,'',3605,'',''),
	--(0,170006,1700,0,1,70,'网店管理','vr',0,1,'',-1,'',''),	
	--	(0,17000601,170006,0,0,10,'电商模块绑定','LIMIT_WDSHOP_MODUL_BIND',0,1,'',4941,'',''),
	--	(0,17000602,170006,0,0,20,'网店业务配置','LIMIT_WDSHOP_CONFIG',0,1,'',4942,'',''),
	--	(0,17000603,170006,0,0,30,'网店业务处理','LIMIT_WDSHOP_BUSI_DEAL',0,1,'',4943,'',''),
	--	(0,17000604,170006,0,1,40,'基本信息同步','vr',0,1,'',3605,'',''),
	--		(0,1700060401,17000604,0,0,10,'商品信息同步','LIMIT_WDSHOP_PTYPE_SYSC',0,1,'',4944,'',''),
	--		(0,1700060401,17000604,0,0,20,'商品信息下载','LIMIT_WDSHOP_PTYPE_DOWNLOAD',0,1,'',5105,'',''),
	--		(0,1700060407,17000604,0,0,30,'客户信息同步','LIMIT_WDSHOP_BTYPEINFO_SYSC',0,1,'',5103,'',''),
	--		(0,1700060405,17000604,0,0,40,'职员同步','LIMIT_WDSHOP_EMPLOYEE_SYSC',0,1,'',4948,'',''),
	--		(0,1700060402,17000604,0,0,50,'仓库货位同步','LIMIT_WDSHOP_STOCK_SYSC',0,1,'',4945,'',''),
	--		(0,1700060403,17000604,0,0,60,'库存同步查询','LIMIT_WDSHOP_CARGO_SYSC',0,1,'',4946,'',''),
	--		(0,1700060404,17000604,0,0,70,'账户信息同步','LIMIT_WDSHOP_ACCOUNT_SYSC',0,1,'',4947,'',''),			
	--		(0,1700060406,17000604,0,0,80,'操作员同步','LIMIT_WDSHOP_OPERATOR_SYSC',0,1,'',4949,'',''),			
	--	(0,17000605,170006,0,0,50,'网店业务同步','LIMIT_WDSHOP_BILL_HAND_SYSC',0,1,'',4950,'',''),
	--	(0,17000606,170006,0,0,50,'1688订单管理','LIMIT_WDSHOP_PREORDER_SYSC',0,1,'',5104,'',''),
	(0,170007,1700,0,0,90,'管金所|融资服务','LIMIT_GJS',0,1,'',-1,'',''),
	(0,170008,1700,0,0,100,'应用中心','LIMIT_YYZX',0,1,'1',-1,'',''),
	(0,170009,1700,0,0,110,'全渠道业务同步中心','LIMIT_QQDYWTBZX',0,1,'',-1,'',''),
	(0,170010,1700,0,0,120,'智慧经营管理系统','LIMIT_TTY',0,1,'',-1,'','')	
END;

BEGIN --其他
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,1,1,0,1,1,'订货系统','vr',0,1,'',-1,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,2,1,0,0,2,'订单录入','LIMIT_G_ORDER_ADD',0,0,'',2,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,3,1,0,0,3,'订单查询','LIMIT_G_ORDER_SEARCH',0,0,'',3,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,4,1,0,1,4,'收货管理','vr',0,1,'',-1,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,5,1,0,0,5,'收货单录入','LIMIT_G_GET_ADD',0,0,'',11,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,6,1,0,0,6,'收货单查询','LIMIT_G_GET_SEARCH',0,0,'',12,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,7,1,0,0,7,'对方发货单查询','LIMIT_G_SEND_SEARCH',0,0,'',13,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,8,1,0,1,8,'退货系统','vr',0,1,'',-1,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,9,1,0,0,9,'退货单录入','LIMIT_G_BACK_ADD',0,0,'',21,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,10,1,0,0,10,'退货单查询','LIMIT_G_BACK_SEARCH',0,0,'',22,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,11,1,0,0,11,'对方收货单查询','LIMIT_G_GIVE_SEARCH',0,0,'',23,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,12,1,0,1,12,'付款系统','vr',0,1,'',-1,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,13,1,0,0,13,'付款单录入','LIMIT_G_PAY_ADD',0,0,'',31,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,14,1,0,0,14,'付款单查询','LIMIT_G_PAY_SEARCH',0,0,'',32,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,15,1,0,0,15,'对方收款单查询','LIMIT_G_GATHING_SEARCH0',0,0,'',33,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,16,1,0,1,16,'返款调账','vr',0,1,'',-1,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,17,1,0,0,17,'对方返款查询','LIMIT_G_BACKACCOUNT_SEARCH',0,0,'',36,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,18,1,0,0,18,'对方调账查询','LIMIT_G_ACCOUNT_SEARCH',0,0,'',37,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,19,1,0,1,19,'往来对账','vr',0,1,'',-1,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,20,1,0,0,20,'应付查询','LIMIT_G_OBJECT_SEARCH',0,0,'',41,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,21,1,0,0,21,'对比往来对账一','LIMIT_G_COMOBJECT',0,0,'',47,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,22,1,0,0,22,'对比往来对账二','LIMIT_G_COMOBJECT2',0,0,'',49,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,24,1,0,0,24,'职员管理','LIMIT_G_EMPLOYEE',0,0,'',43,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,25,1,0,1,25,'系统管理','vr',0,1,'',-1,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,26,1,0,0,26,'操作员权限','LIMIT_G_LIMIT',0,0,'',45,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,28,1,0,0,28,'在线传讯','LIMIT_G_ONLINEINFO',1,0,'',48,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(1,29,1,0,0,29,'自动提示超期应收款','AUTO_OUTDATE_GATHERING',0,0,'',164,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(0,500,499,1,0,500,'内部菜单','InSideRoot',0,0,'',-1,'_txt.gif','')

	--汽配维修相关菜单
	--INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	--VALUES
	--(0,690,500,0,1,90,'维修管理','vr',0,1,'',-1,'',''),
	--	(0,601,690,0,0,10,'维修估价单','LIMIT_QP_REPAIR_INTPRICE',0,0,'',1312,'',''),
	--	(0,634,690,0,1,20,'快修管理','vr',0,0,'',-1,'',''),
	--		(0,602,634,0,0,20,'快修单','LIMIT_QP_FIRSTREPAIR',0,0,'',1313,'',''),
	--		(0,603,634,0,0,30,'快修业务查询','LIMIT_QP_REPARIROPRATIONREPORT',0,0,'1',1316,'',''),
	--	(0,636,690,0,1,90,'洗车管理','vr',0,0,'',-1,'',''),
	--		(0,609,636,0,0,130,'洗车结算单','LIMIT_QP_CARWASH',0,0,'',1311,'',''),
	--		(0,611,636,0,0,140,'洗车业务查询','LIMIT_QP_CARWASHREPORT',0,0,'1',1314,'',''),
	--		(0,612,636,0,0,150,'洗车人员考核','LIMIT_QP_CARWASHCHECKREPORT',0,0,'',1315,'',''),
	--	(0,637,690,0,1,110,'旧件回收','vr',0,0,'',-1,'',''),
	--		(0,607,637,0,0,110,'旧件回收单','LIMIT_QP_CALLBACK',0,0,'',1310,'',''),
	--		(0,608,637,0,0,120,'旧件回收查询','LIMIT_QP_CYCLEQUERY',0,0,'1',1320,'',''),
	--	(0,638,690,0,1,100,'工具管理','vr',0,0,'',-1,'',''),
	--		(0,631,638,0,0,10,'工具入库台账','LIMIT_TOOLINSTOCK',0,0,'',1530,'',''),
	--		(0,632,638,0,0,20,'工具出库台账','LIMIT_TOOLOUTSTOCK',0,0,'',1531,'',''),
	--		(0,62925,638,0,0,30,'工具统计分析','LIMIT_QP_TOOLINPUTSREPORT',0,0,'1',1504,'',''),
	--	(0,639,690,0,1,30,'接待登记管理','vr',0,0,'',-1,'',''),
	--		(0,617,639,0,0,10,'接待登记单','LIMIT_QP_RECEPTIONREG',0,0,'',1462,'',''),
	--		(0,62901,639,0,0,20,'接待登记查询','LIMIT_RECEPATION_QUERY',0,0,'1',1480,'',''),
	--		(0,63901,639,0,0,30,'预约维修查询','LIMIT_BESPOKEREPAIR_QUERY',0,0,'',1534,'',''),
	--	(0,643,690,0,1,50,'领料管理','vr',0,0,'',-1,'',''),
	--		(0,619,643,0,0,10,'领料出库单','LIMIT_MATERIALOUTSTOCK',0,0,'',1465,'',''),
	--		(0,623,643,0,0,20,'领料退回单','LIMIT_MATERIALBACKSTOCK',0,0,'',1466,'',''),
	--		(0,62906,643,0,0,30,'领料单查询','LIMIT_PICKINGBILL_QUERY',0,0,'1',1485,'',''),
	--		(0,62907,643,0,0,40,'商品领用查询','LIMIT_PTYPEPICKINGBILL_QUERY',0,0,'',1486,'',''),
	--	(0,644,690,0,1,40,'维修调度管理','vr',0,0,'',-1,'',''),
	--		(0,618,644,0,0,10,'维修业务调度','LIMIT_QP_ATTEMPER',0,0,'',1464,'',''),
	--		(0,62903,644,0,0,20,'维修进度查询','LIMIT_REPAIROPERATION_QUERY',0,0,'1',1482,'',''),
	--		(0,62904,644,0,0,30,'停工项目查询','LIMIT_STOPITEMS_QUERY',0,0,'',1483,'',''),
	--		(0,62905,644,0,0,40,'到期未完工车辆提醒','LIMIT_EXPIRENOCOMPLETE_QUERY',0,0,'',1484,'',''),
	--	(0,646,690,0,1,60,'维修结算管理','vr',0,0,'',-1,'',''),
	--		(0,624,646,0,0,110,'维修结算单','LIMIT_QP_REPAIRBALANCEBILL',0,0,'',1463,'',''),
	--		(0,62908,646,0,0,120,'维修结算查询','LIMIT_BALANCEBILL_QUERY',0,0,'1',1487,'',''),
	--	(0,647,690,0,1,70,'返修管理','vr',0,0,'',-1,'',''),
	--		(0,625,647,0,0,130,'返修单','LIMIT_BACKINGOUTBILL',0,0,'',1467,'',''),
	--		(0,62902,647,0,0,140,'返修记录查询','LIMIT_BACKINGOUT_QUERY',0,0,'1',1481,'',''),
	--	(0,648,690,0,1,80,'救援管理','vr',0,0,'',-1,'',''),
	--		(0,626,648,0,0,150,'救援单','LIMIT_QP_SUCCORBILL',0,0,'',1468,'',''),
	--		(0,62909,648,0,0,160,'救援单查询','LIMIT_SUCCORBILL_QUERY',0,0,'1',1488,'',''),
	--	(0,633,690,0,1,120,'报    表','vr',0,0,'',-1,'',''),
	--		(0,604,633,0,0,10,'维修项目查询','LIMIT_QP_REPAIRITEMSANSI',0,0,'',1319,'',''),
	--		(0,605,633,0,0,20,'维修用料查询','LIMIT_QP_FIRSTREPAIRREPORT',0,0,'',1317,'',''),
	--		(0,606,633,0,0,30,'维修人员业绩统计','LIMIT_QP_REPAIRETYPEANSI',0,0,'',1318,'',''),
	--		(0,62922,633,0,0,40,'商品销售、维修统计','LIMIT_QP_SALEANDREPAIRINPUTACTION_QUERY',0,0,'1',1501,'',''),
	--		(0,62918,633,0,0,50,'维修业务类别统计','LIMIT_REPAIROPERATORTYPE_QUERY',0,0,'',1497,'',''),
	--		(0,62917,633,0,0,60,'维修成本分析','LIMIT_REPAIRCOST_ANSI',0,0,'',1496,'',''),
	--		(0,62923,633,0,0,70,'维修、销售成本分析','LIMIT_REPAIRSALECOSTFX_QUERY',0,0,'',1502,'',''),
	--		(0,62920,633,0,0,80,'维修接待车次统计','LIMIT_REPAIRJDCARTIMES_QUERY',0,0,'',1499,'',''),
	--		(0,62921,633,0,0,90,'维修车次月统计','LIMIT_CAREEPAIRCONTDION_QUERY',0,0,'',1500,'',''),
	--		(0,62919,633,0,0,100,'超期无服务车辆统计','LIMIT_OUTSERVICECAR_QUERY',0,0,'',1498,'','')
	
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(0,69020781,6902078,0,0,10,'会员到期提醒','LIMIT_QP_NIVP_REACHDAYALERT',0,0,'',1324,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(0,69020782,6902078,0,0,20,'会员事件到期提醒','LIMIT_QP_NIVP_EVENTALERT',0,0,'',1325,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(0,69020783,6902078,0,0,30,'会员生日提醒','LIMIT_QP_NIVP_BIRTHDAYALERT',0,0,'',1323,'','')
	INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)VALUES(0,121908,1219,0,0,2,'短信签名','LIMIT_SMS_SIGNATURE',1,1,'',573,'','')

	--汽配售后服务相关菜单
	--INSERT INTO WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
	--VALUES
	--(0,1600,500,0,1,100,'售后服务','vr',0,1,'',-1,'',''),
	--	(0,160001,1600,0,1,10,'三包索赔管理','vr',0,1,'',-1,'',''),
	--	(0,627,160001,0,0,10,'三包索赔单','LIMIT_QP_THREEPACKETSBILL',0,0,'',1469,'',''),
	--	(0,62910,160001,0,0,20,'三包索赔单查询','LIMIT_THREEPACKETS_QUERY',0,0,'1',1489,'',''),
	--	(0,62911,160001,0,0,30,'索赔项目查询','LIMIT_PACKETSITEMS_QUERY',0,0,'',1490,'',''),
	--	(0,62912,160001,0,0,40,'索赔材料查询','LIMIT_PACKETSPTYPE_QUERY',0,0,'',1491,'',''),
	--(0,160002,1600,0,1,20,'保险理赔管理','vr',0,1,'',-1,'',''),
	--	(0,613,160002,0,0,70,'保险理赔单','LIMIT_INSURANCEBILL_VCHTYPE',0,0,'',1369,'',''),
	--	(0,614,160002,0,0,90,'理赔项目查询','LIMIT_INSURANCEITEMS_BILL_QUERY',0,0,'',1366,'',''),
	--	(0,615,160002,0,0,100,'理赔材料查询','LIMIT_INSURANCEPTYPE_BILL_QUERY',0,0,'',1367,'',''),
	--	(0,616,160002,0,0,80,'保险理赔单查询','LIMIT_INSURANCE_BILL_QUERY',0,0,'1',1368,'',''),
	--(0,160003,1600,0,1,20,'维修回访管理','vr',0,1,'',-1,'',''),
	--	(0,62913,160003,0,0,30,'维修回访提醒','LIMIT_REPAIRTALKBACKAWOKE_QUERY',0,0,'',1492,'',''),
	--	(0,62914,160003,0,0,20,'维修回访查询','LIMIT_REPAIRINTERVIEWCONTION_QUERY',0,0,'1',1493,'',''),
	--(0,62915,1600,0,0,40,'保险到期车辆提醒','LIMIT_INSURANCEEXPIRE_QUERY',0,0,'',1494,'',''),
	--(0,62916,1600,0,0,50,'年审到期车辆提醒','LIMIT_YEARCHECKALERT_QUERY',0,0,'',1495,'',''),
	--(0,160004,1600,0,0,60,'首保到期提醒','LIMIT_FIRST_MAINTAIN_ALERT',0,0,'',2025,'',''),
	--(0,160005,1600,0,0,70,'车辆强保提醒','LIMIT_FORCE_MAINTAIN_ALERT',0,0,'',2026,'','')
	


END;

--API测试
--BEGIN
--INSERT INTO dbo.WebMenu(SysId,MenuId,ParentId,IsRoot,IsSubMenu,TabOrd,Caption,Name,AllUser,CallType,Title,OffSet,Img,ShortCut)
--VALUES
--	(0,101050,600,0,1,43,'API申请','vr',0,1,'',-1,'',''),
--	(0,10105010,101050,0,0,10,'API申请','LIMIT_API_BASE',0,0,'',-1,'',''),	
--	(0,10105020,101050,0,0,20,'API单据审核','LIMIT_APIAudit_BASE',0,0,'',-1,'',''),	
--	(0,10105030,101050,0,0,30,'API查询','LIMIT_APIQuery_BASE',0,0,'',-1,'','')	
--END

--OM
BEGIN	
	INSERT [dbo].[WebMenu] ([SysID], [MenuID], [ParentID], [IsRoot], [IsSubMenu], [Tabord], [Caption], [Name], [AllUser], [CallType], [Title], [Offset], [img], [ShortCut]) VALUES (0, 516, 511030, 0, 0, 9, N'OM订单明细', N'LIMIT_OMBILL_QUERY', 0, 0, N'', 3657, N'_txt.gif', N'')
	INSERT [dbo].[WebMenu] ([SysID], [MenuID], [ParentID], [IsRoot], [IsSubMenu], [Tabord], [Caption], [Name], [AllUser], [CallType], [Title], [Offset], [img], [ShortCut]) VALUES (0, 517, 511030, 0, 0, 9, N'OM退货列表', N'LIMIT_OMBACKBILL_QUERY', 0, 0, N'', 3661, N'_txt.gif', N'')
	--INSERT [dbo].[WebMenu] ([SysID], [MenuID], [ParentID], [IsRoot], [IsSubMenu], [Tabord], [Caption], [Name], [AllUser], [CallType], [Title], [Offset], [img], [ShortCut]) VALUES (0, 1276, 101020, 0, 0, 260, N'OM存货信息设置', N'LIMIT_COMMON_STOCK_SET', 0, 0, N'1', 3651, N'', N'')
	--INSERT [dbo].[WebMenu] ([SysID], [MenuID], [ParentID], [IsRoot], [IsSubMenu], [Tabord], [Caption], [Name], [AllUser], [CallType], [Title], [Offset], [img], [ShortCut]) VALUES (0, 1277, 101020, 0, 0, 270, N'OM存货信息录入', N'LIMIT_COMMON_STOCK_INS', 0, 0, N'', 3652, N'', N'')
	INSERT [dbo].[WebMenu] ([SysID], [MenuID], [ParentID], [IsRoot], [IsSubMenu], [Tabord], [Caption], [Name], [AllUser], [CallType], [Title], [Offset], [img], [ShortCut]) VALUES (0, 1278, 101020, 0, 0, 280, N'OM咨询回复', N'LIMIT_OM_QuestionReply', 0, 0, N'1', 3658, N'', N'')
	DELETE FROM dbo.WebMenu WHERE Caption='OM存货信息设置'
	DELETE FROM dbo.WebMenu WHERE Caption='OM存货信息录入' --这里用caption作为条件，是因为防止以后有用到menuid=1276,1277的菜单
END;
GO

------------------------------------------------------------修改数据------------------------------------------------------------
UPDATE WebMenu SET ShortCut = '' WHERE ShortCut IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 







GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = object_id(N'[dbo].[xw_SelfDataType]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
    --DROP TABLE xw_SelfDataType
CREATE TABLE xw_SelfDataType                   -- 自定义数据类型
(
  _Id              INT IDENTITY primary key,
  Name             VARCHAR(100),
  Deleted          BIT NOT NULL DEFAULT 0      -- 删除标记，删除时只是填为1
)

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = object_id(N'[dbo].[xw_SelfData]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
    --DROP TABLE xw_SelfData
CREATE TABLE xw_SelfData                       -- 自定义数据
(
  _Id              INT IDENTITY primary key,
  DataTypeId       INT NOT NULL,               -- 自定义类型ID，对应 xw_SelfDataType._Id
  TypeId           VARCHAR(50),
  ParTypeId        VARCHAR(50),
  [level]          INT NOT NULL DEFAULT 0,
  SonNum           INT NOT NULL DEFAULT 0,
  SonCount         INT NOT NULL DEFAULT 0,
  FullName         VARCHAR(500),
  UserCode         VARCHAR(500),
  PyCode           VARCHAR(500),
  Field1           VARCHAR(500),
  Field2           VARCHAR(500),
  Field3           VARCHAR(500),
  Field4           VARCHAR(500),
  Deleted          BIT NOT NULL DEFAULT 0,      -- 删除标记，删除时只是填为1
  XiWaMaxNumber    int NULL,                    -- XiWa更新版本标志
)

GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = object_id(N'[dbo].[xw_Message]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
    DROP TABLE xw_Message 
CREATE TABLE xw_Message                        -- 操作员短信
(
  _Id        INT IDENTITY primary key,
  SenderId   VARCHAR(100) ,                    -- 发送人ID
  ReceiverId VARCHAR(100) NOT NULL,            -- 接收人ID
  SendDate   DATETIME NOT NULL,                -- 发送日期
  Message    VARCHAR(4000),                    -- 消息内容
  IsNew      BIT NOT NULL DEFAULT 1,           -- 消息是否未读
  Deleted    BIT NOT NULL DEFAULT 0            -- 删除标记，暂时没用
)
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[xw_Message]') AND name = N'Ixw_Message_SenderId')
	CREATE INDEX Ixw_Message_SenderId ON xw_Message(SenderId) 
	
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[xw_Message]') AND name = N'Ixw_Message_ReceiverId')	
	CREATE INDEX Ixw_Message_ReceiverId ON xw_Message(ReceiverId) 

GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = object_id(N'[dbo].[xw_Attachment]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
    DROP TABLE xw_Attachment  
     
CREATE TABLE xw_Attachment                     -- 附件
(
  _Id  INT IDENTITY primary key,
  Guid UNIQUEIDENTIFIER,                       -- 附件唯一标识
  OwnerGuid UNIQUEIDENTIFIER,                  -- 临时使用的单据唯一标识
  OwnerId int,                                 -- 单据ID   
  Content IMAGE NOT NULL,                      -- 内容
  Filename varchar (255),                      -- 文件名
  Comment varchar (255),                       -- 备注
  CreationTime datetime NOT NULL,              -- 创建时间
  LastModifiedTime datetime NOT NULL,          -- 最后修改时间
  Deleted    BIT NOT NULL DEFAULT 0            -- 删除标记，暂时没用
)
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[xw_Attachment]') AND name = N'Ixw_Attachment')
	CREATE INDEX Ixw_Attachment ON xw_Attachment(OwnerId)
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[xw_Attachment]') AND name = N'Ixw_Attachment_OwnerGuid')
	CREATE INDEX Ixw_Attachment_OwnerGuid ON xw_Attachment(OwnerGuid)
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[xw_Attachment]') AND name = N'Ixw_Attachment_CreationDate')
	CREATE INDEX Ixw_Attachment_CreationDate ON xw_Attachment(CreationTime)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/* 自定义报表*/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = object_id(N'[dbo].[xw_CustomReport]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
    DROP TABLE xw_CustomReport
CREATE TABLE  xw_CustomReport 
(
    [ID] [int] primary key not Null,    -- 自定义报表在数据库中的ID
    [ProcedureName] [NVarChar](100),    -- 存储过程名
    [Caption]   [NVarChar](1000),       -- 报表名称
    [ReportInfo]   nText                -- 自定义报表详细信息
)
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[xw_CustomReport]') AND name = N'Ixw_CustomReport')
	CREATE INDEX Ixw_CustomReport ON xw_CustomReport(ProcedureName)      

GO


/* 存储过程备份 */
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = object_id(N'[dbo].[xw_ProcedureBackup]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
    DROP TABLE xw_ProcedureBackup
CREATE TABLE  xw_ProcedureBackup
(
    [ID] [int] primary key not Null,    -- ID
    [ProcedureName] [NVarChar](100),    -- 存储过程名
    [ProcedureInfo]  nText              -- 存储过程代码
)
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[xw_ProcedureBackup]') AND name = N'Ixw_ProcedureBackup')
	CREATE INDEX Ixw_ProcedureBackup ON xw_ProcedureBackup(ProcedureName)   --存储过程名需唯一
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Account')
            and   type = 'U')   
BEGIN
	create table Ac_Account (
		StypeId              varchar(50)          not null,
		TypeId               varchar(50)          not null,
		ParId                varchar(50)          not null,
		Leveal               int                  not null,
		SonNum               int                  not null,
		SonCount             int                  not null,
		UserCode             varchar(200)         not null,
		FullName             varchar(200)         not null,
		Name                 varchar(200)         null,
		Fdc                  int                  null,
		IsCash               int                  null default 0,
		IsBank               int                  null default 0,
		IsDiary              int                  null default 0,
	    IsPreGather          int                  null default 0,
	    IsPrePay             int                  null default 0,
	    IsGather             int                  null default 0,
	    IsPay                int                  null default 0,
	    IsVip                int                  null default 0,		
		Comment              varchar(400)         null,
		PyCode               varchar(200)         null,
		ETypeId              varchar(50)          not null,
		CreateDateTime       datetime             not null,
		MainItems            varchar(100)         null,
		AdditionItems        varchar(100)         null,
		ExchId               int                  null,
		FAcctint             int                  null,
		FAcnt                int                  null default 0,
		AscIds               int                  null,
		FAdjustRate          int                  null default 0,
		FContact             int                  null default 0,
		FInterest            int                  null default 0,
		FintRate             numeric(18,4)        null
	)
END
GO
------------------------------------------------------修改表------------------------------------------------------
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='Len1'
)
BEGIN
	ALTER TABLE Ac_Account 
		DROP COLUMN Len1,Len2,Len3,Len4,Len5,Len6,Len7,Len8,Len9,Len10		
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='FAcctint'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD 
			FAcctint INT NULL DEFAULT(0),
			FAcnt INT NULL DEFAULT(0),
			AscIds INT NULL,
			FAdjustRate INT NULL DEFAULT(0),
			FContact INT NULL DEFAULT(0),
			FInterest INT NULL DEFAULT(0),
			FintRate INT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='FLeveal'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD FLeveal INT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='Deleted'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD Deleted INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='XiWaMaxNumber'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD XiWaMaxNumber INT NOT NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='IsOther'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD IsOther INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='Cid'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD Cid INT NULL DEFAULT(-1)
END
GO

IF EXISTS(SELECT * from syscolumns where id = object_id(N'[dbo].[Ac_Account]') and  name = 'AscIds' and Length = 4)
BEGIN
     ALTER TABLE Ac_Account
	    ALTER COLUMN AscIds VARCHAR(200) NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='IsDist'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD IsDist INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='KeyId'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD KeyId BIGINT NOT NULL Identity(1,1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='Group'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD [Group] VARCHAR(10) NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='IsPreGather'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD IsPreGather INT NULL DEFAULT(0),
			IsPrePay INT NULL DEFAULT(0),
			IsGather INT NULL DEFAULT(0),
			IsPay INT NULL DEFAULT(0),
			IsVip INT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='CheckType'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD CheckType INT NULL DEFAULT(0)
END
GO
--数量核算
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='AdjustAccounts'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD AdjustAccounts BIT NOT NULL DEFAULT(0)
END
GO
--计量单位
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='UnitID'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD UnitID INT NOT NULL DEFAULT(0)
END
GO
--科目tree节点
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='AcId'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD AcId INT NOT NULL DEFAULT(0)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT') AND name = 'CIX_AC_ACCOUNT_Typeid')
--DROP INDEX CIX_AC_ACCOUNT_Typeid ON AC_ACCOUNT 
CREATE CLUSTERED INDEX CIX_AC_ACCOUNT_Typeid ON AC_ACCOUNT(Typeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT') AND name = 'NCIX_AC_ACCOUNT_Stypeid_Parid')
--DROP INDEX NCIX_AC_ACCOUNT_Stypeid_Parid ON AC_ACCOUNT 
CREATE NONCLUSTERED INDEX NCIX_AC_ACCOUNT_Stypeid_Parid ON AC_ACCOUNT(Stypeid,Parid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT') AND name = 'NCIX_AC_ACCOUNT_Usercode')
--DROP INDEX NCIX_AC_ACCOUNT_Usercode ON AC_ACCOUNT 
CREATE NONCLUSTERED INDEX NCIX_AC_ACCOUNT_Usercode ON AC_ACCOUNT(Usercode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT') AND name = 'NCIX_AC_ACCOUNT_Fullname')
--DROP INDEX NCIX_AC_ACCOUNT_Fullname ON AC_ACCOUNT 
CREATE NONCLUSTERED INDEX NCIX_AC_ACCOUNT_Fullname ON AC_ACCOUNT(Fullname) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------预置数据-----------------------------------------------

------------------------------------------预置数据-----------------------------------------------


------------------------------------------------------修改数据------------------------------------------------------
UPDATE Ac_Account SET Deleted = 0 WHERE Deleted IS NULL
GO
UPDATE Ac_Account SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL
GO
UPDATE Ac_Account SET IsOther = 0 WHERE IsOther IS NULL
GO
UPDATE Ac_Account SET AscIds = '' WHERE AscIds IS NULL
GO
UPDATE Ac_Account SET Cid = -1 WHERE Cid IS NULL
GO
UPDATE Ac_Account SET IsDist = 0 WHERE IsDist IS NULL
GO
UPDATE Ac_Account SET IsPreGather = 0 WHERE IsPreGather IS NULL
GO
UPDATE Ac_Account SET IsPrePay = 0 WHERE IsPrePay IS NULL
GO
UPDATE Ac_Account SET IsGather = 0 WHERE IsGather IS NULL
GO
UPDATE Ac_Account SET IsPay = 0 WHERE IsPay IS NULL
GO
UPDATE Ac_Account SET IsVip = 0 WHERE IsVip IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='FintRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Account 
	ALTER COLUMN FintRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Account_Assist_CheckItems')
            and   type = 'U')
BEGIN
	create table Ac_Account_Assist_CheckItems (
	   STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   Cid                  int                  null,
	   Ascids               int                  null,
	   IsRequired           int                  null default 1
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account_Assist_CheckItems' AND a.Name='IsRequired'
)
BEGIN
	ALTER TABLE Ac_Account_Assist_CheckItems 
		ADD IsRequired INT NULL DEFAULT(1)
END
GO
--辅助核算类型默认值
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account_Assist_CheckItems' AND a.Name='DTypeID'
)
BEGIN
	ALTER TABLE Ac_Account_Assist_CheckItems 
		ADD DTypeID VARCHAR(50) DEFAULT('')
END
GO
--科目tree节点
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account_Assist_CheckItems' AND a.Name='AcId'
)
BEGIN
	ALTER TABLE Ac_Account_Assist_CheckItems 
		ADD AcId INT NULL DEFAULT(0)
END
GO
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE DTypeID IS NULL)
	BEGIN
		UPDATE Ac_Account_Assist_CheckItems SET DTypeID='' WHERE DTypeID IS NULL
	END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT_ASSIST_CHECKITEMS') AND name = 'CIX_AC_ACCOUNT_ASSIST_CHECKITEMS_Atypeid')
--DROP INDEX CIX_AC_ACCOUNT_ASSIST_CHECKITEMS_Atypeid ON AC_ACCOUNT_ASSIST_CHECKITEMS 
CREATE CLUSTERED INDEX CIX_AC_ACCOUNT_ASSIST_CHECKITEMS_Atypeid ON AC_ACCOUNT_ASSIST_CHECKITEMS(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_ACCOUNT_ASSIST_CHECKITEMS_Stypeid')
--DROP INDEX NCIX_AC_ACCOUNT_ASSIST_CHECKITEMS_Stypeid ON AC_ACCOUNT_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_ACCOUNT_ASSIST_CHECKITEMS_Stypeid ON AC_ACCOUNT_ASSIST_CHECKITEMS(Stypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------------------修改数据------------------------------------------------------
UPDATE Ac_Account_Assist_CheckItems SET IsRequired = 1 WHERE IsRequired IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--科目多级权限表
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE ID=OBJECT_ID(N'Ac_Account_L') AND OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Ac_Account_L]
	(	
		etypeid	VARCHAR(100),--操作员
		stypeid	VARCHAR(100),--分支机构
		typeid	VARCHAR(100),--科目ID
		flag    CHAR(1)		 --1=代表有全部权限，0=代表没有权限（比如现在父类下的子节点，那么子节点的flag为1，父节点的flag=0）同其他多级权限一样
	)
	
	--业务员
	INSERT Ac_Account_L VALUES('0000100001','00000','00000',1)
END
GO

IF NOT EXISTS (SELECT TOP 1 1 FROM Ac_Account_L WHERE etypeid = '00001' AND stypeid = '00000' AND typeid='00000' AND flag = 1)
BEGIN
	INSERT Ac_Account_L VALUES('00001','00000','00000',1)
END
GO



------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Account_L') AND name = 'CIX_Ac_Account_L_etypeid')
	--DROP INDEX CIX_Ac_Account_L_etypeid ON Ac_Account_L 
CREATE CLUSTERED INDEX CIX_Ac_Account_L_etypeid ON Ac_Account_L(etypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------


SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF EXISTS (	SELECT 1
            FROM  sysobjects
			WHERE  id = object_id('Ac_Account_Set_Detail')
            AND   type = 'U')
   DROP TABLE Ac_Account_Set_Detail
GO

/*==============================================================*/
/* Table: Ac_Account_Set_Detail                                */
/*==============================================================*/
CREATE TABLE Ac_Account_Set_Detail (
   DtId                 INT                  IDENTITY(1,1),
   SubId                INT                  NOT NULL,
   [Group]              VARCHAR(200)         NULL,
   TypeId               VARCHAR(50)          NULL,
   ParId                VARCHAR(50)          NULL,
   FLeveal              INT                  NULL,
   Leveal               INT                  NULL,
   SonNum               INT                  NULL,
   SonCount             INT                  NULL,
   UserCode             VARCHAR(200)         NULL,
   FullName             VARCHAR(200)         NULL,
   Name                 VARCHAR(200)         NULL,
   Fdc                  INT                  NULL,
   IsCash               INT                  NULL,
   IsBank               INT                  NULL,
   IsOther              INT                  NULL,
   fcontact             INT                  NULL,
   checktype            INT                  NULL,
   Comment              VARCHAR(400)         NULL,
   PyCode               VARCHAR(200)         NULL
)
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account' AND a.Name='FLeveal'
)
BEGIN
	ALTER TABLE Ac_Account 
		ADD FLeveal INT NOT NULL DEFAULT(0)
END
GO

---------------------------------------------------------企业会计制度科目----------------------------------------------------------------

INSERT INTO Ac_Account_Set_Detail(TypeId,ParId,Leveal,SonNum,SonCount,SubId,UserCode,FullName,Name,PyCode,Comment,[Group],Fdc,IsCash,IsBank,IsOther,fcontact,checktype) 
VALUES	----------------------------------分类---------------------------------------
		('00001','00001',1,0,0,1,'','资产','','','','100',-1,0,0,0,0,0),
		('00002','00001',1,0,0,1,'','负债','','','','200',-1,0,0,0,0,0),
		('00003','00001',1,0,0,1,'','损益','','','','500',-1,0,0,0,0,0),
		('00004','00001',1,0,0,1,'','成本','','','','400',-1,0,0,0,0,0),
		('00005','00001',1,0,0,1,'','权益','','','','300',-1,0,0,0,0,0),
		('00006','00001',1,0,0,1,'','共同','','','','700',-1,0,0,0,0,0),
		-----------------------------------资产---------------------------------------
		('0000100001','00001',2,0,0,1,'1001','现金','','','','101',1,1,0,0,0,0),
		('0000100002','00001',2,0,0,1,'1002','银行存款','','','','101',1,0,1,0,0,0),
		('0000100003','00001',2,0,0,1,'1009','其他货币资金','','','','101',1,0,0,1,0,0),
			('000010000300001','0000100003',3,0,0,1,'100901','外埠存款','','','','101',1,0,0,1,0,0),
			('000010000300002','0000100003',3,0,0,1,'100902','银行本票','','','','101',1,0,0,1,0,0),
			('000010000300003','0000100003',3,0,0,1,'100903','银行汇票','','','','101',1,0,0,1,0,0),
			('000010000300004','0000100003',3,0,0,1,'100904','信用卡','','','','101',1,0,0,1,0,0),
			('000010000300005','0000100003',3,0,0,1,'100905','信用证保证金','','','','101',1,0,0,1,0,0),
			('000010000300006','0000100003',3,0,0,1,'100906','存出投资款','','','','101',1,0,0,1,0,0),
		('0000100004','00001',2,0,0,1,'1101','短期投资','','','','101',1,0,0,0,0,0),
			('000010000400001','0000100004',3,0,0,1,'110101','股票','','','','101',1,0,0,0,0,0),
			('000010000400002','0000100004',3,0,0,1,'110102','债券','','','','101',1,0,0,0,0,0),
			('000010000400003','0000100004',3,0,0,1,'110103','基金','','','','101',1,0,0,0,0,0),
			('000010000400004','0000100004',3,0,0,1,'110110','其他','','','','101',1,0,0,0,0,0),
		('0000100005','00001',2,0,0,1,'1102','短期投资跌价准备','','','','101',-1,0,0,0,0,0),
		('0000100006','00001',2,0,0,1,'1111','应收票据','','','','101',1,0,0,0,0,0),
		('0000100007','00001',2,0,0,1,'1121','应收股利','','','','101',1,0,0,0,0,0),
		('0000100008','00001',2,0,0,1,'1122','应收利息','','','','101',1,0,0,0,0,0),
		('0000100009','00001',2,0,0,1,'1131','应收账款','','','','101',1,0,0,0,1,1),
		('0000100010','00001',2,0,0,1,'1133','其他应收款','','','','101',1,0,0,0,1,1),
		('0000100011','00001',2,0,0,1,'1141','坏账准备','','','','101',-1,0,0,0,0,0),
		('0000100012','00001',2,0,0,1,'1151','预付账款','','','','101',1,0,0,0,1,2),
		('0000100013','00001',2,0,0,1,'1161','应收补贴款','','','','101',1,0,0,0,0,0),
		('0000100014','00001',2,0,0,1,'1201','物资采购','','','','101',1,0,0,0,0,0),
		('0000100015','00001',2,0,0,1,'1211','原材料','','','','101',1,0,0,0,0,0),
		('0000100016','00001',2,0,0,1,'1221','包装物','','','','101',1,0,0,0,0,0),
		('0000100017','00001',2,0,0,1,'1231','低值易耗品','','','','101',1,0,0,0,0,0),
		('0000100018','00001',2,0,0,1,'1232','材料成本差异','','','','101',1,0,0,0,0,0),
		('0000100019','00001',2,0,0,1,'1241','自制半成品','','','','101',1,0,0,0,0,0),
		('0000100020','00001',2,0,0,1,'1243','库存商品','','','','101',1,0,0,0,0,0),
		('0000100021','00001',2,0,0,1,'1244','商品进销差价','','','','101',1,0,0,0,0,0),
		('0000100022','00001',2,0,0,1,'1251','委托加工物资','','','','101',1,0,0,0,0,0),
		('0000100023','00001',2,0,0,1,'1261','委托代销商品','','','','101',1,0,0,0,0,0),
		('0000100024','00001',2,0,0,1,'1271','受托代销商品','','','','101',1,0,0,0,0,0),
		('0000100025','00001',2,0,0,1,'1281','存货跌价准备','','','','101',-1,0,0,0,0,0),
		('0000100026','00001',2,0,0,1,'1291','分期收款发出商品','','','','101',1,0,0,0,0,0),
		('0000100027','00001',2,0,0,1,'1301','待摊费用','','','','101',1,0,0,0,0,0),
		('0000100028','00001',2,0,0,1,'1401','长期股权投资','','','','102',1,0,0,0,0,0),
			('000010002800001','0000100028',3,0,0,1,'140101','股票投资','','','','102',1,0,0,0,0,0),
			('000010002800002','0000100028',3,0,0,1,'140102','其他股权投资','','','','102',1,0,0,0,0,0),
		('0000100029','00001',2,0,0,1,'1402','长期债权投资','','','','102',1,0,0,0,0,0),
			('000010002900001','0000100029',3,0,0,1,'140201','债券投资','','','','102',1,0,0,0,0,0),
			('000010002900002','0000100029',3,0,0,1,'140202','其他债权投资','','','','102',1,0,0,0,0,0),
		--('0000100045','00001',2,0,0,1,'1411','周转材料','','','','102',1,0,0,0,0,0),
		('0000100030','00001',2,0,0,1,'1421','长期投资减值准备','','','','102',-1,0,0,0,0,0),
		('0000100031','00001',2,0,0,1,'1431','委托贷款','','','','102',1,0,0,0,0,0),
			('000010003100001','0000100031',3,0,0,1,'143101','本金','','','','102',1,0,0,0,0,0),
			('000010003100002','0000100031',3,0,0,1,'143102','利息','','','','102',1,0,0,0,0,0),
			('000010003100003','0000100031',3,0,0,1,'143103','减值准备','','','','102',-1,0,0,0,0,0),
		('0000100032','00001',2,0,0,1,'1501','固定资产','','','','102',1,0,0,0,0,0),
		('0000100033','00001',2,0,0,1,'1502','累计折旧','','','','102',-1,0,0,0,0,0),
		('0000100034','00001',2,0,0,1,'1505','固定资产减值准备','','','','102',-1,0,0,0,0,0),
		('0000100035','00001',2,0,0,1,'1601','工程物资','','','','102',1,0,0,0,0,0),
			('000010003500001','0000100035',3,0,0,1,'160101','专用材料','','','','102',1,0,0,0,0,0),
			('000010003500002','0000100035',3,0,0,1,'160102','专用设备','','','','102',1,0,0,0,0,0),
			('000010003500003','0000100035',3,0,0,1,'160103','预付大型设备','','','','102',1,0,0,0,0,0),
			('000010003500004','0000100035',3,0,0,1,'160104','为生产准备的工具及器具','','','','102',1,0,0,0,0,0),
		('0000100036','00001',2,0,0,1,'1603','在建工程','','','','102',1,0,0,0,0,0),
		('0000100037','00001',2,0,0,1,'1605','在建工程减值准备','','','','102',-1,0,0,0,0,0),
		('0000100038','00001',2,0,0,1,'1701','固定资产清理','','','','102',1,0,0,0,0,0),
		('0000100039','00001',2,0,0,1,'1801','无形资产','','','','102',1,0,0,0,0,0),
		('0000100040','00001',2,0,0,1,'1805','无形资产减值准备','','','','102',-1,0,0,0,0,0),
		('0000100041','00001',2,0,0,1,'1815','未确认融资费用','','','','102',1,0,0,0,0,0),
		('0000100042','00001',2,0,0,1,'1901','长期待摊费用','','','','102',1,0,0,0,0,0),
		('0000100043','00001',2,0,0,1,'1911','待处理财产损溢','','','','101',1,0,0,0,0,0),
			('000010004300001','0000100043',3,0,0,1,'191101','待处理流动资产损溢','','','','101',1,0,0,0,0,0),
			('000010004300002','0000100043',3,0,0,1,'191102','待处理固定资产损溢','','','','101',1,0,0,0,0,0),
		('0000100044','00001',2,0,0,1,'1242','发出商品','','','','101',1,0,0,0,0,0),
		--------------------------------------------负债------------------------------------------------------
		('0000200001','00002',2,0,0,1,'2101','短期借款','','','','201',-1,0,0,0,0,0),
		('0000200002','00002',2,0,0,1,'2111','应付票据','','','','201',-1,0,0,0,0,0),
		('0000200003','00002',2,0,0,1,'2121','应付账款','','','','201',-1,0,0,0,1,2),
			('000020000300001','0000200003',3,0,0,1,'212101','应付货款','','','','201',-1,0,0,0,1,2),
			('000020000300002','0000200003',3,0,0,1,'212102','应付暂估','','','','201',-1,0,0,0,1,2),
		('0000200004','00002',2,0,0,1,'2131','预收账款','','','','201',-1,0,0,0,1,1),
		('0000200005','00002',2,0,0,1,'2141','代销商品款','','','','201',-1,0,0,0,0,0),
		('0000200006','00002',2,0,0,1,'2151','应付工资','','','','201',-1,0,0,0,0,0),
		('0000200007','00002',2,0,0,1,'2153','应付福利费','','','','201',-1,0,0,0,0,0),
		('0000200008','00002',2,0,0,1,'2161','应付股利','','','','201',-1,0,0,0,0,0),
		('0000200009','00002',2,0,0,1,'2171','应交税金','','','','201',-1,0,0,0,0,0),
			('000020000900001','0000200009',3,0,0,1,'217101','应交增值税','','','','201',-1,0,0,0,0,0),
				('00002000090000100001','000020000900001',4,0,0,1,'21710101','进项税额','','','','201',1,0,0,0,0,0),
				('00002000090000100002','000020000900001',4,0,0,1,'21710102','已交税金','','','','201',1,0,0,0,0,0),
				('00002000090000100003','000020000900001',4,0,0,1,'21710103','转出未交增值税','','','','201',1,0,0,0,0,0),
				('00002000090000100004','000020000900001',4,0,0,1,'21710104','减免税款','','','','201',1,0,0,0,0,0),
				('00002000090000100005','000020000900001',4,0,0,1,'21710105','销项税额','','','','201',-1,0,0,0,0,0),
				('00002000090000100006','000020000900001',4,0,0,1,'21710106','出口退税','','','','201',1,0,0,0,0,0),
				('00002000090000100007','000020000900001',4,0,0,1,'21710107','进项税额转出','','','','201',-1,0,0,0,0,0),
				('00002000090000100008','000020000900001',4,0,0,1,'21710108','出口抵减内销产品应纳税额','','','','201',-1,0,0,0,0,0),
				('00002000090000100009','000020000900001',4,0,0,1,'21710109','转出多交增值税','','','','201',1,0,0,0,0,0),
				('00002000090000100010','000020000900001',4,0,0,1,'21710110','未交增值税','','','','201',-1,0,0,0,0,0),
			('000020000900002','0000200009',3,0,0,1,'217102','应交营业税','','','','201',-1,0,0,0,0,0),
			('000020000900003','0000200009',3,0,0,1,'217103','应交消费税','','','','201',-1,0,0,0,0,0),
			('000020000900004','0000200009',3,0,0,1,'217104','应交资源税','','','','201',-1,0,0,0,0,0),
			('000020000900005','0000200009',3,0,0,1,'217105','应交所得税','','','','201',-1,0,0,0,0,0),
			('000020000900006','0000200009',3,0,0,1,'217106','应交土地增值税','','','','201',-1,0,0,0,0,0),
			('000020000900007','0000200009',3,0,0,1,'217107','应交城市维护建设税','','','','201',-1,0,0,0,0,0),
			('000020000900008','0000200009',3,0,0,1,'217108','应交房产税','','','','201',-1,0,0,0,0,0),
			('000020000900009','0000200009',3,0,0,1,'217109','应交土地使用税','','','','201',-1,0,0,0,0,0),
			('000020000900010','0000200009',3,0,0,1,'217110','应交车船使用税','','','','201',-1,0,0,0,0,0),
			('000020000900011','0000200009',3,0,0,1,'217111','应交个人所得税','','','','201',-1,0,0,0,0,0),
		('0000200010','00002',2,0,0,1,'2176','其他应交款','','','','201',-1,0,0,0,0,0),
		('0000200011','00002',2,0,0,1,'2181','其他应付款','','','','201',-1,0,0,0,1,2),
		('0000200012','00002',2,0,0,1,'2191','预提费用','','','','201',-1,0,0,0,0,0),
		('0000200013','00002',2,0,0,1,'2201','待转资产价值','','','','201',-1,0,0,0,0,0),
		('0000200014','00002',2,0,0,1,'2211','预计负债','','','','201',-1,0,0,0,0,0),
		('0000200015','00002',2,0,0,1,'2301','长期借款','','','','202',-1,0,0,0,0,0),
		('0000200016','00002',2,0,0,1,'2311','应付债券','','','','202',-1,0,0,0,0,0),
			('000020001600001','0000200016',3,0,0,1,'231101','债券面值','','','','202',-1,0,0,0,0,0),
			('000020001600002','0000200016',3,0,0,1,'231102','债券溢价','','','','202',-1,0,0,0,0,0),
			('000020001600003','0000200016',3,0,0,1,'231103','债券折价','','','','202',-1,0,0,0,0,0),
			('000020001600004','0000200016',3,0,0,1,'231104','应计利息','','','','202',-1,0,0,0,0,0),
		('0000200017','00002',2,0,0,1,'2321','长期应付款','','','','202',-1,0,0,0,0,0),
		('0000200018','00002',2,0,0,1,'2331','专项应付款','','','','202',-1,0,0,0,0,0),
		('0000200019','00002',2,0,0,1,'2341','递延税款','','','','202',-1,0,0,0,0,0),
		--------------------------------------------损益-----------------------------------------------------------------
		('0000300001','00003',2,0,0,1,'5101','主营业务收入','','','','501',-1,0,0,0,0,0),
		('0000300002','00003',2,0,0,1,'5102','其他业务收入','','','','504',-1,0,0,0,0,0),
		('0000300003','00003',2,0,0,1,'5201','投资收益','','','','504',-1,0,0,0,0,0),
		('0000300004','00003',2,0,0,1,'5203','补贴收入','','','','504',-1,0,0,0,0,0),
		('0000300005','00003',2,0,0,1,'5301','营业外收入','','','','504',-1,0,0,0,0,0),
		('0000300006','00003',2,0,0,1,'5401','主营业务成本','','','','502',1,0,0,0,0,0),
		('0000300007','00003',2,0,0,1,'5402','主营业务税金及附加','','','','502',1,0,0,0,0,0),
		('0000300008','00003',2,0,0,1,'5405','其他业务支出','','','','505',1,0,0,0,0,0),
		('0000300009','00003',2,0,0,1,'5501','营业费用','','','','503',1,0,0,0,0,0),
		('0000300010','00003',2,0,0,1,'5502','管理费用','','','','503',1,0,0,0,0,0),
		('0000300011','00003',2,0,0,1,'5503','财务费用','','','','503',1,0,0,0,0,0),
		('0000300012','00003',2,0,0,1,'5601','营业外支出','','','','505',1,0,0,0,0,0),
		('0000300013','00003',2,0,0,1,'5701','所得税','','','','507',1,0,0,0,0,0),
		('0000300014','00003',2,0,0,1,'5801','以前年度损益调整','','','','506',-1,0,0,0,0,0),
		-------------------------------------------成本----------------------------------------------------------
		('0000400001','00004',2,0,0,1,'4101','生产成本','','','','400',1,0,0,0,0,0),
			('000040000100001','0000400001',3,0,0,1,'410101','基本生产成本','','','','400',1,0,0,0,0,0),
			('000040000100002','0000400001',3,0,0,1,'410102','辅助生产成本','','','','400',1,0,0,0,0,0),
		('0000400002','00004',2,0,0,1,'4105','制造费用','','','','400',1,0,0,0,0,0),
		('0000400003','00004',2,0,0,1,'4107','劳务成本','','','','400',1,0,0,0,0,0),
		-------------------------------------------权益----------------------------------------------------------
		('0000500001','00005',2,0,0,1,'3101','实收资本（或股本）','','','','300',-1,0,0,0,0,0),
		('0000500002','00005',2,0,0,1,'3103','已归还投资','','','','300',1,0,0,0,0,0),
		('0000500003','00005',2,0,0,1,'3111','资本公积','','','','300',-1,0,0,0,0,0),
			('000050000300001','0000500003',3,0,0,1,'311101','资本（或股本）溢价','','','','300',-1,0,0,0,0,0),
			('000050000300002','0000500003',3,0,0,1,'311102','接受现金捐赠','','','','300',-1,0,0,0,0,0),
			('000050000300003','0000500003',3,0,0,1,'311103','接受捐赠非现金资产准备','','','','300',-1,0,0,0,0,0),
			('000050000300004','0000500003',3,0,0,1,'311104','股权投资准备','','','','300',-1,0,0,0,0,0),
			('000050000300005','0000500003',3,0,0,1,'311105','拨款转入','','','','300',-1,0,0,0,0,0),
			('000050000300006','0000500003',3,0,0,1,'311106','外币资本折算差额','','','','300',-1,0,0,0,0,0),
			('000050000300007','0000500003',3,0,0,1,'311107','其他资本公积','','','','300',-1,0,0,0,0,0),
		('0000500004','00005',2,0,0,1,'3121','盈余公积','','','','300',-1,0,0,0,0,0),
			('000050000400001','0000500004',3,0,0,1,'312101','法定盈余公积','','','','300',-1,0,0,0,0,0),
			('000050000400002','0000500004',3,0,0,1,'312102','任意盈余公积','','','','300',-1,0,0,0,0,0),
			('000050000400003','0000500004',3,0,0,1,'312103','法定公益金','','','','300',-1,0,0,0,0,0),
			('000050000400004','0000500004',3,0,0,1,'312104','储备基金','','','','300',-1,0,0,0,0,0),
			('000050000400005','0000500004',3,0,0,1,'312105','企业发展基金','','','','300',-1,0,0,0,0,0),
			('000050000400006','0000500004',3,0,0,1,'312106','利润归还投资','','','','300',-1,0,0,0,0,0),
		('0000500005','00005',2,0,0,1,'3131','本年利润','','','','300',-1,0,0,0,0,0),
		('0000500006','00005',2,0,0,1,'3141','利润分配','','','','300',-1,0,0,0,0,0),
			('000050000600001','0000500006',3,0,0,1,'314101','其他转入','','','','300',1,0,0,0,0,0),
			('000050000600002','0000500006',3,0,0,1,'314102','提取法定盈余公积','','','','300',1,0,0,0,0,0),
			('000050000600003','0000500006',3,0,0,1,'314103','提取法定公益金','','','','300',1,0,0,0,0,0),
			('000050000600004','0000500006',3,0,0,1,'314104','提取储备基金','','','','300',1,0,0,0,0,0),
			('000050000600005','0000500006',3,0,0,1,'314105','提取企业发展基金','','','','300',1,0,0,0,0,0),
			('000050000600006','0000500006',3,0,0,1,'314106','提取职工奖励及福利基金','','','','300',1,0,0,0,0,0),
			('000050000600007','0000500006',3,0,0,1,'314107','利润归还投资','','','','300',-1,0,0,0,0,0),
			('000050000600008','0000500006',3,0,0,1,'314108','应付优先股股利','','','','300',1,0,0,0,0,0),
			('000050000600009','0000500006',3,0,0,1,'314109','提取任意盈余公积','','','','300',1,0,0,0,0,0),
			('000050000600010','0000500006',3,0,0,1,'314110','应付普通股股利','','','','300',1,0,0,0,0,0),
			('000050000600011','0000500006',3,0,0,1,'314111','转作资本（或股本）的普通股股利','','','','300',1,0,0,0,0,0),
			('000050000600012','0000500006',3,0,0,1,'314115','未分配利润','','','','300',-1,0,0,0,0,0)


---------------------------------------------------------小企业会计准则科目----------------------------------------------------------------

INSERT INTO Ac_Account_Set_Detail(TypeId,ParId,Leveal,SonNum,SonCount,SubId,UserCode,FullName,Name,PyCode,Comment,[Group],Fdc,IsCash,IsBank,IsOther,fcontact,checktype) 
VALUES	----------------------------------分类---------------------------------------
		('00001','00002',1,0,0,2,'','资产','','','','100',-1,0,0,0,0,0),
		('00002','00002',1,0,0,2,'','负债','','','','200',-1,0,0,0,0,0),
		('00003','00002',1,0,0,2,'','损益','','','','500',-1,0,0,0,0,0),
		('00004','00002',1,0,0,2,'','成本','','','','400',-1,0,0,0,0,0),
		('00005','00002',1,0,0,2,'','权益','','','','300',-1,0,0,0,0,0),
		('00006','00002',1,0,0,2,'','共同','','','','700',-1,0,0,0,0,0),
		-----------------------------------资产---------------------------------------
		('0000100001','00001',2,0,0,2,'1001','库存现金','','','','101',1,1,0,0,0,0),
		('0000100002','00001',2,0,0,2,'1002','银行存款','','','','101',1,0,1,0,0,0),
		('0000100003','00001',2,0,0,2,'1012','其他货币资金','','','','101',1,0,0,1,0,0),
		('0000100004','00001',2,0,0,2,'1101','短期投资','','','','101',1,0,0,0,0,0),
		('0000100005','00001',2,0,0,2,'1121','应收票据','','','','101',1,0,0,0,0,0),
		('0000100006','00001',2,0,0,2,'1122','应收账款','','','','101',1,0,0,0,1,1),
		('0000100007','00001',2,0,0,2,'1123','预付账款','','','','101',1,0,0,0,1,2),
		('0000100008','00001',2,0,0,2,'1131','应收股利','','','','101',1,0,0,0,0,0),
		('0000100009','00001',2,0,0,2,'1132','应收利息','','','','101',1,0,0,0,0,0),
		('0000100010','00001',2,0,0,2,'1221','其他应收款','','','','101',1,0,0,0,1,1),
		('0000100011','00001',2,0,0,2,'1401','材料采购','','','','101',1,0,0,0,0,0),
		('0000100012','00001',2,0,0,2,'1402','在途物资','','','','101',1,0,0,0,0,0),
		('0000100013','00001',2,0,0,2,'1403','原材料','','','','101',1,0,0,0,0,0),
		('0000100014','00001',2,0,0,2,'1404','材料成本差异','','','','101',1,0,0,0,0,0),
		('0000100015','00001',2,0,0,2,'1405','库存商品','','','','101',1,0,0,0,0,0),
		('0000100016','00001',2,0,0,2,'1407','商品进销差价','','','','101',1,0,0,0,0,0),
		('0000100017','00001',2,0,0,2,'1408','委托加工物资','','','','101',1,0,0,0,0,0),
		('0000100018','00001',2,0,0,2,'1411','周转材料','','','','101',1,0,0,0,0,0),
		('0000100019','00001',2,0,0,2,'1421','消耗性生物资产','','','','101',1,0,0,0,0,0),
		('0000100020','00001',2,0,0,2,'1501','长期债权投资','','','','102',1,0,0,0,0,0),
		('0000100021','00001',2,0,0,2,'1511','长期股权投资','','','','102',1,0,0,0,0,0),
		('0000100022','00001',2,0,0,2,'1601','固定资产','','','','102',1,0,0,0,0,0),
		('0000100023','00001',2,0,0,2,'1602','累计折旧','','','','102',-1,0,0,0,0,0),
		('0000100024','00001',2,0,0,2,'1604','在建工程','','','','102',1,0,0,0,0,0),
		('0000100025','00001',2,0,0,2,'1605','工程物资','','','','102',1,0,0,0,0,0),
		('0000100026','00001',2,0,0,2,'1606','固定资产清理','','','','102',1,0,0,0,0,0),
		('0000100027','00001',2,0,0,2,'1621','生产性生物资产','','','','102',1,0,0,0,0,0),
		('0000100028','00001',2,0,0,2,'1622','生产性生物资产累计折旧','','','','102',-1,0,0,0,0,0),
		('0000100029','00001',2,0,0,2,'1701','无形资产','','','','102',1,0,0,0,0,0),
		('0000100030','00001',2,0,0,2,'1702','累计摊销','','','','102',-1,0,0,0,0,0),
		('0000100031','00001',2,0,0,2,'1801','长期待摊费用','','','','102',1,0,0,0,0,0),
		('0000100032','00001',2,0,0,2,'1901','待处理财产损溢','','','','101',1,0,0,0,0,0),
		('0000100033','00001',2,0,0,2,'1406','发出商品','','','','101',1,0,0,0,0,0),
		--------------------------------------------负债-----------------------------------
		('0000200001','00002',2,0,0,2,'2001','短期借款','','','','201',-1,0,0,0,0,0),
		('0000200002','00002',2,0,0,2,'2201','应付票据','','','','201',-1,0,0,0,0,0),
		('0000200003','00002',2,0,0,2,'2202','应付账款','','','','201',-1,0,0,0,1,2),
			('000020000300001','0000200003',3,0,0,2,'220201','应付货款','','','','201',-1,0,0,0,1,2),
			('000020000300002','0000200003',3,0,0,2,'220202','应付暂估','','','','201',-1,0,0,0,1,2),
		('0000200004','00002',2,0,0,2,'2203','预收账款','','','','201',-1,0,0,0,1,1),
		('0000200005','00002',2,0,0,2,'2211','应付职工薪酬','','','','201',-1,0,0,0,0,0),
		('0000200006','00002',2,0,0,2,'2221','应缴税费','','','','201',-1,0,0,0,0,0),
		('0000200007','00002',2,0,0,2,'2231','应付利息','','','','201',-1,0,0,0,0,0),
		('0000200008','00002',2,0,0,2,'2232','应付利润','','','','201',-1,0,0,0,0,0),
		('0000200009','00002',2,0,0,2,'2241','其他应付款','','','','201',-1,0,0,0,1,2),
		('0000200010','00002',2,0,0,2,'2401','递延收益','','','','201',-1,0,0,0,0,0),
		('0000200011','00002',2,0,0,2,'2501','长期借款','','','','202',-1,0,0,0,0,0),
		('0000200012','00002',2,0,0,2,'2701','长期应付款','','','','202',-1,0,0,0,0,0),
		--------------------------------------------损益-------------------------------------
		('0000300001','00003',2,0,0,2,'5001','主营业务收入','','','','501',-1,0,0,0,0,0),
		('0000300002','00003',2,0,0,2,'5051','其他业务收入','','','','504',-1,0,0,0,0,0),
		('0000300003','00003',2,0,0,2,'5111','投资收益','','','','504',-1,0,0,0,0,0),
		('0000300004','00003',2,0,0,2,'5301','营业外收入','','','','504',-1,0,0,0,0,0),
		('0000300005','00003',2,0,0,2,'5401','主营业务成本','','','','502',1,0,0,0,0,0),
		('0000300006','00003',2,0,0,2,'5402','其他业务支出','','','','505',1,0,0,0,0,0),
		('0000300007','00003',2,0,0,2,'5403','营业税金及附加','','','','502',1,0,0,0,0,0),
		('0000300008','00003',2,0,0,2,'5601','销售费用','','','','503',1,0,0,0,0,0),
		('0000300009','00003',2,0,0,2,'5602','管理费用','','','','503',1,0,0,0,0,0),
		('0000300010','00003',2,0,0,2,'5603','财务费用','','','','503',1,0,0,0,0,0),		
		('0000300011','00003',2,0,0,2,'5711','营业外支出','','','','505',1,0,0,0,0,0),
		('0000300012','00003',2,0,0,2,'5801','所得税费用','','','','507',1,0,0,0,0,0),
		--------------------------------------------成本------------------------------------
		('0000400001','00004',2,0,0,2,'4001','生产成本','','','','400',1,0,0,0,0,0),
		('0000400002','00004',2,0,0,2,'4101','制造费用','','','','400',1,0,0,0,0,0),
		('0000400003','00004',2,0,0,2,'4301','研发支出','','','','400',1,0,0,0,0,0),
		('0000400004','00004',2,0,0,2,'4401','工程施工','','','','400',1,0,0,0,0,0),
		('0000400005','00004',2,0,0,2,'4403','机械作业','','','','400',1,0,0,0,0,0),

		--------------------------------------------权益------------------------------------
		('0000500001','00005',2,0,0,2,'3001','实收资本','','','','300',-1,0,0,0,0,0),
		('0000500002','00005',2,0,0,2,'3002','资本公积','','','','300',-1,0,0,0,0,0),
		('0000500003','00005',2,0,0,2,'3101','盈余公积','','','','300',-1,0,0,0,0,0),
		('0000500004','00005',2,0,0,2,'3103','本年利润','','','','300',-1,0,0,0,0,0),
		('0000500005','00005',2,0,0,2,'3104','利润分配','','','','300',-1,0,0,0,0,0)


---------------------------------------------------------新会计准则科目----------------------------------------------------------------

INSERT INTO Ac_Account_Set_Detail(TypeId,ParId,Leveal,SonNum,SonCount,SubId,UserCode,FullName,Name,PyCode,Comment,[Group],Fdc,IsCash,IsBank,IsOther,fcontact,checktype) 
VALUES	----------------------------------分类---------------------------------------
		('00001','00028',1,0,0,28,'','资产','','','','100',-1,0,0,0,0,0),
		('00002','00028',1,0,0,28,'','负债','','','','200',-1,0,0,0,0,0),
		('00003','00028',1,0,0,28,'','损益','','','','500',-1,0,0,0,0,0),
		('00004','00028',1,0,0,28,'','成本','','','','400',-1,0,0,0,0,0),
		('00005','00028',1,0,0,28,'','权益','','','','300',-1,0,0,0,0,0),
		('00006','00028',1,0,0,28,'','共同','','','','700',-1,0,0,0,0,0),
		-----------------------------------资产---------------------------------------
		('0000100001','00001',2,0,0,28,'1001','库存现金','','','','101',1,1,0,0,0,0),
		('0000100002','00001',2,0,0,28,'1002','银行存款','','','','101',1,0,1,0,0,0),
		('0000100003','00001',2,0,0,28,'1012','其他货币资金','','','','101',1,0,0,1,0,0),
		('0000100004','00001',2,0,0,28,'1101','交易性金融资产','','','','101',1,0,0,0,0,0),
		('0000100005','00001',2,0,0,28,'1121','应收票据','','','','101',1,0,0,0,0,0),
		('0000100006','00001',2,0,0,28,'1122','应收账款','','','','101',1,0,0,0,1,1),
		('0000100007','00001',2,0,0,28,'1123','预付账款','','','','101',1,0,0,0,1,2),
		('0000100008','00001',2,0,0,28,'1131','应收股利','','','','101',1,0,0,0,0,0),
		('0000100009','00001',2,0,0,28,'1132','应收利息','','','','101',1,0,0,0,0,0),
		('0000100010','00001',2,0,0,28,'1221','其他应收款','','','','101',1,0,0,0,1,1),
		('0000100011','00001',2,0,0,28,'1231','坏账准备','','','','101',-1,0,0,0,0,0),
		('0000100012','00001',2,0,0,28,'1321','代理业务资产','','','','101',1,0,0,0,0,0),
		('0000100013','00001',2,0,0,28,'1401','材料采购','','','','101',1,0,0,0,0,0),
		('0000100014','00001',2,0,0,28,'1402','在途物资','','','','101',1,0,0,0,0,0),
		('0000100015','00001',2,0,0,28,'1403','原材料','','','','101',1,0,0,0,0,0),
		('0000100016','00001',2,0,0,28,'1404','材料成本差异','','','','101',1,0,0,0,0,0),
		('0000100017','00001',2,0,0,28,'1405','库存商品','','','','101',1,0,0,0,0,0),
		('0000100018','00001',2,0,0,28,'1406','发出商品','','','','101',1,0,0,0,0,0),
		('0000100019','00001',2,0,0,28,'1407','商品进销差价','','','','101',1,0,0,0,0,0),
		('0000100020','00001',2,0,0,28,'1408','委托加工物资','','','','101',1,0,0,0,0,0),
		('0000100046','00001',2,0,0,28,'1411','周转材料','','','','101',1,0,0,0,0,0),
		('0000100021','00001',2,0,0,28,'1471','存货跌价准备','','','','101',-1,0,0,0,0,0),
		('0000100022','00001',2,0,0,28,'1501','持有至到期投资','','','','101',1,0,0,0,0,0),
		('0000100023','00001',2,0,0,28,'1502','持有至到期投资减值准备','','','','101',-1,0,0,0,0,0),
		('0000100024','00001',2,0,0,28,'1503','可供出售金融资产','','','','101',1,0,0,0,0,0),
		('0000100025','00001',2,0,0,28,'1511','长期股权投资','','','','102',1,0,0,0,0,0),
		('0000100026','00001',2,0,0,28,'1512','长期股权投资减值准备','','','','102',-1,0,0,0,0,0),
		('0000100027','00001',2,0,0,28,'1521','投资性房地产','','','','101',1,0,0,0,0,0),
		('0000100028','00001',2,0,0,28,'1531','长期应收款','','','','102',1,0,0,0,0,0),
		('0000100029','00001',2,0,0,28,'1532','未实现融资收益','','','','102',1,0,0,0,0,0),
		('0000100030','00001',2,0,0,28,'1601','固定资产','','','','102',1,0,0,0,0,0),
		('0000100031','00001',2,0,0,28,'1602','累计折旧','','','','102',-1,0,0,0,0,0),
		('0000100032','00001',2,0,0,28,'1603','固定资产减值准备','','','','102',-1,0,0,0,0,0),
		('0000100033','00001',2,0,0,28,'1604','在建工程','','','','102',1,0,0,0,0,0),
		('0000100034','00001',2,0,0,28,'1605','工程物资','','','','102',1,0,0,0,0,0),
		('0000100035','00001',2,0,0,28,'1606','固定资产清理','','','','102',1,0,0,0,0,0),
		('0000100036','00001',2,0,0,28,'1701','无形资产','','','','102',1,0,0,0,0,0),
		('0000100037','00001',2,0,0,28,'1702','累计摊销','','','','102',-1,0,0,0,0,0),
		('0000100038','00001',2,0,0,28,'1703','无形资产减值准备','','','','102',-1,0,0,0,0,0),
		('0000100039','00001',2,0,0,28,'1711','商誉','','','','102',1,0,0,0,0,0),
		('0000100040','00001',2,0,0,28,'1801','长期待摊费用','','','','102',1,0,0,0,0,0),
		('0000100041','00001',2,0,0,28,'1811','递延所得税资产','','','','102',1,0,0,0,0,0),
		('0000100042','00001',2,0,0,28,'1901','待处理财产损溢','','','','101',1,0,0,0,0,0),
		--('0000100043','00001',2,0,0,28,'1261','委托代销商品','','','','101',1,0,0,0,0,0),
		--('0000100044','00001',2,0,0,28,'1271','受托代销商品','','','','101',1,0,0,0,0,0),
		('0000100045','00001',2,0,0,28,'1301','贴现资产','','','','101',1,0,0,0,0,0),
		--------------------------------------------负债-----------------------------------
		('0000200001','00002',2,0,0,28,'2001','短期借款','','','','201',-1,0,0,0,0,0),
		('0000200002','00002',2,0,0,28,'2101','交易性金融负债','','','','201',-1,0,0,0,0,0),
		('0000200003','00002',2,0,0,28,'2201','应付票据','','','','201',-1,0,0,0,0,0),
		('0000200004','00002',2,0,0,28,'2202','应付账款','','','','201',-1,0,0,0,1,2),
			('000020000400001','0000200004',3,0,0,28,'220201','应付货款','','','','201',-1,0,0,0,1,2),
			('000020000400002','0000200004',3,0,0,28,'220202','应付暂估','','','','201',-1,0,0,0,1,2),
		('0000200005','00002',2,0,0,28,'2203','预收账款','','','','201',-1,0,0,0,1,1),
		('0000200006','00002',2,0,0,28,'2211','应付职工薪酬','','','','201',-1,0,0,0,0,0),
		('0000200007','00002',2,0,0,28,'2221','应交税费','','','','201',-1,0,0,0,0,0),
		('0000200008','00002',2,0,0,28,'2231','应付利息','','','','201',-1,0,0,0,0,0),
		('0000200009','00002',2,0,0,28,'2232','应付股利','','','','201',-1,0,0,0,0,0),
		('0000200010','00002',2,0,0,28,'2241','其他应付款','','','','201',-1,0,0,0,1,2),
		('0000200011','00002',2,0,0,28,'2314','代理业务负债','','','','201',-1,0,0,0,0,0),
		('0000200012','00002',2,0,0,28,'2401','递延收益','','','','201',-1,0,0,0,0,0),
		('0000200013','00002',2,0,0,28,'2501','长期借款','','','','202',-1,0,0,0,0,0),
		('0000200014','00002',2,0,0,28,'2502','长期债券','','','','202',-1,0,0,0,0,0),
		('0000200015','00002',2,0,0,28,'2701','长期应付款','','','','202',-1,0,0,0,0,0),
		('0000200016','00002',2,0,0,28,'2702','未确认融资费用','','','','202',-1,0,0,0,0,0),
		('0000200017','00002',2,0,0,28,'2711','专项应付款','','','','202',-1,0,0,0,0,0),
		('0000200018','00002',2,0,0,28,'2801','预计负债','','','','201',-1,0,0,0,0,0),
		('0000200019','00002',2,0,0,28,'2901','递延所得税负债','','','','202',-1,0,0,0,0,0),
		('0000200020','00002',2,0,0,28,'2141','代销商品款','','','','201',-1,0,0,0,0,0),
		--------------------------------------------损益-------------------------------------
		('0000300001','00003',2,0,0,28,'6001','主营业务收入','','','','501',-1,0,0,0,0,0),
		('0000300002','00003',2,0,0,28,'6051','其他业务收入','','','','504',-1,0,0,0,0,0),
		('0000300003','00003',2,0,0,28,'6101','公允价值变动损益','','','','504',-1,0,0,0,0,0),
		('0000300004','00003',2,0,0,28,'6111','投资收益','','','','504',-1,0,0,0,0,0),
		('0000300005','00003',2,0,0,28,'6301','营业外收入','','','','504',-1,0,0,0,0,0),
		('0000300006','00003',2,0,0,28,'6401','主营业务成本','','','','502',1,0,0,0,0,0),
		('0000300007','00003',2,0,0,28,'6402','其他业务成本','','','','505',1,0,0,0,0,0),
		('0000300008','00003',2,0,0,28,'6403','营业税金及附加','','','','502',1,0,0,0,0,0),
		('0000300009','00003',2,0,0,28,'6601','销售费用','','','','503',1,0,0,0,0,0),
		('0000300010','00003',2,0,0,28,'6602','管理费用','','','','503',1,0,0,0,0,0),
		('0000300011','00003',2,0,0,28,'6603','财务费用','','','','503',1,0,0,0,0,0),
		('0000300012','00003',2,0,0,28,'6604','勘探费用','','','','503',1,0,0,0,0,0),
		('0000300013','00003',2,0,0,28,'6701','资产减值损失','','','','505',1,0,0,0,0,0),
		('0000300014','00003',2,0,0,28,'6711','营业外支出','','','','505',1,0,0,0,0,0),
		('0000300015','00003',2,0,0,28,'6801','所得税','','','','507',1,0,0,0,0,0),
		('0000300016','00003',2,0,0,28,'6901','以前年度损益调整','','','','506',-1,0,0,0,0,0),
		--------------------------------------------成本------------------------------------
		('0000400001','00004',2,0,0,28,'5001','生产成本','','','','400',1,0,0,0,0,0),
		('0000400002','00004',2,0,0,28,'5101','制造费用','','','','400',1,0,0,0,0,0),
		('0000400003','00004',2,0,0,28,'5201','劳务成本','','','','400',1,0,0,0,0,0),
		('0000400004','00004',2,0,0,28,'5301','研发支出','','','','400',1,0,0,0,0,0),
		--------------------------------------------权益------------------------------------
		('0000500001','00005',2,0,0,28,'4001','实收资本','','','','300',-1,0,0,0,0,0),
		('0000500002','00005',2,0,0,28,'4002','资本公积','','','','300',-1,0,0,0,0,0),
		('0000500003','00005',2,0,0,28,'4101','盈余公积','','','','300',-1,0,0,0,0,0),
		('0000500004','00005',2,0,0,28,'4103','本年利润','','','','300',-1,0,0,0,0,0),
		('0000500005','00005',2,0,0,28,'4104','利润分配','','','','300',-1,0,0,0,0,0),
		('0000500006','00005',2,0,0,28,'4201','库存股','','','','300',-1,0,0,0,0,0),
		-------------------------------------------共同---------------------------------------
		('0000600001','00006',2,0,0,28,'3101','衍生工具','','','','700',1,0,0,0,0,0),
		('0000600002','00006',2,0,0,28,'3201','套期工具','','','','700',1,0,0,0,0,0),
		('0000600003','00006',2,0,0,28,'3202','被套期项目','','','','700',1,0,0,0,0,0)


---------------------------------------------------------GRASP科目表----------------------------------------------------------------

INSERT INTO Ac_Account_Set_Detail(TypeId,ParId,Leveal,SonNum,SonCount,SubId,UserCode,FullName,Name,PyCode,Comment,[Group],Fdc,IsCash,IsBank,IsOther,fcontact,checktype) 
VALUES	----------------------------------分类---------------------------------------
		('00001','00029',1,0,0,29,'','资产','','','','100',-1,0,0,0,0,0),
		('00002','00029',1,0,0,29,'','负债','','','','200',-1,0,0,0,0,0),
		('00003','00029',1,0,0,29,'','损益','','','','500',-1,0,0,0,0,0),
		('00004','00029',1,0,0,29,'','成本','','','','400',-1,0,0,0,0,0),
		('00005','00029',1,0,0,29,'','权益','','','','300',-1,0,0,0,0,0),
		('00006','00029',1,0,0,29,'','共同','','','','700',-1,0,0,0,0,0),
		--------------------------------------------资产------------------------------------
		('0000100001','00001',2,0,0,29,'1001','现金','','','','101',1,1,0,0,0,0),
		('0000100002','00001',2,0,0,29,'1002','固定资产__甲','','','','102',1,0,0,0,0,0),
		('0000100004','00001',2,0,0,29,'1004','内部应收','','','','104',1,0,0,0,0,0),
		('0000100005','00001',2,0,0,29,'1005','其他应收款','','','','105',1,0,0,0,1,1),
		('0000100006','00001',2,0,0,29,'1006','预付账款','','','','106',1,0,0,0,1,2),
		('0000100007','00001',2,0,0,29,'1007','库存商品','','','','107',1,0,0,0,0,0),
		('0000100008','00001',2,0,0,29,'1008','委托代销','','','','108',1,0,0,0,0,0),
		('0000100009','00001',2,0,0,29,'1009','待摊费用','','','','109',1,0,0,0,0,0),
		('0000100010','00001',2,0,0,29,'1010','中国银行','','','','110',1,0,1,0,0,0),
		('0000100011','00001',2,0,0,29,'1011','应收账款','','','','111',1,0,0,0,1,1),
		('0000100012','00001',2,0,0,29,'1012','资产折旧','','','','307',-1,0,0,0,0,0),

		--------------------------------------------负债-----------------------------------
		('0000200001','00002',2,0,0,29,'2001','应付账款','','','','201',-1,0,0,0,1,2),
		('0000200002','00002',2,0,0,29,'2002','其他应付款','','','','202',-1,0,0,0,1,2),
		('0000200003','00002',2,0,0,29,'2003','代销款','','','','203',-1,0,0,0,0,0),
		('0000200004','00002',2,0,0,29,'2004','应交税金','','','','204',-1,0,0,0,0,0),
		('0000200005','00002',2,0,0,29,'2005','预收账款','','','','205',-1,0,0,0,1,1),
		('0000200006','00002',2,0,0,29,'2006','会员储值','','','','206',-1,0,0,0,0,0),
		--------------------------------------------损益------------------------------------
		('0000300001','00003',2,0,0,29,'3001','销售折扣返利支出','','','','501',1,0,0,0,0,0),
		('0000300002','00003',2,0,0,29,'3002','商品报损','','','','502',1,0,0,0,0,0),
		('0000300003','00003',2,0,0,29,'3003','商品赠出','','','','503',1,0,0,0,0,0),
		('0000300004','00003',2,0,0,29,'3004','商品维修支出','','','','504',1,0,0,0,0,0),
		('0000300005','00003',2,0,0,29,'3005','商品送修支出','','','','505',1,0,0,0,0,0),
		('0000300006','00003',2,0,0,29,'3006','调账亏损','','','','501',1,0,0,0,0,0),
        ('0000300007','00003',2,0,0,29,'3007','其他','','','','501',1,0,0,0,0,0),
        ('0000300008','00003',2,0,0,29,'3008','优惠金额','','','','501',1,0,0,0,0,0),
        ('0000300009','00003',2,0,0,29,'3009','销售成本','','','','503',1,0,0,0,0,0),
        ('0000300010','00003',2,0,0,29,'3010','商品获赠','','','','504',-1,0,0,0,0,0),
        ('0000300011','00003',2,0,0,29,'3011','调价收入','','','','502',-1,0,0,0,0,0),
        ('0000300012','00003',2,0,0,29,'3012','结算差价','','','','502',-1,0,0,0,0,0),
        ('0000300013','00003',2,0,0,29,'3013','调拨差价','','','','501',-1,0,0,0,0,0),
        ('0000300014','00003',2,0,0,29,'3014','拆装差价','','','','501',-1,0,0,0,0,0),
        ('0000300015','00003',2,0,0,29,'3015','维修收入','','','','503',-1,0,0,0,0,0),
        ('0000300016','00003',2,0,0,29,'3016','受托退货差价','','','','501',-1,0,0,0,0,0),
        ('0000300017','00003',2,0,0,29,'3017','利息收入','','','','502',-1,0,0,0,0,0),
        ('0000300018','00003',2,0,0,29,'3018','其他','','','','503',-1,0,0,0,0,0),
        ('0000300019','00003',2,0,0,29,'3019','销售收入','','','','501',-1,0,0,0,0,0),
        ('0000300020','00003',2,0,0,29,'3020','返点获利收入','','','','501',-1,0,0,0,0,0),
        ('0000300021','00003',2,0,0,29,'3021','调账收入','','','','501',-1,0,0,0,0,0),
		('0000300022','00003',2,0,0,29,'3022','商品报溢收入','','','','505',-1,0,0,0,0,0)
		--------------------------------------------成本------------------------------------
		
		--------------------------------------------权益------------------------------------
		
		--------------------------------------------共同------------------------------------


GO	


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT_SET_DETAIL') AND name = 'CIX_AC_ACCOUNT_SET_DETAIL_Subid')
--DROP INDEX CIX_AC_ACCOUNT_SET_DETAIL_Subid ON AC_ACCOUNT_SET_DETAIL 
CREATE CLUSTERED INDEX CIX_AC_ACCOUNT_SET_DETAIL_Subid ON AC_ACCOUNT_SET_DETAIL(Subid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT_SET_DETAIL') AND name = 'NCIX_AC_ACCOUNT_SET_DETAIL_Pycode')
--DROP INDEX NCIX_AC_ACCOUNT_SET_DETAIL_Pycode ON AC_ACCOUNT_SET_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_ACCOUNT_SET_DETAIL_Pycode ON AC_ACCOUNT_SET_DETAIL(Pycode) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (	SELECT 1
            FROM  sysobjects
			WHERE  id = object_id('Ac_Account_Set_List')
            AND   type = 'U')
BEGIN
	CREATE TABLE Ac_Account_Set_List (
   		   SubId                int                  not null,
		   FullName             varchar(200)         not null,
		   Len1                 int                  null,
		   Len2                 int                  null,
		   Len3                 int                  null,
		   Len4                 int                  null,
		   Len5                 int                  null,
		   Len6                 int                  null,
		   Len7                 int                  null,
		   Len8                 int                  null,
		   Len9                 int                  null,
		   Len10                int                  null,
		   Cash                 varchar(200)         null,
		   Bank                 varchar(200)         null,
		   Asset                varchar(200)         null,
		   Depr                 varchar(200)         null,
		   Earn                 varchar(200)         null,
		   IsVisible			int					 null,
		   Comment              varchar(400)         null
	)	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account_Set_List' AND a.Name='IsUse'
)
BEGIN
	ALTER TABLE Ac_Account_Set_List 
		ADD IsUse INT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Account_Set_List' AND a.Name='IsVisible'
)
BEGIN
	ALTER TABLE Ac_Account_Set_List 
		ADD IsVisible INT NULL DEFAULT(1)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ACCOUNT_SET_LIST') AND name = 'CIX_AC_ACCOUNT_SET_LIST_Subid')
--DROP INDEX CIX_AC_ACCOUNT_SET_LIST_Subid ON AC_ACCOUNT_SET_LIST 
CREATE CLUSTERED INDEX CIX_AC_ACCOUNT_SET_LIST_Subid ON AC_ACCOUNT_SET_LIST(Subid) 
------------------------------------------创建索引区域结束-----------------------------------------------
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account_Set_List)
BEGIN
	DELETE FROM Ac_Account_Set_List
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	1,'企业会计制度科目',4,2,2,2,'1001'	,'1002','1501','1502','3131',1)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	2,'小企业会计准则科目',4,2,2,2,'1001','1002','1501','1502','3131',1)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	3,'工业企业',	3,1,2,2,'101','102','161','165','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	4,'商品流通企业',3,1,2,2,'101','102','171','175','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	5,'旅游饮食服务企业',3,1,2,2,'101','102','151','155','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	6,'运输（交通）企业',3,1,2,2,'101','102','161','165','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	7,'运输（民用航空）企业',3,1,2,2,'101','102','161','165','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	8,'运输（铁路）企业',3,1,2,2,'101','102','161','165','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	9,'房地产开发企业',3,1,2,2,'101','102','151','155','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	10,'施工企业',3,1,2,2,'101','102','151','155','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	11,'金融企业',4,2,2,2,'1001','1002','1801','1802','3131',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	12,'保险企业',4,2,2,2,'1001','1002','1601','1602','3141',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	13,'对外经济合作企业',3,2,2,2,'101','102','171','172','351',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	14,'邮电通信企业',3,1,2,2,'101','102','161','165','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	15,'农业企业',3,1,2,2,'101','102','151','155','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	16,'股份制企业',4,2,2,2,'1001','1002','1501','1502','3131',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	17,'外商投资企业',4,2,2,2,'1101','1111','1601','1611','3301',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	18,'事业单位',3,1,2,2,'101','102','120','','302',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	19,'行政单位',3,1,2,2,'101','102','106','','302',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	20,'建筑安装企业',4,2,2,2,'1001','1002','1501','1502','3131',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	21,'商品期货企业',4,2,2,2,'1001','1002','1501','1502','3131',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	22,'地质勘查企业',3,1,2,2,'101','102','151','155','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	23,'国有建设单位',3,1,2,2,'233','232','201','202','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	24,'勘察设计企业',3,1,2,2,'101','102','161','165','321',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	25,'证券行业',4,2,2,2,'1001','1002','1501','1502','3141',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	26,'财政总预算',3,1,2,2,'','','','','',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	27,'农经系统',3,2,3,2,'101','102','108','109','305',0)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	28,'新会计准则科目',4,2,2,2,'1001','1002','1501','1602','4103',1)
	INSERT INTO Ac_Account_Set_List(SubId,FullName,Len1,Len2,Len3,Len4,Cash,Bank,Asset,Depr,Earn,IsVisible) VALUES(	29,'GRASP科目表',4,2,NULL,NULL,'1001','1012','1002','3007',NULL,1)
END
GO
UPDATE Ac_Account_Set_List SET IsUse = 0 WHERE IsUse IS NULL
GO
UPDATE Ac_Account_Set_List SET IsVisible = 1 WHERE IsVisible IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('Ac_Account_Table') AND type = 'U')   
BEGIN
	CREATE TABLE Ac_Account_Table (
		StypeId				VARCHAR(50)         NOT NULL,
		TypeId              VARCHAR(50)         NOT NULL,
		ParId               VARCHAR(50)         NOT NULL,
		Leveal              INT                 NOT NULL,
		SonNum              INT                 NOT NULL,
		SonCount            INT                 NOT NULL,
		UserCode            VARCHAR(200)        NOT NULL,
		FullName            VARCHAR(200)        NOT NULL,
		Name                VARCHAR(200)        NULL,
		Fdc                 INT                 NULL,
		IsCash              INT                 NULL DEFAULT 0,
		IsBank              INT                 NULL DEFAULT 0,
		IsDiary             INT                 NULL DEFAULT 0,
		IsPreGather         INT                 NULL DEFAULT 0,
		IsPrePay            INT                 NULL DEFAULT 0,
		IsGather            INT                 NULL DEFAULT 0,
		IsPay               INT                 NULL DEFAULT 0,
		IsVip               INT                 NULL DEFAULT 0,		
		Comment             VARCHAR(400)        NULL,
		PyCode              VARCHAR(200)        NULL,
		ETypeId             VARCHAR(50)         NOT NULL,
		CreateDATETIME      DATETIME            NOT NULL,
		MainItems           VARCHAR(100)        NULL,
		AdditionItems       VARCHAR(100)        NULL,
		ExchId              INT                 NULL,
		FAcctINT            INT                 NULL,
		FAcnt               INT                 NULL DEFAULT 0,
		AscIds              VARCHAR(200)		NULL,
		FAdjustRate         INT                 NULL DEFAULT 0,
		FContact            INT                 NULL DEFAULT 0,
		FINTerest           INT                 NULL DEFAULT 0,
		FINTRate            NUMERIC(24,10)       NULL,
		FLeveal             INT					NOT NULL DEFAULT(0),
		Deleted				INT					NOT NULL DEFAULT(0),
		XiWaMaxNumber		INT					NOT NULL DEFAULT(0),
		IsOther				INT					NOT NULL DEFAULT(0),
		Cid					INT					NULL DEFAULT(-1),
		IsDist				INT					NULL DEFAULT(0),
		KeyId				BIGINT				NOT NULL Identity(1,1),
		[Group]				VARCHAR(10)			NULL,
		CheckType			INT					NULL DEFAULT(0),
		AdjustAccounts		BIT					DEFAULT(0),
		UnitID				INT					DEFAULT(0)
	)
END
GO
------------------------------------------------------修改表------------------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Account_Table') AND name = 'CIX_Ac_Account_Table_Typeid')
	CREATE CLUSTERED INDEX CIX_Ac_Account_Table_Typeid ON Ac_Account_Table(Typeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Account_Table') AND name = 'NCIX_Ac_Account_Table_Stypeid_Parid')
	CREATE NONCLUSTERED INDEX NCIX_Ac_Account_Table_Stypeid_Parid ON Ac_Account_Table(Stypeid,Parid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Account_Table') AND name = 'NCIX_Ac_Account_Table_Usercode')
	CREATE NONCLUSTERED INDEX NCIX_Ac_Account_Table_Usercode ON Ac_Account_Table(Usercode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Account_Table') AND name = 'NCIX_Ac_Account_Table_Fullname')
	CREATE NONCLUSTERED INDEX NCIX_Ac_Account_Table_Fullname ON Ac_Account_Table(Fullname) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------------------修改数据------------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
                             
------------------------------------------修改字段小数位数区域结束-----------------------------------------------




if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_AccountsPeroid_Stype')
            and   type = 'U')
BEGIN
	create table Ac_AccountsPeroid_Stype (
	   Id	INT IDENTITY(1,1),
	   Stypeid	VARCHAR(50),
	   FYear	INT,
	   FPeriod	INT
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AccountsPeroid_Stype' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE Ac_AccountsPeroid_Stype ADD FYear INT
END
GO
--启用年度
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AccountsPeroid_Stype' AND a.Name='SFYear'
)
BEGIN
	ALTER TABLE Ac_AccountsPeroid_Stype ADD SFYear INT NULL DEFAULT(0)
END
GO
--启用期间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AccountsPeroid_Stype' AND a.Name='SFPeriod'
)
BEGIN
	ALTER TABLE Ac_AccountsPeroid_Stype ADD SFPeriod INT NULL DEFAULT(0)
END
GO
--是否开账
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AccountsPeroid_Stype' AND a.Name='IsUse'
)
BEGIN
	ALTER TABLE Ac_AccountsPeroid_Stype ADD IsUse BIT NOT NULL DEFAULT(0)
END
GO
--是否默认数据
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AccountsPeroid_Stype' AND a.Name='SysRow'
)
BEGIN
	ALTER TABLE Ac_AccountsPeroid_Stype ADD SysRow BIT NOT NULL DEFAULT(0)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 
---预制数据
--======================================默认数据==============================
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype)
	BEGIN
		SET IDENTITY_INSERT dbo.Ac_AccountsPeroid_Stype ON
		INSERT INTO Ac_AccountsPeroid_Stype(Id,Stypeid,FYear,FPeriod,SFYear,SFPeriod,IsUse,SysRow)
		VALUES(1,'00001',0,0,0,0,0,1)
		SET IDENTITY_INSERT dbo.Ac_AccountsPeroid_Stype OFF
	END



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_AssetBusinessType') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AssetBusinessType
	(
		Id					INT IDENTITY(1,1),
		BusinessType		INT,--0  增加 1：减少 2：部门转移 3：计提减值准备 4:折旧
		FullName			VARCHAR(66),
		Atid				INT,
		AuditType			INT,
		STypeId				VARCHAR(50),--分支机构
		Deleted	BIT NOT NULL DEFAULT(0)--特殊处理 1表示启用 0表示未启用
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetBusinessType' AND a.Name='Deleted'
)
BEGIN
	ALTER TABLE Ac_AssetBusinessType ADD Deleted BIT NOT NULL DEFAULT (0)
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetBusinessType' AND a.Name='BillType'
)
BEGIN
	ALTER TABLE Ac_AssetBusinessType DROP COLUMN BillType
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetBusinessType' AND a.Name='Atid'
)
BEGIN
	ALTER TABLE Ac_AssetBusinessType ADD Atid INT NULL
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetBusinessType' AND a.Name='SysRow'
)
BEGIN
	ALTER TABLE Ac_AssetBusinessType DROP COLUMN SysRow
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetBusinessType' AND a.Name='AuditType'
)
BEGIN
	ALTER TABLE Ac_AssetBusinessType ADD AuditType INT DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetBusinessType' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_AssetBusinessType ADD STypeId VARCHAR(50) DEFAULT('')
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetBusinessType)
	BEGIN
		SET IDENTITY_INSERT dbo.Ac_AssetBusinessType ON
		
		INSERT INTO Ac_AssetBusinessType(Id,BusinessType,FullName,Atid,AuditType,STypeid,Deleted) 
		SELECT 1,0,'购入（原值含税）',NULL,1,'00001',1 UNION 
		SELECT 2,0,'购入（原值不含税）',NULL,2,'00001',1 UNION 
		SELECT 3,0,'自建工程',NULL,3,'00001',1 UNION 
		--SELECT 4,0,'接受投资',NULL,4,1 UNION 
		SELECT 4,0,'接受捐赠',NULL,5,'00001',1 UNION 
		SELECT 5,0,'盘盈',NULL,6,'00001',1 UNION 
		SELECT 6,1,'变卖',NULL,7,'00001',1 UNION 
		SELECT 7,1,'报废',NULL,8,'00001',1 UNION 
		SELECT 8,1,'投资转出',NULL,9,'00001',1 UNION 
		SELECT 9,1,'捐赠转出',NULL,10,'00001',1 UNION 
		SELECT 10,1,'盘亏',NULL,11,'00001',1 UNION 
		SELECT 11,2,'部门转移',NULL,12,'00001',1 UNION 
		SELECT 12,3,'计提减值准备',NULL,13,'00001',1 UNION 
		SELECT 13,4,'折旧',NULL,14,'00001',1  
		
		SET IDENTITY_INSERT dbo.Ac_AssetBusinessType OFF
	END
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_AssetsCards') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AssetsCards
	(
		Id				INT IDENTITY(1,1),	
		TypeId			VARCHAR(50) NULL,
		Parid			VARCHAR(50)	NULL,
		UserCode		VARCHAR(200)NULL,
		FullName		VARCHAR(200)	NULL,
		STypeId			VARCHAR(50)	NULL,
		AssertATypeId	VARCHAR(50)	NULL,
		DepATypeId		VARCHAR(50)	NULL,
		DisATypeId		VARCHAR(50)	NULL,
		DevalueATypeId	VARCHAR(50)	NULL,
		CategoryId		INT	NULL,
		LocationId		INT	NULL,
		ConditionId		INT	NULL,
		Size			VARCHAR(200)NULL,
		DTypeid			VARCHAR(50)	NULL,
		InAccountDate		DATETIME	NULL,
		BusinessTypeId		INT	NULL,
		Total				NUMERIC(22,10)	NULL,
		Cid					INT	NULL,	
		F_Total				NUMERIC(22,10)	NULL,
		Rate				NUMERIC(18,4)	NULL,
		DepTotal			NUMERIC(22,10)	NULL,
		DevalueReady		NUMERIC(22,10)	NULL,
		NetValue			NUMERIC(22,10)	NULL,
		NetSalvage			NUMERIC(22,10)	NULL,
		NetSalvageRate		NUMERIC(18,4)	NULL,
		DepreciationMean	INT	NULL,	
		DurYear				INT	NULL,
		DepreciationMonth 	INT	NULL,
		Units				VARCHAR(200) NULL,
		Comment				VARCHAR(400)NULL,
		AssetsState			INT	NULL,
		OperationDate		DATETIME,
		ETypeId				VARCHAR(50),
		BarCode				VARCHAR(200) NULL DEFAULT '',
		ExpectWork			NUMERIC(18,2) NULL DEFAULT(0),
		FinishWork			NUMERIC(18,2) NULL DEFAULT(0),
		WorkUnit			VARCHAR(50) NULL DEFAULT '',
		Qty					NUMERIC(24,10) NULL DEFAULT(0),
		XiWaMaxNumber		NUMERIC(18, 0) NULL DEFAULT (0)
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='durmonth'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ADD durmonth INT	NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='XiWaMaxNumber'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ADD XiWaMaxNumber NUMERIC(18, 0) NULL DEFAULT (0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='DevalueATypeId'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ADD DevalueATypeId VARCHAR(50)	NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='NetValue'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ADD NetValue NUMERIC(22,10)	NULL
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='ParentId'
)
BEGIN
	ALTER TABLE Ac_AssetsCards DROP COLUMN ParentID
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='Parid'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ADD Parid VARCHAR(50)NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='OperationDate'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ADD OperationDate DATETIME
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='ETypeId'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ADD ETypeId VARCHAR(50)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='Units'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ADD Units VARCHAR(200) DEFAULT ''
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='UserCode'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ALTER COLUMN UserCode VARCHAR(200)
END
GO 
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='FullName'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ALTER COLUMN FullName VARCHAR(200)
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='Size'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ALTER COLUMN Size VARCHAR(200)
END
GO

--2014.04.03添加“固定资产条码”、“预计工作量”、“已提工作量”、“工作量单位”
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='BarCode'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards ADD BarCode VARCHAR(200) NULL DEFAULT ''
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='ExpectWork'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards ADD ExpectWork NUMERIC(18,2) NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='FinishWork'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards ADD FinishWork NUMERIC(18,2) NULL 
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='WorkUnit'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards ADD WorkUnit VARCHAR(50) NULL DEFAULT ''
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='Qty'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards ADD Qty NUMERIC(24,10) DEFAULT(0)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='F_Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN F_Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='DepTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN DepTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='DevalueReady' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN DevalueReady NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='NetValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN NetValue NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='NetSalvage' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN NetSalvage NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='NetSalvageRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN NetSalvageRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='ExpectWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN ExpectWork NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards' AND a.Name='FinishWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards 
	ALTER COLUMN FinishWork NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO
--升级处理固定资产卡片表里面qty为null或是0的数据
UPDATE Ac_AssetsCards SET Qty = 1 WHERE Qty IS NULL OR Qty = 0
GO



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_AssetsCards_History') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AssetsCards_History
	(
		Id				INT IDENTITY(1,1),
		AssertsCardId	INT,	
		TypeId			VARCHAR(50) NULL,
		Parid			VARCHAR(50)	NULL,
		UserCode		VARCHAR(200)NULL,
		FullName		VARCHAR(200)NULL,
		STypeId			VARCHAR(50)	NULL,
		AssertATypeId	VARCHAR(50)	NULL,
		DepATypeId		VARCHAR(50)	NULL,
		DisATypeId		VARCHAR(50)	NULL,
		DevalueATypeId	VARCHAR(50)	NULL,
		CategoryId		INT	NULL,
		LocationId		INT	NULL,
		ConditionId		INT	NULL,
		Size			VARCHAR(200)NULL,
		DTypeid			VARCHAR(50)	NULL,
		InAccountDate		DATETIME	NULL,
		BusinessTypeId		INT	NULL,
		Total				NUMERIC(22,10)	NULL,
		Cid					INT	NULL,	
		F_Total				NUMERIC(22,10)	NULL,
		Rate				NUMERIC(18,4)	NULL,
		DepTotal			NUMERIC(22,10)	NULL,
		DevalueReady		NUMERIC(22,10)	NULL,
		NetValue			NUMERIC(22,10)	NULL,
		NetSalvage			NUMERIC(22,10)	NULL,
		NetSalvageRate		NUMERIC(18,4)	NULL,
		DepreciationMean	INT	NULL,	
		DurYear				INT	NULL,
		DepreciationMonth 	INT	NULL,
		Comment				VARCHAR(400)NULL,
		AssetsState			INT	NULL,
		BusinessDate		DATETIME,
		OperationDate		DATETIME,
		ETypeId				VARCHAR(50),
		BillId				INT,
		BillType			INT,
		AuditType			INT,
		BarCode				VARCHAR(200) NULL DEFAULT '',
		ExpectWork			NUMERIC(18,2) NULL DEFAULT(0),
		FinishWork			NUMERIC(18,2) NULL DEFAULT(0),
		WorkUnit			VARCHAR(50) NULL DEFAULT ''
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='durmonth'
)
BEGIN
	ALTER TABLE Ac_AssetsCards_History ADD durmonth INT NOT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='Id'
)
BEGIN
	ALTER TABLE Ac_AssetsCards_History ADD Id INT IDENTITY(1,1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='BusinessDate'
)
BEGIN
	ALTER TABLE Ac_AssetsCards_History ADD BusinessDate DATETIME
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='BillType'
)
BEGIN
	ALTER TABLE Ac_AssetsCards_History ADD BillType INT
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='UserCode'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ALTER COLUMN UserCode VARCHAR(200)
END
GO 
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='FullName'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ALTER COLUMN FullName VARCHAR(200)
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='Size'
)
BEGIN
	ALTER TABLE Ac_AssetsCards ALTER COLUMN Size VARCHAR(200)
END
GO

--2014.04.09添加“固定资产条码”、“预计工作量”、“已提工作量”、“工作量单位”
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='BarCode'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards_History ADD BarCode VARCHAR(200) NULL DEFAULT ''
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='ExpectWork'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards_History ADD ExpectWork NUMERIC(18,2) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='FinishWork'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards_History ADD FinishWork NUMERIC(18,2) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='WorkUnit'
)
BEGIN
	ALTER TABLE dbo.Ac_AssetsCards_History ADD WorkUnit VARCHAR(50) NULL DEFAULT ''
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='F_Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN F_Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='DepTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN DepTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='DevalueReady' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN DevalueReady NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='NetValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN NetValue NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='NetSalvage' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN NetSalvage NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='NetSalvageRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN NetSalvageRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='ExpectWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN ExpectWork NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCards_History' AND a.Name='FinishWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCards_History 
	ALTER COLUMN FinishWork NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_AssetsCardsState') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AssetsCardsState
	(
		Id	INT,
		Comment	VARCHAR(200)
	)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCardsState)
BEGIN
	INSERT INTO dbo.Ac_AssetsCardsState( Id, Comment )
	VALUES  (1,'初始'),
			(2,'未入账'),
			(3,'已入账'),
			(4,'已提折旧'),
			(5,'已清理'),
			(6,'拆分中'),
			(7,'已作废')
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_AssetsCategory') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AssetsCategory
	(
		Id					INT IDENTITY(1,1),
		StypeId				VARCHAR(50) NULL,
		UserCode			VARCHAR(26) NULL,
		FullName			VARCHAR(66) NULL,
		Units				VARCHAR(200) NULL,
		DepreciationMean	INT NULL,
		DurYear				INT NULL,
		RemainsRate			NUMERIC(18,4) NULL,
		DepATypeId			VARCHAR(50) NULL,
		ExpenseATypeId		VARCHAR(50) NULL,
		AssertATypeId		VARCHAR(50) NULL,
		Deleted				BIT NOT NULL DEFAULT(0),
		Comment				VARCHAR(256) NULL
	)
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCategory' AND a.Name='StypeId'
)
BEGIN
	ALTER TABLE Ac_AssetsCategory ADD STypeID VARCHAR(50) NULL
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCategory' AND a.Name='DepreciationMean'
)
BEGIN
	ALTER TABLE Ac_AssetsCategory ALTER COLUMN DepreciationMean INT NULL
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCategory' AND a.Name='Unit'
)
BEGIN
	ALTER TABLE Ac_AssetsCategory DROP COLUMN Unit
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCategory' AND a.Name='UnitsId'
)
BEGIN
	ALTER TABLE Ac_AssetsCategory ADD UnitsId INT NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCategory' AND a.Name='Deleted'
)
BEGIN
	ALTER TABLE Ac_AssetsCategory ADD Deleted BIT NOT NULL DEFAULT (0)
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCategory' AND a.Name='UnitsId'
)
BEGIN
	ALTER TABLE Ac_AssetsCategory DROP COLUMN UnitsId
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCategory' AND a.Name='Units'
)
BEGIN
	ALTER TABLE Ac_AssetsCategory ADD Units VARCHAR(200) DEFAULT ''
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsCategory' AND a.Name='RemainsRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_AssetsCategory 
	ALTER COLUMN RemainsRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_AssetsModifyRecords') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AssetsModifyRecords
	(
		Id		INT IDENTITY(1,1),
		CardId	INT,
		OldDTypeId	VARCHAR(50),
		DTypeId		VARCHAR(50),
		OldLocationId	INT,
		LocationId		INT,
		OldDisATypeId	VARCHAR(50),
		DisATypeId		VARCHAR(50),
		BusinessDate	DATETIME,
		OperationDate	DATETIME,
		ETypeId			VARCHAR(50)
	)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsModifyRecords' AND a.Name='OldSTypeId'
)
BEGIN
	ALTER TABLE Ac_AssetsModifyRecords DROP COLUMN OldSTypeId
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsModifyRecords' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_AssetsModifyRecords DROP COLUMN STypeId
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetsModifyRecords' AND a.Name='BusinessDate'
)
BEGIN
	ALTER TABLE Ac_AssetsModifyRecords ADD BusinessDate DATETIME
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1  FROM   sysobjects WHERE  id = object_id('Ac_AssetStorageLocation') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AssetStorageLocation
	(
		Id	INT IDENTITY(1,1),
		Deleted	BIT NOT NULL DEFAULT(0),
		Location	VARCHAR(256)
	)
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetStorageLocation' AND a.Name='Deleted'
)
BEGIN
	ALTER TABLE Ac_AssetStorageLocation ADD Deleted BIT NOT NULL DEFAULT (0)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_AssetWorkingCondition') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AssetWorkingCondition
	(
		Id		INT IDENTITY(1,1),
		Comment	VARCHAR(256),
		Deleted	BIT NOT NULL DEFAULT(0),
		SysRow	INT NOT NULL DEFAULT(0)
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetWorkingCondition' AND a.Name='SysRow'
)
BEGIN
	ALTER TABLE Ac_AssetWorkingCondition ADD SysRow INT NOT NULL DEFAULT (0)
	UPDATE dbo.Ac_AssetWorkingCondition SET sysrow = 1 WHERE id <=4
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_AssetWorkingCondition' AND a.Name='Deleted'
)
BEGIN
	ALTER TABLE Ac_AssetWorkingCondition ADD Deleted BIT NOT NULL DEFAULT (0)
END
GO

--预置数据
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetWorkingCondition)
BEGIN
	INSERT INTO Ac_AssetWorkingCondition(Comment,Sysrow)
	VALUES	('使用中',1),
			('未使用',1),
			('不需要',1),
			('待报废',1)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Assist_CheckItems')
            and   type = 'U')
BEGIN  
	create table Ac_Assist_CheckItems (
	   AscIds               int                  identity(1,1),
	   UserCode             varchar(200)         not null,
	   FullName             varchar(200)         not null
	)
	
--预置数据
    INSERT INTO Ac_Assist_CheckItems
    (
		UserCode,
		FullName
	)VALUES
	('01','分支机构'),
	('02','部门'),
	('03','职员'),
	('04','往来单位')
END
GO


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ASSIST_CHECKITEMS') AND name = 'CIX_AC_ASSIST_CHECKITEMS_Ascids')
--DROP INDEX CIX_AC_ASSIST_CHECKITEMS_Ascids ON AC_ASSIST_CHECKITEMS 
CREATE CLUSTERED INDEX CIX_AC_ASSIST_CHECKITEMS_Ascids ON AC_ASSIST_CHECKITEMS(Ascids) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Assist_CheckItems_BillType')
            and   type = 'U')
BEGIN
	create table Ac_Assist_CheckItems_BillType (
	   nId                  int                  identity(1,1),
	   AscIds               int                  not null,
	   BillType             int                  not null,
	   FullName             varchar(200)         not null,
	   FieldValue           varchar(100)         not NULL,
	   AuditType			INT					 NULL
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Assist_CheckItems_BillType' AND a.Name='AuditType'
)
BEGIN
	ALTER TABLE Ac_Assist_CheckItems_BillType 
		ADD AuditType INT NULL DEFAULT(0)
END
GO

--调拨标识
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Assist_CheckItems_BillType' AND a.Name='InOutType'
)
BEGIN
	ALTER TABLE Ac_Assist_CheckItems_BillType 
		ADD InOutType INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType)
BEGIN
	TRUNCATE TABLE Ac_Assist_CheckItems_BillType
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
			( AscIds ,
			  BillType ,
			  FullName ,
			  FieldValue
			)
	VALUES  (1,305,'分支机构','stypeid'),
			(2,305,'部门','dtypeid'),
			(3,305,'经手人','etypeid'),
			(4,305,'结算单位','btypeid'),
			(4,305,'往来单位','dealbtypeid'),
			
			(1,11,'分支机构','stypeid'),
			(2,11,'部门','dtypeid'),
			(3,11,'经手人','etypeid'),
			(4,11,'结算单位','btypeid'),
			(4,11,'往来单位','dealbtypeid'),
			
			(1,160,'分支机构','stypeid'),
			(2,160,'部门','dtypeid'),
			(3,160,'经手人','etypeid'),
			(4,160,'结算单位','btypeid'),
			(4,160,'往来单位','dealbtypeid'),
			
			(1,45,'分支机构','stypeid'),
			(2,45,'部门','dtypeid'),
			(3,45,'经手人','etypeid'),
			(4,45,'结算单位','btypeid'),
			(4,45,'往来单位','dealbtypeid'),
			
			(1,34,'分支机构','stypeid'),
			(2,34,'部门','dtypeid'),
			(3,34,'经手人','etypeid'),
			(4,34,'结算单位','btypeid'),
			(4,34,'往来单位','dealbtypeid'),
			
			(1,6,'分支机构','stypeid'),
			(2,6,'部门','dtypeid'),
			(3,6,'经手人','etypeid'),
			(4,6,'结算单位','btypeid'),
			(4,6,'往来单位','dealbtypeid'),
			
			(1,161,'分支机构','stypeid'),
			(2,161,'部门','dtypeid'),
			(3,161,'经手人','etypeid'),
			(4,161,'结算单位','btypeid'),
			(4,161,'往来单位','dealbtypeid'),
			
			(1,126,'分支机构','stypeid'),
			(2,126,'部门','dtypeid'),
			(3,126,'经手人','etypeid'),
			(4,126,'结算单位','btypeid'),
			(4,126,'往来单位','dealbtypeid'),
			
			(1,21,'分支机构','stypeid'),
			(2,21,'部门','dtypeid'),
			(3,21,'经手人','etypeid'),
			(4,21,'结算单位','btypeid'),
			(4,21,'往来单位','dealbtypeid'),
			
			(1,201,'分支机构','stypeid'),
			(2,201,'部门','dtypeid'),
			(3,201,'经手人','etypeid'),
			(4,201,'结算单位','btypeid'),
			(4,201,'往来单位','dealbtypeid'),
			
			(1,202,'分支机构','stypeid'),
			(2,202,'部门','dtypeid'),
			(3,202,'经手人','etypeid'),
			(4,202,'结算单位','btypeid'),
			(4,202,'往来单位','dealbtypeid'),
			
			(1,172,'分支机构','stypeid'),
			(2,172,'部门','dtypeid'),
			(3,172,'经手人','etypeid'),
			(4,172,'结算单位','btypeid'),
			(4,172,'往来单位','dealbtypeid'),
			
			(1,170,'分支机构','stypeid'),
			(2,170,'部门','dtypeid'),
			(3,170,'经手人','etypeid'),
			(4,170,'结算单位','btypeid'),
			(4,170,'往来单位','dealbtypeid'),
			
			(1,168,'分支机构','stypeid'),
			(2,168,'部门','dtypeid'),
			(3,168,'经手人','etypeid'),
			(4,168,'结算单位','btypeid'),
			(4,168,'往来单位','dealbtypeid'),
			
			(1,167,'分支机构','stypeid'),
			(2,167,'部门','dtypeid'),
			(3,167,'经手人','etypeid'),
			(4,167,'结算单位','btypeid'),
			(4,167,'往来单位','dealbtypeid'),
			
			(1,166,'分支机构','stypeid'),
			(2,166,'部门','dtypeid'),
			(3,166,'经手人','etypeid'),
			(4,166,'结算单位','btypeid'),
			(4,166,'往来单位','dealbtypeid'),
			
			(1,183,'分支机构','stypeid'),
			(2,183,'部门','dtypeid'),
			(3,183,'经手人','etypeid'),
			(4,183,'结算单位','btypeid'),
			(4,183,'往来单位','dealbtypeid'),
			
			(1,181,'分支机构','stypeid'),
			(2,181,'部门','dtypeid'),
			(3,181,'经手人','etypeid'),		
			(4,181,'往来单位','dealbtypeid'),
			
			(1,57,'分支机构','stypeid'),
			(2,57,'部门','dtypeid'),
			(3,57,'经手人','etypeid'),
			(4,57,'结算单位','btypeid'),
			(4,57,'往来单位','dealbtypeid'),
			
			(1,150,'分支机构','stypeid'),
			(2,150,'部门','dtypeid'),
			(3,150,'经手人','etypeid'),
			(4,150,'结算单位','btypeid'),
			(4,150,'往来单位','dealbtypeid'),
			
			(1,148,'分支机构','stypeid'),
			(2,148,'部门','dtypeid'),
			(3,148,'经手人','etypeid'),
			(4,148,'结算单位','btypeid'),
			(4,148,'往来单位','dealbtypeid'),
			
			(1,190,'分支机构','stypeid'),
			(2,190,'部门','dtypeid'),
			(3,190,'经手人','etypeid'),
			(4,190,'结算单位','btypeid'),
			(4,190,'往来单位','dealbtypeid'),
			
			(1,66,'分支机构','stypeid'),
			(2,66,'部门','dtypeid'),
			(3,66,'经手人','etypeid'),
			(4,66,'结算单位','btypeid'),
			(4,66,'往来单位','dealbtypeid'),
			
			(1,189,'分支机构','stypeid'),
			(2,189,'部门','dtypeid'),
			(3,189,'经手人','etypeid'),
			(4,189,'结算单位','btypeid'),
			(4,189,'往来单位','dealbtypeid'),
			
			(1,4,'分支机构','stypeid'),
			(2,4,'部门','dtypeid'),
			(3,4,'经手人','etypeid'),
			(4,4,'结算单位','btypeid'),
			(4,4,'往来单位','dealbtypeid'),
			
			(1,129,'分支机构','stypeid'),
			(2,129,'部门','dtypeid'),
			(3,129,'经手人','etypeid'),
			(4,129,'单位','dealbtypeid'),
			
			(1,128,'分支机构','stypeid'),
			(2,128,'部门','dtypeid'),
			(3,128,'经手人','etypeid'),
			(4,128,'单位','dealbtypeid'),
			
			(1,115,'分支机构','stypeid'),
			(2,115,'部门','dtypeid'),
			(3,115,'经手人','etypeid'),
			(4,115,'单位','dealbtypeid'),
			
			(1,116,'分支机构','stypeid'),
			(2,116,'部门','dtypeid'),
			(3,116,'经手人','etypeid'),
			(4,116,'单位','dealbtypeid'),
			
			(1,16,'分支机构','stypeid'),
			(2,16,'部门','dtypeid'),
			(3,16,'经手人','etypeid'),
			(4,16,'结算单位','btypeid'),
			(4,16,'往来单位','dealbtypeid'),
			
			(1,14,'分支机构','stypeid'),
			(2,14,'部门','dtypeid'),
			(3,14,'经手人','etypeid'),
			(4,14,'结算单位','btypeid'),
			(4,14,'往来单位','dealbtypeid'),
			
			(1,9,'分支机构','stypeid'),
			(2,9,'部门','dtypeid'),
			(3,9,'经手人','etypeid'),
			(4,9,'结算单位','btypeid'),
			(4,9,'往来单位','dealbtypeid'),
			
			(1,36,'分支机构','stypeid'),
			(2,36,'部门','dtypeid'),
			(3,36,'经手人','etypeid'),
			(4,36,'结算单位','btypeid'),
			(4,36,'往来单位','dealbtypeid'),
			
			(1,78,'分支机构','stypeid'),
			(2,78,'部门','dtypeid'),
			(3,78,'经手人','etypeid'),
			(4,78,'结算单位','btypeid'),
			(4,78,'往来单位','dealbtypeid'),
			
			(1,158,'分支机构','stypeid'),
			(2,158,'部门','dtypeid'),
			(3,158,'经手人','etypeid'),
			(4,158,'结算单位','btypeid'),
			(4,158,'往来单位','dealbtypeid'),
			
			(1,77,'分支机构','stypeid'),
			(2,77,'部门','dtypeid'),
			(3,77,'经手人','etypeid'),
			(4,77,'结算单位','btypeid'),
			(4,77,'往来单位','dealbtypeid'),
			
			(1,93,'分支机构','stypeid'),
			(2,93,'部门','dtypeid'),
			(3,93,'经手人','etypeid'),
			(4,93,'结算单位','btypeid'),
			(4,93,'往来单位','dealbtypeid'),
			
			(1,140,'分支机构','stypeid'),
			(2,140,'部门','dtypeid'),
			(3,140,'经手人','etypeid'),
			(4,140,'结算单位','btypeid'),
			(4,140,'往来单位','dealbtypeid'),
			
			(1,142,'分支机构','stypeid'),
			(2,142,'部门','dtypeid'),
			(3,142,'经手人','etypeid'),
			(4,142,'结算单位','btypeid'),
			(4,142,'往来单位','dealbtypeid'),
			
			(1,141,'分支机构','stypeid'),
			(2,141,'部门','dtypeid'),
			(3,141,'经手人','etypeid'),
			(4,141,'结算单位','btypeid'),
			(4,141,'往来单位','dealbtypeid'),
			
			(1,5,'分支机构','stypeid'),
			(2,5,'部门','dtypeid'),
			(3,5,'经手人','etypeid'),
			(4,5,'结算单位','btypeid'),
			(4,5,'往来单位','dealbtypeid'),
			
			(1,10,'分支机构','stypeid'),
			(2,10,'部门','dtypeid'),
			(3,10,'经手人','etypeid'),
			(4,10,'结算单位','btypeid'),
			(4,10,'往来单位','dealbtypeid'),
			
			(1,144,'分支机构','stypeid'),
			(2,144,'部门','dtypeid'),
			(3,144,'经手人','etypeid'),
			(4,144,'结算单位','btypeid'),
			(4,144,'往来单位','dealbtypeid'),
			
			(1,145,'分支机构','stypeid'),
			(2,145,'部门','dtypeid'),
			(3,145,'经手人','etypeid'),
			(4,145,'结算单位','btypeid'),
			(4,145,'往来单位','dealbtypeid'),
			
			(1,146,'分支机构','stypeid'),
			(2,146,'部门','dtypeid'),
			(3,146,'经手人','etypeid'),
			(4,146,'结算单位','btypeid'),
			(4,146,'往来单位','dealbtypeid'),
			
			(1,149,'分支机构','stypeid'),
			(2,149,'部门','dtypeid'),
			(3,149,'经手人','etypeid'),
			(4,149,'结算单位','btypeid'),
			(4,149,'往来单位','dealbtypeid'),
			
			(1,151,'分支机构','stypeid'),
			(2,151,'部门','dtypeid'),
			(3,151,'经手人','etypeid'),
			(4,151,'结算单位','btypeid'),
			(4,151,'往来单位','dealbtypeid'),
			
			(1,205,'分支机构','stypeid'),
			(2,205,'部门','dtypeid'),
			(3,205,'经手人','etypeid'),
			(4,205,'结算单位','btypeid'),
			(4,205,'往来单位','dealbtypeid'),
			
			(1,159,'分支机构','stypeid'),
			(2,159,'部门','dtypeid'),
			(3,159,'经手人','etypeid'),
			(4,159,'结算单位','btypeid'),
			(4,159,'往来单位','dealbtypeid'),
			
			(1,139,'分支机构','stypeid'),
			(2,139,'部门','dtypeid'),
			(3,139,'经手人','etypeid'),
			(4,139,'结算单位','btypeid'),
			(4,139,'往来单位','dealbtypeid'),
			
			(1,187,'出库方分支机构','stypeid'),
			(1,187,'入库方分支机构','instypeid'),
			(2,187,'部门','dtypeid'),
			(3,187,'经手人','etypeid'),
			(4,187,'结算单位','btypeid'),
			(4,187,'往来单位','dealbtypeid'),
			
			(1,188,'入库方分支机构','stypeid'),
			(1,188,'出库方分支机构','outstypeid'),
			(2,188,'部门','dtypeid'),
			(3,188,'经手人','etypeid'),
			(4,188,'结算单位','btypeid'),
			(4,188,'往来单位','dealbtypeid'),
			
			(1,429,'出库方分支机构','stypeid'),
			(1,429,'入库方分支机构','instypeid'),
			(2,429,'部门','dtypeid'),
			(3,429,'经手人','etypeid'),
			(4,429,'结算单位','btypeid'),
			(4,429,'往来单位','dealbtypeid'),
			
			(1,428,'入库方分支机构','stypeid'),
			(1,428,'出库方分支机构','outstypeid'),
			(2,428,'部门','dtypeid'),
			(3,428,'经手人','etypeid'),
			(4,428,'结算单位','btypeid'),
			(4,428,'往来单位','dealbtypeid'),
			
			(1,84,'分支机构','stypeid'),
			(2,84,'部门','dtypeid'),
			(3,84,'经手人','etypeid'),
			(4,84,'结算单位','btypeid'),
			(4,84,'往来单位','dealbtypeid'),
			
			(1,85,'分支机构','stypeid'),
			(2,85,'部门','dtypeid'),
			(3,85,'经手人','etypeid'),
			(4,85,'结算单位','btypeid'),
			(4,85,'往来单位','dealbtypeid')
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 173)
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  (1,173,'分支机构','stypeid'),
			(2,173,'部门','dtypeid'),
			(3,173,'经手人','etypeid'),
			(4,173,'往来单位','dealbtypeid')
END
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 174)
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  (1,174,'分支机构','stypeid'),
			(2,174,'部门','dtypeid'),
			(3,174,'经手人','etypeid'),
			(4,174,'往来单位','dealbtypeid')
END
GO
IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 187 AND AscIds=1 AND FullName = '分支机构')
BEGIN
	UPDATE dbo.Ac_Assist_CheckItems_BillType SET FullName = '出库方分支机构' WHERE BillType = 187 AND AscIds = 1 AND FullName = '分支机构' 	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 187 AND AscIds = 1 AND FullName = '入库方分支机构')
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  ( 1 , -- AscIds - int
	          187 , -- BillType - int
	          '入库方分支机构' , -- FullName - varchar(200)
	          'instypeid'  -- FieldValue - varchar(100)
	        )	
END
GO
IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 188 AND AscIds=1 AND FullName = '分支机构')
BEGIN
	UPDATE dbo.Ac_Assist_CheckItems_BillType SET FullName = '入库方分支机构' WHERE BillType = 188 AND AscIds = 1 AND FullName = '分支机构' 	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 188 AND AscIds = 1 AND FullName = '出库方分支机构')
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  ( 1 , -- AscIds - int
	          188 , -- BillType - int
	          '出库方分支机构' , -- FullName - varchar(200)
	          'outstypeid'  -- FieldValue - varchar(100)
	        )	
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 212)
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  (1,212,'分支机构','stypeid'),
			(2,212,'部门','dtypeid'),
			(3,212,'经手人','etypeid'),
			(4,212,'结算单位','btypeid'), 
			(4,212,'往来单位','dealbtypeid')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 213)
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  (1,213,'分支机构','stypeid'),
			(2,213,'部门','dtypeid'),
			(3,213,'经手人','etypeid'),
			(4,213,'结算单位','btypeid'), 
			(4,213,'往来单位','dealbtypeid')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 214)
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  (1,214,'分支机构','stypeid'),
			(2,214,'部门','dtypeid'),
			(3,214,'经手人','etypeid'),
			(4,214,'结算单位','btypeid'), 
			(4,214,'往来单位','dealbtypeid')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 410)
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  (1,410,'分支机构','stypeid'),
			(2,410,'部门','dtypeid'),
			(3,410,'经手人','etypeid'),
			(4,410,'结算单位','btypeid'), 
			(4,410,'往来单位','dealbtypeid')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = -1 ) --部门变更
BEGIN
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  (1,-1,'分支机构','stypeid'),
			(3,-1,'经手人','etypeid'),
			(4,-1,'往来单位','dealbtypeid'), 
			(2,-1,'原部门','olddtypeid'),
			(2,-1,'新部门','dtypeid')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = -2 ) --减值准备
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  (1,-2,'分支机构','stypeid'),
			(2,-2,'部门','dtypeid'),
			(3,-2,'经手人','etypeid'),
			(4,-2,'往来单位','dealbtypeid')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 215 ) --零售退货单
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,215,'分支机构','stypeid'),
			(2,215,'部门','dtypeid'),
			(3,215,'经手人','etypeid'),
			(4,215,'结算单位','btypeid'),
			(4,215,'往来单位','dealbtypeid')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 147 ) --受托代销调价
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,147,'分支机构','stypeid'),
			(2,147,'部门','dtypeid'),
			(3,147,'经手人','etypeid'),
			(4,147,'结算单位','btypeid'),
			(4,147,'往来单位','dealbtypeid')
END
GO

--调拨单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 310)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue,
	          InOutType
	        )
	VALUES  
			(1,310,'调出分支机构','stypeid',1),
			(1,310,'调入分支机构','stypeid2',-1),
			(2,310,'部门','dtypeid',0),
			(3,310,'经手人','etypeid',0),
			(4,310,'结算单位','btypeid',0),
			(4,310,'往来单位','dealbtypeid',0),
			(5,310,'调出账户','bankaccountout',0),
			(5,310,'调入账户','bankaccountin',0)
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 312 ) --会员批量储值充值单
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,312,'分支机构','stypeid'),
			(2,312,'部门','dtypeid'),
			(3,312,'经手人','etypeid'),		
			(4,312,'结算单位','dealbtypeid')
END
GO
--提成单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 311)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,311,'分支机构','stypeid'),
			(2,311,'部门','dtypeid'),
			(3,311,'经手人','etypeid'),		
			(4,311,'结算单位','dealbtypeid')

END
GO

--暂估入库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 400)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,400,'分支机构','stypeid'),
			(2,400,'部门','dtypeid'),
			(3,400,'经手人','etypeid'),		
			(4,400,'结算单位','btypeid'),
			(4,400,'往来单位','dealbtypeid')

END
GO
--暂估退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 401)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,401,'分支机构','stypeid'),
			(2,401,'部门','dtypeid'),
			(3,401,'经手人','etypeid'),		
			(4,401,'结算单位','btypeid'),
			(4,401,'往来单位','dealbtypeid')
END
GO
--发出商品出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 402)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,402,'分支机构','stypeid'),
			(2,402,'部门','dtypeid'),
			(3,402,'经手人','etypeid'),		
			(4,402,'结算单位','btypeid'),
			(4,402,'往来单位','dealbtypeid')
END
GO
--发出商品退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 403)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,403,'分支机构','stypeid'),
			(2,403,'部门','dtypeid'),
			(3,403,'经手人','etypeid'),		
			(4,403,'结算单位','btypeid'),
			(4,403,'往来单位','dealbtypeid')
END
GO

--采购暂估开票
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 404)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,404,'分支机构','stypeid'),
			(2,404,'部门','dtypeid'),
			(3,404,'经手人','etypeid'),		
			(4,404,'结算单位','btypeid'),
			(4,404,'往来单位','dealbtypeid')
END
GO
--销售发货开票
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 405)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,405,'分支机构','stypeid'),
			(2,405,'部门','dtypeid'),
			(3,405,'经手人','etypeid'),		
			(4,405,'结算单位','btypeid'),
			(4,405,'往来单位','dealbtypeid')
END
GO

--往来核销单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 450)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,450,'分支机构','stypeid'),
			(2,450,'部门','dtypeid'),
			(3,450,'经手人','etypeid'),		
			(4,450,'结算单位','btypeid'),
			(4,450,'往来单位','dealbtypeid')
END
GO
--组合品销售出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 12)
	BEGIN
		INSERT INTO dbo.Ac_Assist_CheckItems_BillType
		( 
			AscIds ,
			BillType ,
			FullName ,
			FieldValue
		)
		VALUES  
			(1,12,'分支机构','stypeid'),
			(2,12,'部门','dtypeid'),
			(3,12,'经手人','etypeid'),
			(4,12,'结算单位','btypeid'),
			(4,12,'往来单位','dealbtypeid')
	END
--组合品销售退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 46)
	BEGIN
		INSERT INTO dbo.Ac_Assist_CheckItems_BillType
		( 
			AscIds ,
			BillType ,
			FullName ,
			FieldValue
		)
		VALUES  
			(1,46,'分支机构','stypeid'),
			(2,46,'部门','dtypeid'),
			(3,46,'经手人','etypeid'),
			(4,46,'结算单位','btypeid'),
			(4,46,'往来单位','dealbtypeid')
	END

DELETE FROM  dbo.Ac_Assist_CheckItems_BillType WHERE BillType =414 	
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 414 ) --运输配送单
BEGIN 
	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,414,'分支机构','stypeid'),
			(2,414,'部门','dtypeid'),
			(3,414,'经手人','etypeid'),
			(4,414,'往来单位','dealbtypeid')		
END
GO

--===============================983新增【BEGIN】===============================
--优惠券入库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 423)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,423,'分支机构','stypeid'),
			(2,423,'部门','dtypeid'),
			(3,423,'经手人','etypeid'),		
			(4,423,'结算单位','btypeid'),
			(4,423,'往来单位','dealbtypeid')

END
GO
--优惠券出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 424)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,424,'分支机构','stypeid'),
			(2,424,'部门','dtypeid'),
			(3,424,'经手人','etypeid'),		
			(4,424,'结算单位','btypeid'),
			(4,424,'往来单位','dealbtypeid')

END
GO
--优惠券退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 426)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,426,'分支机构','stypeid'),
			(2,426,'部门','dtypeid'),
			(3,426,'经手人','etypeid'),		
			(4,426,'结算单位','btypeid'),
			(4,426,'往来单位','dealbtypeid')

END
GO

--积分转储值单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 427)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,427,'分支机构','stypeid'),
			(2,427,'部门','dtypeid'),
			(3,427,'经手人','etypeid'),		
			(4,427,'结算单位','btypeid')

END
GO


--门店配送单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 327)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,327,'分支机构','stypeid'),
			(2,327,'部门','dtypeid'),
			(3,327,'经手人','etypeid'),		
			(4,327,'结算单位','btypeid')

END
GO

--门店配送退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 328)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,328,'分支机构','stypeid'),
			(2,328,'部门','dtypeid'),
			(3,328,'经手人','etypeid'),		
			(4,328,'结算单位','btypeid')

END
GO

--门店验收单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = 329)
BEGIN 

	INSERT INTO dbo.Ac_Assist_CheckItems_BillType
	        ( AscIds ,
	          BillType ,
	          FullName ,
	          FieldValue
	        )
	VALUES  
			(1,329,'分支机构','stypeid'),
			(2,329,'部门','dtypeid'),
			(3,329,'经手人','etypeid'),		
			(4,329,'结算单位','btypeid')

END
GO

--9.4暂时废弃银行账户辅助核算
DELETE FROM dbo.Ac_Assist_CheckItems_BillType WHERE AscIds = 5
GO

UPDATE Ac_Assist_CheckItems_BillType SET AuditType=0 WHERE AuditType IS NULL
GO
--===============================983新增【END】===============================
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ASSIST_CHECKITEMS_BILLTYPE') AND name = 'CIX_AC_ASSIST_CHECKITEMS_BILLTYPE_Ascids')
--DROP INDEX CIX_AC_ASSIST_CHECKITEMS_BILLTYPE_Ascids ON AC_ASSIST_CHECKITEMS_BILLTYPE 
CREATE CLUSTERED INDEX CIX_AC_ASSIST_CHECKITEMS_BILLTYPE_Ascids ON AC_ASSIST_CHECKITEMS_BILLTYPE(Ascids) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ASSIST_CHECKITEMS_BILLTYPE') AND name = 'NCIX_AC_ASSIST_CHECKITEMS_BILLTYPE_Billtype')
--DROP INDEX NCIX_AC_ASSIST_CHECKITEMS_BILLTYPE_Billtype ON AC_ASSIST_CHECKITEMS_BILLTYPE 
CREATE NONCLUSTERED INDEX NCIX_AC_ASSIST_CHECKITEMS_BILLTYPE_Billtype ON AC_ASSIST_CHECKITEMS_BILLTYPE(Billtype) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS(SELECT 1 FROM  sysobjects WHERE id = object_id('Ac_Assist_CheckItemsDetail') AND type = 'U')
BEGIN  
	CREATE TABLE Ac_Assist_CheckItemsDetail (
		TypeId		VARCHAR(50),
		ParId		VARCHAR(50)		NOT NULL,	--父节点
		Leveal      INT             NOT NULL,	--级别
		SonNum		INT				NOT NULL,	--父节点
		SonCount	INT				NOT NULL,	--父节点
		AscIds      INT				NOT NULL,	-- 核算类型
		UserCode    VARCHAR(200)	NOT NULL,	--编号
		FullName    VARCHAR(200)    NOT NULL,	--名称
		CreatedBy	VARCHAR(50)		NOT NULL,	--创建人
		CreatedDate	DATETIME		NOT NULL DEFAULT(GETDATE()),--创建时间
		Comment		VARCHAR(1000)	NULL		--备注
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Assist_CheckItemsDetail') AND name = 'CIX_Ac_Assist_CheckItemsDetail_TypeId')
--DROP INDEX CIX_Ac_Assist_CheckItemsDetail_TypeId ON Ac_Assist_CheckItemsDetail 
CREATE CLUSTERED INDEX CIX_Ac_Assist_CheckItemsDetail_TypeId ON Ac_Assist_CheckItemsDetail(TypeId) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('Ac_Auditing_AcFrom') AND type = 'U')
	BEGIN
		CREATE TABLE Ac_Auditing_AcFrom(
			NID				INT				IDENTITY(1,1),
			AcFromId		INT,
			FullName		VARCHAR(200)	NOT NULL,
			IsAssets		BIT				NOT NULL DEFAULT(0),
			XiWaMaxNumber   INT				NULL DEFAULT(1)	--缓存ID
		)
	END
GO
------------------------------------------表修改区-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Auditing_AcFrom') AND name = 'CIX_Ac_Auditing_AcFrom_NID')
	CREATE CLUSTERED INDEX CIX_Ac_Auditing_AcFrom_NID ON Ac_Auditing_AcFrom(NID) 

------------------------------------------创建索引区域结束-----------------------------------------------

--------------------------------预制数据----------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Auditing_AcFrom)
	BEGIN
	INSERT INTO Ac_Auditing_AcFrom(AcFromId,FullName,IsAssets)
	SELECT 1 ,'手工选择',0 UNION 
	SELECT 2 ,'单据上收付款项目对应科目',0 UNION 
	SELECT 3 ,'单据上往来科目',0 UNION 
	SELECT 4 ,'单据上项目对应科目',0 UNION 
	SELECT 5 ,'单据上项目对应固定资产科目',0 UNION
	SELECT 5 ,'固定资产科目',1 UNION
	SELECT 6 ,'固定资产累计折旧科目',0 UNION 
	SELECT 7 ,'单据上贷方项目对应科目',0 UNION 
	SELECT 8 ,'单据上业务类型对应科目',0 UNION 
	SELECT 9 ,'固定资产累计折旧科目',1 UNION 
	SELECT 9 ,'单据上项目对应累计折旧科目',0 UNION 
	SELECT 10 ,'固定资产折旧分配科目',1 UNION 
	SELECT 10 ,'单据上项目对应折旧分配科目',0 UNION 
	SELECT 11 ,'固定资产减值准备科目',0 UNION 
	SELECT 12 ,'单据上账户对应科目',0 UNION 
	SELECT 13 ,'单据上往来科目（借）',0 UNION 
	SELECT 14 ,'单据上往来科目（贷）',0 UNION 
	SELECT 15 ,'存货类型的存货科目',0 UNION 
	SELECT 16 ,'存货类型的收入科目',0 UNION 
	SELECT 17 ,'存货类型的成本科目',0 UNION 
	SELECT 18 ,'入账原值差异科目',0 UNION
	SELECT 19 ,'汇率影响原值科目',0
	END
GO




if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Auditing_Template')
            and   type = 'U')
BEGIN
	create table Ac_Auditing_Template (
	   AtId                 int                  identity(1,1),
	   UserCode             varchar(200)         not null,
	   FullName             varchar(200)         not null,
	   BillType             int                  null,
	   ETypeId              varchar(50)          null,
	   IsDefault            int                  null,
	   CreateDateTime       datetime             null,
	   PyCode               varchar(200)         null,
	   Comment              varchar(400)         NULL,
	   FromAtid				INT					 NULL,
	   AuditType			INT					 NULL,
	   ChargeOffType		INT					 NULL,	--往来核销类别
	   InOutType			INT					 NULL
	)
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='VgId'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD VgId INT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD STypeId VARCHAR(50) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='Sysrow'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD Sysrow INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='FromAtid'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD FromAtid INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='AuditType'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD AuditType INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='Explaintext'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD Explaintext VARCHAR(400) NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='ExplainAuditType'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD ExplainAuditType VARCHAR(200) NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='IsCombineRow'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD IsCombineRow INT NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='InOutType'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD InOutType INT NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template' AND a.Name='ChargeOffType'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template 
		ADD ChargeOffType INT NULL
END
GO



------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_AUDITING_TEMPLATE') AND name = 'CIX_AC_AUDITING_TEMPLATE_AtId')
--DROP INDEX CIX_AC_AUDITING_TEMPLATE_AtId ON AC_AUDITING_TEMPLATE 
CREATE CLUSTERED INDEX CIX_AC_AUDITING_TEMPLATE_AtId ON AC_AUDITING_TEMPLATE(AtId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_AUDITING_TEMPLATE') AND name = 'NCIX_AC_AUDITING_TEMPLATE_Billtype')
--DROP INDEX NCIX_AC_AUDITING_TEMPLATE_Billtype ON AC_AUDITING_TEMPLATE 
CREATE NONCLUSTERED INDEX NCIX_AC_AUDITING_TEMPLATE_Billtype ON AC_AUDITING_TEMPLATE(Billtype) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------------修改数据------------------------------------------------
UPDATE Ac_Auditing_Template SET STypeId = '00001' WHERE STypeId IS NULL
GO
UPDATE Ac_Auditing_Template SET Sysrow = 1 WHERE Sysrow IS NULL
GO
UPDATE Ac_Auditing_Template SET  IsCombineRow=0 where IsCombineRow IS NULL AND BillType='159'
GO


----预制内容【谢吉康先关闭 以后再说 2012-06-21】
--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template)
--BEGIN
--	INSERT INTO [Ac_Auditing_Template] (UserCode,FullName,BillType,etypeid,IsDefault,CreateDateTime,PyCode,VgId,STypeID,Sysrow)
--	VALUES
--	('LS0001','零售单凭证模板','305','00001','1',GetDate(),'LSDPZMB','1','00001',1),
--	('XSCK0001','销售出库单凭证模板','11','00001','1',GetDate(),'XSCKDPZMB','1','00001',1),
--	('XSHH0001','销售换货单凭证模板','160','00001','1',GetDate(),'XSHHDPZMB','1','00001',1),
--	('XSTH0001','销售退货单凭证模板','45','00001','1',GetDate(),'XSTHDPZMB','1','00001',1),
--	('CGRK0001','采购入库单凭证模板','34','00001','1',GetDate(),'CGRKDPZMB','1','00001',1),
--	('CGTH0001','采购入库单凭证模板','6','00001','1',GetDate(),'CGRKDPZMB','1','00001',1),
--	('CGHH0001','采购换货单凭证模板','161','00001','1',GetDate(),'CGHHDPZMB','1','00001',1),
--	('CGHZ0001','获赠单凭证模板','126','00001','1',GetDate(),'HZDPZMB','1','00001',1),
--	('BJDB0001','变价调拨单凭证模板','21','00001','1',GetDate(),'BJDBDPZMB','1','00001',1),
--	('QTRK0001','其它入库单凭证模板','201','00001','1',GetDate(),'QTRKDPZMB','1','00001',1),
--	('QTCK0001','其它出库单凭证模板','202','00001','1',GetDate(),'QTCKDPZMB','1','00001',1),
--	('XWSMXW0001','上门维修单凭证模板','172','00001','1',GetDate(),'SMWXDPZMB','1','00001',1),
--	('XWSXFH0001','送修返回单凭证模板','170','00001','1',GetDate(),'SXFHDPZMB','1','00001',1),
--	('WXZJGH0001','整机更换单凭证模板','168','00001','1',GetDate(),'ZJGHDPZMB','1','00001',1),
--	('WXQJD0001','维修取件单凭证模板','167','00001','1',GetDate(),'WXQJDPZMB','1','00001',1),
--	('WX0001','维修单凭证模板','166','00001','1',GetDate(),'WXDPZMB','1','00001',1),
--	('JFDH0001','积分兑换单凭证模板','183','00001','1',GetDate(),'JFDHDPZMB','1','00001',1),
--	('HYCZ0001','会员储值单凭证模板','181','00001','1',GetDate(),'HYCZDPZMB','1','00001',1),
--	('CBDJ0001','成本调价单凭证模板','57','00001','1',GetDate(),'CBDJDPZMB','1','00001',1),
--	('HLHSZSD0001','获利核算执行单凭证模板','150','00001','1',GetDate(),'HLHSZXDPZMB','1','00001',1),
--	('FLHSZSD0001','返利核算执行单凭证模板','148','00001','1',GetDate(),'FLHSZXDPZMB','1','00001',1),
--	('YFKD0001','预付款单凭证模板','190','00001','1',GetDate(),'YFKDPZMB','1','00001',1),
--	('FKD0001','付款单凭证模板','66','00001','1',GetDate(),'FKDPZMB','1','00001',1),
--	('YSKD0001','预收款单凭证模板','189','00001','1',GetDate(),'YSKDPZMB','1','00001',1),
--	('SKD0001','收款单凭证模板','4','00001','1',GetDate(),'SKDPZMB','1','00001',1),
--	('QTYFJS0001','其它应付减少单凭证模板','129','00001','1',GetDate(),'QTYFJSDPZMB','1','00001',1),
--	('QTYFZJ0001','其它应付增加单凭证模板','128','00001','1',GetDate(),'QTYFZJDPZMB','1','00001',1),
--	('QTYSJS0001','其它应收减少凭证模板','115','00001','1',GetDate(),'QTYSJSPZMB','1','00001',1),
--	('QTYSZJ0001','其它应收增加单凭证模板','116','00001','1',GetDate(),'QTYSZJDPZMB','1','00001',1),
--	('SCCZ0001','生产拆装单凭证模板','16','00001','1',GetDate(),'SCCZDPZMB','1','00001',1),
--	('BYD0001','报溢单凭证模板','14','00001','1',GetDate(),'BYDPZMB','1','00001',1),
--	('BSD0001','报损单凭证模板','9','00001','1',GetDate(),'BSDPZMB','1','00001',1),
--	('FYD0001','费用单凭证模板','36','00001','1',GetDate(),'FYDPZMB','1','00001',1),
--	('GDZCZJ0001','固定资产折旧凭证模板','78','00001','1',GetDate(),'GDZCZJPZMB','1','00001',1),
--	('XJFYD0001','现金费用单凭证模板','158','00001','1',GetDate(),'XJFYDPZMB','1','00001',1),
--	('ZKD0001','转款单凭证模板','77','00001','1',GetDate(),'ZKDPZMB','1','00001',1),
--	('QTSRD0001','其它收入单凭证模板','93','00001','1',GetDate(),'QTSRDPZMB','1','00001',1),
--	('WTDX0001','委托代销凭证模板','140','00001','1',GETDATE(),'WTDXPZMB','1','00001',1),
--	('WTDXTH0001','委托代销退货凭证模板','142','00001','1',GETDATE(),'WTDXTHPZMB','1','00001',1),
--	('WTDXJS0001','委托代销结算凭证模板','141','00001','1',GETDATE(),'WTDXJSPZMB','1','00001',1),
--	('DTFYD0001','待摊费用单凭证模板','5','00001','1',GETDATE(),'DTFYDPZMB','1','00001',1),
--	('DTFYFSD0001','待摊费用摊销单凭证模板','10','00001','1',GETDATE(),'DTFYTXDPZMB','1','00001',1),
--	('STDX0001','受托代销收货单凭证模板','144','00001','1',GETDATE(),'STDXSHDPZMB','1','00001',1),
--	('STDXJS0001','受托代销结算单凭证模板','145','00001','1',GETDATE(),'STDXJSDPZMB','1','00001',1),
--	('STDXTH0001','受托代销退货单凭证模板','146','00001','1',GETDATE(),'STDXTHDPZMB','1','00001',1),
--	('JBZXD0001','价保执行单凭证模板','149','00001','1',GETDATE(),'JBZXDPZMB','1','00001',1),
--	('HDJB0001','获得价保执行单凭证模板','151','00001','1',GETDATE(),'HDJBZXDPZMB','1','00001',1),
--	('FYFT0001','采购费用分摊凭证模板','205','00001','1',GETDATE(),'CGFYFTPZMB','1','00001',1),
--	('WXSMWX0001','业务凭证凭证模板','159','00001','1',GETDATE(),'YWPZPZMB','1','00001',1)
--END
----预制内容【固定资产购入模板（原值含税）】
--INSERT INTO [Ac_Auditing_Template] (UserCode,FullName,BillType,etypeid,IsDefault,CreateDateTime,PyCode,VgId,STypeID,Sysrow)
--	VALUES
--('固定资产购入模板（原值含税）','固定资产购入模板（原值含税）','212','00001','1',GETDATE(),'YWPZPZMB','1','00001',1)
DELETE FROM Ac_Auditing_Template WHERE FullName='固定资产购入模板（原值含税）' AND UserCode='固定资产购入模板（原值含税）'
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Auditing_Template_Detail')
            and   type = 'U')
BEGIN
	create table Ac_Auditing_Template_Detail (
	   AtdId                int                  identity(1,1),
	   Atid                 int                  null,
	   Summary              varchar(400)         null,
	   AcFrom               varchar(100)         null,
	   ATypeId              varchar(50)          null,
	   Fdc                  int                  null,
	   BillMoneyId          varchar(400)         null,
	   Express              varchar(1000)        null,
	   AssistCheckItmes     varchar(200)         null,
	   AssistCheckItmesIds  varchar(200)         null
	)
END
GO

--预制内容【谢吉康先关闭 以后再说 2012-06-21】
--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template_Detail)
--BEGIN
--	INSERT INTO [Ac_Auditing_Template_Detail] ([Atid],	[Summary],	[AcFrom],	[ATypeId],	[Fdc],	[BillMoneyId],	[Express])
--	VALUES 
--	('1','销售商品','2','','1','30','totalinmoney'),
--	('1','销售商品','1','0000300001','-1','34','taxtotal'),
--	('1','销售商品','1','0000300006','1','32','costtotal'),
--	('1','销售商品','1','0000100017','-1','32','costtotal'),
--	('2','销售商品','3','','1','8','taxtotal - preferencemoney - totalinmoney'),
--	('2','销售商品','2','','1','1','totalinmoney'),
--	('2','销售商品','1','0000300001','-1','4','total'),
--	('2','销售商品','1','0000300009','1','2','preferencemoney'),
--	('2','销售商品','1','0000200007','-1','7','taxtotal - total'),
--	('2','销售商品','1','0000300006','1','3','costtotal'),
--	('2','销售商品','1','0000100017','-1','3','costtotal'),
--	('3','销售换货','3','','1','27','instocktaxtotal - outstocktaxtotal - preferencemoney - totalinmoney'),
--	('3','销售换货','2','','1','17','totalinmoney'),
--	('3','销售换货','1','0000300001','-1','28','instocktotal - outstocktotal'),
--	('3','销售换货','1','0000300009','1','18','preferencemoney'),
--	('3','销售换货','1','0000200007','-1','29','outstocktaxtotal - outstocktotal - instocktaxtotal + instocktotal'),
--	('3','销售换货','1','0000300006','1','19','costtotal'),
--	('3','销售换货','1','0000100017','-1','19','costtotal'),
--	('4','销售退货','2','','1','9','totalinmoney'),
--	('4','销售退货','1','0000300009','1','10','preferencemoney'),
--	('4','销售退货','1','0000300006','1','11','costtotal'),
--	('4','销售退货','1','0000100017','-1','11','costtotal'),
--	('4','销售退货','1','0000300001','-1','12','total'),
--	('4','销售退货','1','0000200007','-1','15','taxtotal - total'),
--	('4','销售退货','3','','1','16','taxtotal - preferencemoney - totalinmoney'),
--	('5','采购入库','1','0000100017','1','56','total'),
--	('5','采购入库','1','0000200007','1','59','taxtotal - total'),
--	('5','采购入库','3','','-1','60','taxtotal - preferencemoney - totalinmoney'),
--	('5','采购入库','2','','-1','53','totalinmoney'),
--	('5','采购入库','1','0000300002','-1','54','preferencemoney'),
--	('6','采购退货','1','0000100017','1','64','total'),
--	('6','采购退货','1','0000200007','1','67','taxtotal - total'),
--	('6','采购退货','3','','-1','68','taxtotal - preferencemoney - totalinmoney'),
--	('6','采购退货','2','','-1','61','totalinmoney'),
--	('6','采购退货','1','0000300002','-1','62','preferencemoney'),
--	('7','采购换货','1','0000100017','1','169','instocktotal-outstocktotal'),
--	('7','采购换货','1','0000200007','1','81','instocktaxTotal - instocktotal - outstocktaxTotal + outstocktotal'),
--	('7','采购换货','3','','-1','80','instocktaxtotal - outstocktaxtotal - preferencemoney - totalinmoney'),
--	('7','采购换货','2','','-1','69','totalinmoney'),
--	('7','采购换货','1','0000300007','-1','70','preferencemoney'),
--	('8','获赠','1','0000100017','1','82','costtotal'),
--	('8','获赠','1','0000300002','-1','82','costtotal'),
--	('9','变价调拨','1','0000100017','1','100','total - costtotal'),
--	('9','变价调拨','1','0000100042','-1','100','total - costtotal'),
--	('10','其它入库','1','0000100017','1','101','total'),
--	('10','其它入库','1','0000300002','-1','101','total'),
--	('11','其它入库','1','0000300007','1','102','total'),
--	('11','其它入库','1','0000100017','-1','102','total'),
--	('12','维修','3','','1','171','total - preferencemoney - totalinmoney'),
--	('12','维修','1','0000300002','-1','172','total - preferencemoney'),
--	('12','维修','2','','1','168','totalinmoney'),
--	('13','维修','3','','1','166','total - preferencemoney - totalinmoney'),
--	('13','维修','1','0000300002','-1','167','total - preferencemoney'),
--	('13','','2','','1','163','totalinmoney'),
--	('14','整机更换','3','','-1','161','total - preferencemoney - totalinmoney'),
--	('14','整机更换','1','0000300007','1','162','total - preferencemoney'),
--	('14','','2','','-1','158','totalinmoney'),
--	('15','维修','3','','1','156','total - preferencemoney - totalinmoney'),
--	('15','维修','1','0000300002','-1','157','total - preferencemoney'),
--	('15','','2','','1','153','totalinmoney'),
--	('16','维修','1','0000300007','1','152','totalmoney'),
--	('16','维修','1','0000100017','-1','152','totalmoney'),
--	('17','积分兑换','1','0000300007','1','151','costtotal'),
--	('17','积分兑换','1','0000100017','-1','151','costtotal'),
--	('18','会员储值','2','','1','149','totalinmoney'),
--	('18','会员储值','1','0000200005','-1','149','totalinmoney'),
--	('19','报损','1','0000100017','1','147','total - beforetotal'),
--	('19','报损','1','0000100042','-1','147','total - beforetotal'),
--	('20','获利','3','','1','121','total - totalinmoney'),
--	('20','获利','1','0000300002','-1','120','total'),
--	('20','获利','2','','1','119','totalinmoney'),
--	('21','返利','3','','-1','118','total - totalinmoney'),
--	('21','返利','1','0000300009','1','117','total'),
--	('21','返利','2','','-1','116','totalinmoney'),
--	('22','预付款','3','','1','115','total'),
--	('22','预付款','2','','-1','115','total'),
--	('23','付款','3','','1','114','total'),
--	('23','付款','2','','-1','114','total'),
--	('24','预收款','2','','1','113','total'),
--	('24','预收款','3','','-1','113','total'),
--	('25','收款','2','','1','112','total'),
--	('25','收款','3','','-1','112','total'),
--	('26','其他应付调整','1','0000300007','1','111','total'),
--	('26','其他应付调整','3','','-1','111','total'),
--	('27','其他应付调整','1','0000300007','1','110','total'),
--	('27','其他应付调整','3','','-1','110','total'),
--	('28','其他应用收调整','3','','1','109','total'),
--	('28','其他应用收调整','1','0000300001','-1','109','total'),
--	('29','其他应用收调整','3','','1','108','total'),
--	('29','其他应用收调整','1','0000300002','-1','108','total'),
--	('30','报损','1','0000100017','1','107','instockgoodscosttotal - outstockgoodscosttotal'),
--	('30','报损','1','0000100042','-1','107','instockgoodscosttotal - outstockgoodscosttotal'),
--	('31','报损','1','0000100017','1','104','costtotal'),
--	('31','报损','1','0000100042','-1','104','costtotal'),
--	('32','报损','1','0000100042','1','103','costtotal'),
--	('32','报损','1','0000100017','-1','103','costtotal'),
--	('33','费用','4','','1','129','total'),
--	('33','费用','3','','-1','130','total - totalinmoney'),
--	('33','费用','2','','-1','128','totalinmoney'),
--	('34','固定资产折旧','5','','1','135','total'),
--	('34','固定资产折旧','5','','-1','135','total'),
--	('35','现金费用单','4','','1','136','total'),
--	('35','现金费用单','2','','-1','137',''),
--	('36','转款单','4','','1','139','total'),
--	('36','转款单','2','','-1','138','totalinmoney'),
--	('37','其他收入','4','','-1','141','total'),
--	('37','其他收入','2','','1','140','totalinmoney'),
--	('37','其他收入','3','','1','142','total - totalinmoney'),
--	('38','委托代销发出商品','1','0000100023','1','40','costtotal'),
--	('38','委托代销发出商品','1','0000100017','-1','40','costtotal'),
--	('39','委托代销发出商品','1','0000100023','1','43','costtotal'),
--	('39','委托代销发出商品','1','0000100017','-1','43','costtotal'),
--	('40','委托代销结算','3','','1','52','taxtotal - totalinmoney'),
--	('40','委托代销结算','2','','1','46','totalinmoney'),
--	('40','委托代销结算','1','0000300001','-1','49','total'),
--	('40','委托代销结算','1','0000200007','-1','51','taxtotal - total'),
--	('40','委托代销结算','1','0000300006','1','48','costtotal'),
--	('40','委托代销结算','1','0000100023','-1','48','costtotal'),
--	('41','待摊费用','1','0000100027','1','143','total'),
--	('41','待摊费用','4','','-1','143','total'),
--	('42','待摊费用','4','','1','144','total'),
--	('42','待摊费用','1','0000100027','-1','144','total'),
--	('43','受托代销收货单','1','0000100024','1','84','total'),
--	('43','受托代销收货单','1','0000200005','-1','84','total'),
--	('44','受托代销结算单','1','0000200007','1','95','taxtotal - total'),
--	('44','受托代销结算单','2','','-1','90','totalinmoney'),
--	('44','受托代销结算单','3','','-1','96','taxtotal - totalinmoney'),
--	('44','受托代销结算单','1','0000300006','1','92','costtotal'),
--	('44','受托代销结算单','1','0000100024','-1','92','costtotal'),
--	('45','受托代销退货单','1','0000100024','1','88','total'),
--	('45','受托代销退货单','1','0000200005','-1','88','total'),
--	('46','价保','3','','-1','124','total - totalinmoney'),
--	('46','价保','1','0000300010','1','123','total'),
--	('46','价保','2','','-1','122','totalinmoney'),
--	('47','获得价保','3','','1','127','total - totalinmoney'),
--	('47','获得价保','1','0000300002','-1','126','total'),
--	('47','获得价保','2','','1','125','totalinmoney'),
--	('48','采购费用分摊','1','0000100017','1','148','sharefee'),
--	('48','采购费用分摊','4','','-1','148','sharefee'),
--	('49','业务凭证','6','','1','173','j_total'),
--	('49','业务凭证','7','','-1','174','d_total')
--END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template_Detail' AND a.Name='SummaryType'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template_Detail ADD SummaryType VARCHAR(50)NOT NULL DEFAULT ('')
END

GO
UPDATE Ac_Auditing_Template_Detail SET SummaryType = '' WHERE SummaryType IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template_Detail' AND a.Name='FromAtdId'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template_Detail 
		ADD FromAtdId INT NULL DEFAULT(0)
END
GO
--是否属于成本类数据
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template_Detail' AND a.Name='isCost'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template_Detail 
		ADD isCost BIT NOT NULL DEFAULT(0)
END
GO
--凭证模板明细排序ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template_Detail' AND a.Name='OrderID'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template_Detail 
		ADD OrderID INT DEFAULT(1)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_AUDITING_TEMPLATE_DETAIL') AND name = 'CIX_AC_AUDITING_TEMPLATE_DETAIL_Atdid')
--DROP INDEX CIX_AC_AUDITING_TEMPLATE_DETAIL_Atdid ON AC_AUDITING_TEMPLATE_DETAIL 
CREATE CLUSTERED INDEX CIX_AC_AUDITING_TEMPLATE_DETAIL_Atdid ON AC_AUDITING_TEMPLATE_DETAIL(Atdid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_AUDITING_TEMPLATE_DETAIL') AND name = 'NCIX_AC_AUDITING_TEMPLATE_DETAIL_AtId')
--DROP INDEX NCIX_AC_AUDITING_TEMPLATE_DETAIL_AtId ON AC_AUDITING_TEMPLATE_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_AUDITING_TEMPLATE_DETAIL_AtId ON AC_AUDITING_TEMPLATE_DETAIL(AtId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_AUDITING_TEMPLATE_DETAIL') AND name = 'NCIX_AC_AUDITING_TEMPLATE_DETAIL_AcFrom')
--DROP INDEX NCIX_AC_AUDITING_TEMPLATE_DETAIL_AcFrom ON AC_AUDITING_TEMPLATE_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_AUDITING_TEMPLATE_DETAIL_AcFrom ON AC_AUDITING_TEMPLATE_DETAIL(AcFrom) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Auditing_Template_Detail_Assist_CheckItems')
            and   type = 'U')
BEGIN
	create table Ac_Auditing_Template_Detail_Assist_CheckItems (
	   AtdId                int                  null,
	   Atid                 int                  null,
	   AssistCheckItmes     varchar(200)         null,
	   AssistCheckItmesIds  varchar(200)         null,
	   Express              varchar(1000)        null
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template_Detail_Assist_CheckItems' AND a.Name='AscIds'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template_Detail_Assist_CheckItems 
		ADD AscIds INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Auditing_Template_Detail_Assist_CheckItems' AND a.Name='AscIdsDetailId'
)
BEGIN
	ALTER TABLE Ac_Auditing_Template_Detail_Assist_CheckItems 
		ADD AscIdsDetailId INT NULL DEFAULT(0)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS') AND name = 'CIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_AtdId')
--DROP INDEX CIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_AtdId ON AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS 
CREATE CLUSTERED INDEX CIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_AtdId ON AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS(AtdId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_Atid_AscIdsDetailId')
--DROP INDEX NCIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_Atid_AscIdsDetailId ON AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_Atid_AscIdsDetailId ON AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS(Atid,AscIdsDetailId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_AscIds')
--DROP INDEX NCIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_AscIds ON AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS_AscIds ON AC_AUDITING_TEMPLATE_DETAIL_ASSIST_CHECKITEMS(AscIds) 

------------------------------------------创建索引区域结束-----------------------------------------------
---------------------------------------------修改数据---------------------------------------------
UPDATE Ac_Auditing_Template_Detail_Assist_CheckItems SET AscIds = 0 WHERE AscIds IS NULL
GO
UPDATE Ac_Auditing_Template_Detail_Assist_CheckItems SET AscIdsDetailId = 0 WHERE AscIdsDetailId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF  EXISTS ( SELECT  1
                FROM    sysobjects
                WHERE   id = OBJECT_ID('Ac_Auditing_Template_SummaryFiled')
                        AND type = 'U' ) 
BEGIN
	DROP TABLE Ac_Auditing_Template_SummaryFiled
END 

IF NOT EXISTS ( SELECT  1
                FROM    sysobjects
                WHERE   id = OBJECT_ID('Ac_Auditing_Template_SummaryFiled')
                        AND type = 'U' ) 
BEGIN
    CREATE TABLE Ac_Auditing_Template_SummaryFiled
        (
          FiledID	INT IDENTITY(1, 1),
          Filed		VARCHAR(50) NULL DEFAULT(''),
          TableName	VARCHAR(200) NULL DEFAULT(''),
          Comment	VARCHAR(200) NULL DEFAULT('')
      )
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Auditing_Template_SummaryFiled)
BEGIN
	INSERT INTO Ac_Auditing_Template_SummaryFiled(Filed,TableName,Comment)
	VALUES('BillDate','BillIndex','单据日期'),
		('FullName','Stype','分支机构名称'),
		('FullName','Btype','结算单位名称'),
		('FullName','employee','经手人名称'),
		('explain','BillIndex','说明'),
		('comment','BillIndex','摘要'),
		('billcode','BillIndex','单据编号')
END



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_AuditType') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_AuditType
	(
		Id		INT,
		Comment	VARCHAR(200)
	)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AuditType)
BEGIN
	INSERT	INTO Ac_AuditType
	        ( Id, Comment )
	VALUES  (1,'购入（原值含税）'),
			(2,'购入（原值不含税）'),
			(3,'自建工程'),
			(4,'接受投资'),
			(5,'接受捐赠'),
			(6,'盘盈'),
			(7,'变卖'),
			(8,'报废'),
			(9,'投资转出'),
			(10,'捐赠转出'),
			(11,'盘亏'),
			(12,'部门转移'),
			(13,'计提减值准备'),
			(14,'折旧')

END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Balance')
            and   type = 'U')   
BEGIN
	create table Ac_Balance (
	   STypeId              varchar(50)          null,
	   ATypeId              varchar(50)          null,
	   FBeginBalance        numeric(18,2)        null,		--本币期初
	   FBeginBalanceFor     numeric(18,2)        null,		--原币期初
	   FDebit               numeric(18,2)        null,
	   FDebitFor            numeric(18,2)        null,
	   FCredit              numeric(18,2)        null,
	   FCreditFor           numeric(18,2)        null,
	   Cid                  int                  null,	   
	   FEndBalance          numeric(18,2)        null,
	   FEndBalanceFor       numeric(18,2)        null,
	   FYtdDebit            numeric(18,2)        null,
	   FYtdDebitFor         numeric(18,2)        null,
	   FYtdCredit           numeric(18,2)        null,
	   FYtdCreditFor        numeric(18,2)        null,
	   FYear                INT					 null,
	   FPeriod              INT			         null,
	   FBeginqty			numeric(24,10)		 NOT NULL DEFAULT(0),
	   FDebitqty			numeric(24,10)		 NOT NULL DEFAULT(0),
	   FCreditqty			numeric(24,10)		 NOT NULL DEFAULT(0),
	   FEndqty				numeric(24,10)		 NOT NULL DEFAULT(0),
	   FYtdDebitqty			numeric(24,10)		 NOT NULL DEFAULT(0),
	   FYtdCreditqty		numeric(24,10)		 NOT NULL DEFAULT(0)
	)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='AscIds'
)
BEGIN
	ALTER TABLE Ac_Balance 
		DROP COLUMN AscIds
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FBeginqty'
)
BEGIN
	ALTER TABLE Ac_Balance 
		ADD FBeginqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FDebitqty'
)
BEGIN
	ALTER TABLE Ac_Balance 
		ADD FDebitqty numeric(24,10)NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FCreditqty'
)
BEGIN
	ALTER TABLE Ac_Balance 
		ADD FCreditqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FEndqty'
)
BEGIN
	ALTER TABLE Ac_Balance 
		ADD FEndqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FYtdDebitqty'
)
BEGIN
	ALTER TABLE Ac_Balance 
		ADD FYtdDebitqty numeric(24,10) NOT NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FYtdCreditqty'
)
BEGIN
	ALTER TABLE Ac_Balance 
		ADD FYtdCreditqty numeric(24,10) NOT NULL DEFAULT(0) 
END
GO
--删除索引 以便修改列类型
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE') AND name = 'CIX_AC_BALANCE_FYear_FPeriod')
	DROP INDEX CIX_AC_BALANCE_FYear_FPeriod ON AC_BALANCE 
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE Ac_Balance 
		ALTER COLUMN FYear INT
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FPeriod'
)
BEGIN
	ALTER TABLE Ac_Balance 
		ALTER COLUMN FPeriod INT
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE') AND name = 'CIX_AC_BALANCE_FYear_FPeriod')
--DROP INDEX CIX_AC_BALANCE_FYear_FPeriod ON AC_BALANCE 
CREATE CLUSTERED INDEX CIX_AC_BALANCE_FYear_FPeriod ON AC_BALANCE(FYear,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE') AND name = 'NCIX_AC_BALANCE_Atypeid')
--DROP INDEX NCIX_AC_BALANCE_Atypeid ON AC_BALANCE 
CREATE NONCLUSTERED INDEX NCIX_AC_BALANCE_Atypeid ON AC_BALANCE(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE') AND name = 'NCIX_AC_BALANCE_STypeId_Cid')
--DROP INDEX NCIX_AC_BALANCE_STypeId_Cid ON AC_BALANCE 
CREATE NONCLUSTERED INDEX NCIX_AC_BALANCE_STypeId_Cid ON AC_BALANCE(STypeId, Cid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FBeginBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FBeginBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FBeginBalanceFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FBeginBalanceFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FCreditFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FEndBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FEndBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FEndBalanceFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FEndBalanceFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FYtdDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FYtdDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FYtdDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FYtdDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FYtdCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FYtdCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance' AND a.Name='FYtdCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance 
	ALTER COLUMN FYtdCreditFor NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Balance_Assist_CheckItems')
            and   type = 'U')
BEGIN
	create table Ac_Balance_Assist_CheckItems (
	   STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   Cid                  int                  null default -1,	   
	   IniYTotal            numeric(18,2)        null default 0,
	   IniYTotalFor         numeric(18,2)        null default 0,
	   FDebit               numeric(18,2)        null default 0,
	   FDebitFor            numeric(18,2)        null default 0,
	   FCredit              numeric(18,2)        null default 0,
	   FCreditFor           numeric(18,2)        null default 0,
	   IniTotal             numeric(18,2)        null default 0,
	   IniTotalFor          numeric(18,2)        null default 0,
	   IniYqty          numeric(18,2)        not null default 0,
	   FDebitqty          numeric(18,2)       not null default 0,
	   FCreditqty          numeric(18,2)      not  null default 0,
	   Iniqty          numeric(18,2)       not null default 0
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		ADD FYear VARCHAR(10) NULL,
			FPeriod VARCHAR(10) NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FEndBalance'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		ADD FEndBalance NUMERIC(18,2) NULL DEFAULT(0),
			FEndBalanceFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FEndqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		ADD FEndqty NUMERIC(18,2) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FDebit'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		ADD FDebit NUMERIC(18,2) NULL DEFAULT(0),
			FDebitFor NUMERIC(18,2) NULL DEFAULT(0),
			FCredit NUMERIC(18,2) NULL DEFAULT(0),
			FCreditFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='Debit'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		DROP COLUMN Debit,DebitFor,Credit,CreditFor
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='CidType'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		DROP COLUMN CidType
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='Ascids'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		DROP COLUMN Ascids
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='AscidsNid'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		DROP COLUMN AscidsNid
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='GroupId'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		DROP COLUMN GroupId
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='IniYqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		ADD IniYqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FDebitqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		ADD FDebitqty numeric(24,10) NOT NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FCreditqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		ADD FCreditqty numeric(24,10) NOT NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='Iniqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
		ADD Iniqty numeric(24,10) NOT NULL DEFAULT(0) 
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE_ASSIST_CHECKITEMS') AND name = 'CIX_AC_BALANCE_ASSIST_CHECKITEMS_FYear_FPeriod')
--DROP INDEX CIX_AC_BALANCE_ASSIST_CHECKITEMS_FYear_FPeriod ON AC_BALANCE_ASSIST_CHECKITEMS 
CREATE CLUSTERED INDEX CIX_AC_BALANCE_ASSIST_CHECKITEMS_FYear_FPeriod ON AC_BALANCE_ASSIST_CHECKITEMS(FYear,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_BALANCE_ASSIST_CHECKITEMS_Atypeid')
--DROP INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_Atypeid ON AC_BALANCE_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_Atypeid ON AC_BALANCE_ASSIST_CHECKITEMS(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_BALANCE_ASSIST_CHECKITEMS_STypeId_Cid')
--DROP INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_STypeId_Cid ON AC_BALANCE_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_STypeId_Cid ON AC_BALANCE_ASSIST_CHECKITEMS(STypeId, Cid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------修改数据------------------------------------
UPDATE Ac_Balance_Assist_CheckItems SET FYear = '' WHERE FYear IS NULL
GO
UPDATE Ac_Balance_Assist_CheckItems SET FPeriod = '' WHERE FPeriod IS NULL
GO
UPDATE Ac_Balance_Assist_CheckItems SET FEndBalance = 0 WHERE FEndBalance IS NULL
GO
UPDATE Ac_Balance_Assist_CheckItems SET FEndBalanceFor = 0 WHERE FEndBalanceFor IS NULL
GO
UPDATE Ac_Balance_Assist_CheckItems SET FEndqty = 0 WHERE FEndqty IS NULL
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='IniYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN IniYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='IniYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN IniYTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN FDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN FCreditFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='IniTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN IniTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='IniTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN IniTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FEndBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN FEndBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FEndBalanceFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN FEndBalanceFor NUMERIC(24,10)
    END
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems' AND a.Name='FEndqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems 
	ALTER COLUMN FEndqty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Balance_Assist_CheckItems_Detail')
            and   type = 'U')
BEGIN
	create table Ac_Balance_Assist_CheckItems_Detail (
	   STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   Cid                  int                  null default -1,
	   Ascids               int                  null default -1,
	   FieldValue           varchar(50)          null,
	   FDebit				numeric(18,2)		 null default 0,	   
	   FDebitFor			numeric(18,2)		 null default 0,
	   FCredit				numeric(18,2)		 null default 0,
	   FCreditFor			numeric(18,2)		 null default 0,
	   IniTotal				numeric(18,2)		 null default 0,
	   IniTotalFor			numeric(18,2)		 null default 0,
	   FEndBalance			numeric(18,2)		 null default 0,
	   FEndBalanceFor		numeric(18,2)		 null default 0,
	   FYear                varchar(10)          null,
	   FPeriod              int                  null,
	   Iniqty			numeric(24,10)		not null default 0,
	   FDebitqty			numeric(24,10)		not null default 0,
	   FCreditqty			numeric(24,10)		not null default 0,
	   FEndqty				numeric(24,10)		not null default 0
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
		ADD FYear VARCHAR(10) NULL DEFAULT(''),
		    FPeriod INT NULL DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FDebit'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
		ADD FDebit NUMERIC(18,2) NULL DEFAULT(0),
			FDebitFor NUMERIC(18,2) NULL DEFAULT(0),
			FCredit NUMERIC(18,2) NULL DEFAULT(0),
			FCreditFor NUMERIC(18,2) NULL DEFAULT(0),
			IniTotal NUMERIC(18,2) NULL DEFAULT(0),
			IniTotalFor NUMERIC(18,2) NULL DEFAULT(0),
			FEndBalance NUMERIC(18,2) NULL DEFAULT(0),
			FEndBalanceFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='Iniqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
		ADD Iniqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FDebitqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
		ADD FDebitqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FCreditqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
		ADD FCreditqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FEndqty'
)
BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
		ADD FEndqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE_ASSIST_CHECKITEMS_DETAIL') AND name = 'CIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_FYear_FPeriod')
--DROP INDEX CIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_FYear_FPeriod ON AC_BALANCE_ASSIST_CHECKITEMS_DETAIL 
CREATE CLUSTERED INDEX CIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_FYear_FPeriod ON AC_BALANCE_ASSIST_CHECKITEMS_DETAIL(FYear,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE_ASSIST_CHECKITEMS_DETAIL') AND name = 'NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_Atypeid')
--DROP INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_Atypeid ON AC_BALANCE_ASSIST_CHECKITEMS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_Atypeid ON AC_BALANCE_ASSIST_CHECKITEMS_DETAIL(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE_ASSIST_CHECKITEMS_DETAIL') AND name = 'NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_STypeId_Cid')
--DROP INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_STypeId_Cid ON AC_BALANCE_ASSIST_CHECKITEMS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_STypeId_Cid ON AC_BALANCE_ASSIST_CHECKITEMS_DETAIL(STypeId,Cid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCE_ASSIST_CHECKITEMS_DETAIL') AND name = 'NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_Ascids')
--DROP INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_Ascids ON AC_BALANCE_ASSIST_CHECKITEMS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_BALANCE_ASSIST_CHECKITEMS_DETAIL_Ascids ON AC_BALANCE_ASSIST_CHECKITEMS_DETAIL(Ascids) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
	ALTER COLUMN FDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
	ALTER COLUMN FCreditFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='IniTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
	ALTER COLUMN IniTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='IniTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
	ALTER COLUMN IniTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FEndBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
	ALTER COLUMN FEndBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Balance_Assist_CheckItems_Detail' AND a.Name='FEndBalanceFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Balance_Assist_CheckItems_Detail 
	ALTER COLUMN FEndBalanceFor NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_BalanceType')
            and   type = 'U')
BEGIN
	create table Ac_BalanceType (
	   BtId                 int                  identity(1,1),
	   UserCode             varchar(200)         not null,
	   FullName             varchar(200)         not null,
	   ATypeId              varchar(50)          null
	)
END
GO


-------------------------------------添加内置结算方式--------------------------------
/*
	作者:佘海源
	日期:2012-3-30
	描述:结算方式基础资料 A8-9.0
*/
BEGIN
  if NOT EXISTS(select 1 from Ac_BalanceType where UserCode = 'JF01')
       INSERT INTO Ac_BalanceType(UserCode,FullName) VALUES('JF01','现金')
  if NOT EXISTS(select 1 from Ac_BalanceType where UserCode = 'JF02')
       INSERT INTO Ac_BalanceType(UserCode,FullName) VALUES('JF02','电汇')
  if NOT EXISTS(select 1 from Ac_BalanceType where UserCode = 'JF03')
       INSERT INTO Ac_BalanceType(UserCode,FullName) VALUES('JF03','信汇')
  if NOT EXISTS(select 1 from Ac_BalanceType where UserCode = 'JF04')
       INSERT INTO Ac_BalanceType(UserCode,FullName) VALUES('JF04','商业汇票')
  if NOT EXISTS(select 1 from Ac_BalanceType where UserCode = 'JF05')
       INSERT INTO Ac_BalanceType(UserCode,FullName) VALUES('JF05','银行汇票')
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BALANCETYPE') AND name = 'CIX_AC_BALANCETYPE_Btid')
--DROP INDEX CIX_AC_BALANCETYPE_Btid ON AC_BALANCETYPE 
CREATE CLUSTERED INDEX CIX_AC_BALANCETYPE_Btid ON AC_BALANCETYPE(Btid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Bank')
            and   type = 'U')   
BEGIN
	create table Ac_Bank (
	   nId                  int                  identity(1,1),
	   STypeId				varchar(50)			 null default(''),
	   UserCode             varchar(200)         null,
	   FullName             varchar(400)         null,
	   CreateBank           varchar(400)         null,
	   BankType             varchar(200)         null,
	   ATypeId              varchar(50)          null,
	   IsBank				int					 null default(0),
	   Comment              varchar(500)         null,
	   Deleted				int                  null default(0)
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Bank' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_Bank 
		ADD STypeId VARCHAR(50) NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Bank' AND a.Name='IsBank'
)
BEGIN
	ALTER TABLE Ac_Bank 
		ADD IsBank INT NULL DEFAULT(0)
END
GO
-------------------------------------------预制数据-------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Bank)
BEGIN
	DECLARE @STypeId VARCHAR(50)

	DECLARE SType_Cursor CURSOR FOR
		SELECT TypeId FROM SType WHERE SonNum = 0
		
	OPEN SType_Cursor	

	FETCH NEXT FROM SType_Cursor INTO @STypeId

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Bank WHERE UserCode = '1001')
		BEGIN
			INSERT INTO Ac_Bank(STypeId,UserCode,FullName,CreateBank,BankType,ATypeId,Comment,Deleted)VALUES(@STypeId,'1001','现金','','','','',0)
			UPDATE Ac_Bank SET ATypeId = (SELECT TypeId FROM Ac_Account WHERE FullName = '现金' AND StypeId = @STypeId)
		END
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Bank WHERE UserCode = '2081')
		BEGIN
			INSERT INTO Ac_Bank(STypeId,UserCode,FullName,CreateBank,BankType,ATypeId,Comment,Deleted)VALUES(@STypeId,'2081','『会员储值』','','','','',0)
			UPDATE Ac_Bank SET ATypeId = (SELECT TypeId FROM Ac_Account WHERE FullName = '『会员储值』' AND StypeId = @STypeId)
		END
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Bank WHERE UserCode = '3131')
		BEGIN
			INSERT INTO Ac_Bank(STypeId,UserCode,FullName,CreateBank,BankType,ATypeId,Comment,Deleted)VALUES(@STypeId,'3131','『预收账款』','','','','',0)
			UPDATE Ac_Bank SET ATypeId = (SELECT TypeId FROM Ac_Account WHERE FullName = '『预收账款』' AND StypeId = @STypeId)
		END
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Bank WHERE UserCode = '1151')
		BEGIN
			INSERT INTO Ac_Bank(STypeId,UserCode,FullName,CreateBank,BankType,ATypeId,Comment,Deleted)VALUES(@STypeId,'1151','『预付账款』','','','','',0)
			UPDATE Ac_Bank SET ATypeId = (SELECT TypeId FROM Ac_Account WHERE FullName = '『预付账款』' AND StypeId = @STypeId)
		END
		
		FETCH NEXT FROM SType_Cursor INTO @STypeId		
	END

	CLOSE SType_Cursor
	DEALLOCATE SType_Cursor
END



------------------------------------------修改数据------------------------------------------
UPDATE Ac_Bank SET STypeId = '' WHERE STypeId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ac_Batch_Bills]') AND type in (N'U'))
BEGIN
	CREATE TABLE Ac_Batch_Bills
	(
		BillNumberId	INT
	)
END

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ac_Batch_Bills_Result]') AND type in (N'U'))
BEGIN
	CREATE TABLE Ac_Batch_Bills_Result
	(
		Nid			INT IDENTITY(1,1),
		BillCode	VARCHAR(500),
		Msg			VARCHAR(2000)
	)
END

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if  exists (select 1
            from  sysobjects
           where  id = object_id('ac_BatchCreateVoucher_result')
            and   type = 'U')
BEGIN
	drop table ac_BatchCreateVoucher_result
END


create table ac_BatchCreateVoucher_result (
   billcode			    varchar(50)         ,
   txt         varchar(500),
   flag			 int
   ,voucherid		NUMERIC(10,0)
   ,deficitvoucher	INT
   ,returnvalue		INT
)


GO

------------------------------------------创建索引区域开始-----------------------------------------------



------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------------------------------修改数据----------------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if exists (select 1
            from  sysobjects
           where  id = object_id('Ac_BatchCreatingRsult')
            and   type = 'U')
BEGIN
	drop table Ac_BatchCreatingRsult
END
	create table Ac_BatchCreatingRsult (
	   a			INT
	)
GO

------------------------------------------创建索引区域开始-----------------------------------------------




------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------------------------------修改数据----------------------------------------------------------

--if not exists( select top 1 1 from sysdata WHERE SubName = 'BatchCreateStart' )
--begin
--	declare @maxSubno INT
--	select @maxSubno = max(subno) from sysdata
--	insert into sysdata(subno,SubName,SubValue) values(@maxSubno+1,'BatchCreateStart',0)
--end

--GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_BillMoney_List')
            and   type = 'U')
BEGIN
	create table Ac_BillMoney_List (
	   BillMoneyId          int                  identity(1,1),
	   BillType             int                  null,
	   FullName             varchar(200)         not null,
	   Express              varchar(2000)        not null,
	   [Content]			varchar(max)		 null
	)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_BillMoney_List' AND a.Name='Sysrow'
)
BEGIN
	ALTER TABLE Ac_BillMoney_List 
		ADD Sysrow INT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_BillMoney_List' AND a.Name='Content'
)
BEGIN
	ALTER TABLE Ac_BillMoney_List 
		ADD [Content] varchar(max) NULL DEFAULT('')
END
GO
--是否成本类
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_BillMoney_List' AND a.Name='isCost'
)
BEGIN
	ALTER TABLE Ac_BillMoney_List 
		ADD isCost BIT NOT NULL DEFAULT(0)
END
GO

--预制内容
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List)
BEGIN
	TRUNCATE TABLE dbo.Ac_BillMoney_List

	INSERT  INTO Ac_BillMoney_List(BillType,FullName,Express,Sysrow,Content)
	VALUES
	---------------------------销售出库
	(11,'收款金额','totalinmoney',1,'收款金额'),
	(11,'抹零金额','preferencemoney',1,'抹零金额'),
	(11,'成本金额','costtotal',1,'成本金额'),
	(11,'折后金额','total',1,'折后金额'),
	(11,'价税合计','taxtotal',1,'价税合计'),
	(11,'抹零后金额','(taxTotal- preferencemoney)',1,'抹零后金额'),
	(11,'税额','(taxTotal - total)',1,'税额'),
	(11,'抹零后金额 减 收款金额','(taxTotal - preferencemoney - totalinmoney)',1,'抹零后金额-收款金额'),
	---------------------------销售退货
	(45,'实付金额','totalinmoney',1,'实付金额'),
	(45,'抹零金额','preferencemoney',1,'抹零金额'),
	(45,'成本金额','costtotal',1,'成本金额'),
	(45,'折后金额','total',1,'折后金额'),
	(45,'价税合计','taxtotal',1,'价税合计'),
	(45,'抹零后金额','(taxTotal - preferencemoney)',1,'抹零后金额'),
	(45,'税额','(taxTotal - total)',1,'税额'),
	(45,'抹零后金额 减 实付金额','(taxTotal - preferencemoney - totalinmoney)',1,'抹零后金额-实付金额'),
	--------------------------销售换货
	(160,'收款金额','totalinmoney',1,'收款金额'),
	(160,'抹零金额','preferencemoney',1,'抹零金额'),
	(160,'入库成本金额','incosttotal',1,'入库成本金额'),--分出入
	(160,'出库成本金额','outcosttotal',1,'出库成本金额'),
	(160,'入库折后金额','instocktotal',1,'入库折后金额'),	--分出入
	(160,'出库折后金额','outstocktotal',1,'出库折后金额'),	
	(160,'抹零后金额','(outstocktaxtotal - instocktaxtotal - preferencemoney)',1,'抹零后金额'),
	(160,'入库价税合计','instocktaxtotal',1,'入库价税合计'),--分出入
	(160,'出库价税合计','outstocktaxtotal',1,'出库价税合计'),
	(160,'入库税额','(instocktaxtotal - instocktotal)',1,'入库税额'),--分出入
	(160,'出库税额','(outstocktaxtotal - outstocktotal)',1,'出库税额'),
	(160,'抹零后金额 减 收款金额','(outstocktaxtotal - instocktaxtotal - preferencemoney - totalinmoney)',1,'抹零后金额-收款金额'),
	(160,'出库折后金额 减 入库折后金额','(outstocktotal - instocktotal)',1,'出库折后金额-入库折后金额'),
	(160,'出库税额 减 入库税额','(outstocktaxtotal - outstocktotal - instocktaxtotal + instocktotal)',1,'出库税额-入库税额'),
	--------------------------零售单
	(305,'收款金额','totalinmoney',1,'收款金额'),
	(305,'抹零金额','preferencemoney',1,'抹零金额'),
	(305,'成本金额','costtotal',1,'成本金额'),  
	(305,'折后金额','total',1,'折后金额'),
	(305,'价税合计','taxtotal',1,'价税合计'),
	(305,'应收金额','taxtotal',1,'应收金额'),
	--------------------------赠送单
	(139,'成本金额','costtotal',1,'成本金额'),
	--------------------------委托代销发货
	(140,'成本金额','costtotal',1,'成本金额'),
	(140,'折后金额','total',1,'折后金额'),
	(140,'价税合计','taxtotal',1,'价税合计'),
	--------------------------委托代销退货
	(142,'成本金额','costtotal',1,'成本金额'),
	(142,'折后金额','total',1,'折后金额'),
	(142,'价税合计','taxtotal',1,'价税合计'),
	--------------------------委托代销结算
	(141,'实收金额','totalinmoney',1,'实收金额'),
	(141,'抹零金额','preferencemoney',1,'抹零金额'),
	(141,'成本金额','costtotal',1,'成本金额'),
	(141,'折后金额','total',1,'折后金额'),
	(141,'价税合计','taxtotal',1,'价税合计'),
	(141,'税额','(taxTotal - total)',1,'税额'),
	(141,'价税合计 减 实收金额','(taxtotal - totalinmoney)',1,'价税合计-实收金额'),
	--------------------------采购入库
	(34,'实付金额','totalinmoney',1,'实付金额'),
	(34,'抹零金额','preferencemoney',1,'抹零金额'),
	(34,'成本金额','costtotal',1,'成本金额'),
	(34,'折后金额','total',1,'折后金额'),
	(34,'价税合计','taxtotal',1,'价税合计'),
	(34,'抹零后金额','(taxTotal- preferencemoney)',1,'抹零后金额'),
	(34,'税额','(taxTotal - total)',1,'税额'),
	(34,'抹零后金额 减 实付金额','(taxTotal - preferencemoney - totalinmoney)',1,'抹零后金额-实付金额'),
	--------------------------采购退货
	(6,'实收金额','totalinmoney',1,'实收金额'),
	(6,'抹零金额','preferencemoney',1,'抹零金额'),
	(6,'成本金额','costtotal',1,'成本金额'),
	(6,'折后金额','total',1,'折后金额'),
	(6,'价税合计','taxtotal',1,'价税合计'),
	(6,'抹零后金额','(taxTotal- preferencemoney)',1,'抹零后金额'),
	(6,'税额','(taxTotal - total)',1,'税额'),
	(6,'抹零后金额 减 实收金额','(taxTotal - preferencemoney - totalinmoney)',1,'抹零后金额-实收金额'),
	(6,'折后金额 减 成本金额','(total - costtotal)',1,'折后金额-成本金额'),
	--------------------------采购换货
	(161,'实付金额','totalinmoney',1,'实付金额'),
	(161,'抹零金额','preferencemoney',1,'抹零金额'),
	(161,'出库成本金额','outcosttotal',1,'出库成本金额'),--分出入
	(161,'入库成本金额','incosttotal',1,'入库成本金额'),
	(161,'入库折后金额','instocktotal',1,'入库折后金额'),	--分出入
	(161,'出库折后金额','outstocktotal',1,'出库折后金额'),	
	(161,'入库价税合计','instocktaxtotal',1,'入库价税合计'),--分出入
	(161,'出库价税合计','outstocktaxtotal',1,'出库价税合计'),
	(161,'入库税额','(instocktaxTotal - instocktotal)',1,'入库部分税额'),--分出入
	(161,'出库税额','(outstocktaxTotal - outstocktotal)',1,'出库部分税额'),
	(161,'抹零后金额','(instocktaxtotal - outstocktaxtotal - preferencemoney)',1,'抹零后金额'),
	(161,'入库折后金额 减 出库折后金额','(instocktotal - outstocktotal)',1,'入库折后金额-出库折后金额'),
	(161,'抹零后金额 减 实付金额','(instocktaxtotal - outstocktaxtotal - preferencemoney - totalinmoney)',1,'抹零后金额-实付金额'),
	(161,'入库税额 减 出库税额','(instocktaxTotal - instocktotal - outstocktaxTotal + outstocktotal)',1,'入库税额-出库税额'),
	(161,'出库折后金额 减 出库成本金额','(outstocktotal - outcosttotal)',1,'出库折后金额-出库成本金额'),
	(161,'入库成本金额 减 出库成本金额','(incosttotal - outcosttotal)',1,'入库成本金额-出库成本金'),
	---------------------------获赠单
	(126,'成本金额','costtotal',1,'成本金额'),
	--------------------------受托代销收货
	(144,'成本金额','costtotal',1,'成本金额'),
	(144,'折后金额','total',1,'折后金额'),
	(144,'价税合计','taxtotal',1,'价税合计'),
	--------------------------受托代销退货
	(146,'成本金额','costtotal',1,'成本金额'),
	(146,'折后金额','total',1,'折后金额'),
	(146,'价税合计','taxtotal',1,'价税合计'),
	(146,'折后金额 减 成本金额','(total - costtotal)',1,'折后金额—成本金额'),
	--------------------------受托代销结算
	(145,'实付金额','totalinmoney',1,'实付金额'),
	(145,'抹零金额','preferencemoney',1,'抹零金额'),
	(145,'成本金额','costtotal',1,'成本金额'),
	(145,'折后金额','total',1,'折后金额'),
	(145,'价税合计','taxtotal',1,'价税合计'),
	(145,'税额','(taxTotal - total)',1,'税额'),
	(145,'价税合计 减 实付金额','(taxtotal - totalinmoney)',1,'价税合计-实付金额'),
	--------------------------同价调拨单
	(17,'成本金额','costtotal',1,'成本金额'),
	--------------------------变价调拨单
	(21,'调拨金额','total',1,'调拨金额'),
	(21,'出库成本','costtotal',1,'出库成本'),
	(21,'调拨金额 减 出库成本','(total - costtotal)',1,'调拨金额-出库成本'),
	-------------------------分支机构调拨出库
	(187,'金额','total',1,'金额'),
	(187,'成本金额','goodscosttotal',1,'成本金额'),
	(187,'金额 减 成本金额','(total - goodscosttotal)',1,'金额 — 成本金额'),
	-------------------------分支机构调拨入库
	(188,'金额','total',1,'金额'),
	-------------------------其他入库单
	(201,'金额','total',1,'金额'),
	-------------------------其他出库单
	(202,'金额','total',1,'金额'),
	-------------------------报损单
	(9,'成本金额','costtotal',1,'成本金额'),
	-------------------------报溢单
	(14,'成本金额','costtotal',1,'成本金额'),
	-------------------------生产拆装单
	(16,'入库成本金额','instockGoodsCostTotal',1,'入库成本金额'),
	(16,'出库成本金额','outstockGoodsCostTotal',1,'出库成本金额'),
	(16,'入库成本金额 减 出库成本金额','(instockGoodsCostTotal - outstockGoodsCostTotal)',1,'入库成本金额-出库成本金额'),
	-------------------------应收款增加
	(116,'金额','total',1,'金额'),
	-------------------------应收款减少
	(115,'金额','total',1,'金额'),
	-------------------------应付款增加
	(128,'金额','total',1,'金额'),
	------------------------应付款减少
	(129,'金额','total',1,'金额'),
	------------------------收款单
	(4,'金额','total',1,'金额'),
	(4,'抹零金额','preferencemoney',1,'抹零金额'),
	(4,'金额 加 抹零金额','(total + preferencemoney)',1,'金额+抹零金额'),
	------------------------预收款单
	(189,'金额','total',1,'金额'),
	------------------------付款单
	(66,'金额','total',1,'金额'),
	(66,'抹零金额','preferencemoney',1,'抹零金额'),
	(66,'金额 加 抹零金额','(total + preferencemoney)',1,'金额+抹零金额'),
	-------------------------预付款单
	(190,'金额','total',1,'金额'),
	-------------------------返利核算执行
	(148,'实付金额','totalinmoney',1,'实付金额'),
	(148,'返利金额','total',1,'返利金额'),
	(148,'返利金额 减 实付金额','(total - totalinmoney)',1,'返利金额-实付金额'),
	-------------------------获利核算执行
	(150,'实收金额','totalinmoney',1,'实收金额'),
	(150,'获利金额','total',1,'获利金额'),
	(150,'获利金额 减 实收金额','(total - totalinmoney)',1,'获利金额-实收金额'),
	-------------------------价保执行单
	(149,'实付金额','totalinmoney',1,'实付金额'),
	(149,'应保价金额','total',1,'应保价金额'),
	(149,'应保价金额 减 实付金额','(total - totalinmoney)',1,'应保价金额-实付金额'),
	------------------------获得价保执行单
	(151,'实收金额','totalinmoney',1,'实收金额'),
	(151,'应保价金额','total',1,'应保价金额'),
	(151,'应保价金额 减 实收金额','(total - totalinmoney)',1,'应保价金额-实收金额'),
	------------------------费用单
	(36,'实付金额','totalinmoney',1,'实付金额'),
	(36,'金额','total',1,'金额'),
	(36,'金额减实付金额','(total - totalinmoney)',1,'金额-实付金额'),
	------------------------固定资产购买
	(84,'实付金额','totalinmoney',1,'实付金额'),
	(84,'金额','total',1,'金额'),
	(84,'金额 减 实付金额','(total - totalinmoney)',1,'金额-实付金额'),
	------------------------固定资产变卖
	(85,'金额','total',1,'金额'),
	(85,'实收金额','totalinmoney',1,'实收金额'),
	(85,'金额 减 实收金额','(total - totalinmoney)',1,'金额-实收金额'),
	------------------------固定资产折旧
	(78,'金额','total',1,'金额'),
	------------------------现金费用单
	(158,'金额','total',1,'金额'),
	------------------------转款单
	(77,'实付金额','totalinmoney',1,'实付金额'),
	(77,'金额','total',1,'金额'),
	------------------------其他收入单
	(93,'实收金额','totalinmoney',1,'实收金额'),
	(93,'金额','total',1,'金额'),
	(93,'金额 减 实收金额','(total - totalinmoney)',1,'金额-实收金额'),
	------------------------待摊费用发生
	(5,'金额','total',1,'金额'),
	------------------------待摊费用摊销
	(10,'金额','total',1,'金额'),
	------------------------成本调价单
	(57,'调前金额','beforetotal',1,'调前金额'),
	(57,'调后金额','total',1,'调后金额'),
	(57,'调后金额 减 调前金额','(total - beforetotal)',1,'调后金额-调前金额'),
	------------------------采购费用分摊
	(205,'分摊金额','sharefee',1,'分摊金额'),
	------------------------会员储值充值单
	(181,'充值金额','totalmoney',1,'充值金额'),
	(181,'实收金额','totalinmoney',1,'实收金额'),
	(181,'抹零金额','preferencemoney',1,'抹零金额'),
	(181,'充值金额 减 抹零金额 减 实收金额','(totalmoney - preferencemoney - totalinmoney)',1,'充值金额—抹零金额—实收金额'),
	-------------------------积分兑换单
	(183,'成本金额','costtotal',1,'成本金额'),
	------------------------维修单
	(166,'成本金额','costtotal',1,'成本金额'),
	------------------------取件单
	(167,'收款金额','totalinmoney',1,'收款金额'),
	(167,'抹零金额','preferencemoney',1,'抹零金额'),
	(167,'维修费','total',1,'维修费'),
	(167,'维修费 减 抹零金额 减 收款金额','(total - preferencemoney - totalinmoney)',1,'维修费-抹零金额-收款金额'),
	(167,'维修费 减 抹零金额','(total - preferencemoney)',1,'维修费-抹零金额'),
	------------------------整机更换单
	(168,'收款金额','totalinmoney',1,'收款金额'),
	(168,'抹零金额','preferencemoney',1,'抹零金额'),
	(168,'维修费','total',1,'维修费'),
	(168,'维修费 减 抹零金额 减 收款金额','(total - preferencemoney - totalinmoney)',1,'维修费-抹零金额-收款金额'),
	(168,'维修费 减 抹零金额','(total - preferencemoney)',1,'维修费-抹零金额'),
	(168,'成本金额','costtotal',1,'成本金额'),
	------------------------送修返回单
	(170,'付款金额','totalinmoney',1,'付款金额'),
	(170,'抹零金额','preferencemoney',1,'抹零金额'),
	(170,'维修费','total',1,'维修费'),
	(170,'维修费 减 抹零金额 减 付款金额','(total - preferencemoney - totalinmoney)',1,'维修费-抹零金额-付款金额'),
	(170,'维修费 减 抹零金额','(total - preferencemoney)',1,'维修费-抹零金额'),
	------------------------上门维修单 
	(172,'收款金额','totalinmoney',1,'收款金额'),
	(172,'抹零金额','preferencemoney',1,'抹零金额'),
	(172,'维修费合计','totalmoney',1,'维修费合计'),
	(172,'维修费合计 减 抹零金额 减 收款金额','(totalmoney - preferencemoney - totalinmoney)',1,'维修费合计-抹零金额-收款金额'),
	(172,'维修费合计 减 抹零金额','(totalmoney - preferencemoney)',1,'维修费合计-抹零金额'),
	(172,'成本金额','costtotal',1,'成本金额'),
	---------------------业务凭证
	(159,'单据上当前借方项目金额','j_total',1,'单据上当前借方项目金额'),
	(159,'单据上当前贷方项目金额','d_total',1,'单据上当前贷方项目金额'),
	---------------------维修品调入
	(173,'成本金额','costtotal',1,'成本金额'),
	---------------------维修品调出
	(174,'成本金额','costtotal',1,'成本金额')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Express='(outcosttotal - incosttotal)' AND BillType = 160)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES  ( 160 ,
	          '出库成本金额 减 入库成本金额' , 
	          '(outcosttotal - incosttotal)' , 
	          '出库成本金额-入库成本金额' , 
	          1
	        )
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE FullName = '税率' AND Sysrow = 1 AND BillType = 6)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES  ( 6 , 
	          '税率' , 
	          '(Tax/100)' , 
	          '税率' , 
	          1
	        )
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE FullName = '税率' AND Sysrow = 1 AND BillType = 161)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES  ( 161 , 
	          '税率' , 
	          '(Tax/100)' , 
	          '税率' , 
	          1
	        )
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE FullName = '材料成本差异额' AND Sysrow = 1 AND BillType = 6)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	    
	VALUES  ( 6 , 
	          '材料成本差异额' , 
	          '(taxtotal-costtotal-(taxTotal - total))*(1+(Tax/100))' , 
	          '(价税合计-成本金额-税额)*(1+税率)' ,
	          1 
	        )
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE FullName = '材料成本差异额' AND Sysrow = 1 AND BillType = 161)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES  ( 161 , 
	          '材料成本差异额' , 
	          '(outstocktaxtotal-outcosttotal-(outstocktaxTotal - outstocktotal))*(1+(Tax/100))' , 
	          '(出库价税合计-出库成本金额-出库部分税额)*(1+税率)' ,
	          1 
	        )
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE FullName = '材料成本差异税额' AND Sysrow = 1 AND BillType = 6)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES  ( 6 , 
	          '材料成本差异税额' , 
	          '(taxtotal-costtotal-(taxTotal - total))*(Tax/100)' , 
	          '(价税合计-成本金额-税额)*税率' ,
	          1 
	        )
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE FullName = '材料成本差异税额' AND Sysrow = 1 AND BillType = 161)
BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES  ( 161 , 
	          '材料成本差异税额' , 
	          '(outstocktaxtotal-outcosttotal-(outstocktaxTotal - outstocktotal))*(Tax/100)' , 
	          '(出库价税合计-出库成本金额-出库部分税额)*税率' ,
	          1 
	        )
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Express = 'balancemoney' AND Sysrow = 1 AND BillType = 0)
BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES  ( 0 , 
	          '平衡数' , 
	          'balancemoney' , 
	          '借方:平衡数=贷方总额-非平衡数借方总额,贷方:平衡数=借方总额-非平衡数贷方总额' ,
	          1 
	        )
END
GO

--Mark:sp5 1454 确认先屏蔽
--2013-05-21调整此功能，放开
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE FullName='累计折旧科目余额' AND Sysrow = 1 AND BillType = 85)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES(85,'累计折旧科目余额','ac_balanceB','累计折旧科目余额',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE FullName='固定资产科目余额' AND Sysrow = 1 AND BillType = 85)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES(85,'固定资产科目余额','ac_balanceA','固定资产科目余额',1)
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 212) --固定资产增加
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(212,'金额','total',1,'金额'),
	(212,'税额','(taxtotal- total)',1,'税额'),
	(212,'价税合计','taxTotal',1,'价税合计'),
	(212,'实付金额','totalinmoney',1,'实付金额'),
	(212,'价税合计 减 实付金额','(taxTotal-totalinmoney)',1,'价税合计-实付金额'),
	(212,'金额 加 税额 减 实付金额','(taxTotal-totalinmoney)',1,'金额+税额-实付金额'),
	(212,'累计折旧','ac_balanceB',1,'累计折旧'),
	(212,'固定资产原值','cardtotal',1,'固定资产原值')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 213) --固定资产减少
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(213,'金额','total',1,'金额'),
	(213,'税额','(taxtotal- total)',1,'税额'),
	(213,'价税合计','taxTotal',1,'价税合计'),
	(213,'实收金额','totalinmoney',1,'实收金额'),
	(213,'累计折旧','ac_balanceB',1,'累计折旧'),
	(213,'固定资产原值','cardtotal',1,'固定资产原值'),
	(213,'价税合计 减 实收金额','(total+(taxtotal- total)-totalinmoney)',1,'价税合计 减 实收金额'),
	(213,'固定资产减值准备','devalueready',1,'固定资产减值准备')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 214) --固定资产折旧
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(214,'固定资产折旧额','deptotal',1,'固定资产折旧额'),
	(214,'固定资产原值','total',1,'固定资产原值'),
	(214,'固定资产净值','netvalue',1,'固定资产净值'),
	(214,'固定资产残值','total-netvalue',1,'固定资产残值'),
	(214,'固定资产减值准备','devalueready',1,'固定资产减值准备')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 410) --固定资产变更
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(410,'入账原值差异','TotalDif',1,'入账原值差异'),
	(410,'累计折旧差异','DepTotalDif',1,'累计折旧差异'),
	(410,'入账原值差异-汇率影响原值','(TotalDif-NetValueDif)',1,'入账原值差异-汇率影响原值'),
	(410,'汇率影响原值','NetValueDif',1,'汇率影响原值'),
	(410,'累计折旧差异','DepTotalDif',1,'累计折旧差异')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 414) --运输配送单
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(414,'合计运费*（1-税率）','totalfreight*(1-(Tax/100))',1,'合计运费*（1-税率）'),
	(414,'合计运费*税率','totalfreight*(Tax/100)',1,'合计运费*税率'),
	(414,'付款金额','totalinmoney',1,'付款金额'),
	(414,'合计运费 减 付款金额','totalfreight-totalinmoney',1,'合计运费 减 付款金额')
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = -1) --固定资产部门变更
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(-1,'固定资产折旧额','deptotal',1,'固定资产折旧额'),
	(-1,'固定资产原值','total',1,'固定资产原值'),
	(-1,'固定资产减值准备','devalueready',1,'固定资产减值准备')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = -2) --减值准备
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(-2,'金额','devalueready',1,'金额')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 215) --零售退货单
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(215,'付款金额','totalinmoney',1,'付款金额'),
	(215,'抹零金额','preferencemoney',1,'抹零金额'),
	(215,'成本金额','costtotal',1,'成本金额'),  
	(215,'折后金额','total',1,'折后金额'),
	(215,'价税合计','taxtotal',1,'价税合计'),
	(215,'应付金额','taxtotal',1,'应付金额')
END
GO

--(161,'抹零后金额 减 实付金额','(instocktaxtotal - outstocktaxtotal - preferencemoney - totalinmoney)',1,'抹零后金额-实付金额')

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 161 AND FullName='抹零后金额 减 实收金额') 
BEGIN
	UPDATE Ac_BillMoney_List
	SET FullName='抹零后金额 减 实付金额',
		Express='instocktaxtotal - outstocktaxtotal - preferencemoney - totalinmoney',
		Content='抹零后金额-实付金额'
	WHERE BillType=161 
	AND FullName='抹零后金额 减 实收金额'
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 147) --零售退货单
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
        ( BillType ,
          FullName ,
          Express ,
          Sysrow,
          Content
        )
	VALUES  
	(147,'调整差额','totalmoney-total',1,'调整差额')
END
GO
----------------------------------9.4添加----------------------------------
--调拨单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 310)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Sysrow,
	          Content 
	        )
	VALUES
	(310,'调拨金额（现金）','transferprice_c',1,'调拨金额（现金）'),
	(310,'调拨金额（银行存款）','transferprice_b',1,'调拨金额（银行存款）'),
	(310,'调拨金额','transferprice',1,'调拨金额')
END
GO

--调拨单 手续费金额
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 310 AND Express = 'deductprice')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES
	(310,'手续费金额','deductprice','手续费金额',1),
	(310,'手续费金额（现金）','deductprice_c','手续费金额（现金）',1),
	(310,'手续费金额（账户）','deductprice_b','手续费金额（账户）',1),
	(310,'调拨总额（现金）','(transferprice_c + deductprice_c)','调拨金额（现金） + 手续费金额（现金）',1),
	(310,'调拨总额（账户）','(transferprice_b + deductprice_b)','调拨金额（银行存款） + 手续费金额（账户）',1)
END
GO


--提成单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 311)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES (311,'提成金额','commissiontotal','提成金额',1)
END
GO


--采购入库
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 34 AND Express='costtotal_S')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES (34,'成本金额(服务商品)','costtotal_S','成本金额(服务商品)',1)
	
	UPDATE Ac_BillMoney_List
	SET FullName='成本金额(库存商品)',Content='成本金额(库存商品)'
	WHERE BillType=34 AND Sysrow=1 AND Express='costtotal'
END
GO

--采购退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 6 AND Express='costtotal_S')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES (6,'成本金额(服务商品)','costtotal_S','成本金额(服务商品)',1)
	
	UPDATE Ac_BillMoney_List
	SET FullName='成本金额(库存商品)',Content='成本金额(库存商品)'
	WHERE BillType=6 AND Sysrow=1 AND Express='costtotal'

	UPDATE Ac_BillMoney_List
	SET FullName='折后金额 减 成本金额(库存商品)',Content='折后金额-成本金额(库存商品)'
	WHERE BillType=6 AND Sysrow=1 AND Express='(total - costtotal)'
	
	UPDATE dbo.Ac_BillMoney_List
	SET Content='(价税合计-成本金额(库存商品)-税额)*(1+税率)'
	WHERE BillType = 6 AND Sysrow = 1 AND Express='(taxtotal-costtotal-(taxTotal - total))*(1+(Tax/100))'
	
	UPDATE dbo.Ac_BillMoney_List
	SET Content='(价税合计-成本金额(库存商品)-税额)*税率'
	WHERE BillType = 6 AND Sysrow = 1 AND Express='(taxtotal-costtotal-(taxTotal - total))*(Tax/100)'
END
GO

--采购换货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 161 AND Express='outcosttotal_S')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES 
	(161,'出库成本金额(服务商品)','outcosttotal_S','出库成本金额(服务商品)',1),
	(161,'入库成本金额(服务商品)','incosttotal_S','入库成本金额(服务商品)',1),
	(161,'入库成本金额(服务商品) 减 出库成本金额(服务商品)','(incosttotal_S - outcosttotal_S)','入库成本金额(服务商品) - 出库成本金额(服务商品)',1)
	
	UPDATE Ac_BillMoney_List
	SET FullName='出库成本金额(库存商品)',Content='出库成本金额(库存商品)'
	WHERE BillType=161 AND Sysrow=1 AND Express='outcosttotal'
	
	UPDATE Ac_BillMoney_List
	SET FullName='入库成本金额(库存商品)',Content='入库成本金额(库存商品)'
	WHERE BillType=161 AND Sysrow=1 AND Express='incosttotal'
	
	UPDATE Ac_BillMoney_List
	SET FullName='出库折后金额 减 出库成本金额(库存商品)',Content='出库折后金额-出库成本金额(库存商品)'
	WHERE BillType=161 AND Sysrow=1 AND Express='(outstocktotal - outcosttotal)'

	UPDATE Ac_BillMoney_List
	SET FullName='入库成本金额(库存商品) 减 出库成本金额(库存商品)',Content='入库成本金额(库存商品)-出库成本金额(库存商品)'
	WHERE BillType=161 AND Sysrow=1 AND Express='(incosttotal - outcosttotal)'

	UPDATE Ac_BillMoney_List
	SET Content='(出库价税合计-出库成本金额(库存商品)-出库部分税额)*(1+税率)'
	WHERE BillType=161 AND Sysrow=1 AND Express='(outstocktaxtotal-outcosttotal-(outstocktaxTotal - outstocktotal))*(1+(Tax/100))'

	UPDATE Ac_BillMoney_List
	SET Content='(出库价税合计-出库成本金额(库存商品)-出库部分税额)*税率'
	WHERE BillType=161 AND Sysrow=1 AND Express='(outstocktaxtotal-outcosttotal-(outstocktaxTotal - outstocktotal))*(Tax/100)'

END
GO

--零售单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 305 AND Express='total_S')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES (305,'折后金额(服务商品)','total_S','折后金额(服务商品)',1)
	
	UPDATE Ac_BillMoney_List
	SET FullName='折后金额(库存商品)',Content='折后金额(库存商品)'
	WHERE BillType=305 AND Sysrow=1 AND Express='total'
END
GO

--零售退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 215 AND Express='total_S')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES (215,'折后金额(服务商品)','total_S','折后金额(服务商品)',1)
	
	UPDATE Ac_BillMoney_List
	SET FullName='折后金额(库存商品)',Content='折后金额(库存商品)'
	WHERE BillType=215 AND Sysrow=1 AND Express='total'
END
GO

--销售出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 11 AND Express='total_S')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES (11,'折后金额(服务商品)','total_S','折后金额(服务商品)',1)
	
	UPDATE Ac_BillMoney_List
	SET FullName='折后金额(库存商品)',Content='折后金额(库存商品)'
	WHERE BillType=11 AND Sysrow=1 AND Express='total'
END
GO

--销售退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 45 AND Express='total_S')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES (45,'折后金额(服务商品)','total_S','折后金额(服务商品)',1)
	
	UPDATE Ac_BillMoney_List
	SET FullName='折后金额(库存商品)',Content='折后金额(库存商品)'
	WHERE BillType=45 AND Sysrow=1 AND Express='total'
END
GO

--销售换货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Sysrow = 1 AND BillType = 160 AND Express='outstocktotal_S')
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES 
	(160,'出库折后金额(服务商品)','outstocktotal_S','出库折后金额(服务商品)',1),
	(160,'入库折后金额(服务商品)','instocktotal_S','入库折后金额(服务商品)',1),
	(160,'出库折后金额(服务商品) 减 入库折后金额(服务商品)','(outstocktotal_S - instocktotal_S)','出库折后金额(服务商品) - 入库折后金额(服务商品)',1)
	
	UPDATE Ac_BillMoney_List
	SET FullName='出库折后金额(库存商品)',Content='出库折后金额(库存商品)'
	WHERE BillType=160 AND Sysrow=1 AND Express='outcosttotal'
	
	UPDATE Ac_BillMoney_List
	SET FullName='入库折后金额(库存商品)',Content='入库折后金额(库存商品)'
	WHERE BillType=160 AND Sysrow=1 AND Express='instocktotal'
	
	UPDATE Ac_BillMoney_List
	SET FullName='出库折后金额(库存商品) 减 入库折后金额(库存商品)',Content='出库折后金额(库存商品)-入库折后金额(库存商品)'
	WHERE BillType=160 AND Sysrow=1 AND Express='(outstocktotal - instocktotal)'
END
GO

--针对原有复合金额调整
--采购退货6
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 6 AND FullName = '材料成本差异额' AND Express = '(taxtotal-costtotal-(taxTotal - total))*(1+(Tax/100))')
BEGIN
	UPDATE dbo.Ac_BillMoney_List SET Express = '(taxtotal-costtotal-costtotal_s-(taxTotal - total))*(1+(Tax/100))' 
	WHERE BillType = 6 AND FullName = '材料成本差异额'
END
GO
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 6 AND FullName = '材料成本差异税额' AND Express = '(taxtotal-costtotal-(taxTotal - total))*(Tax/100)')
BEGIN
	UPDATE dbo.Ac_BillMoney_List SET Express = '(taxtotal-costtotal-costtotal_s-(taxTotal - total))*(Tax/100)' 
	WHERE BillType = 6 AND FullName = '材料成本差异税额'
END
GO
--采购换货161
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 161 AND FullName = '材料成本差异额' AND Express = '(outstocktaxtotal-outcosttotal-(outstocktaxtotal - outstocktotal))*(1+(tax/100))')
BEGIN
	UPDATE dbo.Ac_BillMoney_List SET Express = '(outstocktaxtotal-outcosttotal-outcosttotal_s-(outstocktaxtotal - outstocktotal))*(1+(tax/100))' 
	WHERE BillType = 161 AND FullName = '材料成本差异额'
END
GO
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType= 161 AND FullName = '材料成本差异税额' AND Express='(outstocktaxtotal-outcosttotal-(outstocktaxTotal - outstocktotal))*(Tax/100)')
BEGIN
	UPDATE dbo.Ac_BillMoney_List SET Express='(outstocktaxtotal-outcosttotal-outcosttotal_s-(outstocktaxTotal - outstocktotal))*(Tax/100)'
	WHERE BillType = 161 AND FullName = '材料成本差异税额'
END
GO
--销售出库11
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 11 AND FullName = '税额' AND Express='(taxtotal - total)')
BEGIN
	UPDATE dbo.Ac_BillMoney_List SET Express = '(taxtotal-total-total_s)'
	WHERE BillType = 11 AND FullName = '税额'
END
GO
--销售退货45
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 45 AND FullName = '税额' AND Express='(taxtotal - total)')
BEGIN
	UPDATE dbo.Ac_BillMoney_List SET Express = '(taxtotal-total-total_s)'
	WHERE BillType = 45 AND FullName = '税额'
END
GO
--销售换货160
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 160 AND FullName = '出库税额 减 入库税额' AND Express='(outstocktaxtotal - outstocktotal - instocktaxtotal + instocktotal)')
BEGIN
	UPDATE dbo.Ac_BillMoney_List SET Express='(outstocktaxtotal - outstocktotal - outstocktotal_s - instocktaxtotal + instocktotal + instocktotal_s)'
	WHERE BillType = 160 AND FullName = '出库税额 减 入库税额'
END
GO

--会员批量储值充值单312
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 312 )
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Sysrow,
	          Content
	        )
	VALUES 
	(312,'充值金额合计','totalmoney',1,'充值金额合计'),
	(312,'实收金额合计','totalinmoney',1,'实收金额合计'),
	(312,'抹零金额合计','preferencemoney',1,'抹零金额合计'),
	(312,'充值金额合计 减 抹零金额合计 减 实收金额合计','(totalmoney - preferencemoney - totalinmoney)',1,'充值金额合计—抹零金额合计—实收金额合计')
END


--9.6添加 发出商品出库，发出商品退货，暂估入库，暂估退货，采购暂估开票，成本调价（入库），成本调价（出库-销出）
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 402 )
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Sysrow,
	          Content
	        )
	VALUES 
	(402,'成本金额','costtotal',1,'成本金额'),	--发出商品出库
	(403,'成本金额','costtotal',1,'成本金额'),	--发出商品退货
	(400,'成本金额','costtotal',1,'成本金额'),	--暂估入库
	(401,'成本金额','costtotal',1,'成本金额'),	--暂估退货
	(404,'采购金额','total',1,'采购金额'),(404,'税额','(taxtotal- total)',1,'税额'),(404,'价税合计','taxTotal',1,'价税合计'),	--采购暂估开票 税额，加税合计，采购金额
	(405,'价税合计','taxTotal',1,'价税合计'),(405,'销售金额','total',1,' 销售金额'),(405,'税额','(taxtotal- total)',1,'税额'),(405,'本次开票成本','InvoiceCostTotal',1,'本次开票成本'), --销售发货开票
	(406,'价税合计','taxTotal',1,'价税合计'),(406,'销售金额','total',1,' 销售金额'),(406,'税额','(taxtotal- total)',1,'税额'),  --采购发货开票
	(57,'调整金额','costtotal',1,'调整金额'),  --成本调价（入库） （出库-销出）
	(57,'调整金额','changetotal',1,'调整金额')  --成本调价（入库） （出库-销出）
END

--9.7添加 往来核销单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 450 )
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Sysrow,
	          Content
	        )
	VALUES 
	(450,'核销金额','chargeoffvalue',1,'核销金额')
END
--组合品销售出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 12 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		(12,'抹零后金额 减 收款金额','(taxTotal - preferencemoney - totalinmoney)',1,'抹零后金额-收款金额',0),
		(12,'收款金额','totalinmoney',1,'收款金额',0),
		(12,'折后金额(库存商品)','total',1,'折后金额(库存商品)',0),
		(12,'折后金额(服务商品)','total_S',1,'折后金额(服务商品)',0),
		(12,'抹零金额','preferencemoney',1,'抹零金额',0),
		(12,'税额','(taxTotal-total-total_S)',1,'税额',0),
		(12,'成本金额','costtotal',1,'成本金额',1),
		(12,'价税合计','taxtotal',1,'价税合计',0),
		(12,'抹零后金额','(taxTotal- preferencemoney)',1,'抹零后金额',0)
	END
--组合品销售退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 46 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		(46,'抹零后金额 减 实付金额','(taxTotal - preferencemoney - totalinmoney)',1,'抹零后金额-实付金额',0),
		(46,'实付金额','totalinmoney',1,'实付金额',0),
		(46,'折后金额(库存商品)','total',1,'折后金额(库存商品)',0),
		(46,'折后金额(服务商品)','total_S',1,'折后金额(服务商品)',0),
		(46,'抹零金额','preferencemoney',1,'抹零金额',0),
		(46,'税额','(taxTotal-total-total_S)',1,'税额',0),
		(46,'成本金额','costtotal',1,'成本金额',1),
		(46,'价税合计','taxtotal',1,'价税合计',0),
		(46,'抹零后金额','(taxTotal - preferencemoney)',1,'抹零后金额',0)
	END

--修改凭证金额来源成本类标志
UPDATE Ac_BillMoney_List SET isCost=1 
WHERE 
	BillType IN(305,215,11,45,160,139,140,142,141,402,403,405,12,46)
	AND FullName LIKE'%成本%'
GO
--存货类型文档添加
--成本金额
INSERT INTO Ac_BillMoney_List
(
	BillType,
	FullName,
	Express,
	Content,
	Sysrow,
	isCost
)
SELECT DISTINCT
	BillType,
	'成本金额' FullName,
	'costtotal' Express,
	'成本金额' Content,
	1 Sysrow,
	1 isCost 
FROM Ac_BillMoney_List
WHERE 
	BillType IN (305,215,11,45,160,139,140,142,141,402,403,12,46,34,6,161,126,144,146,145,147,400,401,21,187,188,9,14,16,202,201,414,166,167,168,170,172,173,174,57,404,405,183)
	AND BillType NOT IN(
		SELECT BillType FROM Ac_BillMoney_List WHERE BillType IN(305,215,11,45,160,139,140,142,141,402,403,12,46,34,6,161,126,144,146,145,147,400,401,21,187,188,9,14,16,202,201,414,166,167,168,170,172,173,174,57,404,405,183) AND FullName='成本金额'
	) 
--折后金额（库存商品）
INSERT INTO Ac_BillMoney_List
(
	BillType,
	FullName,
	Express,
	Content,
	Sysrow,
	isCost
)
SELECT DISTINCT
	BillType,
	'折后金额（库存商品）' FullName,
	'total' Express,
	'折后金额（库存商品）' Content,
	1 Sysrow,
	0 isCost 
FROM Ac_BillMoney_List
WHERE 
	BillType IN (305,215,11,45,160,139,140,142,141,402,403,12,46,34,6,161,126,144,146,145,147,400,401,21,187,188,9,14,16,202,201,414,166,167,168,170,172,173,174,57,404,405,183)
	AND BillType NOT IN(
		SELECT BillType FROM Ac_BillMoney_List WHERE BillType IN(305,215,11,45,160,139,140,142,141,402,403,12,46,34,6,161,126,144,146,145,147,400,401,21,187,188,9,14,16,202,201,414,166,167,168,170,172,173,174,57,404,405,183) AND FullName='折后金额（库存商品）'
	)
GO
IF NOT EXISTS (SELECT 1 FROM Ac_BillMoney_List WHERE BillType = 57 AND FullName = '调整金额' AND Content = '调整金额' AND Express = 'changetotal')
    BEGIN 
        INSERT  INTO dbo.Ac_BillMoney_List
                ( BillType ,
                  FullName ,
                  Express ,
                  Sysrow ,
                  Content
	            )
        VALUES  ( 57 ,
                  '调整金额' ,
                  'changetotal' ,
                  1 ,
                  '调整金额'
                )  --成本调价（入库） （出库-销出）
    END 

IF EXISTS (SELECT 1 FROM Ac_BillMoney_List WHERE BillType = 57 AND FullName = '调整金额' AND Content = '调整金额' AND Express = 'total')
BEGIN 
    UPDATE dbo.Ac_BillMoney_List SET Express = 'costtotal' WHERE BillType = 57 AND FullName = '调整金额' AND Content = '调整金额' AND Express = 'total'
END 

--9.8稳定bug2088 成本调价单不要成本金额
IF  EXISTS (SELECT 1 FROM Ac_BillMoney_List WHERE BillType = 57 AND FullName = '成本金额')
    BEGIN 
        DELETE FROM dbo.Ac_BillMoney_List WHERE BillType = 57 AND FullName = '成本金额'
    END 
	
--===============================983新增【BEGIN】===============================
-- 423优惠券入库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 423 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		(423,'成本金额','costtotal',1,'成本金额',0),
		(423,'实付金额','totalinmoney',1,'实付金额',0),
		(423,'成本金额 减 收付款金额 减 抹零金额','costtotal-totalinmoney-preferencemoney',1,'成本金额 减 收付款金额 减 抹零金额',0),
		(423,'抹零金额','preferencemoney',1,'抹零金额',0)
	END
GO

--424	优惠券出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 424 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		(424,'实收金额','totalinmoney',1,'实收金额',0),
		(424,'代金券面值 减 代金券金额 加 抹零金额','d_couponvalue-d_totalmoney+preferencemoney',1,'代金券面值 减 代金券金额 加 抹零金额',0),
		(424,'金额 减 实收金额 减 抹零金额','totalmoney-totalinmoney-preferencemoney',1,'金额 减 实收金额 减 抹零金额',0),
		(424,'折扣券金额','z_totalmoney',1,'折扣券金额',0),
		(424,'代金券面值 加 兑换券出库金额','d_couponvalue+d_outtotal',1,'代金券面值 加 兑换券出库金额',0)
	END
GO 
--426	优惠券退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 426 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		(426,'折扣券金额','z_totalmoney',1,'折扣券金额',0),
		(426,'代金券面值 加 兑换券出库金额','d_couponvalue+d_outtotal',1,'代金券面值 加 兑换券出库金额',0),
		(426,'实收金额','totalinmoney',1,'实收金额',0),
		(426,'代金券面值 减 代金券金额 加 抹零金额','d_couponvalue-d_totalmoney+preferencemoney',1,'代金券面值 减 代金券金额 加 抹零金额',0),
		(426,'金额 减 实付金额 减 抹零金额','totalmoney-totalinmoney-preferencemoney',1,'金额 减 实付金额 减 抹零金额',0),
		(426,'兑换券出库金额 减 兑换券退货金额','d_outtotal-d_backtotal',1,'兑换券出库金额 减 兑换券退货金额',0)
	END
GO 

--在【零售单、零售退货单、销售出库单、销售退货单、组合品销售出库单、组合品销售退货单】这几张单据的凭证模板里的金额来源处新增一个：“代金券差额”的金额字段；具体取值，用当前单据对应的【代金券面值总和-适用代金券商品的价税合计之和】，
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType=305 AND FullName='代金券差额')
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		SELECT 305,'代金券差额','couponDifferenceValue',1,'代金券差额',0 UNION
		SELECT 215,'代金券差额','couponDifferenceValue',1,'代金券差额',0 UNION
		SELECT 11,'代金券差额','couponDifferenceValue',1,'代金券差额',0 UNION
		SELECT 45,'代金券差额','couponDifferenceValue',1,'代金券差额',0 UNION
		SELECT 12,'代金券差额','couponDifferenceValue',1,'代金券差额',0 UNION
		SELECT 46,'代金券差额','couponDifferenceValue',1,'代金券差额',0
	END
--427	积分转储值单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 427 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		(427,'转储值的金额','z_totalmoney',1,'转储值的金额',0),		
		(428,'金额','totalmoney',1,'金额',0),		
		(429,'金额','totalmoney',1,'金额',0)		
	END
GO 
---991新增---
-- ?门店配送单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 327 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		
		(327,'配送金额','total',1,'配送金额',0),
		(327,'出库成本','outcosttotal',1,'出库成本',0),	
		(327,'配送金额 减 出库成本','total-outcosttotal',1,'配送金额 减 出库成本',0),	
		(327,'成本金额','costtotal',1,'成本金额',0)		
	END
GO
-- ?门店配送退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 328 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		
		(328,'配送金额','total',1,'配送金额',0),
		(328,'出库成本','outcosttotal',1,'出库成本',0),	
		(328,'配送金额 减 出库成本','total-outcosttotal',1,'配送金额 减 出库成本',0),	
		(328,'成本金额','costtotal',1,'成本金额',0)		
	END
GO
-- ?配送验收单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 329 )
	BEGIN
		INSERT INTO dbo.Ac_BillMoney_List
		( 
			BillType ,
			FullName ,
			Express ,
			Sysrow,
			Content,
			isCost
		)
		VALUES 
		
		(329,'配送金额','total',1,'配送金额',0),
		(329,'出库成本','outcosttotal',1,'出库成本',0),	
		(329,'配送金额 减 出库成本','total-outcosttotal',1,'配送金额 减 出库成本',0),	
		(329,'成本金额','costtotal',1,'成本金额',0)		
	END
GO
--===============================983新增【END】===============================   
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BILLMONEY_LIST') AND name = 'CIX_AC_BILLMONEY_LIST_Billmoneyid')
--DROP INDEX CIX_AC_BILLMONEY_LIST_Billmoneyid ON AC_BILLMONEY_LIST 
CREATE CLUSTERED INDEX CIX_AC_BILLMONEY_LIST_Billmoneyid ON AC_BILLMONEY_LIST(Billmoneyid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_BILLMONEY_LIST') AND name = 'NCIX_AC_BILLMONEY_LIST_Billtype')
--DROP INDEX NCIX_AC_BILLMONEY_LIST_Billtype ON AC_BILLMONEY_LIST 
CREATE NONCLUSTERED INDEX NCIX_AC_BILLMONEY_LIST_Billtype ON AC_BILLMONEY_LIST(Billtype) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_CashMoneyItems')
            and   type = 'U')
BEGIN
	create table Ac_CashMoneyItems (
	   TypeId               varchar(50)          not null,
	   ParId                varchar(50)          not null,
	   Leveal               int                  not null,
	   SonNum               int                  not null,
	   SonCount             int                  not null,
	   UserCode             varchar(200)         not null,
	   FullName             varchar(200)         not null,
	   PyCode               varchar(200)         null
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_CashMoneyItems' AND a.Name='Sysrow'
)
BEGIN
	ALTER TABLE Ac_CashMoneyItems 
		ADD Sysrow INT NOT NULL DEFAULT(0)	
END
GO
--========================================预设数据===========================================廖晨羽
IF((SELECT COUNT(typeid) FROM Ac_CashMoneyItems) = 0)
BEGIN
	INSERT Ac_CashMoneyItems VALUES('00000','root',0,5,5,'abc','ABC','',1),
								   ('00001','00000',1,2,2,'CI1','经营活动产生的现金流量','',1),
								   ('0000100001','00001',2,3,3,'CI1.01','现金流入','',1),
								   ('0000100002','00001',2,4,4,'CI1.02','现金流出','',1),
								   ('000010000100001','0000100001',3,0,0,'CI1.01.01','销售商品、提供劳务收到的现金','',1),
								   ('000010000100002','0000100001',3,0,0,'CI1.01.02','收到的税费返还','',1),
								   ('000010000100003','0000100001',3,0,0,'CI1.01.03','收到其他与经营活动有关的现金','',1),
								   ('000010000200001','0000100002',3,0,0,'CI1.02.01','购买商品、接受劳务支付的现金','',1),
								   ('000010000200002','0000100002',3,0,0,'CI1.02.02','支付给职工以及为职工支付的现金','',1),
								   ('000010000200003','0000100002',3,0,0,'CI1.02.03','支付的各项税费','',1),
								   ('000010000200004','0000100002',3,0,0,'CI1.02.04','支付其他与经营活动有关的现金','',1),
								   ('00002','00000',1,2,2,'CI2','投资活动产生的现金流量','',1),
								   ('0000200001','00002',2,5,5,'CI2.01','现金流入','',1),
								   ('0000200002','00002',2,4,4,'CI2.02','现金流出','',1),
								   ('000020000100001','0000200001',3,0,0,'CI2.01.01','收回投资收到的现金','',1),
								   ('000020000100002','0000200001',3,0,0,'CI2.01.02','取得投资收益收到的现金','',1),
								   ('000020000100003','0000200001',3,0,0,'CI2.01.03','处置固定资产、无形资产和其他长期资产收回的现金净额','',1),
								   ('000020000100004','0000200001',3,0,0,'CI2.01.04','处置子公司及其他营业单位收到的现金净额','',1),
								   ('000020000100005','0000200001',3,0,0,'CI2.01.05','收到其他与投资活动有关的现金','',1),
								   ('000020000200001','0000200002',3,0,0,'CI2.02.01','购建固定资产、无形资产和其他长期资产支付的现金','',1),
								   ('000020000200002','0000200002',3,0,0,'CI2.02.02','投资支付的现金','',1),
								   ('000020000200003','0000200002',3,0,0,'CI2.02.03','取得子公司及其他营业单位支付的现金净额','',1),
								   ('000020000200004','0000200002',3,0,0,'CI2.02.04','支付其他与投资活动有关的现金','',1),
								   ('00003','00000',1,2,2,'CI3','筹资活动产生的现金流量','',1),
								   ('0000300001','00003',2,3,3,'CI3.01','现金流入','',1),
								   ('0000300002','00003',2,3,3,'CI3.02','现金流出','',1),
								   ('000030000100001','0000300001',3,0,0,'CI3.01.01','吸收投资收到的现金','',1),
								   ('000030000100002','0000300001',3,0,0,'CI3.01.02','取得借款收到的现金','',1),
								   ('000030000100003','0000300001',3,0,0,'CI3.01.03','收到其他与筹资活动有关的现金','',1),
								   ('000030000200001','0000300002',3,0,0,'CI3.02.01','偿还债务支付的现金','',1),
								   ('000030000200002','0000300002',3,0,0,'CI3.02.02','分配股利、利润或偿付利息支付的现金','',1),
								   ('000030000200003','0000300002',3,0,0,'CI3.02.03','支付其他与筹资活动有关的现金','',1),
								   ('00004','00000',1,2,2,'CI4','汇率变动产生的现金流量','',1),
								   ('0000400001','00004',2,0,0,'CI4.01','现金流入','',1),
								   ('0000400002','00004',2,0,0,'CI4.02','现金流出','',1),
								   ('00005','00000',1,2,2,'CI5','现金流量附表项目','',1),
								   ('0000500001','00005',2,16,16,'CI5.01','将净利润调节为经营活动现金流量','',1),
								   ('0000500002','00005',2,3,3,'CI5.02','不涉及现金收支的重大投资和筹资活动','',1),
								   ('000050000100001','0000500001',3,0,0,'CI5.01.01','净利润','',1),
								   ('000050000100002','0000500001',3,0,0,'CI5.01.02','资产减值准备','',1),
								   ('000050000100003','0000500001',3,0,0,'CI5.01.03','固定资产折旧、油气资产折耗、生产性生物资产折旧','',1),
								   ('000050000100004','0000500001',3,0,0,'CI5.01.04','无形资产摊销','',1),
								   ('000050000100005','0000500001',3,0,0,'CI5.01.05','长期待摊费用摊销','',1),
								   ('000050000100006','0000500001',3,0,0,'CI5.01.06','处置固定资产、无形资产和其他长期资产的损失','',1),
								   ('000050000100007','0000500001',3,0,0,'CI5.01.07','固定资产报废损失','',1),
								   ('000050000100008','0000500001',3,0,0,'CI5.01.08','公允价值变动损失','',1),
								   ('000050000100009','0000500001',3,0,0,'CI5.01.09','财务费用','',1),
								   ('000050000100010','0000500001',3,0,0,'CI5.01.10','投资损失','',1),
								   ('000050000100011','0000500001',3,0,0,'CI5.01.11','递延所得税资产减少','',1),
								   ('000050000100012','0000500001',3,0,0,'CI5.01.12','递延所得税负债增加','',1),
								   ('000050000100013','0000500001',3,0,0,'CI5.01.13','存货的减少','',1),
								   ('000050000100014','0000500001',3,0,0,'CI5.01.14','经营性应收项目的减少','',1),
								   ('000050000100015','0000500001',3,0,0,'CI5.01.15','经营性应付项目的增加','',1),
								   ('000050000100016','0000500001',3,0,0,'CI5.01.16','其他','',1),
								   ('000050000200001','0000500002',3,0,0,'CI5.02.01','债务转为资本','',1),
								   ('000050000200002','0000500002',3,0,0,'CI5.02.02','一年内到期的可转换公司债券','',1),
								   ('000050000200003','0000500002',3,0,0,'CI5.02.03','融资租入固定资产','',1)
END


GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_CASHMONEYITEMS') AND name = 'CIX_AC_CASHMONEYITEMS_Typeid')
--DROP INDEX CIX_AC_CASHMONEYITEMS_Typeid ON AC_CASHMONEYITEMS 
CREATE CLUSTERED INDEX CIX_AC_CASHMONEYITEMS_Typeid ON AC_CASHMONEYITEMS(Typeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_CASHMONEYITEMS') AND name = 'NCIX_AC_CASHMONEYITEMS_UserCode')
--DROP INDEX NCIX_AC_CASHMONEYITEMS_UserCode ON AC_CASHMONEYITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_CASHMONEYITEMS_UserCode ON AC_CASHMONEYITEMS(UserCode) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS ( SELECT  1
                FROM    sysobjects
                WHERE   id = OBJECT_ID('Ac_CommissionBill_VoucherBill')
                        AND type = 'U' ) 
BEGIN
    CREATE TABLE Ac_CommissionBill_VoucherBill
    (
          Agvbid INT IDENTITY(1, 1) ,
          GoodsBillId NUMERIC(18, 0) NULL DEFAULT ( 0 ) ,
          VourchBillId NUMERIC(18, 0) NULL DEFAULT ( 0 ),
          BillType	INT
     )
END
GO

IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[Ac_CommissionBill_VoucherBill]') AND name = 'BillType' )
BEGIN
	ALTER TABLE dbo.Ac_CommissionBill_VoucherBill ADD
		BillType INT NOT NULL DEFAULT(311)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--优惠券-凭证生成 对应关系表
IF NOT EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE id=OBJECT_ID('Ac_CouponBill_VoucherBill') AND type='U')
BEGIN
	CREATE TABLE Ac_CouponBill_VoucherBill (
	   Acvbid			INT IDENTITY(1,1),
	   CouponBillId		NUMERIC(18,0)	NOT NULL DEFAULT(0),--优惠券ID
	   VourchBillId		NUMERIC(18,0)	NOT NULL DEFAULT(0),--凭证ID
	   BillType			INT				NOT NULL DEFAULT(0)--单据类型  423=优惠券入库单 424=优惠券出库单 426=优惠券退货单
	)
END
GO

--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='Ac_CouponBill_VoucherBill' AND a.Name='InOutType'
--)
--BEGIN
--	ALTER TABLE Ac_CouponBill_VoucherBill 
--		ADD InOutType INT NULL
--END
--GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_CouponBill_VoucherBill') AND name = 'CIX_Ac_CouponBill_VoucherBill_Acvbid')
	CREATE CLUSTERED INDEX CIX_Ac_CouponBill_VoucherBill_Acvbid ON Ac_CouponBill_VoucherBill(Acvbid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_CouponBill_VoucherBill') AND name = 'NCIX_Ac_CouponBill_VoucherBill_CouponBillId')
	CREATE NONCLUSTERED INDEX NCIX_Ac_CouponBill_VoucherBill_CouponBillId ON Ac_CouponBill_VoucherBill(CouponBillId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_CouponBill_VoucherBill') AND name = 'NCIX_Ac_CouponBill_VoucherBill_VourchBillId')
	CREATE NONCLUSTERED INDEX NCIX_Ac_CouponBill_VoucherBill_VourchBillId ON Ac_CouponBill_VoucherBill(VourchBillId) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Currency')
            and   type = 'U')
BEGIN
	create table Ac_Currency (
	   CId                  int                  identity(1,1),
	   UserCode             varchar(200)         not null,
	   FullName             varchar(200)         not null,
	   Rate                 numeric(18,4)        null,
	   BasisType            int                  null,
	   PyCode               varchar(200)         null,
	   Deleted              int                  null
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Currency' AND a.Name='Sysrow'
)
BEGIN
	ALTER TABLE Ac_Currency 
		ADD Sysrow INT NOT NULL DEFAULT(0)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_CURRENCY') AND name = 'CIX_AC_CURRENCY_CId')
--DROP INDEX CIX_AC_CURRENCY_CId ON AC_CURRENCY 
CREATE CLUSTERED INDEX CIX_AC_CURRENCY_CId ON AC_CURRENCY(CId) 

------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------修改数据----------------------------------
UPDATE Ac_Currency SET Sysrow = 0 WHERE Sysrow IS NULL
GO
----------------------------------预制数据----------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Currency)
	BEGIN
		INSERT INTO Ac_Currency([UserCode],[FullName],[Rate],[BasisType],[Deleted],[Sysrow])VALUES('RMB','人民币',1,0,0,1)
	END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Currency' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Currency 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--优惠券-凭证生成 对应关系表
IF NOT EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE id=OBJECT_ID('Ac_DeliveryBill_VoucherBill') AND type='U')
BEGIN
	CREATE TABLE Ac_DeliveryBill_VoucherBill (
	   Acvbid			INT IDENTITY(1,1),
	   DeliveryBillId	NUMERIC(18,0)	NOT NULL DEFAULT(0),--配送单ID
	   VourchBillId		NUMERIC(18,0)	NOT NULL DEFAULT(0),--凭证ID
	   BillType			INT				NOT NULL DEFAULT(0)--单据类型  327=配送单 328=配送退货单 329=验收单
	)
END
GO


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_DeliveryBill_VoucherBill') AND name = 'CIX_Ac_DeliveryBill_VoucherBill_Acvbid')
	CREATE CLUSTERED INDEX CIX_Ac_DeliveryBill_VoucherBill_Acvbid ON Ac_DeliveryBill_VoucherBill(Acvbid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_DeliveryBill_VoucherBill') AND name = 'NCIX_Ac_DeliveryBill_VoucherBill_DeliveryBillId')
	CREATE NONCLUSTERED INDEX NCIX_Ac_DeliveryBill_VoucherBill_DeliveryBillId ON Ac_DeliveryBill_VoucherBill(DeliveryBillId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_DeliveryBill_VoucherBill') AND name = 'NCIX_Ac_DeliveryBill_VoucherBill_VourchBillId')
	CREATE NONCLUSTERED INDEX NCIX_Ac_DeliveryBill_VoucherBill_VourchBillId ON Ac_DeliveryBill_VoucherBill(VourchBillId) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_DepreciationAlteration') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_DepreciationAlteration
	(
		Id					INT	IDENTITY(1,1),
		CardId				INT,
		OldNetSalvage		NUMERIC(22,10),
		NetSalvage			NUMERIC(22,10),
		OldNetSalvageRate	NUMERIC(18,4),
		NetSalvageRate		NUMERIC(18,4),
		OldDepreciationMean	INT,
		DepreciationMean	INT,
		OldDurYear			INT,
		DurYear				INT,
		BusinessDate		DATETIME,
		OperationDate		DATETIME,
		ETypeId				VARCHAR(50)
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='durmonth'
)
BEGIN
	ALTER TABLE Ac_DepreciationAlteration ADD durmonth INT NOT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='BusinessDate'
)
BEGIN
	ALTER TABLE Ac_DepreciationAlteration ADD BusinessDate DATETIME
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='ExpectWork'
)
BEGIN
	ALTER TABLE Ac_DepreciationAlteration ADD ExpectWork NUMERIC(18,10)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='OldExpectWork'
)
BEGIN
	ALTER TABLE Ac_DepreciationAlteration ADD OldExpectWork NUMERIC(18,10)
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='FinishWork'
)
BEGIN
	ALTER TABLE Ac_DepreciationAlteration ADD FinishWork NUMERIC(18,10)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='OldFinishWork'
)
BEGIN
	ALTER TABLE Ac_DepreciationAlteration ADD OldFinishWork NUMERIC(18,10)
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='WorkUnit'
)
BEGIN
	ALTER TABLE Ac_DepreciationAlteration ADD WorkUnit VARCHAR(50)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='OldWorkUnit'
)
BEGIN
	ALTER TABLE Ac_DepreciationAlteration ADD OldWorkUnit VARCHAR(50)
END




GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='OldNetSalvage' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationAlteration 
	ALTER COLUMN OldNetSalvage NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='NetSalvage' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationAlteration 
	ALTER COLUMN NetSalvage NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='OldNetSalvageRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationAlteration 
	ALTER COLUMN OldNetSalvageRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='NetSalvageRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationAlteration 
	ALTER COLUMN NetSalvageRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='ExpectWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationAlteration 
	ALTER COLUMN ExpectWork NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='OldExpectWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationAlteration 
	ALTER COLUMN OldExpectWork NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='FinishWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationAlteration 
	ALTER COLUMN FinishWork NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationAlteration' AND a.Name='OldFinishWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationAlteration 
	ALTER COLUMN OldFinishWork NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_DepreciationMean') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_DepreciationMean
	(
		Id		INT,
		Comment	VARCHAR(200)
	)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_DepreciationMean)
BEGIN
	INSERT INTO Ac_DepreciationMean( Id, Comment )
	VALUES  (0,'不折旧'),
			(1,'手工折旧'),
			(2,'平均年限法'),
			(3,'双倍余额递减法')
END
GO

--2014.04.03增加折旧方法“年数总和法”
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationMean WHERE Comment = '年数总和法')
BEGIN
	INSERT INTO dbo.Ac_DepreciationMean(Id,Comment )
	VALUES  (4,'年数总和法')
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationMean WHERE Comment = '工作量法')
BEGIN
	INSERT INTO dbo.Ac_DepreciationMean(Id,Comment )
	VALUES  (5,'工作量法')
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_DepreciationPlan') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_DepreciationPlan
	(
		Id				INT IDENTITY(1,1),
		STypeId			VARCHAR(50),
		DTypeid			VARCHAR(50),
		CategoryId		INT,
		InAccountDate	DATETIME,
		UserCode		VARCHAR(200),
		FullName		VARCHAR(200),
		DepreciationMean	INT,
		YearOrder		INT,
		FYear			INT,
		FPeroid			INT,
		MonthOrder		INT,
		PlanType		INT,
		AssetCardId		INT,
		Depreciation	NUMERIC(22,10),
		DepTotal		NUMERIC(22,10),
		Total			NUMERIC(22,10),
		DevalueReady	NUMERIC(22,10),
		NetValue		NUMERIC(22,10),
		NetSalvage		NUMERIC(22,10),
		PlanState		INT,
		LocationId		INT	NULL,
		DisATypeId		VARCHAR(50)	NULL,
		BillNumberId	INT,
		ExpectWork			NUMERIC(18,2) NULL DEFAULT(0),
		FinishWork			NUMERIC(18,2) NULL DEFAULT(0),
		WorkUnit			VARCHAR(50) NULL DEFAULT ''
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='MonthOrder'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan ADD MonthOrder INT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='PlanType'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan ADD PlanType INT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='AssetCardId'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan ADD AssetCardId INT
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='FPeroid'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan DROP COLUMN FPeroid
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='FPeriod'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan ADD FPeriod INT
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='DepAmount'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan DROP COLUMN DepAmount
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='Depreciation'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan ADD Depreciation NUMERIC(22,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='BillNumberId'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan ADD BillNumberId INT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='LocationId'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan ADD LocationId INT NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='DisATypeId'
)
BEGIN
	ALTER TABLE Ac_DepreciationPlan ADD DisATypeId VARCHAR(50) NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='ExpectWork'
)
BEGIN
	ALTER TABLE dbo.Ac_DepreciationPlan ADD ExpectWork NUMERIC(18,2) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='FinishWork'
)
BEGIN
	ALTER TABLE dbo.Ac_DepreciationPlan ADD FinishWork NUMERIC(18,2) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='WorkUnit'
)
BEGIN
	ALTER TABLE dbo.Ac_DepreciationPlan ADD WorkUnit VARCHAR(50) NULL DEFAULT ''
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='Depreciation' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationPlan 
	ALTER COLUMN Depreciation NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='DepTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationPlan 
	ALTER COLUMN DepTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationPlan 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='DevalueReady' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationPlan 
	ALTER COLUMN DevalueReady NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='NetValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationPlan 
	ALTER COLUMN NetValue NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='NetSalvage' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationPlan 
	ALTER COLUMN NetSalvage NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='ExpectWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationPlan 
	ALTER COLUMN ExpectWork NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_DepreciationPlan' AND a.Name='FinishWork' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_DepreciationPlan 
	ALTER COLUMN FinishWork NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Expenses')
            and   type = 'U')
BEGIN
	create table Ac_Expenses (
	   nid                  int                  identity(1,1),
	   STypeId              varchar(50)          null,
	   UserCode             varchar(200)         null,
	   FullName             varchar(400)         null,
	   Comment              varchar(500)         null,
	   Deleted              int                  null default 0
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Expenses' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_Expenses 
		ADD STypeId VARCHAR(50) NULL DEFAULT('')
END
GO

------------------------------------------修改数据------------------------------------------
UPDATE Ac_Expenses SET STypeId = '' WHERE STypeId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_FixedAssets')
            and   type = 'U')
BEGIN
	create table Ac_FixedAssets (
	   nId					int					 not null identity(1,1),
	   STypeId				varchar(50)			 not null default(''),
	   TypeId               varchar(50)          not null,
	   ParId                varchar(50)          not null,
	   Leveal               int                  not null,
	   SonNum               int                  not null,
	   SonCount             int                  not null,
	   UserCode             varchar(200)         not null,
	   FullName             varchar(200)         not null,
	   Name                 varchar(200)         null,
	   Comment              varchar(400)         null,
	   PyCode               varchar(200)         null,
	   Deleted              int                  not null default 0,
	   ATypeId				varchar(50)			 not null default(''),
	   DepATypeId			varchar(50)			 not null default(''),
	   DisATypeId			varchar(50)			 not null default(''),
	   XiWaMaxNumber        int                  null default 1
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_FixedAssets' AND a.Name='nId'
)
BEGIN
	ALTER TABLE Ac_FixedAssets 
		ADD nId INT NOT NULL Identity(1,1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_FixedAssets' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_FixedAssets 
		ADD STypeId VARCHAR(50) NOT NULL DEFAULT(''),
			DepATypeId VARCHAR(50) NOT NULL DEFAULT(''),
			DisATypeId VARCHAR(50) NOT NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_FixedAssets' AND a.Name='ATypeId'
)
BEGIN
	ALTER TABLE Ac_FixedAssets 
		ADD ATypeId VARCHAR(50) NOT NULL DEFAULT('')
END
GO
------------------------------------------------------修改数据--------------------------------------------------------
UPDATE Ac_FixedAssets SET STypeId = '' WHERE STypeId IS NULL
GO
UPDATE Ac_FixedAssets SET DepATypeId = '' WHERE DepATypeId IS NULL
GO
UPDATE Ac_FixedAssets SET DisATypeId = '' WHERE DisATypeId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_FixedAssetsInit_Stype') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_FixedAssetsInit_Stype
	(
		Id			INT IDENTITY(1,1),
		StypeId		VARCHAR(50),
		FYear		INT,
		FPeriod		INT,
		EtypeId		VARCHAR(50),
		InitDate	DATETIME
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_FixedAssetsInit_Stype' AND a.Name='InitDate'
)
BEGIN
	ALTER TABLE Ac_FixedAssetsInit_Stype ADD InitDate DATETIME
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_GoodsBill_VoucherBill')
            and   type = 'U')   
BEGIN
	create table Ac_GoodsBill_VoucherBill (
	   Agvbid               int                  identity(1,1),
	   GoodsBillId          numeric(18,0)        null default(0),
	   VourchBillId         numeric(18,0)        null default(0),
	   AtId                 int                  null default(0),
	   InOutType			INT					 null,  -- -1出库  1入库  往来核销单 核销类型:0：应收冲应付1：预收冲预付2：应收转应收3：应付转应付4：预收转应付5：预付转应收
	   IsCost				INT					 NOT NULL DEFAULT(2)--0：基础凭证。1：成本凭证（结转成本生成）。2：完成凭证
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_GoodsBill_VoucherBill' AND a.Name='InOutType'
)
BEGIN
	ALTER TABLE Ac_GoodsBill_VoucherBill 
		ADD InOutType INT NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_GoodsBill_VoucherBill' AND a.Name='IsCost'
)
BEGIN
	ALTER TABLE Ac_GoodsBill_VoucherBill 
		ADD IsCost INT NOT NULL DEFAULT(2)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_GOODSBILL_VOUCHERBILL') AND name = 'CIX_AC_GOODSBILL_VOUCHERBILL_Agvbid')
--DROP INDEX CIX_AC_GOODSBILL_VOUCHERBILL_Agvbid ON AC_GOODSBILL_VOUCHERBILL 
CREATE CLUSTERED INDEX CIX_AC_GOODSBILL_VOUCHERBILL_Agvbid ON AC_GOODSBILL_VOUCHERBILL(Agvbid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_GOODSBILL_VOUCHERBILL') AND name = 'NCIX_AC_GOODSBILL_VOUCHERBILL_GoodsBillid')
--DROP INDEX NCIX_AC_GOODSBILL_VOUCHERBILL_GoodsBillid ON AC_GOODSBILL_VOUCHERBILL 
CREATE NONCLUSTERED INDEX NCIX_AC_GOODSBILL_VOUCHERBILL_GoodsBillid ON AC_GOODSBILL_VOUCHERBILL(GoodsBillid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_GOODSBILL_VOUCHERBILL') AND name = 'NCIX_AC_GOODSBILL_VOUCHERBILL_VourchBillId')
--DROP INDEX NCIX_AC_GOODSBILL_VOUCHERBILL_VourchBillId ON AC_GOODSBILL_VOUCHERBILL 
CREATE NONCLUSTERED INDEX NCIX_AC_GOODSBILL_VOUCHERBILL_VourchBillId ON AC_GOODSBILL_VOUCHERBILL(VourchBillId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_GOODSBILL_VOUCHERBILL') AND name = 'NCIX_AC_GOODSBILL_VOUCHERBILL_ISCOST')
--DROP INDEX NCIX_AC_GOODSBILL_VOUCHERBILL_ISCOST ON AC_GOODSBILL_VOUCHERBILL 
CREATE NONCLUSTERED INDEX NCIX_AC_GOODSBILL_VOUCHERBILL_ISCOST ON AC_GOODSBILL_VOUCHERBILL(ISCOST,GoodsBillId) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_IniAccount')
            and   type = 'U')
BEGIN
	create table Ac_IniAccount (
	   STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   iniYTotal            numeric(18,2)        null default '0',  --年初本币
	   iniYTotalFor         numeric(18,2)        null default '0',	--年初原币
	   FDebit               numeric(18,2)        null default '0',  --本币借方
	   FDebitFor            numeric(18,2)        null default '0',	--原币借方
	   FCredit              numeric(18,2)        null default '0',	--本币贷方
	   FCreditFor           numeric(18,2)        null default '0',	--原币贷方
	   iniTotal             numeric(18,2)        null default '0',	--本币期初
	   iniTotalFor          numeric(18,2)        null default '0',	--原币期初
	   Cid                  int                  null,
	   IniYqty				numeric(24,10)		 NOT NULL DEFAULT(0),
	   FDebitqty			numeric(24,10)		 NOT NULL DEFAULT(0),
	   FCreditqty			numeric(24,10)		 NOT NULL DEFAULT(0),
	   iniqty				numeric(24,10)		 NOT NULL DEFAULT(0)
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE Ac_IniAccount 
		ADD FYear VARCHAR(10) NULL DEFAULT(''),
			FPeriod INT NULL DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYTotal'
)
BEGIN
	ALTER TABLE Ac_IniAccount 
		ADD FYTotal NUMERIC(18,2) NULL DEFAULT(0),
			FYTotalFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYTotalDebit'
)
BEGIN
	ALTER TABLE Ac_IniAccount 
		ADD FYTotalDebit NUMERIC(18,2) NULL DEFAULT(0),
			FYTotalDebitFor NUMERIC(18,2) NULL DEFAULT(0),
			FYTotalCredit NUMERIC(18,2) NULL DEFAULT(0),
			FYTotalCreditFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='IniYqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount 
		ADD IniYqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FDebitqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount 
		ADD FDebitqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FCreditqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount 
		ADD FCreditqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='iniqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount 
		ADD iniqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT') AND name = 'CIX_AC_INIACCOUNT_FYear_FPeriod')
--DROP INDEX CIX_AC_INIACCOUNT_FYear_FPeriod ON AC_INIACCOUNT 
CREATE CLUSTERED INDEX CIX_AC_INIACCOUNT_FYear_FPeriod ON AC_INIACCOUNT(FYear,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT') AND name = 'NCIX_AC_INIACCOUNT_Atypeid')
--DROP INDEX NCIX_AC_INIACCOUNT_Atypeid ON AC_INIACCOUNT 
CREATE NONCLUSTERED INDEX NCIX_AC_INIACCOUNT_Atypeid ON AC_INIACCOUNT(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT') AND name = 'NCIX_AC_INIACCOUNT_Stypeid_Cid')
--DROP INDEX NCIX_AC_INIACCOUNT_Stypeid_Cid ON AC_INIACCOUNT 
CREATE NONCLUSTERED INDEX NCIX_AC_INIACCOUNT_Stypeid_Cid ON AC_INIACCOUNT(Stypeid,Cid) 
------------------------------------------创建索引区域结束-----------------------------------------------
GO
UPDATE Ac_IniAccount SET FYTotalDebit = 0 WHERE FYTotalDebit IS NULL
GO
UPDATE Ac_IniAccount SET FYTotalDebitFor = 0 WHERE FYTotalDebitFor IS NULL
GO
UPDATE Ac_IniAccount SET FYTotalCredit = 0 WHERE FYTotalCredit IS NULL
GO
UPDATE Ac_IniAccount SET FYTotalCreditFor = 0 WHERE FYTotalCreditFor IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='iniYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN iniYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='iniYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN iniYTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FCreditFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='iniTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN iniTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='iniTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN iniTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FYTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYTotalDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FYTotalDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYTotalDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FYTotalDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYTotalCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FYTotalCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount' AND a.Name='FYTotalCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount 
	ALTER COLUMN FYTotalCreditFor NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_IniAccount_Assist_CheckItems')
            and   type = 'U')
BEGIN
	create table Ac_IniAccount_Assist_CheckItems (
		STypeId              varchar(50)          not null,
		ATypeId              varchar(50)          not null,
		Cid                  int                  null default -1,	   
		IniYTotal            numeric(24,10)        null default 0,
		IniYTotalFor         numeric(24,10)        null default 0,
		FDebit               numeric(24,10)        null default 0,
		FDebitFor            numeric(24,10)        null default 0,
		FCredit              numeric(24,10)        null default 0,
		FCreditFor           numeric(24,10)        null default 0,
		IniTotal             numeric(24,10)        null default 0,
		IniTotalFor          numeric(24,10)        null default 0,
		IniYqty				numeric(24,10)		 NOT NULL DEFAULT(0),
		FDebitqty			numeric(24,10)		 NOT NULL DEFAULT(0),
		FCreditqty          numeric(24,10)		 NOT NULL DEFAULT(0),
		Iniqty				numeric(24,10)		 NOT NULL DEFAULT(0)
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='IniYTotalFor'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		ADD 			
			IniYTotalFor NUMERIC(18,2) NOT NULL DEFAULT(0),
			DebitFor NUMERIC(18,2) NOT NULL DEFAULT(0),
			CreditFor NUMERIC(18,2) NOT NULL DEFAULT(0),
			IniTotalFor NUMERIC(18,2) NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FDebit'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		ADD FDebit NUMERIC(18,2) NULL DEFAULT(0),
			FDebitFor NUMERIC(18,2) NULL DEFAULT(0),
			FCredit NUMERIC(18,2) NULL DEFAULT(0),
			FCreditFor VARCHAR(50) NULL DEFAULT(0)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='Debit'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		DROP COLUMN Debit,DebitFor,Credit,CreditFor
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='AscidsNid'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		DROP COLUMN AscidsNid
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='Ascids'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		DROP COLUMN Ascids
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FieldValue'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		DROP COLUMN FieldValue
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='GroupId'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		DROP COLUMN GroupId
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		ADD FYear VARCHAR(10) NULL DEFAULT(''),
			FPeriod INT NULL DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FYTotal'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		ADD FYTotal NUMERIC(18,2) NULL DEFAULT(0),
			FYTotalFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='IniYqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		ADD IniYqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FDebitqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		ADD FDebitqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FCreditqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		ADD FCreditqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='Iniqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
		ADD Iniqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT_ASSIST_CHECKITEMS') AND name = 'CIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_FYear_FPeriod')
--DROP INDEX CIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_FYear_FPeriod ON AC_INIACCOUNT_ASSIST_CHECKITEMS 
CREATE CLUSTERED INDEX CIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_FYear_FPeriod ON AC_INIACCOUNT_ASSIST_CHECKITEMS(FYear,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_Stypeid_Cid')
--DROP INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_Stypeid_Cid ON AC_INIACCOUNT_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_Stypeid_Cid ON AC_INIACCOUNT_ASSIST_CHECKITEMS(Stypeid,Cid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_Atypeid')
--DROP INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_Atypeid ON AC_INIACCOUNT_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_Atypeid ON AC_INIACCOUNT_ASSIST_CHECKITEMS(Atypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
-------------------------------------------修改数据-------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='IniYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN IniYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='IniYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN IniYTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN FDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN FCreditFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='IniTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN IniTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='IniTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN IniTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='DebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN DebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='CreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN CreditFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN FYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN FYTotalFor NUMERIC(24,10)
    END
    
 IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='Iniqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN Iniqty NUMERIC(24,10)
    END                  
    
    IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FCreditqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN FCreditqty NUMERIC(24,10)
    END
    
    IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='FDebitqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN FDebitqty NUMERIC(24,10)
    END
    
    IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems' AND a.Name='IniYqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems 
	ALTER COLUMN IniYqty NUMERIC(24,10)
    END               
                   


                     
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_IniAccount_Assist_CheckItems_Detail')
            and   type = 'U')
BEGIN
	create table Ac_IniAccount_Assist_CheckItems_Detail (
	   STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   Cid                  int                  null default -1,
	   Ascids               int                  null default -1,
	   FieldValue           varchar(50)          null,	   
	   IniYTotal			numeric(18,2)		 null default 0,
	   IniYTotalFor			numeric(18,2)		 null default 0,	   
	   FDebit				numeric(18,2)		 null default 0,	   
	   FDebitFor			numeric(18,2)		 null default 0,
	   FCredit				numeric(18,2)		 null default 0,
	   FCreditFor			numeric(18,2)		 null default 0,
	   IniTotal				numeric(18,2)		 null default 0,
	   IniTotalFor			numeric(18,2)		 null default 0,	   	   
	   GroupId              int                  null,
	   IniYqty				numeric(24,10)		 NOT NULL DEFAULT(0),
	   FDebitqty			numeric(24,10)		 NOT NULL DEFAULT(0),
	   FCreditqty			numeric(24,10)		 NOT NULL DEFAULT(0),
	   iniqty				numeric(24,10)		 NOT NULL DEFAULT(0)
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='IniYTotal'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
		ADD IniYTotal NUMERIC(18,2) NULL DEFAULT(0),
			IniYTotalFor NUMERIC(18,2) NULL DEFAULT(0),
			FDebit NUMERIC(18,2) NULL DEFAULT(0),
			FDebitFor NUMERIC(18,2) NULL DEFAULT(0),
			FCredit NUMERIC(18,2) NULL DEFAULT(0),
			FCreditFor NUMERIC(18,2) NULL DEFAULT(0),
			IniTotal NUMERIC(18,2) NULL DEFAULT(0),
			IniTotalFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
		ADD FYear VARCHAR(10) NULL DEFAULT(''),
			FPeriod INT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FYTotal'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
		ADD FYTotal NUMERIC(18,2) NULL DEFAULT(0),
			FYTotalFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='IniYqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
		ADD IniYqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FDebitqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
		ADD FDebitqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FCreditqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
		ADD FCreditqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='iniqty'
)
BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
		ADD iniqty numeric(24,10) NOT NULL DEFAULT(0)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL') AND name = 'CIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_FYear_FPeriod')
--DROP INDEX CIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_FYear_FPeriod ON AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL 
CREATE CLUSTERED INDEX CIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_FYear_FPeriod ON AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL(FYear,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL') AND name = 'NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Atypeid')
--DROP INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Atypeid ON AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Atypeid ON AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL') AND name = 'NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Stypeid_Cid')
--DROP INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Stypeid_Cid ON AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Stypeid_Cid ON AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL(Stypeid,Cid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL') AND name = 'NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Ascids')
--DROP INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Ascids ON AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL_Ascids ON AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL(Ascids) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='IniYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN IniYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='IniYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN IniYTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN FDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN FCreditFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='IniTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN IniTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='IniTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN IniTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN FYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_IniAccount_Assist_CheckItems_Detail' AND a.Name='FYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_IniAccount_Assist_CheckItems_Detail 
	ALTER COLUMN FYTotalFor NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




--EXEC Gp_ImportAtypeToItemtype
if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Items')
            and   type = 'U')
BEGIN
	create table Ac_Items (
	   nId                  int                  identity(1,1),
	   nTypeId				VARCHAR(50)			 NULL,
	   nParId				VARCHAR(50)			 NULL,
	   TypeId               varchar(50)          null,
	   ParId                varchar(50)          null,
	   Leveal               int                  null,
	   SonNum               int                  null,
	   SonCount             int                  null,
	   UserCode             varchar(200)         not null,
	   FullName             varchar(200)         not null,
	   Name                 varchar(200)         null,
	   CreateBank           varchar(400)         null,
	   BankType             varchar(400)         null,
	   IsBank               int                  null,
	   Comment              varchar(400)         null,
	   PyCode               varchar(200)         null,
	   Deleted              int                  not null default 0,
	   TypeName             varchar(2)           null,
	   XiWaMaxNumber        int                  null default 1,
	   Sysrow               int                  null default 0
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Items' AND a.Name='BankType'
)
BEGIN
	ALTER TABLE Ac_Items 
		ADD BankType VARCHAR(400) NULL DEFAULT('')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Items' AND a.Name='Sysrow'
)
BEGIN
	ALTER TABLE Ac_Items 
		ADD Sysrow INT NULL DEFAULT(0)
END

GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Items' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_Items 
		DROP COLUMN STypeId,ATypeId,DepATypeId,DisATypeId
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Items' AND a.Name='IsModify'
)
BEGIN
	ALTER TABLE Ac_Items 
		ADD IsModify INT NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Items' AND a.Name='nTypeId'
)
BEGIN
	ALTER TABLE Ac_Items 
		ADD nTypeId VARCHAR(50) NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Items' AND a.Name='nParId'
)
BEGIN
	ALTER TABLE Ac_Items 
		ADD nParId VARCHAR(50) NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Items' AND a.Name='WdSyncFlag'
)
BEGIN
	ALTER TABLE Ac_Items 
		ADD WdSyncFlag BIT NOT NULL DEFAULT 0
END
GO
--是否同步
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('Ac_Items') and name='IsWmsSync')
BEGIN
	ALTER TABLE Ac_Items 
		ADD IsWmsSync INT NOT NULL DEFAULT 0 
End 
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ITEMS') AND name = 'CIX_AC_ITEMS_Nid')
--DROP INDEX CIX_AC_ITEMS_Nid ON AC_ITEMS 
CREATE CLUSTERED INDEX CIX_AC_ITEMS_Nid ON AC_ITEMS(Nid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ITEMS') AND name = 'NCIX_AC_ITEMS_Typeid')
--DROP INDEX NCIX_AC_ITEMS_Typeid ON AC_ITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_ITEMS_Typeid ON AC_ITEMS(Typeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ITEMS') AND name = 'NCIX_AC_ITEMS_Usercode')
--DROP INDEX NCIX_AC_ITEMS_Usercode ON AC_ITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_ITEMS_Usercode ON AC_ITEMS(Usercode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ITEMS') AND name = 'NCIX_AC_ITEMS_TypeName_SonNum')
--DROP INDEX NCIX_AC_ITEMS_TypeName_SonNum ON AC_ITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_ITEMS_TypeName_SonNum ON AC_ITEMS(TypeName,SonNum) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------
UPDATE Ac_Items SET BankType = '' WHERE BankType IS NULL
GO
UPDATE Ac_Items SET IsModify = 0 WHERE IsModify IS NULL
GO
------------------------------------------预制数据-------------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items)
BEGIN
	SET IDENTITY_INSERT dbo.Ac_Items ON
	--现金
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(1,'','',1,0,0,'1001','默认现金',1,0,'B','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(2,'','',1,0,0,'5288','银行存款-中国银行',1,1,'B','','',1,'','')
	--收入
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(3,'','',1,0,0,'0321','商品报溢收入',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(4,'','',1,0,0,'0322','商品获赠收入',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(5,'','',1,0,0,'0323','成本调价收入',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(6,'','',1,0,0,'0324','采购退货差价',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(7,'','',1,0,0,'0325','变价调拨差价',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(8,'','',1,0,0,'0326','商品拆装差价',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(9,'','',1,0,0,'0328','商品维修收入',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(10,'','',1,0,0,'0329','受托退货差价',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(11,'','',1,0,0,'5101','销售收入',1,0,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(12,'','',1,0,0,'5103','返点获利收入',1,0,'G','','',0,'','')
	--以上项目单据上默认不出,业务凭证,其他出入库的业务类别除外
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(13,'','',1,0,0,'0332','利息收入',1,1,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(14,'','',1,0,0,'0333','其他收入',1,1,'G','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(15,'','',1,0,0,'03333','调账收入',1,0,'G','','',0,'','')
	
	--支出,费用
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(16,'','',1,0,0,'0404','销售折扣返利支出',1,0,'E','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(17,'','',1,0,0,'0421','商品报损',1,0,'E','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(18,'','',1,0,0,'0422','商品赠出',1,0,'E','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(19,'','',1,0,0,'0423','商品维修支出',1,0,'E','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(20,'','',1,0,0,'0424','商品送修支出',1,0,'E','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(21,'','',1,0,0,'5401','销售成本',1,0,'E','','',0,'','')
	--以上项目单据上默认不出,业务凭证，其他出入库的业务类别除外
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(22,'','',1,0,0,'0431','调账亏损',1,0,'E','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(23,'','',1,0,0,'0455','其他支出',1,1,'E','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(24,'','',1,0,0,'0456','优惠/抹零金额',1,0,'E','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(25,'','',1,0,0,'0432','固定资产折旧',1,0,'E','','',0,'','')
	
	--固定资产
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(26,'','',1,0,0,'1501','固定资产',1,1,'F','','',0,'','')
	
	--资产
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(27,'','',1,0,0,'1151','预付资金',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(28,'','',1,0,0,'1132','内部应收',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(29,'','',1,0,0,'1133','其他应收',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(30,'','',1,0,0,'1241','库存商品总值',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(31,'','',1,0,0,'1261','委托代销商品',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(32,'','',1,0,0,'1301','待摊费用',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(33,'','',1,0,0,'987','应收合计',1,0,'C','','',0,'','')
	--负债
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(34,'','',1,0,0,'2181','会员储值',1,0,'L','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(35,'','',1,0,0,'2121','应付合计',1,0,'L','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(36,'','',1,0,0,'2132','其他应付',1,0,'L','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(37,'','',1,0,0,'2141','代销商品',1,0,'L','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(38,'','',1,0,0,'2171','应交税金',1,0,'L','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(39,'','',1,0,0,'2131','预收资金',1,0,'L','','',0,'','')
	
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(40,'','',1,0,0,'SYS-1511','长期股权投资',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(41,'','',1,0,0,'SYC-1601','固定资产卡片原值',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(42,'','',1,0,0,'SYC-1602','固定资产卡片累计折旧',1,0,'C','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(43,'','',1,0,0,'SYS-1604','在建工程',1,0,'C','','',0,'','')

	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(44,'','',1,0,0,'SYS-1001','『全部现金合计』',1,1,'B','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(45,'','',1,0,0,'05','【所有者权益】',1,1,'A','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(46,'','',1,0,0,'3001','实收资本',1,1,'A','','',0,'','')
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(47,'','',1,0,0,'3101','其他资本',1,0,'A','','',0,'','')	
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(48,'','',1,0,0,'3111','资本公积',1,1,'A','','',0,'','')	
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(49,'','',1,0,0,'3121','盈余公积',1,1,'A','','',0,'','')	
	INSERT INTO Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES(50,'','',1,0,0,'3141','未分配利润',1,0,'A','','',0,'','')	
	
	SET IDENTITY_INSERT dbo.Ac_Items OFF
END

GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = 'SYS-1301' AND Sysrow = 1)
BEGIN
	--【资产】 待摊费用合计
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',1,0,0,'SYS-1301','『待摊费用合计』',1,1,'C','','',0,'','')
END


IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '0435' AND Sysrow = 1)
BEGIN
	--【支出类-费用合计】 0435-财务费用
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',3,0,0,'0435','财务费用',1,1,'E','','',0,'','CWFY')
END


IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '043599' AND Sysrow = 1)
BEGIN
	--【支出类-费用合计-财务费用】 043599-汇兑损益
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',4,0,0,'043599','汇兑损益',1,0,'E','','',0,'','HDSY')
END

--在【基础资料-项目管理-支出类-费用合计】下预设【0445-销售费用】项目，并预设下级项目【045599-业务提成】项目；
--在【基础资料-项目管理-负债合计】下预设【2211-应付职工薪酬、221199-员工提成】项目；

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '0445' AND Sysrow = 1)
BEGIN
	--【支出类-费用合计】 0445-销售费用
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',3,0,0,'0445','销售费用',1,1,'E','','',0,'','XSFY')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '044599' AND Sysrow = 1)
BEGIN
	--【支出类-费用合计-财务费用】 044599-业务提成
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',4,0,0,'044599','业务提成',1,1,'E','','',0,'','YWTC')
END

--【支出类-费用合计-销售费用】 044597-市场活动费用
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '044597' AND Sysrow = 1)
BEGIN
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',4,0,0,'044597','市场活动费用',1,1,'E','','',0,'','SCHDFY')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '2211' AND Sysrow = 1)
BEGIN
	--【负债合计】 2211-应付职工薪酬
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',2,0,0,'2211','应付职工薪酬',1,1,'L','','',0,'','YFZGXC')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '221199' AND Sysrow = 1)
BEGIN
	--【负债合计】 221199-员工提成
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',3,0,0,'221199','员工提成',1,0,'L','','',0,'','YGTC')
END

--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '21911' AND Sysrow = 1)
--BEGIN
--	--【负债合计】 21911-代金券
--	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',3,0,0,'21911','『代金券』',1,0,'L','','',0,'','DJQ')
--END

--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '21912' AND Sysrow = 1)
--BEGIN
--	--【负债合计】 21912-折扣券
--	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',3,0,0,'21912','『折扣券』',1,0,'L','','',0,'','ZKQ')
--END

--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '21913' AND Sysrow = 1)
--BEGIN
--	--【负债合计】 21913-兑换券
--	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',3,0,0,'21913','『兑换券』',1,0,'L','','',0,'','DHQ')
--END


--9.6添加

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '1251' AND Sysrow = 1)
BEGIN
	--【资产类】 1251-发出商品
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',2,0,0,'1251','发出商品',1,0,'C','','',0,'','FCSP')
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '2122' AND Sysrow = 1)
BEGIN
	--【负债合计】 2122-应付暂估
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',2,0,0,'2122','应付暂估',1,0,'L','','',0,'','YFZG')
END

--【负债合计】 2191-优惠券
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '2191' AND Sysrow = 1)
BEGIN
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',2,0,0,'2191','『优惠券』',1,0,'L','','',0,'','YHQ')
END

--【5102其它收入】 0334-优惠券收入
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '0334' AND Sysrow = 1)
BEGIN
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',4,0,0,'0334','优惠券收入',1,1,'G','','',0,'','YHQSR')
END
--991添加
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '0335' AND Sysrow = 1)
BEGIN
	--【5102其它收入】 0335-“配送差价”
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',4,0,0,'0335','配送差价',1,0,'G','','',0,'','PSCJ')
END
--运杂费
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode='044598' AND Sysrow=1)
	BEGIN
		INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',4,0,0,'044598','运杂费',1,1,'E','','',0,'','YZF')
	END 

--【支出类-费用合计】 0435-财务费用
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '044596' AND Sysrow = 1)
BEGIN
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',4,0,0,'044596','积分转储值',1,1,'E','','',0,'','JFZCZ')
END

--991添加 
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '1271' AND Sysrow = 1)
BEGIN
	--【资产类】 1271-“周转材料”
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode)VALUES('','',2,0,0,'1271','周转材料',1,0,'C','','',0,'','ZZZL')
END


-------------数据校验，如果有typeid与nid不匹配的数据，修正-------
SELECT *
INTO #Tmp_Check 
FROM dbo.Ac_Items WHERE TypeId IN ('0000200001','0000100005','0000200006','0000100009','0000100010')

DECLARE @nid INT,@typeid VARCHAR(50),@nTypeid VARCHAR(50),@dNid INT
DECLARE checkCur CURSOR READ_ONLY FOR
	SELECT nId,TypeId,nTypeId
	FROM #Tmp_Check
OPEN checkCur
FETCH NEXT FROM checkCur INTO @nid,@typeid,@ntypeid
WHILE @@FETCH_STATUS = 0
BEGIN

	IF @typeid <> @nTypeid
	BEGIN
		UPDATE dbo.Ac_Items 
			SET nTypeId = @nTypeid,
				nParId = LEFT(@nTypeid,LEN(@nTypeid) - 5)
		WHERE nTypeId = @typeid
		
		UPDATE dbo.Ac_Items 
			SET nTypeId = @nTypeid + RIGHT(nTypeId,LEN(nTypeId) - 5*(Leveal-1)),
				nParId = LEFT(@nTypeid,LEN(@nTypeid) - 5)
		WHERE nTypeId LIKE ''''+@typeid+'%''' AND Leveal >=3
		
		UPDATE dbo.Ac_Items SET nTypeId = @typeid WHERE nId = @nid
	END


	FETCH NEXT FROM checkCur INTO @nid,@typeid,@ntypeid
END
CLOSE checkCur
DEALLOCATE checkCur

DROP TABLE #Tmp_Check
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO
 
--WMS下载
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('Ac_Items') and name='IsWmsDownLoad')
BEGIN
	ALTER TABLE Ac_Items 
		ADD IsWmsDownLoad INT NOT NULL DEFAULT 0 
End 
GO
UPDATE Ac_Items SET IsWmsDownLoad = 0 WHERE IsWmsDownLoad IS NULL
GO

--是否同步
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('Ac_Items') and name='IsWmsSync')
BEGIN
	ALTER TABLE Ac_Items 
		ADD IsWmsSync INT NOT NULL DEFAULT 0 
End 
GO
UPDATE Ac_Items SET IsWmsSync = 0 WHERE IsWmsSync IS NULL

--D9关联字段
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('Ac_Items') and name='D9NId')
BEGIN
	ALTER TABLE Ac_Items 
		ADD D9NId INT  DEFAULT -1 
End 
GO
--D9关联字段
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('Ac_Items') and name='D9NId')
BEGIN
	ALTER TABLE Ac_Items 
		ADD D9NId INT DEFAULT -1 
End 
GO
UPDATE Ac_Items SET D9NId = -1 WHERE D9NId IS NULL
GO
UPDATE Ac_Items SET Name = '' WHERE Name IS NULL
GO
UPDATE Ac_Items SET Comment = '' WHERE Comment IS NULL
GO



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Items_Detail')
            and   type = 'U')
BEGIN
	create table Ac_Items_Detail (
	   DId                  int                  identity(1,1),
	   nId                  int                  null,
	   STypeId              varchar(50)          null,
	   ATypeId              varchar(50)          null,
	   DepATypeId           varchar(50)          null,
	   DisATypeId           varchar(50)          null,
	   XiWaMaxNumber        int                  null default 1
	)
END
GO


------------------------------------------预制数据-------------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items_Detail)
BEGIN
	INSERT INTO Ac_Items_Detail
	(
		nId,
		STypeId,
		ATypeId,
		DepATypeId,
		DisATypeId
	)
	SELECT 
		I.nId,
		S.TypeId, 
		'' AS ATypeId,
		'' AS DepATypeId,
		'' AS DisATypeId
	FROM Ac_Items I,SType S
	WHERE 
		S.TypeId<>'00000' 
		AND S.sonnum=0
	ORDER BY nId
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ITEMS_DETAIL') AND name = 'CIX_AC_ITEMS_DETAIL_Did')
--DROP INDEX CIX_AC_ITEMS_DETAIL_Did ON AC_ITEMS_DETAIL 
CREATE CLUSTERED INDEX CIX_AC_ITEMS_DETAIL_Did ON AC_ITEMS_DETAIL(Did) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ITEMS_DETAIL') AND name = 'NCIX_AC_ITEMS_DETAIL_Nid')
--DROP INDEX NCIX_AC_ITEMS_DETAIL_Nid ON AC_ITEMS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_ITEMS_DETAIL_Nid ON AC_ITEMS_DETAIL(Nid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_ITEMS_DETAIL') AND name = 'NCIX_AC_ITEMS_DETAIL_Stypeid_Atypeid')
--DROP INDEX NCIX_AC_ITEMS_DETAIL_Stypeid_Atypeid ON AC_ITEMS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_ITEMS_DETAIL_Stypeid_Atypeid ON AC_ITEMS_DETAIL(Stypeid,Atypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_MulColumnAccount')
            and   type = 'U')   
BEGIN
	CREATE TABLE Ac_MulColumnAccount               ---多账栏表
	(
		
		STypeid			VARCHAR(50),			---分支机构名称
		ATypeid			VARCHAR(50),			---科目名称
		AccountName		VARCHAR(200),			---账栏名称
		Ascid			INT,					---辅助核算项
		flevel			INT,					---项目级别
		AssistID		INT IDENTITY(1,1),		---自增长id，同时作为副表的外键
		Cids			VARCHAR(100),			---币别选择，多选以，隔开
		Flag			INT,					---标记该方案选择的是明细科目，还是非明细科目
	 -- Creator			VARCHAR(50),			---创建者
	 -- CreatorStypeId  VARCHAR(50),			---创建者所属机构
	 -- IsPublic	    BIT,					---是否可见,1为自己可见，0为所有可见
	 -- Comment			NVARCHAR(500)			---备注
	)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_MulColumnAccount' AND a.Name='Creator'
)
BEGIN
	ALTER TABLE Ac_MulColumnAccount ADD Creator	VARCHAR(50) DEFAULT ('') NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_MulColumnAccount' AND a.Name='CreatorStypeId'
)
BEGIN
	ALTER TABLE Ac_MulColumnAccount ADD CreatorStypeId VARCHAR(50) DEFAULT('') NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_MulColumnAccount' AND a.Name='IsPublic'
)
BEGIN
	ALTER TABLE Ac_MulColumnAccount ADD IsPublic BIT 
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_MulColumnAccount' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE Ac_MulColumnAccount ADD Comment NVARCHAR(500) DEFAULT('') NULL 
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_MULCOLUMNACCOUNT') AND name = 'CIX_AC_MULCOLUMNACCOUNT_Assistid')
--DROP INDEX CIX_AC_MULCOLUMNACCOUNT_Assistid ON AC_MULCOLUMNACCOUNT 
CREATE CLUSTERED INDEX CIX_AC_MULCOLUMNACCOUNT_Assistid ON AC_MULCOLUMNACCOUNT(Assistid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_MULCOLUMNACCOUNT') AND name = 'NCIX_AC_MULCOLUMNACCOUNT_Ascid')
--DROP INDEX NCIX_AC_MULCOLUMNACCOUNT_Ascid ON AC_MULCOLUMNACCOUNT 
CREATE NONCLUSTERED INDEX NCIX_AC_MULCOLUMNACCOUNT_Ascid ON AC_MULCOLUMNACCOUNT(Ascid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_MulColumnAccount_Assist')
            and   type = 'U')   
BEGIN
	CREATE TABLE Ac_MulColumnAccount_Assist
	(
		ID			INT IDENTITY(1,1), ---自增长id
		AssistID	INT,			   ---主表的对应键
		Fdc			INT,			   ---分析方向 借1，贷-1，双向0
		FValue		VARCHAR(50)		   ---明细科目或辅助核算项的typeid
	)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_MULCOLUMNACCOUNT_ASSIST') AND name = 'CIX_AC_MULCOLUMNACCOUNT_ASSIST_Assistid')
--DROP INDEX CIX_AC_MULCOLUMNACCOUNT_ASSIST_Assistid ON AC_MULCOLUMNACCOUNT_ASSIST 
CREATE CLUSTERED INDEX CIX_AC_MULCOLUMNACCOUNT_ASSIST_Assistid ON AC_MULCOLUMNACCOUNT_ASSIST(Assistid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_OtherGains')
            and   type = 'U')   
BEGIN
	create table Ac_OtherGains (
	   nid                  int                  identity(1,1),
	   STypeId				varchar(50)			 null default(''),
	   UserCode             varchar(200)         null,
	   FullName             varchar(400)         null,
	   Comment              varchar(500)         null,
	   Deleted              int                  null default 0
	)
END	
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_OtherGains' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_OtherGains 
		ADD STypeId VARCHAR(50) NULL DEFAULT('')
END
GO

------------------------------------------修改数据------------------------------------------
UPDATE Ac_OtherGains SET STypeId = '' WHERE STypeId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Period')
            and   type = 'U')
BEGIN
	create table Ac_Period (
	   PeriodId             int                  identity(1,1),
	   FYear                varchar(10)          not null,
	   FMonth               varchar(10)          not null,
	   IsNature             int                  null,
	   NatureCount          int                  null,
	   FPeriod              int                  null,
	   FBegin               datetime             null,
	   FEnd                 datetime             null,
	   Deleted              int                  NULL,
	   IsCurrent			INT					 NOT NULL  DEFAULT(1)
	)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Period' AND a.Name='IsDynamic'
)
BEGIN
	ALTER TABLE Ac_Period 
		ADD IsDynamic INT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Period' AND a.Name='IsCurrent'
)
BEGIN
	ALTER TABLE Ac_Period 
		ADD IsCurrent INT NOT NULL DEFAULT(1)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_PERIOD') AND name = 'CIX_AC_PERIOD_FPeriod')
--DROP INDEX CIX_AC_PERIOD_FPeriod ON AC_PERIOD 
CREATE CLUSTERED INDEX CIX_AC_PERIOD_FPeriod ON AC_PERIOD(FPeriod) 

------------------------------------------创建索引区域结束-----------------------------------------------
---------------------------------------------修改数据---------------------------------------------
UPDATE Ac_Period SET IsDynamic = 0 WHERE IsDynamic IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_ProfitAndLoss')
            and   type = 'U')
BEGIN
	create table Ac_ProfitAndLoss (
	   STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   Cid                  int                  null,
	   FFTotal              numeric(18,2)        null default 0,
	   FFTotalFor           numeric(18,2)        null default 0,
	   FYTotal              numeric(18,2)        null default 0,
	   FYTotalFor           numeric(18,2)        null default 0,
	   FYear                varchar(10)          null,
	   FPeriod              varchar(10)          null
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_PROFITANDLOSS') AND name = 'CIX_AC_PROFITANDLOSS_FYear_FPeriod')
--DROP INDEX CIX_AC_PROFITANDLOSS_FYear_FPeriod ON AC_PROFITANDLOSS 
CREATE CLUSTERED INDEX CIX_AC_PROFITANDLOSS_FYear_FPeriod ON AC_PROFITANDLOSS(FYear ,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_PROFITANDLOSS') AND name = 'NCIX_AC_PROFITANDLOSS_Stypeid_Atypeid')
--DROP INDEX NCIX_AC_PROFITANDLOSS_Stypeid_Atypeid ON AC_PROFITANDLOSS 
CREATE NONCLUSTERED INDEX NCIX_AC_PROFITANDLOSS_Stypeid_Atypeid ON AC_PROFITANDLOSS(Stypeid ,Atypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProfitAndLoss' AND a.Name='FFTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProfitAndLoss 
	ALTER COLUMN FFTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProfitAndLoss' AND a.Name='FFTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProfitAndLoss 
	ALTER COLUMN FFTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProfitAndLoss' AND a.Name='FYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProfitAndLoss 
	ALTER COLUMN FYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProfitAndLoss' AND a.Name='FYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProfitAndLoss 
	ALTER COLUMN FYTotalFor NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_ProfitAndLoss_Detail')
            and   type = 'U')
BEGIN
	create table Ac_ProfitAndLoss_Detail (
	   STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   Cid                  int                  null default -1,
	   Ascids               int                  null default -1,
	   FieldValue           varchar(50)          null,
	   FFTotal              numeric(18,2)        null default 0,
	   FFTotalFor           numeric(18,2)        null default 0,
	   FYTotal              numeric(18,2)        null default 0,
	   FYTotalFor           numeric(18,2)        null default 0,
	   FYear                varchar(10)          null,
	   FPeriod              int                  null
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_PROFITANDLOSS_DETAIL') AND name = 'CIX_AC_PROFITANDLOSS_DETAIL_FYear_FPeriod')
--DROP INDEX CIX_AC_PROFITANDLOSS_DETAIL_FYear_FPeriod ON AC_PROFITANDLOSS_DETAIL 
CREATE CLUSTERED INDEX CIX_AC_PROFITANDLOSS_DETAIL_FYear_FPeriod ON AC_PROFITANDLOSS_DETAIL(FYear ,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_PROFITANDLOSS_DETAIL') AND name = 'NCIX_AC_PROFITANDLOSS_DETAIL_Stypeid_Atypeid')
--DROP INDEX NCIX_AC_PROFITANDLOSS_DETAIL_Stypeid_Atypeid ON AC_PROFITANDLOSS_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_PROFITANDLOSS_DETAIL_Stypeid_Atypeid ON AC_PROFITANDLOSS_DETAIL(Stypeid ,Atypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProfitAndLoss_Detail' AND a.Name='FFTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProfitAndLoss_Detail 
	ALTER COLUMN FFTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProfitAndLoss_Detail' AND a.Name='FFTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProfitAndLoss_Detail 
	ALTER COLUMN FFTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProfitAndLoss_Detail' AND a.Name='FYTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProfitAndLoss_Detail 
	ALTER COLUMN FYTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProfitAndLoss_Detail' AND a.Name='FYTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProfitAndLoss_Detail 
	ALTER COLUMN FYTotalFor NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_Provision_Voucher') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_Provision_Voucher
	(
		Id	INT IDENTITY(1,1),
		SourceId	INT,
		SourceType	INT,
		VoucherId	INT
	)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_ProvisionForImpairment') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_ProvisionForImpairment
	(
		Id					INT IDENTITY(1,1),
		CardId				INT,
		DevalueReady		NUMERIC(22,10),
		UsedDevalueReady	NUMERIC(22,10),
		AfterNetValue		NUMERIC(22,10),
		BusinessDate		DATETIME,
		OperationDate		DATETIME,
		ETypeId				VARCHAR(50),
		FYear				INT,
		FPeriod				INT,
		IfRecalculate		INT NOT NULL DEFAULT(0),
		BillnumberId		INT
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProvisionForImpairment' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE Ac_ProvisionForImpairment ADD FYear INT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProvisionForImpairment' AND a.Name='FPeriod'
)
BEGIN
	ALTER TABLE Ac_ProvisionForImpairment ADD FPeriod INT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProvisionForImpairment' AND a.Name='IfRecalculate'
)
BEGIN
	ALTER TABLE Ac_ProvisionForImpairment ADD IfRecalculate INT DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProvisionForImpairment' AND a.Name='BusinessDate'
)
BEGIN
	ALTER TABLE Ac_ProvisionForImpairment ADD BusinessDate DATETIME
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProvisionForImpairment' AND a.Name='BillnumberId'
)
BEGIN
	ALTER TABLE Ac_ProvisionForImpairment ADD BillnumberId INT
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProvisionForImpairment' AND a.Name='DevalueReady' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProvisionForImpairment 
	ALTER COLUMN DevalueReady NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProvisionForImpairment' AND a.Name='UsedDevalueReady' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProvisionForImpairment 
	ALTER COLUMN UsedDevalueReady NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ProvisionForImpairment' AND a.Name='AfterNetValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_ProvisionForImpairment 
	ALTER COLUMN AfterNetValue NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_RateAdjust')
            and   type = 'U')
BEGIN
	create table Ac_RateAdjust (
	   ATypeId              varchar(50)          null,
	   Cid                  int                  null,
	   AscIds               int                  null,
	   FDifference          numeric(18,2)        null,
	   FEndBalance          numeric(18,2)        null,
	   FEndBalanceFor       numeric(18,2)        null,
	   Rate                 numeric(18,4)        null,
	   FPeriod              int                  null,
	   FYear                varchar(10)          null
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_RATEADJUST') AND name = 'CIX_AC_RATEADJUST_FYear_FPeriod')
--DROP INDEX CIX_AC_RATEADJUST_FYear_FPeriod ON AC_RATEADJUST 
CREATE CLUSTERED INDEX CIX_AC_RATEADJUST_FYear_FPeriod ON AC_RATEADJUST(FYear ,FPeriod) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_RateAdjust' AND a.Name='FDifference' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_RateAdjust 
	ALTER COLUMN FDifference NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_RateAdjust' AND a.Name='FEndBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_RateAdjust 
	ALTER COLUMN FEndBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_RateAdjust' AND a.Name='FEndBalanceFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_RateAdjust 
	ALTER COLUMN FEndBalanceFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_RateAdjust' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_RateAdjust 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS ( SELECT  1
                FROM    sysobjects
                WHERE   id = OBJECT_ID('Ac_ReceiptBill_VoucherBill')
                        AND type = 'U' ) 
BEGIN
    CREATE TABLE Ac_ReceiptBill_VoucherBill
    (
          Agvbid INT IDENTITY(1, 1) ,
          GoodsBillId NUMERIC(18, 0) NULL DEFAULT ( 0 ) ,
          VourchBillId NUMERIC(18, 0) NULL DEFAULT ( 0 ),
		  IsCost	INT	NOT NULL DEFAULT(2)--0：基础凭证。1：成本凭证（结转成本生成）。2：完成凭证
     )
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_ReceiptBill_VoucherBill' AND a.Name='IsCost'
)
BEGIN
	ALTER TABLE Ac_ReceiptBill_VoucherBill 
		ADD IsCost INT NOT NULL DEFAULT(2)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_SubsidiaryEquipment') AND  type = 'U')
BEGIN
	CREATE TABLE Ac_SubsidiaryEquipment
	(
		Id			INT IDENTITY(1,1),
		CardId		INT,
		FullName	VARCHAR(200),
		LocationId	INT,
		Size		VARCHAR(200),
		Qty			INT,
		Units		VARCHAR(200),
		Value		NUMERIC(22,10),
		UseDate		DATETIME,
		Comment		VARCHAR(200)
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_SubsidiaryEquipment' AND a.Name='CardId'
)
BEGIN
	ALTER TABLE Ac_SubsidiaryEquipment ADD CardId INT
END
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_SubsidiaryEquipment' AND a.Name='UnitsId'
)
BEGIN
	ALTER TABLE Ac_SubsidiaryEquipment DROP COLUMN UnitsId
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_SubsidiaryEquipment' AND a.Name='Units'
)
BEGIN
	ALTER TABLE Ac_SubsidiaryEquipment ADD Units VARCHAR(200) DEFAULT ''
END
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_SubsidiaryEquipment' AND a.Name='Value' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_SubsidiaryEquipment 
	ALTER COLUMN Value NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Table')
            and   type = 'U')
BEGIN
	create table Ac_Table (
	   AcId                 int                  identity(1,1),
	   UserCode             varchar(200)         not null,
	   FullName             varchar(200)         not null,
	   Comment              varchar(200)         null,
	   Len1                 int                  null default 0,
	   Len2                 int                  null default 0,
	   Len3                 int                  null default 0,
	   Len4                 int                  null default 0,
	   Len5                 int                  null default 0,
	   Len6                 int                  null default 0,
	   Len7                 int                  null default 0,
	   Len8                 int                  null default 0,
	   Len9                 int                  null default 0,
	   Len10                int                  null default 0,
	   EType                varchar(50)          null,
	   CreateDateTime       datetime             null
	)
END
GO
-----------------------------------------------------修改表-----------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Table' AND a.Name='IsUsed'
)
BEGIN
	ALTER TABLE Ac_Table 
		ADD IsUsed INT NOT NULL DEFAULT(0)
END
GO
--属于哪套模板名称
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Table' AND a.Name='SetFullName'
)
BEGIN
	ALTER TABLE Ac_Table 
		ADD SetFullName VARCHAR(200)
END
GO
--属于哪套模板id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Table' AND a.Name='SetId'
)
BEGIN
	ALTER TABLE Ac_Table 
		ADD SetId INT NULL DEFAULT(0)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_TABLE') AND name = 'CIX_AC_TABLE_Acid')
DROP INDEX CIX_AC_TABLE_Acid ON AC_TABLE 
CREATE CLUSTERED INDEX CIX_AC_TABLE_Acid ON AC_TABLE(Acid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_TABLE') AND name = 'NCIX_AC_TABLE_Usercode')
DROP INDEX NCIX_AC_TABLE_Usercode ON AC_TABLE 
CREATE NONCLUSTERED INDEX NCIX_AC_TABLE_Usercode ON AC_TABLE(Usercode) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_TABLE') AND name = 'NCIX_AC_TABLE_Fullname')
DROP INDEX NCIX_AC_TABLE_Fullname ON AC_TABLE 
CREATE NONCLUSTERED INDEX NCIX_AC_TABLE_Fullname ON AC_TABLE(Fullname) 
------------------------------------------创建索引区域结束-----------------------------------------------

-----------------------------------------------------修改数据-----------------------------------------------------
UPDATE Ac_Table SET IsUsed = 0 WHERE IsUsed IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



------------------------------------------预置数据-----------------------------------------------

------------------------------------------预置数据-----------------------------------------------



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher')
            and   type = 'U')
BEGIN
	create table Ac_Voucher (
	   STypeId			    varchar(50)          not null,
	   VgId                 int                  null,
	   BillNumberId         numeric(18,0)        identity(1,1),
	   BillDate             datetime             null,
	   BillCode             varchar(400)         null,
	   FlowNo               numeric(18,0)        null,
	   AttachFileCount      int                  null,
	   TallyId              varchar(50)          null,
	   FChecked             int                  null,
	   AuditId              varchar(50)          null,
	   ETypeId              varchar(50)          null,
	   FYear                varchar(10)          null,
	   FPeriod              int                  null,
	   MarkError            varchar(200)         null,
	   FCreditTotal         numeric(18,2)        null,
	   FDebitTotal          numeric(18,2)        null,
	   FEntryCount          int                  null,
	   FModifyTime          datetime             null,
	   FComment             varchar(400)         null,
	   FFootNote            varchar(400)         null,
	   Audited              int                  null,
	   FSerialNum           int                  NULL,
	   Teller				VARCHAR(50)			 NULL,
	   IsSelect				INT					 DEFAULT(0)
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_Voucher 
		ADD STypeId VARCHAR(50) NOT NULL DEFAULT('')
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='GoodsBillId'
)
BEGIN
	ALTER TABLE Ac_Voucher 
		DROP COLUMN GoodsBillId
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='ReCheckId'
)
BEGIN
	ALTER TABLE Ac_Voucher 
		ADD ReCheckId VARCHAR(50) NOT NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='IfCheck'
)
BEGIN
	ALTER TABLE Ac_Voucher 
		ADD IfCheck VARCHAR(50) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='posttime'
)
BEGIN
	ALTER TABLE Ac_Voucher ADD posttime DATETIME NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='RedWord'
)
BEGIN
	ALTER TABLE Ac_Voucher ADD RedWord INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='VoucherType'
)
BEGIN
	ALTER TABLE Ac_Voucher ADD VoucherType INT NULL DEFAULT(0)
END
GO

--2014.04.15新增 “出纳”
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='Teller'
)
BEGIN
	ALTER TABLE Ac_Voucher ADD Teller VARCHAR(50) NULL DEFAULT('')
END
GO

--2014.04.22新增“是否被日记账选择”
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='IsSelect'
)
BEGIN
	ALTER TABLE dbo.Ac_Voucher ADD IsSelect	INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='IsCommission'
)
BEGIN
	ALTER TABLE dbo.Ac_Voucher ADD IsCommission	INT NULL DEFAULT(0)
END
GO


----------2019.09.10  9.91新增反审核人----------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='RChecker'
)
BEGIN
	ALTER TABLE Ac_Voucher 
		ADD RChecker VARCHAR(50) NULL DEFAULT('')
END
GO
UPDATE Ac_Voucher SET RChecker = '' WHERE RChecker IS NULL
GO
-------------------END--------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER') AND name = 'CIX_AC_VOUCHER_BillDate')
--DROP INDEX CIX_AC_VOUCHER_BillDate ON AC_VOUCHER 
CREATE CLUSTERED INDEX CIX_AC_VOUCHER_BillDate ON AC_VOUCHER(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER') AND name = 'NCIX_AC_VOUCHER_Vgid')
--DROP INDEX NCIX_AC_VOUCHER_Vgid ON AC_VOUCHER 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_Vgid ON AC_VOUCHER(Vgid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER') AND name = 'NCIX_AC_VOUCHER_Ifcheck')
--DROP INDEX NCIX_AC_VOUCHER_Ifcheck ON AC_VOUCHER 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_Ifcheck ON AC_VOUCHER(Ifcheck) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER') AND name = 'NCIX_AC_VOUCHER_BillNumberId')
--DROP INDEX NCIX_AC_VOUCHER_BillNumberId ON AC_VOUCHER 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_BillNumberId ON AC_VOUCHER(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER') AND name = 'NCIX_AC_VOUCHER_FYear_FPeriod')
--DROP INDEX NCIX_AC_VOUCHER_FYear_FPeriod ON AC_VOUCHER 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_FYear_FPeriod ON AC_VOUCHER(FYear ,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER') AND name = 'NCIX_AC_VOUCHER_VoucherType')
--DROP INDEX NCIX_AC_VOUCHER_VoucherType ON AC_VOUCHER 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_VoucherType ON AC_VOUCHER(VoucherType) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER') AND name = 'NCIX_AC_VOUCHER_Stypeid')
--DROP INDEX NCIX_AC_VOUCHER_Stypeid ON AC_VOUCHER 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_Stypeid ON AC_VOUCHER(Stypeid) 

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER') AND name = 'IX_Ac_Voucher_FlowNo' )
--DROP INDEX IX_Ac_Voucher_FlowNo ON Ac_Voucher
CREATE NONCLUSTERED INDEX [IX_Ac_Voucher_FlowNo] ON [dbo].[Ac_Voucher]([FlowNo] ASC)
WITH (STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------------------------------修改数据----------------------------------------------------------
UPDATE Ac_Voucher SET ReCheckId = '' WHERE ReCheckId IS NULL
GO
UPDATE Ac_Voucher SET IfCheck = '' WHERE IfCheck IS NULL
GO
UPDATE Ac_Voucher SET RedWord = 0 WHERE RedWord IS NULL
GO
UPDATE Ac_Voucher SET VoucherType = 0 WHERE VoucherType IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='FCreditTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher 
	ALTER COLUMN FCreditTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher' AND a.Name='FDebitTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher 
	ALTER COLUMN FDebitTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill')
            and   type = 'U')
BEGIN
	create table Ac_Voucher_Bill (
	   BillNumberId         numeric(18,0)         null,
	   Summary              varchar(400)         not null,
	   STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   ATypeId2             varchar(50)          null,
	   Fdc                  int                  null,
	   F_ExchId             varchar(50)          null,	   
	   F_ExchIdFor          varchar(50)          null,	   
	   FDebitTotal          numeric(18,2)        null default 0,
	   FDebitTotalFor       numeric(18,2)        null default 0,
	   FCreditTotal         numeric(18,2)        null default 0,
	   FCreditTotalFor      numeric(18,2)        null default 0,	   
	   ID                   numeric(18,0)        identity(1,1),
	   OldID				numeric(18,0)		 null default 0,
	   FCashFlowItem        int                  null,
	   AscIds               varchar(4000)        null,
	   FSettleNo            varchar(200)         null,
	   FSettleTypeID        int                  null,
	   FSettleDate			DATETIME			 NULL,
	   FYear				varchar(100)		 null default '',
	   FPeriod				int					 null default 1,
	   FDebitQty			NUMERIC(24,10)		 not null DEFAULT(0),
	   FCreditQty			NUMERIC(24,10)		 not null DEFAULT(0)
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD Comment VARCHAR(500) NULL DEFAULT('')
END
GO

IF EXISTS(SELECT * from syscolumns where id = object_id(N'[dbo].[Ac_Voucher_Bill]') and  name = 'AscIds' and Length = 4)
BEGIN
     ALTER TABLE Ac_Voucher_Bill
	    ALTER COLUMN AscIds VARCHAR(200) NULL
END
GO

IF EXISTS(SELECT * from syscolumns where id = object_id(N'[dbo].[Ac_Voucher_Bill]') and  name = 'AscIds' and Length = 200)
BEGIN
     ALTER TABLE Ac_Voucher_Bill
	    ALTER COLUMN AscIds VARCHAR(4000) NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='Cid'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD Cid INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='RowNo'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD RowNo INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD Rate NUMERIC(18,4) NULL DEFAULT(1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FAdc'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD FAdc INT NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD STypeId VARCHAR(50) NULL DEFAULT(''),
			FYear VARCHAR(10) NULL DEFAULT(''),
			FPeriod	INT NULL DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FDebitTotalFor'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD FDebitTotalFor NUMERIC(18,2) NULL DEFAULT(0),
			FCreditTotalFor NUMERIC(18,2) NULL DEFAULT(0)
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FAmount'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		DROP COLUMN FAmount,FAmountFor
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='OldID'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD OldID INT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FSettleDate'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD FSettleDate DATETIME NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FDebitQty'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD FDebitQty numeric(24,10) not NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FCreditQty'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD FCreditQty numeric(24,10) not NULL DEFAULT(0) 
END
GO

/*
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='price'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD price numeric(24,10) NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='total'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill 
		ADD total numeric(24,10) NULL 
END
GO
*/

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL') AND name = 'CIX_AC_VOUCHER_BILL_BillNumberId')
--DROP INDEX CIX_AC_VOUCHER_BILL_BillNumberId ON AC_VOUCHER_BILL 
CREATE CLUSTERED INDEX CIX_AC_VOUCHER_BILL_BillNumberId ON AC_VOUCHER_BILL(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL') AND name = 'NCIX_AC_VOUCHER_BILL_Id')
--DROP INDEX NCIX_AC_VOUCHER_BILL_Id ON AC_VOUCHER_BILL 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_BILL_Id ON AC_VOUCHER_BILL(Id) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL') AND name = 'NCIX_AC_VOUCHER_BILL_FYear_FPeriod')
--DROP INDEX NCIX_AC_VOUCHER_BILL_FYear_FPeriod ON AC_VOUCHER_BILL 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_BILL_FYear_FPeriod ON AC_VOUCHER_BILL(FYear ,FPeriod) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL') AND name = 'NCIX_AC_VOUCHER_BILL_STypeId')
--DROP INDEX NCIX_AC_VOUCHER_BILL_STypeId ON AC_VOUCHER_BILL 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_BILL_STypeId ON AC_VOUCHER_BILL(STypeId) 


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL') AND name = 'NCIX_AC_VOUCHER_BILL_ATypeId')
--DROP INDEX NCIX_AC_VOUCHER_BILL_ATypeId ON AC_VOUCHER_BILL 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_BILL_ATypeId ON AC_VOUCHER_BILL(ATypeId) 
------------------------------------------创建索引区域结束-----------------------------------------------
-----------------------------------------------修改数据-----------------------------------------------
UPDATE Ac_Voucher_Bill SET Comment = '' WHERE Comment IS NULL
GO
UPDATE Ac_Voucher_Bill SET AscIds = '' WHERE AscIds IS NULL
GO
UPDATE Ac_Voucher_Bill SET Cid = 0 WHERE Cid IS NULL
GO
UPDATE Ac_Voucher_Bill SET RowNo = 0 WHERE RowNo IS NULL
GO
UPDATE Ac_Voucher_Bill SET Rate = 1 WHERE Rate IS NULL
GO
UPDATE Ac_Voucher_Bill SET FAdc = CASE WHEN ISNULL(FDebitTotal,0)<> 0 THEN 1 ELSE -1 END
GO
UPDATE Ac_Voucher_Bill SET FDebitTotalFor = 0 WHERE FDebitTotalFor IS NULL
GO
UPDATE Ac_Voucher_Bill SET FCreditTotalFor = 0 WHERE FCreditTotalFor IS NULL
GO
UPDATE Ac_Voucher_Bill SET OldID = 0 WHERE OldID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FDebitTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill 
	ALTER COLUMN FDebitTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FDebitTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill 
	ALTER COLUMN FDebitTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FCreditTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill 
	ALTER COLUMN FCreditTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='FCreditTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill 
	ALTER COLUMN FCreditTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill_Assist_CheckItems')
            and   type = 'U')
BEGIN
	create table Ac_Voucher_Bill_Assist_CheckItems (
	   nId                  int                  identity(1,1),
	   BillNumberId         numeric(18,0)        null,
	   vBId                 int                  null,
	   typeName             varchar(10)          null,
	   TypeId               varchar(50)          null
	)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Assist_CheckItems' AND a.Name='BillNumberId'
)
BEGIN
	ALTER TABLE Ac_Voucher_Bill_Assist_CheckItems 
		ADD BillNumberId NUMERIC(18,0) NOT NULL DEFAULT(0) 
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL_ASSIST_CHECKITEMS') AND name = 'CIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_Vbid')
--DROP INDEX CIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_Vbid ON AC_VOUCHER_BILL_ASSIST_CHECKITEMS 
CREATE CLUSTERED INDEX CIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_Vbid ON AC_VOUCHER_BILL_ASSIST_CHECKITEMS(Vbid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_BillNumberId')
--DROP INDEX NCIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_BillNumberId ON AC_VOUCHER_BILL_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_BillNumberId ON AC_VOUCHER_BILL_ASSIST_CHECKITEMS(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL_ASSIST_CHECKITEMS') AND name = 'NCIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_Typeid')
--DROP INDEX NCIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_Typeid ON AC_VOUCHER_BILL_ASSIST_CHECKITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_BILL_ASSIST_CHECKITEMS_Typeid ON AC_VOUCHER_BILL_ASSIST_CHECKITEMS(Typeid) 
------------------------------------------创建索引区域结束-----------------------------------------------





------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 






-----Ac_Voucher_Bill_Assist_CheckItems_Temp表用于《批量操作提示》按钮生成凭证时存储生成结果
if exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill_Assist_CheckItems_Temp')
            and   type = 'U')
BEGIN
	drop table Ac_Voucher_Bill_Assist_CheckItems_Temp
END


create table Ac_Voucher_Bill_Assist_CheckItems_Temp (
   nid                 int                  null,
   BillNumberId         numeric(18,0)        ,
   vbid			int,
   usercode		varchar(500),
   typeid		varchar(50),
   fullname		varchar(500),
   displayfield	varchar(50),
   datafield	varchar(50),
   value		int
)

GO

------------------------------------------创建索引区域开始-----------------------------------------------




------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------------------------------修改数据----------------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill_Backup')
            and   type = 'U')
BEGIN
	create table Ac_Voucher_Bill_Backup (
	   BillNumberId         numeric(18,0)         null,
	   Summary              varchar(400)          null,
	   STypeId              varchar(50)           null,
	   ATypeId              varchar(50)           null,
	   ATypeId2             varchar(50)          null,
	   Fdc                  int                  null,
	   F_ExchId             varchar(50)          null,	   
	   F_ExchIdFor          varchar(50)          null,	   
	   FDebitTotal          numeric(18,2)        null default 0,
	   FDebitTotalFor       numeric(18,2)        null default 0,
	   FCreditTotal         numeric(18,2)        null default 0,
	   FCreditTotalFor      numeric(18,2)        null default 0,	   
	   ID                   numeric(18,0)        NULL,
	   OldID				numeric(18,0)		 null default 0,
	   FCashFlowItem        int                  null,
	   AscIds               varchar(4000)        null,
	   FSettleNo            varchar(200)         null,
	   FSettleTypeID        int                  null,
	   FSettleDate			DATETIME			 NULL,
	   FYear				varchar(100)		 null default '',
	   FPeriod				int					 null default 1,
	   Comment				varchar(500)		 null default '',
	   Cid					int					 null default 0,
	   RowNo				int					 null default 0,
	   Rate					NUMERIC(18,4)		 null default 1,
	   FAdc					int					 null 
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Voucher_Bill_Backup') AND name = 'CIX_Ac_Voucher_Bill_Backup_BillNumberId')
--DROP INDEX CIX_Ac_Voucher_Bill_Backup_BillNumberId ON Ac_Voucher_Bill_Backup 
CREATE CLUSTERED INDEX CIX_Ac_Voucher_Bill_Backup_BillNumberId ON Ac_Voucher_Bill_Backup(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Voucher_Bill_Backup') AND name = 'NCIX_Ac_Voucher_Bill_Backup_Id')
--DROP INDEX NCIX_Ac_Voucher_Bill_Backup_Id ON Ac_Voucher_Bill_Backup 
CREATE NONCLUSTERED INDEX NCIX_Ac_Voucher_Bill_Backup_Id ON Ac_Voucher_Bill_Backup(Id) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ac_Voucher_Bill_Backup') AND name = 'NCIX_Ac_Voucher_Bill_Backup_FYear_FPeriod')
--DROP INDEX NCIX_Ac_Voucher_Bill_Backup_FYear_FPeriod ON Ac_Voucher_Bill_Backup 
CREATE NONCLUSTERED INDEX NCIX_Ac_Voucher_Bill_Backup_FYear_FPeriod ON Ac_Voucher_Bill_Backup(FYear ,FPeriod) 
------------------------------------------创建索引区域结束-----------------------------------------------
-----------------------------------------------修改数据-----------------------------------------------
UPDATE Ac_Voucher_Bill_Backup SET Comment = '' WHERE Comment IS NULL
GO
UPDATE Ac_Voucher_Bill_Backup SET AscIds = '' WHERE AscIds IS NULL
GO
UPDATE Ac_Voucher_Bill_Backup SET Cid = 0 WHERE Cid IS NULL
GO
UPDATE Ac_Voucher_Bill_Backup SET RowNo = 0 WHERE RowNo IS NULL
GO
UPDATE Ac_Voucher_Bill_Backup SET Rate = 1 WHERE Rate IS NULL
GO
UPDATE Ac_Voucher_Bill_Backup SET FAdc = CASE WHEN ISNULL(FDebitTotal,0)<> 0 THEN 1 ELSE -1 END
GO
UPDATE Ac_Voucher_Bill_Backup SET FDebitTotalFor = 0 WHERE FDebitTotalFor IS NULL
GO
UPDATE Ac_Voucher_Bill_Backup SET FCreditTotalFor = 0 WHERE FCreditTotalFor IS NULL
GO
UPDATE Ac_Voucher_Bill_Backup SET OldID = 0 WHERE OldID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Backup' AND a.Name='FDebitTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Backup 
	ALTER COLUMN FDebitTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Backup' AND a.Name='FDebitTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Backup 
	ALTER COLUMN FDebitTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Backup' AND a.Name='FCreditTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Backup 
	ALTER COLUMN FCreditTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Backup' AND a.Name='FCreditTotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Backup 
	ALTER COLUMN FCreditTotalFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Backup' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Backup 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

if exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill_Backup')
            and   type = 'U')
BEGIN
	DROP TABLE Ac_Voucher_Bill_Backup
END
GO
            



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill_CashMoneyItems')
            and   type = 'U')
BEGIN
	create table Ac_Voucher_Bill_CashMoneyItems (
	   nId                  int                  identity(1,1),
	   BillNumberId         numeric(18,0)        null,
	   STypeId              varchar(50)          null,
	   MATypeId             varchar(50)          null,
	   DATypeId             varchar(50)          null,
	   FDc                  int                  null,
	   FAdc                 int                  null,
	   RowNo                int                  null,
	   Cid                  int                  null,
	   Total                numeric(18,2)        null default 0,
	   TotalFor             numeric(18,2)        null default 0,
	   FYear                varchar(10)          null,
	   FPeriod              int                  null
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL_CASHMONEYITEMS') AND name = 'CIX_AC_VOUCHER_BILL_CASHMONEYITEMS_BillNumberId')
--DROP INDEX CIX_AC_VOUCHER_BILL_CASHMONEYITEMS_BillNumberId ON AC_VOUCHER_BILL_CASHMONEYITEMS 
CREATE CLUSTERED INDEX CIX_AC_VOUCHER_BILL_CASHMONEYITEMS_BillNumberId ON AC_VOUCHER_BILL_CASHMONEYITEMS(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_BILL_CASHMONEYITEMS') AND name = 'NCIX_AC_VOUCHER_BILL_CASHMONEYITEMS_MATypeId')
--DROP INDEX NCIX_AC_VOUCHER_BILL_CASHMONEYITEMS_MATypeId ON AC_VOUCHER_BILL_CASHMONEYITEMS 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_BILL_CASHMONEYITEMS_MATypeId ON AC_VOUCHER_BILL_CASHMONEYITEMS(MATypeId) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_CashMoneyItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_CashMoneyItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_CashMoneyItems' AND a.Name='TotalFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_CashMoneyItems 
	ALTER COLUMN TotalFor NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill_Log')
            and   type = 'U')
BEGIN
	create table Ac_Voucher_Bill_Log (
	  billnumberid INT ,
	  explain VARCHAR(200),
	  atypeid  VARCHAR(50),
	  atypeid2 VARCHAR(50),
	  Fdc  INT,
	  f_exchid INT ,
	  f_exchidfor INT,
	  lendprice NUMERIC(18,2),
	  loanprice NUMERIC(18,2),
	  lendpricefor NUMERIC(18,2),
	  loanpricefor NUMERIC(18,2),
	  FCashFlowItem INT,
	  ascids VARCHAR(4000),
	  FSettleNo VARCHAR(200),
	  FSettleTypeID INT,
	  comment VARCHAR(200),
	  cid INT,
	  rate NUMERIC(18,4),
	  fadc INT,
	  stypeid VARCHAR(50),
	  fyear INT,
	  fperiod INT,
	  atid INT,
	  atdid INT,
	  addebtid INT,
	  billid INT,
	  CardId				INT,
	  credenceId			INT,
	  capitalid			INT					--调拨单明细id
	)
END
GO


ALTER TABLE Ac_Voucher_Bill_Log ALTER COLUMN explain VARCHAR(400)
ALTER TABLE Ac_Voucher_Bill_Log ALTER COLUMN comment VARCHAR(500)



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Log' AND a.Name='lendprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Log 
	ALTER COLUMN lendprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Log' AND a.Name='loanprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Log 
	ALTER COLUMN loanprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Log' AND a.Name='lendpricefor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Log 
	ALTER COLUMN lendpricefor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Log' AND a.Name='loanpricefor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Log 
	ALTER COLUMN loanpricefor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Log' AND a.Name='rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Log 
	ALTER COLUMN rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 
if exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill_Log')
            and   type = 'U')
BEGIN
	DROP TABLE Ac_Voucher_Bill_Log
END
GO
            






-----Ac_Voucher_Bill_Temp表用于《批量操作提示》按钮生成凭证时存储生成结果
if exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Bill_Temp')
            and   type = 'U')
BEGIN
	drop table Ac_Voucher_Bill_Temp

END

create table Ac_Voucher_Bill_Temp 
(
   BillNumberId         numeric(18,0)         null,
   explain              varchar(400)         not null,
   usercode				varchar(500),
   fullname				varchar(500),
   typeid				varchar(50),
   sysrow				int,
   cid					int,
   moneytype			int,
   basisType			int,
   rate					numeric(18,4),
   balanceprice			numeric(18,4),
   lendprice			numeric(18,4),
   loanprice			numeric(18,4),
   FSettleNo            varchar(200)         null,
   FSettleTypeID        int                  null,
   comment				varchar(500),
   STypeId              varchar(50)          not null,
   Fdc                  int                  null,
   fadc					int,
   facnt				int,
   FCashFlowItem        int                  null,
   rowno				int,
   id					numeric(18,0) ,
   MainItems			varchar(500),
   AdditionItems		varchar(500),
   KeyId				bigint,
   iscash				int,
   isbank				int,
   IsDiary				int,
   isother				int,
   mcid					int,
   mainitemsid			varchar(500),
   additionitemsid		varchar(500),
   mainitemsname		varchar(500),
   additionitemsname	varchar(500),
   assist				varchar(5000),
   asslist				varchar(5000) null,
   balancenum			varchar(500),
   balancetype			int,
   cUserCode			varchar(500),
   cFullName			varchar(500),
   islimit_ac			int
 )

GO

------------------------------------------创建索引区域开始-----------------------------------------------


------------------------------------------创建索引区域结束-----------------------------------------------
-----------------------------------------------修改数据-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Temp' AND a.Name='rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Temp 
	ALTER COLUMN rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Temp' AND a.Name='balanceprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Temp 
	ALTER COLUMN balanceprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Temp' AND a.Name='lendprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Temp 
	ALTER COLUMN lendprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Bill_Temp' AND a.Name='loanprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Bill_Temp 
	ALTER COLUMN loanprice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
/************************************************************
 * 创 建 人：罗淮文
 * 创建时间: 2014/4/18 10:58:04
 * 内容描述：常用凭证模板主表
 ************************************************************/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ac_Voucher_Commonly]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Ac_Voucher_Commonly]
	(
		[BillCode]            [varchar](400) NOT NULL,	--单据编号
		[BillName]            [varchar](400) NOT NULL,--单据名称                                	
		[STypeId]             [varchar](50) NOT NULL,	--分支机构ID
		[VgId]                [int] NULL,	--凭证字ID
		[BillNumberId]        [numeric](18, 0) IDENTITY(1, 1) NOT NULL,	--单据编号ID
		[AttachFileCount]     [int] NULL,	--附件数
		[ETypeId]             [varchar](50) NULL,	--制单人
		[FYear]               [varchar](10) NULL,	--会计年度
		[FPeriod]             [int] NULL,	--会计期间
		[FDebitTotal]         [numeric](18, 2) NULL,	--借方金额合计
		[FCreditTotal]        [numeric](18, 2) NULL,	--贷方金额合计
		[FEntryCount]         [int] NULL,	--分录数（明细记录数）
		[FModifyTime]         [datetime] NULL,	--修改日期
		[FComment]            [varchar](400) NULL,	--备注
	) ON [PRIMARY]
END
GO

SET ANSI_PADDING OFF
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly' AND a.Name='BillCode'
)
BEGIN
	ALTER TABLE [dbo].[Ac_Voucher_Commonly] ADD  DEFAULT(('')) FOR [BillCode]
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly' AND a.Name='BillName'
)
BEGIN
	ALTER TABLE [dbo].[Ac_Voucher_Commonly] ADD  DEFAULT(('')) FOR [BillName]
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly' AND a.Name='FDebitTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Commonly 
	ALTER COLUMN FDebitTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly' AND a.Name='FCreditTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Commonly 
	ALTER COLUMN FCreditTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
/************************************************************
 * 创 建 人：罗淮文
 * 创建时间: 2014/4/18 11:19:43
 * 内容描述：常用凭证模板明细
 ************************************************************/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ac_Voucher_Commonly_Bill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Ac_Voucher_Commonly_Bill]
	(
		[ID]                  [numeric](18, 0) IDENTITY(1, 1) NOT NULL,	--自增长ID
		[BillNumberId]        [numeric](18, 0) NULL,	--单据编号ID
		[Summary]             [varchar](400) NOT NULL,	--摘要
		[STypeId]             [varchar](50) NOT NULL,	--分支机构ID
		[ATypeId]             [varchar](50) NOT NULL,	--会计科目ID
		[Fdc]                 [int] NULL,	--科目余额借贷方向 1.借方 -1.贷方
		[FAdc]                [int] NULL,	--会计分录借贷方向 1.借方 -1.贷方
		[FDebitTotal]         [numeric](18, 2) NULL,	--本币借方金额
		[FCreditTotal]        [numeric](18, 2) NULL,	--本币贷方金额
		[FYear]               [varchar](100) NULL,	--会计年度
		[FPeriod]             [int] NULL,	--会计期间
		[Comment]             [varchar](500) NULL,	--备注
		[RowNo]               [int] NULL,	--分录号
		[AscIds]			  [VARCHAR](4000) NULL --辅助核算
	) ON [PRIMARY]
END
GO

SET ANSI_PADDING OFF
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly_Bill' AND a.Name='FDebitTotal'
)
BEGIN
	ALTER TABLE [dbo].[Ac_Voucher_Commonly_Bill] ADD  DEFAULT ((0)) FOR [FDebitTotal]
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly_Bill' AND a.Name='FCreditTotal'
)
BEGIN

	ALTER TABLE [dbo].[Ac_Voucher_Commonly_Bill] ADD  DEFAULT ((0)) FOR [FCreditTotal]
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly_Bill' AND a.Name='FYear'
)
BEGIN
	ALTER TABLE [dbo].[Ac_Voucher_Commonly_Bill] ADD  DEFAULT ('') FOR [FYear]
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly_Bill' AND a.Name='FPeriod'
)
BEGIN
	ALTER TABLE [dbo].[Ac_Voucher_Commonly_Bill] ADD  DEFAULT ((1)) FOR [FPeriod]
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly_Bill' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE [dbo].[Ac_Voucher_Commonly_Bill] ADD  DEFAULT ('') FOR [Comment]
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly_Bill' AND a.Name='RowNo'
)
BEGIN
	ALTER TABLE [dbo].[Ac_Voucher_Commonly_Bill] ADD  DEFAULT ((0)) FOR [RowNo]
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly_Bill' AND a.Name='FDebitTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Commonly_Bill 
	ALTER COLUMN FDebitTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Commonly_Bill' AND a.Name='FCreditTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ac_Voucher_Commonly_Bill 
	ALTER COLUMN FCreditTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





-----Ac_Voucher_Generate_Voucherbill_GoodsBills表用于《批量操作提示》按钮生成凭证时存储生成结果 ps保存凭证和业务单据对应关系
if  exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Generate_Voucherbill_GoodsBills')
            and   type = 'U')
BEGIN
	drop table Ac_Voucher_Generate_Voucherbill_GoodsBills
END


create table Ac_Voucher_Generate_Voucherbill_GoodsBills (
   STypeId			    varchar(50)          not null,
   BillNumberId         numeric(18,0),
   billnumberids		varchar(max)
)


GO

------------------------------------------创建索引区域开始-----------------------------------------------



------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------------------------------修改数据----------------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Group')
            and   type = 'U')
BEGIN
	create table Ac_Voucher_Group (
	   VgId                 int                  identity(1,1),
	   FullName             varchar(200)         not null,
	   IsMulVourchLimit     int                  null,
	   PyCode               varchar(200)         null
	)
END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Group' AND a.Name='IsDebit'
)
BEGIN
	ALTER TABLE Ac_Voucher_Group 
		DROP COLUMN IsDebit,IsCredit,IsDebitOrCredit,IsNoDebit,IsNoCredit,IsNoDebitAndCredit
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ac_Voucher_Group' AND a.Name='IsDefault'
)
BEGIN
	ALTER TABLE Ac_Voucher_Group 
		ADD IsDefault INT NOT NULL DEFAULT(0)
END
GO

--默认记账凭证
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Group)
BEGIN
	INSERT INTO Ac_Voucher_Group(FullName,IsMulVourchLimit,PyCode,IsDefault)VALUES('记',0,'J',1)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_GROUP') AND name = 'CIX_AC_VOUCHER_GROUP_Vgid')
--DROP INDEX CIX_AC_VOUCHER_GROUP_Vgid ON AC_VOUCHER_GROUP 
CREATE CLUSTERED INDEX CIX_AC_VOUCHER_GROUP_Vgid ON AC_VOUCHER_GROUP(Vgid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_GROUP') AND name = 'NCIX_AC_VOUCHER_GROUP_Fullname')
--DROP INDEX NCIX_AC_VOUCHER_GROUP_Fullname ON AC_VOUCHER_GROUP 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_GROUP_Fullname ON AC_VOUCHER_GROUP(Fullname) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Group_Detail')
            and   type = 'U')   
BEGIN
	create table Ac_Voucher_Group_Detail (
	   VgdId                int                  identity(1,1),
	   VgId                 int                  null,
	   ATypeId              varchar(50)          null,
	   IsDebit              int                  null default 0,
	   IsCredit             int                  null default 0,
	   IsDebitOrCredit      int                  null default 0,
	   IsNoDebit            int                  null default 0,
	   IsNoCredit           int                  null default 0,
	   IsNoDebitAndCredit   int                  null default 0
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_GROUP_DETAIL') AND name = 'CIX_AC_VOUCHER_GROUP_DETAIL_Vgid')
--DROP INDEX CIX_AC_VOUCHER_GROUP_DETAIL_Vgid ON AC_VOUCHER_GROUP_DETAIL 
CREATE CLUSTERED INDEX CIX_AC_VOUCHER_GROUP_DETAIL_Vgid ON AC_VOUCHER_GROUP_DETAIL(Vgid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AC_VOUCHER_GROUP_DETAIL') AND name = 'NCIX_AC_VOUCHER_GROUP_DETAIL_Atypeid')
--DROP INDEX NCIX_AC_VOUCHER_GROUP_DETAIL_Atypeid ON AC_VOUCHER_GROUP_DETAIL 
CREATE NONCLUSTERED INDEX NCIX_AC_VOUCHER_GROUP_DETAIL_Atypeid ON AC_VOUCHER_GROUP_DETAIL(Atypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Repair_Msg')
            and   type = 'U')   
BEGIN
	CREATE TABLE Ac_Voucher_Repair_Msg
	(
		nid		INT IDENTITY(1,1),
		Msg		VARCHAR(2000)
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





-----Ac_Voucher_Temp表用于《批量操作提示》按钮生成凭证时存储生成结果
if exists (select 1
            from  sysobjects
           where  id = object_id('Ac_Voucher_Temp')
            and   type = 'U')
BEGIN
	drop table Ac_Voucher_Temp
END
	create table Ac_Voucher_Temp (
	   STypeId			    varchar(50)          not null,
	   VgId                 int                  null,
	   BillNumberId         numeric(18,0)        identity(1,1),
	   BillDate             datetime             null,
	   FlowNo               numeric(18,0)        null,	   
	   FComment             varchar(400)         null,
	   SbillType			INT,
	   InOutType			INT
	)
GO

------------------------------------------创建索引区域开始-----------------------------------------------




------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------------------------------修改数据----------------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

/************************************************************
 * 创 建 人：罗淮文
 * 创建时间: 2014/4/18 11:19:43
 * 内容描述：常用凭证模板辅助核算
 ************************************************************/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ac_VoucherCommonly_Bill_Assist_CheckItems]') AND type in (N'U'))
BEGIN
	CREATE TABLE Ac_VoucherCommonly_Bill_Assist_CheckItems
	(
		nId INT IDENTITY(1,1) NOT NULL,--自增长ID
		BillNumberId	INT NULL,--模板凭证BillNumberId
		vBId	INT NULL,--Ac_VoucherCommonly_Bill的ID
		typeName	VARCHAR(10) NULL,--基本信息类型 E.职员 K.仓库
		TypeId	VARCHAR(50) NULL--基本信息ID
	) 
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Ac_VoucherType') AND  type = 'U')
BEGIN
	CREATE TABLE  Ac_VoucherType
	(
		Id	INT,
		FullName	VARCHAR(100)
	)
END
GO
IF NOT EXISTS (SELECT TOP 1 1 FROM Ac_VoucherType)
BEGIN
	INSERT INTO Ac_VoucherType( Id, FullName )
	VALUES	(0,'手工录入'),
			(1,'期末调汇'),
			(2,'结转损益'),
			(3,'业务单据生成'),
			(4,'固定资产系统生成单据'),
			(5,'固定资产系统部门转移'),
			(6,'固定资产系统计提减值')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_VoucherType WHERE Id = 7)
BEGIN
	INSERT INTO dbo.Ac_VoucherType( Id, FullName )
	VALUES(7,'出纳系统单据')
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AccountCredence]    脚本日期: 05/05/2010 14:46:25 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AccountCredence]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AccountCredence](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[TypeATypeID] [varchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[ATypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[J_Total] [numeric](18, 4) NULL,
		[D_Total] [numeric](18, 4) NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) NULL DEFAULT (''),
		[NJ_Total] [numeric](18, 4) NULL DEFAULT(0),
		[ND_Total] [numeric](18, 4) NULL DEFAULT(0),
		[CID]		INT NULL DEFAULT(0),
		[Rate]		NUMERIC(22,10) NULL DEFAULT(0),
		[AlertDay]  INT NOT NULL DEFAULT(9999),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AccountCredence',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.AccountCredence
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AccountCredence',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.AccountCredence
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 483 FROM SysColumns WHERE ID=OBJECT_ID(N'AccountCredence',N'U') AND Name='AlertDay')
BEGIN
	ALTER TABLE AccountCredence
	ADD AlertDay INT NOT NULL DEFAULT(9999)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='NJ_Total'
)
BEGIN
	ALTER TABLE AccountCredence ADD NJ_Total [numeric](18, 4) NULL  DEFAULT(0),ND_Total [numeric](18, 4) NULL  DEFAULT(0)
	
	
	EXEC('
	UPDATE AccountCredence SET NJ_Total=J_Total,ND_Total=D_Total
	WHERE NJ_Total IS NULL
	')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE AccountCredence ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE AccountCredence SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='CID'
)
BEGIN
	ALTER TABLE AccountCredence ADD CID int  NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE AccountCredence ADD Rate NUMERIC(22,10)
END
GO
--商品品牌
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='BrandarTypeId'
)
BEGIN
		ALTER TABLE AccountCredence 
			ADD [BrandarTypeId] VARCHAR(50) NOT NULL DEFAULT('') --商品品牌
END
GO
UPDATE AccountCredence SET BrandarTypeId ='' WHERE BrandarTypeId IS NULL
GO

--经手人
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='ETypeId'
)
BEGIN
		ALTER TABLE AccountCredence 
			ADD [ETypeId] VARCHAR(50) NOT NULL DEFAULT('') --商品品牌
END

--部门
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='DTypeId'
)
BEGIN
		ALTER TABLE AccountCredence 
			ADD [DTypeId] VARCHAR(50) NOT NULL DEFAULT('') --商品品牌
END
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ACCOUNTCREDENCE') AND name = 'CIX_ACCOUNTCREDENCE_BillNumberID')
--DROP INDEX CIX_ACCOUNTCREDENCE_BillNumberID ON ACCOUNTCREDENCE 
CREATE CLUSTERED INDEX CIX_ACCOUNTCREDENCE_BillNumberID ON ACCOUNTCREDENCE(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ACCOUNTCREDENCE') AND name = 'NCIX_ACCOUNTCREDENCE_Stypeid')
--DROP INDEX NCIX_ACCOUNTCREDENCE_Stypeid ON ACCOUNTCREDENCE 
CREATE NONCLUSTERED INDEX NCIX_ACCOUNTCREDENCE_Stypeid ON ACCOUNTCREDENCE(Stypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ACCOUNTCREDENCE') AND name = 'NCIX_ACCOUNTCREDENCE_Atypeid_TypeATypeId')
--DROP INDEX NCIX_ACCOUNTCREDENCE_Atypeid_TypeATypeId ON ACCOUNTCREDENCE 
CREATE NONCLUSTERED INDEX NCIX_ACCOUNTCREDENCE_Atypeid_TypeATypeId ON ACCOUNTCREDENCE(Atypeid,TypeATypeId) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='J_Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AccountCredence 
	ALTER COLUMN J_Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='D_Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AccountCredence 
	ALTER COLUMN D_Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='NJ_Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AccountCredence 
	ALTER COLUMN NJ_Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='ND_Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AccountCredence 
	ALTER COLUMN ND_Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AccountCredence' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AccountCredence 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AccountInterFaceFileList]    脚本日期: 05/05/2010 14:46:26 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AccountInterFaceFileList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AccountInterFaceFileList](
		[FileID] [int] IDENTITY(1,1) NOT NULL,
		[FileName] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[CreateDate] [datetime] NOT NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ContentType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[FileSize] [int] NULL,
		[BinaryData] [image] NULL,
		[Memo] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AccountSubjectSet]    脚本日期: 05/05/2010 14:46:27 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AccountSubjectSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AccountSubjectSet](
		[SoftType] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[ATypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[SubjectCode] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[J_D] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AccountTimeConfig]    脚本日期: 05/05/2010 14:46:28 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AccountTimeConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AccountTimeConfig](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Col] [int] NULL DEFAULT ('1'),
		[Col0] [int] NULL DEFAULT ('0'),
		[Col1] [int] NULL DEFAULT ('0'),
		[Col2] [int] NULL DEFAULT ('0'),
		[Col3] [int] NULL DEFAULT ('0'),
		[Col4] [int] NULL DEFAULT ('0'),
		[Col5] [int] NULL DEFAULT ('0'),
		[Col6] [int] NULL DEFAULT ('0'),
		[Col7] [int] NULL DEFAULT ('0'),
		[Col8] [int] NULL DEFAULT ('0'),
		[Col9] [int] NULL DEFAULT ('0')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AdDebtBill]    脚本日期: 05/05/2010 14:46:29 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AdDebtBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AdDebtBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_AdDebtBill_total]  DEFAULT (0),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[CompleteTotal] [numeric](18, 4) NULL CONSTRAINT [DF_AdDebtBill_CompleteTotal]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[NTotal] [numeric](18, 4) DEFAULT (0),
		[NCompleteTotal] [numeric](18, 4)  DEFAULT (0),
		[ShowOrder] INT DEFAULT(0),
		[AlertDay]  INT NOT NULL DEFAULT(9999),
		[IfStopMoney] BIT NOT NULL DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[jsStyle] INT NOT NULL DEFAULT (0), --结算方式 0未结算 1 按单 2 按商品 3 按品牌
		[jsState] INT NOT NULL  DEFAULT (0) --结算状态 0未结算 1 已结算未完成 2 结算完成
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AdDebtBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.AdDebtBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AdDebtBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.AdDebtBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AdDebtBill',N'U') AND Name='IfStopMoney')
BEGIN
	ALTER TABLE dbo.AdDebtBill
	ADD IfStopMoney BIT DEFAULT(0)
END

IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AdDebtBill',N'U') AND Name='AlertDay' AND XType=104)
BEGIN
	DECLARE @SQL VARCHAR(1000)
	SELECT @SQL=Name FROM Sys.Default_Constraints WHERE OBJECT_ID IN(SELECT default_object_id FROM Sys.Columns WHERE OBJECT_ID=OBJECT_ID(N'AdDebtBill',N'U') AND Name='AlertDay')
	IF @SQL IS NOT NULL
		EXEC ('ALTER TABLE AdDebtBill DROP CONSTRAINT '+@SQL);
	ALTER TABLE AdDebtBill
	DROP COLUMN AlertDay
END

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AdDebtBill',N'U') AND Name='AlertDay')
BEGIN
	ALTER TABLE dbo.AdDebtBill
	ADD AlertDay INT DEFAULT(9999)
END



IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AdDebtBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.AdDebtBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE AdDebtBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE AdDebtBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE AdDebtBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE AdDebtBill ADD [NTotal] [numeric](18, 4)  DEFAULT (0)
		
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='NCompleteTotal'
)
BEGIN
		ALTER TABLE AdDebtBill ADD [NCompleteTotal] [numeric](18, 4)  DEFAULT (0)
		
END

GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CID';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='AdDebtBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='ChargeOffTotal'
)
BEGIN
	ALTER TABLE AdDebtBill 
		ADD ChargeOffTotal NUMERIC(24,10) DEFAULT 0 NOT NULL 
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='NChargeOffTotal'
)
BEGIN
	ALTER TABLE AdDebtBill 
		ADD NChargeOffTotal NUMERIC(24,10) DEFAULT 0 NOT NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='BrandarTypeID'
)
BEGIN
	ALTER TABLE AdDebtBill 
		ADD BrandarTypeID VARCHAR(50) NOT NULL DEFAULT('')
END
GO
------------------------------------------表修改区域结束-------------------------------------------------
UPDATE dbo.AdDebtBill SET NChargeOffTotal=0 WHERE NChargeOffTotal IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='BrandarTypeId'
)
BEGIN
	ALTER TABLE AdDebtBill 
		ADD BrandarTypeId VARCHAR(50) DEFAULT('') NULL
END
GO
UPDATE AdDebtBill SET BrandarTypeId = '' WHERE BrandarTypeId IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='JsStyle'
)
BEGIN
	ALTER TABLE AdDebtBill 
		ADD JsStyle INT NOT NULL DEFAULT (0)
END
GO
UPDATE AdDebtBill SET JsStyle = 0 WHERE JsStyle IS NULL
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='jsState'
)
BEGIN
	ALTER TABLE AdDebtBill 
			ADD jsState INT NOT NULL DEFAULT (0)
END
GO
UPDATE AdDebtBill SET jsState = 0 WHERE jsState IS NULL
GO

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS(select * from dbo.sysindexes where id = object_id(N'[dbo].[AdDebtBill]') and name = 'IX_AdDebtBill')
--DROP INDEX [AdDebtBill].[IX_AdDebtBill]
CREATE  UNIQUE  INDEX [IX_AdDebtBill] ON [dbo].[AdDebtBill]([ID]) ON [PRIMARY]


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADDEBTBILL') AND name = 'CIX_ADDEBTBILL_BillNumberID')
--DROP INDEX CIX_ADDEBTBILL_BillNumberID ON ADDEBTBILL 
CREATE CLUSTERED INDEX CIX_ADDEBTBILL_BillNumberID ON ADDEBTBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADDEBTBILL') AND name = 'NCIX_ADDEBTBILL_Stypeid')
--DROP INDEX NCIX_ADDEBTBILL_Stypeid ON ADDEBTBILL 
CREATE NONCLUSTERED INDEX NCIX_ADDEBTBILL_Stypeid ON ADDEBTBILL(Stypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADDEBTBILL') AND name = 'NCIX_ADDEBTBILL_Btypeid')
--DROP INDEX NCIX_ADDEBTBILL_Btypeid ON ADDEBTBILL 
CREATE NONCLUSTERED INDEX NCIX_ADDEBTBILL_Btypeid ON ADDEBTBILL(Btypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdDebtBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdDebtBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdDebtBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdDebtBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
    
IF Exists (	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdDebtBill' AND a.Name='IfStopMoney' and a.isnullable=1 )
	BEGIN 
		UPDATE AdDebtBill SET  IfStopMoney=0 WHERE  IfStopMoney IS NULL
		ALTER TABLE AdDebtBill 
		ALTER COLUMN IfStopMoney BIT NOT NULL 	
	END                                            
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
新增打印次数记录表
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AddPrintCountRecord]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AddPrintCountRecord](
		[BillType] [numeric](4,0) NOT NULL,
		[BillNumberId] [numeric](10,0) NOT NULL,
		[etypeid] [varchar](50) NOT NULL,
		[addprintcount] INT NOT NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AdPriceBill]    脚本日期: 05/05/2010 14:46:30 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AdPriceBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AdPriceBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_AdPriceBill_Qty]  DEFAULT (0),
		[BeforePrice] [numeric](18, 4) NULL CONSTRAINT [DF_AdPriceBill_BeforePrice]  DEFAULT (0),
		[BeforeTotal] [numeric](18, 4) NULL CONSTRAINT [DF_AdPriceBill_BeforeTotal]  DEFAULT (0),
		[Rate] [numeric](18, 4) NULL CONSTRAINT [DF_AdPriceBill_Rate]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_AdPriceBill_Price]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_AdPriceBill_total]  DEFAULT (0),
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_AdPriceBill_JobNumber]  DEFAULT (''),
		[GoodsNo] [int] NULL CONSTRAINT [DF_AdPriceBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_AdPriceBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ChangeAllStock] [int] NULL,
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_AdPriceBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_AdPriceBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_AdPriceBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_AdPriceBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_AdPriceBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_AdPriceBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_AdPriceBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_AdPriceBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_AdPriceBill_HandZeroCost]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ktypeid] VARCHAR(50) NOT NULL DEFAULT(''),
		[Serial] VARCHAR(MAX) DEFAULT (''),
		NPrice NUMERIC(22,10) DEFAULT(0),
		NTotal NUMERIC(22,10) DEFAULT(0),
		FromBillNumberID	INT NULL,
		FromBillType	INT NULL,
		FromBillID	INT NULL
		,ShowOrder INT DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AdPriceBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.AdPriceBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AdPriceBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.AdPriceBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AdPriceBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.AdPriceBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.AdPriceBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE AdPriceBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE AdPriceBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='BeforePrice'
)
BEGIN
		ALTER TABLE AdPriceBill ADD BeforePrice NUMERIC(18,4) DEFAULT(0)
		
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='ChangeTotal'
)
BEGIN
		ALTER TABLE AdPriceBill ADD ChangeTotal NUMERIC(24,10) DEFAULT(0)
		
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='BeforeTotal'
)
BEGIN
		ALTER TABLE AdPriceBill ADD BeforeTotal NUMERIC(18,4) DEFAULT(0)
		
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='Rate'
)
BEGIN
		ALTER TABLE AdPriceBill ADD Rate NUMERIC(18,4) DEFAULT(0)
		
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE AdPriceBill ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE AdPriceBill ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE AdPriceBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE AdPriceBill ADD IsCombined   INT
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='cargoID'
)
BEGIN
		ALTER TABLE AdPriceBill ADD cargoID   INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='Type'
)
BEGIN
		ALTER TABLE AdPriceBill ADD Type   INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='ktypeid'
)
BEGIN
		ALTER TABLE AdPriceBill ADD [ktypeid] VARCHAR(50) NOT NULL DEFAULT('')
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='Serial'
)
BEGIN
		ALTER TABLE AdPriceBill ADD Serial varchar(MAX) DEFAULT('')
		
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='NPrice'
)
BEGIN
		ALTER TABLE AdPriceBill ADD NPrice NUMERIC(22,10) DEFAULT(0),NTotal NUMERIC(22,10) DEFAULT(0)
		
		EXEC('
		UPDATE AdpriceBill
		SET NPrice=Price,NTotal=Total
		')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='FromBillNumberID'
)
BEGIN
		ALTER TABLE AdPriceBill ADD FromBillNumberID	INT NULL,FromBillType	INT NULL
		
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='FromBillID'
)
BEGIN
		ALTER TABLE AdPriceBill ADD FromBillID	INT NULL
		
END

GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'NBeforePrice'  UNION ALL SELECT 'NBeforeTotal';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='SaleBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADPRICEBILL') AND name = 'CIX_ADPRICEBILL_BillNumberID')
--DROP INDEX CIX_ADPRICEBILL_BillNumberID ON ADPRICEBILL 
CREATE CLUSTERED INDEX CIX_ADPRICEBILL_BillNumberID ON ADPRICEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADPRICEBILL') AND name = 'NCIX_ADPRICEBILL_Ptypeid')
--DROP INDEX NCIX_ADPRICEBILL_Ptypeid ON ADPRICEBILL 
CREATE NONCLUSTERED INDEX NCIX_ADPRICEBILL_Ptypeid ON ADPRICEBILL(Ptypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADPRICEBILL') AND name = 'NCIX_ADPRICEBILL_Price')
DROP INDEX NCIX_ADPRICEBILL_Price ON ADPRICEBILL 
                                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_ADPRICEBILL_Price ON ADPRICEBILL(Price) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='BeforePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN BeforePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='BeforeTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN BeforeTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='NPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN NPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AdPriceBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AdPriceBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Advantage]    脚本日期: 05/05/2010 14:46:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Advantage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Advantage](
		[BillNumberId] [numeric](18, 0) NOT NULL,
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Advantage_Serial]  DEFAULT (''),
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[StartDate] [datetime] NOT NULL,
		[EndDate] [datetime] NOT NULL,
		[StandardCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Type] [int] NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL CONSTRAINT [DF_Advantage_Qty]  DEFAULT (0),
		[Total] [numeric](18, 4) NOT NULL CONSTRAINT [DF_Advantage_Total]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[BillType] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  null,
	    GoodsNumber			 VARCHAR(100)	DEFAULT(''),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Advantage',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.Advantage
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Advantage',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.Advantage
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


if exists (select * from syscolumns where id = object_id(N'[dbo].[Advantage]') and  name = 'StandardCode' and length=25)
BEGIN
     ALTER TABLE Advantage
	    ALTER COLUMN StandardCode varchar(50) 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE Advantage ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE Advantage SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE Advantage ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE Advantage ADD IsCombined   INT
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE Advantage ADD GoodsNumber   VARCHAR(100) DEFAULT('')
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADVANTAGE') AND name = 'CIX_ADVANTAGE_BillNumberID')
--DROP INDEX CIX_ADVANTAGE_BillNumberID ON ADVANTAGE 
CREATE CLUSTERED INDEX CIX_ADVANTAGE_BillNumberID ON ADVANTAGE(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADVANTAGE') AND name = 'NCIX_ADVANTAGE_Ptypeid')
--DROP INDEX NCIX_ADVANTAGE_Ptypeid ON ADVANTAGE 
CREATE NONCLUSTERED INDEX NCIX_ADVANTAGE_Ptypeid ON ADVANTAGE(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADVANTAGE') AND name = 'NCIX_ADVANTAGE_StandardCode')
--DROP INDEX NCIX_ADVANTAGE_StandardCode ON ADVANTAGE 
CREATE NONCLUSTERED INDEX NCIX_ADVANTAGE_StandardCode ON ADVANTAGE(StandardCode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ADVANTAGE') AND name = 'NCIX_ADVANTAGE_Billtype')
--DROP INDEX NCIX_ADVANTAGE_Billtype ON ADVANTAGE 
CREATE NONCLUSTERED INDEX NCIX_ADVANTAGE_Billtype ON ADVANTAGE(Billtype) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Advantage 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Advantage 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Advantage_standard]    脚本日期: 05/05/2010 14:46:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Advantage_standard]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Advantage_standard](
		[StandardCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[StandardName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Type] [int] NOT NULL,
		[Dates] [int] NOT NULL,
		[LowQty] [numeric](18, 4) NOT NULL,
		[HighQty] [numeric](18, 4) NOT NULL,
		[Advantage_Total] [numeric](18, 4) NOT NULL,
		[explain] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Advantage_standard_explain]  DEFAULT (''),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage_standard' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE Advantage_standard ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE Advantage_standard SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage_standard' AND a.Name='LowQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Advantage_standard 
	ALTER COLUMN LowQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage_standard' AND a.Name='HighQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Advantage_standard 
	ALTER COLUMN HighQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Advantage_standard' AND a.Name='Advantage_Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Advantage_standard 
	ALTER COLUMN Advantage_Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AppendProcess]    脚本日期: 05/05/2010 14:46:32 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AppendProcess]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AppendProcess](
		[TypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[OPTable] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
		[Mode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[OPDate] [datetime] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[AppraisalBackBill]') AND type in (N'U'))
BEGIN

	CREATE TABLE [dbo].[AppraisalBackBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](18, 4) NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[discount] [numeric](18, 4) NULL,
		[DiscountPrice] [numeric](18, 4) NULL,
		[costprice] [numeric](18, 4) NULL,
		[total] [numeric](18, 4) NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [varchar](max) NULL,
		[OldID] numeric(10,0) NULL,
		[OldBillNumberID] numeric(10,0) NULL,
		[InputCostPrice] [numeric](18, 4) NULL,
		[GoodsOrder] [int] NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](18, 4) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](18, 4) NULL,
		[Tax] [numeric](5, 2) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney] [numeric](22, 10) NULL,
		[NSalePrice] [numeric](22, 10) NULL,
		[NSaleTotal] [numeric](22, 10) NULL,
		[NDiscountPrice] [numeric](22, 10) NULL,
		[NTotal] [numeric](22, 10) NULL,
		[NTaxPrice] [numeric](22, 10) NULL,
		[NTaxTotal] [numeric](22, 10) NULL,
		[NTaxMoney] [numeric](22, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](22, 10) NULL,
		[UnitRate] [numeric](22, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](22, 10) NULL,
		[MUnitRate] [numeric](22, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](22, 10) NULL,
		[MDiscountPrice] [numeric](22, 10) NULL,
		[MTaxPrice] [numeric](22, 10) NULL,
		[CurMSalePrice] [numeric](22, 10) NULL,
		[CurMDiscountPrice] [numeric](22, 10) NULL,
		[CurMTaxPrice] [numeric](22, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[InvoiceQty] [numeric](18, 4) NULL,
		[InvoiceMoney] [numeric](22, 10) NULL,
		[NInvoiceMoney] [numeric](22, 10) NULL,
		[IsGift] [int] NULL,
		[PriceStyle] [int] NOT NULL,
		[InvoiceCostTotal] [numeric](22,10) NULL,
		[InvoiceMoneyEX] NUMERIC(22,10) NULL,
		[NInvoiceMoneyEX] NUMERIC(22,10) NULL,
		[InvoiceNQty] [numeric](18, 4) NULL,
		[CostTotal]  [numeric](22, 10) NULL,
		[InvoiceSaleMoney] [numeric](22,10) NULL,
		[NInvoiceSaleMoney] [numeric](22,10) NULL,
		ShowOrder INT DEFAULT(0)
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0), --拣货数量
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		PriceSource VARCHAR(200)
	) ON [PRIMARY]

	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_Qty]  DEFAULT ((0)) FOR [Qty]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_SalePrice]  DEFAULT ((0)) FOR [SalePrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_discount]  DEFAULT ((1)) FOR [discount]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_DiscountPrice]  DEFAULT ((0)) FOR [DiscountPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_costprice]  DEFAULT ((0)) FOR [costprice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_total]  DEFAULT ((0)) FOR [total]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_TaxPrice]  DEFAULT ((0)) FOR [TaxPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_TaxTotal]  DEFAULT ((0)) FOR [TaxTotal]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_comment]  DEFAULT ('') FOR [comment]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_Serial]  DEFAULT ('') FOR [Serial]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_OldID]  DEFAULT ('') FOR [OldID]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_OldBillNumberID]  DEFAULT ((0)) FOR [OldBillNumberID]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_InputCostPrice]  DEFAULT ((0)) FOR [InputCostPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_odsOrder]  DEFAULT ('-1') FOR [GoodsOrder]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_odsNumber]  DEFAULT ('') FOR [GoodsNumber]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_ProduceDate]  DEFAULT ('') FOR [ProduceDate]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_ValidDate]  DEFAULT ('') FOR [ValidDate]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_odsCostPrice]  DEFAULT ((0)) FOR [GoodsCostPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_HandZeroCost]  DEFAULT ((0)) FOR [HandZeroCost]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_SaleTotal]  DEFAULT ((0)) FOR [SaleTotal]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  CONSTRAINT [DF_AppraisalBackBill_Tax]  DEFAULT ((0)) FOR [Tax]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ('') FOR [Stypeid]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [TaxMoney]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NSalePrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NSaleTotal]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NDiscountPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NTotal]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NTaxPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NTaxTotal]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NTaxMoney]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [UnitID]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NUnitID]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NQty]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [UnitRate]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [MUnitID]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [MQty]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((1)) FOR [MUnitRate]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [MSalePrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [MDiscountPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [MTaxPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [CurMSalePrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [CurMDiscountPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [CurMTaxPrice]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [CargoID]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [InvoiceQty]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [InvoiceMoney]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NInvoiceMoney]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [IsGift]


	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [PriceStyle]

	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [InvoiceCostTotal]
	
	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [InvoiceMoneyEX]
	
	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NInvoiceMoneyEX]
	
	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [InvoiceNQty]
	
	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [InvoiceSaleMoney]
	
	ALTER TABLE [dbo].[AppraisalBackBill] ADD  DEFAULT ((0)) FOR [NInvoiceSaleMoney]
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE AppraisalBackBill ADD PriceSource   VARCHAR(200)
END
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AppraisalBackBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.AppraisalBackBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AppraisalBackBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.AppraisalBackBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AppraisalBackBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE AppraisalBackBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE AppraisalBackBill SET PickedQty=0 WHERE PickedQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AppraisalBackBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.AppraisalBackBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.AppraisalBackBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='ShareFee'
)
BEGIN
		ALTER TABLE AppraisalBackBill ADD [ShareFee] [numeric](22, 10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE AppraisalBackBill ADD [SendedQty] DECIMAL(24, 10) NULL DEFAULT(0)
END
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'AppraisalBackBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.AppraisalBackBill
	ADD ShowOrder INT  DEFAULT(0)
END
GO
	UPDATE dbo.AppraisalBackBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='InvoiceCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN InvoiceCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='InvoiceMoneyEX' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN InvoiceMoneyEX NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NInvoiceMoneyEX' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NInvoiceMoneyEX NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='InvoiceNQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN InvoiceNQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='InvoiceSaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN InvoiceSaleMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='NInvoiceSaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN NInvoiceSaleMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBackBill 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
 
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBackBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE AppraisalBackBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                         
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[AppraisalBill]') AND type in (N'U'))
BEGIN

	CREATE TABLE [dbo].[AppraisalBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](18, 4) NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[discount] [numeric](18, 4) NULL,
		[DiscountPrice] [numeric](18, 4) NULL,
		[total] [numeric](18, 4) NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo1] [int] NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[orderid] [int] NOT NULL,
		[Serial] [varchar](max) NULL,
		[InputCostPrice] [numeric](18, 4) NULL,
		[GoodsOrder] [int] NULL,
		[BackQty] [numeric](18, 4) NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](18, 4) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](18, 4) NULL,
		[Tax] [numeric](5, 2) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney] [numeric](22, 10) NULL,
		[NSalePrice] [numeric](22, 10) NULL,
		[NSaleTotal] [numeric](22, 10) NULL,
		[NDiscountPrice] [numeric](22, 10) NULL,
		[NTotal] [numeric](22, 10) NULL,
		[NTaxPrice] [numeric](22, 10) NULL,
		[NTaxTotal] [numeric](22, 10) NULL,
		[NTaxMoney] [numeric](22, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](22, 10) NULL,
		[UnitRate] [numeric](22, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](22, 10) NULL,
		[MUnitRate] [numeric](22, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](22, 10) NULL,
		[MDiscountPrice] [numeric](22, 10) NULL,
		[MTaxPrice] [numeric](22, 10) NULL,
		[CurMSalePrice] [numeric](22, 10) NULL,
		[CurMDiscountPrice] [numeric](22, 10) NULL,
		[CurMTaxPrice] [numeric](22, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[entryCode] [varchar](200) NULL,
		[InvoiceQty] [numeric](18, 4) NULL,
		[InvoiceMoney] [numeric](22, 10) NULL,
		[NInvoiceMoney] [numeric](22, 10) NULL,
		[IsGift] [int] NULL,
		[InvoiceMoneyEX] [numeric](22, 10) NULL,
		[NInvoiceMoneyEX] [numeric](22, 10) NULL,
		[InvoiceCostTotal] [numeric](22,10) NULL,
		[OldID]	numeric(10,0) NULL,
		[OldBillNumberID] numeric(10,0) NULL,
		[InvoiceNQty] [numeric](18, 4) NULL,
		[InvoiceSaleMoney] [numeric](22,10) NULL,
		[NInvoiceSaleMoney] [numeric](22,10) NULL,
		ShowOrder INT DEFAULT(0),
		InFlowQty NUMERIC(24,10), --入库数量
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		PriceSource VARCHAR(200)
	) ON [PRIMARY]
	
	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_SalePrice]  DEFAULT ((0)) FOR [SalePrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_discount]  DEFAULT ((1)) FOR [discount]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_DiscountPrice]  DEFAULT ((0)) FOR [DiscountPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_total]  DEFAULT ((0)) FOR [total]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_TaxPrice]  DEFAULT ((0)) FOR [TaxPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_TaxTotal]  DEFAULT ((0)) FOR [TaxTotal]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_orderid]  DEFAULT ('-1') FOR [orderid]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_Serial]  DEFAULT ('') FOR [Serial]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_InputCostPrice_1]  DEFAULT ((0)) FOR [InputCostPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_odsOrder]  DEFAULT ('-1') FOR [GoodsOrder]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_BackQty]  DEFAULT ((0)) FOR [BackQty]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_odsNumber]  DEFAULT ('') FOR [GoodsNumber]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_ProduceDate]  DEFAULT ('') FOR [ProduceDate]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_ValidDate]  DEFAULT ('') FOR [ValidDate]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_odsCostPrice]  DEFAULT ((0)) FOR [GoodsCostPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_HandZeroCost]  DEFAULT ((0)) FOR [HandZeroCost]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_SaleTotal]  DEFAULT ((0)) FOR [SaleTotal]

	ALTER TABLE [dbo].[AppraisalBill] ADD  CONSTRAINT [DF_AppraisalBill_Tax]  DEFAULT ((0)) FOR [Tax]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ('') FOR [Stypeid]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [TaxMoney]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NSalePrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NSaleTotal]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NDiscountPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NTotal]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NTaxPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NTaxTotal]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NTaxMoney]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [UnitID]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NUnitID]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NQty]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [UnitRate]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [MUnitID]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [MQty]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((1)) FOR [MUnitRate]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [MSalePrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [MDiscountPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [MTaxPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [CurMSalePrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [CurMDiscountPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [CurMTaxPrice]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [CargoID]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ('') FOR [entryCode]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [InvoiceQty]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [InvoiceMoney]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NInvoiceMoney]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [IsGift]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [InvoiceMoneyEX]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NInvoiceMoneyEX]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [InvoiceCostTotal]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [InvoiceNQty]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [InvoiceSaleMoney]

	ALTER TABLE [dbo].[AppraisalBill] ADD  DEFAULT ((0)) FOR [NInvoiceSaleMoney]
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE AppraisalBill ADD PriceSource   VARCHAR(200)
END
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AppraisalBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.AppraisalBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AppraisalBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.AppraisalBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AppraisalBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.AppraisalBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.AppraisalBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='ShareFee'
)
BEGIN
		ALTER TABLE AppraisalBill ADD [ShareFee] [numeric](22, 10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AppraisalBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.AppraisalBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.AppraisalBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'AppraisalBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.AppraisalBill
	ADD ShowOrder INT  DEFAULT(0)
END
GO
	UPDATE dbo.AppraisalBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='InvoiceMoneyEX' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN InvoiceMoneyEX NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NInvoiceMoneyEX' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NInvoiceMoneyEX NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='InvoiceCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN InvoiceCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='InvoiceNQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN InvoiceNQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='InvoiceSaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN InvoiceSaleMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='NInvoiceSaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN NInvoiceSaleMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AppraisalBill 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
    
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AppraisalBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE AppraisalBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--往来对账明细 -结算单位表头字段配置 
IF NOT EXISTS (SELECT  1  FROM  sysobjects WHERE  id = object_id('ArApExtendBtypeDetails_Config') AND   type = 'U')
	BEGIN
		CREATE TABLE ArApExtendBtypeDetails_Config (
			nId				INT IDENTITY(1,1),
			DataField		VARCHAR(200),--字段
			Comment		VARCHAR(200),--字段名称
			IsCheck			BIT,--是否选中
			PageName		VARCHAR(200),--页面
			OperatorId		VARCHAR(50)--操作员
		)
	END
GO   
------------------------------------------表修改区域开始-------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='ArApExtendBtypeDetails_Config' AND a.Name='XXX'
--)
--BEGIN
--	ALTER TABLE ArApExtendBtypeDetails_Config 
--		ADD XXX VARCHAR(400) NULL DEFAULT('')
--END

--GO

------------------------------------------表修改区域开始-------------------------------------------------



/****** 对象:  Table [dbo].[Area]    脚本日期: 05/05/2010 14:46:33 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Area]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Area](
		[typeid] [int] IDENTITY(1,1) NOT NULL,
		[usercode] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[Fullname] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Comment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Area_Comment]  DEFAULT (''),
		[deleted] [bit] NOT NULL CONSTRAINT [DF_Area_deleted]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS (select * from syscolumns where id = object_id(N'[dbo].[Area]') and  name = 'Comment' AND length = 1000)
BEGIN
     ALTER TABLE Area
	    ALTER COLUMN Comment varchar(1000) 
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Area)
BEGIN
	INSERT INTO Area(usercode,Fullname,Comment,deleted)VALUES('1','000X001','','0')
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Area WHERE Fullname = '000X002')
BEGIN
	INSERT INTO Area(usercode,Fullname,Comment,deleted)VALUES('2','000X002','','0')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Area WHERE Fullname = '000X003')
BEGIN
	INSERT INTO Area(usercode,Fullname,Comment,deleted)VALUES('3','000X003','','0')	
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AREATYPE]    脚本日期: 05/05/2010 14:46:34 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AreaType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AreaType](
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[parid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint] NOT NULL,
		[sonnum] [int] NOT NULL,
		[soncount] [int] NOT NULL,
		[FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[TEL] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMan] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[sysflag] [char](2) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_AREATYPE_sysflag]  DEFAULT ('1'),
		[deleted] [bit] NOT NULL CONSTRAINT [DF_AREATYPE_deleted]  DEFAULT (0),
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_AREATYPE_PyCode]  DEFAULT (''),
		[ifCanEdit] [bit] NULL CONSTRAINT [DF_AREATYPE_ifCanEdit]  DEFAULT (1),
		[ifCanClass] [bit] NULL CONSTRAINT [DF_AREATYPE_ifCanClass]  DEFAULT (1),
		[ifCanDel] [bit] NULL CONSTRAINT [DF_AREATYPE_ifCanDel]  DEFAULT (1),
		[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0)
	) ON [PRIMARY]

	-- 初始化地区
	Delete from AreaType
	INSERT INTO AreaType (typeid,parid,leveal,sonnum,soncount,usercode,fullname,Name,Comment,Tel,LinkMan,Deleted,sysflag)VALUES ('00000','root',0,0,0,'所有地区','所有地区','所有地区','系统保留','','',0,0)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
--提供XiWa交互功能，每次修改或者新增基本信息后，必须在原来的值上加1 谢吉康 2010-05-04
if not exists (select name from syscolumns where id = object_id(N'[dbo].[AreaType]') and name = 'XiWaMaxNumber' )
	BEGIN
		BEGIN TRANSACTION
		SET QUOTED_IDENTIFIER ON
		SET ARITHABORT ON
		SET NUMERIC_ROUNDABORT OFF
		SET CONCAT_NULL_YIELDS_NULL ON
		SET ANSI_NULLS ON
		SET ANSI_PADDING ON
		SET ANSI_WARNINGS ON
		COMMIT
		BEGIN TRANSACTION
		ALTER TABLE dbo.AreaType ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
		
		COMMIT
	END
GO
UPDATE AreaType SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL OR XiWaMaxNumber = 0
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  地区档案自定义字段
  张陈仁
  3023-04-10
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Areatype_CustomColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table Areatype_CustomColumns 
	(
	   ID                   bigint               identity(1,1),
	   typeid               varchar(100)         null,
	   Costom1              VARCHAR(600)         null,
	   Costom2              VARCHAR(600)         null,
	   Costom3              VARCHAR(600)         null,
	   Costom4              VARCHAR(600)         null,
	   Costom5              VARCHAR(600)         null,
	   Costom6              VARCHAR(600)         null,
	   Costom7              VARCHAR(600)         null,
	   Costom8              VARCHAR(600)         null,
	   Costom9              VARCHAR(600)         null,
	   Costom10             VARCHAR(600)         null,
	   Costom11             VARCHAR(600)         null,
	   Costom12             VARCHAR(600)         null,
	   Costom13             VARCHAR(600)         null,
	   Costom14             VARCHAR(600)         null,
	   Costom15             VARCHAR(600)         null,
	   Costom16             VARCHAR(600)         null,
	   Costom17             VARCHAR(600)         null,
	   Costom18             VARCHAR(600)         null,
	   Costom19             VARCHAR(600)         null,
	   Costom20             VARCHAR(600)         null
   )
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AskPriceBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[AskPriceBill] (
		[BillNumberID] [int] NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Qty] [numeric](18, 4) Default(0) NOT NULL ,
		[IsUnit2] [int] Default(0) NOT NULL ,
		[Price] [numeric](22, 8) Default(0) NOT NULL ,
		[SaleTotal] [numeric](18, 4) Default(0) NOT NULL ,
		[Discount] [numeric](18, 4) Default(1) NOT NULL ,
		[DiscountPrice] [numeric](22, 8) Default(0) NOT NULL ,
		[Total] [numeric](18, 4) Default(0) NOT NULL ,
		[Tax] [numeric](5, 2) Default(0) NOT NULL ,
		[TaxPrice] [numeric](22, 8) Default(0) NOT NULL ,
		[TaxTotal] [numeric](18, 4) Default(0) NOT NULL ,
		[Comment] [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL Default(''),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
	   TaxMoney             numeric(22,10)    NULL Default(0),
	   NSalePrice           numeric(22,10)      NULL Default(0),
	   NSaleTotal           numeric(22,10)      NULL Default(0),
	   NDiscountPrice       numeric(22,10)      NULL Default(0),
	   NTotal               numeric(22,10)      NULL Default(0),
	   NTaxPrice            numeric(22,10)      NULL Default(0),
	   NTaxTotal            numeric(22,10)      NULL Default(0),
	   NTaxMoney            numeric(22,10)      NULL Default(0),
	   UnitID               int                NULL Default(0),
	   NUnitID              int                NULL Default(0),
	   NQty                 numeric(22,10)     NULL Default(0),
	   UnitRate             numeric(22,10)     NULL Default(0),
	   NUnitMsg             varchar(50)        null,
	   MUnitID              int                NULL Default(0),
	   MQty                 numeric(22,10)     NULL Default(0),
	   MUnitRate            numeric(22,10)     NULL Default(1),
	   MUnitMsg             varchar(50)        null,
	   MSalePrice           numeric(22,10)     NULL Default(0),
	   MDiscountPrice       numeric(22,10)     NULL Default(0),
	   MTaxPrice            numeric(22,10)     NULL Default(0),
	   CurMSalePrice        numeric(22,10)     NULL Default(0),
	   CurMDiscountPrice    numeric(22,10)     NULL Default(0),
	   CurMTaxPrice         numeric(22,10)     NULL Default(0),
	   ItemID               bigint               null,
	   IsCombined           int                  NULL,
	   ShowOrder INT DEFAULT(0),
	   UseQty				NUMERIC(24,10) DEFAULT(0),		--已完成数量 参考至报价单
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[PriceSource] VARCHAR(200)
	) ON [PRIMARY]
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AskPriceBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.AskPriceBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AskPriceBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.AskPriceBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

--已完成数量 参考至报价单
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AskPriceBill',N'U') AND Name='UseQty')
BEGIN
	ALTER TABLE dbo.AskPriceBill
	ADD UseQty NUMERIC(24,10) DEFAULT(0)
END
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'AskPriceBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.AskPriceBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.AskPriceBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE AskPriceBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE AskPriceBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE AskPriceBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE AskPriceBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE AskPriceBill ADD UnitID  INT  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NUnitID INT  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NQty   numeric(22,10)    NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE AskPriceBill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE AskPriceBill ADD NUnitMsg   varchar(50)  NULL  
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE AskPriceBill ADD MUnitID  INT  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE AskPriceBill ADD MQty   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE AskPriceBill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE AskPriceBill ADD MUnitMsg   varchar(50)  NULL  
END
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD MSalePrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD MDiscountPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD MTaxPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD CurMSalePrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD CurMDiscountPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE AskPriceBill ADD CurMTaxPrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE AskPriceBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE AskPriceBill ADD IsCombined   INT
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='askpricebill' AND a.Name='IfBargainOn' 
)
BEGIN
	ALTER TABLE askpricebill ADD IfBargainOn INT NOT NULL DEFAULT(0)           ---成交状态
END
GO
--UPDATE askpricebill SET IfBargainON=0 WHERE IfBargainON IS NULL

--GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CurRate';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='AskPriceBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ASKPRICEBILL') AND name = 'CIX_ASKPRICEBILL_BillNumberID')
--DROP INDEX CIX_ASKPRICEBILL_BillNumberID ON ASKPRICEBILL 
CREATE CLUSTERED INDEX CIX_ASKPRICEBILL_BillNumberID ON ASKPRICEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ASKPRICEBILL') AND name = 'NCIX_ASKPRICEBILL_Ptypeid')
--DROP INDEX NCIX_ASKPRICEBILL_Ptypeid ON ASKPRICEBILL 
CREATE NONCLUSTERED INDEX NCIX_ASKPRICEBILL_Ptypeid ON ASKPRICEBILL(Ptypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ASKPRICEBILL') AND name = 'NCIX_ASKPRICEBILL_Price')
DROP INDEX NCIX_ASKPRICEBILL_Price ON ASKPRICEBILL      
                               
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_ASKPRICEBILL_Price ON ASKPRICEBILL(Price) 
------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AskPriceBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AskPriceBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('AssetIncChangeBill') AND  type = 'U')
BEGIN
	CREATE TABLE  AssetIncChangeBill
	(
		Id				INT IDENTITY(1,1),	
		TypeId			VARCHAR(50) NULL,
		Parid			VARCHAR(50)	NULL,
		AcAsTypeid		VARCHAR(50) NULL,
		AcAsUserCode	VARCHAR(200)NULL,
		AcAsFullName	VARCHAR(200)	NULL,
		BillDate		DATETIME   NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_AssetIncChangeBill_BillCode]  DEFAULT (''),
		Stypeid			VARCHAR(50) NULL,
		ChangeReasonID	VARCHAR(50) NULL,
		ETypeId			VARCHAR(50) NULL,
		DTypeId			VARCHAR(50) NULL,
		CID				INT NULL,
		Rate			NUMERIC(24,10) NULL,
		BusinessTypeId	INT NULL,		
		BtypeId			VARCHAR(50) NULL,
		OldF_Total			NUMERIC(24,10)	NULL,
		OldTotal			NUMERIC(24,10) NULL,
		OldNetValue		NUMERIC(24,10)	NULL,
		OldRate			NUMERIC(24,10) NULL,
		OldDepTotal		NUMERIC(24,10) NULL,
		OldDevalueReady	NUMERIC(24,10) NULL,
		OldNetSalvage	NUMERIC(24,10) NULL,
		F_Total			NUMERIC(24,10)	NULL,
		Total			NUMERIC(24,10) NULL,
		DepTotal		NUMERIC(24,10) NULL,
		NetValue		NUMERIC(24,10)	NULL,
		F_TotalDif			NUMERIC(24,10)	NULL,
		TotalDif			NUMERIC(24,10) NULL,
		DepTotalDif		NUMERIC(24,10) NULL,
		NetValueDif		NUMERIC(24,10)	NULL,
		XiWaMaxNumber		NUMERIC(18, 0) NULL DEFAULT (0),
		Draft INT NULL,
		[DELETE] INT  null,
		AssetsState int null
	)
END

------------------------------------------表修改区域结束-------------------------------------------------
IF not EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncChangeBill' AND a.Name='Draft' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncChangeBill ADD Draft INT NULL
    END
    
 IF not EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncChangeBill' AND a.Name='DELETE' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncChangeBill ADD [DELETE] INT null
    END 
    
    IF not EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncChangeBill' AND a.Name='AssetsState' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncChangeBill ADD AssetsState INT null
    END  
GO
------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AssetIncChangeBill') AND name = 'CIX_AssetIncChangeBill_BillNumberID')
--CREATE CLUSTERED INDEX CIX_AssetIncChangeBill_BillNumberID ON AssetIncChangeBill(AcAsTypeid)  
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

------------------------------------------修改字段小数位数区域结束-----------------------------------------------








GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[AssetIncDecBill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [AssetIncDecBill](
	Id INT PRIMARY KEY IDENTITY(1,1)
	,BillNumberId INT NOT NULL
	,AssetCardId INT NOT NULL DEFAULT(0)
	,BillType INT NOT NULL DEFAULT(0)
	,NTotal NUMERIC(22,10) 
	,Total NUMERIC(22,10)
	,Tax NUMERIC(18,4)
	,NTaxMoney NUMERIC(22,10)
	,TaxMoney NUMERIC(22,10)
	,NTaxTotal NUMERIC(22,10)
	,TaxTotal NUMERIC(22,10)
	,NDepTotal NUMERIC(22,10)
	,DepTotal NUMERIC(22,10)
	,NNetValue NUMERIC(22,10)
	,NetValue NUMERIC(22,10)
	,Comment VARCHAR(255),
	[DraftFlag] [bit] NOT NULL DEFAULT (1),
	[IsIniFlag] [bit] NOT NULL DEFAULT (0)
)
END

GO
------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AssetIncDecBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.AssetIncDecBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'AssetIncDecBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.AssetIncDecBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='NTotal' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN NTotal NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='Total' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN Total NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='NTaxMoney' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN NTaxMoney NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='TaxMoney' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN TaxMoney NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='NTaxTotal' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN NTaxTotal NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='TaxTotal' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN TaxTotal NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='NDepTotal' AND system_type_id=108 AND([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN NDepTotal NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='DepTotal' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN DepTotal NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='NNetValue' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN NNetValue NUMERIC(22,10) 
go
IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('AssetIncDecBill') AND name='NetValue' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE AssetIncDecBill ALTER COLUMN NetValue NUMERIC(22,10) 
go
------------------------------------------表修改区域结束-----------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='NDepTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN NDepTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='DepTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN DepTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='NNetValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN NNetValue NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AssetIncDecBill' AND a.Name='NetValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AssetIncDecBill 
	ALTER COLUMN NetValue NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('AssetIncSplit') AND  type = 'U')
BEGIN
	CREATE TABLE [dbo].[AssetIncSplit](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[checker] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_AssetIncSplit_BillCode]  DEFAULT (''),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_AssetIncSplit_etypeid]  DEFAULT ('0'),
		[DTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_AssetIncSplit_DTypeId]  DEFAULT ('0'),
		[Qty] [numeric](24, 10) NULL CONSTRAINT [DF_AssetIncSplit_Qty]  DEFAULT (0),
		[SplitType] [numeric](4, 0) NOT NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[SplitRule] [numeric](4, 0) NOT NULL,--拆分规则0:平均拆分,1:比例拆分
		[draft] [bit] NOT NULL CONSTRAINT [DF_AssetIncSplit_draft]  DEFAULT (0),
		[OldCardId]		VARCHAR(50) NULL,
		[NewCardIds]	VARCHAR(max) NULL
		
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END
GO



/****** 对象:  Table [dbo].[atype]    脚本日期: 05/05/2010 14:46:35 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[atype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[atype](
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[parid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint] NOT NULL,
		[sonnum] [int] NOT NULL,
		[soncount] [int] NOT NULL,
		[FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_atype_Name]  DEFAULT (''),
		[UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_atype_UserCode]  DEFAULT (''),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_atype_Comment]  DEFAULT (''),
		[Total] [numeric](18, 4) NOT NULL CONSTRAINT [DF_atype_Total]  DEFAULT (0),
		[Total00] [numeric](18, 4) NOT NULL CONSTRAINT [DF_atype_Total00]  DEFAULT (0),
		[sysflag] [char](2) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_atype_sysflag]  DEFAULT (0),
		[sysrow] [bit] NOT NULL CONSTRAINT [DF_atype_sysfield]  DEFAULT (0),
		[deleted] [bit] NOT NULL CONSTRAINT [DF_atype_deleted]  DEFAULT (0),
		[j_d] [bit] NULL CONSTRAINT [DF_atype_j_d]  DEFAULT (0),
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[ifCanEdit] [bit] NULL CONSTRAINT [DF_atype_ifCanEdit]  DEFAULT (1),
		[ifCanClass] [bit] NULL CONSTRAINT [DF_atype_ifCanClass]  DEFAULT (1),
		[ifCanDel] [bit] NULL CONSTRAINT [DF_atype_ifCanDel]  DEFAULT (1),
		[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0)
	) ON [PRIMARY]

	-- ********	处理 AType	********
	DELETE FROM  AType
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('00000','root',0,5,5,'root','','','0',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('00001','00000',1,10,10,'【资产合计】','资产合计','90','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100001','00001',2,0,0,'『库存商品总值合计』','库存商品','1241','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100002','00001',2,1,1,'『固定资产合计』','固定资产','1501','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000010000200001','0000100002',3,0,0,'固定资产__甲','固资__甲','0121','',0,0,'0',0,0,1,1,1)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100003','00001',2,0,0,'现    金','现    金','1001','',0,0,'1',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100004','00001',2,1,1,'『全部银行存款合计』','','87','',0,0,'1',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000010000400001','0000100004',3,0,0,'中国银行','','5288','开户名：填写开户名称',0,0,'1',0,0,1,1,1)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100005','00001',2,0,0,'『应收款合计』','应收账款','987','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100007','00001',2,0,0,'『待摊费用』','待摊费用','1301','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100008','00001',2,0,0,'『委托代销商品』','委托代销','1261','',0,0,'0',1,0,0,0,0)
	
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100009','00001',2,0,0,'『预付账款』','预付账款','1151','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100010','00001',2,0,0,'『内部应收』','内部应收','1132','',0,0,'0',1,0,0,0,0)
	
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('00002','00000',1,6,6,'【负债合计】','负债合计','02','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000200001','00002',2,0,0,'『应付账款合计』','应付账款','2121','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000200003','00002',2,0,0,'『代销商品款』','代销款','2141','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000200004','00002',2,0,0,'『应交税金』','应交税金','2171','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel)VALUES('0000200005','00002',2,0,0,'『会员储值』','会员储值','2181','',0,0,'0',1,0,0,0,0)
	
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000200006','00002',2,0,0,'『预收账款』','预收账款','2131','',0,0,'0',1,0,0,0,0)
	--INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000200007','00002',2,0,0,'『优惠券』','优惠券','2191','',0,0,'0',1,0,0,0,0)
	
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('00003','00000',1,3,4,'【收入类】','收入类','03','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000300001','00003',2,0,0,'『销售收入』','销售收入','5101','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000300002','00003',2,9,9,'『商品类收入』','商品收入','032','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000200001','0000300002',3,0,0,'商品报溢收入','商品报溢','0321','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000200002','0000300002',3,0,0,'商品获赠收入','商品获赠','0322','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000200003','0000300002',3,0,0,'成本调价收入','调价收入','0323','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000200004','0000300002',3,0,0,'采购退货差价','结算差价','0324','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000200005','0000300002',3,0,0,'变价调拨差价','调拨差价','0325','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000200006','0000300002',3,0,0,'商品拆装差价','拆装差价','0326','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000200007','0000300002',3,0,0,'借转采购结算与成本差','其他收入','0327','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000300003','00003',2,3,3,'『其他收入』','其他收入','5102','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000300001','0000300003',3,0,0,'调账收入','调账收入','03333','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000300002','0000300003',3,0,0,'利息收入','利息收入','0332','',0,0,'0',0,0,1,1,1)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000300003','0000300003',3,0,0,'其他.....','其他.....','0333','其他.....',0,0,'0',0,0,1,1,1)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('00004','00000',1,4,4,'【支出类】','支出类','04','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000400001','00004',2,0,0,'『销售成本』','销售成本','5401','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000400002','00004',2,4,4,'『商品类支出』','商品支出','042','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000040000200001','0000400002',3,0,0,'商品报损','商品报损','0421','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000040000200002','0000400002',3,0,0,'商品赠出','商品赠出','0422','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000400003','00004',2,4,4,'『费用合计』','费用合计','043','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000040000300001','0000400003',3,0,0,'调账亏损','调账亏损','0431','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000040000300002','0000400003',3,0,0,'固定资产折旧','资产折旧','0432','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000040000300003','0000400003',3,0,0,'其他....','其他....','0455','',0,0,'0',0,0,1,1,1)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000040000300004','0000400003',3,0,0,'优惠金额','优惠金额', '0456','0', 0, 0, '0', 1, 0,0,0,0) 
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('00005','00000',1,5,5,'【所有者权益】','权益类','05','',0,0,'0',1,0,0,1,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000500001','00005',2,0,0,'『实收资本』','实收资本','3101','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000500002','00005',2,0,0,'『资本公积』','资本公积','3111','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000500003','00005',2,0,0,'『盈余公积』','盈余公积','3121','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000500004','00005',2,0,0,'『本年利润』','本年利润','3131','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000500005','00005',2,0,0,'『利润分配』','利润分配','3141','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000400004','00004',2,0,0,'销售折扣返利支出','销售折扣返利支出','0404','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES ('000030000200008', '0000300002', 3, 0, 0, '商品维修收入', '维修收入', '0328','0', 0, 0, '0', 1, 0,0,0,0) 
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000030000200009','0000300002',3,0,0,'受托退货差价','受托退货差价','0329','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,ParID,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,SysFlag,SysRow,Deleted,j_d,ifCanEdit,ifCanClass,ifCanDel) VALUES ('0000300004','00003','2',0,0,'返点获利收入','返点获利收入','5103','',0,0,'0',1,0,0,0,0,0)
	
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000040000200003','0000400002',3,0,0,'商品维修支出','商品维修支出','0423','',0,0,'0',1,0,0,0,0)
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('000040000200004','0000400002',3,0,0,'商品送修支出','商品送修支出','0424','',0,0,'0',1,0,0,0,0)
	UPDATE AType SET Total = 0, Total00 = 0
	UPDATE Atype set ifCanEdit=1,ifCanClass=1,ifCanDel =1 where TypeID in ('000030000300002','000030000300003','000040000300003','000010000200001')
END
GO

------------------------------------------表修改区域开始【特殊处理从500开始】-------------------------------------------------
IF NOT EXISTS(SELECT TypeID FROM AType WHERE typeId='0000100009')
BEGIN
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100009','00001',2,0,0,'『预付账款』','预付账款','1151','',0,0,'1',1,0,0,0,0)	
	
	UPDATE AType SET soncount=soncount+1,sonnum=sonnum+1 WHERE typeId='00001'
END
GO

IF NOT EXISTS(SELECT TypeID FROM AType WHERE typeId='0000100010')
BEGIN
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100010','00001',2,0,0,'『内部应收』','内部应收','1132','',0,0,'1',1,0,0,0,0)
	
	UPDATE AType SET soncount=soncount+1,sonnum=sonnum+1 WHERE typeId='00001'
END
GO

IF NOT EXISTS(SELECT TypeID FROM AType WHERE typeId='0000100011')
BEGIN
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000100011','00001',2,0,0,'『其他应收款』','其他应收款','1133','',0,0,'1',1,0,0,0,0)
	
	UPDATE AType SET soncount=soncount+1,sonnum=sonnum+1 WHERE typeId='00001'
END
GO

IF NOT EXISTS(SELECT TypeID FROM AType WHERE typeId='0000200006')
BEGIN
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000200006','00002',2,0,0,'『预收账款』','预收账款','2131','',0,0,'1',1,0,0,0,0)
	
	UPDATE AType SET soncount=soncount+1,sonnum=sonnum+1 WHERE typeId='00002'	
END
GO

IF NOT EXISTS(SELECT TypeID FROM AType WHERE typeId='0000200007')
BEGIN
	INSERT INTO  AType(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Total,Total00,sysflag,sysrow,Deleted,ifCanEdit,ifCanClass,ifCanDel) VALUES('0000200007','00002',2,0,0,'『其他应付款』','其他应付款','2132','',0,0,'1',1,0,0,0,0)
	
	UPDATE AType SET soncount=soncount+1,sonnum=sonnum+1 WHERE typeId='00002'
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[atype]') AND name = N'atypeidx')
--DROP INDEX [dbo].[atype].[atypeidx]
CREATE UNIQUE CLUSTERED INDEX [atypeidx] ON [dbo].[atype] 
(
	[typeId] ASC
) ON [PRIMARY]


------------------------------------------创建索引区域结束-----------------------------------------------
--提供XiWa交互功能，每次修改或者新增基本信息后，必须在原来的值上加1 谢吉康 2010-05-04
if not exists (select name from syscolumns where id = object_id(N'[dbo].[AType]') and name = 'XiWaMaxNumber' )
	BEGIN
		BEGIN TRANSACTION
		SET QUOTED_IDENTIFIER ON
		SET ARITHABORT ON
		SET NUMERIC_ROUNDABORT OFF
		SET CONCAT_NULL_YIELDS_NULL ON
		SET ANSI_NULLS ON
		SET ANSI_PADDING ON
		SET ANSI_WARNINGS ON
		COMMIT
		BEGIN TRANSACTION
		ALTER TABLE dbo.AType ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
		
		COMMIT
	END
GO
UPDATE AType SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL OR XiWaMaxNumber = 0

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='atype' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE atype 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='atype' AND a.Name='Total00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE atype 
	ALTER COLUMN Total00 NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[atype_l]    脚本日期: 05/05/2010 14:46:36 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[atype_l]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[atype_l](
		[etypeid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[typeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[flag] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[type] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

-- Add by 李海洋 
-- Date: 2012-09-09
-- Description: 增加: 删除多级权限的多余列
------------------------------------------表修改区域开始-------------------------------------------------
-- 修改权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = OBJECT_ID(N'[dbo].[atype_l]') 
		AND name = 'modifyflag'
)
BEGIN
		ALTER TABLE dbo.atype_l DROP COLUMN  modifyflag ;
END
GO

-- 分类权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = OBJECT_ID(N'[dbo].[atype_l]') 
		AND name = 'assortflag'
)
BEGIN
  ALTER TABLE dbo.atype_l DROP COLUMN  assortflag ;
END
GO

-- 停用权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = OBJECT_ID(N'[dbo].[atype_l]') 
		AND name = 'disableflag'
)
BEGIN
  ALTER TABLE dbo.atype_l DROP COLUMN disableflag ;
END
GO

-- 删除权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = OBJECT_ID(N'[dbo].[atype_l]') 
		AND name = 'delflag'
)
BEGIN
		ALTER TABLE dbo.atype_l DROP COLUMN  delflag ;
END  
GO

------------------------------------------表修改区域结束-------------------------------------------------




------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[atype_l]') AND name = N'IX_atype_l')
--BEGIN
	--DROP INDEX IX_atype_l ON atype_l
--END
CREATE CLUSTERED INDEX IX_atype_l ON atype_L(ETypeID)
------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[AType_Total]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[AType_Total](
		[ATypeID] [varchar] (50) NOT NULL,
		[STypeID] [varchar] (50) NULL,
		[Total00] numeric(22,10) NULL DEFAULT 0,
		[Total] numeric(22,10) NULL DEFAULT 0,
		[CID]	INT  DEFAULT(0),
		[Ntotal00]	NUMERIC(22,10)  DEFAULT(0),
		[Ntotal]	NUMERIC(22,10)  DEFAULT(0)
		
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AType_Total' AND a.Name='CID'
)
BEGIN
		ALTER TABLE AType_Total ADD CID INT DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AType_Total' AND a.Name='Ntotal'
)
BEGIN
		ALTER TABLE AType_Total ADD Ntotal NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AType_Total' AND a.Name='Ntotal00'
)
BEGIN
		ALTER TABLE AType_Total ADD Ntotal00 NUMERIC(22,10) DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AType_Total]') AND name = N'CIX_IX_ATYPEIDSTYPEID')
--	DROP INDEX [dbo].[AType_Total].[CIX_IX_ATYPEIDSTYPEID]
--GO
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AType_Total]') AND name = N'NCIX_IX_STYPEID')
--	DROP INDEX [dbo].[AType_Total].[NCIX_IX_STYPEID]
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ATYPE_TOTAL') AND name = 'CIX_ATYPE_TOTAL_Atypeid')
--DROP INDEX CIX_ATYPE_TOTAL_Atypeid ON ATYPE_TOTAL 
CREATE CLUSTERED INDEX CIX_ATYPE_TOTAL_Atypeid ON ATYPE_TOTAL(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ATYPE_TOTAL') AND name = 'NCIX_ATYPE_TOTAL_Stypeid')
--DROP INDEX NCIX_ATYPE_TOTAL_Stypeid ON ATYPE_TOTAL 
CREATE NONCLUSTERED INDEX NCIX_ATYPE_TOTAL_Stypeid ON ATYPE_TOTAL(Stypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AType_Total' AND a.Name='Total00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AType_Total 
	ALTER COLUMN Total00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AType_Total' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AType_Total 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AType_Total' AND a.Name='Ntotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AType_Total 
	ALTER COLUMN Ntotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AType_Total' AND a.Name='Ntotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE AType_Total 
	ALTER COLUMN Ntotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AuditingBill]    脚本日期: 05/05/2010 14:46:37 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AuditingBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AuditingBill](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[AuditingID] [int] NOT NULL,
		[AuditingSteps] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfAudit] [char](2) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BillDate] [datetime] NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[BillDetail] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[BillIndexType] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[PassSteps] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[StepReasons] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AuditingBill' AND a.Name='BillDetail' AND a.xtype=35
)
BEGIN
	ALTER TABLE AuditingBill ALTER COLUMN BillDetail VARCHAR(MAX)
END
GO

--增加制单人
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AuditingBill' AND a.Name='Checke'
)
BEGIN
	ALTER TABLE AuditingBill 
		ADD Checke VARCHAR(50) DEFAULT('')
END
GO
UPDATE AuditingBill SET Checke = '' WHERE Checke IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--部分发出去的数据库中存在这个索引
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AuditingBill]') AND name = N'IX_AuditingBill_BillDate')
	DROP INDEX [dbo].AuditingBill.IX_AuditingBill_BillDate

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AuditingBill]') AND name = N'CIX_BID')
--	DROP INDEX [dbo].AuditingBill.CIX_BID

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AuditingBill]') AND name = N'NCIX_IFAUDIT')
--	DROP INDEX [dbo].AuditingBill.NCIX_IFAUDIT
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AUDITINGBILL') AND name = 'CIX_AUDITINGBILL_BillNumberID')
--DROP INDEX CIX_AUDITINGBILL_BillNumberID ON AUDITINGBILL 
CREATE CLUSTERED INDEX CIX_AUDITINGBILL_BillNumberID ON AUDITINGBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AUDITINGBILL') AND name = 'NCIX_AUDITINGBILL_IfAudit')
--DROP INDEX NCIX_AUDITINGBILL_IfAudit ON AUDITINGBILL 
CREATE NONCLUSTERED INDEX NCIX_AUDITINGBILL_IfAudit ON AUDITINGBILL(IfAudit) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AUDITINGBILL') AND name = 'NCIX_AUDITINGBILL_BillIndexType') 
CREATE NONCLUSTERED INDEX NCIX_AUDITINGBILL_BillIndexType ON AUDITINGBILL(BillIndexType) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AuditingBillDetail]    脚本日期: 05/05/2010 14:46:37 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AuditingBillDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AuditingBillDetail](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[AuditingExplain] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[AuditingDate] [datetime] NOT NULL CONSTRAINT [DF_AudtingBillDetail_AuditingDate]  DEFAULT (getdate()),
		[AuditingFlag] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[AuditingStep] [int] NOT NULL,
		[BillIndexType] [char](1) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AuditingBillDetail') AND name = 'NCIX_AuditingBillDetail_BillNumberId')
CREATE NONCLUSTERED INDEX NCIX_AuditingBillDetail_BillNumberId ON AuditingBillDetail(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AuditingBillDetail') AND name = 'NCIX_AuditingBillDetail_BillIndexType')
CREATE NONCLUSTERED INDEX NCIX_AuditingBillDetail_BillIndexType ON AuditingBillDetail(BillIndexType) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AuditingFlowDetail]    脚本日期: 05/05/2010 14:46:38 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AuditingFlowDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AuditingFlowDetail](
		[AuditingID] [int] NOT NULL,
		[BillType] [int] NOT NULL,
		[AuditingDescription] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[AuditingStep] [int] NOT NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[AuditingAlerm] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_AuditingFlowDetail_AuditingAlerm]  DEFAULT (0),
		[OutKty] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Id] INT IDENTITY(1,1)
	) ON [PRIMARY]


END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AuditingFlowDetail' AND a.Name='Id'
)
BEGIN
	ALTER TABLE [AuditingFlowDetail] ADD Id INT IDENTITY(1,1)
END
go


------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------
------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[AuditingFlowDetail]') AND name = N'IX_AuditingFlowDetail')
DROP INDEX [IX_AuditingFlowDetail] ON [dbo].[AuditingFlowDetail] WITH ( ONLINE = OFF )

------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
CREATE NONCLUSTERED INDEX [IX_AuditingFlowDetail] ON [dbo].[AuditingFlowDetail] 
(
	[ETypeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('AuditingFlowDetail') AND name = 'NCIX_AuditingFlowDetail_AuditingID') 
CREATE NONCLUSTERED INDEX NCIX_AuditingFlowDetail_AuditingID ON AuditingFlowDetail(AuditingID) 
GO

/****** Object:  Index [NCIX_AuditingFlowDetail_UNION]    Script Date: 09/01/2017 18:24:21 ******/
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[AuditingFlowDetail]') AND name = N'NCIX_AuditingFlowDetail_UNION')

CREATE NONCLUSTERED INDEX [NCIX_AuditingFlowDetail_UNION] ON [dbo].[AuditingFlowDetail] 
(
	[AuditingID] ASC,
	[ETypeID] ASC,
	[AuditingStep] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


/****** Object:  Index [NCIX_AuditingFlowDetail_AuditingID]    Script Date: 09/01/2017 18:25:32 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[AuditingFlowDetail]') AND name = N'NCIX_AuditingFlowDetail_AuditingID')

/****** Object:  Index [NCIX_AuditingFlowDetail_AuditingID]    Script Date: 09/01/2017 18:25:49 ******/
CREATE NONCLUSTERED INDEX [NCIX_AuditingFlowDetail_AuditingID] ON [dbo].[AuditingFlowDetail] 
(
	[AuditingID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO



------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
------------------------------------------删除外键开始-----------------------------------------------
IF OBJECT_ID(N'[dbo].[FK_AuditingFlowDetail_AuditingFlowSet]', 'F') IS NOT NULL
    ALTER TABLE [dbo].[AuditingFlowDetail] DROP CONSTRAINT [FK_AuditingFlowDetail_AuditingFlowSet];
GO
------------------------------------------删除外键结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AuditingFlowNunciator]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.AuditingFlowNunciator
		(
		AuditingID          INT NOT NULL,
		BillType            INT NOT NULL,
		AuditingDescription VARCHAR (255) NULL,
		AuditingStep        INT NOT NULL,
		ETypeID             VARCHAR (50) NOT NULL,
		AuditingAlerm       CHAR (10) DEFAULT ((0)) NOT NULL,
		OutKty              CHAR (10) NOT NULL,
		Id                  INT IDENTITY NOT NULL
		)
END

GO






/****** 对象:  Table [dbo].[AuditingReason]    脚本日期: 05/05/2010 14:46:40 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AuditingReason]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AuditingReason](
		[AuditingID] [int] NOT NULL,
		[ReasonNo] [int] NOT NULL,
		[ReasonValue] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[AuditingStep] [int] NULL,
		[Id] INT IDENTITY(1,1)
	) ON [PRIMARY]


END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AuditingReason' AND a.Name='Id'
)
BEGIN
	ALTER TABLE AuditingReason ADD Id INT IDENTITY(1,1)
END
go

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------

------------------------------------------删除外键开始-----------------------------------------------
IF OBJECT_ID(N'[dbo].[FK_AuditingReason_AuditingFlowSet]', 'F') IS NOT NULL
    ALTER TABLE [dbo].[AuditingReason] DROP CONSTRAINT [FK_AuditingReason_AuditingFlowSet];
GO
------------------------------------------删除外键结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AuditingRelation]    脚本日期: 05/05/2010 14:46:41 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AuditingRelation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AuditingRelation](
		[OffSet] [int] NOT NULL,
		[KeyName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Relation] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[UnChecked] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Description] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[TabOrder] [int] NULL,
		[Id] INT IDENTITY(1,1)
	) ON [PRIMARY]
END
GO


------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from syscolumns where id = object_id(N'[dbo].[AuditingRelation]') and  name = 'UnChecked' AND length = 100)
BEGIN
     ALTER TABLE AuditingRelation
	    ALTER COLUMN UnChecked varchar(100) 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AuditingRelation' AND a.Name='Id'
)
BEGIN
	ALTER TABLE AuditingRelation ADD Id INT IDENTITY(1,1)
END
go

------------------------------------------表修改区域结束-------------------------------------------------
-- ==================================== 单据审核原因设置表
DELETE FROM AuditingRelation
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (1,'',NULL,'2,3,4,5,6,7,8,9,10,11,12,13,14,15','无需审核',10)  
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (2,'',NULL,'1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32','必须全部审核',20) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (3,'ARLimit','>','1,2','超过信用额度审核',30)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (4,'','>','1,2','超过信用期审核',40) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (5,'Total','>=','1,2,14','单据金额高于等于____元审核',50) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (6,'Total','<=','1,2','单据金额低于等于____元审核',60) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (7,'','>=','1,2','单据单价大于等于最近售价审核',70) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (8,'','<=','1,2','商品售价小于等于成本价均价审核',80) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (9,'Discount','>=','1,2','单据扣率大于等于____折审核',90) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (10,'Discount','<=','1,2','单据扣率小于等于____折审核',100) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (11,'','>=','1,2','单据成本大于等于____元审核',110)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (12,'','','1,2','有超期应收款审核',120)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (13,'','','1,2','低于____审核',130)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (14,'','','1,2,5','出、入库审核',150)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (15,'','>','1,2','高于____审核',160)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (16,'Discount','<=','1,2','商品扣率小于等于_____折审核',170) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (17,'Discount','<=','1,2','项目扣率小于等于_____折审核',180)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (18,'','<=','1,2','工时费小于等于工时成本审核',190)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (19,'Total','<','1,2','商品价格低于____元审核',60) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (20,'Total','><','1,2','单据金额从____到____元审核',60) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (21,'','<','1,2','比成本价低____%销售审核',210) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (22,'Total','><','1,2','毛利总额从____到____元审核',60) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (23,'','<','1,2','商品售价低于____审核',220) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (24,'','>=','1,2','收/付款金额高于等于____元审核',220) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (25,'Total','><','1,2','毛利率从____%到____%审核',60) 
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (26,'','>','1,2','抹零金额大于充值金额的__%进行审核',60)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (27,'','<','1,2','低于往来单位适用售价进行审核',60)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (28,'','=','1,2','发票类型等于____审核',230)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (29,'','>=','1,2','单据价税合计总额大于等于____审核',240)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (30,'','>','1,2','超过库存上限审核',250)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (31,'','>=','1,2','单据核销金额高于等于____元审核',260)
INSERT INTO AuditingRelation (OffSet,KeyName,Relation,UnChecked,Description,TabOrder)VALUES (32,'','<','1,2','超过库存下限审核',270)
GO

------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AuditingStepReason]    脚本日期: 05/05/2010 14:46:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'AuditingStepReason') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[AuditingStepReason](
		[AuditingID] [int] NOT NULL,
		[AuditingStep] [int] NOT NULL,
		[AuditingReason] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[OutKty] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Id] INT IDENTITY(1,1)
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='AuditingStepReason' AND a.Name='Id'
)
BEGIN
	ALTER TABLE AuditingStepReason ADD Id INT IDENTITY(1,1)
END
go

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AutoType]    脚本日期: 05/05/2010 14:48:55 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[AutoType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

	CREATE TABLE [dbo].[AutoType](
		[id] [int] IDENTITY(1,1) NOT NULL,
		[fullname] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[comment] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]

END
GO

------------------------------------------表修改区域开始-------------------------------------------------

ALTER TABLE [dbo].[AutoType] ALTER COLUMN [fullname] [varchar](200)  NOT NULL

GO

if not exists (select * from syscolumns where id = object_id(N'[dbo].[AutoType]') and name=N'PYCode')
alter table AutoType add PYCode varchar(100) null
go

--调整长度到200
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[AutoType]') and  name = 'PYCode' and Length=100)
BEGIN
	 ALTER TABLE AutoType
	    ALTER COLUMN PYCode VARCHAR(200) NULL
END
GO

------------------------------------------表修改区域结束-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/*
  作者：张陈仁
  时间：2011-09-15
  描述：电子秤接口配置表
*/

/****** Object:  Table [dbo].[BalanceFiles]    Script Date: 07/25/2011 09:50:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BalanceFiles]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BalanceFiles](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[FileName] [varchar](150) NULL,
		[CreateTime] [datetime] NULL,
		[FileSize] [varchar](50) NULL,
		[EtypeID] [varchar](200) NULL,
		[FileContent] [text] NULL,
	 CONSTRAINT [PK_BalanceFiles] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
	END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='ZwCode'
)
BEGIN
	ALTER TABLE BalanceFiles ADD ZwCode TEXT DEFAULT '' NULL	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='Status'
)
BEGIN
	ALTER TABLE BalanceFiles ADD [Status] INT DEFAULT 0 NULL	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='TempleName'
)
BEGIN
	ALTER TABLE BalanceFiles ADD TempleName VARCHAR(150) DEFAULT '' NULL	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='TempleEtypeID'
)
BEGIN
	ALTER TABLE BalanceFiles ADD TempleEtypeID VARCHAR(200) DEFAULT '' NULL	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='TempleTime'
)
BEGIN
	ALTER TABLE BalanceFiles ADD TempleTime DATETIME DEFAULT  NULL	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='CodeLength'
)
BEGIN
	ALTER TABLE BalanceFiles ADD CodeLength Text DEFAULT '' NULL	
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='Is100'
)
BEGIN
	ALTER TABLE BalanceFiles ADD Is100 INT DEFAULT 0 NULL	
END

GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='FileContent'
)
BEGIN
	ALTER TABLE BalanceFiles ALTER COLUMN FileContent VARCHAR(max) NULL	
END

GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BalanceFiles' AND a.Name='ZwCode' AND a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('BalanceFiles') AND name='ZwCode')
	IF @dfname IS NOT NULL
		EXEC ('alter table BalanceFiles drop constraint '+@dfname);
		
	ALTER TABLE BalanceFiles ALTER COLUMN ZwCode VARCHAR(MAX) NULL 
	ALTER TABLE BalanceFiles ADD CONSTRAINT DF_BalanceFiles_ZwCode DEFAULT('') FOR ZwCode
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------


SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  作者：张陈仁
  时间：3011-09-15
  描述：电子秤接口字符表
*/

/****** Object:  Table [dbo].[BalanceSelect]    Script Date: 09/15/2011 17:35:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BalanceSelect]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BalanceSelect](
		[code] [varchar](50) NULL,
		[name] [varchar](100) NULL
	) ON [PRIMARY]
END
GO
DELETE FROM BalanceSelect
INSERT INTO BalanceSelect(code,name) VALUES ('usercode','【编号】')
INSERT INTO BalanceSelect(code,name) VALUES ('fullname','【名称】')
INSERT INTO BalanceSelect(code,name) VALUES ('name','【简名】')
INSERT INTO BalanceSelect(code,name) VALUES ('id','【PLU序号】')
INSERT INTO BalanceSelect(code,name) VALUES ('prebuyprice1','【预设进价1】')
INSERT INTO BalanceSelect(code,name) VALUES ('prebuyprice2','【预设进价2】')
INSERT INTO BalanceSelect(code,name) VALUES ('prebuyprice3','【预设进价3】')
INSERT INTO BalanceSelect(code,name) VALUES ('prebuyprice4','【预设进价4】')
INSERT INTO BalanceSelect(code,name) VALUES ('prebuyprice5','【预设进价5】')
INSERT INTO BalanceSelect(code,name) VALUES ('retailprice','【零售价】')
INSERT INTO BalanceSelect(code,name) VALUES ('topsaleprice','【最高售价】')
INSERT INTO BalanceSelect(code,name) VALUES ('lowsaleprice','【最低售价】')
INSERT INTO BalanceSelect(code,name) VALUES ('usefullifeday','【有效期】')
INSERT INTO BalanceSelect(code,name) VALUES ('entrycode','【条码】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice1','【预设售价1】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice2','【预设售价2】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice3','【预设售价3】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice4','【预设售价4】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice5','【预设售价5】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice6','【预设售价6】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice7','【预设售价7】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice8','【预设售价8】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice9','【预设售价9】')
INSERT INTO BalanceSelect(code,name) VALUES ('presaleprice10','【预设售价10】')
SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*------------------------------------------
	作者：王刚
	日期：2014-07-02
	描述：出纳管理银行账户
-------------------------------------------*/


IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Bank_l]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Bank_l]
	(
		[etypeid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[typeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[flag] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL
	) 
END
GO


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[bank_l]') AND name = N'IX_bank_l')
--	DROP INDEX IX_bank_l ON bank_l
CREATE CLUSTERED INDEX IX_bank_l ON bank_l(ETypeID)
------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*==============================================================*/
/* Table: BarCode                                               */
/*==============================================================*/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BarCode]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[BarCode] 
	(
	   ID                   int                  identity(1,1),
	   UserCode             varchar(200)         NOT NULL DEFAULT '',
	   FullName             varchar(200)         NOT NULL DEFAULT '',
	   Deleted				bit					 NOT NULL DEFAULT(0),
	   IsDefault			BIT					 NOT NULL DEFAULT(0),
	   IsPrint				BIT					 NOT NULL DEFAULT(0)
	)ON [PRIMARY]
END

GO

-----------------修改表区域开始------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[BarCode]') and name = 'Deleted' )
BEGIN	
	ALTER TABLE dbo.BarCode ADD
		Deleted	BIT NOT NULL DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[BarCode]') and name = 'IsDefault' )
BEGIN	
	ALTER TABLE dbo.BarCode ADD
		IsDefault	BIT	NOT NULL DEFAULT(0)
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[BarCode]') and name = 'IsPrint' )
BEGIN	
	ALTER TABLE dbo.BarCode ADD
		IsPrint	BIT	NOT NULL DEFAULT(0)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BARCODE') AND name = 'CIX_BARCODE_ID')
--DROP INDEX CIX_BARCODE_ID ON BARCODE 
CREATE CLUSTERED INDEX CIX_BARCODE_ID ON BARCODE(ID) 
------------------------------------------创建索引区域结束-----------------------------------------------
-----------------修改表区域结束------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*==============================================================*/
/* Table: BarCode_Ext 条形码明细                                            */
/*==============================================================*/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BarCode_Ext]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].BarCode_Ext 
	(
		BarCodeID	int	NOT NULL,	--条形码id
		StartNum    int	NOT NULL,	--起始位
		EndNum      int	NOT NULL,	--结束位
		SourceID    int	NOT NULL	--条形码来源id
	)ON [PRIMARY]
END

GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BARCODE_EXT') AND name = 'CIX_BARCODE_EXT_BarCodeID')
--DROP INDEX CIX_BARCODE_EXT_BarCodeID ON BARCODE_EXT 
CREATE CLUSTERED INDEX CIX_BARCODE_EXT_BarCodeID ON BARCODE_EXT(BarCodeID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BARCODE_EXT') AND name = 'NCIX_BARCODE_EXT_SourceID')
--DROP INDEX NCIX_BARCODE_EXT_SourceID ON BARCODE_EXT 
CREATE NONCLUSTERED INDEX NCIX_BARCODE_EXT_SourceID ON BARCODE_EXT(SourceID) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*==============================================================*/
/* Table: BarCode_Source 条形码来源                                              */
/*==============================================================*/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BarCode_Source]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].BarCode_Source 
	(
		ID                   int                  NOT NULL,					--编号
		Fullname             varchar(200)         NOT NULL DEFAULT(''),		--代表含义
		DecimalLength		 int				  NOT NULL DEFAULT(0)		--小数位数
	)ON [PRIMARY]
END

GO

-----------------修改表区域开始------------------

if not exists (select name from syscolumns where id = object_id(N'[dbo].[BarCode_Source]') and name = 'DecimalLength' )
BEGIN	
	ALTER TABLE dbo.BarCode_Source ADD
		DecimalLength int NOT NULL DEFAULT(0)
END
GO

-----------------修改表区域结束------------------



---------------------添加表预置数据--------------
--计量单位编码  商品编码  商品条码 仓库编码  单价--------
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BarCode_Source]') AND type in (N'U'))
BEGIN
	DELETE FROM BarCode_Source
	INSERT INTO BarCode_Source  VALUES (1,'计量单位编码',0)
	INSERT INTO BarCode_Source  VALUES (2,'商品编码',0)
	INSERT INTO BarCode_Source  VALUES (3,'商品条码',0)
	INSERT INTO BarCode_Source  VALUES (4,'仓库编码',0)
	INSERT INTO BarCode_Source  VALUES (5,'单价',4)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BARCODE_SOURCE') AND name = 'CIX_BARCODE_SOURCE_ID')
--DROP INDEX CIX_BARCODE_SOURCE_ID ON BARCODE_SOURCE 
CREATE CLUSTERED INDEX CIX_BARCODE_SOURCE_ID ON BARCODE_SOURCE(ID) 

------------------------------------------创建索引区域结束-----------------------------------------------
-------------------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*==============================================================*/
/* Table: BarCodeForBilltype 单据条形码明规则                                           */
/*==============================================================*/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BarCodeForBilltype]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].BarCodeForBilltype 
	(
		BillType	int NOT NULL,	--单据编号
		BarCodeID	int	NULL	--条形码id
	)ON [PRIMARY]
	
-------------------表 数 据 源 (内置数据，不需要清空，关联数据来自BillName )---------------------------	
DELETE FROM BarCodeForBilltype

INSERT INTO BarCodeForBilltype (BillType,BarCodeID) VALUES 
(305,0),
(300,0),
(11,0),
(45,0),
(160,0),
(139,0),
(140,0),
(142,0),
(143,0),
(141,0),
(301,0),
(34,0),
(6,0),
(161,0),
(126,0),
(144,0),
(146,0),
(147,0),
(145,0),
(17,0),
(21,0),
(187,0),
(188,0),
(201,0),
(202,0),
(9,0),
(14,0),
(16,0),
--(165,0),
(166,0),
--(167,0),
--(168,0),
(169,0),
--(170,0),
--(171,0),
(172,0),
(173,0),
(174,0),
(175,0),
(306,0),
(400,0),
(402,0)
----------------------------------------------------
END

GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BARCODEFORBILLTYPE') AND name = 'CIX_BARCODEFORBILLTYPE_Billtype')
--DROP INDEX CIX_BARCODEFORBILLTYPE_Billtype ON BARCODEFORBILLTYPE 
CREATE CLUSTERED INDEX CIX_BARCODEFORBILLTYPE_Billtype ON BARCODEFORBILLTYPE(Billtype) 

------------------------------------------创建索引区域结束-----------------------------------------------


----------------------------------------------修改表数据开始----------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM BarCodeForBilltype WHERE BillType=215)
BEGIN
	INSERT INTO BarCodeForBilltype	(BillType,BarCodeID) VALUES(215,0)
END
GO

IF NOT EXISTS(SELECT 1 FROM BarCodeForBilltype WHERE BillType=400)
BEGIN
	INSERT INTO BarCodeForBilltype	(BillType,BarCodeID) VALUES(400,0)
END
GO
 
IF NOT EXISTS(SELECT 1 FROM BarCodeForBilltype WHERE BillType=402)
BEGIN
	INSERT INTO BarCodeForBilltype	(BillType,BarCodeID) VALUES(402,0)
END
GO
--删除不要的数据
--982 bug904 2017.08.14 现在要用条形码查询
IF NOT EXISTS(SELECT 1 FROM BarCodeForBilltype WHERE BillType=401)
BEGIN
	INSERT INTO BarCodeForBilltype	(BillType,BarCodeID) VALUES(401,0)
END
GO

IF NOT EXISTS(SELECT 1 FROM BarCodeForBilltype WHERE BillType=403)
BEGIN
	INSERT INTO BarCodeForBilltype	(BillType,BarCodeID) VALUES(403,0)
END
GO 

----------------------------------------------修改表数据结束----------------------------------------------------





------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('Base_FixedReasonForChange') AND type = 'U')
	BEGIN
		CREATE TABLE Base_FixedReasonForChange(
			NID				INT				IDENTITY(1,1),
			UserCode		VARCHAR(200)	NOT NULL,
			FullName		VARCHAR(200)	NOT NULL,
			Comment			VARCHAR(1000),
			Sysrow			BIT				NOT NULL DEFAULT(0),
			XiWaMaxNumber   INT				NULL DEFAULT(1)	--缓存ID
		)
	END
GO
------------------------------------------表修改区-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Base_FixedReasonForChange') AND name = 'CIX_Base_FixedReasonForChange_NID')
	CREATE CLUSTERED INDEX CIX_Base_FixedReasonForChange_NID ON Base_FixedReasonForChange(NID) 

------------------------------------------创建索引区域结束-----------------------------------------------

--------------------------------预制数据----------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Base_FixedReasonForChange)
	BEGIN
		SET IDENTITY_INSERT dbo.Base_FixedReasonForChange ON
		
		INSERT INTO Base_FixedReasonForChange(NID,UserCode,FullName,Comment,Sysrow,XiWaMaxNumber)VALUES(1,'BG001','资产评估原值增','应用于资产评估原值增加的情况；如遇减少请用计提减值准备功能',1,default)
		INSERT INTO Base_FixedReasonForChange(NID,UserCode,FullName,Comment,Sysrow,XiWaMaxNumber)VALUES(2,'BG002','资产价值调整','应用与购买资产原值或累计折旧入错帐的调整',1,default)
		
		SET IDENTITY_INSERT dbo.Base_FixedReasonForChange OFF
		
	END
GO




IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('Base_FixedReasonForChangeDetails') AND type = 'U')
	BEGIN
		CREATE TABLE Base_FixedReasonForChangeDetails(
			NID				INT	 IDENTITY(1,1),
			TID				INT,				--变更原因主表ID
			STypeID			VARCHAR(50),		--分支机构ID
			EnterATypeID	VARCHAR(50),		--入账原值差异科目
			ForeignATypeID	VARCHAR(50),		--外币影响原值差异科目
			RateATypeID		VARCHAR(50),		--汇率影响原值科目
			XiWaMaxNumber   INT NULL DEFAULT(1)	--缓存ID
		)
	END
GO
------------------------------------------表修改区-----------------------------------------------

--select * from Base_FixedReasonForChangeDetails
--TRUNCATE table Base_FixedReasonForChangeDetails

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Base_FixedReasonForChangeDetails') AND name = 'CIX_Base_FixedReasonForChangeDetails_NID')
	CREATE CLUSTERED INDEX CIX_Base_FixedReasonForChangeDetails_NID ON Base_FixedReasonForChangeDetails(NID) 

------------------------------------------创建索引区域结束----------------------------------------------

----------------------------------预制数据----------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Base_FixedReasonForChangeDetails)
	BEGIN
		INSERT INTO Base_FixedReasonForChangeDetails(TID,STypeID,EnterATypeID,ForeignATypeID,RateATypeID,XiWaMaxNumber)
		SELECT 
			1 TID,
			TypeId STypeID,
			'' EnterATypeID,
			'' ForeignATypeID,
			'' RateATypeID,
			null XiWaMaxNumber
		FROM SType
		WHERE TypeId<>'00000'
		UNION ALL
		SELECT 
			2 TID,
			TypeId STypeID,
			'' EnterATypeID,
			'' ForeignATypeID,
			'' RateATypeID,
			null XiWaMaxNumber
		FROM SType
		WHERE TypeId<>'00000'
	END
GO






IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('Base_InventoryType') AND type = 'U')
	BEGIN
		CREATE TABLE Base_InventoryType(
			NID				INT				IDENTITY(1,1),
			UserCode		VARCHAR(200)	NOT NULL,
			FullName		VARCHAR(200)	NOT NULL,
			Comment			VARCHAR(1000),
			Sysrow			BIT				NOT NULL DEFAULT(0),
			XiWaMaxNumber   INT				NULL DEFAULT(1)	--缓存ID
		)
	END
GO
------------------------------------------表修改区-----------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Base_InventoryType' AND a.Name='XiWaMaxNumber'
)
BEGIN
	ALTER TABLE Base_InventoryType 
		ADD XiWaMaxNumber  INT NULL DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Base_InventoryType' AND a.Name='SysRowId'
)
BEGIN
	ALTER TABLE Base_InventoryType 
		ADD SysRowId  INT NOT NULL DEFAULT(0)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Base_InventoryType') AND name = 'CIX_Base_InventoryType_NID')
	CREATE CLUSTERED INDEX CIX_Base_InventoryType_NID ON Base_InventoryType(NID) 

------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------预制数据----------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Base_InventoryType)
	BEGIN
		SET IDENTITY_INSERT dbo.Base_InventoryType ON
		
		INSERT INTO Base_InventoryType(NID,UserCode,FullName,Comment,Sysrow,SysRowId)VALUES(1,'CH01','原材料','',1,1)
		INSERT INTO Base_InventoryType(NID,UserCode,FullName,Comment,Sysrow,SysRowId)VALUES(2,'CH02','库存商品','',1,2)
		
		SET IDENTITY_INSERT dbo.Base_InventoryType OFF
		
	END
GO




IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('Base_InventoryTypeDetails') AND type = 'U')
	BEGIN
		CREATE TABLE Base_InventoryTypeDetails(
			NID				INT	 IDENTITY(1,1),
			TID				INT,				--存货类型主表ID
			STypeID			VARCHAR(50),		--分支机构ID
			StockATypeID	VARCHAR(50),		--存货核算科目
			IncomeATypeID	VARCHAR(50),		--销售收入科目
			CostATypeID		VARCHAR(50),		--销售成本科目
			XiWaMaxNumber   INT NULL DEFAULT(1)	--缓存ID
		)
	END
GO
------------------------------------------表修改区-----------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Base_InventoryTypeDetails' AND a.Name='XiWaMaxNumber'
)
BEGIN
	ALTER TABLE Base_InventoryTypeDetails 
		ADD XiWaMaxNumber  INT NULL DEFAULT(1)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Base_InventoryTypeDetails') AND name = 'CIX_Base_InventoryTypeDetails_NID')
	CREATE CLUSTERED INDEX CIX_Base_InventoryTypeDetails_NID ON Base_InventoryTypeDetails(NID) 

------------------------------------------创建索引区域结束-----------------------------------------------

----------------------------------预制数据----------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM Base_InventoryTypeDetails)
	BEGIN
		INSERT INTO Base_InventoryTypeDetails(TID,STypeID,StockATypeID,IncomeATypeID,CostATypeID)
		SELECT 
			1 TID,
			TypeId STypeID,
			'' StockATypeID,
			'' IncomeATypeID,
			'' CostATypeID
		FROM SType
		WHERE TypeId<>'00000'
		UNION ALL
		SELECT 
			2 TID,
			TypeId STypeID,
			'' StockATypeID,
			'' IncomeATypeID,
			'' CostATypeID
		FROM SType
		WHERE TypeId<>'00000'
	END
GO





/****** Object:  Table [dbo].[BaseAttachFile]    Script Date: 05/17/2019 08:48:44 ******/


IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id(N'[dbo].[BaseAttachFile]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
	CREATE TABLE [dbo].[BaseAttachFile](
	[ID]         [int] IDENTITY(1,1)   NOT NULL,
	[pid]        [numeric](24, 10)     NOT NULL,
	[FileName]   [varchar](300)        NOT NULL DEFAULT (''),
	[FileType]   [varchar](50)         NOT NULL DEFAULT (''),
	[Size]       [varchar](100)        NOT NULL DEFAULT (''),
	[AttachDate] [datetime]            NOT NULL DEFAULT (''),
	[Annexcomment]    [varchar](100)        NULL,
	[Data]       [image]               NOT NULL,
	[ETypeId]    [varchar](50)         NULL DEFAULT (''),
	[basetypeid] [int] NOT NULL        DEFAULT(0)
	)ON [PRIMARY]
	
	END
GO	

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BaseAttachFile' AND a.Name='comment'
)
BEGIN
	execute sp_rename 'BaseAttachFile.comment','Annexcomment'
END

GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BaseAttachFile') AND name = 'NCIX_BaseAttachFile_PID')
--DROP INDEX NCIX_BillAttachFiles_BILLNUMBERID ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_BaseAttachFile_PID ON BaseAttachFile(PID) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO



/*
* 基本信息分类、删除、搬移判断用
* 吴雷 2014.04.16
*/ 
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('BaseInfoAssitDetection') AND  type = 'U')
BEGIN
	CREATE TABLE  BaseInfoAssitDetection
	(
	Id				INT IDENTITY(1,1),					--自增Id
	BaseinfoType	VARCHAR(200) NOT NULL DEFAULT(''),	--基本信息类型，比如商品 ptype 客户btype
	TableName		VARCHAR(200) NOT NULL DEFAULT(''),	--需要判断的表名
	TableColumnname VARCHAR(200) NOT NULL DEFAULT(''),	--表里列名 
	IfCategory		BIT			 NOT NULL DEFAULT(0),	--分类需要判断 
	IfDelete		BIT			 NOT NULL DEFAULT(0),	--删除需要判断 
	IfMove			BIT			 NOT NULL DEFAULT(0),	--搬移需要判断
	IfUsed			BIT			 NOT NULL DEFAULT(0),	--是否使用需要判断
	Explain			VARCHAR(400) NOT NULL DEFAULT(''),	--说明
	Conditions		VARCHAR(400) NOT NULL DEFAULT('')	--条件
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BaseInfoAssitDetection' AND a.Name='Conditions'
)
BEGIN
	ALTER TABLE BaseInfoAssitDetection ADD Conditions VARCHAR(2000) NOT NULL DEFAULT('')
END
GO

-------------------------------表预制数据----------------------------------------------------------
DELETE FROM BaseInfoAssitDetection
--======================地区===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('AreaType','Btype','AreaTypeID','','1','1','1','1','该地区档案已经在客户或供货商档案中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('AreaType','Crm_Btype','AreaTypeID','','1','1','1','1','该地区档案已在CRM客户管理中使用')
--======================会计科目===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','AccountCredence','atypeId','TypeATypeID NOT IN(''0000200001'',''0000100005'',''0000200006'',''0000100009'',''0000100010'')','1','1','1','1','该会计科目已关联会计凭证')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','atype','typeId','(sonnum=0 AND sysrow=1)','1','1','1','1','该会计科目为系统会计科目')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','atype','typeId','(Total<>0 OR Total00<>0)','1','1','1','1','该会计科目账户金额不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','atype','atypeId','IFCanClass=0','1','1','1','1','该会计科目为系统科目')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','PayConfigInfo','BankCardID','','1','1','1','1','该账户已在支付宝或微信结算设置中使用') --982 bug229
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','AType_Total','atypeId','Total00<>0','1','1','1','1','该会计科目已有期初数据')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','billindex','atypeId','','1','1','1','1','该会计科目已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','BillMulAccount','atypeId','','1','1','1','1','该会计科目在多账户中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','gatheringbill','atypeId','','1','1','1','1','该会计科目在收款单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','listtable','atypeId','','1','1','1','1','该会计科目已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','MoneyBill','atypeId','','1','1','1','1','该会计科目已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','MoveMoneyBill','atypeId','','1','1','1','1','该会计科目已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','OtherInOUTType','atypeId','','1','1','1','1','该会计科目在其他出入库业务类别中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','paybill','atypeId','','1','1','1','1','该会计科目在付款单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','PosRetailCash','atypeId','','1','1','1','1','该会计科目在pos管理中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','PreBill','atypeId','','1','1','1','1','该会计科目已经经营过')
--======================往来单位===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','AccountCredence','ATypeID','TypeATypeID in(33273539)','1','1','1','1','该往来单位已关联业务凭证')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','AdDebtBill','btypeid','','1','1','1','1','该往来单位已在应收应付中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','BillIndex','btypeid','','1','1','1','1','该往来单位已经经营过')
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','CouponBillIndex','btypeid','','1','1','1','1','该往来单位已经在优惠券中经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','BillIndex','DealBTypeID','','1','1','1','1','该往来单位已经经营过')
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','CouponBillIndex','DealBTypeID','','1','1','1','1','该往来单位已经在优惠券中经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','btype','typeid','ARTotal-ApTotal<>0','1','1','1','1','该往来单位往来帐不为零')
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','btype','denominatedid','typeId<>@Parid','1','1','1','1','该往来单位已与结算单位关联')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','BType_ArApTotal','btypeid','(ARTotal00<>0 or APTotal00<>0 or YSTotal00<>0 or YFTotal00<>0)','1','1','1','1','该往来单位应收或应付期初中不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','BType_Credit','btypeid','','1','0','1','1','该往来单位已有信用额度') /*9.6删除不判断*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','CommissionStock','btypeid','Qty<>0','1','1','1','1','该往来单位有代销情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','CommissionStock','btypeid','(total<>0 or costtotal<>0)','1','1','1','1','该往来单位有代销情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','CommonPosInfo','btypeid','','1','1','1','1','该往来单位已关联pos')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','CommonPosSaleIndex','btypeid','','1','1','1','1','该往来单位已关联pos')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','FapiaoBillIndex','btypeid','','1','1','1','1','该往来单位有发票')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','gp_CruPtypeSerial','btypeid1','','1','1','1','1','该往来单位已有序列号关联情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','gp_CruPtypeSerial','btypeid2','','1','1','1','1','已有序列号已有序列号关联情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','gp_initPtypeSerial','btypeid1','','1','1','1','1','该往来单位已有期初序列号关联情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','gp_initPtypeSerial','btypeid2','','1','1','1','1','该往来单位已有期初序列号关联情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','iniCommissionStock','btypeid','Qty<>0','1','1','1','1','该往来单位有代销情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','iniCommissionStock','btypeid','(total<>0 or costtotal<>0)','1','1','1','1','该往来单位有代销情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','LendIndex','btypeid','totalQty<>0','1','1','1','1','该往来单位已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','LendIndex','btypeid','','1','1','1','1','该往来单位已在借欠单中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','listtable','btypeid','','1','1','1','1','该往来单位已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','nvipcardsign','btypeid','','1','1','1','1','该往来单位已关联会员卡')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','OrderIndex','btypeid','','1','1','1','1','该往来单位已在订单中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','OrderIndex','DealBTypeID','','1','1','1','1','该往来单位已在订单中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','PosInfo','btypeid','','1','1','1','1','该往来单位关联pos')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','PosInfo','dealbtypeid','','1','1','1','1','该往来单位关联pos')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','WdShopConfig','btype','','1','1','1','1','该往来单位已在网店配置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','PriceProtect','btypeid','','1','1','1','1','该往来单位有价保通知')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','PriceRule_Detail_BConfig','btypeid','','1','1','1','1','该往来单位关联促销')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','PriceTrack','btypeid','','1','0','1','1','该往来单位已关联价格跟踪')/*9.6删除不判断*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','QP_PType_Ext','btypeid','','1','1','1','1','该往来单位已关联商品')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','Qp_ReceptionBill_Insurance','btypeid','','1','1','1','1','该往来单位已关联维修业务')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','SType','btypeid1','','1','1','1','1','该往来单位已经被分支机构关联')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','SType','btypeid2','','1','1','1','1','该往来单位已经被分支机构关联')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','V_LendStatus','btypeid','','1','1','1','1','该往来单位有借进借出')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','Ac_VoucherCommonly_Bill_Assist_CheckItems','typeid','typeName=''04''','1','0','1','1','该往来单位已在常用凭证模板辅助核算中使用') /*9.6删除不判断*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','PUserCode','btypeid','','0','0','0','0','该往来单位设置了多商品编码')/*9.6删除不判断*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','AccountCredence','Atypeid','','0','1','1','0','该往来单位在业务凭证核算明细中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','Custom_BillDetails','SysDiy13','','1','1','1','1','该往来单位已在表体自定义13中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','Custom_BillIndex','SysDiy13_head','','1','1','1','1','该往来单位已在表头自定义13中使用')
/*往来单位关联辅助核算*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('BTYPE','Ac_Voucher_Bill_Assist_CheckItems','TypeId','typeName = ''04''','1','1','1','1','该往来单位已在凭证辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('BTYPE','Ac_Balance_Assist_CheckItems_Detail','FieldValue','Ascids = 4','1','1','1','1','该往来单位已在科目余额辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('BTYPE','Ac_IniAccount_Assist_CheckItems_Detail','FieldValue','Ascids = 4','1','1','1','1','该往来单位已在期初科目辅助核算中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','GP_initLendPTypeSerial','btypeid1','','1','1','1','1','该往来单位有借欠期初序列号') 
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','GP_initLendPTypeSerial','btypeid2','','1','1','1','1','该往来单位有借欠期初序列号')
 
--======================部门===================
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','department','typeid','WdSyncFlag = 1','1','0','0','0','该部门已同步到全渠道，请取消同步再分类或删除')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','CombinationProductIndex','dtypeId','','1','1','1','1','该部门已在组合品模版中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','Ac_AssetsCards','dtypeId','','1','1','1','1','该部门已在固定资产卡片中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','Billindex','dtypeId','','1','1','1','1','该部门存在经营历程')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','CM_CarUseIndex','dtypeId','','1','1','1','1','该部门已经在使用登记单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','CM_FeeIndex','dtypeId','','1','1','1','1','该部门已经在车辆费用单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','DtypeSaleplan','dtypeId','','1','1','1','1','该部门已经在销售计划中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','employee','dtypeId','','1','1','1','1','该部门已经在职员信息中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','FapiaoBillIndex','dtypeId','','1','1','1','1','该部门已作为发票开单的部门')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','LendIndex','dtypeId','','1','1','1','1','该部门已在借欠单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','nVipConfiscateConfig','dtypeId','','1','1','1','1','该部门已经在充值单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','nVipWashCarTimesConfig','dtypeId','','1','1','1','1','该部门已经在充值单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','OrderIndex','dtypeId','','1','1','1','1','该部门已在订单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','MoneyBill','dtypeId','','1','1','1','1','该部门已在现金费用单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','FixedAssetsIndex','dtypeId','','1','1','1','1','该部门已在固定资产盘点单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','Ac_VoucherCommonly_Bill_Assist_CheckItems','typeid','typeName=''02''','1','1','1','1','该部门已在常用凭证模板辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','Custom_BillDetails','SysDiy14','','1','1','1','1','该部门已在表体自定义14中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','Custom_BillIndex','SysDiy14_head','','1','1','1','1','该部门已在表头自定义14中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','PosAllotApplyBillIndex','dtypeid','','1','1','1','1','该部门已在门店类单据或调货申请中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','depbill','dtypeid','','1','1','1','1','该部门已在固定资产折旧单中使用')
/*部门关联辅助核算*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('DEPARTMENT','Ac_Voucher_Bill_Assist_CheckItems','TypeId','typeName = ''02''','1','1','1','1','该部门已在凭证辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('DEPARTMENT','Ac_Balance_Assist_CheckItems_Detail','FieldValue','Ascids = 2','1','1','1','1','该部门已在科目余额辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('DEPARTMENT','Ac_IniAccount_Assist_CheckItems_Detail','FieldValue','Ascids = 2','1','1','1','1','该部门已在期初科目辅助核算中使用')


--======================职员===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','employee','typeid','WdSyncFlag = 1','1','0','0','0','该职员已同步到全渠道，请取消同步再分类或删除')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CombinationProductIndex','etypeid','','1','1','1','1','该职员已在组合品模版中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','PosAllotApplyBillIndex','applyetypeid','','1','1','1','1','该职员已在门店类单据或调货申请中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','PosAllotApplyBillIndex','checke','','1','1','1','1','该职员已在门店类单据或调货申请中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','MoneyBill','etypeId','','1','1','1','1','该职员已在现金费用单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Ac_AssetsCards','etypeId','etypeid<>''00001''','1','1','1','1','该职员作为资产卡片制卡人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Ac_AssetsCards_History','etypeId','','1','1','1','1','该职员已有资产卡片历史')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Ac_AssetsModifyRecords','etypeId','','1','1','1','1','该职员已处理过资产卡片变更')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Ac_DepreciationAlteration','etypeId','','1','1','1','1','该职员已做过资产卡片折旧计划')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Ac_ProvisionForImpairment','etypeId','','1','1','1','1','该职员已做过减值准备')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Advantage_standard','etypeId','etypeid<>''00001''','1','1','1','1','该职员作为返利标准的制作人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','billindex','etypeId','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','billindex','checke','checke<>''00001''','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','billindex','wxmanID','wxmanID<>''00001''','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Billindex_CarRepair','ReceptionId','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Billindex_CarRepair','ItemPrincipal','','1','1','1','1','该职员关联维修业务调度中的负责人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Billindex_CarRepair','MonitorPrincipal','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Billindex_CarRepair','UnitSatrap','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CM_CarInfo','Driver','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CM_CarUseBill','Driver','','1','1','1','1','该职员已经关联使用登记单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CM_CarUseBill','etypeId','','1','1','1','1','该职员已经关联使用登记单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CM_CarUseIndex','etypeId','','1','1','1','1','该职员已经关联使用登记单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CM_FeeIndex','etypeId','','1','1','1','1','该职员已经关联车辆费用单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommonPosInfo','etypeId1','','1','1','1','1','该职员关联pos')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_Btype','createor','createor<>''00001''','1','1','1','1','该职员已创建了CRM客户')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_linkMan','createor','createor<>''00001''','1','1','1','1','该职员已创建了CRM联系人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_Message','SenderTypeID','SenderTypeID<>''00001''','1','1','1','1','该职员已在日程中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_Message','ReceiverTypeID','ReceiverTypeID<>''00002''','1','1','1','1','该职员已在日程中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_MessageNoread','SenderTypeID','SenderTypeID<>''00001''','1','1','1','1','该职员已在日程中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_MessageNoread','ReceiverTypeID','ReceiverTypeID<>''00001''','1','1','1','1','该职员已在日程中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_MessageNoread','CreatorTypeID','CreatorTypeID<>''00001''','1','1','1','1','该职员已在日程中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_Schedule','CreatorTypeID','CreatorTypeID<>''00001''','1','1','1','1','该职员已在维修单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','crm_Schedule','CreatorTypeID','CreatorTypeID<>''00001''','1','1','1','1','该职员已在日程中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','DiyIndex','checke','checke<>''00001''','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','EtypeSaleplan','etypeId','','1','1','1','1','该职员已经关联销售计划')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','FapiaoBillIndex','etypeId','etypeid<>''00001''','1','1','1','1','该职员作为发票经手人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','FapiaoBillIndex','Assessor','Assessor<>''00001''','1','1','1','1','该职员作为发票审核人或制单人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','FapiaoBillIndex','checke','checke<>''00001''','1','1','1','1','该职员作为发票审核人或制单人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','LendIndex','etypeId','etypeid<>''00001''','1','1','1','1','该职员已在借欠单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','LendIndex','checke','checke<>''00001''','1','1','1','1','该职员已在借欠单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','loginuser','etypeId','etypeid<>''00001''','1','1','1','1','该职员已经是操作员')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','nVipAdjust','etypeId','etypeid<>''00001''','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','nVipAdjust','etypeId','','1','1','1','1','该职员已在会员卡消费调整或者积分中进行处理')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','nVipCardSign','etypeId','etypeid<>''00001''','1','1','1','1','该职员作为会员卡的发卡人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','nVipConfiscateConfig','etypeId','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','nVipWashCarTimesConfig','etypeId','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','OrderIndex','etypeId','etypeid<>''00001''','1','1','1','1','该职员已在订单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','OrderIndex','checke','checke<>''00001''','1','1','1','1','该职员已在订单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','PerformanceDistribution','etypeId','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','PriceProtect','WriteId','WriteId<>''00001''','1','1','1','1','该职员有价保通知')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','PriceRule_Detail_EConfig','etypeId','','1','1','1','1','该职员已关联价格表档案')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','PriceRule_Detail_EConfig','etypeId','','1','1','1','1','该职员已关联促销')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Qp_AttemperBill_RepairItemsPerson','etypeId','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Qp_SuccorBill_RepairItems','etypeId','','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','RepairEngage','etypeId','etypeid<>''00001''','1','1','1','1','该职员已在维修单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','RequestBill','etypeId','','1','1','1','1','该职员已经关联请购单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','RequestIndex','etypeId','','1','1','1','1','该职员已经关联请购单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','StockCheckIndex','etypeId','etypeid<>''00001''','1','1','1','1','该职员已在盘点单中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','TcBillIndex','etypeId','EtypeId<>''00001''','1','1','1','1','该职员作为提成规则单制单人或审核人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','TcBillIndex','checke','checke<>''00001''','1','1','1','1','该职员作为提成规则单制单人或审核人')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','ToolIndex','etypeId','','1','1','1','1','该职员已在工具入出库台帐中用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','wx_bill_call','etypeId','etypeid<>''00001''','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','wx_bill_jiejian','etypeId','etypeid<>''00001''','1','1','1','1','该职员已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Te_AccountInTransit_Detail','etypeId','etypeid<>''00001''','1','1','1','1','该职员已在出纳模块中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommissionRulePtype','etypeid','','1','1','1','1','该职员已在提成规则职员商品设置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommissionRuleEtype','etypeid','','1','1','1','1','该职员已在提成规则职员设置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommissionRule','checke','','1','1','1','1','该职员已在提成规则中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommissionRule','checker','','1','1','1','1','该职员已在提成规则中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','ReferencePlanCommission','checke','','1','1','1','1','该职员已在参照计划提成中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','ReferencePlanCommission','checker','','1','1','1','1','该职员已在参照计划提成中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','ReferencePlanCommissionEtype','etypeid','','1','1','1','1','该职员已在参照计划提成规则中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommissionBillNew','checke','','1','1','1','1','该职员已在提成单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommissionBillNew','checker','','1','1','1','1','该职员已在提成单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommissionBillNewDetail','etypeid','','1','1','1','1','该职员已在提成单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','FixedAssetsIndex','etypeid','','1','1','1','1','该职员已在固定资产盘点单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','EtypeCommissionType','etypeid','','1','1','1','1','该职员已在业务提成设置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CommissionType','etypeid','','1','1','1','1','该职员已在业务提成设置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Te_Journal_Detail','etypeid','','1','1','1','1','该职员已在现金日记账中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Ac_VoucherCommonly_Bill_Assist_CheckItems','typeid','typeName=''03''','1','1','1','1','该职员已在常用凭证模板辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Ac_Voucher_Commonly','etypeid','','1','1','1','1','该职员已在常用凭证模板中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','retailBill','etypeid','','1','1','1','1','该职员已在零售单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','RetailBackBill','etypeid','','1','1','1','1','该职员已在零售退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','DiyIndex','etypeid','','1','1','1','1','该职员已在电脑装机配置单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Custom_BillDetails','SysDiy11','','1','1','1','1','该职员已在表体自定义11中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Custom_BillIndex','SysDiy11_head','','1','1','1','1','该职员已在表头自定义11中使用')
/*职员关联辅助核算*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('EMPLOYEE','Ac_Voucher_Bill_Assist_CheckItems','TypeId','typeName = ''03''','1','1','1','1','该职员已在凭证辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('EMPLOYEE','Ac_Balance_Assist_CheckItems_Detail','FieldValue','Ascids = 3','1','1','1','1','该职员已在科目余额辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('EMPLOYEE','Ac_IniAccount_Assist_CheckItems_Detail','FieldValue','Ascids = 3','1','1','1','1','该职员已在期初科目辅助核算中使用')
/*销售出库单、销售退货单、销售换货单 表体业务员*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','salebill','etypeid','','1','1','1','1','该职员已在销售出库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','salebackbill','etypeid','','1','1','1','1','该职员已在销售退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','salegoodsexchangebill','etypeid','','1','1','1','1','该职员已在销售换货单中使用')
--优惠券入库单出库单表头经手人
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','CouponBillIndex','etypeid','','1','1','1','1','该职员已在优惠券中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Ac_Auditing_Template','ETypeId','etypeid<>''00001''','1','1','1','1','该职员已添加的凭证模板')


--======================仓库===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','PosAllotApplyBill','ktypeid','','1','1','1','1','该仓库已在调货申请中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','PosAllotApplyBill','InKTypeID','','1','1','1','1','该仓库已在调货申请中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','PosAllotApplyBillIndex','ktypeid','','1','1','1','1','该仓库已在门店类单据或调货申请中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','PosAllotApplyBillIndex','InKTypeID','','1','1','1','1','该仓库已在门店类单据或调货申请中使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Billindex','ktypeid','','1','1','1','1','该仓库已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Billindex','ktypeid2','','1','1','1','1','该仓库已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Billindex','ktypeid3','kTypeID <> ''00000''','1','1','1','1','该仓库已经经营过')
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','CouponApplyStock','ktypeid','','1','1','1','','该仓库已在优惠券中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','BuybackBill','ktypeid','','1','1','1','1','该仓库已关联采购退货单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','BuyBill','ktypeid','','1','1','1','1','该仓库已关联采购入库单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','BuyGoodsExchangeBill','ktypeid','','1','1','1','1','该仓库已关联采购换货单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','BuyGoodsExchangeBill','ktypeid2','','1','1','1','1','该仓库已关联采购换货单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','CommissionBill','ktypeid','','1','1','1','1','该仓库已关联委托代销单据')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','CommissionStock','ktypeid','(Qty<>0 OR total<>1)','1','1','1','1','该仓库存在代销情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','CommonPosInfo','stockid','','1','1','1','1','该仓库已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','CommonPosPtypeCheckNdx','ktypeid','','1','1','1','1','该仓库已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','CommonPosSaleIndex','ktypeid','','1','1','1','1','该仓库已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','CX_SaleStocksArea','ktypeid','','1','1','1','1','该仓库已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','DisassembleBill','ktypeid','','1','1','1','1','该仓库已关联生产拆装单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','FaPiaoBill','ktypeid','','1','1','1','1','该仓库已在发票中关联')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','goodsstocks','ktypeid','Qty<>0','1','1','1','1','该仓库库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','DefaultStock','ktypeid','','1','1','1','1','该仓库已在商品默认仓库中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','gp_CruPtypeSerial','ktypeid','','1','1','1','1','该仓库有序列号关联情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','gp_initPtypeSerial','ktypeid','','1','1','1','1','该仓库有期初序列号关联情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Ini_GOODSSTOCKS_QTY','ktypeid','Qty<>0','1','1','1','1','该仓库期初库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','iniCommissionStock','ktypeid','(Qty<>0 OR total<>0)','1','1','1','1','该仓库存在代销情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','inigoodsstocks','ktypeid','Qty<>0','1','1','1','1','该仓库库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','inigoodsstocks','ktypeid','Qty<>0','1','1','1','1','该仓库有库存期初')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','InOutStockTable','ktypeid','Qty<>0','1','1','1','1','该仓库已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','IntegralExchangeBill','ktypeid','','1','1','1','1','该仓库已关联积分兑换单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','LendIndex','ktypeid','totalQty<>0','1','1','1','1','该仓库已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','LendIndex','ktypeid','','1','1','1','1','该仓库已在借欠单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','OrderBill','ktypeid','','1','1','1','1','该仓库已关联销售订单或采购订单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','OrderIndex','ktypeid','','1','1','1','1','该仓库已在订单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','PosInfo','ktypeid','','1','1','1','1','该仓库已关联POS')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','PriceRule_Detail_KConfig','ktypeid','','1','1','1','1','该仓库已关联价格策略')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','PromoRule_Detail_KConfig','ktypeid','','1','1','1','1','该仓库已关联促销规则')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','SaleBackBill','ktypeid','','1','1','1','1','该仓库已关联销售退货单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','SaleBill','ktypeid','','1','1','1','1','该仓库已关联销售出库单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','SaleGoodsExchangeBill','ktypeid','','1','1','1','1','该仓库已关联销售换货单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','SaleGoodsExchangeBill','ktypeid2','','1','1','1','1','该仓库已关联销售换货单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','StockCheckIndex','ktypeid','','1','1','1','1','该仓库已在库存盘点单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','StypeMoveBill','ktypeid','','1','1','1','1','该仓库已关联分支机构调拨出库单或分支机构调拨入库单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','StypeMoveBill','ktypeid2','','1','1','1','1','该仓库已关联分支机构调拨出库单或分支机构调拨入库单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','V_LendStatus','ktypeid','Qty<>0','1','1','1','1','该仓库有借进借出')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','wx_goodsstocks','ktypeid','Qty<>0','1','1','1','1','该仓库库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Wx_iniGoodsstocks','ktypeid','Qty<>0','1','1','1','1','该仓库维修品库存期初余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','wx_inigoodsstocks','ktypeid','Qty<>0','1','1','1','1','该仓库库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','adpricebill','ktypeid','','1','1','1','1','该仓库已在成本调价单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','AppraisalBill','ktypeid','','1','1','1','1','该仓库在暂估入库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','AppraisalBackBill','ktypeid','','1','1','1','1','该仓库在暂估退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','ReceiptBill','ktypeid','','1','1','1','1','该仓库在采购或销售开票中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','SendBill','ktypeid','','1','1','1','1','该仓库在发出商品出库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','SendBackBill','ktypeid','','1','1','1','1','该仓库在发出商品退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Custom_BillDetails','SysDiy15','','1','1','1','1','该仓库已在表体自定义15中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Custom_BillIndex','SysDiy15_head','','1','1','1','1','该仓库已在表头自定义15中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','GP_initLendPTypeSerial','ktypeid','','1','1','1','1','该仓库有借欠期初序列号')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Stock','typeid','WdSyncFlag = 1','1','0','1','0','该仓库已同步到全渠道')

--======================商品档案===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PosAllotApplyBill','ptypeid','','1','1','1','1','已被调货申请使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','AskPriceBill','ptypeid','','1','1','1','1','已被询价单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','Billindex','ptypeid','','1','1','1','1','该商品已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','DeliveryApplyBill','ptypeid','','1','1','1','1','该商品已经被要货单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','DeliveryBill','ptypeid','','1','1','1','1','该商品已经被门店配送单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','DeliveryBackBill','ptypeid','','1','1','1','1','该商品已经被门店配送退货单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','DeliveryCheckBill','ptypeid','','1','1','1','1','该商品已经被配送验收单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CommissionStock','ptypeid','','1','1','1','1','该商品有代销情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CommonPosPtypeCheckList','ptypeid','','1','1','1','1','该商品已在pos中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CommonPosSaleList','ptypeid','','1','1','1','1','该商品已在pos中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CX_CombinationDetailBill','ptypeid','','1','1','1','1','该商品已在pos中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CX_LargessBill','ptypeid','','1','1','1','1','该商品已在pos中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CX_SpecialOfferBill','ptypeid','','1','1','1','1','该商品已在pos中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','goodsstocks','ptypeid','Qty <> 0','1','1','1','1','该商品库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','gp_CruPtypeSerial','ptypeid','','1','1','1','1','该商品有序列号关联情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','gp_initPtypeSerial','ptypeid','','1','1','1','1','该商品有期初序列号关联情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','gp_LENDPtypeserial','ptypeid','','1','1','1','1','该商品有借欠序列号')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','iniCommissionStock','ptypeid','','1','1','1','1','该商品有代销情况')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','inigoodsstocks','ptypeid','(Qty <> 0 OR Total<>0)','1','1','1','1','该商品库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','InOutStockTable','ptypeid','Qty <> 0','1','1','1','1','该商品已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','IntegralExchangeBill','ptypeid','','1','1','1','1','该商品已被关联积分兑换')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','LENDBill','ptypeid','Qty <> 0','1','1','1','1','该商品已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','OrderBill','ptypeid','','1','1','1','1','该商品已在订单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PriceDetail','ptypeid','','1','0','1','1','该商品已在价格表档案中使用')/*9.6 删除不再判断*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PriceTrack','ptypeid','','1','0','1','1','该商品已在价格跟踪中使用')	/*9.6 删除不再判断*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','produceModel','ptypeid','','1','1','1','1','该商品有生产模板')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','produceModelIndex','ptypeid','','1','1','1','1','该商品有生产模板')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PromoRule_Detail_PConfig','ptypeid','','1','1','1','1','该商品已关联促销')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PromotePrice','ptypeid','','1','1','1','1','该商品已在促销中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PType_STypePrice','ptypeid','(PreBuyPrice1<>0 or PreBuyPrice2<>0 or PreBuyPrice3<>0 or PreBuyPrice4<>0 or PreBuyPrice5<>0)','1','0','1','1','该商品在分支机构物价信息中使用') /*9.6 删除不再判断*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PuserCode','ptypeid','','1','0','1','1','该商品设置了多编码') /*9.6 删除不再判断*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','QP_EvaluationBill_PType','ptypeid','','1','1','1','1','该商品已被备料估价单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','QP_InsuranceBill_PType','ptypeid','','1','1','1','1','该商品已经经营过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','QP_QuickRepairBill_PType','ptypeid','','1','1','1','1','该商品已被快修单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','QP_RecycleBill','ptypeid','','1','1','1','1','该商品已被旧件回收单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','QP_RepairSETMeal_Fittings','ptypeid','','1','1','1','1','该商品设置了维修套餐')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','QuotePriceBill','ptypeid','','1','1','1','1','该商品已被报价单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','RepairEngage','ptypeid','','1','1','1','1','该商品已在维修中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','RetailBackBill','ptypeid','','1','1','1','1','该商品在零售退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','stockcheck','ptypeid','','1','1','1','1','该商品有盘点单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','V_LENDStatus','ptypeid','Qty <> 0','1','1','1','1','该商品有借进借出')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','wx_goodsstocks','ptypeid','Qty <> 0','1','1','1','1','该商品库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','wx_inigoodsstocks','ptypeid','Qty <> 0','1','1','1','1','该商品库存余量不为零')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','BuyBill','ptypeid','','1','1','1','1','该商品在单据中已保存草稿或过账')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CommissionRulePtype','ptypeid','','1','1','1','1','该商品已在提成规则职员商品设置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PromoRule_Detail_PromotConfig','ptypeid','','1','1','1','1','该商品已在促销中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','GiveBill','ptypeid','','1','1','1','1','该商品已在赠送单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','GivemeBill','ptypeid','','1','1','1','1','该商品已在获赠单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','SaleGoodsExchangeBill','ptypeid','','1','1','1','1','该商品已在销售换货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','AdPriceBill','ptypeid','','1','1','1','1','该商品已在变价调拨单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','Advantage','ptypeid','','1','1','1','1','该商品已在获利返利中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','BuyBackBill','ptypeid','','1','1','1','1','该商品已在采购退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','BuyGoodsExchangeBill','ptypeid','','1','1','1','1','该商品已在采购换货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CommissionBill','ptypeid','','1','1','1','1','该商品已在代销中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','DisassembleBill','ptypeid','','1','1','1','1','该商品已在生产拆装单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','FaPiaoBill','ptypeid','','1','1','1','1','该商品已在发票中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','LoseBill','ptypeid','','1','1','1','1','该商品已在报损单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','MoveBill','ptypeid','','1','1','1','1','该商品已在同价调拨单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','MoveBjBill','ptypeid','','1','1','1','1','该商品已在变价调拨单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','SerialAdjustBill','ptypeid','','1','1','1','1','该商品已在序列号调整单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','StockCheck','ptypeid','','1','1','1','1','该商品已在库存盘点中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','STypeMoveBill','ptypeid','','1','1','1','1','该商品已在分支机构调拨出库入库中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','TCBill','ptypeid','','0','1','1','1','该商品已在提成中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','OtherInOutBill','ptypeid','','1','1','1','1','该商品已在其他出入库单表中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','overflowBill','ptypeid','','1','1','1','1','该商品已在报溢单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','RequestBill','ptypeid','','1','1','1','1','该商品已在请购单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','retailBill','ptypeid','','1','1','1','1','该商品已在零售单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','RetailCombinationBill','ptypeid','','1','1','1','1','该商品已在零售单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','saleBackBill','ptypeid','','1','1','1','1','该商品已在销售退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','SaleBill','ptypeid','','1','1','1','1','该商品已在销售出库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','DiyTypePTypeID','ptypeid','','1','1','1','1','该商品已在电脑装机商品设置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PType_Units_Ext','ptypeid',' isdefaultunit=0 ','0','0','0','0','该商品设置了多计量单位信息')/*9.6 删除不再判断 要判断存在非基本单位不 存在就是有多单位信息*/ 
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PromoRule_Detail_PromotConfig','BindPtypeId','','0','1','1','0','该商品已在促销捆绑商品中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','DiyBill','ptypeid','','0','1','1','0','该商品已在电脑装机配置单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','AppraisalBill','ptypeid','','1','1','1','1','该商品在暂估入库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','AppraisalBackBill','ptypeid','','1','1','1','1','该商品在暂估退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','ReceiptBill','ptypeid','','1','1','1','1','该商品在采购或销售开票中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','SendBill','ptypeid','','1','1','1','1','该商品在发出商品出库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','SendBackBill','ptypeid','','1','1','1','1','该商品在发出商品退货单中使用')
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CouponApplyPtype','ptypeid','','1','1','1','','该商品在优惠券中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','Custom_BillDetails','SysDiy12','','1','1','1','1','该商品已在表体自定义12中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','Custom_BillIndex','SysDiy12_head','','1','1','1','1','该商品已在表头自定义12中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CombinationProductIndex','CombinationProductPtypeId','','1','1','1','1','该商品已在组合品模版中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CombinationProductDetail','PTypeID','','1','1','1','1','该商品已在组合品模版中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','GP_initLendPTypeSerial','ptypeid','','1','1','1','1','该商品有借欠期初序列号')
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','CouponExchangePtype','ptypeid','','1','1','1','1','该商品已在兑换券中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','WdShopConfig','ptypeid','','1','1','1','1','该商品已在网店配置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','wx_bill_send','ptypeid','','1','1','1','1','该商品已在送修单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','ptype','typeid','WdSyncFlag = 1','1','1','1','1','该商品已经上传到全渠道，请取消同步再分类或删除！')


--======================分支机构===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PosAllotApplyBillIndex','stypeid','','1','1','1','1','该分支机构已在门店类单据或调货申请中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Account','stypeid','','1','1','1','1','该分支机构已在会计科目中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Account_Assist_CheckItems','stypeid','','1','1','1','1','该分支机构已在会计科目辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_AssetsCards','stypeid','','1','1','1','1','该分支机构已在固定资产卡片中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_AssetsCards_History','stypeid','','1','1','1','1','该分支机构已在固定资产卡片中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_AssetsCategory','stypeid','','1','1','1','1','该分支机构已在固定资产类别中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Auditing_Template','stypeid','','1','1','1','1','该分支机构已在过账模版中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Balance','stypeid','','1','1','1','1','该分支机构已在结算方式中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Balance_Assist_CheckItems','stypeid','','1','1','1','1','该分支机构已在科目余额中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Balance_Assist_CheckItems_Detail','stypeid','','1','1','1','1','该分支机构已在科目余额中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_DepreciationPlan','stypeid','','1','1','1','1','该分支机构已在折旧计划中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_FixedAssetsInit_Stype','stypeid','','1','1','1','1','该分支机构已使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_IniAccount','stypeid','','1','1','1','1','该分支机构已在账务期初中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_IniAccount_Assist_CheckItems','stypeid','','1','1','1','1','该分支机构已在账务期初辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_IniAccount_Assist_CheckItems_Detail','stypeid','','1','1','1','1','该分支机构已在期初科目余额中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Items_Detail','stypeid',' ATypeId <>'''' OR DepATypeId<>'''' OR DisATypeId<>'''' ','1','1','1','1','该分支机构已在项目明细中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_MulColumnAccount','stypeid','','1','1','1','1','该分支机构已在多栏账中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_OtherGains','stypeid','','1','1','1','1','该分支机构已使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_ProfitAndLoss','stypeid','','1','1','1','1','该分支机构已在损益类科目中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_ProfitAndLoss_Detail','stypeid','','1','1','1','1','该分支机构已在损益类科目中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Voucher','stypeid','','1','1','1','1','该分支机构已在凭证字中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Voucher_Bill','stypeid','','1','1','1','1','该分支机构已在记账凭证中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Voucher_Bill_CashMoneyItems','stypeid','','1','1','1','1','该分支机构已在会计凭证现金流量中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AccountCredence','stypeid','','1','1','1','1','该分支机构已经关联会计凭证单据')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AccountCredence','ATypeID','TypeATypeID=28','1','1','1','1','该分支机构已经关联业务凭证单据')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AccountCredence','stypeid','','1','1','1','1','该分支机构已在会计凭证中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AdDebtBill','stypeid','','1','1','1','1','该分支机构已在应收应付中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AdPriceBill','stypeid','','1','1','1','1','该分支机构已在成本调价明细中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Advantage','stypeid','','1','1','1','1','该分支机构已在获利返利中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Advantage_standard','stypeid','','1','1','1','1','该分支机构已在获利返利标准中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AskPriceBill','stypeid','','1','1','1','1','该分支机构已在询价单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AType_Total','stypeid','Total00<>0','1','1','1','1','该分支机构已经关联会计科目期初')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AuditingFlowSet','stypeid','','1','1','1','1','该分支机构已在审核设置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BeforePromoteRetailBill','stypeid','','1','1','1','1','该分支机构已在促销前的零售单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BillAtype','stypeid','atypeid<>'' '' ','1','1','1','1','该分支机构已使用')
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BillCode_Seed','stypeid','','1','1','1','1','该分支机构已在单据编号中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BillIndex','stypeid','','1','1','1','1','该分支机构已在单据中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BType_ARAPTotal','stypeid','(ARTotal<>0 or ARTotal00<>0 or APTotal<>0 or APTotal00<>0 or YFTotal<>0 or YFTotal00<>0 or YSTotal<>0 or YSTotal00<>0)','1','1','1','1','该分支机构已经关联会计科目期初')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BType_Credit','stypeid','','1','1','1','1','该分支机构已经关联信用额度')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','btype_credit','stypeid','','1','1','1','1','该分支机构已在单位信用额度中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BtypePriceInfo','stypeid','','1','1','1','1','该分支机构已使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BuyBackBill','stypeid','','1','1','1','1','该分支机构已在采购退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BuyBill','stypeid','','1','1','1','1','该分支机构已在采购单据中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','BuyGoodsExchangeBill','stypeid','','1','1','1','1','该分支机构已在采购退货中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CashMoneyBill','stypeid','','1','1','1','1','该分支机构已在现金银行中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CM_CarUseIndex','stypeid','','1','1','1','1','该分支机构已经关联使用登记单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CM_CarUseIndex','stypeid','','1','1','1','1','该分支机构已在车辆使用中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CM_FeeIndex','stypeid','','1','1','1','1','该分支机构已经关联车辆费用单')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CM_FeeIndex','stypeid','','1','1','1','1','该分支机构已在车辆管理费中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CommissionBill','stypeid','','1','1','1','1','该分支机构已在代销明细中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CommissionStock','stypeid','','1','1','1','1','该分支机构已在代销库存中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CommissionStock_Qty','stypeid','','1','1','1','1','该分支机构已在期初代销库存状况中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','DisassembleBill','stypeid','','1','1','1','1','该分支机构已在生产拆装单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','DtypeSaleplan','stypeid','','1','1','1','1','该分支机构已在部门销售计划中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','employee','stypeid','','1','1','1','1','该分支机构已在职员基本信息中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','EtypeSaleplan','stypeid','','1','1','1','1','该分支机构已在人员销售计划中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','FaPiaoBill','stypeid','','1','1','1','1','该分支机构已在发票中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','FaPiaoBillIndex','stypeid','','1','1','1','1','该分支机构已在发票中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','FrozeBusiness','stypeid','','1','1','1','1','该分支机构已使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','gatheringBill','stypeid','','1','1','1','1','该分支机构已在收款单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','GiveBill','stypeid','','1','1','1','1','该分支机构已在赠送单明细使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','GiveFromSaleOrBuyBill','stypeid','','1','1','1','1','该分支机构已在赠送获赠关联信息中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','GivemeBill','stypeid','','1','1','1','1','该分支机构已在获赠单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','gp_CruPtypeSerial','stypeid','','1','1','1','1','该分支机构已在当前序列号使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','gp_initPtypeSerial','stypeid','','1','1','1','1','该分支机构已在期初序列号中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','inicommissionStock','stypeid',' Qty<>0 and Type=140','1','1','1','1','该分支机构已经关联委托代销期初')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','inicommissionStock','stypeid','Qty<>0 and Type=144','1','1','1','1','该分支机构已经关联受托代销期初')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','IniCommissionStock_Qty','stypeid','','1','1','1','1','该分支机构已在期初代销库存中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','InOutstocktable','stypeid','','1','1','1','1','该分支机构已在出入库汇总中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','IntegralExchangeBill','stypeid','','1','1','1','1','该分支机构已在积分兑换单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','IntercourseSETting','stypeid','','1','1','1','1','该分支机构已关联往来预警')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','ItemType','stypeid','','1','1','1','1','该分支机构已在项目分类中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','LendBill','stypeid','','1','1','1','1','该分支机构已在借欠明细中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','LendIndex','stypeid','','1','1','1','1','该分支机构已在借欠中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','ListTable','stypeid','','1','1','1','1','该分支机构已在钱流单据中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','LoseBill','stypeid','','1','1','1','1','该分支机构已在报损单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','MoneyBill','stypeid','','1','1','1','1','该分支机构已在现金银行中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','MonthATypeHistory','stypeid','','1','1','1','1','该分支机构已在月结历史中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','MoveBill','stypeid','','1','1','1','1','该分支机构已在分支机构调拨中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','MoveBjBill','stypeid','','1','1','1','1','该分支机构已在变价调拨中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','MoveMoneyBill','stypeid','','1','1','1','1','该分支机构已在转款中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','nVipConfiscateConfig','stypeid','','1','1','1','1','该分支机构已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','nVipConfiscateConfig','stypeid','','1','1','1','1','该分支机构已在会员卡充值中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','nVipWashCarTimesConfig','stypeid','','1','1','1','1','该分支机构已经使用过')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','nVipWashCarTimesConfig','stypeid','','1','1','1','1','该分支机构已在洗车次数充值配置中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','OrderBill','stypeid','','1','1','1','1','该分支机构已在订单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','OrderIndex','stypeid','','1','1','1','1','该分支机构已在订单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','OtherInOutBill','stypeid','','1','1','1','1','该分支机构已在其他出入库中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','overflowBill','stypeid','','1','1','1','1','该分支机构已在报溢单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PayBill','stypeid','','1','1','1','1','该分支机构已在付款单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PosDataUpdated','stypeid','','1','1','1','1','该分支机构已使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PosInfo','stypeid','','1','1','1','1','该分支机构已在POS档案使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PosIsUpdateData','stypeid','','1','1','1','1','该分支机构在【PosIsUpdateData】表中已有记录')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PosReDataGlobal','stypeid','','1','1','1','1','该分支机构已使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PosRetailCash','stypeid','','1','1','1','1','该分支机构已经关联pos')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PosRetailCash','stypeid','','1','1','1','1','该分支机构已使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PosUpdatedMaxNumber','stypeid','','1','1','1','1','该分支机构已使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PreBill','stypeid','','1','1','1','1','该分支机构已在预收预付中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceBillIndex_Stype','stypeid','','1','1','1','1','该分支机构已在价格表中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceProtect','stypeid','','1','1','1','1','该分支机构已在价保标准中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceProtectBill','stypeid','','1','1','1','1','该分支机构已在价保中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceProtectList','stypeid','','1','1','1','1','该分支机构已在价保中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceRule_Stype','stypeid','','1','1','1','1','该分支机构已在价格规则中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceRulePriority','stypeid','','1','1','1','1','该分支机构已在价格规则优先级中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceTrack','stypeid','','1','1','1','1','该分支机构已在价格跟踪中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PromoRule_Stype','stypeid','','1','1','1','1','该分支机构已在促销规则中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PType_STypePrice','stypeid','','1','1','1','1','该分支机构已经关联分支机构物价信息')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PType_STypePrice','stypeid','','1','1','1','1','该分支机构已在商品分支机构价格信息中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','QuotePriceBill','stypeid','','1','1','1','1','该分支机构已在报价单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','RequestBill','stypeid','','1','1','1','1','该分支机构已在请购单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','RequestIndex','stypeid','','1','1','1','1','该分支机构已在请购单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','RetailBackBill','stypeid','','1','1','1','1','该分支机构已在零售退货中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','retailBill','stypeid','','1','1','1','1','该分支机构已在零售单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','saleBackBill','stypeid','','1','1','1','1','该分支机构已在销售退货中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','SaleBill','stypeid','','1','1','1','1','该分支机构已在销售出库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','SaleGoodsExchangeBill','stypeid','','1','1','1','1','该分支机构已在销售换货中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','SerialAdjustIndex','stypeid','','1','1','1','1','该分支机构已在序列号调整中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Stock','stypeid','','1','1','1','1','该分支机构已在仓库中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','SType_InnerARTotal','stypeid','','1','1','1','1','该分支机构已在内部应收中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','SType_UserConfig','stypeid',' value=''1'' ','1','1','1','1','该分支机构已在分支机构开账信息中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','STypeMoveBill','stypeid','','1','1','1','1','该分支机构已在分支机构调拨中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','StypeSaleplan','stypeid','','1','1','1','1','该分支机构已经关联销售计划')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','StypeSaleplan','stypeid','','1','1','1','1','该分支机构已在分支机构销售计划中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','tmpGain','stypeid','','1','1','1','1','该分支机构已在月结期间数据中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','ToolIndex','stypeid','','1','1','1','1','该分支机构已在工具中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','UFO_Temple','stypeid','','1','1','1','1','该分支机构已在财务报表模板中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Vacation','stypeid','','1','1','1','1','该分支机构已在考勤节假日中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','WorkTime','stypeid','','1','1','1','1','该分支机构已在考勤节假日中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_Call','stypeid','','1','1','1','1','该分支机构已在报修单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_GetBack','stypeid','','1','1','1','1','该分支机构已在维修取件单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_Goto','stypeid','','1','1','1','1','该分支机构已在上门维修中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_In','stypeid','','1','1','1','1','该分支机构已在维修品调入中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_JieJian','stypeid','','1','1','1','1','该分支机构已在维修接件单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_Move','stypeid','','1','1','1','1','该分支机构已在维修品调拨单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_Out','stypeid','','1','1','1','1','该分支机构已在维修品调出单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_Replace','stypeid','','1','1','1','1','该分支机构已在整机更换单使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_Self','stypeid','','1','1','1','1','该分支机构已在维修单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_Send','stypeid','','1','1','1','1','该分支机构已在送修单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_Bill_SendBack','stypeid','','1','1','1','1','该分支机构已在送修返回中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','wx_InOutStockTable','stypeid','','1','1','1','1','该分支机构已在维修商品出入库中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Te_StartPeriod','stypeid','IsUse=1','1','1','1','1','该分支机构已在出纳管理中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','CommissionSchemeStype','stypeid','','1','1','1','1','该分支机构已在提成方案中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','FixedAssetsIndex','stypeid','','1','1','1','1','该分支机构已在固定资产盘点单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Voucher_Commonly','stypeid','','1','1','1','1','该分支机构已在常用凭证模板中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','DefaultStock','Stypeid','','1','1','1','1','该分支机构已在商品默认仓库中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_Voucher_Commonly_Bill','stypeid','','1','1','1','1','该分支机构已在常用凭证模板中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Ac_VoucherCommonly_Bill_Assist_CheckItems','typeid','typeName=''01''','1','1','1','1','该分支机构已在常用凭证模板辅助核算中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AppraisalBill','stypeid','','1','1','1','1','该分支机构在暂估入库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AppraisalBackBill','stypeid','','1','1','1','1','该分支机构在暂估退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','ReceiptBill','stypeid','','1','1','1','1','该分支机构在采购或销售开票中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','SendBill','stypeid','','1','1','1','1','该分支机构在发出分支机构出库单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','SendBackBill','stypeid','','1','1','1','1','该分支机构在发出分支机构退货单中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Custom_BillDetails','SysDiy13','','1','1','1','1','该分支机构已在表体自定义16中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Custom_BillIndex','SysDiy13_head','','1','1','1','1','该分支机构已在表头自定义16中使用')
/*分支机构关联凭证辅助核算*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('STYPE','Ac_Voucher_Bill_Assist_CheckItems','TypeId','typeName = ''01''','1','1','1','1','该分支机构已在凭证辅助核算中使用')

/*判断分支机构是否在会员管理中使用*/
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','nVipCardSignStype','stypeid','(cZyeMoney<>0 or lJxFMoney<>0 or bNxFMoney<>0) ','1','1','1','1','该分支机构已在会员管理中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','stypepayconfiginfo','stypeid','','1','1','1','1','该分支机构已在支付宝或微信结算设置中使用')--982bug230，231

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','nVipCardSign','jkStypeId','','1','0','1','1','该分支机构已在会员卡管理信息建卡机构中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','VipCard_ApplyStype','StypeId','','1','0','1','1','该分支机构已在会员卡管理信息适用机构中使用')
-------------------------------------------9.8新增表 基本信息操作控制---------------------------------------



----------实物库存
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','IniFactStocks','PTypeId','','1','1','1','1','该商品已在实物库存期初中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','IniFactStocks','KTypeId','','1','1','1','1','该仓库已在实物库存期初中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','IniFactStocks_Qty','PTypeId','','1','1','1','1','该商品已在实物库存期初中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','IniFactStocks_Qty','KTypeId','','1','1','1','1','该仓库已在实物库存期初中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','FactInOut','KTypeId','','1','1','1','1','该仓库已在期初未实物出入库单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','FactInOut','PTypeId','','1','1','1','1','该商品已在期初未实物出入库单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','FactDepotInOut','PTypeId','','1','1','1','1','该商品已在仓库出入库单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','FactDepotInOut','KTypeId','','1','1','1','1','该仓库已在仓库出入库单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','FactDepotAllot','PTypeId','','1','1','1','1','该商品已在仓库调拨单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','FactIndex','STypeId','','1','1','1','1','该分支机构已在实物单据中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','FactDepotAllot','KTypeId','','1','1','1','1','该仓库已在仓库调拨单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('Stock','FactIndex','ktypeid','','1','1','1','1','该仓库已在实物单据中使用')--呃，BaseinfoType是'Stock',难怪一直不行,差点看瞎



-------组合品
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PT_Combin_OrderBill','PTypeId','','1','1','1','1','该商品已在组合品订单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','PT_Combin_OrderBill','KTypeId','','1','1','1','1','该仓库已在组合品订单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PT_Combin_OrderBill','STypeId','','1','1','1','1','该分支机构已在组合品订单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PT_Combin_SaleBill','STypeId','','1','1','1','1','该分支机构已在组合品销售出库单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PT_Combin_SaleBill','PTypeId','','1','1','1','1','该商品已在组合品销售出库单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','PT_Combin_SaleBill','KTypeId','','1','1','1','1','该仓库已在组合品销售出库单中使用') 

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PT_Combin_SaleBillDetail','STypeId','','1','1','1','1','该分支机构已在组合品销售出库单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PT_Combin_SaleBillDetail','PTypeId','','1','1','1','1','该商品已在组合品销售出库单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','PT_Combin_SaleBillDetail','KTypeId','','1','1','1','1','该仓库已在组合品销售出库单中使用') 

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PT_Combin_SaleBackBill','STypeId','','1','1','1','1','该分支机构已在组合品销售退货单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PT_Combin_SaleBackBill','PTypeId','','1','1','1','1','该商品已在组合品销售退货单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','PT_Combin_SaleBackBill','KTypeId','','1','1','1','1','该仓库已在组合品销售退货单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PT_Combin_SaleBackBillDetail','STypeId','','1','1','1','1','该分支机构已在组合品销售退货单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PT_Combin_SaleBackBillDetail','PTypeId','','1','1','1','1','该商品已在组合品销售退货单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','PT_Combin_SaleBackBillDetail','KTypeId','','1','1','1','1','该仓库已在组合品销售退货单中使用')


----其他
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','UnitsTrack','PTypeId','','1','1','1','1','该商品已在计量单位跟踪信息中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','UnitsTrack','BTypeId','','1','1','1','1','该往来单位已在计量单位跟踪信息中使用')


INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','PT_SaleOrderLockDetail','ETypeId','','1','1','1','1','该职员已在销售订单锁库明细表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','PT_SaleOrderLockDetail','KTypeId','','1','1','1','1','该仓库已在销售订单锁库明细表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','ChargeOffBill','BTypeId','','1','1','1','1','该往来单位已在往来核销单详细中使用')

--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Base_FixedReasonForChangeDetails','STypeId','','1','1','1','1','该分支机构已在固定资产变更原因明细中使用')

--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceTrack_SType_Send','STypeId','','1','1','1','1','该分支机构已在发出商品分支机构间价格跟踪表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PriceTrack_SType_Send','PTypeId','','1','1','1','1','该商品已在发出商品分支机构间价格跟踪表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','PriceTrack_STypeMove','PTypeId','','1','1','1','1','该商品已在分支结构调拨单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceTrack_STypeMove','InSTypeID','','1','1','1','1','该分支机构已在分支结构调拨单中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','PriceTrack_STypeMove','OutSTypeID','','1','1','1','1','该分支机构已在分支结构调拨单中使用')

------物流

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ktype','onShelvespickIndex','Ktypeid','','1','1','1','1','该仓库已在上架单拣货单主表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','onShelvespickIndex','Etypeid','','1','1','1','1','该职员已在上架单拣货单主表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','onShelvespickIndex','Checke','','1','1','1','1','该职员已在上架单拣货单主表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','onShelvespickIndex','Updatee','','1','1','1','1','该职员已在上架单拣货单主表中使用')
 
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','onShelvespickIndex','Poster','','1','1','1','1','该职员已在上架单拣货单主表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','onShelvespickIndex','Dtypeid','','1','1','1','1','该部门已在上架单拣货单主表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','onShelvespickIndex','Stypeid','','1','1','1','1','该分支机构已在上架单拣货单主表中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','onShelvesbill','Ptypeid','','1','1','1','1','该商品已在上架单明细中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','pickbill','Ptypeid','','1','1','1','1','该商品已在拣货单明细中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','Transportbill','Ptypeid','','1','1','1','1','该商品已在运输单明细中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AssetIncChangeBill','STypeId','','1','1','1','1','该商品已在固定资产卡片变更中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','AssetIncChangeBill','ETypeId','','1','1','1','1','该职员已在固定资产卡片变更中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','AssetIncChangeBill','DTypeid','','1','1','1','1','该部门已在固定资产卡片变更中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','AssetIncSplit','DTypeid','','1','1','1','1','该部门已在固定资产拆分中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','AssetIncSplit','checke','','1','1','1','1','该职员已在固定资产拆分中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','AssetIncSplit','checker','','1','1','1','1','该职员已在固定资产拆分中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','AssetIncSplit','etypeid','','1','1','1','1','该职员已在固定资产拆分中使用')

INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','AssetIncSplit','stypeid','','1','1','1','1','该分支机构已在固定资产拆分中使用')

-------------------------------------------9.8新增表 基本信息操作控制 结束---------------------------------------


--=============================9.8.3 基本信息操作控制【BEGIN】==========================

--===================会计科目============
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','Coupon_BillIndex','ATypeID','','1','1','1','1','该会计科目已在优惠券单据中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('atype','Coupon_BillIndex','ATypeID1','','1','1','1','1','该会计科目已在优惠券单据中使用')

--===================商品档案============
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','coupon_ApplyPtype','PtypeId',' IsExchangePtype = 1 ','1','1','1','1','该商品档案已在优惠券名称中使用')--优惠券兑换券关联商品
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','coupon_ApplyPtype','PtypeId',' IsExchangePtype = 0 ','0','1','1','1','该商品档案已在优惠券名称中使用')--优惠券关联商品
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','Coupon_OutBill_Ptype','PtypeId','','1','1','1','1','该商品档案已在优惠券单据中使用')--优惠券出库单_下表体

--===================职员============
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','Coupon_BillIndex','ETypeID','','1','1','1','1','该职员已在优惠券单据中使用')

--======================仓库===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Coupon_BillIndex','InKTypeId','','1','1','1','1','该仓库已在优惠券单据中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Coupon_BillIndex','OutKTypeID','','1','1','1','1','该仓库已在优惠券单据中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stock','Coupon_CodeInfo','KTypeID','','1','1','1','1','该仓库已在优惠券单据中使用')
--======================分支机构===================
--INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','coupon_ApplyStype','STypeID','','1','1','1','1','该分支机构已在优惠券适用机构中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','Coupon_BillIndex','STypeID','','1','1','1','1','该分支机构已在优惠券单据中使用')--优惠券单据表头

--======================部门===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('department','Coupon_BillIndex','DTypeID','','1','1','1','1','该部门已在优惠券单据中使用')

--======================往来单位===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','Coupon_BillIndex','BTypeID','','1','1','1','1','该往来单位已在优惠券单据中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','Coupon_BillIndex','DealBTypeID','','1','1','1','1','该往来单位已在优惠券单据中使用')





--POS终端管辖

--===================商品============
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('ptype','POSPtype','PtypeId','','0','0','0','0','该商品已在POS权限管辖中使用')

--===================职员============
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('employee','POSEmployee','ETypeID','','0','0','0','0','该职员已在POS权限管辖中使用')

--======================往来单位===================
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','POSBtype','TypeID','','0','0','0','0','该往来单位已在POS权限管辖中使用')


INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('btype','btype','typeid','WdSyncFlag = 1','1','0','1','0','该客户档案信息已同步到全渠道')

--=============================9.8.3 基本信息操作控制【END】  ==========================

--985版本新增
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','nVipCardSign','jkstypeId','','1','1','1','1','该分支机构已在会员管理信息-建卡机构中使用')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain) VALUES('stype','VipCard_ApplyStype','StypeId','','1','1','1','1','该分支机构已在会员管理信息-适用机构中使用')

--987新增
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain)VALUES('ptype','WmsErpPtypeContrastSetting','erp_typeid','','1','1','1','1','该商品已在WMS系统中使用，请先删除对应关系')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain)VALUES('btype','WmsErpbtypeContrastSetting','erp_typeid','','1','1','1','1','该单位已在WMS系统中使用，请先删除对应关系')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain)VALUES('employee','WmsErpemployeeContrastSetting','erp_typeid','','1','1','1','1','该职员已在WMS系统中使用，请先删除对应关系')
INSERT INTO BaseInfoAssitDetection (BaseinfoType,TableName,TableColumnname,Conditions,IfCategory,IfDelete,IfMove,IfUsed,Explain)VALUES('stock','WmsErpstockContrastSetting','erp_typeid','','1','1','1','1','该仓库已在WMS系统中使用，请先删除对应关系')

-------------------------------表预制数据----------------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('BaseInfoTreeExpand') AND  type = 'U')
BEGIN
	CREATE TABLE BaseInfoTreeExpand
	(
		BaseInfoName	VARCHAR(100),
		IsExpand		BIT,
		ETypeid			VARCHAR(50)
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BaseInfoXiWaMaxNumber]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE BaseInfoXiWaMaxNumber
	(
		TableName	VARCHAR(50),
		XiWaMaxNumber numeric(18, 0) NULL DEFAULT (0)
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BatchPrice]    脚本日期: 05/05/2010 14:46:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BatchPrice]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BatchPrice](
		[id] [int] IDENTITY(1,1) NOT NULL,
		[DepartId] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[DepartUserCode] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[DepartFullName] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
		[PTypeId] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[PUserCode] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[PFullName] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
		[PEntryCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PStandard] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PrePrice1] [numeric](18, 4) NULL CONSTRAINT [DF_BatchPrice_PrePrice1]  DEFAULT (0),
		[PrePrice2] [numeric](18, 4) NULL CONSTRAINT [DF_BatchPrice_PrePrice2]  DEFAULT (0),
		[PrePrice3] [numeric](18, 4) NULL CONSTRAINT [DF_BatchPrice_PrePrice3]  DEFAULT (0),
		[PrePrice4] [numeric](18, 4) NULL CONSTRAINT [DF_BatchPrice_PrePrice4]  DEFAULT (0),
		[recPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BatchPrice_recPrice]  DEFAULT (0),
		[Explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BatchPrice_Explain]  DEFAULT (''),
		[Default] [int] NULL CONSTRAINT [DF_BatchPrice_Default]  DEFAULT (0)		
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BatchPrice]') AND name = N'PK_BatchPrice')
--ALTER TABLE [dbo].[BatchPrice] DROP CONSTRAINT [PK_BatchPrice]
--GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BATCHPRICE') AND name = 'CIX_BATCHPRICE_id')
--DROP INDEX CIX_BATCHPRICE_id ON BATCHPRICE 
CREATE CLUSTERED INDEX CIX_BATCHPRICE_id ON BATCHPRICE(id) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BatchPrice' AND a.Name='PrePrice1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BatchPrice 
	ALTER COLUMN PrePrice1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BatchPrice' AND a.Name='PrePrice2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BatchPrice 
	ALTER COLUMN PrePrice2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BatchPrice' AND a.Name='PrePrice3' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BatchPrice 
	ALTER COLUMN PrePrice3 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BatchPrice' AND a.Name='PrePrice4' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BatchPrice 
	ALTER COLUMN PrePrice4 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BatchPrice' AND a.Name='recPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BatchPrice 
	ALTER COLUMN recPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



 IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('BATypeIdPreset') AND  type = 'U')
BEGIN
	CREATE TABLE BATypeIdPreset
	(
	Id			INT IDENTITY(1,1),
	BTypeName	VARCHAR(100),
	UserCode	VARCHAR(200),
	FullName	VARCHAR(200),
	SubId			INT
	)
END
GO
DELETE FROM BATypeIdPreset

IF NOT EXISTS(SELECT TOP 1 1 FROM BATypeIdPreset)
BEGIN
	INSERT INTO dbo.BATypeIdPreset
	        ( BTypeName ,
	          UserCode ,
	          FullName ,
	          SubId
	        )
	VALUES  
	('本年利润科目','4103','本年利润',28),
	('利润分配科目','4104','利润分配',28),
	('汇兑损益科目','6603','财务费用',28),
	('存货科目','1405','库存商品',28),
	('销售出库单','1122','应收账款',28),
	('销售退货单','1122','应收账款',28),
	('销售换货单','1122','应收账款',28),
	('委托代销结算单','1122','应收账款',28),
	('采购入库单','220201','应付货款',28),
	('采购退货单','220201','应付货款',28),
	('采购换货单','220201','应付货款',28),
	('受托代销结算单','220201','应付货款',28),
	('维修取件单','1122','应收账款',28),
	('整机更换单','1122','应收账款',28),
	('送修返回单','220201','应付货款',28),
	('上门维修单','1122','应收账款',28),
	('应收增加','1122','应收账款',28),
	('应收减少','1122','应收账款',28),
	('应付增加','220201','应付货款',28),
	('应付减少','220201','应付货款',28),
	('预收款单','2203','预收账款',28),
	('预付款单','1123','预付账款',28),
	('返利执行单','1122','应收账款',28),
	('获利执行单','220201','应付货款',28),
	('价保执行单','1122','应收账款',28),
	('获得价保','220201','应付货款',28),
	('收款单','1122','应收账款',28),
	('付款单','220201','应付货款',28),
	('会员储值充值单','1122','应收账款',28),
	('固定资产(项目)变卖','1122','应收账款',28),
	('固定资产(项目)购买','220201','应付货款',28),
	('费用单（供货商）','220201','应付货款',28),
	('费用单（客户）','1122','应收账款',28),
	('其他收入单','1221','其他应收款',28),
	('本年利润科目','3103','本年利润',2),
	('利润分配科目','3104','利润分配',2),
	('汇兑损益科目','5603','财务费用',2),
	('存货科目','1405','库存商品',2),
	('销售出库单','1122','应收账款',2),
	('销售退货单','1122','应收账款',2),
	('销售换货单','1122','应收账款',2),
	('委托代销结算单','1122','应收账款',2),
	('采购入库单','220201','应付货款',2),
	('采购退货单','220201','应付货款',2),
	('采购换货单','220201','应付货款',2),
	('受托代销结算单','220201','应付货款',2),
	('维修取件单','1122','应收账款',2),
	('整机更换单','1122','应收账款',2),
	('送修返回单','220201','应付货款',2),
	('上门维修单','1122','应收账款',2),
	('应收增加','1122','应收账款',2),
	('应收减少','1122','应收账款',2),
	('应付增加','220201','应付货款',2),
	('应付减少','220201','应付货款',2),
	('预收款单','2203','预收账款',2),
	('预付款单','1123','预付账款',2),
	('返利执行单','1122','应收账款',2),
	('获利执行单','220201','应付货款',2),
	('价保执行单','1122','应收账款',2),
	('获得价保','220201','应付货款',2),
	('收款单','1122','应收账款',2),
	('付款单','220201','应付货款',2),
	('会员储值充值单','1122','应收账款',2),
	('固定资产(项目)变卖','1122','应收账款',2),
	('固定资产(项目)购买','220201','应付货款',2),
	('费用单（供货商）','220201','应付货款',2),
	('费用单（客户）','1122','应收账款',2),
	('其他收入单','1221','其他应收款',2),
	('本年利润科目','3131','本年利润',1),
	('利润分配科目','314115','利润分配',1),
	('汇兑损益科目','5503','财务费用',1),
	('存货科目','1243','库存商品',1),
	('销售出库单','1131','应收账款',1),
	('销售退货单','1131','应收账款',1),
	('销售换货单','1131','应收账款',1),
	('委托代销结算单','1131','应收账款',1),
	('采购入库单','212101','应付货款',1),
	('采购退货单','212101','应付货款',1),
	('采购换货单','212101','应付货款',1),
	('受托代销结算单','212101','应付货款',1),
	('维修取件单','1131','应收账款',1),
	('整机更换单','1131','应收账款',1),
	('送修返回单','212101','应付货款',1),
	('上门维修单','1131','应收账款',1),
	('应收增加','1131','应收账款',1),
	('应收减少','1131','应收账款',1),
	('应付增加','212101','应付货款',1),
	('应付减少','212101','应付货款',1),
	('预收款单','2131','预收账款',1),
	('预付款单','1151','预付账款',1),
	('返利执行单','1131','应收账款',1),
	('获利执行单','212101','应付货款',1),
	('价保执行单','1131','应收账款',1),
	('获得价保','212101','应付货款',1),
	('收款单','1131','应收账款',1),
	('付款单','212101','应付货款',1),
	('会员储值充值单','1131','应收账款',1),
	('固定资产(项目)变卖','1131','应收账款',1),
	('固定资产(项目)购买','212101','应付货款',1),
	('费用单（供货商）','212101','应付货款',1),
	('费用单（客户）','1131','应收账款',1),
	('其他收入单','1133','其他应收款',1),
	('固定资产减少','1122','应收账款',28),
	('固定资产减少','1122','应收账款',2),
	('固定资产减少','1131','应收账款',1),
	('固定资产增加','220201','应付货款',28),
	('固定资产增加','220201','应付货款',2),
	('固定资产增加','212101','应付货款',1),
	('会员批量储值充值单','1131','应收账款',1),
	('会员批量储值充值单','1122','应收账款',2),
	('会员批量储值充值单','1122','应收账款',28),
	
	--发票立账相关往来科目
	('暂估入库单','212102','应付暂估',1),
	('暂估入库单','220202','应付暂估',2),
	('暂估入库单','220202','应付暂估',28),
	('暂估退货单','212102','应付暂估',1),
	('暂估退货单','220202','应付暂估',2),
	('暂估退货单','220202','应付暂估',28),
	('采购暂估开票（借）','212102','应付暂估',1),
	('采购暂估开票（借）','220202','应付暂估',2),
	('采购暂估开票（借）','220202','应付暂估',28),
	('采购暂估开票（贷）','212101','应付货款',1),
	('采购暂估开票（贷）','220201','应付货款',2),
	('采购暂估开票（贷）','220201','应付货款',28),
	('发出商品开票','1131','应收账款',1),
	('发出商品开票','1122','应收账款',2),
	('发出商品开票','1122','应收账款',28),
	('成本调价单（入库）','212102','应付暂估',1),
	('成本调价单（入库）','220202','应付暂估',2),
	('成本调价单（入库）','220202','应付暂估',28)
	
	--9.8新增组合品销售出库单、组合品销售退货单
	,('组合品销售出库单','1131','应收账款',1)
	,('组合品销售出库单','1122','应收账款',2)
	,('组合品销售出库单','1122','应收账款',28)
	,('组合品销售退货单','1131','应收账款',1)
	,('组合品销售退货单','1122','应收账款',2)
	,('组合品销售退货单','1122','应收账款',28)
	,('运输配送单','212101','应付货款',1)
	,('运输配送单','220201','应付货款',2)
	,('运输配送单','220201','应付货款',28)
	
	
	--=====================9.8.3优惠券入库单、优惠券出库单 优惠券退货单=======================
	,('优惠券入库单','212101','应付货款',1)
	,('优惠券入库单','220201','应付货款',28)
	,('优惠券入库单','220201','应付货款',2)
	
	,('优惠券出库单','1131','应收账款',1)
	,('优惠券出库单','1122','应收账款',28)
	,('优惠券出库单','1122','应收账款',2)
	
	,('优惠券退货单','1131','应收账款',1)
	,('优惠券退货单','1122','应收账款',28)
	,('优惠券退货单','1122','应收账款',2)
END

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BBS_catalog]    脚本日期: 05/05/2010 14:46:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BBS_catalog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BBS_catalog](
		[NUM] [int] IDENTITY(1,1) NOT NULL,
		[barname] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[layer1] [int] NULL,
		[layer2] [int] NOT NULL CONSTRAINT [DF_BBS_catalog_layer2]  DEFAULT (1),
		[layer3] [int] NOT NULL CONSTRAINT [DF_BBS_catalog_layer3]  DEFAULT (1),
		[layer4] [int] NOT NULL CONSTRAINT [DF_BBS_catalog_layer4]  DEFAULT (1),
		[layer5] [int] NOT NULL CONSTRAINT [DF_BBS_catalog_layer5]  DEFAULT (1),
		[layer6] [int] NOT NULL CONSTRAINT [DF_BBS_catalog_layer6]  DEFAULT (1),
		[bardescript] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[url] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[parent] [int] NULL,
		[son] [int] NULL,
		[soncount] [int] NOT NULL CONSTRAINT [DF_BBS_catalog_soncount]  DEFAULT (0),
		[levelnum] [int] NULL CONSTRAINT [DF_BBS_catalog_levelnum]  DEFAULT (1),
		[powername0] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[store] [int] NOT NULL CONSTRAINT [DF_BBS_catalog_store]  DEFAULT (0),
		[nsave] [int] NULL,
		[breed] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BBS_luntan]    脚本日期: 05/05/2010 14:46:44 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BBS_luntan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BBS_luntan](
		[num] [int] IDENTITY(1,1) NOT NULL,
		[title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[texts] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[dates] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[lastdates] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[author] [char](50) COLLATE Chinese_PRC_CI_AS NULL,
		[reply] [int] NOT NULL CONSTRAINT [DF_BBS_luntan_reply]  DEFAULT (0),
		[new_number] [int] NULL,
		[re_number] [int] NULL,
		[img] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[clicknum] [int] NOT NULL CONSTRAINT [DF_BBS_luntan_clicknum]  DEFAULT (0),
		[htmlcode] [int] NULL,
		[image] [image] NULL,
		[imagelength] [int] NULL,
		[imagetype] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[haveimage] [int] NULL,
		[filename] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BBS_luntan' AND a.Name='texts' and a.xtype=35
)
BEGIN
	ALTER TABLE BBS_luntan ALTER COLUMN texts VARCHAR(MAX)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BBS_userinformation]    脚本日期: 05/05/2010 14:46:45 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BBS_userinformation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BBS_userinformation](
		[typeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[exp] [int] NOT NULL CONSTRAINT [DF_BBS_userinformation_exp]  DEFAULT (0),
		[store] [int] NOT NULL CONSTRAINT [DF_BBS_userinformation_store]  DEFAULT (0),
		[articlenumber] [int] NOT NULL CONSTRAINT [DF_BBS_userinformation_articlenumber]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BBSUpFiles]    脚本日期: 05/05/2010 14:46:46 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BBSUpFiles]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BBSUpFiles](
		[BBSID] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[FileName] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[BinaryContent] [image] NULL,
		[ContentType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[ContentLength] [int] NULL,
		[szDate] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BillIndex]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BeforePromoteIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE BeforePromoteIndex(
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillCode] [varchar](200)  NULL  DEFAULT (''),		
	) ON [PRIMARY]


END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table dbo.BeforePromoteRetailBill    脚本日期: 05/05/2010 14:49:02 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BeforePromoteRetailBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BeforePromoteRetailBill](
		BillNumberId		numeric(10, 0) NOT NULL,
		PtypeId				varchar(50) NULL,
		Qty					numeric(18, 4) NOT NULL,
		SalePrice			numeric(18, 4) NULL,
		discount			numeric(18, 4) NULL DEFAULT (1),
		DiscountPrice		numeric(18, 4) NULL,
		costprice			numeric(18, 4) NULL DEFAULT (0),
		jobnumber			varchar(20)   NULL,
		goodsno				int NULL,
		total				numeric(18, 4) NULL,
		OutFactoryDate		datetime NULL,
		TaxPrice			numeric(18, 4) NULL,
		TaxTotal			numeric(18, 4) NULL,
		comment				varchar(255)   NULL,
		OrderID				int NULL  DEFAULT ('-1'),
		TeamNo				int NULL,
		ID					int IDENTITY(1,1) NOT NULL,
		TeamNO1				int NULL,
		IsUnit2				int NOT NULL  DEFAULT (0),
		Serial				text NULL  DEFAULT (''),
		InputCostPrice		numeric(18, 4) NULL  DEFAULT (0),
		GoodsOrder			int NULL DEFAULT ('-1'),
		GoodsNumber			varchar(100) NULL DEFAULT (''),
		ProduceDate			varchar(50) NULL DEFAULT (''),
		ValidDate			varchar(50) NULL DEFAULT (''),
		GoodsBTypeID		varchar(50) NULL DEFAULT (''),
		GoodsCostPrice		numeric(18, 4) NULL DEFAULT (0),
		GoodsCostTotal		numeric(18, 2) NULL DEFAULT (0),
		HandZeroCost		int NULL DEFAULT (0),
		BackQTY				numeric(18, 4) NULL DEFAULT (0),
		SaleTotal			numeric(18, 4) NULL DEFAULT (0),
		Tax					numeric(5, 2) NULL DEFAULT (0),
		Stypeid				varchar(50) NULL DEFAULT (''),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift				 int NOT NULL  DEFAULT(0),
		[PriceDetailId] INT NOT NULL DEFAULT(0),
		[PriceRuleId] INT NOT NULL DEFAULT(0),
		[PriceSource] VARCHAR(200) NOT NULL DEFAULT(''),
		ShowOrder INT DEFAULT(0)
		,CouponCode	VARCHAR(200) DEFAULT('')		--优惠券券编码，目前在兑换券的时候会使用
		,IsPromotion	INT DEFAULT(1)					--使用优惠券后，是否参与促销
		,IsVipPoint INT DEFAULT(1)					--使用优惠券后，是否参与会员积分
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BeforePromoteRetailBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.BeforePromoteRetailBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE BeforePromoteRetailBill SET ShowOrder=ID WHERE ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='PriceDetailId'
)
BEGIN
	ALTER TABLE BeforePromoteRetailBill ADD PriceDetailId INT NOT NULL DEFAULT(0)
END
go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='PriceRuleId'
)
BEGIN
	ALTER TABLE BeforePromoteRetailBill ADD PriceRuleId INT NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='PriceSource'
)
BEGIN
	ALTER TABLE BeforePromoteRetailBill ADD PriceSource VARCHAR(200) NOT NULL DEFAULT('')
END
go


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='etypeid'
)
BEGIN
	ALTER TABLE BeforePromoteRetailBill ADD etypeid VARCHAR(200) NOT NULL DEFAULT('')
END
go

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='Serial' AND a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('BeforePromoteRetailBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table BeforePromoteRetailBill drop constraint '+@dfname);
		
	ALTER TABLE BeforePromoteRetailBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE BeforePromoteRetailBill ADD CONSTRAINT DF_BeforePromoteRetailBill_Serial DEFAULT('') FOR Serial
END
go

-- 是否是赠品
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='IsGift'
)
BEGIN
	ALTER TABLE BeforePromoteRetailBill ADD IsGift INT NOT NULL DEFAULT(0);
END
go

--优惠券券编码，目前在兑换券的时候会使用
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BeforePromoteRetailBill',N'U') AND Name='CouponCode')
BEGIN
	ALTER TABLE dbo.BeforePromoteRetailBill
	ADD CouponCode VARCHAR(200) DEFAULT('')
END
GO

--使用优惠券后，是否参与促销
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BeforePromoteRetailBill',N'U') AND Name='IsPromotion')
BEGIN
	ALTER TABLE dbo.BeforePromoteRetailBill
	ADD IsPromotion INT DEFAULT(1)
END
GO

--使用优惠券后，是否参与会员积分
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BeforePromoteRetailBill',N'U') AND Name='IsVipPoint')
BEGIN
	ALTER TABLE dbo.BeforePromoteRetailBill
	ADD IsVipPoint INT DEFAULT(1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BeforePromoteRetailBill') AND name = 'CIX_BeforePromoteRetailBill_BillNumberID')
--DROP INDEX CIX_BeforePromoteRetailBill_BillNumberID ON BeforePromoteRetailBill 
CREATE CLUSTERED INDEX CIX_BeforePromoteRetailBill_BillNumberID ON BeforePromoteRetailBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BeforePromoteRetailBill') AND name = 'NCIX_BeforePromoteRetailBill_Ptypeid')
--DROP INDEX NCIX_BeforePromoteRetailBill_Ptypeid ON BeforePromoteRetailBill 
CREATE NONCLUSTERED INDEX NCIX_BeforePromoteRetailBill_Ptypeid ON BeforePromoteRetailBill(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BeforePromoteRetailBill') AND name = 'NCIX_BeforePromoteRetailBill_Orderid')
--DROP INDEX NCIX_BeforePromoteRetailBill_Orderid ON BeforePromoteRetailBill 
CREATE NONCLUSTERED INDEX NCIX_BeforePromoteRetailBill_Orderid ON BeforePromoteRetailBill(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BeforePromoteRetailBill') AND name = 'NCIX_BeforePromoteRetailBill_Stypeid')
--DROP INDEX NCIX_BeforePromoteRetailBill_Stypeid ON BeforePromoteRetailBill 
CREATE NONCLUSTERED INDEX NCIX_BeforePromoteRetailBill_Stypeid ON BeforePromoteRetailBill(Stypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BeforePromoteRetailBill') AND name = 'NCIX_BeforePromoteRetailBill_SalePrice')
DROP INDEX NCIX_BeforePromoteRetailBill_SalePrice ON BeforePromoteRetailBill              
                   
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_BeforePromoteRetailBill_SalePrice ON BeforePromoteRetailBill(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BeforePromoteRetailBill') AND name = 'NCIX_BeforePromoteRetailBill_Discount')
DROP INDEX NCIX_BeforePromoteRetailBill_Discount ON BeforePromoteRetailBill 

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                  
CREATE NONCLUSTERED INDEX NCIX_BeforePromoteRetailBill_Discount ON BeforePromoteRetailBill(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BeforePromoteRetailBill') AND name = 'NCIX_BeforePromoteRetailBill_Tax')
DROP INDEX NCIX_BeforePromoteRetailBill_Tax ON BeforePromoteRetailBill 
                             
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_BeforePromoteRetailBill_Tax ON BeforePromoteRetailBill(Tax) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
              
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='BackQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN BackQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
           
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteRetailBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 
--是否为组合品（上表体数据）,1:是；0:不是。如果没有启用组合品，则该值永远为0.
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='iscombination'
)
BEGIN
		ALTER TABLE BeforePromoteRetailBill ADD iscombination   BIT NOT NULL Default(0)
END
GO

--所属组合品ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='combinationptypeid'
)
BEGIN
		ALTER TABLE BeforePromoteRetailBill ADD combinationptypeid   VARCHAR(200) NULL
END
GO

--启用组合品上下表体唯一ID值
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteRetailBill' AND a.Name='pindexid'
)
BEGIN
		ALTER TABLE BeforePromoteRetailBill ADD pindexid  VARCHAR(300) NULL
END
GO



/****** 对象:  Table [dbo].[SaleBill]    脚本日期: 05/05/2010 14:49:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BeforePromoteSaleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].BeforePromoteSaleBill(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL DEFAULT (0),
		[discount] [numeric](18, 4) NULL DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL DEFAULT (0),
		[costprice] [numeric](18, 4) NULL DEFAULT (0),
		[jobnumber] [varchar](20)  DEFAULT (''),
		[goodsno] [numeric](18, 4) NULL  DEFAULT (0),
		[total] [numeric](18, 4) NULL  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL  DEFAULT (0),
		[GoodsOrder] [int] NULL DEFAULT ('-1'),
		[BackQty] [numeric](18, 4) NULL  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL  DEFAULT (0),
		[HandZeroCost] [int] NULL  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ShareFee]	[numeric](18,2) NULL DEFAULT(0),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int                NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			 VARCHAR(200)		NULL DEFAULT('') ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		PriceSource   VARCHAR(200),
		IsGift INT NOT NULL DEFAULT(0), -- 是否是赠品 价格促销
		ETypeID VARCHAR(100) NULL,
		ShowOrder INT DEFAULT(0),
		CouponCode	VARCHAR(200) DEFAULT('')		--优惠券券编码，目前在兑换券的时候会使用
		,IsPromotion	INT DEFAULT(1)					--使用优惠券后，是否参与促销
		,IsVipPoint INT DEFAULT(1)				--使用优惠券后，是否参与会员积分		
		,[PriceDetailId] INT  NULL DEFAULT(0)		--高级价格明细id
		,[PriceRuleId] INT  NULL DEFAULT(0)			--高级价格id
		) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

--高级价格明细id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='PriceDetailId'
)
BEGIN
	ALTER TABLE BeforePromoteSaleBill ADD PriceDetailId INT  NULL DEFAULT(0)
END
go

--高级价格id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='PriceRuleId'
)
BEGIN
	ALTER TABLE BeforePromoteSaleBill ADD PriceRuleId INT  NULL DEFAULT(0)
END
go

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('BeforePromoteSaleBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table BeforePromoteSaleBill drop constraint '+@dfname);
		
	ALTER TABLE BeforePromoteSaleBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE BeforePromoteSaleBill ADD CONSTRAINT DF_BeforePromoteSaleBill_Serial DEFAULT('') FOR Serial
	
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BeforePromoteSaleBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.BeforePromoteSaleBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE BeforePromoteSaleBill SET ShowOrder=ID WHERE ShowOrder IS NULL
GO
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE BeforePromoteSaleBill ADD IsGift INT NOT NULL DEFAULT(0);
END
GO

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='ETypeID'
)
BEGIN
		ALTER TABLE BeforePromoteSaleBill ADD ETypeID VARCHAR(100) NULL;
END
GO

--优惠券券编码，目前在兑换券的时候会使用
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BeforePromoteSaleBill',N'U') AND Name='CouponCode')
BEGIN
	ALTER TABLE dbo.BeforePromoteSaleBill
	ADD CouponCode VARCHAR(200) DEFAULT('')
END
GO

--使用优惠券后，是否参与促销
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BeforePromoteSaleBill',N'U') AND Name='IsPromotion')
BEGIN
	ALTER TABLE dbo.BeforePromoteSaleBill
	ADD IsPromotion INT DEFAULT(1)
END
GO

--使用优惠券后，是否参与会员积分
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BeforePromoteSaleBill',N'U') AND Name='IsVipPoint')
BEGIN
	ALTER TABLE dbo.BeforePromoteSaleBill
	ADD IsVipPoint INT DEFAULT(1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BeforePromoteSaleBill') AND name = 'CIX_BeforePromoteSaleBill_BillNumberID')
	--DROP INDEX CIX_BeforePromoteSaleBill_BillNumberID ON BeforePromoteSaleBill 
CREATE CLUSTERED INDEX CIX_BeforePromoteSaleBill_BillNumberID ON BeforePromoteSaleBill(BillNumberID)
go

------------------------------------------创建索引区域结束-----------------------------------------------
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='goodsno' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN goodsno NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BeforePromoteSaleBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

--是否为组合品（上表体数据）,1:是；0:不是。如果没有启用组合品，则该值永远为0.
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='iscombination'
)
BEGIN
		ALTER TABLE BeforePromoteSaleBill ADD iscombination   BIT NOT NULL Default(0)
END
GO

--所属组合品ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='combinationptypeid'
)
BEGIN
		ALTER TABLE BeforePromoteSaleBill ADD combinationptypeid   VARCHAR(200) NULL
END
GO

--启用组合品上下表体唯一ID值
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BeforePromoteSaleBill' AND a.Name='pindexid'
)
BEGIN
		ALTER TABLE BeforePromoteSaleBill ADD pindexid  VARCHAR(300) NULL
END
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillAttachFiles]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillAttachFiles](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[FileName] VARCHAR(300) NULL DEFAULT(''),
		[FileType] VARCHAR(50) NULL DEFAULT(''),
		[Size] VARCHAR(100) NULL DEFAULT(''),
		[Comment] VARCHAR(500) NULL DEFAULT(''),
		[ETypeId] VARCHAR(50) NULL DEFAULT(''),
		[AttachDate] DATETIME NULL DEFAULT(''),
		[Data] image NULL,
		[BillIndexType] INT NULL DEFAULT(0)		
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillAttachFiles' AND a.Name='BillGuid'
)
BEGIN
	ALTER TABLE BillAttachFiles ADD 
		BillGuid VARCHAR(100) NULL DEFAULT('')
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='BillAttachFiles' AND a.Name='BillType')
BEGIN
	ALTER TABLE BillAttachFiles ADD 
		BillType INT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillAttachFiles') AND name = 'NCIX_BillAttachFiles_BILLNUMBERID')
--DROP INDEX NCIX_BillAttachFiles_BILLNUMBERID ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_BillAttachFiles_BILLNUMBERID ON BillAttachFiles(BILLNUMBERID) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO
UPDATE BillAttachFiles SET BillGuid = '' WHERE BillGuid IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillAttachFilesLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillAttachFilesLog](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[OperateDate] DATETIME NULL DEFAULT(''),
		[ETypeId] VARCHAR(50) NULL DEFAULT(''),
		[logtype] VARCHAR(20) NULL,
		[FileName] VARCHAR(300) NULL DEFAULT(''),
		[FileSize] VARCHAR(100) NULL DEFAULT(''),
		[FileComment] VARCHAR(500) NULL DEFAULT(''),
		[FileUpEtype] VARCHAR(100) NULL DEFAULT(''),
		[FileUpTime] DateTime NULL DEFAULT(''),
		[BillGuid] VARCHAR(100) NULL DEFAULT(''),
		[BillIndexType] INT NULL DEFAULT(0)	
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='BillAttachFilesLog' AND a.Name='BillType')
BEGIN
	ALTER TABLE BillAttachFilesLog ADD 
		BillType INT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BillCode_Seed]    脚本日期: 08/28/2008 17:19:24 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BillCode_Seed]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[BillCode_Seed](
		[_ID] [INT] IDENTITY(1,1) NOT NULL,
		[BillType] [INT] NOT NULL,
		[STypeID] VARCHAR(50) NOT NULL,
		[KTypeID] VARCHAR(50) NOT NULL,
		[ETypeID] VARCHAR(50) NOT NULL,
		[FlowDate] [varchar](8) NOT NULL,
		[Seed] [numeric](18, 0) NOT NULL
	) ON [PRIMARY]


END
GO
-- 修改表
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillCode_Seed' AND a.Name='DTypeId'
)
	ALTER TABLE [BillCode_Seed] ADD DTypeId VARCHAR(50) NOT NULL DEFAULT('');
--
go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillCode_Seed' AND a.Name='CETypeId'
)
	ALTER TABLE [BillCode_Seed] ADD CETypeId VARCHAR(50) NOT NULL DEFAULT('');
--
go

-- 创建索引
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillCode_Seed]') AND name = N'CIX_BillCode_Seed_BillType')
	--DROP  INDEX [dbo].[BillCode_Seed].CIX_BillCode_Seed_BillType
CREATE INDEX CIX_BillCode_Seed_BillType ON BillCode_Seed(BillType,FlowDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillCode_Seed') AND name = 'NCIX_BillCode_Seed_WD')
CREATE NONCLUSTERED INDEX NCIX_BillCode_Seed_WD ON BillCode_Seed(BillType,FlowDate,ETypeID,KTypeID,DTypeId,STypeID) 

GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
-- ========================================================================
-- 建立人：		刘飞
-- 建立时间:	2017-03-14
-- 表说明:		单据删除日志记录表
-- ========================================================================

IF NOT EXISTS (SELECT TOP 1 1 FROM SysObjects WHERE ID = OBJECT_ID(N'BillDeleteLog',N'U'))
BEGIN
	CREATE TABLE BillDeleteLog(
		 Id				INT PRIMARY KEY IDENTITY(1,1)		                                            --流水号
		,BillNumberID	NUMERIC(10, 0) NOT NULL DEFAULT(0)				                                --单据ID
		,BillType		NUMERIC(4, 0) NOT NULL CONSTRAINT DF_BillDeleteLog_BillType DEFAULT(0)			--单据类型
		,BillCode		VARCHAR(200) NOT NULL CONSTRAINT DF_BillDeleteLog_BillCode DEFAULT('')	        --单据编号
		,BillDate		DATETIME NOT NULL                                   				            --录单日期
		,StypeID		VARCHAR(50) NOT NULL CONSTRAINT DF_BillDeleteLog_StypeID DEFAULT('')	        --分支机构ID
		,BtypeID		VARCHAR(50) NOT NULL CONSTRAINT DF_BillDeleteLog_BtypeID DEFAULT('')	        --结算单位ID
		,DealBTypeID	VARCHAR(50) NOT NULL CONSTRAINT DF_BillDeleteLog_DealBTypeID DEFAULT('')	    --往来单位ID
		,Checke         VARCHAR(50) NOT NULL CONSTRAINT DF_BillDeleteLog_Checke DEFAULT('')             --制单人ID
		--,NTotalMoney    NUMERIC(22,10) NOT NULL DEFAULT(0)                                              --总金额
		,DelDate        DATETIME NOT NULL DEFAULT (GETDATE())                                           --删除时间
		,DelEtypeID     VARCHAR(50) NOT NULL CONSTRAINT DF_BillDeleteLog_DelEtypeID DEFAULT ('')        --删除人ID
		,DelIP          VARCHAR(50) NOT NULL CONSTRAINT DF_BillDeleteLog_DelIP DEFAULT ('127.0.0.1')    --删除人IP
	)
END

GO
------------------------------------------表修改区域开始-----------------------------------------------
------------------------------------------表修改区域结束-----------------------------------------------
------------------------------------------删除索引区域开始---------------------------------------------
------------------------------------------删除索引区域结束---------------------------------------------
------------------------------------------创建索引区域开始---------------------------------------------
------------------------------------------创建索引区域结束---------------------------------------------
------------------------------------------修改字段小数位数区域开始-------------------------------------
------------------------------------------修改字段小数位数区域结束-------------------------------------
------------------------------------------表数据更新开始-----------------------------------------------
------------------------------------------表数据更新结束-----------------------------------------------
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillExpressage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillExpressage](
		[vchcode] [varchar](100) NULL,
		[jName] [varchar](20) NULL,
		[jDWName] [varchar](200) NULL,
		[jAddress] [varchar](400) NULL,
		[jPhone] [varchar](50) NULL,
		[jPostal] [varchar](20) NULL,
		[jAddress_sheng] [varchar](200) NULL,
		[jAddress_shi] [varchar](200) NULL,
		[jAddress_qu] [varchar](200) NULL,
		[jTel] [varchar](20) NULL,
		[sName] [varchar](20) NULL,
		[sDWName] [varchar](200) NULL,
		[sAddress] [varchar](400) NULL,
		[sPhone] [varchar](50) NULL,
		[sPostal] [varchar](20) NULL,
		[sAddress_sheng] [varchar](200) NULL,
		[sAddress_shi] [varchar](200) NULL,
		[sAddress_qu] [varchar](200) NULL,
		[sTel] [varchar](20) NULL,
		[goodsQuantity] [varchar](20) NULL,
		[goodsPrice] [varchar](20) NULL,
		[goodsWeight] [varchar](20) NULL,
		[goodsVol] [varchar](20) NULL,
		[goodsDesc] [varchar](400) NULL,
		[weight] [varchar](20) NULL,
		[quantity] [varchar](20) NULL,
		[volume] [varchar](20) NULL,
		[remark] [varchar](400) NULL,
		[payType] [varchar](1) NULL,
		[isNotice] [varchar](1) NULL,
		[logisticCode] [varchar](50) NULL,
		[cost] [varchar](20) NULL,
		[otherCost] [varchar](20) NULL,
		[wlType] [varchar](20) NULL,
		[startDate] [varchar](20) NULL,
		[startDateTime] [varchar](20) NULL,
		[endDate] [varchar](20) NULL,
		[endDateTime] [varchar](20) NULL,
		[printType] [int] NULL,
		[thrOrderCode] [varchar](100) NULL,
		[goodsName] [nvarchar](1000) NULL,
		[goodscode] [nvarchar](1000) NULL,
		[SendStaff] [nvarchar](30) NULL
	)
END

GO

--Guid
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='BillExpressage' AND a.Name='BillGuid')
BEGIN
	ALTER TABLE BillExpressage 
		ADD BillGuid VARCHAR(100) DEFAULT('') NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'jAddress' and length=200)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN jAddress VARCHAR(400) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'sAddress' and length=200)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN sAddress VARCHAR(400) NULL
END
GO

UPDATE BillExpressage SET BillGuid = '' WHERE BillGuid IS NULL
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'goodsName' and length=1000)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN goodsName VARCHAR(3000) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'goodscode' and length=1000)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN goodscode VARCHAR(3000) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'jPhone' and length=50)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN jPhone VARCHAR(500) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'sPhone' and length=50)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN sPhone VARCHAR(500) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'jTel' and length=20)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN jTel VARCHAR(200) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'sTel' and length=20)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN sTel VARCHAR(200) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'sPostal' and length=20)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN sPostal VARCHAR(200) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'jPostal' and length=20)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN jPostal VARCHAR(200) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'jName' and length=20)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN jName VARCHAR(200) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'sName' and length=20)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN sName VARCHAR(200) NULL
END
GO
IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'TemplateSize')
BEGIN
	 ALTER TABLE BillExpressage
	    ADD TemplateSize VARCHAR(20) NULL DEFAULT('')
END
GO
UPDATE BillExpressage SET TemplateSize = '' WHERE TemplateSize IS NULL
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'jDWName' and length=100)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN jDWName VARCHAR(200) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'sDWName' and length=100)
BEGIN
	 ALTER TABLE BillExpressage
	    ALTER COLUMN sDWName VARCHAR(200) NULL
END
GO

--收件快递员(网点提供)
IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BillExpressage]') and  name = 'SendStaff')
BEGIN
	 ALTER TABLE BillExpressage
	    ADD SendStaff VARCHAR(30) NULL DEFAULT('')
END
GO
UPDATE BillExpressage SET SendStaff = '' WHERE SendStaff IS NULL
GO

SET ANSI_PADDING OFF
GO






/****** 对象:  Table [dbo].[BillIndex]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[BillIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_BillIndex_BillCode]  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](MAX) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_BillComment]  DEFAULT (''),
		[atypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_atypeid]  DEFAULT ('0'),
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_ptypeid]  DEFAULT ('0'),
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_btypeid]  DEFAULT ('0'),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_etypeid]  DEFAULT ('0'),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_ktypeid]  DEFAULT ('0'),
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_ktypeid2]  DEFAULT ('0'),
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_ifcheck]  DEFAULT ('t'),
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalmoney] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndex_total]  DEFAULT (0),
		[totalinmoney] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndex_totalinmoney]  DEFAULT (0),--在零售单中 对应packway字段
		[totalqty] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndex_totalqty]  DEFAULT (0),
		[tax] [numeric](5, 2) NULL CONSTRAINT [DF_BillIndex_tax]  DEFAULT (17),
		[period] [smallint] NULL CONSTRAINT [DF_BillIndex_period]  DEFAULT (0),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_explain]  DEFAULT (''),
		[RedWord] [int] NOT NULL CONSTRAINT [DF_BillIndex_RedWord]  DEFAULT (0),
		[draft] [bit] NOT NULL CONSTRAINT [DF_BillIndex_draft]  DEFAULT (0),
		[OrderId] [numeric](10, 0) NULL CONSTRAINT [DF_BillIndex_OrderId]  DEFAULT (0),
		[waybillcode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_billinex_goodsnumber]  DEFAULT (''),
		[packway] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,--在零售单中 此字段表示收现金额
		[TEL] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,--在零售单中 此字段表示找零
		[Uploaded] [bit] NOT NULL CONSTRAINT [DF_BillIndex_Uploaded]  DEFAULT (0),
		[OFF_ID] [uniqueidentifier] NULL,
		[TeamNo] [int] NULL,
		[AlertDay] [int] NULL CONSTRAINT [DF_BillIndex_AlertDay]  DEFAULT (9999),
		[CompleteTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndex_CompleteTotal]  DEFAULT (0),
		[ID] [numeric](10, 0) NOT NULL CONSTRAINT [DF_BillIndex_ID]  DEFAULT (0),
		[Assessor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfAudit] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[Audit_explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[IfStopMoney] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_IfStopMoney]  DEFAULT (0),
		[preferencemoney] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndex_preferencemoney]  DEFAULT (0),
		[DTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_DTypeId]  DEFAULT ('0'),
		[JF] [int] NULL CONSTRAINT [DF_BillIndex_JF]  DEFAULT (0),
		[VipCardID] [int] NULL CONSTRAINT [DF_BillIndex_VipCardID]  DEFAULT ((-1)),
		[vipCZMoney] [numeric](18, 4) NULL,
		[jsStyle] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_jsStyle]  DEFAULT (0),--结算方式 0未结算 1 按单 2 按商品 3 按品牌 4.混合（按单，按品牌 应收增加减少单）
		[jsState] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_jsState]  DEFAULT (0),--结算状态 0未结算 1 已结算未完成 2 结算完成
		[KTypeID3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_KTypeID3]  DEFAULT ('0'),
		[LinkMan] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_LinkMan]  DEFAULT (''),
		[LinkTel] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_LinkTel]  DEFAULT (''),
		[LinkAddr] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_LinkAddr]  DEFAULT (''),
		[wxManID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_wxMan]  DEFAULT (''),
		[JieJianBillNumberID] [int] NULL CONSTRAINT [DF_BillIndex_JieJianCode]  DEFAULT ((-1)),
		[JieJianID] [int] NULL CONSTRAINT [DF_BillIndex_JieJianID]  DEFAULT ((-1)),
		[JieJianState] [int] NULL CONSTRAINT [DF_BillIndex_JieJianState]  DEFAULT ((-1)),
		[BaoXiuBillNumberID] [int] NULL CONSTRAINT [DF_BillIndex_BaoXiuCode]  DEFAULT ((-1)),
		[BaoXiuID] [int] NULL CONSTRAINT [DF_BillIndex_BaoXiuID]  DEFAULT ((-1)),
		[BuyDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_BuyDate]  DEFAULT (''),
		[Serial] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_Serial]  DEFAULT (''),
		[wxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndex_wxTotal]  DEFAULT (0),
		[ErrDes] [varchar](3000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndex_ErrDes]  DEFAULT (''),
		[ifHideJieJian] [int] NULL CONSTRAINT [DF_BillIndex_ifHideJieJian]  DEFAULT (0),
		[ifWX] [int] NULL CONSTRAINT [DF_BillIndex_ifWX]  DEFAULT (0),
		[ifYearBill] [int] NULL CONSTRAINT [DF_BillIndex_ifYearBill]  DEFAULT (0),
		[Poster] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LastUpdateTime] DateTime NULL CONSTRAINT [DF_BillIndex_LastUpdateTime]  DEFAULT GETDATE(),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL DEFAULT ('0'),
		[CostSale] [BIT] DEFAULT 0,
		[OtherInOutType]	INT DEFAULT 0,
		[PosBillType] INT NULL DEFAULT 0,
		[checkTime]		DATETIME NULL,
		[posttime]		DATETIME NULL,
		[updateE]		VARCHAR(50) NULL  DEFAULT (''),
		[ShareMode]		TINYINT NULL	DEFAULT 0,
		[TransportId]   VARCHAR(10) NULL DEFAULT(0),
		[IsIni]			BIT NULL DEFAULT(0),
		[ATypeID1]		VARCHAR(50) NULL DEFAULT(''),
		[NCompleteTotal] [numeric](22, 10) NULL DEFAULT (0),
		[ATID]			INT DEFAULT(0),
		[IfCargo]		BIT DEFAULT(0),
		[InvoiceMoney] numeric(22,10) null DEFAULT(0),
		[NInvoiceMoney] numeric(22,10) null DEFAULT(0),
		[RedReason] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		PrePriceNum INT DEFAULT(0) NOT NULL, --预设售价，进价
		AssetBusinessTypeId int, --固定资产业务类型id
		PromoRuleId int NOT NULL DEFAULT(0), --促销方案id
		BeforePromoBillNumberId int NOT NULL DEFAULT(0), --促销前数据id
		ImportType tinyint NOT NULL DEFAULT(0), --导入类型
		NewPosBill tinyint NULL DEFAULT(0),
		[PromotionMsg] NVARCHAR(500) NOT NULL DEFAULT(0),
		[Reconciliation] CHAR(1) DEFAULT('f'), --对账 默认f 对账t
		/*添加字段 ARTOTAL,APTOTAL,YSTOTAL,YFTOTAL 2014-1-15 tangtao */
		 ARTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 APTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 YSTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 YFTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 IsAuto int DEFAULT(0), --0=手动，1=自动
		IsYapi bit NULL DEFAULT(0),
		YapiOrderID NUMERIC(20,0) NULL DEFAULT(0),
		DeliveryAddress VARCHAR(256) NOT NULL DEFAULT(''), --送货地址
		AddDTypeETypeType INT NOT NULL DEFAULT(0), --补录部门经手人类型 0 未补录 1 补录过部门 2补录过经手人 3 同时都补录过
		BillTime VARCHAR(20)  NULL, -- 单据的时分秒
		citestate int NOT NULL DEFAULT(0),--拣货状态0=未引用1=已引用未完成2=已完成
		ShelveRefState INT NOT NULL DEFAULT(0),				--上架引用状态  0=未引用1=已引用未完成2=已完成
		progressstate int NOT NULL DEFAULT(0),				--0=已开单1=拣货中2=已出库
		ShelveState   INT NOT NULL DEFAULT(0),				--上架状态 0=已开单1=上架中2=已上架
		TransPortState INT NOT NULL DEFAULT(0),				--运输状态 0=已开单，1=发运中，2=已发运
		[WarehouseOutDay] [int] NULL DEFAULT (9999),--出库期限@StockInDeadline
		[StockInDeadline] [int] NULL DEFAULT (9999),--出库期限
		shipper VARCHAR(50) NULL DEFAULT(''), --托运方
		totalfreight NUMERIC(24,10) NULL DEFAULT(0),--合计运费
		Ntotalfreight NUMERIC(24,10) NULL DEFAULT(0),--原币合计运费
		transportno varchar(200)	NULL DEFAULT(''),--承运商运单号
		Transporterid varchar(50)	NULL DEFAULT('0'),--承运商id
		Transporterfullname varchar(200)	NULL DEFAULT(''),--承运商名称
		shipperfullname varchar(100)	NULL DEFAULT(''),--托运方
		shipperperson varchar(100)	NULL DEFAULT(''),--托运人
		shippertel varchar(100)	NULL DEFAULT(''),--托运联系电话
		[FaPiaoCode] [varchar](256)  NULL CONSTRAINT [DF_BillIndex_FaPiaoCode]  DEFAULT (''),
		InFactState       INT DEFAULT(0),	  --1 仓库入库未完成 2仓库入库已完成
		InFactRefState    INT DEFAULT(0),    -- 0仓库入库未引用  1仓库入库已引用
		OutFactState	  INT DEFAULT(0),	  --1 仓库出库未完成 2仓库出库已完成	
		OutFactRefState   INT DEFAULT(0),	  --0 仓库出库未引用 1仓库出库已引用
		PayType int DEFAULT(0),--是否支付  0-未支付 1-已支付
		PromonIds VARCHAR(1000) NULL DEFAULT('') ,--所有使用的促销方案id，逗号分隔
		isByBrandarType	 INT NULL  DEFAULT(0), --按品牌收款
		PayOnTheSpot	INT NOT NULL DEFAULT(0),	--是否当面付：0否 1是
		UploadPreOrder	INT NOT NULL DEFAULT(0),	--是否上传预订单：0否 1是
		PreOrderStatus	INT	NOT NULL DEFAULT(0),	--预订单状态 2为已支付 其他为未支付
		PreOrderId		VARCHAR(50) NOT NULL DEFAULT(''), --预订单id
		PosId			INT, --pos机id
		RChecker VARCHAR(50) NULL DEFAULT(''),	--反审核人
		RVaildDate DATETIME NULL				--反审核时间
	) ON [PRIMARY]

END
GO


------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='PosId'
)
BEGIN
	ALTER TABLE BillIndex ADD PosId INT NOT NULL DEFAULT (0)
END

GO


-- 添加促销方案id字段，记录商品应用的所有促销方案
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='PromonIds')
BEGIN
	ALTER TABLE dbo.BillIndex
	ADD PromonIds VARCHAR(1000) NULL DEFAULT('')
END
ELSE
BEGIN
	ALTER TABLE dbo.BillIndex
	ALTER Column PromonIds VARCHAR(1000) NULL
END
GO

--是否支付
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='PayType')
BEGIN
	ALTER TABLE dbo.BillIndex 
	ADD PayType INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='InFactRefState')
BEGIN
	ALTER TABLE BillIndex
	ADD InFactRefState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='OutFactRefState')
BEGIN
	ALTER TABLE BillIndex
	ADD OutFactRefState INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='InFactState')
BEGIN
	ALTER TABLE BillIndex
	ADD InFactState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='OutFactState')
BEGIN
	ALTER TABLE BillIndex
	ADD OutFactState INT DEFAULT(0)
END
GO
	UPDATE dbo.BillIndex SET InFactState=0 WHERE InFactState IS NULL
	UPDATE dbo.BillIndex SET OutFactState=0 WHERE OutFactState IS NULL
	UPDATE dbo.BillIndex SET InFactRefState=0 WHERE InFactRefState IS NULL
	UPDATE dbo.BillIndex SET OutFactRefState=0 WHERE OutFactRefState IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='ShelveState')
BEGIN
	ALTER TABLE BillIndex
	ADD ShelveState INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='ShelveRefState')
BEGIN
	ALTER TABLE BillIndex
	ADD ShelveRefState INT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='TransPortState')
BEGIN
	ALTER TABLE BillIndex
	ADD TransPortState INT NOT NULL DEFAULT(0)
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='TEL'
)
BEGIN
	ALTER TABLE BillIndex 
		ALTER COLUMN TEL  [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='CWCheck'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD CWCheck INT NOT NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IfBargainOn' 
)
BEGIN
	ALTER TABLE BillIndex ADD IfBargainOn INT NULL DEFAULT(0)
END
GO
UPDATE billindex SET IfBargainON=0 WHERE IfBargainON IS NULL

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='LastUpdateTime'
)
BEGIN
	ALTER TABLE BillIndex ADD LastUpdateTime DateTime NULL CONSTRAINT [DF_BillIndex_LastUpdateTime]  DEFAULT GETDATE()
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='Poster'
)
BEGIN
	ALTER TABLE BillIndex ADD Poster VARCHAR(50) NOT NULL DEFAULT ('')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE BillIndex ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE BillIndex SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE BillIndex ADD FromBillNumberID [numeric](10, 0)  NULL DEFAULT ('0')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='CostSale'
)
BEGIN
	ALTER TABLE BillIndex ADD CostSale [bit]  NULL	DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IfMulAccount'
)
BEGIN
	ALTER TABLE BillIndex ADD IfMulAccount INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='OtherInOutType'
)
BEGIN
	ALTER TABLE BillIndex ADD OtherInOutType INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='PosBillType'
)
BEGIN
	ALTER TABLE BillIndex ADD PosBillType INT NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='checkTime'
)
BEGIN
	ALTER TABLE BillIndex ADD checkTime DATETIME NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='posttime'
)
BEGIN
	ALTER TABLE BillIndex ADD posttime DATETIME NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='updateE'
)
BEGIN
	ALTER TABLE BillIndex ADD updateE VARCHAR(50) NULL DEFAULT('') 
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ShareMode'
)
BEGIN
	ALTER TABLE BillIndex ADD ShareMode TINYINT NULL DEFAULT 0
END
GO

IF  EXISTS(
	SELECT b.name 
	FROM  sysconstraints a  
	INNER JOIN sysobjects b 
	ON a.constid= b.id AND b.xtype='d' AND a.constid= OBJECT_ID(N'[dbo].[DF_BillIndex_LastUpdateTime]')
)
BEGIN
	ALTER TABLE BillIndex  DROP [DF_BillIndex_LastUpdateTime] 
END
GO



IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndex' AND a.Name='IsFreightMoney')
BEGIN
	ALTER TABLE BillIndex 
		ADD IsFreightMoney INT NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndex' AND a.Name='FreightAddr')
BEGIN
	ALTER TABLE BillIndex 
		ADD FreightAddr VARCHAR(300) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndex' AND a.Name='FreightPerson')
BEGIN
	ALTER TABLE BillIndex 
		ADD FreightPerson VARCHAR(100) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndex' AND a.Name='FreightTel')
BEGIN
	ALTER TABLE BillIndex 
		ADD FreightTel VARCHAR(100) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndex' AND a.Name='IfInvoice')
BEGIN
	ALTER TABLE BillIndex 
		ADD IfInvoice INT NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndex' AND a.Name='TransportId')
BEGIN
	ALTER TABLE BillIndex 
		ADD TransportId VARCHAR(10) NULL DEFAULT(0) 
END
GO	

--添加自定义字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='UF1'
)
BEGIN
	ALTER TABLE BillIndex ADD UF1 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='UF2'
)
BEGIN
	ALTER TABLE BillIndex ADD UF2 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='UF3'
)
BEGIN
	ALTER TABLE BillIndex ADD UF3 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='UF4'
)
BEGIN
	ALTER TABLE BillIndex ADD UF4 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='UF5'
)
BEGIN
	ALTER TABLE BillIndex ADD UF5 VARCHAR(200)  NULL DEFAULT('')
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ATID'
)
BEGIN
	ALTER TABLE BillIndex ADD ATID INT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NewPosBill'
)
BEGIN
	ALTER TABLE BillIndex ADD NewPosBill tinyint NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='iscombinationstyle'
)
BEGIN
	ALTER TABLE BillIndex ADD iscombinationstyle tinyint NULL DEFAULT(0)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='telandaddress'
)
BEGIN
	IF NOT EXISTS(
		SELECT a.Name FROM syscolumns a
		INNER JOIN sysobjects	b
		ON a.ID=b.ID
		WHERE b.Name='BillIndex' AND a.Name='DeliveryAddress'
	)
		EXEC sp_rename 'BillIndex.telandaddress','DeliveryAddress','column'
	ELSE
		BEGIN
			-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
			DECLARE @t1 TABLE(name VARCHAR(100)); 
			INSERT INTO @t1 SELECT 'telandaddress'
			DECLARE @sql1 NVARCHAR(max)='';
			DECLARE @tn1 NVARCHAR(500)='billindex';

			SELECT @sql1=@sql1+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn1+' drop constraint '+a.name+';' END
				+ ' alter table '+@tn1+' drop column '+d.name+';'
			FROM sys.default_constraints a 
				RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
				JOIN @t1 d ON b.name=d.name
				WHERE b.object_id=object_id(@tn1,'U')

			IF @sql1<>''
				EXEC(@sql1);
			
		END
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='DeliveryAddress'
)
BEGIN
	ALTER TABLE BillIndex ADD DeliveryAddress VARCHAR(256) NOT NULL DEFAULT('') --送货地址
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='AddDTypeETypeType'
)
BEGIN
	ALTER TABLE BillIndex ADD AddDTypeETypeType TINYINT NOT NULL DEFAULT(0)
END
GO



-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'SettleBTypeID' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'CurID' UNION ALL SELECT 'TaskType'
UNION ALL SELECT 'NARTOTAL'
UNION ALL SELECT 'NAPTOTAL'
UNION ALL SELECT 'NYSTOTAL'
UNION ALL SELECT 'NYFTOTAL';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='billindex';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='DealBTypeID'
)
BEGIN
	ALTER TABLE BillIndex ADD DealBTypeID VARCHAR(50)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='CID'
)
BEGIN
	ALTER TABLE BillIndex ADD CID int  NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE BillIndex ADD Rate NUMERIC(22,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE BillIndex ADD NTotalMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NTotalInMoney'
)
BEGIN
	ALTER TABLE BillIndex ADD NTotalInMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NPreferenceMoney'
)
BEGIN
	ALTER TABLE BillIndex ADD NPreferenceMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NVIPCZMoney'
)
BEGIN
	ALTER TABLE BillIndex ADD NVIPCZMoney NUMERIC(22,10) DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD IsIni BIT NULL DEFAULT(0)
		
	EXEC('UPDATE BillIndex SET IsIni=0 WHERE IsIni IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ATypeID1'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD ATypeID1 VARCHAR(50) NULL DEFAULT('')
		
	
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NCompleteTotal'
)
BEGIN
	ALTER TABLE BillIndex ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
ELSE
BEGIN
	ALTER TABLE BillIndex ALTER COLUMN NCompleteTotal NUMERIC(22,10)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='billproperty'
)
BEGIN
	ALTER TABLE BillIndex ADD billproperty int default(-1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='TallyId'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD TallyId VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IfCargo'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD IfCargo BIT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='InvoiceMoney'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD InvoiceMoney NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NInvoiceMoney'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD NInvoiceMoney NUMERIC(22,10) NULL DEFAULT(0)
END
GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='progressstate'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD progressstate INT NULL DEFAULT(0)
END
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ac_Currency]') AND type in (N'U')) AND EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetCid]') and xtype in (N'FN', N'IF', N'TF'))
	BEGIN
		UPDATE t SET t.rate = t1.rate 
		FROM billindex T JOIN Ac_Currency t1 
		ON T.cid = t1.cid
		WHERE t.Rate = 0
		--EXEC('

		--	UPDATE  BillIndex
		--	SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
		--						   THEN ROUND(APTOTAL * Rate, 2)
		--						   ELSE ROUND(APTOTAL / Rate, 2)
		--						   END
		--	WHERE  APTOTAL IS NOT NULL

		--	UPDATE  BillIndex
		--	SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
		--						   THEN ROUND(YSTOTAL * Rate, 2)
		--						   ELSE ROUND(YSTOTAL / Rate, 2)
		--						   END
		--	WHERE  YSTOTAL IS NOT NULL

		--	UPDATE  BillIndex
		--	SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
		--						   THEN ROUND(YFTOTAL * Rate, 2)
		--						   ELSE ROUND(YFTOTAL / Rate, 2)
		--						   END
		--	WHERE  YFTOTAL IS NOT NULL
		--')
	END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='RedReason'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD RedReason [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='PrePriceNum'
)
BEGIN
	ALTER TABLE billindex ADD PrePriceNum INT DEFAULT(0) NOT NULL;
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='AssetBusinessTypeId'
)
BEGIN
	ALTER TABLE billindex ADD AssetBusinessTypeId INT
END

go
--促销方案id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='PromoRuleId'
)
BEGIN
	ALTER TABLE billindex ADD PromoRuleId INT NOT NULL DEFAULT(0)
END
go
--促销前数据id
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='BeforePromoteBillNumberId'
)
BEGIN
	EXEC sp_rename 'BillIndex.BeforePromoteBillNumberId','BeforePromoBillNumberId','column';
END
ELSE
BEGIN
	IF NOT EXISTS(
		SELECT a.Name FROM syscolumns a
		INNER JOIN sysobjects	b
		ON a.ID=b.ID
		WHERE b.Name='BillIndex' AND a.Name='BeforePromoBillNumberId'
	)
	BEGIN
		ALTER TABLE billindex ADD BeforePromoBillNumberId  INT NOT NULL DEFAULT(0)
	END
END
go
--导入类型
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ImportType'
)
BEGIN
	ALTER TABLE billindex ADD ImportType tinyint NOT NULL DEFAULT(0);
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='PromotionMsg'
)
BEGIN
	ALTER TABLE billindex ADD [PromotionMsg] NVARCHAR(500) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE billindex ADD [Reconciliation] CHAR(1) DEFAULT('f') --对账 默认f 对账t
END
go


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ARTOTAL'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD ARTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='APTOTAL'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD APTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='YSTOTAL'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD YSTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='YFTOTAL'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD YFTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IsAuto'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD IsAuto int DEFAULT(0) --0=手动，1=自动
END
GO

--增加一个分支机构id(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='StypeID2'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD StypeID2 VARCHAR(50) NULL DEFAULT('')
END
GO
--是否确认入账(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IfConfirm'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD IfConfirm INT NOT NULL DEFAULT(0)
END
GO

--资金调拨业务类型(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='TransferType'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD TransferType INT NOT NULL DEFAULT(1)
END
GO
--资金调拨单费用扣除账户类型:1,调出账户，2,调入账户(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='FeeDeductType'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD FeeDeductType INT NOT NULL DEFAULT(1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IsYapi'
)
BEGIN
	ALTER TABLE billindex ADD IsYapi bit NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='YapiOrderID'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD YapiOrderID NUMERIC(20,0) NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='BillTime'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD BillTime VARCHAR(20) NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IsLend'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD IsLend BIT  NULL DEFAULT(0)
END
GO

--增加扣率
IF NOT EXISTS (SELECT Name FROM SYSColumns WHERE ID=OBJECT_ID('BillIndex') AND Name='Discount')
BEGIN
	ALTER TABLE dbo.BillIndex
	Add Discount NUMERIC(22,10) DEFAULT(1)
END

--增加业务类型,只用于成本条件单,默认为库存0,1-入库,2-出库
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='AdPriceType'
)
BEGIN
	ALTER TABLE BillIndex 
		ADD AdPriceType TINYINT NOT NULL DEFAULT(0)
END
GO

--9.6.1运单号从20个字符升级为50个字符
IF EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID('BillIndex',N'U') AND LOWER(Name)='waybillcode' AND [Length]=20)
BEGIN
	ALTER TABLE dbo.BillIndex
	ALTER COLUMN waybillcode VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL
END
--自定义字段结束
--添加往来核销单需要的字段

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ChargeOffBtypeid'
)
BEGIN
	ALTER TABLE billindex ADD ChargeOffBtypeid VARCHAR(50) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ChargeOffType'
)
BEGIN
	ALTER TABLE billindex ADD ChargeOffType INT NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ChargeOffTotal'
)
BEGIN
	ALTER TABLE billindex ADD ChargeOffTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NChargeOffTotal'
)
BEGIN
	ALTER TABLE billindex ADD NChargeOffTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='cwchecker'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD cwchecker VARCHAR(50)  NULL  DEFAULT('')
END
GO
--添加往来核销单需要的字段结束

--引用状态
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='citestate'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD citestate INT  NOT NULL DEFAULT(0)
END

IF EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	LEFT JOIN syscomments e ON a.cdefault=e.id AND a.id= OBJECT_ID('BillIndex')
	WHERE b.Name='BillIndex' AND a.Name='citestate' AND e.text IS NULL)
BEGIN
	ALTER TABLE BillIndex add constraint df_citestate default (0) for citestate
END
go
UPDATE billindex SET citestate=0 WHERE citestate IS NULL
go
  --上架、拣货、运输等状态
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='progressstate'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD progressstate INT
END
--是否需要运输配送
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IsNeedTransport'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD IsNeedTransport BIT
END
--托运方
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='shipper'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD shipper VARCHAR(50)
END
--合计运费
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='totalfreight'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD totalfreight NUMERIC(24,10)
END
--原币合计运费
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ntotalfreight'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD ntotalfreight NUMERIC(24,10)
END

--承运商运单号
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='transportno'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD transportno varchar(200)
END
--出库期限
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='WarehouseOutDay'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD [WarehouseOutDay] VARCHAR(50)
END
--入库期限
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='StockInDeadline'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD [StockInDeadline] VARCHAR(50)
END
--承运商档案
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='Transporterid'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD [Transporterid] VARCHAR(50) NULL DEFAULT('0')
END
--承运商档案
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='Transporterfullname'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD [Transporterfullname] VARCHAR(200) NULL DEFAULT('')
END
--托运方
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='shipperfullname'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD [shipperfullname] VARCHAR(100) NULL DEFAULT('')
END
--托运人
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='shipperperson'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD [shipperperson] VARCHAR(100) NULL DEFAULT('')
END
--托运联系电话
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='shippertel'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD [shippertel] VARCHAR(100) NULL DEFAULT('')
END
--发票编号
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='FaPiaoCode'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD [FaPiaoCode] VARCHAR(256) NULL DEFAULT('')
END

--按品牌收款
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='isByBrandarType'
)
BEGIN
	ALTER TABLE dbo.BillIndex ADD isByBrandarType INT NULL   DEFAULT(0)
END
GO
UPDATE BillIndex SET isByBrandarType=0 WHERE  isByBrandarType IS NULL
GO

--是否当面付
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='PayOnTheSpot')
BEGIN
	ALTER TABLE dbo.BillIndex 
	ADD PayOnTheSpot INT NOT NULL DEFAULT(0)
END
GO

--是否上传预订单
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='UploadPreOrder')
BEGIN
	ALTER TABLE dbo.BillIndex 
	ADD UploadPreOrder INT NOT NULL DEFAULT(0)
END
GO

--预订单状态 2为已支付 其他为未支付
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='PreOrderStatus')
BEGIN
	ALTER TABLE dbo.BillIndex 
	ADD PreOrderStatus	INT	NOT NULL DEFAULT(0)
END
GO

--预订单id
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndex',N'U') AND Name='PreOrderId')
BEGIN
	ALTER TABLE dbo.BillIndex 
	ADD PreOrderId	VARCHAR(50) NOT NULL DEFAULT('')
END
GO


-------9.91添加反审核人、反审核时间-------- 
if not exists (select name from syscolumns where id = object_id(N'[dbo].[BillIndex]') and name = 'RChecker' )
BEGIN
	ALTER TABLE BillIndex 
	ADD RChecker VARCHAR(50) NULL DEFAULT('')
END
GO
UPDATE BillIndex SET RChecker = '' WHERE RChecker IS NULL
GO

---反审核日期
IF NOT EXISTS (select name from syscolumns where id = object_id(N'[dbo].[BillIndex]') and name = 'RVaildDate' )
BEGIN
	ALTER TABLE BillIndex 
	ADD RVaildDate DATETIME NULL
END
GO
-----------------END-----------------------


------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'NCIX_IFCHECK')
--	DROP INDEX [dbo].BillIndex.NCIX_IFCHECK

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'NCIX_REDWORD')
--	DROP INDEX [dbo].BillIndex.NCIX_REDWORD

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'NCIX_BILLTYPE')
--	DROP INDEX [dbo].BillIndex.NCIX_BILLTYPE

--IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'NCIX_DRAFT')
--	DROP INDEX [NCIX_DRAFT] ON [dbo].[BillIndex]
--GO

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'IX_BillIndex_ATypeID')
--	DROP  INDEX [IX_BillIndex_ATypeID] ON BILLINDEX 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'IX_BillIndex_BillCode')
--DROP  INDEX [IX_BillIndex_BillCode] ON BILLINDEX 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'IX_BillIndex_BillDate')
--DROP  INDEX [IX_BillIndex_BillDate] ON BILLINDEX 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'IX_BillIndex_BillNumberId')
--DROP  INDEX [IX_BillIndex_BillNumberId] ON BILLINDEX 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'IX_BillIndex_BTypeId')
--DROP INDEX [IX_BillIndex_BTypeId] ON BILLINDEX 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'IX_BillIndex_ETypeID')
--DROP INDEX [IX_BillIndex_ETypeId] ON BILLINDEX 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'IX_BillIndex_KTypeID')
--DROP INDEX [IX_BillIndex_KTypeId] ON BILLINDEX 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'IX_BillIndex_KTypeID2')
--DROP INDEX [IX_BillIndex_KTypeId2] ON BILLINDEX 
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLINDEX') AND name = 'CIX_BILLINDEX_BillDate')
--DROP INDEX CIX_BILLINDEX_BillDate ON BILLINDEX 
CREATE CLUSTERED INDEX CIX_BILLINDEX_BillDate ON BILLINDEX(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLINDEX') AND name = 'NCIX_BILLINDEX_BillNumberID')
--DROP INDEX NCIX_BILLINDEX_BillNumberID ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_BILLINDEX_BillNumberID ON BILLINDEX(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLINDEX') AND name = 'NCIX_BILLINDEX_Billcode')
--DROP INDEX NCIX_BILLINDEX_Billcode ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_BILLINDEX_Billcode ON BILLINDEX(Billcode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLINDEX') AND name = 'NCIX_BILLINDEX_Btypeid')
--DROP INDEX NCIX_BILLINDEX_Btypeid ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_BILLINDEX_Btypeid ON BILLINDEX(Btypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLINDEX') AND name = 'NCIX_BILLINDEX_Atypeid')
--DROP INDEX NCIX_BILLINDEX_Atypeid ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_BILLINDEX_Atypeid ON BILLINDEX(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLINDEX') AND name = 'NCIX_BILLINDEX_Etypeid')
--DROP INDEX NCIX_BILLINDEX_Etypeid ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_BILLINDEX_Etypeid ON BILLINDEX(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLINDEX') AND name = 'NCIX_BILLINDEX_Ktypeid')
--DROP INDEX NCIX_BILLINDEX_Ktypeid ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_BILLINDEX_Ktypeid ON BILLINDEX(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLINDEX') AND name = 'NCIX_BILLINDEX_Ktypeid2')
--DROP INDEX NCIX_BILLINDEX_Ktypeid2 ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_BILLINDEX_Ktypeid2 ON BILLINDEX(Ktypeid2) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'NCIX_BILLINDEX_BILLTYPE')
--DROP INDEX NCIX_BILLINDEX_BILLTYPE ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_BILLINDEX_BILLTYPE ON BILLINDEX(BILLTYPE) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[BillIndex]') AND name = N'NCIX_BILLINDEX_STYPEID_INCLUDE')
--DROP INDEX [NCIX_BILLINDEX_STYPEID_INCLUDE] ON [dbo].[BillIndex] WITH ( ONLINE = OFF )
--GO
CREATE NONCLUSTERED INDEX [NCIX_BILLINDEX_STYPEID_INCLUDE] ON [dbo].[BillIndex] 
(
	[Stypeid] ASC,
	[BillDate] ASC,
	[BillType] ASC
)
INCLUDE ( [BillNumberId]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE BillIndex SET FromBillNumberID = 0 WHERE FromBillNumberID IS NULL
GO
UPDATE BillIndex SET CostSale = 0 WHERE CostSale IS NULL
GO
UPDATE BillIndex SET IfMulAccount = 0 WHERE IfMulAccount IS NULL
GO
UPDATE BillIndex SET sharemode = 0 WHERE sharemode IS NULL
GO
UPDATE BillIndex SET posbilltype = 0 WHERE posbilltype IS NULL
GO
UPDATE BillIndex SET TransportId = 0 WHERE TransportId IS NULL
GO
UPDATE BillIndex SET IsFreightMoney = 0 WHERE IsFreightMoney IS NULL
GO
UPDATE BillIndex SET FreightAddr = '' WHERE FreightAddr IS NULL
GO
UPDATE BillIndex SET FreightPerson = '' WHERE FreightPerson IS NULL
GO
UPDATE BillIndex SET FreightTel = '' WHERE FreightTel IS NULL
GO
UPDATE BillIndex SET IfInvoice = 0 WHERE IfInvoice IS NULL
GO
UPDATE BillIndex SET billproperty = -0 WHERE IfInvoice IS NULL
GO
UPDATE Billindex SET TallyId = '' WHERE TallyId IS NULL
GO
UPDATE Billindex SET NewPosbill = 0 WHERE NewPosbill IS NULL
GO
UPDATE BillIndex SET IsLend = 0 WHERE IsLend IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='preferencemoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN preferencemoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='vipCZMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN vipCZMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='wxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN wxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ARTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN ARTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='APTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN APTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='YSTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN YSTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='YFTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN YFTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NTotalInMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN NTotalInMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NPreferenceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN NPreferenceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NVIPCZMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN NVIPCZMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='ChargeOffTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN ChargeOffTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='NChargeOffTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndex 
	ALTER COLUMN NChargeOffTotal NUMERIC(24,10)
    END
    
 
  
 alter table BillIndex drop constraint DF_BillIndex_BillComment

  ALTER TABLE BillIndex 
	ALTER COLUMN Comment VarChar(Max)  

	Alter Table BillIndex   
	Add Constraint DF_BillIndex_BillComment default('') for Comment   
	

 alter table BillIndex drop constraint DF_BillIndex_explain

  ALTER TABLE BillIndex 
	ALTER COLUMN explain VarChar(Max)  

	Alter Table BillIndex   
	Add Constraint DF_BillIndex_explain default('') for explain   

--是否上传到WMS	
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IsUploadWms'
    )
    BEGIN
	ALTER TABLE BillIndex 
		ADD IsUploadWms INT DEFAULT(0)
    END
GO
UPDATE BillIndex SET IsUploadWms = 0 WHERE IsUploadWms IS NULL      


--WMS任务id
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='WmsTaskId'
    )
    BEGIN
	ALTER TABLE BillIndex 
		ADD WmsTaskId VARCHAR(50) NULL DEFAULT('')
    END
GO    

--WMS单据号
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='WmsVchCode'
    )
    BEGIN
	ALTER TABLE BillIndex 
		ADD WmsVchCode VARCHAR(50) NULL DEFAULT('')
    END
GO    

--是否WMS生成
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='IsFromWms'
    )
    BEGIN
	ALTER TABLE BillIndex 
		ADD IsFromWms INT NULL DEFAULT(0)
    END
GO
--易聚客生成单据编号  
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndex' AND a.Name='YjkBillCode'
    )
    BEGIN
	ALTER TABLE BillIndex 
		ADD YjkBillCode VARCHAR(200) NULL DEFAULT('')
    END
GO
UPDATE  BillIndex SET  YjkBillCode = '' WHERE YjkBillCode IS NULL            
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Billindex_CarRepair]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Billindex_CarRepair]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Billindex_CarRepair](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[RATypeID] [varchar](50) NOT NULL,
		[OperationSort] [varchar](200) NULL,
		[RepairMode] [varchar](200) NULL,
		[Oil] [varchar](200) NULL,
		[Mileage] [varchar](200) NULL,
		[EpibolyItem] [varchar](200) NULL,
		[OtherItem] [varchar](200) NULL,
		[Status] INT NOT NULL DEFAULT 0,
		[ManHourTotal] [numeric](18, 4) NOT NULL DEFAULT 0,
		[ManHourTax] [numeric](18, 4) NOT NULL DEFAULT 0,
		[ManHourTaxTotal] [numeric](18, 4) NOT NULL DEFAULT 0,
		[PTypeTotal] [numeric](18, 4) NOT NULL DEFAULT 0,
		[PTypeTax] [numeric](18, 4) NOT NULL DEFAULT 0,
		[PTypeTaxTotal] [numeric](18, 4) NOT NULL DEFAULT 0,
		[EpibolyTotal] [numeric](18, 4) NOT NULL DEFAULT 0,
		[OtherTotal] [numeric](18, 4) NOT NULL	 DEFAULT 0,
		[InPriceType] varchar(50) NOT NULL DEFAULT '',
		[BTypeID1] VARCHAR(50) NULL,
		[QuickRepairBillID] NUMERIC(10,0) NULL,
		[ManHourInsuranceTotal] NUMERIC(18,4) NOT NULL DEFAULT 0,
		[PTypeInsuranceTotal] NUMERIC(18,4) NOT NULL DEFAULT 0,
		[InvoiceMode] INT NULL,
		[InvoiceCode] VARCHAR(200) NOT NULL DEFAULT '',
		[InsuranceStatus] INT NOT NULL DEFAULT 0
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Billindex_CarRepair' AND a.Name='RepairType')
BEGIN
	ALTER TABLE Billindex_CarRepair ADD 
		RepairType INT NULL	DEFAULT(0),
		BespokeDate DATETIME NULL,
		ReceptionDate DATETIME NULL,
		CompleteDate DATETIME NULL,
		InFactoryDate DATETIME NULL,
		FactCompleteDate DATETIME NULL,
		ReceptionId VARCHAR(50) NULL,
		UnitSatrap VARCHAR(50) NULL,
		SendPerson VARCHAR(50) NULL,
		ErrDescription VARCHAR(2000) NULL,
		EpibolyCostTotal NUMERIC(18,4) DEFAULT(0),
		PreferenceReason VARCHAR(250) NULL DEFAULT(''),
		BalanceDate DATETIME NULL,
		ItemPrincipal VARCHAR(50) NULL DEFAULT(''),
		MonitorPrincipal VARCHAR(50) NULL DEFAULT(''),
		BillState INT NULL DEFAULT(0),
		IntendingKickback NUMERIC(18,4) NULL DEFAULT(0),
		SettlementKickback NUMERIC(18,4) NULL DEFAULT(0),
		BackTypeId INT NULL DEFAULT(0),
		IntendingTalkBackDate DATETIME NULL,
		IsTalkBackOver INT NULL DEFAULT(0) 
END
GO
IF EXISTS(SELECT TOP 1 1 FROM syscolumns A INNER JOIN sysobjects b ON A.id = b.id INNER JOIN systypes T ON A.xtype = T.xtype WHERE B.name = 'BillIndex_CarRepair' AND T.Name = 'varchar' AND A.name = 'IntendingKickback')
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE name LIKE 'DF__Billindex__Inten%')
	BEGIN
		DECLARE @strName varchar(100)
		SELECT @strName=Name FROM sysobjects WHERE name LIKE 'DF__Billindex__Inten%'
		EXEC('ALTER TABLE [dbo].[BillIndex_CarRepair] DROP CONSTRAINT ['+@strName+']')
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE name LIKE 'DF__Billindex__Settl%')
	BEGIN
		DECLARE @strName1 varchar(100)
		SELECT @strName1=Name FROM sysobjects WHERE name LIKE 'DF__Billindex__Settl%'
		EXEC('ALTER TABLE [dbo].[BillIndex_CarRepair] DROP CONSTRAINT ['+@strName1+']')
	END	

	ALTER TABLE Billindex_CarRepair DROP COLUMN IntendingKickback,SettlementKickback
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Billindex_CarRepair' AND a.Name='IntendingKickback')
BEGIN
	ALTER TABLE Billindex_CarRepair ADD 
	IntendingKickback NUMERIC(18,4) NULL DEFAULT(0),
	SettlementKickback NUMERIC(18,4) NULL DEFAULT(0)
END
GO	
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Billindex_CarRepair' AND a.Name='CounterClaimStatus')
BEGIN
	ALTER TABLE Billindex_CarRepair ADD 
		CounterClaimStatus INT NULL DEFAULT(0)
END
GO	
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Billindex_CarRepair' AND a.Name='CzBeforeTimes')
BEGIN
	ALTER TABLE Billindex_CarRepair ADD 
		CzBeforeTimes INT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Billindex_CarRepair' AND a.Name='RepairAutoTypeId')
BEGIN
	ALTER TABLE Billindex_CarRepair ADD 
		RepairAutoTypeId VARCHAR(50) NULL DEFAULT('')
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Billindex_CarRepair SET IntendingKickback = 0 WHERE IntendingKickback IS NULL
GO
UPDATE Billindex_CarRepair SET SettlementKickback = 0 WHERE SettlementKickback IS NULL
GO
UPDATE Billindex_CarRepair SET CounterClaimStatus = 0 WHERE CounterClaimStatus IS NULL
GO
UPDATE Billindex_CarRepair SET EpibolyCostTotal = 0 WHERE EpibolyCostTotal IS NULL
GO
UPDATE Billindex_CarRepair SET CzBeforeTimes = 0 WHERE CzBeforeTimes IS NULL
GO
UPDATE Billindex_CarRepair SET CompleteDate = '9999-12-31 23:59:59.997' WHERE CompleteDate IS NULL
GO
UPDATE Billindex_CarRepair SET BespokeDate = '9999-12-31 23:59:59.997' WHERE BespokeDate IS NULL
GO
UPDATE Billindex_CarRepair SET repairtype = 0 WHERE repairtype IS NULL
GO
UPDATE Billindex_CarRepair SET ReceptionDate = '9999-12-31 23:59:59.997' WHERE ReceptionDate IS NULL
GO
UPDATE Billindex_CarRepair SET InFactoryDate = '9999-12-31 23:59:59.997' WHERE InFactoryDate IS NULL
GO
UPDATE Billindex_CarRepair SET BillState = 1 WHERE BillState IS NULL
GO
UPDATE Billindex_CarRepair SET RepairAutoTypeId = '' WHERE RepairAutoTypeId IS NULL
GO
UPDATE Billindex_CarRepair SET BalanceDate = '9999-12-31 23:59:59.997' WHERE BalanceDate IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='ManHourTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN ManHourTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='ManHourTax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN ManHourTax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='ManHourTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN ManHourTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='PTypeTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN PTypeTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='PTypeTax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN PTypeTax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='PTypeTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN PTypeTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='EpibolyTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN EpibolyTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='OtherTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN OtherTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='ManHourInsuranceTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN ManHourInsuranceTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='PTypeInsuranceTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN PTypeInsuranceTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='EpibolyCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN EpibolyCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='IntendingKickback' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN IntendingKickback NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Billindex_CarRepair' AND a.Name='SettlementKickback' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Billindex_CarRepair 
	ALTER COLUMN SettlementKickback NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[BillIndexAutoDraft](
		[BillGuid]	VARCHAR(100) NULL DEFAULT(''),
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_BillIndexAutoDraft_BillCode]  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](MAX) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_BillComment]  DEFAULT (''),
		[atypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_atypeid]  DEFAULT ('0'),
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_ptypeid]  DEFAULT ('0'),
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_btypeid]  DEFAULT ('0'),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_etypeid]  DEFAULT ('0'),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_ktypeid]  DEFAULT ('0'),
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_ktypeid2]  DEFAULT ('0'),
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_ifcheck]  DEFAULT ('t'),
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalmoney] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndexAutoDraft_total]  DEFAULT (0),
		[totalinmoney] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndexAutoDraft_totalinmoney]  DEFAULT (0),--在零售单中 对应packway字段
		[totalqty] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndexAutoDraft_totalqty]  DEFAULT (0),
		[tax] [numeric](5, 2) NULL CONSTRAINT [DF_BillIndexAutoDraft_tax]  DEFAULT (17),
		[period] [smallint] NULL CONSTRAINT [DF_BillIndexAutoDraft_period]  DEFAULT (0),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_explain]  DEFAULT (''),
		[RedWord] [int] NOT NULL CONSTRAINT [DF_BillIndexAutoDraft_RedWord]  DEFAULT (0),
		[draft] [bit] NOT NULL CONSTRAINT [DF_BillIndexAutoDraft_draft]  DEFAULT (0),
		[OrderId] [numeric](10, 0) NULL CONSTRAINT [DF_BillIndexAutoDraft_OrderId]  DEFAULT (0),
		[waybillcode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_billinexAutoDraft_goodsnumber]  DEFAULT (''),
		[packway] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,--在零售单中 此字段表示收现金额
		[TEL] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,--在零售单中 此字段表示找零
		[Uploaded] [bit] NOT NULL CONSTRAINT [DF_BillIndexAutoDraft_Uploaded]  DEFAULT (0),
		[OFF_ID] [uniqueidentifier] NULL,
		[TeamNo] [int] NULL,
		[AlertDay] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_AlertDay]  DEFAULT (9999),
		[CompleteTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndexAutoDraft_CompleteTotal]  DEFAULT (0),
		[ID] [numeric](10, 0) NOT NULL CONSTRAINT [DF_BillIndexAutoDraft_ID]  DEFAULT (0),
		[Assessor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfAudit] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[Audit_explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[IfStopMoney] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_IfStopMoney]  DEFAULT (0),
		[preferencemoney] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndexAutoDraft_preferencemoney]  DEFAULT (0),
		[DTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_DTypeId]  DEFAULT ('0'),
		[JF] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_JF]  DEFAULT (0),
		[VipCardID] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_VipCardID]  DEFAULT ((-1)),
		[vipCZMoney] [numeric](18, 4) NULL,
		[jsStyle] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_jsStyle]  DEFAULT (0),--结算方式 0未结算 1 按单 2 按商品 3 按品牌 4.混合（按单，按品牌 应收增加减少单）
		[jsState] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_jsState]  DEFAULT (0),--结算状态 0未结算 1 已结算未完成 2 结算完成
		[KTypeID3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_KTypeID3]  DEFAULT ('0'),
		[LinkMan] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_LinkMan]  DEFAULT (''),
		[LinkTel] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_LinkTel]  DEFAULT (''),
		[LinkAddr] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_LinkAddr]  DEFAULT (''),
		[wxManID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_wxMan]  DEFAULT (''),
		[JieJianBillNumberID] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_JieJianCode]  DEFAULT ((-1)),
		[JieJianID] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_JieJianID]  DEFAULT ((-1)),
		[JieJianState] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_JieJianState]  DEFAULT ((-1)),
		[BaoXiuBillNumberID] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_BaoXiuCode]  DEFAULT ((-1)),
		[BaoXiuID] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_BaoXiuID]  DEFAULT ((-1)),
		[BuyDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_BuyDate]  DEFAULT (''),
		[Serial] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_Serial]  DEFAULT (''),
		[wxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BillIndexAutoDraft_wxTotal]  DEFAULT (0),
		[ErrDes] [varchar](3000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BillIndexAutoDraft_ErrDes]  DEFAULT (''),
		[ifHideJieJian] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_ifHideJieJian]  DEFAULT (0),
		[ifWX] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_ifWX]  DEFAULT (0),
		[ifYearBill] [int] NULL CONSTRAINT [DF_BillIndexAutoDraft_ifYearBill]  DEFAULT (0),
		[Poster] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LastUpdateTime] DateTime NULL CONSTRAINT [DF_BillIndexAutoDraft_LastUpdateTime]  DEFAULT GETDATE(),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL DEFAULT ('0'),
		[CostSale] [BIT] DEFAULT 0,
		[OtherInOutType]	INT DEFAULT 0,
		[PosBillType] INT NULL DEFAULT 0,
		[checkTime]		DATETIME NULL,
		[posttime]		DATETIME NULL,
		[updateE]		VARCHAR(50) NULL  DEFAULT (''),
		[ShareMode]		TINYINT NULL	DEFAULT 0,
		[TransportId]   VARCHAR(10) NULL DEFAULT(0),
		[IsIni]			BIT NULL DEFAULT(0),
		[ATypeID1]		VARCHAR(50) NULL DEFAULT(''),
		[NCompleteTotal] [numeric](22, 10) NULL DEFAULT (0),
		[ATID]			INT DEFAULT(0),
		[IfCargo]		BIT DEFAULT(0),
		[InvoiceMoney] numeric(22,10) null DEFAULT(0),
		[NInvoiceMoney] numeric(22,10) null DEFAULT(0),
		[RedReason] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		PrePriceNum INT DEFAULT(0) NOT NULL, --预设售价，进价
		AssetBusinessTypeId int, --固定资产业务类型id
		PromoRuleId int NOT NULL DEFAULT(0), --促销方案id
		BeforePromoBillNumberId int NOT NULL DEFAULT(0), --促销前数据id
		ImportType tinyint NOT NULL DEFAULT(0), --导入类型
		NewPosBill tinyint NULL DEFAULT(0),
		[PromotionMsg] NVARCHAR(500) NOT NULL DEFAULT(0),
		[Reconciliation] CHAR(1) DEFAULT('f'), --对账 默认f 对账t
		/*添加字段 ARTOTAL,APTOTAL,YSTOTAL,YFTOTAL 2014-1-15 tangtao */
		 ARTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 APTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 YSTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 YFTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 IsAuto int DEFAULT(0), --0=手动，1=自动
		IsYapi bit NULL DEFAULT(0),
		YapiOrderID NUMERIC(20,0) NULL DEFAULT(0),
		DeliveryAddress VARCHAR(256) NOT NULL DEFAULT(''), --送货地址
		AddDTypeETypeType INT NOT NULL DEFAULT(0), --补录部门经手人类型 0 未补录 1 补录过部门 2补录过经手人 3 同时都补录过
		BillTime VARCHAR(20)  NULL, -- 单据的时分秒
		citestate int NOT NULL DEFAULT(0),--拣货状态0=未引用1=已引用未完成2=已完成
		ShelveRefState INT NOT NULL DEFAULT(0),				--上架引用状态  0=未引用1=已引用未完成2=已完成
		progressstate int NOT NULL DEFAULT(0),				--0=已开单1=拣货中2=已出库
		ShelveState   INT NOT NULL DEFAULT(0),				--上架状态 0=已开单1=上架中2=已上架
		TransPortState INT NOT NULL DEFAULT(0),				--运输状态 0=已开单，1=发运中，2=已发运
		[WarehouseOutDay] [int] NULL DEFAULT (9999),--出库期限@StockInDeadline
		[StockInDeadline] [int] NULL DEFAULT (9999),--出库期限
		shipper VARCHAR(50) NULL DEFAULT(''), --托运方
		totalfreight NUMERIC(24,10) NULL DEFAULT(0),--合计运费
		Ntotalfreight NUMERIC(24,10) NULL DEFAULT(0),--原币合计运费
		transportno varchar(200)	NULL DEFAULT(''),--承运商运单号
		Transporterid varchar(50)	NULL DEFAULT('0'),--承运商id
		Transporterfullname varchar(200)	NULL DEFAULT(''),--承运商名称
		shipperfullname varchar(100)	NULL DEFAULT(''),--托运方
		shipperperson varchar(100)	NULL DEFAULT(''),--托运人
		shippertel varchar(100)	NULL DEFAULT(''),--托运联系电话
		[FaPiaoCode] [varchar](256)  NULL CONSTRAINT [DF_BillIndexAutoDraft_FaPiaoCode]  DEFAULT (''),
		InFactState       INT DEFAULT(0),	  --1 仓库入库未完成 2仓库入库已完成
		InFactRefState    INT DEFAULT(0),    -- 0仓库入库未引用  1仓库入库已引用
		OutFactState	  INT DEFAULT(0),	  --1 仓库出库未完成 2仓库出库已完成	
		OutFactRefState   INT DEFAULT(0),	  --0 仓库出库未引用 1仓库出库已引用
		PayType int DEFAULT(0),--是否支付  0-未支付 1-已支付
		PromonIds VARCHAR(1000) NULL DEFAULT('') ,--所有使用的促销方案id，逗号分隔
		isByBrandarType	 INT NULL  DEFAULT(0), --按品牌收款
		PayOnTheSpot	INT NOT NULL DEFAULT(0),	--是否当面付：0否 1是
		UploadPreOrder	INT NOT NULL DEFAULT(0),	--是否上传预订单：0否 1是
		PreOrderStatus	INT	NOT NULL DEFAULT(0),	--预订单状态 2为已支付 其他为未支付
		PreOrderId		VARCHAR(50) NOT NULL DEFAULT(''), --预订单id
		PosId			INT, --pos机id
		RChecker		VARCHAR(50) NULL DEFAULT(''),	--反审核人
		RVaildDate		DATETIME NULL,				--反审核时间
		CreateDate		DATETIME DEFAULT(GETDATE())
	) ON [PRIMARY]

END
GO


------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='PosId'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD PosId INT NOT NULL DEFAULT (0)
END

GO


-- 添加促销方案id字段，记录商品应用的所有促销方案
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='PromonIds')
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft
	ADD PromonIds VARCHAR(1000) NULL DEFAULT('')
END
ELSE
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft
	ALTER Column PromonIds VARCHAR(1000) NULL
END
GO

--是否支付
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='PayType')
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft 
	ADD PayType INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='InFactRefState')
BEGIN
	ALTER TABLE BillIndexAutoDraft
	ADD InFactRefState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='OutFactRefState')
BEGIN
	ALTER TABLE BillIndexAutoDraft
	ADD OutFactRefState INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='InFactState')
BEGIN
	ALTER TABLE BillIndexAutoDraft
	ADD InFactState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='OutFactState')
BEGIN
	ALTER TABLE BillIndexAutoDraft
	ADD OutFactState INT DEFAULT(0)
END
GO
	UPDATE dbo.BillIndexAutoDraft SET InFactState=0 WHERE InFactState IS NULL
	UPDATE dbo.BillIndexAutoDraft SET OutFactState=0 WHERE OutFactState IS NULL
	UPDATE dbo.BillIndexAutoDraft SET InFactRefState=0 WHERE InFactRefState IS NULL
	UPDATE dbo.BillIndexAutoDraft SET OutFactRefState=0 WHERE OutFactRefState IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='ShelveState')
BEGIN
	ALTER TABLE BillIndexAutoDraft
	ADD ShelveState INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='ShelveRefState')
BEGIN
	ALTER TABLE BillIndexAutoDraft
	ADD ShelveRefState INT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='TransPortState')
BEGIN
	ALTER TABLE BillIndexAutoDraft
	ADD TransPortState INT NOT NULL DEFAULT(0)
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='TEL'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ALTER COLUMN TEL  [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='CWCheck'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD CWCheck INT NOT NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IfBargainOn' 
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD IfBargainOn INT NULL DEFAULT(0)
END
GO
UPDATE BillIndexAutoDraft SET IfBargainON=0 WHERE IfBargainON IS NULL

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='LastUpdateTime'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD LastUpdateTime DateTime NULL CONSTRAINT [DF_BillIndexAutoDraft_LastUpdateTime]  DEFAULT GETDATE()
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='Poster'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD Poster VARCHAR(50) NOT NULL DEFAULT ('')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE BillIndexAutoDraft SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD FromBillNumberID [numeric](10, 0)  NULL DEFAULT ('0')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='CostSale'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD CostSale [bit]  NULL	DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IfMulAccount'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD IfMulAccount INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='OtherInOutType'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD OtherInOutType INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='PosBillType'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD PosBillType INT NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='checkTime'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD checkTime DATETIME NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='posttime'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD posttime DATETIME NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='updateE'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD updateE VARCHAR(50) NULL DEFAULT('') 
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ShareMode'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD ShareMode TINYINT NULL DEFAULT 0
END
GO

IF  EXISTS(
	SELECT b.name 
	FROM  sysconstraints a  
	INNER JOIN sysobjects b 
	ON a.constid= b.id AND b.xtype='d' AND a.constid= OBJECT_ID(N'[dbo].[DF_BillIndexAutoDraft_LastUpdateTime]')
)
BEGIN
	ALTER TABLE BillIndexAutoDraft  DROP [DF_BillIndexAutoDraft_LastUpdateTime] 
END
GO



IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndexAutoDraft' AND a.Name='IsFreightMoney')
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD IsFreightMoney INT NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndexAutoDraft' AND a.Name='FreightAddr')
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD FreightAddr VARCHAR(300) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndexAutoDraft' AND a.Name='FreightPerson')
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD FreightPerson VARCHAR(100) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndexAutoDraft' AND a.Name='FreightTel')
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD FreightTel VARCHAR(100) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndexAutoDraft' AND a.Name='IfInvoice')
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD IfInvoice INT NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='BillIndexAutoDraft' AND a.Name='TransportId')
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD TransportId VARCHAR(10) NULL DEFAULT(0) 
END
GO	

--添加自定义字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='UF1'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD UF1 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='UF2'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD UF2 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='UF3'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD UF3 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='UF4'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD UF4 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='UF5'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD UF5 VARCHAR(200)  NULL DEFAULT('')
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ATID'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD ATID INT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NewPosBill'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD NewPosBill tinyint NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='iscombinationstyle'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD iscombinationstyle tinyint NULL DEFAULT(0)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='telandaddress'
)
BEGIN
	IF NOT EXISTS(
		SELECT a.Name FROM syscolumns a
		INNER JOIN sysobjects	b
		ON a.ID=b.ID
		WHERE b.Name='BillIndexAutoDraft' AND a.Name='DeliveryAddress'
	)
		EXEC sp_rename 'BillIndexAutoDraft.telandaddress','DeliveryAddress','column'
	ELSE
		BEGIN
			-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
			DECLARE @t1 TABLE(name VARCHAR(100)); 
			INSERT INTO @t1 SELECT 'telandaddress'
			DECLARE @sql1 NVARCHAR(max)='';
			DECLARE @tn1 NVARCHAR(500)='BillIndexAutoDraft';

			SELECT @sql1=@sql1+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn1+' drop constraint '+a.name+';' END
				+ ' alter table '+@tn1+' drop column '+d.name+';'
			FROM sys.default_constraints a 
				RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
				JOIN @t1 d ON b.name=d.name
				WHERE b.object_id=object_id(@tn1,'U')

			IF @sql1<>''
				EXEC(@sql1);
			
		END
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='DeliveryAddress'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD DeliveryAddress VARCHAR(256) NOT NULL DEFAULT('') --送货地址
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='AddDTypeETypeType'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD AddDTypeETypeType TINYINT NOT NULL DEFAULT(0)
END
GO



-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'SettleBTypeID' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'CurID' UNION ALL SELECT 'TaskType'
UNION ALL SELECT 'NARTOTAL'
UNION ALL SELECT 'NAPTOTAL'
UNION ALL SELECT 'NYSTOTAL'
UNION ALL SELECT 'NYFTOTAL';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='BillIndexAutoDraft';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='DealBTypeID'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD DealBTypeID VARCHAR(50)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='CID'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD CID int  NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD Rate NUMERIC(22,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD NTotalMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NTotalInMoney'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD NTotalInMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NPreferenceMoney'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD NPreferenceMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NVIPCZMoney'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD NVIPCZMoney NUMERIC(22,10) DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD IsIni BIT NULL DEFAULT(0)
		
	EXEC('UPDATE BillIndexAutoDraft SET IsIni=0 WHERE IsIni IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ATypeID1'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD ATypeID1 VARCHAR(50) NULL DEFAULT('')
		
	
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NCompleteTotal'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
ELSE
BEGIN
	ALTER TABLE BillIndexAutoDraft ALTER COLUMN NCompleteTotal NUMERIC(22,10)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='billproperty'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD billproperty int default(-1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='TallyId'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD TallyId VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IfCargo'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD IfCargo BIT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='InvoiceMoney'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD InvoiceMoney NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NInvoiceMoney'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD NInvoiceMoney NUMERIC(22,10) NULL DEFAULT(0)
END
GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='progressstate'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD progressstate INT NULL DEFAULT(0)
END
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ac_Currency]') AND type in (N'U')) AND EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetCid]') and xtype in (N'FN', N'IF', N'TF'))
	BEGIN
		UPDATE t SET t.rate = t1.rate 
		FROM BillIndexAutoDraft T JOIN Ac_Currency t1 
		ON T.cid = t1.cid
		WHERE t.Rate = 0
		--EXEC('

		--	UPDATE  BillIndexAutoDraft
		--	SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
		--						   THEN ROUND(APTOTAL * Rate, 2)
		--						   ELSE ROUND(APTOTAL / Rate, 2)
		--						   END
		--	WHERE  APTOTAL IS NOT NULL

		--	UPDATE  BillIndexAutoDraft
		--	SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
		--						   THEN ROUND(YSTOTAL * Rate, 2)
		--						   ELSE ROUND(YSTOTAL / Rate, 2)
		--						   END
		--	WHERE  YSTOTAL IS NOT NULL

		--	UPDATE  BillIndexAutoDraft
		--	SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
		--						   THEN ROUND(YFTOTAL * Rate, 2)
		--						   ELSE ROUND(YFTOTAL / Rate, 2)
		--						   END
		--	WHERE  YFTOTAL IS NOT NULL
		--')
	END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='RedReason'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD RedReason [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='PrePriceNum'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD PrePriceNum INT DEFAULT(0) NOT NULL;
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='AssetBusinessTypeId'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD AssetBusinessTypeId INT
END

go
--促销方案id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='PromoRuleId'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD PromoRuleId INT NOT NULL DEFAULT(0)
END
go
--促销前数据id
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='BeforePromoteBillNumberId'
)
BEGIN
	EXEC sp_rename 'BillIndexAutoDraft.BeforePromoteBillNumberId','BeforePromoBillNumberId','column';
END
ELSE
BEGIN
	IF NOT EXISTS(
		SELECT a.Name FROM syscolumns a
		INNER JOIN sysobjects	b
		ON a.ID=b.ID
		WHERE b.Name='BillIndexAutoDraft' AND a.Name='BeforePromoBillNumberId'
	)
	BEGIN
		ALTER TABLE BillIndexAutoDraft ADD BeforePromoBillNumberId  INT NOT NULL DEFAULT(0)
	END
END
go
--导入类型
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ImportType'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD ImportType tinyint NOT NULL DEFAULT(0);
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='PromotionMsg'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD [PromotionMsg] NVARCHAR(500) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD [Reconciliation] CHAR(1) DEFAULT('f') --对账 默认f 对账t
END
go


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ARTOTAL'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD ARTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='APTOTAL'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD APTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='YSTOTAL'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD YSTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='YFTOTAL'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD YFTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IsAuto'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD IsAuto int DEFAULT(0) --0=手动，1=自动
END
GO

--增加一个分支机构id(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='StypeID2'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD StypeID2 VARCHAR(50) NULL DEFAULT('')
END
GO
--是否确认入账(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IfConfirm'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD IfConfirm INT NOT NULL DEFAULT(0)
END
GO

--资金调拨业务类型(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='TransferType'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD TransferType INT NOT NULL DEFAULT(1)
END
GO
--资金调拨单费用扣除账户类型:1,调出账户，2,调入账户(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='FeeDeductType'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD FeeDeductType INT NOT NULL DEFAULT(1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IsYapi'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD IsYapi bit NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='YapiOrderID'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD YapiOrderID NUMERIC(20,0) NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='BillTime'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD BillTime VARCHAR(20) NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IsLend'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD IsLend BIT  NULL DEFAULT(0)
END
GO

--增加扣率
IF NOT EXISTS (SELECT Name FROM SYSColumns WHERE ID=OBJECT_ID('BillIndexAutoDraft') AND Name='Discount')
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft
	Add Discount NUMERIC(22,10) DEFAULT(1)
END

--增加业务类型,只用于成本条件单,默认为库存0,1-入库,2-出库
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='AdPriceType'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD AdPriceType TINYINT NOT NULL DEFAULT(0)
END
GO

--9.6.1运单号从20个字符升级为50个字符
IF EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID('BillIndexAutoDraft',N'U') AND LOWER(Name)='waybillcode' AND [Length]=20)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft
	ALTER COLUMN waybillcode VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL
END
--自定义字段结束
--添加往来核销单需要的字段

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ChargeOffBtypeid'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD ChargeOffBtypeid VARCHAR(50) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ChargeOffType'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD ChargeOffType INT NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ChargeOffTotal'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD ChargeOffTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NChargeOffTotal'
)
BEGIN
	ALTER TABLE BillIndexAutoDraft ADD NChargeOffTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='cwchecker'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD cwchecker VARCHAR(50)  NULL  DEFAULT('')
END
GO
--添加往来核销单需要的字段结束

--引用状态
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='citestate'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD citestate INT  NOT NULL DEFAULT(0)
END

IF EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	LEFT JOIN syscomments e ON a.cdefault=e.id AND a.id= OBJECT_ID('BillIndexAutoDraft')
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='citestate' AND e.text IS NULL)
BEGIN
	ALTER TABLE BillIndexAutoDraft add constraint df_citestate default (0) for citestate
END
go
UPDATE BillIndexAutoDraft SET citestate=0 WHERE citestate IS NULL
go
  --上架、拣货、运输等状态
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='progressstate'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD progressstate INT
END
--是否需要运输配送
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IsNeedTransport'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD IsNeedTransport BIT
END
--托运方
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='shipper'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD shipper VARCHAR(50)
END
--合计运费
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='totalfreight'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD totalfreight NUMERIC(24,10)
END
--原币合计运费
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ntotalfreight'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD ntotalfreight NUMERIC(24,10)
END

--承运商运单号
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='transportno'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD transportno varchar(200)
END
--出库期限
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='WarehouseOutDay'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD [WarehouseOutDay] VARCHAR(50)
END
--入库期限
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='StockInDeadline'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD [StockInDeadline] VARCHAR(50)
END
--承运商档案
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='Transporterid'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD [Transporterid] VARCHAR(50) NULL DEFAULT('0')
END
--承运商档案
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='Transporterfullname'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD [Transporterfullname] VARCHAR(200) NULL DEFAULT('')
END
--托运方
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='shipperfullname'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD [shipperfullname] VARCHAR(100) NULL DEFAULT('')
END
--托运人
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='shipperperson'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD [shipperperson] VARCHAR(100) NULL DEFAULT('')
END
--托运联系电话
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='shippertel'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD [shippertel] VARCHAR(100) NULL DEFAULT('')
END
--发票编号
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='FaPiaoCode'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD [FaPiaoCode] VARCHAR(256) NULL DEFAULT('')
END

--按品牌收款
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='isByBrandarType'
)
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft ADD isByBrandarType INT NULL   DEFAULT(0)
END
GO
UPDATE BillIndexAutoDraft SET isByBrandarType=0 WHERE  isByBrandarType IS NULL
GO

--是否当面付
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='PayOnTheSpot')
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft 
	ADD PayOnTheSpot INT NOT NULL DEFAULT(0)
END
GO

--是否上传预订单
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='UploadPreOrder')
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft 
	ADD UploadPreOrder INT NOT NULL DEFAULT(0)
END
GO

--预订单状态 2为已支付 其他为未支付
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='PreOrderStatus')
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft 
	ADD PreOrderStatus	INT	NOT NULL DEFAULT(0)
END
GO

--预订单id
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillIndexAutoDraft',N'U') AND Name='PreOrderId')
BEGIN
	ALTER TABLE dbo.BillIndexAutoDraft 
	ADD PreOrderId	VARCHAR(50) NOT NULL DEFAULT('')
END
GO


-------9.91添加反审核人、反审核时间-------- 
if not exists (select name from syscolumns where id = object_id(N'[dbo].[BillIndexAutoDraft]') and name = 'RChecker' )
BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ADD RChecker VARCHAR(50) NULL DEFAULT('')
END
GO
UPDATE BillIndexAutoDraft SET RChecker = '' WHERE RChecker IS NULL
GO

---反审核日期
IF NOT EXISTS (select name from syscolumns where id = object_id(N'[dbo].[BillIndexAutoDraft]') and name = 'RVaildDate' )
BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ADD RVaildDate DATETIME NULL
END
GO
-----------------END-----------------------


------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'NCIX_IFCHECK')
--	DROP INDEX [dbo].BillIndexAutoDraft.NCIX_IFCHECK

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'NCIX_REDWORD')
--	DROP INDEX [dbo].BillIndexAutoDraft.NCIX_REDWORD

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'NCIX_BILLTYPE')
--	DROP INDEX [dbo].BillIndexAutoDraft.NCIX_BILLTYPE

--IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'NCIX_DRAFT')
--	DROP INDEX [NCIX_DRAFT] ON [dbo].[BillIndexAutoDraft]
--GO

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'IX_BillIndexAutoDraft_ATypeID')
--	DROP  INDEX [IX_BillIndexAutoDraft_ATypeID] ON BillIndexAutoDraft 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'IX_BillIndexAutoDraft_BillCode')
--DROP  INDEX [IX_BillIndexAutoDraft_BillCode] ON BillIndexAutoDraft 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'IX_BillIndexAutoDraft_BillDate')
--DROP  INDEX [IX_BillIndexAutoDraft_BillDate] ON BillIndexAutoDraft 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'IX_BillIndexAutoDraft_BillNumberId')
--DROP  INDEX [IX_BillIndexAutoDraft_BillNumberId] ON BillIndexAutoDraft 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'IX_BillIndexAutoDraft_BTypeId')
--DROP INDEX [IX_BillIndexAutoDraft_BTypeId] ON BillIndexAutoDraft 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'IX_BillIndexAutoDraft_ETypeID')
--DROP INDEX [IX_BillIndexAutoDraft_ETypeId] ON BillIndexAutoDraft 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'IX_BillIndexAutoDraft_KTypeID')
--DROP INDEX [IX_BillIndexAutoDraft_KTypeId] ON BillIndexAutoDraft 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'IX_BillIndexAutoDraft_KTypeID2')
--DROP INDEX [IX_BillIndexAutoDraft_KTypeId2] ON BillIndexAutoDraft 
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillIndexAutoDraft') AND name = 'CIX_BillIndexAutoDraft_BillDate')
--DROP INDEX CIX_BillIndexAutoDraft_BillDate ON BillIndexAutoDraft 
CREATE CLUSTERED INDEX CIX_BillIndexAutoDraft_BillDate ON BillIndexAutoDraft(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillIndexAutoDraft') AND name = 'NCIX_BillIndexAutoDraft_BillNumberID')
--DROP INDEX NCIX_BillIndexAutoDraft_BillNumberID ON BillIndexAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillIndexAutoDraft_BillNumberID ON BillIndexAutoDraft(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillIndexAutoDraft') AND name = 'NCIX_BillIndexAutoDraft_Billcode')
--DROP INDEX NCIX_BillIndexAutoDraft_Billcode ON BillIndexAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillIndexAutoDraft_Billcode ON BillIndexAutoDraft(Billcode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillIndexAutoDraft') AND name = 'NCIX_BillIndexAutoDraft_Btypeid')
--DROP INDEX NCIX_BillIndexAutoDraft_Btypeid ON BillIndexAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillIndexAutoDraft_Btypeid ON BillIndexAutoDraft(Btypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillIndexAutoDraft') AND name = 'NCIX_BillIndexAutoDraft_Atypeid')
--DROP INDEX NCIX_BillIndexAutoDraft_Atypeid ON BillIndexAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillIndexAutoDraft_Atypeid ON BillIndexAutoDraft(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillIndexAutoDraft') AND name = 'NCIX_BillIndexAutoDraft_Etypeid')
--DROP INDEX NCIX_BillIndexAutoDraft_Etypeid ON BillIndexAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillIndexAutoDraft_Etypeid ON BillIndexAutoDraft(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillIndexAutoDraft') AND name = 'NCIX_BillIndexAutoDraft_Ktypeid')
--DROP INDEX NCIX_BillIndexAutoDraft_Ktypeid ON BillIndexAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillIndexAutoDraft_Ktypeid ON BillIndexAutoDraft(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillIndexAutoDraft') AND name = 'NCIX_BillIndexAutoDraft_Ktypeid2')
--DROP INDEX NCIX_BillIndexAutoDraft_Ktypeid2 ON BillIndexAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillIndexAutoDraft_Ktypeid2 ON BillIndexAutoDraft(Ktypeid2) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'NCIX_BillIndexAutoDraft_BILLTYPE')
--DROP INDEX NCIX_BillIndexAutoDraft_BILLTYPE ON BillIndexAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillIndexAutoDraft_BILLTYPE ON BillIndexAutoDraft(BILLTYPE) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[BillIndexAutoDraft]') AND name = N'NCIX_BillIndexAutoDraft_STYPEID_INCLUDE')
--DROP INDEX [NCIX_BillIndexAutoDraft_STYPEID_INCLUDE] ON [dbo].[BillIndexAutoDraft] WITH ( ONLINE = OFF )
--GO
CREATE NONCLUSTERED INDEX [NCIX_BillIndexAutoDraft_STYPEID_INCLUDE] ON [dbo].[BillIndexAutoDraft] 
(
	[Stypeid] ASC,
	[BillDate] ASC,
	[BillType] ASC
)
INCLUDE ( [BillNumberId]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE BillIndexAutoDraft SET FromBillNumberID = 0 WHERE FromBillNumberID IS NULL
GO
UPDATE BillIndexAutoDraft SET CostSale = 0 WHERE CostSale IS NULL
GO
UPDATE BillIndexAutoDraft SET IfMulAccount = 0 WHERE IfMulAccount IS NULL
GO
UPDATE BillIndexAutoDraft SET sharemode = 0 WHERE sharemode IS NULL
GO
UPDATE BillIndexAutoDraft SET posbilltype = 0 WHERE posbilltype IS NULL
GO
UPDATE BillIndexAutoDraft SET TransportId = 0 WHERE TransportId IS NULL
GO
UPDATE BillIndexAutoDraft SET IsFreightMoney = 0 WHERE IsFreightMoney IS NULL
GO
UPDATE BillIndexAutoDraft SET FreightAddr = '' WHERE FreightAddr IS NULL
GO
UPDATE BillIndexAutoDraft SET FreightPerson = '' WHERE FreightPerson IS NULL
GO
UPDATE BillIndexAutoDraft SET FreightTel = '' WHERE FreightTel IS NULL
GO
UPDATE BillIndexAutoDraft SET IfInvoice = 0 WHERE IfInvoice IS NULL
GO
UPDATE BillIndexAutoDraft SET billproperty = -0 WHERE IfInvoice IS NULL
GO
UPDATE BillIndexAutoDraft SET TallyId = '' WHERE TallyId IS NULL
GO
UPDATE BillIndexAutoDraft SET NewPosbill = 0 WHERE NewPosbill IS NULL
GO
UPDATE BillIndexAutoDraft SET IsLend = 0 WHERE IsLend IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='preferencemoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN preferencemoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='vipCZMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN vipCZMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='wxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN wxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ARTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN ARTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='APTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN APTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='YSTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN YSTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='YFTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN YFTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NTotalInMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN NTotalInMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NPreferenceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN NPreferenceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NVIPCZMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN NVIPCZMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='ChargeOffTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN ChargeOffTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='NChargeOffTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN NChargeOffTotal NUMERIC(24,10)
    END
    
 
  
 alter table BillIndexAutoDraft drop constraint DF_BillIndexAutoDraft_BillComment

  ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN Comment VarChar(Max)  

	Alter Table BillIndexAutoDraft   
	Add Constraint DF_BillIndexAutoDraft_BillComment default('') for Comment   
	

 alter table BillIndexAutoDraft drop constraint DF_BillIndexAutoDraft_explain

  ALTER TABLE BillIndexAutoDraft 
	ALTER COLUMN explain VarChar(Max)  

	Alter Table BillIndexAutoDraft   
	Add Constraint DF_BillIndexAutoDraft_explain default('') for explain   

--是否上传到WMS	
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IsUploadWms'
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD IsUploadWms INT DEFAULT(0)
    END
GO
UPDATE BillIndexAutoDraft SET IsUploadWms = 0 WHERE IsUploadWms IS NULL      


--WMS任务id
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='WmsTaskId'
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD WmsTaskId VARCHAR(50) NULL DEFAULT('')
    END
GO    

--WMS单据号
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='WmsVchCode'
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD WmsVchCode VARCHAR(50) NULL DEFAULT('')
    END
GO    

--是否WMS生成
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='BillIndexAutoDraft' AND a.Name='IsFromWms'
    )
    BEGIN
	ALTER TABLE BillIndexAutoDraft 
		ADD IsFromWms INT NULL DEFAULT(0)
    END
GO                     
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--   修改：梁晰   日期：2016-12-22  增加支付方式字段

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillMulAccount]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillMulAccount](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[ATypeID] VARCHAR(50) NULL DEFAULT(''),		
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[Comment] VARCHAR(500) NULL DEFAULT(''),		
		[BillType] INT 		   DEFAULT(0),
		[TradeNo] VARCHAR(200) DEFAULT(''),
		[PayType] INT DEFAULT(0),
		yhType		INT,		--优惠类型：-1没有，0会员卡， 1代金券，2兑换券
		CouponCode	VARCHAR(5000) DEFAULT(''),	--券编码
		VipTotal	NUMERIC(24,10)  NOT NULL DEFAULT(0),	--对接界面上的卡/券余额
		NTotalMoney NUMERIC(24,10)	DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='VipCardID'
)
BEGIN
	ALTER TABLE BillMulAccount ADD VipCardID INT NULL DEFAULT(-1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE BillMulAccount ADD NTotalMoney  NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='paymoney'
)
BEGIN
	ALTER TABLE BillMulAccount ADD paymoney   NUMERIC(24,10)  NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='TradeNo'
)
BEGIN
	ALTER TABLE BillMulAccount ADD TradeNo   varchar(200)  NOT NULL DEFAULT''
END
GO

--支付方式
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='PayType'
)
BEGIN
	ALTER TABLE BillMulAccount ADD PayType   INT  NOT NULL DEFAULT(0)
END
GO


--优惠类型：-1没有，0会员卡， 1代金券，2兑换券
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='yhType'
)
BEGIN
	ALTER TABLE BillMulAccount ADD yhType   INT  NOT NULL DEFAULT(-1)
END
GO

--券编码
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='CouponCode'
)
BEGIN
	ALTER TABLE BillMulAccount ADD CouponCode   VARCHAR(5000) DEFAULT('')
END
GO

--单据类型
IF NOT EXISTS(SELECT TOP 1  1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillMulAccount') AND Name='BillType')
BEGIN
	ALTER TABLE dbo.BillMulAccount
	ADD BillType INT DEFAULT(0)
END
GO

--卡/券余额
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='VipTotal'
)
BEGIN
	ALTER TABLE BillMulAccount ADD VipTotal  NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLMULACCOUNT') AND name = 'CIX_BILLMULACCOUNT_BillNumberID')
--DROP INDEX CIX_BILLMULACCOUNT_BillNumberID ON BILLMULACCOUNT 
CREATE CLUSTERED INDEX CIX_BILLMULACCOUNT_BillNumberID ON BILLMULACCOUNT(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BILLMULACCOUNT') AND name = 'NCIX_BILLMULACCOUNT_Atypeid')
--DROP INDEX NCIX_BILLMULACCOUNT_Atypeid ON BILLMULACCOUNT 
CREATE NONCLUSTERED INDEX NCIX_BILLMULACCOUNT_Atypeid ON BILLMULACCOUNT(Atypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE BillMulAccount SET VipCardID = -1 WHERE VipCardID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillMulAccount 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccount' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillMulAccount 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--   修改：梁晰   日期：2016-12-22  增加支付方式字段

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillMulAccountAutoDraft]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillMulAccountAutoDraft](
		[BillGuid]	VARCHAR(100) NULL DEFAULT(''),
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[ATypeID] VARCHAR(50) NULL DEFAULT(''),		
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[Comment] VARCHAR(500) NULL DEFAULT(''),		
		[BillType] INT 		   DEFAULT(0),
		[TradeNo] VARCHAR(200) DEFAULT(''),
		[PayType] INT DEFAULT(0),
		yhType		INT,		--优惠类型：-1没有，0会员卡， 1代金券，2兑换券
		CouponCode	VARCHAR(5000) DEFAULT(''),	--券编码
		VipTotal	NUMERIC(24,10)  NOT NULL DEFAULT(0),	--对接界面上的卡/券余额
		NTotalMoney NUMERIC(24,10)	DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='VipCardID'
)
BEGIN
	ALTER TABLE BillMulAccountAutoDraft ADD VipCardID INT NULL DEFAULT(-1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE BillMulAccountAutoDraft ADD NTotalMoney  NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='paymoney'
)
BEGIN
	ALTER TABLE BillMulAccountAutoDraft ADD paymoney   NUMERIC(24,10)  NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='TradeNo'
)
BEGIN
	ALTER TABLE BillMulAccountAutoDraft ADD TradeNo   varchar(200)  NOT NULL DEFAULT''
END
GO

--支付方式
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='PayType'
)
BEGIN
	ALTER TABLE BillMulAccountAutoDraft ADD PayType   INT  NOT NULL DEFAULT(0)
END
GO


--优惠类型：-1没有，0会员卡， 1代金券，2兑换券
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='yhType'
)
BEGIN
	ALTER TABLE BillMulAccountAutoDraft ADD yhType   INT  NOT NULL DEFAULT(-1)
END
GO

--券编码
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='CouponCode'
)
BEGIN
	ALTER TABLE BillMulAccountAutoDraft ADD CouponCode   VARCHAR(5000) DEFAULT('')
END
GO

--单据类型
IF NOT EXISTS(SELECT TOP 1  1 FROM SysColumns WHERE ID=OBJECT_ID(N'BillMulAccountAutoDraft') AND Name='BillType')
BEGIN
	ALTER TABLE dbo.BillMulAccountAutoDraft
	ADD BillType INT DEFAULT(0)
END
GO

--卡/券余额
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='VipTotal'
)
BEGIN
	ALTER TABLE BillMulAccountAutoDraft ADD VipTotal  NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillMulAccountAutoDraft') AND name = 'CIX_BillMulAccountAutoDraft_BillNumberID')
--DROP INDEX CIX_BillMulAccountAutoDraft_BillNumberID ON BillMulAccountAutoDraft 
CREATE CLUSTERED INDEX CIX_BillMulAccountAutoDraft_BillNumberID ON BillMulAccountAutoDraft(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillMulAccountAutoDraft') AND name = 'NCIX_BillMulAccountAutoDraft_Atypeid')
--DROP INDEX NCIX_BillMulAccountAutoDraft_Atypeid ON BillMulAccountAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BillMulAccountAutoDraft_Atypeid ON BillMulAccountAutoDraft(Atypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE BillMulAccountAutoDraft SET VipCardID = -1 WHERE VipCardID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillMulAccountAutoDraft 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillMulAccountAutoDraft' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillMulAccountAutoDraft 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--商品品牌多账户信息
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[BillMulBrand]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE BillMulBrand
	(	
		ID			INT IDENTITY(1,1),
		STypeID		VARCHAR(50) NOT NULL,	--分支机构ID	
		BTypeID		VARCHAR(50) NOT NULL,	--往来单位ID	
		BrandarTypeID VARCHAR(50) NOT NULL,	--商品品牌ID
		BillNumberId	NUMERIC(10,0) NOT NULL,--单据ID
		BillType		INT NOT NULL DEFAULT(-1),--单据类型
		Cid				INT NOT NULL DEFAULT(-1),	--币种
		Rate			NUMERIC(24,10) NOT NULL DEFAULT(0),	--币种汇率
		TaxTotal		NUMERIC(24,10) NOT NULL DEFAULT(0),--价税合计金额（销售金额）
		NTaxTotal		NUMERIC(24,10) NOT NULL DEFAULT(0),--原币价税合计金额（销售金额）
		PreferenceMoney NUMERIC(24,10) NOT NULL DEFAULT(0),--抹零金额
		NPreferenceMoney NUMERIC(24,10) NOT NULL DEFAULT(0),--原币抹零金额
		TotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--实付金额	
		NTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币实付金额	
		YSTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--实付金额	
		NYSTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--预收冲抵金额	
		TheOrderARTotal NUMERIC(24,10) NOT NULL DEFAULT(0),--原币预收冲抵金额	
		NTheOrderARTotal NUMERIC(24,10) NOT NULL DEFAULT(0),--本单原币应付金额
		isIni			INT NOT NULL DEFAULT(0)--是否期初数据
	)
END
GO 
------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillMulBrand') AND name = 'CIX_BillMulBrand_BillNumberId')
	CREATE CLUSTERED INDEX CIX_BillMulBrand_BillNumberId ON BillMulBrand(BillNumberId) 
	
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillMulBrand') AND name = 'NCIX_BillMulBrand_BrandarTypeID')
	CREATE NONCLUSTERED INDEX NCIX_BillMulBrand_BrandarTypeID ON BillMulBrand(BrandarTypeID) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO
------------------------------------------预制数据-------------------------------------------------
GO



--商品品牌多账户信息
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[BillMulBrandAutoDraft]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE BillMulBrandAutoDraft
	(	
		ID			INT IDENTITY(1,1),
		BillGuid		VARCHAR(100) NULL DEFAULT(''),
		STypeID		VARCHAR(50) NOT NULL,	--分支机构ID	
		BTypeID		VARCHAR(50) NOT NULL,	--往来单位ID	
		BrandarTypeID VARCHAR(50) NOT NULL,	--商品品牌ID
		BillNumberId	NUMERIC(10,0) NOT NULL,--单据ID
		BillType		INT NOT NULL DEFAULT(-1),--单据类型
		Cid				INT NOT NULL DEFAULT(-1),	--币种
		Rate			NUMERIC(24,10) NOT NULL DEFAULT(0),	--币种汇率
		TaxTotal		NUMERIC(24,10) NOT NULL DEFAULT(0),--价税合计金额（销售金额）
		NTaxTotal		NUMERIC(24,10) NOT NULL DEFAULT(0),--原币价税合计金额（销售金额）
		PreferenceMoney NUMERIC(24,10) NOT NULL DEFAULT(0),--抹零金额
		NPreferenceMoney NUMERIC(24,10) NOT NULL DEFAULT(0),--原币抹零金额
		TotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--实付金额	
		NTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币实付金额	
		YSTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--实付金额	
		NYSTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--预收冲抵金额	
		TheOrderARTotal NUMERIC(24,10) NOT NULL DEFAULT(0),--原币预收冲抵金额	
		NTheOrderARTotal NUMERIC(24,10) NOT NULL DEFAULT(0),--本单原币应付金额
		isIni			INT NOT NULL DEFAULT(0)--是否期初数据
	)
END
GO 
------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillMulBrandAutoDraft') AND name = 'CIX_BillMulBrandAutoDraft_BillNumberId')
	CREATE CLUSTERED INDEX CIX_BillMulBrandAutoDraft_BillNumberId ON BillMulBrandAutoDraft(BillNumberId) 
	
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BillMulBrandAutoDraft') AND name = 'NCIX_BillMulBrandAutoDraft_BrandarTypeID')
	CREATE NONCLUSTERED INDEX NCIX_BillMulBrandAutoDraft_BrandarTypeID ON BillMulBrandAutoDraft(BrandarTypeID) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO
------------------------------------------预制数据-------------------------------------------------
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillOperateLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillOperateLog](		
		[Id] INT IDENTITY(1,1) NOT NULL,
		[BillnumberID] INT,				
		[OperateType] VARCHAR(50) NULL DEFAULT(''),
		[EtypeID] VARCHAR(50) NULL DEFAULT(''),
		[OperateTime] DATETIME NULL DEFAULT(GETDATE()),
		[IP] VARCHAR(50) NULL,
		[BillCode] VARCHAR(200) NOT NULL DEFAULT(''),
		[BillDate] DATETIME ,
		[ifcheck] CHAR(1) NOT NULL DEFAULT(''),
		[btypeid] VARCHAR(50) NOT NULL DEFAULT(''),
		[NTotalMoney] NUMERIC(22,10) DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillOperateLog' AND a.Name='BillCode'
)
BEGIN
	ALTER TABLE BillOperateLog ADD [BillCode] VARCHAR(200) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillOperateLog' AND a.Name='BillDate'
)
BEGIN
	ALTER TABLE BillOperateLog ADD [BillDate] DATETIME
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillOperateLog' AND a.Name='ifcheck'
)
BEGIN
	ALTER TABLE BillOperateLog ADD [ifcheck] CHAR(1) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillOperateLog' AND a.Name='btypeid'
)
BEGIN
	ALTER TABLE BillOperateLog ADD [btypeid] VARCHAR(50) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillOperateLog' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE BillOperateLog ADD [NTotalMoney] NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillOperateLog' AND a.Name='billtype'
)
BEGIN
	ALTER TABLE BillOperateLog ADD billtype INT  NOT NULL DEFAULT(0)
	/* 放到升级脚本处理
	EXEC ('
	UPDATE t SET t.billtype = t1.BillType FROM BillOperateLog t JOIN  BillIndex t1			ON ( t.BillCode = t1.BillCode AND t.BillnumberID = t1.BillNumberId)
	UPDATE t SET t.billtype = t1.BillType FROM BillOperateLog t JOIN  OrderIndex t1			ON ( t.BillCode = t1.BillCode AND t.BillnumberID = t1.BillNumberId)
	UPDATE t SET t.billtype = t1.BillType FROM BillOperateLog t JOIN  RequestIndex t1		ON ( t.BillCode = t1.BillCode AND t.BillnumberID = t1.BillNumberId)
	UPDATE t SET t.billtype = t1.BillType FROM BillOperateLog t JOIN  CommissionBillNew t1	ON ( t.BillCode = t1.BillCode AND t.BillnumberID = t1.BillNumberId)
	UPDATE t SET t.billtype = t1.BillType FROM BillOperateLog t JOIN  Lendindex t1			ON ( t.BillCode = t1.BillCode AND t.BillnumberID = t1.BillNumberId)
	')
	 */
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillOperateLog' AND a.Name='IP' AND A.length<>50
    )
    BEGIN
	ALTER TABLE BillOperateLog 
	ALTER COLUMN IP VARCHAR(50)
    END
GO
    
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillOperateLog' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BillOperateLog 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'BillPrintConfig') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[BillPrintConfig]
(
	ID				INT IDENTITY(1,1),
	BillTypes		INT NOT NULL,		--单据类别
	BillType		INT NOT NULL,		--单据
	AddState		INT NOT NULL,		--新增状态
	SaveState		INT NOT NULL,		--保存状态
	PassState		INT NOT NULL,		--过账状态
	SaveAlert		INT NOT NULL,		--保存后提醒
	PassAlert		INT NOT NULL,		--过账后提醒
	PrintNum		INT	NOT NULL,			--打印次数
	SortID			INT NOT NULL		--如果要排序，可以指定顺序
) 

INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)

--销售类
		  SELECT 	1,	184,	0,	0,	0,	0,	0,	0,1	--报价单
UNION ALL SELECT 	1,	305,	0,	0,	0,	0,	0,	0,2	--零售单
UNION ALL SELECT 	1,	215,	0,	0,	0,	0,	0,	0,3	--零售退货单
UNION ALL SELECT 	1,	300,	0,	0,	0,	0,	0,	0,4	--销售订单
UNION ALL SELECT 	1,	11,		0,	0,	0,	0,	0,	0,5	--销售出库单
UNION ALL SELECT 	1,	45,		0,	0,	0,	0,	0,	0,6	--销售退货单
UNION ALL SELECT 	1,	160,	0,	0,	0,	0,	0,	0,7	--销售换货单
UNION ALL SELECT 	1,	139,	0,	0,	0,	0,	0,	0,8	--赠送单
UNION ALL SELECT 	1,	140,	0,	0,	0,	0,	0,	0,9	--委托代销发货单
UNION ALL SELECT 	1,	142,	0,	0,	0,	0,	0,	0,10	--委托代销退货单
UNION ALL SELECT 	1,	143,	0,	0,	0,	0,	0,	0,11	--委托代销调价单
UNION ALL SELECT 	1,	141,	0,	0,	0,	0,	0,	0,12	--委托代销结算单
UNION ALL SELECT 	1,	402,	0,	0,	0,	0,	0,	0,13	--发出商品
UNION ALL SELECT 	1,	403,	0,	0,	0,	0,	0,	0,14	--发出商品退货
UNION ALL SELECT 	1,	313,	0,	0,	0,	0,	0,	0,15	--组合品销售订单
UNION ALL SELECT 	1,	12,	0,	0,	0,	0,	0,	0,16	--组合品销售出库单
UNION ALL SELECT 	1,	46,	0,	0,	0,	0,	0,	0,17	--组合品销售退货单


--   采购类
UNION ALL SELECT 	2,	204,	0,	0,	0,	0,	0,	0,1	--请购单
UNION ALL SELECT 	2,	185,	0,	0,	0,	0,	0,	0,2	--询价单
UNION ALL SELECT 	2,	301,	0,	0,	0,	0,	0,	0,3	--采购订单
UNION ALL SELECT 	2,	34,		0,	0,	0,	0,	0,	0,4	--采购入库单
UNION ALL SELECT 	2,	6,		0,	0,	0,	0,	0,	0,5	--采购退货单
UNION ALL SELECT 	2,	161,	0,	0,	0,	0,	0,	0,6	--采购换货单
UNION ALL SELECT 	2,	126,	0,	0,	0,	0,	0,	0,7	--获赠单
UNION ALL SELECT 	2,	144,	0,	0,	0,	0,	0,	0,8	--受托代销收货单
UNION ALL SELECT 	2,	146,	0,	0,	0,	0,	0,	0,9	--受托代销退货单
UNION ALL SELECT 	2,	147,	0,	0,	0,	0,	0,	0,10	--受托代销调价单
UNION ALL SELECT 	2,	145,	0,	0,	0,	0,	0,	0,11	--受托代销结算单
UNION ALL SELECT 	2,	400,	0,	0,	0,	0,	0,	0,12	--暂估入库
UNION ALL SELECT 	2,	401,	0,	0,	0,	0,	0,	0,13	--暂估退货

-- 仓储类
UNION ALL SELECT 	3,	17,		0,	0,	0,	0,	0,	0,1	--同价调拨单
UNION ALL SELECT 	3,	21,		0,	0,	0,	0,	0,	0,2	--变价调拨单
UNION ALL SELECT 	3,	187,	0,	0,	0,	0,	0,	0,3	--分支机构调拨出库单
UNION ALL SELECT 	3,	188,	0,	0,	0,	0,	0,	0,4	--分支机构调拨入库单
UNION ALL SELECT 	3,	201,	0,	0,	0,	0,	0,	0,5	--其他入库单
UNION ALL SELECT 	3,	202,	0,	0,	0,	0,	0,	0,6	--其他出库单
UNION ALL SELECT 	3,	306,	0,	0,	0,	0,	0,	0,7	--盘点单
UNION ALL SELECT 	3,	9,		0,	0,	0,	0,	0,	0,8	--报损单
UNION ALL SELECT 	3,	14,		0,	0,	0,	0,	0,	0,9	--报溢单
UNION ALL SELECT 	3,	87,		0,	0,	0,	0,	0,	0,10	--借出开单
UNION ALL SELECT 	3,	71,		0,	0,	0,	0,	0,	0,11	--借进开单
UNION ALL SELECT 	3,	88,		0,	0,	0,	0,	0,	0,12	--借出还回单
UNION ALL SELECT 	3,	72,		0,	0,	0,	0,	0,	0,13	--借进还出单
UNION ALL SELECT 	3,	16,		0,	0,	0,	0,	0,	0,14	--生产拆装单
UNION ALL SELECT 	3,	203,	0,	0,	0,	0,	0,	0,15	--序列号调整单
UNION ALL SELECT 	3,	127,	0,	0,	0,	0,	0,	0,16	--生成模版
UNION ALL SELECT 	3,	412,	0,	0,	0,	0,	0,	0,17	--上架单
UNION ALL SELECT 	3,	413,	0,	0,	0,	0,	0,	0,18	--拣货单
UNION ALL SELECT 	3,	414,	0,	0,	0,	0,	0,	0,19	--运输配送单
UNION ALL SELECT 	3,	418,	0,	0,	0,	0,	0,	0,20	--仓库入库单
UNION ALL SELECT 	3,	419,	0,	0,	0,	0,	0,	0,21	--仓库出库单
UNION ALL SELECT 	3,	420,	0,	0,	0,	0,	0,	0,22	--仓库调拨单
UNION ALL SELECT 	3,	22,		0,	0,	0,	0,	0,	0,23	--调货申请单
UNION ALL SELECT 	3,	326,	0,	0,	0,	0,	0,	0,24	--要货申请单
UNION ALL SELECT 	3,	327,	0,	0,	0,	0,	0,	0,25	--门店配送单
UNION ALL SELECT 	3,	328,	0,	0,	0,	0,	0,	0,26	--门店配送退货单
UNION ALL SELECT 	3,	329,	0,	0,	0,	0,	0,	0,27	--配送验收单

--往来类
UNION ALL SELECT 	5,	116,	0,	0,	0,	0,	0,	0,1	--应收增加单
UNION ALL SELECT 	5,	115,	0,	0,	0,	0,	0,	0,2	--应收减少单
UNION ALL SELECT 	5,	128,	0,	0,	0,	0,	0,	0,3	--应付增加单
UNION ALL SELECT 	5,	129,	0,	0,	0,	0,	0,	0,4	--应付减少单
UNION ALL SELECT 	5,	4,	    0,	0,	0,	0,	0,	0,5	--收款单
UNION ALL SELECT 	5,	189,	0,	0,	0,	0,	0,	0,6	--预收款单
UNION ALL SELECT 	5,	66,		0,	0,	0,	0,	0,	0,7	--付款单
UNION ALL SELECT 	5,	190,	0,	0,	0,	0,	0,	0,8	--预付款单
UNION ALL SELECT 	5,	148,	0,	0,	0,	0,	0,	0,9	--返利执行单
UNION ALL SELECT 	5,	150,	0,	0,	0,	0,	0,	0,10	--获利执行单
UNION ALL SELECT 	5,	149,	0,	0,	0,	0,	0,	0,11	--价保执行单
UNION ALL SELECT 	5,	151,	0,	0,	0,	0,	0,	0,12	--获得价保
UNION ALL SELECT 	5,	163,	0,	0,	0,	0,	0,	0,13	--采购发票
UNION ALL SELECT 	5,	162,	0,	0,	0,	0,	0,	0,14	--销售发票
UNION ALL SELECT 	5,	404,	0,	0,	0,	0,	0,	0,15	--暂估入库开票
UNION ALL SELECT 	5,	405,	0,	0,	0,	0,	0,	0,16	--销售发货开票
UNION ALL SELECT 	5,	450,	0,	0,	0,	0,	0,	0,17	--往来核销

--财务类
UNION ALL SELECT 	6,	36,		0,	0,	0,	0,	0,	0,1	--费用单
UNION ALL SELECT 	6,	158,	0,	0,	0,	0,	0,	0,2	--现金费用单
UNION ALL SELECT 	6,	77,		0,	0,	0,	0,	0,	0,3	--转款单
UNION ALL SELECT 	6,	93,		0,	0,	0,	0,	0,	0,4	--其他收入单
UNION ALL SELECT 	6,	5,		0,	0,	0,	0,	0,	0,5	--待摊费用发生
UNION ALL SELECT 	6,	10,		0,	0,	0,	0,	0,	0,6	--待摊费用摊销
UNION ALL SELECT 	6,	84,		0,	0,	0,	0,	0,	0,7	--固定资产(项目)购买单
UNION ALL SELECT 	6,	85,		0,	0,	0,	0,	0,	0,8	--固定资产(项目)变卖单
UNION ALL SELECT 	6,	78,		0,	0,	0,	0,	0,	0,9	--固定资产(项目)折旧单
UNION ALL SELECT 	6,	57,		0,	0,	0,	0,	0,	0,10	--成本调价单
UNION ALL SELECT 	6,	159,	0,	0,	0,	0,	0,	0,11	--业务凭证
UNION ALL SELECT 	6,	205,	0,	0,	0,	0,	0,	0,12	--采购费用分摊单
UNION ALL SELECT 	6,	206,	0,	0,	0,	0,	0,	0,13	--销售费用分摊单
UNION ALL SELECT 	6,	213,	0,	0,	0,	0,	0,	0,14	--固定资产减少单
UNION ALL SELECT 	6,	212,	0,	0,	0,	0,	0,	0,15	--固定资产增加单
UNION ALL SELECT 	6,	214,	0,	0,	0,	0,	0,	0,16	--固定资产折旧单(新)
UNION ALL SELECT 	6,	310,	0,	0,	0,	0,	0,	0,17	--资金调拨单
--特殊
UNION ALL SELECT 	6,	307,	0,	0,	0,	0,	0,	0,18	--固定资产盘点单
UNION ALL SELECT 	6,	181,	0,	0,	0,	0,	0,	0,19	--会员储值充值单
UNION ALL SELECT 	6,	183,	0,	0,	0,	0,	0,	0,20	--积分兑换单
UNION ALL SELECT 	6,	312,	0,	0,	0,	0,	0,	0,21	--会员批量储值充值单
UNION ALL SELECT 	6,	164,	0,	0,	0,	0,	0,	0,22	--业务员提成规则设置
UNION ALL SELECT 	6,	311,	0,	0,	0,	0,	0,	0,23	--提成单
UNION ALL SELECT 	6,	427,	0,	0,	0,	0,	0,	0,24	--积分转储值单

--维修类
UNION ALL SELECT 	8,	165,	0,	0,	0,	0,	0,	0,1	--维修接件单
UNION ALL SELECT 	8,	166,	0,	0,	0,	0,	0,	0,2	--维修单
UNION ALL SELECT 	8,	167,	0,	0,	0,	0,	0,	0,3	--维修取件单
UNION ALL SELECT 	8,	168,	0,	0,	0,	0,	0,	0,4	--整机更换单
UNION ALL SELECT 	8,	169,	0,	0,	0,	0,	0,	0,5	--送修单
UNION ALL SELECT 	8,	170,	0,	0,	0,	0,	0,	0,6	--送修返回单
UNION ALL SELECT 	8,	171,	0,	0,	0,	0,	0,	0,7	--报修单
UNION ALL SELECT 	8,	172,	0,	0,	0,	0,	0,	0,8	--上门维修单
UNION ALL SELECT 	8,	173,	0,	0,	0,	0,	0,	0,9	--维修品调入单
UNION ALL SELECT 	8,	174,	0,	0,	0,	0,	0,	0,10	--维修品调出单
UNION ALL SELECT 	8,	175,	0,	0,	0,	0,	0,	0,11	--维修品调拨单

--其他类 --208 使用登记单   --   209 车辆费用单
UNION ALL SELECT 	20,	208,	0,	0,	0,	0,	0,	0,1	--使用登记单
UNION ALL SELECT 	20,	209,	0,	0,	0,	0,	0,	0,2	--车辆费用单
UNION ALL SELECT 	20,	423,	0,	0,	0,	0,	0,	0,3	--优惠券入库单
UNION ALL SELECT 	20,	424,	0,	0,	0,	0,	0,	0,4	--优惠券出库单
UNION ALL SELECT 	20,	425,	0,	0,	0,	0,	0,	0,5	--优惠券调拨单
UNION ALL SELECT 	20,	426,	0,	0,	0,	0,	0,	0,6	--优惠券退货单
UNION ALL SELECT 	20,	428,	0,	0,	0,	0,	0,	0,7	--优惠券分支机构调拨入库单
UNION ALL SELECT 	20,	429,	0,	0,	0,	0,	0,	0,8	--优惠券分支机构调拨出库单

END
GO
--添加主键，存在列名的情况下
IF EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BillPrintConfig',N'U') AND Name='Id')
	AND NOT EXISTS(
					SELECT	TOP 1 1 
					FROM	SYSOBJECTS A
					INNER   JOIN SYSOBJECTS B ON A.ID=B.PARENT_OBJ AND A.XTYPE='U' AND B.XTYPE='PK'
					WHERE	A.name = 'BillPrintConfig'
	)
BEGIN
	ALTER TABLE BillPrintConfig 
	ADD CONSTRAINT BillPrintConfig_PkId PRIMARY KEY(Id)
END
GO
--164 业务员提成规则设置
--311 提成单

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 164)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	6,	164,	0,	0,	0,	0,	0,	0,22	--业务员提成规则设置
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 311)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	6,	311,	0,	0,	0,	0,	0,	0,23	--业务员提成规则设置
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 411)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	6,	411,	0,	0,	0,	0,	0,	0,24	--固定资产拆分单
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 212)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	6,	212,	0,	0,	0,	0,	0,	0,25	--固定资产增加单
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 410)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	6,	410,	0,	0,	0,	0,	0,	0,26	--固定资产变更单
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 163)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	5,	163,	0,	0,	0,	0,	0,	0,13	--采购发票
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 162)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	5,	162,	0,	0,	0,	0,	0,	0,14	--销售发票
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 127)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	127,	0,	0,	0,	0,	0,	0,16	--生成模版
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 208)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	20,	208,	0,	0,	0,	0,	0,	0,1	--使用登记单
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 209)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 20,	209,	0,	0,	0,	0,	0,	0,2	--车辆费用单
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 400)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	2,	400,	0,	0,	0,	0,	0,	0,12	--暂估入库
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 401)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	2,	401,	0,	0,	0,	0,	0,	0,13	--暂估退货
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 402)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	1,	402,	0,	0,	0,	0,	0,	0,13	--发出商品
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 403)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	1,	403,	0,	0,	0,	0,	0,	0,14	--发出商品退货
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 404)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	5,	404,	0,	0,	0,	0,	0,	0,15	--暂估入库开票
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 405)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	5,	405,	0,	0,	0,	0,	0,	0,16	--销售发货开票
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 450)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	5,	450,	0,	0,	0,	0,	0,	0,17	--销售发货开票
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 412)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	412,	0,	0,	0,	0,	0,	0,17	--上架单
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 413)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	413,	0,	0,	0,	0,	0,	0,18	--拣货单
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 414)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	414,	0,	0,	0,	0,	0,	0,19	--运输配送单
END
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 418)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	418,	0,	0,	0,	0,	0,	0,20	--仓库入库单
END
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 419)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	419,	0,	0,	0,	0,	0,	0,21	--仓库出库单
END
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 420)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	420,	0,	0,	0,	0,	0,	0,21	--仓库调拨单
END

GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 313)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	1,	313,	0,	0,	0,	0,	0,	0,15	--组合品销售订单
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 12)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	1,	12,	0,	0,	0,	0,	0,	0,16	--组合品销售出库单
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 46)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	1,	46,	0,	0,	0,	0,	0,	0,17	--组合品销售退货单
END
GO

---调货申请单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 22)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	22,	0,	0,	0,	0,	0,	0,23	--组合品销售退货单
END
GO

--优惠券入库单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 423)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	20,	423,	0,	0,	0,	0,	0,	0,3	
END
GO

--优惠券出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 424)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	20,	424,	0,	0,	0,	0,	0,	0,4	 
END 
GO
--优惠券调拨单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 425)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	20,	425,	0,	0,	0,	0,	0,	0,5	
END
GO
--优惠券退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 426)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	20,	426,	0,	0,	0,	0,	0,	0,6	
END
GO
--积分转储值单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 427)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	6,	427,	0,	0,	0,	0,	0,	0,24	
END
GO

--要货申请单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 326)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	326,	0,	0,	0,	0,	0,	0,24
	
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	327,	0,	0,	0,	0,	0,	0,25
	
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	328,	0,	0,	0,	0,	0,	0,26
	
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	3,	329,	0,	0,	0,	0,	0,	0,27	
END
GO


--优惠券分支机调拨出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 428)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	20,	428,	0,	0,	0,	0,	0,	0,7
END
GO

--优惠券分支机调拨入库单
IF NOT EXISTS(SELECT TOP 1 1 FROM BillPrintConfig WHERE BillType = 429)
BEGIN
	INSERT BillPrintConfig(BillTypes,BillType,AddState,SaveState,PassState,SaveAlert,PassAlert,PrintNum,SortID)
	SELECT 	20,	429,	0,	0,	0,	0,	0,	0,8
END
GO


SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[atype_l]    脚本日期: 05/05/2010 14:46:36 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	By: Haiyang, Li
	Date: 2012-10-30
	Description: 单据分时记录函数
*/
IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[BillSaveTimeLog]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        CREATE TABLE [dbo].[BillSaveTimeLog]
            (
              SaveDate		DATETIME NOT NULL ,		-- 保存时间
              BillTypeID	INT NOT NULL ,				-- 单据类型	
              BillCode		VARCHAR(100) NOT NULL ,	-- 单据编号
              FunctionOrder INT ,									-- 方法调用顺序
              FunctionName	VARCHAR(100) NOT NULL ,	-- 方法名称
              Elapsed		INT NOT NULL			-- 耗时(毫秒)
            )
        ON  [PRIMARY]


    END
GO
--DROP TABLE [dbo].[BillSaveTimeLog]

------------------------------------------表修改区域结束-------------------------------------------------




------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BillSaveTimeLog]') AND name = N'CIX_Time_l')
	--DROP INDEX CIX_Time_l ON BillSaveTimeLog
CREATE CLUSTERED INDEX CIX_Time_l ON BillSaveTimeLog(savedate)
------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('BossListConfig')
            and   type = 'U')
BEGIN
	CREATE TABLE BossListConfig
	(
		etypeid  VARCHAR(50),
		atypeid  VARCHAR(50),
		TypeName   VARCHAR(2),
		flag	INT   
	)
	INSERT INTO	BossListConfig
	SELECT etypeid,	'00003','G',1
	FROM dbo.loginuser
	INSERT INTO	BossListConfig
	SELECT etypeid,	'00004','E',1
	FROM dbo.loginuser
	INSERT INTO	BossListConfig
	SELECT etypeid,	'0000100003','B',1
	FROM dbo.loginuser
	INSERT INTO	BossListConfig
	SELECT etypeid,	'0000100004','B',1
	FROM dbo.loginuser
	
END
GO
-----------------------------------------------------修改表-----------------------------------------------------
------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

-----------------------------------------------------修改数据-----------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BranchExpressage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BranchExpressage](
		[branchID] [varchar](50) NOT NULL,
		[jName] [varchar](20) NULL,
		[jDWName] [varchar](100) NULL,
		[jAddress] [varchar](200) NULL,
		[jPhone] [varchar](50) NULL,
		[jPostal] [varchar](20) NULL,
		[wlType] [int] NULL,
		[jAddress_sheng] [varchar](200) NULL,
		[jAddress_shi] [varchar](200) NULL,
		[jAddress_qu] [varchar](200) NULL,
		[jTel] [varchar](20) NULL,
	 CONSTRAINT [PK_branchID] PRIMARY KEY CLUSTERED 
	(
		[branchID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END	

GO

SET ANSI_PADDING OFF
GO




--品牌往来账
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Brandar_ArApTotal]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Brandar_ArApTotal				
	(	
		ID			INT IDENTITY(1,1),--自增长列 +1
		BrandarTypeID VARCHAR(50),--品牌ID
		StypeID		VARCHAR(50) NOT NULL,--分支机构ID
		BtypeID		VARCHAR(50) NOT NULL,--往来单位ID
		Cid			INT NOT NULL DEFAULT(-1),--币种
		YSTotal00	NUMERIC(24,10) NOT NULL DEFAULT(0),--本币预收期初
		NYSTotal00	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币预收期初
		YSTotal		NUMERIC(24,10) NOT NULL DEFAULT(0),--本币预收余额
		NYSTotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币预收余额
		ARTotal00	NUMERIC(24,10) NOT NULL DEFAULT(0),--本币应收期初	
		NARTotal00	NUMERIC(24,10) NOT NULL DEFAULT(0),--本币应收期初
		ARTotal		NUMERIC(24,10) NOT NULL DEFAULT(0),--本币应收余额	
		NARTotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币应收余额
	)
END
GO 
------------------------------------------表修改区域开始-------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='Brandar_ArApTotal' AND a.Name='Total'
--)
--BEGIN
--	ALTER TABLE Brandar_ArApTotal 
--		ADD Total NUMERIC(24,10) NOT NULL DEFAULT(0)
--END
--GO

------------------------------------------表修改区域结束-------------------------------------------------
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Brandar_ArApTotal') AND name = 'CIX_Brandar_ArApTotal_BrandarTypeID')
	CREATE CLUSTERED INDEX CIX_Brandar_ArApTotal_BrandarTypeID ON Brandar_ArApTotal(BrandarTypeID) 
	
------------------------------------------创建索引区域结束-----------------------------------------------
GO
------------------------------------------预制数据-------------------------------------------------
GO



--商品品牌
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[brandar_Commodity]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE brandar_Commodity
	(
		BrandID			INT IDENTITY(1,1),--品牌ID，自增长
		TypeId			VARCHAR(50) UNIQUE,
		ParId			VARCHAR(50),
		Leveal			INT,--Level
		SonNum			INT,
		SonCount		INT,
		UserCode		VARCHAR(200) NOT NULL,
		FullName		VARCHAR(200) NOT NULL,
		Comment			VARCHAR(500) NULL,
		IsSys			INT NOT NULL DEFAULT(0),--是否系统默认
		XiWaMaxNumber	INT,								--缓存字段
		DbGuid			VARCHAR(50) NOT NULL DEFAULT(NEWID())
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('brandar_Commodity') AND name = 'CIX_brandar_Commodity_BrandarId')
	CREATE CLUSTERED INDEX CIX_brandar_Commodity_BrandarId ON brandar_Commodity(TypeId) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO
------------------------------------------预制数据-------------------------------------------------

IF NOT EXISTS(SELECT TOP 1 1 FROM brandar_Commodity)
BEGIN
	SET IDENTITY_INSERT dbo.brandar_Commodity ON	
	
	INSERT INTO brandar_Commodity(BrandID,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Comment,IsSys,XiWaMaxNumber)
	SELECT 1,'00000','root',0,1,1,'所有品牌','所有品牌','系统保留',1,1 UNION 
	SELECT 2,'00001','00000',1,0,0,'QTPP','其他品牌','系统默认品牌',1,1
	
	SET IDENTITY_INSERT dbo.brandar_Commodity OFF
END
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
--品牌余额
IF  EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Brandar_Total]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	DROP TABLE Brandar_Total
	--CREATE TABLE Brandar_Total				
	--(	
	--	ID				INT IDENTITY(1,1),--自增长列 +1
	--	BrandarTypeID	VARCHAR(50),--品牌ID
	--	StypeID		VARCHAR(50) NOT NULL,--分支机构ID
	--	BtypeID		VARCHAR(50) NOT NULL,--往来单位ID
	--	Cid			INT NOT NULL DEFAULT(-1),--币种
	--	Total	NUMERIC(24,10) NOT NULL DEFAULT(0),--本币余额
	--	Ntotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币余额
	--	Total00		NUMERIC(24,10) NOT NULL DEFAULT(0),--本币期初
	--	NTotal00	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币期初
	--)
END
GO 




/****** 对象:  Table [dbo].[btype]    脚本日期: 05/05/2010 14:46:49 ******/
/*
	作者：廖晨羽
	日期：2011-08-17
	描述：修改表的地址长度为256位,添加etypeid字段
*/


/*
	作者：吕文祺
	日期：2012-04-18
	描述：新增字段denominatedid为保存结算单位ID
*/
/*
修改：魏伟
日期：2016-5-25
描述：新增 stopdate字段，停用时间 ltbuyinsday 字段，最近采购入库日  ltbuyorderday 字段，最近采购订货日
           ltbuyrtday 字段，最近采购退货日 ltsaleoutsday 字段，最近销售出库日 ltsaleorderday 字段，最近            销售订货日 ltsalertday 字段，最近销售退货日
*/


SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[btype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[btype](
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[parid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint] NOT NULL,
		[soncount] [int] NOT NULL,
		[sonnum] [int] NOT NULL,
		[UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_UserCode]  DEFAULT (''),
		[FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[Area] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_Area]  DEFAULT (0),
		[TelAndAddress] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_TelAndAddress]  DEFAULT (''),
		[PostCode] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_PostCode]  DEFAULT (''),
		[Person] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_Person]  DEFAULT (''),
		[TaxNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_TaxNumber]  DEFAULT (''),
		[BankAndAcount] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_BankAndAcount]  DEFAULT (''),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_Comment]  DEFAULT (''),
		[CreateDate] [datetime] NULL,
		[ARTotal] [numeric](18, 4) NULL CONSTRAINT [DF_btype_ARTotal]  DEFAULT (0),
		[APTotal] [numeric](18, 4) NULL CONSTRAINT [DF_btype_APTotal]  DEFAULT (0),
		[ARTotal00] [numeric](18, 4) NULL CONSTRAINT [DF_btype_ARTotal00]  DEFAULT (0),
		[APTotal00] [numeric](18, 4) NULL CONSTRAINT [DF_btype_APTotal00]  DEFAULT (0),
		[deleted] [bit] NOT NULL CONSTRAINT [DF_btype_deleted]  DEFAULT (0),
		[Client] [bit] NULL,
		[ARLimit] [numeric](18, 4) NULL,
		[initcomment] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[arapexplain] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[Tel1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Tel2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Tel3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Fax] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[WWW] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Bank] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BankName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMan1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkSex1] [bit] NULL,
		[LinkBirthDay1] [datetime] NULL,
		[LinkJob1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkCall1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkTel1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMobile1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkPost1] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkAddress1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkEmail1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkComment1] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMan2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkSex2] [bit] NULL,
		[LinkBirthDay2] [datetime] NULL,
		[LinkJob2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkCall2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkTel2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMobile2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkPost2] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkAddress2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkEmail2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkComment2] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[ARLimitTime] [numeric](18, 4) NULL,
		[paymentLTime] [numeric](18, 4) NULL,
		[SaleZekou] [numeric](18, 4) NULL,
		[BuyZekou] [numeric](18, 4) NULL,
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[Price] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[AreaTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_btype_AreaTypeID]  DEFAULT (''),
		[smsMobile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[smsComment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Cid]	[INT] NULL,
		[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0),
		[PriceTrackEnable] INT NOT NULL DEFAULT(1),
		cqdays INT NULL, --超期提前预警 天数
		chkskmonthday INT  NULL DEFAULT(0), --启用收款月结日 checkbox
		skmonthday INT NULL, --启用收款月结日  
		chkfkmonthday INT  NULL DEFAULT(0), --启用付款月结日 checkbox
		fkmonthday INT NULL, --启用付款月结日  
		dzdays INT NULL, --每月对账日期  
		dzwarningdays INT NULL --对账日提前预警天数  

	) ON [PRIMARY]
	
	-- ********	处理 BType	********
	DELETE FROM BType
	INSERT INTO BType(TypeID,Parid,Leveal,SonCount,SonNum,UserCode,FullName,Name,Area,TelAndAddress,PostCode,Person,TaxNumber,BankAndAcount,Comment,ARTotal,APTotal,ARTotal00,APTotal00,Deleted,Client,ARLimit,initcomment,arapexplain,Tel1,Tel2,Tel3,Fax,WWW,Bank,BankName,Email,LinkMan1,LinkSex1,LinkBirthDay1,LinkJob1,LinkCall1,LinkTel1,LinkMobile1,LinkPost1,LinkAddress1,LinkEmail1,LinkComment1,LinkMan2,LinkSex2,LinkBirthDay2,LinkJob2,LinkCall2,LinkTel2,LinkMobile2,LinkPost2,LinkAddress2,LinkEmail2,LinkComment2) VALUES('00000','root',0,2,2,'abc','ABC','','','ABC市','100000','ABC','','','',0,0,0,0,0,1,0,'','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','')
	INSERT INTO BType(TypeID,Parid,Leveal,SonCount,SonNum,UserCode,FullName,Name,Area,TelAndAddress,PostCode,Person,TaxNumber,BankAndAcount,Comment,ARTotal,APTotal,ARTotal00,APTotal00,Deleted,Client,ARLimit,initcomment,arapexplain,Tel1,Tel2,Tel3,Fax,WWW,Bank,BankName,Email,LinkMan1,LinkSex1,LinkBirthDay1,LinkJob1,LinkCall1,LinkTel1,LinkMobile1,LinkPost1,LinkAddress1,LinkEmail1,LinkComment1,LinkMan2,LinkSex2,LinkBirthDay2,LinkJob2,LinkCall2,LinkTel2,LinkMobile2,LinkPost2,LinkAddress2,LinkEmail2,LinkComment2) VALUES('00001','00000',1,0,0,'KH','所有客户','','','','客户','','','','',0,0,0,0,0,0,0,'','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','')
	INSERT INTO BType(TypeID,Parid,Leveal,SonCount,SonNum,UserCode,FullName,Name,Area,TelAndAddress,PostCode,Person,TaxNumber,BankAndAcount,Comment,ARTotal,APTotal,ARTotal00,APTotal00,Deleted,Client,ARLimit,initcomment,arapexplain,Tel1,Tel2,Tel3,Fax,WWW,Bank,BankName,Email,LinkMan1,LinkSex1,LinkBirthDay1,LinkJob1,LinkCall1,LinkTel1,LinkMobile1,LinkPost1,LinkAddress1,LinkEmail1,LinkComment1,LinkMan2,LinkSex2,LinkBirthDay2,LinkJob2,LinkCall2,LinkTel2,LinkMobile2,LinkPost2,LinkAddress2,LinkEmail2,LinkComment2) VALUES('00002','00000',1,0,0,'DL','全部供货商','','0','','供货商','','','','',0,0,0,0,0,0,0,'','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','')
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
--修改btype的TelAndAddress长度
ALTER TABLE [dbo].[btype] 
ALTER COLUMN TelAndAddress VARCHAR(256) NULL
GO

--修改btype的LinkAddress1,LinkAddress2长度
ALTER TABLE [dbo].[btype] 
ALTER COLUMN LinkAddress1 VARCHAR(256) NULL			 
GO
ALTER TABLE [dbo].[btype] 
ALTER COLUMN LinkAddress2 VARCHAR(256) NULL
GO

--添加etypeid字段
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='etypeid')
	ALTER TABLE [dbo].[btype] 
		ADD etypeid VARCHAR(50) NULL
GO

--添加buyprice字段，适用进价
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='buyprice')
	ALTER TABLE [dbo].[btype] 
		ADD buyprice VARCHAR(50) NULL
GO
--添加stopdate字段，停用时间
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='stopdate')
	ALTER TABLE [dbo].[btype] 
		ADD stopdate [datetime] NULL
GO
--添加 ltbuyinsday 字段，最近采购入库日
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='ltbuyinsday')
	ALTER TABLE [dbo].[btype] 
		ADD ltbuyinsday [datetime] NULL
GO
--添加 ltbuyorderday 字段，最近采购订货日
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='ltbuyorderday')
	ALTER TABLE [dbo].[btype] 
		ADD ltbuyorderday [datetime] NULL
GO
--添加 ltbuyrtday 字段，最近采购退货日
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='ltbuyrtday')
	ALTER TABLE [dbo].[btype] 
		ADD ltbuyrtday [datetime] NULL
GO
--添加 ltsaleoutsday 字段，最近销售出库日
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='ltsaleoutsday')
	ALTER TABLE [dbo].[btype] 
		ADD ltsaleoutsday [datetime] NULL
GO
--添加 ltsaleorderday 字段，最近销售订货日
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='ltsaleorderday')
	ALTER TABLE [dbo].[btype] 
		ADD ltsaleorderday [datetime] NULL
GO
--添加 ltsalertday 字段，最近销售退货日
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='ltsalertday')
	ALTER TABLE [dbo].[btype] 
		ADD ltsalertday [datetime] NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='ConsigneeAddress'
)
BEGIN
	ALTER TABLE btype 
		ADD ConsigneeAddress VARCHAR(1000) NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='Consignee'
)
BEGIN
	ALTER TABLE btype 
		ADD Consignee VARCHAR(100) NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='ConsigneeTel'
)
BEGIN
	ALTER TABLE btype 
		ADD ConsigneeTel VARCHAR(100) NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='CanNotModifyPrice'
)
BEGIN
	ALTER TABLE btype 
		ADD CanNotModifyPrice BIT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='BackLimitDay'
)
BEGIN
	ALTER TABLE btype 
		ADD BackLimitDay int
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='BackPercent'
)
BEGIN
	ALTER TABLE btype 
		ADD BackPercent int
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='denominatedid' 
)
BEGIN
	ALTER TABLE btype 
		ADD denominatedid varchar(50)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='Bid')
BEGIN
	ALTER TABLE btype ADD Bid INT identity(1,1)
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='Cid')
BEGIN
	ALTER TABLE btype ADD Cid INT NULL
END
GO

--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('btype') and name='WdSyncFlag')
BEGIN
	ALTER TABLE btype ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End      

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='cqdays')
	ALTER TABLE BTYPE ADD cqdays INT NULL --收款超期提前预警

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='chkskmonthday')
	ALTER TABLE BTYPE ADD chkskmonthday INT  NULL DEFAULT(0) --启用收款月结日 checkbox

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='skmonthday')
	ALTER TABLE BTYPE ADD skmonthday INT NULL --启用收款月结日  

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='chkfkmonthday')
	ALTER TABLE BTYPE ADD chkfkmonthday INT  NULL DEFAULT(0) --启用付款月结日 checkbox

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='fkmonthday')
	ALTER TABLE BTYPE ADD fkmonthday INT NULL --启用付款月结日  

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='dzdays')
	ALTER TABLE BTYPE ADD dzdays INT NULL  --收款每月对账日期  

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='dzwarningdays')
	ALTER TABLE BTYPE ADD dzwarningdays  INT NULL --收款对账日提前预警天数   
--------------9.7.1
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='ckarlimittime')
	ALTER TABLE BTYPE ADD ckarlimittime  INT NULL DEFAULT(0)--收款期限选择项 radiobutton   
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='ckpaymentltime')
	ALTER TABLE BTYPE ADD ckpaymentltime  INT NULL DEFAULT(0) --付款期限选择项 radiobutton  
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='fkcqdays')
	ALTER TABLE BTYPE ADD fkcqdays  INT NULL  --付款超期提前预警 
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='fkdzdays')
	ALTER TABLE BTYPE ADD fkdzdays INT NULL --付款每月对账日期  
	
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='fkdzwarningdays')
	ALTER TABLE BTYPE ADD fkdzwarningdays  INT NULL --付款对账日提前预警天数  
	
 	
---------------9.7.1
--承运商  
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='iscarrier')
	ALTER TABLE BTYPE ADD iscarrier  BIT NOT NULL DEFAULT(0) 

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='PriceTrackEnable')
	ALTER TABLE BTYPE ADD PriceTrackEnable  INT NOT NULL DEFAULT(1) 
	

--添加isusebrandartype启用品牌应收功能
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[btype]') AND name='IsUseBrandarType')
	ALTER TABLE [dbo].[btype] 
		ADD IsUseBrandarType BIT NOT NULL DEFAULT(0)
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[btype]') AND name = N'btypeidx')
--	DROP INDEX [dbo].[btype].[btypeidx]

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BType]') AND name = N'NCIX_PAID')
--	DROP INDEX [dbo].BType.NCIX_PAID
	
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BType]') AND name = N'NCIX_SONNUM')
--	DROP INDEX [dbo].BType.NCIX_SONNUM
--GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BTYPE') AND name = 'CIX_BTYPE_typeId')
--DROP INDEX CIX_BTYPE_typeId ON BTYPE 
CREATE CLUSTERED INDEX CIX_BTYPE_typeId ON BTYPE(typeId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BTYPE') AND name = 'NCIX_BTYPE_parid_deleted')
--DROP INDEX NCIX_BTYPE_parid_deleted ON BTYPE 
CREATE NONCLUSTERED INDEX NCIX_BTYPE_parid_deleted ON BTYPE(parid,deleted) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BTYPE') AND name = 'NCIX_BTYPE_sonnum_deleted_FullName')
--DROP INDEX NCIX_BTYPE_sonnum_deleted_FullName ON BTYPE 
CREATE NONCLUSTERED INDEX NCIX_BTYPE_sonnum_deleted_FullName ON BTYPE(sonnum,deleted,FullName) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BTYPE') AND name = 'NCIX_BTYPE_UserCode')
CREATE NONCLUSTERED INDEX NCIX_BTYPE_UserCode ON BTYPE(UserCode) 

GO


------------------------------------------创建索引区域结束-----------------------------------------------
--提供XiWa交互功能，每次修改或者新增基本信息后，必须在原来的值上加1 谢吉康 2010-05-04
if not exists (select name from syscolumns where id = object_id(N'[dbo].[BType]') and name = 'XiWaMaxNumber' )
	BEGIN
		BEGIN TRANSACTION
		SET QUOTED_IDENTIFIER ON
		SET ARITHABORT ON
		SET NUMERIC_ROUNDABORT OFF
		SET CONCAT_NULL_YIELDS_NULL ON
		SET ANSI_NULLS ON
		SET ANSI_PADDING ON
		SET ANSI_WARNINGS ON
		COMMIT
		BEGIN TRANSACTION
		ALTER TABLE dbo.BType ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
		
		COMMIT
	END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[BType]') and  name = 'PostCode' AND length=200)
BEGIN
     ALTER TABLE BType
	    ALTER COLUMN PostCode varchar(200) 
END
GO
UPDATE BType SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL OR XiWaMaxNumber = 0
GO
UPDATE BType SET Price = 0 WHERE ISNULL(Price,'')=''
GO
UPDATE btype SET buyprice='0' WHERE buyprice IS NULL
GO
UPDATE btype SET price='0' WHERE buyprice IS NULL
GO
UPDATE btype SET ConsigneeAddress = '' WHERE ConsigneeAddress IS NULL
GO
UPDATE btype SET Consignee = '' WHERE Consignee IS NULL
GO
UPDATE btype SET ConsigneeTel = '' WHERE ConsigneeTel IS NULL
GO
UPDATE btype SET CanNotModifyPrice = 1 WHERE CanNotModifyPrice IS NULL
GO
UPdate Btype SET denominatedid=typeid WHERE denominatedid IS NULL
GO
UPDATE btype SET PriceTrackEnable = 1 WHERE PriceTrackEnable IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='ARTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN ARTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='APTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN APTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='ARTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN ARTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='APTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN APTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='ARLimit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN ARLimit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='ARLimitTime' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN ARLimitTime NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='paymentLTime' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN paymentLTime NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='SaleZekou' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN SaleZekou NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype' AND a.Name='BuyZekou' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype 
	ALTER COLUMN BuyZekou NUMERIC(24,10)
    END

--省
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='sheng')
BEGIN
	ALTER TABLE btype 
		ADD sheng VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE btype SET sheng = '' WHERE sheng IS NULL
GO
--市
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='shi')
BEGIN
	ALTER TABLE btype 
		ADD shi VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE btype SET shi = '' WHERE shi IS NULL
GO
--县
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='xian')
BEGIN
	ALTER TABLE btype 
		ADD xian VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE btype SET xian = '' WHERE xian IS NULL      
--单位等级
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='blevel')
BEGIN
	ALTER TABLE btype 
		ADD blevel VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE btype SET blevel = '' WHERE blevel IS NULL                                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

--WMS下载
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('btype') and name='IsWmsDownLoad')
BEGIN
	ALTER TABLE btype 
		ADD IsWmsDownLoad INT NOT NULL DEFAULT 0 
End 
GO
UPDATE btype SET IsWmsDownLoad = 0 WHERE IsWmsDownLoad IS NULL
GO

--是否同步
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('btype') and name='IsWmsSync')
BEGIN
	ALTER TABLE btype 
		ADD IsWmsSync INT NOT NULL DEFAULT 0 
End 
GO
UPDATE btype SET IsWmsSync = 0 WHERE IsWmsSync IS NULL
GO
--编号改成200
if exists (select * from syscolumns where id = object_id(N'[dbo].[BType]') and  name = 'UserCode' AND length=26)
BEGIN
     ALTER TABLE BType
	    ALTER COLUMN UserCode varchar(200) 
END
--名称改成200
if exists (select * from syscolumns where id = object_id(N'[dbo].[BType]') and  name = 'FullName' AND length=66)
BEGIN
     ALTER TABLE BType
	    ALTER COLUMN FullName varchar(200) 
END
GO

--收款第几月
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='skmonth')
BEGIN
	ALTER TABLE btype 
		ADD skmonth INT NULL 
END
GO

--收款第几日
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='skday')
BEGIN
	ALTER TABLE btype 
		ADD skday INT NULL 
END
GO

--按对账日期计算收款期限
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='skdzdayflag')
BEGIN
	ALTER TABLE btype 
		ADD skdzdayflag INT NULL DEFAULT(0)
END
GO
UPDATE btype SET skdzdayflag = 0 WHERE skdzdayflag IS NULL
GO

--付款第几月
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='fkmonth')
BEGIN
	ALTER TABLE btype 
		ADD fkmonth INT NULL 
END
GO

--付款第几日
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='fkday')
BEGIN
	ALTER TABLE btype 
		ADD fkday INT NULL 
END
GO

--按对账日期计算付款期限
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='fkdzdayflag')
BEGIN
	ALTER TABLE btype 
		ADD fkdzdayflag INT NULL DEFAULT(0)
END
GO
UPDATE btype SET fkdzdayflag = 0 WHERE fkdzdayflag IS NULL
GO

--收款次月结
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='skcyjartime')
BEGIN
	ALTER TABLE btype 
		ADD skcyjartime INT NULL DEFAULT(0)
END
GO
UPDATE btype SET skcyjartime = 0 WHERE skcyjartime IS NULL
GO

--付款次月结
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='btype' AND a.Name='fkcyjaptime')
BEGIN
	ALTER TABLE btype 
		ADD fkcyjaptime INT NULL DEFAULT(0)
END
GO
UPDATE btype SET fkcyjaptime = 0 WHERE fkcyjaptime IS NULL
GO



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BType_ArApTotal]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[BType_ArApTotal](
		[BTypeID] [varchar] (50) NOT NULL,
		[STypeID] [varchar] (50) NOT NULL,
		[ARTotal] numeric(24,10) NULL DEFAULT 0,
		[APTotal] numeric(24,10) NULL DEFAULT 0,
		[YSTotal] numeric(24,10) NULL DEFAULT 0,
		[YFTotal] numeric(24,10) NULL DEFAULT 0,
		[ARTotal00] numeric(24,10) NULL DEFAULT 0,
		[APTotal00] numeric(24,10) NULL DEFAULT 0,
		[YSTotal00] numeric(24,10) NULL DEFAULT 0,
		[YFTotal00] numeric(24,10) NULL DEFAULT 0,
		[nARTotal] numeric(24,10) NULL DEFAULT 0,
		[nAPTotal] numeric(24,10) NULL DEFAULT 0,
		[nYSTotal] numeric(24,10) NULL DEFAULT 0,
		[nYFTotal] numeric(24,10) NULL DEFAULT 0,
		[nARTotal00] numeric(24,10) NULL DEFAULT 0,
		[nAPTotal00] numeric(24,10) NULL DEFAULT 0,
		[nYSTotal00] numeric(24,10) NULL DEFAULT 0,
		[nYFTotal00] numeric(24,10) NULL DEFAULT 0,
		[CID]	INT NULL,
		[GRIRTotal]		numeric(24,10) NULL DEFAULT 0,
		[NGRIRTotal]	numeric(24,10) NULL DEFAULT 0,
		[GRIRTotal00]	numeric(24,10) NULL DEFAULT 0,
		[NGRIRTotal00]	numeric(24,10) NULL DEFAULT 0,
		[FCTotal]		numeric(24,10) NULL DEFAULT 0,
		[NFCTotal]	numeric(24,10) NULL DEFAULT 0,
		[FCTotal00]	numeric(24,10) NULL DEFAULT 0,
		[NFCTotal00]	numeric(24,10) NULL DEFAULT 0
	) ON [PRIMARY]

END
GO

------------------------------------------表修改区域结束-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='CID'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD CID  INT NULL
	
	--EXEC('UPDATE BType_ArApTotal SET CurID=(SELECT CID FROM Ac_Currency WHERE SysRow=1) WHERE CurID IS NULL')
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nARTotal'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD nARTotal   numeric(22,10) NULL DEFAULT 0
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nApTotal'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD nApTotal   numeric(22,10) NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nysTotal'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD nysTotal   numeric(22,10) NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nyfTotal'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD nyfTotal   numeric(22,10) NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nARTotal00'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD nARTotal00   numeric(22,10) NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nApTotal00'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD nApTotal00   numeric(22,10) NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nysTotal00'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD nysTotal00   numeric(22,10) NULL DEFAULT 0
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nyfTotal00'
)
BEGIN
	ALTER TABLE BType_ArApTotal ADD nyfTotal00   numeric(22,10) NULL DEFAULT 0
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='CurID'
)
BEGIN
	ALTER TABLE BType_ArApTotal DROP COLUMN CurID
END

GO

--------------新增字段--------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE dbo.BType_ArApTotal 
		ADD STypeId VARCHAR(50) NOT NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='YSTotal00'
)
BEGIN
	ALTER TABLE dbo.BType_ArApTotal 
		ADD YSTotal00 NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='ARTotal00'
)
BEGIN
	ALTER TABLE dbo.BType_ArApTotal 
		ADD ARTotal00 NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nYSTotal00'
)
BEGIN
	ALTER TABLE dbo.BType_ArApTotal 
		ADD nYSTotal00 NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='nARTotal00'
)
BEGIN
	ALTER TABLE dbo.BType_ArApTotal 
		ADD nARTotal00 NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
--------------新增字段--------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ArApTotal' AND a.Name='GRIRTotal'
)
BEGIN
	ALTER TABLE BType_ArApTotal 
	ADD [GRIRTotal]		numeric(22,10) NULL DEFAULT 0,
		[NGRIRTotal]	numeric(22,10) NULL DEFAULT 0,
		[GRIRTotal00]	numeric(22,10) NULL DEFAULT 0,
		[NGRIRTotal00]	numeric(22,10) NULL DEFAULT 0,
		[FCTotal]		numeric(22,10) NULL DEFAULT 0,
		[NFCTotal]	numeric(22,10) NULL DEFAULT 0,
		[FCTotal00]	numeric(22,10) NULL DEFAULT 0,
		[NFCTotal00]	numeric(22,10) NULL DEFAULT 0
END
GO

UPDATE BType_ArApTotal 
SET	   GRIRTotal=ISNULL(GRIRTotal,0),
	   NGRIRTotal=ISNULL(NGRIRTotal,0),
	   GRIRTotal00=ISNULL(GRIRTotal00,0),
	   NGRIRTotal00=ISNULL(NGRIRTotal00,0),
	   FCTotal=ISNULL(FCTotal,0),
	   NFCTotal=ISNULL(NFCTotal,0),
	   FCTotal00=ISNULL(FCTotal00,0),
	   NFCTotal00=ISNULL(NFCTotal00,0)
GO


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BType_ArApTotal]') AND name = N'NCIX_STYPEID')
--	DROP INDEX [dbo].BType_ArApTotal.NCIX_STYPEID
	
--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BType_ArApTotal]') AND name = N'CIX_BType_ArApTotal_BSTYPEID')
--	DROP INDEX [CIX_BType_ArApTotal_BSTYPEID] ON [dbo].[BType_ArApTotal]
	
--GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BTYPE_ARAPTOTAL') AND name = 'CIX_BTYPE_ARAPTOTAL_Btypeid')
--DROP INDEX CIX_BTYPE_ARAPTOTAL_Btypeid ON BTYPE_ARAPTOTAL 
CREATE CLUSTERED INDEX CIX_BTYPE_ARAPTOTAL_Btypeid ON BTYPE_ARAPTOTAL(Btypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BTYPE_ARAPTOTAL') AND name = 'NCIX_BTYPE_ARAPTOTAL_Stypeid')
--DROP INDEX NCIX_BTYPE_ARAPTOTAL_Stypeid ON BTYPE_ARAPTOTAL 
CREATE NONCLUSTERED INDEX NCIX_BTYPE_ARAPTOTAL_Stypeid ON BTYPE_ARAPTOTAL(Stypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='ARTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN ARTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='APTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN APTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='YSTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN YSTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='YFTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN YFTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='ARTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN ARTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='APTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN APTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='YSTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN YSTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='YFTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN YFTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nARTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nARTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nAPTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nAPTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nYSTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nYSTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nYFTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nYFTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nARTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nARTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nAPTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nAPTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nYSTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nYSTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nYFTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nYFTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='GRIRTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN GRIRTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='NGRIRTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN NGRIRTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='GRIRTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN GRIRTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='NGRIRTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN NGRIRTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='FCTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN FCTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='NFCTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN NFCTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='FCTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN FCTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='NFCTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN NFCTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nApTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nApTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nysTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nysTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nyfTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nyfTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nApTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nApTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nysTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nysTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BType_ARAPTotal' AND a.Name='nyfTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BType_ARAPTotal 
	ALTER COLUMN nyfTotal00 NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[btype_credit]    脚本日期: 05/05/2010 14:46:49 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[btype_credit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[btype_credit](
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[StypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Credit]  [numeric]	(18,2) NULL 
	) ON [PRIMARY]
	
	-- ********	处理 BType	********
END
GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------



------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='btype_credit' AND a.Name='Credit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE btype_credit 
	ALTER COLUMN Credit NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  往来单位自定义字段
  张陈仁
  3023-04-10
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Btype_CustomColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table Btype_CustomColumns 
	(
	   ID                   bigint               identity(1,1),
	   typeid               varchar(100)         null,
	   Costom1              VARCHAR(600)         null,
	   Costom2              VARCHAR(600)         null,
	   Costom3              VARCHAR(600)         null,
	   Costom4              VARCHAR(600)         null,
	   Costom5              VARCHAR(600)         null,
	   Costom6              VARCHAR(600)         null,
	   Costom7              VARCHAR(600)         null,
	   Costom8              VARCHAR(600)         null,
	   Costom9              VARCHAR(600)         null,
	   Costom10             VARCHAR(600)         null,
	   Costom11             VARCHAR(600)         null,
	   Costom12             VARCHAR(600)         null,
	   Costom13             VARCHAR(600)         null,
	   Costom14             VARCHAR(600)         null,
	   Costom15             VARCHAR(600)         null,
	   Costom16             VARCHAR(600)         null,
	   Costom17             VARCHAR(600)         null,
	   Costom18             VARCHAR(600)         null,
	   Costom19             VARCHAR(600)         null,
	   Costom20             VARCHAR(600)         null
   )
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[btype_l]    脚本日期: 05/05/2010 14:46:50 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[btype_l]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[btype_l](
		[etypeid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[typeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[flag] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO
-- Add by 李海洋 
-- Date: 2012-03-30
-- Description: 增加: 修改, 分类, 停用, 删除 细分权限
------------------------------------------表修改区域开始-------------------------------------------------
-- 修改权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[btype_l]') 
		AND name = 'modifyflag'
)
BEGIN
		ALTER TABLE dbo.btype_l DROP COLUMN modifyflag ;
END
GO

-- 分类权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[btype_l]') 
		AND name = 'assortflag'
)
BEGIN
  ALTER TABLE dbo.btype_l DROP COLUMN assortflag ;
END
GO

-- 停用权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[btype_l]') 
		AND name = 'disableflag'
)
BEGIN
  ALTER TABLE dbo.btype_l DROP COLUMN disableflag ;
END
GO

-- 删除权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[btype_l]') 
		AND name = 'delflag'
)
BEGIN
		ALTER TABLE dbo.btype_l DROP COLUMN delflag ;
END  
GO

------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[btype_l]') AND name = N'IX_btype_l')
BEGIN
	DROP INDEX IX_btype_l ON btype_l
END
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BTYPE_L') AND name = 'CIX_BTYPE_L_etypeid')
--DROP INDEX CIX_BTYPE_L_etypeid ON BTYPE_L 
CREATE CLUSTERED INDEX CIX_BTYPE_L_etypeid ON BTYPE_L(etypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------更新新加列结束-------------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BType_Picture]    脚本日期: 01/11/2011 09:27:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BType_Picture]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[BType_Picture] (
	[BTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[Name]	[varchar](50) NOT NULL,
	[OrderID] [numeric](10, 0) IDENTITY(1,1) NOT NULL ,	
	[ImgURL] [VARCHAR](200) NOT NULL,
	[pic] [image] NULL,
	[length] [int] NULL,
	[filename] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[type] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,	
) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BuyBackBill]    脚本日期: 05/05/2010 14:46:50 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BuyBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BuyBackBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_Qty]  DEFAULT (0),
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBackBill_jobnumber]  DEFAULT (''),
		[goodsno] [int] NULL CONSTRAINT [DF_BuyBackBill_goodsno]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_TaxTotal]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBackBill_comment]  DEFAULT (''),
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_BuyBackBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBackBill_Serial]  DEFAULT (''),
		[OldID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBackBill_OldID]  DEFAULT (''),
		[OldBillNumberID] [numeric](18, 0) NULL CONSTRAINT [DF_BuyBackBill_OldBillNumberID]  DEFAULT (0),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_BuyBackBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBackBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBackBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBackBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBackBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_BuyBackBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_BuyBackBill_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__BuyBackBi__Compl__1CD54D62]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBackBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_BuyBackBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,ShowOrder INT DEFAULT(0)
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
		,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[PriceSource] VARCHAR(200)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBackBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.BuyBackBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBackBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.BuyBackBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBackBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.BuyBackBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.BuyBackBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBackBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE BuyBackBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE BuyBackBill SET PickedQty=0 WHERE PickedQty IS NULL
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[BuyBackBill]') and name = 'KTypeID' )
BEGIN
	
	ALTER TABLE dbo.BuyBackBill ADD
		KTypeID varchar(50) NULL
END
GO

UPDATE BuyBackBill
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE BuyBackBill.BillNumberID=b.BillNumberID AND BuyBackBill.KTypeID IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE BuyBackBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE BuyBackBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE BuyBackBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE BuyBackBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE BuyBackBill ADD UnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NUnitID INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NQty   numeric(22,10)    NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE BuyBackBill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE BuyBackBill ADD MUnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE BuyBackBill ADD MQty   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE BuyBackBill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE BuyBackBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD MSalePrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD MDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD MTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD CurMSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD CurMDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE BuyBackBill ADD CurMTaxPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE BuyBackBill ADD CargoID   INT  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE BuyBackBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE BuyBackBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE BuyBackBill ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE BuyBackBill ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NInvoiceMoney'
)
BEGIN
		ALTER TABLE BuyBackBill ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO		

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE BuyBackBill ADD IsGift INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='PriceStyle'
)
BEGIN
		ALTER TABLE BuyBackBill ADD PriceStyle INT NOT NULL DEFAULT(0) --价格类型
END
GO
-- 添加物流运输 已发运数量
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE BuyBackBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBackBill',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE BuyBackBill ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE BuyBackBill SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBackBill',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE BuyBackBill ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE BuyBackBill SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'BuyBackBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.BuyBackBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.BuyBackBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSapce' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'GiftFlag';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='BuyBackBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
from sys.default_constraints a 
	RIGHT JOIN sys.all_columns b on a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='Serial' AND a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('BuyBackBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table BuyBackBill drop constraint '+@dfname);
		
	ALTER TABLE BuyBackBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE BuyBackBill ADD CONSTRAINT DF_BuyBackBill_Serial DEFAULT('') FOR Serial

END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBackBill]') AND name = N'IX_BuyBackBill_BillNumberId')
--DROP INDEX [dbo].[BuyBackBill].[IX_BuyBackBill_BillNumberId]
--GO

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBackBill]') AND name = N'IX_BuyBackBill_PTypeID')
--DROP INDEX [dbo].[BuyBackBill].[IX_BuyBackBill_PTypeID]
--GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBACKBILL') AND name = 'NCIX_BUYBACKBILL_BillNumberId')
--DROP INDEX NCIX_BUYBACKBILL_BillNumberId ON BUYBACKBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYBACKBILL_BillNumberId ON BUYBACKBILL(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBACKBILL') AND name = 'NCIX_BUYBACKBILL_PtypeId')
--DROP INDEX NCIX_BUYBACKBILL_PtypeId ON BUYBACKBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYBACKBILL_PtypeId ON BUYBACKBILL(PtypeId) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBackBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
 GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBackBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE BuyBackBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
                                       
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BuyBill]    脚本日期: 05/05/2010 14:46:51 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BuyBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BuyBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_DiscountPrice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_TaxTotal]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo1] [int] NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[orderid] [int] NOT NULL CONSTRAINT [DF_BuyBill_orderid]  DEFAULT ('-1'),
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_BuyBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_InputCostPrice_1]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_BuyBill_GoodsOrder]  DEFAULT ('-1'),
		[BackQty] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_BackQty]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBill_GoodsBTypeID]  DEFAULT (''),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__BuyBill__Complet__1BE12929]  DEFAULT (0),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_BuyBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_BuyBill_HandZeroCost]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_BuyBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[FromBillID] [numeric](10, 0)  NULL,
		[ShareFee]	[numeric](18,2) NULL DEFAULT(0),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int                NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			VARCHAR(200)	   NULL DEFAULT(''),
   		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		ShowOrder INT DEFAULT(0),
		InflowQty NUMERIC(24,10) DEFAULT(0) ,  --入库数量
		InFactQty NUMERIC(24,10) DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[PriceSource] VARCHAR(200)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.BuyBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.BuyBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.BuyBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.BuyBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.BuyBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.BuyBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE BuyBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='KTypeID'
)
BEGIN
	ALTER TABLE BuyBill ADD KTypeID VARCHAR(50) NULL

END
GO

UPDATE BuyBill
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE BuyBill.BillNumberID=b.BillNumberID AND BuyBill.KTypeID IS NULL 
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE BuyBill ADD STypeID VARCHAR(50) DEFAULT('')
	
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE BuyBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE BuyBill ADD FromBillNumberID  [numeric](10, 0)  NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='FromBillID'
)
BEGIN
	ALTER TABLE BuyBill ADD FromBillID  [numeric](10, 0)  NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='ShareFee'
)
BEGIN
	ALTER TABLE BuyBill ADD ShareFee  [numeric](18, 2)  NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE BuyBill ADD TaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE BuyBill ADD NSalePrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE BuyBill ADD NSaleTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBill ADD NDiscountPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE BuyBill ADD NTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE BuyBill ADD NTaxPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE BuyBill ADD NTaxTotal   numeric(22,10)   NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE BuyBill ADD NTaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE BuyBill ADD UnitID  INT   NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE BuyBill ADD NUnitID INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE BuyBill ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE BuyBill ADD UnitRate   numeric(22,10)     NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE BuyBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE BuyBill ADD MUnitID  INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE BuyBill ADD MQty   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE BuyBill ADD MUnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE BuyBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE BuyBill ADD MSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBill ADD MDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE BuyBill ADD MTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE BuyBill ADD CurMSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBill ADD CurMDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE BuyBill ADD CurMTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE BuyBill ADD CargoID   INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE BuyBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE BuyBill ADD IsCombined   INT
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='entryCode'
)
BEGIN
		ALTER TABLE BuyBill ADD entryCode   VARCHAR(200) DEFAULT('')
END
ELSE
	ALTER TABLE dbo.BuyBill ALTER COLUMN entryCode varchar(200)
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE BuyBill ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE BuyBill ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NInvoiceMoney'
)
BEGIN
		ALTER TABLE BuyBill ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE BuyBill ADD IsGift  INT NOT NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='LendBillNumberID'
)
BEGIN
		ALTER TABLE BuyBill ADD LendBillNumberID numeric(10, 0)  NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='LendBillID'
)
BEGIN
		ALTER TABLE BuyBill ADD LendBillID NUMERIC(10, 0)  NULL DEFAULT(0)
END
GO	

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='Serial' AND a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('BuyBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table BuyBill drop constraint '+@dfname);
		
	ALTER TABLE BuyBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE BuyBill ADD CONSTRAINT DF_BuyBill_Serial DEFAULT('') FOR Serial

END
GO	

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'BuyBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.BuyBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.BuyBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO


IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBill',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE BuyBill ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE BuyBill SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBill',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE BuyBill ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE BuyBill SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL

GO

IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBill',N'U') AND Name='AskBillNumberID')
BEGIN
	ALTER TABLE dbo.BuyBill
	ADD AskBillNumberID INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBill',N'U') AND Name='AskBillID')
BEGIN
	ALTER TABLE dbo.BuyBill
	ADD AskBillID INT DEFAULT(0)
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'BarCode' UNION SELECT 'GiftFlag';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='BuyBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBill]') AND name = N'CIX_BID')
--	DROP INDEX [dbo].[BuyBill].CIX_BID

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBill]') AND name = N'NCIX_ORDERID')
--	DROP INDEX [dbo].[BuyBill].NCIX_ORDERID
--GO

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBill]') AND name = N'IX_BuyBill_BillNumberId')
--DROP INDEX [IX_BuyBill_BillNumberId] ON [dbo].[BuyBill] 


--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBill]') AND name = N'IX_BuyBill_PTypeID')
--DROP INDEX [IX_BuyBill_PTypeID] ON [dbo].[BuyBill] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBILL') AND name = 'CIX_BUYBILL_BillNumberID')
--DROP INDEX CIX_BUYBILL_BillNumberID ON BUYBILL 
CREATE CLUSTERED INDEX CIX_BUYBILL_BillNumberID ON BUYBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBILL') AND name = 'NCIX_BUYBILL_Ptypeid')
--DROP INDEX NCIX_BUYBILL_Ptypeid ON BUYBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYBILL_Ptypeid ON BUYBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBILL') AND name = 'NCIX_BUYBILL_Orderid')
--DROP INDEX NCIX_BUYBILL_Orderid ON BUYBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYBILL_Orderid ON BUYBILL(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBILL') AND name = 'NCIX_BUYBILL_Ktypeid')
--DROP INDEX NCIX_BUYBILL_Ktypeid ON BUYBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYBILL_Ktypeid ON BUYBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBILL') AND name = 'NCIX_BUYBILL_Stypeid')
--DROP INDEX NCIX_BUYBILL_Stypeid ON BUYBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYBILL_Stypeid ON BUYBILL(Stypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBILL') AND name = 'NCIX_BUYBILL_SalePrice')
DROP INDEX NCIX_BUYBILL_SalePrice ON BUYBILL 
                                   
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_BUYBILL_SalePrice ON BUYBILL(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBILL') AND name = 'NCIX_BUYBILL_Discount')
DROP INDEX NCIX_BUYBILL_Discount ON BUYBILL 
 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                   
CREATE NONCLUSTERED INDEX NCIX_BUYBILL_Discount ON BUYBILL(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYBILL') AND name = 'NCIX_BUYBILL_Tax')
DROP INDEX NCIX_BUYBILL_Tax ON BUYBILL 
                                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                  
CREATE NONCLUSTERED INDEX NCIX_BUYBILL_Tax ON BUYBILL(Tax) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE BuyBill SET sharefee = 0 WHERE sharefee IS NULL
GO
UPDATE BuyBill SET LendBillID = 0 WHERE LendBillID IS NULL
GO
UPDATE BuyBill SET LendBillNumberID = 0 WHERE LendBillNumberID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
         
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
          
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE BuyBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BuyBillAutoDraft]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BuyBillAutoDraft](
		[BillGuid]	VARCHAR(100) NULL DEFAULT(''),
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_DiscountPrice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_TaxTotal]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo1] [int] NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[orderid] [int] NOT NULL CONSTRAINT [DF_BuyBillAutoDraft_orderid]  DEFAULT ('-1'),
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_BuyBillAutoDraft_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBillAutoDraft_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_InputCostPrice_1]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_BuyBillAutoDraft_GoodsOrder]  DEFAULT ('-1'),
		[BackQty] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_BackQty]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBillAutoDraft_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBillAutoDraft_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBillAutoDraft_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyBillAutoDraft_GoodsBTypeID]  DEFAULT (''),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__BuyBillAutoDraft__Complet__1BE12929]  DEFAULT (0),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_BuyBillAutoDraft_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_BuyBillAutoDraft_HandZeroCost]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BuyBillAutoDraft_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_BuyBillAutoDraft_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[FromBillID] [numeric](10, 0)  NULL,
		[ShareFee]	[numeric](18,2) NULL DEFAULT(0),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int                NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			VARCHAR(200)	   NULL DEFAULT(''),
   		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		ShowOrder INT DEFAULT(0),
		InflowQty NUMERIC(24,10) DEFAULT(0) ,  --入库数量
		InFactQty NUMERIC(24,10) DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[PriceSource] VARCHAR(200)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBillAutoDraft',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.BuyBillAutoDraft
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBillAutoDraft',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.BuyBillAutoDraft
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBillAutoDraft',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.BuyBillAutoDraft
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.BuyBillAutoDraft SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBillAutoDraft',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.BuyBillAutoDraft
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.BuyBillAutoDraft SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='KTypeID'
)
BEGIN
	ALTER TABLE BuyBillAutoDraft ADD KTypeID VARCHAR(50) NULL

END
GO

UPDATE BuyBillAutoDraft
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE BuyBillAutoDraft.BillNumberID=b.BillNumberID AND BuyBillAutoDraft.KTypeID IS NULL 
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE BuyBillAutoDraft ADD STypeID VARCHAR(50) DEFAULT('')
	
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE BuyBillAutoDraft SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE BuyBillAutoDraft ADD FromBillNumberID  [numeric](10, 0)  NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='FromBillID'
)
BEGIN
	ALTER TABLE BuyBillAutoDraft ADD FromBillID  [numeric](10, 0)  NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='ShareFee'
)
BEGIN
	ALTER TABLE BuyBillAutoDraft ADD ShareFee  [numeric](18, 2)  NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD TaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NSalePrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NSaleTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NDiscountPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NTaxPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NTaxTotal   numeric(22,10)   NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NTaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD UnitID  INT   NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NUnitID INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD UnitRate   numeric(22,10)     NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD MUnitID  INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD MQty   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD MUnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD MSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD MDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD MTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD CurMSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD CurMDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD CurMTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD CargoID   INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD IsCombined   INT
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='entryCode'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD entryCode   VARCHAR(200) DEFAULT('')
END
ELSE
	ALTER TABLE dbo.BuyBillAutoDraft ALTER COLUMN entryCode varchar(200)
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NInvoiceMoney'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD IsGift  INT NOT NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='LendBillNumberID'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD LendBillNumberID numeric(10, 0)  NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='LendBillID'
)
BEGIN
		ALTER TABLE BuyBillAutoDraft ADD LendBillID NUMERIC(10, 0)  NULL DEFAULT(0)
END
GO	

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='Serial' AND a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('BuyBillAutoDraft') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table BuyBillAutoDraft drop constraint '+@dfname);
		
	ALTER TABLE BuyBillAutoDraft ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE BuyBillAutoDraft ADD CONSTRAINT DF_BuyBillAutoDraft_Serial DEFAULT('') FOR Serial

END
GO	

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'BuyBillAutoDraft',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.BuyBillAutoDraft
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.BuyBillAutoDraft SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO


IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBillAutoDraft',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE BuyBillAutoDraft ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE BuyBillAutoDraft SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBillAutoDraft',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE BuyBillAutoDraft ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE BuyBillAutoDraft SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL

GO

IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBillAutoDraft',N'U') AND Name='AskBillNumberID')
BEGIN
	ALTER TABLE dbo.BuyBillAutoDraft
	ADD AskBillNumberID INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyBillAutoDraft',N'U') AND Name='AskBillID')
BEGIN
	ALTER TABLE dbo.BuyBillAutoDraft
	ADD AskBillID INT DEFAULT(0)
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'BarCode' UNION SELECT 'GiftFlag';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='BuyBillAutoDraft';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBillAutoDraft]') AND name = N'CIX_BID')
--	DROP INDEX [dbo].[BuyBillAutoDraft].CIX_BID

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBillAutoDraft]') AND name = N'NCIX_ORDERID')
--	DROP INDEX [dbo].[BuyBillAutoDraft].NCIX_ORDERID
--GO

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBillAutoDraft]') AND name = N'IX_BuyBillAutoDraft_BillNumberId')
--DROP INDEX [IX_BuyBillAutoDraft_BillNumberId] ON [dbo].[BuyBillAutoDraft] 


--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BuyBillAutoDraft]') AND name = N'IX_BuyBillAutoDraft_PTypeID')
--DROP INDEX [IX_BuyBillAutoDraft_PTypeID] ON [dbo].[BuyBillAutoDraft] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BuyBillAutoDraft') AND name = 'CIX_BuyBillAutoDraft_BillNumberID')
--DROP INDEX CIX_BuyBillAutoDraft_BillNumberID ON BuyBillAutoDraft 
CREATE CLUSTERED INDEX CIX_BuyBillAutoDraft_BillNumberID ON BuyBillAutoDraft(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BuyBillAutoDraft') AND name = 'NCIX_BuyBillAutoDraft_Ptypeid')
--DROP INDEX NCIX_BuyBillAutoDraft_Ptypeid ON BuyBillAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BuyBillAutoDraft_Ptypeid ON BuyBillAutoDraft(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BuyBillAutoDraft') AND name = 'NCIX_BuyBillAutoDraft_Orderid')
--DROP INDEX NCIX_BuyBillAutoDraft_Orderid ON BuyBillAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BuyBillAutoDraft_Orderid ON BuyBillAutoDraft(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BuyBillAutoDraft') AND name = 'NCIX_BuyBillAutoDraft_Ktypeid')
--DROP INDEX NCIX_BuyBillAutoDraft_Ktypeid ON BuyBillAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BuyBillAutoDraft_Ktypeid ON BuyBillAutoDraft(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BuyBillAutoDraft') AND name = 'NCIX_BuyBillAutoDraft_Stypeid')
--DROP INDEX NCIX_BuyBillAutoDraft_Stypeid ON BuyBillAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_BuyBillAutoDraft_Stypeid ON BuyBillAutoDraft(Stypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BuyBillAutoDraft') AND name = 'NCIX_BuyBillAutoDraft_SalePrice')
DROP INDEX NCIX_BuyBillAutoDraft_SalePrice ON BuyBillAutoDraft 
                                   
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_BuyBillAutoDraft_SalePrice ON BuyBillAutoDraft(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BuyBillAutoDraft') AND name = 'NCIX_BuyBillAutoDraft_Discount')
DROP INDEX NCIX_BuyBillAutoDraft_Discount ON BuyBillAutoDraft 
 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                   
CREATE NONCLUSTERED INDEX NCIX_BuyBillAutoDraft_Discount ON BuyBillAutoDraft(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BuyBillAutoDraft') AND name = 'NCIX_BuyBillAutoDraft_Tax')
DROP INDEX NCIX_BuyBillAutoDraft_Tax ON BuyBillAutoDraft 
                                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                  
CREATE NONCLUSTERED INDEX NCIX_BuyBillAutoDraft_Tax ON BuyBillAutoDraft(Tax) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE BuyBillAutoDraft SET sharefee = 0 WHERE sharefee IS NULL
GO
UPDATE BuyBillAutoDraft SET LendBillID = 0 WHERE LendBillID IS NULL
GO
UPDATE BuyBillAutoDraft SET LendBillNumberID = 0 WHERE LendBillNumberID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
         
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
          
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyBillAutoDraft 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyBillAutoDraft' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE BuyBillAutoDraft 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BuyGoodsExchangeBill]    脚本日期: 05/05/2010 14:46:52 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BuyGoodsExchangeBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BuyGoodsExchangeBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[InOrOut] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyGoodsExchangeBill_jobnumber]  DEFAULT (''),
		[goodsno] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_goodsno]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_BuyGoodsExchangeBill_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_BuyGoodsExchangeBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyGoodsExchangeBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_BuyGoodsExchangeBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyGoodsExchangeBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyGoodsExchangeBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyGoodsExchangeBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_BuyGoodsExchangeBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_BuyGoodsExchangeBill_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__BuyGoodsE__Compl__1DC9719B]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_BuyGoodsExchangeBill_Tax]  DEFAULT (0),
		[KTypeID]  [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KTypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null	 ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift				 INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		OldID VARCHAR(50)    DEFAULT (''),
		OldBillNumberID      numeric(18, 0)   DEFAULT (0)
		,ShowOrder INT DEFAULT(0)
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
		,InFlowQty NUMERIC(24,10) NULL DEFAULT(0) --入库数量
		,InFactQty NUMERIC(24,10) NULL DEFAULT(0)
		,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[PriceSource] VARCHAR(200)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.BuyGoodsExchangeBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.BuyGoodsExchangeBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.BuyGoodsExchangeBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.BuyGoodsExchangeBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.BuyGoodsExchangeBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.BuyGoodsExchangeBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.BuyGoodsExchangeBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.BuyGoodsExchangeBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE BuyGoodsExchangeBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE BuyGoodsExchangeBill SET PickedQty=0 WHERE PickedQty IS NULL
GO
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.BuyGoodsExchangeBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.BuyGoodsExchangeBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[BuyGoodsExchangeBill]') and name = 'KTypeID' )
BEGIN
	ALTER TABLE dbo.BuyGoodsExchangeBill ADD
		KTypeID 	varchar(50) NULL	
END
GO
UPDATE BuyGoodsExchangeBill
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE BuyGoodsExchangeBill.BillNumberID=b.BillNumberID AND BuyGoodsExchangeBill.KTypeID IS NULL AND BuyGoodsExchangeBill.InOrOut='O'
GO

UPDATE BuyGoodsExchangeBill
SET KTypeID=b.KTypeID2
FROM BillIndex b
WHERE BuyGoodsExchangeBill.BillNumberID=b.BillNumberID AND BuyGoodsExchangeBill.KTypeID IS NULL AND BuyGoodsExchangeBill.InOrOut='I'
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[BuyGoodsExchangeBill]') and name = 'KTypeID2' )
BEGIN
	ALTER TABLE dbo.BuyGoodsExchangeBill ADD
		KTypeID2 	varchar(50) NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE BuyGoodsExchangeBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD PriceSource   VARCHAR(200)
END
GO

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD UnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NUnitID INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NQty   numeric(22,10)    NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD MUnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD MQty   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD MSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD MDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD MTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD CurMSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD CurMDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD CurMTaxPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD CargoID   INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NInvoiceMoney'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO		

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD IsGift INT NOT NULL DEFAULT(0)
END
GO	


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='OldID'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD OldID VARCHAR(50) NOT NULL DEFAULT('') 
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='OldBillNumberID'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD OldBillNumberID  numeric(18, 0) NOT NULL DEFAULT(0)
END
GO	
----物流运输 已发运数量
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE BuyGoodsExchangeBill ADD SendedQty  DECIMAL(24, 10) NULL DEFAULT(0)
END
GO	

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('BuyGoodsExchangeBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table BuyGoodsExchangeBill drop constraint '+@dfname);
		
	ALTER TABLE BuyGoodsExchangeBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE BuyGoodsExchangeBill ADD CONSTRAINT DF_BuyGoodsExchangeBill_Serial DEFAULT('') FOR Serial

END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE BuyGoodsExchangeBill ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE BuyGoodsExchangeBill SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'BuyGoodsExchangeBill',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE BuyGoodsExchangeBill ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE BuyGoodsExchangeBill SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'GiftFlag';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='BuyGoodsExchangeBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
from sys.default_constraints a 
	RIGHT JOIN sys.all_columns b on a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'CIX_BUYGOODSEXCHANGEBILL_BillNumberID')
--DROP INDEX CIX_BUYGOODSEXCHANGEBILL_BillNumberID ON BUYGOODSEXCHANGEBILL 
CREATE CLUSTERED INDEX CIX_BUYGOODSEXCHANGEBILL_BillNumberID ON BUYGOODSEXCHANGEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'NCIX_BUYGOODSEXCHANGEBILL_Ptypeid')
--DROP INDEX NCIX_BUYGOODSEXCHANGEBILL_Ptypeid ON BUYGOODSEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYGOODSEXCHANGEBILL_Ptypeid ON BUYGOODSEXCHANGEBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'NCIX_BUYGOODSEXCHANGEBILL_Orderid')
--DROP INDEX NCIX_BUYGOODSEXCHANGEBILL_Orderid ON BUYGOODSEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYGOODSEXCHANGEBILL_Orderid ON BUYGOODSEXCHANGEBILL(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'NCIX_BUYGOODSEXCHANGEBILL_Ktypeid')
--DROP INDEX NCIX_BUYGOODSEXCHANGEBILL_Ktypeid ON BUYGOODSEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYGOODSEXCHANGEBILL_Ktypeid ON BUYGOODSEXCHANGEBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'NCIX_BUYGOODSEXCHANGEBILL_Stypeid')
--DROP INDEX NCIX_BUYGOODSEXCHANGEBILL_Stypeid ON BUYGOODSEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYGOODSEXCHANGEBILL_Stypeid ON BUYGOODSEXCHANGEBILL(Stypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'NCIX_BUYGOODSEXCHANGEBILL_SalePrice')
DROP INDEX NCIX_BUYGOODSEXCHANGEBILL_SalePrice ON BUYGOODSEXCHANGEBILL 
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                            
CREATE NONCLUSTERED INDEX NCIX_BUYGOODSEXCHANGEBILL_SalePrice ON BUYGOODSEXCHANGEBILL(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'NCIX_BUYGOODSEXCHANGEBILL_Discount')
DROP INDEX NCIX_BUYGOODSEXCHANGEBILL_Discount ON BUYGOODSEXCHANGEBILL 
        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_BUYGOODSEXCHANGEBILL_Discount ON BUYGOODSEXCHANGEBILL(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'NCIX_BUYGOODSEXCHANGEBILL_Tax')
DROP INDEX NCIX_BUYGOODSEXCHANGEBILL_Tax ON BUYGOODSEXCHANGEBILL 
                                     
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
       
CREATE NONCLUSTERED INDEX NCIX_BUYGOODSEXCHANGEBILL_Tax ON BUYGOODSEXCHANGEBILL(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('BUYGOODSEXCHANGEBILL') AND name = 'NCIX_BUYGOODSEXCHANGEBILL_Stypeid')
--DROP INDEX NCIX_BUYGOODSEXCHANGEBILL_Stypeid ON BUYGOODSEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_BUYGOODSEXCHANGEBILL_Stypeid ON BUYGOODSEXCHANGEBILL(Stypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='goodsno' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN goodsno NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BuyGoodsExchangeBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE BuyGoodsExchangeBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
/************************************************************
 * 创 建 人：罗淮文
 * 创建时间: 2014/4/18 10:58:04
 * 内容描述：资金调拨单明细表
 ************************************************************/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[CapitalTransfer_Bill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[CapitalTransfer_Bill]
	(
		[ID]				  [int] IDENTITY(1,1) NOT NULL,--自增列
		[BillNumberId]        [int] NOT NULL,	--单据编号ID
		[BankAccountOut]      [varchar](50) NOT NULL,	--调出账户
		[BankAccountIn]       [varchar](50) NOT NULL,	--调入账户
		[TransferPrice]		  [numeric](18,2) NOT NULL,--调拨金额
		[DeductPrice]		  [numeric](18,2) NOT NULL,--手续费扣除金额
		[NTransferPrice]	  [numeric](18,2) NOT NULL,--本位币调拨金额
		[NDeductPrice]		  [numeric](18,2) NOT NULL,--本位币手续费扣除金额
		[Comment]			  [varchar](256) NULL,--备注
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]

	ALTER TABLE [dbo].[CapitalTransfer_Bill] ADD  DEFAULT(('')) FOR [BillNumberId]
	ALTER TABLE [dbo].[CapitalTransfer_Bill] ADD  DEFAULT(('')) FOR [BankAccountOut]
	ALTER TABLE [dbo].[CapitalTransfer_Bill] ADD  DEFAULT(('')) FOR [BankAccountIn]
	ALTER TABLE [dbo].[CapitalTransfer_Bill] ADD  DEFAULT((0)) FOR [TransferPrice]
	ALTER TABLE [dbo].[CapitalTransfer_Bill] ADD  DEFAULT((0)) FOR [DeductPrice]
	ALTER TABLE [dbo].[CapitalTransfer_Bill] ADD  DEFAULT((0)) FOR [NTransferPrice]
	ALTER TABLE [dbo].[CapitalTransfer_Bill] ADD  DEFAULT((0)) FOR [NDeductPrice]
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'CapitalTransfer_Bill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.CapitalTransfer_Bill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'CapitalTransfer_Bill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.CapitalTransfer_Bill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CapitalTransfer_Bill' AND a.Name='TransferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CapitalTransfer_Bill 
	ALTER COLUMN TransferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CapitalTransfer_Bill' AND a.Name='DeductPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CapitalTransfer_Bill 
	ALTER COLUMN DeductPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CapitalTransfer_Bill' AND a.Name='NTransferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CapitalTransfer_Bill 
	ALTER COLUMN NTransferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CapitalTransfer_Bill' AND a.Name='NDeductPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CapitalTransfer_Bill 
	ALTER COLUMN NDeductPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CargoSpace]    脚本日期: 05/05/2010 14:46:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[CargoSpace]') AND type in (N'U'))
DROP TABLE CargoSpace
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/*
	货位基本信息表
*/

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CargoType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table CargoType (
	   CargoID              int                  identity(1,1),
	   UserCode             varchar(200)         null,
	   FullName             varchar(200)         null,
	   KtypeID              varchar(50)          null,
	   Comment              varchar(500)         null,
	   PyCode               varchar(200)         null,
	   deleted				int  default(0),
	   IsDefault			INT DEFAULT(0)		NOT NULL,
	   XiWaMaxNumber          numeric(18,0)        NULL,
	   PathNo	INT	NULL
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CargoType' AND a.Name='XiWaMaxNumber'
)
BEGIN
	ALTER TABLE CargoType 
		ADD XiWaMaxNumber INT NOT NULL DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CargoType' AND a.Name='IsDefault'
)
BEGIN
	ALTER TABLE CargoType 
		ADD IsDefault INT NOT NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CargoType' AND a.Name='PathNo'
)
BEGIN
	ALTER TABLE CargoType 
		ADD PathNo INT NULL 
END

--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('CargoType') and name='WdSyncFlag')
BEGIN
	ALTER TABLE CargoType ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End

GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CARGOTYPE') AND name = 'CIX_CARGOTYPE_CargoID')
--DROP INDEX CIX_CARGOTYPE_CargoID ON CARGOTYPE 
CREATE CLUSTERED INDEX CIX_CARGOTYPE_CargoID ON CARGOTYPE(CargoID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CARGOTYPE') AND name = 'NCIX_CARGOTYPE_UserCode')
--DROP INDEX NCIX_CARGOTYPE_UserCode ON CARGOTYPE 
CREATE NONCLUSTERED INDEX NCIX_CARGOTYPE_UserCode ON CARGOTYPE(UserCode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CARGOTYPE') AND name = 'NCIX_CARGOTYPE_Ktypeid')
--DROP INDEX NCIX_CARGOTYPE_Ktypeid ON CARGOTYPE 
CREATE NONCLUSTERED INDEX NCIX_CARGOTYPE_Ktypeid ON CARGOTYPE(Ktypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE CargoType SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--常用承运单位
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CarriageUnit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CarriageUnit
(
	 ID	 NUMERIC(18,0) IDENTITY(1,1),
	 usercode	 VARCHAR(60)   NOT NULL,	  
	 fullname	 VARCHAR(60)	  NOT NULL,	  
)
END

GO

------------------------------------------表修改区域-开始-------------------------------------------------

IF EXISTS(select * from syscolumns where id = object_id(N'[CarriageUnit]') and  name = 'usercode' and LENGTH<>60)
BEGIN
	ALTER TABLE dbo.CarriageUnit  ALTER COLUMN usercode VARCHAR(60)
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[CarriageUnit]') and  name = 'fullname' and LENGTH<>60)
BEGIN
	ALTER TABLE dbo.CarriageUnit  ALTER COLUMN fullname VARCHAR(60)
END
GO
 
------------------------------------------表修改区域-结束-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CashMoneyBill]    脚本日期: 05/05/2010 14:46:53 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CashMoneyBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CashMoneyBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CashMoneyBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE CashMoneyBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE CashMoneyBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CashMoneyBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CashMoneyBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ChargeOffBill]    脚本日期: 09/28/2015 14:46:51 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ChargeOffBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ChargeOffBill](
		[BillNumberId] numeric(10, 0) NOT NULL,
		[FromBillNumberid] numeric(10, 0) NOT NULL,
		[FromBillType] Numeric(4,0) NOT NULL,
		[FromBillID] INT DEFAULT 0,
		[ID] int IDENTITY(1,1) NOT NULL,
		[ChargeOffType] int NOT NULL DEFAULT (0),
		[IsCharged] TINYINT NOT NULL DEFAULT (0),
		[BTypeID] varchar(50) NOT NULL DEFAULT (''),
		[ChargeOffValue] numeric(18, 10) NOT NULL DEFAULT (0),
		[NChargeOffValue] numeric(18, 10) NOT NULL DEFAULT (0),
		[TeamNo] INT DEFAULT 0,
		[Comment] VARCHAR(2000) DEFAULT ''
		,ShowOrder INT DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] 


END
GO


------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'chargeoffbill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.chargeoffbill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'chargeoffbill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.chargeoffbill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'chargeoffbill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.ChargeOffBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE chargeoffbill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ChargeOffBill' AND a.Name='FromBillType'
)
BEGIN
	ALTER TABLE ChargeOffBill 
		ADD FromBillType Numeric(4,0) NOT NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ChargeOffBill' AND a.Name='FromBillID'
)
BEGIN
	ALTER TABLE ChargeOffBill 
		ADD FromBillID INT DEFAULT 0
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ChargeOffBill' AND a.Name='TeamNo'
)
BEGIN
	ALTER TABLE ChargeOffBill 
		ADD TeamNo INT DEFAULT 0
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ChargeOffBill' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE ChargeOffBill 
		ADD Comment VARCHAR(256) DEFAULT ''
END
GO

--修改摘要的长度
IF EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID('ChargeOffBill',N'U') AND LOWER(Name)='Comment' AND [Length]=256)
BEGIN
	ALTER TABLE dbo.ChargeOffBill
	ALTER COLUMN Comment VARCHAR(2000) NULL
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ChargeOffBill') AND name = 'CIX_ChargeOffBill_BillNumberID')
--DROP INDEX CIX_ChargeOffBill_BillNumberID ON ChargeOffBill 
CREATE CLUSTERED INDEX CIX_ChargeOffBill_BillNumberID ON ChargeOffBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ChargeOffBill') AND name = 'CIX_ChargeOffBill_FromBillNumberid')
--DROP INDEX CIX_ChargeOffBill_FromBillNumberid ON ChargeOffBill 
CREATE NONCLUSTERED INDEX CIX_ChargeOffBill_FromBillNumberid ON ChargeOffBill(FromBillNumberid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ChargeOffBill' AND a.Name='ChargeOffValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ChargeOffBill 
	ALTER COLUMN ChargeOffValue NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ChargeOffBill' AND a.Name='NChargeOffValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ChargeOffBill 
	ALTER COLUMN NChargeOffValue NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_action]    脚本日期: 05/05/2010 14:46:54 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_action]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_action](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[act_name] [char](100) COLLATE Chinese_PRC_CI_AS NULL,
		[alias] [char](100) COLLATE Chinese_PRC_CI_AS NULL,
		[toall] [char](200) COLLATE Chinese_PRC_CI_AS NULL,
		[toself] [char](200) COLLATE Chinese_PRC_CI_AS NULL,
		[toother] [char](200) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_autoact]    脚本日期: 05/05/2010 14:46:55 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_autoact]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_autoact](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[text_body] [char](100) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_desc]    脚本日期: 05/05/2010 14:46:55 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_desc]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_desc](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[alias] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[describ] [char](254) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_guestbook]    脚本日期: 05/05/2010 14:46:56 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_guestbook]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_guestbook](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[who] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[towho] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[secret] [bit] NULL,
		[ip] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[email] [char](250) COLLATE Chinese_PRC_CI_AS NULL,
		[web] [char](250) COLLATE Chinese_PRC_CI_AS NULL,
		[addr] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[post_time] [datetime] NULL,
		[text_title] [char](100) COLLATE Chinese_PRC_CI_AS NULL,
		[text_body] [text] COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Chat_guestbook' AND a.Name='text_body' and a.xtype=35
)
BEGIN
	ALTER TABLE Chat_guestbook ALTER COLUMN text_body VARCHAR(MAX) NULL
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_helpbody]    脚本日期: 05/05/2010 14:46:57 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_helpbody]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_helpbody](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[alias] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[body] [text] COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Chat_helpbody' AND a.Name='body' and a.xtype=35
)
BEGIN
	ALTER TABLE Chat_helpbody ALTER COLUMN body VARCHAR(MAX)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_ip_lock]    脚本日期: 05/05/2010 14:46:58 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_ip_lock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_ip_lock](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ip] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[end_time] [datetime] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_record]    脚本日期: 05/05/2010 14:46:59 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_record]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_record](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[occ_time] [datetime] NULL,
		[occ_env] [char](200) COLLATE Chinese_PRC_CI_AS NULL,
		[for_what] [char](200) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_room]    脚本日期: 05/05/2010 14:47:00 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_room]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_room](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[room_name] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[room_auto] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[room_owner] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[room_des] [char](500) COLLATE Chinese_PRC_CI_AS NULL,
		[room_ref] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[room_title] [char](300) COLLATE Chinese_PRC_CI_AS NULL,
		[room_keep] [bit] NULL,
		[room_time] [datetime] NULL,
		[room_html] [bit] NULL,
		[ip_protect] [bit] NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Chat_room' AND a.Name='room_ref' and a.xtype=35
)
BEGIN
	ALTER TABLE Chat_room ALTER COLUMN room_ref VARCHAR(MAX)
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Chat_room)
BEGIN
	INSERT INTO Chat_room (room_name, room_des, room_time)VALUES ('32','gji_hcgbkfhc' , '2014-06-20')
	INSERT INTO Chat_room (room_name, room_des, room_time)VALUES ('82','hekahbadlaje' , '2014-06-20')
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Chat_room WHERE room_name = 'gws')
BEGIN
	INSERT INTO Chat_room (room_name, room_des, room_time)VALUES ('gws','http://chat_room/graspwebserver/gws.asmx' , '2014-06-20')
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_user]    脚本日期: 05/05/2010 14:47:01 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_user]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_user](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[username] [char](200) COLLATE Chinese_PRC_CI_AS NULL,
		[passwd] [char](200) COLLATE Chinese_PRC_CI_AS NULL,
		[sex] [bit] NULL,
		[user_level] [int] NULL,
		[log_time] [datetime] NULL,
		[visit_num] [int] NULL,
		[in_time] [datetime] NULL,
		[out_info] [int] NULL,
		[out_time] [datetime] NULL,
		[exp_num] [int] NULL,
		[f_size] [int] NULL,
		[l_height] [int] NULL,
		[n_color] [int] NULL,
		[s_color] [int] NULL,
		[email] [char](100) COLLATE Chinese_PRC_CI_AS NULL,
		[remand] [char](500) COLLATE Chinese_PRC_CI_AS NULL,
		[answer] [char](500) COLLATE Chinese_PRC_CI_AS NULL,
		[bgcolor] [char](100) COLLATE Chinese_PRC_CI_AS NULL,
		[temppass] [char](500) COLLATE Chinese_PRC_CI_AS NULL,
		[oicq] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[saved] [bit] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_vote]    脚本日期: 05/05/2010 14:47:01 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_vote]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_vote](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[exp_num] [int] NULL,
		[votename] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[voteoptions] [char](500) COLLATE Chinese_PRC_CI_AS NULL,
		[votenum] [int] NULL,
		[voted_user] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[begin_time] [datetime] NULL,
		[end_flag] [datetime] NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Chat_vote' AND a.Name='voted_user' and a.xtype=35
)
BEGIN
	ALTER TABLE Chat_vote ALTER COLUMN voted_user VARCHAR(MAX)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Chat_vrecord]    脚本日期: 05/05/2010 14:47:02 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Chat_vrecord]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Chat_vrecord](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[username] [char](200) COLLATE Chinese_PRC_CI_AS NULL,
		[votetype] [int] NULL,
		[end_time] [datetime] NULL,
		[temp_level] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CheckInfo]    脚本日期: 05/05/2010 14:47:03 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CheckInfo](
		[CheckTime] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[InOROut] [varchar](5) COLLATE Chinese_PRC_CI_AS NULL,
		[CheckDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[CheckTerm] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[StoreName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CheckStock]    脚本日期: 05/05/2010 14:47:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckStock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CheckStock](
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CheckStock_ptypeid]  DEFAULT (0),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CheckStock_ktypeid]  DEFAULT (0),
		[qty] [numeric](18, 4) NULL CONSTRAINT [DF_CheckStock_qty]  DEFAULT (0),
		[lossQty] [numeric](18, 4) NULL CONSTRAINT [DF_CheckStock_lossQty]  DEFAULT (0),
		[comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CheckStock_comment]  DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CheckStock' AND a.Name='qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CheckStock 
	ALTER COLUMN qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CheckStock' AND a.Name='lossQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CheckStock 
	ALTER COLUMN lossQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CheckTimeset]    脚本日期: 05/05/2010 14:47:05 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckTimeset]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CheckTimeset](
		[TimeTypeName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[TimeStart] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[TimeEnd] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[DromedaryName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if NOT exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[city]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[city] (
		[id] [int] IDENTITY (1, 1) NOT NULL ,
		[areaid] [int] NULL ,
		[Cname] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[orderid] [int] NULL 
	) ON [PRIMARY]
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM city)
BEGIN
	SET IDENTITY_INSERT city ON
	insert into city(id,areaid,cname,orderid) values (1,20,'安庆',35)
	insert into city(id,areaid,cname,orderid) values (2,20,'蚌埠',36)
	insert into city(id,areaid,cname,orderid) values (3,20,'巢湖',37)
	insert into city(id,areaid,cname,orderid) values (4,20,'池州',38)
	insert into city(id,areaid,cname,orderid) values (5,20,'滁州',39)
	insert into city(id,areaid,cname,orderid) values (6,20,'阜阳',40)
	insert into city(id,areaid,cname,orderid) values (7,20,'合肥',41)
	insert into city(id,areaid,cname,orderid) values (8,20,'淮北',42)
	insert into city(id,areaid,cname,orderid) values (9,20,'淮南',43)
	insert into city(id,areaid,cname,orderid) values (10,20,'黄山',44)
	insert into city(id,areaid,cname,orderid) values (11,20,'六安',45)
	insert into city(id,areaid,cname,orderid) values (12,20,'马鞍山',46)
	insert into city(id,areaid,cname,orderid) values (13,20,'宿州',47)
	insert into city(id,areaid,cname,orderid) values (14,20,'铜陵',48)
	insert into city(id,areaid,cname,orderid) values (15,20,'芜湖',49)
	insert into city(id,areaid,cname,orderid) values (16,20,'宣城',50)
	insert into city(id,areaid,cname,orderid) values (17,20,'亳州',51)
	insert into city(id,areaid,cname,orderid) values (18,12,'北京',52)
	insert into city(id,areaid,cname,orderid) values (19,6,'福州',53)
	insert into city(id,areaid,cname,orderid) values (20,6,'龙岩',54)
	insert into city(id,areaid,cname,orderid) values (21,6,'南平',55)
	insert into city(id,areaid,cname,orderid) values (22,6,'宁德',56)
	insert into city(id,areaid,cname,orderid) values (23,6,'莆田',57)
	insert into city(id,areaid,cname,orderid) values (24,6,'泉州',58)
	insert into city(id,areaid,cname,orderid) values (25,6,'三明',59)
	insert into city(id,areaid,cname,orderid) values (26,6,'厦门',60)
	insert into city(id,areaid,cname,orderid) values (27,6,'漳州',61)
	insert into city(id,areaid,cname,orderid) values (28,30,'白银',62)
	insert into city(id,areaid,cname,orderid) values (29,30,'定西',63)
	insert into city(id,areaid,cname,orderid) values (30,30,'甘南藏族自治州',64)
	insert into city(id,areaid,cname,orderid) values (31,30,'嘉峪关',65)
	insert into city(id,areaid,cname,orderid) values (32,30,'金昌',66)
	insert into city(id,areaid,cname,orderid) values (371,36,'其它地区',406)
	insert into city(id,areaid,cname,orderid) values (34,30,'酒泉',68)
	insert into city(id,areaid,cname,orderid) values (35,30,'临夏回族自治州',69)
	insert into city(id,areaid,cname,orderid) values (36,30,'陇南',70)
	insert into city(id,areaid,cname,orderid) values (37,30,'平凉',71)
	insert into city(id,areaid,cname,orderid) values (38,30,'庆阳',72)
	insert into city(id,areaid,cname,orderid) values (39,30,'天水',73)
	insert into city(id,areaid,cname,orderid) values (40,30,'武威',74)
	insert into city(id,areaid,cname,orderid) values (41,30,'张掖',75)
	insert into city(id,areaid,cname,orderid) values (42,3,'潮州',76)
	insert into city(id,areaid,cname,orderid) values (43,3,'东莞',77)
	insert into city(id,areaid,cname,orderid) values (44,3,'佛山',78)
	insert into city(id,areaid,cname,orderid) values (45,3,'广州',79)
	insert into city(id,areaid,cname,orderid) values (46,3,'河源',80)
	insert into city(id,areaid,cname,orderid) values (47,3,'惠州',81)
	insert into city(id,areaid,cname,orderid) values (48,3,'江门',82)
	insert into city(id,areaid,cname,orderid) values (49,3,'揭阳',83)
	insert into city(id,areaid,cname,orderid) values (50,3,'茂名',84)
	insert into city(id,areaid,cname,orderid) values (51,3,'梅州',85)
	insert into city(id,areaid,cname,orderid) values (52,3,'清远',86)
	insert into city(id,areaid,cname,orderid) values (53,3,'汕头',87)
	insert into city(id,areaid,cname,orderid) values (54,3,'汕尾',88)
	insert into city(id,areaid,cname,orderid) values (55,3,'韶关',89)
	insert into city(id,areaid,cname,orderid) values (56,3,'深圳',90)
	insert into city(id,areaid,cname,orderid) values (57,3,'阳江',91)
	insert into city(id,areaid,cname,orderid) values (58,3,'云浮',92)
	insert into city(id,areaid,cname,orderid) values (59,3,'湛江',93)
	insert into city(id,areaid,cname,orderid) values (60,3,'肇庆',94)
	insert into city(id,areaid,cname,orderid) values (61,3,'中山',95)
	insert into city(id,areaid,cname,orderid) values (62,3,'珠海',96)
	insert into city(id,areaid,cname,orderid) values (63,4,'百色',97)
	insert into city(id,areaid,cname,orderid) values (64,4,'北海',98)
	insert into city(id,areaid,cname,orderid) values (65,4,'崇左',99)
	insert into city(id,areaid,cname,orderid) values (66,4,'防城港',100)
	insert into city(id,areaid,cname,orderid) values (67,4,'桂林',101)
	insert into city(id,areaid,cname,orderid) values (68,4,'贵港',102)
	insert into city(id,areaid,cname,orderid) values (69,4,'河池',103)
	insert into city(id,areaid,cname,orderid) values (70,4,'贺州',104)
	insert into city(id,areaid,cname,orderid) values (71,4,'来宾',105)
	insert into city(id,areaid,cname,orderid) values (72,4,'柳州',106)
	insert into city(id,areaid,cname,orderid) values (73,4,'南宁',107)
	insert into city(id,areaid,cname,orderid) values (74,4,'钦州',108)
	insert into city(id,areaid,cname,orderid) values (75,4,'梧州',109)
	insert into city(id,areaid,cname,orderid) values (76,4,'玉林',110)
	insert into city(id,areaid,cname,orderid) values (77,25,'安顺',111)
	insert into city(id,areaid,cname,orderid) values (78,25,'毕节',112)
	insert into city(id,areaid,cname,orderid) values (79,25,'贵阳',113)
	insert into city(id,areaid,cname,orderid) values (80,25,'六盘水',114)
	insert into city(id,areaid,cname,orderid) values (81,25,'黔东南苗族侗族自治州',115)
	insert into city(id,areaid,cname,orderid) values (82,25,'黔南布依族苗族自治州',116)
	insert into city(id,areaid,cname,orderid) values (83,25,'黔西南布依族苗族自治州',117)
	insert into city(id,areaid,cname,orderid) values (84,25,'铜仁',118)
	insert into city(id,areaid,cname,orderid) values (85,25,'遵义',119)
	insert into city(id,areaid,cname,orderid) values (86,5,'白沙黎族自治县',120)
	insert into city(id,areaid,cname,orderid) values (87,5,'保亭黎族苗族自治县',121)
	insert into city(id,areaid,cname,orderid) values (88,5,'昌江黎族自治县',122)
	insert into city(id,areaid,cname,orderid) values (89,5,'澄迈县',123)
	insert into city(id,areaid,cname,orderid) values (90,5,'定安县',124)
	insert into city(id,areaid,cname,orderid) values (91,5,'东方',125)
	insert into city(id,areaid,cname,orderid) values (92,5,'海口',126)
	insert into city(id,areaid,cname,orderid) values (93,5,'乐东黎族自治县',127)
	insert into city(id,areaid,cname,orderid) values (94,5,'临高县',128)
	insert into city(id,areaid,cname,orderid) values (95,5,'陵水黎族自治县',129)
	insert into city(id,areaid,cname,orderid) values (96,5,'琼海',130)
	insert into city(id,areaid,cname,orderid) values (97,5,'琼中黎族苗族自治县',131)
	insert into city(id,areaid,cname,orderid) values (98,5,'三亚',132)
	insert into city(id,areaid,cname,orderid) values (99,5,'屯昌县',133)
	insert into city(id,areaid,cname,orderid) values (100,5,'万宁',134)
	insert into city(id,areaid,cname,orderid) values (101,5,'文昌',135)
	insert into city(id,areaid,cname,orderid) values (102,5,'五指山',136)
	insert into city(id,areaid,cname,orderid) values (103,5,'儋州',137)
	insert into city(id,areaid,cname,orderid) values (104,14,'保定',138)
	insert into city(id,areaid,cname,orderid) values (105,14,'沧州',139)
	insert into city(id,areaid,cname,orderid) values (106,14,'承德',140)
	insert into city(id,areaid,cname,orderid) values (107,14,'邯郸',141)
	insert into city(id,areaid,cname,orderid) values (108,14,'衡水',142)
	insert into city(id,areaid,cname,orderid) values (109,14,'廊坊',143)
	insert into city(id,areaid,cname,orderid) values (110,14,'秦皇岛',144)
	insert into city(id,areaid,cname,orderid) values (111,14,'石家庄',145)
	insert into city(id,areaid,cname,orderid) values (112,14,'唐山',146)
	insert into city(id,areaid,cname,orderid) values (113,14,'邢台',147)
	insert into city(id,areaid,cname,orderid) values (114,14,'张家口',148)
	insert into city(id,areaid,cname,orderid) values (115,22,'安阳',149)
	insert into city(id,areaid,cname,orderid) values (116,22,'鹤壁',150)
	insert into city(id,areaid,cname,orderid) values (117,22,'济源',151)
	insert into city(id,areaid,cname,orderid) values (118,22,'焦作',152)
	insert into city(id,areaid,cname,orderid) values (119,22,'开封',153)
	insert into city(id,areaid,cname,orderid) values (120,22,'洛阳',154)
	insert into city(id,areaid,cname,orderid) values (121,22,'南阳',155)
	insert into city(id,areaid,cname,orderid) values (122,22,'平顶山',156)
	insert into city(id,areaid,cname,orderid) values (123,22,'三门峡',157)
	insert into city(id,areaid,cname,orderid) values (124,22,'商丘',158)
	insert into city(id,areaid,cname,orderid) values (125,22,'新乡',159)
	insert into city(id,areaid,cname,orderid) values (126,22,'信阳',160)
	insert into city(id,areaid,cname,orderid) values (127,22,'许昌',161)
	insert into city(id,areaid,cname,orderid) values (128,22,'郑州',162)
	insert into city(id,areaid,cname,orderid) values (129,22,'周口',163)
	insert into city(id,areaid,cname,orderid) values (130,22,'驻马店',164)
	insert into city(id,areaid,cname,orderid) values (131,22,'漯河',165)
	insert into city(id,areaid,cname,orderid) values (132,22,'濮阳',166)
	insert into city(id,areaid,cname,orderid) values (133,11,'大庆',167)
	insert into city(id,areaid,cname,orderid) values (134,11,'大兴安岭',168)
	insert into city(id,areaid,cname,orderid) values (135,11,'哈尔滨',169)
	insert into city(id,areaid,cname,orderid) values (136,11,'鹤岗',170)
	insert into city(id,areaid,cname,orderid) values (137,11,'黑河',171)
	insert into city(id,areaid,cname,orderid) values (138,11,'鸡西',172)
	insert into city(id,areaid,cname,orderid) values (139,11,'佳木斯',173)
	insert into city(id,areaid,cname,orderid) values (140,11,'牡丹江',174)
	insert into city(id,areaid,cname,orderid) values (141,11,'七台河',175)
	insert into city(id,areaid,cname,orderid) values (142,11,'齐齐哈尔',176)
	insert into city(id,areaid,cname,orderid) values (143,11,'双鸭山',177)
	insert into city(id,areaid,cname,orderid) values (144,11,'绥化',178)
	insert into city(id,areaid,cname,orderid) values (145,11,'伊春',179)
	insert into city(id,areaid,cname,orderid) values (146,7,'鄂州',180)
	insert into city(id,areaid,cname,orderid) values (147,7,'恩施土家族苗族自治州',181)
	insert into city(id,areaid,cname,orderid) values (148,7,'黄冈',182)
	insert into city(id,areaid,cname,orderid) values (149,7,'黄石',183)
	insert into city(id,areaid,cname,orderid) values (150,7,'荆门',184)
	insert into city(id,areaid,cname,orderid) values (151,7,'荆州',185)
	insert into city(id,areaid,cname,orderid) values (152,7,'潜江',186)
	insert into city(id,areaid,cname,orderid) values (153,7,'神农架林区',187)
	insert into city(id,areaid,cname,orderid) values (154,7,'十堰',188)
	insert into city(id,areaid,cname,orderid) values (155,7,'随州',189)
	insert into city(id,areaid,cname,orderid) values (156,7,'天门',190)
	insert into city(id,areaid,cname,orderid) values (157,7,'武汉',191)
	insert into city(id,areaid,cname,orderid) values (158,7,'仙桃',192)
	insert into city(id,areaid,cname,orderid) values (159,7,'咸宁',193)
	insert into city(id,areaid,cname,orderid) values (160,7,'襄阳',194)
	insert into city(id,areaid,cname,orderid) values (161,7,'孝感',195)
	insert into city(id,areaid,cname,orderid) values (162,7,'宜昌',196)
	insert into city(id,areaid,cname,orderid) values (163,23,'常德',197)
	insert into city(id,areaid,cname,orderid) values (164,23,'长沙',198)
	insert into city(id,areaid,cname,orderid) values (165,23,'郴州',199)
	insert into city(id,areaid,cname,orderid) values (166,23,'衡阳',200)
	insert into city(id,areaid,cname,orderid) values (167,23,'怀化',201)
	insert into city(id,areaid,cname,orderid) values (168,23,'娄底',202)
	insert into city(id,areaid,cname,orderid) values (169,23,'邵阳',203)
	insert into city(id,areaid,cname,orderid) values (170,23,'湘潭',204)
	insert into city(id,areaid,cname,orderid) values (171,23,'湘西土家族苗族自治州',205)
	insert into city(id,areaid,cname,orderid) values (172,23,'益阳',206)
	insert into city(id,areaid,cname,orderid) values (173,23,'永州',207)
	insert into city(id,areaid,cname,orderid) values (174,23,'岳阳',208)
	insert into city(id,areaid,cname,orderid) values (175,23,'张家界',209)
	insert into city(id,areaid,cname,orderid) values (176,23,'株洲',210)
	insert into city(id,areaid,cname,orderid) values (177,10,'白城',211)
	insert into city(id,areaid,cname,orderid) values (178,10,'白山',212)
	insert into city(id,areaid,cname,orderid) values (179,10,'长春',213)
	insert into city(id,areaid,cname,orderid) values (180,10,'吉林',214)
	insert into city(id,areaid,cname,orderid) values (181,10,'辽源',215)
	insert into city(id,areaid,cname,orderid) values (182,10,'四平',216)
	insert into city(id,areaid,cname,orderid) values (183,10,'松原',217)
	insert into city(id,areaid,cname,orderid) values (184,10,'通化',218)
	insert into city(id,areaid,cname,orderid) values (185,10,'延边朝鲜族自治州',219)
	insert into city(id,areaid,cname,orderid) values (186,17,'常州',220)
	insert into city(id,areaid,cname,orderid) values (187,17,'淮安',221)
	insert into city(id,areaid,cname,orderid) values (188,17,'连云港',222)
	insert into city(id,areaid,cname,orderid) values (189,17,'南京',223)
	insert into city(id,areaid,cname,orderid) values (190,17,'南通',224)
	insert into city(id,areaid,cname,orderid) values (191,17,'苏州',225)
	insert into city(id,areaid,cname,orderid) values (192,17,'宿迁',226)
	insert into city(id,areaid,cname,orderid) values (193,17,'泰州',227)
	insert into city(id,areaid,cname,orderid) values (194,17,'无锡',228)
	insert into city(id,areaid,cname,orderid) values (195,17,'徐州',229)
	insert into city(id,areaid,cname,orderid) values (196,17,'盐城',230)
	insert into city(id,areaid,cname,orderid) values (197,17,'扬州',231)
	insert into city(id,areaid,cname,orderid) values (198,17,'镇江',232)
	insert into city(id,areaid,cname,orderid) values (199,21,'抚州',233)
	insert into city(id,areaid,cname,orderid) values (200,21,'赣州',234)
	insert into city(id,areaid,cname,orderid) values (201,21,'吉安',235)
	insert into city(id,areaid,cname,orderid) values (202,21,'景德镇',236)
	insert into city(id,areaid,cname,orderid) values (203,21,'九江',237)
	insert into city(id,areaid,cname,orderid) values (204,21,'南昌',238)
	insert into city(id,areaid,cname,orderid) values (205,21,'萍乡',239)
	insert into city(id,areaid,cname,orderid) values (206,21,'上饶',240)
	insert into city(id,areaid,cname,orderid) values (207,21,'新余',241)
	insert into city(id,areaid,cname,orderid) values (208,21,'宜春',242)
	insert into city(id,areaid,cname,orderid) values (209,21,'鹰潭',243)
	insert into city(id,areaid,cname,orderid) values (210,9,'鞍山',244)
	insert into city(id,areaid,cname,orderid) values (211,9,'本溪',245)
	insert into city(id,areaid,cname,orderid) values (212,9,'朝阳',246)
	insert into city(id,areaid,cname,orderid) values (213,9,'大连',247)
	insert into city(id,areaid,cname,orderid) values (214,9,'丹东',248)
	insert into city(id,areaid,cname,orderid) values (215,9,'抚顺',249)
	insert into city(id,areaid,cname,orderid) values (216,9,'阜新',250)
	insert into city(id,areaid,cname,orderid) values (217,9,'葫芦岛',251)
	insert into city(id,areaid,cname,orderid) values (218,9,'锦州',252)
	insert into city(id,areaid,cname,orderid) values (219,9,'辽阳',253)
	insert into city(id,areaid,cname,orderid) values (220,9,'盘锦',254)
	insert into city(id,areaid,cname,orderid) values (221,9,'沈阳',255)
	insert into city(id,areaid,cname,orderid) values (222,9,'铁岭',256)
	insert into city(id,areaid,cname,orderid) values (223,9,'营口',257)
	insert into city(id,areaid,cname,orderid) values (224,15,'阿拉善盟',258)
	insert into city(id,areaid,cname,orderid) values (225,15,'巴彦淖尔盟',259)
	insert into city(id,areaid,cname,orderid) values (226,15,'包头',260)
	insert into city(id,areaid,cname,orderid) values (227,15,'赤峰',261)
	insert into city(id,areaid,cname,orderid) values (228,15,'鄂尔多斯',262)
	insert into city(id,areaid,cname,orderid) values (229,15,'呼和浩特',263)
	insert into city(id,areaid,cname,orderid) values (230,15,'呼伦贝尔',264)
	insert into city(id,areaid,cname,orderid) values (231,15,'通辽',265)
	insert into city(id,areaid,cname,orderid) values (232,15,'乌海',266)
	insert into city(id,areaid,cname,orderid) values (233,15,'乌兰察布盟',267)
	insert into city(id,areaid,cname,orderid) values (234,15,'锡林郭勒盟',268)
	insert into city(id,areaid,cname,orderid) values (235,15,'兴安盟',269)
	insert into city(id,areaid,cname,orderid) values (236,31,'固原',270)
	insert into city(id,areaid,cname,orderid) values (237,31,'石嘴山',271)
	insert into city(id,areaid,cname,orderid) values (238,31,'吴忠',272)
	insert into city(id,areaid,cname,orderid) values (239,31,'银川',273)
	insert into city(id,areaid,cname,orderid) values (240,26,'果洛藏族自治州',274)
	insert into city(id,areaid,cname,orderid) values (241,26,'海北藏族自治州',275)
	insert into city(id,areaid,cname,orderid) values (242,26,'海东',276)
	insert into city(id,areaid,cname,orderid) values (243,26,'海南藏族自治州',277)
	insert into city(id,areaid,cname,orderid) values (244,26,'海西蒙古族藏族自治州',278)
	insert into city(id,areaid,cname,orderid) values (245,26,'黄南藏族自治州',279)
	insert into city(id,areaid,cname,orderid) values (246,26,'西宁',280)
	insert into city(id,areaid,cname,orderid) values (247,26,'玉树藏族自治州',281)
	insert into city(id,areaid,cname,orderid) values (248,16,'滨州',282)
	insert into city(id,areaid,cname,orderid) values (249,16,'德州',283)
	insert into city(id,areaid,cname,orderid) values (250,16,'东营',284)
	insert into city(id,areaid,cname,orderid) values (251,16,'菏泽',285)
	insert into city(id,areaid,cname,orderid) values (252,16,'济南',286)
	insert into city(id,areaid,cname,orderid) values (253,16,'济宁',287)
	insert into city(id,areaid,cname,orderid) values (254,16,'莱芜',288)
	insert into city(id,areaid,cname,orderid) values (255,16,'聊城',289)
	insert into city(id,areaid,cname,orderid) values (256,16,'临沂',290)
	insert into city(id,areaid,cname,orderid) values (257,16,'青岛',291)
	insert into city(id,areaid,cname,orderid) values (258,16,'日照',292)
	insert into city(id,areaid,cname,orderid) values (259,16,'泰安',293)
	insert into city(id,areaid,cname,orderid) values (260,16,'威海',294)
	insert into city(id,areaid,cname,orderid) values (261,16,'潍坊',295)
	insert into city(id,areaid,cname,orderid) values (262,16,'烟台',296)
	insert into city(id,areaid,cname,orderid) values (263,16,'枣庄',297)
	insert into city(id,areaid,cname,orderid) values (264,16,'淄博',298)
	insert into city(id,areaid,cname,orderid) values (265,32,'长治',299)
	insert into city(id,areaid,cname,orderid) values (266,32,'大同',300)
	insert into city(id,areaid,cname,orderid) values (267,32,'晋城',301)
	insert into city(id,areaid,cname,orderid) values (268,32,'晋中',302)
	insert into city(id,areaid,cname,orderid) values (269,32,'临汾',303)
	insert into city(id,areaid,cname,orderid) values (270,32,'吕梁',304)
	insert into city(id,areaid,cname,orderid) values (271,32,'朔州',305)
	insert into city(id,areaid,cname,orderid) values (272,32,'太原',306)
	insert into city(id,areaid,cname,orderid) values (273,32,'忻州',307)
	insert into city(id,areaid,cname,orderid) values (274,32,'阳泉',308)
	insert into city(id,areaid,cname,orderid) values (275,32,'运城',309)
	insert into city(id,areaid,cname,orderid) values (276,29,'安康',310)
	insert into city(id,areaid,cname,orderid) values (277,29,'宝鸡',311)
	insert into city(id,areaid,cname,orderid) values (278,29,'汉中',312)
	insert into city(id,areaid,cname,orderid) values (279,29,'商洛',313)
	insert into city(id,areaid,cname,orderid) values (280,29,'铜川',314)
	insert into city(id,areaid,cname,orderid) values (281,29,'渭南',315)
	insert into city(id,areaid,cname,orderid) values (282,29,'西安',316)
	insert into city(id,areaid,cname,orderid) values (283,29,'咸阳',317)
	insert into city(id,areaid,cname,orderid) values (284,29,'延安',318)
	insert into city(id,areaid,cname,orderid) values (285,29,'榆林',319)
	insert into city(id,areaid,cname,orderid) values (286,19,'上海',320)
	insert into city(id,areaid,cname,orderid) values (287,1,'简阳',321)
	insert into city(id,areaid,cname,orderid) values (288,1,'巴中',322)
	insert into city(id,areaid,cname,orderid) values (289,1,'成都',323)
	insert into city(id,areaid,cname,orderid) values (290,1,'达州',324)
	insert into city(id,areaid,cname,orderid) values (291,1,'德阳',325)
	insert into city(id,areaid,cname,orderid) values (292,1,'甘孜藏族自治州',326)
	insert into city(id,areaid,cname,orderid) values (293,1,'广安',327)
	insert into city(id,areaid,cname,orderid) values (294,1,'广元',328)
	insert into city(id,areaid,cname,orderid) values (295,1,'乐山',329)
	insert into city(id,areaid,cname,orderid) values (296,1,'凉山彝族自治州',330)
	insert into city(id,areaid,cname,orderid) values (297,1,'眉山',331)
	insert into city(id,areaid,cname,orderid) values (298,1,'绵阳',332)
	insert into city(id,areaid,cname,orderid) values (299,1,'南充',333)
	insert into city(id,areaid,cname,orderid) values (300,1,'内江',334)
	insert into city(id,areaid,cname,orderid) values (301,1,'攀枝花',335)
	insert into city(id,areaid,cname,orderid) values (302,1,'遂宁',336)
	insert into city(id,areaid,cname,orderid) values (303,1,'雅安',337)
	insert into city(id,areaid,cname,orderid) values (304,1,'宜宾',338)
	insert into city(id,areaid,cname,orderid) values (305,1,'资阳',339)
	insert into city(id,areaid,cname,orderid) values (306,1,'自贡',340)
	insert into city(id,areaid,cname,orderid) values (307,1,'泸州',341)
	insert into city(id,areaid,cname,orderid) values (308,13,'天津',342)
	insert into city(id,areaid,cname,orderid) values (309,27,'阿里',343)
	insert into city(id,areaid,cname,orderid) values (310,27,'昌都',344)
	insert into city(id,areaid,cname,orderid) values (311,27,'拉萨',345)
	insert into city(id,areaid,cname,orderid) values (312,27,'林芝',346)
	insert into city(id,areaid,cname,orderid) values (313,27,'那曲',347)
	insert into city(id,areaid,cname,orderid) values (314,27,'日喀则',348)
	insert into city(id,areaid,cname,orderid) values (315,27,'山南',349)
	insert into city(id,areaid,cname,orderid) values (316,28,'阿克苏',350)
	insert into city(id,areaid,cname,orderid) values (317,28,'阿拉尔',351)
	insert into city(id,areaid,cname,orderid) values (318,28,'巴音郭楞蒙古自治州',352)
	insert into city(id,areaid,cname,orderid) values (319,28,'博尔塔拉蒙古自治州',353)
	insert into city(id,areaid,cname,orderid) values (320,28,'昌吉回族自治州',354)
	insert into city(id,areaid,cname,orderid) values (321,28,'哈密',355)
	insert into city(id,areaid,cname,orderid) values (322,28,'和田',356)
	insert into city(id,areaid,cname,orderid) values (323,28,'喀什',357)
	insert into city(id,areaid,cname,orderid) values (324,28,'克拉玛依',358)
	insert into city(id,areaid,cname,orderid) values (325,28,'克孜勒苏柯尔克孜自治州',359)
	insert into city(id,areaid,cname,orderid) values (326,28,'石河子',360)
	insert into city(id,areaid,cname,orderid) values (327,28,'图木舒克',361)
	insert into city(id,areaid,cname,orderid) values (328,28,'吐鲁番',362)
	insert into city(id,areaid,cname,orderid) values (329,28,'乌鲁木齐',363)
	insert into city(id,areaid,cname,orderid) values (330,28,'五家渠',364)
	insert into city(id,areaid,cname,orderid) values (331,28,'伊犁哈萨克自治州',365)
	insert into city(id,areaid,cname,orderid) values (332,24,'保山',366)
	insert into city(id,areaid,cname,orderid) values (333,24,'楚雄彝族自治州',367)
	insert into city(id,areaid,cname,orderid) values (334,24,'大理白族自治州',368)
	insert into city(id,areaid,cname,orderid) values (335,24,'德宏傣族景颇族自治州',369)
	insert into city(id,areaid,cname,orderid) values (336,24,'迪庆藏族自治州',370)
	insert into city(id,areaid,cname,orderid) values (337,24,'红河哈尼族彝族自治州',371)
	insert into city(id,areaid,cname,orderid) values (338,24,'昆明',372)
	insert into city(id,areaid,cname,orderid) values (339,24,'丽江',373)
	insert into city(id,areaid,cname,orderid) values (340,24,'临沧',374)
	insert into city(id,areaid,cname,orderid) values (341,24,'怒江傈傈族自治州',375)
	insert into city(id,areaid,cname,orderid) values (342,24,'曲靖',376)
	insert into city(id,areaid,cname,orderid) values (343,24,'普洱',377)
	insert into city(id,areaid,cname,orderid) values (344,24,'文山壮族苗族自治州',378)
	insert into city(id,areaid,cname,orderid) values (345,24,'西双版纳傣族自治州',379)
	insert into city(id,areaid,cname,orderid) values (346,24,'玉溪',380)
	insert into city(id,areaid,cname,orderid) values (347,24,'昭通',381)
	insert into city(id,areaid,cname,orderid) values (348,18,'杭州',382)
	insert into city(id,areaid,cname,orderid) values (349,18,'湖州',383)
	insert into city(id,areaid,cname,orderid) values (350,18,'嘉兴',384)
	insert into city(id,areaid,cname,orderid) values (351,18,'金华',385)
	insert into city(id,areaid,cname,orderid) values (352,18,'丽水',386)
	insert into city(id,areaid,cname,orderid) values (353,18,'宁波',387)
	insert into city(id,areaid,cname,orderid) values (354,18,'绍兴',388)
	insert into city(id,areaid,cname,orderid) values (355,18,'台州',389)
	insert into city(id,areaid,cname,orderid) values (356,18,'温州',390)
	insert into city(id,areaid,cname,orderid) values (357,18,'舟山',391)
	insert into city(id,areaid,cname,orderid) values (358,18,'衢州',392)
	insert into city(id,areaid,cname,orderid) values (359,2,'重庆',393)
	insert into city(id,areaid,cname,orderid) values (360,33,'香港',394)
	insert into city(id,areaid,cname,orderid) values (361,34,'澳门',395)
	insert into city(id,areaid,cname,orderid) values (362,35,'台湾',396)
	insert into city(id,areaid,cname,orderid) values (363,4,'东兴',397)
	insert INTO city(id,areaid,cname,orderid) values (364,24,'大理',398)
	insert into city(id,areaid,cname,orderid) values (365,30,'兰州',399)
	insert into city(id,areaid,cname,orderid) values (366,1,'资中',402)
	insert into city(id,areaid,cname,orderid) values (367,6,'云霄',405)
	insert into city(id,areaid,cname,orderid) values (372,1,'阿坝藏族羌族自治州',408)
	SET IDENTITY_INSERT city OFF
END



/****** 对象:  Table [dbo].[CodeConfig]    脚本日期: 05/05/2010 14:47:06 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CodeConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CodeConfig](
		[Billtype] [numeric](4, 0) NOT NULL,
		[Code1] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code1]  DEFAULT (''),
		[Code2] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code2]  DEFAULT (''),
		[Code3] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code3]  DEFAULT (''),
		[Code4] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code4]  DEFAULT (''),
		[Code5] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code5]  DEFAULT (''),
		[Code6] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code6]  DEFAULT (''),
		[Code7] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code7]  DEFAULT (''),
		[Code8] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code8]  DEFAULT (''),
		[Code9] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code9]  DEFAULT (''),
		[Code10] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code10]  DEFAULT (''),
		[Code11] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code11]  DEFAULT (''),
		[Code12] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code12]  DEFAULT (''),
		[EtypeID] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_EtypeID]  DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF not EXISTS(select * from syscolumns where id = object_id(N'[dbo].[CodeConfig]') and  name = 'Code13')
BEGIN
ALTER TABLE CodeConfig ADD [Code13] VARCHAR(200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_Code13]  DEFAULT ('')
END
GO

IF not EXISTS(select * from syscolumns where id = object_id(N'[dbo].[CodeConfig]') and  name = 'CodeFlowset')
BEGIN
ALTER TABLE CodeConfig ADD [CodeFlowset] VARCHAR(200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CodeConfig_CodeFlowset]  DEFAULT (0)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ColumnsField]    脚本日期: 01/09/2011 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ColumnsField]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ColumnsField](
		[ID]		DECIMAL(18,0) Identity(1,1),
		[DataField] VARCHAR(200)  NOT NULL,
		[Fullname]	VARCHAR(200),
		[ShowOrder]	DECIMAL(18,0) DEFAULT (0),
		[ReportName]		VARCHAR(100)
	)
END
DELETE FROM ColumnsField

--销售订单查询
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('orderqty','订货数量',1,'saleOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('locknumber','锁库数量',2,'saleOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billoverNumber','中止数量',3,'saleOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachqty','已发货数量',4,'saleOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billovertotal','中止金额',5,'saleOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ordermoney','订货金额',6,'saleOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachmoney','已发货金额',7,'saleOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ordermoneybb','订金（本币/原币）',8,'saleOrderBill')

--采购订单查询
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('orderqty','订货数量',1,'buyOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('locknumber','锁库数量',2,'buyOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billoverNumber','中止数量',3,'buyOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachqty','已发货数量',4,'buyOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billovertotal','中止金额',5,'buyOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ordermoney','订货金额',6,'buyOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachmoney','已发货金额',7,'buyOrderBill')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ordermoneybb','订金（本币/原币）',8,'buyOrderBill')


--未完成采购订单查询
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ordermqty','订货采购单位数量',1,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('orderqty','订货基本单位数量',2,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachmqty','已发货销售单位数量',3,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachqty','已发货基本单位数量',4,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhmqty','未发货销售单位数量',5,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhqty','未发货基本单位数量',6,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','采购单价',7,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('discountprice','折后单价',8,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxprice','含税单价',9,'buyOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxtotal','价税合计',10,'buyOrderBillNotComplete')

--未完成销售订单查询
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ordermqty','订货销售单位数量',1,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('orderqty','订货基本单位数量',2,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachmqty','已发货销售单位数量',3,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachqty','已发货基本单位数量',4,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhmqty','未发货销售单位数量',5,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhqty','未发货基本单位数量',6,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','销售单价',7,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('discountprice','折后单价',8,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxprice','含税单价',9,'saleOrderBillNotComplete')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxtotal','价税合计',10,'saleOrderBillNotComplete')

--销售订单报警列表
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalqty','订货数量',1,'saleOrderBillAlarm')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachqty','已发货数量',2,'saleOrderBillAlarm')

--采购订单报警列表
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalqty','订货数量',1,'buyOrderBillAlarm')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachqty','已发货数量',2,'buyOrderBillAlarm')

--销售订单汇总表
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','订货数量',1,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('assistunit1','订货辅助数量',2,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachqty','发货数量',3,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('assistunit2','发货辅助数量',4,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('notqty','未发货数量',5,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('assistunit3','未发货辅助数量',6,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('orderqty','补订货数量',7,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('assistunit4','补订货辅助数量',8,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('overqty','中止数量',9,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('assistunit5','中止辅助数量',10,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('pricew','订货平均单价',11,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachpricpe','发货单价',12,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('notpriced','未发货单价',13,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('orderpricet','补订货单价',14,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('overproice','中止单价',15,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total','订货金额',16,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachtotal','发货金额',17,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('nottotal','未发货金额',18,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ordertotal','补订货金额',19,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('overtotal','中止金额',20,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxtotal','订货价税合计',21,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('reachtaxtotal','发货价税合计',22,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('nottaxtotal','未发货价税合计',23,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ordertaxtotal','补订货价税合计',24,'saleOrderBillSum')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('overtaxtotal','中止价税合计',25,'saleOrderBillSum')

--销售订单分组明细表
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','订货数量',1,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('fhqty','发货数量',2,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhqty','未发货数量',3,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('bdhqty','补订货数量',4,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('yzzqty','中止数量',5,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total','订货金额',6,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('fhtotal','发货金额',7,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhtotal','未发货金额',8,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('bdhtotal','补订货金额',9,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('yzztotal','中止金额',10,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxtotal','订货价税合计',11,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('fhtaxtotal','发货价税合计',12,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhtaxtotal','未发货价税合计',13,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('bdhtaxtotal','补订货价税合计',14,'saleOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('yzztaxtotal','中止价税合计',15,'saleOrderBillGroup')

--采购订单分组明细表
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','订货数量',1,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('fhqty','发货数量',2,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhqty','未发货数量',3,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('bdhqty','补订货数量',4,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('yzzqty','中止数量',5,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total','订货金额',6,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('fhtotal','发货金额',7,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhtotal','未发货金额',8,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('bdhtotal','补订货金额',9,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('yzztotal','中止金额',10,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxtotal','订货价税合计',11,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('fhtaxtotal','发货价税合计',12,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wfhtaxtotal','未发货价税合计',13,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('bdhtaxtotal','补订货价税合计',14,'buyOrderBillGroup')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('yzztaxtotal','中止价税合计',15,'buyOrderBillGroup')

--销售订单采购查询
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','订货数量',1,'saleOrderBillBuy')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('salereachqty','已销售发货数量',1,'saleOrderBillBuy')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('buyqty','已采购订货数量',1,'saleOrderBillBuy')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('buyreachqty','已采购入库数量',1,'saleOrderBillBuy')


--销售统计/排行
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sum_qty','销售数量',1,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('salecount','销售单数',2,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('salebackcount','退货单数',3,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','单价',4,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('discountprice','折前单价',5,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sum_discounttotal','折前金额',6,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sum_total','折后金额',7,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('unitrelationship','单位关系',8,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sum_taxTotal','价税合计',9,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxge','税额',10,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('costprice','成本单价',11,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sum_costTotal','成本金额',12,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('pricetotal','价保金额',13,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('advantagetotal','返利金额',14,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('preferencemoney','抹零金额',15,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('zeropriceqty','0单价数量',16,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty_qz','销量权重(%)',17,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total_qz','金额权重(%)',18,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('maoli_qz','利润权重(%)',19,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('pjlirun','平均利润',20,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sharefee','费用分摊金额',21,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('maoli','毛利',22,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('maolilu','毛利率(%)',23,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('LockNumber','锁定基本数量',24,'saleOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('discount','扣率',25,'saleOrder')


INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','销售数量',1,'saleReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('fzsl','辅助数量相关',2,'saleReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','销售均价',3,'saleReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total','折后金额',4,'saleReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('unitrelationship','单位关系',5,'saleReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxtotal','价税合计',6,'saleReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('discount','扣率',7,'saleReport')


INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','数量',1,'saleorderReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','单价',3,'saleorderReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total',' 金额',4,'saleorderReport')

INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sum_qty','采购数量',1,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','折后单价',2,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sum_total','折后金额',3,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sum_taxtotal','价税合计',4,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('unitrelationship','单位关系',5,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxge','税额',6,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('pricetotal','获得价保金额',7,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('advantagetotal','获利金额',8,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('zeropriceqty','0单价数量',9,'buyOrder')
--9.5++
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('tax','税率',10,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxprice','含税单价',11,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('saleprice','采购单价',12,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('saletotal','采购金额',13,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('discountge','折扣额',14,'buyOrder')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('discount','扣率',15,'buyOrder')

INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','采购数量',1,'buyReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','采购均价',2,'buyReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total','采购金额',3,'buyReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxtotal','价税合计',4,'buyReport')

INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','账面库存',1,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('kunitrate','库存状况',2,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('dwgx','单位关系',3,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('virtualqty','虚拟库存',4,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('jj','借进',5,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('jc','借出',6,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sjczkc','实际存在库存',7,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('rkqty','草稿入库',8,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ckqty','草稿出库',9,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('kfhdqty','可发货数量',10,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ycgdhqty','已采购订货数量',11,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('yxsdhqty','已销售订货数量',12,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('kxsdhqty','可销售订货数量',13,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','成本均价',14,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total','成本金额',15,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('stwjs','受托未结算',16,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('wtwjs','委托未结算',17,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('sjyykc','实际拥有库存',18,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('saleqty','已销售数量',19,'stockStatus')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('btypeid','供货商',20,'stockStatus')--供货商
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('locknumber','锁定基本数量',21,'stockStatus')

--INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('dwgx','单位关系',1,'stockDistributing')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('fzsl','辅助数量',3,'stockDistributing')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','成本均价',4,'stockDistributing')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total','成本金额',5,'stockDistributing')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','账面库存',6,'stockDistributing')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('nqty','浮动数量',7,'stockDistributing')

INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billdate','单据日期',1,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billcode','单据编号',2,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('auditedname','单据审核状态',3,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billtype','单据类型',4,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalqty','合计数量',5,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ntotalmoney','合计金额',6,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ntotalinmoney','收付款金额',7,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('checkename','制单人',8,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('checktime','制单时间',9,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('updateefullname','修改人',10,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('lastupdatetime','修改时间',11,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('printcount','打印次数',12,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',13,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',14,'draftList')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('npreferencemoney','原币优惠/抹零金额',15,'draftList')

INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billdate','单据日期',1,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billcode','单据编号',2,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('billtype','单据类型',3,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalqty','合计数量',4,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ntotalmoney','合计金额',5,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('ntotalinmoney','收付款金额',6,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('cwcheck','财务审核',7,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('checkename','制单人',8,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('checktime','制单时间',9,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('updateefullname','修改人',10,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('lastupdatetime','修改时间',11,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('postname','过账人',12,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('posttime','过账时间',13,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('printcount','打印次数',14,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',15,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',16,'indexAudit')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('npreferencemoney','原币优惠/抹零金额',17,'indexAudit')

--发出商品--开始
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('qty','销售数量',1,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('price','单价',2,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('total','折后金额',3,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxtotal','价税合计',4,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('costprice','成本单价',5,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('costtotal','成本金额',6,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('invoiceqty','已开票数量',7,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('invoicemoneyex','已开票销售金额',8,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('invoicemoney','已开票价税合计',9,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('invoicecosttotal','已开票成本金额',10,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('uninvoiceqty','未开票数量',11,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('giftqty','单据赠品数量',12,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('tax','税率',13,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('taxmoney','税额',14,'sendGoodsReport')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('discount','扣率',15,'sendGoodsReport')

--发出商品--结束

--INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('unitrelationship','单位关系',1,'virtualstockstaus')
--INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('virtualjj','借进',1,'virtualstockstaus')
--INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('virtualjc','借出',2,'virtualstockstaus')
--INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('virtualrkqty','草稿入库',3,'virtualstockstaus')
--INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('virtualckqty','草稿出库',4,'virtualstockstaus')


---------------------------------------------单据表头控制BEGIN   2013-11-20 by：duguolei -------------------------------------------
--销售订单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('carrierUnit','承运单位',1,'saleOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('itemNumber','物件数量',2,'saleOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('modesOfPacking','包装方式',3,'saleOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('trackNumber','运单号',4,'saleOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',5,'saleOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',6,'saleOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('barCodeInput','条形码录入',7,'saleOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('earnestMoney','订金',8,'saleOrderHead')

--销售出库单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('paymentTerm','收款期限',1,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('trackNumber','运单号',2,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('carrierUnit','承运单位',3,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('itemNumber','物件数量',4,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('modesOfPacking','包装方式',5,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',6,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',7,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('barCodeOfGoods','条码对货',8,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('barCodeInput','条形码录入',9,'saleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('costOfSales','按成本价销售',10,'saleOutStockBillHead')


--采购订单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('carrierUnit','承运单位',1,'buyOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('itemNumber','物件数量',2,'buyOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('modesOfPacking','包装方式',3,'buyOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('trackNumber','运单号',4,'buyOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',5,'buyOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',6,'buyOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('barCodeInput','条形码录入',7,'buyOrderHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('earnestMoney','订金',8,'buyOrderHead')


--采购入库单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('prompt','付款期限',1,'buyInStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',2,'buyInStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',3,'buyInStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('barCodeOfGoods','条码对货',4,'buyInStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('barCodeInput','条形码录入',5,'buyInStockBillHead')


--生产拆装单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',1,'productHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',2,'productHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('outStockBarCode','出库条码',3,'productHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('inStockBarCode','入库条码',4,'productHead')


--维修接件单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contacts','联系人',1,'recBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactNumber','联系电话',2,'recBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactAddress','联系地址',3,'recBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',4,'recBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',5,'recBillHead')


--维修单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('seriesNumber','序列号',1,'repairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('pickNumber','接件单号',2,'repairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('purchaseDate','购买日期',3,'repairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('troubleDescriptions ','故障描述',4,'repairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('repairer','维修人',5,'repairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',6,'repairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',7,'repairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('outStockBarCode','出库条码',8,'repairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('inStockBarCode','入库条码',9,'repairBillHead')


--维修取件单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contacts','联系人',1,'getBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactNumber','联系电话',2,'getBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactAddress','联系地址',3,'getBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',4,'getBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',5,'getBillHead')


--报修单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contacts','联系人',1,'reportBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactNumber','联系电话',2,'reportBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactAddress','联系电话',3,'reportBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',4,'reportBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',5,'reportBillHead')


--上门维修单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('seriesNumberRemark','序列号备注',1,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('repairsNumber','报修单号',2,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('purchaseDate','购买日期',3,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('troubleDescriptions','故障描述',4,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('repairer','维修人',5,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contacts','联系人',6,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactNumber','联系电话',7,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactAddress','联系地址',8,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',9,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',10,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('outStockBarCode','出库条码',11,'getBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('inStockBarCode','入库条码',12,'getBillInHead')


--整机更换单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contacts','联系人',1,'exchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactNumber','联系电话',2,'exchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactAddress','联系地址',3,'exchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',4,'exchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',5,'exchangeBillHead')


--期初未结算销售出库单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('paymentTerm','收款期限',1,'beginPeriodUnSaleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('trackNumber','运单号',2,'beginPeriodUnSaleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('carrierUnit','承运单位',3,'beginPeriodUnSaleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('itemNumber','物件数量',4,'beginPeriodUnSaleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('modesOfPacking','包装方式',5,'beginPeriodUnSaleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',6,'beginPeriodUnSaleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',7,'beginPeriodUnSaleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('barCodeInput','条形码录入',8,'beginPeriodUnSaleOutStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalinmoney','已结算原币金额',9,'beginPeriodUnSaleOutStockBillHead')


--期初未结算销售换货单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',1,'beginPeriodUnSaleExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',2,'beginPeriodUnSaleExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('outStockBarCode','出库条码',3,'beginPeriodUnSaleExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('inStockBarCode','入库条码',4,'beginPeriodUnSaleExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalinmoney','已结算原币金额',5,'beginPeriodUnSaleExchangeBillHead')


--期初未结算采购入库单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('prompt','付款期限',1,'beginPeriodUnBuyInStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',2,'beginPeriodUnBuyInStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',3,'beginPeriodUnBuyInStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('barCodeInput','条形码录入',4,'beginPeriodUnBuyInStockBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalinmoney','已结算原币金额',5,'beginPeriodUnBuyInStockBillHead')


--期初未结算采购换货单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',1,'beginPeriodUnBuyExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',2,'beginPeriodUnBuyExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('outStockBarCode','出库条码',3,'beginPeriodUnBuyExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('inStockBarCode','入库条码',4,'beginPeriodUnBuyExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalinmoney','已结算原币金额',5,'beginPeriodUnBuyExchangeBillHead')


--期初维修取件单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contacts','联系人',1,'beginPeriodRepairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactNumber','联系电话',2,'beginPeriodRepairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactAddress','联系地址',3,'beginPeriodRepairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',4,'beginPeriodRepairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',5,'beginPeriodRepairBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalinmoney','已结算原币金额',6,'beginPeriodRepairBillHead')


--期初整机更换单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contacts','联系人',1,'beginPeriodExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactNumber','联系电话',2,'beginPeriodExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactAddress','联系地址',3,'beginPeriodExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',4,'beginPeriodExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',5,'beginPeriodExchangeBillHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalinmoney','已结算原币金额',6,'beginPeriodExchangeBillHead')


--期初上门维修单
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('seriesNumberRemark','序列号备注',1,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('repairsNumber','报修单号',2,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('purchaseDate','购买日期',3,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('troubleDescriptions','故障描述',4,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('repairer','维修人',5,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contacts','联系人',6,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactNumber','联系电话',7,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('contactAddress','联系地址',8,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('outStock','出库仓库',9,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('inStock','入库仓库',10,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('explain','说明',11,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('comment','摘要',12,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('outStockBarCode','出库条码',13,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('inStockBarCode','入库条码',14,'beginPeriodGetBillInHead')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('totalinmoney','已结算原币金额',15,'beginPeriodGetBillInHead')

--总账管理
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('voucherQuery','辅助核算',1,'voucherQuery')
INSERT INTO ColumnsField(DataField,Fullname,ShowOrder,ReportName) values('tellerQuery','辅助核算',1,'tellerQuery')

---------------------------------------------单据表头控制END ------------------------------------------------------







------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ProduceModelIndex]    脚本日期: 05/05/2010 14:48:52 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CombinationProductDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CombinationProductDetail](
		id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,--明细id
		[CombinationProductID] [int] , --主表id
		[Ptypeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--商品ID
		[Unit]    INT ,--单位
		[Qty]     NUMERIC(18,4),--数量
		[Price]   NUMERIC(18,4) ,--单价
		[Remark] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--备注
		[ItemId]  int ,--自由项
		[Standard] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--规格
		[Barcode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL--条码
	) ON [PRIMARY]
END
GO
   IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'CombinationProductDetail',N'U') AND Name='Total')
   BEGIN
		ALTER TABLE CombinationProductDetail
		ADD Total NUMERIC(24,10)
   END
   
   IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CombinationProductDetail' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CombinationProductDetail 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
           
    IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CombinationProductDetail' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CombinationProductDetail 
	ALTER COLUMN Price NUMERIC(24,10)
    END
GO



/****** 对象:  Table [dbo].[ProduceModelIndex]    脚本日期: 05/05/2010 14:48:52 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CombinationProductIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CombinationProductIndex](
		[CombinationProductID]  [int] IDENTITY(1,1) PRIMARY KEY NOT NULL, --id
		[CombinationProductPtypeId] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--组合品商品ID
		[CombinationProductUsercode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--编码
		[CombinationProductFullName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--名称
		[Etypeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--经手人
		[Dtypeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--部门
		[Barcode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--条码
		[Summary] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--摘要
		[Standard] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--规格
		[ModelNumber] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,--型号
		[Price] NUMERIC(18,4) ,--单价
		[CombinationProductUnit] INT,--单位
		IsStop    INT,	--是否启用  1为启用  0为没启用
		IsCheck   INT   --是否审核  1为审核	 0为没审核	
	) ON [PRIMARY]


END
GO
	IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CombinationProductIndex' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CombinationProductIndex 
	ALTER COLUMN Price NUMERIC(24,10)
    END
           
GO




/****** 对象:  Table [dbo].[CommissionBill]    脚本日期: 05/05/2010 14:47:07 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CommissionBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[Type] [int] NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_Total]  DEFAULT (0),
		[Discount] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_Jobnumber]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_GoodsNo]  DEFAULT (0),
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionBill_Comment]  DEFAULT (''),
		[Goodsno] [int] NULL CONSTRAINT [DF_CommissionBill_Goodsno_1]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_Total_1]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_CommissionBill_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_CommissionBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_CommissionBill_GoodsOrder_1]  DEFAULT ('-1'),
		[OldID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionBill_OldID]  DEFAULT (''),
		[OldBillNumberID] [numeric](18, 0) NULL CONSTRAINT [DF_CommissionBill_OldBillNumberID]  DEFAULT ('0'),
		[BackQty] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_BackQty]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__Commissio__Compl__1AED04F0]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_CommissionBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_CommissionBill_HandZeroCost]  DEFAULT (0),
		[BQTY] [numeric](18, 4) NULL DEFAULT (0),
		[OldBillid] [numeric](18, 0) NULL DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_CommissionBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		TaxMoney             numeric(22,10)    NOT NULL Default(0),
		NSalePrice           numeric(22,10)      NOT NULL Default(0),
		NSaleTotal           numeric(22,10)      NOT NULL Default(0),
		NDiscountPrice       numeric(22,10)      NOT NULL Default(0),
		NTotal               numeric(22,10)      NOT NULL Default(0),
		NTaxPrice            numeric(22,10)      NOT NULL Default(0),
		NTaxTotal            numeric(22,10)      NOT NULL Default(0),
		NTaxMoney            numeric(22,10)      NOT NULL Default(0),
		UnitID               int                NOT NULL Default(0),
		NUnitID              int                NOT NULL Default(0),
		NQty                 numeric(22,10)     NOT NULL Default(0),
		UnitRate             numeric(22,10)     NOT NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NOT NULL Default(0),
		MQty                 numeric(22,10)     NOT NULL Default(0),
		MUnitRate            numeric(22,10)     NOT NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NOT NULL Default(0),
		MDiscountPrice       numeric(22,10)     NOT NULL Default(0),
		MTaxPrice            numeric(22,10)     NOT NULL Default(0),
		CurMSalePrice        numeric(22,10)     NOT NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NOT NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NOT NULL Default(0),
		CargoID              int               NOT NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,ShowOrder INT DEFAULT(0)
		,ClearQty NUMERIC(24,10)	--解锁数量
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0)--物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0)--拣货数量
		,InflowQty NUMERIC(24,10) NULL DEFAULT(0)--入库数量
		,InFactQty NUMERIC(24,10) NULL DEFAULT(0)
		,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		PriceSource VARCHAR(200)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.CommissionBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.CommissionBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.CommissionBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.CommissionBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.CommissionBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.CommissionBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.CommissionBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.CommissionBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE CommissionBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE CommissionBill SET PickedQty=0 WHERE PickedQty IS NULL
GO
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.CommissionBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.CommissionBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND Name='ClearQty')
BEGIN
	ALTER TABLE dbo.CommissionBill
	ADD ClearQty NUMERIC(24,10) DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionBill]') and name = 'KTypeID' )
BEGIN
	ALTER TABLE dbo.CommissionBill ADD
		KTypeID varchar(50) NULL
END
GO

UPDATE CommissionBill
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE CommissionBill.BillNumberID=b.BillNumberID AND CommissionBill.KTypeID IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE CommissionBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE CommissionBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE CommissionBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE CommissionBill ADD TaxMoney   numeric(22,10)  NOT NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD NSalePrice   numeric(22,10)  NOT NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE CommissionBill ADD NSaleTotal   numeric(22,10)  NOT NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD NDiscountPrice   numeric(22,10)  NOT NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE CommissionBill ADD NTotal   numeric(22,10)  NOT NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD NTaxPrice   numeric(22,10)  NOT NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE CommissionBill ADD NTaxTotal   numeric(22,10)  NOT NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE CommissionBill ADD NTaxMoney   numeric(22,10)  NOT NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE CommissionBill ADD UnitID  INT  NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE CommissionBill ADD NUnitID INT  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE CommissionBill ADD NQty   numeric(22,10)    NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE CommissionBill ADD UnitRate   numeric(22,10)    NOT NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE CommissionBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE CommissionBill ADD MUnitID  INT  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE CommissionBill ADD MQty   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE CommissionBill ADD MUnitRate   numeric(22,10)  NOT NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE CommissionBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD MSalePrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD MDiscountPrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD MTaxPrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD CurMSalePrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD CurMDiscountPrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD CurMTaxPrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE CommissionBill ADD CargoID   INT  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE CommissionBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE CommissionBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE CommissionBill ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE CommissionBill ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='nInvoiceMoney'
)
BEGIN
		ALTER TABLE CommissionBill ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO			

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='ReferPrice'
)
BEGIN
		ALTER TABLE CommissionBill ADD ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0) --参考成本
END
GO			

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='PriceStyle'
)
BEGIN
		ALTER TABLE CommissionBill ADD PriceStyle INT NOT NULL DEFAULT(0) --价格类型
END
GO	
-- 添加物流运输 已发运数量
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE CommissionBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0) 
END
GO	
---
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('CommissionBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table CommissionBill drop constraint '+@dfname);
		
	ALTER TABLE CommissionBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE CommissionBill ADD CONSTRAINT DF_CommissionBill_Serial DEFAULT('') FOR Serial

END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE CommissionBill ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE CommissionBill SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBill',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE CommissionBill ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE CommissionBill SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='CommissionBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CommissionBill]') AND name = N'IX_CommissionBill_BillNumberId')
--DROP INDEX [dbo].[CommissionBill].[IX_CommissionBill_BillNumberId]
--GO

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CommissionBill]') AND name = N'IX_CommissionBill_PTypeID')
--DROP INDEX [dbo].[CommissionBill].[IX_CommissionBill_PTypeID]
--GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONBILL') AND name = 'CIX_COMMISSIONBILL_BillNumberID')
--DROP INDEX CIX_COMMISSIONBILL_BillNumberID ON COMMISSIONBILL 
CREATE CLUSTERED INDEX CIX_COMMISSIONBILL_BillNumberID ON COMMISSIONBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONBILL') AND name = 'NCIX_COMMISSIONBILL_Ptypeid')
--DROP INDEX NCIX_COMMISSIONBILL_Ptypeid ON COMMISSIONBILL 
CREATE NONCLUSTERED INDEX NCIX_COMMISSIONBILL_Ptypeid ON COMMISSIONBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONBILL') AND name = 'NCIX_COMMISSIONBILL_Orderid')
--DROP INDEX NCIX_COMMISSIONBILL_Orderid ON COMMISSIONBILL 
CREATE NONCLUSTERED INDEX NCIX_COMMISSIONBILL_Orderid ON COMMISSIONBILL(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONBILL') AND name = 'NCIX_COMMISSIONBILL_Ktypeid')
--DROP INDEX NCIX_COMMISSIONBILL_Ktypeid ON COMMISSIONBILL 
CREATE NONCLUSTERED INDEX NCIX_COMMISSIONBILL_Ktypeid ON COMMISSIONBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONBILL') AND name = 'NCIX_COMMISSIONBILL_Stypeid')
--DROP INDEX NCIX_COMMISSIONBILL_Stypeid ON COMMISSIONBILL 
CREATE NONCLUSTERED INDEX NCIX_COMMISSIONBILL_Stypeid ON COMMISSIONBILL(Stypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONBILL') AND name = 'NCIX_COMMISSIONBILL_SalePrice')
DROP INDEX NCIX_COMMISSIONBILL_SalePrice ON COMMISSIONBILL     
                            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                      
CREATE NONCLUSTERED INDEX NCIX_COMMISSIONBILL_SalePrice ON COMMISSIONBILL(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONBILL') AND name = 'NCIX_COMMISSIONBILL_Discount')
DROP INDEX NCIX_COMMISSIONBILL_Discount ON COMMISSIONBILL                
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                               
CREATE NONCLUSTERED INDEX NCIX_COMMISSIONBILL_Discount ON COMMISSIONBILL(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONBILL') AND name = 'NCIX_COMMISSIONBILL_Tax')
DROP INDEX NCIX_COMMISSIONBILL_Tax ON COMMISSIONBILL 
                                  
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                  
CREATE NONCLUSTERED INDEX NCIX_COMMISSIONBILL_Tax ON COMMISSIONBILL(Tax) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='BQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN BQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE CommissionBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成单
--2014--04-07  wg
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionBillNew
(
	BillNumberId			NUMERIC(18,0) IDENTITY(1,1),
	BillCode				VARCHAR(200) NOT NULL,   --单据编号 
	BillDate				DATETIME NOT NULL,		 --单据日期 
	CommissionStart			DATETIME NULL,			 --提成开始
	CommissionEnd			DATETIME NULL,			 --提成结束
	CommissionSchemeID		NUMERIC(18,0) NOT NULL DEFAULT(0),  --提成方案ID
	CommissionType			INT DEFAULT(0),			 --提成类型 0=手动做单 1=规则提成  2= 参照计划提成
	Checke					VARCHAR(50) NOT NULL,				--制单人
	Checker					VARCHAR(50) NOT NULL DEFAULT(''),	--审核人
	CheckeTime				DATETIME NOT NULL,		--制单时间
	CheckerTime				DATETIME NULL,		    --审核时间
	Explain					VARCHAR(256) NOT NULL DEFAULT(''),	--说明
	Comment					VARCHAR(256) NOT NULL DEFAULT(''),	--摘要
	IsAuto					INT	NOT NULL,						--自动生成  0=手动 1=自动
	BillState				INT NOT NULL						--单据状态  1=无需审核  2=审核通过 3=待审核 4=审核未通过 已过账的状态看ifcheck字段
)

END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'CommissionStart')
BEGIN
	 ALTER TABLE CommissionBillNew ADD CommissionStart DATETIME NULL 
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'CommissionEnd')
BEGIN
	 ALTER TABLE CommissionBillNew ADD CommissionEnd DATETIME NULL 
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'ifcheck')
BEGIN
	 ALTER TABLE CommissionBillNew ADD ifcheck CHAR(1) DEFAULT('f')
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'draft')
BEGIN
	 ALTER TABLE CommissionBillNew ADD draft BIT DEFAULT(1)
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'StypeID')
BEGIN
	 ALTER TABLE CommissionBillNew ADD StypeID VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'RedWord')
BEGIN
	 ALTER TABLE CommissionBillNew ADD RedWord INT DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'Poster')
BEGIN
	 ALTER TABLE CommissionBillNew ADD Poster VARCHAR(50) NULL
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'PostTime')
BEGIN
	 ALTER TABLE CommissionBillNew ADD PostTime DATETIME NULL
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'CommissionTotal')
BEGIN
	 ALTER TABLE CommissionBillNew ADD CommissionTotal NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'Total')
BEGIN
	 ALTER TABLE CommissionBillNew ADD Total NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'qty')
BEGIN
	 ALTER TABLE CommissionBillNew ADD qty NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'FChecker')
BEGIN
	 ALTER TABLE CommissionBillNew ADD FChecker VARCHAR(50) NOT NULL DEFAULT('')	--反审核人
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'FCheckerTime')
BEGIN
	 ALTER TABLE CommissionBillNew ADD FCheckerTime DATETIME NULL --反审核时间
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'FPoster')
BEGIN
	 ALTER TABLE CommissionBillNew ADD FPoster VARCHAR(50) NULL --反过账人
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'FPostTime')
BEGIN
	 ALTER TABLE CommissionBillNew ADD FPostTime DATETIME NULL --反过账时间
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'CommissionType')
BEGIN
	 ALTER TABLE CommissionBillNew ADD CommissionType INT DEFAULT(0) --选择方案提成时 是计算的规则，还是参照计划
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'atid')
BEGIN
	 ALTER TABLE CommissionBillNew ADD atid INT DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNew]') AND  name = 'billtype')
BEGIN
	 ALTER TABLE CommissionBillNew ADD billtype numeric(4,0)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBillNew' AND a.Name='CommissionTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBillNew 
	ALTER COLUMN CommissionTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBillNew' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBillNew 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBillNew' AND a.Name='qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBillNew 
	ALTER COLUMN qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成单--明细
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionBillNewDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionBillNewDetail
(
	BillNumberId			NUMERIC(18,0) NOT NULL,
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	EtypeID					VARCHAR(50),				--职员
	DtypeID					VARCHAR(50),				--部门
	Qty						NUMERIC(22,10) NOT NULL DEFAULT(0) ,--数量
	Total					NUMERIC(22,10) NOT NULL DEFAULT(0) ,--金额
	CommissionTotal			NUMERIC(22,10) NOT NULL DEFAULT(0),--提成金额
	Comment					VARCHAR(256)	--备注
	,ShowOrder INT DEFAULT(0)
)

END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'CommissionBillNewDetail',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.CommissionBillNewDetail
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE CommissionBillNewDetail SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionBillNewDetail]') and  name = 'CommissionTotal')
BEGIN
	 ALTER TABLE CommissionBillNewDetail ADD CommissionTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionBillNewDetail]') AND  name = 'DtypeID')
BEGIN
	 ALTER TABLE CommissionBillNewDetail ADD DtypeID VARCHAR(50) NOT NULL 
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBillNewDetail' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBillNewDetail 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBillNewDetail' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBillNewDetail 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionBillNewDetail' AND a.Name='CommissionTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionBillNewDetail 
	ALTER COLUMN CommissionTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成规则表
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionRule]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionRule
(
	BillNumberId			NUMERIC(18,0) IDENTITY(1,1),
	BillCode				VARCHAR(200) NOT NULL,   --单据编号
	FullName				VARCHAR(200) NOT NULL DEFAULT(''),   --单据名称
	BillDate				DATETIME NOT NULL,		 --单据日期 
	RuleStart				DATETIME NOT NULL,		 --规则开始
	RuleEnd					DATETIME NOT NULL,		 --规则结束
	CommissionStandard		INT NOT NULL,			 --提成基准  1=折后金额 2=价税合计 3=销售数量 4=销售毛利 5=回款额 6=维修费7=获利金额
	IsUseEtypeCommission	INT NOT NULL,			 --是否使用职员提成比例 1=勾选
	ECommissionType			INT NOT NULL,			 --提成人类型  1=业务员   2=上级参与提成
	CommissionStyle			INT NOT NULL,			 --提成方式    1=单一提成 2=区间提成
	Checke					VARCHAR(50) NOT NULL,				--制单人
	Checker					VARCHAR(50) NOT NULL DEFAULT(''),	--审核人
	CheckeTime				DATETIME NOT NULL,		--制单时间
	CheckerTime				DATETIME NULL,		    --审核时间
	Comment					VARCHAR(256) NOT NULL DEFAULT(''),	--摘要
	BillState				INT NOT NULL,						--单据状态  1=未审核  2=审核  3=禁用
	UseState				INT NOT NULL DEFAULT(0),			--使用状态  1=未引用  2=已引用  --------3=部分完成 4=全部完成
	IsStop					INT NOT NULL DEFAULT(0),				--是否禁用  0=正常  1/2当禁用时写入单据状态 启用时写到单据状态列 起保存禁用时的状态
	SalesFlag				INT NULL,                                   --是否是促销商品 1=是促销 0=不是 
	BelowCostFlag			INT NULL,										--是否低于成本价  1=低于成本价 0=不低于成本价
	RChecker VARCHAR(50) NULL DEFAULT(''),	--反审核人
	RVaildDate DATETIME NULL				--反审核时间
)

END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionRule]') and name = 'FullName' )
BEGIN
ALTER TABLE CommissionRule ADD FullName VARCHAR(200) NOT NULL DEFAULT('')
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionRule]') and name = 'SalesFlag')
BEGIN
ALTER TABLE CommissionRule ADD SalesFlag int null
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionRule]') and name = 'BelowCostFlag' )
BEGIN
ALTER TABLE CommissionRule ADD BelowCostFlag int null
END
GO

-------------2019-09-11 9.91 增加反审核人、反审核日期---------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionRule]') and name = 'RChecker' )
BEGIN
	ALTER TABLE CommissionRule 
	ADD RChecker VARCHAR(50) NULL DEFAULT('')
END
GO
UPDATE CommissionRule SET RChecker='' WHERE RChecker IS NULL
GO


if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionRule]') and name = 'RVaildDate' )
BEGIN
	ALTER TABLE CommissionRule 
	ADD RVaildDate DATETIME NULL
END
GO
--------------------------EN--D---------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成规则--职员设置
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionRuleEtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionRuleEtype
(
	BillNumberId			NUMERIC(18,0) NOT NULL,
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	EtypeID					VARCHAR(50) NOT NULL	--业务员
)

END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成规则--提成类别取价设置
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionRuleLeader]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionRuleLeader
(
	BillNumberId			NUMERIC(18,0) NOT NULL,
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	CommissionTypeID		VARCHAR(50) NOT NULL,		--提成类别
	MinRegion				NUMERIC(18,10) NOT NULL, --下限
	MaxRegion				NUMERIC(18,10) NOT NULL, --上限
	Proportion				NUMERIC(18,10)  NULL,  --提成率
	Percentage			NUMERIC(24,10) NULL--固定提成额
)

END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionRuleLeader]') and  name = 'EtypeID')
BEGIN
	 ALTER TABLE CommissionRuleLeader ADD EtypeID VARCHAR(50) DEFAULT('')  --级别当时对应的复制人（9.4版本中由于不能修改负责人，值未写）
END
GO

ALTER TABLE CommissionRuleLeader ALTER COLUMN MinRegion NUMERIC(22,10)   NOT NULL 
ALTER TABLE CommissionRuleLeader ALTER COLUMN MaxRegion NUMERIC(22,10)   NOT NULL 
ALTER TABLE CommissionRuleLeader ALTER COLUMN Proportion NUMERIC(22,10)    NULL 

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRuleLeader' AND a.Name='MinRegion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionRuleLeader 
	ALTER COLUMN MinRegion NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRuleLeader' AND a.Name='MaxRegion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionRuleLeader 
	ALTER COLUMN MaxRegion NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRuleLeader' AND a.Name='Proportion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionRuleLeader 
	ALTER COLUMN Proportion NUMERIC(24,10)
    END
   
   IF NOT  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRuleLeader' AND a.Name='Percentage'
    )
    BEGIN
	ALTER TABLE CommissionRuleLeader ADD  Percentage NUMERIC(24,10)    NULL 
    END 
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成规则--职员--商品设置
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionRulePtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionRulePtype
(
	BillNumberId			NUMERIC(18,0) NOT NULL,
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	EtypeID					VARCHAR(50) NOT NULL,	--业务员
	PtypeID					VARCHAR(50) NOT NULL,	--商品,
	Proportion				NUMERIC(18,10) NOT NULL DEFAULT(0)	--提成率
)

END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRulePtype' AND a.Name='Proportion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionRulePtype 
	ALTER COLUMN Proportion NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成规则--职员--商品--区间设置
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionRuleRegion]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionRuleRegion
(
	BillNumberId			NUMERIC(18,0) NOT NULL,
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	EtypeID					VARCHAR(50) NOT NULL,	--业务员
	PtypeID					VARCHAR(50) NOT NULL,	--商品
	MinRegion				NUMERIC(18,4) NOT NULL, --下限
	MaxRegion				NUMERIC(18,4) NOT NULL, --上限
	Proportion				NUMERIC(18,4)  NULL,  --提成率
	Percentage			NUMERIC(24,10) NULL--固定提成额
)
END
GO


ALTER TABLE CommissionRuleRegion ALTER COLUMN MinRegion NUMERIC(22,10) NOT NULL
ALTER TABLE CommissionRuleRegion ALTER COLUMN MaxRegion NUMERIC(22,10) NOT NULL
ALTER TABLE CommissionRuleRegion ALTER COLUMN Proportion NUMERIC(22,10)  NULL

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRuleRegion' AND a.Name='MinRegion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionRuleRegion 
	ALTER COLUMN MinRegion NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRuleRegion' AND a.Name='MaxRegion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionRuleRegion 
	ALTER COLUMN MaxRegion NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRuleRegion' AND a.Name='Proportion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionRuleRegion 
	ALTER COLUMN Proportion NUMERIC(24,10)
    END
    
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionRuleRegion' AND a.Name='Percentage' 
    )
    BEGIN
	ALTER TABLE CommissionRuleRegion ADD  Percentage NUMERIC(24,10)    NULL 
    END 
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成方案表
--2014--04-07  wg
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CommissionScheme]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionScheme
(
	BillNumberId			NUMERIC(18,0) IDENTITY(1,1),
	SchemeStart				DATETIME NOT NULL,
	SchemeEnd				DATETIME NOT NULL,
	SchemeName				VARCHAR(256) NOT NULL,	 --方案名称
	CommissionRuleID		NUMERIC(18,0) NOT NULL DEFAULT(0),	--提成规则
	ReferencePlanID			NUMERIC(18,0) NOT NULL DEFAULT(0),	--参照计划提成
	Comment					VARCHAR(256) NOT NULL DEFAULT(''),	--摘要
	Checke					VARCHAR(50) NOT NULL,				--制单人
	Checker					VARCHAR(50) NOT NULL DEFAULT(''),	--审核人
	CheckeTime				DATETIME NOT NULL,		--制单时间
	CheckerTime				DATETIME NULL,		    --审核时间
	BillState				INT NOT NULL,						--单据状态  1=未审核  2=审核  3=禁用
	UseState				INT NOT NULL DEFAULT(0),			--使用状态  1=未引用  2=已引用  --------3=部分完成 4=全部完成
	IsStop					INT NOT NULL DEFAULT(0)				--是否禁用  0=正常  1/2当禁用时写入单据状态 启用时写到单据状态列 起保存禁用时的状态
)

END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionScheme]') AND name = 'ReferencePlanID' )
BEGIN
	ALTER TABLE CommissionScheme ADD ReferencePlanID NUMERIC(18,0) NOT NULL DEFAULT(0)
END
GO

--修改时间列，可以为null，开始结算时间没有了
IF EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionScheme]') AND name = 'SchemeStart' )
BEGIN
	ALTER TABLE CommissionScheme ALTER COLUMN SchemeStart DATETIME NULL
END
GO

IF EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[CommissionScheme]') AND name = 'SchemeEnd' )
BEGIN
	ALTER TABLE CommissionScheme ALTER COLUMN SchemeEnd DATETIME NULL
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成方案表--分支机构
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionSchemeStype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionSchemeStype
(
	BillNumberId			NUMERIC(18,0) NOT NULL,
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	StypeID					VARCHAR(50)					--分支机构
)

END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CommissionStock]    脚本日期: 05/05/2010 14:47:07 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionStock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CommissionStock](
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionStock_Ptypeid]  DEFAULT ('0'),
		[Btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionStock_Btypeid]  DEFAULT ('0'),
		[Type] [int] NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionStock_Qty]  DEFAULT (0),
		[CostTotal] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionStock_CostTotal]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionStock_Total]  DEFAULT (0),
		[Tax] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionStock_Tax]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_CommissionStock_TaxTotal]  DEFAULT (0),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionStock_explain]  DEFAULT (''),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CommissionStock_KTypeID]  DEFAULT (''),
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE CommissionStock ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE CommissionStock SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionStock 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionStock 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionStock 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionStock 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionStock 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CommissionStock_Qty]    脚本日期: 05/05/2010 14:47:07 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionStock_Qty]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CommissionStock_Qty](
		[Ptypeid]					VARCHAR(50)		DEFAULT (''),
		[Btypeid]					VARCHAR(50)		DEFAULT (''),
		[Stypeid]					VARCHAR(50)		DEFAULT (''),
		[Type]						INT				DEFAULT(0),
		ItemID						INT				DEFAULT(0),
		Iscombined					BIT				DEFAULT(0),
		GoodsNumber					VARCHAR(100)	DEFAULT(''),
		ProduceDate					VARCHAR(50)		DEFAULT (''),
		ValidDate					VARCHAR(50)		DEFAULT (''),
		Qty							NUMERIC(22,10)	DEFAULT(0),
		NQty						NUMERIC(22,10)	DEFAULT(0),
		GoodsCostPrice				NUMERIC(22,10)  DEFAULT(0)		
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock_Qty' AND a.Name='GoodsCostPrice'
)
BEGIN
	ALTER TABLE CommissionStock_Qty ADD GoodsCostPrice NUMERIC(22,10) DEFAULT(0)
END
GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'GoodsOrder'
UNION ALL
SELECT 'CargoID'
UNION ALL
SELECT 'GoodsCostPrice'
;
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='CommissionStock_Qty';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO


IF EXISTS(
	SELECT  Ptypeid
	FROM CommissionStock_Qty
)
BEGIN
	BEGIN TRAN
		SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,SUM(Qty) AS Qty,SUM(NQty) AS NQty
		INTO #CommissionStockQtyUpgrade
		FROM CommissionStock_Qty
		GROUP BY Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate
	
		TRUNCATE TABLE CommissionStock_Qty
		
		INSERT CommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty)
		SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty
		FROM #CommissionStockQtyUpgrade

		DROP TABLE #CommissionStockQtyUpgrade
	IF @@ERROR=0
	BEGIN		
		COMMIT TRAN	
	END
	ELSE
	BEGIN
		ROLLBACK TRAN
	END
END

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMMISSIONSTOCK_QTY') AND name = 'CIX_COMMISSIONSTOCK_QTY_Ptypeid_Btypeid')
--DROP INDEX CIX_COMMISSIONSTOCK_QTY_Ptypeid_Btypeid ON COMMISSIONSTOCK_QTY 
CREATE CLUSTERED INDEX CIX_COMMISSIONSTOCK_QTY_Ptypeid_Btypeid ON COMMISSIONSTOCK_QTY(Ptypeid,Btypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock_Qty' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionStock_Qty 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock_Qty' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionStock_Qty 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommissionStock_Qty' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommissionStock_Qty 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--提成类别表
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CommissionType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE CommissionType
(
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	TypeID					VARCHAR(50) NOT NULL,
	ParID					VARCHAR(50) NOT NULL,
	Sonnum					INT NOT NULL DEFAULT(0),
	FullName				VARCHAR(256) NOT NULL,	--类别名称
	EtypeID					VARCHAR(50) NOT NULL,	--负责人
	IsSystem				INT NOT NULL DEFAULT(0) --预制的不能删除  0=添加的  1=预制的
)

INSERT INTO CommissionType(TypeID,ParID,Sonnum,FullName,EtypeID,IsSystem)
VALUES('00000','root',0,'业务提成','','1')
END
if not exists (select name from syscolumns where id = object_id(N'[dbo].[CommissionType]') and name = 'SonCount' )
BEGIN
	ALTER TABLE dbo.CommissionType ADD
		SonCount INT NOT NULL DEFAULT(0) 
END
GO

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosInfo]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosInfo]
        (
          [PosID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                NOT NULL
                                PRIMARY KEY ,
          [FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS
                                   NULL ,
          [Branchid] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [ETypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Stockid] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [BTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [deleted] [int] NOT NULL ,
          [IsKeyset] [int] NOT NULL ,					--会员卡号不支持键盘输入  0是 1否
          [IsHeadquartersStock] [int] NOT NULL ,		--允许查看总部其它仓库库存 0是 1否
          [IsJoinStock] [int] NOT NULL ,				--允许查看其它加盟商库存   0是 1否
          [PosPassword] [varchar](25) COLLATE Chinese_PRC_CI_AS
                                      NOT NULL ,	--POS密码
          [Possessive] [INT]
            NOT NULL
            CONSTRAINT [DF_CommonPosInfo_Possessive] DEFAULT ( 0 ) ,--被POS客户端占有状态，初始建立时该值为0.
          [Comment] [varchar](100) COLLATE Chinese_PRC_CI_AS
                                   NULL ,
          [IsTicketCount] INT
            NOT NULL
            CONSTRAINT DF_CommonPosInfo_IsTicketCount DEFAULT ( 1 ) , --存为小票 或者 直接过账 0--存为小票 1--直接过账
          [cBYZD1] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                 NULL ,
          [cBYZD2] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                 NULL ,
          [iBYZD1] INT NULL ,
          [iBYZD2] INT NULL ,
          [nBYZD1] [numeric](24, 10) NULL ,
          [nBYZD2] [numeric](24, 10) NULL,
          [ETypeid1] [varchar](50) NULL
        )
    ON  [PRIMARY]
GO

------------------------------------------创建索引区域开始-----------------------------------------------


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommonPosInfo' AND a.Name='nBYZD1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommonPosInfo 
	ALTER COLUMN nBYZD1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CommonPosInfo' AND a.Name='nBYZD2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CommonPosInfo 
	ALTER COLUMN nBYZD2 NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*公司图片信息表*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CompanyImage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[CompanyImage] (
		[PIC] IMAGE,
		[Name] VARCHAR(200),
		[type] VARCHAR(50)
	)  ON [PRIMARY]
END
GO

SET ANSI_PADDING OFF
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--品牌结算表
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CompleteBrandarTotal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CompleteBrandarTotal]
	(
		ID				INT IDENTITY(1,1),
		GoodsBillID		NUMERIC(10,0),	
		MoneyBillId		NUMERIC(10,0),
		BrandarTypeID	VARCHAR	(50) NOT NULL,
		STypeId			VARCHAR	(50) NOT NULL,
		BTypeId			VARCHAR	(50) NOT NULL,
		BillType		INT NOT NULL,--单据类型
		BillDate		DATETIME,--当前保存时间
		BillCode		VARCHAR(200),--单据编号
		CId				INT,--币种
		CompleteTotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--结算金额
		NCompleteTotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币结算金额
		Comment			VARCHAR(500),--备注
		EtypeID			VARCHAR(50),--经手人ID
		IsDraft			TINYINT  NOT NULL DEFAULT(1),--是否草稿
		IsIni			TINYINT NOT NULL DEFAULT(0),--是否期初
		DetailId		INT	NOT NULL DEFAULT(0)		--应收增加/减少单明细id

	) ON [PRIMARY]


END
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteBrandarTotal' AND a.Name='DetailId'
)
BEGIN
	ALTER TABLE CompleteBrandarTotal 
		ADD DetailId INT NOT NULL DEFAULT(0)	 
END

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CompleteBrandarTotal') AND name = 'CIX_CompleteBrandarTotal_GoodsBillid')
	CREATE CLUSTERED INDEX CIX_CompleteBrandarTotal_GoodsBillid ON CompleteBrandarTotal(GoodsBillid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CompleteBrandarTotal') AND name = 'NCIX_CompleteBrandarTotal_MoneyBillid')
	CREATE NONCLUSTERED INDEX NCIX_CompleteBrandarTotal_MoneyBillid ON CompleteBrandarTotal(MoneyBillid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CompleteBrandarTotal') AND name = 'NCIX_CompleteBrandarTotal_BrandarTypeID')
	CREATE NONCLUSTERED INDEX NCIX_CompleteBrandarTotal_BrandarTypeID ON CompleteBrandarTotal(BrandarTypeID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
                              
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CompleteGoodTotal]    脚本日期: 05/05/2010 14:47:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CompleteGoodTotal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CompleteGoodTotal](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[GoodsBillID] [int] NOT NULL,
		[MoneyBillID] [int] NOT NULL,
		[InOrOut] [char](1) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[CompleteGoodQTY] [numeric](18, 4) NOT NULL DEFAULT(0),
		[Draft] [tinyint] NULL,
		[Billdate] [datetime] NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Billid] [int] NULL,
		[CompleteGoodTotal] [numeric](18, 4) NULL,
		[Price] [numeric](18, 4) NULL DEFAULT (0),
		[NCompleteGoodTotal] [numeric](22, 10) NULL DEFAULT(0),
		[BillType] [INT] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------





IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteGoodTotal' AND a.Name='IsSelect'
)
BEGIN
	ALTER TABLE CompleteGoodTotal ADD IsSelect bit NULL
END
GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteGoodTotal' AND a.Name='NCompleteGoodTotal'
)
BEGIN
	ALTER TABLE CompleteGoodTotal ADD NCompleteGoodTotal NUMERIC(22,10) NULL DEFAULT(0)
	
	EXEC('UPDATE CompleteGoodTotal SET NCompleteGoodTotal=CompleteTotal WHERE NCompleteGoodTotal IS NULL')
END
ELSE 
BEGIN
	ALTER TABLE CompleteGoodTotal ALTER COLUMN NCompleteGoodTotal NUMERIC(22,10) NULL
END 
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CID' UNION ALL SELECT 'CurID';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='CompleteGoodTotal';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteGoodTotal' AND a.Name='BillType'
)
BEGIN
	ALTER TABLE CompleteGoodTotal ADD BillType INT NULL
END
GO
    UPDATE  A
    SET     A.BillType = B.BillType
    FROM    dbo.CompleteGoodTotal A
    INNER JOIN dbo.BillIndex B ON A.GoodsBillID = B.BillNumberId
    WHERE   A.BillType IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMPLETEGOODTOTAL') AND name = 'CIX_COMPLETEGOODTOTAL_GoodsBillid')
--DROP INDEX CIX_COMPLETEGOODTOTAL_GoodsBillid ON COMPLETEGOODTOTAL 
CREATE CLUSTERED INDEX CIX_COMPLETEGOODTOTAL_GoodsBillid ON COMPLETEGOODTOTAL(GoodsBillid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMPLETEGOODTOTAL') AND name = 'NCIX_COMPLETEGOODTOTAL_MoneyBillid')
--DROP INDEX NCIX_COMPLETEGOODTOTAL_MoneyBillid ON COMPLETEGOODTOTAL 
CREATE NONCLUSTERED INDEX NCIX_COMPLETEGOODTOTAL_MoneyBillid ON COMPLETEGOODTOTAL(MoneyBillid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMPLETEGOODTOTAL') AND name = 'NCIX_COMPLETEGOODTOTAL_Billid')
--DROP INDEX NCIX_COMPLETEGOODTOTAL_Billid ON COMPLETEGOODTOTAL 
CREATE NONCLUSTERED INDEX NCIX_COMPLETEGOODTOTAL_Billid ON COMPLETEGOODTOTAL(Billid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteGoodTotal' AND a.Name='CompleteGoodQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CompleteGoodTotal 
	ALTER COLUMN CompleteGoodQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteGoodTotal' AND a.Name='CompleteGoodTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CompleteGoodTotal 
	ALTER COLUMN CompleteGoodTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteGoodTotal' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CompleteGoodTotal 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteGoodTotal' AND a.Name='NCompleteGoodTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CompleteGoodTotal 
	ALTER COLUMN NCompleteGoodTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CompleteTotal]    脚本日期: 05/05/2010 14:47:09 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CompleteTotal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CompleteTotal](
		[GoodsBillID] [int] NOT NULL,
		[MoneyBillID] [int] NOT NULL,
		[CompleteTotal] [numeric](18, 4) NOT NULL DEFAULT(0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Draft] [tinyint] NULL DEFAULT (0),
		[Billdate] [datetime] NULL,
		[EtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[NCompleteTotal] [numeric](22, 10)  NULL DEFAULT(0),
		[GoodsBillDetailID] [int] NULL,
		[BillType] [INT] NULL
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteTotal' AND a.Name='NCompleteTotal'
)
BEGIN
	ALTER TABLE CompleteTotal ADD NCompleteTotal NUMERIC(22,10)
	
	EXEC('UPDATE CompleteTotal SET NCompleteTotal=CompleteTotal WHERE NCompleteTotal IS NULL')
END
ELSE
BEGIN
	ALTER TABLE CompleteTotal ALTER COLUMN NCompleteTotal NUMERIC(22,10)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteTotal' AND a.Name='GoodsBillDetailID'
)
BEGIN
	ALTER TABLE CompleteTotal ADD GoodsBillDetailID INT NULL
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteTotal' AND a.Name='IsSelect'
)
BEGIN
	ALTER TABLE CompleteTotal ADD IsSelect bit NULL
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CID' UNION ALL SELECT 'CurID';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='CompleteTotal';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
BEGIN	
	EXEC(@sql);
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteTotal' AND a.Name='BillType'
)
BEGIN
	ALTER TABLE CompleteTotal ADD BillType INT NULL
END
GO
    UPDATE  A
    SET     A.BillType = B.BillType
    FROM    dbo.CompleteTotal A
    INNER JOIN dbo.BillIndex B ON A.GoodsBillID = B.BillNumberId
    WHERE   A.BillType IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMPLETETOTAL') AND name = 'CIX_COMPLETETOTAL_GoodsBillid')
--DROP INDEX CIX_COMPLETETOTAL_GoodsBillid ON COMPLETETOTAL 
CREATE CLUSTERED INDEX CIX_COMPLETETOTAL_GoodsBillid ON COMPLETETOTAL(GoodsBillid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('COMPLETETOTAL') AND name = 'NCIX_COMPLETETOTAL_MoneyBillid')
--DROP INDEX NCIX_COMPLETETOTAL_MoneyBillid ON COMPLETETOTAL 
CREATE NONCLUSTERED INDEX NCIX_COMPLETETOTAL_MoneyBillid ON COMPLETETOTAL(MoneyBillid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteTotal' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CompleteTotal 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CompleteTotal' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CompleteTotal 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[Cost_NoRelog]    Script Date: 12/10/2015 15:39:59 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Cost_NoRelog_PTypeID]') AND type = 'D')
BEGIN

	CREATE TABLE [dbo].[Cost_NoRelog](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[PTypeID] [varchar](50) NULL,
		[STypeID] [varchar](50) NULL,
		[PostTime] [datetime] NULL,
		[OperatorID] [varchar](50) NULL,
		[DealTime] [DATETIME] NULL DEFAULT GETDATE(),
		[BillNumberID] BIGINT NULL,
		[BillType] INT NULL,
	 CONSTRAINT [PK_Cost_NoRelog] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]



	SET ANSI_PADDING OFF


	ALTER TABLE [dbo].[Cost_NoRelog] ADD  CONSTRAINT [DF_Cost_NoRelog_PTypeID]  DEFAULT ('') FOR [PTypeID]


	ALTER TABLE [dbo].[Cost_NoRelog] ADD  CONSTRAINT [DF_Cost_NoRelog_STypeID]  DEFAULT ('') FOR [STypeID]


	ALTER TABLE [dbo].[Cost_NoRelog] ADD  CONSTRAINT [DF_Cost_NoRelog_PostTime]  DEFAULT (getdate()) FOR [PostTime]

END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Cost_NoRelog' AND a.Name='DealTime'
)
BEGIN
	ALTER TABLE Cost_NoRelog ADD [DealTime] [DATETIME] NULL DEFAULT GETDATE()
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Cost_NoRelog' AND a.Name='BillNumberID'
)
BEGIN
	ALTER TABLE Cost_NoRelog ADD [BillNumberID] BIGINT NULL,[BillType] INT NULL
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Cost_NoRelog' AND a.Name='RedWordBillNumberID'
)
BEGIN
	ALTER TABLE Cost_NoRelog DROP COLUMN RedWordBillNumberID,ModifyBillNumberID
END

GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CostRe_Bill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CostRe_Bill](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[BillType] INT,
		[PTypeID] VARCHAR(50) NULL DEFAULT(''),		
		[KTypeID] VARCHAR(50) NULL DEFAULT(''),
		[STypeID] VARCHAR(50) NULL DEFAULT(''),
		[PostTime] DATETIME NULL DEFAULT(GETDATE()),
		[BillDate] DATETIME NULL
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT 1 FROM Sys.Indexes WHERE object_id = OBJECT_ID('CostRe_Bill') AND Name = 'CIX_CostRe_Bill_PostTime')
CREATE CLUSTERED INDEX CIX_CostRe_Bill_PostTime ON CostRe_Bill(PostTime) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE object_id = OBJECT_ID('CostRe_Bill') AND name = 'NCIX_CostRe_Bill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_CostRe_Bill_BillNumberID ON CostRe_Bill(BillNumberID) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE object_id = OBJECT_ID('CostRe_Bill') AND name = 'NCIX_CostRe_Bill_PTypeID')
CREATE NONCLUSTERED INDEX NCIX_CostRe_Bill_PTypeID ON CostRe_Bill(PTypeID) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE object_id = OBJECT_ID('CostRe_Bill') AND name = 'NCIX_CostRe_Bill_STypeID')
CREATE NONCLUSTERED INDEX NCIX_CostRe_Bill_STypeID ON CostRe_Bill(STypeID) 

------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[CostReLog]    Script Date: 12/10/2015 15:39:59 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_CostReLog_PTypeID]') AND type = 'D')
BEGIN

	CREATE TABLE [dbo].[CostReLog](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[PTypeID] [varchar](50) NULL,
		[STypeID] [varchar](50) NULL,
		[PostTime] [datetime] NULL,
		[OperatorID] [varchar](50) NULL,
		[DealTime] [DATETIME] NULL DEFAULT GETDATE(),
		[BillNumberID] BIGINT NULL,
		[BillType] INT NULL,
	 CONSTRAINT [PK_CostReLog] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]



	SET ANSI_PADDING OFF


	ALTER TABLE [dbo].[CostReLog] ADD  CONSTRAINT [DF_CostReLog_PTypeID]  DEFAULT ('') FOR [PTypeID]


	ALTER TABLE [dbo].[CostReLog] ADD  CONSTRAINT [DF_CostReLog_STypeID]  DEFAULT ('') FOR [STypeID]


	ALTER TABLE [dbo].[CostReLog] ADD  CONSTRAINT [DF_CostReLog_PostTime]  DEFAULT (getdate()) FOR [PostTime]

END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CostReLog' AND a.Name='DealTime'
)
BEGIN
	ALTER TABLE CostReLog ADD [DealTime] [DATETIME] NULL DEFAULT GETDATE()
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CostReLog' AND a.Name='BillNumberID'
)
BEGIN
	ALTER TABLE CostReLog ADD [BillNumberID] BIGINT NULL,[BillType] INT NULL
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CostReLog' AND a.Name='RedWordBillNumberID'
)
BEGIN
	ALTER TABLE CostReLog DROP COLUMN RedWordBillNumberID,ModifyBillNumberID
END

GO




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_AllotBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_AllotBill
	(
		Id						NUMERIC(18,0) IDENTITY(1,1),						--明细ID
		BillNumberId			NUMERIC(18,0),						--主表单据ID
		CouponId				INT,								--优惠券ID
		CouponCode				VARCHAR(MAX),						--券编码	
		InCargoId				INT,								--入库货位	
		OutCargoId				INT,								--出库货位	
		Comment					VARCHAR(255) DEFAULT(''),			--备注
		Qty						NUMERIC(24,10)						--数量
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_AllotBill' AND a.Name='InCargoId'
)
BEGIN
	ALTER TABLE Coupon_AllotBill ADD InCargoId	INT DEFAULT 1 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_AllotBill' AND a.Name='OutCargoId'
)
BEGIN
	ALTER TABLE Coupon_AllotBill ADD OutCargoId	INT DEFAULT 1 NULL
END
GO
--判断是否是自增长列，修改表结构
DECLARE @identity INT
SELECT @identity = COLUMNPROPERTY( OBJECT_ID('Coupon_AllotBill'),'id','IsIdentity')
IF @identity = 0
BEGIN
	alter table Coupon_AllotBill 
		drop column id
		
	alter table Coupon_AllotBill
		add id NUMERIC(18,0) identity(1,1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_AllotBill' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE Coupon_AllotBill ADD Comment VARCHAR(255) DEFAULT('') NULL
END
GO
UPDATE Coupon_AllotBill SET Comment = '' WHERE Comment IS NULL
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_AllotBill' AND a.Name='Qty'
)
BEGIN
	ALTER TABLE Coupon_AllotBill ADD Qty NUMERIC(24,10)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_AllotBill') AND name = 'CIX_Coupon_AllotBill_BillNumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_AllotBill_BillNumberId ON Coupon_AllotBill(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_AllotBillStype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_AllotBillStype
	(
		Id						NUMERIC(18,0) IDENTITY(1,1),		--明细ID
		BillNumberId			NUMERIC(18,0),						--主表单据ID
		CouponId				INT,								--优惠券ID
		CouponCode				VARCHAR(MAX),						--券编码	
		InCargoId				INT,								--入库货位	
		OutCargoId				INT,								--出库货位	
		Comment					VARCHAR(255) DEFAULT(''),			--备注
		Qty						NUMERIC(24,10),						--数量
		Price					numeric(24,10),						--单价
		Total					numeric(24,10),						--金额
		InStockDate				date,								--入库日期
		InvalidDate				date,								--失效日期
		OutDate					date,								--出库日期
		FromBillNumberID		numeric(10, 0)  NULL DEFAULT (0),
		FromBillID				int NULL DEFAULT (0)
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Coupon_AllotBillStype]') and  name = 'InStockDate')
BEGIN
	 ALTER TABLE Coupon_AllotBillStype
	    ADD InStockDate DATE NULL
END

GO

IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Coupon_AllotBillStype]') and  name = 'InvalidDate')
BEGIN
	 ALTER TABLE Coupon_AllotBillStype
	    ADD InvalidDate DATE NULL
END

GO

IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Coupon_AllotBillStype]') and  name = 'OutDate')
BEGIN
	 ALTER TABLE Coupon_AllotBillStype
	    ADD OutDate DATE NULL
END

GO

IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Coupon_AllotBillStype]') and  name = 'FromBillNumberID')
BEGIN
	 ALTER TABLE Coupon_AllotBillStype
	    ADD FromBillNumberID numeric(10, 0)  NULL DEFAULT (0)
END

GO

IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Coupon_AllotBillStype]') and  name = 'FromBillID')
BEGIN
	 ALTER TABLE Coupon_AllotBillStype
	    ADD FromBillID int NULL DEFAULT (0)
END

GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_AllotBillStype') AND name = 'CIX_Coupon_AllotBillStype_BillNumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_AllotBillStype_BillNumberId ON Coupon_AllotBillStype(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--优惠券-适用门店
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_ApplyPos]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_ApplyPos
	(
		CouponId			INT,--优惠券ID
		PosId				INT	--POS终端ID  0.所有终端信息，否则为具体pos终端信息
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_ApplyPOS') AND name = 'CIX_Coupon_ApplyPOS_CouponId')
	CREATE CLUSTERED INDEX CIX_Coupon_ApplyPOS_CouponId ON Coupon_ApplyPOS(CouponId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_ApplyPtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_ApplyPtype
	(
		CouponId			INT ,				--优惠券ID
		PtypeId				VARCHAR(50),		--商品ID  00000.所有商品，否则为具体商品
		Qty					NUMERIC(24,10),		--数量
		Price				NUMERIC(24,10),		--参考单价
		Total				NUMERIC(24,10)		--参考金额
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Coupon_ApplyPtype',N'U') AND Name='IsExchangePtype')
BEGIN
	ALTER TABLE dbo.Coupon_ApplyPtype
		ADD IsExchangePtype INT NOT NULL DEFAULT(0) --是否兑换商品
END
GO

IF EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'Coupon_ApplyPtype',N'U') AND name = 'ItemID')
BEGIN
	ALTER TABLE dbo.Coupon_ApplyPtype DROP COLUMN ItemID
END

IF EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'Coupon_ApplyPtype',N'U') AND name = 'IsCombined')
BEGIN
	ALTER TABLE dbo.Coupon_ApplyPtype DROP COLUMN IsCombined
END 


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_ApplyPtype') AND name = 'CIX_Coupon_ApplyPtype_CouponId')
	CREATE CLUSTERED INDEX CIX_Coupon_ApplyPtype_CouponId ON Coupon_ApplyPtype(CouponId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_ApplyStype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_ApplyStype
	(
		CouponId			INT ,				--优惠券ID
		StypeId				VARCHAR(50)			--分支机构ID  00000.所有分支机构，否则为具体分支机构值
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_ApplyStype') AND name = 'CIX_Coupon_ApplyStype_CouponId')
	CREATE CLUSTERED INDEX CIX_Coupon_ApplyStype_CouponId ON Coupon_ApplyStype(CouponId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_BackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_BackBill
	(
		Id						NUMERIC(18,0) IDENTITY(1,1),						--明细ID
		BillNumberId			NUMERIC(18,0),						--主表单据ID
		CouponId				INT,								--优惠券ID
		CouponCode				VARCHAR(MAX),						--券编码		
		Qty						NUMERIC(24,10),						--数量
		Price					NUMERIC(24,10),						--单价
		NPrice					NUMERIC(24,10),						--单价原币
		Total					NUMERIC(24,10),						--金额
		NTotal					NUMERIC(24,10),						--金额原币				
		Comment					VARCHAR(255) DEFAULT(''),			--备注
		CargoId					INT,								--货位	
		OutBillId				INT									--销售单明细id
		
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BackBill' AND a.Name='CargoId'
)
BEGIN
	ALTER TABLE Coupon_BackBill ADD CargoId	INT DEFAULT 1 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BackBill' AND a.Name='OutBillId'
)
BEGIN
	ALTER TABLE Coupon_BackBill ADD OutBillId	INT DEFAULT 0 NULL
END
GO

--判断是否是自增长列，修改表结构
DECLARE @identity INT
SELECT @identity = COLUMNPROPERTY( OBJECT_ID('Coupon_BackBill'),'id','IsIdentity')
IF @identity = 0
BEGIN
	alter table Coupon_BackBill 
		drop column id
		
	alter table Coupon_BackBill
		add id NUMERIC(18,0) identity(1,1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_BackBill') AND name = 'CIX_Coupon_BackBill_BillNumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_BackBill_BillNumberId ON Coupon_BackBill(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------






SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_BillIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_BillIndex
	(
		BillNumberId			NUMERIC(18,0) IDENTITY(1,1) NOT NULL,						--单据ID
		BillDate				DATETIME,							--单据日期
		BillCode				VARCHAR(200),						--单据编号
		BillType				INT,								--单据类型
		FromType				INT,								--券来源  0.期初 1.自制 2.外购 3.报溢
		STypeId					VARCHAR(50) DEFAULT(''),			--分支机构ID
		DTypeId					VARCHAR(50) DEFAULT(''),			--部门ID
		ETypeId					VARCHAR(50) DEFAULT(''),			--经手人ID
		OutKTypeId				VARCHAR(50) DEFAULT(''),			--出库仓库ID【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		InKTypeId				VARCHAR(50) DEFAULT(''),			--入库仓库ID【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		Cid						INT,								--币种
		Rate					NUMERIC(24,10),						--汇率
		TotalQty				NUMERIC(24,10) NOT NULL DEFAULT(0),						--总数量
		TotalMoney				NUMERIC(24,10) NOT NULL DEFAULT(0),						--总金额
		NTotalMoney				NUMERIC(24,10) NOT NULL DEFAULT(0),						--总金额原币
		CompleteTotal			NUMERIC(24,10) NOT NULL DEFAULT(0),						--已结算金额
		NCompleteTotal			NUMERIC(24,10) NOT NULL DEFAULT(0),						--已结算金额原币
		TotalInMoney			NUMERIC(24,10) NOT NULL DEFAULT(0),						--收付款金额
		NTotalInMoney			NUMERIC(24,10) NOT NULL DEFAULT(0),						--收付款金额原币
		IfMulAccount			INT,								--多账号 0.否 1.是
		ATypeId					VARCHAR(50) DEFAULT(''),			--收款项目
		BTypeId					VARCHAR(50) DEFAULT(''),			--往来单位
		DealBTypeId				VARCHAR(50) DEFAULT(''),			--结算单位【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		Explain					VARCHAR(255) DEFAULT(''),			--说明
		Comment					VARCHAR(256) DEFAULT(''),			--摘要
		Poster					VARCHAR(50) DEFAULT(''),			--过账人ID【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		PostTime				DATETIME,							--过账时间
		MakeTime				DATETIME,							--制单时间，带时分秒
		Maker					VARCHAR(50) DEFAULT(''),			--制单人typeid【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		Checker					VARCHAR(50) DEFAULT(''),			--审核人typeid【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		CheckeTime				DATETIME,							--审核时间
		IfAudit					INT,								--审核	0.否  1.是
		Draft					INT,								--草稿	0.否  1.是
		IfCheck					CHAR(1) NOT NULL DEFAULT('f'),		--过账	f.否  t.是
		RedWord					INT,								--红冲  0.正常单据  1.蓝单  2.红单
		IsIni					INT,								--期初单据  0.否  1.是
		IfYearBill				INT,								--是否年结存保留单据  0.否 1.是
		RedReason				VARCHAR(500) DEFAULT(''),			--红冲原因
		ATypeId1				VARCHAR(50),						--往来科目ID【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		Atid					INT,								--凭证模板ID
		TallyId					VARCHAR(50),						--记账人typeid【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		ChargeOffTotal			NUMERIC(24,10) NOT NULL DEFAULT(0),						--核销金额
		NChargeOffTotal			NUMERIC(24,10) NOT NULL DEFAULT(0),						--核销金额原币
		JsState					INT,								--结算状态：0未结算 1结算未完全 2完全结算
		PosId					INT,								--pos终端id
		PreferenceMoney			NUMERIC(24, 10) NOT NULL  DEFAULT (0),  --抹零金额
		NPreferenceMoney		NUMERIC(24, 10) NOT NULL  DEFAULT (0),  --抹零金额
		Reconciliation			CHAR(1) DEFAULT('f'),			--对账 默认f 对账t
		updateE					VARCHAR(50) DEFAULT(''),					--修改人
		LastUpdateTime			DATETIME	DEFAULT(''),					--修改时间
		FromBillNumberID		NUMERIC(18,0) DEFAULT (0)
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Coupon_BillIndex',N'U') AND Name='NTotaInlMoney')
BEGIN
	ALTER TABLE Coupon_BillIndex 
		DROP COLUMN NTotaInlMoney
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Coupon_BillIndex',N'U') AND Name='NTotalInMoney')
BEGIN
	ALTER TABLE Coupon_BillIndex 
		ADD NTotalInMoney NUMERIC(24,10) DEFAULT(0)
END
GO

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Coupon_BillIndex',N'U') AND Name='TallId')
BEGIN
	exec sp_rename 'Coupon_BillIndex.TallId','TallyId','column'
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='ChargeOffTotal'
)
BEGIN
	ALTER TABLE Coupon_BillIndex ADD ChargeOffTotal NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='NChargeOffTotal'
)
BEGIN
	ALTER TABLE Coupon_BillIndex ADD NChargeOffTotal NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='JsState'
)
BEGIN
	ALTER TABLE Coupon_BillIndex ADD JsState INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='PosId'
)
BEGIN
	ALTER TABLE Coupon_BillIndex ADD PosId INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='PreferenceMoney'
)
BEGIN
	ALTER TABLE Coupon_BillIndex ADD PreferenceMoney NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='NPreferenceMoney'
)
BEGIN
	ALTER TABLE Coupon_BillIndex ADD NPreferenceMoney NUMERIC(22,10) NOT NULL DEFAULT(0)
END
GO

UPDATE Coupon_BillIndex SET NTotalInMoney = 0 WHERE NTotalInMoney IS NULL
GO

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Coupon_BillIndex',N'U') AND Name='IfCheck')
BEGIN
	ALTER TABLE Coupon_BillIndex 
		ALTER COLUMN IfCheck CHAR(1) 
	
	UPDATE dbo.Coupon_BillIndex SET IfCheck = CASE WHEN IfCheck = '1' THEN 't' ELSE 'f' END WHERE IfCheck = '1' OR IfCheck = '0'
END
GO

UPDATE dbo.Coupon_BillIndex SET ChargeOffTotal = 0,NChargeOffTotal =0 WHERE ChargeOffTotal IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE Coupon_BillIndex ADD Reconciliation CHAR(1) DEFAULT('f')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='Checke'
)
BEGIN
	ALTER TABLE Coupon_BillIndex 
		ADD Checke VARCHAR(50) NULL DEFAULT('')
END
GO
UPDATE Coupon_BillIndex SET checke = '' WHERE checke IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='updateE'
)
BEGIN
	ALTER TABLE Coupon_BillIndex 
		ADD updateE VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='LastUpdateTime'
)
BEGIN
	ALTER TABLE Coupon_BillIndex 
		ADD LastUpdateTime DATETIME  DEFAULT('')
END
GO 

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='PosBillCode'
)
BEGIN
	ALTER TABLE Coupon_BillIndex 
		ADD PosBillCode VARCHAR(200)  DEFAULT('')
END
GO 

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillIndex' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE Coupon_BillIndex 
		ADD FromBillNumberID VARCHAR(200)  DEFAULT (0)
END
GO 

ALTER TABLE Coupon_BillIndex ALTER COLUMN RedReason VARCHAR(500)
go

ALTER TABLE Coupon_BillIndex ALTER COLUMN Comment VARCHAR(256)
go
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_BillIndex') AND name = 'CIX_Coupon_BillIndex_BillNumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_BillIndex_BillNumberId ON Coupon_BillIndex(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_BillUsed]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_BillUsed
	(	
		BillnumberId			NUMERIC(18,0),					--单据BillnumberId
		CouponCode				VARCHAR(200),					--券编码		
		BillType				INT,							--单据类型
		PosId					INT	NOT NULL DEFAULT(0),			--pos机id，用于标识pos端使用的券
		CouponId				INT								--券类型ID
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillUsed' AND a.Name='PosId'
)
BEGIN
	ALTER TABLE Coupon_BillUsed ADD PosId INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillUsed' AND a.Name='CouponId'
)
BEGIN
	ALTER TABLE Coupon_BillUsed ADD CouponId INT 
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_BillUsed') AND name = 'CIX_Coupon_BillUsed_BillnumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_BillUsed_BillnumberId ON Coupon_BillUsed(BillnumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_BillUsedAutoDraft]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_BillUsedAutoDraft
	(	
		BillGuid				VARCHAR(100),
		BillnumberId			NUMERIC(18,0),					--单据BillnumberId
		CouponCode				VARCHAR(200),					--券编码		
		BillType				INT,							--单据类型
		PosId					INT	NOT NULL DEFAULT(0),			--pos机id，用于标识pos端使用的券
		CouponId				INT								--券类型ID
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillUsedAutoDraft' AND a.Name='PosId'
)
BEGIN
	ALTER TABLE Coupon_BillUsedAutoDraft ADD PosId INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_BillUsedAutoDraft' AND a.Name='CouponId'
)
BEGIN
	ALTER TABLE Coupon_BillUsedAutoDraft ADD CouponId INT 
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_BillUsedAutoDraft') AND name = 'CIX_Coupon_BillUsedAutoDraft_BillnumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_BillUsedAutoDraft_BillnumberId ON Coupon_BillUsedAutoDraft(BillnumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_CodeInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_CodeInfo
	(
		Id						INT IDENTITY(1,1),					--ID		
		CouponCode				VARCHAR(200),						--券编码		
		CouponId				INT,								--券类型ID
		[State]					INT,								--状态  1.入库、在库 2.出库 3.消费  4.消费红冲 5.消费退货 6报损  7.分支机构调拨出库,8分支机构调拨入库
		Dbguid					VARCHAR(50) NULL DEFAULT(NEWID()),	--记录一个内部ID
		IsIni					INT,								--期初记录
		KtypeId					VARCHAR(50),						--所在仓库
		CargoId					INT,								--所在货位
		IniState				INT,								--期初状态
		InvalidDate				DATETIME,							--失效日期
		IsYear					INT,								--年结记录
		OutPrice				NUMERIC(24,10),						--券出库价格
		InDate					DATETIME,							--入库时间
		OutDate					DATETIME,							--出库时间
		IniKtypeId				VARCHAR(50),						--期初仓库
		IniCargoId				INT								--期初货位
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD IsIni	INT DEFAULT 0 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='KtypeId'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD KtypeId	VARCHAR(50) DEFAULT '' NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='CargoId'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD CargoId	INT DEFAULT 1 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='IniState'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD IniState	INT DEFAULT 1 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='InvalidDate'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD InvalidDate	DATETIME DEFAULT('') NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='IsYear'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD IsYear	INT DEFAULT 0 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='OutPrice'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD OutPrice	NUMERIC(24,10) DEFAULT 0 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='InDate'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD InDate DATETIME
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='OutDate'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD OutDate	DATETIME
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='IniKtypeId'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD IniKtypeId	VARCHAR(50)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_CodeInfo' AND a.Name='IniCargoId'
)
BEGIN
	ALTER TABLE Coupon_CodeInfo ADD IniCargoId	INT
END
GO



GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_CodeInfo') AND name = 'CIX_Coupon_CodeInfo_CouponCode')
	CREATE CLUSTERED INDEX CIX_Coupon_CodeInfo_CouponCode ON Coupon_CodeInfo(CouponCode) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_CodeInOut]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_CodeInOut
	(
		BillNumberId			NUMERIC(18,0),						--单据id
		BillType				INT,								--单据类型
		BillDate				DATETIME,							--单据日期
		DetailId				INT,								--明细id	
		CouponCode				VARCHAR(200),						--券编码		
		CouponId				INT,								--券类型ID
		[State]					INT,								--状态  1.入库、在库 2.出库 3.消费  4.消费红冲 5.消费退货 6报损
		InKtypeId				VARCHAR(50),						--入库仓库
		InCargoId				INT,								--入库货位
		OutKtypeId				VARCHAR(50),						--出库仓库		
		OutCargoId				INT	,								--出库货位
		Total					NUMERIC(24,10),						--金额
		NTotal					NUMERIC(24,10)						--原币金额
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_CodeInOut') AND name = 'CIX_Coupon_CodeInOut_CouponCode')
	CREATE CLUSTERED INDEX CIX_Coupon_CodeInOut_CouponCode ON Coupon_CodeInOut(CouponCode) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_InBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_InBill
	(
		Id						NUMERIC(18,0) IDENTITY(1,1),						--明细ID
		BillNumberId			NUMERIC(18,0),						--主表单据ID		
		CouponId				INT,								--优惠券ID
		CouponCode				VARCHAR(MAX),						--券编码
		Comment					VARCHAR(255) DEFAULT(''),			--备注		
		Qty						NUMERIC(24,10),						--数量	
		InDate					DATETIME,							--入库日期
		InvalidDate				DATETIME,							--失效日期
		CostPrice				NUMERIC(24,10),						--成本单价
		NCostPrice				NUMERIC(24,10),						--成本单价原币
		CostTotal				NUMERIC(24,10),						--成本金额
		NCostTotal				NUMERIC(24,10),						--成本金额原币	
		CargoId					INT									--货位	
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_InBill' AND a.Name='CargoId'
)
BEGIN
	ALTER TABLE Coupon_InBill ADD CargoId	INT DEFAULT 1 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_InBill' AND a.Name='InDate'
)
BEGIN
	ALTER TABLE Coupon_InBill ADD InDate DATETIME NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_InBill' AND a.Name='InvalidDate'
)
BEGIN
	ALTER TABLE Coupon_InBill ADD InvalidDate	DATETIME NULL
END
GO

--判断是否是自增长列，修改表结构
DECLARE @identity INT
SELECT @identity = COLUMNPROPERTY( OBJECT_ID('Coupon_InBill'),'id','IsIdentity')
IF @identity = 0
BEGIN
	alter table Coupon_InBill 
		drop column id
		
	alter table Coupon_InBill
		add id NUMERIC(18,0) identity(1,1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_InBill') AND name = 'CIX_Coupon_InBill_BillNumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_InBill_BillNumberId ON Coupon_InBill(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_OutBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_OutBill
	(
		Id						NUMERIC(18,0) IDENTITY(1,1),						--明细ID
		BillNumberId			NUMERIC(18,0),						--主表单据ID
		CouponId				INT,								--优惠券ID
		CouponCode				VARCHAR(MAX),						--券编码
		Comment					VARCHAR(255) DEFAULT(''),			--备注		
		Qty						NUMERIC(24,10),						--数量
		Price					NUMERIC(24,10),						--单价
		NPrice					NUMERIC(24,10),						--单价原币
		Total					NUMERIC(24,10),						--金额
		NTotal					NUMERIC(24,10),						--金额原币		
		OutDate					DATETIME,							--出库日期
		InvalidDate				DATETIME,							--失效日期
		CargoId					INT,								--货位	
		BackQty					NUMERIC(24,10)						--退货数量
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_OutBill' AND a.Name='CargoId'
)
BEGIN
	ALTER TABLE Coupon_OutBill ADD CargoId	INT DEFAULT 1 NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_OutBill' AND a.Name='BackQty'
)
BEGIN
	ALTER TABLE Coupon_OutBill ADD BackQty	NUMERIC(24,10) DEFAULT 0 NULL
END
GO

--判断是否是自增长列，修改表结构
DECLARE @identity INT
SELECT @identity = COLUMNPROPERTY( OBJECT_ID('Coupon_OutBill'),'id','IsIdentity')
IF @identity = 0
BEGIN
	alter table Coupon_OutBill 
		drop column id
		
	alter table Coupon_OutBill
		add id NUMERIC(18,0) identity(1,1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_OutBill') AND name = 'CIX_Coupon_OutBill_BillNumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_OutBill_BillNumberId ON Coupon_OutBill(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_OutBill_Ptype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_OutBill_Ptype
	(
		BId						NUMERIC(18,0),						--明细ID
		BillNumberId			NUMERIC(18,0),						--主表单据ID
		CouponId				INT,								--优惠券ID
		CouponCode				VARCHAR(MAX),						--券编码
		PtypeId					VARCHAR(50) DEFAULT(''),			--商品typeid	
		ItemId					INT,								--自由项ID
		IsCombined				INT,								--组合项标识   0.否  1.是	
		Qty						NUMERIC(24,10),						--数量
		Price					NUMERIC(24,10),						--单价
		NPrice					NUMERIC(24,10),						--单价原币
		Total					NUMERIC(24,10),						--金额
		NTotal					NUMERIC(24,10)						--金额原币				
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_OutBill_Ptype' AND a.Name='ItemId'
)
BEGIN
	ALTER TABLE Coupon_OutBill_Ptype ADD ItemId INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Coupon_OutBill_Ptype' AND a.Name='IsCombined'
)
BEGIN
	ALTER TABLE Coupon_OutBill_Ptype ADD IsCombined INT NOT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_OutBill_Ptype') AND name = 'CIX_Coupon_OutBill_Ptype_BillNumberId')
	CREATE CLUSTERED INDEX CIX_Coupon_OutBill_Ptype_BillNumberId ON Coupon_OutBill_Ptype(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON


IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Coupon_TypeInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Coupon_TypeInfo
	(
		CouponId				INT IDENTITY(1,1) NOT NULL,				--优惠券自增长ID
		UserCode				VARCHAR(200) NOT NULL DEFAULT(''),		--优惠券编码
		FullName				VARCHAR(200) NOT NULL DEFAULT(''),		--优惠券名称
		CouponType				INT NOT NULL,							--券类型 1.代金券 2.折扣券 3.兑换券
		Discount				NUMERIC(24,10),							--折扣
		CouponValue				NUMERIC(24,10),							--面值
		Cid						INT,									--币种
		Maker					VARCHAR(50) DEFAULT(''),				--创建人【非标准字段，需要加入到搬移表中Sys_BaseInfoUsing_Tables中】
		CreateDate				DATETIME DEFAULT(GETDATE()),			--创建日期
		InvalidType				INT,									--失效方式 1.不失效 2.固定期限 3.固定时间
		InvalidDate				DATETIME,								--失效日期
		InvalidStartDateType	INT,									--失效开始类型  1.入库日期 2.出库日期 3.自定义
		InvalidStartDate		DATETIME,								--失效开始
		InvalidTermType			INT,									--失效期限类型  1.年 2.月 3.天
		InvalidTerm				INT,									--失效期限
		MoneyType				INT,									--适用商品选项 1.抹零后金额  2.价税合计
		MinMoney				NUMERIC(24,10),							--使用代金券的底线金额 0.否 1.是
		IsPromotion				INT,									--参与促销 0.否 1.是
		IsVipPoint				INT,									--参与会员积分  0.否 1.是
		Comment					VARCHAR(255) NULL DEFAULT(''),			--备注
		IsDelete				INT,									--是否作废  0.否 1.是
		Dbguid					VARCHAR(50) NULL DEFAULT(NEWID())		--记录一个内部ID
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Coupon_TypeInfo',N'U') AND Name='InvalidStartDateType')
BEGIN
	ALTER TABLE dbo.Coupon_TypeInfo
		ADD InvalidStartDateType INT NULL DEFAULT(1)
END
GO
UPDATE Coupon_TypeInfo SET InvalidStartDateType = 1 WHERE InvalidStartDateType IS NULL
GO
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Coupon_TypeInfo',N'U') AND Name='MoneyType')
BEGIN
	ALTER TABLE dbo.Coupon_TypeInfo
		ADD MoneyType INT NULL DEFAULT(1)
END
GO
UPDATE Coupon_TypeInfo SET MoneyType = 1 WHERE MoneyType IS NULL
GO

IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Coupon_TypeInfo',N'U') AND Name='IsPosAll')
BEGIN
	ALTER TABLE dbo.Coupon_TypeInfo
		ADD IsPosAll INT NOT NULL DEFAULT(1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Coupon_TypeInfo') AND name = 'CIX_Coupon_TypeInfo_CouponId')
	CREATE CLUSTERED INDEX CIX_Coupon_TypeInfo_CouponId ON Coupon_TypeInfo(CouponId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------




SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

/**
创建人：罗淮文
日  期：2016-07-25
描  述：优惠券兑换商品方案明细表
**/
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CouponExchangePtypeBill]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CouponExchangePtypeBill](
		BillNumberId	INT NOT NULL,							--单据编号
		ID				INT IDENTITY(1,1) PRIMARY KEY NOT NULL,	--自增列
		PtypeId			VARCHAR(200)	NOT NULL,				--商品编号
		Qty				NUMERIC(24,10) NOT NULL DEFAULT(0),		--兑换数量
		UnitId			INT NOT NULL,							--兑换商品单位
		IsDefault		BIT NOT NULL DEFAULT(0)					--是否默认
		
	)
END
GO




SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

/**
创建人：罗淮文
日  期：2016-07-25
描  述：优惠券兑换商品方案主表
**/
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CouponExchangePtypeIndex]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CouponExchangePtypeIndex](
		BillNumberId	INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
		BillCode		VARCHAR(200) NOT NULL,	--单据编号
		BillName		VARCHAR(200) NOT NULL,	--单据名称
		BillDate		DATETIME NOT NULL,		--单据日期
		ETypeId			VARCHAR(200) NOT NULL,	--制单人
		IsVaild			BIT NOT NULL DEFAULT(0),--是否作废
		Comment			VARCHAR(256) NULL		--备注
	)
END
GO




/****** 对象:  Table [dbo].[CPCX_catalog]    脚本日期: 05/05/2010 14:47:10 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CPCX_catalog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CPCX_catalog](
		[NUM] [int] IDENTITY(1,1) NOT NULL,
		[barname] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[layer1] [int] NULL,
		[layer2] [int] NOT NULL CONSTRAINT [DF_CPCX_catalog_layer2]  DEFAULT (1),
		[layer3] [int] NOT NULL CONSTRAINT [DF_CPCX_catalog_layer3]  DEFAULT (1),
		[layer4] [int] NOT NULL CONSTRAINT [DF_CPCX_catalog_layer4]  DEFAULT (1),
		[layer5] [int] NOT NULL CONSTRAINT [DF_CPCX_catalog_layer5]  DEFAULT (1),
		[layer6] [int] NOT NULL CONSTRAINT [DF_CPCX_catalog_layer6]  DEFAULT (1),
		[bardescript] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[url] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[parent] [int] NULL,
		[son] [int] NULL,
		[soncount] [int] NOT NULL CONSTRAINT [DF_CPCX_catalog_soncount]  DEFAULT (0),
		[levelnum] [int] NULL CONSTRAINT [DF_CPCX_catalog_levelnum]  DEFAULT (1),
		[powername0] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[store] [int] NOT NULL CONSTRAINT [DF_CPCX_catalog_store]  DEFAULT (0),
		[nsave] [int] NULL,
		[breed] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CPCX_luntan]    脚本日期: 05/05/2010 14:47:11 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CPCX_luntan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CPCX_luntan](
		[New_Number] [int] NULL,
		[UserCode] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[FullName] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
		[Name] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Standard] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Type] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Area] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Unit] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[Manufacturer] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[ImageFile] [image] NULL,
		[FileType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[FileName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[FileLength] [int] NULL,
		[szDate] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[OpeatorID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ClickNum] [int] NULL CONSTRAINT [DF_CPCX_luntan_ClickNum]  DEFAULT (0),
		[FJBinaryContent] [image] NULL,
		[FJContentType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[FJContentLength] [int] NULL,
		[FJFileName] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CPCX_luntan' AND a.Name='Comment' and a.xtype=35
)
BEGIN
	ALTER TABLE CPCX_luntan ALTER COLUMN Comment VARCHAR(MAX)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CPCX_luntan]') AND name = N'PK_CPCX_luntan')
ALTER TABLE [dbo].[CPCX_luntan] DROP CONSTRAINT [PK_CPCX_luntan]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CPCX_LUNTAN') AND name = 'CIX_CPCX_LUNTAN_UserCode')
--DROP INDEX CIX_CPCX_LUNTAN_UserCode ON CPCX_LUNTAN 
CREATE CLUSTERED INDEX CIX_CPCX_LUNTAN_UserCode ON CPCX_LUNTAN(UserCode) 



------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CPCX_luntan' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CPCX_luntan 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[crm_btype]    脚本日期: 05/10/2010 17:24:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[crm_btype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[crm_btype](
		[parid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint] NOT NULL,
		[soncount] [int] NOT NULL,
		[sonnum] [int] NOT NULL,
		[UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS NULL,
		[FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[Area] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[TelAndAddress] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[PostCode] [char](10) COLLATE Chinese_PRC_CI_AS NULL,
		[Person] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[TaxNumber] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[BankAndAcount] [char](66) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[CreateDate] [datetime] NULL,
		[ARTotal] [numeric](18, 4) NULL,
		[APTotal] [numeric](18, 4) NULL,
		[ARTotal00] [numeric](18, 4) NULL,
		[APTotal00] [numeric](18, 4) NULL,
		[deleted] [bit] NOT NULL,
		[Client] [bit] NULL,
		[ARLimit] [numeric](18, 4) NULL,
		[initcomment] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[arapexplain] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[Tel1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Tel2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Tel3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Fax] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[WWW] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Bank] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BankName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Email] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkManId1] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMan1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkSex1] [bit] NULL,
		[LinkBirthDay1] [datetime] NULL,
		[LinkJob1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkCall1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkTel1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMobile1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkPost1] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkAddress1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkEmail1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkComment1] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkManId2] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMan2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkSex2] [bit] NULL,
		[LinkBirthDay2] [datetime] NULL,
		[LinkJob2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkCall2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkTel2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMobile2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkPost2] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkAddress2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkEmail2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkComment2] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[ARLimitTime] [numeric](18, 4) NULL,
		[paymentLTime] [numeric](18, 4) NULL,
		[SaleZekou] [numeric](18, 4) NULL,
		[BuyZekou] [numeric](18, 4) NULL,
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[Price] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[AreaTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[id] [int] IDENTITY(1,1) NOT NULL,
		[createor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[createorName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]
END	

GO

SET ANSI_PADDING OFF
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='ARTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN ARTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='APTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN APTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='ARTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN ARTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='APTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN APTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='ARLimit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN ARLimit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='ARLimitTime' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN ARLimitTime NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='paymentLTime' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN paymentLTime NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='SaleZekou' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN SaleZekou NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Crm_Btype' AND a.Name='BuyZekou' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Crm_Btype 
	ALTER COLUMN BuyZekou NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*==============================================================*/
/* Table: CRM_BtypeShared                                              */
/*==============================================================*/
IF NOT EXISTS (SELECT 1
            FROM  sysobjects
           WHERE  ID = OBJECT_ID('CRM_BtypeShared')
            AND   TYPE = 'U')
BEGIN 
	CREATE TABLE CRM_BtypeShared
	( 
		ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
		CRMBtypeID INT NOT NULL,
		SharedEtypeID VARCHAR(50) NOT NULL
	)
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[crm_linkman]    脚本日期: 05/10/2010 17:25:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[crm_linkman]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[crm_linkman](
		[id] [int] IDENTITY(1,1) NOT NULL,
		[createor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[createorName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Crm_BtypeId] [int] NULL,
		[LinkMan] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[LinkSex] [bit] NOT NULL,
		[LinkBirthDay] [datetime] NULL,
		[LinkJob] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkCall] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkTel] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMobile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkPost] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkAddress] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkEmail] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkComment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Deleted] [int] NOT NULL,
		[CreateDate] [datetime] NOT NULL
	) ON [PRIMARY]
END	

GO
SET ANSI_PADDING OFF
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*==============================================================*/
/* Table: CRM_LinkManShared                                     */
/*==============================================================*/
IF NOT EXISTS (SELECT 1
            FROM  sysobjects
           WHERE  ID = OBJECT_ID('CRM_LinkManShared')
            AND   TYPE = 'U')
BEGIN 
	CREATE TABLE CRM_LinkManShared
	( 
		ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
		CRMLinkManID INT NOT NULL,
		SharedEtypeID VARCHAR(50) NOT NULL
	)
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CRM_Message]    脚本日期: 05/10/2010 17:25:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Crm_Message]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Crm_Message](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[CreateDate] [datetime] NULL,
		[SenderTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ReceiverTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Content] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[IsRead] [bit] NULL,
		[CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Type] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__CRM_Messag__Type__3B0BC30C]  DEFAULT ('Normal'),
		[BeginDate] [datetime] NOT NULL CONSTRAINT [DF__CRM_Messa__Begin__3BFFE745]  DEFAULT (getdate()),
		[Source] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__CRM_Messa__Sourc__3CF40B7E]  DEFAULT ('User'),
		[SourceTypeID] [int] NOT NULL,
		[ReadTime] [datetime] NOT NULL CONSTRAINT [DF__CRM_Messa__ReadT__0F4D3C5F]  DEFAULT ('1978-03-22'),
		[SenderName] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__CRM_Messa__Sende__10416098]  DEFAULT (''),
		[ReceiverName] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__CRM_Messa__Recei__113584D1]  DEFAULT (''),
		[SendMsgID] [int] NOT NULL CONSTRAINT [DF__CRM_Messa__SendM__1229A90A]  DEFAULT (0)
	) ON [PRIMARY]
END

GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CRM_MESSAGE') AND name = 'NCIX_CRM_MESSAGE_ID')
--DROP INDEX NCIX_CRM_MESSAGE_ID ON CRM_MESSAGE 

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Crm_Message]') AND name = N'IX_CRM_Message')
BEGIN
	IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CRM_MESSAGE') AND name = 'NCIX_CRM_MESSAGE_ID')
		CREATE NONCLUSTERED INDEX NCIX_CRM_MESSAGE_ID ON CRM_MESSAGE(ID) 
END

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CRM_MessageNoRead]    脚本日期: 05/10/2010 17:25:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Crm_MessageNoRead]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Crm_MessageNoRead](
		[ID] [int] NOT NULL CONSTRAINT [DF__CRM_MessageN__ID__16EE5E27]  DEFAULT (0),
		[CreateDate] [datetime] NULL CONSTRAINT [DF__CRM_Messa__Creat__17E28260]  DEFAULT (getdate()),
		[SenderTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF__CRM_Messa__Sende__18D6A699]  DEFAULT (''),
		[ReceiverTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF__CRM_Messa__Recei__19CACAD2]  DEFAULT (''),
		[Content] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF__CRM_Messa__Conte__1ABEEF0B]  DEFAULT (''),
		[IsRead] [bit] NULL CONSTRAINT [DF__CRM_Messa__IsRea__1BB31344]  DEFAULT (0),
		[CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF__CRM_Messa__Creat__1CA7377D]  DEFAULT (''),
		[Type] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__CRM_Messag__Type__1D9B5BB6]  DEFAULT ('Normal'),
		[BeginDate] [datetime] NOT NULL CONSTRAINT [DF__CRM_Messa__Begin__1E8F7FEF]  DEFAULT (getdate()),
		[Source] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__CRM_Messa__Sourc__1F83A428]  DEFAULT ('User'),
		[SourceTypeID] [int] NOT NULL,
		[ReadTime] [datetime] NOT NULL CONSTRAINT [DF__CRM_Messa__ReadT__216BEC9A]  DEFAULT ('1978-03-22'),
		[SenderName] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__CRM_Messa__Sende__226010D3]  DEFAULT (''),
		[ReceiverName] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__CRM_Messa__Recei__2354350C]  DEFAULT (''),
		[SendMsgID] [int] NOT NULL CONSTRAINT [DF__CRM_Messa__SendM__24485945]  DEFAULT (0)	 
	)
END	
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------
------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CRM_MESSAGENOREAD') AND name = 'CIX_CRM_MESSAGENOREAD_ID')
DROP INDEX CIX_CRM_MESSAGENOREAD_ID ON CRM_MESSAGENOREAD 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CRM_MESSAGENOREAD') AND name = 'NCIX_CRM_MESSAGENOREAD_CreatorTypeID_ReceiverTypeID_BeginDate')
DROP INDEX NCIX_CRM_MESSAGENOREAD_CreatorTypeID_ReceiverTypeID_BeginDate ON CRM_MESSAGENOREAD 

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRM_MessageNoRead]') AND name = N'PK_CRM_MessageNoRead')
BEGIN
	CREATE UNIQUE CLUSTERED INDEX PK_CRM_MessageNoRead ON dbo.CRM_MessageNoRead
	(
		[ID]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Crm_MessageNoRead]') AND name = N'IX_CRM_MessageNoRead')
BEGIN
	CREATE NONCLUSTERED INDEX IX_CRM_MessageNoRead ON dbo.CRM_MessageNoRead
	(
		[CreatorTypeID],
		[ReceiverTypeID],
		[BeginDate]
	) ON [PRIMARY]
END
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CRM_Schedule]    脚本日期: 05/10/2010 17:25:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Crm_Schedule]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Crm_Schedule](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TYPE] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CRM_Schedule_TYPE]  DEFAULT ('Event'),
		[CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Date] [datetime] NOT NULL,
		[CreateDate] [datetime] NULL,
		[AlterDate] [datetime] NULL,
		[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CRM_Schedule_Title]  DEFAULT (''),
		[Content] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CRM_Schedule_Content]  DEFAULT (''),
		[IsAlert] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_CRM_Schedule_IsAlert]  DEFAULT ('0'),
		[ViewEtypeIDS] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_CRM_Schedule_ViewEtypeIDS]  DEFAULT ('')
	) ON [PRIMARY]
END	

GO
SET ANSI_PADDING OFF
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CRM_Schedule_Etype]    脚本日期: 05/10/2010 17:25:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Crm_Schedule_Etype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Crm_Schedule_Etype](
		[Schedule_ID] [int] NOT NULL,
		[EtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]
END	

GO
SET ANSI_PADDING OFF
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 
		表名:基本信息自定义类型表头
		时间:2012-6-8
		作者：张陈仁 
******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CustomBaseInforColumnsDefines]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CustomBaseInforColumnsDefines
	(
		BaseType        VARCHAR(50),
		CustomerType	VARCHAR(50),
		CustomerOrder	INT
	)
END

GO  
  IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CustomBaseInforColumnsDefines' AND a.Name='CustomerCaption'--自定义列名名称
   )
  BEGIN
	ALTER TABLE CustomBaseInforColumnsDefines ADD CustomerCaption VARCHAR(500) DEFAULT '' NULL
  END
GO

GO
  UPDATE CustomBaseInforColumnsDefines SET BaseType='gtype' WHERE BaseType='gbtype'
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
/*==============================================================*/
/* Table: CustomBillColumns                                     */
/*==============================================================*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CustomBillColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table CustomBillColumns (
	   ID                   bigint               identity(1,1),
	   billnumberid         numeric(18,0)        null,
	   billtype             varchar(100)         null,
	   Costom1              VARCHAR(600)         null,
	   Costom2              VARCHAR(600)         null,
	   Costom3              VARCHAR(600)         null,
	   Costom4              VARCHAR(600)         null,
	   Costom5              VARCHAR(600)         null,
	   Costom6              VARCHAR(600)         null,
	   Costom7              VARCHAR(600)         null,
	   Costom8              VARCHAR(600)         null,
	   Costom9              VARCHAR(600)         null,
	   Costom10             VARCHAR(600)         null,
	   Costom11             VARCHAR(600)         null,
	   Costom12             VARCHAR(600)         null,
	   Costom13             VARCHAR(600)         null,
	   Costom14             VARCHAR(600)         null,
	   Costom15             VARCHAR(600)         null,
	   Costom16             VARCHAR(600)         null,
	   Costom17             VARCHAR(600)         null,
	   Costom18             VARCHAR(600)         null,
	   Costom19             VARCHAR(600)         null,
	   Costom20             VARCHAR(600)         null
	)
END
GO


IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CustomBillColumns') AND name = 'NCIX_BILLTYPE')
DROP INDEX NCIX_BILLTYPE ON CustomBillColumns 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CustomBillColumns') AND name = 'NCIX_BILLID')
DROP INDEX NCIX_BILLID ON CustomBillColumns 
CREATE NONCLUSTERED INDEX NCIX_BILLID ON CustomBillColumns(billnumberid)

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 
		表名:单据体自定义类型表头
		时间:2012-6-8
		作者：张陈仁 
******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CustomBillColumnsDefines]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CustomBillColumnsDefines
	(
		BillType        INT,
		CustomerType	VARCHAR(50),
		CustomerOrder	INT
	)
END

GO  
  IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CustomBillColumnsDefines' AND a.Name='CustomerCaption'--自定义列名名称
   )
  BEGIN
	ALTER TABLE CustomBillColumnsDefines ADD CustomerCaption VARCHAR(500) DEFAULT '' NULL
  END
GO




-----------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CustomBillColumnsDefines') AND name = 'NCIX_BILLTYPE')
DROP INDEX NCIX_BILLTYPE ON CustomBillColumnsDefines 
CREATE NONCLUSTERED INDEX [NCIX_BILLTYPE] ON [dbo].[CustomBillColumnsDefines] 
(
	[BillType] ASC,
	[CustomerOrder] ASC
)
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
/*==============================================================*/
/* Table: 单据表体自定义列                                 */
/*==============================================================*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CustomBillDetailColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
create table CustomBillDetailColumns (
   ID                   bigint               identity(1,1),
   billnumberid         numeric(18,0)        null,
   billtype             varchar(100)         null,
   detailId             bigint               null,
   InOrOut              CHAR(1)              NULL,
   Costom1              VARCHAR(600)         null,
   Costom2              VARCHAR(600)         null,
   Costom3              VARCHAR(600)         null,
   Costom4              VARCHAR(600)         null,
   Costom5              VARCHAR(600)         null,
   Costom6              VARCHAR(600)         null,
   Costom7              VARCHAR(600)         null,
   Costom8              VARCHAR(600)         null,
   Costom9              VARCHAR(600)         null,
   Costom10             VARCHAR(600)         null,
   Costom11             VARCHAR(600)         null,
   Costom12             VARCHAR(600)         null,
   Costom13             VARCHAR(600)         null,
   Costom14             VARCHAR(600)         null,
   Costom15             VARCHAR(600)         null,
   Costom16             VARCHAR(600)         null,
   Costom17             VARCHAR(600)         null,
   Costom18             VARCHAR(600)         null,
   Costom19             VARCHAR(600)         null,
   Costom20             VARCHAR(600)         null
)
GO

--------------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CustomBillDetailColumns') AND name = 'NCIX_BILLTYPE')
DROP INDEX NCIX_BILLTYPE ON CustomBillDetailColumns 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CustomBillDetailColumns') AND name = 'NCIX_DETAILID')
DROP INDEX NCIX_DETAILID ON CustomBillDetailColumns 
CREATE NONCLUSTERED INDEX NCIX_DETAILID ON CustomBillDetailColumns(detailId)
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 
		表名:单据体自定义类型表体
		时间:2012-6-8
		作者：张陈仁 
******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CustomBillDetailColumnsDefines]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CustomBillDetailColumnsDefines
	(
		BillType        INT,
		CustomerType	VARCHAR(50),
		CustomerOrder	INT,
		InOrOut         CHAR(1)
	)
END

GO  
  IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CustomBillDetailColumnsDefines' AND a.Name='CustomerCaption'--自定义列名名称
   )
  BEGIN
	ALTER TABLE CustomBillDetailColumnsDefines ADD CustomerCaption VARCHAR(500) DEFAULT '' NULL
  END
GO

-------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CustomBillDetailColumnsDefines') AND name = 'NCIX_BILLTYPE')
DROP INDEX NCIX_BILLTYPE ON CustomBillDetailColumnsDefines 
CREATE NONCLUSTERED INDEX [NCIX_BILLTYPE] ON [dbo].[CustomBillDetailColumnsDefines] 
(
	[BillType] ASC,
	[CustomerOrder] ASC,
	[InOrOut]  ASC
)
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
自定义操作日志记录
*/
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[customchangelog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[customchangelog] (
		[id] [int] IDENTITY (1, 1) NOT NULL ,		
		[dateTime] [datetime] NOT NULL ,	
		[ipAddress] [varchar] (15) COLLATE Chinese_PRC_CI_AS NULL ,
		[formname]  [varchar](100) COLLATE Chinese_PRC_CI_AS NULL ,
		[datafiled]  [varchar](100) NULL ,
		[label]  [varchar](100) NULL ,
		[changefiled]  [varchar](100) NULL ,
		[logtext]  [varchar](300) NULL ,
		[loginUserId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  表名：自定义列名表
  作者：张陈仁
  时间：2012-05-09
*/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[CustomColumnConfig]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[CustomColumnConfig](
	[CustomName] [varchar](100) NULL,
	[CustomNewName] [varchar](100) NULL
    ) ON [PRIMARY]
    
   -- DELETE FROM CustomColumnConfig
    
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息1','附加信息1')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息2','附加信息2')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息3','附加信息3')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息4','附加信息4')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息5','附加信息5')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息6','附加信息6')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息7','附加信息7')  
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息8','附加信息8')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息9','附加信息9')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息10','附加信息10')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息11','附加信息11')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息12','附加信息12')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息13','附加信息13')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息14','附加信息14')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息15','附加信息15')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息16','附加信息16')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息17','附加信息17')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息18','附加信息18')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息19','附加信息19')
    INSERT INTO CustomColumnConfig (CustomName,CustomNewName) VALUES ('附加信息20','附加信息20')

END
GO


	

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





/****** Object:  Table [dbo].[CustomFieldData]    
        Script Date: 04/21/2012 16:15:46 
        autor：  张陈仁
******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CustomFieldData]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CustomFieldData](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[configKind] [varchar](50) NULL,
		[profile] [varchar](MAX) NULL,
		[userId] [varchar](50) NULL,
		[elementId] [varchar](100) NOT NULL,
		[content] TEXT NOT NULL,
	 CONSTRAINT [PK_CustomFieldData] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

SET ANSI_PADDING OFF
GO

GO
  UPDATE CustomFieldData SET elementId='gtype' WHERE elementId='gbtype'
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CustomFieldData' AND a.Name='content' and a.xtype=35
)
BEGIN
	ALTER TABLE CustomFieldData ALTER COLUMN content VARCHAR(MAX)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

if NOT EXISTS (select 1 from  sysobjects where  id = object_id('customPtypeItems') and   type = 'U')
BEGIN
	/*==============================================================*/
	/* Table:商品自由项--组合                                    */
	/*==============================================================*/
	CREATE TABLE [dbo].[customPtypeItems](
		[id] [bigint] IDENTITY(1,1) NOT NULL,
		[usercode] [varchar](300) NULL,
		[fullname] [varchar](300) NULL,
		[referenceIdList] [varchar](max) NULL,
		[isUse] [int] default 0
	) 
	ON [PRIMARY]
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
if NOT EXISTS (select 1 from  sysobjects where  id = object_id('CustomReference') and   type = 'U')
BEGIN

/*==============================================================*/
/* Table: CustomReference                                       */
/*==============================================================*/
CREATE TABLE [dbo].[CustomReference](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[itemsId] [bigint] NOT NULL,
	[selfDataId] [bigint] NULL,
	[childCount] [int] NOT NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[CustomReference] ADD  DEFAULT ((0)) FOR [childCount]
END
GO




------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

if NOT EXISTS (select 1 from  sysobjects where  id = object_id('CustomReferenceValue') and   type = 'U')
BEGIN

/*==============================================================*/
/* Table: CustomReferenceValue                                  */
/*==============================================================*/
CREATE TABLE [dbo].[CustomReferenceValue](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[itemsid] [bigint] NOT NULL,
	[ReferenId] [varchar](max) NOT NULL,
	[Fullname] [varchar](max) NULL,
	PosDataVersion timestamp
) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[CustomReferenceValue]') and name = 'XiWaMaxNumber' )
	BEGIN
		ALTER TABLE dbo.CustomReferenceValue ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
	END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[CustomReferenceValue]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.CustomReferenceValue ADD  PosDataVersion timestamp
END
GO

UPDATE CustomReferenceValue SET XiWaMaxNumber = 0 WHERE XiWaMaxNumber IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[DBCONFIG]    脚本日期: 05/05/2010 14:47:12 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DbConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[DbConfig](
		[OFFLINE] [bit] NOT NULL CONSTRAINT [DF_DBCONFIG_OFFLINE]  DEFAULT (0),
		[FLAG] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[STOCKID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--默认仓库表
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DefaultStock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE DefaultStock
(
	ID				NUMERIC(18,0) IDENTITY(1,1),	
	Ptypeid			VARCHAR(50)	  NOT NULL,		    --商品的ID
	Stypeid			VARCHAR(50)	  NOT NULL,			--分支机构ID
	--SFullName		VARCHAR(100)  NOT NULL,			--分支机构名称	 
	ktypeid			VARCHAR(50)   NULL DEFAULT(''),	--默认仓库ID			 
	--kFullName		VARCHAR(100)  NULL DEFAULT('')	--默认仓库名称 
	 
)
END

GO

------------------------------------------表修改区域-开始-------------------------------------------------
IF NOT EXISTS (select name from syscolumns where id = object_id(N'[dbo].[DefaultStock]') and name = 'Ptypeid' )
BEGIN
	ALTER TABLE dbo.DefaultStock ADD
		Ptypeid VARCHAR(50) NOT NULL
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[DefaultStock]') AND name = 'CargoId' )
BEGIN
	ALTER TABLE dbo.DefaultStock ADD
		CargoId INT NOT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域-结束-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[MoveBill]    脚本日期: 05/05/2010 14:48:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryApplyBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[DeliveryApplyBill](
		[ID]			[int] IDENTITY(1,1) NOT NULL,
	    ShowOrder		INT DEFAULT(0),
		[BillNumberId]	[numeric](10, 0) NOT NULL,
		[PtypeId]		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty]			[numeric](24, 10) NULL  DEFAULT (0),
		[Price]			[numeric](24, 10) NULL,
		[Total]			[numeric](24, 10) NULL,
		UnitID          int             Default(0)  NULL,
		MUnitID         int             Default(0)  NULL,
		MQty            numeric(24,10)  Default(0)  NULL,
		MUnitRate       numeric(24,10)  Default(0)  NULL,
		MUnitMsg        varchar(50)          null,
		MPrice			numeric(24,10)  Default(0)  NULL,
		ItemID          bigint               null,
	    IsCombined      int  NULL,
		[Comment]		[varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		CargoID			INT				DEFAULT(0) NULL,
	    DeliveryQty		DECIMAL(24,10) NULL DEFAULT(0) --门店配送单数量
	) ON [PRIMARY] 


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
					
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[DeliveryBackBill]    脚本日期: 12/12/2019 14:48:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[DeliveryBackBill](
		[ID]			[int] IDENTITY(1,1) NOT NULL,
	    ShowOrder		INT DEFAULT(0),
		[BillNumberId]	[numeric](10, 0) NOT NULL,
		[Serial] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		outktypeid		varchar(50),
		outCargoID		INT				DEFAULT(0) NULL,
		inktypeid		varchar(50),
		inCargoID		INT				DEFAULT(0) NULL,
		[PtypeId]		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		ItemID          bigint               null,
	    IsCombined      int  NULL,
		GoodsNumber		[varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ProduceDate		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ValidDate		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[Qty]			[numeric](18, 4) NULL   DEFAULT (0),
		[Price]			[numeric](18, 4) NULL,
		[Total]			[numeric](18, 4) NULL,
		UnitID          int             Default(0)  NULL,
		MUnitID         int             Default(0)  NULL,
		MQty            numeric(22,10)  Default(0)  NULL,
		MUnitRate       numeric(22,10)  Default(0)  NULL,
		MUnitMsg        varchar(50)          null,
		MPrice			numeric(22,10)  Default(0)  NULL,
		NUnitID              int             Default(0)  NULL,
		NUnitRate             numeric(22,10)  Default(0)  NULL,
		NQty                 numeric(22,10)  Default(0)  NULL,
		NUnitMsg             varchar(50)          null,
		[Comment]		[varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		InflowQty		NUMERIC(24,10) NULL DEFAULT(0), --上架数量
		InFactQty		NUMERIC(24,10) NULL DEFAULT(0),	--入库实物数量
		OutFactQty		NUMERIC(24,10) NULL DEFAULT(0)	--出库实物数量
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--门店配送单明细ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DeliveryBackBill' AND a.Name='DeliveryID'
)
BEGIN
		ALTER TABLE DeliveryBackBill ADD DeliveryID   INT NULL DEFAULT(0)
END
GO 

-- 修改上架单字段名
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DeliveryBackBill' AND a.Name='OnShelvesQty'
)
BEGIN
	EXEC sp_rename 'dbo.DeliveryBackBill.[OnShelvesQty]', 'InflowQty'
END
GO 

--重新添加上架单字段
IF	NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DeliveryBackBill' AND a.Name='InflowQty'
)
BEGIN
	ALTER TABLE DeliveryBackBill ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO 

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBackBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.DeliveryBackBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DeliveryBackBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBackBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.DeliveryBackBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DeliveryBackBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBackBill',N'U') AND Name='GoodsCostPrice')
BEGIN
		ALTER TABLE dbo.DeliveryBackBill
		ADD GoodsCostPrice  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBackBill',N'U') AND Name='GoodsCostTotal')
BEGIN
		ALTER TABLE dbo.DeliveryBackBill
		ADD GoodsCostTotal  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBackBill',N'U') AND Name='HandZeroCost')
BEGIN
		ALTER TABLE dbo.DeliveryBackBill
		ADD HandZeroCost  int  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBackBill',N'U') AND Name='InputCostPrice')
BEGIN
		ALTER TABLE dbo.DeliveryBackBill
		ADD InputCostPrice  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
					
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[DeliveryBill]    脚本日期: 2019-12-11 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[DeliveryBill](
		[ID]			[int] IDENTITY(1,1) NOT NULL,
	    ShowOrder		INT DEFAULT(0),
		[BillNumberId]	[numeric](10, 0) NOT NULL,
		[Serial] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ktypeidout		varchar(50),
		CargoIDout		INT				DEFAULT(0) NULL,
		ktypeidin		varchar(50),
		CargoIDin		INT				DEFAULT(0) NULL,
		[PtypeId]		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		ItemID          bigint               null,
	    IsCombined      int  NULL,
		GoodsNumber		[varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ProduceDate		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ValidDate		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[Qty]			[numeric](18, 4) NULL   DEFAULT (0),
		[Price]			[numeric](18, 4) NULL,
		[Total]			[numeric](18, 4) NULL,
		UnitID          int             Default(0)  NULL,
		MUnitID         int             Default(0)  NULL,
		MQty            numeric(22,10)  Default(0)  NULL,
		MUnitRate       numeric(22,10)  Default(0)  NULL,
		MUnitMsg        varchar(50)          null,
		MPrice			numeric(22,10)  Default(0)  NULL,
		NUnitID              int             Default(0)  NULL,
		NUnitRate             numeric(22,10)  Default(0)  NULL,
		NQty                 numeric(22,10)  Default(0)  NULL,
		NUnitMsg             varchar(50)          null,
		[Comment]		[varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		PickedQty		NUMERIC(24,10) NULL DEFAULT(0), --拣货数量
	    CheckQty		NUMERIC(24,10) NULL DEFAULT(0), --验收数量
	    BackQty         NUMERIC(24,10) NULL DEFAULT(0), --退货数量
	    UnfinishedQty   NUMERIC(24,10) NULL DEFAULT(0),  --未完成数量
	    DeliveryApplyBillId	int	NULL	DEFAULT(0), 		--要货申请单明细id
	    GoodsCostPrice			 NUMERIC(24, 10) 	DEFAULT(0),	-- 出库批次成本单价
		GoodsCostTotal 		 NUMERIC(24, 10)  DEFAULT(0),
		HandZeroCost				INT		DEFAULT(0),	-- 手工指定成本单价
		InFactQty		NUMERIC(24,10) NULL DEFAULT(0),	--入库实物数量
		OutFactQty		NUMERIC(24,10) NULL DEFAULT(0),	--出库实物数量
		SendedQty		DECIMAL(24,10) NULL DEFAULT(0)	--物流运输 已发运数量
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='SendedQty')
BEGIN
	ALTER TABLE dbo.DeliveryBill
	ADD SendedQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DeliveryBill SET SendedQty=0 WHERE SendedQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.DeliveryBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DeliveryBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.DeliveryBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DeliveryBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='UnfinishedQty')
BEGIN
		ALTER TABLE dbo.DeliveryBill
		ADD UnfinishedQty  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='DeliveryApplyBillId')
BEGIN
		ALTER TABLE dbo.DeliveryBill
		ADD DeliveryApplyBillId  INT  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='GoodsCostPrice')
BEGIN
		ALTER TABLE dbo.DeliveryBill
		ADD GoodsCostPrice  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='GoodsCostTotal')
BEGIN
		ALTER TABLE dbo.DeliveryBill
		ADD GoodsCostTotal  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='HandZeroCost')
BEGIN
		ALTER TABLE dbo.DeliveryBill
		ADD HandZeroCost  int  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='InputCostPrice')
BEGIN
		ALTER TABLE dbo.DeliveryBill
		ADD InputCostPrice  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryBill',N'U') AND Name='BackQty')
BEGIN
		ALTER TABLE dbo.DeliveryBill
		ADD BackQty  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
					
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[MoveBill]    脚本日期: 05/05/2010 14:48:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryCheckBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[DeliveryCheckBill](
		[ID]			[int] IDENTITY(1,1) NOT NULL,
	    ShowOrder		INT DEFAULT(0),
		[BillNumberId]	[numeric](10, 0) NOT NULL,
		[Serial] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		outktypeid		varchar(50),
		outCargoID		INT				DEFAULT(0) NULL,
		inktypeid		varchar(50),
		inCargoID		INT				DEFAULT(0) NULL,
		[PtypeId]		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		ItemID          bigint               null,
	    IsCombined      int  NULL,
		GoodsNumber		[varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ProduceDate		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ValidDate		[varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[Qty]			[numeric](18, 4) NULL   DEFAULT (0),
		[Price]			[numeric](18, 4) NULL,
		[Total]			[numeric](18, 4) NULL,
		UnitID          int             Default(0)  NULL,
		MUnitID         int             Default(0)  NULL,
		MQty            numeric(22,10)  Default(0)  NULL,
		MUnitRate       numeric(22,10)  Default(0)  NULL,
		MUnitMsg        varchar(50)          null,
		MPrice			numeric(22,10)  Default(0)  NULL,
		NUnitID              int             Default(0)  NULL,
		NUnitRate             numeric(22,10)  Default(0)  NULL,
		NQty                 numeric(22,10)  Default(0)  NULL,
		NUnitMsg             varchar(50)          null,
		[Comment]		[varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		InflowQty		NUMERIC(24,10) NULL DEFAULT(0), --上架数量
		InFactQty		NUMERIC(24,10) NULL DEFAULT(0),	--入库实物数量
		OutFactQty		NUMERIC(24,10) NULL DEFAULT(0)	--出库实物数量
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--门店配送单明细ID
IF	NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DeliveryCheckBill' AND a.Name='DeliveryID'
)
BEGIN
	ALTER TABLE DeliveryCheckBill ADD DeliveryID   INT NULL DEFAULT(0)
END
GO 
-- 修改上架单字段名
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DeliveryCheckBill' AND a.Name='OnShelvesQty'
)
BEGIN
	EXEC sp_rename 'dbo.DeliveryCheckBill.[OnShelvesQty]', 'InflowQty'
END
GO 

--重新添加上架单字段
IF	NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DeliveryCheckBill' AND a.Name='InflowQty'
)
BEGIN
	ALTER TABLE DeliveryCheckBill ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryCheckBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.DeliveryCheckBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DeliveryCheckBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryCheckBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.DeliveryCheckBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DeliveryCheckBill SET InFactQty=0 WHERE InFactQty IS NULL
GO 

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryCheckBill',N'U') AND Name='GoodsCostPrice')
BEGIN
		ALTER TABLE dbo.DeliveryCheckBill
		ADD GoodsCostPrice  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryCheckBill',N'U') AND Name='GoodsCostTotal')
BEGIN
		ALTER TABLE dbo.DeliveryCheckBill
		ADD GoodsCostTotal  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryCheckBill',N'U') AND Name='HandZeroCost')
BEGIN
		ALTER TABLE dbo.DeliveryCheckBill
		ADD HandZeroCost  int  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DeliveryCheckBill',N'U') AND Name='InputCostPrice')
BEGIN
		ALTER TABLE dbo.DeliveryCheckBill
		ADD InputCostPrice  NUMERIC(24,10)  NULL DEFAULT(0) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
					
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Department]    脚本日期: 05/05/2010 14:47:13 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Department]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Department](
		[typeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[parid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [int] NOT NULL,
		[sonnum] [int] NOT NULL,
		[soncount] [int] NOT NULL,
		[usercode] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Department_usercode]  DEFAULT (''),
		[FullName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Department_FullName]  DEFAULT (''),
		[Name] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Department_Comment]  DEFAULT (''),
		[deleted] [bit] NOT NULL CONSTRAINT [DF_Department_deleted]  DEFAULT (0),
		[Tel] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMan] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Fax] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[rec] [int] IDENTITY(1,1) NOT NULL,
		[namepy] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Department_nameby]  DEFAULT (''),
		[parrec] [int] NOT NULL CONSTRAINT [DF_Department_parrec]  DEFAULT (0),
		[OrderNo] [int] NOT NULL CONSTRAINT [DF_Department_OrderNo]  DEFAULT (0),
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0)
	) ON [PRIMARY]

	-- 初始化部门
	Delete from DepartMent
	INSERT INTO DepartMent (typeid,parid,leveal,sonnum,soncount,usercode,fullname,Name,Comment,deleted,Tel,LinkMan,Fax,namepy,parrec,OrderNo)VALUES ('00000','root',0,0,0,'所有部门','所有部门','','',0,'','','','',0,0)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('Department') and name='WdSyncFlag')
BEGIN
	ALTER TABLE Department ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
--提供XiWa交互功能，每次修改或者新增基本信息后，必须在原来的值上加1 谢吉康 2010-05-04
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Department]') and name = 'XiWaMaxNumber' )
	BEGIN
		BEGIN TRANSACTION
		SET QUOTED_IDENTIFIER ON
		SET ARITHABORT ON
		SET NUMERIC_ROUNDABORT OFF
		SET CONCAT_NULL_YIELDS_NULL ON
		SET ANSI_NULLS ON
		SET ANSI_PADDING ON
		SET ANSI_WARNINGS ON
		COMMIT
		BEGIN TRANSACTION
		ALTER TABLE dbo.Department ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
		
		COMMIT
	END
GO
UPDATE Department SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL OR XiWaMaxNumber = 0
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO

-- ========================================================================
-- 修改人：		刘飞
-- 修改时间:	2017-03-06
-- 修改内容:	增加字段“使用部门”
-- ========================================================================

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[DepBill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [DepBill](
		Id INT PRIMARY KEY IDENTITY(1,1)
		,BillNumberId INT NOT NULL DEFAULT(0)
		,AssetCardId INT NOT NULL DEFAULT(0)
		,Depreciation NUMERIC(22,10)
		,Comment VARCHAR(255)
		,WorkTime NUMERIC(22,10) -- 工作量
		,WorkUnit VARCHAR(500) --工作量单位
		,DTypeId VARCHAR(50) NOT NULL DEFAULT('') --使用部门
		,[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	)
END

GO
------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'DepBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.DepBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'DepBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.DepBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('DepBill') AND name='Depreciation' AND system_type_id=108 AND ([precision]<>22 or scale<>10))
	ALTER TABLE DepBill ALTER COLUMN Depreciation NUMERIC(22,10) 
go

IF NOT EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('DepBill') AND name='WorkTime')
	ALTER TABLE DepBill ADD WorkTime NUMERIC(22,10) -- 工作量
GO

IF NOT EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('DepBill') AND name='WorkUnit')
	ALTER TABLE DepBill ADD WorkUnit VARCHAR(500) --工作量单位
GO

-- 清除字段Dfullname
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'Dfullname';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='DepBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.all_columns b
	LEFT JOIN sys.default_constraints a ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF NOT EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('DepBill') AND name='DTypeId')
BEGIN
	ALTER TABLE DepBill ADD DTypeId VARCHAR(50) NOT NULL DEFAULT('');--使用部门
END
GO
------------------------------------------表修改区域结束-----------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepBill' AND a.Name='Depreciation' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepBill 
	ALTER COLUMN Depreciation NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepBill' AND a.Name='WorkTime' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepBill 
	ALTER COLUMN WorkTime NUMERIC(24,10)
    END

GO                              
------------------------------------------修改字段小数位数区域结束-----------------------------------------------

------------------------------------------表数据更新开始-----------------------------------------------
IF EXISTS(SELECT TOP 1 1 FROM dbo.DepBill MB LEFT JOIN dbo.Ac_AssetsCards AAC ON MB.AssetCardId=AAC.Id
	WHERE ISNULL(MB.DTypeId,'')='')
BEGIN
	UPDATE MB SET MB.DTypeId=AAC.DTypeId 
	FROM dbo.DepBill MB LEFT JOIN dbo.Ac_AssetsCards AAC ON MB.AssetCardId=AAC.Id
	WHERE ISNULL(MB.DTypeId,'')=''
END
GO
------------------------------------------表数据更新结束-----------------------------------------------



SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING OFF
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'DepositBillDetail') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE DepositBillDetail
	(
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BillnumberID] [int] NULL,
		[DepositBillID] [int] NULL,
		[PID] [int] NULL,
		[total] [numeric](24, 10) NULL,
		[price] [numeric](24, 10) NULL,
		[saleqty] [numeric](24, 10) NULL,
		[depositedqty] [numeric](24, 10) NULL,
		[depositqty] [numeric](24, 10) NULL,
		[pickupqty] [numeric](24, 10) NULL,
		[pickedupqty] [numeric](24, 10) NULL,
		[depositprice] [numeric](24, 10) NULL,
		[remainqty] [numeric](24, 10) NULL,
		[pickupprice] [numeric](24, 10) NULL,
		[unpickupqty] [numeric](24, 10) NULL,
		[unpickupmoney] [numeric](24, 10) NULL
	)
END

GO 

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='DepositBillDetail' AND a.Name='PosBillDetailID')
BEGIN
	ALTER TABLE dbo.DepositBillDetail ADD
			PosBillDetailID int NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='DepositBillDetail' AND a.Name='UnitID')
BEGIN
	ALTER TABLE dbo.DepositBillDetail ADD
			UnitID int NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='DepositBillDetail' AND a.Name='BaseUnitId')
BEGIN
	ALTER TABLE dbo.DepositBillDetail ADD
			BaseUnitId int NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='DepositBillDetail' AND a.Name='UnitRate')
BEGIN
	ALTER TABLE dbo.DepositBillDetail ADD
			UnitRate NUMERIC(24,10) NULL DEFAULT(1)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='DepositBillDetail' AND a.Name='Guid')
BEGIN
	ALTER TABLE dbo.DepositBillDetail ADD
			Guid VARCHAR(50)
END
GO

-----------------------------------创建索引区域-----------------------
IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('DepositBillDetail') AND name = 'CIX_DepositBillDetail_DepositBillID')
	CREATE INDEX CIX_DepositBillDetail_DepositBillID ON DepositBillDetail(DepositBillID ASC);

IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('DepositBillDetail') AND name = 'CIX_DepositBillDetail_ID')
	CREATE INDEX CIX_DepositBillDetail_ID ON DepositBillDetail(ID ASC);

GO


SET ANSI_PADDING OFF
GO



SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING OFF
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'DepositBillIndex') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE DepositBillIndex     
	(
		[DepositBillID] [int] IDENTITY(1,1) NOT NULL,
		[PosBillnumberID] [int] NULL,
		[DepositBillTime] [varchar](50) NULL,
		[PickUpBillTime] [varchar](50) NULL,
		[SaleTime] [varchar](50) NULL,
		[BillCode] [varchar](50) NULL,
		[billqty]  [NUMERIC](24,10) NULL,
		[SID] [int] NULL,
		[BID] [int] NULL,
		[KID] [int] NULL,
		[PosID] [int] NULL,
		[EID] [int] NULL,
		[IsUpLoad] [int] DEFAULT(0),
		[DepositPerson] [varchar](200) NULL,		--寄存人员
		[PickUpPerson] [varchar](200) NULL			--取货人员
	)
END

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepositBillIndex' AND a.Name='Billtype'
)
BEGIN
	ALTER TABLE DepositBillIndex 
		DROP COLUMN Billtype
END

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='DepositBillIndex' AND a.Name='DepositIndexID')
BEGIN
	ALTER TABLE dbo.DepositBillIndex ADD
			DepositIndexID int NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='DepositBillIndex' AND a.Name='Guid')
BEGIN
	ALTER TABLE dbo.DepositBillIndex ADD
			[Guid] VARCHAR(50) NULL 
END
GO

IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('DepositBillIndex') AND name = 'CIX_DepositBillIndex_DepositBillID')
	CREATE INDEX CIX_DepositBillIndex_DepositBillID ON DepositBillIndex(DepositBillID ASC);

GO
SET ANSI_PADDING OFF
GO




GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[DepPlanBill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [DepPlanBill](
		Id INT PRIMARY KEY IDENTITY(1,1)
		,PlanId INT NOT NULL DEFAULT(0)
		,[Year] INT
		,[Month] INT
		,NDepMoney NUMERIC(18,10)
		,DepMoney NUMERIC(18,10)
		,NDepTotal NUMERIC(18,10)
		,DepTotal NUMERIC(18,10)
		,NNetValue NUMERIC(18,10)
		,NetValue NUMERIC(18,10)
	)
END

GO
------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-----------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepPlanBill' AND a.Name='NDepMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepPlanBill 
	ALTER COLUMN NDepMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepPlanBill' AND a.Name='DepMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepPlanBill 
	ALTER COLUMN DepMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepPlanBill' AND a.Name='NDepTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepPlanBill 
	ALTER COLUMN NDepTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepPlanBill' AND a.Name='DepTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepPlanBill 
	ALTER COLUMN DepTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepPlanBill' AND a.Name='NNetValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepPlanBill 
	ALTER COLUMN NNetValue NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepPlanBill' AND a.Name='NetValue' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepPlanBill 
	ALTER COLUMN NetValue NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[DepPlanIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [DepPlanIndex](
		Id INT PRIMARY KEY IDENTITY(1,1)
		,BillNumberId INT NOT NULL DEFAULT(0)
		,AssetCardId INT NOT NULL DEFAULT(0)
		,DepType INT NOT NULL DEFAULT(0)
		,Cid INT NOT NULL DEFAULT(0)
		,Rate NUMERIC(18,4)
		,Flag INT 
		,[DateTime] DATETIME
	)
END

GO
------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-----------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DepPlanIndex' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DepPlanIndex 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[DtypeSaleplan]    Script Date: 06/23/2011 11:21:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DetailDtypeSaleplan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[DetailDtypeSaleplan]---部门销售计划明细表
(
	[DtypeSaleplanID] int,             --明细计划总表ID
	[DetailTimeID] int NULL,	       --时间表ID
	[RatingValue] [decimal](18, 2) NULL,--额定值
	[PlanValue] [decimal](18, 2) NULL, ---计划值

        
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[DetailEtypeSaleplan]    Script Date: 06/24/2011 09:54:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DetailEtypeSaleplan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[DetailEtypeSaleplan]---人员销售计划明细表
(
	[EtypeSaleplanID] int,             --明细人员总表ID
	[DetailTimeID] int NULL,	       --时间表ID
	[RatingValue] [decimal](18, 2) NULL,--额定值
	[PlanValue] [decimal](18, 2) NULL, ---计划值

        
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[DetailStypeSaleplan]    Script Date: 06/23/2011 11:22:51 ******/
SET QUOTED_IDENTIFIER ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DetailStypeSaleplan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[DetailStypeSaleplan]---分支机构销售计划明细表
(
        
	[StypeSaleplanID] [int],             --分支机构明细总表ID
	[DetailTimeID] int NULL,	      --时间表ID
	[RatingValue] [decimal](18, 2) NULL,--额定值
	[PlanValue] [decimal](18, 2) NULL, ---计划值

        
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[DigitConfiguration]    脚本日期: 09/21/2015 14:46:48 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DigitConfiguration]')  AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[DigitConfiguration](
		[ItemId] [int],
		[ItemName] [varchar](20),
		[DisplayName] [varchar](20),
		[DecimalDigit] [int],
		[NumberFormat] [int]
	) ON [PRIMARY]
END
GO
--初始化配置信息
IF NOT EXISTS(SELECT * FROM DigitConfiguration)
BEGIN
	INSERT INTO DigitConfiguration(ItemId,ItemName,DisplayName,DecimalDigit,NumberFormat) VALUES(1,'qty','数量',4,0);--qty:数量
	INSERT INTO DigitConfiguration(ItemId,ItemName,DisplayName,DecimalDigit,NumberFormat) VALUES(2,'price','单价',4,0);--price:单价
	INSERT INTO DigitConfiguration(ItemId,ItemName,DisplayName,DecimalDigit,NumberFormat) VALUES(3,'total','金额',2,0);--total:金额	
	INSERT INTO DigitConfiguration(ItemId,ItemName,DisplayName,DecimalDigit,NumberFormat) VALUES(4,'discount','扣率',4,0);--discount:扣率
	INSERT INTO DigitConfiguration(ItemId,ItemName,DisplayName,DecimalDigit,NumberFormat) VALUES(5,'tax','税率',0,0);--tax:税率	
	INSERT INTO DigitConfiguration(ItemId,ItemName,DisplayName,DecimalDigit,NumberFormat) VALUES(6,'exchangeRate','汇率',4,0);--exchangeRate:汇率
	INSERT INTO DigitConfiguration(ItemId,ItemName,DisplayName,DecimalDigit,NumberFormat) VALUES(7,'percentage','百分比',2,0);--percentage:百分比
	INSERT INTO DigitConfiguration(ItemId,ItemName,DisplayName,DecimalDigit,NumberFormat) VALUES(8,'translateRate','换算率',4,0);--translateRate:换算率
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[DisassembleBill]    脚本日期: 05/05/2010 14:47:13 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DisassembleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[DisassembleBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL CONSTRAINT [DF_DisassembleBill_Qty]  DEFAULT (0),
		[costprice] [numeric](18, 4) NOT NULL CONSTRAINT [DF_DisassembleBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NOT NULL CONSTRAINT [DF_DisassembleBill_total]  DEFAULT (0),
		[inorout] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[outfactorydate] [datetime] NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_DisassembleBill_comment]  DEFAULT (''),
		[goodsno] [int] NULL CONSTRAINT [DF_DisassembleBill_goodsno]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_DisassembleBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_DisassembleBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_DisassembleBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_DisassembleBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_DisassembleBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_DisassembleBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_DisassembleBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_DisassembleBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_DisassembleBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_DisassembleBill_HandZeroCost]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1),
		CargoID				 INT NULL DEFAULT(0),
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    MUnitId INT NOT NULL DEFAULT(0), --大单位
	    MUnitRate NUMERIC(22,10) NOT NULL DEFAULT(1),--大单位换算率
	    MQty NUMERIC(22,10) NOT NULL DEFAULT(0), --大单位数量
	    CurMSalePrice NUMERIC(22,10) NOT NULL DEFAULT(0) -- 大单位单价
	    ,ShowOrder INT DEFAULT(0)
	    ,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
	    ,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
	    ,InFlowQty NUMERIC(24,10) NULL DEFAULT(0) --入库数量
	    ,InFactQty NUMERIC(24,10) NULL DEFAULT(0)
	    ,OutFactQty NUMERIC(24,10) NULL DEFAULT(0)
	    ,[DraftFlag] [bit] NOT NULL DEFAULT (1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	    ,[ShareFee]	NUMERIC(24,10) NULL DEFAULT(0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'DisassembleBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.DisassembleBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'DisassembleBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.DisassembleBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DisassembleBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.DisassembleBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DisassembleBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DisassembleBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.DisassembleBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DisassembleBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DisassembleBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.DisassembleBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.DisassembleBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'DisassembleBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE DisassembleBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE DisassembleBill SET PickedQty=0 WHERE PickedQty IS NULL
GO
IF NOT EXISTS(SELECT 1 FROM  SysColumns WHERE ID=OBJECT_ID(N'DisassembleBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.DisassembleBill
	ADD ShowOrder INT DEFAULT(0)
END
Go
	UPDATE DisassembleBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
Go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='KTypeID'
)
BEGIN
	ALTER TABLE DisassembleBill ADD KTypeID [varchar](50) NULL
END
GO

	UPDATE DisassembleBill
	SET KTypeID=b.KTypeID
	FROM BillIndex b
	WHERE DisassembleBill.BillNumberID=b.BillNumberID AND DisassembleBill.KTypeID IS NULL AND DisassembleBill.InOrOut='O'

	UPDATE DisassembleBill
	SET KTypeID=b.KTypeID2
	FROM BillIndex b
	WHERE DisassembleBill.BillNumberID=b.BillNumberID AND DisassembleBill.KTypeID IS NULL AND DisassembleBill.InOrOut='I'
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='IsUnit2'
)
BEGIN
	ALTER TABLE DisassembleBill ADD IsUnit2 [int] NOT NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE DisassembleBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE DisassembleBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='DisassembleBill' AND a.Name='CargoID')
BEGIN
	ALTER TABLE DisassembleBill ADD CargoID INT NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE DisassembleBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE DisassembleBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE DisassembleBill ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE DisassembleBill ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END

go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='MUnitId'
)
BEGIN
		ALTER TABLE DisassembleBill ADD MUnitId INT NOT NULL DEFAULT(0) --大单位
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE DisassembleBill ADD MUnitRate NUMERIC(22,10) NOT NULL DEFAULT(1)--大单位换算率
END
go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE DisassembleBill ADD MQty NUMERIC(22,10) NOT NULL DEFAULT(0) --大单位数量
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE DisassembleBill ADD CurMSalePrice NUMERIC(22,10) NOT NULL DEFAULT(0) -- 大单位单价
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE DisassembleBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0)
END
go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='ShareFee'
)
BEGIN
		ALTER TABLE DisassembleBill ADD ShareFee DECIMAL(24,10) NULL DEFAULT(0)
END
go
--
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('DisassembleBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table DisassembleBill drop constraint '+@dfname);
		
	ALTER TABLE DisassembleBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE DisassembleBill ADD CONSTRAINT DF_DisassembleBill_Serial DEFAULT('') FOR Serial

END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CargoSpace' UNION ALL SELECT 'MPrice';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='DisassembleBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('DISASSEMBLEBILL') AND name = 'CIX_DISASSEMBLEBILL_BillNumberID')
--DROP INDEX CIX_DISASSEMBLEBILL_BillNumberID ON DISASSEMBLEBILL 
CREATE CLUSTERED INDEX CIX_DISASSEMBLEBILL_BillNumberID ON DISASSEMBLEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('DISASSEMBLEBILL') AND name = 'NCIX_DISASSEMBLEBILL_Ptypeid')
--DROP INDEX NCIX_DISASSEMBLEBILL_Ptypeid ON DISASSEMBLEBILL 
CREATE NONCLUSTERED INDEX NCIX_DISASSEMBLEBILL_Ptypeid ON DISASSEMBLEBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('DISASSEMBLEBILL') AND name = 'NCIX_DISASSEMBLEBILL_Ktypeid')
--DROP INDEX NCIX_DISASSEMBLEBILL_Ktypeid ON DISASSEMBLEBILL 
CREATE NONCLUSTERED INDEX NCIX_DISASSEMBLEBILL_Ktypeid ON DISASSEMBLEBILL(Ktypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('DISASSEMBLEBILL') AND name = 'NCIX_DISASSEMBLEBILL_CostPrice')
DROP INDEX NCIX_DISASSEMBLEBILL_CostPrice ON DISASSEMBLEBILL 
                                
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_DISASSEMBLEBILL_CostPrice ON DISASSEMBLEBILL(CostPrice) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE DisassembleBill SET IsUnit2 = 0 WHERE IsUnit2 IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DisassembleBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DisassembleBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[distributingshowformat]    脚本日期: 2012.02.15 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[distributingshowformat]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].distributingshowformat
	(
		value VARCHAR(3) NOT NULL DEFAULT '011'
	) ON [PRIMARY]
END
DELETE FROM distributingshowformat
INSERT INTO distributingshowformat VALUES('011')

GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[WorkTime]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[DocFile]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[DocFile](
		[Id] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[pathId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),		--目录id
		[FullName] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--名称
		[FileSize] [numeric](10, 0) NOT NULL DEFAULT(0),							--文件大小
		[FileType] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--文件类型
		[Binarydata] [image] NOT NULL,												--文件内容
		[UploadDate] [datetime] NOT NULL,											--上传时间
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),		--创建者id
		[xpsFileName] [varchar](50) NULL DEFAULT('')								--生成的xps文件名字
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[WorkTime]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[DocFilePath]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[DocFilePath](
		[typeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),		--ID
		[parid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),		--上级目录id
		[leveal] [smallint] NOT NULL,												--层级
		[sonnum] [int] NOT NULL,													--儿子数
		[soncount] [int] NOT NULL,
		[FullName] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--名称		
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')		--创建者id
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  部门档案自定义字段
  张陈仁
  3023-04-10
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Dtype_CustomColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table Dtype_CustomColumns 
	(
	   ID                   bigint               identity(1,1),
	   typeid               varchar(100)         null,
	   Costom1              varchar(max)         null,
	   Costom2              varchar(max)         null,
	   Costom3              varchar(max)         null,
	   Costom4              varchar(max)         null,
	   Costom5              varchar(max)         null,
	   Costom6              varchar(max)         null,
	   Costom7              varchar(max)         null,
	   Costom8              varchar(max)         null,
	   Costom9              varchar(max)         null,
	   Costom10             varchar(max)         null,
	   Costom11             varchar(max)         null,
	   Costom12             varchar(max)         null,
	   Costom13             varchar(max)         null,
	   Costom14             varchar(max)         null,
	   Costom15             varchar(max)         null,
	   Costom16             varchar(max)         null,
	   Costom17             varchar(max)         null,
	   Costom18             varchar(max)         null,
	   Costom19             varchar(max)         null,
	   Costom20             varchar(max)         null
   )
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[dtype_l]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[dtype_l] (
		[etypeid] [varchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[typeid] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[flag] [char] (1) COLLATE Chinese_PRC_CI_AS NOT NULL 
	) ON [PRIMARY]
END
GO


-- Add by 李海洋 
-- Date: 2012-03-30
-- Description: 增加: 修改, 分类, 停用, 删除 细分权限
------------------------------------------表修改区域开始-------------------------------------------------
-- 修改权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[dtype_l]') 
		AND name = 'modifyflag'
)
BEGIN
		ALTER TABLE dbo.dtype_l DROP COLUMN modifyflag ;
END
GO

-- 分类权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[dtype_l]') 
		AND name = 'assortflag'
)
BEGIN
  ALTER TABLE dbo.dtype_l DROP COLUMN assortflag ;
END
GO

-- 停用权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[dtype_l]') 
		AND name = 'disableflag'
)
BEGIN
  ALTER TABLE dbo.dtype_l DROP COLUMN disableflag ;
END
GO

-- 删除权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[dtype_l]') 
		AND name = 'delflag'
)
BEGIN
		ALTER TABLE dbo.dtype_l DROP COLUMN delflag ;
END  
GO

------------------------------------------表修改区域结束-------------------------------------------------






------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[dtype_l]') AND name = N'IX_dtype_l')
BEGIN
	DROP INDEX IX_dtype_l ON dtype_l
END
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('DTYPE_L') AND name = 'CIX_DTYPE_L_etypeid')
--DROP INDEX CIX_DTYPE_L_etypeid ON DTYPE_L 
CREATE CLUSTERED INDEX CIX_DTYPE_L_etypeid ON DTYPE_L(etypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------


				
------------------------------------------更新新加列结束-------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[DtypeSaleAllPlan]    Script Date: 06/24/2011 09:54:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DtypeSaleAllPlan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[DtypeSaleAllPlan]   --部门总表
(
    [ID]           [int] identity (1,1),     --部门总表ID
    [FullName]	   [VARCHAR] (400) NOT NULL,	--计划名称
    [TotalID]      [int] NULL,               --时间总表ID
    [STypePlanID]  [int] NULL,               --分支机构总表ID
	[AllPlanValue] [decimal](18, 2) NULL,    --总体计划值
	[AllRatingValue] [decimal](18, 2) NULL,  --总体额定值
	[TimeID] [int] NULL ,                    --时间表ID
    [IfAudit] [bit]  NULL,                   --是否通过审核
    [Comment] [varchar](800) NULL ,          --描述字段
    [IfUse]   [tinyint]   NULL,               --是否启用
	[MoneyUnit] [varchar] (50) NULL          --金额单位
) ON [PRIMARY]

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='DtypeSaleAllPlan' AND a.Name='FullName')
BEGIN
	ALTER TABLE DtypeSaleAllPlan 
		ADD FullName VARCHAR(400) NULL DEFAULT('') 
END
GO

UPDATE DtypeSaleAllPlan SET FullName = '' WHERE FullName IS NULL
GO


SET QUOTED_IDENTIFIER OFF
GO


SET ANSI_PADDING OFF
GO





------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[DtypeSaleplan]    Script Date: 06/23/2011 11:21:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[DtypeSaleplan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[DtypeSaleplan]---部门销售明细计划总表
(
    [ID]          [int] identity (1,1),     --明细计划总表ID
    [DplanID]     [int]     NULL,           --部门总表ID
	[DtypeID]     [varchar](50) NULL,       --部门ID
	[TimeID]      [int]     NULL,           --时间总表ID
	[StypeID]     [varchar](50) NULL,       --分支机构ID
	[RatingValue] [decimal](18, 2) NULL,    --额定值
	[PlanValue]   [decimal](18, 2) NULL,    --计划值
	[ApportionScale] [decimal](18, 2) NULL  --分摊比例,
        
) ON [PRIMARY]

GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DtypeSaleplan' AND a.Name='ApportionScale' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DtypeSaleplan 
	ALTER COLUMN ApportionScale NUMERIC(24,10)
    END
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

/**
创 建 人：罗淮文
创建日期：2016-08-03
功能描述：电子秤型号
说    明：没有维护界面，自动添加预制数据
**/
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ElectronicScaleEntryCodeFormat]') AND type IN (N'U'))
BEGIN
	DROP TABLE ElectronicScaleEntryCodeFormat
END
BEGIN
	CREATE TABLE ElectronicScaleEntryCodeFormat
	(
		ScaleTypeId		INT NOT NULL,
		ID				INT IDENTITY(0,1) PRIMARY KEY NOT NULL,
		EntryCodeFormat	VARCHAR(50) NOT NULL,
		IsDefault		BIT NOT NULL DEFAULT(0),
		Comment			VARCHAR(256) NULL
	)
END

GO

-----------------预制数据 BEGIN---------------------
TRUNCATE TABLE ElectronicScaleEntryCodeFormat
BEGIN
	INSERT INTO ElectronicScaleEntryCodeFormat(ScaleTypeId,EntryCodeFormat,IsDefault,Comment)
	VALUES
	(0,'FWWWWWWEEEEENNNNN0',1,''),
	(1,'FWWWWWWEEEEE0',0,''),
	(2,'FWWWWWWEEEEE0',0,''),
	(3,'2IIIIIIPPPPPWWWWWC',0,'')
END
-----------------预制数据 END-----------------------

GO




SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

/**
创 建 人：罗淮文
创建日期：2016-08-03
功能描述：电子秤型接口配置
**/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ElectronicScaleInterfaceConfig]') AND type IN (N'U'))
BEGIN
	CREATE TABLE ElectronicScaleInterfaceConfig
	(
		ID		INT IDENTITY(0,1) PRIMARY KEY NOT NULL,
		InterfaceCode	VARCHAR(25) NOT NULL,		--接口编码
		InterfaceName	VARCHAR(50) NOT NULL,		--接口名称
		ElectronicScaleTypeId	INT NOT NULL,		--电子秤类型（关联表：ElectronicScaleType的typeid）
		EntryCodeFormatId		INT NOT NULL,		--电子秤对应的条码格式ID（关联表：ElectronicScaleEntryCodeFormat）
		SendPrice	VARCHAR(25) NOT NULL,			--传输价格类型（零售价，预设价格......）
		QtyDigitLenth	INT NOT NULL DEFAULT(2),	--数量小数位数
		MoneyDigitLenth INT NOT NULL DEFAULT(2),	--金额小数位数
		SendCode	INT NOT NULL DEFAULT(0),		--传入内码：0，商品条码；1，商品编码
		SendName	INT NOT NULL DEFAULT(0),		--传入名称：0，商品名称；1，商品简名
		Comment		VARCHAR(256) NULL,				--备注
		CreateDate	datetime NULL,					--创建日期
		UpdateTime	datetime NULL,					--修改日期
		EtypeId		VARCHAR(50) NULL,				--创建人
		UpdateE		VARCHAR(50) NULL				--修改人
	)
END

GO



SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

/**
创 建 人：罗淮文
创建日期：2016-08-03
功能描述：电子秤型号
说    明：没有维护界面，自动添加预制数据
**/
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ElectronicScaleType]') AND type IN (N'U'))
BEGIN
	DROP TABLE ElectronicScaleType
END
BEGIN
	CREATE TABLE ElectronicScaleType
	(
		TypeId		INT IDENTITY(0,1) PRIMARY KEY NOT NULL,
		UserCode	VARCHAR(25) NOT NULL,
		FullName	VARCHAR(25) NOT NULL,
		Comment		VARCHAR(256) NULL
	)
END

GO

-----------------预制数据 BEGIN---------------------
TRUNCATE TABLE ElectronicScaleType
BEGIN
	INSERT INTO ElectronicScaleType(UserCode,FullName,Comment)
	VALUES
	('00001','大华条码秤TMA4.0',''),
	('00002','托利多ACS-JJ T2B-15D',''),
	('00003','大华条码秤TM15H',''),
	('00004','顶尖标签秤LS6X','')
END
-----------------预制数据 END-----------------------

GO





/****** 对象:  Table [dbo].[EmpIncSet]    脚本日期: 05/05/2010 14:47:15 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EmpIncSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[EmpIncSet](
		[EtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[AtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[employee]    脚本日期: 05/05/2010 14:47:16 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[employee]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[employee](
		[BtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_employee_BtypeID]  DEFAULT ('00000'),
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Parid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint] NOT NULL,
		[soncount] [int] NOT NULL,
		[sonnum] [int] NOT NULL,
		[FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_employee_Name]  DEFAULT (''),
		[UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_employee_UserCode]  DEFAULT (''),
		[Department] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_employee_Department]  DEFAULT (0),
		[Tel] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_employee_Tel]  DEFAULT (''),
		[Address] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_employee_Address]  DEFAULT (''),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_employee_Comment]  DEFAULT (''),
		[deleted] [bit] NOT NULL CONSTRAINT [DF_employee_deleted]  DEFAULT (0),
		[Sex] [bit] NULL,
		[Nation] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Knowledge] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Blood] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Health] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[IDcard] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Birthday] [datetime] NULL,
		[Marriage] [int] NULL,
		[Job] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Job2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[JobTime] [datetime] NULL,
		[Tel2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Mob] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Mail] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[political] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[nat_place] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[college] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[for_language] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[reg_place] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[com_level] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[weight] [float] NULL,
		[stature] [float] NULL,
		[fam_status] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[informer] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[speciality] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[for_lan_level] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[PostCode] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL, 
		[Email] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[DtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_employee_DtypeID]  DEFAULT (''),
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[MaxPre] [numeric](18, 2) NULL CONSTRAINT [DF_employee_MaxPre]  DEFAULT ((-999999999918.99)),
		[smsMobile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[smsComment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[tichengRate] [numeric](18, 4) NULL,
		[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0)
	) ON [PRIMARY]

	-- ********	处理 Employee	********
	DELETE FROM Employee
	--INSERT INTO Employee(BTypeID,TypeID,Parid,Leveal,SonCount,SonNum,FullName,Name,UserCode,DTypeId,Department,Tel,Address,Comment,Deleted,Sex,Nation,Knowledge,Blood,Health,IDcard,Birthday,Marriage,Job,Job2,JobTime,Tel2,Mob,Mail,political,nat_place,college,for_language,reg_place,com_level,weight,stature,fam_status,informer,speciality,for_lan_level,PostCode,Email) VALUES('00000','00000','root',0,1,1,'root','','00000','','','','','',0,'','','','','','','','','','','','','','','','','','','','','','','','','','','','')
	--INSERT INTO Employee(BTypeID,TypeID,Parid,Leveal,SonCount,SonNum,FullName,Name,UserCode,DTypeId,Department,Tel,Address,Comment,Deleted,Sex,Nation,Knowledge,Blood,Health,IDcard,Birthday,Marriage,Job,Job2,JobTime,Tel2,Mob,Mail,political,nat_place,college,for_language,reg_place,com_level,weight,stature,fam_status,informer,speciality,for_lan_level,PostCode,Email) VALUES('00000','00001','00000',1,0,0,'超级用户','','admin','','','','','',0,'','','','','','','','','','','','','','','','','','','','','','','','','','','','')
	--极简模式加入
	INSERT INTO employee (BtypeID, typeId, Parid, leveal, soncount, sonnum, FullName, Name, UserCode, Department, Tel, Address, Comment, deleted, Sex, Nation, Knowledge, Blood, Health, IDcard, Birthday, Marriage, Job, Job2, JobTime, Tel2, Mob, Mail, political, nat_place, college, for_language, reg_place, com_level, weight, stature, fam_status, informer, speciality, for_lan_level, PostCode, Email, DtypeID, PyCode, MaxPre, smsMobile, smsComment, tichengRate, XiWaMaxNumber)VALUES ('00000', '00000', 'root', 0, 1, 1, 'root', '', '00000', NULL, '', '', '', 0, 0, '', '', '', '', '', '1900-01-01', 0, '', '', '1900-01-01', '', '', '', '', '', '', '', '', '', 0, 0, '', '', '', '', '', '', '', NULL, -999999999918.99, NULL, NULL, 0, 1)
	INSERT INTO employee (BtypeID, typeId, Parid, leveal, soncount, sonnum, FullName, Name, UserCode, Department, Tel, Address, Comment, deleted, Sex, Nation, Knowledge, Blood, Health, IDcard, Birthday, Marriage, Job, Job2, JobTime, Tel2, Mob, Mail, political, nat_place, college, for_language, reg_place, com_level, weight, stature, fam_status, informer, speciality, for_lan_level, PostCode, Email, DtypeID, PyCode, MaxPre, smsMobile, smsComment, tichengRate, XiWaMaxNumber)VALUES ('00000', '00001', '00000', 1, 1, 1, '超级用户', '', 'admin', NULL, '', '', '', 0, 0, '', '', '', '', '', '1900-01-01', 0, '', '', '1900-01-01', '', '', '', '', '', '', '', '', '', 0, 0, '', '', '', '', '', '', '', NULL, -999999999918.99, NULL, NULL, 0, 1)
	INSERT INTO employee (BtypeID, typeId, Parid, leveal, soncount, sonnum, FullName, Name, UserCode, Department, Tel, Address, Comment, deleted, Sex, Nation, Knowledge, Blood, Health, IDcard, Birthday, Marriage, Job, Job2, JobTime, Tel2, Mob, Mail, political, nat_place, college, for_language, reg_place, com_level, weight, stature, fam_status, informer, speciality, for_lan_level, PostCode, Email, DtypeID, PyCode, MaxPre, smsMobile, smsComment, tichengRate, XiWaMaxNumber)VALUES ('00000', '0000100001', '00001', 2, 0, 0, '业务员', '', '001', '系统默认部门', '', '', '', 0, 1, '', '', '', '', '', '2050-01-01', 0, '', '', '2050-01-01', '', '', '', '', '', '', '', '', '', NULL, NULL, '', '', '', '', '', NULL, '00001', 'YWY', -999999999918.99, NULL, NULL, 0, 2)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='employee' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE employee ADD STypeID VARCHAR(50) NULL
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE employee SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END
GO
UPDATE employee SET STypeID = '00001' WHERE ISNULL(STypeId,'') = ''

GO

UPDATE employee
SET Department=''
WHERE Department IS NULL OR Department='0'
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='employee' AND a.Name='QQ')
BEGIN
	ALTER TABLE dbo.employee ADD
		QQ varchar(50) NULL,
		MSN varchar(50) NULL,
		Blog varchar(200) NULL,
		mBlog varchar(200) NULL

	ALTER TABLE dbo.employee ADD CONSTRAINT
		DF_employee_QQ DEFAULT '' FOR QQ

	ALTER TABLE dbo.employee ADD CONSTRAINT
		DF_employee_MSN DEFAULT '' FOR MSN

	ALTER TABLE dbo.employee ADD CONSTRAINT
		DF_employee_Blog DEFAULT '' FOR Blog

	ALTER TABLE dbo.employee ADD CONSTRAINT
		DF_employee_mBlog DEFAULT '' FOR mBlog

	ALTER TABLE dbo.employee SET (LOCK_ESCALATION = TABLE)
	END
GO
--汽配3S加的Team班组字段
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='employee' AND a.Name='Team')
BEGIN
	ALTER TABLE dbo.employee ADD
			Team varchar(200) NULL DEFAULT('')
END
GO

--HR系统职位
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='employee' AND a.Name='HrpostionId')
BEGIN
	ALTER TABLE dbo.employee ADD
			HrpostionId int NULL DEFAULT(0)
END
GO

--HR增加人员状态
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='employee' AND a.Name='HrPersonStatu')
BEGIN
	ALTER TABLE dbo.employee ADD
			HrPersonStatu int NULL DEFAULT(4)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='employee' AND a.Name='Eid')
BEGIN
	ALTER TABLE employee ADD Eid INT identity(1,1)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='employee' AND a.Name='IsDownLoad')
BEGIN
	ALTER TABLE employee ADD IsDownLoad BIT NULL DEFAULT(0)
END
GO 

--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('employee') and name='WdSyncFlag')
BEGIN
	ALTER TABLE employee ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
END
GO 

--采购最低下限值
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='employee' AND a.Name='BuyerMinvalue')
BEGIN
	ALTER TABLE dbo.employee ADD
			BuyerMinvalue NUMERIC(24, 10) NOT  NULL DEFAULT(0)
END
GO

--销售最低下限值
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='employee' AND a.Name='SaleMinvalue')
BEGIN
	ALTER TABLE dbo.employee ADD
			SaleMinvalue NUMERIC(24, 10) NOT  NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[employee]') AND name = N'etypeidx')
--	DROP INDEX [dbo].[employee].[etypeidx]

--IF EXISTS  (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[employee]') AND name = N'IX_Emolyee_DTypeID')
--	DROP INDEX [dbo].[employee].IX_Emolyee_DTypeID
	
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('EMPLOYEE') AND name = 'CIX_EMPLOYEE_typeId')
	--DROP INDEX CIX_EMPLOYEE_typeId ON EMPLOYEE 
CREATE CLUSTERED INDEX CIX_EMPLOYEE_typeId ON EMPLOYEE(typeId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('EMPLOYEE') AND name = 'NCIX_EMPLOYEE_DtypeID')
	--DROP INDEX NCIX_EMPLOYEE_DtypeID ON EMPLOYEE 
CREATE NONCLUSTERED INDEX NCIX_EMPLOYEE_DtypeID ON EMPLOYEE(DtypeID) 
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[employee]') AND name = N'NCIX_Emolyee_FullName')
	--DROP  INDEX [dbo].[employee].NCIX_Emolyee_FullName
CREATE INDEX NCIX_Emolyee_FullName ON EMPLOYEE(FullName) 


------------------------------------------创建索引区域结束-----------------------------------------------
--提供XiWa交互功能，每次修改或者新增基本信息后，必须在原来的值上加1 谢吉康 2010-05-04
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Employee]') and name = 'XiWaMaxNumber' )
	BEGIN
		BEGIN TRANSACTION
		SET QUOTED_IDENTIFIER ON
		SET ARITHABORT ON
		SET NUMERIC_ROUNDABORT OFF
		SET CONCAT_NULL_YIELDS_NULL ON
		SET ANSI_NULLS ON
		SET ANSI_PADDING ON
		SET ANSI_WARNINGS ON
		COMMIT
		BEGIN TRANSACTION
		ALTER TABLE dbo.Employee ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
		
		COMMIT
	END
GO
UPDATE Employee SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL OR XiWaMaxNumber = 0
GO
UPDATE employee SET HrpostionId = 0 WHERE HrpostionId IS NULL
GO
UPDATE employee SET HrPersonStatu = 4 WHERE HrPersonStatu IS NULL
GO
UPDATE employee SET IsDownLoad=0 WHERE IsDownLoad IS NULL
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='employee' AND a.Name='MaxPre' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE employee 
	ALTER COLUMN MaxPre NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='employee' AND a.Name='tichengRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE employee 
	ALTER COLUMN tichengRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

--WMS下载
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('employee') and name='IsWmsDownLoad')
BEGIN
	ALTER TABLE employee 
		ADD IsWmsDownLoad INT NOT NULL DEFAULT 0 
End 
GO
UPDATE employee SET IsWmsDownLoad = 0 WHERE IsWmsDownLoad IS NULL
GO

--是否同步
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('employee') and name='IsWmsSync')
BEGIN
	ALTER TABLE employee 
		ADD IsWmsSync INT NOT NULL DEFAULT 0 
End 
GO
UPDATE employee SET IsWmsSync = 0 WHERE IsWmsSync IS NULL
GO



------------------------店帐通基本信息表------------------------

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EshopBaseInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].[EshopBaseInfo]
		(
			[Id]			[int]				IDENTITY(1,1) NOT NULL,
			[Field]			[varchar](50)		NULL,
			[Value]			[varchar](max)		NULL,
		) ON [PRIMARY]
	 END

--增加列
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='EshopBaseInfo' AND a.Name='EshopID'
)
BEGIN
	ALTER TABLE EshopBaseInfo ADD EshopID VARCHAR(200) DEFAULT('')
END 
GO

IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'RegisterUrl' )                                   --注册URL
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('RegisterUrl','http://dzt.mygjp.com/Register.gspx')
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'ChargeUrl' )                                     --支付购买URL
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('ChargeUrl','http://dzt.mygjp.com/Payment.gspx')
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'ApiUrl' )										 --Api调用URL
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('ApiUrl','http://dzt.mygjp.com/Gateway.gspx')	
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'LoginFactor' )									 --登录次数计数器
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('LoginFactor','0')	
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'AdminLoginUrl' )								 --店帐通登录地址(不带参数)
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('AdminLoginUrl','http://dzt.mygjp.com/Login.gspx?')	
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'SetPwdUrl' )									 --重置密码
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('SetPwdUrl','http://dzt.mygjp.com/Password.gspx?appkey=')	
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'StypeItem' )									 --分支机构
	BEGIN
		IF EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)  --V3
			INSERT INTO EshopBaseInfo(Field,Value)VALUES('StypeItem','00001')	
		ELSE 
			INSERT INTO EshopBaseInfo(Field,Value)VALUES('StypeItem','')	
	END
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'FreightPayItem' )									 --物流运费结算付款项
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('FreightPayItem','')
--IF EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'FreightFeeItem' )									 --修改bug 2013.4.12，后续不再支持
--	UPDATE dbo.EshopBaseInfo SET Value='' WHERE Field='FreightFeeItem'	
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'FreightFeeItem' )									 --物流运费结算费用项
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('FreightFeeItem','')	
IF NOT EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'FreightAtypeItem' )									 --物流运费结算往来科目
	INSERT INTO EshopBaseInfo(Field,Value)VALUES('FreightAtypeItem','')	
IF  EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'FeeItem' AND (eshopid='' OR eshopid IS null))										 --付款项配置ID
	DELETE dbo.EshopBaseInfo WHERE  Field = 'FeeItem' AND (eshopid='' OR eshopid IS null)
IF  EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'IncomeItem' AND (eshopid='' OR eshopid IS null))									 --收款项配置ID
	DELETE dbo.EshopBaseInfo WHERE  Field = 'IncomeItem' AND (eshopid='' OR eshopid IS null)
IF  EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'FYItem' AND (eshopid='' OR eshopid IS null))										 --费用项配置ID
	DELETE dbo.EshopBaseInfo WHERE  Field = 'FYItem' AND (eshopid='' OR eshopid IS null)
IF EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'MoneyFeeItem' )										 --现金费用项配置ID （不在需要现金费用项）
	DELETE  EshopBaseInfo WHERE Field = 'MoneyFeeItem'       
IF  EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'SRItem' AND (eshopid='' OR eshopid IS null))										 --收入项配置ID
	DELETE dbo.EshopBaseInfo WHERE  Field = 'SRItem' AND (eshopid='' OR eshopid IS null)
IF  EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'InOutBtype' AND (eshopid='' OR eshopid IS null))									 --发货/退货单往来单位
	DELETE dbo.EshopBaseInfo WHERE  Field = 'InOutBtype' AND (eshopid='' OR eshopid IS null)
IF  EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'OtherBuyBtype' AND (eshopid='' OR eshopid IS null))								 --买家运费往来单位
	DELETE dbo.EshopBaseInfo WHERE  Field = 'OtherBuyBtype' AND (eshopid='' OR eshopid IS null)
IF  EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'MallBtype' AND (eshopid='' OR eshopid IS null))									 --商城扣费，货到付款往来单位
	DELETE dbo.EshopBaseInfo WHERE  Field = 'MallBtype' AND (eshopid='' OR eshopid IS null)
IF EXISTS( SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'KtypeidItem' )									 --删除仓库IDs
	DELETE  EshopBaseInfo WHERE Field = 'KtypeidItem'     
IF EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EshopGoodsInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)  --删除多余的表
	DROP  TABLE EshopGoodsInfo
IF NOT EXISTS(SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'SummaryItem' )									 --单据摘要，默认选择订单的摘要
    INSERT INTO dbo.EshopBaseInfo (Field,Value)VALUES('SummaryItem','summary')
IF NOT EXISTS(SELECT TOP 1 1 FROM EshopBaseInfo WHERE Field = 'StockItem' )										 --库存取数，默认虚拟库存
    INSERT INTO dbo.EshopBaseInfo (Field,Value)VALUES('StockItem','virtual')
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



------------------------店帐通订单与本地单据对应表------------------------

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EshopBillRelation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].[EshopBillRelation]
		(
			[Id]			[int]				IDENTITY(1,1) NOT NULL,
			[EshopBillID]			[varchar](100)		NULL,
			[Billnumberid]			NUMERIC(18,0)		NULL,
			Flag			INT                                          ---单据类型标示
		) ON [PRIMARY]
	 END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF  EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[EshopGoodsInfo]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
BEGIN
 DROP TABLE EshopGoodsInfo
END
GO

------------------------店帐通商品基本信息表------------------------

CREATE TABLE [dbo].[EshopGoodsInfo](
	[EshopId] [varchar](100) NOT NULL,	--店铺ID
	[NumIid] [varchar](100) NOT NULL,	--商品ID
	[OuterId] [varchar](100) NOT NULL,	--商品编码-对应本地商品Usercode
	[SkuId] [varchar](100) ,	--属性ID
	[GoodsName] [varchar](500) 	--商品名称
) ON [PRIMARY]


GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  职员档案自定义字段
  张陈仁
  3023-04-10
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Etype_CustomColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table Etype_CustomColumns 
	(
	   ID                   bigint               identity(1,1),
	   typeid               varchar(100)         null,
	   Costom1              varchar(max)         null,
	   Costom2              varchar(max)         null,
	   Costom3              varchar(max)         null,
	   Costom4              varchar(max)         null,
	   Costom5              varchar(max)         null,
	   Costom6              varchar(max)         null,
	   Costom7              varchar(max)         null,
	   Costom8              varchar(max)         null,
	   Costom9              varchar(max)         null,
	   Costom10             varchar(max)         null,
	   Costom11             varchar(max)         null,
	   Costom12             varchar(max)         null,
	   Costom13             varchar(max)         null,
	   Costom14             varchar(max)         null,
	   Costom15             varchar(max)         null,
	   Costom16             varchar(max)         null,
	   Costom17             varchar(max)         null,
	   Costom18             varchar(max)         null,
	   Costom19             varchar(max)         null,
	   Costom20             varchar(max)         null
   )
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[etype_l]    脚本日期: 05/05/2010 14:47:17 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[etype_l]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[etype_l](
		[etypeid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[typeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[flag] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO
-- Add by 李海洋 
-- Date: 2012-03-30
-- Description: 增加: 修改, 分类, 停用, 删除 细分权限
------------------------------------------表修改区域开始-------------------------------------------------
-- 修改权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[Etype_l]') 
		AND name = 'modifyflag'
)
BEGIN
		ALTER TABLE dbo.Etype_l DROP COLUMN modifyflag ;
END
GO

-- 分类权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[Etype_l]') 
		AND name = 'assortflag'
)
BEGIN
  ALTER TABLE dbo.Etype_l DROP COLUMN assortflag ;
END
GO

-- 停用权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[Etype_l]') 
		AND name = 'disableflag'
)
BEGIN
  ALTER TABLE dbo.Etype_l DROP COLUMN disableflag ;
END
GO

-- 删除权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[Etype_l]') 
		AND name = 'delflag'
)
BEGIN
		ALTER TABLE dbo.Etype_l DROP COLUMN delflag ;
END  
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[etype_l]') AND name = N'IX_etype_l')
BEGIN
	DROP INDEX IX_etype_l ON etype_l
END
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ETYPE_L') AND name = 'CIX_ETYPE_L_etypeid')
--DROP INDEX CIX_ETYPE_L_etypeid ON ETYPE_L 
CREATE CLUSTERED INDEX CIX_ETYPE_L_etypeid ON ETYPE_L(etypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------更新新加列结束-------------------------------------------------


		
		
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[EType_Price]    脚本日期: 12/06/2011 14:46:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EType_Picture]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[EType_Picture] (
	[ETypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[Name]	[varchar](50) NOT NULL,
	[OrderID] [numeric](10, 0) IDENTITY(1,1) NOT NULL ,	
	[ImgURL] [VARCHAR](200) NOT NULL,
	[pic] [image] NULL,
	[length] [int] NULL,
	[filename] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[type] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,	
) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--职员所属类别表
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EtypeCommissionType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE EtypeCommissionType
(
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	ETypeID					VARCHAR(50) NOT NULL,--职员
	CommissionTypeID		VARCHAR(50) NOT NULL,--所属分类
)

END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[EtypeSaleAllPlan]    Script Date: 06/24/2011 09:58:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EtypeSaleAllPlan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[EtypeSaleAllPlan]    --人员总表
(
    [ID]           [int]identity (1,1),		--人员总表ID
    [FullName]	   [VARCHAR]	 (400),		--计划名称
    [TotalID]      [int]           NULL,	--时间总表ID
    [DTypePlanID]  [int]           NULL,	--部门计划总表ID
	[AllPlanValue] [decimal](18,2) NULL,	--总体计划值
	[AllRatingValue] [decimal](18,2) NULL,	--总体额定值
    [Comment]   [varchar](800)  NULL,		--描述字段
    [IfAudit] [bit]  NULL,					--是否通过审核
    [IfUse]      [tinyint],                 --是否启用
	[MoneyUnit] [varchar] (50) NULL         --金额单位  
) ON [PRIMARY]

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='EtypeSaleAllPlan' AND a.Name='FullName')
BEGIN
	ALTER TABLE EtypeSaleAllPlan 
		ADD FullName VARCHAR(400) NULL DEFAULT('') 
END
GO

UPDATE EtypeSaleAllPlan SET FullName = '' WHERE FullName IS NULL
GO


SET ANSI_PADDING OFF
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[EtypeSaleplan]    Script Date: 06/24/2011 09:54:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EtypeSaleplan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[EtypeSaleplan]---人员销售计划明细总表
(
    [ID]       [int] identity (1,1), --明细计划人员总表ID
    [EplanID]  [int]     NULL,      --人员总表ID
	[EtypeID] [varchar](50) NULL,      --人员ID
	[DtypeID] [varchar](50) NULL,       --部门ID
    [StypeID] [varchar](50) NULL,       --分支机构ID
    [TimeID]  [int]         NULL,       --时间总表ID
	[RatingValue] [decimal](18,2) NULL,--额定值
	[PlanValue] [decimal](18,2) NULL, ---计划值
	[ApportionScale] [decimal](18, 2) NULL, --分摊比例
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='EtypeSaleplan' AND a.Name='ApportionScale' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE EtypeSaleplan 
	ALTER COLUMN ApportionScale NUMERIC(24,10)
    END
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Event]    脚本日期: 05/05/2010 14:47:18 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Event]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Event](
		[EventId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[EventName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]
END
GO
-- 刷新整个日志表 谢吉康 2009-7-29
GO
DELETE FROM Event
GO
INSERT INTO Event SELECT DISTINCT Name,Caption FROM WebMenu WHERE IsSubMenu = 0
GO
INSERT INTO Event(EventId,EventName) VALUES('LIMIT_REPAIR_ENGAGE','维修接件单')
GO
INSERT INTO Event(EventId,EventName) VALUES('LIMIT_REPAIR_ENGAGE_QUERY','维修接件单查询')
GO
INSERT INTO Event(EventId,EventName) VALUES('LIMIT_REPAIR_DEAL','维修受理单')
GO
INSERT INTO Event(EventId,EventName) VALUES('LIMIT_REPAIR_DEAL_QUERY_PRODUCT','维修商品换货查询')
GO
INSERT INTO Event(EventId,EventName) VALUES('LIMIT_REPAIR_DEAL_PTYPE_SEARCH','维修受理商品查询')
GO
INSERT INTO Event(EventId,EventName) VALUES('LIMIT_ONLINE_INFO','在线传讯')

--OM
insert into event values('LIMIT_OM_QuestionReply','OM咨询回复')


GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[EventLog]    脚本日期: 05/05/2010 14:47:19 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EventLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[EventLog](
		[Id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
		[EventDate] [datetime] NOT NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[EventId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Ip] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Deleted] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_EventLog_Deleted]  DEFAULT (0),
		[LogData] [varchar](2000) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='EventLog' AND a.Name='LogData'
)
BEGIN
		ALTER TABLE EventLog ADD [LogData] [varchar](2000) NULL
END

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[EventLog]') AND name = N'CIX_EDATE')
	DROP INDEX [dbo].[EventLog].CIX_EDATE 
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[EventLog]') AND name = N'NCIX_ETYPE')
	DROP INDEX [dbo].[EventLog].NCIX_ETYPE
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('EVENTLOG') AND name = 'CIX_EVENTLOG_EventDate')
--DROP INDEX CIX_EVENTLOG_EventDate ON EVENTLOG 
CREATE CLUSTERED INDEX CIX_EVENTLOG_EventDate ON EVENTLOG(EventDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('EVENTLOG') AND name = 'NCIX_EVENTLOG_etypeid')
--DROP INDEX NCIX_EVENTLOG_etypeid ON EVENTLOG 
CREATE NONCLUSTERED INDEX NCIX_EVENTLOG_etypeid ON EVENTLOG(etypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
DELETE 
FROM	EventLog 
WHERE	EventId IN (
						SELECT	[Name] AS EventId
						FROM	WebMenu
						WHERE	MenuID IN (945,6901402)
					)

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Express]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Express](
		[id] [int] IDENTITY(1,1) NOT NULL,
		[name] [varchar](100) NOT NULL,
		[code] [varchar](100) NULL,
		[legalPerson] [varchar](20) NULL,
		[expressLicence] [varchar](50) NULL,
		[telephone] [varchar](20) NULL,
		[phone] [varchar](20) NULL,
		[registrationNumber] [varchar](50) NULL,
		[postal] [varchar](20) NULL,
		[manageType] [varchar](50) NULL,
		[serviceQuery] [int] DEFAULT(0) NOT NULL,
		[deleted] [int] DEFAULT(0) NOT NULL,
		[isKDN] [int] DEFAULT(1) NOT NULL,
		[printType] [int] DEFAULT(0) NOT NULL,
		[shipperCode] [varchar](10) NULL,
		[customerName] [varchar](100) NULL,
		[customerPwd] [varchar](100) NULL,
		[monthCode] [varchar](100) NULL,
		[sendSite] [varchar](100) NULL,				
		[SendStaff] [varchar](30) NULL
	 CONSTRAINT [PK_Express_id] PRIMARY KEY NONCLUSTERED 
	(
		[id] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END

GO

--模版尺寸
IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Express]') and  name = 'TemplateSize')
BEGIN
	 ALTER TABLE Express
	    ADD TemplateSize VARCHAR(20) NULL DEFAULT('')
END
GO
UPDATE Express SET TemplateSize = '' WHERE TemplateSize IS NULL
GO

--客户号
IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Express]') and  name = 'CustomerName')
BEGIN
	 ALTER TABLE Express
	    ADD CustomerName VARCHAR(50) NULL DEFAULT('')
END
GO
UPDATE Express SET CustomerName = '' WHERE CustomerName IS NULL
GO

--网点编号(仓库号)
IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Express]') and  name = 'SendSite')
BEGIN
	 ALTER TABLE Express
	    ADD SendSite VARCHAR(30) NULL DEFAULT('')
END
GO
UPDATE Express SET SendSite = '' WHERE SendSite IS NULL
GO

--收件快递员(网点提供)
IF NOT EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Express]') and  name = 'SendStaff')
BEGIN
	 ALTER TABLE Express
	    ADD SendStaff VARCHAR(30) NULL DEFAULT('')
END
GO
UPDATE Express SET SendStaff = '' WHERE SendStaff IS NULL
GO


SET ANSI_PADDING OFF
GO



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ExpressCompany]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ExpressCompany](
		[companyId] [int] IDENTITY(1,1) NOT NULL,
		[name] [varchar](20) NOT NULL,
		[code] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_companyId] PRIMARY KEY CLUSTERED 
	(
		[companyId] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END

GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ExpressCompany') AND name = 'NCIX_ExpressCompany_companyId')
BEGIN
	CREATE NONCLUSTERED INDEX NCIX_ExpressCompany_companyId ON ExpressCompany(companyId) 	
END	

GO

--写入预制数据
DELETE FROM ExpressCompany
INSERT INTO ExpressCompany([Name],[Code])VALUES('顺丰速运','SF')
INSERT INTO ExpressCompany([Name],[Code])VALUES('圆通速递','YTO')
INSERT INTO ExpressCompany([Name],[Code])VALUES('中通快递','ZTO')
INSERT INTO ExpressCompany([Name],[Code])VALUES('申通快递','STO')
INSERT INTO ExpressCompany([Name],[Code])VALUES('韵达速递','YD')
INSERT INTO ExpressCompany([Name],[Code])VALUES('京东物流','HHTT')
INSERT INTO ExpressCompany([Name],[Code])VALUES('德邦','DBL')
INSERT INTO ExpressCompany([Name],[Code])VALUES('邮政快递包裹','YZPY')
INSERT INTO ExpressCompany([Name],[Code])VALUES('EMS','EMS')
INSERT INTO ExpressCompany([Name],[Code])VALUES('天天快递','SF')
INSERT INTO ExpressCompany([Name],[Code])VALUES('全峰快递','QFKD')
INSERT INTO ExpressCompany([Name],[Code])VALUES('国通快递','GTO')
INSERT INTO ExpressCompany([Name],[Code])VALUES('优速快递','UC')
INSERT INTO ExpressCompany([Name],[Code])VALUES('快捷快递','FAST')
INSERT INTO ExpressCompany([Name],[Code])VALUES('宅急送','ZJS')
INSERT INTO ExpressCompany([Name],[Code])VALUES('百世快递','HTKY')	
INSERT INTO ExpressCompany([Name],[Code])VALUES('速尔快递','SURE')
INSERT INTO ExpressCompany([Name],[Code])VALUES('品骏快递','PJ')

SET ANSI_PADDING OFF
GO



/****** 对象:  Table [dbo].[Expression]    脚本日期: 05/05/2010 14:47:19 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Expression]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Expression](
		[ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
		[EtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Sub] [varchar](2000) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[SubName] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Comment] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
		[ConstFlag] [int] NOT NULL CONSTRAINT [DF_Expression_ConstFlag]  DEFAULT (0),
		[HiddenSub] [varchar](2000) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(SELECT 1 from dbo.SysObjects WHERE ID = OBJECT_ID(N'[dbo].[Fact_InoutPtypeSerial]',N'U'))
BEGIN
	CREATE TABLE [dbo].[Fact_InoutPtypeSerial](
		[Serial]				VARCHAR(50)  NOT NULL,
		[PtypeID]				VARCHAR(50)  ,
		[BillNumberid]			VARCHAR(50)  NOT NULL,
		[InKtypeID]				VARCHAR(50)  ,
		[OutKtyeID]				VARCHAR(50)  ,
		[IfCheck]				VARCHAR(4)   ,
		[BillType]				INT 		   DEFAULT (0),
		[InKtypeTime]			DATETIME ,
		[OutKtypeTime]			DATETIME ,
		[User]					VARCHAR(256)	DEFAULT (''),
		[State]					INT				DEFAULT (''),
		ID						NUMERIC(10, 0)	IDENTITY(1,1) NOT NULL,
		[GoodsOrder]			INT DEFAULT(0)						  ,
		[GoodsNumber]			VARCHAR(100)	DEFAULT('') ,
		[LendState]				INT DEFAULT(0),
		[Flag]					INT DEFAULT(1),
		[CargoID]				INT,
		[ItemID]				INT DEFAULT(0),
		[IsCombined]			BIT,
		[ProduceDate]			VARCHAR(50),
		[ValidDate]				VARCHAR(50),
		[PostTime]				DATETIME		DEFAULT GETDATE() 
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InoutPtypeSerial',N'U') AND Name='LendState')
BEGIN
	ALTER TABLE Fact_InoutPtypeSerial
	ADD LendState INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InoutPtypeSerial',N'U') AND Name='CargoID')
BEGIN
	ALTER TABLE Fact_InoutPtypeSerial
	ADD CargoID INT 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InoutPtypeSerial',N'U') AND Name='Flag')
BEGIN
	ALTER TABLE Fact_InoutPtypeSerial
	ADD Flag INT DEFAULT(1)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InoutPtypeSerial',N'U') AND Name='ItemID')
BEGIN
	ALTER TABLE Fact_InoutPtypeSerial
	ADD ItemID INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InoutPtypeSerial',N'U') AND Name='IsCombined')
BEGIN
	ALTER TABLE Fact_InoutPtypeSerial
	ADD IsCombined BIT
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InoutPtypeSerial',N'U') AND Name='ProduceDate')
BEGIN
	ALTER TABLE Fact_InoutPtypeSerial
	ADD ProduceDate VARCHAR(50)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InoutPtypeSerial',N'U') AND Name='ValidDate')
BEGIN
	ALTER TABLE Fact_InoutPtypeSerial
	ADD ValidDate VARCHAR(50)
END
GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Fact_InoutPtypeSerial]') and  name = 'Serial' and Length=50)
BEGIN
	 ALTER TABLE Fact_InoutPtypeSerial
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO 
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('Fact_InoutPtypeSerial') AND name = 'CIX_Fact_InoutPtypeSerial_Serial')
	CREATE CLUSTERED INDEX CIX_Fact_InoutPtypeSerial_Serial ON Fact_InoutPtypeSerial(Serial) 

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('Fact_InoutPtypeSerial') AND name = 'NCIX_Fact_InoutPtypeSerial_BillNumberId')
	CREATE NONCLUSTERED INDEX NCIX_Fact_InoutPtypeSerial_BillNumberId ON Fact_InoutPtypeSerial(BillNumberId) 

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('Fact_InoutPtypeSerial') AND name = 'NCIX_Fact_InoutPtypeSerial_ID')
	CREATE NONCLUSTERED INDEX NCIX_Fact_InoutPtypeSerial_ID ON Fact_InoutPtypeSerial(ID) 
------------------------------------------创建索引区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Fact_InOutstocktable]    脚本日期: 05/05/2010 14:47:53 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID = OBJECT_ID(N'[dbo].[Fact_InOutstocktable]',N'U'))
BEGIN
	CREATE TABLE [dbo].[Fact_InOutstocktable]
	(
		[BillNumberId]			NUMERIC	(10, 0)		NOT NULL			    ,
		[BillDate]				DATETIME								    ,
		[BillType]				INT					NOT NULL			    ,
		[PtypeId]				VARCHAR	(50)					DEFAULT (0) ,
		[EtypeId] 				VARCHAR (50)					DEFAULT (0) ,
		[KtypeId]				VARCHAR (50)					DEFAULT (0) ,
		[Qty]					NUMERIC(24,10)					DEFAULT (0) ,
		[OutFactoryDate]        DATETIME								    ,
		[Audited]				BIT					NOT NULL	DEFAULT (0) ,
		[GoodsNumber]			VARCHAR(100)					DEFAULT (''),
		[ProduceDate]			VARCHAR(50)						DEFAULT (''),
		[ValidDate]				VARCHAR(50)						DEFAULT (''),
		[GoodsOrder]			INT											,
		[ID]					INT								DEFAULT (-1),
		[DTypeID]				VARCHAR(50)						DEFAULT (''),
		[STypeID]				VARCHAR(50)						DEFAULT (''),
		[PostTime]				DATETIME						DEFAULT GETDATE(),
		[SortID]				BIGINT							IDENTITY(1,1),
		[CargoID]				INT								DEFAULT (0),
		[ItemID]				INT					NOT NULL	DEFAULT(0),
		[IsCombined]			BIT					NOT NULL	DEFAULT(0),
		[NQty]					NUMERIC(24,10)					DEFAULT(0),
		[UnitRate]				NUMERIC(24,10)					DEFAULT(0),
		[Comment]				VARCHAR(250),
		[MUnitID]			    INT										  ,
		[MUnitRate]				NUMERIC(24,10)					DEFAULT(1),
		[UnitID]				INT				
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name='MUnitID')
BEGIN
	ALTER TABLE Fact_InOutstocktable
	ADD MUnitID INT
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name='UnitID')
BEGIN
	ALTER TABLE Fact_InOutstocktable
	ADD UnitID INT
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name='MUnitRate')
BEGIN
	ALTER TABLE Fact_InOutstocktable
	ADD MUnitRate NUMERIC(24,10) DEFAULT(1)
END
GO

ALTER TABLE Fact_InOutstocktable ALTER COLUMN Comment VARCHAR(250)
GO

------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE OBJECT_ID = OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name = 'CIX_Fact_InOutstocktable_BillDate')
	CREATE CLUSTERED INDEX CIX_Fact_InOutstocktable_BillDate ON Fact_InOutstocktable(BillDate) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE OBJECT_ID = OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name = 'NCIX_Fact_InOutstocktable_BillNumberID')
	CREATE NONCLUSTERED INDEX NCIX_Fact_InOutstocktable_BillNumberID ON Fact_InOutstocktable(BillNumberID) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE OBJECT_ID = OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name = 'NCIX_Fact_InOutstocktable_Ktypeid')
	CREATE NONCLUSTERED INDEX NCIX_Fact_InOutstocktable_Ktypeid ON Fact_InOutstocktable(Ktypeid) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE OBJECT_ID = OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name = 'NCIX_Fact_InOutstocktable_Etypeid')
	CREATE NONCLUSTERED INDEX NCIX_Fact_InOutstocktable_Etypeid ON Fact_InOutstocktable(Etypeid) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE OBJECT_ID = OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name = 'NCIX_Fact_InOutstocktable_PostTime')
	CREATE NONCLUSTERED INDEX NCIX_Fact_InOutstocktable_PostTime ON Fact_InOutstocktable(PostTime) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE OBJECT_ID = OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name = 'NCIX_Fact_InOutstocktable_Ptypeid_Ktypeid')
	CREATE NONCLUSTERED INDEX NCIX_Fact_InOutstocktable_Ptypeid_Ktypeid ON Fact_InOutstocktable(Ptypeid, Ktypeid) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE OBJECT_ID = OBJECT_ID(N'Fact_InOutstocktable',N'U') AND Name = 'NCIX_Fact_InOutstocktable_Billtype')
	CREATE NONCLUSTERED INDEX NCIX_Fact_InOutstocktable_Billtype ON Fact_InOutstocktable(Billtype) 

GO  



GO
/*
*	仓库调拨单	
*/

IF NOT EXISTS (SELECT 1 FROM SysObjects WHERE id = OBJECT_ID(N'dbo.FactDepotAllot',N'U'))
BEGIN
	CREATE TABLE dbo.FactDepotAllot
	(
		BillNumberId	INT NOT NULL									,  --单据ID
		Comment			VARCHAR (256)	 COLLATE Chinese_PRC_CI_AS NULL	,  --说明备注
		PtypeId			VARCHAR (50)	 COLLATE Chinese_PRC_CI_AS NULL	,  --商品ID
		Qty				NUMERIC (24, 10) DEFAULT (0)					,  --数量
		Total			NUMERIC (24, 10)								,  --金额
		Jobnumber		VARCHAR (20)		DEFAULT (0)					,  
		GoodsNo			INT					DEFAULT (0)					,  
		OutFactoryDate	DATETIME										,  --出库日期
		IsUnit2			INT NOT NULL		DEFAULT (0)					,  --是否启用双单位 0=小单位 1=大单位
		ID				INT					IDENTITY(1, 1)				,  --明细ID
		Serial			NVARCHAR(MAX) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),  --序列号
		GoodsOrder		INT  DEFAULT ('-1')								,  --
		GoodsNumber		VARCHAR (100)		DEFAULT ('')				,  --批号
		ProduceDate		VARCHAR (50)		DEFAULT ('')				,  --生产日期
		ValidDate		VARCHAR (50)		DEFAULT ('')				,  --效期至
		UnitID			INT					DEFAULT (0)					,  --浮动单位ID
		NUnitID			INT					DEFAULT (0)					,  --辅助单位ID
		NQty			NUMERIC (24, 10)    DEFAULT (0)					,  --辅助数量
		UnitRate		NUMERIC (24, 10)    DEFAULT (0)					,  --浮动单位数量
		NUnitMsg		VARCHAR (50)									,  --辅助单位转换结果
		MUnitID			INT					DEFAULT (0)					,  --大单位ID
		MQty			NUMERIC (24, 10)	DEFAULT (0)					,  --大单位数量
		MUnitRate		NUMERIC (24, 10)	DEFAULT (0)					,  --大单位转换率
		MUnitMsg		VARCHAR (50)									,  --大单位转换结果
		InCargoID		INT					DEFAULT (0)					,  --入库货位
		OutCargoID		INT				    DEFAULT (0)					,  --出库货位
		ItemID			INT												,  --自由项
		IsCombined		INT												,  --是否组合项
		KTypeId			VARCHAR(50)										,  --入库仓库
		KTypeId2		VARCHAR (50)									   --出库仓库
	) 
 END
 GO
 
 



GO
/*
*		仓库入库单 仓库出库单表
*/
IF NOT EXISTS (SELECT 1 FROM sysobjects WHERE id = OBJECT_ID(N'dbo.FactDepotInOut') AND type in (N'U'))
BEGIN

	CREATE TABLE dbo.FactDepotInOut
	(
		BillNumberID		INT NOT NULL,							--单据ID
		BillType			INT,									--单据类型
		Id					INT  IDENTITY(1,1) ,					--ID
		ptypeid				VARCHAR(50) ,							--商品ID
		ktypeid				VARCHAR (50) ,							--仓库ID
		qty					NUMERIC (24, 10) DEFAULT (0),			--基本单位数量
		UnitID				INT				 DEFAULT (0),			--浮动计量单位
		UnitRate			NUMERIC(24,10)	 DEFAULT (1),			--浮动单位转换率			 
		NQty				NUMERIC (24, 10) DEFAULT (0),			--辅助数量
		NUnitID				INT			     DEFAULT (0),		    --辅助单位
		NUnitMsg			VARCHAR(50)      DEFAULT (''),			--换算结果
		MUnitID			    INT              DEFAULT (0),		    --大单位ID     入库单位  出库单位	
		MQty				NUMERIC(24,10),							--大单位数量  入库数量  出库数量
		MUnitRate		    NUMERIC(24,10)   DEFAULT(1),			--大单位换算率
		MUnitMsg			VARCHAR(50)		 DEFAULT(''),			--大单位换算结果
		ItemID				INT              DEFAULT(0),			--自由项
		IsCombined			INT				 DEFAULT(0),			--是否组合项
		GoodsOrder			INT				 DEFAULT('-1'),			
		GoodsNumber			VARCHAR(100)	 DEFAULT(''),			--批号
		ProduceDate			VARCHAR (50)     DEFAULT(''),			--生产日期
		ValidDate		    VARCHAR (50)     DEFAULT(''),			--效期至
		CargoID				INT				 DEFAULT(0),			--货位
		FromBillID			INT              DEFAULT(0),			--来源单据明细ID
		FromBillNumberID    INT				 DEFAULT(0),			--来源单据编号
		FromBillType		INT				 DEFAULT(0),			--来源单据类型
		Serial				NVARCHAR(MAX)	 DEFAULT (''),			--序列号
		comment				VARCHAR (250)    DEFAULT (''),			--说明备注
		entryCode			VARCHAR(50)      DEFAULT('')			--商品条码
	)  

 END
  
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='BillType')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD BillType INT
END


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='UnitRate')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD UnitRate	NUMERIC(24,10)	 DEFAULT (1)
END


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='NUnitMsg')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD NUnitMsg	VARCHAR(50)      DEFAULT ('')
END
	

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='MUnitID')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD MUnitID	INT    DEFAULT (0)
END


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='MQty')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD MQty	NUMERIC(24,10)
END
	

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='MUnitRate')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD MUnitRate	NUMERIC(24,10) DEFAULT(1)
END
	

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='MUnitMsg')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD MUnitMsg	VARCHAR(50)		 DEFAULT('')
END
	

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='GoodsNumber')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD GoodsNumber		VARCHAR(100)	 DEFAULT('')
END
	

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='FromBillNumberID')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD FromBillNumberID    INT			DEFAULT(0)
END
	

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='FromBillType')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD FromBillType	INT		DEFAULT(0)
END
	

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='entryCode')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
	ADD entryCode			VARCHAR(50)      DEFAULT('')	
END

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='BillDate')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
		ADD BillDate DATETIME 
END

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactDepotInOut',N'U') AND Name='STypeId')
BEGIN
	ALTER TABLE dbo.FactDepotInOut 
		ADD STypeId VARCHAR(50) 
END

GO	 









IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[FactIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[FactIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200)  DEFAULT (''),
		[OtherType] [numeric](4, 0) NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[Stypeid] [varchar](50)  DEFAULT (''),
		[dtypeId] [varchar](50),
		[etypeid] [varchar](50) ,
		[ktypeid] [varchar](50)  DEFAULT ('0'),
		[ktypeid2] [varchar](50) DEFAULT ('0'),
		[ifcheck] [char](1)   ,
		[checke] [varchar](50)  NULL, --zhidanren
		[checkTime]	DATETIME NULL,
		[RedWord] [int]  NULL  DEFAULT (0),
		[RedReason] [varchar](500)  NULL DEFAULT (''),
		[draft] [bit] NOT NULL  DEFAULT (0),
		[totalqty] [numeric](24, 10) NULL   DEFAULT (0),
		[IsIni] BIT NULL DEFAULT(0),
		[EntryCode] VARCHAR(200) NULL DEFAULT (''),
		[Comment] [varchar](256)  NULL  DEFAULT (''),
		[explain] [varchar](256)  NULL  DEFAULT (''),
		[updateE]   [varchar](50)   NULL DEFAULT ('') ,--修改人
		[DealBTypeID] [varchar](50)  DEFAULT (''),
		[LastUpdateTime] [datetime]  NULL DEFAULT(GETDATE()),
		[Poster]					VARCHAR(100) DEFAULT(''),
		[PostTime]					DATETIME,
		[FromBillType]				INT DEFAULT(0),
		[ifcargo] BIT NULL DEFAULT(0)--启用货位调整
		)
END
	
	--------------------修改--------------------
	
	IF NOT EXISTS(SELECT  1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactIndex',N'U') AND Name='Poster')
	BEGIN
		ALTER TABLE dbo.FactIndex
		ADD Poster VARCHAR(100) DEFAULT('')
	END
	GO
	
	IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactIndex',N'U') AND Name='PostTime')
	BEGIN
		ALTER TABLE dbo.FactIndex
		ADD PostTime DATETIME
	END	
	GO
	
	IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactIndex',N'U') AND Name='FromBillType')
	BEGIN
		ALTER TABLE dbo.FactIndex
		ADD FromBillType INT DEFAULT(0)
	END	
	GO
	
	IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactIndex',N'U') AND Name='updateE')
	BEGIN
		ALTER TABLE dbo.FactIndex
		ADD updateE VARCHAR(50)
	END	
	GO
	
	IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactIndex',N'U') AND Name='OtherType')
	BEGIN
		ALTER TABLE dbo.FactIndex
		ADD OtherType [numeric](4, 0) NOT NULL
	END	
	GO
	
	IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactIndex',N'U') AND Name='DealBTypeID')
	BEGIN
		ALTER TABLE dbo.FactIndex
		ADD DealBTypeID VARCHAR(50)
	END	
	GO
	
	IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactIndex',N'U') AND Name='LastUpdateTime')
	BEGIN
		ALTER TABLE dbo.FactIndex
		ADD LastUpdateTime [datetime]  NULL DEFAULT(GETDATE())
	END	
	GO

    IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactIndex',N'U') AND Name='ifcargo')
	BEGIN
		ALTER TABLE dbo.FactIndex
		ADD ifcargo BIT NULL DEFAULT 0
	END	
	GO


	--------------------修改--------------------
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FACTINDEX') AND name = 'CIX_FACTINDEX_BillDate')
--DROP INDEX CIX_FACTINDEX_BillDate ON FACTINDEX 
CREATE CLUSTERED INDEX CIX_FACTINDEX_BillDate ON FACTINDEX(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FACTINDEX') AND name = 'NCIX_FACTINDEX_BillNumberID')
--DROP INDEX NCIX_FACTINDEX_BillNumberID ON FACTINDEX 
CREATE NONCLUSTERED INDEX NCIX_FACTINDEX_BillNumberID ON FACTINDEX(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FACTINDEX') AND name = 'NCIX_FACTINDEX_Billcode')
--DROP INDEX NCIX_FACTINDEX_Billcode ON FACTINDEX 
CREATE NONCLUSTERED INDEX NCIX_FACTINDEX_Billcode ON FACTINDEX(Billcode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FACTINDEX') AND name = 'NCIX_FACTINDEX_DealBtypeid')
--DROP INDEX NCIX_FACTINDEX_Btypeid ON FACTINDEX 
CREATE NONCLUSTERED INDEX NCIX_FACTINDEX_DealBtypeid ON FACTINDEX(DealBtypeid) 

--IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FACTINDEX') AND name = 'NCIX_FACTINDEX_Atypeid')
----DROP INDEX NCIX_FACTINDEX_Atypeid ON FACTINDEX 
--CREATE NONCLUSTERED INDEX NCIX_FACTINDEX_Atypeid ON FACTINDEX(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FACTINDEX') AND name = 'NCIX_FACTINDEX_Etypeid')
--DROP INDEX NCIX_FACTINDEX_Etypeid ON FACTINDEX 
CREATE NONCLUSTERED INDEX NCIX_FACTINDEX_Etypeid ON FACTINDEX(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FACTINDEX') AND name = 'NCIX_FACTINDEX_Ktypeid')
--DROP INDEX NCIX_FACTINDEX_Ktypeid ON FACTINDEX 
CREATE NONCLUSTERED INDEX NCIX_FACTINDEX_Ktypeid ON FACTINDEX(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FACTINDEX') AND name = 'NCIX_FACTINDEX_Ktypeid2')
--DROP INDEX NCIX_FACTINDEX_Ktypeid2 ON BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_FACTINDEX_Ktypeid2 ON FACTINDEX(Ktypeid2) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[FACTINDEX]') AND name = N'NCIX_FACTINDEX_STYPEID_INCLUDE')
--DROP INDEX [NCIX_FACTINDEX_STYPEID_INCLUDE] ON [dbo].[FACTINDEX] WITH ( ONLINE = OFF )
--GO
CREATE NONCLUSTERED INDEX [NCIX_FACTINDEX_STYPEID_INCLUDE] ON [dbo].FACTINDEX 
(
	[Stypeid] ASC,
	[BillDate] ASC,
	[BillType] ASC
)
INCLUDE ( [BillNumberId]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

------------------------------------------创建索引区域结束-----------------------------------------------
	
GO







IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[FactInOut]') AND type in (N'U'))
BEGIN

	CREATE TABLE [dbo].[FactInOut] 
	(
		[billNumberID] [numeric] (18, 0) NOT NULL,
		[Id] [int]  IDENTITY(1,1) ,
		[billtype] INT NOT NULL,
		[Stypeid] varchar(50),
		[ptypeid] [varchar] (50) ,
		[ktypeid] [varchar] (50) ,
		[qty] [numeric] (24, 10) DEFAULT ((0)),
		[UnitID] [int] NULL   DEFAULT ((0)),-- 基本单位
		[NQty] [numeric] (24, 10) NULL DEFAULT ((0)),
		[NUnitID] [int] NULL  DEFAULT ((0)),-- 浮动单位
		[ItemID] [bigint] NULL DEFAULT ((0)),
		[IsCombined] [int] NULL DEFAULT ((0)),
		[GoodsOrder] [int] NULL  DEFAULT ('-1'),
		[ProduceDate] [varchar] (50)   DEFAULT (''),
		[ValidDate] [varchar] (50)  DEFAULT (''),
		[CargoID] [int]     DEFAULT ((0)),
		[Serial] [varchar](MAX)  DEFAULT (''),
		[comment] [varchar] (250)  DEFAULT ('')	,
		FromBillNumberID  INT,						--来源单据
		FromBillID		  INT,					    --来源单据明细
		FromBillType      INT						--来源单据类型
	)  

 END

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='IsUnit2')
BEGIN
	ALTER TABLE FactInOut
	ADD IsUnit2 int
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='FromBillNumberID')
BEGIN
	ALTER TABLE FactInOut
	ADD FromBillNumberID int
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='FromBillID')
BEGIN
	ALTER TABLE FactInOut
	ADD FromBillID int
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='FromBillType')
BEGIN
	ALTER TABLE FactInOut
	ADD FromBillType int
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='GoodsNumber')
BEGIN
	ALTER TABLE FactInOut
	ADD GoodsNumber VARCHAR(100)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='NUnitMsg')
BEGIN
	ALTER TABLE FactInOut
	ADD NUnitMsg VARCHAR(50)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='MUnitMsg')
BEGIN
	ALTER TABLE FactInOut
	ADD MUnitMsg VARCHAR(50)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='STypeId')
BEGIN
	ALTER TABLE FactInOut
	ADD STypeId VARCHAR(50)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='entryCode')
BEGIN
	ALTER TABLE FactInOut
	ADD entryCode VARCHAR(50)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='UnitRate')
BEGIN
	ALTER TABLE FactInOut
	ADD UnitRate numeric(24,10) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='MQty')
BEGIN
	ALTER TABLE FactInOut
	ADD MQty numeric(24,10) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='MUnitRate')
BEGIN
	ALTER TABLE FactInOut
	ADD MUnitRate numeric(24,10) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='MUnitID')
BEGIN
	ALTER TABLE FactInOut
	ADD MUnitID int
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='Base')
BEGIN
	ALTER TABLE FactInOut
	ADD Base VARCHAR(500)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FactInOut',N'U') AND Name='Sqty')
BEGIN
	ALTER TABLE FactInOut
	ADD Sqty [numeric] (24, 10) 
END
GO
 




GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FactStocks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FactStocks]
	(
		[PtypeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
		[JobNumber] [varchar] (20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FactStocks_JobNumber] DEFAULT (''),
		[OutFactoryDate] [datetime] NULL CONSTRAINT [DF_FactStocks_OutFactoryDate] DEFAULT (getdate()),
		[Qty] [numeric] (24, 10) NULL CONSTRAINT [DF_FactStocks_Qty] DEFAULT ((0)),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_FactStocks_GoodsOrder] DEFAULT ((0)),
		[GoodsNumber] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FactStocks_GoodsNumber] DEFAULT (''),
		[ProduceDate] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FactStocks_ProduceDate] DEFAULT (''),
		[ValidDate] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FactStocks_ValidDate] DEFAULT ('')
	)  

END
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FactStocks') AND name = 'CIX_FactStocks_PtypeId')
	CREATE CLUSTERED INDEX [CIX_FactStocks_PtypeId] ON [dbo].[FactStocks] ([PtypeId]) ON [PRIMARY]
	
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FactStocks') AND name = 'CIX_FactStocks_PtypeId')
	CREATE NONCLUSTERED INDEX [CIX_FactStocks_PtypeId] ON [dbo].[FactStocks] ([KtypeId], [Qty]) ON [PRIMARY]

GO

 




GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FactStocks_Qty]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FactStocks_Qty]
	(
	[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
	[KTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
	[CargoID] [int] NULL,
	[ItemID] [int] NULL,
	[Iscombined] [bit] NULL,
	[GoodsNumber] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL,
	[ProduceDate] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FactStocks_Qty_ProduceDate] DEFAULT (''),
	[ValidDate] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FactStocks_Qty_ValidDate] DEFAULT (''),
	[Qty] [numeric] (24, 10) NULL,
	[NQty] [numeric] (24, 10) NULL  DEFAULT ((0)),
	) 
END
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FactStocks_Qty') AND name = 'CIX_FactStocks_Qty_Ptypeid_Ktypeid')
	CREATE CLUSTERED INDEX [CIX_FactStocks_Qty_Ptypeid_Ktypeid] ON [dbo].[FactStocks_Qty] ([PTypeID], [KTypeID]) ON [PRIMARY]
GO




/****** 对象:  Table [dbo].[FaPiaoBill]    脚本日期: 05/05/2010 14:47:20 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FaPiaoBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FaPiaoBill](
		[BillNumberID] [numeric](10, 0) NOT NULL CONSTRAINT [DF_FaPiaoBill_BillNumberID]  DEFAULT (0),
		[BillType] [numeric](4, 0) NOT NULL,
		[MainBillNumberID] [numeric](10, 0) NULL CONSTRAINT [DF_FaPiaoBill_MainBillNumberID]  DEFAULT (0),
		[KTypeID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBill_KTypeID]  DEFAULT (''),
		[PTypeID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBill_PTypeID]  DEFAULT (''),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBill_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBill_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBill_Total]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_FaPiaoBill_Tax]  DEFAULT (0),
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBill_Comment]  DEFAULT (''),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')	,
		[discount] [numeric](18, 4) NULL DEFAULT (1),
		[BeforePrice] [numeric](18, 4) NULL DEFAULT (0),
		[BeforeTotal] [numeric](18, 4) NULL DEFAULT (0),
		[RecordedItemId] INT NOT NULL DEFAULT(0),
	   Nprice               numeric(22,10)       NULL  DEFAULT(0),
	   NTotal               numeric(22,10)       NULL  DEFAULT(0),
	   NTaxPrice            numeric(22,10)       NULL  DEFAULT(0),
	   NTaxTotal            numeric(22,10)       NULL  DEFAULT(0),
	   NTaxMoney            numeric(22,10)       NULL  DEFAULT(0),
	   CargoID              int                  NULL  DEFAULT(0),
	   UnitID               int                  null,
	   NUnitID              int                  null,
	   NQty                 numeric(22,10)       NULL  DEFAULT(0),
	   UnitRate             numeric(22,10)       NULL  DEFAULT(0),
	   NUnitMsg             varchar(50)          NULL  ,
	   MUnitID              int                  NULL  DEFAULT(0),
	   MQty                 numeric(22,10)       NULL  DEFAULT(0),
	   MUnitRate            numeric(22,10)       NULL  DEFAULT(0),
	   MUnitMsg             varchar(50)          NULL  ,
	   MPrice				numeric(22,10)       NULL  DEFAULT(0),
	   MTaxPrice            numeric(22,10)       NULL  DEFAULT(0),
	   CurMPrice			numeric(22,10)       NULL  DEFAULT(0),
	   CurMTaxPrice         numeric(22,10)       NULL  DEFAULT(0),
	   ItemID               bigint               null   DEFAULT(0),
	   IsCombined           int                  null	DEFAULT(0),
	   Nbeforeprice         numeric(22,10)       NULL DEFAULT(0),
	   Nberoretotal         numeric(22,10)       NULL DEFAULT(0),
	   goodsnumber			 [varchar](100),
	   saleprice			numeric(22,10)       NULL DEFAULT(0),
	   saletotal			numeric(22,10)       NULL DEFAULT(0),
	   nsaleprice			numeric(22,10)       NULL DEFAULT(0),
	   nsaletotal			numeric(22,10)       NULL DEFAULT(0),
	   curmsaleprice		numeric(22,10)       NULL DEFAULT(0),
	   curmsaletotal		numeric(22,10)       NULL DEFAULT(0),
	   taxmoney				numeric(22,10)       NULL DEFAULT(0)
	   ,ShowOrder INT DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FaPiaoBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.FaPiaoBill 
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.FaPiaoBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE FaPiaoBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='discount'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD discount NUMERIC(18,4) NULL DEFAULT(1)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='BeforePrice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD BeforePrice NUMERIC(18,4) NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='BeforeTotal'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD BeforeTotal NUMERIC(18,4) NULL DEFAULT(0)
END

GO
-- 添加已开票明细记录id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='RecordedItemId'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD RecordedItemId INT NOT NULL DEFAULT(0)
END 
GO

---------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='CurRate  '
)
BEGIN
	ALTER TABLE FaPiaoBill ADD CurRate   NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Nprice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD Nprice NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NTotal'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD  NTotal NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NTaxPrice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD NTaxPrice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NTaxTotal'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD NTaxTotal NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NTaxMoney'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD NTaxMoney NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='CargoID'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD CargoID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='UnitID'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD UnitID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NUnitID'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD NUnitID INT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NQty'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD NQty  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='UnitRate'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD UnitRate  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NUnitMsg'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD NUnitMsg VARCHAR(50) NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MUnitID'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD  MUnitID  INT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MQty'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD  MQty   NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MUnitRate'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD  MUnitRate  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MUnitMsg'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   MUnitMsg  VARCHAR(50) NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MPrice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD  MPrice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MTaxPrice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   MTaxPrice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='CurMPrice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   CurMPrice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='CurMTaxPrice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   CurMTaxPrice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Nbeforeprice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   Nbeforeprice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Nberoretotal'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   Nberoretotal  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   ItemID  BIGINT NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('FaPiaoBill') AND b.name='ItemID'
	)
	begin
		select @sql=' alter table FaPiaoBill drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('FaPiaoBill') AND b.name='ItemID'
		EXEC(@sql);
	END
	ALTER TABLE FaPiaoBill ALTER COLUMN ItemID BIGINT NULL;
	ALTER TABLE FaPiaoBill add CONSTRAINT DF_FaPiaoBill_ItemID DEFAULT(0) FOR ItemID
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='IsCombined'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   IsCombined  INT NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('FaPiaoBill') AND b.name='IsCombined'
	)
	begin
		select @sql=' alter table FaPiaoBill drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('FaPiaoBill') AND b.name='IsCombined'
		EXEC(@sql);
	END
	ALTER TABLE FaPiaoBill ALTER COLUMN IsCombined int NULL;
	ALTER TABLE FaPiaoBill add CONSTRAINT DF_FaPiaoBill_IsCombined DEFAULT(0) FOR IsCombined
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='goodsnumber'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD    goodsnumber varchar(100)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='saleprice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   saleprice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='saletotal'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   saletotal  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='nsaleprice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   nsaleprice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='nsaletotal'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   nsaletotal  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='curmsaleprice'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   curmsaleprice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='curmsaletotal'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   curmsaletotal  NUMERIC(22,10) NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='taxmoney'
)
BEGIN
	ALTER TABLE FaPiaoBill ADD   taxmoney  NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS (SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FaPiaoBill',N'U') AND Name='ProduceDate')
BEGIN
	ALTER TABLE dbo.FaPiaoBill
	ADD ProduceDate VARCHAR(50) DEFAULT('')
END
GO

UPDATE dbo.FaPiaoBill SET ProduceDate='' WHERE ProduceDate IS NULL
GO

IF NOT EXISTS (SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'FaPiaoBill',N'U') AND Name='ValidDate')
BEGIN
	ALTER TABLE dbo.FaPiaoBill
	ADD ValidDate VARCHAR(50) DEFAULT('')
END
GO

UPDATE dbo.FaPiaoBill SET ValidDate='' WHERE ValidDate IS NULL
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CurRate' UNION ALL SELECT 'CompleteQty ' UNION ALL SELECT 'CompleteTotal ' UNION ALL SELECT 'NCompleteTotal ' UNION ALL SELECT 'IsGift ';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='FaPiaoBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
	


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILL') AND name = 'CIX_FAPIAOBILL_MainBillNumberID')
--DROP INDEX CIX_FAPIAOBILL_MainBillNumberID ON FAPIAOBILL 
CREATE CLUSTERED INDEX CIX_FAPIAOBILL_MainBillNumberID ON FAPIAOBILL(MainBillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILL') AND name = 'NCIX_FAPIAOBILL_BillNumberID')
--DROP INDEX NCIX_FAPIAOBILL_BillNumberID ON FAPIAOBILL 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILL_BillNumberID ON FAPIAOBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILL') AND name = 'NCIX_FAPIAOBILL_Ktypeid')
--DROP INDEX NCIX_FAPIAOBILL_Ktypeid ON FAPIAOBILL 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILL_Ktypeid ON FAPIAOBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILL') AND name = 'NCIX_FAPIAOBILL_Ptypeid')
--DROP INDEX NCIX_FAPIAOBILL_Ptypeid ON FAPIAOBILL 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILL_Ptypeid ON FAPIAOBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILL') AND name = 'NCIX_FAPIAOBILL_BillType')
--DROP INDEX NCIX_FAPIAOBILL_BillType ON FAPIAOBILL 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILL_BillType ON FAPIAOBILL(BillType) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='BeforePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN BeforePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='BeforeTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN BeforeTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Nprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN Nprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN MPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='CurMPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN CurMPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Nbeforeprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN Nbeforeprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='Nberoretotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN Nberoretotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='saleprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN saleprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='saletotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN saletotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='nsaleprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN nsaleprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='nsaletotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN nsaletotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='curmsaleprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN curmsaleprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='curmsaletotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN curmsaletotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='taxmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN taxmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBill' AND a.Name='CurRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBill 
	ALTER COLUMN CurRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FaPiaoBillIndex]    脚本日期: 05/05/2010 14:47:21 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FaPiaoBillIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FaPiaoBillIndex](
		[BillNumberID] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_InvoiceBillIndex_BillCode]  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[FaPiaoType] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBillIndex_FaPiaoType]  DEFAULT (1),
		[FaPiaoCode] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBillIndex_FaPiaoCode]  DEFAULT (''),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InvoiceBillIndex_Comment]  DEFAULT (''),
		[Explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBillIndex_Explain]  DEFAULT (''),
		[BTypeID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBillIndex_BTypeID]  DEFAULT (''),
		[ETypeID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBillIndex_ETypeID]  DEFAULT (''),
		[DTypeID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_FaPiaoBillIndex_DTypeID]  DEFAULT (''),
		[checke] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Assessor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_FaPiaoBillIndex_Tax]  DEFAULT (17),
		[TotalQty] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBillIndex_TotalQty]  DEFAULT (0),
		[TotalMoney] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBillIndex_TotalMoney]  DEFAULT (0),
		[TaxTotalMoney] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBillIndex_TaxTotalMoney]  DEFAULT (0),
		[ID] [int] NULL CONSTRAINT [DF_FaPiaoBillIndex_ID]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[OtherTotal] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBillIndex_OtherTotal]  DEFAULT (0),
		[ifYearBill] [int] NULL CONSTRAINT [DF_FaPiaoBillIndex_ifYearBill]  DEFAULT (0),
		[IsIni]	BIT NULL DEFAULT(0),
		CID int  NULL DEFAULT(0),
		Rate NUMERIC(22,10) DEFAULT(0),
		NTotalMoney NUMERIC(22,10) NULL DEFAULT(0),
		NTotalInMoney NUMERIC(22,10) NULL DEFAULT(0),
		NTaxTotalMoney NUMERIC(22,10) NULL DEFAULT(0),
		DealBTypeID VARCHAR(50) NULL DEFAULT(0),
		TaskType tinyint NULL DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE FaPiaoBillIndex SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='OtherTotal'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD [OtherTotal] [numeric](18, 4) NULL CONSTRAINT [DF_FaPiaoBillIndex_OtherTotal]  DEFAULT (0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='ifYearBill'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD [ifYearBill] [int] NULL CONSTRAINT [DF_FaPiaoBillIndex_ifYearBill]  DEFAULT (0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex 
		ADD IsIni BIT NULL DEFAULT(0)
		
	EXEC('UPDATE FaPiaoBillIndex SET IsIni=0 WHERE IsIni IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='CID'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD CID int  NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD Rate NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD NTotalMoney NUMERIC(22,10) NULL DEFAULT(0)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='NTaxTotalMoney'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD NTaxTotalMoney NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='DealBTypeID'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD DealBTypeID VARCHAR(50) DEFAULT('')
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='TaskType'
)
BEGIN
	ALTER TABLE FaPiaoBillIndex ADD TaskType TINYINT DEFAULT(0)
END
GO


DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CurID' UNION ALL SELECT 'NTotalInMoney ' UNION ALL SELECT 'AlertDay '
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='FaPiaoBillIndex';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILLINDEX') AND name = 'CIX_FAPIAOBILLINDEX_BillDate')
--DROP INDEX CIX_FAPIAOBILLINDEX_BillDate ON FAPIAOBILLINDEX 
CREATE CLUSTERED INDEX CIX_FAPIAOBILLINDEX_BillDate ON FAPIAOBILLINDEX(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILLINDEX') AND name = 'NCIX_FAPIAOBILLINDEX_Etypeid')
--DROP INDEX NCIX_FAPIAOBILLINDEX_Etypeid ON FAPIAOBILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILLINDEX_Etypeid ON FAPIAOBILLINDEX(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILLINDEX') AND name = 'NCIX_FAPIAOBILLINDEX_Btypeid')
--DROP INDEX NCIX_FAPIAOBILLINDEX_Btypeid ON FAPIAOBILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILLINDEX_Btypeid ON FAPIAOBILLINDEX(Btypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILLINDEX') AND name = 'NCIX_FAPIAOBILLINDEX_Dtypeid')
--DROP INDEX NCIX_FAPIAOBILLINDEX_Dtypeid ON FAPIAOBILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILLINDEX_Dtypeid ON FAPIAOBILLINDEX(Dtypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILLINDEX') AND name = 'NCIX_FAPIAOBILLINDEX_Assessor')
--DROP INDEX NCIX_FAPIAOBILLINDEX_Assessor ON FAPIAOBILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILLINDEX_Assessor ON FAPIAOBILLINDEX(Assessor) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILLINDEX') AND name = 'NCIX_FAPIAOBILLINDEX_Checke')
--DROP INDEX NCIX_FAPIAOBILLINDEX_Checke ON FAPIAOBILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILLINDEX_Checke ON FAPIAOBILLINDEX(Checke) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FAPIAOBILLINDEX') AND name = 'NCIX_FAPIAOBILLINDEX_BillNumberID')
--DROP INDEX NCIX_FAPIAOBILLINDEX_BillNumberID ON FAPIAOBILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_FAPIAOBILLINDEX_BillNumberID ON FAPIAOBILLINDEX(BillNumberID) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE FaPiaoBillIndex SET [OtherTotal]=0 WHERE [OtherTotal] IS NULL
UPDATE FaPiaoBillIndex SET [ifYearBill]=0 WHERE [ifYearBill] IS NULL
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='TotalQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN TotalQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='TaxTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN TaxTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='OtherTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN OtherTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='NTotalInMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN NTotalInMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FaPiaoBillIndex' AND a.Name='NTaxTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FaPiaoBillIndex 
	ALTER COLUMN NTaxTotalMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[fb_a]    脚本日期: 05/05/2010 14:47:22 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[fb_a]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[fb_a](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[A] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  [FixedAssetsDetails]    脚本日期: 2014-04-08  ******/
SET ANSI_NULLS ON



SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FixedAssetsDetails]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
create  table FixedAssetsDetails --明细表
(
ID                  [numeric](10, 0) IDENTITY(1,1) NOT NULL, --自增ID
BillNumberID	varchar(100),	--单据编号
AssertsCardId		int,			--待盘资产id
UserCode			varchar(200),	--待盘资产编号
FullName			varchar(200),	--资产名称
barcode		        int	,			--固定资产条码
acstate			int	,			--状态内容为固定资产卡片上的状态
panbarcode				varchar(200),	--盘点条码
panstate			int,				--盘点状态
comment				varchar(200),	--备注
[DraftFlag] [bit] NOT NULL DEFAULT (1),
[IsIniFlag] [bit] NOT NULL DEFAULT (0)
)

END
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'FixedAssetsDetails',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.FixedAssetsDetails
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'FixedAssetsDetails',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.FixedAssetsDetails
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('FixedAssetsDetails') AND name ='BillIndexNumberID')
	exec sp_rename 'FixedAssetsDetails.BillIndexNumberID','BillNumberID','column';
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  [FixedAssetsIndex]    脚本日期: 2014-04-08  ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FixedAssetsIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
create  table FixedAssetsIndex --索引表
(
createdate	 date,			--录单日期
billcode     varchar(100),  -- 单据编号
BillNumberID [numeric](10, 0) IDENTITY(1,1) NOT NULL,  --单据ID
stypeid		 varchar(50),	--分支机构
dtypeId		 varchar(50),	--部门
etypeId		 varchar(50),	--经手人
[state]		 int	,		--状态 待盘点/已盘点/已处理  1/2/3
memo		 varchar(200),	--说明
comment		 varchar(200),   --摘要
)
end
go

if not exists (select name from syscolumns where id = object_id(N'[dbo].[FixedAssetsIndex]') and  name = 'billcode')
BEGIN
     ALTER TABLE FixedAssetsIndex   add  billcode varchar(100) NULL
END
GO




------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[FrozeBusiness]') AND type in (N'U'))
BEGIN
	CREATE TABLE FrozeBusiness(
		Stypeid VARCHAR(50) NULL,
		FrozeDate DATETIME NULL
	) ON [PRIMARY]
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





/****** Object:  Table [dbo].[frtype]    Script Date: 09/19/2011 09:22:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[frtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[frtype](
	[typeId] [varchar](50) NULL,
	[ParId] [varchar](50) NULL,
	[leveal] [smallint] NOT NULL,
	[sonnum] [int] NOT NULL,
	[soncount] [int] NOT NULL,
	[UserCode] [varchar](200) NULL,
	[FaultExplain] [varchar](1000) NULL,
	[FaultReason] [varchar](2000) NULL,
	[XiWaMaxNumber] [numeric](19, 0) NULL
) ON [PRIMARY]

	-- ********	处理 frtype	********
	DELETE FROM frtype
	INSERT INTO frtype( typeid,parid,leveal,sonnum,soncount,UserCode,FaultExplain,FaultReason,XiWaMaxNumber)VALUES('00000','root',0,0,0,'0','维修故障档案','维修故障档案',1)
END
GO

SET ANSI_PADDING OFF
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FZ_Color]    脚本日期: 05/05/2010 14:47:23 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FZ_Color]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FZ_Color](
		[ColorID] [int] NOT NULL,
		[ColorName] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Del] [bit] NOT NULL CONSTRAINT [DF_FZ_Color_Del]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[FZ_Color]') AND name = N'PK_FZ_Color')
ALTER TABLE [dbo].[FZ_Color] DROP CONSTRAINT [PK_FZ_Color]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FZ_COLOR') AND name = 'CIX_FZ_COLOR_ColorID')
--DROP INDEX CIX_FZ_COLOR_ColorID ON FZ_COLOR 
CREATE CLUSTERED INDEX CIX_FZ_COLOR_ColorID ON FZ_COLOR(ColorID) 

------------------------------------------创建索引区域结束-----------------------------------------------
--原始数据
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.FZ_Color)
BEGIN
	INSERT INTO dbo.FZ_Color(ColorID, ColorName, Del)VALUES(16,'橙96',0)
	INSERT INTO dbo.FZ_Color(ColorID, ColorName, Del)VALUES(176,'绿1056',0)
	INSERT INTO dbo.FZ_Color(ColorID, ColorName, Del)VALUES(446,'红2676',0)
	INSERT INTO dbo.FZ_Color(ColorID, ColorName, Del)VALUES(696,'黄4176',0)
END
GO
--第一次调整数据
TRUNCATE TABLE dbo.FZ_Color
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.FZ_Color)
BEGIN
	INSERT INTO dbo.FZ_Color(ColorID, ColorName, Del)VALUES(104,'橙624',0)
	INSERT INTO dbo.FZ_Color(ColorID, ColorName, Del)VALUES(240,'红1440',0)
	INSERT INTO dbo.FZ_Color(ColorID, ColorName, Del)VALUES(960,'绿5760',0)
	INSERT INTO dbo.FZ_Color(ColorID, ColorName, Del)VALUES(1200,'黄7200',0)	
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FZ_ColorGroup]    脚本日期: 05/05/2010 14:47:24 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FZ_ColorGroup]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FZ_ColorGroup](
		[ColorGroupID] [int] NOT NULL,
		[ColorGroupName] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Del] [bit] NOT NULL CONSTRAINT [DF_FZ_ColorGroup_Del]  DEFAULT (0),
		[Comment] VARCHAR(100) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


--添加[Comment]字段
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[FZ_ColorGroup]') AND name='Comment')
	ALTER TABLE [dbo].[FZ_ColorGroup] 
		ADD Comment VARCHAR(100) NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[FZ_ColorGroup]') AND name = N'PK_FZ_ColorGroup')
ALTER TABLE [dbo].[FZ_ColorGroup] DROP CONSTRAINT [PK_FZ_ColorGroup]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FZ_COLORGROUP') AND name = 'CIX_FZ_COLORGROUP_ColorGroupID')
--DROP INDEX CIX_FZ_COLORGROUP_ColorGroupID ON FZ_COLORGROUP 
CREATE CLUSTERED INDEX CIX_FZ_COLORGROUP_ColorGroupID ON FZ_COLORGROUP(ColorGroupID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------

------------------------------------------添加预置数据区域开始-----------------------------------------------
IF NOT EXISTS(SELECT 1 FROM FZ_ColorGroup WHERE ColorGroupName = 'ZTUniqueCode')
	INSERT INTO FZ_ColorGroup(ColorGroupID,ColorGroupName,Del,COMMENT) VALUES(0,'ZTUniqueCode',1,'')
------------------------------------------添加预置数据区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FZ_CurColorSize]    脚本日期: 05/05/2010 14:47:25 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FZ_CurColorSize]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FZ_CurColorSize](
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ColorID] [int] NOT NULL,
		[SizeID] [int] NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FZ_CurColorSize' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FZ_CurColorSize 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FZ_InitColorSize]    脚本日期: 05/05/2010 14:47:26 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FZ_InitColorSize]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FZ_InitColorSize](
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ColorID] [int] NOT NULL,
		[SizeID] [int] NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FZ_InitColorSize' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FZ_InitColorSize 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FZ_InOutColorSize]    脚本日期: 05/05/2010 14:47:27 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FZ_InOutColorSize]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FZ_InOutColorSize](
		[BillDate] [datetime] NOT NULL,
		[BillNumberID] [varchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BillType] [numeric](18, 0) NOT NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ColorID] [int] NOT NULL,
		[SizeID] [int] NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[IfCheck] [int] NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='FZ_InOutColorSize' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE FZ_InOutColorSize 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FZ_Size]    脚本日期: 05/05/2010 14:47:28 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FZ_Size]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FZ_Size](
		[SizeID] [int] NOT NULL,
		[SizeName] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Del] [bit] NOT NULL CONSTRAINT [DF_FZ_Size_Del]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[FZ_Size]') AND name = N'PK_FZ_Size')
ALTER TABLE [dbo].[FZ_Size] DROP CONSTRAINT [PK_FZ_Size]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FZ_SIZE') AND name = 'CIX_FZ_SIZE_SizeID')
--DROP INDEX CIX_FZ_SIZE_SizeID ON FZ_SIZE 
CREATE CLUSTERED INDEX CIX_FZ_SIZE_SizeID ON FZ_SIZE(SizeID) 



------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FZ_SizeGroup]    脚本日期: 05/05/2010 14:47:29 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FZ_SizeGroup]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FZ_SizeGroup](
		[SizeGroupID] [int] NOT NULL,
		[SizeGroupName] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Del] [bit] NOT NULL CONSTRAINT [DF_FZ_SizeGroup_Del]  DEFAULT (0),
		[Comment] VARCHAR(100) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


--添加[Comment]字段
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[FZ_SizeGroup]') AND name='Comment')
	ALTER TABLE [dbo].[FZ_SizeGroup] 
		ADD Comment VARCHAR(100) NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[FZ_SizeGroup]') AND name = N'PK_FZ_SizeGroup')
ALTER TABLE [dbo].[FZ_SizeGroup] DROP CONSTRAINT [PK_FZ_SizeGroup]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('FZ_SIZEGROUP') AND name = 'CIX_FZ_SIZEGROUP_SizeGroupID')
--DROP INDEX CIX_FZ_SIZEGROUP_SizeGroupID ON FZ_SIZEGROUP 
CREATE CLUSTERED INDEX CIX_FZ_SIZEGROUP_SizeGroupID ON FZ_SIZEGROUP(SizeGroupID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------


------------------------------------------添加预置数据区域开始-----------------------------------------------
IF NOT EXISTS(SELECT 1 FROM FZ_SizeGroup WHERE SizeGroupName = 'ZTUniqueCode')
	INSERT INTO FZ_SizeGroup(SizeGroupID,SizeGroupName,Del,COMMENT) VALUES(0,'ZTUniqueCode',1,'')
------------------------------------------添加预置数据区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FZ_SizeMatching]    脚本日期: 05/05/2010 14:47:30 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[FZ_SizeMatching]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[FZ_SizeMatching](
		[SizeID] [int] NOT NULL,
		[SizeGroupID] [int] NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[gatheringBill]    脚本日期: 05/05/2010 14:47:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[gatheringBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[gatheringBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_gatheringBill_total]  DEFAULT (0),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gatheringBill_BillComment]  DEFAULT (''),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		 ntotal		numeric(22,10) null DEFAULT(0)	
		 ,ShowOrder INT DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		 PreferenceMoney		numeric(24,10) null DEFAULT(0)	,
		 nPreferenceMoney	numeric(24,10) null DEFAULT(0)	
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'gatheringBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.gatheringBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'gatheringBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.gatheringBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'gatheringBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.gatheringBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE gatheringBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE gatheringBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE gatheringBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='VipCardID'
)
BEGIN
	ALTER TABLE gatheringBill ADD VipCardID INT NULL DEFAULT(-1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='ntotal'
)
BEGIN
	ALTER TABLE gatheringBill ADD ntotal NUMERIC(22,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='RelevanceBillId'
)
BEGIN
	ALTER TABLE gatheringBill ADD RelevanceBillId NUMERIC(10,0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='BrandarTypeID'
)
BEGIN
	ALTER TABLE gatheringBill 
		ADD BrandarTypeID  VARCHAR(50) NOT NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='PreferenceMoney'
)
BEGIN
	ALTER TABLE gatheringBill ADD PreferenceMoney NUMERIC(24,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='NPreferenceMoney'
)
BEGIN
	ALTER TABLE gatheringBill ADD NPreferenceMoney NUMERIC(24,10) DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gatheringBill]') AND name = N'IX_gatheringBill')
DROP INDEX [dbo].[gatheringBill].[IX_gatheringBill]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GATHERINGBILL') AND name = 'CIX_GATHERINGBILL_BillNumberID')
--DROP INDEX CIX_GATHERINGBILL_BillNumberID ON GATHERINGBILL 
CREATE CLUSTERED INDEX CIX_GATHERINGBILL_BillNumberID ON GATHERINGBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GATHERINGBILL') AND name = 'NCIX_GATHERINGBILL_Stypeid')
--DROP INDEX NCIX_GATHERINGBILL_Stypeid ON GATHERINGBILL 
CREATE NONCLUSTERED INDEX NCIX_GATHERINGBILL_Stypeid ON GATHERINGBILL(Stypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GATHERINGBILL') AND name = 'NCIX_GATHERINGBILL_Atypeid')
--DROP INDEX NCIX_GATHERINGBILL_Atypeid ON GATHERINGBILL 
CREATE NONCLUSTERED INDEX NCIX_GATHERINGBILL_Atypeid ON GATHERINGBILL(Atypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE gatheringBill SET VipCardID = -1 WHERE VipCardID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE gatheringBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gatheringBill' AND a.Name='ntotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE gatheringBill 
	ALTER COLUMN ntotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  供应商自定义字段
  张陈仁
  3023-04-10
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GBtype_CustomColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table GBtype_CustomColumns 
	(
	   ID                   bigint               identity(1,1),
	   typeid               varchar(100)         null,
	   Costom1              VARCHAR(600)         null,
	   Costom2              VARCHAR(600)         null,
	   Costom3              VARCHAR(600)         null,
	   Costom4              VARCHAR(600)         null,
	   Costom5              VARCHAR(600)         null,
	   Costom6              VARCHAR(600)         null,
	   Costom7              VARCHAR(600)         null,
	   Costom8              VARCHAR(600)         null,
	   Costom9              VARCHAR(600)         null,
	   Costom10             VARCHAR(600)         null,
	   Costom11             VARCHAR(600)         null,
	   Costom12             VARCHAR(600)         null,
	   Costom13             VARCHAR(600)         null,
	   Costom14             VARCHAR(600)         null,
	   Costom15             VARCHAR(600)         null,
	   Costom16             VARCHAR(600)         null,
	   Costom17             VARCHAR(600)         null,
	   Costom18             VARCHAR(600)         null,
	   Costom19             VARCHAR(600)         null,
	   Costom20             VARCHAR(600)         null
   )
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GDSETCODE]    脚本日期: 05/05/2010 14:47:32 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GDSETCODE]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GDSETCODE](
		[ID] [int] NOT NULL CONSTRAINT [DF_GDSETCODE_ID]  DEFAULT (1),
		[SETCODECHAR] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Des] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_GDSETCODE_Des]  DEFAULT (''),
		[FlagDate] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_GDSETCODE_FlagDate]  DEFAULT ('0'),
		[Years] [char](4) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_GDSETCODE_Years]  DEFAULT ('0'),
		[months] [char](2) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_GDSETCODE_months]  DEFAULT ('0'),
		[days] [char](2) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_GDSETCODE_days]  DEFAULT ('0')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--添加Code
	DELETE FROM GDSETCODE
	INSERT GDSETCODE VALUES (1,'仓库编号','KUserCode',0,0,0,0)
	INSERT GDSETCODE VALUES (2,'经手人编号','EUserCode',0,0,0,0)
	INSERT GDSETCODE VALUES (13,'部门编号','DUserCOde',0,0,0,0)
	INSERT GDSETCODE VALUES (14,'制单人编号','CEUserCOde',0,0,0,0)
	--新增分支机构
	INSERT GDSETCODE VALUES (3,'YYYY年MM月DD日','2004-12-13',1,4,2,2)
	INSERT GDSETCODE VALUES (4,'YYYY年M月D日','2004-12-13',1,4,1,1)
	INSERT GDSETCODE VALUES (5,'YY年MM月DD日','04-12-13',1,2,2,2)
	INSERT GDSETCODE VALUES (6,'YY年M月D日','04-12-13',1,2,1,1)
	INSERT GDSETCODE VALUES (7,'MM月DD日','12-13',1,0,2,2)
	INSERT GDSETCODE VALUES (8,'M月D日','12-13',1,0,1,1)
	INSERT GDSETCODE VALUES (9,'YYYY年','2006',1,4,0,0)
	INSERT GDSETCODE VALUES (10,'YY年','06',1,2,0,0)
	INSERT GDSETCODE VALUES (11,'YYYY年MM月','2006-05',1,4,2,0)
	INSERT GDSETCODE VALUES (12,'YY年MM月','04-12',1,2,2,0)

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GDSETCODE]') AND name = N'PK_GDSETCODE')
ALTER TABLE [dbo].[GDSETCODE] DROP CONSTRAINT [PK_GDSETCODE]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GDSETCODE') AND name = 'CIX_GDSETCODE_SETCODECHAR')
--DROP INDEX CIX_GDSETCODE_SETCODECHAR ON GDSETCODE 
CREATE CLUSTERED INDEX CIX_GDSETCODE_SETCODECHAR ON GDSETCODE(SETCODECHAR) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GiveBill]    脚本日期: 05/05/2010 14:47:32 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GiveBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GiveBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_GiveBill_Qty]  DEFAULT (0),
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveBill_JobNumber]  DEFAULT (''),
		[GoodsNo] [int] NULL CONSTRAINT [DF_GiveBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_GiveBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_GiveBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_GiveBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_GiveBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_GiveBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_GiveBill_HandZeroCost]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		 UnitID               int                NULL Default(0),
	    NUnitID              int                NULL Default(0),
	    NQty                 numeric(22,10)     NULL Default(0),
	    UnitRate             numeric(22,10)     NULL Default(0),
	    NUnitMsg             varchar(50)        null,
	    MUnitID              int                NULL Default(0),
	    MQty                 numeric(22,10)     NULL Default(0),
	    MUnitRate            numeric(22,10)     NULL Default(1),
	    MUnitMsg             varchar(50)        null,
	    CargoID              int               NULL Default(0),
	       ItemID               bigint               null,
	   IsCombined           int                  null	,
	   KTypeId VARCHAR(50) NOT NULL DEFAULT('')
	   ,ShowOrder INT DEFAULT(0)
	   ,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
	   ,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
	   ,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'GiveBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.GiveBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'GiveBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.GiveBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'GiveBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.GiveBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.GiveBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'GiveBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE GiveBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE GiveBill SET PickedQty=0 WHERE PickedQty IS NULL
GO
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'GiveBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.GiveBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.GiveBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

------------------------------------------表修改区域结束-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE GiveBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE GiveBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE Givebill ADD UnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE Givebill ADD NUnitID INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE Givebill ADD NQty   numeric(22,10)    NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE Givebill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE Givebill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE Givebill ADD MUnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE Givebill ADD MQty   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE Givebill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE Givebill ADD MUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE Givebill ADD CargoID   INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE Givebill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE Givebill ADD IsCombined   INT
END
GO

-- 添加多仓库字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='KTypeId'
)
BEGIN
	ALTER TABLE Givebill ADD KTypeId VARCHAR(50) NOT NULL DEFAULT('')
END
GO

-- 添加物流运输 已发运数量
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='SendedQty'
)
BEGIN
	ALTER TABLE Givebill ADD SendedQty DECIMAL(24,10)  NULL DEFAULT(0)
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givebill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('Givebill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table Givebill drop constraint '+@dfname);
		
	ALTER TABLE Givebill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE Givebill ADD CONSTRAINT DF_Givebill_Serial DEFAULT('') FOR Serial

END
-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CargoSpace';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='GiveBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
	
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE GiveBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO 
------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GiveBill]') AND name = N'CIX_BID')
	DROP INDEX [dbo].GiveBill.CIX_BID
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GiveBill]') AND name = N'NCIX_PTYPEID')
	DROP INDEX [dbo].GiveBill.NCIX_PTYPEID
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------]
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GIVEBILL') AND name = 'CIX_GIVEBILL_BillNumberID')
--DROP INDEX CIX_GIVEBILL_BillNumberID ON GIVEBILL 
CREATE CLUSTERED INDEX CIX_GIVEBILL_BillNumberID ON GIVEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GIVEBILL') AND name = 'NCIX_GIVEBILL_Ptypeid')
--DROP INDEX NCIX_GIVEBILL_Ptypeid ON GIVEBILL 
CREATE NONCLUSTERED INDEX NCIX_GIVEBILL_Ptypeid ON GIVEBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GIVEBILL') AND name = 'NCIX_GIVEBILL_Stypeid')
--DROP INDEX NCIX_GIVEBILL_Stypeid ON GIVEBILL 
CREATE NONCLUSTERED INDEX NCIX_GIVEBILL_Stypeid ON GIVEBILL(Stypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

go
-- 添加了多仓库后更新以前老版本数据
update a set a.ktypeid=b.ktypeid from givebill a join billindex b on a.billnumberid=b.BillNumberId 
WHERE a.ktypeid='' OR a.ktypeid IS NULL;

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END                                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GiveFromSaleOrBuy]    脚本日期: 05/05/2010 14:47:33 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GiveFromSaleOrBuy]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GiveFromSaleOrBuy](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[SourceBillNumberId] [int] NULL,
		[DestBillNumberId] [int] NULL,
		[IfCheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GiveFromSaleOrBuyBill]    脚本日期: 05/05/2010 14:47:34 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GiveFromSaleOrBuyBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GiveFromSaleOrBuyBill](
		[BillID] [int] IDENTITY(1,1) NOT NULL,
		[ID] [int] NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveFromSaleOrBuyBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE GiveFromSaleOrBuyBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE GiveFromSaleOrBuyBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GiveFromSaleOrBuyBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GiveFromSaleOrBuyBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GivemeBill]    脚本日期: 05/05/2010 14:47:35 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GivemeBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GivemeBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_GivemeBill_Qty]  DEFAULT (0),
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GivemeBill_JobNumber]  DEFAULT (''),
		[GoodsNo] [int] NULL CONSTRAINT [DF_GivemeBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_GivemeBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GivemeBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_GivemeBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_GivemeBill_GoodsOrder_1]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveMeBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveMeBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveMeBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GiveMeBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_GiveMeBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_GiveMeBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_GiveMeBill_HandZeroCost]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		 UnitID               int                NULL Default(0),
	    NUnitID              int                NULL Default(0),
	    NQty                 numeric(22,10)     NULL Default(0),
	    UnitRate             numeric(22,10)     NULL Default(0),
	    NUnitMsg             varchar(50)        null,
	    MUnitID              int                NULL Default(0),
	    MQty                 numeric(22,10)     NULL Default(0),
	    MUnitRate            numeric(22,10)     NULL Default(1),
	    MUnitMsg             varchar(50)        null,
	    CargoID              int               NULL Default(0),
	    ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    KTypeId VARCHAR(50) NOT NULL DEFAULT('')	
	    ,ShowOrder INT DEFAULT(0)
	    ,InflowQty NUMERIC(24,10) DEFAULT(0) --入库数量
	    ,InFactQty NUMERIC(24,10) DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'GivemeBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.GivemeBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'GivemeBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.GivemeBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'GivemeBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.GivemeBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.GivemeBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'GivemeBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.GivemeBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.GivemeBill SET InFactQty=0 WHERE InFactQty IS NULL
GO
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'GivemeBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.GivemeBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.GivemeBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE GivemeBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE GivemeBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE Givemebill ADD UnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE Givemebill ADD NUnitID INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE Givemebill ADD NQty   numeric(22,10)    NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE Givemebill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE Givemebill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE Givemebill ADD MUnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE Givemebill ADD MQty   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE Givemebill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE Givemebill ADD MUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE Givemebill ADD CargoID   INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE Givemebill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE Givemebill ADD IsCombined   INT
END
GO
-- 添加多仓库字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='KTypeId'
)
BEGIN
	ALTER TABLE Givemebill ADD KTypeId VARCHAR(50) NOT NULL DEFAULT('')
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('Givemebill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table Givemebill drop constraint '+@dfname);
		
	ALTER TABLE Givemebill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE Givemebill ADD CONSTRAINT DF_Givemebill_Serial DEFAULT('') FOR Serial

END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='Givemebill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b on a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Givemebill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE Givemebill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO 
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GIVEMEBILL') AND name = 'CIX_GIVEMEBILL_BillNumberID')
--DROP INDEX CIX_GIVEMEBILL_BillNumberID ON GIVEMEBILL 
CREATE CLUSTERED INDEX CIX_GIVEMEBILL_BillNumberID ON GIVEMEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GIVEMEBILL') AND name = 'NCIX_GIVEMEBILL_Stypeid')
--DROP INDEX NCIX_GIVEMEBILL_Stypeid ON GIVEMEBILL 
CREATE NONCLUSTERED INDEX NCIX_GIVEMEBILL_Stypeid ON GIVEMEBILL(Stypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GIVEMEBILL') AND name = 'NCIX_GIVEMEBILL_Ptypeid')
--DROP INDEX NCIX_GIVEMEBILL_Ptypeid ON GIVEMEBILL 
CREATE NONCLUSTERED INDEX NCIX_GIVEMEBILL_Ptypeid ON GIVEMEBILL(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
go
-- 添加了多仓库后更新以前老版本数据
update a set a.ktypeid=b.ktypeid from dbo.GivemeBill a join billindex b on a.billnumberid=b.BillNumberId 
WHERE a.ktypeid='' OR a.ktypeid IS NULL;
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GivemeBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GivemeBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GivemeBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GivemeBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GivemeBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GivemeBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GivemeBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GivemeBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GivemeBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GoodsExchangeBill]    脚本日期: 05/05/2010 14:47:36 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GoodsExchangeBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GoodsExchangeBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[InOrOut] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[discount] [numeric](18, 4) NULL,
		[DiscountPrice] [numeric](18, 4) NULL,
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_GoodsExchangeBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsno] [numeric](18, 4) NULL,
		[total] [numeric](18, 4) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_GoodsExchangeBill_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_GoodsExchangeBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_GoodsExchangeBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_GoodsExchangeBill_GoodsOrder]  DEFAULT ('-1')
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	ALTER TABLE GoodsExchangeBill ALTER COLUMN Serial VARCHAR(MAX)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='goodsno' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN goodsno NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsExchangeBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsExchangeBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GoodsLend]    脚本日期: 05/05/2010 14:47:37 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GoodsLend]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GoodsLend](
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GoodsLend_JobNumber]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL CONSTRAINT [DF_GoodsLend_OutFactoryDate]  DEFAULT (getdate()),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_GoodsLend_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_GoodsLend_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_GoodsLend_Total]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_GoodsLend_GoodsOrder]  DEFAULT (0),
		GoodsNumber					VARCHAR(100) DEFAULT(''),		
		ItemID						INT DEFAULT(0),
		Iscombined					BIT DEFAULT(0),
		NQty						NUMERIC(22,10)	DEFAULT(0),
		ProduceDate					VARCHAR(50)		DEFAULT (''),
		ValidDate					VARCHAR(50)		DEFAULT ('')
		
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE GoodsLend ADD
		ItemID						INT DEFAULT(0),
		Iscombined					BIT DEFAULT(0),
		NQty						NUMERIC(22,10)	DEFAULT(0),
		GoodsNumber					VARCHAR(100) DEFAULT(''),		
		ProduceDate					VARCHAR(50)		DEFAULT (''),
		ValidDate					VARCHAR(50)		DEFAULT ('')
		
END
GO




IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='LendQty'
)
BEGIN
	ALTER TABLE GoodsLend ADD LendQty NUMERIC(22,10) NULL DEFAULT(0)
END
GO
UPDATE GoodsLend SET LendQty = 0 WHERE LendQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='NLendQty'
)
BEGIN
	ALTER TABLE GoodsLend ADD NLendQty NUMERIC(22,10) NULL DEFAULT(0)
END
GO
UPDATE GoodsLend SET NLendQty = 0 WHERE NLendQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='BorrowQty'
)
BEGIN
	ALTER TABLE GoodsLend ADD BorrowQty NUMERIC(22,10) NULL DEFAULT(0)
END
GO
UPDATE GoodsLend SET BorrowQty = 0 WHERE BorrowQty IS NULL
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='NBorrowQty'
)
BEGIN
	ALTER TABLE GoodsLend ADD NBorrowQty NUMERIC(22,10) NULL DEFAULT(0)
END
GO
UPDATE GoodsLend SET NBorrowQty = 0 WHERE NBorrowQty IS NULL
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal' UNION ALL SELECT 'CargoID';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='GoodsLend';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GoodsLend]') AND name = N'goodsstockindex')
DROP INDEX [dbo].[GoodsLend].[goodsstockindex]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GOODSLEND') AND name = 'CIX_GOODSLEND_Ptypeid_Ktypeid')
--DROP INDEX CIX_GOODSLEND_Ptypeid_Ktypeid ON GOODSLEND 
CREATE CLUSTERED INDEX CIX_GOODSLEND_Ptypeid_Ktypeid ON GOODSLEND(Ptypeid,Ktypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLend 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLend 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLend 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLend 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='LendQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLend 
	ALTER COLUMN LendQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='NLendQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLend 
	ALTER COLUMN NLendQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='BorrowQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLend 
	ALTER COLUMN BorrowQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLend' AND a.Name='NBorrowQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLend 
	ALTER COLUMN NBorrowQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GoodsLocal]    脚本日期: 05/05/2010 14:47:38 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GoodsLocal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GoodsLocal](
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LTypeID] [varchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[OutFactoryDate] [datetime] NULL,
		[QTY] [numeric](18, 4) NOT NULL,
		[Price] [numeric](18, 4) NULL,
		[Total] [numeric](18, 4) NULL,
		[GoodsOrder] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLocal' AND a.Name='QTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLocal 
	ALTER COLUMN QTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLocal' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLocal 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsLocal' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsLocal 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GoodsStocks]    脚本日期: 05/05/2010 14:47:38 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GoodsStocks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GoodsStocks](
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GoodsStocks_JobNumber]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL CONSTRAINT [DF_GoodsStocks_OutFactoryDate]  DEFAULT (getdate()),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_GoodsStocks_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_GoodsStocks_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_GoodsStocks_Total]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_GoodsStocks_GoodsOrder]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GoodsStocks_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GoodsStocks_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GoodsStocks_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GoodsStocks_GoodsBTypeID]  DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GoodsStocks]') AND name = N'CIX_PTYPEID')
	DROP INDEX [dbo].[GoodsStocks].CIX_PTYPEID
--老板中使用的是goodsstockindex，因此需要drop
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GoodsStocks]') AND name = N'goodsstockindex')
	DROP INDEX [dbo].[GoodsStocks].[goodsstockindex]
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GoodsStocks]') AND name = N'NCIX_KTYPEID')
	DROP INDEX [dbo].[GoodsStocks].NCIX_KTYPEID
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GOODSSTOCKS') AND name = 'CIX_GOODSSTOCKS_PtypeId')
--DROP INDEX CIX_GOODSSTOCKS_PtypeId ON GOODSSTOCKS 
CREATE CLUSTERED INDEX CIX_GOODSSTOCKS_PtypeId ON GOODSSTOCKS(PtypeId) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GOODSSTOCKS') AND name = 'NCIX_GOODSSTOCKS_KtypeId_Qty')
DROP INDEX NCIX_GOODSSTOCKS_KtypeId_Qty ON GOODSSTOCKS 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsStocks' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsStocks 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_GOODSSTOCKS_KtypeId_Qty ON GOODSSTOCKS(KtypeId,Qty) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsStocks' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsStocks 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsStocks' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GoodsStocks 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GOODSSTOCKS_ASSIST]    脚本日期: 05/05/2010 14:47:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSSTOCKS_ASSIST]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE GOODSSTOCKS_ASSIST
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GOODSSTOCKS_BATCHNO]    脚本日期: 05/05/2010 14:47:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSSTOCKS_BATCHNO]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE GOODSSTOCKS_BATCHNO
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GOODSSTOCKS_CARGO]    脚本日期: 05/05/2010 14:47:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSSTOCKS_CARGO]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE GOODSSTOCKS_CARGO
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GoodsStocks_Draft]    脚本日期: 05/05/2010 14:47:38 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GoodsStocks_Draft]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GoodsStocks_Draft](	
		[ID]  INT IDENTITY(1,1) PRIMARY KEY,
		[PtypeId]	VARCHAR(50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT (''),	--商品ID
		[KtypeId]	VARCHAR(50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT (''),	--仓库ID		
		[GoodsNumber]	VARCHAR(100) NOT NULL DEFAULT (''),		--批号
		[ProduceDate]	VARCHAR(50) CONSTRAINT [DF_GoodsStocks_Qty_ProduceDate] NOT NULL DEFAULT (''),	--生产日期
		[ValidDate]	VARCHAR(50) CONSTRAINT [DF_GoodsStocks_Qty_ValidDate] NOT NULL DEFAULT (''),	--效期至
		[CargoID]	INT NOT NULL DEFAULT(0),	--货位
		[ItemID]	INT NOT NULL DEFAULT(0),	--自由项
		[IsCombined]	BIT NOT NULL DEFAULT(0),	--是否自由项组合
		[RQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--草稿入库数量
		[CQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--草稿出库数量
		[Qty]	[numeric](24,10) NOT NULL DEFAULT (0),	--草稿库存数量【入库-出库】
		GoodsCostPrice	  NUMERIC(24,10) NOT NULL DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsStocks_Draft' AND a.Name='GoodsCostPrice'
)
BEGIN	
	ALTER TABLE GoodsStocks_Draft ADD GoodsCostPrice NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
/****** Object:  Index [PK__GoodsSto__3214EC275BDBB2AD]    Script Date: 09/07/2017 18:48:39 ******/
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[GoodsStocks_Draft]') AND name LIKE N'PK__GoodsSto__%')
BEGIN
	DECLARE 
		@strTemp VARCHAR(100)
	SELECT @strTemp=NAME
	FROM sys.indexes 
	WHERE object_id = OBJECT_ID(N'[dbo].[GoodsStocks_Draft]') AND name LIKE N'PK__GoodsSto__%'	
		
	EXEC('ALTER TABLE [dbo].[GoodsStocks_Draft] DROP CONSTRAINT ['+@strTemp+']')
END
GO





IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GoodsStocks_Draft') AND name = 'NCIX_GoodsStocks_Draft_WD')

DROP INDEX [NCIX_GoodsStocks_Draft_WD] ON [dbo].[GoodsStocks_Draft] WITH ( ONLINE = OFF )
GO



IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GoodsStocks_Draft') AND name = 'CIX_GoodsStocks_Draft_WD')
CREATE CLUSTERED INDEX CIX_GoodsStocks_Draft_WD ON GoodsStocks_Draft(ptypeid,ktypeid,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined) 


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GoodsStocks_Draft') AND name = 'NCIX_GoodsStocks_Draft_PKtypeID') 
CREATE NONCLUSTERED INDEX NCIX_GoodsStocks_Draft_PKtypeID ON GoodsStocks_Draft(ptypeid,ktypeid) 

GO
------------------------------------------创建索引区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GOODSSTOCKS_ITEM]    脚本日期: 05/05/2010 14:47:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSSTOCKS_ITEM]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE GOODSSTOCKS_ITEM
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GoodsStocks_Order]    脚本日期: 2017-08-24 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GoodsStocks_Order]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GoodsStocks_Order](	
		[ID]  INT IDENTITY(1,1) PRIMARY KEY,
		[PtypeId]	VARCHAR(50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT (''),	--商品ID
		[KtypeId]	VARCHAR(50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT (''),	--仓库ID		
		[GoodsNumber]	VARCHAR(100) NOT NULL DEFAULT (''),		--批号
		[ProduceDate]	VARCHAR(50) NOT NULL DEFAULT (''),	--生产日期
		[ValidDate]	VARCHAR(50) NOT NULL DEFAULT (''),	--效期至
		[CargoID]	INT NOT NULL DEFAULT(0),	--货位
		[ItemID]	INT NOT NULL DEFAULT(0),	--自由项
		[IsCombined]	BIT NOT NULL DEFAULT(0),	--是否自由项组合
		GoodsCostPrice	  NUMERIC(24,10) NOT NULL DEFAULT(0),--成本价
		[SaleOrderQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--销售订单数量
		[SaleReferQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--销售被引用未过账数量
		[SaleReachQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--销售被引用已过账数量
		[LimitSaleQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--销售被引用过账数量<=销售订单数量
		[BuyOrderQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--采购订单数量
		[BuyReferQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--采购被引用未过账数量
		[BuyReachQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--采购被引用已过账数量
		[LimitBuyQty]	[numeric](24,10) NOT NULL DEFAULT (0)	--采购被引用过账数量<=采购订单数量
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsStocks_Order' AND a.Name='LimitSaleQty'
)
BEGIN	
	ALTER TABLE GoodsStocks_Order ADD LimitSaleQty NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GoodsStocks_Order' AND a.Name='LimitBuyQty'
)
BEGIN	
	ALTER TABLE GoodsStocks_Order ADD LimitBuyQty NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GoodsStocks_Order') AND name = 'NCIX_GoodsStocks_Order_PKtypeID') 
CREATE NONCLUSTERED INDEX NCIX_GoodsStocks_Order_PKtypeID ON GoodsStocks_Order(ptypeid,ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GoodsStocks_Order') AND name = 'NCIX_GoodsStocks_Order_WD')
CREATE NONCLUSTERED INDEX NCIX_GoodsStocks_Order_WD ON GoodsStocks_Order(ptypeid,ktypeid,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID) 
------------------------------------------创建索引区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GOODSSTOCKS_QTY]    脚本日期: 05/05/2010 14:47:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSSTOCKS_QTY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

	CREATE TABLE GOODSSTOCKS_QTY  (
	  ID				  INT IDENTITY(1,1),
	  PTypeID             VARCHAR(50),
	  KTypeID             VARCHAR(50),
	  CargoID             INT,
	  ItemID              INT,
	  Iscombined          BIT,
	  GoodsNumber         VARCHAR(100),
	  ProduceDate		  VARCHAR(50) CONSTRAINT [DF_GoodsStocks_Qty_ProduceDate]  DEFAULT (''),
	  ValidDate			  VARCHAR(50) CONSTRAINT [DF_GoodsStocks_Qty_ValidDate]  DEFAULT (''),
	  Qty                 NUMERIC(24,10),
	  NQty				  NUMERIC(24,10) DEFAULT(0),
	  GoodsCostPrice	  NUMERIC(24,10) DEFAULT(0),
	  LockNumber		NUMERIC(24,10) NOT NULL DEFAULT(0)
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GOODSSTOCKS_QTY' AND a.Name='NQty'
)
BEGIN
	ALTER TABLE GOODSSTOCKS_QTY DROP COLUMN AlterableQty
	
	ALTER TABLE GOODSSTOCKS_QTY ADD NQty NUMERIC(24,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GOODSSTOCKS_QTY' AND a.Name='GoodsCostPrice'
)
BEGIN
	ALTER TABLE GOODSSTOCKS_QTY ADD GoodsCostPrice NUMERIC(24,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GOODSSTOCKS_QTY' AND a.Name='LockNumber'
)
BEGIN
	ALTER TABLE GOODSSTOCKS_QTY ADD LockNumber NUMERIC(24,10) NOT NULL DEFAULT(0) 
	END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'GoodsOrder';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='GOODSSTOCKS_QTY';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GOODSSTOCKS_QTY') AND name = 'CIX_GOODSSTOCKS_QTY_Ptypeid_Ktypeid')
--DROP INDEX CIX_GOODSSTOCKS_QTY_Ptypeid_Ktypeid ON GOODSSTOCKS_QTY 
CREATE CLUSTERED INDEX CIX_GOODSSTOCKS_QTY_Ptypeid_Ktypeid ON GOODSSTOCKS_QTY(Ptypeid,Ktypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------









------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GOODSSTOCKS_QTY' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GOODSSTOCKS_QTY 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GOODSSTOCKS_QTY' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GOODSSTOCKS_QTY 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GOODSSTOCKS_QTY' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GOODSSTOCKS_QTY 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[gp_CruPtypeSerial]    脚本日期: 05/05/2010 14:47:39 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_CruPtypeSerial]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[gp_CruPtypeSerial](
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_CruPtypeSerial_BTypeID1]  DEFAULT (''),
		[BTypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_CruPtypeSerial_BTypeID2]  DEFAULT (''),
		[InKtypeTime] [datetime] NULL,
		[OutKtypeTime] [datetime] NULL,
		[User] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_CruPtypeSerial_User]  DEFAULT (''),
		[State] [int] NOT NULL CONSTRAINT [DF_gp_CruPtypeSerial_State]  DEFAULT (1),
		[Note] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_CruPtypeSerial_Note]  DEFAULT (''),
		[Flag] [bit] NOT NULL CONSTRAINT [DF_gp_CruPtypeSerial_Flag]  DEFAULT (1),
		[CommissionState] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_CruPtypeSerial_CommissionState]  DEFAULT (''),
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[iniFlag] [int] NULL CONSTRAINT [DF_gp_CruPtypeSerial_iniFlag]  DEFAULT (0),
		[CostPrice] [numeric](18,4) DEFAULT(0) NULL,
		[GoodsOrder] int DEFAULT(0) NULL,
		[GoodsNumber] VARCHAR(100) DEFAULT('') NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Gp_CruPtypeSerial ADD STypeId VARCHAR(50) DEFAULT '' NULL	
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE gp_CruPtypeSerial SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='Comment1'  )
BEGIN
	ALTER TABLE Gp_CruPtypeSerial ADD Comment1 VARCHAR(256) DEFAULT '' NULL	
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='Comment2'   )
BEGIN
	ALTER TABLE Gp_CruPtypeSerial ADD Comment2 VARCHAR(256) DEFAULT '' NULL	
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='Comment3')
BEGIN
	ALTER TABLE Gp_CruPtypeSerial ADD Comment3 VARCHAR(256) DEFAULT '' NULL	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='CostPrice'
)
BEGIN
	ALTER TABLE Gp_CruPtypeSerial ADD CostPrice NUMERIC(18,4) DEFAULT 0 NULL
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE gp_CruPtypeSerial SET CostPrice=0
	WHERE CostPrice IS NULL '
	
	EXEC(@strSql)
END
GO


IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='CostTotal'
)
BEGIN
	DECLARE @strCONSTRAINT VARCHAR(100)
	
	SELECT @strCONSTRAINT=a.name 
	FROM sys.default_constraints a
	INNER JOIN sys.all_objects b
	ON a.parent_object_id=b.object_id
	INNER JOIN sys.all_columns c
	ON a.parent_column_id=c.column_id
	AND a.parent_object_id=c.object_id
	WHERE b.name='gp_CruPtypeSerial' and c.name='CostTotal'
	
	
	EXEC('
	ALTER TABLE dbo.gp_CruPtypeSerial
	DROP CONSTRAINT '+@strCONSTRAINT+'
	
	ALTER TABLE Gp_CruPtypeSerial DROP COLUMN CostTotal
	')
	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='GoodsOrder'
)
BEGIN
	ALTER TABLE Gp_CruPtypeSerial ADD GoodsOrder INT DEFAULT 0 NULL
	
	--升级
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='GoodsNumber'
)
BEGIN
	ALTER TABLE Gp_CruPtypeSerial ADD [GoodsNumber] VARCHAR(100) DEFAULT('') NULL
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_CruPtypeSerial' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE Gp_CruPtypeSerial ADD ItemID INT DEFAULT 0 NULL,IsCombined BIT  DEFAULT 0 NULL ,CargoID INT DEFAULT 0,ProduceDate VARCHAR(50) DEFAULT '' NULL,ValidDate VARCHAR(50) DEFAULT '' NULL
END
GO

EXEC('
IF EXISTS(
	SELECT PTypeID
	FROM Gp_CruPtypeSerial
	WHERE ItemID IS NULL
)
BEGIN

	UPDATE Gp_CruPtypeSerial
	SET ItemID=0,IsCombined=0,CargoID=0,ProduceDate='''',ValidDate=''''
	WHERE ItemID IS NULL
	
END
')
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'AppraisalState' UNION SELECT 'IsOnShelves' UNION SELECT 'IsPicked' UNION SELECT 'IsTransported'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='Gp_CruPtypeSerial';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO





------------------------------------------表修改区域结束-------------------------------------------------
--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('gp_CruPtypeSerial') and name='WdSyncFlag')
BEGIN
	ALTER TABLE dbo.gp_CruPtypeSerial ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End

------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_CruPtypeSerial]') AND name = N'IX_gp_CruPtypeSerial_BTypeID1')
DROP INDEX [dbo].[gp_CruPtypeSerial].[IX_gp_CruPtypeSerial_BTypeID1]
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_CruPtypeSerial]') AND name = N'IX_gp_CruPtypeSerial_BTypeID2')
DROP INDEX [dbo].[gp_CruPtypeSerial].[IX_gp_CruPtypeSerial_BTypeID2]
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_CruPtypeSerial]') AND name = N'IX_gp_CruPtypeSerial_KTypeID')
DROP INDEX [dbo].[gp_CruPtypeSerial].[IX_gp_CruPtypeSerial_KTypeID]
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_CruPtypeSerial]') AND name = N'IX_gp_CruPtypeSerial_PTypeID')
DROP INDEX [dbo].[gp_CruPtypeSerial].[IX_gp_CruPtypeSerial_PTypeID]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_CRUPTYPESERIAL') AND name = 'CIX_GP_CRUPTYPESERIAL_Serial')
--DROP INDEX CIX_GP_CRUPTYPESERIAL_Serial ON GP_CRUPTYPESERIAL 
CREATE CLUSTERED INDEX CIX_GP_CRUPTYPESERIAL_Serial ON GP_CRUPTYPESERIAL(Serial) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_CRUPTYPESERIAL') AND name = 'NCIX_GP_CRUPTYPESERIAL_Ptypeid')
--DROP INDEX NCIX_GP_CRUPTYPESERIAL_Ptypeid ON GP_CRUPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_CRUPTYPESERIAL_Ptypeid ON GP_CRUPTYPESERIAL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_CRUPTYPESERIAL') AND name = 'NCIX_GP_CRUPTYPESERIAL_Ktypeid')
--DROP INDEX NCIX_GP_CRUPTYPESERIAL_Ktypeid ON GP_CRUPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_CRUPTYPESERIAL_Ktypeid ON GP_CRUPTYPESERIAL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_CRUPTYPESERIAL') AND name = 'NCIX_GP_CRUPTYPESERIAL_Btypeid1')
--DROP INDEX NCIX_GP_CRUPTYPESERIAL_Btypeid1 ON GP_CRUPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_CRUPTYPESERIAL_Btypeid1 ON GP_CRUPTYPESERIAL(Btypeid1) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_CRUPTYPESERIAL') AND name = 'NCIX_GP_CRUPTYPESERIAL_Btypeid2')
--DROP INDEX NCIX_GP_CRUPTYPESERIAL_Btypeid2 ON GP_CRUPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_CRUPTYPESERIAL_Btypeid2 ON GP_CRUPTYPESERIAL(Btypeid2) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_CRUPTYPESERIAL') AND name = 'NCIX_GP_CRUPTYPESERIAL_Ltypeid')
--DROP INDEX NCIX_GP_CRUPTYPESERIAL_Ltypeid ON GP_CRUPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_CRUPTYPESERIAL_Ltypeid ON GP_CRUPTYPESERIAL(Ltypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_CRUPTYPESERIAL') AND name = 'NCIX_GP_CRUPTYPESERIAL_InKtypeTime')
--DROP INDEX NCIX_GP_CRUPTYPESERIAL_InKtypeTime ON GP_CRUPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_CRUPTYPESERIAL_InKtypeTime ON GP_CRUPTYPESERIAL(InKtypeTime) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_CRUPTYPESERIAL') AND name = 'NCIX_GP_CRUPTYPESERIAL_OutKtypeTime')
--DROP INDEX NCIX_GP_CRUPTYPESERIAL_OutKtypeTime ON GP_CRUPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_CRUPTYPESERIAL_OutKtypeTime ON GP_CRUPTYPESERIAL(OutKtypeTime) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_CruPtypeSerial' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE gp_CruPtypeSerial 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[gp_CruPtypeSerial]') and  name = 'Serial' and Length=50)
BEGIN
	 ALTER TABLE gp_CruPtypeSerial
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO                                         
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 






GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_FactPtypeSerial]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[gp_FactPtypeSerial]
(
	[Serial] [varchar] (50)  NULL,
	[KtypeID] [varchar] (50) NULL,
	[PtypeID] [varchar] (50)  NULL,
	[InKtypeTime] [datetime] NULL,
	[OutKtypeTime] [datetime] NULL,
	[State] [int] NOT NULL   DEFAULT ((1)),
	[Flag] [bit] NOT NULL DEFAULT ((1)),					--是否在库
	[CommissionState] [varchar] (1)  DEFAULT (''),
	[ETypeID] [varchar] (50)   NULL,
	[GoodsOrder] [int] NULL  DEFAULT ((0)),
	[GoodsNumber] [varchar] (100)   DEFAULT (''),
	[STypeId] [varchar] (50)   DEFAULT (''),
	[Comment1] [varchar] (256)   DEFAULT (''),
	[ItemID] [int] NULL   DEFAULT ((0)),
	[IsCombined] [bit] NULL DEFAULT ((0)),
	[CargoID] [int]  NULL DEFAULT ((0)),
	[ProduceDate] [varchar] (50) NULL DEFAULT (''),
	[ValidDate] [varchar] (50) NULL  DEFAULT (''),
	[iniFlag]	 INT		DEFAULT(0),
	[LendState]  INT DEFAULT(0)                          --借进序列号状态 1=借进，2=借出，3=借进还出，4=借出还回
) 
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'gp_FactPtypeSerial',N'U') AND Name='LendState')
BEGIN
	ALTER TABLE dbo.gp_FactPtypeSerial
	ADD LendState INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'gp_FactPtypeSerial',N'U') AND Name='iniFlag')
BEGIN
	ALTER TABLE dbo.gp_FactPtypeSerial
	ADD iniFlag INT DEFAULT(0)
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[gp_FactPtypeSerial]') and  name = 'Serial' and Length=50)
BEGIN
	 ALTER TABLE gp_FactPtypeSerial
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO	










GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_iniFactPtypeSerial]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[gp_iniFactPtypeSerial]
(
	[Serial] [varchar] (50)  NULL,
	[KtypeID] [varchar] (50) NULL,
	[PtypeID] [varchar] (50)  NULL,
	[InKtypeTime] [datetime] NULL,
	[OutKtypeTime] [datetime] NULL,
	[State] [int] NOT NULL   DEFAULT ((1)),
	[Flag] [bit] NOT NULL DEFAULT ((1)),
	[CommissionState] [varchar] (1)  DEFAULT (''),
	[ETypeID] [varchar] (50)   NULL,
	[IniFlag][int] NULL DEFAULT((1)),
	[GoodsOrder] [int] NULL  DEFAULT ((0)),
	[GoodsNumber] [varchar] (100)   DEFAULT (''),
	[STypeId] [varchar] (50)   DEFAULT (''),
	[Comment1] [varchar] (256)   DEFAULT (''),
	[ItemID] [int] NULL   DEFAULT ((0)),
	[IsCombined] [bit] NULL DEFAULT ((0)),
	[CargoID] [int]  NULL DEFAULT ((0)),
	[ProduceDate] [varchar] (50) NULL DEFAULT (''),
	[ValidDate] [varchar] (50) NULL  DEFAULT (''),
	[LendState] INT DEFAULT(0)
) 
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'gp_iniFactPtypeSerial',N'U') AND Name='IniFlag')
BEGIN
	ALTER TABLE dbo.gp_iniFactPtypeSerial
	ADD [IniFlag][int] NULL DEFAULT(1)
END

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'gp_iniFactPtypeSerial',N'U') AND Name='LendState')
BEGIN
	ALTER TABLE dbo.gp_iniFactPtypeSerial
	ADD LendState INT DEFAULT(0)
END
GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[gp_iniFactPtypeSerial]') and  name = 'Serial' and Length=50)
BEGIN
	 ALTER TABLE gp_iniFactPtypeSerial
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO





/****** 对象:  Table [dbo].[gp_initLendPtypeSerial]    脚本日期: 05/05/2010 14:47:40 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_initLendPtypeSerial]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[gp_initLendPtypeSerial](
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BtypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[InKtypeTime] [datetime] NULL,
		[OutKTypeTime] [datetime] NULL,
		[User] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[State] [int] NULL,
		[Note] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Flag] [bit] NULL,
		[CommissionState] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BFlag] [bit] NULL CONSTRAINT [DF_gp_initLendPtypeSerial_BFlag]  DEFAULT ('0')
	) ON [PRIMARY]


END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_initLendPtypeSerial' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE gp_initLendPtypeSerial ADD ItemID INT DEFAULT 0 NULL,IsCombined BIT  DEFAULT 0 NULL ,CargoID INT DEFAULT 0,ProduceDate VARCHAR(50) DEFAULT '' NULL,ValidDate VARCHAR(50) DEFAULT '' NULL
	
END
GO

EXEC('
IF EXISTS(
	SELECT PTypeID
	FROM gp_initLendPtypeSerial
	WHERE ItemID IS NULL
)
BEGIN
	
	UPDATE gp_initLendPtypeSerial
	SET ItemID=0,IsCombined=0,CargoID=0,ProduceDate='''',ValidDate=''''
	WHERE ItemID IS NULL
	
END
')
GO

IF NOT EXISTS (
	SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'gp_initLendPtypeSerial') AND LOWER(Name)='goodsnumber')
	BEGIN
		ALTER TABLE gp_initLendPtypeSerial ADD GoodsNumber VARCHAR(100) DEFAULT('') 
	END
GO
UPDATE gp_initLendPtypeSerial SET GoodsNumber='' WHERE GoodsNumber IS NULL
GO
------------------------------------------表修改区域开始-------------------------------------------------


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'AppraisalState'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='gp_initLendPtypeSerial';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[gp_initLendPtypeSerial]') and  name = 'Serial' and Length=50)
BEGIN
	 ALTER TABLE gp_initLendPtypeSerial
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO 
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[gp_initPtypeSerial]    脚本日期: 05/05/2010 14:47:41 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_initPtypeSerial]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[gp_initPtypeSerial](
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_initPtypeSerial_BTypeID1]  DEFAULT (''),
		[BtypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_initPtypeSerial_BtypeID2]  DEFAULT (''),
		[InKtypeTime] [datetime] NULL,
		[OutKTypeTime] [datetime] NULL,
		[User] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_initPtypeSerial_User]  DEFAULT (''),
		[State] [int] NULL CONSTRAINT [DF_gp_initPtypeSerial_State]  DEFAULT (1),
		[Note] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_initPtypeSerial_Note]  DEFAULT (''),
		[Flag] [bit] NULL CONSTRAINT [DF_gp_initPtypeSerial_Flag]  DEFAULT (1),
		[CommissionState] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_initPtypeSerial_CommissionState]  DEFAULT (''),
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[iniFlag] [int] NULL CONSTRAINT [DF_gp_initPtypeSerial_iniFlag]  DEFAULT (1),
		[CostPrice] [numeric](18,4) DEFAULT(0) NULL,
		[GoodsOrder] int DEFAULT(0) NULL,
		[GoodsNumber] VARCHAR(100) DEFAULT('') NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD STypeId VARCHAR(50) DEFAULT '' NULL	
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE gp_initPtypeSerial SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='Comment1'  )
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD Comment1 VARCHAR(256) DEFAULT '' NULL	
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='Comment2'   )
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD Comment2 VARCHAR(256) DEFAULT '' NULL	
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='Comment3')
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD Comment3 VARCHAR(256) DEFAULT '' NULL	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='CostPrice'
)
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD CostPrice NUMERIC(18,4) DEFAULT 0 NULL
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE Gp_InitPtypeSerial SET CostPrice=0
	WHERE CostPrice IS NULL '
	
	EXEC(@strSql)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='CostTotal'
)
BEGIN
	DECLARE @strCONSTRAINT VARCHAR(100)
	
	SELECT @strCONSTRAINT=a.name 
	FROM sys.default_constraints a
	INNER JOIN sys.all_objects b
	ON a.parent_object_id=b.object_id
	INNER JOIN sys.all_columns c
	ON a.parent_column_id=c.column_id
	AND a.parent_object_id=c.object_id
	WHERE b.name='Gp_InitPtypeSerial' and c.name='CostTotal'
	
	
	EXEC('
	ALTER TABLE dbo.Gp_InitPtypeSerial
	DROP CONSTRAINT '+@strCONSTRAINT+'
	
	ALTER TABLE Gp_InitPtypeSerial DROP COLUMN CostTotal
	')
	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='GoodsOrder'
)
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD GoodsOrder INT DEFAULT 0 NULL
	
	--升级
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='GoodsNumber'
)
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD [GoodsNumber] VARCHAR(100) DEFAULT('') NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='ID'
)
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD ID INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Gp_InitPtypeSerial' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE Gp_InitPtypeSerial ADD ItemID INT DEFAULT 0 NULL,IsCombined BIT  DEFAULT 0 NULL ,CargoID INT DEFAULT 0,ProduceDate VARCHAR(50) DEFAULT '' NULL,ValidDate VARCHAR(50) DEFAULT '' NULL
	
END
GO

EXEC('
IF EXISTS(
	SELECT PTypeID
	FROM Gp_InitPtypeSerial
	WHERE ItemID IS NULL
)
BEGIN
	UPDATE Gp_InitPtypeSerial
	SET ItemID=0,IsCombined=0,CargoID=0,ProduceDate='''',ValidDate=''''
	WHERE ItemID IS NULL
	
END
')
GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'AppraisalState'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='Gp_InitPtypeSerial';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[gp_initPtypeSerial]') and  name = 'Serial' and Length=50)
BEGIN
	 ALTER TABLE gp_initPtypeSerial
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO   
------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_initPtypeSerial]') AND name = N'IX_gp_initPtypeSerial')
DROP INDEX [dbo].[gp_initPtypeSerial].[IX_gp_initPtypeSerial]
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_initPtypeSerial]') AND name = N'IX_gp_initPtypeSerial_BTypeID1')
DROP INDEX [dbo].[gp_initPtypeSerial].[IX_gp_initPtypeSerial_BTypeID1]
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_initPtypeSerial]') AND name = N'IX_gp_initPtypeSerial_BTypeID2')
DROP INDEX [dbo].[gp_initPtypeSerial].[IX_gp_initPtypeSerial_BTypeID2]
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_initPtypeSerial]') AND name = N'IX_gp_initPtypeSerial_KTypeID')
DROP INDEX [dbo].[gp_initPtypeSerial].[IX_gp_initPtypeSerial_KTypeID]
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_initPtypeSerial]') AND name = N'IX_gp_initPtypeSerial_PTypeID')
DROP INDEX [dbo].[gp_initPtypeSerial].[IX_gp_initPtypeSerial_PTypeID]
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INITPTYPESERIAL') AND name = 'CIX_GP_INITPTYPESERIAL_Serial')
--DROP INDEX CIX_GP_INITPTYPESERIAL_Serial ON GP_INITPTYPESERIAL 
CREATE CLUSTERED INDEX CIX_GP_INITPTYPESERIAL_Serial ON GP_INITPTYPESERIAL(Serial) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INITPTYPESERIAL') AND name = 'NCIX_GP_INITPTYPESERIAL_Ptypeid')
--DROP INDEX NCIX_GP_INITPTYPESERIAL_Ptypeid ON GP_INITPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_INITPTYPESERIAL_Ptypeid ON GP_INITPTYPESERIAL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INITPTYPESERIAL') AND name = 'NCIX_GP_INITPTYPESERIAL_Ktypeid')
--DROP INDEX NCIX_GP_INITPTYPESERIAL_Ktypeid ON GP_INITPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_INITPTYPESERIAL_Ktypeid ON GP_INITPTYPESERIAL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INITPTYPESERIAL') AND name = 'NCIX_GP_INITPTYPESERIAL_Btypeid1')
--DROP INDEX NCIX_GP_INITPTYPESERIAL_Btypeid1 ON GP_INITPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_INITPTYPESERIAL_Btypeid1 ON GP_INITPTYPESERIAL(Btypeid1) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INITPTYPESERIAL') AND name = 'NCIX_GP_INITPTYPESERIAL_Btypeid2')
--DROP INDEX NCIX_GP_INITPTYPESERIAL_Btypeid2 ON GP_INITPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_INITPTYPESERIAL_Btypeid2 ON GP_INITPTYPESERIAL(Btypeid2) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INITPTYPESERIAL') AND name = 'NCIX_GP_INITPTYPESERIAL_Ltypeid')
--DROP INDEX NCIX_GP_INITPTYPESERIAL_Ltypeid ON GP_INITPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_INITPTYPESERIAL_Ltypeid ON GP_INITPTYPESERIAL(Ltypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_initPtypeSerial' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE gp_initPtypeSerial 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
   
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[gp_inoutPtypeSerial]    脚本日期: 05/05/2010 14:47:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_inoutPtypeSerial]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[gp_inoutPtypeSerial](
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BillNumberid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[InKtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[OutKtyeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfCheck] [varchar](4) COLLATE Chinese_PRC_CI_AS NULL,
		[BillType] [int] NULL CONSTRAINT [DF_gp_inoutPtypeSerial_BillType]  DEFAULT (0),
		[BTypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_inoutPtypeSerial_BTypeID1]  DEFAULT (''),
		[BTypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_inoutPtypeSerial_BTypeID2]  DEFAULT (''),
		[InKtypeTime] [datetime] NULL,
		[OutKtypeTime] [datetime] NULL,
		[User] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_gp_inoutPtypeSerial_User]  DEFAULT (''),
		[State] [int] NULL CONSTRAINT [DF_gp_inoutPtypeSerial_State]  DEFAULT (''),
		ID [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[CostPrice] [numeric](18,4) DEFAULT(0) NULL,
		[GoodsOrder] int DEFAULT(0) NULL,
		[GoodsNumber] VARCHAR(100) DEFAULT('') NULL,
		[PostTime] DATETIME DEFAULT GETDATE() NULL,
		[detailID] int DEFAULT(-1) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='CostPrice'
)
BEGIN
	ALTER TABLE gp_inoutPtypeSerial ADD CostPrice NUMERIC(18,4) DEFAULT 0 NULL
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE gp_inoutPtypeSerial SET CostPrice=0
	WHERE CostPrice IS NULL '
	
	EXEC(@strSql)
END
GO


IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='CostTotal'
)
BEGIN
	DECLARE @strCONSTRAINT VARCHAR(100)
	
	SELECT @strCONSTRAINT=a.name 
	FROM sys.default_constraints a
	INNER JOIN sys.all_objects b
	ON a.parent_object_id=b.object_id
	INNER JOIN sys.all_columns c
	ON a.parent_column_id=c.column_id
	AND a.parent_object_id=c.object_id
	WHERE b.name='gp_inoutPtypeSerial' and c.name='CostTotal'
	
	
	EXEC('
	ALTER TABLE dbo.gp_inoutPtypeSerial
	DROP CONSTRAINT '+@strCONSTRAINT+'
	
	ALTER TABLE gp_inoutPtypeSerial DROP COLUMN CostTotal
	')
	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='GoodsOrder'
)
BEGIN
	ALTER TABLE gp_inoutPtypeSerial ADD GoodsOrder INT DEFAULT 0 NULL
	
	--升级
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='GoodsNumber'
)
BEGIN
	ALTER TABLE gp_inoutPtypeSerial ADD [GoodsNumber] VARCHAR(100) DEFAULT('') NULL
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE gp_inoutPtypeSerial ADD ItemID INT DEFAULT 0 NULL,IsCombined BIT  DEFAULT 0 NULL ,CargoID INT DEFAULT 0,ProduceDate VARCHAR(50) DEFAULT '' NULL,ValidDate VARCHAR(50) DEFAULT '' NULL
	
END
GO

EXEC('
IF EXISTS(
	SELECT PTypeID
	FROM gp_inoutPtypeSerial
	WHERE ItemID IS NULL
)
BEGIN

	UPDATE gp_inoutPtypeSerial
	SET ItemID=0,IsCombined=0,CargoID=0,ProduceDate='''',ValidDate=''''
	WHERE ItemID IS NULL

END
')
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='PostTime'
)
BEGIN
	ALTER TABLE gp_inoutPtypeSerial ADD PostTime DATETIME DEFAULT GETDATE() NULL
END
GO

--明细ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='detailID'
)
BEGIN
	ALTER TABLE gp_inoutPtypeSerial ADD detailID INT DEFAULT(-1) NULL
END
GO
EXEC('
IF EXISTS(
	SELECT PTypeID
	FROM gp_inoutPtypeSerial
	WHERE detailID IS NULL
)
BEGIN

	UPDATE gp_inoutPtypeSerial
	SET detailID=-1
	WHERE detailID IS NULL

END
')
GO
--销售单价 
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='saleprice'
--)
--BEGIN
--	ALTER TABLE gp_inoutPtypeSerial ADD saleprice numeric(24,10)  DEFAULT 0 NULL
--	DECLARE @strSql VARCHAR(8000)
	
--	SELECT @strSql='
--	UPDATE gp_inoutPtypeSerial SET saleprice=0
--	WHERE saleprice IS NULL '
	
--	EXEC(@strSql)
--END
--GO
--清除销售单价字段

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'AppraisalState'
INSERT INTO @t SELECT 'saleprice'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='gp_inoutPtypeSerial';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_inoutPtypeSerial]') AND name = N'IX_gp_inoutPtypeSerial')
DROP INDEX [dbo].[gp_inoutPtypeSerial].[IX_gp_inoutPtypeSerial]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_inoutPtypeSerial]') AND name = N'IX_gp_inoutPtypeSerial_1')
DROP INDEX [dbo].[gp_inoutPtypeSerial].[IX_gp_inoutPtypeSerial_1]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_inoutPtypeSerial]') AND name = N'IX_gp_inoutPtypeSerial_BTypeID1')
DROP INDEX [dbo].[gp_inoutPtypeSerial].[IX_gp_inoutPtypeSerial_BTypeID1]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_inoutPtypeSerial]') AND name = N'IX_gp_inoutPtypeSerial_BTypeID2')
DROP INDEX [dbo].[gp_inoutPtypeSerial].[IX_gp_inoutPtypeSerial_BTypeID2]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_inoutPtypeSerial]') AND name = N'IX_gp_inoutPtypeSerial_InKTypeID')
DROP INDEX [dbo].[gp_inoutPtypeSerial].[IX_gp_inoutPtypeSerial_InKTypeID]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_inoutPtypeSerial]') AND name = N'IX_gp_inoutPtypeSerial_OutKTypeID')
DROP INDEX [dbo].[gp_inoutPtypeSerial].[IX_gp_inoutPtypeSerial_OutKTypeID]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[gp_inoutPtypeSerial]') AND name = N'IX_gp_inoutPtypeSerial_PTypeID')
DROP INDEX [dbo].[gp_inoutPtypeSerial].[IX_gp_inoutPtypeSerial_PTypeID]
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INOUTPTYPESERIAL') AND name = 'CIX_GP_INOUTPTYPESERIAL_Serial')
--DROP INDEX CIX_GP_INOUTPTYPESERIAL_Serial ON GP_INOUTPTYPESERIAL 
CREATE CLUSTERED INDEX CIX_GP_INOUTPTYPESERIAL_Serial ON GP_INOUTPTYPESERIAL(Serial) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INOUTPTYPESERIAL') AND name = 'NCIX_GP_INOUTPTYPESERIAL_BillNumberId')
--DROP INDEX NCIX_GP_INOUTPTYPESERIAL_BillNumberId ON GP_INOUTPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_INOUTPTYPESERIAL_BillNumberId ON GP_INOUTPTYPESERIAL(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INOUTPTYPESERIAL') AND name = 'NCIX_GP_INOUTPTYPESERIAL_ID')
--DROP INDEX NCIX_GP_INOUTPTYPESERIAL_ID ON GP_INOUTPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_INOUTPTYPESERIAL_ID ON GP_INOUTPTYPESERIAL(ID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GP_INOUTPTYPESERIAL') AND name = 'NCIX_GP_INOUTPTYPESERIAL_DETAILID')
--DROP INDEX NCIX_GP_INOUTPTYPESERIAL_DETAILID ON GP_INOUTPTYPESERIAL 
CREATE NONCLUSTERED INDEX NCIX_GP_INOUTPTYPESERIAL_DETAILID ON GP_INOUTPTYPESERIAL(detailID) 
------------------------------------------创建索引区域结束-----------------------------------------------


--序列号出入库升级
IF NOT  EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[gp_inoutPtypeSerial]') and  name = 'ID')
BEGIN
	SELECT s.* INTO #tmp
	FROM gp_inoutPtypeSerial s
	
	TRUNCATE TABLE [gp_inoutPtypeSerial]
	ALTER TABLE [gp_inoutPtypeSerial]
	    ADD ID [numeric](10, 0) IDENTITY(1,1) NOT NULL
	INSERT INTO gp_inoutPtypeSerial 
	SELECT serial,PtypeID,BillNumberid,InKtypeID,OutKtyeID,IfCheck,BillType,BTypeID1,BTypeID2,InKtypeTime,OutKtypeTime,[user],State 
	FROM 
	(
    SELECT s.serial,s.PtypeID,s.BillNumberid,s.InKtypeID,s.OutKtyeID,s.IfCheck,s.BillType,
		s.BTypeID1,s.BTypeID2,s.InKtypeTime,s.OutKtypeTime,s.[user],s.State,i.ID as id,1 as orderid
    FROM #tmp  s,BillIndex i
	WHERE S.BillNumberid=I.BillNumberId and  s.BillType=i.BillType
	UNION ALL 
    SELECT s.serial,s.PtypeID,s.BillNumberid,s.InKtypeID,s.OutKtyeID,s.IfCheck,s.BillType,
		s.BTypeID1,s.BTypeID2,s.InKtypeTime,s.OutKtypeTime,s.[user],s.State,d.BillId as id, 
		2 orderid
	FROM #tmp  s,SerialAdjustIndex i,SerialAdjustBill d
	WHERE S.BillNumberid=I.BillNumberId and s.BillNumberid=d.BillNumberId  and s.BillType=i.BillType and (d.OldSerial='я'+ s.Serial+'я' or  d.Serial='я'+ s.Serial+'я')
	) I
	ORDER BY I.ID,I.orderid,i.BillNumberid
	
	DROP TABLE #tmp
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE gp_inoutPtypeSerial 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
    
--IF  EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='gp_inoutPtypeSerial' AND a.Name='saleprice' AND  (a.xscale<>10 or xprec<>24)
--    )
--    BEGIN
--	ALTER TABLE gp_inoutPtypeSerial 
--	ALTER COLUMN saleprice NUMERIC(24,10)
--    END
     
GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[gp_inoutPtypeSerial]') and  name = 'Serial' and Length=50)
BEGIN
	 ALTER TABLE gp_inoutPtypeSerial
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO 



/****** 对象:  Table [dbo].[gp_LendPtypeSerial]    脚本日期: 05/05/2010 14:47:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_LendPtypeSerial]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[gp_LendPtypeSerial](
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[InKtypeTime] [datetime] NULL,
		[OutKtypeTime] [datetime] NULL,
		[User] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[State] [int] NOT NULL,
		[Note] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Flag] [bit] NOT NULL,
		[CommissionState] [varchar](1) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BFlag] [bit] NULL CONSTRAINT [DF_gp_LendPtypeSerial_BFlag]  DEFAULT ('0')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='gp_LendPtypeSerial' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE gp_LendPtypeSerial ADD ItemID INT DEFAULT 0 NULL,IsCombined BIT  DEFAULT 0 NULL ,CargoID INT DEFAULT 0,ProduceDate VARCHAR(50) DEFAULT '' NULL,ValidDate VARCHAR(50) DEFAULT '' NULL
	
END
GO

EXEC('
IF EXISTS(
	SELECT PTypeID
	FROM gp_LendPtypeSerial
	WHERE ItemID IS NULL
)
BEGIN
	
	UPDATE gp_LendPtypeSerial
	SET ItemID=0,IsCombined=0,CargoID=0,ProduceDate='''',ValidDate=''''
	WHERE ItemID IS NULL
	
END
')
GO

IF NOT EXISTS(
	SELECT Name FROM SysColumns WHERE id=OBJECT_ID('gp_LendPtypeSerial') AND name='GoodsNumber'
)

BEGIN
	ALTER TABLE gp_LendPtypeSerial
	Add GoodsNumber VARCHAR(100) DEFAULT('')
END
Go

UPDATE dbo.gp_LendPtypeSerial SET State = 34 WHERE State = 32
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'AppraisalState'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='gp_LendPtypeSerial';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[gp_LendPtypeSerial]') and  name = 'Serial' and Length=50)
BEGIN
	 ALTER TABLE gp_LendPtypeSerial
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GuestBack]    脚本日期: 05/05/2010 14:47:44 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GuestBack]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GuestBack](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NOT NULL,
		[discount] [numeric](3, 2) NOT NULL,
		[DiscountPrice] [numeric](18, 4) NULL,
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsno] [int] NULL,
		[total] [numeric](18, 4) NOT NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[ID] [int] NULL,
		[TeamNO1] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBack' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBack 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBack' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBack 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBack' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBack 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBack' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBack 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBack' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBack 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBack' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBack 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBack' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBack 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GuestBackIndex]    脚本日期: 05/05/2010 14:47:45 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GuestBackIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GuestBackIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[atypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalmoney] [numeric](18, 4) NULL,
		[totalinmoney] [numeric](18, 4) NULL,
		[totalqty] [numeric](18, 4) NULL,
		[tax] [numeric](5, 2) NULL,
		[period] [smallint] NULL,
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[RedWord] [bit] NOT NULL,
		[draft] [bit] NOT NULL,
		[OrderId] [numeric](10, 0) NULL,
		[WayBillCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[GoodsNumber] [numeric](2, 0) NULL,
		[PackWay] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[TEL] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--9.6.1运单号从20个字符升级为50个字符
IF EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID('GuestBackIndex',N'U') AND LOWER(Name)='waybillcode' AND [Length]=20)
BEGIN
	ALTER TABLE GuestBackIndex
	ALTER COLUMN WayBillCode VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL
END
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GuestBackIndex]') AND name = N'PK_GuestBackIndex')
ALTER TABLE [dbo].[GuestBackIndex] DROP CONSTRAINT [PK_GuestBackIndex]
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GuestBackIndex]') AND name = N'Idx_GuestBackIndex')
DROP INDEX [dbo].[GuestBackIndex].[Idx_GuestBackIndex]
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GUESTBACKINDEX') AND name = 'CIX_GUESTBACKINDEX_BillNumberId')
--DROP INDEX CIX_GUESTBACKINDEX_BillNumberId ON GUESTBACKINDEX 
CREATE CLUSTERED INDEX CIX_GUESTBACKINDEX_BillNumberId ON GUESTBACKINDEX(BillNumberId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GUESTBACKINDEX') AND name = 'NCIX_GUESTBACKINDEX_BillNumberId')
--DROP INDEX NCIX_GUESTBACKINDEX_BillNumberId ON GUESTBACKINDEX 
CREATE NONCLUSTERED INDEX NCIX_GUESTBACKINDEX_BillNumberId ON GUESTBACKINDEX(BillNumberId) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBackIndex' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBackIndex 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBackIndex' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBackIndex 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBackIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBackIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestBackIndex' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestBackIndex 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GuestGet]    脚本日期: 05/05/2010 14:47:46 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GuestGet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GuestGet](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_GuestGet_SalePrice]  DEFAULT (0),
		[discount] [numeric](3, 2) NULL CONSTRAINT [DF_GuestGet_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_GuestGet_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_GuestGet_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGet_jobnumber]  DEFAULT (''),
		[goodsno] [int] NULL CONSTRAINT [DF_GuestGet_goodsno]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_GuestGet_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_GuestGet_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL,
		[TeamNo1] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = object_id(N'[dbo].[GuestGet]') AND name = N'SaleGuestGetIndex')
DROP INDEX [dbo].[GuestGet].SaleGuestGetIndex
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GUESTGET') AND name = 'CIX_GUESTGET_BillNumberId')
--DROP INDEX CIX_GUESTGET_BillNumberId ON GUESTGET 
CREATE CLUSTERED INDEX CIX_GUESTGET_BillNumberId ON GUESTGET(BillNumberId) 



------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGet' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGet 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGet' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGet 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGet' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGet 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGet' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGet 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGet' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGet 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGet' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGet 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGet' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGet 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGet' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGet 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GuestGetIndex]    脚本日期: 05/05/2010 14:47:46 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GuestGetIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GuestGetIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_GuestGetIndex_BillCode]  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_BillComment]  DEFAULT (''),
		[atypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_atypeid]  DEFAULT ('0'),
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_ptypeid]  DEFAULT ('0'),
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_btypeid]  DEFAULT ('0'),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_etypeid]  DEFAULT ('0'),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_ktypeid]  DEFAULT ('0'),
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_ktypeid2]  DEFAULT ('0'),
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_ifcheck]  DEFAULT ('t'),
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalmoney] [numeric](18, 4) NULL CONSTRAINT [DF_GuestGetIndex_total]  DEFAULT (0),
		[totalinmoney] [numeric](18, 4) NULL CONSTRAINT [DF_GuestGetIndex_totalinmoney]  DEFAULT (0),
		[totalqty] [numeric](18, 4) NULL CONSTRAINT [DF_GuestGetIndex_totalqty]  DEFAULT (0),
		[tax] [numeric](5, 2) NULL CONSTRAINT [DF_GuestGetIndex_tax]  DEFAULT (17),
		[period] [smallint] NULL CONSTRAINT [DF_GuestGetIndex_period]  DEFAULT (0),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_GuestGetIndex_explain]  DEFAULT (''),
		[RedWord] [bit] NOT NULL CONSTRAINT [DF_GuestGetIndex_RedWord]  DEFAULT ('F'),
		[draft] [bit] NOT NULL CONSTRAINT [DF_GuestGetIndex_draft]  DEFAULT (0),
		[OrderId] [numeric](10, 0) NULL CONSTRAINT [DF_GuestGetIndex_OrderId]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GuestGetIndex]') AND name = N'Idx_GuestGetIndex')
DROP INDEX [dbo].[GuestGetIndex].[Idx_GuestGetIndex]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('GUESTGETINDEX') AND name = 'CIX_GUESTGETINDEX_BillNumberId')
--DROP INDEX CIX_GUESTGETINDEX_BillNumberId ON GUESTGETINDEX 
CREATE CLUSTERED INDEX CIX_GUESTGETINDEX_BillNumberId ON GUESTGETINDEX(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGetIndex' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGetIndex 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGetIndex' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGetIndex 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGetIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGetIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestGetIndex' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestGetIndex 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GuestPay]    脚本日期: 05/05/2010 14:47:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GuestPay]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GuestPay](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[ID] [int] NULL,
		[TeamNO1] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestPay' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestPay 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[GuestPayIndex]    脚本日期: 05/05/2010 14:47:48 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[GuestPayIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[GuestPayIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[atypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalmoney] [numeric](18, 4) NULL,
		[totalinmoney] [numeric](18, 4) NULL,
		[totalqty] [numeric](18, 4) NULL,
		[tax] [numeric](5, 2) NULL,
		[period] [smallint] NULL,
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[RedWord] [bit] NOT NULL,
		[draft] [bit] NOT NULL,
		[OrderId] [numeric](10, 0) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestPayIndex' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestPayIndex 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestPayIndex' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestPayIndex 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestPayIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestPayIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='GuestPayIndex' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE GuestPayIndex 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Hotlist]    脚本日期: 05/05/2010 14:47:49 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Hotlist]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Hotlist](
		[HappenDate] [smalldatetime] NULL,
		[Address] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PloyTypeid] [int] NULL,
		[Title] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[New_number] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Operator] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Hotlist' AND a.Name='Comment' and a.xtype=35
)
BEGIN
	ALTER TABLE Hotlist ALTER COLUMN Comment VARCHAR(MAX)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Hotlist]') AND name = N'PK_Hotlist')
ALTER TABLE [dbo].[Hotlist] DROP CONSTRAINT [PK_Hotlist]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('HOTLIST') AND name = 'CIX_HOTLIST_ID')
--DROP INDEX CIX_HOTLIST_ID ON HOTLIST 
CREATE CLUSTERED INDEX CIX_HOTLIST_ID ON HOTLIST(ID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_Message]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
     CREATE TABLE IM_Message
     (
      ID           INT IDENTITY(1,1)                           NOT NULL,
      Title        VARCHAR(100)                                    NULL,
      Content      VARCHAR(MAX)      COLLATE Chinese_PRC_CI_AS NOT NULL,
      BillNumberID VARCHAR(50)       COLLATE Chinese_PRC_CI_AS     NULL,
      BillCode     VARCHAR(MAX)      COLLATE Chinese_PRC_CI_AS     NULL,
      BillType     INT                                             NULL,
      SenderID     VARCHAR(50)       COLLATE Chinese_PRC_CI_AS NOT NULL,
      ReceiverID   VARCHAR(50)       COLLATE Chinese_PRC_CI_AS NOT NULL,
      MessageType  VARCHAR(50)       COLLATE Chinese_PRC_CI_AS NOT NULL,
      CreateDate   VARCHAR(50)       COLLATE Chinese_PRC_CI_AS NOT NULL,
      IsRead       INT                                         NOT NULL,
      SenderIP     VARCHAR(50)       COLLATE Chinese_PRC_CI_AS     NULL,
      ReceiverIP   VARCHAR(50)       COLLATE Chinese_PRC_CI_AS     NULL                               
     ) 
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_Message_NoSocket]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [IM_Message_NoSocket](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Title] [varchar](100) NULL,
	[Content] [varchar](max) NOT NULL,
	[TypeID] [varchar](50) NULL,
	[BillCode] [varchar](max) NULL,
	[BillType] [int] NULL,
	[SenderID] [varchar](50) NOT NULL,
	[SenderName] [varchar](66) NOT NULL,
	[ReceiverID] [varchar](50) NOT NULL,
	[ReceiverName] [VARCHAR](66) NOT NULL, 
	[MessageType] [varchar](50) NOT NULL,
	[CreateDate] [DATETIME] NOT NULL,
	[IsRead] [int] NOT NULL,
	[SenderIP] [varchar](50) NULL,
	[ReceiverIP] [varchar](50) NULL,
	[BillNumberId] INT NOT NULL DEFAULT(0) --单据id
) ON [PRIMARY]

END
GO
--

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IM_Message_NoSocket' AND a.Name='BillNumberId'
)
BEGIN
	ALTER TABLE IM_Message_NoSocket 
		ADD BillNumberId INT NOT NULL DEFAULT(0)
END

GO

--
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IM_Message_NoSocket') AND name = 'NCIX_IM_Message_NoSocket_SenderID')
	DROP INDEX NCIX_IM_Message_NoSocket_SenderID ON IM_Message_NoSocket 
CREATE NONCLUSTERED INDEX NCIX_IM_Message_NoSocket_SenderID ON IM_Message_NoSocket(SenderID) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IM_Message_NoSocket') AND name = 'NCIX_IM_Message_NoSocket_ReceiverID')
	DROP INDEX NCIX_IM_Message_NoSocket_ReceiverID ON IM_Message_NoSocket 
CREATE NONCLUSTERED INDEX NCIX_IM_Message_NoSocket_ReceiverID ON IM_Message_NoSocket(ReceiverID) 

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_Message_NoSocket_Bak]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [IM_Message_NoSocket_Bak](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Title] [varchar](100) NULL,
	[Content] [varchar](max) NOT NULL,
	[TypeID] [varchar](50) NULL,
	[BillCode] [varchar](max) NULL,
	[BillType] [int] NULL,
	[SenderID] [varchar](50) NOT NULL,
	[SenderName] [varchar](66) NOT NULL,
	[ReceiverID] [varchar](50) NOT NULL,
	[ReceiverName] [VARCHAR](66) NOT NULL, 
	[MessageType] [varchar](50) NOT NULL,
	[CreateDate] [DATETIME] NOT NULL,
	[IsRead] [int] NOT NULL,
	[SenderIP] [varchar](50) NULL,
	[ReceiverIP] [varchar](50) NULL,
	[BillNumberId] INT NOT NULL DEFAULT(0) --单据id
) ON [PRIMARY]

END
GO
--

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IM_Message_NoSocket_Bak' AND a.Name='BillNumberId'
)
BEGIN
	ALTER TABLE IM_Message_NoSocket_Bak 
		ADD BillNumberId INT NOT NULL DEFAULT(0)
END

GO

--
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IM_Message_NoSocket_Bak') AND name = 'NCIX_IM_Message_NoSocket_Bak_SenderID')
	DROP INDEX NCIX_IM_Message_NoSocket_Bak_SenderID ON IM_Message_NoSocket_Bak 
CREATE NONCLUSTERED INDEX NCIX_IM_Message_NoSocket_Bak_SenderID ON IM_Message_NoSocket_Bak(SenderID) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IM_Message_NoSocket_Bak') AND name = 'NCIX_IM_Message_NoSocket_Bak_ReceiverID')
	DROP INDEX NCIX_IM_Message_NoSocket_Bak_ReceiverID ON IM_Message_NoSocket_Bak
CREATE NONCLUSTERED INDEX NCIX_IM_Message_NoSocket_Bak_ReceiverID ON IM_Message_NoSocket_Bak(ReceiverID) 

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ImportMoneyBillTemp]    脚本日期: 06/10/2017 15:52:06 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ImportMoneyBillTemp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ImportMoneyBillTemp](
		[billtype] INT NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](24, 10) NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[NTotal] [numeric](24, 10) DEFAULT(0),
		[DTypeId] VARCHAR(50) NOT NULL DEFAULT(''), --部门
		[ETypeId] VARCHAR(50) NOT NULL DEFAULT(''), --经手人
		ShowOrder INT DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[UserId] VARCHAR(50) NOT NULL DEFAULT(''), --操作员id
		[DELETE] INT, --是否删除 
		BrandarTypeId VARCHAR(50) NULL DEFAULT('')--商品品牌编码
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportMoneyBillTemp' AND a.Name='BrandarTypeId'
)
BEGIN
	ALTER TABLE ImportMoneyBillTemp 
		ADD BrandarTypeId VARCHAR(50) DEFAULT('') NULL
END
GO
UPDATE ImportMoneyBillTemp SET BrandarTypeId = '' WHERE BrandarTypeId IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------


                   
------------------------------------------修改字段小数位数区域结束-----------------------------------------------

------------------------------------------表数据更新开始-----------------------------------------------

------------------------------------------表数据更新结束-----------------------------------------------



/*
单据导入临时表
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ImportPriceTemp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ImportPriceTemp](
		[etypeid] [varchar] (50) NOT NULL,
		[typeid] [varchar] (50) NOT NULL,
		[usercode] [varchar] (200),
		[fullname] [varchar] (200),
		[itemid] BIGINT,
		[itemname] [varchar] (100) DEFAULT(''),
		[iscombined] TINYINT DEFAULT(0),
		[munit] [varchar] (100) DEFAULT(''),
		[munitid] INT,
		[munitrate]	 [numeric] (18,4),
		[baojiamode] int,
		[price] [numeric] (18,4),
		[discount] [numeric] (18,4),
		[curmdiscountprice] [numeric] (18,4),
		[xianjiamode] [BIT],
		[comment] [VARCHAR] (200),
		[deleted] [BIT] DEFAULT(0),
		[importtime] DATETIME DEFAULT(GETDATE())
	) ON [PRIMARY]
END
GO

SET ANSI_PADDING OFF
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[ImportPriceTemp]') and name = 'tax' )
BEGIN
	alter table ImportPriceTemp add tax numeric (18,4)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[ImportPriceTemp]') and name = 'curmtaxprice' )
BEGIN
	alter table ImportPriceTemp add curmtaxprice numeric (18,4)
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPriceTemp' AND a.Name='munitrate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ImportPriceTemp 
	ALTER COLUMN munitrate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPriceTemp' AND a.Name='price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ImportPriceTemp 
	ALTER COLUMN price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPriceTemp' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ImportPriceTemp 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPriceTemp' AND a.Name='curmdiscountprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ImportPriceTemp 
	ALTER COLUMN curmdiscountprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPriceTemp' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ImportPriceTemp 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPriceTemp' AND a.Name='curmtaxprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ImportPriceTemp 
	ALTER COLUMN curmtaxprice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
单据导入临时表
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

     

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ImportPtypeTemp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ImportPtypeTemp](
		[etypeid]		[varchar](50) NOT NULL,
		[BillType]		[varchar](4) NOT NULL,
		[PtypeId]		[varchar] (50) NOT NULL,
		[Qty]			[numeric] (18,4) NOT NULL,
		[StrEntryCode]  [varchar](500),
        [StrPrice]      [varchar](66),
        [StrTax]        [varchar](66),
        [StrDiscount]   [varchar](66),
        [munitid]       [varchar](66),
        [munit]         [varchar](66),
        [baseunitid]    [varchar](66),
        [baseunit]      [varchar](66),
        [nunitid]       [varchar](66),
        [nunit]         [varchar](66),
        [munitrate]     [varchar](66),
        [unitrate]      [varchar](66),
        [unitstype]		[varchar](66),
		[deleted]		[BIT],
		[ImportTime]	[DATETIME],
		[stockid]		[varchar](500),
		[stockidin]		[varchar](500),
        [stockname]     [varchar](500),
        [stocknamein]   [varchar](500),
        [cargoid]		[varchar](500),
        [cargoidin]		[varchar](500),
        [cargoName]		[varchar](500),
        [cargoNamein]	[varchar](500),
		[Serial]		[varchar](MAX),
		[isGift]        BIT 	
		) ON [PRIMARY]
END
GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='StrEntryCode'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD StrEntryCode VARCHAR(500)
END

GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='StrEntryCode' and a.length <> 500
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ALTER column StrEntryCode VARCHAR(500)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='StrPrice'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD StrPrice VARCHAR(66)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='StrTax'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD StrTax VARCHAR(66)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='StrDiscount'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD StrDiscount VARCHAR(66)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='munitid'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD munitid VARCHAR(66)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='munit'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD munit VARCHAR(66)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='baseunitid'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD baseunitid VARCHAR(66)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='baseunit'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD baseunit VARCHAR(66)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='nunitid'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD nunitid VARCHAR(66)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='nunit'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD nunit VARCHAR(66)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='munitrate'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD munitrate VARCHAR(66)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='unitrate'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD unitrate VARCHAR(66)
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='unitstype'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD unitstype VARCHAR(66)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='stockid'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD stockid VARCHAR(500)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='stockidin'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD stockidin VARCHAR(500)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='stockname'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD stockname VARCHAR(500)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='stocknamein'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD stocknamein VARCHAR(500)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='cargoid'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD cargoid VARCHAR(500)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='cargoidin'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD cargoidin VARCHAR(500)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='cargoName'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD cargoName VARCHAR(500)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='cargoNamein'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD cargoNamein VARCHAR(500)
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='ProduceDate'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD ProduceDate VARCHAR(100)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='ValidDate'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD ValidDate VARCHAR(100)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='GoodsNumber'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD GoodsNumber VARCHAR(100)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD Comment VARCHAR(255)
END

GO
--是否是服务商品
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='IsService'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD IsService INT
END

GO
--商品参考成本
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='ReferPrice'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD ReferPrice NUMERIC(18,4)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='unitsentrycode'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD unitsentrycode VARCHAR(200)
END
GO 

--是否是赠品商品
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='isGift'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD [isGift] BIT
END

--序列号
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='Serial'
)
BEGIN
	ALTER TABLE ImportPtypeTemp 
		ADD Serial VARCHAR(MAX)
END
GO 

SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ImportPtypeTemp 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ImportPtypeTemp' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ImportPtypeTemp 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
单据导入临时表1
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
 

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ImportPtypeTemp1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ImportPtypeTemp1](
		[etypeid] [varchar](50) NOT NULL, --职员id
		[BillType] [varchar](4) NOT NULL, --类型
		[PtypeId] [varchar] (50) NOT NULL --商品id
	) ON [PRIMARY]
END
GO


SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ImportState]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ImportState](
		[Typeid] int NOT null,
		[State] int NOT NULL,
		[UserId] varchar(100)  
	) 
END
GO
IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[ImportState]') and  name = 'UserId')
BEGIN
	alter table ImportState add UserId varchar(100)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*------------------------------------------
   个人首页数据汇总存储
-------------------------------------------*/


IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IndexChartData]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].IndexChartData
	(
		TypeID VARCHAR(50) NOT NULL,
		FullName  VARCHAR(200),
		total  NUMERIC(24,10),
		Total1 NUMERIC(24,10),
		Total2 NUMERIC(24,10) ,
		flag  INT,
		CountType	INT DEFAULT(0) --统计类型 1 表示w元 0表示元
	) 
END
GO


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[IndexChartData]') AND name = N'IX_IndexChartData_TypeID')
--BEGIN
--	DROP INDEX IX_IndexChartData_TypeID ON IndexChartData
--END
CREATE CLUSTERED INDEX IX_IndexChartData_TypeID ON IndexChartData(TypeID)
------------------------------------------创建索引区域结束-----------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IndexChartData' AND a.Name='CountType'
)
BEGIN
	ALTER TABLE dbo.IndexChartData ADD CountType INT NULL DEFAULT(0)
END
go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Ini_GoodsStocks_Order]    脚本日期: 2017-09-08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ini_GoodsStocks_Order]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Ini_GoodsStocks_Order](	
		[ID]  INT IDENTITY(1,1) PRIMARY KEY,
		[BillNumberID] [numeric](18, 0) NOT NULL,	--订单单据号
		[OrderID] [int] NOT NULL ,					--被单据引用的明细，例如orderbill的orderID=buybill的orderID
		[BillType] [numeric](4, 0) NOT NULL,		--单据类型（11,12,34,140,144,400,402）
		[ReachQty]	[numeric](24,10) NOT NULL DEFAULT (0),	--被引用过账数量
		[ReachTotal] [numeric](24, 10) NULL Default (0),
		[ReachTaxTotal] [numeric](24, 10) NULL Default (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Ini_GoodsStocks_Order') AND name = 'NCIX_Ini_GoodsStocks_Order_WD')
CREATE NONCLUSTERED INDEX NCIX_Ini_GoodsStocks_Order_WD ON Ini_GoodsStocks_Order(BillNumberID,OrderID,BillType) 
------------------------------------------创建索引区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Ini_GOODSSTOCKS_QTY]    脚本日期: 05/05/2010 14:47:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ini_GOODSSTOCKS_QTY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

	CREATE TABLE Ini_GOODSSTOCKS_QTY  (
	  ID				  INT IDENTITY(1,1),
	  PTypeID             VARCHAR(50),
	  KTypeID             VARCHAR(50),
	  CargoID             INT DEFAULT 0,
	  ItemID              INT DEFAULT 0,
	  Iscombined          BIT DEFAULT 0,
	  GoodsNumber         VARCHAR(100),
	  ProduceDate		  VARCHAR(50) CONSTRAINT [DF_Ini_GOODSSTOCKS_QTY_ProduceDate]  DEFAULT (''),
	  ValidDate			  VARCHAR(50) CONSTRAINT [DF_Ini_GOODSSTOCKS_QTY_ValidDate]  DEFAULT (''),
	  Qty                 NUMERIC(22,10),
	  NQty				  NUMERIC(22,10) DEFAULT(0),
	  GoodsCostPrice	  NUMERIC(22,10) DEFAULT(0),
	  LockNumber		NUMERIC(24,10) DEFAULT(0)
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ini_GOODSSTOCKS_QTY' AND a.Name='GoodsCostPrice'
)
BEGIN
	ALTER TABLE Ini_GOODSSTOCKS_QTY ADD GoodsCostPrice NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ini_GOODSSTOCKS_QTY' AND a.Name='LockNumber'
)
BEGIN
	ALTER TABLE Ini_GOODSSTOCKS_QTY ADD LockNumber NUMERIC(24,10) NOT NULL DEFAULT(0) 
	END
GO
UPDATE Ini_GOODSSTOCKS_QTY SET LockNumber=0 WHERE LockNumber IS NULL
-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'GoodsOrder' UNION ALL SELECT 'SerialCount';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='Ini_GOODSSTOCKS_QTY';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INI_GOODSSTOCKS_QTY') AND name = 'CIX_INI_GOODSSTOCKS_QTY_Ptypeid')
--DROP INDEX CIX_INI_GOODSSTOCKS_QTY_Ptypeid ON INI_GOODSSTOCKS_QTY 
CREATE CLUSTERED INDEX CIX_INI_GOODSSTOCKS_QTY_Ptypeid ON INI_GOODSSTOCKS_QTY(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INI_GOODSSTOCKS_QTY') AND name = 'NCIX_INI_GOODSSTOCKS_QTY_Ktypeid')
--DROP INDEX NCIX_INI_GOODSSTOCKS_QTY_Ktypeid ON INI_GOODSSTOCKS_QTY 
CREATE NONCLUSTERED INDEX NCIX_INI_GOODSSTOCKS_QTY_Ktypeid ON INI_GOODSSTOCKS_QTY(Ktypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------









------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ini_GOODSSTOCKS_QTY' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ini_GOODSSTOCKS_QTY 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ini_GOODSSTOCKS_QTY' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ini_GOODSSTOCKS_QTY 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ini_GOODSSTOCKS_QTY' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Ini_GOODSSTOCKS_QTY 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[IniBType_ArApTotal]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[IniBType_ArApTotal](
		[STypeID] [varchar] (50) NOT NULL,
		[BTypeID] [varchar] (50) NOT NULL,
		[DTypeId] VARCHAR(50) NOT NULL,
		[ETypeId] VARCHAR(50) NOT NULL,
		[ARTotal00] numeric(22,10) NOT NULL DEFAULT 0, --应收
		[APTotal00] numeric(22,10) NOT NULL DEFAULT 0, --应付
		[YSTotal00] numeric(22,10) NOT NULL DEFAULT 0, --预收
		[YFTotal00] numeric(22,10) NOT NULL DEFAULT 0, --预付
		[nARTotal00] numeric(22,10) NOT NULL DEFAULT 0,
		[nAPTotal00] numeric(22,10) NOT NULL DEFAULT 0,
		[nYSTotal00] numeric(22,10) NOT NULL DEFAULT 0,
		[nYFTotal00] numeric(22,10) NOT NULL DEFAULT 0,
		[CID]	INT NOT NULL DEFAULT(0),
		[GRIRTotal]		numeric(22,10) NULL DEFAULT 0,
		[NGRIRTotal]	numeric(22,10) NULL DEFAULT 0,
		[GRIRTotal00]	numeric(22,10) NULL DEFAULT 0,
		[NGRIRTotal00]	numeric(22,10) NULL DEFAULT 0,
		[FCTotal]		numeric(22,10) NULL DEFAULT 0,
		[NFCTotal]	numeric(22,10) NULL DEFAULT 0,
		[FCTotal00]	numeric(22,10) NULL DEFAULT 0,
		[NFCTotal00]	numeric(22,10) NULL DEFAULT 0
	) ON [PRIMARY]
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='GRIRTotal'
)
BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ADD [GRIRTotal]		numeric(22,10) NULL DEFAULT 0,
		[NGRIRTotal]	numeric(22,10) NULL DEFAULT 0,
		[GRIRTotal00]	numeric(22,10) NULL DEFAULT 0,
		[NGRIRTotal00]	numeric(22,10) NULL DEFAULT 0,
		[FCTotal]		numeric(22,10) NULL DEFAULT 0,
		[NFCTotal]	numeric(22,10) NULL DEFAULT 0,
		[FCTotal00]	numeric(22,10) NULL DEFAULT 0,
		[NFCTotal00]	numeric(22,10) NULL DEFAULT 0
END
GO

UPDATE dbo.IniBType_ArApTotal 
SET			GRIRTotal=ISNULL(GRIRTotal,0),
			NGRIRTotal=ISNULL(NGRIRTotal,0),
			GRIRTotal00=ISNULL(GRIRTotal00,0),
			NGRIRTotal00=ISNULL(NGRIRTotal00,0),
			FCTotal=ISNULL(FCTotal,0),
			NFCTotal=ISNULL(NFCTotal,0),
			FCTotal00=ISNULL(FCTotal00,0),
			NFCTotal00=ISNULL(NFCTotal00,0)
GO
-- 创建索引
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IniBTYPE_ARAPTOTAL') AND name = 'CIX_IniBTYPE_ARAPTOTAL')
	--DROP INDEX CIX_IniBTYPE_ARAPTOTAL ON IniBTYPE_ARAPTOTAL 
CREATE CLUSTERED INDEX CIX_IniBTYPE_ARAPTOTAL ON IniBTYPE_ARAPTOTAL(STypeID,BtypeId,DtypeId,ETypeId);
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='ARTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN ARTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='APTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN APTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='YSTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN YSTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='YFTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN YFTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='nARTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN nARTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='nAPTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN nAPTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='nYSTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN nYSTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='nYFTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN nYFTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='GRIRTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN GRIRTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='NGRIRTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN NGRIRTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='GRIRTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN GRIRTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='NGRIRTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN NGRIRTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='FCTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN FCTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='NFCTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN NFCTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='FCTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN FCTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniBType_ArApTotal' AND a.Name='NFCTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniBType_ArApTotal 
	ALTER COLUMN NFCTotal00 NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[IniCommissionStock]    脚本日期: 05/05/2010 14:47:50 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IniCommissionStock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[IniCommissionStock](
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_IniCommissionStock_Ptypeid]  DEFAULT ('0'),
		[Btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_IniCommissionStock_Btypeid]  DEFAULT ('0'),
		[Type] [int] NOT NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_IniCommissionStock_Qty]  DEFAULT (0),
		[CostTotal] [numeric](18, 4) NULL CONSTRAINT [DF_IniCommissionStock_CostTotal]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_IniCommissionStock_Total]  DEFAULT (0),
		[Tax] [numeric](18, 4) NULL CONSTRAINT [DF_IniCommissionStock_Tax]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_IniCommissionStock_TaxTotal]  DEFAULT (0),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniCommissionStock_explain]  DEFAULT ('0'),
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[DealType] TINYINT NULL DEFAULT(0),
		[SerialType]	TINYINT NULL DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE IniCommissionStock ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE IniCommissionStock SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock' AND a.Name='DealType'
)
BEGIN
	ALTER TABLE IniCommissionStock ADD DealType TINYINT NULL DEFAULT(0)

	
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock' AND a.Name='SerialType'
)
BEGIN
	ALTER TABLE IniCommissionStock ADD SerialType TINYINT NULL DEFAULT(0)

	
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t 
SELECT 'CargoID' UNION ALL SELECT 'ItemID' UNION ALL SELECT 'NQty' UNION ALL SELECT 'GoodsNumber';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='IniCommissionStock';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniCommissionStock 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniCommissionStock 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniCommissionStock 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniCommissionStock 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniCommissionStock 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[IniCommissionStock_Qty]    脚本日期: 05/05/2010 14:47:07 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IniCommissionStock_Qty]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[IniCommissionStock_Qty](
		[Ptypeid]					VARCHAR(50)		DEFAULT (''),
		[Btypeid]					VARCHAR(50)		DEFAULT (''),
		[Stypeid]					VARCHAR(50)		DEFAULT (''),
		[Type]						INT				DEFAULT(0),
		ItemID						INT				DEFAULT(0),
		Iscombined					BIT				DEFAULT(0),
		GoodsNumber					VARCHAR(100)	DEFAULT(''),
		ProduceDate					VARCHAR(50)		DEFAULT (''),
		ValidDate					VARCHAR(50)		DEFAULT (''),
		Qty							NUMERIC(22,10)	DEFAULT(0),
		NQty						NUMERIC(22,10)	DEFAULT(0),
		[DealType]					TINYINT NULL DEFAULT(0),
		KTypeID						VARCHAR(50) NULL DEFAULT(''),
		CargoID						INT NULL DEFAULT(0),
		SerialType					TINYINT NULL DEFAULT(0),
		GoodsCostPrice				NUMERIC(22,10) NULL DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock_Qty' AND a.Name='GoodsCostPrice'
)
BEGIN
	ALTER TABLE IniCommissionStock_Qty ADD GoodsCostPrice NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock_Qty' AND a.Name='DealType'
)
BEGIN
	ALTER TABLE IniCommissionStock_Qty ADD DealType TINYINT NULL DEFAULT(0)

	
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock_Qty' AND a.Name='KTypeID'
)
BEGIN
	ALTER TABLE IniCommissionStock_Qty ADD KTypeID VARCHAR(50) NULL DEFAULT(''),CargoID INT NULL DEFAULT(0)

	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock_Qty' AND a.Name='SerialType'
)
BEGIN
	ALTER TABLE IniCommissionStock_Qty ADD SerialType TINYINT NULL DEFAULT(0)

	
END
GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock_Qty' AND a.Name='GoodsCostPrice'
)
BEGIN
	ALTER TABLE IniCommissionStock_Qty ADD GoodsCostPrice NUMERIC(22,10) NULL DEFAULT(0)
END



-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'GoodsOrder' UNION ALL SELECT 'BTypeID2'

;
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='IniCommissionStock_Qty';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO


IF EXISTS(
	SELECT  Ptypeid
	FROM IniCommissionStock_Qty
)
BEGIN
	BEGIN TRAN
		SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,SUM(Qty) AS Qty,SUM(NQty) AS NQty,GoodsCostPrice,DealType,KTypeID,SerialType,CargoID
		INTO #IniCommissionStockQtyUpgrade
		FROM IniCommissionStock_Qty
		GROUP BY Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,DealType,KTypeID,SerialType,CargoID
	
		TRUNCATE TABLE IniCommissionStock_Qty
		
		INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,DealType,KTypeID,SerialType,CargoID)
		SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,DealType,KTypeID,SerialType,CargoID
		FROM #IniCommissionStockQtyUpgrade
		
		DROP TABLE #IniCommissionStockQtyUpgrade

	IF @@ERROR=0
	BEGIN		
		COMMIT TRAN	
	END
	ELSE
	BEGIN
		ROLLBACK TRAN
	END
END


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INICOMMISSIONSTOCK_QTY') AND name = 'CIX_INICOMMISSIONSTOCK_QTY_Ptypeid')
--DROP INDEX CIX_INICOMMISSIONSTOCK_QTY_Ptypeid ON INICOMMISSIONSTOCK_QTY 
CREATE CLUSTERED INDEX CIX_INICOMMISSIONSTOCK_QTY_Ptypeid ON INICOMMISSIONSTOCK_QTY(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INICOMMISSIONSTOCK_QTY') AND name = 'NCIX_INICOMMISSIONSTOCK_QTY_Stypeid')
--DROP INDEX NCIX_INICOMMISSIONSTOCK_QTY_Stypeid ON INICOMMISSIONSTOCK_QTY 
CREATE NONCLUSTERED INDEX NCIX_INICOMMISSIONSTOCK_QTY_Stypeid ON INICOMMISSIONSTOCK_QTY(Stypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock_Qty' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniCommissionStock_Qty 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock_Qty' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniCommissionStock_Qty 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniCommissionStock_Qty' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniCommissionStock_Qty 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IniFactStocks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[IniFactStocks]
	(
		[PtypeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric] (24, 10) NULL CONSTRAINT [DF_IniFactStocks_Qty] DEFAULT ((0))
	)  

END
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IniFactStocks') AND name = 'CIX_IniFactStocks_PtypeId')
	CREATE CLUSTERED INDEX [CIX_IniFactStocks_PtypeId] ON [dbo].[IniFactStocks] ([PtypeId]) ON [PRIMARY]
	
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IniFactStocks') AND name = 'CIX_IniFactStocks_PtypeId')
	CREATE NONCLUSTERED INDEX [CIX_IniFactStocks_PtypeId] ON [dbo].[IniFactStocks] ([KtypeId], [Qty]) ON [PRIMARY]

GO



DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'JobNumber' UNION ALL SELECT 'OutFactoryDate' UNION ALL SELECT 'GoodsOrder' UNION ALL SELECT 'GoodsNumber'
UNION ALL SELECT 'ProduceDate' UNION ALL SELECT 'ValidDate'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='IniFactStocks';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
 




GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IniFactStocks_Qty]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[IniFactStocks_Qty]
	(
	[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
	[KTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
	[CargoID] [int] NULL CONSTRAINT [DF_IniFactStocks_Qty_CargoID] DEFAULT 0,
	[ItemID] [int] NULL CONSTRAINT [DF_IniFactStocks_Qty_ItemID] DEFAULT 0,
	[Iscombined] [bit] NULL CONSTRAINT [DF_IniFactStocks_Qty_Iscombined] DEFAULT 0,
	[GoodsNumber] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniFactStocks_Qty_GoodsNumber] DEFAULT (''),
	[ProduceDate] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniFactStocks_Qty_ProduceDate] DEFAULT (''),
	[ValidDate] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniFactStocks_Qty_ValidDate] DEFAULT (''),
	[Qty] [numeric] (24, 10) NULL,
	[NQty] [numeric] (24, 10) NULL  DEFAULT ((0)),
	) 
END
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IniFactStocks_Qty') AND name = 'CIX_IniFactStocks_Qty_Ptypeid_Ktypeid')
	CREATE CLUSTERED INDEX [CIX_IniFactStocks_Qty_Ptypeid_Ktypeid] ON [dbo].[IniFactStocks_Qty] ([PTypeID], [KTypeID]) ON [PRIMARY]
GO

IF  NOT EXISTS (
SELECT * FROM sys.default_constraints WHERE object_id = OBJECT_ID(N'[dbo].[DF_IniFactStocks_Qty_CargoID]') AND parent_object_id = OBJECT_ID(N'[dbo].[IniFactStocks_Qty]')
)
BEGIN
	ALTER TABLE IniFactStocks_Qty ADD CONSTRAINT [DF_IniFactStocks_Qty_CargoID] DEFAULT 0 FOR CargoID
	ALTER TABLE IniFactStocks_Qty ADD CONSTRAINT [DF_IniFactStocks_Qty_ItemID] DEFAULT 0 FOR ItemID
	ALTER TABLE IniFactStocks_Qty ADD CONSTRAINT [DF_IniFactStocks_Qty_Iscombined] DEFAULT 0 FOR Iscombined
	ALTER TABLE IniFactStocks_Qty ADD CONSTRAINT [DF_IniFactStocks_Qty_GoodsNumber] DEFAULT ('') FOR GoodsNumber
END
GO





/****** 对象:  Table [dbo].[IniGoodsLend]    脚本日期: 05/05/2010 14:47:51 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IniGoodsLend]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[IniGoodsLend](
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniGoodsLend_JobNumber]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL CONSTRAINT [DF_IniGoodsLend_OutFactoryDate]  DEFAULT (getdate()),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_IniGoodsLend_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_IniGoodsLend_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_IniGoodsLend_Total]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_IniGoodsLend_GoodsOrder]  DEFAULT (0),
		[GoodsNumber] varchar(100)  NULL  DEFAULT (''),
		ItemID BIGINT DEFAULT(0),
		Iscombined	BIT DEFAULT(0),
		Nqty NUMERIC(22,10) DEFAULT(0),	
		ProduceDate					VARCHAR(100)		DEFAULT (''),
		ValidDate					VARCHAR(100)		DEFAULT (''),
		LendQty						NUMERIC(22,10)	DEFAULT(0),
		NLendQty					NUMERIC(22,10)	DEFAULT(0),
		BorrowQty					NUMERIC(22,10)	DEFAULT(0),
		NBorrowQty					NUMERIC(22,10)	DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 读写分离
DECLARE @sql NVARCHAR(max)='';
IF EXISTS(
	SELECT * FROM sys.objects a WHERE type='pk' AND a.parent_object_id=object_id('IniGoodsLend') 
)
begin
	select @sql=' alter table IniGoodsLend drop constraint ['+a.name+'] ' FROM sys.objects a WHERE type='pk' AND  a.parent_object_id=object_id('IniGoodsLend')
	EXEC(@sql);
END
go
--


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='GoodsNumber'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD GoodsNumber varchar(100)  NULL  DEFAULT ('')
END

GO




IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD ItemID bigint  null
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='ItemID'
	)
	begin
		select @sql=' alter table IniGoodsLend drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='ItemID'
		EXEC(@sql);
	END
	ALTER TABLE IniGoodsLend ALTER COLUMN ItemID int NULL;
	ALTER TABLE IniGoodsLend add CONSTRAINT DF_IniGoodsLend_ItemID DEFAULT(0) FOR ItemID
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='Iscombined'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD Iscombined	BIT DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='Nqty'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD Nqty NUMERIC(22,10) NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='Nqty'
	)
	begin
		select @sql=' alter table IniGoodsLend drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='Nqty'
		EXEC(@sql);
	END
	ALTER TABLE IniGoodsLend ALTER COLUMN Nqty int NULL;
	ALTER TABLE IniGoodsLend add CONSTRAINT DF_IniGoodsLend_Nqty DEFAULT(0) FOR Nqty
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='ProduceDate'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD ProduceDate varchar(100)  NULL  DEFAULT ('')
END
ELSE
BEGIN
	ALTER TABLE IniGoodsLend ALTER COLUMN ProduceDate varchar(100)  NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='ValidDate'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD ValidDate varchar(100)  NULL  DEFAULT ('')
END
ELSE
BEGIN
	ALTER TABLE IniGoodsLend ALTER COLUMN ValidDate varchar(100)  NULL
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='LendQty'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD LendQty NUMERIC(22,10) NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='LendQty'
	)
	begin
		select @sql=' alter table IniGoodsLend drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='LendQty'
		EXEC(@sql);
	END
	ALTER TABLE IniGoodsLend ALTER COLUMN LendQty NUMERIC(22,10) NULL;
	ALTER TABLE IniGoodsLend add CONSTRAINT DF_IniGoodsLend_LendQty DEFAULT(0) FOR LendQty
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='NLendQty'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD NLendQty NUMERIC(22,10) NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='NLendQty'
	)
	begin
		select @sql=' alter table IniGoodsLend drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='NLendQty'
		EXEC(@sql);
	END
	ALTER TABLE IniGoodsLend ALTER COLUMN NLendQty NUMERIC(22,10) NULL;
	ALTER TABLE IniGoodsLend add CONSTRAINT DF_IniGoodsLend_NLendQty DEFAULT(0) FOR NLendQty
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='BorrowQty'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD BorrowQty NUMERIC(22,10) NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='BorrowQty'
	)
	begin
		select @sql=' alter table IniGoodsLend drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='BorrowQty'
		EXEC(@sql);
	END
	ALTER TABLE IniGoodsLend ALTER COLUMN BorrowQty NUMERIC(22,10) NULL;
	ALTER TABLE IniGoodsLend add CONSTRAINT DF_IniGoodsLend_BorrowQty DEFAULT(0) FOR BorrowQty
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='NBorrowQty'
)
BEGIN
	ALTER TABLE IniGoodsLend ADD NBorrowQty NUMERIC(22,10) NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='NBorrowQty'
	)
	begin
		select @sql=' alter table IniGoodsLend drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('IniGoodsLend') AND b.name='NBorrowQty'
		EXEC(@sql);
	END
	ALTER TABLE IniGoodsLend ALTER COLUMN NBorrowQty NUMERIC(22,10) NULL;
	ALTER TABLE IniGoodsLend add CONSTRAINT DF_IniGoodsLend_NBorrowQty DEFAULT(0) FOR NBorrowQty
END

GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t 
SELECT 'CargoID'
;
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='IniGoodsLend';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[IniGoodsLend]') AND name = N'IniGoodsLendindex')
DROP INDEX [dbo].[IniGoodsLend].[IniGoodsLendindex]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INIGOODSLEND') AND name = 'CIX_INIGOODSLEND_Ktypeid')
--DROP INDEX CIX_INIGOODSLEND_Ktypeid ON INIGOODSLEND 
CREATE CLUSTERED INDEX CIX_INIGOODSLEND_Ktypeid ON INIGOODSLEND(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INIGOODSLEND') AND name = 'NCIX_INIGOODSLEND_Ptypeid')
--DROP INDEX NCIX_INIGOODSLEND_Ptypeid ON INIGOODSLEND 
CREATE NONCLUSTERED INDEX NCIX_INIGOODSLEND_Ptypeid ON INIGOODSLEND(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsLend 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsLend 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsLend 
	ALTER COLUMN Total NUMERIC(24,10)
    END
  
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='LendQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsLend 
	ALTER COLUMN LendQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='NLendQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsLend 
	ALTER COLUMN NLendQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='BorrowQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsLend 
	ALTER COLUMN BorrowQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsLend' AND a.Name='NBorrowQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsLend 
	ALTER COLUMN NBorrowQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[IniGoodsStocks]    脚本日期: 05/05/2010 14:47:52 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IniGoodsStocks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[IniGoodsStocks](
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniGoodsStocks_JobNumber]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL CONSTRAINT [DF_IniGoodsStocks_OutFactoryDate]  DEFAULT (getdate()),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_IniGoodsStocks_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_IniGoodsStocks_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_IniGoodsStocks_Total]  DEFAULT (0),
		[GoodsOrder] [numeric](4, 0) NULL CONSTRAINT [DF_IniGoodsStocks_GoodsOrder]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniGoodsStocks_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniGoodsStocks_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniGoodsStocks_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_IniGoodsStocks_GoodsBTypeID]  DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsStocks' AND a.Name='GoodsOrder'
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('IniGoodsStocks') AND name='GoodsOrder')
	IF @dfname IS NOT NULL
		EXEC ('alter table IniGoodsStocks drop constraint '+@dfname);
	ALTER TABLE IniGoodsStocks 
		ALTER COLUMN GoodsOrder INT 
END
GO
-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t 
SELECT 'CargoID' UNION ALL SELECT 'ItemID' UNION ALL SELECT 'NQty' UNION ALL SELECT 'SerialCount';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='IniGoodsStocks';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--老版本用的是gp_inistocks，因此也需要drop
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[IniGoodsStocks]') AND name = N'gp_inistocks')
	DROP INDEX [dbo].[IniGoodsStocks].[gp_inistocks]

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[IniGoodsStocks]') AND name = N'CIX_PTYPEID')
	DROP INDEX [dbo].[IniGoodsStocks].CIX_PTYPEID

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[IniGoodsStocks]') AND name = N'NCIX_KTYPEID')
	DROP INDEX [dbo].[IniGoodsStocks].NCIX_KTYPEID
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INIGOODSSTOCKS') AND name = 'CIX_INIGOODSSTOCKS_PtypeId')
--DROP INDEX CIX_INIGOODSSTOCKS_PtypeId ON INIGOODSSTOCKS 
CREATE CLUSTERED INDEX CIX_INIGOODSSTOCKS_PtypeId ON INIGOODSSTOCKS(PtypeId) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INIGOODSSTOCKS') AND name = 'NCIX_INIGOODSSTOCKS_KtypeId_Qty_Total')
DROP INDEX NCIX_INIGOODSSTOCKS_KtypeId_Qty_Total ON INIGOODSSTOCKS 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsStocks' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsStocks 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                                              
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsStocks' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsStocks 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                  
CREATE NONCLUSTERED INDEX NCIX_INIGOODSSTOCKS_KtypeId_Qty_Total ON INIGOODSSTOCKS(KtypeId,Qty,Total) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
             
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='IniGoodsStocks' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE IniGoodsStocks 
	ALTER COLUMN Price NUMERIC(24,10)
    END
           
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[RequestIndex]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[InitSaleSeralIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[InitSaleSeralIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT (''),
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[explain] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT (''),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[IsIni]	BIT NULL DEFAULT(0)
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------

/****** Object:  Table [dbo].[InitSaleSeralIndex]    Script Date: 04/08/2015 14:45:22 ******/
/*
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InitSaleSeralIndex]') AND type in (N'U'))
DROP TABLE [dbo].[InitSaleSeralIndex]
GO
*/

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[gp_initPtypeSerial]    脚本日期: 05/05/2010 14:47:41 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[initSaleSerialbill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[initSaleSerialbill](
		ID   [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		BillNumerID INT,
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_initSaleSerialbill_BTypeID1]  DEFAULT (''),
		[BtypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_initSaleSerialbill_BtypeID2]  DEFAULT (''),
		[InKtypeTime] [datetime] NULL,
		[OutKTypeTime] [datetime] NULL,
		[State] [int] NULL CONSTRAINT [DF_initSaleSerialbill_State]  DEFAULT (1)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------



/****** Object:  Table [dbo].[initSaleSerialbill]    Script Date: 04/08/2015 14:44:29 ******/
/*
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[initSaleSerialbill]') AND type in (N'U'))
DROP TABLE [dbo].[initSaleSerialbill]
GO
*/

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[InOutstocktable]    脚本日期: 05/05/2010 14:47:53 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[InOutstocktable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[InOutstocktable](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillDate] [datetime] NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_AtypeId]  DEFAULT (0),
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_PtypeId]  DEFAULT (0),
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_BtypeId]  DEFAULT (0),
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_EtypeId]  DEFAULT (0),
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_KtypeId]  DEFAULT (0),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_Total]  DEFAULT (0),
		[CostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_CostPrice]  DEFAULT (0),
		[CostTotal] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_CostTotal]  DEFAULT (0),
		[JobNumber] [char](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_JobNumber]  DEFAULT (0),
		[GoodsNo] [int] NULL CONSTRAINT [DF_InOutstocktable_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[Audited] [bit] NOT NULL CONSTRAINT [DF_InOutstocktable_Audited]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_GoodsCostPrice]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_InOutstocktable_HandZeroCost_1]  DEFAULT (0),
		[ID] [int] NULL CONSTRAINT [DF_InOutstocktable_ID]  DEFAULT ((-1)),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_InOutstocktable_tax]  DEFAULT (0),
		[Discount] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_discount]  DEFAULT (1),
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_saleprice]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_saletotal]  DEFAULT (0),
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_taxprice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_InOutstocktable_taxtotal]  DEFAULT (0),
		[DTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_DTypeID]  DEFAULT (''),
		[STypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_InOutstocktable_STypeID]  DEFAULT (''),
		[PostTime] [DATETIME] NULL CONSTRAINT [DF_InOutstocktable_PostTime]  DEFAULT GETDATE(),
		[SortID]	[BIGINT] IDENTITY(1,1) NOT NULL,
		[ShareFee] [numeric](18,4) NULL CONSTRAINT [DF_InOutstocktable_ShareFee]  DEFAULT (0),
		[CargoID] [int] NULL CONSTRAINT [DF_InOutstocktable_CargoID]  DEFAULT (0),
		[NPrice] [numeric](18, 4) NULL DEFAULT (0),
		[NTotal] [numeric](18, 4) NULL DEFAULT (0),
		[NSalePrice] [numeric](18, 4) NULL DEFAULT (0),
		[NSaleTotal] [numeric](18, 4) NULL DEFAULT (0),
		[NTaxPrice] [numeric](18, 4) NULL DEFAULT (0),
		[NTaxTotal] [numeric](18, 4) NULL DEFAULT (0),
		[ItemID] [INT] NOT NULL DEFAULT(0),
		[IsCombined] [Bit] NOT NULL DEFAULT(0),
		[NQty]   [numeric](22,10)     NULL Default(0),
		[UnitRate]  [numeric](22,10)     NULL Default(0),
		[MUNITID] [int] NULL DEFAULT(0),
		[IsGift] INT NOT NULL DEFAULT(0), --是否是赠品
		[IsService] INT NOT NULL DEFAULT(0), -- 0 普通商品 1 服务商品
		[MUnitRate]	NUMERIC(22,10) NULL
	) ON [PRIMARY]


END
GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='DTypeID'
)
BEGIN
	ALTER TABLE InOutStockTable ADD DTypeID VARCHAR(50) NULL CONSTRAINT [DF_InOutstocktable_DTypeID]  DEFAULT ('')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE InOutStockTable ADD STypeID VARCHAR(50) NULL CONSTRAINT [DF_InOutstocktable_STypeID]  DEFAULT ('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE InOutstocktable SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='PostTime'
)
BEGIN
	ALTER TABLE InOutStockTable ADD PostTime DATETIME NULL CONSTRAINT [DF_InOutstocktable_PostTime]  DEFAULT GETDATE()
	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='SortID'
)
BEGIN
	ALTER TABLE InOutStockTable ADD SortID [BIGINT] IDENTITY(1,1) NOT NULL
	
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='ShareFee'
)
BEGIN
	ALTER TABLE InOutStockTable ADD ShareFee [numeric](18,4) NULL CONSTRAINT [DF_InOutstocktable_ShareFee]  DEFAULT (0)
	
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='CargoID'
)
BEGIN
	ALTER TABLE InOutStockTable ADD CargoID INT NULL CONSTRAINT [DF_InOutstocktable_CargoID]  DEFAULT (0)
	
	EXEC('UPDATE InOutStockTable SET CargoID=0 WHERE CargoID IS NULL')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='NPrice'
)
BEGIN
	ALTER TABLE InOutStockTable ADD NPrice  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE InOutStockTable SET NPrice=Price WHERE NPrice IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='NTOTAL'
)
BEGIN
	ALTER TABLE InOutStockTable ADD NTOTAL  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE InOutStockTable SET NTOTAL=TOTAL WHERE NTOTAL IS NULL')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='NSALEPRICE'
)
BEGIN
	ALTER TABLE InOutStockTable ADD NSALEPRICE  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE InOutStockTable SET NSALEPRICE=SALEPRICE WHERE NSALEPRICE IS NULL')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='NSALETOTAL'
)
BEGIN
	ALTER TABLE InOutStockTable ADD NSALETOTAL  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE InOutStockTable SET NSALETOTAL=SALETOTAL WHERE NSALETOTAL IS NULL')
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='NTAXPRICE'
)
BEGIN
	ALTER TABLE InOutStockTable ADD NTAXPRICE  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE InOutStockTable SET NTAXPRICE=TAXPRICE WHERE NTAXPRICE IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='NTAXTOTAL'
)
BEGIN
	ALTER TABLE InOutStockTable ADD NTAXTOTAL  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE InOutStockTable SET NTAXTOTAL=TAXTOTAL WHERE NTAXTOTAL IS NULL')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE InOutStockTable ADD ItemID int NOT NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('InOutStockTable') AND b.name='ItemID'
	)
	begin
		select @sql=' alter table InOutStockTable drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('InOutStockTable') AND b.name='ItemID'
		EXEC(@sql);
	END
	ALTER TABLE InOutStockTable ALTER COLUMN ItemID int NOT NULL;
	ALTER TABLE InOutStockTable add CONSTRAINT DF_InOutStockTable_Item DEFAULT(0) FOR itemId
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='IsCombined'
)
BEGIN
	ALTER TABLE InOutStockTable ADD IsCombined BIT NOT NULL DEFAULT(0)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='NQty'
)
BEGIN
	ALTER TABLE InOutStockTable ADD NQty NUMERIC(22,10)  DEFAULT(0)
	
	
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='UnitRate'
)
BEGIN
	ALTER TABLE InOutStockTable ADD UnitRate NUMERIC(22,10)  DEFAULT(0)
	
	EXEC('UPDATE InOutStockTable SET NQty=Qty,UnitRate=1 WHERE NQty=0')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='MUNITID'
)
BEGIN
	ALTER TABLE InOutStockTable ADD MUNITID INT  DEFAULT(0)
	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutStockTable' AND a.Name='IsGift'
)
BEGIN
	ALTER TABLE InOutStockTable ADD IsGift INT NOT NULL DEFAULT(0)
	
	EXEC('
	UPDATE InOutstocktable
	SET IsGift=1
	WHERE BillType IN (139,126)
	')
END

GO

IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[InOutStockTable]') AND name = 'IsService')
BEGIN
	ALTER TABLE InOutStockTable ADD [IsService] INT NOT NULL DEFAULT(0) -- 0 普通商品 1 服务商品
END

IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[InOutStockTable]') AND name = 'Comment')
BEGIN
	ALTER TABLE InOutStockTable ADD [Comment] VARCHAR(255) DEFAULT ''  
	EXEC('UPDATE InOutStockTable SET Comment='''' WHERE Comment is null')
END


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'InOutStockTable',N'U') AND Name='MUnitRate')
BEGIN
	ALTER TABLE InOutStockTable
	ADD MUnitRate NUMERIC(22,10) NULL
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'NCIX_STYPEID')
	DROP INDEX [dbo].[InOutstocktable].NCIX_STYPEID  
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'NCIX_DTYPEID')
	DROP INDEX [dbo].[InOutstocktable].NCIX_DTYPEID 
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'NCIX_PTYPEID')
	DROP INDEX [dbo].[InOutstocktable].NCIX_PTYPEID 
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'NCIX_AUDITED')
	DROP INDEX [dbo].[InOutstocktable].NCIX_AUDITED  

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'IX_InOutStockTable_ATypeID')
DROP INDEX [IX_InOutStockTable_ATypeID] ON [dbo].[InOutStockTable] 


IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'IX_InOutStockTable_BillDate')
DROP INDEX [IX_InOutStockTable_BillDate] ON [dbo].[InOutStockTable] 

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'IX_InOutStockTable_BillNumberId')
DROP INDEX [IX_InOutStockTable_BillNumberId] ON [dbo].[InOutStockTable] 
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'IX_InOutStockTable_BTypeId')
DROP INDEX [IX_InOutStockTable_BTypeId] ON [dbo].[InOutStockTable] 


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'IX_InOutStockTable_ETypeID')
DROP INDEX [IX_InOutStockTable_ETypeId] ON [dbo].[InOutStockTable] 
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'IX_InOutStockTable_KTypeID')
DROP INDEX [IX_InOutStockTable_KTypeId] ON [dbo].[InOutStockTable] 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[InOutStockTable]') AND name = N'IX_InOutStockTable_PTypeID')
DROP INDEX [IX_InOutStockTable_PTypeId] ON [dbo].[InOutStockTable] 

GO
-------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'CIX_INOUTSTOCKTABLE_BillDate')
--DROP INDEX CIX_INOUTSTOCKTABLE_BillDate ON INOUTSTOCKTABLE 
CREATE CLUSTERED INDEX CIX_INOUTSTOCKTABLE_BillDate ON INOUTSTOCKTABLE(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_BillNumberID')
--DROP INDEX NCIX_INOUTSTOCKTABLE_BillNumberID ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_BillNumberID ON INOUTSTOCKTABLE(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_Ktypeid')
--DROP INDEX NCIX_INOUTSTOCKTABLE_Ktypeid ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_Ktypeid ON INOUTSTOCKTABLE(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_Atypeid')
--DROP INDEX NCIX_INOUTSTOCKTABLE_Atypeid ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_Atypeid ON INOUTSTOCKTABLE(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_Btypeid')
--DROP INDEX NCIX_INOUTSTOCKTABLE_Btypeid ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_Btypeid ON INOUTSTOCKTABLE(Btypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_Etypeid')
--DROP INDEX NCIX_INOUTSTOCKTABLE_Etypeid ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_Etypeid ON INOUTSTOCKTABLE(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_PostTime')
--DROP INDEX NCIX_INOUTSTOCKTABLE_PostTime ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_PostTime ON INOUTSTOCKTABLE(PostTime) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_SortID')
--DROP INDEX NCIX_INOUTSTOCKTABLE_SortID ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_SortID ON INOUTSTOCKTABLE(SortID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_Ptypeid_Ktypeid')
--DROP INDEX NCIX_INOUTSTOCKTABLE_Ptypeid_Ktypeid ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_Ptypeid_Ktypeid ON INOUTSTOCKTABLE(Ptypeid, Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_Billtype')
--DROP INDEX NCIX_INOUTSTOCKTABLE_Billtype ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_Billtype ON INOUTSTOCKTABLE(Billtype) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('INOUTSTOCKTABLE') AND name = 'NCIX_INOUTSTOCKTABLE_PTYPEID_BILLNUMBERID')
--DROP INDEX NCIX_INOUTSTOCKTABLE_PTYPEID_BILLNUMBERID ON INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_INOUTSTOCKTABLE_PTYPEID_BILLNUMBERID ON INOUTSTOCKTABLE(PTYPEID,BILLNUMBERID) 

GO
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NSALEPRICE' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NSALEPRICE NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NSALETOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NSALETOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NTAXPRICE' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NTAXPRICE NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='NTAXTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InOutstocktable 
	ALTER COLUMN NTAXTOTAL NUMERIC(24,10)
    END
GO   
    
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InOutstocktable' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE InOutstocktable 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
                                  
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[IntercourseSetting]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[IntercourseSetting](
		[ID]			INT  PRIMARY KEY IDENTITY(1,1) ,			--自增id
		[BtypeId]		VARCHAR(50),								--往来单位id
		[StypeId]		VARCHAR(50),								--分支机构id
		[LimitDay]		INT											--报警时间间隔
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--商品档案--存货类型关联表-
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PType_InventoryType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PType_InventoryType
(
	ID				NUMERIC(18,0) IDENTITY(1,1),	
	Ptypeid			VARCHAR(50)	  NOT NULL,		    --商品的ID
	Stypeid			VARCHAR(50)	  NOT NULL,			--分支机构ID 
	InventoryTypeid			VARCHAR(50)   NULL DEFAULT(''),	--存货类型ID			 
 
	 
)
END

GO

------------------------------------------表修改区域-开始-------------------------------------------------
IF NOT EXISTS (select name from syscolumns where id = object_id(N'[dbo].[PType_InventoryType]') and name = 'Ptypeid' )
BEGIN
	ALTER TABLE dbo.PType_InventoryType ADD
		Ptypeid VARCHAR(50) NOT NULL
END
GO

------------------------------------------表修改区域-结束-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[InvoiceBill]    脚本日期: 05/05/2010 14:47:54 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[InvoiceBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[InvoiceBill](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[IfInVoice] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[InvoiceStyle] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[InvoiceTotal] [numeric](18, 4) NULL,
		[Explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[InvoiceDate] [datetime] NULL,
		[InvoiceNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[isDraft] [bit] NOT NULL,
		[InvoiceID] [int] IDENTITY(1,1) NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='InvoiceBill' AND a.Name='InvoiceTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE InvoiceBill 
	ALTER COLUMN InvoiceTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'IsStartOk') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[IsStartOk]
	(
	[typeID] [VARCHAR](MAX) NULL,
	[parID] [VARCHAR](MAX) NULL,
	[level] [INT] NULL,
	[sonnum] [INT] NULL,
	[soncount] [INT] NULL,
	[delete] [BIT] NULL,
	[userID] VARCHAR(100) NOT NULL,
	[stypeID] [VARCHAR](MAX) NOT NULL,
	[isOpen] [INT] NOT NULL,		--0=打开开账向导页面，1= 不打开开账向导页面
	) 
END

GO




------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('ItemATypeIdPreset') AND  type = 'U')
BEGIN
	CREATE TABLE ItemATypeIdPreset
	(
	Id			INT IDENTITY(1,1),
	UserCode	VARCHAR(200),
	FullName	VARCHAR(200),
	ATypeUserCode	VARCHAR(200),
	ATypeFullName	VARCHAR(200),
	SubId			INT
	)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM ItemATypeIdPreset)
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES('0321','商品报溢收入','6051','其他业务收入',28),
	('0322','商品获赠收入','6051','其他业务收入',28),
	('0323','成本调价收入','6051','其他业务收入',28),
	('0324','采购退货差价','6051','其他业务收入',28),
	('0325','变价调拨差价','6051','其他业务收入',28),
	('0326','商品拆装差价','6051','其他业务收入',28),
	('0328','商品维修收入','6051','其他业务收入',28),
	('0329','受托退货差价','6051','其他业务收入',28),
	('0332','利息收入','6051','其他业务收入',28),
	('0333','其他收入','6051','其他业务收入',28),
	('03333','调账收入','6051','其他业务收入',28),
	('0404','销售折扣返利支出','6402','其他业务成本',28),
	('0421','商品报损','6402','其他业务成本',28),
	('0422','商品赠出','6402','其他业务成本',28),
	('0423','商品维修支出','6402','其他业务成本',28),
	('0424','商品送修支出','6402','其他业务成本',28),
	('0431','调账亏损','6402','其他业务成本',28),
	('0432','固定资产折旧','6602','管理费用',28),
	('0455','其他支出','6711','营业外支出',28),
	('0456','优惠/抹零金额','6601','销售费用',28),
	('1001','现金','1001','库存现金',28),
	('1132','内部应收','','',28),
	('1133','其他应收','1221','其他应收款',28),
	('1151','预付资金','1123','预付账款',28),
	('1241','库存商品总值','1405','库存商品',28),
	('1261','委托代销商品','','',28),
	('1301','待摊费用','1801','长期待摊费用',28),
	('1501','固定资产','1601','固定资产',28),
	('2121','应付合计','220201','应付货款',28),
	('2131','预收资金','2203','预收账款',28),
	('2132','其他应付','2241','其他应付款',28),
	('2141','代销商品','','',28),
	('2171','应交税金','2221','应交税费',28),
	('2181','会员储值','2203','预收账款',28),
	('5101','销售收入','6001','主营业务收入',28),
	('5103','返点获利收入','6051','其他业务收入',28),
	('5288','银行存款-中国银行','1002','银行存款',28),
	('5401','销售成本','6401','主营业务成本',28),
	('987','应收合计','1122','应收账款',28),
	('0321','商品报溢收入','5051','其他业务收入',2),
	('0322','商品获赠收入','5051','其他业务收入',2),
	('0323','成本调价收入','5051','其他业务收入',2),
	('0324','采购退货差价','5051','其他业务收入',2),
	('0325','变价调拨差价','5051','其他业务收入',2),
	('0326','商品拆装差价','5051','其他业务收入',2),
	('0328','商品维修收入','5051','其他业务收入',2),
	('0329','受托退货差价','5051','其他业务收入',2),
	('0332','利息收入','5051','其他业务收入',2),
	('0333','其他收入','5051','其他业务收入',2),
	('03333','调账收入','5051','其他业务收入',2),
	('0404','销售折扣返利支出','5402','其他业务支出',2),
	('0421','商品报损','5402','其他业务支出',2),
	('0422','商品赠出','5402','其他业务支出',2),
	('0423','商品维修支出','5402','其他业务支出',2),
	('0424','商品送修支出','5402','其他业务支出',2),
	('0431','调账亏损','5402','其他业务支出',2),
	('0432','固定资产折旧','5602','管理费用',2),
	('0455','其他支出','5711','营业外支出',2),
	('0456','优惠/抹零金额','5601','销售费用',2),
	('1001','现金','1001','库存现金',2),
	('1132','内部应收','','',2),
	('1133','其他应收','1221','其他应收款',2),
	('1151','预付资金','1123','预付账款',2),
	('1241','库存商品总值','1405','库存商品',2),
	('1261','委托代销商品','','',2),
	('1301','待摊费用','1801','长期待摊费用',2),
	('1501','固定资产','1601','固定资产',2),
	('2121','应付合计','220201','应付货款',2),
	('2131','预收资金','2203','预收账款',2),
	('2132','其他应付','2241','其他应付款',2),
	('2141','代销商品','','',2),
	('2171','应交税金','2221','应缴税费',2),
	('2181','会员储值','2203','预收账款',2),
	('5101','销售收入','5001','主营业务收入',2),
	('5103','返点获利收入','5051','其他业务收入',2),
	('5288','银行存款-中国银行','1002','银行存款',2),
	('5401','销售成本','5401','主营业务成本',2),
	('987','应收合计','1122','应收账款',2),
	('0321','商品报溢收入','5102','其他业务收入',1),
	('0322','商品获赠收入','5102','其他业务收入',1),
	('0323','成本调价收入','5102','其他业务收入',1),
	('0324','采购退货差价','5102','其他业务收入',1),
	('0325','变价调拨差价','5102','其他业务收入',1),
	('0326','商品拆装差价','5102','其他业务收入',1),
	('0328','商品维修收入','5102','其他业务收入',1),
	('0329','受托退货差价','5102','其他业务收入',1),
	('0332','利息收入','5102','其他业务收入',1),
	('0333','其他收入','5102','其他业务收入',1),
	('03333','调账收入','5102','其他业务收入',1),
	('0404','销售折扣返利支出','5405','其他业务支出',1),
	('0421','商品报损','5405','其他业务支出',1),
	('0422','商品赠出','5405','其他业务支出',1),
	('0423','商品维修支出','5405','其他业务支出',1),
	('0424','商品送修支出','5405','其他业务支出',1),
	('0431','调账亏损','5405','其他业务支出',1),
	('0432','固定资产折旧','5502','管理费用',1),
	('0455','其他支出','5601','营业外支出',1),
	('0456','优惠/抹零金额','5501','营业费用',1),
	('1001','现金','1001','现金',1),
	('1132','内部应收','','',1),
	('1133','其他应收','1133','其他应收款',1),
	('1151','预付资金','1151','预付账款',1),
	('1241','库存商品总值','1243','库存商品',1),
	('1261','委托代销商品','','',1),
	('1301','待摊费用','1901','长期待摊费用',1),
	('1501','固定资产','1501','固定资产',1),
	('2121','应付合计','212101','应付货款',1),
	('2131','预收资金','2131','预收账款',1),
	('2132','其他应付','2181','其他应付款',1),
	('2141','代销商品','','',1),
	('2171','应交税金','21710110','未交增值税',1),
	('2181','会员储值','2131','预收账款',1),
	('5101','销售收入','5101','主营业务收入',1),
	('5103','返点获利收入','5102','其他业务收入',1),
	('5288','银行存款-中国银行','1002','银行存款',1),
	('5401','销售成本','5401','主营业务成本',1),
	('987','应收合计','1131','应收账款',1)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '实收资本')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('3001','实收资本','3101','实收资本（或股本）',1),
	('3001','实收资本','3001','实收资本',2),
	('3001','实收资本','4001','实收资本',28),
	('3101','其他资本','3101','实收资本（或股本）',1),
	('3101','其他资本','3001','实收资本',2),
	('3101','其他资本','4001','实收资本',28),
	('3111','资本公积','3111','资本公积',1),
	('3111','资本公积','3002','资本公积',2),
	('3111','资本公积','4002','资本公积',28),
	('3121','盈余公积','3121','盈余公积',1),
	('3121','盈余公积','3101','盈余公积',2),
	('3121','盈余公积','4101','盈余公积',28),
	('3141','未分配利润','314115','未分配利润',1),
	('3141','未分配利润','3104','利润分配',2),
	('3141','未分配利润','4104','利润分配',28)
END
GO
IF EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '资本公积' AND SubId = 1 AND ATypeFullName='资本公积')
BEGIN
	UPDATE dbo.ItemATypeIdPreset SET ATypeUserCode = '311101',ATypeFullName='资本（或股本）溢价' WHERE FullName = '资本公积' AND SubId = 1 AND ATypeFullName='资本公积'
	UPDATE dbo.ItemATypeIdPreset SET ATypeUserCode = '312101',ATypeFullName='法定盈余公积' WHERE FullName = '盈余公积' AND SubId = 1 AND ATypeFullName='盈余公积'
END
GO
IF EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '现金')
BEGIN
	UPDATE dbo.ItemATypeIdPreset SET FullName = '默认现金' WHERE FullName = '现金' 	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '长期股权投资')
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('SYS-1511','长期股权投资','140102','其他股权投资',1),
	('SYS-1511','长期股权投资','1511','长期股权投资',2),
	('SYS-1511','长期股权投资','1511','长期股权投资',28)
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '在建工程')
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
		('SYS-1604','在建工程','1603','在建工程',1),
	('SYS-1604','在建工程','1604','在建工程',2),
	('SYS-1604','在建工程','1604','在建工程',28)
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '会员储值')
BEGIN
	UPDATE dbo.ItemATypeIdPreset SET FullName = '『会员储值』' WHERE FullName = '会员储值'
END
GO

--9.7新增项目对应科目
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '发出商品')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('1251','发出商品','1242','发出商品',1),
	('1251','发出商品','1406','发出商品',2),
	('1251','发出商品','1406','发出商品',28),
	('2122','应付暂估','212102','应付暂估',1),
	('2122','应付暂估','220202','应付暂估',2),
	('2122','应付暂估','220202','应付暂估',28),
	('2121','应付合计','212101','应付货款',1),
	('2121','应付合计','220201','应付货款',2),
	('2121','应付合计','220201','应付货款',28)
	
END
GO


DELETE FROM dbo.ItemATypeIdPreset WHERE FullName = '运杂费'
--9.8.1 bug1358
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '运杂费')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('044598','运杂费','5501','营业费用',1),
	('044598','运杂费','5601','销售费用',2),
	('044598','运杂费','6601','销售费用',28)
	--('044598','运杂费','21710101','进项税额',1),
	--('044598','运杂费','2221','应缴税费',2),
	--('044598','运杂费','2221','应交税费',28)
END
GO

DELETE FROM ItemATypeIdPreset WHERE FullName = '兑汇损益'
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '汇兑损益')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('043599','汇兑损益','5503','财务费用',1),
	('043599','汇兑损益','5603','财务费用',2),
	('043599','汇兑损益','6603','财务费用',28)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '业务提成')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('044599','业务提成','5501','营业费用',1),
	('044599','业务提成','5601','销售费用',2),
	('044599','业务提成','6601','销售费用',28)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '市场活动费用')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('044597','市场活动费用','5501','营业费用',1),
	('044597','市场活动费用','5601','销售费用',2),
	('044597','市场活动费用','6601','销售费用',28)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '优惠券收入')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('0334','优惠券收入','5102','其他业务收入',1),
	('0334','优惠券收入','5051','其他业务收入',2),
	('0334','优惠券收入','6051','其他业务收入',28)
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '『优惠券』')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('2191','『优惠券』','2131','预收账款',1),
	('2191','『优惠券』','2203','预收账款',2),
	('2191','『优惠券』','2203','预收账款',28)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '积分转储值')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('044596','积分转储值','5501','营业费用',1),
	('044596','积分转储值','5601','销售费用',2),
	('044596','积分转储值','6601','销售费用',28)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '周转材料')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	--('1271','周转材料','1231','低值易耗品',1), --企业会计制度
	('1271','周转材料','1411','周转材料',2),--小企业会计准则
	('1271','周转材料','1411','周转材料',28)--新会计准则
		
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemATypeIdPreset WHERE FullName = '配送差价')
BEGIN
	INSERT INTO ItemATypeIdPreset(UserCode,FullName,ATypeUserCode,ATypeFullName,SubId)
	VALUES
	('0335','配送差价','5102','其他业务收入',1), --企业会计制度
	('0335','配送差价','5051','其他业务收入',2),--小企业会计准则
	('0335','配送差价','6051','其他业务收入',28)--新会计准则
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ItemType]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ItemType](
		[nId]	INT IDENTITY(1,1),
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ParId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint] NOT NULL,
		[sonnum] [int] NOT NULL,
		[soncount] [int] NOT NULL,
		[CanModify] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[UserCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[FullName] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Attribute]	[SMALLINT] NOT NULL,
		[Comment] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL,
		[STypeid] [VARCHAR](50) NOT NULL,
		[deleted] [bit] NOT NULL DEFAULT (0),
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0)
	) ON [PRIMARY]
END


IF NOT EXISTS(SELECT TOP 1 1 FROM Itemtype)
BEGIN
	INSERT INTO dbo.ItemType(typeId,ParId,leveal,sonnum,soncount,CanModify,UserCode,FullName,Name,Attribute,Comment,STypeid,deleted,PyCode,XiWaMaxNumber)
	VALUES  ('00000','',0,0,0,0,'','','',0,'','00001',0,'',0)
END

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ItemType_Item]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ItemType_Item](
		nId INT IDENTITY(1,1),
		itemTypeId INT NOT NULL,
		itemId	INT NOT NULL
	)
END
GO

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[KDBirdInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[KDBirdInfo](
		[businessId] [varchar](400) NULL,
		[appKey] [varchar](400) NULL,
		[userId] [varchar](400) NULL
	) ON [PRIMARY]
END	

GO

SET ANSI_PADDING OFF
GO






/*
  仓库自定义字段
  张陈仁
  3023-04-10
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ktype_CustomColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table Ktype_CustomColumns 
	(
	   ID                   bigint               identity(1,1),
	   typeid               varchar(100)         null,
	   Costom1              VARCHAR(600)         null,
	   Costom2              VARCHAR(600)         null,
	   Costom3              VARCHAR(600)         null,
	   Costom4              VARCHAR(600)         null,
	   Costom5              VARCHAR(600)         null,
	   Costom6              VARCHAR(600)         null,
	   Costom7              VARCHAR(600)         null,
	   Costom8              VARCHAR(600)         null,
	   Costom9              VARCHAR(600)         null,
	   Costom10             VARCHAR(600)         null,
	   Costom11             VARCHAR(600)         null,
	   Costom12             VARCHAR(600)         null,
	   Costom13             VARCHAR(600)         null,
	   Costom14             VARCHAR(600)         null,
	   Costom15             VARCHAR(600)         null,
	   Costom16             VARCHAR(600)         null,
	   Costom17             VARCHAR(600)         null,
	   Costom18             VARCHAR(600)         null,
	   Costom19             VARCHAR(600)         null,
	   Costom20             VARCHAR(600)         null
   )
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ktype_l]    脚本日期: 05/05/2010 14:47:54 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ktype_l]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ktype_l](
		[etypeid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[typeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[flag] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

-- Add by 李海洋 
-- Date: 2012-03-30
-- Description: 增加: 修改, 分类, 停用, 删除 细分权限
------------------------------------------表修改区域开始-------------------------------------------------
-- 修改权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[ktype_l]') 
		AND name = 'modifyflag'
)
BEGIN
		ALTER TABLE dbo.ktype_l DROP COLUMN modifyflag ;
END
GO

-- 分类权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[ktype_l]') 
		AND name = 'assortflag'
)
BEGIN
  ALTER TABLE dbo.ktype_l DROP COLUMN assortflag ;
END
GO

-- 停用权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[ktype_l]') 
		AND name = 'disableflag'
)
BEGIN
  ALTER TABLE dbo.ktype_l DROP COLUMN disableflag ;
END
GO

-- 删除权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[ktype_l]') 
		AND name = 'delflag'
)
BEGIN
		ALTER TABLE dbo.ktype_l DROP COLUMN delflag ;
END  
GO

------------------------------------------表修改区域结束-------------------------------------------------





------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ktype_l]') AND name = N'IX_ktype_l')
BEGIN
	DROP INDEX IX_ktype_l ON ktype_l
END
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('KTYPE_L') AND name = 'CIX_KTYPE_L_etypeid')
--DROP INDEX CIX_KTYPE_L_etypeid ON KTYPE_L 
CREATE CLUSTERED INDEX CIX_KTYPE_L_etypeid ON KTYPE_L(etypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------更新新加列结束-------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[LendBill]    脚本日期: 05/05/2010 14:47:55 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[LendBill]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        CREATE TABLE [dbo].[LendBill]
            (
              BillNumberId NUMERIC(10, 0) NOT NULL ,
              PtypeId VARCHAR(50) COLLATE Chinese_PRC_CI_AS
                                  NULL ,
              Qty NUMERIC(18, 4) NULL
                                 CONSTRAINT [DF_LendBill_Qty] DEFAULT ( 0 ) ,
              JobNumber VARCHAR(20)
                COLLATE Chinese_PRC_CI_AS
                NULL
                CONSTRAINT DF_LendBill_JobNumber DEFAULT ( '' ) ,
              GoodsNo INT NULL
                          CONSTRAINT [DF_LendBill_GoodsNo] DEFAULT ( 0 ) ,
              OutFactoryDate DATETIME NULL ,
              comment VARCHAR(255) COLLATE Chinese_PRC_CI_AS
                                   NULL ,
              Serial TEXT COLLATE Chinese_PRC_CI_AS
                          NULL
                          CONSTRAINT [DF_LendBill_Serial] DEFAULT ( '' ) ,
              BackQty NUMERIC(18, 4) NULL ,
              Id INT IDENTITY(1, 1)
                     NOT NULL ,
              Stypeid VARCHAR(50) COLLATE Chinese_PRC_CI_AS
                                  NULL
                                  DEFAULT ( '' ) ,
              CargoID INT NULL
                          DEFAULT ( 0 ) ,
              BackItemId INT NOT NULL
                             DEFAULT ( 0 ) ,
              ItemID BIGINT NULL ,
              IsCombined INT NULL ,
              NQty NUMERIC(22, 10) DEFAULT ( 0 ) ,
              GoodsNumber VARCHAR(100) DEFAULT ( '' ) ,
              ProduceDate VARCHAR(50) DEFAULT ( '' ) ,
              ValidDate VARCHAR(50) DEFAULT ( '' ) ,
              UnitRate NUMERIC(18, 4)
              ,ShowOrder INT DEFAULT(0),
              InFactQty   NUMERIC(24,10) DEFAULT(0),
              OutFactQty  NUMERIC(24,10) DEFAULT(0),
             FromBillid	INT DEFAULT(0) 
            )
        ON  [PRIMARY] TEXTIMAGE_ON [PRIMARY]


    END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LendBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.LendBill
	ADD InFactQty NUMERIC(24,10) DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LendBill',N'U') AND Name='FromBillid')
BEGIN
	ALTER TABLE dbo.LendBill
	ADD FromBillid INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LendBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.LendBill
	ADD OutFactQty NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE dbo.LendBill SET InFactQty=0 WHERE InFactQty IS NULL
	UPDATE dbo.LendBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LendBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.LendBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.LendBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'STypeID' ) 
    BEGIN
        ALTER TABLE LendBill ADD STypeID VARCHAR(50) DEFAULT('')
        DECLARE @strSql VARCHAR(8000)
	
        SELECT  @strSql = '
		UPDATE LendBill SET STypeID=' + CHAR(39) + '00001' + CHAR(39) + '
		WHERE STypeID=' + CHAR(39) + CHAR(39) + ' OR STypeID IS NULL '
		
        EXEC(@strSql)
    END

GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'CargoID' ) 
    BEGIN
        ALTER TABLE LendBill ADD CargoID INT NULL DEFAULT(0)
    END

GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'BackItemId' ) 
    BEGIN
        ALTER TABLE LendBill ADD BackItemId INT NOT NULL DEFAULT(0);
    END

GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'ItemID' ) 
    BEGIN
        ALTER TABLE LendBill ADD ItemID  BIGINT
    END
GO
IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'IsCombined' ) 
    BEGIN
        ALTER TABLE LendBill ADD IsCombined   INT
    END
GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'NQty' ) 
    BEGIN
        ALTER TABLE LendBill ADD NQty   NUMERIC(22,10)     DEFAULT(0)
    END
GO


IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'GoodsNumber' ) 
    BEGIN
        ALTER TABLE LendBill ADD
        GoodsNumber					VARCHAR(100) DEFAULT(''),		
        ProduceDate					VARCHAR(50)		DEFAULT (''),
        ValidDate					VARCHAR(50)		DEFAULT ('')
		
    END
GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'UnitRate' ) 
    BEGIN
        ALTER TABLE LendBill ADD
        UnitRate NUMERIC(18, 4) DEFAULT(1)
    END
GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'BuyQty' ) 
    BEGIN
        ALTER TABLE LendBill ADD
        BuyQty NUMERIC(24, 10) NULL DEFAULT(0)
    END
GO

UPDATE dbo.LendBill SET BuyQty = 0 WHERE BuyQty IS NULL
GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'LendBill'
                        AND a.Name = 'SaleQty' ) 
    BEGIN
        ALTER TABLE LendBill ADD
        SaleQty NUMERIC(24, 10) NULL DEFAULT(0)
    END
GO

UPDATE dbo.LendBill SET SaleQty = 0 WHERE SaleQty IS NULL
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('LendBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table LendBill drop constraint '+@dfname);
		
	ALTER TABLE LendBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE LendBill ADD CONSTRAINT DF_LendBill_Serial DEFAULT('') FOR Serial

END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE ( name VARCHAR(100) ); 
INSERT  INTO @t
        SELECT  'MSaleTotal'
        UNION ALL
        SELECT  'MTotal'
        UNION ALL
        SELECT  'MTaxTotal'
        UNION ALL
        SELECT  'CurMSaleTotal'
        UNION ALL
        SELECT  'CurMTotal'
        UNION ALL
        SELECT  'CurMTaxTotal';
DECLARE @sql NVARCHAR(MAX)= '';
DECLARE @tn VARCHAR(500)= 'LendBill';

SELECT  @sql = @sql + CASE WHEN a.name IS NULL THEN ''
                           ELSE ' alter table ' + @tn + ' drop constraint '
                                + a.name + ';'
                      END + ' alter table ' + @tn + ' drop column ' + d.name
        + ';'
FROM    sys.default_constraints a
        RIGHT JOIN sys.all_columns b ON a.parent_object_id = b.object_id
                                        AND a.parent_column_id = b.column_id
        JOIN @t d ON b.name = d.name
WHERE   b.object_id = OBJECT_ID(@tn, 'U')

IF @sql <> '' 
    EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LENDBILL') AND name = 'CIX_LENDBILL_BillNumberID')
--DROP INDEX CIX_LENDBILL_BillNumberID ON LENDBILL 
CREATE CLUSTERED INDEX CIX_LENDBILL_BillNumberID ON LENDBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LENDBILL') AND name = 'NCIX_LENDBILL_Ptypeid')
--DROP INDEX NCIX_LENDBILL_Ptypeid ON LENDBILL 
CREATE NONCLUSTERED INDEX NCIX_LENDBILL_Ptypeid ON LENDBILL(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
            
 IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendBill' AND a.Name='BuyQty' AND  a.xprec <>24
    )
    BEGIN
	ALTER TABLE LendBill 
	ALTER COLUMN BuyQty NUMERIC(24,10)
    END
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendBill' AND a.Name='SaleQty' AND a.xprec <>24
    )
    BEGIN
	ALTER TABLE LendBill 
	ALTER COLUMN SaleQty NUMERIC(24,10)
    END                            
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/*
借钱过账表  
参照V_LendFace
*/
IF  EXISTS (SELECT 1
           FROM  sysobjects
           WHERE   id = object_id('LendCheck')
           AND  type = 'U')
           DROP TABLE LendCheck
BEGIN
	CREATE TABLE LendCheck (
		pTypeId                 VARCHAR(50) ,   
		pEntryCode              VARCHAR(200),
		kTypeId					VARCHAR(50) ,  
		bTypeID					VARCHAR(50) , 
		DealBtypeId				VARCHAR(50) ,--结算单位
		ETypeId					VARCHAR(50) ,
		BillNumberID			NUMERIC(10,0),
		BillDate				DATETIME,
		BillType				INT ,
		BillCode				VARCHAR(200),
		Comment					VARCHAR(255),	
		STypeID					VARCHAR(50),
		Qty						NUMERIC(18,4),
		ItemID					BIGINT,
		IsCombined				INT,
		NQty					NUMERIC(18,4),
		GoodsNumber				VARCHAR(100),
		Producedate				VARCHAR(50),
		ValidDate				VARCHAR(50),
		CustomdetailID			INT -- 明细id
	)
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendCheck' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendCheck 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendCheck' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendCheck 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[LendIndex]    脚本日期: 05/05/2010 14:47:56 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[LendIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[LendIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_LendIndex_BillCode]  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_BillComment]  DEFAULT (''),
		[atypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_atypeid]  DEFAULT ('0'),
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_ptypeid]  DEFAULT ('0'),
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_btypeid]  DEFAULT ('0'),
		[dealbtypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_dealbtypeid]  DEFAULT ('0'),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_etypeid]  DEFAULT ('0'),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_ktypeid]  DEFAULT ('0'),
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_ktypeid2]  DEFAULT ('0'),
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_ifcheck]  DEFAULT ('t'),
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalmoney] [numeric](18, 4) NULL CONSTRAINT [DF_LendIndex_total]  DEFAULT (0),
		[totalinmoney] [numeric](18, 4) NULL CONSTRAINT [DF_LendIndex_totalinmoney]  DEFAULT (0),
		[totalqty] [numeric](18, 4) NULL CONSTRAINT [DF_LendIndex_totalqty]  DEFAULT (0),
		[tax] [numeric](5, 2) NULL CONSTRAINT [DF_LendIndex_tax]  DEFAULT (17),
		[period] [smallint] NULL CONSTRAINT [DF_LendIndex_period]  DEFAULT (0),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_explain]  DEFAULT (''),
		[RedWord] [bit] NOT NULL CONSTRAINT [DF_LendIndex_RedWord]  DEFAULT (0),
		[draft] [bit] NOT NULL CONSTRAINT [DF_LendIndex_draft]  DEFAULT (0),
		[OrderId] [numeric](10, 0) NULL CONSTRAINT [DF_LendIndex_OrderId]  DEFAULT (0),
		[waybillcode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsnumber] [numeric](2, 0) NULL,
		[packway] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[TEL] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
		[Uploaded] [bit] NOT NULL CONSTRAINT [DF_LendIndex_Uploaded]  DEFAULT (0),
		[OFF_ID] [uniqueidentifier] NULL,
		[DTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_DTypeID]  DEFAULT (''),
		[ID] [numeric](10, 0) NOT NULL CONSTRAINT [DF_LendIndex_ID]  DEFAULT (0),
		[IfAudit] [int] NULL CONSTRAINT [DF_LendIndex_IfAudit]  DEFAULT ('1'),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[IsIni]			BIT NULL DEFAULT(0),
		InFactState       INT DEFAULT(0),	  --1 仓库入库未完成 2仓库入库已完成
		InFactRefState    INT DEFAULT(0),     -- 0仓库入库未引用  1仓库入库已引用
		OutFactState	  INT DEFAULT(0),	  --1 仓库出库未完成 2仓库出库已完成	
		OutFactRefState   INT DEFAULT(0),	  --0 仓库出库未引用 1仓库出库已引用
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LendIndex',N'U') AND Name='InFactRefState')
BEGIN
	ALTER TABLE LendIndex
	ADD InFactRefState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LendIndex',N'U') AND Name='OutFactRefState')
BEGIN
	ALTER TABLE LendIndex
	ADD OutFactRefState INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LendIndex',N'U') AND Name='InFactState')
BEGIN
	ALTER TABLE LendIndex
	ADD InFactState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LendIndex',N'U') AND Name='OutFactState')
BEGIN
	ALTER TABLE LendIndex
	ADD OutFactState INT DEFAULT(0)
END
GO
	UPDATE dbo.LendIndex SET InFactState=0 WHERE InFactState IS NULL
	UPDATE dbo.LendIndex SET OutFactState=0 WHERE OutFactState IS NULL
	UPDATE dbo.LendIndex SET InFactRefState=0 WHERE InFactRefState IS NULL
	UPDATE dbo.LendIndex SET OutFactRefState=0 WHERE OutFactRefState IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE LendIndex ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE LendIndex SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE LendIndex 
		ADD IsIni BIT NULL DEFAULT(0)
		
	EXEC('UPDATE LendIndex SET IsIni=0 WHERE IsIni IS NULL')
END

-- 添加[dealbtypeid]
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='dealbtypeid'
)
BEGIN
	ALTER TABLE LendIndex 
		ADD dealbtypeid VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LendIndex_dealbtypeid]  DEFAULT ('0')
		
	EXEC('UPDATE LendIndex SET dealbtypeid = btypeid WHERE dealbtypeid IS NULL')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='redreason'
)
BEGIN

	ALTER TABLE LendIndex 
		ADD redreason VARCHAR(500) NULL 
	EXEC('UPDATE LendIndex SET redreason = '''' WHERE redreason IS NULL')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='Poster'
)
BEGIN

	ALTER TABLE LendIndex ADD Poster VARCHAR(50) NULL 
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='posttime'
)
BEGIN

	ALTER TABLE LendIndex ADD posttime DATETIME NULL 
END
GO

--借欠类单据增加制单时间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='checkTime'
)
BEGIN

	ALTER TABLE LendIndex ADD checkTime DATETIME DEFAULT GETDATE()
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='ifYearBill'
)
BEGIN
	ALTER TABLE LendIndex ADD ifYearBill INT DEFAULT(0)
END
GO 
UPDATE dbo.LendIndex SET ifYearBill = 0 WHERE ifYearBill IS NULL
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='RedWord' AND a.xtype=104
)
BEGIN

	DECLARE @sql VARCHAR(255)
	SELECT @sql='alter table ['+b.name+'] drop constraint ['+d.name+']'
	FROM syscolumns a
	JOIN sysobjects b ON a.id=b.id AND a.name='RedWord' AND b.name='LendIndex'
	JOIN syscomments c ON a.cdefault=c.id
	JOIN sysobjects d ON c.id=d.id
	EXEC(@sql)
	ALTER TABLE LendIndex ALTER COLUMN RedWord INT 
	
END
GO

--修改 fiaudit 默认值为 ' '
IF EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'LendIndex',N'U') AND LOWER(Name)='ifaudit')
BEGIN
	ALTER TABLE LendIndex
	DROP CONSTRAINT [DF_LendIndex_IfAudit]
	
	ALTER TABLE LendIndex
	ALTER COLUMN IfAudit CHAR(1)
	
	ALTER TABLE LendIndex
	ADD CONSTRAINT [DF_LendIndex_IfAudit] DEFAULT('') FOR IfAudit
END
	

IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID('LendIndex',N'U') AND Name='UpdateE')
BEGIN
	ALTER TABLE LendIndex ADD UpdateE VARCHAR(50) DEFAULT('')
END

--9.6.1运单号从20个字符升级为50个字符
IF EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID('LendIndex',N'U') AND LOWER(NAME)='waybillcode' AND [Length]=20)
BEGIN
	ALTER TABLE dbo.LendIndex 
	ALTER COLUMN waybillcode VARCHAR(50)  COLLATE Chinese_PRC_CI_AS NULL
END
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[LendIndex]') AND name = N'Idx_LendIndex')
DROP INDEX [dbo].[LendIndex].[Idx_LendIndex]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LENDINDEX') AND name = 'CIX_LENDINDEX_BillNumberId')
--DROP INDEX CIX_LENDINDEX_BillNumberId ON LENDINDEX 
CREATE CLUSTERED INDEX CIX_LENDINDEX_BillNumberId ON LENDINDEX(BillNumberId) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendIndex 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendIndex 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LendIndex' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LendIndex 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT  * FROM    dbo.sysobjects WHERE   id = OBJECT_ID(N'[dbo].[LimitLog]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        CREATE TABLE [dbo].[LimitLog]
            (
              [Operator] [varchar](100),	--操作员ID
              [Etypeid] [varchar](100),		--被修改权限的操作员ID
              [oldlim] [varchar](8000),		--原权限字符串
              [newlim] [varchar](8000),		--修改后权限字符串
              [ChangeDatetime] DATETIME,	--修改时间	
              [ChangeEvent]	VARCHAR(200)	--操作事件
            )
        ON  [PRIMARY]
    END	
GO

-----------------------------------------修改表结构----------------------------------------------------
IF NOT EXISTS(SELECT * FROM syscolumns where id = object_id(N'[dbo].[LimitLog]') and  name = 'oldlim' AND length = 8000)
	BEGIN
		 ALTER TABLE LimitLog
			ALTER COLUMN oldlim varchar(8000) 
	END
GO
IF NOT EXISTS(SELECT * FROM syscolumns where id = object_id(N'[dbo].[LimitLog]') and  name = 'newlim' AND length = 8000)
	BEGIN
		 ALTER TABLE LimitLog
			ALTER COLUMN newlim varchar(8000) 
	END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Listtable]    脚本日期: 05/05/2010 14:47:57 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ListTable](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillDate] [datetime] NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Listtable_AtypeId]  DEFAULT (0),
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Listtable_PtypeId]  DEFAULT (0),
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Listtable_BtypeId]  DEFAULT (0),
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Listtable_EtypeId]  DEFAULT (0),
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Listtable_KtypeId]  DEFAULT (0),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_Listtable_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_Listtable_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_Listtable_Total]  DEFAULT (0),
		[CostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_Listtable_CostPrice]  DEFAULT (0),
		[CostTotal] [numeric](18, 4) NULL CONSTRAINT [DF_Listtable_CostTotal]  DEFAULT (0),
		[JobNumber] [char](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Listtable_JobNumber]  DEFAULT (0),
		[GoodsNo] [int] NULL CONSTRAINT [DF_Listtable_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[Audited] [bit] NOT NULL CONSTRAINT [DF_Listtable_Audited]  DEFAULT (0),
		[Ifout] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Listtable_Ifout]  DEFAULT ('0'),
		[DTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_ListTable_DTypeID]  DEFAULT (''),
		[STypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[STypeID2] [varchar](50) DEFAULT '',
		[CID]	INT  NULL  DEFAULT(0),
		[Ntotal]	NUMERIC(22,10) NULL  DEFAULT(0),
		[Id] INT IDENTITY(1,1)
	) ON [PRIMARY]


END
GO



------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ListTable' AND a.Name='DTypeID'
)
BEGIN
	ALTER TABLE ListTable ADD DTypeID VARCHAR(50) NULL CONSTRAINT [DF_ListTable_DTypeID]  DEFAULT ('')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ListTable' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE ListTable ADD STypeID VARCHAR(50) DEFAULT('')
		
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE Listtable SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ListTable' AND a.Name='STypeID2'
)
BEGIN
		ALTER TABLE ListTable ADD STypeID2 VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ListTable' AND a.Name='CID'
)
BEGIN
		ALTER TABLE ListTable ADD CID INT DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ListTable' AND a.Name='Ntotal'
)
BEGIN
		ALTER TABLE ListTable ADD Ntotal NUMERIC(22,10) DEFAULT(0)
END
GO
-- 添加汇率字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ListTable' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE ListTable ADD Rate NUMERIC(18,4)
END
go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ListTable' AND a.Name='Id'
)
BEGIN
	ALTER TABLE ListTable ADD Id INT IDENTITY(1,1)
END
go

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ListTable]') AND name = N'NCIX_ATYPEID')
	DROP INDEX [dbo].[ListTable].NCIX_ATYPEID
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ListTable]') AND name = N'NCIX_AUDITED')
	DROP INDEX [dbo].[ListTable].NCIX_AUDITED
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Listtable]') AND name = N'IX_ListTable_ATypeID')
DROP INDEX [IX_ListTable_ATypeID] ON [dbo].[Listtable] 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Listtable]') AND name = N'IX_ListTable_BillDate')
DROP INDEX [IX_ListTable_BillDate] ON [dbo].[Listtable] 

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Listtable]') AND name = N'IX_ListTable_BillNumberId')
DROP INDEX [IX_ListTable_BillNumberId] ON [dbo].[Listtable] 

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Listtable]') AND name = N'IX_ListTable_BTypeId')
DROP INDEX [IX_ListTable_BTypeId] ON [dbo].[Listtable] 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Listtable]') AND name = N'IX_ListTable_ETypeID')
DROP INDEX [IX_ListTable_ETypeId] ON [dbo].[Listtable] 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Listtable]') AND name = N'IX_ListTable_KTypeID')
DROP INDEX [IX_ListTable_KTypeId] ON [dbo].[Listtable] 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Listtable]') AND name = N'IX_ListTable_PTypeID')
DROP INDEX [IX_ListTable_PTypeId] ON [dbo].[Listtable] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'CIX_LISTTABLE_BillDate')
--DROP INDEX CIX_LISTTABLE_BillDate ON LISTTABLE 
CREATE CLUSTERED INDEX CIX_LISTTABLE_BillDate ON LISTTABLE(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'NCIX_LISTTABLE_BillNumberID')
--DROP INDEX NCIX_LISTTABLE_BillNumberID ON LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_LISTTABLE_BillNumberID ON LISTTABLE(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'NCIX_LISTTABLE_Ptypeid')
--DROP INDEX NCIX_LISTTABLE_Ptypeid ON LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_LISTTABLE_Ptypeid ON LISTTABLE(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'NCIX_LISTTABLE_Atypeid')
--DROP INDEX NCIX_LISTTABLE_Atypeid ON LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_LISTTABLE_Atypeid ON LISTTABLE(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'NCIX_LISTTABLE_Billtype')
--DROP INDEX NCIX_LISTTABLE_Billtype ON LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_LISTTABLE_Billtype ON LISTTABLE(Billtype) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'NCIX_LISTTABLE_Btypeid')
--DROP INDEX NCIX_LISTTABLE_Btypeid ON LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_LISTTABLE_Btypeid ON LISTTABLE(Btypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'NCIX_LISTTABLE_Etypeid')
--DROP INDEX NCIX_LISTTABLE_Etypeid ON LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_LISTTABLE_Etypeid ON LISTTABLE(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'NCIX_LISTTABLE_Ktypeid')
--DROP INDEX NCIX_LISTTABLE_Ktypeid ON LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_LISTTABLE_Ktypeid ON LISTTABLE(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LISTTABLE') AND name = 'NCIX_LISTTABLE_Stypeid')
--DROP INDEX NCIX_LISTTABLE_Stypeid ON LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_LISTTABLE_Stypeid ON LISTTABLE(Stypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Listtable' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Listtable 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Listtable' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Listtable 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Listtable' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Listtable 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Listtable' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Listtable 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Listtable' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Listtable 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Listtable' AND a.Name='Ntotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Listtable 
	ALTER COLUMN Ntotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Listtable' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Listtable 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[LoadBillForOperator]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[LoadBillForOperator]
	(
		Url				VARCHAR(200) NULL DEFAULT(''),	--记录位置
		ETypeId			VARCHAR(50) NULL DEFAULT(''),	--操作员ID
		BeginDate		VARCHAR(50) NULL DEFAULT(''),	--开始日期
		EndDate			VARCHAR(50) NULL DEFAULT(''),	--截止日期
		IsSumPType		INT  NULL DEFAULT(0),			--是否汇总商品选项
		IsImportPrice	INT  NULL DEFAULT(0)			--是否导入价格选项
	)
END

--正在操作的单据类型
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b ON a.ID=b.ID
WHERE b.Name='LoadBillForOperator' AND a.Name='LoadBillType'
)
BEGIN
	ALTER TABLE LoadBillForOperator 
		ADD LoadBillType INT NULL DEFAULT(0)
END
GO 
UPDATE LoadBillForOperator SET LoadBillType = 0 WHERE LoadBillType IS NULL
GO
--调单类型
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b ON a.ID=b.ID
WHERE b.Name='LoadBillForOperator' AND a.Name='LoadFromBillType'
)
BEGIN
	ALTER TABLE LoadBillForOperator 
		ADD LoadFromBillType INT NULL DEFAULT(0)
END
GO 
UPDATE LoadBillForOperator SET LoadFromBillType = 0 WHERE LoadFromBillType IS NULL
GO
--状态
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b ON a.ID=b.ID
WHERE b.Name='LoadBillForOperator' AND a.Name='LoadBillState'
)
BEGIN
	ALTER TABLE LoadBillForOperator 
		ADD LoadBillState INT NULL DEFAULT(0)
END
GO 
UPDATE LoadBillForOperator SET LoadBillState = 0 WHERE LoadBillState IS NULL
GO



/****** 对象:  Table [dbo].[LocalDetail]    脚本日期: 05/05/2010 14:47:58 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[LocalDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[LocalDetail](
		[ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
		[BillNumberID] [numeric](18, 0) NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LTypeID] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
		[LTypeID2] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
		[QTY] [numeric](18, 4) NOT NULL,
		[Price] [numeric](18, 4) NULL,
		[Total] [numeric](18, 4) NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[IsUnit2] [int] NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LocalDetail' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	ALTER TABLE LocalDetail ALTER COLUMN Serial VARCHAR(MAX)
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LocalDetail' AND a.Name='QTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LocalDetail 
	ALTER COLUMN QTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LocalDetail' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LocalDetail 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LocalDetail' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LocalDetail 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[LocalIndex]    脚本日期: 05/05/2010 14:47:59 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[LocalIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[LocalIndex](
		[BillNumberID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfCheck] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
		[TotalQty] [numeric](18, 4) NOT NULL,
		[BID] [numeric](10, 0) NULL,
		[BCode] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
		[Period] [smallint] NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[RedWord] [int] NOT NULL,
		[Draft] [bit] NOT NULL,
		[Assessor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[EtypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LocalIndex' AND a.Name='TotalQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LocalIndex 
	ALTER COLUMN TotalQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('LoginLog')
            and   type = 'U')   
BEGIN
	create table LoginLog (
	   id                   int                  identity(1,1),
	   LogTime				DATETIME,
	   comment              varchar(200)         null,
	   beginloginmp			varchar(200),
	   endloginmp				varchar(200),
	   requeststamp			VARCHAR(200),
	   getstamp				VARCHAR(200),
	   finishstamp			VARCHAR(200) ,
	   flag					INT	,
	   timecontrast			INT
	)
END	
GO



			
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[LoginManageInfo]    脚本日期: 05/05/2010 14:48:00 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[LoginManageInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[LoginManageInfo](
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[ManageType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ManageType1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ManageType2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ManageType3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ManageType4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ManageType5] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ManageValue] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[LoginUserCol]    脚本日期: 05/05/2010 14:48:01 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[LoginUserCol]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[LoginUserCol](
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BillType] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[ColDataField] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Display] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_LoginUserCol_Display]  DEFAULT (1)		--1.显示  2.不显示
	) ON [PRIMARY]

	--单据表体字段
	TRUNCATE TABLE LoginUserCol
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','nsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','virtualstockqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','stockunitqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16Out','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','sourcebillname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','billcode','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','ncompletetotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','completetotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','unncompletetotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','uncompletetotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','ktypeid','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','404','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','sourcebillname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','billcode','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','ncompletetotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','completetotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','unncompletetotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','ktypeid','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','sourcebillname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','405','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','nocompleteqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','pricesource','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','costprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','402','costtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','nocompleteqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','costprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','403','costtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','201','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','201','stockunitqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','201','munit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','201','mqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','201','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','201','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','201','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','201','curmsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','202','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','202','stockunitqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','202','munit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','202','mqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','202','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','202','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','202','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','state','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','requestdate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','orderdate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','btypeid','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','nsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','total','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','discounttotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','taxmoney','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','204','taxtotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','jiejiancode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','jiejianusercode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','jiejianfullname','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','jiejianbuydate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','jiejianerrdes','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','errdes1','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','jiejianrepairmode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','169','jiejianstate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','jiejianusercode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','jiejianfullname','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','jiejianbuydate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','jiejianerrdes','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','jiejianrepairmode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','jiejianstate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','jiejiancode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','168','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','126','referprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','nsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','total','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','taxmoney','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','163','taxtotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','nsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','taxtotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','taxmoney','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','162','total','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','base','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','142','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','jiejiancode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','jiejianusercode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','jiejianfullname','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','jiejianbuydate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','jiejianerrdes','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','jiejianrepairmode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','167','jiejianstate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','165','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','165','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','165','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','mqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','stockunitqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','munit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','9','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','87','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','87','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','87','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','nsaletotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','base','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46up','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','57','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','57','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','57','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','57','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','57','adrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','57','nprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','57','ntotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','6','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','mqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','virtualstockqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','stockunitqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','munit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','17','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','nsaletotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','141','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','140','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','nsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','total','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','147','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','146','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','145','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','144','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','buyOrder','pricetotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','buyOrder','advantagetotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','buyOrder','zeropriceqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16In','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16In','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16In','nsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16In','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16In','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16In','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16In','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','16In','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','166Out','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','166Out','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','166Out','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','mqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','msaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','virtualstockqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','stockunitqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','munit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','21','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','munit','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','base','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','nocompleteqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','eusercode','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','efullname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','pricesource','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','promos','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','11','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','71','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','71','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','71','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','eusercode','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','efullname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160Out','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','eusercode','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','efullname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','45','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','nocompleteqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','invoiceqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','ninvoicemoneyex','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','invoicemoneyex','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','ninvoicemoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','invoicemoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','invoicenqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','401','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','factqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','frombillcode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','418','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','419','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','419','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','419','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','419','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','419','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','419','frombillcode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','419','factqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','eusercode','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','efullname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','160In','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','46down','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','414','weight','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','414','volume','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','412','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','412','billqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','412','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','412','billname','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','412','billcode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','413','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','413','behooveqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','413','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','413','billname','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','413','billcode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','413','rqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','accountqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','referprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','139','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','eusercode','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','efullname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','posusercode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','posfullname','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','munit','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','215','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','base','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161Out','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','88','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','88','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','88','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','173','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','173','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','173','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','171','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','171','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','171','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','170','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','170','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','170','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','170','sendcode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','170','sendusercode','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','170','sendfullname','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','170','sendbilldate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','170','senderrdes','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','175','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','175','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','175','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','174','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','174','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','174','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','nsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','total','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','referprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','143','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','161In','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','nsaletotal','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','reachqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','pricesource','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313up','stopreason','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','172Out','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','172Out','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','172Out','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','nsaletotal','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','reachqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','factqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','locknumber','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','pricesource','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','stopreason','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','313down','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','ntaxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','nocompleteqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','pricesource','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12down','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','base','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','nocompleteqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','pricesource','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','promos','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','12up','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','saleOrder','salecount','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','saleOrder','salebackcount','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','saleOrder','pricetotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','saleOrder','advantagetotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','saleOrder','zeropriceqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','saleOrder','qty_qz','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','saleOrder','total_qz','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','saleOrder','maoli_qz','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','72','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','72','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','72','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','172In','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','172In','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','172In','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','stockqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','stocknqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','stockcauqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','cauqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','countqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','countnqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','306','countcauqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','reachqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','base','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','301','stopreason','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','reachqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','base','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','factqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','locknumber','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','pricesource','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','stopreason','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','300','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','188','mqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','188','curmsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','188','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','188','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','188','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','188','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','188','munit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','188','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','base','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','eusercode','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','efullname','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','pricesource','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','promos','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','305','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','nocompleteqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','34','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','ntaxmoney','1')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','nocompleteqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','invoiceqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','ninvoicemoneyex','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','invoicemoneyex','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','ninvoicemoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','invoicemoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','invoicenqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','400','isgift','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','14','mqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','14','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','14','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','14','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','14','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','14','munit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','14','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','14','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','conversionrelationship','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','factqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','420','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','mqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','msaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','accountqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','virtualstockqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','munit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','stockunitqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','costprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','187','costtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','unit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','qty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','nsaleprice','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','assistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','customassistantunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','unitrate','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','nunit','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','nqty','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','total','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','discounttotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','taxmoney','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','185','taxtotal','0')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','unit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','qty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','nsaleprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','conversionrelationship','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','total','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','discounttotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','taxmoney','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','taxtotal','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','expectedinterestrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','expectedinterest','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','referprice','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','assistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','184','customassistantunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','183','unitrate','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','183','nunit','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','183','nqty','2')
	
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')
	INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES('0000100001','329','nqty','2')


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO

DECLARE @operatorid VARCHAR(100)

DECLARE LoginUserColCursor CURSOR FOR
	SELECT etypeid FROM LoginUser WHERE etypeid <> '00001' ORDER BY ETypeId ASC
	
OPEN LoginUserColCursor

FETCH NEXT FROM LoginUserColCursor INTO @operatorid

WHILE @@FETCH_STATUS = 0
BEGIN
	--添加默认不允许修改单据列的“原币税额”
	IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUserCol WHERE etypeid = @operatorid AND ColDataField = 'ntaxmoney')
	BEGIN		
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'160In','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'184','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'11','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'6','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'45','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'301','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'145','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'161Out','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'161In','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'160Out','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'142','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'141','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'140','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'34','ntaxmoney','1')		
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'300','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'146','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'144','ntaxmoney','1')
	END
	
	FETCH NEXT FROM LoginUserColCursor INTO @operatorid
END

CLOSE LoginUserColCursor
DEALLOCATE LoginUserColCursor	

GO



/****** 对象:  Table [dbo].[LoginUserTimeSet]    脚本日期: 05/05/2010 14:48:02 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[LoginUserTimeSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[LoginUserTimeSet](
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[StartTime] [nvarchar](5) COLLATE Chinese_PRC_CI_AS NULL,
		[EndTime] [nvarchar](5) COLLATE Chinese_PRC_CI_AS NULL,
		[Mon] [int] NULL,
		[Tue] [int] NULL,
		[Wed] [int] NULL,
		[Thu] [int] NULL,
		[Fri] [int] NULL,
		[Sat] [int] NULL,
		[Sun] [int] NULL,
		[StartDate] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[EndDate] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[LoginUserTimeSet]') and name = 'Etype' )
BEGIN
     ALTER TABLE dbo.LoginUserTimeSet ADD
           Etype VARCHAR(100) NULL
END

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[LoseBill]    脚本日期: 05/05/2010 14:48:03 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[LoseBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[LoseBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_LoseBill_Qty]  DEFAULT (0),
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LoseBill_JobNumber]  DEFAULT (''),
		[GoodsNo] [int] NULL CONSTRAINT [DF_LoseBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_LoseBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LoseBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_LoseBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_LoseBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LoseBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LoseBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LoseBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_LoseBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_LoseBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_LoseBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_LoseBill_HandZeroCost]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_LoseBill_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_LoseBill_Total]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		UnitID               int             Default(0)  NULL,
		NUnitID              int             Default(0)  NULL,
		NQty                 numeric(22,10)  Default(0)  NULL,
		UnitRate             numeric(22,10)  Default(0)  NULL,
		NUnitMsg             varchar(50)          null,
		MUnitID              int             Default(0)  NULL,
		MQty                 numeric(22,10)  Default(0)  NULL,
		MUnitRate            numeric(22,10)  Default(0)  NULL,
		MUnitMsg             varchar(50)          NULL,
		MPrice				 numeric(22,10)  Default(0)  NULL,
		CargoID				 INT			 DEFAULT(0) NULL,
		ItemID               bigint               null,
	   IsCombined           int                  null	
	   ,ShowOrder INT DEFAULT(0)		
	   ,OutFactQty NUMERIC(24,10) DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),
		[ifWX] [int] NOT NULL DEFAULT(0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'LoseBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.LoseBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'LoseBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.LoseBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'LoseBill',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.LoseBill
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'LoseBill',N'U') AND Name='ifWX')
BEGIN
	ALTER TABLE dbo.LoseBill
	ADD [ifWX] [int] NOT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LoseBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.LoseBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.LoseBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'LoseBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.LoseBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.LoseBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE LoseBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE LoseBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='UnitID')
BEGIN
	ALTER TABLE LoseBill ADD UnitID  INT   NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='NUnitID')
BEGIN
	ALTER TABLE LoseBill ADD NUnitID INT   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='NQty')
BEGIN
	ALTER TABLE LoseBill ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='UnitRate')
BEGIN
	ALTER TABLE LoseBill ADD UnitRate   numeric(22,10)    NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='NUnitMsg')
BEGIN
	ALTER TABLE LoseBill ADD NUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='MUnitID')
BEGIN
	ALTER TABLE LoseBill ADD MUnitID  INT   NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='MQty')
BEGIN
	ALTER TABLE LoseBill ADD MQty   numeric(22,10)   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='MUnitRate')
BEGIN
	ALTER TABLE LoseBill ADD MUnitRate   numeric(22,10)   NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='MUnitMsg')
BEGIN
	ALTER TABLE LoseBill ADD MUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='MPrice')
BEGIN
	ALTER TABLE LoseBill ADD MPrice   numeric(22,10)   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='LoseBill' AND a.Name='CargoID')
BEGIN
	ALTER TABLE LoseBill ADD CargoID INT NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE LoseBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE LoseBill ADD IsCombined   INT
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('LoseBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table LoseBill drop constraint '+@dfname);
		
	ALTER TABLE LoseBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE LoseBill ADD CONSTRAINT DF_LoseBill_Serial DEFAULT('') FOR Serial
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='LoseBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LOSEBILL') AND name = 'CIX_LOSEBILL_BillNumberID')
--DROP INDEX CIX_LOSEBILL_BillNumberID ON LOSEBILL 
CREATE CLUSTERED INDEX CIX_LOSEBILL_BillNumberID ON LOSEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('LOSEBILL') AND name = 'NCIX_LOSEBILL_Ptypeid')
--DROP INDEX NCIX_LOSEBILL_Ptypeid ON LOSEBILL 
CREATE NONCLUSTERED INDEX NCIX_LOSEBILL_Ptypeid ON LOSEBILL(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='LoseBill' AND a.Name='MPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE LoseBill 
	ALTER COLUMN MPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[LType]    脚本日期: 05/05/2010 14:48:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[LType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[LType](
		[TypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ParID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Leveal] [smallint] NOT NULL,
		[SonNum] [int] NOT NULL,
		[SonCount] [int] NOT NULL,
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[UserCode] [varchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](26) COLLATE Chinese_PRC_CI_AS NULL,
		[SysFlag] [bit] NOT NULL CONSTRAINT [DF_LType_SysFlag]  DEFAULT (0),
		[Deleted] [bit] NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]

	delete from ltype
	insert into ltype values ('00000','root',0,0,0,'root','root','root','root',1,0,'系统保留','')
	
	-- 代销仓库加入默认货位
	if not exists(select * from ltype where typeid ='10000' and ktypeid ='10000' and usercode='dftLocal' )
	insert into ltype (typeid,parid,leveal,sonnum,soncount,ktypeid,usercode,fullname,[name],sysflag,deleted,comment)values('10000','00000',1,0,0,'10000','dftLocal','默认货位','默认货位',1,0,'系统保留')	
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
-- ====================================加入 Ltype 的默认货位

Declare @ktypeid varchar(25)
Declare @Ltypeid varchar(25)
if not exists (Select * from ltype where typeid <> '00000')
begin

    Declare ktype_cursor cursor for
    Select TypeId From Stock Where Deleted = 0 And SonNum = 0 ORder By TypeId
    open ktype_cursor
    
    fetch next from ktype_cursor into @ktypeid
    while @@fetch_status = 0
    begin
	select @Ltypeid = cast((SonCount + 1) as varchar)from ltype where typeid = '00000'
	Set @ltypeid = replicate('0',5 - len(@ltypeid)) + @ltypeid
    
	insert into ltype (typeid,parid,leveal,sonnum,soncount,ktypeid,usercode,fullname,[name],sysflag,deleted,comment)
	    values(@ltypeid,'00000',1,0,0,@ktypeid,'dftLocal','默认货位','默认货位',1,0,'系统保留')
	update ltype Set SonNum = SonNum + 1,SonCount = SonCount + 1 where Typeid = '00000'
	fetch next from ktype_cursor into @ktypeid
    end
    
    close ktype_cursor
    Deallocate ktype_cursor
end

-- ====================================End 加入 Ltype 的默认货位
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ManageBType]    脚本日期: 05/05/2010 14:48:05 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ManageBType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ManageBType](
		[ManageBtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Type] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_ManageBType_Type]  DEFAULT (1)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ManageBType]') AND name = N'IX_ManageBType')
--ALTER TABLE [dbo].[ManageBType] DROP CONSTRAINT [IX_ManageBType]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
--ALTER TABLE [dbo].[ManageBType] ADD  CONSTRAINT [IX_ManageBType] UNIQUE NONCLUSTERED 
--(
--	[ManageBtypeID] ASC,
--	[ETypeID] ASC,
--	[Type] ASC
--)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

GO


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON


IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[MenuConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[MenuConfig]
	(
		MoDeid INT,	 --模块ID 
		ModeName VARCHAR(200),  --模块名称
		MenuID VARCHAR(20),	 --模块菜单ID
		IsVisible INT	 --是否可见
	)

END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--账套模板配置表
IF NOT EXISTS(select 1 FROM  sysobjects WHERE id = object_id('MenuTemplateConfig') and type = 'U')
	BEGIN
		CREATE TABLE MenuTemplateConfig (
			NId			INT			IDENTITY(1,1),
			MenuID		INT			NOT NULL,
			Caption		VARCHAR(50)	NOT NULL,
			Name		VARCHAR(50) NOT NULL,
			IsChecked	INT			DEFAULT(0)
		)
	END
GO

--===============================================默认值【BEGIN】============================================
IF NOT EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig)
	BEGIN
		INSERT INTO MenuTemplateConfig(MenuID,Caption,Name,IsChecked)
		SELECT 510,'销售管理','limit_menu_sale',	1 UNION
		SELECT 520,'采购管理','limit_menu_buy',	1		UNION
		SELECT 530,'仓储管理','limit_menu_stock',	1 UNION
		SELECT 540,'往来管理','limit_menu_come',	1 UNION
		SELECT 550,'成本费用管理','limit_menu_finance',1 UNION
		SELECT 560,'总账管理','limit_menu_ac',		1 UNION
		SELECT 56041,'出纳管理','limit_menu_te',	1 UNION
		SELECT 561,'固定资产管理','limit_menu_fixe',1 UNION
		SELECT 570,'会员管理','limit_menu_vip',	1 UNION
		SELECT 580,'维修管理','limit_menu_repair',1 UNION
		SELECT 620,'决策支持','limit_menu_mgr',	1 UNION
		SELECT 1700,'更多应用','limit_menu_crm',	1
	END
GO
--2017-03-02 
IF NOT EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig WHERE MenuID=590)
	BEGIN
		INSERT INTO MenuTemplateConfig(MenuID,Caption,Name,IsChecked)
		SELECT 590,'单据中心','limit_menu_bill',1 UNION
		SELECT 600,'基础资料','limit_menu_baseinfo',1 UNION
		SELECT 610,'系统管理','limit_menu_system',1
	END
GO
--===============================================默认值【END】============================================



/****** 对象:  Table [dbo].[MoneyBill]    脚本日期: 05/05/2010 14:48:06 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[MoneyBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[MoneyBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[NTotal] [numeric](18, 4) DEFAULT(0),
		[DTypeId] VARCHAR(50) NOT NULL DEFAULT(''), --部分
		[ETypeId] VARCHAR(50) NOT NULL DEFAULT('') --经手人
		,ShowOrder INT DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'MoneyBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.MoneyBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'MoneyBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.MoneyBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoneyBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.MoneyBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.MoneyBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoneyBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE MoneyBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE MoneyBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoneyBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE MoneyBill ADD [NTotal] NUMERIC(18,4) DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoneyBill' AND a.Name='DTypeId'
)
BEGIN
		ALTER TABLE MoneyBill ADD [DTypeId] VARCHAR(50) NOT NULL DEFAULT('') --经手人
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoneyBill' AND a.Name='ETypeId'
)
BEGIN
		ALTER TABLE MoneyBill ADD [ETypeId] VARCHAR(50) NOT NULL DEFAULT('') --经手人
END
GO	

--商品品牌
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoneyBill' AND a.Name='BrandarTypeId'
)
BEGIN
		ALTER TABLE MoneyBill 
			ADD [BrandarTypeId] VARCHAR(50) NOT NULL DEFAULT('') --商品品牌
END
GO

--网店加个字段，关联明细
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoneyBill' AND a.Name='mid'
)
BEGIN
		ALTER TABLE MoneyBill ADD mid INT NULL DEFAULT(0)
END
GO	


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CID';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='MoneyBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

-- 清除字段UseDTypeId
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'UseDTypeId';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='MoneyBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.all_columns b
	LEFT JOIN sys.default_constraints a ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MONEYBILL') AND name = 'CIX_MONEYBILL_BillNumberID')
--DROP INDEX CIX_MONEYBILL_BillNumberID ON MONEYBILL 
CREATE CLUSTERED INDEX CIX_MONEYBILL_BillNumberID ON MONEYBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MONEYBILL') AND name = 'NCIX_MONEYBILL_Atypeid')
--DROP INDEX NCIX_MONEYBILL_Atypeid ON MONEYBILL 
CREATE NONCLUSTERED INDEX NCIX_MONEYBILL_Atypeid ON MONEYBILL(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MONEYBILL') AND name = 'NCIX_MONEYBILL_Id')
--DROP INDEX NCIX_MONEYBILL_Id ON MONEYBILL 
CREATE NONCLUSTERED INDEX NCIX_MONEYBILL_Id ON MONEYBILL(Id) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoneyBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoneyBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoneyBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoneyBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END

go                   
------------------------------------------修改字段小数位数区域结束-----------------------------------------------

------------------------------------------表数据更新开始-----------------------------------------------
IF EXISTS(SELECT TOP 1 1 FROM dbo.MoneyBill MB LEFT JOIN BillIndex BI ON MB.BillNumberId=BI.BillNumberId
	WHERE BI.BillType=78 AND ISNULL(MB.DTypeId,'')='')
BEGIN
	UPDATE MB SET MB.DTypeId=BI.DTypeId 
	FROM dbo.MoneyBill MB LEFT JOIN BillIndex BI ON MB.BillNumberId=BI.BillNumberId
	WHERE BI.BillType=78 AND ISNULL(MB.DTypeId,'')=''
END
GO
------------------------------------------表数据更新结束-----------------------------------------------



/****** 对象:  Table [dbo].[MonthATypeHistory]    脚本日期: 05/05/2010 14:48:07 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[MonthATypeHistory]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[MonthATypeHistory](
		[period] [int]  NULL,
		[ATypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Total] [numeric](18, 4)  NULL DEFAULT (0),
		[BqTotal] [numeric](18, 4)  NULL DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[NTotal] [numeric](18, 4)  NULL DEFAULT (0),
		[NBqTotal] [numeric](18, 4)  NULL  DEFAULT (0),
		[CID]	INT NULL,
		[Year]  INT
	) ON [PRIMARY]

END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MonthATypeHistory' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE MonthATypeHistory ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE MonthATypeHistory SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MonthATypeHistory' AND a.Name='NTotal'
)
BEGIN
	ALTER TABLE MonthATypeHistory ADD NTotal numeric(18, 4) NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MonthATypeHistory' AND a.Name='NBqTotal'
)
BEGIN
	ALTER TABLE MonthATypeHistory ADD NBqTotal numeric(18, 4) NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MonthATypeHistory' AND a.Name='CID'
)
BEGIN
	ALTER TABLE MonthATypeHistory ADD CID INT NULL 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MonthATypeHistory',N'U') AND Name='Year')
BEGIN
	ALTER TABLE MonthATypeHistory ADD [Year] INT NULL 
END
GO



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF EXISTS(SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[MonthATypeHistory]') AND name = N'NCIX_MonthATypeHistory_period' )
	DROP INDEX [NCIX_MonthATypeHistory_period] ON MonthATypeHistory
go

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MonthATypeHistory' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MonthATypeHistory 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                      
CREATE NONCLUSTERED INDEX [NCIX_MonthATypeHistory_period]
ON [dbo].[MonthATypeHistory] ([period],[ATypeID],[Stypeid])
INCLUDE (Total)
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
  
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MonthATypeHistory' AND a.Name='BqTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MonthATypeHistory 
	ALTER COLUMN BqTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MonthATypeHistory' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MonthATypeHistory 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MonthATypeHistory' AND a.Name='NBqTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MonthATypeHistory 
	ALTER COLUMN NBqTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[MonthProc]    脚本日期: 05/05/2010 14:48:07 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[MonthProc]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[MonthProc](
		[STypeID] VARCHAR(50),
		[MonthNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[StartDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[period] [int] NULL,
		[Year]    INT,											--年度
		[comment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MonthProc',N'U') AND Name='Year')
BEGIN
	ALTER TABLE dbo.MonthProc
	ADD [Year] INT 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MonthProc',N'U') AND Name='STypeID')
BEGIN
	ALTER TABLE dbo.MonthProc
	ADD STypeID VARCHAR(50)
END
GO

------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[MonthProc]') AND name = N'PK_MonthProc')
ALTER TABLE [dbo].[MonthProc] DROP CONSTRAINT [PK_MonthProc]
GO

IF EXISTS(SELECT 1 FROM SysIndexes WHERE ID=OBJECT_ID(N'MonthProc',N'U') AND Name='IX_MonthrProc_STypeID')
BEGIN
	DROP INDEX dbo.MonthProc.IX_MonthrProc_STypeID
END
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
CREATE  CLUSTERED INDEX IX_MonthrProc_STypeID ON MonthProc(STypeID)
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 


IF NOT EXISTS(SELECT 1 FROM dbo.MonthProc)
BEGIN
	INSERT INTO dbo.MonthProc
	        ( STypeID ,
	          MonthNo ,
	          StartDate ,
	          EndDate ,
	          period ,
	          Year ,
	          comment
	        )
	Select '00000','本期','2010-11-26',NULL,1,2010,''
END

IF EXISTS(SELECT 1 FROM dbo.MonthProc WHERE ISNULL(stypeid,'00000')='00000')
BEGIN
	SELECT * INTO #Month FROM dbo.MonthProc
	TRUNCATE TABLE dbo.MonthProc
	INSERT INTO dbo.MonthProc
	        ( 
			  STypeID,
			  MonthNo ,
	          StartDate ,
	          EndDate ,
	          period ,
	          Year,
	          comment
	        )
	SELECT ISNULL(A.TypeID,''),
		   B.MonthNo,
		   B.StartDate,
		   B.EndDate,
		   B.Period,
		   ISNULL(B.[Year],YEAR(B.StartDate)),
		   B.Comment
	FROM dbo.SType A RIGHT JOIN #Month B ON 1=1 AND A.sonnum=0
	DROP TABLE #Month
END
ELSE
BEGIN
	UPDATE dbo.MonthProc SET Year=YEAR(StartDate) WHERE Year IS NULL
END
GO



/****** 对象:  Table [dbo].[MoveBill]    脚本日期: 05/05/2010 14:48:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[MoveBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_MoveBill_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL,
		[Total] [numeric](18, 4) NULL,
		[Jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBill_Jobnumber]  DEFAULT (0),
		[GoodsNo] [int] NULL CONSTRAINT [DF_MoveBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_MoveBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [varchar](max) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_MoveBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_MoveBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_MoveBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_MoveBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_MoveBill_HandZeroCost]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		UnitID               int             Default(0)  NULL,
		NUnitID              int             Default(0)  NULL,
		NQty                 numeric(22,10)  Default(0)  NULL,
		UnitRate             numeric(22,10)  Default(0)  NULL,
		NUnitMsg             varchar(50)          null,
		MUnitID              int             Default(0)  NULL,
		MQty                 numeric(22,10)  Default(0)  NULL,
		MUnitRate            numeric(22,10)  Default(0)  NULL,
		MUnitMsg             varchar(50)          null,
		MPrice				 numeric(22,10)  Default(0)  NULL,
		InCargoID			 INT			 DEFAULT(0) NULL,
		OutCargoID			 INT			 DEFAULT(0) NULL,
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    AllotID				 INT			 DEFAULT(0)  NULL				--引用的调货申请单明细ID 未引用时为0
	    ,ShowOrder INT DEFAULT(0)
	    ,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
	    ,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
	    ,InFlowQty NUMERIC(24,10) NULL DEFAULT(0) --入库数量
	    ,InFactQty NUMERIC(24,10) NULL DEFAULT(0)
	    ,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.MoveBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.MoveBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.MoveBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.MoveBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.MoveBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.MoveBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.MoveBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.MoveBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE MoveBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE MoveBill SET PickedQty=0 WHERE PickedQty IS NULL
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.MoveBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.MoveBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE MoveBill ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	SELECT @strSql='UPDATE MoveBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	EXEC(@strSql)
END

GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[MoveBill]') and name = 'KTypeId' )
BEGIN	
	ALTER TABLE dbo.MoveBill ADD
		KTypeId varchar(50) NULL
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[MoveBill]') and name = 'KTypeId2' )
BEGIN	
	ALTER TABLE dbo.MoveBill ADD
		KTypeId2 varchar(50) NULL
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='UnitID')
BEGIN
	ALTER TABLE MoveBill ADD UnitID  INT  NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='NUnitID')
BEGIN
	ALTER TABLE MoveBill ADD NUnitID INT NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='NQty')
BEGIN
	ALTER TABLE MoveBill ADD NQty   numeric(22,10)   NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='UnitRate')
BEGIN
	ALTER TABLE MoveBill ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='NUnitMsg')
BEGIN
	ALTER TABLE MoveBill ADD NUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='MUnitID')
BEGIN
	ALTER TABLE MoveBill ADD MUnitID  INT  NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='MQty')
BEGIN
	ALTER TABLE MoveBill ADD MQty   numeric(22,10)  NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='MUnitRate')
BEGIN
	ALTER TABLE MoveBill ADD MUnitRate   numeric(22,10)  NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='MUnitMsg')
BEGIN
	ALTER TABLE MoveBill ADD MUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='MPrice')
BEGIN
	ALTER TABLE MoveBill ADD MPrice   numeric(22,10)  NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='InCargoID')
BEGIN
	ALTER TABLE MoveBill ADD InCargoID INT NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBill' AND a.Name='OutCargoID')
BEGIN
	ALTER TABLE MoveBill ADD OutCargoID INT NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE MoveBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE MoveBill ADD IsCombined   INT
END
GO
--物流运输 已发运数量
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE MoveBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0) 
END
GO
-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal' 
UNION ALL SELECT 'InCargoSpace' UNION ALL SELECT 'OutCargoSpace';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='MoveBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

--修改字段Serial数据类型,text修改为VARCHAR(MAX)
IF NOT EXISTS(
	SELECT TOP 1 1 FROM syscolumns C,systypes T 
	WHERE C.xusertype=T.xusertype AND ID=OBJECT_ID(N'MoveBill',N'U')
	AND C.Name='Serial' AND T.Name='varchar')
	BEGIN		
		DECLARE @Name VARCHAR(100);
		
		SELECT  @Name = name
		FROM    sys.default_constraints
		WHERE   parent_object_id = OBJECT_ID(N'MoveBill',N'U')
				AND parent_column_id = COLUMNPROPERTY(OBJECT_ID(N'MoveBill',N'U'),'Serial', 'columnid');
				
		IF ( @Name = '')
			BEGIN 
				BEGIN TRANSACTION;
				--PRINT '没有约束，直接更改字段类型';
				ALTER TABLE MoveBill ALTER COLUMN Serial VARCHAR(MAX) NULL;
				IF @@ERROR <> 0
					BEGIN
						ROLLBACK TRANSACTION;
						--PRINT '修改失败'; 
					END;
				ELSE
					BEGIN 
						COMMIT TRANSACTION;
						--PRINT '修改成功';
					END;
			END; 
		ELSE
			BEGIN
				BEGIN TRANSACTION;
				--PRINT '有约束要先删除,再更改字段类型'
				EXEC('ALTER TABLE MoveBill DROP CONSTRAINT '+@Name);
				ALTER TABLE MoveBill ALTER COLUMN Serial VARCHAR(MAX) NULL;
				IF @@ERROR <> 0
					BEGIN
						ROLLBACK TRANSACTION;
					END;
				ELSE
					BEGIN 
						COMMIT TRANSACTION;
					END;
			END;
	END;
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[MoveBill]') AND name = N'CIX_BID')
	DROP INDEX [dbo].MoveBill.CIX_BID
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[MoveBill]') AND name = N'NCIX_PTYPEID')
	DROP INDEX [dbo].MoveBill.NCIX_PTYPEID
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[movebill]') AND name = N'IX_MoveBill_BillNumberID')
	DROP INDEX [dbo].[movebill].IX_MoveBill_BillNumberID
	
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MOVEBILL') AND name = 'CIX_MOVEBILL_BillNumberID')
--DROP INDEX CIX_MOVEBILL_BillNumberID ON MOVEBILL 
CREATE CLUSTERED INDEX CIX_MOVEBILL_BillNumberID ON MOVEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MOVEBILL') AND name = 'NCIX_MOVEBILL_Ptypeid')
--DROP INDEX NCIX_MOVEBILL_Ptypeid ON MOVEBILL 
CREATE NONCLUSTERED INDEX NCIX_MOVEBILL_Ptypeid ON MOVEBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MOVEBILL') AND name = 'NCIX_MOVEBILL_Ktypeid')
--DROP INDEX NCIX_MOVEBILL_Ktypeid ON MOVEBILL 
CREATE NONCLUSTERED INDEX NCIX_MOVEBILL_Ktypeid ON MOVEBILL(Ktypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE	MoveBill 
SET		KTypeId  = B.KTypeId,
		KTypeId2 = B.KTypeId2
FROM	MoveBill M,
		BillIndex B
WHERE	M.BillNumberId = B.BillNumberId 
		AND (ISNULL(M.KTypeId,'') = '' OR ISNULL(M.KTypeId2,'')='')
GO						
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                               
--调货申请单明细ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='AllotID'
)
BEGIN
		ALTER TABLE MoveBill ADD AllotID   INT NULL DEFAULT(0)
END
GO 
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBill' AND a.Name='MPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBill 
	ALTER COLUMN MPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[MoveBjBill]    脚本日期: 05/05/2010 14:48:09 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveBjBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[MoveBjBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_MoveBjBill_Qty]  DEFAULT (0),
		[price] [numeric](18, 4) NULL CONSTRAINT [DF_MoveBjBill_price]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_MoveBjBill_total]  DEFAULT (0),
		[Jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBjBill_Jobnumber]  DEFAULT (0),
		[GoodsNo] [int] NULL CONSTRAINT [DF_MoveBjBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_MoveBjBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBjBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_MoveBjBill_InputCostPrice_1]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_MoveBjBill_GoodsOrder_1]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBjBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBjBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBjBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_MoveBjBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_MoveBjBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_MoveBjBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_MoveBjBill_HandZeroCost]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		UnitID               int             Default(0)  NULL,
		NUnitID              int             Default(0)  NULL,
		NQty                 numeric(22,10)  Default(0)  NULL,
		UnitRate             numeric(22,10)  Default(0)  NULL,
		NUnitMsg             varchar(50)          null,
		MUnitID              int             Default(0)  NULL,
		MQty                 numeric(22,10)  Default(0)  NULL,
		MUnitRate            numeric(22,10)  Default(0)  NULL,
		MUnitMsg             varchar(50)          null,
		MPrice				 numeric(22,10)  Default(0)  NULL,
		InCargoID			 INT			 DEFAULT(0) NULL,
		OutCargoID			 INT			 DEFAULT(0) NULL,
		ItemID               bigint               null,
		IsCombined           int                  NULL,
		AllotID				 INT			 DEFAULT(0) NULL		--引用的调货申请单明细ID 未引用时为0
		,ShowOrder INT DEFAULT(0)
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
		,InflowQty NUMERIC(24,10) NULL DEFAULT(0) --入库数量
		,InFactQty NUMERIC(24,10) NULL DEFAULT(0)
		,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBjBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.MoveBjBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBjBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.MoveBjBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBjBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.MoveBjBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.MoveBjBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBjBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.MoveBjBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.MoveBjBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBjBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.MoveBjBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.MoveBjBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBjBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE MoveBjBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE MoveBjBill SET PickedQty=0 WHERE PickedQty IS NULL
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveBjBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.MoveBjBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.MoveBjBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE MoveBjBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE MoveBjBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='UnitID')
BEGIN
	ALTER TABLE MoveBjBill ADD UnitID  INT   NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='NUnitID')
BEGIN
	ALTER TABLE MoveBjBill ADD NUnitID INT   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='NQty')
BEGIN
	ALTER TABLE MoveBjBill ADD NQty   numeric(22,10)   NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='UnitRate')
BEGIN
	ALTER TABLE MoveBjBill ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='NUnitMsg')
BEGIN
	ALTER TABLE MoveBjBill ADD NUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='MUnitID')
BEGIN
	ALTER TABLE MoveBjBill ADD MUnitID  INT  NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='MQty')
BEGIN
	ALTER TABLE MoveBjBill ADD MQty   numeric(22,10)  NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='MUnitRate')
BEGIN
	ALTER TABLE MoveBjBill ADD MUnitRate   numeric(22,10)  NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='MUnitMsg')
BEGIN
	ALTER TABLE MoveBjBill ADD MUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='MPrice')
BEGIN
	ALTER TABLE MoveBjBill ADD MPrice   numeric(22,10)   NULL  DEFAULT(0)
END


IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='InCargoID')
BEGIN
	ALTER TABLE MoveBjBill ADD InCargoID INT NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='MoveBjBill' AND a.Name='OutCargoID')
BEGIN
	ALTER TABLE MoveBjBill ADD OutCargoID INT NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE MoveBjBill ADD ItemID  BIGINT
END
GO

--调货申请单明细ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='AllotID'
)
BEGIN
		ALTER TABLE MoveBjBill ADD AllotID   INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE MoveBjBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE MoveBjBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[MoveBjBill]') and name = 'KTypeId' )
BEGIN	
	ALTER TABLE dbo.MoveBjBill ADD
		KTypeId varchar(50) NULL
		
	
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[MoveBjBill]') and name = 'KTypeId2' )
BEGIN	
	ALTER TABLE dbo.MoveBjBill ADD
		KTypeId2 varchar(50) NULL
		
	EXEC('UPDATE MoveBjBill SET KTypeID=b.KTypeID,KTypeID2=b.KTypeID2 
	FROM BillIndex b
	WHERE MoveBjBill.BillNumberID=b.BillNumberID
	AND MoveBjBill.KTypeID IS NULL
	')
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('MoveBjBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table MoveBjBill drop constraint '+@dfname);
		
	ALTER TABLE MoveBjBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE MoveBjBill ADD CONSTRAINT DF_MoveBjBill_Serial DEFAULT('') FOR Serial
END
GO
-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'InCargoSpace' UNION ALL SELECT 'OutCargoSpace';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='MoveBjBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MOVEBJBILL') AND name = 'CIX_MOVEBJBILL_BillNumberID')
--DROP INDEX CIX_MOVEBJBILL_BillNumberID ON MOVEBJBILL 
CREATE CLUSTERED INDEX CIX_MOVEBJBILL_BillNumberID ON MOVEBJBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MOVEBJBILL') AND name = 'NCIX_MOVEBJBILL_Ptypeid')
--DROP INDEX NCIX_MOVEBJBILL_Ptypeid ON MOVEBJBILL 
CREATE NONCLUSTERED INDEX NCIX_MOVEBJBILL_Ptypeid ON MOVEBJBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('MOVEBJBILL') AND name = 'NCIX_MOVEBJBILL_Ktypeid')
--DROP INDEX NCIX_MOVEBJBILL_Ktypeid ON MOVEBJBILL 
CREATE NONCLUSTERED INDEX NCIX_MOVEBJBILL_Ktypeid ON MOVEBJBILL(Ktypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveBjBill' AND a.Name='MPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveBjBill 
	ALTER COLUMN MPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[MoveMoneyBill]    脚本日期: 05/05/2010 14:48:10 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveMoneyBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[MoveMoneyBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_MoveMoneyBill_total]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ntotal] [numeric](18,4) DEFAULT(0)
		,ShowOrder INT DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'MoveMoneyBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.MoveMoneyBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'MoveMoneyBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.MoveMoneyBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveMoneyBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE MoveMoneyBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE MoveMoneyBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveMoneyBill' AND a.Name='ntotal'
)
BEGIN
		ALTER TABLE MoveMoneyBill ADD ntotal NUMERIC(18,4) DEFAULT(0)
END

GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'MoveMoneyBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.MoveMoneyBill 
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.MoveMoneyBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveMoneyBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveMoneyBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MoveMoneyBill' AND a.Name='ntotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE MoveMoneyBill 
	ALTER COLUMN ntotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Msg_MessageList]    脚本日期: 05/05/2010 14:48:11 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Msg_MessageList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Msg_MessageList](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[MessageDate] [datetime] NULL,
		[Comment] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
		[SendEmployeeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[SendEmployeeName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[GetEmployeeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[GetEmployeeName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IsRead] [bit] NOT NULL CONSTRAINT [DF_Msg_MessageList_IsRead]  DEFAULT (0),
		[IsSendDelete] [bit] NOT NULL CONSTRAINT [DF_Msg_MessageList_IsSendDelete]  DEFAULT (0),
		[IsGetDelete] [bit] NOT NULL CONSTRAINT [DF_Msg_MessageList_IsGetDelete]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Msg_Online]    脚本日期: 05/05/2010 14:48:12 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Msg_Online]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Msg_Online](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ConnectID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LatestConnectTime] [datetime] NULL,
		[LoginTime] [datetime] NULL,
		[UserName] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[Unit] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[IP] [varchar](15) COLLATE Chinese_PRC_CI_AS NULL,
		[State] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[news]    脚本日期: 05/05/2010 14:48:13 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[news]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[news](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[nCatalogID] [int] NULL,
		[strTitle] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[strContent] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[strDateTime] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[strAuthor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[nClickNumber] [int] NOT NULL CONSTRAINT [DF_news_nClickNumber]  DEFAULT (0),
		[nAuthorID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IsDocking] [bit] NOT NULL CONSTRAINT [DF__news__IsDocking__6F370936]  DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='news' AND a.Name='strContent' and a.xtype=35
)
BEGIN
	ALTER TABLE news ALTER COLUMN strContent VARCHAR(MAX)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[news]') AND name = N'IX_news')
DROP INDEX [dbo].[news].[IX_news]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('NEWS') AND name = 'NCIX_NEWS_ID')
--DROP INDEX NCIX_NEWS_ID ON NEWS 
CREATE NONCLUSTERED INDEX NCIX_NEWS_ID ON NEWS(ID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[news_catalog]    脚本日期: 05/05/2010 14:48:13 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[news_catalog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[news_catalog](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ShowOrder] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'NotePad') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[NotePad]
	(
	[typeID] [varchar](100) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CreateTime] [datetime] NOT NULL,
	[AlertTime] [datetime] NULL,
	[Content] [varchar](max) NOT NULL,
	[Flag] [int] NULL,						--0表示待处理，1表示完成	
	[UserId] [varchar](100) NOT NULL,
	[Importance] [int] NULL,				--0=重要
	[ScanTimes] [int] NULL					--从提醒框打开的记事次数
	) 
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='NotePad' AND a.Name='ScanTimes')
BEGIN
	ALTER TABLE NotePad 
		ADD ScanTimes [int] NULL DEFAULT(0) 
END
GO

ALTER TABLE NotePad
	ALTER COLUMN UserId VARCHAR(100) NOT NULL

UPDATE NotePad SET ScanTimes = 0 WHERE ScanTimes IS NULL
GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[numberconfig]    脚本日期: 05/05/2010 14:48:14 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[numberconfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[numberconfig](
		[typename] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[digits] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[numberformat] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]

	--增加XiWa平台的小数位数预制数据
	DELETE FROM NumberConfig
	INSERT INTO NumberConfig(typename,digits,numberformat)VALUES('整数','0','0')
	INSERT INTO NumberConfig(typename,digits,numberformat)VALUES('qty','4','0')
	INSERT INTO NumberConfig(typename,digits,numberformat)VALUES('price','4','1')
	INSERT INTO NumberConfig(typename,digits,numberformat)VALUES('total','2','1')
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[nVipAddMoney]    脚本日期: 05/05/2010 14:48:15 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[nVipAddMoney]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[nVipAddMoney](
		[nID] [int] IDENTITY(1,1) NOT NULL,
		[CardId] INT NOT NULL,
		[BillDate] [datetime] NULL,
		[ETypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[aMoney] [numeric](18, 2) NULL,
		[ATypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Checke] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipAddMoney]') and name = 'TotalInMoney' )
BEGIN
	ALTER TABLE dbo.nVipAddMoney ADD
		TotalInMoney [numeric](18, 2) NULL
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipAddMoney]') and name = 'PreferenceMoney' )
BEGIN
	ALTER TABLE dbo.nVipAddMoney ADD
		PreferenceMoney [numeric](18, 2) NULL
END

GO

if exists (select * from syscolumns where id = object_id(N'[dbo].[nVipAddMoney]') and  name = 'CardId' and length=50)
BEGIN
     ALTER TABLE nVipAddMoney
	    ALTER COLUMN CardId INT NOT NULL
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipAddMoney' AND a.Name='aMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipAddMoney 
	ALTER COLUMN aMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipAddMoney' AND a.Name='TotalInMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipAddMoney 
	ALTER COLUMN TotalInMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipAddMoney' AND a.Name='PreferenceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipAddMoney 
	ALTER COLUMN PreferenceMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[nVipAdjust]    脚本日期: 05/05/2010 14:48:16 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipAdjust]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipAdjust](
		[BillNumberId] [numeric](18, 0) NOT NULL,
		[BillDate] [datetime] NULL,
		[BillCode] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeId] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Checke] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[VipNo] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[UpCost] [numeric](18, 2) NULL,
		[DownCost] [numeric](18, 2) NULL,
		[SumCost] [numeric](18, 2) NULL,
		[Reason] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
		[IsSend] [int] NULL,
		[nType] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipAdjust' AND a.Name='UpCost' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipAdjust 
	ALTER COLUMN UpCost NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipAdjust' AND a.Name='DownCost' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipAdjust 
	ALTER COLUMN DownCost NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipAdjust' AND a.Name='SumCost' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipAdjust 
	ALTER COLUMN SumCost NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[nVipCardSet]    脚本日期: 05/05/2010 14:48:17 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipCardSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipCardSet](
		[VipCardTypeID] [int] IDENTITY(1,1) NOT NULL,
		[TypeName] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[DiscountType] [char](1) COLLATE Chinese_PRC_CI_AS NULL ,
		[ifJF] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[deleted] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('0'),
		[Comment] [varchar](600) COLLATE Chinese_PRC_CI_AS NULL,
		[VipCardnum] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

if exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'Comment' )
BEGIN
	ALTER TABLE dbo.nVipCardSet ALTER
	COLUMN Comment varchar(600) COLLATE Chinese_PRC_CI_AS NULL
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'ValidDate' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD ValidDate INT NULL DEFAULT(1)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'ValidType' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD ValidType INT NULL DEFAULT(0)
END
IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'CardTypeDiscount' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD CardTypeDiscount DECIMAL(11,10) NULL DEFAULT(NULL)
END
if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'jfgz' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD jfgz INT NULL DEFAULT(99999)
END
IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'GiveCent' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD GiveCent DECIMAL(10,0) NULL DEFAULT(0)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'TypeLevel' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD TypeLevel INT NULL DEFAULT(0)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'StandardCent' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD StandardCent DECIMAL(10,0) NULL DEFAULT(0)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'DeductCent' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD DeductCent DECIMAL(10,0) NULL DEFAULT(0)
END
--
IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'IfBirthDay' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD IfBirthDay   VARCHAR(10) NOT NULL DEFAULT(1)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'BirthDayMultiple' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD BirthDayMultiple   VARCHAR(10)  NULL DEFAULT(null)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'IfDate' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD IfDate   VARCHAR(10) NOT NULL DEFAULT(1)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'DateMultiple' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD DateMultiple   VARCHAR(10)  NULL DEFAULT(null)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'StartDate' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD StartDate   VARCHAR(50) NULL DEFAULT(NULL)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'EndDate' )
BEGIN
	ALTER TABLE dbo.nVipCardSet 
	ADD EndDate   VARCHAR(50) NULL DEFAULT(NULL)
END

IF exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'DiscountType' AND [length] = 1)
BEGIN
	ALTER TABLE dbo.nVipCardSet ALTER COLUMN DiscountType CHAR(10)
END

IF NOT exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSet]') and name = 'IfSalesIntegral' )
BEGIN
	ALTER TABLE dbo.nVipCardSet ADD  IfSalesIntegral INT
END
--积分付款 xxx积分兑换一元人民币
IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[nVipCardSet]') AND name = 'CentToMoney' )
BEGIN
	ALTER TABLE dbo.nVipCardSet ADD  CentToMoney INT NOT NULL DEFAULT(0)
END
-----删除表列


GO

UPDATE dbo.nVipCardSet SET ValidDate=1 WHERE ValidDate IS NULL
UPDATE dbo.nVipCardSet SET ValidType=0 WHERE ValidType IS NULL
--UPDATE dbo.nVipCardSet SET CardTypeDiscount=1 WHERE CardTypeDiscount IS NULL
UPDATE dbo.nVipCardSet SET jfgz=99999 WHERE jfgz IS NULL
UPDATE dbo.nVipCardSet SET GiveCent=0 WHERE GiveCent IS NULL
UPDATE dbo.nVipCardSet SET TypeLevel=0 WHERE TypeLevel IS NULL
UPDATE dbo.nVipCardSet SET StandardCent=0 WHERE StandardCent IS NULL
UPDATE dbo.nVipCardSet SET DeductCent=0 WHERE DeductCent IS NULL
UPDATE dbo.nVipCardSet SET IfSalesIntegral=0 WHERE IfSalesIntegral IS NULL
go
------------------------------------------表修改区域结束-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSet' AND a.Name='CardTypeDiscount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	
	ALTER TABLE dbo.nVipCardSet 
	ALTER COLUMN CardTypeDiscount DECIMAL(11,10) --NULL --DEFAULT(NULL)
END

------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--积分类型-积分转储值设置表
IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('nVipCardSet_IntegralExchange') AND type = 'U')
BEGIN
	CREATE TABLE nVipCardSet_IntegralExchange (
	   NId                  INT                 IDENTITY(1,1),
	   VipCardTypeID		INT					NOT NULL,
	   JFCent				NUMERIC(24,10)		NOT NULL DEFAULT(0),
	   JFMoney              NUMERIC(24,10)		NOT NULL DEFAULT(0)
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='nVipCardSet_IntegralExchange' AND a.Name='BankType'
--)
--BEGIN
--	ALTER TABLE nVipCardSet_IntegralExchange 
--		ADD BankType VARCHAR(400) NULL DEFAULT('')
--END

--GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('nVipCardSet_IntegralExchange') AND name = 'CIX_nVipCardSet_IntegralExchange_Nid')
	CREATE CLUSTERED INDEX CIX_nVipCardSet_IntegralExchange_Nid ON nVipCardSet_IntegralExchange(NId) 
GO
------------------------------------------创建索引区域结束-----------------------------------------------

GO
 





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[NVipCardSetLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	--修改日期和时间、操作员、卡类型、勾选项的变化（取消或勾选）
	CREATE TABLE NVipCardSetLog
	(
	 iD INT IDENTITY(1,1) NOT NULL,
	 updateTime DATETIME,
	 etypeid VARCHAR(50),
	 VipCardTypeID  INT,
	 ChangeType INT, --勾选变化（0为取消，1为勾选）
	 comment VARCHAR(200)--备注
	 )
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
 
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[nVipCardSign]    脚本日期: 05/05/2010 14:48:18 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipCardSign]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipCardSign](
		[VipCardID] [int] IDENTITY(1,1) NOT NULL,
		[VipCardCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[VipCardTypeID] [int] NOT NULL,
		[Bname] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[Bsex] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[Bbirthday] [datetime] NULL,
		[Btel] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Baddr] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Bpostcode] [varchar](6) COLLATE Chinese_PRC_CI_AS NULL,
		[Btrade] [varchar](12) COLLATE Chinese_PRC_CI_AS NULL,
		[BIDcard] [varchar](26) COLLATE Chinese_PRC_CI_AS NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[CreateDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[deleted] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('0'),
		[BeginMoney] [numeric](18, 2) NULL DEFAULT (0),
		[BeginCent] [numeric](18, 2) NULL DEFAULT (0),
		[totalMoney] [numeric](18, 2) NULL DEFAULT (0),
		[totalCent] [numeric](18, 2) NULL DEFAULT (0),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[qCczMoney] [numeric](18, 2) NULL CONSTRAINT [DF_nVipCardSign_qCczMoney]  DEFAULT ('0'),
		[lJczMoney] [numeric](18, 2) NULL CONSTRAINT [DF_nVipCardSign_lJczMoney]  DEFAULT ('0'),
		[xFczMoney] [numeric](18, 2) NULL CONSTRAINT [DF_nVipCardSign_xFczMoney]  DEFAULT ('0'),
		[cZyeMoney] [numeric](18, 2) NULL CONSTRAINT [DF_nVipCardSign_cZyeMoney]  DEFAULT ('0'),
		[IsCz] [varchar](2) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_nVipCardSign_IsCz]  DEFAULT ('0'),
		[pWord] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_nVipCardSign_pWord]  DEFAULT (''),
		[jkStypeId] VARCHAR(50) NOT NULL DEFAULT('00001'),  --建卡机构
		[isApplyAllStype]	INT NOT NULL DEFAULT(1),	--适用所有分支机构 1是 0否
		[isApplyAllPOS]		INT NOT NULL DEFAULT(1)		--适用所有门店		1是 0否
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

/**********汽配专用字段开始********/
if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and name = 'RATypeID' )
BEGIN
	ALTER TABLE dbo.nVipCardSign ADD
		RATypeID VARCHAR(50) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and name = 'BTypeID' )
BEGIN
	ALTER TABLE dbo.nVipCardSign ADD
		BTypeID VARCHAR(50) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and name = 'CarType' )
BEGIN
	ALTER TABLE dbo.nVipCardSign ADD
		CarType INT NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and name = 'CarWashPrice' )
BEGIN
	ALTER TABLE dbo.nVipCardSign ADD
		CarWashPrice numeric(18, 4) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and name = 'IsWashTimes' )
BEGIN
	ALTER TABLE dbo.nVipCardSign ADD
		IsWashTimes CHAR(1) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and name = 'CanWashTimes00' )
BEGIN
	ALTER TABLE dbo.nVipCardSign ADD
		CanWashTimes00 INT NULL
END
GO
UPDATE nVipCardSign SET CanWashTimes00=0 WHERE CanWashTimes00 IS NULL

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and name = 'CanWashTimes' )
BEGIN
	ALTER TABLE dbo.nVipCardSign ADD
		CanWashTimes INT NULL
END
GO
UPDATE nVipCardSign SET CanWashTimes=0 WHERE CanWashTimes IS NULL

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and name = 'CanWashTimesTotal' )
BEGIN
	ALTER TABLE dbo.nVipCardSign ADD
		CanWashTimesTotal INT NULL DEFAULT(0)
END
GO
UPDATE nVipCardSign SET CanWashTimesTotal=0 WHERE CanWashTimesTotal IS NULL

if exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and  name = 'Btel' and length=20)
BEGIN
     ALTER TABLE nVipCardSign
	    ALTER COLUMN Btel varchar(50) 
END
GO

if exists (select name from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and  name = 'Baddr' and length=36)
BEGIN
     ALTER TABLE nVipCardSign
	    ALTER COLUMN Baddr varchar(50) 
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='nVipCardSign' AND a.Name='PyCode')
BEGIN
	ALTER TABLE nVipCardSign ADD PyCode VARCHAR(300) DEFAULT '' NULL	
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and  name = 'BPostCode' AND length=200)
BEGIN
     ALTER TABLE nVipCardSign
	    ALTER COLUMN BPostCode varchar(200) 
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[nVipCardSign]') and  name = 'dbgudid')
BEGIN
     ALTER TABLE nVipCardSign
	    ADD dbgudid varchar(100) NULL DEFAULT(NEWID())
END
GO
UPDATE nVipCardSign SET dbgudid = NEWID() WHERE dbgudid IS NULL
/**********汽配专用字段结束********/
GO

--建卡机构
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='nVipCardSign' AND a.Name='jkStypeId')
BEGIN
	ALTER TABLE nVipCardSign ADD jkStypeId VARCHAR(50) NOT NULL DEFAULT('00001')
END
GO

--适用所有分支机构 1是 0否
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='nVipCardSign' AND a.Name='isApplyAllStype')
BEGIN
	ALTER TABLE nVipCardSign ADD isApplyAllStype INT NOT NULL DEFAULT(1)
END
GO

--适用所有门店		1是 0否
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='nVipCardSign' AND a.Name='isApplyAllPOS')
BEGIN
	ALTER TABLE nVipCardSign ADD isApplyAllPOS INT NOT NULL DEFAULT(1)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('nVipCardSign') AND name = 'CIX_nVipCardSign_VipCardID')
CREATE CLUSTERED INDEX CIX_nVipCardSign_VipCardID ON nVipCardSign(VipCardID) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='BeginMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN BeginMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='BeginCent' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN BeginCent NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='totalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN totalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='totalCent' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN totalCent NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='qCczMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN qCczMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='lJczMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN lJczMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='xFczMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN xFczMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='cZyeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN cZyeMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='CarWashPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipCardSign 
	ALTER COLUMN CarWashPrice NUMERIC(24,10)
    END   
 
 --生日短息发送日期                                       
 IF NOT EXISTS(
		SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='nVipCardSign' AND a.Name='sendsmsbirthday'
    )
    BEGIN
		ALTER TABLE nVipCardSign 
			ADD sendsmsbirthday VARCHAR(20) NULL DEFAULT('')
    END 
GO
UPDATE nVipCardSign SET sendsmsbirthday = '' WHERE sendsmsbirthday IS NULL    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipCardSignStype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipCardSignStype](
		[VipCardID] [int]  NOT NULL,
		StypeId	VARCHAR(50) NOT NULL,
		[qCczMoney] [numeric](24, 10) NULL   DEFAULT ('0'),			--期初储值金额
		[lJczMoney] [numeric](24, 10) NULL   DEFAULT ('0'),			--累计储值金额
		[lJxFczMoney] [numeric](24, 10) NULL   DEFAULT ('0'),		--累计消费储值金额
		[bNczMoney] [numeric](24, 10) NULL   DEFAULT ('0'),         --本年储值金额
		[bNxFczMoney] [numeric](24, 10) NULL   DEFAULT ('0'),		--本年消费储值金额
		[cZyeMoney] [numeric](24, 10) NULL   DEFAULT ('0'),			--储值余额
		[lJxFMoney] [numeric](24, 10) NULL   DEFAULT ('0'),			--累计消费金额
		[bNxFMoney] [numeric](24, 10) NULL   DEFAULT ('0')			--本年消费金额
	) 


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO 



/****** 对象:  Table [dbo].[nVipCardSign]    脚本日期: 05/05/2010 14:48:18 ******/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipCardTypeChange]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipCardTypeChange](
		[VipCardID] [int] NOT NULL,
		[OldVipCardTypeID] [int] NOT NULL,
		[NewVipCardTypeID] [int] NOT NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ChangeDate] [datetime] NULL,
		[Comment] VARCHAR(200) NULL,
		[OperatStyle] INT NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(select name from syscolumns where id = object_id(N'[dbo].[nVipCardTypeChange]') and name = 'Comment')
	BEGIN
		ALTER TABLE dbo.nVipCardTypeChange ADD [Comment] VARCHAR(200) NULL
	END
GO

IF NOT EXISTS(select name from syscolumns where id = object_id(N'[dbo].[nVipCardTypeChange]') and name = 'OperatStyle')
	BEGIN
		ALTER TABLE dbo.nVipCardTypeChange ADD [OperatStyle] INT NULL DEFAULT(0)
	END
GO

UPDATE dbo.nVipCardTypeChange SET OperatStyle=0 WHERE OperatStyle IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipConfiscateConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipConfiscateConfig](
		[OperatorID] VARCHAR(50) NULL DEFAULT(''),
		[ETypeID] VARCHAR(50) NULL DEFAULT(''),
		[DTypeID] VARCHAR(50) NULL DEFAULT(''),
		[STypeID] VARCHAR(50) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[nVipGoodsSign]    脚本日期: 05/05/2010 14:48:19 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipGoodsSign]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipGoodsSign](
		[VipGoodsSignID] [int] IDENTITY(1,1) NOT NULL,
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[VipDiscount1] [numeric](18, 4) NULL,
		[VipDiscount2] [numeric](18, 4) NULL,
		[VipDiscount3] [numeric](18, 4) NULL,
		[VipDiscount4] [numeric](18, 4) NULL,
		[VipPrice] [numeric](18, 4) NULL, -- 升级时处理到[VipPrice1]中
		[JFid] [int] NOT NULL DEFAULT (0),
		[VipPrice1] [numeric](18, 4) NULL,
		[VipPrice2] [numeric](18, 4) NULL,
		[VipPrice3] [numeric](18, 4) NULL,
		[VipPrice4] [numeric](18, 4) NULL,
		[VipPrice5] [numeric](18, 4) NULL,
		UnitID  INT  NOT NULL DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipGoodsSign]') and name = 'VipPrice1' )
BEGIN
ALTER TABLE nVipGoodsSign ADD VipPrice1 [numeric](18, 4) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipGoodsSign]') and name = 'VipPrice2' )
BEGIN
ALTER TABLE nVipGoodsSign ADD VipPrice2 [numeric](18, 4) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipGoodsSign]') and name = 'VipPrice3' )
BEGIN
ALTER TABLE nVipGoodsSign ADD VipPrice3 [numeric](18, 4) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipGoodsSign]') and name = 'VipPrice4' )
BEGIN
ALTER TABLE nVipGoodsSign ADD VipPrice4 [numeric](18, 4) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[nVipGoodsSign]') and name = 'VipPrice5' )
BEGIN
ALTER TABLE nVipGoodsSign ADD VipPrice5 [numeric](18, 4) NULL
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'[dbo].[nVipGoodsSign]') AND Name='UnitID')
BEGIN
	ALTER TABLE dbo.nVipGoodsSign
	ADD UnitID  INT  NOT NULL DEFAULT(0)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipDiscount1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipDiscount1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipDiscount2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipDiscount2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipDiscount3' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipDiscount3 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipDiscount4' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipDiscount4 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipPrice1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipPrice1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipPrice2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipPrice2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipPrice3' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipPrice3 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipPrice4' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipPrice4 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipGoodsSign' AND a.Name='VipPrice5' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipGoodsSign 
	ALTER COLUMN VipPrice5 NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 


------------------------------------------升级表数据开始-----------------------------------------------
if exists(select top 1 1 from nVipGoodsSign where isnull(UnitID,0)=0 )
begin
	update nVipGoodsSign 
	set UnitID=p.baseunitid
	from nVipGoodsSign n inner join ptype p on p.typeid=n.ptypeid
end
go

------------------------------------------升级表数据结束-----------------------------------------------





/****** 对象:  Table [dbo].[nVipJfRule]    脚本日期: 05/05/2010 14:48:19 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipJfRule]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipJfRule](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Explain] [varchar](1024) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[nVipJfSet]    脚本日期: 05/05/2010 14:48:20 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipJfSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipJfSet](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Total] [numeric](18, 2) NULL,
		[Jf] [numeric](18, 0) NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
/*
  作者:佘海源
  时间：2012.3.27
  描述：新增字段 TimeValue(有效期限)，用于记录时间有效期
*/


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipJfSet' AND a.Name='TimeValue'  
)
BEGIN
	ALTER TABLE nVipJfSet ADD TimeValue datetime  NULL	
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipJfSet' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE nVipJfSet 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[nVipWashCarTimesConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[nVipWashCarTimesConfig](
		[OperatorID] VARCHAR(50) NULL DEFAULT(''),
		[ETypeID] VARCHAR(50) NULL DEFAULT(''),
		[DTypeID] VARCHAR(50) NULL DEFAULT(''),
		[STypeID] VARCHAR(50) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_ASP_Dispatch]    脚本日期: 05/05/2010 14:48:21 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_ASP_Dispatch]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_ASP_Dispatch](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[AgentName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[AgentBTypeID] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[AgentVirtualPath] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_Attachment]    脚本日期: 05/05/2010 14:48:22 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_Attachment]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_Attachment](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[FatherID] [int] NULL,
		[Type] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[CreateDate] [datetime] NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[FileName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[ContentType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[FileSize] [int] NULL,
		[BinaryData] [image] NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_Attachment]') AND name = N'IX_OA_Attachment')
DROP INDEX  [dbo].[OA_Attachment].[IX_OA_Attachment]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_ATTACHMENT') AND name = 'CIX_OA_ATTACHMENT_ID')
--DROP INDEX CIX_OA_ATTACHMENT_ID ON OA_ATTACHMENT 
CREATE CLUSTERED INDEX CIX_OA_ATTACHMENT_ID ON OA_ATTACHMENT(ID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_Catalog]    脚本日期: 05/05/2010 14:48:23 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_Catalog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_Catalog](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ParentID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[SonNumber] [int] NULL,
		[SonCounter] [int] NULL,
		[SortOrder] [int] NULL,
		[Name] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
		[Description] [varchar](400) COLLATE Chinese_PRC_CI_AS NULL,
		[FontColor] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_OA_Catalog_FontColor]  DEFAULT ('#834e1f'),
		[ImgFileName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_OA_Catalog_ImgFileName]  DEFAULT ('1.png'),
		[Expand] [int] NOT NULL DEFAULT (1),
		[IsFlowCheck] [int] NOT NULL DEFAULT (0),
		[IsCascadeCheck] [int] NOT NULL DEFAULT (0),
		[ClickNumber] [int] NOT NULL DEFAULT (0),
		[SplitBanner] [int] NOT NULL DEFAULT (0),
		[SplitImg] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]

	-- ********	处理 OA_Catalog	********
	DELETE FROM OA_Catalog
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001','001',9,9,1,'公告',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002','001',2,2,2,'论坛',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001003','001',3,3,4,'个人邮箱',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001003001','001003',2,2,1,'邮箱',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001003001001','001003001',0,0,1,'收件箱',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001003001002','001003001',0,0,2,'发件箱',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001003002','001003',0,0,2,'消息',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001003003','001003',0,0,3,'便笺',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001004','001',1,1,5,'产品资料',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001005','001',2,2,3,'资料',' ','#000000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001001','001001',0,0,1,'内部公告板',' ','#834e1f','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001002','001001',0,0,2,'外部公告板',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001003','001001',0,0,3,'人事调整',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001004','001001',0,0,4,'培训与反馈',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001005','001001',0,0,5,'点名批评',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001006','001001',0,0,6,'会议及预约',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001007','001001',0,0,7,'表扬感谢祝贺',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001008','001001',0,0,8,'企业文化展示',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001001009','001001',0,0,9,'竞争对手情报',' ','#0000ff','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001','001002',8,9,1,'公司论坛',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001001','001002001',0,0,1,'管理建议',' ','#834e1f','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001002','001002001',0,0,2,'客户与服务',' ','#834e1f','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001003','001002001',0,0,3,'开发与技术',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001004','001002001',0,0,4,'市场与销售',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001005','001002001',0,0,5,'机会与信息',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001006','001002001',0,0,6,'业余生活',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001008','001002001',0,0,7,'专题讨论',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002002','001002',2,2,2,'合作伙伴论坛',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002002001','001002002',0,0,1,'生活话题',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002002002','001002002',0,0,2,'营销话题',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001005001','001005',4,4,1,'内部资料',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001005001001','001005001',0,0,1,'公司规章制度',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001005001002','001005001',0,0,2,'反面范例或样板',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001005001003','001005001',0,0,3,'开发部文件',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001005001004','001005001',0,0,4,'市场部文件',' ','#ff0000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001005002','001005',1,1,2,'资料汇集',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001005002001','001005002',0,0,1,'综合或其它',' ','#008000','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001002001009','001002001',0,0,8,'部门主管论坛',' ','#0000ff','1.png',1,0,0,0,0)
	INSERT INTO OA_Catalog([TypeID],[ParentID],[SonNumber],[SonCounter],[SortOrder],[Name],[Description],[FontColor],[ImgFileName],[Expand],[IsFlowCheck],[IsCascadeCheck],[ClickNumber],[SplitBanner]) VALUES('001004001','001004',0,0,1,'公司自产产品',' ','#0000ff','1.png',1,0,0,0,0)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_Catalog]') AND name = N'IX_OA_Catalog')
DROP INDEX [dbo].[OA_Catalog].[IX_OA_Catalog]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_CATALOG') AND name = 'CIX_OA_CATALOG_TypeID_ParentID')
--DROP INDEX CIX_OA_CATALOG_TypeID_ParentID ON OA_CATALOG 
CREATE CLUSTERED INDEX CIX_OA_CATALOG_TypeID_ParentID ON OA_CATALOG(TypeID,ParentID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_IPAddress]    脚本日期: 05/05/2010 14:48:24 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_IPAddress]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_IPAddress](
		[STARTIP] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ENDIP] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[COUNTRY] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LOCAL] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[THANK] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_IPAddress]') AND name = N'IX_OA_IPAddress1008')
DROP INDEX [dbo].[OA_IPAddress].[IX_OA_IPAddress1008]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_IPADDRESS') AND name = 'NCIX_OA_IPADDRESS_STARTIP_ENDIP')
--DROP INDEX NCIX_OA_IPADDRESS_STARTIP_ENDIP ON OA_IPADDRESS 
CREATE NONCLUSTERED INDEX NCIX_OA_IPADDRESS_STARTIP_ENDIP ON OA_IPADDRESS(STARTIP,ENDIP) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_Message]    脚本日期: 05/05/2010 14:48:25 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_Message]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_Message](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[CatalogID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Content] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL,
		[CreateDate] [datetime] NULL,
		[ETypeID_SenderTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID_ReceiverTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[AttachmentID] [int] NOT NULL,
		[IsRead] [int] NOT NULL,
		[Type] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Docking] [int] NOT NULL,
		[SortOrder] [int] NOT NULL,
		[MessageType] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[InviteURL] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_Message]') AND name = N'IX_OA_Message')
DROP INDEX [dbo].[OA_Message].[IX_OA_Message]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_MESSAGE') AND name = 'CIX_OA_MESSAGE_ID_ETypeID_CreatorTypeID')
--DROP INDEX CIX_OA_MESSAGE_ID_ETypeID_CreatorTypeID ON OA_MESSAGE 
CREATE CLUSTERED INDEX CIX_OA_MESSAGE_ID_ETypeID_CreatorTypeID ON OA_MESSAGE(ID,ETypeID_CreatorTypeID) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_Message_Bak]    脚本日期: 05/05/2010 14:48:26 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_Message_Bak]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_Message_Bak](
		[ID] [int] NOT NULL,
		[CatalogID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Content] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[CreateDate] [datetime] NULL,
		[ETypeID_SenderTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID_ReceiverTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[AttachmentID] [int] NOT NULL CONSTRAINT [DF_OA_Message_Bak_AttachmentID]  DEFAULT (0),
		[IsRead] [int] NOT NULL CONSTRAINT [DF_OA_Message_Bak_IsRead]  DEFAULT (0),
		[Type] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Docking] [int] NOT NULL CONSTRAINT [DF_OA_Message_Bak_Docking]  DEFAULT (0),
		[SortOrder] [int] NOT NULL CONSTRAINT [DF_OA_Message_Bak_SortOrder]  DEFAULT (0),
		[MessageType] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_OA_Message_Bak_MessageType]  DEFAULT ('Normal'),
		[InviteURL] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_Message_Bak]') AND name = N'IX_OA_Message_Bak')
DROP INDEX [dbo].[OA_Message_Bak].[IX_OA_Message_Bak]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_MESSAGE_BAK') AND name = 'NCIX_OA_MESSAGE_BAK_ETypeID_ReceiverTypeID_CreateDate')
--DROP INDEX NCIX_OA_MESSAGE_BAK_ETypeID_ReceiverTypeID_CreateDate ON OA_MESSAGE_BAK 
CREATE NONCLUSTERED INDEX NCIX_OA_MESSAGE_BAK_ETypeID_ReceiverTypeID_CreateDate ON OA_MESSAGE_BAK(ETypeID_ReceiverTypeID,CreateDate) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_OnlineUser]    脚本日期: 05/05/2010 14:48:26 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_OnlineUser]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_OnlineUser](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeID_UserTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LatestConnectTime] [datetime] NULL,
		[LoginTime] [datetime] NULL,
		[UserName] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[IP] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[Status] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[IPLocal] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OA_OnlineUser' AND a.Name='PollineTime'
)
BEGIN
	ALTER TABLE OA_OnlineUser ADD PollineTime INT NULL DEFAULT (0)
END

GO
UPDATE OA_OnlineUser SET PollineTime = 180 WHERE PollineTime IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_PersonalDesktop]    脚本日期: 05/05/2010 14:48:27 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_PersonalDesktop]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_PersonalDesktop](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[CatalogTypeID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[SortOrder] [int] NOT NULL CONSTRAINT [DF_OA_PersonalDesktop_SortOrder]  DEFAULT (0),
		[DesktopList] [int] NOT NULL CONSTRAINT [DF_OA_PersonalDesktop_DesktopList]  DEFAULT (0),
		[Notify] [int] NOT NULL CONSTRAINT [DF_OA_PersonalDesktop_Notify]  DEFAULT (0),
		[ReplyNotify] [int] NOT NULL DEFAULT (0),
		[RefusePassiveReplyNotify] [int] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

---插入预置预订栏目信息--
IF NOT EXISTS(SELECT TOP 1 1 FROM OA_PersonalDesktop)
BEGIN
	INSERT INTO dbo.OA_PersonalDesktop
	        ( ETypeID_CreatorTypeID ,
	          CatalogTypeID ,
	          SortOrder ,
	          DesktopList ,
	          Notify ,
	          ReplyNotify ,
	          RefusePassiveReplyNotify
	        )
	VALUES  ( '00001' , '001001001' , 1 , 1 , 0 , 0 , 0  ),
			( '00001' , '001001002' , 1 , 1 , 0 , 0 , 0  )
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_PersonalDesktop]') AND name = N'IX_OA_PersonalDesktop')
DROP INDEX [dbo].[OA_PersonalDesktop].IX_OA_PersonalDesktop
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_PERSONALDESKTOP') AND name = 'CIX_OA_PERSONALDESKTOP_ETypeID_CreatorTypeID_CatalogTypeID')
--DROP INDEX CIX_OA_PERSONALDESKTOP_ETypeID_CreatorTypeID_CatalogTypeID ON OA_PERSONALDESKTOP 
CREATE CLUSTERED INDEX CIX_OA_PERSONALDESKTOP_ETypeID_CreatorTypeID_CatalogTypeID ON OA_PERSONALDESKTOP(ETypeID_CreatorTypeID,CatalogTypeID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_PersonalMsgNotify_AND]    脚本日期: 05/05/2010 14:48:28 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_PersonalMsgNotify_AND]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_PersonalMsgNotify_AND](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[CatalogTypeID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[PublisherTypeID] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[PublisherName] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[Content] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[ModifyDate] [datetime] NOT NULL CONSTRAINT [DF_OA_PersonalMsgNotify_AND_ModifyDate]  DEFAULT (getdate()),
		[Available] [int] NOT NULL CONSTRAINT [DF_OA_PersonalMsgNotify_AND_Available]  DEFAULT (1),
		[Grammar] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_PersonalMsgNotify_OR]    脚本日期: 05/05/2010 14:48:29 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_PersonalMsgNotify_OR]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_PersonalMsgNotify_OR](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[CatalogTypeID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[PublisherTypeID] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[PublisherName] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[Content] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL,
		[ModifyDate] [datetime] NOT NULL CONSTRAINT [DF_OA_PersonalMsgNotify_OR_ModifyDate]  DEFAULT (getdate()),
		[Available] [int] NOT NULL CONSTRAINT [DF_OA_PersonalMsgNotify_OR_Available]  DEFAULT (1),
		[Grammar] [varchar](2000) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_PrivateDB]    脚本日期: 05/05/2010 14:48:30 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_PrivateDB]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_PrivateDB](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[CatalogID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Content] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL,
		[CreateDate] [datetime] NULL,
		[ETypeID_SenderTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID_ReceiverTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[AttachmentID] [int] NOT NULL,
		[IsRead] [int] NOT NULL,
		[Type] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Docking] [int] NOT NULL,
		[SortOrder] [int] NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_PrivateDB]') AND name = N'IX_OA_PrivateDB')
DROP INDEX [dbo].[OA_PrivateDB].[IX_OA_PrivateDB]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_PRIVATEDB') AND name = 'CIX_OA_PRIVATEDB_ID_ETypeID_CreatorTypeID')
--DROP INDEX CIX_OA_PRIVATEDB_ID_ETypeID_CreatorTypeID ON OA_PRIVATEDB 
CREATE CLUSTERED INDEX CIX_OA_PRIVATEDB_ID_ETypeID_CreatorTypeID ON OA_PRIVATEDB(ID,ETypeID_CreatorTypeID) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_Product]    脚本日期: 05/05/2010 14:48:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_Product]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_Product](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[CatalogID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[UserCode] [varchar](65) COLLATE Chinese_PRC_CI_AS NULL,
		[FullName] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
		[Name] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Standard] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Type] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Area] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[Unit] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[Manufacturer] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[ImageFile] [image] NULL,
		[FileType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[FileName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[FileLength] [int] NULL,
		[szDate] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID_OpeatorID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ClickNum] [int] NULL,
		[FJBinaryContent] [image] NULL,
		[FJContentType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[FJContentLength] [int] NULL,
		[FJFileName] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OA_Product' AND a.Name='Comment' and a.xtype=35
)
BEGIN
	ALTER TABLE OA_Product ALTER COLUMN Comment VARCHAR(MAX)
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OA_Product' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OA_Product 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_PublicDB]    脚本日期: 05/05/2010 14:48:32 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_PublicDB]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_PublicDB](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[CatalogID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[Title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Content] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[CreateDate] [datetime] NULL,
		[ModifyDate] [datetime] NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID_ModifierTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ClickNumber] [int] NULL,
		[ReplyNumber] [int] NULL,
		[EmotionImg] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,
		[HtmlCode] [int] NOT NULL CONSTRAINT [DF_OA_PublicDB_HtmlCode]  DEFAULT (0),
		[ParentID] [varchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_OA_PublicDB_ParentID]  DEFAULT (0),
		[Docking] [int] NOT NULL CONSTRAINT [DF_OA_PublicDB_Docking]  DEFAULT (0),
		[Hidden] [int] NOT NULL CONSTRAINT [DF_OA_PublicDB_Hidden]  DEFAULT (0),
		[Emulate] [int] NOT NULL CONSTRAINT [DF_OA_PublicDB_Emulate]  DEFAULT (0),
		[SortOrder] [int] NOT NULL CONSTRAINT [DF_OA_PublicDB_SortOrder]  DEFAULT (0),
		[IsEnableCreatorDel] [int] NOT NULL CONSTRAINT [DF__OA_Public__IsEna__5F29F348]  DEFAULT (1),
		[DocFileName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[DocFileLength] [int] NOT NULL CONSTRAINT [DF__OA_Public__DocFi__723CC7BC]  DEFAULT (0),
		[IsRefuseRepeat] [int] NOT NULL CONSTRAINT [DF__OA_Public__IsRef__7330EBF5]  DEFAULT (1),
		[IsVote] [int] NOT NULL CONSTRAINT [DF__OA_Public__IsVot__7425102E]  DEFAULT (0),
		[VoteName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[VoteMode] [int] NOT NULL CONSTRAINT [DF__OA_Public__VoteM__75193467]  DEFAULT (0),
		[VoteEndDateTime] [datetime] NULL,
		[IsEnableVote] [int] NOT NULL CONSTRAINT [DF__OA_Public__IsEna__760D58A0]  DEFAULT (1),
		[IsEnableView] [int] NOT NULL CONSTRAINT [DF__OA_Public__IsEna__77017CD9]  DEFAULT (1),
		[IsEnableAgentVote] [int] NOT NULL CONSTRAINT [DF__OA_Public__IsEna__77F5A112]  DEFAULT (0),
		[Vote_S1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S5] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S6] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S7] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S8] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S9] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_S10] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Vote_N1] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___78E9C54B]  DEFAULT (0),
		[Vote_N2] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___79DDE984]  DEFAULT (0),
		[Vote_N3] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___7AD20DBD]  DEFAULT (0),
		[Vote_N4] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___7BC631F6]  DEFAULT (0),
		[Vote_N5] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___7CBA562F]  DEFAULT (0),
		[Vote_N6] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___7DAE7A68]  DEFAULT (0),
		[Vote_N7] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___7EA29EA1]  DEFAULT (0),
		[Vote_N8] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___7F96C2DA]  DEFAULT (0),
		[Vote_N9] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___008AE713]  DEFAULT (0),
		[Vote_N10] [int] NOT NULL CONSTRAINT [DF__OA_Public__Vote___017F0B4C]  DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OA_PublicDB' AND a.Name='Content' and a.xtype=35
)
BEGIN
	ALTER TABLE OA_PublicDB ALTER COLUMN Content VARCHAR(MAX)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OA_publicDB' AND a.Name='IsFromDD'
)
BEGIN
	ALTER TABLE OA_publicDB ADD IsFromDD VARCHAR(10) DEFAULT('')
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_PublicDB]') AND name = N'IX_OA_PublicDB_1')
DROP INDEX [dbo].[OA_PublicDB].[IX_OA_PublicDB_1]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_PublicDB]') AND name = N'IX_OA_PublicDB')
DROP INDEX [dbo].[OA_PublicDB].[IX_OA_PublicDB]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_PUBLICDB') AND name = 'CIX_OA_PUBLICDB_ID')
--DROP INDEX CIX_OA_PUBLICDB_ID ON OA_PUBLICDB 
CREATE CLUSTERED INDEX CIX_OA_PUBLICDB_ID ON OA_PUBLICDB(ID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_PUBLICDB') AND name = 'NCIX_OA_PUBLICDB_CatalogID_ETypeID_CreatorTypeID')
--DROP INDEX NCIX_OA_PUBLICDB_CatalogID_ETypeID_CreatorTypeID ON OA_PUBLICDB 
CREATE NONCLUSTERED INDEX NCIX_OA_PUBLICDB_CatalogID_ETypeID_CreatorTypeID ON OA_PUBLICDB(CatalogID,ETypeID_CreatorTypeID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_Right]    脚本日期: 05/05/2010 14:48:33 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_Right]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_Right](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeID_EmployeeTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[CatalogID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[RightString] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[ModifyDate] [datetime] NULL,
		[ETypeID_ModifierTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_Right]') AND name = N'IX_OA_Right')
DROP INDEX [dbo].[OA_Right].[IX_OA_Right]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_RIGHT') AND name = 'CIX_OA_RIGHT_ETypeID_EmployeeTypeID_CatalogID')
--DROP INDEX CIX_OA_RIGHT_ETypeID_EmployeeTypeID_CatalogID ON OA_RIGHT 
CREATE CLUSTERED INDEX CIX_OA_RIGHT_ETypeID_EmployeeTypeID_CatalogID ON OA_RIGHT(ETypeID_EmployeeTypeID,CatalogID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_RightTemplateDetail]    脚本日期: 05/05/2010 14:48:34 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_RightTemplateDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_RightTemplateDetail](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TemplateID] [int] NOT NULL,
		[CatalogTypeID] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[RightString] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------

--IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_OA_RightTemplateDetail_OA_RightTemplateType]') AND parent_object_id = OBJECT_ID(N'[dbo].[OA_RightTemplateDetail]'))
--ALTER TABLE [dbo].[OA_RightTemplateDetail] DROP CONSTRAINT [FK_OA_RightTemplateDetail_OA_RightTemplateType]

GO
------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_RightTemplateType]    脚本日期: 05/05/2010 14:48:34 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_RightTemplateType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_RightTemplateType](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TemplateName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ModifyDate] [datetime] NULL,
		[ETypeID_CreatorTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_RIGHTTEMPLATETYPE') AND name = 'CIX_OA_RIGHTTEMPLATETYPE_ID')
DROP INDEX CIX_OA_RIGHTTEMPLATETYPE_ID ON OA_RIGHTTEMPLATETYPE 

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_RightTemplateType]') AND name = N'PK_OA_RightTemplateType')
BEGIN
	ALTER TABLE [dbo].[OA_RightTemplateType] ADD  CONSTRAINT [PK_OA_RightTemplateType] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	) ON [PRIMARY]
END
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_Subscibe]    脚本日期: 05/05/2010 14:48:35 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_Subscibe]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_Subscibe](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ArticleID] [int] NULL,
		[ETypeID_SubsciberTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_UserInformation]    脚本日期: 05/05/2010 14:48:36 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_UserInformation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_UserInformation](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeID_UserTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Experience] [int] NOT NULL,
		[Add] [int] NULL,
		[Reply] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_UserInformation]') AND name = N'IX_OA_UserInformation')
DROP INDEX [dbo].[OA_UserInformation].IX_OA_UserInformation
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_USERINFORMATION') AND name = 'NCIX_OA_USERINFORMATION_ETypeID_UserTypeID')
--DROP INDEX NCIX_OA_USERINFORMATION_ETypeID_UserTypeID ON OA_USERINFORMATION 
CREATE NONCLUSTERED INDEX NCIX_OA_USERINFORMATION_ETypeID_UserTypeID ON OA_USERINFORMATION(ETypeID_UserTypeID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OA_Vote_EmployeeVoteInfo]    脚本日期: 05/05/2010 14:48:37 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OA_Vote_EmployeeVoteInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OA_Vote_EmployeeVoteInfo](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[VoteID] [int] NOT NULL,
		[ETypeID] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_Vote_EmployeeVoteInfo]') AND name = N'IX_OA_Vote_EmployeeVoteInfo')
DROP INDEX [dbo].[OA_Vote_EmployeeVoteInfo].[IX_OA_Vote_EmployeeVoteInfo]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OA_Vote_EmployeeVoteInfo]') AND name = N'PK_OA_Vote_EmployeeVoteInfo')
ALTER TABLE [dbo].[OA_Vote_EmployeeVoteInfo] DROP CONSTRAINT [PK_OA_Vote_EmployeeVoteInfo]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_VOTE_EMPLOYEEVOTEINFO') AND name = 'CIX_OA_VOTE_EMPLOYEEVOTEINFO_VoteID_ETypeID')
--DROP INDEX CIX_OA_VOTE_EMPLOYEEVOTEINFO_VoteID_ETypeID ON OA_VOTE_EMPLOYEEVOTEINFO 
CREATE CLUSTERED INDEX CIX_OA_VOTE_EMPLOYEEVOTEINFO_VoteID_ETypeID ON OA_VOTE_EMPLOYEEVOTEINFO(VoteID,ETypeID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OA_VOTE_EMPLOYEEVOTEINFO') AND name = 'NCIX_OA_VOTE_EMPLOYEEVOTEINFO_VoteID')
--DROP INDEX NCIX_OA_VOTE_EMPLOYEEVOTEINFO_VoteID ON OA_VOTE_EMPLOYEEVOTEINFO 
CREATE NONCLUSTERED INDEX NCIX_OA_VOTE_EMPLOYEEVOTEINFO_VoteID ON OA_VOTE_EMPLOYEEVOTEINFO(VoteID) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OFF_Ftype]    脚本日期: 05/05/2010 14:48:38 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OFF_Ftype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OFF_Ftype](
		[NUM] [int] IDENTITY(1,1) NOT NULL,
		[barname] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[layer1] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_layer1]  DEFAULT (0),
		[layer2] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_layer2]  DEFAULT (0),
		[layer3] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_layer3]  DEFAULT (0),
		[layer4] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_layer4]  DEFAULT (0),
		[layer5] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_layer5]  DEFAULT (0),
		[layer6] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_layer6]  DEFAULT (0),
		[bardescript] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[url] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[parent] [int] NULL,
		[son] [int] NULL,
		[soncount] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_soncount]  DEFAULT (0),
		[levelnum] [int] NULL,
		[powername0] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[powername4] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[store] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_store]  DEFAULT (0),
		[nsave] [int] NULL,
		[breed] [int] NULL,
		[AllSee] [int] NOT NULL CONSTRAINT [DF_OFF_Ftype_AllSee]  DEFAULT (0),
		[room_name] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[room_auto] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[room_owner] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[room_des] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[room_ref] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[room_title] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[room_keep] [bit] NULL,
		[room_time] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[room_html] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ip_protect] [bit] NULL
	) ON [PRIMARY]

	-- ********	处理 OFF_Ftype	********
	DELETE FROM OFF_Ftype
	SET identity_INSERT OFF_Ftype ON 
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(1,'公告板',1,1,1,1,1,1,'','',0,null,2,1,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(3,'BBS论坛',3,1,1,1,1,1,'','',0,null,4,1,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(4,'公司资料',4,1,1,1,1,1,'','',0,null,4,1,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(5,'产品资料',5,1,1,1,1,1,'','',0,null,2,1,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(6,'业务活动',6,1,1,1,1,1,'','',0,null,1,1,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(7,'内部公告板',1,2,1,1,1,1,'','',1,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(8,'分销商公告板',1,3,1,1,1,1,'','',1,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(11,'企业内产品论坛',3,2,1,1,1,1,'','',3,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(12,'企业内营销论坛',3,3,1,1,1,1,'','',3,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(13,'分销商论坛',3,4,1,1,1,1,'','',3,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(14,'企业管理论坛',3,5,1,1,1,1,'','',3,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(15,'企业内部文件',4,2,1,1,1,1,'','',4,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(16,'代理策略汇集',4,3,1,1,1,1,'','',4,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(17,'成败案例分析',4,4,1,1,1,1,'','',4,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(18,'服务培训管理',4,5,1,1,1,1,'','',4,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(19,'ABC系列',5,2,1,1,1,1,'','',5,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(20,'DEF系列',5,3,1,1,1,1,'','',5,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(21,'内部销售会议',6,2,1,1,1,1,'','',6,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(22,'全国性广告',6,3,1,1,1,1,'','',6,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	INSERT INTO OFF_Ftype(NUM,barname,layer1,layer2,layer3,layer4,layer5,layer6,bardescript,url,parent,son,SonCount,levelnum,powername0,powername1,powername2,powername3,powername4,store,nsave,breed,AllSee,room_name,room_auto,room_owner,room_des,room_ref,room_title,room_keep,room_time,room_html,ip_protect) VALUES(24,'分销商拜访',6,4,1,1,1,1,'','',6,null,0,2,'','','','','',0,null,1,0,'','','超级用户','','','',null,'','',null)
	SET identity_INSERT OFF_Ftype OFF
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OFF_Right]    脚本日期: 05/05/2010 14:48:39 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OFF_Right]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OFF_Right](
		[FtypeId] [varchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Right] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[OFF_Right]') AND name = N'IX_OFF_Right')
--ALTER TABLE [dbo].[OFF_Right] DROP CONSTRAINT [IX_OFF_Right]
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
--ALTER TABLE [dbo].[OFF_Right] ADD  CONSTRAINT [IX_OFF_Right] UNIQUE NONCLUSTERED 
--(
--	[FtypeId] ASC,
--	[EtypeId] ASC
--)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

GO


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Offline_Bill]    脚本日期: 05/05/2010 14:48:40 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Offline_Bill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Offline_Bill](
		[OFF_ID] [uniqueidentifier] NOT NULL,
		[BillNumberId] [numeric](18, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL,
		[ReachQty] [numeric](18, 4) NULL,
		[Price] [numeric](18, 4) NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[total] [numeric](18, 4) NULL,
		[totalinmoney] [numeric](18, 4) NULL,
		[discount] [numeric](3, 2) NULL,
		[DiscountPrice] [numeric](18, 4) NULL,
		[costprice] [numeric](18, 4) NULL,
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[GoodsNo] [int] NULL,
		[inorout] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[OutFactoryDate] [datetime] NULL,
		[Checked] [bit] NOT NULL CONSTRAINT [DF_Offline_Bill_Checked]  DEFAULT (0),
		[ID] [int] NULL,
		[TeamNo] [int] NULL,
		[TeamNO1] [int] NULL,
		[OrderID] [numeric](18, 0) NULL CONSTRAINT [DF_Offline_Bill_OrderID]  DEFAULT (0),
		[TASKID] [int] NOT NULL CONSTRAINT [DF_Offline_Bill_TASKID]  DEFAULT (0),
		[OFFLINE_ID] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_Offline_Bill_IsUnit2]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='ReachQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN ReachQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_Bill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_Bill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Offline_BillIndex]    脚本日期: 05/05/2010 14:48:41 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Offline_BillIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Offline_BillIndex](
		[OFF_ID] [uniqueidentifier] NOT NULL,
		[BillNumberId] [numeric](18, 0) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[atypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalmoney] [numeric](18, 4) NULL,
		[totalinmoney] [numeric](18, 4) NULL,
		[totalqty] [numeric](18, 4) NULL,
		[tax] [numeric](5, 2) NULL,
		[period] [smallint] NULL,
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[RedWord] [bit] NOT NULL,
		[draft] [bit] NOT NULL,
		[OrderId] [numeric](10, 0) NULL,
		[waybillcode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsnumber] [numeric](2, 0) NULL,
		[packway] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[TEL] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
		[Status] [int] NULL,
		[StockName] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[TaskID] [int] NOT NULL CONSTRAINT [DF_Offline_BillIndex_TaskID]  DEFAULT (1),
		[Import] [int] NOT NULL CONSTRAINT [DF_Offline_BillIndex_Import]  DEFAULT (0),
		[STOCKID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[AlertDay] [int] NULL CONSTRAINT [DF_Offline_BillIndex_AlertDay]  DEFAULT (9999),
		[CompleteTotal] [numeric](18, 4) NULL,
		[Assessor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfAudit] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[Audit_explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[ID] [numeric](18, 0) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--9.6.1运单号从20个字符升级为50个字符
IF EXISTS(SELECT Name FROM SySColumns WHERE ID=OBJECT_ID('Offline_BillIndex',N'U') AND LOWER(Name)='waybillcode' AND [Length]=20)
BEGIN
	ALTER TABLE Offline_BillIndex
	ALTER COLUMN waybillcode VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL
END

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Offline_BillIndex]') AND name = N'PK_Offline_BillIndex')
ALTER TABLE [dbo].[Offline_BillIndex] DROP CONSTRAINT [PK_Offline_BillIndex]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OFFLINE_BILLINDEX') AND name = 'NCIX_OFFLINE_BILLINDEX_OFF_ID')
--DROP INDEX NCIX_OFFLINE_BILLINDEX_OFF_ID ON OFFLINE_BILLINDEX 
CREATE NONCLUSTERED INDEX NCIX_OFFLINE_BILLINDEX_OFF_ID ON OFFLINE_BILLINDEX(OFF_ID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_BillIndex' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_BillIndex 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_BillIndex' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_BillIndex 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_BillIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_BillIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_BillIndex' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_BillIndex 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Offline_BillIndex' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Offline_BillIndex 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OFFLINE_TASK]    脚本日期: 05/05/2010 14:48:41 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OFFLINE_TASK]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OFFLINE_TASK](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[FILENAME] [varchar](255) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[DATE] [datetime] NOT NULL,
		[FLAG] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[TASKID] [int] NOT NULL,
		[STATUS] [int] NOT NULL CONSTRAINT [DF_OFFLINE_TASK_STATUS]  DEFAULT (0),
		[STOCKID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[OftenComment]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[OftenComment] (
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[UserCode] [varchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL default('') ,
		[Content] [varchar] (256) COLLATE Chinese_PRC_CI_AS NOT NULL  default('')
	) ON [PRIMARY]
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[OftenExplain]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[OftenExplain] (
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[UserCode] [varchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL default(''),
		[Content] [varchar] (256) COLLATE Chinese_PRC_CI_AS NOT NULL default('')
	) ON [PRIMARY]
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OftenMenu]    脚本日期: 05/05/2010 14:48:00 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OftenMenu]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OftenMenu](
		[etypeid] [varchar](100)  NOT NULL,
		[MenuID] [varchar](100) NOT NULL,
		[MenuName] [varchar](100) NOT NULL,
		[LimitName] [varchar](100) NOT NULL,
		[ShowOrder] [int] NOT NULL DEFAULT 0
	) ON [PRIMARY]

	-- ********	处理 OftenMenu	********
	DELETE FROM OftenMenu
END
GO

------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OftenMenu]') AND name = N'PK_OftenMenu')
ALTER TABLE [dbo].[OftenMenu] DROP CONSTRAINT [PK_OftenMenu]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_addebtbill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_addebtbill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BrandarTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[BTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[Total] [numeric](22, 10) NULL DEFAULT(0),	
		[NTotal] [numeric](22,10)   NULL Default(0),
		[CompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[NCompleteTotal]   [NUMERIC](22,10)   NULL Default(0)
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_addebtbill') AND name = 'CIX_Old_addebtbill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_addebtbill_BillNumberID ON Old_addebtbill(BillNumberID) 
GO





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_Bill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_Bill](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[BillType] INT,
		[ID] INT,
		[PTypeID] VARCHAR(50) NULL DEFAULT(''),		
		[KTypeID] VARCHAR(50) NULL DEFAULT(''),
		[STypeID] VARCHAR(50) NULL DEFAULT(''),
		[PostTime] DATETIME NULL DEFAULT(GETDATE()),
		[BillDate] DATETIME NULL
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_Bill' AND a.Name='UpdateTime'
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('Old_Bill') AND name='UpdateTime')
	
	IF @dfname IS NOT NULL
	EXEC ('ALTER TABLE Old_Bill DROP CONSTRAINT '+@dfname);
	ALTER TABLE Old_Bill DROP COLUMN UpdateTime
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_Bill' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE Old_Bill ADD STypeID VARCHAR(50) NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_Bill' AND a.Name='PostTime'
)
BEGIN
	ALTER TABLE Old_Bill ADD PostTime DATETIME NULL
END
GO

IF NOT EXISTS ( SELECT  1
                FROM    SysColumns
                WHERE   ID = OBJECT_ID(N'Old_Bill', N'U')
                        AND Name = 'BillDate' )
    BEGIN
        ALTER TABLE dbo.Old_Bill ADD BillDate DATETIME NULL
    END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT 1 FROM Sys.Indexes WHERE object_id = OBJECT_ID('Old_Bill') AND Name = 'CIX_Old_Bill_PostTime')
CREATE CLUSTERED INDEX CIX_Old_Bill_PostTime ON Old_Bill(PostTime) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE object_id = OBJECT_ID('Old_Bill') AND name = 'NCIX_Old_Bill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_Old_Bill_BillNumberID ON Old_Bill(BillNumberID) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE object_id = OBJECT_ID('Old_Bill') AND name = 'NCIX_Old_Bill_PTypeID')
CREATE NONCLUSTERED INDEX NCIX_Old_Bill_PTypeID ON Old_Bill(PTypeID) 

IF NOT EXISTS (SELECT 1 FROM Sys.Indexes WHERE object_id = OBJECT_ID('Old_Bill') AND name = 'NCIX_Old_Bill_STypeID')
CREATE NONCLUSTERED INDEX NCIX_Old_Bill_STypeID ON Old_Bill(STypeID) 

------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_BillMulAccount]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_BillMulAccount](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[ATypeID] VARCHAR(50) NULL DEFAULT(''),		
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[VipCardID] INT NULL DEFAULT(-1),
		[Comment] VARCHAR(500) NULL DEFAULT(''),
		[BillType]	INT	NULL	
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_BillMulAccount' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE Old_BillMulAccount ADD NTotalMoney  NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_BillMulAccount' AND a.Name='BillType'
)
BEGIN
	ALTER TABLE Old_BillMulAccount ADD BillType  INT NULL
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS(SELECT 1 FROM Sys.Indexes WHERE object_id=OBJECT_ID(N'Old_BillMulAccount',N'U') AND Name='CIX_Old_BillMulAccount_BillnumberID')
CREATE CLUSTERED INDEX CIX_Old_BillMulAccount_BillnumberID ON dbo.Old_BillMulAccount(BillNumberId)
------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_BillMulAccount' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_BillMulAccount 
	ALTER COLUMN Total NUMERIC(24,10)
    END

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_BillMulAccount' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_BillMulAccount 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                       
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--商品品牌多账户信息
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Old_BillMulBrand]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Old_BillMulBrand
	(	
		ID			INT IDENTITY(1,1),
		STypeID		VARCHAR(50) NOT NULL,	--分支机构ID	
		BTypeID		VARCHAR(50) NOT NULL,	--往来单位ID	
		BrandarTypeID VARCHAR(50) NOT NULL,	--商品品牌ID
		BillNumberId	NUMERIC(10,0) NOT NULL,--单据ID
		BillType		INT NOT NULL DEFAULT(-1),--单据类型
		Cid				INT NOT NULL DEFAULT(-1),	--币种
		Rate			NUMERIC(24,10) NOT NULL DEFAULT(0),	--币种汇率
		TaxTotal		NUMERIC(24,10) NOT NULL DEFAULT(0),--价税合计金额（销售金额）
		NTaxTotal		NUMERIC(24,10) NOT NULL DEFAULT(0),--原币价税合计金额（销售金额）
		PreferenceMoney NUMERIC(24,10) NOT NULL DEFAULT(0),--抹零金额
		NPreferenceMoney NUMERIC(24,10) NOT NULL DEFAULT(0),--原币抹零金额
		TotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--实付金额	
		NTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币实付金额	
		YSTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--实付金额	
		NYSTotalInMoney	NUMERIC(24,10) NOT NULL DEFAULT(0),--预收冲抵金额	
		TheOrderARTotal NUMERIC(24,10) NOT NULL DEFAULT(0),--原币预收冲抵金额	
		NTheOrderARTotal NUMERIC(24,10) NOT NULL DEFAULT(0),--本单原币应付金额
		isIni			INT NOT NULL DEFAULT(0)--是否期初数据
	)
END
GO 
------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_BillMulBrand') AND name = 'CIX_Old_BillMulBrand_BillNumberId')
	CREATE CLUSTERED INDEX CIX_Old_BillMulBrand_BillNumberId ON Old_BillMulBrand(BillNumberId) 
	
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_BillMulBrand') AND name = 'NCIX_Old_BillMulBrand_BrandarTypeID')
	CREATE NONCLUSTERED INDEX NCIX_Old_BillMulBrand_BrandarTypeID ON Old_BillMulBrand(BrandarTypeID) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO
------------------------------------------预制数据-------------------------------------------------
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_commissionbill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_commissionbill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[TaxTotal] [numeric](22, 10) NULL DEFAULT(0),	
		[NTaxTotal] [numeric](22,10)   NULL Default(0),
		[CompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[NCompleteTotal]   [NUMERIC](22,10)   NULL Default(0)
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_commissionbill') AND name = 'CIX_Old_commissionbill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_commissionbill_BillNumberID ON Old_commissionbill(BillNumberID) 
GO



--品牌结算表
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_CompleteBrandarTotal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_CompleteBrandarTotal]
	(
		ID				INT IDENTITY(1,1),
		GoodsBillID		NUMERIC(10,0),	
		MoneyBillId		NUMERIC(10,0),
		BrandarTypeID	VARCHAR	(50) NOT NULL,
		STypeId			VARCHAR	(50) NOT NULL,
		BTypeId			VARCHAR	(50) NOT NULL,
		BillType		INT NOT NULL,--单据类型
		BillDate		DATETIME,--当前保存时间
		BillCode		VARCHAR(200),--单据编号
		CId				INT,--币种
		CompleteTotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--结算金额
		NCompleteTotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币结算金额
		Comment			VARCHAR(500),--备注
		EtypeID			VARCHAR(50),--经手人ID
		IsDraft			TINYINT  NOT NULL DEFAULT(1),--是否草稿
		IsIni			TINYINT NOT NULL DEFAULT(0),--是否期初
		DetailId		INT	NOT NULL DEFAULT(0)		--应收增加/减少单明细id

	) ON [PRIMARY]


END
GO
------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_CompleteBrandarTotal') AND name = 'CIX_Old_CompleteBrandarTotal_GoodsBillid')
	CREATE CLUSTERED INDEX CIX_Old_CompleteBrandarTotal_GoodsBillid ON Old_CompleteBrandarTotal(GoodsBillid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_CompleteBrandarTotal') AND name = 'NCIX_Old_CompleteBrandarTotal_MoneyBillid')
	CREATE NONCLUSTERED INDEX NCIX_Old_CompleteBrandarTotal_MoneyBillid ON Old_CompleteBrandarTotal(MoneyBillid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_CompleteBrandarTotal') AND name = 'NCIX_Old_CompleteBrandarTotal_BrandarTypeID')
	CREATE NONCLUSTERED INDEX NCIX_Old_CompleteBrandarTotal_BrandarTypeID ON Old_CompleteBrandarTotal(BrandarTypeID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
                              
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Old_CompleteGoodTotal]    脚本日期: 05/05/2010 14:47:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_CompleteGoodTotal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_CompleteGoodTotal](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[GoodsBillID] [int] NOT NULL,
		[MoneyBillID] [int] NOT NULL,
		[InOrOut] [char](1) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[CompleteGoodQTY] [numeric](18, 4) NOT NULL,
		[Draft] [tinyint] NULL,
		[Billdate] [datetime] NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Billid] [int] NULL,
		[CompleteGoodTotal] [numeric](18, 4) NULL,
		[Price] [numeric](18, 4) NULL DEFAULT (0),
		[NCompleteTotal] [numeric](22, 10)  NULL DEFAULT(0),
		[BillType] [INT] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteGoodTotal' AND a.Name='NCompleteTotal'
)
BEGIN
	ALTER TABLE Old_CompleteGoodTotal ADD NCompleteTotal NUMERIC(22,10) null
	
	EXEC('UPDATE Old_CompleteGoodTotal SET NCompleteTotal=CompleteGoodTotal WHERE NCompleteTotal IS NULL')
END
ELSE
BEGIN
	ALTER TABLE Old_CompleteGoodTotal ALTER COLUMN NCompleteTotal NUMERIC(22,10) null
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteGoodTotal' AND a.Name='BillType'
)
BEGIN
	ALTER TABLE Old_CompleteGoodTotal ADD BillType INT NULL
	
	EXEC (
	'UPDATE a SET a.billtype = b.billtype FROM dbo.Old_CompleteGoodTotal  a JOIN  
	(SELECT BillNumberId,BillType FROM dbo.BillIndex WHERE BillType IN (
		SELECT Billtype
		FROM   dbo.BillName
		WHERE  BillName IN ( ''销售出库单'', ''销售换货单'', ''销售退货单'', ''委托代销结算单'',
							 ''维修取件单'', ''整机更换单'', ''采购入库单'', ''采购换货单'',
							 ''采购退货单'', ''受托代销结算单'', ''送修返回单'' )
	)) b ON( a.GoodsBillID = b.BillNumberId ) ')

END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS(SELECT 1 FROM Sys.Indexes WHERE object_id=OBJECT_ID(N'Old_CompleteGoodTotal') AND Name='CIX_Old_CompleteGoodTotal_ID')
CREATE CLUSTERED INDEX CIX_Old_CompleteGoodTotal_ID ON dbo.Old_CompleteGoodTotal(MoneyBillID,GoodsBillID)
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteGoodTotal' AND a.Name='CompleteGoodQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_CompleteGoodTotal 
	ALTER COLUMN CompleteGoodQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteGoodTotal' AND a.Name='CompleteGoodTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_CompleteGoodTotal 
	ALTER COLUMN CompleteGoodTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteGoodTotal' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_CompleteGoodTotal 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteGoodTotal' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_CompleteGoodTotal 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Old_CompleteTotal]    脚本日期: 05/05/2010 14:47:09 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_CompleteTotal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_CompleteTotal](
		[GoodsBillID] [int] NOT NULL,
		[MoneyBillID] [int] NOT NULL,
		[CompleteTotal] [numeric](18, 4) NOT NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Draft] [tinyint] NULL DEFAULT (0),
		[Billdate] [datetime] NULL,
		[EtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[NCompleteTotal] [numeric](22, 10)  NULL DEFAULT(0),
		[BillType] [INT] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteTotal' AND a.Name='NCompleteTotal'
)
BEGIN
	ALTER TABLE Old_CompleteTotal ADD NCompleteTotal NUMERIC(22,10) NULL;
	
	EXEC('UPDATE Old_CompleteTotal SET NCompleteTotal=CompleteTotal WHERE NCompleteTotal IS NULL')
END
ELSE
BEGIN
	ALTER TABLE Old_CompleteTotal ALTER COLUMN NCompleteTotal NUMERIC(22,10) NULL;
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteTotal' AND a.Name='BillType'
)
BEGIN
	ALTER TABLE Old_CompleteTotal ADD BillType INT NULL
	EXEC (
			'UPDATE a SET a.billtype = b.billtype FROM dbo.Old_CompleteTotal  a JOIN  
			(SELECT BillNumberId,BillType FROM dbo.BillIndex WHERE BillType IN (
				SELECT Billtype
				FROM   dbo.BillName
				WHERE  BillName IN ( ''销售出库单'', ''销售换货单'', ''销售退货单'', ''委托代销结算单'',
									 ''维修取件单'', ''整机更换单'', ''采购入库单'', ''采购换货单'',
									 ''采购退货单'', ''受托代销结算单'', ''送修返回单'' )
			)) b ON( a.GoodsBillID = b.BillNumberId ) ')

END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS(SELECT 1 FROM Sys.Indexes WHERE object_id=OBJECT_ID(N'Old_CompleteTotal') AND Name='CIX_Old_CompleteTotal_ID')
CREATE CLUSTERED INDEX CIX_Old_CompleteTotal_ID ON dbo.Old_CompleteTotal(MoneyBillID,GoodsBillID)
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteTotal' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_CompleteTotal 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_CompleteTotal' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_CompleteTotal 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Old_GatheringBill]    脚本日期: 05/05/2010 14:47:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_GatheringBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_GatheringBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_Old_GatheringBill_total]  DEFAULT (0),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Old_GatheringBill_BillComment]  DEFAULT (''),
		[TeamNo] [int] NULL,
		[ID] [int] NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[VipCardID] INT NULL DEFAULT(-1)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_GatheringBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE Old_GatheringBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE Old_GatheringBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_GatheringBill' AND a.Name='RelevanceBillId'
)
BEGIN
	ALTER TABLE Old_GatheringBill ADD RelevanceBillId NUMERIC(10,0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_GatheringBill' AND a.Name='ntotal'
)
BEGIN
	ALTER TABLE Old_GatheringBill ADD ntotal NUMERIC(24,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_GatheringBill' AND a.Name='BrandarTypeID'
)
BEGIN
	ALTER TABLE Old_GatheringBill 
		ADD BrandarTypeID  VARCHAR(50) NOT NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_GatheringBill' AND a.Name='PreferenceMoney'
)
BEGIN
	ALTER TABLE Old_GatheringBill ADD PreferenceMoney NUMERIC(24,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_GatheringBill' AND a.Name='NPreferenceMoney'
)
BEGIN
	ALTER TABLE Old_GatheringBill ADD NPreferenceMoney NUMERIC(24,10) DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Old_GatheringBill]') AND name = N'IX_Old_GatheringBill')
DROP INDEX [dbo].[Old_GatheringBill].[IX_Old_GatheringBill]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysIndexes WHERE ID=OBJECT_ID(N'Old_GatheringBill',N'U') AND Name='CIX_Old_GatheringBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_GatheringBill_BillNumberID ON dbo.Old_GatheringBill(BillNumberId)

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_GatheringBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_GatheringBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Old_Listtable]    脚本日期: 05/05/2010 14:47:57 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_Listtable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_Listtable](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Old_Listtable_AtypeId]  DEFAULT (0),
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Old_Listtable_BtypeId]  DEFAULT (0),
		[STypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BillType] [numeric](4, 0)  NULL
	) ON [PRIMARY]


END
GO



------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_Listtable' AND a.Name='BillType'
)
BEGIN
	ALTER TABLE Old_Listtable ADD BillType INT NULL
	EXEC (
			'
			UPDATE Old_ListTable
			SET BillType=b.BillType
			FROM ListTable b
			WHERE Old_ListTable.BillNumberID=b.BillNumberID
			')

END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Old_Listtable]') AND name = N'IX_Old_Listtable_ATypeID')
DROP INDEX [IX_Old_Listtable_ATypeID] ON [dbo].[Old_Listtable] 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Old_Listtable]') AND name = N'IX_Old_Listtable_BillNumberId')
DROP INDEX [IX_Old_Listtable_BillNumberId] ON [dbo].[Old_Listtable] 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Old_Listtable]') AND name = N'IX_Old_Listtable_BTypeId')
DROP INDEX [IX_Old_Listtable_BTypeId] ON [dbo].[Old_Listtable] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OLD_LISTTABLE') AND name = 'NCIX_OLD_LISTTABLE_AtypeId')
--DROP INDEX NCIX_OLD_LISTTABLE_AtypeId ON OLD_LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_OLD_LISTTABLE_AtypeId ON OLD_LISTTABLE(AtypeId) 

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OLD_LISTTABLE') AND name = 'NCIX_OLD_LISTTABLE_BillNumberId')
DROP INDEX NCIX_OLD_LISTTABLE_BillNumberId ON OLD_LISTTABLE 

--BillnumberID,BillType联合建聚集索引
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OLD_LISTTABLE') AND name = 'CIX_OLD_LISTTABLE_BillNumberId_BillType')
CREATE CLUSTERED INDEX CIX_OLD_LISTTABLE_BillNumberId_BillType ON dbo.Old_Listtable(BillNumberId,BillType)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OLD_LISTTABLE') AND name = 'NCIX_OLD_LISTTABLE_BtypeId')
--DROP INDEX NCIX_OLD_LISTTABLE_BtypeId ON OLD_LISTTABLE 
CREATE NONCLUSTERED INDEX NCIX_OLD_LISTTABLE_BtypeId ON OLD_LISTTABLE(BtypeId) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_moneybill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_moneybill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BrandarTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[Total] [numeric](22, 10) NULL DEFAULT(0),	
		[NTotal] [numeric](22,10)   NULL Default(0)
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_moneybill') AND name = 'CIX_Old_moneybill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_moneybill_BillNumberID ON Old_moneybill(BillNumberID) 
GO





/****** 对象:  Table [dbo].[Old_PayBill]    脚本日期: 05/05/2010 14:48:46 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_PayBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_PayBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_Old_PayBill_total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[VipCardID] [INT] NULL DEFAULT(-1)	
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_PayBill' AND a.Name='RelevanceBillId'
)
BEGIN
	ALTER TABLE Old_PayBill ADD RelevanceBillId NUMERIC(10,0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_PayBill' AND a.Name='ntotal'
)
BEGIN
	ALTER TABLE Old_PayBill ADD ntotal NUMERIC(24,10)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Old_PayBill]') AND name = N'IX_Old_PayBill')
DROP INDEX [dbo].[Old_PayBill].[IX_Old_PayBill]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysIndexes WHERE ID=OBJECT_ID(N'Old_PayBill',N'U') AND Name='CIX_Old_PayBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_PayBill_BillNumberID ON dbo.Old_PayBill(BillNumberId)
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_PayBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_PayBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Old_PreBill]    脚本日期: 05/05/2010 14:46:29 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_PreBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_PreBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillType] [int] NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_Old_PreBill_total]  DEFAULT (0),
		[TeamNo] [int] NULL,
		[ID] [int] NOT NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')	
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_PreBill' AND a.Name='vipcardid'
)
BEGIN
	ALTER TABLE Old_PreBill 
		ADD vipcardid  INT NULL DEFAULT(-1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_PreBill' AND a.Name='RelevanceBillId'
)
BEGIN
	ALTER TABLE Old_PreBill ADD RelevanceBillId NUMERIC(10,0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_PreBill' AND a.Name='ntotal'
)
BEGIN
	ALTER TABLE Old_PreBill ADD ntotal NUMERIC(24,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_PreBill' AND a.Name='BrandarTypeID'
)
BEGIN
	ALTER TABLE Old_PreBill 
		ADD BrandarTypeID  VARCHAR(50) NOT NULL DEFAULT('')
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysIndexes WHERE ID=OBJECT_ID(N'Old_PreBill',N'U') AND Name='CIX_Old_PreBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_PreBill_BillNumberID ON dbo.Old_PreBill(BillNumberId)

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Old_PreBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Old_PreBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_PT_Combin_SaleBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_PT_Combin_SaleBackBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[TaxTotal] [numeric](22, 10) NULL DEFAULT(0),	
		[NTaxTotal] [numeric](22,10)   NULL Default(0),
		[CompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[NCompleteTotal]   [NUMERIC](22,10)   NULL Default(0)
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_PT_Combin_SaleBackBill') AND name = 'CIX_Old_PT_Combin_SaleBackBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_PT_Combin_SaleBackBill_BillNumberID ON Old_PT_Combin_SaleBackBill(BillNumberID) 
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_PT_Combin_SaleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_PT_Combin_SaleBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[TaxTotal] [numeric](22, 10) NULL DEFAULT(0),	
		[NTaxTotal] [numeric](22,10)   NULL Default(0),
		[CompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[NCompleteTotal]   [NUMERIC](22,10)   NULL Default(0)
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_PT_Combin_SaleBill') AND name = 'CIX_Old_PT_Combin_SaleBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_PT_Combin_SaleBill_BillNumberID ON Old_PT_Combin_SaleBill(BillNumberID) 
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_ReceiptBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_ReceiptBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[TaxTotal] [numeric](22, 10) NULL DEFAULT(0),	
		[NTaxTotal] [numeric](22,10)   NULL Default(0),
		[CompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[NCompleteTotal]   [NUMERIC](22,10)   NULL Default(0)
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_ReceiptBill') AND name = 'CIX_Old_ReceiptBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_ReceiptBill_BillNumberID ON Old_ReceiptBill(BillNumberID) 
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_retailBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_retailBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[TaxTotal] [numeric](22, 10) NULL DEFAULT(0),	
		[NTaxTotal] [numeric](22,10)   NULL Default(0)		
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_retailBill') AND name = 'CIX_Old_retailBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_retailBill_BillNumberID ON Old_retailBill(BillNumberID) 
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_salebackbill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_salebackbill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[TaxTotal] [numeric](22, 10) NULL DEFAULT(0),	
		[NTaxTotal] [numeric](22,10)   NULL Default(0),
		[CompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[NCompleteTotal]   [NUMERIC](22,10)   NULL Default(0)
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_salebackbill') AND name = 'CIX_Old_salebackbill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_salebackbill_BillNumberID ON Old_salebackbill(BillNumberID) 
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_SaleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_SaleBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[TaxTotal] [numeric](22, 10) NULL DEFAULT(0),	
		[NTaxTotal] [numeric](22,10)   NULL Default(0),
		[CompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[NCompleteTotal]   [NUMERIC](22,10)   NULL Default(0)
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_SaleBill') AND name = 'CIX_Old_SALEBILL_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_SALEBILL_BillNumberID ON Old_SALEBILL(BillNumberID) 
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Old_salegoodsexchangebill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Old_salegoodsexchangebill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,		
		[TaxTotal] [numeric](22, 10) NULL DEFAULT(0),	
		[NTaxTotal] [numeric](22,10)   NULL Default(0),
		[CompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[NCompleteTotal]   [NUMERIC](22,10)   NULL Default(0),
		[InOrOut] VARCHAR(10) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Old_salegoodsexchangebill') AND name = 'CIX_Old_salegoodsexchangebill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Old_salegoodsexchangebill_BillNumberID ON Old_salegoodsexchangebill(BillNumberID) 
GO



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[onShelvesbill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].onShelvesbill(
		[billNumberID] [numeric](18, 0) NOT NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesbill_ptypeid]  DEFAULT ('0'),
		[qty] [numeric](22, 10) NOT NULL CONSTRAINT [DF_onShelvesbill_qty]  DEFAULT (0),
		[comment] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesbill_comment]  DEFAULT (''),
		[GoodsBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[GoodsBillID] [numeric](10, 0)  NULL DEFAULT (0),
		[GoodsBillType]	INT,
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesbill_GoodsNumber]  DEFAULT (''),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_onShelvesbill_GoodsOrder]  DEFAULT ('-1'),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesbill_Serial]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesbill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesbill_ValidDate]  DEFAULT (''),
		[CargoID] INT DEFAULT(0),
		ShowOrder INT DEFAULT(0),
		MQty		NUMERIC(22,10),
		BillQty		NUMERIC(22,10),
		BillMQty	NUMERIC(22,10),
		MUnitId		INT,
		MUnitRate	NUMERIC(22,10),
		UnitID		INT
	) ON [PRIMARY]

END
GO

------------------------------------------表修改区域结束-------------------------------------------------
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'onShelvesbill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.onShelvesbill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.onShelvesbill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

--货位号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'onShelvesbill',N'U') AND Name='CargoID')
BEGIN
	ALTER TABLE dbo.onShelvesbill
	ADD CargoID INT DEFAULT(0)
END
GO


--采购单位上架数量
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'onShelvesbill',N'U') AND Name='MQty')
BEGIN
	ALTER TABLE dbo.onShelvesbill
	ADD MQty NUMERIC(22,10) DEFAULT(0)
END
GO

--基本单位数量
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'onShelvesbill',N'U') AND Name='BillQty')
BEGIN
	ALTER TABLE dbo.onShelvesbill
	ADD BillQty NUMERIC(22,10) DEFAULT(0)
END
GO

--采购单位数量
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'onShelvesbill',N'U') AND Name='BillMQty')
BEGIN
	ALTER TABLE dbo.onShelvesbill
	ADD BillMQty NUMERIC(22,10) DEFAULT(0)
END
GO

--采购单位id
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'onShelvesbill',N'U') AND Name='MUnitId')
BEGIN
	ALTER TABLE dbo.onShelvesbill
	ADD MUnitId INT DEFAULT(0)
END
GO

--采购单位换算率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'onShelvesbill',N'U') AND Name='MUnitRate')
BEGIN
	ALTER TABLE dbo.onShelvesbill
	ADD MUnitRate NUMERIC(22,10) NOT NULL DEFAULT(1)
END
GO

--单位id
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'onShelvesbill',N'U') AND Name='UnitId')
BEGIN
	ALTER TABLE dbo.onShelvesbill
	ADD UnitId INT DEFAULT(0)
END
GO
------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('onShelvesbill') AND name = 'CIX_onShelvesbill_BillNumberID')
CREATE CLUSTERED INDEX CIX_onShelvesbill_BillNumberID ON onShelvesbill(BillNumberID)  
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[onShelvespickIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].onShelvespickIndex(
		[billNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesIndex_etypeid]  DEFAULT (''),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesIndex_ktypeid]  DEFAULT (''),
		[BillDate] [datetime] NOT NULL,
		[Billcode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_onShelvesIndex_Billcode]  DEFAULT (0),
		[billtype] [smallint] NOT NULL CONSTRAINT [DF_onShelvesIndex_billtype]  DEFAULT (0),
		[totalqty] [numeric](22, 10) NOT NULL CONSTRAINT [DF_onShelvesIndex_totalqty]  DEFAULT (0),
		[period] [smallint] NOT NULL CONSTRAINT [DF_onShelvesIndex_period]  DEFAULT (0),
		[comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesIndex_comment]  DEFAULT (''),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesIndex_explain]  DEFAULT (''),
		[Checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfAudit] CHAR(1) NULL CONSTRAINT [DF_onShelvesIndex_IfAudit]  DEFAULT (''),
		[DtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_onShelvesIndex_DtypeId]  DEFAULT (''),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')	,
		[draft] [bit] NOT NULL CONSTRAINT [DF_onShelvesIndex_draft]  DEFAULT (0),
		[checkTime]		DATETIME NULL,
		[posttime]		DATETIME NULL,
		[updateE]		VARCHAR(50) NULL  DEFAULT (''),
		[Poster] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LastUpdateTime] DateTime NULL CONSTRAINT [DF_onShelvesIndex_LastUpdateTime]  DEFAULT GETDATE(),
		[IsIni]			BIT NULL DEFAULT(0),
		[ifYearBill]	INT DEFAULT(0),
		[RedWord]	INT DEFAULT(0),
		[IfCheck] CHAR(1) DEFAULT('f'),
		citestate int NOT NULL DEFAULT(0),--引用状态0=未引用1=已引用未完成2=已完成
		RedReason VARCHAR(500)  
	) ON [PRIMARY]

END
GO
 
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID('onShelvespickIndex',N'U') AND Name='RedReason')
BEGIN
	ALTER TABLE onShelvespickIndex
	ADD RedReason VARCHAR(500)
END
 
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='onShelvespickIndex' AND a.Name='IfCheck'
)
BEGIN
	ALTER TABLE onShelvespickIndex  ADD IfCheck CHAR(1) NULL DEFAULT('f')
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='onShelvespickIndex' AND a.Name='RedWord'
)
BEGIN
	ALTER TABLE onShelvespickIndex  ADD RedWord INT NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='onShelvespickIndex' AND a.Name='ifYearBill'
)
BEGIN
	ALTER TABLE onShelvespickIndex ADD ifYearBill INT NULL DEFAULT(0)
END
GO 

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='onShelvespickIndex' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE onShelvespickIndex  ADD IsIni BIT NULL DEFAULT(0)
END

IF EXISTS(
	SELECT  b.name FROM SYSCOLUMNS A,SYSOBJECTS B WHERE A.ID=object_id('onshelvespickindex') AND B.ID=A.CDEFAULT AND A.NAME='ifaudit' AND a.xtype = 56
)
BEGIN
	ALTER TABLE ONSHELVESPICKINDEX DROP CONSTRAINT DF_onShelvesIndex_IfAudit
END

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='onShelvespickIndex' AND a.Name='IfAudit' AND  a.xtype = 56
)
BEGIN
	ALTER TABLE onShelvespickIndex  ALTER COLUMN IfAudit CHAR(1)  
	ALTER TABLE onShelvespickIndex  ADD CONSTRAINT DF_onShelvesIndex_IfAudit  DEFAULT ('') FOR IFAUDIT
END
--引用状态
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='onShelvespickIndex' AND a.Name='citestate'
)
BEGIN
	ALTER TABLE dbo.onShelvespickIndex ADD citestate INT  NOT NULL DEFAULT(0)
END





------------------------------------------表修改区域结束-------------------------------------------------



------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('onShelvespickIndex') AND name = 'CIX_onShelvespickIndex_Billdate')
CREATE CLUSTERED INDEX CIX_onShelvespickIndex_Billdate ON onShelvespickIndex(Billdate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('onShelvespickIndex') AND name = 'NCIX_onShelvespickIndex_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_onShelvespickIndex_BillNumberID ON onShelvespickIndex(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('onShelvespickIndex') AND name = 'NCIX_onShelvespickIndex_Billtype')
CREATE NONCLUSTERED INDEX NCIX_onShelvespickIndex_Billtype ON onShelvespickIndex(Billtype) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('onShelvespickIndex') AND name = 'NCIX_onShelvespickIndex_Billcode')
CREATE NONCLUSTERED INDEX NCIX_onShelvespickIndex_Billcode ON onShelvespickIndex(Billcode) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OperatorConfig]    脚本日期: 05/05/2010 14:48:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OperatorConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OperatorConfig](
		[ETYpeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Associate] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[price] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OperatorConfig' AND a.Name='unitsid'
)
BEGIN
	ALTER TABLE OperatorConfig ADD unitsid INT NULL DEFAULT 0
END

GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT TOP 1 1 FROM SYSOBJECTS WHERE  id = object_id('OrderFiledSchemeDetail') and type='U')
BEGIN
	CREATE TABLE OrderFiledSchemeDetail (
	   nId				INT			IDENTITY(1,1),
	   SchemeId			INT			NOT NULL,	--默认方案ID
	   OrderFiled		VARCHAR(50)	NOT NULL,	--排序字段
	   OrderBy			VARCHAR(5)	NOT NULL,	--排序 升序 降序
	   OrderID			INT			NOT NULL	--排序	顺序
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OrderIndex]    脚本日期: 05/05/2010 14:48:44 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OrderIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OrderIndex](
		[billNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_btypeid]  DEFAULT (''),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_etypeid]  DEFAULT (''),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_ktypeid]  DEFAULT (''),
		[BillDate] [datetime] NOT NULL,
		[ReachDate] [datetime] NULL,
		[Billcode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_OrderIndex_Billcode]  DEFAULT (0),
		[billtype] [smallint] NOT NULL CONSTRAINT [DF_OrderIndex_billtype]  DEFAULT (0),
		[totalmoney] [numeric](18, 4) NOT NULL CONSTRAINT [DF_OrderIndex_totalmoney]  DEFAULT (0),
		[totalqty] [numeric](18, 4) NOT NULL CONSTRAINT [DF_OrderIndex_totalqty]  DEFAULT (0),
		[period] [smallint] NOT NULL CONSTRAINT [DF_OrderIndex_period]  DEFAULT (0),
		[checked] [bit] NOT NULL CONSTRAINT [DF_OrderIndex_checked]  DEFAULT (0),
		[redWord] [bit] NOT NULL CONSTRAINT [DF_OrderIndex_redWord]  DEFAULT (0),
		[BillOver] [bit] NOT NULL CONSTRAINT [DF_OrderIndex_BillOver]  DEFAULT (0),
		[comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_comment]  DEFAULT (''),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_explain]  DEFAULT (''),
		[Checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Tax] [numeric](5, 2) NOT NULL CONSTRAINT [DF_OrderIndex_Tax]  DEFAULT (17),
		[BillStatus] [int] NOT NULL CONSTRAINT [DF_OrderIndex_BillStatus]  DEFAULT (0),
		[etypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[WayMode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[WayBillCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[GoodsNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[PackWay] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[TEL] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[IfAudit] [int] NULL CONSTRAINT [DF_OrderIndex_IfAudit]  DEFAULT (0),
		[DtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_DtypeId]  DEFAULT (''),
		[IsFinished] [int] NULL,
		[CanAlert] [char](10) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_CanAlert]  DEFAULT ('1'),
		[DelayType] [char](10) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_DelayType]  DEFAULT ('0'),
		[DelayValue] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OrderIndex_DelayValue]  DEFAULT ('0'),
		[OrderState] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_OrderIndex_OrderState]  DEFAULT ('0'),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[CustomerTotal] [numeric](18, 4) NOT NULL DEFAULT(0),
		[IsIni]	BIT NULL DEFAULT(0),
		[Ntotalmoney] [numeric](22,10)   DEFAULT (0),
		[CID] int  NULL DEFAULT(0),
		[Rate] NUMERIC(22,10) DEFAULT(0),
		billproperty	INT NULL DEFAULT(-1),
		PrePriceNum INT DEFAULT(0) NOT NULL, --预设售价，进价
		IsYapi BIT DEFAULT(0) NULL,
		YapiOrderID VARCHAR(20) DEFAULT('') NULL,
		ARTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		APTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		YSTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		YFTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		[VipCardID] [int] NULL DEFAULT ((-1))
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='VipCardID'
)
BEGIN
	ALTER TABLE OrderIndex 
		ADD [VipCardID] INT NULL DEFAULT(-1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='ARTOTAL'
)
BEGIN
	ALTER TABLE OrderIndex 
		ADD ARTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='APTOTAL'
)
BEGIN
	ALTER TABLE OrderIndex 
		ADD APTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='YSTOTAL'
)
BEGIN
	ALTER TABLE OrderIndex 
		ADD YSTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='YFTOTAL'
)
BEGIN
	ALTER TABLE OrderIndex 
		ADD YFTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE OrderIndex ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE OrderIndex SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE OrderIndex ADD FromBillNumberID [numeric](10, 0)  NULL	
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='CustomerTotal'
)
BEGIN
	ALTER TABLE OrderIndex ADD CustomerTotal [numeric](18, 4) NOT NULL DEFAULT(0)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE OrderIndex 
		ADD IsIni BIT NULL DEFAULT(0)
		
	EXEC('UPDATE OrderIndex SET IsIni=0 WHERE IsIni IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE OrderIndex 
		ADD NTotalMoney  NUMERIC(22,10) DEFAULT(0)
		
	EXEC('UPDATE OrderIndex SET NTotalMoney=TotalMoney WHERE NTotalMoney=0')
END
ELSE
BEGIN
		ALTER TABLE OrderIndex 
		ALTER COLUMN NTotalMoney  NUMERIC(22,10);
		
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='NCustomerTotal'
)
BEGIN
	ALTER TABLE OrderIndex 
		ADD NCustomerTotal [numeric](18, 4) NOT NULL DEFAULT(0)
END

GO

	-- 清除多添加字段
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CurID' UNION ALL SELECT 'CurRate'
UNION ALL SELECT 'NARTOTAL'
UNION ALL SELECT 'NAPTOTAL'
UNION ALL SELECT 'NYSTOTAL'
UNION ALL SELECT 'NYFTOTAL'
UNION ALL SELECT 'ARTOTAL'
UNION ALL SELECT 'APTOTAL'
UNION ALL SELECT 'YSTOTAL'
UNION ALL SELECT 'YFTOTAL';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='orderindex';
SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
 + ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
 RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
 JOIN @t d ON b.name=d.name
 WHERE b.object_id=object_id(@tn,'U') IF @sql<>''
 EXEC(@sql);

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='CID'
)
BEGIN
	ALTER TABLE OrderIndex ADD CID int  NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE OrderIndex ADD Rate NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='billproperty'
)
BEGIN
	ALTER TABLE OrderIndex ADD billproperty INT NULL DEFAULT(-1)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='DealBTypeID'
)
BEGIN
	ALTER TABLE OrderIndex ADD DealBTypeID VARCHAR(50)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='PrePriceNum'
)
BEGIN
	ALTER TABLE dbo.OrderIndex ADD PrePriceNum INT DEFAULT(0) NOT NULL;
END
go


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='atypeID'
)
BEGIN
	ALTER TABLE dbo.OrderIndex ADD atypeID VARCHAR(50)  NULL DEFAULT('')
END
go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='totalinmoney'
)
BEGIN
	ALTER TABLE OrderIndex ADD totalinmoney NUMERIC(24,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='ntotalinmoney'
)
BEGIN
	ALTER TABLE OrderIndex ADD ntotalinmoney NUMERIC(24,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='IsYapi'
)
BEGIN
	ALTER TABLE dbo.OrderIndex ADD IsYapi BIT DEFAULT(0) NULL
	ALTER TABLE dbo.OrderIndex ADD YapiOrderID VARCHAR(20) DEFAULT('') NULL
END
go


--销售订单、采购订单增加 制单时间
IF NOT EXISTS (SELECT Name FROM SysColumns WHERE id=OBJECT_ID('OrderIndex') AND Name='checkTime')
BEGIN
	ALTER TABLE dbo.OrderIndex
	ADD checkTime DATETIME DEFAULT GETDATE()
END
GO
	UPDATE OrderIndex SET checkTime=BillDate WHERE checkTime IS NULl
GO

--增加扣率
IF NOT EXISTS (SELECT Name FROM SYSColumns WHERE ID=OBJECT_ID('OrderIndex') AND Name='Discount')
BEGIN
	ALTER TABLE dbo.OrderIndex
	Add Discount NUMERIC(22,10) DEFAULT(1)
END
GO

--承运单位增长
IF EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'OrderIndex',N'U') AND LOWER(Name)='tel')
BEGIN
	ALTER TABLE OrderIndex
	ALTER Column Tel VARCHAR(100) 
END
GO

--9.6.1运单号从20个字符升级为50个字符
IF EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'OrderIndex',N'U') AND LOWER(Name)='waybillcode' AND [Length]=20)
BEGIN
	ALTER TABLE dbo.OrderIndex
	ALTER COLUMN WayBillCode VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL
END
GO

--是否审核通过IfAudit，如果默认写成1，会导致需要审核的订单，在还没点确认是否送审前，就可以被调用，应该默认写成0，不允许被调用
IF EXISTS(SELECT name FROM sysobjects t WHERE id = (SELECT cdefault FROM syscolumns WHERE id = object_id(N'OrderIndex') AND name='IfAudit') AND name='DF_OrderIndex_IfAudit')
BEGIN	
	ALTER TABLE [dbo].[OrderIndex] DROP CONSTRAINT [DF_OrderIndex_IfAudit]	
	ALTER TABLE [dbo].[OrderIndex] ADD  CONSTRAINT [DF_OrderIndex_IfAudit]  DEFAULT ((0)) FOR [IfAudit]
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'NCIX_BILLTYPE')
	DROP INDEX [dbo].OrderIndex.NCIX_BILLTYPE
	
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'NCIX_FROMID')
	DROP INDEX [dbo].OrderIndex.NCIX_FROMID
	
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'NCIX_DTYPEID')
	DROP INDEX [dbo].OrderIndex.NCIX_DTYPEID
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'IX_OrderIndex_BillCode')
	DROP INDEX [IX_OrderIndex_BillCode] ON [dbo].[OrderIndex] 


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'IX_OrderIndex_BillDate')
DROP INDEX [IX_OrderIndex_BillDate] ON [dbo].[OrderIndex] 


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'IX_OrderIndex_BillNumberId')
DROP INDEX [IX_OrderIndex_BillNumberId] ON [dbo].[OrderIndex] 


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'IX_OrderIndex_btypeid')
DROP INDEX [IX_OrderIndex_btypeid] ON [dbo].[OrderIndex] 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'IX_OrderIndex_etypeid')
DROP INDEX [IX_OrderIndex_etypeid] ON [dbo].[OrderIndex] 


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[OrderIndex]') AND name = N'IX_OrderIndex_ktypeid')
DROP INDEX [IX_OrderIndex_ktypeid] ON [dbo].[OrderIndex] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERINDEX') AND name = 'CIX_ORDERINDEX_Billdate')
--DROP INDEX CIX_ORDERINDEX_Billdate ON ORDERINDEX 
CREATE CLUSTERED INDEX CIX_ORDERINDEX_Billdate ON ORDERINDEX(Billdate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERINDEX') AND name = 'NCIX_ORDERINDEX_BillNumberID')
--DROP INDEX NCIX_ORDERINDEX_BillNumberID ON ORDERINDEX 
CREATE NONCLUSTERED INDEX NCIX_ORDERINDEX_BillNumberID ON ORDERINDEX(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERINDEX') AND name = 'NCIX_ORDERINDEX_Btypeid')
--DROP INDEX NCIX_ORDERINDEX_Btypeid ON ORDERINDEX 
CREATE NONCLUSTERED INDEX NCIX_ORDERINDEX_Btypeid ON ORDERINDEX(Btypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERINDEX') AND name = 'NCIX_ORDERINDEX_Ktypeid')
--DROP INDEX NCIX_ORDERINDEX_Ktypeid ON ORDERINDEX 
CREATE NONCLUSTERED INDEX NCIX_ORDERINDEX_Ktypeid ON ORDERINDEX(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERINDEX') AND name = 'NCIX_ORDERINDEX_Etypeid')
--DROP INDEX NCIX_ORDERINDEX_Etypeid ON ORDERINDEX 
CREATE NONCLUSTERED INDEX NCIX_ORDERINDEX_Etypeid ON ORDERINDEX(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERINDEX') AND name = 'NCIX_ORDERINDEX_Dtypeid')
--DROP INDEX NCIX_ORDERINDEX_Dtypeid ON ORDERINDEX 
CREATE NONCLUSTERED INDEX NCIX_ORDERINDEX_Dtypeid ON ORDERINDEX(Dtypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERINDEX') AND name = 'NCIX_ORDERINDEX_Etypeid')
--DROP INDEX NCIX_ORDERINDEX_Etypeid ON ORDERINDEX 
CREATE NONCLUSTERED INDEX NCIX_ORDERINDEX_Etypeid ON ORDERINDEX(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ORDERINDEX') AND name = 'NCIX_ORDERINDEX_Billcode')
--DROP INDEX NCIX_ORDERINDEX_Billcode ON ORDERINDEX 
CREATE NONCLUSTERED INDEX NCIX_ORDERINDEX_Billcode ON ORDERINDEX(Billcode) 
GO
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE OrderBill
SET Tax=b.Tax
FROM OrderIndex b
WHERE OrderBill.BillNumberID=b.BillNumberID
AND OrderBill.Tax=0 AND b.Tax<>0
GO

UPDATE OrderBill
SET KTypeID=b.KTypeID
FROM OrderIndex b
WHERE OrderBill.BillNumberID=b.BillNumberID AND OrderBill.KTypeID IS NULL
GO



UPDATE OrderIndex
SET billproperty=-1
WHERE billproperty IS NULL
GO

UPDATE dbo.OrderIndex 
SET isyapi=0 WHERE isyapi IS NULL
GO


--更新历史数据制单时间到单据日期
UPDATE dbo.OrderIndex
SET checkTime=BillDate
WHERE checkTime IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='CustomerTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN CustomerTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='Ntotalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN Ntotalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='NCustomerTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN NCustomerTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OrderIndex 
	ALTER COLUMN Discount NUMERIC(24,10)
    END                                  
GO
--是否上传到WMS	
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='IsUploadWms'
    )
    BEGIN
	ALTER TABLE OrderIndex 
		ADD IsUploadWms INT DEFAULT(0)
    END
GO
UPDATE OrderIndex SET IsUploadWms = 0 WHERE IsUploadWms IS NULL   

--WMS单据号
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='OrderIndex' AND a.Name='WmsVchCode'
    )
    BEGIN
	ALTER TABLE OrderIndex 
		ADD WmsVchCode VARCHAR(50) NULL DEFAULT('')
    END
GO       
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OtherInOutBill]    脚本日期: 05/05/2010 14:48:03 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OtherInOutBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OtherInOutBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillType] INT NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_OtherInOutBill_Qty]  DEFAULT (0),
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OtherInOutBill_JobNumber]  DEFAULT (''),
		[GoodsNo] [int] NULL CONSTRAINT [DF_OtherInOutBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[comment] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_OtherInOutBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OtherInOutBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_OtherInOutBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_OtherInOutBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OtherInOutBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OtherInOutBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OtherInOutBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OtherInOutBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_OtherInOutBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_OtherInOutBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_OtherInOutBill_HandZeroCost]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_OtherInOutBill_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_OtherInOutBill_Total]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		UnitID               int             Default(0)  NULL,
		NUnitID              int             Default(0)  NULL,
		NQty                 numeric(22,10)  Default(0)  NULL,
		UnitRate             numeric(22,10)  Default(0)  NULL,
		NUnitMsg             varchar(50)          null,
		MUnitID              int             Default(0)  NULL,
		MQty                 numeric(22,10)  Default(0)  NULL,
		MUnitRate            numeric(22,10)  Default(0)  NULL,
		MUnitMsg             varchar(50)          null,
		MPrice               numeric(22,10)  Default(0)  NULL,
		CargoID				 INT			 DEFAULT(0) NULL,
		ItemID               bigint               null,
	   IsCombined           int                  null		
	   ,ShowOrder INT DEFAULT(0)
	   ,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
	   ,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
	   ,InFlowQty NUMERIC(24,10) NULL DEFAULT(0) --入库数量
	   ,InFactQty NUMERIC(24,10) NULL DEFAULT(0)
	   ,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'OtherInOutBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.OtherInOutBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'OtherInOutBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.OtherInOutBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'OtherInOutBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.OtherInOutBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.OtherInOutBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'OtherInOutBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.OtherInOutBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.OtherInOutBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'OtherInOutBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.OtherInOutBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.OtherInOutBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'OtherInOutBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE OtherInOutBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE OtherInOutBill SET PickedQty=0 WHERE PickedQty IS NULL
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'OtherInOutBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.OtherInOutBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.OtherInOutBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='UnitID')
BEGIN
	ALTER TABLE OtherInOutBill ADD UnitID  INT   NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='NUnitID')
BEGIN
	ALTER TABLE OtherInOutBill ADD NUnitID INT   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='NQty')
BEGIN
	ALTER TABLE OtherInOutBill ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='UnitRate')
BEGIN
	ALTER TABLE OtherInOutBill ADD UnitRate   numeric(22,10)     NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='NUnitMsg')
BEGIN
	ALTER TABLE OtherInOutBill ADD NUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='MUnitID')
BEGIN
	ALTER TABLE OtherInOutBill ADD MUnitID  INT   NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='MQty')
BEGIN
	ALTER TABLE OtherInOutBill ADD MQty   numeric(22,10)   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='MUnitRate')
BEGIN
	ALTER TABLE OtherInOutBill ADD MUnitRate   numeric(22,10)   NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='MUnitMsg')
BEGIN
	ALTER TABLE OtherInOutBill ADD MUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='MPrice')
BEGIN
	ALTER TABLE OtherInOutBill ADD MPrice   numeric(22,10)   NULL  DEFAULT(0)
END


IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='OtherInOutBill' AND a.Name='CargoID')
BEGIN
	ALTER TABLE OtherInOutBill ADD CargoID INT NULL DEFAULT(0)
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE OtherInOutBill ADD ItemID  BIGINT
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE OtherInOutBill ADD IsCombined   INT
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE OtherInOutBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0)
END


IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('OtherInOutBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table OtherInOutBill drop constraint '+@dfname);
		
	ALTER TABLE OtherInOutBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE OtherInOutBill ADD CONSTRAINT DF_OtherInOutBill_Serial DEFAULT('') FOR Serial
END


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='OtherInOutBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OTHERINOUTBILL') AND name = 'CIX_OTHERINOUTBILL_BillNumberID')
--DROP INDEX CIX_OTHERINOUTBILL_BillNumberID ON OTHERINOUTBILL 
CREATE CLUSTERED INDEX CIX_OTHERINOUTBILL_BillNumberID ON OTHERINOUTBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OTHERINOUTBILL') AND name = 'NCIX_OTHERINOUTBILL_Ptypeid')
--DROP INDEX NCIX_OTHERINOUTBILL_Ptypeid ON OTHERINOUTBILL 
CREATE NONCLUSTERED INDEX NCIX_OTHERINOUTBILL_Ptypeid ON OTHERINOUTBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OTHERINOUTBILL') AND name = 'NCIX_OTHERINOUTBILL_Ktypeid')
--DROP INDEX NCIX_OTHERINOUTBILL_Ktypeid ON OTHERINOUTBILL 
CREATE NONCLUSTERED INDEX NCIX_OTHERINOUTBILL_Ktypeid ON OTHERINOUTBILL(Ktypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OtherInOutBill' AND a.Name='MPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OtherInOutBill 
	ALTER COLUMN MPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[OtherInOutType]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[OtherInOutType]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OtherInOutType](
		[ID] INT IDENTITY(1,1), 
		[FullName] varchar(100) NOT NULL DEFAULT '',
		[ATypeID]  varchar(50) NOT NULL,
		[BillType] INT,
		[ATypeID1] varchar(50) NOT NULL DEFAULT '',
		[InOutType] INT, --出入类型,0:入库、1:出库、2:出入库。 AtypeID 出库科目，AtypeID1 入库科目
	) ON [PRIMARY]

END
GO


------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[OtherInOutType]') and name = 'BillType' )
BEGIN
	ALTER TABLE dbo.OtherInOutType ADD 
	BillType INT
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[OtherInOutType]') and name = 'ATypeID1' )
BEGIN
	ALTER TABLE dbo.OtherInOutType 
	ADD [ATypeID1] varchar(50) NOT NULL DEFAULT '';
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[OtherInOutType]') and name = 'InOutType' )
BEGIN
	ALTER TABLE dbo.OtherInOutType 
	ADD [InOutType] INT;
END
GO


IF NOT EXISTS (SELECT * FROM OtherInOutType)
BEGIN
	INSERT INTO OtherInOutType(FullName,ATypeID,ATypeID1,InOutType,BillType)VALUES ('其他出库业务类别','23','',1,202) --	0455
	INSERT INTO OtherInOutType(FullName,ATypeID,ATypeID1,InOutType,BillType)VALUES ('其他入库业务类别','','14',0,201) --	0333
END
ELSE 
BEGIN 
	--UPDATE dbo.OtherInOutType SET ATypeID = '23',ATypeID1='',InOutType=1 WHERE FullName = '其他出库业务类别' AND BillType = '202'
	--UPDATE dbo.OtherInOutType SET ATypeID = '',ATypeID1='14',InOutType=0 WHERE FullName = '其他入库业务类别' AND BillType = '201'
	
	UPDATE dbo.OtherInOutType SET ATypeID=CASE WHEN billtype=202 THEN atypeid ELSE '' END 
	,ATypeID1=CASE WHEN BillType=202 THEN '' ELSE 
		CASE WHEN ATypeID IS NOT NULL AND ATypeID<>'' THEN ATypeID ELSE atypeid1 END 
	END
	
	
	--处理升级
	UPDATE dbo.OtherInOutType SET InOutType=1 WHERE BillType = 202 AND InOutType IS NULL
	UPDATE dbo.OtherInOutType SET InOutType=0 WHERE BillType = 201 AND InOutType IS NULL
	
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[overflowBill]    脚本日期: 05/05/2010 14:48:45 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[overflowBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[overflowBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_overflowBill_Qty]  DEFAULT (0),
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_overflowBill_JobNumber]  DEFAULT (''),
		[GoodsNo] [int] NULL CONSTRAINT [DF_overflowBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_overflowBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_overflowBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_overflowBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_overflowBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OverFlowBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OverFlowBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OverFlowBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_OverFlowBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_OverFlowBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_OverFlowBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_OverFlowBill_HandZeroCost]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_OverFlowBill_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_OverFlowBill_Total]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		UnitID               int             Default(0)  NULL,
		NUnitID              int             Default(0)  NULL,
		NQty                 numeric(22,10)  Default(0)  NULL,
		UnitRate             numeric(22,10)  Default(0)  NULL,
		NUnitMsg             varchar(50)          null,
		MUnitID              int             Default(0)  NULL,
		MQty                 numeric(22,10)  Default(0)  NULL,
		MUnitRate            numeric(22,10)  Default(0)  NULL,
		MUnitMsg             varchar(50)          null,
		MPrice				 numeric(22,10)  Default(0)  NULL,
		CargoID				 INT			 DEFAULT(0) NULL,
		ItemID               bigint               null,
	    IsCombined           int                  null		
	    ,ShowOrder INT	DEFAULT(0)
	    ,InFactQty NUMERIC(24,10) DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),
		[ifWX] [int] NOT NULL DEFAULT(0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'overflowBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.overflowBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'overflowBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.overflowBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'overflowBill',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.overflowBill
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'overflowBill',N'U') AND Name='ifWX')
BEGIN
	ALTER TABLE dbo.overflowBill
	ADD [ifWX] [int] NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'overflowBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.overflowBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.overflowBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'overflowBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.overflowBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.overflowBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE overflowBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE overflowBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='UnitID')
BEGIN
		ALTER TABLE overflowBill ADD UnitID  INT   NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='NUnitID')
BEGIN
		ALTER TABLE overflowBill ADD NUnitID INT   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='NQty')
BEGIN
		ALTER TABLE overflowBill ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='UnitRate')
BEGIN
		ALTER TABLE overflowBill ADD UnitRate   numeric(22,10)     NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='NUnitMsg')
BEGIN
		ALTER TABLE overflowBill ADD NUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='MUnitID')
BEGIN
		ALTER TABLE overflowBill ADD MUnitID  INT   NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='MQty')
BEGIN
		ALTER TABLE overflowBill ADD MQty   numeric(22,10)   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='MUnitRate')
BEGIN
		ALTER TABLE overflowBill ADD MUnitRate   numeric(22,10)   NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='MUnitMsg')
BEGIN
		ALTER TABLE overflowBill ADD MUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='MPrice')
BEGIN
		ALTER TABLE overflowBill ADD MPrice   numeric(22,10)   NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='overflowBill' AND a.Name='CargoID')
BEGIN
	ALTER TABLE overflowBill ADD CargoID INT NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE overflowBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE overflowBill ADD IsCombined   INT
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('overflowBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table overflowBill drop constraint '+@dfname);
		
	ALTER TABLE overflowBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE overflowBill ADD CONSTRAINT DF_overflowBill_Serial DEFAULT('') FOR Serial

END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='overflowBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OVERFLOWBILL') AND name = 'CIX_OVERFLOWBILL_BillNumberID')
--DROP INDEX CIX_OVERFLOWBILL_BillNumberID ON OVERFLOWBILL 
CREATE CLUSTERED INDEX CIX_OVERFLOWBILL_BillNumberID ON OVERFLOWBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('OVERFLOWBILL') AND name = 'NCIX_OVERFLOWBILL_Ptypeid')
--DROP INDEX NCIX_OVERFLOWBILL_Ptypeid ON OVERFLOWBILL 
CREATE NONCLUSTERED INDEX NCIX_OVERFLOWBILL_Ptypeid ON OVERFLOWBILL(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='overflowBill' AND a.Name='MPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE overflowBill 
	ALTER COLUMN MPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PayBill]    脚本日期: 05/05/2010 14:48:46 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PayBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PayBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_PayBill_total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')	,
		 ntotal		numeric(22,10) null DEFAULT(0)	
		 ,ShowOrder INT DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PayBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.PayBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PayBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.PayBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PayBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.PayBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.PayBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PayBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE PayBill ADD STypeID VARCHAR(50) DEFAULT('')
		
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE PayBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PayBill' AND a.Name='VipCardID'
)
BEGIN
	ALTER TABLE PayBill ADD VipCardID INT NULL DEFAULT(-1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PayBill' AND a.Name='ntotal'
)
BEGIN
	ALTER TABLE PayBill ADD ntotal NUMERIC(22,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PayBill' AND a.Name='RelevanceBillId'
)
BEGIN
	ALTER TABLE PayBill ADD RelevanceBillId NUMERIC(10,0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PayBill]') AND name = N'IX_PayBill')
DROP INDEX [dbo].[PayBill].[IX_PayBill]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PAYBILL') AND name = 'CIX_PAYBILL_BillNumberID')
--DROP INDEX CIX_PAYBILL_BillNumberID ON PAYBILL 
CREATE CLUSTERED INDEX CIX_PAYBILL_BillNumberID ON PAYBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PAYBILL') AND name = 'NCIX_PAYBILL_Atypeid')
--DROP INDEX NCIX_PAYBILL_Atypeid ON PAYBILL 
CREATE NONCLUSTERED INDEX NCIX_PAYBILL_Atypeid ON PAYBILL(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PAYBILL') AND name = 'NCIX_PAYBILL_Stypeid')
--DROP INDEX NCIX_PAYBILL_Stypeid ON PAYBILL 
CREATE NONCLUSTERED INDEX NCIX_PAYBILL_Stypeid ON PAYBILL(Stypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE PayBill SET VipCardID = -1 WHERE VipCardID IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PayBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PayBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PayBill' AND a.Name='ntotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PayBill 
	ALTER COLUMN ntotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
--支付信息--time
IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'PayConfigInfo',N'U'))
BEGIN
	CREATE TABLE PayConfigInfo
	(
		ID	       INT IDENTITY(1,1),
		PID        VARCHAR(100) NOT NULL,
		AppID      VARCHAR(100) NOT NULL,
		KeyWord      VARCHAR(MAX) NULL,
		KeyWordPublic VARCHAR(MAX) NULL,
		PayType    INT	NOT NULL,
		UserCode        VARCHAR(200) NOT NULL,
		FullName        VARCHAR(200) NOT NULL,
		BankCardID    INT	 NULL,
		Comment        VARCHAR(250)  NULL,
		IsDefault	BIT	 DEFAULT(0)	NOT NULL
	)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PayConfigInfo]') and name = 'KeyWord' )
BEGIN
	ALTER TABLE dbo.PayConfigInfo ADD
		KeyWord VARCHAR(MAX) NULL
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PayConfigInfo]') and name = 'KeyWordPublic' )
BEGIN
	ALTER TABLE dbo.PayConfigInfo ADD
		KeyWordPublic VARCHAR(MAX) NULL
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PayConfigInfo]') and name = 'UserCode' )
BEGIN
	ALTER TABLE dbo.PayConfigInfo ADD
		UserCode VARCHAR(200) DEFAULT('') NOT NULL
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PayConfigInfo]') and name = 'FullName' )
BEGIN
	ALTER TABLE dbo.PayConfigInfo ADD
		FullName VARCHAR(200) DEFAULT('') NOT NULL
END

if exists (select name from syscolumns where id = object_id(N'[dbo].[PayConfigInfo]') and name = 'StypeID' )
BEGIN
	ALTER TABLE dbo.PayConfigInfo DROP COLUMN StypeID
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PayConfigInfo]') and name = 'BankCardID' )
BEGIN
	ALTER TABLE dbo.PayConfigInfo ADD
		BankCardID INT NULL
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PayConfigInfo]') and name = 'Comment' )
BEGIN
	ALTER TABLE dbo.PayConfigInfo ADD
		Comment VARCHAR(250)  NULL
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PayConfigInfo]') and name = 'IsDefault' )
BEGIN
	ALTER TABLE dbo.PayConfigInfo ADD
		IsDefault BIT DEFAULT(0) NOT NULL
END

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PayConfigInfo' AND a.Name='KeyWord'
    )
    BEGIN
	ALTER TABLE PayConfigInfo 
	ALTER COLUMN KeyWord VARCHAR(MAX)
    END
GO
--支付宝密匙长度
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PayConfigInfo' AND a.Name='alipaysigntype'
    )
    BEGIN
		ALTER TABLE PayConfigInfo 
			ADD alipaysigntype VARCHAR(10)
    END
GO
UPDATE PayConfigInfo SET alipaysigntype = '1' WHERE alipaysigntype IS NULL
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PayConfigInfo') AND name = 'CIX_PayConfigInfo_ID')
CREATE CLUSTERED INDEX CIX_PayConfigInfo_ID ON PayConfigInfo(ID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PayConfigInfo') AND name = 'NCIX_PayConfigInfo_PayType') 
CREATE NONCLUSTERED INDEX NCIX_PayConfigInfo_PayType ON PayConfigInfo(PayType) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PayConfigInfo') AND name = 'NCIX_PayConfigInfo_IsDefault')
CREATE NONCLUSTERED INDEX NCIX_PayConfigInfo_IsDefault ON PayConfigInfo(IsDefault) 
 
------------------------------------------创建索引区域结束-----------------------------------------------
GO

-------------Start处理之前的账户，默认处理为默认支付账户--------------

IF(SELECT COUNT(*) FROM PayConfigInfo WHERE PayType=1 AND UserCode='' AND FullName='' AND IsDefault=0)=1
BEGIN
	UPDATE PayConfigInfo SET UserCode='ZFB001', FullName='默认支付宝', IsDefault=1 WHERE PayType=1
END

IF(SELECT COUNT(*) FROM PayConfigInfo WHERE PayType=2 AND UserCode='' AND FullName='' AND IsDefault=0)=1
BEGIN
	UPDATE PayConfigInfo SET UserCode='WX001', FullName='默认微信商号',IsDefault=1 WHERE PayType=2
END
--IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'StypePayConfigInfo',N'U'))
--BEGIN
--	IF (SELECT COUNT(*) FROM StypePayConfigInfo)=0
--	BEGIN
--		DECLARE @payconfiginfoID INT;
--		IF EXISTS(SELECT TOP 1 1 FROM PayConfigInfo WHERE UserCode='ZFB001' AND FullName='默认支付宝'AND IsDefault=1 AND PayType=1)
--		BEGIN
--			SELECT @payconfiginfoID=ID FROM PayConfigInfo WHERE UserCode='ZFB001' AND FullName='默认支付宝'AND IsDefault=1 AND PayType=1
--			INSERT INTO StypePayConfigInfo VALUES(@payconfiginfoID,'00001')
--		END
--		IF EXISTS(SELECT TOP 1 1 FROM PayConfigInfo WHERE UserCode='WX001' AND FullName='默认微信商号'AND IsDefault=1 AND PayType=2)
--		BEGIN
--			SELECT @payconfiginfoID=ID FROM PayConfigInfo WHERE UserCode='WX001' AND FullName='默认微信商号'AND IsDefault=1 AND PayType=2
--			INSERT INTO StypePayConfigInfo VALUES(@payconfiginfoID,'00001')
--		END
--	END	
--END
-------------End处理之前的账户，默认处理为默认支付账户--------------
GO

-------Start处理了之前账户之后，删除default约束---------
DECLARE @sql NVARCHAR(MAX)
IF EXISTS(SELECT name 
FROM sys.default_constraints 
WHERE parent_object_id = object_id('PayConfigInfo')
AND type = 'D'
AND parent_column_id = (
    SELECT column_id 
    FROM sys.columns 
    WHERE object_id = object_id('PayConfigInfo')
    AND name = 'UserCode'
))
BEGIN
	SET @sql = N'alter table PayConfigInfo drop constraint ' + (SELECT name 
		FROM sys.default_constraints 
		WHERE parent_object_id = object_id('PayConfigInfo')
		AND type = 'D'
		AND parent_column_id = (
			SELECT column_id 
			FROM sys.columns 
			WHERE object_id = object_id('PayConfigInfo')
			AND name = 'UserCode'
		))
	EXEC sp_executesql @sql
END

IF EXISTS(SELECT name 
FROM sys.default_constraints 
WHERE parent_object_id = object_id('PayConfigInfo')
AND type = 'D'
AND parent_column_id = (
    SELECT column_id 
    FROM sys.columns 
    WHERE object_id = object_id('PayConfigInfo')
    AND name = 'FullName'
))
BEGIN
	SET @sql = N'alter table PayConfigInfo drop constraint ' + (SELECT name 
		FROM sys.default_constraints 
		WHERE parent_object_id = object_id('PayConfigInfo')
		AND type = 'D'
		AND parent_column_id = (
			SELECT column_id 
			FROM sys.columns 
			WHERE object_id = object_id('PayConfigInfo')
			AND name = 'FullName'
		))
	EXEC sp_executesql @sql
END
-------End处理了之前账户之后，删除default约束---------

GO




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PerformanceDistribution]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PerformanceDistribution](
		[BillNumberId] NUMERIC(18,0) NOT NULL,				--单据ID
		[ID] INT IDENTITY(1,1) NOT NULL,					--自增长ID
		[PTypeID] VARCHAR(50) NULL DEFAULT(''),				--商品ID
		[ETypeID] VARCHAR(50) NULL DEFAULT(''),				--职员ID
		[Proportion] NUMERIC(18,4) NULL DEFAULT(0),			--分配比例
		[Total] NUMERIC(18,4) NULL DEFAULT(0),				--分配金额(价税合计，之前的命名)
		[CreateDate] DATETIME NULL DEFAULT(GETDATE()),		--创建日期
		[Checke] VARCHAR(50) NULL DEFAULT(''),				--制单人（Sys_BaseInfoUsing_Tables需要加记录）
		[Comment] VARCHAR(500) NULL DEFAULT(''),			--分配备注
		DiscountTotal	NUMERIC(22,10) NOT NULL DEFAULT(0), --折后金额
		CostTotal	NUMERIC(22,10) NOT NULL DEFAULT(0),		--成本金额
		IsPtype	INT NOT NULL DEFAULT(1)						--0=商品 1=金额
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PerformanceDistribution]') and name = 'DiscountTotal' )
BEGIN
ALTER TABLE PerformanceDistribution ADD DiscountTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PerformanceDistribution]') and name = 'IsPtype' )
BEGIN
ALTER TABLE PerformanceDistribution ADD IsPtype INT NOT NULL DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PerformanceDistribution]') and name = 'CostTotal' )
BEGIN
ALTER TABLE PerformanceDistribution ADD CostTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PerformanceDistribution]') and name = 'BillComment' )
BEGIN
ALTER TABLE PerformanceDistribution ADD BillComment VARCHAR(500) NULL DEFAULT('')
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PerformanceDistribution]') and name = 'pid' )
BEGIN
ALTER TABLE PerformanceDistribution ADD pid VARCHAR(500) NULL DEFAULT('')
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PerformanceDistribution' AND a.Name='Proportion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PerformanceDistribution 
	ALTER COLUMN Proportion NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PerformanceDistribution' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PerformanceDistribution 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PerformanceDistribution' AND a.Name='DiscountTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PerformanceDistribution 
	ALTER COLUMN DiscountTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PerformanceDistribution' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PerformanceDistribution 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PersonalWorkTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].[PersonalWorkTable]
		(
			ETypeId		VARCHAR(50)  NOT NULL,
			MenuID		VARCHAR(100) NOT NULL,
			MenuName	VARCHAR(100) NOT NULL,
			LimitName	VARCHAR(100) NOT NULL,
			ShowOrder	INT			 NOT NULL DEFAULT 0
		) ON [PRIMARY]
	END
GO

------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('PhysicalInventoryConfig') AND type = 'U')
	BEGIN
		CREATE TABLE PhysicalInventoryConfig 
		(
			ID				INT IDENTITY(1,1),
			ETypeId			VARCHAR(50),
			InBillTypes		VARCHAR(500),
			OutBillTypes	VARCHAR(500)
		)
	END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PhysicalInventoryConfig' AND a.Name='InBillTypes'
)
BEGIN
	ALTER TABLE PhysicalInventoryConfig 
		ADD InBillTypes VARCHAR(500) NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PhysicalInventoryConfig' AND a.Name='OutBillTypes'
)
BEGIN
	ALTER TABLE PhysicalInventoryConfig 
		ADD OutBillTypes VARCHAR(500) NULL DEFAULT('')
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PhysicalInventoryConfig' AND a.Name='BillTypes'
)
BEGIN
	ALTER TABLE PhysicalInventoryConfig DROP COLUMN BillTypes
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
GO

------------------------------------------预制数据开始-------------------------------------------------
------------------------------------------预制数据结束-------------------------------------------------
GO




IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[pickbill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].pickbill(
		[billNumberID] [numeric](18, 0) NOT NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_pickbill_ptypeid]  DEFAULT ('0'),
		behooveQty	 [numeric](22, 10) NOT NULL CONSTRAINT [DF_pickbill_behooveQty]  DEFAULT (0),
		[qty] [numeric](22, 10) NOT NULL CONSTRAINT [DF_pickbill_qty]  DEFAULT (0),
		[comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_pickbill_comment]  DEFAULT (''),
		[GoodsBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[GoodsBillCode] VARCHAR(200) NULL DEFAULT(0),
		[GoodsBillID] [numeric](10, 0)  NULL DEFAULT (0),
		[GoodsBillType]	INT,
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_pickbill_GoodsNumber]  DEFAULT (''),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_pickbill_GoodsOrder]  DEFAULT ('-1'),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_pickbill_Serial]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_pickbill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_pickbill_ValidDate]  DEFAULT (''),
		[CargoID] INT DEFAULT(0),
		ShowOrder INT DEFAULT(0),
		MQty		NUMERIC(22,10),
		RMQty		NUMERIC(22,10),
		MUnitId		INT,
		MUnitRate	NUMERIC(22,10),
		UnitID		INT,
		BillQty		NUMERIC(22,10)
	) ON [PRIMARY]

END
GO

------------------------------------------表修改区域结束-------------------------------------------------
--货位号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='CargoID')
BEGIN
	ALTER TABLE dbo.pickbill
	ADD CargoID INT DEFAULT(0)
END
GO

--出库单号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='GoodsBillCode')
BEGIN
	ALTER TABLE dbo.pickbill
	ADD GoodsBillCode VARCHAR(200) NULL DEFAULT(0)
END
GO

--单位数量
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='BillQty')
BEGIN
	ALTER TABLE dbo.pickbill
	ADD BillQty NUMERIC(22,10) DEFAULT(0)
END
GO

--销售单位数量
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='MQty')
BEGIN
	ALTER TABLE dbo.pickbill
	ADD MQty NUMERIC(22,10) DEFAULT(0)
END
GO

--销售单位实捡数量
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='RMQty')
BEGIN
	ALTER TABLE dbo.pickbill
	ADD RMQty NUMERIC(22,10) DEFAULT(0)
END
GO

--销售单位id
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='MUnitId')
BEGIN
	ALTER TABLE dbo.pickbill
	ADD MUnitId INT DEFAULT(0)
END
GO

--销售单位换算率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='MUnitRate')
BEGIN
	ALTER TABLE dbo.pickbill
	ADD MUnitRate NUMERIC(22,10) NOT NULL DEFAULT(1)
END
GO

--单位id
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='UnitId')
BEGIN
	ALTER TABLE dbo.pickbill
	ADD UnitId INT DEFAULT(0)
END
GO

IF  EXISTS(SELECT length FROM SysColumns WHERE ID= OBJECT_ID(N'pickbill',N'U') AND Name='comment')
BEGIN
	alter table dbo.pickbill alter column comment varchar(256)

END
GO
------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('pickbill') AND name = 'CIX_pickbill_BillNumberID')
CREATE CLUSTERED INDEX CIX_pickbill_BillNumberID ON pickbill(BillNumberID)  
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PloyType]    脚本日期: 05/05/2010 14:48:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PloyType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PloyType](
		[ploytypeid] [int] IDENTITY(1,1) NOT NULL,
		[name] [varchar](60) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[deleted] [bit] NOT NULL CONSTRAINT [DF_PloyType_deleted]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PloyType]') AND name = N'PK_PloyTypeID')
ALTER TABLE [dbo].[PloyType] DROP CONSTRAINT [PK_PloyTypeID]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PLOYTYPE') AND name = 'CIX_PLOYTYPE_ploytypeid')
--DROP INDEX CIX_PLOYTYPE_ploytypeid ON PLOYTYPE 
CREATE CLUSTERED INDEX CIX_PLOYTYPE_ploytypeid ON PLOYTYPE(ploytypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not  exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SystemRebuildGuid]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

CREATE TABLE [dbo].[SystemRebuildGuid] (
	[RebuildGuid]  UNIQUEIDENTIFIER      DEFAULT NEWID()
) ON [PRIMARY]
GO

if not  exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CommonPosSaleIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[CommonPosSaleIndex] (
	[PosVchCode] [int] IDENTITY (1, 1) NOT NULL ,
	[BillCode] [varchar] (30) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[Branchid] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[BtypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[KtypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[Cashier] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[Salesman] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[VipCardID] [int] NOT NULL ,
	[Total] [numeric](24, 10) NOT NULL ,
	[BillDiscount] [numeric](24, 10) NOT NULL ,
	[Efface] [numeric](24, 10) NOT NULL ,
	[FinallyTotal] [numeric](24, 10) NOT NULL ,
	[PosID] [varchar] (30) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[SaleDate] [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[SaleTime] [varchar] (8) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[Draft] [int] NOT NULL ,
	[DraftVchcode] [int] NOT NULL ,
	[CashSum] [numeric](24, 10) NOT NULL ,
	[CreditSum] [numeric](24, 10) NOT NULL ,
	[ReplaceCashSum] [numeric](24, 10) NOT NULL ,
	[SaveAccountSum] [numeric](24, 10) NOT NULL ,
	[ChangeSum] [numeric](24, 10) NOT NULL ,
	[VipIntegral] [numeric](24, 10) NOT NULL,
        [BackGoodsVchCode] [int] not null,  
        [SGCXBillID] decimal(9) NOT NULL,
        [RetReplaceCashSum] [numeric](24, 10) NOT NULL ,
        [IsUpSend]  [int] not null   
) ON [PRIMARY]
GO
IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosSaleIndex]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosSaleIndex]
        (
          [PosVchCode] [int] IDENTITY(1, 1)
                             NOT NULL ,
          [BillCode] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [Branchid] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [BtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Cashier] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Salesman] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [VipCardID] [int] NOT NULL ,
          [Total] [numeric](24, 10) NOT NULL ,
          [BillDiscount] [numeric](24, 10) NOT NULL ,
          [Efface] [numeric](24, 10) NOT NULL ,
          [FinallyTotal] [numeric](24, 10) NOT NULL ,
          [PosID] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                NOT NULL ,
          [SaleDate] [varchar](10) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [SaleTime] [varchar](8) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Draft] [int] NOT NULL ,
          [DraftVchcode] [int] NOT NULL ,
          [CashSum] [numeric](24, 10) NOT NULL ,
          [CreditSum] [numeric](24, 10) NOT NULL ,
          [ReplaceCashSum] [numeric](24, 10) NOT NULL ,
          [SaveAccountSum] [numeric](24, 10) NOT NULL ,
          [ChangeSum] [numeric](24, 10) NOT NULL ,
          [VipIntegral] [numeric](24, 10) NOT NULL ,
          [BackGoodsVchCode] [int] NOT NULL ,
          [SGCXBillID] DECIMAL(9) NOT NULL ,
          [RetReplaceCashSum] [numeric](24, 10) NOT NULL ,
          [IsUpSend] [int] NOT NULL
        )
    ON  [PRIMARY]
GO
IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UpLoadPosVchCode'
                        AND [id] = OBJECT_ID('CommonPosSaleIndex') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleIndex] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosSaleIndex_UpLoadPosVchCode DEFAULT 0
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UniqueID'
                        AND [id] = OBJECT_ID('CommonPosSaleIndex') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleIndex] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleIndex_UniqueID DEFAULT ''
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosSaleIndexFreeze]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosSaleIndexFreeze]
        (
          [PosVchCode] [int] IDENTITY(1, 1)
                             NOT NULL ,
          [BillCode] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [Branchid] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [BtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Cashier] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Salesman] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [VipCardID] [int] NOT NULL ,
          [Total] [numeric](24, 10) NOT NULL ,
          [BillDiscount] [numeric](24, 10) NOT NULL ,
          [Efface] [numeric](24, 10) NOT NULL ,
          [FinallyTotal] [numeric](24, 10) NOT NULL ,
          [PosID] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                NOT NULL ,
          [SaleDate] [varchar](10) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [SaleTime] [varchar](8) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Draft] [int] NOT NULL ,
          [DraftVchcode] [int] NOT NULL ,
          [CashSum] [numeric](24, 10) NOT NULL ,
          [CreditSum] [numeric](24, 10) NOT NULL ,
          [ReplaceCashSum] [numeric](24, 10) NOT NULL ,
          [SaveAccountSum] [numeric](24, 10) NOT NULL ,
          [ChangeSum] [numeric](24, 10) NOT NULL ,
          [VipIntegral] [numeric](24, 10) NOT NULL ,
          [BackGoodsVchCode] [int] NOT NULL ,
          [SGCXBillID] DECIMAL(9) NOT NULL ,
          [RetReplaceCashSum] [numeric](24, 10) NOT NULL ,
          [IsUpSend] [int] NOT NULL
        )
    ON  [PRIMARY]
GO

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UpLoadPosVchCode'
                        AND [id] = OBJECT_ID('CommonPosSaleIndexFreeze') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleIndexFreeze] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosSaleIndexFreeze_UpLoadPosVchCode DEFAULT 0
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UniqueID'
                        AND [id] = OBJECT_ID('CommonPosSaleIndexFreeze') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleIndexFreeze] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleIndexFreeze_UniqueID DEFAULT ''
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosSaleList]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosSaleList]
        (
          [PosVchCode] [int] NOT NULL ,
          [ListID] [int] IDENTITY(1, 1)
                         NOT NULL ,
          [PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [ColorID] [int] NULL ,
          [SizeID] [int] NULL ,
          [Qty] [numeric](24, 10) NOT NULL ,
          [RetailPrice] [numeric](24, 10) NOT NULL ,
          [DisCount] [numeric](24, 10) NOT NULL ,
          [DisCountRate] [numeric](24, 10) NOT NULL ,
          [Price] [numeric](24, 10) NOT NULL ,
          [Sum] [numeric](24, 10) NOT NULL ,
          [IsPresent] [int] NOT NULL ,
          [CXBillID] [varchar](500) COLLATE Chinese_PRC_CI_AS
                                    NOT NULL ,
          [CXJFXS] [numeric](24, 10) NOT NULL , ----默认是填1
          [IsUpSend] [int] NOT NULL
        )
    ON  [PRIMARY]
GO

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UpLoadPosVchCode'
                        AND [id] = OBJECT_ID('CommonPosSaleList') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleList] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosSaleList_UpLoadPosVchCode DEFAULT 0
    END
GO
IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UniqueID'
                        AND [id] = OBJECT_ID('CommonPosSaleList') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleList] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleList_UniqueID DEFAULT ''
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosSaleListFreeze]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosSaleListFreeze]
        (
          [PosVchCode] [int] NOT NULL ,
          [ListID] [int] IDENTITY(1, 1)
                         NOT NULL ,
          [PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [ColorID] [int] NULL ,
          [SizeID] [int] NULL ,
          [Qty] [numeric](24, 10) NOT NULL ,
          [RetailPrice] [numeric](24, 10) NOT NULL ,
          [DisCount] [numeric](24, 10) NOT NULL ,
          [DisCountRate] [numeric](24, 10) NOT NULL ,
          [Price] [numeric](24, 10) NOT NULL ,
          [Sum] [numeric](24, 10) NOT NULL ,
          [IsPresent] [int] NOT NULL ,
          [CXBillID] [varchar](500) COLLATE Chinese_PRC_CI_AS
                                    NOT NULL ,
          [CXJFXS] [numeric](24, 10) NOT NULL ,----默认是填1
          [IsUpSend] [int] NOT NULL
        )
    ON  [PRIMARY]
GO
-------

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UpLoadPosVchCode'
                        AND [id] = OBJECT_ID('CommonPosSaleListFreeze') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleListFreeze] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosSaleListFreeze_UpLoadPosVchCode DEFAULT 0
    END
GO
IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UniqueID'
                        AND [id] = OBJECT_ID('CommonPosSaleListFreeze') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleListFreeze] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleListFreeze_UniqueID DEFAULT ''
    END
GO
---------------------------------------------------------------------------------------------------------------------------
--临时表开始
--

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosSaleIndexTemp]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosSaleIndexTemp]
        (
          [PosVchCode] [int] IDENTITY(1, 1)
                             NOT NULL ,
          [BillCode] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [BtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Cashier] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Salesman] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [VipCardID] [int] NOT NULL ,
          [Total] [numeric](24, 10) NOT NULL ,
          [BillDiscount] [numeric](24, 10) NOT NULL ,
          [Efface] [numeric](24, 10) NOT NULL ,
          [FinallyTotal] [numeric](24, 10) NOT NULL ,
          [PosID] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                NOT NULL ,
          [SaleDate] [varchar](10) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [SaleTime] [varchar](8) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Draft] [int] NOT NULL ,
          [DraftVchcode] [int] NOT NULL ,
          [CashSum] [numeric](24, 10) NOT NULL ,
          [CreditSum] [numeric](24, 10) NOT NULL ,
          [ReplaceCashSum] [numeric](24, 10) NOT NULL ,
          [SaveAccountSum] [numeric](24, 10) NOT NULL ,
          [ChangeSum] [numeric](24, 10) NOT NULL ,
          [VipIntegral] [numeric](24, 10) NOT NULL ,
          [BackGoodsVchCode] [int] NOT NULL ,
          [SGCXBillID] DECIMAL(9) NOT NULL ,
          [RetReplaceCashSum] [numeric](24, 10) NOT NULL ,
          [IsUpSend] [int] NOT NULL
        )
    ON  [PRIMARY]
GO
IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UpLoadPosVchCode'
                        AND [id] = OBJECT_ID('CommonPosSaleIndexTemp') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleIndexTemp] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosSaleIndexTemp_UpLoadPosVchCode DEFAULT 0
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UniqueID'
                        AND [id] = OBJECT_ID('CommonPosSaleIndexTemp') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleIndexTemp] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleIndexTemp_UniqueID DEFAULT ''
    END
GO

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CommonPosPtypeCheckNdx]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

CREATE TABLE [dbo].[CommonPosPtypeCheckNdx] (
	[CheckCode] [int] IDENTITY (1, 1) NOT NULL ,
	[KtypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[OperatorID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[PDDate]  [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[PosID] [varchar] (30) COLLATE Chinese_PRC_CI_AS NOT NULL ,
        [IsUpSend]  [int] not null  
) ON [PRIMARY]
GO

IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE NAME = 'PDNumber' AND [id] = object_id('CommonPosPtypeCheckNdx')) 
begin
	ALTER TABLE [CommonPosPtypeCheckNdx] ADD PDNumber VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosPtypeCheckNdx_PDNumber DEFAULT ''
end
GO


IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE NAME = 'PDVchCode' AND [id] = object_id('CommonPosPtypeCheckNdx')) 
begin
	ALTER TABLE [CommonPosPtypeCheckNdx] ADD PDVchCode INT NOT NULL CONSTRAINT DF_CommonPosPtypeCheckNdx_PDVchCode DEFAULT 0
end
GO

IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE NAME = 'UpLoadPosVchCode' AND [id] = object_id('CommonPosPtypeCheckNdx')) 
begin
	ALTER TABLE [CommonPosPtypeCheckNdx] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosPtypeCheckNdx_UpLoadPosVchCode DEFAULT 0
end
GO
IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE NAME = 'UniqueID' AND [id] = object_id('CommonPosPtypeCheckNdx')) 
begin
	ALTER TABLE [CommonPosPtypeCheckNdx] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosPtypeCheckNdx_UniqueID DEFAULT ''
end
GO



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CommonPosPtypeCheckList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

CREATE TABLE [dbo].[CommonPosPtypeCheckList] (
        [CheckCode] [int]  NOT NULL ,
	[CheckList] [int] IDENTITY (1, 1) NOT NULL ,
	[PtypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[ColorID] [int] NULL ,
	[SizeID] [int] NULL ,
	[Qty] [numeric](24, 10) NOT NULL ,
        [IsUpSend]  [int] not null  
) ON [PRIMARY]
GO



IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE NAME = 'UpLoadPosVchCode' AND [id] = object_id('CommonPosPtypeCheckList')) 
begin
	ALTER TABLE [CommonPosPtypeCheckList] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosPtypeCheckList_UpLoadPosVchCode DEFAULT 0
end
GO
IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE NAME = 'UniqueID' AND [id] = object_id('CommonPosPtypeCheckList')) 
begin
	ALTER TABLE [CommonPosPtypeCheckList] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosPtypeCheckList_UniqueID DEFAULT ''
end
GO

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosSaleIndexFreezeTemp]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosSaleIndexFreezeTemp]
        (
          [PosVchCode] [int] IDENTITY(1, 1)
                             NOT NULL ,
          [BillCode] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [BtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Cashier] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Salesman] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [VipCardID] [int] NOT NULL ,
          [Total] [numeric](24, 10) NOT NULL ,
          [BillDiscount] [numeric](24, 10) NOT NULL ,
          [Efface] [numeric](24, 10) NOT NULL ,
          [FinallyTotal] [numeric](24, 10) NOT NULL ,
          [PosID] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                NOT NULL ,
          [SaleDate] [varchar](10) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [SaleTime] [varchar](8) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Draft] [int] NOT NULL ,
          [DraftVchcode] [int] NOT NULL ,
          [CashSum] [numeric](24, 10) NOT NULL ,
          [CreditSum] [numeric](24, 10) NOT NULL ,
          [ReplaceCashSum] [numeric](24, 10) NOT NULL ,
          [SaveAccountSum] [numeric](24, 10) NOT NULL ,
          [ChangeSum] [numeric](24, 10) NOT NULL ,
          [VipIntegral] [numeric](24, 10) NOT NULL ,
          [BackGoodsVchCode] [int] NOT NULL ,
          [SGCXBillID] DECIMAL(9) NOT NULL ,
          [RetReplaceCashSum] [numeric](24, 10) NOT NULL ,
          [IsUpSend] [int] NOT NULL
        )
    ON  [PRIMARY]
GO

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UpLoadPosVchCode'
                        AND [id] = OBJECT_ID('CommonPosSaleIndexFreezeTemp') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleIndexFreezeTemp] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosSaleIndexFreezeTemp_UpLoadPosVchCode DEFAULT 0
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UniqueID'
                        AND [id] = OBJECT_ID('CommonPosSaleIndexFreezeTemp') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleIndexFreezeTemp] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleIndexFreezeTemp_UniqueID DEFAULT ''
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosSaleListTemp]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosSaleListTemp]
        (
          [PosVchCode] [int] NOT NULL ,
          [ListID] [int] IDENTITY(1, 1)
                         NOT NULL ,
          [PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [ColorID] [int] NULL ,
          [SizeID] [int] NULL ,
          [Qty] [numeric](24, 10) NOT NULL ,
          [RetailPrice] [numeric](24, 10) NOT NULL ,
          [DisCount] [numeric](24, 10) NOT NULL ,
          [DisCountRate] [numeric](24, 10) NOT NULL ,
          [Price] [numeric](24, 10) NOT NULL ,
          [Sum] [numeric](24, 10) NOT NULL ,
          [IsPresent] [int] NOT NULL ,
          [CXBillID] [varchar](500) COLLATE Chinese_PRC_CI_AS
                                    NOT NULL ,
          [CXJFXS] [numeric](24, 10) NOT NULL , ----默认是填1
          [IsUpSend] [int] NOT NULL
        )
    ON  [PRIMARY]
GO

IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UpLoadPosVchCode'
                        AND [id] = OBJECT_ID('CommonPosSaleListTemp') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleListTemp] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosSaleListTemp_UpLoadPosVchCode DEFAULT 0
    END
GO
IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UniqueID'
                        AND [id] = OBJECT_ID('CommonPosSaleListTemp') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleListTemp] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleListTemp_UniqueID DEFAULT ''
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosSaleListFreezeTemp]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosSaleListFreezeTemp]
        (
          [PosVchCode] [int] NOT NULL ,
          [ListID] [int] IDENTITY(1, 1)
                         NOT NULL ,
          [PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [ColorID] [int] NULL ,
          [SizeID] [int] NULL ,
          [Qty] [numeric](24, 10) NOT NULL ,
          [RetailPrice] [numeric](24, 10) NOT NULL ,
          [DisCount] [numeric](24, 10) NOT NULL ,
          [DisCountRate] [numeric](24, 10) NOT NULL ,
          [Price] [numeric](24, 10) NOT NULL ,
          [Sum] [numeric](24, 10) NOT NULL ,
          [IsPresent] [int] NOT NULL ,
          [CXBillID] [varchar](500) COLLATE Chinese_PRC_CI_AS
                                    NOT NULL ,
          [CXJFXS] [numeric](24, 10) NOT NULL ,----默认是填1
          [IsUpSend] [int] NOT NULL
        )
    ON  [PRIMARY]
GO
-------
  if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UserPowerRange]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[UserPowerRange] (
	[ListID] [int] NOT NULL ,
	[EtypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[TypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[BaseType] [tinyint] NOT NULL 
) ON [PRIMARY]
GO

-------
IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UpLoadPosVchCode'
                        AND [id] = OBJECT_ID('CommonPosSaleListFreezeTemp') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleListFreezeTemp] ADD UpLoadPosVchCode INT NOT NULL CONSTRAINT DF_CommonPosSaleListFreezeTemp_UpLoadPosVchCode DEFAULT 0
    END
GO
IF NOT EXISTS ( SELECT  *
                FROM    SYSCOLUMNS
                WHERE   NAME = 'UniqueID'
                        AND [id] = OBJECT_ID('CommonPosSaleListFreezeTemp') ) 
    BEGIN
        ALTER TABLE [CommonPosSaleListFreezeTemp] ADD UniqueID VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleListFreezeTemp_UniqueID DEFAULT ''
    END
GO
-----------------------------
--临时表完


IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CommonPosInfo]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[CommonPosInfo]
        (
          [PosID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                NOT NULL
                                PRIMARY KEY ,
          [FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS
                                   NULL ,
          [Branchid] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [ETypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [Stockid] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [BTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [deleted] [int] NOT NULL ,
          [IsKeyset] [int] NOT NULL ,					--会员卡号不支持键盘输入  0是 1否
          [IsHeadquartersStock] [int] NOT NULL ,		--允许查看总部其它仓库库存 0是 1否
          [IsJoinStock] [int] NOT NULL ,				--允许查看其它加盟商库存   0是 1否
          [PosPassword] [varchar](25) COLLATE Chinese_PRC_CI_AS
                                      NOT NULL ,	--POS密码
          [Possessive] [INT]
            NOT NULL
            CONSTRAINT [DF_CommonPosInfo_Possessive] DEFAULT ( 0 ) ,--被POS客户端占有状态，初始建立时该值为0.
          [Comment] [varchar](100) COLLATE Chinese_PRC_CI_AS
                                   NULL ,
          [IsTicketCount] INT
            NOT NULL
            CONSTRAINT DF_CommonPosInfo_IsTicketCount DEFAULT ( 1 ) , --存为小票 或者 直接过账 0--存为小票 1--直接过账
          [cBYZD1] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                 NULL ,
          [cBYZD2] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                 NULL ,
          [iBYZD1] INT NULL ,
          [iBYZD2] INT NULL ,
          [nBYZD1] [numeric](24, 10) NULL ,
          [nBYZD2] [numeric](24, 10) NULL
        )
    ON  [PRIMARY]
GO

/*--------------------------------------
--------------序列号------------------*/
IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE NAME = 'ListRow' AND [id] = object_id('CommonPosSaleList')) 
begin
	ALTER TABLE [CommonPosSaleList] ADD ListRow VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleList_ListRow DEFAULT ''
end
GO

IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE NAME = 'ListRow' AND [id] = object_id('CommonPosSaleListFreeze')) 
begin
	ALTER TABLE [CommonPosSaleListFreeze] ADD ListRow VARCHAR(50) NOT NULL CONSTRAINT DF_CommonPosSaleListFreeze_ListRow DEFAULT ''
end
GO
/*------------------------------------*/

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[PosCommonSysData]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[PosCommonSysData]
        (
          [SysID] [int] NOT NULL ,
          [SysName] [varchar](30) COLLATE Chinese_PRC_CI_AS
                                  NOT NULL ,
          [SysValue] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                   NOT NULL ,
          [SysComment] [varchar](60) COLLATE Chinese_PRC_CI_AS
                                     NULL,
        )
    ON  [PRIMARY]
GO

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[PosVipMoneyList]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    CREATE TABLE [dbo].[PosVipMoneyList]
        (
          [BillnumberID] [numeric](9, 0) IDENTITY(1, 1)
                                         NOT NULL ,
          [PosVchcode] [int] NOT NULL ,   --关联主表字段 CommonPosSaleIndex中的PosVchCode
          [VipID] [int] NOT NULL ,        --Vip号
          [SaveAccountSum] [numeric](24, 10) NOT NULL --刷卡消费金额
        )
    ON  [PRIMARY]
GO

IF NOT EXISTS ( SELECT  1
                FROM    PosCommonSysData
                WHERE   sysid = 1 ) 
    INSERT  INTO PosCommonSysData
            ( sysid ,
              [sysname] ,
              sysValue ,
              SysComment
            )
    VALUES  ( 1 ,
              'MainDBVersionnoDetail' ,
              '20110813' ,
              '控制是否升级主程序数据库'
            )
GO

IF NOT EXISTS ( SELECT  1
                FROM    PosCommonSysData
                WHERE   sysid = 2 ) 
    INSERT  INTO PosCommonSysData
            ( sysid ,
              [sysname] ,
              sysValue ,
              SysComment
            )
    VALUES  ( 2 ,
              'MainProgramName' ,
              'Pos_A8' ,
              '链接的主程序版本'
            ) 
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='BillDiscount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN BillDiscount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='Efface' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN Efface NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='FinallyTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN FinallyTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='CashSum' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN CashSum NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='CreditSum' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN CreditSum NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='ReplaceCashSum' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN ReplaceCashSum NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='SaveAccountSum' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN SaveAccountSum NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='ChangeSum' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN ChangeSum NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='VipIntegral' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN VipIntegral NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='RetReplaceCashSum' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN RetReplaceCashSum NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='RetailPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN RetailPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='DisCount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN DisCount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='DisCountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN DisCountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='Sum' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN Sum NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='CXJFXS' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN CXJFXS NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='nBYZD1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN nBYZD1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Pos_A8_tables' AND a.Name='nBYZD2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Pos_A8_tables 
	ALTER COLUMN nBYZD2 NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_AdvertisementPic]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Pos_AdvertisementPic
	(
	   posid INT ,
	   pic image,
	   [uniquename] varchar(100),
	   ORDERID INT IDENTITY(1,1),
	   imgtype VARCHAR(30),
	   imgname VARCHAR(200),
	   random VARCHAR(100),
	   updatetime DATETIME NOT NULL DEFAULT(GETDATE())
	)
END
go




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_PicUpdateRecord]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE Pos_PicUpdateRecord
	(
		pid INT NOT NULL PRIMARY KEY,
		updatenumber NUMERIC(18,0) NOT NULL DEFAULT(1)
	)
END
go










SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_UploadPicRecord]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

	CREATE TABLE Pos_UploadPicRecord
	(
		posid INT NOT NULL ,
	    pid INT NOT NULL,
		lastupdatenumber NUMERIC(18,0)  NOT NULL DEFAULT(1)
	)
END
go






SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[POSAccount]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE POSAccount(
		Id INT  PRIMARY KEY IDENTITY(1,1) ,	
		ntypeid VARCHAR(50), --账户typeid
		nid    INT,		--账户ID			
		Fullname VARCHAR(200), --账户姓名
		Usercode VARCHAR(200),--账户编号
		Comment VARCHAR(500),    --备注
		Posid   INT 
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='POSAccount' AND a.Name='Posid'
)
BEGIN
	ALTER TABLE POSAccount 
		ADD Posid INT NULL DEFAULT(1)
END
GO

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSAccount',N'U') AND Name='Fullname')
BEGIN
	ALTER TABLE POSAccount 
		DROP COLUMN Fullname
END

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSAccount',N'U') AND Name='Usercode')
BEGIN
	ALTER TABLE POSAccount 
		DROP COLUMN Usercode
END

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSAccount',N'U') AND Name='Comment')
BEGIN
	ALTER TABLE POSAccount 
		DROP COLUMN Comment
END
------------------------------------------表修改区域结束-------------------------------------------------




/****** 对象:  Table [dbo].[BillIndex]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PosAllotApplyBill]') AND type in (N'U'))
BEGIN
	CREATE TABLE PosAllotApplyBill
	(
		ID				INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
		BillNumberId	NUMERIC(18,0) NOT NULL,
		ptypeid			VARCHAR(200) NOT NULL,
		qty				NUMERIC(24,10)	NOT NULL DEFAULT(0),
		BaseUnitid		INT NULL,
		MUnitid			INT,
		MUnitRate		NUMERIC(24,10)	NOT NULL DEFAULT(1),
		MQty			NUMERIC(24,10)	NOT NULL DEFAULT(0),
		KtypeId			VARCHAR(50) NULL,						--出库仓库
		InKtypeId		VARCHAR(50)	NULL,						--入库仓库
		ItemId			INT NULL,
		IsCombined		INT NULL,
		comment			VARCHAR(250) NULL,
		BillOver		INT	NOT NULL DEFAULT(0),				--是否中止 0，否：1，是
		StopReason		VARCHAR(200) DEFAULT(''),				--终止原因,
		CallQty			NUMERIC(24,10) DEFAULT(0)				--调用数量
	)
END

--申请的商品单位
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBill',N'U') AND Name='unitid')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBill
		ADD unitid INT NULL
END
GO
--中止状态
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBill',N'U') AND Name='BillOver')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBill
		ADD BillOver INT NOT NULL DEFAULT(0)
END
GO
--中止原因
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBill',N'U') AND Name='StopReason')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBill
		ADD StopReason VARCHAR(200) DEFAULT('')
END


--调用数量
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBill',N'U') AND Name='CallQty')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBill
		ADD CallQty NUMERIC(24,10) DEFAULT(0)
END
	
GO


--大单位id
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBill',N'U') AND Name='MUnitid')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBill
		ADD MUnitid int
END
	
GO
--大单位换算率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBill',N'U') AND Name='MUnitRate')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBill
		ADD MUnitRate NUMERIC(24,10) not null DEFAULT(1)
END
	
GO
--大单位数量
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBill',N'U') AND Name='MQty')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBill
		ADD MQty NUMERIC(24,10) not null DEFAULT(0)
END
	
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PosAllotApplyBillIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE PosAllotApplyBillIndex
	(
		BillNumberId	NUMERIC(18, 0) IDENTITY(1,1) NOT NULL,
		BillType		INT NOT NULL,
		BillCode		VARCHAR(200) NOT NULL,					--单据编码
		BillDate		DATETIME NOT NULL,						--单据日期
		ApplyEtypeId	VARCHAR(200) NOT NULL,					--申请人
		StypeId			VARCHAR(50) NOT NULL DEFAULT('00001'),	--分支机构
		DtypeId			VARCHAR(50) NOT NULL,					--部门
		KtypeId			VARCHAR(50) NULL,						--出库仓库
		InKtypeId		VARCHAR(50)	NULL,						--入库仓库
		Qty				DECIMAL(24,10) NULL,					--数量
		Comment			VARCHAR(256) NULL,						--备注
		Explain			VARCHAR(256) NULL,						--摘要
		BillState		INT NOT NULL DEFAULT(0),				--0,草稿；1,已审核；2,已接受；3,已拒绝；4,已生单；5,已作废
		checkE			VARCHAR(200) NULL,						--制作人
		checkTime		DATETIME NULL,							--制单时间
		IsAutoGenerate  INT NOT NULL DEFAULT(0),                --是否为自动生成的单据 0，否；1，是
		BillOver		INT	NOT NULL DEFAULT(0),				--是否中止 0，否：1，是
		StopReason		VARCHAR(200) DEFAULT(''),				--终止原因
		Isdone			TINYINT	DEFAULT(0)	,					--是否完成，0表示没完成，1表示完成
        Checker			VARCHAR(200) NULL,						--审核人
		CheckerTime		DATETIME NULL,							--审核时间
		Updater			VARCHAR(200) NULL,						--修改人
		UpdaterTime		DATETIME NULL,						--修改时间
		IsIni			BIT NULL DEFAULT(0),
		CID				int	,									--币种
		Total			DECIMAL(24,10) NULL	 DEFAULT(0)	,				--金额
		IsNeedTransport	bit null default(0)	,--是否需要运输
		WarehouseOutDay [int] NULL DEFAULT (9999),--出库期限
		LinkMan [varchar](256)  NULL    DEFAULT (''), --收货人
		LinkTe [varchar](256)  NULL  DEFAULT (''), --电话
		LinkAddr [varchar](256) NULL  DEFAULT (''), --地址
		InFactState       INT DEFAULT(0),	  --1 仓库入库未完成 2仓库入库已完成
		InFactRefState    INT DEFAULT(0),    -- 0仓库入库未引用  1仓库入库已引用
		OutFactState	  INT DEFAULT(0),	  --1 仓库出库未完成 2仓库出库已完成	
		OutFactRefState   INT DEFAULT(0),	  --0 仓库出库未引用 1仓库出库已引用
		AtId			  int DEFAULT(0),
		progressstate int NOT NULL DEFAULT(0),				--0=已开单1=拣货中2=已出库
		TransPortState INT NOT NULL DEFAULT(0)	,			--运输状态 0=已开单，1=发运中，2=已发运
		RedReason VARCHAR(256) NULL,
		PosId INT NOT NULL DEFAULT(0),				--POS端ID(用于区分erp和pos做单)
		PostTime  DATETIME NULL, --过账时间
	)
END
GO
--POS端ID
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='PosId')
	BEGIN
			ALTER TABLE dbo.PosAllotApplyBillIndex
			ADD PosId INT NOT NULL DEFAULT(0)
	END
GO
UPDATE PosAllotApplyBillIndex SET PosId = 0 WHERE PosId IS NULL
GO

--是否需要运输
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='IsNeedTransport')
	BEGIN
			ALTER TABLE dbo.PosAllotApplyBillIndex
			ADD IsNeedTransport bit NULL	DEFAULT(0)
	END
GO

--金额
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='Total')
	BEGIN
			ALTER TABLE dbo.PosAllotApplyBillIndex
			ADD Total DECIMAL(24,10) NULL	DEFAULT(0)
	END
GO

--币种
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='CID')
	BEGIN
			ALTER TABLE dbo.PosAllotApplyBillIndex
			ADD CID int	
	END
GO

update PosAllotApplyBillIndex set cid = (select CId from Ac_Currency where Sysrow = 1)
where cid is null
go
	
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='IsAutoGenerate')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBillIndex
		ADD IsAutoGenerate INT NOT NULL DEFAULT(0)
END
GO

--制单时间
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='checkTime')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBillIndex
		ADD checkTime DATETIME NULL
END
GO

--中止状态
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='BillOver')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBillIndex
		ADD BillOver INT NOT NULL DEFAULT(0)
END
GO


--中止原因
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='StopReason')
BEGIN
		ALTER TABLE dbo.PosAllotApplyBillIndex
		ADD StopReason VARCHAR(200) DEFAULT('')
END
GO

--是否完成
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='Isdone')
	BEGIN
			ALTER TABLE dbo.PosAllotApplyBillIndex
			ADD Isdone TINYINT	DEFAULT(0)
	END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='RedWord'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD RedWord INT NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='ifcheck'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD ifcheck  [char](1)  NULL  DEFAULT ('t')
END
GO
UPDATE PosAllotApplyBillIndex SET IfCheck = 'f' WHERE IfCheck IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='draft'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD draft [bit]  not NULL  DEFAULT (0)
END
GO
UPDATE PosAllotApplyBillIndex SET draft = '0' WHERE draft IS NULL
GO

-- 审核人
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='Checker'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD Checker VARCHAR(200) NULL
END
GO

-- 审核时间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='CheckerTime'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD CheckerTime DATETIME NULL
END
GO

-- 修改人
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='Updater'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD Updater VARCHAR(200) NULL
END
GO

-- 修改时间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='UpdaterTime'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD UpdaterTime DATETIME NULL
END
GO

-- 是否为期初
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD IsIni BIT NULL DEFAULT(0)	
END
GO
UPDATE PosAllotApplyBillIndex SET IsIni = 0 WHERE IsIni IS NULL
GO

-- 年结存
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='ifYearBill'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD ifYearBill int NULL DEFAULT(0)	
END
GO
UPDATE PosAllotApplyBillIndex SET ifYearBill = 0 WHERE ifYearBill IS NULL
GO

-- 是否按成本配送
IF NOT EXISTS(
  SELECT a.Name FROM syscolumns a
  INNER JOIN sysobjects  b
  ON a.ID=b.ID
  WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='costsale'
)
BEGIN
  ALTER TABLE PosAllotApplyBillIndex 
    ADD costsale int NULL DEFAULT(0)  
END
GO
UPDATE PosAllotApplyBillIndex SET costsale = 0 WHERE costsale IS NULL
GO

--出库期限
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='WarehouseOutDay'
)
BEGIN
	ALTER TABLE dbo.PosAllotApplyBillIndex ADD [WarehouseOutDay] int NULL DEFAULT(9999)
END
go
UPDATE PosAllotApplyBillIndex SET WarehouseOutDay = 9999 WHERE WarehouseOutDay IS NULL
GO



--联系人
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='LinkMan'
)
BEGIN
	ALTER TABLE dbo.PosAllotApplyBillIndex ADD LinkMan VARCHAR(256)NULL
END
go

--电话
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='LinkTel'
)
BEGIN
	ALTER TABLE dbo.PosAllotApplyBillIndex ADD LinkTel VARCHAR(256)NULL
END
go


--地址
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='LinkAddr'
)
BEGIN
	ALTER TABLE dbo.PosAllotApplyBillIndex ADD LinkAddr VARCHAR(256) NULL
END
go

--红冲原因
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='RedReason'
)
BEGIN
	ALTER TABLE dbo.PosAllotApplyBillIndex ADD RedReason VARCHAR(256) NULL
END
go

--实物出入库状态
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='InFactRefState')
BEGIN
	ALTER TABLE PosAllotApplyBillIndex
	ADD InFactRefState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='OutFactRefState')
BEGIN
	ALTER TABLE PosAllotApplyBillIndex
	ADD OutFactRefState INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='InFactState')
BEGIN
	ALTER TABLE PosAllotApplyBillIndex
	ADD InFactState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='OutFactState')
BEGIN
	ALTER TABLE PosAllotApplyBillIndex
	ADD OutFactState INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='AtId')
BEGIN
	ALTER TABLE PosAllotApplyBillIndex
	ADD AtId INT DEFAULT(0)
END
GO

--处理进度
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='progressstate')
BEGIN
	ALTER TABLE PosAllotApplyBillIndex 
	ADD progressstate INT NULL DEFAULT(0)
END
GO

--配送状态
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosAllotApplyBillIndex',N'U') AND Name='TransPortState')
BEGIN
	ALTER TABLE PosAllotApplyBillIndex
	ADD TransPortState INT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosAllotApplyBillIndex' AND a.Name='PostTime'
)
BEGIN
	ALTER TABLE PosAllotApplyBillIndex ADD PostTime DATETIME NULL 
END
GO

	UPDATE dbo.PosAllotApplyBillIndex SET InFactState=0 WHERE InFactState IS NULL
	UPDATE dbo.PosAllotApplyBillIndex SET OutFactState=0 WHERE OutFactState IS NULL
	UPDATE dbo.PosAllotApplyBillIndex SET InFactRefState=0 WHERE InFactRefState IS NULL
	UPDATE dbo.PosAllotApplyBillIndex SET OutFactRefState=0 WHERE OutFactRefState IS NULL
GO





SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT 1 FROM sysobjects WHERE id=OBJECT_ID('PosDataUpdated') AND type='U')
BEGIN
	CREATE TABLE PosDataUpdated
	(
		ID int IDENTITY(1,1) NOT NULL,
		UpdateDateTime datetime  NULL,
		UpdateDataList varchar(1000) NULL,
		AllDataList	VARCHAR(1000) NULL,
		stypeid VARCHAR(50) NULL,
		folder VARCHAR(32) NULL
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosDataUpdated' AND a.Name='folder'
)
BEGIN
	ALTER TABLE PosDataUpdated 
		ADD folder VARCHAR(32) NULL
END

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PosDataUpdated') AND name = 'NCIX_PosDataUpdated_UpdateDateTime')
	--DROP INDEX NCIX_PosDataUpdated_UpdateDateTime ON PosDataUpdated 
CREATE NONCLUSTERED INDEX NCIX_PosDataUpdated_UpdateDateTime ON PosDataUpdated(UpdateDateTime) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PosDataUpdated') AND name = 'NCIX_PosDataUpdated_Stypeid')
	--DROP INDEX NCIX_PosDataUpdated_Stypeid ON PosDataUpdated 
CREATE NONCLUSTERED INDEX NCIX_PosDataUpdated_Stypeid ON PosDataUpdated(STypeId) 
GO
------------------------------------------创建索引区域结束-----------------------------------------------

SET ANSI_PADDING OFF
GO






------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[POSEmployee]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE POSEmployee(
		Id INT  PRIMARY KEY IDENTITY(1,1) ,	
		Etypeid VARCHAR(50), --职员typeid
		Eid    INT,		--职员ID			
		Efullname VARCHAR(200), --职员姓名
		Eusercode VARCHAR(200),--职员编号
		Comment VARCHAR(500)    --备注
	)
END
GO


------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='POSEmployee' AND a.Name='Posid'
)
BEGIN
	ALTER TABLE POSEmployee 
		ADD Posid INT NULL DEFAULT(1)
END
GO

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSEmployee',N'U') AND Name='Efullname')
BEGIN
	ALTER TABLE POSEmployee 
		DROP COLUMN Efullname
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSEmployee',N'U') AND Name='Eusercode')
BEGIN
	ALTER TABLE POSEmployee 
		DROP COLUMN Eusercode
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSEmployee',N'U') AND Name='Comment')
BEGIN
	ALTER TABLE POSEmployee 
		DROP COLUMN Comment
END
GO 
------------------------------------------表修改区域结束-------------------------------------------------



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/************************************************
描    述：Pos流水号自定义配置表
创 建 人：罗淮文
创建日期：2016-03-03
*************************************************/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PosFlowNoConfig]') AND type in (N'U'))
BEGIN
	CREATE TABLE PosFlowNoConfig
	(
		ID				INT IDENTITY(1,1) NOT NULL,			--主键ID
		PosCode			VARCHAR(200),						--POS机编号
		IsDiy			INT DEFAULT(0),						--是否为自定义设置
		FlowNoLen		INT,								--流水号长度
		FlowNoStartVal	INT,								--流水号起始值
		SplitSign		VARCHAR(3)							--分隔符
	)
END
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/************************************************
描    述：Pos流水号前缀自定义配置表
创 建 人：罗淮文
创建日期：2016-03-03
*************************************************/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PosFlowNoPrefix]') AND type in (N'U'))
BEGIN
	CREATE TABLE PosFlowNoPrefix
	(
		ID				INT IDENTITY(1,1) NOT NULL,			--主键ID
		FlowNoConfigID	INT,								--POS流水号配置ID
		PrefixCode		INT,								--前缀编码
		PrefixType		INT,								--前缀类型
		PrefixLen		INT,								--前缀长度
		PrefixVal		VARCHAR(20),						--前缀值
		IsEnabled		INT									--是否启用
	)
END
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PosInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PosInfo
	(
		PosID			INT IDENTITY(1,1) NOT NULL,
		UserCode		VARCHAR(200) NULL,
		FullName		VARCHAR(200) NULL,
		ktypeid			varchar(50),
		stypeid			varchar (50),
		BtypeID			VARCHAR(50) NULL, --对应客户
		BankCardID		INT NULL,--银行卡对应项目
		CashID			INT NULL,--现金对应项目
		VIPMoneyID		INT NULL,--储值对应项目
		IsBinding		INT	NULL DEFAULT(0),	
		MacAddress		VARCHAR(100) NULL DEFAULT(''),	
		STATE			INT DEFAULT(0) NULL,	
		Comment			VARCHAR(500) NULL,
		PyCode			VARCHAR(100) NULL,
		PassType		INT NOT NULL DEFAULT(0),--POS客户端过账方式；0：日结后传输过账 1：即时过账：
		XiWaMaxNumber   INT NULL DEFAULT 1,
		canclezeroway INT NOT NULL DEFAULT(0),	  
		canclezerotype INT NOT NULL DEFAULT(0),
		lowlowestsaleprice INT NOT NULL DEFAULT(0),
		lowlastbuyprice INT NOT NULL DEFAULT(0),
		highhighestsaleprice INT NOT NULL DEFAULT(0),
		codesearchway INT NOT NULL DEFAULT(0),
		stockqueryrange INT NOT NULL DEFAULT(0),
		permitmakevipcard INT NOT NULL DEFAULT(0),
		permitvipcardrecharge INT NOT NULL DEFAULT(0),
		permitshowbatchno INT NOT NULL DEFAULT(0),
		permitshowbatchtime INT NOT NULL DEFAULT(0),
		permitsavenonnumber INT NOT NULL DEFAULT(0),
		autoshowpromote INT NOT NULL DEFAULT(0),
		rememberemployee int  NOT NULL DEFAULT(0)
		
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosInfo',N'U') AND Name='permitshowbtype')
BEGIN
	ALTER TABLE dbo.PosInfo
	ADD permitshowbtype INT  NOT NULL DEFAULT(1)			--品牌应收影响是否能挂往来,默认可以
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosInfo',N'U') AND Name='CouponMoneyID')
BEGIN
	ALTER TABLE dbo.PosInfo
	ADD CouponMoneyID INT  NOT NULL DEFAULT(78)			--优惠券对应项目Ac_Items nid=78
END
GO

UPDATE dbo.PosInfo SET CouponMoneyID=(SELECT nid FROM dbo.Ac_Items WHERE UserCode='2191'	AND FullName='『优惠券』')
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosInfo',N'U') AND Name='prepricenum')
BEGIN
	ALTER TABLE dbo.PosInfo
	ADD prepricenum INT NOT NULL DEFAULT(11)--适用预设价格,默认为零售价
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosInfo',N'U') AND Name='barcodetype')
BEGIN
	ALTER TABLE dbo.PosInfo
	ADD barcodetype INT NOT NULL DEFAULT(0)--条码默认携带
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosInfo',N'U') AND Name='ForeFroegroundStock')
BEGIN
	ALTER TABLE dbo.PosInfo
	ADD ForeFroegroundStock INT NOT NULL DEFAULT(0)--启用库存严格控制
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosInfo',N'U') AND Name='autogenerate')
BEGIN
	ALTER TABLE dbo.PosInfo
	ADD autogenerate INT NOT NULL DEFAULT(0)--Pos生单自动生成批次批号
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosInfo',N'U') AND Name='AllowTransferGoods')
BEGIN
	ALTER TABLE dbo.PosInfo
	ADD AllowTransferGoods INT NOT NULL DEFAULT(0)
END

IF NOT EXISTS (SELECT 1 FROM SysColumns WHERE ID = OBJECT_ID(N'[dbo].[PosInfo]',N'U') AND Name = 'alipayid' )
BEGIN
	ALTER TABLE dbo.PosInfo 
	ADD	alipayid INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT 1 FROM SysColumns WHERE ID = OBJECT_ID(N'[dbo].[PosInfo]',N'U') AND Name = 'allinpayid' )
BEGIN
	ALTER TABLE dbo.PosInfo 
	ADD	allinpayid INT NOT NULL DEFAULT(0)
END
GO

UPDATE PosInfo SET alipayid=0 WHERE alipayid IS NULL
GO
IF NOT EXISTS (SELECT 1 FROM SysColumns WHERE ID = OBJECT_ID(N'[dbo].[PosInfo]',N'U') AND Name = 'wxpayid' )
BEGIN
	ALTER TABLE dbo.PosInfo 
	ADD	wxpayid INT NULL DEFAULT(0)
END
GO

ALTER TABLE dbo.PosInfo ALTER COLUMN wxpayid INT NULL
UPDATE PosInfo SET wxpayid=0 WHERE wxpayid IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PosInfo',N'U') AND Name='enablemonthend')
BEGIN
	ALTER TABLE dbo.PosInfo
	ADD enablemonthend BIT NOT NULL DEFAULT(0)	
END

GO

IF NOT EXISTS (SELECT name FROM syscolumns where id = object_id(N'[dbo].[PosInfo]') and name = 'KID' )
BEGIN
	
	ALTER TABLE dbo.PosInfo ADD
		KID INT NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='autoshowpromote'
)
BEGIN
		ALTER TABLE PosInfo ADD autoshowpromote INT NOT NULL DEFAULT(0) --自动弹出促销窗口
END
GO	


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='rateid'
)
BEGIN
		ALTER TABLE PosInfo ADD rateid INT NOT NULL DEFAULT(0) 
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='startbankrate'
)
BEGIN
		ALTER TABLE PosInfo ADD startbankrate INT NOT NULL DEFAULT(0) 
END
GO	


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='PassType'
)
BEGIN
		ALTER TABLE PosInfo ADD PassType INT NOT NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='PriceBillIndexID'
)
BEGIN
		ALTER TABLE PosInfo ADD PriceBillIndexID numeric(18,0) NOT NULL DEFAULT(0)
END
GO		


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='rememberemployee'
)
BEGIN
		ALTER TABLE PosInfo ADD rememberemployee int  NOT NULL DEFAULT(0)
END
GO		

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='samegoodsumqty'
)
BEGIN
		ALTER TABLE PosInfo ADD samegoodsumqty int  NOT NULL DEFAULT(0)
END
GO		




IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='permitsaleemployee'
)
BEGIN
		ALTER TABLE PosInfo ADD permitsaleemployee INT NOT NULL DEFAULT(0) --是否允许录入业务员
END
GO	

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='canclezeroway')
BEGIN
		ALTER TABLE PosInfo ADD canclezeroway INT NOT NULL DEFAULT(0)	  
END
GO	


IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='canclezerotype')
BEGIN
		ALTER TABLE PosInfo ADD canclezerotype INT NOT NULL DEFAULT(0)	  
END
GO	



IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='lowlowestsaleprice')
BEGIN
		ALTER TABLE PosInfo ADD lowlowestsaleprice INT NOT NULL DEFAULT(0)	  
END
GO	



IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='lowlastbuyprice')
BEGIN
		ALTER TABLE PosInfo ADD lowlastbuyprice INT NOT NULL DEFAULT(0)	  
END
GO	


IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='highhighestsaleprice')
BEGIN
		ALTER TABLE PosInfo ADD highhighestsaleprice INT NOT NULL DEFAULT(0)	  
END
GO	

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='codesearchway')
BEGIN
		ALTER TABLE PosInfo ADD codesearchway INT NOT NULL DEFAULT(0)	  
END
GO	

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='stockqueryrange')
BEGIN
		ALTER TABLE PosInfo ADD stockqueryrange INT NOT NULL DEFAULT(0)	  
END
GO	

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='permitmakevipcard')
BEGIN
		ALTER TABLE PosInfo ADD permitmakevipcard INT NOT NULL DEFAULT(0)	  
END
GO	

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='permitvipcardrecharge')
BEGIN
		ALTER TABLE PosInfo ADD permitvipcardrecharge INT NOT NULL DEFAULT(0)	  
END
GO	


IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='permitshowbatchno')
BEGIN
		ALTER TABLE PosInfo ADD permitshowbatchno INT NOT NULL DEFAULT(0)	  
END
GO	

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='permitshowbatchtime')
BEGIN
		ALTER TABLE PosInfo ADD permitshowbatchtime INT NOT NULL DEFAULT(0)	  
END
GO	

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='permitsavenonnumber')
BEGIN
		ALTER TABLE PosInfo ADD permitsavenonnumber INT NOT NULL DEFAULT(1)	  
END
GO	
IF EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='PosInfo' 
		AND a.Name='permitsavenonnumber')
BEGIN
		UPDATE PosInfo SET  permitsavenonnumber=1	   
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='displayadvpic'
)
BEGIN
		ALTER TABLE PosInfo ADD displayadvpic INT NOT NULL DEFAULT(0) 
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='displayptypepic'
)
BEGIN
		ALTER TABLE PosInfo ADD displayptypepic INT NOT NULL DEFAULT(0) 
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='frequencysecond'
)
BEGIN
		ALTER TABLE PosInfo ADD frequencysecond INT NOT NULL DEFAULT(1) 
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='dealbtypeid'
)
BEGIN
		ALTER TABLE PosInfo ADD dealbtypeid VARCHAR(200) DEFAULT'' 
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='autopromotions'
)
BEGIN
		ALTER TABLE PosInfo ADD autopromotions INT NOT NULL DEFAULT(0) 
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='posnotposting'
)
BEGIN
		ALTER TABLE PosInfo ADD posnotposting INT NOT NULL DEFAULT(0) 
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='enablemultipleaccounts'
)
BEGIN
		ALTER TABLE PosInfo ADD enablemultipleaccounts INT NOT NULL DEFAULT(0) 
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='enablebtype'
)
BEGIN
		ALTER TABLE PosInfo ADD enablebtype INT NOT NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosInfo' AND a.Name='JFPayId'
)
BEGIN
		ALTER TABLE PosInfo ADD JFPayId INT NOT NULL DEFAULT(0) 
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 
if not exists (select * from syscolumns where id = object_id(N'[dbo].[PosInfo]') and  name = 'macaddress' AND length = 100)
BEGIN
     ALTER TABLE PosInfo
	    ALTER COLUMN macaddress varchar(200) 
END

UPDATE dbo.PosInfo SET permitsaleemployee=1,rememberemployee=1,enablemultipleaccounts=1,codesearchway=1
--支付宝、微信升级默认中国银行
UPDATE PosInfo SET alipayid=2 WHERE ISNULL(alipayid,0)=0
UPDATE PosInfo SET wxpayid=2 WHERE ISNULL(wxpayid,0)=0
GO

--新增字段autozereui
go
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE id = OBJECT_ID(N'PosInfo',N'U') AND Name = 'autozeroui' )
BEGIN 
 ALTER TABLE dbo.PosInfo
 ADD autozeroui INT NOT NULL DEFAULT(0)
END 
go

--职员是否全部选择
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE id = OBJECT_ID(N'PosInfo',N'U') AND Name = 'isEall' )
BEGIN 
	 ALTER TABLE dbo.PosInfo
	 ADD isEall BIT NOT NULL DEFAULT(1)
END 
GO


--操作员是否全部选择
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE id = OBJECT_ID(N'PosInfo',N'U') AND Name = 'isOperatorAll' )
BEGIN 
	 ALTER TABLE dbo.PosInfo
	 ADD isOperatorAll BIT NOT NULL DEFAULT(1)
END 
GO

--账户是否全部选择
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE id = OBJECT_ID(N'PosInfo',N'U') AND Name = 'isAccountAll' )
BEGIN 
	 ALTER TABLE dbo.PosInfo
	 ADD isAccountAll BIT NOT NULL DEFAULT(1)
END 
GO

--账户是否全部选择
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE id = OBJECT_ID(N'PosInfo',N'U') AND Name = 'isPtypeAll' )
BEGIN 
	 ALTER TABLE dbo.PosInfo
	 ADD isPtypeAll BIT NOT NULL DEFAULT(1)
END 
GO

--账户是否全部选择
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE id = OBJECT_ID(N'PosInfo',N'U') AND Name = 'isBtypeAll' )
BEGIN 
	 ALTER TABLE dbo.PosInfo
	 ADD isBtypeAll BIT NOT NULL DEFAULT(1)
END 
GO
--严密序列号管理商品必须录入序列号后方可结算
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE id = OBJECT_ID(N'PosInfo',N'U') AND Name = 'serialptypejs' )
BEGIN 
	 ALTER TABLE dbo.PosInfo
	 ADD serialptypejs INT NOT NULL DEFAULT(0)
END 
GO
UPDATE PosInfo SET serialptypejs = 0 WHERE serialptypejs IS NULL
GO

--通联PAYID
IF NOT EXISTS (SELECT 1 FROM SysColumns WHERE ID = OBJECT_ID(N'[dbo].[PosInfo]',N'U') AND Name = 'allinpayid' )
BEGIN
	ALTER TABLE dbo.PosInfo 
	ADD	allinpayid INT NOT NULL DEFAULT(0)
END
GO
UPDATE PosInfo SET alipayid=0 WHERE alipayid IS NULL
GO



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT 1 FROM sysobjects WHERE id=OBJECT_ID('PosIsUpdateData') AND type='U')
BEGIN
	CREATE TABLE PosIsUpdateData
	(
		ID INT IDENTITY(1,1) NOT NULL,
		tbType	VARCHAR(50) NULL,
		Tid		DECIMAL(18,0) NULL,
		ifUpdate INT DEFAULT(1) NULL,
		stypeid  VARCHAR(max) NULL
	)
END
GO

SET ANSI_PADDING OFF
GO


IF NOT EXISTS(SELECT * FROM sys.columns WHERE [object_id]=object_id('PosIsUpdateData') AND name='stypeid' AND max_length=-1)
BEGIN
	ALTER TABLE PosIsUpdateData
		ALTER COLUMN stypeid VARCHAR(MAX) NULL
END
GO	
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
--Pos期间月结时间配置
IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'PosMonthEndConfig',N'U'))
BEGIN
	CREATE TABLE PosMonthEndConfig
	(
		[PosId] INT NOT NULL,
		[Year]	INT NOT NULL,
		[Month] INT NOT NULL,
		[EndDate] DATETIME NOT NULL,
		[EndTime] DATETIME NOT NULL
	)
END
GO





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PosMulAccount]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PosMulAccount](
		[ID] INT IDENTITY(1,1) NOT NULL,
		[BillNumberId] INTEGER NOT NULL,
		[ATypeID] INT NULL,
		[PayStyle] VARCHAR(200),	
		[ATotal] NUMERIC(22,10) NULL DEFAULT(0),
		[VipCardID] INT NULL DEFAULT(-1),
		[Comment] VARCHAR(500) NULL DEFAULT(''),
	) ON [PRIMARY]
END
IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('PosMulAccount') AND name = 'CIX_PosMulAccount_BillNumberID')
	CREATE INDEX CIX_PosMulAccount_BillNumberID ON PosMulAccount(BillnumberID ASC);
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccount' AND a.Name='paymoney'
)
BEGIN
	ALTER TABLE PosMulAccount 
		ADD paymoney NUMERIC(24,10) NOT NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccount' AND a.Name='yhType'
)
BEGIN
	ALTER TABLE PosMulAccount 
		ADD yhType int NOT NULL DEFAULT(-1)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccount' AND a.Name='CouponCode'
)
BEGIN
	ALTER TABLE PosMulAccount 
		ADD CouponCode VARCHAR(200) NOT NULL DEFAULT('')
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccount' AND a.Name='VipTotal'
)
BEGIN
	ALTER TABLE PosMulAccount 
		ADD VipTotal NUMERIC(24,10) NOT NULL DEFAULT(0)
END
--积分付款时的兑换值
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccount' AND a.Name='CentToMoney'
)
BEGIN
	ALTER TABLE PosMulAccount 
		ADD CentToMoney NUMERIC(24,10) NOT NULL DEFAULT(0)
END
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccount' AND a.Name='ATotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosMulAccount 
	ALTER COLUMN ATotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PosMulAccountAll]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PosMulAccountAll](
		[ID] INT IDENTITY(1,1) NOT NULL,
		[BillNumberId] INTEGER NOT NULL,
		[ATypeID] INT NULL,
		[PayStyle] VARCHAR(200),	
		[ATotal] NUMERIC(22,10) NULL DEFAULT(0),
		[VipCardID] INT NULL DEFAULT(-1),
		[Comment] VARCHAR(500) NULL DEFAULT(''),
	) ON [PRIMARY]
END
IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('PosMulAccountAll') AND name = 'CIX_PosMulAccountAll_BillNumberID')
	CREATE INDEX CIX_PosMulAccountAll_BillNumberID ON PosMulAccountAll(BillnumberID ASC);
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccountAll' AND a.Name='paymoney'
)
BEGIN
	ALTER TABLE PosMulAccountAll 
		ADD paymoney NUMERIC(24,10) NOT NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccountAll' AND a.Name='yhType'
)
BEGIN
	ALTER TABLE PosMulAccountAll 
		ADD yhType int NOT NULL DEFAULT(-1)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccountAll' AND a.Name='CouponCode'
)
BEGIN
	ALTER TABLE PosMulAccountAll 
		ADD CouponCode VARCHAR(200) NOT NULL DEFAULT('')
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccountAll' AND a.Name='VipTotal'
)
BEGIN
	ALTER TABLE PosMulAccountAll 
		ADD VipTotal NUMERIC(24,10) NOT NULL DEFAULT(0)
END
--积分付款时的兑换值
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccountAll' AND a.Name='CentToMoney'
)
BEGIN
	ALTER TABLE PosMulAccountAll 
		ADD CentToMoney NUMERIC(24,10) NOT NULL DEFAULT(0)
END
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosMulAccountAll' AND a.Name='ATotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosMulAccountAll 
	ALTER COLUMN ATotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[POSOperator]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE POSOperator(
		Id INT  PRIMARY KEY IDENTITY(1,1) ,	
		Etypeid VARCHAR(50), --职员typeid
		Eid    INT,		--职员ID			
		Efullname VARCHAR(200), --职员姓名
		Eusercode VARCHAR(200),--职员编号
		Comment VARCHAR(500),    --备注
		Dfullname VARCHAR(200),--部门名称
		Dtypeid  VARCHAR(50),--部门id
		PositionName VARCHAR(200)
	)
END
GO


------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='POSOperator' AND a.Name='Posid'
)
BEGIN
	ALTER TABLE POSOperator 
		ADD Posid INT NULL DEFAULT(1)
END
GO

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSOperator',N'U') AND Name='Efullname')
BEGIN
	ALTER TABLE POSOperator 
		DROP COLUMN Efullname
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSOperator',N'U') AND Name='Eusercode')
BEGIN
	ALTER TABLE POSOperator 
		DROP COLUMN Eusercode
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSOperator',N'U') AND Name='Comment')
BEGIN
	ALTER TABLE POSOperator 
		DROP COLUMN Comment
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSOperator',N'U') AND Name='Dfullname')
BEGIN
	ALTER TABLE POSOperator 
		DROP COLUMN Dfullname
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSOperator',N'U') AND Name='Dtypeid')
BEGIN
	ALTER TABLE POSOperator 
		DROP COLUMN Dtypeid
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSOperator',N'U') AND Name='PositionName')
BEGIN
	ALTER TABLE POSOperator 
		DROP COLUMN PositionName
END
GO 
------------------------------------------表修改区域结束-------------------------------------------------



GO
--POS关联支付账户表---
IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'POSPayConfigInfo',N'U'))
BEGIN
	CREATE TABLE POSPayConfigInfo
	(
		ID	       INT IDENTITY(1,1),
		PayConfigID	       INT NOT NULL,
		PosID    INT	 NOT NULL
	)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[POSPayConfigInfo]') and name = 'ID' )
BEGIN
	ALTER TABLE dbo.POSPayConfigInfo ADD
		ID	       INT IDENTITY(1,1)
END

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('POSPayConfigInfo') AND name = 'CIX_POSPayConfigInfo_ID')
CREATE CLUSTERED INDEX CIX_POSPayConfigInfo_ID ON POSPayConfigInfo(ID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('POSPayConfigInfo') AND name = 'NCIX_POSPayConfigInfo_PayConfigID') 
CREATE NONCLUSTERED INDEX NCIX_POSPayConfigInfo_PayConfigID ON POSPayConfigInfo(PayConfigID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('POSPayConfigInfo') AND name = 'NCIX_POSPayConfigInfo_PosID')
CREATE NONCLUSTERED INDEX NCIX_POSPayConfigInfo_PosID ON POSPayConfigInfo(PosID) 
 
------------------------------------------创建索引区域结束-----------------------------------------------
GO





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[POSPtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE POSPtype(
		Id INT  PRIMARY KEY IDENTITY(1,1) ,	
		ptypeid VARCHAR(50), --商品typeid
		pid    INT,		--商品ID			
		Fullname VARCHAR(200), --商品姓名
		Usercode VARCHAR(200),--商品编号
		Comment VARCHAR(500),    --备注
		[Standard] VARCHAR(200), --商品规格
		[Type] VARCHAR(200),--规格
		Entrycode VARCHAR(MAX) --条码
	)
END
GO


------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='POSPtype' AND a.Name='Posid'
)
BEGIN
	ALTER TABLE POSPtype 
		ADD Posid INT NULL DEFAULT(1)
END
GO

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSPtype',N'U') AND Name='Fullname')
BEGIN
	ALTER TABLE POSPtype 
		DROP COLUMN Fullname
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSPtype',N'U') AND Name='Usercode')
BEGIN
	ALTER TABLE POSPtype 
		DROP COLUMN Usercode
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSPtype',N'U') AND Name='Standard')
BEGIN
	ALTER TABLE POSPtype 
		DROP COLUMN [Standard]
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSPtype',N'U') AND Name='Type')
BEGIN
	ALTER TABLE POSPtype 
		DROP COLUMN [Type]
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSPtype',N'U') AND Name='Entrycode')
BEGIN
	ALTER TABLE POSPtype 
		DROP COLUMN Entrycode
END
GO 

IF EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'POSPtype',N'U') AND Name='Comment')
BEGIN
	ALTER TABLE POSPtype 
		DROP COLUMN Comment
END
GO 
------------------------------------------表修改区域结束-------------------------------------------------




SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT 1 FROM sysobjects WHERE id=OBJECT_ID('PosReDataGlobal') AND type='U')
BEGIN
	CREATE TABLE PosReDataGlobal
	(
		IfReData INT DEFAULT(1) NULL,
		stypeid  VARCHAR(50) NULL
	)
END
GO

SET ANSI_PADDING OFF
GO






------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PosRetailCash]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PosRetailCash](
	[Stypeid] [varchar](50) NOT NULL,
	[CashAtypeid] [varchar](50) NULL,
	[BankAtypeid] [varchar](50) NULL,
	[YSAtypeid] [varchar](50) NULL,
	[StoreCardAtypeid] [varchar](50) NULL,
	[Tax] [numeric](5, 2) NULL,
	[Comment] [varchar](200) NULL
) ON [PRIMARY]
END
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosRetailCash' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosRetailCash 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
-- 小票生成零售单关系记录表
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PosRetailRecord]') AND type in (N'U'))
BEGIN
	CREATE TABLE [PosRetailRecord](
		Id INT IDENTITY(1,1),
		PosSaleBillId INT NOT NULL DEFAULT(0),
		PosBillNumberId INT NOT NULL DEFAULT(0),
		RetailBillId INT NOT NULL DEFAULT(0),
		RetailBillNumberId NUMERIC(10,0) NOT NULL DEFAULT(0),
		AuditingFlag TINYINT NOT NULL DEFAULT(0),
		RecordTime DATETIME  NULL 
	);
END

-- 修改字段开始 --
IF NOT EXISTS(
	SELECT a.NAME FROM syscolumns a JOIN sysobjects b ON a.id=b.id
	WHERE b.name='PosRetailRecord' AND a.name='AuditingFlag'
)
BEGIN
	ALTER TABLE PosRetailRecord ADD AuditingFlag TINYINT NOT NULL DEFAULT(0)
END

-- 修改字段开始 --
IF NOT EXISTS(
	SELECT a.NAME FROM syscolumns a JOIN sysobjects b ON a.id=b.id
	WHERE b.name='PosRetailRecord' AND a.name='RecordTime'
)
BEGIN
	ALTER TABLE PosRetailRecord ADD RecordTime DATETIME NULL
END


-- 修改字段结束 --


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

/****** Object:  Index [NCIX_PosRetailRecord_RetailBillNumberId]    Script Date: 09/01/2017 17:26:14 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PosRetailRecord]') AND name = N'NCIX_PosRetailRecord_RetailBillNumberId')
/****** Object:  Index [NCIX_PosRetailRecord_RetailBillNumberId]    Script Date: 09/01/2017 17:25:13 ******/
CREATE NONCLUSTERED INDEX [NCIX_PosRetailRecord_RetailBillNumberId] ON [dbo].[PosRetailRecord] 
(
	[RetailBillNumberId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING OFF
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'PosSaleBill') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PosSaleBill
	(
		BillnumberID int  NULL,
		ID int IDENTITY(1,1) NOT NULL,
		PID INT NULL,
		Qty numeric(24, 10)  NULL,
		BackQty numeric(22,10) NULL DEFAULT(0),
		RetailPrice numeric(22, 10)  NULL,
		Tax numeric(5,2) NULL DEFAULT(0),
		DisCount numeric(22, 10)  NULL DEFAULT(1),
		Price numeric(22, 10)  NULL,
		RetailTotal numeric(22, 10)  NULL,
		Total numeric(22, 10)  NULL,
		UnitID INT  NULL DEFAULT(0),
		UnitRate numeric(22,10) NULL Default(1),
		ItemID    bigint   NULL,
		IsCombined  int   NULL,
		BarCode	VARCHAR(50) NULL DEFAULT(''),
		IsGift int NULL DEFAULT(0),
		Comment varchar(255) NULL,
		BaseUnitID INT  NULL DEFAULT(0),
		PromoIDs varchar(200) NULL
	)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='IsGift'
)
BEGIN
	ALTER TABLE PosSaleBill 
		ADD IsGift INT NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE PosSaleBill
		ADD Comment varchar(255) NULL 
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='BaseUnitID'
)
BEGIN
	ALTER TABLE PosSaleBill
		ADD BaseUnitID INT  NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='PromoType'
)
BEGIN
	ALTER TABLE PosSaleBill
		ADD PromoType INT  NOT NULL DEFAULT(0)
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='SaleEid'
)
BEGIN
	ALTER TABLE PosSaleBill
		ADD SaleEid INT  NOT NULL DEFAULT(0)
END



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='producedate'
)
BEGIN
	ALTER TABLE PosSaleBill
		ADD producedate VARCHAR(50)	NOT NULL DEFAULT('')
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='validdate'
)
BEGIN
	ALTER TABLE PosSaleBill
		ADD validdate VARCHAR(50)	NOT NULL DEFAULT('')
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='goodsnumber'
)
BEGIN
	ALTER TABLE PosSaleBill
		ADD goodsnumber VARCHAR(100)	NOT NULL DEFAULT('')
END



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='serial'
)
BEGIN
	ALTER TABLE PosSaleBill
		ADD serial TEXT NOT NULL DEFAULT('')
END
    

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='goodscostprice'
)
BEGIN
	ALTER TABLE PosSaleBill 
	  ADD  goodscostprice NUMERIC(24,10) 
END



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='guid'
)
BEGIN
	ALTER TABLE PosSaleBill 
	  ADD  guid VARCHAR(100) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='couponcode'
)
BEGIN
	ALTER TABLE PosSaleBill 
	  ADD  couponcode VARCHAR(200) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='pricesource'
)
BEGIN
	ALTER TABLE PosSaleBill 
	  ADD  pricesource VARCHAR(200) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='PromoIDs'
)
BEGIN
	ALTER TABLE PosSaleBill 
		ADD PromoIDs VARCHAR(200)  NULL
END
go

IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('PosSaleBill') AND name = 'CIX_PosSaleBill_BillNumberID')
	CREATE INDEX CIX_PosSaleBill_BillNumberID ON PosSaleBill(BillnumberID ASC);

IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('PosSaleBill') AND name = 'CIX_PosSaleBill_ID')
	CREATE INDEX CIX_PosSaleBill_ID ON PosSaleBill(ID ASC);

GO
SET ANSI_PADDING OFF
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='RetailPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN RetailPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='DisCount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN DisCount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='RetailTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN RetailTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
           
           
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='paymoney'
)
BEGIN
	ALTER TABLE PosSaleBill 
	  ADD  paymoney NUMERIC(24,10) 
END

alter table PosSaleBill alter column Comment varchar(max)

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBill' AND a.Name='BarCode' AND  (a.length = 50)
)
BEGIN
	ALTER TABLE PosSaleBill 
		ALTER COLUMN BarCode VARCHAR(200)
END
                                              
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING OFF
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'PosSaleBillAll') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PosSaleBillAll
	(
		BillnumberID int  NULL,
		ID INT NULL,
		PID INT NULL,
		Qty numeric(24, 10)  NULL,
		BackQty numeric(22,10) NULL DEFAULT(0),
		RetailPrice numeric(22, 10)  NULL,
		Tax numeric(5,2) NULL DEFAULT(0),
		DisCount numeric(22, 10)  NULL DEFAULT(1),
		Price numeric(22, 10)  NULL,
		RetailTotal numeric(22, 10)  NULL,
		Total numeric(22, 10)  NULL,
		UnitID INT  NULL DEFAULT(0),
		UnitRate numeric(22,10) NULL Default(1),
		ItemID    bigint   NULL,
		IsCombined  int   NULL,
		BarCode	VARCHAR(50) NULL DEFAULT(''),
		IsGift int NULL DEFAULT(0),
		Comment varchar(255) NULL,
		BaseUnitID INT  NULL DEFAULT(0),
		PromoIDs varchar(200) NULL
	)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='IsGift'
)
BEGIN
	ALTER TABLE PosSaleBillAll 
		ADD IsGift INT NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE PosSaleBillAll 
		ADD Comment varchar(255) NULL 
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='BaseUnitID'
)
BEGIN
	ALTER TABLE PosSaleBillAll
		ADD BaseUnitID INT  NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='PromoType'
)
BEGIN
	ALTER TABLE PosSaleBillAll
		ADD PromoType INT NOT NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='SaleEid'
)
BEGIN
	ALTER TABLE PosSaleBillAll
		ADD SaleEid INT NOT NULL DEFAULT(0)
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='producedate'
)
BEGIN
	ALTER TABLE PosSaleBillAll
		ADD producedate VARCHAR(50)	NOT NULL DEFAULT('')
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='validdate'
)
BEGIN
	ALTER TABLE PosSaleBillAll
		ADD validdate VARCHAR(50)	NOT NULL DEFAULT('')
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='goodsnumber'
)
BEGIN
	ALTER TABLE PosSaleBillAll
		ADD goodsnumber VARCHAR(100)	NOT NULL DEFAULT('')
END



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='serial'
)
BEGIN
	ALTER TABLE PosSaleBillAll
		ADD serial TEXT NOT NULL DEFAULT('')
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='guid'
)
BEGIN
	ALTER TABLE PosSaleBillAll
		ADD guid VARCHAR(100) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='couponcode'
)
BEGIN
	ALTER TABLE PosSaleBillAll 
	  ADD  couponcode VARCHAR(200) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='pricesource'
)
BEGIN
	ALTER TABLE PosSaleBillAll 
	  ADD  pricesource VARCHAR(200) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='PromoIDs'
)
BEGIN
	ALTER TABLE PosSaleBillAll 
		ADD PromoIDs VARCHAR(200)  NULL
END
go

IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('PosSaleBillAll') AND name = 'CIX_PosSaleBillAll_BillNumberID')
	CREATE  INDEX CIX_PosSaleBillAll_BillNumberID ON PosSaleBillAll(BillnumberID ASC);
IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('PosSaleBillAll') AND name = 'CIX_PosSaleBillAll_ID')
	CREATE  INDEX CIX_PosSaleBillAll_ID ON PosSaleBillAll(ID ASC);
GO
SET ANSI_PADDING OFF
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='RetailPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN RetailPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='DisCount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN DisCount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='RetailTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN RetailTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillAll 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
    
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='goodscostprice'
)
BEGIN
	ALTER TABLE PosSaleBillAll 
	  ADD  goodscostprice NUMERIC(24,10) 
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='paymoney'
)
BEGIN
	ALTER TABLE PosSaleBillAll 
	  ADD  paymoney NUMERIC(24,10) 
END
 
alter table PosSaleBillAll alter column Comment varchar(max)                           

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillAll' AND a.Name='BarCode' AND  (a.length = 50)
)
BEGIN
	ALTER TABLE PosSaleBillAll 
		ALTER COLUMN BarCode VARCHAR(200)
END

------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING OFF
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'PosSaleBillIndex') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PosSaleBillIndex
	(
		BillnumberID  INTEGER IDENTITY(1,1) NOT NULL,
		Billtype INT DEFAULT(305) NULL,
		billdate VARCHAR(20)  NULL,
		BillCode varchar(50)  NULL,
		SID INT NULL,
		BID INT NULL,
		KID INT NULL,
		PosID INT  NULL,
		EID INT  NULL,
		VipCardID INT NULL DEFAULT(-1),
		TotalQty numeric(22, 10)  NULL DEFAULT(0),
		Discount numeric(22, 10)  NULL DEFAULT(1),
		TotalMoney numeric(22, 10)  NULL DEFAULT(0),
		preferencemoney numeric(22, 10)  NULL DEFAULT(0),--优惠金额
		premoney numeric(22, 10)  NULL DEFAULT(0),--抹零金额
		Totalinmoney numeric(22, 10)  NULL DEFAULT(0),
		CashMoney numeric(22, 10)  NULL DEFAULT(0),
		ChangeMoney numeric(22, 10)  NULL DEFAULT(0),
		BackBillnumberID int  NULL DEFAULT(0),
		UpLoadBillnumberID int  NULL,
		PromoRuleId int NULL DEFAULT(0),
		PromotionMsg VARCHAR(200) NULL,
		BuyBackType INT NULL DEFAULT(-1),
		billtime VARCHAR(20)  NULL,
		PromoIDs varchar(200) NULL
	)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='PromotionMsg'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD PromotionMsg varchar(200) NULL 
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='BuyBackType'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD BuyBackType INT NULL DEFAULT(-1) 
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='premoney'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD premoney numeric(22, 10)  NULL DEFAULT(0) 
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='billtime'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD billtime VARCHAR(20)  NULL
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='SaveInCzMoney'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD SaveInCzMoney NUMERIC(24,10) NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='guid'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD guid VARCHAR(50)  NULL
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='BillDescription'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD BillDescription VARCHAR(2000)  NULL
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='CouponCode'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD CouponCode VARCHAR(2000)  NULL
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='PromoIDs'
)
BEGIN
	ALTER TABLE PosSaleBillIndex 
		ADD PromoIDs VARCHAR(200)  NULL
END
go

IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('PosSaleBillIndex') AND name = 'CIX_PosSaleBillIndex_BillnumberID')
	CREATE INDEX CIX_PosSaleBillIndex_BillnumberID ON PosSaleBillIndex(BillnumberID ASC);

GO
SET ANSI_PADDING OFF
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='TotalQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndex 
	ALTER COLUMN TotalQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndex 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndex 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='preferencemoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndex 
	ALTER COLUMN preferencemoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='premoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndex 
	ALTER COLUMN premoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='Totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndex 
	ALTER COLUMN Totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='CashMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndex 
	ALTER COLUMN CashMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndex' AND a.Name='ChangeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndex 
	ALTER COLUMN ChangeMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING OFF
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'PosSaleBillIndexAll') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PosSaleBillIndexAll
	(
		BillnumberID  INT NULL,
		Billtype INT DEFAULT(305) NULL,
		billdate VARCHAR(20)  NULL,
		BillCode varchar(50)  NULL,
		SID INT NULL,
		BID INT NULL,
		KID INT NULL,
		PosID INT  NULL,
		EID INT  NULL,
		VipCardID INT NULL DEFAULT(-1),
		TotalQty numeric(22, 10)  NULL DEFAULT(0),
		Discount numeric(22, 10)  NULL DEFAULT(1),
		TotalMoney numeric(22, 10)  NULL DEFAULT(0),
		preferencemoney numeric(22, 10)  NULL DEFAULT(0),--优惠金额
		premoney numeric(22, 10)  NULL DEFAULT(0),--抹零金额
		Totalinmoney numeric(22, 10)  NULL DEFAULT(0),
		CashMoney numeric(22, 10)  NULL DEFAULT(0),
		ChangeMoney numeric(22, 10)  NULL DEFAULT(0),
		BackBillnumberID int  NULL DEFAULT(0),
		UpLoadBillnumberID int  NULL,
		PromoRuleId int NULL DEFAULT(0),
		PromotionMsg VARCHAR(200) NULL,
		BuyBackType INT NULL DEFAULT(-1),
		billtime VARCHAR(20)  NULL,
		PromoIDs VARCHAR(200) NULL
	)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='PromotionMsg'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD PromotionMsg varchar(200) NULL 
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='BuyBackType'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD BuyBackType INT NULL DEFAULT(-1) 
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='premoney'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD premoney numeric(22, 10)  NULL DEFAULT(0) 
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='billtime'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD billtime VARCHAR(20)  NULL
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='SaveInCzMoney'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD SaveInCzMoney NUMERIC(24,10) NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='guid'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD [guid] VARCHAR(50)  NULL
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='BillDescription'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD BillDescription VARCHAR(2000)  NULL
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='CouponCode'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD CouponCode VARCHAR(2000)  NULL
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='PromoIDs'
)
BEGIN
	ALTER TABLE PosSaleBillIndexAll 
		ADD PromoIDs VARCHAR(200)  NULL
END
go

IF NOT EXISTS(SELECT * FROM sysindexes WHERE id = OBJECT_ID('PosSaleBillIndexAll') AND name = 'CIX_PosSaleBillIndexAll_BillnumberID')
	CREATE INDEX CIX_PosSaleBillIndexAll_BillnumberID ON PosSaleBillIndexAll(BillnumberID ASC);
	


GO



SET ANSI_PADDING OFF
GO


--/****** Object:  Index [CIX_PosSaleBillIndexAll_Unique]    Script Date: 06/24/2015 15:10:36 ******/
--IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PosSaleBillIndexAll]') AND name = N'CIX_PosSaleBillIndexAll_Unique')
--BEGIN	
--	ALTER TABLE [dbo].[PosSaleBillIndexAll] ADD  CONSTRAINT [CIX_PosSaleBillIndexAll_Unique] UNIQUE NONCLUSTERED 
--	(
--		[BillCode] ASC,
--		[UpLoadBillnumberID] ASC,
--		[PosID] ASC
--	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
--END
--GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='TotalQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndexAll 
	ALTER COLUMN TotalQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndexAll 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndexAll 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='preferencemoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndexAll 
	ALTER COLUMN preferencemoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='premoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndexAll 
	ALTER COLUMN premoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='Totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndexAll 
	ALTER COLUMN Totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='CashMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndexAll 
	ALTER COLUMN CashMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosSaleBillIndexAll' AND a.Name='ChangeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PosSaleBillIndexAll 
	ALTER COLUMN ChangeMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

IF EXISTS (select * from sysobjects where parent_obj=object_id(N'PosSaleBillIndexAll') and name='CIX_PosSaleBillIndexAll_Unique' )
      ALTER TABLE PosSaleBillIndexAll  DROP CONSTRAINT  CIX_PosSaleBillIndexAll_Unique
GO






SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
-- 合并失败的小票
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PosSaleMergeFailed]') AND type in (N'U'))
BEGIN
	CREATE TABLE PosSaleMergeFailed(
		Id INT IDENTITY(1,1),
		PosBillNumberId INT NOT NULL DEFAULT(0),
		Reason VARCHAR(500),
		Comment VARCHAR(255)
	);
END

-- 修改字段开始 --

IF EXISTS(
	SELECT a.NAME FROM syscolumns a JOIN sysobjects b ON a.id=b.id
	WHERE b.name='PosSaleMergeFailed' AND a.name='Reason' 
	AND a.length=-1 --如果是varchar(max) 修改500的
)  
BEGIN
	ALTER TABLE PosSaleMergeFailed ALTER COLUMN Reason VARCHAR(500);
END
-- 修改字段结束 --
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PosUpdatedMaxNumber]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PosUpdatedMaxNumber
	(
		TableName	VARCHAR(50),
		Stypeid		VARCHAR(50),
		MaxVersion  BIGINT default(0)
	)
END
GO


IF EXISTS(select b.name from sysobjects b join syscolumns a on b.id = a.cdefault where a.id = object_id('PosUpdatedMaxNumber') and a.name ='XiWaMaxNumber')
BEGIN
	DECLARE @conName varchar(50)
	select  @conName =b.name from sysobjects b join syscolumns a on b.id = a.cdefault where a.id = object_id('PosUpdatedMaxNumber') and a.name ='XiWaMaxNumber'
	exec('ALTER TABLE PosUpdatedMaxNumber drop constraint ' + @conName)
END

if exists (select name from syscolumns where id = object_id(N'[dbo].[PosUpdatedMaxNumber]') and name = 'XiWaMaxNumber' )
BEGIN
	ALTER TABLE dbo.PosUpdatedMaxNumber DROP  column  XiWaMaxNumber 
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PosUpdatedMaxNumber]') and name = 'MaxVersion' )
BEGIN
	ALTER TABLE dbo.PosUpdatedMaxNumber ADD  MaxVersion BIGINT default(0)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PreBill]    脚本日期: 05/05/2010 14:46:29 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PreBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PreBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillType] [int] NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_PreBill_total]  DEFAULT (0),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')	,
		 ntotal		numeric(22,10) null DEFAULT(0)	
		 ,ShowOrder INT DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PreBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.PreBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PreBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.PreBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PreBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.PreBill
	ADD ShowOrder INT DEFAULT(0)
END
GO	
	UPDATE dbo.PreBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PreBill' AND a.Name='vipcardid'
)
BEGIN
	ALTER TABLE PreBill 
		ADD vipcardid  INT NULL DEFAULT(-1)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PreBill' AND a.Name='ntotal'
)
BEGIN
	ALTER TABLE PreBill ADD ntotal NUMERIC(22,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PreBill' AND a.Name='RelevanceBillId'
)
BEGIN
	ALTER TABLE PreBill ADD RelevanceBillId NUMERIC(10,0)
END
GO
--商品品牌
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PreBill' AND a.Name='BrandarTypeId'
)
BEGIN
	ALTER TABLE PreBill 
		ADD BrandarTypeId VARCHAR(50) NOT NULL DEFAULT('')
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PREBILL') AND name = 'CIX_PREBILL_BillNumberID')
--DROP INDEX CIX_PREBILL_BillNumberID ON PREBILL 
CREATE CLUSTERED INDEX CIX_PREBILL_BillNumberID ON PREBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PREBILL') AND name = 'NCIX_PREBILL_Stypeid')
--DROP INDEX NCIX_PREBILL_Stypeid ON PREBILL 
CREATE NONCLUSTERED INDEX NCIX_PREBILL_Stypeid ON PREBILL(Stypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PREBILL') AND name = 'NCIX_PREBILL_Atypeid')
--DROP INDEX NCIX_PREBILL_Atypeid ON PREBILL 
CREATE NONCLUSTERED INDEX NCIX_PREBILL_Atypeid ON PREBILL(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PREBILL') AND name = 'NCIX_PREBILL_BillType')
CREATE NONCLUSTERED INDEX NCIX_PREBILL_BillType ON PREBILL(BillType) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PreBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PreBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PreBill' AND a.Name='ntotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PreBill 
	ALTER COLUMN ntotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceBillindex]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceBillIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceBillIndex
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	UserCode		VARCHAR(200) NOT NULL,
	FullName		VARCHAR(200) NOT NULL,
	CID				INT NOT NULL,			--币种
	IsFreePrice		TINYINT NOT NULL DEFAULT 0,	--1=按自由项报价（勾选）  0=未勾选
	IsUnitPrice		TINYINT NOT NULL DEFAULT 0,	--1=按计量单位报价（勾选）  0=未勾选
	IsDiscount		TINYINT NOT NULL DEFAULT 0,	--1=指定扣率（勾选）  0=未勾选
	IsRate			TINYINT NOT NULL DEFAULT 0,	--1=指定税率（勾选）  0=未勾选
	Explain			VARCHAR(256) DEFAULT '',	--说明
	Comment			VARCHAR(256) DEFAULT '',	--摘要
	BillType		INT NOT NULL,    -- 单据类型 
	[State]			INT,			 --0=全部审核 1=部分审核 2=全部未审核 3=其他状态
	Checke			VARCHAR(50) DEFAULT '',	 --创建人
	XiWaMaxNumber	NUMERIC(18, 0) NULL DEFAULT (0),
	PosDataVersion timestamp
)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceBillIndex]') and name = 'State' )
BEGIN
	ALTER TABLE dbo.PriceBillIndex ADD
		[State]	INT
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceBillIndex]') and name = 'Checke' )
BEGIN
	ALTER TABLE dbo.PriceBillIndex  ADD
		Checke VARCHAR(50) DEFAULT ''
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceBillIndex]') and name = 'XiWaMaxNumber' )
BEGIN
	ALTER TABLE dbo.PriceBillIndex  ADD
		XiWaMaxNumber NUMERIC(18, 0) NULL DEFAULT (0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceBillIndex]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.PriceBillIndex ADD  PosDataVersion timestamp
END
GO


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceBillIndex') AND name = 'CIX_PriceBillIndex_ID')
--DROP INDEX CIX_PriceBillIndex_ID ON PriceBillIndex 
CREATE CLUSTERED INDEX CIX_PriceBillIndex_ID ON PriceBillIndex(ID) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceBillIndex_Stype]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceBillIndex_Stype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceBillIndex_Stype
(
	ID				 NUMERIC(18,0) IDENTITY(1,1),
	PriceBillIndexID NUMERIC(18,0) NOT NULL,    -- 价格主表的ID 
	StypeID			 VARCHAR(50) NOT NULL    -- 分支机构 
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceBillIndex_Stype') AND name = 'NCIX_PriceBillIndex_Stype_PriceID')
--DROP INDEX NCIX_PriceBillIndex_Stype_PriceID ON PriceBillIndex_Stype 
CREATE NONCLUSTERED INDEX NCIX_PriceBillIndex_Stype_PriceID ON PriceBillIndex_Stype(PriceBillIndexID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceBillIndex_Stype') AND name = 'NCIX_PriceBillIndex_Stype_StypeID')
--DROP INDEX NCIX_PriceBillIndex_Stype_StypeID ON PriceBillIndex_Stype 
CREATE NONCLUSTERED INDEX NCIX_PriceBillIndex_Stype_StypeID ON PriceBillIndex_Stype(StypeID)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceDetail]    脚本日期: 17/04/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceDetail
(
	ID numeric(18) identity(1,1)  NOT NULL,    -- 自增长ID 
	PriceBillIndexID numeric(18) NOT NULL,    -- 价格主表ID 
	[State] int NOT NULL,    -- --0=新增 1=待审核  2=已审核 3=作废 4=调整待审核
	Ptypeid varchar(50) NOT NULL,
	FreeID int,    -- 自由项 
	IsCombined tinyint,    -- 是否为组合自由项 1=组合  0=非组合 
	UnitId int NOT NULL,    -- 报价计量单位 
	PriceStyle int DEFAULT 0,    -- 报价方式 0=单价(默认) 1=折后单价 2=含税单价 
	Price numeric(22,10),    -- 单价 
	Discount numeric(18,10),    -- 扣率 
	DiscountPrice numeric(22,10),    -- 折后单价 
	BeforeRetailPrice	 numeric(22,10),    -- 含税折前单价 
	Tax numeric(18,10),    -- 税率 
	TaxPrice numeric(22,10),    -- 含税折后单价 
	IsPriceControl tinyint,    -- 限价控制  1=勾选(默认) 0=未勾选 
	Comment varchar(256),    -- 备注 
	Checke varchar(50),    -- 填制人 
	Checker varchar(50),
	VaildDate datetime,    -- 审核时间 
	CreateDate datetime,    -- 填制日期 
	DeletedDate datetime,    -- 作废时期 
	DeletedR varchar(50),    -- 作废人 
	SortID int,    -- 排序id 
	OldID  numeric(18,0) default(0),  --价格调整时，记录从哪条明细来的
	RChecker VARCHAR(50) NULL DEFAULT(''),	--反审核人
	RVaildDate DATETIME NULL				--反审核时间
)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetail]') and name = 'Tax' )
BEGIN
ALTER TABLE PriceDetail ADD Tax numeric(18,4)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetail]') and name = 'TaxPrice' )
BEGIN
ALTER TABLE PriceDetail ADD TaxPrice numeric(22,10) default 0
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetail]') and name = 'BeforeRetailPrice' )
BEGIN
ALTER TABLE PriceDetail ADD BeforeRetailPrice numeric(22,10) default 0
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetail]') and name = 'OldID' )
BEGIN
ALTER TABLE PriceDetail ADD OldID numeric(18,0) default 0
END
GO

if exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetail]') and name = 'TaxDiscountPrice' )
BEGIN
 ALTER TABLE PriceDetail drop column TaxDiscountPrice
END
GO

-------9.91添加反审核人、反审核时间-------- 
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetail]') and name = 'RChecker' )
BEGIN
	ALTER TABLE PriceDetail 
	ADD RChecker VARCHAR(50) NULL DEFAULT('')
END
GO

UPDATE PriceDetail SET RChecker = '' WHERE RChecker IS NULL
GO


if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetail]') and name = 'RVaildDate' )
BEGIN
ALTER TABLE PriceDetail 
ADD RVaildDate DATETIME NULL
END
GO

--------------------END---------------------
ALTER TABLE PriceDetail ALTER COLUMN Price NUMERIC(22,4)
ALTER TABLE PriceDetail ALTER COLUMN Discount NUMERIC(18,4)
ALTER TABLE PriceDetail ALTER COLUMN DiscountPrice NUMERIC(18,4)
ALTER TABLE PriceDetail ALTER COLUMN BeforeRetailPrice NUMERIC(18,4)
ALTER TABLE PriceDetail ALTER COLUMN Tax NUMERIC(18,4)
ALTER TABLE PriceDetail ALTER COLUMN TaxPrice NUMERIC(18,4)
GO


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceDetail') AND name = 'NCIX_PriceDetail_PriceBillIndexID')
--DROP INDEX NCIX_PriceDetail_PriceBillIndexID ON PriceDetail 
CREATE NONCLUSTERED INDEX NCIX_PriceDetail_PriceBillIndexID ON PriceDetail(PriceBillIndexID,ID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceDetail') AND name = 'NCIX_PriceDetail_ID')
--DROP INDEX NCIX_PriceDetail_ID ON PriceDetail 
CREATE NONCLUSTERED INDEX NCIX_PriceDetail_ID ON PriceDetail(ID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceDetail') AND name = 'NCIX_PriceDetail_Ptypeid')
--DROP INDEX NCIX_PriceDetail_Ptypeid ON PriceDetail 
CREATE NONCLUSTERED INDEX NCIX_PriceDetail_Ptypeid ON PriceDetail(Ptypeid)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetail' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetail 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetail' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetail 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetail' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetail 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetail' AND a.Name='BeforeRetailPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetail 
	ALTER COLUMN BeforeRetailPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetail' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetail 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetail' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetail 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceDetailDeleted]    脚本日期: 17/04/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceDetailDeleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceDetailDeleted
(
	ID numeric(18) identity(1,1)  NOT NULL,    -- 自增长ID 
	PriceBillIndexID numeric(18) NOT NULL,    -- 价格主表ID 
	[State] int NOT NULL,    -- --0=新增 1=待审核  2=已审核 3=作废 4=调整待审核
	Ptypeid varchar(50) NOT NULL,
	FreeID int,    -- 自由项 
	IsCombined tinyint,    -- 是否为组合自由项 1=组合  0=非组合 
	UnitId int NOT NULL,    -- 报价计量单位 
	PriceStyle int DEFAULT 0,    -- 报价方式 0=单价(默认) 1=折后单价 2=含税单价 
	Price numeric(22,10),    -- 单价 
	Discount numeric(18,10),    -- 扣率 
	DiscountPrice numeric(22,10),    -- 折后单价 
	BeforeRetailPrice	 numeric(22,10),    -- 含税折前单价 
	Tax numeric(18,10),    -- 税率 
	TaxPrice numeric(22,10),    -- 含税折后单价 
	IsPriceControl tinyint,    -- 限价控制  1=勾选(默认) 0=未勾选 
	Comment varchar(256),    -- 备注 
	Checke varchar(50),    -- 填制人 
	Checker varchar(50),
	VaildDate datetime,    -- 审核时间 
	CreateDate datetime,    -- 填制日期 
	DeletedDate datetime,    -- 作废时期 
	DeletedR varchar(50),    -- 作废人 
	SortID int,    -- 排序id 
	RChecker VARCHAR(50) NULL DEFAULT(''),	--反审核人
	RVaildDate DATETIME NULL				--反审核时间
)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetailDeleted]') and name = 'Tax' )
BEGIN
ALTER TABLE PriceDetailDeleted ADD Tax numeric(18,4)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetailDeleted]') and name = 'TaxPrice' )
BEGIN
ALTER TABLE PriceDetailDeleted ADD TaxPrice numeric(22,10) default 0
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetailDeleted]') and name = 'BeforeRetailPrice' )
BEGIN
ALTER TABLE PriceDetailDeleted ADD BeforeRetailPrice numeric(22,10) default 0
END
GO

if exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetailDeleted]') and name = 'TaxDiscountPrice' )
BEGIN
 ALTER TABLE PriceDetailDeleted drop column TaxDiscountPrice
END
GO

-------9.91添加反审核人、反审核时间-------- 
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetailDeleted]') and name = 'RChecker' )
BEGIN
	ALTER TABLE PriceDetailDeleted 
	ADD RChecker VARCHAR(50) NULL DEFAULT('')
END
GO

UPDATE PriceDetailDeleted SET RChecker = '' WHERE RChecker IS NULL
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceDetailDeleted]') and name = 'RVaildDate' )
BEGIN
	ALTER TABLE PriceDetailDeleted 
	ADD RVaildDate DATETIME NULL
END
GO
----------------END------------------------- 


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceDetailDeleted') AND name = 'NCIX_PriceDetailDeleted_PriceBillIndexID')
--DROP INDEX NCIX_PriceDetailDeleted_PriceBillIndexID ON PriceDetailDeleted 
CREATE NONCLUSTERED INDEX NCIX_PriceDetailDeleted_PriceBillIndexID ON PriceDetailDeleted(PriceBillIndexID,ID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceDetailDeleted') AND name = 'NCIX_PriceDetailDeleted_Ptypeid')
--DROP INDEX NCIX_PriceDetailDeleted_Ptypeid ON PriceDetailDeleted 
CREATE NONCLUSTERED INDEX NCIX_PriceDetailDeleted_Ptypeid ON PriceDetailDeleted(Ptypeid)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetailDeleted' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetailDeleted 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetailDeleted' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetailDeleted 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetailDeleted' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetailDeleted 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetailDeleted' AND a.Name='BeforeRetailPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetailDeleted 
	ALTER COLUMN BeforeRetailPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetailDeleted' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetailDeleted 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceDetailDeleted' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceDetailDeleted 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1
            FROM  sysobjects
           WHERE  id = object_id('PriceNameSet')
            AND   type = 'U')
BEGIN
	CREATE TABLE PriceNameSet (
	   Id			INT,
	   FiledName	VARCHAR(100),
	   DefaultName	VARCHAR(100),
	   SetName		VARCHAR(200) DEFAULT '',
	   LimitValue	INT
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceNameSet' AND a.Name='LimitValue'
)
BEGIN
	ALTER TABLE PriceNameSet 
		ADD LimitValue INT DEFAULT 0
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceNameSet)
BEGIN
	INSERT INTO dbo.PriceNameSet(Id,FiledName, DefaultName, SetName, LimitValue )
	VALUES  
		(1,'PreBuyPrice1','预设进价1','预设进价1',703),
		(2,'PreBuyPrice2','预设进价2','预设进价2',704),
		(3,'PreBuyPrice3','预设进价3','预设进价3',705),
		(4,'PreBuyPrice4','预设进价4','预设进价4',706),
		(5,'PreBuyPrice5','预设进价5','预设进价5',707),
		(6,'TopBuyPrice','最高进价','最高进价',1800),
		(7,'PreSalePrice1','预设售价1','预设售价1',219),
		(8,'PreSalePrice2','预设售价2','预设售价2',220),
		(9,'PreSalePrice3','预设售价3','预设售价3',221),
		(10,'PreSalePrice4','预设售价4','预设售价4',222),
		(11,'PreSalePrice5','预设售价5','预设售价5',697),
		(12,'PreSalePrice6','预设售价6','预设售价6',698),
		(13,'PreSalePrice7','预设售价7','预设售价7',699),
		(14,'PreSalePrice8','预设售价8','预设售价8',700),
		(15,'PreSalePrice9','预设售价9','预设售价9',701),
		(16,'PreSalePrice10','预设售价10','预设售价10',702),
		(17,'RetailPrice','零售价','零售价',708),
		(18,'TopSalePrice','最高售价','最高售价',709),
		(19,'LowSalePrice','最低售价','最低售价',710)
END
GO
/*IF NOT EXISTS(SELECT 1 FROM PriceNameSet WHERE FiledName='ReferPrice')
BEGIN
	INSERT INTO PriceNameSet values(20,'ReferPrice','参考成本价','参考成本价',2593)
END
GO*/
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceProtect]    脚本日期: 05/05/2010 14:48:48 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceProtect]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PriceProtect](
		[PriceId] [int] IDENTITY(1,1) NOT NULL,
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PriceProtect_Ptypeid]  DEFAULT ('0'),
		[Btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PriceProtect_Btypeid]  DEFAULT ('0'),
		[OldPrice] [numeric](18, 4) NULL CONSTRAINT [DF_PriceProtect_OldPrice]  DEFAULT (0),
		[NewPrice] [numeric](18, 4) NULL CONSTRAINT [DF_PriceProtect_NewPrice]  DEFAULT (0),
		[Date] [datetime] NULL,
		[WriteDate] [datetime] NULL,
		[WriteId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PriceProtect_WriteId]  DEFAULT ('0'),
		[State] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PriceProtect_State]  DEFAULT ('0'),
		[StartDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[BillType] [int] NULL,
		[Billids] [varchar](1500) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF__PriceProt__Billi__529D2C8D]  DEFAULT (''),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtect' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE PriceProtect ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE PriceProtect SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtect' AND a.Name='OldPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtect 
	ALTER COLUMN OldPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtect' AND a.Name='NewPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtect 
	ALTER COLUMN NewPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceProtectBill]    脚本日期: 05/05/2010 14:48:48 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceProtectBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PriceProtectBill](
		[BillNumberid] [numeric](10, 0) NOT NULL,
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PriceProtectBill_Ptypeid]  DEFAULT ('0'),
		[OldTotal] [numeric](18, 2) NULL CONSTRAINT [DF_PriceProtectBill_OldTotal]  DEFAULT (0),
		[OldPrice] [numeric](18, 4) NULL CONSTRAINT [DF_PriceProtectBill_OldPrice]  DEFAULT (0),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_PriceProtectBill_Qty]  DEFAULT (0),
		[NewPrice] [numeric](18, 4) NULL CONSTRAINT [DF_PriceProtectBill_NewPrice]  DEFAULT (0),
		[Total] [numeric](18, 2) NULL CONSTRAINT [DF_PriceProtectBill_Total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[BillType] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  null,
	    GoodsNumber			 VARCHAR(100)         DEFAULT('')	,
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PriceProtectBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.PriceProtectBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PriceProtectBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.PriceProtectBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE PriceProtectBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE PriceProtectBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE PriceProtectBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE PriceProtectBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE PriceProtectBill ADD GoodsNumber   VARCHAR(100) DEFAULT('')
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PRICEPROTECTBILL') AND name = 'CIX_PRICEPROTECTBILL_BillNumberID')
--DROP INDEX CIX_PRICEPROTECTBILL_BillNumberID ON PRICEPROTECTBILL 
CREATE CLUSTERED INDEX CIX_PRICEPROTECTBILL_BillNumberID ON PRICEPROTECTBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PRICEPROTECTBILL') AND name = 'NCIX_PRICEPROTECTBILL_Ptypeid')
--DROP INDEX NCIX_PRICEPROTECTBILL_Ptypeid ON PRICEPROTECTBILL 
CREATE NONCLUSTERED INDEX NCIX_PRICEPROTECTBILL_Ptypeid ON PRICEPROTECTBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PRICEPROTECTBILL') AND name = 'NCIX_PRICEPROTECTBILL_Stypeid')
--DROP INDEX NCIX_PRICEPROTECTBILL_Stypeid ON PRICEPROTECTBILL 
CREATE NONCLUSTERED INDEX NCIX_PRICEPROTECTBILL_Stypeid ON PRICEPROTECTBILL(Stypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='OldTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtectBill 
	ALTER COLUMN OldTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='OldPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtectBill 
	ALTER COLUMN OldPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtectBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='NewPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtectBill 
	ALTER COLUMN NewPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtectBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceProtectList]    脚本日期: 05/05/2010 14:48:49 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceProtectList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PriceProtectList](
		[Serial] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PriceProtectList_Ptypeid]  DEFAULT ('0'),
		[Btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PriceProtectList_Btypeid]  DEFAULT ('0'),
		[OldTotal] [numeric](18, 2) NULL CONSTRAINT [DF_PriceProtectList_OldTotal]  DEFAULT (0),
		[CurPrice] [numeric](18, 4) NULL CONSTRAINT [DF_PriceProtectList_CurPrice]  DEFAULT (0),
		[NewPrice] [numeric](18, 4) NULL CONSTRAINT [DF_PriceProtectList_NewPrice]  DEFAULT (0),
		[BillType] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectList' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE PriceProtectList ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE PriceProtectList SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectList' AND a.Name='OldTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtectList 
	ALTER COLUMN OldTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectList' AND a.Name='CurPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtectList 
	ALTER COLUMN CurPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceProtectList' AND a.Name='NewPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceProtectList 
	ALTER COLUMN NewPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule
(
	ID		 NUMERIC(18,0) IDENTITY(1,1),
	UserCode varchar(200) NOT NULL,				-- 取价规则编号 
	FullName varchar(200) NOT NULL,				-- 取价规则名称 
	PriceBillIndexID numeric(18) NOT NULL,		-- 价格表ID 
	VipConfig int,								-- 规则条件设置之会员卡 0=不区分是否是会员  1=适用全部会员卡类型  2=适用部分会员卡类型  3=不适用部分会员卡类型 
	StoresConfig int,							-- 门店配置  0=适用全部门店  1=使用部分门店  2=不使用部分门店 
	KConfig int,								-- 仓库配置  0=适用全部仓库  1=适用部分仓库  3=不适用部分仓库 
	DConfig int,								-- 部门设置 0=适用全部部分  1=适用部分部门  2=不适用部分部门 
	EConfig int,								-- 业务员配置  0=适用全部业务员  1=适用部分业务员  3=不适使用部分业务员
	BConfig int,								-- 规则条件设置之往来单位 0=适用全部往来单位  1=适用部分往来单位  2=适用部分结算单位 
	StartDate datetime,							-- 生效时期 
	EndDate datetime,							-- 失效时期 
	StartTime varchar(10),  					-- 开始时段 
	EndTime varchar(10),    					-- 结束时段 
	PriceDay varchar(7),    					-- 取价日设定星期1到7存1234567字符串 
	Comment varchar(256),   					-- 备注 
	[State] int,								-- 单据状态0=新增 1=待审核  2=执行  3=作废 
	Checke varchar(50),							-- 制单人 
	Checker varchar(50),    					-- 审核人 
	VaildDate datetime,							-- 审核时期 
	DeletedR varchar(50),   					-- 作废人 
	DeletedDate datetime,   					-- 作废时期 
	CreateDate datetime,    					-- 制单日期 
	XiWaMaxNumber	NUMERIC(18, 0) NULL DEFAULT (0),
	PosDataVersion timestamp,
	VipEnable int,								--会员折扣是否有效 1有效,否则无效
	BtypeEnable int,							--往来单位有效	1有效,否则无效
	VBEnable int								--会员折扣和往来单位都有效 1有效,否则无效
)
END
GO


if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceRule]') and name = 'XiWaMaxNumber' )
BEGIN
	ALTER TABLE dbo.PriceRule  ADD
		XiWaMaxNumber NUMERIC(18, 0) NULL DEFAULT (0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceRule]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.PriceRule ADD  PosDataVersion timestamp
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceRule]') and name = 'BConfig' )
BEGIN
	ALTER TABLE dbo.PriceRule ADD  BConfig int -- 规则条件设置之往来单位 0=适用全部往来单位  1=适用部分往来单位  2=适用部分结算单位
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceRule]') and name = 'VipEnable' )
BEGIN
	ALTER TABLE dbo.PriceRule ADD  VipEnable int--会员折扣是否有效 1有效否则无效
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceRule]') and name = 'BtypeEnable' )
BEGIN
	ALTER TABLE dbo.PriceRule ADD  BtypeEnable int--往来单位有效
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PriceRule]') and name = 'VBEnable' )
BEGIN
	ALTER TABLE dbo.PriceRule ADD  VBEnable int--会员折扣和往来单位都有效
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule') AND name = 'NCIX_PriceRule_PriceBillIndexID')
--DROP INDEX NCIX_PriceRule_PriceBillIndexID ON PriceRule 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_PriceBillIndexID ON PriceRule(PriceBillIndexID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule') AND name = 'NCIX_PriceRule_StartDate')
--DROP INDEX NCIX_PriceRule_StartDate ON PriceRule 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_StartDate ON PriceRule(StartDate)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule') AND name = 'NCIX_PriceRule_EndDate')
--DROP INDEX NCIX_PriceRule_EndDate ON PriceRule 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_EndDate ON PriceRule(EndDate)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule') AND name = 'NCIX_PriceRule_StartTime')
--DROP INDEX NCIX_PriceRule_StartTime ON PriceRule 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_StartTime ON PriceRule(StartTime)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule') AND name = 'NCIX_PriceRule_EndTime')
--DROP INDEX NCIX_PriceRule_EndTime ON PriceRule 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_EndTime ON PriceRule(EndTime)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule_Detail_BConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule_Detail_BConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule_Detail_BConfig
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PriceRuleID		NUMERIC(18,0),
	Btypeid			VARCHAR(50)    -- 客户typeid 
)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule_Detail_DConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule_Detail_DConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule_Detail_DConfig
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PriceRuleID		NUMERIC(18,0),
	Dtypeid			VARCHAR(50)    -- 部门typeid 
)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule_Detail_EConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule_Detail_EConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule_Detail_EConfig
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PriceRuleID		NUMERIC(18,0) NOT NULL,
	Etypeid			VARCHAR(50) NOT NULL    -- 业务员typeid 
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule_Detail_EConfig') AND name = 'NCIX_PriceRule_Detail_EConfig_PriceRuleID')
--DROP INDEX NCIX_PriceRule_Detail_EConfig_PriceRuleID ON PriceRule_Detail_EConfig 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_Detail_EConfig_PriceRuleID ON PriceRule_Detail_EConfig(PriceRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule_Detail_EConfig') AND name = 'NCIX_PriceRule_Detail_EConfig_Etypeid')
--DROP INDEX NCIX_PriceRule_Detail_EConfig_Etypeid ON PriceRule_Detail_EConfig 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_Detail_EConfig_Etypeid ON PriceRule_Detail_EConfig(Etypeid)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule_Detail_KConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule_Detail_KConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule_Detail_KConfig
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PriceRuleID		NUMERIC(18,0),
	Ktypeid			VARCHAR(50)
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule_Detail_KConfig') AND name = 'NCIX_PriceRule_Detail_KConfig_PriceRuleID')
--DROP INDEX NCIX_PriceRule_Detail_KConfig_PriceRuleID ON PriceRule_Detail_KConfig 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_Detail_KConfig_PriceRuleID ON PriceRule_Detail_KConfig(PriceRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule_Detail_KConfig') AND name = 'NCIX_PriceRule_Detail_KConfig_Ktypeid')
--DROP INDEX NCIX_PriceRule_Detail_KConfig_Ktypeid ON PriceRule_Detail_KConfig 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_Detail_KConfig_Ktypeid ON PriceRule_Detail_KConfig(Ktypeid)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule_Detail_StoresConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule_Detail_StoresConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule_Detail_StoresConfig
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PriceRuleID		NUMERIC(18,0),
	StoresID	    VARCHAR(50) -- 门店typeid 
)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule_Detail_StoresConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule_Detail_StoresConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule_Detail_StoresConfig
(
	PriceRuleID		NUMERIC(18,0),
	MDtypeID	    VARCHAR(50) -- 门店typeid 
)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule_Detail_VipConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule_Detail_VipConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule_Detail_VipConfig
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PriceRuleID		NUMERIC(18,0),  -- 主表ID 
	VipTypeID		INT,			-- vip会员卡类型ID 
	StartCardNum	VARCHAR(50),    -- 起始卡号 
	EndCardNum		VARCHAR(50)     -- 截止卡号 
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule_Detail_VipConfig') AND name = 'NCIX_PriceRule_Detail_VipConfig_PriceRuleID')
--DROP INDEX NCIX_PriceRule_Detail_VipConfig_PriceRuleID ON PriceRule_Detail_VipConfig 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_Detail_VipConfig_PriceRuleID ON PriceRule_Detail_VipConfig(PriceRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule_Detail_VipConfig') AND name = 'NCIX_PriceRule_Detail_VipConfig_VipTypeID')
--DROP INDEX NCIX_PriceRule_Detail_VipConfig_VipTypeID ON PriceRule_Detail_VipConfig 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_Detail_VipConfig_VipTypeID ON PriceRule_Detail_VipConfig(VipTypeID)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRule_Stype]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRule_Stype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRule_Stype
(
	PriceRuleID		NUMERIC(18,0) NOT NULL,    -- 价格规则主表ID 
	Stypeid VARCHAR(50)
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule_Stype') AND name = 'NCIX_PriceRule_Stype_PriceRuleID')
--DROP INDEX NCIX_PriceRule_Stype_PriceRuleID ON PriceRule_Stype 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_Stype_PriceRuleID ON PriceRule_Stype(PriceRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRule_Stype') AND name = 'NCIX_PriceRule_Stype_Stypeid')
--DROP INDEX NCIX_PriceRule_Stype_Stypeid ON PriceRule_Stype 
CREATE NONCLUSTERED INDEX NCIX_PriceRule_Stype_Stypeid ON PriceRule_Stype(Stypeid)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceRulePriority]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceRulePriority]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceRulePriority
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PriceRuleID		NUMERIC(18,0), --取价规则ID
	StypeID			VARCHAR(50),
	SortID			INT 
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRulePriority') AND name = 'NCIX_PriceRulePriority_PriceRuleID')
--DROP INDEX NCIX_PriceRulePriority_PriceRuleID ON PriceRulePriority 
CREATE NONCLUSTERED INDEX NCIX_PriceRulePriority_PriceRuleID ON PriceRulePriority(PriceRuleID,SortID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PriceRulePriority') AND name = 'NCIX_PriceRulePriority_StypeID')
--DROP INDEX NCIX_PriceRulePriority_StypeID ON PriceRulePriority 
CREATE NONCLUSTERED INDEX NCIX_PriceRulePriority_StypeID ON PriceRulePriority(StypeID)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceStyle]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceStyle]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PriceStyle
(
	BillType		INT,
	IsTopPolicy		TINYINT,   -- 是否启用高级价格策略 1=启用 
	IsDownPolicy	TINYINT    -- 是否启用基本价格策略 1=启用 
)

DELETE PriceStyle
INSERT PriceStyle VALUES(305,0,1) 

END

GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 305)
BEGIN
	INSERT PriceStyle VALUES(305,0,1) --零售单
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 215)
BEGIN
	INSERT PriceStyle VALUES(215,0,1)--零售退货单
END	
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 11)
BEGIN
	INSERT PriceStyle VALUES(11,0,1) --销售出库
END	
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 45)
BEGIN
	INSERT PriceStyle VALUES(45,0,1)--销售退货单
END	
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 160)
BEGIN
	INSERT PriceStyle VALUES(160,0,1)--销售换货单
END	
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 140)
BEGIN
	INSERT PriceStyle VALUES(140,0,1)--委托代销发货单
END	
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 142)
BEGIN
	INSERT PriceStyle VALUES(142,0,1)--委托代销退货单
END	
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 141)
BEGIN
	INSERT PriceStyle VALUES(141,0,1)--委托代销结算单
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 300)
BEGIN
	INSERT PriceStyle VALUES(300,0,1)-- 销售订单
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 313)
BEGIN
	INSERT PriceStyle VALUES(313,0,1)-- 组合品销售订单
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 12)
BEGIN
	INSERT PriceStyle VALUES(12,0,1)-- 组合品销售出库单
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 46)
BEGIN
	INSERT PriceStyle VALUES(46,0,1)-- 组合品销售退货单
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM PriceStyle WHERE BillType = 403)
BEGIN
	INSERT INTO PriceStyle(BillType,IsTopPolicy,IsDownPolicy) VALUES(403,0,1)-- 组合品销售退货单
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PriceTrack]    脚本日期: 05/05/2010 14:48:50 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceTrack]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PriceTrack](
		[BtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[CostPrice] [numeric](18, 4) NULL,
		[SaleOrderPrice] [numeric](18, 4) NULL,
		[BuyOrderPrice] [numeric](18, 4) NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[BTypeFlag] INT NOT NULL CONSTRAINT DF_PriceTrace_BTypeFlag DEFAULT(0) -- 0结算单位 1往来单位
		,
		BuyOrBackOriginalPrice [numeric](18, 4) NULL,
		BuyOrBackDiscountRate [numeric](22, 10) NULL,
		SaleOrBackOriginalPrice [numeric](18, 4) NULL,
		SaleOrBackDiscountRate [numeric](22, 10) NULL
	) ON [PRIMARY]


END
GO




------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='STypeID'
)
BEGIN
	
	ALTER TABLE PriceTrack ADD STypeID VARCHAR(50) DEFAULT '' NULL
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE PriceTrack SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END


GO

--询价单价格跟踪
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='QueryPrice'
)
BEGIN
	ALTER TABLE PriceTrack ADD QueryPrice [numeric](18, 4) NULL
END
GO

--报价单价格跟踪
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='ResponsePrice'
)
BEGIN
	ALTER TABLE PriceTrack ADD ResponsePrice [numeric](18, 4) NULL
END
	
GO

--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='Discount'
)
BEGIN
	ALTER TABLE PriceTrack ADD Discount [numeric](18, 4) NULL
END
	
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='total'
)
BEGIN
	ALTER TABLE PriceTrack ADD total [numeric](18, 2) NULL
END
	
GO

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='UID'
)
BEGIN
	ALTER TABLE PriceTrack ADD UID INT DEFAULT(0) NULL 
END
GO

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='CID'
)
BEGIN
	ALTER TABLE PriceTrack ADD CID INT DEFAULT(0) NULL 
END
GO

--询价单价格跟踪
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='QueryPrice'
)
BEGIN
	ALTER TABLE PriceTrack ALTER COLUMN QueryPrice [numeric](18, 4) NULL
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='ResponsePrice'
)
BEGIN
	ALTER TABLE PriceTrack ALTER COLUMN ResponsePrice [numeric](18, 4) NULL
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='SalePrice'
)
BEGIN
	ALTER TABLE PriceTrack ALTER COLUMN SalePrice [numeric](18, 4) NULL
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='CostPrice'
)
BEGIN
	ALTER TABLE PriceTrack ALTER COLUMN CostPrice [numeric](18, 4) NULL
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='SaleOrderPrice'
)
BEGIN
	ALTER TABLE PriceTrack ALTER COLUMN SaleOrderPrice [numeric](18, 4) NULL
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='BuyOrderPrice'
)
BEGIN
	ALTER TABLE PriceTrack ALTER COLUMN BuyOrderPrice [numeric](18, 4) NULL
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='total'
)
BEGIN
	ALTER TABLE PriceTrack ALTER COLUMN total [numeric](18, 4) NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='BTypeFlag'
)
BEGIN
	ALTER TABLE PriceTrack ADD [BTypeFlag] INT NOT NULL DEFAULT(0); -- 0结算单位 1往来单位
END
GO


-- 新增
-- 采购，采购退货折前价
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='BuyOrBackOriginalPrice'
)
BEGIN
	ALTER TABLE PriceTrack ADD BuyOrBackOriginalPrice [numeric](18, 4) NULL
END
GO
-- 折扣率
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='BuyOrBackDiscountRate'
)
BEGIN
	ALTER TABLE PriceTrack ADD BuyOrBackDiscountRate [numeric](22, 10) NULL
END
GO
--销售，销售退货
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='SaleOrBackOriginalPrice'
)
BEGIN
	ALTER TABLE PriceTrack ADD SaleOrBackOriginalPrice [numeric](18, 4) NULL
END
GO
--折扣率
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='SaleOrBackDiscountRate'
)
BEGIN
	ALTER TABLE PriceTrack ADD SaleOrBackDiscountRate [numeric](22, 10) NULL
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PriceTrack]') AND name = N'IX_PriceTrack_BTypeId')
DROP INDEX [dbo].[PriceTrack].[IX_PriceTrack_BTypeId]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PriceTrack]') AND name = N'IX_PriceTrack_PTypeId')
DROP INDEX [dbo].[PriceTrack].[IX_PriceTrack_PTypeId]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PRICETRACK') AND name = 'NCIX_PRICETRACK_BtypeID')
--DROP INDEX NCIX_PRICETRACK_BtypeID ON PRICETRACK 
CREATE NONCLUSTERED INDEX NCIX_PRICETRACK_BtypeID ON PRICETRACK(BtypeID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PRICETRACK') AND name = 'NCIX_PRICETRACK_PtypeID')
--DROP INDEX NCIX_PRICETRACK_PtypeID ON PRICETRACK 
CREATE NONCLUSTERED INDEX NCIX_PRICETRACK_PtypeID ON PRICETRACK(PtypeID) 
------------------------------------------创建索引区域结束-----------------------------------------------


-- 升级处理部分
UPDATE dbo.PriceTrack SET BuyOrBackOriginalPrice=CostPrice,BuyOrBackDiscountRate=1 WHERE CostPrice IS NOT NULL AND BuyOrBackDiscountRate IS NULL  AND BuyOrBackOriginalPrice IS NULL;
UPDATE dbo.PriceTrack SET SaleOrBackOriginalPrice=SalePrice,SaleOrBackDiscountRate=1 WHERE SalePrice IS NOT NULL AND SaleOrBackDiscountRate IS NULL AND SaleOrBackOriginalPrice IS NULL;

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='SaleOrderPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN SaleOrderPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='BuyOrderPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN BuyOrderPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='BuyOrBackOriginalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN BuyOrBackOriginalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='BuyOrBackDiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN BuyOrBackDiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='SaleOrBackOriginalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN SaleOrBackOriginalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='SaleOrBackDiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN SaleOrBackDiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='QueryPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN QueryPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='ResponsePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN ResponsePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				暂估入库价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_Appraisal',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_Appraisal]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[STypeID]			VARCHAR(50)		  NOT NULL,		--分支机构Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL		--币种Id
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_STypeID]		DEFAULT('') FOR [STypeID]
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_Appraisal] ADD CONSTRAINT [DF_PriceTrack_Appraisal_CID]			DEFAULT(0)  FOR [CID]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_Appraisal]') AND name = N'IX_PriceTrack_Appraisal')
	DROP INDEX [IX_PriceTrack_Appraisal] ON [dbo].PriceTrack_Appraisal WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_Appraisal] ON [dbo].[PriceTrack_Appraisal] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[StypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Appraisal',N'U') AND LOWER(Name)='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_Appraisal
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_Appraisal SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Appraisal',N'U') AND LOWER(Name)='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_Appraisal
	ADD TaxPrice NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_Appraisal SET TaxPrice=DiscountPrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Appraisal',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_Appraisal
	ADD TrackTime DATETIME
END

---------------------修改区域---------------------------------

SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Appraisal' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Appraisal 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Appraisal' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Appraisal 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Appraisal' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Appraisal 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Appraisal' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Appraisal 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Appraisal' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Appraisal 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrack_AskPrice') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PriceTrack_AskPrice(
		BtypeId VARCHAR(100)
		,BtypeFlag INT
		,PtypeId VARCHAR(100)
		,StypeId VARCHAR(100)
		,[UId] INT
		,[CId] INT
		
		,Price NUMERIC(24,10)
		,DiscountRate NUMERIC(24,10)
		,DiscountPrice NUMERIC(24,10)
	)
END
GO

----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_AskPrice',N'U') AND LOWER(Name)='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_AskPrice
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_AskPrice SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_AskPrice',N'U') AND LOWER(Name)='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_AskPrice
	ADD TaxPrice NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_AskPrice SET TaxPrice=DiscountPrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_AskPrice',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_AskPrice
	ADD TrackTime DATETIME
END
---------------------修改区域---------------------------------


/****** Object:  Index [IX_PriceTrack_AskPrice]    Script Date: 01/27/2015 10:48:20 ******/
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_AskPrice]') AND name = N'IX_PriceTrack_AskPrice')
DROP INDEX [IX_PriceTrack_AskPrice] ON [dbo].[PriceTrack_AskPrice] WITH ( ONLINE = OFF )
GO


/****** Object:  Index [IX_PriceTrack_AskPrice]    Script Date: 01/27/2015 10:48:20 ******/
CREATE NONCLUSTERED INDEX [IX_PriceTrack_AskPrice] ON [dbo].[PriceTrack_AskPrice] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[StypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_AskPrice' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_AskPrice 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_AskPrice' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_AskPrice 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_AskPrice' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_AskPrice 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_AskPrice' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_AskPrice 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_AskPrice' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_AskPrice 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrack_Buy') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PriceTrack_Buy(
		BtypeId VARCHAR(100),
		BtypeFlag INT,
		PtypeId VARCHAR(100),
		StypeId VARCHAR(100),
		UId INT,
		CId INT,
		Price NUMERIC(24,10),
		DiscountRate NUMERIC(24,10),
		DiscountPrice NUMERIC(24,10)
	)
END
GO


----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Buy',N'U') AND LOWER(Name)='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_Buy
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_Buy SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Buy',N'U') AND LOWER(Name)='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_Buy
	ADD TaxPrice NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_Buy SET TaxPrice=DiscountPrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Buy',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_Buy
	ADD TrackTime DATETIME
END
---------------------修改区域---------------------------------


IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_Buy]') AND name = N'IX_PriceTrack_Buy')
DROP INDEX [IX_PriceTrack_Buy] ON [dbo].PriceTrack_Buy WITH ( ONLINE = OFF )
GO


/****** Object:  Index [IX_PriceTrack_SaleOrder]    Script Date: 01/26/2015 15:53:22 ******/
CREATE CLUSTERED INDEX [IX_PriceTrack_Buy] ON [dbo].[PriceTrack_Buy] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[StypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Buy' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Buy 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Buy' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Buy 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Buy' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Buy 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Buy' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Buy 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Buy' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Buy 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrack_BuyOrder') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PriceTrack_BuyOrder(
		BtypeId VARCHAR(100)
		,BtypeFlag INT
		,PtypeId VARCHAR(100)
		,StypeId VARCHAR(100)
		,[UId] INT
		,[CId] INT
		
		,Price NUMERIC(24,10)
		,DiscountRate NUMERIC(24,10)
		,DiscountPrice NUMERIC(24,10)
	)
END
GO

----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_BuyOrder',N'U') AND LOWER(Name)='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_BuyOrder
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_BuyOrder SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_BuyOrder',N'U') AND LOWER(Name)='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_BuyOrder
	ADD TaxPrice NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_BuyOrder SET TaxPrice=DiscountPrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_BuyOrder',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_BuyOrder
	ADD TrackTime DATETIME
END
---------------------修改区域--------------------------------

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_BuyOrder]') AND name = N'IX_PriceTrack_BuyOrder')
DROP INDEX [IX_PriceTrack_BuyOrder] ON [dbo].[PriceTrack_BuyOrder] WITH ( ONLINE = OFF )
GO


/****** Object:  Index [IX_PriceTrack_SaleOrder]    Script Date: 01/26/2015 15:53:22 ******/
CREATE CLUSTERED INDEX [IX_PriceTrack_BuyOrder] ON [dbo].[PriceTrack_BuyOrder] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[StypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_BuyOrder' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_BuyOrder 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_BuyOrder' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_BuyOrder 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_BuyOrder' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_BuyOrder 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_BuyOrder' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_BuyOrder 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_BuyOrder' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_BuyOrder 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrack_Quote') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PriceTrack_Quote(
		BtypeId VARCHAR(100)
		,BtypeFlag INT
		,PtypeId VARCHAR(100)
		,StypeId VARCHAR(100)
		,[UId] INT
		,[CId] INT
		
		,Price NUMERIC(24,10)
		,DiscountRate NUMERIC(24,10)
		,DiscountPrice NUMERIC(24,10)
	)
END
GO


----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Quote',N'U') AND LOWER(Name)='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_Quote
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_Quote SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Quote',N'U') AND LOWER(Name)='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_Quote
	ADD TaxPrice NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_Quote SET TaxPrice=DiscountPrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Quote',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_Quote
	ADD TrackTime DATETIME
END
---------------------修改区域--------------------------------

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_Quote]') AND name = N'IX_PriceTrack_Quote')
DROP INDEX [IX_PriceTrack_Quote] ON [dbo].PriceTrack_Quote WITH ( ONLINE = OFF )
GO



CREATE CLUSTERED INDEX [IX_PriceTrack_Quote] ON [dbo].[PriceTrack_Quote] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[StypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Quote' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Quote 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Quote' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Quote 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Quote' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Quote 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Quote' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Quote 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Quote' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Quote 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrack_Sale') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PriceTrack_Sale(
		BtypeId VARCHAR(100)
		,BtypeFlag INT
		,PtypeId VARCHAR(100)
		,StypeId VARCHAR(100)
		,[UId] INT
		,[CId] INT
		
		,Price NUMERIC(24,10)
		,DiscountRate NUMERIC(24,10)
		,DiscountPrice NUMERIC(24,10)
	)
END
GO

----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Sale',N'U') AND LOWER(Name)='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_Sale
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_Sale SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Sale',N'U') AND LOWER(Name)='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_Sale
	ADD TaxPrice NUMERIC(24,10)
END
GO
	UPDATE PriceTrack_Sale SET TaxPrice=DiscountPrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Sale',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_Sale
	ADD TrackTime DATETIME
END
---------------------修改区域--------------------------------

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_Sale]') AND name = N'IX_PriceTrack_Sale')
DROP INDEX [IX_PriceTrack_Sale] ON [dbo].PriceTrack_Sale WITH ( ONLINE = OFF )
GO


/****** Object:  Index [IX_PriceTrack_SaleOrder]    Script Date: 01/26/2015 15:53:22 ******/
CREATE CLUSTERED INDEX [IX_PriceTrack_Sale] ON [dbo].[PriceTrack_Sale] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[StypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Sale' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Sale 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Sale' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Sale 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Sale' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Sale 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Sale' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Sale 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Sale' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Sale 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrack_SaleOrder') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PriceTrack_SaleOrder(
		BtypeId VARCHAR(100)
		,BtypeFlag INT
		,PtypeId VARCHAR(100)
		,StypeId VARCHAR(100)
		,[UId] INT
		,[CId] INT
		
		,Price NUMERIC(24,10)
		,DiscountRate NUMERIC(24,10)
		,DiscountPrice NUMERIC(24,10)
	)
END
GO


----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_SaleOrder',N'U') AND LOWER(Name)='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_SaleOrder
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_SaleOrder SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_SaleOrder',N'U') AND LOWER(Name)='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_SaleOrder
	ADD TaxPrice NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_SaleOrder SET TaxPrice=DiscountPrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_SaleOrder',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_SaleOrder
	ADD TrackTime DATETIME
END
---------------------修改区域--------------------------------


/****** Object:  Index [IX_PriceTrack_SaleOrder]    Script Date: 01/26/2015 15:52:24 ******/
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SaleOrder]') AND name = N'IX_PriceTrack_SaleOrder')
DROP INDEX [IX_PriceTrack_SaleOrder] ON [dbo].[PriceTrack_SaleOrder] WITH ( ONLINE = OFF )
GO


/****** Object:  Index [IX_PriceTrack_SaleOrder]    Script Date: 01/26/2015 15:53:22 ******/
CREATE CLUSTERED INDEX [IX_PriceTrack_SaleOrder] ON [dbo].[PriceTrack_SaleOrder] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[StypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_SaleOrder' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_SaleOrder 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_SaleOrder' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_SaleOrder 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_SaleOrder' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_SaleOrder 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_SaleOrder' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_SaleOrder 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_SaleOrder' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_SaleOrder 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
	/*
			发出商品价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_Send',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_Send]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[STypeID]			VARCHAR(50)		  NOT NULL,		--分支机构Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL		--币种Id
			
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_BTypeID]			DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_PTypeID]			DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_STypeID]			DEFAULT('') FOR [STypeID]
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_DiscountPrice]	DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_UID]				DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_Send] ADD CONSTRAINT [DF_PriceTrack_Send_CID]				DEFAULT(0)  FOR [CID]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_Send]') AND name = N'IX_PriceTrack_Send')
	DROP INDEX [IX_PriceTrack_Send] ON [dbo].PriceTrack_Send WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_Send] ON [dbo].[PriceTrack_Send] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[StypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Send',N'U') AND LOWER(Name)='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_Send
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_Send SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Send',N'U') AND LOWER(Name)='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_Send
	ADD TaxPrice NUMERIC(24,10)
END
GO
	UPDATE PriceTrack_Send SET TaxPrice=DiscountPrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_Send',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_Send
	ADD TrackTime DATETIME
END
---------------------修改区域--------------------------------

SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Send' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Send 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Send' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Send 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Send' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Send 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Send' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Send 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_Send' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_Send 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				暂估入库分支机构间价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_SType_Appraisal',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_SType_Appraisal]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL,		--币种Id
			[Tax]				NUMERIC(24,10)	  NOT NULL,		--税率
			[TaxPrice]			NUMERIC(24,10)	  NOT NULL,		--含税价格
			[TrackTime]			DATETIME		  NOT NULL		--跟踪时间
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_CID]			DEFAULT(0)  FOR [CID]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_Tax]			DEFAULT(0)  FOR [Tax]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_TaxPrice]		DEFAULT(0)  FOR [TaxPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Appraisal] ADD CONSTRAINT [DF_PriceTrack_SType_Appraisal_TrackTime]		DEFAULT(GETDATE())  FOR [TrackTime]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SType_Appraisal]') AND name = N'IX_PriceTrack_SType_Appraisal')
	DROP INDEX [IX_PriceTrack_SType_Appraisal] ON [dbo].PriceTrack_SType_Appraisal WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_SType_Appraisal] ON [dbo].[PriceTrack_SType_Appraisal] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				询价单分支机构间价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_SType_AskPrice',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_SType_AskPrice]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL,		--币种Id
			[Tax]				NUMERIC(24,10)	  NOT NULL,		--税率
			[TaxPrice]			NUMERIC(24,10)	  NOT NULL,		--含税价格
			[TrackTime]			DATETIME		  NOT NULL		--跟踪时间
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_CID]			DEFAULT(0)  FOR [CID]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_Tax]			DEFAULT(0)  FOR [Tax]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_TaxPrice]		DEFAULT(0)  FOR [TaxPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_AskPrice] ADD CONSTRAINT [DF_PriceTrack_SType_AskPrice_TrackTime]		DEFAULT(GETDATE())  FOR [TrackTime]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SType_AskPrice]') AND name = N'IX_PriceTrack_SType_AskPrice')
	DROP INDEX [IX_PriceTrack_SType_AskPrice] ON [dbo].PriceTrack_SType_AskPrice WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_SType_AskPrice] ON [dbo].[PriceTrack_SType_AskPrice] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				采购入库分支机构间价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_SType_Buy',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_SType_Buy]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL,		--币种Id
			[Tax]				NUMERIC(24,10)	  NOT NULL,		--税率
			[TaxPrice]			NUMERIC(24,10)	  NOT NULL,		--含税价格
			[TrackTime]			DATETIME		  NOT NULL		--跟踪时间
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_CID]			DEFAULT(0)  FOR [CID]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_Tax]			DEFAULT(0)  FOR [Tax]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_TaxPrice]		DEFAULT(0)  FOR [TaxPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Buy] ADD CONSTRAINT [DF_PriceTrack_SType_Buy_TrackTime]		DEFAULT(GETDATE())  FOR [TrackTime]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SType_Buy]') AND name = N'IX_PriceTrack_SType_Buy')
	DROP INDEX [IX_PriceTrack_SType_Buy] ON [dbo].PriceTrack_SType_Buy WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_SType_Buy] ON [dbo].[PriceTrack_SType_Buy] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				采购订单分支机构间价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_SType_BuyOrder',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_SType_BuyOrder]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL,		--币种Id
			[Tax]				NUMERIC(24,10)	  NOT NULL,		--税率
			[TaxPrice]			NUMERIC(24,10)	  NOT NULL,		--含税价格
			[TrackTime]			DATETIME		  NOT NULL		--跟踪时间
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_CID]			DEFAULT(0)  FOR [CID]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_Tax]			DEFAULT(0)  FOR [Tax]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_TaxPrice]		DEFAULT(0)  FOR [TaxPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_BuyOrder] ADD CONSTRAINT [DF_PriceTrack_SType_BuyOrder_TrackTime]		DEFAULT(GETDATE())  FOR [TrackTime]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SType_BuyOrder]') AND name = N'IX_PriceTrack_SType_BuyOrder')
	DROP INDEX [IX_PriceTrack_SType_BuyOrder] ON [dbo].PriceTrack_SType_BuyOrder WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_SType_BuyOrder] ON [dbo].[PriceTrack_SType_BuyOrder] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				报价单分支机构间价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_SType_Quote',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_SType_Quote]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL,		--币种Id
			[Tax]				NUMERIC(24,10)	  NOT NULL,		--税率
			[TaxPrice]			NUMERIC(24,10)	  NOT NULL,		--含税价格
			[TrackTime]			DATETIME		  NOT NULL		--跟踪时间
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_CID]			DEFAULT(0)  FOR [CID]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_Tax]			DEFAULT(0)  FOR [Tax]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_TaxPrice]		DEFAULT(0)  FOR [TaxPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Quote] ADD CONSTRAINT [DF_PriceTrack_SType_Quote_TrackTime]		DEFAULT(GETDATE())  FOR [TrackTime]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SType_Quote]') AND name = N'IX_PriceTrack_SType_Quote')
	DROP INDEX [IX_PriceTrack_SType_Quote] ON [dbo].PriceTrack_SType_Quote WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_SType_Quote] ON [dbo].[PriceTrack_SType_Quote] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				销售出库分支机构间价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_SType_Sale',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_SType_Sale]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL,		--币种Id
			[Tax]				NUMERIC(24,10)	  NOT NULL,		--税率
			[TaxPrice]			NUMERIC(24,10)	  NOT NULL,		--含税价格
			[TrackTime]			DATETIME		  NOT NULL		--跟踪时间
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_CID]			DEFAULT(0)  FOR [CID]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_Tax]			DEFAULT(0)  FOR [Tax]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_TaxPrice]		DEFAULT(0)  FOR [TaxPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Sale] ADD CONSTRAINT [DF_PriceTrack_SType_Sale_TrackTime]		DEFAULT(GETDATE())  FOR [TrackTime]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SType_Sale]') AND name = N'IX_PriceTrack_SType_Sale')
	DROP INDEX [IX_PriceTrack_SType_Sale] ON [dbo].PriceTrack_SType_Sale WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_SType_Sale] ON [dbo].[PriceTrack_SType_Sale] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				销售订单分支机构间价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_SType_SaleOrder',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_SType_SaleOrder]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL,		--币种Id
			[Tax]				NUMERIC(24,10)	  NOT NULL,		--税率
			[TaxPrice]			NUMERIC(24,10)	  NOT NULL,		--含税价格
			[TrackTime]			DATETIME		  NOT NULL		--跟踪时间
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_CID]			DEFAULT(0)  FOR [CID]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_Tax]			DEFAULT(0)  FOR [Tax]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_TaxPrice]		DEFAULT(0)  FOR [TaxPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_SaleOrder] ADD CONSTRAINT [DF_PriceTrack_SType_SaleOrder_TrackTime]		DEFAULT(GETDATE())  FOR [TrackTime]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SType_SaleOrder]') AND name = N'IX_PriceTrack_SType_SaleOrder')
	DROP INDEX [IX_PriceTrack_SType_SaleOrder] ON [dbo].PriceTrack_SType_SaleOrder WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_SType_SaleOrder] ON [dbo].[PriceTrack_SType_SaleOrder] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON

GO
	/*
				发出商品分支机构间价格跟踪表
	*/
	IF NOT EXISTS (SELECT [Name] FROM [dbo].[SysObjects] WHERE [ID]=OBJECT_ID(N'PriceTrack_SType_Send',N'U'))
	BEGIN
		CREATE TABLE [dbo].[PriceTrack_SType_Send]
		(
			[BTypeID]			VARCHAR(100)	  NOT NULL,     --往来结算单位
			[BTypeFlag]			INT				  NOT NULL,
			[PTypeID]			VARCHAR(50)		  NOT NULL,     --商品Id
			[Price]				NUMERIC(24,10)	  NOT NULL,		--单价
			[DiscountRate]		NUMERIC(24,10)	  NOT NULL,		--折扣
			[DiscountPrice]     NUMERIC(24,10)    NOT NULL,		--折后单价
			[UID]				INT				  NOT NULL,		--单位Id
			[CID]				INT				  NOT NULL,		--币种Id
			[Tax]				NUMERIC(24,10)	  NOT NULL,		--税率
			[TaxPrice]			NUMERIC(24,10)	  NOT NULL,		--含税价格
			[TrackTime]			DATETIME		  NOT NULL		--跟踪时间
		)ON [PRIMARY]
		
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_BTypeID]		DEFAULT('') FOR [BTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_BTypeFlag]		DEFAULT(0)  FOR [BTypeFlag]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_PTypeID]		DEFAULT('') FOR [PTypeID]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_Price]			DEFAULT(0)  FOR [Price]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_DiscountRate]	DEFAULT(0)  FOR [DiscountRate]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_DiscountPrice] DEFAULT(0)  FOR [DiscountPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_UID]			DEFAULT(0)  FOR [UID]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_CID]			DEFAULT(0)  FOR [CID]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_Tax]			DEFAULT(0)  FOR [Tax]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_TaxPrice]		DEFAULT(0)  FOR [TaxPrice]
		ALTER TABLE [dbo].[PriceTrack_SType_Send] ADD CONSTRAINT [DF_PriceTrack_SType_Send_TrackTime]		DEFAULT(GETDATE())  FOR [TrackTime]
	END
GO

IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_SType_Send]') AND name = N'IX_PriceTrack_SType_Send')
	DROP INDEX [IX_PriceTrack_SType_Send] ON [dbo].PriceTrack_SType_Send WITH ( ONLINE = OFF )
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_SType_Send] ON [dbo].[PriceTrack_SType_Send] 
(
	[BtypeId] ASC,
	[BtypeFlag] ASC,
	[PtypeId] ASC,
	[UId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
			作者：司华山
			日期：2015-05-22
			描述：商品分支机构调拨价格信息表
*/
IF NOT EXISTS(SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'PriceTrack_STypeMove',N'U'))
BEGIN
	CREATE TABLE [dbo].[PriceTrack_STypeMove]
	(
		[ID]			INT IDENTITY(1,1)		NOT NULL,
		[CID]			INT						NOT NULL,  --币种
		[UnitID]		INT						NOT NULL,  --基本计量单位
		[PTypeID]		VARCHAR(50)				NOT NULL,  --商品ID
		[BillType]		INT						NOT NULL,  --单据类型
		[InSTypeID]		VARCHAR(50)				NOT NULL,  --调入分支机构ID
		[OutStypeID]	VARCHAR(50)				NOT NULL,  --调出分支机构ID
		[RecMovePrice]	NUMERIC(24,10)			NOT NULL   --调拨单价
	)ON [PRIMARY]

	ALTER TABLE  [dbo].[PriceTrack_STypeMove] ADD CONSTRAINT  [DF_PriceTrack_STypeMove_CID]				DEFAULT(0)  FOR [CID]
	ALTER TABLE  [dbo].[PriceTrack_STypeMove] ADD CONSTRAINT  [DF_PriceTrack_STypeMove_UnitID]			DEFAULT(0)  FOR [UnitID]
	ALTER TABLE  [dbo].[PriceTrack_STypeMove] ADD CONSTRAINT  [DF_PriceTrack_STypeMove_RecMovePrice]	DEFAULT(0)  FOR [RecMovePrice]
	ALTER TABLE  [dbo].[PriceTrack_STypeMove] ADD CONSTRAINT  [DF_PriceTrack_STypeMove_InStypeID]		DEFAULT('') FOR [InStypeID]
	ALTER TABLE  [dbo].[PriceTrack_STypeMove] ADD CONSTRAINT  [DF_PriceTrack_STypeMove_OutStypeID]		DEFAULT('') FOR [OutStypeID]
	ALTEr TABLE  [dbo].[PriceTrack_STypeMove] ADD CONSTRAINT  [DF_PriceTrack_STypeMove_BillType]		DEFAULT(0)  FOR [BillType]
END
GO
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_STypeMove]') AND name = N'IX_PriceTrack_STypeMove')
	DROP INDEX [IX_PriceTrack_STypeMove] ON [dbo].[PriceTrack_STypeMove] WITH ( ONLINE = OFF )
GO
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PriceTrack_STypeMove]') AND name = N'DF_PriceTrack_STypeMove_ID')
	ALTER Table  [PriceTrack_STypeMove]  DROP Constraint DF_PriceTrack_STypeMove_ID
GO

CREATE CLUSTERED INDEX [IX_PriceTrack_STypeMove] ON [dbo].[PriceTrack_STypeMove] 
(
	[PtypeId] ASC,
	[InStypeId] ASC,
	[OutStypeID] ASC,
	[BillType] ASC,
	[UnitId] ASC,
	[CId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

----------------------修改区域-------------------------------
--税率
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_STypeMove',N'U') AND Name='tax')
BEGIN
	ALTER TABLE dbo.PriceTrack_STypeMove
	ADD Tax NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_STypeMove SET Tax=0 WHERE Tax IS NULL 
GO
--含税价格
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_STypeMove',N'U') AND Name='taxprice')
BEGIN
	ALTER TABLE dbo.PriceTrack_STypeMove
	ADD TaxPrice NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_STypeMove SET TaxPrice=RecMovePrice WHERE TaxPrice IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_STypeMove',N'U') AND Name='DiscountRate')
BEGIN
	ALTER TABLE dbo.PriceTrack_STypeMove
	ADD DiscountRate NUMERIC(24,10) DEFAULT(0)
END
GO
	UPDATE PriceTrack_STypeMove SET DiscountRate=0 WHERE DiscountRate IS NULL 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PriceTrack_STypeMove',N'U') AND Name='TrackTime')
BEGIN
	ALTER TABLE dbo.PriceTrack_STypeMove
	ADD TrackTime DATETIME
END
---------------------修改区域--------------------------------


SET QUOTED_IDENTIFIER OFF;
GO
SET ANSI_NULLS OFF
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_STypeMove' AND a.Name='RecMovePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_STypeMove 
	ALTER COLUMN RecMovePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_STypeMove' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_STypeMove 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_STypeMove' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_STypeMove 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PriceTrack_STypeMove' AND a.Name='DiscountRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PriceTrack_STypeMove 
	ALTER COLUMN DiscountRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrackConfig') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [PriceTrackConfig](
		[Name] VARCHAR(100)
		,[Value] INT
	)
END
GO


-- 预制数据 --
IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='BuyBtypeFlag')
	INSERT INTO [PriceTrackConfig] SELECT 'BuyBtypeFlag',-1;
GO

IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='SaleBtypeFlag')
	INSERT INTO [PriceTrackConfig] SELECT 'SaleBtypeFlag',-1;
GO

IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='RecentlyPriceTrack')
	INSERT INTO [PriceTrackConfig] SELECT 'RecentlyPriceTrack',1;
GO
IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='saleRecentlyPriceTrack')
	INSERT INTO [PriceTrackConfig] SELECT 'saleRecentlyPriceTrack',0;
GO
IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='BuyPriceTrackField')
	INSERT INTO [PriceTrackConfig] SELECT 'BuyPriceTrackField',4;
GO
IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='SalePriceTrackField ')
	INSERT INTO [PriceTrackConfig] SELECT 'SalePriceTrackField',4;
GO

IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buystypepricetrack ')
	INSERT INTO [PriceTrackConfig] SELECT 'buystypepricetrack',0;
GO

IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buystyperecpricetrack ')
	INSERT INTO [PriceTrackConfig] SELECT 'buystyperecpricetrack',0;
GO


IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salestypepricetrack ')
	INSERT INTO [PriceTrackConfig] SELECT 'salestypepricetrack',0;
GO


IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salestyperecpricetrack ')
	INSERT INTO [PriceTrackConfig] SELECT 'salestyperecpricetrack',0;
GO


IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buyupdatepricetrack')
	INSERT INTO [PriceTrackConfig] SELECT 'buyupdatepricetrack',0;
GO


IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='saleupdatepricetrack')
	INSERT INTO [PriceTrackConfig] SELECT 'saleupdatepricetrack',0;
GO

	
DECLARE @BuyBtypeFlag int
SELECT @BuyBtypeFlag=Value FROM [PriceTrackConfig] WHERE [Name]='BuyBtypeFlag'

IF @BuyBtypeFlag = -1 
    BEGIN
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='askpricebill')
		INSERT INTO [PriceTrackConfig] SELECT 'askpricebill',0;
	    IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buyorderbill')
		INSERT INTO [PriceTrackConfig] SELECT 'buyorderbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buybill')
		INSERT INTO [PriceTrackConfig] SELECT 'buybill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buybackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'buybackbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buygoodsexchangebill')
		INSERT INTO [PriceTrackConfig] SELECT 'buygoodsexchangebill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill1')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill1',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill2')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill2',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill3')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill3',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill4')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill4',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='appraisalbill')
		INSERT INTO [PriceTrackConfig] SELECT 'appraisalbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='appraisalbackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'appraisalbackbill',0;
	END
ELSE	
    BEGIN
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='askpricebill')
		INSERT INTO [PriceTrackConfig] SELECT 'askpricebill',1;
	    IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buyorderbill')
		INSERT INTO [PriceTrackConfig] SELECT 'buyorderbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buybill')
		INSERT INTO [PriceTrackConfig] SELECT 'buybill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buybackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'buybackbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buygoodsexchangebill')
		INSERT INTO [PriceTrackConfig] SELECT 'buygoodsexchangebill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill1')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill1',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill2')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill2',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill3')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill3',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill4')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill4',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='appraisalbill')
		INSERT INTO [PriceTrackConfig] SELECT 'appraisalbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='appraisalbackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'appraisalbackbill',1;
	END		
DECLARE @SaleBtypeFlag int
SELECT @SaleBtypeFlag=Value FROM [PriceTrackConfig] WHERE [Name]='SaleBtypeFlag'	

IF @SaleBtypeFlag = -1
	BEGIN		
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='quotepricebill')
		INSERT INTO [PriceTrackConfig] SELECT 'quotepricebill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='saleorderbill')
		INSERT INTO [PriceTrackConfig] SELECT 'saleorderbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salebill')
		INSERT INTO [PriceTrackConfig] SELECT 'salebill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='retailbill')
		INSERT INTO [PriceTrackConfig] SELECT 'retailbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salebackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'salebackbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill5')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill5',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill6')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill6',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill7')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill7',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill8')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill8',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salegoodsexchangebills')
		INSERT INTO [PriceTrackConfig] SELECT 'salegoodsexchangebills',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='sendbill')
		INSERT INTO [PriceTrackConfig] SELECT 'sendbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='sendbackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'sendbackbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='combinationorderbill')
		INSERT INTO [PriceTrackConfig] SELECT 'combinationorderbill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='combinationsalebill')
		INSERT INTO [PriceTrackConfig] SELECT 'combinationsalebill',0;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='combinationsalebackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'combinationsalebackbill',0;
    END
ELSE
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='quotepricebill')
		INSERT INTO [PriceTrackConfig] SELECT 'quotepricebill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='saleorderbill')
		INSERT INTO [PriceTrackConfig] SELECT 'saleorderbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salebill')
		INSERT INTO [PriceTrackConfig] SELECT 'salebill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='retailbill')
		INSERT INTO [PriceTrackConfig] SELECT 'retailbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salebackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'salebackbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill5')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill5',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill6')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill6',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill7')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill7',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='commissionbill8')
		INSERT INTO [PriceTrackConfig] SELECT 'commissionbill8',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salegoodsexchangebills ')
		INSERT INTO [PriceTrackConfig] SELECT 'salegoodsexchangebills',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='sendbill')
		INSERT INTO [PriceTrackConfig] SELECT 'sendbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='sendbackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'sendbackbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='combinationorderbill')
		INSERT INTO [PriceTrackConfig] SELECT 'combinationorderbill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='combinationsalebill')
		INSERT INTO [PriceTrackConfig] SELECT 'combinationsalebill',1;
		IF NOT EXISTS(SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='combinationsalebackbill')
		INSERT INTO [PriceTrackConfig] SELECT 'combinationsalebackbill',1;
    END	    
    
--启用分支机构调拨出库单价格跟踪，默认升级不勾选
IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='dbckpricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'dbckpricetrack',0;
--启用分支机构调拨入库单价格跟踪 默认升级不勾选
IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='dbrkpricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'dbrkpricetrack',0;

IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buypricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'buypricetrack',0;

IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='salepricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'salepricetrack',0;



---询价跟踪价格
IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='askpricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'askpricetrack',1;
--订单跟踪价格
IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='buyorderpricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'buyorderpricetrack',1;
--暂估跟踪价格
IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='zangupricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'zangupricetrack',1;
--报价跟踪价格
IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='quotepricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'quotepricetrack',1;
--订单跟踪价格
IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='saleorderpricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'saleorderpricetrack',1;
--发出商品跟踪价格
IF NOT EXISTS (SELECT 1 FROM [PriceTrackConfig] WHERE [Name]='fachupricetrack')
INSERT INTO [PriceTrackConfig] SELECT 'fachupricetrack',1;


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrackField') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	DROP TABLE [PriceTrackField];
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




-- 由于有一定量的预制数据，所以这里就是每次创建新表，不一行一行的判断了
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'PriceTrackNameBillSet') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE PriceTrackNameBillSet;
GO
-- 创建
CREATE TABLE [PriceTrackNameBillSet](
	TrackTableName VARCHAR(100)
	,BuySaleType INT
	,GetSetType INT
	,BillType INT
);

GO

-- 预制数据 --
INSERT INTO [PriceTrackNameBillSet] (TrackTableName,BuySaleType,GetSetType,BillType) VALUES
--保存 销售
('PriceTrack_Quote',2,1,184) --报价
,('PriceTrack_SaleOrder',2,1,300) --订单
,('PriceTrack_SaleOrder',2,1,313) --组合品销售订单
,('PriceTrack_Sale',2,1,11) -- 销售出库单
,('PriceTrack_Sale',2,1,12) -- 组合品销售出库单
,('PriceTrack_Sale',2,1,140) -- 委托代销发货单
,('PriceTrack_Sale',2,1,305) --零售单
,('PriceTrack_Send',2,1,402)--发出商品出库单
--分支机构间
,('PriceTrack_SType_Quote',2,3,184) --报价
,('PriceTrack_SType_SaleOrder',2,3,300) --订单
,('PriceTrack_SType_SaleOrder',2,3,313) --组合品销售订单
,('PriceTrack_SType_Sale',2,3,11) -- 销售出库单
,('PriceTrack_SType_Sale',2,3,12) -- 组合品销售出库单
,('PriceTrack_SType_Sale',2,3,140) -- 委托代销发货单
,('PriceTrack_SType_Sale',2,3,305) --零售单
,('PriceTrack_SType_Send',2,3,402)--发出商品出库单
--采购
,('PriceTrack_AskPrice',1,1,185) --询价
,('PriceTrack_BuyOrder',1,1,301) --订单
,('PriceTrack_Buy',1,1,34) -- 采购入库单
,('PriceTrack_Buy',1,1,144) -- 受托代销收货单
,('PriceTrack_Appraisal',1,1,400)--暂估入库单
--分支机构间
,('PriceTrack_SType_AskPrice',1,3,185) --询价
,('PriceTrack_SType_BuyOrder',1,3,301) --订单
,('PriceTrack_SType_Buy',1,3,34) -- 采购入库单
,('PriceTrack_SType_Buy',1,3,144) -- 受托代销收货单
,('PriceTrack_SType_Appraisal',1,3,400)--暂估入库单

--读取 销售
,('PriceTrack_Quote',2,2,184) --报价
,('PriceTrack_SaleOrder',2,2,300) --订单
,('PriceTrack_SaleOrder',2,2,313) --组合品订单
,('PriceTrack_Sale',2,2,11) -- 销售出库单 
,('PriceTrack_Sale',2,2,12) -- 组合品销售出库单 
,('PriceTrack_Sale',2,2,45) -- 销售退货单
,('PriceTrack_Sale',2,2,46) -- 组合品销售退货单
,('PriceTrack_Sale',2,2,160)-- 销售换货单
,('PriceTrack_Sale',2,2,142)-- 委托退货单
,('PriceTrack_Sale',2,2,141)-- 委托结算单
,('PriceTrack_Sale',2,2,140)-- 委托发货
,('PriceTrack_Sale',2,2,305) --零售单
,('PriceTrack_Sale',2,2,215) -- 零售退货单
,('PriceTrack_Send',2,2,402)--发出商品出库单
,('PriceTrack_Send',2,2,403)--发出商品退货单
--分支机构间
,('PriceTrack_SType_Quote',2,4,184) --报价
,('PriceTrack_SType_SaleOrder',2,4,300) --订单
,('PriceTrack_SType_SaleOrder',2,4,313) --订单
,('PriceTrack_SType_Sale',2,4,11) -- 销售出库单 
,('PriceTrack_SType_Sale',2,4,12) -- 组合品销售出库单 
,('PriceTrack_SType_Sale',2,4,45) -- 销售退货单
,('PriceTrack_SType_Sale',2,4,46) -- 组合品销售退货单
,('PriceTrack_SType_Sale',2,4,160)-- 销售换货单
,('PriceTrack_SType_Sale',2,4,142)-- 委托退货单
,('PriceTrack_SType_Sale',2,4,141)-- 委托结算单
,('PriceTrack_SType_Sale',2,4,140)-- 委托发货
,('PriceTrack_SType_Sale',2,4,305) --零售单
,('PriceTrack_SType_Sale',2,4,215) -- 零售退货单
,('PriceTrack_SType_Send',2,4,402)--发出商品出库单
,('PriceTrack_SType_Send',2,4,403)--发出商品退货单
--采购
,('PriceTrack_AskPrice',1,2,185) --询价
,('PriceTrack_BuyOrder',1,2,301) --采购订单
,('PriceTrack_Buy',1,2,34) -- 采购入库单
,('PriceTrack_Buy',1,2,6) -- 采购退货单
,('PriceTrack_Buy',1,2,161)-- 采购换货单
,('PriceTrack_Buy',1,2,146)-- 受托代销退货单
,('PriceTrack_Buy',1,2,145)-- 受托代销结算单
,('PriceTrack_Buy',1,2,144) -- 受托代销收货单
,('PriceTrack_Appraisal',1,2,400)--暂估入库单
,('PriceTrack_Appraisal',1,2,401)--暂估退货单
--分支机构间
,('PriceTrack_SType_AskPrice',1,4,185) --询价
,('PriceTrack_SType_BuyOrder',1,4,301) --采购订单
,('PriceTrack_SType_Buy',1,4,34) -- 采购入库单
,('PriceTrack_SType_Buy',1,4,6) -- 采购退货单
,('PriceTrack_SType_Buy',1,4,161)-- 采购换货单
,('PriceTrack_SType_Buy',1,4,146)-- 受托代销退货单
,('PriceTrack_SType_Buy',1,4,145)-- 受托代销结算单
,('PriceTrack_SType_Buy',1,4,144) -- 受托代销收货单
,('PriceTrack_SType_Appraisal',1,4,400)--暂估入库单
,('PriceTrack_SType_Appraisal',1,4,401)--暂估退货单
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
打印记录表
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PrintRecord]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PrintRecord](
		[BillType] [numeric](4,0) NOT NULL,
		[BillNumberId] [numeric](10,0) NOT NULL,
		[etypeid] [varchar](50) NOT NULL,
		[PrintTime] [datetime] NOT NULL,
		[Ip] [varchar](50) NOT NULL,
		[PrintCount] [int]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PrintRecord' AND a.Name='eFullName'
)
BEGIN
	ALTER TABLE PrintRecord ADD eFullName varchar(150) DEFAULT '' NULL	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PrintRecord' AND a.Name='BillState'
)
BEGIN
	ALTER TABLE PrintRecord ADD BillState int DEFAULT 0 NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PrintRecord' AND a.Name='billcode'
)
BEGIN
	ALTER TABLE PrintRecord ADD billcode varchar(200)  NULL
END
GO
IF NOT EXISTS(
	SELECT a.NAME FROM syscolumns a 
	INNER JOIN SYSOBJECTS b
	ON A.ID=B.id
	WHERE B.name='PrintRecord' AND A.name='RecordState'
)
BEGIN
	ALTER TABLE dbo.PrintRecord ADD [RecordState] SMALLINT NOT NULL DEFAULT(1)
END
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PrintRecord]') AND name = N'NCIX_BILLTYPE')
	DROP INDEX [dbo].PrintRecord.NCIX_BILLTYPE
	
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PRINTRECORD') AND name = 'NCIX_PRINTRECORD_BillType')
DROP INDEX NCIX_PRINTRECORD_BillType ON PRINTRECORD 
CREATE NONCLUSTERED INDEX NCIX_PRINTRECORD_BillType ON PRINTRECORD(BillType) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PRINTRECORD') AND name = 'NCIX_PRINTRECORD_BillTypebill')
CREATE NONCLUSTERED INDEX NCIX_PRINTRECORD_BillTypebill ON PRINTRECORD(BillType,BillNumberId,PrintCount) 


UPDATE PrintRecord SET eFullName = '' WHERE eFullName IS NULL
UPDATE PrintRecord SET BillState = 0 WHERE BillState IS NULL
GO
SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ProduceModel]    脚本日期: 05/05/2010 14:48:51 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ProduceModel]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ProduceModel](
		[ProduceModelID] [int] NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL
		,ShowOrder INT DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ProduceModel',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.ProduceModel
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE ProduceModel SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
Go

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ProduceModel' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ProduceModel 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ProduceModelIndex]    脚本日期: 05/05/2010 14:48:52 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ProduceModelIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ProduceModelIndex](
		[ProduceModelID] [int] NOT NULL,
		[ProduceModelName] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[CreateTime] DATETIME NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ProduceModelIndex' AND a.Name='CreateTime'
)
BEGIN
	ALTER TABLE ProduceModelIndex ADD CreateTime DATETIME NULL DEFAULT (GETDATE())
END

GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ProduceModelIndex]') AND name = N'PK_ProduceModelIndex')
ALTER TABLE [dbo].[ProduceModelIndex] DROP CONSTRAINT [PK_ProduceModelIndex]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PRODUCEMODELINDEX') AND name = 'CIX_PRODUCEMODELINDEX_ProduceModelID')
--DROP INDEX CIX_PRODUCEMODELINDEX_ProduceModelID ON PRODUCEMODELINDEX 
CREATE CLUSTERED INDEX CIX_PRODUCEMODELINDEX_ProduceModelID ON PRODUCEMODELINDEX(ProduceModelID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[productpic]    脚本日期: 05/05/2010 14:48:53 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[productpic]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[productpic](
		[pic] [image] NULL,
		[length] [int] NULL,
		[filename] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[type] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromoRule_Stype]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	BillCode varchar(200),    -- 单据编号 
	FullName varchar(200),    -- 活动名称 
	PromoStylePtype int,    -- 促销模式 0=买满金额  1=买够商品 
	PromoStyleDiscount int,    -- 促销模式之折扣 0=减免金额  1=送点券 2=送赠品 3=打折 4=特价 5=捆绑销售
	VIPConfig int,    -- 会员卡设定  0=全部客户参与  1=全部会员卡客户参与 2=部分会员卡客户参与 3=部分会员卡客户排除 
	KConfig int,    -- 仓库设定 0=全部仓库 1=部分仓库  2=部分仓库排除 
	EConfig int,    -- 业务员设定  0=全部业务员参与  1=部分业务员参与 2=部分业务员排除 
	PConfig int,    -- 商品设定  0=全部商品参与 1=部分商品参与 2=部分商品排除 
	CalculateStyle int,    -- 计算方式  0=按总计  1=按商品分别计算  2=按商品捆绑计算 
	BindType int,    -- 捆绑方式  整数 
	ReachCondition int,    -- 达到条件  0=达标让利  1=超标让利  2=整体让利 
	AccumulatedProfits int,    -- 累计让利  0=未勾选 1=勾选 
	DoubleDiscount int,    -- 折上折有效  默认0=未勾选 
	BillState int,    -- 单据状态  0=新增 1=待审核  2=执行  3=作废 
	Checke varchar(50),    -- 制单人 
	Checker varchar(50),    -- 审核人 
	VaildDate datetime,    -- 审核时间 
	CreateDate datetime,    -- 创建时间 
	DeletedR varchar(50),    -- 作废人 
	DeletedDate datetime,    -- 作废时间 
	StartDate datetime,    -- 生效时期 
	EndDate datetime,    -- 失效时期 
	StartTime varchar(10),    -- 起始时段 
	EndTime varchar(10),    -- 结束时段 
	PriceDay varchar(7),    -- 取价日设定星期1到7存1234567字符串 
	Comment varchar(256),    -- 备注 
	GiftsType int,    -- 赠品类别 
	XiWaMaxNumber	NUMERIC(18, 0) NULL DEFAULT (0),
	PosDataVersion timestamp
)
END
GO


if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'KConfig' )
BEGIN
ALTER TABLE PromoRule ADD KConfig INT
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'XiWaMaxNumber' )
BEGIN
	ALTER TABLE dbo.PromoRule  ADD
		XiWaMaxNumber NUMERIC(18, 0) NULL DEFAULT (0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.PromoRule ADD  PosDataVersion timestamp
END
GO

if exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'PriceDay' and length = 4)
BEGIN
 ALTER TABLE PromoRule ALTER column PriceDay varchar(7)
END
GO
--0=适用全部往来单位,1=适用部分往来单位,2=适用部分结算单位
if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'BtypeConfig' and length = 4)
BEGIN
 ALTER TABLE dbo.PromoRule  ADD  BtypeConfig int DEFAULT (0)  NOT NULL
END
GO
--促销类型   0.每天  1.每周 2.每月
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'PromoType' )
BEGIN
	ALTER TABLE dbo.PromoRule 
		ADD  PromoType INT DEFAULT(0)
END
GO
UPDATE PromoRule SET PromoType = 0 WHERE PromoType IS NULL
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'PriceMonthDay' )
BEGIN
	ALTER TABLE dbo.PromoRule 
		ADD  PriceMonthDay INT DEFAULT(0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'PriceMonthWeek' )
BEGIN
	ALTER TABLE dbo.PromoRule 
		ADD  PriceMonthWeek VARCHAR(10) DEFAULT('')
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'PriceMonthWeekType' )
BEGIN
	ALTER TABLE dbo.PromoRule 
		ADD  PriceMonthWeekType INT DEFAULT(1)
END
GO

-------9.91添加反审核人、反审核时间-------- 
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'RChecker' )
BEGIN
	ALTER TABLE PromoRule 
	ADD RChecker VARCHAR(50) NULL DEFAULT('')
END
GO
UPDATE PromoRule SET RChecker = '' WHERE RChecker IS NULL
GO

---反审核日期
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule]') and name = 'RVaildDate' )
BEGIN
	ALTER TABLE PromoRule 
	ADD RVaildDate DATETIME NULL DEFAULT('')
END
GO
-----------------END-----------------------

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule') AND name = 'NCIX_PromoRule_StartDate')
--DROP INDEX NCIX_PromoRule_StartDate ON PromoRule 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_StartDate ON PromoRule(StartDate)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule') AND name = 'NCIX_PromoRule_EndDate')
--DROP INDEX NCIX_PromoRule_EndDate ON PromoRule 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_EndDate ON PromoRule(EndDate)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule') AND name = 'NCIX_PromoRule_StartTime')
--DROP INDEX NCIX_PromoRule_StartTime ON PromoRule 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_StartTime ON PromoRule(StartTime)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule') AND name = 'NCIX_PromoRule_EndTime')
--DROP INDEX NCIX_PromoRule_EndTime ON PromoRule 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_EndTime ON PromoRule(EndTime)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO




/****** 对象:  Table [dbo].[PromoRule_Detail_PromotConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule_Detail_BtypeConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule_Detail_BtypeConfig
(
	ID			NUMERIC(18,0) IDENTITY(1,1),
	PromoRuleID NUMERIC(18) NOT NULL,    -- 促销规则ID 
	btypeid				VARCHAR(50)  --往来单位
)
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromoRule_Detail_EConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule_Detail_EConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule_Detail_EConfig
(
	ID			NUMERIC(18,0) IDENTITY(1,1),
	PromoRuleID NUMERIC(18) NOT NULL,    -- 促销规则ID 
	Etypeid	VARCHAR(50)
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_EConfig') AND name = 'NCIX_PromoRule_Detail_EConfig_PromoRuleID')
--DROP INDEX NCIX_PromoRule_Detail_EConfig_PromoRuleID ON PromoRule_Detail_EConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_EConfig_PromoRuleID ON PromoRule_Detail_EConfig(PromoRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_EConfig') AND name = 'NCIX_PromoRule_Detail_EConfig_Etypeid')
--DROP INDEX NCIX_PromoRule_Detail_EConfig_Etypeid ON PromoRule_Detail_EConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_EConfig_Etypeid ON PromoRule_Detail_EConfig(Etypeid)

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromoRule_Detail_KConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule_Detail_KConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule_Detail_KConfig
(
	ID			NUMERIC(18,0) IDENTITY(1,1),
	PromoRuleID NUMERIC(18) NOT NULL,    -- 促销规则ID 
	Ktypeid varchar(50)   
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_KConfig') AND name = 'NCIX_PromoRule_Detail_KConfig_PromoRuleID')
--DROP INDEX NCIX_PromoRule_Detail_KConfig_PromoRuleID ON PromoRule_Detail_KConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_KConfig_PromoRuleID ON PromoRule_Detail_KConfig(PromoRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_KConfig') AND name = 'NCIX_PromoRule_Detail_KConfig_Ktypeid')
--DROP INDEX NCIX_PromoRule_Detail_KConfig_Ktypeid ON PromoRule_Detail_KConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_KConfig_Ktypeid ON PromoRule_Detail_KConfig(Ktypeid)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromoRule_Detail_PConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule_Detail_PConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule_Detail_PConfig
(
	ID			NUMERIC(18,0) IDENTITY(1,1),
	PromoRuleID NUMERIC(18) NOT NULL,    -- 促销规则ID 
	Ptypeid varchar(50)    -- 商品ID，可以选择父节点 
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_PConfig') AND name = 'NCIX_PromoRule_Detail_PConfig_PromoRuleID')
--DROP INDEX NCIX_PromoRule_Detail_PConfig_PromoRuleID ON PromoRule_Detail_PConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_PConfig_PromoRuleID ON PromoRule_Detail_PConfig(PromoRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_PConfig') AND name = 'NCIX_PromoRule_Detail_PConfig_Ptypeid')
--DROP INDEX NCIX_PromoRule_Detail_PConfig_Ptypeid ON PromoRule_Detail_PConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_PConfig_Ptypeid ON PromoRule_Detail_PConfig(Ptypeid)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromoRule_Detail_PromotConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule_Detail_PromotConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule_Detail_PromotConfig
(
	ID			NUMERIC(18,0) IDENTITY(1,1),
	PromoRuleID NUMERIC(18) NOT NULL,    -- 促销规则ID 
	PromoStylePtype		INT,    -- 促销模式之商品 促销模式 0=买满金额  1=买够商品 
	PromoStyleDiscount	INT,    -- 促销模式之折扣 促销模式的折扣  0=减免金额  1=送点券 2=送赠品 3=打折 4=特价 
	BuyTotal			NUMERIC(22,10),    -- 买满金额 
	BuyQty				NUMERIC(22,10),    -- 买满数量
	InDatesNum			INT,	   -- 接近效期至天数
	DisCount			NUMERIC(18,4),    -- 折扣 
	Ptypeid				VARCHAR(50),    -- 赠品的typeid 
	Qty					NUMERIC(22,10),			-- 赠送的数量
	OtherTotal			NUMERIC(22,10),    -- 可以代替：减免金额 卡券的对应金额特价金额价格 
	GiftTypeID			INT,    -- 赠送类型 
	CardTypeID			INT    -- 卡券类型 
)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule_Detail_PromotConfig]') and name = 'Qty' )
BEGIN
	ALTER TABLE dbo.PromoRule_Detail_PromotConfig ADD Qty NUMERIC(22,10)
		
END
GO

if exists (select * from syscolumns where id = object_id(N'[dbo].[PromoRule_Detail_PromotConfig]') and  name = 'Qty' AND length = 4)
BEGIN
     ALTER TABLE PromoRule_Detail_PromotConfig
	    ALTER COLUMN Qty NUMERIC(22,10) 
END
GO


if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule_Detail_PromotConfig]') and name = 'BindPtypeId' )
BEGIN
	ALTER TABLE dbo.PromoRule_Detail_PromotConfig ADD BindPtypeId VARCHAR(50)
		
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule_Detail_PromotConfig]') and name = 'InDatesNum' )
BEGIN
	ALTER TABLE dbo.PromoRule_Detail_PromotConfig ADD InDatesNum INT
		
END
GO



------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_PromotConfig') AND name = 'NCIX_PromoRule_Detail_PromotConfig_PromoRuleID')
--DROP INDEX NCIX_PromoRule_Detail_PromotConfig_PromoRuleID ON PromoRule_Detail_PromotConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_PromotConfig_PromoRuleID ON PromoRule_Detail_PromotConfig(PromoRuleID)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PromoRule_Detail_PromotConfig' AND a.Name='BuyTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PromoRule_Detail_PromotConfig 
	ALTER COLUMN BuyTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PromoRule_Detail_PromotConfig' AND a.Name='BuyQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PromoRule_Detail_PromotConfig 
	ALTER COLUMN BuyQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PromoRule_Detail_PromotConfig' AND a.Name='DisCount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PromoRule_Detail_PromotConfig 
	ALTER COLUMN DisCount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PromoRule_Detail_PromotConfig' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PromoRule_Detail_PromotConfig 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PromoRule_Detail_PromotConfig' AND a.Name='OtherTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PromoRule_Detail_PromotConfig 
	ALTER COLUMN OtherTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromoRule_Detail_StoresConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule_Detail_StoresConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule_Detail_StoresConfig
(
	ID			NUMERIC(18,0) IDENTITY(1,1),
	PromoRuleID NUMERIC(18) NOT NULL,    -- 促销规则ID 
	SotresID	VARCHAR(50)    -- 门店ID 
)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromoRule_Detail_VIPConfig]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule_Detail_VIPConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule_Detail_VIPConfig
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PromoRuleID NUMERIC(18) NOT NULL,    -- 促销规则ID 
	VipTypeID INT,    -- 会员卡类型ID 
	StartCardNum  VARCHAR(20),	--起始卡号
	EndCardNum	  VARCHAR(20),	--截止卡号
)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule_Detail_VIPConfig]') and name = 'StartCardNum' )
BEGIN
ALTER TABLE PromoRule_Detail_VIPConfig ADD StartCardNum VARCHAR(20)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PromoRule_Detail_VIPConfig]') and name = 'EndCardNum' )
BEGIN
ALTER TABLE PromoRule_Detail_VIPConfig ADD EndCardNum VARCHAR(20)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_VIPConfig') AND name = 'NCIX_PromoRule_Detail_VIPConfig_PromoRuleID')
--DROP INDEX NCIX_PromoRule_Detail_VIPConfig_PromoRuleID ON PromoRule_Detail_VIPConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_VIPConfig_PromoRuleID ON PromoRule_Detail_VIPConfig(PromoRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Detail_VIPConfig') AND name = 'NCIX_PromoRule_Detail_VIPConfig_VipTypeID')
--DROP INDEX NCIX_PromoRule_Detail_VIPConfig_VipTypeID ON PromoRule_Detail_VIPConfig 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Detail_VIPConfig_VipTypeID ON PromoRule_Detail_VIPConfig(VipTypeID)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromoRule_Stype]    脚本日期: 07/05/2013  */
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoRule_Stype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE PromoRule_Stype
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	PromoRuleID numeric(18) NOT NULL,    -- 促销规则ID 
	StypeID varchar(50)    -- 分支机构 
)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Stype') AND name = 'NCIX_PromoRule_Stype_PromoRuleID')
--DROP INDEX NCIX_PromoRule_Stype_PromoRuleID ON PromoRule_Stype 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Stype_PromoRuleID ON PromoRule_Stype(PromoRuleID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PromoRule_Stype') AND name = 'NCIX_PromoRule_Stype_StypeID')
--DROPs INDEX NCIX_PromoRule_Stype_StypeID ON PromoRule_Stype 
CREATE NONCLUSTERED INDEX NCIX_PromoRule_Stype_StypeID ON PromoRule_Stype(StypeID)

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PromotePrice]    脚本日期: 05/05/2010 14:48:54 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PromotePrice]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PromotePrice](
		[PromoteId] [int] IDENTITY(1,1) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[StartDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[PromotePrice] [numeric](18, 4) NULL,
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[WriteDate] [datetime] NULL,
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		UnitID  INT  NOT NULL DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'[dbo].[PromotePrice]') AND Name='UnitID')
BEGIN
	ALTER TABLE dbo.[PromotePrice]
	ADD UnitID  INT  NOT NULL DEFAULT(0)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PromotePrice' AND a.Name='PromotePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PromotePrice 
	ALTER COLUMN PromotePrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 


------------------------------------------升级表数据开始-----------------------------------------------
if exists(select top 1 1 from PromotePrice where isnull(UnitID,0)=0 )
begin
	update PromotePrice 
	set UnitID=p.baseunitid
	from PromotePrice n inner join ptype p on p.typeid=n.ptypeid
end
go

------------------------------------------升级表数据结束-----------------------------------------------



if NOT exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Province]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Province] (
		[id] [int] IDENTITY (1, 1) NOT NULL ,
		[areacode] [varchar] (20) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[areaname] [varchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[zaiyao] [text] COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[deleted] [bit] NOT NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM Province)
BEGIN
	SET IDENTITY_INSERT Province ON
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (1,'01','四川','hjh',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (2,'02','重庆','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (3,'03','广东','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (4,'04','广西','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (5,'05','海南','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (6,'06','福建','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (7,'07','湖北','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (9,'09','辽宁','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (10,'10','吉林','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (11,'11','黑龙江','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (12,'12','北京','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (13,'13','天津','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (14,'14','河北','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (15,'15','内蒙古','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (16,'16','山东','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (17,'17','江苏','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (18,'18','浙江','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (19,'19','上海','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (20,'20','安徽','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (21,'21','江西','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (22,'22','河南','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (23,'23','湖南','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (24,'24','云南','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (25,'25','贵州','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (26,'26','青海','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (27,'27','西藏','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (28,'28','新疆','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (29,'29','陕西','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (30,'30','甘肃','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (31,'31','宁夏','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (32,'32','山西','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (33,'33','香港','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (34,'34','澳门','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (35,'35','台湾','',0)
	insert into Province(id,areacode,areaname,zaiyao,deleted) values (36,'36','其它地区','',0)
	SET IDENTITY_INSERT Province OFF
END



/****** 对象:  Table [dbo].[ProxyInfo]    脚本日期: 05/05/2010 14:48:54 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ProxyInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ProxyInfo](
		[Id] [int] IDENTITY(1,1) NOT NULL,
		[CompName] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkAddr] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkPhone] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[Email] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMan] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[Note] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PT_Combin_SaleBackBill]    脚本日期: 05/05/2010 14:49:03 ******/
SET ANSI_NULLS ON 

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PT_Combin_SaleBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PT_Combin_SaleBackBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_DiscountPrice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsno] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_goodsno]  DEFAULT (0),
		[total] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_TaxTotal]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_IsUnit2]  DEFAULT (0),
		[OldID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_OldID]  DEFAULT (''),
		[CostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_CostPrice]  DEFAULT (0),
		[OldBillNumberID] [numeric](18, 0) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_OldBillNumberID]  DEFAULT (0),
		[InputCostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_1904BC7E]  DEFAULT (0),
		[SaleTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[FromBillID] [numeric](10, 0)  NULL,
		TaxMoney             numeric(24, 10)    NULL Default(0),
		NSalePrice           numeric(24, 10)      NULL Default(0),
		NSaleTotal           numeric(24, 10)      NULL Default(0),
		NDiscountPrice       numeric(24, 10)      NULL Default(0),
		NTotal               numeric(24, 10)      NULL Default(0),
		NTaxPrice            numeric(24, 10)      NULL Default(0),
		NTaxTotal            numeric(24, 10)      NULL Default(0),
		NTaxMoney            numeric(24, 10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(24, 10)     NULL Default(0),
		UnitRate             numeric(24, 10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(24, 10)     NULL Default(0),
		MUnitRate            numeric(24, 10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(24, 10)     NULL Default(0),
		MDiscountPrice       numeric(24, 10)     NULL Default(0),
		MTaxPrice            numeric(24, 10)     NULL Default(0),
		CurMSalePrice        numeric(24, 10)     NULL Default(0),
		CurMDiscountPrice    numeric(24, 10)     NULL Default(0),
		CurMTaxPrice         numeric(24, 10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(24, 10)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(24, 10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(24, 10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		ReferPrice NUMERIC(24,10) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无 
		,CompleteTotal NUMERIC(24, 10) DEFAULT(0)
		,NCompleteTotal NUMERIC(24, 10) DEFAULT(0)
		,pindexid VARCHAR(300) NULL DEFAULT('')--组合品单据表体关联ID
		,ShowOrder INT DEFAULT(0)
		,PriceSource VARCHAR(100)
		,CouponCode	VARCHAR(200) DEFAULT('')		--优惠券券编码，目前在兑换券的时候会使用
	) ON [PRIMARY] 


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_SaleBackBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE PT_Combin_SaleBackBill ADD PriceSource   VARCHAR(200)
END
GO

--优惠券券编码，目前在兑换券的时候会使用
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBackBill',N'U') AND Name='CouponCode')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBackBill
	ADD CouponCode VARCHAR(200) DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_SaleBackBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE PT_Combin_SaleBackBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO 
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBill') AND name = 'CIX_PT_Combin_SaleBackBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_PT_Combin_SaleBackBill_BillNumberID ON PT_Combin_SaleBackBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBill') AND name = 'NCIX_PT_Combin_SaleBackBill_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBill_Ptypeid ON PT_Combin_SaleBackBill(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBill') AND name = 'NCIX_PT_Combin_SaleBackBill_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBill_Ktypeid ON PT_Combin_SaleBackBill(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBill') AND name = 'NCIX_PT_Combin_SaleBackBill_SalePrice')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBill_SalePrice ON PT_Combin_SaleBackBill(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBill') AND name = 'NCIX_PT_Combin_SaleBackBill_Discount')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBill_Discount ON PT_Combin_SaleBackBill(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBill') AND name = 'NCIX_PT_Combin_SaleBackBill_Tax')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBill_Tax ON PT_Combin_SaleBackBill(Tax) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBill') AND name = 'NCIX_PT_Combin_SaleBackBill_pindexid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBill_pindexid ON PT_Combin_SaleBackBill(pindexid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
         
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PT_Combin_SaleBackBillDetail]    脚本日期: 05/05/2010 14:49:03 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PT_Combin_SaleBackBillDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PT_Combin_SaleBackBillDetail](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_SalePrice]  DEFAULT (0),
		[discount] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_DiscountPrice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsno] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_goodsno]  DEFAULT (0),
		[total] [numeric](24, 10) NOT NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_TaxTotal]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_IsUnit2]  DEFAULT (0),
		[Serial] VARCHAR(max) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_Serial]  DEFAULT (''),
		[OldID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_OldID]  DEFAULT (''),
		[CostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_CostPrice]  DEFAULT (0),
		[OldBillNumberID] [numeric](18, 0) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_OldBillNumberID]  DEFAULT (0),
		[InputCostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_1904BC7E]  DEFAULT (0),
		[SaleTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBackBillDetail_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[FromBillID] [numeric](10, 0)  NULL,
		TaxMoney             numeric(24, 10)    NULL Default(0),
		NSalePrice           numeric(24, 10)      NULL Default(0),
		NSaleTotal           numeric(24, 10)      NULL Default(0),
		NDiscountPrice       numeric(24, 10)      NULL Default(0),
		NTotal               numeric(24, 10)      NULL Default(0),
		NTaxPrice            numeric(24, 10)      NULL Default(0),
		NTaxTotal            numeric(24, 10)      NULL Default(0),
		NTaxMoney            numeric(24, 10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(24, 10)     NULL Default(0),
		UnitRate             numeric(24, 10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(24, 10)     NULL Default(0),
		MUnitRate            numeric(24, 10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(24, 10)     NULL Default(0),
		MDiscountPrice       numeric(24, 10)     NULL Default(0),
		MTaxPrice            numeric(24, 10)     NULL Default(0),
		CurMSalePrice        numeric(24, 10)     NULL Default(0),
		CurMDiscountPrice    numeric(24, 10)     NULL Default(0),
		CurMTaxPrice         numeric(24, 10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(24, 10)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(24, 10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(24, 10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		ReferPrice NUMERIC(24,10) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无 
		,CompleteTotal NUMERIC(24, 10) DEFAULT(0)
		,NCompleteTotal NUMERIC(24, 10) DEFAULT(0)
		,pindexid VARCHAR(300) NULL DEFAULT('')--组合品单据表体关联ID
		,combinationptypeid VARCHAR(200) NULL DEFAULT('')
		,ShowOrder INT DEFAULT(0)
		,InflowQty NUMERIC(24,10) DEFAULT(0),
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		PriceSource VARCHAR(200)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBackBillDetail',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBackBillDetail
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBackBillDetail',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBackBillDetail
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBackBillDetail',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBackBillDetail
	ADD InflowQty NUMERIC(24,10) DEFAULT(0)
END
GO

UPDATE dbo.PT_Combin_SaleBackBillDetail SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBackBillDetail',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBackBillDetail
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.PT_Combin_SaleBackBillDetail SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_SaleBackBillDetail' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE PT_Combin_SaleBackBillDetail ADD PriceSource   VARCHAR(200)
END
GO                                       
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBillDetail') AND name = 'CIX_PT_Combin_SaleBackBillDetail_BillNumberID')
CREATE CLUSTERED INDEX CIX_PT_Combin_SaleBackBillDetail_BillNumberID ON PT_Combin_SaleBackBillDetail(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBillDetail') AND name = 'NCIX_PT_Combin_SaleBackBillDetail_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBillDetail_Ptypeid ON PT_Combin_SaleBackBillDetail(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBillDetail') AND name = 'NCIX_PT_Combin_SaleBackBillDetail_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBillDetail_Ktypeid ON PT_Combin_SaleBackBillDetail(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBillDetail') AND name = 'NCIX_PT_Combin_SaleBackBillDetail_SalePrice')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBillDetail_SalePrice ON PT_Combin_SaleBackBillDetail(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBillDetail') AND name = 'NCIX_PT_Combin_SaleBackBillDetail_Discount')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBillDetail_Discount ON PT_Combin_SaleBackBillDetail(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBillDetail') AND name = 'NCIX_PT_Combin_SaleBackBillDetail_Tax')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBillDetail_Tax ON PT_Combin_SaleBackBillDetail(Tax) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBackBillDetail') AND name = 'NCIX_PT_Combin_SaleBackBillDetail_pindexid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBackBillDetail_pindexid ON PT_Combin_SaleBackBillDetail(pindexid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
         
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PT_Combin_SaleBill]    脚本日期: 05/05/2010 14:49:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PT_Combin_SaleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PT_Combin_SaleBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBill_jobnumber]  DEFAULT (''),
		[goodsno] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_goodsno]  DEFAULT (0),
		[total] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBill_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_PT_Combin_SaleBill_IsUnit2]  DEFAULT (0),
		[InputCostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBill_GoodsOrder]  DEFAULT ('-1'),
		[BackQty] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_BackQty]  DEFAULT (0),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBill_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](24, 10) NULL CONSTRAINT [DF__PT_Combin_SaleBill__Comple__18109845]  DEFAULT (0),
		[SaleTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ShareFee]	[numeric](24, 10) NOT NULL DEFAULT(0),
		TaxMoney             numeric(24, 10)    NULL Default(0),
		NSalePrice           numeric(24, 10)      NULL Default(0),
		NSaleTotal           numeric(24, 10)      NULL Default(0),
		NDiscountPrice       numeric(24, 10)      NULL Default(0),
		NTotal               numeric(24, 10)      NULL Default(0),
		NTaxPrice            numeric(24, 10)      NULL Default(0),
		NTaxTotal            numeric(24, 10)      NULL Default(0),
		NTaxMoney            numeric(24, 10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(24, 10)     NULL Default(0),
		UnitRate             numeric(24, 10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(24, 10)     NULL Default(0),
		MUnitRate            numeric(24, 10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(24, 10)     NULL Default(0),
		MDiscountPrice       numeric(24, 10)     NULL Default(0),
		MTaxPrice            numeric(24, 10)     NULL Default(0),
		CurMSalePrice        numeric(24, 10)     NULL Default(0),
		CurMDiscountPrice    numeric(24, 10)     NULL Default(0),
		CurMTaxPrice         numeric(24, 10)     NULL Default(0),
		CargoID              int                NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			 VARCHAR(200)		NULL DEFAULT('') ,
		InvoiceQty			 numeric(24, 10)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(24, 10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(24, 10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), --是否是赠品 价格促销
		BeforePromoID INT NOT NULL DEFAULT(0),
		ReferPrice NUMERIC(24, 10) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PriceSource   VARCHAR(200)
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,CompleteTotal NUMERIC(24, 10) DEFAULT(0) --已结算金额
		,NCompleteTotal NUMERIC(24, 10) DEFAULT(0)
		,LendBillID NUMERIC(10, 0) NOT NULL DEFAULT(0)
		,LendBillNumberID numeric(10, 0) NOT NULL DEFAULT(0)
		,ShowOrder INT DEFAULT(0)
		,DiyID INT DEFAULT(-1)
		,pindexid VARCHAR(300) NULL DEFAULT('')--组合品单据表体关联ID
		,PromonIds VARCHAR(1000) NOT NULL DEFAULT('')
		,CouponCode	VARCHAR(200) DEFAULT('')		--优惠券券编码，目前在兑换券的时候会使用
		,IsPromotion	INT DEFAULT(1)					--使用优惠券后，是否参与促销
		,IsVipPoint INT DEFAULT(1)					--使用优惠券后，是否参与会员积分
	) ON [PRIMARY] 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

-- 添加促销方案id字段，记录商品应用的所有促销方案
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBill',N'U') AND Name='PromonIds')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBill
	ADD PromonIds VARCHAR(1000) NOT NULL DEFAULT('')
END
GO

--优惠券券编码，目前在兑换券的时候会使用
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBill',N'U') AND Name='CouponCode')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBill
	ADD CouponCode VARCHAR(200) DEFAULT('')
END
GO

--使用优惠券后，是否参与促销
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBill',N'U') AND Name='IsPromotion')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBill
	ADD IsPromotion INT DEFAULT(1)
END
GO

--使用优惠券后，是否参与会员积分
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBill',N'U') AND Name='IsVipPoint')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBill
	ADD IsVipPoint INT DEFAULT(1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_SaleBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE PT_Combin_SaleBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO   
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBill') AND name = 'CIX_PT_Combin_SaleBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_PT_Combin_SaleBill_BillNumberID ON PT_Combin_SaleBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBill') AND name = 'NCIX_PT_Combin_SaleBill_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBill_Ptypeid ON PT_Combin_SaleBill(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBill') AND name = 'NCIX_PT_Combin_SaleBill_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBill_Ktypeid ON PT_Combin_SaleBill(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBill') AND name = 'NCIX_PT_Combin_SaleBill_Orderid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBill_Orderid ON PT_Combin_SaleBill(Orderid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBill') AND name = 'NCIX_PT_Combin_SaleBill_SalePrice')                              
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBill_SalePrice ON PT_Combin_SaleBill(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBill') AND name = 'NCIX_PT_Combin_SaleBill_Discount')          
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBill_Discount ON PT_Combin_SaleBill(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBill') AND name = 'NCIX_PT_Combin_SaleBill_Tax')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBill_Tax ON PT_Combin_SaleBill(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBill') AND name = 'NCIX_PT_Combin_SaleBill_Id')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBill_Id ON PT_Combin_SaleBill(Id) 
------------------------------------------创建索引区域结束-----------------------------------------------



/****** 对象:  Table [dbo].[PT_Combin_SaleBillDetail]    脚本日期: 05/05/2010 14:49:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PT_Combin_SaleBillDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PT_Combin_SaleBillDetail](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_SalePrice]  DEFAULT (0),
		[discount] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_jobnumber]  DEFAULT (''),
		[goodsno] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_goodsno]  DEFAULT (0),
		[total] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_IsUnit2]  DEFAULT (0),
		[Serial] VARCHAR(max) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_GoodsOrder]  DEFAULT ('-1'),
		[BackQty] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_BackQty]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](24, 10) NULL CONSTRAINT [DF__PT_Combin_SaleBillDetail__Comple__18109845]  DEFAULT (0),
		[SaleTotal] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](24, 10) NULL CONSTRAINT [DF_PT_Combin_SaleBillDetail_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ShareFee]	[numeric](24, 10) NOT NULL DEFAULT(0),
		TaxMoney             numeric(24, 10)    NULL Default(0),
		NSalePrice           numeric(24, 10)      NULL Default(0),
		NSaleTotal           numeric(24, 10)      NULL Default(0),
		NDiscountPrice       numeric(24, 10)      NULL Default(0),
		NTotal               numeric(24, 10)      NULL Default(0),
		NTaxPrice            numeric(24, 10)      NULL Default(0),
		NTaxTotal            numeric(24, 10)      NULL Default(0),
		NTaxMoney            numeric(24, 10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(24, 10)     NULL Default(0),
		UnitRate             numeric(24, 10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(24, 10)     NULL Default(0),
		MUnitRate            numeric(24, 10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(24, 10)     NULL Default(0),
		MDiscountPrice       numeric(24, 10)     NULL Default(0),
		MTaxPrice            numeric(24, 10)     NULL Default(0),
		CurMSalePrice        numeric(24, 10)     NULL Default(0),
		CurMDiscountPrice    numeric(24, 10)     NULL Default(0),
		CurMTaxPrice         numeric(24, 10)     NULL Default(0),
		CargoID              int                NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			 VARCHAR(200)		NULL DEFAULT('') ,
		InvoiceQty			 numeric(24, 10)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(24, 10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(24, 10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), --是否是赠品 价格促销
		BeforePromoID INT NOT NULL DEFAULT(0),
		ReferPrice NUMERIC(24, 10) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PriceSource   VARCHAR(200)
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,CompleteTotal NUMERIC(24, 10) DEFAULT(0) --已结算金额
		,NCompleteTotal NUMERIC(24, 10) DEFAULT(0)
		,LendBillID NUMERIC(10, 0) NOT NULL DEFAULT(0)
		,LendBillNumberID numeric(10, 0) NOT NULL DEFAULT(0)
		,ShowOrder INT DEFAULT(0)
		,DiyID INT DEFAULT(-1)
		,pindexid VARCHAR(300) NULL DEFAULT('')--组合品单据表体关联ID
		,combinationptypeid VARCHAR(200) NULL DEFAULT('')
		,SendedQty NUMERIC(24,10) DEFAULT(0) --发货数量，运输单过账回写
		,PickedQty NUMERIC(24,10) DEFAULT(0) --拣货数量
		,ClearQty NUMERIC(24,10)	--解锁数量
		,OutFactQty NUMERIC(24,10) DEFAULT(0),  --实物出库数量
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),	
		[PriceDetailId] INT  NULL DEFAULT(0),
		[PriceRuleId] INT  NULL DEFAULT(0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

--高级价格明细id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_SaleBillDetail' AND a.Name='PriceDetailId'
)
BEGIN
	ALTER TABLE PT_Combin_SaleBillDetail ADD PriceDetailId INT  NULL DEFAULT(0)
END
go

--高级价格id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_SaleBillDetail' AND a.Name='PriceRuleId'
)
BEGIN
	ALTER TABLE PT_Combin_SaleBillDetail ADD PriceRuleId INT  NULL DEFAULT(0)
END
go

update PT_Combin_SaleBillDetail set PriceDetailId = 0 ,PriceRuleId = 0
where PriceDetailId is null
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBillDetail',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBillDetail
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBillDetail',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBillDetail
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBillDetail',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.PT_Combin_SaleBillDetail
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.PT_Combin_SaleBillDetail SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBillDetail',N'U') AND Name='SendedQty')
BEGIN
	ALTER TABLE PT_Combin_SaleBillDetail
	ADD SendedQty NUMERIC(24,10) DEFAULT(0)
END
GO
UPDATE dbo.PT_Combin_SaleBillDetail SET SendedQty=0 WHERE SendedQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PT_Combin_SaleBillDetail' AND a.Name='ClearQty'
)
BEGIN
		ALTER TABLE PT_Combin_SaleBillDetail ADD ClearQty   numeric(22,10)   NULL Default(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PT_Combin_SaleBillDetail',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE PT_Combin_SaleBillDetail
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE PT_Combin_SaleBillDetail SET PickedQty=0 WHERE PickedQty IS NULL
GO                                     

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBillDetail') AND name = 'CIX_PT_Combin_SaleBillDetail_BillNumberID')
CREATE CLUSTERED INDEX CIX_PT_Combin_SaleBillDetail_BillNumberID ON PT_Combin_SaleBillDetail(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBillDetail') AND name = 'NCIX_PT_Combin_SaleBillDetail_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBillDetail_Ptypeid ON PT_Combin_SaleBillDetail(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBillDetail') AND name = 'NCIX_PT_Combin_SaleBillDetail_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBillDetail_Ktypeid ON PT_Combin_SaleBillDetail(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBillDetail') AND name = 'NCIX_PT_Combin_SaleBillDetail_Orderid')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBillDetail_Orderid ON PT_Combin_SaleBillDetail(Orderid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBillDetail') AND name = 'NCIX_PT_Combin_SaleBillDetail_SalePrice')                              
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBillDetail_SalePrice ON PT_Combin_SaleBillDetail(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBillDetail') AND name = 'NCIX_PT_Combin_SaleBillDetail_Discount')          
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBillDetail_Discount ON PT_Combin_SaleBillDetail(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBillDetail') AND name = 'NCIX_PT_Combin_SaleBillDetail_Tax')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBillDetail_Tax ON PT_Combin_SaleBillDetail(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PT_Combin_SaleBillDetail') AND name = 'NCIX_PT_Combin_SaleBillDetail_Id')
CREATE NONCLUSTERED INDEX NCIX_PT_Combin_SaleBillDetail_Id ON PT_Combin_SaleBillDetail(Id) 
------------------------------------------创建索引区域结束-----------------------------------------------



/****** 对象:  Table [dbo].[ptype]    脚本日期: 05/05/2010 14:48:55 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ptype]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ptype](
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ParId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint] NOT NULL,
		[sonnum] [int] NOT NULL,
		[soncount] [int] NOT NULL,
		[CanModify] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[UserCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[FullName] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Name] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Standard] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Type] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Area] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Unit1] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
		[Unit2] [varchar](8) COLLATE Chinese_PRC_CI_AS NULL,
		[UnitRate1] [numeric](18, 4) NULL CONSTRAINT [DF_ptype_UnitRate1]  DEFAULT (1),
		[UnitRate2] [numeric](18, 4) NULL CONSTRAINT [DF_ptype_UnitRate2]  DEFAULT (1),
		[preprice1] [numeric](18, 4) NULL CONSTRAINT [DF_ptype_preprice1]  DEFAULT (0),
		[preprice2] [numeric](18, 4) NULL CONSTRAINT [DF_ptype_preprice2]  DEFAULT (0),
		[preprice3] [numeric](18, 4) NULL CONSTRAINT [DF_ptype_preprice3]  DEFAULT (0),
		[preprice4] [numeric](18, 4) NULL CONSTRAINT [DF_ptype_preprice4]  DEFAULT (0),
		[preprice5] [numeric](18, 4) NULL CONSTRAINT [DF_ptype_preprice5]  DEFAULT (0),
		[UsefulLifeMonth] [smallint] NULL,
		[UsefulLifeDay] [smallint] NULL,
		[Comment] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL,
		[recPrice] [numeric](22, 10) NULL CONSTRAINT [DF_ptype_recPrice]  DEFAULT (0),
		[deleted] [bit] NOT NULL CONSTRAINT [DF_ptype_deleted]  DEFAULT (0),
		[ColorGroupID] [int] NULL,
		[SizeGroupID] [int] NULL,
		[EntryCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[IfSerial] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_ptype_IfSerial]  DEFAULT ('0'),
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[SerialCount] [int] NULL DEFAULT ('0'),
		[ValidDays] [int] NULL CONSTRAINT [DF_ptype_ValidDays]  DEFAULT (0),
		[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0),
		[DwgNo] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[ImgURL] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[IsDownLoad] [bit] DEFAULT(0),
		PosDataVersion TIMESTAMP,
		[CreateDate] DATETIME DEFAULT '',
		[IsService] INT NOT NULL DEFAULT(0), -- 0 普通商品 1 服务商品
		[SortID] INT NOT NULL DEFAULT(0),--排序字段
		[OmUse] BIT DEFAULT(0),
		[OmPrice][numeric](18, 4) NULL DEFAULT(0),
		[BuyDefaultRate] [numeric](24, 10) ,	--采购默认税率值	9.6新增
		[SaleDefaultRate] [numeric](24, 10),	--销售默认税率值	9.6新增
		PtypeCategoryID VARCHAR(50) DEFAULT(''),	--商品类别
		BrandarTypeID VARCHAR(50) NOT NULL DEFAULT('00001'),--商品品牌 默认值【其他品牌】
		[weight]   numeric(24, 10),
		volume numeric(24, 10) ,
		InventoryTypeID INT,
		othercomment1					VARCHAR(250) NULL DEFAULT(''),	--备注1
		othercomment2					VARCHAR(250) NULL DEFAULT(''),	--备注2
		othercomment3					VARCHAR(250) NULL DEFAULT(''),	--备注3
		othercomment4					VARCHAR(250) NULL DEFAULT(''),	--备注4
		othercomment5					VARCHAR(250) NULL DEFAULT('')	--备注5
	) ON [PRIMARY]

	-- ********	处理 PType	********
	DELETE FROM PType
	INSERT INTO PType(TypeID,Parid,Leveal,SonNum,SonCount,CanModify,UserCode,FullName,Name,Standard,Type,Area,Unit1,Unit2,UnitRate1,UnitRate2,preprice1,preprice2,preprice3,preprice4,UsefulLifeMonth,UsefulLifeDay,Comment,recPrice,Deleted,ColorGroupID,SizeGroupID,EntryCode,IfSerial)VALUES('00000','root',0,0,0,'0','0','库存商品','','','','','','',0,0,0,0,0,0,null,null,'',0,0,0,0,'',0)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType',N'U') AND Name='ShowOrder')
BEGIN
	DECLARE @SQL VARCHAR(MAX)=''
	SELECT @SQL='alter table ['+b.name+'] drop constraint ['+d.name+']'
	FROM syscolumns a
	JOIN sysobjects b ON a.id=b.id AND a.name='ShowOrder' AND b.name='PType'
	JOIN syscomments c ON a.cdefault=c.id
	JOIN sysobjects d ON c.id=d.id
	IF @SQL<>''
	BEGIN
		EXEC(@SQL) 
	END
	
	ALTER TABLE dbo.ptype
	DROP COLUMN ShowOrder
END
GO
--提供XiWa交互功能，每次修改或者新增基本信息后，必须在原来的值上加1 谢吉康 2010-05-04
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'XiWaMaxNumber' )
	BEGIN
		BEGIN TRANSACTION
		SET QUOTED_IDENTIFIER ON
		SET ARITHABORT ON
		SET NUMERIC_ROUNDABORT OFF
		SET CONCAT_NULL_YIELDS_NULL ON
		SET ANSI_NULLS ON
		SET ANSI_PADDING ON
		SET ANSI_WARNINGS ON
		COMMIT
		BEGIN TRANSACTION
		ALTER TABLE dbo.PType ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
		
		COMMIT
	END
GO
UPDATE PType SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL OR XiWaMaxNumber = 0
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'DwgNo' )
BEGIN
	ALTER TABLE dbo.PType ADD
		DwgNo varchar(100) COLLATE Chinese_PRC_CI_AS NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'ImgURL' )
BEGIN
	ALTER TABLE dbo.PType ADD
		ImgURL varchar(200) COLLATE Chinese_PRC_CI_AS NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'Integral' )
BEGIN
	ALTER TABLE dbo.PType ADD
		Integral numeric(18, 4) NULL DEFAULT(0)
END
GO

--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='WdSyncFlag')
BEGIN
	ALTER TABLE ptype ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End 

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and  name = 'UserCode' and length=26)
BEGIN
     ALTER TABLE PType
	    ALTER COLUMN UserCode varchar(200) NULL
END
GO

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and  name = 'FullName' and length=66)
BEGIN
     ALTER TABLE PType
	    ALTER COLUMN FullName varchar(200) NOT NULL
END
GO

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and  name = 'Name' and length=30)
BEGIN
     ALTER TABLE PType
	    ALTER COLUMN [Name] varchar(200) NULL
END
GO

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and  name = 'Standard' and length=40)
BEGIN
     ALTER TABLE PType
	    ALTER COLUMN Standard varchar(200) NULL
END
GO

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and  name = 'Type' and length=20)
BEGIN
     ALTER TABLE PType
	    ALTER COLUMN Type varchar(200) NULL
END
GO

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and  name = 'Area' and length=30)
BEGIN
     ALTER TABLE PType
	    ALTER COLUMN Area varchar(200) NULL
END
GO

if  exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and  name = 'EntryCode' and length=50)
BEGIN
     ALTER TABLE PType
	    ALTER COLUMN EntryCode varchar(200) NULL
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'StopBuy' )
BEGIN
	ALTER TABLE dbo.PType ADD
		StopBuy INT NULL
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'IsOm' )
BEGIN
	ALTER TABLE dbo.PType ADD
		IsOm INT NULL DEFAULT 0
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'customitemid' )
BEGIN
	alter table ptype add customitemid varchar(20)


END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'customitemfrom' )
BEGIN
alter table ptype add customitemfrom varchar(20)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'customitemname' )
BEGIN
alter table ptype add customitemname varchar(max)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'customitemrefid' )
BEGIN
alter table ptype add customitemrefid varchar(max)
END
GO

------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'UnitsType' )
BEGIN
alter table ptype add UnitsType INT 
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'AssistantUnitId' )
BEGIN
alter table ptype add AssistantUnitId INT  DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'SaleUnitId' )
BEGIN
alter table ptype add SaleUnitId INT DEFAULT(0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'BuyUnitId' )
BEGIN
alter table ptype add BuyUnitId INT DEFAULT(0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'ProduceUnitId' )
BEGIN
alter table ptype add ProduceUnitId INT DEFAULT(0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'StockUnitId' )
BEGIN
alter table ptype add StockUnitId INT DEFAULT(0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'JobUnitId' )
BEGIN
alter table ptype add JobUnitId INT DEFAULT(0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'baseUnitId' )
BEGIN
alter table ptype add baseUnitId INT DEFAULT(0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'IfUseEntryCode' )
BEGIN
alter table ptype add IfUseEntryCode bit DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'IfUseGoodsNum' )
BEGIN
ALTER TABLE ptype ADD IfUseGoodsNum bit DEFAULT(0)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'IsDownLoad' )
BEGIN
ALTER TABLE ptype ADD IsDownLoad BIT NULL DEFAULT(0)
END

if not exists (select * from sys.default_constraints where name='DF_ptype_recPrice' and parent_object_id=object_id('ptype'))
	ALTER TABLE [dbo].[ptype] ADD  CONSTRAINT [DF_ptype_recPrice]  DEFAULT ((0)) FOR [recPrice]
	
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'PId' )
BEGIN
ALTER TABLE ptype ADD Pid int identity(1,1)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.PType ADD  PosDataVersion timestamp
END
GO

IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='MultEntryCode')
BEGIN
	ALTER TABLE ptype ADD MultEntryCode NVARCHAR(MAX) NOT NULL DEFAULT(''); 
End 

if exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'recPrice' )
BEGIN
	IF EXISTS (select * from sys.default_constraints where name='DF_ptype_recPrice' and parent_object_id=object_id('ptype'))
		ALTER TABLE [ptype] DROP CONSTRAINT DF_ptype_recPrice;
	IF EXISTS(SELECT * FROM sys.views WHERE name='test_data')
		DROP VIEW test_data;
	ALTER TABLE dbo.PType ALTER COLUMN recPrice [numeric](22, 10) NULL;
	ALTER TABLE ptype ADD CONSTRAINT DF_ptype_recPrice DEFAULT(0) FOR [recPrice];
END
GO

--增加“创建时间”
IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[PType]') AND name = 'CreateDate')
BEGIN
	ALTER TABLE dbo.ptype ADD CreateDate DATETIME DEFAULT ''
END
GO
IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[PType]') AND name = 'IsService')
BEGIN
	ALTER TABLE ptype ADD [IsService] INT NOT NULL DEFAULT(0) -- 0 普通商品 1 服务商品
END

GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType]') and name = 'isyapi' )
BEGIN
	ALTER TABLE dbo.PType ADD isyapi BIT DEFAULT(0)
END

IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[PType]') AND name = 'SortID')
BEGIN
	ALTER TABLE ptype ADD [SortID] INT NOT NULL  DEFAULT 0 WITH VALUES  --排序字段,赋初始值为0
END
GO

IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='OmUse'  )
BEGIN
	alter table ptype add  OmUse bit DEFAULT(0) ;
End
GO

IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='OmPrice'  )
BEGIN
	alter table ptype add  OmPrice numeric(18, 4) DEFAULT(0);
End
GO

IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='BuyDefaultRate')
BEGIN
	alter table ptype add  BuyDefaultRate INT;  --采购默认税率值	9.6新增
End
GO

IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='SaleDefaultRate')
BEGIN
	alter table ptype add  SaleDefaultRate INT; --销售默认税率值	9.6新增
End
GO

IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='PtypeCategoryID'  )
BEGIN
	alter table ptype add  PtypeCategoryID VARCHAR(50) DEFAULT('');
End
GO 

--调整字段名称
IF EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'ptype',N'U') AND Name='PtypeBrandarID')
BEGIN
	DECLARE @t TABLE(name VARCHAR(100)); 
	INSERT INTO @t SELECT 'PtypeBrandarID'
	DECLARE @sql NVARCHAR(max)='';
	DECLARE @tn NVARCHAR(500)='ptype';

	SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
		+ ' alter table '+@tn+' drop column '+d.name+';'
	FROM sys.default_constraints a 
		RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
		JOIN @t d ON b.name=d.name
		WHERE b.object_id=object_id(@tn,'U')

	IF @sql<>''
		EXEC(@sql);
END		
GO

IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='BrandarTypeID'  )
BEGIN
	alter table ptype add  BrandarTypeID VARCHAR(50) NOT NULL DEFAULT('00001'); --默认值【其他品牌】
End
GO

--存货类型 InventoryTypeID
IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='InventoryTypeID'  )
BEGIN
	alter table ptype add  InventoryTypeID VARCHAR(50) DEFAULT('');
End
GO

--重量
IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='weight'  )
BEGIN
	alter table ptype add  [weight]   numeric(24, 10) DEFAULT 0;
End
GO

--体积	
IF Not EXISTS (select * from syscolumns where id=object_id('ptype') and name='volume'  )
BEGIN
	alter table ptype add  volume numeric(24, 10) DEFAULT 0;
End


IF EXISTS(SELECT TOP 1 1 FROM dbo.ptype WHERE [PtypeCategoryID] IS NULL)
BEGIN
	UPDATE A  SET A.[PtypeCategoryID]='' FROM dbo.ptype A WHERE A.[PtypeCategoryID] IS NULL
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.ptype WHERE weight IS NULL)
BEGIN
	UPDATE A  SET A.weight=0 FROM dbo.ptype A WHERE A.weight IS NULL
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.ptype WHERE volume IS NULL)
BEGIN
	UPDATE A  SET A.volume=0 FROM dbo.ptype A WHERE A.volume IS NULL
END
GO


--去掉分支机构间最近进价
IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID('PType') AND Name='RecAmgSTypeBuyPrice')
BEGIN
	DECLARE @SQL VARCHAR(MAX)=''
	SELECT @SQL='alter table ['+b.name+'] drop constraint ['+d.name+']'
	FROM syscolumns a
	JOIN sysobjects b ON a.id=b.id AND a.name='RecAmgSTypeBuyPrice' AND b.name='PType'
	JOIN syscomments c ON a.cdefault=c.id
	JOIN sysobjects d ON c.id=d.id
	IF @SQL<>''
	BEGIN
		EXEC(@SQL) 
	END
	ALTER TABLE dbo.ptype
	DROP COLUMN RecAmgSTypeBuyPrice
END
GO
--去掉分支机构间最近售价
IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID('PType') AND Name='RecAmgSTypeSalePrice')
BEGIN
	DECLARE @SQL VARCHAR(MAX)=''
	SELECT @SQL='alter table ['+b.name+'] drop constraint ['+d.name+']'
	FROM syscolumns a
	JOIN sysobjects b ON a.id=b.id AND a.name='RecAmgSTypeSalePrice' AND b.name='PType'
	JOIN syscomments c ON a.cdefault=c.id
	JOIN sysobjects d ON c.id=d.id
	IF @SQL<>''
	BEGIN
		EXEC(@SQL) 
	END
	ALTER TABLE dbo.ptype
	DROP COLUMN RecAmgSTypeSalePrice
END
GO

IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID('PType') AND Name='RecSalePrice')
BEGIN
	DECLARE @SQL VARCHAR(MAX)=''
	SELECT @SQL='alter table ['+b.name+'] drop constraint ['+d.name+']'
	FROM syscolumns a
	JOIN sysobjects b ON a.id=b.id AND a.name='RecSalePrice' AND b.name='PType'
	JOIN syscomments c ON a.cdefault=c.id
	JOIN sysobjects d ON c.id=d.id
	IF @SQL<>''
	BEGIN
		EXEC(@SQL) 
	END
	ALTER TABLE dbo.PType
	DROP COLUMN RecSalePrice
END
GO


--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='WdSyncFlag')
BEGIN
	ALTER TABLE ptype ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End       

--处理旧数据

update ptype set OmUse=0, OmPrice=0 where omuse is null or IsOm is null or OmPrice is Null
go

--是否网店下载数据
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='IsWdDownLoad')
BEGIN
	ALTER TABLE ptype ADD  IsWdDownLoad BIT NOT NULL DEFAULT 0; 
End  
GO

--增加备注1-5
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='othercomment1')
BEGIN
	ALTER TABLE ptype 
	ADD	 othercomment1 VARCHAR(250) NULL DEFAULT('')
END
GO
UPDATE ptype SET othercomment1 = '' WHERE othercomment1 IS NULL
GO
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='othercomment2')
BEGIN
	ALTER TABLE ptype 
	ADD	 othercomment2 VARCHAR(250) NULL DEFAULT('')
END
GO
UPDATE ptype SET othercomment2 = '' WHERE othercomment2 IS NULL
GO

IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='othercomment3')
BEGIN
	ALTER TABLE ptype 
	ADD	 othercomment3 VARCHAR(250) NULL DEFAULT('')
END
GO
UPDATE ptype SET othercomment3 = '' WHERE othercomment3 IS NULL
GO

IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='othercomment4')
BEGIN
	ALTER TABLE ptype 
	ADD	 othercomment4 VARCHAR(250) NULL DEFAULT('')
END
GO
UPDATE ptype SET othercomment4 = '' WHERE othercomment4 IS NULL
GO

IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='othercomment5')
BEGIN
	ALTER TABLE ptype 
	ADD	 othercomment5 VARCHAR(250) NULL DEFAULT('')
END
GO
UPDATE ptype SET othercomment5 = '' WHERE othercomment5 IS NULL

GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ptype]') AND name = N'ptype_index')
	DROP INDEX [dbo].[ptype].[ptype_index]

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ptype]') AND name = N'NCIX_ptype_SONNUM')
	DROP INDEX [NCIX_ptype_SONNUM] ON [dbo].[ptype]

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Ptype]') AND name = N'NCIX_PARID')
	DROP INDEX [dbo].Ptype.NCIX_PARID	

GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE') AND name = 'CIX_PTYPE_Typeid')
--DROP INDEX CIX_PTYPE_Typeid ON PTYPE 
CREATE CLUSTERED INDEX CIX_PTYPE_Typeid ON PTYPE(Typeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE') AND name = 'NCIX_PTYPE_Parid_deleted')
--DROP INDEX NCIX_PTYPE_Parid_deleted ON PTYPE 
CREATE NONCLUSTERED INDEX NCIX_PTYPE_Parid_deleted ON PTYPE(Parid,deleted) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE') AND name = 'NCIX_PTYPE_Sonnum_deleted')
--DROP INDEX NCIX_PTYPE_Sonnum_deleted ON PTYPE 
CREATE NONCLUSTERED INDEX NCIX_PTYPE_Sonnum_deleted ON PTYPE(Sonnum,deleted) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE') AND name = 'CIX_PTYPE_UserCode')
--DROP INDEX CIX_PTYPE_Typeid ON PTYPE 
CREATE NONCLUSTERED INDEX CIX_PTYPE_UserCode ON PTYPE(UserCode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE') AND name = 'CIX_PTYPE_FullName')
--DROP INDEX CIX_PTYPE_Typeid ON PTYPE 
CREATE NONCLUSTERED INDEX CIX_PTYPE_FullName ON PTYPE(FullName) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE PType SET StopBuy = 0 WHERE StopBuy IS NULL
UPDATE PType SET IfUseEntryCode = 0 WHERE IfUseEntryCode IS NULL
GO
UPDATE PType SET IsDownLoad=0 WHERE IsDownLoad IS NULL
UPDATE PType SET isyapi = 0 WHERE isyapi IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='UnitRate1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN UnitRate1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='UnitRate2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN UnitRate2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='preprice1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN preprice1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='preprice2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN preprice2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='preprice3' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN preprice3 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='preprice4' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN preprice4 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='preprice5' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN preprice5 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='recPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN recPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='OmPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN OmPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='Integral' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN Integral NUMERIC(24,10)
    END
 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='BuyDefaultRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN BuyDefaultRate NUMERIC(24,10)
    END

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ptype' AND a.Name='SaleDefaultRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ptype 
	ALTER COLUMN SaleDefaultRate NUMERIC(24,10)
    END
         
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='iscombinationproduct')
BEGIN
	ALTER TABLE ptype ADD  iscombinationproduct INT NOT NULL DEFAULT 0;  
End    
GO
UPDATE ptype SET iscombinationproduct = 0 WHERE iscombinationproduct IS NULL
GO   

--是否启用计量
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='IsScaleWeight')
BEGIN
	ALTER TABLE ptype ADD  IsScaleWeight BIT NOT NULL DEFAULT 0;  
End   
GO
UPDATE ptype SET IsScaleWeight = 0 WHERE IsScaleWeight IS NULL
GO 

--计量方式
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='ScaleWeightType')
BEGIN
	ALTER TABLE ptype ADD  ScaleWeightType INT NOT NULL DEFAULT 0; 
End 
GO
UPDATE ptype SET ScaleWeightType = 0 WHERE ScaleWeightType IS NULL
GO   

                    
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO
UPDATE A  SET A.[PtypeCategoryID]='' FROM dbo.ptype A WHERE A.[PtypeCategoryID] IS NULL
GO

--WMS下载
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='IsWmsDownLoad')
BEGIN
	ALTER TABLE ptype 
		ADD IsWmsDownLoad INT NOT NULL DEFAULT 0 
End 
GO
UPDATE ptype SET IsWmsDownLoad = 0 WHERE IsWmsDownLoad IS NULL
GO

--是否同步
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='IsWmsSync')
BEGIN
	ALTER TABLE ptype 
		ADD IsWmsSync INT NOT NULL DEFAULT 0 
End 
GO
UPDATE ptype SET IsWmsSync = 0 WHERE IsWmsSync IS NULL
GO

--易聚客开票品名
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('ptype') and name='yjkptype')
BEGIN
	ALTER TABLE ptype 
		ADD yjkptype VARCHAR(200) NULL DEFAULT('')
End 
GO
UPDATE ptype SET yjkptype = '' WHERE yjkptype IS NULL
GO



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ptype_8w]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[ptype_8w] (
		[typeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[ParId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[leveal] [smallint] NOT NULL ,
		[sonnum] [int] NOT NULL ,
		[soncount] [int] NOT NULL ,
		[CanModify] [char] (1) COLLATE Chinese_PRC_CI_AS NULL ,
		[UserCode] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Name] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[Standard] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[Type] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[Area] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[Unit1] [varchar] (8) COLLATE Chinese_PRC_CI_AS NULL ,
		[Unit2] [varchar] (8) COLLATE Chinese_PRC_CI_AS NULL ,
		[UnitRate1] [decimal](18, 4) NULL ,
		[UnitRate2] [decimal](18, 4) NULL ,
		[preprice1] [decimal](18, 4) NULL ,
		[preprice2] [decimal](18, 4) NULL ,
		[preprice3] [decimal](18, 4) NULL ,
		[preprice4] [decimal](18, 4) NULL ,
		[preprice5] [decimal](18, 4) NULL ,
		[UsefulLifeMonth] [smallint] NULL ,
		[UsefulLifeDay] [smallint] NULL ,
		[Comment] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL ,
		[recPrice] [money] NULL ,
		[deleted] [bit] NOT NULL ,
		[ColorGroupID] [int] NULL ,
		[SizeGroupID] [int] NULL ,
		[EntryCode] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[IfSerial] [char] (1) COLLATE Chinese_PRC_CI_AS NULL ,
		[PyCode] [varchar] (500) COLLATE Chinese_PRC_CI_AS NULL ,
		[SerialCount] [int] NULL ,
		[ValidDays] [int] NULL ,
		[XiWaMaxNumber] [decimal](18, 0) NULL ,
		[DwgNo] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[ImgURL] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[Integral] [decimal](18, 4) NULL 
	) ON [PRIMARY]
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  商品自定义字段
  张陈仁
  3023-04-10
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ptype_CustomColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table Ptype_CustomColumns 
	(
	   ID                   bigint               identity(1,1),
	   typeid               varchar(100)         null,
	   Costom1              VARCHAR(600)         null,
	   Costom2              VARCHAR(600)         null,
	   Costom3              VARCHAR(600)         null,
	   Costom4              VARCHAR(600)         null,
	   Costom5              VARCHAR(600)         null,
	   Costom6              VARCHAR(600)         null,
	   Costom7              VARCHAR(600)         null,
	   Costom8              VARCHAR(600)         null,
	   Costom9              VARCHAR(600)         null,
	   Costom10             VARCHAR(600)         null,
	   Costom11             VARCHAR(600)         null,
	   Costom12             VARCHAR(600)         null,
	   Costom13             VARCHAR(600)         null,
	   Costom14             VARCHAR(600)         null,
	   Costom15             VARCHAR(600)         null,
	   Costom16             VARCHAR(600)         null,
	   Costom17             VARCHAR(600)         null,
	   Costom18             VARCHAR(600)         null,
	   Costom19             VARCHAR(600)         null,
	   Costom20             VARCHAR(600)         null
   )
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'PType_EntryCode') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PType_EntryCode]
(
	Ptypeid					VARCHAR(50) NOT NULL DEFAULT(''),--商品ID
	EntryCode				VARCHAR(200) NOT NULL,			 --	条码
	UnitsId					INT NOT NULL DEFAULT(-1),		 --区别商品和多单位的默认条码 、区别每个多单位的默认条码,如果为商品条码 则 单位为-1
	IsDefaultEntryCode		BIT NOT NULL DEFAULT(0),		 --是否为默认条码
	SortId					INT NOT NULL					 --排序			
) 
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE_EntryCode') AND name = 'CIX_PTYPE_EntryCode_Ptypeid')
--DROP INDEX CIX_PTYPE_EntryCode_Ptypeid ON PTYPE_EntryCode 
CREATE CLUSTERED INDEX CIX_PTYPE_EntryCode_Ptypeid ON PTYPE_EntryCode(Ptypeid
------------------------------------------创建索引区域结束-----------------------------------------------
) 

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'PType_EntryCode_Ext') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PType_EntryCode_Ext]
(
	Nid						INT IDENTITY(1,1) NOT NULL,					 --排序		
	Ptypeid					VARCHAR(50) NOT NULL DEFAULT(''),--商品ID
	EntryCode				VARCHAR(200) NOT NULL,			 --	条码
	IsDefaultEntryCode		BIT  DEFAULT(0),		 --是否为默认条码		
) 
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------表修改区域开始-----------------------------------
IF  EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='PType_EntryCode_Ext' AND a.Name='SortId')
BEGIN
	EXEC sp_rename  @objname= 'PType_EntryCode_Ext.SortId' ,  @newname ='Nid'
END
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PType_EntryCode_Ext') AND name = 'NCIX_Ptypeid_EntryCode_search')
BEGIN 
	CREATE NONCLUSTERED INDEX NCIX_Ptypeid_EntryCode_search ON PType_EntryCode_Ext(Ptypeid,EntryCode) 
END 
GO
------------------------------------------表修改区域结束-----------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ptype_l]    脚本日期: 05/05/2010 14:48:56 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ptype_l]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ptype_l](
		[etypeid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[typeid] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[flag] [char](1) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

-- Add by 李海洋 
-- Date: 2012-03-30
-- Description: 增加: 修改, 分类, 停用, 删除 细分权限
------------------------------------------表修改区域开始-------------------------------------------------
-- 修改权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[ptype_l]') 
		AND name = 'modifyflag'
)
BEGIN
		ALTER TABLE dbo.ptype_l DROP COLUMN modifyflag;
END
GO

-- 分类权限	
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[ptype_l]') 
		AND name = 'assortflag'
)
BEGIN
  ALTER TABLE dbo.ptype_l DROP COLUMN assortflag ;
END
GO

-- 停用权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[ptype_l]') 
		AND name = 'disableflag'
)
BEGIN
  ALTER TABLE dbo.ptype_l DROP COLUMN disableflag;
END
GO

-- 删除权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = object_id(N'[dbo].[ptype_l]') 
		AND name = 'delflag'
)
BEGIN
		ALTER TABLE dbo.ptype_l DROP COLUMN delflag;
END  
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ptype_l]') AND name = N'IX_ptype_l')
BEGIN
	DROP INDEX IX_ptype_l ON ptype_l
END
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE_L') AND name = 'CIX_PTYPE_L_etypeid')
--DROP INDEX CIX_PTYPE_L_etypeid ON PTYPE_L 
CREATE CLUSTERED INDEX CIX_PTYPE_L_etypeid ON PTYPE_L(etypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------更新新加列结束-------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PType_Price]    脚本日期: 05/05/2010 14:46:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PType_Picture]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[PType_Picture] (
	[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[Name]	[varchar](50) NOT NULL,
	[OrderID] [numeric](10, 0) IDENTITY(1,1) NOT NULL ,	
	[ImgURL] [VARCHAR](200) NOT NULL,
	[pic] [image] NULL,
	[length] [int] NULL,
	[filename] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
	[type] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,	
) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Picture' AND a.Name='pic'
)
BEGIN
	ALTER TABLE PType_Picture ADD pic image NULL	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Picture' AND a.Name='length'
)
BEGIN
	ALTER TABLE PType_Picture ADD length INT NULL	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Picture' AND a.Name='filename'
)
BEGIN
	ALTER TABLE PType_Picture ADD filename VARCHAR(200) NULL	
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Picture' AND a.Name='type'
)
BEGIN
	ALTER TABLE PType_Picture ADD type VARCHAR(50) NULL	
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PType_Price]    脚本日期: 05/05/2010 14:46:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PType_Price]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[PType_Price] (
	[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL Default(0),
	[PreBuyPrice1] [numeric](22, 10) NULL default(0),
	[PreBuyPrice2] [numeric](18, 4) NULL default(0),
	[PreBuyPrice3] [numeric](18, 4) NULL default(0),
	[PreBuyPrice4] [numeric](18, 4) NULL default(0),
	[PreBuyPrice5] [numeric](18, 4) NULL default(0),
	[PreSalePrice1] [numeric](18, 4) NULL default(0),
	[PreSalePrice2] [numeric](18, 4) NULL default(0),
	[PreSalePrice3] [numeric](18, 4) NULL default(0),
	[PreSalePrice4] [numeric](18, 4) NULL default(0),
	[PreSalePrice5] [numeric](18, 4) NULL default(0),
	[PreSalePrice6] [numeric](18, 4) NULL default(0),
	[PreSalePrice7] [numeric](18, 4) NULL default(0),
	[PreSalePrice8] [numeric](18, 4) NULL default(0),
	[PreSalePrice9] [numeric](18, 4) NULL default(0),
	[PreSalePrice10] [numeric](18, 4) NULL default(0),
	[RetailPrice] [numeric](18, 4) NULL default(0),
	[TopSalePrice] [numeric](18, 4) NULL default(0),
	[LowSalePrice] [numeric](18, 4) NULL default(0),
	UnitID  INT  NOT NULL DEFAULT(0),
	IsDefaultUnit	INT NOT NULL DEFAULT(0),  --代表默认单位
	PosDataVersion timestamp
) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

/*XiWaMaxNumber*/
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType_Price]') and name = 'XiWaMaxNumber' )
BEGIN
	ALTER TABLE dbo.PType_Price ADD
		XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
END
GO
UPDATE PType_Price SET XiWaMaxNumber = 0 WHERE XiWaMaxNumber IS NULL
GO

--最近进价
IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType_Price',N'U') AND Name='RecPrice')
BEGIN
	DECLARE @SQL VARCHAR(MAX)=''
	SELECT @SQL='alter table ['+b.name+'] drop constraint ['+d.name+']'
	FROM syscolumns a
	JOIN sysobjects b ON a.id=b.id AND a.name='recprice' AND b.name='PType_Price'
	JOIN syscomments c ON a.cdefault=c.id
	JOIN sysobjects d ON c.id=d.id
	IF @SQL<>''
	BEGIN
		EXEC(@SQL) 
	END
	ALTER TABLE dbo.PType_Price
	DROP COLUMN RecPrice
END
GO

--分支机构间最近进价
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType_Price',N'U') AND Name='RecAmgSTypeBuyPrice')
BEGIN
	ALTER TABLE dbo.PType_Price
	ADD RecAmgSTypeBuyPrice NUMERIC(24,10) DEFAULT(0)
END
GO

--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType_Price',N'U') AND Name='UnitID')
BEGIN
	ALTER TABLE dbo.PType_Price
	ADD UnitID  INT  NOT NULL DEFAULT(0)
END
GO
--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType_Price',N'U') AND Name='IsDefaultUnit')
BEGIN
	ALTER TABLE dbo.PType_Price
	ADD IsDefaultUnit  INT  NOT NULL DEFAULT(0)
END
GO


--分支机构间最近售价
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType_Price',N'U') AND Name='RecAmgSTypeSalePrice')
BEGIN
	ALTER TABLE dbo.PType_Price
	ADD RecAmgSTypeSalePrice NUMERIC(24,10) DEFAULT(0)
END
GO

IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType_Price',N'U') AND Name='RecSalePrice')
BEGIN
	DECLARE @SQL VARCHAR(MAX)=''
	SELECT @SQL='alter table ['+b.name+'] drop constraint ['+d.name+']'
	FROM syscolumns a
	JOIN sysobjects b ON a.id=b.id AND a.name='RecSalePrice' AND b.name='PType_Price'
	JOIN syscomments c ON a.cdefault=c.id
	JOIN sysobjects d ON c.id=d.id
	IF @SQL<>''
	BEGIN
		EXEC(@SQL) 
	END
	ALTER TABLE dbo.PType_Price
	DROP COLUMN RecSalePrice
END
GO
------------------------------------------表修改区域结束-------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType_Price]') and name = 'TopBuyPrice' )
BEGIN
	ALTER TABLE dbo.PType_Price ADD
		TopBuyPrice numeric(18, 4) NULL DEFAULT(0)
END
GO
UPDATE PType_Price SET TopBuyPrice=0 WHERE TopBuyPrice IS NULL
GO




if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType_Price]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.PType_Price ADD  PosDataVersion timestamp
END
GO


IF NOT EXISTS (SELECT NAME FROM SYSCOLUMNS WHERE id= OBJECT_ID(N'[dbo].[PType_Price]') and name = 'ReferPrice' )
BEGIN
	ALTER TABLE dbo.PType_Price ADD
		ReferPrice numeric(22, 10) NULL DEFAULT(0)
END
GO
UPDATE PType_Price SET ReferPrice=0 WHERE ReferPrice IS NULL
GO
------------------------------------------删除索引区域开始-----------------------------------------------
  IF  EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[PType_Price]') AND name = N'PK_PType_Price_PTypeID')
ALTER TABLE [dbo].[PType_Price] DROP CONSTRAINT [PK_PType_Price_PTypeID]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE_PRICE') AND name = 'CIX_PTYPE_PRICE_PTypeID')
--DROP INDEX CIX_PTYPE_PRICE_PTypeID ON PTYPE_PRICE 
CREATE CLUSTERED INDEX CIX_PTYPE_PRICE_PTypeID ON PTYPE_PRICE(PTypeID) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreBuyPrice1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreBuyPrice1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreBuyPrice2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreBuyPrice2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreBuyPrice3' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreBuyPrice3 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreBuyPrice4' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreBuyPrice4 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreBuyPrice5' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreBuyPrice5 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice3' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice3 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice4' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice4 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice5' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice5 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice6' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice6 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice7' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice7 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice8' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice8 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice9' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice9 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='PreSalePrice10' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN PreSalePrice10 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='RetailPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN RetailPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='TopSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN TopSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='LowSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN LowSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='TopBuyPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN TopBuyPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Price' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Price 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
GO


------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** 对象:  Table [dbo].[PType_STypePrice]    脚本日期: 05/05/2010 14:46:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[PType_STypePrice]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[PType_STypePrice] (
	[STypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL Default(0),
	[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL Default(0),
	[PreBuyPrice1] [numeric](22, 10) NULL default(0),
	[PreBuyPrice2] [numeric](18, 4) NULL default(0),
	[PreBuyPrice3] [numeric](18, 4) NULL default(0),
	[PreBuyPrice4] [numeric](18, 4) NULL default(0),
	[PreBuyPrice5] [numeric](18, 4) NULL default(0),
	[PreSalePrice1] [numeric](18, 4) NULL default(0),
	[PreSalePrice2] [numeric](18, 4) NULL default(0),
	[PreSalePrice3] [numeric](18, 4) NULL default(0),
	[PreSalePrice4] [numeric](18, 4) NULL default(0),
	[PreSalePrice5] [numeric](18, 4) NULL default(0),
	[PreSalePrice6] [numeric](18, 4) NULL default(0),
	[PreSalePrice7] [numeric](18, 4) NULL default(0),
	[PreSalePrice8] [numeric](18, 4) NULL default(0),
	[PreSalePrice9] [numeric](18, 4) NULL default(0),
	[PreSalePrice10] [numeric](18, 4) NULL default(0),
	[RetailPrice] [numeric](18, 4) NULL default(0),
	[TopSalePrice] [numeric](18, 4) NULL default(0),
	[LowSalePrice] [numeric](18, 4) NULL default(0),
	[RecPrice] [numeric](22, 10) NULL default(0),
	UnitID  INT  NOT NULL DEFAULT(0),
	IsDefaultUnit	INT NOT NULL DEFAULT(0),  --代表默认单位
	[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0),
	PosDataVersion timestamp
) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType_STypePrice]') and name = 'XiWaMaxNumber' )
	BEGIN
		BEGIN TRANSACTION
		SET QUOTED_IDENTIFIER ON
		SET ARITHABORT ON
		SET NUMERIC_ROUNDABORT OFF
		SET CONCAT_NULL_YIELDS_NULL ON
		SET ANSI_NULLS ON
		SET ANSI_PADDING ON
		SET ANSI_WARNINGS ON
		COMMIT
		BEGIN TRANSACTION
		ALTER TABLE dbo.PType_STypePrice ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
		COMMIT
	END
GO
UPDATE PType_STypePrice SET XiWaMaxNumber = 0 WHERE XiWaMaxNumber IS NULL
GO

if exists (select name from syscolumns where id = object_id(N'[dbo].[PType_STypePrice]') and name = 'RecPrice' )
begin
	ALTER TABLE PType_STypePrice ALTER COLUMN RecPrice NUMERIC(22,10)
end

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType_STypePrice]') and name = 'TopBuyPrice' )
BEGIN
	ALTER TABLE dbo.PType_STypePrice ADD
		TopBuyPrice numeric(18, 4) NULL DEFAULT(0)
END
GO
UPDATE PType_STypePrice SET TopBuyPrice=0 WHERE TopBuyPrice IS NULL
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType_STypePrice]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.PType_STypePrice ADD  PosDataVersion timestamp
END
GO


if not exists (select name from syscolumns where id = object_id(N'[dbo].[PType_STypePrice]') and name = 'referprice' )
BEGIN
	ALTER TABLE dbo.PType_STypePrice ADD
		referprice numeric(18, 4) NULL DEFAULT(0)
END
GO
UPDATE PType_STypePrice SET referprice=0 WHERE referprice IS NULL
GO

--最近销售价格
IF NOT EXISTS (SELECT Name FROM SysColumns WHERE Id=OBJECT_ID(N'[dbo].[PType_STypePrice]') AND Name='RecSalePrice')
BEGIN
	ALTER TABLE dbo.PType_STypePrice
	ADD RecSalePrice NUMERIC(22,10) NULL DEFAULT(0)
END
GO

UPDATE dbo.PType_STypePrice SET RecSalePrice=0 WHERE RecSalePrice IS NULL
GO

--最近暂估入库价格
IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PType_STypePrice',N'U') AND Name='RecAppraisalPrice')
BEGIN
	ALTER TABLE dbo.PType_STypePrice
	ADD RecAppraisalPrice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO

UPDATE dbo.PType_STypePrice SET RecAppraisalPrice=0 WHERE RecAppraisalPrice IS NULL
GO

--最近发出商品价格
IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'PType_STypePrice',N'U') AND Name='RecSendPrice')
BEGIN
	ALTER TABLE dbo.PType_STypePrice
	ADD RecSendPrice  NUMERIC(22,10) NULL DEFAULT(0)
END
GO

--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType_STypePrice',N'U') AND Name='UnitID')
BEGIN
	ALTER TABLE dbo.PType_STypePrice
	ADD UnitID  INT  NOT NULL DEFAULT(0)
END
GO
--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'PType_STypePrice',N'U') AND Name='IsDefaultUnit')
BEGIN
	ALTER TABLE dbo.PType_STypePrice
	ADD IsDefaultUnit  INT  NOT NULL DEFAULT(0)
END
GO

UPDATE dbo.PType_STypePrice SET RecSendPrice=0 WHERE RecSendPrice IS NULL
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
--老版本中明细是PType_STypePrice_index，因此也需要drop
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PType_STypePrice]') AND name = N'PType_STypePrice_index')
	DROP INDEX [dbo].[PType_STypePrice].[PType_STypePrice_index]

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PType_STypePrice]') AND name = N'CIX_PType_STypePrice_PTID')
	DROP INDEX [dbo].PType_STypePrice.[CIX_PType_STypePrice_PTID]
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PType_STypePrice]') AND name = N'NCIX_STYPEID')
	DROP INDEX [dbo].PType_STypePrice.NCIX_STYPEID
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE_STYPEPRICE') AND name = 'CIX_PTYPE_STYPEPRICE_STypeID_PTypeID')
--DROP INDEX CIX_PTYPE_STYPEPRICE_STypeID_PTypeID ON PTYPE_STYPEPRICE 
CREATE CLUSTERED INDEX CIX_PTYPE_STYPEPRICE_STypeID_PTypeID ON PTYPE_STYPEPRICE(STypeID,PTypeID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE_STYPEPRICE') AND name = 'NCIX_PTYPE_STYPEPRICE_STypeID')
--DROP INDEX NCIX_PTYPE_STYPEPRICE_STypeID ON PTYPE_STYPEPRICE 
CREATE NONCLUSTERED INDEX NCIX_PTYPE_STYPEPRICE_STypeID ON PTYPE_STYPEPRICE(STypeID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreBuyPrice1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreBuyPrice1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreBuyPrice2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreBuyPrice2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreBuyPrice3' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreBuyPrice3 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreBuyPrice4' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreBuyPrice4 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreBuyPrice5' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreBuyPrice5 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice1' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice1 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice2' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice2 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice3' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice3 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice4' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice4 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice5' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice5 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice6' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice6 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice7' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice7 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice8' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice8 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice9' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice9 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='PreSalePrice10' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN PreSalePrice10 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='RetailPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN RetailPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='TopSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN TopSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='LowSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN LowSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='RecPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN RecPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='TopBuyPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN TopBuyPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='referprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN referprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='RecSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN RecSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='RecAppraisalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN RecAppraisalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_STypePrice' AND a.Name='RecSendPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_STypePrice 
	ALTER COLUMN RecSendPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 --DROP TABLE PType_TranslateRates
IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'PType_TranslateRates') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PType_TranslateRates]
(
	PtypeId			VARCHAR(50) NOT NULL DEFAULT(''),  --商品ID
	UnitId			INT NOT NULL,                      --单位ID
	TranslateRate   numeric(24, 10),				   --换算率
	FirstUseDate    DATETIME,						   --第一次使用时间
	LastUseDate    DATETIME						   --最后使用时间
) 
END
GO

------------------------------------------表修改区域-开始-------------------------------------------------
 
------------------------------------------表修改区域-结束-------------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (
				SELECT * FROM sys.indexes 
				WHERE object_id = OBJECT_ID('PType_TranslateRates') 
				AND name = 'CIX_PType_TranslateRates_Ptypeid')
--DROP INDEX CIX_PTYPE_UNITS_EXT_Ptypeid ON PTYPE_UNITS_EXT 
CREATE CLUSTERED INDEX CIX_PType_TranslateRates_Ptypeid ON PType_TranslateRates(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_TranslateRates' AND a.Name='TranslateRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_TranslateRates 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'PType_Units') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PType_Units]
(
	UnitsId INT IDENTITY(1,1) NOT NULL,
	UserCode	VARCHAR(200) NOT NULL,
	FullName	VARCHAR(200) NOT NULL,
	Comment		VARCHAR(500) NULL
) 
INSERT INTO PType_Units(UserCode,FullName,Comment) VALUES('pcs','pcs','pcs小单位')
END
GO

--是否网店下载数据
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('PType_Units') and name='IsWdDownLoad')
BEGIN
	ALTER TABLE PType_Units ADD IsWdDownLoad BIT NOT NULL DEFAULT(0); 
End  

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE_UNITS') AND name = 'CIX_PTYPE_UNITS_UnitsId')
CREATE CLUSTERED INDEX CIX_PTYPE_UNITS_UnitsId ON PTYPE_UNITS(UnitsId)
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'PType_Units_EntryCode_Ext') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PType_Units_EntryCode_Ext]
(
	Nid             [NUMERIC](10, 0) IDENTITY(1,1),
	PtypeID			VARCHAR(50) NOT NULL DEFAULT(''),
	UnitsId			INT NOT NULL,
	EntryCode		VARCHAR(200),
	IsDefaultEntryCode BIT 
)
END
GO

------------------------------------------表修改区域-开始-------------------------------------------------
IF  EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='PType_Units_EntryCode_Ext' AND a.Name='SortId')
BEGIN
	EXEC sp_rename  @objname= 'PType_Units_EntryCode_Ext.SortId' ,  @newname ='Nid'
END
GO


IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='PType_Units_EntryCode_Ext' AND a.Name='Nid')
BEGIN
	ALTER TABLE dbo.PType_Units_EntryCode_Ext ADD  [Nid] [NUMERIC](10, 0) IDENTITY(1,1) NOT NULL
END
GO

--默认单位条码字段
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='PType_Units_EntryCode_Ext' AND a.Name='IsDefaultEntryCode')
BEGIN
	ALTER TABLE dbo.PType_Units_EntryCode_Ext ADD  [IsDefaultEntryCode] BIT  DEFAULT 0
END
GO




------------------------------------------表修改区域-结束-------------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PType_Units_EntryCode_Ext') 
AND name = 'NCIX_Ptypeid_EntryCode_Ext_search')
BEGIN 
  CREATE NONCLUSTERED INDEX NCIX_Ptypeid_EntryCode_Ext_search ON PType_Units_EntryCode_Ext(Ptypeid,EntryCode) 
END 
GO
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'PType_Units_Ext') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PType_Units_Ext]
(
	PtypeID			VARCHAR(50) NOT NULL DEFAULT(''),
	UnitsId			INT NOT NULL,
	RateType		INT NOT NULL, --0代码固定，1浮动
	Rate			NUMERIC(18,4),
	EntryCode		VARCHAR(200),
    IsDefaultUnit	INT NOT NULL DEFAULT(0),  --代表默认单位
    IsUse			INT NULL DEFAULT(1),	  --是否启用(0否1是)
) 
END
GO

------------------------------------------表修改区域-开始-------------------------------------------------

IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[PType_Units_Ext]') AND name='EntryCode')
	ALTER TABLE [dbo].[PType_Units_Ext]  ADD EntryCode VARCHAR(200) NULL
	
	
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[PType_Units_Ext]') AND name='IsUse')
	ALTER TABLE [dbo].[PType_Units_Ext]  ADD 
	IsUse			INT NULL  DEFAULT 1 WITH VALUES --增加列并设置默认值为1

------------------------------------------表修改区域-结束-------------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTYPE_UNITS_EXT') AND name = 'CIX_PTYPE_UNITS_EXT_Ptypeid')
--DROP INDEX CIX_PTYPE_UNITS_EXT_Ptypeid ON PTYPE_UNITS_EXT 
CREATE CLUSTERED INDEX CIX_PTYPE_UNITS_EXT_Ptypeid ON PTYPE_UNITS_EXT(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PType_Units_Ext' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE PType_Units_Ext 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[PType_Units_Ext]') AND name='SortId')
BEGIN
	ALTER TABLE [dbo].[PType_Units_Ext]  
		ADD SortId INT IDENTITY(1,1)
END
GO
IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id=OBJECT_ID('[PType_Units_Ext]') AND name='UnitsSortId')
BEGIN
	ALTER TABLE [dbo].[PType_Units_Ext]  
		ADD UnitsSortId INT DEFAULT(0)
END
GO
UPDATE PType_Units_Ext SET UnitsSortId = 0 WHERE UnitsSortId IS NULL
GO



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'PTypeCategory') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PTypeCategory]
(
	typeid	 VARCHAR(50) UNIQUE,
	parid	 VARCHAR(50),
	leveal	 INT,
	sonnum	 INT,
	soncount	INT,
	UserCode	VARCHAR(200) NOT NULL,
	FullName	VARCHAR(200) NOT NULL,
	Comment		VARCHAR(500) NULL
) 
	-- 初始化地区
	Delete from PTypeCategory
	INSERT INTO PTypeCategory (typeid,parid,leveal,sonnum,soncount,usercode,fullname,Comment)VALUES ('00000','root',0,0,0,'所有类别','所有类别','系统保留')

END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PTypeCategory') AND name = 'CIX_PTypeCategory_typeid')
DROP INDEX CIX_PTypeCategory_typeid ON PTypeCategory 
CREATE CLUSTERED INDEX CIX_PTypeCategory_typeid ON PTypeCategory(typeid)
------------------------------------------创建索引区域结束-----------------------------------------------







/****** 对象:  Table [dbo].[PubRecord]    脚本日期: 05/05/2010 14:48:57 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PubRecord]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PubRecord](
		[PublishDate] [datetime] NOT NULL,
		[Version] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[isPack] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PubRecord]') AND name = N'PK_PubRecord')
ALTER TABLE [dbo].[PubRecord] DROP CONSTRAINT [PK_PubRecord]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('PUBRECORD') AND name = 'CIX_PUBRECORD_PublishDate_Version_isPack')
--DROP INDEX CIX_PUBRECORD_PublishDate_Version_isPack ON PUBRECORD 
CREATE CLUSTERED INDEX CIX_PUBRECORD_PublishDate_Version_isPack ON PUBRECORD(PublishDate,Version,isPack) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Pusercode]    脚本日期: 05/05/2010 14:48:58 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Pusercode]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Pusercode](
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[usercode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if  exists (select * from syscolumns where id = object_id(N'[dbo].[Pusercode]') and  name = 'usercode' and length=50)
BEGIN
     ALTER TABLE Pusercode
	    ALTER COLUMN usercode varchar(200) NOT NULL
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Pusercode') AND name = 'CIX_Pusercode_ptypeidbtypeid')
--DROP INDEX CIX_BILLINDEX_BillDate ON BILLINDEX 
CREATE CLUSTERED INDEX CIX_Pusercode_ptypeidbtypeid ON Pusercode(ptypeid,btypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[nVipCardSet]    脚本日期: 05/05/2010 14:48:17 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[QP_nVipCardSet_RepairItems]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[QP_nVipCardSet_RepairItems ](
		[VipCardTypeID] [int] NOT NULL,
		[ID] [INT] IDENTITY(1,1) NOT NULL,
		[RepairItemsTypeID] [varchar](50) NOT NULL,
		[RepairItemsType] INT NOT NULL,
		[ManHour] NUMERIC(18,4) NOT NULL,
		[Discount] NUMERIC(18,4) NOT NULL,
		[VIPPrice] NUMERIC(22,8) NOT NULL,
		[AllowUsedTimes] INT NOT NULL,
		[Comment] VARCHAR(250) NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipCardSet_RepairItems' AND a.Name='ManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipCardSet_RepairItems 
	ALTER COLUMN ManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipCardSet_RepairItems' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipCardSet_RepairItems
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipCardSet_RepairItems' AND a.Name='VIPPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipCardSet_RepairItems 
	ALTER COLUMN VIPPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_AttemperBill_RepairItemsPerson]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_AttemperBill_RepairItemsPerson](
		[BillNumberId] [NUMERIC](18,0) NOT NULL,		
		[ID] [INT] IDENTITY(1,1) NOT NULL,
		[RepairItemsID] [INT] NULL ,
		[ETypeId] [VARCHAR](50) NULL DEFAULT(''),
		[AllocateDate] [DATETIME] NULL,
		[AllocateHour] [NUMERIC](18,4) NULL DEFAULT(0),
		[CheckHour] [NUMERIC](18,4) NULL DEFAULT(0),
		[Total] [NUMERIC](18,4) NULL DEFAULT(0),
		[CostTotal] [NUMERIC](18,4) NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_AttemperBill_RepairItemsPerson' AND a.Name='RepairItemsID'
)
BEGIN
	ALTER TABLE Qp_AttemperBill_RepairItemsPerson ADD RepairItemsID INT NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_AttemperBill_RepairItemsPerson' AND a.Name='AllocateHour'
)
BEGIN
	ALTER TABLE Qp_AttemperBill_RepairItemsPerson ADD AllocateHour NUMERIC(18,4) NULL DEFAULT('0')
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_AttemperBill_RepairItemsPerson' AND a.Name='CostTotal'
)
BEGIN
	ALTER TABLE Qp_AttemperBill_RepairItemsPerson ADD CostTotal NUMERIC(18,4) NULL DEFAULT('0')
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_AttemperBill_RepairItemsPerson' AND a.Name='AllocateHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_AttemperBill_RepairItemsPerson 
	ALTER COLUMN AllocateHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_AttemperBill_RepairItemsPerson' AND a.Name='CheckHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_AttemperBill_RepairItemsPerson 
	ALTER COLUMN CheckHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_AttemperBill_RepairItemsPerson' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_AttemperBill_RepairItemsPerson 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_AttemperBill_RepairItemsPerson' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_AttemperBill_RepairItemsPerson 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_AutoType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_AutoType] (
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Comment] [varchar] (300) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
end
GO

if not exists (select * from syscolumns where id = object_id(N'[dbo].[QP_AutoType]') and name=N'PYCode')
alter table QP_AutoType add PYCode varchar(100) null
go

update QP_AutoType set PYCode='' where PYCode is null 
go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_BackingOut_Bill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_BackingOut_Bill](		
		[BillNumberId] NUMERIC(18,0) NOT NULL,				
		[BackingOutReason] VARCHAR(2000) NULL DEFAULT(''),
		[BackingOutCheck] VARCHAR(2000) NULL DEFAULT(''),
		[BackingOutResult] VARCHAR(2000) NULL DEFAULT(''),
		[BackingOutState] INT NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_BackingOut_Bill' AND a.Name='BackingOutState'
)
BEGIN
	ALTER TABLE Qp_BackingOut_Bill ADD 
		BackingOutState INT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_BackingOut_Bill SET BackingOutState = 0 WHERE BackingOutState IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_BackType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_BackType](
		[BackTypeId] [INT] IDENTITY(1,1) NOT NULL,		
		[FullName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL DEFAULT('')		
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from dbo.syscolumns  where id = object_id(N'[dbo].[Qp_BackType]') and name=N'PYCode')
alter table Qp_BackType add PYCode varchar(100) null
go
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

update Qp_BackType set PYCode='' where PYCode is null
go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_ChargingStandards]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_ChargingStandards] (
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ManHourRate] [numeric](18, 4) NULL default(0),
		[IfDefault] [int] NOT NULL 
	) ON [PRIMARY]
end
GO

if not exists (select * from syscolumns where id = object_id(N'[dbo].[QP_ChargingStandards]') and name=N'PYCode')
alter table QP_ChargingStandards add PYCode varchar(100) null
go

update QP_ChargingStandards set PYCode='' where PYCode is null
go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_ChargingStandards' AND a.Name='ManHourRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_ChargingStandards 
	ALTER COLUMN ManHourRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_EvaluationBill_PType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_EvaluationBill_PType] (
		[BillNumberId] [numeric](10, 0) NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Qty] [numeric](18, 4) NOT NULL ,
		[Price] [numeric](22, 8) NOT NULL ,
		[total] [numeric](18, 4) NOT NULL ,
		[IsUnit2] [int] NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]
end	
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_EvaluationBill_PType' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE QP_EvaluationBill_PType ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE QP_EvaluationBill_PType SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_EvaluationBill_PType' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_EvaluationBill_PType 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_EvaluationBill_PType' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_EvaluationBill_PType 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_EvaluationBill_PType' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_EvaluationBill_PType 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_EvaluationBill_RepairItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_EvaluationBill_RepairItems] (
		[BillNumberId] [numeric](10, 0) NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[RepairItemsTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[StandardManHour] [numeric](18, 4) NOT NULL ,
		[CheckHour] [numeric](18, 4) NOT NULL ,
		[Total] [numeric](18, 4) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]
end	
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_EvaluationBill_RepairItems' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE QP_EvaluationBill_RepairItems ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE QP_EvaluationBill_RepairItems SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_EvaluationBill_RepairItems' AND a.Name='StandardManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_EvaluationBill_RepairItems 
	ALTER COLUMN StandardManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_EvaluationBill_RepairItems' AND a.Name='CheckHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_EvaluationBill_RepairItems 
	ALTER COLUMN CheckHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_EvaluationBill_RepairItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_EvaluationBill_RepairItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_InsuranceAuto]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_InsuranceAuto](
		[InsuranceAutoId] NUMERIC(10,0) IDENTITY(1,1) NOT NULL,				
		[RaTypeID] VARCHAR(50) NULL DEFAULT(''),
		[STypeID] VARCHAR(50) NULL DEFAULT(''),
		[InsuranceName] VARCHAR(500) NULL DEFAULT(''),
		[InsuranceTotal] NUMERIC(18,4) NULL DEFAULT(0),		
		[ReachDate] DATETIME NULL,
		[InsuranceNo] VARCHAR(250) NULL DEFAULT(''),
		[CardNumber] VARCHAR(100) NULL DEFAULT(''),
		[Comment] VARCHAR(100) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Qp_InsuranceAuto' AND a.Name='Mobile')
BEGIN
	ALTER TABLE Qp_InsuranceAuto ADD 
		Mobile VARCHAR(200) NULL DEFAULT('')
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_InsuranceAuto]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_InsuranceAuto
	    ALTER COLUMN Comment varchar(500) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_InsuranceAuto SET Mobile = '' WHERE Mobile IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_InsuranceAuto' AND a.Name='InsuranceTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_InsuranceAuto 
	ALTER COLUMN InsuranceTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_InsuranceBill_PType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_InsuranceBill_PType] (
		[BillNumberId] [numeric](10, 0) NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Qty] [numeric](18, 4) NOT NULL default(0),
		[TaxPrice] [numeric](22, 8) NOT NULL default(0),
		[TaxTotal] [numeric](18, 4) NOT NULL default(0),
		[InsuranceTotal] [numeric](18, 4) NOT NULL default(0),
		[GoodsCostTotal] [numeric](18, 2) NOT NULL default(0),
		[Virtual] [int] NOT NULL default(0),
		[Comment] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL default(''),
		[IsUnit2] [int] NOT NULL default(0),
		[Stypeid] [varchar](50) NULL DEFAULT ('')
	) ON [PRIMARY]
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_PType' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE QP_InsuranceBill_PType ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE QP_InsuranceBill_PType SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_PType' AND a.Name='QuickOrReceptionBillId'
)
BEGIN
	ALTER TABLE QP_InsuranceBill_PType 
		ADD QuickOrReceptionBillId INT NULL DEFAULT(0)	
END
GO

------------------------------------------表修改区域结束-------------------------------------------------
UPDATE QP_InsuranceBill_PType SET QuickOrReceptionBillId = 0 WHERE QuickOrReceptionBillId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_PType' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_PType 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_PType' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_PType 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_PType' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_PType 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_PType' AND a.Name='InsuranceTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_PType 
	ALTER COLUMN InsuranceTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_PType' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_PType 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_InsuranceBill_RepairItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_InsuranceBill_RepairItems] (
		[BillNumberId] [numeric](10, 0) NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[RepairItemsTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ManHour] [numeric](18, 4) NOT NULL default(0),
		[Total] [numeric](18, 4) NOT NULL default(0),
		[InsuranceTotal] [numeric](18, 4) NOT NULL default(0),
		[CostTotal] [numeric](18, 2) NOT NULL default(0),
		[Virtual] [int] NOT NULL default(0),
		[Comment] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL default(''),
		[Stypeid] [varchar](50) NULL DEFAULT ('')
	) ON [PRIMARY]
end	
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[QP_InsuranceBill_RepairItems]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE QP_InsuranceBill_RepairItems
	    ALTER COLUMN Comment varchar(500) 
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_RepairItems' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE QP_InsuranceBill_RepairItems ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE QP_InsuranceBill_RepairItems SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_RepairItems' AND a.Name='QuickOrReceptionBillId'
)
BEGIN
	ALTER TABLE QP_InsuranceBill_RepairItems 
		ADD QuickOrReceptionBillId INT NULL DEFAULT(0)	
END
GO

------------------------------------------表修改区域结束-------------------------------------------------
UPDATE QP_InsuranceBill_RepairItems SET QuickOrReceptionBillId = 0 WHERE QuickOrReceptionBillId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_RepairItems' AND a.Name='ManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_RepairItems 
	ALTER COLUMN ManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_RepairItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_RepairItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_RepairItems' AND a.Name='InsuranceTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_RepairItems 
	ALTER COLUMN InsuranceTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InsuranceBill_RepairItems' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InsuranceBill_RepairItems 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_IntendingTalkBack_Bill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_IntendingTalkBack_Bill](
		[BillNumberId] NUMERIC(18,0) NOT NULL,				
		[ETypeID] VARCHAR(50) NULL DEFAULT(''),
		[RepairContentmentDegree] VARCHAR(200) NULL DEFAULT(''),
		[CompContentmentDegree] VARCHAR(200) NULL DEFAULT(''),
		[CustomerQuestion] VARCHAR(2000) NULL DEFAULT(''),		
		[DealResult] VARCHAR(2000) NULL DEFAULT(''),
		[Comment] VARCHAR(2000) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Qp_IntendingTalkBack_Bill' AND a.Name='Comment')
BEGIN
	ALTER TABLE Qp_IntendingTalkBack_Bill ADD 
		Comment VARCHAR(500) NULL DEFAULT('')
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_IntendingTalkBack_Bill]') and  name = 'Comment' and length=2000)
BEGIN
     ALTER TABLE Qp_IntendingTalkBack_Bill
	    ALTER COLUMN Comment varchar(2000) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_IntendingTalkBack_Bill SET Comment = '' WHERE Comment IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[FaPiaoBill]    脚本日期: 05/05/2010 14:47:20 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_InvoiceOtherTotalDetails]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[QP_InvoiceOtherTotalDetails](
		[BillNumberID] [numeric](10, 0) NOT NULL CONSTRAINT [DF_QP_InvoiceOtherTotalDetails_BillNumberID]  DEFAULT (0),
		[BillType] [numeric](4, 0) NOT NULL,
		[MainBillNumberID] [numeric](10, 0) NULL CONSTRAINT [DF_QP_InvoiceOtherTotalDetails_MainBillNumberID]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_QP_InvoiceOtherTotalDetails_Total]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')	
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InvoiceOtherTotalDetails' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InvoiceOtherTotalDetails 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[QP_InvoiceRepairItems]    脚本日期: 08/11/2011 10:47:20 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_InvoiceRepairItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[QP_InvoiceRepairItems](
		[BillNumberID] [numeric](10, 0) NOT NULL CONSTRAINT [DF_QP_InvoiceRepairItems_BillNumberID]  DEFAULT (0),
		[BillType] [numeric](4, 0) NOT NULL,
		[MainBillNumberID] [numeric](10, 0) NULL CONSTRAINT [DF_QP_InvoiceRepairItems_MainBillNumberID]  DEFAULT (0),
		[RepairItemsTypeID] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_QP_InvoiceRepairItems_RepairItemsTypeID]  DEFAULT (''),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_QP_InvoiceRepairItemsl_Total]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_QP_InvoiceRepairItems_Tax]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_QP_InvoiceRepairItems_Comment]  DEFAULT (''),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')	
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InvoiceRepairItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InvoiceRepairItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InvoiceRepairItems' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InvoiceRepairItems 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_InvoiceRepairItems' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_InvoiceRepairItems 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_MiantenanceInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_MiantenanceInfo](
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[RepairAutoTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[hightMileage] [numeric](18, 0) NULL default(0),
		[lowMileage] [numeric](18, 0) NULL default(0),
		[Suggestion] [varchar] (2000) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]
	
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_MulStockConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[Qp_MulStockConfig] (
		[BillType] [int] NULL ,
		[IsChecked] [int] NULL 
	) ON [PRIMARY]
		
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_nVipAddWashTimes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_nVipAddWashTimes] (
		[nID] [int] IDENTITY (1, 1) NOT NULL ,
		[CardId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[BillDate] [datetime] NULL ,
		[ETypeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[aMoney] [numeric](18, 2) NULL ,
		[TotalInMoney] [numeric](18, 2) NULL ,
		[PreferenceMoney] [numeric](18, 2) NULL ,
		[AddTimes] [int] NULL ,
		[ATypeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[Comment] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipAddWashTimes' AND a.Name='aMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipAddWashTimes 
	ALTER COLUMN aMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipAddWashTimes' AND a.Name='TotalInMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipAddWashTimes 
	ALTER COLUMN TotalInMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipAddWashTimes' AND a.Name='PreferenceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipAddWashTimes 
	ALTER COLUMN PreferenceMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Pusercode]    脚本日期: 05/05/2010 14:48:58 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_nVipCardSet_RepairItems ]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_nVipCardSet_RepairItems ] (
		[VipCardTypeID] [int] NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[RepairItemsTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[RepairItemsType] [int] NOT NULL ,
		[ManHour] [numeric](18, 4) NOT NULL ,
		[Discount] [numeric](18, 4) NOT NULL ,
		[VIPPrice] [numeric](22, 8) NOT NULL ,
		[AllowUsedTimes] [int] NOT NULL ,
		[Comment] [varchar] (1000) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
end	
GO



------------------------------------------表修改区域开始-------------------------------------------------
if  exists (select * from syscolumns where id = object_id(N'[dbo].[QP_nVipCardSet_RepairItems]') and  name = 'Comment' and length <> 1000)
BEGIN
     ALTER TABLE QP_nVipCardSet_RepairItems
	    ALTER COLUMN Comment varchar(1000) NULL
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipCardSet_RepairItems ' AND a.Name='ManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipCardSet_RepairItems  
	ALTER COLUMN ManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipCardSet_RepairItems ' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipCardSet_RepairItems  
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipCardSet_RepairItems ' AND a.Name='VIPPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipCardSet_RepairItems  
	ALTER COLUMN VIPPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_nVipCardSign_RemindEvent]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_nVipCardSign_RemindEvent] (
		[VipCardID] [int] NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[RemindContent] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[RemindDate] [datetime] NOT NULL ,
		[Comment] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[nVipCardSet]    脚本日期: 05/05/2010 14:48:17 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[QP_nVipCardSign_RepairItems]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[QP_nVipCardSign_RepairItems ](
		[VipCardID] [int] NOT NULL,
		[ID] [INT] IDENTITY(1,1) NOT NULL,
		[RepairItemsTypeID] [varchar](50) NOT NULL,
		[ManHour] NUMERIC(18,4) NOT NULL,
		[VIPPrice] NUMERIC(22,8) NOT NULL,
		[AllowUsedTimes] INT NOT NULL,
		[UsedTimes] INT NOT NULL default(0),
		[Comment] VARCHAR(250) NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipCardSign_RepairItems' AND a.Name='ManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipCardSign_RepairItems 
	ALTER COLUMN ManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_nVipCardSign_RepairItems' AND a.Name='VIPPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_nVipCardSign_RepairItems 
	ALTER COLUMN VIPPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_OperationSort]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_OperationSort] (
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL 
	) ON [PRIMARY]
end	
GO

------------------------------表修改区域开始 --------------------------------
if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[QP_OperationSort]') and name=N'PYCode')
alter table QP_OperationSort add PYCode varchar(100) null
go
------------------------------表修改区域结束---------------------------------

update QP_OperationSort set PYCode='' where PYCode is null
go

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_PickingBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_PickingBackBill](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[PickingId] INT NULL DEFAULT(0),
		[KTypeId] VARCHAR(50) NULL DEFAULT(''),
		[PTypeId] VARCHAR(50) NULL DEFAULT(''),
		[Qty] NUMERIC(18,4) NULL DEFAULT(0),
		[Price] NUMERIC(18,4) NULL DEFAULT(0),
		[InputCostPrice] NUMERIC(18,4) NULL DEFAULT(0),
		[CargoSpace] VARCHAR(200) NULL DEFAULT(''),
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[Insurance] INT NULL DEFAULT(0),
		[Comment] VARCHAR(250) NULL DEFAULT(''),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Qp_PickingBackBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.Qp_PickingBackBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Qp_PickingBackBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.Qp_PickingBackBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Qp_PickingBackBill' AND a.Name='CargoSpace')
BEGIN
	ALTER TABLE Qp_PickingBackBill ADD 
		CargoSpace VARCHAR(200) NULL DEFAULT('')
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_PickingBackBill]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_PickingBackBill
	    ALTER COLUMN Comment varchar(500) 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Qp_PickingBackBill' AND a.Name='IsUnit2')
BEGIN
	ALTER TABLE Qp_PickingBackBill ADD 
		IsUnit2 INT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Qp_PickingBackBill' AND a.Name='HandZeroCost')
BEGIN
	ALTER TABLE Qp_PickingBackBill ADD 
		HandZeroCost INT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_PickingBackBill SET CargoSpace = '' WHERE CargoSpace IS NULL
GO
UPDATE Qp_PickingBackBill SET IsUnit2 = 0 WHERE IsUnit2 IS NULL
GO
UPDATE Qp_PickingBackBill SET HandZeroCost = 0 WHERE HandZeroCost IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBackBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBackBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBackBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBackBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBackBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBackBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBackBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBackBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_PickingBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_PickingBill](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[ReceptionBillId] INT NOT NULL,
		[KTypeID] VARCHAR(50) NULL,
		[CargoSpace] VARCHAR(200) NULL DEFAULT(''),
		[PTypeID] VARCHAR(50) NULL,
		[Qty] NUMERIC(18,4) NULL DEFAULT(0),
		[BackQty] NUMERIC(18,4) NULL DEFAULT(0),
		[Price] NUMERIC(18,4) NULL DEFAULT(0),
		[InputCostPrice] NUMERIC(18,4) NULL DEFAULT(0),
		[Total] NUMERIC(18,4) NULL DEFAULT(0),		
		[Insurance] INT NULL DEFAULT(0),
		[IsUnit2] INT NULL DEFAULT(0)
	    ,[DraftFlag] [bit] NOT NULL DEFAULT (1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT (0)	
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Qp_PickingBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.Qp_PickingBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Qp_PickingBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.Qp_PickingBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Qp_PickingBill' AND a.Name='Comment')
BEGIN
	ALTER TABLE Qp_PickingBill ADD
		Comment VARCHAR(250) NULL
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_PickingBill]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_PickingBill
	    ALTER COLUMN Comment varchar(500) 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Qp_PickingBill' AND a.Name='HandZeroCost')
BEGIN
	ALTER TABLE Qp_PickingBill ADD
		HandZeroCost INT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_PickingBill SET Comment = '' WHERE Comment IS NULL
GO
UPDATE Qp_PickingBill SET HandZeroCost = 0 WHERE HandZeroCost IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_PickingBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_PickingBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_PType_Ext]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_PType_Ext] (
		[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Brand] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[Import] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[GeneralType] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[GeneralDwgNo] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL ,
		[Property] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[PackageQty] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[Weight] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[TaxNumber] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[Taxrate] [numeric](18, 4) NULL ,
		[BTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[FcUnit] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[FcPrice] [numeric](18, 4) NULL Default(0)
	) ON [PRIMARY]
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------
if  exists (select * from syscolumns where id = object_id(N'[dbo].[QP_PType_Ext]') and  name = 'FcPrice' and cdefault=0)
BEGIN
    ALTER TABLE dbo.QP_PType_Ext ADD CONSTRAINT
	DF_QP_PType_Ext_FcPrice DEFAULT 0 FOR FcPrice

END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS(SELECT f.name FROM dbo.sysindexes f WHERE f.name = 'PK_Qp_PType_Ext_PTypeId')
	ALTER TABLE [dbo].[QP_PType_Ext] DROP CONSTRAINT [PK_Qp_PType_Ext_PTypeId]


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[QP_PType_Ext]') AND name = N'NCIX_BTYPEID')
	DROP INDEX [dbo].QP_PType_Ext.NCIX_BTYPEID	
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QP_PTYPE_EXT') AND name = 'CIX_QP_PTYPE_EXT_PTypeID')
--DROP INDEX CIX_QP_PTYPE_EXT_PTypeID ON QP_PTYPE_EXT 
CREATE CLUSTERED INDEX CIX_QP_PTYPE_EXT_PTypeID ON QP_PTYPE_EXT(PTypeID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QP_PTYPE_EXT') AND name = 'NCIX_QP_PTYPE_EXT_BTypeID')
--DROP INDEX NCIX_QP_PTYPE_EXT_BTypeID ON QP_PTYPE_EXT 
CREATE NONCLUSTERED INDEX NCIX_QP_PTYPE_EXT_BTypeID ON QP_PTYPE_EXT(BTypeID) 


------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_PType_Ext' AND a.Name='Taxrate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_PType_Ext 
	ALTER COLUMN Taxrate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_PType_Ext' AND a.Name='FcPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_PType_Ext 
	ALTER COLUMN FcPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QuickRepairBill_PType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_QuickRepairBill_PType] (
		[BillNumberId] [numeric](10, 0) NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[KTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[CargoSpace] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Qty] [numeric](18, 4) NOT NULL ,
		[Price] [numeric](22, 8) NOT NULL ,
		[total] [numeric](18, 4) NOT NULL ,
		[Discount] [numeric](18, 4) NOT NULL ,
		[DiscountPrice] [numeric](22, 8) NOT NULL ,
		[DiscountTotal] [numeric](18, 4) NOT NULL ,
		[RepairManTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Comment] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL ,
		[IsUnit2] [int] NOT NULL ,
		[InputCostPrice] [numeric](22, 8) NOT NULL Default(0),
		[GoodsCostPrice] [numeric](22, 8) NOT NULL Default(0),
		[GoodsCostTotal] [numeric](18, 4) NOT NULL Default(0),
		[HandZeroCost] [int] NOT NULL Default(0),
		[Insurance] [int] NOT NULL Default(0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]
end	
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'QP_QuickRepairBill_PType',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.QP_QuickRepairBill_PType
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'QP_QuickRepairBill_PType',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.QP_QuickRepairBill_PType
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE QP_QuickRepairBill_PType ADD STypeID VARCHAR(50) DEFAULT('')
	
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE QP_QuickRepairBill_PType SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='CounterClaimStatus'
)
BEGIN
	ALTER TABLE QP_QuickRepairBill_PType ADD 
		CounterClaimStatus INT DEFAULT '0' NULL	
END
GO


UPDATE QP_QuickRepairBill_PType SET CounterClaimStatus = 0 WHERE CounterClaimStatus IS NULL
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='DiscountTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN DiscountTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_PType' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_PType 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QuickRepairBill_RepairItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_QuickRepairBill_RepairItems] (
		[BillNumberId] [numeric](10, 0) NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[RepairItemsTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[StandardManHour] [numeric](18, 4) NOT NULL ,
		[CheckHour] [numeric](18, 4) NOT NULL ,
		[Total] [numeric](18, 4) NOT NULL ,
		[Discount] [numeric](18, 4) NOT NULL ,
		[DiscountTotal] [numeric](18, 4) NOT NULL ,
		[RepairManTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Comment] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL ,
		[Insurance] [int] NOT NULL Default(0),
		[CostTotal] [numeric](18, 2) NOT NULL Default(0),
		[Limited] [int] NOT NULL Default(0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]
end	
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_RepairItems' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE QP_QuickRepairBill_RepairItems ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE QP_QuickRepairBill_RepairItems SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_RepairItems' AND a.Name='CounterClaimStatus'
)
BEGIN
	ALTER TABLE QP_QuickRepairBill_RepairItems ADD 
		CounterClaimStatus INT DEFAULT '0' NULL	
END
GO


UPDATE QP_QuickRepairBill_RepairItems SET CounterClaimStatus = 0 WHERE CounterClaimStatus IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_RepairItems' AND a.Name='StandardManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_RepairItems 
	ALTER COLUMN StandardManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_RepairItems' AND a.Name='CheckHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_RepairItems 
	ALTER COLUMN CheckHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_RepairItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_RepairItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_RepairItems' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_RepairItems 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_RepairItems' AND a.Name='DiscountTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_RepairItems 
	ALTER COLUMN DiscountTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_QuickRepairBill_RepairItems' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_QuickRepairBill_RepairItems 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ReceptionBill_Accessory]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_ReceptionBill_Accessory](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[Items] VARCHAR(100) NULL DEFAULT(''),
		[OtherAccessory] VARCHAR(1000) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ReceptionBill_FactUsePType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_ReceptionBill_FactUsePType](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ReceptionBillPTypeId] INT NOT NULL,
		[ID] INT IDENTITY(1,1) NOT NULL,		
		[PickingId] INT NOT NULL,
		[PTypeID] VARCHAR(50) NULL,
		[Qty] NUMERIC(18,4) NULL DEFAULT(0),
		[Price] NUMERIC(18,4) NULL DEFAULT(0),
		[Total] NUMERIC(18,4) NULL DEFAULT(0),		
		[CostTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[Insurance] INT NULL DEFAULT(0),
		[ETypeID] VARCHAR(50) NULL,
		[ReceptionBillnumberId] NUMERIC(10,0) NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='ReceptionBillnumberId'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType ADD ReceptionBillnumberId NUMERIC(10,0) DEFAULT(0) NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='Discount'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType ADD Discount NUMERIC(18,4) DEFAULT(0) NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='DiscountPrice'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType ADD DiscountPrice NUMERIC(18,4) DEFAULT(0) NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='DiscountTotal'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType ADD DiscountTotal NUMERIC(18,4) DEFAULT(0) NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType ADD Comment VARCHAR(250) DEFAULT('') NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='Virtual'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType ADD Virtual INT DEFAULT(0) NULL	
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_ReceptionBill_FactUsePType]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_ReceptionBill_FactUsePType
	    ALTER COLUMN Comment varchar(500) 
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='CounterClaimStatus'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType ADD 
		CounterClaimStatus INT DEFAULT '0' NULL	
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_ReceptionBill_FactUsePType SET ReceptionBillnumberId = 0 WHERE ReceptionBillnumberId IS NULL
GO
UPDATE Qp_ReceptionBill_FactUsePType SET Discount = 0 WHERE Discount IS NULL
GO
UPDATE Qp_ReceptionBill_FactUsePType SET DiscountPrice = 0 WHERE DiscountPrice IS NULL
GO
UPDATE Qp_ReceptionBill_FactUsePType SET DiscountTotal = 0 WHERE DiscountTotal IS NULL
GO
UPDATE Qp_ReceptionBill_FactUsePType SET Comment = '' WHERE Comment IS NULL
GO
UPDATE Qp_ReceptionBill_FactUsePType SET Virtual = 0 WHERE Virtual IS NULL
GO
UPDATE Qp_ReceptionBill_FactUsePType SET CounterClaimStatus = 0 WHERE CounterClaimStatus IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_FactUsePType' AND a.Name='DiscountTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_FactUsePType 
	ALTER COLUMN DiscountTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ReceptionBill_Insurance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_ReceptionBill_Insurance](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[BTypeID] VARCHAR(50) NULL DEFAULT(''),
		[AccidentDate] DATETIME NULL,
		[AccidentAddr] VARCHAR(1000) NULL DEFAULT(''),
		[AccidentReason] VARCHAR(2000) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ReceptionBill_Pic]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_ReceptionBill_Pic](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[Pic] IMAGE NULL
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_Pic' AND a.Name='ImgPoint'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_Pic 
		ADD ImgPoint VARCHAR(6000) NULL DEFAULT('')
END

GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_ReceptionBill_Pic SET ImgPoint = '' WHERE ImgPoint IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ReceptionBill_PType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_ReceptionBill_PType](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[PTypeID] VARCHAR(50) NULL,
		[Qty] NUMERIC(18,4) NULL DEFAULT(0),
		[Price] NUMERIC(18,4) NULL DEFAULT(0),
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[Discount] NUMERIC(18,4) NULL DEFAULT(0),
		[DiscountPrice] NUMERIC(18,4) NULL DEFAULT(0),
		[DiscountTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[Insurance] INT NULL DEFAULT(0),
		[Comment] VARCHAR(250) NULL,
		[Virtual] INT NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_PType' AND a.Name='Comment'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_PType ADD Comment VARCHAR(250) DEFAULT '' NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_PType' AND a.Name='Discount'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_PType ADD 
		Discount NUMERIC(18,4) DEFAULT(0) NULL,
		DiscountPrice NUMERIC(18,4) DEFAULT(0) NULL,	
		DiscountTotal NUMERIC(18,4) DEFAULT(0) NULL,
		Virtual INT DEFAULT(0) NULL
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_ReceptionBill_PType]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_ReceptionBill_PType
	    ALTER COLUMN Comment varchar(500) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_ReceptionBill_PType SET Comment = '' WHERE Comment IS NULL
GO
UPDATE Qp_ReceptionBill_PType SET Discount = 0 WHERE Discount IS NULL
GO
UPDATE Qp_ReceptionBill_PType SET DiscountPrice = 0 WHERE DiscountPrice IS NULL
GO
UPDATE Qp_ReceptionBill_PType SET DiscountTotal = 0 WHERE DiscountTotal IS NULL
GO
UPDATE Qp_ReceptionBill_PType SET Virtual = 0 WHERE Virtual IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_PType' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_PType 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_PType' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_PType 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_PType' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_PType 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_PType' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_PType 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_PType' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_PType 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_PType' AND a.Name='DiscountTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_PType 
	ALTER COLUMN DiscountTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
GO	

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ReceptionBill_RepairItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_ReceptionBill_RepairItems](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[RepairItemsTypeID] VARCHAR(50) NULL,
		[StandardManHour] NUMERIC(18,4) NULL DEFAULT(0),
		[CheckHour] NUMERIC(18,4) NULL DEFAULT(0),
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[CostTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[RepairProcess] INT NULL DEFAULT(0),	
		[StopReason] VARCHAR(250) NULL DEFAULT(''),
		[RepairMan] VARCHAR(100) NULL DEFAULT(''),
		[StopTime] DATETIME NULL,
		[Discount] NUMERIC(18,4) NULL DEFAULT(0),
		[DiscountTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[Insurance] INT NULL DEFAULT(0),
		[Comment] VARCHAR(250) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='Virtual'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems ADD Virtual INT DEFAULT '0' NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='AppointTime'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems ADD AppointTime DATETIME NULL 
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_ReceptionBill_RepairItems]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_ReceptionBill_RepairItems
	    ALTER COLUMN Comment varchar(500) 
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='Limited'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems ADD 
		Limited INT DEFAULT '0' NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='CounterClaimStatus'
)
BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems ADD 
		CounterClaimStatus INT DEFAULT '0' NULL	
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_ReceptionBill_RepairItems SET Virtual = 0 WHERE Virtual IS NULL
GO
UPDATE Qp_ReceptionBill_RepairItems SET Limited = 0 WHERE Limited IS NULL
GO
UPDATE Qp_ReceptionBill_RepairItems SET CounterClaimStatus = 0 WHERE CounterClaimStatus IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='StandardManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems 
	ALTER COLUMN StandardManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='CheckHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems 
	ALTER COLUMN CheckHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ReceptionBill_RepairItems' AND a.Name='DiscountTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ReceptionBill_RepairItems 
	ALTER COLUMN DiscountTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RecycleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_RecycleBill] (
		[BillNumberId] [numeric](10, 0) NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Qty] [numeric](18, 4) NOT NULL ,
		[Price] [numeric](22, 8) NOT NULL ,
		[total] [numeric](18, 4) NOT NULL ,
		[Comment] [varchar] (250) COLLATE Chinese_PRC_CI_AS NULL ,
		[Status] [int] NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]
end	
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RecycleBill' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE QP_RecycleBill ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE QP_RecycleBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RecycleBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RecycleBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RecycleBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RecycleBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RecycleBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RecycleBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairAutoInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_RepairAutoInfo] (
		[TypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ParID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Leveal] [int] NOT NULL ,
		[SonCount] [int] NOT NULL ,
		[SonNum] [int] NOT NULL ,
		[PlateNumber] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[EngineNumber] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[BTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[RepairAutoTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[FrameNumber] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[TransmissionNumber] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[VIN] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[Color] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[RecordDate] [datetime] NULL ,
		[ForceMaintainDate] [datetime] NULL ,
		[ForceMaintainMileage] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[FirstMaintainDate] [datetime] NULL ,
		[FirstMaintainMileage] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[Comment] [varchar] (300) COLLATE Chinese_PRC_CI_AS NULL ,
		[LeaveFactoryNum] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[LeaveFactoryDate] [datetime] NULL ,
		[Driver] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[DriverMobilePhone] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[CardNumber] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[ChargingStandardsID] [int] NOT NULL ,
		[XiWaMaxNumber] [numeric](18, 0) NULL default(0)
	) ON [PRIMARY]
	
	--维修车辆信息档案
	DELETE FROM QP_RepairAutoInfo
	INSERT INTO QP_RepairAutoInfo(TypeId,ParId,Leveal,SonCount,SonNum,PlateNumber,EngineNumber,BTypeID,RepairAutoTypeID,FrameNumber,TransmissionNumber,VIN,Color,RecordDate,ForceMaintainDate,ForceMaintainMileage,FirstMaintainDate,FirstMaintainMileage,Comment,LeaveFactoryNum,LeaveFactoryDate,Driver,DriverMobilePhone,CardNumber,ChargingStandardsID)VALUES('00000','root',0,0,0,'全部维修车辆信息档案','','','','','','','','','','','','','','','','','','','')
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[QP_RepairAutoInfo]') and name=N'PYCode')
alter table QP_RepairAutoInfo add PYCode varchar(200) null
GO

update QP_RepairAutoInfo set PYCode='' where PYCode is null
go

if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[QP_RepairAutoInfo]') and name=N'BaoxianBtypeid')
alter table QP_RepairAutoInfo add BaoxianBtypeid varchar(100) null
GO

--拼音码改成和车牌号同样长度200
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairAutoInfo' AND a.Name='PYCode'
)
BEGIN
	ALTER TABLE QP_RepairAutoInfo ALTER COLUMN PYCode VARCHAR(200) NULL

END
GO

------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairAutoInfoSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[QP_RepairAutoInfoSet](
		[etypeid] [nvarchar](50) NULL,
		[IsCreateByPlateNumber] [int] NULL,
		[btypeid] [nvarchar](50) NULL
	) ON [PRIMARY]
END

GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairAutoType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_RepairAutoType] (
		[TypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ParID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Leveal] [int] NOT NULL ,
		[SonCount] [int] NOT NULL ,
		[SonNum] [int] NOT NULL ,
		[UserCode] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[XiWaMaxNumber] [numeric](18, 0) NULL default(0)
	) ON [PRIMARY]
	
	--维修车型档案
	DELETE FROM QP_RepairAutoType
	INSERT INTO QP_RepairAutoType(TypeId,ParId,Leveal,SonCount,SonNum,UserCode,FullName,XiWaMaxNumber)VALUES('00000','root',0,0,0,'00000','全部维修车型档案',0)	
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from syscolumns where id = object_id(N'[dbo].[QP_RepairAutoType]') and name=N'PYCode')
alter table QP_RepairAutoType add PYCode varchar(100) null
go

------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

update QP_RepairAutoType set PYCode='' where PYCode is null
go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_RepairItems] (
		[TypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ParID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Leveal] [int] NOT NULL ,
		[SonCount] [int] NOT NULL ,
		[SonNum] [int] NOT NULL ,
		[UserCode] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ItemType] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[StandardManHour] [numeric](18, 4) NULL default(0),
		[CheckHour] [numeric](18, 4) NULL default(0),
		[StandardPrice] [numeric](18, 4) NULL default(0),
		[TopPrice] [numeric](18, 4) NULL default(0),
		[LowPrice] [numeric](18, 4) NULL default(0),
		[ChargeMode] [int] NULL default(0),
		[RepairAutoTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[MaintainDays] [int] NULL default(0),
		[Comment] [varchar] (300) COLLATE Chinese_PRC_CI_AS NULL ,
		[XiWaMaxNumber] [numeric](18, 0) NULL default(0)
	) ON [PRIMARY]
	
	--维修项目资料
	DELETE FROM QP_RepairItems
	INSERT INTO QP_RepairItems(TypeId,ParId,Leveal,SonCount,SonNum,UserCode,FullName,ItemType,StandardManHour,CheckHour,StandardPrice,TopPrice,LowPrice,ChargeMode,RepairAutoTypeID,MaintainDays,Comment)VALUES('00000','root',0,0,0,'00000','全部维修项目资料','0',0,0,0,0,0,0,0,0,'')	
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from syscolumns where id = object_id(N'[dbo].[QP_RepairItems]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE QP_RepairItems
	    ALTER COLUMN Comment varchar(500) 
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='QP_RepairItems' AND a.Name='MaintainMileage')
BEGIN
	ALTER TABLE QP_RepairItems ADD 
			MaintainMileage NUMERIC(18,0) NULL	DEFAULT(0),
			UserDefine1 VARCHAR(250) NULL	DEFAULT(''),
			UserDefine2 VARCHAR(250) NULL	DEFAULT(''),
			UserDefine3 VARCHAR(250) NULL	DEFAULT(''),
			UserDefine4 VARCHAR(250) NULL	DEFAULT(''),
			UserDefine5 VARCHAR(250) NULL	DEFAULT('')
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='QP_RepairItems' AND a.Name='PyCode')
BEGIN
	ALTER TABLE QP_RepairItems ADD 	
			PyCode VARCHAR(500) NULL
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE QP_RepairItems SET MaintainMileage = 0 WHERE MaintainMileage IS NULL
GO
UPDATE QP_RepairItems SET UserDefine1 = '' WHERE UserDefine1 IS NULL
GO
UPDATE QP_RepairItems SET UserDefine2 = '' WHERE UserDefine2 IS NULL
GO
UPDATE QP_RepairItems SET UserDefine3 = '' WHERE UserDefine3 IS NULL
GO
UPDATE QP_RepairItems SET UserDefine4 = '' WHERE UserDefine4 IS NULL
GO
UPDATE QP_RepairItems SET UserDefine5 = '' WHERE UserDefine5 IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairItems' AND a.Name='StandardManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairItems 
	ALTER COLUMN StandardManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairItems' AND a.Name='CheckHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairItems 
	ALTER COLUMN CheckHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairItems' AND a.Name='StandardPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairItems 
	ALTER COLUMN StandardPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairItems' AND a.Name='TopPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairItems 
	ALTER COLUMN TopPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairItems' AND a.Name='LowPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairItems 
	ALTER COLUMN LowPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairMode]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_RepairMode] (
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL 
	) ON [PRIMARY]
end	
GO



------------------------------表修改区域开始 --------------------------------
if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[QP_RepairMode]') and name=N'PYCode')
alter table QP_RepairMode add PYCode varchar(100) null
go
------------------------------表修改区域结束---------------------------------


UPDATE QP_RepairMode SET PYCode='' WHERE PYCode IS NULL

go


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairSetMeal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_RepairSetMeal] (
		[TypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ParID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Leveal] [int] NOT NULL ,
		[SonCount] [int] NOT NULL ,
		[SonNum] [int] NOT NULL ,
		[UserCode] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[FullName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Failure] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[DealTenet] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL 
	) ON [PRIMARY]
	
	--维修套餐
	DELETE FROM QP_RepairSetMeal
	INSERT INTO QP_RepairSetMeal(TypeID,ParID,Leveal,SonCount,SonNum,UserCode,FullName, Failure, DealTenet)VALUES('00000','root',0,0,0,'00000','全部维修套餐','0','0')	
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[QP_RepairSetMeal]') and name=N'PYCode')
	alter table QP_RepairSetMeal 
		add PYCode varchar(100) null
go
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[QP_RepairSetMeal]') AND name = N'PK_QP_RepairSetMeal')
ALTER TABLE [dbo].[QP_RepairSetMeal] DROP CONSTRAINT [PK_QP_RepairSetMeal]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QP_REPAIRSETMEAL') AND name = 'CIX_QP_REPAIRSETMEAL_TypeID')
--DROP INDEX CIX_QP_REPAIRSETMEAL_TypeID ON QP_REPAIRSETMEAL 
CREATE CLUSTERED INDEX CIX_QP_REPAIRSETMEAL_TypeID ON QP_REPAIRSETMEAL(TypeID) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE QP_RepairSetMeal SET PYCode = '' WHERE PYCode IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




if NOT exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairSetMeal_Fittings]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[QP_RepairSetMeal_Fittings] (
		[TypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Qty] [numeric](18, 4) NOT NULL ,
		[Price] [numeric](18, 4) NOT NULL ,
		[Total] [numeric](18, 4) NOT NULL 
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[QP_RepairSetMeal_Fittings]') AND name = N'IX_QP_RepairSetMeal_Fittings')
BEGIN TRY
		ALTER TABLE [dbo].[QP_RepairSetMeal_Fittings] 
		DROP CONSTRAINT [IX_QP_RepairSetMeal_Fittings]
END TRY
BEGIN CATCH

	DROP INDEX QP_RepairSetMeal_Fittings.IX_QP_RepairSetMeal_Fittings
END CATCH



------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------


------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairSetMeal_Fittings' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairSetMeal_Fittings 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairSetMeal_Fittings' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairSetMeal_Fittings 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairSetMeal_Fittings' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairSetMeal_Fittings 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairSetMeal_Items]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_RepairSetMeal_Items] (
		
		[RepairItemsTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[TypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[StandardManHour] [numeric](18, 4) NOT NULL ,
		[CheckManHour] [numeric](18, 4) NOT NULL ,
		[ManHourExpense] [numeric](18, 4) NOT NULL 
	) ON [PRIMARY]
end
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------


------------------------------------------创建索引区域结束-----------------------------------------------	

update QP_RepairSetMeal set PYCode='' where PYCode is null
go


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairSetMeal_Items' AND a.Name='StandardManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairSetMeal_Items 
	ALTER COLUMN StandardManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairSetMeal_Items' AND a.Name='CheckManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairSetMeal_Items 
	ALTER COLUMN CheckManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QP_RepairSetMeal_Items' AND a.Name='ManHourExpense' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QP_RepairSetMeal_Items 
	ALTER COLUMN ManHourExpense NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_RepairState]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_RepairState](
		[StateId] [INT] NOT NULL,		
		[StateName] [VARCHAR](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT(''),
		[IsOperation] [INT] DEFAULT(0)
	) ON [PRIMARY]
END
GO
-- ********	处理 Qp_RepairState	********
DELETE FROM Qp_RepairState
INSERT INTO Qp_RepairState([StateId],[StateName],[IsOperation])VALUES(0,'正常',0)
INSERT INTO Qp_RepairState([StateId],[StateName],[IsOperation])VALUES(1,'三包',0)
INSERT INTO Qp_RepairState([StateId],[StateName],[IsOperation])VALUES(2,'保险',0)
INSERT INTO Qp_RepairState([StateId],[StateName],[IsOperation])VALUES(3,'返修',0)
INSERT INTO Qp_RepairState([StateId],[StateName],[IsOperation])VALUES(4,'赠送',0)

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SuccorBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_SuccorBill](
		[BillNumberId] NUMERIC(18,0) NOT NULL,	
		[LinkPerson] VARCHAR(100) NULL DEFAULT(''),
		[LinkTel] VARCHAR(100) NULL DEFAULT(''),
		[ServiceCardNo] VARCHAR(100) NULL DEFAULT(''),
		[SuccorAddr] VARCHAR(250) NULL DEFAULT(''),
		[SuccorId] INT NULL DEFAULT(0),
		[StartDate] DATETIME NULL,
		[ReachDate] DATETIME NULL,
		[ReturnDate] DATETIME NULL
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SuccorBill_ErrDescription]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_SuccorBill_ErrDescription](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[Comment] VARCHAR(2000) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_SuccorBill_ErrDescription]') and  name = 'Comment' and length=2000)
BEGIN
     ALTER TABLE Qp_SuccorBill_ErrDescription
	    ALTER COLUMN Comment varchar(2000) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SuccorBill_PType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_SuccorBill_PType](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[PTypeID] VARCHAR(50) NULL DEFAULT(''),
		[Qty] NUMERIC(18,4) NULL DEFAULT(0),
		[Price] NUMERIC(18,4) NULL DEFAULT(0),
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[ETypeID] VARCHAR(50) NULL DEFAULT(''),
		[Comment] VARCHAR(250) NULL DEFAULT(''),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Qp_SuccorBill_PType',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.Qp_SuccorBill_PType
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Qp_SuccorBill_PType',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.Qp_SuccorBill_PType
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='CostTotal')
BEGIN
	ALTER TABLE Qp_SuccorBill_PType ADD CostTotal NUMERIC(18,4) DEFAULT '0' NULL	
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='InputCostPrice')
BEGIN
	ALTER TABLE Qp_SuccorBill_PType ADD InputCostPrice NUMERIC(18,4) DEFAULT '0' NULL	
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='KTypeId')
BEGIN
	ALTER TABLE Qp_SuccorBill_PType ADD KTypeId VARCHAR(50) DEFAULT '' NULL	
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='CargoSpace')
BEGIN
	ALTER TABLE Qp_SuccorBill_PType ADD CargoSpace VARCHAR(200) DEFAULT '' NULL	
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_SuccorBill_PType]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_SuccorBill_PType
	    ALTER COLUMN Comment varchar(500) 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='HandZeroCost')
BEGIN
	ALTER TABLE Qp_SuccorBill_PType ADD
		HandZeroCost INT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_SuccorBill_PType SET KTypeId = '' WHERE KTypeId IS NULL
GO
UPDATE Qp_SuccorBill_PType SET CargoSpace = '' WHERE CargoSpace IS NULL
GO
UPDATE Qp_SuccorBill_PType SET HandZeroCost = 0 WHERE HandZeroCost IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_PType 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_PType 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_PType 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_PType 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_PType' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_PType 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SuccorBill_RepairItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_SuccorBill_RepairItems](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[RepairItemsTypeID] VARCHAR(50) NULL DEFAULT(''),		
		[StandardManHour] NUMERIC(18,4) NULL DEFAULT(0),
		[CheckHour] NUMERIC(18,4) NULL DEFAULT(0),
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[CostTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[ETypeID] VARCHAR(50) NULL DEFAULT(''),		
		[Comment] VARCHAR(250) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_SuccorBill_RepairItems]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_SuccorBill_RepairItems
	    ALTER COLUMN Comment varchar(500) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_RepairItems' AND a.Name='StandardManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_RepairItems 
	ALTER COLUMN StandardManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_RepairItems' AND a.Name='CheckHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_RepairItems 
	ALTER COLUMN CheckHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_RepairItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_RepairItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_RepairItems' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_RepairItems 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SuccorBill_SuccorItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_SuccorBill_SuccorItems](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[SuccorChargeId] INT NULL DEFAULT(0),
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[Comment] VARCHAR(250) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_SuccorBill_SuccorItems]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_SuccorBill_SuccorItems
	    ALTER COLUMN Comment varchar(500) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorBill_SuccorItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorBill_SuccorItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SuccorChargeItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_SuccorChargeItems](		
		[SuccorChargeId] INT IDENTITY(1,1) NOT NULL,
		[FullName] VARCHAR(200) NULL,
		[Total] NUMERIC(18,4) NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_SuccorChargeItems]') and name='PYCode')
alter table Qp_SuccorChargeItems add PYCode varchar(100) null
go
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
update Qp_SuccorChargeItems set PYCode='' where PYCode is null
go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_SuccorChargeItems' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_SuccorChargeItems 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SuccorType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_SuccorType](		
		[SuccorId] INT IDENTITY(1,1) NOT NULL,
		[FullName] VARCHAR(200) NULL
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[Qp_SuccorType]') and name=N'PYCode')
alter table Qp_SuccorType add PYCode varchar(100) null
go
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
update Qp_SuccorType set PYCode='' where PYCode is null
go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ThreePacketsBill_PType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_ThreePacketsBill_PType](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[PTypeID] VARCHAR(50) NULL DEFAULT(''),
		[Qty] NUMERIC(18,4) NULL DEFAULT(0),		
		[CostTotal] NUMERIC(18,4) NULL DEFAULT(0),		
		[TaxPrice] NUMERIC(18,4) NULL DEFAULT(0),
		[TaxTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[InsuranceTotal] NUMERIC(18,4) NULL DEFAULT(0),		
		[Comment] VARCHAR(250) NULL DEFAULT(''),
		[IsUnit2]  INT NULL DEFAULT(0),		
		[QuickOrReceptionBillId] INT NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_PType' AND a.Name='Virtual'
)
BEGIN
	ALTER TABLE Qp_ThreePacketsBill_PType ADD Virtual INT DEFAULT '0' NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_PType' AND a.Name='QuickOrReceptionBillId'
)
BEGIN
	ALTER TABLE Qp_ThreePacketsBill_PType ADD QuickOrReceptionBillId INT DEFAULT '0' NULL	
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_ThreePacketsBill_PType]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_ThreePacketsBill_PType
	    ALTER COLUMN Comment varchar(500) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_ThreePacketsBill_PType SET Virtual = 0 WHERE Virtual IS NULL
GO
UPDATE Qp_ThreePacketsBill_PType SET QuickOrReceptionBillId = 0 WHERE QuickOrReceptionBillId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_PType' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_PType 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_PType' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_PType 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_PType' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_PType 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_PType' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_PType 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_PType' AND a.Name='InsuranceTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_PType 
	ALTER COLUMN InsuranceTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ThreePacketsBill_RepairItems]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_ThreePacketsBill_RepairItems](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[RepairItemsTypeID] VARCHAR(50) NULL DEFAULT(''),
		[StandardManHour] NUMERIC(18,4) NULL DEFAULT(0),
		[RepairTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[InsuranceTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[CostTotal] NUMERIC(18,4) NULL DEFAULT(0),
		[Comment] VARCHAR(500) NULL DEFAULT(''),
		[QuickOrReceptionBillId] INT NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_RepairItems' AND a.Name='Virtual'
)
BEGIN
	ALTER TABLE Qp_ThreePacketsBill_RepairItems ADD Virtual INT DEFAULT '0' NULL	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_RepairItems' AND a.Name='QuickOrReceptionBillId'
)
BEGIN
	ALTER TABLE Qp_ThreePacketsBill_RepairItems ADD QuickOrReceptionBillId INT DEFAULT '0' NULL	
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_ThreePacketsBill_RepairItems]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_ThreePacketsBill_RepairItems
	    ALTER COLUMN Comment varchar(500) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_ThreePacketsBill_RepairItems SET Virtual = 0 WHERE Virtual IS NULL
GO
UPDATE Qp_ThreePacketsBill_RepairItems SET QuickOrReceptionBillId = 0 WHERE QuickOrReceptionBillId IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_RepairItems' AND a.Name='StandardManHour' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_RepairItems 
	ALTER COLUMN StandardManHour NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_RepairItems' AND a.Name='RepairTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_RepairItems 
	ALTER COLUMN RepairTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_RepairItems' AND a.Name='InsuranceTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_RepairItems 
	ALTER COLUMN InsuranceTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_ThreePacketsBill_RepairItems' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_ThreePacketsBill_RepairItems 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--运输方式基本信息表
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Transport]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[QP_Transport](
		[ID] [int] IDENTITY (1, 1) NOT NULL ,								--自增长ID 
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,		--运输方式名称
		[UserCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,			--运输方式编号
		[PYCode]   [varchar](200) NULL,										--运输方式拼音码
		[BTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,		--往来单位ID
		[Comment] [varchar] (1000) COLLATE Chinese_PRC_CI_AS NULL ,			--备注
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_WashCarBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_WashCarBill] (
		[BillNumberId] [numeric](10, 0) NOT NULL ,
		[etypeid] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL 
	) ON [PRIMARY]
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_WorkGroup]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_WorkGroup] (
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[UserCode] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[FullName] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL 
	) ON [PRIMARY]
end	
GO


------------------------------表修改区域开始 --------------------------------
if not exists (select * from dbo.syscolumns where id = object_id(N'[dbo].[QP_WorkGroup]') and name=N'PYCode')
alter table QP_WorkGroup add PYCode varchar(100) null
go
------------------------------表修改区域结束---------------------------------
update QP_WorkGroup set PYCode='' where PYCode is null
go





------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_WorkGroup_Person]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QP_WorkGroup_Person] (
		[WorkGroupID] [int] NOT NULL ,
		[ETypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL 
	) ON [PRIMARY]
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_YearCheck]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qp_YearCheck](
		[YearCheckId] NUMERIC(10,0) IDENTITY(1,1) NOT NULL,				
		[RaTypeID] VARCHAR(50) NULL DEFAULT(''),
		[STypeID] VARCHAR(50) NULL DEFAULT(''),
		[YearCheckNo] VARCHAR(250) NULL DEFAULT(''),
		[YearCheckTotal] NUMERIC(18,4) NULL DEFAULT(0),		
		[YearCheckDate] DATETIME NULL,
		[ReachDate] DATETIME NULL,				
		[Comment] VARCHAR(250) NULL DEFAULT('')
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Qp_YearCheck' AND a.Name='Mobile')
BEGIN
	ALTER TABLE Qp_YearCheck ADD 
		Mobile VARCHAR(200) NULL DEFAULT('')
END
GO
if not exists (select * from syscolumns where id = object_id(N'[dbo].[Qp_YearCheck]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE Qp_YearCheck
	    ALTER COLUMN Comment varchar(500) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE Qp_YearCheck SET Mobile = '' WHERE Mobile IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Qp_YearCheck' AND a.Name='YearCheckTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Qp_YearCheck 
	ALTER COLUMN YearCheckTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QuotePriceBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[QuotePriceBill] (
		[BillNumberID] [int] NOT NULL ,
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[PTypeID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[Qty] [numeric](18, 4) Default(0) NOT NULL ,
		[IsUnit2] [int] Default(0) NOT NULL ,
		[Discount] [numeric](18, 4) Default(1) NOT NULL ,
		[Price] [numeric](22, 8) Default(0) NOT NULL ,
		[SaleTotal] [numeric](18, 4) Default(0) NOT NULL ,
		[DiscountPrice] [numeric](22, 8) Default(0) NOT NULL ,
		[Total] [numeric](18, 4) Default(0) NOT NULL ,
		[Tax] [numeric](5, 2) Default(0) NOT NULL ,
		[TaxPrice] [numeric](22, 8) Default(0) NOT NULL ,
		[TaxTotal] [numeric](18, 4) Default(0) NOT NULL ,
		[Comment] [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL Default(''),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		CurRate             numeric(22,10)      NULL Default(1),
	   TaxMoney             numeric(22,10)    NULL Default(0),
	   NSalePrice           numeric(22,10)      NULL Default(0),
	   NSaleTotal           numeric(22,10)      NULL Default(0),
	   NDiscountPrice       numeric(22,10)      NULL Default(0),
	   NTotal               numeric(22,10)      NULL Default(0),
	   NTaxPrice            numeric(22,10)      NULL Default(0),
	   NTaxTotal            numeric(22,10)      NULL Default(0),
	   NTaxMoney            numeric(22,10)      NULL Default(0),
	   UnitID               int                NULL Default(0),
	   NUnitID              int                NULL Default(0),
	   NQty                 numeric(22,10)     NULL Default(0),
	   UnitRate             numeric(22,10)     NULL Default(0),
	   NUnitMsg             varchar(50)        null,
	   MUnitID              int                NULL Default(0),
	   MQty                 numeric(22,10)     NULL Default(0),
	   MUnitRate            numeric(22,10)     NULL Default(1),
	   MUnitMsg             varchar(50)        null,
	   MSalePrice           numeric(22,10)     NULL Default(0),
	   MDiscountPrice       numeric(22,10)     NULL Default(0),
	   MTaxPrice            numeric(22,10)     NULL Default(0),
	   CurMSalePrice        numeric(22,10)     NULL Default(0),
	   CurMDiscountPrice    numeric(22,10)     NULL Default(0),
	   CurMTaxPrice         numeric(22,10)     NULL Default(0),
	    ItemID               bigint               null,
	   IsCombined           int                  NULL
	   ,ExpectedInterest   [numeric](18, 10)
	   ,ExpectedInterestRate   [numeric](18, 4)--预期毛利率
	   ,ShowOrder INT DEFAULT(0)
	   ,UseQty NUMERIC(24,10) NULL DEFAULT(0),--已引用数量
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]
end
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'QuotePriceBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.QuotePriceBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'QuotePriceBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.QuotePriceBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE QuotePriceBill ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE QuotePriceBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'QuotePriceBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.QuotePriceBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.QuotePriceBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='CurRate'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD CurRate   numeric(22,10)  NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD UnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NUnitID INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NQty   numeric(22,10)    NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD MUnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD MQty   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD MSalePrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD MDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD MTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD CurMSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD CurMDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD CurMTaxPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='ExpectedInterest'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD ExpectedInterest    [numeric](18, 10)  --预期毛利
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='ExpectedInterestRate'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD ExpectedInterestRate   [numeric](18, 4)  NULL Default(0)--预期毛利率
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='UseQty'
)
BEGIN
		ALTER TABLE QuotePriceBill ADD UseQty   [numeric](24, 10) NULL DEFAULT 0 WITH VALUES--已引用数量
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='quotepricebill' AND a.Name='IfBargainOn' 
)
BEGIN
	ALTER TABLE quotepricebill ADD IfBargainOn INT NOT NULL DEFAULT(0)            ---成交状态
END
GO
--UPDATE quotepricebill SET IfBargainON=0 WHERE IfBargainON IS NULL       

--GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='QuotePriceBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QUOTEPRICEBILL') AND name = 'CIX_QUOTEPRICEBILL_BillNumberID')
--DROP INDEX CIX_QUOTEPRICEBILL_BillNumberID ON QUOTEPRICEBILL 
CREATE CLUSTERED INDEX CIX_QUOTEPRICEBILL_BillNumberID ON QUOTEPRICEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QUOTEPRICEBILL') AND name = 'NCIX_QUOTEPRICEBILL_Ptypeid')
--DROP INDEX NCIX_QUOTEPRICEBILL_Ptypeid ON QUOTEPRICEBILL 
CREATE NONCLUSTERED INDEX NCIX_QUOTEPRICEBILL_Ptypeid ON QUOTEPRICEBILL(Ptypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QUOTEPRICEBILL') AND name = 'NCIX_QUOTEPRICEBILL_Discount')
DROP INDEX NCIX_QUOTEPRICEBILL_Discount ON QUOTEPRICEBILL 
                          
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                    
CREATE NONCLUSTERED INDEX NCIX_QUOTEPRICEBILL_Discount ON QUOTEPRICEBILL(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QUOTEPRICEBILL') AND name = 'NCIX_QUOTEPRICEBILL_Price')
DROP INDEX NCIX_QUOTEPRICEBILL_Price ON QUOTEPRICEBILL 

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                
CREATE NONCLUSTERED INDEX NCIX_QUOTEPRICEBILL_Price ON QUOTEPRICEBILL(Price) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QUOTEPRICEBILL') AND name = 'NCIX_QUOTEPRICEBILL_Tax')
DROP INDEX NCIX_QUOTEPRICEBILL_Tax ON QUOTEPRICEBILL 
                            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_QUOTEPRICEBILL_Tax ON QUOTEPRICEBILL(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('QUOTEPRICEBILL') AND name = 'NCIX_QUOTEPRICEBILL_Stypeid')
--DROP INDEX NCIX_QUOTEPRICEBILL_Stypeid ON QUOTEPRICEBILL 
CREATE NONCLUSTERED INDEX NCIX_QUOTEPRICEBILL_Stypeid ON QUOTEPRICEBILL(Stypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                          
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='CurRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN CurRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='ExpectedInterest' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN ExpectedInterest NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='QuotePriceBill' AND a.Name='ExpectedInterestRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE QuotePriceBill 
	ALTER COLUMN ExpectedInterestRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ReceiptBill]') AND type in (N'U'))
BEGIN


CREATE TABLE [dbo].[ReceiptBill](
	[BillNumberID] [numeric](10, 0) NOT NULL,
	[BillType] [numeric](4, 0) NOT NULL,
	[MainBillNumberID] [numeric](10, 0) NULL,
	[KTypeID] [varchar](100) NULL,
	[PTypeID] [varchar](100) NULL,
	[Qty] [numeric](18, 4) NULL,
	[Price] [numeric](18, 4) NULL,
	[Total] [numeric](18, 4) NULL,
	[Tax] [numeric](5, 2) NULL,
	[TaxPrice] [numeric](18, 4) NULL,
	[TaxTotal] [numeric](18, 4) NULL,
	[Comment] [varchar](255) NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Stypeid] [varchar](50) NULL,
	[discount] [numeric](18, 4) NULL,
	[BeforePrice] [numeric](18, 4) NULL,
	[BeforeTotal] [numeric](18, 4) NULL,
	[RecordedItemId] [int] NOT NULL,
	[Nprice] [numeric](22, 10) NULL,
	[NTotal] [numeric](22, 10) NULL,
	[NTaxPrice] [numeric](22, 10) NULL,
	[NTaxTotal] [numeric](22, 10) NULL,
	[NTaxMoney] [numeric](22, 10) NULL,
	[CargoID] [int] NULL,
	[UnitID] [int] NULL,
	[NUnitID] [int] NULL,
	[NQty] [numeric](22, 10) NULL,
	[UnitRate] [numeric](22, 10) NULL,
	[NUnitMsg] [varchar](50) NULL,
	[MUnitID] [int] NULL,
	[MQty] [numeric](22, 10) NULL,
	[MUnitRate] [numeric](22, 10) NULL,
	[MUnitMsg] [varchar](50) NULL,
	[MPrice] [numeric](22, 10) NULL,
	[MTaxPrice] [numeric](22, 10) NULL,
	[CurMPrice] [numeric](22, 10) NULL,
	[CurMTaxPrice] [numeric](22, 10) NULL,
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[Nbeforeprice] [numeric](22, 10) NULL,
	[NBeforeTotal] [numeric](22, 10) NULL,
	[goodsnumber] [varchar](100) NULL,
	[saleprice] [numeric](22, 10) NULL,
	[saletotal] [numeric](22, 10) NULL,
	[nsaleprice] [numeric](22, 10) NULL,
	[nsaletotal] [numeric](22, 10) NULL,
	[curmsaleprice] [numeric](22, 10) NULL,
	[curmsaletotal] [numeric](22, 10) NULL,
	[taxmoney] [numeric](22, 10) NULL,
	[CompleteQty] [numeric](22, 10) NULL,
	[CompleteTotal] [numeric](22, 10) NULL,
	[NCompleteTotal] [numeric](22, 10) NULL,
	[IsGift] [int] NULL,
	[TeamNo] [int] NULL,
	[TeamNO1] [int] NULL,
	[InvoiceCostTotal] [numeric](22, 10) NULL,
	[MainBillType]	INT NULL DEFAULT(-1),
	[InvoiceCostPrice] [numeric](22, 10) NULL,
	[ProduceDate] [varchar](50) DEFAULT (''),
	[ValidDate] [varchar](50) DEFAULT (''),
	[Serial] VARCHAR(MAX)  DEFAULT (''),
	ShowOrder INT DEFAULT(0)
	
) ON [PRIMARY]

	
ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_BillNumberID]  DEFAULT ((0)) FOR [BillNumberID]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_MainBillNumberID]  DEFAULT ((0)) FOR [MainBillNumberID]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_KTypeID]  DEFAULT ('') FOR [KTypeID]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_PTypeID]  DEFAULT ('') FOR [PTypeID]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_Qty]  DEFAULT ((0)) FOR [Qty]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_Price]  DEFAULT ((0)) FOR [Price]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_Total]  DEFAULT ((0)) FOR [Total]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_Tax]  DEFAULT ((0)) FOR [Tax]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_TaxPrice]  DEFAULT ((0)) FOR [TaxPrice]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_Comment]  DEFAULT ('') FOR [Comment]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ('') FOR [Stypeid]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((1)) FOR [discount]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [BeforePrice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [BeforeTotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [RecordedItemId]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [Nprice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [NTotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [NTaxPrice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [NTaxTotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [NTaxMoney]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [CargoID]

ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [NQty]

ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [UnitRate]



ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [MUnitID]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [MQty]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [MUnitRate]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [MPrice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [MTaxPrice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [CurMPrice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [CurMTaxPrice]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_ItemID]  DEFAULT ((0)) FOR [ItemID]


ALTER TABLE [dbo].[ReceiptBill] ADD  CONSTRAINT [DF_ReceiptBill_IsCombined]  DEFAULT ((0)) FOR [IsCombined]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [Nbeforeprice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [NBeforeTotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [saleprice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [saletotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [nsaleprice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [nsaletotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [curmsaleprice]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [curmsaletotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [taxmoney]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [CompleteQty]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [CompleteTotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [NCompleteTotal]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [IsGift]


ALTER TABLE [dbo].[ReceiptBill] ADD  DEFAULT ((0)) FOR [InvoiceCostTotal]



END

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'ReceiptBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.ReceiptBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.ReceiptBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO


------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='BeforePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN BeforePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='BeforeTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN BeforeTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='Nprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN Nprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='MPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN MPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='CurMPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN CurMPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='Nbeforeprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN Nbeforeprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='NBeforeTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN NBeforeTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='saleprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN saleprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='saletotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN saletotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='nsaleprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN nsaleprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='nsaletotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN nsaletotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='curmsaleprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN curmsaleprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='curmsaletotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN curmsaletotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='taxmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN taxmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='CompleteQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN CompleteQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='InvoiceCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN InvoiceCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='InvoiceCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBill 
	ALTER COLUMN InvoiceCostPrice NUMERIC(24,10)
    END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE ReceiptBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO 
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ReceiptBill') AND name = 'CIX_ReceiptBill_BillNumberID')
CREATE NONCLUSTERED INDEX CIX_ReceiptBill_BillNumberID ON ReceiptBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ReceiptBill') AND name = 'CIX_ReceiptBill_PTypeId')
CREATE NONCLUSTERED INDEX CIX_ReceiptBill_PTypeId ON ReceiptBill(PTypeId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ReceiptBill') AND name = 'CIX_ReceiptBill_KTypeId')
CREATE NONCLUSTERED INDEX CIX_ReceiptBill_KTypeId ON ReceiptBill(KTypeID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ReceiptBill') AND name = 'CIX_ReceiptBill_STypeId')
CREATE NONCLUSTERED INDEX CIX_ReceiptBill_STypeId ON ReceiptBill(STypeId)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ReceiptBill') AND name = 'CIX_ReceiptBill_Id')
CREATE NONCLUSTERED INDEX CIX_ReceiptBill_Id ON ReceiptBill(Id)
------------------------------------------创建索引区域开始-----------------------------------------------
GO 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ReceiptBillIndex]') AND type in (N'U'))
BEGIN

CREATE TABLE [dbo].[ReceiptBillIndex](
	[BillNumberID] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
	[BillDate] [datetime] NOT NULL,
	[BillCode] [varchar](200) NOT NULL,
	[BillType] [numeric](4, 0) NOT NULL,
	[FaPiaoType] [char](1) NULL,
	[FaPiaoCode] [varchar](256) NULL,
	[Comment] [varchar](256) NULL,
	[Explain] [varchar](256) NULL,
	[BTypeID] [varchar](100) NULL,
	[ETypeID] [varchar](100) NULL,
	[DTypeID] [varchar](100) NULL,
	[checke] [varchar](100) NULL,
	[Assessor] [varchar](50) NULL,
	[Tax] [numeric](5, 2) NULL,
	[TotalQty] [numeric](18, 4) NULL,
	[TotalMoney] [numeric](18, 4) NULL,
	[TaxTotalMoney] [numeric](18, 4) NULL,
	[Stypeid] [varchar](50) NULL,
	[OtherTotal] [numeric](18, 4) NULL,
	[ifYearBill] [int] NULL,
	[IsIni] [bit] NULL,
	[CID] [int] NULL,
	[Rate] [numeric](22, 10) NULL,
	[NTotalMoney] [numeric](22, 10) NULL,
	[NTaxTotalMoney] [numeric](22, 10) NULL,
	[DealBTypeID] [varchar](50) NULL,
	[TaskType] [tinyint] NULL,
	[AlertDay] [int] NULL,
	[RedWord] [int]  NOT  NULL,
	[ifcheck] [char](1) NOT null,
	IfStopMoney int NOT null,
	CompleteTotal  [numeric](22, 10) NULL,
	NCompleteTotal  [numeric](22, 10) NULL,
	Draft [bit] NOT NULL DEFAULT(0),
	JSState	CHAR(1) DEFAULT('0'),
	JSStyle CHAR(1) DEFAULT('0'),
	[Poster] [varchar](100)  NULL,
	[LastUpdateTime] DateTime NULL   DEFAULT GETDATE(),
	[checkTime]		DATETIME NULL,
	[Posttime]		DATETIME NULL,
	[UpdateE]		VARCHAR(100) NULL  DEFAULT (''),
	[IfAudit] [char](1) NULL,
	[ATypeID1]	VARCHAR(50) NULL DEFAULT(''),
	[ATypeID2]	VARCHAR(50) NULL DEFAULT(''),
	[Period] [smallint] NULL DEFAULT (0),
	[RedReason] [varchar](500) NULL DEFAULT (''),
	[ATID] INT NULL DEFAULT(0),
	[Reconciliation] CHAR(1) NULL DEFAULT('f'),
	[TeamNo] [int] NULL DEFAULT(0)
) ON [PRIMARY]



	
	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_BillCode]  DEFAULT ('') FOR [BillCode]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_FaPiaoType]  DEFAULT ((1)) FOR [FaPiaoType]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_FaPiaoCode]  DEFAULT ('') FOR [FaPiaoCode]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_Comment]  DEFAULT ('') FOR [Comment]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_Explain]  DEFAULT ('') FOR [Explain]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_BTypeID]  DEFAULT ('') FOR [BTypeID]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_ETypeID]  DEFAULT ('') FOR [ETypeID]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_DTypeID]  DEFAULT ('') FOR [DTypeID]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_Tax]  DEFAULT ((17)) FOR [Tax]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_TotalQty]  DEFAULT ((0)) FOR [TotalQty]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_TotalMoney]  DEFAULT ((0)) FOR [TotalMoney]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_TaxTotalMoney]  DEFAULT ((0)) FOR [TaxTotalMoney]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT ('') FOR [Stypeid]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_OtherTotal]  DEFAULT ((0)) FOR [OtherTotal]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  CONSTRAINT [DF_ReceiptBillIndex_ifYearBill]  DEFAULT ((0)) FOR [ifYearBill]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT ((0)) FOR [IsIni]

	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT ((0)) FOR [CID]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT ((0)) FOR [Rate]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT ((0)) FOR [NTotalMoney]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT ((0)) FOR [NTaxTotalMoney]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT ('') FOR [DealBTypeID]


	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT ((1)) FOR [TaskType]
	
	ALTER TABLE [dbo].[ReceiptBillIndex] ADD   DEFAULT (0) FOR [RedWord]

	ALTER TABLE [dbo].[ReceiptBillIndex] ADD   DEFAULT ('t')  FOR [ifcheck]

	ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT (0) FOR IfStopMoney
    ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT (0) FOR CompleteTotal
    ALTER TABLE [dbo].[ReceiptBillIndex] ADD  DEFAULT (0) FOR NcompleteTotal
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='ATID'
)
BEGIN
	ALTER TABLE ReceiptBillIndex ADD ATID INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE ReceiptBillIndex ADD Reconciliation CHAR(1) NULL DEFAULT('f')
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='TeamNo'
)
BEGIN
	ALTER TABLE ReceiptBillIndex ADD [TeamNo] [int] NULL DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'ReceiptBillIndex',N'U') AND Name='TallyId')
BEGIN
	ALTER TABLE ReceiptBillIndex ADD TallyId VARCHAR(50) NULL DEFAULT('')
END
GO


IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'ReceiptBillIndex',N'U') AND Name='ChargeOffTotal')
BEGIN
	ALTER TABLE ReceiptBillIndex ADD ChargeOffTotal NUMERIC(24,10) DEFAULT 0
END
GO


IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'ReceiptBillIndex',N'U') AND Name='NChargeOffTotal')
BEGIN
	ALTER TABLE ReceiptBillIndex ADD NChargeOffTotal NUMERIC(24,10) DEFAULT 0
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='TotalQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN TotalQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='TaxTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN TaxTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='OtherTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN OtherTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='NTaxTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN NTaxTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReceiptBillIndex' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReceiptBillIndex 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[RecordLastSelectPtype]') AND type in (N'U'))
BEGIN
	CREATE TABLE RecordLastSelectPtype
	(
		TypeId			VARCHAR(50),	--商品ID
		ParId			VARCHAR(50),	--商品父ID
		UserCode		VARCHAR(200),	--商品编码
		FullName		VARCHAR(200),	--商品名称
		OperatorID		VARCHAR(200),	--操作员ID
		SelectedIndex	INT	DEFAULT(0)	--光标所在行索引
	)
END
GO




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--参照计划提成
--2014--04-07  wg
IF NOT EXISTS(SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ReferencePlanCommission]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE ReferencePlanCommission
(
	BillNumberId			NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	BillCode				VARCHAR(200) NOT NULL,   --单据编号
	FullName				VARCHAR(200) NOT NULL DEFAULT(''),   --单据名称
	BillDate				DATETIME NOT NULL,		 --单据日期 
	PlanStart				DATETIME NOT NULL,
	PlanEnd					DATETIME NOT NULL,
	CommissionStandard		INT NOT NULL,			 --提成基准  1=销售额 2=价税合计
	Checke					VARCHAR(50) NOT NULL,				--制单人
	Checker					VARCHAR(50) NOT NULL DEFAULT(''),	--审核人
	CheckeTime				DATETIME NOT NULL,		--制单时间
	CheckerTime				DATETIME NULL,		    --审核时间
	Comment					VARCHAR(256) NOT NULL DEFAULT(''),	--摘要
	BillState				INT NOT NULL,						--单据状态  1=未审核  2=审核  3=禁用
	UseState				INT NOT NULL DEFAULT(0),			--使用状态  1=未引用  2=已引用  --------3=部分完成 4=全部完成
	IsStop					INT NOT NULL DEFAULT(0)	,			--是否禁用  0=正常  1/2当禁用时写入单据状态 启用时写到单据状态列 起保存禁用时的状态
    SalesFlag				INT NULL,                                   --是否是促销商品 1=是促销 0=不是 
	BelowCostFlag       INT NULL										--是否低于成本价  1=低于成本价 0=不低于成本价
)

END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[ReferencePlanCommission]') AND name = 'FullName' )
BEGIN
ALTER TABLE ReferencePlanCommission ADD FullName VARCHAR(200) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[ReferencePlanCommission]') AND name = 'PlanStart' )
BEGIN
ALTER TABLE ReferencePlanCommission ADD PlanStart DATETIME NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[ReferencePlanCommission]') AND name = 'PlanEnd' )
BEGIN
ALTER TABLE ReferencePlanCommission ADD PlanEnd DATETIME NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[ReferencePlanCommission]') AND name = 'SalePlanID' )
BEGIN
ALTER TABLE ReferencePlanCommission ADD SalePlanID NUMERIC(18,0) DEFAULT(-1)  --关联计划ID
END
GO

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[ReferencePlanCommission]') AND name = 'SalesFlag' )
BEGIN
ALTER TABLE ReferencePlanCommission ADD SalesFlag  INT NULL
END

IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[ReferencePlanCommission]') AND name = 'BelowCostFlag' )
BEGIN
ALTER TABLE ReferencePlanCommission ADD BelowCostFlag INT NULL
END

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--参照计划提成--职员设置
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ReferencePlanCommissionEtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE ReferencePlanCommissionEtype
(
	BillNumberId			NUMERIC(18,0) NOT NULL,
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	EtypeID					VARCHAR(50) NOT NULL	--业务员
)

END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--参照计划提成--职员--计划完成比例
--2014--04-07  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ReferencePlanCommissionPlan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE ReferencePlanCommissionPlan
(
	BillNumberId			NUMERIC(18,0) NOT NULL,
	ID						NUMERIC(18,0) IDENTITY(1,1),--自增长ID
	EtypeID					VARCHAR(50) NOT NULL,	 --业务员
	MinRegion				NUMERIC(18,10) NOT NULL, --下限
	MaxRegion				NUMERIC(18,10) NOT NULL, --上限
	Proportion				NUMERIC(18,10)  NULL, --提成率
	IsCalculation			INT NOT NULL,			 --是否计算超出部分  0=不计算 1=计算
	Percentage			NUMERIC(24,10) NULL
)

END
GO


alter table ReferencePlanCommissionPlan alter column MinRegion  NUMERIC(18,4)
alter table ReferencePlanCommissionPlan alter column MaxRegion  NUMERIC(18,4)
alter table ReferencePlanCommissionPlan alter column Proportion  NUMERIC(18,4)
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReferencePlanCommissionPlan' AND a.Name='MinRegion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReferencePlanCommissionPlan 
	ALTER COLUMN MinRegion NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReferencePlanCommissionPlan' AND a.Name='MaxRegion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReferencePlanCommissionPlan 
	ALTER COLUMN MaxRegion NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReferencePlanCommissionPlan' AND a.Name='Proportion' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ReferencePlanCommissionPlan 
	ALTER COLUMN Proportion NUMERIC(24,10)
    END
   
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ReferencePlanCommissionPlan' AND a.Name='Percentage' 
    )
    BEGIN
	alter table ReferencePlanCommissionPlan add  Percentage  NUMERIC(24,10)
    END 
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if NOT exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RefIndustry]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[RefIndustry] (
		[ID] [int] IDENTITY (1, 1) NOT NULL ,
		[Name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
		[IsDeleted] [bit] NULL 
	) ON [PRIMARY]
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM RefIndustry)
BEGIN
	SET IDENTITY_INSERT refindustry ON
	insert into refindustry(id,name,isdeleted) values (27,'服装、鞋业',0)
	insert into refindustry(id,name,isdeleted) values (28,'皮具、箱包',0)
	insert into refindustry(id,name,isdeleted) values (29,'办公用品、图书、音像',0)
	insert into refindustry(id,name,isdeleted) values (30,'IT业、数码、通讯',0)
	insert into refindustry(id,name,isdeleted) values (31,'珠宝、玉器、饰品',0)
	insert into refindustry(id,name,isdeleted) values (32,'食品、饮料、烟酒',0)
	insert into refindustry(id,name,isdeleted) values (33,'超市、百货、商场',0)
	insert into refindustry(id,name,isdeleted) values (34,'农资、农业、养殖',0)
	insert into refindustry(id,name,isdeleted) values (35,'餐饮、娱乐、物业',0)
	insert into refindustry(id,name,isdeleted) values (36,'美容、美发、化妆品',0)
	insert into refindustry(id,name,isdeleted) values (37,'布匹、纺织、床上用品',0)
	insert into refindustry(id,name,isdeleted) values (38,'五金建材、灯饰、家装、家具',0)
	insert into refindustry(id,name,isdeleted) values (39,'电子、家电、机电、设备',0)
	insert into refindustry(id,name,isdeleted) values (40,'母婴、文体、户外用品',0)
	insert into refindustry(id,name,isdeleted) values (41,'医药、保健、诊所、医疗器械',0)
	insert into refindustry(id,name,isdeleted) values (42,'汽车销售、汽车美容、汽配、汽修、摩配',0)
	insert into refindustry(id,name,isdeleted) values (43,'事业单位(国营性质企业）',0)
	insert into refindustry(id,name,isdeleted) values (44,'冶金、矿业、化工',0)
	insert into refindustry(id,name,isdeleted) values (45,'其它',0)
	SET IDENTITY_INSERT refindustry OFF
END



/****** 对象:  Table [dbo].[RepairDeal]    脚本日期: 05/05/2010 14:48:59 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[RepairDeal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[RepairDeal](
		[BillNumberID] [numeric](18, 0) NOT NULL,
		[EngageBillID] [numeric](18, 0) NULL,
		[BillDate] [datetime] NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[BillType] [int] NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfCheck] [char](2) COLLATE Chinese_PRC_CI_AS NULL,
		[Checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[RedWord] [int] NULL,
		[Draft] [bit] NULL,
		[Stat] [int] NULL,
		[Fault] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL,
		[Method] [int] NULL,
		[KTypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KTypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[MoneyChange] [numeric](18, 4) NULL,
		[MoneyRepair] [numeric](18, 4) NULL,
		[TotalMoney] [numeric](18, 4) NULL,
		[TotalInMoney] [numeric](18, 4) NULL,
		[BTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ATypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Brief] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[NotFree] [bit] NULL,
		[FreeMemo] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PayDate] [datetime] NULL,
		[IfPay] [bit] NULL,
		[IDCard] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RepairDeal]') AND name = N'PK_RepairDeal')
ALTER TABLE [dbo].[RepairDeal] DROP CONSTRAINT [PK_RepairDeal]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('REPAIRDEAL') AND name = 'CIX_REPAIRDEAL_BillNumberID')
--DROP INDEX CIX_REPAIRDEAL_BillNumberID ON REPAIRDEAL 
CREATE CLUSTERED INDEX CIX_REPAIRDEAL_BillNumberID ON REPAIRDEAL(BillNumberID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDeal' AND a.Name='MoneyChange' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDeal 
	ALTER COLUMN MoneyChange NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDeal' AND a.Name='MoneyRepair' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDeal 
	ALTER COLUMN MoneyRepair NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDeal' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDeal 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDeal' AND a.Name='TotalInMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDeal 
	ALTER COLUMN TotalInMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[RepairDealDetail]    脚本日期: 05/05/2010 14:49:00 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[RepairDealDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[RepairDealDetail](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[InOrOut] [varchar](1) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[discount] [numeric](18, 4) NULL,
		[DiscountPrice] [numeric](18, 4) NULL,
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_RepairDealDetail_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsno] [numeric](18, 4) NULL,
		[total] [numeric](18, 4) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_RepairDealDetail_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_RepairDealDetail_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_RepairDealDetail_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_RepairDealDetail_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_RepairDealDetail_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_RepairDealDetail_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_RepairDealDetail_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_RepairDealDetail_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_RepairDealDetail_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_RepairDealDetail_HandZeroCost]  DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	ALTER TABLE RepairDealDetail ALTER COLUMN Serial VARCHAR(MAX)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='goodsno' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN goodsno NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RepairDealDetail' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RepairDealDetail 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[RepairEngage]    脚本日期: 05/05/2010 14:49:01 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[RepairEngage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[RepairEngage](
		[BillNumberID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BillType] [int] NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Serial] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfCheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[Checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[RedWord] [int] NULL,
		[Draft] [bit] NULL,
		[Stat] [int] NULL,
		[ETypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[RepairDate] [datetime] NULL,
		[ETypeName1] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[Tel] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[BuyDate] [datetime] NULL,
		[SaleBillID] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[SaleBTypeName] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[Buyer] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Address] [varchar](66) COLLATE Chinese_PRC_CI_AS NULL,
		[Brief] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Config] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL,
		[RepairType] [int] NULL,
		[Attach] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL,
		[Fault] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](8000) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Reports]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [Reports](
		[reportId] INT IDENTITY(1,1)
		,[code] VARCHAR(50) PRIMARY KEY
		,[name] NVARCHAR(500) NOT NULL
		,[path] VARCHAR(1000) NOT NULL DEFAULT('')
		,[serverdbId] INT NOT NULL DEFAULT(0)
	)
	
	
	--初始化数据
INSERT INTO Reports (code,name) VALUES
('B02001','商品采购统计')
,('B02002','供货商采购统计')
,('B02003','部门采购统计')
,('S01001','销售日报')
,('S01002','销售月报')
,('S01003','销售报表')
,('S01004','商品销售统计')
,('S01005','客户销售统计')
,('S01006','职员销售统计')
,('S01007','仓库销售统计')
,('S01008','地区销售统计')
,('K03001','库存状况表')
,('K03002','虚拟库存状况表')
,('K03003','多级库存状况表')
,('K03004','库存分布表')
,('K03005','货位分布表')
,('K03006','进销存汇总表')
,('K03007','出入库汇总表')
,('K03008','库存商品流量统计分析')
,('K03009','库存积压统计')
,('K03010','商品自由项查询表')
,('K03011','库龄分析')
,('K03012','库龄分布区间表')
,('K03013','商品批次跟踪')
,('K03014','商品近效期查询')
,('K03015','商品保质期查询')
,('C04001','职员往来查询')
,('C04002','制单人收款统计')
,('C04003','回款分析')
,('C04004','账龄分析')
,('C04005','单据结算分析')
,('C04006','商品收款结算')
,('C04007','商品付款结算')
,('C04008','销售对账查询')
,('C04009','采购对账查询')
,('F05001','收入报表')
,('F05002','费用支出')
,('F05003','现金银行查询')
,('F05004','职员创利报表')
,('F05005','客户业务分析')
,('B09001','业务草稿')
,('B09002','经营历程')
,('B09003','经营日报')
,('B09004','单据统计')
END

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[RequestBill]    脚本日期: 05/05/2010 14:46:51 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[RequestBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[RequestBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_DiscountPrice]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_total]  DEFAULT (0),
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_TaxTotal]  DEFAULT (0),
		[comment] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[FeedBack] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL DEFAULT(''),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_RequestBill_Tax]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[RequestDate] [datetime] NULL,
		[OrderDate]	[datetime] NULL,
		[Btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT(''),
		[State] [tinyint] NULL DEFAULT(0),
		[Etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT(''),
		[Btypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT(''),
		[ComparePrice] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_ComparePrice]  DEFAULT (0),
		[CompareDiscount] [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_Comparediscount]  DEFAULT (1),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		NCompleteTotal       numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
	    ItemID               bigint               null,
	   IsCombined           int                  NULL
	   ,ShowOrder INT DEFAULT(0)
	  ,PriceSource VARCHAR(200) 
	) ON [PRIMARY] 

END
GO


------------------------------------------表修改区域开始-------------------------------------------------
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'RequestBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.RequestBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.RequestBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE RequestBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='FeedBack'
)
BEGIN
	ALTER TABLE dbo.RequestBill ADD FeedBack VARCHAR(500) NULL DEFAULT('')

END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='Btypeid2'
)
BEGIN
	ALTER TABLE dbo.RequestBill ADD Btypeid2 VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT('')

END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='ComparePrice'
)
BEGIN
	ALTER TABLE dbo.RequestBill ADD ComparePrice [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_ComparePrice]  DEFAULT (0)

END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CompareTax'
)
BEGIN
	ALTER TABLE dbo.RequestBill ADD CompareTax [numeric](18, 4) NULL CONSTRAINT [DF_RequestBill_CompareTax]  DEFAULT (0)

END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE RequestBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE RequestBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE RequestBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE RequestBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE RequestBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE RequestBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE RequestBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE RequestBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NCompleteTotal'
)
BEGIN
		ALTER TABLE RequestBill ADD NCompleteTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE RequestBill ADD UnitID  INT  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE RequestBill ADD NUnitID INT  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE RequestBill ADD NQty   numeric(22,10)    NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE RequestBill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE RequestBill ADD NUnitMsg   varchar(50)  NULL  
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE RequestBill ADD MUnitID  INT  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE RequestBill ADD MQty   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE RequestBill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE RequestBill ADD MUnitMsg   varchar(50)  NULL  
END
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE RequestBill ADD MSalePrice   numeric(22,10)  NULL Default(0)
END


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE RequestBill ADD MDiscountPrice   numeric(22,10)  NULL Default(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE RequestBill ADD MTaxPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE RequestBill ADD CurMSalePrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE RequestBill ADD CurMDiscountPrice   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE RequestBill ADD CurMTaxPrice   numeric(22,10)  NULL Default(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE RequestBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE RequestBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='RequestQty'
)
BEGIN
	ALTER TABLE dbo.RequestBill ADD RequestQty NUMERIC(24, 10)  NULL Default(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='orderqty'
)
BEGIN
	ALTER TABLE dbo.RequestBill ADD orderqty NUMERIC(24, 10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='sendqty'
)
BEGIN
	ALTER TABLE dbo.RequestBill ADD sendqty NUMERIC(24, 10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='isstop'
)
BEGIN
	ALTER TABLE dbo.RequestBill ADD isstop INT  NULL Default(0)
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CurRate';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='RequestBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('REQUESTBILL') AND name = 'CIX_REQUESTBILL_BillNumberID')
--DROP INDEX CIX_REQUESTBILL_BillNumberID ON REQUESTBILL 
CREATE CLUSTERED INDEX CIX_REQUESTBILL_BillNumberID ON REQUESTBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('REQUESTBILL') AND name = 'NCIX_REQUESTBILL_Ptypeid')
--DROP INDEX NCIX_REQUESTBILL_Ptypeid ON REQUESTBILL 
CREATE NONCLUSTERED INDEX NCIX_REQUESTBILL_Ptypeid ON REQUESTBILL(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='ComparePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN ComparePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CompareDiscount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN CompareDiscount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='CompareTax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN CompareTax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestBill' AND a.Name='RequestQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestBill 
	ALTER COLUMN RequestQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[RequestIndex]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[RequestIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[RequestIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT (''),
		[dtypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0'),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0'),
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalqty] [numeric](18, 4) NULL   DEFAULT (0),
		[totalmoney] [numeric](18, 4) NULL DEFAULT (0),
		[period] [smallint] NULL  DEFAULT (0),
		[explain] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT (''),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[tax] [numeric](5, 2) NULL DEFAULT (17),
		[IsIni]	BIT NULL DEFAULT(0),
		[CID]	INT  NULL DEFAULT(0),
		[Rate] NUMERIC(22,10) DEFAULT(0),
		[NTotalMoney] NUMERIC(22,10) DEFAULT(0),
		[ifYearBill] [int] NULL CONSTRAINT [DF_RequestIndex_ifYearBill]  DEFAULT (0),
		[IfAudit] [char](1) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='dtypeid'
)
BEGIN
	ALTER TABLE RequestIndex ADD dtypeid VARCHAR(50) NULL DEFAULT('0')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='checke'
)
BEGIN
	ALTER TABLE RequestIndex ADD checke VARCHAR(50) NULL
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='tax'
)
BEGIN
	ALTER TABLE RequestIndex ADD tax [numeric](5, 2) NULL   DEFAULT (17)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='ifAudit'
)
BEGIN
	ALTER TABLE RequestIndex ADD [IfAudit] [char](1) COLLATE Chinese_PRC_CI_AS NULL
END

go


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE RequestIndex 
		ADD IsIni BIT NULL DEFAULT(0)
		
	EXEC('UPDATE RequestIndex SET IsIni=0 WHERE IsIni IS NULL')
END

GO

--保存扣率
IF NOT EXISTS(
	SELECT Name FROM Syscolumns WHERE ID=OBJECT_ID('RequestIndex') AND Name='discount'
)
BEGIN
	ALTER TABLE dbo.RequestIndex
	ADD Discount  NUMERIC(22,10) NULL DEFAULT(0)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='RequestDate'
)
BEGIN
	ALTER TABLE dbo.RequestIndex ADD RequestDate DATETIME  NULL 
END
GO

DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'CurRate' UNION ALL SELECT 'CurID'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='RequestIndex';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='CID'
)
BEGIN
	ALTER TABLE RequestIndex ADD CID int  NULL DEFAULT(0)
	
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE RequestIndex ADD Rate NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE RequestIndex ADD NTotalMoney NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='ifYearBill'
)
BEGIN
	ALTER TABLE RequestIndex ADD ifYearBill [int] NULL CONSTRAINT [DF_RequestIndex_ifYearBill]  DEFAULT (0)
END
GO


--请购单增加制单时间
IF NOT EXISTS (SELECT Name FROM SysColumns WHERE id=OBJECT_ID('RequestIndex') AND Name='checkTime')
BEGIN
	ALTER TABLE dbo.RequestIndex
	ADD checkTime DATETIME DEFAULT GETDATE()
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='isstop'
)
BEGIN
	ALTER TABLE dbo.RequestIndex ADD isstop INT  NULL Default(0)
END
GO

UPDATE RequestIndex SET checkTime=BillDate WHERE checkTime IS NULL
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('REQUESTINDEX') AND name = 'CIX_REQUESTINDEX_Billdate')
--DROP INDEX CIX_REQUESTINDEX_Billdate ON REQUESTINDEX 
CREATE CLUSTERED INDEX CIX_REQUESTINDEX_Billdate ON REQUESTINDEX(Billdate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('REQUESTINDEX') AND name = 'NCIX_REQUESTINDEX_BillNumberID')
--DROP INDEX NCIX_REQUESTINDEX_BillNumberID ON REQUESTINDEX 
CREATE NONCLUSTERED INDEX NCIX_REQUESTINDEX_BillNumberID ON REQUESTINDEX(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('REQUESTINDEX') AND name = 'NCIX_REQUESTINDEX_Billtype')
--DROP INDEX NCIX_REQUESTINDEX_Billtype ON REQUESTINDEX 
CREATE NONCLUSTERED INDEX NCIX_REQUESTINDEX_Billtype ON REQUESTINDEX(Billtype) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('REQUESTINDEX') AND name = 'NCIX_REQUESTINDEX_Billcode')
DROP INDEX NCIX_REQUESTINDEX_Billcode ON REQUESTINDEX 
CREATE NONCLUSTERED INDEX NCIX_REQUESTINDEX_Billcode ON REQUESTINDEX(Billcode) 
------------------------------------------创建索引区域结束-----------------------------------------------



--更新历史数据制单时间到单据日期
UPDATE dbo.RequestIndex
SET checkTime=BillDate
WHERE checkTime IS NULL
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestIndex 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestIndex 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestIndex 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestIndex 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RequestIndex' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RequestIndex 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--零售退货单
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[RetailBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[RetailBackBill](
	[BillNumberId] [numeric](10, 0) NOT NULL,
	[PtypeId] [varchar](50) NULL,
	[Qty] [numeric](24, 10) NOT NULL,
	[SalePrice] [numeric](24, 10) NULL,
	[discount] [numeric](24, 10) NULL DEFAULT(1),
	[DiscountPrice] [numeric](24, 10) NULL,
	[costprice] [numeric](24, 10) NULL DEFAULT(0),
	[jobnumber] [varchar](20) NULL,
	[goodsno] [int] NULL,
	[total] [numeric](24, 10) NULL,
	[OutFactoryDate] [datetime] NULL,
	[TaxPrice] [numeric](24, 10) NULL,
	[TaxTotal] [numeric](24, 10) NULL,
	[comment] [varchar](255) NULL,
	--[OrderID] [int] NULL DEFAULT(-1),
	[TeamNo] [int] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TeamNO1] [int] NULL,
	[IsUnit2] [int] NOT NULL DEFAULT(0),
	[Serial] [text] NULL DEFAULT(''),
	[InputCostPrice] [numeric](24, 10) NULL DEFAULT(0),
	[GoodsOrder] [int] NULL DEFAULT(-1),
	[GoodsNumber] [varchar](100) NULL DEFAULT(''),
	[ProduceDate] [varchar](50) NULL DEFAULT(''),
	[ValidDate] [varchar](50) NULL DEFAULT(''),
	[GoodsBTypeID] [varchar](50) NULL DEFAULT(''),
	[GoodsCostPrice] [numeric](24, 10) NULL DEFAULT(0),
	[GoodsCostTotal] [numeric](24, 10) NULL DEFAULT(0),
	[HandZeroCost] [int] NULL DEFAULT(0),
	[SaleTotal] [numeric](24, 10) NULL DEFAULT(0),
	[Tax] [numeric](24, 10) NULL DEFAULT(0),
	[Stypeid] [varchar](50) NULL DEFAULT(''),
	[TaxMoney] [numeric](24, 10) NULL DEFAULT(0),
	[NSalePrice] [numeric](24, 10) NULL DEFAULT(0),
	[NSaleTotal] [numeric](24, 10) NULL DEFAULT(0),
	[NDiscountPrice] [numeric](24, 10) NULL DEFAULT(0),
	[NTotal] [numeric](24, 10) NULL DEFAULT(0),
	[NTaxPrice] [numeric](24, 10) NULL DEFAULT(0),
	[NTaxTotal] [numeric](24, 10) NULL DEFAULT(0),
	[NTaxMoney] [numeric](24, 10) NULL DEFAULT(0),
	[UnitID] [int] NULL DEFAULT(0),
	[NUnitID] [int] NULL DEFAULT(0),
	[NQty] [numeric](24, 10) NULL DEFAULT(0),
	[UnitRate] [numeric](24, 10) NULL DEFAULT(0),
	[NUnitMsg] [varchar](50) NULL,
	[MUnitID] [int] NULL DEFAULT(0),
	[MQty] [numeric](24, 10) NULL DEFAULT(0),
	[MUnitRate] [numeric](24, 10) NULL DEFAULT(1),
	[MUnitMsg] [varchar](50) NULL,
	[MSalePrice] [numeric](24, 10) NULL DEFAULT(0),
	[MDiscountPrice] [numeric](24, 10) NULL DEFAULT(0),
	[MTaxPrice] [numeric](24, 10) NULL DEFAULT(0),
	[CurMSalePrice] [numeric](24, 10) NULL DEFAULT(0),
	[CurMDiscountPrice] [numeric](24, 10) NULL DEFAULT(0),
	[CurMTaxPrice] [numeric](24, 10) NULL DEFAULT(0),
	[CargoID] [int] NULL DEFAULT(0),
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[InvoiceQty] [numeric](24, 10) NULL DEFAULT(0),
	[InvoiceMoney] [numeric](24, 10) NULL DEFAULT(0),
	[NInvoiceMoney] [numeric](24, 10) NULL DEFAULT(0),
	[IsGift] [int] NOT NULL  DEFAULT(0),
	
	[OldBillNumberId]  NUMERIC(18,0) DEFAULT(0),
	[OldId] NUMERIC(18,0) DEFAULT(0),
	[CompleteQty] NUMERIC(24,10) DEFAULT(0),
	[PosId] INT,
	ReferPrice NUMERIC(24,10) NOT NULL DEFAULT(0), --参考成本
	PriceStyle INT NOT NULL DEFAULT(0) --价格类型
	,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
	,ShowOrder INT DEFAULT(0)
	,InflowQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
	,InFactQty NUMERIC(24,10) NULL DEFAULT(0),
	[DraftFlag] [bit] NOT NULL DEFAULT (1),
	[IsIniFlag] [bit] NOT NULL DEFAULT (0),	
	[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),
    PriceSource VARCHAR(200),
	CouponCode	VARCHAR(200) DEFAULT(''),		--优惠券券编码，目前在兑换券的时候会使用
	PromonIds VARCHAR(200)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailBackBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.RetailBackBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailBackBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.RetailBackBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailBackBill',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.RetailBackBill
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'RetailBackBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.RetailBackBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.RetailBackBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'RetailBackBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.RetailBackBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.RetailBackBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

--清楚字段，有默认的情况
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'OrderID'  UNION ALL SELECT 'BackQty';
DECLARE @sql NVARCHAR(max)='';

DECLARE @tn VARCHAR(500)='RetailBackBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')
	
IF @sql<>''
	EXEC(@sql);
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE RetailBackBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='OldBillNumberId'
)
BEGIN
	ALTER TABLE RetailBackBill ADD [OldBillNumberId]  NUMERIC(18,0) DEFAULT(0);
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='OldId'
)
BEGIN
	ALTER TABLE RetailBackBill ADD [OldId] NUMERIC(18,0) DEFAULT(0);
END
go
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'RetailBackBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.RetailBackBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.RetailBackBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='CompleteQty'
)
BEGIN
	ALTER TABLE RetailBackBill ADD [CompleteQty] NUMERIC(18,10) DEFAULT(0);
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='PosId'
)
BEGIN
	ALTER TABLE RetailBackBill ADD PosId int DEFAULT(0);
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='ReferPrice'
)
BEGIN
	ALTER TABLE RetailBackBill ADD ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0) --参考成本
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='PriceStyle'
)
BEGIN
	ALTER TABLE RetailBackBill ADD PriceStyle INT NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='PromoType'
)
BEGIN
	ALTER TABLE RetailBackBill ADD PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
END
GO

--优惠券券编码，目前在兑换券的时候会使用
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailBackBill',N'U') AND Name='CouponCode')
BEGIN
	ALTER TABLE dbo.RetailBackBill
	ADD CouponCode VARCHAR(200) DEFAULT('')
END
GO

IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailBackBill',N'U') AND Name='PromonIds')
BEGIN
	ALTER TABLE dbo.RetailBackBill
	ADD PromonIds VARCHAR(200)
END
GO


--
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('RetailBackBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table RetailBackBill drop constraint '+@dfname);
		
	ALTER TABLE RetailBackBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE RetailBackBill ADD CONSTRAINT DF_RetailBackBill_Serial DEFAULT('') FOR Serial

END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='ETypeID'
)
BEGIN
	ALTER TABLE RetailBackBill ADD ETypeID VARCHAR(50)  NULL DEFAULT('')
	
	EXEC('
	UPDATE RetailBackBill
	SET ETypeID=b.etypeid
	FROM Billindex b
	WHERE RetailBackBill.BillNumberId=b.BillNumberId
	')
	
	
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'GiftFlag' 
DECLARE @sql NVARCHAR(max)='';

DECLARE @tn VARCHAR(500)='RetailBackBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='CompleteQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN CompleteQty NUMERIC(24,10)
    END
                                        
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE RetailBackBill 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
    
 ALTER TABLE RetailBackBill 
	ALTER COLUMN comment varchar(MAX) 
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='RetailBackBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE RetailBackBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                          
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

/****** Object:  Index [NCIX_RetailBackBill_BillNumberID]    Script Date: 09/01/2017 12:57:57 ******/
IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[RetailBackBill]') AND name = N'NCIX_RetailBackBill_BillNumberID')
/****** Object:  Index [NCIX_RetailBackBill_BillNumberID]    Script Date: 09/01/2017 12:58:29 ******/
CREATE NONCLUSTERED INDEX [NCIX_RetailBackBill_BillNumberID] ON [dbo].[RetailBackBill] 
(
	[BillNumberId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO




/****** 对象:  Table [dbo].[retailBill]    脚本日期: 05/05/2010 14:49:02 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[retailBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[retailBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_retailBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL,
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_retailBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsno] [int] NULL,
		[total] [numeric](18, 4) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_retailBill_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_retailBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_retailBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_retailBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_retailBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_RetailBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_RetailBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_RetailBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_RetailBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_RetailBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_RetailBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_RetailBill_HandZeroCost]  DEFAULT (0),
		[BackQTY] [numeric](18, 4) NULL DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_RetailBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_RetailBill_Tax]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), --是否赠品
		PosId INT  NOT NULL DEFAULT(0),
		BeforePromoID INT NULL DEFAULT(0),
		[PriceDetailId] INT NOT NULL DEFAULT(0),
		[PriceRuleId] INT NOT NULL DEFAULT(0),
		[PriceSource] VARCHAR(500) NOT NULL DEFAULT(''),
		--GiftFlag INT NOT NULL DEFAULT(0) -- 0不是，1是赠品
		ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,ShowOrder INT DEFAULT(0)
		,ShareFee  NUMERIC(24,10)
		,OutFactQty NUMERIC(24,10) DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
		,PromonIds VARCHAR(1000) NOT NULL DEFAULT('')
		,CouponCode	VARCHAR(200) DEFAULT('')   --优惠券券编码，目前在兑换券的时候会使用
		,IsPromotion	INT DEFAULT(1)					--使用优惠券后，是否参与促销
		,IsVipPoint INT DEFAULT(1)					--使用优惠券后，是否参与会员积分
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

-- 添加促销方案id字段，记录商品应用的所有促销方案
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='PromonIds')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD PromonIds VARCHAR(1000) NOT NULL DEFAULT('')
END
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.retailBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='ShareFee')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD ShareFee NUMERIC(24,10) NOT NULL DEFAULT(0)
END
go

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.retailBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE retailBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE retailBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE retailBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE retailBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE retailBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE retailBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE retailBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE retailBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE retailBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE retailBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE retailBill ADD UnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE retailBill ADD NUnitID INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE retailBill ADD NQty   numeric(22,10)    NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE retailBill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE retailBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE retailBill ADD MUnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE retailBill ADD MQty   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE retailBill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE retailBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE retailBill ADD MSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE retailBill ADD MDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE retailBill ADD MTaxPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE retailBill ADD CurMSalePrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE retailBill ADD CurMDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE retailBill ADD CurMTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE retailBill ADD CargoID   INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE retailBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE retailBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE retailBill ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE retailBill ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='nInvoiceMoney'
)
BEGIN
		ALTER TABLE retailBill ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO	
-- 是否是赠品
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='IsGift'
)
BEGIN
	ALTER TABLE retailBill ADD IsGift INT NOT NULL DEFAULT(0);
END
go


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='PosId'
)
BEGIN
	ALTER TABLE retailBill ADD PosId INT NOT NULL DEFAULT(0);
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='BeforePromoID'
)
BEGIN
	ALTER TABLE retailBill ADD BeforePromoID INT NULL DEFAULT(0)
END
go


IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='PriceBillIndexId'
)
BEGIN
	exec sp_rename 'retailBill.PriceBillIndexId','PriceDetailId','column';
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='PriceDetailId'
)
BEGIN
	ALTER TABLE retailBill ADD PriceDetailId INT NOT NULL DEFAULT(0)
END
go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='PriceRuleId'
)
BEGIN
	ALTER TABLE retailBill ADD PriceRuleId INT NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='PriceSource'
)
BEGIN
	ALTER TABLE retailBill ADD PriceSource VARCHAR(500) NOT NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='ReferPrice'
)
BEGIN
	ALTER TABLE retailBill ADD ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0) --参考成本
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='PriceStyle'
)
BEGIN
	ALTER TABLE retailBill ADD PriceStyle INT NOT NULL DEFAULT(0)
	
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='PromoType'
)
BEGIN
	ALTER TABLE retailBill ADD PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='CouponCode'
)
BEGIN
	ALTER TABLE retailBill ADD CouponCode VARCHAR(200) DEFAULT('') --优惠券券编码，目前在兑换券的时候会使用
END
GO


--使用优惠券后，是否参与促销
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='IsPromotion')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD IsPromotion INT DEFAULT(1)
END
GO

--使用优惠券后，是否参与会员积分
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'retailBill',N'U') AND Name='IsVipPoint')
BEGIN
	ALTER TABLE dbo.retailBill
	ADD IsVipPoint INT DEFAULT(1)
END
GO

---

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='PriceSource' AND a.length=200
)
BEGIN
	ALTER TABLE retailBill ALTER COLUMN PriceSource VARCHAR(500) NOT NULL --DEFAULT('') 存在约束不能添加
END
go

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('retailBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table retailBill drop constraint '+@dfname);
		
	ALTER TABLE retailBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE retailBill ADD CONSTRAINT DF_retailBill_Serial DEFAULT('') FOR Serial
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='ETypeID'
)
BEGIN
	ALTER TABLE retailBill ADD ETypeID VARCHAR(50)  NULL DEFAULT('')
	
	EXEC('
	UPDATE retailBill
	SET ETypeID=b.etypeid
	FROM Billindex b
	WHERE retailBill.BillNumberId=b.BillNumberId
	')
	
	
END
GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate'
UNION ALL SELECT 'GiftFlag';
DECLARE @sql NVARCHAR(max)='';

DECLARE @tn VARCHAR(500)='retailBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[retailBill]') AND name = N'IX_RetailBill_BillNumberId')
DROP INDEX [dbo].[RetailBill].[IX_RetailBill_BillNumberId]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[retailBill]') AND name = N'IX_RetailBill_PTypeID')
DROP INDEX [dbo].[retailBill].[IX_RetailBill_PTypeID]
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('RETAILBILL') AND name = 'CIX_RETAILBILL_BillNumberID')
--DROP INDEX CIX_RETAILBILL_BillNumberID ON RETAILBILL 
CREATE CLUSTERED INDEX CIX_RETAILBILL_BillNumberID ON RETAILBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('RETAILBILL') AND name = 'NCIX_RETAILBILL_Ptypeid')
--DROP INDEX NCIX_RETAILBILL_Ptypeid ON RETAILBILL 
CREATE NONCLUSTERED INDEX NCIX_RETAILBILL_Ptypeid ON RETAILBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('RETAILBILL') AND name = 'NCIX_RETAILBILL_Orderid')
--DROP INDEX NCIX_RETAILBILL_Orderid ON RETAILBILL 
CREATE NONCLUSTERED INDEX NCIX_RETAILBILL_Orderid ON RETAILBILL(Orderid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('RETAILBILL') AND name = 'NCIX_RETAILBILL_Stypeid')
--DROP INDEX NCIX_RETAILBILL_Stypeid ON RETAILBILL 
CREATE NONCLUSTERED INDEX NCIX_RETAILBILL_Stypeid ON RETAILBILL(Stypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('RETAILBILL') AND name = 'NCIX_RETAILBILL_SalePrice')
DROP INDEX NCIX_RETAILBILL_SalePrice ON RETAILBILL                            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_RETAILBILL_SalePrice ON RETAILBILL(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('RETAILBILL') AND name = 'NCIX_RETAILBILL_Discount')
DROP INDEX NCIX_RETAILBILL_Discount ON RETAILBILL 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                 
CREATE NONCLUSTERED INDEX NCIX_RETAILBILL_Discount ON RETAILBILL(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('RETAILBILL') AND name = 'NCIX_RETAILBILL_Tax')
DROP INDEX NCIX_RETAILBILL_Tax ON RETAILBILL                            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                       
CREATE NONCLUSTERED INDEX NCIX_RETAILBILL_Tax ON RETAILBILL(Tax) 
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='BackQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN BackQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
              
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE retailBill 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

--是否为组合品（上表体数据）,1:是；0:不是。如果没有启用组合品，则该值永远为0.
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='iscombination'
)
BEGIN
		ALTER TABLE retailBill ADD iscombination   BIT NOT NULL Default(0)
END
GO

--所属组合品ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='combinationptypeid'
)
BEGIN
		ALTER TABLE retailBill ADD combinationptypeid   VARCHAR(200) NULL
END
GO

--启用组合品上下表体唯一ID值
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='pindexid'
)
BEGIN
		ALTER TABLE retailBill ADD pindexid  VARCHAR(300) NULL
END
GO


ALTER TABLE retailBill 
	ALTER COLUMN comment varchar(MAX) 

GO  
  
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='retailBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE retailBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO  



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[RetailCombinationBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[RetailCombinationBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL  DEFAULT (1),
		[DiscountPrice] [numeric](24, 10) NULL,
		[total] [numeric](24, 10) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[IsUnit2] [int] NOT NULL  DEFAULT (0),
		[BackQTY] [numeric](24, 10) NULL DEFAULT (0),
		[SaleTotal] [numeric](24, 10) NULL DEFAULT (0),
		[Tax] [numeric](5, 2) NULL DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), --是否赠品
		PosId INT  NOT NULL DEFAULT(0),
		BeforePromoID INT NULL DEFAULT(0),
		[PriceDetailId] INT NOT NULL DEFAULT(0),
		[PriceRuleId] INT NOT NULL DEFAULT(0),
		[PriceSource] VARCHAR(500) NOT NULL DEFAULT(''),
		PriceStyle INT NOT NULL DEFAULT(0), --价格类型
		PromoType INT NOT NULL DEFAULT(0), --促销类型 0是无
		ETypeID	VARCHAR(200) NULL,
		pindexid	VARCHAR(300),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL
		,PromonIds VARCHAR(1000)
		,CouponCode	VARCHAR(200) DEFAULT('')		--优惠券券编码，目前在兑换券的时候会使用
		,IsPromotion	INT DEFAULT(1)					--使用优惠券后，是否参与促销
		,IsVipPoint INT DEFAULT(1)					--使用优惠券后，是否参与会员积分
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

-- 添加促销方案id字段，记录商品应用的所有促销方案
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailCombinationBill',N'U') AND Name='PromonIds')
BEGIN
	ALTER TABLE dbo.RetailCombinationBill
	ADD PromonIds VARCHAR(1000) NOT NULL DEFAULT('')
END
GO

--优惠券券编码，目前在兑换券的时候会使用
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailCombinationBill',N'U') AND Name='CouponCode')
BEGIN
	ALTER TABLE dbo.RetailCombinationBill
	ADD CouponCode VARCHAR(200) DEFAULT('')
END
GO

--使用优惠券后，是否参与促销
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailCombinationBill',N'U') AND Name='IsPromotion')
BEGIN
	ALTER TABLE dbo.RetailCombinationBill
	ADD IsPromotion INT DEFAULT(1)
END
GO

--使用优惠券后，是否参与会员积分
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'RetailCombinationBill',N'U') AND Name='IsVipPoint')
BEGIN
	ALTER TABLE dbo.RetailCombinationBill
	ADD IsVipPoint INT DEFAULT(1)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------




/****** 对象:  Table [dbo].[RetailConfig]    脚本日期: 05/05/2010 14:49:02 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[RetailConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[RetailConfig](
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ATypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LoginUserId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('SA_ConfigCollate')
            and   type = 'U')
BEGIN
	CREATE TABLE SA_ConfigCollate
	(
		id   INT IDENTITY(1,1),
		reportName VARCHAR(100), --报表名
		orTableName VARCHAR(100), --零时表模板表
		combineproName VARCHAR(100), --合并数据存储过程
		queryProName VARCHAR(100)  --查询存储过程
	)
	INSERT INTO SA_ConfigCollate VALUES('SA_PtypeBuyStat','TP_SA_Buy','GP_GetSABuyStat','WEB_QueyBuyPtypeStat')
	INSERT INTO SA_ConfigCollate VALUES('SA_BtypeBuyStat','TP_SA_Buy','GP_GetSABuyStat','WEB_QueyBuyBtypeStat')
	--商品销售统计
	INSERT INTO SA_ConfigCollate VALUES('SA_GoodsSellStat','TP_SA_GoodsSellStat','GP_GoodsSellStat','WEB_GoodsSellStat')
	--客户销售统计
	INSERT INTO SA_ConfigCollate VALUES('SA_CustomerSellStat','TP_SA_GoodsSellStat','GP_CustomerSellStat','WEB_CustomerSellStat')

END
GO
-----------------------------------------------------修改表-----------------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM SA_ConfigCollate WHERE reportName='SA_PtypeBuyStat')
	INSERT INTO SA_ConfigCollate VALUES('SA_PtypeBuyStat','TP_SA_Buy','GP_GetSABuyStat','WEB_QueyBuyPtypeStat')
IF NOT EXISTS(SELECT TOP 1 1 FROM SA_ConfigCollate WHERE reportName='SA_BtypeBuyStat')
	INSERT INTO SA_ConfigCollate VALUES('SA_BtypeBuyStat','TP_SA_Buy','GP_GetSABuyStatbtype','WEB_QueyBuyBtypeStat')
IF NOT EXISTS(SELECT TOP 1 1 FROM SA_ConfigCollate WHERE reportName='SA_GoodsSellStat')
	INSERT INTO SA_ConfigCollate VALUES('SA_GoodsSellStat','TP_SA_GoodsSellStat','GP_GoodsSellStat','WEB_GoodsSellStat')
IF NOT EXISTS(SELECT TOP 1 1 FROM SA_ConfigCollate WHERE reportName='SA_CustomerSellStat')
	INSERT INTO SA_ConfigCollate VALUES('SA_CustomerSellStat','TP_SA_GoodsSellStat','GP_CustomerSellStat','WEB_CustomerSellStat')

------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

-----------------------------------------------------修改数据-----------------------------------------------------
UPDATE SA_ConfigCollate SET combineproName='GP_GetSABuyStatbtype' WHERE reportName='SA_BtypeBuyStat'
UPDATE SA_ConfigCollate SET combineproName='GP_CustomerSellStat' WHERE reportName='SA_CustomerSellStat'

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[saleBackBill]    脚本日期: 05/05/2010 14:49:03 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[saleBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[saleBackBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NOT NULL CONSTRAINT [DF_saleBackBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NOT NULL CONSTRAINT [DF_saleBackBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_saleBackBill_DiscountPrice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsno] [int] NULL CONSTRAINT [DF_saleBackBill_goodsno]  DEFAULT (0),
		[total] [numeric](18, 4) NOT NULL CONSTRAINT [DF_saleBackBill_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_saleBackBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_saleBackBill_TaxTotal]  DEFAULT (0),
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_saleBackBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_saleBackBill_Serial]  DEFAULT (''),
		[OldID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_saleBackBill_OldID]  DEFAULT (''),
		[CostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_saleBackBill_CostPrice]  DEFAULT (0),
		[OldBillNumberID] [numeric](18, 0) NULL CONSTRAINT [DF_saleBackBill_OldBillNumberID]  DEFAULT (0),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_saleBackBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_saleBackBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBackBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBackBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBackBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBackBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBackBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_SaleBackBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_SaleBackBill_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__saleBackB__Compl__1904BC7E]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBackBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_SaleBackBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[FromBillID] [numeric](10, 0)  NULL,
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		ETypeID VARCHAR(100),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PromoType INT NOT NULL DEFAULT(0), --促销类型 0是无
		ShowOrder INT DEFAULT(0)
		,InflowQty NUMERIC(24,10) DEFAULT(0) --入库数量,上架单过账回写
		,InFactQty NUMERIC(24,10) DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
	    PriceSource VARCHAR(200),
		CouponCode	VARCHAR(200) DEFAULT(''),		--优惠券券编码，目前在兑换券的时候会使用
		PromoIds	VARCHAR(200) DEFAULT('')
		
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBackBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.SaleBackBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBackBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.SaleBackBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBackBill',N'U') AND Name='ETypeID')
BEGIN
	ALTER TABLE SaleBackBill
	ADD ETypeID VARCHAR(100)
END
GO
	UPDATE SaleBackBill
	SET ETypeID=b.etypeid
	FROM Billindex b
	WHERE SaleBackBill.BillNumberId=b.BillNumberId AND ISNULL(SaleBackBill.ETypeID,'')=''
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBackBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.SaleBackBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SaleBackBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBackBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.SaleBackBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SaleBackBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[SaleBackBill]') and name = 'KTypeID' )
BEGIN
	ALTER TABLE dbo.SaleBackBill ADD
		KTypeID varchar(50) NULL
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[SaleBackBill]') and name = 'PromoIds' )
BEGIN
	ALTER TABLE dbo.SaleBackBill ADD
		PromoIds varchar(200) NULL
END
GO

UPDATE SaleBackBill
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE SaleBackBill.BillNumberID=b.BillNumberID AND SaleBackBill.KTypeID IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE saleBackBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE saleBackBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE SaleBackBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE SaleBackBill ADD FromBillNumberID  [numeric](10, 0)  NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='FromBillID'
)
BEGIN
	ALTER TABLE SaleBackBill ADD FromBillID  [numeric](10, 0)  NULL
END

GO

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='salebackbill' AND a.Name='OMBillID'
)
BEGIN
		ALTER TABLE salebackbill ADD OMBillID INT NULL DEFAULT(0)
END
GO
UPDATE salebackbill SET OMBillID = 0 WHERE OMBillID IS NULL
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE SaleBackBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE SaleBackBill ADD UnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NUnitID INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NQty   numeric(22,10)    NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE SaleBackBill ADD UnitRate   numeric(22,10)    NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE SaleBackBill ADD MUnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE SaleBackBill ADD MQty   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE SaleBackBill ADD MUnitRate   numeric(22,10)  NULL Default(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE SaleBackBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD MSalePrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD MDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD MTaxPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD CurMSalePrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD CurMDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD CurMTaxPrice   numeric(22,10)  NULL Default(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE SaleBackBill ADD CargoID   INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE SaleBackBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE SaleBackBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE SaleBackBill ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE SaleBackBill ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='nInvoiceMoney'
)
BEGIN
		ALTER TABLE SaleBackBill ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO		
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE SaleBackBill ADD IsGift INT NOT NULL  DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='ReferPrice'
)
BEGIN
		ALTER TABLE SaleBackBill ADD ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0) --参考成本
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='PriceStyle'
)
BEGIN
		ALTER TABLE SaleBackBill ADD PriceStyle INT NOT NULL DEFAULT(0) --价格类型
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='PromoType'
)
BEGIN
		ALTER TABLE SaleBackBill ADD PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
END
GO

--优惠券券编码，目前在兑换券的时候会使用
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBackBill',N'U') AND Name='CouponCode')
BEGIN
	ALTER TABLE dbo.SaleBackBill
	ADD CouponCode VARCHAR(200) DEFAULT('')
END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'saleBackBill',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE saleBackBill ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE saleBackBill SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'saleBackBill',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE saleBackBill ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE dbo.saleBackBill SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO
---
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('SaleBackBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table SaleBackBill drop constraint '+@dfname);
		
	ALTER TABLE SaleBackBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE SaleBackBill ADD CONSTRAINT DF_SaleBackBill_Serial DEFAULT('') FOR Serial
END
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'SaleBackBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.SaleBackBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.SaleBackBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'GiftFlag';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='SaleBackBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBackBill]') AND name = N'IX_SaleBackBill_BillNumberId')
	DROP INDEX [dbo].[SaleBackBill].[IX_SaleBackBill_BillNumberId]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBackBill]') AND name = N'IX_SaleBackBill_PTypeID')
	DROP INDEX [dbo].[SaleBackBill].[IX_SaleBackBill_PTypeID]
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBackBill]') AND name = N'CIX_BID')
	DROP INDEX [dbo].[SaleBackBill].CIX_BID
GO


IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBackBill]') AND name = N'NCIX_OutFactoryDate')
	DROP INDEX [dbo].[SaleBackBill].NCIX_OutFactoryDate
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBACKBILL') AND name = 'CIX_SALEBACKBILL_BillNumberID')
--DROP INDEX CIX_SALEBACKBILL_BillNumberID ON SALEBACKBILL 
CREATE CLUSTERED INDEX CIX_SALEBACKBILL_BillNumberID ON SALEBACKBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBACKBILL') AND name = 'NCIX_SALEBACKBILL_Ptypeid')
--DROP INDEX NCIX_SALEBACKBILL_Ptypeid ON SALEBACKBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEBACKBILL_Ptypeid ON SALEBACKBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBACKBILL') AND name = 'NCIX_SALEBACKBILL_Ktypeid')
--DROP INDEX NCIX_SALEBACKBILL_Ktypeid ON SALEBACKBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEBACKBILL_Ktypeid ON SALEBACKBILL(Ktypeid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBACKBILL') AND name = 'NCIX_SALEBACKBILL_SalePrice')
DROP INDEX NCIX_SALEBACKBILL_SalePrice ON SALEBACKBILL                            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                  
CREATE NONCLUSTERED INDEX NCIX_SALEBACKBILL_SalePrice ON SALEBACKBILL(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBACKBILL') AND name = 'NCIX_SALEBACKBILL_Discount')
DROP INDEX NCIX_SALEBACKBILL_Discount ON SALEBACKBILL            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                 
CREATE NONCLUSTERED INDEX NCIX_SALEBACKBILL_Discount ON SALEBACKBILL(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBACKBILL') AND name = 'NCIX_SALEBACKBILL_Tax')
DROP INDEX NCIX_SALEBACKBILL_Tax ON SALEBACKBILL                             
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
CREATE NONCLUSTERED INDEX NCIX_SALEBACKBILL_Tax ON SALEBACKBILL(Tax) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
               
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE saleBackBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
    
--网店加个字段，关联明细
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBackBill' AND a.Name='mid'
)
BEGIN
		ALTER TABLE SaleBackBill ADD mid INT NULL DEFAULT(0)
END
GO	

	ALTER TABLE RetailBackBill 
	ALTER COLUMN comment varchar(max)
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='saleBackBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE saleBackBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SaleBill]    脚本日期: 05/05/2010 14:49:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SaleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SaleBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBill_jobnumber]  DEFAULT (''),
		[goodsno] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_goodsno]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_SaleBill_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_SaleBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_SaleBill_GoodsOrder]  DEFAULT ('-1'),
		[BackQty] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_BackQty]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_SaleBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_SaleBill_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__SaleBill__Comple__18109845]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_SaleBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ShareFee]	[numeric](18,2) NULL DEFAULT(0),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int                NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			 VARCHAR(200)		NULL DEFAULT('') ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), --是否是赠品 价格促销
		BeforePromoID INT NOT NULL DEFAULT(0),
		--GiftFlag INT NOT NULL DEFAULT(0) -- 0不是，1是赠品 9.4
		ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,ShowOrder INT DEFAULT(0)
		,DiyID INT DEFAULT(-1)
		,ETypeID VARCHAR(100)
		,ClearQty NUMERIC(24,10)	--解锁数量
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
		,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
		PromonIds VARCHAR(1000) NOT NULL DEFAULT(''), --所有使用的促销方案id，逗号分隔
		CouponCode	VARCHAR(200) NOT NULL DEFAULT('')		--优惠券券编码，目前在兑换券的时候会使用
		,IsPromotion	INT NOT NULL DEFAULT(1)					--使用优惠券后，是否参与促销
		,IsVipPoint INT NOT NULL DEFAULT(1)	,				--使用优惠券后，是否参与会员积分		
		[PriceDetailId] INT  NULL DEFAULT(0),
		[PriceRuleId] INT  NULL DEFAULT(0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

--高级价格明细id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='PriceDetailId'
)
BEGIN
	ALTER TABLE SaleBill ADD PriceDetailId INT  NULL DEFAULT(0)
END
go

--高级价格id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='PriceRuleId'
)
BEGIN
	ALTER TABLE SaleBill ADD PriceRuleId INT  NULL DEFAULT(0)
END
go

update SaleBill set PriceDetailId = 0 ,PriceRuleId = 0
where PriceDetailId is null
GO

-- 添加促销方案id字段，记录商品应用的所有促销方案
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='PromonIds')
BEGIN
	ALTER TABLE dbo.SaleBill
	ADD PromonIds VARCHAR(1000) NOT NULL DEFAULT('')
END
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.SaleBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.SaleBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.SaleBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SaleBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='ETypeID')
BEGIN
	ALTER TABLE SaleBill
	ADD ETypeID VARCHAR(100)
END
GO
	UPDATE SaleBill
	SET ETypeID=b.etypeid
	FROM Billindex b
	WHERE SaleBill.BillNumberId=b.BillNumberId AND ISNULL(SaleBill.ETypeID,'')=''
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE SaleBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE SaleBill SET PickedQty=0 WHERE PickedQty IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='ClearQty'
)
BEGIN
		ALTER TABLE SaleBill ADD ClearQty   numeric(22,10)   NULL Default(0)
END
GO

IF NOT EXISTS(SELECt 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='DiyID')
BEGIN
	ALTER TABLE dbo.SaleBill
	ADD DiyID INT DEFAULT(-1)
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[SaleBill]') and name = 'KTypeID' )
BEGIN
	
	ALTER TABLE dbo.SaleBill ADD
		KTypeID varchar(50) NULL
END
GO
UPDATE SaleBill
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE SaleBill.BillNumberID=b.BillNumberID AND SaleBill.KTypeID IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE SaleBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE SaleBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='ShareFee'
)
BEGIN
	ALTER TABLE SaleBill ADD ShareFee  [numeric](18, 2)  NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE SaleBill ADD TaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE SaleBill ADD NSalePrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE SaleBill ADD NSaleTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBill ADD NDiscountPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE SaleBill ADD NTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE SaleBill ADD NTaxPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE SaleBill ADD NTaxTotal   numeric(22,10)   NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE SaleBill ADD NTaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE SaleBill ADD UnitID  INT   NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE SaleBill ADD NUnitID INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE SaleBill ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE SaleBill ADD UnitRate   numeric(22,10)     NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE SaleBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE SaleBill ADD MUnitID  INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE SaleBill ADD MQty   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE SaleBill ADD MUnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE SaleBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE SaleBill ADD MSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBill ADD MDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE SaleBill ADD MTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE SaleBill ADD CurMSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBill ADD CurMDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE SaleBill ADD CurMTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE SaleBill ADD CargoID   INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE SaleBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE SaleBill ADD IsCombined   INT
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='entryCode'
)
BEGIN
	ALTER TABLE SaleBill ADD entryCode   VARCHAR(200) DEFAULT('')
END
ELSE 
	ALTER TABLE SaleBill ALTER COLUMN entryCode VARCHAR(200)
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE SaleBill ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE SaleBill ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO




IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NInvoiceMoney'
)
BEGIN
		ALTER TABLE SaleBill ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE SaleBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='ReferPrice'
)
BEGIN
		ALTER TABLE SaleBill ADD ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0) --参考成本
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='PriceStyle'
)
BEGIN
		ALTER TABLE SaleBill ADD PriceStyle INT NOT NULL DEFAULT(0) --价格类型
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='PromoType'
)
BEGIN
		ALTER TABLE SaleBill ADD PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CouponCode'
)
BEGIN
		ALTER TABLE SaleBill ADD CouponCode VARCHAR(200) NOT NULL DEFAULT('') --优惠券券编码，目前在兑换券的时候会使用
END
GO

--使用优惠券后，是否参与促销
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='IsPromotion')
BEGIN
	ALTER TABLE dbo.SaleBill
	ADD IsPromotion INT NOT NULL DEFAULT(1)
END
GO

--使用优惠券后，是否参与会员积分
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND Name='IsVipPoint')
BEGIN
	ALTER TABLE dbo.SaleBill
	ADD IsVipPoint INT NOT NULL DEFAULT(1)
END
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'SaleBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.SaleBill
	ADD ShowOrder INT  DEFAULT(0)
END
GO
	UPDATE dbo.SaleBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE SaleBill ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE SaleBill SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBill',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE SaleBill ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE SaleBill SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO
-------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE SaleBill ALTER COLUMN PriceSource   VARCHAR(200)
END
GO
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='OMBillID'
)
BEGIN
		ALTER TABLE SaleBill ADD OMBillID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='LendBillNumberID'
)
BEGIN
		ALTER TABLE SaleBill ADD LendBillNumberID numeric(10, 0) NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='LendBillID'
)
BEGIN
		ALTER TABLE SaleBill ADD LendBillID NUMERIC(10, 0) NULL DEFAULT(0)
END
GO	

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('SaleBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table SaleBill drop constraint '+@dfname);
		
	ALTER TABLE SaleBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE SaleBill ADD CONSTRAINT DF_SaleBill_Serial DEFAULT('') FOR Serial
END
GO




-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'BarCode';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='SaleBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE SaleBill ADD IsGift INT NOT NULL DEFAULT(0);
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='BeforePromoID'
)
BEGIN

		ALTER TABLE SaleBill ADD BeforePromoID INT NOT NULL DEFAULT(0);
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='SendedQty'
)
BEGIN

		ALTER TABLE SaleBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0);
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'GiftFlag' 
DECLARE @sql NVARCHAR(max)='';

DECLARE @tn VARCHAR(500)='SaleBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBill]') AND name = N'NCIX_PTYPEID')
	DROP INDEX [dbo].[SaleBill].NCIX_PTYPEID 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBill]') AND name = N'NCIX_KTYPEID')
	DROP INDEX [dbo].[SaleBill].NCIX_KTYPEID 
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBill]') AND name = N'NCIX_ORDERID')
	DROP INDEX [dbo].[SaleBill].NCIX_ORDERID 
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBill]') AND name = N'NCIX_OutFactoryDate')
	DROP INDEX [dbo].[SaleBill].NCIX_OutFactoryDate 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBill]') AND name = N'IX_SaleBill')
DROP INDEX [IX_SaleBill] ON [dbo].[SaleBill] 


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBill]') AND name = N'IX_SaleBill_PTypeID')
DROP INDEX [IX_SaleBill_PTypeID] ON [dbo].[SaleBill] 


IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBill]') AND name = N'SaleBillIndex')
DROP INDEX [SaleBillIndex] ON [dbo].[SaleBill] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBILL') AND name = 'CIX_SALEBILL_BillNumberID')
--DROP INDEX CIX_SALEBILL_BillNumberID ON SALEBILL 
CREATE CLUSTERED INDEX CIX_SALEBILL_BillNumberID ON SALEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBILL') AND name = 'NCIX_SALEBILL_Ptypeid')
--DROP INDEX NCIX_SALEBILL_Ptypeid ON SALEBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEBILL_Ptypeid ON SALEBILL(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBILL') AND name = 'NCIX_SALEBILL_Ktypeid')
--DROP INDEX NCIX_SALEBILL_Ktypeid ON SALEBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEBILL_Ktypeid ON SALEBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBILL') AND name = 'NCIX_SALEBILL_Orderid')
--DROP INDEX NCIX_SALEBILL_Orderid ON SALEBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEBILL_Orderid ON SALEBILL(Orderid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBILL') AND name = 'NCIX_SALEBILL_SalePrice')
DROP INDEX NCIX_SALEBILL_SalePrice ON SALEBILL                             
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                              
CREATE NONCLUSTERED INDEX NCIX_SALEBILL_SalePrice ON SALEBILL(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBILL') AND name = 'NCIX_SALEBILL_Discount')
DROP INDEX NCIX_SALEBILL_Discount ON SALEBILL                 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                         
CREATE NONCLUSTERED INDEX NCIX_SALEBILL_Discount ON SALEBILL(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBILL') AND name = 'NCIX_SALEBILL_Tax')
DROP INDEX NCIX_SALEBILL_Tax ON SALEBILL                               
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                              
CREATE NONCLUSTERED INDEX NCIX_SALEBILL_Tax ON SALEBILL(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEBILL') AND name = 'NCIX_SALEBILL_Id')
--DROP INDEX NCIX_SALEBILL_Id ON SALEBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEBILL_Id ON SALEBILL(Id) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE SaleBill SET sharefee = 0 WHERE sharefee IS NULL
GO
UPDATE SaleBill SET OMBillID = 0 WHERE OMBillID IS NULL
GO
UPDATE BuyBill SET LendBillID = 0 WHERE LendBillID IS NULL
GO
UPDATE BuyBill SET LendBillNumberID = 0 WHERE LendBillNumberID IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
    
--网店加个字段，关联明细mid
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='mid'
)
BEGIN
		ALTER TABLE SaleBill ADD mid INT NULL DEFAULT(0)
END
GO	

--网店加个字段，关联明细nid
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='nid'
)
BEGIN
		ALTER TABLE SaleBill ADD nid INT NULL DEFAULT(0)
END
GO	
                     
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='goodsno' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
		DECLARE @dfname VARCHAR(1000)
		SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('SaleBill') AND name='goodsno')
		IF @dfname IS NOT NULL
			EXEC ('alter table SaleBill drop constraint '+@dfname);
		ALTER TABLE SaleBill ALTER COLUMN goodsno NUMERIC(24,10)
		ALTER TABLE SaleBill ADD CONSTRAINT DF_SaleBill_goodsno DEFAULT(0) FOR goodsno
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
 
 ALTER TABLE SaleBill 
	ALTER COLUMN comment varchar(MAX) 
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE SaleBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO   

-----------易居客的字段----------- 
--型号
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='model'
    )
    BEGIN
	ALTER TABLE SaleBill 
		ADD model VARCHAR(200) NULL DEFAULT('')
    END
GO
UPDATE  SaleBill SET  model = '' WHERE model IS NULL    

--规格
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='spec'
    )
    BEGIN
	ALTER TABLE SaleBill 
		ADD spec VARCHAR(200) NULL DEFAULT('')
    END
GO
UPDATE  SaleBill SET  spec = '' WHERE spec IS NULL

--是否激活
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='isActivate'
    )
    BEGIN
	ALTER TABLE SaleBill 
		ADD isActivate INT NULL DEFAULT(0)
    END
GO
UPDATE  SaleBill SET  isActivate = 0 WHERE isActivate IS NULL 
   
--使用方式
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='yjkuse'
    )
    BEGIN
	ALTER TABLE SaleBill 
		ADD yjkuse VARCHAR(200) NULL DEFAULT('')
    END
GO
UPDATE  SaleBill SET  yjkuse = '' WHERE yjkuse IS NULL

--使用地  
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='useAddress'
    )
    BEGIN
	ALTER TABLE SaleBill 
		ADD useAddress VARCHAR(200) NULL DEFAULT('')
    END
GO
UPDATE  SaleBill SET  useAddress = '' WHERE useAddress IS NULL
 
--外地原因  
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='nonReason'
    )
    BEGIN
	ALTER TABLE SaleBill 
		ADD nonReason VARCHAR(200) NULL DEFAULT('')
    END
GO
UPDATE  SaleBill SET  nonReason = '' WHERE nonReason IS NULL
  
--异常评估 
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='ycpg'
    )
    BEGIN
	ALTER TABLE SaleBill 
		ADD ycpg VARCHAR(200) NULL DEFAULT('')
    END
GO
UPDATE  SaleBill SET  ycpg = '' WHERE ycpg IS NULL

--异常原因  
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	WHERE b.Name='SaleBill' AND a.Name='ycReason'
    )
    BEGIN
	ALTER TABLE SaleBill 
		ADD ycReason VARCHAR(200) NULL DEFAULT('')
    END
GO
UPDATE  SaleBill SET  ycReason = '' WHERE ycReason IS NULL    

-----------易居客的字段结束-----------  
                                   
 
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SaleBillAutoDraft]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SaleBillAutoDraft](
		[BillGuid]		VARCHAR(100) NULL DEFAULT(''),
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBillAutoDraft_jobnumber]  DEFAULT (''),
		[goodsno] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_goodsno]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_SaleBillAutoDraft_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_SaleBillAutoDraft_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBillAutoDraft_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_SaleBillAutoDraft_GoodsOrder]  DEFAULT ('-1'),
		[BackQty] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_BackQty]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBillAutoDraft_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBillAutoDraft_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBillAutoDraft_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleBillAutoDraft_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_SaleBillAutoDraft_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_SaleBillAutoDraft_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__SaleBillAutoDraft__Comple__18109845]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_SaleBillAutoDraft_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_SaleBillAutoDraft_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ShareFee]	[numeric](18,2) NULL DEFAULT(0),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int                NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			 VARCHAR(200)		NULL DEFAULT('') ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), --是否是赠品 价格促销
		BeforePromoID INT NOT NULL DEFAULT(0),
		--GiftFlag INT NOT NULL DEFAULT(0) -- 0不是，1是赠品 9.4
		ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,ShowOrder INT DEFAULT(0)
		,DiyID INT DEFAULT(-1)
		,ETypeID VARCHAR(100)
		,ClearQty NUMERIC(24,10)	--解锁数量
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
		,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
		PromonIds VARCHAR(1000) NOT NULL DEFAULT(''), --所有使用的促销方案id，逗号分隔
		CouponCode	VARCHAR(200) NOT NULL DEFAULT('')		--优惠券券编码，目前在兑换券的时候会使用
		,IsPromotion	INT NOT NULL DEFAULT(1)					--使用优惠券后，是否参与促销
		,IsVipPoint INT NOT NULL DEFAULT(1)	,				--使用优惠券后，是否参与会员积分		
		[PriceDetailId] INT  NULL DEFAULT(0),
		[PriceRuleId] INT  NULL DEFAULT(0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

--高级价格明细id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='PriceDetailId'
)
BEGIN
	ALTER TABLE SaleBillAutoDraft ADD PriceDetailId INT  NULL DEFAULT(0)
END
go

--高级价格id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='PriceRuleId'
)
BEGIN
	ALTER TABLE SaleBillAutoDraft ADD PriceRuleId INT  NULL DEFAULT(0)
END
go

update SaleBillAutoDraft set PriceDetailId = 0 ,PriceRuleId = 0
where PriceDetailId is null
GO

-- 添加促销方案id字段，记录商品应用的所有促销方案
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='PromonIds')
BEGIN
	ALTER TABLE dbo.SaleBillAutoDraft
	ADD PromonIds VARCHAR(1000) NOT NULL DEFAULT('')
END
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.SaleBillAutoDraft
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.SaleBillAutoDraft
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.SaleBillAutoDraft
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SaleBillAutoDraft SET OutFactQty=0 WHERE OutFactQty IS NULL
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='ETypeID')
BEGIN
	ALTER TABLE SaleBillAutoDraft
	ADD ETypeID VARCHAR(100)
END
GO
	UPDATE SaleBillAutoDraft
	SET ETypeID=b.etypeid
	FROM Billindex b
	WHERE SaleBillAutoDraft.BillNumberId=b.BillNumberId AND ISNULL(SaleBillAutoDraft.ETypeID,'')=''
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE SaleBillAutoDraft
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE SaleBillAutoDraft SET PickedQty=0 WHERE PickedQty IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='ClearQty'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD ClearQty   numeric(22,10)   NULL Default(0)
END
GO

IF NOT EXISTS(SELECt 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='DiyID')
BEGIN
	ALTER TABLE dbo.SaleBillAutoDraft
	ADD DiyID INT DEFAULT(-1)
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[SaleBillAutoDraft]') and name = 'KTypeID' )
BEGIN
	
	ALTER TABLE dbo.SaleBillAutoDraft ADD
		KTypeID varchar(50) NULL
END
GO
UPDATE SaleBillAutoDraft
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE SaleBillAutoDraft.BillNumberID=b.BillNumberID AND SaleBillAutoDraft.KTypeID IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE SaleBillAutoDraft SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='ShareFee'
)
BEGIN
	ALTER TABLE SaleBillAutoDraft ADD ShareFee  [numeric](18, 2)  NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD TaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NSalePrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NSaleTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NDiscountPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NTaxPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NTaxTotal   numeric(22,10)   NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NTaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD UnitID  INT   NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NUnitID INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD UnitRate   numeric(22,10)     NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD MUnitID  INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD MQty   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD MUnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD MSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD MDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD MTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD CurMSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD CurMDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD CurMTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD CargoID   INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD IsCombined   INT
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='entryCode'
)
BEGIN
	ALTER TABLE SaleBillAutoDraft ADD entryCode   VARCHAR(200) DEFAULT('')
END
ELSE 
	ALTER TABLE SaleBillAutoDraft ALTER COLUMN entryCode VARCHAR(200)
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO




IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NInvoiceMoney'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='ReferPrice'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0) --参考成本
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='PriceStyle'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD PriceStyle INT NOT NULL DEFAULT(0) --价格类型
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='PromoType'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CouponCode'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD CouponCode VARCHAR(200) NOT NULL DEFAULT('') --优惠券券编码，目前在兑换券的时候会使用
END
GO

--使用优惠券后，是否参与促销
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='IsPromotion')
BEGIN
	ALTER TABLE dbo.SaleBillAutoDraft
	ADD IsPromotion INT NOT NULL DEFAULT(1)
END
GO

--使用优惠券后，是否参与会员积分
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='IsVipPoint')
BEGIN
	ALTER TABLE dbo.SaleBillAutoDraft
	ADD IsVipPoint INT NOT NULL DEFAULT(1)
END
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'SaleBillAutoDraft',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.SaleBillAutoDraft
	ADD ShowOrder INT  DEFAULT(0)
END
GO
	UPDATE dbo.SaleBillAutoDraft SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE SaleBillAutoDraft ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE SaleBillAutoDraft SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleBillAutoDraft',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE SaleBillAutoDraft ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE SaleBillAutoDraft SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO
-------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ALTER COLUMN PriceSource   VARCHAR(200)
END
GO
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='OMBillID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD OMBillID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='LendBillNumberID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD LendBillNumberID numeric(10, 0) NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='LendBillID'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD LendBillID NUMERIC(10, 0) NULL DEFAULT(0)
END
GO	

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('SaleBillAutoDraft') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table SaleBillAutoDraft drop constraint '+@dfname);
		
	ALTER TABLE SaleBillAutoDraft ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE SaleBillAutoDraft ADD CONSTRAINT DF_SaleBillAutoDraft_Serial DEFAULT('') FOR Serial
END
GO




-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'BarCode';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='SaleBillAutoDraft';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD IsGift INT NOT NULL DEFAULT(0);
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='BeforePromoID'
)
BEGIN

		ALTER TABLE SaleBillAutoDraft ADD BeforePromoID INT NOT NULL DEFAULT(0);
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='SendedQty'
)
BEGIN

		ALTER TABLE SaleBillAutoDraft ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0);
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'GiftFlag' 
DECLARE @sql NVARCHAR(max)='';

DECLARE @tn VARCHAR(500)='SaleBillAutoDraft';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBillAutoDraft]') AND name = N'NCIX_PTYPEID')
	DROP INDEX [dbo].[SaleBillAutoDraft].NCIX_PTYPEID 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBillAutoDraft]') AND name = N'NCIX_KTYPEID')
	DROP INDEX [dbo].[SaleBillAutoDraft].NCIX_KTYPEID 
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBillAutoDraft]') AND name = N'NCIX_ORDERID')
	DROP INDEX [dbo].[SaleBillAutoDraft].NCIX_ORDERID 
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBillAutoDraft]') AND name = N'NCIX_OutFactoryDate')
	DROP INDEX [dbo].[SaleBillAutoDraft].NCIX_OutFactoryDate 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBillAutoDraft]') AND name = N'IX_SaleBillAutoDraft')
DROP INDEX [IX_SaleBillAutoDraft] ON [dbo].[SaleBillAutoDraft] 


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBillAutoDraft]') AND name = N'IX_SaleBillAutoDraft_PTypeID')
DROP INDEX [IX_SaleBillAutoDraft_PTypeID] ON [dbo].[SaleBillAutoDraft] 


IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SaleBillAutoDraft]') AND name = N'SaleBillAutoDraftIndex')
DROP INDEX [SaleBillAutoDraftIndex] ON [dbo].[SaleBillAutoDraft] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SaleBillAutoDraft') AND name = 'CIX_SaleBillAutoDraft_BillNumberID')
--DROP INDEX CIX_SaleBillAutoDraft_BillNumberID ON SaleBillAutoDraft 
CREATE CLUSTERED INDEX CIX_SaleBillAutoDraft_BillNumberID ON SaleBillAutoDraft(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SaleBillAutoDraft') AND name = 'NCIX_SaleBillAutoDraft_Ptypeid')
--DROP INDEX NCIX_SaleBillAutoDraft_Ptypeid ON SaleBillAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_SaleBillAutoDraft_Ptypeid ON SaleBillAutoDraft(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SaleBillAutoDraft') AND name = 'NCIX_SaleBillAutoDraft_Ktypeid')
--DROP INDEX NCIX_SaleBillAutoDraft_Ktypeid ON SaleBillAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_SaleBillAutoDraft_Ktypeid ON SaleBillAutoDraft(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SaleBillAutoDraft') AND name = 'NCIX_SaleBillAutoDraft_Orderid')
--DROP INDEX NCIX_SaleBillAutoDraft_Orderid ON SaleBillAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_SaleBillAutoDraft_Orderid ON SaleBillAutoDraft(Orderid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SaleBillAutoDraft') AND name = 'NCIX_SaleBillAutoDraft_SalePrice')
DROP INDEX NCIX_SaleBillAutoDraft_SalePrice ON SaleBillAutoDraft                             
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                              
CREATE NONCLUSTERED INDEX NCIX_SaleBillAutoDraft_SalePrice ON SaleBillAutoDraft(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SaleBillAutoDraft') AND name = 'NCIX_SaleBillAutoDraft_Discount')
DROP INDEX NCIX_SaleBillAutoDraft_Discount ON SaleBillAutoDraft                 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                         
CREATE NONCLUSTERED INDEX NCIX_SaleBillAutoDraft_Discount ON SaleBillAutoDraft(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SaleBillAutoDraft') AND name = 'NCIX_SaleBillAutoDraft_Tax')
DROP INDEX NCIX_SaleBillAutoDraft_Tax ON SaleBillAutoDraft                               
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                              
CREATE NONCLUSTERED INDEX NCIX_SaleBillAutoDraft_Tax ON SaleBillAutoDraft(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SaleBillAutoDraft') AND name = 'NCIX_SaleBillAutoDraft_Id')
--DROP INDEX NCIX_SaleBillAutoDraft_Id ON SaleBillAutoDraft 
CREATE NONCLUSTERED INDEX NCIX_SaleBillAutoDraft_Id ON SaleBillAutoDraft(Id) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE SaleBillAutoDraft SET sharefee = 0 WHERE sharefee IS NULL
GO
UPDATE SaleBillAutoDraft SET OMBillID = 0 WHERE OMBillID IS NULL
GO
UPDATE BuyBill SET LendBillID = 0 WHERE LendBillID IS NULL
GO
UPDATE BuyBill SET LendBillNumberID = 0 WHERE LendBillNumberID IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
    
--网店加个字段，关联明细mid
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='mid'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD mid INT NULL DEFAULT(0)
END
GO	

--网店加个字段，关联明细nid
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='nid'
)
BEGIN
		ALTER TABLE SaleBillAutoDraft ADD nid INT NULL DEFAULT(0)
END
GO	
                     
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='goodsno' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
		DECLARE @dfname VARCHAR(1000)
		SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('SaleBillAutoDraft') AND name='goodsno')
		IF @dfname IS NOT NULL
			EXEC ('alter table SaleBillAutoDraft drop constraint '+@dfname);
		ALTER TABLE SaleBillAutoDraft ALTER COLUMN goodsno NUMERIC(24,10)
		ALTER TABLE SaleBillAutoDraft ADD CONSTRAINT DF_SaleBillAutoDraft_goodsno DEFAULT(0) FOR goodsno
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
 
 ALTER TABLE SaleBillAutoDraft 
	ALTER COLUMN comment varchar(MAX) 
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleBillAutoDraft' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE SaleBillAutoDraft 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SaleGoodsExchangeBill]    脚本日期: 05/05/2010 14:49:05 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SaleGoodsExchangeBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SaleGoodsExchangeBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[InOrOut] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleGoodsExchangeBill_jobnumber]  DEFAULT (''),
		[goodsno] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_goodsno]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_SaleGoodsExchangeBill_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_SaleGoodsExchangeBill_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleGoodsExchangeBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_SaleGoodsExchangeBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleGoodsExchangeBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleGoodsExchangeBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleGoodsExchangeBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_SaleGoodsExchangeBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchangeBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_SaleGoodsExchangeBill_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__SaleGoods__Compl__19F8E0B7]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_SaleGoodsExchageBill_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_SaleGoodsExchageBill_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KTypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), -- 0不是，1是赠品
		ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0), --价格类型
		[OldID] VARCHAR(50) DEFAULT (''),
		[OldBillNumberID] numeric(18, 0)   DEFAULT (0)
		,ETypeID VARCHAR(100)
		,ShowOrder INT DEFAULT(0)
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
		,InflowQty NUMERIC(24,10) NULL DEFAULT(0) --入库数量
		,InFactQty NUMERIC(24,10) NULL DEFAULT(0)
		,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),		
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[PriceSource] VARCHAR(200)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.SaleGoodsExchangeBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.SaleGoodsExchangeBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.SaleGoodsExchangeBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SaleGoodsExchangeBill SET InFactQty=0 WHERE InFactQty IS NULL
GO



IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.SaleGoodsExchangeBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SaleGoodsExchangeBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND Name='ETypeID')
BEGIN
	ALTER TABLE dbo.SaleGoodsExchangeBill
	ADD ETypeID VARCHAR(100)
END
GO
GO
	UPDATE SaleGoodsExchangeBill
	SET ETypeID=b.etypeid
	FROM Billindex b
	WHERE SaleGoodsExchangeBill.BillNumberId=b.BillNumberId AND ISNULL(SaleGoodsExchangeBill.ETypeID,'')='' 
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.SaleGoodsExchangeBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SaleGoodsExchangeBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE SaleGoodsExchangeBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE SaleGoodsExchangeBill SET PickedQty=0 WHERE PickedQty IS NULL
GO
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.SaleGoodsExchangeBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.SaleGoodsExchangeBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[SaleGoodsExchangeBill]') and name = 'KTypeID' )
BEGIN
	
	ALTER TABLE dbo.SaleGoodsExchangeBill ADD
		KTypeID varchar(50) NULL
END
GO

UPDATE SaleGoodsExchangeBill
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE SaleGoodsExchangeBill.BillNumberID=b.BillNumberID AND SaleGoodsExchangeBill.KTypeID IS NULL AND SaleGoodsExchangeBill.InOrOut='O'
GO

UPDATE SaleGoodsExchangeBill
SET KTypeID=b.KTypeID2
FROM BillIndex b
WHERE SaleGoodsExchangeBill.BillNumberID=b.BillNumberID AND SaleGoodsExchangeBill.KTypeID IS NULL AND SaleGoodsExchangeBill.InOrOut='I'
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[SaleGoodsExchangeBill]') and name = 'KTypeID2' )
BEGIN
	
	ALTER TABLE dbo.SaleGoodsExchangeBill ADD
		KTypeID2 varchar(50) NULL

END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE SaleGoodsExchangeBill SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD TaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NSalePrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NSaleTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NDiscountPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NTotal   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NTaxPrice   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NTaxTotal   numeric(22,10)  NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NTaxMoney   numeric(22,10)  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD UnitID  INT  NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NUnitID INT  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NQty   numeric(22,10)    NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD UnitRate   numeric(22,10)    NOT NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD MUnitID  INT  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD MQty   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD MUnitRate   numeric(22,10)  NOT NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD MSalePrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD MDiscountPrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD MTaxPrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD CurMSalePrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD CurMDiscountPrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE SaleGoodsExchangeBill ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE SaleGoodsExchangeBill SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SaleGoodsExchangeBill',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE SaleGoodsExchangeBill ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE SaleGoodsExchangeBill SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD CurMTaxPrice   numeric(22,10)  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD CargoID   INT  NOT NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='nInvoiceMoney'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO		
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD IsGift int NOT null DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='ReferPrice'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0) --参考成本
END
GO	
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='PriceStyle'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD PriceStyle INT NOT NULL DEFAULT(0) --价格类型
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='OldID'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD OldID VARCHAR(50) NOT NULL DEFAULT('') 
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='OldBillNumberID'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD OldBillNumberID  numeric(18, 0) NOT NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE SaleGoodsExchangeBill ADD SendedQty  DECIMAL(24, 10) NULL DEFAULT(0)
END
GO	

---
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('SaleGoodsExchangeBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table SaleGoodsExchangeBill drop constraint '+@dfname);
		
	ALTER TABLE SaleGoodsExchangeBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE SaleGoodsExchangeBill ADD CONSTRAINT DF_SaleGoodsExchangeBill_Serial DEFAULT('') FOR Serial
END
GO	

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'GiftFlag';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='SaleGoodsExchangeBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEGOODSEXCHANGEBILL') AND name = 'CIX_SALEGOODSEXCHANGEBILL_BillNumberID')
--DROP INDEX CIX_SALEGOODSEXCHANGEBILL_BillNumberID ON SALEGOODSEXCHANGEBILL 
CREATE CLUSTERED INDEX CIX_SALEGOODSEXCHANGEBILL_BillNumberID ON SALEGOODSEXCHANGEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEGOODSEXCHANGEBILL') AND name = 'NCIX_SALEGOODSEXCHANGEBILL_Ktypeid')
--DROP INDEX NCIX_SALEGOODSEXCHANGEBILL_Ktypeid ON SALEGOODSEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEGOODSEXCHANGEBILL_Ktypeid ON SALEGOODSEXCHANGEBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEGOODSEXCHANGEBILL') AND name = 'NCIX_SALEGOODSEXCHANGEBILL_Ktypeid2')
--DROP INDEX NCIX_SALEGOODSEXCHANGEBILL_Ktypeid2 ON SALEGOODSEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEGOODSEXCHANGEBILL_Ktypeid2 ON SALEGOODSEXCHANGEBILL(Ktypeid2) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEGOODSEXCHANGEBILL') AND name = 'NCIX_SALEGOODSEXCHANGEBILL_SalePrice')
DROP INDEX NCIX_SALEGOODSEXCHANGEBILL_SalePrice ON SALEGOODSEXCHANGEBILL                               
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                             
CREATE NONCLUSTERED INDEX NCIX_SALEGOODSEXCHANGEBILL_SalePrice ON SALEGOODSEXCHANGEBILL(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEGOODSEXCHANGEBILL') AND name = 'NCIX_SALEGOODSEXCHANGEBILL_Discount')
DROP INDEX NCIX_SALEGOODSEXCHANGEBILL_Discount ON SALEGOODSEXCHANGEBILL             
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                        
CREATE NONCLUSTERED INDEX NCIX_SALEGOODSEXCHANGEBILL_Discount ON SALEGOODSEXCHANGEBILL(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEGOODSEXCHANGEBILL') AND name = 'NCIX_SALEGOODSEXCHANGEBILL_Tax')
DROP INDEX NCIX_SALEGOODSEXCHANGEBILL_Tax ON SALEGOODSEXCHANGEBILL                       
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                
CREATE NONCLUSTERED INDEX NCIX_SALEGOODSEXCHANGEBILL_Tax ON SALEGOODSEXCHANGEBILL(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SALEGOODSEXCHANGEBILL') AND name = 'NCIX_SALEGOODSEXCHANGEBILL_Ptypeid')
--DROP INDEX NCIX_SALEGOODSEXCHANGEBILL_Ptypeid ON SALEGOODSEXCHANGEBILL 
CREATE NONCLUSTERED INDEX NCIX_SALEGOODSEXCHANGEBILL_Ptypeid ON SALEGOODSEXCHANGEBILL(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                         
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='goodsno' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN goodsno NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                          
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SaleGoodsExchangeBill' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE SaleGoodsExchangeBill 
		ADD Reconciliation VARCHAR(2) NOT NULL DEFAULT('f')
END
GO                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
----------------促销表开始
---------------------------------------------------------------------------------------------------

----------------------------------V5.5促销方案表头相关表及手工促销条件信息表Start-----------------------
IF NOT EXISTS ( SELECT  1
                FROM    sysobjects
                WHERE   id = OBJECT_ID('CX_SalePlanIndex')
                        AND type = 'U' ) 
    BEGIN
	/*==============================================================*/
	/* Table: CX_SalePlanIndex  促销方案表头主表                    */
	/*==============================================================*/
        CREATE TABLE CX_SalePlanIndex
            (
              BillNumberId NUMERIC(9) IDENTITY(1, 1)
                                      NOT NULL ,					--单据ID：自增字段
              BillType VARCHAR(1) NOT NULL ,					--单据类型：1特价促销单，2赠品促销单，3手工促销单，4组合促销单 默认值为：空
              BillName VARCHAR(40) NOT NULL ,					--促销名称：不许为空或重复
              BillCode VARCHAR(25) NOT NULL ,					--单据编号：不许为空或重复
              BillDateTime DATETIME NOT NULL ,					--录单日期格式为:2010-02-22 15:22:18 存储新建单据时的日期时间
              StartDate DATETIME NOT NULL ,					--开始日期格式：2006-01-01
              EndDate DATETIME NOT NULL ,					--结束日期格式：2006-01-01
              EtypeId VARCHAR(50) NOT NULL ,					--制单人ID
              JTypeID VARCHAR(50) NULL ,						--加盟商ID：若为总部单据，则值为Null，若为加盟商单据，则值为加盟商ID
              BillStatus VARCHAR(1) NOT NULL
                                    DEFAULT '0' ,		--审核状态取值说明：0:未审核；1:审核 默认值为：0
              BreakStatus VARCHAR(1) NOT NULL
                                     DEFAULT '0' ,		--中止状态取值说明：0:未中止；1:中止 默认值为：0
              DateTimeType VARCHAR(1) NOT NULL
                                      DEFAULT '1' ,		--时段类型取值说明：1:每天；2:每周；3:每月某日；4:每月某周 默认值为：1
              MonthDay VARCHAR(2) NULL ,						--每月第几日取值范围：0至30；0代表最后一天，1至30代表第1天至第30天 默认值为：空 
              MonthWeek VARCHAR(1) NULL ,						--每月第几周取值范围：0至5；0代表最后一个，1至5代表第1个至第5个 默认值为：空
              MonthWeekDay VARCHAR(1) NULL ,						--每月星期几取值范围：1至7，分别代表周一至周日（配合每月第几周字段） 默认值为：空
              WeekDays VARCHAR(7) NULL ,						--每周星期几格式如：0101011    七个字符依次代表周一至周日的选中状态 0为未选中状态；1为选中状态，默认值为：空
              StartTime VARCHAR(8) NOT NULL
                                   DEFAULT '00:00:00' ,			--开始时间格式：23:02:01 取值范围00:00:00至23:59:59 默认值为：00:00:00
              EndTime VARCHAR(8) NOT NULL
                                 DEFAULT '23:59:59' ,			--结束时间格式：23:02:01 取值范围00:00:00至23:59:59 默认值为：23:59:59
              SalePrice VARCHAR(25) NULL ,						--特价促销预设售价
              SaleType VARCHAR(1) NULL ,						--赠送促销类型取值范围：0或1  0代表按整单促销；1代表按单品促销 默认值为：空
              TotalMoney VARCHAR(18) NULL ,						--赠送促销合计金额
              Remark VARCHAR(100) NULL ,						--备注
              Checke VARCHAR(50) NULL ,						--审核人ID
              Breake VARCHAR(50) NULL ,						--中止人ID
              CheckeDateTime VARCHAR(20) NULL ,						--审核日期时间格式为:2010-02-22 15:22:18 存储审核或反审核的日期时间
              BreakeDateTime VARCHAR(20) NULL ,						--中止日期时间格式为:2010-02-22 15:22:18 存储中止或恢复的日期时间
              CONSTRAINT PK_CX_SALEPLANINDEX PRIMARY KEY ( BillNumberId )
            )
    END
GO

IF NOT EXISTS ( SELECT  1
                FROM    sysobjects
                WHERE   id = OBJECT_ID('CX_SaleByHand')
                        AND type = 'U' ) 
    BEGIN
/*==============================================================*/
/* Table: CX_SaleByHand   手工促销条件表                        */
/*==============================================================*/
        CREATE TABLE CX_SaleByHand
            (
              BillNumberId DECIMAL(9) NOT NULL ,					--单据ID关联主表表头单据ID，不能重复
              SaleType VARCHAR(1) NOT NULL
                                  DEFAULT '1' ,			--促销类型：1代表件数折；2代表买满折；3代表超额减  默认值为：1
              MoneyTicket VARCHAR(1) NULL
                                     DEFAULT '1' ,				--优惠类型：1代表现金；2代表券  默认值为：1
              GoodsPro VARCHAR(1) NULL ,					--商品属性：1:款式；2:面料；3:加工方式；4:品牌；5:季节 默认值为：空(为空时表示对所有商品有效)
              ChoosePro VARCHAR(100) NULL ,					--选择属性：对应商品的属性值，若商品属性字段为空，则此字段为空
              TotalMoney VARCHAR(20) NULL ,					--买满金额：仅对买满折和超额减两种促销类型有效
              TotalQty VARCHAR(20) NULL ,					--买满数量：仅对件数折的促销类型有效
              Discount VARCHAR(10) NULL ,					--折扣率：仅对件数折和买满折的促销类型有效
              RebateMoney VARCHAR(20) NULL ,					--折让金额：仅对超额减的促销类型有效
              MoneyAdd VARCHAR(1) NULL
                                  DEFAULT '0' ,				--金额累加：仅在超额减的促销类型中有效
              CONSTRAINT PK_CX_SALEBYHAND PRIMARY KEY ( BillNumberId )
            )
    END
GO


IF NOT EXISTS ( SELECT  1
                FROM    sysobjects
                WHERE   id = OBJECT_ID('CX_SaleStocksArea')
                        AND type = 'U' ) 
    BEGIN
/*==============================================================*/
/* Table: CX_SaleStocksArea 促销方案适用仓库表                  */
/*==============================================================*/
        CREATE TABLE CX_SaleStocksArea
            (
              BillNumberId NUMERIC(9) NOT NULL ,					--单据ID关联主表表头单据ID，允许重复
              KtypeId VARCHAR(50) NOT NULL ,					--仓库ID
              IsHQ VARCHAR(1) NOT NULL
                              DEFAULT '0'		--仓库类型：0代表总部仓库；1代表加盟商仓库 默认取值为：0
            )
    END
GO

/*lxw 促销单明细表*/
--特价促俏单
IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CX_SpecialOfferBill]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        CREATE TABLE [dbo].[CX_SpecialOfferBill]
            (
              [BillNumberId] [int] NOT NULL ,						-- 促销单Id
              [Row] [int] NOT NULL ,							-- 行号
              [PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                      NOT NULL ,		-- 商品Id
              [SalePrice] [numeric](18, 4) NULL ,					-- 参考售价
              [Discount] [numeric](18, 4) NULL ,					-- 折扣
              [DiscountPrice] [numeric](18, 4) NULL ,					-- 促销价
              [MemberIntegral] [numeric](18, 4) NULL ,				-- 会员积分
              [MemberPrice] [numeric](18, 4) NULL 					-- 会员特价
            )
        ON  [PRIMARY]
	
        ALTER TABLE [dbo].[CX_SpecialOfferBill] WITH NOCHECK ADD 
        CONSTRAINT [PK_CX_SpecialOfferBill] PRIMARY KEY  CLUSTERED 
        (
        [BillNumberId],
        [Row]
        )  ON [PRIMARY] 
	
        ALTER TABLE [dbo].[CX_SpecialOfferBill] ADD 
        CONSTRAINT [DF_CX_SpecialOfferBill_SalePrice] DEFAULT (0) FOR [SalePrice],
        CONSTRAINT [DF_CX_SpecialOfferBill_Discount] DEFAULT (1) FOR [Discount],
        CONSTRAINT [DF_CX_SpecialOfferBill_DiscountPrice] DEFAULT (0) FOR [DiscountPrice],
        CONSTRAINT [DF_CX_SpecialOfferBill_SPIntegral] DEFAULT (0) FOR [MemberIntegral],
        CONSTRAINT [DF_CX_SpecialOfferBill_MemberPrice] DEFAULT (0) FOR [MemberPrice]
    END
GO

--赠品促销单
IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CX_LargessBill]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        CREATE TABLE [dbo].[CX_LargessBill]
            (
              [BillNumberId] [int] NOT NULL ,						-- 促销单Id
              [Row] [int] NOT NULL ,							-- 销售商品行号
              [PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                      NOT NULL ,		-- 销售商品Id
              [Qty] [numeric](18, 4) NULL ,						-- 销售商品数量
              [LargessRow] [int] NOT NULL ,						-- 赠品行号
              [LargessPtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                             NULL ,	-- 赠品Id
              [LargessAddTotal] [numeric](18, 4) NULL ,				-- 赠品加值额
              [LargessQty] [numeric](18, 4) NULL 					-- 赠品数量
            )
        ON  [PRIMARY]
	
        ALTER TABLE [dbo].[CX_LargessBill] WITH NOCHECK ADD 
        CONSTRAINT [PK_CX_LargessBill] PRIMARY KEY  CLUSTERED 
        (
        [BillNumberId],
        [Row],
        [LargessRow]
        )  ON [PRIMARY] 
	
        ALTER TABLE [dbo].[CX_LargessBill] ADD 
        CONSTRAINT [DF_CX_LargessBill_Qty] DEFAULT (0) FOR [Qty],
        CONSTRAINT [DF_CX_LargessBill_LargessTotal] DEFAULT (0) FOR [LargessAddTotal],
        CONSTRAINT [DF_CX_LargessBill_LargessQty] DEFAULT (0) FOR [LargessQty]
	
        CREATE  INDEX [IX_CX_LargessBill] ON [dbo].[CX_LargessBill]([PtypeId], [LargessPtypeId]) ON [PRIMARY]
    END
GO


--组合促销单
IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CX_CombinationBill]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        CREATE TABLE [dbo].[CX_CombinationBill]
            (
              [BillNumberId] [int] NOT NULL ,						-- 促销单Id
              [Row] [int] NOT NULL ,							-- 组合新商品行号
              [UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS
                                       NULL ,		-- 组合新商品编号
              [FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS
                                       NULL ,		-- 组合新商品全名
              [EntryCode] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                        NULL ,		-- 组合新商品条码
              [SalePrice] [numeric](18, 4) NULL ,					-- 组合新商品参考售价
              [Discount] [numeric](18, 4) NULL ,					-- 组合新商品折扣
              [DiscountPrice] [numeric](18, 4) NULL ,					-- 组合新商品促销价
              [MemberPrice] [numeric](18, 4) NULL 					-- 组合新商品会员特价
            )
        ON  [PRIMARY]
	
        ALTER TABLE [dbo].[CX_CombinationBill] WITH NOCHECK ADD 
        CONSTRAINT [PK_CX_CombinationBill] PRIMARY KEY  CLUSTERED 
        (
        [BillNumberId],
        [Row]
        )ON [PRIMARY] 
	
        ALTER TABLE [dbo].[CX_CombinationBill] ADD 
        CONSTRAINT [DF_CX_CombinationBill_SalePrice] DEFAULT (0) FOR [SalePrice],
        CONSTRAINT [DF_CX_CombinationBill_Discount] DEFAULT (1) FOR [Discount],
        CONSTRAINT [DF_CX_CombinationBill_DiscountPrice] DEFAULT (0) FOR [DiscountPrice],
        CONSTRAINT [DF_CX_CombinationBill_MemberPrice] DEFAULT (0) FOR [MemberPrice]

        CREATE  INDEX [IX_CX_CombinationBill] ON [dbo].[CX_CombinationBill]([EntryCode]) ON [PRIMARY]
    END
GO

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[CX_CombinationDetailBill]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        CREATE TABLE [dbo].[CX_CombinationDetailBill]
            (
              [BillNumberId] [int] NOT NULL ,						-- 促销单Id
              [Row] [int] NOT NULL ,							-- 组合新商品行号
              [DetailRow] [int] NOT NULL ,						-- 组合成份商品行号
              [PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                      NOT NULL ,		-- 组合成份商品
              [Qty] [numeric](18, 4) NULL ,						-- 组合成份商品数量
              [SalePrice] [numeric](18, 4) NULL ,					-- 组合成份商品参考售价
              [Discount] [numeric](18, 4) NULL ,					-- 组合成份商品折扣
              [DiscountPrice] [numeric](18, 4) NULL ,					-- 组合成份商品促销价
              [MemberPrice] [numeric](18, 4) NULL 					-- 组合成份商品会员特价
            )
        ON  [PRIMARY]
	
        ALTER TABLE [dbo].[CX_CombinationDetailBill] WITH NOCHECK ADD 
        CONSTRAINT [PK_CX_CombinationDetailBill] PRIMARY KEY  CLUSTERED 
        (
        [BillNumberId],
        [Row],
        [DetailRow]
        )  ON [PRIMARY] 
	
        ALTER TABLE [dbo].[CX_CombinationDetailBill] ADD 
        CONSTRAINT [DF_CX_CombinationDetailBill_Qty] DEFAULT (0) FOR [Qty],
        CONSTRAINT [DF_CX_CombinationDetailBill_SalePrice] DEFAULT (0) FOR [SalePrice],
        CONSTRAINT [DF_CX_CombinationDetailBill_Discount] DEFAULT (1) FOR [Discount],
        CONSTRAINT [DF_CX_CombinationDetailBill_DiscountPrice] DEFAULT (0) FOR [DiscountPrice],
        CONSTRAINT [DF_CX_CombinationDetailBill_MemberPrice] DEFAULT (0) FOR [MemberPrice]
	
        CREATE  INDEX [IX_CX_CombinationDetailBill] ON [dbo].[CX_CombinationDetailBill]([PtypeId]) ON [PRIMARY]
	
--本地去除主外键约束
-- 	ALTER TABLE [dbo].[CX_CombinationDetailBill] ADD 
-- 		CONSTRAINT [FK_CX_CombinationDetailBill_CX_CombinationBill] FOREIGN KEY 
-- 		(
-- 			[BillNumberId],
-- 			[Row]
-- 		) REFERENCES [dbo].[CX_CombinationBill] (
-- 			[BillNumberId],
-- 			[Row]
-- 		) ON DELETE CASCADE  ON UPDATE CASCADE 
    END
GO
	
/*lxw 促销单明细表*/


------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------
-------------------------促销表结束
-----------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationDetailBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationDetailBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_SpecialOfferBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_SpecialOfferBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationDetailBill' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationDetailBill 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                              
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationBill' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationBill 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                                            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_SpecialOfferBill' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_SpecialOfferBill 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                     
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationDetailBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationDetailBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                                  
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                                      
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_SpecialOfferBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_SpecialOfferBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                         
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_SpecialOfferBill' AND a.Name='MemberIntegral' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_SpecialOfferBill 
	ALTER COLUMN MemberIntegral NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationDetailBill' AND a.Name='MemberPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationDetailBill 
	ALTER COLUMN MemberPrice NUMERIC(24,10)
    END
                
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationBill' AND a.Name='MemberPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationBill 
	ALTER COLUMN MemberPrice NUMERIC(24,10)
    END
                
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_SpecialOfferBill' AND a.Name='MemberPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_SpecialOfferBill 
	ALTER COLUMN MemberPrice NUMERIC(24,10)
    END
                                                           
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_LargessBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_LargessBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                                            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_CombinationDetailBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_CombinationDetailBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_LargessBill' AND a.Name='LargessAddTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_LargessBill 
	ALTER COLUMN LargessAddTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CX_LargessBill' AND a.Name='LargessQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CX_LargessBill 
	ALTER COLUMN LargessQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[SaleTime]    Script Date: 06/24/2011 10:00:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SaleTime]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SaleTime]          --时间表
(
	[ID] [int] identity (1,1),              ---时间ID
    [TotalID] [int] null,                      --时间总表ID
	[PeriodTime] [varchar](200) NULL,           --时间段
	[StartTime] [datetime] NULL,               --开始时间
	[EndTime] [datetime] NULL,                 --结束时间
	[Days] [int] NULL                          --天数
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[SaleTimeTotal]    Script Date: 07/19/2011 09:28:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SaleTimeTotal]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SaleTimeTotal](
	[ID] [int]	IDENTITY(1,1) NOT NULL,
	[FullName]	[varchar](400) NULL,
	[Years]		[varchar](10) NULL,
	[Comment]	[varchar](800) NULL,
	[IfAudit]	[bit] NULL,
	[IfUse]		[tinyint] NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Scheme]    脚本日期: 2011-12-8 10:48 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Scheme]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Scheme](
		SchemeId		DECIMAL(18,0) IDENTITY(1,1),
		ETypeID		VARCHAR(50) NOT NULL,--职员
		ReportName	VARCHAR(500),--报表名称
		SchemeName	VARCHAR(500),  --方案名称
		IsDefault	INT default(0),--是否默认方案 
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[Scheme]') AND name = 'inputtype' )
BEGIN
	
	ALTER TABLE dbo.Scheme ADD
		inputtype varchar(200) NULL
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--跨年账配置明细表
--2014--06-10  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SchemeConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE SchemeConfig
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	SchemeID		NUMERIC(18,0) NOT NULL ,--查询方案ID
	IP				VARCHAR(50)   NOT NULL,				--服务器IP
	Port			VARCHAR(50)	  NOT NULL DEFAULT('1433'),	--数据库端口
	instancename	VARCHAR(100)  NULL DEFAULT(''),	--数据库实例名
	ConName			VARCHAR(100)  NOT NULL,				--数据库连接名称
	ConPwd			VARCHAR(100)  NOT NULL DEFAULT(''),	--数据库连接密码
	DbName			VARCHAR(256) NOT NULL,				--数据库名称
	IsDefault		INT,					----1为默认
	CreateTime		DATETIME NOT NULL,		--创建时间
	CreateID		VARCHAR(50) NOT NULL	--创建人
)
END

GO

------------------------------------------表修改区域-开始-------------------------------------------------
IF NOT EXISTS (select name from syscolumns where id = object_id(N'[dbo].[SchemeConfig]') and name = 'Port' )
BEGIN
 ALTER TABLE dbo.SchemeConfig ADD
  Port VARCHAR(50) DEFAULT '1433' WITH VALUES 
END
GO

IF NOT EXISTS (select name from syscolumns where id = object_id(N'[dbo].[SchemeConfig]') and name = 'instancename' )
BEGIN
 ALTER TABLE dbo.SchemeConfig ADD
  instancename VARCHAR(100) DEFAULT '' WITH VALUES 
END
GO
------------------------------------------表修改区域-结束-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SchemeDetail]    脚本日期: 2011-12-8 10:48 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SchemeDetail]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SchemeDetail](
		nId				DECIMAL(18,0) IDENTITY(1,1),
		SchemeId			DECIMAL(18,0) NOT NULL,
		DataField		VARCHAR(200)  NOT NULL,
		DataValue		VARCHAR(3000),
		DataText		VARCHAR(500),
		ControlType	VARCHAR(200),--控件类型
		BaseType		VARCHAR(100)
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[SchemeDetail]') and  name = 'DataValue' and length=3000)
BEGIN
	 ALTER TABLE SchemeDetail
	    ALTER COLUMN DataValue VARCHAR(MAX) NOT NULL
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--跨年账配置主表
--2014--06-10  wg
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SchemeIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE SchemeIndex
(
	ID				NUMERIC(18,0) IDENTITY(1,1),
	SchemeName		VARCHAR(256)  NOT NULL,				--方案名称
	SchemeExplain	VARCHAR(256)  NOT NULL DEFAULT(''),	--方案描述
	IsDefault		INT	NOT NULL DEFAULT(0),			--1为默认
	RuleType		INT	NOT NULL DEFAULT(0),			--规则类型: 0=系统规则,1=自定义规则的编码, 2=自定义规则的名称 , 3=自定义规则的编码和名称
	CreateTime		DATETIME NOT NULL,		--创建时间
	CreateID		VARCHAR(50) NOT NULL	--创建人
)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF not exists (select name from syscolumns where id = object_id(N'[dbo].[SchemeIndex]') and name = 'RuleType' )
BEGIN
	ALTER TABLE dbo.SchemeIndex ADD 
				RuleType INT NOT NULL DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SendBackBill]') AND type in (N'U'))
BEGIN
/****** Object:  Table [dbo].[SendBackBill]    Script Date: 05/04/2015 17:17:48 ******/

	CREATE TABLE [dbo].[SendBackBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NOT NULL,
		[discount] [numeric](18, 4) NOT NULL,
		[DiscountPrice] [numeric](18, 4) NULL,
		[total] [numeric](18, 4) NOT NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[Serial] [varchar](max) NULL,
		[OldID] numeric(10,0) NULL,
		[CostPrice] [numeric](18, 4) NULL,
		[OldBillNumberID] numeric(10,0) NULL,
		[InputCostPrice] [numeric](18, 4) NULL,
		[GoodsOrder] [int] NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](18, 4) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](18, 4) NULL,
		[Tax] [numeric](5, 2) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney] [numeric](22, 10) NULL,
		[NSalePrice] [numeric](22, 10) NULL,
		[NSaleTotal] [numeric](22, 10) NULL,
		[NDiscountPrice] [numeric](22, 10) NULL,
		[NTotal] [numeric](22, 10) NULL,
		[NTaxPrice] [numeric](22, 10) NULL,
		[NTaxTotal] [numeric](22, 10) NULL,
		[NTaxMoney] [numeric](22, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](22, 10) NULL,
		[UnitRate] [numeric](22, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](22, 10) NULL,
		[MUnitRate] [numeric](22, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](22, 10) NULL,
		[MDiscountPrice] [numeric](22, 10) NULL,
		[MTaxPrice] [numeric](22, 10) NULL,
		[CurMSalePrice] [numeric](22, 10) NULL,
		[CurMDiscountPrice] [numeric](22, 10) NULL,
		[CurMTaxPrice] [numeric](22, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[InvoiceQty] [numeric](18, 4) NULL,
		[InvoiceMoney] [numeric](22, 10) NULL,
		[NInvoiceMoney] [numeric](22, 10) NULL,
		[IsGift] [int] NULL,
		[ReferPrice] [numeric](18, 4) NOT NULL,
		[PriceStyle] [int] NOT NULL,
		[InvoiceMoneyEX] [numeric](22, 10) NULL,
		[NInvoiceMoneyEX] [numeric](22, 10) NULL,
		[InvoiceCostTotal] [numeric](22,10) NULL,
		[InvoiceNQty] [numeric](18, 4) NULL,
		[CostTotal]  [numeric](22, 10) NULL,
		[InvoiceSaleMoney] [numeric](22,10) NULL,
		[NInvoiceSaleMoney] [numeric](22,10) NULL,
		[ShowOrder] INT DEFAULT(0),
		[InflowQty] NUMERIC(24,10) NULL DEFAULT(0) ,--入库数量
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
	    PriceSource VARCHAR(200)
	) ON [PRIMARY]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_SalePrice]  DEFAULT ((0)) FOR [SalePrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_discount]  DEFAULT ((1)) FOR [discount]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_DiscountPrice]  DEFAULT ((0)) FOR [DiscountPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_total]  DEFAULT ((0)) FOR [total]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_TaxPrice]  DEFAULT ((0)) FOR [TaxPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_TaxTotal]  DEFAULT ((0)) FOR [TaxTotal]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_Serial]  DEFAULT ('') FOR [Serial]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_OldID]  DEFAULT ('') FOR [OldID]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_CostPrice]  DEFAULT ((0)) FOR [CostPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_OldBillNumberID]  DEFAULT ((0)) FOR [OldBillNumberID]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_InputCostPrice]  DEFAULT ((0)) FOR [InputCostPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_odsOrder]  DEFAULT ('-1') FOR [GoodsOrder]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_odsNumber]  DEFAULT ('') FOR [GoodsNumber]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_ProduceDate]  DEFAULT ('') FOR [ProduceDate]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_ValidDate]  DEFAULT ('') FOR [ValidDate]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_odsCostPrice]  DEFAULT ((0)) FOR [GoodsCostPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_HandZeroCost]  DEFAULT ((0)) FOR [HandZeroCost]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_SaleTotal]  DEFAULT ((0)) FOR [SaleTotal]

	ALTER TABLE [dbo].[SendBackBill] ADD  CONSTRAINT [DF_SendBackBill_Tax]  DEFAULT ((0)) FOR [Tax]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ('') FOR [Stypeid]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [TaxMoney]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NSalePrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NSaleTotal]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NDiscountPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NTotal]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NTaxPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NTaxTotal]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NTaxMoney]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [UnitID]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NUnitID]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NQty]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [UnitRate]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [MUnitID]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [MQty]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((1)) FOR [MUnitRate]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [MSalePrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [MDiscountPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [MTaxPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [CurMSalePrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [CurMDiscountPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [CurMTaxPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [CargoID]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [InvoiceQty]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [InvoiceMoney]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NInvoiceMoney]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [IsGift]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [ReferPrice]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [PriceStyle]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [InvoiceMoneyEX]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NInvoiceMoneyEX]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [InvoiceCostTotal]
	
	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [InvoiceNQty]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [InvoiceSaleMoney]

	ALTER TABLE [dbo].[SendBackBill] ADD  DEFAULT ((0)) FOR [NInvoiceSaleMoney]
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE SendBackBill ADD PriceSource   VARCHAR(200)
END
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SendBackBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.SendBackBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SendBackBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.SendBackBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SendBackBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.SendBackBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SendBackBill SET InflowQty=0 WHERE InflowQty IS NULL
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SendBackBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.SendBackBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SendBackBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='ShareFee'
)
BEGIN
		ALTER TABLE SendBackBill ADD [ShareFee] [numeric](22, 10) NULL DEFAULT(0)
END
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'SendBackBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.SendBackBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.SendBackBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='InvoiceMoneyEX' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN InvoiceMoneyEX NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NInvoiceMoneyEX' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NInvoiceMoneyEX NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='InvoiceCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN InvoiceCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='InvoiceNQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN InvoiceNQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='InvoiceSaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN InvoiceSaleMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='NInvoiceSaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN NInvoiceSaleMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBackBill' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBackBill 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBackBill') AND name = 'CIX_SendBackBill_BillNumberID')
CREATE NONCLUSTERED INDEX CIX_SendBackBill_BillNumberID ON SendBackBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBackBill') AND name = 'CIX_SendBackBill_PTypeId')
CREATE NONCLUSTERED INDEX CIX_SendBackBill_PTypeId ON SendBackBill(PTypeId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBackBill') AND name = 'CIX_SendBackBill_KTypeId')
CREATE NONCLUSTERED INDEX CIX_SendBackBill_KTypeId ON SendBackBill(KTypeID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBackBill') AND name = 'CIX_SendBackBill_STypeId')
CREATE NONCLUSTERED INDEX CIX_SendBackBill_STypeId ON SendBackBill(STypeId)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBackBill') AND name = 'CIX_SendBackBill_Id')
CREATE NONCLUSTERED INDEX CIX_SendBackBill_Id ON SendBackBill(Id)
------------------------------------------创建索引区域结束-----------------------------------------------

GO 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SendBill]') AND type in (N'U'))
BEGIN
/****** Object:  Table [dbo].[SendBill]    Script Date: 05/04/2015 17:17:48 ******/

	CREATE TABLE [dbo].[SendBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL,
		[discount] [numeric](18, 4) NULL,
		[DiscountPrice] [numeric](18, 4) NULL,
		[costprice] [numeric](18, 4) NULL,
		[total] [numeric](18, 4) NULL,
		[TaxPrice] [numeric](18, 4) NULL,
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) NULL,
		[OrderID] [int] NULL,
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[Serial] [varchar](max) NULL,
		[InputCostPrice] [numeric](18, 4) NULL,
		[GoodsOrder] [int] NULL,
		[BackQty] [numeric](18, 4) NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](18, 4) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](18, 4) NULL,
		[Tax] [numeric](5, 2) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[ShareFee] [numeric](22, 10) NULL,
		[TaxMoney] [numeric](22, 10) NULL,
		[NSalePrice] [numeric](22, 10) NULL,
		[NSaleTotal] [numeric](22, 10) NULL,
		[NDiscountPrice] [numeric](22, 10) NULL,
		[NTotal] [numeric](22, 10) NULL,
		[NTaxPrice] [numeric](22, 10) NULL,
		[NTaxTotal] [numeric](22, 10) NULL,
		[NTaxMoney] [numeric](22, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](22, 10) NULL,
		[UnitRate] [numeric](22, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](22, 10) NULL,
		[MUnitRate] [numeric](22, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](22, 10) NULL,
		[MDiscountPrice] [numeric](22, 10) NULL,
		[MTaxPrice] [numeric](22, 10) NULL,
		[CurMSalePrice] [numeric](22, 10) NULL,
		[CurMDiscountPrice] [numeric](22, 10) NULL,
		[CurMTaxPrice] [numeric](22, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[entryCode] [varchar](200) NULL,
		[InvoiceQty] [numeric](18, 4) NULL,
		[InvoiceMoney] [numeric](22, 10) NULL,
		[NInvoiceMoney] [numeric](22, 10) NULL,
		[PriceSource] [varchar](200) NULL,
		[IsGift] [int] NOT NULL,
		[ReferPrice] [numeric](18, 4) NOT NULL,
		[PriceStyle] [int] NOT NULL,
		[InvoiceMoneyEX] [numeric](22, 10) NULL,
		[NInvoiceMoneyEX] [numeric](22, 10) NULL,
		[InvoiceCostTotal] [numeric](22,10) NULL,
		[OldID]	numeric(10,0) NULL,
		[OldBillNumberID] numeric(10,0) NULL,
		[InvoiceNQty] [numeric](18, 4) NULL,
		[CostTotal]  [numeric](22, 10) NULL,
		[InvoiceSaleMoney] [numeric](22,10) NULL,
		[NInvoiceSaleMoney] [numeric](22,10) NULL,
		[ShowOrder]	 INT DEFAULT(0)
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0), --拣货数量
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
		ClearQty NUMERIC(24,10)	NOT NULL DEFAULT (0)--解锁数量
	) ON [PRIMARY]
		
	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_SalePrice]  DEFAULT ((0)) FOR [SalePrice]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_discount]  DEFAULT ((1)) FOR [discount]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_DiscountPrice]  DEFAULT ((0)) FOR [DiscountPrice]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_costprice]  DEFAULT ((0)) FOR [costprice]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_total]  DEFAULT ((0)) FOR [total]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_TaxPrice]  DEFAULT ((0)) FOR [TaxPrice]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_OrderID]  DEFAULT ('-1') FOR [OrderID]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_Serial]  DEFAULT ('') FOR [Serial]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_InputCostPrice]  DEFAULT ((0)) FOR [InputCostPrice]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_odsOrder]  DEFAULT ('-1') FOR [GoodsOrder]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_BackQty]  DEFAULT ((0)) FOR [BackQty]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_odsNumber]  DEFAULT ('') FOR [GoodsNumber]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_ProduceDate]  DEFAULT ('') FOR [ProduceDate]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_ValidDate]  DEFAULT ('') FOR [ValidDate]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_odsCostPrice]  DEFAULT ((0)) FOR [GoodsCostPrice]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_HandZeroCost]  DEFAULT ((0)) FOR [HandZeroCost]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_SaleTotal]  DEFAULT ((0)) FOR [SaleTotal]

	ALTER TABLE [dbo].[SendBill] ADD  CONSTRAINT [DF_SendBill_Tax]  DEFAULT ((0)) FOR [Tax]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ('') FOR [Stypeid]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [ShareFee]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [TaxMoney]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NSalePrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NSaleTotal]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NDiscountPrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NTotal]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NTaxPrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NTaxTotal]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NTaxMoney]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [UnitID]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NUnitID]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NQty]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [UnitRate]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [MUnitID]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [MQty]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((1)) FOR [MUnitRate]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [MSalePrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [MDiscountPrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [MTaxPrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [CurMSalePrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [CurMDiscountPrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [CurMTaxPrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [CargoID]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ('') FOR [entryCode]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [InvoiceQty]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [InvoiceMoney]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NInvoiceMoney]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [IsGift]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [ReferPrice]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [PriceStyle]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [InvoiceMoneyEX]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NInvoiceMoneyEX]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [InvoiceCostTotal]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [InvoiceNQty]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [InvoiceSaleMoney]

	ALTER TABLE [dbo].[SendBill] ADD  DEFAULT ((0)) FOR [NInvoiceSaleMoney]
END

SET ANSI_PADDING OFF
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SendBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.SendBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'SendBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.SendBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SendBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE SendBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE SendBill SET PickedQty=0 WHERE PickedQty IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE SendBill ADD [SendedQty] DECIMAL(24, 10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SendBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.SendBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.SendBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO


--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'SendBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.SendBill
	ADD ShowOrder INT  DEFAULT(0)
END
GO
	UPDATE dbo.SendBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SendBill',N'U') AND Name='ClearQty')
BEGIN
	ALTER TABLE dbo.SendBill
	ADD ClearQty NUMERIC(24,10) NOT NULL DEFAULT(0)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='InvoiceMoneyEX' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN InvoiceMoneyEX NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NInvoiceMoneyEX' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NInvoiceMoneyEX NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='InvoiceCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN InvoiceCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='InvoiceNQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN InvoiceNQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='InvoiceSaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN InvoiceSaleMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SendBill' AND a.Name='NInvoiceSaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SendBill 
	ALTER COLUMN NInvoiceSaleMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO 
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBill') AND name = 'CIX_SendBill_BillNumberID')
CREATE NONCLUSTERED INDEX CIX_SendBill_BillNumberID ON SendBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBill') AND name = 'CIX_SendBill_PTypeId')
CREATE NONCLUSTERED INDEX CIX_SendBill_PTypeId ON SendBill(PTypeId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBill') AND name = 'CIX_SendBill_KTypeId')
CREATE NONCLUSTERED INDEX CIX_SendBill_KTypeId ON SendBill(KTypeID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBill') AND name = 'CIX_SendBill_OrderId')
CREATE NONCLUSTERED INDEX CIX_SendBill_OrderId ON SendBill(OrderId)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBill') AND name = 'CIX_SendBill_STypeId')
CREATE NONCLUSTERED INDEX CIX_SendBill_STypeId ON SendBill(STypeId)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SendBill') AND name = 'CIX_SendBill_Id')
CREATE NONCLUSTERED INDEX CIX_SendBill_Id ON SendBill(Id)
------------------------------------------创建索引区域结束-----------------------------------------------
GO 



/****** 对象:  Table [dbo].[SerialAdjustBill]    脚本日期: 05/05/2010 14:47:39 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SerialAdjustBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SerialAdjustBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
		[OldSerial] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,
		[KtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID1] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[BTypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[InKtypeTime] [datetime] NULL,
		[OutKtypeTime] [datetime] NULL,
		[State] [int] NOT NULL DEFAULT (1),
		[Note] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		sameSearilID INT NULL,
		BillId	 INT NULL,	--上一张涉及此序列号的单据实际过账顺序id
		ShowOrder INT DEFAULT(0)
			) ON [PRIMARY]


END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SerialAdjustBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.SerialAdjustBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE SerialAdjustBill SET ShowOrder=ID WHERE ShowOrder IS NULL
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[SerialAdjustBill]') and name = 'BillNumberID' )
BEGIN
	
	ALTER TABLE dbo.SerialAdjustBill ADD
		BillNumberID [numeric](10, 0) NOT NULL
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[SerialAdjustBill]') and name = 'BillId' )
BEGIN
	
	ALTER TABLE dbo.SerialAdjustBill ADD
		BillId INT  NULL
END
GO


if not exists (select name from syscolumns where id = object_id(N'[dbo].[SerialAdjustBill]') and name = 'Serial' )
BEGIN
	
	ALTER TABLE dbo.SerialAdjustBill ADD
		Serial	VARCHAR(60) NULL,
		OldSerial VARCHAR(60) NULL
END
GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[SerialAdjustBill]') and  name = 'Serial' and Length=60)
BEGIN
	 ALTER TABLE SerialAdjustBill
	    ALTER COLUMN Serial VARCHAR(1000)
END
GO 

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[SerialAdjustBill]') and  name = 'OldSerial' and Length=60)
BEGIN
	 ALTER TABLE SerialAdjustBill
	    ALTER COLUMN OldSerial VARCHAR(1000)
END
GO 
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SerialAdjustIndex]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SerialAdjustIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SerialAdjustIndex](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT (''),
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0'),
		[dtypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0'),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0'),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0'),
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT ('0'),
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL		 DEFAULT ('t'),
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalqty] [numeric](18, 4) NULL   DEFAULT (0),
		[period] [smallint] NULL  DEFAULT (0),
		[explain] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL  DEFAULT (''),
		[RedWord] [int] NOT NULL   DEFAULT (0),
		[draft] [bit] NOT NULL   DEFAULT (0),
		[Poster] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[LastUpdateTime] DateTime NULL CONSTRAINT [DF_SerialAdjustIndex_LastUpdateTime]  DEFAULT GETDATE(),
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SerialAdjustIndex' AND a.Name='LastUpdateTime'
)
BEGIN
	ALTER TABLE SerialAdjustIndex ADD LastUpdateTime DateTime NULL CONSTRAINT [DF_SerialAdjustIndex_LastUpdateTime]  DEFAULT GETDATE()
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SerialAdjustIndex' AND a.Name='dtypeid'
)
BEGIN
	ALTER TABLE SerialAdjustIndex ADD dtypeid VARCHAR(50) NULL DEFAULT('0')
END

GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SerialAdjustIndex' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SerialAdjustIndex 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[ServerDbs]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [ServerDbs](
		serverdbId INT IDENTITY(1,1) PRIMARY KEY
		,[name] NVARCHAR(100) NOT NULL DEFAULT('')
		,[ip] VARCHAR(30) NOT NULL DEFAULT('')
		,[pcName] VARCHAR(100) NOT NULL DEFAULT('')
		,[dbName] VARCHAR(100) NOT NULL DEFAULT('')
		,[dbLogin] VARCHAR(100) NOT NULL DEFAULT('')
		,[dbPwd] VARCHAR(100) NOT NULL DEFAULT('')
		,[connectionString] VARCHAR(1000) NOT NULL
	)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ServerDbs' AND a.Name='dbLogin'
)
BEGIN
	ALTER TABLE [ServerDbs] ADD [dbLogin] VARCHAR(100) NOT NULL DEFAULT('');
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ServerDbs' AND a.Name='dbPwd'
)
BEGIN
	ALTER TABLE [ServerDbs] ADD [dbPwd] VARCHAR(100) NOT NULL DEFAULT('');
END
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ShareFeeBill]    脚本日期: 05/05/2010 14:46:51 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ShareFeeBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ShareFeeBill](
		[BillNumberId]			[numeric](10, 0) NOT NULL,
		[BillType]				[int]	NOT NULL,
		[FromBillNumberID]		[numeric](10, 0) NOT NULL,
		[FromBillID]			[numeric](10, 0) NOT NULL,
		[ID]					[int] IDENTITY(1,1) NOT NULL,
		[Comment]				[varchar](500) DEFAULT('')
		,ShowOrder INT DEFAULT(0)
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ShareFeeBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.ShareFeeBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.ShareFeeBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ShareSourceBill]    脚本日期: 05/05/2010 14:46:51 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ShareSourceBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ShareSourceBill](
		[BillNumberId]			[numeric](10, 0) NOT NULL,
		[BillType]				[int]	NOT NULL,
		[FromBillNumberID]		[numeric](10, 0) NOT NULL,
		[FromBillID]			[numeric](10, 0) NOT NULL,
		[FromBillType]			[int]	NOT NULL,
		[ID]					[int] IDENTITY(1,1) NOT NULL,
		[ShareFee]				[numeric](18, 2) NOT NULL DEFAULT 0,
		[Comment]				[varchar](500) DEFAULT('')
		,ShowOrder INT DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO


------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'ShareSourceBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.ShareSourceBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'ShareSourceBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.ShareSourceBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ShareSourceBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.ShareSourceBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.ShareSourceBill SET ShowOrder=ID WHERE ShowOrder=ID OR ShowOrder IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ShareSourceBill' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ShareSourceBill 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sms_Account]    脚本日期: 05/05/2010 14:49:06 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sms_Account]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sms_Account](
		[Account] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[PassWord] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[DBName] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[IsRun] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[Interal] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SMS_ALARMMAXVCH]    脚本日期: 05/05/2010 14:49:07 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SMS_ALARMMAXVCH]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SMS_ALARMMAXVCH](
		[ALARMRULEID] [int] NULL,
		[MAXVCHCODE] [numeric](10, 0) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Sms_AlarmSendRule]    脚本日期: 05/05/2010 14:49:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Sms_AlarmSendRule]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Sms_AlarmSendRule](
		[RuleID] [int] IDENTITY(1,1) NOT NULL,
		[VchType] [int] NULL,
		[RuleName] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[Phones] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[AlarmNum] [numeric](18, 2) NULL,
		[AlarmType] [int] NULL CONSTRAINT [DF_AlarmSendRule_AlarmType]  DEFAULT (0),
		[SendCount] [int] NULL CONSTRAINT [DF_AlarmSendRule_SendCount]  DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Sms_AlarmSendRule' AND a.Name='Phones' and a.xtype=35
)
BEGIN
	ALTER TABLE Sms_AlarmSendRule ALTER COLUMN Phones VARCHAR(MAX)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Sms_AlarmSendRule]') AND name = N'PK_AlarmSendRule')
ALTER TABLE [dbo].[Sms_AlarmSendRule] DROP CONSTRAINT [PK_AlarmSendRule]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SMS_ALARMSENDRULE') AND name = 'CIX_SMS_ALARMSENDRULE_RuleID')
--DROP INDEX CIX_SMS_ALARMSENDRULE_RuleID ON SMS_ALARMSENDRULE 
CREATE CLUSTERED INDEX CIX_SMS_ALARMSENDRULE_RuleID ON SMS_ALARMSENDRULE(RuleID) 


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Sms_AlarmSendRule' AND a.Name='AlarmNum' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Sms_AlarmSendRule 
	ALTER COLUMN AlarmNum NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Sms_AlarmVchDefine]    脚本日期: 05/05/2010 14:49:09 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Sms_AlarmVchDefine]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Sms_AlarmVchDefine](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[VchType] [int] NULL,
		[VchName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Sms_AlarmVchDefine]') AND name = N'PK_Sms_AlarmVchDefine')
ALTER TABLE [dbo].[Sms_AlarmVchDefine] DROP CONSTRAINT [PK_Sms_AlarmVchDefine]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SMS_ALARMVCHDEFINE') AND name = 'CIX_SMS_ALARMVCHDEFINE_ID')
--DROP INDEX CIX_SMS_ALARMVCHDEFINE_ID ON SMS_ALARMVCHDEFINE 
CREATE CLUSTERED INDEX CIX_SMS_ALARMVCHDEFINE_ID ON SMS_ALARMVCHDEFINE(ID) 



------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sms_BaseInfoMobile]    脚本日期: 05/05/2010 14:49:09 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sms_BaseInfoMobile]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sms_BaseInfoMobile](
		[Id] [int] IDENTITY(1,1) NOT NULL,
		[nType] [int] NULL,
		[TypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Mobile] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SMS_CODEMOBIL_SET]    脚本日期: 05/05/2010 14:49:10 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SMS_CODEMOBIL_SET]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SMS_CODEMOBIL_SET](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[QRYCODE] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[MOBIL] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SMS_GROUPCODE_SET]    脚本日期: 05/05/2010 14:49:11 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SMS_GROUPCODE_SET]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SMS_GROUPCODE_SET](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[GID] [int] NOT NULL,
		[QRYCODE] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SMS_GROUPMOBIL_SET]    脚本日期: 05/05/2010 14:49:12 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SMS_GROUPMOBIL_SET]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SMS_GROUPMOBIL_SET](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[GID] [int] NOT NULL,
		[MOBIL] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SMS_GROUPNAME_SET]    脚本日期: 05/05/2010 14:49:13 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SMS_GROUPNAME_SET]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SMS_GROUPNAME_SET](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[GNAME] [varchar](30) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sms_log]    脚本日期: 05/05/2010 14:49:14 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sms_log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sms_log](
		[LogID] [int] IDENTITY(1,1) NOT NULL,
		[nType] [int] NULL,
		[MOBIL] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[OperID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[SendTime] [datetime] NOT NULL,
		[Content] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[SendId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Deleted] [int] NULL CONSTRAINT [DF_sms_log_Deleted]  DEFAULT ('0')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Sms_MessageRevice]    脚本日期: 05/05/2010 14:49:15 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Sms_MessageRevice]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Sms_MessageRevice](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[PhoneNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[RecvTime] [datetime] NULL,
		[Content] [varchar](1000) COLLATE Chinese_PRC_CI_AS NULL,
		[SendID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfRead] [int] NULL CONSTRAINT [DF_Sms_MessageRevice_IfRead]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Sms_MessageRevice]') AND name = N'PK_Sms_MessageRevice')
ALTER TABLE [dbo].[Sms_MessageRevice] DROP CONSTRAINT [PK_Sms_MessageRevice]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SMS_MESSAGEREVICE') AND name = 'CIX_SMS_MESSAGEREVICE_ID')
--DROP INDEX CIX_SMS_MESSAGEREVICE_ID ON SMS_MESSAGEREVICE 
CREATE CLUSTERED INDEX CIX_SMS_MESSAGEREVICE_ID ON SMS_MESSAGEREVICE(ID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sms_QueryCode_Set]    脚本日期: 05/05/2010 14:49:16 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sms_QueryCode_Set]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sms_QueryCode_Set](
		[CodeID] [int] IDENTITY(1,1) NOT NULL,
		[QryCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[VERSION] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[QRYNAME] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PROCNAME] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Params] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[STATE] [int] NULL,
		[CONTENT] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [text] COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='sms_QueryCode_Set' AND a.Name='CONTENT' and a.xtype=35
)
BEGIN
	ALTER TABLE sms_QueryCode_Set ALTER COLUMN CONTENT VARCHAR(MAX)
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='sms_QueryCode_Set' AND a.Name='Comment' and a.xtype=35
)
BEGIN
	ALTER TABLE sms_QueryCode_Set ALTER COLUMN Comment VARCHAR(MAX)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Sms_ReceiveLog]    脚本日期: 05/05/2010 14:49:16 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Sms_ReceiveLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Sms_ReceiveLog](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[PhoneNo] [text] COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_PhoneNo]  DEFAULT (''),
		[QryCode] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_QryCode]  DEFAULT (''),
		[Content] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_Content]  DEFAULT (''),
		[RecSTime] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_RecSTime]  DEFAULT (''),
		[RecCTime] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_RecCTime]  DEFAULT (''),
		[Response] [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_Response]  DEFAULT (''),
		[SendError] [int] NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_SendError]  DEFAULT (0),
		[State] [int] NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_State]  DEFAULT (0),
		[SmsType] [int] NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_SmsType]  DEFAULT (0),
		[SendId] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_SendId]  DEFAULT (''),
		[OperID] [varchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_OperID]  DEFAULT (''),
		[Deleted] [int] NOT NULL CONSTRAINT [DF_Sms_ReceiveLog_Deleted]  DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Sms_ReceiveLog' AND a.Name='PhoneNo' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('Sms_ReceiveLog') AND name='PhoneNo')
	IF @dfname IS NOT NULL
		EXEC ('alter table Sms_ReceiveLog drop constraint '+@dfname);
		
	ALTER TABLE Sms_ReceiveLog ALTER COLUMN PhoneNo VARCHAR(MAX) NULL 
	ALTER TABLE Sms_ReceiveLog ADD CONSTRAINT DF_Sms_ReceiveLog_PhoneNo DEFAULT('') FOR PhoneNo
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Sms_ReceiveLog]') AND name = N'PK_Sms_ReceiveLog')
ALTER TABLE [dbo].[Sms_ReceiveLog] DROP CONSTRAINT [PK_Sms_ReceiveLog]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SMS_RECEIVELOG') AND name = 'CIX_SMS_RECEIVELOG_ID')
--DROP INDEX CIX_SMS_RECEIVELOG_ID ON SMS_RECEIVELOG 
CREATE CLUSTERED INDEX CIX_SMS_RECEIVELOG_ID ON SMS_RECEIVELOG(ID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Sms_SendPlan]    脚本日期: 05/05/2010 14:49:17 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Sms_SendPlan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Sms_SendPlan](
		[PlanID] [int] IDENTITY(1,1) NOT NULL,
		[Phones] [text] COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT (''),
		[QryCode] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT (''),
		[QryParam] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT (''),
		[SendTime] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('0'),
		[RuleID] [int] NOT NULL DEFAULT ('0'),
		[State] [int] NOT NULL DEFAULT ('0')
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Sms_SendPlan' AND a.Name='Phones' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('Sms_SendPlan') AND name='Phones')
	IF @dfname IS NOT NULL
		EXEC ('alter table Sms_SendPlan drop constraint '+@dfname);
		
	ALTER TABLE Sms_SendPlan ALTER COLUMN Phones VARCHAR(MAX) NULL 
	ALTER TABLE Sms_SendPlan ADD CONSTRAINT DF_Sms_SendPlan_Phones DEFAULT('') FOR Phones

END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sms_SetSendRule]    脚本日期: 05/05/2010 14:49:18 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sms_SetSendRule]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sms_SetSendRule](
		[RuleID] [int] IDENTITY(1,1) NOT NULL,
		[RuleName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[CodeID] [int] NULL,
		[Phones] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[QryParam] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[BeginDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[EndDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[TimeMode] [int] NULL,
		[Interval] [int] NULL,
		[Weeks] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[SendCount] [int] NULL,
		[SendTime] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[CurrSend] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='sms_SetSendRule' AND a.Name='Phones' and a.xtype=35
)
BEGIN
	ALTER TABLE sms_SetSendRule ALTER COLUMN Phones VARCHAR(MAX)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sms_signature]    脚本日期: 05/05/2010 14:49:19 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sms_signature]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sms_signature](
		[id] [int] IDENTITY(1,1) NOT NULL,
		[signatureNo] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[signature] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[employee] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sms_Template]    脚本日期: 05/05/2010 14:49:20 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sms_Template]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sms_Template](
		[TemplateID] [int] IDENTITY(1,1) NOT NULL,
		[TypeID] [int] NOT NULL CONSTRAINT [DF__sms_Templ__TypeI__13D6F02E]  DEFAULT (0),
		[Content] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__sms_Templ__Conte__14CB1467]  DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sms_Template_Type]    脚本日期: 05/05/2010 14:49:21 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sms_Template_Type]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sms_Template_Type](
		[typeID] [int] IDENTITY(1,1) NOT NULL,
		[TypeName] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID('SMSInfo_Params') AND TYPE='U')   
	BEGIN
		--短信模板参数
		CREATE TABLE SMSInfo_Params 
		(
			Id			INT IDENTITY(1,1),
			BillType	INT NOT NULL DEFAULT(-1),--单据类型
			tempTypeId	INT NOT NULL DEFAULT(-1),--模板类型
			Content		VARCHAR(500),--模板内容参数
			isSysRow	INT NOT NULL DEFAULT(0)	--是否系统默认
		)
	END
GO
------------------------------------------------------修改表------------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='SMSInfo_Template' AND a.Name='isPostSend'
--)
--BEGIN
--	ALTER TABLE SMSInfo_Template 
--		ADD isPostSend INT NOT NULL DEFAULT(0)
--END
--GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SMSInfo_Params') AND name = 'CIX_SMSInfo_Params_Id')
	CREATE CLUSTERED INDEX CIX_SMSInfo_Params_Id ON SMSInfo_Params(Id) 
GO
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------预置数据【BEGIN】---------------------------------------------

TRUNCATE TABLE SMSInfo_Params

SET IDENTITY_INSERT SMSInfo_Params ON 

INSERT INTO SMSInfo_Params(Id,BillType,tempTypeId,Content,isSysRow)

SELECT 1,-1,1,'@持卡人、@系统时间、@尾号、@分支机构、@仓库、@门店、@本次储值金额、@储值余额、@本次消费金额、@本次积分、@积分余额、@本次储值结算金额、@原积分余额、@原储值余额、@兑换积分、@转储值金额',1 UNION

--300:销售订单
SELECT 2,300,-1,'@单据编号、@分支机构、@门店、@往来单位、@出库仓库、@说明、@摘要、@商品名称、@销售数量、@销售单位、@基本计量单位、@价税合计',1 UNION

--11:销售出库单
SELECT 3,11,-1,'@单据编号、@分支机构、@门店、@往来单位、@出库仓库、@说明、@摘要、@运单号、@承运单位、@商品名称、@销售数量、@销售单位、@基本计量单位、@价税合计、@应收余额（本币）、@应付余额（本币）、@预收余额（本币）、@预付余额（本币）、@运单号、@物件数量',1 UNION

--45:销售退货单
SELECT 4,45,-1,'@单据编号、@分支机构、@门店、@往来单位、@出库仓库、@说明、@摘要、@商品名称、@销售数量、@销售单位、@基本计量单位、@价税合计',1 UNION

--402:发出商品出库单
SELECT 5,402,-1,'@单据编号、@分支机构、@门店、@往来单位、@出库仓库、@说明、@摘要、@商品名称、@销售数量、@销售单位、@基本计量单位、@价税合计',1 UNION

--301:采购订单
SELECT 6,301,-1,'@单据编号、@分支机构、@门店、@往来单位、@入库仓库、@说明、@摘要、@商品名称、@采购数量、@采购单位、@基本计量单位、@价税合计',1 UNION

--34:采购入库单
SELECT 7,34,-1,'@单据编号、@分支机构、@门店、@往来单位、@入库仓库、@说明、@摘要、@商品名称、@采购数量、@采购单位、@基本计量单位、@价税合计、@应收余额（本币）、@应付余额（本币）、@预收余额（本币）、@预付余额（本币）',1 UNION

--6:采购退货单
SELECT 8,6,-1,'@单据编号、@分支机构、@门店、@往来单位、@入库仓库、@说明、@摘要、@商品名称、@采购数量、@采购单位、@基本计量单位、@价税合计',1 UNION

--400:暂估入库
SELECT 9,400,-1,'@单据编号、@分支机构、@门店、@往来单位、@入库仓库、@说明、@摘要、@商品名称、@采购数量、@采购单位、@基本计量单位、@价税合计',1 UNION

--4:收款单
SELECT 10,4,-1,'@单据编号、@分支机构、@门店、@仓库、@结算单位、@说明、@摘要、@本币金额、@应收账款',1 UNION

--66:付款单
SELECT 11,66,-1,'@单据编号、@分支机构、@门店、@仓库、@结算单位、@说明、@摘要、@本币金额、@应付账款',1 UNION

--405:销售发货开票
SELECT 12,405,-1,'@单据编号、@分支机构、@门店、@仓库、@往来单位、@说明、@摘要、@价税合计',1 UNION

--404:采购暂估开票
SELECT 13,404,-1,'@单据编号、@分支机构、@门店、@仓库、@往来单位、@说明、@摘要、@价税合计',1 UNION 

SELECT 1,-1,6,'@持卡人、@系统时间、@尾号、@分支机构、@会员卡号、@卡类型、@生日、@发卡日期、@有效期、@建卡机构、@积分余额、@储值余额',1

SET IDENTITY_INSERT SMSInfo_Params OFF

GO
------------------------------------------预置数据【END】-----------------------------------------------
UPDATE SMSInfo_Params SET Content = REPLACE(Content,'、@签名','')
GO



IF NOT EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID('SMSInfo_Template') AND TYPE='U')   
	BEGIN
		CREATE TABLE SMSInfo_Template 
		(
			smsId			INT IDENTITY(1,1),
			tempCode		VARCHAR(500) NOT NULL,--短信群发模板编号
			tempName		VARCHAR(500) NOT NULL,--短信群发模板名称
			tempTypeId		INT NOT NULL DEFAULT(0),--模板类型
			tempContent		VARCHAR(500),--群发内容
			comment			VARCHAR(500),--备注
			isPostSend		INT NOT NULL DEFAULT(0),--过账时自动发送(不包含自动过账)
			isSysRow		INT NOT NULL DEFAULT(0)	--是否系统默认
		)
	END
GO
------------------------------------------修改表区域开始-------------------------------------------------
--行业云模版
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSInfo_Template' AND a.Name='HyyunSmsTemplateContent'
)
BEGIN
	ALTER TABLE SMSInfo_Template 
		ADD HyyunSmsTemplateContent VARCHAR(MAX) NULL DEFAULT('')
END
GO  
UPDATE dbo.SMSInfo_Template SET HyyunSmsTemplateContent = '' WHERE HyyunSmsTemplateContent IS NULL
GO
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSInfo_Template' AND a.Name='HyyunSmsTemplateId'
)
BEGIN
	ALTER TABLE SMSInfo_Template 
		ADD HyyunSmsTemplateId VARCHAR(100) NULL DEFAULT('0')
END
GO 
UPDATE dbo.SMSInfo_Template SET HyyunSmsTemplateId = 0 WHERE HyyunSmsTemplateId IS NULL
GO
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSInfo_Template' AND a.Name='HyyunSmsTemplateMsg'
)
BEGIN
	ALTER TABLE SMSInfo_Template 
		ADD HyyunSmsTemplateMsg VARCHAR(500) NULL DEFAULT('')
END
GO
UPDATE dbo.SMSInfo_Template SET HyyunSmsTemplateMsg = '' WHERE HyyunSmsTemplateMsg IS NULL 
GO
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSInfo_Template' AND a.Name='HyyunSmsTemplateStatus'
)
BEGIN
	ALTER TABLE SMSInfo_Template 
		ADD HyyunSmsTemplateStatus VARCHAR(10) NULL DEFAULT('1')	--0已审核，1待审核，2已拒绝
END
GO 
UPDATE dbo.SMSInfo_Template SET HyyunSmsTemplateStatus = '1' WHERE HyyunSmsTemplateStatus IS NULL 
GO
UPDATE SMSInfo_Template SET tempContent = REPLACE(tempContent,'@签名','')
GO


--会员短信模板 （birth_isautosend）会员生日短信提前（senddate）天（sendtime）时间
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSInfo_Template' AND a.Name='Birth_IsAutoSend'
)
BEGIN
	ALTER TABLE SMSInfo_Template 
		ADD Birth_IsAutoSend INT NOT NULL DEFAULT(0)
END
GO 

IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSInfo_Template' AND a.Name='SendDay'
)
BEGIN
	ALTER TABLE SMSInfo_Template 
		ADD SendDay INT NOT NULL DEFAULT(0)
END
GO 

IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSInfo_Template' AND a.Name='SendTime'
)
BEGIN
	ALTER TABLE SMSInfo_Template 
		ADD SendTime Time  NOT NULL DEFAULT('00:00:00')  
END
GO 
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSInfo_Template' AND a.Name='SendDate'
)
BEGIN
	ALTER TABLE SMSInfo_Template 
		ADD SendDate DateTime  NULL DEFAULT('')  
END
GO
UPDATE SMSInfo_Template SET SendDate = '' WHERE SendDate IS NULL
GO
------------------------------------------修改表区域结束-------------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SMSInfo_Template') AND name = 'CIX_SMSInfo_Template_smsId')
	CREATE CLUSTERED INDEX CIX_SMSInfo_Template_smsId ON SMSInfo_Template(smsId) 
GO
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------预置数据【BEGIN】---------------------------------------------

IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template)
	BEGIN
		SET IDENTITY_INSERT SMSInfo_Template ON 
		
		INSERT INTO SMSInfo_Template(smsId,tempCode,tempName,tempTypeId,tempContent,comment,isPostSend,isSysRow)
		SELECT 1,'001','会员储值',1,'尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】充值【@本次储值金额】元，当前储值余额为【@储值余额】元。','',0,1 UNION 
		
		SELECT 2,'002','会员消费（积分）',2,'尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】发生【@本次消费金额】元消费，（本次积分【@本次积分】，当前积分余额为【@积分余额】），感谢您的惠顾！','',0,1 UNION  	
		
		SELECT 3,'003','会员消费（储值）',3,'尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】发生【@本次消费金额】元消费，其中储值消费【@本次储值结算金额】，当前储值余额为【@储值余额】元，如非本人操作，请及时核查。感谢您的惠顾！','',0,1 UNION 	
		
		SELECT 4,'004','会员消费（储值+积分）',4,'尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】发生【@本次消费金额】元消费，（本次积分【@本次积分】，当前积分余额为【@积分余额】），储值消费【@本次储值结算金额】，当前储值余额为【@储值余额】元，如非本人操作，请及时核查。感谢您的惠顾！','',0,1
	
		
		SET IDENTITY_INSERT SMSInfo_Template OFF
		
	END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE tempCode='005')
	BEGIN
		SET IDENTITY_INSERT SMSInfo_Template ON 
		
		INSERT INTO SMSInfo_Template(smsId,tempCode,tempName,tempTypeId,tempContent,comment,isPostSend,isSysRow)
		VALUES( 5,'005','会员积分转储值',5,'尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】发生积分转储值业务，本次兑换积分【@兑换积分】，转储值金额为【@转储值金额】，当前积分余额为【@积分余额】，当前储值余额为【@储值余额】元，如非本人操作，请及时核查。感谢您的惠顾！','',0,1)
		
		SET IDENTITY_INSERT SMSInfo_Template OFF
		
	END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE tempCode='006')
	BEGIN
		SET IDENTITY_INSERT SMSInfo_Template ON 
		
		INSERT INTO SMSInfo_Template(smsId,tempCode,tempName,tempTypeId,tempContent,comment,isPostSend,SendTime,isSysRow)
		VALUES( 6,'006','会员生日',6,'尊敬的【@持卡人】会员，您好！今天是您的生日，衷心祝福您生日快乐！','',0,'09:00:00',1)
		
		SET IDENTITY_INSERT SMSInfo_Template OFF
		
	END
GO
------------------------------------------预置数据【END】-----------------------------------------------




IF NOT EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID('SMSInfo_Template_CardType') AND TYPE='U')   
	BEGIN
		CREATE TABLE SMSInfo_Template_CardType 
		(
			smsId			INT,
			vipCardTypeID	INT--发送对象(卡类型)
		)
	END
GO
------------------------------------------------------修改表------------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='SMSInfo_Template' AND a.Name='isPostSend'
--)
--BEGIN
--	ALTER TABLE SMSInfo_Template 
--		ADD isPostSend INT NOT NULL DEFAULT(0)
--END
--GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SMSInfo_Template_CardType') AND name = 'CIX_SMSInfo_Template_CardType_smsId')
	CREATE CLUSTERED INDEX CIX_SMSInfo_Template_CardType_smsId ON SMSInfo_Template_CardType(smsId) 
GO
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------预置数据【BEGIN】---------------------------------------------

------------------------------------------预置数据【END】-----------------------------------------------




IF NOT EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID('SMSInfo_TempletType') AND TYPE='U')   
	BEGIN
		CREATE TABLE SMSInfo_TempletType 
		(
			tempTypeId		INT IDENTITY(1,1),
			fullName		VARCHAR(200) NOT NULL,--短信模板类型名称
			isSysRow		INT NOT NULL DEFAULT(0)	--是否系统默认
		)
	END
GO
------------------------------------------------------修改表------------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='SMSInfo_TempletType' AND a.Name='isSysRow'
--)
--BEGIN
--	ALTER TABLE SMSInfo_TempletType 
--		ADD isSysRow INT NOT NULL DEFAULT(0)
--END
--GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SMSInfo_TempletType') AND name = 'CIX_SMSInfo_TempletType_tempTypeId')
	CREATE CLUSTERED INDEX CIX_SMSInfo_TempletType_tempTypeId ON SMSInfo_TempletType(tempTypeId) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------预置数据【BEGIN】---------------------------------------------

IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_TempletType)
	BEGIN
		SET IDENTITY_INSERT SMSInfo_TempletType ON 
		
		INSERT INTO SMSInfo_TempletType(tempTypeId,FullName,isSysRow)
		SELECT 1,'会员储值',1 UNION 
		SELECT 2,'会员消费（积分）',1 UNION 
		SELECT 3,'会员消费（储值）',1 UNION 
		SELECT 4,'会员消费（积分+储值）',1
		
		SET IDENTITY_INSERT SMSInfo_TempletType OFF
		
	END
IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_TempletType WHERE fullName='会员积分转储值')
	BEGIN
		SET IDENTITY_INSERT SMSInfo_TempletType ON 
		
		INSERT INTO SMSInfo_TempletType(tempTypeId,FullName,isSysRow)
		VALUES( 5,'会员积分转储值',1 )
		
		SET IDENTITY_INSERT SMSInfo_TempletType OFF
		
	END
IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_TempletType WHERE fullName='自定义模版')
	BEGIN
		SET IDENTITY_INSERT SMSInfo_TempletType ON 
		
		INSERT INTO SMSInfo_TempletType(tempTypeId,FullName,isSysRow)
		VALUES( 6,'自定义模版',1 )
		
		SET IDENTITY_INSERT SMSInfo_TempletType OFF
		
	END
------------------------------------------预置数据【END】-----------------------------------------------




/****** 对象:  Table [dbo].[sp_SysProce]    脚本日期: 05/05/2010 14:49:22 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_SysProce]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sp_SysProce](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[sp_ReportId] [int] NULL,
		[sp_ReportName] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[sp_ProcName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[is_Tree] [int] NULL,
		[hidd_Value] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[onClick] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[onDbClick] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Height] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Width] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sp_sysReportCondition]    脚本日期: 05/05/2010 14:49:22 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_sysReportCondition]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sp_sysReportCondition](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[sp_Id] [int] NULL,
		[funName] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[orderId] [int] NULL,
		[sortId] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sp_sysReportCondition_Item]    脚本日期: 05/05/2010 14:49:23 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_sysReportCondition_Item]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sp_sysReportCondition_Item](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[sp_Id] [int] NULL,
		[orderId] [int] NULL,
		[paramValue] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sp_SysReportConditionList]    脚本日期: 05/05/2010 14:49:24 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_SysReportConditionList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sp_SysReportConditionList](
		[Id] [int] IDENTITY(1,1) NOT NULL,
		[funName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[funExplain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[funExample] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[paramExplain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[paramCount] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sp_SysTableName]    脚本日期: 05/05/2010 14:49:25 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_SysTableName]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sp_SysTableName](
		[ID] [int] NOT NULL,
		[sp_Id] [int] NULL,
		[sp_TableName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderId] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sp_SysTEnItem]    脚本日期: 05/05/2010 14:49:26 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_SysTEnItem]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sp_SysTEnItem](
		[ID] [int] NOT NULL,
		[sp_Id] [int] NULL,
		[sp_SysTableName_Id] [int] NULL,
		[En_Item] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Align] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Format] [int] NULL,
		[Format_Num] [int] NULL,
		[is_Sum] [int] NULL,
		[OrderId] [int] NULL,
		[is_Hidden] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
TRUNCATE TABLE sp_SysTEnItem
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(1,'BillIndex','DeleteBill')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(2,'BillIndex','InsertOrder')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(3,'FaPiaoBillIndex','DelFaPiaoTrigger')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(4,'GoodsStocks','DeleteGoodsStocks')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(5,'GoodsStocks','InsertGoodsStocks')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(6,'GoodsStocks','UpdateGoodsStocks')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(7,'gp_CruPtypeSerial','TG_GoddsLocalIn')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(8,'gp_CruPtypeSerial','TG_GoodsLocalUpdate')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(9,'GuestBackIndex','DelGuestBack')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(10,'GuestGetIndex','dGuestGetIndex')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(11,'ListTable','del_tmpGain')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(12,'ListTable','IN_tmpGain')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(13,'OrderIndex','DelOrderTrigger')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(14,'Stock','TG_DeleteL')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(15,'TemplateTable','DelTemplateTrigger')
INSERT INTO sp_SysTEnItem(id,En_Item,Align)VALUES(16,'PType_EntryCode_Ext','DeletePTypeEntryCode')
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sqlLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[sqlLog] (
		[id] [int] IDENTITY (1, 1) NOT NULL ,
		[type] [tinyint] NOT NULL ,
		[dateTime] [datetime] NOT NULL ,
		[elapsed] [int] NOT NULL ,
		[url] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[params] [varchar] (1000) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ipAddress] [varchar] (15) COLLATE Chinese_PRC_CI_AS NULL ,
		[_sql] [varchar] (8000) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[executeElapsed] [int] NOT NULL ,
		[fetchElapsed] [int] NOT NULL ,
		[_rowCount] [int] NOT NULL ,
		[error] [varchar] (400) COLLATE Chinese_PRC_CI_AS NULL ,
		[profileId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[loginUserId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='sqlLog' AND a.Name='_sql' AND Length=2000
)
BEGIN
	ALTER TABLE sqlLog
	 ALTER COLUMN _sql [varchar] (8000) NOT NULL
END
GO
IF  EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[sqlLog]') and name = 'params' )
BEGIN
	ALTER TABLE sqlLog 
		ALTER COLUMN  params VARCHAR(1000);
END

------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'StartOk') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[StartOk]
	(
	[typeID] [VARCHAR](MAX) NULL,
	[parID] [VARCHAR](MAX) NULL,
	[level] [INT] NULL,
	[sonnum] [INT] NULL,
	[soncount] [INT] NULL,
	[delete] [BIT] NULL,
	[ID] [INT] IDENTITY(1,1) NOT NULL,
	[Name] [VARCHAR](MAX) NOT NULL,
	[NameCode] [INT] NOT NULL,		--1,2,3,4,5
	[Complete] [INT] NOT NULL,		--0=完成，1= 未完成
	) 
END
DELETE FROM StartOk

INSERT INTO StartOk(Name,NameCode,Complete) VALUES ('公共资料',1,0)
INSERT INTO StartOk(Name,NameCode,Complete) VALUES ('选项设置',2,0)
INSERT INTO StartOk(Name,NameCode,Complete) VALUES ('基本信息',3,0)
INSERT INTO StartOk(Name,NameCode,Complete) VALUES ('单据设置',4,0)
INSERT INTO StartOk(Name,NameCode,Complete) VALUES ('期初录入',5,0)
INSERT INTO StartOk(Name,NameCode,Complete) VALUES ('是否打开向导页面',0,0)

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'StartOkItems') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[StartOkItems]
	(
	[typeID] [VARCHAR](MAX) NULL,
	[parID] [VARCHAR](MAX) NULL,
	[level] [INT] NULL,
	[sonnum] [INT] NULL,
	[soncount] [INT] NULL,
	[delete] [BIT] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[itemsName] [VARCHAR](MAX) NOT NULL,
	[partNameID] [INT] NOT NULL,				--此项目的上一级名称ID
	[SortID] [INT] NOT NULL,					--在页面上显示的顺序
	[import] [INT] NOT NULL,					--是否具有导入项 1=有， 0 = 没有
	[otherItemsName] [VARCHAR](MAX)  NULL,		--(其他项目名称)备用
	[expain] [VARCHAR](MAX) NULL,				--相关说明
	[Complete] [INT] NOT NULL,					--1=完成，0= 未完成
	LimitScan	[VARCHAR](MAX) NULL,			--查看的权限字符串
	LimitExport [VARCHAR](MAX) NULL,			--导入的权限字符串
	) 
END
DELETE FROM StartOkItems

--INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('公司信息',1,1,0,0,'','LIMIT_CO_INFO','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('操作员权限',1,2,0,0,'AAA在【操作员权限】中首先需要增加操作员，然后再对操作员设置权限。BBBAAA系统根据管理流程把权限划分为不同的管理模块：销售管理、采购管理等，在各个模块中，只需要勾选中具体的权限，保存退出即可完成操作员的权限设置。BBBAAA具体权限说明请仔细阅读说明书或在线帮助。','LIMIT_LIMIT','')

INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('公共选项',2,1,0,0,'AAA【公共选项】是针对公司具体情况设置使用本系统时的一些基础配置数据，包括以下几个方面：全局配置、单据配置、成本算法、高级配置等。部分设置在开账后不允许修改，故在配置前请仔细阅读软件说明书或在线帮助。','LIMIT_USERCONFIGE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('多仓库配置',2,2,0,0,'','LIMIT_USERCONFIGE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('销售单据配置',2,3,0,0,'AAA根据企业的具体流程，对应配置销售类单据的业务控制。','LIMIT_USERCONFIGE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('采购单据配置',2,4,0,0,'AAA根据企业的具体流程，对应配置采购类单据的业务控制。','LIMIT_USERCONFIGE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('调拨单据配置',2,5,0,0,'AAA针对同价调拔单和变价调拔单使用。如果勾选了该项（即仓库权限范围有效），操作员只有部分仓库权限范围，那么此操作员就不能将商品调进或调出权限范围外的仓库；如果没有勾选该项（即仓库权限范围无效），那么只有部分仓库权限范围的操作员就可以将商品调进或调出权限范围外的仓库。','LIMIT_USERCONFIGE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('其他单据配置',2,6,0,0,'','LIMIT_USERCONFIGE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('其他配置',2,7,0,0,'','LIMIT_USERCONFIGE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('最低售价、最高进价配置',2,8,0,0,'','LIMIT_USERCONFIGE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('虚拟库存配置',2,9,0,0,'','LIMIT_USERCONFIGE','')

INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('分支机构档案',3,1,0,0,'AAA『分支机构档案』记录各分支机构的基本信息，系统允许10级分类。BBBAAA“分支机构名称”、“分支机构编号”不允许重复，点击“分支机构分类”进入后进行子分支机构的增加。','LIMIT_STYPE_BASE','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('商品档案',3,2,1,0,'AAA商品分类的正确建立可方便库存管理、销售管理及各种统计报表，系统允许10级分类。BBBAAA两个计量单位之间是通过“换算比率”来进行换算的，但换算结果以基本单位为基础。 “预设售价1-10”设定后，对于不同的往来单位可以设置不同的销售价格，系统可以自动记录跟踪，在做业务单据的时候，可根据设置自动调用。调出的价格也可以进行修改。BBBAAA商品编号不允许重复、商品名称允许重复。','LIMIT_GOODS_BASE','LIMIT_GOODS_BASE_EXPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('客户档案',3,3,1,0,'AAA客户档案资料主要记录业务往来单位和个人的相关信息,如：客户编号、客户名称、联系人、联系地址、开户行及账号、联系电话、收付款期限等信息，系统允许9级分类。BBBAAA当系统设置使用信用额度时，“信用额度”的数值将会影响该单位的往来款项金额。在“适用价格”栏可靠选择该往来单位对应的适用价格1-10、零售价、最高售价、最低售价，在进行销售出库时直接读取该价格，而不需要选择。BBBAAA客户编号、客户名称不允许重复。','LIMIT_CLIENT_BASE','LIMIT_CLIENT_BASE_EXPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('供货商档案',3,4,1,0,'AAA与客户档案类似，供货商档案资料主要记录业务往来单位和个人的相关信息,如：供货商编号、供货商名称、联系人、联系地址、开户行及账号、联系电话、收付款期限等信息，系统允许9级分类。BBBAAA当系统设置使用信用额度时，“信用额度”的数值将会影响该单位的往来款项金额。在“适用价格”栏可靠选择该往来单位对应的适用价格1-10、零售价、最高售价、最低售价，在进行销售出库时直接读取该价格，而不需要选择。BBBAAA供货商编号、供货商名称不允许重复。BBBAAA注：如同一个单位既有采购业务也有销售业务，可以在『系统配置』中设置“统一客户供货商”','LIMIT_SUPPLY_BASE','LIMIT_SUPPLY_BASE_EXPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('职员档案',3,5,1,0,'AAA职员基本资料是整个系统所有操作员的信息来源，【职员档案】记录公司每个员工的基本信息，系统允许9级分类。BBBAAA只有在【职员档案】中新增了职员后，才能在【操作员权限】中增加其他的操作员BBBAAA职员编号、职员名称不允许重复。','LIMIT_EMPLOYEE_BASE','LIMIT_EMPLOYEE_BASE_EXPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('存货仓库',3,6,1,0,'AAA『存货仓库』记录各仓库的基本信息，系统允许10级分类。BBBAAA“仓库名称”、“仓库编号”不允许重复，点击“仓库分类”进入后进行子仓库的增加。','LIMIT_STOCK_BASE','LIMIT_STOCK_BASE_EXPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('部门档案',3,7,1,0,'','LIMIT_DEPARTMENT_BASE','LIMIT_DEPARTMENT_BASE_EXPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('地区档案',3,8,1,0,'','LIMIT_AREA_BASE','LIMIT_AREA_BASE_EXPORTIN')
--INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('银行账户',3,9,0,0,'','LIMIT_BANK_BASE','')

INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('单据审核设置',4,1,0,0,'定义单据审核流程。','LIMIT_AUDITING_SET','')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('单据编号设置',4,2,0,0,'设置单据编号方案。','LIMIT_BillCode_Config','')

INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('库存期初',5,1,1,0,'AAA建立【库存期初】时，首先应选择“仓库”，再分别对各种商品设置期初值。','LIMIT_INI_GOODS','LIMIT_INI_GOODS_REPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('应收期初',5,2,1,0,'AAA在双击往来单位后可设置对应单位的应收期初。','LIMIT_INI_AR','LIMIT_INI_AR_REPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('应付期初',5,3,1,0,'AAA在双击往来单位后可设置对应单位的应付期初。','LIMIT_INI_AP','LIMIT_INI_AP_REPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('受托库存期初',5,4,1,0,'AAA在双击商品后可设置对应商品的受托期初。BBBAAA建立『受托库存期初』时，首先应选择该”分支机构和往来单位”，系统会自动在库存商品下建立以该分支机构和单位为名称的受托代销商品库。BBBAAA受托代销属已入库性质，在库存期初录入时，需要将受托数量和成本加入；同时在受托期初中录入未结算的受托代销商品数量和金额。','LIMIT_COMMISSION_STOCK_ST_START','LIMIT_COMMISSION_STOCK_ST_START_REPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('委托库存期初',5,5,1,0,'AAA在双击商品后可设置对应商品的委托期初。BBBAAA建立『委托库存期初』时，首先应选择该”分支机构和往来单位”，系统会自动在库存商品下建立以该分支机构和单位为名称的委托代销商品库。BBBAAA委托代销属已出库性质，故“委托代销期初数量”与“库存期初”无关','LIMIT_COMMISSION_STOCK_WT_START','LIMIT_COMMISSION_STOCK_WT_START_REPORTIN')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('借欠期初',5,6,1,0,'AAA在【借欠期初】中录入向往来单位借入的商品情况，和借给往来单位的商品情况。BBBAAA本系统中借欠账目记账外库存，与账面库存没有直接关系，故“库存期初数量”与“借欠期初数量”没有任何加减关系，需分开分别录入。','LIMIT_LENDSTAR','LIMIT_LENDSTAR_REPORINT')
INSERT INTO StartOkItems(itemsName,partNameID,SortID,import,Complete,expain,LimitScan,LimitExport) VALUES ('系统开账',5,7,0,0,'AAA完成上述步骤后，现在您可以进行系统开账了。请在开账前再仔细检查一下之前的工作有没有遗漏。','LIMIT_START','')
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Stock]    脚本日期: 05/05/2010 14:49:28 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Stock](
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[parid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint] NOT NULL CONSTRAINT [DF_Stock_leveal]  DEFAULT (0),
		[sonnum] [int] NOT NULL CONSTRAINT [DF_Stock_sonnum]  DEFAULT (0),
		[soncount] [int] NOT NULL CONSTRAINT [DF_Stock_soncount]  DEFAULT (0),
		[FullName] [varchar](66) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_Stock_FullName]  DEFAULT (''),
		[Name] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Stock_Name]  DEFAULT (''),
		[UserCode] [varchar](26) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Stock_UserCode]  DEFAULT (''),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Stock_Comment]  DEFAULT (''),
		[deleted] [bit] NOT NULL CONSTRAINT [DF_Stock_deleted]  DEFAULT (0),
		[Add] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Tel] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkMan] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
		[PyCode] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[XiWaMaxNumber] [numeric](18, 0) NULL DEFAULT (0)
	) ON [PRIMARY]

	-- ********	处理 Stock	********
	DELETE FROM Stock
	INSERT INTO Stock(TypeID,Parid,Leveal,SonNum,SonCount,FullName,Name,UserCode,Comment,Deleted,[Add],Tel,LinkMan)VALUES('00000','root',0,0,0,'全部仓库','全部仓库','','',0,'','','')
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Stock' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE Stock ADD STypeID VARCHAR(50) NULL
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE stock SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Stock' AND a.Name='Kid')
BEGIN
	ALTER TABLE Stock ADD Kid INT identity(1,1)
END
GO

--职位
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Stock' AND a.Name='job')
BEGIN
	ALTER TABLE Stock 
		ADD job VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE stock SET job = '' WHERE job IS NULL
GO
--手机
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Stock' AND a.Name='mobile')
BEGIN
	ALTER TABLE Stock 
		ADD mobile VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE stock SET mobile = '' WHERE mobile IS NULL
GO
--省
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Stock' AND a.Name='sheng')
BEGIN
	ALTER TABLE Stock 
		ADD sheng VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE stock SET sheng = '' WHERE sheng IS NULL
GO
--市
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Stock' AND a.Name='shi')
BEGIN
	ALTER TABLE Stock 
		ADD shi VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE stock SET shi = '' WHERE shi IS NULL
GO
--县
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Stock' AND a.Name='xian')
BEGIN
	ALTER TABLE Stock 
		ADD xian VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE stock SET xian = '' WHERE xian IS NULL
GO
--邮编
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Stock' AND a.Name='postcode')
BEGIN
	ALTER TABLE Stock 
		ADD postcode VARCHAR(100) DEFAULT('') NULL
END
GO
UPDATE stock SET postcode = '' WHERE postcode IS NULL
GO

UPDATE STOCK
SET UserCode='全部仓库'
WHERE typeId='00000'

GO

--网店同步标志
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Stock' AND a.Name='WdSyncFlag')
BEGIN
	ALTER TABLE Stock ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Stock]') AND name = N'stockidx')
DROP INDEX [dbo].[Stock].[stockidx]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STOCK') AND name = 'CIX_STOCK_typeId')
--DROP INDEX CIX_STOCK_typeId ON STOCK 
CREATE CLUSTERED INDEX CIX_STOCK_typeId ON STOCK(typeId) 


------------------------------------------创建索引区域结束-----------------------------------------------	
--提供XiWa交互功能，每次修改或者新增基本信息后，必须在原来的值上加1 谢吉康 2010-05-04
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Stock]') and name = 'XiWaMaxNumber' )
	BEGIN
		BEGIN TRANSACTION
		SET QUOTED_IDENTIFIER ON
		SET ARITHABORT ON
		SET NUMERIC_ROUNDABORT OFF
		SET CONCAT_NULL_YIELDS_NULL ON
		SET ANSI_NULLS ON
		SET ANSI_PADDING ON
		SET ANSI_WARNINGS ON
		COMMIT
		BEGIN TRANSACTION
		ALTER TABLE dbo.Stock ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
		
		COMMIT
	END
GO
UPDATE Stock SET XiWaMaxNumber = 1 WHERE XiWaMaxNumber IS NULL OR XiWaMaxNumber = 0
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 
--WMS下载
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('Stock') and name='IsWmsDownLoad')
BEGIN
	ALTER TABLE Stock 
		ADD IsWmsDownLoad INT NOT NULL DEFAULT 0 
End 
GO
UPDATE Stock SET IsWmsDownLoad = 0 WHERE IsWmsDownLoad IS NULL
GO

--是否同步
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('Stock') and name='IsWmsSync')
BEGIN
	ALTER TABLE Stock 
		ADD IsWmsSync INT NOT NULL DEFAULT 0 
End 
GO
UPDATE Stock SET IsWmsSync = 0 WHERE IsWmsSync IS NULL
GO



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'StockAgeTimeConfig') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[StockAgeTimeConfig]
	(
		[typeID] [VARCHAR](MAX) NULL,
		[parID] [VARCHAR](MAX) NULL,
		[level] [INT] NULL,
		[sonnum] [INT] NULL,
		[soncount] [INT] NULL,
		[delete] [BIT] NULL,
		[ID] [INT] IDENTITY(1,1) NOT NULL,
		[ETypeID] VARCHAR(MAX) NOT NULL,
		[Col]  int NULL DEFAULT (1),
		[Col0] int NULL DEFAULT (-1),
		[Col1] int NULL DEFAULT (-1),
		[Col2] int NULL DEFAULT (-1),
		[Col3] int NULL DEFAULT (-1),
		[Col4] int NULL DEFAULT (-1),
		[Col5] int NULL DEFAULT (-1),
		[Col6] int NULL DEFAULT (-1),
		[Col7] int NULL DEFAULT (-1),
		[Col8] int NULL DEFAULT (-1),
		[Col9] int NULL DEFAULT (-1)
	) 
END

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[STOCKALARM]    脚本日期: 05/05/2010 14:49:29 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[STOCKALARM]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[STOCKALARM](
		[PTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[KTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[UpLimitQty] [numeric](18, 4) NULL,
		[DownLimitQty] [numeric](18, 4) NULL ,
		[OrderQty] [numeric](18, 4) NULL Default(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[STOCKALARM]') and name = 'OrderQty' )
BEGIN
	
	ALTER TABLE dbo.STOCKALARM ADD
		OrderQty numeric(18, 4) NULL Default(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STOCKALARM' AND a.Name='UpLimitQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STOCKALARM 
	ALTER COLUMN UpLimitQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STOCKALARM' AND a.Name='DownLimitQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STOCKALARM 
	ALTER COLUMN DownLimitQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STOCKALARM' AND a.Name='OrderQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STOCKALARM 
	ALTER COLUMN OrderQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[StockCheck]    脚本日期: 05/05/2010 14:49:29 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[StockCheck]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[StockCheck](
		[StockCheckID] [int] NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_StockCheck_Serial]  DEFAULT (''),
		[StockCheckSerial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_StockCheck_SotckCheckSerial]  DEFAULT (''),
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL,
		[Id] [int] IDENTITY(1,1) NOT NULL,
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_StockCheck_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_StockCheck_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_StockCheck_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_StockCheck_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_StockCheck_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_StockCheck_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_StockCheck_HandZeroCost]  DEFAULT (0),
		[StockQty] [numeric](18, 4) NULL DEFAULT 0,
		[CargoSpace] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL DEFAULT(''),
		CargoID INT NULL DEFAULT(0),
		ItemID               bigint               null,
	    IsCombined           int                  NULL
	    ,ShowOrder INT DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'StockCheck',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.StockCheck
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.StockCheck SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='StockQty'
)
BEGIN
	ALTER TABLE StockCheck ADD StockQty [numeric](18, 4) NULL DEFAULT 0
END

GO


--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='StockCheck' AND a.Name='CargoSpace'
--)
--BEGIN
--	ALTER TABLE StockCheck ADD CargoSpace [varchar](200) COLLATE Chinese_PRC_CI_AS NULL DEFAULT('')
--END

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='StockCheck' AND a.Name='CargoID')
BEGIN
	ALTER TABLE StockCheck ADD CargoID INT NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE StockCheck ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE StockCheck ADD IsCombined   INT
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='StockCheck' AND a.Name='nqty')
BEGIN
	ALTER TABLE StockCheck ADD nqty NUMERIC(18,4) NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='StockCheck' AND a.Name='stocknqty')
BEGIN
	ALTER TABLE StockCheck ADD stocknqty NUMERIC(18,4) NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='Serial'
)
BEGIN
		ALTER TABLE StockCheck ADD Serial  text NUll DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='StockCheckSerial'
)
BEGIN
		ALTER TABLE StockCheck ADD StockCheckSerial  text NUll DEFAULT ('')
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='StockCheck';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STOCKCHECK') AND name = 'CIX_STOCKCHECK_StockcheckId')
--DROP INDEX CIX_STOCKCHECK_StockcheckId ON STOCKCHECK 
CREATE CLUSTERED INDEX CIX_STOCKCHECK_StockcheckId ON STOCKCHECK(StockcheckId) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STOCKCHECK') AND name = 'NCIX_STOCKCHECK_Ptypeid')
--DROP INDEX NCIX_STOCKCHECK_Ptypeid ON STOCKCHECK 
CREATE NONCLUSTERED INDEX NCIX_STOCKCHECK_Ptypeid ON STOCKCHECK(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------更新当前表对应的NULL-----------------------------------------------
UPdate StockCheck SET  stocknqty=0 WHERE stocknqty IS NULL
GO

UPdate StockCheck SET  nqty=0 WHERE nqty IS NULL
GO
------------------------------------------更新当前表对应的NULL-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE StockCheck 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE StockCheck 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE StockCheck 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='StockQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE StockCheck 
	ALTER COLUMN StockQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='nqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE StockCheck 
	ALTER COLUMN nqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheck' AND a.Name='stocknqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE StockCheck 
	ALTER COLUMN stocknqty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[StockCheckIndex]    脚本日期: 05/05/2010 14:49:30 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[StockCheckIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[StockCheckIndex](
		[StockCheckID] [int] NOT NULL,
		[Pass] [bit] NULL CONSTRAINT [DF_StockCheckIndex_Pass]  DEFAULT (0),
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[ifWX] [int] NULL CONSTRAINT [DF_StockCheckIndex_ifWX]  DEFAULT (0),
		[SerialCheck] [int] NULL CONSTRAINT [DF_StockCheckIndex_SerialCheck]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--增加字段：账面数截止时间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheckIndex' AND a.Name='StockQtyEndDate'
)
BEGIN
	ALTER TABLE StockCheckIndex 
		ADD StockQtyEndDate datetime NOT NULL DEFAULT(GETDATE())
END
--增加字段：序列号盘点
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheckIndex' AND a.Name='SerialCheck'
)
BEGIN
	ALTER TABLE StockCheckIndex 
		ADD SerialCheck int NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockCheckIndex' AND a.Name='Checke'
)
BEGIN
	ALTER TABLE StockCheckIndex 
		ADD Checke VARCHAR(50) NULL DEFAULT('')
END
GO
UPDATE StockCheckIndex SET checke = '' WHERE checke IS NULL
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='StockCheckIndex';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[StockCheckIndex]') AND name = N'PK_StockCheckIndex')
ALTER TABLE [dbo].[StockCheckIndex] DROP CONSTRAINT [PK_StockCheckIndex]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STOCKCHECKINDEX') AND name = 'CIX_STOCKCHECKINDEX_StockCheckID')
--DROP INDEX CIX_STOCKCHECKINDEX_StockCheckID ON STOCKCHECKINDEX 
CREATE CLUSTERED INDEX CIX_STOCKCHECKINDEX_StockCheckID ON STOCKCHECKINDEX(StockCheckID) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO
UPDATE A  SET A.[SerialCheck]=0 FROM dbo.StockCheckIndex A WHERE A.[SerialCheck] IS NULL
GO



IF NOT EXISTS (SELECT 1 FROM  sysobjects WHERE  id = object_id('StockPickBillInput') AND type = 'U')   
	BEGIN
		CREATE TABLE StockPickBillInput (
			OperatorId		VARCHAR(50),--当前操作员
			BillType		VARCHAR(500),--要查询的单据类型
			BillTypeFlag	INT NOT NULL DEFAULT(0)--413-拣货 412-上架单
		)
END
GO
------------------------------------------------------修改表------------------------------------------------------
--单据类型 413-拣货 412-上架单
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StockPickBillInput' AND a.Name='BillTypeFlag'
)
BEGIN
	ALTER TABLE StockPickBillInput 
		ADD BillTypeFlag INT NOT NULL DEFAULT(0)
END

GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('StockPickBillInput') AND name = 'CIX_StockPickBillInput_OperatorId')
	CREATE CLUSTERED INDEX CIX_StockPickBillInput_OperatorId ON StockPickBillInput(OperatorId,BillTypeFlag) 

------------------------------------------创建索引区域结束-----------------------------------------------




/****** 对象:  Table [dbo].[StockTotalConfig]    脚本日期: 05/05/2010 14:49:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[StockTotalConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[StockTotalConfig](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeId] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[BillTypes] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[ShowMoney] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[ShowBdPType] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[ShowSum] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SType_Config]    脚本日期: 05/05/2010 14:49:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SType_Config]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SType_Config](
		[ConfigNo] [int] NOT NULL,
		[ConfigName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]

		-- ********	处理 SType_Config	********
	
END
GO

DELETE FROM SType_Config
INSERT INTO SType_Config(ConfigNo,ConfigName)VALUES(1,'stypeinicanmodify')	

GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
  分支机构自定义字段
  张陈仁
  3023-04-10
*/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Stype_CustomColumns]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table Stype_CustomColumns 
	(
	   ID                   bigint               identity(1,1),
	   typeid               varchar(100)         null,
	   Costom1              VARCHAR(600)         null,
	   Costom2              VARCHAR(600)         null,
	   Costom3              VARCHAR(600)         null,
	   Costom4              VARCHAR(600)         null,
	   Costom5              VARCHAR(600)         null,
	   Costom6              VARCHAR(600)         null,
	   Costom7              VARCHAR(600)         null,
	   Costom8              VARCHAR(600)         null,
	   Costom9              VARCHAR(600)         null,
	   Costom10             VARCHAR(600)         null,
	   Costom11             VARCHAR(600)         null,
	   Costom12             VARCHAR(600)         null,
	   Costom13             VARCHAR(600)         null,
	   Costom14             VARCHAR(600)         null,
	   Costom15             VARCHAR(600)         null,
	   Costom16             VARCHAR(600)         null,
	   Costom17             VARCHAR(600)         null,
	   Costom18             VARCHAR(600)         null,
	   Costom19             VARCHAR(600)         null,
	   Costom20             VARCHAR(600)         null
   )
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SType_InnerARTotal]    脚本日期: 08/28/2008 17:19:22 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SType_InnerARTotal]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SType_InnerARTotal](
		[STypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[STypeID2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[InnerARTotal00] [numeric](18, 4) NULL DEFAULT (0),
		[InnerARTotal] [numeric](18, 4) NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType_InnerARTotal' AND a.Name='InnerARTotal00' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SType_InnerARTotal 
	ALTER COLUMN InnerARTotal00 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType_InnerARTotal' AND a.Name='InnerARTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE SType_InnerARTotal 
	ALTER COLUMN InnerARTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[stype_l]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[stype_l] (
		[etypeid] [varchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[typeid] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[flag] [char] (1) COLLATE Chinese_PRC_CI_AS NOT NULL 
	) ON [PRIMARY]
END
GO
-- Add by 李海洋 
-- Date: 2012-03-30
-- Description: 增加: 修改, 分类, 停用, 删除 细分权限
------------------------------------------表修改区域开始-------------------------------------------------
-- 修改权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = OBJECT_ID(N'[dbo].[stype_l]') 
		AND name = 'modifyflag'
)
BEGIN
		ALTER TABLE dbo.stype_l DROP COLUMN modifyflag ;
END
GO

-- 分类权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = OBJECT_ID(N'[dbo].[stype_l]') 
		AND name = 'assortflag'
)
BEGIN
  ALTER TABLE dbo.stype_l DROP COLUMN assortflag ;
END
GO

-- 停用权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = OBJECT_ID(N'[dbo].[stype_l]') 
		AND name = 'disableflag'
)
BEGIN
  ALTER TABLE dbo.stype_l DROP COLUMN disableflag ;
END
GO

-- 删除权限
IF EXISTS (
	SELECT name 
	FROM syscolumns 
	WHERE id = OBJECT_ID(N'[dbo].[stype_l]') 
		AND name = 'delflag'
)
BEGIN
		ALTER TABLE dbo.stype_l DROP COLUMN delflag ;
END  
GO

------------------------------------------表修改区域结束-------------------------------------------------




------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[stype_l]') AND name = N'IX_stype_l')
BEGIN
	DROP INDEX IX_stype_l ON stype_l
END
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STYPE_L') AND name = 'CIX_STYPE_L_etypeid')
--DROP INDEX CIX_STYPE_L_etypeid ON STYPE_L 
CREATE CLUSTERED INDEX CIX_STYPE_L_etypeid ON STYPE_L(etypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------更新新加列结束-------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[SType_UserConfig]    脚本日期: 05/05/2010 14:49:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SType_UserConfig]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SType_UserConfig](
		[ConfigNo] [int]  NOT NULL,
		[StypeId] [varchar](50)  DEFAULT(''),
		[Value] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[SFYear]   INT,  --启用年度
		[SFPeriod] INT,   --启用期间
		[LastCostComputeDate] [datetime] NULL	--上次成本计算时间
	) ON [PRIMARY]

		-- ********	处理 SType_UserConfig	********
	
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--上次成本计算时间
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'SType_UserConfig',N'U') AND Name='LastCostComputeDate')
BEGIN
	ALTER TABLE dbo.SType_UserConfig
	ADD LastCostComputeDate DATETIME
END
GO

--启用年度
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType_UserConfig' AND a.Name='SFYear'
)
BEGIN
	ALTER TABLE SType_UserConfig ADD SFYear INT
END
GO
--启用期间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType_UserConfig' AND a.Name='SFPeriod'
)
BEGIN
	ALTER TABLE SType_UserConfig ADD SFPeriod INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='SType_UserConfig' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE SType_UserConfig ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE SType_UserConfig SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
	INSERT INTO dbo.SType_UserConfig
	        ( ConfigNo ,
	          StypeId ,
	          Value ,
	          EtypeId ,
	          SFYear ,
	          SFPeriod
	        )
	SELECT   1 , -- ConfigNo - int
	         TypeId , -- StypeId - varchar(50)
	         0 , -- Value - varchar(50)
	         '00001'  , -- EtypeId - varchar(50)
	         2010 , -- SFYear - int
	         1  -- SFPeriod - int
	FROM dbo.SType   WHERE TypeID NOT IN(SELECT STypeID FROM dbo.SType_UserConfig) AND sonnum=0   
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[STypeMoveBill]    脚本日期: 05/05/2010 14:48:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[STypeMoveBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[STypeMoveBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_STypeMoveBill_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL,
		[Total] [numeric](18, 4) NULL,
		[Jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_STypeMoveBill_Jobnumber]  DEFAULT (0),
		[GoodsNo] [int] NULL CONSTRAINT [DF_STypeMoveBill_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_STypeMoveBill_IsUnit2]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_STypeMoveBill_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_STypeMoveBill_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_STypeMoveBill_GoodsOrder]  DEFAULT ('-1'),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_STypeMoveBill_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_STypeMoveBill_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_STypeMoveBill_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_STypeMoveBill_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_STypeMoveBill_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_STypeMoveBill_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_STypeMoveBill_HandZeroCost]  DEFAULT (0),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[Ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[Ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[FromBillID] [int] NULL DEFAULT (0),
		UnitID           int             Default(0)  NULL,
		NUnitID          int             Default(0)  NULL,
		NQty             numeric(22,10)  Default(0)  NULL,
		UnitRate         numeric(22,10)  Default(0)  NULL,
		NUnitMsg         varchar(50)          null,
		MUnitID          int             Default(0)  NULL,
		MQty             numeric(22,10)  Default(0)  NULL,
		MUnitRate        numeric(22,10)  Default(0)  NULL,
		MUnitMsg         varchar(50)          null,
		MPrice           numeric(22,10)  Default(0)  NULL,
		InCargoID		 INT			 DEFAULT(0) NULL,
		OutCargoID		 INT			 DEFAULT(0) NULL,
	   ItemID               bigint               null,
	   IsCombined           int                  NULL,
	   AllotId				INT				     DEFAULT(0) NULL	--调用的调货申请单明细ID 未调用时为0	 		
	   ,ShowOrder INT	DEFAULT(0)	
	   ,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
	   ,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
	   ,InFlowQty NUMERIC(24,10) NULL DEFAULT(0) --入库数量
	   ,InFactQty NUMERIC(24,10) NULL DEFAULT(0)
	   ,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO



------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'STypeMoveBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.STypeMoveBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'STypeMoveBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.STypeMoveBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'STypeMoveBill',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.STypeMoveBill
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.STypeMoveBill SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'STypeMoveBill',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.STypeMoveBill
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.STypeMoveBill SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'STypeMoveBill',N'U') AND Name='InflowQty')
BEGIN
	ALTER TABLE dbo.STypeMoveBill
	ADD InflowQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.STypeMoveBill SET InflowQty=0 WHERE InflowQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'STypeMoveBill',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE STypeMoveBill
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE STypeMoveBill SET PickedQty=0 WHERE PickedQty IS NULL
GO
--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'STypeMoveBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.STypeMoveBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE dbo.STypeMoveBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='UnitID')
BEGIN
	ALTER TABLE STypeMoveBill ADD UnitID  INT   NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='NUnitID')
BEGIN
	ALTER TABLE STypeMoveBill ADD NUnitID INT  NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='NQty')
BEGIN
	ALTER TABLE STypeMoveBill ADD NQty   numeric(22,10)   NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='UnitRate')
BEGIN
	ALTER TABLE STypeMoveBill ADD UnitRate   numeric(22,10)  NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='NUnitMsg')
BEGIN
	ALTER TABLE STypeMoveBill ADD NUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='MUnitID')
BEGIN
	ALTER TABLE STypeMoveBill ADD MUnitID  INT  NULL  DEFAULT(0)
END
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='MQty')
BEGIN
	ALTER TABLE STypeMoveBill ADD MQty   numeric(22,10)  NULL  DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='MUnitRate')
BEGIN
	ALTER TABLE STypeMoveBill ADD MUnitRate   numeric(22,10)  NULL  DEFAULT(1)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='MUnitMsg')
BEGIN
	ALTER TABLE STypeMoveBill ADD MUnitMsg   varchar(50)  NULL  
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='MPrice')
BEGIN
	ALTER TABLE STypeMoveBill ADD MPrice   numeric(22,10)  NULL  DEFAULT(0)
END


IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='InCargoID')
BEGIN
	ALTER TABLE STypeMoveBill ADD InCargoID INT NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='STypeMoveBill' AND a.Name='OutCargoID')
BEGIN
	ALTER TABLE STypeMoveBill ADD OutCargoID INT NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE STypeMoveBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE STypeMoveBill ADD IsCombined   INT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE STypeMoveBill ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE STypeMoveBill ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='SendedQty'
)
BEGIN
		ALTER TABLE STypeMoveBill ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0)
END
GO

--调货申请单明细ID
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='AllotID'
)
BEGIN
		ALTER TABLE STypeMoveBill ADD AllotID   INT NULL DEFAULT(0)
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('STypeMoveBill') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table STypeMoveBill drop constraint '+@dfname);
		
	ALTER TABLE STypeMoveBill ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE STypeMoveBill ADD CONSTRAINT DF_STypeMoveBill_Serial DEFAULT('') FOR Serial

END
GO

-- 清除字段 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'InCargoSpace' UNION ALL SELECT 'OutCargoSpace' UNION ALL SELECT 'MTotal';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='STypeMoveBill';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
	
------
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STypeMoveBill]') AND name = N'NCIX_PTYPEID')
	DROP INDEX [dbo].STypeMoveBill.NCIX_PTYPEID
	
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STypeMoveBill]') AND name = N'CIX_BID')
	DROP INDEX [dbo].STypeMoveBill.CIX_BID
	
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STypeMoveBill]') AND name = N'NCIX_KTYPEID')
	DROP INDEX [dbo].STypeMoveBill.NCIX_KTYPEID
	
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STypeMoveBill]') AND name = N'NCIX_KTYPEID2')
	DROP INDEX [dbo].STypeMoveBill.NCIX_KTYPEID2
	
GO
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STYPEMOVEBILL') AND name = 'CIX_STYPEMOVEBILL_BillNumberID')
--DROP INDEX CIX_STYPEMOVEBILL_BillNumberID ON STYPEMOVEBILL 
CREATE CLUSTERED INDEX CIX_STYPEMOVEBILL_BillNumberID ON STYPEMOVEBILL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STYPEMOVEBILL') AND name = 'NCIX_STYPEMOVEBILL_Ktypeid')
--DROP INDEX NCIX_STYPEMOVEBILL_Ktypeid ON STYPEMOVEBILL 
CREATE NONCLUSTERED INDEX NCIX_STYPEMOVEBILL_Ktypeid ON STYPEMOVEBILL(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STYPEMOVEBILL') AND name = 'NCIX_STYPEMOVEBILL_Ktypeid2')
--DROP INDEX NCIX_STYPEMOVEBILL_Ktypeid2 ON STYPEMOVEBILL 
CREATE NONCLUSTERED INDEX NCIX_STYPEMOVEBILL_Ktypeid2 ON STYPEMOVEBILL(Ktypeid2) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STYPEMOVEBILL') AND name = 'NCIX_STYPEMOVEBILL_Stypeid')
--DROP INDEX NCIX_STYPEMOVEBILL_Stypeid ON STYPEMOVEBILL 
CREATE NONCLUSTERED INDEX NCIX_STYPEMOVEBILL_Stypeid ON STYPEMOVEBILL(Stypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('STYPEMOVEBILL') AND name = 'NCIX_STYPEMOVEBILL_Ptypeid')
--DROP INDEX NCIX_STYPEMOVEBILL_Ptypeid ON STYPEMOVEBILL 
CREATE NONCLUSTERED INDEX NCIX_STYPEMOVEBILL_Ptypeid ON STYPEMOVEBILL(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='STypeMoveBill' AND a.Name='MPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE STypeMoveBill 
	ALTER COLUMN MPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'StypePayConfigInfo',N'U'))
BEGIN
	CREATE TABLE StypePayConfigInfo
	(
		ID	       INT IDENTITY(1,1),
		PayConfigID	       INT NOT NULL,
		StypeID        VARCHAR(50) NOT NULL
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('StypePayConfigInfo') AND name = 'CIX_StypePayConfigInfo_ID')
CREATE CLUSTERED INDEX CIX_StypePayConfigInfo_ID ON StypePayConfigInfo(ID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('StypePayConfigInfo') AND name = 'NCIX_StypePayConfigInfo_PayConfigID') 
CREATE NONCLUSTERED INDEX NCIX_StypePayConfigInfo_PayConfigID ON StypePayConfigInfo(PayConfigID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('StypePayConfigInfo') AND name = 'NCIX_StypePayConfigInfo_StypeID')
CREATE NONCLUSTERED INDEX NCIX_StypePayConfigInfo_StypeID ON StypePayConfigInfo(StypeID) 
 
------------------------------------------创建索引区域结束-----------------------------------------------
GO

-------------Start处理之前的账户，处理分支机构为默认--------------
--IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'StypePayConfigInfo',N'U'))
--BEGIN
--	IF (SELECT COUNT(*) FROM StypePayConfigInfo)=0
--	BEGIN
--		DECLARE @payconfiginfoID INT;
--		IF EXISTS(SELECT TOP 1 1 FROM PayConfigInfo WHERE UserCode='ZFB001' AND FullName='默认支付宝'AND IsDefault=1 AND PayType=1)
--		BEGIN
--			SELECT @payconfiginfoID=ID FROM PayConfigInfo WHERE UserCode='ZFB001' AND FullName='默认支付宝'AND IsDefault=1 AND PayType=1
--			INSERT INTO StypePayConfigInfo VALUES(@payconfiginfoID,'00001')
--		END
--		IF EXISTS(SELECT TOP 1 1 FROM PayConfigInfo WHERE UserCode='WX001' AND FullName='默认微信商号'AND IsDefault=1 AND PayType=2)
--		BEGIN
--			SELECT @payconfiginfoID=ID FROM PayConfigInfo WHERE UserCode='WX001' AND FullName='默认微信商号'AND IsDefault=1 AND PayType=2
--			INSERT INTO StypePayConfigInfo VALUES(@payconfiginfoID,'00001')
--		END
--	END	
--END
-------------End处理之前的账户，默认处理为默认支付账户--------------
GO



/****** Object:  Table [dbo].[StypeSaleAllPlan]    Script Date: 07/19/2011 09:48:12 ******/
SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[StypeSaleAllPlan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[StypeSaleAllPlan](
	[ID]  [int] identity(1,1),
	[FullName] [VARCHAR] (400) NOT NULL,
	[AllPlanValue] [decimal](18, 2) NULL,
	[AllRatingValue] [decimal](18, 2) NULL,
	[TotalID] [int] NULL,
	[IfAudit] [bit] NULL,
	[Comment] [varchar](800) NULL,
	[IfUse] [tinyint] NULL,
	[MoneyUnit] [varchar] (50) NULL
) ON [PRIMARY]

GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='StypeSaleAllPlan' AND a.Name='FullName')
BEGIN
	ALTER TABLE StypeSaleAllPlan 
		ADD FullName VARCHAR(400) NULL DEFAULT('') 
END
GO

UPDATE StypeSaleAllPlan SET FullName = '' WHERE FullName IS NULL
GO

SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[StypeSaleplan]    Script Date: 06/23/2011 11:22:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[StypeSaleplan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[StypeSaleplan]---分支机构销售明细计划总表
(       
    [ID]          [int]identity (1,1),   --分支机构明细总表ID
    [SplanID]     [int]         NULL,    --分支机构总表ID
	[StypeID] [varchar](50) NULL,        --分支机构ID
	[RatingValue] [decimal](18, 2) NULL, --额定值
	[PlanValue] [decimal](18, 2) NULL,   --计划值
	[ApportionScale] [decimal](18, 2) NULL,   --分摊比例
    [TimeID] [int] NULL                  --时间表ID
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='StypeSaleplan' AND a.Name='ApportionScale' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE StypeSaleplan 
	ALTER COLUMN ApportionScale NUMERIC(24,10)
    END
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM SysDataDB..sysobjects WHERE id = OBJECT_ID(N'[SysDataDB]..[Sys_City]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [SysDataDB]..[Sys_City] 
		(
			Id			INT IDENTITY(1,1) NOT NULL ,
			AreaId		INT	NULL,
			FullName	VARCHAR(100),
			OrderId		INT NOT NULL DEFAULT(0) 
		) ON [PRIMARY]
	END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM [SysDataDB]..Sys_City)
	BEGIN
		SET IDENTITY_INSERT [SysDataDB]..Sys_City ON
		
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(1,20,'安庆',35)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(2,20,'蚌埠',36)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(3,20,'巢湖',37)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(4,20,'池州',38)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(5,20,'滁州',39)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(6,20,'阜阳',40)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(7,20,'合肥',41)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(8,20,'淮北',42)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(9,20,'淮南',43)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(10,20,'黄山',44)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(11,20,'六安',45)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(12,20,'马鞍山',46)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(13,20,'宿州',47)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(14,20,'铜陵',48)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(15,20,'芜湖',49)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(16,20,'宣城',50)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(17,20,'亳州',51)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(18,12,'北京',52)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(19,6,'福州',53)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(20,6,'龙岩',54)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(21,6,'南平',55)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(22,6,'宁德',56)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(23,6,'莆田',57)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(24,6,'泉州',58)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(25,6,'三明',59)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(26,6,'厦门',60)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(27,6,'漳州',61)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(28,30,'白银',62)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(29,30,'定西',63)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(30,30,'甘南藏族自治州',64)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(31,30,'嘉峪关',65)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(32,30,'金昌',66)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(371,36,'其它地区',406)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(34,30,'酒泉',68)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(35,30,'临夏回族自治州',69)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(36,30,'陇南',70)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(37,30,'平凉',71)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(38,30,'庆阳',72)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(39,30,'天水',73)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(40,30,'武威',74)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(41,30,'张掖',75)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(42,3,'潮州',76)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(43,3,'东莞',77)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(44,3,'佛山',78)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(45,3,'广州',79)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(46,3,'河源',80)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(47,3,'惠州',81)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(48,3,'江门',82)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(49,3,'揭阳',83)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(50,3,'茂名',84)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(51,3,'梅州',85)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(52,3,'清远',86)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(53,3,'汕头',87)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(54,3,'汕尾',88)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(55,3,'韶关',89)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(56,3,'深圳',90)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(57,3,'阳江',91)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(58,3,'云浮',92)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(59,3,'湛江',93)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(60,3,'肇庆',94)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(61,3,'中山',95)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(62,3,'珠海',96)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(63,4,'百色',97)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(64,4,'北海',98)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(65,4,'崇左',99)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(66,4,'防城港',100)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(67,4,'桂林',101)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(68,4,'贵港',102)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(69,4,'河池',103)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(70,4,'贺州',104)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(71,4,'来宾',105)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(72,4,'柳州',106)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(73,4,'南宁',107)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(74,4,'钦州',108)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(75,4,'梧州',109)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(76,4,'玉林',110)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(77,25,'安顺',111)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(78,25,'毕节',112)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(79,25,'贵阳',113)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(80,25,'六盘水',114)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(81,25,'黔东南苗族侗族自治州',115)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(82,25,'黔南布依族苗族自治州',116)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(83,25,'黔西南布依族苗族自治州',117)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(84,25,'铜仁',118)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(85,25,'遵义',119)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(86,5,'白沙黎族自治县',120)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(87,5,'保亭黎族苗族自治县',121)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(88,5,'昌江黎族自治县',122)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(89,5,'澄迈县',123)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(90,5,'定安县',124)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(91,5,'东方',125)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(92,5,'海口',126)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(93,5,'乐东黎族自治县',127)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(94,5,'临高县',128)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(95,5,'陵水黎族自治县',129)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(96,5,'琼海',130)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(97,5,'琼中黎族苗族自治县',131)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(98,5,'三亚',132)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(99,5,'屯昌县',133)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(100,5,'万宁',134)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(101,5,'文昌',135)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(102,5,'五指山',136)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(103,5,'儋州',137)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(104,14,'保定',138)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(105,14,'沧州',139)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(106,14,'承德',140)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(107,14,'邯郸',141)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(108,14,'衡水',142)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(109,14,'廊坊',143)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(110,14,'秦皇岛',144)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(111,14,'石家庄',145)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(112,14,'唐山',146)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(113,14,'邢台',147)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(114,14,'张家口',148)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(115,22,'安阳',149)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(116,22,'鹤壁',150)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(117,22,'济源',151)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(118,22,'焦作',152)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(119,22,'开封',153)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(120,22,'洛阳',154)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(121,22,'南阳',155)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(122,22,'平顶山',156)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(123,22,'三门峡',157)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(124,22,'商丘',158)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(125,22,'新乡',159)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(126,22,'信阳',160)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(127,22,'许昌',161)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(128,22,'郑州',162)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(129,22,'周口',163)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(130,22,'驻马店',164)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(131,22,'漯河',165)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(132,22,'濮阳',166)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(133,11,'大庆',167)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(134,11,'大兴安岭',168)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(135,11,'哈尔滨',169)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(136,11,'鹤岗',170)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(137,11,'黑河',171)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(138,11,'鸡西',172)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(139,11,'佳木斯',173)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(140,11,'牡丹江',174)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(141,11,'七台河',175)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(142,11,'齐齐哈尔',176)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(143,11,'双鸭山',177)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(144,11,'绥化',178)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(145,11,'伊春',179)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(146,7,'鄂州',180)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(147,7,'恩施土家族苗族自治州',181)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(148,7,'黄冈',182)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(149,7,'黄石',183)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(150,7,'荆门',184)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(151,7,'荆州',185)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(152,7,'潜江',186)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(153,7,'神农架林区',187)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(154,7,'十堰',188)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(155,7,'随州',189)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(156,7,'天门',190)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(157,7,'武汉',191)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(158,7,'仙桃',192)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(159,7,'咸宁',193)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(160,7,'襄阳',194)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(161,7,'孝感',195)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(162,7,'宜昌',196)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(163,23,'常德',197)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(164,23,'长沙',198)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(165,23,'郴州',199)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(166,23,'衡阳',200)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(167,23,'怀化',201)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(168,23,'娄底',202)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(169,23,'邵阳',203)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(170,23,'湘潭',204)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(171,23,'湘西土家族苗族自治州',205)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(172,23,'益阳',206)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(173,23,'永州',207)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(174,23,'岳阳',208)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(175,23,'张家界',209)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(176,23,'株洲',210)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(177,10,'白城',211)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(178,10,'白山',212)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(179,10,'长春',213)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(180,10,'吉林',214)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(181,10,'辽源',215)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(182,10,'四平',216)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(183,10,'松原',217)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(184,10,'通化',218)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(185,10,'延边朝鲜族自治州',219)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(186,17,'常州',220)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(187,17,'淮安',221)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(188,17,'连云港',222)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(189,17,'南京',223)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(190,17,'南通',224)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(191,17,'苏州',225)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(192,17,'宿迁',226)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(193,17,'泰州',227)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(194,17,'无锡',228)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(195,17,'徐州',229)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(196,17,'盐城',230)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(197,17,'扬州',231)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(198,17,'镇江',232)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(199,21,'抚州',233)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(200,21,'赣州',234)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(201,21,'吉安',235)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(202,21,'景德镇',236)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(203,21,'九江',237)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(204,21,'南昌',238)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(205,21,'萍乡',239)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(206,21,'上饶',240)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(207,21,'新余',241)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(208,21,'宜春',242)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(209,21,'鹰潭',243)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(210,9,'鞍山',244)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(211,9,'本溪',245)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(212,9,'朝阳',246)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(213,9,'大连',247)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(214,9,'丹东',248)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(215,9,'抚顺',249)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(216,9,'阜新',250)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(217,9,'葫芦岛',251)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(218,9,'锦州',252)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(219,9,'辽阳',253)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(220,9,'盘锦',254)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(221,9,'沈阳',255)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(222,9,'铁岭',256)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(223,9,'营口',257)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(224,15,'阿拉善盟',258)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(225,15,'巴彦淖尔盟',259)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(226,15,'包头',260)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(227,15,'赤峰',261)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(228,15,'鄂尔多斯',262)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(229,15,'呼和浩特',263)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(230,15,'呼伦贝尔',264)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(231,15,'通辽',265)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(232,15,'乌海',266)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(233,15,'乌兰察布盟',267)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(234,15,'锡林郭勒盟',268)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(235,15,'兴安盟',269)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(236,31,'固原',270)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(237,31,'石嘴山',271)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(238,31,'吴忠',272)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(239,31,'银川',273)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(240,26,'果洛藏族自治州',274)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(241,26,'海北藏族自治州',275)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(242,26,'海东',276)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(243,26,'海南藏族自治州',277)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(244,26,'海西蒙古族藏族自治州',278)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(245,26,'黄南藏族自治州',279)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(246,26,'西宁',280)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(247,26,'玉树藏族自治州',281)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(248,16,'滨州',282)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(249,16,'德州',283)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(250,16,'东营',284)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(251,16,'菏泽',285)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(252,16,'济南',286)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(253,16,'济宁',287)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(254,16,'莱芜',288)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(255,16,'聊城',289)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(256,16,'临沂',290)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(257,16,'青岛',291)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(258,16,'日照',292)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(259,16,'泰安',293)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(260,16,'威海',294)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(261,16,'潍坊',295)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(262,16,'烟台',296)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(263,16,'枣庄',297)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(264,16,'淄博',298)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(265,32,'长治',299)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(266,32,'大同',300)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(267,32,'晋城',301)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(268,32,'晋中',302)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(269,32,'临汾',303)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(270,32,'吕梁',304)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(271,32,'朔州',305)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(272,32,'太原',306)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(273,32,'忻州',307)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(274,32,'阳泉',308)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(275,32,'运城',309)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(276,29,'安康',310)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(277,29,'宝鸡',311)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(278,29,'汉中',312)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(279,29,'商洛',313)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(280,29,'铜川',314)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(281,29,'渭南',315)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(282,29,'西安',316)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(283,29,'咸阳',317)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(284,29,'延安',318)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(285,29,'榆林',319)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(286,19,'上海',320)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(287,1,'简阳',321)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(288,1,'巴中',322)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(289,1,'成都',323)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(290,1,'达州',324)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(291,1,'德阳',325)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(292,1,'甘孜藏族自治州',326)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(293,1,'广安',327)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(294,1,'广元',328)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(295,1,'乐山',329)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(296,1,'凉山彝族自治州',330)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(297,1,'眉山',331)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(298,1,'绵阳',332)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(299,1,'南充',333)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(300,1,'内江',334)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(301,1,'攀枝花',335)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(302,1,'遂宁',336)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(303,1,'雅安',337)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(304,1,'宜宾',338)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(305,1,'资阳',339)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(306,1,'自贡',340)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(307,1,'泸州',341)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(308,13,'天津',342)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(309,27,'阿里',343)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(310,27,'昌都',344)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(311,27,'拉萨',345)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(312,27,'林芝',346)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(313,27,'那曲',347)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(314,27,'日喀则',348)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(315,27,'山南',349)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(316,28,'阿克苏',350)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(317,28,'阿拉尔',351)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(318,28,'巴音郭楞蒙古自治州',352)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(319,28,'博尔塔拉蒙古自治州',353)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(320,28,'昌吉回族自治州',354)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(321,28,'哈密',355)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(322,28,'和田',356)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(323,28,'喀什',357)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(324,28,'克拉玛依',358)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(325,28,'克孜勒苏柯尔克孜自治州',359)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(326,28,'石河子',360)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(327,28,'图木舒克',361)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(328,28,'吐鲁番',362)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(329,28,'乌鲁木齐',363)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(330,28,'五家渠',364)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(331,28,'伊犁哈萨克自治州',365)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(332,24,'保山',366)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(333,24,'楚雄彝族自治州',367)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(334,24,'大理白族自治州',368)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(335,24,'德宏傣族景颇族自治州',369)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(336,24,'迪庆藏族自治州',370)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(337,24,'红河哈尼族彝族自治州',371)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(338,24,'昆明',372)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(339,24,'丽江',373)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(340,24,'临沧',374)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(341,24,'怒江傈傈族自治州',375)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(342,24,'曲靖',376)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(343,24,'普洱',377)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(344,24,'文山壮族苗族自治州',378)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(345,24,'西双版纳傣族自治州',379)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(346,24,'玉溪',380)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(347,24,'昭通',381)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(348,18,'杭州',382)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(349,18,'湖州',383)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(350,18,'嘉兴',384)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(351,18,'金华',385)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(352,18,'丽水',386)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(353,18,'宁波',387)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(354,18,'绍兴',388)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(355,18,'台州',389)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(356,18,'温州',390)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(357,18,'舟山',391)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(358,18,'衢州',392)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(359,2,'重庆',393)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(360,33,'香港',394)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(361,34,'澳门',395)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(362,35,'台湾',396)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(363,4,'东兴',397)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(364,24,'大理',398)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(365,30,'兰州',399)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(366,1,'资中',402)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(367,6,'云霄',405)
		INSERT INTO [SysDataDB]..Sys_City(Id,AreaId,FullName,OrderId)VALUES(372,1,'阿坝藏族羌族自治州',408)
		
		SET IDENTITY_INSERT [SysDataDB]..Sys_City OFF
	END
GO



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Sys_InventoryTypePerset') AND  type = 'U')
BEGIN
	CREATE TABLE Sys_InventoryTypePerset
	(
		Id				INT IDENTITY(1,1),  --自增长ID	
		SubId			INT,				--科目表类别，对应Ac_Account_Set_List中的SubId
		InventoryType	INT,				--存货类型
		usercode		VARCHAR(200),		--编号
		fullname		VARCHAR(200),		--名称
		comment			VARCHAR(200),		--备注
		Stockfullname	VARCHAR(200),		--存货核算科目
		Incomefullname	VARCHAR(200),		--销售收入科目
		Costfullname	VARCHAR(200)		--销售成本科目
	)
END

--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='Sys_InventoryTypePerset' AND a.Name='AuditType'
--)
--BEGIN
--	ALTER TABLE Sys_InventoryTypePerset ADD AuditType INT NULL DEFAULT (0)
--END



--添加默认数据，请加上列名isCost进行区分

IF NOT EXISTS(SELECT TOP 1 1 FROM Sys_InventoryTypePerset)
BEGIN
	INSERT Sys_InventoryTypePerset(SubId,InventoryType,usercode,fullname,comment,Stockfullname,Incomefullname,Costfullname)
	VALUES	(1,1,'CH01','原材料','','原材料','其他业务收入','其他业务支出'),
			(1,2,'CH02','库存商品','','库存商品','主营业务收入','主营业务成本'),
			(2,1,'CH01','原材料','','原材料','其他业务收入','其他业务支出'),
			(2,2,'CH02','库存商品','','库存商品','主营业务收入','主营业务成本'),
			(28,1,'CH01','原材料','','原材料','其他业务收入','其他业务成本'),
			(28,2,'CH02','库存商品','','库存商品','主营业务收入','主营业务成本')
END

--select * from Ac_Account_Set_Detail where SubId in (
--SELECT SubId FROM Ac_Account_Set_List WHERE FullName IN('新会计准则科目','小企业会计准则科目','企业会计制度科目')) and FullName in('原材料','其他业务支出','其他业务收入')

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO



IF NOT EXISTS (SELECT * FROM SysDataDB..sysobjects WHERE id = OBJECT_ID(N'[SysDataDB]..[Sys_Province]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [SysDataDB]..[Sys_Province]
		(
			Id			INT IDENTITY (1, 1) NOT NULL ,
			UserCode	VARCHAR(20),
			FullName	VARCHAR(50),
			Deleted		BIT NOT NULL DEFAULT(0)
		)
	END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM [SysDataDB]..Sys_Province)
	BEGIN
		SET IDENTITY_INSERT [SysDataDB]..Sys_Province ON
		
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(1,'01','四川',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(2,'02','重庆',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(3,'03','广东',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(4,'04','广西',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(5,'05','海南',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(6,'06','福建',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(7,'07','湖北',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(9,'09','辽宁',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(10,'10','吉林',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(11,'11','黑龙江',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(12,'12','北京',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(13,'13','天津',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(14,'14','河北',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(15,'15','内蒙古',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(16,'16','山东',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(17,'17','江苏',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(18,'18','浙江',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(19,'19','上海',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(20,'20','安徽',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(21,'21','江西',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(22,'22','河南',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(23,'23','湖南',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(24,'24','云南',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(25,'25','贵州',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(26,'26','青海',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(27,'27','西藏',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(28,'28','新疆',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(29,'29','陕西',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(30,'30','甘肃',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(31,'31','宁夏',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(32,'32','山西',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(33,'33','香港',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(34,'34','澳门',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(35,'35','台湾',0)
		INSERT INTO [SysDataDB]..Sys_Province(Id,UserCode,FullName,Deleted)VALUES(36,'36','其它地区',0)
		
		SET IDENTITY_INSERT [SysDataDB]..Sys_Province OFF
	END
GO



IF NOT EXISTS (SELECT * FROM SysDataDB..sysobjects WHERE id = OBJECT_ID(N'[SysDataDB]..[Sys_RefIndustry]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [SysDataDB]..[Sys_RefIndustry] 
		(
			Id			INT	IDENTITY(1,1) NOT NULL ,
			FullName	VARCHAR(200) NULL ,
			Deleted		BIT NOT NULL DEFAULT(0)
		) ON [PRIMARY]
	END
GO
--================================插入预置数据==============================================
IF NOT EXISTS(SELECT TOP 1 1 FROM [SysDataDB]..Sys_RefIndustry)
	BEGIN
		SET IDENTITY_INSERT [SysDataDB]..Sys_RefIndustry ON
		
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(27,'服装、鞋业',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(28,'皮具、箱包',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(29,'办公用品、图书、音像',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(30,'IT业、数码、通讯',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(31,'珠宝、玉器、饰品',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(32,'食品、饮料、烟酒',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(33,'超市、百货、商场',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(34,'农资、农业、养殖',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(35,'餐饮、娱乐、物业',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(36,'美容、美发、化妆品',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(37,'布匹、纺织、床上用品',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(38,'五金建材、灯饰、家装、家具',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(39,'电子、家电、机电、设备',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(40,'母婴、文体、户外用品',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(41,'医药、保健、诊所、医疗器械',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(42,'汽车销售、汽车美容、汽配、汽修、摩配',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(43,'事业单位(国营性质企业）',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(44,'冶金、矿业、化工',0)
		INSERT INTO [SysDataDB]..Sys_RefIndustry(Id,FullName,Deleted)VALUES(45,'其它',0)
		
		SET IDENTITY_INSERT [SysDataDB]..Sys_refindustry OFF
	END
GO



/****** 对象:  Table [dbo].[sysdata1]    脚本日期: 05/05/2010 14:49:34 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sysdata1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sysdata1](
		[SubNo] [numeric](4, 0) NOT NULL,
		[SubName] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[SubValue] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[SubComment] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]

	-- ********	处理 SysData1	********
	DELETE FROM SysData1
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('1','OffLine','0','') 			--基础版(汽配默认只能是基础版)
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('2','Validate','0','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('3','OPCounter','0','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('4','LanSign','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('5','AccountNum','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('6','ZCFlag','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('7','UseDate','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('8','IfNewDog','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('9','Company','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('10','DogNo','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('11','AreaName','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('12','SeriaNo','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('13','ZCDate','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('14','QPEdition','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('15','ProInfo','','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('16','IsUseAcSystem','','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('17','newOffLine','14','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('18','CentificateNo','','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('19','CentificateNum','','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('20','IsTopDog','0','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('21','curinfo','','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('22','CorpTel','','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('23','Mobil','','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('24','EMail','','')	
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('25','OmValid','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('26','PosValid','','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('27','isSstages','0','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('28','isSstagesEndDate','0','')
	INSERT INTO SysData1(SubNo,SubName,SubValue,SubComment) VALUES('31','LastCountTime','','')
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Sysdata1]') and  name = 'SubValue' and Length=100)
BEGIN
	 ALTER TABLE Sysdata1
	    ALTER COLUMN SubValue VARCHAR(500) NOT NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Sysdata1]') and  name = 'SubValue' and Length=500)
BEGIN
	 ALTER TABLE Sysdata1
	    ALTER COLUMN SubValue VARCHAR(5000) NOT NULL
END
GO

--升级包增加预制数据
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata1 WHERE SubName = 'QPEdition')
BEGIN
	INSERT INTO Sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('14','QPEdition','','')
END
GO

--升级包增加预制数据
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata1 WHERE SubName = 'IsUseAcSystem')
BEGIN
	INSERT INTO Sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('16','IsUseAcSystem','','')
END
GO

--升级包增加预制数据
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata1 WHERE SubName = 'newOffLine')
BEGIN
	INSERT INTO Sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('17','newOffLine','14','')
END
GO

--证书号
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata1 WHERE SubName = 'CentificateNo')
BEGIN
	INSERT INTO Sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('18','CentificateNo','','')
END
GO

--安全码
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata1 WHERE SubName = 'CentificateNum')
BEGIN
	INSERT INTO Sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('19','CentificateNum','','')
END
GO

--是否TOP狗
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata1 WHERE SubName = 'IsTopDog')
BEGIN
	INSERT INTO Sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('20','IsTopDog','','')
END
GO

--当前信息
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='curinfo')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('21','curinfo','','')
END
GO

--当前信息
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='CorpTel')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('22','CorpTel','','')
END
GO

--当前信息
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='Mobil')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('23','Mobil','','')
END
GO

--当前信息
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='EMail')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('24','EMail','','')
END
GO

--OM验证
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='OmValid')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('25','OmValid','','')
END
GO

--POS验证
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='PosValid')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('26','PosValid','','')
END
GO

--是否分期系统
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='isSstages')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('27','isSstages','','')
END
GO

--分期到期日期
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='isSstagesEndDate')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('28','isSstagesEndDate','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='ZTUniqueCode')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('29','ZTUniqueCode','','')
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='BillSaveCheck')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES(30,'BillSaveCheck','','')
END
GO
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='LastCountTime')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('31','LastCountTime','','')
END
GO
--pos
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='posuserCount')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('32','posuserCount','0','')
END
GO
--软狗服务器时间
IF NOT EXISTS(SELECT 1 FROM sysdata1 WHERE SubName='VerificaDate')
BEGIN
	INSERT INTO sysdata1(SubNo,SubName,SubValue,SubComment)VALUES('33','VerificaDate','','')
END
GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[sysdata1]') AND name = N'PK_sysdata1')
ALTER TABLE [dbo].[sysdata1] DROP CONSTRAINT [PK_sysdata1]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('SYSDATA1') AND name = 'NCIX_SYSDATA1_SubNo')
--DROP INDEX NCIX_SYSDATA1_SubNo ON SYSDATA1 
CREATE NONCLUSTERED INDEX NCIX_SYSDATA1_SubNo ON SYSDATA1(SubNo) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[sysmovedata]    脚本日期: 05/05/2010 14:49:35 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[sysmovedata]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[sysmovedata](
		[typeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[newparid] [varchar](25) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[flag] [int] NOT NULL,
		[happendate] [datetime] NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[TaxInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE TaxInfo
	(
		TaxID			INT IDENTITY(1,1) NOT NULL,
		UserCode		VARCHAR(200) NULL,
		FullName		VARCHAR(200) NULL,
		TaxType			INT NULL DEFAULT(0) ,
		Tax				NUMERIC(5, 2) NULL DEFAULT (0),
		Comment			VARCHAR(500) NULL,
		PyCode			VARCHAR(100) NULL
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TaxInfo' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TaxInfo 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[tbShowSet]    脚本日期: 05/05/2010 14:49:36 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[tbShowSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[tbShowSet](
		[No] [int] IDENTITY(1,1) NOT NULL,
		[FullName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[UserCode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[TypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfShow] [bit] NULL CONSTRAINT [DF_tbShowSet_IfShow]  DEFAULT (1)
	) ON [PRIMARY]

	-- ********	处理物价信息配置 - tbShowSet	********
	DELETE FROM tbShowSet
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('商品编号','UserCode','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('商品名称','FullName','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('条码','entrycode','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('单位','unit','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('规格','Standard','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('型号','type','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('产地','Area','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('预售价1','Preprice1','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('预售价2','Preprice2','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('预售价3','Preprice3','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('预售价4','Preprice4','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('预设进价','Preprice5','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('成本均价','cost','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('最近进价','recprice','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('毛利率','gprofit','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('数量','QTY','priceinfo','1')
	INSERT INTO tbShowSet([FullName],[UserCode],[TypeID],[IfShow]) VALUES('备注','comment','priceinfo','1')
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[TCBill]    脚本日期: 05/05/2010 14:49:36 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[TCBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[TCBill](
		[BillnumberID] [numeric](10, 0) NOT NULL,
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[EtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[SubName] [varchar](1000) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Sub] [varchar](2000) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Row] [int] NOT NULL,
		[ConstFlag] [int] NOT NULL CONSTRAINT [DF_TCBill_ConstFlag]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[TCBillindex]    脚本日期: 05/05/2010 14:49:37 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[TCBillindex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[TCBillindex](
		[BillnumberID] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_TCBillindex_BillCode]  DEFAULT (''),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_TCBillindex_Comment]  DEFAULT (''),
		[StartDate] [datetime] NOT NULL,
		[EndDate] [datetime] NOT NULL,
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_TCBillindex_checke]  DEFAULT (''),
		[EtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_TCBillindex_EtypeID]  DEFAULT ('')
		--[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--是否启用 1.启用 0.不启用
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TCBillindex' AND a.Name='IsUse'
)
BEGIN
	ALTER TABLE TCBillindex 
		ADD IsUse INT NULL DEFAULT(1)
END
------------------------------------------表修改区域结束-------------------------------------------------
GO
UPDATE TCBillindex SET IsUse = 1 WHERE IsUse IS NULL
GO

--反审核人
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TCBillindex' AND a.Name='unChecke'
)
BEGIN
	ALTER TABLE TCBillindex 
		ADD unChecke VARCHAR(50)
END
------------------------------------------表修改区域结束-------------------------------------------------
GO
UPDATE TCBillindex SET unChecke = '' WHERE unChecke IS NULL
GO

--反审核世间
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TCBillindex' AND a.Name='unCheckTime'
)
BEGIN
	ALTER TABLE TCBillindex 
		ADD unCheckTime VARCHAR(50)
END
------------------------------------------表修改区域结束-------------------------------------------------
GO
UPDATE TCBillindex SET unCheckTime = '' WHERE unCheckTime IS NULL
GO
------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  未达账明细
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_AccountInTransit_Detail') AND  type = 'U')
BEGIN
	CREATE TABLE Te_AccountInTransit_Detail
	(
		Id			INT IDENTITY(1,1),												--自增id
		IndexId		INT,															--表头id
		CreateDate	DATETIME,														--业务日期
		Summary		VARCHAR(1000) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--摘要
		ETypeId		VARCHAR(50),													--经手人
		FSettleId	INT,															--结算方式
		FSettleNo	VARCHAR(50),													--结算号
		FDebit		NUMERIC(18,2),													--借方
		FCredit		NUMERIC(18,2)													--贷方
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Detail' AND a.Name='FDebit'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Detail ALTER COLUMN FDebit NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Detail' AND a.Name='FCredit'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Detail ALTER COLUMN FCredit NUMERIC(18,2)
END
GO

--增加相应的本位币列
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Detail' AND a.Name='FDebitOri'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Detail ADD FDebitOri NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Detail' AND a.Name='FCreditOri'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Detail ADD FCreditOri NUMERIC(18,2)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Detail' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Detail 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Detail' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Detail 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Detail' AND a.Name='FDebitOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Detail 
	ALTER COLUMN FDebitOri NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Detail' AND a.Name='FCreditOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Detail 
	ALTER COLUMN FCreditOri NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  未达账表头
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_AccountInTransit_Index') AND  type = 'U')
BEGIN
	CREATE TABLE Te_AccountInTransit_Index
	(
		Id				INT	IDENTITY(1,1),	--自增id
		AccountId		INT,				--银行账户id
		FDebitTotal		NUMERIC(18,2),		--借方总额
		FCreditTotal	NUMERIC(18,2),		--贷方总额
		[Type]			INT,				--类型：0.银行未达账 1.企业未达账
		IsInit			INT DEFAULT(0),		--是否期初 0.非期初 1.期初
		ATypeId			VARCHAR(50),		--科目
		Cid				INT,				--币种
		Rate			NUMERIC(22,4)		--汇率
	)
END
GO

--科目
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='ATypeId'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Index ADD ATypeId VARCHAR(50) NULL DEFAULT('')
END
GO

--币种
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='Cid'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Index ADD Cid INT
END
GO

--汇率
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Index ADD Rate NUMERIC(22,4)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='FDebitTotal'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Index ALTER COLUMN FDebitTotal NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='FCreditTotal'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Index ALTER COLUMN FCreditTotal NUMERIC(18,2)
END
GO

--增加相应的本位币列
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='FDebitTotalOri'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Index ADD FDebitTotalOri NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='FCreditTotalOri'
)
BEGIN
	ALTER TABLE Te_AccountInTransit_Index ADD FCreditTotalOri NUMERIC(18,2)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='FDebitTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Index 
	ALTER COLUMN FDebitTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='FCreditTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Index 
	ALTER COLUMN FCreditTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Index 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='FDebitTotalOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Index 
	ALTER COLUMN FDebitTotalOri NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_AccountInTransit_Index' AND a.Name='FCreditTotalOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_AccountInTransit_Index 
	ALTER COLUMN FCreditTotalOri NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳自动对账条件
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_AutoCheckRules') AND  type = 'U')
BEGIN
	CREATE TABLE Te_AutoCheckRules
	(
		Id			INT,			--Id
		FullName	VARCHAR(100),	--名字
		IsUse		INT				--是否使用
	)
END
GO

--预置数据
IF NOT EXISTS(SELECT TOP 1 1 FROM Te_AutoCheckRules)
BEGIN
	INSERT INTO Te_AutoCheckRules(Id,FullName,IsUse)
	VALUES(1,'金额相等',1),
		  (2,'结算日期相同',0),
		  (3,'结算方式一致',0),
		  (4,'结算号相同',0)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳余额表
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_Balance') AND  type = 'U')
BEGIN
	CREATE TABLE Te_Balance
	(
		Id				INT IDENTITY(1,1),	--自增id
		AccountId		INT,				--银行账户Id
		BUId			INT,				--业务类型 Te_BusinessType
		ATypeId			VARCHAR(50),		--对应的会计科目
		STypeId			VARCHAR(50),		--相应的分支机构
		InitBalance		NUMERIC(18,2),		--期初余额本币
		InitBalanceFor	NUMERIC(18,2),		--期初余额原币
		InitYearBalance	NUMERIC(18,2),		--年初余额本币
		InitYearBalanceFor	NUMERIC(18,2),	--年初余额原币
		Cid				INT,				--币种
		FYear			INT,				--年度
		FPeriod			INT,				--期间
		FDebit			NUMERIC(18,2),		--借方发生本币
		FDebitFor		NUMERIC(18,2),		--借方发生原币
		FCredit			NUMERIC(18,2),		--贷方发生本币
		FCreditFor		NUMERIC(18,2),		--贷方发生原币
		FEndBalance		NUMERIC(18,2),		--期末余额本币
		FEndBalanceFor	NUMERIC(18,2),		--期末余额原币
		FYtdDebit		NUMERIC(18,2),		--本年借方累计本币
		FYtdDebitFor	NUMERIC(18,2),		--本年借方累计原币
		FYtdCredit		NUMERIC(18,2),		--本年贷方累计本币
		FYtdCreditFor	NUMERIC(18,2)		--本年贷方累计原币
	)
END
GO

--调整字段BId为BUId
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='BId'
)
BEGIN
	ALTER TABLE Te_Balance DROP COLUMN BId
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='BUId'
)
BEGIN
	ALTER TABLE Te_Balance ADD BUId INT
END
GO

--对应的会计科目
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='ATypeId'
)
BEGIN
	ALTER TABLE Te_Balance ADD ATypeId VARCHAR(50)
END
GO
--分支机构
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='STypeid'
)
BEGIN
	ALTER TABLE Te_Balance ADD STypeid VARCHAR(50)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='InitBalanceFor'
)
BEGIN
	ALTER TABLE Te_Balance ADD InitBalanceFor NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='InitYearBalanceFor'
)
BEGIN
	ALTER TABLE Te_Balance ADD InitYearBalanceFor NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FDebitFor'
)
BEGIN
	ALTER TABLE Te_Balance ADD FDebitFor NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FCreditFor'
)
BEGIN
	ALTER TABLE Te_Balance ADD FCreditFor NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FEndBalanceFor'
)
BEGIN
	ALTER TABLE Te_Balance ADD FEndBalanceFor NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FYtdDebitFor'
)
BEGIN
	ALTER TABLE Te_Balance ADD FYtdDebitFor NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FYtdCreditFor'
)
BEGIN
	ALTER TABLE Te_Balance ADD FYtdCreditFor NUMERIC(18,2)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_Balance') AND name = 'CIX_Te_Balance_ID')
DROP INDEX CIX_Te_Balance_ID ON Te_Balance 
CREATE CLUSTERED INDEX CIX_Te_Balance_ID ON Te_Balance(Id) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_Balance') AND name = 'CIX_Te_Balance_AccountId')
DROP INDEX CIX_Te_Balance_AccountId ON Te_Balance 
CREATE NONCLUSTERED INDEX CIX_Te_Balance_AccountId ON Te_Balance(AccountId) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_Balance') AND name = 'CIX_Te_Balance_ATypeId')
DROP INDEX CIX_Te_Balance_ATypeId ON Te_Balance 
CREATE NONCLUSTERED INDEX CIX_Te_Balance_ATypeId ON Te_Balance(ATypeId) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='InitBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN InitBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='InitBalanceFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN InitBalanceFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='InitYearBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN InitYearBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='InitYearBalanceFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN InitYearBalanceFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FCreditFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FEndBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FEndBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FEndBalanceFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FEndBalanceFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FYtdDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FYtdDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FYtdDebitFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FYtdDebitFor NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FYtdCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FYtdCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Balance' AND a.Name='FYtdCreditFor' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Balance 
	ALTER COLUMN FYtdCreditFor NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
* 金融机构
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_Bank') AND  type = 'U')
BEGIN
	CREATE TABLE Te_Bank
	(
		Id				INT IDENTITY(1,1),												--自增Id
		UserCode		VARCHAR(26) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT (''),	--编号
		FullName		VARCHAR(66)	COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT (''),	--名称
		[Address]		VARCHAR(1000) DEFAULT(''),										--地址
		PhoneNum		VARCHAR(50) DEFAULT(''),										--电话
		ContactMan		VARCHAR(50) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT (''),	--联系人
		Comment			VARCHAR(1000) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--备注
		IsSys			INT	DEFAULT(0)													--是否预置
	)
END
GO
--预置数据
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Bank WHERE IsSys = 1)
BEGIN
	SET IDENTITY_INSERT dbo.Te_Bank ON

	INSERT INTO dbo.Te_Bank
			( 
			  Id,
			  UserCode ,
			  FullName ,
			  [Address] ,
			  PhoneNum ,
			  ContactMan ,
			  Comment ,
			  IsSys
			)
	VALUES  (1,'JR001','中国工商银行','','','','国有商业银行',1),
			(2,'JR002','中国农业银行','','','','国有商业银行',1),
			(3,'JR003','中国建设银行','','','','国有商业银行',1),
			(4,'JR004','交通银行','','','','国有商业银行',1),
			(5,'JR005','中国银行','','','','国有商业银行',1),
			(6,'JR006','招商银行','','','','股份制商业银行',1),
			(7,'JR007','中信银行','','','','股份制商业银行',1),
			(8,'JR008','华夏银行','','','','股份制商业银行',1),
			(9,'JR009','中国光大银行','','','','股份制商业银行',1),
			(10,'JR010','中国民生银行','','','','股份制商业银行',1),
			(11,'JR011','兴业银行','','','','股份制商业银行',1),
			(12,'JR012','广发银行','','','','股份制商业银行',1),
			(13,'JR013','平安银行','','','','股份制商业银行',1),
			(14,'JR014','恒丰银行','','','','股份制商业银行',1),
			(15,'JR015','渤海银行','','','','股份制商业银行',1),
			(16,'JR016','上海浦东发展银行','','','','股份制商业银行',1),
			(17,'JR017','中国邮政储蓄银行','','','','股份制商业银行',1)

	SET IDENTITY_INSERT dbo.Te_Bank OFF
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
* 银行账户
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_BankAccount') AND  type = 'U')
BEGIN
	CREATE TABLE Te_BankAccount
	(
		Id				INT IDENTITY(1,1),												--自增id
		UserCode		VARCHAR(26) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT (''),	--编号
		FullName		VARCHAR(66)	COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT (''),	--名称
		AccountNumber	VARCHAR(50)	DEFAULT(''),										--账号
		STypeId			VARCHAR(50) DEFAULT(''),										--开户分支机构typeId
		BankId			INT,															--金融机构id
		ATypeId			VARCHAR(50) DEFAULT(''),										--会计科目
		CreateDate		DATETIME,														--开户日期
		IsDestroy		INT,															--是否销户 0.未销户 1.销户
		DestroyDate		DATETIME,														--销户日期
		DestroyReson	VARCHAR(1000) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--销户原因
		Comment			VARCHAR(1000) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--备注
		Cid				INT,															--币种
		XiWaMaxNumber	NUMERIC(18, 0) NULL DEFAULT (0)
	)
END
GO

--年结对银行账户的标识
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankAccount' AND a.Name='YearClose'
)
BEGIN
	ALTER TABLE Te_BankAccount ADD YearClose INT DEFAULT(0)
END
GO


------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_BankAccount') AND name = 'CIX_Te_BankAccount_ID')
DROP INDEX CIX_Te_BankAccount_ID ON Te_BankAccount 
CREATE CLUSTERED INDEX CIX_Te_BankAccount_ID ON Te_BankAccount(Id) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳——银行对账单
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_BankStatement') AND  type = 'U')
BEGIN
	CREATE TABLE Te_BankStatement
	(
		Id					INT	IDENTITY(1,1),	--自增id
		Businessdate		DATETIME,			--业务日期
		YesterdayFBalance	NUMERIC(18,2),		--上日余额
		FDebitTotal			NUMERIC(18,2),		--本日借方累计
		FCreditTotal		NUMERIC(18,2),		--本日贷方累计
		FBalance			NUMERIC(18,2),		--本日余额
		AccountId			INT,				--银行账户id
		Cid					INT,				--币种
		FDC					INT,				--借贷方向 1.借 -1.贷
	)
END
GO

--币种
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='Cid'
)
BEGIN
	ALTER TABLE Te_BankStatement 
		ADD Cid INT NULL DEFAULT(0)
END
GO

--借贷方向
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='FDC'
)
BEGIN
	ALTER TABLE Te_BankStatement 
		ADD FDC INT NULL DEFAULT(0)
END
GO


IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='YesterdayFBalance'
)
BEGIN
	ALTER TABLE Te_BankStatement ALTER COLUMN YesterdayFBalance NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='FDebitTotal'
)
BEGIN
	ALTER TABLE Te_BankStatement ALTER COLUMN FDebitTotal NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='FCreditTotal'
)
BEGIN
	ALTER TABLE Te_BankStatement ALTER COLUMN FCreditTotal NUMERIC(18,2)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='YesterdayFBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_BankStatement 
	ALTER COLUMN YesterdayFBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='FDebitTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_BankStatement 
	ALTER COLUMN FDebitTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='FCreditTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_BankStatement 
	ALTER COLUMN FCreditTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatement' AND a.Name='FBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_BankStatement 
	ALTER COLUMN FBalance NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳——银行对账单明细
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_BankStatementDetail') AND  type = 'U')
BEGIN
	CREATE TABLE Te_BankStatementDetail
	(
		Id				INT IDENTITY(1,1),												--自增id
		Businessdate	DATETIME,														--业务日期
		BusinessId		VARCHAR(50) DEFAULT(''),										--交易号
		TellerName		VARCHAR(50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),		--柜员
		FSettleId		INT,															--结算方式
		FSettleNo		VARCHAR(50),													--结算号
		ETypeId			VARCHAR(50),													--出纳
		Summary			VARCHAR(1000) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--摘要
		FDebit			NUMERIC(18,2),													--借方
		FCredit			NUMERIC(18,2),													--贷方
		FEndBalance		NUMERIC(18,2),													--余额
		SourceId		INT,															--来源Id Te_Journal_SourceType
		AccountId		INT,															--银行账户Id
		FDC				INT,															--借贷方向 1.借 -1.贷
		Cid				INT,															--币种
		Rate			NUMERIC(22,4)													--汇率
	)
END
GO

--币种
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='Cid'
)
BEGIN
	ALTER TABLE Te_BankStatementDetail 
		ADD Cid INT NULL DEFAULT(0)
END
GO

--汇率
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE Te_BankStatementDetail ADD Rate NUMERIC(22,4)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='FDebit'
)
BEGIN
	ALTER TABLE Te_BankStatementDetail ALTER COLUMN FDebit NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='FCredit'
)
BEGIN
	ALTER TABLE Te_BankStatementDetail ALTER COLUMN FCredit NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='FEndBalance'
)
BEGIN
	ALTER TABLE Te_BankStatementDetail ALTER COLUMN FEndBalance NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='IsInit'
)
BEGIN
	ALTER TABLE Te_BankStatementDetail ADD IsInit INT DEFAULT 0
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_BankStatementDetail') AND name = 'CIX_Te_BankStatementDetail_ID')
DROP INDEX CIX_Te_BankStatementDetail_ID ON Te_BankStatementDetail 
CREATE CLUSTERED INDEX CIX_Te_BankStatementDetail_ID ON Te_BankStatementDetail(Id) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_BankStatementDetail') AND name = 'CIX_Te_BankStatementDetail_AccountId')
DROP INDEX CIX_Te_BankStatementDetail_AccountId ON Te_BankStatementDetail 
CREATE NONCLUSTERED INDEX CIX_Te_BankStatementDetail_AccountId ON Te_BankStatementDetail(AccountId) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_BankStatementDetail 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_BankStatementDetail 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='FEndBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_BankStatementDetail 
	ALTER COLUMN FEndBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_BankStatementDetail' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_BankStatementDetail 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳业务类型
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_BusinessType') AND  type = 'U')
BEGIN
	CREATE TABLE Te_BusinessType
	(
		Id			INT,		--类型编号
		FullName	VARCHAR(50)	--类型名字
	)
END
GO

--预置数据
IF NOT EXISTS(SELECT TOP 1 1 FROM Te_BusinessType)
BEGIN
	INSERT INTO Te_BusinessType(Id,FullName)
	VALUES	(1,'现金'),
			(2,'银行存款'),
			(3,'银行对账单')
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳——勾对对照表
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_CheckRelevance') AND  type = 'U')
BEGIN
	CREATE TABLE Te_CheckRelevance
	(
		Id				INT IDENTITY(1,1),	--自增id
		JournalId		INT,				--银行日记账Id
		StatementId		INT,				--银行对账单Id
		RelevanceDate	DATETIME,			--勾对日期
		GroupId			INT					--勾对组id sp：971新需求，统计合计勾对
	)
END
GO

--勾对日期
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_CheckRelevance' AND a.Name='RelevanceDate'
)
BEGIN
	ALTER TABLE Te_CheckRelevance ADD RelevanceDate DATETIME
END
GO

--期初企业未达账 1
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_CheckRelevance' AND a.Name='StatementAccountInTransitId'
)
BEGIN
	ALTER TABLE Te_CheckRelevance ADD StatementAccountInTransitId INT
END
GO

--期初银行未达账 0
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_CheckRelevance' AND a.Name='JournalAccountInTransitId'
)
BEGIN
	ALTER TABLE Te_CheckRelevance ADD JournalAccountInTransitId INT
END
GO

--勾对组id sp：971新需求，统计合计勾对
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_CheckRelevance' AND a.Name='GroupId'
)
BEGIN
	ALTER TABLE Te_CheckRelevance ADD GroupId INT
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳期初明细
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_InitDataDetail') AND  type = 'U')
BEGIN
	CREATE TABLE Te_InitDataDetail
	(
		Id			INT IDENTITY(1,1),	--自增id
		IndexId		INT,				--表头Id
		AtypeId		VARCHAR(50),		--会计科目
		FDebit		NUMERIC(22,4),		--借方累计发生
		FCredit		NUMERIC(22,4),		--贷方累计发生
		InitBalance	NUMERIC(22,4),		--期初余额
		AccountId	INT					--银行账户Id（银行存款/银行对账单类型会用到）
	)
END
GO

--增加相应的本位币列
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='FDebitOri'
)
BEGIN
	ALTER TABLE Te_InitDataDetail ADD FDebitOri NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='FCreditOri'
)
BEGIN
	ALTER TABLE Te_InitDataDetail ADD FCreditOri NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='InitBalanceOri'
)
BEGIN
	ALTER TABLE Te_InitDataDetail ADD InitBalanceOri NUMERIC(18,2)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_InitDataDetail 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_InitDataDetail 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='InitBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_InitDataDetail 
	ALTER COLUMN InitBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='FDebitOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_InitDataDetail 
	ALTER COLUMN FDebitOri NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='FCreditOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_InitDataDetail 
	ALTER COLUMN FCreditOri NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataDetail' AND a.Name='InitBalanceOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_InitDataDetail 
	ALTER COLUMN InitBalanceOri NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳期初表头
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_InitDataIndex') AND  type = 'U')
BEGIN
	CREATE TABLE Te_InitDataIndex
	(
		Id		INT IDENTITY(1,1),	--自增Id
		STypeId	VARCHAR(50),		--分支机构
		BUId	INT,				--业务类型 Te_BusinessType
		Cid		INT,				--币种
		Finish	INT	DEFAULT(0),		--结束初始化 0.未结束 1.结束
		Rate	NUMERIC(22,4)		--汇率
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataIndex' AND a.Name='Finish'
)
BEGIN
	ALTER TABLE Te_InitDataIndex ADD Finish INT DEFAULT(0)
END
GO

--调整字段BId为BUId
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataIndex' AND a.Name='BId'
)
BEGIN
	ALTER TABLE Te_InitDataIndex DROP COLUMN BId
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataIndex' AND a.Name='BUId'
)
BEGIN
	ALTER TABLE Te_InitDataIndex ADD BUId INT
END
GO
--汇率
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataIndex' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE Te_InitDataIndex ADD Rate NUMERIC(22,4) DEFAULT(1)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_InitDataIndex' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_InitDataIndex 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳——日记账
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_Journal') AND  type = 'U')
BEGIN
	CREATE TABLE Te_Journal
	(
		Id					INT	IDENTITY(1,1),		--自增id
		Businessdate		DATETIME,				--业务日期
		YesterdayFBalance	NUMERIC(18,2),			--上日余额
		FDebitTotal			NUMERIC(18,2),			--本日借方累计
		FCreditTotal		NUMERIC(18,2),			--本日贷方累计
		FBalance			NUMERIC(18,2),			--本日余额
		AccountId			INT,					--银行账户id
		IsCash				INT,					--是否现金 0.非现金 1.现金
		STypeId				VARCHAR(50)	DEFAULT(''),--分支机构
		ATypeId				VARCHAR(50) DEFAULT(''),--会计科目
		FDC					INT,					--借贷方向 1.借 -1.贷
		Cid					INT						--币种
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='STypeId'
)
BEGIN
	ALTER TABLE Te_Journal ADD STypeId VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='ATypeId'
)
BEGIN
	ALTER TABLE Te_Journal ADD ATypeId VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='FDC'
)
BEGIN
	ALTER TABLE Te_Journal ADD FDC INT
END
GO

--币种
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='Cid'
)
BEGIN
	ALTER TABLE Te_Journal ADD Cid INT NULL DEFAULT(0)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='YesterdayFBalance'
)
BEGIN
	ALTER TABLE Te_Journal ALTER COLUMN YesterdayFBalance NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='FDebitTotal'
)
BEGIN
	ALTER TABLE Te_Journal ALTER COLUMN FDebitTotal NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='FCreditTotal'
)
BEGIN
	ALTER TABLE Te_Journal ALTER COLUMN FCreditTotal NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='FBalance'
)
BEGIN
	ALTER TABLE Te_Journal ALTER COLUMN FBalance NUMERIC(18,2)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='YesterdayFBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal 
	ALTER COLUMN YesterdayFBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='FDebitTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal 
	ALTER COLUMN FDebitTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='FCreditTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal 
	ALTER COLUMN FCreditTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal' AND a.Name='FBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal 
	ALTER COLUMN FBalance NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳——日记账明细
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_Journal_Detail') AND  type = 'U')
BEGIN
	CREATE TABLE Te_Journal_Detail
	(
		Id				INT IDENTITY(1,1),												--自增id
		BusinessDate	DATETIME,														--业务日期
		SourceId		INT,															--来源Id Te_Journal_SourceType
		VoucherId		INT,															--凭证Id
		GoodsBillNumberId	INT,														--单据id
		ETypeId			VARCHAR(50),													--出纳
		Summary			VARCHAR(1000) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--摘要
		FDebit			NUMERIC(18,2),													--借方
		FCredit			NUMERIC(18,2),													--贷方
		FEndBalance		NUMERIC(18,2),													--余额
		AccountId		INT,															--银行账户Id
		IsCash			INT,															--是否现金 0.不是 1.是
		FDC				INT,															--借贷方向 1.借 -1.贷
		STypeId			VARCHAR(50)	DEFAULT(''),										--分支机构
		ATypeId			VARCHAR(50) DEFAULT(''),										--会计科目
		FSettleId		INT,															--结算方式
		FSettleNo		VARCHAR(50),													--结算号
		Cid				INT,															--币种
		Rate			NUMERIC(22,4)													--汇率
	)
END
GO

--币种
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='Cid'
)
BEGIN
	ALTER TABLE Te_Journal_Detail 
		ADD Cid INT NULL DEFAULT(0)
END
GO

--汇率
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ADD Rate NUMERIC(22,4)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FDebit'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ALTER COLUMN FDebit NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FCredit'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ALTER COLUMN FCredit NUMERIC(18,2)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FEndBalance'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ALTER COLUMN FEndBalance NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='GoodsBillNumberId'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ADD GoodsBillNumberId INT
END
GO

--增加本位币金额字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FDebitOri'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ADD FDebitOri NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FCreditOri'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ADD FCreditOri NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FEndBalanceOri'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ADD FEndBalanceOri NUMERIC(18,2)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='IsInit'
)
BEGIN
	ALTER TABLE Te_Journal_Detail ADD IsInit INT DEFAULT 0
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_Journal_Detail') AND name = 'CIX_Te_Journal_Detail_ID')
DROP INDEX CIX_Te_Journal_Detail_ID ON Te_Journal_Detail 
CREATE CLUSTERED INDEX CIX_Te_Journal_Detail_ID ON Te_Journal_Detail(Id) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_Journal_Detail') AND name = 'CIX_Te_Journal_Detail_AccountId')
DROP INDEX CIX_Te_Journal_Detail_AccountId ON Te_Journal_Detail 
CREATE NONCLUSTERED INDEX CIX_Te_Journal_Detail_AccountId ON Te_Journal_Detail(AccountId) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_Journal_Detail') AND name = 'CIX_Te_Journal_Detail_VoucherId')
DROP INDEX CIX_Te_Journal_Detail_VoucherId ON Te_Journal_Detail 
CREATE NONCLUSTERED INDEX CIX_Te_Journal_Detail_VoucherId ON Te_Journal_Detail(VoucherId) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_Journal_Detail') AND name = 'CIX_Te_Journal_Detail_STypeId')
DROP INDEX CIX_Te_Journal_Detail_STypeId ON Te_Journal_Detail 
CREATE NONCLUSTERED INDEX CIX_Te_Journal_Detail_STypeId ON Te_Journal_Detail(STypeId) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Te_Journal_Detail') AND name = 'CIX_Te_Journal_Detail_ATypeId')
DROP INDEX CIX_Te_Journal_Detail_ATypeId ON Te_Journal_Detail 
CREATE NONCLUSTERED INDEX CIX_Te_Journal_Detail_ATypeId ON Te_Journal_Detail(ATypeId) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FDebit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal_Detail 
	ALTER COLUMN FDebit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FCredit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal_Detail 
	ALTER COLUMN FCredit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FEndBalance' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal_Detail 
	ALTER COLUMN FEndBalance NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal_Detail 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FDebitOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal_Detail 
	ALTER COLUMN FDebitOri NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FCreditOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal_Detail 
	ALTER COLUMN FCreditOri NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_Journal_Detail' AND a.Name='FEndBalanceOri' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Te_Journal_Detail 
	ALTER COLUMN FEndBalanceOri NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*  出纳——日记账来源类别
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_Journal_SourceType') AND  type = 'U')
BEGIN
	CREATE TABLE Te_Journal_SourceType
	(
		Id			INT,															--ID
		FullName	VARCHAR(100) COLLATE Chinese_PRC_CI_AS NOT NULL  DEFAULT ('')	--名称
	)
END
GO
--预置数据
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal_SourceType)
BEGIN
	INSERT INTO dbo.Te_Journal_SourceType( Id, FullName )
	VALUES	(1,'手工录入'),
			(2,'总账系统'),
			(3,'出纳系统'),
			(4,'业务系统')
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
* 出纳期间表
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_Period') AND  type = 'U')
BEGIN
	CREATE TABLE Te_Period
	(
		Id		INT	IDENTITY(1,1),		--自增id
		STypeId	VARCHAR(50) DEFAULT(''),--分支机构
		FYear	INT,					--当前年度
		FPeriod	INT						--当前期间
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
*出纳启用期间
*/
IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('Te_StartPeriod') AND  type = 'U')
BEGIN
	CREATE TABLE  Te_StartPeriod
	(
		Id			INT	IDENTITY(1,1),		--自增id
		STypeId		VARCHAR(50) DEFAULT(''),--分支机构
		SFYear		INT,					--启用年度
		SFPeriod	INT,					--启用期间
		IsConnect	INT,					--联用总账 0.未联用 1.联用
		CFYear		INT,					--联用年度
		CFPeriod	INT,					--联用期间
		IsUse		INT	DEFAULT(0)			--是否启用 0.未启用 1.启用
	)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Te_StartPeriod' AND a.Name='IsUse'
)
BEGIN
	ALTER TABLE Te_StartPeriod ADD IsUse INT DEFAULT(0)
END
GO

--预置“默认分支机构数据”
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = '00001')
	INSERT INTO dbo.Te_StartPeriod
			( STypeId ,
			  SFYear ,
			  SFPeriod ,
			  IsConnect ,
			  CFYear ,
			  CFPeriod ,
			  IsUse
			)
	VALUES  ( '00001' , -- STypeId - varchar(50)
			  0 , -- SFYear - int
			  0 , -- SFPeriod - int
			  0 , -- IsConnect - int
			  0 , -- CFYear - int
			  0 , -- CFPeriod - int
			  0  -- IsUse - int
			)
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[TemplateListTable]    脚本日期: 05/05/2010 14:49:38 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[TemplateListTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[TemplateListTable](
		[TemplateID] [int] NOT NULL,
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_TemplateTable_Qty]  DEFAULT (0),
		[comment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_TemplateTable_comment]  DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TemplateListTable' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TemplateListTable 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[TemplateTable]    脚本日期: 05/05/2010 14:49:39 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[TemplateTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[TemplateTable](
		[Templateid] [int] IDENTITY(1,1) NOT NULL,
		[TemplateName] [varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[comment] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_TemplateTable_comment_1]  DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tempPtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [dbo].[tempPtype] (
		[typeid] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[qty] [numeric](18, 4) NOT NULL ,
		[OperatorID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
end	
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='tempPtype' AND a.Name='qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE tempPtype 
	ALTER COLUMN qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('ThreeFinancialFormula') AND type = 'U')
BEGIN
	CREATE TABLE ThreeFinancialFormula (
		nId						INT	IDENTITY(1,1),--自增长列
		AccountSubId			INT,--会计科目模板ID
		ReportType				INT,--1:利润表 2：现金流量表 3：资产负债表
		ItemID					INT,--项目ID
		[Sign]					INT NOT NULL DEFAULT(1),--公式符号 1：正 -1负
		Formula					VARCHAR(1000),--公式/科目
		RowId					INT,--公式/科目 排序
		FormulaType				INT--公式类型比如利润表1：本期金额 2本年累计金额
	)
END
GO 
------------------------------------------表修改区域开始-------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='ThreeFinancialFormula' AND a.Name='FormulaType'
--)
--BEGIN
--	ALTER TABLE ThreeFinancialFormula 
--		ADD FormulaType INT
--END

--GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ThreeFinancialFormula') AND name = 'CIX_ThreeFinancialFormula_Nid')
	CREATE CLUSTERED INDEX CIX_ThreeFinancialFormula_Nid ON ThreeFinancialFormula(Nid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------预制数据-------------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialFormula WHERE ReportType=1)--1:利润表
BEGIN
	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)
	SELECT	28,	1,	1,	1	,'6001',	1,	1	UNION
	SELECT	28,	1,	1,	1	,'6051',	2,	1	UNION
	SELECT	28,	1,	2,	1	,'6401',	1,	1	UNION
	SELECT	28,	1,	2,	1	,'6402',	2,	1	UNION
	SELECT	28,	1,	3,	1	,'6403',	1,	1	UNION
	SELECT	28,	1,	4,	1	,'6601',	1,	1	UNION
	SELECT	28,	1,	5,	1	,'6602',	1,	1	UNION
	SELECT	28,	1,	6,	1	,'6603',	1,	1	UNION
	SELECT	28,	1,	7,	1	,'6701',	1,	1	UNION
	SELECT	28,	1,	8,	1	,'6101',	1,	1	UNION
	SELECT	28,	1,	9,	1	,'6111',	1,	1	UNION

	SELECT	28,	1,	11,	1	,'6301',	1,	1	UNION
	SELECT	28,	1,	12,	1	,'6711',	1,	1	UNION

	SELECT	28,	1,	15,	1	,'6801',	1,	1	UNION

	SELECT	28,	1,	1,	1	,'6001',	1,	2	UNION
	SELECT	28,	1,	1,	1	,'6051',	2,	2	UNION
	SELECT	28,	1,	2,	1	,'6401',	1,	2	UNION
	SELECT	28,	1,	2,	1	,'6402',	2,	2	UNION
	SELECT	28,	1,	3,	1	,'6403',	1,	2	UNION
	SELECT	28,	1,	4,	1	,'6601',	1,	2	UNION
	SELECT	28,	1,	5,	1	,'6602',	1,	2	UNION
	SELECT	28,	1,	6,	1	,'6603',	1,	2	UNION
	SELECT	28,	1,	7,	1	,'6701',	1,	2	UNION
	SELECT	28,	1,	8,	1	,'6101',	1,	2	UNION
	SELECT	28,	1,	9,	1	,'6111',	1,	2	UNION

	SELECT	28,	1,	11,	1	,'6301',	1,	2	UNION
	SELECT	28,	1,	12,	1	,'6711',	1,	2	UNION

	SELECT	28,	1,	15,	1	,'6801',	1,	2	--UNION

	
	--AccountSubId	--1	企业会计制度科目 
					--28新会计准则科目
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)
	SELECT	1,	1,	1,	1	,'5101',	1,	1	UNION
	SELECT	1,	1,	2,	1	,'5401',	1,	1	UNION
	SELECT	1,	1,	3,	1	,'5402',	1,	1	UNION

	SELECT	1,	1,	5,	1	,'5102',	1,	1	UNION
	SELECT	1,	1,	5,	-1	,'5405',	2,	1	UNION
	SELECT	1,	1,	6,	1	,'5501',	1,	1	UNION
	SELECT	1,	1,	7,	1	,'5502',	1,	1	UNION
	SELECT	1,	1,	8,	1	,'5503',	1,	1	UNION

	SELECT	1,	1,	10,	1	,'5201',	1,	1	UNION
	SELECT	1,	1,	11,	1	,'5203',	1,	1	UNION
	SELECT	1,	1,	12,	1	,'5301',	1,	1	UNION
	SELECT	1,	1,	13,	1	,'5601',	1,	1	UNION

	SELECT	1,	1,	15,	1	,'5701',	1,	1	UNION

	SELECT	1,	1,	1,	1	,'5101',	1,	2	UNION
	SELECT	1,	1,	2,	1	,'5401',	1,	2	UNION
	SELECT	1,	1,	3,	1	,'5402',	1,	2	UNION

	SELECT	1,	1,	5,	1	,'5102',	1,	2	UNION
	SELECT	1,	1,	5,	-1	,'5405',	2,	2	UNION
	SELECT	1,	1,	6,	1	,'5501',	1,	2	UNION
	SELECT	1,	1,	7,	1	,'5502',	1,	2	UNION
	SELECT	1,	1,	8,	1	,'5503',	1,	2	UNION

	SELECT	1,	1,	10,	1	,'5201',	1,	2	UNION
	SELECT	1,	1,	11,	1	,'5203',	1,	2	UNION
	SELECT	1,	1,	12,	1	,'5301',	1,	2	UNION
	SELECT	1,	1,	13,	1	,'5601',	1,	2	UNION

	SELECT	1,	1,	15,	1	,'5701',	1,	2	--UNION

	--AccountSubId	--2	小企业会计准则科目 
					--1	企业会计制度科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)		
	SELECT	2,	1,	1,	1	,'5001',	1,	1	UNION
	SELECT	2,	1,	1,	1	,'5051',	2,	1	UNION
	SELECT	2,	1,	2,	1	,'5401',	1,	1	UNION
	SELECT	2,	1,	2,	1	,'5402',	2,	1	UNION
	SELECT	2,	1,	3,	1	,'5403',	1,	1	UNION
	SELECT	2,	1,	11,	1	,'5601',	1,	1	UNION
	SELECT	2,	1,	14,	1	,'5602',	1,	1	UNION
	SELECT	2,	1,	18,	1	,'5603',	1,	1	UNION
	SELECT	2,	1,	20,	1	,'5111',	1,	1	UNION

	SELECT	2,	1,	22,	1	,'5301',	1,	1	UNION
	SELECT	2,	1,	24,	1	,'5711',	1,	1	UNION

	SELECT	2,	1,	31,	1	,'5801',	1,	1	UNION

	SELECT	2,	1,	1,	1	,'5001',	1,	2	UNION
	SELECT	2,	1,	1,	1	,'5051',	2,	2	UNION
	SELECT	2,	1,	2,	1	,'5401',	1,	2	UNION
	SELECT	2,	1,	2,	1	,'5402',	2,	2	UNION
	SELECT	2,	1,	3,	1	,'5403',	1,	2	UNION
	SELECT	2,	1,	11,	1	,'5601',	1,	2	UNION
	SELECT	2,	1,	14,	1	,'5602',	1,	2	UNION
	SELECT	2,	1,	18,	1	,'5603',	1,	2	UNION
	SELECT	2,	1,	20,	1	,'5111',	1,	2	UNION

	SELECT	2,	1,	22,	1	,'5301',	1,	2	UNION
	SELECT	2,	1,	24,	1	,'5711',	1,	2	UNION

	SELECT	2,	1,	31,	1	,'5801',	1,	2	--UNION

END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialFormula WHERE ReportType=2)--2：现金流量表
BEGIN

	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)	
	SELECT	28,	2,	2,	1	,'CI1.01.01',	1,	1	UNION				
	SELECT	28,	2,	3,	1	,'CI1.01.02',	1,	1	UNION				
	SELECT	28,	2,	4,	1	,'CI1.01.03',	1,	1	UNION				

	SELECT	28,	2,	6,	1	,'CI1.02.01',	1,	1	UNION				
	SELECT	28,	2,	7,	1	,'CI1.02.02',	1,	1	UNION				
	SELECT	28,	2,	8,	1	,'CI1.02.03',	1,	1	UNION				
	SELECT	28,	2,	9,	1	,'CI1.02.04',	1,	1	UNION				

	SELECT	28,	2,	13,	1	,'CI2.01.01',	1,	1	UNION				
	SELECT	28,	2,	14,	1	,'CI2.01.02',	1,	1	UNION				
	SELECT	28,	2,	15,	1	,'CI2.01.03',	1,	1	UNION				
	SELECT	28,	2,	16,	1	,'CI2.01.04',	1,	1	UNION				
	SELECT	28,	2,	17,	1	,'CI2.01.05',	1,	1	UNION				

	SELECT	28,	2,	19,	1	,'CI2.02.01',	1,	1	UNION				
	SELECT	28,	2,	20,	1	,'CI2.02.02',	1,	1	UNION				
	SELECT	28,	2,	21,	1	,'CI2.02.03',	1,	1	UNION				
	SELECT	28,	2,	22,	1	,'CI2.02.04',	1,	1	UNION				

	SELECT	28,	2,	26,	1	,'CI3.01.01',	1,	1	UNION				
	SELECT	28,	2,	27,	1	,'CI3.01.02',	1,	1	UNION				
	SELECT	28,	2,	28,	1	,'CI3.01.03',	1,	1	UNION				

	SELECT	28,	2,	30,	1	,'CI3.02.01',	1,	1	UNION				
	SELECT	28,	2,	31,	1	,'CI3.02.02',	1,	1	UNION				
	SELECT	28,	2,	32,	1	,'CI3.02.03',	1,	1	UNION				
	SELECT	28,	2,	37,	1	,'QC(1001)',	1,	1	UNION--期初				
	SELECT	28,	2,	37,	1	,'QC(1002)',	2,	1	UNION--期初					
	SELECT	28,	2,	37,	1	,'QC(1012)',	3,	1	UNION--期初			

	SELECT	28,	2,	2,	1	,'CI1.01.01',	1,	2	UNION				
	SELECT	28,	2,	3,	1	,'CI1.01.02',	1,	2	UNION				
	SELECT	28,	2,	4,	1	,'CI1.01.03',	1,	2	UNION				

	SELECT	28,	2,	6,	1	,'CI1.02.01',	1,	2	UNION				
	SELECT	28,	2,	7,	1	,'CI1.02.02',	1,	2	UNION				
	SELECT	28,	2,	8,	1	,'CI1.02.03',	1,	2	UNION				
	SELECT	28,	2,	9,	1	,'CI1.02.04',	1,	2	UNION				

	SELECT	28,	2,	13,	1	,'CI2.01.01',	1,	2	UNION				
	SELECT	28,	2,	14,	1	,'CI2.01.02',	1,	2	UNION				
	SELECT	28,	2,	15,	1	,'CI2.01.03',	1,	2	UNION				
	SELECT	28,	2,	16,	1	,'CI2.01.04',	1,	2	UNION				
	SELECT	28,	2,	17,	1	,'CI2.01.05',	1,	2	UNION				

	SELECT	28,	2,	19,	1	,'CI2.02.01',	1,	2	UNION				
	SELECT	28,	2,	20,	1	,'CI2.02.02',	1,	2	UNION				
	SELECT	28,	2,	21,	1	,'CI2.02.03',	1,	2	UNION				
	SELECT	28,	2,	22,	1	,'CI2.02.04',	1,	2	UNION				

	SELECT	28,	2,	26,	1	,'CI3.01.01',	1,	2	UNION				
	SELECT	28,	2,	27,	1	,'CI3.01.02',	1,	2	UNION				
	SELECT	28,	2,	28,	1	,'CI3.01.03',	1,	2	UNION				

	SELECT	28,	2,	30,	1	,'CI3.02.01',	1,	2	UNION				
	SELECT	28,	2,	31,	1	,'CI3.02.02',	1,	2	UNION				
	SELECT	28,	2,	32,	1	,'CI3.02.03',	1,	2	UNION				

	SELECT	28,	2,	37,	1	,'NC(1001)',	1,	2	UNION--年初					
	SELECT	28,	2,	37,	1	,'NC(1002)',	2,	2	UNION--年初					
	SELECT	28,	2,	37,	1	,'NC(1012)',	3,	2	--年初					


	--AccountSubId	--1	企业会计制度科目 
					--28新会计准则科目
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)	
	SELECT	1,	2,	2,	1	,'CI1.01.01',	1,	1	UNION
	SELECT	1,	2,	3,	1	,'CI1.01.02',	1,	1	UNION
	SELECT	1,	2,	4,	1	,'CI1.01.03',	1,	1	UNION

	SELECT	1,	2,	6,	1	,'CI1.02.01',	1,	1	UNION
	SELECT	1,	2,	7,	1	,'CI1.02.02',	1,	1	UNION
	SELECT	1,	2,	8,	1	,'CI1.02.03',	1,	1	UNION
	SELECT	1,	2,	9,	1	,'CI1.02.04',	1,	1	UNION

	SELECT	1,	2,	13,	1	,'CI2.01.01',	1,	1	UNION
	SELECT	1,	2,	14,	1	,'CI2.01.02',	1,	1	UNION
	SELECT	1,	2,	15,	1	,'CI2.01.03',	1,	1	UNION
	SELECT	1,	2,	16,	1	,'CI2.01.04',	1,	1	UNION
	SELECT	1,	2,	17,	1	,'CI2.01.05',	1,	1	UNION

	SELECT	1,	2,	19,	1	,'CI2.02.01',	1,	1	UNION
	SELECT	1,	2,	20,	1	,'CI2.02.02',	1,	1	UNION
	SELECT	1,	2,	21,	1	,'CI2.02.03',	1,	1	UNION
	SELECT	1,	2,	22,	1	,'CI2.02.04',	1,	1	UNION

	SELECT	1,	2,	26,	1	,'CI3.01.01',	1,	1	UNION
	SELECT	1,	2,	27,	1	,'CI3.01.02',	1,	1	UNION
	SELECT	1,	2,	28,	1	,'CI3.01.03',	1,	1	UNION

	SELECT	1,	2,	30,	1	,'CI3.02.01',	1,	1	UNION
	SELECT	1,	2,	31,	1	,'CI3.02.02',	1,	1	UNION
	SELECT	1,	2,	32,	1	,'CI3.02.03',	1,	1	UNION

	SELECT	1,	2,	37,	1	,'QC(1001)',	1,	1	UNION--期初
	SELECT	1,	2,	37,	1	,'QC(1002)',	2,	1	UNION--期初
	SELECT	1,	2,	37,	1	,'QC(1009)',	3,	1	UNION--期初

	SELECT	1,	2,	2,	1	,'CI1.01.01',	1,	2	UNION
	SELECT	1,	2,	3,	1	,'CI1.01.02',	1,	2	UNION
	SELECT	1,	2,	4,	1	,'CI1.01.03',	1,	2	UNION

	SELECT	1,	2,	6,	1	,'CI1.02.01',	1,	2	UNION
	SELECT	1,	2,	7,	1	,'CI1.02.02',	1,	2	UNION
	SELECT	1,	2,	8,	1	,'CI1.02.03',	1,	2	UNION
	SELECT	1,	2,	9,	1	,'CI1.02.04',	1,	2	UNION

	SELECT	1,	2,	13,	1	,'CI2.01.01',	1,	2	UNION
	SELECT	1,	2,	14,	1	,'CI2.01.02',	1,	2	UNION
	SELECT	1,	2,	15,	1	,'CI2.01.03',	1,	2	UNION
	SELECT	1,	2,	16,	1	,'CI2.01.04',	1,	2	UNION
	SELECT	1,	2,	17,	1	,'CI2.01.05',	1,	2	UNION

	SELECT	1,	2,	19,	1	,'CI2.02.01',	1,	2	UNION
	SELECT	1,	2,	20,	1	,'CI2.02.02',	1,	2	UNION
	SELECT	1,	2,	21,	1	,'CI2.02.03',	1,	2	UNION
	SELECT	1,	2,	22,	1	,'CI2.02.04',	1,	2	UNION

	SELECT	1,	2,	26,	1	,'CI3.01.01',	1,	2	UNION
	SELECT	1,	2,	27,	1	,'CI3.01.02',	1,	2	UNION
	SELECT	1,	2,	28,	1	,'CI3.01.03',	1,	2	UNION

	SELECT	1,	2,	30,	1	,'CI3.02.01',	1,	2	UNION
	SELECT	1,	2,	31,	1	,'CI3.02.02',	1,	2	UNION
	SELECT	1,	2,	32,	1	,'CI3.02.03',	1,	2	UNION

	SELECT	1,	2,	37,	1	,'NC(1001)',	1,	2	UNION--年初
	SELECT	1,	2,	37,	1	,'NC(1002)',	2,	2	UNION--年初
	SELECT	1,	2,	37,	1	,'NC(1009)',	3,	2	--年初



	--AccountSubId	--2	小企业会计准则科目
					--1	企业会计制度科目 
					-- 28新会计准则科目
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)	
	SELECT	2,	2,	2,	1	,'CI1.01.01',	1,	1	UNION				
	SELECT	2,	2,	3,	1	,'CI1.01.02',	1,	1	UNION				
	SELECT	2,	2,	4,	1	,'CI1.01.03',	1,	1	UNION				

	SELECT	2,	2,	6,	1	,'CI1.02.01',	1,	1	UNION				
	SELECT	2,	2,	7,	1	,'CI1.02.02',	1,	1	UNION				
	SELECT	2,	2,	8,	1	,'CI1.02.03',	1,	1	UNION				
	SELECT	2,	2,	9,	1	,'CI1.02.04',	1,	1	UNION				

	SELECT	2,	2,	13,	1	,'CI2.01.01',	1,	1	UNION				
	SELECT	2,	2,	14,	1	,'CI2.01.02',	1,	1	UNION				
	SELECT	2,	2,	15,	1	,'CI2.01.03',	1,	1	UNION				
	SELECT	2,	2,	16,	1	,'CI2.01.04',	1,	1	UNION				
	SELECT	2,	2,	17,	1	,'CI2.01.05',	1,	1	UNION				

	SELECT	2,	2,	19,	1	,'CI2.02.01',	1,	1	UNION				
	SELECT	2,	2,	20,	1	,'CI2.02.02',	1,	1	UNION				
	SELECT	2,	2,	21,	1	,'CI2.02.03',	1,	1	UNION				
	SELECT	2,	2,	22,	1	,'CI2.02.04',	1,	1	UNION				

	SELECT	2,	2,	26,	1	,'CI3.01.01',	1,	1	UNION				
	SELECT	2,	2,	27,	1	,'CI3.01.02',	1,	1	UNION				
	SELECT	2,	2,	28,	1	,'CI3.01.03',	1,	1	UNION				

	SELECT	2,	2,	30,	1	,'CI3.02.01',	1,	1	UNION				
	SELECT	2,	2,	31,	1	,'CI3.02.02',	1,	1	UNION				
	SELECT	2,	2,	32,	1	,'CI3.02.03',	1,	1	UNION				

	SELECT	2,	2,	37,	1	,'QC(1001)',	1,	1	UNION--期初				
	SELECT	2,	2,	37,	1	,'QC(1002)',	2,	1	UNION--期初				
	SELECT	2,	2,	37,	1	,'QC(1012)',	3,	1	UNION--期初			

	SELECT	2,	2,	2,	1	,'CI1.01.01',	1,	2	UNION				
	SELECT	2,	2,	3,	1	,'CI1.01.02',	1,	2	UNION				
	SELECT	2,	2,	4,	1	,'CI1.01.03',	1,	2	UNION				

	SELECT	2,	2,	6,	1	,'CI1.02.01',	1,	2	UNION				
	SELECT	2,	2,	7,	1	,'CI1.02.02',	1,	2	UNION				
	SELECT	2,	2,	8,	1	,'CI1.02.03',	1,	2	UNION				
	SELECT	2,	2,	9,	1	,'CI1.02.04',	1,	2	UNION				

	SELECT	2,	2,	13,	1	,'CI2.01.01',	1,	2	UNION				
	SELECT	2,	2,	14,	1	,'CI2.01.02',	1,	2	UNION				
	SELECT	2,	2,	15,	1	,'CI2.01.03',	1,	2	UNION				
	SELECT	2,	2,	16,	1	,'CI2.01.04',	1,	2	UNION				
	SELECT	2,	2,	17,	1	,'CI2.01.05',	1,	2	UNION				

	SELECT	2,	2,	19,	1	,'CI2.02.01',	1,	2	UNION				
	SELECT	2,	2,	20,	1	,'CI2.02.02',	1,	2	UNION				
	SELECT	2,	2,	21,	1	,'CI2.02.03',	1,	2	UNION				
	SELECT	2,	2,	22,	1	,'CI2.02.04',	1,	2	UNION				

	SELECT	2,	2,	26,	1	,'CI3.01.01',	1,	2	UNION				
	SELECT	2,	2,	27,	1	,'CI3.01.02',	1,	2	UNION				
	SELECT	2,	2,	28,	1	,'CI3.01.03',	1,	2	UNION				

	SELECT	2,	2,	30,	1	,'CI3.02.01',	1,	2	UNION				
	SELECT	2,	2,	31,	1	,'CI3.02.02',	1,	2	UNION				
	SELECT	2,	2,	32,	1	,'CI3.02.03',	1,	2	UNION				

	SELECT	2,	2,	37,	1	,'NC(1001)',	1,	2	UNION--年初					
	SELECT	2,	2,	37,	1	,'NC(1002)',	2,	2	UNION--年初					
	SELECT	2,	2,	37,	1	,'NC(1012)',	3,	2	--年初				


END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialFormula WHERE ReportType=3)--3：资产负债表
BEGIN
	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)
	SELECT	28,	3,	3,	1	,'1001',	1,	1	UNION
	SELECT	28,	3,	3,	1	,'1002',	2,	1	UNION
	SELECT	28,	3,	3,	1	,'1012',	3,	1	UNION
	SELECT	28,	3,	4,	1	,'1101',	1,	1	UNION
	SELECT	28,	3,	4,	1	,'3101',	2,	1	UNION
	SELECT	28,	3,	4,	1	,'3201',	3,	1	UNION
	SELECT	28,	3,	4,	1	,'3202',	4,	1	UNION
	SELECT	28,	3,	5,	1	,'1121',	1,	1	UNION
	SELECT	28,	3,	6,	1	,'1122',	1,	1	UNION
	SELECT	28,	3,	6,	-1	,'1231',	2,	1	UNION
	SELECT	28,	3,	7,	1	,'1123',	1,	1	UNION
	SELECT	28,	3,	8,	1	,'1132',	1,	1	UNION
	SELECT	28,	3,	9,	1	,'1131',	1,	1	UNION
	SELECT	28,	3,	10,	1	,'1221',	1,	1	UNION
	SELECT	28,	3,	11,	1	,'1401',	1,	1	UNION
	SELECT	28,	3,	11,	1	,'1402',	2,	1	UNION
	SELECT	28,	3,	11,	1	,'1403',	3,	1	UNION
	SELECT	28,	3,	11,	1	,'1404',	4,	1	UNION
	SELECT	28,	3,	11,	1	,'1405',	5,	1	UNION
	SELECT	28,	3,	11,	1	,'1406',	6,	1	UNION
	SELECT	28,	3,	11,	1	,'1407',	7,	1	UNION
	SELECT	28,	3,	11,	1	,'1408',	8,	1	UNION
	SELECT	28,	3,	11,	-1	,'1471',	9,	1	UNION
	SELECT	28,	3,	14,	1	,'1901',	1,	1	UNION

	SELECT	28,	3,	18,	1	,'1503',	1,	1	UNION
	SELECT	28,	3,	19,	1	,'1501',	1,	1	UNION
	SELECT	28,	3,	19,	-1	,'1502',	2,	1	UNION
	SELECT	28,	3,	20,	1	,'1531',	1,	1	UNION
	SELECT	28,	3,	21,	1	,'1511',	1,	1	UNION
	SELECT	28,	3,	21,	-1	,'1512',	2,	1	UNION
	SELECT	28,	3,	22,	1	,'1521',	1,	1	UNION
	SELECT	28,	3,	23,	1	,'1601',	1,	1	UNION
	SELECT	28,	3,	23,	-1	,'1602',	2,	1	UNION
	SELECT	28,	3,	23,	-1	,'1603',	3,	1	UNION
	SELECT	28,	3,	24,	1	,'1604',	1,	1	UNION
	SELECT	28,	3,	25,	1	,'1605',	1,	1	UNION
	SELECT	28,	3,	26,	1	,'1606',	1,	1	UNION
	SELECT	28,	3,	29,	1	,'1701',	1,	1	UNION
	SELECT	28,	3,	29,	-1	,'1702',	2,	1	UNION
	SELECT	28,	3,	29,	-1	,'1703',	3,	1	UNION
	SELECT	28,	3,	31,	1	,'1711',	1,	1	UNION
	SELECT	28,	3,	32,	1	,'1801',	1,	1	UNION
	SELECT	28,	3,	33,	1	,'1811',	1,	1	UNION

	SELECT	28,	3,	39,	1	,'2001',	1,	1	UNION
	SELECT	28,	3,	40,	1	,'2101',	1,	1	UNION
	SELECT	28,	3,	41,	1	,'2201',	1,	1	UNION
	SELECT	28,	3,	42,	1	,'2202',	1,	1	UNION
	SELECT	28,	3,	43,	1	,'2203',	1,	1	UNION
	SELECT	28,	3,	44,	1	,'2211',	1,	1	UNION
	SELECT	28,	3,	45,	1	,'2221',	1,	1	UNION
	SELECT	28,	3,	46,	1	,'2231',	1,	1	UNION
	SELECT	28,	3,	47,	1	,'2232',	1,	1	UNION
	SELECT	28,	3,	48,	1	,'2241',	1,	1	UNION
	SELECT	28,	3,	50,	1	,'2801',	1,	1	UNION

	SELECT	28,	3,	55,	1	,'2501',	1,	1	UNION
	SELECT	28,	3,	56,	1	,'2502',	1,	1	UNION
	SELECT	28,	3,	57,	1	,'2701',	1,	1	UNION
	SELECT	28,	3,	58,	1	,'2711',	1,	1	UNION
	SELECT	28,	3,	59,	1	,'2901',	1,	1	UNION

	SELECT	28,	3,	64,	1	,'4001',	1,	1	UNION
	SELECT	28,	3,	65,	1	,'4002',	1,	1	UNION
	SELECT	28,	3,	66,	1	,'4201',	1,	1	UNION
	SELECT	28,	3,	67,	1	,'4101',	1,	1	UNION
	SELECT	28,	3,	68,	1	,'4103',	1,	1	UNION
	SELECT	28,	3,	68,	1	,'4104',	2,	1	UNION

	SELECT	28,	3,	3,	1	,'1001',	1,	2	UNION
	SELECT	28,	3,	3,	1	,'1002',	2,	2	UNION
	SELECT	28,	3,	3,	1	,'1012',	3,	2	UNION
	SELECT	28,	3,	4,	1	,'1101',	1,	2	UNION
	SELECT	28,	3,	4,	1	,'3101',	2,	2	UNION
	SELECT	28,	3,	4,	1	,'3201',	3,	2	UNION
	SELECT	28,	3,	4,	1	,'3202',	4,	2	UNION
	SELECT	28,	3,	5,	1	,'1121',	1,	2	UNION
	SELECT	28,	3,	6,	1	,'1122',	1,	2	UNION
	SELECT	28,	3,	6,	-1	,'1231',	2,	2	UNION
	SELECT	28,	3,	7,	1	,'1123',	1,	2	UNION
	SELECT	28,	3,	8,	1	,'1132',	1,	2	UNION
	SELECT	28,	3,	9,	1	,'1131',	1,	2	UNION
	SELECT	28,	3,	10,	1	,'1221',	1,	2	UNION
	SELECT	28,	3,	11,	1	,'1401',	1,	2	UNION
	SELECT	28,	3,	11,	1	,'1402',	2,	2	UNION
	SELECT	28,	3,	11,	1	,'1403',	3,	2	UNION
	SELECT	28,	3,	11,	1	,'1404',	4,	2	UNION
	SELECT	28,	3,	11,	1	,'1405',	5,	2	UNION
	SELECT	28,	3,	11,	1	,'1406',	6,	2	UNION
	SELECT	28,	3,	11,	1	,'1407',	7,	2	UNION
	SELECT	28,	3,	11,	1	,'1408',	8,	2	UNION
	SELECT	28,	3,	11,	-1	,'1471',	9,	2	UNION
	SELECT	28,	3,	14,	1	,'1901',	1,	2	UNION

	SELECT	28,	3,	18,	1	,'1503',	1,	2	UNION
	SELECT	28,	3,	19,	1	,'1501',	1,	2	UNION
	SELECT	28,	3,	19,	-1	,'1502',	2,	2	UNION
	SELECT	28,	3,	20,	1	,'1531',	1,	2	UNION
	SELECT	28,	3,	21,	1	,'1511',	1,	2	UNION
	SELECT	28,	3,	21,	-1	,'1512',	2,	2	UNION
	SELECT	28,	3,	22,	1	,'1521',	1,	2	UNION
	SELECT	28,	3,	23,	1	,'1601',	1,	2	UNION
	SELECT	28,	3,	23,	-1	,'1602',	2,	2	UNION
	SELECT	28,	3,	23,	-1	,'1603',	3,	2	UNION
	SELECT	28,	3,	24,	1	,'1604',	1,	2	UNION
	SELECT	28,	3,	25,	1	,'1605',	1,	2	UNION
	SELECT	28,	3,	26,	1	,'1606',	1,	2	UNION
	SELECT	28,	3,	29,	1	,'1701',	1,	2	UNION
	SELECT	28,	3,	29,	-1	,'1702',	2,	2	UNION
	SELECT	28,	3,	29,	-1	,'1703',	3,	2	UNION
	SELECT	28,	3,	31,	1	,'1711',	1,	2	UNION
	SELECT	28,	3,	32,	1	,'1801',	1,	2	UNION
	SELECT	28,	3,	33,	1	,'1811',	1,	2	UNION

	SELECT	28,	3,	39,	1	,'2001',	1,	2	UNION
	SELECT	28,	3,	40,	1	,'2101',	1,	2	UNION
	SELECT	28,	3,	41,	1	,'2201',	1,	2	UNION
	SELECT	28,	3,	42,	1	,'2202',	1,	2	UNION
	SELECT	28,	3,	43,	1	,'2203',	1,	2	UNION
	SELECT	28,	3,	44,	1	,'2211',	1,	2	UNION
	SELECT	28,	3,	45,	1	,'2221',	1,	2	UNION
	SELECT	28,	3,	46,	1	,'2231',	1,	2	UNION
	SELECT	28,	3,	47,	1	,'2232',	1,	2	UNION
	SELECT	28,	3,	48,	1	,'2241',	1,	2	UNION
	SELECT	28,	3,	50,	1	,'2801',	1,	2	UNION

	SELECT	28,	3,	55,	1	,'2501',	1,	2	UNION
	SELECT	28,	3,	56,	1	,'2502',	1,	2	UNION
	SELECT	28,	3,	57,	1	,'2701',	1,	2	UNION
	SELECT	28,	3,	58,	1	,'2711',	1,	2	UNION
	SELECT	28,	3,	59,	1	,'2901',	1,	2	UNION

	SELECT	28,	3,	64,	1	,'4001',	1,	2	UNION
	SELECT	28,	3,	65,	1	,'4002',	1,	2	UNION
	SELECT	28,	3,	66,	1	,'4201',	1,	2	UNION
	SELECT	28,	3,	67,	1	,'4101',	1,	2	UNION
	SELECT	28,	3,	68,	1	,'4103',	1,	2	UNION
	SELECT	28,	3,	68,	1	,'4104',	2,	2	--UNION


	--AccountSubId	--1	企业会计制度科目 
					--2	小企业会计准则科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)	
	SELECT 	1,	3,	3,	1	,'1001',	1,	1	UNION
	SELECT 	1,	3,	3,	1	,'1002',	2,	1	UNION
	SELECT 	1,	3,	3,	1	,'1009',	3,	1	UNION
	SELECT 	1,	3,	4,	1	,'1101',	1,	1	UNION
	SELECT 	1,	3,	4,	-1	,'1102',	2,	1	UNION
	SELECT 	1,	3,	5,	1	,'1111',	1,	1	UNION
	SELECT 	1,	3,	6,	1	,'1121',	2,	1	UNION
	SELECT 	1,	3,	7,	1	,'1122',	3,	1	UNION
	SELECT 	1,	3,	8,	1	,'1131',	1,	1	UNION
	SELECT 	1,	3,	8,	-1	,'1141',	2,	1	UNION
	SELECT 	1,	3,	9,	1	,'1133',	1,	1	UNION
	SELECT 	1,	3,	10,	1	,'1151',	1,	1	UNION
	SELECT 	1,	3,	11,	1	,'1161',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1201',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1211',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1221',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1231',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1232',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1241',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1243',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1244',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1251',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1261',	1,	1	UNION
	SELECT 	1,	3,	12,	1	,'1281',	1,	1	UNION
	SELECT 	1,	3,	13,	1	,'1301',	2,	1	UNION

	SELECT 	1,	3,	18,	1	,'1401',	1,	1	UNION
	SELECT 	1,	3,	19,	1	,'1402',	1,	1	UNION

	SELECT 	1,	3,	22,	1	,'1501',	1,	1	UNION
	SELECT 	1,	3,	23,	1	,'1502',	1,	1	UNION

	SELECT 	1,	3,	25,	1	,'1505',	1,	1	UNION

	SELECT 	1,	3,	27,	1	,'1601',	1,	1	UNION
	SELECT 	1,	3,	28,	1	,'1603',	1,	1	UNION
	SELECT 	1,	3,	28,	-1	,'1605',	2,	1	UNION
	SELECT 	1,	3,	29,	1	,'1701',	1,	1	UNION

	SELECT 	1,	3,	32,	1	,'1801',	1,	1	UNION
	SELECT 	1,	3,	32,	-1	,'1805',	2,	1	UNION
	SELECT 	1,	3,	33,	1	,'1901',	1,	1	UNION

	SELECT 	1,	3,	41,	1	,'2101',	1,	1	UNION
	SELECT 	1,	3,	42,	1	,'2111',	1,	1	UNION
	SELECT 	1,	3,	43,	1	,'2121',	1,	1	UNION
	SELECT 	1,	3,	44,	1	,'2131',	1,	1	UNION
	SELECT 	1,	3,	45,	1	,'2151',	1,	1	UNION
	SELECT 	1,	3,	46,	1	,'2153',	1,	1	UNION
	SELECT 	1,	3,	47,	1	,'2161',	1,	1	UNION
	SELECT 	1,	3,	48,	1	,'2171',	1,	1	UNION
	SELECT 	1,	3,	49,	1	,'2176',	1,	1	UNION
	SELECT 	1,	3,	50,	1	,'2181',	1,	1	UNION
	SELECT 	1,	3,	51,	1	,'2191',	1,	1	UNION
	SELECT 	1,	3,	52,	1	,'2211',	1,	1	UNION

	SELECT 	1,	3,	57,	1	,'2301',	1,	1	UNION
	SELECT 	1,	3,	58,	1	,'2311',	1,	1	UNION
	SELECT 	1,	3,	59,	1	,'2321',	1,	1	UNION
	SELECT 	1,	3,	60,	1	,'2331',	1,	1	UNION

	SELECT 	1,	3,	64,	1	,'2341',	1,	1	UNION

	SELECT 	1,	3,	67,	1	,'3101',	1,	1	UNION
	SELECT 	1,	3,	68,	1	,'3103',	1,	1	UNION

	SELECT 	1,	3,	70,	1	,'3111',	1,	1	UNION
	SELECT 	1,	3,	71,	1	,'3121',	1,	1	UNION
	SELECT 	1,	3,	72,	1	,'312101',	1,	1	UNION
	SELECT 	1,	3,	73,	1	,'3141',	1,	1	UNION
	SELECT 	1,	3,	73,	1	,'3131',	2,	1	UNION

	SELECT 	1,	3,	3,	1	,'1001',	1,	2	UNION
	SELECT 	1,	3,	3,	1	,'1002',	2,	2	UNION
	SELECT 	1,	3,	3,	1	,'1009',	3,	2	UNION
	SELECT 	1,	3,	4,	1	,'1101',	1,	2	UNION
	SELECT 	1,	3,	4,	-1	,'1102',	2,	2	UNION
	SELECT 	1,	3,	5,	1	,'1111',	1,	2	UNION
	SELECT 	1,	3,	6,	1	,'1121',	2,	2	UNION
	SELECT 	1,	3,	7,	1	,'1122',	3,	2	UNION
	SELECT 	1,	3,	8,	1	,'1131',	1,	2	UNION
	SELECT 	1,	3,	8,	-1	,'1141',	2,	2	UNION
	SELECT 	1,	3,	9,	1	,'1133',	1,	2	UNION
	SELECT 	1,	3,	10,	1	,'1151',	1,	2	UNION
	SELECT 	1,	3,	11,	1	,'1161',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1201',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1211',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1221',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1231',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1232',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1241',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1243',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1244',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1251',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1261',	1,	2	UNION
	SELECT 	1,	3,	12,	1	,'1281',	1,	2	UNION
	SELECT 	1,	3,	13,	1	,'1301',	2,	2	UNION

	SELECT 	1,	3,	18,	1	,'1401',	1,	2	UNION
	SELECT 	1,	3,	19,	1	,'1402',	1,	2	UNION

	SELECT 	1,	3,	22,	1	,'1501',	1,	2	UNION
	SELECT 	1,	3,	23,	1	,'1502',	1,	2	UNION

	SELECT 	1,	3,	25,	1	,'1505',	1,	2	UNION

	SELECT 	1,	3,	27,	1	,'1601',	1,	2	UNION
	SELECT 	1,	3,	28,	1	,'1603',	1,	2	UNION
	SELECT 	1,	3,	28,	-1	,'1605',	2,	2	UNION
	SELECT 	1,	3,	29,	1	,'1701',	1,	2	UNION

	SELECT 	1,	3,	32,	1	,'1801',	1,	2	UNION
	SELECT 	1,	3,	32,	-1	,'1805',	2,	2	UNION
	SELECT 	1,	3,	33,	1	,'1901',	1,	2	UNION

	SELECT 	1,	3,	41,	1	,'2101',	1,	2	UNION
	SELECT 	1,	3,	42,	1	,'2111',	1,	2	UNION
	SELECT 	1,	3,	43,	1	,'2121',	1,	2	UNION
	SELECT 	1,	3,	44,	1	,'2131',	1,	2	UNION
	SELECT 	1,	3,	45,	1	,'2151',	1,	2	UNION
	SELECT 	1,	3,	46,	1	,'2153',	1,	2	UNION
	SELECT 	1,	3,	47,	1	,'2161',	1,	2	UNION
	SELECT 	1,	3,	48,	1	,'2171',	1,	2	UNION
	SELECT 	1,	3,	49,	1	,'2176',	1,	2	UNION
	SELECT 	1,	3,	50,	1	,'2181',	1,	2	UNION
	SELECT 	1,	3,	51,	1	,'2191',	1,	2	UNION
	SELECT 	1,	3,	52,	1	,'2211',	1,	2	UNION

	SELECT 	1,	3,	57,	1	,'2301',	1,	2	UNION
	SELECT 	1,	3,	58,	1	,'2311',	1,	2	UNION
	SELECT 	1,	3,	59,	1	,'2321',	1,	2	UNION
	SELECT 	1,	3,	60,	1	,'2331',	1,	2	UNION

	SELECT 	1,	3,	64,	1	,'2341',	1,	2	UNION

	SELECT 	1,	3,	67,	1	,'3101',	1,	2	UNION
	SELECT 	1,	3,	68,	1	,'3103',	1,	2	UNION

	SELECT 	1,	3,	70,	1	,'3111',	1,	2	UNION
	SELECT 	1,	3,	71,	1	,'3121',	1,	2	UNION
	SELECT 	1,	3,	72,	1	,'312101',	1,	2	UNION
	SELECT 	1,	3,	73,	1	,'3141',	1,	2	UNION
	SELECT 	1,	3,	73,	1	,'3131',	2,	2	


	--AccountSubId	--2	小企业会计准则科目
					--1	企业会计制度科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialFormula(AccountSubId,ReportType,ItemID,[Sign],Formula,RowId,FormulaType)
	SELECT 	2,	3,	3,	1	,'1001',	1,	1	UNION 
	SELECT 	2,	3,	3,	1	,'1002',	2,	1	UNION 
	SELECT 	2,	3,	3,	1	,'1012',	3,	1	UNION 
	SELECT 	2,	3,	4,	1	,'1101',	1,	1	UNION 
	SELECT 	2,	3,	5,	1	,'1121',	1,	1	UNION 
	SELECT 	2,	3,	6,	1	,'1122',	1,	1	UNION 
	SELECT 	2,	3,	7,	1	,'1123',	1,	1	UNION 
	SELECT 	2,	3,	8,	1	,'1131',	1,	1	UNION 
	SELECT 	2,	3,	9,	1	,'1132',	1,	1	UNION 
	SELECT 	2,	3,	10,	1	,'1221',	1,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1401',	1,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1402',	2,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1403',	3,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1404',	4,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1405',	5,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1407',	6,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1408',	7,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1411',	8,	1	UNION 
	SELECT 	2,	3,	11,	1	,'1421',	9,	1	UNION 
	SELECT 	2,	3,	14,	1	,'1405',	1,	1	UNION 

	SELECT 	2,	3,	19,	1	,'1501',	1,	1	UNION 
	SELECT 	2,	3,	20,	1	,'1511',	1,	1	UNION 
	SELECT 	2,	3,	21,	1	,'1601',	1,	1	UNION 
	SELECT 	2,	3,	22,	1	,'1602',	1,	1	UNION 
	SELECT 	2,	3,	23,	1	,'1601',	1,	1	UNION 
	SELECT 	2,	3,	23,	-1	,'1602',	2,	1	UNION 
	SELECT 	2,	3,	24,	1	,'1604',	1,	1	UNION 
	SELECT 	2,	3,	25,	1	,'1605',	1,	1	UNION 
	SELECT 	2,	3,	26,	1	,'1606',	1,	1	UNION 
	SELECT 	2,	3,	27,	1	,'1621',	1,	1	UNION 
	SELECT 	2,	3,	27,	-1	,'1622',	2,	1	UNION 
	SELECT 	2,	3,	28,	1	,'1701',	1,	1	UNION 
	SELECT 	2,	3,	30,	1	,'1801',	1,	1	UNION 

	SELECT 	2,	3,	36,	1	,'2001',	1,	1	UNION 
	SELECT 	2,	3,	37,	1	,'2201',	1,	1	UNION 
	SELECT 	2,	3,	38,	1	,'2202',	1,	1	UNION 
	SELECT 	2,	3,	39,	1	,'2203',	1,	1	UNION 
	SELECT 	2,	3,	40,	1	,'2211',	1,	1	UNION 
	SELECT 	2,	3,	41,	1	,'2221',	1,	1	UNION 
	SELECT 	2,	3,	42,	1	,'2231',	1,	1	UNION 
	SELECT 	2,	3,	43,	1	,'2232',	1,	1	UNION 
	SELECT 	2,	3,	44,	1	,'2241',	1,	1	UNION 

	SELECT 	2,	3,	48,	1	,'2501',	1,	1	UNION 
	SELECT 	2,	3,	49,	1	,'2701',	1,	1	UNION 
	SELECT 	2,	3,	50,	1	,'2401',	1,	1	UNION 

	SELECT 	2,	3,	55,	1	,'3001',	1,	1	UNION 
	SELECT 	2,	3,	56,	1	,'3002',	1,	1	UNION 
	SELECT 	2,	3,	57,	1	,'3101',	1,	1	UNION 
	SELECT 	2,	3,	58,	1	,'3104',	1,	1	UNION 
	SELECT 	2,	3,	58,	1	,'3103',	2,	1	UNION 

	SELECT 	2,	3,	3,	1	,'1001',	1,	2	UNION 
	SELECT 	2,	3,	3,	1	,'1002',	2,	2	UNION 
	SELECT 	2,	3,	3,	1	,'1012',	3,	2	UNION 
	SELECT 	2,	3,	4,	1	,'1101',	1,	2	UNION 
	SELECT 	2,	3,	5,	1	,'1121',	1,	2	UNION 
	SELECT 	2,	3,	6,	1	,'1122',	1,	2	UNION 
	SELECT 	2,	3,	7,	1	,'1123',	1,	2	UNION 
	SELECT 	2,	3,	8,	1	,'1131',	1,	2	UNION 
	SELECT 	2,	3,	9,	1	,'1132',	1,	2	UNION 
	SELECT 	2,	3,	10,	1	,'1221',	1,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1401',	1,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1402',	2,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1403',	3,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1404',	4,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1405',	5,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1407',	6,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1408',	7,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1411',	8,	2	UNION 
	SELECT 	2,	3,	11,	1	,'1421',	9,	2	UNION 
	SELECT 	2,	3,	14,	1	,'1405',	1,	2	UNION 

	SELECT 	2,	3,	19,	1	,'1501',	1,	2	UNION 
	SELECT 	2,	3,	20,	1	,'1511',	1,	2	UNION 
	SELECT 	2,	3,	21,	1	,'1601',	1,	2	UNION 
	SELECT 	2,	3,	22,	1	,'1602',	1,	2	UNION 
	SELECT 	2,	3,	23,	1	,'1601',	1,	2	UNION 
	SELECT 	2,	3,	23,	-1	,'1602',	2,	2	UNION 
	SELECT 	2,	3,	24,	1	,'1604',	1,	2	UNION 
	SELECT 	2,	3,	25,	1	,'1605',	1,	2	UNION 
	SELECT 	2,	3,	26,	1	,'1606',	1,	2	UNION 
	SELECT 	2,	3,	27,	1	,'1621',	1,	2	UNION 
	SELECT 	2,	3,	27,	-1	,'1622',	2,	2	UNION 
	SELECT 	2,	3,	28,	1	,'1701',	1,	2	UNION 
	SELECT 	2,	3,	30,	1	,'1801',	1,	2	UNION 

	SELECT 	2,	3,	36,	1	,'2001',	1,	2	UNION 
	SELECT 	2,	3,	37,	1	,'2201',	1,	2	UNION 
	SELECT 	2,	3,	38,	1	,'2202',	1,	2	UNION 
	SELECT 	2,	3,	39,	1	,'2203',	1,	2	UNION 
	SELECT 	2,	3,	40,	1	,'2211',	1,	2	UNION 
	SELECT 	2,	3,	41,	1	,'2221',	1,	2	UNION 
	SELECT 	2,	3,	42,	1	,'2231',	1,	2	UNION 
	SELECT 	2,	3,	43,	1	,'2232',	1,	2	UNION 
	SELECT 	2,	3,	44,	1	,'2241',	1,	2	UNION 

	SELECT 	2,	3,	48,	1	,'2501',	1,	2	UNION 
	SELECT 	2,	3,	49,	1	,'2701',	1,	2	UNION 
	SELECT 	2,	3,	50,	1	,'2401',	1,	2	UNION 

	SELECT 	2,	3,	55,	1	,'3001',	1,	2	UNION 
	SELECT 	2,	3,	56,	1	,'3002',	1,	2	UNION 
	SELECT 	2,	3,	57,	1	,'3101',	1,	2	UNION 
	SELECT 	2,	3,	58,	1	,'3104',	1,	2	UNION 
	SELECT 	2,	3,	58,	1	,'3103',	2,	2	


END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('ThreeFinancialFormula_Stype') AND type = 'U')
BEGIN
	CREATE TABLE ThreeFinancialFormula_Stype (
		nId						INT	IDENTITY(1,1),--自增长列
		ReportType				INT,--1:利润表 2：现金流量表 3：资产负债表
		STypeID					VARCHAR(50),	--分支机构ID 
		ItemID					INT,--项目ID
		[Sign]					INT NOT NULL DEFAULT(1),--公式符号 1：正 -1负
		Formula					VARCHAR(1000),--公式/科目
		RowId					INT,--公式/科目 排序
		FormulaType				INT,--比如利润表1：本期金额 2本年累计金额
		IsEditAll				BIT NOT NULL DEFAULT(0),--编辑时是否选择适用于所有分支机构公式
		UpdateTime				DATETIME,--最后一次修改时间
		OperatorId				VARCHAR(50)--操作员
	)

		
END
GO 
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ThreeFinancialFormula_Stype' AND a.Name='UpdateTime'
)
BEGIN
	ALTER TABLE ThreeFinancialFormula_Stype 
		ADD UpdateTime DATETIME
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ThreeFinancialFormula_Stype' AND a.Name='OperatorId'
)
BEGIN
	ALTER TABLE ThreeFinancialFormula_Stype 
		ADD OperatorId VARCHAR(50)
END

GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ThreeFinancialFormula_Stype') AND name = 'CIX_ThreeFinancialFormula_Stype_Nid')
	CREATE CLUSTERED INDEX CIX_ThreeFinancialFormula_Stype_Nid ON ThreeFinancialFormula_Stype(Nid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------预制数据-------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--固化报表项目表
IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('ThreeFinancialItem') AND type = 'U')
BEGIN
	CREATE TABLE ThreeFinancialItem (
		nId						INT	IDENTITY(1,1),--自增长列
		AccountSubId			INT,--会计科目模板ID
		ReportType				INT,--1:利润表 2：现金流量表 3：资产负债表
		ItemID					INT	NOT NULL DEFAULT(0),--项目ID
		ItemFullName			VARCHAR(200) NULL,--项目名称
		Formula1IsPar			BIT NOT NULL DEFAULT(0),--是否合计类
		Formula2IsPar			BIT NOT NULL DEFAULT(0),--是否合计类
		
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
--判断删除数据
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ThreeFinancialItem' AND a.Name='Formula1IsPar'
)
 OR NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ThreeFinancialItem' AND a.Name='Formula1IsPar'
)
BEGIN
	TRUNCATE TABLE ThreeFinancialItem
END 

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ThreeFinancialItem' AND a.Name='Formula1IsPar'
)
BEGIN
	ALTER TABLE ThreeFinancialItem 
		ADD Formula1IsPar BIT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ThreeFinancialItem' AND a.Name='Formula2IsPar'
)
BEGIN
	ALTER TABLE ThreeFinancialItem 
		ADD Formula2IsPar BIT NOT NULL DEFAULT(0)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ThreeFinancialItem') AND name = 'CIX_ThreeFinancialItem_Nid')
	CREATE CLUSTERED INDEX CIX_ThreeFinancialItem_Nid ON ThreeFinancialItem(Nid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------预制数据-------------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialItem WHERE ReportType=1)--1:利润表
BEGIN
	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT	28,	1,	0,	0,	1,	'	一、营业收入	'	UNION
	SELECT	28,	1,	0,	0,	2,	'	    减：营业成本	'	UNION
	SELECT	28,	1,	0,	0,	3,	'	      营业税费	'	UNION
	SELECT	28,	1,	0,	0,	4,	'	      销售费用	'	UNION
	SELECT	28,	1,	0,	0,	5,	'	      管理费用	'	UNION
	SELECT	28,	1,	0,	0,	6,	'	      财务费用	'	UNION
	SELECT	28,	1,	0,	0,	7,	'	      资产减值损失	'	UNION
	SELECT	28,	1,	0,	0,	8,	'	    加：公允价值变动收益（损失以"-"填列)	'	UNION
	SELECT	28,	1,	0,	0,	9,	'	      投资收益（损失以"-"填列)	'	UNION
	SELECT	28,	1,	1,	1,	10,	'	二、营业利润（亏损以"－"号填列)	'	UNION
	SELECT	28,	1,	0,	0,	11,	'	    加：营业外收入	'	UNION
	SELECT	28,	1,	0,	0,	12,	'	    减：营业外支出	'	UNION
	SELECT	28,	1,	0,	0,	13,	'	    其中：非流动资产处置净损失（净收益以“—”号填列)	'	UNION
	SELECT	28,	1,	1,	1,	14,	'	三、利润总额（亏损总额以"－"号填列)	'	UNION
	SELECT	28,	1,	0,	0,	15,	'	    减：所得税	'	UNION
	SELECT	28,	1,	1,	1,	16,	'	四、净利润（净亏损以"－"号填列)	'	UNION
	SELECT	28,	1,	0,	0,	17,	'	五、每股收益：	'	UNION
	SELECT	28,	1,	0,	0,	18,	'	    （一)基本每股收益	'	UNION
	SELECT	28,	1,	0,	0,	19,	'	    （二)稀释每股收益	'	

	--AccountSubId	--1	企业会计制度科目 
					--28新会计准则科目
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT	1,	1,	0,	0,	1,	'	一、主营业务收入	'	UNION
	SELECT	1,	1,	0,	0,	2,	'	    减：主营业务成本	'	UNION
	SELECT	1,	1,	0,	0,	3,	'	        主营业务税金及附加	'	UNION
	SELECT	1,	1,	1,	1,	4,	'	二、主营业务利润（损失以"-"填列）	'	UNION
	SELECT	1,	1,	0,	0,	5,	'	    加：其他业务利润（损失以"-"填列）	'	UNION
	SELECT	1,	1,	0,	0,	6,	'	    减：营业费用	'	UNION
	SELECT	1,	1,	0,	0,	7,	'	        管理费用	'	UNION
	SELECT	1,	1,	0,	0,	8,	'	        财务费用	'	UNION
	SELECT	1,	1,	1,	1,	9,	'	三、营业利润（亏损以"－"号填列）	'	UNION
	SELECT	1,	1,	0,	0,	10,	'	    加：投资收益（损失以"-"填列）	'	UNION
	SELECT	1,	1,	0,	0,	11,	'	        补贴收入	'	UNION
	SELECT	1,	1,	0,	0,	12,	'	        营业外收入	'	UNION
	SELECT	1,	1,	0,	0,	13,	'	    减：营业外支出	'	UNION
	SELECT	1,	1,	1,	1,	14,	'	四、利润总额（亏损总额以"－"号填列）	'	UNION
	SELECT	1,	1,	0,	0,	15,	'	    减：所得税	'	UNION
	SELECT	1,	1,	1,	1,	16,	'	五、净利润（净亏损以"－"号填列）	'	

	--AccountSubId	--2	小企业会计准则科目 
					--1	企业会计制度科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT	2,	1,	0,	0,	1,	'	一、营业收入	'	UNION
	SELECT	2,	1,	0,	0,	2,	'	    减：营业成本	'	UNION
	SELECT	2,	1,	0,	0,	3,	'	          营业税金及附加	'	UNION
	SELECT	2,	1,	0,	0,	4,	'	            其中：消费税	'	UNION
	SELECT	2,	1,	0,	0,	5,	'	                  营业税	'	UNION
	SELECT	2,	1,	0,	0,	6,	'	                  城市维护建设税	'	UNION
	SELECT	2,	1,	0,	0,	7,	'	                  资源税	'	UNION
	SELECT	2,	1,	0,	0,	8,	'	                  土地增值税	'	UNION
	SELECT	2,	1,	0,	0,	9,	'	                  城镇土地使用税、房产税、车船税、印花税	'	UNION
	SELECT	2,	1,	0,	0,	10,	'	                  教育费附加、矿产资源补偿费、排污费	'	UNION
	SELECT	2,	1,	0,	0,	11,	'	        销售费用	'	UNION
	SELECT	2,	1,	0,	0,	12,	'	          其中：商品维修费	'	UNION
	SELECT	2,	1,	0,	0,	13,	'	                广告费和业务宣传费	'	UNION
	SELECT	2,	1,	0,	0,	14,	'	        管理费用	'	UNION
	SELECT	2,	1,	0,	0,	15,	'	          其中：开办费	'	UNION
	SELECT	2,	1,	0,	0,	16,	'	                业务招待费	'	UNION
	SELECT	2,	1,	0,	0,	17,	'	                研究费用	'	UNION
	SELECT	2,	1,	0,	0,	18,	'	        财务费用	'	UNION
	SELECT	2,	1,	0,	0,	19,	'	          其中：利息费用（收入以“-”号填列）	'	UNION
	SELECT	2,	1,	0,	0,	20,	'	    加：投资收益（损失以“-”号填列）	'	UNION
	SELECT	2,	1,	1,	1,	21,	'	二、营业利润（亏损以“-”号填列）	'	UNION
	SELECT	2,	1,	0,	0,	22,	'	    加：营业外收入	'	UNION
	SELECT	2,	1,	0,	0,	23,	'	          其中：政府补助	'	UNION
	SELECT	2,	1,	0,	0,	24,	'	    减：营业外支出	'	UNION
	SELECT	2,	1,	0,	0,	25,	'	          其中：坏账损失	'	UNION
	SELECT	2,	1,	0,	0,	26,	'	                无法收回的长期债券投资损失	'	UNION
	SELECT	2,	1,	0,	0,	27,	'	                无法收回的长期股权投资损失	'	UNION
	SELECT	2,	1,	0,	0,	28,	'	                自然灾害等不可抗力因素造成的损失	'	UNION
	SELECT	2,	1,	0,	0,	29,	'	                税收滞纳金	'	UNION
	SELECT	2,	1,	1,	1,	30,	'	三、利润总额（亏损总额以"－"号填列）	'	UNION
	SELECT	2,	1,	0,	0,	31,	'	    减：所得税费用	'	UNION
	SELECT	2,	1,	1,	1,	32,	'	四、净利润（净亏损以"－"号填列）	'	

END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialItem WHERE ReportType=2)--2：现金流量表
BEGIN
	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT	28,	2,	0,	0,	1,	'	一、经营活动产生的现金流量：	'	UNION
	SELECT	28,	2,	0,	0,	2,	'	    销售商品、提供劳务收到的现金	'	UNION
	SELECT	28,	2,	0,	0,	3,	'	    收到的税费返还	'	UNION
	SELECT	28,	2,	0,	0,	4,	'	    收到其他与经营活动有关的现金	'	UNION
	SELECT	28,	2,	1,	1,	5,	'	      经营活动现金流入小计	'	UNION
	SELECT	28,	2,	0,	0,	6,	'	    购买商品、接受劳务支付的现金	'	UNION
	SELECT	28,	2,	0,	0,	7,	'	    支付给职工以及为职工支付的现金	'	UNION
	SELECT	28,	2,	0,	0,	8,	'	    支付的各项税费	'	UNION
	SELECT	28,	2,	0,	0,	9,	'	    支付其它与经营活动有关的现金	'	UNION
	SELECT	28,	2,	1,	1,	10,	'	      经营活动现金流出小计	'	UNION
	SELECT	28,	2,	1,	1,	11,	'	经营活动产生的现金流量净额	'	UNION
	SELECT	28,	2,	0,	0,	12,	'	二、投资活动产生的现金流量：	'	UNION
	SELECT	28,	2,	0,	0,	13,	'	    收回投资收到的现金	'	UNION
	SELECT	28,	2,	0,	0,	14,	'	    取得投资收益收到的现金	'	UNION
	SELECT	28,	2,	0,	0,	15,	'	    处置固定资产、无形资产和其他长期资产收回的现金净额	'	UNION
	SELECT	28,	2,	0,	0,	16,	'	    处置子公司及其他营业单位收到的现金净额	'	UNION
	SELECT	28,	2,	0,	0,	17,	'	    收到其他与投资活动有关的现金	'	UNION
	SELECT	28,	2,	1,	1,	18,	'	      投资活动现金流入小计	'	UNION
	SELECT	28,	2,	0,	0,	19,	'	    购建固定资产、无形资产和其他长期资产所支付的现金	'	UNION
	SELECT	28,	2,	0,	0,	20,	'	    投资支付的现金	'	UNION
	SELECT	28,	2,	0,	0,	21,	'	    取得子公司及其他营业单位支付的现金净额	'	UNION
	SELECT	28,	2,	0,	0,	22,	'	    支付的其他与投资活动有关的现金	'	UNION
	SELECT	28,	2,	1,	1,	23,	'	      投资活动现金流出小计	'	UNION
	SELECT	28,	2,	1,	1,	24,	'	投资活动产生的现金流量净额	'	UNION
	SELECT	28,	2,	0,	0,	25,	'	三、筹资活动产生的现金流量：	'	UNION
	SELECT	28,	2,	0,	0,	26,	'	    吸收投资收到的现金	'	UNION
	SELECT	28,	2,	0,	0,	27,	'	    取得借款收到的现金	'	UNION
	SELECT	28,	2,	0,	0,	28,	'	    收到其他与筹资活动有关的现金	'	UNION
	SELECT	28,	2,	1,	1,	29,	'	      筹资活动现金流入小计	'	UNION
	SELECT	28,	2,	0,	0,	30,	'	    偿还债务支付的现金	'	UNION
	SELECT	28,	2,	0,	0,	31,	'	    分配股利、利润或偿付利息支付的现金	'	UNION
	SELECT	28,	2,	0,	0,	32,	'	    支付其他与筹资活动有关的现金	'	UNION
	SELECT	28,	2,	1,	1,	33,	'	      筹资活动现金流出小计	'	UNION
	SELECT	28,	2,	1,	1,	34,	'	筹资活动产生的现金流量净额	'	UNION
	SELECT	28,	2,	0,	0,	35,	'	四、汇率变动对现金及现金等价物的影响	'	UNION
	SELECT	28,	2,	1,	1,	36,	'	五、现金及现金等价物净增加额	'	UNION
	SELECT	28,	2,	0,	0,	37,	'	    加：期初现金及现金等价物余额	'	UNION
	SELECT	28,	2,	1,	1,	38,	'	六、期末现金及现金等价物余额	'	

	--AccountSubId	--1	企业会计制度科目 
					--28新会计准则科目
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT	1,	2,	0,	0,	1,	'	一、经营活动产生的现金流量：	'	UNION
	SELECT	1,	2,	0,	0,	2,	'	    销售商品、提供劳务收到的现金	'	UNION
	SELECT	1,	2,	0,	0,	3,	'	    收到的税费返还	'	UNION
	SELECT	1,	2,	0,	0,	4,	'	    收到其他与经营活动有关的现金	'	UNION
	SELECT	1,	2,	1,	1,	5,	'	      经营活动现金流入小计	'	UNION
	SELECT	1,	2,	0,	0,	6,	'	    购买商品、接受劳务支付的现金	'	UNION
	SELECT	1,	2,	0,	0,	7,	'	    支付给职工以及为职工支付的现金	'	UNION
	SELECT	1,	2,	0,	0,	8,	'	    支付的各项税费	'	UNION
	SELECT	1,	2,	0,	0,	9,	'	    支付其它与经营活动有关的现金	'	UNION
	SELECT	1,	2,	1,	1,	10,	'	      经营活动现金流出小计	'	UNION
	SELECT	1,	2,	1,	1,	11,	'	经营活动产生的现金流量净额	'	UNION
	SELECT	1,	2,	0,	0,	12,	'	二、投资活动产生的现金流量：	'	UNION
	SELECT	1,	2,	0,	0,	13,	'	    收回投资收到的现金	'	UNION
	SELECT	1,	2,	0,	0,	14,	'	    取得投资收益收到的现金	'	UNION
	SELECT	1,	2,	0,	0,	15,	'	    处置固定资产、无形资产和其他长期资产收回的现金净额	'	UNION
	SELECT	1,	2,	0,	0,	16,	'	    处置子公司及其他营业单位收到的现金净额	'	UNION
	SELECT	1,	2,	0,	0,	17,	'	    收到其他与投资活动有关的现金	'	UNION
	SELECT	1,	2,	1,	1,	18,	'	      投资活动现金流入小计	'	UNION
	SELECT	1,	2,	0,	0,	19,	'	    购建固定资产、无形资产和其他长期资产所支付的现金	'	UNION
	SELECT	1,	2,	0,	0,	20,	'	    投资支付的现金	'	UNION
	SELECT	1,	2,	0,	0,	21,	'	    取得子公司及其他营业单位支付的现金净额	'	UNION
	SELECT	1,	2,	0,	0,	22,	'	    支付的其他与投资活动有关的现金	'	UNION
	SELECT	1,	2,	1,	1,	23,	'	      投资活动现金流出小计	'	UNION
	SELECT	1,	2,	1,	1,	24,	'	投资活动产生的现金流量净额	'	UNION
	SELECT	1,	2,	0,	0,	25,	'	三、筹资活动产生的现金流量：	'	UNION
	SELECT	1,	2,	0,	0,	26,	'	    吸收投资收到的现金	'	UNION
	SELECT	1,	2,	0,	0,	27,	'	    取得借款收到的现金	'	UNION
	SELECT	1,	2,	0,	0,	28,	'	    收到其他与筹资活动有关的现金	'	UNION
	SELECT	1,	2,	1,	1,	29,	'	      筹资活动现金流入小计	'	UNION
	SELECT	1,	2,	0,	0,	30,	'	    偿还债务支付的现金	'	UNION
	SELECT	1,	2,	0,	0,	31,	'	    分配股利、利润或偿付利息支付的现金	'	UNION
	SELECT	1,	2,	0,	0,	32,	'	    支付其他与筹资活动有关的现金	'	UNION
	SELECT	1,	2,	1,	1,	33,	'	      筹资活动现金流出小计	'	UNION
	SELECT	1,	2,	1,	1,	34,	'	筹资活动产生的现金流量净额	'	UNION
	SELECT	1,	2,	0,	0,	35,	'	四、汇率变动对现金及现金等价物的影响	'	UNION
	SELECT	1,	2,	1,	1,	36,	'	五、现金及现金等价物净增加额	'	UNION
	SELECT	1,	2,	0,	0,	37,	'	    加：期初现金及现金等价物余额	'	UNION
	SELECT	1,	2,	1,	1,	38,	'	六、期末现金及现金等价物余额	'	

	--AccountSubId	--2	小企业会计准则科目
					--1	企业会计制度科目 
					-- 28新会计准则科目
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT	2,	2,	0,	0,	1,	'	一、经营活动产生的现金流量：	'	UNION
	SELECT	2,	2,	0,	0,	2,	'	    销售商品、提供劳务收到的现金	'	UNION
	SELECT	2,	2,	0,	0,	3,	'	    收到的税费返还	'	UNION
	SELECT	2,	2,	0,	0,	4,	'	    收到其他与经营活动有关的现金	'	UNION
	SELECT	2,	2,	1,	1,	5,	'	      经营活动现金流入小计	'	UNION
	SELECT	2,	2,	0,	0,	6,	'	    购买商品、接受劳务支付的现金	'	UNION
	SELECT	2,	2,	0,	0,	7,	'	    支付给职工以及为职工支付的现金	'	UNION
	SELECT	2,	2,	0,	0,	8,	'	    支付的各项税费	'	UNION
	SELECT	2,	2,	0,	0,	9,	'	    支付其它与经营活动有关的现金	'	UNION
	SELECT	2,	2,	1,	1,	10,	'	      经营活动现金流出小计	'	UNION
	SELECT	2,	2,	1,	1,	11,	'	经营活动产生的现金流量净额	'	UNION
	SELECT	2,	2,	0,	0,	12,	'	二、投资活动产生的现金流量：	'	UNION
	SELECT	2,	2,	0,	0,	13,	'	    收回投资收到的现金	'	UNION
	SELECT	2,	2,	0,	0,	14,	'	    取得投资收益收到的现金	'	UNION
	SELECT	2,	2,	0,	0,	15,	'	    处置固定资产、无形资产和其他长期资产收回的现金净额	'	UNION
	SELECT	2,	2,	0,	0,	16,	'	    处置子公司及其他营业单位收到的现金净额	'	UNION
	SELECT	2,	2,	0,	0,	17,	'	    收到其他与投资活动有关的现金	'	UNION
	SELECT	2,	2,	1,	1,	18,	'	      投资活动现金流入小计	'	UNION
	SELECT	2,	2,	0,	0,	19,	'	    购建固定资产、无形资产和其他长期资产所支付的现金	'	UNION
	SELECT	2,	2,	0,	0,	20,	'	    投资支付的现金	'	UNION
	SELECT	2,	2,	0,	0,	21,	'	    取得子公司及其他营业单位支付的现金净额	'	UNION
	SELECT	2,	2,	0,	0,	22,	'	    支付的其他与投资活动有关的现金	'	UNION
	SELECT	2,	2,	1,	1,	23,	'	      投资活动现金流出小计	'	UNION
	SELECT	2,	2,	1,	1,	24,	'	投资活动产生的现金流量净额	'	UNION
	SELECT	2,	2,	0,	0,	25,	'	三、筹资活动产生的现金流量：	'	UNION
	SELECT	2,	2,	0,	0,	26,	'	    吸收投资收到的现金	'	UNION
	SELECT	2,	2,	0,	0,	27,	'	    取得借款收到的现金	'	UNION
	SELECT	2,	2,	0,	0,	28,	'	    收到其他与筹资活动有关的现金	'	UNION
	SELECT	2,	2,	1,	1,	29,	'	      筹资活动现金流入小计	'	UNION
	SELECT	2,	2,	0,	0,	30,	'	    偿还债务支付的现金	'	UNION
	SELECT	2,	2,	0,	0,	31,	'	    分配股利、利润或偿付利息支付的现金	'	UNION
	SELECT	2,	2,	0,	0,	32,	'	    支付其他与筹资活动有关的现金	'	UNION
	SELECT	2,	2,	1,	1,	33,	'	      筹资活动现金流出小计	'	UNION
	SELECT	2,	2,	1,	1,	34,	'	筹资活动产生的现金流量净额	'	UNION
	SELECT	2,	2,	0,	0,	35,	'	四、汇率变动对现金及现金等价物的影响	'	UNION
	SELECT	2,	2,	1,	1,	36,	'	五、现金及现金等价物净增加额	'	UNION
	SELECT	2,	2,	0,	0,	37,	'	    加：期初现金及现金等价物余额	'	UNION
	SELECT	2,	2,	1,	1,	38,	'	六、期末现金及现金等价物余额	'	
	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialItem WHERE ReportType=3)--3：资产负债表
BEGIN
	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT	28,	3,	0,	0,	1,	'资 产	'	UNION
	SELECT	28,	3,	0,	0,	2,	'	流动资产	'	UNION
	SELECT	28,	3,	0,	0,	3,	'	    货币资金	'	UNION
	SELECT	28,	3,	0,	0,	4,	'	    交易性金融资产	'	UNION
	SELECT	28,	3,	0,	0,	5,	'	    应收票据	'	UNION
	SELECT	28,	3,	0,	0,	6,	'	    应收账款	'	UNION
	SELECT	28,	3,	0,	0,	7,	'	    预付款项	'	UNION
	SELECT	28,	3,	0,	0,	8,	'	    应收利息	'	UNION
	SELECT	28,	3,	0,	0,	9,	'	    应收股利	'	UNION
	SELECT	28,	3,	0,	0,	10,	'	    其他应收款	'	UNION
	SELECT	28,	3,	0,	0,	11,	'	    存货	'	UNION
	SELECT	28,	3,	0,	0,	12,	'	    其中：消耗性生物资产	'	UNION
	SELECT	28,	3,	0,	0,	13,	'	    待摊费用	'	UNION
	SELECT	28,	3,	0,	0,	14,	'	    一年内到期的非流动资产	'	UNION
	SELECT	28,	3,	0,	0,	15,	'	    其他流动资产	'	UNION
	SELECT	28,	3,	1,	1,	16,	'	流动资产合计	'	UNION
	SELECT	28,	3,	0,	0,	17,	'	非流动资产：	'	UNION
	SELECT	28,	3,	0,	0,	18,	'	    可供出售金融资产	'	UNION
	SELECT	28,	3,	0,	0,	19,	'	    持有至到期投资	'	UNION
	SELECT	28,	3,	0,	0,	20,	'	    长期应收款	'	UNION
	SELECT	28,	3,	0,	0,	21,	'	    长期股权投资	'	UNION
	SELECT	28,	3,	0,	0,	22,	'	    投资性房地产	'	UNION
	SELECT	28,	3,	0,	0,	23,	'	    固定资产	'	UNION
	SELECT	28,	3,	0,	0,	24,	'	    在建工程	'	UNION
	SELECT	28,	3,	0,	0,	25,	'	    工程物资	'	UNION
	SELECT	28,	3,	0,	0,	26,	'	    固定资产清理	'	UNION
	SELECT	28,	3,	0,	0,	27,	'	    生产性生物资产	'	UNION
	SELECT	28,	3,	0,	0,	28,	'	    油气资产	'	UNION
	SELECT	28,	3,	0,	0,	29,	'	    无形资产	'	UNION
	SELECT	28,	3,	0,	0,	30,	'	    开发支出	'	UNION
	SELECT	28,	3,	0,	0,	31,	'	    商誉	'	UNION
	SELECT	28,	3,	0,	0,	32,	'	    长期待摊费用	'	UNION
	SELECT	28,	3,	0,	0,	33,	'	    递延所得税资产	'	UNION
	SELECT	28,	3,	0,	0,	34,	'	    其他非流动资产	'	UNION
	SELECT	28,	3,	1,	1,	35,	'	非流动资产合计	'	UNION
	SELECT	28,	3,	1,	1,	36,	'资产总计	'	UNION
	SELECT	28,	3,	0,	0,	37,	'负债及所有者权益（或股东权益）	'	UNION
	SELECT	28,	3,	0,	0,	38,	'	流动负债：	'	UNION
	SELECT	28,	3,	0,	0,	39,	'	    短期借款	'	UNION
	SELECT	28,	3,	0,	0,	40,	'	    交易性金融负债	'	UNION
	SELECT	28,	3,	0,	0,	41,	'	    应付票据	'	UNION
	SELECT	28,	3,	0,	0,	42,	'	    应付账款	'	UNION
	SELECT	28,	3,	0,	0,	43,	'	    预收款项	'	UNION
	SELECT	28,	3,	0,	0,	44,	'	    应付职工薪酬	'	UNION
	SELECT	28,	3,	0,	0,	45,	'	    应交税费	'	UNION
	SELECT	28,	3,	0,	0,	46,	'	    应付利息	'	UNION
	SELECT	28,	3,	0,	0,	47,	'	    应付股利	'	UNION
	SELECT	28,	3,	0,	0,	48,	'	    其他应付款	'	UNION
	SELECT	28,	3,	0,	0,	49,	'	    预提费用	'	UNION
	SELECT	28,	3,	0,	0,	50,	'	    预计负债	'	UNION
	SELECT	28,	3,	0,	0,	51,	'	    一年内到期的非流动负债	'	UNION
	SELECT	28,	3,	0,	0,	52,	'	    其他流动负债	'	UNION
	SELECT	28,	3,	1,	1,	53,	'	流动负债合计	'	UNION
	SELECT	28,	3,	0,	0,	54,	'	非流动负债：	'	UNION
	SELECT	28,	3,	0,	0,	55,	'	    长期借款	'	UNION
	SELECT	28,	3,	0,	0,	56,	'	    应付债券	'	UNION
	SELECT	28,	3,	0,	0,	57,	'	    长期应付款	'	UNION
	SELECT	28,	3,	0,	0,	58,	'	    专项应付款	'	UNION
	SELECT	28,	3,	0,	0,	59,	'	    递延所得税负债	'	UNION
	SELECT	28,	3,	0,	0,	60,	'	    其他非流动负债	'	UNION
	SELECT	28,	3,	1,	1,	61,	'	非流动负债合计	'	UNION
	SELECT	28,	3,	1,	1,	62,	'	负债合计	'	UNION
	SELECT	28,	3,	0,	0,	63,	'	所有者权益（或股东权益）：	'	UNION
	SELECT	28,	3,	0,	0,	64,	'	    实收资本（或股本）	'	UNION
	SELECT	28,	3,	0,	0,	65,	'	    资本公积	'	UNION
	SELECT	28,	3,	0,	0,	66,	'	    减：库存股	'	UNION
	SELECT	28,	3,	0,	0,	67,	'	    盈余公积	'	UNION
	SELECT	28,	3,	0,	0,	68,	'	    未分配利润	'	UNION
	SELECT	28,	3,	1,	1,	69,	'	所有者权益（或股东权益）合计	'	UNION
	SELECT	28,	3,	1,	1,	70,	'负债和所有者权益（或股东权益）总计	'	

	--AccountSubId	--1	企业会计制度科目 
					--2	小企业会计准则科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT 	1,	3,	0,	0,	1,	'资产	'	UNION
	SELECT 	1,	3,	0,	0,	2,	'	流动资产：	'	UNION
	SELECT 	1,	3,	0,	0,	3,	'	    货币资金	'	UNION
	SELECT 	1,	3,	0,	0,	4,	'	    短期投资	'	UNION
	SELECT 	1,	3,	0,	0,	5,	'	    应收票据	'	UNION
	SELECT 	1,	3,	0,	0,	6,	'	    应收股利	'	UNION
	SELECT 	1,	3,	0,	0,	7,	'	    应收利息	'	UNION
	SELECT 	1,	3,	0,	0,	8,	'	    应收账款	'	UNION
	SELECT 	1,	3,	0,	0,	9,	'	    其他应收款	'	UNION
	SELECT 	1,	3,	0,	0,	10,	'	    预付账款	'	UNION
	SELECT 	1,	3,	0,	0,	11,	'	    应收补贴款	'	UNION
	SELECT 	1,	3,	0,	0,	12,	'	    存货	'	UNION
	SELECT 	1,	3,	0,	0,	13,	'	    待摊费用	'	UNION
	SELECT 	1,	3,	0,	0,	14,	'	    一年内到期长期债权投资	'	UNION
	SELECT 	1,	3,	0,	0,	15,	'	    其他流动资产	'	UNION
	SELECT 	1,	3,	1,	1,	16,	'	流动资产合计	'	UNION
	SELECT 	1,	3,	0,	0,	17,	'	长期投资：	'	UNION
	SELECT 	1,	3,	0,	0,	18,	'	    长期股权投资	'	UNION
	SELECT 	1,	3,	0,	0,	19,	'	    长期债权投资	'	UNION
	SELECT 	1,	3,	1,	1,	20,	'	长期投资合计	'	UNION
	SELECT 	1,	3,	0,	0,	21,	'	固定资产：	'	UNION
	SELECT 	1,	3,	0,	0,	22,	'	    固定资产原价	'	UNION
	SELECT 	1,	3,	0,	0,	23,	'	    减：累计折旧	'	UNION
	SELECT 	1,	3,	1,	1,	24,	'	    固定资产净值	'	UNION
	SELECT 	1,	3,	0,	0,	25,	'	    减：固定资产减值准备	'	UNION
	SELECT 	1,	3,	1,	1,	26,	'	    固定资产净额	'	UNION
	SELECT 	1,	3,	0,	0,	27,	'	    工程物质	'	UNION
	SELECT 	1,	3,	0,	0,	28,	'	    在建工程	'	UNION
	SELECT 	1,	3,	0,	0,	29,	'	    固定资产清理	'	UNION
	SELECT 	1,	3,	1,	1,	30,	'	固定资产合计	'	UNION
	SELECT 	1,	3,	0,	0,	31,	'	无形资产及其他资产：	'	UNION
	SELECT 	1,	3,	0,	0,	32,	'	    无形资产	'	UNION
	SELECT 	1,	3,	0,	0,	33,	'	    长期待摊费用	'	UNION
	SELECT 	1,	3,	0,	0,	34,	'	    其他长期资产	'	UNION
	SELECT 	1,	3,	1,	1,	35,	'	无形及其他资产合计	'	UNION
	SELECT 	1,	3,	0,	0,	36,	'	递延税项：	'	UNION
	SELECT 	1,	3,	0,	0,	37,	'	    递延税款借项	'	UNION
	SELECT 	1,	3,	1,	1,	38,	'资产总计	'	UNION
	SELECT 	1,	3,	0,	0,	39,	'负债及所有者权益（或股东权益）	'	UNION
	SELECT 	1,	3,	0,	0,	40,	'	流动负债：	'	UNION
	SELECT 	1,	3,	0,	0,	41,	'	    短期借款	'	UNION
	SELECT 	1,	3,	0,	0,	42,	'	    应付票据	'	UNION
	SELECT 	1,	3,	0,	0,	43,	'	    应付账款	'	UNION
	SELECT 	1,	3,	0,	0,	44,	'	    预收款项	'	UNION
	SELECT 	1,	3,	0,	0,	45,	'	    应付工资	'	UNION
	SELECT 	1,	3,	0,	0,	46,	'	    应付福利费	'	UNION
	SELECT 	1,	3,	0,	0,	47,	'	    应付股利	'	UNION
	SELECT 	1,	3,	0,	0,	48,	'	    应交税金	'	UNION
	SELECT 	1,	3,	0,	0,	49,	'	    其他应交款	'	UNION
	SELECT 	1,	3,	0,	0,	50,	'	    其他应付款	'	UNION
	SELECT 	1,	3,	0,	0,	51,	'	    预提费用	'	UNION
	SELECT 	1,	3,	0,	0,	52,	'	    预计负债	'	UNION
	SELECT 	1,	3,	0,	0,	53,	'	    一年内到期长期负债	'	UNION
	SELECT 	1,	3,	0,	0,	54,	'	    其他流动负债	'	UNION
	SELECT 	1,	3,	1,	1,	55,	'	 流动负债合计	'	UNION
	SELECT 	1,	3,	0,	0,	56,	'	长期负债：	'	UNION
	SELECT 	1,	3,	0,	0,	57,	'	    长期借款	'	UNION
	SELECT 	1,	3,	0,	0,	58,	'	    应付债券	'	UNION
	SELECT 	1,	3,	0,	0,	59,	'	    长期应付款	'	UNION
	SELECT 	1,	3,	0,	0,	60,	'	    专项应付款	'	UNION
	SELECT 	1,	3,	0,	0,	61,	'	    其他长期负债	'	UNION
	SELECT 	1,	3,	1,	1,	62,	'	长期负债合计	'	UNION
	SELECT 	1,	3,	0,	0,	63,	'	递延税项：	'	UNION
	SELECT 	1,	3,	0,	0,	64,	'	    递延税款贷项	'	UNION
	SELECT 	1,	3,	1,	1,	65,	'	负债合计	'	UNION
	SELECT 	1,	3,	0,	0,	66,	'	所有者权益（或股东权益）：	'	UNION
	SELECT 	1,	3,	0,	0,	67,	'	    实收资本（或股本）	'	UNION
	SELECT 	1,	3,	0,	0,	68,	'	    减：已归还投资	'	UNION
	SELECT 	1,	3,	1,	1,	69,	'	    实收资本（或股本）净额	'	UNION
	SELECT 	1,	3,	0,	0,	70,	'	    资本公积	'	UNION
	SELECT 	1,	3,	0,	0,	71,	'	    盈余公积	'	UNION
	SELECT 	1,	3,	0,	0,	72,	'			其中：法定公益金	'	UNION
	SELECT 	1,	3,	0,	0,	73,	'	    未分配利润	'	UNION
	SELECT 	1,	3,	1,	1,	74,	'	所有者权益（股东权益）合计	'	UNION
	SELECT 	1,	3,	1,	1,	75,	'负债及权益（股东权益）合计	'	

	--AccountSubId	--2	小企业会计准则科目
					--1	企业会计制度科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialItem(AccountSubId,ReportType,Formula1IsPar,Formula2IsPar,ItemID,ItemFullName)
	SELECT 	2,	3,	0,	0,	1,	'资 产	'	UNION 
	SELECT 	2,	3,	0,	0,	2,	'	流动资产：	'	UNION 
	SELECT 	2,	3,	0,	0,	3,	'	    货币资金	'	UNION 
	SELECT 	2,	3,	0,	0,	4,	'	    短期投资	'	UNION 
	SELECT 	2,	3,	0,	0,	5,	'	    应收票据	'	UNION 
	SELECT 	2,	3,	0,	0,	6,	'	    应收账款	'	UNION 
	SELECT 	2,	3,	0,	0,	7,	'	    预付账款	'	UNION 
	SELECT 	2,	3,	0,	0,	8,	'	    应收股利	'	UNION 
	SELECT 	2,	3,	0,	0,	9,	'	    应收利息	'	UNION 
	SELECT 	2,	3,	0,	0,	10,	'	    其他应收款	'	UNION 
	SELECT 	2,	3,	0,	0,	11,	'	    存货	'	UNION 
	SELECT 	2,	3,	0,	0,	12,	'	      其中：原材料	'	UNION 
	SELECT 	2,	3,	0,	0,	13,	'	            在产品	'	UNION 
	SELECT 	2,	3,	0,	0,	14,	'	            库存商品	'	UNION 
	SELECT 	2,	3,	0,	0,	15,	'	            周转材料	'	UNION 
	SELECT 	2,	3,	0,	0,	16,	'	    其他流动资产	'	UNION 
	SELECT 	2,	3,	1,	1,	17,	'	流动资产合计	'	UNION 
	SELECT 	2,	3,	0,	0,	18,	'	非流动资产：	'	UNION 
	SELECT 	2,	3,	0,	0,	19,	'	    长期债券投资	'	UNION 
	SELECT 	2,	3,	0,	0,	20,	'	    长期股权投资	'	UNION 
	SELECT 	2,	3,	0,	0,	21,	'	    固定资产原价	'	UNION 
	SELECT 	2,	3,	0,	0,	22,	'	    减：累计折旧	'	UNION 
	SELECT 	2,	3,	0,	0,	23,	'	    固定资产账面价值	'	UNION 
	SELECT 	2,	3,	0,	0,	24,	'	    在建工程	'	UNION 
	SELECT 	2,	3,	0,	0,	25,	'	    工程物资	'	UNION 
	SELECT 	2,	3,	0,	0,	26,	'	    固定资产清理	'	UNION 
	SELECT 	2,	3,	0,	0,	27,	'	    生产性生物资产	'	UNION 
	SELECT 	2,	3,	0,	0,	28,	'	    无形资产	'	UNION 
	SELECT 	2,	3,	0,	0,	29,	'	    开发支出	'	UNION 
	SELECT 	2,	3,	0,	0,	30,	'	    长期待摊费用	'	UNION 
	SELECT 	2,	3,	0,	0,	31,	'	    其他非流动资产	'	UNION 
	SELECT 	2,	3,	1,	1,	32,	'	非流动资产合计	'	UNION 
	SELECT 	2,	3,	1,	1,	33,	'资产总计	'	UNION 
	SELECT 	2,	3,	0,	0,	34,	'负债及所有者权益（或股东权益）	'	UNION 
	SELECT 	2,	3,	0,	0,	35,	'	流动负债：	'	UNION 
	SELECT 	2,	3,	0,	0,	36,	'	    短期借款	'	UNION 
	SELECT 	2,	3,	0,	0,	37,	'	    应付票据	'	UNION 
	SELECT 	2,	3,	0,	0,	38,	'	    应付账款	'	UNION 
	SELECT 	2,	3,	0,	0,	39,	'	    预收账款	'	UNION 
	SELECT 	2,	3,	0,	0,	40,	'	    应付职工薪酬	'	UNION 
	SELECT 	2,	3,	0,	0,	41,	'	    应交税费	'	UNION 
	SELECT 	2,	3,	0,	0,	42,	'	    应付利息	'	UNION 
	SELECT 	2,	3,	0,	0,	43,	'	    应付利润	'	UNION 
	SELECT 	2,	3,	0,	0,	44,	'	    其他应付款	'	UNION 
	SELECT 	2,	3,	0,	0,	45,	'	    其他流动负债	'	UNION 
	SELECT 	2,	3,	1,	1,	46,	'	流动负债合计	'	UNION 
	SELECT 	2,	3,	0,	0,	47,	'	非流动负债：	'	UNION 
	SELECT 	2,	3,	0,	0,	48,	'	    长期借款	'	UNION 
	SELECT 	2,	3,	0,	0,	49,	'	    长期应付款	'	UNION 
	SELECT 	2,	3,	0,	0,	50,	'	    递延收益	'	UNION 
	SELECT 	2,	3,	0,	0,	51,	'	    其他非流动负债	'	UNION 
	SELECT 	2,	3,	1,	1,	52,	'	非流动负债合计	'	UNION 
	SELECT 	2,	3,	1,	1,	53,	'	负债合计	'	UNION 
	SELECT 	2,	3,	0,	0,	54,	'	所有者权益（或股东权益）：	'	UNION 
	SELECT 	2,	3,	0,	0,	55,	'	    实收资本（或股本）	'	UNION 
	SELECT 	2,	3,	0,	0,	56,	'	    资本公积	'	UNION 
	SELECT 	2,	3,	0,	0,	57,	'	    盈余公积	'	UNION 
	SELECT 	2,	3,	0,	0,	58,	'	    未分配利润	'	UNION 
	SELECT 	2,	3,	1,	1,	59,	'	所有者权益（或股东权益）合计	'	UNION 
	SELECT 	2,	3,	1,	1,	60,	'负债和所有者权益（或股东权益）总计	'	

END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--固化报表项目表
IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('ThreeFinancialItem_SType') AND type = 'U')
BEGIN
	CREATE TABLE ThreeFinancialItem_SType (
		nId						INT				IDENTITY(1,1),--自增长列
		ReportType				INT,--1:利润表 2：现金流量表 3：资产负债表
		STypeID					VARCHAR(50),	--分支机构ID 
		ItemID					INT				NOT NULL DEFAULT(0),--项目ID
		ItemFullName			VARCHAR(200)	NULL,--项目名称
		Formula1IsPar			BIT NOT NULL DEFAULT(0),--是否合计类
		Formula2IsPar			BIT NOT NULL DEFAULT(0),--是否合计类
		AccountClassifiable		BIT NOT NULL DEFAULT(0)
	)
END
GO 
------------------------------------------表修改区域开始-------------------------------------------------
----科目重分类
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='ThreeFinancialItem_SType' AND a.Name='AccountClassifiable'
--)
--BEGIN
--	ALTER TABLE ThreeFinancialItem_SType 
--		ADD AccountClassifiable BIT NOT NULL DEFAULT(0)
--END

--GO 
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ThreeFinancialItem_SType') AND name = 'CIX_ThreeFinancialItem_SType_Nid')
	CREATE CLUSTERED INDEX CIX_ThreeFinancialItem_SType_Nid ON ThreeFinancialItem_SType(Nid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------预制数据-------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--固化报表项目表 合计行父节点
IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('ThreeFinancialItemParent') AND type = 'U')
BEGIN
	CREATE TABLE ThreeFinancialItemParent (
		nId						INT				IDENTITY(1,1),--自增长列
		AccountSubId			INT,--会计科目模板ID
		ReportType				INT,--1:利润表 2：现金流量表 3：资产负债表
		ParItemID				INT				NOT NULL DEFAULT(0),--父类项目ID
		[Sign]					INT NOT NULL DEFAULT(1),--公式符号 1：正 -1负
		SonItemID				INT				NOT NULL DEFAULT(0),--自己项目ID
		FormulaType				INT--公式类型比如利润表1：本期金额 2本年累计金额
		
	)
END
GO   

------------------------------------------表修改区域开始-------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='ThreeFinancialItem' AND a.Name='ItemFullName'
--)
--BEGIN
--	ALTER TABLE Ac_Items 
--		ADD ItemFullName VARCHAR(400) NULL DEFAULT('')
--END

--GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ThreeFinancialItemParent') AND name = 'CIX_ThreeFinancialItemParent_Nid')
	CREATE CLUSTERED INDEX CIX_ThreeFinancialItemParent_Nid ON ThreeFinancialItemParent(Nid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------预制数据-------------------------------------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialItemParent WHERE ReportType=1)--1:利润表
BEGIN
	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	--本期金额
	SELECT	28,	1,	10,	1,	1	,1	UNION--二、营业利润（亏损以"－"号填列)
	SELECT	28,	1,	10,	-1,	2	,1	UNION
	SELECT	28,	1,	10,	-1,	3	,1	UNION
	SELECT	28,	1,	10,	-1,	4	,1	UNION
	SELECT	28,	1,	10,	-1,	5	,1	UNION
	SELECT	28,	1,	10,	-1,	6	,1	UNION
	SELECT	28,	1,	10,	-1,	7	,1	UNION
	SELECT	28,	1,	10,	1,	8	,1	UNION
	SELECT	28,	1,	10,	1,	9	,1	UNION
	
	SELECT	28,	1,	14,	1,	10	,1	UNION--三、利润总额（亏损总额以"－"号填列)	
	SELECT	28,	1,	14,	1,	11	,1	UNION
	SELECT	28,	1,	14,	-1,	12	,1	UNION
	
	SELECT	28,	1,	16,	1,	14	,1	UNION--四、净利润（净亏损以"－"号填列)	
	SELECT	28,	1,	16,	-1,	15	,1  UNION
	
	--本年累计
	SELECT	28,	1,	10,	1,	1	,2	UNION--二、营业利润（亏损以"－"号填列)
	SELECT	28,	1,	10,	-1,	2	,2	UNION
	SELECT	28,	1,	10,	-1,	3	,2	UNION
	SELECT	28,	1,	10,	-1,	4	,2	UNION
	SELECT	28,	1,	10,	-1,	5	,2	UNION
	SELECT	28,	1,	10,	-1,	6	,2	UNION
	SELECT	28,	1,	10,	-1,	7	,2	UNION
	SELECT	28,	1,	10,	1,	8	,2	UNION
	SELECT	28,	1,	10,	1,	9	,2	UNION
	
	SELECT	28,	1,	14,	1,	10	,2	UNION--三、利润总额（亏损总额以"－"号填列)	
	SELECT	28,	1,	14,	1,	11	,2	UNION
	SELECT	28,	1,	14,	-1,	12	,2	UNION
	
	SELECT	28,	1,	16,	1,	14	,2	UNION--四、净利润（净亏损以"－"号填列)	
	SELECT	28,	1,	16,	-1,	15	,2


	--AccountSubId	--1	企业会计制度科目 
					--28新会计准则科目
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	--本期金额
	SELECT	1,	1,	4,	1,	1	,1	UNION--二、营业利润（亏损以"－"号填列)
	SELECT	1,	1,	4,	-1,	2	,1	UNION
	SELECT	1,	1,	4,	-1,	3	,1	UNION
	
	SELECT	1,	1,	9,	1,	4	,1	UNION--三、营业利润（亏损以"－"号填列）
	SELECT	1,	1,	9,	1,	5	,1	UNION
	SELECT	1,	1,	9,	-1,	6	,1	UNION
	SELECT	1,	1,	9,	-1,	7	,1	UNION
	SELECT	1,	1,	9,	-1,	8	,1	UNION
	
	SELECT	1,	1,	14,	1,	9	,1	UNION--四、利润总额（亏损总额以"－"号填列）
	SELECT	1,	1,	14,	1,	10	,1	UNION
	SELECT	1,	1,	14,	1,	11	,1	UNION
	SELECT	1,	1,	14,	1,	12	,1	UNION
	SELECT	1,	1,	14,	-1,	13	,1	UNION
	
	SELECT	1,	1,	16,	1,	14	,1	UNION--五、净利润（净亏损以"－"号填列）
	SELECT	1,	1,	16,	-1,	15	,1	UNION
	
	--本年累计金额
	SELECT	1,	1,	4,	1,	1	,2	UNION--二、营业利润（亏损以"－"号填列)
	SELECT	1,	1,	4,	-1,	2	,2	UNION
	SELECT	1,	1,	4,	-1,	3	,2	UNION
	
	SELECT	1,	1,	9,	1,	4	,2	UNION--三、营业利润（亏损以"－"号填列）
	SELECT	1,	1,	9,	1,	5	,2	UNION
	SELECT	1,	1,	9,	-1,	6	,2	UNION
	SELECT	1,	1,	9,	-1,	7	,2	UNION
	SELECT	1,	1,	9,	-1,	8	,2	UNION
	
	SELECT	1,	1,	14,	1,	9	,2	UNION--四、利润总额（亏损总额以"－"号填列）
	SELECT	1,	1,	14,	1,	10	,2	UNION
	SELECT	1,	1,	14,	1,	11	,2	UNION
	SELECT	1,	1,	14,	1,	12	,2	UNION
	SELECT	1,	1,	14,	-1,	13	,2	UNION
	
	SELECT	1,	1,	16,	1,	14	,2	UNION--五、净利润（净亏损以"－"号填列）
	SELECT	1,	1,	16,	-1,	15	,2
	
	--AccountSubId	--2	小企业会计准则科目 
					--1	企业会计制度科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	--本期金额
	SELECT	2,	1,	21,	1,	1	,1	UNION--二、营业利润（亏损以"－"号填列)
	SELECT	2,	1,	21,	-1,	2	,1	UNION
	SELECT	2,	1,	21,	-1,	3	,1	UNION
	SELECT	2,	1,	21,	-1,	11	,1	UNION
	SELECT	2,	1,	21,	-1,	14	,1	UNION
	SELECT	2,	1,	21,	-1,	18	,1	UNION
	SELECT	2,	1,	21,	1,	20	,1	UNION
	
	SELECT	2,	1,	30,	1,	21	,1	UNION--三、利润总额（亏损总额以"－"号填列）
	SELECT	2,	1,	30,	1,	22	,1	UNION
	SELECT	2,	1,	30,	-1,	24	,1	UNION
	
	SELECT	2,	1,	32,	1,	30	,1	UNION--四、净利润（净亏损以"－"号填列）
	SELECT	2,	1,	32,	-1,	31	,1	UNION
	
	--本年累计金额
	SELECT	2,	1,	21,	1,	1	,2	UNION--二、营业利润（亏损以"－"号填列)
	SELECT	2,	1,	21,	-1,	2	,2	UNION
	SELECT	2,	1,	21,	-1,	3	,2	UNION
	SELECT	2,	1,	21,	-1,	11	,2	UNION
	SELECT	2,	1,	21,	-1,	14	,2	UNION
	SELECT	2,	1,	21,	-1,	18	,2	UNION
	SELECT	2,	1,	21,	1,	20	,2	UNION
	
	SELECT	2,	1,	30,	1,	21	,2	UNION--三、利润总额（亏损总额以"－"号填列）
	SELECT	2,	1,	30,	1,	22	,2	UNION
	SELECT	2,	1,	30,	-1,	24	,2	UNION
	
	SELECT	2,	1,	32,	1,	30	,2	UNION--四、净利润（净亏损以"－"号填列）
	SELECT	2,	1,	32,	-1,	31	,2	
	
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialItemParent WHERE ReportType=2)--2：现金流量表
BEGIN
	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	SELECT	28,	2,	5,	1,	2	,1	UNION--流动资产合计
	SELECT	28,	2,	5,	1,	3	,1	UNION
	SELECT	28,	2,	5,	1,	4	,1	UNION
	
	SELECT	28,	2,	10,	1,	6	,1	UNION--经营活动现金流出小计
	SELECT	28,	2,	10,	1,	7	,1	UNION
	SELECT	28,	2,	10,	1,	8	,1	UNION
	SELECT	28,	2,	10,	1,	9	,1	UNION
	
	SELECT	28,	2,	11,	1,	5	,1	UNION--经营活动产生的现金流量净额
	SELECT	28,	2,	11,	-1,	10	,1	UNION
	
	SELECT	28,	2,	18,	1,	13	,1	UNION--投资活动现金流入小计
	SELECT	28,	2,	18,	1,	14	,1	UNION
	SELECT	28,	2,	18,	1,	15	,1	UNION
	SELECT	28,	2,	18,	1,	16	,1	UNION
	SELECT	28,	2,	18,	1,	17	,1	UNION
	
	SELECT	28,	2,	23,	1,	19	,1	UNION--投资活动现金流出小计
	SELECT	28,	2,	23,	1,	20	,1	UNION
	SELECT	28,	2,	23,	1,	21	,1	UNION
	SELECT	28,	2,	23,	1,	22	,1	UNION
	
	SELECT	28,	2,	24,	1,	18	,1	UNION--投资活动产生的现金流量净额
	SELECT	28,	2,	24,	-1,	23	,1	UNION
	
	SELECT	28,	2,	29,	1,	26	,1	UNION--筹资活动现金流入小计
	SELECT	28,	2,	29,	1,	27	,1	UNION
	SELECT	28,	2,	29,	1,	28	,1	UNION
	
	SELECT	28,	2,	33,	1,	30	,1	UNION--筹资活动现金流出小计
	SELECT	28,	2,	33,	1,	31	,1	UNION
	SELECT	28,	2,	33,	1,	32	,1	UNION
	
	SELECT	28,	2,	34,	1,	29	,1	UNION--筹资活动产生的现金流量净额
	SELECT	28,	2,	34,	-1,	33	,1	UNION
	
	SELECT	28,	2,	36,	1,	11	,1	UNION--五、现金及现金等价物净增加额
	SELECT	28,	2,	36,	1,	24	,1	UNION
	SELECT	28,	2,	36,	1,	34	,1	UNION
	SELECT	28,	2,	36,	1,	35	,1	UNION
	
	SELECT	28,	2,	38,	1,	36	,1	UNION--六、期末现金及现金等价物余额
	SELECT	28,	2,	38,	1,	37	,1	UNION

	SELECT	28,	2,	5,	1,	2	,2	UNION--流动资产合计
	SELECT	28,	2,	5,	1,	3	,2	UNION
	SELECT	28,	2,	5,	1,	4	,2	UNION
	
	SELECT	28,	2,	10,	1,	6	,2	UNION--经营活动现金流出小计
	SELECT	28,	2,	10,	1,	7	,2	UNION
	SELECT	28,	2,	10,	1,	8	,2	UNION
	SELECT	28,	2,	10,	1,	9	,2	UNION
	
	SELECT	28,	2,	11,	1,	5	,2	UNION--经营活动产生的现金流量净额
	SELECT	28,	2,	11,	-1,	10	,2	UNION
	
	SELECT	28,	2,	18,	1,	13	,2	UNION--投资活动现金流入小计
	SELECT	28,	2,	18,	1,	14	,2	UNION
	SELECT	28,	2,	18,	1,	15	,2	UNION
	SELECT	28,	2,	18,	1,	16	,2	UNION
	SELECT	28,	2,	18,	1,	17	,2	UNION
	
	SELECT	28,	2,	23,	1,	19	,2	UNION--投资活动现金流出小计
	SELECT	28,	2,	23,	1,	20	,2	UNION
	SELECT	28,	2,	23,	1,	21	,2	UNION
	SELECT	28,	2,	23,	1,	22	,2	UNION
	
	SELECT	28,	2,	24,	1,	18	,2	UNION--投资活动产生的现金流量净额
	SELECT	28,	2,	24,	-1,	23	,2	UNION
	
	SELECT	28,	2,	29,	1,	26	,2	UNION--筹资活动现金流入小计
	SELECT	28,	2,	29,	1,	27	,2	UNION
	SELECT	28,	2,	29,	1,	28	,2	UNION
	
	SELECT	28,	2,	33,	1,	30	,2	UNION--筹资活动现金流出小计
	SELECT	28,	2,	33,	1,	31	,2	UNION
	SELECT	28,	2,	33,	1,	32	,2	UNION
	
	SELECT	28,	2,	34,	1,	29	,2	UNION--筹资活动产生的现金流量净额
	SELECT	28,	2,	34,	-1,	33	,2	UNION
	
	SELECT	28,	2,	36,	1,	11	,2	UNION--五、现金及现金等价物净增加额
	SELECT	28,	2,	36,	1,	24	,2	UNION
	SELECT	28,	2,	36,	1,	34	,2	UNION
	SELECT	28,	2,	36,	1,	35	,2	UNION
	
	SELECT	28,	2,	38,	1,	36	,2	UNION--六、期末现金及现金等价物余额
	SELECT	28,	2,	38,	1,	37	,2	
	
	--AccountSubId	--1	企业会计制度科目 
					--28新会计准则科目
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	SELECT	1,	2,	5,	1,	2	,1	UNION--流动资产合计
	SELECT	1,	2,	5,	1,	3	,1	UNION
	SELECT	1,	2,	5,	1,	4	,1	UNION
	
	SELECT	1,	2,	10,	1,	6	,1	UNION--经营活动现金流出小计
	SELECT	1,	2,	10,	1,	7	,1	UNION
	SELECT	1,	2,	10,	1,	8	,1	UNION
	SELECT	1,	2,	10,	1,	9	,1	UNION
	
	SELECT	1,	2,	11,	1,	5	,1	UNION--经营活动产生的现金流量净额
	SELECT	1,	2,	11,	-1,	10	,1	UNION
	
	SELECT	1,	2,	18,	1,	13	,1	UNION--投资活动现金流入小计
	SELECT	1,	2,	18,	1,	14	,1	UNION
	SELECT	1,	2,	18,	1,	15	,1	UNION
	SELECT	1,	2,	18,	1,	16	,1	UNION
	SELECT	1,	2,	18,	1,	17	,1	UNION
	
	SELECT	1,	2,	23,	1,	19	,1	UNION--投资活动现金流出小计
	SELECT	1,	2,	23,	1,	20	,1	UNION
	SELECT	1,	2,	23,	1,	21	,1	UNION
	SELECT	1,	2,	23,	1,	22	,1	UNION
	
	SELECT	1,	2,	24,	1,	18	,1	UNION--投资活动产生的现金流量净额
	SELECT	1,	2,	24,	-1,	23	,1	UNION
	
	SELECT	1,	2,	29,	1,	26	,1	UNION--筹资活动现金流入小计
	SELECT	1,	2,	29,	1,	27	,1	UNION
	SELECT	1,	2,	29,	1,	28	,1	UNION
	
	SELECT	1,	2,	33,	1,	30	,1	UNION--筹资活动现金流出小计
	SELECT	1,	2,	33,	1,	31	,1	UNION
	SELECT	1,	2,	33,	1,	32	,1	UNION
	
	SELECT	1,	2,	34,	1,	29	,1	UNION--筹资活动产生的现金流量净额
	SELECT	1,	2,	34,	-1,	33	,1	UNION
	
	SELECT	1,	2,	36,	1,	11	,1	UNION--五、现金及现金等价物净增加额
	SELECT	1,	2,	36,	1,	24	,1	UNION
	SELECT	1,	2,	36,	1,	34	,1	UNION
	SELECT	1,	2,	36,	1,	35	,1	UNION
	
	SELECT	1,	2,	38,	1,	36	,1	UNION--六、期末现金及现金等价物余额
	SELECT	1,	2,	38,	1,	37	,1	UNION

	SELECT	1,	2,	5,	1,	2	,2	UNION--流动资产合计
	SELECT	1,	2,	5,	1,	3	,2	UNION
	SELECT	1,	2,	5,	1,	4	,2	UNION
	
	SELECT	1,	2,	10,	1,	6	,2	UNION--经营活动现金流出小计
	SELECT	1,	2,	10,	1,	7	,2	UNION
	SELECT	1,	2,	10,	1,	8	,2	UNION
	SELECT	1,	2,	10,	1,	9	,2	UNION
	
	SELECT	1,	2,	11,	1,	5	,2	UNION--经营活动产生的现金流量净额
	SELECT	1,	2,	11,	-1,	10	,2	UNION
	
	SELECT	1,	2,	18,	1,	13	,2	UNION--投资活动现金流入小计
	SELECT	1,	2,	18,	1,	14	,2	UNION
	SELECT	1,	2,	18,	1,	15	,2	UNION
	SELECT	1,	2,	18,	1,	16	,2	UNION
	SELECT	1,	2,	18,	1,	17	,2	UNION
	
	SELECT	1,	2,	23,	1,	19	,2	UNION--投资活动现金流出小计
	SELECT	1,	2,	23,	1,	20	,2	UNION
	SELECT	1,	2,	23,	1,	21	,2	UNION
	SELECT	1,	2,	23,	1,	22	,2	UNION
	
	SELECT	1,	2,	24,	1,	18	,2	UNION--投资活动产生的现金流量净额
	SELECT	1,	2,	24,	-1,	23	,2	UNION
	
	SELECT	1,	2,	29,	1,	26	,2	UNION--筹资活动现金流入小计
	SELECT	1,	2,	29,	1,	27	,2	UNION
	SELECT	1,	2,	29,	1,	28	,2	UNION
	
	SELECT	1,	2,	33,	1,	30	,2	UNION--筹资活动现金流出小计
	SELECT	1,	2,	33,	1,	31	,2	UNION
	SELECT	1,	2,	33,	1,	32	,2	UNION
	
	SELECT	1,	2,	34,	1,	29	,2	UNION--筹资活动产生的现金流量净额
	SELECT	1,	2,	34,	-1,	33	,2	UNION
	
	SELECT	1,	2,	36,	1,	11	,2	UNION--五、现金及现金等价物净增加额
	SELECT	1,	2,	36,	1,	24	,2	UNION
	SELECT	1,	2,	36,	1,	34	,2	UNION
	SELECT	1,	2,	36,	1,	35	,2	UNION
	
	SELECT	1,	2,	38,	1,	36	,2	UNION--六、期末现金及现金等价物余额
	SELECT	1,	2,	38,	1,	37	,2	

	--AccountSubId	--2	小企业会计准则科目
					--1	企业会计制度科目 
					-- 28新会计准则科目
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	SELECT	2,	2,	5,	1,	2	,1	UNION--流动资产合计
	SELECT	2,	2,	5,	1,	3	,1	UNION
	SELECT	2,	2,	5,	1,	4	,1	UNION
	
	SELECT	2,	2,	10,	1,	6	,1	UNION--经营活动现金流出小计
	SELECT	2,	2,	10,	1,	7	,1	UNION
	SELECT	2,	2,	10,	1,	8	,1	UNION
	SELECT	2,	2,	10,	1,	9	,1	UNION
	
	SELECT	2,	2,	11,	1,	5	,1	UNION--经营活动产生的现金流量净额
	SELECT	2,	2,	11,	-1,	10	,1	UNION
	
	SELECT	2,	2,	18,	1,	13	,1	UNION--投资活动现金流入小计
	SELECT	2,	2,	18,	1,	14	,1	UNION
	SELECT	2,	2,	18,	1,	15	,1	UNION
	SELECT	2,	2,	18,	1,	16	,1	UNION
	SELECT	2,	2,	18,	1,	17	,1	UNION
	
	SELECT	2,	2,	23,	1,	19	,1	UNION--投资活动现金流出小计
	SELECT	2,	2,	23,	1,	20	,1	UNION
	SELECT	2,	2,	23,	1,	21	,1	UNION
	SELECT	2,	2,	23,	1,	22	,1	UNION
	
	SELECT	2,	2,	24,	1,	18	,1	UNION--投资活动产生的现金流量净额
	SELECT	2,	2,	24,	-1,	23	,1	UNION
	
	SELECT	2,	2,	29,	1,	26	,1	UNION--筹资活动现金流入小计
	SELECT	2,	2,	29,	1,	27	,1	UNION
	SELECT	2,	2,	29,	1,	28	,1	UNION
	
	SELECT	2,	2,	33,	1,	30	,1	UNION--筹资活动现金流出小计
	SELECT	2,	2,	33,	1,	31	,1	UNION
	SELECT	2,	2,	33,	1,	32	,1	UNION
	
	SELECT	2,	2,	34,	1,	29	,1	UNION--筹资活动产生的现金流量净额
	SELECT	2,	2,	34,	-1,	33	,1	UNION
	
	SELECT	2,	2,	36,	1,	11	,1	UNION--五、现金及现金等价物净增加额
	SELECT	2,	2,	36,	1,	24	,1	UNION
	SELECT	2,	2,	36,	1,	34	,1	UNION
	SELECT	2,	2,	36,	1,	35	,1	UNION
	
	SELECT	2,	2,	38,	1,	36	,1	UNION--六、期末现金及现金等价物余额
	SELECT	2,	2,	38,	1,	37	,1	UNION

	SELECT	2,	2,	5,	1,	2	,2	UNION--流动资产合计
	SELECT	2,	2,	5,	1,	3	,2	UNION
	SELECT	2,	2,	5,	1,	4	,2	UNION
	
	SELECT	2,	2,	10,	1,	6	,2	UNION--经营活动现金流出小计
	SELECT	2,	2,	10,	1,	7	,2	UNION
	SELECT	2,	2,	10,	1,	8	,2	UNION
	SELECT	2,	2,	10,	1,	9	,2	UNION
	
	SELECT	2,	2,	11,	1,	5	,2	UNION--经营活动产生的现金流量净额
	SELECT	2,	2,	11,	-1,	10	,2	UNION
	
	SELECT	2,	2,	18,	1,	13	,2	UNION--投资活动现金流入小计
	SELECT	2,	2,	18,	1,	14	,2	UNION
	SELECT	2,	2,	18,	1,	15	,2	UNION
	SELECT	2,	2,	18,	1,	16	,2	UNION
	SELECT	2,	2,	18,	1,	17	,2	UNION
	
	SELECT	2,	2,	23,	1,	19	,2	UNION--投资活动现金流出小计
	SELECT	2,	2,	23,	1,	20	,2	UNION
	SELECT	2,	2,	23,	1,	21	,2	UNION
	SELECT	2,	2,	23,	1,	22	,2	UNION
	
	SELECT	2,	2,	24,	1,	18	,2	UNION--投资活动产生的现金流量净额
	SELECT	2,	2,	24,	-1,	23	,2	UNION
	
	SELECT	2,	2,	29,	1,	26	,2	UNION--筹资活动现金流入小计
	SELECT	2,	2,	29,	1,	27	,2	UNION
	SELECT	2,	2,	29,	1,	28	,2	UNION
	
	SELECT	2,	2,	33,	1,	30	,2	UNION--筹资活动现金流出小计
	SELECT	2,	2,	33,	1,	31	,2	UNION
	SELECT	2,	2,	33,	1,	32	,2	UNION
	
	SELECT	2,	2,	34,	1,	29	,2	UNION--筹资活动产生的现金流量净额
	SELECT	2,	2,	34,	-1,	33	,2	UNION
	
	SELECT	2,	2,	36,	1,	11	,2	UNION--五、现金及现金等价物净增加额
	SELECT	2,	2,	36,	1,	24	,2	UNION
	SELECT	2,	2,	36,	1,	34	,2	UNION
	SELECT	2,	2,	36,	1,	35	,2	UNION
	
	SELECT	2,	2,	38,	1,	36	,2	UNION--六、期末现金及现金等价物余额
	SELECT	2,	2,	38,	1,	37	,2	
	
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM ThreeFinancialItemParent WHERE ReportType=3)--3：资产负债表
BEGIN
	--AccountSubId	--28新会计准则科目
					--1	企业会计制度科目 
					--2	小企业会计准则科目 
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	SELECT	28,	3,	16,	1,	3	,1	UNION--流动资产合计
	SELECT	28,	3,	16,	1,	4	,1	UNION
	SELECT	28,	3,	16,	1,	5	,1	UNION
	SELECT	28,	3,	16,	1,	6	,1	UNION
	SELECT	28,	3,	16,	1,	7	,1	UNION
	SELECT	28,	3,	16,	1,	8	,1	UNION
	SELECT	28,	3,	16,	1,	9	,1	UNION
	SELECT	28,	3,	16,	1,	10	,1	UNION
	SELECT	28,	3,	16,	1,	11	,1	UNION
	SELECT	28,	3,	16,	1,	13	,1	UNION
	SELECT	28,	3,	16,	1,	14	,1	UNION
	SELECT	28,	3,	16,	1,	15	,1	UNION
	
	SELECT	28,	3,	35,	1,	18	,1	UNION--非流动资产合计
	SELECT	28,	3,	35,	1,	19	,1	UNION
	SELECT	28,	3,	35,	1,	20	,1	UNION
	SELECT	28,	3,	35,	1,	21	,1	UNION
	SELECT	28,	3,	35,	1,	22	,1	UNION
	SELECT	28,	3,	35,	1,	23	,1	UNION
	SELECT	28,	3,	35,	1,	24	,1	UNION
	SELECT	28,	3,	35,	1,	25	,1	UNION
	SELECT	28,	3,	35,	1,	26	,1	UNION
	SELECT	28,	3,	35,	1,	27	,1	UNION
	SELECT	28,	3,	35,	1,	28	,1	UNION
	SELECT	28,	3,	35,	1,	29	,1	UNION
	SELECT	28,	3,	35,	1,	30	,1	UNION
	SELECT	28,	3,	35,	1,	31	,1	UNION
	SELECT	28,	3,	35,	1,	32	,1	UNION
	SELECT	28,	3,	35,	1,	33	,1	UNION
	SELECT	28,	3,	35,	1,	34	,1	UNION
	
	SELECT	28,	3,	36,	1,	16	,1	UNION--资产总计
	SELECT	28,	3,	36,	1,	35	,1	UNION
	
	SELECT	28,	3,	53,	1,	39	,1	UNION--流动负债合计
	SELECT	28,	3,	53,	1,	40	,1	UNION
	SELECT	28,	3,	53,	1,	41	,1	UNION
	SELECT	28,	3,	53,	1,	42	,1	UNION
	SELECT	28,	3,	53,	1,	43	,1	UNION
	SELECT	28,	3,	53,	1,	44	,1	UNION
	SELECT	28,	3,	53,	1,	45	,1	UNION
	SELECT	28,	3,	53,	1,	46	,1	UNION
	SELECT	28,	3,	53,	1,	47	,1	UNION
	SELECT	28,	3,	53,	1,	48	,1	UNION
	SELECT	28,	3,	53,	1,	49	,1	UNION
	SELECT	28,	3,	53,	1,	50	,1	UNION
	SELECT	28,	3,	53,	1,	51	,1	UNION
	SELECT	28,	3,	53,	1,	52	,1	UNION
	
	SELECT	28,	3,	61,	1,	55	,1	UNION--非流动负债合计
	SELECT	28,	3,	61,	1,	56	,1	UNION
	SELECT	28,	3,	61,	1,	57	,1	UNION
	SELECT	28,	3,	61,	1,	58	,1	UNION
	SELECT	28,	3,	61,	1,	59	,1	UNION
	SELECT	28,	3,	61,	1,	60	,1	UNION
	
	SELECT	28,	3,	62,	1,	53	,1	UNION--负债合计
	SELECT	28,	3,	62,	1,	61	,1	UNION
	
	SELECT	28,	3,	69,	1,	64	,1	UNION--所有者权益（或股东权益）合计
	SELECT	28,	3,	69,	1,	65	,1	UNION
	SELECT	28,	3,	69,	-1,	66	,1	UNION
	SELECT	28,	3,	69,	1,	67	,1	UNION
	SELECT	28,	3,	69,	1,	68	,1	UNION
	
	SELECT	28,	3,	70,	1,	62	,1	UNION--负债和所有者权益（或股东权益）总计
	SELECT	28,	3,	70,	1,	69	,1	UNION
	
	SELECT	28,	3,	16,	1,	3	,2	UNION--流动资产合计
	SELECT	28,	3,	16,	1,	4	,2	UNION
	SELECT	28,	3,	16,	1,	5	,2	UNION
	SELECT	28,	3,	16,	1,	6	,2	UNION
	SELECT	28,	3,	16,	1,	7	,2	UNION
	SELECT	28,	3,	16,	1,	8	,2	UNION
	SELECT	28,	3,	16,	1,	9	,2	UNION
	SELECT	28,	3,	16,	1,	10	,2	UNION
	SELECT	28,	3,	16,	1,	11	,2	UNION
	SELECT	28,	3,	16,	1,	13	,2	UNION
	SELECT	28,	3,	16,	1,	14	,2	UNION
	SELECT	28,	3,	16,	1,	15	,2	UNION
	
	SELECT	28,	3,	35,	1,	18	,2	UNION--非流动资产合计
	SELECT	28,	3,	35,	1,	19	,2	UNION
	SELECT	28,	3,	35,	1,	20	,2	UNION
	SELECT	28,	3,	35,	1,	21	,2	UNION
	SELECT	28,	3,	35,	1,	22	,2	UNION
	SELECT	28,	3,	35,	1,	23	,2	UNION
	SELECT	28,	3,	35,	1,	24	,2	UNION
	SELECT	28,	3,	35,	1,	25	,2	UNION
	SELECT	28,	3,	35,	1,	26	,2	UNION
	SELECT	28,	3,	35,	1,	27	,2	UNION
	SELECT	28,	3,	35,	1,	28	,2	UNION
	SELECT	28,	3,	35,	1,	29	,2	UNION
	SELECT	28,	3,	35,	1,	30	,2	UNION
	SELECT	28,	3,	35,	1,	31	,2	UNION
	SELECT	28,	3,	35,	1,	32	,2	UNION
	SELECT	28,	3,	35,	1,	33	,2	UNION
	SELECT	28,	3,	35,	1,	34	,2	UNION
	
	SELECT	28,	3,	36,	1,	16	,2	UNION--资产总计
	SELECT	28,	3,	36,	1,	35	,2	UNION
	
	SELECT	28,	3,	53,	1,	39	,2	UNION--流动负债合计
	SELECT	28,	3,	53,	1,	40	,2	UNION
	SELECT	28,	3,	53,	1,	41	,2	UNION
	SELECT	28,	3,	53,	1,	42	,2	UNION
	SELECT	28,	3,	53,	1,	43	,2	UNION
	SELECT	28,	3,	53,	1,	44	,2	UNION
	SELECT	28,	3,	53,	1,	45	,2	UNION
	SELECT	28,	3,	53,	1,	46	,2	UNION
	SELECT	28,	3,	53,	1,	47	,2	UNION
	SELECT	28,	3,	53,	1,	48	,2	UNION
	SELECT	28,	3,	53,	1,	49	,2	UNION
	SELECT	28,	3,	53,	1,	50	,2	UNION
	SELECT	28,	3,	53,	1,	51	,2	UNION
	SELECT	28,	3,	53,	1,	52	,2	UNION
	
	SELECT	28,	3,	61,	1,	55	,2	UNION--非流动负债合计
	SELECT	28,	3,	61,	1,	56	,2	UNION
	SELECT	28,	3,	61,	1,	57	,2	UNION
	SELECT	28,	3,	61,	1,	58	,2	UNION
	SELECT	28,	3,	61,	1,	59	,2	UNION
	SELECT	28,	3,	61,	1,	60	,2	UNION
	
	SELECT	28,	3,	62,	1,	53	,2	UNION--负债合计
	SELECT	28,	3,	62,	1,	61	,2	UNION
	
	SELECT	28,	3,	69,	1,	64	,2	UNION--所有者权益（或股东权益）合计
	SELECT	28,	3,	69,	1,	65	,2	UNION
	SELECT	28,	3,	69,	-1,	66	,2	UNION
	SELECT	28,	3,	69,	1,	67	,2	UNION
	SELECT	28,	3,	69,	1,	68	,2	UNION
	
	SELECT	28,	3,	70,	1,	62	,2	UNION--负债和所有者权益（或股东权益）总计
	SELECT	28,	3,	70,	1,	69	,2	
	

	--AccountSubId	--1	企业会计制度科目 
					--2	小企业会计准则科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	SELECT	1,	3,	16,	1,	3	,1	UNION--流动资产合计
	SELECT	1,	3,	16,	1,	4	,1	UNION
	SELECT	1,	3,	16,	1,	5	,1	UNION
	SELECT	1,	3,	16,	1,	6	,1	UNION
	SELECT	1,	3,	16,	1,	7	,1	UNION
	SELECT	1,	3,	16,	1,	8	,1	UNION
	SELECT	1,	3,	16,	1,	9	,1	UNION
	SELECT	1,	3,	16,	1,	10	,1	UNION
	SELECT	1,	3,	16,	1,	11	,1	UNION
	SELECT	1,	3,	16,	1,	12	,1	UNION
	SELECT	1,	3,	16,	1,	13	,1	UNION
	SELECT	1,	3,	16,	1,	14	,1	UNION
	SELECT	1,	3,	16,	1,	15	,1	UNION
	
	SELECT	1,	3,	20,	1,	18	,1	UNION--长期投资合计
	SELECT	1,	3,	20,	1,	19	,1	UNION
	
	SELECT	1,	3,	24,	1,	22	,1	UNION--固定资产净值
	SELECT	1,	3,	24,	-1,	23	,1	UNION
	
	SELECT	1,	3,	26,	1,	24	,1	UNION--固定资产净额
	SELECT	1,	3,	26,	-1,	25	,1	UNION
	
	SELECT	1,	3,	30,	1,	26	,1	UNION--固定资产合计
	SELECT	1,	3,	30,	1,	27	,1	UNION
	SELECT	1,	3,	30,	1,	28	,1	UNION
	SELECT	1,	3,	30,	1,	29	,1	UNION
	
	SELECT	1,	3,	35,	1,	32	,1	UNION--无形及其他资产合计
	SELECT	1,	3,	35,	1,	33	,1	UNION
	SELECT	1,	3,	35,	1,	34	,1	UNION
	
	SELECT	1,	3,	38,	1,	16	,1	UNION--资产总计
	SELECT	1,	3,	38,	1,	20	,1	UNION
	SELECT	1,	3,	38,	1,	30	,1	UNION
	SELECT	1,	3,	38,	1,	35	,1	UNION
	SELECT	1,	3,	38,	1,	37	,1	UNION
	
	SELECT	1,	3,	55,	1,	41	,1	UNION--流动负债合计
	SELECT	1,	3,	55,	1,	42	,1	UNION
	SELECT	1,	3,	55,	1,	43	,1	UNION
	SELECT	1,	3,	55,	1,	44	,1	UNION
	SELECT	1,	3,	55,	1,	45	,1	UNION
	SELECT	1,	3,	55,	1,	46	,1	UNION
	SELECT	1,	3,	55,	1,	47	,1	UNION
	SELECT	1,	3,	55,	1,	48	,1	UNION
	SELECT	1,	3,	55,	1,	49	,1	UNION
	SELECT	1,	3,	55,	1,	50	,1	UNION
	SELECT	1,	3,	55,	1,	51	,1	UNION
	SELECT	1,	3,	55,	1,	52	,1	UNION
	SELECT	1,	3,	55,	1,	53	,1	UNION
	SELECT	1,	3,	55,	1,	54	,1	UNION
	
	SELECT	1,	3,	62,	1,	57	,1	UNION--长期负债合计
	SELECT	1,	3,	62,	1,	58	,1	UNION
	SELECT	1,	3,	62,	1,	59	,1	UNION
	SELECT	1,	3,	62,	1,	60	,1	UNION
	SELECT	1,	3,	62,	1,	61	,1	UNION
	
	SELECT	1,	3,	65,	1,	55	,1	UNION--负债合计
	SELECT	1,	3,	65,	1,	62	,1	UNION
	SELECT	1,	3,	65,	1,	64 	,1	UNION
	
	SELECT	1,	3,	69,	1,	67	,1	UNION--实收资本（或股本）净额
	SELECT	1,	3,	69,	-1,	68	,1	UNION
	
	SELECT	1,	3,	74,	1,	69	,1	UNION--所有者权益（股东权益）合计
	SELECT	1,	3,	74,	1,	70	,1	UNION
	SELECT	1,	3,	74,	1,	71	,1	UNION
	SELECT	1,	3,	74,	1,	73	,1	UNION
	
	SELECT	1,	3,	75,	1,	65	,1	UNION--负债及权益（股东权益）合计
	SELECT	1,	3,	75,	1,	74	,1	UNION
	
	SELECT	1,	3,	16,	1,	3	,2	UNION--流动资产合计
	SELECT	1,	3,	16,	1,	4	,2	UNION
	SELECT	1,	3,	16,	1,	5	,2	UNION
	SELECT	1,	3,	16,	1,	6	,2	UNION
	SELECT	1,	3,	16,	1,	7	,2	UNION
	SELECT	1,	3,	16,	1,	8	,2	UNION
	SELECT	1,	3,	16,	1,	9	,2	UNION
	SELECT	1,	3,	16,	1,	10	,2	UNION
	SELECT	1,	3,	16,	1,	11	,2	UNION
	SELECT	1,	3,	16,	1,	12	,2	UNION
	SELECT	1,	3,	16,	1,	13	,2	UNION
	SELECT	1,	3,	16,	1,	14	,2	UNION
	SELECT	1,	3,	16,	1,	15	,2	UNION
	
	SELECT	1,	3,	20,	1,	18	,2	UNION--长期投资合计
	SELECT	1,	3,	20,	1,	19	,2	UNION
	
	SELECT	1,	3,	24,	1,	22	,2	UNION--固定资产净值
	SELECT	1,	3,	24,	-1,	23	,2	UNION
	
	SELECT	1,	3,	26,	1,	24	,2	UNION--固定资产净额
	SELECT	1,	3,	26,	-1,	25	,2	UNION
	
	SELECT	1,	3,	30,	1,	26	,2	UNION--固定资产合计
	SELECT	1,	3,	30,	1,	27	,2	UNION
	SELECT	1,	3,	30,	1,	28	,2	UNION
	SELECT	1,	3,	30,	1,	29	,2	UNION
	
	SELECT	1,	3,	35,	1,	32	,2	UNION--无形及其他资产合计
	SELECT	1,	3,	35,	1,	33	,2	UNION
	SELECT	1,	3,	35,	1,	34	,2	UNION
	
	SELECT	1,	3,	38,	1,	16	,2	UNION--资产总计
	SELECT	1,	3,	38,	1,	20	,2	UNION
	SELECT	1,	3,	38,	1,	30	,2	UNION
	SELECT	1,	3,	38,	1,	35	,2	UNION
	SELECT	1,	3,	38,	1,	37	,2	UNION
	
	SELECT	1,	3,	55,	1,	41	,2	UNION--流动负债合计
	SELECT	1,	3,	55,	1,	42	,2	UNION
	SELECT	1,	3,	55,	1,	43	,2	UNION
	SELECT	1,	3,	55,	1,	44	,2	UNION
	SELECT	1,	3,	55,	1,	45	,2	UNION
	SELECT	1,	3,	55,	1,	46	,2	UNION
	SELECT	1,	3,	55,	1,	47	,2	UNION
	SELECT	1,	3,	55,	1,	48	,2	UNION
	SELECT	1,	3,	55,	1,	49	,2	UNION
	SELECT	1,	3,	55,	1,	50	,2	UNION
	SELECT	1,	3,	55,	1,	51	,2	UNION
	SELECT	1,	3,	55,	1,	52	,2	UNION
	SELECT	1,	3,	55,	1,	53	,2	UNION
	SELECT	1,	3,	55,	1,	54	,2	UNION
	
	SELECT	1,	3,	62,	1,	57	,2	UNION--长期负债合计
	SELECT	1,	3,	62,	1,	58	,2	UNION
	SELECT	1,	3,	62,	1,	59	,2	UNION
	SELECT	1,	3,	62,	1,	60	,2	UNION
	SELECT	1,	3,	62,	1,	61	,2	UNION
	
	SELECT	1,	3,	65,	1,	55	,2	UNION--负债合计
	SELECT	1,	3,	65,	1,	62	,2	UNION
	SELECT	1,	3,	65,	1,	64 	,2	UNION
	
	SELECT	1,	3,	69,	1,	67	,2	UNION--实收资本（或股本）净额
	SELECT	1,	3,	69,	-1,	68	,2	UNION
	
	SELECT	1,	3,	74,	1,	69	,2	UNION--所有者权益（股东权益）合计
	SELECT	1,	3,	74,	1,	70	,2	UNION
	SELECT	1,	3,	74,	1,	71	,2	UNION
	SELECT	1,	3,	74,	1,	73	,2	UNION
	
	SELECT	1,	3,	75,	1,	65	,2	UNION--负债及权益（股东权益）合计
	SELECT	1,	3,	75,	1,	74	,2
	
	--AccountSubId	--2	小企业会计准则科目
					--1	企业会计制度科目 
					--28新会计准则科目
	INSERT INTO ThreeFinancialItemParent(AccountSubId,ReportType,ParItemID,[Sign],SonItemID,FormulaType)
	SELECT	2,	3,	17,	1,	3	,1	UNION--流动资产合计
	SELECT	2,	3,	17,	1,	4	,1	UNION
	SELECT	2,	3,	17,	1,	5	,1	UNION
	SELECT	2,	3,	17,	1,	6	,1	UNION
	SELECT	2,	3,	17,	1,	7	,1	UNION
	SELECT	2,	3,	17,	1,	8	,1	UNION
	SELECT	2,	3,	17,	1,	9	,1	UNION
	SELECT	2,	3,	17,	1,	10	,1	UNION
	SELECT	2,	3,	17,	1,	11	,1	UNION
	SELECT	2,	3,	17,	1,	16	,1	UNION
	
	SELECT	2,	3,	32,	1,	19	,1	UNION--非流动资产合计
	SELECT	2,	3,	32,	1,	20	,1	UNION
	SELECT	2,	3,	32,	1,	23	,1	UNION
	SELECT	2,	3,	32,	1,	24	,1	UNION
	SELECT	2,	3,	32,	1,	25	,1	UNION
	SELECT	2,	3,	32,	1,	26	,1	UNION
	SELECT	2,	3,	32,	1,	27	,1	UNION
	SELECT	2,	3,	32,	1,	28	,1	UNION
	SELECT	2,	3,	32,	1,	29	,1	UNION
	SELECT	2,	3,	32,	1,	30	,1	UNION
	SELECT	2,	3,	32,	1,	31	,1	UNION
	
	SELECT	2,	3,	33,	1,	17	,1	UNION--资产总计
	SELECT	2,	3,	33,	1,	32	,1	UNION
	
	SELECT	2,	3,	46,	1,	36	,1	UNION--流动负债合计
	SELECT	2,	3,	46,	1,	37	,1	UNION
	SELECT	2,	3,	46,	1,	38	,1	UNION
	SELECT	2,	3,	46,	1,	39	,1	UNION
	SELECT	2,	3,	46,	1,	40	,1	UNION
	SELECT	2,	3,	46,	1,	41	,1	UNION
	SELECT	2,	3,	46,	1,	42	,1	UNION
	SELECT	2,	3,	46,	1,	43	,1	UNION
	SELECT	2,	3,	46,	1,	44	,1	UNION
	SELECT	2,	3,	46,	1,	45	,1	UNION
	
	SELECT	2,	3,	52,	1,	48	,1	UNION--非流动负债合计
	SELECT	2,	3,	52,	1,	49	,1	UNION
	SELECT	2,	3,	52,	1,	50	,1	UNION
	SELECT	2,	3,	52,	1,	51	,1	UNION
	
	SELECT	2,	3,	53,	1,	46	,1	UNION--负债合计
	SELECT	2,	3,	53,	1,	52	,1	UNION
	
	SELECT	2,	3,	59,	1,	55	,1	UNION--所有者权益（或股东权益）合计
	SELECT	2,	3,	59,	1,	56	,1	UNION
	SELECT	2,	3,	59,	1,	57	,1	UNION
	SELECT	2,	3,	59,	1,	58	,1	UNION
	
	SELECT	2,	3,	60,	1,	53	,1	UNION--负债和所有者权益（或股东权益）总计
	SELECT	2,	3,	60,	1,	59	,1	UNION

	SELECT	2,	3,	17,	1,	3	,2	UNION--流动资产合计
	SELECT	2,	3,	17,	1,	4	,2	UNION
	SELECT	2,	3,	17,	1,	5	,2	UNION
	SELECT	2,	3,	17,	1,	6	,2	UNION
	SELECT	2,	3,	17,	1,	7	,2	UNION
	SELECT	2,	3,	17,	1,	8	,2	UNION
	SELECT	2,	3,	17,	1,	9	,2	UNION
	SELECT	2,	3,	17,	1,	10	,2	UNION
	SELECT	2,	3,	17,	1,	11	,2	UNION
	SELECT	2,	3,	17,	1,	16	,2	UNION
	
	SELECT	2,	3,	32,	1,	19	,2	UNION--非流动资产合计
	SELECT	2,	3,	32,	1,	20	,2	UNION
	SELECT	2,	3,	32,	1,	23	,2	UNION
	SELECT	2,	3,	32,	1,	24	,2	UNION
	SELECT	2,	3,	32,	1,	25	,2	UNION
	SELECT	2,	3,	32,	1,	26	,2	UNION
	SELECT	2,	3,	32,	1,	27	,2	UNION
	SELECT	2,	3,	32,	1,	28	,2	UNION
	SELECT	2,	3,	32,	1,	29	,2	UNION
	SELECT	2,	3,	32,	1,	30	,2	UNION
	SELECT	2,	3,	32,	1,	31	,2	UNION
	
	SELECT	2,	3,	33,	1,	17	,2	UNION--资产总计
	SELECT	2,	3,	33,	1,	32	,2	UNION
	
	SELECT	2,	3,	46,	1,	36	,2	UNION--流动负债合计
	SELECT	2,	3,	46,	1,	37	,2	UNION
	SELECT	2,	3,	46,	1,	38	,2	UNION
	SELECT	2,	3,	46,	1,	39	,2	UNION
	SELECT	2,	3,	46,	1,	40	,2	UNION
	SELECT	2,	3,	46,	1,	41	,2	UNION
	SELECT	2,	3,	46,	1,	42	,2	UNION
	SELECT	2,	3,	46,	1,	43	,2	UNION
	SELECT	2,	3,	46,	1,	44	,2	UNION
	SELECT	2,	3,	46,	1,	45	,2	UNION
	
	SELECT	2,	3,	52,	1,	48	,2	UNION--非流动负债合计
	SELECT	2,	3,	52,	1,	49	,2	UNION
	SELECT	2,	3,	52,	1,	50	,2	UNION
	SELECT	2,	3,	52,	1,	51	,2	UNION
	
	SELECT	2,	3,	53,	1,	46	,2	UNION--负债合计
	SELECT	2,	3,	53,	1,	52	,2	UNION
	
	SELECT	2,	3,	59,	1,	55	,2	UNION--所有者权益（或股东权益）合计
	SELECT	2,	3,	59,	1,	56	,2	UNION
	SELECT	2,	3,	59,	1,	57	,2	UNION
	SELECT	2,	3,	59,	1,	58	,2	UNION
	
	SELECT	2,	3,	60,	1,	53	,2	UNION--负债和所有者权益（或股东权益）总计
	SELECT	2,	3,	60,	1,	59	,2  
	
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



--具体分支机构固化报表项目表 合计行父节点
IF NOT EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id = object_id('ThreeFinancialItemParent_Stype') AND type = 'U')
BEGIN
	CREATE TABLE ThreeFinancialItemParent_Stype (
		nId						INT	IDENTITY(1,1),--自增长列
		ReportType				INT,				--1:利润表 2：现金流量表 3：资产负债表
		STypeID					VARCHAR(50),		--分支机构ID 
		ParItemID				INT	NOT NULL DEFAULT(0),--父类项目ID
		[Sign]					INT NOT NULL DEFAULT(1),--公式符号 1：正 -1负
		SonItemID				INT	NOT NULL DEFAULT(0),--自己项目ID
		FormulaType				INT,--公式类型比如利润表1：本期金额 2本年累计金额
		UpdateTime				DATETIME,--最后一次修改时间
		OperatorId				VARCHAR(50)--操作员
		
	)
END
GO  
------------------------------------------表修改区域开始-------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='ThreeFinancialItemParent_Stype' AND a.Name='ItemFullName'
--)
--BEGIN
--	ALTER TABLE ThreeFinancialItemParent_Stype 
--		ADD ItemFullName VARCHAR(400) NULL DEFAULT('')
--END

--GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ThreeFinancialItemParent_Stype') AND name = 'CIX_ThreeFinancialItemParent_Stype_Nid')
	CREATE CLUSTERED INDEX CIX_ThreeFinancialItemParent_Stype_Nid ON ThreeFinancialItemParent_Stype(Nid) 

------------------------------------------创建索引区域结束-----------------------------------------------



/****** 对象:  Table [dbo].[tmpGain]    脚本日期: 05/05/2010 14:49:40 ******/
SET ANSI_NULLS OFF

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[tmpGain]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[tmpGain](
		[TypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BqTotal] [numeric](38, 4) NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='tmpGain' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE tmpGain ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE tmpGain SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------


/****** Object:  Index [IX_tmpGain]    Script Date: 08/09/2017 09:55:31 ******/
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[tmpGain]') AND name = N'IX_tmpGain')
DROP INDEX [IX_tmpGain] ON [dbo].[tmpGain] WITH ( ONLINE = OFF )
GO


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------


/****** Object:  Index [IX_tmpGain]    Script Date: 08/09/2017 09:54:31 ******/
CREATE CLUSTERED INDEX [IX_tmpGain] ON [dbo].[tmpGain] 
(
	[TypeID] ASC,
	[STypeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='tmpGain' AND a.Name='BqTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE tmpGain 
	ALTER COLUMN BqTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ToolBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ToolBill](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[PTypeID] VARCHAR(50) NULL DEFAULT(''),
		[Qty] NUMERIC(18,4) NULL DEFAULT(0),
		[Price] NUMERIC(18,4) NULL DEFAULT(0),		
		[ValidDate] VARCHAR(50) NULL DEFAULT(''),
		[Comment] VARCHAR(250) NULL DEFAULT(''),
		[IsUnit2]  INT NULL DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select * from syscolumns where id = object_id(N'[dbo].[ToolBill]') and  name = 'Comment' and length=500)
BEGIN
     ALTER TABLE ToolBill
	    ALTER COLUMN Comment varchar(500) 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ToolBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ToolBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ToolBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE ToolBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ToolIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ToolIndex](
		[BillNumberId] NUMERIC(18,0) IDENTITY(1,1) NOT NULL,		
		[BillDate] DATETIME NULL,
		[BillCode] VARCHAR(200) NULL DEFAULT(''),
		[BillType] NUMERIC(4,0) NULL,
		[ETypeID] VARCHAR(50) NULL DEFAULT(''),
		[STypeID] VARCHAR(50) NULL DEFAULT(''),
		[DTypeID] VARCHAR(50) NULL DEFAULT(''),
		[Checke] VARCHAR(50) NULL DEFAULT(''),
		[Explain] VARCHAR(256) NULL DEFAULT(''),
		[Comment] VARCHAR(256) NULL DEFAULT(''),
		[InOutType] VARCHAR(200) NULL DEFAULT('')	---出,入库类型,0-采购,1-还回,2-借出,3-报废,4-丢失
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('TP_SA_Buy')
            and   type = 'U')
BEGIN
	CREATE TABLE TP_SA_Buy
	(
		billdate    DATETIME,
		Qty			numeric(18, 4),
		zeroPriceqty		numeric(18, 4),
		Total		numeric(18, 2),
		TaxTotal	numeric(18, 2),
		typeid		VARCHAR(50),
		ProtectTotal  numeric(18, 2),
		Advantagetotal NUMERIC(18,2)
	)
END
GO
-----------------------------------------------------修改表-----------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_Buy]') and name = 'xid' )
BEGIN
	ALTER TABLE dbo.TP_SA_Buy ADD
		xid INT
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_Buy]') and name = 'usercode' )
BEGIN
	ALTER TABLE dbo.TP_SA_Buy ADD
		usercode VARCHAR(200)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_Buy]') and name = 'fullname' )
BEGIN
	ALTER TABLE dbo.TP_SA_Buy ADD
		fullname VARCHAR(200)
END
GO
if  exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_Buy]') and name = 'billdate' )
BEGIN
	ALTER TABLE dbo.TP_SA_Buy DROP COLUMN
		 billdate
END
GO
if  exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_Buy]') and name = 'timeType' )
BEGIN
	ALTER TABLE dbo.TP_SA_Buy DROP COLUMN
		timeType 
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_Buy]') and name = 'timeType' )
BEGIN
	ALTER TABLE dbo.TP_SA_Buy ADD
		timeType VARCHAR(20)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

-----------------------------------------------------修改数据-----------------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_Buy' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_Buy 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_Buy' AND a.Name='zeroPriceqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_Buy 
	ALTER COLUMN zeroPriceqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_Buy' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_Buy 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_Buy' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_Buy 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_Buy' AND a.Name='ProtectTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_Buy 
	ALTER COLUMN ProtectTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_Buy' AND a.Name='Advantagetotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_Buy 
	ALTER COLUMN Advantagetotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1 from  sysobjects where  id = object_id('TP_SA_GoodsSellStat') and type = 'U')
BEGIN
	CREATE TABLE TP_SA_GoodsSellStat
	(
		TypeID varchar(200),
		usercode varchar(200),
		fullname varchar(200),
		basicunit varchar(200),
		isgift  INT ,
		Qty numeric(18, 4),
		Total numeric(18, 4),
		SaleTotal numeric(18, 4),
		TaxTotal numeric(18, 4),
		CostTotal numeric(18, 4),
		ProtectTotal numeric(18, 4),
		Advantagetotal numeric(18, 4),
		ShareFee numeric(18, 4),
		BillDate datetime,
		xid INT,
		timeType VARCHAR(20)
	
	)
END
GO

-----------------------------------------------------表修改区域开始-----------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_GoodsSellStat]') and name = 'xid' )
BEGIN
	ALTER TABLE dbo.TP_SA_GoodsSellStat ADD
		xid INT
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_GoodsSellStat]') and name = 'timeType' )
BEGIN
	ALTER TABLE dbo.TP_SA_GoodsSellStat ADD
		timeType VARCHAR(20)
END
GO

if  exists (select name from syscolumns where id = object_id(N'[dbo].[TP_SA_GoodsSellStat]') and name = 'timeType' )
BEGIN
	ALTER TABLE dbo.TP_SA_GoodsSellStat  ALTER COLUMN 
		timeType VARCHAR(20)
END
GO

-----------------------------------------------------表修改区域结束-----------------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

-----------------------------------------------------修改数据-----------------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_GoodsSellStat' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_GoodsSellStat 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_GoodsSellStat' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_GoodsSellStat 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_GoodsSellStat' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_GoodsSellStat 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_GoodsSellStat' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_GoodsSellStat 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_GoodsSellStat' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_GoodsSellStat 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_GoodsSellStat' AND a.Name='ProtectTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_GoodsSellStat 
	ALTER COLUMN ProtectTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_GoodsSellStat' AND a.Name='Advantagetotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_GoodsSellStat 
	ALTER COLUMN Advantagetotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='TP_SA_GoodsSellStat' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE TP_SA_GoodsSellStat 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Transportbill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].Transportbill(
		[billNumberID] [numeric](18, 0) NOT NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Transportbill_ptypeid]  DEFAULT ('0'),
		[qty] [numeric](22, 10) NOT NULL CONSTRAINT [DF_Transportbill_qty]  DEFAULT (0),
		behooveQty [numeric](22, 10) NOT NULL CONSTRAINT [DF_Transportbill_behooveQty]  DEFAULT (0),
		[comment] [varchar](250) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Transportbill_comment]  DEFAULT (''),
		[GoodsBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[GoodsBillID] [numeric](10, 0)  NULL DEFAULT (0),
		[GoodsBillType]	INT,
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Transportbill_GoodsNumber]  DEFAULT (''),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_Transportbill_GoodsOrder]  DEFAULT ('-1'),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Transportbill_Serial]  DEFAULT (''),
		[weight]  [numeric](22, 10) DEFAULT(0),
		ShowOrder INT DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]

END
GO

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Transportbill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.Transportbill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'Transportbill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.Transportbill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Transportbill',N'U') AND Name='ShareFee')
BEGIN
	ALTER TABLE dbo.Transportbill
	ADD ShareFee [numeric](24, 10) DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'Transportbill',N'U') AND Name='Volume')
BEGIN
	ALTER TABLE dbo.Transportbill
	ADD Volume [numeric](24, 10) DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Transportbill') AND name = 'CIX_Transportbill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Transportbill_BillNumberID ON Transportbill(BillNumberID)  
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Transportcontrastbill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].Transportcontrastbill(
		[billNumberID] [numeric](18, 0) NOT NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[saleBillNumberID] [numeric](10, 0)  NULL DEFAULT (0),
		[saleBillType]	INT,
		ShowOrder INT DEFAULT(0)
	) ON [PRIMARY]

END
GO

------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Transportcontrastbill') AND name = 'CIX_Transportcontrastbill_BillNumberID')
CREATE CLUSTERED INDEX CIX_Transportcontrastbill_BillNumberID ON Transportcontrastbill(BillNumberID)  
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------

------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UgAType_L') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UgAType_L]
(	
	etypeid	INT, --用户组ID
	typeid	VARCHAR(50),
	flag    CHAR(1),
	[type]	CHAR(1)
)   
END
GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UgBank_l') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UgBank_l]
(	
	etypeid	INT, --用户组ID
	typeid	VARCHAR(50),
	flag    CHAR(1)
)   
END
GO


SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UgBtype_l') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UgBtype_l]
(	
	etypeid	INT, --用户组ID
	typeid	VARCHAR(50),
	flag    CHAR(1)
)   
END
GO


SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UgDType_L') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UgDType_L]
(	
	etypeid	INT, --用户组ID
	typeid	VARCHAR(50),
	flag    CHAR(1)
)   
END
GO


SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UgEType_L') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UgEType_L]
(	
	etypeid	INT, --用户组ID
	typeid	VARCHAR(50),
	flag    CHAR(1)
)   
END
GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UgKType_L') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UgKType_L]
(	
	etypeid	INT, --用户组ID
	typeid	VARCHAR(50),
	flag    CHAR(1)
)   
END
GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UgPType_L') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UgPType_L]
(	
	etypeid	INT, --用户组ID
	typeid	VARCHAR(50),
	flag    CHAR(1)
)   
END
GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UgSType_L') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UgSType_L]
(	
	etypeid	INT, --用户组ID
	typeid	VARCHAR(50),
	flag    CHAR(1)
)   
END
GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[UniteName]    脚本日期: 05/05/2010 14:49:41 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[UniteName]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[UniteName](
		[Id] [int] IDENTITY(1,1) NOT NULL,
		[UniteName] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UnitsTrack') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UnitsTrack]
(
	ID	INT		IDENTITY(1,1)	NOT NULL,
	PtypeId		VARCHAR(50)		COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
	BillType	INT		NOT NULL	DEFAULT (0),--单据类型(0:采购1：销售)
	BillDate	VARCHAR(50)	NULL	DEFAULT (''),
	BtypeId		VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
	UnitId		INT		NULL	
) 

END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('UnitsTrack') AND name = 'CIX_UnitsTrack_ID')
CREATE CLUSTERED INDEX CIX_UnitsTrack_ID ON UnitsTrack(ID)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('UnitsTrack') AND name = 'CIX_UnitsTrack_PtypeId')
CREATE NONCLUSTERED INDEX CIX_UnitsTrack_PtypeId ON UnitsTrack(PtypeId)
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateVersionList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[UpdateVersionList](
		ListId		INT IDENTITY(1,1),	--自增长字段
		VersionNo	VARCHAR(50),		--版本列表
		Title		VARCHAR(1000),		--列表头
		Content		VARCHAR(200),		--内容
		SortId		INT DEFAULT(0)		--排序字段
	) ON [PRIMARY]
END
GO
DELETE FROM UpdateVersionList
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('8.2版本','','',1)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('1、','库存分布调整','库存分布权限调整库存分布权限调整库存分布权限调整库存分布权限调整库存分布权限调整库存分布权限调整库存分布权限调整库存分布权限调整库存分布权限调整库存分布权限调整库存分布权限调整',2)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('2、','业务草稿查看单据增加特审','如果是特审人和单据是待审核状态，特审人能够看到审核单据按钮',3)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('3、','登陆界面调整','登陆界面调整',4)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('4、','修改账龄分析报表逻辑','修改账龄分析报表逻辑',5)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('5、','单品进货/销售报表分析','单品进货/销售报表分析',6)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('6、','增加商品销售类型分析','增加商品销售类型分析',7)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('7、','增加职员销售类型分析','增加职员销售类型分析',8)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('8、','增加库存积压统计','增加库存积压统计',9)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('9、','单位销售月分析报表增加回款金额列','单位销售月分析报表增加回款金额列',10)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('10、','回款分析报表','回款分析报表',11)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('11、','职员发卡统计','职员发卡统计',12)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('12、','采购退货统计报表','采购退货统计报表',13)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('13、','提成规则管理中增加规则过期后隐藏功能','提成规则管理中增加规则过期后隐藏功能',14)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('14、','报损单、报溢单中增加单价和金额列','报损单、报溢单中增加单价和金额列',15)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('15、','业务草稿相关修订','业务草稿相关修订',16)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('16、','经营历程相关修订','经营历程相关修订',17)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('17、','单据虚拟库存判断','单据虚拟库存判断',18)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('18、','单据助手-价格参照','单据助手-价格参照',19)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('19、','账套名称显示','账套名称显示',20)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('20、','单据增强','单据增强',21)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('21、','已审核的单据不允许直接删除','已审核的单据不允许直接删除',22)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('22、','在业务单据调入订单或者草稿的界面中，增加原始单据查看按钮','在业务单据调入订单或者草稿的界面中，增加原始单据查看按钮',23)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('23、','增加手工开发票功能','增加手工开发票功能',24)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('24、','增强制作业务单据时模糊查询功能','增强制作业务单据时模糊查询功能',25)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('25、','增加保存查询条件选项','增加保存查询条件选项',26)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('26、','单据助手增加按预设价格更新单据价格功能','单据助手增加按预设价格更新单据价格功能',27)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('27、','单据“修改人”完善','单据“修改人”完善',28)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('28、','发票表体增加一列‘折扣’','发票表体增加一列‘折扣',29)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('29、','A8分支机构间自动生成收付款单','A8分支机构间自动生成收付款单',30)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('30、','单据助手','单据助手',31)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('31、','菜单增加“更多应用”','菜单增加“更多应用',32)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('32、','在线传讯系列问题汇总','在线传讯系列问题汇总',33)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('33、','跨年结算的相关问题处理','跨年结算的相关问题处理',34)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('34、','手工指定下，盘点单中报溢类型批次控制去除','手工指定下，盘点单中报溢类型批次控制去除',35)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('35、','增加会员销售情况查询报表','增加会员销售情况查询报表',36)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('36、','会员卡信息管理中增加“当前积分余额”列','会员卡信息管理中增加“当前积分余额”列',37)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('37、','借进借出功能增强','借进借出功能增强',38)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('38、','期初增加线性列表','期初增加线性列表',39)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('39、','操作员单据列控制','操作员单据列控制',40)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('40、','权限点细化','权限点细化',41)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('41、','最近进价查看权限与库存成本价查看权限分开','最近进价查看权限与库存成本价查看权限分开',42)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('42、','用户组管理','用户组管理',43)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('43、','往来结算增强','往来结算增强',44)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('44、','增加收付款单打印时进行”自定义编辑”时可选“应收余额/应付余额”字段','增加收付款单打印时进行”自定义编辑”时可选“应收余额/应付余额”字段',45)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('45、','业绩分配程序调整','业绩分配程序调整',46)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('46、','应收查询/应付查询报表的查询条件完善','应收查询/应付查询报表的查询条件完善',47)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('47、','往来综合分析报表','往来综合分析报表',48)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('48、','预收余额查询','预收余额查询',49)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('49、','运维平台增加清除数据库日志和收缩数据库的功能','运维平台增加清除数据库日志和收缩数据库的功能',50)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('50、','运维平台中增加对账套的升级功能','运维平台中增加对账套的升级功能',51)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('51、','报价单修订','报价单修订',52)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('52、','发票中表头税率刷新有误','发票中表头税率刷新有误',53)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('53、','控制零售单未过账前不允许打印','控制零售单未过账前不允许打印',54)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('54、','增加零售单的快速打印功能','增加零售单的快速打印功能',55)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('55、','完善订单与询价/报价单查询','完善订单与询价/报价单查询',56)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('56、','在物价生成功能中增加成本价选项','在物价生成功能中增加成本价选项',57)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('57、','在商品物价信息中生成物价时，按照商品生成','在商品物价信息中生成物价时，按照商品生成',58)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('58、','零售打印控制','零售打印控制',59)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('59、','过账后打印控制调整','过账后打印控制调整',60)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('60、','零售单打印过账','零售单打印过账',61)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('61、','采购订单查询修订','采购订单查询修订',62)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('62、','采购发票调单支持按商品调入','采购发票调单支持按商品调入',63)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('63、','采购入库单调订单增加状态过滤','采购入库单调订单增加状态过滤',64)
INSERT INTO UpdateVersionList(VersionNo,Title,Content,SortId)VALUES('64、','考勤系统','考勤系统',65)


GO
------------------------------------------表修改区域开始-------------------------------------------------

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------WEB------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[UpperLowLimit]    脚本日期: 05/05/2010 14:49:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[UpperLowLimit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[UpperLowLimit](
		[Ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_UpperLowLimit_Ktypeid]  DEFAULT (''),
		[UpperLimit] [numeric](18, 4) NULL CONSTRAINT [DF_UpperLowLimit_UpperLimit]  DEFAULT (0),
		[LowLimit] [numeric](18, 4) NULL CONSTRAINT [DF_UpperLowLimit_LowLimit]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='UpperLowLimit' AND a.Name='UpperLimit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE UpperLowLimit 
	ALTER COLUMN UpperLimit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='UpperLowLimit' AND a.Name='LowLimit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE UpperLowLimit 
	ALTER COLUMN LowLimit NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Userconfig]    脚本日期: 05/05/2010 14:49:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Userconfig]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Userconfig](
		[ConfigNo] [int] IDENTITY(1,1) NOT NULL,
		[ConfigName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Value] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL,
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IsAll] [char](10) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]

	-- ********	处理 UserConfig	********
	DELETE FROM UserConfig
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('AverageCostPrice','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('jubuNew','1','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('AllTaxRate','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('GridType','3','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ZekouValue','1','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('PrintOrder','1','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('Serial','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('Billcodeindex','T','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('SaleBillNum','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('IfBillCode','1','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('NoBillCode','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('PriceTrack','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillCodeConfig','1','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('mngserial','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('mnglendserial','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('EmpQueryWldz','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('IsUseSms','0','00001','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('InvalidGoodsForbidSale','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('IfUseValidDate','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('IfTopMenu','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('btypeall','0','0','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('assesstype','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('verifycode','','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('serialprint','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('passoneday','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('moveinoutklimit','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('chgmoneyalimit','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifsaleordersaleprice','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifbuyorderbuyprice','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifsaleordercanqty','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifbuyordersureqty','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifsaleordershowqty','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifbuyordershowqty','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifsaleordershowarap','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifbuyordershowarap','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifusepentrycode','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifusepstandard','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifuseptype','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifuseparea','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('buyassesstype','','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('needbuyassessmoney','','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('needbuyassessmoney1','','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('addcrm','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('defaultcrmurl','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifversionalert','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('draftsaveneedserial','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('printdraft','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('costpriceanomaly','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('closequickprint','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifusepunitrate','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifusepassistantunit','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifusepallotcostprice','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('costpricesaleback','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('costpricebuyback','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('qtysaleback','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('qtybuyback','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifusescan','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('atypebalancecheck','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('batchprepricemanage','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('sysneeddepartment','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifusechangstockprice','1','','')--Wang Wei 2010-10-11 7、变价调拨单使用预设售价：去掉配置，系统自动默认有。
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifbaseuseserial','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('qtylendback','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('qtyborrowback','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('undercostpricealert','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('billeditemployee','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('billremstockandemployee','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('alertsalepriceunderrecprice','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('alertsalepriceundergoodsstocks','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('autocreateresume','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillNeedDepartment','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifusegoodsnumber','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifuseproducedate','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('billvipjfalert','1','','') --单据过账时会员卡积分提示：去掉配置，系统自动默认有 Wang Wei 2010-10-11。
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ifmulticode','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ordertosalebillaudit','0','','')

	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ordertobuybillaudit','0','','')

	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('mngcargospace','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowLen','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('RepairItemsDiscountType','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeDateSeparator','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('AlertBillcodeRepeat','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeAllowRepeat','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowSet','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeCreateTime','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VipCardBlurSearch','0','','') --会员卡支持模糊查找
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('HfDay','0','','') --回访日期
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VirtualQtySQL','isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)','00001','') --虚拟库存默认计算方式
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('IsPosStart','0','','') --配置是否启用POS管理1为启用，0为不启用 Ding Chao
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('userelectronweigh','0','','') --配置是否启用电子秤1为启用，0为不启用 Ding Chao
	
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('qgctrl','0','','') --请购控制 1为严格,0为不严格
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('doubleunit','0','','') --多单位 1为启用,0为不启用
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('reportmaxcount','50000','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('printnew','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('printorderskip','1','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('printdraftskip','0','','')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('gatherbillmoneynotgtcomplete','0','','')
	INSERT INTO Userconfig(ConfigName,Value,EtypeId,IsAll)VALUES('buybillincludeprice','1','','')--采购订单引用请购单时包含请购价格
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('prepaycashisnegative',0,NULL,'')--是否允许预付金额为负数
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('precollectcashisnegative',0,NULL,'')--是否允许预收金额为负数
	
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('coderepeattip','0','','') --弹出条码重复提示
	
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('carryjsr','0','','')  
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('clearoldbill','0','','')  
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('nocarryold','0','','')  
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('reselectnofs','0','','')  
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('retailbankratestart','0','','')  
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('CalcMunitPrePriceByBaseWhenNone','0','','') --当没有多单位预设价格时通过基本单位计算 
	
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Userconfig]') and  name = 'Value')
BEGIN
		SET ANSI_PADDING OFF
		ALTER TABLE Userconfig
	    ALTER COLUMN Value VARCHAR(5000)
		SET ANSI_PADDING ON

END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'mngcargospace' )
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('mngcargospace','1','','')
	
IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'FlowLen' )
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowLen','1','','')
	
IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BillcodeDateSeparator' )
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeDateSeparator','0','','')
	
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'AlertBillcodeRepeat')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('AlertBillcodeRepeat','1','','')
	
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BillcodeAllowRepeat')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeAllowRepeat','0','','')
	
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'FlowSet')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowSet','0','','')
	
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BillcodeCreateTime')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeCreateTime','0','','')

IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'VipCardBlurSearch' )	
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VipCardBlurSearch','0','','') --会员卡支持模糊查找
	
IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'HfDay' )
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('HfDay','0','','') --回访日期
	
IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'VirtualQtySQL' )
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VirtualQtySQL','isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)','00001','') --虚拟库存默认计算方式

IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'IsPosStart' )
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('IsPosStart','0','','') --配置是否启用POS管理0未不启用，1为启用 Ding Chao

IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'retailbankratestart' )
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('retailbankratestart','0','','') --配置是否启用POS管理0未不启用，1为启用 Ding Chao


IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'userelectronweigh' )
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('userelectronweigh','0','','') --配置是否启用电子秤0未不启用，1为启用 Ding Chao
	
		
IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'VipBirthDayBj' )
    INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VipBirthDayBj','10','','')   --配置会员生日到期提醒天数
GO
IF NOT EXISTS( SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'curdate' )
    INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('curdate','','','')   --配置会员生日到期提醒天数
GO
--当前信息
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='curinfo')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('curinfo','','','')	
END
GO	
--报表可显示的最大条数
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='reportmaxcount')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('reportmaxcount','50000','','')	
END
GO	
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'saleOrderArLimit')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('saleOrderArLimit','','','')
END
GO
--会员储值余额提醒 1为启用,0为不启用
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'VipOverage')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VipOverage','0','','')
END
GO
----会员储值余额提醒临界值   默认为0
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'VipLowerNumber')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VipLowerNumber','0','','')
END
GO
----会员储值余额变动短信提醒   1为启用,0为不启用
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'VipOverageSend')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VipOverageSend','0','','')
END
GO

----启用积分升级方案   1为启用,0为不启用
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'UpgradePoint')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('UpgradePoint','0','','')
END
GO

----积分达标，系统自动升级会员级别   1为启用,0为不启用
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'UpgradePointToVip')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('UpgradePointToVip','0','','')
END
GO
--存储信息
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'EV31')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('EV31','','','')
END
GO
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'EV32')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('EV32','','','')
END
GO
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'EA81')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('EA81','','','')
END
GO
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'EA82')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('EA82','','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'BillNeedDepartment')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillNeedDepartment','1','','')
END

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'controlsaleqty')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('controlsaleqty','0','','')
END
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'checksaleqty')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('checksaleqty','0','','')
END
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'controlbuyqty')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('controlbuyqty','0','','')
END
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'checkbuyqty')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('checkbuyqty','0','','')
END
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'pricetracktype')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('pricetracktype','1','','')
END
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'printdraftskip')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('printdraftskip','0','','')
END
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'printorderskip')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('printorderskip','0','','')
END
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'printnew')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('printnew','0','','')
END

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'equalentrycode')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('equalentrycode','0','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'gatherbillmoneynotgtcomplete')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('gatherbillmoneynotgtcomplete','0','','')
END
GO

--采购订单引用请购单时包含请购价格
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'buybillincludeprice')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('buybillincludeprice','1','','')
END

--允许采购单据中非赠品商品单价为0
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'buyordergift')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('buyordergift','1','','')
END
--允许销售单据中非赠品商品单价为0
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'saleordergift')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('saleordergift','1','','')
END
GO

--会员积分兑换提醒 1为启用,0为不启用
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'VipJfChangeHip')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VipJfChangeHip','0','','')
END
GO
----会员积分兑换提醒值   默认为0
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'VipJfChangeNumber')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('VipJfChangeNumber','1','','')
END
GO

----收付款环节增加按单结算
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'paymenforbill')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('paymenforbill','0','','')
END
GO

----收付款环节增加按商品结算
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'paymentforptype')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('paymentforptype','0','','')
END
GO


----报警簿显示醒目提醒灯泡
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'showalarmlight')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('showalarmlight','0','','')
END
GO


----根据单据所选往来单位自动刷新经手人
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'forbtyperefreshetype')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('forbtyperefreshetype','0','','')
END
GO

--同价调拨单批次选择界面显示虚拟库存
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='allotshowvirtualqty')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('allotshowvirtualqty',0,NULL,'')
END
GO


----单据中结算单位不可编辑 默认为1
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'btypeisreadonly')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('btypeisreadonly','0','','')
END
GO


--预设售价选择
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='SetPriceName')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('SetPriceName',0,NULL,'')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='allowautocreatsale')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('allowautocreatsale','0','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='allowautocreatsaleitem')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('allowautocreatsaleitem','0','','')
END
GO


IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='allowautocreatbuy')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('allowautocreatbuy','0','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='allowautocreatbuyitem')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('allowautocreatbuyitem','0','','')
END
GO

----携带销售订单表头经手人
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'carryjsr')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('carryjsr','0','','')
END
GO
----多次调入销售订单后清除调入的原订单数据
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'clearoldbill')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('clearoldbill','0','','')
END
GO
----按单结算界面的经手人不再携带原单值
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'nocarryold')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('nocarryold','0','','')
END
GO
----单据表体重新选择采购/销售单位后数量不再反算
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'reselectnofs')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('reselectnofs','0','','')
END
GO

----按成本价销售、调拨的单据不参与成本计算
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'allowtbbillcostprice')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('allowtbbillcostprice','1','','')
END
GO

----生产拆装单不参与成本计算
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'allowczbillcostprice')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('allowczbillcostprice','1','','')
END
GO
---价格跟踪导入时验证基准
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'pricetrackverification')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('pricetrackverification','0','','')
END
GO

---原业务单据收付款不能大于本单金额
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'paymentsreceived')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('paymentsreceived','1','','')
END
GO

----开单模糊查询商品记忆功能
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'recordlastselectptype')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('recordlastselectptype','0','','')
END
GO


----开单模糊查询商品记忆功能
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'costpricechange')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('costpricechange','0','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'step')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('step','0','','')
END

 --成本计算根据单据日期
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'countcostbybilldate')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('countcostbybilldate','0','','')
END

--btypeunittrack 启用往来单位跟踪商品计量单位
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'btypeunittrack')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('btypeunittrack','0','','')
END

--更改生产日期或效期至后自动反算另一个日期
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'changedatecalculate')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('changedatecalculate','0','','')
END
--入库类单据批号默认为录单日期
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'buybillnumusebilldate')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('buybillnumusebilldate','0','','')
END
--入库类单据生产日期默认为录单日期
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'buybillprodateusebilldate')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('buybillprodateusebilldate','0','','')
END
--启用序列号盘点功能
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'serialselstockcheck')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('serialselstockcheck','0','','')
END
--单据携带预设价格为换算单位预设价格
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'billtakepreprice')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('billtakepreprice','0','','')
END
--czbillcostcontroltype生产拆装单成本差异控制方式
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'czbillcostcontroltype')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('czbillcostcontroltype','0','','')
END
--independentoutprice独立结转出库成本
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'independentoutprice')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('independentoutprice','0','','')
END


--允许实物库存出现负数
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'physicalsstocknegativestock')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('physicalsstocknegativestock','0','','')
END
--只有通过引用单据的仓库入库单才允许过账
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'quotebillinstock')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('quotebillinstock','0','','')
END
--只有通过引用单据的仓库出库单才允许过账
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'quotebilloutstock')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('quotebilloutstock','0','','')
END
--仓库出库单数量大于来源单据数量不允许过账
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'isgreaterquotebillinstock')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('isgreaterquotebillinstock','0','','')
END
--仓库入库单数量大于来源单据数量不允许过账
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'isgreaterquotebilloutstock')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('isgreaterquotebilloutstock','0','','')
END
--组合品销售订单有订金时自动生成																	 放
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'allowautocreatcombin')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('allowautocreatcombin','0','','')
END
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'allowautocreatcombinitem')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('allowautocreatcombinitem','0','','')
END

 ----实际补货量默认公式
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'SjbhlSQL')
BEGIN
INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('SjbhlSQL','isnull(jhbhqty,0)-isnull(kcqty,0)+isnull(jhzqqty,0)','00001','')
END
--采购订单未引用请购单不允许保存
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'orderyuserequest')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('orderyuserequest','0','','')
END
--采购订单单价大于请购单单价不允许保存
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'notorderpricebiggerrequest')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('notorderpricebiggerrequest','0','','')
END
--采购订单数量大于请购单数量不允许保存
 IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'notorderqtybiggerrequest')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('notorderqtybiggerrequest','0','','')
END
--运输配送单出车登记不提示运费分摊
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'transportnotnotsharefee')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('transportnotnotsharefee','0','','')
END
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'ischangeunit')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('ischangeunit','0','','')
END

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'step')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('step','0','','')
END

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'smssendtime')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('smssendtime','','','')
END

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'EADDR')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('EADDR','','','')
END


----销售类单据计算基准（0销售单价、1折后单价、2含税单价、3基本单位单价）
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebasecalcurule')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebasecalcurule','0','','')
END
GO
----采购类单据计算基准（0采购单价、1折后单价、2含税单价 、3基本单位单价）
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybasecalcurule')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybasecalcurule','0','','')
END
GO

----电商网店管理
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='iswd')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('iswd','0','','')
END
GO
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='delbilllog')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('delbilllog','0','','')
END
GO

--当没有多单位预设价格时通过基本单位计算 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='CalcMunitPrePriceByBaseWhenNone')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('CalcMunitPrePriceByBaseWhenNone','1','','')
END
GO
--高级配置-虚拟库存判断条件 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='virtualinventoryjudgment')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('virtualinventoryjudgment','1','','')
END
GO
--982 高级配置-允许销售订单不选自由项保存单据 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='allowsaleswithoutcheckfreeitemstosave')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('allowsaleswithoutcheckfreeitemstosave','0','','')
END
GO
--982 高级配置-允许采购订单不选自由项保存单据 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='allowpurchasewithoutcheckfreeitemstosave')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('allowpurchasewithoutcheckfreeitemstosave','0','','')
END
GO
--982 高级配置-单据明细商品筛选设置 精确匹配 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='bill_ptypeexactmatching')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('bill_ptypeexactmatching','1','','')
END
GO
--982 高级配置-单据明细商品筛选设置 商品编码检索 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='bill_filterptypecode')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('bill_filterptypecode','usercode,entrycode,standard,pycode','','')
END
GO
--982 高级配置-单据明细商品筛选设置 商品名称检索 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='bill_filterptypename')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('bill_filterptypename','usercode,entrycode,standard,pycode,fullname','','')
END
GO
--设置打印时是否加载图片,1:加载,0:不加载 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='PrintBillLoadPic')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('PrintBillLoadPic','0','','')
END
GO

--设置称重价配置默认启用,1:勾选,0:不勾选 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='weightpriceset')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('weightpriceset','1','','')
END
GO

--设置会员价配置默认不启用,1:勾选,0:不勾选 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='vippriceset')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('vippriceset','0','','')
END
GO
--允许业务单据不选表头可直接选表体商品 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='canselectptypenonebillhead')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('canselectptypenonebillhead','0','','')
END
GO
--重选单据头【仓库/往来单位/结算单位】后自动刷新单据明细行价 
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='selectbillheadrefreshprice')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('selectbillheadrefreshprice','0','','')
END
GO
--记忆分支机构调拨出库单按成本价调拨状态
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='savestypemovebilldefaultcostpricestatus')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('savestypemovebilldefaultcostpricestatus','1','','')
END
GO
--【销售类单据导入时模板中单价为：销售单价/折后单价/含税单价】，默认勾选为“销售单价”
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='setsalebilltempletpricetype')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('setsalebilltempletpricetype','0','','')
END
GO
--【采购类单据导入时模板中单价为：采购单价/含税单价/折后单价】，默认勾选为“采购单价”
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='setbuybilltempletpricetype')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('setbuybilltempletpricetype','0','','')
END
GO
--销售订单生成的【预收款单 / 收款单】自动过账
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='saleorderbilltopreorgathbill_pass')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('saleorderbilltopreorgathbill_pass','0','','')
END
GO
--组合品销售订单生成的【预收款单 / 收款单】自动过账
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='ptcombinorderbilltopreorgathbill_pass')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('ptcombinorderbilltopreorgathbill_pass','0','','')
END
GO
--采购订单生成的【预付款单/付款单】自动过账
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buyorderbilltopreorgathbill_pass')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buyorderbilltopreorgathbill_pass','0','','')
END
GO
--使用了优惠券的销售类单据只允许整单退货
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='usecouponbillbackall')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('usecouponbillbackall','1','','')
END
GO
--选商品不带库存
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='selectptypenostockqty')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('selectptypenostockqty','0','','')
END
GO

--==============================985 新增配置=============================================

--会员储值结算使用单据所选分支机构进行储值余额判断
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName = 'vipBillStoredByStypeId')
BEGIN
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('vipBillStoredByStypeId','0','','')
END
GO
--==============================986 新增配置=============================================
--单据汇总页字段配置

--采购、销售类单据支持汇总相同明细的商品；要求以下字段相同的商品才能汇总
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='billgroup')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('billgroup','1','','')
END
GO
--采购类单据
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_ktypeid')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_ktypeid','1','','')
END
GO
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_mngcargospace')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_mngcargospace','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_freeitem')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_freeitem','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_producedate')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_producedate','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_validdate')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_validdate','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_goodsnumber')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_goodsnumber','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_unit')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_unit','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_price')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_price','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_discount')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_discount','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_tax')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_tax','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillgroup_status')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillgroup_status','1','','')
END
GO

--销售类单据
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_ktypeid')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_ktypeid','1','','')
END
GO
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_mngcargospace')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_mngcargospace','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_freeitem')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_freeitem','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_producedate')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_producedate','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_validdate')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_validdate','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_goodsnumber')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_goodsnumber','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_unit')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_unit','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_price')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_price','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_discount')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_discount','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_tax')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_tax','1','','')
END
GO

IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillgroup_status')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillgroup_status','1','','')
END
GO

--销售订单低于成本价不提示
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='saleordercostpricealert')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('saleordercostpricealert','1','','')
END
GO


--销售订单低于成本价不提示
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='SetSaleBillSerialType')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('SetSaleBillSerialType','1','','')
END
GO

--销售订单低于成本价不提示
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='SetBuyBillSerialType')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('SetBuyBillSerialType','1','','')
END
GO

--单据导出Excel不计算打印次数
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='ToExcelNotAddPrintCount')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('ToExcelNotAddPrintCount','0','','')
END

--出库类单据过账时条码对货数量和单据录入数量必须一致
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='entrycodequaltoqtyforsale')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('entrycodequaltoqtyforsale','0','','')
END

--入库类单据过账时条码对货数量和单据录入数量必须一致
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='entrycodequaltoqtyforbuy')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('entrycodequaltoqtyforbuy','0','','')
END

--出库类单据更改价税合计/含税单价，反算税率
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='salebillcalculatetax')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('salebillcalculatetax','0','','')
END

--采购类单据更改价税合计/含税单价，反算税率
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='buybillcalculatetax')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('buybillcalculatetax','0','','')
END

--录单时，修改经手人不自动带出关联部门
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='billeditemployeelinkdepartment')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('billeditemployeelinkdepartment','0','','')
END

GO


--仓储调拨类单据 出库仓库
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_outktypeid')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_outktypeid','1','','')
END
GO
--出库货位
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_outmngcargospace')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_outmngcargospace','1','','')
END
GO
--入库仓库
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_inktypeid')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_inktypeid','1','','')
END
GO
--入库货位
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_inmngcargospace')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_inmngcargospace','1','','')
END
GO
--自由项
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_freeitem')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_freeitem','1','','')
END
GO
--生产日期
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_producedate')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_producedate','1','','')
END
GO
--效期至
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_validdate')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_validdate','1','','')
END
GO
--批号
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_goodsnumber')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_goodsnumber','1','','')
END
GO
--库存单位
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_unit')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_unit','1','','')
END
GO
GO
--库存单价
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stockbillgroup_price')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stockbillgroup_price','1','','')
END
GO
--允许职员名称重复
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='equaleroname')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('equaleroname','0','','')
END
GO
--允许供应商名称重复
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='equalitemname')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('equalitemname','1','','')
END
GO
--允许客户名称重复
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='equalbidname')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('equalbidname','1','','')
END
GO
--【分支机构调拨入库单】成本与【分支机构调拨出库单】商品成本相关联
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='stypeinandstypeout')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('stypeinandstypeout','0','','')
END
GO
--默认使用老打印管理器
IF NOT EXISTS(SELECT 1 FROM UserConfig WHERE ConfigName='useOldPrint')
BEGIN
	INSERT INTO Userconfig(ConfigName, [Value], EtypeId, IsAll)VALUES('useOldPrint','0','','')
END
GO



/****** 对象:  Table [dbo].[UserGridConfig]    脚本日期: 05/05/2010 14:49:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[UserGridConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[UserGridConfig](
		[employeeid] [varchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[rk] [int] NOT NULL CONSTRAINT [DF_UerGridConfig_rk]  DEFAULT (0),
		[ck] [int] NOT NULL CONSTRAINT [DF_UerGridConfig_ck]  DEFAULT (0),
		[qt] [int] NOT NULL CONSTRAINT [DF_UerGridConfig_qt]  DEFAULT (0)
	) ON [PRIMARY]

	-- ********	处理 UserGridConfig	********
	DELETE FROM UserGridConfig
	INSERT INTO UserGridConfig(Employeeid,rk,ck,qt)VALUES('00001',0,31,1)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[UserGridConfig]') AND name = N'PK_UerGridConfig')
ALTER TABLE [dbo].[UserGridConfig] DROP CONSTRAINT [PK_UerGridConfig]
GO

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('USERGRIDCONFIG') AND name = 'CIX_USERGRIDCONFIG_employeeid')
--DROP INDEX CIX_USERGRIDCONFIG_employeeid ON USERGRIDCONFIG 
CREATE CLUSTERED INDEX CIX_USERGRIDCONFIG_employeeid ON USERGRIDCONFIG(employeeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UserGroup]') AND type in (N'U'))
BEGIN
	CREATE TABLE UserGroup
	(
		UgId				INT IDENTITY(1,1),	--用户组ID
		ugname				VARCHAR(200) NOT NULL,		--用户组名称
		lim					VARCHAR(8000) NULL DEFAULT(' '),
												--权限
		Comment				VARCHAR(256),		--说明
		etypeid				VARCHAR(50)  --操作员
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[UserGroup]') and  name = 'Lim' and Length=500)
BEGIN
	 ALTER TABLE UserGroup
	    ALTER COLUMN Lim VARCHAR(5000) NULL
END
GO

IF NOT EXISTS(select top 1 1 from syscolumns where id = object_id(N'[dbo].[UserGroup]') and  name = 'etypeid')
BEGIN
	 ALTER TABLE UserGroup
	    ADD etypeid VARCHAR(50) DEFAULT('')
END
GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[UserGroup]') and  name = 'Lim' and Length=5000)
BEGIN
	 ALTER TABLE UserGroup
	    ALTER COLUMN Lim VARCHAR(8000) NULL
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'UserGroupLimit') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UserGroupLimit]
(	
	ID				INT IDENTITY(1,1),
	EtypeID			INT NOT NULL, --用户组ID
	Lim				VARCHAR (5000) NOT NULL DEFAULT(' ') ,
	MangerETypeID	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerPTypeID	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerKTypeID	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerSTypeID	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerDTypeID	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerBTypeID	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerBTypeID2	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerATypeID	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerRevenue   VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerOwnerEquity	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerExpense		VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerIncome		VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerCpaital		VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerOtherCpaital	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerLiabilities	VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerPay			VARCHAR(50) NOT NULL DEFAULT('-99999'),
	MangerBankID		VARCHAR(50) NOT NULL DEFAULT('-99999')
)   
END
GO

SET ANSI_PADDING OFF
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UserGroupManage]') AND type in (N'U'))
BEGIN
	CREATE TABLE UserGroupManage
	(
		UserGroupManageId	INT IDENTITY(1,1),	--管辖用户组ID
		ETypeId				VARCHAR(50),		--操作员ID
		UgId				INT					--用户组ID
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[VipAddMoneyBatchBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[VipAddMoneyBatchBill](
		BillNumberId INT NOT NULL DEFAULT(0)
		,Id INT NOT NULL IDENTITY(1,1)
		,VipCardId INT NOT NULL DEFAULT(0)
		,BeforeChargeMoney NUMERIC(18,4) NOT NULL DEFAULT(0)
		,AfterChargeMoney NUMERIC(18,4) NOT NULL DEFAULT(0)
		,ChargeMoney NUMERIC(18,4) NOT NULL DEFAULT(0)
		,PreferenceMoney NUMERIC(18,4) NOT NULL DEFAULT(0)
		,TotalInMoney NUMERIC(18,4)
		,EndDate DATETIME NULL 
		,Comment VARCHAR(256) NOT NULL DEFAULT('')
		,ShowOrder INT DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	);
END

go

-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'VipAddMoneyBatchBill',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.VipAddMoneyBatchBill
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'VipAddMoneyBatchBill',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.VipAddMoneyBatchBill
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF EXISTS(SELECT 1 FROM sys.all_columns WHERE object_id=object_id('VipAddMoneyBatchBill') AND name='TotalMoney')
	EXEC sp_rename 'VipAddMoneyBatchBill.TotalMoney','TotalInMoney','column';
GO
IF EXISTS(SELECT 1 FROM sys.all_columns WHERE object_id=object_id('VipAddMoneyBatchBill') AND name='ClosingDate')
	EXEC sp_rename 'VipAddMoneyBatchBill.ClosingDate','EndDate','column'
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'VipAddMoneyBatchBill',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.VipAddMoneyBatchBill
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE VipAddMoneyBatchBill SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipAddMoneyBatchBill' AND a.Name='BeforeChargeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipAddMoneyBatchBill 
	ALTER COLUMN BeforeChargeMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipAddMoneyBatchBill' AND a.Name='AfterChargeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipAddMoneyBatchBill 
	ALTER COLUMN AfterChargeMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipAddMoneyBatchBill' AND a.Name='ChargeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipAddMoneyBatchBill 
	ALTER COLUMN ChargeMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipAddMoneyBatchBill' AND a.Name='PreferenceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipAddMoneyBatchBill 
	ALTER COLUMN PreferenceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipAddMoneyBatchBill' AND a.Name='TotalInMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipAddMoneyBatchBill 
	ALTER COLUMN TotalInMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
--会员卡适用门店（其实就是pos机）---
IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'VipCard_ApplyPOS',N'U'))
BEGIN
	CREATE TABLE VipCard_ApplyPOS
	(
		ID	       INT IDENTITY(1,1),
		VipCardId  INT NOT NULL,
		PosID		INT	 NOT NULL DEFAULT(0)
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------

 
------------------------------------------创建索引区域结束-----------------------------------------------
GO




GO
--会员卡适用分支机构---
IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'VipCard_ApplyStype',N'U'))
BEGIN
	CREATE TABLE VipCard_ApplyStype
	(
		ID	       INT IDENTITY(1,1),
		VipCardId  INT NOT NULL,
		StypeId		VARCHAR(50)	 NOT NULL DEFAULT('')
	)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------

 
------------------------------------------创建索引区域结束-----------------------------------------------
GO




/****** 对象:  Table [dbo].[VipCardAutoZk]    脚本日期: 05/05/2010 14:49:45 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[VipCardAutoZk]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[VipCardAutoZk](
		[VipCardAutoID] [int] IDENTITY(1,1) NOT NULL,
		[VipCardId] [int] NULL,
		[ZkHighLimit] [numeric](18, 4) NULL,
		[ZkLowLimit] [numeric](18, 4) NULL,
		[ZkAutoRate] [numeric](18, 4) NULL,
		[Note] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardAutoZk' AND a.Name='ZkHighLimit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardAutoZk 
	ALTER COLUMN ZkHighLimit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardAutoZk' AND a.Name='ZkLowLimit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardAutoZk 
	ALTER COLUMN ZkLowLimit NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardAutoZk' AND a.Name='ZkAutoRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardAutoZk 
	ALTER COLUMN ZkAutoRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[VipCardConsume]    脚本日期: 05/05/2010 14:49:46 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[VipCardConsume]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[VipCardConsume](
		[VipCardConsumeId] [int] IDENTITY(1,1) NOT NULL,
		[VipCardNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[PreConsumeDate] [datetime] NULL,
		[PreConsumeMoney] [numeric](18, 4) NULL,
		[PreConsumeRate] [numeric](18, 4) NULL,
		[PreConsumeZkMoney] [numeric](18, 4) NULL,
		[SumConsumeMoney] [numeric](18, 4) NULL,
		[NextZkRate] [numeric](18, 4) NULL,
		[SumConsumeZkMoney] [numeric](18, 4) NULL,
		[BillNumberID] [int] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardConsume' AND a.Name='PreConsumeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardConsume 
	ALTER COLUMN PreConsumeMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardConsume' AND a.Name='PreConsumeRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardConsume 
	ALTER COLUMN PreConsumeRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardConsume' AND a.Name='PreConsumeZkMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardConsume 
	ALTER COLUMN PreConsumeZkMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardConsume' AND a.Name='SumConsumeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardConsume 
	ALTER COLUMN SumConsumeMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardConsume' AND a.Name='NextZkRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardConsume 
	ALTER COLUMN NextZkRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardConsume' AND a.Name='SumConsumeZkMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardConsume 
	ALTER COLUMN SumConsumeZkMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[VipCardSet]    脚本日期: 05/05/2010 14:49:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[VipCardSet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[VipCardSet](
		[VipCardID] [int] IDENTITY(1,1) NOT NULL,
		[VipCardName] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[VipCardKL] [numeric](18, 4) NULL,
		[VipCardAutoZK] [bit] NULL,
		[ConsumeMoney] [numeric](18, 4) NULL,
		[ConsumeTimes] [int] NULL,
		[TimeLimit] [int] NULL,
		[StartDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[Note] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[VipCardKz] [bit] NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardSet' AND a.Name='VipCardKL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardSet 
	ALTER COLUMN VipCardKL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardSet' AND a.Name='ConsumeMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardSet 
	ALTER COLUMN ConsumeMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[VipCardSign]    脚本日期: 05/05/2010 14:49:48 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[VipCardSign]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[VipCardSign](
		[VipCardSignId] [int] IDENTITY(1,1) NOT NULL,
		[VipCardNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[VipCardId] [int] NULL,
		[SignDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[VipCardOwner] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[CertificateNo] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkerPhoneNo] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LinkerAddr] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[BTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[VipCardState] [int] NULL,
		[VipCardZK] [numeric](18, 4) NULL,
		[AutoZk] [bit] NULL,
		[Note] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='nVipCardSign' AND a.Name='totalCent'
)
BEGIN
	UPDATE nVipCardSign SET totalCent = ROUND(ISNULL(totalCent,0),0)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCardSign' AND a.Name='VipCardZK' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE VipCardSign 
	ALTER COLUMN VipCardZK NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[VipCentToMoneyBill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[VipCentToMoneyBill]
	(
		BillNumberId		INT NOT NULL DEFAULT(0),--主表单据ID
		Id					INT NOT NULL IDENTITY(1,1),
		VipCardId			INT NOT NULL DEFAULT(0),--会员卡ID
		BeforeYeCent		NUMERIC(24,10) NOT NULL DEFAULT(0),--兑换前积分余额
		AfterYeCent			NUMERIC(24,10) NOT NULL DEFAULT(0),--兑换后积分余额
		ChangeCent			NUMERIC(24,10) NOT NULL DEFAULT(0),--本次兑换积分
		ChangeMoney			NUMERIC(24,10) NOT NULL DEFAULT(0),--本次兑换储值
		BeforeCzMoney		NUMERIC(24,10) NOT NULL DEFAULT(0),--兑换前储值金额
		AfterCzMoney		NUMERIC(24,10) NOT NULL DEFAULT(0) ,--兑换后储值金额
	    DraftFlag			BIT NOT NULL DEFAULT (1),
	    IsIniFlag			BIT NOT NULL DEFAULT (0)
	) ON [PRIMARY]
END
GO 
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCentToMoneyBill' AND a.Name='DraftFlag'
)
BEGIN
	ALTER TABLE VipCentToMoneyBill 
		ADD DraftFlag BIT NOT NULL DEFAULT (1)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCentToMoneyBill' AND a.Name='IsIniFlag'
)
BEGIN
	ALTER TABLE VipCentToMoneyBill 
		ADD IsIniFlag BIT NOT NULL DEFAULT (0)
END

GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipCentToMoneyBill' AND a.Name='Comment'
)
BEGIN
	
	declare @csname varchar(100)
	set @csname=''

	select @csname=[name] --约束名称
	from sysobjects t
	where id=(select cdefault from syscolumns where id=object_id(N'VipCentToMoneyBill') and name='Comment')

	--动态删掉约束
	exec('alter table VipCentToMoneyBill drop constraint '+@csname)

	ALTER TABLE VipCentToMoneyBill DROP COLUMN Comment
END
GO

--修改列名
--EXEC sp_rename 'VipCentToMoneyBill.BeforeMoney','BeforeCzMoney'
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('VipCentToMoneyBill') AND name = 'CIX_VipCentToMoneyBill_BillNumberID')
	CREATE CLUSTERED INDEX CIX_VipCentToMoneyBill_BillNumberID ON VipCentToMoneyBill(BillNumberID) 
GO	
 



--------------------------积分清零日志-----------------------------------------------------
if not exists (select 1
            from  sysobjects
           where  id = object_id('VipClearLog')
            and   type = 'U')   
BEGIN
	create table VipClearLog (
	   id                   int                  identity(1,1),
	   LogTime				DATETIME,
	   comment              varchar(200)         null,
	   checker			varchar(200), --经手人
	)
END	
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VipClearLog' AND a.Name='CardNo'
)
BEGIN
	ALTER TABLE VipClearLog 
		ADD CardNo VARCHAR(MAX) NOT NULL DEFAULT('')
END

GO

			
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM SysDataDB..sysobjects WHERE id = OBJECT_ID(N'[SysDataDB]..[virDirLogo]') AND type in (N'U'))
BEGIN
	CREATE TABLE [SysDataDB]..[virDirLogo](
		[virDirName] [varchar](200) NULL,		
		[logoimg] [image] NULL,
		[logoposition] [varchar](max) NULL,
		[logosize] [varchar](max) NULL,
		[logotype] [varchar](max) NULL
) 
END
GO





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON


IF NOT EXISTS (SELECT * FROM SysDataDB..sysobjects WHERE id = OBJECT_ID(N'[SysDataDB]..[VirtualDirectoryWithAccount]') AND type in (N'U'))
BEGIN
	CREATE TABLE [SysDataDB]..[VirtualDirectoryWithAccount]
	(
		VirtualDirectory VARCHAR(200),	 --虚拟目录名称 
		DogNumber VARCHAR(200),  --软狗号
		PollCode VARCHAR(200),	 --注册码
		UserNumber INT,	 --用户数
		RegisterName VARCHAR(400),	 --注册客户名称
		DataBaseName	VARCHAR(200), --数据库名称
		AccountCode		VARCHAR(400), --帐套编码
		AccountName		VARCHAR(400), -- 帐套名称
		FirstUseDate	DATE,		
		EndDate			DATE,
		
		desUserNumber	VARCHAR(200) NOT NULL DEFAULT(''),	--加密狗号
		certCode		VARCHAR(100) NOT NULL DEFAULT(''),
		safeCode		VARCHAR(100) NOT NULL DEFAULT(''),
		email			VARCHAR(100) NOT NULL DEFAULT(''),
		mobil			VARCHAR(40) NOT NULL DEFAULT(''),
		corpTel			VARCHAR(40) NOT NULL DEFAULT(''),
		productNo		VARCHAR(10)	NOT NULL DEFAULT(''),
		UserCardNo		VARCHAR(100) DEFAULT(''),
		area			VARCHAR(10) DEFAULT(''),
		corpName		VARCHAR(500) NOT NULL DEFAULT(''),
		desEndDate		VARCHAR(200) NULL, --加密截至日期
		accountNumber	INT	 NOT NULL DEFAULT(0),
		regFlag			INT NOT NULL DEFAULT(0),
		regDate			DATETIME NULL,
		ztVersion		INT, --0:未知  1:V3  2:A8
		flag			INT DEFAULT(0), --标识:0云模式数据;1普通模式数据
		webServerIP		VARCHAR(20) DEFAULT(''), --WEB服务器IP，用以区别虚拟目录
		posdno			VARCHAR(200),
		posUserCount	INT,
		desStr			VARCHAR(2000)
	)

END
GO

-----------------------------修改表结构------------------------------------------

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desUserNumber' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE [SysDataDB]..[VirtualDirectoryWithAccount] 
		ADD desUserNumber	VARCHAR(200) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='certCode' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE [SysDataDB]..[VirtualDirectoryWithAccount] 
		ADD certCode	VARCHAR(100) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='safeCode' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD safeCode	VARCHAR(100) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='email' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD email	VARCHAR(100) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='mobil' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD mobil	VARCHAR(40) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='corpTel' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD corpTel	VARCHAR(40) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='productNo' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD productNo	VARCHAR(10) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='UserCardNo' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD UserCardNo	VARCHAR(100)  DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='area' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD area	VARCHAR(10) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='corpName' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD corpName	VARCHAR(500) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desEndDate' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD desEndDate	VARCHAR(200) NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='accountNumber' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD accountNumber	INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='regFlag' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD regFlag	INT NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='regDate' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD regDate	DATETIME NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='flag' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD flag	INT DEFAULT(0) 
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='ztVersion' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD ztVersion	INT DEFAULT(0) 
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='webServerIP' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD webServerIP	VARCHAR(20) DEFAULT('') 
END
GO

--免注册时长
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='limitday' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD limitday	INT  DEFAULT(0) 
END
GO

--修改首次使用时间，增加小时
IF EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='firstusedate' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ALTER COLUMN firstusedate DATETIME 
END
GO

--posno
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='posdno' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  posdno VARCHAR(200) 
END
GO
--posusercount
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='posUserCount' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  posUserCount INT 
END
GO
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desStr' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  desStr VARCHAR(2000) 
END
GO
IF EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desStr' AND b.Name='VirtualDirectoryWithAccount' and a.length=200
)
BEGIN
	ALTER TABLE SysDataDB.dbo.[VirtualDirectoryWithAccount] ALTER COLUMN desStr VarChar(2000) 
END
GO
--验证天数
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='rgDay' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD rgDay INT NOT NULL DEFAULT(0)
END
GO
--最后一次验证时间
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='rgCheckDate' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  rgCheckDate DATETIME NOT NULL DEFAULT(GETDATE())
END
GO
--加密验证天数
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desRgDay' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  desRgDay VARCHAR(100) NOT NULL DEFAULT('')
END
GO
--安装路径
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='DirectoryPath' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD DirectoryPath VARCHAR(1000) NOT NULL DEFAULT('')
END
GO
--最后一次验证时间
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desRgCheckDate' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  desRgCheckDate VARCHAR(200) NOT NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desPosdno' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  desPosdno VARCHAR(200) NOT NULL DEFAULT('')
END

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='desPosUserCount' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  desPosUserCount VARCHAR(200) NOT NULL DEFAULT('')
END
GO
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='IsSysEdit' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD  IsSysEdit BIT NOT NULL DEFAULT(0)
END
GO
--登陆模式
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='loginMode' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD loginMode INT NULL DEFAULT(0)
END
GO
UPDATE SysDataDB.DBO.VirtualDirectoryWithAccount SET loginMode = 1 WHERE loginMode IS NULL
GO
--验证码
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='Verification' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE SysDataDB..[VirtualDirectoryWithAccount] 
		ADD Verification INT NULL DEFAULT(0)
END
GO
UPDATE SysDataDB.DBO.VirtualDirectoryWithAccount SET Verification = 1 WHERE Verification IS NULL
GO
--服务器取限制用户的标识
IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM SysDataDB..syscolumns a
		INNER JOIN SysDataDB..sysobjects b ON a.ID=b.ID
	WHERE a.Name='islimlogin' AND b.Name='VirtualDirectoryWithAccount'
)
BEGIN
	ALTER TABLE [SysDataDB]..[VirtualDirectoryWithAccount] 
		ADD islimlogin VARCHAR(10) NULL DEFAULT('0')
END
GO
UPDATE [SysDataDB].DBO.[VirtualDirectoryWithAccount] SET islimlogin = 0 WHERE islimlogin IS NULL
GO
-----------------------------修改表结构结尾------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[visit]    脚本日期: 05/05/2010 14:49:49 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[visit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[visit](
		[billnumberid] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
		[billdate] [datetime] NOT NULL,
		[billcode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_visit_billcode]  DEFAULT (''),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[jbbillnumberid] [numeric](18, 0) NOT NULL,
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[fullname] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_visit_ptypeid]  DEFAULT (''),
		[linkman] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_visit_linkman]  DEFAULT (''),
		[linktel] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_visit_linktel]  DEFAULT (''),
		[linkaddr] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_visit_linkaddr]  DEFAULT (''),
		[inbilldate] [datetime] NULL,
		[inbillcode] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_visit_jbbillcode]  DEFAULT (''),
		[manyidu] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_visit_manyidu]  DEFAULT (''),
		[jianyi] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_visit_jianyi]  DEFAULT (''),
		[fjid] [numeric](18, 0) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[visitfj]    脚本日期: 05/05/2010 14:49:49 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[visitfj]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[visitfj](
		[billnumberid] [numeric](18, 0) NOT NULL,
		[filename] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[filesize] [int] NOT NULL CONSTRAINT [DF_visitfj_filesize]  DEFAULT (0),
		[filetype] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[binarydata] [image] NOT NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[filename1] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_visitfj_filename1]  DEFAULT ('')
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[voucherChar1]    脚本日期: 05/05/2010 14:49:50 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[voucherChar1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[voucherChar1](
		[BillNumberID] [numeric](18, 0) NULL,
		[BillType] [numeric](18, 0) NULL,
		[voucherChar] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[TotalInMoney] [numeric](18, 0) NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[voucherChar2]    脚本日期: 05/05/2010 14:49:51 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[voucherChar2]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[voucherChar2](
		[BillType] [numeric](18, 0) NULL,
		[BillNumberID] [numeric](18, 0) NULL,
		[voucherChar] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[TotalInMoney] [numeric](18, 0) NULL,
		[ATypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT TOP 1 1 FROM SYSOBJECTS WHERE  id = object_id('VoucherSchemeDetail') and type='U')
BEGIN
	CREATE TABLE VoucherSchemeDetail (
	   nId				INT			IDENTITY(1,1),
	   SchemeId			INT			NOT NULL,	--默认方案ID
	   OrderFiled		VARCHAR(50)	NOT NULL,	--排序字段
	   OrderBy			VARCHAR(5)	NOT NULL,	--排序 升序 降序
	   OrderID			INT			NOT NULL	--排序	顺序
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('VoucherTemplatePreset') AND  type = 'U')
BEGIN
	CREATE TABLE VoucherTemplatePreset
	(
	Id				INT IDENTITY(1,1),  --自增长ID
	Billtype		INT,				--单据类型
	usercode		VARCHAR(200),		--模版编号
	fullname		VARCHAR(200),		--模版名称
	groupfullname	VARCHAR(50),		--凭证字
	summary			VARCHAR(200),		--模版摘要
	atypefrom		VARCHAR(200),		--科目来源
	atypeusercode	VARCHAR(200),		--科目编号
	atypefullname	VARCHAR(200),		--科目名称
	dc				VARCHAR(50),		--借贷方向
	totalfrom		VARCHAR(200),		--金额来源
	assitems		VARCHAR(2000),		--辅助核算
	SubId			INT,				--科目表类别，对应Ac_Account_Set_List中的SubId
	AuditType		INT,				--业务类别 固定资产卡片模式相关字段
	InOutType		INT,				--调出调入 为资金调拨单新增字段
	ChargeOffType	INT,				--往来核销类别
	MainRow			INT DEFAULT(0)		--首行标识，排序用
	)
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VoucherTemplatePreset' AND a.Name='AuditType'
)
BEGIN
	ALTER TABLE VoucherTemplatePreset ADD AuditType INT NULL DEFAULT (0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VoucherTemplatePreset' AND a.Name='InOutType'
)
BEGIN
	ALTER TABLE VoucherTemplatePreset ADD InOutType INT NULL DEFAULT (0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VoucherTemplatePreset' AND a.Name='MainRow'
)
BEGIN
	ALTER TABLE VoucherTemplatePreset ADD MainRow INT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VoucherTemplatePreset' AND a.Name='ChargeOffType'
)
BEGIN
	ALTER TABLE VoucherTemplatePreset ADD ChargeOffType INT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VoucherTemplatePreset' AND a.Name='isCost'
)
BEGIN
	ALTER TABLE VoucherTemplatePreset ADD isCost BIT NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VoucherTemplatePreset' AND a.Name='OrderID'
)
BEGIN
	ALTER TABLE VoucherTemplatePreset ADD OrderID INT NOT NULL DEFAULT (1)
END
GO


--预制数据写入
IF NOT EXISTS(SELECT TOP 1 1 FROM VoucherTemplatePreset)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES('9','BSD001','报损单模板','记','报损单','手工选择','1901','待处理财产损溢','借','成本金额','',28),
			('9','','','','报损单','手工选择','1405','库存商品','贷','成本金额','',28),
			('14','BYD001','报溢单模板','记','报溢单','手工选择','1405','库存商品','借','成本金额','',28),
			('14','','','','报溢单','手工选择','1901','待处理财产损溢','贷','成本金额','',28),
			('205','CGFYFT001','入库费用分摊单模板','记','采购费用分摊单','手工选择','1405','库存商品','借','分摊金额','',28),
			('205','','','','采购费用分摊单','单据上项目对应科目','','','贷','分摊金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('161','CGHH001','采购换货单凭证模板','记','采购换货','手工选择','1405','库存商品','借','入库成本金额 减 出库成本金额','',28),
			('161','','','','采购换货','手工选择','2221','应交税费','借','入库税额 减 出库税额','',28),
			('161','','','','采购换货','手工选择','2221','应交税费','借','材料成本差异税额','',28),
			('161','','','','采购换货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('161','','','','采购换货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('161','','','','采购换货','手工选择','6051','其他业务收入','贷','抹零金额','',28),
			('161','','','','采购换货','手工选择','1404','材料成本差异','贷','材料成本差异额','',28),
			('34','CGRK0001','采购入库单凭证模板','记','采购入库','手工选择','1405','库存商品','借','成本金额','',28),
			('34','','','','采购入库','手工选择','2221','应交税费','借','税额','',28),
			('34','','','','采购入库','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('34','','','','采购入库','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('34','','','','采购入库','手工选择','6051','其他业务收入','贷','抹零金额','',28),
			('6','CGTH001','采购退货单凭证模板','记','采购退货','手工选择','1405','库存商品','贷','成本金额','',28),
			('6','','','','采购退货','手工选择','2221','应交税费','贷','税额','',28),
			('6','','','','采购退货','手工选择','1404','材料成本差异','贷','材料成本差异额','',28),
			('6','','','','采购退货','单据上往来科目','','','借','抹零后金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('6','','','','采购退货','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('6','','','','采购退货','手工选择','6051','其他业务收入','借','抹零金额','',28),
			('6','','','','采购退货','手工选择','2221','应交税费','借','材料成本差异税额','',28),
			('57','CBTJ001','成本调价单模板','记','成本调价单','手工选择','1405','库存商品','借','调后金额 减 调前金额','',28),
			('57','','','','成本调价单','手工选择','1404','材料成本差异','贷','调后金额 减 调前金额','',28),
			('5','DTFYFS001','待摊费用发生模板','记','待摊费用发生','单据上项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('5','','','','待摊费用发生','手工选择','6402','其他业务成本','借','金额','',28),
			('10','DTFYTX001','待摊费用摊销模板','记','待摊费用摊销','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('10','','','','待摊费用摊销','手工选择','6402','其他业务成本','贷','金额','',28),
			('148','FLHS001','返利核算执行模板','记','返利核算执行','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('148','','','','返利核算执行','单据上往来科目','','','贷','返利金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('148','','','','返利核算执行','手工选择','6402','其他业务成本','借','返利金额','',28),
			('36','FYD001','费用单模板','记','费用单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('36','','','','费用单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('36','','','','费用单','单据上往来科目','','','贷','金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('66','FKD001','付款单模板','记','付款单','单据上往来科目','','','借','金额 加 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('66','','','','付款单','手工选择','6051','其他业务收入','贷','抹零金额','',28),
			('66','','','','付款单','单据上收付款项目对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('85','GDZCBM001','固定资产变卖模板','记','固定资产变卖','固定资产科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('85','','','','固定资产变卖','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('85','','','','固定资产变卖','单据上往来科目','','','借','金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('84','GDZCGM001','固定资产购买模板','记','固定资产购买','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('84','','','','固定资产购买','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('84','','','','固定资产购买','单据上往来科目','','','贷','金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('78','GDZCZJ001','固定资产折旧模板','记','固定资产折旧','固定资产科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('78','','','','固定资产折旧','手工选择','6402','其他业务成本','借','金额','',28),
			('181','HYCZCZ001','会员储值充值单模板','记','会员储值充值单','手工选择','2203','预收账款','贷','充值金额','往来单位：往来单位',28),
			('181','','','','会员储值充值单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',28),
			('181','','','','会员储值充值单','手工选择','6601','销售费用','借','抹零金额','',28),
			('181','','','','会员储值充值单','单据上往来科目','','','借','充值金额 减 抹零金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',28),
			('151','HDJB001','获得价保单模板','记','获得价保单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('151','','','','获得价保单','单据上往来科目','','','借','应保价金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('151','','','','获得价保单','手工选择','6051','其他业务收入','贷','应保价金额','',28),
			('150','HLHS001','获利核算执行模板','记','获利核算执行','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('150','','','','获利核算执行','单据上往来科目','','','借','获利金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('150','','','','获利核算执行','手工选择','6051','其他业务收入','贷','获利金额','',28),
			('126','HZD001','获赠单凭证模板','记','获赠','手工选择','1405','库存商品','借','成本金额','',28),
			('126','','','','获赠','手工选择','6051','其他业务收入','贷','成本金额','',28),
			('183','JFDH001','积分兑换单模板','记','积分兑换单','手工选择','6601','销售费用','借','成本金额','',28),
			('183','','','','积分兑换单','手工选择','1405','库存商品','贷','成本金额','',28),
			('149','JBZX001','价保执行单模板','记','价保执行单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('149','','','','价保执行单','单据上往来科目','','','贷','应保价金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('149','','','','价保执行单','手工选择','6402','其他业务成本','借','应保价金额','',28),
			('305','LS0001','零售单凭证模板','记','销售商品','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('305','','','','销售商品','手工选择','6001','主营业务收入','贷','折后金额','',28),
			('305','','','','销售商品','手工选择','6401','主营业务成本','借','成本金额','',28),
			('305','','','','销售商品','手工选择','1405','库存商品','贷','成本金额','',28),
			('305','','','','销售商品','手工选择','6601','销售费用','借','抹零金额','',28),
			('202','QTCK001','其它出库单模板','记','其他出库单','单据上业务类型对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('202','','','','其他出库单','手工选择','1405','库存商品','贷','金额 ','',28),
			('201','QTRK001','其他入库单模板','记','其他入库单','手工选择','1405','库存商品','借','金额 ','',28),
			('201','','','','其他入库单','单据上业务类型对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('93','QTSR001','其他收入单模板','记','其他收入单','单据上项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('93','','','','其他收入单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('93','','','','其他收入单','单据上往来科目','','','借','金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('172','SMWX001','上门维修单模板','记','上门维修','单据上往来科目','','','借','维修费合计 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('172','','','','上门维修','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('172','','','','上门维修','手工选择','6051','其他业务收入','贷','维修费合计','',28),
			('172','','','','上门维修','手工选择','6601','销售费用','借','抹零金额','',28),
			('172','','','','上门维修','手工选择','6402','其他业务成本','借','成本金额','',28),
			('172','','','','上门维修','手工选择','1405','库存商品','贷','成本金额','',28),
			('16','SCCZ001','生产拆装单模板','记','生产拆装单','手工选择','1405','库存商品','借','入库成本金额 减 出库成本金额','',28),
			('16','','','','生产拆装单','手工选择','1404','材料成本差异','贷','入库成本金额 减 出库成本金额','',28),
			('4','SKD001','收款单模板','记','收款单','单据上往来科目','','','贷','金额 加 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('4','','','','收款单','手工选择','6601','销售费用','借','抹零金额','',28),
			('4','','','','收款单','单据上收付款项目对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('145','STDXJS001','受托代销结算模板','记','受托代销结算','手工选择','2314','代理业务负债','借','折后金额','',28),
			('145','','','','受托代销结算','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('145','','','','受托代销结算','单据上往来科目','','','贷','价税合计 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('145','','','','受托代销结算','手工选择','2221','应交税费','借','税额','',28),
			('144','STDX001','受托代销收货模板','记','受托代销收货','手工选择','1321','代理业务资产','借','成本金额','',28),
			('144','','','','受托代销收货','手工选择','2314','代理业务负债','贷','成本金额','',28),
			('146','WTDX001','受托代销退货模板','记','受托代销退货','手工选择','1321','代理业务资产','贷','成本金额','',28),
			('146','','','','受托代销退货','手工选择','2314','代理业务负债','借','成本金额','',28),
			('170','SXFH001','送修返回单模板','记','送修返回','手工选择','6402','其他业务成本','借','维修费','',28),
			('170','','','','送修返回','单据上往来科目','','','贷','维修费 减 抹零金额 减 付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('170','','','','送修返回','单据上收付款项目对应科目','','','贷','付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('170','','','','送修返回','手工选择','6051','其他业务收入','贷',' 抹零金额','',28),
			('166','WXD001','维修单模板','记','维修单','手工选择','6402','其他业务成本','借','成本金额','',28),
			('166','','','','维修单','手工选择','1405','库存商品','贷','成本金额','',28),
			('174','WXSPDC001','维修品调出单模板','记','维修品调出','手工选择','1405','库存商品','借','成本金额','',28),
			('174','','','','维修品调出','手工选择','6402','其他业务成本','贷','成本金额','',28),
			('173','WXSPDR001','维修品调入单模板','记','维修品调入','手工选择','6402','其他业务成本','借','成本金额','',28),
			('173','','','','维修品调入','手工选择','1405','库存商品','贷','成本金额','',28),
			('167','WXQJ001','维修取件单模板','记','维修取件单','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('167','','','','维修取件单','单据上往来科目','','','借','维修费 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('167','','','','维修取件单','手工选择','6051','其他业务收入','贷','维修费 ','',28),
			('167','','','','维修取件单','手工选择','6601','销售费用','借','抹零金额','',28),
			('140','WTDX0001','委托代销凭证模板','记','委托代销商品发货','手工选择','1406','发出商品','借','成本金额','',28),
			('140','','','','委托代销商品发货','手工选择','1405','库存商品','贷','成本金额','',28),
			('141','WTDXJS0001','委托代销结算凭证模板','记','委托代销结算','单据上往来科目','','','借','价税合计 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('141','','','','委托代销结算','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('141','','','','委托代销结算','手工选择','6001','主营业务收入','贷','折后金额','',28),
			('141','','','','委托代销结算','手工选择','2221','应交税费','贷','税额','',28),
			('141','','','','委托代销结算','手工选择','6401','主营业务成本','借','成本金额','',28),
			('141','','','','委托代销结算','手工选择','1406','发出商品','贷','成本金额','',28),
			('142','WTDXTH0001','委托代销退货凭证模板','记','委托代销商品退货','手工选择','1406','发出商品','贷','成本金额','',28),
			('142','','','','委托代销商品退货','手工选择','1405','库存商品','借','成本金额','',28),
			('158','XJFY001','现金费用单模板','记','现金费用单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('158','','','','现金费用单','单据上收付款项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('11','XSCK0001','销售出库单凭证模板','记','商品销售出库','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('11','','','','商品销售出库','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('11','','','','商品销售出库','手工选择','6001','主营业务收入','贷','折后金额','',28),
			('11','','','','商品销售出库','手工选择','6601','销售费用','借','抹零金额','',28),
			('11','','','','商品销售出库','手工选择','2221','应交税费','贷','税额','',28),
			('11','','','','商品销售出库','手工选择','6401','主营业务成本','借','成本金额','',28),
			('11','','','','商品销售出库','手工选择','1405','库存商品','贷','成本金额','',28),
			('160','XSHH001','销售换货单凭证模板','记','商品销售换货','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('160','','','','商品销售换货','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('160','','','','商品销售换货','手工选择','6001','主营业务收入','贷','出库折后金额 减 入库折后金额','',28),
			('160','','','','商品销售换货','手工选择','6601','销售费用','借','抹零金额','',28),
			('160','','','','商品销售换货','手工选择','2221','应交税费','贷','出库税额 减 入库税额','',28),
			('160','','','','商品销售换货','手工选择','6401','主营业务成本','借','出库成本金额 减 入库成本金额','',28),
			('160','','','','商品销售换货','手工选择','1405','库存商品','贷','出库成本金额 减 入库成本金额','',28),
			('45','XSTH001','销售退货单凭证模板','记','商品销售退货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('45','','','','商品销售退货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('45','','','','商品销售退货','手工选择','6001','主营业务收入','借','折后金额','',28),
			('45','','','','商品销售退货','手工选择','6601','销售费用','贷','抹零金额','',28),
			('45','','','','商品销售退货','手工选择','2221','应交税费','借','税额','',28),
			('45','','','','商品销售退货','手工选择','6401','主营业务成本','贷','成本金额','',28),
			('45','','','','商品销售退货','手工选择','1405','库存商品','借','成本金额','',28),
			('159','YWPZ001','业务凭证模板','记','业务凭证','单据上借方项目对应科目','','','借','单据上当前借方项目金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('159','','','','业务凭证','单据上贷方项目对应科目','','','贷','单据上当前贷方项目金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('129','YFKJS001','应付款减少模板','记','应付款减少','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',28),
			('129','','','','应付款减少','手工选择','6402','其他业务成本','贷','金额 ','',28),
			('128','YFKZJ001','应付款增加模板','记','应付款增加','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',28),
			('128','','','','应付款增加','手工选择','6402','其他业务成本','借','金额 ','',28),
			('115','YSKJS001','应收款减少模板','记','应收款减少','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',28),
			('115','','','','应收款减少','手工选择','6051','其他业务收入','借','金额 ','',28),
			('116','YSKZJ001','应收款增加模板','记','应收款增加','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',28),
			('116','','','','应收款增加','手工选择','6051','其他业务收入','贷','金额 ','',28),
			('190','YFKD001','预付款单模板','记','预付款单','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('190','','','','预付款单','单据上收付款项目对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('189','YSKD001','预收款单模板','记','预收款','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('189','','','','预收款','单据上收付款项目对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('139','ZSD001','赠送单凭证模板','记','商品赠送','手工选择','6711','营业外支出','借','成本金额','',28),
			('139','','','','商品赠送','手工选择','1405','库存商品','贷','成本金额','',28),
			('168','ZJGH001','整机更换单模板','记','整机更换','单据上往来科目','','','借','维修费 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('168','','','','整机更换','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('168','','','','整机更换','手工选择','6051','其他业务收入','贷','维修费 ','',28),
			('168','','','','整机更换','手工选择','6601','销售费用','借','抹零金额','',28),
			('168','','','','整机更换','手工选择','6402','其他业务成本','借','成本金额','',28),
			('168','','','','整机更换','手工选择','1405','库存商品','贷','成本金额','',28),
			('77','ZKD001','转款单模板','记','转款单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('77','','','','转款单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
			('181','HYCZCZ001','会员储值充值单模板','记','会员储值充值单','手工选择','2203','预收账款','贷','充值金额','往来单位：往来单位',2),
			('181','','','','会员储值充值单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',2),
			('181','','','','会员储值充值单','手工选择','5601','销售费用','借','抹零金额','',2),
			('181','','','','会员储值充值单','单据上往来科目','','','借','充值金额 减 抹零金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',2),
			('9','BSD001','报损单模板','记','报损单','手工选择','1901','待处理财产损溢','借','成本金额','',2),
			('9','','','','报损单','手工选择','1405','库存商品','贷','成本金额','',2),
			('14','BYD001','报溢单模板','记','报溢单','手工选择','1405','库存商品','借','成本金额','',2),
			('14','','','','报溢单','手工选择','1901','待处理财产损溢','贷','成本金额','',2),
			('205','CGFYFT001','入库费用分摊单模板','记','采购费用分摊单','手工选择','1405','库存商品','借','分摊金额','',2),
			('205','','','','采购费用分摊单','单据上项目对应科目','','','贷','分摊金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('161','CGHH001','采购换货单凭证模板','记','采购换货','手工选择','1405','库存商品','借','入库成本金额 减 出库成本金额','',2),
			('161','','','','采购换货','手工选择','2221','应交税费','借','入库税额 减 出库税额','',2),
			('161','','','','采购换货','手工选择','2221','应交税费','借','材料成本差异税额','',2),
			('161','','','','采购换货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('161','','','','采购换货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('161','','','','采购换货','手工选择','5051','其他业务收入','贷','抹零金额','',2),
			('161','','','','采购换货','手工选择','1404','材料成本差异','贷','材料成本差异额','',2),
			('34','CGRK0001','采购入库单凭证模板','记','采购入库','手工选择','1405','库存商品','借','成本金额','',2),
			('34','','','','采购入库','手工选择','2221','应交税费','借','税额','',2),
			('34','','','','采购入库','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('34','','','','采购入库','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('34','','','','采购入库','手工选择','5051','其他业务收入','贷','抹零金额','',2),
			('6','CGTH001','采购退货单凭证模板','记','采购退货','手工选择','1405','库存商品','贷','成本金额','',2),
			('6','','','','采购退货','手工选择','2221','应交税费','贷','税额','',2),
			('6','','','','采购退货','手工选择','1404','材料成本差异','贷','材料成本差异额','',2),
			('6','','','','采购退货','单据上往来科目','','','借','抹零后金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('6','','','','采购退货','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('6','','','','采购退货','手工选择','5051','其他业务收入','借','抹零金额','',2),
			('6','','','','采购退货','手工选择','2221','应交税费','借','材料成本差异税额','',2),
			('57','CBTJ001','成本调价单模板','记','成本调价单','手工选择','1405','库存商品','借','调后金额 减 调前金额','',2),
			('57','','','','成本调价单','手工选择','1404','材料成本差异','贷','调后金额 减 调前金额','',2),
			('5','DTFYFS001','待摊费用发生模板','记','待摊费用发生','单据上项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('5','','','','待摊费用发生','手工选择','5402','其他业务成本','借','金额','',2),
			('10','DTFYTX001','待摊费用摊销模板','记','待摊费用摊销','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('10','','','','待摊费用摊销','手工选择','5402','其他业务成本','贷','金额','',2),
			('148','FLHS001','返利核算执行模板','记','返利核算执行','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('148','','','','返利核算执行','单据上往来科目','','','贷','返利金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('148','','','','返利核算执行','手工选择','5402','其他业务成本','借','返利金额','',2),
			('36','FYD001','费用单模板','记','费用单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('36','','','','费用单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('36','','','','费用单','单据上往来科目','','','贷','金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('66','FKD001','付款单模板','记','付款单','单据上往来科目','','','借','金额 加 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('66','','','','付款单','手工选择','5051','其他业务收入','贷','抹零金额','',2),
			('66','','','','付款单','单据上收付款项目对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('85','GDZCBM001','固定资产变卖模板','记','固定资产变卖','固定资产科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('85','','','','固定资产变卖','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('85','','','','固定资产变卖','单据上往来科目','','','借','金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('84','GDZCGM001','固定资产购买模板','记','固定资产购买','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('84','','','','固定资产购买','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('84','','','','固定资产购买','单据上往来科目','','','贷','金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('78','GDZCZJ001','固定资产折旧模板','记','固定资产折旧','固定资产科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('78','','','','固定资产折旧','手工选择','5402','其他业务成本','借','金额','',2),
			('151','HDJB001','获得价保单模板','记','获得价保单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('151','','','','获得价保单','单据上往来科目','','','借','应保价金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('151','','','','获得价保单','手工选择','5051','其他业务收入','贷','应保价金额','',2),
			('150','HLHS001','获利核算执行模板','记','获利核算执行','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('150','','','','获利核算执行','单据上往来科目','','','借','获利金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('150','','','','获利核算执行','手工选择','5051','其他业务收入','贷','获利金额','',2),
			('126','HZD001','获赠单凭证模板','记','获赠','手工选择','1405','库存商品','借','成本金额','',2),
			('126','','','','获赠','手工选择','5051','其他业务收入','贷','成本金额','',2),
			('183','JFDH001','积分兑换单模板','记','积分兑换单','手工选择','5601','销售费用','借','成本金额','',2),
			('183','','','','积分兑换单','手工选择','1405','库存商品','贷','成本金额','',2),
			('149','JBZX001','价保执行单模板','记','价保执行单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('149','','','','价保执行单','单据上往来科目','','','贷','应保价金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('149','','','','价保执行单','手工选择','5402','其他业务成本','借','应保价金额','',2),
			('305','LS0001','零售单凭证模板','记','销售商品','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('305','','','','销售商品','手工选择','5001','主营业务收入','贷','折后金额','',2),
			('305','','','','销售商品','手工选择','5401','主营业务成本','借','成本金额','',2),
			('305','','','','销售商品','手工选择','1405','库存商品','贷','成本金额','',2),
			('305','','','','销售商品','手工选择','5601','销售费用','借','抹零金额','',2),
			('202','QTCK001','其它出库单模板','记','其他出库单','单据上业务类型对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('202','','','','其他出库单','手工选择','1405','库存商品','贷','金额 ','',2),
			('201','QTRK001','其他入库单模板','记','其他入库单','手工选择','1405','库存商品','借','金额 ','',2),
			('201','','','','其他入库单','单据上业务类型对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('93','QTSR001','其他收入单模板','记','其他收入单','单据上项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('93','','','','其他收入单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('93','','','','其他收入单','单据上往来科目','','','借','金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('172','SMWX001','上门维修单模板','记','上门维修','单据上往来科目','','','借','维修费合计 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('172','','','','上门维修','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('172','','','','上门维修','手工选择','5051','其他业务收入','贷','维修费合计','',2),
			('172','','','','上门维修','手工选择','5601','销售费用','借','抹零金额','',2),
			('172','','','','上门维修','手工选择','5402','其他业务成本','借','成本金额','',2),
			('172','','','','上门维修','手工选择','1405','库存商品','贷','成本金额','',2),
			('16','SCCZ001','生产拆装单模板','记','生产拆装单','手工选择','1405','库存商品','借','入库成本金额 减 出库成本金额','',2),
			('16','','','','生产拆装单','手工选择','1404','材料成本差异','贷','入库成本金额 减 出库成本金额','',2),
			('4','SKD001','收款单模板','记','收款单','单据上往来科目','','','贷','金额 加 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('4','','','','收款单','手工选择','5601','销售费用','借','抹零金额','',2),
			('4','','','','收款单','单据上收付款项目对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('145','STDXJS001','受托代销结算模板','记','受托代销结算','手工选择','2202','应付账款','借','折后金额','往来单位：结算单位',2),
			('145','','','','受托代销结算','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('145','','','','受托代销结算','单据上往来科目','','','贷','价税合计 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('145','','','','受托代销结算','手工选择','2221','应交税费','借','税额','',2),
			('144','STDX001','受托代销收货模板','记','受托代销收货','手工选择','1408','委托加工物资','借','成本金额','',2),
			('144','','','','受托代销收货','手工选择','2202','应付账款','贷','成本金额','往来单位：结算单位',2),
			('146','WTDX001','受托代销退货模板','记','受托代销退货','手工选择','1408','委托加工物资','贷','成本金额','',2),
			('146','','','','受托代销退货','手工选择','2202','应付账款','借','成本金额','往来单位：结算单位',2),
			('170','SXFH001','送修返回单模板','记','送修返回','手工选择','5402','其他业务成本','借','维修费','',2),
			('170','','','','送修返回','单据上往来科目','','','贷','维修费 减 抹零金额 减 付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('170','','','','送修返回','单据上收付款项目对应科目','','','贷','付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('170','','','','送修返回','手工选择','5051','其他业务收入','贷',' 抹零金额','',2),
			('166','WXD001','维修单模板','记','维修单','手工选择','5402','其他业务成本','借','成本金额','',2),
			('166','','','','维修单','手工选择','1405','库存商品','贷','成本金额','',2),
			('174','WXSPDC001','维修品调出单模板','记','维修品调出','手工选择','1405','库存商品','借','成本金额','',2),
			('174','','','','维修品调出','手工选择','5402','其他业务成本','贷','成本金额','',2),
			('173','WXSPDR001','维修品调入单模板','记','维修品调入','手工选择','5402','其他业务成本','借','成本金额','',2),
			('173','','','','维修品调入','手工选择','1405','库存商品','贷','成本金额','',2),
			('167','WXQJ001','维修取件单模板','记','维修取件单','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('167','','','','维修取件单','单据上往来科目','','','借','维修费 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('167','','','','维修取件单','手工选择','5051','其他业务收入','贷','维修费 ','',2),
			('167','','','','维修取件单','手工选择','5601','销售费用','借','抹零金额','',2),
			('140','WTDX0001','委托代销凭证模板','记','委托代销商品发货','手工选择','1402','在途物资','借','成本金额','',2),
			('140','','','','委托代销商品发货','手工选择','1405','库存商品','贷','成本金额','',2),
			('141','WTDXJS0001','委托代销结算凭证模板','记','委托代销结算','单据上往来科目','','','借','价税合计 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('141','','','','委托代销结算','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('141','','','','委托代销结算','手工选择','5001','主营业务收入','贷','折后金额','',2),
			('141','','','','委托代销结算','手工选择','2221','应交税费','贷','税额','',2),
			('141','','','','委托代销结算','手工选择','5401','主营业务成本','借','成本金额','',2),
			('141','','','','委托代销结算','手工选择','1402','在途物资','贷','成本金额','',2),
			('142','WTDXTH0001','委托代销退货凭证模板','记','委托代销商品退货','手工选择','1402','在途物资','贷','成本金额','',2),
			('142','','','','委托代销商品退货','手工选择','1405','库存商品','借','成本金额','',2),
			('158','XJFY001','现金费用单模板','记','现金费用单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('158','','','','现金费用单','单据上收付款项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('11','XSCK0001','销售出库单凭证模板','记','商品销售出库','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('11','','','','商品销售出库','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('11','','','','商品销售出库','手工选择','5001','主营业务收入','贷','折后金额','',2),
			('11','','','','商品销售出库','手工选择','5601','销售费用','借','抹零金额','',2),
			('11','','','','商品销售出库','手工选择','2221','应交税费','贷','税额','',2),
			('11','','','','商品销售出库','手工选择','5401','主营业务成本','借','成本金额','',2),
			('11','','','','商品销售出库','手工选择','1405','库存商品','贷','成本金额','',2),
			('160','XSHH001','销售换货单凭证模板','记','商品销售换货','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('160','','','','商品销售换货','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('160','','','','商品销售换货','手工选择','5001','主营业务收入','贷','出库折后金额 减 入库折后金额','',2),
			('160','','','','商品销售换货','手工选择','5601','销售费用','借','抹零金额','',2),
			('160','','','','商品销售换货','手工选择','2221','应交税费','贷','出库税额 减 入库税额','',2),
			('160','','','','商品销售换货','手工选择','5401','主营业务成本','借','出库成本金额 减 入库成本金额','',2),
			('160','','','','商品销售换货','手工选择','1405','库存商品','贷','出库成本金额 减 入库成本金额','',2),
			('45','XSTH001','销售退货单凭证模板','记','商品销售退货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('45','','','','商品销售退货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('45','','','','商品销售退货','手工选择','5001','主营业务收入','借','折后金额','',2),
			('45','','','','商品销售退货','手工选择','5601','销售费用','贷','抹零金额','',2),
			('45','','','','商品销售退货','手工选择','2221','应交税费','借','税额','',2),
			('45','','','','商品销售退货','手工选择','5401','主营业务成本','贷','成本金额','',2),
			('45','','','','商品销售退货','手工选择','1405','库存商品','借','成本金额','',2),
			('159','YWPZ001','业务凭证模板','记','业务凭证','单据上借方项目对应科目','','','借','单据上当前借方项目金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('159','','','','业务凭证','单据上贷方项目对应科目','','','贷','单据上当前贷方项目金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('129','YFKJS001','应付款减少模板','记','应付款减少','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',2),
			('129','','','','应付款减少','手工选择','5402','其他业务成本','贷','金额 ','',2),
			('128','YFKZJ001','应付款增加模板','记','应付款增加','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',2),
			('128','','','','应付款增加','手工选择','5402','其他业务成本','借','金额 ','',2),
			('115','YSKJS001','应收款减少模板','记','应收款减少','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',2),
			('115','','','','应收款减少','手工选择','5051','其他业务收入','借','金额 ','',2),
			('116','YSKZJ001','应收款增加模板','记','应收款增加','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',2),
			('116','','','','应收款增加','手工选择','5051','其他业务收入','贷','金额 ','',2),
			('190','YFKD001','预付款单模板','记','预付款单','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('190','','','','预付款单','单据上收付款项目对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('189','YSKD001','预收款单模板','记','预收款','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('189','','','','预收款','单据上收付款项目对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('139','ZSD001','赠送单凭证模板','记','商品赠送','手工选择','5711','营业外支出','借','成本金额','',2),
			('139','','','','商品赠送','手工选择','1405','库存商品','贷','成本金额','',2),
			('168','ZJGH001','整机更换单模板','记','整机更换','单据上往来科目','','','借','维修费 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('168','','','','整机更换','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('168','','','','整机更换','手工选择','5051','其他业务收入','贷','维修费 ','',2),
			('168','','','','整机更换','手工选择','5601','销售费用','借','抹零金额','',2),
			('168','','','','整机更换','手工选择','5402','其他业务成本','借','成本金额','',2),
			('168','','','','整机更换','手工选择','1405','库存商品','贷','成本金额','',2),
			('77','ZKD001','转款单模板','记','转款单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('77','','','','转款单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
			('9','BSD001','报损单模板','记','报损单','手工选择','191101','待处理财产损溢','借','成本金额','',1),
			('9','','','','报损单','手工选择','1243','库存商品','贷','成本金额','',1),
			('14','BYD001','报溢单模板','记','报溢单','手工选择','1243','库存商品','借','成本金额','',1),
			('14','','','','报溢单','手工选择','191101','待处理财产损溢','贷','成本金额','',1),
			('205','CGFYFT001','入库费用分摊单模板','记','采购费用分摊单','手工选择','1243','库存商品','借','分摊金额','',1),
			('205','','','','采购费用分摊单','单据上项目对应科目','','','贷','分摊金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('161','CGHH001','采购换货单凭证模板','记','采购换货','手工选择','1243','库存商品','借','入库成本金额 减 出库成本金额','',1),
			('161','','','','采购换货','手工选择','21710101','进项税额','借','入库税额 减 出库税额','',1),
			('161','','','','采购换货','手工选择','21710101','进项税额','借','材料成本差异税额','',1),
			('161','','','','采购换货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('161','','','','采购换货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('161','','','','采购换货','手工选择','5102','其他业务收入','贷','抹零金额','',1),
			('161','','','','采购换货','手工选择','1232','材料成本差异','贷','材料成本差异额','',1),
			('34','CGRK0001','采购入库单凭证模板','记','采购入库','手工选择','1243','库存商品','借','成本金额','',1),
			('34','','','','采购入库','手工选择','21710101','进项税额','借','税额','',1),
			('34','','','','采购入库','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('34','','','','采购入库','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('34','','','','采购入库','手工选择','5102','其他业务收入','贷','抹零金额','',1),
			('6','CGTH001','采购退货单凭证模板','记','采购退货','手工选择','1243','库存商品','贷','成本金额','',1),
			('6','','','','采购退货','手工选择','21710101','进项税额','贷','税额','',1),
			('6','','','','采购退货','手工选择','1232','材料成本差异','贷','材料成本差异额','',1),
			('6','','','','采购退货','单据上往来科目','','','借','抹零后金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('6','','','','采购退货','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('6','','','','采购退货','手工选择','5102','其他业务收入','借','抹零金额','',1),
			('6','','','','采购退货','手工选择','21710101','进项税额','借','材料成本差异税额','',1),
			('57','CBTJ001','成本调价单模板','记','成本调价单','手工选择','1243','库存商品','借','调后金额 减 调前金额','',1),
			('57','','','','成本调价单','手工选择','1232','材料成本差异','贷','调后金额 减 调前金额','',1),
			('5','DTFYFS001','待摊费用发生模板','记','待摊费用发生','单据上项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('5','','','','待摊费用发生','手工选择','5405','其他业务支出','借','金额','',1),
			('10','DTFYTX001','待摊费用摊销模板','记','待摊费用摊销','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('10','','','','待摊费用摊销','手工选择','5405','其他业务支出','贷','金额','',1),
			('148','FLHS001','返利核算执行模板','记','返利核算执行','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('148','','','','返利核算执行','单据上往来科目','','','贷','返利金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('148','','','','返利核算执行','手工选择','5405','其他业务支出','借','返利金额','',1),
			('36','FYD001','费用单模板','记','费用单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('36','','','','费用单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('36','','','','费用单','单据上往来科目','','','贷','金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('66','FKD001','付款单模板','记','付款单','单据上往来科目','','','借','金额 加 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('66','','','','付款单','手工选择','5102','其他业务收入','贷','抹零金额','',1),
			('66','','','','付款单','单据上收付款项目对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('85','GDZCBM001','固定资产变卖模板','记','固定资产变卖','固定资产科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('85','','','','固定资产变卖','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('85','','','','固定资产变卖','单据上往来科目','','','借','金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('84','GDZCGM001','固定资产购买模板','记','固定资产购买','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('84','','','','固定资产购买','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('84','','','','固定资产购买','单据上往来科目','','','贷','金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('78','GDZCZJ001','固定资产折旧模板','记','固定资产折旧','固定资产科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('78','','','','固定资产折旧','手工选择','5405','其他业务支出','借','金额','',1),
			('181','HYCZCZ001','会员储值充值单模板','记','会员储值充值单','手工选择','2131','预收账款','贷','充值金额','往来单位：往来单位',1),
			('181','','','','会员储值充值单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',1),
			('181','','','','会员储值充值单','手工选择','5501','营业费用','借','抹零金额','',1),
			('181','','','','会员储值充值单','单据上往来科目','','','借','充值金额 减 抹零金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',1),
			('151','HDJB001','获得价保单模板','记','获得价保单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('151','','','','获得价保单','单据上往来科目','','','借','应保价金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('151','','','','获得价保单','手工选择','5102','其他业务收入','贷','应保价金额','',1),
			('150','HLHS001','获利核算执行模板','记','获利核算执行','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('150','','','','获利核算执行','单据上往来科目','','','借','获利金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('150','','','','获利核算执行','手工选择','5102','其他业务收入','贷','获利金额','',1),
			('126','HZD001','获赠单凭证模板','记','获赠','手工选择','1243','库存商品','借','成本金额','',1),
			('126','','','','获赠','手工选择','5102','其他业务收入','贷','成本金额','',1),
			('183','JFDH001','积分兑换单模板','记','积分兑换单','手工选择','5501','营业费用','借','成本金额','',1),
			('183','','','','积分兑换单','手工选择','1243','库存商品','贷','成本金额','',1),
			('149','JBZX001','价保执行单模板','记','价保执行单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('149','','','','价保执行单','单据上往来科目','','','贷','应保价金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('149','','','','价保执行单','手工选择','5405','其他业务支出','借','应保价金额','',1),
			('305','LS0001','零售单凭证模板','记','销售商品','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('305','','','','销售商品','手工选择','5101','主营业务收入','贷','折后金额','',1),
			('305','','','','销售商品','手工选择','5401','主营业务成本','借','成本金额','',1),
			('305','','','','销售商品','手工选择','1243','库存商品','贷','成本金额','',1),
			('305','','','','销售商品','手工选择','5501','营业费用','借','抹零金额','',1),
			('202','QTCK001','其它出库单模板','记','其他出库单','单据上业务类型对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('202','','','','其他出库单','手工选择','1243','库存商品','贷','金额 ','',1),
			('201','QTRK001','其他入库单模板','记','其他入库单','手工选择','1243','库存商品','借','金额 ','',1),
			('201','','','','其他入库单','单据上业务类型对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('93','QTSR001','其他收入单模板','记','其他收入单','单据上项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('93','','','','其他收入单','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('93','','','','其他收入单','单据上往来科目','','','借','金额 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('172','SMWX001','上门维修单模板','记','上门维修','单据上往来科目','','','借','维修费合计 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('172','','','','上门维修','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('172','','','','上门维修','手工选择','5102','其他业务收入','贷','维修费合计','',1),
			('172','','','','上门维修','手工选择','5501','营业费用','借','抹零金额','',1),
			('172','','','','上门维修','手工选择','5405','其他业务支出','借','成本金额','',1),
			('172','','','','上门维修','手工选择','1243','库存商品','贷','成本金额','',1),
			('16','SCCZ001','生产拆装单模板','记','生产拆装单','手工选择','1243','库存商品','借','入库成本金额 减 出库成本金额','',1),
			('16','','','','生产拆装单','手工选择','1232','材料成本差异','贷','入库成本金额 减 出库成本金额','',1),
			('4','SKD001','收款单模板','记','收款单','单据上往来科目','','','贷','金额 加 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('4','','','','收款单','手工选择','5501','营业费用','借','抹零金额','',1),
			('4','','','','收款单','单据上收付款项目对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('145','STDXJS001','受托代销结算模板','记','受托代销结算','手工选择','2141','代销商品款','借','折后金额','',1),
			('145','','','','受托代销结算','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('145','','','','受托代销结算','单据上往来科目','','','贷','价税合计 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('145','','','','受托代销结算','手工选择','21710101','进项税额','借','税额','',1),
			('144','STDX001','受托代销收货模板','记','受托代销收货','手工选择','1271','受托代销商品','借','成本金额','',1),
			('144','','','','受托代销收货','手工选择','2141','代销商品款','贷','成本金额','',1),
			('146','WTDX001','受托代销退货模板','记','受托代销退货','手工选择','1271','受托代销商品','贷','成本金额','',1),
			('146','','','','受托代销退货','手工选择','2141','代销商品款','借','成本金额','',1),
			('170','SXFH001','送修返回单模板','记','送修返回','手工选择','5405','其他业务支出','借','维修费','',1),
			('170','','','','送修返回','单据上往来科目','','','贷','维修费 减 抹零金额 减 付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('170','','','','送修返回','单据上收付款项目对应科目','','','贷','付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('170','','','','送修返回','手工选择','5102','其他业务收入','贷',' 抹零金额','',1),
			('166','WXD001','维修单模板','记','维修单','手工选择','5405','其他业务支出','借','成本金额','',1),
			('166','','','','维修单','手工选择','1243','库存商品','贷','成本金额','',1),
			('174','WXSPDC001','维修品调出单模板','记','维修品调出','手工选择','1243','库存商品','借','成本金额','',1),
			('174','','','','维修品调出','手工选择','5405','其他业务支出','贷','成本金额','',1),
			('173','WXSPDR001','维修品调入单模板','记','维修品调入','手工选择','5405','其他业务支出','借','成本金额','',1),
			('173','','','','维修品调入','手工选择','1243','库存商品','贷','成本金额','',1),
			('167','WXQJ001','维修取件单模板','记','维修取件单','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('167','','','','维修取件单','单据上往来科目','','','借','维修费 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('167','','','','维修取件单','手工选择','5102','其他业务收入','贷','维修费 ','',1),
			('167','','','','维修取件单','手工选择','5501','营业费用','借','抹零金额','',1),
			('140','WTDX0001','委托代销凭证模板','记','委托代销商品发货','手工选择','1261','委托代销商品 ','借','成本金额','',1),
			('140','','','','委托代销商品发货','手工选择','1243','库存商品','贷','成本金额','',1),
			('141','WTDXJS0001','委托代销结算凭证模板','记','委托代销结算','单据上往来科目','','','借','价税合计 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('141','','','','委托代销结算','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('141','','','','委托代销结算','手工选择','5101','主营业务收入','贷','折后金额','',1),
			('141','','','','委托代销结算','手工选择','21710105','销项税额','贷','税额','',1),
			('141','','','','委托代销结算','手工选择','5401','主营业务成本','借','成本金额','',1),
			('141','','','','委托代销结算','手工选择','1261','委托代销商品 ','贷','成本金额','',1),
			('142','WTDXTH0001','委托代销退货凭证模板','记','委托代销商品退货','手工选择','1261','委托代销商品 ','贷','成本金额','',1),
			('142','','','','委托代销商品退货','手工选择','1243','库存商品','借','成本金额','',1),
			('158','XJFY001','现金费用单模板','记','现金费用单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('158','','','','现金费用单','单据上收付款项目对应科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('11','XSCK0001','销售出库单凭证模板','记','商品销售出库','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('11','','','','商品销售出库','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('11','','','','商品销售出库','手工选择','5101','主营业务收入','贷','折后金额','',1),
			('11','','','','商品销售出库','手工选择','5501','营业费用','借','抹零金额','',1),
			('11','','','','商品销售出库','手工选择','21710105','销项税额','贷','税额','',1),
			('11','','','','商品销售出库','手工选择','5401','主营业务成本','借','成本金额','',1),
			('11','','','','商品销售出库','手工选择','1243','库存商品','贷','成本金额','',1),
			('160','XSHH001','销售换货单凭证模板','记','商品销售换货','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('160','','','','商品销售换货','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('160','','','','商品销售换货','手工选择','5101','主营业务收入','贷','出库折后金额 减 入库折后金额','',1),
			('160','','','','商品销售换货','手工选择','5501','营业费用','借','抹零金额','',1),
			('160','','','','商品销售换货','手工选择','21710105','销项税额','贷','出库税额 减 入库税额','',1),
			('160','','','','商品销售换货','手工选择','5401','主营业务成本','借','出库成本金额 减 入库成本金额','',1),
			('160','','','','商品销售换货','手工选择','1243','库存商品','贷','出库成本金额 减 入库成本金额','',1),
			('45','XSTH001','销售退货单凭证模板','记','商品销售退货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('45','','','','商品销售退货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('45','','','','商品销售退货','手工选择','5101','主营业务收入','借','折后金额','',1),
			('45','','','','商品销售退货','手工选择','5501','营业费用','贷','抹零金额','',1),
			('45','','','','商品销售退货','手工选择','21710105','销项税额','借','税额','',1),
			('45','','','','商品销售退货','手工选择','5401','主营业务成本','贷','成本金额','',1),
			('45','','','','商品销售退货','手工选择','1243','库存商品','借','成本金额','',1),
			('159','YWPZ001','业务凭证模板','记','业务凭证','单据上借方项目对应科目','','','借','单据上当前借方项目金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('159','','','','业务凭证','单据上贷方项目对应科目','','','贷','单据上当前贷方项目金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('129','YFKJS001','应付款减少模板','记','应付款减少','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',1),
			('129','','','','应付款减少','手工选择','5405','其他业务支出','贷','金额 ','',1),
			('128','YFKZJ001','应付款增加模板','记','应付款增加','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',1),
			('128','','','','应付款增加','手工选择','5405','其他业务支出','借','金额 ','',1),
			('115','YSKJS001','应收款减少模板','记','应收款减少','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',1),
			('115','','','','应收款减少','手工选择','5102','其他业务收入','借','金额 ','',1),
			('116','YSKZJ001','应收款增加模板','记','应收款增加','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：单位',1),
			('116','','','','应收款增加','手工选择','5102','其他业务收入','贷','金额 ','',1),
			('190','YFKD001','预付款单模板','记','预付款单','单据上往来科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('190','','','','预付款单','单据上收付款项目对应科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('189','YSKD001','预收款单模板','记','预收款','单据上往来科目','','','贷','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('189','','','','预收款','单据上收付款项目对应科目','','','借','金额 ','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('139','ZSD001','赠送单凭证模板','记','商品赠送','手工选择','5601','营业外支出','借','成本金额','',1),
			('139','','','','商品赠送','手工选择','1243','库存商品','贷','成本金额','',1),
			('168','ZJGH001','整机更换单模板','记','整机更换','单据上往来科目','','','借','维修费 减 抹零金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('168','','','','整机更换','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('168','','','','整机更换','手工选择','5102','其他业务收入','贷','维修费 ','',1),
			('168','','','','整机更换','手工选择','5501','营业费用','借','抹零金额','',1),
			('168','','','','整机更换','手工选择','5405','其他业务支出','借','成本金额','',1),
			('168','','','','整机更换','手工选择','1243','库存商品','贷','成本金额','',1),
			('77','ZKD001','转款单模板','记','转款单','单据上项目对应科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
			('77','','','','转款单','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE BillType = 212)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          AuditType
	        )
	VALUES('212','GDZCGRHS001','固定资产购入模板（原值含税）','记','固定资产购入','固定资产科目','','','借','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,1),
('212','','','','固定资产购入','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,1),
('212','','','','固定资产购入','单据上往来科目','','','贷','价税合计 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,1),
('212','GDZCGRHS001','固定资产购入模板（原值含税）','记','固定资产购入','固定资产科目','','','借','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,1),
('212','','','','固定资产购入','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,1),
('212','','','','固定资产购入','单据上往来科目','','','贷','价税合计 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,1),
('212','GDZCGRHS001','固定资产购入模板（原值含税）','记','固定资产购入','固定资产科目','','','借','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,1),
('212','','','','固定资产购入','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,1),
('212','','','','固定资产购入','单据上往来科目','','','贷','价税合计 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,1),

('212','GDZCGRBHS001','固定资产购入模板（原值不含税）','记','固定资产购入','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,2),
('212','','','','固定资产购入','手工选择','2221','应交税费','借','税额','',28,2),
('212','','','','固定资产购入','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,2),
('212','','','','固定资产购入','单据上往来科目','','','贷','金额 加 税额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,2),
('212','GDZCGRBHS001','固定资产购入模板（原值不含税）','记','固定资产购入','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,2),
('212','','','','固定资产购入','手工选择','2221','应交税费','借','税额','',2,2),
('212','','','','固定资产购入','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,2),
('212','','','','固定资产购入','单据上往来科目','','','贷','金额 加 税额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,2),
('212','GDZCGRBHS001','固定资产购入模板（原值不含税）','记','固定资产购入','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,2),
('212','','','','固定资产购入','手工选择','21710101 ','进项税额','借','税额','',1,2),
('212','','','','固定资产购入','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,2),
('212','','','','固定资产购入','单据上往来科目','','','贷','金额 加 税额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,2),

('212','GDZCZJ001','固定资产自建工程模板','记','固定资产自建工程','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,3),
('212','','','','固定资产自建工程','手工选择','1604','在建工程','贷','金额','',28,3),
('212','GDZCZJ001','固定资产自建工程模板','记','固定资产自建工程','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,3),
('212','','','','固定资产自建工程','手工选择','1604','在建工程','贷','金额','',2,3),
('212','GDZCZJ001','固定资产自建工程模板','记','固定资产自建工程','固定资产科目','','','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,3),
('212','','','','固定资产自建工程','手工选择','1603','在建工程','贷','金额','',1,3),

('212','GDZCGSJZ001','固定资产接受捐赠模板','记','固定资产接受捐赠','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,5),
('212','','','','固定资产接受捐赠','固定资产累计折旧科目','','','贷','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,5),
('212','','','','固定资产接受捐赠','手工选择','6301','营业外收入','贷','平衡数','',28,5),
('212','GDZCGSJZ001','固定资产接受捐赠模板','记','固定资产接受捐赠','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,5),
('212','','','','固定资产接受捐赠','固定资产累计折旧科目','','','贷','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,5),
('212','','','','固定资产接受捐赠','手工选择','5301','营业外收入','贷','平衡数','',2,5),
('212','GDZCGSJZ001','固定资产接受捐赠模板','记','固定资产接受捐赠','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,5),
('212','','','','固定资产接受捐赠','固定资产累计折旧科目','','','贷','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,5),
('212','','','','固定资产接受捐赠','手工选择','5301','营业外收入','贷','平衡数','',1,5),

('212','GDZCPY001','固定资产盘盈模板','记','固定资产盘盈','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,6),
('212','','','','固定资产盘盈','固定资产累计折旧科目','','','贷','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,6),
('212','','','','固定资产盘盈','手工选择','1901','待处理财产损溢','贷','平衡数','',28,6),
('212','GDZCPY001','固定资产盘盈模板','记','固定资产盘盈','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,6),
('212','','','','固定资产盘盈','固定资产累计折旧科目','','','贷','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,6),
('212','','','','固定资产盘盈','手工选择','1901','待处理财产损溢','贷','平衡数','',2,6),
('212','GDZCPY001','固定资产盘盈模板','记','固定资产盘盈','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,6),
('212','','','','固定资产盘盈','固定资产累计折旧科目','','','贷','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,6),
('212','','','','固定资产盘盈','手工选择','191102','待处理固定资产损溢','贷','平衡数','',1,6),

('213','GDZCBM001','固定资产变卖模板','记','固定资产变卖','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,7),
('213','','','','固定资产变卖','单据上往来科目','','','借','价税合计 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,7),
('213','','','','固定资产变卖','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,7),
('213','','','','固定资产变卖','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,7),
('213','','','','固定资产变卖','手工选择','2221','应交税费','贷','税额','',28,7),
('213','','','','固定资产变卖','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,7),
('213','','','','固定资产变卖','手工选择','6301','营业外收入','贷','平衡数','',28,7),
('213','GDZCBM001','固定资产变卖模板','记','固定资产变卖','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,7),
('213','','','','固定资产变卖','单据上往来科目','','','借','价税合计 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,7),
('213','','','','固定资产变卖','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,7),
('213','','','','固定资产变卖','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,7),
('213','','','','固定资产变卖','手工选择','2221','应交税费','贷','税额','',2,7),
('213','','','','固定资产变卖','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,7),
('213','','','','固定资产变卖','手工选择','5301','营业外收入','贷','平衡数','',2,7),
('213','GDZCBM001','固定资产变卖模板','记','固定资产变卖','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,7),
('213','','','','固定资产变卖','单据上往来科目','','','借','价税合计 减 实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,7),
('213','','','','固定资产变卖','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,7),
('213','','','','固定资产变卖','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,7),
('213','','','','固定资产变卖','手工选择','21710105 ','销项税额','贷','税额','',1,7),
('213','','','','固定资产变卖','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,7),
('213','','','','固定资产变卖','手工选择','5301','营业外收入','贷','平衡数','',1,7),

('213','GDZCBF001','固定资产报废模板','记','固定资产报废','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,8),
('213','','','','固定资产报废','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,8),
('213','','','','固定资产报废','手工选择','6711','营业外支出','借','平衡数','',28,8),
('213','','','','固定资产报废','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,8),
('213','GDZCBF001','固定资产报废模板','记','固定资产报废','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,8),
('213','','','','固定资产报废','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,8),
('213','','','','固定资产报废','手工选择','5711','营业外支出','借','平衡数','',2,8),
('213','','','','固定资产报废','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,8),
('213','GDZCBF001','固定资产报废模板','记','固定资产报废','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,8),
('213','','','','固定资产报废','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,8),
('213','','','','固定资产报废','手工选择','5601','营业外支出','借','平衡数','',1,8),
('213','','','','固定资产报废','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,8),

('213','GDZCTZZC001','固定资产投资转出模板','记','固定资产投资转出','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,9),
('213','','','','固定资产投资转出','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,9),
('213','','','','固定资产投资转出','手工选择','1511','长期股权投资','借','平衡数','',28,9),
('213','','','','固定资产投资转出','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,9),
('213','GDZCTZZC001','固定资产投资转出模板','记','固定资产投资转出','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,9),
('213','','','','固定资产投资转出','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,9),
('213','','','','固定资产投资转出','手工选择','1511','长期股权投资','借','平衡数','',2,9),
('213','','','','固定资产投资转出','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,9),
('213','GDZCTZZC001','固定资产投资转出模板','记','固定资产投资转出','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,9),
('213','','','','固定资产投资转出','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,9),
('213','','','','固定资产投资转出','手工选择','140102','其他股权投资','借','平衡数','',1,9),
('213','','','','固定资产投资转出','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,9),

('213','GDZCGZZC001','固定资产捐赠转出模板','记','固定资产捐赠转出','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,10),
('213','','','','固定资产捐赠转出','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,10),
('213','','','','固定资产捐赠转出','手工选择','6711','营业外支出','借','平衡数','',28,10),
('213','','','','固定资产捐赠转出','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,10),
('213','GDZCGZZC001','固定资产捐赠转出模板','记','固定资产捐赠转出','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,10),
('213','','','','固定资产捐赠转出','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,10),
('213','','','','固定资产捐赠转出','手工选择','5711','营业外支出','借','平衡数','',2,10),
('213','','','','固定资产捐赠转出','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,10),
('213','GDZCGZZC001','固定资产捐赠转出模板','记','固定资产捐赠转出','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,10),
('213','','','','固定资产捐赠转出','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,10),
('213','','','','固定资产捐赠转出','手工选择','5601','营业外支出','借','平衡数','',1,10),
('213','','','','固定资产捐赠转出','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,10),

('213','GDZCPK001','固定资产盘亏模板','记','固定资产盘亏','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,11),
('213','','','','固定资产盘亏','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,11),
('213','','','','固定资产盘亏','手工选择','1901','待处理财产损溢','借','平衡数','',28,11),
('213','','','','固定资产盘亏','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,11),
('213','GDZCPK001','固定资产盘亏模板','记','固定资产盘亏','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,11),
('213','','','','固定资产盘亏','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,11),
('213','','','','固定资产盘亏','手工选择','1901','待处理财产损溢','借','平衡数','',2,11),
('213','','','','固定资产盘亏','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,11),
('213','GDZCPK001','固定资产盘亏模板','记','固定资产盘亏','固定资产累计折旧科目','','','借','累计折旧','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,11),
('213','','','','固定资产盘亏','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,11),
('213','','','','固定资产盘亏','手工选择','191102','待处理固定资产损溢','借','平衡数','',1,11),
('213','','','','固定资产盘亏','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,11),

('214','GDZCZJ001','固定资产折旧模板','记','固定资产折旧','固定资产累计折旧科目','','','贷','固定资产折旧额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,14),
('214','','','','固定资产折旧','固定资产折旧分配科目','','','借','固定资产折旧额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,14),
('214','GDZCZJ001','固定资产折旧模板','记','固定资产折旧','固定资产累计折旧科目','','','贷','固定资产折旧额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,14),
('214','','','','固定资产折旧','固定资产折旧分配科目','','','借','固定资产折旧额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,14),
('214','GDZCZJ001','固定资产折旧模板','记','固定资产折旧','固定资产累计折旧科目','','','贷','固定资产折旧额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,14),
('214','','','','固定资产折旧','固定资产折旧分配科目','','','借','固定资产折旧额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,14),

('-1','GDZCBMZY001','固定资产部门转移模板','记','固定资产部门转移','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',28,12),
('-1','','','','固定资产部门转移','固定资产累计折旧科目','','','借','固定资产折旧额','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',28,12),
('-1','','','','固定资产部门转移','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',28,12),
('-1','','','','固定资产部门转移','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',28,12),
('-1','','','','固定资产部门转移','固定资产累计折旧科目','','','贷','固定资产折旧额','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',28,12),
('-1','','','','固定资产部门转移','固定资产减值准备科目','','','贷','固定资产减值准备','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',28,12),
('-1','GDZCBMZY001','固定资产部门转移模板','记','固定资产部门转移','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',2,12),
('-1','','','','固定资产部门转移','固定资产累计折旧科目','','','借','固定资产折旧额','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',2,12),
('-1','','','','固定资产部门转移','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',2,12),
('-1','','','','固定资产部门转移','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',2,12),
('-1','','','','固定资产部门转移','固定资产累计折旧科目','','','贷','固定资产折旧额','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',2,12),
('-1','','','','固定资产部门转移','固定资产减值准备科目','','','贷','固定资产减值准备','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',2,12),
('-1','GDZCBMZY001','固定资产部门转移模板','记','固定资产部门转移','固定资产科目','','','贷','固定资产原值','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',1,12),
('-1','','','','固定资产部门转移','固定资产累计折旧科目','','','借','固定资产折旧额','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',1,12),
('-1','','','','固定资产部门转移','固定资产减值准备科目','','','借','固定资产减值准备','分支机构：分支机构，部门：原部门，职员：经手人，往来单位：往来单位',1,12),
('-1','','','','固定资产部门转移','固定资产科目','','','借','固定资产原值','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',1,12),
('-1','','','','固定资产部门转移','固定资产累计折旧科目','','','贷','固定资产折旧额','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',1,12),
('-1','','','','固定资产部门转移','固定资产减值准备科目','','','贷','固定资产减值准备','分支机构：分支机构，部门：新部门，职员：经手人，往来单位：往来单位',1,12),

('-2','JTZCJZZB001','计提资产减值准备模板','记','计提资产减值准备','手工选择','6701','资产减值损失','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',28,13),
('-2','','','','计提资产减值准备','固定资产减值准备科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',28,13),
('-2','JTZCJZZB001','计提资产减值准备模板','记','计提资产减值准备','手工选择','5711','营业外支出','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',2,13),
('-2','','','','计提资产减值准备','固定资产减值准备科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',2,13),
('-2','JTZCJZZB001','计提资产减值准备模板','记','计提资产减值准备','手工选择','5601','营业外支出','借','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',1,13),
('-2','','','','计提资产减值准备','固定资产减值准备科目','','','贷','金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',1,13)
END
GO


IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE BillType = 215)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId 
	        )
	VALUES
	('215','LSTH0001','零售退货单凭证模板','记','销售商品退货','单据上收付款项目对应科目','','','贷','付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
	('215','','','','销售商品退货','手工选择','6001','主营业务收入','借','折后金额','',28),
	('215','','','','销售商品退货','手工选择','6401','主营业务成本','贷','成本金额','',28),
	('215','','','','销售商品退货','手工选择','1405','库存商品','借','成本金额','',28),
	('215','','','','销售商品退货','手工选择','6601','销售费用','贷','抹零金额','',28),
	('215','LSTH0001','零售退货单凭证模板','记','销售商品退货','单据上收付款项目对应科目','','','贷','付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
	('215','','','','销售商品退货','手工选择','5001','主营业务收入','借','折后金额','',2),
	('215','','','','销售商品退货','手工选择','5401','主营业务成本','贷','成本金额','',2),
	('215','','','','销售商品退货','手工选择','1405','库存商品','借','成本金额','',2),
	('215','','','','销售商品退货','手工选择','5601','销售费用','贷','抹零金额','',2),
	('215','LSTH0001','零售退货单凭证模板','记','销售商品退货','单据上收付款项目对应科目','','','贷','付款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
	('215','','','','销售商品退货','手工选择','5101','主营业务收入','借','折后金额','',1),
	('215','','','','销售商品退货','手工选择','5401','主营业务成本','贷','成本金额','',1),
	('215','','','','销售商品退货','手工选择','1243','库存商品','借','成本金额','',1),
	('215','','','','销售商品退货','手工选择','5501','营业费用','贷','抹零金额','',1)
END
GO
--调整9.1中已有预置数据
IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype IN (78,84,85) AND atypefrom = '单据上项目对应固定资产科目' )
BEGIN
	UPDATE dbo.VoucherTemplatePreset SET atypefrom = '固定资产科目' WHERE Billtype IN (78,84,85) AND atypefrom = '单据上项目对应固定资产科目' 
END
GO

--9.3新加单据模板
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 147)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId 
	        )
	VALUES
	('147','STDXTJ0001','受托代销调价凭证模板','记','受托代销调价','手工选择','6401','主营业务成本','借','调整差额','',28),
	('147','','','','受托代销调价','手工选择','2141','代销商品款','贷','调整差额','',28),
	('147','STDXTJ0001','受托代销调价凭证模板','记','受托代销调价','手工选择','5401','主营业务成本','借','调整差额','',2),
	('147','','','','受托代销调价','手工选择','2202','应付账款','贷','调整差额','往来单位：结算单位',2),
	('147','STDXTJ0001','受托代销调价凭证模板','记','受托代销调价','手工选择','5401','主营业务成本','借','调整差额','',1),
	('147','','','','受托代销调价','手工选择','2141','代销商品款','贷','调整差额','',1)
END
GO
--删除 小企业会计制度下 计提减值
IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = -2 AND SubId = 2)
BEGIN
	DELETE FROM dbo.VoucherTemplatePreset WHERE Billtype = -2 AND SubId = 2
END
GO

--资产调拨单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 310)
BEGIN
	--调出
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          InOutType
	        )
	VALUES
	('310','ZJDBC01','资金调拨单凭证模板（调出）','记','资金调出业务','手工选择','1221','其他应收款','借','调拨金额','往来单位：往来单位',28,-1),
	('310','','','','资金调出业务','手工选择','6603','财务费用','借','手续费金额','',28,-1),
	('310','','','','资金调出业务','单据上账户对应科目','','','贷','调拨总额（现金）','分支机构：调入分支机构，部门：部门，职员：经手人，往来单位：往来单位',28,-1),
	('310','','','','资金调出业务','单据上账户对应科目','','','贷','调拨总额（账户）','分支机构：调入分支机构，部门：部门，职员：经手人，往来单位：往来单位',28,-1),
	
	('310','ZJDBC01','资金调拨单凭证模板（调出）','记','资金调出业务','手工选择','1221','其他应收款','借','调拨金额','往来单位：往来单位',2,-1),
	('310','','','','资金调出业务','手工选择','5603','财务费用','借','手续费金额','',2,-1),
	('310','','','','资金调出业务','单据上账户对应科目','','','贷','调拨总额（现金）','分支机构：调入分支机构，部门：部门，职员：经手人，往来单位：往来单位',2,-1),
	('310','','','','资金调出业务','单据上账户对应科目','','','贷','调拨总额（账户）','分支机构：调入分支机构，部门：部门，职员：经手人，往来单位：往来单位',2,-1),
	
	('310','ZJDBC01','资金调拨单凭证模板（调出）','记','资金调出业务','手工选择','1133','其他应收款','借','调拨金额','往来单位：往来单位',1,-1),
	('310','','','','资金调出业务','手工选择','5503','财务费用','借','手续费金额','',1,-1),
	('310','','','','资金调出业务','单据上账户对应科目','','','贷','调拨总额（现金）','分支机构：调入分支机构，部门：部门，职员：经手人，往来单位：往来单位',1,-1),
	('310','','','','资金调出业务','单据上账户对应科目','','','贷','调拨总额（账户）','分支机构：调入分支机构，部门：部门，职员：经手人，往来单位：往来单位',1,-1)
	
	--调入
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          InOutType
	        )
	VALUES
	('310','ZJDBR01','资金调拨单凭证模板（调入）','记','资金调入业务','单据上账户对应科目','','','借','调拨总额（现金）','分支机构：调出分支机构，部门：部门，职员：经手人，往来单位：往来单位',28,1),
	('310','','','','资金调入业务','单据上账户对应科目','','','借','调拨总额（账户）','分支机构：调出分支机构，部门：部门，职员：经手人，往来单位：往来单位',28,1),
	('310','','','','资金调入业务','手工选择','2241','其他应付款','贷','调拨金额','往来单位：往来单位',28,1),
	('310','','','','资金调入业务','手工选择','6603','财务费用','贷','手续费金额','',28,1),
	
	('310','ZJDBR01','资金调拨单凭证模板（调入）','记','资金调入业务','单据上账户对应科目','','','借','调拨总额（现金）','分支机构：调出分支机构，部门：部门，职员：经手人，往来单位：往来单位',2,1),
	('310','','','','资金调入业务','单据上账户对应科目','','','借','调拨总额（账户）','分支机构：调出分支机构，部门：部门，职员：经手人，往来单位：往来单位',2,1),
	('310','','','','资金调入业务','手工选择','2241','其他应付款','贷','调拨金额','往来单位：往来单位',2,1),
	('310','','','','资金调入业务','手工选择','5603','财务费用','贷','手续费金额','',2,1),
	
	('310','ZJDBR01','资金调拨单凭证模板（调入）','记','资金调入业务','单据上账户对应科目','','','借','调拨总额（现金）','分支机构：调出分支机构，部门：部门，职员：经手人，往来单位：往来单位',1,1),
	('310','','','','资金调入业务','单据上账户对应科目','','','借','调拨总额（账户）','分支机构：调出分支机构，部门：部门，职员：经手人，往来单位：往来单位',1,1),
	('310','','','','资金调入业务','手工选择','2181','其他应付款','贷','调拨金额','往来单位：往来单位',1,1),
	('310','','','','资金调入业务','手工选择','5503','财务费用','贷','手续费金额','',1,1)
END
GO

--提成单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE billtype = 311)
BEGIN
		INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
		VALUES
		('311','TCD001','提成单凭证模板','记','业务员提成','手工选择','6601','销售费用','借','提成金额','',28),
		('311','','','','业务员提成','手工选择','2211','应付职工薪酬','贷','提成金额','',28),
		('311','TCD001','提成单凭证模板','记','业务员提成','手工选择','5601','销售费用','借','提成金额','',2),
		('311','','','','业务员提成','手工选择','2211','应付职工薪酬','贷','提成金额','',2),
		('311','TCD001','提成单凭证模板','记','业务员提成','手工选择','5501','营业费用','借','提成金额','',1),
		('311','','','','业务员提成','手工选择','2151','应付工资','贷','提成金额','',1)
END
GO

--9.4添加服务类商品后调整模板
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 34 AND totalfrom = '成本金额(服务商品)')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES	('34','','','','采购入库','手工选择','6402','其他业务成本','借','成本金额(服务商品)','',28),
			('34','','','','采购入库','手工选择','5402','其他业务成本','借','成本金额(服务商品)','',2),
			('34','','','','采购入库','手工选择','5405','其他业务成本','借','成本金额(服务商品)','',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 6 AND totalfrom = '成本金额(服务商品)')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES	('6','','','','采购退货','手工选择','6402','其他业务成本','贷','成本金额(服务商品)','',28),
			('6','','','','采购退货','手工选择','5402','其他业务成本','贷','成本金额(服务商品)','',2),
			('6','','','','采购退货','手工选择','5405','其他业务成本','贷','成本金额(服务商品)','',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 161 AND totalfrom = '入库成本金额(服务商品) 减 出库成本金额(服务商品)')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES	('161','','','','采购换货','手工选择','6402','其他业务成本','借','入库成本金额(服务商品) 减 出库成本金额(服务商品)','',28),
			('161','','','','采购换货','手工选择','5402','其他业务成本','借','入库成本金额(服务商品) 减 出库成本金额(服务商品)','',2),
			('161','','','','采购换货','手工选择','5405','其他业务成本','借','入库成本金额(服务商品) 减 出库成本金额(服务商品)','',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 305 AND totalfrom = '折后金额(服务商品)')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES	('305','','','','销售商品','手工选择','6051','其他业务收入','贷','折后金额(服务商品)','',28),
			('305','','','','销售商品','手工选择','5051','其他业务收入','贷','折后金额(服务商品)','',2),
			('305','','','','销售商品','手工选择','5102','其他业务收入','贷','折后金额(服务商品)','',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 11 AND totalfrom = '折后金额(服务商品)')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES	('11','','','','商品销售出库','手工选择','6051','其他业务收入','贷','折后金额(服务商品)','',28),
			('11','','','','商品销售出库','手工选择','5051','其他业务收入','贷','折后金额(服务商品)','',2),
			('11','','','','商品销售出库','手工选择','5102','其他业务收入','贷','折后金额(服务商品)','',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 215 AND totalfrom = '折后金额(服务商品)')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES	('215','','','','销售商品退货','手工选择','6051','其他业务收入','借','折后金额(服务商品)','',28),
			('215','','','','销售商品退货','手工选择','5051','其他业务收入','借','折后金额(服务商品)','',2),
			('215','','','','销售商品退货','手工选择','5102','其他业务收入','借','折后金额(服务商品)','',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 45 AND totalfrom = '折后金额(服务商品)')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES	('45','','','','商品销售退货','手工选择','6051','其他业务收入','借','折后金额(服务商品)','',28),
			('45','','','','商品销售退货','手工选择','5051','其他业务收入','借','折后金额(服务商品)','',2),
			('45','','','','商品销售退货','手工选择','5102','其他业务收入','借','折后金额(服务商品)','',1)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 160 AND totalfrom = '出库折后金额(服务商品) 减 入库折后金额(服务商品)')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	VALUES	('160','','','','商品销售换货','手工选择','6051','其他业务收入','贷','出库折后金额(服务商品) 减 入库折后金额(服务商品)','',28),
			('160','','','','商品销售换货','手工选择','5051','其他业务收入','贷','出库折后金额(服务商品) 减 入库折后金额(服务商品)','',2),
			('160','','','','商品销售换货','手工选择','5102','其他业务收入','贷','出库折后金额(服务商品) 减 入库折后金额(服务商品)','',1)
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 161 AND totalfrom = '入库成本金额 减 出库成本金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset 
	SET totalfrom = '入库成本金额(库存商品) 减 出库成本金额(库存商品)'
	WHERE Billtype = 161 AND totalfrom = '入库成本金额 减 出库成本金额'
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 34 AND totalfrom = '成本金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset
	SET totalfrom = '成本金额(库存商品)'
	WHERE Billtype = 34 AND totalfrom = '成本金额'
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 6 AND totalfrom = '成本金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset
	SET totalfrom = '成本金额(库存商品)'
	WHERE Billtype = 6 AND totalfrom = '成本金额'
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 305 AND totalfrom = '折后金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset
	SET totalfrom = '折后金额(库存商品)'
	WHERE Billtype = 305 AND totalfrom = '折后金额'
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 215 AND totalfrom = '折后金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset
	SET totalfrom = '折后金额(库存商品)'
	WHERE Billtype = 215 AND totalfrom = '折后金额'
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype =  11 AND totalfrom = '折后金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset
	SET totalfrom = '折后金额(库存商品)'
	WHERE Billtype = 11 AND totalfrom = '折后金额'
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 45 AND totalfrom = '折后金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset
	SET totalfrom = '折后金额(库存商品)'
	WHERE Billtype = 45 AND totalfrom = '折后金额'
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 160 AND totalfrom = '出库折后金额 减入库折后金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset
	SET totalfrom = '出库折后金额(库存商品) 减 入库折后金额(库存商品)'
	WHERE Billtype = 160 AND totalfrom = '出库折后金额 减入库折后金额'
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 160 AND totalfrom = '出库折后金额 减 入库折后金额')
BEGIN
	UPDATE dbo.VoucherTemplatePreset
	SET totalfrom = '出库折后金额(库存商品) 减 入库折后金额(库存商品)'
	WHERE Billtype = 160 AND totalfrom = '出库折后金额 减 入库折后金额'
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 145 AND atypefullname='库存商品')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	 VALUES
	('145','','','','受托代销结算','手工选择','1271','受托代销商品','贷','折后金额','',1),
	('145','','','','受托代销结算','手工选择','1243','库存商品','借','折后金额','',1),	
	('145','','','','受托代销结算','手工选择','1408','委托加工物资','贷','折后金额','',2),
	('145','','','','受托代销结算','手工选择','1405','库存商品','借','折后金额','',2),
	('145','','','','受托代销结算','手工选择','1321','代理业务资产','贷','折后金额','',28),
	('145','','','','受托代销结算','手工选择','1405','库存商品','借','折后金额','',28)
END
GO

DELETE FROM VoucherTemplatePreset WHERE Billtype = 312
--会员批量储值充值单 312
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 312)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	 VALUES
	('312','HYPLCZ001','会员批量储值单模板','记','会员批量储值充值单','手工选择','2131','预收账款','贷','充值金额合计','往来单位：结算单位',1),
	('312','','','','会员批量储值充值单','单据上收付款项目对应科目','','','借','实收金额合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
	('312','','','','会员批量储值充值单','手工选择','5501','营业费用','借','抹零金额合计','',1),
	('312','','','','会员批量储值充值单','单据上往来科目','','','借','充值金额合计 减 抹零金额合计 减 实收金额合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
	
	('312','HYPLCZ001','会员批量储值单模板','记','会员批量储值充值单','手工选择','2203','预收账款','贷','充值金额合计','往来单位：结算单位',2),
	('312','','','','会员批量储值充值单','单据上收付款项目对应科目','','','借','实收金额合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
	('312','','','','会员批量储值充值单','手工选择','5601','销售费用','借','抹零金额合计','',2),
	('312','','','','会员批量储值充值单','单据上往来科目','','','借','充值金额合计 减 抹零金额合计 减 实收金额合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
	
	('312','HYPLCZ001','会员批量储值单模板','记','会员批量储值充值单','手工选择','2203','预收账款','贷','充值金额合计','往来单位：结算单位',28),
	('312','','','','会员批量储值充值单','单据上收付款项目对应科目','','','借','实收金额合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
	('312','','','','会员批量储值充值单','手工选择','6601','销售费用','借','抹零金额合计','',28),
	('312','','','','会员批量储值充值单','单据上往来科目','','','借','充值金额合计 减 抹零金额合计 减 实收金额合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 400)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId
	        )
	 VALUES
	 --暂估入库单 400
	('400','ZGRK001','暂估入库单模板','记','暂估入库单','手工选择','1405','库存商品','借','成本金额','',28),
	('400','','','','暂估入库单','单据上往来科目','','','贷','成本金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
	('400','ZGRK001','暂估入库单模板','记','暂估入库单','手工选择','1405','库存商品','借','成本金额','',2),
	('400','','','','暂估入库单','单据上往来科目','','','贷','成本金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
	('400','ZGRK001','暂估入库单模板','记','暂估入库单','手工选择','1243','库存商品','借','成本金额','',1),
	('400','','','','暂估入库单','单据上往来科目','','','贷','成本金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),

	--暂估退货单
	('401','ZGTH001','暂估退货单模板','记','暂估退货单','单据上往来科目','','','借','成本金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
	('401','','','','暂估退货单','手工选择','1405','库存商品','贷','成本金额','',28),
	('401','ZGTH001','暂估退货单模板','记','暂估退货单','单据上往来科目','','','借','成本金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
	('401','','','','暂估退货单','手工选择','1405','库存商品','贷','成本金额','',2),
	('401','ZGTH001','暂估退货单模板','记','暂估退货单','单据上往来科目','','','借','成本金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
	('401','','','','暂估退货单','手工选择','1243','库存商品','贷','成本金额','',1),

	--发出商品出库
	('402','FCSPCK001','发出商品出库单模板','记','发出商品出库单','手工选择','1406','发出商品','借','成本金额','',28),
	('402','','','','发出商品出库单','手工选择','1405','库存商品','贷','成本金额','',28),
	('402','FCSPCK001','发出商品出库单模板','记','发出商品出库单','手工选择','1406','发出商品','借','成本金额','',2),
	('402','','','','发出商品出库单','手工选择','1405','库存商品','贷','成本金额','',2),
	('402','FCSPCK001','发出商品出库单模板','记','发出商品出库单','手工选择','1242','发出商品','借','成本金额','',1),
	('402','','','','发出商品出库单','手工选择','1243','库存商品','贷','成本金额','',1),
	
	--发出商品退货
	('403','FCSPTH001','发出商品退货单模板','记','发出商品退货单','手工选择','1405','库存商品','借','成本金额','',28),
	('403','','','','发出商品退货单','手工选择','1406','发出商品','贷','成本金额','',28),
	('403','FCSPTH001','发出商品退货单模板','记','发出商品退货单','手工选择','1405','库存商品','借','成本金额','',2),
	('403','','','','发出商品退货单','手工选择','1406','发出商品','贷','成本金额','',2),
	('403','FCSPTH001','发出商品退货单模板','记','发出商品退货单','手工选择','1243','库存商品','借','成本金额','',1),
	('403','','','','发出商品退货单','手工选择','1242','发出商品','贷','成本金额','',1),
	
	--采购暂估开票
	('404','CGZGKP001','采购暂估开票模板','记','采购暂估开票','单据上往来科目（借）','','','借','采购金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
	('404','','','','采购暂估开票','手工选择','2221','应交税费','借','税额','',28),
	('404','','','','采购暂估开票','单据上往来科目（贷）','','','贷','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
	('404','CGZGKP001','采购暂估开票模板','记','采购暂估开票','单据上往来科目（借）','','','借','采购金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
	('404','','','','采购暂估开票','手工选择','2221','应交税费','借','税额','',2),
	('404','','','','采购暂估开票','单据上往来科目（贷）','','','贷','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
	('404','CGZGKP001','采购暂估开票模板','记','采购暂估开票','单据上往来科目（借）','','','借','采购金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
	('404','','','','采购暂估开票','手工选择','21710101','进项税额','借','税额','',1),
	('404','','','','采购暂估开票','单据上往来科目（贷）','','','贷','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
	
	--销售发货开票
	('405','XSFHKP001','销售发货开票模板','记','销售发货开票','单据上往来科目','','','借','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28),
	('405','','','','销售发货开票','手工选择','6001','主营业务收入','贷','销售金额','',28),
	('405','','','','销售发货开票','手工选择','2221','应交税费','贷','税额','',28),
	('405','','','','销售发货开票','手工选择','6401','主营业务成本','借','本次开票成本','',28),
	('405','','','','销售发货开票','手工选择','1406','发出商品','贷','本次开票成本','',28),
	('405','XSFHKP001','销售发货开票模板','记','销售发货开票','单据上往来科目','','','借','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2),
	('405','','','','销售发货开票','手工选择','5001','主营业务收入','贷','销售金额','',2),
	('405','','','','销售发货开票','手工选择','2221','应交税费','贷','税额','',2),
	('405','','','','销售发货开票','手工选择','5401','主营业务成本','借','本次开票成本','',2),
	('405','','','','销售发货开票','手工选择','1406','发出商品','贷','本次开票成本','',2),
	('405','XSFHKP001','销售发货开票模板','记','销售发货开票','单据上往来科目','','','借','价税合计','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1),
	('405','','','','销售发货开票','手工选择','5101','主营业务收入','贷','销售金额','',1),
	('405','','','','销售发货开票','手工选择','21710105','消项税额','贷','税额','',1),
	('405','','','','销售发货开票','手工选择','5401','主营业务成本','借','本次开票成本','',1),
	('405','','','','销售发货开票','手工选择','1242','发出商品','贷','本次开票成本','',1)
		
	--成本调价（库存） InOutType=0  成本调价（入库） InOutType=1 成本调价（出库-销出） InOutType=2 
	UPDATE VoucherTemplatePreset SET InOutType=0 WHERE Billtype=57 AND InOutType IS NULL
	INSERT INTO dbo.VoucherTemplatePreset
        ( Billtype ,
          usercode ,
          fullname ,
          groupfullname ,
          summary ,
          atypefrom ,
          atypeusercode ,
          atypefullname ,
          dc ,
          totalfrom ,
          assitems ,
          SubId,
          InOutType
        )
	VALUES
	--入库
	('57','CBTJRK01','成本调价（入库）凭证模板','记','成本调价（入库）','手工选择','1405','库存商品','借','调整金额','',28,1),
	('57','','','','成本调价（入库）','单据上往来科目','','','贷','调整金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,1),
	('57','CBTJRK01','成本调价（入库）凭证模板','记','成本调价（入库）','手工选择','1405','库存商品','借','调整金额','',2,1),
	('57','','','','成本调价（入库）','单据上往来科目','','','贷','调整金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,1),
	('57','CBTJRK01','成本调价（入库）凭证模板','记','成本调价（入库）','手工选择','1243','库存商品','借','调整金额','',1,1),
	('57','','','','成本调价（入库）','单据上往来科目','','','贷','调整金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,1),
	
	--出库
	('57','CBTJCK01','成本调价（出库-销出）凭证模板','记','成本调价（出库-销出）','手工选择','6401','主营业务成本','借','调整金额','',28,2),
	('57','','','','成本调价（出库-销出）','手工选择','1405','库存商品','贷','调整金额','',28,2),
	('57','CBTJCK01','成本调价（出库-销出）凭证模板','记','成本调价（出库-销出）','手工选择','5401','主营业务成本','借','调整金额','',2,2),
	('57','','','','成本调价（出库-销出）','手工选择','1405','库存商品','贷','调整金额','',2,2),
	('57','CBTJCK01','成本调价（出库-销出）凭证模板','记','成本调价（出库-销出）','手工选择','5401','主营业务成本','借','调整金额','',1,2),
	('57','','','','成本调价（出库-销出）','手工选择','1243','库存商品','贷','调整金额','',1,2)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 450)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	 --往来核销单 应收冲应付 450 0
	('450','WLHX01','往来核销单应收冲应付模板','记','往来核销单','手工选择','220201','应付货款','借','核销金额','往来单位：结算单位',28,0),
	('450','','','','往来核销单','手工选择','1122','应收账款','贷','核销金额','往来单位：结算单位',28,0),
	('450','WLHX01','往来核销单应收冲应付模板','记','往来核销单','手工选择','220201','应付货款','借','核销金额','往来单位：结算单位',2,0),
	('450','','','','往来核销单','手工选择','1122','应收账款','贷','核销金额','往来单位：结算单位',2,0),
	('450','WLHX01','往来核销单应收冲应付模板','记','往来核销单','手工选择','212101','应付货款','借','核销金额','往来单位：结算单位',1,0),
	('450','','','','往来核销单','手工选择','1131','应收账款','贷','核销金额','往来单位：结算单位',1,0),

	--往来核销单 预收冲预付 450 1
	('450','WLHX02','往来核销单预收冲预付模板','记','往来核销单','手工选择','2203','预收账款','借','核销金额','往来单位：结算单位',28,1),
	('450','','','','往来核销单','手工选择','1123','预付账款','贷','核销金额','往来单位：结算单位',28,1),
	('450','WLHX02','往来核销单预收冲预付模板','记','往来核销单','手工选择','2203','预收账款','借','核销金额','往来单位：结算单位',2,1),
	('450','','','','往来核销单','手工选择','1123','预付账款','贷','核销金额','往来单位：结算单位',2,1),
	('450','WLHX02','往来核销单预收冲预付模板','记','往来核销单','手工选择','2131','预收账款','借','核销金额','往来单位：结算单位',1,1),
	('450','','','','往来核销单','手工选择','1151','预付账款','贷','核销金额','往来单位：结算单位',1,1),

	--往来核销单 应收转应收 450 2
	('450','WLHX03','往来核销单应收转应收模板','记','往来核销单','手工选择','1122','应收账款','借','核销金额','往来单位：结算单位',28,2),
	('450','','','','往来核销单','手工选择','1122','应收账款','贷','核销金额','往来单位：结算单位',28,2),
	('450','WLHX03','往来核销单应收转应收模板','记','往来核销单','手工选择','1122','应收账款','借','核销金额','往来单位：结算单位',2,2),
	('450','','','','往来核销单','手工选择','1122','应收账款','贷','核销金额','往来单位：结算单位',2,2),
	('450','WLHX03','往来核销单应收转应收模板','记','往来核销单','手工选择','1131','应收账款','借','核销金额','往来单位：结算单位',1,2),
	('450','','','','往来核销单','手工选择','1131','应收账款','贷','核销金额','往来单位：结算单位',1,2),
	
	--往来核销单 应付转应付 450 3
	('450','WLHX04','往来核销单应付转应付模板','记','往来核销单','手工选择','220201','应付货款','借','核销金额','往来单位：结算单位',28,3),
	('450','','','','往来核销单','手工选择','220201','应付货款','贷','核销金额','往来单位：结算单位',28,3),
	('450','WLHX04','往来核销单应付转应付模板','记','往来核销单','手工选择','220201','应付货款','借','核销金额','往来单位：结算单位',2,3),
	('450','','','','往来核销单','手工选择','220201','应付货款','贷','核销金额','往来单位：结算单位',2,3),
	('450','WLHX04','往来核销单应付转应付模板','记','往来核销单','手工选择','212101','应付货款','借','核销金额','往来单位：结算单位',1,3),
	('450','','','','往来核销单','手工选择','212101','应付货款','贷','核销金额','往来单位：结算单位',1,3),
	
	--往来核销单 预收转应付 450 4
	('450','WLHX05','往来核销单预收转应付模板','记','往来核销单','手工选择','2203','预收账款','借','核销金额','往来单位：结算单位',28,4),
	('450','','','','往来核销单','手工选择','220201','应付货款','贷','核销金额','往来单位：结算单位',28,4),
	('450','WLHX05','往来核销单预收转应付模板','记','往来核销单','手工选择','2203','预收账款','借','核销金额','往来单位：结算单位',2,4),
	('450','','','','往来核销单','手工选择','220201','应付货款','贷','核销金额','往来单位：结算单位',2,4),
	('450','WLHX05','往来核销单预收转应付模板','记','往来核销单','手工选择','2131','预收账款','借','核销金额','往来单位：结算单位',1,4),
	('450','','','','往来核销单','手工选择','212101','应付货款','贷','核销金额','往来单位：结算单位',1,4),
	
	--往来核销单 预付转应收 450 5
	('450','WLHX06','往来核销单预付转应收模板','记','往来核销单','手工选择','1122','应收账款','借','核销金额','往来单位：结算单位',28,5),
	('450','','','','往来核销单','手工选择','1123','预付账款','贷','核销金额','往来单位：结算单位',28,5),
	('450','WLHX06','往来核销单预付转应收模板','记','往来核销单','手工选择','1122','应收账款','借','核销金额','往来单位：结算单位',2,5),
	('450','','','','往来核销单','手工选择','1123','预付账款','贷','核销金额','往来单位：结算单位',2,5),
	('450','WLHX06','往来核销单预付转应收模板','记','往来核销单','手工选择','1131','应收账款','借','核销金额','往来单位：结算单位',1,5),
	('450','','','','往来核销单','手工选择','1151','预付账款','贷','核销金额','往来单位：结算单位',1,5)
		
	
END
GO

--9.6将应付账款分类了
IF EXISTS(SELECT *FROM VoucherTemplatePreset WHERE atypeusercode='2202' AND atypefullname='应付账款' AND SubId='2')
BEGIN
	UPDATE VoucherTemplatePreset SET atypeusercode='220201' , atypefullname='应付货款'  WHERE atypeusercode='2202' AND atypefullname='应付账款' AND SubId='2'
END
--组合品销售出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 12)
	BEGIN
		INSERT INTO dbo.VoucherTemplatePreset
		( 
			Billtype ,
			usercode ,
			fullname ,
			groupfullname ,
			summary ,
			atypefrom ,
			atypeusercode ,
			atypefullname ,
			dc ,
			totalfrom ,
			assitems ,
			SubId,
			isCost
		)
		VALUES
			('12','ZXSCK0001','组合品销售出库单凭证模板','记','商品组合品销售出库','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,0),
			('12','','','','商品组合品销售出库','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,0),
			('12','','','','商品组合品销售出库','手工选择','6001','主营业务收入','贷','折后金额(库存商品)','',28,0),
			('12','','','','商品组合品销售出库','手工选择','6051','其他业务收入','贷','折后金额(服务商品)','',28,0),
			('12','','','','商品组合品销售出库','手工选择','6601','销售费用','借','抹零金额','',28,0),
			('12','','','','商品组合品销售出库','手工选择','2221','应交税费','贷','税额','',28,0),
			('12','','','','商品组合品销售出库','手工选择','6401','主营业务成本','借','成本金额','',28,1),
			('12','','','','商品组合品销售出库','手工选择','1405','库存商品','贷','成本金额','',28,1),

			('12','ZXSCK0001','组合品销售出库单凭证模板','记','商品组合品销售出库','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,0),
			('12','','','','商品组合品销售出库','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,0),
			('12','','','','商品组合品销售出库','手工选择','5001','主营业务收入','贷','折后金额(库存商品)','',2,0),
			('12','','','','商品组合品销售出库','手工选择','5051','其他业务收入','贷','折后金额(服务商品)','',2,0),
			('12','','','','商品组合品销售出库','手工选择','5601','销售费用','借','抹零金额','',2,0),
			('12','','','','商品组合品销售出库','手工选择','2221','应交税费','贷','税额','',2,0),
			('12','','','','商品组合品销售出库','手工选择','5401','主营业务成本','借','成本金额','',2,1),
			('12','','','','商品组合品销售出库','手工选择','1405','库存商品','贷','成本金额','',2,1),

			('12','ZXSCK0001','组合品销售出库单凭证模板','记','商品组合品销售出库','单据上往来科目','','','借','抹零后金额 减 收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,0),
			('12','','','','商品组合品销售出库','单据上收付款项目对应科目','','','借','收款金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,0),
			('12','','','','商品组合品销售出库','手工选择','5101','主营业务收入','贷','折后金额(库存商品)','',1,0),
			('12','','','','商品组合品销售出库','手工选择','5102','其他业务收入','贷','折后金额(服务商品)','',1,0),	
			('12','','','','商品组合品销售出库','手工选择','5501','营业费用','借','抹零金额','',1,0),
			('12','','','','商品组合品销售出库','手工选择','21710105','销项税额','贷','税额','',1,0),
			('12','','','','商品组合品销售出库','手工选择','5401','主营业务成本','借','成本金额','',1,1),
			('12','','','','商品组合品销售出库','手工选择','1243','库存商品','贷','成本金额','',1,1)
	END
--组合品销售退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 46)
	BEGIN
		INSERT INTO dbo.VoucherTemplatePreset
		( 
			Billtype ,
			usercode ,
			fullname ,
			groupfullname ,
			summary ,
			atypefrom ,
			atypeusercode ,
			atypefullname ,
			dc ,
			totalfrom ,
			assitems ,
			SubId,
			isCost
		)
		VALUES
			('46','ZXSTH0001','组合品销售退货单凭证模板','记','组合品销售退货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,0),
			('46','','','','组合品销售退货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,0),
			('46','','','','组合品销售退货','手工选择','6001','主营业务收入','借','折后金额(库存商品)','',28,0),
			('46','','','','组合品销售退货','手工选择','6051','其他业务收入','借','折后金额(服务商品)','',28,0),
			('46','','','','组合品销售退货','手工选择','6601','销售费用','贷','抹零金额','',28,0),
			('46','','','','组合品销售退货','手工选择','2221','应交税费','借','税额','',28,0),
			('46','','','','组合品销售退货','手工选择','6401','主营业务成本','贷','成本金额','',28,1),
			('46','','','','组合品销售退货','手工选择','1405','库存商品','借','成本金额','',28,1),
		
			('46','ZXSTH0001','组合品销售退货单凭证模板','记','组合品销售退货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,0),
			('46','','','','组合品销售退货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,0),
			('46','','','','组合品销售退货','手工选择','5001','主营业务收入','借','折后金额(库存商品)','',2,0),
			('46','','','','组合品销售退货','手工选择','5051','其他业务收入','借','折后金额(服务商品)','',2,0),
			('46','','','','组合品销售退货','手工选择','5601','销售费用','贷','抹零金额','',2,0),
			('46','','','','组合品销售退货','手工选择','2221','应交税费','借','税额','',2,0),
			('46','','','','组合品销售退货','手工选择','5401','主营业务成本','贷','成本金额','',2,1),
			('46','','','','组合品销售退货','手工选择','1405','库存商品','借','成本金额','',2,1),

			('46','ZXSTH0001','组合品销售退货单凭证模板','记','组合品销售退货','单据上往来科目','','','贷','抹零后金额 减 实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,0),
			('46','','','','组合品销售退货','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,0),
			('46','','','','组合品销售退货','手工选择','5101','主营业务收入','借','折后金额(库存商品)','',1,0),
			('46','','','','组合品销售退货','手工选择','5102','其他业务收入','借','折后金额(服务商品)','',1,0),
			('46','','','','组合品销售退货','手工选择','5501','营业费用','贷','抹零金额','',1,0),
			('46','','','','组合品销售退货','手工选择','21710105','销项税额','借','税额','',1,0),
			('46','','','','组合品销售退货','手工选择','5401','主营业务成本','贷','成本金额','',1,1),
			('46','','','','组合品销售退货','手工选择','1243','库存商品','借','成本金额','',1,1)
	END
--select *from Ac_Account_Set_List
--select *from BillName where Billtype>=400
DELETE FROM dbo.VoucherTemplatePreset WHERE Billtype = 410
/*
---固定资产原值变更
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype =410 )
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
		( 
			Billtype ,
			usercode ,
			fullname ,
			groupfullname ,
			summary ,
			atypefrom ,
			atypeusercode ,
			atypefullname ,
			dc ,
			totalfrom ,
			assitems ,
			SubId
		)
		VALUES
			---新会计准则凭证模板
			('410','GDZCBGD001','固定资产变更单模板','记','固定资产变更单凭证','固定资产科目','','','借','入账原值差异','',28),
			('410','','','','固定资产变更单凭证','固定资产折旧分配科目','','','借','累计折旧差异','',28),
			('410','','','','固定资产变更单凭证','入账原值差异科目','','','贷','入账原值差异-汇率影响原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',28),
			('410','','','','固定资产变更单凭证','汇率影响原值科目','','','贷','汇率影响原值','',28),
			('410','','','','固定资产变更单凭证','固定资产累计折旧科目','','','贷','累计折旧差异','',28),
			---小企业会计准则凭证模板
			('410','GDZCBGD001','固定资产变更单模板','记','固定资产变更单凭证','固定资产科目','','','借','入账原值差异','',2),
			('410','','','','固定资产变更单凭证','固定资产折旧分配科目','','','借','累计折旧差异','',2),
			('410','','','','固定资产变更单凭证','入账原值差异科目','','','贷','入账原值差异-汇率影响原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',2),
			('410','','','','固定资产变更单凭证','汇率影响原值科目','','','贷','汇率影响原值','',2),
			('410','','','','固定资产变更单凭证','固定资产累计折旧科目','','','贷','累计折旧差异','',2),
			--企业会计制度凭证模板
			('410','GDZCBGD001','固定资产变更单模板','记','固定资产变更单凭证','固定资产科目','','','借','入账原值差异','',1),
			('410','','','','固定资产变更单凭证','固定资产折旧分配科目','','','借','累计折旧差异','',1),
			('410','','','','固定资产变更单凭证','入账原值差异科目','','','贷','入账原值差异-汇率影响原值','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',1),
			('410','','','','固定资产变更单凭证','汇率影响原值科目','','','贷','汇率影响原值','',1),
			('410','','','','固定资产变更单凭证','固定资产累计折旧科目','','','贷','累计折旧差异','',1)
END
*/
---运输配送单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype =414 )
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
		( 
			Billtype ,
			usercode ,
			fullname ,
			groupfullname ,
			summary ,
			atypefrom ,
			atypeusercode ,
			atypefullname ,
			dc ,
			totalfrom ,
			assitems ,
			SubId
		)
		VALUES
			---新会计准则凭证模板
			('414','YSPS001','运输配送单凭证模板','记','商品运输配送','单据上往来科目','','','贷','合计运费 减 付款金额','',28),
			('414','','','','商品运输配送','单据上收付款项目对应科目','','','贷','付款金额','',28),
			('414','','','','商品运输配送','手工选择','6601','销售费用','借','合计运费*（1-税率）','',28),
			('414','','','','商品运输配送','手工选择','2221','应交税费','借','合计运费*税率','',28),
			---小企业会计准则凭证模板
			('414','YSPS001','运输配送单凭证模板','记','商品运输配送','单据上往来科目','','','贷','合计运费 减 付款金额','',2),
			('414','','','','商品运输配送','单据上收付款项目对应科目','','','贷','付款金额','',2),
			('414','','','','商品运输配送','手工选择','5601','销售费用','借','合计运费*（1-税率）','',2),
			('414','','','','商品运输配送','手工选择','2221','应交税费','借','合计运费*税率','',2),
			--企业会计制度凭证模板
			('414','YSPS001','运输配送单凭证模板','记','商品运输配送','单据上往来科目','','','贷','合计运费 减 付款金额','',1),
			('414','','','','商品运输配送','单据上收付款项目对应科目','','','贷','付款金额','',1),
			('414','','','','商品运输配送','手工选择','5501','营业费用','借','合计运费*（1-税率）','',1),
			('414','','','','商品运输配送','手工选择','21710101','进项税额','借','合计运费*税率','',1)
END
--===============================983新增【BEGIN】===============================
 --9.8.3优惠券入库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 423)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	 ---新会计准则凭证模板
	('423','YHRK0001','优惠券入库单凭证模板','记','优惠券入库','手工选择','6601','销售费用','借','成本金额','',28,null),
	('423','','','','优惠券入库','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,null),
	('423','','','','优惠券入库','单据上往来科目','','','贷','成本金额 减 收付款金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,null),
	('423','','','','优惠券入库','手工选择','6051','其他业务收入','贷','抹零金额','',28,null),	
	---小企业会计准则凭证模板
	('423','YHRK0001','优惠券入库单凭证模板','记','优惠券入库','手工选择','5601','销售费用','借','成本金额','',2,null),
	('423','','','','优惠券入库','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,null),
	('423','','','','优惠券入库','单据上往来科目','','','贷','成本金额 减 收付款金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,null),
	('423','','','','优惠券入库','手工选择','5051','其他业务收入','贷','抹零金额','',2,null),
	--企业会计制度凭证模板	
	('423','YHRK0001','优惠券入库单凭证模板','记','优惠券入库','手工选择','5501','营业费用','借','成本金额','',1,null),
	('423','','','','优惠券入库','单据上收付款项目对应科目','','','贷','实付金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,null),
	('423','','','','优惠券入库','单据上往来科目','','','贷','成本金额 减 收付款金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,null),
	('423','','','','优惠券入库','手工选择','5102','其他业务收入','贷','抹零金额','',1,null)
END
GO
--优惠券出库单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 424)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	  ---新会计准则凭证模板
	('424','YHCK0001','优惠券出库单凭证模板','记','优惠券出库','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,null),
	('424','','','','优惠券出库','手工选择','6601','销售费用','借','代金券面值 减 代金券金额 加 抹零金额','',28,null),
	('424','','','','优惠券出库','单据上往来科目','','','借','金额 减 实收金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',28,null),
    ('424','','','','优惠券出库','手工选择','6051','其他业务收入','贷','折扣券金额','',28,null),
    ('424','','','','优惠券出库','手工选择','2203','预收账款','贷','代金券面值 加 兑换券出库金额','往来单位：往来单位',28,null),
    ---小企业会计准则凭证模板
    ('424','YHCK0001','优惠券出库单凭证模板','记','优惠券出库','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,null),
    ('424','','','','优惠券出库','手工选择','5601','销售费用','借','代金券面值 减 代金券金额 加 抹零金额','',2,null),
    ('424','','','','优惠券出库','单据上往来科目','','','借','金额 减 实收金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',2,null),
    ('424','','','','优惠券出库','手工选择','5051','其他业务收入','贷','折扣券金额','',2,null),
    ('424','','','','优惠券出库','手工选择','2203','预收账款','贷','代金券面值 加 兑换券出库金额','往来单位：往来单位',2,null),
    
    --企业会计制度凭证模板
    ('424','YHCK0001','优惠券出库单凭证模板','记','优惠券出库','单据上收付款项目对应科目','','','借','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,null),
    ('424','','','','优惠券出库','手工选择','5501','营业费用','借','代金券面值 减 代金券金额 加 抹零金额','',1,null),
    ('424','','','','优惠券出库','单据上往来科目','','','借','金额 减 实收金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',1,null),
    ('424','','','','优惠券出库','手工选择','5102','其他业务收入','贷','折扣券金额','',1,null),
    ('424','','','','优惠券出库','手工选择','2131','预收账款','贷','代金券面值 加 兑换券出库金额','往来单位：往来单位',1,null)
END
GO
--优惠券退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 426)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	  ---新会计准则凭证模板
	('426','YHTK0001','优惠券退库单凭证模板','记','优惠券退库','手工选择','6051','其他业务收入','借','折扣券金额','',28,null),
	('426','','','','优惠券退库','手工选择','2203','预收账款','借','代金券面值 加 兑换券出库金额','往来单位：往来单位',28,null),
    ('426','','','','优惠券退库','单据上收付款项目对应科目','','','贷','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',28,null),
    ('426','','','','优惠券退库','手工选择','6601','销售费用','贷','代金券面值 减 代金券金额 加 抹零金额','',28,null),
    ('426','','','','优惠券退库','单据上往来科目','','','贷','金额 减 实付金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',28,null),
    ('426','','','','优惠券退库','手工选择','6051','其他业务收入','贷','兑换券出库金额 减 兑换券退货金额','',28,null),
    ---小企业会计准则凭证模板
	('426','YHTK0001','优惠券退库单凭证模板','记','优惠券退库','手工选择','5051','其他业务收入','借','折扣券金额','',2,null),
	('426','','','','优惠券退库','手工选择','2203','预收账款','借','代金券面值 加 兑换券出库金额','往来单位：往来单位',2,null),
    ('426','','','','优惠券退库','单据上收付款项目对应科目','','','贷','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',2,null),
    ('426','','','','优惠券退库','手工选择','5601','销售费用','贷','代金券面值 减 代金券金额 加 抹零金额','',2,null),
    ('426','','','','优惠券退库','单据上往来科目','','','贷','金额 减 实付金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',2,null),
    ('426','','','','优惠券退库','手工选择','5051','其他业务收入','贷','兑换券出库金额 减 兑换券退货金额','',2,null),
    --企业会计制度凭证模板
	('426','YHTK0001','优惠券退库单凭证模板','记','优惠券退库','手工选择','5102','其他业务收入','借','折扣券金额','',1,null),
	('426','','','','优惠券退库','手工选择','2131','预收账款','借','代金券面值 加 兑换券出库金额','往来单位：往来单位',1,null),
    ('426','','','','优惠券退库','单据上收付款项目对应科目','','','贷','实收金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：结算单位',1,null),
    ('426','','','','优惠券退库','手工选择','5501','营业费用','贷','代金券面值 减 代金券金额 加 抹零金额','',1,null),
    ('426','','','','优惠券退库','单据上往来科目','','','贷','金额 减 实付金额 减 抹零金额','分支机构：分支机构，部门：部门，职员：经手人，往来单位：往来单位',1,null),
    ('426','','','','优惠券退库','手工选择','5102','其他业务收入','贷','兑换券出库金额 减 兑换券退货金额','',1,null)
END
GO 

--在【零售单、零售退货单、销售出库单、销售退货单、组合品销售出库单、组合品销售退货单】这几张单据的凭证模板的“基本”页签下新增一个凭证分录：“销售费用”，放在贷方，金额来源就直接读取上方新增的：“代金券差额”。
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 305 AND totalfrom='代金券差额')
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	 --=======================零售单======================
	  ---新会计准则凭证模板
    ('305','','','','销售商品','手工选择','6601','销售费用','贷','代金券差额','',28,null),
    ('305','','','','销售商品','手工选择','2203','预收账款','借','代金券差额','往来单位：往来单位',28,null),
    ---小企业会计准则凭证模板
    ('305','','','','销售商品','手工选择','5601','销售费用','贷','代金券差额','',2,null),
    ('305','','','','销售商品','手工选择','2203','预收账款','借','代金券差额','往来单位：往来单位',2,null),
    --企业会计制度凭证模板
    ('305','','','','销售商品','手工选择','5501','营业费用','贷','代金券差额','',1,null),
    ('305','','','','销售商品','手工选择','2131','预收账款','借','代金券差额','往来单位：往来单位',1,null),
    
	 --=======================零售退货单======================
	  ---新会计准则凭证模板
    ('215','','','','销售商品退货','手工选择','6601','销售费用','借','代金券差额','',28,null),
    ('215','','','','销售商品退货','手工选择','2203','预收账款','贷','代金券差额','往来单位：往来单位',28,null),
    ---小企业会计准则凭证模板
    ('215','','','','销售商品退货','手工选择','5601','销售费用','借','代金券差额','',2,null),
    ('215','','','','销售商品退货','手工选择','2203','预收账款','贷','代金券差额','往来单位：往来单位',2,null),
    --企业会计制度凭证模板
    ('215','','','','销售商品退货','手工选择','5501','营业费用','借','代金券差额','',1,null),
    ('215','','','','销售商品退货','手工选择','2131','预收账款','贷','代金券差额','往来单位：往来单位',1,null),
    
	 --=======================销售出库单======================
	  ---新会计准则凭证模板
    ('11','','','','商品销售出库','手工选择','6601','销售费用','贷','代金券差额','',28,null),
    ('11','','','','商品销售出库','手工选择','2203','预收账款','借','代金券差额','往来单位：往来单位',28,null),
    ---小企业会计准则凭证模板
    ('11','','','','商品销售出库','手工选择','5601','销售费用','贷','代金券差额','',2,null),
    ('11','','','','商品销售出库','手工选择','2203','预收账款','借','代金券差额','往来单位：往来单位',2,null),
    --企业会计制度凭证模板
    ('11','','','','商品销售出库','手工选择','5501','营业费用','贷','代金券差额','',1,null),
    ('11','','','','商品销售出库','手工选择','2131','预收账款','借','代金券差额','往来单位：往来单位',1,null),
    
	 --=======================销售退货单======================
	  ---新会计准则凭证模板
    ('45','','','','商品销售退货','手工选择','6601','销售费用','借','代金券差额','',28,null),
    ('45','','','','商品销售退货','手工选择','2203','预收账款','贷','代金券差额','往来单位：往来单位',28,null),
    ---小企业会计准则凭证模板
    ('45','','','','商品销售退货','手工选择','5601','销售费用','借','代金券差额','',2,null),
    ('45','','','','商品销售退货','手工选择','2203','预收账款','贷','代金券差额','往来单位：往来单位',2,null),
    --企业会计制度凭证模板
    ('45','','','','商品销售退货','手工选择','5501','营业费用','借','代金券差额','',1,null),
    ('45','','','','商品销售退货','手工选择','2131','预收账款','贷','代金券差额','往来单位：往来单位',1,null),
    
	 --=======================组合品销售出库单======================
	  ---新会计准则凭证模板
    ('12','','','','商品组合品销售出库','手工选择','6601','销售费用','贷','代金券差额','',28,null),
    ('12','','','','商品组合品销售出库','手工选择','2203','预收账款','借','代金券差额','往来单位：往来单位',28,null),
    ---小企业会计准则凭证模板
    ('12','','','','商品组合品销售出库','手工选择','5601','销售费用','贷','代金券差额','',2,null),
    ('12','','','','商品组合品销售出库','手工选择','2203','预收账款','借','代金券差额','往来单位：往来单位',2,null),
    --企业会计制度凭证模板
    ('12','','','','商品组合品销售出库','手工选择','5501','营业费用','贷','代金券差额','',1,null),
    ('12','','','','商品组合品销售出库','手工选择','2131','预收账款','借','代金券差额','往来单位：往来单位',1,null),
    
	 --=======================组合品销售退货单======================
	  ---新会计准则凭证模板
    ('46','','','','组合品销售退货','手工选择','6601','销售费用','借','代金券差额','',28,null),
    ('46','','','','组合品销售退货','手工选择','2203','预收账款','贷','代金券差额','往来单位：往来单位',28,null),
    ---小企业会计准则凭证模板
    ('46','','','','组合品销售退货','手工选择','5601','销售费用','借','代金券差额','',2,null),
    ('46','','','','组合品销售退货','手工选择','2203','预收账款','贷','代金券差额','往来单位：往来单位',2,null),
    --企业会计制度凭证模板
    ('46','','','','组合品销售退货','手工选择','5501','营业费用','借','代金券差额','',1,null),
    ('46','','','','组合品销售退货','手工选择','2131','预收账款','贷','代金券差额','往来单位：往来单位',1,null)
END
GO
--===============================983新增【END】===============================

--积分转储值单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 427)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	  ---新会计准则凭证模板
	('427','JFZCZ001','积分转储值单凭证模板','记','积分转储值单','手工选择','6601','销售费用','借','转储值的金额','',28,null),
	('427','','','','积分转储值单','手工选择','2203','预收账款','贷','转储值的金额','往来单位：结算单位',28,null),
    ---小企业会计准则凭证模板
	('427','JFZCZ001','积分转储值单凭证模板','记','积分转储值单','手工选择','5601','销售费用','借','转储值的金额','',2,null),
	('427','','','','积分转储值单','手工选择','2203','预收账款','贷','转储值的金额','往来单位：结算单位',2,null),
	--企业会计制度凭证模板
	('427','JFZCZ001','积分转储值单凭证模板','记','积分转储值单','手工选择','5501','销售费用','借','转储值的金额','',1,null),
	('427','','','','积分转储值单','手工选择','2131','预收账款','贷','转储值的金额','往来单位：结算单位',1,null)
END
GO 

-------------------------------------991新增
--门店配送单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 327)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	  ---新会计准则凭证模板
	('327','MDPSD001','门店配送单凭证模板','记','门店配送单','手工选择','1411','周转材料','借','出库成本','',28,null),
	('327','','','',                            '门店配送单','手工选择','1405','库存商品','贷','出库成本','',28,null),
    ---小企业会计准则凭证模板
	('327','MDPSD001','门店配送单凭证模板','记','门店配送单','手工选择','1411','周转材料','借','出库成本','',2,null),
	('327','','','',                            '门店配送单','手工选择','1405','库存商品','贷','出库成本','',2,null)
	--企业会计制度凭证模板
	--('327','MDPSD001','门店配送单凭证模板','记','门店配送单','手工选择','1411','周转材料','借','出库成本','',1,null),
	--('327','','','',                              '门店配送单','手工选择','1243','库存商品','贷','出库成本','',1,null)
END
GO 
---- ?门店配送退货单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 328)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	  ---新会计准则凭证模板
	('328','MDPSTHD001','门店配送退货单凭证模板','记','门店配送退货单','手工选择','1405','库存商品','借','出库成本','',28,null),
	('328','','','',                                  '门店配送退货单','手工选择','1411','周转材料','贷','出库成本','',28,null),
    ---小企业会计准则凭证模板
	('328','MDPSTHD001','门店配送退货单凭证模板','记','门店配送退货单','手工选择','1405','库存商品','借','出库成本','',2,null),
	('328','','','',                                  '门店配送退货单','手工选择','1411','周转材料','贷','出库成本','',2,null)
	--企业会计制度凭证模板
	--('328','MDPSTHD001','门店配送退货单凭证模板','记','门店配送退货单','手工选择','1243','库存商品','借','出库成本','',1,null),
	--('328','','','',                                  '门店配送退货单','手工选择','1411','周转材料','贷','出库成本','',1,null)
END
GO 
---- 配送验收单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.VoucherTemplatePreset WHERE Billtype = 329)
BEGIN
	INSERT INTO dbo.VoucherTemplatePreset
	        ( Billtype ,
	          usercode ,
	          fullname ,
	          groupfullname ,
	          summary ,
	          atypefrom ,
	          atypeusercode ,
	          atypefullname ,
	          dc ,
	          totalfrom ,
	          assitems ,
	          SubId,
	          ChargeOffType
	        )
	 VALUES
	  ---新会计准则凭证模板
	('329','MDYSD001','配送验收单凭证模板','记','配送验收单','手工选择','1405','库存商品','借','配送金额','',28,null),
	('329','','','',                            '配送验收单','手工选择','6051','其它业务收入','贷','配送金额 减 出库成本','',28,null),
	('329','','','',                            '配送验收单','手工选择','1411','周转材料','贷','出库成本','',28,null),
    ---小企业会计准则凭证模板
	('329','MDYSD001','配送验收单凭证模板','记','配送验收单','手工选择','1405','库存商品','借','配送金额','',2,null),
	('329','','','',                            '配送验收单','手工选择','5051','其它业务收入','贷','配送金额 减 出库成本','',2,null),
	('329','','','',                            '配送验收单','手工选择','1411','周转材料','贷','出库成本','',2,null)
	--企业会计制度凭证模板
	--('329','MDYSD001','配送验收单凭证模板','记','配送验收单','手工选择','1243','库存商品','借','配送金额','',1,null),
	--('329','','','',                            '配送验收单','手工选择','5102','其它业务收入','贷','配送金额 减 出库成本','',1,null),
 --   ('329','','','',                            '配送验收单','手工选择','1411','周转材料','贷','出库成本','',1,null)
END
GO 
--最后处理标识
UPDATE dbo.VoucherTemplatePreset SET mainrow = 0
UPDATE dbo.VoucherTemplatePreset SET mainrow = 1 WHERE ISNULL(usercode,'') <> ''
GO	
--修改凭证模板金额来源成本类标志
UPDATE VoucherTemplatePreset SET isCost=1 
WHERE 
	BillType IN(305,215,11,45,160,139,140,142,141,402,403,405,12,46)
	AND totalfrom LIKE'%成本%'--'成本金额','出库成本金额 减 入库成本金额','本次开票成本'
GO
------------------排序操作------------------------
DECLARE @Temp TABLE(Id INT,Billtype INT,orderID INT)
INSERT INTO @Temp(Id,Billtype,orderID)
SELECT 
	Id,
	Billtype,
	RANK()OVER
	(PARTITION BY SubId,billtype,isCost ORDER BY id) orderID
FROM VoucherTemplatePreset
ORDER BY SubId,Billtype,isCost,Id

UPDATE VoucherTemplatePreset SET orderID=F.orderID
FROM VoucherTemplatePreset D
INNER JOIN @Temp F ON F.Id=D.Id AND F.Billtype=D.Billtype
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdAccountDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WdAccountDetail](
		[ordercode] [VARCHAR](50) NOT NULL,
		[account_erpid] [VARCHAR](8000) NOT NULL ,
		[total] [NUMERIC](20, 8)  NULL DEFAULT 0
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdAccountDetail' AND a.Name='account_erpid' AND  a.length <> 8000
)
BEGIN
ALTER TABLE WdAccountDetail 
ALTER COLUMN account_erpid VARCHAR(8000)
END



--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------


--------------------------------------------创建索引区域开始-----------------------------------------------


--------------------------------------------创建索引区域结束-----------------------------------------------


--------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[WdBillIndexTemp]    脚本日期: 05/05/2010 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[WdBillIndexTemp](
		[BillNumberId] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF_WdBillIndexTemp_BillCode]  DEFAULT (''),
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_BillComment]  DEFAULT (''),
		[atypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_atypeid]  DEFAULT ('0'),
		[ptypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_ptypeid]  DEFAULT ('0'),
		[btypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_btypeid]  DEFAULT ('0'),
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_etypeid]  DEFAULT ('0'),
		[ktypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_ktypeid]  DEFAULT ('0'),
		[ktypeid2] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_ktypeid2]  DEFAULT ('0'),
		[ifcheck] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_ifcheck]  DEFAULT ('t'),
		[checke] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[totalmoney] [numeric](18, 4) NULL CONSTRAINT [DF_WdBillIndexTemp_total]  DEFAULT (0),
		[totalinmoney] [numeric](18, 4) NULL CONSTRAINT [DF_WdBillIndexTemp_totalinmoney]  DEFAULT (0),--在零售单中 对应packway字段
		[totalqty] [numeric](18, 4) NULL CONSTRAINT [DF_WdBillIndexTemp_totalqty]  DEFAULT (0),
		[tax] [numeric](5, 2) NULL CONSTRAINT [DF_WdBillIndexTemp_tax]  DEFAULT (17),
		[period] [smallint] NULL CONSTRAINT [DF_WdBillIndexTemp_period]  DEFAULT (0),
		[explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_explain]  DEFAULT (''),
		[RedWord] [int] NOT NULL CONSTRAINT [DF_WdBillIndexTemp_RedWord]  DEFAULT (0),
		[draft] [bit] NOT NULL CONSTRAINT [DF_WdBillIndexTemp_draft]  DEFAULT (0),
		[OrderId] [numeric](10, 0) NULL CONSTRAINT [DF_WdBillIndexTemp_OrderId]  DEFAULT (0),
		[waybillcode] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[goodsnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_goodsnumber]  DEFAULT (''),
		[packway] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,--在零售单中 此字段表示收现金额
		[TEL] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL,--在零售单中 此字段表示找零
		[Uploaded] [bit] NOT NULL CONSTRAINT [DF_WdBillIndexTemp_Uploaded]  DEFAULT (0),
		[OFF_ID] [uniqueidentifier] NULL,
		[TeamNo] [int] NULL,
		[AlertDay] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_AlertDay]  DEFAULT (9999),
		[CompleteTotal] [numeric](18, 4) NULL CONSTRAINT [DF_WdBillIndexTemp_CompleteTotal]  DEFAULT (0),
		[ID] [numeric](10, 0) NOT NULL CONSTRAINT [DF_WdBillIndexTemp_ID]  DEFAULT (0),
		[Assessor] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[IfAudit] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[Audit_explain] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[IfStopMoney] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_IfStopMoney]  DEFAULT (0),
		[preferencemoney] [numeric](18, 4) NULL CONSTRAINT [DF_WdBillIndexTemp_preferencemoney]  DEFAULT (0),
		[DTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_DTypeId]  DEFAULT ('0'),
		[JF] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_JF]  DEFAULT (0),
		[VipCardID] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_VipCardID]  DEFAULT ((-1)),
		[vipCZMoney] [numeric](18, 4) NULL,
		[jsStyle] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_jsStyle]  DEFAULT (0),
		[jsState] [char](1) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_jsState]  DEFAULT (0),
		[KTypeID3] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_KTypeID3]  DEFAULT ('0'),
		[LinkMan] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_LinkMan]  DEFAULT (''),
		[LinkTel] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_LinkTel]  DEFAULT (''),
		[LinkAddr] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_LinkAddr]  DEFAULT (''),
		[wxManID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_wxMan]  DEFAULT (''),
		[JieJianBillNumberID] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_JieJianCode]  DEFAULT ((-1)),
		[JieJianID] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_JieJianID]  DEFAULT ((-1)),
		[JieJianState] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_JieJianState]  DEFAULT ((-1)),
		[BaoXiuBillNumberID] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_BaoXiuCode]  DEFAULT ((-1)),
		[BaoXiuID] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_BaoXiuID]  DEFAULT ((-1)),
		[BuyDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_BuyDate]  DEFAULT (''),
		[Serial] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_Serial]  DEFAULT (''),
		[wxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_WdBillIndexTemp_wxTotal]  DEFAULT (0),
		[ErrDes] [varchar](3000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdBillIndexTemp_ErrDes]  DEFAULT (''),
		[ifHideJieJian] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_ifHideJieJian]  DEFAULT (0),
		[ifWX] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_ifWX]  DEFAULT (0),
		[ifYearBill] [int] NULL CONSTRAINT [DF_WdBillIndexTemp_ifYearBill]  DEFAULT (0),
		[Poster] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[LastUpdateTime] DateTime NULL CONSTRAINT [DF_WdBillIndexTemp_LastUpdateTime]  DEFAULT GETDATE(),
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[FromBillNumberID] [numeric](10, 0)  NULL DEFAULT ('0'),
		[CostSale] [BIT] DEFAULT 0,
		[OtherInOutType]	INT DEFAULT 0,
		[PosBillType] INT NULL DEFAULT 0,
		[checkTime]		DATETIME NULL,
		[posttime]		DATETIME NULL,
		[updateE]		VARCHAR(50) NULL  DEFAULT (''),
		[ShareMode]		TINYINT NULL	DEFAULT 0,
		[TransportId]   VARCHAR(10) NULL DEFAULT(0),
		[IsIni]			BIT NULL DEFAULT(0),
		[ATypeID1]		VARCHAR(50) NULL DEFAULT(''),
		[NCompleteTotal] [numeric](22, 10) NULL DEFAULT (0),
		[ATID]			INT DEFAULT(0),
		[IfCargo]		BIT DEFAULT(0),
		[InvoiceMoney] numeric(22,10) null DEFAULT(0),
		[NInvoiceMoney] numeric(22,10) null DEFAULT(0),
		[NARTotal]		NUMERIC(22,10) NULL	DEFAULT(0),
		[NAPTotal]		NUMERIC(22,10) NULL	DEFAULT(0),
		[NYSTotal]		NUMERIC(22,10) NULL	DEFAULT(0),
		[NYFTotal]		NUMERIC(22,10) NULL	DEFAULT(0),
		[RedReason] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		PrePriceNum INT DEFAULT(0) NOT NULL, --预设售价，进价
		AssetBusinessTypeId int, --固定资产业务类型id
		PromoRuleId int NOT NULL DEFAULT(0), --促销方案id
		BeforePromoBillNumberId int NOT NULL DEFAULT(0), --促销前数据id
		ImportType tinyint NOT NULL DEFAULT(0), --导入类型
		NewPosBill tinyint NULL DEFAULT(0),
		[PromotionMsg] NVARCHAR(500) NOT NULL DEFAULT(0),
		[Reconciliation] CHAR(1) DEFAULT('f'), --对账 默认f 对账t
		/*添加字段 ARTOTAL,APTOTAL,YSTOTAL,YFTOTAL 2014-1-15 tangtao */
		 ARTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 APTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 YSTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 YFTOTAL NUMERIC(22,10) NULL DEFAULT(0),
		 IsAuto int DEFAULT(0), --0=手动，1=自动
		IsYapi bit NULL DEFAULT(0),
		YapiOrderID NUMERIC(20,0) NULL DEFAULT(0),
		DeliveryAddress VARCHAR(256) NOT NULL DEFAULT(''), --送货地址
		AddDTypeETypeType INT NOT NULL DEFAULT(0), --补录部门经手人类型 0 未补录 1 补录过部门 2补录过经手人 3 同时都补录过
		BillTime VARCHAR(20)  NULL, -- 单据的时分秒
		citestate int NOT NULL DEFAULT(0),--拣货状态0=未引用1=已引用未完成2=已完成
		ShelveRefState INT NOT NULL DEFAULT(0),				--上架引用状态  0=未引用1=已引用未完成2=已完成
		progressstate int NOT NULL DEFAULT(0),				--0=已开单1=拣货中2=已出库
		ShelveState   INT NOT NULL DEFAULT(0),				--上架状态 0=已开单1=上架中2=已上架
		TransPortState INT NOT NULL DEFAULT(0),				--运输状态 0=已开单，1=发运中，2=已发运
		[WarehouseOutDay] [int] NULL DEFAULT (9999),--出库期限@StockInDeadline
		[StockInDeadline] [int] NULL DEFAULT (9999),--出库期限
		shipper VARCHAR(50) NULL DEFAULT(''), --托运方
		totalfreight NUMERIC(24,10) NULL DEFAULT(0),--合计运费
		Ntotalfreight NUMERIC(24,10) NULL DEFAULT(0),--原币合计运费
		transportno varchar(200)	NULL DEFAULT(''),--承运商运单号
		Transporterid varchar(50)	NULL DEFAULT('0'),--承运商id
		Transporterfullname varchar(200)	NULL DEFAULT(''),--承运商名称
		shipperfullname varchar(100)	NULL DEFAULT(''),--托运方
		shipperperson varchar(100)	NULL DEFAULT(''),--托运人
		shippertel varchar(100)	NULL DEFAULT(''),--托运联系电话
		[FaPiaoCode] [varchar](256)  NULL CONSTRAINT [DF_WdBillIndexTemp_FaPiaoCode]  DEFAULT (''),
		InFactState       INT DEFAULT(0),	  --1 仓库入库未完成 2仓库入库已完成
		InFactRefState    INT DEFAULT(0),    -- 0仓库入库未引用  1仓库入库已引用
		OutFactState	  INT DEFAULT(0),	  --1 仓库出库未完成 2仓库出库已完成	
		OutFactRefState   INT DEFAULT(0),	  --0 仓库出库未引用 1仓库出库已引用
		PayType int DEFAULT(0)--是否支付  0-未支付 1-已支付
	) ON [PRIMARY]

END
GO


------------------------------------------表修改区域开始-------------------------------------------------

--是否支付
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillIndexTemp',N'U') AND Name='PayType')
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp 
	ADD PayType INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillIndexTemp',N'U') AND Name='InFactRefState')
BEGIN
	ALTER TABLE WdBillIndexTemp
	ADD InFactRefState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillIndexTemp',N'U') AND Name='OutFactRefState')
BEGIN
	ALTER TABLE WdBillIndexTemp
	ADD OutFactRefState INT DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillIndexTemp',N'U') AND Name='InFactState')
BEGIN
	ALTER TABLE WdBillIndexTemp
	ADD InFactState INT DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillIndexTemp',N'U') AND Name='OutFactState')
BEGIN
	ALTER TABLE WdBillIndexTemp
	ADD OutFactState INT DEFAULT(0)
END
GO
	UPDATE dbo.WdBillIndexTemp SET InFactState=0 WHERE InFactState IS NULL
	UPDATE dbo.WdBillIndexTemp SET OutFactState=0 WHERE OutFactState IS NULL
	UPDATE dbo.WdBillIndexTemp SET InFactRefState=0 WHERE InFactRefState IS NULL
	UPDATE dbo.WdBillIndexTemp SET OutFactRefState=0 WHERE OutFactRefState IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillIndexTemp',N'U') AND Name='ShelveState')
BEGIN
	ALTER TABLE WdBillIndexTemp
	ADD ShelveState INT NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillIndexTemp',N'U') AND Name='ShelveRefState')
BEGIN
	ALTER TABLE WdBillIndexTemp
	ADD ShelveRefState INT NOT NULL DEFAULT(0)
END
GO
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillIndexTemp',N'U') AND Name='TransPortState')
BEGIN
	ALTER TABLE WdBillIndexTemp
	ADD TransPortState INT NOT NULL DEFAULT(0)
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='TEL'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ALTER COLUMN TEL  [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='CWCheck'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD CWCheck INT NOT NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IfBargainOn' 
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD IfBargainOn INT NULL DEFAULT(0)
END
GO
UPDATE WdBillIndexTemp SET IfBargainON=0 WHERE IfBargainON IS NULL

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='LastUpdateTime'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD LastUpdateTime DateTime NULL CONSTRAINT [DF_WdBillIndexTemp_LastUpdateTime]  DEFAULT GETDATE()
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='Poster'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD Poster VARCHAR(50) NOT NULL DEFAULT ('')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE WdBillIndexTemp SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='FromBillNumberID'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD FromBillNumberID [numeric](10, 0)  NULL DEFAULT ('0')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='CostSale'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD CostSale [bit]  NULL	DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IfMulAccount'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD IfMulAccount INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='OtherInOutType'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD OtherInOutType INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='PosBillType'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD PosBillType INT NULL DEFAULT 0
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='checkTime'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD checkTime DATETIME NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='posttime'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD posttime DATETIME NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='updateE'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD updateE VARCHAR(50) NULL DEFAULT('') 
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ShareMode'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD ShareMode TINYINT NULL DEFAULT 0
END
GO

IF  EXISTS(
	SELECT b.name 
	FROM  sysconstraints a  
	INNER JOIN sysobjects b 
	ON a.constid= b.id AND b.xtype='d' AND a.constid= OBJECT_ID(N'[dbo].[DF_WdBillIndexTemp_LastUpdateTime]')
)
BEGIN
	ALTER TABLE WdBillIndexTemp  DROP [DF_WdBillIndexTemp_LastUpdateTime] 
END
GO



IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='WdBillIndexTemp' AND a.Name='IsFreightMoney')
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD IsFreightMoney INT NULL DEFAULT(0) 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='WdBillIndexTemp' AND a.Name='FreightAddr')
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD FreightAddr VARCHAR(300) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='WdBillIndexTemp' AND a.Name='FreightPerson')
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD FreightPerson VARCHAR(100) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='WdBillIndexTemp' AND a.Name='FreightTel')
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD FreightTel VARCHAR(100) NULL DEFAULT('') 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='WdBillIndexTemp' AND a.Name='IfInvoice')
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD IfInvoice INT NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='WdBillIndexTemp' AND a.Name='TransportId')
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD TransportId VARCHAR(10) NULL DEFAULT(0) 
END
GO	

--添加自定义字段
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='UF1'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD UF1 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='UF2'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD UF2 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='UF3'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD UF3 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='UF4'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD UF4 VARCHAR(200)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='UF5'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD UF5 VARCHAR(200)  NULL DEFAULT('')
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ATID'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD ATID INT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NewPosBill'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD NewPosBill tinyint NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='iscombinationstyle'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD iscombinationstyle tinyint NULL DEFAULT(0)
END
GO

IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='telandaddress'
)
BEGIN
	IF NOT EXISTS(
		SELECT a.Name FROM syscolumns a
		INNER JOIN sysobjects	b
		ON a.ID=b.ID
		WHERE b.Name='WdBillIndexTemp' AND a.Name='DeliveryAddress'
	)
		EXEC sp_rename 'WdBillIndexTemp.telandaddress','DeliveryAddress','column'
	ELSE
		BEGIN
			-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
			DECLARE @t1 TABLE(name VARCHAR(100)); 
			INSERT INTO @t1 SELECT 'telandaddress'
			DECLARE @sql1 NVARCHAR(max)='';
			DECLARE @tn1 NVARCHAR(500)='WdBillIndexTemp';

			SELECT @sql1=@sql1+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn1+' drop constraint '+a.name+';' END
				+ ' alter table '+@tn1+' drop column '+d.name+';'
			FROM sys.default_constraints a 
				RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
				JOIN @t1 d ON b.name=d.name
				WHERE b.object_id=object_id(@tn1,'U')

			IF @sql1<>''
				EXEC(@sql1);
			
		END
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='DeliveryAddress'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD DeliveryAddress VARCHAR(256) NOT NULL DEFAULT('') --送货地址
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='AddDTypeETypeType'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD AddDTypeETypeType TINYINT NOT NULL DEFAULT(0)
END
GO



-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'SettleBTypeID' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'CurID' UNION ALL SELECT 'TaskType'
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='WdBillIndexTemp';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='DealBTypeID'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD DealBTypeID VARCHAR(50)  NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='CID'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD CID int  NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='Rate'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD Rate NUMERIC(22,10)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD NTotalMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NTotalInMoney'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD NTotalInMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NPreferenceMoney'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD NPreferenceMoney NUMERIC(22,10) DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NVIPCZMoney'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD NVIPCZMoney NUMERIC(22,10) DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IsIni'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD IsIni BIT NULL DEFAULT(0)
		
	EXEC('UPDATE WdBillIndexTemp SET IsIni=0 WHERE IsIni IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ATypeID1'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD ATypeID1 VARCHAR(50) NULL DEFAULT('')
		
	
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NCompleteTotal'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
ELSE
BEGIN
	ALTER TABLE WdBillIndexTemp ALTER COLUMN NCompleteTotal NUMERIC(22,10)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='billproperty'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD billproperty int default(-1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='TallyId'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD TallyId VARCHAR(50) DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IfCargo'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD IfCargo BIT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='InvoiceMoney'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD InvoiceMoney NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NInvoiceMoney'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD NInvoiceMoney NUMERIC(22,10) NULL DEFAULT(0)
END
GO




IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NARTotal'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD NARTotal NUMERIC(22,10) NULL DEFAULT(0)
END
GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NAPTotal'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD NAPTotal NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NYSTotal'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD NYSTotal NUMERIC(22,10) NULL DEFAULT(0)
END
GO 

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='progressstate'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD progressstate INT NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NYFTotal'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD NYFTotal NUMERIC(22,10) NULL DEFAULT(0)
		
	IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[BTYPE_ARAPTOTAL]') AND type in (N'U'))
	BEGIN
		EXEC('
		UPDATE WdBillIndexTemp
		SET NARTOTAL=b.NARTotal,NAPTOTAL=b.NAPTotal,NYSTOTAL=b.NYSTotal,NYFTOTAL=b.NYFTotal
		FROM	BTYPE_ARAPTOTAL b
		WHERE WdBillIndexTemp.NARTOTAL IS NULL
		AND WdBillIndexTemp.BTypeID<>''''
		AND WdBillIndexTemp.BTypeID=b.BTypeID
		AND WdBillIndexTemp.STypeID=b.STypeID
		AND WdBillIndexTemp.CID=b.CID
		')
	END
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ac_Currency]') AND type in (N'U')) AND EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetCid]') and xtype in (N'FN', N'IF', N'TF'))
	BEGIN
		UPDATE t SET t.rate = t1.rate 
		FROM WdBillIndexTemp T JOIN Ac_Currency t1 
		ON T.cid = t1.cid
		WHERE t.Rate = 0
		EXEC('
			UPDATE  WdBillIndexTemp
			SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
								   THEN ROUND(NARTOTAL * Rate, 2)
								   ELSE ROUND(NARTOTAL / Rate, 2)
								   END
			WHERE  NARTOTAL IS NOT NULL

			UPDATE  WdBillIndexTemp
			SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
								   THEN ROUND(APTOTAL * Rate, 2)
								   ELSE ROUND(APTOTAL / Rate, 2)
								   END
			WHERE  APTOTAL IS NOT NULL

			UPDATE  WdBillIndexTemp
			SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
								   THEN ROUND(YSTOTAL * Rate, 2)
								   ELSE ROUND(YSTOTAL / Rate, 2)
								   END
			WHERE  YSTOTAL IS NOT NULL

			UPDATE  WdBillIndexTemp
			SET     ARTOTAL = CASE WHEN dbo.F_GetCid(cid) = 1
								   THEN ROUND(YFTOTAL * Rate, 2)
								   ELSE ROUND(YFTOTAL / Rate, 2)
								   END
			WHERE  YFTOTAL IS NOT NULL
		')
	END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='RedReason'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD RedReason [varchar](500) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='PrePriceNum'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD PrePriceNum INT DEFAULT(0) NOT NULL;
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='AssetBusinessTypeId'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD AssetBusinessTypeId INT
END

go
--促销方案id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='PromoRuleId'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD PromoRuleId INT NOT NULL DEFAULT(0)
END
go
--促销前数据id
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='BeforePromoteBillNumberId'
)
BEGIN
	EXEC sp_rename 'WdBillIndexTemp.BeforePromoteBillNumberId','BeforePromoBillNumberId','column';
END
ELSE
BEGIN
	IF NOT EXISTS(
		SELECT a.Name FROM syscolumns a
		INNER JOIN sysobjects	b
		ON a.ID=b.ID
		WHERE b.Name='WdBillIndexTemp' AND a.Name='BeforePromoBillNumberId'
	)
	BEGIN
		ALTER TABLE WdBillIndexTemp ADD BeforePromoBillNumberId  INT NOT NULL DEFAULT(0)
	END
END
go
--导入类型
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ImportType'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD ImportType tinyint NOT NULL DEFAULT(0);
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='PromotionMsg'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD [PromotionMsg] NVARCHAR(500) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='Reconciliation'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD [Reconciliation] CHAR(1) DEFAULT('f') --对账 默认f 对账t
END
go


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ARTOTAL'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD ARTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='APTOTAL'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD APTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='YSTOTAL'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD YSTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='YFTOTAL'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD YFTOTAL NUMERIC(22,10) NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IsAuto'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD IsAuto int DEFAULT(0) --0=手动，1=自动
END
GO

--增加一个分支机构id(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='StypeID2'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD StypeID2 VARCHAR(50) NULL DEFAULT('')
END
GO
--是否确认入账(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IfConfirm'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD IfConfirm INT NOT NULL DEFAULT(0)
END
GO

--资金调拨业务类型(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='TransferType'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD TransferType INT NOT NULL DEFAULT(1)
END
GO
--资金调拨单费用扣除账户类型:1,调出账户，2,调入账户(针对资金调拨单）
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='FeeDeductType'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD FeeDeductType INT NOT NULL DEFAULT(1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IsYapi'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD IsYapi bit NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='YapiOrderID'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD YapiOrderID NUMERIC(20,0) NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='BillTime'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD BillTime VARCHAR(20) NULL 
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IsLend'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD IsLend BIT  NULL DEFAULT(0)
END
GO

--增加扣率
IF NOT EXISTS (SELECT Name FROM SYSColumns WHERE ID=OBJECT_ID('WdBillIndexTemp') AND Name='Discount')
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp
	Add Discount NUMERIC(22,10) DEFAULT(1)
END

--增加业务类型,只用于成本条件单,默认为库存0,1-入库,2-出库
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='AdPriceType'
)
BEGIN
	ALTER TABLE WdBillIndexTemp 
		ADD AdPriceType TINYINT NOT NULL DEFAULT(0)
END
GO

--9.6.1运单号从20个字符升级为50个字符
IF EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID('WdBillIndexTemp',N'U') AND LOWER(Name)='waybillcode' AND [Length]=20)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp
	ALTER COLUMN waybillcode VARCHAR(50) COLLATE Chinese_PRC_CI_AS NULL
END
--自定义字段结束
--添加往来核销单需要的字段

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ChargeOffBtypeid'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD ChargeOffBtypeid VARCHAR(50) NULL DEFAULT('')
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ChargeOffType'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD ChargeOffType INT NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ChargeOffTotal'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD ChargeOffTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NChargeOffTotal'
)
BEGIN
	ALTER TABLE WdBillIndexTemp ADD NChargeOffTotal NUMERIC(22,10) NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='cwchecker'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD cwchecker VARCHAR(50)  NULL  DEFAULT('')
END
GO
--添加往来核销单需要的字段结束

--引用状态
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='citestate'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD citestate INT  NOT NULL DEFAULT(0)
END

IF EXISTS(SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b ON a.ID=b.ID
	LEFT JOIN syscomments e ON a.cdefault=e.id AND a.id= OBJECT_ID('WdBillIndexTemp')
	WHERE b.Name='WdBillIndexTemp' AND a.Name='citestate' AND e.text IS NULL)
BEGIN
	ALTER TABLE WdBillIndexTemp add constraint df_citestate default (0) for citestate
END
go
UPDATE WdBillIndexTemp SET citestate=0 WHERE citestate IS NULL
go
  --上架、拣货、运输等状态
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='progressstate'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD progressstate INT
END
--是否需要运输配送
 IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='IsNeedTransport'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD IsNeedTransport BIT
END
--托运方
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='shipper'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD shipper VARCHAR(50)
END
--合计运费
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='totalfreight'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD totalfreight NUMERIC(24,10)
END
--原币合计运费
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ntotalfreight'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD ntotalfreight NUMERIC(24,10)
END

--承运商运单号
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='transportno'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD transportno varchar(200)
END
--出库期限
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='WarehouseOutDay'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [WarehouseOutDay] VARCHAR(50)
END
--入库期限
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='StockInDeadline'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [StockInDeadline] VARCHAR(50)
END
--承运商档案
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='Transporterid'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [Transporterid] VARCHAR(50) NULL DEFAULT('0')
END
--承运商档案
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='Transporterfullname'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [Transporterfullname] VARCHAR(200) NULL DEFAULT('')
END
--托运方
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='shipperfullname'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [shipperfullname] VARCHAR(100) NULL DEFAULT('')
END
--托运人
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='shipperperson'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [shipperperson] VARCHAR(100) NULL DEFAULT('')
END
--托运联系电话
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='shippertel'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [shippertel] VARCHAR(100) NULL DEFAULT('')
END
--发票编号
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='FaPiaoCode'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [FaPiaoCode] VARCHAR(256) NULL DEFAULT('')
END

--网店汇总单据标志
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='CollectFlag'
)
BEGIN
	ALTER TABLE dbo.WdBillIndexTemp ADD [CollectFlag] VARCHAR NOT  NULL DEFAULT('R')
END
------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------
--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'NCIX_IFCHECK')
--	DROP INDEX [dbo].WdBillIndexTemp.NCIX_IFCHECK

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'NCIX_REDWORD')
--	DROP INDEX [dbo].WdBillIndexTemp.NCIX_REDWORD

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'NCIX_BILLTYPE')
--	DROP INDEX [dbo].WdBillIndexTemp.NCIX_BILLTYPE

--IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'NCIX_DRAFT')
--	DROP INDEX [NCIX_DRAFT] ON [dbo].[WdBillIndexTemp]
--GO

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'IX_WdBillIndexTemp_ATypeID')
--	DROP  INDEX [IX_WdBillIndexTemp_ATypeID] ON WdBillIndexTemp 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'IX_WdBillIndexTemp_BillCode')
--DROP  INDEX [IX_WdBillIndexTemp_BillCode] ON WdBillIndexTemp 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'IX_WdBillIndexTemp_BillDate')
--DROP  INDEX [IX_WdBillIndexTemp_BillDate] ON WdBillIndexTemp 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'IX_WdBillIndexTemp_BillNumberId')
--DROP  INDEX [IX_WdBillIndexTemp_BillNumberId] ON WdBillIndexTemp 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'IX_WdBillIndexTemp_BTypeId')
--DROP INDEX [IX_WdBillIndexTemp_BTypeId] ON WdBillIndexTemp 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'IX_WdBillIndexTemp_ETypeID')
--DROP INDEX [IX_WdBillIndexTemp_ETypeId] ON WdBillIndexTemp 

--IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'IX_WdBillIndexTemp_KTypeID')
--DROP INDEX [IX_WdBillIndexTemp_KTypeId] ON WdBillIndexTemp 

--IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'IX_WdBillIndexTemp_KTypeID2')
--DROP INDEX [IX_WdBillIndexTemp_KTypeId2] ON WdBillIndexTemp 
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillIndexTemp') AND name = 'CIX_WdBillIndexTemp_BillDate')
--DROP INDEX CIX_WdBillIndexTemp_BillDate ON WdBillIndexTemp 
CREATE CLUSTERED INDEX CIX_WdBillIndexTemp_BillDate ON WdBillIndexTemp(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillIndexTemp') AND name = 'NCIX_WdBillIndexTemp_BillNumberID')
--DROP INDEX NCIX_WdBillIndexTemp_BillNumberID ON WdBillIndexTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillIndexTemp_BillNumberID ON WdBillIndexTemp(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillIndexTemp') AND name = 'NCIX_WdBillIndexTemp_Billcode')
--DROP INDEX NCIX_WdBillIndexTemp_Billcode ON WdBillIndexTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillIndexTemp_Billcode ON WdBillIndexTemp(Billcode) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillIndexTemp') AND name = 'NCIX_WdBillIndexTemp_Btypeid')
--DROP INDEX NCIX_WdBillIndexTemp_Btypeid ON WdBillIndexTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillIndexTemp_Btypeid ON WdBillIndexTemp(Btypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillIndexTemp') AND name = 'NCIX_WdBillIndexTemp_Atypeid')
--DROP INDEX NCIX_WdBillIndexTemp_Atypeid ON WdBillIndexTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillIndexTemp_Atypeid ON WdBillIndexTemp(Atypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillIndexTemp') AND name = 'NCIX_WdBillIndexTemp_Etypeid')
--DROP INDEX NCIX_WdBillIndexTemp_Etypeid ON WdBillIndexTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillIndexTemp_Etypeid ON WdBillIndexTemp(Etypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillIndexTemp') AND name = 'NCIX_WdBillIndexTemp_Ktypeid')
--DROP INDEX NCIX_WdBillIndexTemp_Ktypeid ON WdBillIndexTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillIndexTemp_Ktypeid ON WdBillIndexTemp(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillIndexTemp') AND name = 'NCIX_WdBillIndexTemp_Ktypeid2')
--DROP INDEX NCIX_WdBillIndexTemp_Ktypeid2 ON WdBillIndexTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillIndexTemp_Ktypeid2 ON WdBillIndexTemp(Ktypeid2) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'NCIX_WdBillIndexTemp_BILLTYPE')
--DROP INDEX NCIX_WdBillIndexTemp_BILLTYPE ON WdBillIndexTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillIndexTemp_BILLTYPE ON WdBillIndexTemp(BILLTYPE) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[WdBillIndexTemp]') AND name = N'NCIX_WdBillIndexTemp_STYPEID_INCLUDE')
--DROP INDEX [NCIX_WdBillIndexTemp_STYPEID_INCLUDE] ON [dbo].[WdBillIndexTemp] WITH ( ONLINE = OFF )
--GO
CREATE NONCLUSTERED INDEX [NCIX_WdBillIndexTemp_STYPEID_INCLUDE] ON [dbo].[WdBillIndexTemp] 
(
	[Stypeid] ASC,
	[BillDate] ASC,
	[BillType] ASC
)
INCLUDE ( [BillNumberId]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE WdBillIndexTemp SET FromBillNumberID = 0 WHERE FromBillNumberID IS NULL
GO
UPDATE WdBillIndexTemp SET CostSale = 0 WHERE CostSale IS NULL
GO
UPDATE WdBillIndexTemp SET IfMulAccount = 0 WHERE IfMulAccount IS NULL
GO
UPDATE WdBillIndexTemp SET sharemode = 0 WHERE sharemode IS NULL
GO
UPDATE WdBillIndexTemp SET posbilltype = 0 WHERE posbilltype IS NULL
GO
UPDATE WdBillIndexTemp SET TransportId = 0 WHERE TransportId IS NULL
GO
UPDATE WdBillIndexTemp SET IsFreightMoney = 0 WHERE IsFreightMoney IS NULL
GO
UPDATE WdBillIndexTemp SET FreightAddr = '' WHERE FreightAddr IS NULL
GO
UPDATE WdBillIndexTemp SET FreightPerson = '' WHERE FreightPerson IS NULL
GO
UPDATE WdBillIndexTemp SET FreightTel = '' WHERE FreightTel IS NULL
GO
UPDATE WdBillIndexTemp SET IfInvoice = 0 WHERE IfInvoice IS NULL
GO
UPDATE WdBillIndexTemp SET billproperty = -0 WHERE IfInvoice IS NULL
GO
UPDATE WdBillIndexTemp SET TallyId = '' WHERE TallyId IS NULL
GO
UPDATE WdBillIndexTemp SET NewPosbill = 0 WHERE NewPosbill IS NULL
GO
UPDATE WdBillIndexTemp SET IsLend = 0 WHERE IsLend IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN totalmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='totalinmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN totalinmoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='totalqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN totalqty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='preferencemoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN preferencemoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='vipCZMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN vipCZMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='wxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN wxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NARTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NARTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NAPTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NAPTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NYSTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NYSTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NYFTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NYFTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ARTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN ARTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='APTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN APTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='YSTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN YSTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='YFTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN YFTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='Rate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN Rate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NTotalInMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NTotalInMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NPreferenceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NPreferenceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NVIPCZMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NVIPCZMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='ChargeOffTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN ChargeOffTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillIndexTemp' AND a.Name='NChargeOffTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillIndexTemp 
	ALTER COLUMN NChargeOffTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--   修改：梁晰   日期：2016-12-22  增加支付方式字段

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdBillMulAccountTemp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WdBillMulAccountTemp](
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[ID] INT IDENTITY(1,1) NOT NULL,
		[ATypeID] VARCHAR(50) NULL DEFAULT(''),		
		[Total] NUMERIC(18,4) NULL DEFAULT(0),
		[Comment] VARCHAR(500) NULL DEFAULT(''),		
		[BillType] INT 		   DEFAULT(0),
		[TradeNo] VARCHAR(200) DEFAULT(''),
		[PayType] INT DEFAULT(0)
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillMulAccountTemp' AND a.Name='VipCardID'
)
BEGIN
	ALTER TABLE WdBillMulAccountTemp ADD VipCardID INT NULL DEFAULT(-1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillMulAccountTemp' AND a.Name='NTotalMoney'
)
BEGIN
	ALTER TABLE WdBillMulAccountTemp ADD NTotalMoney  NUMERIC(22,10) DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillMulAccountTemp' AND a.Name='paymoney'
)
BEGIN
	ALTER TABLE WdBillMulAccountTemp ADD paymoney   NUMERIC(24,10)  NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillMulAccountTemp' AND a.Name='TradeNo'
)
BEGIN
	ALTER TABLE WdBillMulAccountTemp ADD TradeNo   varchar(200)  NOT NULL DEFAULT''
END
GO

--支付方式
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillMulAccountTemp' AND a.Name='PayType'
)
BEGIN
	ALTER TABLE WdBillMulAccountTemp ADD PayType   INT  NOT NULL DEFAULT(0)
END
GO

--单据类型
IF NOT EXISTS(SELECT TOP 1  1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdBillMulAccountTemp') AND Name='BillType')
BEGIN
	ALTER TABLE dbo.WdBillMulAccountTemp
	ADD BillType INT DEFAULT(0)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillMulAccountTemp') AND name = 'CIX_WdBillMulAccountTemp_BillNumberID')
--DROP INDEX CIX_WdBillMulAccountTemp_BillNumberID ON WdBillMulAccountTemp 
CREATE CLUSTERED INDEX CIX_WdBillMulAccountTemp_BillNumberID ON WdBillMulAccountTemp(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdBillMulAccountTemp') AND name = 'NCIX_WdBillMulAccountTemp_Atypeid')
--DROP INDEX NCIX_WdBillMulAccountTemp_Atypeid ON WdBillMulAccountTemp 
CREATE NONCLUSTERED INDEX NCIX_WdBillMulAccountTemp_Atypeid ON WdBillMulAccountTemp(Atypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE WdBillMulAccountTemp SET VipCardID = -1 WHERE VipCardID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillMulAccountTemp' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillMulAccountTemp 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdBillMulAccountTemp' AND a.Name='NTotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdBillMulAccountTemp 
	ALTER COLUMN NTotalMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdCargoDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WdCargoDetail](
		[ordercode] [VARCHAR](50) NOT NULL,
		[goodscode] [VARCHAR](50) NOT NULL,
		[whstpt_erpid] [VARCHAR](50) NOT NULL ,
		[qty] [NUMERIC](20, 8)  NULL DEFAULT 0
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdCargoDetail',N'U') AND Name='sku_erpid')
BEGIN
	ALTER TABLE dbo.WdCargoDetail
	ADD sku_erpid [VARCHAR](50) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.WdCargoDetail SET sku_erpid=0 WHERE sku_erpid IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdCargoDetail',N'U') AND Name='mid')
BEGIN
	ALTER TABLE dbo.WdCargoDetail
	ADD mid INT NOT  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdCargoDetail',N'U') AND Name='nid')
BEGIN
	ALTER TABLE dbo.WdCargoDetail
	ADD nid INT NOT  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdCargoDetail',N'U') AND Name='serialRelationId')
BEGIN
	ALTER TABLE dbo.WdCargoDetail
	ADD serialRelationId INT NOT  NULL DEFAULT(0) 
END
GO

--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------


--------------------------------------------创建索引区域开始-----------------------------------------------


--------------------------------------------创建索引区域结束-----------------------------------------------


--------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[WDGOODSSTOCKS_QTY]    脚本日期: 05/05/2010 14:47:42 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WDGOODSSTOCKS_QTY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

	CREATE TABLE  WDGOODSSTOCKS_QTY  (
	  ID				  INT IDENTITY(1,1),
	  KTypeID             VARCHAR(50),
	  CargoID             INT,
	  PTypeID             VARCHAR(50),
	  IsCombinedItem      INT,
	  ItemID              INT,
	  Qty                 NUMERIC(24,10) DEFAULT(0),
	  EnableNum			  NUMERIC(24,10) DEFAULT(0),
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------


------------------------------------------创建索引区域结束-----------------------------------------------









------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdItemsDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WdItemsDetail](
		[ordercode] [VARCHAR](200) NOT NULL,
		[goodscode] [VARCHAR](200) NOT NULL,
		[eshopgoodsname] [VARCHAR](200) NULL DEFAULT '',
		[eshopskuname] [VARCHAR](200) NULL DEFAULT '',
		[qty] [NUMERIC](20, 8) NOT NULL ,
		[price] [NUMERIC](20, 8) NULL DEFAULT 0,
		[total] [NUMERIC](20, 8) NULL DEFAULT 0,
		[isgift] INT  NULL  DEFAULT 0,
		[sku_erpid] [VARCHAR](50) NOT NULL ,
		[remark] [VARCHAR](2000) NULL DEFAULT '' 
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdItemsDetail',N'U') AND Name='mid')
BEGIN
	ALTER TABLE dbo.WdItemsDetail
	ADD mid INT NOT NULL DEFAULT(0) 
END
GO

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdItemsDetail' AND a.Name='eshopgoodsname' AND  a.length <> 200
)
BEGIN
ALTER TABLE WdItemsDetail 
ALTER COLUMN eshopgoodsname VARCHAR(200)
END

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdItemsDetail' AND a.Name='eshopskuname' AND  a.length <> 200
)
BEGIN
ALTER TABLE WdItemsDetail 
ALTER COLUMN eshopskuname VARCHAR(200)
END

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdItemsDetail' AND a.Name='remark' AND  a.length <> 2000
)
BEGIN
ALTER TABLE WdItemsDetail 
ALTER COLUMN remark VARCHAR(2000)
END


--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------


--------------------------------------------创建索引区域开始-----------------------------------------------


--------------------------------------------创建索引区域结束-----------------------------------------------


--------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[WdOrder]    脚本日期: 01/12/2016 14:47:16 ******/
SET ANSI_NULLS ON;

SET QUOTED_IDENTIFIER ON;

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[WdOrder]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 )
    BEGIN
        CREATE TABLE [dbo].[WdOrder]
            (
              id INT ,
              billtype VARCHAR(50) ,--单据类型
              wdname VARCHAR(200) ,--网店名称
              wdtype VARCHAR(200) ,--网店类型
              [datetime] DATETIME ,--订单创建时间
              ordernumber VARCHAR(50) ,--原始网店订单编号
              wdbillnumber VARCHAR(50) ,--网店订单编号
              employee VARCHAR(50) ,--经手人
              employeeid VARCHAR(50) ,
              remark VARCHAR(2000) ,--备注
              whs_erpid VARCHAR(50) ,--发货仓库id
              goodsremark VARCHAR(1000) ,--商品备注
              stock VARCHAR(500) ,--仓库
              title VARCHAR(500) ,--网店商品名称
              propsname VARCHAR(500) ,--网店商品属性
              fullname VARCHAR(500) ,--本地商品名称
              usercode VARCHAR(50) ,--商品编号
              ptypeid VARCHAR(50) ,--商品typeid
              price NUMERIC(24, 10) ,--单价
              qty NUMERIC(24, 10) ,--数量
              total NUMERIC(24, 10) ,--金额
              skuid VARCHAR(50) ,--规格id
              itemname VARCHAR(50) ,--自由项
              cargoid VARCHAR(8000) ,--货位id
              itemqty VARCHAR(8000) , --每个货位对应商品数量
              account VARCHAR(8000) , --收款账户
              mobile VARCHAR(50) , --联系方式
              privilege NUMERIC(24, 10) ,--优惠金额
              buyfreight NUMERIC(24, 10) ,--运费
              logisticscode VARCHAR(50) ,--运单号
              logisticsname VARCHAR(500) ,--承运单位
              buyermessage VARCHAR(MAX) ,--买家留言
              totalall NUMERIC(24, 10) ,--单据总价
              isgift BIT ,--是否赠品
              recaddr VARCHAR(5000) ,--收到地址
              buyername VARCHAR(100) ,--买家姓名
              freeitemid BIT ,--0：基本项，1：自由项
              itemid INT ,--自由项id
              totalstr VARCHAR(8000) ,--金额串
              zhaiyao VARCHAR(2000) ,--摘要
              eshopid INT, --店铺id
              btype	 VARCHAR(50) NOT NULL DEFAULT '',
              btypeid	VARCHAR(50) NOT NULL DEFAULT ''
	        ); 

    END;
GO
------------------------------------------表修改区域开始-------------------------------------------------


IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrder' AND a.Name='btype' 
    )
BEGIN
	ALTER TABLE WdOrder
	ADD btype VARCHAR(50) NOT NULL DEFAULT ''
END
GO

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrder' AND a.Name='btypeid' 
    )
BEGIN
	ALTER TABLE WdOrder
	ADD btypeid VARCHAR(50) NOT NULL DEFAULT ''
END
GO

IF NOT EXISTS ( SELECT  a.name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.id = b.id
                WHERE   b.name = 'WdOrder'
                        AND a.name = 'isException' )
    BEGIN
        ALTER TABLE dbo.WdOrder ADD
        isException INT NOT NULL DEFAULT(0);
    END;
GO


IF NOT EXISTS ( SELECT  a.name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.id = b.id
                WHERE   b.name = 'WdOrder'
                        AND a.name = 'Ntotal' )
    BEGIN
        ALTER TABLE dbo.WdOrder ADD
        Ntotal NUMERIC(24, 10) NOT NULL DEFAULT(0);
    END;
    


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------修改字段类型区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrder' AND a.Name='itemqty' AND  a.length <> 8000
    )
    BEGIN
	ALTER TABLE WdOrder 
	ALTER COLUMN itemqty VARCHAR(8000)
    END
    
IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='account' AND  a.length <> 8000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN account VARCHAR(8000)
END


IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='totalstr' AND  a.length <> 8000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN totalstr VARCHAR(8000)
END


IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='cargoid' AND  a.length <> 8000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN cargoid VARCHAR(8000)
END

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='title' AND  a.length <> 500
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN title VARCHAR(500)
END

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='propsname' AND  a.length <> 500
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN propsname VARCHAR(500)
END


IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='fullname' AND  a.length <> 500
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN fullname VARCHAR(500)
END

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='goodsremark' AND  a.length <> 1000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN goodsremark VARCHAR(1000)
END    

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='stock' AND  a.length <> 500
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN stock VARCHAR(500)

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='remark' AND  a.length <>2000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN remark VARCHAR(2000)
END   

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='zhaiyao' AND  a.length <>2000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN zhaiyao VARCHAR(2000)
END   

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='buyermessage' AND  a.length <>8000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN buyermessage VARCHAR(8000)
END

IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='logisticsname' AND  a.length <>500
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN logisticsname VARCHAR(500)
END


IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='buyername' AND  a.length <>1000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN buyername VARCHAR(1000)
END


IF  EXISTS(
SELECT a.Name FROM syscolumns a
INNER JOIN sysobjects	b
ON a.ID=b.ID
WHERE b.Name='WdOrder' AND a.Name='recaddr' AND  a.length <>5000
)
BEGIN
ALTER TABLE WdOrder 
ALTER COLUMN recaddr VARCHAR(5000)
END

END                                   
------------------------------------------修改字段类型区域结束-----------------------------------------------



------------------------------------------删除索引区域开始-----------------------------------------------

	
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------



------------------------------------------创建索引区域结束-----------------------------------------------



------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdOrderBody]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WdOrderBody](
		[ordercode] [VARCHAR](50) NOT NULL,
		[sourceplatformnae] [VARCHAR](50) NOT NULL,
		[ordersourcecode] [VARCHAR](50) NULL DEFAULT '',
		[eshopname] [VARCHAR](500) NOT NULL ,
		[logisticscode] [VARCHAR](50) NULL DEFAULT '',
		[logisticsname] [VARCHAR](100) NULL DEFAULT '',
		[clerk_erpid] [VARCHAR](50) NOT NULL ,
		[whs_erpid] [VARCHAR](50) NOT NULL ,
		[total] [NUMERIC](20, 8) NOT NULL ,
		[buyeraccount] [VARCHAR](50) NOT NULL,
		[qty] [NUMERIC](20, 8) NULL DEFAULT 0,
		[buyermessage] [VARCHAR](5000) NULL DEFAULT '',
		[privilege] [numeric](18, 4) NULL DEFAULT 0,
		[buyfreight] [numeric](18, 4)  NULL DEFAULT 0,
		[remark] [VARCHAR](2000) NULL  DEFAULT '',
		[name] [VARCHAR](50) NULL DEFAULT '',
		[postcode] [VARCHAR](50) NULL DEFAULT '',
		[tel] [VARCHAR](50) NULL DEFAULT '',
		[mobile] [VARCHAR](50)  NULL  DEFAULT '',
		[province] [VARCHAR](200)  DEFAULT (''),
		[city] [VARCHAR](200) NULL DEFAULT '',
		[area] [VARCHAR](200) NULL DEFAULT '',
		[detailaddress] [VARCHAR](2000) NULL DEFAULT '',
		[createtime] [varchar](100) NULL DEFAULT '',
		[orderstatus] [varchar](50) NULL DEFAULT (''),
		[buyerName] [varchar](50) NULL  DEFAULT '',
		[iscod] int NULL,
		[senddate] [varchar](50) NULL DEFAULT '',
		[btype_erpid] INT NOT NULL DEFAULT 0
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------



--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------


--------------------------------------------创建索引区域开始-----------------------------------------------


--------------------------------------------创建索引区域结束-----------------------------------------------


--------------------------------------------修改字段小数位数区域开始-----------------------------------------------

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrderBody' AND a.Name='btype_erpid' 
    )
BEGIN
	ALTER TABLE WdOrderBody 
	ADD btype_erpid INT NOT NULL DEFAULT (0)
END
GO


IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrderBody' AND a.Name='buyermessage' AND  a.length <> 5000
    )
    BEGIN
	ALTER TABLE WdOrderBody 
	ALTER COLUMN buyermessage VARCHAR(5000)
    END
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrderBody' AND a.Name='remark' AND  a.length <> 2000
    )
    BEGIN
	ALTER TABLE WdOrderBody 
	ALTER COLUMN remark VARCHAR(2000)
    END
 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrderBody' AND a.Name='[eshopname]' AND  a.length <> 500
    )
    BEGIN
	ALTER TABLE WdOrderBody 
	ALTER COLUMN [eshopname] VARCHAR(500)
    END 
            
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrderBody' AND a.Name='[detailaddress]' AND  a.length <> 2000
    )
    BEGIN
	ALTER TABLE WdOrderBody 
	ALTER COLUMN [detailaddress] VARCHAR(2000)
    END       
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrderBody' AND a.Name='[province]' AND  a.length <> 200
    )
    BEGIN
	ALTER TABLE WdOrderBody 
	ALTER COLUMN [province] VARCHAR(200)
    END     
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrderBody' AND a.Name='[city]' AND  a.length <> 200
    )
    BEGIN
	ALTER TABLE WdOrderBody 
	ALTER COLUMN [city] VARCHAR(200)
    END       
    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdOrderBody' AND a.Name='[area]' AND  a.length <> 200
    )
    BEGIN
	ALTER TABLE WdOrderBody 
	ALTER COLUMN [area] VARCHAR(200)
    END                              
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[WdSaleBillTemp]    脚本日期: 05/05/2010 14:49:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdSaleBillTemp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WdSaleBillTemp](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_SalePrice]  DEFAULT (0),
		[discount] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_discount]  DEFAULT (1),
		[DiscountPrice] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_DiscountPrice]  DEFAULT (0),
		[costprice] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_costprice]  DEFAULT (0),
		[jobnumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdSaleBillTemp_jobnumber]  DEFAULT (''),
		[goodsno] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_goodsno]  DEFAULT (0),
		[total] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_total]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_TaxPrice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL,
		[comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,
		[OrderID] [int] NULL CONSTRAINT [DF_WdSaleBillTemp_OrderID]  DEFAULT ('-1'),
		[TeamNo] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_WdSaleBillTemp_IsUnit2]  DEFAULT (0),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdSaleBillTemp_Serial]  DEFAULT (''),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_InputCostPrice]  DEFAULT (0),
		[GoodsOrder] [int] NULL CONSTRAINT [DF_WdSaleBillTemp_GoodsOrder]  DEFAULT ('-1'),
		[BackQty] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_BackQty]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdSaleBillTemp_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdSaleBillTemp_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdSaleBillTemp_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_WdSaleBillTemp_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_WdSaleBillTemp_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_WdSaleBillTemp_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF__WdSaleBillTemp__Comple__18109845]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_WdSaleBillTemp_SaleTotal]  DEFAULT (0),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_WdSaleBillTemp_Tax]  DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ShareFee]	[numeric](18,2) NULL DEFAULT(0),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int                NULL Default(0),
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			 VARCHAR(200)		NULL DEFAULT('') ,
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), --是否是赠品 价格促销
		BeforePromoID INT NOT NULL DEFAULT(0),
		--GiftFlag INT NOT NULL DEFAULT(0) -- 0不是，1是赠品 9.4
		ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0), --参考成本
		PriceStyle INT NOT NULL DEFAULT(0) --价格类型
		,PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
		,ShowOrder INT DEFAULT(0)
		,DiyID INT DEFAULT(-1)
		,ETypeID VARCHAR(100)
		,ClearQty NUMERIC(24,10)	--解锁数量
		,SendedQty DECIMAL(24,10) NULL DEFAULT(0) --物流运输 已发运数量
		,PickedQty NUMERIC(24,10) NULL DEFAULT(0) --拣货数量
		,OutFactQty NUMERIC(24,10) NULL DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'WdSaleBillTemp',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.WdSaleBillTemp
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'WdSaleBillTemp',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.WdSaleBillTemp
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdSaleBillTemp',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.WdSaleBillTemp
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.WdSaleBillTemp SET OutFactQty=0 WHERE OutFactQty IS NULL
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdSaleBillTemp',N'U') AND Name='ETypeID')
BEGIN
	ALTER TABLE WdSaleBillTemp
	ADD ETypeID VARCHAR(100)
END
GO
	UPDATE WdSaleBillTemp
	SET ETypeID=b.etypeid
	FROM Billindex b
	WHERE WdSaleBillTemp.BillNumberId=b.BillNumberId AND ISNULL(WdSaleBillTemp.ETypeID,'')=''
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdSaleBillTemp',N'U') AND Name='PickedQty')
BEGIN
	ALTER TABLE WdSaleBillTemp
	ADD PickedQty NUMERIC(24,10) NULL DEFAULT(0)
END
GO
	UPDATE WdSaleBillTemp SET PickedQty=0 WHERE PickedQty IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='ClearQty'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD ClearQty   numeric(22,10)   NULL Default(0)
END
GO

IF NOT EXISTS(SELECt 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdSaleBillTemp',N'U') AND Name='DiyID')
BEGIN
	ALTER TABLE dbo.WdSaleBillTemp
	ADD DiyID INT DEFAULT(-1)
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[WdSaleBillTemp]') and name = 'KTypeID' )
BEGIN
	
	ALTER TABLE dbo.WdSaleBillTemp ADD
		KTypeID varchar(50) NULL
END
GO
UPDATE WdSaleBillTemp
SET KTypeID=b.KTypeID
FROM BillIndex b
WHERE WdSaleBillTemp.BillNumberID=b.BillNumberID AND WdSaleBillTemp.KTypeID IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='STypeID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD STypeID VARCHAR(50) DEFAULT('')
		DECLARE @strSql VARCHAR(8000)
	
		SELECT @strSql='
		UPDATE WdSaleBillTemp SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
		WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
		
		EXEC(@strSql)
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='ShareFee'
)
BEGIN
	ALTER TABLE WdSaleBillTemp ADD ShareFee  [numeric](18, 2)  NULL DEFAULT(0)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='TaxMoney'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD TaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NSalePrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NSalePrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NSaleTotal'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NSaleTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NDiscountPrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NDiscountPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NTotal'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NTotal   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NTaxPrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NTaxPrice   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NTaxTotal'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NTaxTotal   numeric(22,10)   NULL Default(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NTaxMoney'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NTaxMoney   numeric(22,10)   NULL Default(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='UnitID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD UnitID  INT   NULL DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NUnitID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NUnitID INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD UnitRate   numeric(22,10)     NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NUnitMsg'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NUnitMsg   varchar(50)  NULL  
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MUnitID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD MUnitID  INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MQty'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD MQty   numeric(22,10)   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MUnitRate'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD MUnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MUnitMsg'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD MUnitMsg   varchar(50)  NULL  
END
GO
--
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MSalePrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD MSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MDiscountPrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD MDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MTaxPrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD MTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CurMSalePrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD CurMSalePrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CurMDiscountPrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD CurMDiscountPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CurMTaxPrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD CurMTaxPrice   numeric(22,10)   NULL  DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD CargoID   INT   NULL  DEFAULT(0)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD IsCombined   INT
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='entryCode'
)
BEGIN
	ALTER TABLE WdSaleBillTemp ADD entryCode   VARCHAR(200) DEFAULT('')
END
ELSE 
	ALTER TABLE WdSaleBillTemp ALTER COLUMN entryCode VARCHAR(200)
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='InvoiceQty'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD InvoiceQty   numeric(18, 4)		NULL DEFAULT (0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='InvoiceMoney'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD InvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO




IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NInvoiceMoney'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD NInvoiceMoney   numeric(22,10)		null DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD PriceSource   VARCHAR(200)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='ReferPrice'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD ReferPrice NUMERIC(18,4) NOT NULL DEFAULT(0) --参考成本
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='PriceStyle'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD PriceStyle INT NOT NULL DEFAULT(0) --价格类型
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='PromoType'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无
END
GO

--排序号
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID= OBJECT_ID(N'WdSaleBillTemp',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.WdSaleBillTemp
	ADD ShowOrder INT  DEFAULT(0)
END
GO
	UPDATE dbo.WdSaleBillTemp SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'WdSaleBillTemp',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE WdSaleBillTemp ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE WdSaleBillTemp SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'WdSaleBillTemp',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE WdSaleBillTemp ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE WdSaleBillTemp SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO
-------

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='PriceSource'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ALTER COLUMN PriceSource   VARCHAR(200)
END
GO
IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='OMBillID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD OMBillID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='LendBillNumberID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD LendBillNumberID numeric(10, 0) NULL DEFAULT(0)
END
GO	

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='LendBillID'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD LendBillID NUMERIC(10, 0) NULL DEFAULT(0)
END
GO	

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('WdSaleBillTemp') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table WdSaleBillTemp drop constraint '+@dfname);
		
	ALTER TABLE WdSaleBillTemp ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE WdSaleBillTemp ADD CONSTRAINT DF_WdSaleBillTemp_Serial DEFAULT('') FOR Serial
END
GO




-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'MSaleTotal'  UNION ALL SELECT 'MTotal' UNION ALL SELECT 'MTaxTotal' UNION ALL SELECT 'CurMSaleTotal' UNION ALL SELECT 'CurMTotal' UNION ALL SELECT 'CurMTaxTotal'
UNION ALL SELECT 'CargoSpace' UNION ALL SELECT 'CurRate' UNION ALL SELECT 'BarCode';
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn VARCHAR(500)='WdSaleBillTemp';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

IF  NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='IsGift'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD IsGift INT NOT NULL DEFAULT(0);
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='BeforePromoID'
)
BEGIN

		ALTER TABLE WdSaleBillTemp ADD BeforePromoID INT NOT NULL DEFAULT(0);
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='SendedQty'
)
BEGIN

		ALTER TABLE WdSaleBillTemp ADD SendedQty DECIMAL(24,10) NULL DEFAULT(0);
END
GO

-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'GiftFlag' 
DECLARE @sql NVARCHAR(max)='';

DECLARE @tn VARCHAR(500)='WdSaleBillTemp';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdSaleBillTemp]') AND name = N'NCIX_PTYPEID')
	DROP INDEX [dbo].[WdSaleBillTemp].NCIX_PTYPEID 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdSaleBillTemp]') AND name = N'NCIX_KTYPEID')
	DROP INDEX [dbo].[WdSaleBillTemp].NCIX_KTYPEID 
	
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdSaleBillTemp]') AND name = N'NCIX_ORDERID')
	DROP INDEX [dbo].[WdSaleBillTemp].NCIX_ORDERID 
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdSaleBillTemp]') AND name = N'NCIX_OutFactoryDate')
	DROP INDEX [dbo].[WdSaleBillTemp].NCIX_OutFactoryDate 

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdSaleBillTemp]') AND name = N'IX_WdSaleBillTemp')
DROP INDEX [IX_WdSaleBillTemp] ON [dbo].[WdSaleBillTemp] 


IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdSaleBillTemp]') AND name = N'IX_WdSaleBillTemp_PTypeID')
DROP INDEX [IX_WdSaleBillTemp_PTypeID] ON [dbo].[WdSaleBillTemp] 


IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[WdSaleBillTemp]') AND name = N'WdSaleBillTempIndex')
DROP INDEX [WdSaleBillTempIndex] ON [dbo].[WdSaleBillTemp] 

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdSaleBillTemp') AND name = 'CIX_WdSaleBillTemp_BillNumberID')
--DROP INDEX CIX_WdSaleBillTemp_BillNumberID ON WdSaleBillTemp 
CREATE CLUSTERED INDEX CIX_WdSaleBillTemp_BillNumberID ON WdSaleBillTemp(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdSaleBillTemp') AND name = 'NCIX_WdSaleBillTemp_Ptypeid')
--DROP INDEX NCIX_WdSaleBillTemp_Ptypeid ON WdSaleBillTemp 
CREATE NONCLUSTERED INDEX NCIX_WdSaleBillTemp_Ptypeid ON WdSaleBillTemp(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdSaleBillTemp') AND name = 'NCIX_WdSaleBillTemp_Ktypeid')
--DROP INDEX NCIX_WdSaleBillTemp_Ktypeid ON WdSaleBillTemp 
CREATE NONCLUSTERED INDEX NCIX_WdSaleBillTemp_Ktypeid ON WdSaleBillTemp(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdSaleBillTemp') AND name = 'NCIX_WdSaleBillTemp_Orderid')
--DROP INDEX NCIX_WdSaleBillTemp_Orderid ON WdSaleBillTemp 
CREATE NONCLUSTERED INDEX NCIX_WdSaleBillTemp_Orderid ON WdSaleBillTemp(Orderid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdSaleBillTemp') AND name = 'NCIX_WdSaleBillTemp_SalePrice')
DROP INDEX NCIX_WdSaleBillTemp_SalePrice ON WdSaleBillTemp                             
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                              
CREATE NONCLUSTERED INDEX NCIX_WdSaleBillTemp_SalePrice ON WdSaleBillTemp(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdSaleBillTemp') AND name = 'NCIX_WdSaleBillTemp_Discount')
DROP INDEX NCIX_WdSaleBillTemp_Discount ON WdSaleBillTemp                 
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN discount NUMERIC(24,10)
    END
                         
CREATE NONCLUSTERED INDEX NCIX_WdSaleBillTemp_Discount ON WdSaleBillTemp(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdSaleBillTemp') AND name = 'NCIX_WdSaleBillTemp_Tax')
DROP INDEX NCIX_WdSaleBillTemp_Tax ON WdSaleBillTemp                               
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                              
CREATE NONCLUSTERED INDEX NCIX_WdSaleBillTemp_Tax ON WdSaleBillTemp(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WdSaleBillTemp') AND name = 'NCIX_WdSaleBillTemp_Id')
--DROP INDEX NCIX_WdSaleBillTemp_Id ON WdSaleBillTemp 
CREATE NONCLUSTERED INDEX NCIX_WdSaleBillTemp_Id ON WdSaleBillTemp(Id) 
------------------------------------------创建索引区域结束-----------------------------------------------
UPDATE WdSaleBillTemp SET sharefee = 0 WHERE sharefee IS NULL
GO
UPDATE WdSaleBillTemp SET OMBillID = 0 WHERE OMBillID IS NULL
GO
UPDATE BuyBill SET LendBillID = 0 WHERE LendBillID IS NULL
GO
UPDATE BuyBill SET LendBillNumberID = 0 WHERE LendBillNumberID IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
    
--网店加个字段，关联明细mid
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='mid'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD mid INT NULL DEFAULT(0)
END
GO	

--网店加个字段，关联明细nid
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='nid'
)
BEGIN
		ALTER TABLE WdSaleBillTemp ADD nid INT NULL DEFAULT(0)
END
GO	
                     
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='costprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN costprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='goodsno' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
		DECLARE @dfname VARCHAR(1000)
		SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('WdSaleBillTemp') AND name='goodsno')
		IF @dfname IS NOT NULL
			EXEC ('alter table WdSaleBillTemp drop constraint '+@dfname);
		ALTER TABLE WdSaleBillTemp ALTER COLUMN goodsno NUMERIC(24,10)
		ALTER TABLE WdSaleBillTemp ADD CONSTRAINT DF_WdSaleBillTemp_goodsno DEFAULT(0) FOR goodsno
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='BackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN BackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                    
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='ShareFee' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN ShareFee NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='TaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN TaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NTaxMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NTaxMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN MQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MUnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN MUnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN MSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN MDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='MTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN MTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CurMSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN CurMSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CurMDiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN CurMDiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CurMTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN CurMTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='InvoiceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN InvoiceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='InvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN InvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NInvoiceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NInvoiceMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='ReferPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN ReferPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSaleBillTemp' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE WdSaleBillTemp 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdSerialsDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WdSerialsDetail](
		[ordercode] [VARCHAR](50) NOT NULL,
		[goodscode] [VARCHAR](50) NOT NULL,
		[whstpt_erpid] [VARCHAR](50) NOT NULL ,
		[sku_erpid] [VARCHAR](500)  NULL DEFAULT('0'),
		[serial] VARCHAR(MAX) NOT NULL
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdSerialsDetail' AND a.Name='serial' AND  a.length <> 8000
    )
    BEGIN
	ALTER TABLE WdSerialsDetail 
	ALTER COLUMN serial VARCHAR(MAX)
    END

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdSerialsDetail',N'U') AND Name='serialRelationId')
BEGIN
	ALTER TABLE dbo.WdSerialsDetail
	ADD serialRelationId INT NOT  NULL DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'WdSerialsDetail',N'U') AND Name='mid')
BEGIN
	ALTER TABLE dbo.WdSerialsDetail
	ADD mid INT NOT  NULL DEFAULT(0) 
END
GO
--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------


--------------------------------------------创建索引区域开始-----------------------------------------------


--------------------------------------------创建索引区域结束-----------------------------------------------


--------------------------------------------修改字段小数位数区域开始-----------------------------------------------

                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



------------------------网店基本信息表------------------------

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdShopBaseInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].WdShopBaseInfo
		(
			[Id]			[int]				IDENTITY(1,1) NOT NULL,
			[Field]			[varchar](50)		NULL,
			[Value]			[varchar](max)		NULL,
		) ON [PRIMARY]
	 END
GO

IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'product' ) --产品
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('product','FenXiao')
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'pversion' ) --pversion产品版本
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('pversion','1.0')
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'DirectPost' ) --直接过账
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('DirectPost','False')
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'InventoryRefreshIntime' ) --库存实时更新
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('InventoryRefreshIntime','False')
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'BaseInfoRefresh' ) --基本信息实时更新
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('BaseInfoRefresh','False')
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'addsync' ) --新增上传
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('addsync','False')
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'autoSync' ) --自动下载
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('autoSync','False')
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'refreshTime' ) --下载时间间隔
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('refreshTime',10)
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'MonitorTimerTime' ) --汇总生成单据
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('MonitorTimerTime', CONVERT(VARCHAR(100), GETDATE(), 20))
IF NOT EXISTS( SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'BatchNumberDeal' ) --批次号处理
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('BatchNumberDeal',2)--0:自动读取最早入库的批次号/批次信息，1:一个批次数量不够则拆行处理，2：不自动填入批次号 
UPDATE dbo.WdShopBaseInfo SET Value = 10 WHERE Field ='refreshTime' AND Value = 0

--是否启用1688
IF NOT EXISTS(SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'isUse1688')
BEGIN
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('isUse1688',0)
END

--1688Id
IF NOT EXISTS(SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'dpl1688id')
BEGIN
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('dpl1688id','')
END	

--1688Name
IF NOT EXISTS(SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'dpl1688name')
BEGIN
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('dpl1688name','')
END

--上传单位
IF NOT EXISTS(SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'dpdw')
BEGIN
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('dpdw','0')
END	

--收款账户
IF NOT EXISTS(SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'dmf')
BEGIN
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('dmf','')
END	
GO

--专业市场代码
IF NOT EXISTS(SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'markername')
BEGIN
	INSERT INTO WdShopBaseInfo(Field,Value)VALUES('markername','')
END	
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

IF EXISTS(SELECT TOP 1 1 FROM WdShopBaseInfo WHERE Field = 'refreshTime' AND Value = 1)
BEGIN
	UPDATE dbo.WdShopBaseInfo SET Value = 10 WHERE Field = 'refreshTime'
END
GO



------------------------网店订单与本地单据对应表------------------------

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdShopBillRelation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].[WdShopBillRelation]
		(
			[Id]			[int]				IDENTITY(1,1) NOT NULL,
			[WdShopBillID]			[varchar](100)		NULL,
			[Billnumberid]			NUMERIC(18,0)		NULL,
			Flag			INT                                          ---单据类型标示flag=1是销售出库单，5是销售退货单，0是费用单

		) ON [PRIMARY]
	 END
GO


--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('[WdShopBillRelation]') and name='WdSyncFlag')
BEGIN
	ALTER TABLE [WdShopBillRelation] ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End   

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



------------------------网店订单与本地单据对应表------------------------

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdShopBillRelationTemp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].[WdShopBillRelationTemp]
		(
			[Id]			[int]				IDENTITY(1,1) NOT NULL,
			[WdShopBillID]			[varchar](100)		NULL,
			[Billnumberid]			NUMERIC(18,0)		NULL,
			Flag			INT                                          ---单据类型标示
		) ON [PRIMARY]
	 END
GO


--网店同步标志
IF Not EXISTS (SELECT * FROM syscolumns WHERE id=OBJECT_ID('[WdShopBillRelationTemp]') and name='WdSyncFlag')
BEGIN
	ALTER TABLE [WdShopBillRelationTemp] ADD  WdSyncFlag BIT NOT NULL DEFAULT 0; 
End   

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WdShopConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].WdShopConfig
		(
			[Id]			[int]				IDENTITY(1,1) NOT NULL,
			[WdShopName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
			[WdShopType] [varchar](50)  NOT NULL,
			[Btype] [varchar](50) NULL DEFAULT (''),
			[PtypeId] [varchar](50) NULL DEFAULT (''),
			[PayitemId]	[varchar](50) NULL DEFAULT ('')
		) ON [PRIMARY]
	 END
	 GO
	 
	 --增加分支机构列
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdShopConfig' AND a.Name='StypeId'
)
BEGIN
	ALTER TABLE WdShopConfig ADD StypeId VARCHAR(200) DEFAULT('')
END 
GO

	 --增加标志列
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdShopConfig' AND a.Name='Flag'
)
BEGIN
	ALTER TABLE WdShopConfig ADD Flag BIT DEFAULT 0
END 
GO

	 --增加费用项fullname
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdShopConfig' AND a.Name='PayitemFullname'
)
BEGIN
	ALTER TABLE WdShopConfig ADD PayitemFullname VARCHAR(200) DEFAULT('')
END 
GO

--增加单据摘要SummaryItem
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdShopConfig' AND a.Name='SummaryItem'
)
BEGIN
	ALTER TABLE WdShopConfig ADD SummaryItem VARCHAR(MAX) DEFAULT('')
END 
GO

--增加店铺id
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdShopConfig' AND a.Name='eshopid'
)
BEGIN
	ALTER TABLE WdShopConfig ADD eshopid VARCHAR(50) DEFAULT('')
END 
GO

--增加价格类型
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WdShopConfig' AND a.Name='pricetype'
)
BEGIN
	ALTER TABLE WdShopConfig ADD pricetype VARCHAR(50) NOT NULL DEFAULT('0')
END 
GO 



if NOT exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[webLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[webLog] (
		[id] [int] IDENTITY (1, 1) NOT NULL ,
		[type] [tinyint] NOT NULL ,
		[status] [int] NOT NULL ,
		[dateTime] [datetime] NOT NULL ,
		[elapsed] [int] NOT NULL ,
		[businessElapsed] [int] NOT NULL ,
		[url] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[params] [varchar] (1000) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[referrer] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[ipAddress] [varchar] (15) COLLATE Chinese_PRC_CI_AS NULL ,
		[ipLocation] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[browser] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[profileId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[loginUserId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
END	
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF  EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[dbo].[weblog]') and name = 'params' )
BEGIN
	ALTER TABLE weblog
		ALTER COLUMN params VARCHAR(1000);
END

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[WeighBeamConfig]    Script Date: 06/29/2011 14:07:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WeighBeamConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[WeighBeamConfig](
	[RecogniseAmount] [int] NOT NULL,
	[RecogniseCode] [varchar](120) NOT NULL,
	[CodingAmount] [int] NOT NULL,
	[PriceAmount] [int] NOT NULL,
	[WeightAmount] [int] NOT NULL
) ON [PRIMARY]

GO


if not exists (select name from syscolumns where id = object_id(N'[dbo].[WeighBeamConfig]') and name = 'XiaoYanAmount' )
BEGIN
    ALTER TABLE dbo.WeighBeamConfig ADD
        XiaoYanAmount int NULL DEFAULT(0)
END
GO
UPDATE WeighBeamConfig SET XiaoYanAmount=1 WHERE XiaoYanAmount IS NULL
GO

SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




--DROP TABLE WMS_ERPBillRelation

--章鱼侠单据与ERP单据ID对应表
IF NOT EXISTS (SELECT 1 FROM sysobjects WHERE id = object_id('WMS_ERPBillRelation') AND  TYPE = 'U')
BEGIN
	CREATE TABLE WMS_ERPBillRelation (
	   nId                  INT IDENTITY(1,1),
	   WMS_BillNumberID		NUMERIC(24,0) NOT NULL DEFAULT(-1),--主单据ID
	   BillType				INT NOT NULL DEFAULT(-1),--单据类型
	   ERP_BillNumberID		NUMERIC(24,0) NOT NULL DEFAULT(-1),--ERP单据ID
	   ERP_BillCode			VARCHAR(200)--ERP单据编号
	)
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WMS_ERPBillRelation' AND a.Name='RedWord'
)
BEGIN
	ALTER TABLE WMS_ERPBillRelation 
		ADD RedWord VARCHAR(2) NOT NULL DEFAULT('0')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WMS_ERPBillRelation' AND a.Name='ERP_BillType'
)
BEGIN
	ALTER TABLE WMS_ERPBillRelation 
		ADD ERP_BillType INT NOT NULL DEFAULT(-1)
END

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



------------------------ERP-章鱼侠 往来单位-供货商/客户对照关系表------------------------
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WmsErpBTypeContrastSetting]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].WmsErpBTypeContrastSetting
		(
			NId				INT NOT NULL IDENTITY(1,1),
			WMS_TypeId		VARCHAR(50),--往来单位 ID
			WMS_UserCode	VARCHAR(200),--往来单位 编号
			WMS_FullName	VARCHAR(200),--往来单位 名称
			
			ERP_TypeId		VARCHAR(50)--往来单位 ID	
			
		) ON [PRIMARY]
	 END
GO

--===========================预制数据==========================




------------------------ERP-章鱼侠 职员信息 对照关系表------------------------
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WmsErpEmployeeContrastSetting]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].WmsErpEmployeeContrastSetting
		(
			NId				INT NOT NULL IDENTITY(1,1),
			WMS_TypeId		VARCHAR(50),--职员信息 ID
			WMS_UserCode	VARCHAR(200),--职员信息 编号
			WMS_FullName	VARCHAR(200),--职员信息 名称
			
			ERP_TypeId		VARCHAR(50)--职员信息 ID	
			
		) ON [PRIMARY]
	 END
GO

--===========================预制数据==========================




------------------------ERP-章鱼侠 项目信息 对照关系表------------------------
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WmsErpItemContrastSetting]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].WmsErpItemContrastSetting
		(
			NId				INT NOT NULL IDENTITY(1,1),
			WMS_TypeId		VARCHAR(50),--项目信息 ID
			WMS_UserCode	VARCHAR(200),--项目信息 编号
			WMS_FullName	VARCHAR(50),--项目信息 名称
			
			ERP_TypeId		VARCHAR(50)--项目信息 ID	
			
		) ON [PRIMARY]
	 END
GO

--===========================预制数据==========================




------------------------ERP-章鱼侠 商品sku对照关系表------------------------
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WmsErpPtypeContrastSetting]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].WmsErpPtypeContrastSetting
		(
			NId				INT NOT NULL IDENTITY(1,1),
			WMS_TypeId		VARCHAR(50),--商品ID
			WMS_UserCode	VARCHAR(200),--商品编号
			WMS_FullName	VARCHAR(200),--商品名称
			WMS_Standard	VARCHAR(200),--规格
			WMS_Type		VARCHAR(200),--型号
			WMS_Unit1		VARCHAR(200),--单位名称型号	
            WMS_SKUId		VARCHAR(50),--SKUID
			WMS_Prop1		VARCHAR(200),--商品属性1
			WMS_Prop1Name	VARCHAR(200),--商品属性1
			WMS_Prop2		VARCHAR(200),--商品属性2
			WMS_Prop2Name	VARCHAR(200),--商品属性2
			ERP_TypeId		VARCHAR(50),--erp商品ID
			ERP_SKUId		VARCHAR(50),--erp商品自由项ID
			ERP_UnitId		VARCHAR(50),--erp单位
			
			ERP_CustomItemFrom	INT,--erp商品自由项 0基本项 1：组合项
			ERP_CustomItemId	INT,--erp商品自由项ID
			
			NType			INT NOT NULL DEFAULT(0)

		) ON [PRIMARY]
	 END
GO
--===========================修改表结构==========================
IF NOT EXISTS(SELECT * FROM SYSOBJECTS A INNER JOIN SYSCOLUMNS B ON A.id=B.id WHERE A.name='WmsErpPtypeContrastSetting' AND B.name='Erp_CustomItemName' )
	BEGIN
		ALTER TABLE WmsErpPtypeContrastSetting ADD Erp_CustomItemName VARCHAR(200)
	END
GO

--===========================预制数据==========================




------------------------ERP-章鱼侠 仓库信息 对照关系表------------------------
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WmsErpStockContrastSetting]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [dbo].WmsErpStockContrastSetting
		(
			NId				INT NOT NULL IDENTITY(1,1),
			WMS_TypeId		VARCHAR(50),--仓库信息 ID
			WMS_UserCode	VARCHAR(200),--仓库信息 编号
			WMS_FullName	VARCHAR(50),--仓库信息 名称
			
			ERP_TypeId		VARCHAR(50)--仓库信息 ID	
			
		) ON [PRIMARY]
	 END
GO

--===========================预制数据==========================






--DROP TABLE WMSExpenseBill

--章鱼侠 费用单明细表 
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WMSExpenseBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WMSExpenseBill](
		BillNumberID	NUMERIC(24,0) ,
		DId				INT IDENTITY(1,1),
		ATypeId			VARCHAR(50)	NOT NULL DEFAULT(''),--收款账户
		UserCode		VARCHAR(200) NOT NULL DEFAULT(''),--收款编号
		FullName		VARCHAR(200) NOT NULL DEFAULT(''),--收款账户
		Total			NUMERIC(24,10) NOT NULL DEFAULT(0.00),--金额
		Comment			VARCHAR(1000)NOT NULL  DEFAULT(''),--备注
		
		BillState		INT NOT NULL DEFAULT(0)	--基本信息是否正常数据 0=正常,-1=异常
	) 
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------


go 





--DROP TABLE WMSGatherBill

--章鱼侠 收款单明细表 
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WMSGatherBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WMSGatherBill](
		BillNumberID	NUMERIC(24,0)  ,
		DId				INT IDENTITY(1,1),
		ATypeId			VARCHAR(50)	NOT NULL DEFAULT(''),--收款账户
		UserCode		VARCHAR(200) NOT NULL DEFAULT(''),--收款编号
		FullName		VARCHAR(200) NOT NULL DEFAULT(''),--收款账户
		Total			NUMERIC(24,10) NOT NULL DEFAULT(0.00),--金额
		Comment			VARCHAR(1000)NOT NULL  DEFAULT(''),--备注
		
		BillState		INT NOT NULL DEFAULT(0)	--是否正常数据 基本信息完全匹配
	) 
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------



go 




--DROP TABLE WMSOrderIndex

--章鱼侠 订单主表
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WMSOrderIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WMSOrderIndex](
		BillNumberID	NUMERIC(24,0) IDENTITY(1,1),
		BillType		INT NOT NULL DEFAULT(0),--单据类型 11=销售出库单 45=销售退货单 36=费用单 4=收款单
		BillCode		VARCHAR(200) NOT NULL DEFAULT(''),--编号
		BillDate		DATETIME,--日期
		BtypeId			VARCHAR(50),--往来单位
		BFullName		VARCHAR(200),--往来单位
		EshopId			VARCHAR(50),--网店id
		EshopullName	VARCHAR(200),--网店名称
		Total			NUMERIC(24,10),--金额
		MallFee			NUMERIC(24,10),--商城扣费
		Customerfreightfee	NUMERIC(24,10),--买家运费
		Summary			VARCHAR(500),--	单据摘要
		KtypeId			VARCHAR(50),--仓库
		KFullName		VARCHAR(200),--仓库
		ETypeId			VARCHAR(50),--经手人
		EFullName		VARCHAR(200),--经手人
		Comment			VARCHAR(1000),--附加说明
		InputId			VARCHAR(50),--制单人
		InputFullName	VARCHAR(200),--制单人
		atypeid			VARCHAR(50),--收款账户
		afullname		VARCHAR(200),
		paytotal		NUMERIC(24,10),--费用单 实付金额
		custominfo1		VARCHAR(50),--refund-售后 freightfee-运费结算
		deptid			VARCHAR(50),--部门
		dfullname		VARCHAR(50),--部门
		
		BillState		INT NOT NULL DEFAULT(0)	--基本信息是否正常数据 0=正常,-1=异常
		
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
--IF NOT EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='WMSOrderIndex' AND a.Name='IsCreateErpDraft'
--)
--BEGIN
--	ALTER TABLE WMSOrderIndex 
--		ADD IsCreateErpDraft  VARCHAR(2)
--END

--GO
--IF EXISTS(
--	SELECT a.Name FROM syscolumns a
--	INNER JOIN sysobjects	b
--	ON a.ID=b.ID
--	WHERE b.Name='WMSOrderIndex' AND a.Name='BillState'
--)
--BEGIN
--	ALTER TABLE WMSOrderIndex 
--		DROP COLUMN BillState
--END

--GO
--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------



go 




--DROP TABLE WMSSaleBackBill

--章鱼侠 销售退货单明细表 
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WMSSaleBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WMSSaleBackBill](
		BillNumberID	NUMERIC(24,0),
		DId				INT IDENTITY(1,1),
		PTypeId			VARCHAR(50) NOT NULL,--商品ID
		UserCode		VARCHAR(200) NOT NULL,--商品编号
		FullName		VARCHAR(200) NOT NULL,--商品名称
		SKuId			VARCHAR(50) NOT NULL,--商品SKU
		Unit			INT,--商品单位
		UnitRate		NUMERIC(24,10) NOT NULL DEFAULT(0),--单位换算率
		AssQty			NUMERIC(24,10) NOT NULL DEFAULT(0),--数量
		AssPrice		NUMERIC(24,10) NOT NULL DEFAULT(0),--单价
		Total			NUMERIC(24,10) NOT NULL DEFAULT(0),--金额
		DisCount		NUMERIC(24,10) NOT NULL DEFAULT(1),--折扣
		Tax				NUMERIC(24,10) NOT NULL DEFAULT(0),--税率(%)
		SubQty			NUMERIC(24,10) NOT NULL DEFAULT(0),--副单位数量
		ProduceDate		DATETIME,--生产日期
		ExpirationDate	DATETIME,--到期日期
		BatchNo			VARCHAR(200) NOT NULL DEFAULT(''),--批次号
		PStatus			INT NOT NULL DEFAULT(0),--状态
		Comment			VARCHAR(1000) NOT NULL DEFAULT(''),--备注
		Position		VARCHAR(50)  NOT NULL DEFAULT(''),--仓库货位
		
		BillState		INT NOT NULL DEFAULT(0)	--基本信息是否正常数据 0=正常,-1=异常
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WMSSaleBackBill' AND a.Name='Qty'
)
BEGIN
	ALTER TABLE WMSSaleBackBill 
		ADD Qty	NUMERIC(24,10) NOT NULL DEFAULT(0)--基本单位数量
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WMSSaleBackBill' AND a.Name='Price'
)
BEGIN
	ALTER TABLE WMSSaleBackBill 
		ADD Price NUMERIC(24,10) NOT NULL DEFAULT(0)--基本单位金额
END

GO


--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------


go 



















--DROP TABLE WMSSaleBill

--章鱼侠 销售出库单明细表 
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[WMSSaleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WMSSaleBill](
		BillNumberID	NUMERIC(24,0),
		DId				INT IDENTITY(1,1),
		PTypeId			VARCHAR(50) NOT NULL,--商品ID
		UserCode		VARCHAR(200) NOT NULL,--商品编号
		FullName		VARCHAR(200) NOT NULL,--商品名称
		SKuId			VARCHAR(50) NOT NULL,--商品SKU
		Unit			INT,--商品单位
		UnitRate		NUMERIC(24,10),--单位换算率
		AssQty			NUMERIC(24,10),--数量
		AssPrice		NUMERIC(24,10),--单价
		Total			NUMERIC(24,10),--金额
		DisCount		NUMERIC(24,10) NOT NULL DEFAULT(1),--折扣
		AsstpPrice		NUMERIC(24,10),--折后单价
		Tax				NUMERIC(24,10) NOT NULL DEFAULT(0),--税率(%)
		SubQty			NUMERIC(24,10) NOT NULL DEFAULT(0),--副单位数量
		ProduceDate		DATETIME,--生产日期
		ExpirationDate	DATETIME,--到期日期
		BatchNo			VARCHAR(200) NOT NULL DEFAULT(''),--批次号
		IsGift			BIT NOT NULL DEFAULT(0),--是否赠品
		Comment			VARCHAR(1000) NOT NULL DEFAULT(''),--备注
		Position		VARCHAR(50)  NOT NULL DEFAULT(''),--仓库货位
		
		BillState		INT NOT NULL DEFAULT(0)	--基本信息是否正常数据 0=正常,-1=异常
	) 
END
GO


------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WMSSaleBill' AND a.Name='Qty'
)
BEGIN
	ALTER TABLE WMSSaleBill 
		ADD Qty	NUMERIC(24,10) NOT NULL DEFAULT(0)--基本单位数量
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='WMSSaleBill' AND a.Name='Price'
)
BEGIN
	ALTER TABLE WMSSaleBill 
		ADD Price NUMERIC(24,10) NOT NULL DEFAULT(0)--基本单位金额
END

GO

--------------------------------------------表修改区域结束-------------------------------------------------


--------------------------------------------删除索引区域开始-----------------------------------------------


--------------------------------------------删除索引区域结束-----------------------------------------------


go 
























/****** 对象:  Table [dbo].[wx_Bill_Call]    脚本日期: 05/05/2010 14:49:54 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_Call]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_Call](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Call_Qty]  DEFAULT (1),
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_Call_IsUnit2]  DEFAULT (0),
		[Serial] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Call_Serial]  DEFAULT (''),
		[BuyDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Call_BuyDate]  DEFAULT (''),
		[ErrDes] [varchar](3000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Call_ErrDes]  DEFAULT (''),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Call_Total]  DEFAULT (0),
		[ErrDeal] [varchar](3000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Call_ErrDeal]  DEFAULT (''),
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Call_ETypeID]  DEFAULT (''),
		[BaoXiu] [int] NOT NULL CONSTRAINT [DF_wx_Bill_Call_BaoXiu]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Call_comment]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL,
		[State] [int] NULL CONSTRAINT [DF_wx_Bill_Call_State]  DEFAULT (0),
		[ifYearBillDisplay] [int] NULL CONSTRAINT [DF_wx_Bill_Call_ifYearBillDisplay]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    GoodsNumber		varchar(100) NULL DEFAULT (''),
	    CargoID			INT		 NULL DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1)
	    ,ShowOrder INT DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Call',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Call
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Call',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Call
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Call',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_Call
	ADD ShowOrder INT  DEFAULT(0)
END
GO
	UPDATE wx_Bill_Call SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
Go
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_Call ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_Call SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_Call ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_Call ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE wx_Bill_Call ADD GoodsNumber varchar(100) NULL DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_Call ADD CargoID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_Call ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_Call ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_CALL') AND name = 'CIX_WX_BILL_CALL_BillNumberID')
--DROP INDEX CIX_WX_BILL_CALL_BillNumberID ON WX_BILL_CALL 
CREATE CLUSTERED INDEX CIX_WX_BILL_CALL_BillNumberID ON WX_BILL_CALL(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_CALL') AND name = 'NCIX_WX_BILL_CALL_Ptypeid')
--DROP INDEX NCIX_WX_BILL_CALL_Ptypeid ON WX_BILL_CALL 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_CALL_Ptypeid ON WX_BILL_CALL(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Call 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Call 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Call 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Call' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Call 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_GetBack]    脚本日期: 05/05/2010 14:49:55 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_GetBack]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_GetBack](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_GetBack_Qty]  DEFAULT (1),
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_GetBack_IsUnit2]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_GetBack_Comment]  DEFAULT (''),
		[Serial] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_GetBack_Serial]  DEFAULT (''),
		[JieJianBillNumberID] [int] NULL CONSTRAINT [DF_wx_Bill_GetBack_JieJianBillNumberID]  DEFAULT ((-1)),
		[JieJianID] [int] NULL CONSTRAINT [DF_wx_Bill_GetBack_JieJianID]  DEFAULT ((-1)),
		[JieJianPTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_GetBack_JieJianPTypeID]  DEFAULT (''),
		[JieJianState] [int] NULL CONSTRAINT [DF_wx_Bill_GetBack_JieJianState]  DEFAULT ((-1)),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_GetBack_Total]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_GetBack_CompleteQTY]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    GoodsNumber		varchar(100) NULL DEFAULT (''),
	    CargoID			INT		 NULL DEFAULT(0),
		NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1)
	    ,ShowOrder INT DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_getback',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_getback
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_getback',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_getback
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_getback',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE wx_bill_getback 
	ADD ShowOrder INT DEFAULT(0)
END
GO	
	UPDATE wx_bill_getback SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_GetBack ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_GetBack SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_GetBack ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_GetBack ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE wx_Bill_GetBack ADD GoodsNumber varchar(100) NULL DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_GetBack ADD CargoID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_GetBack ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_GetBack ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_GetBack',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE wx_Bill_GetBack ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE wx_Bill_GetBack SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_GetBack',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE wx_Bill_GetBack ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE wx_Bill_GetBack SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO
--
-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'PromoType' 
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='wx_Bill_GetBack';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_GETBACK') AND name = 'CIX_WX_BILL_GETBACK_BillNumberID')
--DROP INDEX CIX_WX_BILL_GETBACK_BillNumberID ON WX_BILL_GETBACK 
CREATE CLUSTERED INDEX CIX_WX_BILL_GETBACK_BillNumberID ON WX_BILL_GETBACK(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_GETBACK') AND name = 'NCIX_WX_BILL_GETBACK_Ptypeid')
--DROP INDEX NCIX_WX_BILL_GETBACK_Ptypeid ON WX_BILL_GETBACK 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_GETBACK_Ptypeid ON WX_BILL_GETBACK(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_GetBack 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_GetBack 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_GetBack 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_GetBack 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_GetBack 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_GetBack 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_GetBack' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_GetBack 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_Goto]    脚本日期: 05/05/2010 14:49:56 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_Goto]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_Goto](
		[BillNumberiD] [numeric](10, 0) NOT NULL,
		[InOrOut] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_Goto_IsUnit2]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Goto_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Goto_Total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Goto_Comment]  DEFAULT (''),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Goto_Serial]  DEFAULT (''),
		[wxProperty] [int] NULL CONSTRAINT [DF_wx_Bill_Goto_wxProperty]  DEFAULT (1),
		[OutFactoryDate] [datetime] NULL,
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Goto_InputCostPrice]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Goto_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Goto_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Goto_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Goto_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Goto_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_wx_Bill_Goto_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_wx_Bill_Goto_HandZeroCost]  DEFAULT (0),
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    CargoID				 INT		 NULL DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1)
	    ,ShowOrder INT DEFAULT(0)
	    ,OutFactQty NUMERIC(24,10) DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')	
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Goto',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Goto
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Goto',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Goto
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Goto',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.wx_Bill_Goto
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Goto',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.wx_Bill_Goto
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.wx_Bill_Goto SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_goto',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_Goto
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_bill_goto SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_Goto ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_Goto SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_Goto ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_Goto ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='CargoID'
)
BEGIN
	ALTER TABLE wx_Bill_Goto ADD CargoID int NULL DEFAULT (0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('wx_Bill_Goto') AND b.name='cargoid'
	)
	begin
		select @sql=' alter table wx_Bill_Goto drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('wx_Bill_Goto') AND b.name='cargoid'
		EXEC(@sql);
	END
	ALTER TABLE wx_Bill_Goto ALTER COLUMN CargoID int NULL;
	ALTER TABLE wx_Bill_Goto add CONSTRAINT DF_wx_Bill_Goto_CargoId DEFAULT(0) FOR CargoId
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_Goto ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_Goto ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='PromoType'
)
BEGIN
		ALTER TABLE wx_Bill_Goto ADD PromoType INT NOT NULL DEFAULT(0) --促销类型 0是无 1简易促销 2普通促销
END
GO

--
-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'PromoType' 
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='wx_Bill_Goto';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_GOTO') AND name = 'CIX_WX_BILL_GOTO_BillNumberID')
--DROP INDEX CIX_WX_BILL_GOTO_BillNumberID ON WX_BILL_GOTO 
CREATE CLUSTERED INDEX CIX_WX_BILL_GOTO_BillNumberID ON WX_BILL_GOTO(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_GOTO') AND name = 'NCIX_WX_BILL_GOTO_Ptypeid')
--DROP INDEX NCIX_WX_BILL_GOTO_Ptypeid ON WX_BILL_GOTO 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_GOTO_Ptypeid ON WX_BILL_GOTO(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Goto 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Goto 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Goto 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Goto 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Goto 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Goto 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Goto 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Goto' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Goto 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_In]    脚本日期: 05/05/2010 14:49:56 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_In]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_In](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_In_IsUnit2]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_In_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_In_Total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_In_Comment]  DEFAULT (''),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_In_Serial]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL,
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_In_InputCostPrice]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_In_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_In_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_In_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_In_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_In_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_wx_Bill_In_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_wx_Bill_In_HandZeroCost]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  null,
	    CargoID			INT		 NULL DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1),
	    ShowOrder INT DEFAULT(0),
	    InFactQty NUMERIC(24,10) DEFAULT(0),
	    OutFactQty NUMERIC(24,10) DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')	
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_in',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_in
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_in',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_in
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_in',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.wx_bill_in
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_in',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.wx_Bill_In
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.wx_Bill_In SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_in',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.wx_Bill_In
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.wx_Bill_In SET OutFactQty=0 WHERE OutFactQty IS NULL
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_in',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_In
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_bill_in SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_In ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_In SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_In ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_In ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_In ADD CargoID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_In ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_In ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_IN') AND name = 'CIX_WX_BILL_IN_BillNumberID')
--DROP INDEX CIX_WX_BILL_IN_BillNumberID ON WX_BILL_IN 
CREATE CLUSTERED INDEX CIX_WX_BILL_IN_BillNumberID ON WX_BILL_IN(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_IN') AND name = 'NCIX_WX_BILL_IN_Ptypeid')
--DROP INDEX NCIX_WX_BILL_IN_Ptypeid ON WX_BILL_IN 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_IN_Ptypeid ON WX_BILL_IN(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_In 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_In 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_In 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_In 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_In 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_In 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_In 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_In' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_In 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_JieJian]    脚本日期: 05/05/2010 14:49:57 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_JieJian]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_JieJian](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_JieJian_Qty]  DEFAULT (1),
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_JieJian_IsUnit2]  DEFAULT (0),
		[Serial] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_JieJian_Serial]  DEFAULT (''),
		[BuyDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_JieJian_BuyDate]  DEFAULT (''),
		[ErrDes] [varchar](3000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_JieJian_ErrDes]  DEFAULT (''),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_JieJian_Total]  DEFAULT (0),
		[AddTotal] [numeric](18, 4) NULL,
		[ErrDeal] [varchar](3000) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_JieJian_ErrDeal]  DEFAULT (''),
		[RepairMode] [int] NULL CONSTRAINT [DF_wx_Bill_JieJian_RepairMode]  DEFAULT (0),
		[ETypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_JieJian_ETypeID]  DEFAULT (''),
		[BaoXiu] [int] NOT NULL CONSTRAINT [DF_wx_Bill_JieJian_BaoXiu]  DEFAULT ((-1)),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_JieJian_comment]  DEFAULT (''),
		[State] [int] NULL CONSTRAINT [DF_wx_Bill_JieJian_State]  DEFAULT (0),
		[SendBackPTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL Default(''),
		[SendBackSerial] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_JieJian_SendBackSerial]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL CONSTRAINT [DF_wx_Bill_JieJian_OutFactoryDate]  DEFAULT (''),
		[ifYearBillDisplay] [int] NULL CONSTRAINT [DF_wx_Bill_JieJian_ifYearBillDisplay]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    GoodsNumber		varchar(100) NULL DEFAULT (''),
	    CargoID			INT		 NULL DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1)
	    ,ShowOrder INT DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_jiejian',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_jiejian
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_jiejian',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_jiejian
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_jiejian',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE wx_bill_jiejian 
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_bill_jiejian SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_JieJian ADD STypeID VARCHAR(50) DEFAULT('')
	
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_JieJian SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_JieJian ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_JieJian ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE wx_Bill_JieJian ADD GoodsNumber varchar(100) NULL DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_JieJian ADD CargoID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_JieJian ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_JieJian ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_JIEJIAN') AND name = 'CIX_WX_BILL_JIEJIAN_BillNumberID')
--DROP INDEX CIX_WX_BILL_JIEJIAN_BillNumberID ON WX_BILL_JIEJIAN 
CREATE CLUSTERED INDEX CIX_WX_BILL_JIEJIAN_BillNumberID ON WX_BILL_JIEJIAN(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_JIEJIAN') AND name = 'NCIX_WX_BILL_JIEJIAN_Ptypeid')
--DROP INDEX NCIX_WX_BILL_JIEJIAN_Ptypeid ON WX_BILL_JIEJIAN 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_JIEJIAN_Ptypeid ON WX_BILL_JIEJIAN(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_JieJian 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_JieJian 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='AddTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_JieJian 
	ALTER COLUMN AddTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_JieJian 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_JieJian' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_JieJian 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_Move]    脚本日期: 05/05/2010 14:49:58 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_Move]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_Move](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_Move_IsUnit2]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Move_Comment]  DEFAULT (''),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Move_Serial]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  null,
	    GoodsNumber			 varchar(100) NULL DEFAULT (''),
	    CargoID	INT NULL DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1),
	    ShowOrder INT DEFAULT(0),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_move',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_move
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_move',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_move
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO


IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_move',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_Move
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_bill_move SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_Move ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_Move SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_Move ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_Move ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE wx_Bill_Move ADD GoodsNumber varchar(100) NULL DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_Move ADD CargoID INT NULL DEFAULT(0)
END
GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_Move ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_Move ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO


------------------------------------------表修改区域结束-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('wx_Bill_Move') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table wx_Bill_Move drop constraint '+@dfname);
		
	ALTER TABLE wx_Bill_Move ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE wx_Bill_Move ADD CONSTRAINT DF_wx_Bill_Move_Serial DEFAULT('') FOR Serial
END
GO

------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_MOVE') AND name = 'CIX_WX_BILL_MOVE_BillNumberID')
--DROP INDEX CIX_WX_BILL_MOVE_BillNumberID ON WX_BILL_MOVE 
CREATE CLUSTERED INDEX CIX_WX_BILL_MOVE_BillNumberID ON WX_BILL_MOVE(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_MOVE') AND name = 'NCIX_WX_BILL_MOVE_Ptypeid')
--DROP INDEX NCIX_WX_BILL_MOVE_Ptypeid ON WX_BILL_MOVE 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_MOVE_Ptypeid ON WX_BILL_MOVE(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Move 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Move 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Move' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Move 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_Out]    脚本日期: 05/05/2010 14:49:59 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_Out]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_Out](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_Out_IsUnit2]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Out_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Out_Total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Out_Comment]  DEFAULT (''),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Out_Serial]  DEFAULT (''),
		[OutFactoryDate] [datetime] NULL,
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Out_InputCostPrice]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Out_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Out_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Out_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Out_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Out_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_wx_Bill_Out_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_wx_Bill_Out_HandZeroCost]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    CargoID				 INT				  NULL	DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1),
	    ShowOrder INT DEFAULT(0),
	    InFactQty NUMERIC(24,10),
	    [DraftFlag] [bit] NOT NULL DEFAULT (1),
	    [IsIniFlag] [bit] NOT NULL DEFAULT (0),
		[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Out',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Out
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Out',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Out
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Out',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.wx_Bill_Out
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Out',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.wx_Bill_Out
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.wx_Bill_Out SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Out',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_Out
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_Bill_Out SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_Out ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_Out SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_Out ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_Out ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_Out ADD CargoID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_Out ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_Out ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('wx_Bill_Out') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table wx_Bill_Out drop constraint '+@dfname);
		
	ALTER TABLE wx_Bill_Out ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE wx_Bill_Out ADD CONSTRAINT DF_wx_Bill_Out_Serial DEFAULT('') FOR Serial

END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_OUT') AND name = 'CIX_WX_BILL_OUT_BillNumberID')
--DROP INDEX CIX_WX_BILL_OUT_BillNumberID ON WX_BILL_OUT 
CREATE CLUSTERED INDEX CIX_WX_BILL_OUT_BillNumberID ON WX_BILL_OUT(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_OUT') AND name = 'NCIX_WX_BILL_OUT_Ptypeid')
--DROP INDEX NCIX_WX_BILL_OUT_Ptypeid ON WX_BILL_OUT 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_OUT_Ptypeid ON WX_BILL_OUT(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Out 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Out 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Out 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Out 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Out 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Out 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Out 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Out' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Out 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_Replace]    脚本日期: 05/05/2010 14:50:00 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_Replace]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_Replace](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Replace_Qty]  DEFAULT (1),
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_Replace_IsUnit2]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Replace_Total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Replace_Comment]  DEFAULT (''),
		[Serial] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Replace_Serial]  DEFAULT (''),
		[JieJianBillNumberID] [int] NULL CONSTRAINT [DF_wx_Bill_Replace_JieJianBillNumberID]  DEFAULT ((-1)),
		[JieJianID] [int] NULL CONSTRAINT [DF_wx_Bill_Replace_JieJianID]  DEFAULT ((-1)),
		[JieJianPTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Replace_JieJianPTypeID]  DEFAULT (''),
		[JieJianState] [int] NULL CONSTRAINT [DF_wx_Bill_Replace_JieJianState]  DEFAULT ((-1)),
		[OutFactoryDate] [datetime] NULL,
		[wxProperty] [int] NULL CONSTRAINT [DF_wx_Bill_Replace_wxProperty]  DEFAULT (1),
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Replace_InputCostPrice]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Replace_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Replace_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Replace_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Replace_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Replace_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_wx_Bill_Replace_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_wx_Bill_Replace_HandZeroCost]  DEFAULT (0),
		[CompleteQTY] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Replace_CompleteQTY]  DEFAULT (0),
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  null,
	    CargoID			INT		 NULL DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1)
	    ,ShowOrder INT DEFAULT(0)
	    ,OutFactQty NUMERIC(24,10) DEFAULT(0)
	    ,[DraftFlag] [bit] NOT NULL DEFAULT (1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT (0)
		,[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')	
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Replace',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Replace
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Replace',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Replace
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Replace',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.wx_Bill_Replace
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Replace',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.wx_Bill_Replace
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.wx_Bill_Replace SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_replace',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_Replace
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_bill_replace SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_Replace ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_Replace SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_Replace ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_Replace ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_Replace ADD CargoID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_Replace ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_Replace ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Replace',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE wx_Bill_Replace ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE wx_Bill_Replace SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Replace',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE wx_Bill_Replace ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE wx_Bill_Replace SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO
--
-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t SELECT 'PromoType' 
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='wx_Bill_Replace';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_REPLACE') AND name = 'CIX_WX_BILL_REPLACE_BillNumberID')
--DROP INDEX CIX_WX_BILL_REPLACE_BillNumberID ON WX_BILL_REPLACE 
CREATE CLUSTERED INDEX CIX_WX_BILL_REPLACE_BillNumberID ON WX_BILL_REPLACE(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_REPLACE') AND name = 'NCIX_WX_BILL_REPLACE_Ptypeid')
--DROP INDEX NCIX_WX_BILL_REPLACE_Ptypeid ON WX_BILL_REPLACE 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_REPLACE_Ptypeid ON WX_BILL_REPLACE(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Replace' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Replace 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_Self]    脚本日期: 05/05/2010 14:50:01 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_Self]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_Self](
		[BillNumberiD] [numeric](10, 0) NOT NULL,
		[InOrOut] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_Self_IsUnit2]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Self_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Self_Total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Self_Comment]  DEFAULT (''),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Self_Serial]  DEFAULT (''),
		[wxProperty] [int] NULL CONSTRAINT [DF_wx_Bill_Self_wxProperty]  DEFAULT (1),
		[OutFactoryDate] [datetime] NULL,
		[InputCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Self_InputCostPrice]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Self_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Self_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Self_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Self_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Self_GoodsCostPrice]  DEFAULT (0),
		[GoodsCostTotal] [numeric](18, 2) NULL CONSTRAINT [DF_wx_Bill_Self_GoodsCostTotal]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_wx_Bill_Self_HandZeroCost]  DEFAULT (0),
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  NULL,
	    CargoID				 INT				NULL DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1)
	    ,ShowOrder INT DEFAULT(0)
	    ,InFactQty NUMERIC(24,10) DEFAULT(0)
	    ,OutFactQty NUMERIC(24,10) DEFAULT(0)
	    ,[DraftFlag] [bit] NOT NULL DEFAULT (1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT (0)
		,[KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')	    
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Self',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Self
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Self',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_Bill_Self
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

-- 添加仓库状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Self',N'U') AND Name='KTypeID')
BEGIN
	ALTER TABLE dbo.wx_Bill_Self
	ADD [KTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Self',N'U') AND Name='OutFactQty')
BEGIN
	ALTER TABLE dbo.wx_Bill_Self
	ADD OutFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.wx_Bill_Self SET OutFactQty=0 WHERE OutFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_Self',N'U') AND Name='InFactQty')
BEGIN
	ALTER TABLE dbo.wx_Bill_Self
	ADD InFactQty NUMERIC(24,10) NULL DEFAULT(0) 
END
GO
	UPDATE dbo.wx_Bill_Self SET InFactQty=0 WHERE InFactQty IS NULL
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_self',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_Self
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_bill_self SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_Self ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_Self SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_Self ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_Self ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_Self ADD CargoID int NULL DEFAULT (0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('wx_Bill_Self') AND b.name='cargoid'
	)
	begin
		select @sql=' alter table wx_Bill_Self drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('wx_Bill_Self') AND b.name='cargoid'
		EXEC(@sql);
	END
	ALTER TABLE wx_Bill_Self ALTER COLUMN CargoID int NULL;
	ALTER TABLE wx_Bill_Self add CONSTRAINT DF_wx_Bill_Self_CargoId DEFAULT(0) FOR CargoId
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_Self ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_Self ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('wx_Bill_Self') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table wx_Bill_Self drop constraint '+@dfname);
		
	ALTER TABLE wx_Bill_Self ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE wx_Bill_Self ADD CONSTRAINT DF_wx_Bill_Self_Serial DEFAULT('') FOR Serial
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_SELF') AND name = 'CIX_WX_BILL_SELF_BillNumberID')
--DROP INDEX CIX_WX_BILL_SELF_BillNumberID ON WX_BILL_SELF 
CREATE CLUSTERED INDEX CIX_WX_BILL_SELF_BillNumberID ON WX_BILL_SELF(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_SELF') AND name = 'NCIX_WX_BILL_SELF_Ptypeid')
--DROP INDEX NCIX_WX_BILL_SELF_Ptypeid ON WX_BILL_SELF 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_SELF_Ptypeid ON WX_BILL_SELF(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Self 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Self 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Self 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='InputCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Self 
	ALTER COLUMN InputCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Self 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='GoodsCostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Self 
	ALTER COLUMN GoodsCostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Self 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Self' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Self 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_Send]    脚本日期: 05/05/2010 14:50:02 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_Bill_Send]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_Bill_Send](
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 4) NOT NULL,
		[IsUnit2] [int] NOT NULL CONSTRAINT [DF_wx_Bill_Send_IsUnit2]  DEFAULT (0),
		[SendBackQty] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Send_NoSendBackQty]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_Bill_Send_Total]  DEFAULT (0),
		[Comment] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Send_Comment]  DEFAULT (''),
		[Serial] [text] COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Send_Serial]  DEFAULT (''),
		[JieJianBillNumberID] [int] NULL CONSTRAINT [DF_wx_Bill_Send_JieJianBillID]  DEFAULT ((-1)),
		[JieJianID] [int] NULL CONSTRAINT [DF_wx_Bill_Send_JieJianID]  DEFAULT ((-1)),
		[JieJianPTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_Bill_Send_JieJianPTypeID]  DEFAULT (''),
		[JieJianState] [int] NULL CONSTRAINT [DF_wx_Bill_Send_JieJianState]  DEFAULT ((-1)),
		[OutFactoryDate] [datetime] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID               bigint               null,
	    IsCombined           int                  null,
	    GoodsNumber		varchar(100) NULL DEFAULT (''),
	    CargoID			INT		 NULL DEFAULT(0),
	    NQty   numeric(22,10)     NULL  DEFAULT(0),
	    UnitRate   numeric(22,10)   NULL  DEFAULT(1)
	    ,ShowOrder INT DEFAULT(0)
	    ,[DraftFlag] [bit] NOT NULL CONSTRAINT [DF_wx_bill_send_draft]  DEFAULT (1)
	    ,[IsIniFlag] [bit] NOT NULL DEFAULT (0)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始--------------------------------------------------- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_send',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_send
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_send',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_send
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_send',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_Send
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_bill_send SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_Bill_Send ADD STypeID VARCHAR(50) DEFAULT('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_Bill_Send SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='ItemID'
)
BEGIN
		ALTER TABLE wx_Bill_Send ADD ItemID  BIGINT
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='IsCombined'
)
BEGIN
		ALTER TABLE wx_Bill_Send ADD IsCombined   INT
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='GoodsNumber'
)
BEGIN
		ALTER TABLE wx_Bill_Send ADD GoodsNumber varchar(100) NULL DEFAULT ('')
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='CargoID'
)
BEGIN
		ALTER TABLE wx_Bill_Send ADD CargoID INT NULL DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='NQty'
)
BEGIN
		ALTER TABLE wx_Bill_Send ADD NQty   numeric(22,10)     NULL  DEFAULT(0)
END
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='UnitRate'
)
BEGIN
		ALTER TABLE wx_Bill_Send ADD UnitRate   numeric(22,10)   NULL  DEFAULT(1)
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='Errdes1'
)
BEGIN
		ALTER TABLE wx_Bill_Send ADD Errdes1 VARCHAR(2000) NULL DEFAULT('')
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('wx_Bill_Send') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table wx_Bill_Send drop constraint '+@dfname);
		
	ALTER TABLE wx_Bill_Send ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE wx_Bill_Send ADD CONSTRAINT DF_wx_Bill_Send_Serial DEFAULT('') FOR Serial
END
GO


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Send 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='SendBackQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Send 
	ALTER COLUMN SendBackQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Send 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Send 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_Send' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_Send 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_Bill_SendBack]    脚本日期: 05/05/2010 14:50:02 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[wx_Bill_SendBack]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        CREATE TABLE [dbo].[wx_Bill_SendBack]
            (
              [BillNumberID] [numeric](10, 0) NOT NULL ,
              [PTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                      NOT NULL ,
              [Qty] [numeric](18, 4) NOT NULL ,
              [IsUnit2] [int]
                NOT NULL
                CONSTRAINT [DF_wx_Bill_SendBack_IsUnit2] DEFAULT ( 0 ) ,
              [Total] [numeric](18, 4)
                NULL
                CONSTRAINT [DF_wx_Bill_SendBack_Total] DEFAULT ( 0 ) ,
              [Comment] [varchar](255)
                COLLATE Chinese_PRC_CI_AS
                NULL
                CONSTRAINT [DF_wx_Bill_SendBack_Comment] DEFAULT ( '' ) ,
              [Serial] [text]
                COLLATE Chinese_PRC_CI_AS
                NULL
                CONSTRAINT [DF_wx_Bill_SendBack_Serial] DEFAULT ( '' ) ,
              [SendBillNumberID] [int]
                NULL
                CONSTRAINT [DF_wx_Bill_SendBack_SendBilID] DEFAULT ( ( -1) ) ,
              [SendID] [int]
                NULL
                CONSTRAINT [DF_wx_Bill_SendBack_SendID] DEFAULT ( ( -1) ) ,
              [SendPTypeID] [varchar](50)
                COLLATE Chinese_PRC_CI_AS
                NULL
                CONSTRAINT [DF_wx_Bill_SendBack_SendPTypeID] DEFAULT ( '' ) ,
              [CompleteQTY] [numeric](18, 4)
                NULL
                CONSTRAINT [DF_wx_Bill_SendBack_CompleteQTY] DEFAULT ( 0 ) ,
              [OutFactoryDate] [datetime] NULL ,
              [TeamNo] [int] NULL ,
              [TeamNo1] [int] NULL ,
              [ID] [int] IDENTITY(1, 1)
                         NOT NULL ,
              [Stypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS
                                      NULL
                                      DEFAULT ( '' ) ,
              ItemID BIGINT NULL ,
              IsCombined INT NULL ,
              GoodsNumber VARCHAR(100) NULL
                                       DEFAULT ( '' ) ,
              CargoID INT NULL
                          DEFAULT ( 0 ) ,
              NQty NUMERIC(22, 10) NULL
                                   DEFAULT ( 0 ) ,
              UnitRate NUMERIC(22, 10) NULL
                                       DEFAULT ( 1 )
              ,ShowOrder INT DEFAULT(0)
              ,[DraftFlag] [bit] NOT NULL DEFAULT (1)
			  ,[IsIniFlag] [bit] NOT NULL DEFAULT(0)
            )
        ON  [PRIMARY] TEXTIMAGE_ON [PRIMARY]


    END
GO

------------------------------------------表修改区域开始-------------------------------------------------
-- 添加草稿状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_sendback',N'U') AND Name='DraftFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_sendback
	ADD [DraftFlag] [bit] NOT NULL DEFAULT (1)
END
GO

-- 添加期初状态字段，用于草稿库存统计使用,为了保证表结构的一致性所有明细表均添加该字段	--施训果
IF NOT EXISTS(SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_sendback',N'U') AND Name='IsIniFlag')
BEGIN
	ALTER TABLE dbo.wx_bill_sendback
	ADD [IsIniFlag] [bit] NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_bill_sendback',N'U') AND Name='ShowOrder')
BEGIN
	ALTER TABLE dbo.wx_Bill_SendBack
	ADD ShowOrder INT DEFAULT(0)
END
GO
	UPDATE wx_bill_sendback SET ShowOrder=ID WHERE ShowOrder=0 OR ShowOrder IS NULL
GO
IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'wx_Bill_SendBack'
                        AND a.Name = 'STypeID' ) 
    BEGIN
        ALTER TABLE wx_Bill_SendBack ADD STypeID VARCHAR(50) DEFAULT('')
        DECLARE @strSql VARCHAR(8000)
	
        SELECT  @strSql = '
	UPDATE wx_Bill_SendBack SET STypeID=' + CHAR(39) + '00001' + CHAR(39) + '
	WHERE STypeID=' + CHAR(39) + CHAR(39) + ' OR STypeID IS NULL '
	
        EXEC(@strSql)
    END

GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'wx_Bill_SendBack'
                        AND a.Name = 'ItemID' ) 
    BEGIN
        ALTER TABLE wx_Bill_SendBack ADD ItemID  BIGINT
    END
GO
IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'wx_Bill_SendBack'
                        AND a.Name = 'IsCombined' ) 
    BEGIN
        ALTER TABLE wx_Bill_SendBack ADD IsCombined   INT
    END
GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'wx_Bill_SendBack'
                        AND a.Name = 'GoodsNumber' ) 
    BEGIN
        ALTER TABLE wx_Bill_SendBack ADD GoodsNumber VARCHAR(100) NULL DEFAULT ('')
    END
GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'wx_Bill_SendBack'
                        AND a.Name = 'CargoID' ) 
    BEGIN
        ALTER TABLE wx_Bill_SendBack ADD CargoID INT NULL DEFAULT(0)
    END
GO

IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'wx_Bill_SendBack'
                        AND a.Name = 'NQty' ) 
    BEGIN
        ALTER TABLE wx_Bill_SendBack ADD NQty   NUMERIC(22,10)     NULL  DEFAULT(0)
    END
IF NOT EXISTS ( SELECT  a.Name
                FROM    syscolumns a
                        INNER JOIN sysobjects b ON a.ID = b.ID
                WHERE   b.Name = 'wx_Bill_SendBack'
                        AND a.Name = 'UnitRate' ) 
    BEGIN
        ALTER TABLE wx_Bill_SendBack ADD UnitRate   NUMERIC(22,10)   NULL  DEFAULT(1)
    END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_SendBack' AND a.Name='Serial' and a.xtype=35
)
BEGIN
	DECLARE @dfname VARCHAR(1000)
	SELECT @dfname=name FROM sys.default_constraints WHERE object_id IN(SELECT default_object_id FROM sys.columns WHERE object_id=object_id('wx_Bill_SendBack') AND name='Serial')
	IF @dfname IS NOT NULL
		EXEC ('alter table wx_Bill_SendBack drop constraint '+@dfname);
		
	ALTER TABLE wx_Bill_SendBack ALTER COLUMN Serial VARCHAR(MAX) NULL 
	ALTER TABLE wx_Bill_SendBack ADD CONSTRAINT DF_wx_Bill_SendBack_Serial DEFAULT('') FOR Serial
END
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_SendBack',N'U') AND LOWER(Name)='completetotal')
BEGIN
	ALTER TABLE wx_Bill_SendBack ADD CompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE wx_Bill_SendBack SET CompleteTotal=0 WHERE CompleteTotal IS NULL
GO

IF NOT EXISTS (SELECT Name FROM SysColumns WHERE ID=OBJECT_ID(N'wx_Bill_SendBack',N'U') AND LOWER(Name)='ncompletetotal')
BEGIN
	ALTER TABLE wx_Bill_SendBack ADD NCompleteTotal NUMERIC(22,10) DEFAULT(0)
END
GO

UPDATE wx_Bill_SendBack SET NCompleteTotal=0 WHERE NCompleteTotal IS NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_SENDBACK') AND name = 'CIX_WX_BILL_SENDBACK_BillNumberID')
--DROP INDEX CIX_WX_BILL_SENDBACK_BillNumberID ON WX_BILL_SENDBACK 
CREATE CLUSTERED INDEX CIX_WX_BILL_SENDBACK_BillNumberID ON WX_BILL_SENDBACK(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_BILL_SENDBACK') AND name = 'NCIX_WX_BILL_SENDBACK_Ptypeid')
--DROP INDEX NCIX_WX_BILL_SENDBACK_Ptypeid ON WX_BILL_SENDBACK 
CREATE NONCLUSTERED INDEX NCIX_WX_BILL_SENDBACK_Ptypeid ON WX_BILL_SENDBACK(Ptypeid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_SendBack' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_SendBack 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_SendBack' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_SendBack 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_SendBack' AND a.Name='CompleteQTY' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_SendBack 
	ALTER COLUMN CompleteQTY NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_SendBack' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_SendBack 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_SendBack' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_SendBack 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_SendBack' AND a.Name='CompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_SendBack 
	ALTER COLUMN CompleteTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_Bill_SendBack' AND a.Name='NCompleteTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_Bill_SendBack 
	ALTER COLUMN NCompleteTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_ErrDescription]    脚本日期: 05/05/2010 14:50:03 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_ErrDescription]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_ErrDescription](
		[ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
		[ErrCode] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_ErrDescription_ErrCode]  DEFAULT (''),
		[ErrName] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_ErrDescription_ErrName]  DEFAULT (''),
		[ErrPyCode] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_ErrDescription_ErrPyCode]  DEFAULT (''),
		[ErrDes] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_ErrDescription_ErrDes]  DEFAULT (''),
		[ErrDeal] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_ErrDescription_ErrDeal]  DEFAULT (''),
		[ErrComment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_ErrDescription_ErrComment]  DEFAULT (''),
		[Total] [numeric](18, 2) NULL CONSTRAINT [DF_wx_ErrDescription_Total]  DEFAULT (0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_ErrDescription' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_ErrDescription 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_GoodsStocks]    脚本日期: 05/05/2010 14:50:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_GoodsStocks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_GoodsStocks](
		[PTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[KTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[OutFactoryDate] [datetime] NULL DEFAULT (getdate()),
		[Qty] [numeric](18, 4) NULL DEFAULT (0),
		[Price] [numeric](18, 4) NULL DEFAULT (0),
		[Total] [numeric](18, 4) NULL DEFAULT (0),
		[GoodsOrder] [int] NULL DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID  INT  DEFAULT(0),
		Iscombined BIT DEFAULT(0),
		Nqty NUMERIC(22,10) DEFAULT(0),
		CargoID INT DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_GoodsStocks' AND a.Name='CargoID'
)
BEGIN
	ALTER TABLE wx_GoodsStocks ADD CargoID INT DEFAULT(0)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_GoodsStocks' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE wx_GoodsStocks ADD ItemID INT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_GoodsStocks' AND a.Name='Iscombined'
)
BEGIN
	ALTER TABLE wx_GoodsStocks ADD Iscombined	BIT DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_GoodsStocks' AND a.Name='Nqty'
)
BEGIN
	ALTER TABLE wx_GoodsStocks ADD Nqty	 NUMERIC(22,10) DEFAULT(0)
END

GO



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_GOODSSTOCKS') AND name = 'CIX_WX_GOODSSTOCKS_Ptypeid')
--DROP INDEX CIX_WX_GOODSSTOCKS_Ptypeid ON WX_GOODSSTOCKS 
CREATE CLUSTERED INDEX CIX_WX_GOODSSTOCKS_Ptypeid ON WX_GOODSSTOCKS(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_GOODSSTOCKS') AND name = 'NCIX_WX_GOODSSTOCKS_Ktypeid')
--DROP INDEX NCIX_WX_GOODSSTOCKS_Ktypeid ON WX_GOODSSTOCKS 
CREATE NONCLUSTERED INDEX NCIX_WX_GOODSSTOCKS_Ktypeid ON WX_GOODSSTOCKS(Ktypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_GoodsStocks' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_GoodsStocks 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_GoodsStocks' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_GoodsStocks 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_GoodsStocks' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_GoodsStocks 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_GoodsStocks' AND a.Name='Nqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_GoodsStocks 
	ALTER COLUMN Nqty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_IniGoodsStocks]    脚本日期: 05/05/2010 14:50:05 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_IniGoodsStocks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_IniGoodsStocks](
		[PTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[KTypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[JobNumber] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[OutFactoryDate] [datetime] NULL DEFAULT (getdate()),
		[Qty] [numeric](18, 4) NULL DEFAULT (0),
		[Price] [numeric](18, 4) NULL DEFAULT (0),
		[Total] [numeric](18, 4) NULL DEFAULT (0),
		[GoodsOrder] [int] NULL DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL DEFAULT (''),
		ItemID  INT  DEFAULT(0),
		Iscombined BIT DEFAULT(0),
		Nqty NUMERIC(22,10) DEFAULT(0)
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_IniGoodsStocks' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE wx_IniGoodsStocks ADD ItemID INT DEFAULT(0)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_IniGoodsStocks' AND a.Name='Iscombined'
)
BEGIN
	ALTER TABLE wx_IniGoodsStocks ADD Iscombined	BIT DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_IniGoodsStocks' AND a.Name='Nqty'
)
BEGIN
	ALTER TABLE wx_IniGoodsStocks ADD Nqty	 NUMERIC(22,10) DEFAULT(0)
END

GO


-- 清除多添加字段 目前这个只支持一个约束的情况 够用了 --
DECLARE @t TABLE(name VARCHAR(100)); 
INSERT INTO @t 
SELECT 'CargoID'
;
DECLARE @sql NVARCHAR(max)='';
DECLARE @tn NVARCHAR(500)='wx_IniGoodsStocks';

SELECT @sql=@sql+ CASE WHEN a.name IS NULL THEN '' ELSE ' alter table '+@tn+' drop constraint '+a.name+';' END
	+ ' alter table '+@tn+' drop column '+d.name+';'
FROM sys.default_constraints a 
	RIGHT JOIN sys.all_columns b ON a.parent_object_id=b.object_id and a.parent_column_id=b.column_id
	JOIN @t d ON b.name=d.name
	WHERE b.object_id=object_id(@tn,'U')

IF @sql<>''
	EXEC(@sql);
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_INIGOODSSTOCKS') AND name = 'CIX_WX_INIGOODSSTOCKS_Ktypeid')
--DROP INDEX CIX_WX_INIGOODSSTOCKS_Ktypeid ON WX_INIGOODSSTOCKS 
CREATE CLUSTERED INDEX CIX_WX_INIGOODSSTOCKS_Ktypeid ON WX_INIGOODSSTOCKS(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_INIGOODSSTOCKS') AND name = 'NCIX_WX_INIGOODSSTOCKS_Ptypeid')
--DROP INDEX NCIX_WX_INIGOODSSTOCKS_Ptypeid ON WX_INIGOODSSTOCKS 
CREATE NONCLUSTERED INDEX NCIX_WX_INIGOODSSTOCKS_Ptypeid ON WX_INIGOODSSTOCKS(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_IniGoodsStocks' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_IniGoodsStocks 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_IniGoodsStocks' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_IniGoodsStocks 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_IniGoodsStocks' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_IniGoodsStocks 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_IniGoodsStocks' AND a.Name='Nqty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_IniGoodsStocks 
	ALTER COLUMN Nqty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_IniOutRepair]    脚本日期: 05/05/2010 14:50:06 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_IniOutRepair]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_IniOutRepair](
		[PtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Qty] [numeric](18, 0) NOT NULL CONSTRAINT [DF_wx_IniOutRepair_Qty]  DEFAULT (0),
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_IniOutRepair_Comment]  DEFAULT ('')
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_InOutStockTable]    脚本日期: 05/05/2010 14:50:07 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_InOutStockTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_InOutStockTable](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillDate] [datetime] NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[AtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_AtypeId]  DEFAULT (0),
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_PtypeId]  DEFAULT (0),
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_BtypeId]  DEFAULT (0),
		[EtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_EtypeId]  DEFAULT (0),
		[KtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_KtypeId]  DEFAULT (0),
		[Qty] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_Qty]  DEFAULT (0),
		[Price] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_Price]  DEFAULT (0),
		[Total] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_Total]  DEFAULT (0),
		[CostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_CostPrice]  DEFAULT (0),
		[CostTotal] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_CostTotal]  DEFAULT (0),
		[JobNumber] [char](20) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_JobNumber]  DEFAULT (0),
		[GoodsNo] [int] NULL CONSTRAINT [DF_wx_InOutStockTable_GoodsNo]  DEFAULT (0),
		[OutFactoryDate] [datetime] NULL,
		[Audited] [bit] NOT NULL CONSTRAINT [DF_wx_InOutStockTable_Audited]  DEFAULT (0),
		[GoodsNumber] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_GoodsNumber]  DEFAULT (''),
		[ProduceDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_ProduceDate]  DEFAULT (''),
		[ValidDate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_ValidDate]  DEFAULT (''),
		[GoodsBTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutStockTable_GoodsBTypeID]  DEFAULT (''),
		[GoodsCostPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_GoodsCostPrice]  DEFAULT (0),
		[HandZeroCost] [int] NULL CONSTRAINT [DF_wx_InOutStockTable_HandZeroCost_1]  DEFAULT (0),
		[ID] [int] NULL CONSTRAINT [DF_wx_InOutStockTable_ID]  DEFAULT ((-1)),
		[Tax] [numeric](5, 2) NULL CONSTRAINT [DF_wx_InOutStockTable_tax]  DEFAULT (0),
		[Discount] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_discount]  DEFAULT (1),
		[SalePrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_saleprice]  DEFAULT (0),
		[SaleTotal] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_saletotal]  DEFAULT (0),
		[TaxPrice] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_taxprice]  DEFAULT (0),
		[TaxTotal] [numeric](18, 4) NULL CONSTRAINT [DF_wx_InOutStockTable_taxtotal]  DEFAULT (0),
		[DTypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutstocktable_DTypeID]  DEFAULT (''),
		[STypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_wx_InOutstocktable_STypeID]  DEFAULT (''),
		[CargoID] [int] NULL CONSTRAINT [DF_wx_InOutstocktable_CargoID]  DEFAULT (0),
		[NPrice] [numeric](18, 4) NULL DEFAULT (0),
		[NTotal] [numeric](18, 4) NULL DEFAULT (0),
		[NSalePrice] [numeric](18, 4) NULL DEFAULT (0),
		[NSaleTotal] [numeric](18, 4) NULL DEFAULT (0),
		[NTaxPrice] [numeric](18, 4) NULL DEFAULT (0),
		[NTaxTotal] [numeric](18, 4) NULL DEFAULT (0),
		[ItemID] [INT] NOT NULL DEFAULT(0),
		[IsCombined] [Bit] NOT NULL DEFAULT(0),
		[NQty]   [numeric](22,10)     NULL Default(0),
		[UnitRate]  [numeric](22,10)     NULL Default(0),
		[MUNITID] [int] NULL DEFAULT(0),
		[SortID] BIGINT IDENTITY(1,1) PRIMARY KEY,
		[IsService] INT NOT NULL DEFAULT(0), -- 0 普通商品 1 服务商品
		[MUnitRate] NUMERIC(24,10) NULL
	) ON [PRIMARY]


END
GO



------------------------------------------表修改区域开始-------------------------------------------------





IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='DTypeID'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD DTypeID VARCHAR(50) NULL CONSTRAINT [DF_wx_InOutstocktable_DTypeID]  DEFAULT ('')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='STypeID'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD STypeID VARCHAR(50) NULL CONSTRAINT [DF_wx_InOutstocktable_STypeID]  DEFAULT ('')
	DECLARE @strSql VARCHAR(8000)
	
	SELECT @strSql='
	UPDATE wx_InOutStockTable SET STypeID='+CHAR(39)+'00001'+CHAR(39)+'
	WHERE STypeID='+CHAR(39)+CHAR(39)+' OR STypeID IS NULL '
	
	EXEC(@strSql)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='CargoID'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD CargoID INT NULL CONSTRAINT [DF_wx_InOutStockTable_CargoID]  DEFAULT (0)
	
	EXEC('UPDATE wx_InOutStockTable SET CargoID=0 WHERE CargoID IS NULL')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NPrice'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD NPrice  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE wx_InOutStockTable SET NPrice=Price WHERE NPrice IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTOTAL'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD NTOTAL  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE wx_InOutStockTable SET NTOTAL=TOTAL WHERE NTOTAL IS NULL')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NSALEPRICE'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD NSALEPRICE  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE wx_InOutStockTable SET NSALEPRICE=SALEPRICE WHERE NSALEPRICE IS NULL')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NSALETOTAL'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD NSALETOTAL  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE wx_InOutStockTable SET NSALETOTAL=SALETOTAL WHERE NSALETOTAL IS NULL')
END

GO



IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTAXPRICE'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD NTAXPRICE  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE wx_InOutStockTable SET NTAXPRICE=TAXPRICE WHERE NTAXPRICE IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTAXTOTAL'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD NTAXTOTAL  [numeric](18, 4) NULL DEFAULT (0)
	
	EXEC('UPDATE wx_InOutStockTable SET NTAXTOTAL=TAXTOTAL WHERE NTAXTOTAL IS NULL')
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='ItemID'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD ItemID int NOT NULL DEFAULT(0)
END
ELSE
BEGIN
	DECLARE @sql NVARCHAR(max)='';
	IF EXISTS(
		SELECT * FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('wx_InOutStockTable') AND b.name='ItemID'
	)
	begin
		select @sql=' alter table wx_InOutStockTable drop constraint ['+a.name+'] ' FROM sys.default_constraints a JOIN sys.columns b ON a.parent_object_id=b.object_id AND a.parent_column_id=b.column_id  where a.parent_object_id=object_id('wx_InOutStockTable') AND b.name='ItemID'
		EXEC(@sql);
	END
	ALTER TABLE wx_InOutStockTable ALTER COLUMN ItemID INT NOT NULL;
	ALTER TABLE wx_InOutStockTable add CONSTRAINT DF_wx_InOutStockTable_ItemId DEFAULT(0) FOR ItemID
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='IsCombined'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD IsCombined BIT NOT NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NQty'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD NQty NUMERIC(22,10)  DEFAULT(0)
	
	
END

GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='UnitRate'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD UnitRate NUMERIC(22,10)  DEFAULT(0)
	
	EXEC('UPDATE wx_InOutStockTable SET NQty=Qty,UnitRate=1 WHERE NQty=0')
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='MUNITID'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD MUNITID INT  DEFAULT(0)
	
END

GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='SortID'
)
BEGIN
	ALTER TABLE wx_InOutStockTable ADD SortID [BIGINT] IDENTITY(1,1) PRIMARY KEY
	
END
go

IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'wx_InOutStockTable') AND name = 'IsService')
BEGIN
	ALTER TABLE wx_InOutStockTable ADD [IsService] INT NOT NULL DEFAULT(0) -- 0 普通商品 1 服务商品
END

IF NOT EXISTS(SELECT name FROM syscolumns WHERE id = object_id(N'wx_InOutStockTable') AND name = 'Comment')
BEGIN
	ALTER TABLE wx_InOutStockTable ADD [Comment] VARCHAR(255) DEFAULT ''  
	EXEC('UPDATE wx_InOutStockTable SET Comment='''' WHERE Comment is null')
END
GO

IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'wx_InOutStockTable',N'U') AND Name='MUnitRate')
BEGIN
	ALTER TABLE wx_InOutStockTable
	ADD MUnitRate NUMERIC(24,10) NULL
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_INOUTSTOCKTABLE') AND name = 'CIX_WX_INOUTSTOCKTABLE_BillDate')
--DROP INDEX CIX_WX_INOUTSTOCKTABLE_BillDate ON WX_INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX CIX_WX_INOUTSTOCKTABLE_BillDate ON WX_INOUTSTOCKTABLE(BillDate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_INOUTSTOCKTABLE') AND name = 'NCIX_WX_INOUTSTOCKTABLE_BillNumberID')
--DROP INDEX NCIX_WX_INOUTSTOCKTABLE_BillNumberID ON WX_INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_WX_INOUTSTOCKTABLE_BillNumberID ON WX_INOUTSTOCKTABLE(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_INOUTSTOCKTABLE') AND name = 'NCIX_WX_INOUTSTOCKTABLE_Ktypeid')
--DROP INDEX NCIX_WX_INOUTSTOCKTABLE_Ktypeid ON WX_INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_WX_INOUTSTOCKTABLE_Ktypeid ON WX_INOUTSTOCKTABLE(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WX_INOUTSTOCKTABLE') AND name = 'NCIX_WX_INOUTSTOCKTABLE_Ptypeid')
--DROP INDEX NCIX_WX_INOUTSTOCKTABLE_Ptypeid ON WX_INOUTSTOCKTABLE 
CREATE NONCLUSTERED INDEX NCIX_WX_INOUTSTOCKTABLE_Ptypeid ON WX_INOUTSTOCKTABLE(Ptypeid) 

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='CostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN CostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='CostTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN CostTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='GoodsCostPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN GoodsCostPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='Tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN Tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='TaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN TaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='TaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN TaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NSalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NSaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NSaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTaxPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NTaxPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTaxTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NTaxTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='UnitRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN UnitRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NTOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NSALEPRICE' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NSALEPRICE NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NSALETOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NSALETOTAL NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTAXPRICE' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NTAXPRICE NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='wx_InOutStockTable' AND a.Name='NTAXTOTAL' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE wx_InOutStockTable 
	ALTER COLUMN NTAXTOTAL NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[wx_StockTotalConfig]    脚本日期: 05/05/2010 14:50:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[wx_StockTotalConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[wx_StockTotalConfig](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeId] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[BillTypes] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[ShowBdPType] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[ShowSum] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'WxBillIndexNumSerial') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	DROP TABLE WxBillIndexNumSerial;
END

GO

---- 维修单表头数量，序列号
--IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'WxBillIndexNumSerial') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
--BEGIN
--	CREATE TABLE WxBillIndexNumSerial(
--		Id INT IDENTITY(1,1)
--		,BillNumberId INT
--		,PtypeId VARCHAR(50)
--		,KtypeId VARCHAR(50)
--		,StypeId VARCHAR(50)
--		,Qty INT NOT NULL DEFAULT(0)
--		,Serial VARCHAR(max)
--	)
--END
--GO

--IF EXISTS(SELECT * FROM sys.columns WHERE object_id=object_id('WxBillIndexNumSerial') AND name='Num')
--BEGIN
--	EXEC sp_rename 'WxBillIndexNumSerial.Num','Qty','column'
--END
--go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

if NOT EXISTS (select 1 from  sysobjects where  id = object_id('xw_SelfData') and   type = 'U')
BEGIN
	/*==============================================================*/
	/* Table:自定义数据                        */
	/*==============================================================*/
	CREATE TABLE [xw_SelfData](
	  --_Id              INT IDENTITY primary key,
	  _Id				INT primary key,
	  DataTypeId       INT NOT NULL,               -- 自定义类型ID，对应 xw_SelfDataType._Id
	  TypeId           VARCHAR(50),
	  ParTypeId        VARCHAR(50),
	  [level]          INT NOT NULL DEFAULT 0,
	  SonNum           INT NOT NULL DEFAULT 0,
	  SonCount         INT NOT NULL DEFAULT 0,
	  FullName         VARCHAR(500),
	  UserCode         VARCHAR(500),
	  PyCode           VARCHAR(500),
	  Field1           VARCHAR(500),
	  Field2           VARCHAR(500),
	  Field3           VARCHAR(500),
	  Field4           VARCHAR(500),
	  Deleted          BIT NOT NULL DEFAULT 0,      -- 删除标记，删除时只是填为1
	 XiWaMaxNumber		numeric(18, 0) NULL DEFAULT(0),                   -- XiWa更新版本标志
	 PosDataVersion timestamp
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[xw_SelfData]') and name = 'XiWaMaxNumber' )
	BEGIN
		ALTER TABLE dbo.xw_SelfData ADD
			XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
	END
ELSE 
	BEGIN
	
		----判断xw_SelfData的XiWaMaxNumber的类型如果为int，则修改成numeric(18, 0) 
		IF  EXISTS(
					select 1  from syscolumns c 
					inner join systypes t 
					on c.xusertype=t.xusertype 
					where objectproperty(id,'IsUserTable')=1 and id=object_id('xw_SelfData') AND   c.name='XiWaMaxNumber' AND   t.name='int'
					)
		BEGIN
				ALTER TABLE xw_SelfData ALTER COLUMN XiWaMaxNumber numeric(18, 0) 
		END
		
	-----------------判断xw_SelfData的XiWaMaxNumber是否存在默认值
		IF NOT EXISTS(	
						SELECT  1 
						FROM dbo.sysobjects SO INNER JOIN dbo.syscolumns SC ON SO.id = SC.id 
						LEFT JOIN dbo.syscomments SM ON SC.cdefault = SM.id 
						WHERE SO.xtype = 'U' 
						AND SM.text IS NOT NULL
						AND SO.name='xw_SelfData'
						AND sc.Name='XiWaMaxNumber'
						And  SM.text='((0))'
					)	
		BEGIN
			ALTER   TABLE   xw_SelfData   ADD  DEFAULT(0)  for  XiWaMaxNumber  WITH   VALUES
		END
	END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[xw_SelfData]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.xw_SelfData ADD  PosDataVersion timestamp
END
GO

UPDATE xw_SelfData SET XiWaMaxNumber = 0 WHERE XiWaMaxNumber IS NULL
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

if NOT EXISTS (select 1 from  sysobjects where  id = object_id('xw_SelfDataType') and   type = 'U')
BEGIN
	/*==============================================================*/
	/* Table:自定义数据类型                                 */
	/*==============================================================*/
	CREATE TABLE [dbo].[xw_SelfDataType](
		  _Id              INT IDENTITY primary key,
		  Name             VARCHAR(100),
		  Deleted          BIT NOT NULL DEFAULT 0,      -- 删除标记，删除时只是填为1
		  PosDataVersion timestamp
		)

END
GO

------------------------------------------表修改区域开始-------------------------------------------------

if not exists (select name from syscolumns where id = object_id(N'[dbo].[xw_SelfDataType]') and name = 'XiWaMaxNumber' )
BEGIN
	ALTER TABLE dbo.xw_SelfDataType ADD
		XiWaMaxNumber numeric(18, 0) NULL DEFAULT(0)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[xw_SelfDataType]') and name = 'PosDataVersion' )
BEGIN
	ALTER TABLE dbo.xw_SelfDataType ADD  PosDataVersion timestamp
END
GO
UPDATE xw_SelfDataType SET XiWaMaxNumber = 0 WHERE XiWaMaxNumber IS NULL
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT 1 FROM  sysobjects WHERE   id = object_id('Yapi_BillSeedID') AND type = 'U')
BEGIN
	CREATE TABLE Yapi_BillSeedID (
	   ID INT IDENTITY(1,1) NOT NULL,
	   billtype TINYINT NOT NULL,
	   SeedID NUMERIC(20,0) NULL DEFAULT(0)
	)
END

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





/****** 对象:  Table [dbo].Yapi_btypeBindMerchant   脚本日期: 15/11/2013 10:46:50 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].Yapi_btypeBindMerchant') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].Yapi_btypeBindMerchant(
		[btypeid] [varchar](50)   NULL,
		[MerchantName] [varchar](200)   NULL,
		[priceLevel] INT DEFAULT(1)  NULL,
		[MerchantId] NUMERIC(20,0)   NULL,
		[IsSeller] BIT DEFAULT(0)  NULL 
	) ON [PRIMARY]

END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT 1 FROM  sysobjects WHERE   id = object_id('Yapi_NewSaleData') AND type = 'U')
BEGIN
	CREATE TABLE Yapi_NewSaleData (
	   billdate VARCHAR(20) NULL,
	   onlineid NUMERIC(20,0) NULL,
	   price NUMERIC(22,10) NULL DEFAULT(0),
	   qty NUMERIC(22,10) NULL DEFAULT(0),
	   total NUMERIC(22,10) NULL DEFAULT(0)
	)
END

GO

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Yapi_NewSaleData') AND name = 'NCIX_YAPINEWSALEDATA_Billdate')
--DROP INDEX NCIX_YAPINEWSALEDATA_Billdate ON Yapi_NewSaleData 
CREATE NONCLUSTERED INDEX NCIX_YAPINEWSALEDATA_Billdate ON Yapi_NewSaleData(billdate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Yapi_NewSaleData') AND name = 'NCIX_YAPINEWSALEDATA_OnLineID')
--DROP INDEX NCIX_YAPINEWSALEDATA_OnLineID ON Yapi_NewSaleData 
CREATE NONCLUSTERED INDEX NCIX_YAPINEWSALEDATA_OnLineID ON Yapi_NewSaleData(onlineid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_NewSaleData' AND a.Name='price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_NewSaleData 
	ALTER COLUMN price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_NewSaleData' AND a.Name='qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_NewSaleData 
	ALTER COLUMN qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_NewSaleData' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_NewSaleData 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*==============================================================*/
/* Table: Yapi_PtypeRelation                                              */
/*==============================================================*/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Yapi_OrderBill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].Yapi_OrderBill 
	(
	   id		NUMERIC(20,0) NULL DEFAULT(0),
	   Orderid	NUMERIC(20,0) NULL DEFAULT(0),
	   goodsid	NUMERIC(20,0) NULL,
	   Qty		NUMERIC(22,10) NULL DEFAULT(0),
	   Price	NUMERIC(22,10) NULL DEFAULT(0),
	   Total	NUMERIC(22,10) NULL DEFAULT(0),
	   Comment	VARCHAR(256) NULL,
	   Unitid	INT DEFAULT(0)
	)ON [PRIMARY]
END

GO

-----------------修改表区域开始------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Yapi_OrderBill]') and name = 'Orderid' )
BEGIN	
	ALTER TABLE dbo.Yapi_OrderBill ADD Orderid NUMERIC(18,0) NULL
END

-----------------修改表区域结束------------------
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Yapi_OrderBill') AND name = 'CIX_YAPIORDERBILL_Orderid')
--DROP INDEX CIX_YAPIORDERBILL_Orderid ON Yapi_OrderBill 
CREATE CLUSTERED INDEX CIX_YAPIORDERBILL_Orderid ON Yapi_OrderBill(Orderid) 
GO
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_OrderBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_OrderBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_OrderBill' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_OrderBill 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_OrderBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_OrderBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*==============================================================*/
/* Table: Yapi_PtypeRelation                                              */
/*==============================================================*/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Yapi_OrderBillIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].Yapi_OrderBillIndex 
	(
	   orderid		NUMERIC(20,0) NULL DEFAULT(0),
	   billcode		VARCHAR(100) NULL,
	   billdate		VARCHAR(20) NULL,
	   STATUS		INT NULL DEFAULT(1),
	   TotalMoney	NUMERIC(22,10) DEFAULT(0),
	   TotalQty 	NUMERIC(22,10) DEFAULT(0),
	   Comment		VARCHAR(256) NULL,
	   explain		VARCHAR(256) NULL,
	   BuyerComment	VARCHAR(256) NULL,
	   SupplierComment VARCHAR(256) NULL,
	   buyerid		NUMERIC(20,0) DEFAULT(0),
	   supplierid	NUMERIC(20,0) DEFAULT(0),
	   billtype		TINYINT DEFAULT(0) NULL 
	)ON [PRIMARY]
END

GO

-----------------修改表区域开始------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Yapi_OrderBillIndex]') and name = 'explain' )
BEGIN	
	ALTER TABLE dbo.Yapi_OrderBillIndex ADD explain VARCHAR(256) NULL		
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[Yapi_OrderBillIndex]') and name = 'sid' )
BEGIN	
	ALTER TABLE dbo.Yapi_OrderBillIndex ADD SID INT NULL DEFAULT(0)	
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[Yapi_OrderBillIndex]') and name = 'TotalQty' )
BEGIN	
	ALTER TABLE dbo.Yapi_OrderBillIndex ADD TotalQty 	NUMERIC(22,10) DEFAULT(0)
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[Yapi_OrderBillIndex]') and name = 'stypeid' )
BEGIN	
	ALTER TABLE dbo.Yapi_OrderBillIndex 
		ADD stypeid VARCHAR(50) NULL DEFAULT('')		
END

if not exists (select name from syscolumns where id = object_id(N'[dbo].[Yapi_OrderBillIndex]') and name = 'ktypeid' )
BEGIN	
	ALTER TABLE dbo.Yapi_OrderBillIndex 
		ADD ktypeid VARCHAR(50) NULL DEFAULT('')	
END  

-----------------修改表区域结束------------------
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Yapi_OrderBillIndex') AND name = 'CIX_YAPIORDERBILLINDEX_Orderid')
--DROP INDEX CIX_YAPIORDERBILLINDEX_Orderid ON Yapi_OrderBillIndex 
CREATE CLUSTERED INDEX CIX_YAPIORDERBILLINDEX_Orderid ON Yapi_OrderBillIndex(Orderid) 
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Yapi_OrderBillIndex') AND name = 'NCIX_YAPIORDERBILLINDEX_Billdate')
--DROP INDEX NCIX_YAPIORDERBILLINDEX_Billdate ON Yapi_OrderBillIndex 
CREATE NONCLUSTERED INDEX NCIX_YAPIORDERBILLINDEX_Billdate ON Yapi_OrderBillIndex(billdate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Yapi_OrderBillIndex') AND name = 'NCIX_YAPIORDERBILLINDEX_STATUS')
--DROP INDEX NCIX_YAPIORDERBILLINDEX_STATUS ON Yapi_OrderBillIndex 
CREATE NONCLUSTERED INDEX NCIX_YAPIORDERBILLINDEX_STATUS ON Yapi_OrderBillIndex(STATUS) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_OrderBillIndex' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_OrderBillIndex 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_OrderBillIndex' AND a.Name='TotalQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
		ALTER TABLE Yapi_OrderBillIndex 
		ALTER COLUMN TotalQty NUMERIC(24,10)
    END

UPDATE Yapi_OrderBillIndex SET stypeid = '' WHERE stypeid IS NULL

UPDATE Yapi_OrderBillIndex SET ktypeid = '' WHERE ktypeid IS NULL
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*==============================================================*/
/* Table: Yapi_PtypeRelation                                              */
/*==============================================================*/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Yapi_PtypeRelation]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].Yapi_PtypeRelation 
	(
	   ID           int             identity(1,1),
	   Ptypeid		VARCHAR(50)		NULL,
	   OnLineID		NUMERIC(20,0)	NULL,
	   SkuId		NUMERIC(20,0)	NULL
	)ON [PRIMARY]
END

GO

-----------------修改表区域开始------------------
--if not exists (select name from syscolumns where id = object_id(N'[dbo].[Yapi_PtypeRelation]') and name = '' )
--BEGIN	
--	ALTER TABLE dbo.Yapi_PtypeRelation ADD
			
--END

-----------------修改表区域结束------------------
------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT 1 FROM  sysobjects WHERE   id = object_id('Yapi_QtyChangePtype') AND type = 'U')
BEGIN
	CREATE TABLE Yapi_QtyChangePtype (
	   ptypeid		varchar(50)			 null 
	)
END

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT 1 FROM  sysobjects WHERE   id = object_id('Yapi_SaleData') AND type = 'U')
BEGIN
	CREATE TABLE Yapi_SaleData (
	   billdate VARCHAR(20) NULL,
	   onlineid NUMERIC(20,0) NULL,
	   price NUMERIC(22,10) NULL DEFAULT(0),
	   qty NUMERIC(22,10) NULL DEFAULT(0),
	   total NUMERIC(22,10) NULL DEFAULT(0)
	)
END

GO

------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Yapi_SaleData') AND name = 'NCIX_YAPISALEDATA_Billdate')
--DROP INDEX NCIX_YAPISALEDATA_Billdate ON Yapi_SaleData 
CREATE NONCLUSTERED INDEX NCIX_YAPISALEDATA_Billdate ON Yapi_SaleData(billdate) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Yapi_SaleData') AND name = 'NCIX_YAPISALEDATA_OnLineID')
--DROP INDEX NCIX_YAPISALEDATA_OnLineID ON Yapi_SaleData 
CREATE NONCLUSTERED INDEX NCIX_YAPISALEDATA_OnLineID ON Yapi_SaleData(onlineid) 

------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_SaleData' AND a.Name='price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_SaleData 
	ALTER COLUMN price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_SaleData' AND a.Name='qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_SaleData 
	ALTER COLUMN qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Yapi_SaleData' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Yapi_SaleData 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*==============================================================*/
/* Table: Yapi_SupplierPtypeRelation                                              */
/*==============================================================*/
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Yapi_SupplierPtypeRelation]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].Yapi_SupplierPtypeRelation 
	(
	   ID           int             identity(1,1),
	   SupplierID	NUMERIC(20,0)	NULL,
	   OnLineID		NUMERIC(20,0)	NULL,
	   OnLineFullname	VARCHAR(200) NULL,
	   OnLineUserCode	VARCHAR(200) NULL,
	   Ptypeid		VARCHAR(50)		NULL,
	   SkuId		NUMERIC(20,0)	NULL
	)ON [PRIMARY]
END

GO

-----------------修改表区域开始------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Yapi_SupplierPtypeRelation]') and name = 'SkuId' )
BEGIN	
	ALTER TABLE dbo.Yapi_SupplierPtypeRelation ADD SkuId		NUMERIC(20,0)	NULL
			
END

-----------------修改表区域结束------------------
------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT 1 FROM  sysobjects WHERE   id = object_id('Yapi_SupplierPtypeSeedID') AND type = 'U')
BEGIN
	CREATE TABLE Yapi_SupplierPtypeSeedID (
	   ID INT IDENTITY(1,1) NOT NULL,
	   SupplierID NUMERIC(20,0) NULL DEFAULT(0),
	   SeedID NUMERIC(20,0) NULL DEFAULT(0)
	)
END

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ZLCY_luntan]    脚本日期: 05/05/2010 14:50:08 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ZLCY_luntan]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ZLCY_luntan](
		[num] [int] IDENTITY(1,1) NOT NULL,
		[title] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[texts] [text] COLLATE Chinese_PRC_CI_AS NULL,
		[dates] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[lastdates] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
		[author] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[reply] [int] NOT NULL CONSTRAINT [DF_ZLCY_luntan_reply]  DEFAULT (0),
		[new_number] [int] NULL,
		[re_number] [int] NULL,
		[img] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[clicknum] [int] NOT NULL CONSTRAINT [DF_ZLCY_luntan_clicknum]  DEFAULT (0),
		[htmlcode] [int] NULL,
		[image] [image] NULL,
		[imagelength] [int] NULL,
		[imagetype] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[haveimage] [int] NULL,
		[filename] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='ZLCY_luntan' AND a.Name='texts' and a.xtype=35
)
BEGIN
	ALTER TABLE ZLCY_luntan ALTER COLUMN texts VARCHAR(MAX)
END
GO

------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ZLCYUpFiles]    脚本日期: 05/05/2010 14:50:09 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ZLCYUpFiles]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ZLCYUpFiles](
		[BBSID] [varchar](25) COLLATE Chinese_PRC_CI_AS NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[FileName] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[Comment] [varchar](256) COLLATE Chinese_PRC_CI_AS NULL,
		[BinaryContent] [image] NULL,
		[ContentType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
		[ContentLength] [int] NULL,
		[szDate] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



GO
	--
	--			AppraisalBackBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_AppraisalBackBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_AppraisalBackBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL,
		[DiscountPrice] [numeric](24, 10) NULL,
		[costprice] [numeric](24, 10) NULL,
		[total] [numeric](24, 10) NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[Serial] [varchar](max) NULL,
		[OldID] [numeric](10, 0) NULL,
		[OldBillNumberID] [numeric](10, 0) NULL,
		[InputCostPrice] [numeric](24, 10) NULL,
		[GoodsOrder] [int] NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney] [numeric](24, 10) NULL,
		[NSalePrice] [numeric](24, 10) NULL,
		[NSaleTotal] [numeric](24, 10) NULL,
		[NDiscountPrice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](24, 10) NULL,
		[MDiscountPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMSalePrice] [numeric](24, 10) NULL,
		[CurMDiscountPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[InvoiceQty] [numeric](24, 10) NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[IsGift] [int] NULL,
		[PriceStyle] [int] NOT NULL,
		[InvoiceCostTotal] [numeric](24, 10) NULL,
		[InvoiceMoneyEX] [numeric](24, 10) NULL,
		[NInvoiceMoneyEX] [numeric](24, 10) NULL,
		[InvoiceNQty] [numeric](24, 10) NULL,
		[CostTotal] [numeric](24, 10) NULL,
		[InvoiceSaleMoney] [numeric](24, 10) NULL,
		[NInvoiceSaleMoney] [numeric](24, 10) NULL,
		[ShareFee] [numeric](24, 10) NULL,
		[ShowOrder] [int] NULL,
		[ID] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_AppraisalBackBill',N'U') AND name = 'NCIX_ModifyLog_AppraisalBackBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_AppraisalBackBill_BillNumberID ON ModifyLog_AppraisalBackBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
	--
	--			AppraisalBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_AppraisalBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_AppraisalBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL,
		[DiscountPrice] [numeric](24, 10) NULL,
		[total] [numeric](24, 10) NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo1] [int] NULL,
		[TeamNo] [int] NULL,
		[orderid] [int] NOT NULL,
		[Serial] [varchar](max) NULL,
		[InputCostPrice] [numeric](24, 10) NULL,
		[GoodsOrder] [int] NULL,
		[BackQty] [numeric](24, 10) NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney] [numeric](24, 10) NULL,
		[NSalePrice] [numeric](24, 10) NULL,
		[NSaleTotal] [numeric](24, 10) NULL,
		[NDiscountPrice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](24, 10) NULL,
		[MDiscountPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMSalePrice] [numeric](24, 10) NULL,
		[CurMDiscountPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[entryCode] [varchar](200) NULL,
		[InvoiceQty] [numeric](24, 10) NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[IsGift] [int] NULL,
		[InvoiceMoneyEX] [numeric](24, 10) NULL,
		[NInvoiceMoneyEX] [numeric](24, 10) NULL,
		[InvoiceCostTotal] [numeric](24, 10) NULL,
		[OldID] [numeric](10, 0) NULL,
		[OldBillNumberID] [numeric](10, 0) NULL,
		[InvoiceNQty] [numeric](24, 10) NULL,
		[InvoiceSaleMoney] [numeric](24, 10) NULL,
		[NInvoiceSaleMoney] [numeric](24, 10) NULL,
		[ShareFee] [numeric](24, 10) NULL,
		[ShowOrder] [int] NULL,
		[ID] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_AppraisalBill',N'U') AND name = 'NCIX_ModifyLog_AppraisalBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_AppraisalBill_BillNumberID ON ModifyLog_AppraisalBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
--
--			Billindex 全面修改单据历史记录
--
IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'ModifyLog_BillIndex',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_BillIndex]
	(
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[Comment] [varchar](2000) NULL,
		[atypeid] [varchar](50) NULL,
		[ptypeid] [varchar](50) NULL,
		[btypeid] [varchar](50) NULL,
		[etypeid] [varchar](50) NULL,
		[ktypeid] [varchar](50) NULL,
		[ktypeid2] [varchar](50) NULL,
		[ifcheck] [char](1) NULL,
		[checke] [varchar](50) NULL,
		[totalmoney] [numeric](24, 10) NULL,
		[totalinmoney] [numeric](24, 10) NULL,
		[totalqty] [numeric](24, 10) NULL,
		[tax] [numeric](24, 10) NULL,
		[period] [smallint] NULL,
		[explain] [varchar](2000) NULL,
		[RedWord] [int] NOT NULL,
		[draft] [bit] NOT NULL,
		[OrderId] [numeric](10, 0) NULL,
		[waybillcode] [varchar](50) NULL,
		[goodsnumber] [varchar](20) NULL,
		[packway] [varchar](20) NULL,
		[TEL] [varchar](100) NULL,
		[Uploaded] [bit] NOT NULL,
		[OFF_ID] [uniqueidentifier] NULL,
		[TeamNo] [int] NULL,
		[AlertDay] [int] NULL,
		[CompleteTotal] [numeric](24, 10) NULL,
		[ID] [numeric](10, 0) NOT NULL,
		[Assessor] [varchar](50) NULL,
		[IfAudit] [char](1) NULL,
		[Audit_explain] [varchar](256) NULL,
		[IfStopMoney] [char](1) NULL,
		[preferencemoney] [numeric](24, 10) NULL,
		[DTypeId] [varchar](50) NULL,
		[JF] [int] NULL,
		[VipCardID] [int] NULL,
		[vipCZMoney] [numeric](24, 10) NULL,
		[jsStyle] [char](1) NULL,
		[jsState] [char](1) NULL,
		[KTypeID3] [varchar](50) NULL,
		[LinkMan] [varchar](256) NULL,
		[LinkTel] [varchar](256) NULL,
		[LinkAddr] [varchar](256) NULL,
		[wxManID] [varchar](50) NULL,
		[JieJianBillNumberID] [int] NULL,
		[JieJianID] [int] NULL,
		[JieJianState] [int] NULL,
		[BaoXiuBillNumberID] [int] NULL,
		[BaoXiuID] [int] NULL,
		[BuyDate] [varchar](50) NULL,
		[Serial] [varchar](200) NULL,
		[wxTotal] [numeric](24, 10) NULL,
		[ErrDes] [varchar](3000) NULL,
		[ifHideJieJian] [int] NULL,
		[ifWX] [int] NULL,
		[ifYearBill] [int] NULL,
		[Poster] [varchar](50) NULL,
		[LastUpdateTime] [datetime] NULL,
		[Stypeid] [varchar](50) NULL,
		[FromBillNumberID] [numeric](10, 0) NULL,
		[CostSale] [bit] NULL,
		[OtherInOutType] [int] NULL,
		[PosBillType] [int] NULL,
		[checkTime] [datetime] NULL,
		[posttime] [datetime] NULL,
		[updateE] [varchar](50) NULL,
		[ShareMode] [tinyint] NULL,
		[TransportId] [varchar](10) NULL,
		[IsIni] [bit] NULL,
		[ATypeID1] [varchar](50) NULL,
		[NCompleteTotal] [numeric](24, 10) NULL,
		[ATID] [int] NULL,
		[IfCargo] [bit] NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[NARTotal] [numeric](24, 10) NULL,
		[NAPTotal] [numeric](24, 10) NULL,
		[NYSTotal] [numeric](24, 10) NULL,
		[NYFTotal] [numeric](24, 10) NULL,
		[RedReason] [varchar](500) NULL,
		[PrePriceNum] [int] NOT NULL,
		[AssetBusinessTypeId] [int] NULL,
		[PromoRuleId] [int] NOT NULL,
		[BeforePromoBillNumberId] [int] NOT NULL,
		[ImportType] [tinyint] NOT NULL,
		[NewPosBill] [tinyint] NULL,
		[PromotionMsg] [nvarchar](500) NOT NULL,
		[Reconciliation] [char](1) NULL,
		[ARTOTAL] [numeric](24, 10) NULL,
		[APTOTAL] [numeric](24, 10) NULL,
		[YSTOTAL] [numeric](24, 10) NULL,
		[YFTOTAL] [numeric](24, 10) NULL,
		[IsAuto] [int] NULL,
		[IsYapi] [bit] NULL,
		[YapiOrderID] [numeric](20, 0) NULL,
		[DeliveryAddress] [varchar](256) NOT NULL,
		[AddDTypeETypeType] [int] NOT NULL,
		[BillTime] [varchar](20) NULL,
		[CWCheck] [int] NOT NULL,
		[IfBargainOn] [int] NULL,
		[IfMulAccount] [int] NULL,
		[IsFreightMoney] [int] NULL,
		[FreightAddr] [varchar](300) NULL,
		[FreightPerson] [varchar](100) NULL,
		[FreightTel] [varchar](100) NULL,
		[IfInvoice] [int] NULL,
		[UF1] [varchar](200) NULL,
		[UF2] [varchar](200) NULL,
		[UF3] [varchar](200) NULL,
		[UF4] [varchar](200) NULL,
		[UF5] [varchar](200) NULL,
		[DealBTypeID] [varchar](50) NULL,
		[CID] [int] NULL,
		[Rate] [numeric](24, 10) NULL,
		[NTotalMoney] [numeric](24, 10) NULL,
		[NTotalInMoney] [numeric](24, 10) NULL,
		[NPreferenceMoney] [numeric](24, 10) NULL,
		[NVIPCZMoney] [numeric](24, 10) NULL,
		[billproperty] [int] NULL,
		[TallyId] [varchar](50) NULL,
		[StypeID2] [varchar](50) NULL,
		[IfConfirm] [int] NOT NULL,
		[TransferType] [int] NOT NULL,
		[FeeDeductType] [int] NOT NULL,
		[Discount] [numeric](24, 10) NULL,
		[AdPriceType] [tinyint] NOT NULL,
		[IsLend] [bit] NULL,
		[ChargeOffBtypeid] [varchar](50) NULL,
		[ChargeOffType] [int] NOT NULL,
		[ChargeOffTotal] [numeric](24, 10) NULL,
		[NChargeOffTotal] [numeric](24, 10) NULL,
		[BillNumberID] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO

---------------------------修改-------------------------------------------
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[ModifyLog_BillIndex]') and  name = 'Comment' and Length=256)
BEGIN
	 ALTER TABLE ModifyLog_BillIndex
	    ALTER COLUMN Comment VARCHAR(2000) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[ModifyLog_BillIndex]') and  name = 'Comment' and Length=256)
BEGIN
	 ALTER TABLE ModifyLog_BillIndex
	    ALTER COLUMN Explain VARCHAR(2000) NULL
END
GO
---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT  EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_BillIndex',N'U') AND Name = 'CIX_ModifyLog_BILLINDEX_BillDate')
CREATE CLUSTERED INDEX CIX_ModifyLog_BILLINDEX_BillDate ON ModifyLog_BillIndex(BillDate) 

IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_BillIndex',N'U') AND Name = 'NCIX_ModifyLog_BILLINDEX_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_BILLINDEX_BillNumberID ON ModifyLog_BillIndex(BillNumberID) 
---------------------------索引-------------------------------------------
GO




GO
	--
	--			BuyBackBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_BuyBackBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_BuyBackBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL,
		[DiscountPrice] [numeric](24, 10) NULL,
		[costprice] [numeric](24, 10) NULL,
		[jobnumber] [varchar](20) NULL,
		[goodsno] [int] NULL,
		[total] [numeric](24, 10) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[TeamNo1] [int] NULL,
		[ID] [int] NOT NULL,
		[IsUnit2] [int] NOT NULL,
		[Serial] [varchar](max) NULL,
		[OldID] [varchar](50) NULL,
		[OldBillNumberID] [numeric](18, 0) NULL,
		[InputCostPrice] [numeric](24, 10) NULL,
		[GoodsOrder] [int] NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsBTypeID] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[GoodsCostTotal] [numeric](24, 10) NULL,
		[HandZeroCost] [int] NULL,
		[CompleteQTY] [numeric](24, 10) NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney] [numeric](24, 10) NULL,
		[NSalePrice] [numeric](24, 10) NULL,
		[NSaleTotal] [numeric](24, 10) NULL,
		[NDiscountPrice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](24, 10) NULL,
		[MDiscountPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMSalePrice] [numeric](24, 10) NULL,
		[CurMDiscountPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[InvoiceQty] [numeric](24, 10) NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[IsGift] [int] NOT NULL,
		[PriceStyle] [int] NOT NULL,
		[CompleteTotal] [numeric](24, 10) NULL,
		[NCompleteTotal] [numeric](24, 10) NULL,
		[ShowOrder] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_BuyBackBill',N'U') AND Name = 'NCIX_ModifyLog_BuyBackBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_BuyBackBill_BillNumberID ON ModifyLog_BuyBackBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
	--
	--			BuyBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_BuyBill',N'U'))
BEGIN
	
CREATE TABLE [dbo].[ModifyLog_BuyBill]
(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL,
		[DiscountPrice] [numeric](24, 10) NULL,
		[jobnumber] [varchar](20) NULL,
		[total] [numeric](24, 10) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo1] [int] NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[orderid] [int] NOT NULL,
		[IsUnit2] [int] NOT NULL,
		[Serial] [varchar](max) NULL,
		[InputCostPrice] [numeric](24, 10) NULL,
		[GoodsOrder] [int] NULL,
		[BackQty] [numeric](24, 10) NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsBTypeID] [varchar](50) NULL,
		[CompleteQTY] [numeric](24, 10) NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[GoodsCostTotal] [numeric](24, 10) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[FromBillNumberID] [numeric](10, 0) NULL,
		[FromBillID] [numeric](10, 0) NULL,
		[ShareFee] [numeric](24, 10) NULL,
		[TaxMoney] [numeric](24, 10) NULL,
		[NSalePrice] [numeric](24, 10) NULL,
		[NSaleTotal] [numeric](24, 10) NULL,
		[NDiscountPrice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](24, 10) NULL,
		[MDiscountPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMSalePrice] [numeric](24, 10) NULL,
		[CurMDiscountPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[entryCode] [varchar](200) NULL,
		[InvoiceQty] [numeric](24, 10) NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[IsGift] [int] NOT NULL,
		[CompleteTotal] [numeric](24, 10) NULL,
		[NCompleteTotal] [numeric](24, 10) NULL,
		[LendBillNumberID] [numeric](10, 0) NULL,
		[LendBillID] [numeric](10, 0) NULL,
		[ShowOrder] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_BuyBill',N'U') AND Name = 'NCIX_ModifyLog_BuyBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_BuyBill_BillNumberID ON ModifyLog_BuyBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
	--
	--			CompleteGoodTotal	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_CompleteGoodTotal',N'U'))
BEGIN
	
CREATE TABLE [dbo].[ModifyLog_CompleteGoodTotal]
	(
		[ID] [int]  NOT NULL,
		[GoodsBillID] [int] NOT NULL,
		[MoneyBillID] [int] NOT NULL,
		[InOrOut] [char](1) NULL,
		[CompleteGoodQTY] [numeric](24, 10) NULL,
		[Draft] [tinyint] NULL,
		[Billdate] [datetime] NULL,
		[PtypeID] [varchar](50) NULL,
		[Billid] [int] NULL,
		[CompleteGoodTotal] [numeric](24, 10) NULL,
		[Price] [numeric](24, 10) NULL,
		[NCompleteGoodTotal] [numeric](24, 10) NULL,
		[IsSelect] [bit] NULL,
		[BillType] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]

END
GO

---------------------------修改-------------------------------------------
---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_CompleteGoodTotal',N'U') AND Name = 'CIX_ModifyLog_CompleteGoodTotal_ID')
CREATE CLUSTERED INDEX CIX_ModifyLog_CompleteGoodTotal_ID ON ModifyLog_CompleteGoodTotal(GoodsBillid,MoneyBillID) 

---------------------------索引-------------------------------------------
GO




GO
	--
	--			CompleteTotal	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_CompleteTotal',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_CompleteTotal]
	(
		[GoodsBillID] [int] NOT NULL,
		[MoneyBillID] [int] NOT NULL,
		[CompleteTotal] [numeric](24, 10) NULL,
		[ID] [int]  NOT NULL,
		[Draft] [tinyint] NULL,
		[Billdate] [datetime] NULL,
		[EtypeID] [varchar](50) NULL,
		[NCompleteTotal] [numeric](24, 10) NULL,
		[GoodsBillDetailID] [int] NULL,
		[IsSelect] [bit] NULL,
		[BillType] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]

END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_CompleteTotal',N'U') AND Name = 'CIX_ModifyLog_CompleteTotal_ID')
CREATE CLUSTERED INDEX CIX_ModifyLog_CompleteTotal_ID ON ModifyLog_CompleteTotal(GoodsBillid,MoneyBillid) 

---------------------------索引-------------------------------------------
GO




GO
	--
	--			GatheringBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_GatheringBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_GatheringBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) NULL,
		[total] [numeric](24, 10) NULL,
		[Comment] [varchar](256) NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) NULL,
		[ntotal] [numeric](24, 10) NULL,
		[VipCardID] [int] NULL,
		[ShowOrder] [int] NULL,
		[RelevanceBillId] [numeric](10, 0) NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO

---------------------------修改-------------------------------------------
---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_GatheringBill',N'U') AND Name = 'NCIX_ModifyLog_GatheringBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_GatheringBill_BillNumberID ON ModifyLog_GatheringBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
	--
	--			PayBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_PayBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_PayBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[AtypeId] [varchar](50) NULL,
		[total] [numeric](24, 10) NULL,
		[Comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) NULL,
		[ntotal] [numeric](24, 10) NULL,
		[VipCardID] [int] NULL,
		[ShowOrder] [int] NULL,
		[RelevanceBillId] [numeric](10, 0) NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]

END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_PayBill',N'U') AND Name = 'NCIX_ModifyLog_PayBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PayBill_BillNumberID ON ModifyLog_PayBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
	--
	--			PreBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_PreBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_PreBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[BillType] [int] NOT NULL,
		[Comment] [varchar](256) NULL,
		[AtypeId] [varchar](50) NULL,
		[total] [numeric](24, 10) NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[Stypeid] [varchar](50) NULL,
		[ntotal] [numeric](24, 10) NULL,
		[vipcardid] [int] NULL,
		[ShowOrder] [int] NULL,
		[RelevanceBillId] [numeric](10, 0) NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_PreBill',N'U') AND Name = 'NCIX_ModifyLog_PreBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PreBill_BillNumberID ON ModifyLog_PreBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



/****** 对象:  Table [dbo].[PT_Combin_SaleBackBill]    脚本日期: 05/05/2010 14:49:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ModifyLog_PT_Combin_SaleBackBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ModifyLog_PT_Combin_SaleBackBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NOT NULL,
		[discount] [numeric](24, 10) NOT NULL,
		[DiscountPrice] [numeric](24, 10) NULL ,
		[jobnumber] [varchar](20)  NULL,
		[goodsno] [int] NULL ,
		[total] [numeric](24, 10) NOT NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL ,
		[TaxTotal] [numeric](24, 10) NULL ,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[ID] [int] NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL,
		[OldID] [varchar](50) NULL ,
		[CostPrice] [numeric](24, 10) NULL ,
		[OldBillNumberID] [numeric](18, 0) NULL ,
		[InputCostPrice] [numeric](24, 10) NULL ,
		[GoodsOrder] [int] NULL ,
		[GoodsBTypeID] [varchar](50) NULL ,
		[GoodsCostPrice] [numeric](24, 10) NULL ,
		[GoodsCostTotal] [numeric](18, 2) NULL,
		[HandZeroCost] [int] NULL ,
		[CompleteQTY] [numeric](24, 10) NULL ,
		[SaleTotal] [numeric](24, 10) NULL ,
		[Tax] [numeric](24, 10) NULL ,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50)  NULL ,
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[FromBillID] [numeric](10, 0)  NULL,
		TaxMoney             numeric(24, 10)    NULL ,
		NSalePrice           numeric(24, 10)      NULL ,
		NSaleTotal           numeric(24, 10)      NULL ,
		NDiscountPrice       numeric(24, 10)      NULL ,
		NTotal               numeric(24, 10)      NULL ,
		NTaxPrice            numeric(24, 10)      NULL ,
		NTaxTotal            numeric(24, 10)      NULL ,
		NTaxMoney            numeric(24, 10)      NULL ,
		UnitID               int                NULL ,
		NUnitID              int                NULL ,
		NQty                 numeric(24, 10)     NULL ,
		UnitRate             numeric(24, 10)     NULL ,
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL ,
		MQty                 numeric(24, 10)     NULL ,
		MUnitRate            numeric(24, 10)     NULL ,
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(24, 10)     NULL ,
		MDiscountPrice       numeric(24, 10)     NULL ,
		MTaxPrice            numeric(24, 10)     NULL ,
		CurMSalePrice        numeric(24, 10)     NULL ,
		CurMDiscountPrice    numeric(24, 10)     NULL ,
		CurMTaxPrice         numeric(24, 10)     NULL ,
		CargoID              int               NULL ,
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(24, 10)		NULL ,
		InvoiceMoney		 numeric(24, 10)		null ,
		NInvoiceMoney		 numeric(24, 10)		null ,
		IsGift INT NOT NULL , -- 0不是，1是赠品
		ReferPrice NUMERIC(24,10) NOT NULL , --参考成本
		PriceStyle INT NOT NULL  --价格类型
		,PromoType INT NOT NULL  --促销类型 0是无 
		,CompleteTotal NUMERIC(24, 10) 
		,NCompleteTotal NUMERIC(24, 10) 
		,pindexid VARCHAR(300) NULL --组合品单据表体关联ID
		,ShowOrder INT 
		,PriceSource VARCHAR(100)
		,CouponCode	VARCHAR(200) 		--优惠券券编码，目前在兑换券的时候会使用
		,Reconciliation  VARCHAR(2) NOT NULL DEFAULT('f')
		,[ModifyTime] [datetime] DEFAULT(GETDATE())
		,[ModifyCount] [int] 
	) ON [PRIMARY] 
END
GO



------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBill') AND name = 'CIX_ModifyLog_PT_Combin_SaleBackBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_ModifyLog_PT_Combin_SaleBackBill_BillNumberID ON ModifyLog_PT_Combin_SaleBackBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBill_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBill_Ptypeid ON ModifyLog_PT_Combin_SaleBackBill(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBill_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBill_Ktypeid ON ModifyLog_PT_Combin_SaleBackBill(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBill_SalePrice')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBill_SalePrice ON ModifyLog_PT_Combin_SaleBackBill(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBill_Discount')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBill_Discount ON ModifyLog_PT_Combin_SaleBackBill(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBill_Tax')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBill_Tax ON ModifyLog_PT_Combin_SaleBackBill(Tax) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBill_pindexid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBill_pindexid ON ModifyLog_PT_Combin_SaleBackBill(pindexid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
         
------------------------------------------修改字段小数位数区域结束-----------------------------------------------



/****** 对象:  Table [dbo].[PT_Combin_OrderBillDetail]    脚本日期: 05/05/2010 14:48:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
	--
	--			PT_Combin_OrderBillDetail	全面修改单据历史记录
	--
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ModifyLog_PT_Combin_SaleBackBillDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ModifyLog_PT_Combin_SaleBackBillDetail](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NOT NULL ,
		[discount] [numeric](24, 10) NOT NULL,
		[DiscountPrice] [numeric](24, 10) NULL ,
		[jobnumber] [varchar](20)  NULL,
		[goodsno] [int] NULL,
		[total] [numeric](24, 10) NOT NULL ,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL ,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL ,
		[Serial] VARCHAR(max)  NULL ,
		[OldID] [varchar](50)  NULL ,
		[CostPrice] [numeric](24, 10) NULL ,
		[OldBillNumberID] [numeric](18, 0) NULL ,
		[InputCostPrice] [numeric](24, 10) NULL ,
		[GoodsOrder] [int] NULL,
		[GoodsNumber] [varchar](100)  NULL ,
		[ProduceDate] [varchar](50)  NULL ,
		[ValidDate] [varchar](50) NULL,
		[GoodsBTypeID] [varchar](50)  NULL ,
		[GoodsCostPrice] [numeric](24, 10) NULL ,
		[GoodsCostTotal] [numeric](18, 2) NULL ,
		[HandZeroCost] [int] NULL ,
		[CompleteQTY] [numeric](24, 10) NULL ,
		[SaleTotal] [numeric](24, 10) NULL ,
		[Tax] [numeric](24, 10) NULL ,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL ,
		[FromBillNumberID] [numeric](10, 0)  NULL,
		[FromBillID] [numeric](10, 0)  NULL,
		TaxMoney             numeric(24, 10)    NULL ,
		NSalePrice           numeric(24, 10)      NULL ,
		NSaleTotal           numeric(24, 10)      NULL ,
		NDiscountPrice       numeric(24, 10)      NULL ,
		NTotal               numeric(24, 10)      NULL ,
		NTaxPrice            numeric(24, 10)      NULL ,
		NTaxTotal            numeric(24, 10)      NULL ,
		NTaxMoney            numeric(24, 10)      NULL ,
		UnitID               int                NULL ,
		NUnitID              int                NULL ,
		NQty                 numeric(24, 10)     NULL ,
		UnitRate             numeric(24, 10)     NULL ,
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL ,
		MQty                 numeric(24, 10)     NULL ,
		MUnitRate            numeric(24, 10)     NULL ,
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(24, 10)     NULL ,
		MDiscountPrice       numeric(24, 10)     NULL ,
		MTaxPrice            numeric(24, 10)     NULL ,
		CurMSalePrice        numeric(24, 10)     NULL ,
		CurMDiscountPrice    numeric(24, 10)     NULL ,
		CurMTaxPrice         numeric(24, 10)     NULL ,
		CargoID              int               NULL ,
		ItemID               bigint               null,
		IsCombined           int                  null ,
		InvoiceQty			 numeric(24, 10)		NULL ,
		InvoiceMoney		 numeric(24, 10)		null ,
		NInvoiceMoney		 numeric(24, 10)		null ,
		IsGift INT NOT NULL , -- 0不是，1是赠品
		ReferPrice NUMERIC(24,10) NOT NULL , --参考成本
		PriceStyle INT NOT NULL  --价格类型
		,PromoType INT NOT NULL  --促销类型 0是无 
		,CompleteTotal NUMERIC(24, 10) 
		,NCompleteTotal NUMERIC(24, 10) 
		,pindexid VARCHAR(300) NULL --组合品单据表体关联ID
		,combinationptypeid VARCHAR(200) NULL 
		,ShowOrder INT 
		,InflowQty NUMERIC(24,10) ,
		[DraftFlag] [bit] NOT NULL ,
		[IsIniFlag] [bit] NOT NULL ,
		PriceSource VARCHAR(200)
		,InFactQty NUMERIC(24,10) NULL
		,[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] 
	) ON [PRIMARY]


END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBillDetail') AND name = 'CIX_ModifyLog_PT_Combin_SaleBackBillDetail_BillNumberID')
CREATE CLUSTERED INDEX CIX_ModifyLog_PT_Combin_SaleBackBillDetail_BillNumberID ON ModifyLog_PT_Combin_SaleBackBillDetail(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_Ptypeid ON ModifyLog_PT_Combin_SaleBackBillDetail(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_Ktypeid ON ModifyLog_PT_Combin_SaleBackBillDetail(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_SalePrice')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_SalePrice ON ModifyLog_PT_Combin_SaleBackBillDetail(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_Discount')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_Discount ON ModifyLog_PT_Combin_SaleBackBillDetail(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_Tax')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_Tax ON ModifyLog_PT_Combin_SaleBackBillDetail(Tax) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBackBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_pindexid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBackBillDetail_pindexid ON ModifyLog_PT_Combin_SaleBackBillDetail(pindexid) 
------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
         
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[PT_Combin_SaleBill]    脚本日期: 05/05/2010 14:49:04 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ModifyLog_PT_Combin_SaleBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ModifyLog_PT_Combin_SaleBill](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NULL ,
		[discount] [numeric](24, 10) NULL ,
		[DiscountPrice] [numeric](24, 10) NULL,
		[costprice] [numeric](24, 10) NULL ,
		[jobnumber] [varchar](20),
		[goodsno] [numeric](24, 10) NULL ,
		[total] [numeric](24, 10) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[OrderID] [int] NULL ,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL,
		[InputCostPrice] [numeric](24, 10) NULL ,
		[GoodsOrder] [int] NULL ,
		[BackQty] [numeric](24, 10) NULL ,
		[GoodsBTypeID] [varchar](50)  NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[GoodsCostTotal] [numeric](24, 10) NULL ,
		[HandZeroCost] [int] NULL ,
		[CompleteQTY] [numeric](24, 10) NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL ,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50)  NULL ,
		[ShareFee]	[numeric](24, 10) NOT NULL ,
		TaxMoney             numeric(24, 10)    NULL,
		NSalePrice           numeric(24, 10)      NULL,
		NSaleTotal           numeric(24, 10)      NULL,
		NDiscountPrice       numeric(24, 10)      NULL,
		NTotal               numeric(24, 10)      NULL,
		NTaxPrice            numeric(24, 10)      NULL,
		NTaxTotal            numeric(24, 10)      NULL,
		NTaxMoney            numeric(24, 10)      NULL,
		UnitID               int                NULL,
		NUnitID              int                NULL,
		NQty                 numeric(24, 10)     NULL,
		UnitRate             numeric(24, 10)     NULL,
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL,
		MQty                 numeric(24, 10)     NULL,
		MUnitRate            numeric(24, 10)     NULL ,
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(24, 10)     NULL,
		MDiscountPrice       numeric(24, 10)     NULL,
		MTaxPrice            numeric(24, 10)     NULL,
		CurMSalePrice        numeric(24, 10)     NULL,
		CurMDiscountPrice    numeric(24, 10)     NULL,
		CurMTaxPrice         numeric(24, 10)     NULL,
		CargoID              int                NULL,
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			 VARCHAR(200)		NULL  ,
		InvoiceQty			 numeric(24, 10)		NULL ,
		InvoiceMoney		 numeric(24, 10)		null,
		NInvoiceMoney		 numeric(24, 10)		null,
		IsGift INT NOT NULL, --是否是赠品 价格促销
		BeforePromoID INT NOT NULL,
		ReferPrice NUMERIC(24, 10) NOT NULL, --参考成本
		PriceStyle INT NOT NULL --价格类型
		,PriceSource   VARCHAR(200)
		,PromoType INT NOT NULL --促销类型 0是无
		,CompleteTotal NUMERIC(24, 10) --已结算金额
		,NCompleteTotal NUMERIC(24, 10)
		,LendBillID NUMERIC(10, 0) NOT NULL
		,LendBillNumberID numeric(10, 0) NOT NULL
		,ShowOrder INT
		,DiyID INT DEFAULT(-1)
		,pindexid VARCHAR(300) NULL DEFAULT('')--组合品单据表体关联ID
		,PromonIds VARCHAR(1000) NOT NULL DEFAULT('')
		,CouponCode	VARCHAR(200) DEFAULT('')		--优惠券券编码，目前在兑换券的时候会使用
		,IsPromotion	INT DEFAULT(1)					--使用优惠券后，是否参与促销
		,IsVipPoint INT DEFAULT(1)					--使用优惠券后，是否参与会员积分
		,Reconciliation  VARCHAR(2) NOT NULL DEFAULT('f')
		,[ModifyTime] [datetime] DEFAULT(GETDATE())
		,[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY] 
END
GO




------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBill') AND name = 'CIX_ModifyLog_PT_Combin_SaleBill_BillNumberID')
CREATE CLUSTERED INDEX CIX_ModifyLog_PT_Combin_SaleBill_BillNumberID ON ModifyLog_PT_Combin_SaleBill(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBill_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBill_Ptypeid ON ModifyLog_PT_Combin_SaleBill(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBill_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBill_Ktypeid ON ModifyLog_PT_Combin_SaleBill(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBill_Orderid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBill_Orderid ON ModifyLog_PT_Combin_SaleBill(Orderid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBill_SalePrice')                              
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBill_SalePrice ON ModifyLog_PT_Combin_SaleBill(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBill_Discount')          
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBill_Discount ON ModifyLog_PT_Combin_SaleBill(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_ModifyLog_PT_Combin_SaleBill') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBill_Tax')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBill_Tax ON ModifyLog_PT_Combin_SaleBill(Tax) 

------------------------------------------创建索引区域结束-----------------------------------------------
go



/****** 对象:  Table [dbo].[PT_Combin_OrderBillDetail]    脚本日期: 05/05/2010 14:48:43 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
	--
	--			PT_Combin_OrderBillDetail	全面修改单据历史记录
	--
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[ModifyLog_PT_Combin_SaleBillDetail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ModifyLog_PT_Combin_SaleBillDetail](
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50)NULL,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NULL ,
		[discount] [numeric](24, 10) NULL ,
		[DiscountPrice] [numeric](24, 10) NULL ,
		[costprice] [numeric](24, 10) NULL ,
		[jobnumber] [varchar](20)  NULL ,
		[goodsno] [numeric](24, 10) NULL ,
		[total] [numeric](24, 10) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL ,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[OrderID] [int] NULL ,
		[TeamNo] [int] NULL,
		[ID] [int] NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL ,
		[Serial] VARCHAR(max)  NULL ,
		[InputCostPrice] [numeric](24, 10) NULL ,
		[GoodsOrder] [int] NULL ,
		[BackQty] [numeric](24, 10) NULL ,
		[GoodsNumber] [varchar](100)  NULL ,
		[ProduceDate] [varchar](50) NULL ,
		[ValidDate] [varchar](50)  NULL ,
		[GoodsBTypeID] [varchar](50)  NULL ,
		[GoodsCostPrice] [numeric](24, 10) NULL ,
		[GoodsCostTotal] [numeric](24, 10) NULL ,
		[HandZeroCost] [int] NULL ,
		[CompleteQTY] [numeric](24, 10) NULL ,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL ,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50)  NULL ,
		[ShareFee]	[numeric](24, 10) NOT NULL ,
		TaxMoney             numeric(24, 10)    NULL ,
		NSalePrice           numeric(24, 10)      NULL ,
		NSaleTotal           numeric(24, 10)      NULL ,
		NDiscountPrice       numeric(24, 10)      NULL ,
		NTotal               numeric(24, 10)      NULL ,
		NTaxPrice            numeric(24, 10)      NULL ,
		NTaxTotal            numeric(24, 10)      NULL ,
		NTaxMoney            numeric(24, 10)      NULL ,
		UnitID               int                NULL ,
		NUnitID              int                NULL ,
		NQty                 numeric(24, 10)     NULL ,
		UnitRate             numeric(24, 10)     NULL ,
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL ,
		MQty                 numeric(24, 10)     NULL ,
		MUnitRate            numeric(24, 10)     NULL,
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(24, 10)     NULL ,
		MDiscountPrice       numeric(24, 10)     NULL ,
		MTaxPrice            numeric(24, 10)     NULL ,
		CurMSalePrice        numeric(24, 10)     NULL ,
		CurMDiscountPrice    numeric(24, 10)     NULL ,
		CurMTaxPrice         numeric(24, 10)     NULL ,
		CargoID              int                NULL ,
		ItemID               bigint             NULL,
		IsCombined           int                NULL,
		entryCode			 VARCHAR(200)		NULL  ,
		InvoiceQty			 numeric(24, 10)		NULL ,
		InvoiceMoney		 numeric(24, 10)		null ,
		NInvoiceMoney		 numeric(24, 10)		null ,
		IsGift INT NOT NULL , --是否是赠品 价格促销
		BeforePromoID INT NOT NULL ,
		ReferPrice NUMERIC(24, 10) NOT NULL , --参考成本
		PriceStyle INT NOT NULL  --价格类型
		,PriceSource   VARCHAR(200)
		,PromoType INT NOT NULL  --促销类型 0是无
		,CompleteTotal NUMERIC(24, 10)  --已结算金额
		,NCompleteTotal NUMERIC(24, 10) 
		,LendBillID NUMERIC(10, 0) NOT NULL 
		,LendBillNumberID numeric(10, 0) NOT NULL 
		,ShowOrder INT 
		,DiyID INT DEFAULT(-1)
		,pindexid VARCHAR(300) NULL--组合品单据表体关联ID
		,combinationptypeid VARCHAR(200) NULL
		,SendedQty NUMERIC(24,10)  --发货数量，运输单过账回写
		,PickedQty NUMERIC(24,10)  --拣货数量
		,ClearQty NUMERIC(24,10)	--解锁数量
		,OutFactQty NUMERIC(24,10) ,  --实物出库数量
		[DraftFlag] [bit] NOT NULL DEFAULT (1),
		[IsIniFlag] [bit] NOT NULL DEFAULT (0)
		,[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] 
	) ON [PRIMARY]


END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBillDetail') AND name = 'CIX_ModifyLog_PT_Combin_SaleBillDetail_BillNumberID')
CREATE CLUSTERED INDEX CIX_ModifyLog_PT_Combin_SaleBillDetail_BillNumberID ON ModifyLog_PT_Combin_SaleBillDetail(BillNumberID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBillDetail_Ptypeid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBillDetail_Ptypeid ON ModifyLog_PT_Combin_SaleBillDetail(Ptypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBillDetail_Ktypeid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBillDetail_Ktypeid ON ModifyLog_PT_Combin_SaleBillDetail(Ktypeid) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBillDetail_Orderid')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBillDetail_Orderid ON ModifyLog_PT_Combin_SaleBillDetail(Orderid) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBillDetail_SalePrice')                              
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBillDetail_SalePrice ON ModifyLog_PT_Combin_SaleBillDetail(SalePrice) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBillDetail_Discount')          
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBillDetail_Discount ON ModifyLog_PT_Combin_SaleBillDetail(Discount) 

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBillDetail_Tax')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBillDetail_Tax ON ModifyLog_PT_Combin_SaleBillDetail(Tax) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('ModifyLog_PT_Combin_SaleBillDetail') AND name = 'NCIX_ModifyLog_PT_Combin_SaleBillDetail_Id')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_PT_Combin_SaleBillDetail_Id ON ModifyLog_PT_Combin_SaleBillDetail(Id) 
------------------------------------------创建索引区域结束-----------------------------------------------
go 




GO
	--
	--			ReceiptBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_ReceiptBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_ReceiptBill]
	(
		[BillNumberID] [numeric](10, 0) NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[MainBillNumberID] [numeric](10, 0) NULL,
		[KTypeID] [varchar](100) NULL,
		[PTypeID] [varchar](100) NULL,
		[Qty] [numeric](24, 10) NULL,
		[Price] [numeric](24, 10) NULL,
		[Total] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[Comment] [varchar](255) NULL,
		[ID] [int] NOT NULL,
		[Stypeid] [varchar](50) NULL,
		[discount] [numeric](24, 10) NULL,
		[BeforePrice] [numeric](24, 10) NULL,
		[BeforeTotal] [numeric](24, 10) NULL,
		[RecordedItemId] [int] NOT NULL,
		[Nprice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[Nbeforeprice] [numeric](24, 10) NULL,
		[NBeforeTotal] [numeric](24, 10) NULL,
		[goodsnumber] [varchar](100) NULL,
		[saleprice] [numeric](24, 10) NULL,
		[saletotal] [numeric](24, 10) NULL,
		[nsaleprice] [numeric](24, 10) NULL,
		[nsaletotal] [numeric](24, 10) NULL,
		[curmsaleprice] [numeric](24, 10) NULL,
		[curmsaletotal] [numeric](24, 10) NULL,
		[taxmoney] [numeric](24, 10) NULL,
		[CompleteQty] [numeric](24, 10) NULL,
		[CompleteTotal] [numeric](24, 10) NULL,
		[NCompleteTotal] [numeric](24, 10) NULL,
		[IsGift] [int] NULL,
		[TeamNo] [int] NULL,
		[TeamNO1] [int] NULL,
		[InvoiceCostTotal] [numeric](24, 10) NULL,
		[MainBillType] [int] NULL,
		[InvoiceCostPrice] [numeric](24, 10) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[Serial] [varchar](max) NULL,
		[ShowOrder] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_ReceiptBill',N'U') AND Name = 'NCIX_ModifyLog_ReceiptBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_ReceiptBill_BillNumberID ON ModifyLog_ReceiptBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
--
--			ReceiptBillIndex 全面修改单据历史记录
--
IF NOT EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'ModifyLog_ReceiptBillIndex',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_ReceiptBillIndex]
	(
		[BillNumberID] [numeric](10, 0)  NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) NOT NULL,
		[BillType] [numeric](4, 0) NOT NULL,
		[FaPiaoType] [char](1) NULL,
		[FaPiaoCode] [varchar](256) NULL,
		[Comment] [varchar](256) NULL,
		[Explain] [varchar](256) NULL,
		[BTypeID] [varchar](100) NULL,
		[ETypeID] [varchar](100) NULL,
		[DTypeID] [varchar](100) NULL,
		[checke] [varchar](100) NULL,
		[Assessor] [varchar](50) NULL,
		[Tax] [numeric](24, 10) NULL,
		[TotalQty] [numeric](24, 10) NULL,
		[TotalMoney] [numeric](24, 10) NULL,
		[TaxTotalMoney] [numeric](24, 10) NULL,
		[Stypeid] [varchar](50) NULL,
		[OtherTotal] [numeric](24, 10) NULL,
		[ifYearBill] [int] NULL,
		[IsIni] [bit] NULL,
		[CID] [int] NULL,
		[Rate] [numeric](24, 10) NULL,
		[NTotalMoney] [numeric](24, 10) NULL,
		[NTaxTotalMoney] [numeric](24, 10) NULL,
		[DealBTypeID] [varchar](50) NULL,
		[TaskType] [tinyint] NULL,
		[AlertDay] [int] NULL,
		[RedWord] [int] NOT NULL,
		[ifcheck] [char](1) NOT NULL,
		[IfStopMoney] [int] NOT NULL,
		[CompleteTotal] [numeric](24, 10) NULL,
		[NCompleteTotal] [numeric](24, 10) NULL,
		[Draft] [bit] NOT NULL,
		[JSState] [char](1) NULL,
		[JSStyle] [char](1) NULL,
		[Poster] [varchar](100) NULL,
		[LastUpdateTime] [datetime] NULL,
		[checkTime] [datetime] NULL,
		[Posttime] [datetime] NULL,
		[UpdateE] [varchar](100) NULL,
		[IfAudit] [char](1) NULL,
		[ATypeID1] [varchar](50) NULL,
		[ATypeID2] [varchar](50) NULL,
		[Period] [smallint] NULL,
		[RedReason] [varchar](500) NULL,
		[ATID] [int] NULL,
		[Reconciliation] [char](1) NULL,
		[TeamNo] [int] NULL,
		[TallyId] [varchar](50) NULL,
		[ChargeOffTotal] [numeric](24, 10) NULL,
		[NChargeOffTotal] [numeric](24, 10) NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO

---------------------------修改-------------------------------------------
---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT  EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID('ModifyLog_ReceiptBillIndex',N'U') AND Name = 'CIX_ModifyLog_ReceiptBillIndex_BillDate')
CREATE CLUSTERED INDEX CIX_ModifyLog_ReceiptBillIndex_BillDate ON ModifyLog_ReceiptBillIndex(BillDate) 

IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID('ModifyLog_ReceiptBillIndex',N'U') AND Name = 'NCIX_ModifyLog_ReceiptBillIndex_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_ReceiptBillIndex_BillNumberID ON ModifyLog_ReceiptBillIndex(BillNumberID) 
---------------------------索引-------------------------------------------
GO




GO
	--
	--			SaleBackBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_SaleBackBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_SaleBackBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL,
		[DiscountPrice] [numeric](24, 10) NULL,
		[jobnumber] [varchar](20) NULL,
		[goodsno] [int] NULL,
		[total] [numeric](24, 10) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL,
		[Serial] [varchar](max) NULL,
		[OldID] [varchar](50) NULL,
		[CostPrice] [numeric](24, 10) NULL,
		[OldBillNumberID] [numeric](18, 0) NULL,
		[InputCostPrice] [numeric](24, 10) NULL,
		[GoodsOrder] [int] NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsBTypeID] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[GoodsCostTotal] [numeric](24, 10) NULL,
		[HandZeroCost] [int] NULL,
		[CompleteQTY] [numeric](24, 10) NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[FromBillNumberID] [numeric](10, 0) NULL,
		[FromBillID] [numeric](10, 0) NULL,
		[TaxMoney] [numeric](24, 10) NULL,
		[NSalePrice] [numeric](24, 10) NULL,
		[NSaleTotal] [numeric](24, 10) NULL,
		[NDiscountPrice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](24, 10) NULL,
		[MDiscountPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMSalePrice] [numeric](24, 10) NULL,
		[CurMDiscountPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[InvoiceQty] [numeric](24, 10) NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[IsGift] [int] NOT NULL,
		[ReferPrice] [numeric](24, 10) NULL,
		[PriceStyle] [int] NOT NULL,
		[PromoType] [int] NOT NULL,
		[OMBillID] [int] NULL,
		[CompleteTotal] [numeric](24, 10) NULL,
		[NCompleteTotal] [numeric](24, 10) NULL,
		[ShowOrder] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_SaleBackBill',N'U') AND Name = 'NCIX_ModifyLog_SaleBackBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_SaleBackBill_BillNumberID ON ModifyLog_SaleBackBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
	--
	--			SaleBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_SaleBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_SaleBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL,
		[DiscountPrice] [numeric](24, 10) NULL,
		[costprice] [numeric](24, 10) NULL,
		[jobnumber] [varchar](20) NULL,
		[goodsno] [numeric](24, 10) NULL,
		[total] [numeric](24, 10) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](2000) NULL,
		[OrderID] [int] NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[IsUnit2] [int] NOT NULL,
		[Serial] [varchar](max) NULL,
		[InputCostPrice] [numeric](24, 10) NULL,
		[GoodsOrder] [int] NULL,
		[BackQty] [numeric](24, 10) NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsBTypeID] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[GoodsCostTotal] [numeric](24, 10) NULL,
		[HandZeroCost] [int] NULL,
		[CompleteQTY] [numeric](24, 10) NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[ShareFee] [numeric](24, 10) NULL,
		[TaxMoney] [numeric](24, 10) NULL,
		[NSalePrice] [numeric](24, 10) NULL,
		[NSaleTotal] [numeric](24, 10) NULL,
		[NDiscountPrice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](24, 10) NULL,
		[MDiscountPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMSalePrice] [numeric](24, 10) NULL,
		[CurMDiscountPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[entryCode] [varchar](200) NULL,
		[InvoiceQty] [numeric](24, 10) NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[IsGift] [int] NOT NULL,
		[BeforePromoID] [int] NOT NULL,
		[ReferPrice] [numeric](24, 10) NULL,
		[PriceStyle] [int] NOT NULL,
		[PromoType] [int] NOT NULL,
		[PriceSource] [varchar](200) NULL,
		[CompleteTotal] [numeric](24, 10) NULL,
		[NCompleteTotal] [numeric](24, 10) NULL,
		[OMBillID] [int] NULL,
		[ShowOrder] [int] NULL,
		[LendBillNumberID] [numeric](10, 0) NULL,
		[LendBillID] [numeric](10, 0) NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[ModifyLog_SaleBill]') and  name = 'Comment' and Length=255)
BEGIN
	 ALTER TABLE ModifyLog_SaleBill
	    ALTER COLUMN Comment VARCHAR(2000) NULL
END
GO
---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_SaleBill',N'U') AND Name = 'NCIX_ModifyLog_SaleBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_SaleBill_BillNumberID ON ModifyLog_SaleBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
	--
	--			SendBackBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_SendBackBill',N'U'))
BEGIN
	
CREATE TABLE [dbo].[ModifyLog_SendBackBill]
(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL,
		[DiscountPrice] [numeric](24, 10) NULL,
		[total] [numeric](24, 10) NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[Serial] [varchar](max) NULL,
		[OldID] [numeric](10, 0) NULL,
		[CostPrice] [numeric](24, 10) NULL,
		[OldBillNumberID] [numeric](10, 0) NULL,
		[InputCostPrice] [numeric](24, 10) NULL,
		[GoodsOrder] [int] NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney] [numeric](24, 10) NULL,
		[NSalePrice] [numeric](24, 10) NULL,
		[NSaleTotal] [numeric](24, 10) NULL,
		[NDiscountPrice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](24, 10) NULL,
		[MDiscountPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMSalePrice] [numeric](24, 10) NULL,
		[CurMDiscountPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[InvoiceQty] [numeric](24, 10) NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[IsGift] [int] NULL,
		[ReferPrice] [numeric](24, 10) NULL,
		[PriceStyle] [int] NOT NULL,
		[InvoiceMoneyEX] [numeric](24, 10) NULL,
		[NInvoiceMoneyEX] [numeric](24, 10) NULL,
		[InvoiceCostTotal] [numeric](24, 10) NULL,
		[InvoiceNQty] [numeric](24, 10) NULL,
		[CostTotal] [numeric](24, 10) NULL,
		[InvoiceSaleMoney] [numeric](24, 10) NULL,
		[NInvoiceSaleMoney] [numeric](24, 10) NULL,
		[ShareFee] [numeric](24, 10) NULL,
		[ShowOrder] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_SendBackBill',N'U') AND Name = 'NCIX_ModifyLog_SendBackBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_SendBackBill_BillNumberID ON ModifyLog_SendBackBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



GO
	--
	--			SendBill	全面修改单据历史记录
	--
IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'ModifyLog_SendBill',N'U'))
BEGIN
	CREATE TABLE [dbo].[ModifyLog_SendBill]
	(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty] [numeric](24, 10) NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL,
		[DiscountPrice] [numeric](24, 10) NULL,
		[costprice] [numeric](24, 10) NULL,
		[total] [numeric](24, 10) NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[comment] [varchar](255) NULL,
		[OrderID] [int] NULL,
		[TeamNo] [int] NULL,
		[ID] [int]  NOT NULL,
		[TeamNO1] [int] NULL,
		[Serial] [varchar](max) NULL,
		[InputCostPrice] [numeric](24, 10) NULL,
		[GoodsOrder] [int] NULL,
		[BackQty] [numeric](24, 10) NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice] [numeric](24, 10) NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal] [numeric](24, 10) NULL,
		[Tax] [numeric](24, 10) NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[ShareFee] [numeric](24, 10) NULL,
		[TaxMoney] [numeric](24, 10) NULL,
		[NSalePrice] [numeric](24, 10) NULL,
		[NSaleTotal] [numeric](24, 10) NULL,
		[NDiscountPrice] [numeric](24, 10) NULL,
		[NTotal] [numeric](24, 10) NULL,
		[NTaxPrice] [numeric](24, 10) NULL,
		[NTaxTotal] [numeric](24, 10) NULL,
		[NTaxMoney] [numeric](24, 10) NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty] [numeric](24, 10) NULL,
		[UnitRate] [numeric](24, 10) NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty] [numeric](24, 10) NULL,
		[MUnitRate] [numeric](24, 10) NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice] [numeric](24, 10) NULL,
		[MDiscountPrice] [numeric](24, 10) NULL,
		[MTaxPrice] [numeric](24, 10) NULL,
		[CurMSalePrice] [numeric](24, 10) NULL,
		[CurMDiscountPrice] [numeric](24, 10) NULL,
		[CurMTaxPrice] [numeric](24, 10) NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[entryCode] [varchar](200) NULL,
		[InvoiceQty] [numeric](24, 10) NULL,
		[InvoiceMoney] [numeric](24, 10) NULL,
		[NInvoiceMoney] [numeric](24, 10) NULL,
		[PriceSource] [varchar](200) NULL,
		[IsGift] [int] NOT NULL,
		[ReferPrice] [numeric](24, 10) NULL,
		[PriceStyle] [int] NOT NULL,
		[InvoiceMoneyEX] [numeric](24, 10) NULL,
		[NInvoiceMoneyEX] [numeric](24, 10) NULL,
		[InvoiceCostTotal] [numeric](24, 10) NULL,
		[OldID] [numeric](10, 0) NULL,
		[OldBillNumberID] [numeric](10, 0) NULL,
		[InvoiceNQty] [numeric](24, 10) NULL,
		[CostTotal] [numeric](24, 10) NULL,
		[InvoiceSaleMoney] [numeric](24, 10) NULL,
		[NInvoiceSaleMoney] [numeric](24, 10) NULL,
		[ShowOrder] [int] NULL,
		[ModifyTime] [datetime] DEFAULT(GETDATE()),
		[ModifyCount] [int] DEFAULT(0)
	) ON [PRIMARY]
END
GO
---------------------------修改-------------------------------------------

---------------------------修改-------------------------------------------

---------------------------索引-------------------------------------------
IF NOT EXISTS (SELECT 1 FROM SysIndexes WHERE ID = OBJECT_ID(N'ModifyLog_SendBill',N'U') AND Name = 'NCIX_ModifyLog_SendBill_BillNumberID')
CREATE NONCLUSTERED INDEX NCIX_ModifyLog_SendBill_BillNumberID ON ModifyLog_SendBill(BillNumberID) 
---------------------------索引-------------------------------------------
GO



/*
	说明：记录升级列表的版本信息
	作者：谢吉康
*/
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[upgradeVersionList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[upgradeVersionList](
		[UpgradeId] INT  PRIMARY KEY IDENTITY(1,1) ,	--自增id
		[oldVersion]		VARCHAR(100),				--升级前主版本
		[oldMidVersion]		VARCHAR(100),				--升级前小版本
		[newVersion]		VARCHAR(100),				--升级后主版本
		[newMidVersion]		VARCHAR(100),				--升级后小版本
		[UpgradeDate]		DATETIME					--升级日期
	)
END
GO
--修改升级版本列表
IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE name = 'sysdata')
BEGIN
	DECLARE @version	VARCHAR(100),
			@mversion	VARCHAR(100)		
	SELECT @version = SubValue  FROM dbo.sysdata WHERE SubName = 'Version'
	SELECT @mversion = SubValue FROM dbo.sysdata WHERE SubName = 'mVersion'
	INSERT INTO upgradeVersionList(oldVersion,oldMidVersion,newVersion,newMidVersion,UpgradeDate)VALUES(@version,@mversion,'abc','abc',GETDATE())	
END
GO



/*
******************************************************************
******************分销ERP通用脚本******************
******************************************************************
*/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[APIApplicationBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[APIApplicationBill](
		BillNumberId			NUMERIC(18,0) IDENTITY(1,1) NOT NULL,		--单据ID
		BillCode				VARCHAR(50) NOT NULL,						--单据编号
		OrderID					VARCHAR(50) NOT NULL,						--顺序编号
		CompanyName				VARCHAR(200) NOT NULL,						--公司名称
		BizLinecenseCode        VARCHAR(200) NOT NULL,						--营业执照编号		
		ContactName				VARCHAR(50) NOT NULL,						--联系人名称
		ContactNum				VARCHAR(50) NOT NULL,						--联系人手机号
		ContactEmail			VARCHAR(50)  NULL,							--联系人邮箱
		ContactAddr				VARCHAR(200)  NULL,							--联系人地址
		SubmitDate				DATETIME,									--申请提交日期
		BillState				INT DEFAULT(0) NOT NULL,					--单据状态0:未审核1：已审核 2：已拒绝
		Auditor					VARCHAR(50)  NULL,							--审核人
		AuditDate				VARCHAR(50)	,								--审核日期
		APPSecret		        VARCHAR(200)						--应用程序密码 密文
	)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------

GO
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO 



/****** 对象:  Table [dbo].[AttendanceLimit]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[AttendanceLimit]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[AttendanceLimit](
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0'),		--操作员ID
		[Islimit] INT NOT NULL DEFAULT(0),											--是否限制
		[MacAddress] VARCHAR(200) NOT NULL DEFAULT '',								--MAC地址
		[HardDiskNo] VARCHAR(200) NOT NULL DEFAULT '',								--硬盘号
		[IPAddress] VARCHAR(50) NOT NULL DEFAULT ''									--IP地址
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[AttendanceTime]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[AttendanceTime]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[AttendanceTime](
		[Id] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0'),		--操作员ID
		[date] [date] NOT NULL,														--当天日期
		[StartTime] [time] NOT NULL DEFAULT ('00:00:00'),							--上班时间
		[EndTime] [time] NOT NULL DEFAULT ('00:00:00'),								--下班时间
		[LeaveReasonID] int NOT NULL DEFAULT 0,										--请假ID
		[Comment] VARCHAR(500) NOT NULL DEFAULT '',									--请假原因
		[Islate] INT NOT NULL DEFAULT(0)											--是否迟到
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[LeaveReason]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[LeaveReason]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[LeaveReason](
		[Id] INT NOT NULL,
		Fullname VARCHAR(200) NOT NULL DEFAULT '',		--请假原因
		Comment VARCHAR(500) NOT NULL DEFAULT ''		--请假原因
	) ON [PRIMARY]
END
DELETE FROM LeaveReason
INSERT INTO LeaveReason(Id,Fullname,Comment) VALUES(1,'年假','')
INSERT INTO LeaveReason(id,Fullname,Comment) VALUES(2,'产假','')
INSERT INTO LeaveReason(id,Fullname,Comment) VALUES(3,'婚假','')
INSERT INTO LeaveReason(id,Fullname,Comment) VALUES(4,'丧假','')
INSERT INTO LeaveReason(id,Fullname,Comment) VALUES(5,'病假','')
INSERT INTO LeaveReason(id,Fullname,Comment) VALUES(6,'事假','')
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[ManualRegist]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[ManualRegist]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ManualRegist](
		[Id] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[AttendanceTimeId][numeric](10, 0)  NOT NULL,								--考勤明细ID
		[RegistStartTime] [time] NOT NULL,											--登记上班时间
		[RegistEndTime] [time] NOT NULL,											--登记下班时间
		[RegistReason] VARCHAR(500) NOT NULL DEFAULT '',								--补卡原因
		[etypeid] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL   DEFAULT ('0')		--补卡员ID
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[Vacation]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Vacation]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Vacation](
		[Id] [numeric](10, 0) IDENTITY(1,1) NOT NULL,
		[Fullname] VARCHAR(max) NOT NULL DEFAULT '',		--假期名称
		[STypeID] VARCHAR(50)NOT NULL DEFAULT '',			--分支机构
		[StartTime] [datetime] NOT NULL,					--假期开始时间
		[EndTime] [datetime] NOT NULL						--假期结束时间
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[WorkTime]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[WorkTime]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[WorkTime](
		[STypeID] VARCHAR(50)NOT NULL DEFAULT '',
		[StartTime] [time] NOT NULL ,						--上班时间
		[EndTime] [time] NOT NULL,							--下班时间
		[LateTime] INT NOT NULL DEFAULT 0,						--可以迟到分钟数
		[WorkDay] VARCHAR(200) NOT NULL DEFAULT '0111110'		--正常上班日期
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/*
******************************************************************
******************分销ERP通用脚本******************
******************************************************************
*/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillAtype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillAtype](
		[BillAtypeId] INT  PRIMARY KEY IDENTITY(1,1) ,	--自增id
		[BillTypeId] VARCHAR(50),						--单据类型id
		[AtypeId]    VARCHAR(50),						--会计科目id
		[StypeId]    VARCHAR(50)						--分支机构id
	)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
/*
	说明：记录升级列表的版本信息
	作者：谢吉康
*/
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[upgradeVersionList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[upgradeVersionList](
		[UpgradeId] INT  PRIMARY KEY IDENTITY(1,1) ,	--自增id
		[oldVersion]		VARCHAR(100),				--升级前主版本
		[oldMidVersion]		VARCHAR(100),				--升级前小版本
		[newVersion]		VARCHAR(100),				--升级后主版本
		[newMidVersion]		VARCHAR(100),				--升级后小版本
		[UpgradeDate]		DATETIME					--升级日期
	)
END
GO
------------------------------------------创建索引区域结束-----------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
GO 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_BillDetails')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_BillDetails
(
	BillId		INT,
	Detailid	INT,
	BillType	INT,
	SysDiy1		VARCHAR(500),
	SysDiy2		VARCHAR(500),
	SysDiy3		VARCHAR(500),
	SysDiy4		VARCHAR(500),
	SysDiy5		VARCHAR(500),
	SysDiy6		NUMERIC(22,10),
	SysDiy7		NUMERIC(22,10),
	SysDiy8		NUMERIC(22,10),
	SysDiy9		NUMERIC(22,10),
	SysDiy10	NUMERIC(22,10),
	SysDiy11	VARCHAR(500),
	SysDiy12	VARCHAR(500),
	SysDiy13	VARCHAR(500),
	SysDiy14	VARCHAR(500),
	SysDiy15	VARCHAR(500),
	SysDiy16	VARCHAR(500),
	SysDiy17  	VARCHAR(500),
	SysDiy18  	VARCHAR(500),
	SysDiy19  	VARCHAR(500),
	SysDiy20  	VARCHAR(500),
	SysDiy21  	VARCHAR(500),
	SysDiy22  	VARCHAR(500),
	SysDiy23  	VARCHAR(500),
	SysDiy24  	VARCHAR(500),
	SysDiy25  	VARCHAR(500),
	SysDiy26  	VARCHAR(500),
	SysDiy27  	NUMERIC(24,10),
	SysDiy28  	NUMERIC(24,10),
	SysDiy29  	NUMERIC(24,10),
	SysDiy30  	NUMERIC(24,10),
	SysDiy31  	NUMERIC(24,10),
	SysDiy32  	DATETIME,
	iscombination VARCHAR(20),
	InOrOut		CHAR(1)			NOT NULL	DEFAULT('')
)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetails' AND a.Name='SysDiy6' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetails 
	ALTER COLUMN SysDiy6 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetails' AND a.Name='SysDiy7' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetails 
	ALTER COLUMN SysDiy7 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetails' AND a.Name='SysDiy8' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetails 
	ALTER COLUMN SysDiy8 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetails' AND a.Name='SysDiy9' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetails 
	ALTER COLUMN SysDiy9 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetails' AND a.Name='SysDiy10' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetails 
	ALTER COLUMN SysDiy10 NUMERIC(24,10)
    END       

IF Not EXISTS (select * from syscolumns where id=object_id('Custom_BillDetails') and name='iscombination'  )
BEGIN
	alter table Custom_BillDetails add  iscombination VARCHAR(20);
End
GO
IF NOT EXISTS(
	SELECT * 
	FROM syscolumns 
	WHERE id=object_id('Custom_BillDetails') AND name='InOrOut'
    )
    BEGIN
		ALTER TABLE Custom_BillDetails 
		ADD InOrOut CHAR(1) NOT NULL DEFAULT('')
    END 
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy17  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy17   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy18  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy18   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy19  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy19   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy20  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy20   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy21  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy21   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy22  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy22   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy23  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy23   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy24  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy24   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy25  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy25   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy26  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy26   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy27  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy27   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy28  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy28   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy29  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy29   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy30  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy30   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy31  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy31   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy32  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy32   DATETIME
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy33  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy33   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy34  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy34   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy35  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy35   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy36  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy36   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy37  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy37   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy38  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy38   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy39  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy39   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetails]') and name = 'SysDiy40  ' )
BEGIN
	alter table Custom_BillDetails add SysDiy40   VARCHAR(500)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Custom_BillDetails') AND name = 'NCIX_Custom_BillDetails_Billnumberid')
CREATE NONCLUSTERED INDEX NCIX_Custom_BillDetails_Billnumberid ON Custom_BillDetails(BillId) 

------------------------------------------创建索引区域结束-----------------------------------------------
--组合品单据自定义升级,只有下表体有数据,所以升级为InOrOut='O'
IF EXISTS(SELECT * FROM Custom_BillDetails WHERE BillType IN (313,12,46,305) AND InOrOut='')
BEGIN
	UPDATE Custom_BillDetails SET InOrOut='O' WHERE BillType IN (313,12,46,305) AND InOrOut='';
END
GO



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_BillDetailsAutoDraft')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_BillDetailsAutoDraft
(
	BillGuid	VARCHAR(100),
	BillId		INT,
	Detailid	INT,
	BillType	INT,
	SysDiy1		VARCHAR(500),
	SysDiy2		VARCHAR(500),
	SysDiy3		VARCHAR(500),
	SysDiy4		VARCHAR(500),
	SysDiy5		VARCHAR(500),
	SysDiy6		NUMERIC(22,10),
	SysDiy7		NUMERIC(22,10),
	SysDiy8		NUMERIC(22,10),
	SysDiy9		NUMERIC(22,10),
	SysDiy10	NUMERIC(22,10),
	SysDiy11	VARCHAR(500),
	SysDiy12	VARCHAR(500),
	SysDiy13	VARCHAR(500),
	SysDiy14	VARCHAR(500),
	SysDiy15	VARCHAR(500),
	SysDiy16	VARCHAR(500),
	SysDiy17  	VARCHAR(500),
	SysDiy18  	VARCHAR(500),
	SysDiy19  	VARCHAR(500),
	SysDiy20  	VARCHAR(500),
	SysDiy21  	VARCHAR(500),
	SysDiy22  	VARCHAR(500),
	SysDiy23  	VARCHAR(500),
	SysDiy24  	VARCHAR(500),
	SysDiy25  	VARCHAR(500),
	SysDiy26  	VARCHAR(500),
	SysDiy27  	NUMERIC(24,10),
	SysDiy28  	NUMERIC(24,10),
	SysDiy29  	NUMERIC(24,10),
	SysDiy30  	NUMERIC(24,10),
	SysDiy31  	NUMERIC(24,10),
	SysDiy32  	DATETIME,
	iscombination VARCHAR(20),
	InOrOut		CHAR(1)			NOT NULL	DEFAULT('')
)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetailsAutoDraft' AND a.Name='SysDiy6' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetailsAutoDraft 
	ALTER COLUMN SysDiy6 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetailsAutoDraft' AND a.Name='SysDiy7' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetailsAutoDraft 
	ALTER COLUMN SysDiy7 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetailsAutoDraft' AND a.Name='SysDiy8' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetailsAutoDraft 
	ALTER COLUMN SysDiy8 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetailsAutoDraft' AND a.Name='SysDiy9' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetailsAutoDraft 
	ALTER COLUMN SysDiy9 NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillDetailsAutoDraft' AND a.Name='SysDiy10' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE Custom_BillDetailsAutoDraft 
	ALTER COLUMN SysDiy10 NUMERIC(24,10)
    END       

IF Not EXISTS (select * from syscolumns where id=object_id('Custom_BillDetailsAutoDraft') and name='iscombination'  )
BEGIN
	alter table Custom_BillDetailsAutoDraft add  iscombination VARCHAR(20);
End
GO
IF NOT EXISTS(
	SELECT * 
	FROM syscolumns 
	WHERE id=object_id('Custom_BillDetailsAutoDraft') AND name='InOrOut'
    )
    BEGIN
		ALTER TABLE Custom_BillDetailsAutoDraft 
		ADD InOrOut CHAR(1) NOT NULL DEFAULT('')
    END 
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 

if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy17  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy17   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy18  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy18   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy19  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy19   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy20  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy20   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy21  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy21   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy22  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy22   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy23  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy23   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy24  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy24   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy25  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy25   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy26  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy26   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy27  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy27   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy28  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy28   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy29  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy29   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy30  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy30   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy31  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy31   NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy32  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy32   DATETIME
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy33  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy33   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy34  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy34   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy35  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy35   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy36  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy36   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy37  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy37   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy38  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy38   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy39  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy39   VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'SysDiy40  ' )
BEGIN
	alter table Custom_BillDetailsAutoDraft add SysDiy40   VARCHAR(500)
END
GO

--BillGuid的增加
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillDetailsAutoDraft]') and name = 'BillGuid' )
BEGIN
	ALTER TABLE Custom_BillDetailsAutoDraft 
		ADD BillGuid   VARCHAR(100)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Custom_BillDetailsAutoDraft') AND name = 'NCIX_Custom_BillDetailsAutoDraft_Billnumberid')
CREATE NONCLUSTERED INDEX NCIX_Custom_BillDetailsAutoDraft_Billnumberid ON Custom_BillDetailsAutoDraft(BillId) 

------------------------------------------创建索引区域结束-----------------------------------------------
--组合品单据自定义升级,只有下表体有数据,所以升级为InOrOut='O'
IF EXISTS(SELECT * FROM Custom_BillDetailsAutoDraft WHERE BillType IN (313,12,46,305) AND InOrOut='')
BEGIN
	UPDATE Custom_BillDetailsAutoDraft SET InOrOut='O' WHERE BillType IN (313,12,46,305) AND InOrOut='';
END
GO



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_BillIndex')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_BillIndex
(
	BillId			INT,
	BillType		INT,
	SysDiy1_head	VARCHAR(500),
	SysDiy2_head	VARCHAR(500),
	SysDiy3_head	VARCHAR(500),
	SysDiy4_head	VARCHAR(500),
	SysDiy5_head	VARCHAR(500),
	SysDiy6_head	NUMERIC(24,10),
	SysDiy7_head	NUMERIC(24,10),
	SysDiy8_head	NUMERIC(24,10),
	SysDiy9_head	NUMERIC(24,10),
	SysDiy10_head	NUMERIC(24,10),
	SysDiy11_head	VARCHAR(500),
	SysDiy12_head	VARCHAR(500),
	SysDiy13_head	VARCHAR(500),
	SysDiy14_head	VARCHAR(500),
	SysDiy15_head	VARCHAR(500),
	SysDiy16_head	VARCHAR(500),
	SysDiy17_head	VARCHAR(500),
	SysDiy18_head	VARCHAR(500),
	SysDiy19_head	VARCHAR(500),
	SysDiy20_head	VARCHAR(500),
	SysDiy21_head	VARCHAR(500),
	SysDiy22_head	VARCHAR(500),
	SysDiy23_head	VARCHAR(500),
	SysDiy24_head	VARCHAR(500),
	SysDiy25_head	VARCHAR(500),
	SysDiy26_head	VARCHAR(500),
	SysDiy27_head	NUMERIC(24,10),
	SysDiy28_head	NUMERIC(24,10),
	SysDiy29_head	NUMERIC(24,10),
	SysDiy30_head	NUMERIC(24,10),
	SysDiy31_head	NUMERIC(24,10),
	SysDiy32_head	DATETIME
)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillIndex' AND a.Name='SysDiy1_head'
)
BEGIN
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy1
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy2
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy3
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy4
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy5
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy6
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy7
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy8
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy9
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy10
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy11
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy12
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy13
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy14
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy15
	ALTER TABLE dbo.Custom_BillIndex DROP COLUMN SysDiy16
	
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy1_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy2_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy3_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy4_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy5_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy6_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy7_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy8_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy9_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy10_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy11_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy12_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy13_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy14_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy15_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndex ADD  SysDiy16_head	VARCHAR(500)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy17_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy17_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy18_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy18_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy19_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy19_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy20_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy20_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy21_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy21_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy22_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy22_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy23_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy23_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy24_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy24_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy25_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy25_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy26_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy26_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy27_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy27_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy28_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy28_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy29_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy29_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy30_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy30_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy31_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy31_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy32_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy32_head DATETIME
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy33_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy33_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy34_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy34_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy35_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy35_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy36_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy36_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy37_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy37_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy38_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy38_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy39_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy39_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndex]') and name = 'SysDiy40_head' )
BEGIN
	alter table Custom_BillIndex add SysDiy40_head VARCHAR(500)
END
GO

------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Custom_BillIndex') AND name = 'CIX_Custom_BillIndex_Billnumberid')
--DROP INDEX CIX_Custom_BillIndex_Billnumberid ON BILLINDEX 
CREATE CLUSTERED INDEX CIX_Custom_BillIndex_Billnumberid ON Custom_BillIndex(BillId,billtype) 

------------------------------------------创建索引区域结束-----------------------------------------------




if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_BillIndexAutoDraft')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_BillIndexAutoDraft
(
	BillGuid		VARCHAR(100),
	BillId			INT,
	BillType		INT,
	SysDiy1_head	VARCHAR(500),
	SysDiy2_head	VARCHAR(500),
	SysDiy3_head	VARCHAR(500),
	SysDiy4_head	VARCHAR(500),
	SysDiy5_head	VARCHAR(500),
	SysDiy6_head	NUMERIC(24,10),
	SysDiy7_head	NUMERIC(24,10),
	SysDiy8_head	NUMERIC(24,10),
	SysDiy9_head	NUMERIC(24,10),
	SysDiy10_head	NUMERIC(24,10),
	SysDiy11_head	VARCHAR(500),
	SysDiy12_head	VARCHAR(500),
	SysDiy13_head	VARCHAR(500),
	SysDiy14_head	VARCHAR(500),
	SysDiy15_head	VARCHAR(500),
	SysDiy16_head	VARCHAR(500),
	SysDiy17_head	VARCHAR(500),
	SysDiy18_head	VARCHAR(500),
	SysDiy19_head	VARCHAR(500),
	SysDiy20_head	VARCHAR(500),
	SysDiy21_head	VARCHAR(500),
	SysDiy22_head	VARCHAR(500),
	SysDiy23_head	VARCHAR(500),
	SysDiy24_head	VARCHAR(500),
	SysDiy25_head	VARCHAR(500),
	SysDiy26_head	VARCHAR(500),
	SysDiy27_head	NUMERIC(24,10),
	SysDiy28_head	NUMERIC(24,10),
	SysDiy29_head	NUMERIC(24,10),
	SysDiy30_head	NUMERIC(24,10),
	SysDiy31_head	NUMERIC(24,10),
	SysDiy32_head	DATETIME
)
END
GO


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_BillIndexAutoDraft' AND a.Name='SysDiy1_head'
)
BEGIN
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy1
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy2
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy3
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy4
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy5
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy6
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy7
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy8
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy9
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy10
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy11
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy12
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy13
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy14
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy15
	ALTER TABLE dbo.Custom_BillIndexAutoDraft DROP COLUMN SysDiy16
	
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy1_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy2_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy3_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy4_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy5_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy6_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy7_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy8_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy9_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy10_head	NUMERIC(24,10)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy11_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy12_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy13_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy14_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy15_head	VARCHAR(500)
	ALTER TABLE dbo.Custom_BillIndexAutoDraft ADD  SysDiy16_head	VARCHAR(500)
END
GO

if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy17_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy17_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy18_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy18_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy19_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy19_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy20_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy20_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy21_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy21_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy22_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy22_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy23_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy23_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy24_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy24_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy25_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy25_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy26_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy26_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy27_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy27_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy28_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy28_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy29_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy29_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy30_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy30_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy31_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy31_head NUMERIC(24,10)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy32_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy32_head DATETIME
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy33_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy33_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy34_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy34_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy35_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy35_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy36_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy36_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy37_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy37_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy38_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy38_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy39_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy39_head VARCHAR(500)
END
GO
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'SysDiy40_head' )
BEGIN
	alter table Custom_BillIndexAutoDraft add SysDiy40_head VARCHAR(500)
END
GO
--BillGuid字段增加
if not exists (select name from syscolumns where id = object_id(N'[dbo].[Custom_BillIndexAutoDraft]') and name = 'BillGuid' )
BEGIN
	ALTER TABLE Custom_BillIndexAutoDraft 
		ADD BillGuid VARCHAR(100)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Custom_BillIndexAutoDraft') AND name = 'CIX_Custom_BillIndexAutoDraft_Billnumberid')
--DROP INDEX CIX_Custom_BillIndexAutoDraft_Billnumberid ON BILLINDEX 
CREATE CLUSTERED INDEX CIX_Custom_BillIndexAutoDraft_Billnumberid ON Custom_BillIndexAutoDraft(BillId,billtype) 

------------------------------------------创建索引区域结束-----------------------------------------------




if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_Column')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_Column
(
	id INT IDENTITY,
	ColumnName VARCHAR(100),
	ColumnType INT,
	Comment VARCHAR(200)
)
END
GO


--预置数据
TRUNCATE TABLE Custom_Column
IF NOT EXISTS(SELECT TOP 1 1 FROM Custom_Column)
BEGIN
	SET IDENTITY_INSERT Custom_Column ON
	
	INSERT INTO dbo.Custom_Column
	        (id,ColumnName, Comment ,ColumnType)
	VALUES  (1,'SysDiy1','文本自定义1',1),
			(2,'SysDiy2','文本自定义2',1),
			(3,'SysDiy3','文本自定义3',1),
			(4,'SysDiy4','文本自定义4',1),
			(5,'SysDiy5','文本自定义5',1),
			(6,'SysDiy6','数字自定义1',2),
			(7,'SysDiy7','数字自定义2',2),
			(8,'SysDiy8','数字自定义3',2),
			(9,'SysDiy9','数字自定义4',2),
			(10,'SysDiy10','数字自定义5',2),
			(11,'SysDiy11','职员自定义1',3),
			(12,'SysDiy12','商品自定义',4),
			(13,'SysDiy13','往来自定义',5),
			(14,'SysDiy14','部门自定义1',6),
			(15,'SysDiy15','仓库自定义',7),
			(16,'SysDiy16','分支机构自定义',8),
			(17,'SysDiy17','文本自定义6',1),
			(18,'SysDiy18','文本自定义7',1),
			(19,'SysDiy19','文本自定义8',1),
			(20,'SysDiy20','文本自定义9',1),
			(21,'SysDiy21','文本自定义10',1),
			(22,'SysDiy22','文本自定义11',1),
			(23,'SysDiy23','文本自定义12',1),
			(24,'SysDiy24','文本自定义13',1),
			(25,'SysDiy25','文本自定义14',1),
			(26,'SysDiy26','文本自定义15',1),
			(27,'SysDiy27','数字自定义6',2),
			(28,'SysDiy28','数字自定义7',2),
			(29,'SysDiy29','数字自定义8',2),
			(30,'SysDiy30','数字自定义9',2),
			(31,'SysDiy31','数字自定义10',2),
			(32,'SysDiy32','日期自定义',9),
			(33,'SysDiy33','职员自定义2',3),
			(34,'SysDiy34','职员自定义3',3),
			(35,'SysDiy35','职员自定义4',3),
			(36,'SysDiy36','职员自定义5',3),
			(37,'SysDiy37','部门自定义2',6),
			(38,'SysDiy38','部门自定义3',6),
			(39,'SysDiy39','部门自定义4',6),
			(40,'SysDiy40','部门自定义5',6)
	
	SET IDENTITY_INSERT Custom_Column OFF
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_Column_BillDetail')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_Column_BillDetail
(
	BillType INT,
	CustomColumnId INT,
	Label VARCHAR(200),
	IsVisible INT,
	IsRequired INT
)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_Column_BillDetail' AND a.Name='InOut'
)
BEGIN
	ALTER TABLE	Custom_Column_BillDetail ADD InOut CHAR(1) NOT NULL DEFAULT ''
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
------------------------------------------升级表数据区域开始-----------------------------------------------------
--组合品单据自定义升级,只有下表体有数据,所以升级为InOut='O'
IF EXISTS (SELECT * FROM Custom_Column_BillDetail WHERE BillType IN (313,12,46,305) AND (InOut IS NULL OR InOut=''))
BEGIN
	UPDATE Custom_Column_BillDetail SET InOut='O' WHERE BillType IN (313,12,46,305) AND (InOut IS NULL OR InOut='')
END
GO
------------------------------------------升级表数据区域结束-----------------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_Column_BillIndex')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_Column_BillIndex
(
	BillType INT,
	CustomColumnId INT,
	Label VARCHAR(200),
	IsVisible INT,
	IsRequired INT
)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_ColumnType')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_ColumnType
(
	id INT IDENTITY,
	Comment VARCHAR(100)
)
END
GO

--预置数据
IF NOT EXISTS(SELECT TOP 1 1 FROM Custom_ColumnType)
BEGIN
	SET IDENTITY_INSERT Custom_ColumnType ON
	
	INSERT INTO dbo.Custom_ColumnType
	        (id,Comment )
	VALUES  (1,'文本'),
			(2,'数值'),
			(3,'职员'),
			(4,'商品'),
			(5,'往来'),
			(6,'部门'),
			(7,'仓库'),
			(8,'分支机构')
	SET IDENTITY_INSERT Custom_ColumnType OFF
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_DisplayColumn')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_DisplayColumn
(
	id			INT IDENTITY,
	DataField	VARCHAR(100),
	Comment		VARCHAR(200),
	BaseInfo	VARCHAR(100)
)
END
GO

--字段前缀说明：
--第一个d代表diy，全部都有
--e 职员
--d 部门
--db 往来单位
--b 结算单位
--st 仓库
--s 分支机构
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Custom_DisplayColumn)
BEGIN
	INSERT INTO dbo.Custom_DisplayColumn
	        ( DataField, Comment, BaseInfo )
	VALUES  ('de_usercode','经手人编号','employee'),
			('de_birthday','出生日期','employee'),
			('de_tel','办公电话','employee'),
			('de_mob','移动电话','employee'),
			('de_mail','电子邮件','employee'),
			('de_job','职位','employee'),
			('de_address','联系地址','employee'),
			('de_pycode','职员拼音码','employee'),
			('de_comment','职员备注','employee'),
			('de_maxpre','每单抹零限额','employee'),
			('de_tichengrate','提成比例%','employee'),
			('de_sfullname','职员对应分支机构名称','employee'),
			
			('dd_usercode','部门编号','Department'),
			('dd_name','部门简名','Department'),
			('dd_tel','部门电话','Department'),
			('dd_fax','部门传真','Department'),
			('dd_linkman','部门负责人','Department'),
			('dd_pycode','部门拼音码','Department'),
			('dd_comment','部门备注','Department'),
			
			('ddb_tel1','往来单位电话1','dbtype'),
			('ddb_tel2','往来单位电话2','dbtype'),
			('ddb_tel3','往来单位电话3','dbtype'),
			('ddb_telandaddress','往来单位地址','dbtype'),
			('ddb_www','往来单位网络地址','dbtype'),
			('ddb_email','往来单位电子邮件','dbtype'),
			('ddb_fax','往来单位传真','dbtype'),
			('ddb_afullname','往来单位所属地区','dbtype'),
			('ddb_taxnumber','往来单位税号','dbtype'),
			('ddb_bank','往来单位银行户名','dbtype'),
			('ddb_bankname','往来单位开户银行','dbtype'),
			('ddb_bankandacount','往来单位银行账号','dbtype'),
			('ddb_linkman1','往来单位联系人1','dbtype'),
			('ddb_linktel1','往来单位联系人1电话','dbtype'),
			('ddb_linkmobile1','往来单位联系人1手机','dbtype'),
			('ddb_linkman2','往来单位联系人2','dbtype'),
			('ddb_linktel2','往来单位联系人2电话','dbtype'),
			('ddb_linkmobile2','往来单位联系人2手机','dbtype'),
			('ddb_pycode','往来单位拼音码','dbtype'),
			('ddb_arlimittime','往来单位收款期限','dbtype'),
			('ddb_paymentltime','往来单位付款期限','dbtype'),
			('ddb_salezekou','往来单位销售折扣','dbtype'),
			('ddb_buyzekou','往来单位采购折扣','dbtype'),
			('ddb_efullname','往来单位关联职员','dbtype'),
			('ddb_comment','往来单位备注','dbtype'),
			
			('db_tel1','结算单位电话1','btype'),
			('db_tel2','结算单位电话2','btype'),
			('db_tel3','结算单位电话3','btype'),
			('db_telandaddress','结算单位地址','btype'),
			('db_www','结算单位网络地址','btype'),
			('db_email','结算单位电子邮件','btype'),
			('db_fax','结算单位传真','btype'),
			('db_afullname','结算单位所属地区','btype'),
			('db_taxnumber','结算单位税号','btype'),
			('db_bank','结算单位银行户名','btype'),
			('db_bankname','结算单位开户银行','btype'),
			('db_bankandacount','结算单位银行账号','btype'),
			('db_linkman1','结算单位联系人1','btype'),
			('db_linktel1','结算单位联系人1电话','btype'),
			('db_linkmobile1','结算单位联系人1手机','btype'),
			('db_linkman2','结算单位联系人2','btype'),
			('db_linktel2','结算单位联系人2电话','btype'),
			('db_linkmobile2','结算单位联系人2手机','btype'),
			('db_pycode','结算单位拼音码','btype'),
			('db_arlimittime','结算单位收款期限','btype'),
			('db_paymentltime','结算单位付款期限','btype'),
			('db_salezekou','结算单位销售折扣','btype'),
			('db_buyzekou','结算单位采购折扣','btype'),
			('db_efullname','结算单位关联职员','btype'),
			('db_comment','结算单位备注','btype'),
			
			('dst_usercode','仓库编号','Stock'),
			('dst_name','仓库简名','Stock'),
			('dst_add','仓库地址','Stock'),
			('dst_tel','仓库电话','Stock'),
			('dst_linkman','仓库联系人','Stock'),
			('dst_pycode','仓库拼音码','Stock'),
			('dst_comment','仓库备注','Stock'),
			('dst_sfullname','仓库所属分支机构','Stock'),
			
			
			('ds_usercode','分支机构编号','stype'),
			('ds_tel','分支机构电话','stype'),
			('ds_linkman','分支机构联系人','stype'),
			('ds_pricetype','分支机构适用价格','stype')
END
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Custom_DisplayColumn WHERE DataField = 'dd_pycode')
BEGIN
	INSERT INTO dbo.Custom_DisplayColumn
	        ( DataField, Comment, BaseInfo )
	VALUES ('dd_pycode','部门拼音码','Department')
END
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.Custom_DisplayColumn WHERE DataField = 'de_Birthday')
BEGIN
	UPDATE dbo.Custom_DisplayColumn SET DataField= 'de_birthday' WHERE DataField = 'de_Birthday'
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_DisplayColumn_BillIndex')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_DisplayColumn_BillIndex
(
	BillType INT,
	CustomDisColumnId INT,
	Label VARCHAR(200),
	IsVisible INT
)
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Custom_DisplayColumn_BillIndex' AND a.Name='OrderId'
)
BEGIN
	ALTER TABLE	Custom_DisplayColumn_BillIndex ADD OrderId INT
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



if not exists (select 1
            from  sysobjects
           where  id = object_id('Custom_DisplayColumnOrder')
            and   type = 'U')
BEGIN
CREATE TABLE Custom_DisplayColumnOrder
(
	id			INT IDENTITY,
	OrderName	VARCHAR(100),
	Comment		VARCHAR(200)
)
END
GO



IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Custom_DisplayColumnOrder)
BEGIN
	SET IDENTITY_INSERT Custom_DisplayColumnOrder ON
	
	INSERT INTO dbo.Custom_DisplayColumnOrder
	        (id,OrderName,Comment)
	VALUES  (1,'SysDisplay1','经手人显示1'),
			(2,'SysDisplay2','经手人显示2'),
			(3,'SysDisplay3','经手人显示3'),
			(4,'SysDisplay4','部门显示1'),
			(5,'SysDisplay5','部门显示2'),
			(6,'SysDisplay6','部门显示3'),
			(7,'SysDisplay7','往来单位显示1'),
			(8,'SysDisplay8','往来单位显示2'),
			(9,'SysDisplay9','往来单位显示3'),
			(10,'SysDisplay10','往来单位显示4'),
			(11,'SysDisplay11','结算单位显示1'),
			(12,'SysDisplay12','结算单位显示2'),
			(13,'SysDisplay13','结算单位显示3'),
			(14,'SysDisplay14','仓库显示1'),
			(15,'SysDisplay15','仓库显示2'),
			(16,'SysDisplay16','仓库显示3'),
			(17,'SysDisplay17','分支机构显示1'),
			(18,'SysDisplay18','分支机构显示2')
		
		
	SET IDENTITY_INSERT Custom_DisplayColumnOrder OFF
END
GO



------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('CustomBillDetailColumns') AND name = 'NCIX_CustomBillDetailColumns_Billnumberid')
CREATE NONCLUSTERED INDEX NCIX_CustomBillDetailColumns_Billnumberid ON CustomBillDetailColumns(billnumberid) 

------------------------------------------创建索引区域结束-----------------------------------------------



/****** 对象:  Table [dbo].[BillName]    脚本日期: 05/05/2010 14:46:48 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BillName]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BillName](
		[Billtype] [numeric](4, 0) NOT NULL,
		[BillName] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[Billtypes] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[BillNames] [varchar](200) COLLATE Chinese_PRC_CI_AS NOT NULL,
		[SortId]  [int] 
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillName' AND a.Name='SortId'
)
BEGIN
	ALTER TABLE BillName ADD SortId	int DEFAULT 0 NULL
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillName' AND a.Name='detailTable'
)
BEGIN
	ALTER TABLE BillName ADD detailTable VARCHAR(100) DEFAULT('') NULL
END
GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BillName' AND a.Name='IndexTable'
)
BEGIN
	ALTER TABLE BillName ADD IndexTable VARCHAR(100) DEFAULT('') NOT NULL
END
GO
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------
--处理BillName表
TRUNCATE TABLE billname
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('184','报价单','1','销售类',101,'quotepricebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('305','零售单','1','销售类',102,'retailbill','Billindex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('215','零售退货单','1','销售类',103,'RetailBackBill','Billindex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('300','销售订单','1','销售类',104,'orderbill','OrderIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('313','组合品销售订单','1','销售类',113,'PT_Combin_OrderBill','OrderIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('11','销售出库单','1','销售类',105,'salebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('45','销售退货单','1','销售类',106,'salebackbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('160','销售换货单','1','销售类',107,'salegoodsexchangebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('139','赠送单','1','销售类',108,'givebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('140','委托代销发货单','1','销售类',109,'commissionbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('142','委托代销退货单','1','销售类',110,'commissionbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('143','委托代销调价单','1','销售类',111,'commissionbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('141','委托代销结算单','1','销售类',112,'commissionbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('12','组合品销售出库单','1','销售类',114,'PT_Combin_SaleBillDetail','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('46','组合品销售退货单','1','销售类',115,'PT_Combin_SaleBackBillDetail','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('204','请购单','2','采购类',201,'requestbill','RequestIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('185','询价单','2','采购类',202,'askpricebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('301','采购订单','2','采购类',203,'orderbill','OrderIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('34','采购入库单','2','采购类',204,'buybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('6','采购退货单','2','采购类',205,'buybackbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('161','采购换货单','2','采购类',206,'buygoodsexchangebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('126','获赠单','2','采购类',207,'givemebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('144','受托代销收货单','2','采购类',208,'commissionbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('146','受托代销退货单','2','采购类',209,'commissionbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('147','受托代销调价单','2','采购类',210,'commissionbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('145','受托代销结算单','2','采购类',211,'commissionbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('17','同价调拨单','3','仓储类',301,'movebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('21','变价调拨单','3','仓储类',302,'movebjbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('187','分支机构调拨出库单','3','仓储类',303,'stypemovebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('188','分支机构调拨入库单','3','仓储类',304,'stypemovebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('201','其他入库单','3','仓储类',305,'otherinoutbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('202','其他出库单','3','仓储类',306,'otherinoutbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('306','盘点单','3','仓储类',307,'stockcheck','StockCheckIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('9','报损单','3','仓储类',308,'losebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('14','报溢单','3','仓储类',309,'overflowbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('87','借出开单','3','仓储类',310,'lendbill','LendIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('71','借进开单','3','仓储类',311,'lendbill','LendIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('88','借出还回单','3','仓储类',312,'lendbill','LendIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('72','借进还出单','3','仓储类',323,'lendbill','LendIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('16','生产拆装单','3','仓储类',314,'disassemblebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('203','序列号调整单','3','仓储类',324,'serialadjustbill','SerialAdjustIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('22','调货申请单','3','仓储类',325,'PosAllotApplyBill','PosAllotApplyBillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('326','要货申请单','3','仓储类',326,'DeliveryApplyBill','PosAllotApplyBillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('327','门店配送单','3','仓储类',327,'DeliveryBill','PosAllotApplyBillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('328','门店配送退货单','3','仓储类',328,'DeliveryBackBill','PosAllotApplyBillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('329','配送验收单','3','仓储类',329,'DeliveryCheckBill','PosAllotApplyBillIndex')

INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('116','应收增加单','5','往来类',501,'addebtbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('115','应收减少单','5','往来类',502,'addebtbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('128','应付增加单','5','往来类',503,'addebtbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('129','应付减少单','5','往来类',504,'addebtbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('4','收款单','5','往来类',505,'gatheringbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('189','预收款单','5','往来类',506,'prebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('66','付款单','5','往来类',507,'paybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('190','预付款单','5','往来类',508,'prebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('148','返利执行单','5','往来类',509,'advantage','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('150','获利执行单','5','往来类',510,'advantage','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('149','价保执行单','5','往来类',511,'priceprotectbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('151','获得价保','5','往来类',512,'priceprotectbill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('450','往来核销单','5','往来类',513,'chargeoffbill','BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('162','销售发票','5','往来类',514,'FaPiaoBill','FaPiaoBillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('163','采购发票','5','往来类',515,'FaPiaoBill','FaPiaoBillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('36','费用单','6','财务类',601,'moneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('158','现金费用单','6','财务类',602,'moneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('77','转款单','6','财务类',603,'movemoneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('93','其他收入单','6','财务类',604,'moneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('5','待摊费用发生','6','财务类',605,'moneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('10','待摊费用摊销','6','财务类',606,'moneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('84','固定资产(项目)购买单','6','财务类',607,'moneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('85','固定资产(项目)变卖单','6','财务类',608,'moneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('78','固定资产(项目)折旧单','6','财务类',609,'moneybill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('57','成本调价单','6','财务类',610,'adpricebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('159','业务凭证','6','财务类',611,'accountcredence','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('205','入库费用分摊单','6','财务类',612,'sharesourcebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('206','销售费用分摊单','6','财务类',613,'sharesourcebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('165','维修接件单','8','维修类',801,'wx_bill_jiejian','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('166','维修单','8','维修类',802,'wx_bill_self','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('167','维修取件单','8','维修类',803,'wx_bill_getback','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('168','整机更换单','8','维修类',804,'wx_bill_replace','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('169','送修单','8','维修类',805,'wx_bill_send','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('170','送修返回单','8','维修类',806,'wx_bill_sendback','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('171','报修单','8','维修类',807,'wx_bill_call','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('172','上门维修单','8','维修类',808,'wx_bill_goto','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('173','维修品调入单','8','维修类',809,'wx_bill_in','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('174','维修品调出单','8','维修类',810,'wx_bill_out','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('175','维修品调拨单','8','维修类',811,'wx_bill_move','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('181','会员储值充值单','9','汽配维修类',905,'','')--BillIndex
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('183','积分兑换单','9','汽配维修类',907,'integralexchangebill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('213','固定资产减少单','6','财务类',908,'AssetIncDecBill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('212','固定资产增加单','6','财务类',909,'AssetIncDecBill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('214','固定资产折旧单(新)','6','财务类',910,'DepBill','BillIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('307','固定资产盘点单','6','财务类',911,'FixedAssetsDetails','FixedAssetsIndex')
INSERT INTO billname(BillType,BillName,BillTypes,BillNames,SortId,DetailTable,IndexTable)VALUES('311','提成单','6','财务类',912,'CommissionBillNewDetail','CommissionBillNew')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('310','资金调拨单','9','出纳类',913,'CapitalTransfer_Bill','BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('312','会员批量储值充值单','7','会员类',914,'VipAddMoneyBatchBill','BillIndex')


INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('400','暂估入库单','2','暂估类',950,'AppraisalBill','BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('401','暂估退货单','2','暂估类',951,'AppraisalBackBill','BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('402','发出商品出库单','1','暂估类',952,'SendBill','BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('403','发出商品退货单','1','暂估类',953,'SendBackBill','BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('404','采购暂估开票','5','暂估类',954,'ReceiptBill','ReceiptBillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('405','销售发货开票','5','暂估类',955,'ReceiptBill','ReceiptBillIndex')

INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('410','卡片原值变更单','6','财务类',960,'AssetIncChangeBill','AssetIncChangeBill')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('411','固定资产拆分单','6','财务类',961,'Ac_AssetsSplitCards','AssetIncSplit')

INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('412','上架单','3','仓储类',962,'onShelvesBill','onShelvespickIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('413','拣货单','3','仓储类',963,'pickbill','onShelvespickIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('414','运输配送单','3','仓储类',964,'Transportbill','billindex')
--9.8暂时干掉了运输费用分摊
--INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('415','运输费用分摊单','3','仓储类',965,'ShareSourceBill')
--新增实物库存
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('418','仓库入库单','3','仓储类',970,'FactDepotInOut','factindex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('419','仓库出库单','3','仓储类',971,'FactDepotInOut','factindex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('420','仓库调拨单','3','仓储类',972,'FactDepotAllot','factindex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('421','未实物出库单','3','仓储类',973,'FactInOut','FactIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('422','未实物入库单','3','仓储类',974,'FactInOut','FactIndex')

--优惠券
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('423','优惠券入库单','7','会员类',980,'Coupon_InBill','Coupon_BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('424','优惠券出库单','7','会员类',981,'Coupon_OutBill','Coupon_BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('425','优惠券调拨单','7','会员类',982,'Coupon_AllotBill','Coupon_BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('426','优惠券退货单','7','会员类',983,'Coupon_BackBill','Coupon_BillIndex')

--会员积分转储值单
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('427','积分转储值单','7','会员类',984,'VipCentToMoneyBill','BillIndex')

--分支机构优惠券出库单、入库单
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('428','优惠券分支机构调拨入库单','7','会员类',985,'Coupon_AllotBillStype','Coupon_BillIndex')
INSERT INTO BillName (BillType,BillName,Billtypes,BillNames,SortId,DetailTable,IndexTable) VALUES ('429','优惠券分支机构调拨出库单','7','会员类',986,'Coupon_AllotBillStype','Coupon_BillIndex')

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BtypePriceInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BtypePriceInfo]
	(
		id INT IDENTITY(1,1),
		stypeid		VARCHAR(50),
		ptypeid		VARCHAR(50),
		btypeid		VARCHAR(50),
		areatypeid	VARCHAR(50),
		ktypeid		VARCHAR(50),
		SalePrice	numeric(18, 4) NULL default(0),
		RetailPrice numeric(18, 4) NULL default(0),
		TopbuyPrice numeric(18, 4) NULL default(0),
		BuyPrice	numeric(18, 4) NULL default(0),
		LowSalePrice numeric(18, 4) NULL default(0)
	)
	
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BtypePriceInfo' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BtypePriceInfo 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BtypePriceInfo' AND a.Name='RetailPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BtypePriceInfo 
	ALTER COLUMN RetailPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BtypePriceInfo' AND a.Name='TopbuyPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BtypePriceInfo 
	ALTER COLUMN TopbuyPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BtypePriceInfo' AND a.Name='BuyPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BtypePriceInfo 
	ALTER COLUMN BuyPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BtypePriceInfo' AND a.Name='LowSalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BtypePriceInfo 
	ALTER COLUMN LowSalePrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PriceTypeConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PriceTypeConfig]
	(
		PriceType	VARCHAR(30),	--取价方式
		IsEnable	INT,	--是否启用
		PRIORITY	INT		--优先级次
	)
	
	INSERT INTO PriceTypeConfig VALUES('促销价格',1,0),('会员价格',1,1),('价格跟踪',0,2),('往来单位物价信息',0,3)
	IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubValue=2 AND SubName='ProInfo')
		INSERT INTO PriceTypeConfig VALUES('分支机构物价信息',1,4),('商品物价信息',1,5)
	ELSE
		INSERT INTO PriceTypeConfig VALUES('商品物价信息',1,4)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[BrandBtype_Credit]    脚本日期: 05/05/2010 14:46:49 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[BrandBtype_Credit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BrandBtype_Credit](
		[BtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[StypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[BrandarTypeId] [varchar](50) ,
		[Credit]  [numeric]	(18,2) NULL 
	) ON [PRIMARY]
	
	-- ********	处理 BType	********
END
GO
------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------


------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------



------------------------------------------创建索引区域结束-----------------------------------------------


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='BrandBtype_Credit' AND a.Name='Credit' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE BrandBtype_Credit 
	ALTER COLUMN Credit NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON



SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[CheckBIllData]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[CheckBIllData](
	    [id]                int identity(1,1) NOT NULL,
		[corpid]            [varchar](500)  NULL,
		[guid]              [varchar](500)  NULL,
		[dbname]            [varchar](500)  NULL,
		[operatorid]        [varchar](500)  NULL,
		[auditingstep]      [varchar](500)  NULL,
		[billnumberid]      [varchar](500)  NULL,
		[billindextype]     [varchar](500)  NULL,
		[billtype]          [varchar](500)  NULL,
		[stypeid]           [varchar](500)  NULL,
		[dtypeid]           [varchar](500)  NULL,
		[etypeid]           [varchar](500)  NULL,
		[dealbtypeid]       [varchar](500)  NULL,
		[result]            [varchar](500)  NULL,
		[billcode]          [varchar](500)  NULL,
		[audtype]          [varchar](500)  NULL
	) ON [PRIMARY]

	-- ********	处理 tempptypeinfo	********
	DELETE FROM CheckBIllData
END
GO



/****** 对象:  Table [dbo].[CM_CarInfo]    脚本日期: 11/14/2011 17:14:13 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

SET ANSI_PADDING ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CM_CarInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CM_CarInfo](
		[TypeId] [int] IDENTITY(1,1) NOT NULL,
		[Platenumber] [varchar](50) NOT NULL,
		[Cartype] [varchar](50) NOT NULL,
		[Receptiondate] [datetime] NULL,
		[Driver] [varchar](50) NULL
	) ON [PRIMARY]
END
GO




------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[CM_CarUseBill]    Script Date: 11/14/2011 17:34:57 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CM_CarUseBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[CM_CarUseBill](
	[BillNumberId] [numeric](11, 0) NOT NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Comment] [varchar](256) NULL,
	[CarId] [int] NOT NULL,
	[Driver] [varchar](50) NULL,
	[Etypeid] [varchar](50) NULL,
	[Destination] [varchar](200) NULL,
	[Use] [varchar](500) NULL,
	[Usestartdate] [datetime] NOT NULL,
	[Useenddate] [datetime] NOT NULL
) ON [PRIMARY]
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[CM_CarUseIndex]    Script Date: 11/14/2011 17:37:24 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CM_CarUseIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CM_CarUseIndex](
		[BillNumberId] [numeric](11, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) NOT NULL,
		[BillType] [numeric](10, 0) NOT NULL,
		[Comment] [varchar](256) NULL,
		[Stypeid] [varchar](50) NOT NULL,
		[Etypeid] [varchar](50) NOT NULL,
		[Explain] [varchar](256) NULL
	) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CM_CarUseIndex' AND a.Name='Dtypeid'
)
BEGIN
	ALTER TABLE CM_CarUseIndex 
		ADD Dtypeid VARCHAR(50) NULL DEFAULT(0)
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CM_CarUseIndex' AND a.Name='checke'
)
BEGIN
	ALTER TABLE CM_CarUseIndex 
		ADD checke VARCHAR(50) NULL DEFAULT(0)
END

GO

------------------------------------------表修改区域结束-------------------------------------------------


UPDATE CM_CarUseIndex SET Dtypeid='',checke='' WHERE Dtypeid IS NULL OR checke IS NULL




------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CM_FeeBill]    脚本日期: 11/14/2011 17:38:27 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CM_FeeBill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[CM_FeeBill](
	[BillNumberId] [numeric](11, 0) NOT NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Comment] [varchar](256) NULL,
	[FeetypeId] [int] NOT NULL,
	[Total] [numeric](19, 2) NULL
) ON [PRIMARY]
END
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CM_FeeBill' AND a.Name='Total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CM_FeeBill 
	ALTER COLUMN Total NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CM_FreeIndex]    脚本日期: 11/14/2011 17:39:33 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CM_FeeIndex]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CM_FeeIndex](
		[BillNumberId] [numeric](11, 0) IDENTITY(1,1) NOT NULL,
		[BillDate] [datetime] NOT NULL,
		[BillCode] [varchar](200) NOT NULL,
		[BillType] [numeric](10, 0) NOT NULL,
		[Comment] [varchar](256) NULL,
		[CarId] [int] NOT NULL,
		[Stypeid] [varchar](50) NOT NULL,
		[Etypeid] [varchar](50) NOT NULL,
		[Dtypeid] [varchar](50) NOT NULL,
		[Totalmoney] [numeric](19, 2) NULL,
		[checke]  [varchar](50)  NULL,
		[Explain] [varchar](256) NULL
	) ON [PRIMARY]
END
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='CM_FeeIndex' AND a.Name='Totalmoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE CM_FeeIndex 
	ALTER COLUMN Totalmoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 对象:  Table [dbo].[CM_FeeType]    脚本日期: 11/14/2011 17:39:28 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[CM_FeeType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CM_FeeType](
		[FeeTypeId] [int] IDENTITY(1,1) NOT NULL,
		[Usercode] [varchar](50) NOT NULL,
		[Fullname] [varchar](100) NOT NULL,
		[Comment] [varchar](256) NULL
	) ON [PRIMARY]
END
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'DiyBill ') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DiyBill](
	[BillNumberId] [numeric](10,0) NOT NULL,   --单据Id
	[PtypeId] [varchar](50) NOT NULL,          --产品Id
	[Qty] [numeric](18,4)  NOT NULL,           --明细数量
	[SalePrice] [numeric](18,4)  NULL,         --明细折前单价
	[Comment]  [Varchar] (255) NULL,           --备注
	[SaleTotal] [numeric](18,4) NULL,          --折前金额
	[typeId]    [varchar](50) NOT NULL,        --对应一级父类Id
) ON [PRIMARY]
END 
GO

SET ANSI_PADDING OFF
GO

------------------------------------------表修改区域开始-------------------------------------------------

    ALTER TABLE DiyBill Alter column Comment varchar(500) NULL
GO
------------------------------------------表修改区域结束-------------------------------------------------

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DiyBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DiyBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DiyBill' AND a.Name='SalePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DiyBill 
	ALTER COLUMN SalePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DiyBill' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DiyBill 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'DiyBillTypePSaleTypeID') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DiyBillTypePSaleTypeID](
	[DiyBillTypeId] [varchar](50) NOT NULL,      --电脑装机配置单Id
	[SalebillNumberId] [varchar](50) NOT NULL    --销售出库单Id
) ON [PRIMARY]
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
if not exists (select name from syscolumns where id = object_id(N'[dbo].[DiyBillTypePSaleTypeID]') and name = 'ifcheck' )
BEGIN
	
	ALTER TABLE dbo.[DiyBillTypePSaleTypeID] ADD
		ifcheck varchar(10) NULL
END
GO

UPDATE DiyBillTypePSaleTypeID SET ifcheck='t' WHERE ifcheck IS NULL
------------------------------------------表修改区域结束-------------------------------------------------
SET ANSI_PADDING OFF
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'DiyIndex') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DiyIndex](
	[BillNumberId] [numeric](10,0) IDENTITY(1,1) NOT NULL,  --Diy单据Id 
	[BillDate] [Datetime] NOT NULL,           --单据日期
	[EtypeId]  [Varchar] (50) NOT NULL ,    --经手人
	[ToTalQty] [numeric] (18,4) NULL ,         --单据总数量
	[TotalMoney] [numeric] (18,4) NULL,     --单据总金额
	[Comment]  [Varchar] (500)   NULL,        --总备注
    [IndexOrderId] [Varchar] (500)    NOT NULL,          --编号
    [Counts]      [Int]    NOT NULL            --被销售出库单调用次数
) ON [PRIMARY]
END
GO

SET ANSI_PADDING OFF
GO


------------------------------------------表修改区域开始-------------------------------------------------

if not exists (select name from syscolumns where id = object_id(N'[dbo].[DiyIndex]') and name = 'Checke' )
BEGIN
    ALTER TABLE dbo.DiyIndex ADD
        Checke [Varchar] (50) NOT NULL 
END
GO
------------------------------------------表修改区域结束-------------------------------------------------




------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DiyIndex' AND a.Name='ToTalQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DiyIndex 
	ALTER COLUMN ToTalQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DiyIndex' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE DiyIndex 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'DiyType') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DiyType](
	[typeId] [varchar](50) NULL,
	[ParId] [varchar](50) NULL,
	[leveal] [smallint] NOT NULL,
	[sonnum] [int] NOT NULL,
	[soncount] [int] NOT NULL,
	[deleted] [bit] NOT NULL,
	[TypeNumber][varchar](200) NOT NULL,
	[FullName] [varchar](200) NOT NULL,
	[Name] [varchar](200) NULL,
	[Remark][varchar](400) NULL
) ON [PRIMARY]
END
GO
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='DiyType' AND a.Name='IsSys'
)
BEGIN
	ALTER TABLE dbo.DiyType ADD IsSys INT DEFAULT(0) 
END
GO

IF NOT EXISTS(SELECT *FROM DiyType)
BEGIN
DELETE DiyType
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00000','root','0','16','16','0','P00000','root',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00001','00000','1','2','2','0','P00001','CPU',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00002','00000','1','2','2','0','P00002','主板',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00003','00000','1','2','2','0','P00003','内存',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00004','00000','1','2','2','0','P00004','显卡',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00005','00000','1','2','2','0','P00005','硬盘',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00006','00000','1','2','2','0','P00006','声卡',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00007','00000','1','2','2','0','P00007','光驱',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00008','00000','1','2','2','0','P00008','网卡',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00009','00000','1','2','2','0','P00009','显示器',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00010','00000','1','2','2','0','P00010','机箱',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00011','00000','1','2','2','0','P00011','电源',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00012','00000','1','2','2','0','P00012','鼠标',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00013','00000','1','2','2','0','P00013','键盘',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00014','00000','1','2','2','0','P00014','音箱',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00015','00000','1','2','2','0','P00015','散热器',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('00016','00000','1','2','2','0','P00016','其他',1)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000100001','00001','2','0','0','0','P0000100001','AMD品牌',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000100002','00001','2','0','0','0','P0000100002','Intel品牌',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000200001','00002','2','0','0','0','P0000200001','主板品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000200002','00002','2','0','0','0','P0000200002','主板品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000300001','00003','2','0','0','0','P0000300001','内存品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000300002','00003','2','0','0','0','P0000300002','内存品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000400001','00004','2','0','0','0','P0000400001','显卡品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000400002','00004','2','0','0','0','P0000400002','显卡品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000500001','00005','2','0','0','0','P0000500001','硬盘品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000500002','00005','2','0','0','0','P0000500002','硬盘品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000600001','00006','2','0','0','0','P0000600001','声卡品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000600002','00006','2','0','0','0','P0000600002','声卡品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000700001','00007','2','0','0','0','P0000700001','光驱品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000700002','00007','2','0','0','0','P0000700002','光驱品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000800001','00008','2','0','0','0','P0000800001','网卡品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000800002','00008','2','0','0','0','P0000800002','网卡品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000900001','00009','2','0','0','0','P0000900001','显示器品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0000900002','00009','2','0','0','0','P0000900002','显示器品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001000001','00010','2','0','0','0','P0001000001','机箱品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001000002','00010','2','0','0','0','P0001000002','机箱品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001100001','00011','2','0','0','0','P0001100001','电源品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001100002','00011','2','0','0','0','P0001100002','电源品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001200001','00012','2','0','0','0','P0001200001','鼠标品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001200002','00012','2','0','0','0','P0001200002','鼠标品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001300001','00013','2','0','0','0','P0001300001','键盘品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001300002','00013','2','0','0','0','P0001300002','键盘品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001400001','00014','2','0','0','0','P0001400001','音箱品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001400002','00014','2','0','0','0','P0001400002','音箱品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001500001','00015','2','0','0','0','P0001500001','散热器品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001500002','00015','2','0','0','0','P0001500002','散热器品牌2',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001600001','00016','2','0','0','0','P0001600001','其他品牌1',0)
INSERT INTO DiyType (typeId,ParId,leveal,soncount,sonnum,deleted,TypeNumber,FullName,IsSys) VALUES ('0001600002','00016','2','0','0','0','P0001600002','其他品牌2',0)
END
GO

--系统预置的名称增加标识
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.DiyType WHERE IsSys = 1)
BEGIN
	UPDATE dbo.DiyType SET IsSys = 0
	
	UPDATE dbo.DiyType SET IsSys = 1 
	WHERE typeId IN ('00000','00001','00002','00003','00004','00005','00006','00007','00008','00009','00010','00011','00012','00013','00014','00015','00016')
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'DiyTypePTypeID') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DiyTypePTypeID](
	[Ptypeid] [varchar](50) NOT NULL,
	[Diytypeid] [varchar](50) NOT NULL
) ON [PRIMARY]
END
GO

SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[EtypeMacAndIP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE EtypeMacAndIP
(
	etypeid			        VARCHAR(200) NOT NULL,
	macaddress		        VARCHAR(200),
	harddiskno		        VARCHAR(200) 
)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_Department') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_Department]
	(
		[typeID]	[varchar](max) NULL,
		[parID]		[varchar](max) NULL,
		[level]		[int] NULL,
		[sonnum]	[int] NULL,
		[soncount]	[int] NULL,
		[delete]	[bit] NULL,
		[ID]		[int] IDENTITY(1,1) NOT NULL,
		[Name]		[varchar](max) NULL,
		[Remark]	[varchar](max) NULL,
		[userCode]	[varchar](max) NULL,			--部门编号
	) 
END
GO

IF NOT EXISTS(SELECT * FROM HR_Department)
BEGIN
	INSERT INTO HR_Department(Name,Remark,userCode)VALUES('后台管理部','负责系统后台维护','HTGLB')
	INSERT INTO HR_Department(Name,Remark,userCode)VALUES('开发部','负责开发','KFB')
END
GO 
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_Img') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_Img]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[pic] [image] NULL,
	[filename] [varchar](max) NULL,
	[length] [int] NULL,
	[Person_ID] [int] NULL
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------


IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='HR_Img' AND a.Name='pic'
)
BEGIN
	ALTER TABLE HR_Img ADD pic [image] NULL	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='HR_Img' AND a.Name='length'
)
BEGIN
	ALTER TABLE HR_Img ADD [length] int NULL	
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='HR_Img' AND a.Name='filename'
)
BEGIN
	ALTER TABLE HR_Img ADD [filename] [varchar](MAX) NULL
END

GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'[HR_InterviewDirection]') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
    CREATE TABLE [dbo].[HR_InterviewDirection]
    (
	--面试考察方向
		[typeID]	[varchar](max) NULL,
		[parID]		[varchar](max) NULL,
		[level]		[int] NULL,
		[sonnum]	[int] NULL,
		[soncount]	[int] NULL,
		[delete]	[bit] NULL,
		[ID]		[int] IDENTITY(1,1) NOT NULL,
		[Name]		[varchar](max) NULL,
		[Remark]	[varchar](max) NULL,						--备注
	) 
END

IF NOT EXISTS(SELECT * FROM HR_InterviewDirection)
	BEGIN
		INSERT INTO HR_InterviewDirection (Name) VALUES ('学习能力')
		INSERT INTO HR_InterviewDirection (Name) VALUES ('沟通能力')
		INSERT INTO HR_InterviewDirection (Name) VALUES ('思维能力')
		INSERT INTO HR_InterviewDirection (Name) VALUES ('仪表仪态')
	END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_InterviewerEstimate') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_InterviewerEstimate]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Times] [int] NOT NULL,
	[Title] [varchar](max) NULL,
	[Content] [varchar](max) NULL,
	[Score] [int] NULL,
	[Person_ID] [int] NOT NULL,
	[HR_ID] varchar(50) NULL,
	[DateTime] [datetime] NULL,
	) 
END

IF  EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_InterviewerEstimate') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	ALTER TABLE HR_InterviewerEstimate 
	ALTER COLUMN HR_ID varchar (50) not NULL
END

GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_NextEstimateTimes') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_NextEstimateTimes]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Person_ID] [int] NOT NULL,
	[NextTimes] [int] DEFAULT(0) NOT NULL,
	) 
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_Person') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_Person]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](max) NOT NULL,			--长度为十个汉字
	[LoginName] [varchar](max) NULL,			--登陆名
	[password] [varchar](max) NULL DEFAULT '',
	[Sex] [int] NULL,
	[Age] [int] NULL,
	[IDCard] [varchar](max) NULL,			--身份证
	[University] [varchar](max) NULL,		--毕业院校
	[Speciality] [varchar](max) NULL,		--专业
	[Email] [varchar](max) NULL,				
	[Phone] [varchar](max) NULL,
	[BirthDay] [varchar](max) NULL ,
	[Tall][int] NULL,						--身高
	[Intro] [varchar](max) NULL,			--自我介绍
	[PersonStatus_ID] [int] NOT NULL,		--人员状态id
	[Postion_ID] VARCHAR(50) NULL,
	[Hukou] [varchar](max) NULL,			--户口
	[Polity] [varchar](max) NULL,			--政治面貌
	[Marriage] [int] NULL,					--婚姻状况
	[Degree] [varchar](max) NULL,			--学位
	[GraduateDate] [varchar](max) NULL,		--毕业时间
	[Address] [varchar](max) NULL,			--地址
	[AccessionDate] [varchar](max) NULL,	--可到职日期
	[OldMonthlyPay] [varchar](max) NULL,	--旧月薪
	[WantPay] [varchar](max) NULL,			--期望薪水
	[LimitID] [int] NULL,				--对应的权限
	[Remark] [varchar](max) NULL,			--备注
	) 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='HR_Person' AND a.Name='PyCode')
BEGIN
	ALTER TABLE HR_Person ADD 
	PyCode VARCHAR(MAX) NULL DEFAULT('')
END
GO	
IF NOT EXISTS(SELECT * FROM HR_Person)
	BEGIN
		INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('admin','admin','','','1','1','1')
	END
GO 

IF  EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_Person') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	ALTER TABLE HR_Person 
	ALTER COLUMN sex int NULL
	
	ALTER TABLE HR_Person 
	ALTER COLUMN Marriage int  NULL
END

UPDATE HR_Person SET PyCode = '' WHERE PyCode IS NULL
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00001')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00001','','','','1','1','1')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00002')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00002','','Cru8fRVjto1UAAbeaA173crNcUcdLLm8btSfHefhqWy5M3g4Ky9f+5vQvTmm3Mgw9kyJ7HJDX5c=','','1','1','1')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00003')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00003','','0','','1','1','0')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00004')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00004','','bhWCruESCG0=','','1','1','1')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00005')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00005','','','','1','1','1')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00006')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00006','','','','1','1','1')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00007')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00007','','','','1','1','1')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00008')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00008','','','','1','1','1')	
END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM hr_person WHERE name = '00009')
BEGIN
	INSERT INTO HR_Person (Name,LoginName,Password,BirthDay,PersonStatus_ID,Postion_ID,LimitID) VALUES ('00009','','','','1','1','1')	
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_PersonEdu') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_PersonEdu]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Person_ID] [int] NOT NULL,
	[Date] [varchar](max) NULL,	
	[School] [varchar](max) NULL,
	[Specialty] [varchar](max) NULL,
	[Degree] [varchar](max) NULL,	
	) 
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'[HR_PersonFamily]') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_PersonFamily]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Person_ID] [int] NOT NULL,
	[Appellation] [varchar](max) NULL,
	[Name] [varchar](max) NULL,
	[Company] [varchar](max) NULL,
	[Phone] [varchar](max)NULL,
	[Remark] [varchar](max) NULL
	) 
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_PersonLimit') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_PersonLimit]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Person_ID] int NOT NULL,
	[Identifier] [int] NOT NULL,					--身份：0，超级管理员。1，普通操作员。2，试用期
	[Limit] [varchar](max) NOT NULL	
	) 
END
GO

IF NOT EXISTS(SELECT * FROM HR_PersonLimit)
BEGIN
	INSERT INTO HR_PersonLimit(Identifier,Person_ID,Limit)VALUES('0','1','1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111')
END
GO 
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_PersonStatus') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_PersonStatus]
	(
		[typeID]	[varchar](max) NULL,
		[parID]		[varchar](max) NULL,
		[level]		[int] NULL,
		[sonnum]	[int] NULL,
		[soncount]	[int] NULL,
		[delete]	[bit] NULL,
		[ID]		[int] NOT NULL,
		[Name]		[varchar](max) NULL,
		[Remark]	[varchar](max) NULL,
	) 
END
GO

IF NOT EXISTS(SELECT * FROM HR_PersonStatus)
BEGIN
	INSERT INTO HR_PersonStatus (ID,Name) VALUES (1,'未面试')
	INSERT INTO HR_PersonStatus (ID,Name) VALUES (2,'已面试')
	INSERT INTO HR_PersonStatus (ID,Name) VALUES (3,'试用')
	INSERT INTO HR_PersonStatus (ID,Name) VALUES (4,'正式')
END
GO 
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'[HR_PersonWorkExp]') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_PersonWorkExp]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Person_ID] [int] NOT NULL,
	[Date] [varchar](max) NULL,
	[Company] [varchar](max) NULL,
	[Department] [varchar](max) NULL,
	[Job] [varchar](max)NULL,
	[DimissionReason] [varchar](max) NULL,
	[ProvePerson] [varchar](max) NULL,
	[CompanyPhone] [varchar](max) NULL
	) 
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_Postion') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_Postion]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](max) NULL,
	[Department_ID] varchar(50) NOT NULL,
	[Intro] [varchar](max) NULL,
	[Remark] [varchar](max) NULL,
	) 
END
GO

IF  EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_Postion') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	ALTER TABLE HR_POSTION 
	ALTER COLUMN Department_ID varchar(50) NOT NULL
END
GO 
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_Task') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_Task]
	(
		[typeID] [varchar](max) NULL,
		[parID] [varchar](max) NULL,
		[level] [int] NULL,
		[sonnum] [int] NULL,
		[soncount] [int] NULL,
		[delete] [bit] NULL,
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[Name] [varchar](max) NULL,
		[Content] [varchar](max) NULL,
		[IntendingDays] [int] NULL,
		[Postion_ID][int] NOT NULL,
		[Remark] [varchar](max) NULL,
	) 
END
GO
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='HR_Task' AND a.Name='StatusID')
BEGIN
	ALTER TABLE HR_Task ADD 
	StatusID int NULL DEFAULT(0)
END
GO	
IF NOT EXISTS(SELECT * FROM HR_Task)
	BEGIN
		INSERT INTO HR_Task (Name,Content,IntendingDays,Postion_ID,Remark) VALUES ('admin','admin','1','1','1')
	END
GO 
UPDATE HR_Task SET StatusID = 0 WHERE StatusID IS NULL
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_TaskDistribution') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_TaskDistribution]
	(
	[typeID] [varchar](max) NULL,
	[parID] [varchar](max) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Task_ID] [int] NOT NULL,
	[BeginTime] [datetime] NULL,
	[EndTime] [datetime] NULL,
	[DeadTime] [datetime] NULL,
	[Person_ID] [int] NOT NULL,
	[TaskStatus_ID] [int] NOT NULL,
	[Remark] [varchar](max) NULL,
	) 
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_TaskEstimate') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_TaskEstimate](
	[typeID] [VARCHAR](MAX) NULL,
	[parID] [VARCHAR](MAX) NULL,
	[level] [INT] NULL,
	[sonnum] [INT] NULL,
	[soncount] [INT] NULL,
	[delete] [BIT] NULL,
	[ID] [INT] IDENTITY(1,1) NOT NULL,
	[Content] [VARCHAR](max) NULL,
	[Task_ID] [INT] NOT NULL,
	[Person_ID] [INT] NOT NULL,
	[HR_ID] [INT] NOT NULL,
	[DateTime] [datetime] NULL,
	) 
END
GO

------------------------------------------表修改区域开始-------------------------------------------------

--和系统里的employee相关
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='HR_TaskEstimate' AND a.Name='Person_ID')
BEGIN
	ALTER TABLE dbo.employee ALTER COLUMN
			Person_ID VARCHAR(50) NOT NULL
END
GO

--和系统里的employee相关
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='HR_TaskEstimate' AND a.Name='HR_ID')
BEGIN
	ALTER TABLE dbo.employee ALTER COLUMN
			HR_ID VARCHAR(50) NOT NULL
END
GO

------------------------------------------表修改区域结束-------------------------------------------------
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_TaskStatus') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_TaskStatus]
	(
		[typeID]	[varchar](max) NULL,
		[parID]		[varchar](max) NULL,
		[level]		[int] NULL,
		[sonnum]	[int] NULL,
		[soncount]	[int] NULL,
		[delete]	[bit] NULL,
		[ID]		[int] NOT NULL,
		[Name]		[varchar](max) NULL,
		[Remark]	[varchar](max) NULL,
	) 
END
GO

IF NOT EXISTS(SELECT * FROM HR_TaskStatus)
BEGIN
	INSERT INTO HR_TaskStatus (ID,Name) VALUES (1,'正在进行')
	INSERT INTO HR_TaskStatus (ID,Name) VALUES (2,'已经完成')
	INSERT INTO HR_TaskStatus (ID,NAME) VALUES (3,'未分配')
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('IniStockAgeGroup') AND  type = 'U')
BEGIN
	CREATE TABLE  IniStockAgeGroup
	(
		ID			INT IDENTITY(1,1) NOT NULL,
		KtypeID		VARCHAR(50),
		PtypeID		VARCHAR(50),
		InStockDate VARCHAR(50),
		StockAge	NUMERIC(24,10),
		Qty			NUMERIC(24,10),
		Total		NUMERIC(24,10)
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('IniStockAgeStock') AND  type = 'U')
BEGIN
	CREATE TABLE  IniStockAgeStock
	(
		ID			INT IDENTITY(1,1) NOT NULL,
		KtypeID		VARCHAR(50),
		PtypeID		VARCHAR(50),
		InStockDate VARCHAR(50),
		StockAge	NUMERIC(24,10),
		Qty			NUMERIC(24,10),
		Total		NUMERIC(24,10)
	)
END
GO
------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IniStockAgeStock') AND name = 'NCIX_IniStockAgeStock_KtypeID')
CREATE NONCLUSTERED INDEX NCIX_IniStockAgeStock_KtypeID ON IniStockAgeStock(KtypeID) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IniStockAgeStock') AND name = 'NCIX_IniStockAgeStock_PtypeID')
CREATE NONCLUSTERED INDEX NCIX_IniStockAgeStock_PtypeID ON IniStockAgeStock(PtypeID) 

------------------------------------------创建索引区域结束-----------------------------------------------
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF NOT EXISTS (SELECT 1 FROM   sysobjects WHERE  id = object_id('IniStockAgeStype') AND  type = 'U')
BEGIN
	CREATE TABLE  IniStockAgeStype
	(
		ID			INT IDENTITY(1,1) NOT NULL,
		KtypeID		VARCHAR(50),
		PtypeID		VARCHAR(50),
		InStockDate VARCHAR(50),
		StockAge	NUMERIC(24,10),
		Qty			NUMERIC(24,10),
		Total		NUMERIC(24,10)
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[OM_BackBillCodeSeed]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_BackBillCodeSeed]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_BackBillCodeSeed](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FlowDate] [varchar](8) NULL,
	[Seed] [int] NULL
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_BackCart]    Script Date: 11/10/2014 11:31:05 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_BackCart]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_BackCart](
		[Id] [int] IDENTITY(1,1) NOT NULL,
		[CommodityId] [varchar](50) NOT NULL,
		[CommodityName] [nvarchar](100) NOT NULL,
		[Quantity] [numeric](22, 10) NOT NULL,
		[Price] [numeric](22, 10) NOT NULL,
		[Discount] [numeric](22, 10) NOT NULL,
		[DiscountPrice] [numeric](22, 10) NOT NULL,
		[TotalMoney] [numeric](22, 10) NOT NULL,
		[SaleMoney] [numeric](22, 10) NOT NULL,
		[UnitID] [int] NOT NULL,
		[UnitName] [nvarchar](50) NOT NULL,
		[InventoryInfoId] [int] NOT NULL,
		[BtypeId] [varchar](50) NOT NULL,
		[BtypeName] [nvarchar](100) NOT NULL,
		[Comment] [nvarchar](200) NOT NULL,
		[CreatorId] [int] NOT NULL,
		[CreatorName] [nvarchar](200) NOT NULL,
		[CreatedTime] [datetime] NOT NULL,
		[ModifierId] [int] NOT NULL,
		[ModifierName] [nvarchar](200) NOT NULL,
		[ModifiedTime] [datetime] NOT NULL,
		[OrderIndexId] [int] NOT NULL,
		[OrderId] [int] NOT NULL,
		[pid] NUMERIC(10,0) NOT NULL DEFAULT(0)
	 CONSTRAINT [PK_OMBackCart] PRIMARY KEY NONCLUSTERED 
	(
		[Id] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]


	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBack__ptype__32CD1974]  DEFAULT ('') FOR [CommodityId]
	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBackgC__qty__33C13DAD]  DEFAULT ((0)) FOR [Quantity]
	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBack__price__34B561E6]  DEFAULT ((0)) FOR [Price]
	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBack__Disco__3791CE91]  DEFAULT ((1)) FOR [Discount]
	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBack__Disco__3885F2CA]  DEFAULT ((0)) FOR [DiscountPrice]
	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBack__total__35A9861F]  DEFAULT ((0)) FOR [TotalMoney]
	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBack__SaleT__397A1703]  DEFAULT ((0)) FOR [SaleMoney]
	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBack__UnitI__3A6E3B3C]  DEFAULT ((0)) FOR [UnitID]
	ALTER TABLE [dbo].[OM_BackCart] ADD  CONSTRAINT [DF__OMBack__comme__369DAA58]  DEFAULT ('') FOR [Comment]
	
END
GO
if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_BackCart]') and  name = 'pid' )
BEGIN
     ALTER TABLE OM_BackCart ADD pid  NUMERIC(10) NOT NULL DEFAULT(0)
END
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackCart' AND a.Name='Quantity' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackCart 
	ALTER COLUMN Quantity NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackCart' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackCart 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackCart' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackCart 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackCart' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackCart 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackCart' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackCart 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackCart' AND a.Name='SaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackCart 
	ALTER COLUMN SaleMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_BackOrder]    Script Date: 11/11/2014 10:46:49 ******/
IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_BackOrder]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_BackOrder](
		[Id] [int] IDENTITY(1,1) NOT NULL,
		[SerialNo] [varchar](50) NOT NULL,
		[Quantity] [numeric](22, 10) NOT NULL,
		[Discount] [numeric](3, 2) NOT NULL,
		[TotalMoney] [numeric](22, 10) NOT NULL,
		[Comment] [nvarchar](200) NOT NULL,
		[Status] [tinyint] NOT NULL,
		[BtypeId] [varchar](50) NOT NULL,
		[BtypeName] [nvarchar](200) NOT NULL,
		[CreatorId] [int] NOT NULL,
		[CreatorName] [nvarchar](200) NOT NULL,
		[CreatedTime] [datetime] NOT NULL,
		[ModifierId] [int] NOT NULL,
		[ModifierName] [nvarchar](200) NOT NULL,
		[ModifiedTime] [datetime] NOT NULL,
		[OrderIndexId] INT NOT NULL,
	 CONSTRAINT [PK_OM_BackOrderIndex] PRIMARY KEY NONCLUSTERED 
	(
		[Id] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
	ALTER TABLE [dbo].[OM_BackOrder] ADD  CONSTRAINT [DF__OM_BackOrderInd__Billc__1FBA4500]  DEFAULT ('') FOR [SerialNo]
	ALTER TABLE [dbo].[OM_BackOrder] ADD  CONSTRAINT [DF__OM_BackOrderInd__total__21A28D72]  DEFAULT ((0)) FOR [Quantity]
	ALTER TABLE [dbo].[OM_BackOrder] ADD  CONSTRAINT [DF__OM_BackOrderInd__Disco__238AD5E4]  DEFAULT ((1)) FOR [Discount]
	ALTER TABLE [dbo].[OM_BackOrder] ADD  CONSTRAINT [DF__OM_BackOrderInd__total__20AE6939]  DEFAULT ((0)) FOR [TotalMoney]
	ALTER TABLE [dbo].[OM_BackOrder] ADD  CONSTRAINT [DF__OM_BackOrderInd__comme__2296B1AB]  DEFAULT ('') FOR [Comment]
	ALTER TABLE [dbo].[OM_BackOrder] ADD  CONSTRAINT [DF__OM_BackOrderInd__BillS__247EFA1D]  DEFAULT ((0)) FOR [Status]
	ALTER TABLE [dbo].[OM_BackOrder] ADD  CONSTRAINT [DF__OM_BackOrderInd__btype__1EC620C7]  DEFAULT ('') FOR [BtypeId]
END
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrder' AND a.Name='Quantity' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrder 
	ALTER COLUMN Quantity NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrder' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrder 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrder' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrder 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_BackOrderDetail]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_BackOrderDetail](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[billNumberID] [numeric](18, 0) NULL,
		[ptypeid] [varchar](50) NULL,
		[qty] [numeric](22, 10) NULL,
		[price] [numeric](22, 10) NULL,
		[total] [numeric](22, 10) NULL,
		taxprice NUMERIC(22, 10) NULL,
		[tax] NUMERIC(10,4) NULL,
		[comment] [varchar](250) NULL,
		[Discount] [numeric](22, 10) NULL,
		[DiscountPrice] [numeric](22, 10) NULL,
		[SaleTotal] [numeric](22, 10) NULL,
		[UnitID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[ReachQty] [numeric](22, 10) NULL,
		[ConfirmQty] [numeric](22, 10) NULL,
		[StopQty] [numeric](22, 10) NULL,
		[STATUS] [tinyint] NULL,
		[InventoryInfoId] [int] NULL,
		[OrderIndexId] INT NOT NULL,
		[OrderId] INT NOT NULL,
	 CONSTRAINT [PK_BackOMBill] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__ptypeid__10780170]  DEFAULT ('') FOR [ptypeid]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__qty__116C25A9]  DEFAULT ((0)) FOR [qty]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__price__126049E2]  DEFAULT ((0)) FOR [price]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__total__13546E1B]  DEFAULT ((0)) FOR [total]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__comment__14489254]  DEFAULT ('') FOR [comment]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__Discount__153CB68D]  DEFAULT ((1)) FOR [Discount]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__Discount__1630DAC6]  DEFAULT ((0)) FOR [DiscountPrice]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__SaleTota__1724FEFF]  DEFAULT ((0)) FOR [SaleTotal]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__UnitID__18192338]  DEFAULT ((0)) FOR [UnitID]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__ReachQty__190D4771]  DEFAULT ((0)) FOR [ReachQty]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__ConfirmQ__1A016BAA]  DEFAULT ((0)) FOR [ConfirmQty]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__StopQty__1AF58FE3]  DEFAULT ((0)) FOR [StopQty]
	ALTER TABLE [dbo].[OM_BackOrderDetail] ADD  CONSTRAINT [DF__OMBackBill__STATUS__1BE9B41C]  DEFAULT ((0)) FOR [STATUS]
END
GO


if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_BackOrderDetail]') and  name = 'taxprice' )
BEGIN
     ALTER TABLE OM_BackOrderDetail ADD taxprice NUMERIC(22, 10) NULL
END
GO

if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_BackOrderDetail]') and  name = 'tax' )
BEGIN
     ALTER TABLE OM_BackOrderDetail ADD tax NUMERIC(10,4) NULL
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='taxprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN taxprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='ReachQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN ReachQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='ConfirmQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN ConfirmQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BackOrderDetail' AND a.Name='StopQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BackOrderDetail 
	ALTER COLUMN StopQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_BillCodeSeed]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_BillCodeSeed]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_BillCodeSeed](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FlowDate] [varchar](8) NULL,
	[Seed] [int] NULL
	) ON [PRIMARY]	
End
GO

--迁移数据
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMBillCode_Seed]') AND type in (N'U'))
BEGIN
insert into dbo.OM_BillCodeSeed([FlowDate],[Seed]) select  [FlowDate],[Seed] from dbo.OMBillCode_Seed
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[OM_BillIndex]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_BillIndex]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_BillIndex](
	[BillNumberID] [int] IDENTITY(1,1) NOT NULL,
	[BillDate] [date] NULL,
	[State] [int] NULL,
	[CancelReason] [varchar](500) NULL,
	[BillCode] [varchar](200) NULL,
	[BillType] [int] NULL,
	[BtypeID] [varchar](50) NULL,
	[LoginUser_ID] [int] NOT NULL,
	[TotalReturnQty] [numeric](18, 4) NULL,
	[CompeledDate] [date] NULL,
 CONSTRAINT [PK_OM_BILLINDEX] PRIMARY KEY CLUSTERED 
(
	[BillNumberID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_BillIndex' AND a.Name='TotalReturnQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_BillIndex 
	ALTER COLUMN TotalReturnQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[OM_Carts]    Script Date: 07/29/2014 18:05:25 ******/

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_Carts]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_Carts](
	[TypeID] [int] NOT NULL,
	[PtypeID] [varchar](50) NOT NULL,
	[LoginUser_ID] [int] NOT NULL,
	[Qty] [int] NOT NULL,
	[Date] [datetime] NOT NULL
) ON [PRIMARY]
End
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_DeliveryAddress]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_DeliveryAddress]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_DeliveryAddress](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NULL,
	[Address] [nvarchar](500) NULL,
	[PhoneNumber] [nvarchar](50) NULL,
	[TelPhone] [nvarchar](50) NULL,
	[Email] [nvarchar](50) NULL,
	[Comment] [nvarchar](500) NULL,
	[CreatorId] [int] NULL,
	[CreatorName] [nvarchar](200) NULL,
	[CreatedTime] [datetime] NULL,
	[ModifierId] [int] NULL,
	[ModifierName] [nvarchar](200) NULL,
	[ModifiedTime] [datetime] NULL,
	[IsDefault] [bit] null
) ON [PRIMARY]
End
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** Object:  Table [dbo].[OM_DiscountBill]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_DiscountBill]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_DiscountBill](
	[BillNumberID] [int] IDENTITY(1,1) NOT NULL,
	[BillIndex_ID] [int] NULL,
	[OldDiscount] [numeric](19, 4) NULL,
	[NewDiscount] [numeric](19, 4) NULL,
	[ModReason] [varchar](500) NULL,
 CONSTRAINT [PK_OM_DISCOUNTBILL] PRIMARY KEY CLUSTERED 
(
	[BillNumberID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]	
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_DiscountBill' AND a.Name='OldDiscount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_DiscountBill 
	ALTER COLUMN OldDiscount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_DiscountBill' AND a.Name='NewDiscount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_DiscountBill 
	ALTER COLUMN NewDiscount NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_Inventory]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_Inventory]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_Inventory](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[UserCode] [varchar](200) NOT NULL CONSTRAINT [DF__OMInvento__UserC__2B2BF7AC]  DEFAULT (''),
	[FullName] [varchar](200) NOT NULL CONSTRAINT [DF__OMInvento__FullN__2C201BE5]  DEFAULT (''),
	[Comment] [varchar](256) NOT NULL CONSTRAINT [DF__OMInvento__Comme__2D14401E]  DEFAULT (''),
	[CreatorId] [int] NULL,
	[CreatorName] [nvarchar](200) NULL,
	[CreatedTime] [datetime] NULL,
	[ModifierId] [int] NULL,
	[ModifierName] [nvarchar](200) NULL,
	[ModifiedTime] [datetime] NULL
) ON [PRIMARY]
End
GO


--迁移数据
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMInventoryInfo]') AND type in (N'U'))
BEGIN
insert into OM_Inventory(
       [UserCode]
      ,[FullName]
      ,[Comment]
      ,[CreatorId]
      ,[CreatorName]
      ,[CreatedTime]
      ,[ModifierId]
      ,[ModifierName]
      ,[ModifiedTime]
)

select [UserCode]
      ,[FullName]
      ,[Comment]
      ,0
      ,''
      ,getdate()
      ,0
      ,''
      ,getdate()
      from OMInventoryInfo
end

--升级或完全安装后，判断是否需要插入预制数据
IF NOT EXISTS (select * from dbo.OM_Inventory where UserCode=N'QB')
begin
INSERT [dbo].[OM_Inventory]  VALUES (N'QB', N'全部', N' ', 1, N'Admin', CAST(0x0000A2C800000000 AS DateTime), 1, N'Admin', CAST(0x0000A2C800000000 AS DateTime))
end

go
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_Inventory_Ext]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_Inventory_Ext]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[OM_Inventory_Ext](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[InventoryId] [int] NOT NULL CONSTRAINT [DF__OMInvento__Inven__2EFC8890]  DEFAULT ((0)),
	[PtypeId] [varchar](50) NOT NULL CONSTRAINT [DF__OMInvento__Ptype__2FF0ACC9]  DEFAULT (''),
	[Status] [varchar](100) NOT NULL CONSTRAINT [DF__OMInvento__Statu__30E4D102]  DEFAULT (''),
	[CreatorId] [int] NULL,
	[CreatorName] [nvarchar](200) NULL,
	[CreatedTime] [datetime] NULL,
	[ModifierId] [int] NULL,
	[ModifierName] [nvarchar](200) NULL,
	[ModifiedTime] [datetime] NULL,
 CONSTRAINT [PK_OMInventoryInfo_Ext] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO



--迁移数据
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMInventoryInfo_Ext]') AND type in (N'U'))
BEGIN
insert into OM_Inventory_Ext(
       [InventoryId]
      ,[PtypeId]
      ,[Status]
      ,[CreatorId]
      ,[CreatorName]
      ,[CreatedTime]
      ,[ModifierId]
      ,[ModifierName]
      ,[ModifiedTime]
)
select [InventoryID]
      ,[Ptypeid]
      ,[Status] 
      ,0
      ,''
      ,getdate()
      ,0
      ,''
      ,getdate()
      from OMInventoryInfo_Ext

end
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_InvoceBill]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_InvoceBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_InvoceBill](
	[BillNumberID] [int] IDENTITY(1,1) NOT NULL,
	[BillIndex_ID] [int] NULL,
	[InvoceQty] [numeric](18, 4) NULL,
	[InvocePrice] [numeric](23, 4) NULL,
	[InvoceTotalPrice] [numeric](23, 4) NULL,
	[InvocedQty] [numeric](18, 4) NULL,
	[InvocedTotalPrice] [numeric](23, 4) NULL,
	[Qty] [numeric](18, 4) NULL,
 CONSTRAINT [PK_OM_INVOCEBILL] PRIMARY KEY CLUSTERED 
(
	[BillNumberID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_InvoceBill' AND a.Name='InvoceQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_InvoceBill 
	ALTER COLUMN InvoceQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_InvoceBill' AND a.Name='InvocePrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_InvoceBill 
	ALTER COLUMN InvocePrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_InvoceBill' AND a.Name='InvoceTotalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_InvoceBill 
	ALTER COLUMN InvoceTotalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_InvoceBill' AND a.Name='InvocedQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_InvoceBill 
	ALTER COLUMN InvocedQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_InvoceBill' AND a.Name='InvocedTotalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_InvoceBill 
	ALTER COLUMN InvocedTotalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_InvoceBill' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_InvoceBill 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_LoginUserLeveal]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_LoginUserLeveal]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_LoginUserLeveal](
	[TypeID] [int] IDENTITY(1,1) NOT NULL,
	[FullName] [varchar](50) NOT NULL,
	[Remark] [varchar](500) NULL
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_LoginUsers]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_LoginUsers]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_LoginUsers](
	[TypeID] [int] IDENTITY(1,1) NOT NULL,
	[BtypeID] [varchar](50) NULL,
	[UserCode] [varchar](50) NULL,
	[UserName] [varchar](50) NULL,
	[Date] [date] NULL,
	[Level] [int] NULL,
	[TelePhone] [varchar](50) NULL,
	[QQ] [varchar](50) NULL,
	[Email] [varchar](50) NULL,
	[MobilePhone] [varchar](50) NULL,
	[Lim] [varchar](5000) NULL,
	[Password] [varchar](10) NULL
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_Order]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_Order]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_Order](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[SerialNo] [varchar](50) NOT NULL CONSTRAINT [DF__OMBillInd__Billc__1FBA4500]  DEFAULT (''),
	[Quantity] [numeric](22, 10) NOT NULL CONSTRAINT [DF__OMBillInd__total__21A28D72]  DEFAULT ((0)),
	[Discount] [numeric](3, 2) NOT NULL CONSTRAINT [DF__OMBillInd__Disco__238AD5E4]  DEFAULT ((1)),
	[TotalMoney] [numeric](22, 10) NOT NULL CONSTRAINT [DF__OMBillInd__total__20AE6939]  DEFAULT ((0)),
	[Comment] [nvarchar](200) NOT NULL CONSTRAINT [DF__OMBillInd__comme__2296B1AB]  DEFAULT (''),
	[Status] [tinyint] NOT NULL CONSTRAINT [DF__OMBillInd__BillS__247EFA1D]  DEFAULT ((0)),
	[BtypeId] [varchar](50) NOT NULL CONSTRAINT [DF__OMBillInd__btype__1EC620C7]  DEFAULT (''),
	[BtypeName] [nvarchar](200) NOT NULL,
	[CreatorId] [int] NOT NULL,
	[CreatorName] [nvarchar](200) NOT NULL,
	[CreatedTime] [datetime] NOT NULL,
	[ModifierId] [int] NOT NULL,
	[ModifierName] [nvarchar](200) NOT NULL,
	[ModifiedTime] [datetime] NOT NULL,
 CONSTRAINT [PK_OMBillIndex] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_Order]') and  name = 'PreferenceMoney' )
BEGIN
     ALTER TABLE OM_Order
	    ADD PreferenceMoney  [numeric](18, 4) NOT NULL DEFAULT(0)
END
GO


if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_Order]') and  name = 'bid' )
BEGIN
     ALTER TABLE OM_Order
	    ADD bid  INT  NOT NULL DEFAULT(0)
END
GO

----迁移数据
--IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMBillIndex]') AND type in (N'U'))
--BEGIN
--Insert into OM_Order(
--            [SerialNo]
--           ,[Quantity]
--           ,[Discount]
--           ,[TotalMoney]
--           ,[Comment]
--           ,[Status]
--           ,[BtypeId]
--           ,[BtypeName]
--           ,[CreatorId]
--           ,[CreatorName]
--           ,[CreatedTime]
--           ,[ModifierId]
--           ,[ModifierName]
--           ,[ModifiedTime]) 
           
--           select 
--            [Billcode]
--           ,[totalqty]
--           ,[Discount]
--           ,[totalmoney]
--           ,[comment]
--           ,[BillStatus]
--           ,[btypeid]
--           ,'' 
--           ,[OMOperatorID]
--           ,'' 
--           ,[BillDate]
--           ,[OMOperatorID]
--           ,''
--           ,[BillDate]
--            from OMBillIndex
--end
--GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_Order' AND a.Name='Quantity' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_Order 
	ALTER COLUMN Quantity NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_Order' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_Order 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_Order' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_Order 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_Order' AND a.Name='PreferenceMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_Order 
	ALTER COLUMN PreferenceMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_OrderDetail]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_OrderDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_OrderDetail](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[billNumberID] [numeric](18, 0) NULL,
	[ptypeid] [varchar](50) NULL CONSTRAINT [DF__OMBill__ptypeid__10780170]  DEFAULT (''),
	[qty] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__qty__116C25A9]  DEFAULT ((0)),
	[price] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__price__126049E2]  DEFAULT ((0)),
	[total] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__total__13546E1B]  DEFAULT ((0)),
	taxprice NUMERIC(22, 10) NULL,
	[tax] NUMERIC(10,4) NULL,
	[comment] [varchar](250) NULL CONSTRAINT [DF__OMBill__comment__14489254]  DEFAULT (''),
	[Discount] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__Discount__153CB68D]  DEFAULT ((1)),
	[DiscountPrice] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__Discount__1630DAC6]  DEFAULT ((0)),
	[SaleTotal] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__SaleTota__1724FEFF]  DEFAULT ((0)),
	[UnitID] [int] NULL CONSTRAINT [DF__OMBill__UnitID__18192338]  DEFAULT ((0)),
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[ReachQty] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__ReachQty__190D4771]  DEFAULT ((0)),
	[ConfirmQty] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__ConfirmQ__1A016BAA]  DEFAULT ((0)),
	[StopQty] [numeric](22, 10) NULL CONSTRAINT [DF__OMBill__StopQty__1AF58FE3]  DEFAULT ((0)),
	[STATUS] [tinyint] NULL CONSTRAINT [DF__OMBill__STATUS__1BE9B41C]  DEFAULT ((0)),
	[InventoryInfoId] [int] NULL,
	IsGift BIT NOT NULL DEFAULT(0),
	pid NUMERIC(10,0) NOT NULL DEFAULT(0),
 CONSTRAINT [PK_OMBill] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_OrderDetail]') and  name = 'pid' )
BEGIN
     ALTER TABLE OM_OrderDetail ADD pid  NUMERIC(10) NOT NULL DEFAULT(0)
END
GO

if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_OrderDetail]') and  name = 'IsGift' )
BEGIN
     ALTER TABLE OM_OrderDetail ADD IsGift BIT NOT NULL DEFAULT(0)
END
GO

if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_OrderDetail]') and  name = 'taxprice' )
BEGIN
     ALTER TABLE OM_OrderDetail ADD taxprice NUMERIC(22, 10) NULL
END
GO

if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_OrderDetail]') and  name = 'tax' )
BEGIN
     ALTER TABLE OM_OrderDetail ADD tax NUMERIC(10,4) NULL
END
GO




----迁移数据
--IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMBill]') AND type in (N'U'))
--BEGIN
--insert into OM_OrderDetail(
--      [billNumberID]
--      ,[ptypeid]
--      ,[qty]
--      ,[price]
--      ,[total]
--      ,[comment]
--      ,[Discount]
--      ,[DiscountPrice]
--      ,[SaleTotal]
--      ,[UnitID]
--      ,[ItemID]
--      ,[IsCombined]
--      ,[ReachQty]
--      ,[ConfirmQty]
--      ,[StopQty]
--      ,[STATUS]
--      ,[InventoryInfoId]
--)

--select [billNumberID]
--      ,[ptypeid]
--      ,[qty]
--      ,[price]
--      ,[total]
--      ,[comment]
--      ,[Discount]
--      ,[DiscountPrice]
--      ,[SaleTotal]
--      ,[UnitID]
--      ,[ItemID]
--      ,[IsCombined]
--      ,[ReachQty]
--      ,[ConfirmQty]
--      ,[StopQty]
--      ,[STATUS]
--      ,[InventoryInfoId]
      
--      from OMBill
--end
--GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='total' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN total NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='taxprice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN taxprice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='tax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN tax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='SaleTotal' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN SaleTotal NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='ReachQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN ReachQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='ConfirmQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN ConfirmQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetail' AND a.Name='StopQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetail 
	ALTER COLUMN StopQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_OrderDetails]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_OrderDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_OrderDetails](
	[BillNumberID] [int] IDENTITY(1,1) NOT NULL,
	[Billindex_ID] [int] NULL,
	[PtypeID] [varchar](50) NULL,
	[StypeID] [varchar](50) NULL,
	[Qty] [numeric](18, 4) NULL,
	[TaxRate] [numeric](5, 2) NULL,
	[TaxAmount] [numeric](18, 4) NULL,
	[PriceNoTax] [numeric](18, 4) NULL,
	[TotalPriceNoTax] [numeric](18, 4) NULL,
	[Price] [numeric](18, 4) NULL,
	[TotalPrice] [numeric](18, 4) NULL,
	[Discount] [numeric](19, 4) NULL,
	[DiscountPrice] [numeric](23, 4) NULL,
	[DiscountTotalPrice] [numeric](23, 4) NULL,
	[PriceNature] [bit] NULL,
	[SpecalPrice] [numeric](18, 4) NULL,
	[SpecalTotalPrice] [numeric](18, 4) NULL,
	[ShipmentsQty] [numeric](18, 4) NULL,
	[OutQty] [numeric](18, 4) NULL,
 CONSTRAINT [PK_OM_ORDERDETAILS] PRIMARY KEY CLUSTERED 
(
	[BillNumberID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='Qty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN Qty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='TaxRate' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN TaxRate NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='TaxAmount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN TaxAmount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='PriceNoTax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN PriceNoTax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='TotalPriceNoTax' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN TotalPriceNoTax NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='TotalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN TotalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='DiscountTotalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN DiscountTotalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='SpecalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN SpecalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='SpecalTotalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN SpecalTotalPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='ShipmentsQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN ShipmentsQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_OrderDetails' AND a.Name='OutQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_OrderDetails 
	ALTER COLUMN OutQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_Ptype]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_Ptype]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_Ptype](
	[TypeID] [int] IDENTITY(1,1) NOT NULL,
	[PtypeID] [varchar](50) NOT NULL,
	[PtypeClass_ID] [varchar](50) NOT NULL,
	[IsSave] [bit] NOT NULL,
 CONSTRAINT [PK_OM_PTYPE] PRIMARY KEY CLUSTERED 
(
	[TypeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_Ptype_l]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_Ptype_l]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_Ptype_l](
	[LoginUserLevelID] [int] NOT NULL,
	[PtypeClassID] [int] NOT NULL
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_PtypeClass]    Script Date: 07/29/2014 18:05:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_PtypeClass]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_PtypeClass](
	[TypeID] [varchar](50) NOT NULL,
	[UserCode] [varchar](50) NULL,
	[FullName] [varchar](100) NULL,
	[ParID] [varchar](50) NULL,
	[Leveal] [int] NULL,
	[Sonnum] [int] NULL,
	[Soncount] [int] NULL,
	[Remark] [varchar](500) NULL,
 CONSTRAINT [PK_OM_PTYPECLASS] PRIMARY KEY CLUSTERED 
(
	[TypeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_QuestionReply]    Script Date: 07/29/2014 18:05:26 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_QuestionReply]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_QuestionReply](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Contents] [nvarchar](500) NOT NULL,
	[Reply] [nvarchar](500) NOT NULL,
	[CreatorId] [int] NOT NULL,
	[CreatorName] [nvarchar](200) NOT NULL,
	[CreatedTime] [datetime] NOT NULL,
	[ModifierId] [int] NOT NULL,
	[ModifierName] [nvarchar](200) NOT NULL,
	[ModifiedTime] [datetime] NOT NULL,
 CONSTRAINT [PK_OM_QuestionReply] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_ReplacementGoods]    Script Date: 07/29/2014 18:05:26 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_ReplacementGoods]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_ReplacementGoods](
	[BillNumberId] [int] IDENTITY(1,1) NOT NULL,
	[BillIndex_ID] [int] NULL,
	[OrderDetails_ID] [int] NULL,
	[ReplacementGoodsQty] [numeric](18, 4) NULL,
	[ReplacementGoodsableQty] [numeric](18, 4) NULL,
	[Reason] [varchar](500) NULL,
 CONSTRAINT [PK_OM_REPLACEMENTGOODS] PRIMARY KEY CLUSTERED 
(
	[BillNumberId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ReplacementGoods' AND a.Name='ReplacementGoodsQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ReplacementGoods 
	ALTER COLUMN ReplacementGoodsQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ReplacementGoods' AND a.Name='ReplacementGoodsableQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ReplacementGoods 
	ALTER COLUMN ReplacementGoodsableQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_ReturnGoods]    Script Date: 07/29/2014 18:05:26 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_ReturnGoods]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_ReturnGoods](
	[BillNumberID] [int] IDENTITY(1,1) NOT NULL,
	[BillIndex_ID] [int] NULL,
	[OrderDetails_ID] [int] NULL,
	[ReturnGoodsableQty] [numeric](18, 4) NULL,
	[ReturnGoodsQty] [numeric](18, 4) NULL,
	[Reason] [varchar](500) NULL,
	[ReturnPrice] [numeric](18, 4) NULL,
	[ReturnTotalPrice] [numeric](18, 4) NULL,
 CONSTRAINT [PK_OM_RETURNGOODS] PRIMARY KEY CLUSTERED 
(
	[BillNumberID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ReturnGoods' AND a.Name='ReturnGoodsableQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ReturnGoods 
	ALTER COLUMN ReturnGoodsableQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ReturnGoods' AND a.Name='ReturnGoodsQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ReturnGoods 
	ALTER COLUMN ReturnGoodsQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ReturnGoods' AND a.Name='ReturnPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ReturnGoods 
	ALTER COLUMN ReturnPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ReturnGoods' AND a.Name='ReturnTotalPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ReturnGoods 
	ALTER COLUMN ReturnTotalPrice NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_Shipments]    Script Date: 07/29/2014 18:05:26 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_Shipments]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_Shipments](
	[ID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
	[OMBillID] [int] NULL,
	[GoodsBillID] [int] NULL,
	[ReachQty] [numeric](22, 10) NULL DEFAULT ((0)),
	[ConfirmQty] [numeric](22, 10) NULL DEFAULT ((0)),
	[STATUS] [bit] NULL DEFAULT ((0)),
	[comment] [varchar](250) NULL DEFAULT ('')
) ON [PRIMARY]
End
GO

--迁移数据
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMBillShipments]') AND type in (N'U'))
BEGIN
insert into OM_Shipments(
       [OMBillID]
      ,[GoodsBillID]
      ,[ReachQty]
      ,[ConfirmQty]
      ,[STATUS]
      ,[comment]
      )
select [OMBillID]
      ,[GoodsBillID]
      ,[ReachQty]
      ,[ConfirmQty]
      ,[STATUS]
      ,[comment] from OMBillShipments
end
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_Shipments' AND a.Name='ReachQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_Shipments 
	ALTER COLUMN ReachQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_Shipments' AND a.Name='ConfirmQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_Shipments 
	ALTER COLUMN ConfirmQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_ShoppingCart]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_ShoppingCart](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[CommodityId] [varchar](50) NOT NULL CONSTRAINT [DF__OMShoppin__ptype__32CD1974]  DEFAULT (''),
	[CommodityName] [nvarchar](100) NOT NULL,
	[Quantity] [numeric](22, 10) NOT NULL CONSTRAINT [DF__OMShoppingC__qty__33C13DAD]  DEFAULT ((0)),
	[Price] [numeric](22, 10) NOT NULL CONSTRAINT [DF__OMShoppin__price__34B561E6]  DEFAULT ((0)),
	[Discount] [numeric](22, 10) NOT NULL CONSTRAINT [DF__OMShoppin__Disco__3791CE91]  DEFAULT ((1)),
	[DiscountPrice] [numeric](22, 10) NOT NULL CONSTRAINT [DF__OMShoppin__Disco__3885F2CA]  DEFAULT ((0)),
	[TotalMoney] [numeric](22, 10) NOT NULL CONSTRAINT [DF__OMShoppin__total__35A9861F]  DEFAULT ((0)),
	[SaleMoney] [numeric](22, 10) NOT NULL CONSTRAINT [DF__OMShoppin__SaleT__397A1703]  DEFAULT ((0)),
	[UnitID] [int] NOT NULL CONSTRAINT [DF__OMShoppin__UnitI__3A6E3B3C]  DEFAULT ((0)),
	[UnitName] [nvarchar](50) NOT NULL,
	[InventoryInfoId] [int] NOT NULL,
	[BtypeId] [varchar](50) NOT NULL,
	[BtypeName] [nvarchar](100) NOT NULL,
	[Comment] [nvarchar](200) NOT NULL CONSTRAINT [DF__OMShoppin__comme__369DAA58]  DEFAULT (''),
	[CreatorId] [int] NOT NULL,
	[CreatorName] [nvarchar](200) NOT NULL,
	[CreatedTime] [datetime] NOT NULL,
	[ModifierId] [int] NOT NULL,
	[ModifierName] [nvarchar](200) NOT NULL,
	[ModifiedTime] [datetime] NOT NULL,
	[IsShopping] [bit] not null,
	[IsGift] [bit] not null
 CONSTRAINT [PK_OMShoppingCart] PRIMARY KEY NONCLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_ShoppingCart]') and  name = 'pid' )
BEGIN
     ALTER TABLE OM_ShoppingCart
	    ADD pid  NUMERIC(10) NOT NULL DEFAULT(0)
END
GO

if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_ShoppingCart]') and  name = 'bid' )
BEGIN
     ALTER TABLE OM_ShoppingCart
	    ADD bid  INT  NOT NULL DEFAULT(0)
END
GO
if NOT exists (select name from syscolumns where id = object_id(N'[dbo].[OM_ShoppingCart]') and  name = 'IsGift' )
BEGIN
     ALTER TABLE OM_ShoppingCart
	    ADD IsGift  INT  NOT NULL DEFAULT(0)
END
GO

----迁移数据
--IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMShoppingCart]') AND type in (N'U'))
--BEGIN


--insert into om_ShoppingCart(
--      [CommodityId]
--      ,[CommodityName]
--      ,[Quantity]
--      ,[Price]
--      ,[Discount]
--      ,[DiscountPrice]
--      ,[TotalMoney]
--      ,[SaleMoney]
--      ,[UnitID]
--      ,[UnitName]
--      ,[InventoryInfoId]
--      ,[BtypeId]
--      ,[BtypeName]
--      ,[Comment]
--      ,[CreatorId]
--      ,[CreatorName]
--      ,[CreatedTime]
--      ,[ModifierId]
--      ,[ModifierName]
--      ,[ModifiedTime]
--      ,[IsShopping]
--)

--select 
--      [ptypeid]
--      ,''
--      ,[qty]
--      ,[price]
--      ,[Discount]
--      ,[DiscountPrice]
--      ,[total]
--      ,[SaleTotal]
--      ,[UnitID]
--      ,''
--      ,[InventoryInfoId]
--      ,[btypeid]
--      ,''
--      ,[comment]
--      ,[OMOperatorID]
--      ,''
--      ,getdate()
--      ,[OMOperatorID]
--      ,''
--      ,getdate()
--      ,1
-- from OMShoppingCart



----更新关联数据
--update om_shoppingcart set om_shoppingcart.CommodityName=ptype.FullName  from ptype
--   where om_shoppingcart.Commodityid=ptype.typeid
   
--   update om_shoppingcart set om_shoppingcart.unitname=ptype_units.FullName from ptype_units
--		where om_shoppingcart.UnitId=ptype_units.unitsid


--END
--GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ShoppingCart' AND a.Name='Quantity' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ShoppingCart 
	ALTER COLUMN Quantity NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ShoppingCart' AND a.Name='Price' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ShoppingCart 
	ALTER COLUMN Price NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ShoppingCart' AND a.Name='Discount' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ShoppingCart 
	ALTER COLUMN Discount NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ShoppingCart' AND a.Name='DiscountPrice' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ShoppingCart 
	ALTER COLUMN DiscountPrice NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ShoppingCart' AND a.Name='TotalMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ShoppingCart 
	ALTER COLUMN TotalMoney NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OM_ShoppingCart' AND a.Name='SaleMoney' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OM_ShoppingCart 
	ALTER COLUMN SaleMoney NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OM_SqlLog]    Script Date: 07/29/2014 18:05:26 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OM_SqlLog]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OM_SqlLog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Type] [tinyint] NOT NULL,
	[DateTime] [datetime] NOT NULL,
	[Elapsed] [int] NOT NULL,
	[Params] [varchar](1000) NULL,
	[IPAddress] [varchar](15) NULL,
	[_Sql] [varchar](8000) NULL,
	[ExecuteElapsed] [int] NULL,
	[FetchElapsed] [int] NULL,
	[_RowCount] [int] NULL,
	[Error] [varchar](400) NULL,
	[LoginUserID] [int] NOT NULL,
 CONSTRAINT [PK_OM_SQLLOG] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[OMBillAttachFiles]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[OMBillAttachFiles](	
		[ID] INT IDENTITY(1,1) NOT NULL,
		[BillNumberId] NUMERIC(18,0) NOT NULL,		
		[FileName] VARCHAR(300) NOT NULL DEFAULT(''),
		[FileType] VARCHAR(50) NOT NULL DEFAULT(''),
		[Size] VARCHAR(100) NOT NULL DEFAULT(''),
		[AttachDate] DATETIME NOT NULL DEFAULT(''),
		[newname] VARCHAR(100),
		[Data] image NOT NULL,
		[BillIndexType] INT NOT NULL DEFAULT(0), --300订单	
		bid INT NOT NULL DEFAULT(0),
		[operatorname] VARCHAR(200)
	) ON [PRIMARY]
END
GO

if   not   EXISTS(select   *   from   syscolumns   where   id=object_id( 'OMBillAttachFiles')   and   name= 'operatorname' )
begin 
	alter table OMBillAttachFiles add   operatorname VARCHAR(200)
end
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OMBillCode_Seed]    Script Date: 07/29/2014 18:05:26 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMBillCode_Seed]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OMBillCode_Seed](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FlowDate] [varchar](8) NULL,
	[Seed] [int] NULL
) ON [PRIMARY]
End
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




/****** Object:  Table [dbo].[OMBillShipments]    Script Date: 07/29/2014 18:05:26 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OMBillShipments]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OMBillShipments](
	[ID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
	[OMBillID] [int] NULL,
	[GoodsBillID] [int] NULL,
	[ReachQty] [numeric](22, 10) NULL DEFAULT ((0)),
	[ConfirmQty] [numeric](22, 10) NULL DEFAULT ((0)),
	[STATUS] [bit] NULL DEFAULT ((0)),
	[comment] [varchar](250) NULL DEFAULT ('')
) ON [PRIMARY]
End
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OMBillShipments' AND a.Name='ReachQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OMBillShipments 
	ALTER COLUMN ReachQty NUMERIC(24,10)
    END
                                        
IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='OMBillShipments' AND a.Name='ConfirmQty' AND  (a.xscale<>10 or xprec<>24)
    )
    BEGIN
	ALTER TABLE OMBillShipments 
	ALTER COLUMN ConfirmQty NUMERIC(24,10)
    END
                                        
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	插件程序集表配置表
	作    者：	王涛
	修改时间：	2003-09-27
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ord_AssemblyInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table [dbo].[Ord_AssemblyInfo]
	(
		Id int identity(1,1) primary key,
		PlugId int not null,
		Name varchar(100) not null,
		Destinationalpath varchar(200) not null,
		ServerTemppath varchar(200) not NULL,
		[type] VARCHAR(10) NOT null
	)
END
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 





/****** Object:  Table [dbo].[Ord_CahcePlugLimitData]    Script Date: 06/09/2014 15:25:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ord_CahcePlugLimitData]') AND type in (N'U'))
DROP TABLE [dbo].[Ord_CahcePlugLimitData]
GO

/****** Object:  Table [dbo].[Ord_CahcePlugLimitData]    Script Date: 06/09/2014 15:25:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Ord_CahcePlugLimitData](
	[PlugID] [int] NULL,
	[ETypeID] [varchar](50) NULL,
	[Lim] [int] NULL,
	[QXEnum] [varchar](200) NULL,
	[QXName] [varchar](200) NULL,
	[LimitType] [int] NULL,
	[Name] [varchar](200) NULL,
	[NameSpaceAndClass] [varchar](500) NULL,
	[NeedLoadAssembly] [varchar](500) NULL,
	[WebMenuName] [varchar](500) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	插件功能权限点主表
	作    者：	王涛
	修改时间：	2003-09-27
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ord_LimitList]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table [dbo].[Ord_LimitList]
	(
		Id int identity(1,1),
		PlugId int not null,
		QXName varchar(200) null,
		QXEnum varchar(200) not null,
		plugmenuid INT,
		limittype INT--1:单据录入2:单据过账3：单据调阅4：单据打印5：单据导出6：单据导入7：报表查询8：报表打印9报表导出
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	已安装插件主表
	作    者：	王涛
	修改时间：	2003-09-27
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ord_Plug]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table [dbo].[Ord_Plug]
	(
		Id int identity(1,1),
		PlugName varchar(200) primary key,
		AppropriateVerSion varchar(200) not null,
		XmlPath VARCHAR(200),
		IsInstalled int not null,
		plugversion VARCHAR(50),
		plugfuncdescription VARCHAR(2000),
		InstallDate datetime default(getdate())
	)
END
GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Ord_Plug]') and  name = 'AppropriateVerSion' and (Length=200 OR length=1000))
BEGIN
	 ALTER TABLE Ord_Plug
	    ALTER COLUMN AppropriateVerSion VARCHAR(4000) NOT NULL
END
GO
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[Ord_Plug]') and  name = 'XmlPath' and Length=200)
BEGIN
	 ALTER TABLE Ord_Plug
	    ALTER COLUMN XmlPath VARCHAR(2000) NOT NULL
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	插件安装日志表
	作    者：	王涛
	修改时间：	2003-09-27
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ord_PlugInstallLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Ord_PlugInstallLog]
	(
		id INT IDENTITY(1,1),
		plugname VARCHAR(200),
		plugid INT,
		XmlContent text not null,
		installdate DATETIME DEFAULT GETDATE()
	)
END
GO

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='Ord_PlugInstallLog' AND a.Name='XmlContent' and a.xtype=35
)
BEGIN
	ALTER TABLE Ord_PlugInstallLog ALTER COLUMN XmlContent VARCHAR(MAX)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	操作员插件权限点对应关系表
	作    者：	王涛
	修改时间：	2003-09-27
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ord_PlugLimitFooting]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table [dbo].[Ord_PlugLimitFooting]
	(
		Id int identity(1,1),
		plugid int not null,
		LimitId int not null,
		EtypeId varchar(50) not null,
		Lim int not null default(0)
	)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	插件菜单配置表
	作    者：	王涛
	修改时间：	2003-09-27
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Ord_PopUpPage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table [dbo].[Ord_PopUpPage]
	(
		Id int identity(1,1) primary key,
		PlugId int not null,
		Name varchar(50) not null,
		parentmenuid int not null,
		NameSpaceAndClass varchar(500) not null,
		NeedLoadAssembly varchar(500) not null,
		Offset int not null,
		ismdi INT ,
		paramlist VARCHAR(200),
		replacemenuid VARCHAR(20),
		menutype INT,
		webmenuname VARCHAR(2000),
		menuguid VARCHAR(40),
		xapname VARCHAR(100)
	)
END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	插件功能权限点主表
	作    者：	王涛
	修改时间：	2003-09-27
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[plug_Event]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[plug_Event]
	(
		[plugid] INT ,
		[EventId] [varchar](2000) NULL,
		[EventName] [varchar](200) NULL
	)
END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	插件功能权限点主表
	作    者：	王涛
	修改时间：	2003-09-27
*/

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Plug_EventLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Plug_EventLog](
		[Id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
		[EventDate] [datetime] NOT NULL,
		[etypeid] [varchar](50) NULL,
		[EventId] [varchar](2000) NULL,
		[Ip] [varchar](50) NULL,
		[Deleted] [char](1) NOT NULL DEFAULT 0
	)
END 
GO





------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
/*
	功能说明：	插件角色权限
	作    者：	王涛
	修改时间：	2014年5月30日 11:18:10
*/

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Plug_UserGroup]') AND type in (N'U'))
BEGIN
	CREATE TABLE Plug_UserGroup
	(
		UgId				INT NOT NULL,	--用户组ID
		plugid				INT NOT NULL,
		limitid				INT NOT NULL,
		lim					int NOT NULL
	)
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_UploadDogInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	create table [dbo].Pos_UploadDogInfo
	(
		Id  BIGINT identity(1,1),
	    dognumber VARCHAR(200),
	    posname VARCHAR(200),
	    eid INT,
	    billcount INT,
	    logtime DATETIME NOT NULL DEFAULT(GETDATE()),
	    uploadtime DATETIME,
	    IsUpload CHAR(1)
	)
END
GO


------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 






SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[POSBankRateInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE POSBankRateInfo
	(
		rateid			INT IDENTITY(1,1) NOT NULL,
		UserCode		VARCHAR(200) NULL,
		FullName		VARCHAR(200) NULL,
		bankitemid		varchar(50),
		payitemid		varchar (50),
		payrate			NUMERIC(24,4) NULL,
		limittotal		NUMERIC(24,2) NULL,
		retaildefault 	INT NOT NULL DEFAULT(0),
		ratestate BIT NOT NULL DEFAULT(0),
		comment			varchar (500)			
	)
END
GO





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[POSPtypeShortCutConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE POSPtypeShortCutConfig(
		id INT  PRIMARY KEY IDENTITY(1,1) ,	
		posid INT,					---pos终端ID
		pid    INT,		--商品ID			
		shortcut VARCHAR(100)		-- 快捷键字符串 组合键以+ 分开; 如 Shift+Q
	)
END
GO





SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PosVipLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PosVipLog(
		id INT IDENTITY NOT NULL,
		vipCardcode VARCHAR(200) NOT NULL,
		vipmoney decimal(24, 10) NULL,
		TotalMoney decimal(24, 10) NULL,
		BillDate DATETIME NOT NULL,
		PosName VARCHAR(200) NOT NULL,
		DanjuId VARCHAR(200) NOT NULL
)
END
GO 

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosVipLog' AND a.Name='BillDate'
)
BEGIN
	ALTER TABLE PosVipLog ADD BillDate DATETIME  NULL
END
GO


IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosVipLog' AND a.Name='BillData'
)
BEGIN
	ALTER TABLE PosVipLog drop COLUMN BillData 
END
GO


IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PosVipLog' AND a.Name='vipmoney' AND  (a.xscale<>10 or xprec<>24)
    )
BEGIN

DROP TABLE PosVipLog

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[PosVipLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE PosVipLog(
		id INT IDENTITY NOT NULL,
		vipCardcode VARCHAR(200) NOT NULL,
		vipmoney   decimal(24, 10) NULL,
		TotalMoney decimal(24, 10) NULL,
		BillDate DATETIME NOT NULL,
		PosName VARCHAR(200) NOT NULL,
		DanjuId VARCHAR(200) NOT NULL
)
END


END
GO



SET ANSI_NULLS ON


SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[RecvSysGgDetail]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[RecvSysGgDetail](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[GGID] [int] NULL,
	[POSID] [int] NULL,
	[LOOKTIME] [datetime] NULL,
	[ISLOOK] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

END
GO



SET ANSI_NULLS ON


SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SMSBillType]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SMSBillType](
	    [id]                int identity(1,1) NOT NULL,
		[SMSBillType]       [varchar](500)  NULL,
		[SMSBillName]       [varchar](500)  NULL,
		[smstemplatecode]   [varchar](500)  NULL,
		[smstemplatename]   [varchar](500)  NULL,
		[smstemplatecontent][varchar](500)  NULL,
		[smsbeizhu]         [varchar](500)  NULL,
		[flag]              [varchar](500)  NULL,--0 保存 1 过账 2 定时
		[selected]          bit             NULL,
		[templateid]        [varchar](50)  NULL,
		[HyyunSmsTemplateContent] VARCHAR(MAX) NULL DEFAULT('')
	) ON [PRIMARY]

	-- ********	处理 SMSBillType	********
	DELETE FROM SMSBillType
	Insert into SMSBillType(SMSBillType,SMSBillName) select billtype,billname from billname where billtype in (300,11,45,301,34,6,4,66,402,400,404,405)
	
	-- ********	处理 SMSBillType 预制信息	********
	
	update SMSBillType set smstemplatecode='001',smstemplatename='销售出库单系统预置短信模板001',smstemplatecontent='您好，@单据编号,@商品名称等@销售数量@基本计量单位已发货出库，请注意查收。',smsbeizhu='',flag='0',selected=1,templateid='1' where SMSBillType='11'
	update SMSBillType set smstemplatecode='002',smstemplatename='销售出库单系统预置短信模板002',smstemplatecontent='您好，@单据编号,@商品名称等@销售数量@基本计量单位已发货出库，请注意查收。',smsbeizhu='',flag='0',selected=1,templateid='2' where SMSBillType='402'
	update SMSBillType set smstemplatecode='003',smstemplatename='销售订单系统预置短信模板',smstemplatecontent='您的订单@商品名称等@销售数量@基本计量单位已收到，正在准备发货，请知悉。',smsbeizhu='',flag='1',selected=1,templateid='3' where SMSBillType='300'
	update SMSBillType set smstemplatecode='004',smstemplatename='销售退库单系统预置短信模板',smstemplatecontent='您好，销售退货@商品名称等@销售数量@基本计量单位已发货出库，请注意查收。',smsbeizhu='',flag='0',selected=1,templateid='4' where SMSBillType='45'
	update SMSBillType set smstemplatecode='005',smstemplatename='采购订单系统预置短信模板',smstemplatecontent='我方订货@商品名称等@采购数量@基本计量单位，请知悉。',smsbeizhu='',flag='1',selected=1,templateid='5' where SMSBillType='301'
	update SMSBillType set smstemplatecode='006',smstemplatename='采购入库系统预置短信模板001',smstemplatecontent='您发出的@商品名称等@采购数量@基本计量单位已到货。',smsbeizhu='',flag='0',selected=1,templateid='6' where SMSBillType='34'
	update SMSBillType set smstemplatecode='007',smstemplatename='采购入库系统预置短信模板002',smstemplatecontent='您发出的@商品名称等@采购数量@基本计量单位已到货。',smsbeizhu='',flag='0',selected=1,templateid='7' where SMSBillType='400'
	update SMSBillType set smstemplatecode='008',smstemplatename='采购退货单系统预置短信模板',smstemplatecontent='我方退货@商品名称等@采购数量@基本计量单位已出库，请注意查收。',smsbeizhu='',flag='0',selected=1,templateid='8' where SMSBillType='6'
	update SMSBillType set smstemplatecode='009',smstemplatename='收款单系统预置短信模板',smstemplatecontent='您的款项已收到，原欠款@应收账款，本次付款@本币金额，请知悉。',smsbeizhu='',flag='0',selected=1,templateid='9' where SMSBillType='4'
	update SMSBillType set smstemplatecode='010',smstemplatename='销售发票开票系统预置短信模板',smstemplatecontent='我方本次开出发票@价税合计元，请知悉。@签名',smsbeizhu='',flag='0',selected=1,templateid='10' where SMSBillType='405'
	update SMSBillType set smstemplatecode='011',smstemplatename='付款单系统预置短信模板',smstemplatecontent='我方已付出款项，原应付余额@应付账款，本次付出@本币金额请注意查收。',smsbeizhu='',flag='0',selected=1,templateid='11' where SMSBillType='66'
	update SMSBillType set smstemplatecode='012',smstemplatename='采购暂估开票系统预置短信模板',smstemplatecontent='我方已收到发票@价税合计元，请注意查收。',smsbeizhu='',flag='0',selected=1,templateid='12' where SMSBillType='404'
	-- ********	处理 SMSBillType 预制信息	********
	
	
    update SMSBillType set [selected]=0
END
GO
--行业云模版
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSBillType' AND a.Name='HyyunSmsTemplateContent'
)
BEGIN
	ALTER TABLE SMSBillType 
		ADD HyyunSmsTemplateContent VARCHAR(MAX) NULL DEFAULT('')
END
GO 
UPDATE dbo.SMSBillType SET smstemplatecontent = REPLACE(smstemplatecontent,'@签名','')
GO



SET ANSI_NULLS ON


SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SMSConfig]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SMSConfig](
	    [id]                int identity(1,1) NOT NULL,
		[SMSUserCode]       [varchar](500)  NULL,
		[SMSUserPassword]   [varchar](500)  NULL,
		[SMSCompany]        [varchar](500)  NULL,
		[SMSCompanyname]    [varchar](500)  NULL,
		[apikey]            [varchar](500)  NULL
	) ON [PRIMARY]

	-- ********	处理 SMSConfig	********
	DELETE FROM SMSConfig
END
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--drop table SMSGroupTemplate

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SMSGroupTemplate]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SMSGroupTemplate](
	    id                int identity(1,1) NOT NULL,
		smstemplatecode       varchar(500)  NULL,
		smstemplatename       varchar(500)  NULL,
		stypeid               varchar(500)  NULL,--分支机构
		sfullname             varchar(max)  NULL,--分支机构名称
		templatesendtype      int NULL,--0 定时 1 保存即使发送 2 生日自动发送
		templatesendtimedate      varchar(200),--定时发送时间-年月日
		templatesendtime      varchar(200),--定时发送时间-时分秒
		templatesendtimedatebydatabegin  varchar(200),--自定义日期开始数据
		templatesendtimedatebydataend  varchar(200),--自定义日期结束数据
		templatesendtimetype  int NULL,--0 发送对账期内数据 1 发送自定义日期数据
		templatesenduser      int NULL,--0 客户 1 职员
		templatesendusermobile int NULL,--0 联系人1 1 联系人2 2 全部
	    smsbeizhu             varchar(max)  NULL,
		smstemplatecontent    varchar(max)  NULL
	) ON [PRIMARY]

	-- ********	处理 SMSGroupTemplate	********
	DELETE FROM SMSGroupTemplate
	
END
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

--drop table SMSGroupTemplateReceiveUsers

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SMSGroupTemplateReceiveUsers]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SMSGroupTemplateReceiveUsers](
	    id					int identity(1,1) NOT NULL,
	    tempid              int NULL,
		typeid				varchar(500)  NULL,
		usercode			varchar(500)  NULL,
		fullname			varchar(500)  NULL
	) ON [PRIMARY]

	-- ********	处理 SMSGroupTemplateReceiveUsers	********
	DELETE FROM SMSGroupTemplateReceiveUsers
	
END
GO



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SMSTemplate]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SMSTemplate](
	    id                int identity(1,1) NOT NULL,
		smstemplatecode       varchar(500)  NULL,
		smstemplatename       varchar(500)  NULL,
		smstemplatecontent    varchar(max)  NULL,
		smsbeizhu             varchar(max)  NULL,
		templatetype          int NULL,
		smsbilltype           int NULL
	) ON [PRIMARY]

	-- ********	处理 SMSTemplate	********
	DELETE FROM SMSTemplate
	
	-- ********	处理 SMSTemplate 预制信息	********

	INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('001','销售出库单系统预置短信模板001','您好，@单据编号,@商品名称等@销售数量@基本计量单位已发货出库，请注意查收。','','1','11')
		INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('002','销售出库单系统预置短信模板002','您好，@单据编号,@商品名称等@销售数量@基本计量单位已发货出库，请注意查收。','','1','402')
		INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('003','销售订单系统预置短信模板','您的订单@商品名称等@销售数量@基本计量单位已收到，正在准备发货，请知悉。','','1','300')
		INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('004','销售退库单系统预置短信模板','您好，销售退货@商品名称等@销售数量@基本计量单位已发货出库，请注意查收。','','1','45')
			INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('005','采购订单系统预置短信模板','我方订货@商品名称等@采购数量@基本计量单位，请知悉。','','1','301')
		INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('006','采购入库系统预置短信模板001','您发出的@商品名称等@采购数量@基本计量单位已到货。','','1','34')
			INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('007','采购入库系统预置短信模板002','您发出的@商品名称等@采购数量@基本计量单位已到货。','','1','400')
				INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('008','采购退货单系统预置短信模板','我方退货@商品名称等@采购数量@基本计量单位已出库，请注意查收。','','1','6')
				INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('009','收款单系统预置短信模板','您的款项已收到，原欠款@应收账款，本次付款@本币金额，请知悉。','','1','4')
		INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('010','销售发票开票系统预置短信模板','我方本次开出发票@价税合计元，请知悉。','','1','405')
	
			INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('011','付款单系统预置短信模板','我方已付出款项，原应付余额@应付账款，本次付出@本币金额请注意查收。','','1','66')
	
				INSERT INTO SMSTemplate(smstemplatecode,smstemplatename,smstemplatecontent,smsbeizhu,templatetype,smsbilltype)
	VALUES('012','采购暂估开票系统预置短信模板','我方已收到发票@价税合计元，请注意查收。','','1','404')
		
	
	-- ********	处理 SMSTemplate 预制信息	********
	
END
GO
--行业云模版
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSTemplate' AND a.Name='HyyunSmsTemplateContent'
)
BEGIN
	ALTER TABLE SMSTemplate 
		ADD HyyunSmsTemplateContent VARCHAR(MAX) NULL DEFAULT('')
END
GO
UPDATE SMSTemplate SET HyyunSmsTemplateContent = '' WHERE HyyunSmsTemplateContent IS NULL
GO
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSTemplate' AND a.Name='HyyunSmsTemplateId'
)
BEGIN
	ALTER TABLE SMSTemplate 
		ADD HyyunSmsTemplateId VARCHAR(100) NULL DEFAULT('0')
END
GO 
UPDATE dbo.SMSTemplate SET HyyunSmsTemplateId = 0 WHERE HyyunSmsTemplateId IS NULL
GO
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSTemplate' AND a.Name='HyyunSmsTemplateMsg'
)
BEGIN
	ALTER TABLE SMSTemplate 
		ADD HyyunSmsTemplateMsg VARCHAR(500) NULL DEFAULT('')
END
GO 
UPDATE SMSTemplate SET HyyunSmsTemplateMsg = '' WHERE HyyunSmsTemplateMsg IS NULL
GO
IF NOT EXISTS(
SELECT a.Name FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name='SMSTemplate' AND a.Name='HyyunSmsTemplateStatus'
)
BEGIN
	ALTER TABLE SMSTemplate 
		ADD HyyunSmsTemplateStatus VARCHAR(10) NULL DEFAULT('1')	--0已审核，1待审核，2已拒绝
END
GO 
UPDATE SMSTemplate SET HyyunSmsTemplateStatus = '1' WHERE HyyunSmsTemplateStatus IS NULL
GO
UPDATE SMSTemplate SET smstemplatecontent = REPLACE(smstemplatecontent,'@签名','')
GO



/****** Object:  Table [dbo].[ScratchPad]    Author:  tiancheng ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID = OBJECT_ID(N'ScratchPad') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ScratchPad](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UserID] [varchar](64) NOT NULL,	--操作员ID
	[SP_ID] [int] NOT NULL,				--便签ID
	[SP_X] [float] NOT NULL,			--便签横坐标
	[SP_Y] [float] NOT NULL,			--便签纵坐标
	[Width] [float] NOT NULL,			--便签宽度
	[Hight] [float] NOT NULL,			--便签高度
	[SP_Text] [varchar](2500) NOT NULL,			--便签内容
	[Style] [varchar](10) NOT NULL,		--便签风格
	[Opacity] [float] NOT NULL			--便签透明度
) ON [PRIMARY]
END


ALTER TABLE ScratchPad ALTER COLUMN [SP_Text] VARCHAR(MAX) NOT NULL

SET ANSI_PADDING OFF
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON


SET QUOTED_IDENTIFIER ON
--公告主表
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SysGongGao]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SysGongGao](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[SENDTIME] [datetime] NULL,
	[etypeid] [varchar](max) NULL,
	[TITLE] [varchar](1000) NULL,
	[CONTENT] [varchar](2000) NULL
PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO



/*
	作者：鲁大林
	时间：2013-07-24 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_SelfType' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Web_QueryCustomerDetail]') AND TYPE in (N'P', N'PC'))
		DROP PROC Web_QueryCustomerDetail;
	DROP TYPE TBType_SelfType;
END
GO

CREATE TYPE dbo.TBType_SelfType AS TABLE
(
	BillNumberId  	varchar(100),
	BillType VARCHAR(10)
) 
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



SET ANSI_NULLS ON



SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[tempbtypeinfo]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[tempbtypeinfo](
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ParId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint]  NULL,
		[sonnum] [int]  NULL,
		[soncount] [int]  NULL,
		[userid] [varchar](500),
		[BTypeLx] [varchar](50) NULL
	) ON [PRIMARY]

	-- ********	处理 tempptypeinfo	********
	DELETE FROM tempbtypeinfo
END
GO



SET ANSI_NULLS ON



SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[tempptypeinfo]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[tempptypeinfo](
		[typeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[ParId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		[leveal] [smallint]  NULL,
		[sonnum] [int]  NULL,
		[soncount] [int]  NULL,
		[userid] [varchar](500)
	) ON [PRIMARY]

	-- ********	处理 tempptypeinfo	********
	DELETE FROM tempptypeinfo
END
GO




/****** 
		Object: Table [dbo].[UFO_DefineFucType]    
		Script Date: 07/25/2012 16:54:16 
		Autor: 张陈仁
******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[UFO_DefineFucType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

	CREATE TABLE [dbo].[UFO_DefineFucType](
		[ID] [int] NOT NULL,
		[TypeName] [varchar](50) NOT NULL,
		[OrderBy] [int] NULL
	) ON [PRIMARY]

	INSERT INTO UFO_DefineFucType (ID,TypeName,OrderBy) VALUES (2,'日期函数',1)
	INSERT INTO UFO_DefineFucType (ID,TypeName,OrderBy) VALUES (3,'查询条件函数',2)
	INSERT INTO UFO_DefineFucType (ID,TypeName,OrderBy) VALUES (1,'总账函数',3)
END
IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_DefineFucType WHERE ID=4 AND TypeName='业务函数')	
	BEGIN
		INSERT INTO UFO_DefineFucType (ID,TypeName,OrderBy) VALUES (4,'业务函数',4)
	END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_DefineFucType WHERE ID=5 AND TypeName='业务单据函数')	
	BEGIN
		INSERT INTO UFO_DefineFucType (ID,TypeName,OrderBy) VALUES (5,'业务单据函数',5)
	END
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 
		表名: UFO报表自定义公式    
		时间: 06/08/2011 10:37:38
		作者：张陈仁 
******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[UFO_DefineFunctions]')
                    AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
    BEGIN
        DROP TABLE [UFO_DefineFunctions]
    END
	
CREATE TABLE [dbo].[UFO_DefineFunctions]
    (
      [ID] [int] IDENTITY(1, 1)
                 NOT NULL ,
      [Code] [varchar](30) NOT NULL ,
      [Name] [varchar](100) NOT NULL ,
      [Fuction] [varchar](300) NULL ,
      [Format] [varchar](400) NULL ,
      [Description] [varchar](300) NULL ,
      [Demo] [varchar](500) NOT NULL ,
      [ExampleRemark] [varchar](200) NULL ,
      [Typeid] [int] NOT NULL ,
      CONSTRAINT [PK_UFO_DEFINEFUNCTIONS] PRIMARY KEY CLUSTERED ( [ID] ASC )
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
    )
ON  [PRIMARY]
        
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'QC' ,
          N'年初余额' ,
          N'取指定科目和期间的上月期末数作为年初余额' ,
          N'QC("科目编码","币种","年","月","科目方向","部门=部门编号%职员=职员编号%往来单位=往来单位编号%分支机构=分支机构编号%")' ,
          N'根据明细科目取余额若明细科目启用辅助核算，根据勾选的辅助核算取辅助明细的余额方向为空时，代表借贷方余额都取。取值代表取本币值还是原币值' ,
          N'QC(String AUserCode,String Cid,String FYear,String FPeriod,[String Fdc],[String Aux])' ,
          NULL ,
          1
                
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'QM' ,
          N'期末余额函数' ,
          N'取指定科目和期间的期末余额' ,
          N'QM("科目编码","币种","年","月","科目方向","部门=部门编号%职员=职员编号%往来单位=往来单位编号%分支机构=分支机构编号%")' ,
          NULL ,
          N'QM(String AUserCode,String Cid,String FYear,String FPeriod,[String Fdc],[String Aux])' ,
          NULL ,
          1
                
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'TYear' ,
          N'年' ,
          N'取登陆时间对应的自然年份。' ,
          N'TYear()' ,
          N'无参数，返回值为当前用户登陆时间对应的自然年份。' ,
          N'TYear()' ,
          NULL ,
          2
                
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'TMoth' ,
          N'月' ,
          N'取登陆时间对应的自然月份。' ,
          N'TMoth()' ,
          N'无参数，返回值为当前用户登陆时间对应的自然月份。' ,
          N'TMoth()' ,
          NULL ,
          2
                
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'TDay' ,
          N'天' ,
          N'取登陆时间对应的自然月份中的第几天' ,
          N'TDay()' ,
          N'无参数，返回值为当前用户登陆时间对应的自然月份中的第几天。' ,
          N'TDay()' ,
          NULL ,
          2
                
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'TDate' ,
          N' 日期' ,
          N'取登陆日期' ,
          N'TDate()' ,
          N'无参数，返回值为当前用户登陆日期。' ,
          N'TDate()' ,
          NULL ,
          2
                
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'QueryAYear' ,
          N'会计年度' ,
          N'取查询条件中的会计年度' ,
          N'QueryAYear()' ,
          N'无参数，返回值为查询窗口中录入的会计月。' ,
          N'QueryAYear()' ,
          NULL ,
          3
                
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'QueryAMonth' ,
          N'会计期间' ,
          N'取查询条件中的会计月。' ,
          N'QueryAMonth()' ,
          N'无参数，返回值为查询窗口中录入的会计月' ,
          N'QueryAMonth()' ,
          NULL ,
          3
                
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'QueryCom()' ,
          N'分支机构' ,
          N'取查询条件中的单位。' ,
          N'QueryCom()' ,
          N'无参数，返回值为查询窗口中录入的单位。' ,
          N'QueryCom()' ,
          NULL ,
          3
                
        )
	--INSERT [dbo].[UFO_DefineFunctions] ([Code], [Name], [Fuction], [Format], [Description], [Demo], [ExampleRemark], [Typeid]) VALUES (N'QueryPosting()', N'包含未记账凭证', N'取查询条件中的“包含未记账凭证"。', N'QueryPosting()', N'无参数，返回值为查询窗口中录入的“包含未记账凭证"的值，即“是"或“否"。', N'QueryPosting()', NULL, 3)
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'XFS' ,
          N'当期发生额' ,
          N'取指定科目和期间的借方发生额或贷方发生额。' ,
          N'XFS("科目编码","币种","年","月","科目方向","部门=部门编号%职员=职员编号%往来单位=往来单位编号%分支机构=分支机构编号%")' ,
          N'可以按摘要完全匹配和摘要包含匹配取数' ,
          N'XFS(String AUserCode,String Cid,String FYear,String FPeriod,[String Fdc],[String Aux])' ,
          NULL ,
          1
                
        )
	--INSERT [dbo].[UFO_DefineFunctions] ([Code], [Name], [Fuction], [Format], [Description], [Demo], [ExampleRemark], [Typeid]) VALUES (N'JE', N'净额', N'取科目在指定期间当期借、贷方发生的差额。', N'JE("科目编码","币种","年","月")', NULL, N'JE(String AUserCode,String Cid,String FYear,String FPeriod)', NULL, 1)
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'XJLL' ,
          N'现金流量累计数' ,
          N'指从本年度第1期间开始至当前查询期间或指定期间内，现金流量项目所发生的累计数' ,
          N'XJLL("年","月","开始日期","结束日期","现金流量项目")' ,
          NULL ,
          N'XJLL(String FYear,String FPeriod,String StartDate,String EndDate,String lx)' ,
          NULL ,
          1
        )
INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'LFS' ,
          N'累计发生额' ,
          N'根据方向，取某科目截止到指定期间的累计借方发生额或累计贷方发生额。' ,
          N'LFS("科目编码","币种","年","月","科目方向","部门=部门编号%职员=职员编号%往来单位=往来单位编号%分支机构=分支机构编号%")' ,
          N'从本年度第一个会计期间到当前日期或当前期间累计发生额' ,
          N'LFS(String AUserCode,String Cid,String FYear,String FPeriod,[String Fdc],[String Aux])' ,
          NULL ,
          1
                
        )
        
 INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'XMQC' ,
          N'项目期初余额' ,
          N'取指定项目和开始时间的项目余额' ,
          N'XMQC("项目编码","开始时间","结束时间","币种")' ,
          N'根据所选项目取项目指定开始时间点的项目余额，当开始时间为默认时取报表查询时查询条件中开始时间' ,
          N'XMQC(String UserCode,String BeginDate,String EndDate,String Cid)' ,
          NULL ,
          4      
        )       
 INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'XMQM' ,
          N'项目期末余额' ,
          N'取指定项目和结束时间的项目余额' ,
          N'XMQM("项目编码","开始时间","结束时间","币种")' ,
          N'根据所选项目取项目指定结束时间点的项目余额，当结束时间为默认时取报表查询时查询条件中结束时间' ,
          N'XMQM(String UserCode,String BeginDate,String EndDate,String Cid)' ,
          NULL ,
          4      
        )
 INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'XMFS' ,
          N'项目发生额' ,
          N'取指定项目在开始时间至结束时间的项目发生额' ,
          N'XMFS("项目编码","开始时间","结束时间","币种")' ,
          N'根据所选项目取项目开始至结束时间点的项目发生额，当开始与结束时间为默认时取报表查询时查询条件中的开始和结束时间' ,
          N'XMFS(String UserCode,String BeginDate,String EndDate,String Cid)' ,
          NULL ,
          4      
        )
        
        
---9.4总账添加

INSERT  [dbo].[UFO_DefineFunctions]
        ( [Code] ,
          [Name] ,
          [Fuction] ,
          [Format] ,
          [Description] ,
          [Demo] ,
          [ExampleRemark] ,
          [Typeid]
                
        )
VALUES  ( N'XJFS' ,
          N'现金流量发生额' ,
          N'指查询当前期间或指定期间的现金流量项目本期的发生数据' ,
          N'XJFS("年","月","开始日期","结束日期","现金流量项目")' ,
          NULL ,
          N'XJFS(String FYear,String FPeriod,String StartDate,String EndDate,String lx)' ,
          NULL ,
          1
        )
GO

---业务类函数        
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'BJD' , N'报价单' , N'指定条件的发生额' , N'BJD("取数类型")' , N'根据所选条件，查询报价单的发生额' , N'BJD(String typeId)' ,NULL ,5)
GO
   
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'XSDD' , N'销售订单' , N'指定条件的发生额' , N'XSDD("取数类型")' , N'根据所选条件，查询销售订单的发生额' , N'XSDD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'QGD' , N'请购单' , N'指定条件的发生额' , N'QGD("取数类型")' , N'根据所选条件，查询请购单的发生额' , N'QGD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'XJD' , N'询价单' , N'指定条件的发生额' , N'XJD("取数类型")' , N'根据所选条件，查询询价单的发生额' , N'XJD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'CGDD' , N'采购订单' , N'指定条件的发生额' , N'CGDD("取数类型")' , N'根据所选条件，查询采购订单的发生额' , N'CGDD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'LSD' , N'零售单' , N'指定条件的发生额' , N'LSD("取数类型")' , N'根据所选条件，查询零售单的发生额' , N'LSD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'LSTHD' , N'零售退货单' , N'指定条件的发生额' , N'LSTHD("取数类型")' , N'根据所选条件，查询零售退货单的发生额' , N'LSTHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'XSCKD' , N'销售出库单' , N'指定条件的发生额' , N'XSCKD("取数类型")' , N'根据所选条件，查询销售出库单的发生额' , N'XSCKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'XSTHD' , N'销售退货单' , N'指定条件的发生额' , N'XSTHD("取数类型")' , N'根据所选条件，查询销售退货单的发生额' , N'XSTHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'XSHHD' , N'销售换货单' , N'指定条件的发生额' , N'XSHHD("取数类型")' , N'根据所选条件，查询销售换货单的发生额' , N'XSHHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'ZSD' , N'赠送单' , N'指定条件的发生额' , N'ZSD("取数类型")' , N'根据所选条件，查询赠送单的发生额' , N'ZSD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'WTFHD' , N'委托代销发货单' , N'指定条件的发生额' , N'WTFHD("取数类型")' , N'根据所选条件，查询委托代销发货单的发生额' , N'WTFHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'WTTHD' , N'委托代销退货单' , N'指定条件的发生额' , N'WTTHD("取数类型")' , N'根据所选条件，查询委托代销退货单的发生额' , N'WTTHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'WTJSD' , N'委托代销结算单' , N'指定条件的发生额' , N'WTJSD("取数类型")' , N'根据所选条件，查询委托代销结算单的发生额' , N'WTJSD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'CGRKD' , N'采购入库单' , N'指定条件的发生额' , N'CGRKD("取数类型")' , N'根据所选条件，查询采购入库单的发生额' , N'CGRKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'CGTHD' , N'采购退货单' , N'指定条件的发生额' , N'CGTHD("取数类型")' , N'根据所选条件，查询采购退货单的发生额' , N'CGTHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'CGHHD' , N'采购换货单' , N'指定条件的发生额' , N'CGHHD("取数类型")' , N'根据所选条件，查询采购换货单的发生额' , N'CGHHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'HZD' , N'获赠单' , N'指定条件的发生额' , N'HZD("取数类型")' , N'根据所选条件，查询获赠单的发生额' , N'HZD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'STSHD' , N'受托代销收货单' , N'指定条件的发生额' , N'STSHD("取数类型")' , N'根据所选条件，查询受托代销收货单的发生额' , N'STSHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'STTHD' , N'受托代销退货单' , N'指定条件的发生额' , N'STTHD("取数类型")' , N'根据所选条件，查询受托代销退货单的发生额' , N'STTHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'STJSD' , N'受托代销结算单' , N'指定条件的发生额' , N'STJSD("取数类型")' , N'根据所选条件，查询受托代销结算单的发生额' , N'STJSD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'STTJD' , N'受托代销调价单' , N'指定条件的发生额' , N'STTJD("取数类型")' , N'根据所选条件，查询受托代销调价单的发生额' , N'STTJD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'TJDBD' , N'同价调拨单' , N'指定条件的发生额' , N'TJDBD("取数类型")' , N'根据所选条件，查询同价调拨单的发生额' , N'TJDBD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'BJDBD' , N'变价调拨单' , N'指定条件的发生额' , N'BJDBD("取数类型")' , N'根据所选条件，查询变价调拨单的发生额' , N'BJDBD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'FZJGCKD' , N'分支机构调拨出库单' , N'指定条件的发生额' , N'FZJGCKD("取数类型")' , N'根据所选条件，查询分支机构调拨出库单的发生额' , N'FZJGCKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'FZJGRKD' , N'分支机构调拨入库单' , N'指定条件的发生额' , N'FZJGRKD("取数类型")' , N'根据所选条件，查询分支机构调拨入库单的发生额' , N'FZJGRKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'QTRKD' , N'其他入库单' , N'指定条件的发生额' , N'QTRKD("取数类型")' , N'根据所选条件，查询其他入库单的发生额' , N'QTRKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'QTCKD' , N'其他出库单' , N'指定条件的发生额' , N'QTCKD("取数类型")' , N'根据所选条件，查询其他出库单的发生额' , N'QTCKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'BSD' , N'报损单' , N'指定条件的发生额' , N'BSD("取数类型")' , N'根据所选条件，查询报损单的发生额' , N'BSD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'BYD' , N'报溢单' , N'指定条件的发生额' , N'BYD("取数类型")' , N'根据所选条件，查询报溢单的发生额' , N'BYD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'SCCZD' , N'生产拆装单' , N'指定条件的发生额' , N'SCCZD("取数类型")' , N'根据所选条件，查询生产拆装单的发生额' , N'SCCZD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'WXD' , N'维修单' , N'指定条件的发生额' , N'WXD("取数类型")' , N'根据所选条件，查询维修单的发生额' , N'WXD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'WXQJD' , N'维修取件单' , N'指定条件的发生额' , N'WXQJD("取数类型")' , N'根据所选条件，查询维修取件单的发生额' , N'WXQJD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'ZJGHD' , N'整机更换单' , N'指定条件的发生额' , N'ZJGHD("取数类型")' , N'根据所选条件，查询整机更换单的发生额' , N'ZJGHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'SXFHD' , N'送修返回单' , N'指定条件的发生额' , N'SXFHD("取数类型")' , N'根据所选条件，查询送修返回单的发生额' , N'SXFHD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'SMWXD' , N'上门维修单' , N'指定条件的发生额' , N'SMWXD("取数类型")' , N'根据所选条件，查询上门维修单的发生额' , N'SMWXD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'WXPDR' , N'维修品调入单' , N'指定条件的发生额' , N'WXPDR("取数类型")' , N'根据所选条件，查询维修品调入的发生额' , N'WXPDR(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'WXPDC' , N'维修品调出单' , N'指定条件的发生额' , N'WXPDC("取数类型")' , N'根据所选条件，查询维修品调出的发生额' , N'WXPDC(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'YSZJD' , N'应收增加单' , N'指定条件的发生额' , N'YSZJD("取数类型")' , N'根据所选条件，查询应收增加单的发生额' , N'YSZJD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'YSJSD' , N'应收减少单' , N'指定条件的发生额' , N'YSJSD("取数类型")' , N'根据所选条件，查询应收减少单的发生额' , N'YSJSD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'YFZJD' , N'应付增加单' , N'指定条件的发生额' , N'YFZJD("取数类型")' , N'根据所选条件，查询应付增加单的发生额' , N'YFZJD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'YFJSD' , N'应付减少单' , N'指定条件的发生额' , N'YFJSD("取数类型")' , N'根据所选条件，查询应付减少单的发生额' , N'YFJSD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'SKD' , N'收款单' , N'指定条件的发生额' , N'SKD("取数类型")' , N'根据所选条件，查询收款单的发生额' , N'SKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'YSKD' , N'预收款单' , N'指定条件的发生额' , N'YSKD("取数类型")' , N'根据所选条件，查询预收款单的发生额' , N'YSKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'FKD' , N'付款单' , N'指定条件的发生额' , N'FKD("取数类型")' , N'根据所选条件，查询付款单的发生额' , N'FKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'YFKD' , N'预付款单' , N'指定条件的发生额' , N'YFKD("取数类型")' , N'根据所选条件，查询预付款单的发生额' , N'YFKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'FLZXD' , N'返利执行单' , N'指定条件的发生额' , N'FLZXD("取数类型")' , N'根据所选条件，查询返利执行单的发生额' , N'FLZXD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'HLZXD' , N'获利执行单' , N'指定条件的发生额' , N'HLZXD("取数类型")' , N'根据所选条件，查询获利执行单的发生额' , N'HLZXD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'JBZXD' , N'价保执行单' , N'指定条件的发生额' , N'JBZXD("取数类型")' , N'根据所选条件，查询价保执行单的发生额' , N'JBZXD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'HDJB' , N'获得价保' , N'指定条件的发生额' , N'HDJB("取数类型")' , N'根据所选条件，查询获得价保的发生额' , N'HDJB(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'FYD' , N'费用单' , N'指定条件的发生额' , N'FYD("取数类型")' , N'根据所选条件，查询费用单的发生额' , N'FYD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'XJFYD' , N'现金费用单' , N'指定条件的发生额' , N'XJFYD("取数类型")' , N'根据所选条件，查询现金费用单的发生额' , N'XJFYD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'ZKD' , N'转款单' , N'指定条件的发生额' , N'ZKD("取数类型")' , N'根据所选条件，查询转款单的发生额' , N'ZKD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'QTSRD' , N'其他收入单' , N'指定条件的发生额' , N'QTSRD("取数类型")' , N'根据所选条件，查询其他收入单的发生额' , N'QTSRD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'DTFYFS' , N'待摊费用发生' , N'指定条件的发生额' , N'DTFYFS("取数类型")' , N'根据所选条件，查询待摊费用发生的发生额' , N'DTFYFS(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'DTFYTX' , N'待摊费用摊销' , N'指定条件的发生额' , N'DTFYTX("取数类型")' , N'根据所选条件，查询待摊费用摊销的发生额' , N'DTFYTX(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'ZCGMD' , N'固定资产(项目)购买单' , N'指定条件的发生额' , N'ZCGMD("取数类型")' , N'根据所选条件，查询固定资产购买单-项目的发生额' , N'ZCGMD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'ZCBMD' , N'固定资产(项目)变卖单' , N'指定条件的发生额' , N'ZCBMD("取数类型")' , N'根据所选条件，查询固定资产变卖单-项目的发生额' , N'ZCBMD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'ZCZJD' , N'固定资产(项目)折旧单' , N'指定条件的发生额' , N'ZCZJD("取数类型")' , N'根据所选条件，查询固定资产折旧单-项目的发生额' , N'ZCZJD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'CBTJD' , N'成本调价单' , N'指定条件的发生额' , N'CBTJD("取数类型")' , N'根据所选条件，查询成本调价单的发生额' , N'CBTJD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'YWPZ' , N'业务凭证' , N'指定条件的发生额' , N'YWPZ("取数类型")' , N'根据所选条件，查询业务凭证的发生额' , N'YWPZ(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'CGFYFT' , N'采购费用分摊单' , N'指定条件的发生额' , N'CGFYFT("取数类型")' , N'根据所选条件，查询采购费用分摊的发生额' , N'CGFYFT(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'XSFYFT' , N'销售费用分摊单' , N'指定条件的发生额' , N'XSFYFT("取数类型")' , N'根据所选条件，查询销售费用分摊的发生额' , N'XSFYFT(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'HYZCD' , N'会员储值充值单' , N'指定条件的发生额' , N'HYZCD("取数类型")' , N'根据所选条件，查询会员储值充值单的发生额' , N'HYZCD(String typeId)' ,NULL ,5)
GO
INSERT  [dbo].[UFO_DefineFunctions]        
		( [Code] ,[Name] ,[Fuction] ,[Format] ,[Description] ,[Demo] ,[ExampleRemark] ,[Typeid])
VALUES  ( N'JFDHD' , N'积分兑换单' , N'指定条件的发生额' , N'JFDHD("取数类型")' , N'根据所选条件，查询积分兑换单的发生额' , N'JFDHD(String typeId)' ,NULL ,5)
GO
--增加【年初借方余额（NCJ）、年初贷方余额（NCD）期末借方余额（QMJ）、期末贷方余额（QMD）】四个函数：  
INSERT  [dbo].[UFO_DefineFunctions]
(
	Code,
	Name,
	Fuction,
	Format,
	Description,
	Demo,
	ExampleRemark,
	Typeid
)
VALUES  
( 
	N'NCJ' ,
	N'年初借方余额' ,
	N'取指定科目的年初借方数据' ,
	N'NCJ("科目编码","币种","年","月","科目方向","部门=部门编号%职员=职员编号%往来单位=往来单位编号%分支机构=分支机构编号%")' ,
	N'科目在指定条件下的年期初借方余额' ,
	N'NCJ(String AUserCode,String Cid,String FYear,String FPeriod,[String Fdc],[String Aux])' ,
	NULL ,
	1
) 
GO
--年初贷方余额（QCD）
INSERT  [dbo].[UFO_DefineFunctions]
(
	Code,
	Name,
	Fuction,
	Format,
	Description,
	Demo,
	ExampleRemark,
	Typeid
)
VALUES  
( 
	N'NCD' ,
	N'年初贷方余额' ,
	N'取指定科目的年初贷方余额' ,
	N'NCD("科目编码","币种","年","月","科目方向","部门=部门编号%职员=职员编号%往来单位=往来单位编号%分支机构=分支机构编号%")' ,
	N'科目在指定条件下的年期初贷方余额' ,
	N'NCD(String AUserCode,String Cid,String FYear,String FPeriod,[String Fdc],[String Aux])' ,
	NULL ,
	1
) 
GO
--期末借方余额（QMJ）
INSERT  [dbo].[UFO_DefineFunctions]
(
	Code,
	Name,
	Fuction,
	Format,
	Description,
	Demo,
	ExampleRemark,
	Typeid
)
VALUES  
( 
	N'QMJ' ,
	N'期末借方余额' ,
	N'取指定科目的期末借方余额' ,
	N'QMJ("科目编码","币种","年","月","科目方向","部门=部门编号%职员=职员编号%往来单位=往来单位编号%分支机构=分支机构编号%")' ,
	N'科目在指定查询条件下对应期间期末借方余额数据' ,
	N'QMJ(String AUserCode,String Cid,String FYear,String FPeriod,[String Fdc],[String Aux])' ,
	NULL ,
	1
) 
GO
--期末贷方余额（QMD）
INSERT  [dbo].[UFO_DefineFunctions]
(
	Code,
	Name,
	Fuction,
	Format,
	Description,
	Demo,
	ExampleRemark,
	Typeid
)
VALUES  
( 
	N'QMD' ,
	N'期末贷方余额' ,
	N'取指定科目的期末贷方额' ,
	N'QMD("科目编码","币种","年","月","科目方向","部门=部门编号%职员=职员编号%往来单位=往来单位编号%分支机构=分支机构编号%")' ,
	N'科目在指定查询条件下对应期间期末贷方余额数据' ,
	N'QMD(String AUserCode,String Cid,String FYear,String FPeriod,[String Fdc],[String Aux])' ,
	NULL ,
	1
) 
GO



------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE name='UFO_OpenFile' AND TYPE='U')
	DROP TABLE UFO_OpenFile
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE name='UFO_OpenFile' AND TYPE='U')
	BEGIN
		CREATE TABLE UFO_OpenFile(
			nId					INT IDENTITY(1,1),
			STypeID				VARCHAR(MAX) NOT NULL,			--分支机构ID
			AtypeID				VARCHAR(50) NOT NULL,			--项目/科目ID
			BeginDate			DATETIME NULL,					--开始时间
			EndDate				DATETIME NULL,					--结束时间
			Cid					INT NOT NULL DEFAULT(-1),		--币种
			Fyear				INT NULL,						--年份
			FPeriod				INT NULL,						--期间
			ShowNotPost			INT NULL,						--包含未记账凭证
			CreatedBy			VARCHAR(50) NOT NULL,			--创建人
			CreatedDate			DATETIME DEFAULT(GETDATE()),	--创建时间
			[Type]				INT,							--类型, 1：总账 2业务
			Assets				INT DEFAULT(0),					--1 卡片  0项目
			FunctionName		VARCHAR(20)						--公式名称
		)
	END
GO

------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 
		表名:UFO分类    
		时间:2012-6-8
		作者：张陈仁 
******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[UFO_ReportCategory]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[UFO_ReportCategory](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TypeId] [varchar](50) NOT NULL,
	[Name] [varchar](200) NOT NULL,
	[ParentTypeId] [varchar](50) NULL,
	[SysType] [int] NULL,
	[IsShares] [int] NULL,
	[etypeid] [VARCHAR](50) NULL
	) ON [PRIMARY]
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'00001', N'总账', N'root', 0, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000100001', N'系统模板', N'00001', 0, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000100002', N'个人模板', N'00001', 0, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000010000200002', N'利润表', N'0000100002', 0, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000010000200003', N'现金流量表', N'0000100002', 0, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000010000200001', N'资产负债表', N'0000100002', 0, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'00001', N'总账', N'root', 1, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000100001', N'系统模板', N'00001', 1, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000010000100001', N'利润表', N'0000100001', 1, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000010000100002', N'现金流量表', N'0000100001', 1, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000010000100003', N'资产负债表', N'0000100001', 1, 1)
	INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000100002', N'个人模板', N'00001', 1, 1)
END
GO
-- date:2013-05-29 by:glj
IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_ReportCategory WHERE Name='业务' AND SysType=0 AND ParentTypeId='root')
	BEGIN
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'00002', N'业务', N'root', 0, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000200001', N'系统模板', N'00002', 0, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000200002', N'个人模板', N'00002', 0, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000020000200001',N'项目余额表',N'0000200002',0, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000020000200002',N'项目经营表',N'0000200002',0, 1)
		
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'00002',N'业务',N'root', 1, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000200001',N'系统模板', N'00002',1, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000200002',N'个人模板', N'00002', 1, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000020000100001',N'项目余额表',N'0000200001',1, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'000020000100002',N'项目经营表',N'0000200001',1, 1)
	END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_ReportCategory WHERE Name='业务单据' AND SysType=0 AND ParentTypeId='root')
	BEGIN
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'00003', N'业务单据', N'root', 0, 1)
		--INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000300001', N'系统模板', N'00003', 0, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000300002', N'个人模板', N'00003', 0, 1)
		
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'00003',N'业务单据',N'root', 1, 1)
		--INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000300001',N'系统模板', N'00003',1, 1)
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( N'0000300002',N'个人模板', N'00003', 1, 1)
	END
GO
IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_ReportCategory WHERE Name='年度损益统计表' AND etypeid IS NULL  )
	BEGIN
		DECLARE @TypeID	VARCHAR(50),
				@ID		INT,
				@I		INT=0,
				@Ret	VARCHAR(5)=''
		SELECT @TypeID=MAX(TypeId)  FROM UFO_ReportCategory WHERE SysType=1 AND TypeId LIKE '0000100001%'
		SET @ID=CAST(SUBSTRING(@TypeID,LEN(@TypeID)-5,5) AS INT)+1
		WHILE(@I<5-LEN(@ID))
			BEGIN
				SET @Ret+='0'
				++@I
			END
			
		SET @TypeID=REPLACE(@TypeID,SUBSTRING(@TypeID,LEN(@TypeID)-5,5),@Ret+CAST(@ID AS VARCHAR(5)))
			
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( @TypeID, N'年度损益统计表', N'0000100001', 1, 1)
		SELECT @TypeID=MAX(TypeId)  FROM UFO_ReportCategory WHERE SysType=0 AND TypeId LIKE '0000100002%'
		SET @ID=CAST(SUBSTRING(@TypeID,LEN(@TypeID)-5,5) AS INT)+1
		WHILE(@I<5-LEN(@ID))
			BEGIN
				SET @Ret+='0'
				++@I
			END	
		SET @TypeID=REPLACE(@TypeID,SUBSTRING(@TypeID,LEN(@TypeID)-5,5),@Ret+CAST(@ID AS VARCHAR(5)))
		INSERT [dbo].[UFO_ReportCategory] ([TypeId], [Name], [ParentTypeId], [SysType],[IsShares]) VALUES ( @TypeID, N'年度损益统计表', N'0000100002', 0, 1)
	END
GO
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 



/****** 
		表名:  UFO报表模板
		时间: 06/08/2012 16:16:34 
******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[UFO_Temple]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[UFO_Temple](
		[ID] [int] IDENTITY(1,1) NOT NULL,--自定增长列
		[TempleName] [varchar](200) NOT NULL,--模板/报表名称
		[ModeID] [int] NULL,--所属模块
		[CreateEtypeID] [varchar](50) NULL,--创建人id
		[CreateTime] [datetime] NULL,--创建时间
		[UpdateEtypeID] [varchar](50) NULL,--更新人id
		[UpdateTime] [datetime] NULL,--更新时间
		[TempleContent] [text] NULL,--模板样式内容
		[IsVisible] [int] NOT NULL,--是否显示
		[TempleCategoryID] [varchar](50) NULL,--分类id
		[CreateEtypeName] [varchar](200) NULL,--创建人名称
		[UpdateEtypeName] [varchar](50) NULL,--更新人名称
		[ClassId] [int] NULL,--1：系统模板 2：个人模板 3：个人报表
		[Stypeid] [varchar](50) NULL,--报表查询条件：分支机构ID
		[Fyear] [varchar](20) NULL,--报表查询条件：年
		[Fperiod] [int] NULL,--报表查询条件：期间
		[ShownotPost] [int] NULL,--是否包含凭证
		[IsShare] [int] NULL,--是否分享
		[ReMarks] [varchar](100) NULL,--备注
		[TStypeid] [VARCHAR](50) NULL,--模板设计分支机构ID
	 CONSTRAINT [PK_UFO_TEMPLE] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
	
	INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'利润表(新会计准则)', 1, N'00001',  N'000000000000000000000000000000000000000000000000000000000000000000000000000000007461702e323030300600040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001800e5027003cd0460030d008f017701d40105023b0068010101000000000000000000000000000000000000000000000000a803000086000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000071070000810700008d070000d104000017000000ec04000000000000000000000000000000000000cc0000001f8b080000000000020b6361606090006246242ccc80095e3033303031f048b36291db02c42c500c030148e62d03eb85e0562001e482713d2344ad2ed40dcc48fa7590f44f84ea1507e2ffff19080264bf3023b15990e471811fc81cfa6960837a9195548d30db80e1cd854d0ea7f328d2c0448cb328f20f3de3877d98f9878808a5d83f0640fd4a4a1073884a3eb4d54095f881da467c70d34ec3a87f46fd33ea9f51ff8cfa67d43fa3fe19f5cfa87f46fd33ea9f51ff8cfa67d43f83c53fcc0486e10096a8d1b45b140000cd0200001f8b080000000000020bed943168135118c73f6b2b55abb6a543058550755010d30ce226080a3a083a38083a38383858cce0e020ea50d0c1c1c1c141b81cb649449bb4dec5dca59794c4985ebca6b94b1368bab444874a424a88a59516bf77f7aee4da9848415c7c10feeff7eeff7defbdfbbe4b2b00f4e2efd10ea83bb803f5d70f771a7a8e721bf51dc73cc12e806297c169e40ba84fa8ef620bc025d441ca69e4cba8cf283fde097015f539e583ad00d7505f50f6235f477d69e66b03b889fa8af212f22dd4d794e77701dc4675517eda0e70077588f295dd007751bda61fd989fade3c5f8ff5ded53d00f75147292b7b011ea0f2946f74003c4415281fdb678dbfb789951ab6c3fff16f47f9ec00f64f0be9b32260e740e467a282532c3ad86ce27cbc6277d02747ce3b9d034eec1b0b1846eecd94c80a192f607340aa6433462c0ced24b3149f1d2ff3251d265314b06d40151997e655397926f1dd9ab6534f6bb385aaac401c63937ec9eae8a10e731057d2174883efe378486bec4dadcaf9405a8b367605e722c5e6aed1f8d4d25657ef26574e1e5d0d55b35cb22c0f5b9d274c67486385e0db8c1cca67397f811f9167d46fac9b04a899be937d5f4a13d3acc71a7bd4ba8bc2e7e43f883a658d8a17b2d3acc06726bc9a375e5139411152c68c8b9919c146bef875a35aa4455877783959c62dd8777dc2a77abb749b15d48c0a2a0b5babdcbda9caca427678ec87d573887a8c63063e4f2cf323e46d7e18ca46f5b7495e42628d719163e5e6f8927134326b74bcfd355b2757b868d2075b8a482e9d8c312e4934ae2c89cd2e4db24e7d655cd1707052af84a0df9175ab22eb1157fc92f9802ef3ebac27c5c8cac6724db6bf39adff95f758b0e6ab362ee6b0f73b628b7ca2df119f0d15b6bf64f94fe8d021b618c98b6bfac29926f566ddbf7de2d9566b3b30a65e4a4934b693446253338c8ff132fe8dba9f6e70ce26a1b5e31700b818ab8f080000170000001f8b080000000000020b636080000069df226508000000810200001f8b080000000000020bed95cd6b134114c0275dd37cecd688f52c610f921a177636c92639d9ec805e928256504f12ed52834916b64ae92dfe1382b71c3de4e2454104a188045aaa4829d2a35841f190b397f8de3691254c3a23f4e021036f67e6bd79f39bf7e6ed2e21b3366bff47dbd9db3d3ac99e245ffb11c11ee740ce8cf652a17fbdbdb377efba63e5a885ea3787c7ea77bddda3913a0ad3655caee120b43e30a043600879c4615e69aebb7ea3dec645151834d5f120ed34eb0f1e697fa72b75dff7365330bfd568b91be91577337dd36bd5dbf3a05add6addf79a0918dd6eb4d7d74036505df3d65cbf1d39b5cc76aee2f33bf91d082111827b3f532fc7114d2a4f970989fdf3ae89513f1c0ec9603020dd6e97fcfaf185f45e3c2743a4763a64ff537f56d8b346d22073a3f793041548c825903bd75633ba5da454bfa2bffc7c7000ddfb9ff0d8dfc651afff113a7d49e17856a53c9199e23273a69899e232459ec83c1bf2bc08e2140cc7369ca2e1940ca76c38d404a159875a203985e3c10a06b30d563458c96065838107030f061e8ce690b1c08d8b4ae472811b1795c8a5c6674ae452e3332572a9f26b4682a9f26b468299e4326d33276426b94c91e75ce87b3ac9b484ccc414a62564c6a730c5b98d4f618a731be332f312b98d71997989dcce873c6b21e6c9a7cd8e9789af601250950354a5001841941b8129178159105f68941b812917810880115c0801f0261d0adf425a563826062646cb385542267cb76e3c71fd2de6b532c1a1c3d6ccd85ab9ebd6fdcc52160ef2aaaf678f7535affdf8212a3f1cbefda6e37916b9755892a8fd456e1d96246aff7cc8530d7290871f00fc1ca8ad70cc0ccc0ccc8cdadac42ff50f2a271bc9ba0d00000c00000030010000cc000000000000000800000000020000cd0200000900000005000000b5da31d2b3', 1, N'0000100001', N'超级用户', 1,1)
	INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'现金流量表(新会计准则)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)
    INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'资产负债表(新会计准则)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)
END
GO
--增加列
IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='UFO_Temple' AND a.Name='BeginDate'
)
BEGIN
	ALTER TABLE UFO_Temple 
		ADD BeginDate DATETIME NULL
END

GO

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='UFO_Temple' AND a.Name='EndDate'
)
BEGIN
	ALTER TABLE UFO_Temple 
		ADD EndDate DATETIME NULL
END

GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[UFO_Temple]') and  name = 'CreateEtypeName' and Length=50)
BEGIN
   ALTER TABLE UFO_Temple
      ALTER COLUMN CreateEtypeName VARCHAR(200) NULL
END
GO

IF EXISTS(SELECT TOP 1 1 FROM UFO_Temple WHERE ClassId = 1 AND TempleName IN('利润表','现金流量表','资产负债表'))
	BEGIN
		UPDATE dbo.UFO_Temple SET TempleContent = '000000000000000000000000000000000000000000000000000000000000000000000000000000007461702e323030300600040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001800e5027003cd0460030d008f017701d40105023b0068010101000000000000000000000000000000000000000000000000a803000086000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000071070000810700008d070000d104000017000000ec04000000000000000000000000000000000000cc0000001f8b080000000000020b6361606090006246242ccc80095e3033303031f048b36291db02c42c500c030148e62d03eb85e0562001e482713d2344ad2ed40dcc48fa7590f44f84ea1507e2ffff19080264bf3023b15990e471811fc81cfa6960837a9195548d30db80e1cd854d0ea7f328d2c0448cb328f20f3de3877d98f9878808a5d83f0640fd4a4a1073884a3eb4d54095f881da467c70d34ec3a87f46fd33ea9f51ff8cfa67d43fa3fe19f5cfa87f46fd33ea9f51ff8cfa67d43f83c53fcc0486e10096a8d1b45b140000cd0200001f8b080000000000020bed943168135118c73f6b2b55abb6a543058550755010d30ce226080a3a083a38083a38383858cce0e020ea50d0c1c1c1c141b81cb649449bb4dec5dca59794c4985ebca6b94b1368bab444874a424a88a59516bf77f7aee4da9848415c7c10feeff7eeff7defbdfbbe4b2b00f4e2efd10ea83bb803f5d70f771a7a8e721bf51dc73cc12e806297c169e40ba84fa8ef620bc025d441ca69e4cba8cf283fde097015f539e583ad00d7505f50f6235f477d69e66b03b889fa8af212f22dd4d794e77701dc4675517eda0e70077588f295dd007751bda61fd989fade3c5f8ff5ded53d00f75147292b7b011ea0f2946f74003c4415281fdb678dbfb789951ab6c3fff16f47f9ec00f64f0be9b32260e740e467a282532c3ad86ce27cbc6277d02747ce3b9d034eec1b0b1846eecd94c80a192f607340aa6433462c0ced24b3149f1d2ff3251d265314b06d40151997e655397926f1dd9ab6534f6bb385aaac401c63937ec9eae8a10e731057d2174883efe378486bec4dadcaf9405a8b367605e722c5e6aed1f8d4d25657ef26574e1e5d0d55b35cb22c0f5b9d274c67486385e0db8c1cca67397f811f9167d46fac9b04a899be937d5f4a13d3acc71a7bd4ba8bc2e7e43f883a658d8a17b2d3acc06726bc9a375e5139411152c68c8b9919c146bef875a35aa4455877783959c62dd8777dc2a77abb749b15d48c0a2a0b5babdcbda9caca427678ec87d573887a8c63063e4f2cf323e46d7e18ca46f5b7495e42628d719163e5e6f8927134326b74bcfd355b2757b868d2075b8a482e9d8c312e4934ae2c89cd2e4db24e7d655cd1707052af84a0df9175ab22eb1157fc92f9802ef3ebac27c5c8cac6724db6bf39adff95f758b0e6ab362ee6b0f73b628b7ca2df119f0d15b6bf64f94fe8d021b618c98b6bfac29926f566ddbf7de2d9566b3b30a65e4a4934b693446253338c8ff132fe8dba9f6e70ce26a1b5e31700b818ab8f080000170000001f8b080000000000020b636080000069df226508000000810200001f8b080000000000020bed95cd6b134114c0275dd37cecd688f52c610f921a177636c92639d9ec805e928256504f12ed52834916b64ae92dfe1382b71c3de4e2454104a188045aaa4829d2a35841f190b397f8de3691254c3a23f4e021036f67e6bd79f39bf7e6ed2e21b3366bff47dbd9db3d3ac99e245ffb11c11ee740ce8cf652a17fbdbdb377efba63e5a885ea3787c7ea77bddda3913a0ad3655caee120b43e30a043600879c4615e69aebb7ea3dec645151834d5f120ed34eb0f1e697fa72b75dff7365330bfd568b91be91577337dd36bd5dbf3a05add6addf79a0918dd6eb4d7d74036505df3d65cbf1d39b5cc76aee2f33bf91d082111827b3f532fc7114d2a4f970989fdf3ae89513f1c0ec9603020dd6e97fcfaf185f45e3c2743a4763a64ff537f56d8b346d22073a3f793041548c825903bd75633ba5da454bfa2bffc7c7000ddfb9ff0d8dfc651afff113a7d49e17856a53c9199e23273a69899e232459ec83c1bf2bc08e2140cc7369ca2e1940ca76c38d404a159875a203985e3c10a06b30d563458c96065838107030f061e8ce690b1c08d8b4ae472811b1795c8a5c6674ae452e3332572a9f26b4682a9f26b468299e4326d33276426b94c91e75ce87b3ac9b484ccc414a62564c6a730c5b98d4f618a731be332f312b98d71997989dcce873c6b21e6c9a7cd8e9789af601250950354a5001841941b8129178159105f68941b812917810880115c0801f0261d0adf425a563826062646cb385542267cb76e3c71fd2de6b532c1a1c3d6ccd85ab9ebd6fdcc52160ef2aaaf678f7535affdf8212a3f1cbefda6e37916b9755892a8fd456e1d96246aff7cc8530d7290871f00fc1ca8ad70cc0ccc0ccc8cdadac42ff50f2a271bc9ba0d00000c00000030010000cc000000000000000800000000020000cd0200000900000005000000b5da31d2b3',TempleName+='(新会计准则)' WHERE ClassId = 1 AND TempleName = '利润表'

		UPDATE dbo.UFO_Temple SET TempleContent = ' ',TempleName+='(新会计准则)' WHERE ClassId = 1 AND TempleName = '现金流量表'

		UPDATE dbo.UFO_Temple SET TempleContent = ' ',TempleName+='(新会计准则)' WHERE ClassId = 1 AND TempleName = '资产负债表'
	END	
GO

IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_Temple WHERE ClassId=1 AND TempleName IN('利润表(企业会计)'))--判断一个表名
	BEGIN
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'利润表(企业会计)', 1, N'00001',  N'000000000000000000000000000000000000000000000000000000000000000000000000000000007461702e323030300600040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001800e202700303057b03040089019501d4012f0226006801ef00000000000000000000000000000000000000000000000000a80300008600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000010000007d0700008d07000099070000de04000017000000f904000000000000000000000000000000000000b90000001f8b080000000000020b63616060100562462866026211064cf0821924c723cd8a456e0b10b340310c042099e9c60c311784b9808a805c300e876ad085ba811949bf0e92fe8948eefaff9f81206044c2cc486c36a8393035403772c1f420bbfd07b2612cd4d2c0444803039af370019cb651a0817d703b8f88e046779e0190aba40411262aae68ab015be84135131f18b4d330eabc61ecbc51a78da6b951e78d3a6fb440198dd451e7d1ce79cc04fa2500b34ea2086c0d0000ed0200001f8b080000000000020bed54416b1341147e6a2b554b6d63141585a4ea41416c72f42208edc183480f828207ff80420e1e3c080a0a7af0e0c17bba68d3883669ddadd9dd26ad896bb2db2475936ea12d424b5ab09290126aa9c5e29bdd59dd6db7ad88e2c581e19befcdf7decc9b79337500b01ffba56de0d8d8bdcef6a3cd069ea7bc9eea4e629c580b40b9c5e03e174007e23daabb8ffc02e203ca3f21bf88f888f2cc3e80b78839caafbb01244499f2bb3b003a111f537ea80ee032e213caa3c8af223ea5fc6103808aa8517e0593bd8118a67c01f904e247cadb0f00cc20ce513ebd0b2080f88af2c5dd00b710fb28cfee01b88dc8517ead11e00e228ffd2cfc6fffb655cffde988a17a80eda4cecab0136168255dc3211605783cc2b4546bf3d39963ed81c0cd00d6998d1842f6594e60f86218b078205ff1182d95800612392e4d0c56b98a4e32794ab0ac4015825d85b0caca63e9cff6b0cd7a588f475c6478a2e8cf44e376c561aa301b512991c1aa1879332816368f36f0a19004d21d55a4c5a686ca5babfaa4dc82b3eae09add8dcb7d5fc5458d55aa72b75d79ca548a05868fbd28cae2a4c6464b5caf3ca6ce3121e2a0165b4fb78e548647991ebbef71fb2a596e5cfe05af33762fa9a48d323c571c0e17c2524d65f92c9f37466cca8c081ef4497f336e8b9408134a2c29555c8279d9cabf735ac5659e79c138f3ecccfa5b76adb997ec8cd6ddffc5ae394235c63607de0f2f71bde4345f3fd792fa6992435052c12eb2adf129ae626c8d8c36db5e93656965994d2a91f5974892cecd06bbe28291725cd82ae926ea914cc432fa4df07a8e4c4815981e61391a3727a8995b657af24139fbc36c89f63787ceafdc6da396576d24e66ff3f953f35cdae79726c4d2ef9b6c7f42a34e52f34393a2a41b9ae9bfa02d918ac82de855e3b6dc9639a17f09d65fc09cb0fc02a49380dceacf802477f03a18d73f9b13961a964acacac6ca7a72be9ded1d5ecbc86bf1def869dafe93d8c8b29eafcb62b43c1e6bfb0e59ad4908e8080000170000001f8b080000000000020b636080000069df226508000000800200001f8b080000000000020bed95cd6b134114c02759f3d12436d5f807843d486a5cc86cb2f938d9ec805e928256504f12ed52834916b64ae92dfe1382b71c3de4e2454104a188045a2a8814e951aca078c8d94b7c6fb32d4b9c7546e8c14306dececcfb98dfdbf7265942e6633efe8fb1bbbf77f4377b827c198504672c819cf1ce4ac2fc6a6777ffee35532f521dd5af0fa7eab7c3bd234f1d81ed0abaa770e1f3770d18e01a7c1171d8d73b1b96d36ef5d0a90e8b4ef27891353badfb0f5327dbd596e3d85b69d8df6c77adcdecaab595bd61775bbd28a8d6b6bbf7ecce02ac6eb57b1beb209ba86edaeb96d30b9d5a65fb57f0f98dfc72859010c1b39f262fc5114dea4f560889fdf3a9716f9e4c26643c1e93c160407e7eff4c86cf9f910952fbfdf9a59e0fa2828441ce797bbc7b17416e5f5dcba946b940d5cbea8b8f070730bdfb018f4f3bb81a8e3ec0a42e2b9cc8865464d8fb3ff8935994602e71994509669acbd40b452133cd658a2291b918c014bfe7620053fc9e677d91d821b39a376b9a490b20144457384eac9a67358d8113032746753c29c5cdde90a8588a9bbd2151b1640053173293014c5dc84c0430c55d4a0430c55d5af045364f985490ad36752b150c616ab380861ca0210508fbbe33216f6d1a9a59d6cc8ac2b1314363658d55302ec6ad7649a2c3316eb54b121d8e0630c51d8e0630c51d8e7099548219e132a904f3822f12ab65d22afce26b0ac7c4c0c4680db78acf8437fafa63cbd9667637e766e3b7e68eadf53b56cbc92de721919723353fd535eddea307a87c7ff8e6ab8af964b835a848d420c3ad4145a206e77d9119b706c5bc494b200608dc50ea5ed15937066e0cdc18b8317063b4929af962fe06edb91f75960d00000c00000030010000b90000000000000008000000ed010000ed0200000900000005000000b5da31d2b3', 1, N'0000100001', N'超级用户', 1,1)
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'现金流量表(企业会计)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'资产负债表(企业会计)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)


		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'利润表(小企业会计)', 1, N'00001',  N' ', 1, N'0000100001', N'超级用户', 1,1)
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'现金流量表(小企业会计)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'资产负债表(小企业会计)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)
	END
GO
--date:2013-05-29 by:glj
IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_Temple WHERE TempleName IN('项目余额表','项目经营表') AND ClassId=1)
	BEGIN
		DECLARE @ModeID	INT
		IF EXISTS(SELECT TOP 1 1 FROM UFO_ReportCategory WHERE SysType=0 AND TypeId='00002')
			SELECT @ModeID=ID FROM UFO_ReportCategory WHERE SysType=0 AND TypeId='00002'
		ELSE 
			SELECT @ModeID=MAX(ID)+1 FROM UFO_ReportCategory WHERE SysType=0 AND TypeId='00002'
		INSERT [dbo].[UFO_Temple] 
		(
			[TempleName],
			[ModeID],
			[CreateEtypeID],
			[TempleContent],
			[IsVisible],
			[TempleCategoryID],
			[CreateEtypeName],
			[ClassId],
			[IsShare]
		) 
		VALUES 
		( 
			N'项目余额表', 
			@ModeID, 
			N'00001', 
			N'000000000000000000000000000000000000000000000000000000000000000000000000000000007461702e323030300600020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001800e30270038d047203fbff8b018b01d40121022d006801f500000000000000000000000000000000000000000000000000a8030000860000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000001000000cf060000df060000eb0600009704000017000000b204000000000000000000000000000000000000d10000001f8b080000000000020b63666060900762462866026236064cf0821924c723cd8a456e0b103343310c04209919cd04311784f73041e475a1f67223e9d141d293c380d0138b64be1510b300312f10ffffcfc0c0c700c1f640cc0fc4225071510608760162312096848a4b3140b00d104b03b11c549c1060440b23189b0dca87a9714070c1ee84811fc886b190ab01d9261d248d0cc4d8449206649b3448b5091720c64f0c23daa651278e10270e4c6030905b04e88cc6db60d0c830384be291109a232170980934820092b7031e2d0a00008e0200001f8b080000000000020bed53cf6b1351101eb1609ba635961cc48b4550f0a8a0373d0816f4e0c183a0074141410f9e44f0e241d0bb470f1e224123626b92cd26d9986ec010926d6aa2e9269028a42a051183b988a4149c793befedbeb47f820f967c6f7e7c33f3e6cb6e003888dfdd5db0ed044da7f0bbc6f8dc24c06dc6c33d7ecc13b43f647c6c1f4088f1d12980078c9f219e63bc3ee5e71ec6e0038cef237eccb8180af4330d7084f117c477646e18e038e35b884f327e13f67387884f333e31037046d642bc206bcdf8f15b88cf33be3c0b7041f68ff8a2e4447c89f1d9bd00f7183f427c85f10fc457654c04e03ae3a7886fe2ef21f87fc6cf8d094f3b8d41d96ef5cd41f2174cf015506250e9965f911d68bfb1e58e931a598d7795982d0cf65763a356af643b9fdb1988508495af9b091555f0c8dac5df1015deeaeb94fde96fb3696cd8038ea02aad178e4b577131b6ea4bd98fadf7a2c287a5d5a6316a8ca88af0aec57366c74142ba94bb299b72bd56bfaf6c8a0be5a5e3956ebe564dac62b097d72d26f2f1749d07c959ee220fe2359033fd0682f50aeb6b49e3398ee715775c55dcab973399a05858798b9e90a077dceacf521fc967c5d8c456ea9391076e8c9c1e5dbd6e2ca2622f19b299ccb7c2b0244c4cd87e99fe2308239cedf6ec5e3653da248756850ccc13b3e81d03ef4c89e95a7259ac45cc4b74f378b44d02fd39e7b56d47396edb8227d92196bc5f45edb0e8303bd5b2a5412d5c36a32d5d46a9c54b835abe342801481e4d048a470a81870c28c1ef90d5a03a1c6f46a9c2ef8e95a13783eaf0495921d35e5d259139f5689a4c649e924a44c505e4228d9a64b882d24c3440a5e966bc346bc7af14d04fb01fa1a11d5f39aa298044c1e9c1f30ff225c15809070000170000001f8b080000000000020b636080000069df226508000000190200001f8b080000000000020b5bbc84010c5420144303940e0d7601d3aea1410cb404274e1ffeb8f1126ef9c307aeacc2a7ffe876fcf294ea1f05f403a7cf9d798a4f9e8be1d1094602660800310bd42c6e20bdfdd0e973f1ee4e46c6864620e15db720c2fbd79c790a156605721d40ca79400c24f560099006b004920e0e20df31273db52833310fa4c811c8c8e18631149c721293b379e05cbfc4a2a2fc727e203f243337b558c12fb55c21283f37318f0d28145c999b949fc309648567e6a5a700713148d8373f25b5288f916a21db600f229f31fc02630606460690d9d3b8b53840563338363a90632a0b94feffff3fc3870f1f18162c58309a884701830c103301b120940f4a6bb2401ce11be8aba164646861a8a4a37464cd89f3084a4993099a79b16930c1a5811f8706235c1af8903480b2687169ae8693a1a995939101585e0eab81a62606b80ce4c5aac1d0d0d818870659240d32700d0626b8d4f3e0b2c0088706191c16e052cf8dc302535c5e96c6aac1c0c4c00487062eec361899e1b2410a5b2c19995b391943628913bb81c6386349127bb41a1ae00a750eac816869618e43bd042e0b70853a3b920669b8069ce68be3321f978fd9903428c235044706eb1a1ae0d424863de9e04c6aac582d313435307400da84439328d6c83502664153b03c0b8ed482b31010c1510898e3d2c08ca4811be602132b274363b0b4300ef3700683102e0dd81cc083563f00007e87f3ed810b00000c00000030010000d10000000000000008000000050200008e0200000900000005000000b5da31d2b3',
			1,
			N'0000200001',
			N'超级用户',
			1,
			1)	
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'项目经营表', @ModeID, N'00001', N'000000000000000000000000000000000000000000000000000000000000000000000000000000007461702e3230303006000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018006b039803a703b001ea0121026900d401a000b30168015802000000000000000000000000000000000000000000000000a8030000860000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000001000000a9040000b9040000c5040000e7020000170000000203000000000000000000000000000000000000a50000001f8b080000000000020b63666060e0036246286602625e064cf0821924c723cd8a456e0b103343310c04209959ce08311784d9a18a74a1f6b223e9d141d2339101a1c70dc97c0d206681eafbff9f818183018241e29c50b783c4090146343fc3d86c503e4c4d00820be6c3c00f64c35850357011ad8101cd360b24db1888b18d240d4c68fe070125250a345364f310d53c1a60446826592333811c0b006d54fae6a70400000a0100001f8b080000000000020b63666060e003e2150c98c09105c1ce04e25e28fb24103341d9ac8c0c0c6c50b62790cd05652f6584980b023f816c3128db17a8510acaee04b2e5a0ecb340b61294adc9ccc0a00665d702d95a50f643205b0f48f330d01e6842fd75e0f789cf1bdf82bd75fedd91fdfbd65e5e05e4b240b960f18dfb8edddabee8e4af6defc0dc85fb4e5d3df1fac08385fbc10e550082f3bf4edd06093208410516ee3a79e6d8f6030f40820b773308c0858f3d39fd1b4d70fbd6ad8f777f3c0016865a706df9e66f18166c3eb9711f8605209528166cbf78f9f0aef37b8e01054590345fbdbdfff6f6ad077e83d4837d07f237baaf611a200049021900006a652fa851020000170000001f8b080000000000020b636080000069df226508000000a30100001f8b080000000000020b5bbc84010c5420144303940e0d7601d3aea1410cb404274e1ffeb8f1126ef9c307aeacc2a7ffe876fcf294ea1f05f403a7cf9d798a4f9e8be1d1094602660800310bd42c6e20bdfdd0e973f1ee4e46c6864620e15db720c2fbd79c790a156605721d40ca79400c24f560099006b004920e0e20df31273db52833310fa4c811c8c8e18631149c721293b379e05cbfc4a2a2fc727e203f243337b558c12fb55c21283f37318f0d28145c999b949fc309648567e6a5a700713148d8373f25b5288f916a21db600f229f31fc02630606460690d9d3b8b53840563338363a90632a3794feffff3fc39b973718d6ac98c9f0e1c30786050b1630fc07d9da002c4d1a1cc085ca950b274613f82800a7192620e685f241e91094879c8c759d2c40123c4812b2401ce1eb16aca164606260a2a4a37464cd89f3084a49930929158234c8206930c6a19e0b877a231cea39b13ac8d4c4c01087060e240d20c71597e66a38595a39191a81a5d9b19b676880cbc16cb834e072312b761f1ae352cf82cb025c3e6446d2c005f3a1899593b9260f5a0a0700f91a5f115f0800000c00000030010000a50000000000000008000000d90100000a0100000900000005000000b5da31d2b3', 1, N'0000200001', N'超级用户', 1,1)
	END
GO

--date:2013-07-04 by:glj
IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_Temple WHERE TempleName IN('年度损益统计表(小企业会计)','年度损益统计表(企业会计)','年度损益统计表(新会计准则)') AND ClassId=1)
	BEGIN
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'年度损益统计表(新会计准则)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'年度损益统计表(企业会计)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)
		INSERT [dbo].[UFO_Temple] ([TempleName], [ModeID], [CreateEtypeID],  [TempleContent], [IsVisible], [TempleCategoryID], [CreateEtypeName], [ClassId],[IsShare]) VALUES ( N'年度损益统计表(小企业会计)', 1, N'00001', N' ', 1, N'0000100001', N'超级用户', 1,1)
	END
GO
IF EXISTS(SELECT TOP 1 1 FROM UFO_Temple WHERE TempleName='利润表(小企业会计)')
	BEGIN
		UPDATE UFO_Temple 
		SET TempleContent=' ' 
		WHERE TempleName='利润表(小企业会计)' AND ClassId=1
	END
GO

 
UPDATE dbo.UFO_Temple 
SET TempleContent = 
'000000000000000000000000000000000000000000000000000000000000000000000000000000007461702e323030300600040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001800e2026003d3046903040079018501d401190224006801e500000000000000000000000000000000000000000000000000a8030000860000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000001000000e3140000f3140000ff140000b80f000017000000d30f000000000000000000000000000000000000630100001f8b080000000000020bed984b4ec3301086c76eda88525e1b16acaa6e403c24d69ca2e764cd09380d476057c6f204dc340a71a44655f259fa55679a7f66f265d2aa2d45e441e54c73d59d1caeaf998897d5f9bce1bd0f5569aad636c9f9e98237ea56f79a2a4af78544bdfb583b68a5fb85443df998efc5fa3c4b6a3c2735b6963fe4ddedfef2be59ce0bf35f9a1e5557a610bf3685f88deadee2ff2d9fd42decb5ea6951dbd7976bc9fb9d1e1483197c6254a4cb2a5c74a93439439d5843b8f3bd1981a1f43e87d85e82f5e179ed1507322c7d7a951d0c991082f9550f379b8c219d9ca1e141fb35771ed2a31b4ea9a5eaacde5f197d5b931e06777a2d8117bc47318017bce0052f78c10b5ef08217bc7b7fbf8d11ad03ed880d7c288077ba783d782736bd1ebc4c2f78c10b5ef08e0cef5a06ba814c2f78c10b5ef08237bb357e883190e0052f78c10b5ef0e65d8b30368ccd28f0cea47dfd001d1e16e3de3500001d0d00001f8b080000000000020bed1b6b6c1cc579680909214f9a864743644ca0602bd4b777b663b781503731899400012a1509fa90e047d5b425824af083065a68499bd0f61ffd11f57c799ced3c7cb1efecbbf3d94e72397c777ec5f73071421a52884a2abb069a406c25ea37b3dfecedcecede2eb41255752bcdcecdf79a996fe67b6d9cd98490bba1fde05a62fbacdf483ed373e75fd4fe23907dfd2f8db8ef212ebc89900968b73f44c80e80dde22564a317e77bb840ffb2d7c85f0df2eabf4cc87dd062805b7a1d21b75ea7e20280db00f04dd02e036e39c0cb11f7e436429e00f853d03636117217c02b107712703f06f84fa1bd0eb87b01ae20eef197097911e02f413b0eb81a80d723ee04e0b6037c27b46b7cb026807f9bcff70a217f06f82e3a1fe0d6017c039f0f702d003f48e703dc26806fe67cbf222402f01e3a1fe0be0bf0271077a0b5a08727f7133209f08f1077dbfe022eb7dfa8b3e41f09b90467310d6df101f80d3cd3c8f7eaaf0b746b770be7fe2a21e3b08e33d0c202eee4ab85dfb3f680ee40de5694f9c3d7605dc07309dafa3d46be59bf81b9017e15da0ec0fd02785e44be37013717d6b8005a12702f01fc15bebfdfc239037c39b4597b09790de0dbf9b903ae02e0f7425b0fb89d00ff13e2d6be0ee705f0fb24f7fc08e036007c139d0ff876014f133ff7eda077803f05edb67d46be0f00f723803f03ed59c0ed059e16aecfdf15e862803b08f0c3885bfcfb02ee4341e620e0b683bc9dd0b6f80909014f04f99edd51a03b01b81e801f45dc04e09a80672fb4f9cd8424009ee2e7b013e6067808da23801b02f828e703dc518027a0ed005c1ee0e3887bfd0d6bdbdef207a0039e33542f0741efb3e1cc66e3bd03dc39809f87f6420bf420ef02b4f4359c7bea7ed66dfbce1a0460bf16fb396abf8d8f1761bf0efb2588e7e39bb16fc47e19e2f9b80cfb07b12f473c1fafc07e3df677219e8f3760ef46f8461c7bb0df847d35e2f9b806fb87b0af453c1fafc2fe61ecebd47e0d1fd7233d1f7f53edfbf8f85bd83f82fd6ae4e7e3fb909f8fef477e3e5e83fd66a4c3f11a1c9307108ee33e0e7f14e9b0dfd6803d8efbb027fc7c1f53fb87df40fc56638fcfae4fab1e30e8df82aef4949ed2537aec1f8c33a5a7f4949ed2537a4a4fe9f9bf7ca295507fd27a7ddd43df7fece92d3fffc9d38456b17d33fd1f072618a6ac2cfa6ee2e32a05861473c7daad5b7fb695b418072a6170cf50d417c9b6901b60383c59a63ef15e32877e65e8498cc7a642936c901cc6c13c188c46bd4d9996d1602ad7ff0fa3d8454c6c5959f7455f8452b427033d468a5b91823f942add169bea6eeb8a75678cb44b04dae1e9d4a9ce139963c5a9c2a7fb26eca90e27863e3453dd2c508da50e4f775fcc07d353a97d46ca0a4ed99df145c2add954f7a97c30f05ee8502a377adee7a70ca3d9f295e5039347467ccd46de15c65906436329075cdf307225decb8ff822a1ec91964c4be2e3d160643032acfe0ac6b94452063ca1abea69d12be2f3f77e929e82297c07ca23c765b3dcc84f30a39ee0e039f329df289cf2e0b9fcbef64b469a6548a32eb3f3ad239f840e516d76eccd1f63daa44ae8bfe26da2cb1a3b1d9a5497467f395a1e4c9dbe1c3c966e331f22dd743aee6dea89aa5bee89da6d7a010c86def7361deb0d27d94944d8443eff68d4d71cbd1ce8e1080487aefa9a87bda9410dbc4272ef5d9287d91d5543572477100c944e1c98881cf74598cdbad0840367f309d536c9d7841b5916bf40dfd9a3f4dd9f63c6a999f13c265dbbe2d3847e041c19e918626489f17873e62c1a74fc42fb4536a0daa2abe96e4b5fce8ce4fedaef1f3d3f7faecf1ffd289c0cb5d21168cb819cebe907463ce47a6d4425d773b77431303a968a4d91c530745555b92a2ae1add0b74
 
657bb1cd0abd41684382143ad12886de15055bd857f02c42d470eb970010921215508456a5510aa2ad423a248200e397309f3366b67b51e3383c481432cad77bd33bf9979bf9937fbdeda308e3fc79fffc7e7eefd7b8fff49be60fcb23743d878128e27525b25387f75e7eefdb75f0da423a4befdf5a3c3dbdfeede7b9cde36e1e725ad5ed61719fd44a00189208328c2eff5cd1bdde146a7af95d6e162b334baa8049b9d773f288f7f5eee0c87835b4bf0fbf58d5e77ab72b97bab7275d0ebf42db875ed76ef9dc1e63c5cbdb9d1bf711d8e2d7d5b0dae7787fd99ff8cd9ed57f4f76fc65fc961183386b6fd49e9a5a2766dac7f7cc930e6feb5d5527a3e383830f6f7f78d9d9d1de3cfdf7f36763fffcc38d05eb7b7e10b4cc3e9c18f7bc7057efc31de874357f853e96f5d87cfc37125ac5565d316d597ab5ffcf4f0219cbefb03be1edcd157bb7b3fc0a9ba666240c50016a678142d02383bc52309d41eab98c786a03d56318f14d09c02742511aa35255412a83d9ec73cdab6243d9ec73c72804b58e548970e7509ab1c0aa8f358c9003f1ce79120e762aa25595a0e591313412856108a1584620461e682c8649baeaf0a9e6d9afb1319e01b3329f72e01aca75a92a5e5b0b45c9696c7d2f2595a0d965693515f6e83ee3913442b16d18a45b46211ad58442b16d18a45b46211ad58442b06d1568ee8a3fee54872f29d40fb1701d47368117b0e4949d7c422f61ca280e61420844a93b3889343039fcb00f54a3696763d962d131145208a644b3353c698110ecd4c196386029a538092a2d49a122a09d4637c161ba34f4c8d590ca818402b07d4616fddecd56229dbb16c261c60f208e411c80b997d452e2b928cb88467859e5a25342b82ce4a09cd8aa0b3720ecf8a478ef11c9e158ff4b880b22ae995c702caaaa4570b0b28abc463c09a122a09d4633c8bb3ea92633c8bb3ea92a1621e658bb170c63c4aceaee20cb61af559ab519fb51af519abd133d86ad467ad467dd66ad467647b3e13c46b4715cd19a364f4f809f38a655e31cc9b39f399d9416f80e6f1d941af034e63b3c363ac034e63b3c3633cb4308f92b391c53c92403dc622dee5e83116f12e47875ac4f3489353c4f3488f7105ab7b4f703a8027e8a7e80a56f7b479c5306fe5cc1fd504a363aea035c178813397017e3a4e2d676be3f0b424538b9ea213a186ac504356a8212bd49011aa990b759c0ec1a8fb39ac0004a3ee97d1fec5e8e4cb68ff62ec2a308fd263908379248185f4dde8c4d3dd66bdefb059ef3b6c4607b0b0a7bbcd7a1760b3de05504198b920c61472de355958d238c017f37b4807f6904ed34444118822a7594044a168d543a7398b8802100587a853680f67ade2a8329ac5cc2b9679c5306fe5cc67e605ddc34fe1f38206be90013e9d244042029c8b91e3c2d983c32fe4d4465bcb508a76e834125e307900f200e41a7f126d318c05f149b4c530f63af981c530b0180616c3c0621858ecf85aed998c5a69b4a7f6dbb16825f460e2c86f4720d6b70a19b1de5c5db9d91dde0e07bd5a127b565a1b49d7dfea7686b5b53ac4fde55eb57e784f0dfa1fbda76f7effe89b5fab1ab78a11d664fcc7b18a11d6642c0d5791d27605e7e52268d11bba55646232cc870cf38534c523f3cba302f5dba170d7eaa1f0e168c091740f4c35f0db81560d403500d54024dde4029a05c6d2e8029a05c67cc4802ee7e98f854a02cbb97f11ff06306130d2b62200000c00000030010000630100000000000008000000970200001d0d00000900000005000000b5da31d2b3'
 WHERE ClassId = 1 AND TempleName = '资产负债表(新会计准则)'
 GO
 
 UPDATE dbo.UFO_Temple 
 SET TempleContent = 
	'000000000000000000000000000000000000000000000000000000000000000000000000000000007461702e323030300600020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001800e30270038d047203fbff8b018b01d40121022d006801f500000000000000000000000000000000000000000000000000a8030000860000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000001000000cf060000df060000eb0600009704000017000000b204000000000000000000000000000000000000d10000001f8b080000000000020b63666060900762462866026236064cf0821924c723cd8a456e0b103343310c04209919cd04311784f73041e475a1f67223e9d141d293c380d0138b64be1510b300312f10ffffcfc0c0c700c1f640cc0fc4225071510608760162312096848a4b3140b00d104b03b11c549c1060440b23189b0dca87a9714070c1ee84811fc886b190ab01d9261d248d0cc4d8449206649b3448b5091720c64f0c23daa651278e10270e4c6030905b04e88cc6db60d0c830384be291109a232170980934820092b7031e2d0a00008e0200001f8b080000000000020bed53cf6b1351101eb1609ba635961cc48b4550f0a8a0373d0816f4e0c183a0074141410f9e44f0e241d0bb470f1e224123626b92cd26d9986ec010926d6aa2e9269028a42a051183b988a4149c793befedbeb47f820f967c6f7e7c33f3e6cb6e003888dfdd5db0ed044da7f0bbc6f8dc24c06dc6c33d7ecc13b43f647c6c1f4088f1d12980078c9f219e63bc3ee5e71ec6e0038cef237eccb8180af4330d7084f117c477646e18e038e35b884f327e13f67387884f333e31037046d642bc206bcdf8f15b88cf33be3c0b7041f68ff8a2e4447c89f1d9bd00f7183f427c85f10fc457654c04e03ae3a7886fe2ef21f87fc6cf8d094f3b8d41d96ef5cd41f2174cf015506250e9965f911d68bfb1e58e931a598d7795982d0cf65763a356af643b9fdb1988508495af9b091555f0c8dac5df1015deeaeb94fde96fb3696cd8038ea02aad178e4b577131b6ea4bd98fadf7a2c287a5d5a6316a8ca88af0aec57366c74142ba94bb299b72bd56bfaf6c8a0be5a5e3956ebe564dac62b097d72d26f2f1749d07c959ee220fe2359033fd0682f50aeb6b49e3398ee715775c55dcab973399a05858798b9e90a077dceacf521fc967c5d8c456ea9391076e8c9c1e5dbd6e2ca2622f19b299ccb7c2b0244c4cd87e99fe2308239cedf6ec5e3653da248756850ccc13b3e81d03ef4c89e95a7259ac45cc4b74f378b44d02fd39e7b56d47396edb8227d92196bc5f45edb0e8303bd5b2a5412d5c36a32d5d46a9c54b835abe342801481e4d048a470a81870c28c1ef90d5a03a1c6f46a9c2ef8e95a13783eaf0495921d35e5d259139f5689a4c649e924a44c505e4228d9a64b882d24c3440a5e966bc346bc7af14d04fb01fa1a11d5f39aa298044c1e9c1f30ff225c15809070000170000001f8b080000000000020b636080000069df226508000000190200001f8b080000000000020b5bbc84010c5420144303940e0d7601d3aea1410cb404274e1ffeb8f1126ef9c307aeacc2a7ffe876fcf294ea1f05f403a7cf9d798a4f9e8be1d1094602660800310bd42c6e20bdfdd0e973f1ee4e46c6864620e15db720c2fbd79c790a156605721d40ca79400c24f560099006b004920e0e20df31273db52833310fa4c811c8c8e18631149c721293b379e05cbfc4a2a2fc727e203f243337b558c12fb55c21283f37318f0d28145c999b949fc309648567e6a5a700713148d8373f25b5288f916a21db600f229f31fc02630606460690d9d3b8b53840563338363a90632a0b94feffff3fc3870f1f18162c58309a884701830c103301b120940f4a6bb2401ce11be8aba164646861a8a4a37464cd89f3084a4993099a79b16930c1a5811f8706235c1af8903480b2687169ae8693a1a995939101585e0eab81a62606b80ce4c5aac1d0d0d818870659240d32700d0626b8d4f3e0b2c0088706191c16e052cf8dc302535c5e96c6aac1c0c4c00487062eec361899e1b2410a5b2c19995b391943628913bb81c6386349127bb41a1ae00a750eac816869618e43bd042e0b70853a3b920669b8069ce68be3321f978fd9903428c235044706eb1a1ae0d424863de9e04c6aac582d313435307400da84439328d6c83502664153b03c0b8ed482b31010c1510898e3d2c08ca4811be602132b274363b0b4300ef3700683102e0dd81cc083563f00007e87f3ed810b00000c00000030010000d10000000000000008000000050200008e0200000900000005000000b5da31d2b3'
 WHERE ClassId = 1 AND TempleName = '项目余额表'
 GO
 
 IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='UFO_Temple' AND a.Name='TempleContent' and a.xtype=35
)
BEGIN
	ALTER TABLE UFO_Temple ALTER COLUMN TempleContent VARCHAR(MAX)
END
GO

UPDATE dbo.UFO_Temple 
SET TempleContent = 
' '
WHERE ClassId = 1 AND TempleName = '现金流量表(新会计准则)'
GO

UPDATE dbo.UFO_Temple 
SET TempleContent = 
' '
WHERE ClassId = 1 AND TempleName = '现金流量表(小企业会计)'
GO

UPDATE dbo.UFO_Temple 
SET TempleContent = 
' '
WHERE ClassId = 1 AND TempleName = '现金流量表(企业会计)'
GO
UPDATE UFO_Temple SET TempleContent=' ' WHERE TempleName='资产负债表(企业会计)' AND [ClassId]=1
------------------------------------------修改字段小数位数区域开始-----------------------------------------------
------------------------------------------修改字段小数位数区域结束-----------------------------------------------
go 




SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

/*
	作者：谢吉康
	日期：2020-04-04 
	描述：易聚客配置表  今天是祭奠新冠病毒逝去同胞纪念日
*/
IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[YJK_Config]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[YJK_Config](
		Pk_ID		INT IDENTITY PRIMARY KEY,		
		ConfigName	VARCHAR(50),
		ConfigValue	VARCHAR(1000),
		Comment		VARCHAR(200)
	)
END

--插入数据

--默认往来单位(存的BID，搬移就不用处理了)
IF NOT EXISTS(SELECT TOP 1 1 FROM YJK_Config WHERE ConfigName = 'BTypeId')
BEGIN
	INSERT INTO YJK_Config(ConfigName,ConfigValue,Comment)VALUES('BTypeId','','')
END

--默认制单人(存的EID，搬移就不用处理了)
IF NOT EXISTS(SELECT TOP 1 1 FROM YJK_Config WHERE ConfigName = 'ETypeId')
BEGIN
	INSERT INTO YJK_Config(ConfigName,ConfigValue,Comment)VALUES('ETypeId','','')
END

GO





GO
/****** Object:  UserDefinedTableType [dbo].[Type_OMPtypes]    Script Date: 07/29/2014 19:44:19 ******/
IF NOT EXISTS (select * from sys.systypes where name='Type_OMPtypes')
BEGIN

CREATE TYPE [dbo].[Type_OMPtypes] AS TABLE(
	[InventoryID] [int] NULL,
	[Ptypeid] [varchar](50) NULL,
	[Status] [varchar](100) NULL
)


End
GO







IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_AdvancedPriceSet' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_AdvancedPriceSet]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_AdvancedPriceSet;
	DROP TYPE Tb_AdvancedPriceSet;
END
GO

CREATE TYPE Tb_AdvancedPriceSet AS TABLE(
	BillType			INT,  --单据类型
	IsTopPolicy			TINYINT, --高级
	IsDownPolicy		TINYINT --基本
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_BillDetailCheck' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_CheckBillDetail]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_CheckBillDetail;
	DROP TYPE Tb_BillDetailCheck ;
END
GO

CREATE TYPE Tb_BillDetailCheck  AS TABLE(    
	rowno                  VARCHAR(10),		--行号               
	typeid                 VARCHAR(50),		--商品typeid        
	fullname               VARCHAR(200),	--商品名称     
	ktypeid                VARCHAR(50),		--仓库typeid
	kfullname				VARCHAR(200),	--仓库名称
	kusercode				VARCHAR(200),	--仓库编号
	cargoid			       INT,				--货位id                   
	GoodsNumber            VARCHAR(100),	--批号        
	itemid				   INT,				--自由项id  
	etypeid					VARCHAR(50),	--业务员typeid  
	efullname				VARCHAR(200),	--业务员名称 
	orderid					INT				--关联订单明细表orderbill中的orderid
	,discountprice			numeric(24,10)	--折扣单价
	,goodsnumberprice		numeric(24,10)	--批次成本价
	,isservice				int				--是否服务商品
	,isgift					int				--是否赠品
	,recprice				numeric(24,10)	--最近进价
	,mdiscountprice			numeric(24,10)	--大单位折扣单价
	,qty					numeric(24,10)	--基本单位数量
	,taxprice				numeric(24,10)	--含税单价
	,mtaxprice				numeric(24,10)	--大单位含税单价
	,BeforePromoID			int				--促销记录id
	,munitid				int				--大单位id
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_BillDiyColumnsConfig' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_SaveBillDiyColumnsConfig]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_SaveBillDiyColumnsConfig;
	DROP TYPE Tb_BillDiyColumnsConfig;
END
GO

CREATE TYPE Tb_BillDiyColumnsConfig AS TABLE(
	BillType			INT NOT NULL,		--单据
	CustomColumnId		INT  NULL,		--自定义id
	Label				VARCHAR(200)  NULL,		--显示的列名
	IsVisible			INT NOT NULL,		--是否显示
	IsRequired			INT  NULL,		--是否必填
	CustomDisColumnId	INT  NULL,		--显示字段关联的id
	InOut				 CHAR(1)	NULL,			--出入库
	ifindex				INT NULL,			--是否主表
	isdisplay			int null  --是否显示字段
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_BillPrintConfig' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_SaveBillPrintConfig]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_SaveBillPrintConfig;
	DROP TYPE Tb_BillPrintConfig;
END
GO

CREATE TYPE Tb_BillPrintConfig AS TABLE(
	BillTypes		INT NOT NULL,		--单据类别
	BillType		INT NOT NULL,		--单据
	AddState		INT NOT NULL,		--新增状态
	SaveState		INT NOT NULL,		--保存状态
	PassState		INT NOT NULL,		--过账状态
	SaveAlert		INT NOT NULL,		--保存后提醒
	PassAlert		INT NOT NULL,		--过账后提醒
	PrintNum		INT	NULL			--打印次数
)
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_DeliveryApplyBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertDeliveryApplyBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertDeliveryApplyBillDT;
	DROP TYPE Tb_DeliveryApplyBill;
END
GO
/*
	作者：chenqiang
	日期：2019-11-14
	说明：要货申请单
*/

CREATE TYPE Tb_DeliveryApplyBill AS TABLE 
(
	ID				INT,
	[BillNumberId]	[numeric](10, 0),
	ShowOrder		INT DEFAULT(0),
	[PtypeId]		[varchar](50) NULL,
	[Qty]			[numeric](24, 10) NULL  DEFAULT (0),
	[Price]			[numeric](24, 10) NULL,
	[Total]			[numeric](24, 10) NULL,
	UnitID          int             Default(0)  NULL,
	MUnitID         int             Default(0)  NULL,
	MQty            numeric(24,10)  Default(0)  NULL,
	MUnitRate       numeric(24,10)  Default(0)  NULL,
	MUnitMsg        varchar(50)          null,
	MPrice			numeric(24,10)  Default(0)  NULL,
	ItemID          bigint               null,
    IsCombined      int  NULL,
	[Comment]		[varchar](255) NULL,
	CargoID			INT				DEFAULT(0) NULL,
    DeliveryQty		DECIMAL(24,10) NULL DEFAULT(0)
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_GoodsStocksQTY' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Web_GetMultGoodsStocksQTY]') AND TYPE in (N'P', N'PC'))
		DROP PROC Web_GetMultGoodsStocksQTY;
	DROP TYPE Tb_GoodsStocksQTY ;
END
GO

CREATE TYPE Tb_GoodsStocksQTY  AS TABLE(    
	PTypeID			VARCHAR(50),		--商品ID
	KTypeID			VARCHAR(50),		--仓库ID	
	ItemID				INT,				--自由项ID
	GoodsNumber		VARCHAR(100),		--批号	
	CargoID			INT,				--货位ID
	GoodsCostPrice		VARCHAR(50),		--成本价
	producedate		VARCHAR(50),		--生产日期
	validdate			VARCHAR(50),		--效期至
	baseunitid			VARCHAR(10),		--基本单位
	munitid			VARCHAR(10),		--销售单位
	isSelectedGoodsNo  VARCHAR(3),
	ifwx				INT,				--是否是维修 0：否    1：是
	ifcommission		INT,				--是否是受托委托单据
	outcargoid			int,
	stypeid				varchar(50),
	orderid				int	,
	nid			int				
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_Gp_PriceOrderSet' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_PriceOrderSet]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_PriceOrderSet;
	DROP TYPE Tb_Gp_PriceOrderSet;
END
GO

CREATE TYPE Tb_Gp_PriceOrderSet AS TABLE(
	PriceType			VARCHAR(200),  --价格类型
	[Priority]			INT	           --优先级
)
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_ImportSaleBillDetails ' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Qp_ImportSaleBillDetails]') AND TYPE in (N'P', N'PC'))
		DROP PROC Qp_ImportSaleBillDetails;
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Qp_ImportBuyBillDetails]') AND TYPE in (N'P', N'PC'))
		DROP PROC Qp_ImportBuyBillDetails;
	DROP TYPE Tb_ImportSaleBillDetails ;
END
GO

CREATE TYPE Tb_ImportSaleBillDetails  AS TABLE(
	billNumberID    NUMERIC (18),          
	detailID        INT,
	billtype		INT
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_NoinKindBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_FactInOroutSaveDetail]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_FactInOroutSaveDetail;
	DROP TYPE Tb_NoinKindBill;
END
GO

CREATE TYPE Tb_NoinKindBill AS TABLE(
	[BillNumberID] [int] ,
	[id]           [int],
	[BillType] [int] ,
	[Serial] [varchar](max) ,
	[stypeid] VARCHAR(50),
	[ktypeid] [varchar](50) ,
	[CargoID] [varchar](50) ,
	[ptypeid] [varchar](50) ,
	[ItemID] [int] ,
	[IsCombined] [int] ,
	[productdate] [varchar](50) ,
	[validate] [varchar](50) ,
	[GoodsNumber] [varchar](100) ,  --批号
	[UnitID] [int] ,
	[qty] [numeric](24, 10) ,
	[NUnitID] [int] ,
	[UnitRate] [numeric](24, 10) ,
	[NQty] [numeric](24, 10) ,
	[SQty] [numeric](24, 10) ,
	[Base] [VARCHAR](200),
	[FromBillType] [int] 
)
GO






IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_onShelvesBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertOnShelvesBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertOnShelvesBillDT;
	DROP TYPE Tb_onShelvesBill;
END
GO

CREATE TYPE Tb_onShelvesBill AS TABLE(
	billNumberID        	NUMERIC (18),          
	ID                  	INT,                   
	ptypeid             	VARCHAR (50),          
	qty                 	NUMERIC (22,10),       
	comment             	VARCHAR (250),          -- 5
	GoodsBillNumberID   	NUMERIC (10),          
	GoodsBillID         	NUMERIC (10),          
	GoodsBillType       	INT,                   
	ItemID              	BIGINT,                
	IsCombined          	INT,                    -- 10
	GoodsNumber         	VARCHAR (100),         
	GoodsOrder          	INT,                   
	Serial              	TEXT,                  
	ProduceDate         	VARCHAR (50),          
	ValidDate           	VARCHAR (50),           -- 15
	ShowOrder           	INT,                   
	CargoID             	INT,
	MQty					NUMERIC(22,10),
	BillQty					NUMERIC(22,10),
	BillMQty				NUMERIC(22,10),
	MUnitId					INT,
	MUnitRate				NUMERIC(22,10),
	UnitID					INT
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_PhysicalBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_PhysicalIndexSave]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_PhysicalIndexSave;
	DROP TYPE Tb_PhysicalBill;
END
GO

CREATE TYPE Tb_PhysicalBill AS TABLE(
	[qty] [numeric](24, 10) ,
	[ItemID] [int] ,
	[IsCombined] [bit] ,
	[GoodsNumber] [varchar](100) ,
	[ProduceDate] [varchar](50) ,
	[ValidDate] [varchar](50) ,
	[CargoID] [int] ,
	[Serial] [varchar](max) ,
	[Nqty] [numeric](24, 10)
)
GO









IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_PickBill ' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertPickBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertPickBillDT;
	DROP TYPE Tb_PickBill ;
END
GO

CREATE TYPE Tb_PickBill  AS TABLE(
	billNumberID            NUMERIC (18),          
	ID                      INT,                   
	ptypeid                 VARCHAR (50),          
	qty                     NUMERIC (22,10),       
	comment                 VARCHAR (256),          -- 5
	GoodsBillNumberID       NUMERIC (10),          
	GoodsBillID             NUMERIC (10),          
	GoodsBillType           INT,                   
	ItemID                  BIGINT,                
	IsCombined              INT,                    -- 10
	GoodsNumber             VARCHAR (100),         
	GoodsOrder              INT,                   
	Serial                  TEXT,                  
	ProduceDate             VARCHAR (50),          
	ValidDate               VARCHAR (50),           -- 15
	ShowOrder               INT,                   
	CargoID                 INT,
	behooveQty				NUMERIC (22,10),
	BillQty					NUMERIC(22,10),
	MQty					NUMERIC(22,10),
	RMQty					NUMERIC(22,10),
	MUnitId					INT,
	MUnitRate				NUMERIC(22,10),
	UnitID					INT
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_Gp_PriceOrderSet' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tb_Gp_PriceOrderSet]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_PriceOrderSet;
	DROP TYPE Tb_Gp_PriceOrderSet;
END
GO

CREATE TYPE Tb_Gp_PriceOrderSet AS TABLE(
	PriceType			VARCHAR(200),  --价格类型
	[Priority]			INT	           --优先级
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_PriceRulePriority' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Web_SavePriceRulePriority]') AND TYPE in (N'P', N'PC'))
		DROP PROC Web_SavePriceRulePriority;
	DROP TYPE Tb_PriceRulePriority;
END
GO

CREATE TYPE Tb_PriceRulePriority AS TABLE(
	PriceRuleID		INT,			--价格规则ID
	--StypeID			varchar(50),	--分支机构ID
	SortID			INT				--排序ID		
)
GO






IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_QueryCustom' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Web_QueryCustomData]') AND TYPE in (N'P', N'PC'))
		DROP PROC Web_QueryCustomData;
	DROP TYPE Tb_QueryCustom;
END
GO

CREATE TYPE Tb_QueryCustom AS TABLE(
	BillNumberID		NUMERIC(10,0),	-- 单据 ID 值
	BillType			INT,  --单据类型
	ID					BIGINT, --明细ID
	OrderID				INT    --排序id			
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_SerialStockCheckBill ' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_StockSerialCheckHzBillAutoCaoGao]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_StockSerialCheckHzBillAutoCaoGao;
	DROP TYPE Tb_SerialStockCheckBill ;
END
GO

CREATE TYPE Tb_SerialStockCheckBill  AS TABLE(
	Serial			 VARCHAR(max),
	StockCheckSerial VARCHAR(max),
	KtypeID			 VARCHAR(100),
	PTypeID			VARCHAR(100),
	GoodsCostPrice	 NUMERIC(24, 10) ,
	GoodsNumber		VARCHAR(100),
	ProduceDate		VARCHAR(100),
	ValidDate		VARCHAR(100),
	SQty			 NUMERIC(24, 10) ,
	StockCheckID	INT,
	qty				 NUMERIC(24, 10) ,
	newNO			VARCHAR(3000),
	CargoID			INT,
	ItemID			INT,
	IsCombined		INT,
	nqty			 NUMERIC(24, 10) ,
	snqty			 NUMERIC(24, 10)
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_StockAllotBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertStockAllotBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertStockAllotBillDT;
	DROP TYPE Tb_StockAllotBill;
END
GO

CREATE TYPE Tb_StockAllotBill AS TABLE(
[BillNumberId] [int],
[Serial] VARCHAR(max),
[KTypeId] [varchar] (50) ,
[KTypeId2] [varchar] (50),
[PtypeId] [varchar] (50) ,
[ItemID] [bigint] NULL,
[NUnitID] [int] ,
[Qty] [numeric] (24, 10) ,
[UnitID] [int] ,
[UnitRate] [numeric] (24, 10) ,
[NQty] [numeric] (24, 10),
[NUnitMsg] [varchar] (50) ,
[MUnitID] [int] ,
[MQty] [numeric] (24, 10),
[MUnitRate] [numeric] (24, 10),
[MUnitMsg] [varchar] (50) ,
[IsCombined] [int] ,
[GoodsOrder] [int] ,
[GoodsNumber] [varchar] (100) ,
[ProduceDate] [varchar] (50) ,
[ValidDate] [varchar] (50) ,
[InCargoID] [int],
[OutCargoID] [int] ,
[Comment] [varchar] (256) 	
)
GO






IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_StockIoutBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertStockIoutBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertStockIoutBillDT;
	DROP TYPE Tb_StockIoutBill;
END
GO

CREATE TYPE Tb_StockIoutBill AS TABLE(
	[BillNumberID] [int] ,
	[BillType] [int] ,
	[billdate] [varchar](50),
	[stypeid] [varchar](50),
	[ptypeid] [varchar](50) ,
	[ktypeid] [varchar](50) ,
	[qty] [numeric](24, 10) ,
	[UnitID] [int] ,
	[UnitRate] [numeric](24, 10) ,
	[NQty] [numeric](24, 10) ,
	[NUnitID] [int] ,
	[NUnitMsg] [varchar](50) ,
	[MUnitID] [int] ,
	[MQty] [numeric](24, 10) ,
	[MUnitRate] [numeric](24, 10) ,
	[MUnitMsg] [varchar](50) ,
	[ItemID] [int] ,
	[IsCombined] [int] ,
	[GoodsOrder] [int] ,
	[GoodsNumber] [varchar](100) ,
	[ProduceDate] [varchar](50) ,
	[ValidDate] [varchar](50) ,
	[CargoID] [int] ,
	[FromBillID] [int] ,
	[FromBillNumberID] [int] ,
	[FromBillType] [int] ,
	[Serial] [varchar](max) ,
	[comment] [varchar](250) ,
	[entryCode] [varchar](50) 
)
GO







IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_VirtualStock ' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Web_QueryCompareVirtualStock]') AND TYPE in (N'P', N'PC'))
		DROP PROC Web_QueryCompareVirtualStock;
	DROP TYPE TbType_VirtualStock ;
END
GO

CREATE TYPE TbType_VirtualStock AS TABLE(
	KTypeId			VARCHAR(50),		--仓库ID
	PTypeId			VARCHAR(50),		--商品ID
	ProduceDate		VARCHAR(50),		--生产日期
	ValidDate		VARCHAR(50),		--效期至
	ItemID			INT,				--自由项
	GoodsNumber		VARCHAR(100),		--批号
	CargoID			INT,				--货位
	Qty				NUMERIC (24,10),	--数量
	Unit			INT,				--单位关系
	GoodsCostPrice	NUMERIC(24, 10), 	--批次成本价
	orderid			VARCHAR(100)	--引用的订单id
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Tb_WmsTask' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_WmsTaskToBuyBill]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_WmsTaskToBuyBill;
	DROP TYPE Tb_WmsTask;
END
GO

CREATE TYPE Tb_WmsTask AS TABLE(
	billnumberid	INT NOT NULL,		--单据id
	billtype		INT NOT NULL,		--单据类型
	detailid		INT NOT NULL,		--erp订单明细id
	qty				NUMERIC(24,10) NOT NULL,	--任务完成数量
	wmstaskid		VARCHAR(50)			--wms任务id
)
GO





/*
	作者：唐韬
	时间：2014-06-16 11:43:02.953
	描述：凭证模板明细之辅助核算明细
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_Ac_Auditing_Template_Detail_Assist_CheckItems' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertAc_Auditing_Template_DetailDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertAc_Auditing_Template_DetailDT
	DROP TYPE TbType_Ac_Auditing_Template_Detail_Assist_CheckItems
END
GO

CREATE TYPE TbType_Ac_Auditing_Template_Detail_Assist_CheckItems AS TABLE(
AtdId INT,--模版明细ID
ATID INT ,--模版主表ID
AscIds INT ,--辅助核算主表ID,
AscIdsDetailId INT  --辅助核算明细表ID	
)
GO







IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_AccountCredence' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertAccountCredenceDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertAccountCredenceDT;
	DROP TYPE TbType_AccountCredence;
END
GO
/*
	作者：周华
	时间：2012-06-13 10:00:00
	描述：会计凭证写入对应dt
*/
CREATE TYPE TbType_AccountCredence AS TABLE(
	[TypeATypeID] VARCHAR(25)
	,[ATypeID] VARCHAR(50)
	,[J_Total]  NUMERIC(24, 10) 
	,[D_Total]  NUMERIC(24, 10) 
	,[comment] VARCHAR(256)
	,NJ_Total  NUMERIC(24, 10) 
	,ND_Total  NUMERIC(24, 10) 
	,Cid INT
	,Rate  NUMERIC(24, 10)
	,BrandarTypeId VARCHAR(50)
	,EtypeID	varchar(50)
	,DtypeID	varchar(50)
);
GO





/*
	作者：吴雷
	时间：2014.05.16
	描述：未达账明细使用
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_AccountInTransit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_SaveTeAccountInTransit]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_SaveTeAccountInTransit;
	DROP TYPE TbType_AccountInTransit;
END
GO

CREATE TYPE TbType_AccountInTransit AS TABLE(
	RowId		INT,															--明细id
	CreateDate	DATETIME,														--业务日期
	Summary		VARCHAR(1000) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT(''),	--摘要
	ETypeId		VARCHAR(50),													--经手人
	FSettleId	INT,															--结算方式
	FSettleNo	VARCHAR(50),													--结算号
	FDebit		 NUMERIC(24, 10) ,													--借方
	FCredit		 NUMERIC(24, 10) 													--贷方
)
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_AccountMultiLevelEdit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_AccountMultiLevelEdit]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_AccountMultiLevelEdit;
	DROP TYPE TbType_AccountMultiLevelEdit;
END
GO
/*
	作者：杨俊	
	时间：2014-11-20
	描述：会计科目多级权限修改对应table
*/
CREATE TYPE TbType_AccountMultiLevelEdit AS TABLE
(
	typeid VARCHAR(500),		--科目
	flag INT					--是否有权限
	--stypeid VARCHAR(50),		--分支机构
	--parid VARCHAR(50),		--父节点
	--soncount INT,				--子节点数量
	--leveal INT,				--等级
	--etypeid VARCHAR(50)		--职员 
)
GO




/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_AdDebt' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertAdDebtBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertAdDebtBillDT;
	DROP TYPE TBType_AdDebt;
END
GO

CREATE TYPE dbo.TBType_AdDebt AS TABLE
(
	BillNumberId  [numeric](10,0),
	BtypeId  [varchar](50),
	Total    NUMERIC(24, 10) ,
	Comment  [varchar](256),
	STypeID  [varchar](50) DEFAULT(''),
	--9.0新加字段
	NTOTAL  NUMERIC(24, 10) ,
	[NCompleteTotal]  NUMERIC(24, 10)   DEFAULT (0),
	CompleteTotal  NUMERIC(24, 10)   DEFAULT (0),
	ShowOrder INT,
	AlertDay INT DEFAULT(9999),
	brandartypeid VARCHAR(50)
) 
GO



/*
	作者：周华
	时间：2012-05-24 
	描述：成本调价单明细保存dt版表类型 
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_AdPrice' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertAdPriceBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertAdPriceBillDT;
	DROP TYPE TbType_AdPrice;
END
GO
CREATE TYPE TbType_AdPrice AS TABLE(
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10) ,
	Price   		 NUMERIC(24, 10) ,
	Total   		 NUMERIC(24, 10) ,
	Comment  		[varchar](256),
	intisUnit2 	[int],
	ChangeAllStock [int],    			--是否修改所有商品的成本
	InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	--成本单价
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),				-- 手工指定成本单价
	BeforePrice	VARCHAR(MAX),		--调价前单价
	BeforeTotal	VARCHAR(MAX),		--调价前金额
	AdRate		 NUMERIC(24, 10) 		--调价比率
	
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined BIT
	,CargoId INT
	,ktypeid VARCHAR(50)
	,Serial  VARCHAR(MAX)
	,NTotal  NUMERIC(24, 10) 
	,NPrice  NUMERIC(24, 10) 
	,frombillid  INT
	,ShowOrder INT
	,ChangeTotal NUMERIC(24,10) DEFAULT(0)
);
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Advantage' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertAdvantageBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertAdvantageBillDT;
	DROP TYPE TBType_Advantage;
END
GO

CREATE TYPE dbo.TBType_Advantage AS TABLE
( 
	BillNumberID		numeric(10,0),	-- 单据 ID 值
	Serial             varchar(100),
	PtypeID			varchar(50),	-- 商品 ID 值
	StartDate          datetime,
	EndDate            datetime,
	StandardCode       varchar(50),
	Type               int,
	Qty                 NUMERIC(24, 10) ,
	Total               NUMERIC(24, 10) ,
	Comment            varchar(255) ,
	BillType			int,
	STypeID			varchar(50) DEFAULT(''),
	--9.0新加字段	
	ITEMID		BIGINT,
	IsCombined		INT,
	GoodsNumber	 VARCHAR(100)
) 
GO




























GO

IF EXISTS (SELECT Name FROM Systypes WHERE name=N'TbType_AppraisalBackBill' AND XType=243)
BEGIN
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.Gp_InsertAppraisalBackBillDT',N'P'))
	BEGIN
		DROP PROC dbo.Gp_InsertAppraisalBackBillDT
	END
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertAppraisalBackBillDTCheck',N'P'))
	BEGIN
		DROP PROC dbo.GP_InsertAppraisalBackBillDTCheck
	END
	
	DROP TYPE dbo.TbType_AppraisalBackBill
END
GO

/*
			作者：司华山
			日期：2015-05-14
			描述：暂估退货表类型
*/

CREATE TYPE dbo.TbType_AppraisalBackBill AS TABLE(
				[BillNumberId] [numeric](10, 0) NOT NULL,
				[PtypeId] [varchar](50) NULL,
				[Qty]  NUMERIC(24, 10)  NULL,
				[SalePrice]  NUMERIC(24, 10)  NULL,
				[discount]  NUMERIC(24, 10)  NULL,
				[DiscountPrice]  NUMERIC(24, 10)  NULL,
				[costprice]  NUMERIC(24, 10)  NULL,
				[total]  NUMERIC(24, 10)  NULL,
				[TaxPrice]  NUMERIC(24, 10)  NULL,
				[TaxTotal]  NUMERIC(24, 10)  NULL,
				[comment] [varchar](255) NULL,
				[TeamNo] [int] NULL,
				[TeamNo1] [int] NULL,
				[Serial] [varchar](max) NULL,
				[OldID] [varchar](50) NULL,
				[OldBillNumberID] [numeric](18, 0) NULL,
				[InputCostPrice]  NUMERIC(24, 10)  NULL,
				[GoodsOrder] [int] NULL,
				[GoodsNumber] [varchar](100) NULL,
				[ProduceDate] [varchar](50) NULL,
				[ValidDate] [varchar](50) NULL,
				[GoodsCostPrice]  NUMERIC(24, 10)  NULL,
				[HandZeroCost] [int] NULL,
				[SaleTotal]  NUMERIC(24, 10)  NULL,
				[Tax]  NUMERIC(24, 10)  NULL,
				[KTypeID] [varchar](50) NULL,
				[Stypeid] [varchar](50) NULL,
				[TaxMoney]  NUMERIC(24, 10)  NULL,
				[NSalePrice]  NUMERIC(24, 10)  NULL,
				[NSaleTotal]  NUMERIC(24, 10)  NULL,
				[NDiscountPrice]  NUMERIC(24, 10)  NULL,
				[NTotal]  NUMERIC(24, 10)  NULL,
				[NTaxPrice]  NUMERIC(24, 10)  NULL,
				[NTaxTotal]  NUMERIC(24, 10)  NULL,
				[NTaxMoney]  NUMERIC(24, 10)  NULL,
				[UnitID] [int] NULL,
				[NUnitID] [int] NULL,
				[NQty]  NUMERIC(24, 10)  NULL,
				[UnitRate]  NUMERIC(24, 10)  NULL,
				[NUnitMsg] [varchar](50) NULL,
				[MUnitID] [int] NULL,
				[MQty]  NUMERIC(24, 10)  NULL,
				[MUnitRate]  NUMERIC(24, 10)  NULL,
				[MUnitMsg] [varchar](50) NULL,
				[MSalePrice]  NUMERIC(24, 10)  NULL,
				[MDiscountPrice]  NUMERIC(24, 10)  NULL,
				[MTaxPrice]  NUMERIC(24, 10)  NULL,
				[CurMSalePrice]  NUMERIC(24, 10)  NULL,
				[CurMDiscountPrice]  NUMERIC(24, 10)  NULL,
				[CurMTaxPrice]  NUMERIC(24, 10)  NULL,
				[CargoID] [int] NULL,
				[ItemID] [bigint] NULL,
				[IsCombined] [int] NULL,
				[InvoiceQty]  NUMERIC(24, 10)  NULL,
				[InvoiceMoney]  NUMERIC(24, 10)  NULL,
				[NInvoiceMoney]  NUMERIC(24, 10)  NULL,
				[IsGift] [int] NULL,
				[PriceStyle] [int] NOT NULL,
				[InvoiceCostTotal]  NUMERIC(24, 10)  NULL,
				[InvoiceMoneyEX]  NUMERIC(24, 10)  NULL,
				[NInvoiceMoneyEX]  NUMERIC(24, 10)  NULL,
				[InvoiceNQty]  NUMERIC(24, 10)  NULL,
				[CostTotal]   NUMERIC(24, 10)  NULL,
				[InvoiceSaleMoney]  NUMERIC(24, 10)  NULL,
				[NInvoiceSaleMoney]  NUMERIC(24, 10)  NULL,
				[ShareFee]  NUMERIC(24, 10)  NULL,
				[ShowOrder]		INT,
				[ID]			INT,
			    PriceSource VARCHAR(200)
)
GO



GO 


IF EXISTS (SELECT * FROM Systypes WHERE Name=N'TbType_AppraisalBill')
BEGIN
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertAppraisalBillDT',N'P'))
	BEGIN
		DROP PROC dbo.GP_InsertAppraisalBillDT
	END
	DROP TYPE dbo.TbType_AppraisalBill
END
GO

/*
			作者：司华山
			日期：2015-05-14
			描述：暂估入库单表类型
*/

CREATE TYPE dbo.TbType_AppraisalBill AS TABLE
(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty]  NUMERIC(24, 10)  NULL,
		[SalePrice]  NUMERIC(24, 10)  NULL,
		[discount]  NUMERIC(24, 10)  NULL,
		[DiscountPrice]  NUMERIC(24, 10)  NULL,
		[total]  NUMERIC(24, 10)  NULL,
		[TaxPrice]  NUMERIC(24, 10)  NULL,
		[TaxTotal]  NUMERIC(24, 10)  NULL,
		[comment] [varchar](255) NULL,
		[TeamNo1] [int] NULL,
		[TeamNo] [int] NULL,
		[orderid] [int] NOT NULL,
		[Serial] [varchar](max) NULL,
		[InputCostPrice]  NUMERIC(24, 10)  NULL,
		[GoodsOrder] [int] NULL,
		[BackQty]  NUMERIC(24, 10)  NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice]  NUMERIC(24, 10)  NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal]  NUMERIC(24, 10)  NULL,
		[Tax]  NUMERIC(24, 10)  NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney]  NUMERIC(24, 10)  NULL,
		[NSalePrice]  NUMERIC(24, 10)  NULL,
		[NSaleTotal]  NUMERIC(24, 10)  NULL,
		[NDiscountPrice]  NUMERIC(24, 10)  NULL,
		[NTotal]  NUMERIC(24, 10)  NULL,
		[NTaxPrice]  NUMERIC(24, 10)  NULL,
		[NTaxTotal]  NUMERIC(24, 10)  NULL,
		[NTaxMoney]  NUMERIC(24, 10)  NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty]  NUMERIC(24, 10)  NULL,
		[UnitRate]  NUMERIC(24, 10)  NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty]  NUMERIC(24, 10)  NULL,
		[MUnitRate]  NUMERIC(24, 10)  NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice]  NUMERIC(24, 10)  NULL,
		[MDiscountPrice]  NUMERIC(24, 10)  NULL,
		[MTaxPrice]  NUMERIC(24, 10)  NULL,
		[CurMSalePrice]  NUMERIC(24, 10)  NULL,
		[CurMDiscountPrice]  NUMERIC(24, 10)  NULL,
		[CurMTaxPrice]  NUMERIC(24, 10)  NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[entryCode] [varchar](200) NULL,
		[InvoiceQty]  NUMERIC(24, 10)  NULL,
		[InvoiceMoney]  NUMERIC(24, 10)  NULL,
		[NInvoiceMoney]  NUMERIC(24, 10)  NULL,
		[IsGift] [int] NULL,
		[InvoiceMoneyEX]  NUMERIC(24, 10)  NULL,
		[NInvoiceMoneyEX]  NUMERIC(24, 10)  NULL,
		[InvoiceCostTotal]  NUMERIC(24, 10)  NULL,
		[InvoiceNQty]  NUMERIC(24, 10)  NULL,
		[InvoiceSaleMoney]  NUMERIC(24, 10)  NULL,
		[NInvoiceSaleMoney]  NUMERIC(24, 10)  NULL,
		[ShareFee]  NUMERIC(24, 10)  NULL,
		[OldBillNumberID] numeric(10,0) NULL,
		[OldID]	numeric(10,0) NULL,
		[ShowOrder]		INT,
		[ID]			INT,
		PriceSource VARCHAR(200)
)

GO





GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_AskPrice' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertAskPriceBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertAskPriceBillDT;
	DROP TYPE TbType_AskPrice;
END
GO

/*
	作者：周华
	时间：2012-05-04 09:42:48.077
	描述：询价单明细查入 对应的 表类型
*/
CREATE TYPE [dbo].[TbType_AskPrice] AS TABLE(
	[BillNumberID] INT NULL,
	[PtypeID] [varchar](50) NULL,
	[Qty]  NUMERIC(24, 10)  NULL,
	[Price]  NUMERIC(24, 10)  NULL,
	[SaleTotal]  NUMERIC(24, 10)  NULL,
	[Discount]  NUMERIC(24, 10)  NULL,
	[DiscountPrice]  NUMERIC(24, 10)  NULL,
	[Total]  NUMERIC(24, 10)  NULL,
	[Tax]  NUMERIC(24, 10)  NULL,
	[TaxPrice]  NUMERIC(24, 10)  NULL,
	[TaxTotal]  NUMERIC(24, 10)  NULL,
	[Comment] [varchar](255) NULL,
	[IsUnit2] [int] NULL,
	[STypeID] [varchar](50) NULL DEFAULT (''),
	[TaxMoney]  NUMERIC(24, 10)  NULL,
	[NSalePrice]  NUMERIC(24, 10)  NULL,
	[NSaleTotal]  NUMERIC(24, 10)  NULL,
	[NDiscountPrice]  NUMERIC(24, 10)  NULL,
	[NTotal]  NUMERIC(24, 10)  NULL,
	[NTaxPrice]  NUMERIC(24, 10)  NULL,
	[NTaxTotal]  NUMERIC(24, 10)  NULL,
	[NTaxMoney]  NUMERIC(24, 10)  NULL,
	[UnitId] [int] NULL,
	[NUnitId] [int] NULL,
	[NQty]  NUMERIC(24, 10)  NULL,
	[UnitRate]  NUMERIC(24, 10)  NULL,
	[NUnitMsg] [varchar](50) NULL,
	[MUnitId] [int] NULL,
	[MQty]  NUMERIC(24, 10)  NULL,
	[MUnitRate]  NUMERIC(24, 10)  NULL,
	[MUnitMsg] [varchar](50) NULL,
	[MSalePrice]  NUMERIC(24, 10)  NULL,
	[MDiscountPrice]  NUMERIC(24, 10)  NULL,
	[MTaxPrice]  NUMERIC(24, 10)  NULL,
	[CurMSalePrice]  NUMERIC(24, 10)  NULL,
	[CurMDiscountPrice]  NUMERIC(24, 10)  NULL,
	[CurMTaxPrice]  NUMERIC(24, 10)  NULL,
	[ItemId] [bigint] NULL,
	[IsCombined] [int] NULL,
	[IfBargainOn] [INT] NULL,
	[ShowOrder]		INT,
	[PriceSource] VARCHAR(200)
)
GO







/*
	作者：周华
	时间：2013-05-20 11:04:03.030
	描述：固定资产减少单明细保存结构
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_AssetDec' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertFixedReduceDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertFixedReduceDT;
	DROP TYPE TbType_AssetDec;
END
GO

CREATE TYPE TbType_AssetDec AS TABLE(
	BillNumberId INT
	,AssetCardId INT 
	,BillType INT
	,NTotal  NUMERIC(24, 10) 
	,Total  NUMERIC(24, 10) 
	,Tax  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,TaxMoney  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,TaxTotal  NUMERIC(24, 10) 
	,NNetValue  NUMERIC(24, 10) 
	,NetValue  NUMERIC(24, 10) 
	,Comment VARCHAR(255)
)
GO





/*
	作者：周华
	时间：2013-05-20 11:04:03.030
	描述：固定资产折旧单明细保存结构
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_AssetDep' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertAssetDepDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertAssetDepDT;
	DROP TYPE TbType_AssetDep;
END
GO

CREATE TYPE TbType_AssetDep AS TABLE(
	BillNumberId INT
	,AssetCardId INT 
	,Depreciation  NUMERIC(24, 10) 
	,Comment VARCHAR(255)
	,WorkTime  NUMERIC(24, 10) 
	,WorkUnit VARCHAR(500)
	,Dtypeid VARCHAR(500)
)
GO





/*
	作者：周华
	时间：2013-05-20 10:52:12.523
	描述：固定资产增加单明细保存结构
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_AssetInc' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertFixedAddDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertFixedAddDT;
	DROP TYPE TbType_AssetInc;
END
GO

CREATE TYPE TbType_AssetInc AS TABLE(
	BillNumberId INT
	,AssetCardId INT 
	,BillType INT
	,NTotal  NUMERIC(24, 10) 
	,Total  NUMERIC(24, 10) 
	,Tax  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,TaxMoney  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,TaxTotal  NUMERIC(24, 10) 
	,NDepTotal  NUMERIC(24, 10) 
	,DepTotal  NUMERIC(24, 10) 
	,Comment VARCHAR(255)
)
GO






IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_BaseInfoCustom' AND ss.name = N'dbo')
BEGIN
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ImportCustomers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		drop procedure [dbo].[Gp_ImportCustomers]
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ImportEmployee]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		drop procedure [dbo].[Gp_ImportEmployee]
	DROP TYPE TbType_BaseInfoCustom
END
GO

CREATE TYPE TbType_BaseInfoCustom AS TABLE(
EditKind			VARCHAR(50) ,				--数据类型
label				VARCHAR(50),				--属性名称
datafield			VARCHAR(50),				-- 数据库对应字段
maxbytelength		int     --长度
)
GO




/*
	作者：吴雷
	时间：2012-09-21
	描述：导入的凭证模板数据
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_BillAtype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_ImportBillAtype]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_ImportBillAtype;
	DROP TYPE TbType_BillAtype;
END
GO

CREATE TYPE TbType_BillAtype AS TABLE(
	SfullName	VARCHAR(200),	--分支机构名称
	BillName	VARCHAR(100),	--结转科目项、存货科目项或单据名称
	UserCode	VARCHAR(100),	--科目编号
	FullName	VARCHAR(200)	--科目名称		
)
GO




/*
	By: Haiyang, Li
	Date: 2012-10-30
	Description: 单据分时记录函数
*/
IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TbType_BillSaveTimeLog'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    sys.objects
                    WHERE   object_id = OBJECT_ID(N'[dbo].[GP_InsertBillSaveTimeLog]')
                            AND TYPE IN ( N'P', N'PC' ) ) 
            DROP PROC GP_InsertBillSaveTimeLog;
        DROP TYPE TbType_BillSaveTimeLog;
    END
GO

CREATE TYPE TbType_BillSaveTimeLog AS TABLE(
	BillTypeID		INT NOT NULL ,					-- 单据类型	
	BillCode		VARCHAR(100) NOT NULL ,		-- 单据编号
	FunctionOrder INT,										-- 方法调用顺序
	FunctionName	VARCHAR(100) NOT NULL , -- 方法名称
	Elapsed			INT NOT NULL							-- 耗时(毫秒)
)
GO





/*
	作者：周华
	时间：2012-05-03 09:18:19.193
	描述：把单据明细保存存储过程dt版要用到的自定义表类型
	2012-11-15 修改entrycode 长度为200
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_Buy' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertBuyBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertBuyBillDT;
	DROP TYPE TbType_Buy;
END
GO

CREATE TYPE TbType_Buy AS TABLE(
	BillNumberID		NUMERIC(10,0),	-- 单据 ID 值
	PtypeID		VARCHAR(50),	-- 商品 ID 值
	Qty			 NUMERIC(24, 10) ,	-- 商品数量
	SalePrice		 NUMERIC(24, 10) ,	-- 商品单价
	Discount		 NUMERIC(24, 10) ,	-- 扣率
	DiscountPrice		 NUMERIC(24, 10) ,	-- 折后单价
	Jobno			VARCHAR(20),
	Total			 NUMERIC(24, 10) ,	-- 商品金额
	MakeDate		DATETIME,	-- 单据日期
	TaxPrice		 NUMERIC(24, 10) ,	-- 税后单价
	TaxTotal		 NUMERIC(24, 10) ,	-- 价税合计
	Comment		VARCHAR(255),	-- 备注
	OrderID		INT DEFAULT(-1),	-- 订单编号
	intIsUnit2		INT,		-- 是否采用双单位。0：否；1：是
	--@Serial			varchar(50)	-- 序列号值
	Serial			VARCHAR(MAX),	-- 序列号值
	GoodsNumber	VARCHAR(100) DEFAULT(''),	-- 批号
	ProduceDate	VARCHAR(50) DEFAULT(''),	-- 生产日期
	ValidDate		VARCHAR(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	VARCHAR(50) DEFAULT(''),	-- 供货商ID值
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	KTypeID		VARCHAR(50) DEFAULT(''),
	STypeID			VARCHAR(50) DEFAULT(''),
	FromBillNumberID	NUMERIC(10,0) DEFAULT(0),
	FromBillID			NUMERIC(10,0) DEFAULT(0)
	
	-- 新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQty  NUMERIC(24, 10) 
	,entryCode VARCHAR(200)
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,IsGift INT
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,LendBillID		NUMERIC(10,0)
	,LendBillNumberID		NUMERIC(10,0)
	,ID INT
	,ShowOrder INT
	,AskBillID INT
	,AskBillNumberID INT
	,[PriceSource] VARCHAR(200)
)
GO





/*
	作者：周华
	时间：2012-05-03 09:18:19.193
	描述：把单据明细保存存储过程dt版要用到的自定义表类型
	2012-11-15 修改entrycode 长度为200
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_BuyAutoDraft' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertBuyBillAutoDraftDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertBuyBillAutoDraftDT;
	DROP TYPE TbType_BuyAutoDraft;
END
GO

CREATE TYPE TbType_BuyAutoDraft AS TABLE(
	BillGuid			VARCHAR(100),   --单据Guid
	BillNumberID		NUMERIC(10,0),	-- 单据 ID 值
	PtypeID		VARCHAR(50),	-- 商品 ID 值
	Qty			 NUMERIC(24, 10) ,	-- 商品数量
	SalePrice		 NUMERIC(24, 10) ,	-- 商品单价
	Discount		 NUMERIC(24, 10) ,	-- 扣率
	DiscountPrice		 NUMERIC(24, 10) ,	-- 折后单价
	Jobno			VARCHAR(20),
	Total			 NUMERIC(24, 10) ,	-- 商品金额
	MakeDate		DATETIME,	-- 单据日期
	TaxPrice		 NUMERIC(24, 10) ,	-- 税后单价
	TaxTotal		 NUMERIC(24, 10) ,	-- 价税合计
	Comment		VARCHAR(255),	-- 备注
	OrderID		INT DEFAULT(-1),	-- 订单编号
	intIsUnit2		INT,		-- 是否采用双单位。0：否；1：是
	--@Serial			varchar(50)	-- 序列号值
	Serial			VARCHAR(MAX),	-- 序列号值
	GoodsNumber	VARCHAR(100) DEFAULT(''),	-- 批号
	ProduceDate	VARCHAR(50) DEFAULT(''),	-- 生产日期
	ValidDate		VARCHAR(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	VARCHAR(50) DEFAULT(''),	-- 供货商ID值
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	KTypeID		VARCHAR(50) DEFAULT(''),
	STypeID			VARCHAR(50) DEFAULT(''),
	FromBillNumberID	NUMERIC(10,0) DEFAULT(0),
	FromBillID			NUMERIC(10,0) DEFAULT(0)
	
	-- 新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQty  NUMERIC(24, 10) 
	,entryCode VARCHAR(200)
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,IsGift INT
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,LendBillID		NUMERIC(10,0)
	,LendBillNumberID		NUMERIC(10,0)
	,ID INT
	,ShowOrder INT
	,AskBillID INT
	,AskBillNumberID INT
	,[PriceSource] VARCHAR(200)
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_BuyBack' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertBuyBackBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertBuyBackBillDT;
	DROP TYPE TbType_BuyBack;
END
GO

/*
	作者：周华
	时间：2012-05-03 15:15:58.937
	描述：采购退货单明细对应 表类型
*/

CREATE TYPE TbType_BuyBack AS TABLE(
	BillNumberId  	[numeric](10,0),
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10) ,
	SalePrice  		 NUMERIC(24, 10) ,
	Discount  		 NUMERIC(24, 10) ,
	DiscountPrice 	 NUMERIC(24, 10) ,
	JobNo   		[varchar](20),
	Total   		 NUMERIC(24, 10) ,
	MakeDate  		[datetime],
	TaxPrice  		 NUMERIC(24, 10) ,
	TaxTotal  		 NUMERIC(24, 10) ,
	Comment        	[varchar](255),
	intIsUnit2 		[int],
	Serial				VARCHAR(MAX),	-- 序列号
	OldID  			[varchar](20) DEFAULT(''),
	OldBillNumberID  	[numeric](10,0)DEFAULT(0),
	InputCostPrice		 NUMERIC(24, 10)  DEFAULT(0),
	GoodsNumber	VARCHAR(100) DEFAULT(''),	
	ProduceDate	VARCHAR(50) DEFAULT(''),	
	ValidDate		VARCHAR(50) DEFAULT(''),	
	GoodsBTypeID	VARCHAR(50) DEFAULT(''),	
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	
	HandZeroCost	INT DEFAULT(0),			
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	KTypeID		VARCHAR(50) DEFAULT(''),
	STypeID			VARCHAR(50) DEFAULT('')
	-- 新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQty  NUMERIC(24, 10) 
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,IsGift INT
	,PriceStyle INT NOT NULL DEFAULT(0)
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,ID INT
	,ShowOrder INT
	,[PriceSource] VARCHAR(200)
);
GO





GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_BuyBackCheck' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertBuyBackBillDTCheck]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertBuyBackBillDTCheck;
	DROP TYPE TbType_BuyBackCheck;
END
GO

/*
	作者：周华
	时间：2012-05-03 15:15:58.937
	描述：采购退货单明细验证对应 表类型
*/
CREATE TYPE TbType_BuyBackCheck AS TABLE(
	OldBillNumberID  	[numeric](10,0)DEFAULT(0),
	OldID  			[varchar](20) DEFAULT(''),
	Qty   			 NUMERIC(24, 10) 
);
GO




GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_BuyGoodsExchange' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertBuyGoodsExchangeBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertBuyGoodsExchangeBillDT;
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'GP_BuyGoodsExchangeCheck',N'P'))
		DROP PROC Gp_BuyGoodsExchangeCheck
	DROP TYPE TbType_BuyGoodsExchange;
END
GO
/*
	作者：周华
	时间：2012-05-03 16:58:13.333
	描述：采购换货单明细对应 表类型
*/
CREATE TYPE TbType_BuyGoodsExchange AS TABLE(
	BillNumberId  	[numeric](10,0),
	InOrOut  		[char](1),
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10) ,
	SalePrice  	 NUMERIC(24, 10) ,
	Discount  		 NUMERIC(24, 10) ,
	DiscountPrice   NUMERIC(24, 10) ,
	Jobnumber  	[varchar](20),
	Total   		 NUMERIC(24, 10) ,
	OutFactoryDate [datetime] ,
	TaxPrice  		 NUMERIC(24, 10) ,
	TaxTotal  		 NUMERIC(24, 10) ,
	Comment  		[varchar](255),
	intisUnitTow 	[int],
	--	@Serial		varchar(50)
	Serial			VARCHAR(MAX),				-- 序列号值
	InputCostPrice  NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),			-- 手工指定成本单价
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	KTypeID		varchar(50) DEFAULT(''),
	STypeID		varchar(50) DEFAULT('')

	-- 新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQty  NUMERIC(24, 10) 
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,IsGift INT
	,OldID  			VARCHAR(20) DEFAULT('')  			
	,OldBillNumberID  	NUMERIC(10,0) DEFAULT(0)
	,CompleteTotal       NUMERIC(24, 10) 
	,NCompleteTotal      NUMERIC(24, 10)  		
	,ShowOrder	INT	
	,[PriceSource] VARCHAR(200)
);
GO




GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_BuyRequest' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertIntoRequestBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertIntoRequestBillDT;
	DROP TYPE TbType_BuyRequest;
END
GO
/*
	作者：周华
	时间：2012-05-04 09:26:48.117
	描述：请购单明细查入 对应的 表类型
*/
CREATE TYPE TbType_BuyRequest AS TABLE(
	BillNumberId			NUMERIC(10, 0),	 --单据编号
	PtypeId				VARCHAR(50),	 --商品编号
	Qty					 NUMERIC(24, 10)  , --数量
	SalePrice				 NUMERIC(24, 10) ,	 --折前单价
	discount				 NUMERIC(24, 10) ,	 --折扣
	DiscountPrice			 NUMERIC(24, 10) ,	 --折后单价
	total					 NUMERIC(24, 10) ,	 --折后金额
	TaxPrice				 NUMERIC(24, 10) ,	 --含税单价
	TaxTotal				 NUMERIC(24, 10)  , --含税金额
	comment				VARCHAR(255),	 --备注
	SaleTotal				 NUMERIC(24, 10)  , --折前金额
	Tax					 NUMERIC(24, 10) ,	 --税率
	Stypeid				VARCHAR(50) ,	 --分支机构
	RequestDate			DATETIME,		 --需求时间
	OrderDate				DATETIME,		 --建议订购时间
	Btypeid				VARCHAR(50),	 --建议供货商
	[State]					TINYINT,		 --状态
	compareprice			 NUMERIC(24, 10) ,	 -- 比价单价
	Etypeid				VARCHAR(50)	 --职员
	
	-- 新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,ShowOrder INT
	,PriceSource VARCHAR(200)
);
GO




/*
	作者：周华
	时间：2014-05-23 11:12:34.437
	描述：资金调拨单明细保存结构
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_CapitalTransfer' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertCapitalTransferAddDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertCapitalTransferAddDT;
	DROP TYPE TbType_CapitalTransfer;
END
GO

CREATE TYPE TbType_CapitalTransfer AS TABLE(
	BillNumberId INT
	,BankAccountOut VARCHAR(50)
	,[BankAccountIn] VARCHAR(50)
	,[TransferPrice]  NUMERIC(24, 10) 
	,[NTransferPrice]  NUMERIC(24, 10) 
	,DeductPrice  NUMERIC(24, 10) 
	,NDeductPrice  NUMERIC(24, 10) 
	,Comment VARCHAR(255)
)
GO




/*
	作者：施训果
	时间：
	描述：货位明细保存dt版表类型 
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_Cargo' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCargo]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCargo;
	DROP TYPE TbType_Cargo;
END
GO
CREATE TYPE TbType_Cargo AS TABLE(
	UserCode  		varchar(200),
	FullName   		varchar(200) ,
	KtypeID   		varchar(50) ,
	Comment			varchar(500) ,
	PyCode			varchar(200),
	IsDefault		INT,
	XiWaMaxNumber	Numeric(18,0),
	PathNo          INT NULL
);
GO




/*
	作者：施训果
	时间：
	描述：往来核销单的数据类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_ChargeOff' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertChargeOffBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertChargeOffBillDT;
	DROP TYPE TbType_ChargeOff;
END
GO

CREATE TYPE TbType_ChargeOff AS TABLE(
		  BillNumberID	NUMERIC(10,0),	-- 单据 ID 值
          FromBillNumberid  NUMERIC(10,0),
          ChargeOffType int,
          IsCharged tinyint,
          BTypeID varchar(50),
          ChargeOffValue NUMERIC(24,10),
          NChargeOffValue NUMERIC(24,10),
          FromBillType Numeric(4,0),
		  FromBillID INT DEFAULT 0,
		  TeamNo INT DEFAULT 0,
		  Comment VARCHAR(2000),
		  ShowOrder INT
	)
GO





/*
	作者
	时间：2012-05-03 09:18:19.193
	描述：把单据明细保存存储过程dt版要用到的自定义表类型
	2012-11-15 修改entrycode 长度为200
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_ClearDetail' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_DoLock]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_DoLock;
	DROP TYPE TbType_ClearDetail;
END
GO

CREATE TYPE TbType_ClearDetail AS TABLE(
	BillNumberID		NUMERIC(10,0),	-- 单据 ID 值
	OrderID		INT DEFAULT(-1)	-- 订单编号
)
GO





/*
	作者：吴雷
	时间：2012-08-29
	描述：结转损益使用，存储传递结转的数据
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_CLPData' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_CarryLossProfit_Operate]') AND TYPE in (N'P', N'PC'))
		DROP PROC dbo.GP_CarryLossProfit_Operate;
	DROP TYPE TbType_CLPData;
END
GO

CREATE TYPE TbType_CLPData AS TABLE(
	Id				INT,
	FDC				INT,
	FDebit			 NUMERIC(24, 10) ,
	FDebitFor		 NUMERIC(24, 10) ,
	FCredit			 NUMERIC(24, 10) ,
	FCreditFor		 NUMERIC(24, 10) ,
	Cid				INT,
	ATypeId			VARCHAR(50),
	Ascids			VARCHAR(1000),
	Item			VARCHAR(500)
)
GO





GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_CombinationOrder' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateCombinationOrderBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_UpdateCombinationOrderBillDT;
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateCombinationOrderBillDetailsDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_UpdateCombinationOrderBillDetailsDT;
	DROP TYPE TbType_CombinationOrder;
END
GO
/*
	作者：罗淮文
	时间：2016-07-11
	描述：组合品销售订单 明细插入 对应的 表类型
*/
CREATE TYPE TbType_CombinationOrder AS TABLE(
	--intBillNumberID		numeric(10,0),		--  1、单据 ID 值
	chvPTypeID				varchar(50)	DEFAULT(''),	--  2、商品 ID 值
	numQty					 NUMERIC(24, 10) 	DEFAULT(0),	--  3、商品数量
	numPrice				 NUMERIC(24, 10) 	DEFAULT(0),	--  4、商品单价
	numTotal				 NUMERIC(24, 10) 	DEFAULT(0),	--  5、商品金额(折后金额)
	chvComment				varchar(255)	DEFAULT(''),	--  6、单行备注
	--intFlag				int		DEFAULT(0),	--  7、操作标识 
	intOrderID				int		DEFAULT(0),	--  8、订单单据 ID 值 ( 已弃用 )
	intIsUnitTow			int,			--  9、是否采用双单位
	numReachQty			 NUMERIC(24, 10) 	DEFAULT(0),	-- 10、已发货 ( 收 ) 货数量
	numDiscount			 NUMERIC(24, 10) 	DEFAULT(1),	-- 11、扣率
	numDiscountPrice		 NUMERIC(24, 10) 	DEFAULT(0),	-- 12、折后单价
	numTaxPrice			 NUMERIC(24, 10) 	DEFAULT(0),	-- 13、税后单价
	numTaxTotal			 NUMERIC(24, 10) 	DEFAULT(0),	-- 14、税后金额
	numSaleTotal			 NUMERIC(24, 10) 	DEFAULT(0),	-- 15、普通金额（折前金额）
	numTax					 NUMERIC(24, 10) 	DEFAULT(0),	-- 16、税率
	KTypeID				varchar(50) DEFAULT(''),
	STypeID				varchar(50) DEFAULT(''),
	FromBillNumberID		numeric(10, 0),
	FromBillID				numeric(10, 0),
	requestbillnumberid	numeric(10, 0),
	requestbillid			numeric(10, 0),
	askbillnumberid		numeric(10, 0),
	askbillid				numeric(10, 0)
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	--,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,GoodsNumber VARCHAR(100)
	,CargoID   INT
	,GoodsCostPrice  NUMERIC(24, 10)  NULL  DEFAULT (0)
	,GoodsOrder INT NULL  DEFAULT ('-1')
	,ProduceDate VARCHAR(50) NULL  DEFAULT ('')
	,ValidDate VARCHAR(50) NULL DEFAULT ('')
	,[entrycode] varchar(max)
	,isgift INT
	,YapiID VARCHAR(20) NULL DEFAULT('')
	,PriceSource VARCHAR(200) NOT NULL DEFAULT('')
	,OrderId INT NOT NULL DEFAULT(0)
	,Id INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,ShowOrder INT
	,pindexid VARCHAR(300) NULL
	,combinationptypeid VARCHAR(50) DEFAULT('')
);
GO



/*
	作者：罗淮文
	时间：2016-07-14 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CombinationSale' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCombinationSaleBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCombinationSaleBillDT;
	
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCombinationSaleBillDetailsDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCombinationSaleBillDetailsDT;
	DROP TYPE TBType_CombinationSale;
END
GO

CREATE TYPE dbo.TBType_CombinationSale AS TABLE
(
	BillNumberId  	[numeric](10,0),
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10) ,
	SalePrice  	 NUMERIC(24, 10) ,
	Discount  		 NUMERIC(24, 10) ,
	DiscountPrice   NUMERIC(24, 10) ,
	Jobnumber  	[varchar](20),
	Total   		 NUMERIC(24, 10) ,
	OutFactoryDate [datetime] DEFAULT(NULL),
	TaxPrice  		 NUMERIC(24, 10) ,
	TaxTotal  		 NUMERIC(24, 10) ,
	Comment  		[varchar](255),
	OrderID 		[int],
	intisUnitTow 	[int],
	Serial			VARCHAR(MAX),	-- 序列号值
	InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
	GoodsNumber	varchar(100)  DEFAULT(''),	-- 批号
	ProduceDate	varchar(50)  DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50)  DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50)  DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)   DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int  DEFAULT(0),			-- 手工指定成本单价
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	KTypeID		[varchar](50) DEFAULT(''),
	STypeID		[varchar](50)
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQTY  NUMERIC(24, 10) 
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,entryCode VARCHAR(200)
	
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,PriceSource VARCHAR(200)--价格来源
	,IsGift INT
	,BeforePromoID INT
	,ReferPrice  NUMERIC(24, 10) 
	,PriceStyle INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,OMBillID INT
	,LendBillID		NUMERIC(10,0)
	,LendBillNumberID		NUMERIC(10,0)
	,ID INT
	,ShowOrder	INT
	,DiyID INT
	,pindexid VARCHAR(300)
	,combinationptypeid VARCHAR(200) DEFAULT(NULL)
	,PromonIds VARCHAR(1000) DEFAULT('')
	,CouponCode VARCHAR(200)
	,IsPromotion	INT
	,IsVipPoint	INT
	,[PriceDetailId] INT  NULL DEFAULT(0)
	,[PriceRuleId] INT  NULL DEFAULT(0)
) 
GO



/*
	作者：罗淮文
	时间：2016-07-19 
	描述：组合品销售退货单自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CombinationSaleBack' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCombinationSaleBackBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCombinationSaleBackBillDT;
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCombinationSaleBackBillDetailDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCombinationSaleBackBillDetailDT;
	DROP TYPE TBType_CombinationSaleBack;
END
GO

CREATE TYPE dbo.TBType_CombinationSaleBack AS TABLE
(
	BillNumberId  		[numeric](10,0)
	,PtypeId  			[varchar](50)
	,Qty   				 NUMERIC(24, 10) 
	,SalePrice  		 NUMERIC(24, 10) 
	,Discount  			 NUMERIC(24, 10) 
	,DiscountPrice  	 NUMERIC(24, 10) 
	,JobNo   			[varchar](20)
	,Total   			 NUMERIC(24, 10) 
	,MakeDate  			[datetime]
	,TaxPrice  			 NUMERIC(24, 10) 
	,TaxTotal  			 NUMERIC(24, 10) 
	,Comment  			[varchar](255)
	,intisUnit2  		[int]
	,Serial				VARCHAR(max)						-- 序列号值
	,OldID  			[varchar](20) DEFAULT('')  			-- 新增销售退货，采购退货关联的商品行的写入顺序ID add by chen_qihua 2004-6-18
	,OldBillNumberID  	[numeric](10,0) DEFAULT(0) 			-- 新增销售退货，采购退货关联的单据ID      		-- 新增销售退货，采购退货关联的商品的成本
	,InputCostPrice		 NUMERIC(24, 10)  DEFAULT(0)      		-- 手工输入的成本
	,GoodsNumber	varchar(100) DEFAULT('')	-- 批号
	,ProduceDate	varchar(50) DEFAULT('')	-- 生产日期
	,ValidDate		varchar(50) DEFAULT('')	-- 效期至
	,GoodsBTypeID	varchar(50) DEFAULT('')	-- 供货商ID值
	,GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0)	-- 出库批次成本单价
	,HandZeroCost	int DEFAULT(0)			-- 手工指定成本单价
	,Tax			 NUMERIC(24, 10)  DEFAULT(0)
	,SaleTotal		 NUMERIC(24, 10)  DEFAULT(0)
	,KTypeID		varchar(50) DEFAULT('')
	,STypeID		varchar(50) DEFAULT('')
	,FromBillNumberID	[numeric](10,0) DEFAULT(0)
	,FromBillID			[numeric](10,0) DEFAULT(0)
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQTY  NUMERIC(24, 10) 
	,InvoiceQty DECIMAL(18,4)
	,InvoiceMoney DECIMAL(22,10)
	,NInvoiceMoney DECIMAL(22,10)
	,IsGift INT
	,ReferPrice  NUMERIC(24, 10) 
	,PriceStyle INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,OMBillID INT
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,ID INT 
	,pindexid VARCHAR(300)
	,combinationptypeid VARCHAR(200)
	,ShowOrder INT
	,PriceSource VARCHAR(100)
	,Couponcode VARCHAR(200)
) 
GO




GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_Commission' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCommissionBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCommissionBillDT;
	DROP TYPE TbType_Commission;
END
GO

/*
	作者：周华
	时间：2012-05-04 13:44:17.917
	描述：受托单明细查入 对应的 表类型
*/
CREATE TYPE TbType_Commission AS TABLE(
	BillNumberId  	[numeric](10,0),
	BillType 		int,
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10) ,
	SalePrice 	 	 NUMERIC(24, 10) ,
	Discount  		 NUMERIC(24, 10) ,
	DiscountPrice   NUMERIC(24, 10) ,
	Jobno   		[varchar](20),
	Total   		 NUMERIC(24, 10) ,
	OutFactoryDate [datetime],
	TaxPrice  		 NUMERIC(24, 10) ,
	TaxTotal  		 NUMERIC(24, 10) ,
	Comment 		[varchar](255),
	OrderID 		[int] DEFAULT(-1),
	IsUnit2 		[int] DEFAULT(0),
	Serial			VARCHAR(MAX),				-- 序列号值
	OldID  			[varchar](20) DEFAULT(''),  			-- 新增代销结算关联的商品行的写入顺序ID add by chen_qihua 2005-7-19
	OldBillNumberID  	[numeric](10,0) DEFAULT(0), 			-- 新增代销结算/退货关联的单据ID
	InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	--成本单价
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),			-- 手工指定成本单价
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	KTypeID		varchar(50) DEFAULT(''),
	STypeID		varchar(50) DEFAULT('')
	
	-- 新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQTY  NUMERIC(24, 10) 
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,ReferPrice  NUMERIC(24, 10) 
	,PriceStyle INT NOT NULL DEFAULT(0)
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10)
	,ShowOrder INT 
	,PriceSource VARCHAR(100)
);
GO



/*
	By：Haiyang, Li
	Date：2012-6-9
	Description：受托委托代销期初, 表值参数
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CommissionInit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_CommissionInitInsert]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_CommissionInitInsert;
	DROP TYPE TBType_CommissionInit;
END
GO

CREATE TYPE TBType_CommissionInit AS TABLE(
	 qty 					 NUMERIC(24, 10)  	DEFAULT(0)
	,nQty 				 NUMERIC(24, 10)  	DEFAULT(0)
	,goodsNumber	VARCHAR(100)	 	DEFAULT('')
	,itemId				INT							DEFAULT(0)
	,isCombined		BIT							DEFAULT(0)
	,producedate	VARCHAR(50) DEFAULT('')
	,validdate	VARCHAR(50) DEFAULT('')
	,KTypeID	VARCHAR(50) NULL DEFAULT('')
	,CargoID	INT NULL DEFAULT(0)
	,GoodsCostPrice	 NUMERIC(24, 10)  NULL DEFAULT(0)
);

GO




/*
	作者：周华
	时间：2012-05-09 15:13:53.773
	描述：受托委托类单据更新
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_CommissionUpdate' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_UpdateCommissionDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_UpdateCommissionDT;
	DROP TYPE TbType_CommissionUpdate;
END
GO

CREATE TYPE TbType_CommissionUpdate AS TABLE(
	Qty DECIMAL(22,10)
	,OldBillNumberId INT
	,OldId VARCHAR(50)
);
GO




/*
	作者：SHUSHAN
	时间：2017-11-18 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CouponAllot' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCouponAllotBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCouponAllotBillDT;
	
	DROP TYPE TBType_CouponAllot;
END
GO

CREATE TYPE dbo.TBType_CouponAllot AS TABLE
(
	billnumberid	numeric(18,0),
	Couponcode		varchar(max),
	couponid		INT,
	InCargoId		INT,
	OutCargoId		INT,
	Comment			VARCHAR(255),
	Qty				NUMERIC(24,10)			
) 
GO



/*
	作者：谢吉康
	时间：2019-11-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CouponAllotStype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCouponStypeOutBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCouponStypeOutBillDT;
		
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCouponStypeInBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCouponStypeInBillDT;	
	
	DROP TYPE TBType_CouponAllotStype;
END
GO

CREATE TYPE dbo.TBType_CouponAllotStype AS TABLE
(
	BillNumberID	numeric(18,0),
	Couponcode		varchar(max),	
	Comment			varchar(255),
	CouponId		INT,	
	Qty				numeric(24,10),
	Price			numeric(24,10),
	Total			numeric(24,10),
	CostPrice		numeric(24,10),
	NCostPrice		numeric(24,10),
	CostTotal		numeric(24,10),
	NCostTotal		numeric(24,10),
	OutCargoId		int	,
	InCargoId		int	,
	InDate			DATETIME,
	InvalidDate		DATETIME,
	InStockDate		DATETIME
) 
GO





/*
	作者：SHUSHAN
	时间：2017-11-18 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Couponback' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCouponBackBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCouponBackBillDT;
	
	DROP TYPE TBType_Couponback;
END
GO

CREATE TYPE dbo.TBType_Couponback AS TABLE
(
	billnumberid	numeric(18,0),
	Couponcode	varchar(max),
	comment	varchar(255),
	CouponId	INT,	
	qty	numeric(24,10),
	price	numeric(24,10),
	nprice	numeric(24,10),
	total	numeric(24,10),
	ntotal	numeric(24,10),
	CargoId	INT,
	OutBillId INT



) 
GO



/*
	作者：LF
	时间：2018-01-03 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CouponCodeInfo' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCouponCodeInfo]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCouponCodeInfo;
		
	DROP TYPE TBType_CouponCodeInfo;
END
GO

CREATE TYPE dbo.TBType_CouponCodeInfo AS TABLE
(
	CouponCode	VARCHAR(200),
	CouponId	INT,
	State		INT,
	IsIni		INT,
	KtypeId		VARCHAR(50),
	CargoId		INT,
	IniState	INT,
	InvalidDate	DATETIME,
	IsYear		INT,
	InDate		DATETIME,
	OutDate		DATETIME,
	OutPrice	NUMERIC(20,10)
) 
GO



/*
	作者：SHUSHAN
	时间：2017-11-18 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CouponCodes' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Web_CheckMultiCouponCode]') AND TYPE in (N'P', N'PC'))
		DROP PROC Web_CheckMultiCouponCode;
	
	DROP TYPE TBType_CouponCodes;
END
GO

CREATE TYPE dbo.TBType_CouponCodes AS TABLE
(
	
	DetailID		INT,
	Couponcode	varchar(max),	
	CouponId	INT	
	
) 
GO



/*
	作者：SHUSHAN
	时间：2017-11-18 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CouponIn' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCouponInBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCouponInBillDT;
	
	DROP TYPE TBType_CouponIn;
END
GO

CREATE TYPE dbo.TBType_CouponIn AS TABLE
(
	BillNumberID	numeric(18,0),
	Couponcode	varchar(max),	
	Comment	varchar(255),
	CouponId	INT,	
	Qty	numeric(24,10),
	CostPrice	numeric(24,10),
	NCostPrice	numeric(24,10),
	CostTotal	numeric(24,10),
	NCostTotal	numeric(24,10),
	CargoId	int	,
	InDate DATETIME,
	InvalidDate DATETIME 
) 
GO



/*
	作者：SHUSHAN
	时间：2017-11-18 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CouponOut' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCouponOutBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCouponOutBillDT;
	
	DROP TYPE TBType_CouponOut;
END
GO

CREATE TYPE dbo.TBType_CouponOut AS TABLE
(
	ID INT,
	BillNumberID	numeric(18,0),
	Couponcode	varchar(max),
	Comment	varchar(255),
	CouponId	INT,
	Qty	numeric(24,10),
	Price	numeric(24,10),
	NPrice	numeric(24,10),
	Total	numeric(24,10),
	NTotal	numeric(24,10),
	OutDate	DATETIME,
	InvalidDate	DATETIME,
	CargoId	INT,
	BackQty numeric(24,10)
	
) 
GO



/*
	作者：SHUSHAN
	时间：2017-11-18 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_CouponOutPtype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCouponOutBillDetailsDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertCouponOutBillDetailsDT;
	
	DROP TYPE TBType_CouponOutPtype;
END
GO

CREATE TYPE dbo.TBType_CouponOutPtype AS TABLE
(
	BillnumberId	numeric(18,0),
	Couponcode	varchar(max),	
	ptypeid	varchar(50),
	CouponId	INT,								--优惠券ID
	qty	numeric(24,10),
	price	numeric(24,10),
	nprice	numeric(24,10),
	total	numeric(24,10),
	ntotal	numeric(24,10)


) 
GO




/*
	作者：吴雷
	时间：2012-05-21
	描述：期末调汇使用，调整汇率的币别表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_Currency' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_TerminalAdjustRate]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_TerminalAdjustRate;
	DROP TYPE TbType_Currency;
END
GO

CREATE TYPE TbType_Currency AS TABLE(
	cid			INT,			--币别
	newrate		 NUMERIC(24, 10) 	--调整汇率
)
GO




GO
IF EXISTS (SELECT Name FROM SysTypes WHERE Name=N'TbType_DeliveryBackBill' AND XType=243)
BEGIN
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'Gp_InsertDeliveryBackBillDT',N'P'))
	BEGIN			  
		DROP PROC dbo.Gp_InsertDeliveryBackBillDT;
	END
	
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'GP_DeliveryBackBillDTCheck',N'P'))
	BEGIN
		DROP PROC dbo.GP_DeliveryBackBillDTCheck
	END
	DROP TYPE dbo.TbType_DeliveryBackBill;
END
GO

/*		
	作者：陈强
	日期：2019-12-02
	描述：门店配送退货单表值参数
*/

CREATE TYPE dbo.TbType_DeliveryBackBill AS TABLE
(
	[ID]			INT ,	--自增id
    ShowOrder		INT ,	--排序id				
	BillNumberId    numeric(10, 0)	NOT NULL,			--单价主表id
	Serial          varchar(max)	NULL DEFAULT (''),	--序列号
	outktypeid		varchar(50)		NULL DEFAULT (''),	--出库仓库id
	outCargoID		INT				NULL DEFAULT(0),	--出库货位id
	inktypeid		varchar(50)		NULL,	--要货仓库id
	inCargoID		INT				NULL DEFAULT(0),	--要货货位id
	PtypeId		    varchar(50)		NULL,	--商品id
	ItemID          bigint          NULL,	--自由项Id
    IsCombined      int				NULL,	--组合项标识
	GoodsNumber		varchar(100)	NULL,	--批号
	ProduceDate		varchar(50)		NULL,	--生产日期
	ValidDate		varchar(50)		NULL,	--校期至
	Qty			    numeric(18, 4)  NOT NULL,	--基本单位数量
	Price			numeric(18, 4)  NOT NULL,	--基本单位单价
	Total			numeric(18, 4)  NOT NULL,	--金额
	UnitID          int             NULL,	--基本单位id
	MUnitID         int             NULL,	--大单位Id
	MQty            numeric(22,10)  NULL,	--大单位数量
	MUnitRate       numeric(22,10)  NULL,	--大单位换算率
	MUnitMsg        varchar(50)     NULL,	--大单位信息
	MPrice			numeric(22,10)  NULL,	--大单位单价
	NUnitID         int             NULL,	--浮动单位id
	NUnitRate       numeric(22,10)  NULL,	--浮动单位换算率
	NQty            numeric(22,10)  NULL,	--浮动数量
	NUnitMsg        varchar(50)     NULL,	--浮动单位信息
	Comment		    varchar(255)    NULL,	--备注
	InflowQty	NUMERIC(24,10)  NULL,	--上架数量
	DeliveryID		INT             NULL,	--门店配送单明细ID	
	GoodsCostPrice	NUMERIC(24, 10) 	DEFAULT(0),	-- 出库批次成本单价
	GoodsCostTotal 	NUMERIC(24, 10)  DEFAULT(0),
	HandZeroCost	INT						DEFAULT(0)	-- 手工指定成本单价	
)
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_DeliVeryBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertDeliVeryBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertDeliVeryBillDT	
	    DROP TYPE TBType_DeliVeryBill	
END
GO



/*
Author:			赵燕琴
Create date: 2019-12-02
Description 门店调拨单(表值)
*/
CREATE TYPE dbo.TBType_DeliVeryBill AS TABLE
(      
		[BillNumberId]		NUMERIC(10,0) ,
		Serial              VARCHAR(max)    DEFAULT (''),
		ktypeidout		varchar(50),
		CargoIDout		INT				DEFAULT(0) ,
		ktypeidin		varchar(50),
		CargoIDin		INT				DEFAULT(0) ,
		PtypeId				VARCHAR(50)  ,
		ItemID				BIGINT               ,
	    IsCombined			INT  ,
		GoodsNumber			VARCHAR(100)  DEFAULT (''),
		ProduceDate		varchar(50)		NULL,	--生产日期
	    ValidDate		varchar(50)		NULL,	--校期至
		Qty					NUMERIC(18, 4)   ,
		Price				NUMERIC(18, 4) ,
		Total				NUMERIC(18, 4) ,
		UnitID				INT             Default(0)  ,
		MUnitID				INT             Default(0)  ,
		MQty				NUMERIC(22,10)   ,
		MUnitRate			NUMERIC(22,10)   ,
		MUnitMsg			VARCHAR(50)          ,
		MPrice				NUMERIC(22,10)  ,
		NUnitID             INT             Default(0)  ,
		NUnitRate           NUMERIC(22,10)  Default(0)  ,
		NQty                NUMERIC(22,10)  Default(0)  ,
		NUnitMsg            VARCHAR(50)          ,
		Comment		        VARCHAR(255)  ,
		PickedQty		    NUMERIC(24,10)  DEFAULT(0), --拣货数量
	    CheckQty		    NUMERIC(24,10)  DEFAULT(0), --验收数量
	    UnfinishedQty       NUMERIC(24,10)  DEFAULT(0),  --未完成数量
	    DeliveryApplyBillId	  INT		DEFAULT(0)	,	--要货申请单明细id
	    GoodsCostPrice			 NUMERIC(24, 10) 	DEFAULT(0),	-- 出库批次成本单价
		GoodsCostTotal 		 NUMERIC(24, 10)  DEFAULT(0),
		HandZeroCost				INT						DEFAULT(0),	-- 手工指定成本单价	
		InputCostPrice      numeric(18, 4) NULL DEFAULT (0),  
	    ShowOrder		    INT DEFAULT(0),
	    ID INT
)
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_DeliveryCheckBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertDeliveryCheckBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertDeliveryCheckBillDT	
	    DROP TYPE TBType_DeliveryCheckBill	
END
GO



/*
Author:			赵燕琴
Create date: 2019-12-02
Description 门店验收单(表值)
*/
CREATE TYPE dbo.TBType_DeliveryCheckBill AS TABLE
(      
		BillNumberId		NUMERIC(10,0) ,
		Serial              VARCHAR(max)    DEFAULT (''),
		outktypeid			VARCHAR(50),
		outCargoID			INT				DEFAULT(0) ,
		inktypeid			VARCHAR(50),
		inCargoID			INT				DEFAULT(0) ,
		PtypeId				VARCHAR(50)  ,
		ItemID				BIGINT               ,
	    IsCombined			INT  ,
		GoodsNumber			VARCHAR(100)  DEFAULT (''),
		ProduceDate			VARCHAR(50)   DEFAULT (''),
		ValidDate			VARCHAR(50)   DEFAULT (''),
		Qty					NUMERIC(18, 4)   ,
		Price				NUMERIC(18, 4) ,
		Total				NUMERIC(18, 4) ,
		UnitID				INT             Default(0)  ,
		MUnitID				INT             Default(0)  ,
		MQty				NUMERIC(22,10)   ,
		MUnitRate			NUMERIC(22,10)   ,
		MUnitMsg			VARCHAR(50)          ,
		MPrice				NUMERIC(22,10)  ,
		NUnitID             INT             Default(0)  ,
		NUnitRate           NUMERIC(22,10)  Default(0)  ,
		NQty                NUMERIC(22,10)  Default(0)  ,
		NUnitMsg            VARCHAR(50)          ,
		Comment		        VARCHAR(255)  ,		
	    InflowQty           NUMERIC(24,10)  DEFAULT(0),  --未完成数量  
	    DeliveryID		    INT DEFAULT(0),
	    GoodsCostPrice			 NUMERIC(24, 10) 	DEFAULT(0),	-- 出库批次成本单价
		GoodsCostTotal 		 NUMERIC(24, 10)  DEFAULT(0),
		HandZeroCost				INT						DEFAULT(0),	-- 手工指定成本单价	
	    ShowOrder		    INT DEFAULT(0)
)
GO



/*
	作者：吕文祺
	时间：2017-08-01 
	描述：自定义寄存单据表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_DepositBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_SaveDepositBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_SaveDepositBillDT;
	DROP TYPE TBType_DepositBill;
END
GO

CREATE TYPE dbo.TBType_DepositBill AS TABLE
(
		DepositBillID				int,
		PosBillNumberID				INT,
		PID							INT,
		PosBillDetailID				INT,
		UnitID						INT,
		BaseUnitId					INT,
		UnitRate					NUMERIC(24, 10) ,
		total						NUMERIC(24, 10) ,
		price						NUMERIC(24, 10) ,
		saleqty						NUMERIC(24, 10) ,
		depositedqty				NUMERIC(24, 10),
		depositqty					NUMERIC(24, 10),
		pickupqty					NUMERIC(24, 10)  ,
		pickedupqty					NUMERIC(24, 10) ,
		depositprice				NUMERIC(24, 10) ,
		remainqty					NUMERIC(24, 10) ,
		pickupprice					NUMERIC(24, 10),
		unpickupqty					NUMERIC(24, 10),
		unpickupmoney				NUMERIC(24, 10),
		Guid						VARCHAR(50)
	
) 
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_DissBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertDissBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertDissBillDT
	DROP TYPE TBType_DissBill	
END
GO



/*
	Author:			 李海洋
	Create date: 2012-05-15 
	Description: 自定义表值类型(损,益单明细)
*/
CREATE TYPE dbo.TBType_DissBill AS TABLE
(
	BillNumberId			NUMERIC(10, 0)
	,PtypeId  				VARCHAR(50)
	,Qty   						 NUMERIC(24, 10) 
	,CostPrice				 NUMERIC(24, 10) 
	,JobNo   					VARCHAR(20)
	,Total   					 NUMERIC(24, 10) 
	,InOrOut  				CHAR(1)
	,MakeDate  				DATETIME
	,Comment  				VARCHAR(255)
	,intisUnitTow 		INT	
	,Serial						VARCHAR(MAX)						-- 序列号值	
	,InputCostPrice		 NUMERIC(24, 10) 	-- 成本单价
	,GoodsNumber			VARCHAR(100)		-- 批号
	,ProduceDate			VARCHAR(50) 		-- 生产日期
	,ValidDate				VARCHAR(50) 		-- 效期至
	,GoodsBTypeID			VARCHAR(50) 		-- 供货商ID值
	,GoodsCostPrice		 NUMERIC(24, 10) 		-- 出库批次成本单价
	,HandZeroCost			INT							-- 手工指定成本单价
	,KTypeID					VARCHAR(50)
	,STypeID					VARCHAR(50)
	--9.0新字段
	,CargoId					INT							-- 货位ID	
	,ItemId						BIGINT					-- 自由项id
	,IsCombined				INT							-- 是否组合
	,NQty							 NUMERIC(24, 10)  DEFAULT (0)
	,UnitRate					 NUMERIC(24, 10)  DEFAULT (0)
	,MUnitId INT NOT NULL DEFAULT(0) --大单位
    ,MUnitRate  NUMERIC(24, 10)  NOT NULL DEFAULT(1)--大单位换算率
    ,MQty  NUMERIC(24, 10)  NOT NULL DEFAULT(0) --大单位数量
    ,CurMSalePrice  NUMERIC(24, 10)  NOT NULL DEFAULT(0) -- 大单位单价
    ,ShowOrder INT
)
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_FaPiao' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertFaPiaoBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertFaPiaoBillDT;
	DROP TYPE TBType_FaPiao;
END
GO

CREATE TYPE dbo.TBType_FaPiao AS TABLE
( 
	BillNumberId  	[numeric](10,0),
	BillType		[int],
	MainBillNumberID [numeric](10,0),
	KtypeId  		[varchar](100),
	PtypeId  		[varchar](100),
	Qty   			 NUMERIC(24, 10) ,
	Price		  	 NUMERIC(24, 10) ,
	Total   		 NUMERIC(24, 10) ,
	Tax   			 NUMERIC(24, 10) ,
	TaxPrice  		 NUMERIC(24, 10) ,
	TaxTotal  		 NUMERIC(24, 10) ,
	Comment  		[varchar](255),
	STypeID		varchar(50) DEFAULT(''),
	discount		 NUMERIC(24, 10)  DEFAULT(1),
	BeforePrice	 NUMERIC(24, 10)  DEFAULT(0),
	BeforeTotal	 NUMERIC(24, 10)  DEFAULT(0),
	RecordedItemId INT DEFAULT(0), -- 表示已经开票的记录id，这个id可以配合MainBillNumberId 一起找到明细在哪一个表中
	--9.0新加字段
	nprice		 NUMERIC(24, 10) ,		
	ntotal		 NUMERIC(24, 10) ,		
	ntaxprice	 NUMERIC(24, 10) ,	 	
	ntaxtotal	 NUMERIC(24, 10) ,		
	ntaxmoney	 NUMERIC(24, 10) ,		
	cargoid		INT,		
	unitid		INT,			
	nunitid		INT,		
	nqty		 NUMERIC(24, 10) ,		
	unitrate	 NUMERIC(24, 10) ,		
	nunitmsg	VARCHAR(50),		
	munitid		INT,		
	mqty		 NUMERIC(24, 10) ,		
	munitrate	 NUMERIC(24, 10) ,		
	munitmsg	VARCHAR(50),		
	mprice		 NUMERIC(24, 10) ,		
	mtaxprice	 NUMERIC(24, 10) ,		
	curmprice	 NUMERIC(24, 10) ,		
	curmtaxprice  NUMERIC(24, 10) ,		
	itemid		BIGINT,		
	iscombined	BIT,		
	nbeforeprice  NUMERIC(24, 10) ,		
	nberoretotal  NUMERIC(24, 10) ,
	goodsnumber varchar(100),
	curmsaleprice  NUMERIC(24, 10) ,
	nsaletotal   NUMERIC(24, 10) ,
	saleprice	 NUMERIC(24, 10) , 
	taxmoney	 NUMERIC(24, 10) ,
	nsaleprice	 NUMERIC(24, 10),
	ProduceDate	 VARCHAR(50),
	ValidDate    VARCHAR(50),
	ShowOrder	 INT
) 
GO





























/*
	作者：周华
	时间：2014-04-21
	描述：固定资产盘点单明细保存结构
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_FixedAssetsStockCheck' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertFixedAssetsStockCheckDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertFixedAssetsStockCheckDT;
	DROP TYPE TbType_FixedAssetsStockCheck;
END
GO

CREATE TYPE TbType_FixedAssetsStockCheck AS TABLE(
	BillNumberId INT
	,AssetsCardId INT 
	,UserCode VARCHAR(200)
	,FullName VARCHAR(200)
	,barcode INT
	,acstate INT
	,panbarcode VARCHAR(200)
	,panstate int
	,Comment VARCHAR(200)
)
GO




/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Gathering' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGatheringBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGatheringBillDT;
	DROP TYPE TBType_Gathering;
END
GO

CREATE TYPE dbo.TBType_Gathering AS TABLE
( 
	BillNumberId  [numeric](10,0),
	AtypeId  [varchar](50),
	Total    NUMERIC(24, 10) ,
	Comment  [varchar](256),
	STypeID	VARCHAR(50),
	vipcardid	VARCHAR(MAX) DEFAULT('-1')
	--9.0新加字段	
	,ntotal		 NUMERIC(24, 10) 
	,RelevanceBillId INT
	,ShowOrder	INT
	,brandartypeid  VARCHAR(50)
	,preferencemoney NUMERIC(24, 10) 
	,npreferencemoney NUMERIC(24, 10) 
) 
GO




























/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
	2013-05-09 周华 添加 ktypeid字段 多仓库
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Give' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertGiveBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertGiveBillDT;
	DROP TYPE TBType_Give;
END
GO

CREATE TYPE dbo.TBType_Give AS TABLE
(
	DbName         [varchar](30),
	BillNumberId  	[numeric](10,0),
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10)  ,
	Comment  		[varchar](255),
	intIsUnit2 	[int] DEFAULT(0),
	Serial			VARCHAR(MAX),				-- 序列号值
	InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	--成本单价
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),				-- 手工指定成本单价
	STypeID		varchar(50) DEFAULT('')
	-- 9.0新字段
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,ItemId BIGINT
	,IsCombined INT
	,KTypeId VARCHAR(50) NOT NULL DEFAULT('')
	,ShowOrder INT
) 
GO




GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_GiveMe' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGivemeBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGivemeBillDT;
	DROP TYPE TbType_GiveMe;
END
GO

/*
	作者：周华
	时间：2012-05-03 17:21:09.263
	描述：获赠单明细查入 对应的 表类型
	2013-05-09 周华 添加KTypeId字段 多仓库
*/
CREATE TYPE TbType_GiveMe AS TABLE(
	DbName         [varchar](30),
	BillNumberId  	[numeric](10,0),
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10)  ,
	Comment  		[varchar](255),
	intIsUnit2 	[int] DEFAULT(0),
	Serial			VARCHAR(MAX),				-- 序列号值
	InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	--成本单价
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),				-- 手工指定成本单价
	STypeID		VARCHAR(50)
	
	-- 新字段
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,ItemId BIGINT
	,IsCombined INT
	
	--多仓库
	,KTypeId VARCHAR(50) DEFAULT('')
	,ShowOrder INT
);
GO




/*
	作者：周华
	时间：2012-6-11
	描述：先进先出 库存期初 下grid 保存对应表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_GoodsInitFIFO_b' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitFIFO]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitFIFO;
	DROP TYPE TbType_GoodsInitFIFO_b;
END
GO

CREATE TYPE TbType_GoodsInitFIFO_b AS TABLE(
	Qty  NUMERIC(24, 10) 
	,CargoId INT
	,GoodsNumber VARCHAR(50)
	,ItemId BIGINT
	,NQty  NUMERIC(24, 10) 
	,IsCombined BIT
	,Serial VARCHAR(8000)
	,LockNumber NUMERIC(24, 10)
);

GO 



/*
	作者：周华
	时间：2012-6-11
	描述：先进先出 库存期初 上grid 保存对应表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_GoodsInitFIFO_h' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitFIFO]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitFIFO;
	DROP TYPE TbType_GoodsInitFIFO_h;
END
GO

CREATE TYPE TbType_GoodsInitFIFO_h AS TABLE(
	Qty  NUMERIC(24, 10) 
	,Price  NUMERIC(24, 10) 
	,Total  NUMERIC(24, 10) 
);

GO 



/*
	作者：周华
	时间：2012-8-28
	描述：手工指定法
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_GoodsInitMan' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitManSimple]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitManSimple;
	DROP TYPE TbType_GoodsInitMan;
END
GO
CREATE TYPE TbType_GoodsInitMan AS TABLE(
	Qty  NUMERIC(24, 10) 
	,Nqty  NUMERIC(24, 10) 
	,Price  NUMERIC(24, 10) 
	,Total  NUMERIC(24, 10) 
	,CargoId INT
	,ItemId INT
	,Iscombined BIT
	,ProduceDate VARCHAR(50)
	,Validdate VARCHAR(50)
	,GoodsNumber VARCHAR(100)
	,Serial VARCHAR(MAX)
	,locknumber NUMERIC(24, 10)
	--,Sqty INT
);
GO



/*
	作者：周华
	时间：2012-6-11
	描述：先进先出 库存期初 上grid 保存对应表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_GoodsInitMan_b' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitMan]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitMan;
	DROP TYPE TbType_GoodsInitMan_b;
END
GO
CREATE TYPE TbType_GoodsInitMan_b AS TABLE(
	Qty  NUMERIC(24, 10) 
	,CargoId INT
	,ItemId BIGINT
	,NQty  NUMERIC(24, 10) 
	,Iscombined BIT
	,ProduceDate VARCHAR(50)
	,Validdate VARCHAR(50)
	,GoodsNumber VARCHAR(100)
	,GoodsCostPrice  NUMERIC(24, 10) 
);
GO



/*
	作者：周华
	时间：2012-6-11
	描述：先进先出 库存期初 上grid 保存对应表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_GoodsInitMan_h' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitMan]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitMan;
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitManSimple]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitManSimple;
	DROP TYPE TbType_GoodsInitMan_h;
END
GO
CREATE TYPE TbType_GoodsInitMan_h AS TABLE(
	Qty  NUMERIC(24, 10) 
	,Nqty  NUMERIC(24, 10) 
	,Price  NUMERIC(24, 10) 
	,Total  NUMERIC(24, 10) 
	,ProduceDate VARCHAR(50)
	,Validdate VARCHAR(50)
	,GoodsNumber VARCHAR(100)
);
GO



/*
	作者：周华
	时间：2012-6-11
	描述：保存库存期初对应的表 移动加权
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_GoodsInitMV' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitMV]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitMV;
	DROP TYPE TbType_GoodsInitMV;
END
GO

CREATE TYPE TbType_GoodsInitMV AS TABLE(
	Qty  NUMERIC(24, 10) 
	,CargoId INT 
	,GoodsNumber VARCHAR(100)
	,ItemId  BIGINT
	,NQty DECIMAL(24,10)
	,Iscombined BIT
	,Serial VARCHAR(max)
	,ProduceDate VARCHAR(50)
	,Validdate VARCHAR(50)
	,LockNumber NUMERIC(24, 10) 
);

GO 



/*
	描述：库存期初序列号自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Gp_InitPTypeSerial' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertInitPTypeSerialDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertInitPTypeSerialDT;
	DROP TYPE TBType_Gp_InitPTypeSerial;
END
GO

CREATE TYPE TBType_Gp_InitPTypeSerial AS TABLE
(
   Serial varchar(1000),
   KtypeID varchar(50),
   PtypeID varchar(50),
   STypeId varchar(50),
   ETypeID varchar(50)
)
GO




/*
	By：Haiyang, Li
	Date：2012-6-9
	Description：导入受托委托代销期初, 表值参数
*/
IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TBType_ImportInitCommission'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    sys.objects
                    WHERE   object_id = OBJECT_ID(N'[dbo].[GP_ImportInitCommission]')
                            AND TYPE IN ( N'P', N'PC' ) ) 
            DROP PROC GP_ImportInitCommission;
       IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportInitSerial]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
			DROP PROCEDURE [dbo].[Gp_ImportInitSerial]
			
		IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportInitSerialNoRel]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
			DROP PROCEDURE [dbo].[Gp_ImportInitSerialNoRel]
        DROP TYPE TBType_ImportInitCommission;
    END
GO

CREATE TYPE TBType_ImportInitCommission AS TABLE
(	
		 btypeid 				VARCHAR (50)					DEFAULT ('')
		,stypeid 				VARCHAR (50)					DEFAULT ('')
		,ptypeid				VARCHAR (50)					DEFAULT ('')
		,ktypeid				VARCHAR (50)					DEFAULT ('')
		,cargoid				VARCHAR (50)					DEFAULT ('')
		,type						INT NOT NULL
		,goodsNumber		VARCHAR(100)				 	DEFAULT ('')
		,itemId					INT										DEFAULT (0)
		,isCombined			BIT										DEFAULT (0)
		,qty 						 NUMERIC(24, 10)  				DEFAULT (0)
		,nQty 					 NUMERIC(24, 10)  				DEFAULT (0)
		,costprice			 NUMERIC(24, 10) 				DEFAULT (0)
		,price					 NUMERIC(24, 10) 			  DEFAULT (0)
		,explain				VARCHAR(256)				  DEFAULT ('')
		--,ktypeId				VARCHAR (50) 					DEFAULT ('')  --暂时无用
		--,etypeId				VARCHAR (50) 					DEFAULT ('')  --暂时无用
		,Producedate             VARCHAR(50)               DEFAULT ('')
		,Validdate				VARCHAR(50)				  DEFAULT ('')
		,SerialType					INT
		,DealType					INT
);

GO





/*
	By：施训果
	Date：2015-05-25
	Description：导入受托委托库存期初, 表值参数
*/
IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TBType_ImportInitSerial'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportInitSerial]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
		DROP PROCEDURE [dbo].[Gp_ImportInitSerial]
            
        IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportInitSerialNoRel]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
			DROP PROCEDURE [dbo].[Gp_ImportInitSerialNoRel]
        DROP TYPE TBType_ImportInitSerial;
    END
GO

CREATE TYPE TBType_ImportInitSerial AS TABLE
(	
		 btypeid 				VARCHAR (50)					DEFAULT ('')
		,stypeid 				VARCHAR (50)					DEFAULT ('')
		,ptypeid				VARCHAR (50)					DEFAULT ('')
		,ktypeid				VARCHAR (50)					DEFAULT ('')
		,cargoid				VARCHAR (50)					DEFAULT ('')
		,goodsNumber		VARCHAR(100)				 	DEFAULT ('')
		,itemId					INT										DEFAULT (0)
		,isCombined			BIT										DEFAULT (0)
		,qty 						 NUMERIC(24, 10)  				DEFAULT (0)
		,nQty 					 NUMERIC(24, 10)  				DEFAULT (0)
		,costprice			 NUMERIC(24, 10) 				DEFAULT (0)
		,price					 NUMERIC(24, 10) 			  DEFAULT (0)
		,Serial					VARCHAR (1000)					DEFAULT ('')
		,SerialType					INT
		,Producedate             VARCHAR(50)               DEFAULT ('')
		,Validdate				VARCHAR(50)				  DEFAULT ('')
		,TBType_ImportInitSerial INT
);

GO





/*
	By：Haiyang, Li
	Date：2012-6-9
	Description：导入维修品库存期初, 表值参数
*/
IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TBType_ImportInitWxStock'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    sys.objects
                    WHERE   object_id = OBJECT_ID(N'[dbo].[GP_ImportInitWxStock]')
                            AND TYPE IN ( N'P', N'PC' ) ) 
            DROP PROC GP_ImportInitWxStock;
        DROP TYPE TBType_ImportInitWxStock;
    END
GO

CREATE TYPE TBType_ImportInitWxStock AS TABLE
(	
		ptypeid			VARCHAR (50) 		NOT NULL,
		ktypeid			VARCHAR (50) 		NOT NULL,
		goodsnumber VARCHAR (100)		NULL		DEFAULT (''),
		itemid			INT							NULL		DEFAULT (0),
		iscombined	BIT							NULL		DEFAULT (0),
		qty					 NUMERIC(24, 10) 		NULL		DEFAULT (0),
		nqty				 NUMERIC(24, 10)  NULL		DEFAULT (0),
		producedate		datetime		NULL,
		validdate		datetime        NULL,
		serial			VARCHAR(MAX) NULL
);

GO





/*	
	作	  者：tangtao
	日    期：2015-08-27
	描	  述：库存上下限批量导入 表值参数
*/

IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TBType_ImportStockAlarm'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    sys.objects
                    WHERE   object_id = OBJECT_ID(N'[dbo].[Gp_ImportStockAlarmDT]')
                            AND TYPE IN ( N'P', N'PC' ) ) 
            DROP PROC Gp_ImportStockAlarmDT;
        DROP TYPE TBType_ImportStockAlarm;
    END
GO

CREATE TYPE TBType_ImportStockAlarm AS TABLE
(	
	ID					INT					NOT NULL			,
	PTypeId				VARCHAR (50) 		NOT NULL			   ,
	UpLimitQty			 NUMERIC(24, 10) 		NULL		DEFAULT (0),
	DownLimitQty		 NUMERIC(24, 10) 		NULL		DEFAULT (0)
)

GO





/*
	作者：周华
	时间：2012-08-17
	描述：借欠期初导入dt
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_IniLend' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[gp_ImportIniLendDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC gp_ImportIniLendDT;
	DROP TYPE TbType_IniLend;
END
GO

CREATE TYPE TbType_IniLend AS TABLE(
	BtypeId VARCHAR(50)
	,PtypeId VARCHAR(50)
	,KtypeId VARCHAR(50)
	,GoodsNumber VARCHAR(100)
	,ItemId INT
	,Iscombined BIT
	,LendQty  NUMERIC(24, 10) 
	,NLendQty  NUMERIC(24, 10) 
	,BorrowQty  NUMERIC(24, 10) 
	,NBorrowQty  NUMERIC(24, 10) 
)
GO



/*
	作者：周华
	时间：2012-08-17
	描述：库存期初导入dt
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_IniStock' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[gp_ImportIniStockDT]') AND TYPE in (N'P', N'PC'))
	BEGIN
		DROP PROC gp_ImportIniStockDT;
	END	
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[gp_ImportIniPhStockDT]') AND TYPE in (N'P', N'PC'))
	BEGIN
		DROP PROC gp_ImportIniPhStockDT
	END	
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[gp_ChangeIniFlag]') AND TYPE in (N'P', N'PC'))
	BEGIN
		DROP PROC gp_ChangeIniFlag
	END	
	
	DROP TYPE TbType_IniStock;
END
GO

CREATE TYPE TbType_IniStock AS TABLE(
	PtypeId VARCHAR(50)
	,KtypeId VARCHAR(50)
	,CargoId INT
	,ItemId INT
	,Iscombined BIT
	,GoodsNumber VARCHAR(100)
	,ProduceDate VARCHAR(50)
	,ValidDate VARCHAR(50)
	,Qty  NUMERIC(24, 10) 
	,NQty  NUMERIC(24, 10) 
	,Price  NUMERIC(24, 10) 
	,Serial VARCHAR(MAX)
)
GO





/*
	作者：周华
	时间：2012-06-18 10:23:37.660
	描述：积分兑换单保存对应表值
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_IntegralExchange' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertIntegralExchangeBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertIntegralExchangeBillDT;
	DROP TYPE TbType_IntegralExchange;
END
GO

CREATE TYPE TbType_IntegralExchange AS TABLE(
	KTypeId VARCHAR(50)
	,PTypeId VARCHAR(50)
	,Qty  NUMERIC(24, 10) 
	,Price  NUMERIC(24, 10) 
	,Total  NUMERIC(24, 10) 
	,Comment VARCHAR(250)
	,IsUnit2 INT
	,InputCostPrice  NUMERIC(24, 10) 
	,HandZeroCost INT
	,Serial VARCHAR(MAX)
	,GoodsNumber VARCHAR(100)
	,ProduceDate VARCHAR(50)
	,ValidDate VARCHAR(50)
	,GoodsCostPrice  NUMERIC(24, 10) 
	,CargoId INT
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,ShowOrder	INT
);

GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_JieJian' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertJieJianBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertJieJianBillDT;
	DROP TYPE TBType_JieJian;
END
GO

CREATE TYPE dbo.TBType_JieJian AS TABLE
(
	BillNumberID		NUMERIC(10,0),
	PTypeID					VARCHAR(50),
	intIsUnit2			int,												-- 是否采用双单位。0：否；1：是
	BuyDate					VARCHAR(50)		DEFAULT(''),	-- 购买日期
	ErrDes					VARCHAR(3000) DEFAULT(''),	-- 故障描述
	ErrDeal					VARCHAR(3000) DEFAULT(''),	-- 处理意见
	Total						 NUMERIC(24, 10) ,							-- 预计费用
	RepairMode			INT,												-- 维修方式，0：空；1：维修；2：送修；3：换机
	ETypeID					VARCHAR(50),								-- 维修人
	BaoXiu					INT,												-- 保内/保外，-1：空；0：保内；1：保外
	Comment					VARCHAR(255)	DEFAULT(''),	-- 备注
	Serial					VARCHAR(200)	DEFAULT(''),	-- 序列号（只录一个）
	OutFactoryDate	DATETIME			DEFAULT(NULL),
	STypeID					VARCHAR(50)		DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,goodsnumber VARCHAR(100)
	,cargoid INT
	,ShowOrder INT
) 
GO




GO
IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TbType_LendBorrow'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    sys.objects
                    WHERE   object_id = OBJECT_ID(N'[dbo].[Gp_InsertLendBillDT]')
                            AND TYPE IN ( N'P', N'PC' ) ) 
            DROP PROC Gp_InsertLendBillDT;
        DROP TYPE TbType_LendBorrow;
    END
GO
CREATE TYPE TbType_LendBorrow AS TABLE
(
		PtypeId  		VARCHAR(50),		--商品ID
		Qty   			 NUMERIC(24, 10) ,	--数量
		Comment  		VARCHAR(255),		--备注
		Serial			VARCHAR(MAX),	--序列号
		BackItemId	INT DEFAULT(0), -- 原借，欠单的id
		CargoId			INT DEFAULT(0),
		ItemId			BIGINT DEFAULT(0),
		IsCombined	INT DEFAULT(0),
		NQty				 NUMERIC(24, 10)  DEFAULT(0),
		GoodsNumber VARCHAR(100) DEFAULT(''), 
		UnitRate DECIMAL(24, 10) DEFAULT(1),
		ValidDate VARCHAR(50) DEFAULT(''),		
		ProduceDate VARCHAR(50)	DEFAULT(''),
		ShowOrder INT,
		FromBillid INT DEFAULT(0)
);
GO




GO
IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TbType_LendBorrowAfterCheck'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    sys.objects
                    WHERE   object_id = OBJECT_ID(N'[dbo].[Gp_InsertLendBillDTAfterCheck]')
                            AND TYPE IN ( N'P', N'PC' ) ) 
            DROP PROC Gp_InsertLendBillDTAfterCheck;
        DROP TYPE TbType_LendBorrowAfterCheck;
    END
GO
CREATE TYPE TbType_LendBorrowAfterCheck AS TABLE(
PtypeId VARCHAR(50),
ItemId			BIGINT DEFAULT(0),
IsCombined	INT DEFAULT(0),
GoodsNumber VARCHAR(100) DEFAULT('')
);
GO



/*
	作者：周华
	时间：2012-6-7
	描述：保存借欠期初对应的表
	修改：2015-04-28 SiHuaShan 新增Serial 字段
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_LendInit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertLendInit]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertLendInit;
	DROP TYPE TbType_LendInit;
END
GO

CREATE TYPE TbType_LendInit AS TABLE(
	Qty  NUMERIC(24, 10) 
	--,CargoId INT 
	,GoodsNumber VARCHAR(100)
	,ItemId  BIGINT
	,NQty DECIMAL(22,10)
	,Iscombined BIT
	,Lend DECIMAL(22,10)
	,LendNqty DECIMAL(22,10)
	,Borrow DECIMAL(22,10)
	,BorrowNqty DECIMAL(22,10)
	,IfBorrow  INT
	,Serial	   VARCHAR(MAX)
);

GO 




/*
	作者
	时间：2012-05-03 09:18:19.193
	描述：把单据明细保存存储过程dt版要用到的自定义表类型
	2012-11-15 修改entrycode 长度为200
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_LockDetail' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_DoLock]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_DoLock;
	DROP TYPE TbType_LockDetail;
END
GO

CREATE TYPE TbType_LockDetail AS TABLE(
	LockInfo	VARCHAR(1000),		--锁库信息
	BillNumberID		NUMERIC(10,0),	-- 单据 ID 值
	OrderID		INT DEFAULT(-1),	-- 订单编号
	PtypeID		VARCHAR(50),	-- 商品 ID 值
	etypeid		VARCHAR(50) DEFAULT(''),
	KTypeID		VARCHAR(50) DEFAULT(''),
	CargoId INT,
	GoodsNumber	VARCHAR(100) DEFAULT(''),	-- 批号
	ItemId BIGINT,
	IsCombined INT,
	ProduceDate	VARCHAR(50) DEFAULT(''),	-- 生产日期
	ValidDate		VARCHAR(50) DEFAULT(''),	-- 效期至
	GoodsCostPrice	NUMERIC(24, 10) ,	-- 成本价
	LockNumber			 NUMERIC(24, 10) 	
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_LoseOverFlowBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertLoseBillDT]') AND TYPE in (N'P', N'PC'))
	BEGIN
		DROP PROC GP_InsertLoseBillDT
	END
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertOverFlowBillDT]') AND TYPE in (N'P', N'PC'))
	BEGIN
		DROP PROC GP_InsertOverFlowBillDT
	END
	DROP TYPE TBType_LoseOverFlowBill	
END
GO



/*
	Author:			 李海洋
	Create date: 2012-05-15 
	Description: 自定义表值类型(损,益单明细)
*/
CREATE TYPE dbo.TBType_LoseOverFlowBill AS TABLE
(
	BillNumberId			NUMERIC(10,0)
	,PtypeId  				VARCHAR(50)
	,Qty   						 NUMERIC(24, 10) 
	,Price   					 NUMERIC(24, 10) 
	,Total  					 NUMERIC(24, 10) 
	,Comment  				VARCHAR(255)
	,IsUnit2 					INT
	--@Serial				varchar(50)
	,Serial						VARCHAR(MAX)						-- 序列号值
	,InputCostPrice		 NUMERIC(24, 10) 	DEFAULT(0)	-- 成本单价	
	,GoodsNumber			VARCHAR(100)	DEFAULT('')	-- 批号
	,ProduceDate			VARCHAR(50)		DEFAULT('')	-- 生产日期
	,ValidDate				VARCHAR(50)		DEFAULT('')	-- 效期至
	,GoodsBTypeID			VARCHAR(50)		DEFAULT('')	-- 供货商ID值
	,GoodsCostPrice		 NUMERIC(24, 10) 	DEFAULT(0)	-- 出库批次成本单价
	,HandZeroCost			INT						DEFAULT(0)	-- 手工指定成本单价
	,STypeID					VARCHAR(50)		DEFAULT('')
	-- 9.0 新字段
	,UnitId						INT							-- 基本单位										
	,NUnitId					INT							-- 辅助单位
	,NQty							 NUMERIC(24, 10) 	-- 辅助数量
	,UnitRate					 NUMERIC(24, 10) 	-- 单位换算率
	,NUnitMsg					VARCHAR(50)			-- 换算结果
	,MUnitId					INT							-- 大单位
	,MQty							 NUMERIC(24, 10) 	-- 大单位数量
	,MUnitRate				 NUMERIC(24, 10) 	-- 大单位换算率
	,MUnitMsg					VARCHAR(50)			-- 大单位换算结果
	,MPrice						 NUMERIC(24, 10) 	-- 大单位单价
	,CargoId					INT							-- 货位ID
	,ItemId						BIGINT					-- 自由项id
	,IsCombined				INT							-- 是否组合
	,ShowOrder				INT
	,KTypeID				[varchar](50)
	,ifWX					INT
)
GO



/*
	作者：周华
	时间：2012-05-15 16:05:21.263
	描述：财务单据过据  多数单据通用的dt版表类型 
	
	6-11 添加ntotal字段
*/

IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_Money' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertMoneyBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertMoneyBillDT;
	--这里由于以前这样处理,所以现在删除不掉,只能让这个先删除
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertMoveMoneyBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC [Gp_InsertMoveMoneyBillDT];
	DROP TYPE TbType_Money;
END
GO

CREATE TYPE TbType_Money AS TABLE(
	ATypeId			varchar(50),
	Total			NUMERIC(24, 10) ,
	Comment			varchar(255),
	NTotal			NUMERIC(24, 10) ,
	[DTypeId]		VARCHAR(50) NOT NULL DEFAULT(''), --部分
	[ETypeId]		VARCHAR(50) NOT NULL DEFAULT(''), --经手人
	ShowOrder		INT,
	BrandarTypeId	VARCHAR(50)						  --品牌ID
);
GO






IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_MoveBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertMoveBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertMoveBillDT	
	DROP TYPE TBType_MoveBill	
END
GO



/*
	Author:			 李海洋
	Create date: 2012-05-12 
	Description: 自定义表值类型(同价调拨单)
*/
CREATE TYPE dbo.TBType_MoveBill AS TABLE
(
	 BillNumberId  	NUMERIC(10,0)
	,PtypeId  			VARCHAR(50)
	,Qty   					 NUMERIC(24, 10) 
	,Price   				 NUMERIC(24, 10) 
	,Total   				 NUMERIC(24, 10) 
	,Comment  			VARCHAR(256)
	,isUnit2 		INT
	--	@Serial			varchar(50)
	,Serial					VARCHAR(MAX)							-- 序列号值
	,InputCostPrice	 NUMERIC(24, 10) 	DEFAULT(0)	-- 成本单价
	,GoodsNumber		VARCHAR(100)		DEFAULT('')	-- 批号
	,ProduceDate		VARCHAR(50)			DEFAULT('')	-- 生产日期
	,ValidDate			VARCHAR(50)			DEFAULT('')	-- 效期至
	,GoodsBTypeID		VARCHAR(50)			DEFAULT('')	-- 供货商ID值
	,GoodsCostPrice	 NUMERIC(24, 10) 	DEFAULT(0)	-- 出库批次成本单价
	,HandZeroCost		INT							DEFAULT(0)	-- 手工指定成本单价
	,STypeID				VARCHAR(50)  		DEFAULT('')
	,KTypeId				VARCHAR(50)  		DEFAULT('')	-- 出库仓库
	,KTypeId2				VARCHAR(50)  		DEFAULT('')	-- 入库仓库
	-- 9.0新字段
	,UnitId					INT								--基本单位				
	,NUnitId				INT								--辅助单位
	,NQty						 NUMERIC(24, 10) 		--辅助数量
	,UnitRate				 NUMERIC(24, 10) 		--单位换算率
	,NUnitMsg				VARCHAR(50)				--换算结果
	,MUnitId				INT								--大单位
	,MQty						 NUMERIC(24, 10) 		--大单位数量
	,MUnitRate			 NUMERIC(24, 10) 		--大单位换算率
	,MUnitMsg				VARCHAR(50)				--大单位换算结果
	,MPrice					 NUMERIC(24, 10) 		--大单位单价
	,Incargoid			INT								--入库货位ID
	,Outcargoid			INT								--出库货位ID
	,ItemId					BIGINT						--自由项id
	,IsCombined			INT								--是否组合
    ,AllotID			INT							--调货申请单明细ID
	,Showorder			INT
)
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_MoveBjBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertMoveBjBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertMoveBjBillDT	
	DROP TYPE TBType_MoveBjBill	
END
GO



/*
	Author:			 李海洋
	Create date: 2012-05-12 
	Description: 自定义表值类型(变价调拨)
*/
CREATE TYPE dbo.TBType_MoveBjBill AS TABLE
(
	 BillNumberId  	NUMERIC(10,0)
	,PtypeId  			VARCHAR(50)
	,Qty   					 NUMERIC(24, 10) 
	,Price   				 NUMERIC(24, 10) 
	,Total  				 NUMERIC(24, 10) 
	,Comment  			VARCHAR(256)
	,IsUnit2 				INT
	--,	@Serial			varchar(50)
	,Serial					VARCHAR(max)											-- 序列号值
	,InputCostPrice	 NUMERIC(24, 10) 	DEFAULT(0)	-- 成本单价
	,GoodsNumber		VARCHAR(100) 	DEFAULT('') -- 批号
	,ProduceDate		VARCHAR(50) 	DEFAULT('')	-- 生产日期
	,ValidDate			VARCHAR(50) 	DEFAULT('')	-- 效期至
	,GoodsBTypeID		VARCHAR(50) 	DEFAULT('')	-- 供货商ID值
	,GoodsCostPrice	 NUMERIC(24, 10) 	DEFAULT(0)	-- 出库批次成本单价
	,HandZeroCost		INT						DEFAULT(0)	-- 手工指定成本单价
	,STypeID				VARCHAR(50)		DEFAULT('') 
	,KTypeId				VARCHAR(50)  	DEFAULT('')	-- 出库仓库
	,KTypeId2				VARCHAR(50)  	DEFAULT('')	-- 入库仓库
	-- 9.0 新字段
	,UnitId					INT							--基本单位														
	,NUnitId				INT							--辅助单位
	,NQty						 NUMERIC(24, 10) 	--辅助数量
	,UnitRate				 NUMERIC(24, 10) 	--单位换算率
	,NUnitMsg				VARCHAR(50)			--换算结果
	,MUnitId				INT							--大单位
	,MQty						 NUMERIC(24, 10) 	--大单位数量
	,MUnitRate			 NUMERIC(24, 10) 	--大单位换算率
	,MUnitMsg				VARCHAR(50)			--大单位换算结果
	,MPrice					 NUMERIC(24, 10) 	--大单位单价
	,Incargoid			INT							--入库货位ID
	,Outcargoid			INT							--出库货位ID
	,ItemId					BIGINT					--自由项id
	,IsCombined			INT							--是否组合
	,ShowOrder			INT
	,AllotId INT --调入的调货单行号ID (默认-1，专用于同价调货、变价调货、分支机构出库调申请单)
)
GO



/*
	作者：周华
	时间：2014-11-10
	描述：之前两个过程用的同一个tbtype,现在分开,添加了字段
	
	6-11 添加ntotal字段
*/

IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_MoveMoney' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertMoveMoneyBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertMoveMoneyBillDT;
	DROP TYPE TbType_MoveMoney;
END
GO

CREATE TYPE TbType_MoveMoney AS TABLE(
	ATypeId       varchar(50),
	Total         NUMERIC(24, 10) ,
	Comment       varchar(255),
	NTotal	 NUMERIC(24, 10) ,
	ShowOrder INT
);
GO







IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_NewTC' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertNewTCDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertNewTCDT;
	DROP TYPE TbType_NewTC;
END
GO

CREATE TYPE TbType_NewTC AS TABLE(
	BillNumberId			NUMERIC(18,0) ,
	EtypeID					VARCHAR(50),				--职员
	DtypeID					VARCHAR(50),				--部门
	Qty						 NUMERIC(24, 10)  DEFAULT(0) ,--数量
	Total					 NUMERIC(24, 10)  DEFAULT(0) ,--金额
	CommissionTotal			 NUMERIC(24, 10)  DEFAULT(0),--提成金额
	Comment					VARCHAR(256)	--备注
	,ShowOrder INT
)
GO





GO
/****** Object:  UserDefinedTableType [dbo].[TBType_OMBackBill]    Script Date: 07/29/2014 19:44:16 ******/
IF NOT EXISTS (select * from sys.systypes where name='TBType_OMBackBill')
BEGIN

CREATE TYPE [dbo].[TBType_OMBackBill] AS TABLE(
	[BillnumberID] [numeric](18, 0) NULL,
	[Ptypeid] [varchar](50) NULL,
	[Qty]  NUMERIC(24, 10)  NULL,
	[Price]  NUMERIC(24, 10)  NULL,
	[Total]  NUMERIC(24, 10)  NULL,
	[DisCount]  NUMERIC(24, 10)  NULL DEFAULT ((1)),
	[DiscountPrice]  NUMERIC(24, 10)  NULL,
	[SaleTotal]  NUMERIC(24, 10)  NULL,
	[UnitID] [int] NULL DEFAULT ((0)),
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[Comment] [varchar](255) NULL,
	[OrderIndexId] INT,
	[OrderId] INT
)

End
GO





/*
	作者：王涛
	时间：2014年11月11日 15:15:48
	描述：OM退货明细表生成销售退货单构造参数集合
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_OMBackDetail' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_GenerationSaleBackDetail]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_OM_GenerationSaleBackDetail;
	DROP TYPE TbType_OMBackDetail;
END
GO

CREATE TYPE TbType_OMBackDetail AS TABLE(
	id INT,
	qty  NUMERIC(24, 10) 
)
GO






IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_OMBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_SaveOrderDetail]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_OM_SaveOrderDetail;
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_SaveOMBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_SaveOMBillDT;
	DROP TYPE TBType_OMBill;
END
GO

CREATE TYPE [dbo].[TBType_OMBill] AS TABLE(
	[BillnumberID] [numeric](18, 0) NULL,
	[Ptypeid] [varchar](50) NULL,
	[Qty]  NUMERIC(24, 10)  NULL,
	[Price]  NUMERIC(24, 10)  NULL,
	[Total]  NUMERIC(24, 10)  NULL,
	[DisCount]  NUMERIC(24, 10)  NULL DEFAULT ((1)),
	[DiscountPrice]  NUMERIC(24, 10)  NULL,
	[SaleTotal]  NUMERIC(24, 10)  NULL,
	[UnitID] [int] NULL DEFAULT ((0)),
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[Comment] [varchar](255) NULL,
	IsGift BIT NOT NULL DEFAULT(0),
	pid NUMERIC(10,0) NOT NULL DEFAULT(0),
	bid INT ,--用于删除客户购物车
	productkey NUMERIC(10,0) NOT NULL DEFAULT(0),
	taxprice  NUMERIC(24, 10)  NULL,
	[tax]  NUMERIC(24, 10)  NULL
)
GO





GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_Order' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateOrderBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_UpdateOrderBillDT;
	DROP TYPE TbType_Order;
END
GO
/*
	作者：周华
	时间：2012-05-07 11:13:50.777
	描述：采购订单，销售订单 明细查入 对应的 表类型
*/
CREATE TYPE TbType_Order AS TABLE(
	--intBillNumberID		numeric(10,0),		--  1、单据 ID 值
	chvPTypeID				varchar(50)	DEFAULT(''),	--  2、商品 ID 值
	numQty					 NUMERIC(24, 10) 	DEFAULT(0),	--  3、商品数量
	numPrice				 NUMERIC(24, 10) 	DEFAULT(0),	--  4、商品单价
	numTotal				 NUMERIC(24, 10) 	DEFAULT(0),	--  5、商品金额(折后金额)
	chvComment				varchar(255)	DEFAULT(''),	--  6、单行备注
	--intFlag				int		DEFAULT(0),	--  7、操作标识 
	intOrderID				int		DEFAULT(0),	--  8、订单单据 ID 值 ( 已弃用 )
	intIsUnitTow			int,			--  9、是否采用双单位
	numReachQty			 NUMERIC(24, 10) 	DEFAULT(0),	-- 10、已发货 ( 收 ) 货数量
	numDiscount			 NUMERIC(24, 10) 	DEFAULT(1),	-- 11、扣率
	numDiscountPrice		 NUMERIC(24, 10) 	DEFAULT(0),	-- 12、折后单价
	numTaxPrice			 NUMERIC(24, 10) 	DEFAULT(0),	-- 13、税后单价
	numTaxTotal			 NUMERIC(24, 10) 	DEFAULT(0),	-- 14、税后金额
	numSaleTotal			 NUMERIC(24, 10) 	DEFAULT(0),	-- 15、普通金额（折前金额）
	numTax					 NUMERIC(24, 10) 	DEFAULT(0),	-- 16、税率
	KTypeID				varchar(50) DEFAULT(''),
	STypeID				varchar(50) DEFAULT(''),
	FromBillNumberID		numeric(10, 0),
	FromBillID				numeric(10, 0),
	requestbillnumberid	numeric(10, 0),
	requestbillid			numeric(10, 0),
	askbillnumberid		numeric(10, 0),
	askbillid				numeric(10, 0)
	
	-- 新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	--,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,GoodsNumber VARCHAR(100)
	,CargoID   INT
	,GoodsCostPrice  NUMERIC(24, 10)  NULL  DEFAULT (0)
	,GoodsOrder INT NULL  DEFAULT ('-1')
	,ProduceDate VARCHAR(50) NULL  DEFAULT ('')
	,ValidDate VARCHAR(50) NULL DEFAULT ('')
	,isrequest INT NULL  DEFAULT ('0')
	,oldcurmtaxprice  NUMERIC(24, 10) 
	,oldqty NUMERIC(24, 10) 
	,[entrycode] varchar(max)
	,isgift INT
	,YapiID VARCHAR(20) NULL DEFAULT('')
	,PriceSource VARCHAR(200) NOT NULL DEFAULT('')
	,OrderId INT NOT NULL DEFAULT(0)
	,Id INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,ShowOrder INT
	,SaleOrderReachQty NUMERIC(24, 10) 
	,SaleOrderId INT  DEFAULT(0)
	,PTCombinOrderBillDetailID INT DEFAULT(0)

);
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_OtherInOutBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertOtherInOutBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertOtherInOutBillDT	
	DROP TYPE TBType_OtherInOutBill	
END
GO



/*
	Author:			 李海洋
	Create date: 2012-05-15 
	Description: 自定义表值类型(其他出入库单)
*/
CREATE TYPE dbo.TBType_OtherInOutBill AS TABLE
(
	 BillNumberID			NUMERIC(10,0)
	,BillType					INT
	,KTypeId					VARCHAR(50)
	,PTypeId					VARCHAR(50)
	,Qty							 NUMERIC(24, 10) 
	,JobNumber				VARCHAR(20)
	,GoodsNo					INT
	,OutFactoryDate		datetime
	,Comment					VARCHAR(500)
	,IsUnit2					INT
	,Serial						VARCHAR(MAX)
	,InputCostPrice		 NUMERIC(24, 10) 
	,GoodsOrder				INT
	,GoodsNumber			VARCHAR(100)
	,ProduceDate			VARCHAR(50)
	,ValidDate				VARCHAR(50)
	,GoodsBTypeID			VARCHAR(50)
	,GoodsCostPrice		 NUMERIC(24, 10) 
	,GoodsCostTotal		 NUMERIC(24, 10) 	
	,HandZeroCost			INT
	,Price						 NUMERIC(24, 10) 
	,Total						 NUMERIC(24, 10) 
	,STypeId					VARCHAR(50)		
	-- 9.0 新字段
	,UnitId						INT							--基本单位										
	,NUnitId					INT							--辅助单位
	,NQty							 NUMERIC(24, 10) 	--辅助数量
	,UnitRate					 NUMERIC(24, 10) 	--单位换算率
	,NUnitMsg					VARCHAR(50)			--换算结果
	,MUnitId					INT							--大单位
	,MQty							 NUMERIC(24, 10) 	--大单位数量
	,MUnitRate				 NUMERIC(24, 10) 	--大单位换算率
	,MUnitMsg					VARCHAR(50)			--大单位换算结果
	,MPrice						 NUMERIC(24, 10) 	--大单位单价
	,CargoId					INT								--货位ID
	,ItemId						BIGINT					--自由项id
	,IsCombined				INT							--是否组合
	,ShowOrder				INT
)
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Pay' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertPayBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertPayBillDT;
	DROP TYPE TBType_Pay;
END
GO

CREATE TYPE dbo.TBType_Pay AS TABLE
( 
	BillNumberId  [numeric](10,0),
	AtypeId  [varchar](50),
	Total    NUMERIC(24, 10) ,
	Comment  [varchar](256),
	STypeID	VARCHAR(50),
	vipcardid	VARCHAR(MAX) DEFAULT('-1')
	--9.0新加字段	
	,ntotal		 NUMERIC(24, 10) 
	,RelevanceBillId INT
	,ShowOrder INT
) 
GO




























IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PosAllotApplyBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_SavePosAllotApplyBill]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_SavePosAllotApplyBill;
		
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_SavePosDeliveryApplyBill]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_SavePosDeliveryApplyBill;		
		
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_SaveDeliveryCheckBill]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_SaveDeliveryCheckBill;		
		
	DROP TYPE TBType_PosAllotApplyBill;
END
GO

CREATE TYPE dbo.TBType_PosAllotApplyBill AS TABLE
(
		ID				INT,
		BillNumberId	NUMERIC(18,0) NOT NULL,
		ptypeid			VARCHAR(200) NOT NULL,
		qty				NUMERIC(24,10)	NOT NULL DEFAULT(0),
		BaseUnitid		INT NULL,
		KtypeId			VARCHAR(50) NULL,
		InKtypeId		VARCHAR(50)	NULL,
		ItemId			INT NULL,
		IsCombined		INT NULL,
		comment			VARCHAR(250) NULL,
		MUnitid			INT,
		MQty			NUMERIC(24,10)	NOT NULL DEFAULT(0),
		MUnitRate		NUMERIC(24,10)	NOT NULL DEFAULT(1)
)

GO



/*
	作者：韩林
	时间：2013-01-15 
	描述：自定义POS小票表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PosSale' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_SavePosBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_SavePosBillDT;
	DROP TYPE TBType_PosSale;
END
GO

CREATE TYPE dbo.TBType_PosSale AS TABLE
(
		BillnumberID int,
		ID INT,
		PID INT,
		Qty  NUMERIC(24, 10) ,
		BackQty  NUMERIC(24, 10) ,
		RetailPrice  NUMERIC(24, 10) ,
		Tax  NUMERIC(24, 10)  DEFAULT(0),
		DisCount  NUMERIC(24, 10)   DEFAULT(1),
		Price  NUMERIC(24, 10)  ,
		RetailTotal  NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		UnitID INT DEFAULT(0),
		UnitRate  NUMERIC(24, 10)  Default(1),
		ItemID    bigint   NULL,
		IsCombined  int   NULL,
		BarCode	VARCHAR(200) NULL DEFAULT('') ,
		IsGift int NULL DEFAULT(0),
		Comment varchar(MAX) NULL,
		BaseUnitID INT  NULL DEFAULT(0),
		PromoType INT NOT NULL DEFAULT(0),
		SaleEid INT NOT NULL DEFAULT(0),
		validdate VARCHAR(50) NOT NULL DEFAULT('') ,
		producedate VARCHAR(50) NOT NULL DEFAULT('') ,
		goodsnumber VARCHAR(100) NOT NULL DEFAULT('') ,
		serial TEXT NOT NULL DEFAULT('') ,
		goodscostprice  NUMERIC(24, 10)  Default(0),
		[guid]   VARCHAR(100)  NULL DEFAULT('') ,
		couponcode VARCHAR(200) NULL DEFAULT(''),
		pricesource VARCHAR(200) NULL DEFAULT(''),
		PromoIDs VARCHAR(200) NULL DEFAULT('')
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Pre' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertPreBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertPreBillDT;
	DROP TYPE TBType_Pre;
END
GO

CREATE TYPE dbo.TBType_Pre AS TABLE
( 
	BillNumberId		[numeric](10,0),
	BillType			[int],
	AtypeId				[varchar](50),
	Total				NUMERIC(24, 10) ,
	Comment				[varchar](256),
	STypeID				[varchar](50) DEFAULT(''),
	vipcardid			INT DEFAULT(-1)
	--9.0新加字段	
	,ntotal				NUMERIC(24, 10),
	RelevanceBillId		INT,
	ShowOrder			INT,
	BrandarTypeId		VARCHAR(50)	--商品品牌
) 
GO




























/*
	作者：覃雨翔
	时间：2013-05-24 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PriceBillDetails' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPriceBillDetailsDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPriceBillDetailsDT;
	DROP TYPE TBType_PriceBillDetails;
END
GO

CREATE TYPE TBType_PriceBillDetails AS TABLE
(
    PriceBillIndexID         NUMERIC(18,0)
   ,State                    INT
   ,PtypeID                  VARCHAR(50)
   ,FreeID                   INT
   ,IsCombined               TINYINT
   ,UnitId                   INT
   ,PriceStyle               INT
   ,Price                     NUMERIC(24, 10) 
   ,Discount                  NUMERIC(24, 10) 
   ,DiscountPrice             NUMERIC(24, 10) 
   ,BeforeRetailPrice         NUMERIC(24, 10) 
   ,Tax                       NUMERIC(24, 10) 
   ,TaxPrice                  NUMERIC(24, 10) 
   ,IsPriceControl           TINYINT
   ,Comment                  VARCHAR(256)
   ,Checke                   VARCHAR(50)
   ,Checker                  VARCHAR(50)
   ,VaildDate                DATETIME
   ,CreateDate               DATETIME
   ,DeletedDate              DATETIME
   ,DeletedR                 VARCHAR(50)
   ,SortID                   INT
   ,OldID                    NUMERIC(18,0)
)
GO



/*
	作者：覃雨翔
	时间：2013-05-21 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PriceBillIndex_Stype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPriceBillIndex_StypeDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPriceBillIndex_StypeDT;
	DROP TYPE TBType_PriceBillIndex_Stype;
END
GO

CREATE TYPE TBType_PriceBillIndex_Stype AS TABLE
(
   PriceBillIndexID         INT
  ,StypeID                  VARCHAR(50)
)
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PriceProtect' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertPriceProtectBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertPriceProtectBillDT;
	DROP TYPE TBType_PriceProtect;
END
GO

CREATE TYPE dbo.TBType_PriceProtect AS TABLE
( 
	BillNumberID		numeric(10,0),	-- 单据 ID 值
	PtypeID			varchar(50),	-- 商品 ID 值
	OldTotal            NUMERIC(24, 10) ,
	Serial             varchar(50),
	OldPrice            NUMERIC(24, 10) ,
	NewPrice            NUMERIC(24, 10) ,
	Qty                 NUMERIC(24, 10) ,
	Total               NUMERIC(24, 10) ,
	Comment            varchar(255),
	BillType			int,
	Protectid			INT DEFAULT(-1),
	STypeID			varchar(50) DEFAULT('')
	--9.0新加字段	
	,ITEMID		BIGINT
	,IsCombined		INT
	,GoodsNumber	 VARCHAR(100)
) 
GO




























/*
	描述：取价规则往来单位自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PriceRule_Btype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertPriceRule_BtypeDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertPriceRule_BtypeDT;
	DROP TYPE TBType_PriceRule_Btype;
END
GO

CREATE TYPE TBType_PriceRule_Btype AS TABLE
(
   PriceRuleID              NUMERIC(18,0)
  ,Btypeid                  VARCHAR(50)
)
GO




/*
单据导入临时表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_PriceTemp' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_ImportPriceTempDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_ImportPriceTempDT;
	DROP TYPE TbType_PriceTemp;
END
GO

CREATE TYPE TbType_PriceTemp AS TABLE(
		[etypeid] [varchar] (50) NOT NULL,
		[typeid] [varchar] (50) NOT NULL,
		[usercode] [varchar] (200),
		[fullname] [varchar] (200),
		[itemid] BIGINT,
		[itemname] [varchar] (100) DEFAULT(''),
		[iscombined] [TINYINT] DEFAULT(0),
		[munit] [varchar] (100) DEFAULT(''),
		[munitid] INT,
		[munitrate]	  NUMERIC(24, 10) ,
		[baojiamode] int,
		[price]  NUMERIC(24, 10) ,
		[discount]  NUMERIC(24, 10) ,
		[curmdiscountprice]  NUMERIC(24, 10) ,
		[tax]  NUMERIC(24, 10) ,
		[curmtaxprice]  NUMERIC(24, 10) ,
		[xianjiamode] [BIT],
		[comment] [VARCHAR] (200)
)
GO







/*
单据导入临时表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_PriceTrackDetail' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_ImportPriceTrackDetail]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_ImportPriceTrackDetail;
	DROP TYPE TbType_PriceTrackDetail;
END
GO

CREATE TYPE TbType_PriceTrackDetail AS TABLE(
		BTypeID  varchar(100),
		BTypeFlag  int,
		PTypeID varchar(50),
		STypeID varchar(50),
		Price NUMERIC(24,10),
		DiscountRate NUMERIC(24,10),
		DiscountPrice NUMERIC(24,10),
		[UID] int,
		CID int,
		Tax numeric (24,10),
		TaxPrice NUMERIC(24,10)
)
GO






/*
	描述：促销往来单位自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PromoRule_Btype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertPromoRule_BtypeDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertPromoRule_BtypeDT;
	DROP TYPE TBType_PromoRule_Btype;
END
GO

CREATE TYPE TBType_PromoRule_Btype AS TABLE
(
   PromoRuleID              INT
  ,BtypeID                  VARCHAR(50)
)
GO



/*
	作者：覃雨翔
	时间：2013-05-28
	描述：促销业务员表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PromoRule_Detail_EConfig' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPromoRule_Detail_EConfigDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPromoRule_Detail_EConfigDT;
	DROP TYPE TBType_PromoRule_Detail_EConfig;
END
GO

CREATE TYPE TBType_PromoRule_Detail_EConfig AS TABLE
(
   PromoRuleID              INT
  ,Etypeid                  VARCHAR(50)
)
GO



/*
	作者：覃雨翔
	时间：2013-05-28
	描述：促销仓库自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PromoRule_Detail_KConfig' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPromoRule_Detail_KConfigDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPromoRule_Detail_KConfigDT;
	DROP TYPE TBType_PromoRule_Detail_KConfig;
END
GO

CREATE TYPE TBType_PromoRule_Detail_KConfig AS TABLE
(
   PromoRuleID              INT
  ,ktypeid                  VARCHAR(50)
)
GO



/*
	作者：覃雨翔
	时间：2013-05-28
	描述：促销商品表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PromoRule_Detail_PConfig' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPromoRule_Detail_PConfigDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPromoRule_Detail_PConfigDT;
	DROP TYPE TBType_PromoRule_Detail_PConfig;
END
GO

CREATE TYPE TBType_PromoRule_Detail_PConfig AS TABLE
(
   PromoRuleID              INT
  ,Ptypeid                  VARCHAR(50)
)
GO



/*
	作者：覃雨翔
	时间：2013-05-28
	描述：促销方式配置表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PromoRule_Detail_PromotConfig' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPromoRule_Detail_PromotConfigDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPromoRule_Detail_PromotConfigDT;
	DROP TYPE TBType_PromoRule_Detail_PromotConfig;
END
GO

CREATE TYPE TBType_PromoRule_Detail_PromotConfig AS TABLE
(
   PromoRuleID              INT
  ,PromoStylePtype          INT
  ,PromoStyleDiscount       INT
  ,BuyTotal                 NUMERIC(24, 10) 
  ,BuyQty                   NUMERIC(24, 10) 
  ,InDatesNum				INT	   -- 接近效期至天数
  ,DisCount                 NUMERIC(24, 10) 
  ,Ptypeid                  VARCHAR(50)
  ,Qty                      NUMERIC(24, 10) 
  ,OtherTotal               NUMERIC(24, 10) 
  ,GiftTypeID               INT
  ,CardTypeID               INT
  ,BindPtypeId              VARCHAR(50)
)
GO



/*
	作者：覃雨翔
	时间：2013-05-28
	描述：促销会员卡类型自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PromoRule_Detail_VIPConfig' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPromoRule_Detail_VIPConfigDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPromoRule_Detail_VIPConfigDT;
	DROP TYPE TBType_PromoRule_Detail_VIPConfig;
END
GO

CREATE TYPE TBType_PromoRule_Detail_VIPConfig AS TABLE
(
   PromoRuleID              NUMERIC(18,0)
  ,VipTypeID                INT
)
GO



/*
	作者：覃雨翔
	时间：2013-05-28
	描述：促销分支机构自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PromoRule_Stype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertPromoRule_StypeDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertPromoRule_StypeDT;
	DROP TYPE TBType_PromoRule_Stype;
END
GO

CREATE TYPE TBType_PromoRule_Stype AS TABLE
(
   PromoRuleID              INT
  ,StypeID                  VARCHAR(50)
)
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_PtypeCustom' AND ss.name = N'dbo')
BEGIN
	IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportProduct]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_ImportProduct]

	DROP TYPE TbType_PtypeCustom
END
GO

CREATE TYPE TbType_PtypeCustom AS TABLE(
EditKind			VARCHAR(50) ,				--数据类型
label				VARCHAR(50),				--属性名称
datafield			VARCHAR(50),				-- 数据库对应字段
maxbytelength		int     --长度
)
GO




/*
	作者：周华
	时间：2012-6-8
	描述：保存库存（先进先出）期初对应的表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_PtypeInit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPtypeInit]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPtypeInit;
	DROP TYPE TbType_PtypeInit;
END
GO

CREATE TYPE TbType_PtypeInit AS TABLE(
	qty  NUMERIC(24, 10)  DEFAULT(0)
	,price  NUMERIC(24, 10)  DEFAULT(0)
	,total  NUMERIC(24, 10)  DEFAULT(0)
	,Serial VARCHAR(8000)
);

GO 



/*
	By：Shixunguo
	Date：2015-5-14
	Description：受托委托代销期初, 序列号表值参数
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_PtypeSerialInit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_CommissionInitInsert]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_CommissionInitInsert;
	DROP TYPE TBType_PtypeSerialInit;
END
GO

CREATE TYPE TBType_PtypeSerialInit AS TABLE(
	 Serial		VARCHAR(1000) DEFAULT('')
	,KTypeID	VARCHAR(50) NULL DEFAULT('')
	,CostPrice	 NUMERIC(24, 10)  NULL DEFAULT(0)
	,goodsNumber	VARCHAR(100)	 	DEFAULT('')
	,itemId		INT							DEFAULT(0)
	,isCombined	BIT							DEFAULT(0)
	,producedate	VARCHAR(50) DEFAULT('')
	,validdate	VARCHAR(50) DEFAULT('')
	,CargoID	INT NULL DEFAULT(0)
);

GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_QuotePrice' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertQuotePriceBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertQuotePriceBillDT;
	DROP TYPE TBType_QuotePrice;
END
GO

CREATE TYPE TBType_QuotePrice AS TABLE(
	BillNumberID		numeric(10,0),	-- 单据 ID 值
	PtypeID			varchar(50),	-- 商品 ID 值
	Qty				 NUMERIC(24, 10) ,	-- 商品数量
	Price				 NUMERIC(24, 10) ,	-- 商品单价
	SaleTotal			 NUMERIC(24, 10) ,
	Discount			 NUMERIC(24, 10) ,	-- 
	DiscountPrice		 NUMERIC(24, 10) ,	-- 折后单价
	Total				 NUMERIC(24, 10) ,	-- 商品金额
	Tax				 NUMERIC(24, 10) ,
	TaxPrice			 NUMERIC(24, 10) ,	-- 税后单价
	TaxTotal			 NUMERIC(24, 10) ,	-- 价税合计
	Comment			varchar(255),	-- 备注
	intIsUnit2			int,			-- 是否采用双单位。0：否；1：是
	STypeID			varchar(50) DEFAULT('')
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	--,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	
	,ExpectedInterest  NUMERIC(24, 10) 
	,ExpectedInterestRate  NUMERIC(24, 10) 
	,IfBargainOn INT
	,ShowOrder	INT
	
);
GO



GO

IF EXISTS (SELECT Name FROM SysTypes WHERE Name=N'TbType_ReceiptBill' AND XType=243)
BEGIN
	IF EXISTS (SELECT Name FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'Gp_InsertReceiptBillDT',N'P'))
	BEGIN
		DROP PROC dbo.Gp_InsertReceiptBillDT;
	END
	DROP TYPE dbo.TbType_ReceiptBill;
END

GO

/*
			作者：司华山
			日期：2015-05-14
			描述：发票明细 表类型
*/

CREATE Type dbo.TbType_ReceiptBill AS TABLE 
(
	[BillNumberID] [numeric](10, 0) NOT NULL,
	[BillType] [numeric](4, 0) NOT NULL,
	[MainBillNumberID] [numeric](10, 0) NULL,
	[KTypeID] [varchar](100) NULL,
	[PTypeID] [varchar](100) NULL,
	[Qty]  NUMERIC(24, 10)  NULL,
	[Price]  NUMERIC(24, 10)  NULL,
	[Total]  NUMERIC(24, 10)  NULL,
	[Tax]  NUMERIC(24, 10)  NULL,
	[TaxPrice]  NUMERIC(24, 10)  NULL,
	[TaxTotal]  NUMERIC(24, 10)  NULL,
	[Comment] [varchar](255) NULL,
	[Stypeid] [varchar](50) NULL,
	[discount]  NUMERIC(24, 10)  NULL,
	[BeforePrice]  NUMERIC(24, 10)  NULL,
	[BeforeTotal]  NUMERIC(24, 10)  NULL,
	[RecordedItemId] [int] NOT NULL,
	[Nprice]  NUMERIC(24, 10)  NULL,
	[NTotal]  NUMERIC(24, 10)  NULL,
	[NTaxPrice]  NUMERIC(24, 10)  NULL,
	[NTaxTotal]  NUMERIC(24, 10)  NULL,
	[NTaxMoney]  NUMERIC(24, 10)  NULL,
	[CargoID] [int] NULL,
	[UnitID] [int] NULL,
	[NUnitID] [int] NULL,
	[NQty]  NUMERIC(24, 10)  NULL,
	[UnitRate]  NUMERIC(24, 10)  NULL,
	[NUnitMsg] [varchar](50) NULL,
	[MUnitID] [int] NULL,
	[MQty]  NUMERIC(24, 10)  NULL,
	[MUnitRate]  NUMERIC(24, 10)  NULL,
	[MUnitMsg] [varchar](50) NULL,
	[MPrice]  NUMERIC(24, 10)  NULL,
	[MTaxPrice]  NUMERIC(24, 10)  NULL,
	[CurMPrice]  NUMERIC(24, 10)  NULL,
	[CurMTaxPrice]  NUMERIC(24, 10)  NULL,
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[Nbeforeprice]  NUMERIC(24, 10)  NULL,
	[Nbeforetotal]  NUMERIC(24, 10)  NULL,
	[goodsnumber] [varchar](100) NULL,
	[saleprice]  NUMERIC(24, 10)  NULL,
	[saletotal]  NUMERIC(24, 10)  NULL,
	[nsaleprice]  NUMERIC(24, 10)  NULL,
	[nsaletotal]  NUMERIC(24, 10)  NULL,
	[curmsaleprice]  NUMERIC(24, 10)  NULL,
	[curmsaletotal]  NUMERIC(24, 10)  NULL,
	[taxmoney]  NUMERIC(24, 10)  NULL,
	[CompleteQty]  NUMERIC(24, 10)  NULL,
	[CompleteTotal]  NUMERIC(24, 10)  NULL,
	[NCompleteTotal]  NUMERIC(24, 10)  NULL,
	[IsGift] [int] NULL,
	[TeamNo] [int] NULL,
	[TeamNO1] [int] NULL,
	[InvoiceCostTotal]  NUMERIC(24, 10)  NULL,
	[MainBillType]	INT NULL DEFAULT(-1),
	[InvoiceCostPrice]  NUMERIC(24, 10) ,
	[ProduceDate] VARCHAR(50),
	[ValidDate]   VARCHAR(50),
	[Serial]	  VARCHAR(MAX),
	[ShowOrder]		INT,
	[ID]			INT
)
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Retail' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertRetailBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertRetailBillDT;
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPromoteRetailBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPromoteRetailBillDT;
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getserial]') and xtype in (N'FN', N'IF', N'TF'))
		drop function [dbo].[f_getserial]
	DROP TYPE TBType_Retail;
END
GO

CREATE TYPE dbo.TBType_Retail AS TABLE
(
	BillNumberId  [numeric](10,0),
	PtypeId  [varchar](50),
	Qty    NUMERIC(24, 10) ,
	SalePrice   NUMERIC(24, 10) ,
	Discount   NUMERIC(24, 10) ,
	DiscountPrice   NUMERIC(24, 10) ,
	Jobnumber  [varchar](20),
	Total    NUMERIC(24, 10) ,
	TaxPrice   NUMERIC(24, 10) ,
	TaxTotal   NUMERIC(24, 10) ,
	Comment  [varchar](255),
	OrderID [int],
	intIsUnit2 [int],
	--	@Serial varchar(50)
	Serial			VARCHAR(MAX),	-- 序列号值
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),			-- 手工指定成本单价
	InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	STypeID			varchar(50)DEFAULT('')
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,IsGift INT
	,BeforePromoID INT
	,[PriceDetailId] INT NOT NULL DEFAULT(0)
	,[PriceRuleId] INT NOT NULL DEFAULT(0)
	,[PriceSource] VARCHAR(500) NOT NULL DEFAULT('')
	,PosId INT  NOT NULL DEFAULT(0)
	,ReferPrice  NUMERIC(24, 10) 
	,PriceStyle INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,ETypeId  VARCHAR(50)-- 业务员
	,ShowOrder INT
	,iscombination	BIT NOT NULL DEFAULT(0)
	,combinationptypeid VARCHAR(200) NULL
	,pindexid VARCHAR(300) NULL
	,KTypeID VARCHAR(50) 
	,PromonIds VARCHAR(1000) DEFAULT('')
	,CouponCode VARCHAR(200)                      
    ,IsPromotion	INT
    ,IsVipPoint	INT
) 
GO



/*
	作者：韩林
	时间：2013-06-05
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_RetailBack' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertRetailBackBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertRetailBackBillDT;
	DROP TYPE TBType_RetailBack;
END
GO

CREATE TYPE TBType_RetailBack AS TABLE
(
	BillNumberId  		[numeric](10,0)
	,PtypeId  			[varchar](50)
	,Qty   				 NUMERIC(24, 10) 
	,SalePrice  		 NUMERIC(24, 10) 
	,Discount  			 NUMERIC(24, 10) 
	,DiscountPrice  	 NUMERIC(24, 10) 
	,jobnumber   		[varchar](20)
	,Total   			 NUMERIC(24, 10) 
	,MakeDate  			[datetime]
	,TaxPrice  			 NUMERIC(24, 10) 
	,TaxTotal  			 NUMERIC(24, 10) 
	,Comment  			[varchar](255)
	,intisUnit2  		[int]
	,Serial				VARCHAR(MAX)						-- 序列号值
	,InputCostPrice		 NUMERIC(24, 10)  DEFAULT(0)      		-- 手工输入的成本
	,GoodsNumber	varchar(100) DEFAULT('')	-- 批号
	,ProduceDate	varchar(50) DEFAULT('')	-- 生产日期
	,ValidDate		varchar(50) DEFAULT('')	-- 效期至
	,GoodsBTypeID	varchar(50) DEFAULT('')	-- 供货商ID值
	,GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0)	-- 出库批次成本单价
	,HandZeroCost	int DEFAULT(0)			-- 手工指定成本单价
	,SaleTotal		 NUMERIC(24, 10)  DEFAULT(0)
	,Tax			 NUMERIC(24, 10)  DEFAULT(0)
	,STypeID		varchar(50) DEFAULT('')
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoID INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,ISGift INT	
	,OldBillNumberID  	[numeric](10,0) DEFAULT(0) 	
	,OldID  			[varchar](20) DEFAULT('')  		
	,CompleteQTY  NUMERIC(24, 10) 
	,PosId INT  NOT NULL DEFAULT(0)
	,ReferPrice  NUMERIC(24, 10) 	
	,PriceStyle INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,ETypeId VARCHAR(50)--业务员
	,ShowOrder INT
	,KTypeID VARCHAR(50)
	,PriceSource VARCHAR(100)
	,Couponcode VARCHAR(200)
) 
GO



GO
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_RetailCombination' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertRetailCombinationDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertRetailCombinationDT;
	DROP TYPE TbType_RetailCombination;
END

CREATE TYPE TbType_RetailCombination
AS 
TABLE 
(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) ,
		[Qty] [numeric](24, 10) NOT NULL,
		[SalePrice] [numeric](24, 10) NULL,
		[discount] [numeric](24, 10) NULL  DEFAULT (1),
		[DiscountPrice] [numeric](24, 10) NULL,
		[total] [numeric](24, 10) NULL,
		[OutFactoryDate] [datetime] NULL,
		[TaxPrice] [numeric](24, 10) NULL,
		[TaxTotal] [numeric](24, 10) NULL,
		[IsUnit2] [int] NOT NULL  DEFAULT (0),
		[BackQTY] [numeric](24, 10) NULL DEFAULT (0),
		[SaleTotal] [numeric](24, 10) NULL DEFAULT (0),
		[Tax] [numeric](5, 2) NULL DEFAULT (0),
		[Stypeid] [varchar](50)  NULL DEFAULT (''),
		TaxMoney             numeric(22,10)    NULL Default(0),
		NSalePrice           numeric(22,10)      NULL Default(0),
		NSaleTotal           numeric(22,10)      NULL Default(0),
		NDiscountPrice       numeric(22,10)      NULL Default(0),
		NTotal               numeric(22,10)      NULL Default(0),
		NTaxPrice            numeric(22,10)      NULL Default(0),
		NTaxTotal            numeric(22,10)      NULL Default(0),
		NTaxMoney            numeric(22,10)      NULL Default(0),
		UnitID               int                NULL Default(0),
		NUnitID              int                NULL Default(0),
		NQty                 numeric(22,10)     NULL Default(0),
		UnitRate             numeric(22,10)     NULL Default(0),
		NUnitMsg             varchar(50)        null,
		MUnitID              int                NULL Default(0),
		MQty                 numeric(22,10)     NULL Default(0),
		MUnitRate            numeric(22,10)     NULL Default(1),
		MUnitMsg             varchar(50)        null,
		MSalePrice           numeric(22,10)     NULL Default(0),
		MDiscountPrice       numeric(22,10)     NULL Default(0),
		MTaxPrice            numeric(22,10)     NULL Default(0),
		CurMSalePrice        numeric(22,10)     NULL Default(0),
		CurMDiscountPrice    numeric(22,10)     NULL Default(0),
		CurMTaxPrice         numeric(22,10)     NULL Default(0),
		CargoID              int               NULL Default(0),
		InvoiceQty			 numeric(18, 4)		NULL DEFAULT (0),
		InvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		NInvoiceMoney		 numeric(22,10)		null DEFAULT(0),
		IsGift INT NOT NULL DEFAULT(0), --是否赠品
		PosId INT  NOT NULL DEFAULT(0),
		BeforePromoID INT NULL DEFAULT(0),
		[PriceDetailId] INT NOT NULL DEFAULT(0),
		[PriceRuleId] INT NOT NULL DEFAULT(0),
		[PriceSource] VARCHAR(500) NOT NULL DEFAULT(''),
		PriceStyle INT NOT NULL DEFAULT(0), --价格类型
		PromoType INT NOT NULL DEFAULT(0), 
		pindexid	VARCHAR(300),
		[comment] [varchar](255) ,
		ETypeID VARCHAR(100),
		itemid	 INT,
		Iscombined INT,
		PromonIds	VARCHAR(1000),
		CouponCode VARCHAR(200),
		IsPromotion	INT ,
		IsVipPoint INT 
)
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Sale' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertSaleBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertSaleBillDT;
	
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPromoteSaleBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPromoteSaleBillDT;
	DROP TYPE TBType_Sale;
END
GO

CREATE TYPE dbo.TBType_Sale AS TABLE
(
	BillNumberId  	[numeric](10,0),
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10) ,
	SalePrice  	 NUMERIC(24, 10) ,
	Discount  		 NUMERIC(24, 10) ,
	DiscountPrice   NUMERIC(24, 10) ,
	Jobnumber  	[varchar](20),
	Total   		 NUMERIC(24, 10) ,
	OutFactoryDate [datetime] DEFAULT(NULL),
	TaxPrice  		 NUMERIC(24, 10) ,
	TaxTotal  		 NUMERIC(24, 10) ,
	Comment  		[varchar](255),
	OrderID 		[int],
	intisUnitTow 	[int],
	Serial			VARCHAR(MAX),	-- 序列号值
	InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
	GoodsNumber	varchar(100)  DEFAULT(''),	-- 批号
	ProduceDate	varchar(50)  DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50)  DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50)  DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)   DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int  DEFAULT(0),			-- 手工指定成本单价
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	KTypeID		[varchar](50) DEFAULT(''),
	STypeID		[varchar](50)
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQTY  NUMERIC(24, 10) 
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,entryCode VARCHAR(200)
	
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,PriceSource VARCHAR(200)--价格来源
	,IsGift INT
	,BeforePromoID INT
	,ReferPrice  NUMERIC(24, 10) 
	,PriceStyle INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,OMBillID INT
	,LendBillID		NUMERIC(10,0)
	,LendBillNumberID		NUMERIC(10,0)
	,ID INT
	,ShowOrder	INT
	,DiyID INT
	,iscombination BIT NULL DEFAULT(0)
	,combinationptypeid varchar(200) NULL
	,pindexid VARCHAR(300) NULL
	,ETypeID  VARCHAR(100)
	,PromonIds	VARCHAR(1000)
	,CouponCode VARCHAR(200)	
	,IsPromotion	INT
	,IsVipPoint	INT	
	,[PriceDetailId] INT  NULL DEFAULT(0)
	,[PriceRuleId] INT  NULL DEFAULT(0)
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_SaleAutoDraft' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertSaleBillAutoDraftDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertSaleBillAutoDraftDT;
	
	DROP TYPE TBType_SaleAutoDraft;
END
GO

CREATE TYPE dbo.TBType_SaleAutoDraft AS TABLE
(
	BillGuid		VARCHAR(100),
	BillNumberId  	[numeric](10,0),
	PtypeId  		[varchar](50),
	Qty   			 NUMERIC(24, 10) ,
	SalePrice  	 NUMERIC(24, 10) ,
	Discount  		 NUMERIC(24, 10) ,
	DiscountPrice   NUMERIC(24, 10) ,
	Jobnumber  	[varchar](20),
	Total   		 NUMERIC(24, 10) ,
	OutFactoryDate [datetime] DEFAULT(NULL),
	TaxPrice  		 NUMERIC(24, 10) ,
	TaxTotal  		 NUMERIC(24, 10) ,
	Comment  		[varchar](255),
	OrderID 		[int],
	intisUnitTow 	[int],
	Serial			VARCHAR(MAX),	-- 序列号值
	InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
	GoodsNumber	varchar(100)  DEFAULT(''),	-- 批号
	ProduceDate	varchar(50)  DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50)  DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50)  DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)   DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int  DEFAULT(0),			-- 手工指定成本单价
	Tax			 NUMERIC(24, 10)  DEFAULT(0),
	SaleTotal		 NUMERIC(24, 10)  DEFAULT(0),
	KTypeID		[varchar](50) DEFAULT(''),
	STypeID		[varchar](50)
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQTY  NUMERIC(24, 10) 
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,entryCode VARCHAR(200)
	
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,PriceSource VARCHAR(200)--价格来源
	,IsGift INT
	,BeforePromoID INT
	,ReferPrice  NUMERIC(24, 10) 
	,PriceStyle INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,OMBillID INT
	,LendBillID		NUMERIC(10,0)
	,LendBillNumberID		NUMERIC(10,0)
	,ID INT
	,ShowOrder	INT
	,DiyID INT
	,iscombination BIT NULL DEFAULT(0)
	,combinationptypeid varchar(200) NULL
	,pindexid VARCHAR(300) NULL
	,ETypeID  VARCHAR(100)
	,PromonIds	VARCHAR(1000)
	,CouponCode VARCHAR(200)	
	,IsPromotion	INT
	,IsVipPoint	INT	
	,[PriceDetailId] INT  NULL DEFAULT(0)
	,[PriceRuleId] INT  NULL DEFAULT(0)
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_SaleBack' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertSaleBackBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertSaleBackBillDT;
	DROP TYPE TBType_SaleBack;
END
GO

CREATE TYPE dbo.TBType_SaleBack AS TABLE
(
	BillNumberId  		[numeric](10,0)
	,PtypeId  			[varchar](50)
	,Qty   				 NUMERIC(24, 10) 
	,SalePrice  		 NUMERIC(24, 10) 
	,Discount  			 NUMERIC(24, 10) 
	,DiscountPrice  	 NUMERIC(24, 10) 
	,JobNo   			[varchar](20)
	,Total   			 NUMERIC(24, 10) 
	,MakeDate  			[datetime]
	,TaxPrice  			 NUMERIC(24, 10) 
	,TaxTotal  			 NUMERIC(24, 10) 
	,Comment  			[varchar](255)
	,intisUnit2  		[int]
	,Serial				VARCHAR(max)						-- 序列号值
	,OldID  			[varchar](20) DEFAULT('')  			-- 新增销售退货，采购退货关联的商品行的写入顺序ID add by chen_qihua 2004-6-18
	,OldBillNumberID  	[numeric](10,0) DEFAULT(0) 			-- 新增销售退货，采购退货关联的单据ID      		-- 新增销售退货，采购退货关联的商品的成本
	,InputCostPrice		 NUMERIC(24, 10)  DEFAULT(0)      		-- 手工输入的成本
	,GoodsNumber	varchar(100) DEFAULT('')	-- 批号
	,ProduceDate	varchar(50) DEFAULT('')	-- 生产日期
	,ValidDate		varchar(50) DEFAULT('')	-- 效期至
	,GoodsBTypeID	varchar(50) DEFAULT('')	-- 供货商ID值
	,GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0)	-- 出库批次成本单价
	,HandZeroCost	int DEFAULT(0)			-- 手工指定成本单价
	,Tax			 NUMERIC(24, 10)  DEFAULT(0)
	,SaleTotal		 NUMERIC(24, 10)  DEFAULT(0)
	,KTypeID		varchar(50) DEFAULT('')
	,STypeID		varchar(50) DEFAULT('')
	,FromBillNumberID	[numeric](10,0) DEFAULT(0)
	,FromBillID			[numeric](10,0) DEFAULT(0)
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQTY  NUMERIC(24, 10) 
	
	,InvoiceQty DECIMAL(18,4)
	,InvoiceMoney DECIMAL(22,10)
	,NInvoiceMoney DECIMAL(22,10)
	,IsGift INT
	,ReferPrice  NUMERIC(24, 10) 
	,PriceStyle INT NOT NULL DEFAULT(0)
	,PromoType INT NOT NULL DEFAULT(0)
	,OMBillID INT
	,CompleteTotal  NUMERIC(24, 10) 
	,NCompleteTotal  NUMERIC(24, 10) 
	,ID INT
	,ShowOrder INT
	,ETypeID	VARCHAR(100)
	,PriceSource VARCHAR(100)
	,CouponCode VARCHAR(200)
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_SaleGoodsExchange' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertSaleGoodsExchangeBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertSaleGoodsExchangeBillDT;
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'GP_SaleGoodsExchangeCheck',N'P'))
		DROP PROC GP_SaleGoodsExchangeCheck
	DROP TYPE TBType_SaleGoodsExchange;
END
GO

CREATE TYPE dbo.TBType_SaleGoodsExchange AS TABLE
(
	BillNumberId  	[numeric](10,0)
	,InOrOut  		[char](1)
	,PtypeId  		[varchar](50)
	,Qty   			 NUMERIC(24, 10) 
	,SalePrice  	 NUMERIC(24, 10) 
	,Discount  		 NUMERIC(24, 10) 
	,DiscountPrice   NUMERIC(24, 10) 
	,Jobnumber  	[varchar](20)
	,Total   		 NUMERIC(24, 10) 
	,OutFactoryDate [datetime] DEFAULT(NULL)
	,TaxPrice  		 NUMERIC(24, 10) 
	,TaxTotal  		 NUMERIC(24, 10) 
	,Comment  		[varchar](255)
	,intisUnitTow 	[int]
	,Serial			VARCHAR(MAX)				-- 序列号值
	,InputCostPrice  NUMERIC(24, 10)  DEFAULT(0)	-- 成本单价
	,GoodsNumber	varchar(100) DEFAULT('')	-- 批号
	,ProduceDate	varchar(50) DEFAULT('')	-- 生产日期
	,ValidDate		varchar(50) DEFAULT('')	-- 效期至
	,GoodsBTypeID	varchar(50) DEFAULT('')	-- 供货商ID值
	,GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0)	-- 出库批次成本单价
	,HandZeroCost	int DEFAULT(0)			-- 手工指定成本单价
	,Tax			 NUMERIC(24, 10)  DEFAULT(0)
	,SaleTotal		 NUMERIC(24, 10)  DEFAULT(0)
	,KTypeID		varchar(50) DEFAULT('')
	,STypeID		varchar(50) DEFAULT('')
	-- 9.0新字段
	,TaxMoney  NUMERIC(24, 10) 
	,NSalePrice  NUMERIC(24, 10) 
	,NSaleTotal  NUMERIC(24, 10) 
	,NDiscountPrice  NUMERIC(24, 10) 
	,NTotal  NUMERIC(24, 10) 
	,NTaxPrice  NUMERIC(24, 10) 
	,NTaxTotal  NUMERIC(24, 10) 
	,NTaxMoney  NUMERIC(24, 10) 
	,CargoId INT
	,UnitId INT
	,NUnitId INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,NUnitMsg VARCHAR(50)
	,MUnitId INT
	,MQty  NUMERIC(24, 10) 
	,MUnitRate  NUMERIC(24, 10) 
	,MUnitMsg VARCHAR(50)
	,MSalePrice  NUMERIC(24, 10) 
	,MDiscountPrice  NUMERIC(24, 10) 
	,MTaxPrice  NUMERIC(24, 10) 
	,CurMSalePrice  NUMERIC(24, 10) 
	,CurMDiscountPrice  NUMERIC(24, 10) 
	,CurMTaxPrice  NUMERIC(24, 10) 
	,ItemId BIGINT
	,IsCombined INT
	,CompleteQTY  NUMERIC(24, 10) 
	
	,InvoiceQty  NUMERIC(24, 10) 
	,InvoiceMoney  NUMERIC(24, 10) 
	,NInvoiceMoney  NUMERIC(24, 10) 
	,IsGift INT
	,ReferPrice  NUMERIC(24, 10) 
	,PriceStyle INT NOT NULL DEFAULT(0)
	,OldID  			VARCHAR(20) DEFAULT('')  			-- 新增销售退货，采购退货关联的商品行的写入顺序ID
	,OldBillNumberID  	NUMERIC(10,0) DEFAULT(0) 			-- 新增销售退货，采购退货关联的单据ID      		-- 新增销售
	,CompleteTotal       NUMERIC(24, 10) 
	,NCompleteTotal      NUMERIC(24, 10)
	,ShowOrder			INT
	,ETypeID			VARCHAR(100)
	,PriceSource VARCHAR(200)
) 
GO



GO

IF EXISTS (SELECT Name FROM SysTypes WHERE Name=N'TbType_SendBackBill' AND XType=243)
BEGIN
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'Gp_InsertSendBackBillDT',N'P'))
	BEGIN			  
		DROP PROC dbo.Gp_InsertSendBackBillDT;
	END
	
	IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertSendBackBillDTCheck',N'P'))
	BEGIN
		DROP PROC dbo.GP_InsertSendBackBillDTCheck
	END
	DROP TYPE dbo.TbType_SendBackBill;
END

GO

/*		
		作者：司华山
		日期：2015-05-14
		描述：发出商品退货表类型
*/

CREATE TYPE dbo.TbType_SendBackBill AS TABLE
(
		[BillNumberId] [numeric](10, 0) NOT NULL,
		[PtypeId] [varchar](50) NULL,
		[Qty]  NUMERIC(24, 10)  NOT NULL,
		[SalePrice]  NUMERIC(24, 10)  NOT NULL,
		[discount]  NUMERIC(24, 10)  NOT NULL,
		[DiscountPrice]  NUMERIC(24, 10)  NULL,
		[total]  NUMERIC(24, 10)  NOT NULL,
		[TaxPrice]  NUMERIC(24, 10)  NULL,
		[TaxTotal]  NUMERIC(24, 10)  NULL,
		[comment] [varchar](255) NULL,
		[TeamNo] [int] NULL,
		[TeamNO1] [int] NULL,
		[Serial] [varchar](max) NULL,
		[OldID] [varchar](50) NULL,
		[CostPrice]  NUMERIC(24, 10)  NULL,
		[OldBillNumberID] [numeric](18, 0) NULL,
		[InputCostPrice]  NUMERIC(24, 10)  NULL,
		[GoodsOrder] [int] NULL,
		[GoodsNumber] [varchar](100) NULL,
		[ProduceDate] [varchar](50) NULL,
		[ValidDate] [varchar](50) NULL,
		[GoodsCostPrice]  NUMERIC(24, 10)  NULL,
		[HandZeroCost] [int] NULL,
		[SaleTotal]  NUMERIC(24, 10)  NULL,
		[Tax]  NUMERIC(24, 10)  NULL,
		[KTypeID] [varchar](50) NULL,
		[Stypeid] [varchar](50) NULL,
		[TaxMoney]  NUMERIC(24, 10)  NULL,
		[NSalePrice]  NUMERIC(24, 10)  NULL,
		[NSaleTotal]  NUMERIC(24, 10)  NULL,
		[NDiscountPrice]  NUMERIC(24, 10)  NULL,
		[NTotal]  NUMERIC(24, 10)  NULL,
		[NTaxPrice]  NUMERIC(24, 10)  NULL,
		[NTaxTotal]  NUMERIC(24, 10)  NULL,
		[NTaxMoney]  NUMERIC(24, 10)  NULL,
		[UnitID] [int] NULL,
		[NUnitID] [int] NULL,
		[NQty]  NUMERIC(24, 10)  NULL,
		[UnitRate]  NUMERIC(24, 10)  NULL,
		[NUnitMsg] [varchar](50) NULL,
		[MUnitID] [int] NULL,
		[MQty]  NUMERIC(24, 10)  NULL,
		[MUnitRate]  NUMERIC(24, 10)  NULL,
		[MUnitMsg] [varchar](50) NULL,
		[MSalePrice]  NUMERIC(24, 10)  NULL,
		[MDiscountPrice]  NUMERIC(24, 10)  NULL,
		[MTaxPrice]  NUMERIC(24, 10)  NULL,
		[CurMSalePrice]  NUMERIC(24, 10)  NULL,
		[CurMDiscountPrice]  NUMERIC(24, 10)  NULL,
		[CurMTaxPrice]  NUMERIC(24, 10)  NULL,
		[CargoID] [int] NULL,
		[ItemID] [bigint] NULL,
		[IsCombined] [int] NULL,
		[InvoiceQty]  NUMERIC(24, 10)  NULL,
		[InvoiceMoney]  NUMERIC(24, 10)  NULL,
		[NInvoiceMoney]  NUMERIC(24, 10)  NULL,
		[IsGift] [int] NULL,
		[ReferPrice]  NUMERIC(24, 10)  NOT NULL,
		[PriceStyle] [int] NOT NULL,
		[InvoiceMoneyEX]  NUMERIC(24, 10)  NULL,
		[NInvoiceMoneyEX]  NUMERIC(24, 10)  NULL,
		[InvoiceCostTotal]  NUMERIC(24, 10)  NULL,
		[InvoiceNQty]  NUMERIC(24, 10)  NULL,
		[CostTotal]   NUMERIC(24, 10)  NULL,
		[InvoiceSaleMoney]  NUMERIC(24, 10)  NULL,
		[NInvoiceSaleMoney]  NUMERIC(24, 10)  NULL,
		[ShareFee]  NUMERIC(24, 10)  NULL,
		[ShowOrder]			INT,
		[ID]				INT,
		[PriceSource] VARCHAR(200)
)
GO



GO

IF EXISTS (SELECT Name FROM SysTypes WHERE Name='TbType_SendBill' AND XType='243')
BEGIN
	IF EXISTS (SELECT Name FROM SysOBjects WHERE ID=OBJECT_ID(N'Gp_InsertSendBillDT',N'P'))
	BEGIN
		DROP  PROC dbo.Gp_InsertSendBillDT
	END
	DROP  TYPE dbo.TbType_SendBill 
END

GO

/*
			作者：司华山
			日期：2015-05-14
			描述：发出商品明细表类型
*/

CREATE TYPE dbo.TbType_SendBill AS TABLE
(
	[BillNumberId] [numeric](10, 0) NOT NULL,
	[PtypeId] [varchar](50) NULL,
	[Qty]  NUMERIC(24, 10)  NOT NULL,
	[SalePrice]  NUMERIC(24, 10)  NULL,
	[discount]  NUMERIC(24, 10)  NULL,
	[DiscountPrice]  NUMERIC(24, 10)  NULL,
	[costprice]  NUMERIC(24, 10)  NULL,
	[total]  NUMERIC(24, 10)  NULL,
	[TaxPrice]  NUMERIC(24, 10)  NULL,
	[TaxTotal]  NUMERIC(24, 10)  NULL,
	[comment] [varchar](255) NULL,
	[OrderID] [int] NULL,
	[TeamNo] [int] NULL,
	[TeamNO1] [int] NULL,
	[Serial] [varchar](max) NULL,
	[InputCostPrice]  NUMERIC(24, 10)  NULL,
	[GoodsOrder] [int] NULL,
	[BackQty]  NUMERIC(24, 10)  NULL,
	[GoodsNumber] [varchar](100) NULL,
	[ProduceDate] [varchar](50) NULL,
	[ValidDate] [varchar](50) NULL,
	[GoodsCostPrice]  NUMERIC(24, 10)  NULL,
	[HandZeroCost] [int] NULL,
	[SaleTotal]  NUMERIC(24, 10)  NULL,
	[Tax]  NUMERIC(24, 10)  NULL,
	[KTypeID] [varchar](50) NULL,
	[Stypeid] [varchar](50) NULL,
	[ShareFee]  NUMERIC(24, 10)  NULL,
	[TaxMoney]  NUMERIC(24, 10)  NULL,
	[NSalePrice]  NUMERIC(24, 10)  NULL,
	[NSaleTotal]  NUMERIC(24, 10)  NULL,
	[NDiscountPrice]  NUMERIC(24, 10)  NULL,
	[NTotal]  NUMERIC(24, 10)  NULL,
	[NTaxPrice]  NUMERIC(24, 10)  NULL,
	[NTaxTotal]  NUMERIC(24, 10)  NULL,
	[NTaxMoney]  NUMERIC(24, 10)  NULL,
	[UnitID] [int] NULL,
	[NUnitID] [int] NULL,
	[NQty]  NUMERIC(24, 10)  NULL,
	[UnitRate]  NUMERIC(24, 10)  NULL,
	[NUnitMsg] [varchar](50) NULL,
	[MUnitID] [int] NULL,
	[MQty]  NUMERIC(24, 10)  NULL,
	[MUnitRate]  NUMERIC(24, 10)  NULL,
	[MUnitMsg] [varchar](50) NULL,
	[MSalePrice]  NUMERIC(24, 10)  NULL,
	[MDiscountPrice]  NUMERIC(24, 10)  NULL,
	[MTaxPrice]  NUMERIC(24, 10)  NULL,
	[CurMSalePrice]  NUMERIC(24, 10)  NULL,
	[CurMDiscountPrice]  NUMERIC(24, 10)  NULL,
	[CurMTaxPrice]  NUMERIC(24, 10)  NULL,
	[CargoID] [int] NULL,
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[entryCode] [varchar](200) NULL,
	[InvoiceQty]  NUMERIC(24, 10)  NULL,
	[InvoiceMoney]  NUMERIC(24, 10)  NULL,
	[NInvoiceMoney]  NUMERIC(24, 10)  NULL,
	[PriceSource] [varchar](200) NULL,
	[IsGift] [int] NOT NULL,
	[ReferPrice]  NUMERIC(24, 10)  NOT NULL,
	[PriceStyle] [int] NOT NULL,
	[InvoiceMoneyEX]  NUMERIC(24, 10)  NULL,
	[NInvoiceMoneyEX]  NUMERIC(24, 10)  NULL,
	[InvoiceCostTotal]  NUMERIC(24, 10)  NULL,
	[OldBillNumberID] numeric(10,0) NULL,
	[OldID]	numeric(10,0) NULL,
	[InvoiceNQty]  NUMERIC(24, 10)  NULL,
	[CostTotal]   NUMERIC(24, 10)  NULL,
	[InvoiceSaleMoney]  NUMERIC(24, 10)  NULL,
	[NInvoiceSaleMoney]  NUMERIC(24, 10)  NULL,
	[ShowOrder]		INT,
	[ID]			INT
)

GO



/*
	作者：李海洋
	时间：2012-05-12 
	描述：自定义表值类型(序列号调整单)
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_SerialEdit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertSerialAdjustBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertSerialAdjustBillDT;
	DROP TYPE TBType_SerialEdit;
END
GO

CREATE TYPE dbo.TBType_SerialEdit AS TABLE
(
	BillNumberId		NUMERIC(10, 0),	--单据编号
	Serial					VARCHAR(1000),		--新序列号
	OldSerial				VARCHAR(1000),		--旧的序列号
	Ktypeid					VARCHAR(50),		--仓库
	Ptypeid					VARCHAR(50),		--商品
	Btypeid1				VARCHAR(50),		--供应商
	Btypeid2				VARCHAR(50),		--销售商
	InKtypeTime			DATETIME,				--入库时间
	OutKtypeTime		DATETIME,				--出库时间
	State						INT,						--状态
	Note						VARCHAR(500),		--备注
	ShowOrder		INT
	-- 9.0新字段
) 
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_SerialNo' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_SerialOperateForLendDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_SerialOperateForLendDT;
	DROP TYPE TbType_SerialNo;
END
GO

/*
	作者：周华
	时间：2012-05-11 09:45:33.390
	描述：处理借欠所有单据的序列号dt版 对应表类型
*/
CREATE TYPE TbType_SerialNo AS TABLE(
	rn INT
	,pTypeId INT
	,sn VARCHAR(1000)
)
GO




/*
	作者：周华
	时间：2012-05-15 16:05:21.263
	描述：采购待摊费用明细1保存dt版表类型 
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_ShareFee' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertShareFeeBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertShareFeeBillDT;
	DROP TYPE TbType_ShareFee;
END
GO

CREATE TYPE TbType_ShareFee AS TABLE(
	FromBillNumberID INT
	,FromBillId	INT
	,Comment NVARCHAR(MAX)
	,ShowOrder INT
); 
GO



/*
	作者：周华
	时间：2012-05-15 16:05:21.263
	描述：采购待摊费用明细2保存dt版表类型 
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_ShareSource' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertShareSourceBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertShareSourceBillDT;
	DROP TYPE TbType_ShareSource;
END
GO

CREATE TYPE TbType_ShareSource AS TABLE(
	FromBillNumberID INT
	,FromBillId	INT
	,Comment NVARCHAR(MAX)
	,FromBillType INT
	,ShareFee DECIMAL(22,10)
	,ShowOrder INT
); 
GO



/*
	库龄
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_StockAge' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitMV]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitMV; 
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitFIFO]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitFIFO;  
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitManSimple]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertGoodsInitManSimple;  
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPtypeInit]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertPtypeInit;  
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertIniGoodsStockStockAge]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertIniGoodsStockStockAge;   
	DROP TYPE TbType_StockAge;
END
GO

CREATE TYPE TbType_StockAge AS TABLE(
	id  INT
	,InStockDate VARCHAR(50),
	[TYPE] INT
)

GO 




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_STypeMoveBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertSTypeMoveBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_InsertSTypeMoveBillDT	
	DROP TYPE TBType_STypeMoveBill	
END
GO



/*
	Author:			 李海洋
	Create date: 2012-05-12 
	Description: 自定义表值类型(分支机构调拨出入库单)
*/
CREATE TYPE dbo.TBType_STypeMoveBill AS TABLE
(
	 BillNumberId  			NUMERIC(10,0)
	,PtypeId  					VARCHAR(50)
	,Qty   							 NUMERIC(24, 10) 
	,Price   						 NUMERIC(24, 10) 
	,Total   						 NUMERIC(24, 10) 
	,Comment  					VARCHAR(256)
	,IsUnit2 						INT
	,Serial							VARCHAR(MAX)						--序列号值
	,InputCostPrice			 NUMERIC(24, 10) 	DEFAULT(0)	--成本单价
	,GoodsNumber				VARCHAR(100)	DEFAULT('')	-- 批号
	,ProduceDate				VARCHAR(50)		DEFAULT('')	-- 生产日期
	,ValidDate					VARCHAR(50)		DEFAULT('')	-- 效期至
	,GoodsBTypeID				VARCHAR(50)		DEFAULT('')	-- 供货商ID值
	,GoodsCostPrice			 NUMERIC(24, 10) 	DEFAULT(0)	-- 出库批次成本单价
	,GoodsCostTotal 		 NUMERIC(24, 10)  DEFAULT(0)
	,HandZeroCost				INT						DEFAULT(0)	-- 手工指定成本单价
	,STypeID						VARCHAR(50)		DEFAULT('')
	,BillType						INT
	,KTypeID						VARCHAR(50)
	,KTypeID2						VARCHAR(50)
	,FromBillNumberID		NUMERIC(10,0)	DEFAULT(0)
	,FromBillID					NUMERIC(10,0)	DEFAULT(0)
	-- 9.0 新字段
	,UnitId							INT							--基本单位										
	,NUnitId						INT							--辅助单位
	,NQty								 NUMERIC(24, 10) 	--辅助数量
	,UnitRate						 NUMERIC(24, 10) 	--单位换算率
	,NUnitMsg						VARCHAR(50)			--换算结果
	,MUnitId						INT							--大单位
	,MQty								 NUMERIC(24, 10) 	--大单位数量
	,MUnitRate					 NUMERIC(24, 10) 	--大单位换算率
	,MUnitMsg						VARCHAR(50)			--大单位换算结果
	,MPrice							 NUMERIC(24, 10) 	--大单位单价
	,Incargoid					INT							--入库货位ID
	,Outcargoid					INT							--出库货位ID
	,ItemId							BIGINT					--自由项id
	,IsCombined					INT							--是否组合
	,ShowOrder					INT
)
GO




/*
	作者：吴雷
	时间：2014.04.24
	描述：出纳管理 启用期间 使用的分支机构启用期间数据表
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_TeStartPeriod' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateTeStartPeriod]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_UpdateTeStartPeriod;
	DROP TYPE TbType_TeStartPeriod;
END
GO

CREATE TYPE TbType_TeStartPeriod AS TABLE(
		STypeId		VARCHAR(50) DEFAULT(''),--分支机构
		SFYear		INT,					--启用年度
		SFPeriod	INT,					--启用期间
		IsConnect	INT,					--联用总账 0.未联用 1.联用
		CFYear		INT,					--联用年度
		CFPeriod	INT						--联用期间
)
GO



IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_Transportbill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertTransportBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertTransportbillDT;
	DROP TYPE TbType_Transportbill;
END
GO

CREATE TYPE TbType_Transportbill AS TABLE(
		[billNumberID] [numeric](18, 0),
		[ptypeid] [varchar](50),
		[qty] [numeric](22, 10),
		behooveQty [numeric](22, 10),
		[comment] [varchar](250),
		[GoodsBillNumberID] [numeric](10, 0),
		[GoodsBillID] [numeric](10, 0),
		[GoodsBillType]	INT,
		ItemID    bigint ,
		IsCombined   int ,
		[GoodsNumber] [varchar](100),
		[GoodsOrder] [int],
		[Serial] [text],
		[weight]  [numeric](22, 10),
		[Volume] [NUMERIC](24,10),
		ShowOrder INT,
		saleBillnumberid numeric(10,0),
		saleBilltype INT,ID INT
)
GO





IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_VipAddMoneyBatch' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertVipAddMoneyBatchBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_InsertVipAddMoneyBatchBillDT;
	DROP TYPE TbType_VipAddMoneyBatch;
END
GO

CREATE TYPE TbType_VipAddMoneyBatch AS TABLE(
		BillNumberId INT NOT NULL DEFAULT(0)
		--,Id INT NOT NULL IDENTITY(1,1)
		,VipCardId INT NOT NULL DEFAULT(0)
		,BeforeChargeMoney  NUMERIC(24, 10)  NOT NULL DEFAULT(0)
		,AfterChargeMoney  NUMERIC(24, 10)  NOT NULL DEFAULT(0)
		,ChargeMoney  NUMERIC(24, 10)  NOT NULL DEFAULT(0)
		,PreferenceMoney  NUMERIC(24, 10)  NOT NULL DEFAULT(0)
		,TotalInMoney  NUMERIC(24, 10) 
		,EndDate DATETIME NULL 
		,Comment VARCHAR(256) NOT NULL DEFAULT('')
		,ShowOrder INT
)



/*
	作者：韩林
	时间：2013-06-26 
	描述：pos修改会员卡积分时上传商品的自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_VipCardPtype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateVipCardCent]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_UpdateVipCardCent;
	DROP TYPE TBType_VipCardPtype;
END
GO

CREATE TYPE dbo.TBType_VipCardPtype AS TABLE
(
	Pid INT,
	Total DECIMAL(22,10),
	UnitId INT
) 
GO



/*
	作者：吴雷
	时间：2012-08-28
	描述：导入的凭证模板数据
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_VoucherTemplate' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_ImportVoucherTemplate]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_ImportVoucherTemplate;
	DROP TYPE TbType_VoucherTemplate;
END
GO

CREATE TYPE TbType_VoucherTemplate AS TABLE(
	sfullname		VARCHAR(100),
	billname		VARCHAR(100),
	usercode		VARCHAR(200),
	fullname		VARCHAR(200),
	groupfullname	VARCHAR(50),
	isdefault		VARCHAR(10),
	summary			VARCHAR(200),
	atypefrom		VARCHAR(200),
	atypeusercode	VARCHAR(50),
	atypefullname	VARCHAR(50),
	dc				VARCHAR(50),
	totalfrom		VARCHAR(200),
	assitems		VARCHAR(2000),
	isCost			VARCHAR(50)
)
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_Call' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertCallBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertCallBillDT;
	DROP TYPE TBType_Wx_Call;
END
GO

CREATE TYPE dbo.TBType_Wx_Call AS TABLE
(
	BillNumberID	numeric(10,0),
	PTypeID		varchar(50),
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	BuyDate		varchar(50) DEFAULT(''),	-- 购买日期
	ErrDes			varchar(3000) DEFAULT(''),	-- 故障描述
	ErrDeal		varchar(3000) DEFAULT(''),	-- 处理意见
	Total			 NUMERIC(24, 10) ,	-- 预计费用
	ETypeID		varchar(50),	-- 维修人
	BaoXiu			int,	-- 保内/保外，0：保内；1：保外
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			VARCHAR(MAX) DEFAULT(''),	-- 序列号
	OutFactoryDate	datetime DEFAULT(NULL),
	STypeID		VARCHAR(50) DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,goodsnumber VARCHAR(100)
	,cargoid INT
	,ShowOrder INT
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_GetBack' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertGetBackBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertGetBackBillDT;
	DROP TYPE TBType_Wx_GetBack;
END
GO

CREATE TYPE dbo.TBType_Wx_GetBack AS TABLE
(
	BillNumberID	numeric(10,0),
	PTypeID		varchar(50),
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	JieJianBillNumberID	int,	--  接件单的BillNumberID
	JieJianID		int,	-- 接件单对应商品明细行的物理顺序ID
	JieJianPTypeID	varchar(50),	-- 接件单明细商品ID
	wxTotal		 NUMERIC(24, 10) ,
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			varchar(200) DEFAULT(''),	-- 序列号（只录一个）
	OutFactoryDate	datetime DEFAULT(NULL),
	STypeID		VARCHAR(50)DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,goodsnumber VARCHAR(100)
	,cargoid INT
	,ShowOrder INT
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TBType_Wx_Goto'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    sys.objects
                    WHERE   object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertGotoBillDT]')
                            AND TYPE IN ( N'P', N'PC' ) ) 
            DROP PROC GP_Wx_InsertGotoBillDT;
        DROP TYPE TBType_Wx_Goto;
    END
GO

CREATE TYPE dbo.TBType_Wx_Goto AS TABLE
(
		BillNumberID		NUMERIC(10,0),
		InOrOut					CHAR(1),	-- 出入库标识，O：出库；I：入库
		PTypeID					VARCHAR(50),
		Qty							 NUMERIC(24, 10) ,
		intIsUnit2			INT,	-- 是否采用双单位。0：否；1：是
		Price						 NUMERIC(24, 10)  DEFAULT(0),	-- 单价
		Total						 NUMERIC(24, 10)  DEFAULT(0),	-- 金额
		Comment					VARCHAR(255) DEFAULT(''),	-- 备注
		Serial					VARCHAR(200) DEFAULT(''),	-- 序列号（只录一个）
		wxProperty			INT,	-- 维修属性，0：正常商品；1：维修商品
		OutFactoryDate	DATETIME DEFAULT(NULL),
		InputCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
		GoodsNumber			VARCHAR(100) DEFAULT(''),	-- 批号
		ProduceDate			VARCHAR(50) DEFAULT(''),	-- 生产日期
		ValidDate				VARCHAR(50) DEFAULT(''),	-- 效期至
		GoodsBTypeID		VARCHAR(50) DEFAULT(''),	-- 供货商ID值
		GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
		HandZeroCost		INT DEFAULT(0),				-- 手工指定成本单价
		STypeID					VARCHAR(50) DEFAULT(''),
		-- 9.0新字段
		ItemId					BIGINT DEFAULT(0),
		IsCombined			INT DEFAULT(0),
		NQty						 NUMERIC(24, 10)  DEFAULT(0),
		UnitRate				 NUMERIC(24, 10)  DEFAULT(0),
		cargoid					INT,
		GoodsCostTotal  NUMERIC(24, 10),
		ShowOrder INT,
		KTypeID	VARCHAR(50) DEFAULT('')
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_In' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertInBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertInBillDT;
	DROP TYPE TBType_Wx_In;
END
GO

CREATE TYPE dbo.TBType_Wx_In AS TABLE
(
	BillNumberID	numeric(10,0),
	PTypeID		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	Price			 NUMERIC(24, 10) ,		-- 成本单价
	Total			 NUMERIC(24, 10) ,		-- 成本金额
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			VARCHAR(max) DEFAULT(''),	-- 序列号
	OutFactoryDate	datetime DEFAULT(NULL) ,
	InputCostPrice  NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),				-- 手工指定成本单价
	STypeID		VARCHAR(50)DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,cargoid INT
	,GoodsCostTotal  NUMERIC(24, 10) 
	,ShowOrder INT
	,KTypeID	varchar(50) DEFAULT('')
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_Move' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertMoveBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertMoveBillDT;
	DROP TYPE TBType_Wx_Move;
END
GO

CREATE TYPE dbo.TBType_Wx_Move AS TABLE
(
	BillNumberID	numeric(10,0),
	PTypeID		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			VARCHAR(MAX) DEFAULT(''),	-- 序列号
	OutFactoryDate	datetime DEFAULT(NULL),
	STypeID		VARCHAR(50) DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,goodsnumber VARCHAR(100)
	,ShowOrder INT
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_Out' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertOutBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertOutBillDT;
	DROP TYPE TBType_Wx_Out;
END
GO

CREATE TYPE dbo.TBType_Wx_Out AS TABLE
(
	BillNumberID	numeric(10,0),
	PTypeID		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	Price			 NUMERIC(24, 10) ,		-- 成本单价
	Total			 NUMERIC(24, 10) ,		-- 成本金额
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			VARCHAR(MAX) DEFAULT(''),	-- 序列号
	OutFactoryDate	datetime DEFAULT(NULL),
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	STypeID		VARCHAR(50)DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,cargoid INT
	,GoodsCostTotal  NUMERIC(24, 10)
	,ShowOrder INT
	,InFactQty NUMERIC(24, 10)
	,KtypeID VARCHAR(50)
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_Replace' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertReplaceBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertReplaceBillDT;
	DROP TYPE TBType_Wx_Replace;
END
GO

CREATE TYPE dbo.TBType_Wx_Replace AS TABLE
(
	BillNumberID	numeric(10,0),
	PTypeID		varchar(50),
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	JieJianBillNumberID	int,	--  接件单的BillNumberID
	JieJianID		int,	-- 接件单对应商品明细行的物理顺序ID
	JieJianPTypeID	varchar(50),	-- 接件单明细商品ID
	wxTotal		 NUMERIC(24, 10) ,
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			varchar(200) DEFAULT(''),	-- 序列号（只录一个）
	wxProperty		int,	-- 维修属性，0：正常商品；1：维修商品
	OutFactoryDate	datetime DEFAULT(NULL),
	InputCostPrice  NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),				-- 手工指定成本单价
	STypeID		VARCHAR(50)DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,cargoid INT
	,GoodsCostTotal  NUMERIC(24, 10) 
	,ShowOrder INT
	,KTypeID	VARCHAR(50)DEFAULT('')
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_Self' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertSelfBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertSelfBillDT;
	DROP TYPE TBType_Wx_Self;
END
GO

CREATE TYPE dbo.TBType_Wx_Self AS TABLE
(
	BillNumberID	numeric(10,0),
	InOrOut		char(1),	-- 出入库标识，O：出库；I：入库
	PTypeID		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	Price			 NUMERIC(24, 10)  DEFAULT(0),	-- 单价
	Total			 NUMERIC(24, 10)  DEFAULT(0),	-- 金额
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			VARCHAR(MAX) DEFAULT(''),	-- 序列号
	wxProperty		int,	-- 维修属性，0：正常商品；1：维修商品
	OutFactoryDate	datetime DEFAULT(NULL),
	InputCostPrice  NUMERIC(24, 10)  DEFAULT(0),	-- 成本单价
	GoodsNumber	varchar(100) DEFAULT(''),	-- 批号
	ProduceDate	varchar(50) DEFAULT(''),	-- 生产日期
	ValidDate		varchar(50) DEFAULT(''),	-- 效期至
	GoodsBTypeID	varchar(50) DEFAULT(''),	-- 供货商ID值
	GoodsCostPrice	 NUMERIC(24, 10)  DEFAULT(0),	-- 出库批次成本单价
	HandZeroCost	int DEFAULT(0),				-- 手工指定成本单价
	STypeID		VARCHAR(50)DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,cargoid INT
	,GoodsCostTotal  NUMERIC(24, 10) 
	,ShowOrder INT
	,KTypeID VARCHAR(50)DEFAULT('')
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_SendBack' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertSendBackBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertSendBackBillDT;
	DROP TYPE TBType_Wx_SendBack;
END
GO

CREATE TYPE dbo.TBType_Wx_SendBack AS TABLE
(
	BillNumberID	numeric(10,0),
	PTypeID		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	SendBillNumberID	int,	--  接件单的BillNumberID
	SendID		int,	-- 接件单对应商品明细行的物理顺序ID
	SendPTypeID	varchar(50),	-- 接件单明细商品ID
	wxTotal		 NUMERIC(24, 10) ,
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			VARCHAR(MAX) DEFAULT(''),	-- 序列号
	OutFactoryDate	datetime DEFAULT(NULL),
	STypeID		VARCHAR(50) DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,goodsnumber VARCHAR(100)
	,cargoid INT
	,ShowOrder	INT
) 
GO



/*
	作者：廖晨羽
	时间：2012-05-08 
	描述：自定义表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Wx_SendBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_Wx_InsertSendBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_Wx_InsertSendBillDT;
	DROP TYPE TBType_Wx_SendBill;
END
GO

CREATE TYPE dbo.TBType_Wx_SendBill AS TABLE
(
	BillNumberID	numeric(10,0),
	PTypeID		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	intIsUnit2		int,	-- 是否采用双单位。0：否；1：是
	JieJianBillNumberID	int,	--  接件单的BillNumberID
	JieJianID		int,	-- 接件单对应商品明细行的物理顺序ID
	JieJianPTypeID	varchar(50),	-- 接件单明细商品ID
	wxTotal		 NUMERIC(24, 10) ,
	Comment		varchar(255) DEFAULT(''),	-- 备注
	Serial			VARCHAR(MAX) DEFAULT(''),	-- 序列号
	OutFactoryDate	datetime DEFAULT(NULL),
	STypeID		VARCHAR(50) DEFAULT('')
	-- 9.0新字段
	,ItemId BIGINT
	,IsCombined INT
	,NQty  NUMERIC(24, 10) 
	,UnitRate  NUMERIC(24, 10) 
	,goodsnumber VARCHAR(100)
	,cargoid INT
	,errdes1 VARCHAR(1000) DEFAULT('')
	,ShowOrder INT
) 
GO



/*
	By：Haiyang, Li
	Date：2012-6-9
	Description：维修期初, 表值参数
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_WxPtypeInit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_WxInitInsertDetail]') AND TYPE in (N'P', N'PC'))
		DROP PROC GP_WxInitInsertDetail;
	DROP TYPE TBType_WxPtypeInit;
END
GO

CREATE TYPE TBType_WxPtypeInit AS TABLE(
	 qty 					 NUMERIC(24, 10)  	DEFAULT(0)
	,nQty 				 NUMERIC(24, 10)  	DEFAULT(0)
	,goodsNumber	VARCHAR(100)	 	DEFAULT('')
	,itemId				INT							DEFAULT(NULL)
	,isCombined		BIT							DEFAULT(NULL)
);

GO



/*
	By：Haiyang, Li
	Date：2012-6-9
	Description：维修期初, 表值参数
	2015-04-28  SiHuaShan 新增 Serial 字段
*/
IF EXISTS ( SELECT  *
            FROM    sys.types st
                    JOIN sys.schemas ss ON st.schema_id = ss.schema_id
            WHERE   st.name = N'TBType_WxStockInit'
                    AND ss.name = N'dbo' ) 
    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    sys.objects
                    WHERE   object_id = OBJECT_ID(N'[dbo].[GP_WxStockInitInsertDetail]')
                            AND TYPE IN ( N'P', N'PC' ) ) 
            DROP PROC GP_WxStockInitInsertDetail;
        DROP TYPE TBType_WxStockInit;
    END
GO

CREATE TYPE TBType_WxStockInit AS TABLE(
qty 					 NUMERIC(24, 10)  	DEFAULT(0)
,nQty 				 NUMERIC(24, 10)  	DEFAULT(0)
,goodsNumber	VARCHAR(100)	 	DEFAULT('')
,itemId				INT							DEFAULT(0)
,isCombined		BIT							DEFAULT(0)
,Serial			VARCHAR(MAX) 
);

GO



/*
	作者：韩林
	时间：2013-10-28
	描述：自定义云分销订单表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Yapi_OrderBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_Yapi_SaveOrderBillDT]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_Yapi_SaveOrderBillDT;
	DROP TYPE TBType_Yapi_OrderBill;
END
GO

CREATE TYPE dbo.TBType_Yapi_OrderBill AS TABLE
(
		ID NUMERIC(20,0),
		OrderId	NUMERIC(20,0),
		GoodsID	NUMERIC(20,0),
		Qty  NUMERIC(24, 10) ,
		Price  NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		UnitID INT DEFAULT(0),
		Comment varchar(255) NULL
) 
GO



/*
	作者：韩林
	时间：2013-10-28
	描述：自定义云分销订单表值类型
*/
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_Yapi_SupplierPtype' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_Yapi_SaveSupplierPtype]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_Yapi_SaveSupplierPtype;
	DROP TYPE TBType_Yapi_SupplierPtype;
END
GO

CREATE TYPE dbo.TBType_Yapi_SupplierPtype AS TABLE
(
		SupplierID NUMERIC(20,0),
		GoodsID	NUMERIC(20,0),
		FullName VARCHAR(200),
		PYCode	VARCHAR(50),
		UserCode VARCHAR(200),
		UnitName VARCHAR(50),
		Skuid	 NUMERIC(20,0),
		Area	VARCHAR(200),
		STANDARD	VARCHAR(100),
		TYPE		VARCHAR(100),
		Price1  NUMERIC(24, 10) ,
		Price2  NUMERIC(24, 10) ,
		Price3  NUMERIC(24, 10) ,
		Price4  NUMERIC(24, 10) ,
		Price5  NUMERIC(24, 10) ,
		RetailPrice  NUMERIC(24, 10) 
) 
GO



IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_YJK_Sale' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[YJK_Gp_BillToSaleBill]') AND TYPE in (N'P', N'PC'))
		DROP PROC YJK_Gp_BillToSaleBill;
		
	DROP TYPE TBType_YJK_Sale;
END
GO

CREATE TYPE dbo.TBType_YJK_Sale AS TABLE
(
	BillNumberId  	[numeric](10,0),
	PtypeId  		[varchar](50),
	KTypeID			[varchar](50) DEFAULT(''),
	salesPrice		 NUMERIC(24, 10) ,--销售价(标价)
	itemId			BIGINT,			--商品属性
	salesAmout		NUMERIC(24, 10),--应收金额（标准金额）
	rebate			NUMERIC(24, 10),--折扣金额
	sectionPrice	NUMERIC(24, 10),--考核低价(门店考核价)
	realnumber		NUMERIC(24, 10),--销售数量
	priceincludetax	NUMERIC(24, 10),--含税单价（折后价）
	realsum			NUMERIC(24, 10),--实收金额（折扣金额）
	remark			varchar(255),--备注
	model			varchar(100),--型号
	spec			varchar(100),--规格
	isActivate		int,--是否激活
	yjkuse		varchar(100),--使用方式
	useAddress		varchar(100),--使用地
	nonReason		varchar(200),--外地原因
	ycpg			varchar(100),--异常评估
	ycReason		varchar(100),--异常原因
	batch			varchar(10)--批次
) 
GO



IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_YJK_SalePayList' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[YJK_Gp_BillToSaleBill]') AND TYPE in (N'P', N'PC'))
		DROP PROC YJK_Gp_BillToSaleBill;
		
	DROP TYPE TBType_YJK_SalePayList;
END
GO

CREATE TYPE dbo.TBType_YJK_SalePayList AS TABLE
(
	paytype		varchar(100),--支付类型编码
	payAmount	numeric(24,10),--支付金额
	remark		varchar(255)--备注
) 
GO





--==================================================
--by:glj
--date:2016-02-17
--description:未达账使用到
--==================================================
IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Type_AccountInTransit' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_SaveTeAccountInitialTransit]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_SaveTeAccountInitialTransit
	DROP TYPE Type_AccountInTransit;
END
GO

CREATE TYPE Type_AccountInTransit AS TABLE(
	RowId		INT,
	IndexId		INT,						--出纳初始数据表头ID
	AccountId	INT,						--银行账户ID
	ATypeId		VARCHAR(50),				--银行科目id
	CreateDate	DATETIME,					--业务日期
	Cid			INT,						--币种
	Summary		VARCHAR(1000) DEFAULT(''),	--摘要
	ETypeId		VARCHAR(50),				--经手人
	FSettleId	INT,						--结算方式
	FSettleNo	VARCHAR(50),				--结算号
	FDebit		NUMERIC(24, 10),			--借方
	FCredit		NUMERIC(24, 10), 			--贷方
	IsEdit		INT							--数据是否被修改
)
GO





IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_AcPeriod' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAcPeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_UpdateAcPeriod]--删除此存储过程的引用
	DROP type [dbo].Type_AcPeriod 
END
GO
CREATE TYPE Type_AcPeriod AS TABLE					--该表列同表AC_INIACCOUNT
(
	STypeId              VARCHAR(50),        
	ATypeId              VARCHAR(50),        
	iniYTotal             NUMERIC(24, 10) ,      
	iniYTotalFor          NUMERIC(24, 10) ,      
	FDebit                NUMERIC(24, 10) ,      
	FDebitFor             NUMERIC(24, 10) ,      
	FCredit               NUMERIC(24, 10) ,      
	FCreditFor            NUMERIC(24, 10) ,      
	iniTotal              NUMERIC(24, 10) ,      
	iniTotalFor           NUMERIC(24, 10) , 
	FYTOTAL				 NUMERIC(24, 10) ,
	FYTOTALFOR			 NUMERIC(24, 10) ,     
	Cid                  INT,   
	IniYqty				NUMERIC(24, 10) ,--年初数量
	FDebitqty			NUMERIC(24, 10) ,--借方数量
	FCreditqty			NUMERIC(24, 10) ,--贷方数量
	iniqty				NUMERIC(24, 10) --期初数量             
)
GO

IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_CGInsert' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetBillsTotalByAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].Web_GetBillsTotalByAccount--删除此存储过程的引用
	DROP type [dbo].Type_CGInsert 
END
GO
CREATE TYPE Type_CGInsert AS TABLE					 
(
	STYPEID				    VARCHAR(50),
	ETYPEID				    VARCHAR(50),
	BTYPEID				    VARCHAR(50),
	DTYPEID				    VARCHAR(50),
    STYPENAME				NVARCHAR(200),	  ---机构名称
	ETYPENAME				NVARCHAR(200),	  ---职员名称
	BTYPENAME				NVARCHAR(200),     ---往来单位名称
	DTYPENAME				NVARCHAR(200),	  ---部门名称
	TOTAL					 NUMERIC(24, 10) ,	  ---余额本币
	TOTALFOR				 NUMERIC(24, 10) 	  ---余额外币
)
GO

IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_CardInsert' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetCardsTotalByAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].Web_GetCardsTotalByAccount--删除此存储过程的引用
	DROP type [dbo].Type_CardInsert 
END
GO
CREATE TYPE Type_CardInsert AS TABLE					 
(
	STYPEID				    VARCHAR(50),
	ETYPEID				    VARCHAR(50),
	BTYPEID				    VARCHAR(50),
	DTYPEID				    VARCHAR(50),
    STYPENAME				NVARCHAR(200),	  ---机构名称
	ETYPENAME				NVARCHAR(200),	  ---职员名称
	BTYPENAME				NVARCHAR(200),     ---往来单位名称
	DTYPENAME				NVARCHAR(200),	  ---部门名称
	TOTAL					 NUMERIC(24, 10) 	  ---余额本币
)
GO



IF EXISTS(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_CompleteBrandarTotal' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertCompleteBrandarTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_InsertCompleteBrandarTotal]--删除此存储过程的引用
		
	DROP type [dbo].Type_CompleteBrandarTotal 
END
GO
CREATE TYPE Type_CompleteBrandarTotal AS TABLE	--该表列同表
(
	BrandarTypeID	VARCHAR	(50),
	CId				INT,--币种
	NCompleteTotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--原币结算金额
	CompleteTotal	NUMERIC(24,10) NOT NULL DEFAULT(0),--结算金额
	Comment			VARCHAR(200)--备注
)
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Type_CouponExchangePtypeBill' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_SaveCouponExchangePtype]') AND TYPE in (N'P', N'PC'))
		BEGIN
			DROP PROC Gp_SaveCouponExchangePtype;
			
		END
	DROP TYPE Type_CouponExchangePtypeBill;
END
GO
-- ==============================================
-- 描述：	返回优惠券兑换商品方案明细表变量
-- 时间：	2016-07-27
-- 作者：	sshan
-- =============================================
CREATE TYPE Type_CouponExchangePtypeBill AS TABLE
(
	NID				INT,
	BID				INT,				--兑换商品方案主表ID
	PtypeId			VARCHAR(200)	,	--商品编号
	Qty				NUMERIC(24,10) ,	--兑换数量
	UnitId			INT NOT NULL,			--兑换商品单位
	IsDefault		BIT NOT NULL DEFAULT(0)	--是否默认
);
GO




IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_CouponInfo' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_CouponInfo_Check]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[GP_CouponInfo_Check]--删除此存储过程的引用
	DROP type [dbo].Type_CouponInfo 
END
GO
CREATE TYPE Type_CouponInfo AS TABLE				
(
	Typeid     VARCHAR(50)
)
GO





IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_CouponPosInfo' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateCouponPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_UpdateCouponPtype]--删除此存储过程的引用
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DealCouponInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_DealCouponInfo]--删除此存储过程的引用	
	DROP type [dbo].Type_CouponPosInfo 
	
END
GO
CREATE TYPE Type_CouponPosInfo AS TABLE				
(
	PosId  INT
)
GO




IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_CouponPtypeInfo' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateCouponPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_UpdateCouponPtype]--删除此存储过程的引用
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DealCouponInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_DealCouponInfo]--删除此存储过程的引用	
	DROP type [dbo].Type_CouponPtypeInfo 
	
END
GO
CREATE TYPE Type_CouponPtypeInfo AS TABLE				
(
	typeid              VARCHAR(50),
	Qty					NUMERIC(24,10),		--数量
	Price				NUMERIC(24,10),		--参考单价
	Total				NUMERIC(24,10)		--参考金额
)
GO




IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_CouponStypeInfo' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateCouponStype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_UpdateCouponStype]--删除此存储过程的引用
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DealCouponInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_DealCouponInfo]--删除此存储过程的引用	
	DROP type [dbo].Type_CouponStypeInfo 
	
END
GO

CREATE TYPE Type_CouponStypeInfo AS TABLE				
(
	typeid              VARCHAR(50)
)
GO



IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Type_FixedReasonForChangeDetails' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_Base_SaveFixedReasonForChangeDetails]') AND TYPE in (N'P', N'PC'))
	BEGIN
		DROP PROC Gp_Base_SaveFixedReasonForChangeDetails;
	END
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_Base_SaveFixedReasonForChange]') AND TYPE in (N'P', N'PC'))
	BEGIN
		DROP PROC Gp_Base_SaveFixedReasonForChange
	END
	
	DROP TYPE Type_FixedReasonForChangeDetails;
END
GO
-- ==============================================
-- 描述：	返回变更原因明细表变量
-- 时间：	2016-05-12
-- 作者：	lxl
-- =============================================
CREATE TYPE Type_FixedReasonForChangeDetails AS TABLE
(
	NID				INT,
	TID				INT,				--变更原因主表ID
	STypeID			VARCHAR(50),		--分支机构ID
	EnterATypeID	VARCHAR(50),		--入账原值差异科目
	ForeignATypeID	VARCHAR(50),		--外币影响原值差异科目
	RateATypeID		VARCHAR(50),		--汇率影响原值科目
	XiWaMaxNumber   INT NULL DEFAULT(1)	--缓存ID
);
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Type_InventoryTypeDetails' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_Base_SaveInventoryType]') AND TYPE in (N'P', N'PC'))
		BEGIN
			DROP PROC Gp_Base_SaveInventoryType;
			DROP PROC Gp_Base_SaveInventoryTypeDetails;
		END
	DROP TYPE Type_InventoryTypeDetails;
END
GO
-- ==============================================
-- 描述：	返回存货类型明细表变量
-- 时间：	2016-04-28
-- 作者：	glj
-- =============================================
CREATE TYPE Type_InventoryTypeDetails AS TABLE
(
	NID				INT,
	TID				INT,				--存货类型主表ID
	STypeID			VARCHAR(50),		--分支机构ID
	StockATypeID	VARCHAR(50),		--存货核算科目
	IncomeATypeID	VARCHAR(50),		--销售收入科目
	CostATypeID		VARCHAR(50)			--销售成本科目
);
GO




IF Exists(SELECT TOP 1 1  FROM sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_MulColInfor' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateMulColAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].Gp_UpdateMulColAccount--删除此存储过程的引用
	DROP TYPE [dbo].Type_MulColInfor 
END
GO
CREATE TYPE Type_MulColInfor AS TABLE             --该表列同表Ac_IniAccount_Assist_CheckItems
(
	FDC			INT,				--分析方向 借1，贷-1，双向0
	FVALUE		VARCHAR(50)			--明细科目或辅助核算项的typeid
)
GO



IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_PosEmployee' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdatePosAdminitorInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_UpdatePosAdminitorInfo]--删除此存储过程的引用
	DROP type [dbo].Type_PosEmployee 
	DROP type [dbo].Type_PosPtype 
	DROP type [dbo].Type_PosAccount 
	DROP type [dbo].Type_PosBtype 
	DROP type [dbo].Type_PosOperator 
	
END
GO
CREATE TYPE Type_PosEmployee AS TABLE				
(
	Eid              INT
)
GO

CREATE TYPE Type_PosPtype AS TABLE				
(
	Pid              INT
)
GO

CREATE TYPE Type_PosAccount AS TABLE					
(
	nid             INT 
)
GO

CREATE TYPE Type_PosBtype AS TABLE					
(
	Bid              INT
)
GO

CREATE TYPE Type_PosOperator AS TABLE					
(
	Operatorid              INT
)
GO



IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_PosInfo' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_PosInfo_Check]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[GP_PosInfo_Check]--删除此存储过程的引用
	DROP type [dbo].Type_PosInfo 
END
GO
CREATE TYPE Type_PosInfo AS TABLE				
(
	Typeid     VARCHAR(50)
)
GO






IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id where t.name= N'Type_UnitConvertSet' AND ss.name=N'dbo')
BEGIN
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_InsertUnitConvertSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		drop procedure [dbo].[Gp_InsertUnitConvertSet]--删除此存储过程的引用
	DROP type [dbo].Type_UnitConvertSet 
/*
修改:魏伟
时间:2016-07-22\
描述:添加/修改价格信息
*/
END
GO
Create Type [dbo].Type_UnitConvertSet as table
(
	UnitsId				INT,
	oldunitsid				INT,
	RateType			INT,			--0代表固定  1代码浮动
	Rate				 NUMERIC(24, 10) ,	--换算率
	IsDefaultUnit		INT,			--是否默认单位
	EntryCode			VARCHAR(200),
	IsUse				INT	,			--是否启用(0否1是)
    PreBuyPrice1        NUMERIC(24,10) ,       
    PreBuyPrice2        NUMERIC(24,10) ,
    PreBuyPrice3        NUMERIC (24,10),
    PreBuyPrice4        NUMERIC (24,10),
    PreBuyPrice5        NUMERIC (24,10),
    PreSalePrice1         NUMERIC(24,10) ,
    PreSalePrice2         NUMERIC(24,10) ,
    PreSalePrice3         NUMERIC (24,10),
    PreSalePrice4         NUMERIC(24,10) ,
    PreSalePrice5        NUMERIC(24,10)  ,
    PreSalePrice6        NUMERIC(24,10)  ,
    PreSalePrice7        NUMERIC(24,10)  ,
    PreSalePrice8        NUMERIC (24,10) ,
    PreSalePrice9        NUMERIC (24,10) ,
    PreSalePrice10        NUMERIC(24,10)  ,
    RetailPrice        NUMERIC(24,10)  ,
    TopSalePrice        NUMERIC (24,10) ,
    LowSalePrice        NUMERIC(24,10)  ,  
    TopBuyPrice        NUMERIC(24,10)    
)
GO





IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_WdGoodsStocks' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateWdGoodsStocks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_UpdateWdGoodsStocks]--删除此存储过程的引用
	DROP type [dbo].Type_WdGoodsStocks 
END
GO
CREATE TYPE Type_WdGoodsStocks AS TABLE					--该表列同表网店库存数据表
(
	KTypeID             VARCHAR(50),
	CargoID             INT,
	PTypeID             VARCHAR(50),
	IsCombinedItem      INT,
	ItemID              INT,
	Qty                 NUMERIC(24,10) DEFAULT(0),
	EnableNum			NUMERIC(24,10) DEFAULT(0)
)
GO



--章鱼侠-ERP  【仓库信息、客户信息、供货商信息、职员信息、项目信息】对照表
IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_WmsErpContrast' AND ss.name=N'dbo')
BEGIN
	--删除 仓库信息 此存储过程的引用
	IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveWmsErpContrastSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_SaveWmsErpContrastSetting]
	
	DROP type [dbo].Type_WmsErpContrast 
END
GO

CREATE TYPE Type_WmsErpContrast AS TABLE	
(
	WMS_TypeId		VARCHAR(50),--信息 ID
	WMS_UserCode	VARCHAR(200),--信息 编号
	WMS_FullName	VARCHAR(200),--信息 名称
	
	ERP_TypeId		VARCHAR(50)--信息 ID	
)
GO





--章鱼侠-ERP  【商品SKU】对照表
IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_WmsErpPtypeContrast' AND ss.name=N'dbo')
BEGIN
	--删除此存储过程的引用
	IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveWmsErpPTypeContrastSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_SaveWmsErpPTypeContrastSetting]
		
		
	DROP type [dbo].Type_WmsErpPtypeContrast 
END
GO

CREATE TYPE Type_WmsErpPtypeContrast AS TABLE					--该表列同表
(
	WMS_TypeId		VARCHAR(50),--商品ID
	WMS_UserCode	VARCHAR(200),--商品编号
	WMS_FullName	VARCHAR(200),--商品名称
	WMS_Standard	VARCHAR(200),--规格
	WMS_Type		VARCHAR(200),--型号
	WMS_Unit1		VARCHAR(200),--单位名称型号	
    WMS_SKUId		VARCHAR(50),--SKUID
	WMS_Prop1		VARCHAR(200),--商品属性1
	WMS_Prop1Name	VARCHAR(200),--商品属性1
	WMS_Prop2		VARCHAR(200),--商品属性2
	WMS_Prop2Name	VARCHAR(200),--商品属性2
	
	ERP_TypeId		VARCHAR(50),--erp商品ID
	ERP_SKUId		VARCHAR(50),--erp商品自由项明细ID
	ERP_CustomItemFrom	INT,--erp商品自由项 0基本项 1：组合项
	ERP_CustomItemId	INT,--erp商品自由项ID
	Erp_CustomItemName	VARCHAR(200)--erp商品自由项ID
	
)
GO




IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[YJK_Paging]') AND type in (N'P', N'PC')) 
	DROP PROCEDURE [YJK_Paging]  

/*
	作者：谢吉康
	日期：2020-04-04
	描述：易聚客通用算法
*/
IF  EXISTS (SELECT 1 FROM sys.types WHERE is_table_type=1 AND name = N'YJK_Paging_Param') 
	DROP TYPE [YJK_Paging_Param]
BEGIN 
	CREATE TYPE [YJK_Paging_Param] AS TABLE
	(
		[ParaName] [varchar](1000) NOT NULL DEFAULT '',
		[DataType] [varchar](1000) NOT NULL DEFAULT '',
		[ParaValue] [varchar](max) NOT NULL DEFAULT ''
	)
END



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CX_CombinationBillView]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[CX_CombinationBillView]
/****** Object:  View [dbo].[CX_CombinationBillView]    Script Date: 07/19/2011 14:52:19 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
 GO 


CREATE VIEW [dbo].[CX_CombinationBillView]
--@Encode$--
AS 
SELECT * FROM CX_CombinationBill


GO





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

/****** Object:  View [dbo].[CX_CombinationDetailBillView]    Script Date: 07/19/2011 15:01:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


CREATE VIEW [dbo].[CX_CombinationDetailBillView]
--@Encode$--
AS 
SELECT * FROM CX_CombinationDetailBill


GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW CX_LargessBillView
--@Encode$--
AS 
SELECT * FROM CX_LargessBill

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW CX_SaleByHandView
--@Encode$--
AS 
SELECT * FROM CX_SaleByHand

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW CX_SalePlanIndexView
--@Encode$--
AS 
SELECT * FROM CX_SalePlanIndex

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW CX_SaleStocksAreaView
--@Encode$--
AS 
SELECT * FROM CX_SaleStocksArea

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW CX_SpecialOfferBillView
--@Encode$--
AS 
SELECT * FROM CX_SpecialOfferBill

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosAssistAttributeView
--@Encode$--
AS 
SELECT 0 as  attributeid,0 as typeid,cast('' as  varchar) as typename,cast('' as  varchar) as username,cast('' as  varchar) as usercode 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosAssistTypeView
--@Encode$--
AS 
SELECT 0 as typeid,cast('' as varchar) as typename,0 as typeorder,0 as choose,cast('' as varchar) as comment 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosAtypeView
--@Encode$--
AS
select typeId as Atypeid,fullname,Sonnum,[name],deleted,usercode from atype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosBarCodeTypeView
--@Encode$--
AS
SELECT 0 as bartypeid,cast('' as varchar) as BarName,cast('' as varchar) as DisplayBarName,0 as BarCheckDigit,0 AS IsStoped,0 AS IsDeleted,CAST('' AS VARCHAR)  AS cBYZD
,0 AS iBYZD 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosBarCodeView  
--@Encode$--
AS  
SELECT  typeid as ptypeid,0 as colorid,0 as sizeid,0 AS BarTypeid,EntryCode as FullBarCode,0 as PRI FROM  ptype where typeid<>'00000'
UNION ALL
SELECT cast('' as varchar) as ptypeid,0 as colorid,0 as sizeid,0 as bartypeid,cast('' as varchar) AS FullBarCode ,0 as pri 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosBranchView
--@Encode$--
AS
SELECT TypeId as BranchID,
       ParID,
       Sonnum,
       Leveal,
       0 as Rec,
       Soncount,
       0 AS branchtype,
       UserCode,
       FullName,
       Name,
       PyCode as Namepy,
       Comment,
       CAST('' AS VARCHAR) as Area,
       Address,
       Tel,
       CAST('' AS VARCHAR) as Email,
       Deleted,
       0 as CheckAndAccept,
       CAST('' AS VARCHAR) as BtypeId,
       0 as DefTaxRate,
       CAST('' AS VARCHAR) as DefBtypeId,
       CAST('' AS VARCHAR) as DefKtypeId,
       CAST('' AS VARCHAR) as DefAtypeId,
       0 as CashAsBillMoney,
       0 as RoundType,
       -1 as PayType,
       xiwamaxnumber as UpdateTag,
       CAST('' AS VARCHAR) as ExtId 
       FROM stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosBtypeDistributeView
--@Encode$--
AS
SELECT 0 as Id,
       cast('' as varchar) as BranchId,
       typeId as BtypeId,
       cast('' as varchar) as PriceTypeid,
       cast('' as varchar) as MarketDiscountId,
       cast('' as varchar) as DiscountTypeId,
       0 as TaxRate,
       0 as Flag from btype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[PosBtypeView]')
                    AND OBJECTPROPERTY(id, N'IsView') = 1 ) 
    DROP VIEW [dbo].[PosBtypeView]
GO

CREATE VIEW PosBtypeView
--@Encode$--
AS
SELECT  CAST('' as varchar) as branchid ,
        typeid AS btypeid ,
        parid ,
        leveal ,
        soncount ,
        sonnum ,
        usercode ,
        fullname ,
        name ,
        deleted ,
        0 AS PriceTypeId ,
        XiWaMaxNumber as  updatetag ,
        CAST('' AS VARCHAR) AS cBYZD1 ,
        CAST('' AS VARCHAR) AS cBYZD2 ,
        0 AS iBYZD1 ,
        0 AS iBYZD2 ,
        0 AS nBYZD1 ,
        0 AS nBYZD2
FROM    btype 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosColorView
--@Encode$--
AS 
SELECT 0 as colorid,
       cast('' as varchar) as  ColorName 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosCxEPowerView
--@Encode$--
AS 
--转换非管理员的所有促销相关权限
SELECT  etypeid,
CAST('' as varchar) AS moduleid,
CAST('' as varchar) AS actionid
FROM    loginuser
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[PosEmployeeView]')
                    AND OBJECTPROPERTY(id, N'IsView') = 1 ) 
    DROP VIEW [dbo].[PosEmployeeView]
GO

CREATE VIEW PosEmployeeView
--@Encode$--
AS
SELECT  typeid AS etypeid ,
        stypeid AS branchid ,
        0 as rec ,
        dtypeid ,
        parid ,
        leveal ,
        soncount ,
        sonnum ,
        fullname ,
        name ,
        usercode ,
        deleted ,
        0 as isShopSale ,
        0 as zkPopedom ,
        MaxPre as  YHPopedom ,
        XiWaMaxNumber as updatetag ,
        CAST('' AS VARCHAR) AS cBYZD1 ,
        CAST('' AS VARCHAR) AS cBYZD2 ,
        0 AS iBYZD1 ,
        0 AS iBYZD2 ,
        0 AS nBYZD1 ,
        0 AS nBYZD2
FROM    employee
WHERE   typeId not in ('00000')
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosGoodsStocksDetailView
--@Encode$--
AS
SELECT b.GoodsOrder as OrderID, b.ptypeid,b.Ktypeid,0 as colorid,0 as sizeid,a.qty,0 AS Price,a.Total,CAST('' AS VARCHAR)  AS cBYZD
,0 AS iBYZD,0 AS nBYZD  FROM inoutstocktable  a INNER JOIN goodsstocks b ON a.KtypeId = b.KtypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosGoodsStocksView
--@Encode$--
AS
SELECT 0 as OrderID,ptypeid,ktypeid,qty,price,total,GoodsOrder,0 as RowOrder,CAST('' AS VARCHAR)  AS cBYZD
,0 AS iBYZD,0 AS nBYZD FROM goodsstocks

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosInfoView
--@Encode$--
AS
SELECT PosID,FullName,UserCode,Branchid,ETypeid1 AS Etypeid, stockid,Btypeid,Deleted,isKeySet,IsHeadquartersStock,IsJoinStock,PosPassword,Possessive,Comment,IsTicketCount,CAST('' AS VARCHAR)  AS cBYZD1,CAST('' AS VARCHAR)  AS cBYZD2,
0 AS iBYZD1,0 AS iBYZD2,0 AS nBYZD1,0 AS nBYZD2
FROM CommonPosinfo 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosLoginUserView
--@Encode$--
AS
SELECT etypeid,[Password],SysID,0 as MinDiscount,CAST('' as varchar) as  KeyNo,SmsSendID as SendID,OpenLock as LockID,UserRank as LockLevel 
FROM loginuser

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosPriceTypeView
--@Encode$--
AS 
SELECT CAST('' as varchar) as  BranchId,
       CAST('' as varchar) as PriceTypeId,
       CAST('' as varchar) as PriceName,
       CAST('' as varchar) as DisplayName,
       CAST('' as varchar) as Type,
       0 as SortLevel,
       1 as IsSystem 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosPtypeAttributeView
--@Encode$--
AS 
SELECT  cast('' as varchar) as ptypeid,
        0 as attributeid 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosPtypeColorSizeView
--@Encode$--
AS
SELECT  typeid as ptypeid ,0 AS ColorID,0 AS SizeID ,
0 AS sizeorderid,0 AS colororderid, XiWaMaxNumber as updatetag from ptype



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosPtypePriceView
--@Encode$--
AS 
SELECT 
       cast('' as varchar) as PriceTypeId,
       Ptypeid,
       RetailPrice as Price 
       from PType_Price

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[PosPtypeView]')
                    AND OBJECTPROPERTY(id, N'IsView') = 1 ) 
    DROP VIEW [dbo].[PosPtypeView]
GO

CREATE VIEW PosPtypeView
--@Encode$--
AS
SELECT  typeid AS Ptypeid ,
        CAST('' AS VARCHAR) AS batchNumber ,
        CAST('' AS VARCHAR) AS WareNumber ,
        Parid ,
        Leveal ,
        Sonnum ,
        soncount ,
        UserCode ,
        FullName ,
        Name ,
        standard ,
        type ,
        area ,
        unit1 AS unit ,
        0 AS relprice ,
        0 as retailprice ,
        Deleted ,
        0 as stop ,
        UsefulLifeMonth as  stopdate ,
        CAST('' AS VARCHAR) as IssueDate ,
        XiWaMaxNumber as UpdateTag ,
        CAST('' AS VARCHAR) AS cBYZD1 ,
        CAST('' AS VARCHAR) AS cBYZD2 ,
        0 AS iBYZD1 ,
        0 AS iBYZD2 ,
        0 AS nBYZD1 ,
        0 AS nBYZD2
FROM    ptype
WHERE   typeid <> '00000'
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosSizeView
--@Encode$--
AS 
SELECT 0 as Sizeid,CAST('' as varchar) AS Sizename 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosStockView
--@Encode$--
AS
SELECT stypeid as branchid, 
       typeid AS Ktypeid,
       parid,
       leveal,
       sonnum,
       soncount,
       fullname,
       name,
       usercode,
       0 AS PriceTypeID,
       deleted,
       XiWaMaxNumber  as updatetag,
       CAST('' AS VARCHAR)  AS cBYZD,
	   0 AS iBYZD 
FROM stock

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosUserPowerRangeView
--@Encode$--
AS 
SELECT 0 as ListID,EtypeID, cast('' as  varchar) as TypeID,0 as BaseType FROM loginuser

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosVipCardBoundView
--@Encode$--
AS 
SELECT 0 as CardTypeID, cast('' as varchar) as Branchid 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosVipCardExpandView
--@Encode$--
AS 
SELECT VipCardID AS CardTypeid,
       0 as oneconsume,
       0 as allconsume,
       0 as Integral1,
       0 as Integral2,
       0 as ExpandType,
       0 as Base,
       0 as [Percent],
       0 AS isshop,
       cast('' as varchar) as atypeid,
       0 as  batchno 
FROM nVipCardSign

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetVipMoney]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetVipMoney]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年9月21日
-- Description:	获取VIP储值余额（减去POS小票中未结转的VIP消费金额总值和A8草稿中所涉及VIP消费金额总值）
-- =============================================
CREATE FUNCTION F_GetVipMoney 
(
    @vipcardid INT,   --VIP卡ID
	@CzYe   NUMERIC(24, 10)  --储值余额
)
RETURNS  NUMERIC(24, 10) 
AS
BEGIN
  DECLARE @PosSaleVipTotal  NUMERIC(24, 10)  --POS端未结转的零售VIP消费金额
  DECLARE @PosBackVipTOtal  NUMERIC(24, 10)  --POS端未结转的退货VIP返回金额
  DECLARE @A8SaleVipTotal   NUMERIC(24, 10)  --A8端未过账的POS零售VIP消费金额
  DECLARE @A8BackVipTotal   NUMERIC(24, 10)  --A8端未过账的POS退货VIP返回金额
  DECLARE @CzYeResult  NUMERIC(24, 10) 
 
  SELECT @PosSaleVipTotal=ISNULL(SUM(b.SaveAccountSum),0) FROM commonpossaleindex a
  INNER JOIN PosVipMoneyList b ON a.PosVchCode=b.PosVchcode 
  WHERE a.Total>0 and a.Draft=0 AND b.VipID=@vipcardid
  
  SELECT @PosBackVipTOtal=ISNULL(SUM(b.SaveAccountSum),0) FROM commonpossaleindex a
  INNER JOIN PosVipMoneyList b ON a.PosVchCode=b.PosVchcode 
  WHERE a.Total<0 and a.Draft=0 AND b.VipID=@vipcardid
  
  SELECT @A8SaleVipTotal=ISNULL(SUM(b.Total),0) FROM billindex a
  INNER JOIN BillMulAccount b ON a.BillNumberId=b.BillNumberId 
  WHERE a.ifcheck='f' AND a.BillType=305 AND a.PosBillType<>0 AND b.VipCardID<>-1 AND b.ATypeID='0000200005' AND b.VipCardID=@vipcardid
  
  SELECT @A8BackVipTotal=ISNULL(SUM(b.Total),0) FROM billindex a
  INNER JOIN BillMulAccount b ON a.BillNumberId=b.BillNumberId 
  WHERE a.ifcheck='f' AND a.BillType=45 AND a.PosBillType<>0 AND b.VipCardID<>-1 AND b.ATypeID='0000200005' AND b.VipCardID=@vipcardid
  
  SET @CzYeResult=@CzYe-@PosSaleVipTotal-@A8SaleVipTotal-@PosBackVipTOtal+@A8BackVipTotal
  RETURN @CzYeResult
END
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosVipCardsView
--@Encode$--
AS 
SELECT c.VipCardID as CardId,
       c.VipCardCode as CardNo,
       c.VipCardTypeID as CardtypeId,
       c.Deleted as CardState,
       c.Bname as HolderName,
       CASE WHEN c.Bsex=1 THEN '男' WHEN c.Bsex=0 THEN '女' END  AS HolderSex,
       c.BIDcard as HolderId,
       c.Btel as HolderTel,
       CAST('' AS VARCHAR)  AS HolderTel2,
       c.Baddr AS HolderAdress,
	   CAST('' AS VARCHAR)  AS HandOutDept, 
	   c.Btypeid,
       dbo.F_GetVipMoney(c.VipCardID,c.CzYeMOney) AS Deposit,  --储值余额
       c.CreateDate as HandOutDate,
       c.EndDate as ValidDate,
       c.pWord AS CardPassWord,
       0 AS ISheadquarters,
       CAST('' AS VARCHAR)  AS OperateID,
       0 as ConsumeAbility,
       c.totalMoney as SaveMoney,
       c.xFczMoney as AllConsume,
       ISNULL(
       (
			SELECT SUM(IB.total) as XFJF 
			FROM BillIndex A 
			INNER JOIN nVipCardSign N ON A.VipCardID=N.VipCardID
			INNER JOIN IntegralExchangeBill IB ON A.BillNumberId=IB.BillNumberId 
			WHERE BillType=183
			AND N.VipCardCode=c.VipCardCode),0
        ) as doIntegral,
       c.begincent+c.totalCent AS NowIntegral,
       0 as NowDiscountTotal,
       0 as LJXFJFJE,
       c.qCczMoney+c.lJczMoney as TotalFillMoney,
       0 as TotalSpendMoney,
       0 as FillSite,
       c.BeginMoney as YearIniMoney,
       c.Comment AS coment,
       c.Deleted,
       0 as UpdateTag,
       CAST('' AS VARCHAR) AS cBYZD1,
       CAST('' AS VARCHAR)  AS cBYZD2,
       0 AS iBYZD1,
       0 AS iBYZD2,
       0 AS nBYZD1,
       0 AS nBYZD2 
FROM nVipCardSign  c


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE VIEW PosvipcardtypesView
--@Encode$--
AS 
SELECT VipCardTypeID AS CardTypeId,
       TypeName AS CardTypeName, 
       CardTypeDiscount as  Discount,
       0 AS LimitTotal,
       0 AS IntegralMod,
       CAST('' AS VARCHAR)  AS OperateId,
       DiscountType,
       CAST('' AS VARCHAR) as PriceTypeId,
       0 AS IsMoney,
       0 as NeedPass,
       deleted as isStop,
       0 as  type,
       CAST('' AS VARCHAR)  AS cBYZD1,
       CAST('' AS VARCHAR)  AS cBYZD2,
       0 AS iBYZD1,
       0 AS iBYZD2,
       0 AS nBYZD1,
       0 AS nBYZD2,
       CAST('' AS VARCHAR) as BranchID,
       0 as IsAllowAdd 
FROM nVipCardSet

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








create view v_getdate
as
select getdate() [output]








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-06-07
	描述：由于组合的自由项与非组合的自由项是在不同的表中，为了方便连接，所以创建一个视图
*/
IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[V_ITEM]') AND OBJECTPROPERTY(ID, N'ISVIEW') = 1)
	DROP VIEW V_Item
GO
CREATE VIEW V_Item
AS
	SELECT 1 AS iscombined,a.id AS itemid,REPLACE(a.fullname,'я','/') AS itemname  FROM CustomReferenceValue a 
	UNION ALL
	SELECT 0,b._id,b.fullname FROM xw_SelfData b 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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












/****** Object:  View dbo.V_LendFace    Script Date: 2002-6-20 10:14:43 ******/


CREATE  VIEW dbo.V_LendFace
--@Encode$--
AS
SELECT	
	p.UserCode AS pUserCode, 
	p.FullName AS pFullName,
	p.EntryCode AS pEntryCode,
	lb.PtypeId AS pTypeID, 
	k.UserCode AS kUserCode,
	k.FullName AS kFullName,
	li.kTypeID, 
	b.UserCode AS bUserCode,
	b.FullName AS bFullName,
	li.bTypeID,
	li.dealbtypeid,
	e.UserCode AS eUserCode,
	e.FullName AS eFullName,
	li.eTypeID,
	li.BillNumberID,
	li.BillDate,
	li.BillType,
	li.BillCode,
	li.Comment,
	lb.STypeID,	
	lb.Qty AS Qty,
	lb.ItemID,
	lb.IsCombined,
	lb.NQty,
	lb.GoodsNumber,
	lb.producedate,
	lb.ValidDate,
	lb.id AS CustomdetailID,
	li.ifcheck,
	li.RedWord,
	li.Draft,
	CASE li.BillType WHEN 71 THEN Qty ELSE 0 END AS Borrow,
	CASE li.BillType WHEN 72 THEN -Qty ELSE 0 END AS BorrowBack,
	CASE li.BillType WHEN 87 THEN -Qty ELSE 0 END AS Lend,
	CASE li.BillType WHEN 88 THEN Qty ELSE 0 END AS LendBack,
	CASE li.BillType WHEN 71 THEN NQty ELSE 0 END AS NBorrow,
	CASE li.BillType WHEN 72 THEN -NQty ELSE 0 END AS NBorrowBack,
	CASE li.BillType WHEN 87 THEN -NQty ELSE 0 END AS NLend,
	CASE li.BillType WHEN 88 THEN NQty ELSE 0 END AS NLendBack,
	0 AS buyqty,
	0 AS saleqty,
	lb.CargoID
FROM dbo.LendBill lb 
      INNER JOIN dbo.LendIndex li ON li.BillNumberId = lb.BillNumberId 
      INNER JOIN dbo.ptype p ON lb.PtypeId = p.typeId 
      INNER JOIN dbo.btype b ON li.btypeid= b.typeId 
      INNER JOIN dbo.Stock k ON li.ktypeid = k.typeId
      LEFT JOIN dbo.Employee e ON (li.etypeid = e.typeId)
--WHERE li.RedWord=0 AND DRAFT=0 AND IFCHECK='t'
UNION ALL
SELECT	
	p.UserCode AS pUserCode, 
	p.FullName AS pFullName,
	p.EntryCode AS pEntryCode,
	lb.PtypeId AS pTypeID, 
	k.UserCode AS kUserCode,
	k.FullName AS kFullName,
	li.kTypeID, 
	b.UserCode AS bUserCode,
	b.FullName AS bFullName,
	li.DealBTypeID as bTypeID,
	li.dealbtypeid,
	e.UserCode AS eUserCode,
	e.FullName AS eFullName,
	li.eTypeID,
	li.BillNumberID,
	li.BillDate,
	li.BillType,
	li.BillCode,
	li.Comment,
	lb.STypeID,	
	0,
	lb.ItemID,
	lb.IsCombined,
	lb.NQty,
	lb.GoodsNumber,
	lb.producedate,
	lb.ValidDate,
	lb.id AS CustomdetailID,
	li.ifcheck,
	li.RedWord,
	li.Draft,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	lb.qty,
	lb.CargoID
FROM dbo.SaleBill lb 
      INNER JOIN dbo.BillIndex li ON li.BillNumberId = lb.BillNumberId  AND li.ifYearBill=0
      INNER JOIN dbo.ptype p ON lb.PtypeId = p.typeId 
      INNER JOIN dbo.btype b ON li.DealBTypeID= b.typeId 
      INNER JOIN dbo.Stock k ON li.ktypeid = k.typeId
      LEFT JOIN dbo.Employee e ON (li.etypeid = e.typeId)
WHERE li.IsLend=1
AND RedWord=0
AND ifcheck='t'
UNION ALL
SELECT	
	p.UserCode AS pUserCode, 
	p.FullName AS pFullName,
	p.EntryCode AS pEntryCode,
	lb.PtypeId AS pTypeID, 
	k.UserCode AS kUserCode,
	k.FullName AS kFullName,
	li.kTypeID, 
	b.UserCode AS bUserCode,
	b.FullName AS bFullName,
	li.DealBTypeID as bTypeID,
	li.dealbtypeid,
	e.UserCode AS eUserCode,
	e.FullName AS eFullName,
	li.eTypeID,
	li.BillNumberID,
	li.BillDate,
	li.BillType,
	li.BillCode,
	li.Comment,
	lb.STypeID,	
	0,
	lb.ItemID,
	lb.IsCombined,
	lb.NQty,
	lb.GoodsNumber,
	lb.producedate,
	lb.ValidDate,
	lb.id AS CustomdetailID,
	li.ifcheck,
	li.RedWord,
	li.Draft,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	lb.Qty,
	0,
	lb.CargoID
FROM dbo.BuyBill lb 
      INNER JOIN dbo.BillIndex li ON li.BillNumberId = lb.BillNumberId   AND li.ifYearBill=0
      INNER JOIN dbo.ptype p ON lb.PtypeId = p.typeId 
      INNER JOIN dbo.btype b ON li.DealBTypeID= b.typeId 
      INNER JOIN dbo.Stock k ON li.ktypeid = k.typeId
      LEFT JOIN dbo.Employee e ON (li.etypeid = e.typeId)
WHERE li.IsLend=1
AND RedWord=0
AND ifcheck='t'




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/****** Object:  View dbo.V_LendFace00    Script Date: 2002-6-20 10:14:43 ******/


--显示借欠期初的列表
CREATE  VIEW dbo.V_LendFace00
--@Encode$--
AS
SELECT 	p.UserCode AS pUserCode, 
	p.FullName AS pFullName, 
	p.EntryCode AS pEntryCode,
	k.UserCode AS kUserCode,
	k.FullName AS kFullName, 
	k.STypeID AS STypeID, 
	b.UserCode AS bUserCode,
	b.FullName AS bFullName,
	ls.PtypeId AS pTypeID,
	ls.bTypeID,
	ls.kTypeID,	
	ls.GoodsNumber,
	ISNULL(ls.Iscombined, 0) AS Iscombined,
	ISNULL(ls.ItemID, 0) AS ItemID, 
	ls.producedate,
	ls.ValidDate,
	ISNULL(SUM(ls.Qty),0) AS Qty,
	--SUM(CASE WHEN (ls.Qty > 0) THEN ls.Qty ELSE 0 END) AS Borrow, 
	--SUM(CASE WHEN (ls.Qty < 0) THEN -ls.Qty ELSE 0 END) AS Lend
	SUM(BorrowQty) AS Borrow,
	SUM(LendQty) AS Lend,
	SUM(NBorrowQty) AS NBorrow,
	SUM(NLendQty) AS NLend
FROM dbo.IniGoodsLend ls 
	LEFT JOIN dbo.ptype p ON ls.PtypeId = p.typeId 
	LEFT JOIN dbo.btype b ON ls.btypeid = b.typeId 
	LEFT JOIN dbo.Stock k ON ls.ktypeid = k.typeId 
-- 9.0修改期初
GROUP BY p.UserCode,p.FullName,p.EntryCode,k.UserCode,k.FullName,k.STypeID,b.UserCode ,b.FullName,ls.PtypeId, ls.BtypeId, ls.KtypeId
, GoodsNumber, Iscombined, ItemID,ls.producedate,ls.ValidDate
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.V_LendStatus    Script Date: 2002-6-20 10:14:43 ******/



/*借进借出的总的库存状况表（包括期初）*/
CREATE   VIEW dbo.V_LendStatus
AS
SELECT	pUserCode,
		pFullName,
		pTypeID,
		kUserCode,
		kFullName,
		kTypeID,
		bUserCode,
		bFullName,
		bTypeID,
		BillDate,
		GoodsNumber,
		IsCombined,
		ItemID,
	    producedate,
	    ValidDate,
		SUM(Qty) AS Qty,
		SUM(Borrow) AS Borrow,
		SUM(BorrowBack) AS BorrowBack,
		SUM(Lend) AS Lend,
		SUM(LendBack) AS LendBack,
		SUM(NBorrow) AS NBorrow,
		SUM(NBorrowBack) AS NBorrowBack,
		SUM(NLend) AS NLend,
		SUM(NLendBack) AS NLendBack,
		SUM(saleqty) AS saleqty,
		SUM(buyqty) AS buyqty,
		CargoId
FROM(
	SELECT	pUserCode,			
			pFullName,
			pTypeID,
			kUserCode,
			kFullName,
			kTypeID,
			bUserCode,
			bFullName,
			bTypeID,
			billdate,
			GoodsNumber,
			producedate,
	        ValidDate,
			IsCombined,
			ItemID,
			qty,
			Borrow,
			BorrowBack,
			Lend,
			LendBack,
			NBorrow,
			NBorrowBack,
			NLend,
			NLendBack,saleqty,buyqty,
			cargoId
	FROM		V_LendFace
	UNION ALL
	SELECT	pUserCode,
			pFullName,
			pTypeID,
			kUserCode,
			kFullName,
			v.kTypeID,
			bUserCode,
			bFullName,
			bTypeID,
			0 as billdate,
			GoodsNumber,
			producedate,
	        ValidDate,
			IsCombined,
			ItemID,
			qty,
			Borrow,
			0 AS BorrowBack,
			Lend,
			0 AS LendBack,
			NBorrow,
			0 AS NBorrowBack,
			NLend,
			0 AS NLendBack,0,0,
			c.CargoID
	FROM V_LendFace00 v
	LEFT JOIN dbo.CargoType c ON c.KtypeID = v.kTypeID AND c.IsDefault = 1
	) AS	Lend
GROUP BY	pUserCode,
		pFullName,
		pTypeID,
		kUserCode,
		kFullName,
		kTypeID,
		bUserCode,
		bFullName,
		bTypeID,
		BillDate ,
		GoodsNumber,
			IsCombined,
			ItemID,
			producedate,
	        ValidDate,
	        cargoid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*借进借出的总的库存状况表（包括期初，过滤草稿）*/
CREATE   VIEW dbo.V_LendStatus01
AS
SELECT	pUserCode,
		pFullName,
		pTypeID,
		kUserCode,
		kFullName,
		kTypeID,
		bUserCode,
		bFullName,
		bTypeID,
		BillDate,
		GoodsNumber,
		IsCombined,
		ItemID,
	    producedate,
	    ValidDate,
		SUM(Qty) AS Qty,
		SUM(Borrow) AS Borrow,
		SUM(BorrowBack) AS BorrowBack,
		SUM(Lend) AS Lend,
		SUM(LendBack) AS LendBack,
		SUM(NBorrow) AS NBorrow,
		SUM(NBorrowBack) AS NBorrowBack,
		SUM(NLend) AS NLend,
		SUM(NLendBack) AS NLendBack,
		SUM(saleqty) AS saleqty,
		SUM(buyqty) AS buyqty,
		CargoId
FROM(
	SELECT	pUserCode,			
			pFullName,
			pTypeID,
			kUserCode,
			kFullName,
			kTypeID,
			bUserCode,
			bFullName,
			bTypeID,
			billdate,
			GoodsNumber,
			producedate,
	        ValidDate,
			IsCombined,
			ItemID,
			qty,
			Borrow,
			BorrowBack,
			Lend,
			LendBack,
			NBorrow,
			NBorrowBack,
			NLend,
			NLendBack,saleqty,buyqty,
			cargoId
	FROM		V_LendFace
	WHERE ifcheck = 't' AND Draft =0 AND RedWord =0
	UNION ALL
	SELECT	pUserCode,
			pFullName,
			pTypeID,
			kUserCode,
			kFullName,
			v.kTypeID,
			bUserCode,
			bFullName,
			bTypeID,
			0 as billdate,
			GoodsNumber,
			producedate,
	        ValidDate,
			IsCombined,
			ItemID,
			qty,
			Borrow,
			0 AS BorrowBack,
			Lend,
			0 AS LendBack,
			NBorrow,
			0 AS NBorrowBack,
			NLend,
			0 AS NLendBack,0,0,
			c.CargoID
	FROM V_LendFace00 v
	LEFT JOIN dbo.CargoType c ON c.KtypeID = v.kTypeID AND c.IsDefault = 1
	) AS	Lend
GROUP BY	pUserCode,
		pFullName,
		pTypeID,
		kUserCode,
		kFullName,
		kTypeID,
		bUserCode,
		bFullName,
		bTypeID,
		BillDate ,
		GoodsNumber,
			IsCombined,
			ItemID,
			producedate,
	        ValidDate,
	        cargoid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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












/****** Object:  View dbo.V_LendStatus    Script Date: 2002-6-20 10:14:43 ******/



/*借进借出的总的库存状况表（包括期初）*/
CREATE VIEW dbo.V_LendStatus2
AS
SELECT	pUserCode,
		pFullName,
		pTypeID,
		kUserCode,
		kFullName,
		kTypeID,
		bUserCode,
		bFullName,
		bTypeID,
		STypeId,
		--BillDate,
		SUM(Qty) AS Qty,
		SUM(Borrow) AS Borrow,SUM(BorrowBack) AS BorrowBack,
		SUM(Lend) AS Lend,SUM(LendBack) AS LendBack
FROM(
	SELECT	pUserCode,			
			pFullName,
			pTypeID,
			kUserCode,
			kFullName,
			kTypeID,
			bUserCode,
			bFullName,
			bTypeID,
			billdate,
			qty,
			Borrow,
			BorrowBack,
			Lend,
			LendBack,
			STypeID
	FROM	V_LendFace
	UNION ALL
	SELECT	pUserCode,
			pFullName,
			pTypeID,
			kUserCode,
			kFullName,
			kTypeID,
			bUserCode,
			bFullName,
			bTypeID,
			0 as billdate,
			qty,
			Borrow,
			0 AS BorrowBack,
			Lend,
			0 AS LendBack,
			STypeID
	FROM	V_LendFace00
	) AS	Lend
GROUP BY	pUserCode,
		pFullName,
		pTypeID,
		kUserCode,
		kFullName,
		kTypeID,
		bUserCode,
		bFullName,
		bTypeID,
		STypeId
	--	BillDate 























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










CREATE VIEW dbo.v_VirtualStockOrderStatus
--@Encode$--
AS
SELECT 	d.ptypeid,
		d.ktypeid,
		SUM(ISNULL(d.SaleOrderQty,0)) AS SaleOrderQty,
		SUM(ISNULL(d.BuyOrderQty,0)) AS BuyOrderQty,
		SUM(ISNULL(d.drafBuyQty,0)) drafBuyQty,
		SUM(ISNULL(d.saleDrafQty,0)) saleDrafQty,
		CASE WHEN SUM(ISNULL(d.QuantityQty,0)) < 0 THEN 0 ELSE SUM(ISNULL(d.QuantityQty,0)) END AS QuantityQty,
		CASE WHEN SUM(ISNULL(d.yxsdhQty,0)) < 0 THEN 0 ELSE SUM(ISNULL(d.yxsdhQty,0)) END AS yxsdhQty,
		SUM(ISNULL(d.SaleReachQty,0)) AS SaleReachQty,
		SUM(ISNULL(d.BuyReachQty,0)) AS BuyReachQty,
		d.CargoID,
		d.ItemID,
		d.IsCombined,
	    d.GoodsNumber,
	    d.ProduceDate,
	    d.ValidDate
	   
FROM 
(
	SELECT 	c.ptypeid,
			c.ktypeid,
			CASE WHEN c.billtype IN( 300,313) THEN c.qty ELSE 0 END AS SaleOrderQty,
			CASE c.billtype WHEN 301 THEN c.qty ELSE 0 END AS BuyOrderQty,
			CASE c.billtype WHEN 301 THEN c.drafBuyQty ELSE 0 END AS drafBuyQty,
			CASE WHEN c.billtype IN(300,313) THEN c.saleDrafQty ELSE 0 END AS saleDrafQty,
			CASE c.billtype WHEN 301 THEN c.qty - c.reachqty - c.drafBuyQty ELSE 0 END AS QuantityQty,
			CASE WHEN c.billtype IN( 300,313) THEN c.qty - c.reachqty - c.saleDrafQty ELSE 0 END AS yxsdhQty,
			CASE WHEN c.billtype IN( 300,313) THEN c.Reachqty ELSE 0 END AS SaleReachQty,
			CASE c.billtype WHEN 301 THEN c.Reachqty ELSE 0 END AS BuyReachQty,
			c.CargoID,
			c.ItemID,
		    c.IsCombined,
			c.GoodsNumber,
			c.ProduceDate,
			c.ValidDate
			
   FROM
	(
		SELECT 	a.billtype,
				b.ptypeid,
				b.ktypeid ,
				SUM(b.qty) AS qty,
				SUM(b.reachqty) AS reachqty,
				SUM(ISNULL(buyDraf.Qty,0.00)) drafBuyQty,--订单入库草稿数量
				SUM(ISNULL(saleDraf.Qty,0.00)) saleDrafQty,--销售出库草稿数量
				CASE b.CargoID WHEN 0 THEN (SELECT CargoID FROM CargoType WHERE KtypeID=b.ktypeid AND IsDefault=1) ELSE b.CargoID END AS CargoID,
				b.ItemID,
				b.IsCombined,
				b.GoodsNumber,
				b.ProduceDate,
				b.ValidDate
		FROM 	orderindex a 
		JOIN orderbill b ON (a.billnumberid=b.billnumberid)
		LEFT JOIN (	SELECT OrderID,ISNULL(SUM(Qty),0) Qty FROM (
					SELECT B.OrderID,B.Qty
					FROM BuyBill B 
					WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=B.BillNumberId)
						AND b.OrderID > 0
					UNION ALL
					SELECT B.OrderID,B.Qty
					FROM dbo.AppraisalBill b 
					WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=B.BillNumberId)
						AND b.OrderID > 0) Bi GROUP BY Bi.OrderID
				) buyDraf ON buyDraf.OrderID=B.OrderID
		LEFT JOIN (SELECT OrderID,ISNULL(SUM(Qty),0) Qty FROM (
					SELECT BB.OrderID,BB.Qty
					FROM SaleBill BB 
					WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=BB.BillNumberId)
					 AND bb.OrderID > 0
					UNION ALL
					SELECT BB.OrderID,BB.Qty
					FROM SendBill BB 
					WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=BB.BillNumberId)
					 AND bb.OrderID > 0) S GROUP BY S.OrderID
				) saleDraf ON saleDraf.OrderID=B.OrderID
		WHERE	
				A.BillOver = 0
				AND A.OrderState<>1
				AND b.BillOver = 0
		GROUP BY b.ptypeid,b.ktypeid,a.billtype,b.CargoID,b.ItemID,b.IsCombined,b.GoodsNumber,b.ProduceDate,b.ValidDate
		UNION ALL
		SELECT 	a.billtype,
				b.ptypeid,
				b.ktypeid ,
				SUM(b.qty) AS qty,
				SUM(b.reachqty) AS reachqty,
				0 drafBuyQty,
				0 saleDrafQty,
				CASE b.CargoID WHEN 0 THEN (SELECT CargoID FROM CargoType WHERE KtypeID=b.ktypeid AND IsDefault=1) ELSE b.CargoID END AS CargoID,
				b.ItemID,
				b.IsCombined,
				b.GoodsNumber,
				b.ProduceDate,
				b.ValidDate
		FROM 	orderindex a 
		INNER JOIN PT_Combin_OrderBillDetail b ON (a.billnumberid=b.billnumberid)
		WHERE	
				A.BillOver = 0
				AND A.OrderState<>1
				AND b.BillOver = 0
		GROUP BY b.ptypeid,b.ktypeid,a.billtype,b.CargoID,b.ItemID,b.IsCombined,b.GoodsNumber,b.ProduceDate,b.ValidDate
	) c 
)
d GROUP BY d.ptypeid,d.ktypeid,d.CargoID,d.ItemID,d.IsCombined,d.GoodsNumber,d.ProduceDate,d.ValidDate
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






/****** Object:  View [dbo].[vPtypeUnitALL]    Script Date: 11/20/2012 18:13:43 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vPtypeUnitALL]'))
DROP VIEW [dbo].[vPtypeUnitALL]
GO

/****** Object:  View [dbo].[vPtypeUnitALL]    Script Date: 11/20/2012 18:13:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


    
CREATE VIEW [dbo].[vPtypeUnitALL]
AS   
	 SELECT 	P.typeId,
				P.ParId,
				P.leveal,
				P.sonnum,
				p.UserCode,
				p.FullName,
				p.EntryCode,
				p.deleted,
				p.Area,
				1 as baseUnitRate,
				ISNULL(e1.Rate,1) as buyUnitRate,
				ISNULL(e2.Rate,1) as saleUnitRate,
				ISNULL(e3.Rate,1) as stockUnitRate,
				e4.FullName AS buyunitfullname,
				e5.FullName AS saleunitfullname,
				e6.FullName AS stockunitfullname,
				e7.FullName AS baseunitfullname,
				e8.FullName AS assistantfullname  
		FROM 	dbo.PType P
		LEFT JOIN dbo.PType_Units_Ext e1 ON e1.PTypeId = P.TypeId AND P.BuyUnitId = E1.UnitsId
		LEFT JOIN dbo.PType_Units_Ext e2 ON e2.PTypeId = P.TypeId AND P.SaleUnitId = e2.UnitsId
		LEFT JOIN dbo.PType_Units_Ext e3 ON e3.PTypeId = P.TypeId AND P.StockUnitId = e3.UnitsId
		LEFT JOIN dbo.PType_Units e4 ON  e4.UnitsId = P.BuyUnitId
		LEFT JOIN dbo.PType_Units e5 ON  e5.UnitsId = P.SaleUnitId
		LEFT JOIN dbo.PType_Units e6 ON  e6.UnitsId = P.StockUnitId
		LEFT JOIN dbo.PType_Units e7 ON  e7.UnitsId = p.baseUnitId
		LEFT  JOIN dbo.PType_Units  e8 ON e8.UnitsId = p.AssistantUnitId
		WHERE 	P.TypeId <> '00000' 
		

GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_AdDebt    Script Date: 2002-6-20 10:14:43 ******/

CREATE VIEW dbo.vWeb_AdDebt
--@Encode$--
AS
SELECT dbo.AdDebtBill.BillNumberId, dbo.AdDebtBill.Comment, dbo.AdDebtBill.BtypeId, 
      dbo.AdDebtBill.total, dbo.btype.UserCode, dbo.btype.FullName,dbo.AdDebtBill.ID
FROM dbo.AdDebtBill INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



/*
成本调价单明细
*/
CREATE    VIEW dbo.vWeb_AdPriceBill
--@Encode$--
AS

SELECT
		dbo.AdPriceBill.BillNumberId,
		dbo.AdPriceBill.Comment AS base, 		
		--CASE WHEN (i.ktypeid='00000' AND i.draft=1) --调价全部仓库 且是草稿时
		--	THEN (SELECT SUM(QTY) FROM goodsstocks_qty WHERE ptypeid=AdPriceBill.ptypeid GROUP BY ptypeid)
		--ELSE 
		dbo.AdPriceBill.Qty AS QTY,
		price =CASE 
				WHEN dbo.AdPriceBill.IsUnit2=1 
					THEN       dbo.AdPriceBill.Price *  dbo.ptype.UnitRate1 
					ELSE     dbo.AdPriceBill.Price 
				END,
		beforeprice =CASE 
				WHEN dbo.AdPriceBill.IsUnit2=1 
					THEN       dbo.AdPriceBill.beforeprice *  dbo.ptype.UnitRate1 
					ELSE     dbo.AdPriceBill.beforeprice 
				END,
		dbo.AdPriceBill.NTotal,
		dbo.AdPriceBill.NPrice,
		dbo.AdPriceBill.frombillid,
		dbo.AdPriceBill.total, 
		dbo.AdPriceBill.beforetotal, 
		dbo.AdpriceBill.Rate,
		dbo.AdPriceBill.ProduceDate, 
		dbo.AdPriceBill.ValidDate, 
		dbo.AdPriceBill.GoodsNumber, 
		dbo.AdPriceBill.GoodsCostPrice, 
		dbo.AdPriceBill.HandZeroCost, 
		dbo.AdPriceBill.PtypeId, 
		dbo.AdPriceBill.IsUnit2, 
		dbo.AdPriceBill.ChangeAllStock, 
		dbo.AdPriceBill.ID,			        
		dbo.AdPriceBill.ItemID,
		itemname= CASE WHEN dbo.AdPriceBill .IsCombined = 0  THEN
						    (SELECT FullName FROM xw_SelfData WHERE _Id= dbo.AdPriceBill.ItemId)
					        ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= dbo.AdPriceBill.ItemId ) END,
		iscombined=dbo.AdPriceBill.IsCombined,
		dbo.ptype.baseUnitId AS UnitID,
		dbo.ptype.AssistantUnitId AS NUnitID,			
		u.FullName AS unit,
		v.FullName AS nunit,		
		CASE WHEN dbo.ptype.AssistantUnitId IS NULL THEN NULL ELSE dbo.AdPriceBill.UnitRate END AS UnitRate,		
		CASE WHEN dbo.ptype.AssistantUnitId IS NULL THEN NULL ELSE dbo.AdPriceBill.NQty END AS NQty,
		dbo.AdPriceBill.cargoID,
		ct.FullName AS cargofullname,
		dbo.AdPriceBill.ktypeid,
		s.FullName AS kfullname,
		tmp.BillCode AS frombillnumberusercode,
		adpricebill.FromBillNumberId,
		AdPriceBill.serial,
		dbo.Ptype.*,cbd.*,
		dbo.AdPriceBill.ChangeTotal
FROM	dbo.AdPriceBill 
	INNER JOIN dbo.ptype ON dbo.AdPriceBill.PtypeId = dbo.ptype.typeId
	LEFT  JOIN PType_Units u ON u.UnitsId=dbo.ptype.baseUnitId
	LEFT  JOIN PType_Units v ON v.UnitsId=dbo.ptype.AssistantUnitId
	LEFT  JOIN CargoType ct ON ct.CargoID=dbo.AdPriceBill.cargoID
	LEFT  JOIN Stock s ON s.typeId=dbo.AdPriceBill.ktypeid
	INNER JOIN BillIndex i On AdPriceBill.Billnumberid=i.billnumberid
	INNER JOIN 
	(
		SELECT bi.billCode,T.AdPriceId FROM 
		(
			SELECT rb.BillNumberId,rb.MainBillNumberId,rb.id,ab.id AS AdPriceId FROM ADPriceBill ab
			LEFT JOIN ReceiptBill rb ON rb.id=ab.FromBillID
		) T LEFT JOIN BillIndex bi ON T.MainBillNumberId=bi.BillNumberId
	) tmp ON tmp.AdPriceId=dbo.AdPriceBill.Id
	LEFT JOIN
	(
		SELECT cbd.*,e.fullname as efullnamecustom,
		p.fullname as pfullnamecustom,
		b.fullname as bfullnamecustom,
		d.fullname as dfullnamecustom,
		k.fullname as kfullnamecustom,
		s.fullname as sfullnamecustom
		 FROM custom_billdetails cbd
		LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
		LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
		LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
		LEFT JOIN department d ON cbd.sysdiy14=d.typeid
		LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
		LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
	) cbd ON cbd.Billid=AdPriceBill.BillnumberId AND cbd.detailid=AdPriceBill.id AND cbd.BillType=i.billtype
	
	




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE   VIEW dbo.vWeb_AdvantageBill
AS
	SELECT     	                
		distinct a.BillNumberID,
                                a.Serial,
				b.typeid,
                                b.UserCode,
                                b.FullName,
				a.StartDate,
				a.EndDate,
				a.StandardCode,
				c.StandardName,
				a.type,
		                case a.Type When 1 then '按数量' else '按金额' end as standardtype,
				a.Qty,
		                a.Total,
		                a.Comment,
				a.Comment AS Base,
				a.itemid,
				a.IsCombined,
				itemname= CASE WHEN a.IsCombined = 0  THEN
						 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
				b.customitemid ,
				b.customitemfrom ,
				b.customitemname,
				b.customitemrefid,
				a.[ID],
				a.GoodsNumber
	FROM dbo.Advantage a
                JOIN Ptype b on (a.ptypeid=b.typeid)
                JOIN Advantage_standard c on (a.StandardCode=c.StandardCode)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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






/****** Object:  View dbo.vWeb_ARAPIndex    Script Date: 2002-6-20 10:14:43 *****

INNER JOIN
          (SELECT DISTINCT BillNumberId
         FROM Listtable
         WHERE AtypeId IN ('0000100005', '0000200001')) L ON 
      dbo.BillIndex.BillNumberId = L.BillNumberId

*/
CREATE   VIEW dbo.vWeb_ARAPIndex
AS
SELECT 	BillCode,
		BillNumberId,
		BillDate,
		etypeid,
		btypeid,
		BillType,
		totalmoney AS Total, 
      	totalinmoney, 
		Comment,
		atypeid,
		TeamNo,
		RedWord
FROM 	BillIndex
WHERE 	BillType IN (11,45,34,6,36,93,4,66,115,116,128,129,305,84,85,148,149,141,145,150,151,155,157,160,161) 
		AND ifcheck = 't' 
		AND draft = 0
UNION ALL
SELECT	A.BillCode,
		A.BillNumberId,
		A.BillDate,
		A.ETypeid,
		L.BTypeid,
		A.BillType,
		CASE A.RedWord 
			WHEN 0 THEN L.Total
			ELSE ABS(L.Total)
		END AS Total,
      	0 AS totalinmoney, 
		A.Comment,
		L.ATypeid,
		A.TeamNo,
		A.RedWord
FROM	BillIndex A,
		ListTable L
WHERE	A.BillNumberId = L.BillNumberId
		AND A.BillType = 159
		AND A.IfCheck = 't'
		AND A.Draft = 0
		AND L.ATypeId IN ('0000100005','0000200001')
		








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE                VIEW dbo.vWeb_Balance
AS
SELECT l.BillType, 
		l.btypeid, 
		l.etypeid, 
		ISNULL(l.ktypeid, '') AS ktypeid, 
		ISNULL(l.ktypeid2,'') AS ktypeid2, 
		b.UserCode AS bUserCode, 
		b.FullName AS bFullName, 
		l.BillNumberId, 
		l.BillDate, 
		l.BillCode, 
		e.FullName AS EFullName, 
		CAST(ISNULL(l.totalmoney, 0) - ISNULL(l.totalinmoney, 0) - ISNULL(l.CompleteTotal, 0) - ISNULL(l.preferencemoney,0) AS  NUMERIC(24, 10) ) AS unCompleteTotal, 
		CAST(ISNULL(l.preferencemoney, 0) AS  NUMERIC(24, 10) ) AS preferencemoney, 
		CAST(ISNULL(l.totalmoney, 0) AS  NUMERIC(24, 10) ) AS completetotal, 
		CAST(ISNULL(l.totalinmoney, 0) + ISNULL(l.CompleteTotal, 0) AS  NUMERIC(24, 10) ) AS totalinmoney, 
		l.IfStopMoney
FROM dbo.btype b INNER JOIN
      dbo.BillIndex l ON b.typeId = l.btypeid INNER JOIN
      dbo.employee e ON l.etypeid = e.typeId LEFT OUTER JOIN
      dbo.Stock k ON l.ktypeid = k.typeId
WHERE l.BillType IN (11, 6, 141, 150, 157, 149, 93, 85, 34, 45, 145, 151, 148, 36, 84, 160,161,167,168,170,172) 
AND (l.RedWord = 0) 
AND (l.draft = 0)
AND (
	     (ISNULL(l.totalmoney, 0)  - ISNULL(l.CompleteTotal, 0)<>0 AND ISNULL(l.totalinmoney, 0)=0 AND ISNULL(l.preferencemoney,0)=0)
	     OR((
			(ISNULL(l.totalmoney, 0)  -(ISNULL(l.CompleteTotal, 0)+ISNULL(l.totalinmoney, 0)+ISNULL(l.preferencemoney,0))<0 AND ISNULL(l.totalmoney, 0)<0)
			OR
			(ISNULL(l.totalmoney, 0)  -(ISNULL(l.CompleteTotal, 0)+ISNULL(l.totalinmoney, 0)+ISNULL(l.preferencemoney,0))>0 AND ISNULL(l.totalmoney, 0)>=0))
			AND (ISNULL(l.totalinmoney, 0)<>0 OR ISNULL(l.preferencemoney,0)<>0)
		    )
		OR (l.BillType IN (160,161) AND l.jsState <> '2')
	) 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE            VIEW dbo.vWeb_Balance1
AS
SELECT l.BillType, 
		l.btypeid, 
		l.etypeid, 
		ISNULL(l.ktypeid, '') AS ktypeid, 
		ISNULL(l.ktypeid2,'') AS ktypeid2, 
		b.UserCode AS bUserCode, 
		b.FullName AS bFullName, 
		l.BillNumberId, 
		l.BillDate, 
		l.BillCode, 
		e.FullName AS EFullName, 
		CAST(ISNULL(l.totalmoney, 0) - ISNULL(l.totalinmoney, 0) - ISNULL(l.CompleteTotal, 0) - ISNULL(l.preferencemoney,0) AS  NUMERIC(24, 10) ) AS unCompleteTotal, 
		CAST(ISNULL(l.preferencemoney, 0) AS  NUMERIC(24, 10) ) AS preferencemoney, 
		CAST(ISNULL(l.totalmoney, 0) AS  NUMERIC(24, 10) ) AS completetotal, 
		CAST(ISNULL(l.totalinmoney, 0) + ISNULL(l.CompleteTotal, 0) AS  NUMERIC(24, 10) ) AS totalinmoney, 
		l.IfStopMoney
FROM dbo.btype b INNER JOIN
      dbo.BillIndex l ON b.typeId = l.btypeid INNER JOIN
      dbo.employee e ON l.etypeid = e.typeId LEFT OUTER JOIN
      dbo.Stock k ON l.ktypeid = k.typeId
WHERE l.BillType IN (11, 6, 141, 150, 157, 149, 93, 85, 34, 45, 145, 151, 148, 36, 84, 160,161,167,168,170,172) 
AND (l.RedWord = 0) 
AND (l.draft = 0)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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








--可发货金额=信用额度+预收-应收－预付＋应付

/****** Object:  View dbo.vWeb_BtypeAR    Script Date: 2002-6-20 10:14:43 ******/

CREATE VIEW dbo.vWeb_BtypeAR
--@Encode$--
AS
SELECT	B.TypeId, 
		B.FullName,
		M.STypeId,
		SUM(ISNULL(M.ARTotal,0)) AS artotal,
		SUM(ISNULL(M.YsTotal,0)) AS ystotal,
		SUM(ISNULL(M.APTotal,0)) AS aptotal,
		SUM(ISNULL(M.YfTotal,0)) AS yftotal,
		SUM(ISNULL(M.Credit,0)) AS ARLimit, 
		SUM(ISNULL(M.Credit,0)) + SUM(ISNULL(M.YsTotal,0))- SUM(ISNULL(M.ARTotal,0))- SUM(ISNULL(M.YfTotal,0)) + SUM(ISNULL(M.APTotal,0)) AS fhje
FROM	btype B
LEFT JOIN (
			SELECT	BtypeId,
					StypeId,
					Credit,
					0 AS ArTotal,
					0 AS ApTotal,
					0 AS YsTotal,
					0 AS YfTotal
			FROM	btype_credit
			UNION ALL
			SELECT  BTypeId,
					STypeId,
					0 AS Credit,
					ArTotal,
					ApTotal,
					YSTotal,
					YFTotal
			FROM	BType_ARAPTotal			
)M ON LEFT(M.BTypeId,LEN(B.TypeId)) = B.TypeId
WHERE	B.deleted = 0 
		AND B.sonnum = 0
GROUP BY B.typeId,
		 b.FullName,
		 M.StypeId		











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_Gathering    Script Date: 2002-6-20 10:14:43 ******/

CREATE VIEW dbo.vWeb_Gathering
--@Encode$--
AS
SELECT dbo.gatheringBill.BillNumberId, dbo.gatheringBill.AtypeId, dbo.gatheringBill.total, 
      dbo.gatheringBill.Comment, dbo.atype.FullName, dbo.atype.UserCode,dbo.gatheringBill.ID
FROM dbo.atype INNER JOIN
      dbo.gatheringBill ON dbo.atype.typeId = dbo.gatheringBill.AtypeId












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE  VIEW dbo.vWeb_GatheringPay_SaleBuy
AS
SELECT B.BillDate, 
       B.BillCode, 
       C.NCompleteTotal, 
       B.BillType,
       C.GoodsBillID, 
       C.MoneyBillID, 
       E.FullName, 
       E.TypeID AS ETypeID,
       C.Draft,
       C.GoodsBillDetailID,
       B.ifYearBill
FROM dbo.BillIndex B
INNER JOIN dbo.CompleteTotal C ON C.GoodsBillID= B.BillNumberId AND C.BillType=B.BillType
LEFT JOIN dbo.employee E ON E.typeId=B.ETypeId
WHERE 
	B.BillType IN (11,12, 6, 141, 150, 157, 93, 85, 151, 160,167,168,172,178,186,195,196,179,181,182,200,115,116,128,129,212,213,312,450,34, 45,46, 145, 149, 148, 36, 84, 161,170)
UNION ALL
SELECT B.BillDate, 
       B.BillCode, 
       C.NCompleteTotal, 
       B.BillType,
       C.GoodsBillID, 
       C.MoneyBillID, 
       E.FullName, 
       E.TypeID AS ETypeID,
       C.Draft,
       C.GoodsBillDetailID,
       B.ifYearBill
FROM  dbo.ReceiptBillIndex B
INNER JOIN dbo.CompleteTotal C ON C.GoodsBillID= B.BillNumberId AND C.BillType=B.BillType
LEFT JOIN dbo.employee E ON E.typeId=B.ETypeId
WHERE 
	B.BillType IN (404,405)
UNION ALL
SELECT B.BillDate, 
       B.BillCode, 
       C.NCompleteTotal, 
       B.BillType,
       C.GoodsBillID, 
       C.MoneyBillID, 
       E.FullName, 
       E.TypeID AS ETypeID,
       C.Draft,
       C.GoodsBillDetailID,
       B.ifYearBill
FROM  dbo.Coupon_BillIndex  B
INNER JOIN dbo.CompleteTotal C ON C.GoodsBillID= B.BillNumberId AND C.BillType=B.BillType
LEFT JOIN dbo.employee E ON E.typeId=B.ETypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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











-- ========================================================================
-- 功能说明：		结合 GiveBill 和 GiveMeBill 查询赠送单、获赠单数据，
-- 			并结合 PType 商品信息表，返回具体草稿数据
-- 作者：		卢春
-- 最后修改时间：	2002-10-30
-- ========================================================================

CREATE  VIEW dbo.vWeb_GiveBill
AS
	SELECT	a.Comment AS BillComment,
		a.BillNumberID,
		a.PTypeID,
		Qty =
			CASE WHEN a.isUnit2 = 1 THEN
				CASE WHEN b.UnitRate1 <> 0 THEN
					CAST( a.Qty/b.UnitRate1 AS  NUMERIC(24, 10)  ) 
				ELSE NULL END 
			ELSE a.Qty END,
		a.IsUnit2, 
		b.UserCode,
		b.FullName,
		b.Unit1,
		b.Unit2,
		b.UnitRate1,
		b.UnitRate2,
		a.ID
	FROM dbo.GiveBill a
	INNER JOIN
	dbo.PType b ON a.PTypeID = b.TypeID

	UNION ALL

	SELECT	a.Comment AS BillComment,
		a.BillNumberID,
		a.PTypeId,
		Qty =
			CASE WHEN a.isUnit2 = 1 THEN
				CASE WHEN b.UnitRate1 <> 0 THEN
					CAST( a.Qty/b.UnitRate1 AS  NUMERIC(24, 10)  ) 
				ELSE NULL END 
			ELSE a.Qty END,
		a.IsUnit2, 
		b.UserCode,
		b.FullName,
		b.Unit1,
		b.Unit2,
		b.UnitRate1,
		b.UnitRate2,
		a.ID
	FROM dbo.GiveMeBill a
	INNER JOIN
	dbo.PType b ON a.PTypeID = b.TypeID














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_GuestGet    Script Date: 2002-6-20 10:14:43 ******/

CREATE VIEW dbo.vWeb_GuestGet
--@Encode$--
AS
SELECT ptype.UserCode, ptype.FullName, GuestGet.*, ptype.Unit1
FROM GuestGet INNER JOIN
      ptype ON GuestGet.PtypeId = ptype.typeId











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_GuestWLDZ    Script Date: 2002-6-20 10:14:43 ******/

CREATE view vWeb_GuestWLDZ(BID,BDate,BCode,Btype,Btypeid,ApAdd,ApReduce,TeamNo1,Comment,ID)
--@Encode$--
as
SELECT dbo.GuestBackIndex.BillNumberId, dbo.GuestBackIndex.BillDate, 
      dbo.GuestBackIndex.BillCode, dbo.GuestBackIndex.BillType, 
      dbo.GuestBackIndex.btypeid,null,
      dbo.GuestBack.TaxTotal,dbo.GuestBack.TeamNo1,'退货:'+dbo.ptype.FullName+' '+cast(dbo.GuestBack.Qty as varchar(15)) +'*'+cast(dbo.GuestBack.TaxPrice as varchar(15)),
     dbo.GuestBack.ID
FROM dbo.GuestBack INNER JOIN
      dbo.GuestBackIndex ON 
      dbo.GuestBack.BillNumberId = dbo.GuestBackIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.GuestBack.PtypeId = dbo.ptype.typeId
union all
SELECT dbo.GuestPayIndex.BillNumberId,dbo.GuestPayIndex.BillDate, dbo.GuestPayIndex.BillCode, 
      dbo.GuestPayIndex.BillType, dbo.GuestPayIndex.btypeid,null,dbo.GuestPay.total, 
      dbo.GuestPay.TeamNo1,'付款:'+dbo.GuestPay.Comment,
      dbo.GuestPay.ID
FROM dbo.GuestPay INNER JOIN
      dbo.GuestPayIndex ON 
      dbo.GuestPay.BillNumberId = dbo.GuestPayIndex.BillNumberId INNER JOIN
      dbo.atype ON dbo.GuestPay.AtypeId = dbo.atype.typeId
union all
SELECT dbo.GuestGetIndex.BillNumberId, dbo.GuestGetIndex.BillDate, 
      dbo.GuestGetIndex.BillCode, dbo.GuestGetIndex.BillType, 
      dbo.GuestGetIndex.btypeid, dbo.GuestGetIndex.totalmoney, NULL,dbo.GuestGet.TeamNo1, 
      '收货:' + dbo.ptype.FullName + ' ' + CAST(dbo.GuestGet.Qty AS varchar(15)) 
      + '*' + CAST(dbo.GuestGet.TaxPrice AS varchar(15)) AS Expr2, 
      dbo.GuestGet.OrderID
FROM dbo.GuestGetIndex INNER JOIN
      dbo.GuestGet ON 
      dbo.GuestGetIndex.BillNumberId = dbo.GuestGet.BillNumberId INNER JOIN
      dbo.ptype ON dbo.GuestGet.PtypeId = dbo.ptype.typeId
union all
SELECT dbo.BillIndex.BillNumberId, dbo.BillIndex.BillDate, dbo.BillIndex.BillCode, 
      dbo.BillIndex.BillType, dbo.AdDebtBill.BtypeId,null, dbo.AdDebtBill.total, 
      dbo.AdDebtBill.TeamNo1,dbo.AdDebtBill.Comment,
      dbo.AdDebtBill.ID
FROM dbo.AdDebtBill INNER JOIN
      dbo.BillIndex ON dbo.AdDebtBill.BillNumberId = dbo.BillIndex.BillNumberId
where dbo.BillIndex.BillType in (115,128)
union all
SELECT dbo.BillIndex.BillNumberId, dbo.BillIndex.BillDate, dbo.BillIndex.BillCode, 
      dbo.BillIndex.BillType, dbo.AdDebtBill.BtypeId, dbo.AdDebtBill.total,null, 
      dbo.AdDebtBill.TeamNo1,dbo.AdDebtBill.Comment,
      dbo.AdDebtBill.ID
FROM dbo.AdDebtBill INNER JOIN
      dbo.BillIndex ON dbo.AdDebtBill.BillNumberId = dbo.BillIndex.BillNumberId
where dbo.BillIndex.BillType in (116,129)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_HotList    Script Date: 2002-6-20 10:14:43 ******/

CREATE VIEW dbo.vWeb_HotList
--@Encode$--
AS
SELECT dbo.Hotlist.HappenDate, dbo.Hotlist.Title, dbo.PloyType.name AS PloyName, 
      dbo.btype.FullName AS BFullName, dbo.employee.FullName AS EFullName, 
      dbo.Hotlist.Etypeid, dbo.Hotlist.Btypeid, dbo.Hotlist.PloyTypeid, 
      dbo.Hotlist.New_number, dbo.Hotlist.ID, dbo.Hotlist.Address, 
      dbo.Hotlist.Comment
FROM dbo.PloyType INNER JOIN
      dbo.Hotlist ON dbo.PloyType.ploytypeid = dbo.Hotlist.PloyTypeid INNER JOIN
      dbo.employee ON dbo.Hotlist.Etypeid = dbo.employee.typeId INNER JOIN
      dbo.btype ON dbo.Hotlist.Btypeid = dbo.btype.typeId











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：黄飞佳
	日期：2012-05-17
	描述：根据Iscombined值获取所有满足条件的ItemID
*/
CREATE VIEW vWeb_ItemIDByIsCombined
(
	itemID,
	iscombined,
	fullname,
	id,
	DataTypeId
)
AS
SELECT	CASE 
			WHEN IsCombined =1 THEN 'C_'+CAST(T.id AS VARCHAR(10)) 
			ELSE 'B_'+CAST(T.id AS VARCHAR(10)) 
		END  AS itemID,
		t.iscombined,
		t.fullname,
		t.id,
		DataTypeId
FROM	(	 
			SELECT	1 as IsCombined, 
					REPLACE(FullName,'я','/') AS FullName,
					id,
					itemsid AS DataTypeId 
			FROM	CustomReferenceValue
			UNION  ALL 
			SELECT  0 AS IsCombined,  
					FullName,_Id AS id,
					DataTypeId 
			FROM	xw_SelfData 
			WHERE	ParTypeId<>'root'             
      ) t
      
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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









----------王跃 得到保损报溢mingxi

CREATE VIEW dbo.vWeb_LoseBill
AS
SELECT m.comment AS mcomment, m.BillNumberId, m.PtypeId,
              qty = case when m.isUnit2 =1 
                                        then  case when p.UnitRate1<>0 
                                                              then cast(m.Qty/p.UnitRate1 as  NUMERIC(24, 10) ) 
                                                              else null end 
                                       else m.Qty end,
                m.IsUnit2, 
                p.UserCode, p.FullName, p.Unit1, p.Unit2, p.UnitRate1, p.UnitRate2, m.ID,
	p.EntryCode,
	p.Standard,
	p.Type,
	p.Area,
	p.IfSerial,
	m.Serial
FROM dbo.LoseBill m INNER JOIN
      dbo.ptype p ON m.PtypeId = p.typeId

union all

SELECT m.comment AS mcomment, m.BillNumberId, m.PtypeId,
              qty = case when m.isUnit2 =1 
                                        then  case when p.UnitRate1<>0 
                                                              then cast(m.Qty/p.UnitRate1 as  NUMERIC(24, 10) ) 
                                                              else null end 
                                       else m.Qty end,
                m.IsUnit2, 
                p.UserCode, p.FullName, p.Unit1, p.Unit2, p.UnitRate1, p.UnitRate2, m.ID,
	p.EntryCode,
	p.Standard,
	p.Type,
	p.Area,
	p.IfSerial,
	m.Serial
FROM dbo.OverFlowBill m INNER JOIN
      dbo.ptype p ON m.PtypeId = p.typeId













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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











-- ========================================================================
-- 功能说明：		结合 GiveBill 和 GiveMeBill 查询赠送单、获赠单数据，
-- 			并结合 PType 商品信息表，返回具体草稿数据
-- 作者：		卢春
-- 最后修改时间：	2002-10-30
-- ========================================================================

CREATE  VIEW dbo.vWeb_MoneyBill
AS
	SELECT	a.Comment AS BillComment,
		a.BillNumberID,
		a.ATypeID,
		a.Total,
		b.UserCode,
		b.FullName,
		a.ID
	FROM dbo.MoneyBill a
	INNER JOIN
	dbo.AType b ON a.ATypeID = b.TypeID











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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









CREATE VIEW dbo.vWeb_MoveBill
AS
SELECT m.comment AS mcomment, m.BillNumberId, m.PtypeId, 
      qty = CASE WHEN m.isUnit2 = 1 THEN CASE WHEN p.UnitRate1 <> 0 THEN cast(m.Qty
       / p.UnitRate1 AS  NUMERIC(24, 10) ) ELSE NULL END ELSE m.Qty END, m.IsUnit2, 
      p.UserCode, p.FullName, p.Unit1, p.Unit2, p.UnitRate1, p.UnitRate2,m.ID,
	m.Serial,
	p.EntryCode,
	p.Standard,
	p.Type,
	p.Area,
	p.IfSerial
FROM dbo.MoveBill m INNER JOIN
      dbo.ptype p ON m.PtypeId = p.typeId











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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









CREATE VIEW dbo.vWeb_MoveBjBill
AS
SELECT m.comment AS mcomment, m.BillNumberId, m.PtypeId, 
      qty = CASE WHEN m.isUnit2 = 1 THEN CASE WHEN p.UnitRate1 <> 0 THEN cast(m.Qty
       / p.UnitRate1 AS  NUMERIC(24, 10) ) ELSE NULL END ELSE m.Qty END, m.IsUnit2, 
      p.UserCode, p.FullName, p.Unit1, p.Unit2, p.UnitRate1, p.UnitRate2,
     price= case when m.isUnit2 = 1 then m.price *  p.UnitRate1 else m.price end,
     m.total,m.ID,
	p.EntryCode,
	p.Standard,
	p.Type,
	p.Area,
	p.IfSerial,
	m.Serial
FROM dbo.MoveBJBill m INNER JOIN
      dbo.ptype p ON m.PtypeId = p.typeId













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO








CREATE                VIEW dbo.vWeb_OrderBill
AS
SELECT	OrderIndex.billNumberId,
	btype.FullName AS fhdw,
	OrderBill.OrderID,
	OrderBill.WaitQty,
	qty = case when dbo.OrderBill.isUnit2 =1 
		then case when dbo.ptype.UnitRate1 <> 0 
			then cast(dbo.OrderBill.Qty/dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
			else dbo.OrderBill.Qty end 
		else dbo.OrderBill.Qty end,
	Price = case when dbo.OrderBill.isUnit2 =1 AND dbo.ptype.UnitRate1 <> 0 
			then cast(dbo.OrderBill.Price * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
		else dbo.OrderBill.Price end,
    OrderBill.Discount,
	OrderBill.Tax,
	TaxPrice = case when dbo.OrderBill.isUnit2 =1 AND dbo.ptype.UnitRate1 <> 0 
			then cast(dbo.OrderBill.TaxPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
		else dbo.OrderBill.TaxPrice end,
	DiscountPrice = case when dbo.OrderBill.isUnit2 =1 AND dbo.ptype.UnitRate1 <> 0 
			then cast(dbo.OrderBill.DiscountPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
		else dbo.OrderBill.DiscountPrice end,
	OrderBill.TaxTotal,
	BigQty =
		CASE WHEN dbo.ptype.UnitRate1 = 0 THEN
			OrderBill.Qty
		ELSE CAST(OrderBill.Qty/dbo.ptype.UnitRate1 AS  NUMERIC(24, 10) ) END,
	OrderBill.total,
	ReachQty = case when dbo.OrderBill.isUnit2 =1 
		then case when dbo.ptype.UnitRate1 <> 0 
			then cast(dbo.OrderBill.ReachQty/dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
			else dbo.OrderBill.ReachQty end 
		else dbo.OrderBill.ReachQty end,
	OrderBill.PassQty, 
	OrderBill.SaleTotal,
	OrderBill.Ktypeid,
	OrderBill.frombillnumberid,
	OrderBill.frombillid,
	OrderBill.RequestBillNumberID,
	OrderBill.RequestBillID,
	ptype.typeid as ptypeid,
	ptype.UserCode,
	ptype.FullName,
	ptype.EntryCode,
	ptype.Standard,
	ptype.Type,
	ptype.Area,
	ptype.Unit1,
	ptype.Unit2,
	ptype.UnitRate1,
	ptype.UnitRate2,
	ptype.IfSerial,
	ptype.serialcount,
	ptype.validdays,
	ptype.usefullifeday,
	OrderBill.comment,
	Stock.UserCode AS KUserCode,
	Stock.FullName AS KFullName,
	CustomerCode = (SELECT UserCode FROM PuserCode WHERE PtypeId = OrderBill.PtypeId AND BtypeId = OrderIndex.BtypeId),
	IsUnit2 = CASE WHEN OrderBill.IsUnit2 = 1 AND ptype.UnitRate1 <> 0 THEN OrderBill.IsUnit2
				ELSE CAST(0 AS bit) END,
	accountqty=(select  isnull(SUM(qty),0) from GoodsStocks where OrderBill.ptypeid=ptypeid AND OrderBill.ktypeid=ktypeid) 
FROM OrderIndex 
    LEFT JOIN
      btype ON OrderIndex.btypeid = btype.typeId     
    INNER JOIN
      OrderBill ON OrderIndex.billNumberId = OrderBill.billNumberID 
    INNER JOIN
      ptype ON OrderBill.ptypeid = ptype.typeId
    LEFT JOIN
      Stock ON OrderBill.KtypeId=Stock.typeId
   
WHERE (OrderIndex.checked = 0)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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





CREATE             VIEW dbo.vWeb_OrderBillFromBill
AS
SELECT	OrderIndex.billNumberId,
	btype.FullName AS fhdw,
	OrderBill.OrderID,
	qty = dbo.OrderBill.Qty,
	Price = case when dbo.OrderBill.isUnit2 =1 AND dbo.ptype.UnitRate1 <> 0 
			then cast(dbo.OrderBill.Price * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
		else dbo.OrderBill.Price end,
    OrderBill.Discount,
	OrderIndex.Tax,
	TaxPrice = case when dbo.OrderBill.isUnit2 =1 AND dbo.ptype.UnitRate1 <> 0 
			then cast(dbo.OrderBill.TaxPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
		else dbo.OrderBill.TaxPrice end,
	DiscountPrice = case when dbo.OrderBill.isUnit2 =1 AND dbo.ptype.UnitRate1 <> 0 
			then cast(dbo.OrderBill.DiscountPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
		else dbo.OrderBill.DiscountPrice end,
	OrderBill.TaxTotal,
	BigQty =
		CASE WHEN dbo.ptype.UnitRate1 = 0 THEN
			OrderBill.Qty
		ELSE CAST(OrderBill.Qty/dbo.ptype.UnitRate1 AS  NUMERIC(24, 10) ) END,
	OrderBill.total,
	ReachQty = dbo.OrderBill.ReachQty,
	OrderBill.PassQty, 
	ptype.typeid as ptypeid,
	ptype.UserCode,
	ptype.FullName,
	ptype.EntryCode,
	ptype.Standard,
	ptype.Type,
	ptype.Area,
	ptype.Unit1,
	ptype.Unit2,
	ptype.UnitRate1,
	ptype.UnitRate2,
	ptype.IfSerial,
	ptype.serialcount,
	ptype.validdays,
	OrderBill.comment,
	CustomerCode = (SELECT UserCode FROM PuserCode WHERE PtypeId = OrderBill.PtypeId AND BtypeId = OrderIndex.BtypeId),
	IsUnit2 = CASE WHEN OrderBill.IsUnit2 = 1 AND ptype.UnitRate1 <> 0 THEN OrderBill.IsUnit2
				ELSE CAST(0 AS bit) END
FROM OrderIndex 
    LEFT JOIN
      btype ON OrderIndex.btypeid = btype.typeId 
    INNER JOIN
      OrderBill ON OrderIndex.billNumberId = OrderBill.billNumberID 
    INNER JOIN
      ptype ON OrderBill.ptypeid = ptype.typeId
WHERE (OrderIndex.checked = 0)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














/*
	修改作者：谢吉康
	修改日期：2003-07-21
	修改原因：格式化该视图
*/

CREATE              VIEW dbo.vWeb_OrderBillIndex
AS
SELECT	
		OrderIndex.billNumberId,
		ISNULL(btype.FullName,'') AS BName, 
		OrderIndex.BillDate, 
      	OrderIndex.Billcode, 
		OrderIndex.totalmoney, 
		OrderIndex.totalqty, 
      	OrderIndex.comment, 
		OrderIndex.IfAudit,
		ISNULL(employee.FullName,'') AS EName1, 
		btype.PostCode, 
      	btype.TelAndAddress, 
		OrderIndex.ReachDate, 
		OrderIndex.WayMode, 
      	CASE OrderIndex.BillStatus 
			WHEN 0 THEN '新增' 
			WHEN 1 THEN '审批中' 
			WHEN 2 THEN '已发货' 	
			WHEN 3 THEN '中止执行' 
		END AS BillStatus, 
      	ISNULL(Stock.FullName,'') AS KName,
		OrderIndex.btypeid,
		OrderIndex.etypeid,
		OrderIndex.ktypeid,
		OrderIndex.dtypeid,
		OrderIndex.Tax,
		btype.usercode AS busercode,
		CASE ISNULL(btype.price,'0') WHEN '0' THEN '1' ELSE btype.price END AS saleprice,
		CASE ISNULL(btype.buyprice,'0') WHEN '0' THEN '1' ELSE btype.buyprice END AS buyprice,
		employee.usercode AS eusercode,
		stock.usercode AS kusercode,
		department.usercode AS dusercode,
		ISNULL(department.fullname,'') AS DName,
		OrderIndex.billtype,
		ISNULL(OrderIndex.etypeid2,'') AS EName2,
		OrderIndex.explain,
		orderindex.WayBillCode,
		orderindex.GoodsNumber,
		orderindex.PackWay,
		orderindex.TEL,
		OrderIndex.IsFinished,
		OrderIndex.OrderState,
		OrderBill.Qty,
		OrderBill.ReachQty,
		ISNULL(BType.ARlimitTime,0) AS ARLimitTime,
		ISNULL(BType.PaymentLTime,0) AS PaymentLTime,
		AuditingBill.BillDetail AS BillDetail,
		OrderIndex.stypeid,
		ISNULL(SType.fullname,'') AS SName
FROM 	OrderIndex 
		LEFT JOIN btype ON OrderIndex.btypeid = btype.typeId 
		LEFT JOIN employee ON OrderIndex.etypeid = employee.typeId
     	LEFT JOIN Stock ON OrderIndex.ktypeid = Stock.typeId 
		LEFT JOIN department ON OrderIndex.dtypeid = department.typeId   
		LEFT JOIN SType ON OrderIndex.STypeID=stype.TypeId   
		INNER JOIN (
						SELECT 	
								BillNumberID,
								sum(OrderBill.Qty) as Qty,
								sum(OrderBill.ReachQty) as ReachQty 
						FROM 	OrderBill 						
						GROUP BY BillNumberID
					) 
        OrderBill ON (OrderIndex.billNumberID=OrderBill.billNumberID)
LEFT  JOIN AuditingBill ON (orderIndex.billNumberID = AuditingBill.billNumberID AND AuditingBill.BillIndexType = 0)
WHERE ( OrderIndex.checked = 0 AND BillOver = 0 )



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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















CREATE          VIEW dbo.vWeb_OrderBillIndex_New
AS
SELECT	
		OrderIndex.billNumberId,
		BName = (SELECT ISNULL(FullName,'') FROM BType WHERE TypeId = OrderIndex.BTypeId), 
		OrderIndex.BillDate, 
      	OrderIndex.Billcode, 
		OrderIndex.totalmoney, 
		OrderIndex.totalqty, 
      	OrderIndex.comment, 
		OrderIndex.IfAudit,
		ISNULL(employee.FullName,'') AS EName1, 
		PostCode = (SELECT PostCode FROM BType WHERE TypeId = OrderIndex.BTypeId), 
      	TelAndAddress = (SELECT TelAndAddress FROM BType WHERE TypeId = OrderIndex.BTypeId), 
		OrderIndex.ReachDate, 
		OrderIndex.WayMode, 
      	CASE OrderIndex.BillStatus 
			WHEN 0 THEN '新增' 
			WHEN 1 THEN '审批中' 
			WHEN 2 THEN '已发货' 	
			WHEN 3 THEN '中止执行' 
		END AS BillStatus, 
      	ISNULL(Stock.FullName,'') AS KName,
		OrderIndex.btypeid,
		OrderIndex.etypeid,
		OrderIndex.ktypeid,
		busercode = (SELECT usercode FROM BType WHERE TypeId = OrderIndex.BTypeId),
		employee.usercode AS eusercode,
		stock.usercode AS kusercode,
		department.usercode AS dusercode,
		ISNULL(department.fullname,'') AS DName,
		OrderIndex.billtype,
		ISNULL(OrderIndex.etypeid2,'') AS EName2,
		OrderIndex.explain,
		orderindex.WayBillCode,
		orderindex.GoodsNumber,
		orderindex.PackWay,
		orderindex.TEL,
		OrderIndex.IsFinished,
		OrderBill.Qty,
		OrderBill.ReachQty,
		OrderIndex.OrderState,
		ARLimitTime = (SELECT ISNULL(BType.ARlimitTime,0) FROM BType WHERE TypeId = OrderIndex.BTypeId)
FROM 	OrderIndex 
		--INNER JOIN btype ON OrderIndex.btypeid = btype.typeId 
		INNER JOIN employee ON OrderIndex.etypeid = employee.typeId
     	INNER JOIN Stock ON OrderIndex.ktypeid = Stock.typeId
		LEFT JOIN department ON OrderIndex.dtypeid = department.typeId
		INNER JOIN (
						SELECT 	
								BillNumberID,
								sum(OrderBill.Qty) as Qty,
								sum(OrderBill.ReachQty) as ReachQty 
						FROM 	OrderBill 
						WHERE	BillNumberId NOT IN 
								(
									SELECT 	A.BillNumberId
									FROM 	OrderIndex O,
											AuditingBill A
									WHERE	O.BillNumberId = A.BillNumberId
											AND A.BillIndexType=0
								)
						GROUP BY BillNumberID
					) 
        OrderBill ON (OrderIndex.billNumberID=OrderBill.billNumberID)
WHERE (OrderIndex.checked = 0 AND OrderIndex.BillOver = 0 )















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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














CREATE          VIEW dbo.vWeb_OrderBillIndex_New_Xjkang
AS
SELECT	OrderIndex.billNumberId,
		BName = (select ISNULL(fullname,'') from btype where typeid = orderindex.btypeid),
		OrderIndex.BillDate, 
      	OrderIndex.Billcode, 
		OrderIndex.totalmoney, 
		OrderIndex.totalqty, 
      	OrderIndex.comment, 
		OrderIndex.IfAudit,
		ISNULL(employee.FullName,'') AS EName1, 
		PostCode = (select PostCode from btype where typeid = orderindex.btypeid),      	
		TelAndAddress = (select TelAndAddress from btype where typeid = orderindex.btypeid),
		OrderIndex.ReachDate, 
		OrderIndex.WayMode, 
      	CASE OrderIndex.BillStatus 
			WHEN 0 THEN '新增' 
			WHEN 1 THEN '审批中' 
			WHEN 2 THEN '已发货' 	
			WHEN 3 THEN '中止执行' 
		END AS BillStatus, 
      	ISNULL(Stock.FullName,'') AS KName,
		OrderIndex.btypeid,
		OrderIndex.etypeid,
		OrderIndex.ktypeid,		
		busercode = (select usercode from btype where typeid = orderindex.btypeid),
		employee.usercode AS eusercode,
		stock.usercode AS kusercode,
		department.usercode AS dusercode,
		ISNULL(department.fullname,'') AS DName,
		OrderIndex.billtype,
		ISNULL(OrderIndex.etypeid2,'') AS EName2,
		OrderIndex.explain,
		orderindex.WayBillCode,
		orderindex.GoodsNumber,
		orderindex.PackWay,
		orderindex.TEL,
		OrderIndex.IsFinished,
		OrderBill.Qty,
		OrderBill.ReachQty,
		OrderIndex.OrderState,
		ARLimitTime = (select ISNULL(BType.ARlimitTime,0) from btype where typeid = orderindex.btypeid)
FROM 	OrderIndex 
		INNER JOIN employee ON OrderIndex.etypeid = employee.typeId
     	INNER JOIN Stock ON OrderIndex.ktypeid = Stock.typeId
		LEFT JOIN department ON OrderIndex.dtypeid = department.typeId
		INNER JOIN (
						SELECT 	
								BillNumberID,
								sum(OrderBill.Qty) as Qty,
								sum(OrderBill.ReachQty) as ReachQty 
						FROM 	OrderBill 
						WHERE	BillNumberId NOT IN 
								(
									SELECT 	A.BillNumberId
									FROM 	OrderIndex O,
											AuditingBill A
									WHERE	O.BillNumberId = A.BillNumberId
											AND A.BillIndexType=0
								)
						GROUP BY BillNumberID
					) 
        OrderBill ON (OrderIndex.billNumberID=OrderBill.billNumberID)
WHERE (OrderIndex.checked = 0 AND OrderIndex.BillOver = 0 )














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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














/****** Object:  View dbo.vWeb_OrderBillIndex    Script Date: 2002-6-20 10:14:43 ******/
/*
	修改作者：谢吉康
	修改日期：2003-07-21
	修改原因：格式化该视图
*/
CREATE                 VIEW dbo.vWeb_OrderBillIndex_NoBillStop
AS
SELECT	
		OrderIndex.billNumberId,
		btype.FullName AS BName, 
		OrderIndex.BillDate, 
      	OrderIndex.Billcode, 
		OrderIndex.totalmoney, 
		OrderIndex.totalqty, 
      	OrderIndex.comment, 
		OrderIndex.IfAudit,
		employee.FullName AS EName1, 
		btype.PostCode, 
      	btype.TelAndAddress, 
		OrderIndex.ReachDate, 
		OrderIndex.WayMode, 
      	CASE OrderIndex.BillStatus 
			WHEN 0 THEN '新增' 
			WHEN 1 THEN '审批中' 
			WHEN 2 THEN '已发货' 	
			WHEN 3 THEN '中止执行' 
		END AS BillStatus, 
      	Stock.FullName AS KName,
		OrderIndex.btypeid,
		OrderIndex.etypeid,
		OrderIndex.ktypeid,
		OrderIndex.dtypeid,
		OrderIndex.Tax,
		btype.usercode AS busercode,
		CASE ISNULL(btype.price,'0') WHEN '0' THEN '1' ELSE btype.price END AS saleprice,
		CASE ISNULL(btype.buyprice,'0') WHEN '0' THEN '1' ELSE btype.buyprice END AS buyprice,
		employee.usercode AS eusercode,
		stock.usercode AS kusercode,
		department.usercode AS dusercode,
		department.fullname AS DName,
		(select fullname from employee where typeid=orderindex.checke) AS checkeman,
		OrderIndex.billtype,
		OrderIndex.etypeid2 AS EName2,
		OrderIndex.explain,
		orderindex.WayBillCode,
		orderindex.GoodsNumber,
		orderindex.PackWay,
		orderindex.TEL,
		OrderBill.Qty,
		OrderBill.ReachQty,
                           OrderIndex.OrderState,
		ISNULL(BType.ARlimitTime,0) AS ARLimitTime,
		ISNULL(BType.PaymentLTime,0) AS PaymentLTime,
		AuditingBill.BillDetail AS BillDetail,
		OrderIndex.stypeid,
		ISNULL(SType.fullname,'') AS SName,
		OrderIndex.CustomerTotal,
		orderindex.frombillnumberid
FROM 	OrderIndex 
		LEFT JOIN btype ON OrderIndex.btypeid = btype.typeId 
		left JOIN employee ON OrderIndex.etypeid = employee.typeId
     	left JOIN Stock ON OrderIndex.ktypeid = Stock.typeId 
		LEFT JOIN department ON OrderIndex.dtypeid = department.typeId   
		LEFT JOIN SType ON OrderIndex.STypeID=stype.TypeId      
		INNER JOIN (
						SELECT 	
								BillNumberID,
								sum(OrderBill.Qty) as Qty,
								sum(OrderBill.ReachQty) as ReachQty 
						FROM 	OrderBill 						
						GROUP BY BillNumberID
					) 
        OrderBill ON (OrderIndex.billNumberID=OrderBill.billNumberID)
LEFT  JOIN AuditingBill ON ( orderIndex.billNumberID = AuditingBill.billNumberID AND AuditingBill.BillindexType=0)
WHERE ( OrderIndex.checked = 0 )
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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











/****** Object:  View dbo.vWeb_OrderBillIndex    Script Date: 2002-6-20 10:14:43 ******/
/*
	修改作者：谢吉康
	修改日期：2003-07-21
	修改原因：格式化该视图
*/

CREATE      VIEW dbo.vWeb_OrderBillIndexHavingAuditing
AS
SELECT	OrderIndex.billNumberId,
		ISNULL(btype.FullName,'') AS BName, 
		OrderIndex.BillDate, 
      	OrderIndex.Billcode, 
		OrderIndex.totalmoney, 
		OrderIndex.totalqty,
		OrderIndex.checke, 
      	OrderIndex.comment, 
		ISNULL(employee.FullName,'') AS EName1, 
		btype.PostCode, 
      	btype.TelAndAddress, 
		OrderIndex.ReachDate, 
		OrderIndex.WayMode, 
      	CASE OrderIndex.BillStatus 
			WHEN 0 THEN '新增' 
			WHEN 1 THEN '审批中' 
			WHEN 2 THEN '已发货' 	
			WHEN 3 THEN '中止执行' 
		END AS BillStatus, 
      	ISNULL(Stock.FullName,'') AS KName,
		OrderIndex.btypeid,
		OrderIndex.etypeid,
		OrderIndex.ktypeid,
		btype.usercode AS busercode,
		employee.usercode AS eusercode,
		stock.usercode AS kusercode,
		OrderIndex.billtype,
		ISNULL(OrderIndex.etypeid2,'') AS EName2,
		OrderIndex.explain,
		orderindex.WayBillCode,
		orderindex.GoodsNumber,
		orderindex.PackWay,
		orderindex.TEL,
		OrderIndex.IsFinished,
                           OrderIndex.OrderState,
		OrderBill.Qty,
		OrderBill.ReachQty,
		AuditingBill.IfAudit
FROM 	OrderIndex 
		INNER JOIN AuditingBill ON OrderIndex.BillNumberID = AuditingBill.BillNumberID
		INNER JOIN AuditingFlowSet ON AuditingFlowSet.AuditingID = AuditingBill.AuditingID
		LEFT JOIN btype ON OrderIndex.btypeid = btype.typeId 
		INNER JOIN employee ON OrderIndex.etypeid = employee.typeId
     	INNER JOIN Stock ON OrderIndex.ktypeid = Stock.typeId      
		INNER JOIN (
						SELECT 	
								BillNumberID,
								sum(OrderBill.Qty) as Qty,
								sum(OrderBill.ReachQty) as ReachQty 
						FROM 	OrderBill 
						GROUP BY BillNumberID
					) 
        OrderBill ON (OrderIndex.billNumberID=OrderBill.billNumberID)
WHERE (OrderIndex.checked = 0 AND OrderIndex.BillOver = 0 AND AuditingBill.BillIndexType=0)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_Pay    Script Date: 2002-6-20 10:14:43 ******/

CREATE VIEW dbo.vWeb_Pay
--@Encode$--
AS
SELECT dbo.PayBill.BillNumberId, dbo.PayBill.AtypeId, dbo.PayBill.total, 
      dbo.PayBill.Comment, dbo.atype.FullName, dbo.atype.UserCode,dbo.PayBill.ID
FROM dbo.atype INNER JOIN
      dbo.PayBill ON dbo.atype.typeId = dbo.PayBill.AtypeId












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





CREATE   VIEW dbo.vWeb_PriceProtectBill
AS
	SELECT     	                
		distinct a.BillNumberID,
		b.typeid,
                b.UserCode,
                b.FullName,
		a.Oldtotal,
		a.Serial,
		a.OldPrice,
		a.NewPrice,
		a.Qty,
		a.Total,
		a.Total AS ntotal,
		a.Comment,
		a.comment AS Base,
		a.itemid,
		a.IsCombined,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			      ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,
		a.goodsnumber,	
		a.[ID],
		CAST(b.IfUseGoodsNum AS INT) AS IfUseGoodsNum
	FROM dbo.PriceProtectBill a
                JOIN Ptype b on (a.ptypeid=b.typeid)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE id = OBJECT_ID(N'[dbo].[vWeb_RetailCombinationBill]') and OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW [dbo].[vWeb_RetailCombinationBill]
GO
CREATE  VIEW [dbo].[vWeb_RetailCombinationBill]

AS
--2017-03-20 梁晰 增加参数KtypeID
--2017-07-19 刘飞 区别上下表体I:上表体，O:下表体

SELECT [BillNumberId]
      ,[PtypeId]
      ,[Qty]
      ,[SalePrice]
      ,[discount]
      ,[DiscountPrice]
      ,[costprice]
      ,[jobnumber]
      ,[goodsno]
      ,[total]
      ,[OutFactoryDate]
      ,[TaxPrice]
      ,[TaxTotal]
      ,[comment]
      ,[OrderID]
      ,[TeamNo]
      ,[ID]
      ,[TeamNO1]
      ,[IsUnit2]
      ,[Serial]
      ,[InputCostPrice]
      ,[GoodsOrder]
      ,[GoodsNumber]
      ,[ProduceDate]
      ,[ValidDate]
      ,[GoodsBTypeID]
      ,[GoodsCostPrice]
      ,[GoodsCostTotal]
      ,[HandZeroCost]
      ,[BackQTY]
      ,[SaleTotal]
      ,[Tax]
      ,[Stypeid]
      ,[TaxMoney]
      ,[NSalePrice]
      ,[NSaleTotal]
      ,[NDiscountPrice]
      ,[NTotal]
      ,[NTaxPrice]
      ,[NTaxTotal]
      ,[NTaxMoney]
      ,[UnitID]
      ,[NUnitID]
      ,[NQty]
      ,[UnitRate]
      ,[NUnitMsg]
      ,[MUnitID]
      ,[MQty]
      ,[MUnitRate]
      ,[MUnitMsg]
      ,[MSalePrice]
      ,[MDiscountPrice]
      ,[MTaxPrice]
      ,[CurMSalePrice]
      ,[CurMDiscountPrice]
      ,[CurMTaxPrice]
      ,[CargoID]
      ,[ItemID]
      ,[IsCombined]
      ,[InvoiceQty]
      ,[InvoiceMoney]
      ,[NInvoiceMoney]
      ,[IsGift]
      ,[PosId]
      ,[BeforePromoID]
      ,[PriceDetailId]
      ,[PriceRuleId]
      ,[PriceSource]
      ,[ReferPrice]
      ,[PriceStyle]
      ,[PromoType]
      ,[ShowOrder]
      ,[ETypeID]
      ,[iscombination]
      ,[combinationptypeid]
      ,[pindexid]
      ,sharefee
      ,OutFactQty
      ,IsIniFlag
      ,DraftFlag
      ,KTypeID 
      ,'O' AS InOrOut
      ,PromonIds
      ,CouponCode
      ,IsPromotion
      ,IsVipPoint
      ,Reconciliation
  FROM [dbo].[retailBill]
  
UNION ALL

SELECT [BillNumberId]
  ,[PtypeId]
  ,[Qty]
  ,[SalePrice]
  ,[discount]
  ,[DiscountPrice]
  ,-1 AS [costprice]
  ,NULL AS [jobnumber]
  ,NULL AS [goodsno]
  ,[total]
  ,[OutFactoryDate]
  ,[TaxPrice]
  ,[TaxTotal]
  ,[comment]
  ,NULL AS [OrderID]
  ,NULL AS [TeamNo]
  ,[ID]
  ,NULL AS [TeamNO1]
  ,[IsUnit2]
  ,NULL AS [Serial]
  ,NULL AS [InputCostPrice]
  ,NULL AS [GoodsOrder]
  ,NULL AS [GoodsNumber]
  ,NULL AS [ProduceDate]
  ,NULL AS [ValidDate]
  ,NULL AS [GoodsBTypeID]
  ,NULL AS [GoodsCostPrice]
  ,NULL AS [GoodsCostTotal]
  ,NULL AS [HandZeroCost]
  ,[BackQTY]
  ,[SaleTotal]
  ,[Tax]
  ,[Stypeid]
  ,[TaxMoney]
  ,[NSalePrice]
  ,[NSaleTotal]
  ,[NDiscountPrice]
  ,[NTotal]
  ,[NTaxPrice]
  ,[NTaxTotal]
  ,[NTaxMoney]
  ,[UnitID]
  ,[NUnitID]
  ,[NQty]
  ,[UnitRate]
  ,[NUnitMsg]
  ,[MUnitID]
  ,[MQty]
  ,[MUnitRate]
  ,[MUnitMsg]
  ,[MSalePrice]
  ,[MDiscountPrice]
  ,[MTaxPrice]
  ,[CurMSalePrice]
  ,[CurMDiscountPrice]
  ,[CurMTaxPrice]
  ,[CargoID]
  ,[ItemID]
  ,[IsCombined]
  ,[InvoiceQty]
  ,[InvoiceMoney]
  ,[NInvoiceMoney]
  ,[IsGift]
  ,[PosId]
  ,[BeforePromoID]
  ,[PriceDetailId]
  ,[PriceRuleId]
  ,[PriceSource]
  ,NULL AS [ReferPrice]
  ,[PriceStyle]
  ,[PromoType]
  ,NULL AS [ShowOrder]
  ,[ETypeID]
  ,1 AS [iscombination]
  ,NULL AS [combinationptypeid]
  ,[pindexid]
  ,null as sharefee
  ,0 AS OutFactQty
  ,0 AS IsIniFlag
  ,0 AS DraftFlag
  ,'' AS KTypeID
  ,'I' AS InOrOut
  ,PromonIds
  ,CouponCode
  ,IsPromotion
  ,IsVipPoint
  ,'f'
FROM [dbo].[retailCombinationBill]
  
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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











/****** Object:  View dbo.vWeb_SaleBill    Script Date: 2002-6-20 10:14:43 ******/


--得到销售单，销售退货单,进货单,进货退货单明细,零售单
------------2002-7-9加上单位之间换算,价格换算


CREATE  VIEW dbo.vWeb_SaleBill
--@Encode$--
AS
SELECT dbo.ptype.UserCode, dbo.ptype.FullName, dbo.ptype.Unit1, dbo.ptype.Unit2, dbo.ptype.UnitRate1, dbo.ptype.UnitRate2, 
	dbo.PType.EntryCode,
	dbo.PType.Standard,
	dbo.PType.Type,
	dbo.PType.Area,
	dbo.PType.IfSerial,
                  qty = case when dbo.RetailBill.isUnit2 =1 
                                        then  case when  dbo.ptype.UnitRate1<>0 
                                                              then cast(dbo.RetailBill.Qty/dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                              else null end 
                                       else dbo.RetailBill.Qty end,
                 SalePrice = case when  dbo.RetailBill.isUnit2 =1 
                                                    then cast(dbo.RetailBill.SalePrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.RetailBill.SalePrice end,
                 TaxPrice = case when  dbo.RetailBill.isUnit2 =1 
                                                    then cast(dbo.RetailBill.TaxPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.RetailBill.TaxPrice end,

                dbo.RetailBill.TaxTotal,
               dbo.RetailBill.comment, dbo.RetailBill.BillNumberId, dbo.RetailBill.OrderID,dbo.RetailBill.ID,
              dbo.RetailBill.Total,
             dbo.RetailBill.Discount,
                 DiscountPrice = case when  dbo.RetailBill.isUnit2 =1 
                                                    then cast(dbo.RetailBill.DiscountPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.RetailBill.DiscountPrice end,
            dbo.RetailBill.isUnit2,
	dbo.RetailBill.Serial
FROM dbo.retailBill INNER JOIN
      dbo.ptype ON dbo.RetailBill.PtypeId = dbo.ptype.typeId
union all
-------------------

SELECT dbo.ptype.UserCode, dbo.ptype.FullName, dbo.ptype.Unit1, dbo.ptype.Unit2, dbo.ptype.UnitRate1, dbo.ptype.UnitRate2, 
	dbo.PType.EntryCode,
	dbo.PType.Standard,
	dbo.PType.Type,
	dbo.PType.Area,
	dbo.PType.IfSerial,
                  qty = case when dbo.SaleBill.isUnit2 =1 
                                        then  case when  dbo.ptype.UnitRate1<>0 
                                                              then cast(dbo.SaleBill.Qty/dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                              else null end 
                                       else dbo.SaleBill.Qty end,
                 SalePrice = case when  dbo.SaleBill.isUnit2 =1 
                                                    then cast(dbo.SaleBill.SalePrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.SaleBill.SalePrice end,
                 TaxPrice = case when  dbo.SaleBill.isUnit2 =1 
                                                    then cast(dbo.SaleBill.TaxPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.SaleBill.TaxPrice end,
              dbo.SaleBill.TaxTotal,
              dbo.SaleBill.comment, dbo.SaleBill.BillNumberId, dbo.SaleBill.OrderID,dbo.SaleBill.ID,
              dbo.SaleBill.Total,
             dbo.SaleBill.Discount,
              DiscountPrice = case when  dbo.SaleBill.isUnit2 =1 
                                                    then cast(dbo.SaleBill.DiscountPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.SaleBill.DiscountPrice end,
             dbo.SaleBill.isUnit2,
	dbo.SaleBill.Serial
FROM dbo.SaleBill INNER JOIN
      dbo.ptype ON dbo.SaleBill.PtypeId = dbo.ptype.typeId
union all
-------------
SELECT dbo.ptype.UserCode, dbo.ptype.FullName, dbo.ptype.Unit1, dbo.ptype.Unit2, dbo.ptype.UnitRate1, dbo.ptype.UnitRate2, 
	dbo.PType.EntryCode,
	dbo.PType.Standard,
	dbo.PType.Type,
	dbo.PType.Area,
	dbo.PType.IfSerial,
                  qty = case when dbo.SaleBackBill.isUnit2 =1 
                                        then  case when  dbo.ptype.UnitRate1<>0 
                                                              then cast(dbo.SaleBackBill.Qty/dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                              else null end 
                                       else dbo.SaleBackBill.Qty end,
                 SalePrice = case when  dbo.SaleBackBill.isUnit2 =1 
                                                    then cast(dbo.SaleBackBill.SalePrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.SaleBackBill.SalePrice end,
                 TaxPrice = case when  dbo.SaleBackBill.isUnit2 =1 
                                                    then cast(dbo.SaleBackBill.TaxPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.SaleBackBill.TaxPrice end,
                  dbo.SaleBackBill.TaxTotal ,

                dbo.SaleBackBill.comment, dbo.SaleBackBill.BillNumberId,Null,dbo.SaleBackBill.ID,
               dbo.SaleBackBill.Total,
              dbo.SaleBackBill.Discount,
              DiscountPrice = case when  dbo.SaleBackBill.isUnit2 =1 
                                                    then cast(dbo.SaleBackBill.DiscountPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.SaleBackBill.DiscountPrice end,
             dbo.SaleBackBill.isUnit2,
	dbo.SaleBackBill.Serial
FROM dbo.SaleBackBill INNER JOIN
      dbo.ptype ON dbo.SaleBackBill.PtypeId = dbo.ptype.typeId
union all
--------------
SELECT	dbo.PType.UserCode,
	dbo.PType.FullName,
	dbo.PType.Unit1,
	dbo.PType.Unit2,
	dbo.PType.UnitRate1,
	dbo.PType.UnitRate2,
	dbo.PType.EntryCode,
	dbo.PType.Standard,
	dbo.PType.Type,
	dbo.PType.Area,
	dbo.PType.IfSerial,
	Qty = CASE WHEN dbo.BuyBill.isUnit2 =1 
		THEN CASE WHEN dbo.PType.UnitRate1 <> 0 
			THEN CAST(dbo.BuyBill.Qty/dbo.PType.UnitRate1 AS  NUMERIC(24, 10) )
			ELSE null
			END
		ELSE dbo.BuyBill.Qty
		END,
	SalePrice = CASE WHEN dbo.BuyBill.isUnit2 = 1 
		THEN CAST(dbo.BuyBill.SalePrice * dbo.PType.UnitRate1 AS  NUMERIC(24, 10) )
		ELSE dbo.BuyBill.SalePrice
		END,
	TaxPrice = CASE WHEN dbo.BuyBill.isUnit2 = 1 
		THEN cast(dbo.BuyBill.TaxPrice * dbo.PType.UnitRate1 AS  NUMERIC(24, 10) )
		ELSE dbo.BuyBill.TaxPrice
		END,
	dbo.BuyBill.TaxTotal,
	dbo.BuyBill.Comment,
	dbo.BuyBill.BillNumberID,
	dbo.BuyBill.OrderID,
	dbo.BuyBill.ID,
	dbo.BuyBill.Total,
	dbo.BuyBill.Discount,
	DiscountPrice = CASE WHEN dbo.BuyBill.isUnit2 = 1 
		THEN CAST(dbo.BuyBill.DiscountPrice * dbo.PType.UnitRate1 AS  NUMERIC(24, 10) )
		ELSE dbo.BuyBill.DiscountPrice
		END,
	dbo.BuyBill.isUnit2,
	dbo.BuyBill.Serial
FROM	dbo.BuyBill
INNER JOIN dbo.PType
ON dbo.BuyBill.PTypeID = dbo.PType.TypeID
union all
---------
SELECT dbo.ptype.UserCode, dbo.ptype.FullName, dbo.ptype.Unit1, dbo.ptype.Unit2, dbo.ptype.UnitRate1, dbo.ptype.UnitRate2,
	dbo.PType.EntryCode,
	dbo.PType.Standard,
	dbo.PType.Type,
	dbo.PType.Area,
	dbo.PType.IfSerial,
                  qty = case when dbo.BuyBackBill.isUnit2 =1 
                                        then  case when  dbo.ptype.UnitRate1<>0 
                                                              then cast(dbo.BuyBackBill.Qty/dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                              else null end 
                                       else dbo.BuyBackBill.Qty end,
                 SalePrice = case when  dbo.BuyBackBill.isUnit2 =1 
                                                    then cast(dbo.BuyBackBill.SalePrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.BuyBackBill.SalePrice end,
                 TaxPrice = case when  dbo.BuyBackBill.isUnit2 =1 
                                                    then cast(dbo.BuyBackBill.TaxPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.BuyBackBill.TaxPrice end,
                 dbo.BuyBackBill.TaxTotal ,

      dbo.BuyBackBill.comment, dbo.BuyBackBill.BillNumberId, Null,dbo.BuyBackBill.ID,
      dbo.BuyBackBill.Total,
      dbo.BuyBackBill.Discount,
              DiscountPrice = case when  dbo.BuyBackBill.isUnit2 =1 
                                                    then cast(dbo.BuyBackBill.DiscountPrice * dbo.ptype.UnitRate1 as  NUMERIC(24, 10) ) 
                                                    else dbo.BuyBackBill.DiscountPrice end,
     dbo.BuyBackBill.isUnit2,
	dbo.BuyBackBill.Serial
FROM dbo.BuyBackBill INNER JOIN
      dbo.ptype ON dbo.BuyBackBill.PtypeId = dbo.ptype.typeId








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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






/*
	修 改 人：谢吉康
 	修改日期：2003-9-23
	修改原因：成本分析中没有委托结算单
*/
CREATE  VIEW dbo.vWeb_SaleBillIndexConfirmed
--@Encode$--
AS
SELECT 	BillIndex.BillNumberId, 
		BillIndex.BillDate, 
		BillIndex.BillCode, 
		BillIndex.etypeid,
      	BillIndex.Comment, 
		btype.FullName AS shdw, 
		btype.typeId AS shdwID, 
      	employee.FullName AS jsr, 
		BillIndex.totalmoney, 
		BillIndex.totalqty, 
      	BillIndex.tax, 
      	BillIndex.Stypeid,
      	BillIndex.DTypeId,
		Stock.FullName AS StockOut,
		StockIn = (SELECT FullName FROM Stock WHERE TypeId = BillIndex.KTypeId2)
FROM 	BillIndex 
		INNER JOIN 	btype ON BillIndex.DealBTypeID = btype.typeId 
		INNER JOIN  employee ON BillIndex.etypeid = employee.typeId 
		LEFT OUTER JOIN  Stock ON dbo.BillIndex.ktypeid = Stock.typeId
WHERE 	BillIndex.BillType IN( 11,12,45,46,305,141,155,157,160215) 
		AND (BillIndex.ifcheck = 'T') 
		AND (BillIndex.draft = 0) 
		AND (BillIndex.RedWord = 0)




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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












CREATE VIEW dbo.vWeb_SaleBuy_GatheringPay
--@Encode$--
AS
--收款单不显示草稿的结算过程，付款单要显示草稿的结算过程
SELECT dbo.BillIndex.BillDate, dbo.BillIndex.BillCode, dbo.BillIndex.totalinmoney, dbo.BillIndex.NTotalInMoney,
      dbo.CompleteTotal.CompleteTotal, dbo.CompleteTotal.NCompleteTotal,dbo.BillIndex.BillType,CompleteTotal.BillType as jsbilltype ,
      dbo.CompleteTotal.GoodsBillID, dbo.CompleteTotal.MoneyBillID,dbo.CompleteTotal.Draft,dbo.CompleteTotal.GoodsBillDetailID,dbo.BillIndex.ifYearBill,
      dbo.CompleteTotal.BillType as ComBillType
FROM dbo.BillIndex 
INNER JOIN dbo.CompleteTotal ON dbo.BillIndex.BillNumberId = dbo.CompleteTotal.MoneyBillID
WHERE dbo.BillIndex.BillType=4
UNION ALL
SELECT dbo.BillIndex.BillDate, dbo.BillIndex.BillCode, dbo.BillIndex.totalinmoney, dbo.BillIndex.NTotalInMoney, 
      dbo.CompleteTotal.CompleteTotal,dbo.CompleteTotal.NCompleteTotal, dbo.BillIndex.BillType ,CompleteTotal.BillType as jsbilltype ,
      dbo.CompleteTotal.GoodsBillID, dbo.CompleteTotal.MoneyBillID,dbo.CompleteTotal.Draft,dbo.CompleteTotal.GoodsBillDetailID,dbo.BillIndex.ifYearBill,
      dbo.CompleteTotal.BillType as ComBillType
FROM dbo.BillIndex 
INNER JOIN dbo.CompleteTotal ON dbo.BillIndex.BillNumberId = dbo.CompleteTotal.MoneyBillID
WHERE dbo.BillIndex.BillType=66








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_StockCurDisByP    Script Date: 2002-6-20 10:14:43 ******/

CREATE View vWeb_StockCurDisByP 
--@Encode$--
AS 
SELECT S.Fullname AS SFullName, P.FullName AS PFullName, C.PTypeid, C.Ktypeid, 
      C.Qty, C.Total, C.Price
FROM (SELECT PtypeId, KtypeId, SUM(Qty) AS Qty, SUM(Total) AS Total, 
              cast((CASE WHEN SUM(qty) = 0 THEN NULL ELSE SUM(Total) / SUM(Qty) END) 
              AS Money) AS Price
        FROM dbo.GoodsStocks
        GROUP BY PtypeId, KtypeId) C INNER JOIN
      dbo.PType P ON (C.PTypeid = P.Typeid) INNER JOIN
      dbo.Stock S ON (C.KTypeid = S.typeid)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_StockDistributing    Script Date: 2002-6-20 10:14:43 ******/

--last modify date:2001-08-30
CREATE VIEW dbo.vWeb_StockDistributing
--@Encode$--
AS
/*
SELECT [ktypeid] = CASE WHEN IniGoodsStocks.ktypeid IS NULL 
      THEN GoodsStocks.ktypeid ELSE IniGoodsStocks.ktypeid END, 
      [ptypeid] = CASE WHEN IniGoodsStocks.ptypeid IS NULL 
      THEN GoodsStocks.ptypeid ELSE IniGoodsStocks.ptypeid END, 
      [qty] = isnull(GoodsStocks.qty, 0) + isnull(IniGoodsStocks.qty, 0), 
      [total] = isnull(GoodsStocks.total, 0) + isnull(IniGoodsStocks.total, 0)
FROM IniGoodsStocks FULL OUTER JOIN
      GoodsStocks ON IniGoodsStocks.KtypeId = GoodsStocks.KtypeId AND 
      IniGoodsStocks.ptypeid = GoodsStocks.ptypeid
*/
--系统建帐后将期初库存导入导库存里
--系统开帐
select ktypeid,ptypeid,sum(qty) as qty,sum(total) as total,SUM(price) as price from goodsstocks group by ktypeid,ptypeid











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_StockDistributing_1    Script Date: 2002-6-20 10:14:43 ******/

CREATE VIEW dbo.vWeb_StockDistributing_1
--@Encode$--
AS
SELECT	vWeb_StockDistributing.ktypeid, 
		vWeb_StockDistributing.ptypeid, 
		SUM(vWeb_StockDistributing.qty) AS qty,
		SUM(vWeb_StockDistributing.price) AS price,
		SUM(vWeb_StockDistributing.total) AS total
FROM	ptype INNER JOIN vWeb_StockDistributing ON ptype.typeId = vWeb_StockDistributing.ptypeid 
INNER JOIN Stock ON vWeb_StockDistributing.ktypeid = Stock.typeId
WHERE	(ptype.sonnum = 0)  
		AND (Stock.sonnum = 0)		
GROUP BY vWeb_StockDistributing.ktypeid, vWeb_StockDistributing.ptypeid











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










/****** Object:  View dbo.vWeb_StockIniDisByP    Script Date: 2002-6-20 10:14:43 ******/

CREATE View vWeb_StockIniDisByP 
--@Encode$--
AS 
SELECT S.Fullname AS SFullName, P.FullName AS PFullName, C.PTypeid, C.Ktypeid, 
      C.Qty, C.Total, C.Price
FROM (SELECT PtypeId, KtypeId, SUM(Qty) AS Qty, SUM(Total) AS Total, 
              cast((CASE WHEN SUM(qty) = 0 THEN NULL ELSE SUM(Total) / SUM(Qty) END) 
              AS Money) AS Price
        FROM dbo.IniGoodsStocks
        GROUP BY PtypeId, KtypeId) C INNER JOIN
      dbo.PType P ON (C.PTypeid = P.Typeid) INNER JOIN
      dbo.Stock S ON (C.KTypeid = S.typeid)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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












/****** Object:  View dbo.vWeb_WLDZ    Script Date: 2002-6-20 10:14:43 ******/
--------往来对帐格式二
--------author:王跃
---------status:ok
--修改人：冯波
--修改日期：2004-3-16
--修改原因：在应收查询中加入维修单，#1

--修改人：冯波
--修改日期：2004-3-16
--修改原因：将销售换货单的入库从负的应收增加改为正的应收减少，#2
CREATE           view vWeb_WLDZ
(zy,fullName,ArAdd,ArReduce ,BillDate,BillCode,etypeid,TeamNo,Id,Btypeid,BillNumberID,BillType, TeamNo1,RedWord)
--@Encode$--
as
SELECT 
     '销售:' + dbo.ptype.FullName + ' ' + cast(dbo.SaleBill.Qty as varchar(20)) + '*' + CAST(dbo.SaleBill.TaxPrice AS varchar(20)),
      dbo.ptype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.SaleBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.SaleBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.SaleBill.TeamNo,
      dbo.SaleBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.SaleBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.SaleBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.SaleBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.SaleBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 11)
union all

SELECT 
      '进货:' + dbo.ptype.FullName + ' ' + CAST(dbo.BuyBill.Qty AS varchar(20)) + '*' + CAST(dbo.BuyBill.TaxPrice AS varchar(20)), 
      dbo.ptype.FullName,       
      case when dbo.vWeb_ARAPIndex.RedWord=2 then  dbo.BuyBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.BuyBill.TaxTotal else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.BuyBill.TeamNo,
      dbo.BuyBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.BuyBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.BuyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.BuyBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 34)
union all
SELECT ' 付款:'+dbo.atype.FullName,
      null,
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 34 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all

SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 11 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
union all
SELECT  

      '退货:' + dbo.ptype.FullName + ' ' + CAST(dbo.BuyBackBill.Qty AS varchar(10)) + '*' + CAST(dbo.BuyBackBill.TaxPrice AS varchar(20)), 
      dbo.ptype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.BuyBackBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.BuyBackBill.TaxTotal else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.BuyBackBill.TeamNo, 
      dbo.BuyBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.BuyBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.BuyBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.BuyBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 6)
union all
SELECT 
     '零售:' + dbo.ptype.FullName + ' ' + cast(dbo.RetailBill.Qty as varchar(20)) + '*' + CAST(dbo.RetailBill.TaxPrice AS varchar(20)),
      dbo.ptype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.RetailBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.RetailBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.RetailBill.TeamNo,
      dbo.RetailBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.RetailBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.RetailBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.RetailBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.RetailBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)
union all
SELECT 
       '收款:'+dbo.atype.FullName,
       null,
       case when dbo.vWeb_ARAPIndex.RedWord =2 then  dbo.vWeb_ARAPIndex.totalinmoney else null end,
       case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney else null end,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid,
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 6 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 305 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(dbo.saleBackBill.Qty AS varchar(10)) + '*' + CAST(dbo.saleBackBill.TaxPrice AS varchar(20)), 
      dbo.ptype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then dbo.saleBackBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.saleBackBill.TaxTotal else null end,

      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.saleBackBill.TeamNo, 
      dbo.saleBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.saleBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.saleBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.saleBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.saleBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)

union all
SELECT 
     '付款:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.PayBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.PayBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PayBill.TeamNo, 
      dbo.PayBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PayBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PayBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PayBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)

union all
SELECT 
     '返利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.Advantage.total else null end,       
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.Advantage.total else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 148)

union all
SELECT 
     '价保执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.PriceProtectBill.total-dbo.vWeb_ARAPIndex.TotalInMoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.PriceProtectBill.total-dbo.vWeb_ARAPIndex.TotalInMoney else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 149)

union all
SELECT 
     '委托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.CommissionBill.TaxTotal else null end,             
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.CommissionBill.TaxTotal else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 141)

union all
SELECT 
     '受托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.CommissionBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.CommissionBill.TaxTotal else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 

      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 145)

union all
SELECT 
     '获利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.CommissionBill.total else null end,             
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.CommissionBill.total else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 150)

union all
SELECT '付款:'+dbo.atype.FullName,
       null,
       case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.totalinmoney else null end,
       case when dbo.vWeb_ARAPIndex.RedWord=2  then dbo.vWeb_ARAPIndex.totalinmoney else null end,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 45 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
--应收减少，应付增加
SELECT 
      dbo.AdDebtBill.Comment,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.AdDebtBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId,  
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType in(115,128))

union all
SELECT '收款:' + dbo.btype.FullName,
      dbo.btype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.gatheringBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.gatheringBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo,
      dbo.gatheringBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)

--应收增加，应付减少
union all
SELECT 
      dbo.AdDebtBill.Comment,dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.AdDebtBill.total else null end,

      case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType in(116,129))
--36费用单93其他收入单
union all
SELECT
             '费用单：'+dbo.MoneyBill.Comment, 
             dbo.atype.FullName, 
            case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.MoneyBill.total else null end, 
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.MoneyBill.total else null end, 
            dbo.vWeb_ARAPIndex.BillDate,
            dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
            dbo.MoneyBill.TeamNo, 
            dbo.MoneyBill.ID, 
            dbo.vWeb_ARAPIndex.btypeid, 
            dbo.vWeb_ARAPIndex.BillNumberId, 
           dbo.vWeb_ARAPIndex.BillType, 
           dbo.MoneyBill.TeamNo1,
           dbo.vWeb_ARAPIndex.RedWord
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType =36)

union all
SELECT 
     ' 付款:'+dbo.atype.FullName,
     null,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 36 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
SELECT 
       dbo.MoneyBill.Comment, 
       dbo.atype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,

      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo,
      dbo.MoneyBill.ID,
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType, 
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType =93)
union all
SELECT 
     ' 收款:'+dbo.atype.FullName,
     null,
     case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 93 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
union all
SELECT 
     '固定资产购买:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 84)
union all
SELECT 
     '固定资产变卖:' + dbo.btype.FullName,
      dbo.btype.FullName,
	  case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total-dbo.vWeb_ARAPIndex.TotalInMoney else null end,
	  case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 85)

union all
SELECT 
	 Case dbo.GoodsExchangeBill.InOrOut
		when 'O' then
     		'销售换货出库:' + dbo.ptype.FullName + ' ' + cast(dbo.GoodsExchangeBill.Qty as varchar(20)) + '*' + CAST(dbo.GoodsExchangeBill.TaxPrice AS varchar(20))
		when 'I' then
     		'销售换货入库:' + dbo.ptype.FullName + ' ' + cast(dbo.GoodsExchangeBill.Qty as varchar(20)) + '*' + CAST(dbo.GoodsExchangeBill.TaxPrice AS varchar(20))
	  end,

      dbo.ptype.FullName, 
      /*
      case dbo.GoodsExchangeBill.InOrOut
		when 'O' then
      		case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
		when 'I' then
      		case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then -cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
	  end,
      case dbo.GoodsExchangeBill.InOrOut
        when 'O' then
      		case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
		when 'I' then
      		case when dbo.vWeb_ARAPIndex.RedWord=2 then -cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
            case when dbo.vWeb_ARAPIndex.RedWord=2 then -cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
	  end,
      */
      --#2，冯波2004-3-16修改开始（上面注释掉的那段是修改前的，主要作了这样的修改：对于销售换货单，正常出库作为应收增加，正常入库作为应收减少，红字出库作为应收减少，红字入库作为应收增加）
	  case dbo.GoodsExchangeBill.InOrOut
          when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
      end,
      
	  case dbo.GoodsExchangeBill.InOrOut
          when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.GoodsExchangeBill.TaxTotal as  NUMERIC(24, 10) ) else null end
		
      end,
      --#2修改结束
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.GoodsExchangeBill.TeamNo,
      dbo.GoodsExchangeBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.GoodsExchangeBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.GoodsExchangeBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.GoodsExchangeBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.GoodsExchangeBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 155)

union all
SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 155 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)


--#1,冯波，2004-3-13修改开始，在应收查询中加入维修单
union all
--商品维修受理单      157         收款
SELECT 
     '商品维修单:' + dbo.btype.FullName,
      dbo.btype.FullName,
	  case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo, 
      --dbo.vWeb_ARAPIndex.ID, 
      null,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      --dbo.vWeb_ARAPIndex.TeamNo1,
      null,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId 
WHERE (dbo.vWeb_ARAPIndex.BillType = 157)


union all

SELECT ' 收款:'+dbo.atype.FullName,
      null,      
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 157 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
--#1，修改结束













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



















/****** Object:  View dbo.vWeb_WLDZ_GYS    Script Date: 2002-6-20 10:14:43 ******/
--供应商应付往来格式二
CREATE          view vWeb_WLDZ_GYS(zy,fullName,ApAdd,ApReduce,BillDate,BillCode,etypeid,TeamNo,Id,Btypeid,BillNumberID,BillType, TeamNo1,RedWord)
--@Encode$--
as
--销售			    11			收款
SELECT 
     '销售:' + dbo.ptype.FullName + ' ' + cast(dbo.SaleBill.Qty as varchar(20)) + '*' + CAST(dbo.SaleBill.TaxPrice AS varchar(20)),
      dbo.ptype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.SaleBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.SaleBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.SaleBill.TeamNo,
      dbo.SaleBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.SaleBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.SaleBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.SaleBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.SaleBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 11)
union all

SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 11 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)


--进货			    34			付款
union all
SELECT 
      '进货:' + dbo.ptype.FullName + ' ' + CAST(dbo.BuyBill.Qty AS varchar(20)) + '*' + CAST(dbo.BuyBill.TaxPrice AS varchar(20)), 
      dbo.ptype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.BuyBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then  dbo.BuyBill.TaxTotal else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.BuyBill.TeamNo,
      dbo.BuyBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.BuyBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.BuyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.BuyBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 34)
union all
SELECT ' 付款:'+dbo.atype.FullName,
      null,
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 34 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)


--采购退货			6			收款
union all
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(dbo.BuyBackBill.Qty AS varchar(10)) + '*' + CAST(dbo.BuyBackBill.TaxPrice AS varchar(20)), 
      dbo.ptype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.BuyBackBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.BuyBackBill.TaxTotal else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.BuyBackBill.TeamNo, 
      dbo.BuyBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.BuyBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.BuyBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.BuyBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 6)

union all
SELECT 
       '收款:'+dbo.atype.FullName,
       null,
       case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney else null end,
       case when dbo.vWeb_ARAPIndex.RedWord =2 then  dbo.vWeb_ARAPIndex.totalinmoney else null end,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid,
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 6 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

--零售			    305			收款
union all
SELECT 
     '零售:' + dbo.ptype.FullName + ' ' + cast(dbo.RetailBill.Qty as varchar(20)) + '*' + CAST(dbo.RetailBill.TaxPrice AS varchar(20)),
      dbo.ptype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.RetailBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.RetailBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.RetailBill.TeamNo,
      dbo.RetailBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.RetailBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.RetailBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.RetailBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.RetailBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)

union all
SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 305 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
--4  ？？
SELECT 
      '收款:' + dbo.btype.FullName,
      dbo.btype.FullName,  
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.gatheringBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.gatheringBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo, 
      dbo.gatheringBill.ID, 

      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)



--销售退货			45			付款
union all
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(dbo.saleBackBill.Qty AS varchar(10)) + '*' + CAST(dbo.saleBackBill.TaxPrice AS varchar(20)), 
      dbo.ptype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.saleBackBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then dbo.saleBackBill.TaxTotal else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.saleBackBill.TeamNo, 
      dbo.saleBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.saleBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.saleBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.saleBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.saleBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)


union all
SELECT '付款:'+dbo.atype.FullName,
       null,
       case when dbo.vWeb_ARAPIndex.RedWord=2  then dbo.vWeb_ARAPIndex.totalinmoney else null end,
       case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.totalinmoney else null end,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 45 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

--？？
union all
SELECT 
     '付款:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.PayBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.PayBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PayBill.TeamNo, 
      dbo.PayBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PayBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PayBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PayBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)


--返利执行		    148         付款
union all
SELECT 
     '返利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.Advantage.total else null end,       
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.Advantage.total else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 148)



--2004-3-10，新加的，疑问：在什么情况下条件要加dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0？
union all
SELECT '付款:'+dbo.atype.FullName,
      null,
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 148 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)


--价保执行		    149         付款
union all
SELECT 
     '价保执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.PriceProtectBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.PriceProtectBill.total else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 149)
--2004-3-10新增加
union all
SELECT '付款:'+dbo.atype.FullName,
      null,
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 149 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)


--获得价保            151         收款
union all
SELECT 
     '获得价保:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.PriceProtectBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.PriceProtectBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 151)

Union All
--2004-3-10新增加
SELECT 
      '收款:' + dbo.btype.FullName,
      dbo.btype.FullName,  
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.gatheringBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.gatheringBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo, 
      dbo.gatheringBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 151)


--委托代销结算        141         收款
union all
SELECT 
     '委托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.CommissionBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.CommissionBill.TaxTotal else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 141)


--2004-3-10新增加
Union All
SELECT 
      '收款:' + dbo.btype.FullName,
      dbo.btype.FullName,  
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.gatheringBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.gatheringBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo, 
      dbo.gatheringBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 141)


--受托结算            145         付款
union all
SELECT 
     '受托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.CommissionBill.TaxTotal else null end,       
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.CommissionBill.TaxTotal else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 145)

--2004-3-10新增加
union all
SELECT '付款:'+dbo.atype.FullName,
      null,
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 145 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)



--获利执行            150         付款
union all
SELECT 
     '获利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.Advantage.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.Advantage.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 150)

--2004-3-10新增加
union all
SELECT '付款:'+dbo.atype.FullName,
      null,
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 150 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

--应收减少，应付增加
union all
SELECT 
      dbo.AdDebtBill.Comment,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.AdDebtBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId,  
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType in(115,128))


--应收增加，应付减少
union all
SELECT 
      dbo.AdDebtBill.Comment,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then dbo.AdDebtBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType in(116,129))


--费用                36          付款
union all
SELECT
      '费用:'+dbo.MoneyBill.Comment, 
      dbo.atype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then dbo.MoneyBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 

      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType, 
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId      
WHERE (dbo.vWeb_ARAPIndex.BillType =36)
union all
SELECT 
     '付款:'+dbo.atype.FullName,
     null,
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 36 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)


--其他收入单          93          收款
union all
SELECT 
       dbo.MoneyBill.Comment, 
       dbo.atype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo,
      dbo.MoneyBill.ID,
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType, 
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType =93)
union all
SELECT 
     '收款:'+dbo.atype.FullName,
     null,
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end,
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end,
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 93 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)


--固定资产购买        84          付款
union all
SELECT 
     '固定资产购买:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
	  case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 84)

union all
SELECT ' 付款:'+dbo.atype.FullName,
      null,
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 84 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)


--固定资产变卖        85          收款
union all
SELECT 
     '固定资产变卖:' + dbo.btype.FullName,
      dbo.btype.FullName,
	  case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,
	  case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 85)

union all

SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 85 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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





CREATE VIEW vWeb_WLDZ_GYS_YH
(
	zy,
	fullName,
	ApAdd,
	ApReduce,
	BillDate,
	BillCode,
	etypeid,
	TeamNo,
	Id,
	Btypeid,
	BillNumberID,
	BillType, 
	TeamNo1,
	RedWord,
	Comment
)
--@Encode$--
AS
--销售			    11			收款
SELECT 
      '销售:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.SaleBill.Qty as float) AS varchar(20)) + '*' + CAST(cast(dbo.SaleBill.TaxPrice as float) AS varchar(20)),
      dbo.ptype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN CAST(dbo.SaleBill.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN CAST(dbo.SaleBill.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.SaleBill.TeamNo,
      dbo.SaleBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.SaleBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.SaleBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.SaleBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.SaleBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 11)


UNION ALL                 -- #-01
	SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
	FROM 
	dbo.vWeb_ARAPIndex 
	INNER JOIN
	dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
	
	WHERE (dbo.vWeb_ARAPIndex.BillType = 11)

UNION ALL

SELECT ' 收款:'+dbo.atype.FullName,
      NULL,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 11 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--进货			    34			付款
UNION ALL								 -- #-01
SELECT 
      '进货:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.BuyBill.Qty as float) AS varchar(20)) + '*' + CAST(cast(dbo.BuyBill.TaxPrice as float) AS varchar(20)), 
      dbo.ptype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.BuyBill.TaxTotal ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN  dbo.BuyBill.TaxTotal ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.BuyBill.TeamNo,
      dbo.BuyBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.BuyBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.BuyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.BuyBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 34)


UNION ALL							 -- #-01
	SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
	FROM 
	dbo.vWeb_ARAPIndex 
	INNER JOIN
	dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
	
	WHERE (dbo.vWeb_ARAPIndex.BillType = 34)



UNION ALL
SELECT ' 付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 34 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--采购退货			6			收款
UNION ALL
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.BuyBackBill.Qty as float) AS varchar(10)) + '*' + CAST(cast(dbo.BuyBackBill.TaxPrice as float) AS varchar(20)), 
      dbo.ptype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.BuyBackBill.TaxTotal ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.BuyBackBill.TaxTotal ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.BuyBackBill.TeamNo, 
      dbo.BuyBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.BuyBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.BuyBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.BuyBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 6)



UNION ALL                                        -- #-01
	SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
	FROM 
	dbo.vWeb_ARAPIndex 
	INNER JOIN
	dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
	
	WHERE (dbo.vWeb_ARAPIndex.BillType = 6)

UNION ALL
SELECT 
       '收款:'+dbo.atype.FullName,
       NULL,
       CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
       CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN  dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid,
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      NULL,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 6 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

--零售			    305			收款
UNION ALL
SELECT 
     '零售:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.RetailBill.Qty as float) AS varchar(20)) + '*' + CAST(cast(dbo.RetailBill.TaxPrice as float) AS varchar(20)),
      dbo.ptype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN CAST(dbo.RetailBill.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN CAST(dbo.RetailBill.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.RetailBill.TeamNo,
      dbo.RetailBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.RetailBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.RetailBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.RetailBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.RetailBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)
UNION ALL                                        -- #-01

SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
	FROM 
	dbo.vWeb_ARAPIndex 
	INNER JOIN
	dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
	
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)

UNION ALL
SELECT ' 收款:'+dbo.atype.FullName,
      NULL,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 305 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

UNION ALL
--4  ？？
SELECT 
      '收款:' + dbo.btype.FullName,
      dbo.btype.FullName,  
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.gatheringBill.total ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.gatheringBill.total ELSE NULL END, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo, 
      dbo.gatheringBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)
UNION ALL
SELECT                                            -- #-01
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,	
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex 
INNER JOIN dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)


--销售退货			45			付款
UNION ALL
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.saleBackBill.Qty as float) AS varchar(10)) + '*' + CAST(cast(dbo.saleBackBill.TaxPrice as float) AS varchar(20)), 
      dbo.ptype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.saleBackBill.TaxTotal ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN dbo.saleBackBill.TaxTotal ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.saleBackBill.TeamNo, 
      dbo.saleBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.saleBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.saleBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.saleBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.saleBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)


UNION ALL
SELECT                                               -- #-01
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)

UNION ALL
SELECT '付款:'+dbo.atype.FullName,
       NULL,
       CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2  THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
       CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1)  THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      NULL,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 45 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

--？？
UNION ALL
SELECT 
     '付款:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.PayBill.total ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.PayBill.total ELSE NULL END, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PayBill.TeamNo, 
      dbo.PayBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PayBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PayBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PayBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)
UNION ALL
SELECT                                               -- #-01
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)
--返利执行		    148         付款
UNION ALL
SELECT 
     '返利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.Advantage.total ELSE NULL END,       
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.Advantage.total ELSE NULL END,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 148)--2004-3-10，新加的，疑问：在什么情况下条件要加dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0？
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 148 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--价保执行		    149         付款
UNION ALL
SELECT 
     '价保执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.PriceProtectBill.total ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.PriceProtectBill.total ELSE NULL END,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 149)
--2004-3-10新增加
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 149 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--获得价保            151         收款
UNION ALL
SELECT 
     '获得价保:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.PriceProtectBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.PriceProtectBill.total ELSE NULL END, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 151)


--2004-3-10新增加
UNION ALL             -- #-01
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
    CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,  
	dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 151 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

/*SELECT 
      '收款:' + dbo.btype.FullName,
      dbo.btype.FullName,  
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.gatheringBill.total ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.gatheringBill.total ELSE NULL END, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo, 
      dbo.gatheringBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 151)
*/

--委托代销结算        141         收款
UNION ALL
SELECT 
     '委托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.CommissionBill.TaxTotal ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.CommissionBill.TaxTotal ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN

      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 141)


--2004-3-10新增加
UNION ALL
SELECT '收款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	 CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 141 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)



--受托结算            145         付款
UNION ALL
SELECT 
     '受托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.CommissionBill.TaxTotal ELSE NULL END,       
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.CommissionBill.TaxTotal ELSE NULL END,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 145)

--2004-3-10新增加
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 145 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)



--获利执行            150         付款
UNION ALL
SELECT 
     '获利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.Advantage.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.Advantage.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 150)

--2004-3-10新增加
UNION ALL
SELECT '收款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	 CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头

     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 150 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

--应收减少，应付增加
UNION ALL
SELECT 
      dbo.AdDebtBill.Comment,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.AdDebtBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.AdDebtBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId,  
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType IN(115,128))


--应收增加，应付减少
UNION ALL
SELECT 
      dbo.AdDebtBill.Comment,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN dbo.AdDebtBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.AdDebtBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType IN(116,129))


--费用                36          付款
UNION ALL
SELECT
      '费用:'+dbo.MoneyBill.Comment, 
      dbo.atype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.MoneyBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN dbo.MoneyBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,       dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType, 
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId      
WHERE (dbo.vWeb_ARAPIndex.BillType =36)
UNION ALL
SELECT 
     '付款:'+dbo.atype.FullName,
     NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      NULL,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 36 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--其他收入单          93          收款
UNION ALL
SELECT 
       dbo.MoneyBill.Comment, 
       dbo.atype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.MoneyBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.MoneyBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo,
      dbo.MoneyBill.ID,
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType, 
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType =93)
UNION ALL
SELECT 
     '收款:'+dbo.atype.FullName,
     NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      NULL,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 93 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--固定资产购买        84          付款
UNION ALL
SELECT 
     '固定资产购买:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.MoneyBill.total ELSE NULL END,
	  CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.MoneyBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 84)

UNION ALL
SELECT ' 付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 84 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--固定资产变卖        85          收款
UNION ALL
SELECT 
     '固定资产变卖:' + dbo.btype.FullName,
      dbo.btype.FullName,
	  CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.MoneyBill.total ELSE NULL END,
	  CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.MoneyBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 85)

UNION ALL

SELECT ' 收款:'+dbo.atype.FullName,
      NULL,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 85 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)




























































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







CREATE VIEW vWeb_WLDZ_GYS_YH_1
(
	zy,
	fullName,
	ApAdd,
	ApReduce,
	BillDate,
	BillCode,
	etypeid,
	TeamNo,
	Id,
	Btypeid,
	BillNumberID,
	BillType, 
	TeamNo1,
	RedWord,
	Comment
)
--@Encode$--
AS
SELECT                               -- #-01
     '商品维修单:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total else null end,
	  case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo, 
      null,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId 
WHERE (dbo.vWeb_ARAPIndex.BillType = 157)


UNION ALL

SELECT '付款:'+dbo.atype.FullName,
      null,      
    case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end,  
	case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 157 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
--2005-8-29 增加会计凭证单据 谢吉康
UNION ALL
SELECT	'应收:'+B.FullName,
		NULL,
		CASE WHEN V.RedWord IN (0,1) THEN ABS(V.Total) ELSE NULL END,
		CASE WHEN V.RedWord = 2      THEN ABS(V.Total) ELSE NULL END,
		V.BillDate,
		V.BillCode,
		V.ETypeId,
		V.TeamNo,
		-1,
		V.BTypeId,
		V.BillNumberId,
		V.BillType,
		NULL,
		V.RedWord,
		V.Comment 
FROM	vWeb_ARAPIndex V,
		BType B
WHERE	V.BTypeId = B.TypeId
		AND B.Deleted = 0
		AND B.SonNum = 0
		AND V.BillType = 159
		AND V.ATypeId = '0000100005'
UNION ALL
SELECT	'应付:'+B.FullName,		
		NULL,		
		CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,
		CASE WHEN V.RedWord = 2      THEN ABS(V.Total) ELSE NULL END,
		V.BillDate,
		V.BillCode,
		V.ETypeId,
		V.TeamNo,
		-1,
		V.BTypeId,
		V.BillNumberId,
		V.BillType,
		NULL,
		V.RedWord,
		V.Comment 
FROM	vWeb_ARAPIndex V,
		BType B
WHERE	V.BTypeId = B.TypeId
		AND B.Deleted = 0
		AND B.SonNum = 0
		AND V.BillType = 159
		AND V.ATypeId = '0000200001'
UNION ALL
SELECT                                     -- #-01
	 Case dbo.BuyGoodsExchangeBill.InOrOut
		when 'O' then
     		'采购换货出库:' + dbo.ptype.FullName + ' ' + cast(cast(dbo.BuyGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(cast(dbo.BuyGoodsExchangeBill.TaxPrice as float) AS varchar(20))
		when 'I' then
     		'采购换货入库:' + dbo.ptype.FullName + ' ' + cast(cast(dbo.BuyGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(cast(dbo.BuyGoodsExchangeBill.TaxPrice as float) AS varchar(20))
	  end,

      dbo.ptype.FullName, 
	  case dbo.BuyGoodsExchangeBill.InOrOut
          when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(cast(dbo.BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(cast(dbo.BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
		
      end,
			case dbo.BuyGoodsExchangeBill.InOrOut
	    when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(cast(dbo.BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(cast(dbo.BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
      end,
      
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.BuyGoodsExchangeBill.TeamNo,
      dbo.BuyGoodsExchangeBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyGoodsExchangeBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.BuyGoodsExchangeBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.BuyGoodsExchangeBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.BuyGoodsExchangeBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 161)
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      null,     
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
	 case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
	 dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 161 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL
SELECT                                               -- #-01
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 161)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

















CREATE VIEW vWeb_WLDZ_GYS_YH_TY
(
	zy,
	fullName,
	ApAdd,
	ApReduce,
	BillDate,
	BillCode,
	etypeid,
	TeamNo,
	Id,
	Btypeid,
	BillNumberID,
	BillType, 
	TeamNo1,
	RedWord,
	Comment
)
--@Encode$--
AS
--销售			    11			收款
SELECT 
     '销售:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.SaleBill.Qty as float) AS varchar(20)) + '*' + CAST(cast(dbo.SaleBill.TaxPrice as float) AS varchar(20)),
      dbo.ptype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN CAST(dbo.SaleBill.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN CAST(dbo.SaleBill.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.SaleBill.TeamNo,
      dbo.SaleBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.SaleBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.SaleBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.SaleBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.SaleBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 11)


UNION ALL                 -- #-01
	SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
	FROM 
	dbo.vWeb_ARAPIndex 
	INNER JOIN
	dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
	
	WHERE (dbo.vWeb_ARAPIndex.BillType = 11)

UNION ALL

SELECT ' 收款:'+dbo.atype.FullName,
      NULL,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 11 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--进货			    34			付款
UNION ALL								 -- #-01
SELECT 
      '进货:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.BuyBill.Qty as float) AS varchar(20)) + '*' + CAST(cast(dbo.BuyBill.TaxPrice as float) AS varchar(20)), 
      dbo.ptype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.BuyBill.TaxTotal ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN  dbo.BuyBill.TaxTotal ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.BuyBill.TeamNo,
      dbo.BuyBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.BuyBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.BuyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.BuyBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 34)


UNION ALL							 -- #-01
	SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
	FROM 
	dbo.vWeb_ARAPIndex 
	INNER JOIN
	dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
	
	WHERE (dbo.vWeb_ARAPIndex.BillType = 34)



UNION ALL
SELECT ' 付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 34 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--采购退货			6			收款
UNION ALL
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.BuyBackBill.Qty as float) AS varchar(10)) + '*' + CAST(cast(dbo.BuyBackBill.TaxPrice as float) AS varchar(20)), 
      dbo.ptype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.BuyBackBill.TaxTotal ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.BuyBackBill.TaxTotal ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.BuyBackBill.TeamNo, 
      dbo.BuyBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.BuyBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.BuyBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.BuyBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 6)



UNION ALL                                        -- #-01
	SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
	FROM 
	dbo.vWeb_ARAPIndex 
	INNER JOIN
	dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
	
	WHERE (dbo.vWeb_ARAPIndex.BillType = 6)

UNION ALL
SELECT 
       '收款:'+dbo.atype.FullName,
       NULL,
       CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
       CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN  dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid,
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      NULL,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 6 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

--零售			    305			收款
UNION ALL
SELECT 
     '零售:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.RetailBill.Qty as float) AS varchar(20)) + '*' + CAST(cast(dbo.RetailBill.TaxPrice as float) AS varchar(20)),
      dbo.ptype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN CAST(dbo.RetailBill.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN CAST(dbo.RetailBill.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.RetailBill.TeamNo,
      dbo.RetailBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.RetailBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.RetailBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.RetailBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.RetailBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)
UNION ALL                                        -- #-01

SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
	FROM 
	dbo.vWeb_ARAPIndex 
	INNER JOIN
	dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
	
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)

UNION ALL
SELECT ' 收款:'+dbo.atype.FullName,
      NULL,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 305 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

UNION ALL
--4  ？？
SELECT 
      '收款:' + dbo.btype.FullName,
      dbo.btype.FullName,  
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.gatheringBill.total ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.gatheringBill.total ELSE NULL END, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo, 
      dbo.gatheringBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)
UNION ALL
SELECT                                            -- #-01
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,	
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex 
INNER JOIN dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)


--销售退货			45			付款
UNION ALL
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.saleBackBill.Qty as float) AS varchar(10)) + '*' + CAST(cast(dbo.saleBackBill.TaxPrice as float) AS varchar(20)), 
      dbo.ptype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.saleBackBill.TaxTotal ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN dbo.saleBackBill.TaxTotal ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.saleBackBill.TeamNo, 
      dbo.saleBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.saleBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.saleBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.saleBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.saleBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)


UNION ALL
SELECT                                               -- #-01
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)

UNION ALL
SELECT '付款:'+dbo.atype.FullName,
       NULL,
       CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2  THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
       CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1)  THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      NULL,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 45 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

--？？
UNION ALL
SELECT 
     '付款:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.PayBill.total ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.PayBill.total ELSE NULL END, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PayBill.TeamNo, 
      dbo.PayBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PayBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PayBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PayBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)
UNION ALL
SELECT                                               -- #-01
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)
--返利执行		    148         付款
UNION ALL
SELECT 
     '返利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.Advantage.total ELSE NULL END,       
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.Advantage.total ELSE NULL END,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 148)--2004-3-10，新加的，疑问：在什么情况下条件要加dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0？
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 148 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--价保执行		    149         付款
UNION ALL
SELECT 
     '价保执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.PriceProtectBill.total ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.PriceProtectBill.total ELSE NULL END,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 149)
--2004-3-10新增加
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 149 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--获得价保            151         收款
UNION ALL
SELECT 
     '获得价保:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.PriceProtectBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.PriceProtectBill.total ELSE NULL END, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 151)


--2004-3-10新增加
UNION ALL             -- #-01
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
    CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,  
	dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 151 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

/*SELECT 
      '收款:' + dbo.btype.FullName,
      dbo.btype.FullName,  
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.gatheringBill.total ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.gatheringBill.total ELSE NULL END, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo, 
      dbo.gatheringBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 151)
*/

--委托代销结算        141         收款
UNION ALL
SELECT 
     '委托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.CommissionBill.TaxTotal ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.CommissionBill.TaxTotal ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN

      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 141)


--2004-3-10新增加
UNION ALL
SELECT '收款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	 CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 141 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)



--受托结算            145         付款
UNION ALL
SELECT 
     '受托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.CommissionBill.TaxTotal ELSE NULL END,       
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.CommissionBill.TaxTotal ELSE NULL END,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 145)

--2004-3-10新增加
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 145 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)



--获利执行            150         付款
UNION ALL
SELECT 
     '获利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.Advantage.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.Advantage.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 150)

--2004-3-10新增加
UNION ALL
SELECT '收款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	 CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头

     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 150 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)

--应收减少，应付增加
UNION ALL
SELECT 
      dbo.AdDebtBill.Comment,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.AdDebtBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.AdDebtBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId,  
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType IN(115,128))


--应收增加，应付减少
UNION ALL
SELECT 
      dbo.AdDebtBill.Comment,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN dbo.AdDebtBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.AdDebtBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType IN(116,129))


--费用                36          付款
UNION ALL
SELECT
      '费用:'+dbo.MoneyBill.Comment, 
      dbo.atype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.MoneyBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord=2 THEN dbo.MoneyBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,       dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType, 
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId      
WHERE (dbo.vWeb_ARAPIndex.BillType =36)
UNION ALL
SELECT 
     '付款:'+dbo.atype.FullName,
     NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      NULL,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 36 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--其他收入单          93          收款
UNION ALL
SELECT 
       dbo.MoneyBill.Comment, 
       dbo.atype.FullName, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.MoneyBill.total ELSE NULL END,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.MoneyBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo,
      dbo.MoneyBill.ID,
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType, 
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType =93)
UNION ALL
SELECT 
     '收款:'+dbo.atype.FullName,
     NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      NULL,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 93 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)























































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










CREATE VIEW vWeb_WLDZ_GYS_YH_TY_1
(
	zy,
	fullName,
	ApAdd,
	ApReduce,
	BillDate,
	BillCode,
	etypeid,
	TeamNo,
	Id,
	Btypeid,
	BillNumberID,
	BillType, 
	TeamNo1,
	RedWord,
	Comment
)
--@Encode$--
AS
--固定资产购买        84          付款
SELECT 
     '固定资产购买:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.MoneyBill.total ELSE NULL END,
	  CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.MoneyBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 84)

UNION ALL
SELECT ' 付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 84 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


--固定资产变卖        85          收款
UNION ALL
SELECT 
     '固定资产变卖:' + dbo.btype.FullName,
      dbo.btype.FullName,
	  CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.MoneyBill.total ELSE NULL END,
	  CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.MoneyBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 85)
UNION ALL
SELECT ' 收款:'+dbo.atype.FullName,
      NULL,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 85 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL
SELECT                               -- #-01
     '维修受理单:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total else null end,
	  case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo, 
      null,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId 
WHERE (dbo.vWeb_ARAPIndex.BillType = 157)


union all

SELECT '付款:'+dbo.atype.FullName,
      null,      
    case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end,  
	case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 157 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
--2005-8-29 增加会计凭证单据 谢吉康
UNION ALL
SELECT	'应收:'+B.FullName,
		NULL,
		CASE WHEN V.RedWord = 2      THEN V.Total ELSE NULL END,
		CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,		
		V.BillDate,
		V.BillCode,
		V.ETypeId,
		V.TeamNo,
		-1,
		V.BTypeId,
		V.BillNumberId,
		V.BillType,
		NULL,
		V.RedWord,
		V.Comment 
FROM	vWeb_ARAPIndex V,
		BType B
WHERE	V.BTypeId = B.TypeId
		AND B.Deleted = 0
		AND B.SonNum = 0
		AND V.BillType = 159
		AND V.ATypeId = '0000100005'
UNION ALL
SELECT	'应付:'+B.FullName,		
		NULL,		
		CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,
		CASE WHEN V.RedWord = 2      THEN V.Total ELSE NULL END,
		V.BillDate,
		V.BillCode,
		V.ETypeId,
		V.TeamNo,
		-1,
		V.BTypeId,
		V.BillNumberId,
		V.BillType,
		NULL,
		V.RedWord,
		V.Comment 
FROM	vWeb_ARAPIndex V,
		BType B
WHERE	V.BTypeId = B.TypeId
		AND B.Deleted = 0
		AND B.SonNum = 0
		AND V.BillType = 159
		AND V.ATypeId = '0000200001'		
UNION ALL
SELECT                                     -- #-01
	 Case dbo.SaleGoodsExchangeBill.InOrOut
		when 'O' then
     		'销售换货出库:' + dbo.ptype.FullName + ' ' + cast(cast(dbo.SaleGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(cast(dbo.SaleGoodsExchangeBill.TaxPrice as float) AS varchar(20))
		when 'I' then
     		'销售换货入库:' + dbo.ptype.FullName + ' ' + cast(cast(dbo.SaleGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(cast(dbo.SaleGoodsExchangeBill.TaxPrice as float) AS varchar(20))
	  end,

      dbo.ptype.FullName, 
	  case dbo.SaleGoodsExchangeBill.InOrOut
          when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(cast(dbo.SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then

            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(cast(dbo.SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
		
      end,
			case dbo.SaleGoodsExchangeBill.InOrOut
	    when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(cast(dbo.SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(cast(dbo.SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
      end,
      
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.SaleGoodsExchangeBill.TeamNo,
      dbo.SaleGoodsExchangeBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.SaleGoodsExchangeBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.SaleGoodsExchangeBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.SaleGoodsExchangeBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.SaleGoodsExchangeBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 160)
union all
SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
	 dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 160 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL                 -- #-01
SELECT	'优惠金额:',
		' ',
		CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
		CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
		dbo.vWeb_ARAPIndex.BillDate, 
		dbo.vWeb_ARAPIndex.BillCode,
		dbo.vWeb_ARAPIndex.etypeid,
		dbo.vWeb_ARAPIndex.TeamNo,
		-1,
		dbo.vWeb_ARAPIndex.BtypeId, 
		dbo.BillIndex.BillNumberId,
		dbo.vWeb_ARAPIndex.BillType,
		' ',
		dbo.vWeb_ARAPIndex.RedWord,
		dbo.vWeb_ARAPIndex.Comment
FROM 	dbo.vWeb_ARAPIndex INNER JOIN dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId	
WHERE (dbo.vWeb_ARAPIndex.BillType = 160)
UNION ALL
SELECT                                     -- #-01
	 Case dbo.BuyGoodsExchangeBill.InOrOut
		when 'O' then
     		'采购换货出库:' + dbo.ptype.FullName + ' ' + cast(cast(dbo.BuyGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(cast(dbo.BuyGoodsExchangeBill.TaxPrice as float) AS varchar(20))
		when 'I' then
     		'采购换货入库:' + dbo.ptype.FullName + ' ' + cast(cast(dbo.BuyGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(cast(dbo.BuyGoodsExchangeBill.TaxPrice as float) AS varchar(20))
	  end,

      dbo.ptype.FullName, 
	  case dbo.BuyGoodsExchangeBill.InOrOut
          when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(cast(dbo.BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then

            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(cast(dbo.BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
		
      end,
			case dbo.BuyGoodsExchangeBill.InOrOut
	    when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(cast(dbo.BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(cast(dbo.BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
      end,
      
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.BuyGoodsExchangeBill.TeamNo,
      dbo.BuyGoodsExchangeBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyGoodsExchangeBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.BuyGoodsExchangeBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.BuyGoodsExchangeBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.BuyGoodsExchangeBill.PtypeId = dbo.ptype.typeId

WHERE (dbo.vWeb_ARAPIndex.BillType = 161)
union all
SELECT '付款:'+dbo.atype.FullName,
      null,      
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
	 case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
	 dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 161 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL                 -- #-01
SELECT	'优惠金额:',
		' ',
		CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
		CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
		dbo.vWeb_ARAPIndex.BillDate, 
		dbo.vWeb_ARAPIndex.BillCode,
		dbo.vWeb_ARAPIndex.etypeid,
		dbo.vWeb_ARAPIndex.TeamNo,
		-1,
		dbo.vWeb_ARAPIndex.BtypeId, 
		dbo.BillIndex.BillNumberId,
		dbo.vWeb_ARAPIndex.BillType,
		' ',
		dbo.vWeb_ARAPIndex.RedWord,
		dbo.vWeb_ARAPIndex.Comment
FROM 	dbo.vWeb_ARAPIndex INNER JOIN dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId	
WHERE (dbo.vWeb_ARAPIndex.BillType = 161)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







/****** Object:  View dbo.vWeb_WLDZ_GYS1    Script Date: 2002-6-20 10:14:43 ******/
--供应商应付往来
CREATE view vWeb_WLDZ_GYS1(djlx,zy,ApAdd,ApReduce,BillDate,BillCode,Btypeid,BillNumberID,BillType,RedWord)
--@Encode$--
as
SELECT 
     '固定资产购买',dbo.vWeb_ARAPIndex.comment,
    case
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
         else null
         end,
    case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         else null
         end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM  dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType = 84)
union all
SELECT 
     '固定资产变卖',dbo.vWeb_ARAPIndex.comment,
    case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         else null
         end,
    case
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
         else null
         end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM  dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType = 85)
union all
SELECT 
     '销售单',dbo.vWeb_ARAPIndex.comment,
    case
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and (vWeb_ARAPIndex.RedWord =2) then  dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         else null
         end,
    case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         else null
         end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM  dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType = 11)
union all
SELECT 
     '零售单',dbo.vWeb_ARAPIndex.comment,
    case
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney
         else null
         end,
    case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         else null
         end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM  dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)
union all
SELECT  
      '销售退货',dbo.vWeb_ARAPIndex.comment,
    case 
          when (dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
          when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
          else null
          end,
   case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         when (dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney
         else null  
         end,
    dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
    dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)
union all
SELECT 
     '进货单',dbo.vWeb_ARAPIndex.comment,
    case 
     when dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
     when dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
    else null  end,
    case
     when dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
     when dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
     else null
     end,
     dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
     dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 34)
union all
SELECT  
      '退货',dbo.vWeb_ARAPIndex.comment,
    case 
    when dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
    when dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
    else null   end,
    case 
     when dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney
    when dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2  then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
    else null   
    end,
     dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
     dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 6)
union all
SELECT '销售收款',dbo.vWeb_ARAPIndex.comment,  
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then  dbo.vWeb_ARAPIndex.totalinmoney else null end,
      case when dbo.vWeb_ARAPIndex.RedWord =2  then  dbo.vWeb_ARAPIndex.totalinmoney else null end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)
union all
SELECT '付款',dbo.vWeb_ARAPIndex.comment,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId,
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)
union all
SELECT '返利执行',dbo.vWeb_ARAPIndex.comment,
      case 
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       else null 
       end,
      case 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =148)
union all
SELECT '价保执行',dbo.vWeb_ARAPIndex.comment,
      case 
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       else null 
       end,
      case 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =149)
union all
SELECT '委托代销结算',dbo.vWeb_ARAPIndex.comment,
      case 
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       else null 
       end,
      case 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =141)
union all
SELECT '受托代销结算',dbo.vWeb_ARAPIndex.comment,
      case 
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       else null 
       end,
      case 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =145)

union all
SELECT '获利执行',dbo.vWeb_ARAPIndex.comment,
      case 
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       else null 
       end,
      case 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =150)

union all
--应收减少，应付增加
SELECT
      '调帐(应付增加)', 
      dbo.AdDebtBill.Comment,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.AdDebtBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
      dbo.AdDebtBill.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType in(115,128))
union all
--应收增加，应付减少
SELECT
      '调帐(应付减少)', 
      dbo.AdDebtBill.Comment,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then dbo.AdDebtBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
      dbo.AdDebtBill.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType in(116,129))
--36费用单93其他收入单
union all
SELECT '费用单',dbo.vWeb_ARAPIndex.comment,
      case 
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       else null 
       end,
      case 
       when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
       when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
       else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =36)
union all
SELECT '其他收入单',dbo.vWeb_ARAPIndex.comment,
      case 
        when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
        when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2  then  dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney
        else null end,
     case 
      when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1)  then  dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney
      when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
      else null 
      end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =93)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE  view vWeb_WLDZ_YH
(	
	zy,
	fullName,
	ArAdd,
	ArReduce,
	BillDate,
	BillCode,
	etypeid,
	TeamNo,
	Id,
	Btypeid,
	BillNumberID,
	BillType,
	TeamNo1,
	RedWord,
	Comment
)
--@Encode$--
as
SELECT 
     '销售:' + dbo.ptype.FullName + ' ' + cast(cast(dbo.SaleBill.Qty as float) as varchar(20)) + '*' + CAST(cast(dbo.SaleBill.TaxPrice as float) AS varchar(20)),
      dbo.ptype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.SaleBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.SaleBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.SaleBill.TeamNo,
      dbo.SaleBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.SaleBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.SaleBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.SaleBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.SaleBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 11)
union all

--优惠金额
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 11)


union all
SELECT 
      '进货:' + dbo.ptype.FullName + ' ' + CAST(cast(dbo.BuyBill.Qty as float) AS varchar(20)) + '*' + CAST(cast(dbo.BuyBill.TaxPrice as float) AS varchar(20)), 
      dbo.ptype.FullName,       
      case when dbo.vWeb_ARAPIndex.RedWord=2 then  (dbo.BuyBill.TaxTotal ) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then (dbo.BuyBill.TaxTotal) else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.BuyBill.TeamNo,
      dbo.BuyBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.BuyBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.BuyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.BuyBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 34)


--优惠金额
union all
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 34)


union all
SELECT ' 付款:'+dbo.atype.FullName,

      null,
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 


     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord,
     dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 34 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 11 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(CAST(dbo.BuyBackBill.Qty AS Float) AS varchar(10)) + '*' + CAST(CAST(dbo.BuyBackBill.TaxPrice AS Float) AS varchar(20)), 
      dbo.ptype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then (dbo.BuyBackBill.TaxTotal) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then (dbo.BuyBackBill.TaxTotal) else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.BuyBackBill.TeamNo, 
      dbo.BuyBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.BuyBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.BuyBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.BuyBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.BuyBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 6)

--优惠金额

union all
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 6)

union all
SELECT 
     '零售:' + dbo.ptype.FullName + ' ' + cast(CAST(dbo.RetailBill.Qty as float) as varchar(20)) + '*' + CAST(CAST(dbo.RetailBill.TaxPrice as float) AS varchar(20)),
      dbo.ptype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(dbo.RetailBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(dbo.RetailBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.RetailBill.TeamNo,
      dbo.RetailBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.RetailBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.RetailBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.RetailBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.RetailBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)
UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)

union all
SELECT 
       '收款:'+dbo.atype.FullName,
       null,
       case when dbo.vWeb_ARAPIndex.RedWord =2 then  dbo.vWeb_ARAPIndex.totalinmoney else null end,
       case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.totalinmoney else null end,

       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid,
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 6 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 305 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
SELECT  
      '退货:' + dbo.ptype.FullName + ' ' + CAST(CAST(dbo.saleBackBill.Qty as float) AS varchar(10)) + '*' + CAST(CAST(dbo.saleBackBill.TaxPrice as float) AS varchar(20)), 
      dbo.ptype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord=2 then (dbo.saleBackBill.TaxTotal) else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then (dbo.saleBackBill.TaxTotal) else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.saleBackBill.TeamNo, 
      dbo.saleBackBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.saleBackBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
     dbo.saleBackBill ON 
     dbo.vWeb_ARAPIndex.BillNumberId = dbo.saleBackBill.BillNumberId INNER JOIN
     dbo.ptype ON dbo.saleBackBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)
--优惠金额
union all
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,	--2004-08-18 谢吉康 调换了和下面一条语句的顺序
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)

union all
SELECT 
     '付款:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.PayBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.PayBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PayBill.TeamNo, 
      dbo.PayBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PayBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PayBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PayBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)
--优惠金额
union all
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,	--2004-08-18 谢吉康 调换了和下面一条语句的顺序
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)

union all
SELECT 
     '返利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.Advantage.total else null end,       
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.Advantage.total else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 148)
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 148 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


union all
SELECT 
     '价保执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.PriceProtectBill.total ELSE NULL END,       
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.PriceProtectBill.total ELSE NULL END, 
	  dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 149)
--2004-3-10新增加
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	 dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 149 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)
union all
SELECT 
     '委托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.CommissionBill.TaxTotal else null end,             
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.CommissionBill.TaxTotal else null end,       
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 
      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 141)
UNION all
SELECT '收款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 141 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


union all
SELECT 
     '受托代销结算:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.CommissionBill.TaxTotal else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.CommissionBill.TaxTotal else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.CommissionBill.TeamNo, 


      dbo.CommissionBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.CommissionBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.CommissionBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.CommissionBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 145)
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
		NULL,     
		CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
		CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
		dbo.vWeb_ARAPIndex.BillDate, 
		dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
		dbo.vWeb_ARAPIndex.TeamNo,
		-1,--////////////////////////////////////////////标明该行为表头
		dbo.vWeb_ARAPIndex.btypeid, 
		dbo.vWeb_ARAPIndex.BillNumberId, 
		dbo.vWeb_ARAPIndex.BillType,
		NULL,
		dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 145 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)



union all
SELECT                        --#-01
     '获利执行:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.Advantage.total ELSE NULL END,
	  CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.Advantage.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.Advantage.TeamNo, 
      dbo.Advantage.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.Advantage.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.Advantage ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.Advantage.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 150)

UNION ALL
SELECT '收款:'+dbo.atype.FullName,
      NULL,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 150 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)


union all
SELECT '付款:'+dbo.atype.FullName,
       null,
       case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.totalinmoney else null end,
       case when dbo.vWeb_ARAPIndex.RedWord=2  then dbo.vWeb_ARAPIndex.totalinmoney else null end,
       dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId, 
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 45 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
--应收减少，应付增加
SELECT 
      dbo.AdDebtBill.Comment,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.AdDebtBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId,  
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex  INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType in(115,128))

union all
SELECT '收款:' + dbo.btype.FullName,
      dbo.btype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.gatheringBill.total else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.gatheringBill.total else null end, 
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.gatheringBill.TeamNo,
      dbo.gatheringBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.gatheringBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.gatheringBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.gatheringBill.BillNumberId INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)
UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,	
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)


--应收增加，应付减少
union all
SELECT 
      dbo.AdDebtBill.Comment,dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.AdDebtBill.total else null end,

      case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.AdDebtBill.TeamNo, 
      dbo.AdDebtBill.ID, 
      dbo.AdDebtBill.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.AdDebtBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
     INNER JOIN
      dbo.btype ON dbo.AdDebtBill.BtypeId = dbo.btype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType in(116,129))
--36费用单93其他收入单
union all
SELECT
             '费用单：'+dbo.MoneyBill.Comment, 
             dbo.atype.FullName, 
            case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.MoneyBill.total else null end, 
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.MoneyBill.total else null end, 
            dbo.vWeb_ARAPIndex.BillDate,
            dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
            dbo.MoneyBill.TeamNo, 
            dbo.MoneyBill.ID, 
            dbo.vWeb_ARAPIndex.btypeid, 
            dbo.vWeb_ARAPIndex.BillNumberId, 
           dbo.vWeb_ARAPIndex.BillType, 
           dbo.MoneyBill.TeamNo1,
           dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType =36)

union all
SELECT 
     ' 付款:'+dbo.atype.FullName,
     null,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,null,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 36 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)

union all
SELECT 
       dbo.MoneyBill.Comment, 
       dbo.atype.FullName, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,

      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo,
      dbo.MoneyBill.ID,
      dbo.vWeb_ARAPIndex.btypeid, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType, 
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.MoneyBill INNER JOIN
      dbo.atype ON dbo.MoneyBill.AtypeId = dbo.atype.typeId INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.MoneyBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType =93)
union all
SELECT 
     ' 收款:'+dbo.atype.FullName,
     null,
     case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,

     null,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 93 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
union all
SELECT 
     '固定资产购买:' + dbo.btype.FullName,
      dbo.btype.FullName,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 84)
UNION ALL
SELECT ' 付款:'+dbo.atype.FullName,
      null,
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
     dbo.vWeb_ARAPIndex.RedWord,
     dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 84 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
union all
SELECT 
     '固定资产变卖:' + dbo.btype.FullName,
      dbo.btype.FullName,
	  case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.MoneyBill.total else null end,
	  case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.MoneyBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.MoneyBill.TeamNo, 
      dbo.MoneyBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.MoneyBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.MoneyBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.MoneyBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 85)
UNION ALL
SELECT 
     ' 收款:'+dbo.atype.FullName,
     null,
     case when dbo.vWeb_ARAPIndex.RedWord =2  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,

     null,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 85 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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






CREATE  view vWeb_WLDZ_YH_1
(	
	zy,
	fullName,
	ArAdd,
	ArReduce,
	BillDate,
	BillCode,
	etypeid,
	TeamNo,
	Id,
	Btypeid,
	BillNumberID,
	BillType,
	TeamNo1,
	RedWord,
	Comment
)
--@Encode$--
AS
--商品维修受理单      157         收款
SELECT 
     '商品维修单:' + dbo.btype.FullName,
      dbo.btype.FullName,
	  case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total else null end,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.vWeb_ARAPIndex.TeamNo, 
      -1,--////////////////////////////////////////////标明该行为表头
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      null,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM  dbo.vWeb_ARAPIndex INNER JOIN
      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId 
WHERE (dbo.vWeb_ARAPIndex.BillType = 157)

union all

SELECT ' 收款:'+dbo.atype.FullName,
      null,      
     case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 157 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL                                 --#-01
SELECT 
     '获得价保:' + dbo.btype.FullName,
      dbo.btype.FullName,
      CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.PriceProtectBill.total ELSE NULL END, 
	  CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.PriceProtectBill.total ELSE NULL END,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
      dbo.PriceProtectBill.TeamNo, 
      dbo.PriceProtectBill.ID, 
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.PriceProtectBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.vWeb_ARAPIndex INNER JOIN

      dbo.btype ON dbo.vWeb_ARAPIndex.BtypeId = dbo.btype.typeId INNER JOIN
      dbo.PriceProtectBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.PriceProtectBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 151)
--2004-3-10新增加
UNION ALL
SELECT '付款:'+dbo.atype.FullName,
      NULL,
     CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END,  
	 CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN dbo.vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid, 
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     NULL,
     dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 151 AND dbo.vWeb_ARAPIndex.atypeid<>'' AND dbo.vWeb_ARAPIndex.totalinmoney<>0)
--2005-8-29 增加会计凭证单据 谢吉康
UNION ALL
SELECT	'应收:'+B.FullName,
		NULL,
		CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,
		CASE WHEN V.RedWord = 2 THEN ABS(V.Total) ELSE NULL END,
		V.BillDate,
		V.BillCode,
		V.ETypeId,
		V.TeamNo,
		-1,
		V.BTypeId,
		V.BillNumberId,
		V.BillType,
		NULL,
		V.RedWord,
		V.Comment 
FROM	vWeb_ARAPIndex V,
		BType B
WHERE	V.BTypeId = B.TypeId
		AND B.Deleted = 0
		AND B.SonNum = 0
		AND V.BillType = 159
		AND V.ATypeId = '0000100005'
UNION ALL
SELECT	'应付:'+B.FullName,		
		NULL,		
		CASE WHEN V.RedWord = 2 THEN ABS(V.Total) ELSE NULL END,
		CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,		
		V.BillDate,
		V.BillCode,
		V.ETypeId,
		V.TeamNo,
		-1,
		V.BTypeId,
		V.BillNumberId,
		V.BillType,
		NULL,
		V.RedWord,
		V.Comment 
FROM	vWeb_ARAPIndex V,
		BType B
WHERE	V.BTypeId = B.TypeId
		AND B.Deleted = 0
		AND B.SonNum = 0
		AND V.BillType = 159
		AND V.ATypeId = '0000200001'
UNION ALL
--销售换货单      160         收款
SELECT 
	 Case dbo.SaleGoodsExchangeBill.InOrOut
		when 'O' then
     		'销售换货出库:' + dbo.ptype.FullName + ' ' + cast(CAST(dbo.SaleGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(CAST(dbo.SaleGoodsExchangeBill.TaxPrice as float) AS varchar(20))
		when 'I' then
     		'销售换货入库:' + dbo.ptype.FullName + ' ' + cast(CAST(dbo.SaleGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(CAST(dbo.SaleGoodsExchangeBill.TaxPrice as float) AS varchar(20))
	  end,

      dbo.ptype.FullName, 
		case dbo.SaleGoodsExchangeBill.InOrOut
	    when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(CAST(dbo.SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(CAST(dbo.SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
      end,
      
	  case dbo.SaleGoodsExchangeBill.InOrOut
          when 'O' then
            case when dbo.vWeb_ARAPIndex.RedWord=2 then cast(CAST(dbo.SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then cast(CAST(dbo.SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
		
      end,
      dbo.vWeb_ARAPIndex.BillDate,
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid,
      dbo.SaleGoodsExchangeBill.TeamNo,
      dbo.SaleGoodsExchangeBill.ID,
      dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,
      dbo.vWeb_ARAPIndex.BillType,
      dbo.SaleGoodsExchangeBill.TeamNo1,
      dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.SaleGoodsExchangeBill INNER JOIN
      dbo.vWeb_ARAPIndex ON 
      dbo.SaleGoodsExchangeBill.BillNumberId = dbo.vWeb_ARAPIndex.BillNumberId INNER JOIN
      dbo.ptype ON dbo.SaleGoodsExchangeBill.PtypeId = dbo.ptype.typeId
WHERE (dbo.vWeb_ARAPIndex.BillType = 160)
union all
SELECT ' 收款:'+dbo.atype.FullName,
      null,
      case when dbo.vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
      case when dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end, 
     dbo.vWeb_ARAPIndex.BillDate, 
     dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.etypeid, 
     dbo.vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     dbo.vWeb_ARAPIndex.btypeid,
     dbo.vWeb_ARAPIndex.BillNumberId, 
     dbo.vWeb_ARAPIndex.BillType,
     null,
    dbo.vWeb_ARAPIndex.RedWord,
	  dbo.vWeb_ARAPIndex.Comment
FROM dbo.atype INNER JOIN
      dbo.vWeb_ARAPIndex ON dbo.atype.typeId = dbo.vWeb_ARAPIndex.atypeid
WHERE (dbo.vWeb_ARAPIndex.BillType = 160 and dbo.vWeb_ARAPIndex.atypeid<>'' and dbo.vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL
--优惠金额
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord =2 THEN dbo.billindex.preferencemoney ELSE NULL END,
	CASE WHEN dbo.vWeb_ARAPIndex.RedWord IN(0,1) THEN  dbo.billindex.preferencemoney ELSE NULL END,
	dbo.vWeb_ARAPIndex.BillDate, 
	dbo.vWeb_ARAPIndex.BillCode,
	dbo.vWeb_ARAPIndex.etypeid,
	dbo.vWeb_ARAPIndex.TeamNo,
	-1,
	dbo.vWeb_ARAPIndex.BtypeId, 
	dbo.BillIndex.BillNumberId,
	dbo.vWeb_ARAPIndex.BillType,
	' ',
	dbo.vWeb_ARAPIndex.RedWord,
	dbo.vWeb_ARAPIndex.Comment
FROM 
      dbo.vWeb_ARAPIndex 
	  INNER JOIN
	  dbo.billindex ON dbo.vWeb_ARAPIndex.BillNumberId = dbo.billindex.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType = 160)






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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





CREATE  view vWeb_WLDZ_YH_TY
(	
	zy,
	fullName,
	ArAdd,
	ArReduce,
	BillDate,
	BillCode,
	etypeid,
	TeamNo,
	Id,
	Btypeid,
	BillNumberID,
	BillType,
	TeamNo1,
	RedWord,
	Comment
)
--@Encode$--
as
SELECT 
     '销售:' + ptype.FullName + ' ' + cast(cast(SaleBill.Qty as float) as varchar(20)) + '*' + CAST(cast(SaleBill.TaxPrice as float) AS varchar(20)),
      ptype.FullName, 
      case when vWeb_ARAPIndex.RedWord in(0,1) then cast(SaleBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      case when vWeb_ARAPIndex.RedWord=2 then cast(SaleBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      vWeb_ARAPIndex.BillDate,
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid,
      SaleBill.TeamNo,
      SaleBill.ID,
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      SaleBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM SaleBill INNER JOIN
      vWeb_ARAPIndex ON 
      SaleBill.BillNumberId = vWeb_ARAPIndex.BillNumberId INNER JOIN
      ptype ON SaleBill.PtypeId = ptype.typeId
WHERE (vWeb_ARAPIndex.BillType = 11)
UNION ALL
--优惠金额
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,
	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 11)
UNION ALL
SELECT 
      '进货:' + ptype.FullName + ' ' + CAST(cast(BuyBill.Qty as float) AS varchar(20)) + '*' + CAST(cast(BuyBill.TaxPrice as float) AS varchar(20)), 
      ptype.FullName,       
      case when vWeb_ARAPIndex.RedWord=2 then  (BuyBill.TaxTotal ) else null end,
      case when vWeb_ARAPIndex.RedWord in(0,1) then (BuyBill.TaxTotal) else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid,
      BuyBill.TeamNo,
      BuyBill.ID,
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      BuyBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM BuyBill INNER JOIN
      vWeb_ARAPIndex ON 
      BuyBill.BillNumberId = vWeb_ARAPIndex.BillNumberId INNER JOIN
      ptype ON BuyBill.PtypeId = ptype.typeId
WHERE (vWeb_ARAPIndex.BillType = 34)
--优惠金额
UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,
	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 34)
UNION ALL
SELECT ' 付款:'+atype.FullName,
      null,
     case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.totalinmoney else null end, 
     case when vWeb_ARAPIndex.RedWord =2 then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 

     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     null,
     vWeb_ARAPIndex.RedWord,
     vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 34 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)

UNION ALL
SELECT ' 收款:'+atype.FullName,
      null,
      case when vWeb_ARAPIndex.RedWord =2 then vWeb_ARAPIndex.totalinmoney else null end, 
      case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid,
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     null,
    vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 11 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)

UNION ALL
SELECT  
      '退货:' + ptype.FullName + ' ' + CAST(CAST(BuyBackBill.Qty AS Float) AS varchar(10)) + '*' + CAST(CAST(BuyBackBill.TaxPrice AS Float) AS varchar(20)), 
      ptype.FullName,
      case when vWeb_ARAPIndex.RedWord in(0,1) then (BuyBackBill.TaxTotal) else null end,
      case when vWeb_ARAPIndex.RedWord =2 then (BuyBackBill.TaxTotal) else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      BuyBackBill.TeamNo, 
      BuyBackBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      BuyBackBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
     BuyBackBill ON 
     vWeb_ARAPIndex.BillNumberId = BuyBackBill.BillNumberId INNER JOIN
     ptype ON BuyBackBill.PtypeId = ptype.typeId
WHERE (vWeb_ARAPIndex.BillType = 6)

--优惠金额

UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,
	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 6)

UNION ALL
SELECT 
     '零售:' + ptype.FullName + ' ' + cast(CAST(RetailBill.Qty as float) as varchar(20)) + '*' + CAST(CAST(RetailBill.TaxPrice as float) AS varchar(20)),
      ptype.FullName, 
      case when vWeb_ARAPIndex.RedWord in(0,1) then cast(RetailBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      case when vWeb_ARAPIndex.RedWord=2 then cast(RetailBill.TaxTotal as  NUMERIC(24, 10) ) else null end,
      vWeb_ARAPIndex.BillDate,
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid,
      RetailBill.TeamNo,
      RetailBill.ID,
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      RetailBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM RetailBill INNER JOIN
      vWeb_ARAPIndex ON 
      RetailBill.BillNumberId = vWeb_ARAPIndex.BillNumberId INNER JOIN
      ptype ON RetailBill.PtypeId = ptype.typeId
WHERE (vWeb_ARAPIndex.BillType = 305)
UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,
	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 305)

UNION ALL
SELECT 
       '收款:'+atype.FullName,
       null,
       case when vWeb_ARAPIndex.RedWord =2 then  vWeb_ARAPIndex.totalinmoney else null end,
       case when vWeb_ARAPIndex.RedWord in(0,1) then  vWeb_ARAPIndex.totalinmoney else null end,

       vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      vWeb_ARAPIndex.btypeid,
      vWeb_ARAPIndex.BillNumberId, 
      vWeb_ARAPIndex.BillType,
      null,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 6 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)

UNION ALL
SELECT ' 收款:'+atype.FullName,
      null,
      case when vWeb_ARAPIndex.RedWord =2 then vWeb_ARAPIndex.totalinmoney else null end, 
      case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid,
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     null,
    vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 305 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)

UNION ALL
SELECT  
      '退货:' + ptype.FullName + ' ' + CAST(CAST(saleBackBill.Qty as float) AS varchar(10)) + '*' + CAST(CAST(saleBackBill.TaxPrice as float) AS varchar(20)), 
      ptype.FullName,
      case when vWeb_ARAPIndex.RedWord=2 then (saleBackBill.TaxTotal) else null end,
      case when vWeb_ARAPIndex.RedWord in(0,1) then (saleBackBill.TaxTotal) else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      saleBackBill.TeamNo, 
      saleBackBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      saleBackBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
     saleBackBill ON 
     vWeb_ARAPIndex.BillNumberId = saleBackBill.BillNumberId INNER JOIN
     ptype ON saleBackBill.PtypeId = ptype.typeId
WHERE (vWeb_ARAPIndex.BillType = 45)
--优惠金额
UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,	--2004-08-18 谢吉康 调换了和下面一条语句的顺序
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,

	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 45)

UNION ALL
SELECT 
     '付款:' + btype.FullName,
      btype.FullName,
      case when vWeb_ARAPIndex.RedWord in(0,1) then PayBill.total else null end, 
      case when vWeb_ARAPIndex.RedWord =2 then PayBill.total else null end, 
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      PayBill.TeamNo, 
      PayBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      PayBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      PayBill ON 
      vWeb_ARAPIndex.BillNumberId = PayBill.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 66)
--优惠金额
UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,	--2004-08-18 谢吉康 调换了和下面一条语句的顺序
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,
	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 66)
UNION ALL
SELECT 
     '返利执行:' + btype.FullName,
      btype.FullName,
      case when vWeb_ARAPIndex.RedWord =2 then Advantage.total else null end,       
      case when vWeb_ARAPIndex.RedWord in(0,1) then Advantage.total else null end,       
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      Advantage.TeamNo, 
      Advantage.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      Advantage.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      Advantage ON 
      vWeb_ARAPIndex.BillNumberId = Advantage.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 148)
UNION ALL
SELECT '付款:'+atype.FullName,
      NULL,
     CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     NULL,
     vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 148 AND vWeb_ARAPIndex.atypeid<>'' AND vWeb_ARAPIndex.totalinmoney<>0)


UNION ALL
SELECT 
     '价保执行:' + btype.FullName,
      btype.FullName,
      CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN PriceProtectBill.total ELSE NULL END,       
      CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN PriceProtectBill.total ELSE NULL END, 
	  vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      PriceProtectBill.TeamNo, 
      PriceProtectBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      PriceProtectBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      PriceProtectBill ON 
      vWeb_ARAPIndex.BillNumberId = PriceProtectBill.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 149)
--2004-3-10新增加
UNION ALL
SELECT '付款:'+atype.FullName,
      NULL,
     CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	 vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     NULL,
     vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 149 AND vWeb_ARAPIndex.atypeid<>'' AND vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL
SELECT 
     '委托代销结算:' + btype.FullName,
      btype.FullName,
      case when vWeb_ARAPIndex.RedWord in(0,1) then CommissionBill.TaxTotal else null end,             
      case when vWeb_ARAPIndex.RedWord =2 then CommissionBill.TaxTotal else null end,       
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      CommissionBill.TeamNo, 
      CommissionBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      CommissionBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      CommissionBill ON 
      vWeb_ARAPIndex.BillNumberId = CommissionBill.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 141)
UNION ALL
SELECT '收款:'+atype.FullName,
      NULL,
     CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     NULL,
     vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 141 AND vWeb_ARAPIndex.atypeid<>'' AND vWeb_ARAPIndex.totalinmoney<>0)


UNION ALL
SELECT 
     '受托代销结算:' + btype.FullName,
      btype.FullName,
      case when vWeb_ARAPIndex.RedWord =2 then CommissionBill.TaxTotal else null end,
      case when vWeb_ARAPIndex.RedWord in(0,1) then CommissionBill.TaxTotal else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      CommissionBill.TeamNo, 


      CommissionBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      CommissionBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      CommissionBill ON 
      vWeb_ARAPIndex.BillNumberId = CommissionBill.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 145)
UNION ALL
SELECT '付款:'+atype.FullName,
		NULL,     
		CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
		CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
		vWeb_ARAPIndex.BillDate, 
		vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
		vWeb_ARAPIndex.TeamNo,
		-1,--////////////////////////////////////////////标明该行为表头
		vWeb_ARAPIndex.btypeid, 
		vWeb_ARAPIndex.BillNumberId, 
		vWeb_ARAPIndex.BillType,
		NULL,
		vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 145 AND vWeb_ARAPIndex.atypeid<>'' AND vWeb_ARAPIndex.totalinmoney<>0)



UNION ALL
SELECT                        --#-01
     '获利执行:' + btype.FullName,
      btype.FullName,
      CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN Advantage.total ELSE NULL END,
	  CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN Advantage.total ELSE NULL END,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      Advantage.TeamNo, 
      Advantage.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      Advantage.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      Advantage ON 
      vWeb_ARAPIndex.BillNumberId = Advantage.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 150)

UNION ALL
SELECT '收款:'+atype.FullName,
      NULL,
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     NULL,
     vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 150 AND vWeb_ARAPIndex.atypeid<>'' AND vWeb_ARAPIndex.totalinmoney<>0)


UNION ALL
SELECT '付款:'+atype.FullName,
       null,
       case when vWeb_ARAPIndex.RedWord in(0,1)  then vWeb_ARAPIndex.totalinmoney else null end,
       case when vWeb_ARAPIndex.RedWord=2  then vWeb_ARAPIndex.totalinmoney else null end,
       vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      vWeb_ARAPIndex.TeamNo,
      -1,--////////////////////////////////////////////标明该行为表头
      vWeb_ARAPIndex.btypeid, 
      vWeb_ARAPIndex.BillNumberId, 
      vWeb_ARAPIndex.BillType,
      null,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 45 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)

UNION ALL
--应收减少，应付增加
SELECT 
      AdDebtBill.Comment,
      btype.FullName,
      case when vWeb_ARAPIndex.RedWord =2 then AdDebtBill.total else null end,
      case when vWeb_ARAPIndex.RedWord in(0,1) then AdDebtBill.total else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      AdDebtBill.TeamNo, 
      AdDebtBill.ID, 
      AdDebtBill.BtypeId,  
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      AdDebtBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex  INNER JOIN
      AdDebtBill ON 
      vWeb_ARAPIndex.BillNumberId = AdDebtBill.BillNumberId
     INNER JOIN
      btype ON AdDebtBill.BtypeId = btype.typeId
WHERE (vWeb_ARAPIndex.BillType in(115,128))
UNION ALL
SELECT '收款:' + btype.FullName,
      btype.FullName, 
      case when vWeb_ARAPIndex.RedWord =2 then gatheringBill.total else null end, 
      case when vWeb_ARAPIndex.RedWord in(0,1) then gatheringBill.total else null end, 
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      gatheringBill.TeamNo,
      gatheringBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      gatheringBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      gatheringBill ON 
      vWeb_ARAPIndex.BillNumberId = gatheringBill.BillNumberId INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId
WHERE (vWeb_ARAPIndex.BillType = 4)
UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,	
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,
	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 4)
--应收增加，应付减少
UNION ALL
SELECT 
      AdDebtBill.Comment,btype.FullName,
      case when vWeb_ARAPIndex.RedWord in(0,1)  then AdDebtBill.total else null end,

      case when vWeb_ARAPIndex.RedWord =2  then AdDebtBill.total else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      AdDebtBill.TeamNo, 
      AdDebtBill.ID, 
      AdDebtBill.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      AdDebtBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      AdDebtBill ON 
      vWeb_ARAPIndex.BillNumberId = AdDebtBill.BillNumberId
     INNER JOIN
      btype ON AdDebtBill.BtypeId = btype.typeId
WHERE (vWeb_ARAPIndex.BillType in(116,129))
--36费用单93其他收入单
UNION ALL
SELECT
             '费用单：'+MoneyBill.Comment, 
             atype.FullName, 
            case when vWeb_ARAPIndex.RedWord =2  then MoneyBill.total else null end, 
            case when vWeb_ARAPIndex.RedWord in(0,1)  then MoneyBill.total else null end, 
            vWeb_ARAPIndex.BillDate,
            vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
            MoneyBill.TeamNo, 
            MoneyBill.ID, 
            vWeb_ARAPIndex.btypeid, 
            vWeb_ARAPIndex.BillNumberId, 
           vWeb_ARAPIndex.BillType, 
           MoneyBill.TeamNo1,
           vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM MoneyBill INNER JOIN
      atype ON MoneyBill.AtypeId = atype.typeId INNER JOIN
      vWeb_ARAPIndex ON 
      MoneyBill.BillNumberId = vWeb_ARAPIndex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType =36)

UNION ALL
SELECT 
     ' 付款:'+atype.FullName,
     null,
      case when vWeb_ARAPIndex.RedWord in(0,1)  then vWeb_ARAPIndex.totalinmoney else null end, 
      case when vWeb_ARAPIndex.RedWord =2  then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,null,
     vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 36 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)

UNION ALL
SELECT 
       MoneyBill.Comment, 
       atype.FullName, 
      case when vWeb_ARAPIndex.RedWord in(0,1) then MoneyBill.total else null end,
      case when vWeb_ARAPIndex.RedWord =2 then MoneyBill.total else null end,

      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      MoneyBill.TeamNo,
      MoneyBill.ID,
      vWeb_ARAPIndex.btypeid, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType, 
      MoneyBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM MoneyBill INNER JOIN
      atype ON MoneyBill.AtypeId = atype.typeId INNER JOIN
      vWeb_ARAPIndex ON 
      MoneyBill.BillNumberId = vWeb_ARAPIndex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType =93)
UNION ALL
SELECT 
     ' 收款:'+atype.FullName,
     null,
     case when vWeb_ARAPIndex.RedWord =2  then vWeb_ARAPIndex.totalinmoney else null end, 
     case when vWeb_ARAPIndex.RedWord in(0,1)  then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,

     null,
     vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 93 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL
SELECT 
     '固定资产购买:' + btype.FullName,
      btype.FullName,
      case when vWeb_ARAPIndex.RedWord =2 then MoneyBill.total else null end,
      case when vWeb_ARAPIndex.RedWord in(0,1) then MoneyBill.total else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      MoneyBill.TeamNo, 
      MoneyBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      MoneyBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      MoneyBill ON 
      vWeb_ARAPIndex.BillNumberId = MoneyBill.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 84)
UNION ALL
SELECT ' 付款:'+atype.FullName,
      null,
     case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.totalinmoney else null end, 
     case when vWeb_ARAPIndex.RedWord =2 then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     null,
     vWeb_ARAPIndex.RedWord,
     vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 84 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL
SELECT 
     '固定资产变卖:' + btype.FullName,
      btype.FullName,
	  case when vWeb_ARAPIndex.RedWord in(0,1) then MoneyBill.total else null end,
	  case when vWeb_ARAPIndex.RedWord =2 then MoneyBill.total else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      MoneyBill.TeamNo, 
      MoneyBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      MoneyBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      MoneyBill ON 
      vWeb_ARAPIndex.BillNumberId = MoneyBill.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 85)
UNION ALL
SELECT 
     ' 收款:'+atype.FullName,
     null,
     case when vWeb_ARAPIndex.RedWord =2  then vWeb_ARAPIndex.totalinmoney else null end, 
     case when vWeb_ARAPIndex.RedWord in(0,1)  then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,

     null,
     vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 85 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)












































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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








CREATE  view vWeb_WLDZ_YH_TY_1
(	
	zy,
	fullName,
	ArAdd,
	ArReduce,
	BillDate,
	BillCode,
	etypeid,
	TeamNo,
	Id,
	Btypeid,
	BillNumberID,
	BillType,
	TeamNo1,
	RedWord,
	Comment
)
--@Encode$--
as
--商品维修受理单      157         收款
SELECT 
     '商品维修单:' + btype.FullName,
      btype.FullName,
	  case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.total else null end,
      case when vWeb_ARAPIndex.RedWord =2 then vWeb_ARAPIndex.total else null end,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      vWeb_ARAPIndex.TeamNo, 
      -1,--////////////////////////////////////////////标明该行为表头
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      null,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM  vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId 
WHERE (vWeb_ARAPIndex.BillType = 157)
UNION ALL
SELECT ' 收款:'+atype.FullName,
      null,      
     case when vWeb_ARAPIndex.RedWord =2 then vWeb_ARAPIndex.totalinmoney else null end, 
     case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid,
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     null,
    vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM  atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 157 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL                                 --#-01
SELECT 
     '获得价保:' + btype.FullName,
      btype.FullName,
      CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN PriceProtectBill.total ELSE NULL END, 
	  CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN PriceProtectBill.total ELSE NULL END,
      vWeb_ARAPIndex.BillDate, 
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
      PriceProtectBill.TeamNo, 
      PriceProtectBill.ID, 
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      PriceProtectBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM  vWeb_ARAPIndex INNER JOIN
      btype ON vWeb_ARAPIndex.BtypeId = btype.typeId INNER JOIN
      PriceProtectBill ON 
      vWeb_ARAPIndex.BillNumberId = PriceProtectBill.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 151)
--2004-3-10新增加
UNION ALL
SELECT '付款:'+atype.FullName,
      NULL,
     CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END,  
	 CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN vWeb_ARAPIndex.totalinmoney ELSE NULL END, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid, 
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     NULL,
     vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 151 AND vWeb_ARAPIndex.atypeid<>'' AND vWeb_ARAPIndex.totalinmoney<>0)
--2005-8-29 增加会计凭证单据 谢吉康
UNION ALL
SELECT	'应收:'+B.FullName,
		NULL,
		CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,
		CASE WHEN V.RedWord = 2 THEN ABS(V.Total) ELSE NULL END,
		V.BillDate,
		V.BillCode,
		V.ETypeId,
		V.TeamNo,
		-1,
		V.BTypeId,
		V.BillNumberId,
		V.BillType,
		NULL,
		V.RedWord,
		V.Comment 
FROM	vWeb_ARAPIndex V,
		BType B
WHERE	V.BTypeId = B.TypeId
		AND B.Deleted = 0
		AND B.SonNum = 0
		AND V.BillType = 159
		AND V.ATypeId = '0000100005'
UNION ALL
SELECT	'应付:'+B.FullName,		
		NULL,		
		CASE WHEN V.RedWord = 2 THEN ABS(V.Total) ELSE NULL END,
		CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,		
		V.BillDate,
		V.BillCode,
		V.ETypeId,
		V.TeamNo,
		-1,
		V.BTypeId,
		V.BillNumberId,
		V.BillType,
		NULL,
		V.RedWord,
		V.Comment 
FROM	vWeb_ARAPIndex V,
		BType B
WHERE	V.BTypeId = B.TypeId
		AND B.Deleted = 0
		AND B.SonNum = 0
		AND V.BillType = 159
		AND V.ATypeId = '0000200001'
UNION ALL
SELECT 
	 Case SaleGoodsExchangeBill.InOrOut
		when 'O' then
     		'销售换货出库:' + ptype.FullName + ' ' + cast(CAST(SaleGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(CAST(SaleGoodsExchangeBill.TaxPrice as float) AS varchar(20))
		when 'I' then
     		'销售换货入库:' + ptype.FullName + ' ' + cast(CAST(SaleGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(CAST(SaleGoodsExchangeBill.TaxPrice as float) AS varchar(20))
	  end,

      ptype.FullName, 
		case SaleGoodsExchangeBill.InOrOut
	    when 'O' then
            case when vWeb_ARAPIndex.RedWord in(0,1) then cast(CAST(SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when vWeb_ARAPIndex.RedWord=2 then cast(CAST(SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
      end,
      
	  case SaleGoodsExchangeBill.InOrOut
          when 'O' then
            case when vWeb_ARAPIndex.RedWord=2 then cast(CAST(SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when vWeb_ARAPIndex.RedWord in(0,1) then cast(CAST(SaleGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
		
      end,
      vWeb_ARAPIndex.BillDate,
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid,
      SaleGoodsExchangeBill.TeamNo,
      SaleGoodsExchangeBill.ID,
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      SaleGoodsExchangeBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM SaleGoodsExchangeBill INNER JOIN
      vWeb_ARAPIndex ON 
      SaleGoodsExchangeBill.BillNumberId = vWeb_ARAPIndex.BillNumberId INNER JOIN
      ptype ON SaleGoodsExchangeBill.PtypeId = ptype.typeId
WHERE (vWeb_ARAPIndex.BillType = 160)

UNION ALL
SELECT ' 收款:'+atype.FullName,
      null,
      case when vWeb_ARAPIndex.RedWord =2 then vWeb_ARAPIndex.totalinmoney else null end, 
      case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.totalinmoney else null end, 
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid,
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     null,
    vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 160 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)
UNION ALL
--优惠金额
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,
	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 160)
UNION ALL
SELECT 
	 Case BuyGoodsExchangeBill.InOrOut
		when 'O' then
     		'采购换货出库:' + ptype.FullName + ' ' + cast(CAST(BuyGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(CAST(BuyGoodsExchangeBill.TaxPrice as float) AS varchar(20))
		when 'I' then
     		'采购换货入库:' + ptype.FullName + ' ' + cast(CAST(BuyGoodsExchangeBill.Qty as float) as varchar(20)) + '*' + CAST(CAST(BuyGoodsExchangeBill.TaxPrice as float) AS varchar(20))
	  end,

      ptype.FullName, 
		case BuyGoodsExchangeBill.InOrOut
	    when 'O' then
            case when vWeb_ARAPIndex.RedWord in(0,1) then cast(CAST(BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when vWeb_ARAPIndex.RedWord=2 then cast(CAST(BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
      end,
      
	  case BuyGoodsExchangeBill.InOrOut
          when 'O' then
            case when vWeb_ARAPIndex.RedWord=2 then cast(CAST(BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
          when 'I' then
            case when vWeb_ARAPIndex.RedWord in(0,1) then cast(CAST(BuyGoodsExchangeBill.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
		
      end,
      vWeb_ARAPIndex.BillDate,
      vWeb_ARAPIndex.BillCode,vWeb_ARAPIndex.etypeid,
      BuyGoodsExchangeBill.TeamNo,
      BuyGoodsExchangeBill.ID,
      vWeb_ARAPIndex.BtypeId, 
      vWeb_ARAPIndex.BillNumberId,
      vWeb_ARAPIndex.BillType,
      BuyGoodsExchangeBill.TeamNo1,
      vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM BuyGoodsExchangeBill INNER JOIN
      vWeb_ARAPIndex ON 
      BuyGoodsExchangeBill.BillNumberId = vWeb_ARAPIndex.BillNumberId INNER JOIN
      ptype ON BuyGoodsExchangeBill.PtypeId = ptype.typeId
WHERE (vWeb_ARAPIndex.BillType = 161)
UNION ALL
SELECT ' 付款:'+atype.FullName,
      null,      
      case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.totalinmoney else null end, 
	  case when vWeb_ARAPIndex.RedWord =2 then vWeb_ARAPIndex.totalinmoney else null end, 	
     vWeb_ARAPIndex.BillDate, 
     vWeb_ARAPIndex.BillCode,
	 vWeb_ARAPIndex.etypeid, 
     vWeb_ARAPIndex.TeamNo,
     -1,--////////////////////////////////////////////标明该行为表头
     vWeb_ARAPIndex.btypeid,
     vWeb_ARAPIndex.BillNumberId, 
     vWeb_ARAPIndex.BillType,
     null,
    vWeb_ARAPIndex.RedWord,
	  vWeb_ARAPIndex.Comment
FROM atype INNER JOIN
      vWeb_ARAPIndex ON atype.typeId = vWeb_ARAPIndex.atypeid
WHERE (vWeb_ARAPIndex.BillType = 161 and vWeb_ARAPIndex.atypeid<>'' and vWeb_ARAPIndex.totalinmoney<>0)
--优惠金额
UNION ALL
SELECT 
	'优惠金额:',
	' ',
	CASE WHEN vWeb_ARAPIndex.RedWord IN(0,1) THEN  billindex.preferencemoney ELSE NULL END,
	CASE WHEN vWeb_ARAPIndex.RedWord =2 THEN billindex.preferencemoney ELSE NULL END,
	vWeb_ARAPIndex.BillDate, 
	vWeb_ARAPIndex.BillCode,
	vWeb_ARAPIndex.etypeid,
	vWeb_ARAPIndex.TeamNo,
	-1,
	vWeb_ARAPIndex.BtypeId, 
	BillIndex.BillNumberId,
	vWeb_ARAPIndex.BillType,
	' ',
	vWeb_ARAPIndex.RedWord,
	vWeb_ARAPIndex.Comment
FROM 
      vWeb_ARAPIndex 
	  INNER JOIN
	  billindex ON vWeb_ARAPIndex.BillNumberId = billindex.BillNumberId
WHERE (vWeb_ARAPIndex.BillType = 161)






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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







/****** Object:  View dbo.vWeb_WLDZ1    Script Date: 2002-6-20 10:14:43 ******/
CREATE view vWeb_WLDZ1(djlx,zy,ArAdd,ArReduce,BillDate,BillCode,Btypeid,BillNumberID,BillType,RedWord)
--@Encode$--
as
SELECT 
     '固定资产购买',dbo.vWeb_ARAPIndex.comment,
    case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         else null
         end,
    case
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
         else null
         end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM  dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType = 84)
union all
SELECT 
     '固定资产变卖',dbo.vWeb_ARAPIndex.comment,
    case
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
         else null
         end,
    case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         else null
         end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM  dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType = 85)
union all
SELECT 
     '销售单',dbo.vWeb_ARAPIndex.comment,
    case
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
         else null
         end,
    case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         else null
         end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM  dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType = 11)
union all
SELECT 
     '零售单',dbo.vWeb_ARAPIndex.comment,
    case
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
         else null
         end,
    case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney<0)  and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0)  and (vWeb_ARAPIndex.RedWord =2) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         else null
         end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM  dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType = 305)
union all
SELECT  
      '销售退货',dbo.vWeb_ARAPIndex.comment,
    case 
          when (dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
          when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
          else null
          end,
   case 
         when (dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
         when (dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
         else null  
         end,
    dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
    dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 45)
union all
SELECT 
     '进货单',dbo.vWeb_ARAPIndex.comment,
    case 
     when dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
     when dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
    else null  end,
    case
     when dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
     when dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total
     else null
     end,
     dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode,
     dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 34)
union all
SELECT  
      '进货退货',dbo.vWeb_ARAPIndex.comment,
    case 
    when dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1)  then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney 
    when dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
    else null   end,
    case 
     when dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.total 
    when dbo.vWeb_ARAPIndex.Totalinmoney-dbo.vWeb_ARAPIndex.totalinmoney>0 and dbo.vWeb_ARAPIndex.RedWord =2  then dbo.vWeb_ARAPIndex.Total-dbo.vWeb_ARAPIndex.totalinmoney
    else null   
    end,
     dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
     dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,dbo.vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 6)
union all
SELECT '销售收款',dbo.vWeb_ARAPIndex.comment,
     case when vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney else NULL end, 
      case when vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney else null end,  
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
      dbo.vWeb_ARAPIndex.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 4)
union all
SELECT '付款',dbo.vWeb_ARAPIndex.comment,
       case when vWeb_ARAPIndex.RedWord in(0,1) then vWeb_ARAPIndex.totalinmoney else null end,
       case when vWeb_ARAPIndex.RedWord=2 then vWeb_ARAPIndex.totalinmoney else null end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
WHERE (dbo.vWeb_ARAPIndex.BillType = 66)

union all
SELECT '返利执行',dbo.vWeb_ARAPIndex.comment,
      case 
        when (dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
        when (dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney
        else null
        end,
      case 
        when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
        when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total 
        else null 
        end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =148)

union all
SELECT '价保执行',dbo.vWeb_ARAPIndex.comment,
      case 
        when (dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
        when (dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney
        else null
        end,
      case 
        when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
        when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total 
        else null 
        end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =149)

union all
SELECT '委托代销结算',dbo.vWeb_ARAPIndex.comment,
      case 
        when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
        when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total 
        else null
        end,
      case 
        when (dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
        when (dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney
        else null 
        end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =141)

union all
SELECT '受托代销结算',dbo.vWeb_ARAPIndex.comment,
      case 
        when (dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
        when (dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney
        else null
        end,
      case 
        when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
        when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total 
        else null 
        end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =145)

union all
SELECT '获利执行',dbo.vWeb_ARAPIndex.comment,
      case 
        when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
        when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total 
        else null
        end,
      case 
        when (dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
        when (dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney
        else null 
        end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =150)

union all
SELECT 
      '调帐(应收减少)',dbo.AdDebtBill.comment,
      case when vWeb_ARAPIndex.RedWord =2 then dbo.AdDebtBill.total else null end,   
      case when vWeb_ARAPIndex.RedWord in(0,1) then dbo.AdDebtBill.total else null end,   
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
      dbo.AdDebtBill.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
     INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId 
WHERE (dbo.vWeb_ARAPIndex.BillType in(115,128))
union all
SELECT 
      '调帐(应收增加)',dbo.AdDebtBill.comment,
      case when vWeb_ARAPIndex.RedWord in(0,1) then dbo.AdDebtBill.total else null end,
      case when vWeb_ARAPIndex.RedWord=2 then  dbo.AdDebtBill.total else null end,
      dbo.vWeb_ARAPIndex.BillDate, dbo.vWeb_ARAPIndex.BillCode, 
      dbo.AdDebtBill.BtypeId, dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex
      INNER JOIN
      dbo.AdDebtBill ON 
      dbo.vWeb_ARAPIndex.BillNumberId = dbo.AdDebtBill.BillNumberId
WHERE (dbo.vWeb_ARAPIndex.BillType in(116,129))
--36费用单93其他收入单
union all
SELECT '费用单',dbo.vWeb_ARAPIndex.comment,
      case 
        when (dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
        when (dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord =2 then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney
        else null
        end,
      case 
        when dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0 and vWeb_ARAPIndex.RedWord in(0,1) then dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
        when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and vWeb_ARAPIndex.RedWord=2 then dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total 
        else null 
        end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =36)
union all
SELECT '其他收入单',dbo.vWeb_ARAPIndex.comment,
      case 
      when (dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord in(0,1) then  dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
      when (dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0) and vWeb_ARAPIndex.RedWord=2 then  dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
      else null end,
      case 
      when dbo.vWeb_ARAPIndex.totalinmoney-vWeb_ARAPIndex.total>0 and vWeb_ARAPIndex.RedWord in(0,1)  then  dbo.vWeb_ARAPIndex.totalinmoney-dbo.vWeb_ARAPIndex.total
      when (dbo.vWeb_ARAPIndex.total-vWeb_ARAPIndex.totalinmoney>0) and vWeb_ARAPIndex.RedWord=2 then  dbo.vWeb_ARAPIndex.total-dbo.vWeb_ARAPIndex.totalinmoney 
      else null
      end,
      dbo.vWeb_ARAPIndex.BillDate, 
      dbo.vWeb_ARAPIndex.BillCode,dbo.vWeb_ARAPIndex.BtypeId, 
      dbo.vWeb_ARAPIndex.BillNumberId,dbo.vWeb_ARAPIndex.BillType,vWeb_ARAPIndex.RedWord
FROM dbo.vWeb_ARAPIndex 
WHERE (dbo.vWeb_ARAPIndex.BillType =93)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_CombinePtypeSearchByConfig]') and xtype in (N'FN', N'IF', N'TF'))
	DROP FUNCTION dbo.[F_CombinePtypeSearchByConfig]
GO
--==========================================================
--BY:zy
--DATE:2017-07-11
--DESCRIPTION:选商品根据配置来进行匹配
--==========================================================
CREATE FUNCTION F_CombinePtypeSearchByConfig
(
	@chvMode 			varchar(50) = '',  ---标示商品列检索：usercode/fullname
	@chvUserCode 		varchar(500) = '',  ---商品编码
	@chvEntryCode 		varchar(500) = '',   ---商品条码
	@standard			VARCHAR(200)='',		--商品规格
	@chvFullName 		varchar(500) = '',   ---商品名称
	@chvType 			varchar(500) = '',   ---商品型号
	@MultiCode			varchar(1)='0'  ---是否启用多编码
)
RETURNS NVARCHAR(MAX)
--@encode$--

AS
BEGIN
	DECLARE @tempSQL NVARCHAR(MAX)='';
	DECLARE @beforeoperatesign VARCHAR(50)='',@afteroperatesign VARCHAR(50)='';
	DECLARE @usercodeSQL VARCHAR(800)='',@fullnameSQL VARCHAR(800)='';
	DECLARE @searchValue VARCHAR(800)='';
	DECLARE @entrycodeflag INT;
	
	--精确匹配
	IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='bill_ptypeexactmatching' AND [Value]='1')
	BEGIN
		SET @beforeoperatesign='LIKE ''%';
		SET @afteroperatesign='%'' ';
		SET @entrycodeflag=2;
	END
	
	--模糊匹配
	ELSE
	BEGIN
		SET @beforeoperatesign='LIKE ''%';
		SET @afteroperatesign='%'' ';
		SET @entrycodeflag=2;
	END	

	--根据商品编码检索
	IF @chvMode ='usercode' AND @chvUserCode <> ''
	BEGIN
		SELECT @searchValue=[Value] FROM Userconfig WHERE ConfigName='bill_filterptypecode' 
		
		IF (LEN(@searchValue)>0)
		BEGIN
		
			SET @usercodeSQL=@beforeoperatesign+@chvUserCode+@afteroperatesign;
			
			--编码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='usercode')
			BEGIN
				SET @tempSQL += 'OR p.UserCode '+@usercodeSQL;
			END
			--条码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='entrycode')
			BEGIN
				IF(@entrycodeflag=1)
					BEGIN
						SET @tempSQL+='OR P.EntryCode='''+@chvUserCode+'''
						OR EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=P.TypeId AND E.EntryCode='''+@chvUserCode+''')
						OR EXISTS(SELECT TOP 1 1 FROM PType_Units_EntryCode_Ext PE WHERE PE.Ptypeid=P.TypeId AND PE.EntryCode='''+@chvUserCode+''')'
					END
				ELSE IF(@entrycodeflag=2)
					BEGIN
						SET @tempSQL+='OR P.EntryCode LIKE ''%'+@chvUserCode+'%''
						OR EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=P.TypeId AND E.EntryCode LIKE ''%'+@chvUserCode+'%'')
						OR EXISTS(SELECT TOP 1 1 FROM PType_Units_EntryCode_Ext PE WHERE PE.Ptypeid=P.TypeId AND PE.EntryCode LIKE ''%'+@chvUserCode+'%'')'
					END				
			END
			--规格
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='standard')
			BEGIN
				SET @tempSQL += 'OR p.Standard '+@usercodeSQL;
			END
			--拼音码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='pycode')
			BEGIN
				SET @tempSQL += 'OR p.PyCode '+@usercodeSQL;
			END
			--多编码
			IF (@MultiCode='1')
			BEGIN
				SET @tempSQL += 'OR u.UserCode '+@usercodeSQL;
			END
			--名称
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='fullname')
			BEGIN
				SET @tempSQL += 'OR p.FullName '+@usercodeSQL;
			END
			--型号
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='type')
			BEGIN
				SET @tempSQL += 'OR p.Type '+@usercodeSQL;
			END
		END
		ELSE
		BEGIN
			IF @MultiCode = '1' --使用多编码
			BEGIN
			SET @tempSQL += '   p.UserCode LIKE ''%'+@chvUserCode+'%'' 
 									OR p.PyCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvUserCode + ''',2))
    								OR u.UserCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.Type LIKE ''%'+@chvUserCode+'%'' 
									OR p.Standard LIKE ''%'+@chvUserCode+'%''';
			END
			ELSE
			BEGIN
			SET @tempSQL += '   p.UserCode LIKE ''%'+@chvUserCode+'%'' 
 									OR p.PyCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvUserCode + ''',2))
    								OR p.Type LIKE ''%'+@chvUserCode+'%'' 
									OR p.Standard LIKE ''%'+@chvUserCode+'%''';
			END	
		END
	END
	
	--根据商品名称检索
	IF @chvMode ='fullname' AND @chvFullName <> ''
	BEGIN
		SELECT @searchValue=[Value] FROM Userconfig WHERE ConfigName='bill_filterptypename' 
		
		IF (LEN(@searchValue)>0)
		BEGIN
		
			SET @fullnameSQL=@beforeoperatesign+@chvFullName+@afteroperatesign;
			
			--编码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='usercode')
			BEGIN
				SET @tempSQL += 'OR p.UserCode '+@fullnameSQL;
			END
			--条码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='entrycode')
			BEGIN
				IF(@entrycodeflag=1)
					BEGIN
						SET @tempSQL+='OR P.EntryCode='''+@chvFullName+'''
						OR EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=P.TypeId AND E.EntryCode='''+@chvFullName+''')
						OR EXISTS(SELECT TOP 1 1 FROM PType_Units_EntryCode_Ext PE WHERE PE.Ptypeid=P.TypeId AND PE.EntryCode='''+@chvFullName+''')'
					END
				ELSE IF(@entrycodeflag=2)
					BEGIN
						SET @tempSQL+='OR P.EntryCode LIKE ''%'+@chvFullName+'%''
						OR EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=P.TypeId AND E.EntryCode LIKE ''%'+@chvFullName+'%'')
						OR EXISTS(SELECT TOP 1 1 FROM PType_Units_EntryCode_Ext PE WHERE PE.Ptypeid=P.TypeId AND PE.EntryCode LIKE ''%'+@chvFullName+'%'')'
					END
			END
			--规格
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='standard')
			BEGIN
				SET @tempSQL += 'OR p.Standard '+@fullnameSQL;
			END
			--拼音码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='pycode')
			BEGIN
				SET @tempSQL += 'OR p.PyCode '+@fullnameSQL;
			END
			--名称
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='fullname')
			BEGIN
				SET @tempSQL += 'OR p.FullName '+@fullnameSQL;
			END
			--型号
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='type')
			BEGIN
				SET @tempSQL += 'OR p.Type '+@fullnameSQL;
			END
		END
		ELSE
		BEGIN
			SET @tempSQL += '   p.FullName LIKE ''%'+@chvFullName+'%'' 
								OR p.PyCode LIKE ''%' + @chvFullName + '%''
								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvFullName + ''',2))
								OR p.Type LIKE ''%'+@chvFullName+'%'' 
								OR p.Standard LIKE ''%'+@chvFullName+'%''';
		END
	END				
	
	IF LEN(@tempSQL)>3
	BEGIN
		SET @tempSQL=' AND ( '+substring(@tempSQL,3,len(@tempSQL))+' ) ';
	END
	RETURN @tempSQL
END

GO	
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_CombinePtypeSearchByConfigForSearchOneP]') and xtype in (N'FN', N'IF', N'TF'))
	DROP FUNCTION dbo.[F_CombinePtypeSearchByConfigForSearchOneP]
GO
--==========================================================
--BY:zy
--DATE:2017-07-11
--DESCRIPTION:选商品根据配置来进行匹配
--==========================================================
CREATE FUNCTION F_CombinePtypeSearchByConfigForSearchOneP
(
	@chvMode 			varchar(50) = '',  ---标示商品列检索：usercode/fullname
	@chvUserCode 		varchar(500) = '',  ---商品编码
	@chvEntryCode 		varchar(500) = '',   ---商品条码
	@standard			VARCHAR(200)='',		--商品规格
	@chvFullName 		varchar(500) = '',   ---商品名称
	@chvType 			varchar(500) = '',   ---商品型号
	@MultiCode			varchar(1)='0'  ---是否启用多编码
)
RETURNS NVARCHAR(MAX)
--@encode$--

AS
BEGIN
	DECLARE @tempSQL NVARCHAR(MAX)='';
	DECLARE @beforeoperatesign VARCHAR(50)='',@afteroperatesign VARCHAR(50)='';
	DECLARE @usercodeSQL VARCHAR(800)='',@fullnameSQL VARCHAR(800)='';
	DECLARE @searchValue VARCHAR(800)='';
	DECLARE @entrycodeflag INT;
	
	--精确匹配
	IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='bill_ptypeexactmatching' AND [Value]='1')
	BEGIN
		SET @beforeoperatesign='LIKE ''%';
		SET @afteroperatesign='%'' ';
		SET @entrycodeflag=2;
	END
	
	--模糊匹配
	ELSE
	BEGIN
		SET @beforeoperatesign='LIKE ''%';
		SET @afteroperatesign='%'' ';
		SET @entrycodeflag=2;
	END	

	--根据商品编码检索
	IF @chvMode ='usercode' AND @chvUserCode <> ''
	BEGIN
		SELECT @searchValue=[Value] FROM Userconfig WHERE ConfigName='bill_filterptypecode' 
		
		IF (LEN(@searchValue)>0)
		BEGIN
		
			SET @usercodeSQL=@beforeoperatesign+@chvUserCode+@afteroperatesign;
			
			--编码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='usercode')
			BEGIN
				SET @tempSQL += 'OR p.UserCode '+@usercodeSQL;
			END
			--条码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='entrycode')
			BEGIN
				IF(@entrycodeflag=1)
					BEGIN
						SET @tempSQL+='OR P.EntryCode='''+@chvUserCode+'''
						OR EXISTS(SELECT TOP 1 1 FROM #PType_EntryCode E WHERE E.Ptypeid=P.TypeId )
						'
					END
				ELSE IF(@entrycodeflag=2)
					BEGIN
						SET @tempSQL+='OR P.EntryCode LIKE ''%'+@chvUserCode+'%''
						OR EXISTS(SELECT TOP 1 1 FROM #PType_EntryCode E WHERE E.Ptypeid=P.TypeId )
						'
					END				
			END
			--规格
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='standard')
			BEGIN
				SET @tempSQL += 'OR p.Standard '+@usercodeSQL;
			END
			--拼音码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='pycode')
			BEGIN
				SET @tempSQL += 'OR p.PyCode '+@usercodeSQL;
			END
			--多编码
			IF (@MultiCode='1')
			BEGIN
				SET @tempSQL += 'OR u.UserCode '+@usercodeSQL;
			END
			--名称
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='fullname')
			BEGIN
				SET @tempSQL += 'OR p.FullName '+@usercodeSQL;
			END
			--型号
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='type')
			BEGIN
				SET @tempSQL += 'OR p.Type '+@usercodeSQL;
			END
		END
		ELSE
		BEGIN
			IF @MultiCode = '1' --使用多编码
			BEGIN
			SET @tempSQL += '   p.UserCode LIKE ''%'+@chvUserCode+'%'' 
 									OR p.PyCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvUserCode + ''',2))
    								OR u.UserCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.Type LIKE ''%'+@chvUserCode+'%'' 
									OR p.Standard LIKE ''%'+@chvUserCode+'%''';
			END
			ELSE
			BEGIN
			SET @tempSQL += '   p.UserCode LIKE ''%'+@chvUserCode+'%'' 
 									OR p.PyCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvUserCode + ''',2))
    								OR p.Type LIKE ''%'+@chvUserCode+'%'' 
									OR p.Standard LIKE ''%'+@chvUserCode+'%''';
			END	
		END
	END
	
	--根据商品名称检索
	IF @chvMode ='fullname' AND @chvFullName <> ''
	BEGIN
		SELECT @searchValue=[Value] FROM Userconfig WHERE ConfigName='bill_filterptypename' 
		
		IF (LEN(@searchValue)>0)
		BEGIN
		
			SET @fullnameSQL=@beforeoperatesign+@chvFullName+@afteroperatesign;
			
			--编码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='usercode')
			BEGIN
				SET @tempSQL += 'OR p.UserCode '+@fullnameSQL;
			END
			--条码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='entrycode')
			BEGIN
				IF(@entrycodeflag=1)
					BEGIN
						SET @tempSQL+='OR P.EntryCode='''+@chvFullName+'''
						OR EXISTS(SELECT TOP 1 1 FROM #PType_EntryCode E WHERE E.Ptypeid=P.TypeId )
						'
					END
				ELSE IF(@entrycodeflag=2)
					BEGIN
						SET @tempSQL+='OR P.EntryCode LIKE ''%'+@chvFullName+'%''
						OR EXISTS(SELECT TOP 1 1 FROM #PType_EntryCode E WHERE E.Ptypeid=P.TypeId )
						'
					END
			END
			--规格
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='standard')
			BEGIN
				SET @tempSQL += 'OR p.Standard '+@fullnameSQL;
			END
			--拼音码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='pycode')
			BEGIN
				SET @tempSQL += 'OR p.PyCode '+@fullnameSQL;
			END
			--名称
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='fullname')
			BEGIN
				SET @tempSQL += 'OR p.FullName '+@fullnameSQL;
			END
			--型号
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='type')
			BEGIN
				SET @tempSQL += 'OR p.Type '+@fullnameSQL;
			END
		END
		ELSE
		BEGIN
			SET @tempSQL += '   p.FullName LIKE ''%'+@chvFullName+'%'' 
								OR p.PyCode LIKE ''%' + @chvFullName + '%''
								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvFullName + ''',2))
								OR p.Type LIKE ''%'+@chvFullName+'%'' 
								OR p.Standard LIKE ''%'+@chvFullName+'%''';
		END
	END				
	
	IF LEN(@tempSQL)>3
	BEGIN
		SET @tempSQL=' AND ( '+substring(@tempSQL,3,len(@tempSQL))+' ) ';
	END
	RETURN @tempSQL
END

GO	
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_CombinePtypeSearchByConfigNew]') and xtype in (N'FN', N'IF', N'TF'))
	DROP FUNCTION dbo.[F_CombinePtypeSearchByConfigNew]
GO
--==========================================================
--BY:zy
--DATE:2017-07-11
--DESCRIPTION:选商品根据配置来进行匹配
--==========================================================
CREATE FUNCTION F_CombinePtypeSearchByConfigNew
(
	@chvMode 			varchar(50) = '',  ---标示商品列检索：usercode/fullname
	@chvUserCode 		varchar(500) = '',  ---商品编码
	@chvEntryCode 		varchar(500) = '',   ---商品条码
	@standard			VARCHAR(200)='',		--商品规格
	@chvFullName 		varchar(500) = '',   ---商品名称
	@chvType 			varchar(500) = '',   ---商品型号
	@MultiCode			varchar(1)='0',  ---是否启用多编码
	@Flag				INT=0  --查询条件运算符 0:根据配置进行选择 1:使用=号
)
RETURNS NVARCHAR(MAX)
--@encode$--

AS
BEGIN
	DECLARE @tempSQL NVARCHAR(MAX)='';
	DECLARE @beforeoperatesign VARCHAR(50)='',@afteroperatesign VARCHAR(50)='';
	DECLARE @usercodeSQL VARCHAR(800)='',@fullnameSQL VARCHAR(800)='';
	DECLARE @searchValue VARCHAR(800)='';
	DECLARE @entrycodeflag INT;
	
	IF @Flag = 0
	BEGIN
		--精确匹配
		IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='bill_ptypeexactmatching' AND [Value]='1')
		BEGIN
			SET @beforeoperatesign='LIKE ''%';
			SET @afteroperatesign='%'' ';
			SET @entrycodeflag=2;
		END
		
		--模糊匹配
		ELSE
		BEGIN
			SET @beforeoperatesign='LIKE ''%';
			SET @afteroperatesign='%'' ';
			SET @entrycodeflag=2;
		END	
	END 
	ELSE
	BEGIN
			SET @beforeoperatesign='= ''';
			SET @afteroperatesign=''' ';
			SET @entrycodeflag=1;
	END 

	--根据商品编码检索
	IF @chvMode ='usercode' AND @chvUserCode <> ''
	BEGIN
		SELECT @searchValue=[Value] FROM Userconfig WHERE ConfigName='bill_filterptypecode' 
		
		IF (LEN(@searchValue)>0)
		BEGIN
		
			SET @usercodeSQL=@beforeoperatesign+@chvUserCode+@afteroperatesign;
			
			--编码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='usercode')
			BEGIN
				SET @tempSQL += 'OR p.UserCode '+@usercodeSQL;
			END
			--条码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='entrycode')
			BEGIN
				SET @tempSQL += 'OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycodeForSearch(''' + @chvUserCode + ''','+cast(@entrycodeflag AS varchar(1))+')) ';
			END
			--规格
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='standard')
			BEGIN
				SET @tempSQL += 'OR p.Standard '+@usercodeSQL;
			END
			--拼音码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='pycode')
			BEGIN
				SET @tempSQL += 'OR p.PyCode '+@usercodeSQL;
			END
			--多编码
			IF (@MultiCode='1')
			BEGIN
				SET @tempSQL += 'OR u.UserCode '+@usercodeSQL;
			END
			--名称
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='fullname')
			BEGIN
				SET @tempSQL += 'OR p.FullName '+@usercodeSQL;
			END
			--型号
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='type')
			BEGIN
				SET @tempSQL += 'OR p.Type '+@usercodeSQL;
			END
		END
		ELSE
		BEGIN
			IF @MultiCode = '1' --使用多编码
			BEGIN
			SET @tempSQL += '   p.UserCode LIKE ''%'+@chvUserCode+'%'' 
 									OR p.PyCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvUserCode + ''',2))
    								OR u.UserCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.Type LIKE ''%'+@chvUserCode+'%'' 
									OR p.Standard LIKE ''%'+@chvUserCode+'%''';
			END
			ELSE
			BEGIN
			SET @tempSQL += '   p.UserCode LIKE ''%'+@chvUserCode+'%'' 
 									OR p.PyCode LIKE ''%'+@chvUserCode+'%'' 
    								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvUserCode + ''',2))
    								OR p.Type LIKE ''%'+@chvUserCode+'%'' 
									OR p.Standard LIKE ''%'+@chvUserCode+'%''';
			END	
		END
	END
	
	--根据商品名称检索
	IF @chvMode ='fullname' AND @chvFullName <> ''
	BEGIN
		SELECT @searchValue=[Value] FROM Userconfig WHERE ConfigName='bill_filterptypename' 
		
		IF (LEN(@searchValue)>0)
		BEGIN
		
			SET @fullnameSQL=@beforeoperatesign+@chvFullName+@afteroperatesign;
			
			--编码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='usercode')
			BEGIN
				SET @tempSQL += 'OR p.UserCode '+@fullnameSQL;
			END
			--条码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='entrycode')
			BEGIN
				SET @tempSQL += 'OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycodeForSearch(''' + @chvFullName + ''','+cast(@entrycodeflag AS varchar(1))+')) ';
			END
			--规格
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='standard')
			BEGIN
				SET @tempSQL += 'OR p.Standard '+@fullnameSQL;
			END
			--拼音码
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='pycode')
			BEGIN
				SET @tempSQL += 'OR p.PyCode '+@fullnameSQL;
			END
			--名称
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='fullname')
			BEGIN
				SET @tempSQL += 'OR p.FullName '+@fullnameSQL;
			END
			--型号
			IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(lower(@searchValue),',') WHERE a='type')
			BEGIN
				SET @tempSQL += 'OR p.Type '+@fullnameSQL;
			END
		END
		ELSE
		BEGIN
			SET @tempSQL += '   p.FullName LIKE ''%'+@chvFullName+'%'' 
								OR p.PyCode LIKE ''%' + @chvFullName + '%''
								OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @chvFullName + ''',2))
								OR p.Type LIKE ''%'+@chvFullName+'%'' 
								OR p.Standard LIKE ''%'+@chvFullName+'%''';
		END
	END				
	
	IF LEN(@tempSQL)>3
	BEGIN
		SET @tempSQL=' AND ( '+substring(@tempSQL,3,len(@tempSQL))+' ) ';
	END
	RETURN @tempSQL
END

GO	
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAc_Items]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAc_Items]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION F_GetAc_Items
(
	@BillNumberId			varchar(100),
	@eid                    varchar(max)
	
)

RETURNS varchar(500)
AS
begin

declare @str varchar(max),
        @flag varchar(50)

select @str=''

SELECT @flag=SUBSTRING(lim,166,1) FROM dbo.loginuser WHERE etypeid = @eid--取操作员是否有权限查看成本
if(@flag='1')
select @str=@str+' '+b.FullName+':'+CONVERT(VARCHAR(50),cast(round(a.NTotalMoney,2) as  NUMERIC(24, 10)  ))+char(13)+char(10) from BillMulAccount a
inner join Ac_Items b on a.ATypeID=b.nId
where a.BillNumberId=@BillNumberId
else
select @str=@str+' '+b.FullName+': ****'+char(13)+char(10) from BillMulAccount a
inner join Ac_Items b on a.ATypeID=b.nId
where a.BillNumberId=@BillNumberId

return (char(13)+@str+char(13)+char(10))

end

go



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if EXISTS(SELECT 1 FROM sysobjects WHERE id=object_id('dbo.F_GetAcVoucherCommonly_Assist_CheckItems_Str') and objectproperty(id,'IsInlineFunction')=0)  
BEGIN
	DROP FUNCTION dbo.F_GetAcVoucherCommonly_Assist_CheckItems_Str
END
GO
/************************************************************
 * 创 建 人：罗淮文
 * 创建时间: 2014/4/18 11:19:43
 * 内容描述：常用凭证模板辅助核算转换
 ************************************************************/
CREATE FUNCTION dbo.F_GetAcVoucherCommonly_Assist_CheckItems_Str(@billnumberid VARCHAR(2000),@rowno VARCHAR(200),@OperatorId VARCHAR(200)='00001',@assistcontrol INT=1)
RETURNS VARCHAR(2000)
WITH EXECUTE AS caller
AS
BEGIN
	DECLARE @Str VARCHAR(2000)
	SET @Str = ''
	SELECT	@str +='【'+aa.Fullname+'】：'+
			CASE avb.typeName
			WHEN '01' THEN 
			(
				CASE WHEN @OperatorId<>'00001' AND
				NOT EXISTS(SELECT 1 FROM F_AllTreeS(@OperatorId) WHERE typeid=avb.TypeId) AND @assistcontrol=0 THEN '****'
				ELSE
				(
					SELECT FullName FROM SType WHERE TypeId = avb.TypeId
				)END
			)
			WHEN '02' THEN 
			(
				CASE WHEN @OperatorId<>'00001' AND
				NOT EXISTS(SELECT 1 FROM F_LineD(@OperatorId) WHERE typeid=avb.TypeId) AND @assistcontrol=0 THEN '****'
				ELSE
				(
			
					SELECT FullName FROM Department WHERE TypeId = avb.TypeId
				)END
			)
			WHEN '03' THEN 
			(
				CASE WHEN @OperatorId<>'00001' AND
				NOT EXISTS(SELECT 1 FROM F_LineE(@OperatorId) WHERE typeid=avb.TypeId) AND @assistcontrol=0 THEN '****'
				ELSE
				(
					SELECT FullName FROM employee WHERE TypeId = avb.TypeId
				)END
			)
			WHEN '04' THEN 
			(
				CASE WHEN @OperatorId<>'00001' AND
				NOT EXISTS (SELECT 1 FROM F_LineB(@OperatorId) where typeid=avb.TypeId) AND @assistcontrol=0 THEN '****'
				ELSE 
				(
					SELECT FullName FROM BType b
					WHERE b.TypeId = avb.TypeId  
				)END
			)
			ELSE 
			(
				ISNULL((SELECT FULLNAME FROM Ac_Assist_CheckItemsDetail WHERE TYPEID=AVB.TYPEID),'')
			)
			END + '；'
	FROM	Ac_Assist_CheckItems aa
			LEFT JOIN Ac_VoucherCommonly_Bill_Assist_CheckItems avb ON aa.UserCode = avb.typeName
			LEFT JOIN Ac_Voucher_Commonly_Bill av ON avb.BillNumberId = av.BillNumberId AND avb.vBId = av.ID
	WHERE	av.BillNumberId = @billnumberid and RowNo = @rowno
	
	SELECT @Str = LEFT(@Str,LEN(@Str)-1) WHERE @Str != ''
	RETURN @Str
END

GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getallcolumns]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_getallcolumns]
GO


--实现查询表的所有列功能 的函数
--date    :2012-5-08
CREATE FUNCTION f_getallcolumns
(
	@tablename varchar(500)
)
returns nvarchar(max) 
AS 
BEGIN
    DECLARE @a VARCHAR(MAX)=''
	SELECT @a=@a+a.name+',' FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID WHERE b.Name=@tablename
	SET @a=SUBSTRING(@a,1,LEN(@a)-1)
    RETURN @a
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetAllEntrycode]') and xtype in (N'FN', N'IF', N'TF'))
	DROP FUNCTION dbo.[F_GetAllEntrycode]
GO
--==========================================================
--BY:zy
--DATE:2017-08-16
--DESCRIPTION:获取商品多条码或者单位多条码
--==========================================================
CREATE FUNCTION F_GetAllEntrycode
(
	@PtypeID VARCHAR(50),
	@UnitsId INT=0,
	@searchflag INT    ----1:商品多条码，2:单位多条码
)
RETURNS NVARCHAR(MAX)
--@encode$--

AS
BEGIN
DECLARE @tempSQL NVARCHAR(MAX)='';
IF (@searchflag = 1)
BEGIN	
	SELECT @tempSQL = stuff
			((SELECT     ';' + t.EntryCode
            FROM     PType_EntryCode_Ext AS t
            WHERE t.Ptypeid=A.Ptypeid ORDER BY t.IsDefaultEntryCode DESC,t.Nid FOR xml path('')), 1, 1, '')
			FROM PType_EntryCode_Ext A
			WHERE A.Ptypeid=@PtypeID
			GROUP BY A.Ptypeid
END
IF (@searchflag = 2)
BEGIN
	SELECT @tempSQL = stuff
			((SELECT     ';' + t.EntryCode
            FROM     PType_Units_EntryCode_Ext AS t
            WHERE t.Ptypeid=A.Ptypeid and t.UnitsId=A.UnitsId ORDER BY t.IsDefaultEntryCode DESC,t.Nid FOR xml path('')), 1, 1, '')
			FROM PType_Units_EntryCode_Ext A
			WHERE A.Ptypeid=@PtypeID AND A.UnitsId=@UnitsId
			GROUP BY A.Ptypeid,A.UnitsId
END

RETURN @tempSQL
END

GO	
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllotBillExecState]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetAllotBillExecState
GO

-- ========================================================================
-- 功能说明：获取调货单执行状态
-- 作者：寇晨 
-- 时间：2016-11-07
-- ========================================================================
CREATE  FUNCTION  F_GetAllotBillExecState
(
	@billnumberid  NUMERIC(10, 0)
)
RETURNS INT
AS  
BEGIN 

	DECLARE @execstate INT
	DECLARE @mexecqty NUMERIC(24,10)
	DECLARE @sexecqty NUMERIC(24,10)
	DECLARE @billqty NUMERIC(24,10)
	DECLARE @Isdone INT

	SET @mexecqty = (SELECT ISNULL(SUM(m.qty),0)
						FROM (SELECT Qty,AllotID FROM dbo.MoveBill m 
						INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
						WHERE bi.RedWord=0 --AND bi.draft=0 --引用要算草稿
						UNION ALL SELECT Qty,AllotID FROM dbo.MoveBjBill m
						INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
						WHERE bi.RedWord=0 --AND bi.draft=0 --引用要算草稿
						) m
						INNER JOIN dbo.PosAllotApplyBill pb ON pb.ID=m.AllotID WHERE pb.BillNumberId=@billnumberid)
	SET @sexecqty = (SELECT ISNULL(SUM(s.Qty),0) FROM dbo.STypeMoveBill s 
					 INNER JOIN dbo.BillIndex bi ON s.BillNumberId=bi.BillNumberId
					 INNER JOIN dbo.PosAllotApplyBill pb ON pb.ID=s.AllotID
					  WHERE pb.BillNumberId=@billnumberid AND bi.RedWord=0 
					  --AND bi.draft=0--引用要算草稿
					  )
	SET @billqty = (SELECT qty FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId=@billnumberid)
	SET @Isdone = (SELECT isdone FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId=@billnumberid)
	
	IF(@Isdone=1)
		SET @execstate=1		--已完成
	ELSE IF((@mexecqty>0 OR @sexecqty>0) and @Isdone=0  )
		SET @execstate=2		--已引用未完成
	ELSE
		SET @execstate=3		--未引用
		
	RETURN @execstate

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllTime]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllTime]
GO
/*
	作者：郑红霞
	日期：2012-02-09
	描述：得到某个时间段的所有天数
*/
CREATE  FUNCTION [dbo].[F_GetAllTime]
(
	@StartDate		DATETIME,	
	@EndDate		DATETIME
)	
RETURNS @result TABLE(times DATETIME)
--@Encode$--
AS
Begin
WHILE @StartDate <= @EndDate
BEGIN
  INSERT INTO @result(times) VALUES (@StartDate) 
  SET @StartDate =  DATEADD(DAY,1,@StartDate)
END
	RETURN
END

GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetATypeTotalBy_nTypeId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetATypeTotalBy_nTypeId]
GO

/*

功能说明：       根据nTypeid STypeID获得AType_Total

作    者：       tangtao

创建日期：       2014-01-22 

返回结果：        NUMERIC(24, 10) 

*/
CREATE FUNCTION F_GetATypeTotalBy_nTypeId
(
	@nTypeid VARCHAR(8000) ,
	@STypeID VARCHAR(8000) 
)
RETURNS  NUMERIC(24, 10) 
AS 
BEGIN
  
	 DECLARE @total  NUMERIC(24, 10) 
	 DECLARE @nid INT 
	 IF @STypeID <>''
		 BEGIN
			 SELECT @total = SUM(isnull(a.Total00,0)) FROM dbo.AType_Total a 
			 JOIN ( SELECT nid FROM dbo.Ac_Items  WHERE LEFT(nParId ,LEN(@nTypeid))= @nTypeid OR nTypeId= @nTypeid  ) AS t 
			 ON a.ATypeID = t.nid
			 WHERE a.STypeID = @STypeID
		 END
	 ELSE
		 BEGIN
			SELECT @total = SUM(isnull(a.Total00,0)) FROM dbo.AType_Total a 
			 JOIN ( SELECT nid FROM dbo.Ac_Items  WHERE LEFT(nParId ,LEN(@nTypeid))= @nTypeid OR nTypeId= @nTypeid  ) AS t 
			 ON a.ATypeID = t.nid
		 END
	 RETURN isnull(@total,0)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetBillDetailCostPrice]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetBillDetailCostPrice]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作    者：谢吉康
	日    期：2019-12-11
	描    述：根据成本算法获取单据明细商品的成本
	代码来源：Web_CalculateCostPrice
*/
CREATE FUNCTION F_GetBillDetailCostPrice
(
	@chvPtypeId			VARCHAR(50),		--商品Id
	@chvKtypeId			VARCHAR(50),		--仓库Id
	@decQty				NUMERIC(24, 10) ,	--商品数量
	@intCosting			VARCHAR(10),		--成本算法:0,移动加权平均;1,先进先出;2,后进先出
	@BillType			INT=-1,
	@BillNumberId		INT=-1
)
RETURNS VARCHAR(100)
AS
BEGIN
	DECLARE @CostPrice				VARCHAR(100)
	DECLARE	@decCostingPrice		NUMERIC(24, 10) ,		--商品成本价
			@intAverageCostPrice	INT,			--各仓库商品成本均价是否一致
			@chvSql					VARCHAR(2000)		
			
	IF @intCosting = 0 		--移动加权平均
	BEGIN
		IF @BillNumberId = -1
		BEGIN
			SELECT TOP 1 @intAverageCostPrice=value FROM Userconfig WHERE ConfigName='AverageCostPrice'
			
			IF @intAverageCostPrice=0 	--各仓库商品成本均价不一致
			BEGIN		
				SELECT	@CostPrice = ISNULL((cast(SUM(Total)AS Numeric(22,10)) / CASE WHEN SUM(QTY) = 0 THEN NULL ELSE cast(SUM(QTY)AS Numeric(22,10)) END),0)
				FROM	GoodsStocks
				WHERE	kTypeId= @chvKtypeId 
						AND Ptypeid=@chvPtypeId
			END
			ELSE
			BEGIN				
				SELECT	@CostPrice = (cast(SUM(Total)AS Numeric(22,10)) / CASE WHEN SUM(QTY) = 0 THEN NULL ELSE cast(SUM(QTY)AS Numeric(22,10)) END)
				FROM	GoodsStocks
				WHERE	Ptypeid=@chvPtypeId
			END			
		END
		ELSE
		BEGIN
			SELECT	@CostPrice = CostPrice 
			FROM	InOutstocktable 
			WHERE	BillNumberId=@BillnumberId 
					AND BillType=@BillType
					AND Ktypeid=@chvKtypeId 
					AND Ptypeid=@chvPtypeId
		END		
	END	
	
	DECLARE 
			@decSumQty		 NUMERIC(24, 10) ,
			@decQtyCursor	 NUMERIC(24, 10) ,
			@decSumQtyTemp	 NUMERIC(24, 10) ,
			@decSumTotal	 NUMERIC(24, 10) ,
			@decSumTotalTemp	 NUMERIC(24, 10) ,
			@decTotalCursor		 NUMERIC(24, 10) ,
			@intOrderCursor		int	
			
	DECLARE @TempGoodsStocks TABLE
	(
		Qty			NUMERIC(24, 10) ,
		Total		NUMERIC(24, 10) ,
		GoodsOrder	INT
	)	
	
	DECLARE @TotalDigit INT

	SELECT @TotalDigit = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName = 'total'		
	
	IF @intCosting = 1		--先进先出
	BEGIN
		SET	@decSumQty=0
		SET	@decSumQtyTemp=0
		SET	@decSumTotal=0
		SET	@decSumTotalTemp=0
		DECLARE CostPrice_Cursor CURSOR FOR				
				 SELECT  Qty,Total,GoodsOrder 
				 FROM GoodsStocks 
				 WHERE Ptypeid = @chvPtypeId
					  AND Ktypeid = @chvKtypeId ORDER BY GoodsOrder 
		
		
		OPEN CostPrice_Cursor          --打开游标
		FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
		WHILE  @@FETCH_STATUS = 0	AND @decSumQty < @decQty   --循环写入临时表
		BEGIN 
			INSERT INTO @TempGoodsStocks VALUES(@decQtyCursor,@decTotalCursor,@intOrderCursor)
			SELECT @decSumQty=SUM(Qty),@decSumTotal=SUM(Total) FROM @TempGoodsStocks
			IF @decQty<=@decSumQty 	OR  @decSumQty=0--加了该批次就大于调拨数量了,或者没有库存
				BREAK
			SET	@decSumQtyTemp=@decSumQty
			SET @decSumTotalTemp=@decSumTotal
			FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
		END
		CLOSE CostPrice_Cursor 
    		DEALLOCATE CostPrice_Cursor
 		
 		
		IF @decSumQty <= @decQty  --库存商品数量小于调拨数量
		BEGIN
			IF @decSumQty=0
				SET @decCostingPrice=0
			ELSE
				SET @decCostingPrice=@decSumTotal/@decSumQty
		END
		IF @decSumQty > @decQty         --库存商品数量大于调拨数量
		BEGIN
			SET @decCostingPrice=(ROUND((@decSumTotal-@decSumTotalTemp)/(@decSumQty-@decSumQtyTemp)*(@decQty-@decSumQtyTemp),@TotalDigit) + @decSumTotalTemp)/@decQty
		END
		SELECT @CostPrice = @decCostingPrice
	END	
	
	IF @intCosting = 2		--后进先出
	BEGIN
		SET	@decSumQty=0
		SET	@decSumQtyTemp=0
		SET	@decSumTotal=0
		SET	@decSumTotalTemp=0
		
		DECLARE CostPrice_Cursor CURSOR FOR				
				 SELECT  Qty,Total,GoodsOrder 
				 FROM GoodsStocks 
				 WHERE Ptypeid =@chvPtypeId
					  AND Ktypeid = @chvKtypeId ORDER BY GoodsOrder DESC

		OPEN CostPrice_Cursor          --打开游标
		FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
		WHILE  @@FETCH_STATUS = 0	AND @decSumQty < @decQty   --循环写入临时表
		BEGIN  
			INSERT INTO @TempGoodsStocks VALUES(@decQtyCursor,@decTotalCursor,@intOrderCursor)
			SELECT @decSumQty=SUM(Qty),@decSumTotal=SUM(Total) 
			FROM	@TempGoodsStocks
			IF @decQty<=@decSumQty 	OR @decSumQty=0	--加了该批次就大于调拨数量了
				BREAK
			SET	@decSumQtyTemp=@decSumQty
			SET @decSumTotalTemp=@decSumTotal
			FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
		END
		CLOSE CostPrice_Cursor 
		DEALLOCATE CostPrice_Cursor

		IF @decSumQty <= @decQty  --库存商品数量小于调拨数量
		BEGIN
			IF @decSumQty=0
				SET @decCostingPrice=0
			ELSE
				SET @decCostingPrice=@decSumTotal/@decSumQty
		END
		IF @decSumQty > @decQty         --库存商品数量大于调拨数量
			SET @decCostingPrice=(ROUND((@decSumTotal-@decSumTotalTemp)/(@decSumQty-@decSumQtyTemp)*(@decQty-@decSumQtyTemp),@TotalDigit)+@decSumTotalTemp)/@decQty
		
		SELECT @CostPrice = @decCostingPrice
		
	END
	
	IF @intCosting = 3		--手工指定法
	BEGIN
		DECLARE @recPrice  NUMERIC(24, 10) 
		SELECT @recPrice=recPrice FROM Ptype WHERE typeId=@chvPtypeId
		IF @recPrice=0
			SELECT @CostPrice = NULL
		ELSE
			SELECT @CostPrice = recPrice FROM Ptype WHERE typeId=@chvPtypeId
		
	END	
	
	RETURN @CostPrice
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetBorrowLendDraftState]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetBorrowLendDraftState
GO

-- ========================================================================
-- 功能说明：获取借欠单据草稿状态
-- 作者：蒋奎  
-- 时间：2015-04-20
-- ========================================================================
CREATE  FUNCTION  F_GetBorrowLendDraftState
(
	@billnumberid  [numeric] (10, 0)
)
RETURNS VARCHAR(50)
AS  
BEGIN 
  DECLARE @BillState VARCHAR(50)
  
  SELECT 
	@BillState=
		CASE WHEN IfAudit = '0' THEN '待审核'
			 WHEN IfAudit = '-1' THEN '审核不通过'
			 WHEN IfAudit = '1' THEN '审核通过'
		END
  FROM  AuditingBill ab 
  WHERE
		ab.BillNumberID=@billnumberid AND ab.BillIndexType = 1  
  
  IF @BillState IS NULL
	SET @BillState='原始草稿'

  RETURN @BillState
  
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetCid]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetCid]
GO


CREATE FUNCTION F_GetCid
(
	@cid int 
)
returns int
AS 
BEGIN
	declare @BasisType int
    SELECT @BasisType = t.BasisType  FROM dbo.Ac_Currency t WHERE t.CId = @cid
    RETURN @BasisType
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetCombinBuyStatus]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetCombinBuyStatus
GO

-- ========================================================================
-- 功能说明：获取组合品订单采购状态
-- 作者：寇晨 
-- 时间：2016-08-31
-- ========================================================================
CREATE  FUNCTION  F_GetCombinBuyStatus
(
	@billnumberid  [numeric] (10, 0),
	@billtype		INT
)
RETURNS INT
AS  
BEGIN 
  DECLARE @orderState INT
  
   IF EXISTS(SELECT TOP 1 1 FROM OrderBill a INNER JOIN dbo.PT_Combin_OrderBillDetail b ON a.PTCombinOrderBillDetailID=b.OrderID  WHERE a. Qty<=a.ReachQty AND b.billNumberId=@billnumberid)
       SET @orderState=4		--已完成采购
       
   IF EXISTS(SELECT TOP 1 1 FROM OrderBill a INNER JOIN dbo.PT_Combin_OrderBillDetail b ON a.PTCombinOrderBillDetailID=b.OrderID  WHERE a. Qty>a.ReachQty AND b.billNumberId=@billnumberid)
					OR NOT EXISTS(SELECT TOP 1 1  FROM OrderBill a INNER JOIN dbo.PT_Combin_OrderBillDetail b  ON a.PTCombinOrderBillDetailID=b.OrderID AND b.billNumberId=@billnumberid)  
    SET @orderState=3		--未完成采购
    
   IF EXISTS(SELECT TOP 1 1 FROM OrderBill a INNER JOIN dbo.PT_Combin_OrderBillDetail b ON a.PTCombinOrderBillDetailID=b.OrderID  WHERE a. Qty>a.ReachQty AND b.billNumberId=@billnumberid )
      SET @orderState=2		--已采购未完成
      
   IF NOT EXISTS(SELECT TOP 1 1  FROM OrderBill a INNER JOIN dbo.PT_Combin_OrderBillDetail b  ON a.PTCombinOrderBillDetailID=b.OrderID AND b.billNumberId=@billnumberid)
       SET @orderState=1		--未采购
      
    
   RETURN @orderState
  
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetCombinOrderState]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetCombinOrderState
GO

-- ========================================================================
-- 功能说明：获取组合品销售订单状态
-- 作者：寇晨 
-- 时间：2016-08-31
-- ========================================================================
CREATE  FUNCTION  F_GetCombinOrderState
(
	@billnumberid  [numeric] (10, 0),
	@billtype		INT
)
RETURNS INT
AS  
BEGIN 
  DECLARE @orderState INT
  
   IF EXISTS(SELECT TOP 1 1 FROM dbo.OrderIndex WHERE OrderState=1 AND billNumberId=@billnumberid)
       SET @orderState=2		--已完成
   ELSE IF EXISTS (SELECT TOP  1 1 
					FROM 
					dbo.PT_Combin_SaleBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.PT_Combin_OrderBill o,dbo.OrderIndex i WHERE o.billNumberID=i.billNumberId AND i.billNumberId=@billnumberid)c
					WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID AND @billtype=313)
		 OR EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_OrderBill WHERE ReachQty<>0 AND billNumberID=@billnumberid)

   BEGIN
		 SET @orderState=1  --已引用未完成
   END
   ELSE
		SET @orderState=4 --未引用
    
   RETURN @orderState
  
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetDetailCostPrice]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetDetailCostPrice]
GO

/*

返回某行的成本

不取为0的行是为了在代销处可以取价格

*/

CREATE FUNCTION F_GetDetailCostPrice
(
	@intBillNumberID	BIGINT,
	@intID				BIGINT
	
)
RETURNS  NUMERIC(24, 10) 
AS 
BEGIN
    DECLARE
		@decCostPrice	 NUMERIC(24, 10)
		
		
	DECLARE @intPriceDot INT
	SELECT	@intPriceDot = DecimalDigit
	FROM	dbo.DigitConfiguration
	WHERE	ItemId=2 
		
	SELECT @decCostPrice=0
		
	SELECT @decCostPrice=ROUND(CostPrice,@intPriceDot)
	FROM InOutstocktable
	WHERE BillNumberId=@intBillNumberID AND ID=@intID AND CostPrice<>0
	
	RETURN @decCostPrice
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/************************************************************
 * 创 建 人：罗淮文
 * 创建时间: 2014-04-10 11:08:34
 * 内容描述：获取分摊费用类型(针对【待摊费用发生】【待摊费用摊销】)
 ************************************************************/
IF EXISTS (
       SELECT *
       FROM   dbo.sysobjects
       WHERE  id = OBJECT_ID(N'[dbo].[F_GetExpenseShareType]')
              AND xtype IN (N'FN', N'IF', N'TF')
   )
    DROP FUNCTION [dbo].[F_GetExpenseShareType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION F_GetExpenseShareType
(
	@OperateID VARCHAR(100)
)
RETURNS TABLE
AS
	RETURN 
	SELECT *
	FROM   Ac_Items
	WHERE  EXISTS(
	           SELECT TOP 1 1
	           FROM   LoginUser
	           WHERE  ETypeId = @OperateID
	                  AND MangerExpense = '0000'
	       )
	       AND nparid = '0000100007'
	       
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetIsValidIData]') and xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetIsValidIData]
GO

CREATE FUNCTION F_GetIsValidIData
(
	@strIpAddress NVARCHAR(32)
)
RETURNS  INT
AS  
BEGIN 
	DECLARE @rstFlag	INT,
			@strIP		NVARCHAR(16),
			@tempIP		NVARCHAR(16),
			@tempIPLen	INT

	DECLARE @ValidFlag_1 BIT,
			@ValidFlag_2 BIT,
			@ValidFlag_3 BIT,
			@ValidFlag_4 BIT

	DECLARE @tempFlag_1 BIT,
			@tempFlag_2 BIT,
			@tempFlag_3 BIT,
			@tempFlag_4 BIT

	DECLARE @strIP_1 NVARCHAR(4),
			@strIP_2 NVARCHAR(4),
			@strIP_3 NVARCHAR(4),
			@strIP_4 NVARCHAR(4)

	DECLARE @tempPoINT_1 INT,
			@tempPoINT_2 INT,
			@tempPoINT_3 INT,
			@tempPoINT_4 INT


	SET @rstFlag=0
	
	SET @strIP=RTRIM(LTRIM(@strIPAddress))
	SET @tempIPLen=Len(@strIP)

	SET @tempIP= @strIP
	SELECT @tempPoINT_1= CHARINDEX('.',@tempIP)
	SET @strIP_1=SUBSTRING(@strIP,0,@tempPoINT_1)
	
	IF(@strIP_1='10' OR @strIP_1='127' OR @strIP_1='192')
		SET @rstFlag = 0
	ELSE
		BEGIN	
			SELECT @tempFlag_1=ISNUMERIC(@strIP_1)
			IF(@tempFlag_1=1)
			BEGIN 
				IF((@tempPoINT_1>1) AND ( @tempPoINT_1<5) AND CONVERT(INT,@strIP_1,4)>=0 AND CONVERT(INT,@strIP_1,4) <=255) 
				SET @ValidFlag_1=1
			ELSE
				SET @ValidFlag_1=0
			END

			IF(@ValidFlag_1 =1)
			BEGIN
				SET @tempIP=SUBSTRING( @strIP,@tempPoINT_1+1,@tempIPLen-@tempPoINT_1)
				SELECT @tempPoINT_2= CHARINDEX('.',@tempIP)
				SET @strIP_2=SUBSTRING(@tempIP,0,@tempPoINT_2)


				SELECT @tempFlag_2=ISNUMERIC(@strIP_2)
				IF(@tempFlag_2=1)
				BEGIN 
					IF((@tempPoINT_2>1) AND ( @tempPoINT_2<5) AND CONVERT(INT,@strIP_2,4)>=0 AND CONVERT(INT,@strIP_2,4) <=255) 
					SET @ValidFlag_2=1
				ELSE
					SET @ValidFlag_2=0
				END

				IF(@ValidFlag_2=1)
				BEGIN
					SET @tempIP=SUBSTRING( @strIP,@tempPoINT_1+@tempPoINT_2+1,@tempIPLen-@tempPoINT_1-@tempPoINT_2)
					SELECT @tempPoINT_3= CHARINDEX('.',@tempIP)
					SET @strIP_3=SUBSTRING(@tempIP,0,@tempPoINT_3)

					SELECT @tempFlag_3=ISNUMERIC(@strIP_3)
					IF(@tempFlag_3=1)
					BEGIN
						IF((@tempPoINT_3>1) AND ( @tempPoINT_3<5) AND CONVERT(INT,@strIP_3,4)>=0 AND CONVERT(INT,@strIP_3,4) <=255) 
						SET @ValidFlag_3 =1
					ELSE
						SET @ValidFlag_3 =0
					END 

					IF(@ValidFlag_3 =1)
					BEGIN
						SET @strIP_4=SUBSTRING(@strIP,@tempPoINT_1+@tempPoINT_2+@tempPoINT_3+1,@tempIPLen-@tempPoINT_1-@tempPoINT_2-@tempPoINT_3)

						SELECT @tempFlag_4=ISNUMERIC(@strIP_4)
						IF(@tempFlag_4=1)
						BEGIN
							IF(CONVERT(INT,@strIP_4,4)>=0 AND CONVERT(INT,@strIP_4,4) <=255) 
							SET @rstFlag=1
						ELSE
							SET @rstFlag=0  
						END
					END			
				END
			END
		END
	RETURN (@rstFlag)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetOrderState]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetOrderState
GO

-- ========================================================================
-- 功能说明：获取订单状态
-- 作者：毛欣蓉  
-- 时间：2015-01-07
-- ========================================================================
CREATE  FUNCTION  F_GetOrderState
(
	@billnumberid  [numeric] (10, 0),
	@billtype		INT
)
RETURNS INT
AS  
BEGIN 
  DECLARE @orderState INT
  
   IF EXISTS(SELECT TOP 1 1 FROM dbo.OrderIndex WHERE OrderState=1 AND billNumberId=@billnumberid)
       SET @orderState=2		--已完成
   ELSE IF EXISTS (SELECT TOP  1 1 
					FROM 
					dbo.SaleBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill o,dbo.OrderIndex i WHERE o.billNumberID=i.billNumberId AND i.billNumberId=@billnumberid)c
					WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID AND @billtype=300)
		 OR EXISTS(SELECT TOP  1 1 
					FROM 
					dbo.BuyBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill o,dbo.OrderIndex i WHERE o.billNumberID=i.billNumberId AND i.billNumberId=@billnumberid)c
					WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID AND @billtype=301)
		 OR EXISTS(SELECT TOP  1 1 
					FROM 
					dbo.SendBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill o,dbo.OrderIndex i WHERE o.billNumberID=i.billNumberId AND i.billNumberId=@billnumberid)c
					WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID AND @billtype=300)
		 OR EXISTS(SELECT TOP  1 1 
					FROM 
					dbo.AppraisalBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill o,dbo.OrderIndex i WHERE o.billNumberID=i.billNumberId AND i.billNumberId=@billnumberid)c
					WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID AND @billtype=301)
		 OR EXISTS(SELECT TOP  1 1 
					FROM 
					dbo.CommissionBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill o,dbo.OrderIndex i WHERE o.billNumberID=i.billNumberId AND i.billNumberId=@billnumberid)c
					WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID AND @billtype=300)
		 OR EXISTS(SELECT TOP  1 1 
					FROM 
					dbo.CommissionBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill o,dbo.OrderIndex i WHERE o.billNumberID=i.billNumberId AND i.billNumberId=@billnumberid)c
					WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID AND @billtype=301)
		 OR EXISTS(SELECT TOP 1 1 FROM dbo.OrderBill WHERE ReachQty<>0 AND billNumberID=@billnumberid)

   BEGIN
		 SET @orderState=1  --已引用未完成
   END
   ELSE
		SET @orderState=4 --未引用
    
   RETURN @orderState
  
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetOrderWaitQty]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetOrderWaitQty
GO

-- ========================================================================
-- 功能说明：获取销售订单包含草稿的到货数量
-- 作者：毛欣蓉  
-- 时间：2015-06-09
-- ========================================================================
CREATE  FUNCTION  F_GetOrderWaitQty
(
	@billnumberid  [numeric] (10, 0),
	@orderid		INT,
	@IncludeDraft		INT
)
RETURNS  NUMERIC(24, 10) 
AS  
BEGIN 
  DECLARE @waitqty  NUMERIC(24, 10) =0
			,@billtype int
  IF @IncludeDraft=1
  BEGIN
	select @billtype = billtype from OrderIndex where BillNumberId = @billnumberid
	
	if @billtype <> 301
	begin
		SELECT @waitqty=ISNULL(SUM(a.QTY),0)  FROM 
			dbo.SaleBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill WHERE billNumberId=@billnumberid AND OrderID=@orderid)c
		WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID  AND A.OrderID=@orderid AND b.ifcheck='f'

		SELECT @waitqty=@waitqty+ISNULL(SUM(a.QTY),0) 
		FROM 
		   dbo.SendBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill  WHERE billNumberId=@billnumberid  AND OrderID=@orderid)c
		 WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0  AND c.OrderID=a.OrderID AND A.OrderID=@orderid AND b.ifcheck='f'
		 
		 --wt
		SELECT @waitqty=@waitqty+ISNULL(SUM(a.QTY),0)  FROM 
			dbo.CommissionBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill WHERE billNumberId=@billnumberid AND OrderID=@orderid)c
		WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID  AND A.OrderID=@orderid AND b.ifcheck='f'
		
		SELECT @waitqty=@waitqty+ISNULL(SUM(ReachQty),0) FROM OrderBill where billNumberID=@billnumberid and OrderID=@orderid
	 end
	 else
	 begin
		SELECT @waitqty=ISNULL(SUM(a.QTY),0)  FROM 
			dbo.BuyBill a,dbo.BillIndex b,(SELECT OrderID FROM dbo.OrderBill WHERE billNumberId=@billnumberid AND OrderID=@orderid)c
		WHERE a.BillNumberId=b.BillNumberId AND b.RedWord=0	AND c.OrderID=a.OrderID  AND A.OrderID=@orderid 
	 end
  END
  ELSE
  BEGIN
	 SELECT @waitqty=ReachQty FROM OrderBill where billNumberID=@billnumberid and OrderID=@orderid
  END
	
  RETURN @waitqty
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetPriceBase_Stype]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetPriceBase_Stype]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION F_GetPriceBase_Stype
(
	@pricebillindexid	varchar(max)
)

RETURNS varchar(max)
AS
begin

declare @str varchar(max)
select @str=''

select @str=@str+s.FullName+',' from PriceBillIndex_Stype ps
inner join Stype s on s.typeid=ps.StypeID
where ps.PriceBillIndexID=@pricebillindexid

SET @str=@str+'#'
select @str=@str+s.TypeId+',' from PriceBillIndex_Stype ps
inner join Stype s on s.typeid=ps.StypeID
where ps.PriceBillIndexID=@pricebillindexid

return @str


end

go



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetPtypeIdsByEntrycode]') and xtype in (N'FN', N'IF', N'TF'))
	DROP FUNCTION dbo.[F_GetPtypeIdsByEntrycode]
GO
--==========================================================
--BY:zy
--DATE:2017-07-07
--DESCRIPTION:根据条码获取多个商品ID
--==========================================================
CREATE FUNCTION F_GetPtypeIdsByEntrycode
(
	@entrycode VARCHAR(200),
	@searchflag INT    ----1:精确匹配，2:模糊匹配
)
RETURNS @Temp TABLE
(
	Ptypeid varchar(50)
)
--@encode$--

AS
BEGIN

IF (@searchflag = 1)
BEGIN
	INSERT INTO @Temp(Ptypeid)
	SELECT DISTINCT P.Ptypeid FROM
	(
	SELECT DISTINCT typeId as 'Ptypeid' FROM PType WHERE EntryCode=@entrycode
	UNION ALL
	SELECT DISTINCT Ptypeid FROM PType_Units_Ext WHERE EntryCode=@entrycode AND IsUse=1
	UNION ALL
	SELECT DISTINCT Ptypeid FROM PType_EntryCode_Ext WHERE EntryCode=@entrycode
	UNION ALL
	SELECT DISTINCT A.Ptypeid FROM PType_Units_EntryCode_Ext A INNER JOIN PType_Units_Ext B ON A.PtypeID=B.PtypeID AND A.UnitsId=B.UnitsId AND B.IsUse=1
	WHERE A.EntryCode=@entrycode
	)P ORDER BY P.Ptypeid
END
IF (@searchflag = 2)
BEGIN
	INSERT INTO @Temp(Ptypeid)
	SELECT DISTINCT P.Ptypeid FROM
	(
	SELECT DISTINCT typeId as 'Ptypeid' FROM PType WHERE EntryCode LIKE '%'+@entrycode+'%'
	UNION ALL
	SELECT DISTINCT Ptypeid FROM PType_Units_Ext WHERE EntryCode LIKE '%'+@entrycode+'%' AND IsUse=1
	UNION ALL
	SELECT DISTINCT Ptypeid FROM PType_EntryCode_Ext WHERE EntryCode LIKE '%'+@entrycode+'%'
	UNION ALL
	SELECT DISTINCT A.Ptypeid FROM PType_Units_EntryCode_Ext A INNER JOIN PType_Units_Ext B ON A.PtypeID=B.PtypeID AND A.UnitsId=B.UnitsId AND B.IsUse=1
	WHERE A.EntryCode LIKE '%'+@entrycode+'%'
	)P ORDER BY P.Ptypeid
END

RETURN 
END

GO	
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetPtypeIdsByEntrycodeForSearch]') and xtype in (N'FN', N'IF', N'TF'))
	DROP FUNCTION dbo.[F_GetPtypeIdsByEntrycodeForSearch]
GO
--==========================================================
--BY:zy
--DATE:2017-07-07
--DESCRIPTION:根据条码获取多个商品ID,表体
--==========================================================
CREATE FUNCTION F_GetPtypeIdsByEntrycodeForSearch
(
	@entrycode VARCHAR(200),
	@searchflag INT    ----1:精确匹配，2:模糊匹配
)
RETURNS @Temp TABLE
(
	Ptypeid varchar(50)
)
--@encode$--

AS
BEGIN

IF (@searchflag = 1)
BEGIN
	INSERT INTO @Temp(Ptypeid)
	SELECT DISTINCT P.Ptypeid FROM
	(
	SELECT DISTINCT typeId as 'Ptypeid' FROM PType WHERE EntryCode=@entrycode
	UNION ALL
	SELECT DISTINCT Ptypeid FROM PType_EntryCode_Ext WHERE EntryCode=@entrycode
	UNION ALL
	SELECT DISTINCT Ptypeid FROM PType_Units_EntryCode_Ext WHERE EntryCode=@entrycode

	)P ORDER BY P.Ptypeid
END
IF (@searchflag = 2)
BEGIN
	INSERT INTO @Temp(Ptypeid)
	SELECT DISTINCT P.Ptypeid FROM
	(
	SELECT DISTINCT typeId as 'Ptypeid' FROM PType WHERE EntryCode LIKE '%'+@entrycode+'%'
	UNION ALL
	SELECT DISTINCT Ptypeid FROM PType_EntryCode_Ext WHERE EntryCode LIKE '%'+@entrycode+'%'
	UNION ALL
	SELECT DISTINCT Ptypeid FROM PType_Units_EntryCode_Ext WHERE EntryCode LIKE '%'+@entrycode+'%'
	)P ORDER BY P.Ptypeid
END

RETURN 
END

GO	
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getserial]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_getserial]
GO       

--f_getserial 的函数
--date    :2003-10-14
CREATE FUNCTION f_getserial
(
	@beforePromoID INT,
	@details TBType_Retail READONLY
)
RETURNS VARCHAR(max)
AS
BEGIN
	DECLARE @a VARCHAR(max)=''
    SELECT @a +=isnull(cast(serial AS varchar(max)),'')
    FROM @details
    WHERE BeforePromoID=@beforePromoID
    RETURN REPLACE(@a,'яя','я')
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetStrMIndex]') and xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetStrMIndex]
GO

CREATE FUNCTION F_GetStrMIndex
(
    @Str	NVARCHAR(4000),	
    @Flag	BIT=1,			
    @Value	NVARCHAR(50)	
)
RETURNS NVARCHAR(4000)
--@encode$--
AS
BEGIN
	DECLARE @LenStr INT,
			@i		INT,
			@Str2 NVARCHAR(4000),
			@Split NVARCHAR(2),
			@LenValue INT

	SELECT @Str=@Str+'A',@LenStr=LEN(@Str),@i=1,@Str2='',@LenValue=LEN(@Value+'A')-1

	WHILE @i<@LenStr
			SELECT	@Split=SUBSTRING(@Str,@i,1),
					@Split=NCHAR((UNICODE(@Split)+CASE @Flag WHEN 1 THEN unicode(substring(@Value+'A',@i%@LenValue+1,1))-1                                                
														WHEN 0 THEN 65535-unicode(substring(@Value+'A',@i%@LenValue+1,1))
														ELSE 0 END)%65535+cast(@Flag as int)),
					@Str2=@Str2+@Split,@i=@i+1
	RETURN @Str2
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetStypeNames]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetStypeNames]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION F_GetStypeNames
(
	@Id			varchar(100)
)

RETURNS varchar(max)
AS
begin

declare @str varchar(max)
SET @str=''

select @str+=s.FullName+',' from PromoRule_Stype ps
INNER JOIN Stype s on s.TypeId=ps.StypeID
where ps.PromoRuleID=@Id

return @str

end

go



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF exists (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetTwoDate]') and xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetTwoDate]
GO

/*------------------------------------------
	作者：王刚
	日期：2014-6-13
	描述：得到时间段函数
-------------------------------------------*/

CREATE FUNCTION F_GetTwoDate
(
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@Flag			INT --1=月  2=季  3=年
)
RETURNS @temp TABLE
		(	id				 INT IDENTITY(1,1), 
			YearFullName	 VARCHAR(10),
			SeasonFullName	 VARCHAR(10),
			MonthFullName	 VARCHAR(10),
			MonthPlaceholder VARCHAR(10),
			StartDate		 DATE,
			EndDate			 DATE
		)
AS 
BEGIN
	
	IF @StartDate = '' OR @StartDate IS NULL OR @EndDate = '' OR @EndDate IS NULL
		RETURN
 
 
	--格式化处理时间2014-07-07
	SET @StartDate = CONVERT(DATE,@StartDate,120)
	SET @EndDate = CONVERT(DATE,@EndDate,120)

    DECLARE @TempDate DATE
    
    WHILE (@StartDate <= @EndDate)
	BEGIN
		IF @Flag = 1 ----1=月  2=季  3=年
			SET @TempDate = DATEADD(Day,-1,CONVERT(VARCHAR(8),DATEADD(Month,1,@StartDate),120)+'1')
		IF @Flag = 2
			SET @TempDate = DATEADD(Day,-1,CONVERT(VARCHAR(8),DATEADD(Month,1+DATEPART(Quarter,@StartDate)*3-Month(@StartDate),@StartDate),120)+'1')
		IF @Flag = 3
			SET @TempDate = CONVERT(VARCHAR(5),@StartDate,120)+'12-31'
		
		IF @TempDate <= @EndDate
			INSERT @temp VALUES('','','','',@StartDate,@TempDate)
		ELSE
			INSERT @temp VALUES('','','','',@StartDate,@EndDate)
		
		SET @StartDate = CONVERT(VARCHAR(10),DATEADD(DAY,1,@TempDate),120)
	END 
	
	UPDATE @temp 
	SET YearFullName = YEAR(StartDate),SeasonFullName=DATEPART(Quarter,StartDate),
		MonthFullName = MONTH(StartDate),MonthPlaceholder = DATENAME(mm,StartDate)
	
	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LinePtypeCategory]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_LinePtypeCategory
GO




/*
	作者：谢吉康
	日期：2018-6-15
	描述：根据操作员，商品类别来获取权限范围内的商品信息(线性商品，用于查询数据)
*/
CREATE FUNCTION F_LinePtypeCategory
(
	@chvOperatorId	varchar(100),
	@pctypeid		VARCHAR(MAX)
)
RETURNS @Temp TABLE
(
	TypeId					VARCHAR(100),
	Deleted					VARCHAR(10),
	iscombinationproduct	VARCHAR(10)
	
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
	BEGIN
		IF ISNULL(@pctypeid,'')<>''
			INSERT INTO @Temp(TypeId,Deleted,iscombinationproduct) 
			SELECT p.TypeID,P.Deleted,P.iscombinationproduct FROM PType p,dbo.F_Split(@pctypeid,',') b WHERE p.SonNum = 0 AND p.PTypeCategoryid LIKE b.a+'%'
		ELSE
			INSERT INTO @Temp(TypeId,Deleted,iscombinationproduct) 
			SELECT p.TypeID,P.Deleted,P.iscombinationproduct FROM PType p WHERE p.SonNum = 0 
		
	END
	ELSE
	BEGIN
		IF ISNULL(@pctypeid,'')<>''
			INSERT INTO @Temp(TypeId,Deleted,iscombinationproduct) 
			SELECT	P.TypeId,
					P.Deleted,
					p.iscombinationproduct
			FROM	PType_L L
			INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
			INNER JOIN  dbo.F_Split(@pctypeid,',') b ON p.PtypeCategoryID LIKE b.a+'%'
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag = 1 
					AND P.sonnum = 0
		ELSE
			INSERT INTO @Temp(TypeId,Deleted,iscombinationproduct) 
			SELECT	P.TypeId,
					p.Deleted,
					p.iscombinationproduct
			FROM	PType_L L
			INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag = 1 
					AND P.sonnum = 0
	END			
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_split_get_char_count]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_split_get_char_count]
GO

/*
	作者：谢吉康
	日期：2012-11-20
	描述：得到字符出现的次数
*/


CREATE FUNCTION f_split_get_char_count
(
	@SourceSql  VARCHAR(MAX),
	@StrSeprate VARCHAR(10)
)
RETURNS INT
AS 
BEGIN
	DECLARE @intCount INT
	
    SELECT 	@intCount = COUNT(*) 
	FROM	master.dbo.spt_values
	WHERE	number>0 
			AND type='P' 
			AND SUBSTRING(@SourceSql,number,1) = @StrSeprate
	
    RETURN @intCount
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_split_table]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_split_table]
GO

/*
	作者：谢吉康
	日期：2012-11-19
	描述：返回带自增长列的表
*/

CREATE FUNCTION f_split_table
(
	@SourceSql		VARCHAR(MAX),
	@StrSeprate		VARCHAR(10)
)
RETURNS @temp TABLE
(	
	nID INT IDENTITY(1,1),
	a	VARCHAR(MAX)
)
AS 
BEGIN
    DECLARE @i INT
    
    SET @SourceSql=RTRIM(LTRIM(@SourceSql))
    SET @i=CHARINDEX(@StrSeprate,@SourceSql)
    
    WHILE @i>=1
    BEGIN
        INSERT @temp VALUES(LEFT(@SourceSql,@i-1))
        SET @SourceSql=SUBSTRING(@SourceSql,@i+1,LEN(@SourceSql)-@i)
        SET @i=CHARINDEX(@StrSeprate,@SourceSql)
    END

    IF @SourceSql<>''
    BEGIN
       INSERT @temp VALUES(@SourceSql)
    END
       
    RETURN
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetAllCharCount]')and ((OBJECTPROPERTY(id, N'IsTableFunction') = 1) OR (OBJECTPROPERTY(id, N'IsScalarFunction') = 1))
)
drop Function [dbo].[FN_GetAllCharCount]
GO



/*

功能说明：       得到指定字符在字符串中的出现次数

作    者：       冯波

创建日期：       2011-3-22

返回结果：       

*/

CREATE FUNCTION FN_GetAllCharCount(
	@strChar	VARCHAR(10),
	@strList	VARCHAR(500)
)
Returns INT
--@Encode$--
AS 
BEGIN    
	DECLARE
		@intStart	INT,
		@intLen		INT,
		@intResult	INT
		
	SELECT
		@intStart=CHARINDEX(@strChar,@strList),
		@intLen=LEN(@strList),
		@intResult=0
		
	WHILE @intStart>0 AND @intStart<=@intLen
	BEGIN
		IF @intStart>0 SET @intResult=@intResult+1
	
		SELECT
			@intStart=CHARINDEX(@strChar,@strList,@intStart+1) 
	END

	RETURN @intResult

END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetAllCharIndex]')and ((OBJECTPROPERTY(id, N'IsTableFunction') = 1) OR (OBJECTPROPERTY(id, N'IsScalarFunction') = 1))
)
drop Function [dbo].[FN_GetAllCharIndex]
GO



/*

功能说明：       得到指定字符在字符串中的所有位置

作    者：       冯波

创建日期：       2011-3-22

返回结果：       

*/

CREATE FUNCTION FN_GetAllCharIndex(
	@strChar	VARCHAR(10),
	@strList	VARCHAR(MAX)
)
Returns @AllCharIndexTab TABLE(
	AllCharIndex	INT      
)
--@Encode$--
AS 
BEGIN    
	DECLARE
		@intStart	INT,
		@intLen		INT
		
	SELECT
		@intStart=CHARINDEX(@strChar,@strList),
		@intLen=LEN(@strList)
		
	WHILE @intStart>0 AND @intStart<=@intLen
	BEGIN
		INSERT @AllCharIndexTab SELECT @intStart
		
		SELECT
			@intStart=CHARINDEX(@strChar,@strList,@intStart+1) 
	END

	RETURN 

END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetCurrentAuditETypeNames]')and ((OBJECTPROPERTY(id, N'IsTableFunction') = 1) OR (OBJECTPROPERTY(id, N'IsScalarFunction') = 1))
)
drop Function [dbo].[FN_GetCurrentAuditETypeNames]
GO

CREATE FUNCTION FN_GetCurrentAuditETypeNames
(
	@intBillNumberID	INT,			--单据ID
	@strSTypeID			VARCHAR(50),
	@intBillType		Int				--单据类型
		
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @etypenames VARCHAR(MAX),
			@i			INT,
			@ncount		INT,
			@etypeid	VARCHAR(50),
			@ename		VARCHAR(500)
	
	SET @etypenames = ''
	
	DECLARE @Result TABLE
	(
		nid				INT IDENTITY(1,1),
		etypeid			VARCHAR(50)
	)
	INSERT INTO @Result(etypeid)
	SELECT  DISTINCT
			b.ETypeID
	FROM [dbo].FN_GetCurrentAuditETypeID(@intBillNumberID,@strSTypeID,@intBillType) B
	INNER JOIN dbo.employee E ON E.typeId = b.ETypeID
	INNER JOIN dbo.AuditingFlowDetail Ad ON B.AuditingStep = Ad.AuditingStep
	
	SET @ncount = @@rowcount
	
	SET @i = 1
	
	WHILE (@i <= @ncount)
	BEGIN
		SELECT	@ename = e.fullname 
		FROM	@Result r
		INNER JOIN dbo.employee e ON r.etypeid = e.typeId
		WHERE	r.nid = @i
		
		IF @etypenames = ''
			SET @etypenames = @ename
		ELSE
			SET @etypenames = @etypenames + ',' + @ename
			
		SET @i = @i + 1
	END
	
	RETURN @etypenames
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fun_getPY]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fun_getPY]
GO












/*
	作者：谢吉康
	日期：2005-6-7
	描述：传入参数返回拼音
	实例：
			DECLARE @returnPym varchar(1000)
			EXEC @returnPym = fun_getPY '任我行软件'
			SET @returnPym = UPPER(@returnPym)	--小写LOWER
			PRINT(@returnPym)
*/

CREATE  FUNCTION fun_getPY 
 ( 
    @Str nvarchar(4000) 
 ) 
returns nvarchar(4000) 
--@ENCODE$--
AS 
BEGIN 
	DECLARE @word nchar(1),@PY nvarchar(4000) 
	
	--空格需要替换，否则生成的结果不正确
	SET @Str = REPLACE(@Str,' ','')

	SET @PY='' 

	WHILE len(@STR)>0 
	BEGIN 
		SET @word=LEFT(@STR,1) 
		
		--如果非汉字字符，返回原字符 
		SET @PY=@PY+(CASE WHEN unicode(@word) BETWEEN 19968 AND 19968+20901 
		           THEN (  
		                        SELECT TOP 1 PY  
		                        FROM  
		                        (  
			                         SELECT 'A' AS PY,N'驁' AS word 
			                         UNION ALL SELECT 'B',N'簿' 
			                         UNION ALL SELECT 'C',N'錯' 
					                 UNION ALL SELECT 'D',N'鵽' 
					                 UNION ALL SELECT 'E',N'樲' 
					                 UNION ALL SELECT 'F',N'鰒' 
					                 UNION ALL SELECT 'G',N'腂' 
					                 UNION ALL SELECT 'H',N'夻' 
					                 UNION ALL SELECT 'J',N'攈' 
					                 UNION ALL SELECT 'K',N'穒' 
					                 UNION ALL SELECT 'L',N'鱳' 
					                 UNION ALL SELECT 'M',N'旀' 
					                 UNION ALL SELECT 'N',N'桛' 
					                 UNION ALL SELECT 'O',N'漚' 
					                 UNION ALL SELECT 'P',N'曝' 
					                 UNION ALL SELECT 'Q',N'囕' 
					                 UNION ALL SELECT 'R',N'鶸' 
					                 UNION ALL SELECT 'S',N'蜶' 
					                 UNION ALL SELECT 'T',N'籜' 
					                 UNION ALL SELECT 'W',N'鶩' 
					                 UNION ALL SELECT 'X',N'鑂' 
					                 UNION ALL SELECT 'Y',N'韻' 
					                 UNION ALL SELECT 'Z',N'咗' 
		                  	) T  
		               WHERE word>=@word collate Chinese_PRC_CS_AS_KS_WS  
		               ORDER BY PY ASC 
		                      )  
		                  ELSE @word  
		             END) 
		SET @STR=RIGHT(@STR,len(@STR)-1) 
	END 
	RETURN @PY 
END 















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO


IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Get_StrArrayStrOfIndex]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) )
    DROP FUNCTION [dbo].[Get_StrArrayStrOfIndex];
GO

/*
	作者：YX
	日期：2017-01-19
	描述：按指定字符分隔字符串
*/

CREATE FUNCTION Get_StrArrayStrOfIndex
    (
      @str VARCHAR(1024) , --要分割的字符串
      @split VARCHAR(10) , --分隔符号
      @index INT --取第几个元素
    )
RETURNS VARCHAR(1024)
AS
    BEGIN
        DECLARE @location INT;
        DECLARE @start INT;
        DECLARE @next INT;
        DECLARE @seed INT;

        SET @str = LTRIM(RTRIM(@str));
        SET @start = 1;
        SET @next = 1;
        SET @seed = LEN(@split);

        SET @location = CHARINDEX(@split, @str);
        WHILE @location <> 0
            AND @index > @next
            BEGIN
                SET @start = @location + @seed;
                SET @location = CHARINDEX(@split, @str, @start);
                SET @next = @next + 1;
            END;
        IF @location = 0
            SELECT  @location = LEN(@str) + 1;
--这儿存在两种情况：1、字符串不存在分隔符号 2、字符串中存在分隔符号，跳出while循环后，@location为0，那默认为字符串后边有一个分隔符号。
        RETURN SUBSTRING(@str,@start,@location-@start);
    END;


GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllAType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllAType]
GO




















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖现金银行-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllAType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM AType WHERE  SonNum = 0 AND (TypeId LIKE '0000100004%' OR TypeId = '0000100003')
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT A.TypeId 
		FROM	AType_L L
		INNER JOIN AType A ON (L.Flag=1 AND A.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND L.Type = '0'
				AND (A.TypeId LIKE '0000100004%' OR A.TypeId = '0000100003')
		UNION
		SELECT  L.typeid
		FROM	atype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.Type = '0'
				AND L.flag=0
				AND (L.TypeId LIKE '0000100004%' OR L.TypeId = '0000100003')

	RETURN
END




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllATypeFy]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllATypeFy]
GO























/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖费用-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllATypeFy
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM AType WHERE  SonNum = 0 AND TypeId LIKE '0000400003%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT A.TypeId 
		FROM	AType_L L
		INNER JOIN AType A ON (L.Flag=1 AND A.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND L.type = '1'
				AND A.TypeId LIKE '0000400003%'
		UNION
		SELECT  L.typeid
		FROM	Atype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.Type = '1'
				AND L.flag=0
				AND L.TypeId LIKE '0000400003%'

	RETURN
END

































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllATypeSr]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllATypeSr]
GO























/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖收入-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllATypeSr
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '0000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM AType WHERE  SonNum = 0 AND TypeId LIKE '0000300003%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT A.TypeId 
		FROM	AType_L L
		INNER JOIN AType A ON (L.Flag=1 AND A.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND L.type = '2'
				AND A.TypeId LIKE '0000300003%'
		UNION
		SELECT L.TypeID
		FROM	atype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.type = '2'
				AND L.flag=0
				AND L.TypeId LIKE '0000300003%'
		

	RETURN
END
































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllATypeZc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllATypeZc]
GO






















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖资产-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllATypeZc
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM AType WHERE  SonNum = 0 AND TypeId LIKE '0000100002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT A.TypeId 
		FROM	AType_L L
		INNER JOIN AType A ON (L.Flag=1 AND A.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND L.type = '3'
				AND A.TypeId LIKE '0000100002%'
		UNION
		SELECT L.TypeID
		FROM	atype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.type = '3'
				AND L.flag=0
				AND L.TypeId LIKE '0000100002%'
		

	RETURN
END






























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllBType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllBType]
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllBType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @TypeId varchar(100),
			@Flag	char(1)

	--客户
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE  SonNum = 0 AND TypeId LIKE '00001%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND B.typeId LIKE '00001%'
		UNION
		SELECT L.TypeID
		FROM	btype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0
				AND L.typeId LIKE '00001%'
		
				

	--供货商
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE  SonNum = 0 AND TypeId LIKE '00002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND B.typeId LIKE '00002%'
		UNION
		SELECT L.TypeID
		FROM	btype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0
				AND L.typeId LIKE '00002%'

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllDType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllDType]
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖分支机构-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllDType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerDTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Department WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT D.TypeId 
		FROM	DType_L L
		INNER JOIN Department D ON (L.Flag=1 AND D.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
		UNION
		SELECT L.TypeID
		FROM	dtype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0
				

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllEType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllEType]
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖职员-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllEType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Employee WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT E.TypeId 
		FROM	EType_L L
		INNER JOIN Employee E ON (L.Flag=1 AND E.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
		UNION
		SELECT L.TypeID
		FROM	etype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0
				

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllKType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllKType]
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖仓库-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllKType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Stock WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT K.TypeId 
		FROM	KType_L L
		INNER JOIN Stock K ON (L.Flag=1 AND K.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
		UNION
		SELECT L.TypeID
		FROM	ktype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllPType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllPType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖商品-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAllPType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT P.TypeId 
		FROM	PType_L L
		INNER JOIN PType  P ON (L.Flag=1 AND P.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
		UNION
		SELECT	L.TypeID
		FROM	ptype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAllSType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAllSType]
GO

/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖分支机构-线性表
*/

CREATE FUNCTION F_BaseGetManDetailAllSType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM SType WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT S.TypeId 
		FROM	SType_L L
		INNER JOIN SType S ON (L.Flag=1 AND S.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
		UNION
		SELECT	L.TypeID
		FROM	stype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0

	RETURN
END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailAType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailAType]
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖现金银行-线性表
*/
CREATE FUNCTION F_BaseGetManDetailAType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM AType WHERE  SonNum = 0 AND (TypeId LIKE '0000100004%' OR TypeId = '0000100003')
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	A.TypeId 
		FROM	AType_L L
		INNER JOIN AType A ON A.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND A.sonnum = 0
				AND L.type = '0'
				AND (A.TypeId LIKE '0000100004%' OR A.TypeId = '0000100003')

	RETURN
END


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailATypeFy]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailATypeFy]
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖费用-线性表
*/
CREATE FUNCTION F_BaseGetManDetailATypeFy
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nId FROM dbo.Ac_Items WHERE  SonNum = 0 AND TypeName='E'
	ELSE
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	a.nTypeId,A.nId 
		FROM	AType_L L
		INNER JOIN Ac_Items A ON A.nTypeId LIKE L.TypeId +'%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND A.sonnum = 0
				AND L.type = '1'
				AND A.nTypeId LIKE '0000400003%'
	RETURN
END





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailATypeSr]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailATypeSr]
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖收入-线性表
*/
CREATE FUNCTION F_BaseGetManDetailATypeSr
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeID,nid FROM Ac_Items WHERE  SonNum = 0 AND nTypeId LIKE '00003%'
	ELSE
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	a.nTypeId,a.nId 
		FROM	AType_L L
		INNER JOIN Ac_Items A ON A.nTypeId LIKE L.TypeId +'%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND A.sonnum = 0
				AND L.type = '2'
				AND A.nTypeId LIKE '0000300003%'

	RETURN
END




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailATypeZc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailATypeZc]
GO




















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖资产-线性表
*/
CREATE FUNCTION F_BaseGetManDetailATypeZc
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM AType WHERE  SonNum = 0 AND TypeId LIKE '0000100002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	A.TypeId 
		FROM	AType_L L
		INNER JOIN AType A ON A.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND A.sonnum = 0
				AND L.type = '3'
				AND A.TypeId LIKE '0000100002%'

	RETURN
END




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailBType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailBType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-线性表
*/
CREATE FUNCTION F_BaseGetManDetailBType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @TypeId varchar(100)
	--客户
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE  SonNum = 0 AND TypeId LIKE '00001%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND B.sonnum = 0
				AND B.typeId LIKE '00001%'

	--供货商
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE  SonNum = 0 AND TypeId LIKE '00002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND B.sonnum = 0
				AND B.typeId LIKE '00002%'

	RETURN
END

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailDType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailDType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖分支机构-线性表
*/
CREATE FUNCTION F_BaseGetManDetailDType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerDTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Department WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	D.TypeId 
		FROM	DType_L L
		INNER JOIN Department D ON D.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND D.sonnum = 0

	RETURN
END

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailEType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailEType]
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖职员-线性表
*/
CREATE FUNCTION F_BaseGetManDetailEType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '00001')
		BEGIN
			INSERT INTO @Temp(TypeId)VALUES('00001')
			INSERT INTO @Temp(TypeId) SELECT TypeID FROM Employee WHERE  SonNum = 0
		END
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	E.TypeId 
		FROM	EType_L L
		INNER JOIN Employee E ON E.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND E.sonnum = 0

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailKType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailKType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖仓库-线性表
*/
CREATE FUNCTION F_BaseGetManDetailKType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Stock WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	K.TypeId 
		FROM	KType_L L
		INNER JOIN Stock K ON K.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND K.sonnum = 0

	RETURN
END

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailPType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailPType]
GO














/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖商品-线性表
*/
CREATE FUNCTION F_BaseGetManDetailPType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	P.TypeId 
		FROM	PType_L L
		INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND P.sonnum = 0

	RETURN
END






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDetailSType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDetailSType]
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖分支机构-线性表
*/

CREATE FUNCTION F_BaseGetManDetailSType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM SType WHERE  SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	S.TypeId 
		FROM	SType_L L
		INNER JOIN SType S ON S.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND S.sonnum = 0

	RETURN
END






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'dbo.F_GetAssisitItem') IS NOT NULL
DROP FUNCTION dbo.F_GetAssisitItem
GO
/*
	作者：佘海源
	日期：2012-07-12
	描述：获取指定辅助所有
*/
CREATE FUNCTION [dbo].[F_GetAssisitItem] 
(
	@type INT,
	@FieldValue VARCHAR(MAX),
	@OperatorId VARCHAR(100)
)
RETURNS @Temp TABLE(AssistUserCode VARCHAR(200),AssistFullName VARCHAR(200),FieldValue varchar(50),Usercode VARCHAR(200),FullName varchar(200))
AS 
BEGIN
	IF(@type=1) --分支机构
		INSERT INTO @Temp(AssistUserCode,AssistFullName,FieldValue,Usercode,FullName) SELECT '01' AssistUserCode,'分支机构' AssistFullName,a.TypeId,a.UserCode,FullName FROM SType a
		INNER JOIN F_GetAllManagerBaseTypeId(@FieldValue,11,@OperatorId) B ON B.TypeId=A.TypeId
	ELSE IF(@type=2)--部门
		INSERT INTO @Temp(AssistUserCode,AssistFullName,FieldValue,Usercode,FullName) SELECT '02' AssistUserCode,'部门' AssistFullName,a.TypeId,a.UserCode,FullName FROM Department a
		INNER JOIN F_GetAllManagerBaseTypeId(@FieldValue,9,@OperatorId) B ON B.TypeId=A.TypeId
	ELSE IF(@type=3)--职员
		INSERT INTO @Temp(AssistUserCode,AssistFullName,FieldValue,Usercode,FullName) SELECT '03' AssistUserCode,'职员' AssistFullName,a.TypeId,a.UserCode,FullName FROM employee a
		INNER JOIN F_GetAllManagerBaseTypeId(@FieldValue,3,@OperatorId) B ON B.TypeId=A.TypeId
	ELSE IF(@type=4) --往来单位
		INSERT INTO @Temp(AssistUserCode,AssistFullName,FieldValue,Usercode,FullName) SELECT '04' AssistUserCode,'往来单位' AssistFullName,a.TypeId,a.UserCode,FullName FROM btype a
		INNER JOIN F_GetAllManagerBaseTypeId(@FieldValue,2,@OperatorId) B ON B.TypeId=A.TypeId AND A.parid<>'root'
	ELSE
		INSERT INTO @Temp(AssistUserCode,AssistFullName,FieldValue,Usercode,FullName)
		SELECT
			I.UserCode AssistUserCode,
			I.FullName AssistFullName,
			D.TypeId,
			D.UserCode,
			D.FullName 
		FROM Ac_Assist_CheckItemsDetail D
		INNER JOIN Ac_Assist_CheckItems I ON I.AscIds=D.AscIds
		INNER JOIN dbo.F_GetAllAssistCheckItemsDetail(@FieldValue,@type,@OperatorId) F ON F.TypeId=D.TypeId AND D.AscIds=@type
	RETURN
END 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllAType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllAType]
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖现金银行-线性表
*/
CREATE FUNCTION F_GetManDetailAllAType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nId FROM dbo.Ac_Items WHERE SonNum = 0  aND (nTypeId LIKE '0000100004%' OR nTypeId LIKE '0000100003%')
	ELSE
	BEGIN
		INSERT INTO @Temp(nTypeId,nId) 
		SELECT	DISTINCT A.nTypeId,a.nId 
		FROM	AType_l L 
		--LEFT JOIN AType A ON LEFT(A.TypeId,LEN(L.TypeId)) = L.typeid 
		INNER JOIN Ac_Items  A ON (L.Flag=1 AND A.nTypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId 
				AND L.Type = '0'
		UNION
		SELECT	L.TypeID,a.nId
		FROM	atype_l L
		INNER JOIN Ac_Items a ON l.typeid = a.nTypeId
		WHERE	L.etypeid = @chvOperatorId 
				AND L.Type = '0'
				AND L.flag=0
	END
	RETURN
END


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllATypeFy]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllATypeFy]
GO




















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖费用-线性表
*/
CREATE FUNCTION F_GetManDetailAllATypeFy
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nId FROM Ac_Items WHERE SonNum = 0 AND  TypeName='E' AND nTypeId LIKE '0000400003%'
	ELSE
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	DISTINCT A.nTypeId,a.nId 
		FROM	AType_l L 
		--LEFT JOIN AType A ON LEFT(A.TypeId,LEN(L.TypeId)) = L.typeid 
		INNER JOIN Ac_Items  A ON (L.Flag=1 AND A.nTypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId 
				AND L.Type = '1'
		UNION
		SELECT	L.TypeID,a.nId
		FROM	atype_l L
		INNER JOIN Ac_Items a ON l.typeid = a.nTypeId
		WHERE	L.etypeid = @chvOperatorId 
				AND L.flag=0
				AND L.Type = '1'
		

	RETURN
END































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllATypeSr]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllATypeSr]
GO




















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖收入-线性表
*/
CREATE FUNCTION F_GetManDetailAllATypeSr
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nId FROM dbo.Ac_Items WHERE SonNum = 0 AND TypeName='G' AND nTypeId LIKE '0000300003%'
	ELSE
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	DISTINCT A.nTypeId,a.nId 
		FROM	AType_l L 
		--LEFT JOIN AType A ON LEFT(A.TypeId,LEN(L.TypeId)) = L.typeid 
		INNER JOIN Ac_Items  A ON (L.Flag=1 AND A.nTypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId 
				AND L.Type = '2'
		UNION
		SELECT	L.TypeID,a.nId
		FROM	atype_l L
		INNER JOIN Ac_Items  A ON l.typeid = a.nTypeId
		WHERE	L.etypeid = @chvOperatorId 
				AND L.flag=0
				AND L.Type = '2'
	RETURN
END






























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllATypeZc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllATypeZc]
GO




















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖资产-线性表
*/
CREATE FUNCTION F_GetManDetailAllATypeZc
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nid FROM dbo.Ac_Items WHERE SonNum = 0 AND TypeName='F' AND nTypeId LIKE '0000100002%'
	ELSE
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	DISTINCT A.nTypeId ,a.nId
		FROM	AType_l L 
		--LEFT JOIN AType A ON LEFT(A.TypeId,LEN(L.TypeId)) = L.typeid 
		INNER JOIN Ac_Items  A ON (L.Flag=1 AND A.nTypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId 
				AND L.Type = '3'
		UNION
		SELECT	L.TypeID,a.nId
		FROM	atype_l L
		INNER JOIN Ac_Items a ON l.typeid = a.nTypeId
		WHERE	L.etypeid = @chvOperatorId 
				AND L.Type = '3'
				AND L.flag=0
		

	RETURN
END




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllBType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllBType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-线性表
*/
CREATE FUNCTION F_GetManDetailAllBType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @TypeId varchar(100),
			@Flag	char(1)

		--客户
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE  SonNum = 0 AND TypeId LIKE '00001%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND B.typeId LIKE '00001%'
		UNION
		SELECT	L.TypeID
		FROM	btype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.typeId LIKE '00001%'
				AND L.flag=0
		
				

	--供货商
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE  SonNum = 0 AND TypeId LIKE '00002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND B.typeId LIKE '00002%'
		UNION
		SELECT	L.TypeID
		FROM	btype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.typeId LIKE '00002%'
				AND L.flag=0

	RETURN
END

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllDType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllDType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖部门-线性表
*/
CREATE FUNCTION F_GetManDetailAllDType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerDTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Department WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT D.TypeId 
		FROM	DType_l L 
		--LEFT JOIN Department D ON LEFT(D.TypeId,LEN(L.TypeId)) = L.typeid 
		INNER JOIN Department D ON (L.Flag=1 AND D.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId 
		UNION
		SELECT	L.TypeID
		FROM	dtype_l L
		WHERE	L.etypeid = @chvOperatorId 
				AND L.flag=0
	
	RETURN
END

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllEType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllEType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖职员-线性表
*/
CREATE FUNCTION F_GetManDetailAllEType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Employee WHERE SonNum = 0
	ELSE
		BEGIN
			/*
			DECLARE @TypeId varchar(100),
					@Flag	char(1)
			
			DECLARE PType_Cursor CURSOR FOR
				SELECT TypeId,Flag FROM EType_L WHERE ETypeID = @chvOperatorId

			OPEN PType_Cursor

			FETCH NEXT FROM PType_Cursor INTO @TypeId,@Flag

			WHILE @@FETCH_STATUS = 0
				BEGIN
					IF @Flag = '0'
						INSERT INTO @Temp(TypeId)VALUES(@TypeId)
					ELSE
						INSERT INTO @Temp(TypeId) SELECT TypeId FROM Employee WHERE TypeId LIKE @TypeID + '%' AND TypeId NOT IN (SELECT TypeID FROM @Temp)

					FETCH NEXT FROM PType_Cursor INTO @TypeId,@Flag
				END

			CLOSE PType_Cursor
			DEALLOCATE PType_Cursor
			*/
			
			INSERT INTO @Temp(TypeId) 
			SELECT	DISTINCT e.TypeId 
			FROM	EType_L L
			INNER JOIN employee  e ON (L.Flag=1 AND E.TypeId LIKE L.TypeId + '%')
			WHERE	L.etypeid = @chvOperatorId
			UNION
			SELECT	L.TypeID
			FROM	etype_l L
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag=0
		END

	RETURN
END

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllKType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllKType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖仓库-线性表
*/
CREATE FUNCTION F_GetManDetailAllKType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Stock WHERE SonNum = 0
	ELSE
		BEGIN
			/*
			DECLARE @TypeId varchar(100),
					@Flag	char(1)
			
			DECLARE PType_Cursor CURSOR FOR
				SELECT TypeId,Flag FROM KType_L WHERE ETypeID = @chvOperatorId

			OPEN PType_Cursor

			FETCH NEXT FROM PType_Cursor INTO @TypeId,@Flag

			WHILE @@FETCH_STATUS = 0
				BEGIN
					IF @Flag = '0'
						INSERT INTO @Temp(TypeId)VALUES(@TypeId)
					ELSE
						INSERT INTO @Temp(TypeId) SELECT TypeId FROM Stock WHERE TypeId LIKE @TypeID + '%' AND TypeId NOT IN (SELECT TypeID FROM @Temp)

					FETCH NEXT FROM PType_Cursor INTO @TypeId,@Flag
				END

			CLOSE PType_Cursor
			DEALLOCATE PType_Cursor
			*/
			INSERT INTO @Temp(TypeId) 
			SELECT	DISTINCT K.TypeId 
			FROM	KType_L L
			INNER JOIN Stock K ON (L.Flag=1 AND K.TypeId LIKE L.TypeId + '%')
			WHERE	L.etypeid = @chvOperatorId
			UNION
			SELECT	L.TypeID
			FROM	ktype_l L
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag=0
		END

	RETURN
END

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllPType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllPType]
GO















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖商品-线性表
*/
CREATE FUNCTION F_GetManDetailAllPType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT P.TypeId 
		FROM	PType_L L
		INNER JOIN PType  P ON (L.Flag=1 AND P.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
		UNION
		SELECT	L.TypeID
		FROM	ptype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0

	RETURN
END

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAllSType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAllSType]
GO

/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖分支机构-线性表
*/
CREATE FUNCTION F_GetManDetailAllSType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM SType WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT S.TypeId 
		FROM	SType_l L 
		--LEFT JOIN SType S ON LEFT(S.TypeId,LEN(L.TypeId)) = L.typeid 
		INNER JOIN SType S ON (L.Flag=1 AND S.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId 
		UNION
		SELECT	L.TypeID
		FROM	stype_l L
		WHERE	L.etypeid = @chvOperatorId 
				AND L.flag=0

	RETURN
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailAType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailAType]
GO
















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖现金银行-线性表
*/
CREATE FUNCTION F_GetManDetailAType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
		--INSERT INTO @Temp(TypeId) SELECT nId FROM dbo.Ac_Items WHERE SonNum = 0  AND TypeName='B' AND UserCode NOT IN('2181','2131','1151')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeID,nId FROM Ac_Items WHERE SonNum = 0 AND (nTypeId LIKE '0000100004%' OR nTypeId LIKE '0000100003%')
	ELSE	
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	a.nTypeId ,a.nId
		FROM	AType_L L
		INNER JOIN Ac_Items  A ON A.nTypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1
				AND L.type = '0' 
				AND A.sonnum = 0
				AND (A.nTypeId LIKE '0000100004%'  OR a.nTypeId LIKE '0000100003%')


	RETURN
END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailATypeFy]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailATypeFy]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖费用-线性表
*/
CREATE FUNCTION F_GetManDetailATypeFy
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid int)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nId FROM dbo.Ac_Items WHERE SonNum = 0 AND TypeName='E' and nTypeId LIKE '00004%'
	ELSE		
		INSERT INTO @Temp(nTypeId,nid)
		SELECT	A.nTypeId,A.nid
		FROM	AType_L L
		INNER JOIN Ac_Items  A ON A.nTypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1
				AND L.type = '1' 
				AND A.sonnum = 0
				AND A.TypeName='E' AND A.nTypeId LIKE '00004%'

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailATypeSr]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailATypeSr]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖收入-线性表
*/
CREATE FUNCTION F_GetManDetailATypeSr
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid int)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nId FROM dbo.Ac_Items WHERE SonNum = 0 AND TypeName='G' AND nTypeId LIKE '0000300003%'
	ELSE
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	a.nTypeId,A.nId 
		FROM	AType_L L
		INNER JOIN Ac_Items  A ON A.nTypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1
				AND L.type = '2' 
				AND A.sonnum = 0
				AND TypeName='G' AND A.nTypeId LIKE '0000300003%'

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailATypeZc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailATypeZc]
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖资产-线性表
*/
CREATE FUNCTION F_GetManDetailATypeZc
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nId FROM Ac_Items WHERE SonNum = 0 AND TypeName='F' AND nTypeId LIKE '0000100002%'
	ELSE
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	a.nTypeId,A.nId 
		FROM	AType_L L
		INNER JOIN Ac_Items  A ON A.nTypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1
				AND L.type = '3' 
				AND A.sonnum = 0
				AND A.TypeName='F'
				AND a.nTypeId LIKE '0000100002%'
	RETURN
END


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailBType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailBType]
GO















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-线性表
*/
CREATE FUNCTION F_GetManDetailBType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @TypeId varchar(100)
	--客户
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE SonNum = 0 AND TypeId LIKE '00001%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND B.typeId LIKE '00001%'
				AND L.flag = 1 
				AND B.sonnum = 0				

	--供货商
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE SonNum = 0 AND TypeId LIKE '00002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND B.typeId LIKE '00002%'
				AND L.flag = 1 
				AND B.sonnum = 0

	RETURN
END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailCType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailCType]
GO















/*
	作者：舒珊
	日期：2016-6-30
	描述：获取承运商-线性表
*/
CREATE FUNCTION F_GetManDetailCType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @TypeId varchar(100)
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
		INSERT INTO @Temp(TypeId) 
		SELECT TypeID FROM BType WHERE SonNum = 0 AND TypeId LIKE '00002%' AND iscarrier=1
	ELSE	
	INSERT INTO @Temp(TypeId) 
	SELECT	DISTINCT B.TypeId 
	FROM	BType_L L
	INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
	WHERE	L.etypeid = @chvOperatorId
			AND B.typeId LIKE '00002%'
			AND L.flag = 1 
			AND B.sonnum = 0
			AND B.iscarrier=1
	RETURN
END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_GetManDetailDType') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetManDetailDType
GO















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖部门-线性表
*/
CREATE FUNCTION F_GetManDetailDType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerDTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Department WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	D.TypeId 
		FROM	DType_L L
		INNER JOIN Department D ON D.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND D.sonnum = 0

	RETURN
END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailEType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailEType]
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖职员-线性表
*/
CREATE FUNCTION F_GetManDetailEType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '00001')		
		BEGIN
			INSERT INTO @Temp(TypeId)VALUES('00001')
			INSERT INTO @Temp(TypeId) SELECT TypeID FROM Employee WHERE SonNum = 0
		END
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	E.TypeId 
		FROM	EType_L L
		INNER JOIN Employee  E ON E.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND E.sonnum = 0

	RETURN
END



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailKType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailKType]
GO















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖仓库-线性表
*/
CREATE FUNCTION F_GetManDetailKType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Stock WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	K.TypeId 
		FROM	KType_L L
		INNER JOIN Stock  K ON K.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND K.sonnum = 0

	RETURN
END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailPType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailPType]
GO

/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖商品-线性表
*/
CREATE FUNCTION F_GetManDetailPType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	TypeId varchar(100)
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	P.TypeId 
		FROM	PType_L L
		INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND P.sonnum = 0
	RETURN
END




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





							  SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailPTypeIncludeCombination]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailPTypeIncludeCombination]
GO


/*
	作者：王刚
	日期：201-9-9
	描述：获取所有管辖商品-线性表 排除服务类商品
*/
CREATE FUNCTION F_GetManDetailPTypeIncludeCombination
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	TypeId varchar(100)
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType WHERE SonNum = 0 
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	P.TypeId 
		FROM	PType_L L
		INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND P.sonnum = 0
	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailPTypeNotService]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailPTypeNotService]
GO


/*
	作者：王刚
	日期：201-9-9
	描述：获取所有管辖商品-线性表 排除服务类商品
*/
CREATE FUNCTION F_GetManDetailPTypeNotService
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	TypeId varchar(100)
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType WHERE SonNum = 0 AND IsService = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	P.TypeId 
		FROM	PType_L L
		INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND P.sonnum = 0
				AND p.IsService = 0

	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailSType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailSType]
GO
/*

	作者：冯波
	日期：2010-5-6
	描述：获取所有管辖分支机构-线性表
*/


CREATE FUNCTION F_GetManDetailSType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')		
		BEGIN
			INSERT INTO @Temp(TypeId) SELECT TypeID FROM SType WHERE SonNum = 0
		END
	ELSE
		BEGIN
			/*
			DECLARE @TypeId varchar(100)			
			
			DECLARE SType_Cursor CURSOR FOR
				SELECT TypeId FROM SType_L WHERE ETypeID = @chvOperatorId AND Flag = 1

			OPEN SType_Cursor

			FETCH NEXT FROM SType_Cursor INTO @TypeId

			WHILE @@FETCH_STATUS = 0
				BEGIN
					INSERT INTO @Temp(TypeId) SELECT TypeId FROM SType WHERE TypeId LIKE @TypeID + '%' AND SonNum = 0

					FETCH NEXT FROM SType_Cursor INTO @TypeId
				END

			CLOSE SType_Cursor
			DEALLOCATE SType_Cursor
			*/
			
			INSERT INTO @Temp(TypeId) 
			SELECT	S.TypeId 
			FROM	SType_l L 
			--LEFT JOIN SType S ON LEFT(S.TypeId,LEN(L.TypeId)) = L.typeid 
			INNER JOIN SType S ON S.TypeId LIKE L.typeid+'%'
			WHERE	L.etypeid = @chvOperatorId 
					AND L.flag = 1 
					AND S.sonnum = 0
		END

	RETURN
END


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_ManPTypeFilterPTypeIdAndCategoryIdDetail]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_ManPTypeFilterPTypeIdAndCategoryIdDetail
GO

/*
	作者：谢吉康
	日期：2018-6-15
	描述：根据操作员，商品ID，商品类别来获取权限范围内的商品信息
	SELECT * FROM F_ManPTypeFilterPTypeIdAndCategoryIdDetail('00001',,'','')
*/
CREATE FUNCTION F_ManPTypeFilterPTypeIdAndCategoryIdDetail
(
	@chvOperatorId	VARCHAR(100),	--操作员ID
	@ptypeids		VARCHAR(MAX),	--商品ID
	@pctypeids		VARCHAR(MAX)	--商品类别ID	
)
RETURNS @Temp TABLE
(
	TypeId					VARCHAR(50),
	Deleted					VARCHAR(10),
	iscombinationproduct	VARCHAR(10)
)
--@Encode$--
AS
BEGIN	
	IF @ptypeids = '00000' OR @ptypeids = '' OR @ptypeids = '%'
		INSERT INTO @Temp(TypeId,Deleted,iscombinationproduct) 
		SELECT	TypeId,
				Deleted,
				iscombinationproduct 
		FROM	F_LinePtypeCategory(@chvOperatorId,@pctypeids)
	ELSE
		BEGIN					
			INSERT INTO @Temp(TypeId,Deleted,iscombinationproduct)
			SELECT 	DISTINCT A.TypeId,A.Deleted,A.iscombinationproduct
			FROM 	F_LinePtypeCategory(@chvOperatorId,@pctypeids) A, 
					(SELECT A FROM dbo.F_Split(@ptypeids,',')) B 
			WHERE	A.TypeId LIKE B.A + '%'
		END
		
	RETURN		
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManAType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManAType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖职员范围
*/
CREATE FUNCTION F_BaseGetManAType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT 	typeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				Name,
				UserCode,
				Comment,
				Total,
				Total00,
				sysflag,
				sysrow,
				deleted,
				j_d,
				PyCode,
				ifCanEdit,
				ifCanClass,
				ifCanDel,
				XiWaMaxNumber
		FROM 	AType 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
				AND TypeId <> '00000' 
				AND (TypeId LIKE '0000100004%' OR TypeId = '0000100003') 				
		UNION ALL
		SELECT 	A.typeId,
				A.parid,
				A.leveal,
				A.sonnum,
				A.soncount,
				A.FullName,
				A.Name,
				A.UserCode,
				A.Comment,
				A.Total,
				A.Total00,
				A.sysflag,
				A.sysrow,
				A.deleted,
				A.j_d,
				A.PyCode,
				A.ifCanEdit,
				A.ifCanClass,
				A.ifCanDel,
				A.XiWaMaxNumber
		FROM 	AType A INNER JOIN F_BaseGetManDetailAllAType(@chvOperatorId) M ON M.TypeId = A.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '-99999')
	)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManATypeFy]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManATypeFy]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖费用
*/
CREATE FUNCTION F_BaseGetManATypeFy
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN 	(
		SELECT 	typeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				Name,
				UserCode,
				Comment,
				Total,
				Total00,
				sysflag,
				sysrow,
				deleted,
				j_d,
				PyCode,
				ifCanEdit,
				ifCanClass,
				ifCanDel,
				XiWaMaxNumber
		FROM 	AType 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
				AND TypeId <> '00000' 
				AND TypeId LIKE '00004%' 
		UNION ALL
		SELECT 	A.typeId,
				A.parid,
				A.leveal,
				A.sonnum,
				A.soncount,
				A.FullName,
				A.Name,
				A.UserCode,
				A.Comment,
				A.Total,
				A.Total00,
				A.sysflag,
				A.sysrow,
				A.deleted,
				A.j_d,
				A.PyCode,
				A.ifCanEdit,
				A.ifCanClass,
				A.ifCanDel,
				A.XiWaMaxNumber
		FROM 	AType A INNER JOIN F_BaseGetManDetailAllATypeFy(@chvOperatorId) M ON M.TypeId = A.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '-99999')
	)





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManATypeSr]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManATypeSr]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖收入
*/
CREATE FUNCTION F_BaseGetManATypeSr
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT 	typeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				Name,
				UserCode,
				Comment,
				Total,
				Total00,
				sysflag,
				sysrow,
				deleted,
				j_d,
				PyCode,
				ifCanEdit,
				ifCanClass,
				ifCanDel,
				XiWaMaxNumber
		FROM 	AType 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '0000')
				AND TypeId <> '00000' 
				AND TypeId LIKE '00003%' 
		UNION ALL
		SELECT 	A.typeId,
				A.parid,
				A.leveal,
				A.sonnum,
				A.soncount,
				A.FullName,
				A.Name,
				A.UserCode,
				A.Comment,
				A.Total,
				A.Total00,
				A.sysflag,
				A.sysrow,
				A.deleted,
				A.j_d,
				A.PyCode,
				A.ifCanEdit,
				A.ifCanClass,
				A.ifCanDel,
				A.XiWaMaxNumber
		FROM 	AType A INNER JOIN F_GetManDetailAllATypeSr(@chvOperatorId) M ON A.TypeId = M.nTypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '-99999')
	)



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManATypeZc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManATypeZc]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO





















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖资产
*/
CREATE FUNCTION F_BaseGetManATypeZc
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT 	typeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				Name,
				UserCode,
				Comment,
				Total,
				Total00,
				sysflag,
				sysrow,
				deleted,
				j_d,
				PyCode,
				ifCanEdit,
				ifCanClass,
				ifCanDel,
				XiWaMaxNumber
		FROM 	AType 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
				AND TypeId <> '00000' 
				AND TypeId LIKE '0000100002%' 
		UNION ALL
		SELECT 	A.typeId,
				A.parid,
				A.leveal,
				A.sonnum,
				A.soncount,
				A.FullName,
				A.Name,
				A.UserCode,
				A.Comment,
				A.Total,
				A.Total00,
				A.sysflag,
				A.sysrow,
				A.deleted,
				A.j_d,
				A.PyCode,
				A.ifCanEdit,
				A.ifCanClass,
				A.ifCanDel,
				A.XiWaMaxNumber
		FROM 	AType A INNER JOIN F_BaseGetManDetailAllATypeZc(@chvOperatorId) M ON A.TypeId = M.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '-99999')
	)




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManBType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManBType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖往来单位范围
*/
CREATE FUNCTION F_BaseGetManBType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT	typeId,
				Bid,
				parid,
				leveal,
				soncount,
				sonnum,
				UserCode,
				FullName,
				Name,
				Area,
				TelAndAddress,
				PostCode,
				Person,
				TaxNumber,
				BankAndAcount,
				Comment,
				CreateDate,
				ARTotal,
				APTotal,
				ARTotal00,
				APTotal00,
				deleted,
				Client,
				ARLimit,
				initcomment,
				arapexplain,
				Tel1,
				Tel2,
				Tel3,
				Fax,
				WWW,
				Bank,
				BankName,
				Email,
				LinkMan1,
				LinkSex1,
				LinkBirthDay1,
				LinkJob1,
				LinkCall1,
				LinkTel1,
				LinkMobile1,
				LinkPost1,
				LinkAddress1,
				LinkEmail1,
				LinkComment1,
				LinkMan2,
				LinkSex2,
				LinkBirthDay2,
				LinkJob2,
				LinkCall2,
				LinkTel2,
				LinkMobile2,
				LinkPost2,
				LinkAddress2,
				LinkEmail2,
				LinkComment2,
				ARLimitTime,
				paymentLTime,
				SaleZekou,
				BuyZekou,
				PyCode,
				Price,
				AreaTypeID,
				smsMobile,
				smsComment,
				XiWaMaxNumber,
				etypeid,
				buyprice,
				ConsigneeAddress,
				Consignee,
				ConsigneeTel,
				cannotmodifyprice,
				denominatedid,
				Cid,
				chkskmonthday,
				skmonthday,
				chkfkmonthday,
				fkmonthday,
				dzdays,
				isusebrandartype
		FROM 	BType 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
				AND TypeId <> '00000' 
				AND TypeId LIKE '00001%' 
		UNION ALL
		SELECT	B.typeId,
				B.Bid,
				B.parid,
				B.leveal,
				B.soncount,
				B.sonnum,
				B.UserCode,
				B.FullName,
				B.Name,
				B.Area,
				B.TelAndAddress,
				B.PostCode,
				B.Person,
				B.TaxNumber,
				B.BankAndAcount,
				B.Comment,
				B.CreateDate,
				B.ARTotal,
				B.APTotal,
				B.ARTotal00,
				B.APTotal00,
				B.deleted,
				B.Client,
				B.ARLimit,
				B.initcomment,
				B.arapexplain,
				B.Tel1,
				B.Tel2,
				B.Tel3,
				B.Fax,
				B.WWW,
				B.Bank,
				B.BankName,
				B.Email,
				B.LinkMan1,
				B.LinkSex1,
				B.LinkBirthDay1,
				B.LinkJob1,
				B.LinkCall1,
				B.LinkTel1,
				B.LinkMobile1,
				B.LinkPost1,
				B.LinkAddress1,
				B.LinkEmail1,
				B.LinkComment1,
				B.LinkMan2,
				B.LinkSex2,
				B.LinkBirthDay2,
				B.LinkJob2,
				B.LinkCall2,
				B.LinkTel2,
				B.LinkMobile2,
				B.LinkPost2,
				B.LinkAddress2,
				B.LinkEmail2,
				B.LinkComment2,
				B.ARLimitTime,
				B.paymentLTime,
				B.SaleZekou,
				B.BuyZekou,
				B.PyCode,
				B.Price,
				B.AreaTypeID,
				B.smsMobile,
				B.smsComment,
				B.XiWaMaxNumber,
				B.etypeid,
				B.buyprice,
				B.ConsigneeAddress,
				B.Consignee,
				B.ConsigneeTel,
				B.cannotmodifyprice,
				denominatedid,
				B.Cid,
				B.chkskmonthday,
				B.skmonthday,
				B.chkfkmonthday,
				B.fkmonthday,
				B.dzdays,
				B.isusebrandartype
		FROM 	BType B INNER JOIN F_BaseGetManDetailAllBType(@chvOperatorId) M ON B.TypeId = M.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '-99999')
				AND B.TypeId LIKE '00001%' 
		UNION ALL		
		SELECT	typeId,
				Bid,
				parid,
				leveal,
				soncount,
				sonnum,
				UserCode,
				FullName,
				Name,
				Area,
				TelAndAddress,
				PostCode,
				Person,
				TaxNumber,
				BankAndAcount,
				Comment,
				CreateDate,
				ARTotal,
				APTotal,
				ARTotal00,
				APTotal00,
				deleted,
				Client,
				ARLimit,
				initcomment,
				arapexplain,
				Tel1,
				Tel2,
				Tel3,
				Fax,
				WWW,
				Bank,
				BankName,
				Email,
				LinkMan1,
				LinkSex1,
				LinkBirthDay1,
				LinkJob1,
				LinkCall1,
				LinkTel1,
				LinkMobile1,
				LinkPost1,
				LinkAddress1,
				LinkEmail1,
				LinkComment1,
				LinkMan2,
				LinkSex2,
				LinkBirthDay2,
				LinkJob2,
				LinkCall2,
				LinkTel2,
				LinkMobile2,
				LinkPost2,
				LinkAddress2,
				LinkEmail2,
				LinkComment2,
				ARLimitTime,
				paymentLTime,
				SaleZekou,
				BuyZekou,
				PyCode,
				Price,
				AreaTypeID,
				smsMobile,
				smsComment,
				XiWaMaxNumber,
				etypeid,
				buyprice,
				ConsigneeAddress,
				Consignee,
				ConsigneeTel,
				cannotmodifyprice,
				denominatedid,
				Cid,
				chkskmonthday,
				skmonthday,
				chkfkmonthday,
				fkmonthday,
				dzdays,
				isusebrandartype
		FROM 	BType
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
				AND TypeId <> '00000' 
				AND TypeId LIKE '00002%' 
		UNION ALL
		SELECT	B.typeId,
				B.Bid,
				B.parid,
				B.leveal,
				B.soncount,
				B.sonnum,
				B.UserCode,
				B.FullName,
				B.Name,
				B.Area,
				B.TelAndAddress,
				B.PostCode,
				B.Person,
				B.TaxNumber,
				B.BankAndAcount,
				B.Comment,
				B.CreateDate,
				B.ARTotal,
				B.APTotal,
				B.ARTotal00,
				B.APTotal00,
				B.deleted,
				B.Client,
				B.ARLimit,
				B.initcomment,
				B.arapexplain,
				B.Tel1,
				B.Tel2,
				B.Tel3,
				B.Fax,
				B.WWW,
				B.Bank,
				B.BankName,
				B.Email,
				B.LinkMan1,
				B.LinkSex1,
				B.LinkBirthDay1,
				B.LinkJob1,
				B.LinkCall1,
				B.LinkTel1,
				B.LinkMobile1,
				B.LinkPost1,
				B.LinkAddress1,
				B.LinkEmail1,
				B.LinkComment1,
				B.LinkMan2,
				B.LinkSex2,
				B.LinkBirthDay2,
				B.LinkJob2,
				B.LinkCall2,
				B.LinkTel2,
				B.LinkMobile2,
				B.LinkPost2,
				B.LinkAddress2,
				B.LinkEmail2,
				B.LinkComment2,
				B.ARLimitTime,
				B.paymentLTime,
				B.SaleZekou,
				B.BuyZekou,
				B.PyCode,
				B.Price,
				B.AreaTypeID,
				B.smsMobile,
				B.smsComment,
				B.XiWaMaxNumber,
				B.etypeid,
				B.buyprice,
				B.ConsigneeAddress,
				B.Consignee,
				B.ConsigneeTel,
				B.cannotmodifyprice,
				denominatedid,
				B.Cid,
				B.chkskmonthday,
				B.skmonthday,
				B.chkfkmonthday,
				B.fkmonthday,
				B.dzdays,
				B.isusebrandartype
		FROM 	BType B INNER JOIN F_BaseGetManDetailAllBType(@chvOperatorId) M ON B.TypeId = M.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '-99999')
				AND B.TypeId LIKE '00002%' 
)

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖部门范围
*/
CREATE FUNCTION F_BaseGetManDType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	typeid    		varchar(150),
	parid    		varchar(150),
	leveal    		varchar(10),
	sonnum    		varchar(10),
	soncount    	varchar(10),
	usercode    	varchar(200),
	FullName    	varchar(200),
	Name    		varchar(200),
	Comment    		varchar(200),
	deleted    		varchar(10),
	Tel    			varchar(150),
	LinkMan    		varchar(150),
	Fax    			varchar(150),
	rec    			varchar(10),
	namepy    		varchar(200),
	parrec    		varchar(10),
	OrderNo    		varchar(10),
	PyCode    		varchar(600),
	XiWaMaxNumber    NUMERIC(24, 10) 
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerDTypeID = '00000')
		INSERT INTO @Temp	
		SELECT 	typeid,
				parid,
				leveal,
				sonnum,
				soncount,
				usercode,
				FullName,
				Name,
				Comment,
				deleted,
				Tel,
				LinkMan,
				Fax,
				rec,
				namepy,
				parrec,
				OrderNo,
				PyCode,
				XiWaMaxNumber 
		FROM 	Department
		WHERE 	TypeId <> '00000'
	ELSE
		INSERT INTO @Temp	
		SELECT 	typeid,
				parid,
				leveal,
				sonnum,
				soncount,
				usercode,
				FullName,
				Name,
				Comment,
				deleted,
				Tel,
				LinkMan,
				Fax,
				rec,
				namepy,
				parrec,
				OrderNo,
				PyCode,
				XiWaMaxNumber 
		FROM 	Department
		WHERE	TypeId IN (SELECT TypeId FROM F_BaseGetManDetailAllDType(@chvOperatorId))

	RETURN
END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManEType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManEType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖职员范围
*/
CREATE FUNCTION F_BaseGetManEType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
	 	SELECT 	BtypeID,
				typeId,
				Parid,
				leveal,
				soncount,
				sonnum,
				FullName,
				Name,
				UserCode,
				Department,
				Tel,
				Address,
				Comment,
				deleted,
				Sex,
				Nation,
				Knowledge,
				Blood,
				Health,
				IDcard,
				Birthday,
				Marriage,
				Job,
				Job2,
				JobTime,
				Tel2,
				Mob,
				Mail,
				political,
				nat_place,
				college,
				for_language,
				reg_place,
				com_level,
				weight,
				stature,
				fam_status,
				informer,
				speciality,
				for_lan_level,
				PostCode,
				Email,
				DtypeID,
				PyCode,
				MaxPre,
				smsMobile,
				smsComment,
				tichengRate,
				XiWaMaxNumber,
				STypeId,
				QQ,
				MSN,
				Blog,
				mBlog,
				Team,
				HrpostionId,
				HrPersonStatu
		FROM 	Employee 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '00001')
				AND TypeId <> '00000' 
		UNION ALL
		SELECT 	E.BtypeID,
				E.typeId,
				E.Parid,
				E.leveal,
				E.soncount,
				E.sonnum,
				E.FullName,
				E.Name,
				E.UserCode,
				E.Department,
				E.Tel,
				E.Address,
				E.Comment,
				E.deleted,
				E.Sex,
				E.Nation,
				E.Knowledge,
				E.Blood,
				E.Health,
				E.IDcard,
				E.Birthday,
				E.Marriage,
				E.Job,
				E.Job2,
				E.JobTime,
				E.Tel2,
				E.Mob,
				E.Mail,
				E.political,
				E.nat_place,
				E.college,
				E.for_language,
				E.reg_place,
				E.com_level,
				E.weight,
				E.stature,
				E.fam_status,
				E.informer,
				E.speciality,
				E.for_lan_level,
				E.PostCode,
				E.Email,
				E.DtypeID,
				E.PyCode,
				E.MaxPre,
				E.smsMobile,
				E.smsComment,
				E.tichengRate,
				E.XiWaMaxNumber,
				E.STypeId,
				E.QQ,
				E.MSN,
				E.Blog,
				E.mBlog,
				E.Team,
				E.HrpostionId,
				E.HrPersonStatu
		FROM	Employee E INNER JOIN F_BaseGetManDetailAllEType(@chvOperatorId) M ON M.TypeId = E.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '-99999')
)























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManKType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManKType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖商品范围
*/
CREATE FUNCTION F_BaseGetManKType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT 	typeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				Name,
				UserCode,
				Comment,
				deleted,
				[Add],
				Tel,
				LinkMan,
				PyCode,
				STypeId,
				XiWaMaxNumber
		FROM 	Stock 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
				AND TypeId <> '00000' 
		UNION ALL
		SELECT 	K.typeId,
				K.parid,
				K.leveal,
				K.sonnum,
				K.soncount,
				K.FullName,
				K.Name,
				K.UserCode,
				K.Comment,
				K.deleted,
				K.[Add],
				K.Tel,
				K.LinkMan,
				K.PyCode,
				K.STypeId,
				K.XiWaMaxNumber
		FROM 	Stock K INNER JOIN F_BaseGetManDetailAllKType(@chvOperatorId) M ON M.TypeId = K.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '-99999')

	)























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManPType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManPType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖商品范围
*/
CREATE FUNCTION F_BaseGetManPType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT 	P.typeId,
				P.ParId,
				P.leveal,
				P.sonnum,
				P.soncount,
				P.CanModify,
				P.UserCode,
				P.FullName,
				P.Name,
				P.Standard,
				P.Type,
				P.Area,
				P.Unit1,
				P.Unit2,
				P.UnitRate1,
				P.UnitRate2,
				P.preprice1,
				P.preprice2,
				P.preprice3,
				P.preprice4,
				P.preprice5,
				P.UsefulLifeMonth,
				P.UsefulLifeDay,
				P.Comment,
				P.recPrice,
				P.deleted,
				P.ColorGroupID,
				P.SizeGroupID,
				P.EntryCode,
				P.IfSerial,
				P.PyCode,
				P.SerialCount,
				P.ValidDays,
				P.DwgNo,
				P.XiWaMaxNumber,
				E.Brand,
				E.Import,
				E.GeneralType,
				E.GeneralDwgNo,
				E.Property,
				E.PackageQty,
				E.Weight,
				E.TaxNumber,
				E.Taxrate,
				E.BTypeID,
				E.FcUnit,
				E.FcPrice,
				R.PreBuyPrice1,
				R.PreBuyPrice2,
				R.PreBuyPrice3,
				R.PreBuyPrice4,
				R.PreBuyPrice5,
				R.PreSalePrice1,
				R.PreSalePrice2,
				R.PreSalePrice3,
				R.PreSalePrice4,
				R.PreSalePrice5,
				R.PreSalePrice6,
				R.PreSalePrice7,
				R.PreSalePrice8,
				R.PreSalePrice9,
				R.PreSalePrice10,
				R.RetailPrice,
				R.TopSalePrice,
				R.LowSalePrice,p.IsService
		FROM 	PType P
		INNER JOIN (
			SELECT	PTypeId,
					PreBuyPrice1,
					PreBuyPrice2,
					PreBuyPrice3,
					PreBuyPrice4,
					PreBuyPrice5,
					PreSalePrice1,
					PreSalePrice2,
					PreSalePrice3,
					PreSalePrice4,
					PreSalePrice5,
					PreSalePrice6,
					PreSalePrice7,
					PreSalePrice8,
					PreSalePrice9,
					PreSalePrice10,
					RetailPrice,
					TopSalePrice,
					LowSalePrice,
					isdefaultunit
			FROM 	PType_Price
		)R ON R.PTypeId = P.TypeId and R.isdefaultunit=1
		LEFT JOIN (
			SELECT	PTypeID,
					Brand,
					Import,
					GeneralType,
					GeneralDwgNo,
					Property,
					PackageQty,
					Weight,
					TaxNumber,
					Taxrate,
					BTypeID,
					FcUnit,
					FcPrice
			FROM 	Qp_PType_Ext
		)E ON E.PTypeId = P.TypeId
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
				AND P.TypeId <> '00000' 
		UNION ALL		
		SELECT 	P.typeId,
				P.ParId,
				P.leveal,
				P.sonnum,
				P.soncount,
				P.CanModify,
				P.UserCode,
				P.FullName,
				P.Name,
				P.Standard,
				P.Type,
				P.Area,
				P.Unit1,
				P.Unit2,
				P.UnitRate1,
				P.UnitRate2,
				P.preprice1,
				P.preprice2,
				P.preprice3,
				P.preprice4,
				P.preprice5,
				P.UsefulLifeMonth,
				P.UsefulLifeDay,
				P.Comment,
				P.recPrice,
				P.deleted,
				P.ColorGroupID,
				P.SizeGroupID,
				P.EntryCode,
				P.IfSerial,
				P.PyCode,
				P.SerialCount,
				P.ValidDays,
				P.DwgNo,
				P.XiWaMaxNumber,
				E.Brand,
				E.Import,
				E.GeneralType,
				E.GeneralDwgNo,
				E.Property,
				E.PackageQty,
				E.Weight,
				E.TaxNumber,
				E.Taxrate,
				E.BTypeID,
				E.FcUnit,
				E.FcPrice,
				R.PreBuyPrice1,
				R.PreBuyPrice2,
				R.PreBuyPrice3,
				R.PreBuyPrice4,
				R.PreBuyPrice5,
				R.PreSalePrice1,
				R.PreSalePrice2,
				R.PreSalePrice3,
				R.PreSalePrice4,
				R.PreSalePrice5,
				R.PreSalePrice6,
				R.PreSalePrice7,
				R.PreSalePrice8,
				R.PreSalePrice9,
				R.PreSalePrice10,
				R.RetailPrice,
				R.TopSalePrice,
				R.LowSalePrice,
				p.IsService
		FROM 	PType P
		INNER JOIN F_BaseGetManDetailAllPType(@chvOperatorId) M ON P.TypeId = M.TypeId
		INNER JOIN (
			SELECT	PTypeId,
					PreBuyPrice1,
					PreBuyPrice2,
					PreBuyPrice3,
					PreBuyPrice4,
					PreBuyPrice5,
					PreSalePrice1,
					PreSalePrice2,
					PreSalePrice3,
					PreSalePrice4,
					PreSalePrice5,
					PreSalePrice6,
					PreSalePrice7,
					PreSalePrice8,
					PreSalePrice9,
					PreSalePrice10,
					RetailPrice,
					TopSalePrice,
					LowSalePrice,
					isdefaultunit
			FROM 	PType_Price
		)R ON R.PTypeId = P.TypeId  and R.isdefaultunit=1
		LEFT JOIN (
			SELECT	PTypeID,
					Brand,
					Import,
					GeneralType,
					GeneralDwgNo,
					Property,
					PackageQty,
					Weight,
					TaxNumber,
					Taxrate,
					BTypeID,
					FcUnit,
					FcPrice
			FROM 	Qp_PType_Ext
		)E ON E.PTypeId = P.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '-99999')
	)




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManSType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManSType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖分支机构范围
*/

CREATE FUNCTION F_BaseGetManSType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	TypeId			varchar(50),
	parid			varchar(50),
	leveal			varchar(10),
	sonnum			varchar(10),
	soncount		varchar(10),
	FullName		varchar(66),
	[Name]			varchar(30),
	UserCode		varchar(26),
	Comment			varchar(256),
	LinkMan			varchar(100),
	Address			varchar(100),
	Tel				varchar(100),
	PostCode		varchar(100),
	TaxNo			varchar(100),
	Bank			varchar(100),
	Account			varchar(100),
	deleted			varchar(10),
	PyCode			varchar(500),
	BTypeId1		varchar(50),
	BTypeId2		varchar(50),
	XiWaMaxNumber	numeric(18,0)
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')
		INSERT INTO @Temp	
		SELECT 	TypeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				[Name],
				UserCode,
				Comment,
				LinkMan,
				Address,
				Tel,
				PostCode,
				TaxNo,
				Bank,
				Account,
				deleted,
				PyCode,
				BTypeId1,
				BTypeId2,
				XiWaMaxNumber
		FROM 	SType 
		WHERE 	TypeId <> '00000'
	ELSE
		INSERT INTO @Temp	
		SELECT 	TypeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				[Name],
				UserCode,
				Comment,
				LinkMan,
				Address,
				Tel,
				PostCode,
				TaxNo,
				Bank,
				Account,
				deleted,
				PyCode,
				BTypeId1,
				BTypeId2,
				XiWaMaxNumber
		FROM 	SType 
		WHERE	TypeId IN (SELECT TypeId FROM F_BaseGetManDetailAllSType(@chvOperatorId))

	RETURN
END



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetBillDetails]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetBillDetails]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION F_GetBillDetails
(
	@billtype	NUMERIC,
	@ptype	VARCHAR(50)
)
RETURNS @TABLE TABLE(
		[BillNumberId] [numeric](10, 0) NULL,
		[PtypeId] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
		SendedQty DECIMAL(24,10) NULL DEFAULT(0))
AS
BEGIN
	DECLARE @BillTableName VARCHAR(100),
			@BillNumberId numeric(10, 0),
			@PtypeId VARCHAR(50),
			@SendedQty DECIMAL(24,10)
	
	if(@billtype=11)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from salebill WHERE PtypeId=@ptype
	if(@billtype=160)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from salegoodsexchangebill WHERE PtypeId=@ptype
	if(@billtype=139)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from givebill WHERE PtypeId=@ptype
	if(@billtype IN (140,146))
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from commissionbill WHERE PtypeId=@ptype
	if(@billtype=6)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from buybackbill WHERE PtypeId=@ptype
	if(@billtype=161)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from buygoodsexchangebill WHERE PtypeId=@ptype
	if(@billtype=17)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from movebill WHERE PtypeId=@ptype
	if(@billtype=21)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from movebjbill WHERE PtypeId=@ptype
	if(@billtype=187)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from stypemovebill WHERE PtypeId=@ptype
	if(@billtype=202)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from otherinoutbill WHERE PtypeId=@ptype
	if(@billtype=16)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from disassemblebill WHERE PtypeId=@ptype
	if(@billtype=183)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from integralexchangebill WHERE PtypeId=@ptype
	if(@billtype=401)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from AppraisalBackBill WHERE PtypeId=@ptype
	if(@billtype=402)
		select @BillNumberId=BillNumberId,@PtypeId=PtypeId,@SendedQty=SendedQty from SendBill WHERE PtypeId=@ptype
	
	INSERT INTO @TABLE( BillNumberId, PtypeId, SendedQty )
	VALUES(@BillNumberId,@PtypeId,CASE WHEN @SendedQty IS NULL THEN 0 ELSE @SendedQty end)
	
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetCommissionBTypeID]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetCommissionBTypeID]
GO
-- =============================================
-- Author:		
-- Create date: 
-- Description:	获取代销结算单位

-- =============================================

CREATE FUNCTION [dbo].[F_GetCommissionBTypeID](
	@strSerial			VARCHAR(500),
	@State				INT,
	@BillType			INT
	)
RETURNS VARCHAR(50)
WITH EXECUTE AS caller
AS
BEGIN
	DECLARE
		@intBillNumberID	INT,
		@strBTypeID			VARCHAR(50)

	IF @State IN (7,32,9,10,11,16,14,13)
	BEGIN
		SELECT TOP 1 @intBillNumberID=CAST(a.BillNumberid AS BIGINT)
		FROM gp_inoutPtypeSerial a
		INNER JOIN BillIndex b ON a.BillNumberid=b.BillNumberId
		WHERE a.Serial=@strSerial AND a.BillType=@BillType AND b.RedWord=0
		ORDER BY B.posttime DESC
	END
	ELSE
	BEGIN		
		SELECT TOP 1 @intBillNumberID=CAST(a.BillNumberid AS BIGINT)
		FROM gp_inoutPtypeSerial a
		INNER JOIN BillIndex b ON a.BillNumberid=b.BillNumberId
		WHERE a.Serial=@strSerial AND b.RedWord=0
		ORDER BY B.posttime DESC
	END

	SELECT @strBTypeID=btypeid
	FROM Billindex
	WHERE BillNumberId=@intBillNumberID
	
	SELECT @strBTypeID=ISNULL(@strBTypeID,'')
	
	IF @strBTypeID=''
	BEGIN
		IF @BillType=144
		BEGIN
			SELECT @strBTypeID=BTypeID2
			FROM gp_CruPtypeSerial
			WHERE Serial=@strSerial
		END
		ELSE
		BEGIN
			--140
			SELECT @strBTypeID=BTypeID1
			FROM gp_CruPtypeSerial
			WHERE Serial=@strSerial
		END
	END
	
	
	RETURN ISNULL(@strBTypeID,'')
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManAType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManAType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖职员范围
*/
CREATE FUNCTION F_GetManAType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  nId AS Typeid,
				nId,
				TypeId as atypeid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
				--AND TypeName='B'
				AND (nTypeId LIKE '0000100004%' OR nTypeId LIKE '0000100003%')
		UNION ALL
		SELECT  A.nId AS Typeid,
				a.nid,
				A.TypeId as atypeid,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN F_GetManDetailAllAType(@chvOperatorId) M ON M.nTypeId = A.nTypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '-99999')
		--AND a.nTypeId<>'00001'
	)























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManATypeFy]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManATypeFy]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖费用
*/
CREATE FUNCTION F_GetManATypeFy
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN 	(
		SELECT  nId AS Typeid,
				nid,
				TypeId as atypeid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
				AND TypeName='E' 
				AND nTypeId <> '00000' 
				AND nTypeId LIKE '00004%' 
		UNION ALL
		SELECT  a.nId AS typeid,
				a.nId,
				a.TypeId AS atypeid,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN F_GetManDetailAllATypeFy(@chvOperatorId) M ON M.nTypeId = A.nTypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '-99999')
			AND a.TypeName='E' 
	)




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManATypeSr]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManATypeSr]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖收入
*/
CREATE FUNCTION F_GetManATypeSr
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT  nId  AS typeid,
				TypeId AS Atypeid ,
				nId,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '0000')
				AND TypeName='G' 
				AND nTypeId <> '00000' 
				AND nTypeId LIKE '00003%' 
		UNION ALL
		SELECT  a.nId  AS typeid,
				a.TypeId AS Atypeid ,
				a.nId,
				a.nTypeId,
				a.nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A
		INNER JOIN F_GetManDetailAllATypeSr(@chvOperatorId) M ON A.nTypeId = M.nTypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '-99999')
	)


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManATypeZc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManATypeZc]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖资产
*/
CREATE FUNCTION F_GetManATypeZc
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT  nId AS Typeid,
				nId,
				TypeId as atypeid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
				AND TypeName='F' 
				AND nTypeId <> '00000' 
				AND nTypeId LIKE '0000100002%' 
		UNION ALL
		SELECT  a.nId AS typeid,
				a.nId,
				a.TypeId AS atypeid,
				a.nTypeId,
				a.nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN F_GetManDetailAllATypeZC(@chvOperatorId) M ON M.nTypeId = A.nTypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '-99999')
			AND a.TypeName='F' 
	)



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManBType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManBType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖往来单位范围
*/

/*
	修改者：廖晨羽
	日期：2011-08-18
	描述：添加etypeid字段，关联职员功能
*/

/*
	修改者：吕文祺
	日期：2012-04-18
	描述：添加字段denominatedid为查询出权限以外的字段
*/


CREATE FUNCTION F_GetManBType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT	typeId,
				Bid,
				parid,
				leveal,
				soncount,
				sonnum,
				UserCode,
				FullName,
				Name,
				Area,
				TelAndAddress,
				PostCode,
				Person,
				TaxNumber,
				BankAndAcount,
				Comment,
				CreateDate,
				ARTotal,
				APTotal,
				ARTotal00,
				APTotal00,
				deleted,
				Client,
				ARLimit,
				initcomment,
				arapexplain,
				Tel1,
				Tel2,
				Tel3,
				Fax,
				WWW,
				Bank,
				BankName,
				Email,
				LinkMan1,
				LinkSex1,
				LinkBirthDay1,
				LinkJob1,
				LinkCall1,
				LinkTel1,
				LinkMobile1,
				LinkPost1,
				LinkAddress1,
				LinkEmail1,
				LinkComment1,
				LinkMan2,
				LinkSex2,
				LinkBirthDay2,
				LinkJob2,
				LinkCall2,
				LinkTel2,
				LinkMobile2,
				LinkPost2,
				LinkAddress2,
				LinkEmail2,
				LinkComment2,
				ARLimitTime,
				paymentLTime,
				SaleZekou,
				BuyZekou,
				PyCode,
				Price,
				AreaTypeID,
				smsMobile,
				smsComment,
				XiWaMaxNumber,
				etypeid,
				buyprice,
				ConsigneeAddress,
				Consignee,
				ConsigneeTel,
				cannotmodifyprice,
				denominatedid,
				Cid,
				chkskmonthday,
				skmonthday,
				chkfkmonthday,
				fkmonthday,
				dzdays,
				iscarrier,
				IsWmsSync,
				isusebrandartype,
				isnull(skmonth,0) as skmonth,
				isnull(skday,0) as skday,
				isnull(skdzdayflag,0) as skdzdayflag,
				isnull(skcyjartime,0) as skcyjartime,
				isnull(fkmonth,0) as fkmonth,
				isnull(fkday,0) as fkday,
				isnull(fkdzdayflag,0) as fkdzdayflag,
				isnull(fkcyjaptime,0) as fkcyjaptime
		FROM 	BType 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
				AND TypeId <> '00000' 
				AND TypeId LIKE '00001%' 
		UNION ALL
		SELECT	B.typeId,
				B.Bid,
				B.parid,
				B.leveal,
				B.soncount,
				B.sonnum,
				B.UserCode,
				B.FullName,
				B.Name,
				B.Area,
				B.TelAndAddress,
				B.PostCode,
				B.Person,
				B.TaxNumber,
				B.BankAndAcount,
				B.Comment,
				B.CreateDate,
				B.ARTotal,
				B.APTotal,
				B.ARTotal00,
				B.APTotal00,
				B.deleted,
				B.Client,
				B.ARLimit,
				B.initcomment,
				B.arapexplain,
				B.Tel1,
				B.Tel2,
				B.Tel3,
				B.Fax,
				B.WWW,
				B.Bank,
				B.BankName,
				B.Email,
				B.LinkMan1,
				B.LinkSex1,
				B.LinkBirthDay1,
				B.LinkJob1,
				B.LinkCall1,
				B.LinkTel1,
				B.LinkMobile1,
				B.LinkPost1,
				B.LinkAddress1,
				B.LinkEmail1,
				B.LinkComment1,
				B.LinkMan2,
				B.LinkSex2,
				B.LinkBirthDay2,
				B.LinkJob2,
				B.LinkCall2,
				B.LinkTel2,
				B.LinkMobile2,
				B.LinkPost2,
				B.LinkAddress2,
				B.LinkEmail2,
				B.LinkComment2,
				B.ARLimitTime,
				B.paymentLTime,
				B.SaleZekou,
				B.BuyZekou,
				B.PyCode,
				B.Price,
				B.AreaTypeID,
				B.smsMobile,
				B.smsComment,
				B.XiWaMaxNumber,
				B.etypeid,
				B.buyprice,
				B.ConsigneeAddress,
				B.Consignee,
				B.ConsigneeTel,
				B.cannotmodifyprice,
				denominatedid,
				B.Cid,
				B.chkskmonthday,
				B.skmonthday,
				B.chkfkmonthday,
				B.fkmonthday,
				B.dzdays,
				B.iscarrier,
				B.IsWmsSync,
				B.isusebrandartype,
				isnull(b.skmonth,0) as skmonth,
				isnull(b.skday,0) as skday,
				isnull(b.skdzdayflag,0) as skdzdayflag,
				isnull(b.skcyjartime,0) as skcyjartime,
				isnull(b.fkmonth,0) as fkmonth,
				isnull(b.fkday,0) as fkday,
				isnull(b.fkdzdayflag,0) as fkdzdayflag,
				isnull(b.fkcyjaptime,0) as fkcyjaptime
		FROM 	BType B INNER JOIN F_GetManDetailAllBType(@chvOperatorId) M ON B.TypeId = M.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '-99999')
				AND B.TypeId LIKE '00001%' 
		UNION ALL		
		SELECT	typeId,
				Bid,
				parid,
				leveal,
				soncount,
				sonnum,
				UserCode,
				FullName,
				Name,
				Area,
				TelAndAddress,
				PostCode,
				Person,
				TaxNumber,
				BankAndAcount,
				Comment,
				CreateDate,
				ARTotal,
				APTotal,
				ARTotal00,
				APTotal00,
				deleted,
				Client,
				ARLimit,
				initcomment,
				arapexplain,
				Tel1,
				Tel2,
				Tel3,
				Fax,
				WWW,
				Bank,
				BankName,
				Email,
				LinkMan1,
				LinkSex1,
				LinkBirthDay1,
				LinkJob1,
				LinkCall1,
				LinkTel1,
				LinkMobile1,
				LinkPost1,
				LinkAddress1,
				LinkEmail1,
				LinkComment1,
				LinkMan2,
				LinkSex2,
				LinkBirthDay2,
				LinkJob2,
				LinkCall2,
				LinkTel2,
				LinkMobile2,
				LinkPost2,
				LinkAddress2,
				LinkEmail2,
				LinkComment2,
				ARLimitTime,
				paymentLTime,
				SaleZekou,
				BuyZekou,
				PyCode,
				Price,
				AreaTypeID,
				smsMobile,
				smsComment,
				XiWaMaxNumber,
				etypeid,
				buyprice,
				ConsigneeAddress,
				Consignee,
				ConsigneeTel,
				cannotmodifyprice,
				denominatedid,
				Cid,
				chkskmonthday,
				skmonthday,
				chkfkmonthday,
				fkmonthday,
				dzdays,
				iscarrier,
				IsWmsSync,
				isusebrandartype,
				isnull(skmonth,0) as skmonth,
				isnull(skday,0) as skday,
				isnull(skdzdayflag,0) as skdzdayflag,
				isnull(skcyjartime,0) as skcyjartime,
				isnull(fkmonth,0) as fkmonth,
				isnull(fkday,0) as fkday,
				isnull(fkdzdayflag,0) as fkdzdayflag,
				isnull(fkcyjaptime,0) as fkcyjaptime
		FROM 	BType
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
				AND TypeId <> '00000' 
				AND TypeId LIKE '00002%' 
		UNION ALL
		SELECT	B.typeId,
				B.Bid,
				B.parid,
				B.leveal,
				B.soncount,
				B.sonnum,
				B.UserCode,
				B.FullName,
				B.Name,
				B.Area,
				B.TelAndAddress,
				B.PostCode,
				B.Person,
				B.TaxNumber,
				B.BankAndAcount,
				B.Comment,
				B.CreateDate,
				B.ARTotal,
				B.APTotal,
				B.ARTotal00,
				B.APTotal00,
				B.deleted,
				B.Client,
				B.ARLimit,
				B.initcomment,
				B.arapexplain,
				B.Tel1,
				B.Tel2,
				B.Tel3,
				B.Fax,
				B.WWW,
				B.Bank,
				B.BankName,
				B.Email,
				B.LinkMan1,
				B.LinkSex1,
				B.LinkBirthDay1,
				B.LinkJob1,
				B.LinkCall1,
				B.LinkTel1,
				B.LinkMobile1,
				B.LinkPost1,
				B.LinkAddress1,
				B.LinkEmail1,
				B.LinkComment1,
				B.LinkMan2,
				B.LinkSex2,
				B.LinkBirthDay2,
				B.LinkJob2,
				B.LinkCall2,
				B.LinkTel2,
				B.LinkMobile2,
				B.LinkPost2,
				B.LinkAddress2,
				B.LinkEmail2,
				B.LinkComment2,
				B.ARLimitTime,
				B.paymentLTime,
				B.SaleZekou,
				B.BuyZekou,
				B.PyCode,
				B.Price,
				B.AreaTypeID,
				B.smsMobile,
				B.smsComment,
				B.XiWaMaxNumber,
				B.etypeid,
				B.buyprice,
				B.ConsigneeAddress,
				B.Consignee,
				B.ConsigneeTel,
				B.cannotmodifyprice,
				denominatedid,
				B.Cid,
				B.chkskmonthday,
				B.skmonthday,
				B.chkfkmonthday,
				B.fkmonthday,
				B.dzdays,
				B.iscarrier,
				B.IsWmsSync,
				B.isusebrandartype,
				isnull(b.skmonth,0) as skmonth,
				isnull(b.skday,0) as skday,
				isnull(b.skdzdayflag,0) as skdzdayflag,
				isnull(b.skcyjartime,0) as skcyjartime,
				isnull(b.fkmonth,0) as fkmonth,
				isnull(b.fkday,0) as fkday,
				isnull(b.fkdzdayflag,0) as fkdzdayflag,
				isnull(b.fkcyjaptime,0) as fkcyjaptime
		FROM 	BType B INNER JOIN F_GetManDetailAllBType(@chvOperatorId) M ON B.TypeId = M.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '-99999')
				AND B.TypeId LIKE '00002%' 
)






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailBTypeForAudit]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailBTypeForAudit]
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-线性表
*/
CREATE FUNCTION F_GetManDetailBTypeForAudit
(
	@chvOperatorId			varchar(100),
	@Btypeid				VARCHAR(50)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @TypeId varchar(100)
	--客户
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE typeid = @Btypeid AND SonNum = 0 AND TypeId LIKE '00001%' 
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType  B ON B.TypeId = @Btypeid AND B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId				
				AND B.typeId LIKE '00001%'
				AND L.flag = 1 
				AND B.sonnum = 0					

	--供货商
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE typeid = @Btypeid AND SonNum = 0 AND TypeId LIKE '00002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType  B ON B.typeId = @Btypeid AND B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId				
				AND B.typeId LIKE '00002%'
				AND L.flag = 1 
				AND B.sonnum = 0				

	RETURN
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_GetManDType') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetManDType
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖部门范围
*/
CREATE FUNCTION F_GetManDType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	typeid    		varchar(150),
	parid    		varchar(150),
	leveal    		varchar(10),
	sonnum    		varchar(10),
	soncount    	varchar(10),
	usercode    	varchar(200),
	FullName    	varchar(200),
	Name    		varchar(200),
	Comment    		varchar(200),
	deleted    		varchar(10),
	Tel    			varchar(150),
	LinkMan    		varchar(150),
	Fax    			varchar(150),
	rec    			varchar(10),
	namepy    		varchar(200),
	parrec    		varchar(10),
	OrderNo    		varchar(10),
	PyCode    		varchar(600),
	XiWaMaxNumber    NUMERIC(24, 10) 
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerDTypeID = '00000')
		INSERT INTO @Temp	
		SELECT 	typeid,
				parid,
				leveal,
				sonnum,
				soncount,
				usercode,
				FullName,
				Name,
				Comment,
				deleted,
				Tel,
				LinkMan,
				Fax,
				rec,
				namepy,
				parrec,
				OrderNo,
				PyCode,
				XiWaMaxNumber 
		FROM 	Department
		WHERE 	TypeId <> '00000' 
	ELSE
		INSERT INTO @Temp		
		SELECT 	typeid,
				parid,
				leveal,
				sonnum,
				soncount,
				usercode,
				FullName,
				Name,
				Comment,
				deleted,
				Tel,
				LinkMan,
				Fax,
				rec,
				namepy,
				parrec,
				OrderNo,
				PyCode,
				XiWaMaxNumber 
		FROM 	Department
		WHERE	TypeId IN (SELECT TypeId FROM F_GetManDetailAllDType(@chvOperatorId))


	RETURN
END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManEType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManEType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖职员范围
*/
CREATE FUNCTION F_GetManEType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
	 	SELECT 	BtypeID,
				typeId,
				Parid,
				leveal,
				soncount,
				sonnum,
				FullName,
				Name,
				UserCode,
				Department,
				Tel,
				Address,
				Comment,
				deleted,
				Sex,
				Nation,
				Knowledge,
				Blood,
				Health,
				IDcard,
				Birthday,
				Marriage,
				Job,
				Job2,
				JobTime,
				Tel2,
				Mob,
				Mail,
				political,
				nat_place,
				college,
				for_language,
				reg_place,
				com_level,
				weight,
				stature,
				fam_status,
				informer,
				speciality,
				for_lan_level,
				PostCode,
				Email,
				DtypeID,
				PyCode,
				MaxPre,
				smsMobile,
				smsComment,
				tichengRate,
				XiWaMaxNumber,
				STypeId,
				QQ,
				MSN,
				Blog,
				mBlog,
				Team,
				HrpostionId,
				HrPersonStatu,
				iswmssync
		FROM 	Employee 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '00001')
				AND TypeId <> '00000' 
		UNION ALL
		SELECT 	E.BtypeID,
				E.typeId,
				E.Parid,
				E.leveal,
				E.soncount,
				E.sonnum,
				E.FullName,
				E.Name,
				E.UserCode,
				E.Department,
				E.Tel,
				E.Address,
				E.Comment,
				E.deleted,
				E.Sex,
				E.Nation,
				E.Knowledge,
				E.Blood,
				E.Health,
				E.IDcard,
				E.Birthday,
				E.Marriage,
				E.Job,
				E.Job2,
				E.JobTime,
				E.Tel2,
				E.Mob,
				E.Mail,
				E.political,
				E.nat_place,
				E.college,
				E.for_language,
				E.reg_place,
				E.com_level,
				E.weight,
				E.stature,
				E.fam_status,
				E.informer,
				E.speciality,
				E.for_lan_level,
				E.PostCode,
				E.Email,
				E.DtypeID,
				E.PyCode,
				E.MaxPre,
				E.smsMobile,
				E.smsComment,
				E.tichengRate,
				E.XiWaMaxNumber,
				E.STypeId,
				E.QQ,
				E.MSN,
				E.Blog,
				E.mBlog,
				E.Team,
				E.HrpostionId,
				E.HrPersonStatu,
				iswmssync
		FROM	Employee E INNER JOIN F_GetManDetailAllEType(@chvOperatorId) M ON M.TypeId = E.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '-99999')
)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManKType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManKType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

















/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖仓库范围
*/
CREATE FUNCTION F_GetManKType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT 	typeId,
				Kid,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				Name,
				UserCode,
				Comment,
				deleted,
				[Add],
				Tel,
				LinkMan,
				PyCode,
				XiWaMaxNumber,
				STypeId,
				IsWmsSync
		FROM 	Stock 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
				AND TypeId <> '00000' 
		UNION ALL
		SELECT 	K.typeId,
				K.Kid,
				K.parid,
				K.leveal,
				K.sonnum,
				K.soncount,
				K.FullName,
				K.Name,
				K.UserCode,
				K.Comment,
				K.deleted,
				K.[Add],
				K.Tel,
				K.LinkMan,
				K.PyCode,
				K.XiWaMaxNumber,
				K.STypeId,
				K.IsWmsSync
		FROM 	Stock K INNER JOIN F_GetManDetailAllKType(@chvOperatorId) M ON M.TypeId = K.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '-99999')

	)























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManPType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManPType]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖商品范围
*/

/*
	作者：吕文祺
	日期：2012-4-17
	描述：增加对商品基本信息表的增加字段(自由项)
*/


/*
	修改：舒珊
	日期：2016-6-06
	描述：ptype_price 关联关系添加 基本单位，缩小关联范围
*/
CREATE FUNCTION F_GetManPType
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (  	
		SELECT 	P.typeId,
				p.Pid,
				P.ParId,
				P.leveal,
				P.sonnum,
				p.customitemid,
				p.customitemfrom,
				p.customitemname,
				p.customitemrefid,
				P.soncount,
				P.CanModify,
				P.UserCode,
				P.FullName,
				P.Name,
				P.Standard,
				P.Type,
				P.Area,
				P.Unit1,
				P.Unit2,
				p.BuyUnitId,
				p.SaleUnitId,
				p.StockUnitId,
				p.baseUnitId,
				P.UnitRate1,
				P.UnitRate2,
				P.preprice1,
				P.preprice2,
				P.preprice3,
				P.preprice4,
				P.preprice5,
				P.UsefulLifeMonth,
				P.UsefulLifeDay,
				P.Comment,
				P.recPrice,
				P.deleted,
				P.ColorGroupID,
				P.SizeGroupID,
				P.EntryCode AS EntryCode,
				P.IfSerial,
				P.PyCode,
				P.SerialCount,
				P.ValidDays,
				P.DwgNo,
				P.XiWaMaxNumber,
				P.ifuseentrycode,
				E.Brand,
				E.Import,
				E.GeneralType,
				E.GeneralDwgNo,
				E.Property,
				E.PackageQty,
				E.Weight,
				E.TaxNumber,
				E.Taxrate,
				E.BTypeID,
				E.FcUnit,
				E.FcPrice,
				R.PreBuyPrice1,
				R.PreBuyPrice2,
				R.PreBuyPrice3,
				R.PreBuyPrice4,
				R.PreBuyPrice5,
				R.PreSalePrice1,
				R.PreSalePrice2,
				R.PreSalePrice3,
				R.PreSalePrice4,
				R.PreSalePrice5,
				R.PreSalePrice6,
				R.PreSalePrice7,
				R.PreSalePrice8,
				R.PreSalePrice9,
				R.PreSalePrice10,
				R.RetailPrice,
				R.TopSalePrice,
				R.LowSalePrice,
				p.stopbuy,
				R.TopBuyPrice,
				p.AssistantUnitId,
				p.ProduceUnitId,
				p.IsService,
				p.PtypeCategoryID,
				p.SortID,
				p.iscombinationproduct,
				P.multentrycode,
				p.IsScaleWeight,
				p.brandartypeid,
				p.IsWmsSync
		FROM 	PType P
		INNER JOIN (
			SELECT	PTypeId,
					PreBuyPrice1,
					PreBuyPrice2,
					PreBuyPrice3,
					PreBuyPrice4,
					PreBuyPrice5,
					PreSalePrice1,
					PreSalePrice2,
					PreSalePrice3,
					PreSalePrice4,
					PreSalePrice5,
					PreSalePrice6,
					PreSalePrice7,
					PreSalePrice8,
					PreSalePrice9,
					PreSalePrice10,
					RetailPrice,
					TopSalePrice,
					LowSalePrice,
					TopBuyPrice,
					unitid
			FROM 	PType_Price
		)R ON R.PTypeId = P.TypeId and p.baseunitid=R.unitid
		LEFT JOIN (
			SELECT	PTypeID,
					Brand,
					Import,
					GeneralType,
					GeneralDwgNo,
					Property,
					PackageQty,
					Weight,
					TaxNumber,
					Taxrate,
					BTypeID,
					FcUnit,
					FcPrice
			FROM 	Qp_PType_Ext
		)E ON E.PTypeId = P.TypeId
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
				AND P.TypeId <> '00000' 
		UNION ALL		
		SELECT 	P.typeId,
				p.Pid,
				P.ParId,
				P.leveal,
				P.sonnum,
				p.customitemid,
				p.customitemfrom,
				p.customitemname,
				p.customitemrefid,
				P.soncount,
				P.CanModify,
				P.UserCode,
				P.FullName,
				P.Name,
				P.Standard,
				P.Type,
				P.Area,
				P.Unit1,
				P.Unit2,
				p.BuyUnitId,
				p.SaleUnitId,
				p.StockUnitId,
				p.baseUnitId,
				P.UnitRate1,
				P.UnitRate2,
				P.preprice1,
				P.preprice2,
				P.preprice3,
				P.preprice4,
				P.preprice5,
				P.UsefulLifeMonth,
				P.UsefulLifeDay,
				P.Comment,
				P.recPrice,
				P.deleted,
				P.ColorGroupID,
				P.SizeGroupID,
				P.EntryCode,
				P.IfSerial,
				P.PyCode,
				P.SerialCount,
				P.ValidDays,
				P.DwgNo,
				P.XiWaMaxNumber,
				P.ifuseentrycode,
				E.Brand,
				E.Import,
				E.GeneralType,
				E.GeneralDwgNo,
				E.Property,
				E.PackageQty,
				E.Weight,
				E.TaxNumber,
				E.Taxrate,
				E.BTypeID,
				E.FcUnit,
				E.FcPrice,
				R.PreBuyPrice1,
				R.PreBuyPrice2,
				R.PreBuyPrice3,
				R.PreBuyPrice4,
				R.PreBuyPrice5,
				R.PreSalePrice1,
				R.PreSalePrice2,
				R.PreSalePrice3,
				R.PreSalePrice4,
				R.PreSalePrice5,
				R.PreSalePrice6,
				R.PreSalePrice7,
				R.PreSalePrice8,
				R.PreSalePrice9,
				R.PreSalePrice10,
				R.RetailPrice,
				R.TopSalePrice,
				R.LowSalePrice,
				p.stopbuy,
				R.TopBuyPrice,
				p.AssistantUnitId,
				p.ProduceUnitId,
				p.IsService,
				p.PtypeCategoryID,
				p.SortID,
				p.iscombinationproduct,
				P.multentrycode,
				p.IsScaleWeight,
				p.brandartypeid,
				p.IsWmsSync
		FROM 	F_GetManDetailAllPType(@chvOperatorId) M
		INNER JOIN PType P ON P.TypeId = M.TypeId
		INNER JOIN (
			SELECT	PTypeId,
					PreBuyPrice1,
					PreBuyPrice2,
					PreBuyPrice3,
					PreBuyPrice4,
					PreBuyPrice5,
					PreSalePrice1,
					PreSalePrice2,
					PreSalePrice3,
					PreSalePrice4,
					PreSalePrice5,
					PreSalePrice6,
					PreSalePrice7,
					PreSalePrice8,
					PreSalePrice9,
					PreSalePrice10,
					RetailPrice,
					TopSalePrice,
					LowSalePrice,
					TopBuyPrice,
					unitid
			FROM 	PType_Price
		)R ON R.PTypeId = P.TypeId and p.baseunitid=R.unitid
		LEFT JOIN (
			SELECT	PTypeID,
					Brand,
					Import,
					GeneralType,
					GeneralDwgNo,
					Property,
					PackageQty,
					Weight,
					TaxNumber,
					Taxrate,
					BTypeID,
					FcUnit,
					FcPrice
			FROM 	Qp_PType_Ext
		)E ON E.PTypeId = P.TypeId
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '-99999')
	)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManPTypeIdS]') and xtype in (N'FN', N'IF', N'TF'))
BEGIN
	drop function [dbo].[F_GetManPTypeIdS]
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/*
	作者：刘飞
	日期：2017-9-1
	描述：查询职员的管辖商品范围
*/
CREATE FUNCTION F_GetManPTypeIdS
(
	@chvoperatorid			varchar(100)	--操作员ID
)
RETURNS  @Temp TABLE
(
	TypeId			VARCHAR(50)
)
AS
BEGIN
	-------- 权限检查 - Start --------
	DECLARE @chvMPTypeID varchar(50)

	SELECT 	@chvMPTypeID=MangerPTypeID
	FROM 	LoginUser(NOLOCK)
	WHERE 	ETypeId=@chvoperatorid

	--拥有查询所有商品的权限（MangerPTypeID = '00000'）
	--（MangerPTypeID = '-99999'并且ptype_l没有记录，表示没有权限)
	--（MangerPTypeID = '-99999'并且ptype_l有记录，表示拥有部分权限)

	IF @chvMPTypeID IS NOT NULL AND @chvMPTypeID = '-99999'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM PType_L WHERE ETypeId = @chvoperatorid)
		BEGIN
			insert into @Temp (Typeid)	
			SELECT 	M.typeId
			FROM 	(
					SELECT	DISTINCT P.TypeId 
					FROM	PType_L L
					INNER JOIN PType  P ON (L.etypeid = @chvoperatorid 
											AND L.Flag=1 
											AND P.deleted = 0
											AND P.TypeId LIKE L.TypeId + '%' )
					UNION
					SELECT	L.TypeID
					FROM	ptype_l L
					WHERE	L.etypeid = @chvoperatorid
							AND L.flag=0
				) M
		END
	END
	ELSE IF @chvMPTypeID IS NOT NULL AND @chvMPTypeID = '00000'
	BEGIN
		insert into @Temp (Typeid)	
		SELECT DISTINCT typeId FROM PType WHERE sonnum = 0 AND deleted = 0 
	END
	
	RETURN
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_GetManSType') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetManSType
GO

/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据存储的配置来确定职员的管辖商品范围
*/
/*
	修改：李灏龙
	日期：2012年6月25日11:22:02
	描述：增加一些字段，保持与stype表的结构相同，避免其他地方调用时报错
		  具体修改标识：zs001
*/

CREATE FUNCTION F_GetManSType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	TypeId			varchar(50),
	SID				INT,
	parid			varchar(50),
	leveal			varchar(10),
	sonnum			varchar(10),
	soncount		varchar(10),
	FullName		varchar(66),
	[Name]			varchar(30),
	UserCode		varchar(26),
	Comment			varchar(256),
	LinkMan			varchar(100),
	Address			varchar(100),
	Tel				varchar(100),
	PostCode		varchar(100),
	TaxNo			varchar(100),
	Bank			varchar(100),
	Account			varchar(100),
	deleted			varchar(10),
	PyCode			varchar(500),
	BTypeId1		varchar(50),
	BTypeId2		varchar(50),
	PriceType		tinyint,
	XiWaMaxNumber	numeric(18,0),
	ATypeID			VARCHAR(50),  --zs001
	--ATypeID1		VARCHAR(50),  --zs001
	ATypeID2		VARCHAR(50),  --zs001
	ATypeID3		VARCHAR(50),  --zs001
	IsSelfVerify	varchar(2),
	VerifyID		VARCHAR(50),  --zs001
	ATypeID4		VARCHAR(50),  --zs001
	calcFullName	VARCHAR(100)   --zs001
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')
		INSERT INTO @Temp	
		SELECT 	TypeId,
				Sid,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				[Name],
				UserCode,
				Comment,
				LinkMan,
				Address,
				Tel,
				PostCode,
				TaxNo,
				Bank,
				Account,
				deleted,
				PyCode,
				BTypeId1,
				BTypeId2,
				PriceType,
				XiWaMaxNumber,
				ATypeID,
				ATypeID2,
				ATypeID3,
				IsSelfVerify,
				VerifyID,
				ATypeID4,
				calcFullName
		FROM 	SType 		
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')
				AND TypeId <> '00000' 		
	ELSE
		INSERT INTO @Temp		
		SELECT 	S.TypeId,
				S.Sid,
				S.parid,
				S.leveal,
				S.sonnum,
				S.soncount,
				S.FullName,
				S.[Name],
				S.UserCode,
				S.Comment,
				S.LinkMan,
				S.Address,
				S.Tel,
				S.PostCode,
				S.TaxNo,
				S.Bank,
				S.Account,
				S.deleted,
				S.PyCode,
				S.BTypeId1,
				S.BTypeId2,
				S.PriceType,
				S.XiWaMaxNumber,
				S.ATypeID,
				S.ATypeID2,
				S.ATypeID3,
				S.IsSelfVerify,
				S.VerifyID,
				S.ATypeID4,
				S.calcFullName
		FROM 	SType S
		INNER JOIN F_GetManDetailAllSType(@chvOperatorId) M ON M.TypeId = S.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '-99999')				
	RETURN
END






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetPtypeRate]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetPtypeRate]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		张陈仁
-- Create date: 2012年04月26日
-- Description:	获取浮动率
-- =============================================

CREATE FUNCTION dbo.F_GetPtypeRate(@ptypeID VARCHAR(100),@UnitsId INT)
RETURNS  NUMERIC(24, 10) 
WITH EXECUTE AS caller
AS
BEGIN
	DECLARE @rate  NUMERIC(24, 10) 
	SELECT @rate= rate FROM PType_Units_Ext WHERE PtypeID=@ptypeID AND UnitsId=@UnitsId
	RETURN @rate
END
GO









if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetUnitName]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetUnitName]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		张陈仁
-- Create date: 2012年04月26日
-- Description:	根据传入的单位ID查询出单位名称
-- @unitID多单位ID  @isRate是否需要判断浮动或者固定 （1需要，0不需要）
-- =============================================

CREATE FUNCTION dbo.F_GetUnitName(@unitID INT,@isRate INT)
RETURNS VARCHAR(200)
WITH EXECUTE AS caller
AS
BEGIN
	DECLARE @UnitName VARCHAR(200)
	IF(@isRate=1)
	BEGIN
		SELECT @UnitName= a.FullName 
		FROM PType_Units a INNER JOIN PType_Units_Ext b 
		ON a.UnitsId=b.UnitsId 
		WHERE a.UnitsId=@unitID 
	END
	ELSE IF(@isRate=0)
	BEGIN
		SELECT @UnitName= FullName FROM PType_Units WHERE UnitsId=@unitID
	END
	
	RETURN @UnitName
END
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetUnitRate]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetUnitRate]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		黄清
-- Create date: 2014年05月05日
-- Description:	根据传入的单位ID查询出单位换算率
-- @unitID多单位ID  @isRate是否需要判断浮动或者固定 （1需要，0不需要）
-- =============================================

CREATE FUNCTION dbo.F_GetUnitRate(@unitID INT,@ptypeid VARCHAR(50),@fzunit INT)
RETURNS VARCHAR(200)
WITH EXECUTE AS CALLER
AS
BEGIN
	DECLARE @UnitRate VARCHAR(200)
	IF @fzunit=0
	BEGIN
		SELECT @UnitRate=Rate FROM PType_Units_Ext
		WHERE PtypeID=@ptypeid AND UnitsId=@unitID
	END
	ELSE
	BEGIN
		SELECT @UnitRate=CASE WHEN SaleUnitID1=@unitID THEN SaleUnitRate1
							  WHEN SaleUnitID2=@unitID THEN SaleUnitRate2
							  WHEN SaleUnitID3=@unitID THEN SaleUnitRate3
							  END
		FROM PType_AuxiliaryUnits_Ext
		WHERE PtypeID=@ptypeid 
	END
	RETURN @UnitRate
END
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetCommissionCostPrice]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[FN_GetCommissionCostPrice]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		
-- Create date: 
-- Description:	获取受托代销按成本价入库的成本价

-- =============================================

CREATE FUNCTION dbo.FN_GetCommissionCostPrice(
	@intID					BIGINT,
	@intBillNumberID		BIGINT
	)
RETURNS NUMERIC(22,10)
WITH EXECUTE AS caller
AS
BEGIN
	DECLARE
		@decCostPrice	NUMERIC(22,10)
	SELECT @decCostPrice=CostPrice
	FROM InOutstocktable
	WHERE BillNumberId=@intBillNumberID AND ID=@intID
	AND KtypeId<>'10000'
	
	RETURN @decCostPrice
END
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AcTypeSelector_AssisitItem]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_AcTypeSelector_AssisitItem]
GO

/**
 作者：佘海源
 描述：科目选择器辅助项组合函数
**/
CREATE FUNCTION F_AcTypeSelector_AssisitItem
(
	@ATypeId Varchar(100)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	 declare @str varchar(max) SET @str='' 
   
   SELECT @str=@str+'/'+a.FullName 
   FROM 
   (
   SELECT DISTINCT AAAC.ATypeId,
				   AAC.FullName 
			  FROM Ac_Account_Assist_CheckItems AAAC
		INNER JOIN Ac_Assist_CheckItems AAC 
				ON AAAC.Ascids=AAC.AscIds
   )a
   WHERE ATypeId=@ATypeId
   RETURN @str
END
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_AllBillType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_AllBillType]
GO
-- ========================================================================
-- 功能说明：		得到所有的单据类型，单据名称,调用方式dbo.f_AllBillType()，用于关联出单据类型，目前没有单据类型表，暂时采用函数
-- 最后修改作者：	冯 波
-- 最后修改时间：	2004-03-29
-- ========================================================================
CREATE   FUNCTION f_AllBillType()
Returns @AllBillTypeTab TABLE(
        BillType		INT,
        BillTypeName	VARCHAR(100),
        TableName		VARCHAR(100) DEFAULT ''
)
--@Encode$--
AS 
BEGIN       
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(4,'收款单','GatheringBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(5,'待摊费用发生')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(6,'采购退货单','BuybackBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(9,'报损单','LoseBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(10,'待摊费用摊销')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(11,'销售单','SaleBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(14,'报溢','OverFlowBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(16,'生产拆装单','DisassembleBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(17,'同价调拨','MoveBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(21,'变价调拨','MoveBJBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(34,'进货单','BuyBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(36,'费用单','MoneyBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(45,'销售退货单','SaleBackBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(57,'成本调价单','AdPriceBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(66,'付款单','PayBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(71,'借进','LendBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(72,'借进还回','LendBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(77,'转款单','MoveMoneyBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(78,'固定资产折旧')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(84,'固定资产购买')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(85,'固定资产变卖')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(87,'借出','LendBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(88,'借出还回','LendBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(93,'其他收入单','MoneyBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(115,'应收款减少','AdDebtBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(116,'应收款增加','AdDebtBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(126,'获赠单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(127,'生产模板')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(128,'应付款增加','AdDebtBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(129,'应付款减少','AdDebtBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(139,'赠送单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(140,'委托代销发货单','CommissionBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(141,'委托代销结算单','CommissionBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(142,'委托代销退货单','CommissionBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(143,'委托代销调价单','CommissionBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(144,'受托代销收货单','CommissionBill')
            Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(145,'受托代销结算单','CommissionBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(146,'受托代销退货单','CommissionBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(147,'受托代销调价单','CommissionBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(148,'返利执行单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(149,'价保执行单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(150,'获利核算执行单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(300,'销售订单','OrderBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(301,'进货订单','OrderBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(305,'零售单','RetailBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(306,'库存盘点单')
	        Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(151,'获得价保执行单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(152,'入库货位分配单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(153,'出库货位分配单')
            Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(154,'货位调拨单')
	
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(156,'商品维修接件单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(157,'商品维修受理单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(158,'现金费用单','MoneyBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(159,'会计凭证')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(160,'销售换货单','SaleGoodsExchangeBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(161,'采购换货单','BuyGoodsExchangeBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(165,'维修接件单','Wx_Bill_JieJian')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(166,'维修单','Wx_Bill_Self')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(167,'维修取件单','Wx_Bill_GetBack')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(168,'整机更换单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(169,'送修单','Wx_Bill_Send')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(170,'送修返回单','Wx_Bill_SendBack')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(171,'报修单','Wx_Bill_Call')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(172,'上门维修单','Wx_Bill_GoTo')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(173,'维修品调入单','Wx_Bill_In')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(174,'维修品调出单','Wx_Bill_Out')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(175,'维修品调拨单','Wx_Bill_Move')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(177,'维修估价单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(178,'快修单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(179,'洗车结算单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(180,'旧件回收单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(181,'会员储值充值单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(182,'洗车次数充值单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(183,'积分兑换单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(184,'报价单','QuotePriceBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(185,'询价单','AskPriceBill')
			Insert Into @AllBillTypeTab(BillType,BillTypeName) Values(186,'保险理赔单')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(187,'分支机构调拨出库单','StypeMoveBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(188,'分支机构调拨入库单','StypeMoveBill')
		    Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(189,'预收款单','PreBill')
			Insert Into @AllBillTypeTab(BillType,BillTypeName,TableName) Values(190,'预付款单','PreBill')

    RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'dbo.AssisitItemSelector') IS NOT NULL
DROP FUNCTION dbo.AssisitItemSelector
GO
/*
	作者：佘海源
	日期：2012-05-28
	描述：辅助选择获取指定辅助项目名
*/
CREATE FUNCTION [dbo].[AssisitItemSelector] 
(
	@Type		VARCHAR(200),--辅助核算类型
	@TypeId		VARCHAR(50),--辅助核算ID
	@OperatorId	VARCHAR(50),--操作员ID
	@STypeId	VARCHAR(50) --分支机构ID
)
RETURNS  VARCHAR(100)
AS 
BEGIN
DECLARE @Result VARCHAR(100) 
IF(@type='01')--分支机构
	BEGIN
		SELECT @Result=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE S.FullName END 
		FROM SType S 
		LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',11,@OperatorId,@STypeId) F ON F.TypeId=S.TypeId
		WHERE S.TypeId=@TypeId
	END 
ELSE IF(@type='02') --部门
	BEGIN
		SELECT @Result=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE D.FullName END 
		FROM Department D 
		LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',9,@OperatorId,@STypeId) F ON F.TypeId=D.TypeId  
		WHERE D.TypeId=@TypeId
	END
ELSE IF(@type='03') --职员
	BEGIN
		SELECT @Result=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE E.FullName END 
		FROM employee E 
		LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',3,@OperatorId,@STypeId) F ON F.TypeId=E.TypeId 
		WHERE E.TypeId=@TypeId
	END
ELSE IF(@type='04') -- 往来单位
	BEGIN
		SELECT @Result=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE B.FullName END 
		FROM btype B 
		LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',2,@OperatorId,@STypeId) F ON F.TypeId=B.TypeId 
		WHERE B.TypeId=@TypeId
	END
ELSE
	BEGIN
		DECLARE @AscIds INT=0
		SELECT @AscIds=AscIds FROM Ac_Assist_CheckItems WHERE UserCode=@Type--查询类别ID
		SELECT @Result=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE B.FullName END 
		FROM Ac_Assist_CheckItemsDetail B 
		LEFT JOIN dbo.F_GetAllAssistCheckItemsDetail(@TypeId,@AscIds,@OperatorId) F ON F.TypeId=B.TypeId AND B.AscIds=@AscIds
		WHERE  B.TypeId=@TypeId
	END
RETURN @Result
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetAllBaseTypeId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetAllBaseTypeId]
GO



















/*
	作者：谢吉康
	日期：2010-01-13
	描述：获取基本信息的节点ID
*/
CREATE  FUNCTION F_BaseGetAllBaseTypeId
(
	@TypeId			varchar(8000),
	@Flag			int
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)

	DECLARE @BaseTypeId		varchar(100)

	IF @Flag = 1			--商品
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM PType WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE PType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN PType_Cursor
		
					FETCH NEXT FROM PType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM PType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM PType_Cursor INTO @BaseTypeId
						END
		
					CLOSE PType_Cursor
					DEALLOCATE PType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT P.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN PType P ON P.TypeId LIKE L.a + '%'
					WHERE	P.sonnum = 0
				END
		END
	ELSE IF @Flag = 2		--往来单位
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM BType WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE BType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN BType_Cursor
		
					FETCH NEXT FROM BType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM BType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM BType_Cursor INTO @BaseTypeId
						END
		
					CLOSE BType_Cursor
					DEALLOCATE BType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT B.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN BType B ON  B.TypeId LIKE L.a  + '%'
					WHERE	B.sonnum = 0
				END
		END
	ELSE IF @Flag = 3		--职员
		BEGIN
			IF @TypeId = '00001' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Employee
			ELSE
				BEGIN
					/*
					DECLARE EType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN EType_Cursor
		
					FETCH NEXT FROM EType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Employee WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM EType_Cursor INTO @BaseTypeId
						END
		
					CLOSE EType_Cursor
					DEALLOCATE EType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT E.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN employee E ON E.TypeId LIKE L.a  + '%'
					WHERE	E.sonnum = 0
				END
		END
	ELSE IF @Flag = 4		--仓库
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Stock WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Stock WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT K.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN STOCK K ON K.TypeId LIKE L.a  + '%'
					WHERE	K.sonnum = 0
				END
		END
	ELSE IF @Flag = 5		--现金银行
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE SonNum = 0 AND (TypeId = '0000100003' OR TypeID LIKE '0000100004%')
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND (TypeId = '0000100003' OR TypeID LIKE '0000100004%')
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN ATYPE A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					AND (TypeId = '0000100003' OR TypeID LIKE '0000100004%')
				END
		END
	ELSE IF @Flag = 6		--费用
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE SonNum = 0 AND TypeID LIKE '00004%'
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND TypeID LIKE '00004%'
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN ATYPE A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					AND  TypeID LIKE '00004%'
				END
		END
	ELSE IF @Flag = 7		--收入
		BEGIN 
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE SonNum = 0 AND TypeID LIKE '00003%'
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND TypeID LIKE '00003%'
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN ATYPE A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					AND  TypeID LIKE '00003%'
				END
		END
	ELSE IF @Flag = 8		--资产
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE SonNum = 0 AND TypeID LIKE '0000100002%'
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND TypeID LIKE '0000100002%'
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN ATYPE A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					AND  TypeID LIKE '0000100002%'
				END
		END
	ELSE IF @Flag = 9		--部门
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Department WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE DType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN DType_Cursor
		
					FETCH NEXT FROM DType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Department WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM DType_Cursor INTO @BaseTypeId
						END
		
					CLOSE DType_Cursor
					DEALLOCATE DType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT D.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN Department D ON D.TypeId LIKE L.a  + '%'
					WHERE	D.sonnum = 0
					
				END
		END
	ELSE IF @Flag = 10		--地区
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Areatype WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE AreaType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN AreaType_Cursor
		
					FETCH NEXT FROM AreaType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Areatype WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM AreaType_Cursor INTO @BaseTypeId
						END
		
					CLOSE AreaType_Cursor
					DEALLOCATE AreaType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN AreaType A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
				END
		END
	ELSE IF @Flag = 11			--分支机构
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM SType WHERE Deleted = 0 AND SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE SType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN SType_Cursor
		
					FETCH NEXT FROM SType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM SType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND Deleted = 0
		
							FETCH NEXT FROM SType_Cursor INTO @BaseTypeId
						END
		
					CLOSE SType_Cursor
					DEALLOCATE SType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT S.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN SType S ON S.TypeId LIKE L.a  + '%'
					WHERE	S.sonnum = 0
				END
		END			

	RETURN
END


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetAllManagerBaseTypeId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetAllManagerBaseTypeId]
GO


















/*
	作者：谢吉康
	日期：2010-07-15
	描述：获取基本信息的节点ID（有删除的信息在内），带了权限范围
*/
CREATE  FUNCTION F_BaseGetAllManagerBaseTypeId
(
	@TypeId			varchar(MAX),	--需要拆分的基本信息ID
	@Flag			int,			--基本信息的标识 1.商品 2.往来单位 3.职员等
	@OperatorId		varchar(100)	--当前操作员的ID
)	
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)

	DECLARE @BaseTypeId		varchar(100)

	IF @Flag = 1			--商品
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailPType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailPType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 2		--往来单位
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailBType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailBType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 3		--职员
		BEGIN
			IF @TypeId = '00001' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailEType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailEType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 4		--仓库
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailKType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailKType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 5		--现金银行
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailAllAType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailAllAType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 6		--费用
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailAllATypeFy(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailAllATypeFy(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 7		--收入
		BEGIN 
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailAllATypeSr(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailAllATypeSr(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 8		--资产
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailAllATypeZc(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailAllATypeZc(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 9		--部门
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailDType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailDType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				END
		END
	ELSE IF @Flag = 10		--地区
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AreaType WHERE SonNum = 0
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	AreaType A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
							AND A.SonNum = 0
				END
		END
	ELSE IF @Flag = 11			--分支机构
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_BaseGetManDetailSType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	F_BaseGetManDetailSType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE 	LEFT(A.TypeId,LEN(B.A))=B.A
				
					/*DECLARE SType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN SType_Cursor
		
					FETCH NEXT FROM SType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM SType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM SType_Cursor INTO @BaseTypeId
						END
		
					CLOSE SType_Cursor
					DEALLOCATE SType_Cursor*/
				END
		END		

	RETURN
END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManATypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManATypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖现金银行-树形表
*/
CREATE FUNCTION F_BaseGetManATypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_BaseGetManAType(@chvOperatorId)
)


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManATypeFyAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManATypeFyAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖费用-树形表
*/
CREATE FUNCTION F_BaseGetManATypeFyAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_BaseGetManATypeFy(@chvOperatorId)
)


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManATypeSrAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManATypeSrAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖收入-树形表
*/
CREATE FUNCTION F_BaseGetManATypeSrAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_BaseGetManATypeSr(@chvOperatorId)
)


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManATypeZcAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManATypeZcAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
























/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖资产-树形表
*/
CREATE FUNCTION F_BaseGetManATypeZcAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_BaseGetManATypeZc(@chvOperatorId)
)



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManBTypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManBTypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-树形表
*/
CREATE FUNCTION F_BaseGetManBTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_BaseGetManBType(@chvOperatorId)
)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManDTypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManDTypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖部门-树型表
*/
CREATE FUNCTION F_BaseGetManDTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_BaseGetManDType(@chvOperatorId)
)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManETypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManETypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖职员-树形表
*/
CREATE FUNCTION F_BaseGetManETypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_BaseGetManEType(@chvOperatorId)
)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManKTypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManKTypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖仓库-树型表
*/
CREATE FUNCTION F_BaseGetManKTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_BaseGetManKType(@chvOperatorId)
)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManPTypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManPTypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖商品-树型表
*/
CREATE FUNCTION F_BaseGetManPTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
		SELECT	*
		FROM	F_BaseGetManPType(@chvOperatorId)
)






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BillTableName]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BillTableName]
GO

/*

返回单据明细表

*/

CREATE FUNCTION F_BillTableName
(
	@intBillType INT
	
)
RETURNS VARCHAR(100)
AS 
BEGIN
    DECLARE
		@strBillTableName		VARCHAR(100)
		
	/*		
	184	报价单
	305	零售单
	300	销售订单
	11	销售出库单
	45	销售退货单
	160	销售换货单
	139	赠送单
	140	委托代销发货单
	142	委托代销退货单
	143	委托代销调价单
	141	委托代销结算单
	204	请购单
	185	询价单
	301	采购订单
	34	采购入库单
	6	采购退货单
	161	采购换货单
	126	获赠单
	144	受托代销收货单
	146	受托代销退货单
	147	受托代销调价单
	145	受托代销结算单
	17	同价调拨单
	21	变价调拨单
	187	分支机构调拨出库单
	188	分支机构调拨入库单
	201	其他入库单
	202	其他出库单
	306	盘点单
	9	报损单
	14	报溢单
	87	借出开单
	71	借进开单
	88	借出还回单
	16	生产拆装单
	72	借进还出单
	203	序列号调整单
	116	应收增加单
	115	应收减少单
	128	应付增加单
	129	应付减少单
	4	收款单
	189	预收款单
	66	付款单
	190	预付款单
	148	返利执行单
	150	获利执行单
	149	价保执行单
	151	获得价保
	36	费用单
	158	现金费用单
	77	转款单
	93	其他收入单
	5	待摊费用发生
	10	待摊费用摊销
	84	固定资产购买
	85	固定资产变卖
	78	固定资产折旧
	57	成本调价单
	159	会计凭证
	205	采购费用分摊单
	206	销售费用分摊单
	165	维修接件单
	166	维修单
	167	维修取件单
	168	整机更换单
	169	送修单
	170	送修返回单
	171	报修单
	172	上门维修单
	173	维修品调入单
	174	维修品调出单
	175	维修品调拨单
	177	维修估价单
	178	快修单
	179	洗车结算单
	180	旧件回收单
	181	会员储值充值单
	182	洗车次数充值单
	183	积分兑换单
	186	保险理赔单
	191	领料出库单
	197	领料退回单
	198	维修回访单
	200	三包索赔单
	196	救援单
	192	返修单
	195	维修结算单
	*/
		
	IF @intBillType=184			SET @strBillTableName='quotepricebill'
	ELSE IF @intBillType=305	SET @strBillTableName='RetailBill'
	ELSE IF @intBillType=300	SET @strBillTableName='OrderBill'
	ELSE IF @intBillType=11		SET @strBillTableName='SaleBill'
	ELSE IF @intBillType=45		SET @strBillTableName='SaleBackBill'
	ELSE IF @intBillType=160	SET @strBillTableName='SaleGoodsExchangeBill'
	ELSE IF @intBillType=139	SET @strBillTableName='GiveBill'
	ELSE IF @intBillType=140	SET @strBillTableName='CommissionBill'
	ELSE IF @intBillType=142	SET @strBillTableName='CommissionBill'
	ELSE IF @intBillType=143	SET @strBillTableName='CommissionBill'
	ELSE IF @intBillType=141	SET @strBillTableName='CommissionBill'
	ELSE IF @intBillType=204	SET @strBillTableName='RequestBill'
	ELSE IF @intBillType=185	SET @strBillTableName='AskPriceBill'
	ELSE IF @intBillType=301	SET @strBillTableName='OrderBill'
	ELSE IF @intBillType=34		SET @strBillTableName='BuyBill'
	ELSE IF @intBillType=6		SET @strBillTableName='BuyBackBill'
	ELSE IF @intBillType=161	SET @strBillTableName='BuyGoodsExchangeBill'
	ELSE IF @intBillType=126	SET @strBillTableName='GivemeBill'
	ELSE IF @intBillType=144	SET @strBillTableName='CommissionBill'
	ELSE IF @intBillType=146	SET @strBillTableName='CommissionBill'
	ELSE IF @intBillType=147	SET @strBillTableName='CommissionBill'
	ELSE IF @intBillType=145	SET @strBillTableName='CommissionBill'
	ELSE IF @intBillType=17		SET @strBillTableName='MoveBill'
	ELSE IF @intBillType=21		SET @strBillTableName='MoveBjBill'
	ELSE IF @intBillType=187	SET @strBillTableName='STypeMoveBill'
	ELSE IF @intBillType=188	SET @strBillTableName='STypeMoveBill'
	ELSE IF @intBillType=201	SET @strBillTableName='OtherInOutBill'
	ELSE IF @intBillType=202	SET @strBillTableName='OtherInOutBill'
	ELSE IF @intBillType=9		SET @strBillTableName='LoseBill'
	ELSE IF @intBillType=14		SET @strBillTableName='OverFlowBill'
	ELSE IF @intBillType=87		SET @strBillTableName='LendBill'
	ELSE IF @intBillType=71		SET @strBillTableName='LendBill'
	ELSE IF @intBillType=88		SET @strBillTableName='LendBill'
	ELSE IF @intBillType=16		SET @strBillTableName='DisassembleBill'
	ELSE IF @intBillType=72		SET @strBillTableName='LendBill'
	ELSE IF @intBillType=203	SET @strBillTableName='SerialAdjustBill'
	ELSE IF @intBillType=165	SET @strBillTableName='wx_Bill_JieJian'
	ELSE IF @intBillType=166   SET @strBillTableName='wx_Bill_Self'
	ELSE IF @intBillType=167   SET @strBillTableName='wx_Bill_GetBack'
	ELSE IF @intBillType=168   SET @strBillTableName='wx_Bill_Replace'
	ELSE IF @intBillType=169   SET @strBillTableName='wx_Bill_Send'
	ELSE IF @intBillType=170   SET @strBillTableName='wx_Bill_SendBack'
	ELSE IF @intBillType=171   SET @strBillTableName='wx_Bill_Call'
	ELSE IF @intBillType=172   SET @strBillTableName='wx_Bill_Goto'
	ELSE IF @intBillType=173   SET @strBillTableName='wx_Bill_In'
	ELSE IF @intBillType=174   SET @strBillTableName='wx_Bill_Out'
	ELSE IF @intBillType=175   SET @strBillTableName='wx_Bill_Move'
	ELSE IF @intBillType=183   SET @strBillTableName='IntegralExchangeBill'
	ELSE IF @intBillType=57	   SET @strBillTableName='AdPriceBill'
    ELSE IF @intBillType=215	SET @strBillTableName='RetailBackBill'
	ELSE IF @intBillType=400	SET @strBillTableName='AppraisalBill'
	ELSE IF @intBillType=401	SET @strBillTableName='AppraisalBackBill'
	ELSE IF @intBillType=402	SET @strBillTableName='SendBill'
	ELSE IF @intBillType=403	SET @strBillTableName='SendBackBill'
	ELSE IF @intBillType=212	SET @strBillTableName='AssetIncDecBill'
	ELSE IF @intBillType=213	SET @strBillTableName='AssetIncDecBill'
	ELSE IF @intBillType=214	SET @strBillTableName='DepBill'
	ELSE SELECT @strBillTableName=detailTable FROM dbo.BillName WHERE Billtype=@intBillType
    RETURN @strBillTableName
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_CX_CompareWeekDay]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_CX_CompareWeekDay]
GO

/****** Object:  UserDefinedFunction [dbo].[F_CX_CompareWeekDay]    Script Date: 07/19/2011 14:45:09 ******/
SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO


CREATE FUNCTION [dbo].[F_CX_CompareWeekDay]
(
  @DateSet varchar(7),
  @CurWeekDay tinyInt
)  
RETURNS int 
--@encode$--
AS  
BEGIN 
if @CurWeekDay = 1 
  select @CurWeekDay = 8
  if @CurWeekDay <= 8 
  begin 
    if substring(@DateSet,@CurWeekDay - 1,1) = '1'
      return 0
  end
  else
  begin
     if substring(@DateSet, 1,1) = '1'   return 0
  end
 Return -1
END


GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_FormatDate]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_FormatDate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-09-01
	描述：格式化日期，返回标准的（2010-09-01）
	PRINT(dbo.F_FormatDate('2010-01-01','-','-'))
*/

CREATE FUNCTION F_FormatDate
(
	@Date		DATETIME,
	@SplitChar	VARCHAR(1) = '-',
	@RepChar	VARCHAR(1) = '-'
)
RETURNS VARCHAR(10)
AS
BEGIN
	DECLARE @dDate 	VARCHAR(10),
			@Month	VARCHAR(2),
			@Day	VARCHAR(2),
			@Rdate	VARCHAR(10)
	
	SET @dDate = CONVERT(VARCHAR(10),@Date,120)
	
	--对于不符合要求的日期格式，如09-01-01，则不返回1900-01-01
	IF SUBSTRING(@dDate,3,1) = @SplitChar
		SET @Rdate = REPLACE('1900-01-01',@SplitChar,@RepChar)
	ELSE
		BEGIN
			--先将日期2010-04-01变换成2010-4-1
			SET @dDate = REPLACE(@dDate,@SplitChar+'0',@SplitChar)
			IF LEN(@dDate)<10
				BEGIN
					SET @Rdate = LEFT(@dDate,4) + @RepChar
			
					IF LEN(@dDate) = 8
						BEGIN
							SET @Rdate = @Rdate + '0'+SUBSTRING(@dDate,6,1)
							SET @Rdate = @Rdate + @RepChar + '0' + SUBSTRING(@dDate,8,1)
						END
					ELSE 
						BEGIN
							IF SUBSTRING(@dDate,7,1)=@SplitChar
								BEGIN
									SET @Rdate = @Rdate + '0'+SUBSTRING(@dDate,6,1)
									SET @Rdate = @Rdate + @RepChar + SUBSTRING(@dDate,8,2)
								END
							ELSE
								BEGIN
									SET @Rdate = @Rdate + SUBSTRING(@dDate,6,2)
									SET @Rdate = @Rdate + @RepChar + '0' + SUBSTRING(@dDate,9,1)
								END				
						END
				END
			ELSE
				BEGIN
					SET @Rdate = REPLACE(LEFT(@dDate,10),@SplitChar,@RepChar)
				END
		END

	RETURN @Rdate
END
	



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_Date]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_Date]
GO



















-- ========================================================================
-- 功能说明：
-- 作者：陈启华  2005-06-18


-- ========================================================================

CREATE       FUNCTION F_Get_Date
(
@chvDate VARCHAR(100),
@intDay  int
)
RETURNS varchar(200) 
AS  
BEGIN 
	DECLARE @ReturnStr varchar(200)
	DECLARE @ReturnStr1 varchar(200)
	
	DECLARE  @TotDay Datetime
	
	SELECT @ReturnStr= Rtrim(ltrim(Convert(char(4),Year(@chvDate)))) +'-'+Rtrim(Ltrim(Convert(char(2),Month(@chvDate))))+'-'+ Rtrim(Ltrim(Convert(char(2),Day(@chvDate))))

	SET @TotDay=DATEADD(Day,@intDay,@ReturnStr)	

	SELECT @ReturnStr1= Rtrim(ltrim(Convert(char(4),Year(@TotDay)))) +'-'+Rtrim(Ltrim(Convert(char(2),Month(@TotDay))))+'-'+ Rtrim(Ltrim(Convert(char(2),Day(@TotDay))))

	RETURN  @ReturnStr1
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_Month]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_Month]
GO













CREATE       FUNCTION F_Get_Month
(
@chvDate VARCHAR(100),
@intMonth  int
)
RETURNS varchar(200) 
AS  
BEGIN 
	DECLARE @ReturnStr varchar(200)
	DECLARE @ReturnStr1 varchar(200)
	
	DECLARE  @TotDay Datetime
	
	SELECT @ReturnStr= Rtrim(ltrim(Convert(char(4),Year(@chvDate)))) +'-'+Rtrim(Ltrim(Convert(char(2),Month(@chvDate))))+'-'+ Rtrim(Ltrim(Convert(char(2),Day(@chvDate))))

	SET @TotDay=DATEADD(Month,@intMonth,@ReturnStr)	

	SELECT @ReturnStr1= Rtrim(ltrim(Convert(char(4),Year(@TotDay)))) +'-'+Rtrim(Ltrim(Convert(char(2),Month(@TotDay))))+'-01'

	RETURN  @ReturnStr1
END














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_QUARTER]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_QUARTER]
GO














CREATE       FUNCTION F_Get_QUARTER
(
@chvDate VARCHAR(100),
@intQuarter  int,
@beginFlag       int -- 1 表明开始 2 表明结束
)
RETURNS varchar(200) 
AS  
BEGIN 
	DECLARE @ReturnStr varchar(200)
	DECLARE @DayInt INT
	DECLARE  @DateTmp varchar(20)
	DECLARE @Begin varchar(10)
	DECLARE @End varchar(10)
	
	SET @DateTmp=CONVERT(VARCHAR(10),DATEADD(Quarter,@intQuarter,@chvDate) ,20)

	SET @DayInt=DatePart(qq,@DateTmp)		
	IF @DayInt=1 
	BEGIN 
		SET  @Begin=SubString(@DateTmp,1,4)+'-01-01'
		SET @End=SubString(@DateTmp,1,4)+'-03-31'
	END
	IF @DayInt=2
	BEGIN 
		SET  @Begin=SubString(@DateTmp,1,4)+'-04-01'
		SET @End=SubString(@DateTmp,1,4)+'-06-30'
	END			
	IF @DayInt=3 
	BEGIN 
		SET  @Begin=SubString(@DateTmp,1,4)+'-07-01'
		SET @End=SubString(@DateTmp,1,4)+'-09-30'
	END
	IF @DayInt=4 
	BEGIN 
		SET  @Begin=SubString(@DateTmp,1,4)+'-10-01'
		SET @End=SubString(@DateTmp,1,4)+'-12-31'
	END
	IF @beginFlag =1
		SET @ReturnStr =@Begin
	IF @beginFlag =2
		SET @ReturnStr =@End

	RETURN  @ReturnStr
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_WEEK]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_WEEK]
GO













CREATE       FUNCTION F_Get_WEEK
(
@chvDate VARCHAR(100),
@intWeek  int,
@beginFlag       int -- 1 表明开始 2 表明结束
)
RETURNS varchar(200) 
AS  
BEGIN 
	DECLARE @ReturnStr varchar(200)
	DECLARE @DayInt INT
	DECLARE  @DateTmp varchar(20)
	DECLARE @Begin varchar(10)
	DECLARE @End varchar(10)
	

	SET @DateTmp=CONVERT(VARCHAR(10),DATEADD(Week,@intWeek,@chvDate) ,20)

	SET @DayInt=DatePart(weekday,@DateTmp)		
	IF @DayInt=1 
	BEGIN 
		SET  @Begin=DATEADD(Day,0,@DateTmp)
		SET  @End=DATEADD(Day,6,@DateTmp)
	END
	IF @DayInt=2
	BEGIN 
		SET  @Begin=DATEADD(Day,-1,@DateTmp)
		SET  @End=DATEADD(Day,5,@DateTmp)
	END			
	IF @DayInt=3 
	BEGIN 
		SET  @Begin=DATEADD(Day,-2,@DateTmp)
		SET  @End=DATEADD(Day,4,@DateTmp)
	END
	IF @DayInt=4 
	BEGIN 
		SET  @Begin=DATEADD(Day,-3,@DateTmp)
		SET  @End=DATEADD(Day,3,@DateTmp)
	END
	IF @DayInt=5 
	BEGIN 
		SET  @Begin=DATEADD(Day,-4,@DateTmp)
		SET  @End=DATEADD(Day,2,@DateTmp)
	END
	IF @DayInt=6 
	BEGIN 
		SET  @Begin=DATEADD(Day,-5,@DateTmp)
		SET  @End=DATEADD(Day,1,@DateTmp)
	END
	IF @DayInt=7 
	BEGIN 
		SET  @Begin=DATEADD(Day,-6,@DateTmp)
		SET  @End=DATEADD(Day,0,@DateTmp)
	END

	


	IF @beginFlag =1
		SET @ReturnStr =@Begin
	IF @beginFlag =2
		SET @ReturnStr =@End
	
	SET @ReturnStr =CONVERT(varchar(10),Convert(datetime,@ReturnStr),20)

	RETURN  @ReturnStr
END








--select top 1 dbo.F_Get_WEEK('2005-8-25',0,1)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_YMD]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_YMD]
GO


















-- ========================================================================
-- 功能说明：单据编号自定义字符时，一些系统固定字符要翻译成字串 如 YYYY-MM-DD 要翻译成当前系统的时间 2004-12-15,如经手人编号要翻译成当前的经手人编号  
-- 特例 	：
-- 仓库编号   ==》  #KK# 在系统中再用当前的编号更换之			
-- 经手人编号 ==》  #EE# 在系统中再用当前的编号更换之
-- 空        ==》   ' '

-- 作者：陈启华  2004-12-15


-- ========================================================================

CREATE       FUNCTION F_Get_YMD
(
@chvYMD VARCHAR(100)

)
RETURNS varchar(200) 
AS  
BEGIN 
	DECLARE @chvDate   datetime
	DECLARE @ReturnStr varchar(200)
	DECLARE @SETCODECHAR varchar(200)
	DECLARE @FlagDate char(10)
	DECLARE @FlagYears char(10)
	DECLARE @FlagMonths char(10)
	DECLARE @FlagDays char(10)
	DECLARE @ChvYears varchar(4)
	DECLARE @ChvMonths varchar(2)
	DECLARE @ChvDays varchar(2)
	SET @SETCODECHAR =''
	SET @FlagDate ='0'
	SET @FlagYears =''
	SET @FlagMonths =''
	SET @FlagDays =''
	SET @ChvYears =''
	SET @ChvMonths =''
	SET @ChvDays =''

	-- A==================================================== 非系统字符
	IF NOT EXISTS (SELECT * FROM GDSETCODE WHERE SETCODECHAR =@chvYMD) 
	BEGIN
		SET @ReturnStr =@chvYMD
	END
	ELSE -- A================================================ 系统字符
	BEGIN
		SELECT @SETCODECHAR=SETCODECHAR,@FlagDate=FlagDate,@FlagYears=Years,@FlagMonths=Months,@FlagDays=Days FROM GDSETCODE WHERE SETCODECHAR =@chvYMD 
		IF @FlagDate ='1'  --B 日期型
		BEGIN
			SELECT @chvDate   = output from v_getdate
			SELECT @chvYears  = Rtrim(ltrim(Convert(char(4),Year(@chvDate))))
			SELECT @chvMonths = Rtrim(Ltrim(Convert(char(2),Month(@chvDate))))
			SELECT @chvDays   = Rtrim(Ltrim(Convert(char(2),Day(@chvDate))))
			SET @ReturnStr    = @SETCODECHAR
			-- 年份
			IF @FlagYears ='4'
				SET @ReturnStr =REPLACE(@ReturnStr,'YYYY',@chvYears)
			ELSE
				BEGIN
				IF @FlagYears ='2'
					SET @ReturnStr =REPLACE(@ReturnStr,'YY',RIGHT(@chvYears,2))
				END
				

			-- 月份
			IF @FlagMonths ='2'
			BEGIN
				IF Convert(int,@chvMonths)<10 AND LEN(@chvMonths)=1
					SET @chvMonths ='0'+@chvMonths
				SET @ReturnStr =REPLACE(@ReturnStr,'MM',@chvMonths)			
			END
			ELSE
			BEGIN
				IF @FlagMonths ='1'
				BEGIN
					IF Convert(int,@chvMonths)<10 AND LEN(@chvMonths)=2
						SET @chvMonths =RIGHT(@chvMonths,1)
					SET @ReturnStr =REPLACE(@ReturnStr,'M',@chvMonths)						
				END
				
			END
			-- 天数
			IF @FlagDays = '2'
			BEGIN
				IF Convert(int,@chvDays)<10 AND LEN(@chvDays)=1
					SET @chvDays ='0'+@chvDays
				SET @ReturnStr =REPLACE(@ReturnStr,'DD',@chvDays)				
			END
			ELSE
			BEGIN
				IF @FlagDays = '1'
				BEGIN
					IF Convert(int,@chvDays)<10 AND LEN(@chvDays)=2
						SET @chvDays =RIGHT(@chvDays,1)
					SET @ReturnStr =REPLACE(@ReturnStr,'D',@chvDays)					
				END
			END
		END
		ELSE  -- B===========================非日期型
		BEGIN
			IF @SETCODECHAR ='-' 
				SET @ReturnStr = '-'
			IF @SETCODECHAR ='仓库编号'
				SET @ReturnStr = '#KK#'
			IF @SETCODECHAR ='经手人编号'
				SET @ReturnStr ='#EE#'
			IF @SETCODECHAR ='部门编号'
				SET @ReturnStr ='#BM#'
			IF @SETCODECHAR ='制单人编号'
				SET @ReturnStr = '#ZDR#'
			IF @SETCODECHAR ='分支机构编号'
				SET @ReturnStr = '#SS#'
			IF @SETCODECHAR ='空'
				SET @ReturnStr = ' '
			IF @SETCODECHAR = ''
				SET @ReturnStr = ''
		END
	END
	RETURN  @ReturnStr
END



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_YMD_New]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_YMD_New]
GO


















-- ========================================================================
-- 功能说明：日期翻译成自定义分割符的日期，如经手人编号要翻译成当前的经手人编号  
-- 仓库编号   ==》  #KK# 在系统中再用当前的编号更换之			
-- 经手人编号 ==》  #EE# 在系统中再用当前的编号更换之
-- 作者：徐辉  2011-03-22


-- ========================================================================

CREATE       FUNCTION F_Get_YMD_New
(
@chvYMD 		VARCHAR(100),
@BillDate		VARCHAR(100),
@yearSeparator	varchar(5),
@monthSeparator	varchar(5),
@daySeparator	varchar(5)
)
RETURNS varchar(200) 
AS  
BEGIN 
	DECLARE @chvDate   datetime
	DECLARE @ReturnStr varchar(200)
	DECLARE @SETCODECHAR varchar(200)
	DECLARE @FlagDate char(10)
	DECLARE @FlagYears char(10)
	DECLARE @FlagMonths char(10)
	DECLARE @FlagDays char(10)
	DECLARE @ChvYears varchar(4)
	DECLARE @ChvMonths varchar(2)
	DECLARE @ChvDays varchar(2)
	SET @SETCODECHAR =''
	SET @FlagDate ='0'
	SET @FlagYears =''
	SET @FlagMonths =''
	SET @FlagDays =''
	SET @ChvYears =''
	SET @ChvMonths =''
	SET @ChvDays =''
	DECLARE @IfYear VARCHAR(1),@IfMonth VARCHAR(1),@IfDay VARCHAR(1)
	SELECT @IfYear='0',@IfMonth='0',@IfDay='0'
	

	-- A==================================================== 非系统字符
	IF NOT EXISTS (SELECT * FROM GDSETCODE WHERE SETCODECHAR =@chvYMD) 
	BEGIN
		SET @ReturnStr =@chvYMD
	END
	ELSE -- A================================================ 系统字符
	BEGIN
		SELECT @SETCODECHAR=SETCODECHAR,@FlagDate=FlagDate,@FlagYears=Years,@FlagMonths=Months,@FlagDays=Days FROM GDSETCODE WHERE SETCODECHAR =@chvYMD 
		IF @FlagDate ='1'  --B 日期型
		BEGIN
			SELECT @chvDate   = @BillDate
			SELECT @chvYears  = Rtrim(ltrim(Convert(char(4),Year(@chvDate))))
			SELECT @chvMonths = Rtrim(Ltrim(Convert(char(2),Month(@chvDate))))
			SELECT @chvDays   = Rtrim(Ltrim(Convert(char(2),Day(@chvDate))))
			SET @ReturnStr    = @SETCODECHAR
			-- 年份
			IF @FlagYears ='4'
			BEGIN
				SET @ReturnStr =REPLACE(@ReturnStr,'YYYY',@chvYears)
				SET @IfYear='1'
			END
			ELSE
			BEGIN
				IF @FlagYears ='2'
				BEGIN
					SET @ReturnStr =REPLACE(@ReturnStr,'YY',RIGHT(@chvYears,2))
					SET @IfYear='1'
				END
			END
				

			-- 月份
			IF @FlagMonths ='2'
			BEGIN
				IF Convert(int,@chvMonths)<10 AND LEN(@chvMonths)=1
					SET @chvMonths ='0'+@chvMonths
				SET @ReturnStr =REPLACE(@ReturnStr,'MM',@chvMonths)	
				SET @IfMonth='1'	
				IF @IfYear='1'
						SET @ReturnStr =REPLACE(@ReturnStr,'年',@yearSeparator)		
			END
			ELSE
			BEGIN
				IF @FlagMonths ='1'
				BEGIN
					IF Convert(int,@chvMonths)<10 AND LEN(@chvMonths)=2
						SET @chvMonths =RIGHT(@chvMonths,1)
					SET @ReturnStr =REPLACE(@ReturnStr,'M',@chvMonths)	
					SET @IfMonth='1'
					IF @IfYear='1'
						SET @ReturnStr =REPLACE(@ReturnStr,'年',@yearSeparator)							
				END
				
			END
			-- 天数
			IF @FlagDays = '2'
			BEGIN
				IF Convert(int,@chvDays)<10 AND LEN(@chvDays)=1
					SET @chvDays ='0'+@chvDays
				SET @ReturnStr =REPLACE(@ReturnStr,'DD',@chvDays)	
				SET @IfDay='1'
				IF @IfMonth='1'
					SET @ReturnStr =REPLACE(@ReturnStr,'月',@monthSeparator)					
			END
			ELSE
			BEGIN
				IF @FlagDays = '1'
				BEGIN
					IF Convert(int,@chvDays)<10 AND LEN(@chvDays)=2
						SET @chvDays =RIGHT(@chvDays,1)
					SET @ReturnStr =REPLACE(@ReturnStr,'D',@chvDays)	
					SET @IfDay='1'
					IF @IfMonth='1'
						SET @ReturnStr =REPLACE(@ReturnStr,'月',@monthSeparator)						
				END
			END
			
			IF @IfDay='1' AND @daySeparator<>'日'
				SET @ReturnStr =REPLACE(@ReturnStr,'日','')				
			IF @IfYear='1' AND @IfMonth='0'
				SET @ReturnStr =REPLACE(@ReturnStr,'年','')	
			IF @IfMonth='1' AND @IfDay='0'
				SET @ReturnStr =REPLACE(@ReturnStr,'月','')		
			
				
		END
		ELSE  -- B===========================非日期型
		BEGIN
			IF @SETCODECHAR ='-' 
				SET @ReturnStr = '-'
			IF @SETCODECHAR ='仓库编号'
				SET @ReturnStr = '#KK#'
			IF @SETCODECHAR ='经手人编号'
				SET @ReturnStr ='#EE#'
			IF @SETCODECHAR ='部门编号'
				SET @ReturnStr ='#BM#'	
			IF @SETCODECHAR ='制单人编号'
				SET @ReturnStr ='#ZDR#'	
			IF @SETCODECHAR ='分支机构编号'
				SET @ReturnStr ='#SS#'
			IF @SETCODECHAR ='空'
				SET @ReturnStr = ' '
			IF @SETCODECHAR = ''
				SET @ReturnStr = ''
		END
	END
	RETURN  @ReturnStr
END



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAccountPath]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAccountPath]
GO

-- ========================================================================
-- 功能说明：获取会计科目信息的路径
-- 作者：李灏龙  
-- 时间：2013-03-26
-- ========================================================================
CREATE  FUNCTION  F_GetAccountPath
(
	@typeid as	VARCHAR(50),
	@stypeid as VARCHAR(50)
)
RETURNS VARCHAR(1000) 
AS  
BEGIN 
	IF @typeid IS NULL  RETURN 1
	
	DECLARE @szThePath	VARCHAR(1000),
			@temp	VARCHAR(66),
			@parid	VARCHAR(50),
			@path	VARCHAR(350),
			@i		INT
	SET @path=''
	SET @i=10
	
	WHILE 1=1
		BEGIN
			SELECT @parid=LEFT(@typeid,@i)  
			IF len(@parid)<=len(@typeid)
				BEGIN
					SELECT TOP 1 @temp=fullname FROM Ac_Account WHERE TypeId=@parid AND StypeId=@stypeid
					
					--IF @flag=18 AND @parid='00000' SELECT @temp='全部会计科目'
					SELECT @path=@path + @temp + ' - '
					SELECT @i=@i+5
				END

			IF len(@parid)=len(@typeid)   BREAK
		END 
		
	SELECT @szThePath=LEFT(@path,len(@path)-1)
	return @szThePath
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetAllAssistCheckItemsDetail]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[F_GetAllAssistCheckItemsDetail]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-- ========================================================================
-- 描述：	返回自定义辅助核算明明细typeid 带权限范围(暂时没有该功能)
-- 时间：	2015-10-09
-- 作者：	古丽娟
-- ========================================================================
CREATE  FUNCTION F_GetAllAssistCheckItemsDetail
(
	@TypeId			VARCHAR(MAX),		--需要拆分的基本信息ID
	@Flag			INT,				--自定义辅助核算明明细 类型
	@OperatorId		VARCHAR(50)			--当前操作员的ID	
)	
RETURNS @Temp TABLE(TypeId VARCHAR(50))
--@Encode$--
AS
BEGIN

IF ISNULL(@TypeId,'')='' AND @Flag=0--得到该表所有权限范围内明细
	BEGIN
		INSERT INTO @Temp(TypeId)
		SELECT TypeId FROM Ac_Assist_CheckItemsDetail WHERE Leveal<>0
	END
ELSE --得到指定权限范围内明细
	BEGIN
		IF(ISNULL(@TypeId,'')='')
			BEGIN
				INSERT INTO @Temp(TypeId)
				SELECT TypeId FROM Ac_Assist_CheckItemsDetail WHERE AscIds=@Flag AND Leveal<>0
			END
		ELSE
			BEGIN
				INSERT INTO @Temp(TypeId)
				SELECT D.TypeId
				FROM Ac_Assist_CheckItemsDetail D 
				INNER JOIN f_split(@TypeId,',') F ON D.AscIds=@Flag AND D.Leveal<>0 AND D.TypeId LIKE F.a+'%'
			END
	END

RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllBaseTypeId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllBaseTypeId]
GO


















/*
	作者：谢吉康
	日期：2009-09-11
	描述：获取基本信息的节点ID
*/
CREATE  FUNCTION F_GetAllBaseTypeId
(
	@TypeId			varchar(max),
	@Flag			int
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)

	DECLARE @BaseTypeId		varchar(100)

	IF @Flag = 1			--商品
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM PType WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE PType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN PType_Cursor
		
					FETCH NEXT FROM PType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM PType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM PType_Cursor INTO @BaseTypeId
						END
		
					CLOSE PType_Cursor
					DEALLOCATE PType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT P.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN PType P ON P.TypeId LIKE L.a  + '%'
					WHERE	P.sonnum = 0
				END
		END
	ELSE IF @Flag = 2		--往来单位
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM BType WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE BType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN BType_Cursor
		
					FETCH NEXT FROM BType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM BType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM BType_Cursor INTO @BaseTypeId
						END
		
					CLOSE BType_Cursor
					DEALLOCATE BType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT B.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN btype B ON B.TypeId LIKE L.a  + '%'
					WHERE	B.sonnum = 0
				END
		END
	ELSE IF @Flag = 3		--职员
		BEGIN
			IF @TypeId = '00001' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Employee
			ELSE
				BEGIN
					/*
					DECLARE EType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN EType_Cursor
		
					FETCH NEXT FROM EType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Employee WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM EType_Cursor INTO @BaseTypeId
						END
		
					CLOSE EType_Cursor
					DEALLOCATE EType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT E.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN employee E ON E.TypeId LIKE L.a  + '%'
					WHERE	E.sonnum = 0
				END
		END
	ELSE IF @Flag = 4		--仓库
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Stock WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Stock WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT K.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN STOCK K ON K.TypeId LIKE L.a  + '%'
					WHERE	K.sonnum = 0
				END
		END
	ELSE IF @Flag = 5		--现金银行
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE SonNum = 0 AND (TypeId = '0000100003' OR TypeID LIKE '0000100004%')
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND (TypeId = '0000100003' OR TypeID LIKE '0000100004%')
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN AType A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					AND (TypeId = '0000100003' OR TypeID LIKE '0000100004%')
				END
		END
	ELSE IF @Flag = 6		--费用
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE SonNum = 0 AND TypeID LIKE '00004%'
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND TypeID LIKE '00004%'
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN AType A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					AND TypeID LIKE '00004%'
				END
		END
	ELSE IF @Flag = 7		--收入
		BEGIN 
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE SonNum = 0 AND TypeID LIKE '00003%'
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND TypeID LIKE '00003%'
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN AType A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					AND TypeID LIKE '00003%'
				END
		END
	ELSE IF @Flag = 8		--资产
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE SonNum = 0 AND TypeID LIKE '0000100002%'
			ELSE
				BEGIN
					/*
					DECLARE KType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN KType_Cursor
		
					FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0 AND TypeID LIKE '0000100002%'
		
							FETCH NEXT FROM KType_Cursor INTO @BaseTypeId
						END
		
					CLOSE KType_Cursor
					DEALLOCATE KType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN AType A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					AND TypeID LIKE  '0000100002%'
				END
		END
	ELSE IF @Flag = 9		--部门
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Department WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE DType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN DType_Cursor
		
					FETCH NEXT FROM DType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Department WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM DType_Cursor INTO @BaseTypeId
						END
		
					CLOSE DType_Cursor
					DEALLOCATE DType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT D.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN Department D ON D.TypeId LIKE L.a  + '%'
					WHERE	D.sonnum = 0
					
				END
		END
	ELSE IF @Flag = 10		--地区
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Areatype WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE AreaType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN AreaType_Cursor
		
					FETCH NEXT FROM AreaType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Areatype WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM AreaType_Cursor INTO @BaseTypeId
						END
		
					CLOSE AreaType_Cursor
					DEALLOCATE AreaType_Cursor
					*/
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT A.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN Areatype A ON A.TypeId LIKE L.a  + '%'
					WHERE	A.sonnum = 0
					
				END
		END
	ELSE IF @Flag = 11			--分支机构
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM SType WHERE SonNum = 0
			ELSE
				BEGIN
					/*
					DECLARE SType_Cursor CURSOR FOR
						SELECT * FROM F_Split(@TypeId,',')
		
					OPEN SType_Cursor
		
					FETCH NEXT FROM SType_Cursor INTO @BaseTypeId
		
					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM SType WHERE TypeID LIKE @BaseTypeId + '%' AND SonNum = 0
		
							FETCH NEXT FROM SType_Cursor INTO @BaseTypeId
						END
		
					CLOSE SType_Cursor
					DEALLOCATE SType_Cursor
					*/
					
					INSERT INTO @Temp(TypeId)
					SELECT	DISTINCT S.TypeId 
					FROM	F_Split(@TypeId,',') L
					INNER JOIN STYPE S ON S.TypeId LIKE L.a  + '%'
					WHERE	S.sonnum = 0
				END
		END		

	RETURN
END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllBaseTypeIdFromUOrFLike]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllBaseTypeIdFromUOrFLike]
GO















/*
	作者：谢吉康
	日期：2009-09-11
	描述：F_GetAllBaseTypeIdFromUOrFLike根据编号或者名称获取基本信息的TypeID
*/
CREATE FUNCTION F_GetAllBaseTypeIdFromUOrFLike
(
	@TypeId			varchar(8000),
	@Flag			int
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserData(@TypeId)

	DECLARE @BaseTypeId		varchar(1000),
			@BaseName		varchar(1000)

	IF @Flag = 1			--商品
		BEGIN
			DECLARE PType_Cursor CURSOR FOR
				SELECT * FROM F_Split(@TypeId,';')

			OPEN PType_Cursor

			FETCH NEXT FROM PType_Cursor INTO @BaseName

			WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE PType_CursorMx CURSOR FOR
						SELECT TypeId FROM PType WHERE (UserCode LIKE '%'+@BaseName+'%' OR FullName LIKE '%'+@BaseName+'%')

					OPEN PType_CursorMx

					FETCH NEXT FROM PType_CursorMx INTO @BaseTypeId

					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM PType WHERE TypeId LIKE @BaseTypeId + '%'

							FETCH NEXT FROM PType_CursorMx INTO @BaseTypeId
						END

					CLOSE PType_CursorMx
					DEALLOCATE PType_CursorMx

					FETCH NEXT FROM PType_Cursor INTO @BaseName
				END

			CLOSE PType_Cursor
			DEALLOCATE PType_Cursor
		END
	ELSE IF @Flag = 2		--往来单位
		BEGIN
			DECLARE BType_Cursor CURSOR FOR
				SELECT * FROM F_Split(@TypeId,';')

			OPEN BType_Cursor

			FETCH NEXT FROM BType_Cursor INTO @BaseName

			WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE BType_CursorMx CURSOR FOR
						SELECT TypeId FROM BType WHERE (UserCode LIKE '%'+@BaseName+'%' OR FullName LIKE '%'+@BaseName+'%')

					OPEN BType_CursorMx

					FETCH NEXT FROM BType_CursorMx INTO @BaseTypeId

					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM BType WHERE TypeId LIKE @BaseTypeId + '%'

							FETCH NEXT FROM BType_CursorMx INTO @BaseTypeId
						END

					CLOSE BType_CursorMx
					DEALLOCATE BType_CursorMx

					FETCH NEXT FROM BType_Cursor INTO @BaseName
				END

			CLOSE BType_Cursor
			DEALLOCATE BType_Cursor
		END
	ELSE IF @Flag = 3		--职员
		BEGIN
			DECLARE EType_Cursor CURSOR FOR
				SELECT * FROM F_Split(@TypeId,';')

			OPEN EType_Cursor

			FETCH NEXT FROM EType_Cursor INTO @BaseName

			WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE EType_CursorMx CURSOR FOR
						SELECT TypeId FROM Employee WHERE (UserCode LIKE '%'+@BaseName+'%' OR FullName LIKE '%'+@BaseName+'%')

					OPEN EType_CursorMx

					FETCH NEXT FROM EType_CursorMx INTO @BaseTypeId

					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Employee WHERE TypeId LIKE @BaseTypeId + '%'

							FETCH NEXT FROM EType_CursorMx INTO @BaseTypeId
						END

					CLOSE EType_CursorMx
					DEALLOCATE EType_CursorMx

					FETCH NEXT FROM EType_Cursor INTO @BaseName
				END

			CLOSE EType_Cursor
			DEALLOCATE EType_Cursor
		END
	ELSE IF @Flag = 4		--仓库
		BEGIN
			DECLARE KType_Cursor CURSOR FOR
				SELECT * FROM F_Split(@TypeId,';')

			OPEN KType_Cursor

			FETCH NEXT FROM KType_Cursor INTO @BaseName

			WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE KType_CursorMx CURSOR FOR
						SELECT TypeId FROM Stock WHERE (UserCode LIKE '%'+@BaseName+'%' OR FullName LIKE '%'+@BaseName+'%')

					OPEN KType_CursorMx

					FETCH NEXT FROM KType_CursorMx INTO @BaseTypeId

					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Stock WHERE TypeId LIKE @BaseTypeId + '%'

							FETCH NEXT FROM KType_CursorMx INTO @BaseTypeId
						END

					CLOSE KType_CursorMx
					DEALLOCATE KType_CursorMx

					FETCH NEXT FROM KType_Cursor INTO @BaseName
				END

			CLOSE KType_Cursor
			DEALLOCATE KType_Cursor
		END
	ELSE IF @Flag = 5		--现金银行
		BEGIN
			DECLARE AType_Cursor CURSOR FOR
				SELECT * FROM F_Split(@TypeId,';')

			OPEN AType_Cursor
			FETCH NEXT FROM AType_Cursor INTO @BaseName

			WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE AType_CursorMx CURSOR FOR
						SELECT nId FROM Ac_Items WHERE (UserCode LIKE '%'+@BaseName+'%' OR FullName LIKE '%'+@BaseName+'%')

					OPEN AType_CursorMx

					FETCH NEXT FROM AType_CursorMx INTO @BaseTypeId

					WHILE @@FETCH_STATUS = 0        
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT nId FROM Ac_Items WHERE   TypeName='B'

							FETCH NEXT FROM AType_CursorMx INTO @BaseTypeId
						END

					CLOSE AType_CursorMx
					DEALLOCATE AType_CursorMx

					FETCH NEXT FROM AType_Cursor INTO @BaseName
				END

			CLOSE AType_Cursor
			DEALLOCATE AType_Cursor
		END
	ELSE IF @Flag = 6		--地区
		BEGIN
			DECLARE AreaType_Cursor CURSOR FOR
				SELECT * FROM F_Split(@TypeId,';')

			OPEN AreaType_Cursor

			FETCH NEXT FROM AreaType_Cursor INTO @BaseName

			WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE AreaType_CursorMx CURSOR FOR
						SELECT TypeId FROM AreaType WHERE (UserCode LIKE '%'+@BaseName+'%' OR FullName LIKE '%'+@BaseName+'%')

					OPEN AreaType_CursorMx

					FETCH NEXT FROM AreaType_CursorMx INTO @BaseTypeId

					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM AreaType WHERE TypeId LIKE @BaseTypeId + '%'

							FETCH NEXT FROM AreaType_CursorMx INTO @BaseTypeId
						END

					CLOSE AreaType_CursorMx
					DEALLOCATE AreaType_CursorMx

					FETCH NEXT FROM AreaType_Cursor INTO @BaseName
				END

			CLOSE AreaType_Cursor
			DEALLOCATE AreaType_Cursor
		END
	ELSE IF @Flag = 7		--部门
		BEGIN
			DECLARE Department_Cursor CURSOR FOR
				SELECT * FROM F_Split(@TypeId,';')

			OPEN Department_Cursor

			FETCH NEXT FROM Department_Cursor INTO @BaseName

			WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE Department_CursorMx CURSOR FOR
						SELECT TypeId FROM Department WHERE (UserCode LIKE '%'+@BaseName+'%' OR FullName LIKE '%'+@BaseName+'%')

					OPEN Department_CursorMx

					FETCH NEXT FROM Department_CursorMx INTO @BaseTypeId

					WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @Temp(TypeId) SELECT TypeId FROM Department WHERE TypeId LIKE @BaseTypeId + '%'

							FETCH NEXT FROM Department_CursorMx INTO @BaseTypeId
						END

					CLOSE Department_CursorMx
					DEALLOCATE Department_CursorMx

					FETCH NEXT FROM Department_Cursor INTO @BaseName
				END

			CLOSE Department_Cursor
			DEALLOCATE Department_Cursor
		END

	RETURN
END

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllManagerBaseANDFatherTypeId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllManagerBaseANDFatherTypeId]
GO

/*
	作者：cqiang
	日期：2020-04-24
	描述：获取基本信息的节点ID与父节点，带了权限范围
*/
CREATE  FUNCTION F_GetAllManagerBaseANDFatherTypeId
(
	@TypeId			VARCHAR(MAX),	--需要拆分的基本信息ID
	@Flag			INT,			--基本信息的标识 1.商品 2.往来单位 3.职员等
	@OperatorId		VARCHAR(100),	--当前操作员的ID	
	@PtypeFlag		INT=0			--获取基本信息的节点以及父节点(991 商品其他功能编号生成条码)
)	
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)

	DECLARE @BaseTypeId		varchar(100)

	IF @Flag = 1			--商品
	BEGIN
		IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
			INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailANDFatherPType(@OperatorId,@PtypeFlag)
		ELSE
			BEGIN					
				INSERT INTO @Temp(TypeId)
				SELECT 	DISTINCT A.TypeId 
				FROM 	F_GetManDetailANDFatherPType(@OperatorId,@PtypeFlag) A, 
						(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
				WHERE	A.TypeId LIKE B.A + '%'
			END
	END				

	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllManagerBaseTypeId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllManagerBaseTypeId]
GO

/*
	作者：谢吉康
	日期：2010-07-15
	描述：获取基本信息的节点ID，带了权限范围
*/
CREATE  FUNCTION F_GetAllManagerBaseTypeId
(
	@TypeId			VARCHAR(MAX),	--需要拆分的基本信息ID
	@Flag			INT,			--基本信息的标识 1.商品 2.往来单位 3.职员等
	@OperatorId		VARCHAR(100)	--当前操作员的ID	
)	
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)

	DECLARE @BaseTypeId		varchar(100)

	IF @Flag = 1			--商品
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailPType(@OperatorId)
			ELSE
				BEGIN					
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailPType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END
	ELSE IF @Flag = 2		--往来单位
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailBType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailBType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END
	ELSE IF @Flag = 3		--职员
		BEGIN
			IF @TypeId = '00001' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailEType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END
	ELSE IF @Flag = 4		--仓库
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailKType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END
	ELSE IF @Flag = 5		--现金银行
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT nid FROM F_GetManDetailAllAType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.nid 
					FROM 	F_GetManDetailAllAType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B ,
							Ac_Items c
					WHERE  b.a=c.nId  AND A.nTypeId LIKE c.nTypeId + '%'
				END
		END
	ELSE IF @Flag = 6		--费用
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT nid FROM F_GetManDetailAllATypeFy(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.nid 
					FROM 	F_GetManDetailAllATypeFy(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B,
							Ac_Items c
					WHERE  b.a=c.nId  AND A.nTypeId LIKE c.nTypeId + '%'
				END
		END
	ELSE IF @Flag = 7		--收入
		BEGIN 
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT nid FROM F_GetManDetailAllATypeSr(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.nid 
					FROM 	F_GetManDetailAllATypeSr(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B ,
							Ac_Items c
					WHERE  b.a=c.nId  AND A.nTypeId LIKE c.nTypeId + '%'
				END
		END
	ELSE IF @Flag = 8		--资产
		BEGIN
			IF @TypeId = '0000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT nid FROM F_GetManDetailAllATypeZc(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.nid 
					FROM 	F_GetManDetailAllATypeZc(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B ,
							Ac_Items c
					WHERE  b.a=c.nId  AND A.nTypeId LIKE c.nTypeId + '%'
				END
		END
	ELSE IF @Flag = 9		--部门
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailDType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailAllDType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'						
				END
		END
	ELSE IF @Flag = 10		--地区
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM AreaType WHERE SonNum = 0
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	AreaType A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
							AND A.SonNum = 0
				END
		END
	ELSE IF @Flag = 11			--分支机构
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailSType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailAllSType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END
	ELSE IF @Flag = 12			--车牌号
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM QP_RepairAutoInfo WHERE SonNum = 0
			ELSE
				INSERT INTO @Temp(TypeId)
				SELECT 	DISTINCT A.TypeId 
				FROM 	QP_RepairAutoInfo A, 
						(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
				WHERE	A.TypeId LIKE B.A + '%'
						AND A.SonNum = 0		
		END		
	ELSE IF @Flag = 13			--维修项目
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM QP_RepairItems WHERE SonNum = 0
			ELSE
				INSERT INTO @Temp(TypeId)
				SELECT 	DISTINCT A.TypeId 
				FROM 	QP_RepairItems A, 
						(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
				WHERE	A.TypeId LIKE B.A + '%'
						AND A.SonNum = 0		
		END	
	ELSE IF @Flag = 14			--维修车型
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM QP_RepairAutoType WHERE SonNum = 0
			ELSE
				INSERT INTO @Temp(TypeId)
				SELECT 	DISTINCT A.TypeId 
				FROM 	QP_RepairAutoType A, 
						(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
				WHERE	A.TypeId LIKE B.A + '%'
						AND A.SonNum = 0		
		END	
	ELSE IF @Flag = 15			--凭证字
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT VgId FROM Ac_Voucher_Group
			ELSE
				INSERT INTO @Temp(TypeId)
				SELECT 	A.VgId 
				FROM 	Ac_Voucher_Group A, 
						(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
				WHERE	A.VgId LIKE B.A + '%'						
		END
	ELSE IF @Flag = 16			--币别
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT CId FROM Ac_Currency
			ELSE
				INSERT INTO @Temp(TypeId)
				SELECT 	A.CId 
				FROM 	Ac_Currency A, 
						(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
				WHERE	A.CId LIKE B.A + '%'						
		END		
	ELSE IF @Flag = 17			--货位
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT CargoID FROM CargoType
			ELSE
				INSERT INTO @Temp(TypeId)
				SELECT 	A.CargoID 
				FROM 	CargoType A, 
						(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
				WHERE	A.CargoID LIKE B.A + '%'						
		END		
	ELSE IF @Flag = 18			--总账会计科目
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM Ac_Account WHERE SonNum = 0
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.TypeId 
					FROM 	Ac_Account A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
							AND A.SonNum = 0							
				END	
		END
	ELSE IF @Flag = 19			--出纳银行
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT typeid FROM F_LineBank(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	A.typeid
					FROM 	F_LineBank(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE  A.typeid = B.A
				END	
				
		END
	ELSE IF @Flag = 20			--商品 排除服务类商品
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailPTypeNotService(@OperatorId)
			ELSE
				BEGIN					
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailPTypeNotService(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END	
	ELSE IF @Flag=21			--承运商
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) 
				SELECT TypeId FROM F_GetManDetailCType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailCType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END
					

	RETURN
END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetInvalidDate]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetInvalidDate]
GO
/*
	作者：shushan
	日期：
	描述：
*/
CREATE  FUNCTION [dbo].[F_GetInvalidDate]
(
	@CouponId		INT,
	@billdate		datetime, --入库、出库日期
	@billtype		INT
)	
RETURNS  DATETIME
--@Encode$--
AS
Begin
	--DECLARE @InvalidDate DATETIME,
	--		@InvalidType INT,
	--		@InvalidDate DATETIME,
	DECLARE	@InvalidDate DATETIME,
			@InvalidStartDateType INT,
			@InvalidTermType INT,
			@InvalidTerm INT
	
	SELECT @InvalidStartDateType=InvalidStartDateType,
			@InvalidTermType=InvalidTermType,
			@InvalidTerm =InvalidTerm
	FROM coupon_TypeInfo WHERE CouponId=@CouponId

	IF @billtype=423 AND @InvalidStartDateType=1
	BEGIN
		IF @InvalidTermType=1 --年
			SET @InvalidDate=  DATEADD(YEAR,@InvalidTerm,@billdate)
		IF @InvalidTermType=2 --月
			SET @InvalidDate=  DATEADD(MONTH,@InvalidTerm,@billdate)
		IF @InvalidTermType=3 --日
			SET @InvalidDate=  DATEADD(DAY,@InvalidTerm,@billdate)
	END
	IF @BILLTYPE=424 AND @InvalidStartDateType=2
	BEGIN
		IF @InvalidTermType=1 --年
			SET @InvalidDate=  DATEADD(YEAR,@InvalidTerm,@billdate)
		IF @InvalidTermType=2 --月
			SET @InvalidDate=  DATEADD(MONTH,@InvalidTerm,@billdate)
		IF @InvalidTermType=3 --日
			SET @InvalidDate=  DATEADD(DAY,@InvalidTerm,@billdate)
	END
	RETURN @InvalidDate
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManATypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManATypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖现金银行-树形表
*/
CREATE FUNCTION F_GetManATypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_GetManAType(@chvOperatorId)
)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManATypeFyAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManATypeFyAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖费用-树形表
*/
CREATE FUNCTION F_GetManATypeFyAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_GetManATypeFy(@chvOperatorId)
)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManATypeSrAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManATypeSrAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖收入-树形表
*/
CREATE FUNCTION F_GetManATypeSrAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
		SELECT	*
		FROM	F_GetManATypeSr(@chvOperatorId)
)
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManATypeZcAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManATypeZcAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖资产-树形表
*/
CREATE FUNCTION F_GetManATypeZcAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
		SELECT	*
		FROM	F_GetManATypeZc(@chvOperatorId)
)

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManBTypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManBTypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-树形表
*/
CREATE FUNCTION F_GetManBTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT
		*
	FROM
		F_GetManBType(@chvOperatorId)
)






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailANDFatherPType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailANDFatherPType]
GO


/*
	作者：cqiang
	日期：2020-04-24
	描述：获取所有管辖商品-线性表与父节点
*/
CREATE FUNCTION F_GetManDetailANDFatherPType
(
	@chvOperatorId			varchar(100),
	@Flag					int=0   --查询带有父节点
)
RETURNS @Temp TABLE
(
	TypeId varchar(100)
)
--@Encode$--
AS
BEGIN
	IF @Flag=1
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
			INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType
		ELSE
			INSERT INTO @Temp(TypeId) 
			SELECT	P.TypeId 
			FROM	PType_L L
			INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag = 1 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
			INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType WHERE SonNum = 0
		ELSE
			INSERT INTO @Temp(TypeId) 
			SELECT	P.TypeId 
			FROM	PType_L L
			INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag = 1 
					AND P.sonnum = 0
	END
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailKTypeSType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailKTypeSType]
GO



/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖仓库-线性表
	返回仓库ID与分支机构ID
*/
CREATE FUNCTION F_GetManDetailKTypeSType
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100),STypeId VARCHAR(100))
--@Encode$--
AS

BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
		INSERT INTO @Temp(TypeId,STypeId) SELECT TypeID,STypeID FROM Stock WHERE SonNum = 0
	ELSE
		BEGIN
			/*
			DECLARE @TypeId varchar(100)
			
			DECLARE PType_Cursor CURSOR FOR
				SELECT TypeId FROM KType_L WHERE ETypeID = @chvOperatorId AND Flag = 1

			OPEN PType_Cursor

			FETCH NEXT FROM PType_Cursor INTO @TypeId

			WHILE @@FETCH_STATUS = 0
				BEGIN
					INSERT INTO @Temp(TypeId,STypeId) SELECT TypeId,STypeId FROM Stock WHERE TypeId LIKE @TypeID + '%' AND SonNum = 0

					FETCH NEXT FROM PType_Cursor INTO @TypeId
				END

			CLOSE PType_Cursor
			DEALLOCATE PType_Cursor
			*/
			INSERT INTO @Temp(TypeId,STypeId) 
			SELECT	s.TypeId,s.STypeID
			FROM	KType_L L
			INNER JOIN stock  s ON S.TypeId LIKE L.TypeId + '%'
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag = 1 
					AND s.sonnum = 0
					
					
		END

	RETURN
END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_GetManDTypeAll') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetManDTypeAll
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖部门-树型表
*/
CREATE FUNCTION F_GetManDTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
	RETURN (
		SELECT	*
		FROM	 F_GetManDType(@chvOperatorId)
	)






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManETypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManETypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖职员-树形表
*/
CREATE FUNCTION F_GetManETypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
		SELECT	a.*
		FROM	F_GetManEType(@chvOperatorId) a
)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManKTypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManKTypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



















/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖仓库-树型表
*/
CREATE FUNCTION F_GetManKTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
	RETURN (
		SELECT	*
		FROM	F_GetManKType(@chvOperatorId)
	)






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManPTypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManPTypeAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖商品-树型表
*/
CREATE FUNCTION F_GetManPTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
RETURN (
	SELECT	*
	FROM	F_GetManPType(@chvOperatorId)
)




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManPTypeDetailALL]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManPTypeDetailALL]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



/*
	作者：毛欣蓉
	日期：2012-05-10
	描述：得到职员的管辖商品和其单位间的换算率
*/

CREATE FUNCTION F_GetManPTypeDetailALL
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (  	
		SELECT 	P.typeId,
				P.ParId,
				P.leveal,
				P.sonnum,
				p.UserCode,
				p.FullName,
				p.EntryCode,
				p.deleted,
				p.Area,
				p.Standard,
				p.Type,
				1 as baseUnitRate,
				ISNULL(e1.Rate,1) as buyUnitRate,
				ISNULL(e2.Rate,1) as saleUnitRate,
				ISNULL(e3.Rate,1) as stockUnitRate,
			    e4.FullName AS buyunitfullname,
			    e5.FullName AS saleunitfullname,
			    e6.FullName AS stockunitfullname,
			    e7.FullName AS baseunitfullname,
			    e8.FullName AS assistantfullname,
				p.IsService,
				p.SortID,
				p.iscombinationproduct
		FROM 	PType P
		LEFT JOIN PType_Units_Ext e1 ON e1.PTypeId = P.TypeId AND P.BuyUnitId = E1.UnitsId
		LEFT JOIN PType_Units_Ext e2 ON e2.PTypeId = P.TypeId AND P.SaleUnitId = e2.UnitsId
		LEFT JOIN PType_Units_Ext e3 ON e3.PTypeId = P.TypeId AND P.StockUnitId = e3.UnitsId
		LEFT JOIN dbo.PType_Units e4 ON  e4.UnitsId = P.BuyUnitId
		LEFT JOIN dbo.PType_Units e5 ON  e5.UnitsId = P.SaleUnitId
		LEFT JOIN dbo.PType_Units e6 ON  e6.UnitsId = P.StockUnitId
		LEFT JOIN dbo.PType_Units e7 ON  e7.UnitsId = p.baseUnitId
		LEFT  JOIN dbo.PType_Units  e8 ON e8.UnitsId = p.AssistantUnitId
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
				AND P.TypeId <> '00000' 
		UNION ALL		
		SELECT 	P.typeId,
				P.ParId,
				P.leveal,
				P.sonnum,
				p.UserCode,
				p.FullName,
				p.EntryCode,
				p.deleted,
				p.Area,
				p.Standard,
				p.Type,
				1 as baseUnitRate,
				ISNULL(e1.Rate,1) as buyUnitRate,
				ISNULL(e2.Rate,1) as saleUnitRate,
				ISNULL(e3.Rate,1) as stockUnitRate,
				 e4.FullName AS fullname4,
			     e5.FullName AS fullname5,
			     e6.FullName AS fullname6,
			     e7.FullName AS baseunitfullname,
			     e8.FullName AS assistantfullname,
			     p.IsService,
			     p.SortID,
			     p.iscombinationproduct
		FROM 	F_GetManDetailAllPType(@chvOperatorId) M
		INNER JOIN PType P ON P.TypeId = M.TypeId
		LEFT JOIN PType_Units_Ext e1 ON e1.PTypeId = P.TypeId AND P.BuyUnitId = E1.UnitsId
		LEFT JOIN PType_Units_Ext e2 ON e2.PTypeId = P.TypeId AND P.SaleUnitId = e2.UnitsId
		LEFT JOIN PType_Units_Ext e3 ON e3.PTypeId = P.TypeId AND P.StockUnitId = E3.UnitsId
		LEFT JOIN dbo.PType_Units e4 ON  e4.UnitsId = P.BuyUnitId
		LEFT JOIN dbo.PType_Units e5 ON  e5.UnitsId = P.SaleUnitId
		LEFT JOIN dbo.PType_Units e6 ON  e6.UnitsId = P.StockUnitId
		LEFT JOIN dbo.PType_Units e7 ON  e7.UnitsId = p.baseUnitId
		LEFT  JOIN dbo.PType_Units e8 ON e8.UnitsId = p.AssistantUnitId
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '-99999')
	)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_GetManSTypeAll') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetManSTypeAll
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖分支机构-树型表
*/

CREATE FUNCTION F_GetManSTypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@Encode$--
AS
	RETURN (
		SELECT	a.*
		FROM	F_GetManSType(@chvOperatorId) a
	)





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetOrderMark]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetOrderMark]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  UserDefinedFunction [dbo].[F_GetVipMoney]    Script Date: 12/14/2011 15:07:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年12月14日
-- Description:	获取单据的引用状况
-- =============================================
Create FUNCTION [dbo].[F_GetOrderMark] 
(
    @billnumberid INT,  --单据ID
    @billtype  int
)
RETURNS INT
AS
BEGIN
  Declare @Mark  INT 
  Declare @table varchar(100)
  Declare @SQL VARCHAR(MAX)

IF(@billtype=301)
BEGIN
	IF EXISTS(
	SELECT * FROM	OrderBill A INNER JOIN BuyBill  B ON A.ORDERID=B.ORDERID where A.billnumberid=@billnumberid)
	SET @Mark=1
	ELSE
	SET @Mark=0
END
ELSE
	IF EXISTS(
	SELECT * FROM	OrderBill A INNER JOIN SaleBill  B ON A.ORDERID=B.ORDERID where A.billnumberid=@billnumberid)
	SET @Mark=1
	ELSE
	SET @Mark=0
RETURN @Mark
END
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetOrderNCustomerTotal]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetOrderNCustomerTotal]
GO

--组合品订单 销售订单 订金
CREATE FUNCTION F_GetOrderNCustomerTotal
(
	@BillNumberId  [numeric](10, 0),
	@billtype     [numeric](4, 0)   
)
returns [numeric](18, 4) 
AS 
BEGIN
	declare @ncostomerTotal [numeric](18, 4)
	--如果调用的订单只有一个币种，统计订金原币
	--如果调用的订单有两个币种，统计订金本币
	IF @billtype=11
	BEGIN
		select @ncostomerTotal= CASE WHEN COUNT(a.cid)>1 THEN isnull( sum(customertotal),0)
								ELSE isnull(sum(ncustomertotal),0)
								END 
		from 
		(
			SELECT o.cid,  sum(o.ncustomertotal)as ncustomertotal,sum(o.customertotal) AS customertotal 
			FROM ORDERINDEX O
			INNER JOIN (
						SELECT DISTINCT BILLNUMBERID FROM ORDERBILL WHERE ORDERID IN (SELECT ORDERID FROM SALEBILL WHERE BILLNUMBERID =@BillNumberId)
						) B on o.BILLNUMBERID=b.BILLNUMBERID
			group by o.cid 		
		) A			
					
	END
	ELSE IF @billtype=12
	BEGIN
		select @ncostomerTotal= CASE WHEN COUNT(a.cid)>1 THEN isnull( sum(customertotal),0)
								ELSE isnull(sum(ncustomertotal),0)
								END 
		from 
		(
			SELECT o.cid,  sum(o.ncustomertotal)as ncustomertotal,sum(o.customertotal) AS customertotal 
			FROM ORDERINDEX O
			INNER JOIN (
						SELECT DISTINCT BILLNUMBERID FROM PT_Combin_OrderBillDetail WHERE ORDERID IN (SELECT ORDERID FROM PT_Combin_SaleBillDetail WHERE BILLNUMBERID =@BillNumberId)
						) B on o.BILLNUMBERID=b.BILLNUMBERID 
			group by o.cid 		
		) A			
	END
	ELSE
	BEGIN
		SET @ncostomerTotal=0
	END

    RETURN  @ncostomerTotal
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetPath]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetPath]
GO

-- ========================================================================
-- 功能说明：获取基本信息的路径
-- 作者：毛欣蓉  
-- 时间：2010-08-27
-- ========================================================================
CREATE  FUNCTION  F_GetPath
(
	@typeid as	VARCHAR(50),
	@flag	as	INT
)
RETURNS VARCHAR(1000) 
AS  
BEGIN 
Declare @szThePath as VARCHAR(1000) 

IF @typeid IS NULL OR @flag IS NULL RETURN 1
	DECLARE @temp VARCHAR(66),@parid VARCHAR(50),@path VARCHAR(350)
	DECLARE @i INT
	

	declare @pathname varchar(100)
	SET @pathname=''
	IF @flag=1  --atype 
		SET @pathname='全部会计科目'
	ELSE IF @flag=2  --btype
	BEGIN
		if LEFT(@typeid,5)='00001'
			SET @pathname='全部客户'
		else
			SET @pathname='全部供货商'		
	END
	ELSE IF @flag=3  --employee
		SET @pathname='全部职员'
	ELSE IF @flag=4  --ptype
		SET @pathname='全部商品'
	ELSE IF @flag=5 --stock
		SET @pathname='全部仓库'
	ELSE IF @flag=6 --atype
		SET @pathname='全部账户'
	ELSE IF @flag=7 --expense
		SET @pathname='全部费用'
	ELSE IF @flag=8 --income
		SET @pathname='全部其他收入'
	ELSE IF @flag=9 --capital asserts  固定资产
		SET @pathname='全部固定资产'
	ELSE IF @flag=10 --DepartMent  分支机构
		SET @pathname='所有部门'
	ELSE IF @flag=11 --Atype  会计科目
		SET @pathname='全部会计科目'
	ELSE IF @flag=12 --AreaType  地区档案
		SET @pathname='全部地区档案'
	ELSE IF @flag=13 --SType  分支机构
		SET @pathname='全部分支机构'
	ELSE IF @flag = 14 	--QP_RepairAutoType 维修车型档案
		SET @pathname = '全部维修车型'
	ELSE IF @flag = 15  --QP_RepairItems   维修项目资料
		SET @pathname = '全部维修项目资料'
	ELSE IF @flag = 16  --QP_RepairComb   维修套餐档案
		SET @pathname = '全部维修套餐档案'
	ELSE IF @flag = 17	--QP_RepairAutoInfo	维修车辆信息档案
		SET @pathname = '全部维修车辆信息档案'
	ELSE IF @flag = 18  --会计科目
		SET @pathname = '全部会计科目'

	SELECT @typeid=RTRIM(@typeid)
	IF @flag=18
		SELECT @path=''
	ELSE
		SELECT @path='\'
	IF @flag=9
		SELECT @i=10
	ELSE IF @flag=18
		SELECT @i=10
	ELSE
		SELECT @i=5
	declare @deleted int
	set @deleted=0
	WHILE 1=1
		BEGIN
			SELECT @parid=LEFT(@typeid,@i)  
			IF len(@parid)<=len(@typeid)
				BEGIN
					IF @flag=1  --atype 
						SELECT @temp=fullname,@deleted=deleted FROM atype WHERE typeid=@parid
					ELSE IF @flag=2  --btype
							SELECT @temp=fullname,@deleted=deleted FROM btype WHERE typeid=@parid
					ELSE IF @flag=3  --employee
							SELECT @temp=fullname,@deleted=deleted FROM employee WHERE typeid=@parid
					ELSE IF @flag=4  --ptype
							SELECT @temp=fullname,@deleted=deleted FROM ptype WHERE typeid=@parid
					ELSE IF @flag=5 --stock
							SELECT @temp=fullname,@deleted=deleted FROM stock WHERE typeid=@parid
					ELSE IF @flag=6 --atype
						SELECT @temp=fullname,@deleted=deleted FROM atype WHERE typeid=@parid
					ELSE IF @flag=7 --expense
						SELECT @temp=fullname,@deleted=deleted FROM atype WHERE typeid=@parid
					ELSE IF @flag=8 --income
						SELECT @temp=fullname,@deleted=deleted FROM atype WHERE typeid=@parid
					ELSE IF @flag=9 --capital asserts  固定资产
						SELECT @temp=fullname ,@deleted=deleted FROM Ac_FixedAssets WHERE typeid=@parid
					ELSE IF @flag=10 --DepartMent  部门
						SELECT @temp=fullname,@deleted=deleted FROM DepartMent WHERE typeid=@parid
					ELSE IF @flag=11 --Atype  会计科目
						SELECT @temp=fullname,@deleted=deleted FROM Atype WHERE typeid=@parid
					ELSE IF @flag=12 --AreaType  地区档案
						SELECT @temp=fullname,@deleted=deleted FROM AreaType WHERE typeid=@parid
					ELSE IF @flag=13 --SType  分支机构
						SELECT @temp=fullname,@deleted=deleted FROM SType WHERE typeid=@parid
					ELSE IF @flag = 14 --RepairAutoType 维修车型档案
						SELECT @temp=fullname FROM QP_RepairAutoType WHERE typeid=@parid
					ELSE IF @flag = 15 --QP_RepairItems   维修项目资料
						SELECT @temp=fullname FROM QP_RepairItems WHERE typeid=@parid
					ELSE IF @flag = 16 --QP_RepairComb   维修套餐档案
						SELECT @temp=fullname FROM dbo.QP_RepairSetMeal WHERE typeid=@parid
					ELSE IF @flag = 17	--QP_RepairAutoInfo	维修车辆信息档案
						SELECT @temp=PlateNumber FROM dbo.QP_RepairAutoInfo WHERE typeid=@parid
					ELSE IF @flag = 18  --会计科目
						SELECT TOP 1 @temp=fullname FROM Ac_Account WHERE TypeId=@parid

					--print @temp
					IF (@deleted=1 and @parid<>'0000' ) or @typeid='-99999'
						BEGIN
							IF @typeid = '-99999' SET @Path=@Path+'★部分授权'
							ELSE SET @Path=@path+'已停用'
							BREAK
						END

					IF @temp='库存商品' AND @flag != 18 SELECT @temp='全部商品'
					IF @temp='所有客户' SELECT @temp='全部客户'
					IF @temp='全部供货商'     SELECT @temp='全部供货商'
					IF @temp='超级用户' SELECT @temp='全部职员'
					IF @temp='全部仓库' SELECT @temp='全部仓库'
					IF @temp='所有部门' SELECT @temp='所有部门'		
					
					IF @flag=4 IF @path='\' AND @temp<>'全部商品' SELECT @temp='全部商品\'+@temp
					IF @flag=5 IF @path='\' AND @temp<>'全部仓库' SELECT @temp='全部仓库\'+@temp
					IF @flag=6 AND @parid='0000' SELECT @temp='全部账户'
					IF @flag=7 AND @parid='0000' SELECT @temp='全部费用'
					IF @flag=8 AND @parid='0000' SELECT @temp='全部其他收入'
					IF @flag=9 AND @parid='0000100002' SELECT @temp='全部固定资产'

					IF @flag=10 AND @parid='00000' SELECT @temp='所有部门'
					IF @flag=10 IF @path='\' AND @temp<>'所有部门' SELECT @temp='所有部门\'+@temp

					IF @flag=11 AND @parid='00000' SELECT @temp='全部会计科目'
					IF @flag=11 IF @path='\' AND @temp<>'全部会计科目' SELECT @temp='全部会计科目\'+@temp
					
					IF @flag=12 AND @parid='00000' SELECT @temp='全部地区档案'
					IF @flag=12 IF @path='\' AND @temp<>'全部地区档案' SELECT @temp='全部地区档案\'+@temp
					
					IF @flag=13 AND @parid='00000' SELECT @temp='全部分支机构'
					IF @flag=13 IF @path='\' AND @temp<>'全部分支机构' SELECT @temp='全部分支机构\'+@temp

					IF @flag=14 AND @parid='00000' SELECT @temp='全部维修车型档案'
					IF @flag=14 IF @path='\' AND @temp<>'全部维修车型档案' SELECT @temp='全部维修车型档案\'+@temp

					IF @flag=15 AND @parid='00000' SELECT @temp='全部维修项目资料'
					IF @flag=15 IF @path='\' AND @temp<>'全部维修项目资料' SELECT @temp='全部维修项目资料\'+@temp


					IF @flag=16 AND @parid='00000' SELECT @temp='全部维修套餐档案'
					IF @flag=16 IF @path='\' AND @temp<>'全部维修套餐档案' SELECT @temp='全部维修套餐档案\'+@temp

					IF @flag=17 AND @parid='00000' SELECT @temp='全部维修车辆信息档案'
					IF @flag=17 IF @path='\' AND @temp<>'全部维修车辆信息档案' SELECT @temp='全部维修车辆信息档案\'+@temp
					
					--IF @flag=18 AND @parid='00000' SELECT @temp='全部会计科目'
					IF @flag=18 
						SELECT @path=@path + @temp + ' - '
					ELSE
						SELECT @path=@path+@temp+'\'
					
					SELECT @i=@i+5
				END

			IF len(@parid)=len(@typeid)   BREAK
		END 
	IF @path='\已停用'
		SET @path='\'+@pathname+@path
	IF @flag=18
		SELECT @szThePath=LEFT(@path,len(@path)-1)
	ELSE
		SELECT @szThePath=@path
	return @szThePath
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetPromoRuleNames]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetPromoRuleNames]
GO

/*
	描述：通过促销方案的id字符串获取对应的名称字符串
*/
CREATE  FUNCTION F_GetPromoRuleNames
(
	@PromonRuleIds		VARCHAR(1000) 	--促销方案ids字符串，id之间逗号分隔	
)	
returns varchar(1000)
AS 
BEGIN
	DECLARE @result VARCHAR(1001)
	SET @result = '';
	SELECT @result += ';' + p.FullName FROM dbo.PromoRule p INNER JOIN dbo.f_split(@PromonRuleIds,',') f ON f.a = p.ID

	RETURN SUBSTRING(@result,2,1000)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetUnionBillType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetUnionBillType]
GO

/*
	作者：谢吉康
	日期：2011-08-09
	描述：判断单据类型是否存在
*/

CREATE FUNCTION F_GetUnionBillType
(
	@SourceBillType VARCHAR(MAX),	--源单据类型
	@DescBillType	VARCHAR(MAX)	--目标单据类型
)
RETURNS INT
--@Encode$--
AS 
BEGIN
	DECLARE @intResult INT
	SET @intResult = 0
    IF EXISTS(
		SELECT	S.* 
		FROM	f_split(@SourceBillType,',') S
		INNER JOIN (
					SELECT	* 
					FROM	f_split(@DescBillType,',')
		)D ON S.A = D.A 
    ) 
		SET @intResult = 1
		
    RETURN @intResult
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetValidUserData]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetValidUserData]
GO



/*
	作者：谢吉康
	日期：2009-11-11
	描述：对于操作员自己输入的名称进行处理
*/
CREATE FUNCTION F_GetValidUserData
(
	@chvData		varchar(4000)
)
RETURNS varchar(8000)
--@encode$--
AS
	BEGIN
		DECLARE @chvSplitor	varchar(1000),
				@rString	varchar(6000)
				
		SET @rString = ''
		
		DECLARE SplitorCursor CURSOR FOR
			SELECT A FROM f_split(@chvData,';') WHERE ISNULL(A,'')<>''	
		
		OPEN SplitorCursor
		
		FETCH NEXT FROM SplitorCursor INTO @chvSplitor
		
		WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @rString = @rString + ';' + @chvSplitor
				FETCH NEXT FROM SplitorCursor INTO @chvSplitor
			END
		
		CLOSE SplitorCursor
		DEALLOCATE SplitorCursor
		
		IF @rString <> ''
			SET @rString = RIGHT(@rString,LEN(@rString)-1)
		
		RETURN @rString
	END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetValidUserDataId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetValidUserDataId]
GO


/*
	作者：谢吉康
	日期：2009-11-11
	描述：对于操作员自己输入的名称进行处理
	
	日期：2012-11-30
	作者：王伟峰
	描述：调整权限函数
*/
CREATE FUNCTION F_GetValidUserDataId
(
	@chvData		varchar(MAX)
)
RETURNS varchar(MAX)
--@encode$--
AS
	BEGIN
		DECLARE @chvSplitor	varchar(1000),
				@rString	varchar(MAX)
				
		SET @rString = ''
		IF @chvData = '00000' OR @chvData = '' OR @chvData = '%'
		BEGIN
			SET @rString = '%'
			RETURN @rString
		END
		
		DECLARE SplitorCursor CURSOR FOR
			SELECT A FROM f_split(@chvData,',') WHERE ISNULL(A,'')<>''	
		
		OPEN SplitorCursor
		
		FETCH NEXT FROM SplitorCursor INTO @chvSplitor
		
		WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @rString = @rString + ',' + @chvSplitor
				FETCH NEXT FROM SplitorCursor INTO @chvSplitor
			END
		
		CLOSE SplitorCursor
		DEALLOCATE SplitorCursor
		
		IF @rString <> ''
			SET @rString = RIGHT(@rString,LEN(@rString)-1)
		
		RETURN @rString
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_splitAN]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_splitAN]
GO














--实现split功能 的函数
--date    :2003-10-14
CREATE FUNCTION f_splitAN
(
	@SourceSql varchar(max),
	@StrSeprate varchar(10)
)
returns @temp TABLE([ID] int ,a varchar(100))
AS 
BEGIN
    DECLARE @i int
    DECLARE @j int
	SET @j =1
    SET @SourceSql=RTRIM(LTRIM(@SourceSql))
    SET @i=charindex(@StrSeprate,@SourceSql)
    WHILE @i>=1
	    BEGIN
	        INSERT @temp VALUES(@j,LEFT(@SourceSql,@i-1))
			SET @j = @j +1
	        SET @SourceSql=SUBSTRING(@SourceSql,@i+1,len(@SourceSql)-@i)
	        SET @i=charindex(@StrSeprate,@SourceSql)
	    END
    IF @SourceSql<>'' 
       INSERT @temp VALUES(@j,@SourceSql)
       SET @j = @j +1
    RETURN 
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT  1 FROM dbo.SysObjects WHERE ID = OBJECT_ID(N'[dbo].[F_SplitIncludEmpty]') AND XType IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[F_SplitIncludEmpty]
GO

--实现split功能 的函数
--date    :2003-10-14
CREATE FUNCTION F_SplitIncludEmpty
(
	@SourceSql varchar(8000),
	@StrSeprate varchar(10)
)
returns @temp TABLE([ID] int ,a varchar(100))
AS 
BEGIN
    DECLARE @i int
    DECLARE @j int
	SET @j =1
    SET @SourceSql=RTRIM(LTRIM(@SourceSql))
    SET @i=charindex(@StrSeprate,@SourceSql)
    WHILE @i>=1
	    BEGIN
	        INSERT @temp VALUES(@j,LEFT(@SourceSql,@i-1))
			SET @j = @j +1
	        SET @SourceSql=SUBSTRING(@SourceSql,@i+1,len(@SourceSql)-@i)
	        SET @i=charindex(@StrSeprate,@SourceSql)
	    END
    INSERT @temp VALUES(@j,@SourceSql)
    SET @j = @j +1
    RETURN 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_SplitSerial]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_SplitSerial]
GO
-- ========================================================================
-- 功能说明：		分割序列号，用于序列号过账
-- 最后修改作者：	冯 波
-- 最后修改时间：	2014-07-01
-- ========================================================================
CREATE   FUNCTION   F_SplitSerial(@StrSerial   VARCHAR(MAX),@StrSplit   VARCHAR(10))  
RETURNS   @t   TABLE(Serial   VARCHAR(100),ShowOrder INT IDENTITY(1,1))  
AS
BEGIN
		WHILE(CHARINDEX(@strSplit,@StrSerial)<>0)  
		BEGIN  
			IF SUBSTRING(@StrSerial,1,CHARINDEX(@strSplit,@StrSerial)-1)<>''
			BEGIN
				INSERT   @t(Serial)   VALUES(SUBSTRING(@StrSerial,1,CHARINDEX(@strSplit,@StrSerial)-1))  
			END
			SET   @StrSerial=STUFF(@StrSerial,1,CHARINDEX(@strSplit,@StrSerial),'')  
			
		END

		IF @StrSerial<>''	
		BEGIN
			INSERT   @t(Serial)   VALUES(@StrSerial)  
		END

		RETURN  
END
     
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_FixStr]')and ((OBJECTPROPERTY(id, N'IsTableFunction') = 1) OR (OBJECTPROPERTY(id, N'IsScalarFunction') = 1))
)
drop Function [dbo].[FN_FixStr]
GO




/*

功能说明：       根据指定的字符和长度来进行填充

作    者：       冯波

创建日期：       2004-6-10

返回结果：       记录集

*/

CREATE FUNCTION FN_FixStr(
	@intLen	Int,					--长度
	@strConvertedStr Varchar(100),	--需要转换的字符串
	@strFixChar Varchar(1)			--需要填充的字符
)
Returns Varchar(500)
--@Encode$--
AS 

BEGIN
	--通过循环来填充
	WHILE LEN(@strConvertedStr)<@intLen
	BEGIN
		SET @strConvertedStr=@strFixChar+@strConvertedStr
	END	    
	RETURN @strConvertedStr
END



GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetCurrentAuditETypeID]')and ((OBJECTPROPERTY(id, N'IsTableFunction') = 1) OR (OBJECTPROPERTY(id, N'IsScalarFunction') = 1))
)
drop Function [dbo].[FN_GetCurrentAuditETypeID]
GO



/*

功能说明：       得到指定单据的当前审核人

作    者：       冯波

创建日期：       2011-3-18

返回结果：       

*/

CREATE FUNCTION FN_GetCurrentAuditETypeID(
	@intBillNumberID	INT,			--单据ID
	@strSTypeID			VARCHAR(50),
	@intBillType		Int				--单据类型
		
)
Returns @GetCurrentAuditStepTab TABLE(
	ETypeID			VARCHAR(50),
	AuditingStep	INT      
)
--@Encode$--
AS 
BEGIN    
	DECLARE 
		@intAuditingID				INT,			--审核流程ID
		@intAuditingType			INT				--签呈方式(1表示顺序,0表示会签)
		

	SELECT @intAuditingID=AuditingID,@intAuditingType=AuditingType
	FROM AuditingFlowSet(NOLOCK)
	WHERE STypeID=@strSTypeID AND BillType=@intBillType AND IfUse=1
	
	IF NOT EXISTS(
	SELECT BillNumberID FROM AuditingBill(NOLOCK)
	WHERE BillNumberID=@intBillNumberID AND IfAudit=0
	)
	BEGIN
		RETURN
	END


	--如果是顺序审核，则查下一步的审核人
	--如果是会签审核，则查所有未审核的步骤的审核人
	
	--PassSteps表示各步骤是否需要审核的状态，1表示要审核的，2表示不审核的
	--AuditingSteps表示各步骤是否审核通过的状态，1表示审核通过的，2表示未审核
	
	DECLARE
			@strPassSteps		VARCHAR(500),
			@strAuditingSteps	VARCHAR(500)
	
	SELECT
			@strPassSteps=PassSteps,
			@strAuditingSteps=AuditingSteps
		FROM AuditingBill(NOLOCK)
		WHERE BillNumberID=@intBillNumberID	AND AuditingID=@intAuditingID
		
	--顺序审核，先看当前需要审核的步骤是哪一步
	DECLARE
			@intFirstNeedAuditStep	INT
	
	SELECT @intFirstNeedAuditStep=MIN(a.AuditingStep)
	FROM AuditingFlowDetail a(NOLOCK)
	WHERE
		a.AuditingStep IN
		(
			SELECT AllCharIndex FROM FN_GetAllCharIndex('1',@strPassSteps)
		)
		AND a.AuditingStep NOT IN
		(
			SELECT AllCharIndex FROM FN_GetAllCharIndex('1',@strAuditingSteps)
		)

	IF @intAuditingType=1
	BEGIN
		--只管顺序审核
		INSERT @GetCurrentAuditStepTab
		SELECT ETypeID,AuditingStep
		FROM AuditingFlowDetail(NOLOCK)
		WHERE AuditingID=@intAuditingID AND AuditingStep=@intFirstNeedAuditStep
	END
	ELSE
	BEGIN			
		INSERT @GetCurrentAuditStepTab
		SELECT A.ETypeID,A.AuditingStep
		FROM AuditingFlowDetail A
		INNER JOIN AuditingBill B ON a.AuditingID=b.AuditingID
		
		WHERE B.BillNumberID=@intBillNumberID AND 
			  A.AuditingStep NOT IN (SELECT AuditingStep FROM AuditingBillDetail WHERE BillNumberID=@intBillNumberID AND BillIndexType=B.BillIndexType)
		
		GROUP BY A.ETypeID,A.AuditingStep
		ORDER BY A.AuditingStep ASC
	END
	
	RETURN

END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_sms_format]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_sms_format]
GO














CREATE  function fn_sms_format(@dec  NUMERIC(24, 10) )
RETURNS varchar(50)
as
begin
Declare @vreturn varchar(50)
if @dec = 0 return '0'

set @vreturn = @dec
while right(@vreturn,1) = '0'  and right(@vreturn,1) <> '.'
set @vreturn = left(@vreturn,len(@vreturn) - 1)
if right(@vreturn,1) = '.' 
set @vreturn = left(@vreturn,len(@vreturn) - 1)

return @vreturn  
end














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[ClearZero]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].ClearZero
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能：清除小数位数后面的0
-- 作者：彭勇  
-- 时间：2015-12-03
-- ========================================================================
CREATE FUNCTION [ClearZero] ( @inValue NUMERIC(24,10) )
RETURNS VARCHAR(34)
AS 
    BEGIN
    
   DECLARE @temp NUMERIC(24,10)
   SET @temp=dbo.F_RoundData( @inValue,'qty')
 
    
        DECLARE @returnValue VARCHAR(34)
        --IF ( @inValue = '' ) 
        --    SET @returnValue = '' --空的时候为空
          IF ( CHARINDEX('.', @temp) = '0' ) 
                SET @returnValue = @temp --针对不含小数点的
        ELSE  IF ( SUBSTRING(REVERSE(@temp),
                               PATINDEX('%[^0]%', REVERSE(@temp)), 1) = '.' ) 
                    SET @returnValue = LEFT(@temp,
                                            LEN(@temp) - PATINDEX('%[^0]%',
                                                              REVERSE(@temp))) --针对小数点后全是0的
        ELSE 
                    SET @returnValue = LEFT(@temp,
                                            LEN(@temp)
                                            - PATINDEX('%[^0]%.%',
                                                       REVERSE(@temp)) + 1) --其他任何情形
         RETURN        @returnValue                                       
                                                       
                                                       
    END
    
    GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetIdStrListTable]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[FN_GetIdStrListTable]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




CREATE FUNCTION [FN_GetIdStrListTable] (
	@IdList varchar(8000)
)  
RETURNS @table table(
 	GetId Varchar(50)
) 
--@Encode$--
AS  
BEGIN 
    declare @Id 	varchar(50)
    declare @CharIndex  int
		if @IdList = '' or @idList = '00000'
		begin
      Insert @table select ''
                    union all select '00000'    
			return
		end

    while(@IdList <> '')
    begin
      set @Id=0
      set @CharIndex = CHARINDEX( ',', @IdList,1)
      if @CharIndex > 0 
      begin
          set @Id = substring(@IdList,1,@CharIndex - 1)
          set @IdList = substring(@IdList,@CharIndex + 1,len(@IdList))
      end
      else
      if @IdList <> ''
      begin
          set @Id = @IdList
          set @IdList = ''
      end
      if @Id <> ''
          Insert @table select @Id
    end      
	return 
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FN_GetPowerRangeBList]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[FN_GetPowerRangeBList]
GO





CREATE      FUNCTION FN_GetPowerRangeBList
    (
      @OperatorID VARCHAR(50) ,
      @ParID VARCHAR(8000) = '%' ,
      @BtypeList VARCHAR(1000) = '2'
    )
RETURNS @BtypeRange TABLE
    (
      [BranchID] [varchar](50) ,
      [TypeId] [varchar](50) ,
      [ParID] [varchar](50) ,
      [Leveal] [smallint] ,
      [SonCount] [int] ,
      [SonNum] [int] ,
      [UserCode] [varchar](30) ,
      [FullName] [varchar](100) ,
      [Name] [varchar](100)
    )
--@Encode$--
AS 
    BEGIN
       INSERT  INTO @BtypeRange
                        ( 
                          BranchID,
                          TypeId ,
                          ParID ,
                          Leveal ,
                          SonCount ,
                          SonNum ,
                          UserCode ,
                          FullName ,
                          Name
                        )
                        select b.TypeId as  BranchID,
                          a.TypeId ,
                          a.ParID ,
                          a.Leveal ,
                          a.SonCount ,
                          a.SonNum ,
                          a.UserCode ,
                          a.FullName ,
                          a.Name 
                          from F_GetManBTypeAll(@OperatorID) a
                          LEFT OUTER JOIN 
                          stype b(NOLOCK) on a.typeId=b.BTypeID1                    
                          where a.sonnum=0
                          RETURN
    END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FN_GetPowerRangeEList]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[FN_GetPowerRangeEList]
GO




CREATE  FUNCTION FN_GetPowerRangeEList
    (
      @OperatorID VARCHAR(50) ,
      @ParID VARCHAR(8000) = '%'
    )
RETURNS @EmployeeRange TABLE
    (
      [TypeId] [varchar](50) ,
      [Rec] [int] ,
      [ParID] [varchar](50) ,
      [Leveal] [smallint] ,
      [SonCount] [int] ,
      [SonNum] [int] ,
      [FullName] [varchar](100) ,
      [Name] [varchar](100) ,
      [UserCode] [varchar](100) ,
      [Dtypeid] [varchar](50) ,
      [Deleted] [bit] ,
      [ZkPopedom]  NUMERIC(24, 10)  ,
      [YhPopedom]  NUMERIC(24, 10)  ,
      [IsShopSale] [bit] ,
      [BranchId] [varchar](50) ,
      [UpdateTag] [int]
    )
--@Encode$--
AS 
    BEGIN
        INSERT  INTO @EmployeeRange
                        ( 
                          TypeId ,
                          Rec ,
                          ParID ,
                          Leveal ,
                          SonCount ,
                          SonNum ,
                          FullName ,
                          Name ,
                          UserCode ,
                          Dtypeid ,
                          Deleted ,
                          ZkPopedom ,
                          YhPopedom ,
                          IsShopSale ,
                          BranchId ,
                          UpdateTag
                        )
                    SELECT TypeId ,
                          0 as Rec ,
                          ParID ,
                          Leveal ,
                          SonCount ,
                          SonNum ,
                          FullName ,
                          Name ,
                          UserCode ,
                          Dtypeid ,
                          Deleted ,
                          0 as ZkPopedom ,
                          0 as YhPopedom ,
                          0 as IsShopSale ,
                          stypeid as BranchId ,
                          XiWaMaxNumber as UpdateTag
				    FROM F_GetManETypeAll(@OperatorID) where sonnum=0


        RETURN
    END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FN_GetPowerRangePList]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[FN_GetPowerRangePList]
GO


CREATE  FUNCTION FN_GetPowerRangePList
    (
      @OperatorID VARCHAR(50) ,
      @ParID VARCHAR(8000) = ''
    )
RETURNS TABLE
--@Encode$--
AS
RETURN
    ( 
       select * from F_GetManPTypeAll(@OperatorID)
    )

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AssistByStype]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AssistByStype
GO

/*
	作者：GLJ
	日期：2013-11-05
	描述：辅助核算分支机构
*/
CREATE  FUNCTION F_AssistByStype
(
	@STypeId		varchar(50),	 
	@TypeId			varchar(50),	 
	@OperatorId		varchar(100)	 
)	
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @result VARCHAR(30)
    SELECT @result=SubValue FROM dbo.sysdata WHERE SubName='innerstypesaleralation'
        
    IF @result='1'
		INSERT INTO @Temp(TypeId)
		SELECT s.TypeId FROM F_GetAllManagerBaseTypeId(@TypeId,11,@OperatorId) f
		JOIN dbo.SType s ON  s.TypeId=f.TypeId AND s.VerifyID=@STypeId
	ELSE 
		INSERT INTO @Temp(TypeId)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@TypeId,11,@OperatorId) f
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AssistStype]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AssistStype
GO

/*
	作者：董湛
	日期：2013-5-08
	描述：分支机构辅助核算项特殊处理
*/
CREATE  FUNCTION F_AssistStype
(
	@TypeId			varchar(50),	 
	@OperatorId		varchar(100)	 
)	
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @result VARCHAR(30)
    SELECT @result=SubValue FROM dbo.sysdata WHERE SubName='innerstypesaleralation'
        
    IF @result='1'
		INSERT INTO @Temp(TypeId)
		SELECT s.TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorId) f
		JOIN dbo.SType s ON  s.TypeId=f.TypeId AND s.VerifyID=@TypeId
	ELSE 
		INSERT INTO @Temp(TypeId)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorId) f
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_CalAccountDate]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_CalAccountDate]
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2015-10-10
-- Description: 计算对账日期
-- =============================================
CREATE FUNCTION [F_CalAccountDate]
(
	@BILLDATE	DATETIME,
	@dzdays		INT
)
RETURNS DATETIME
--@Encode$--
AS 
BEGIN
	DECLARE @accountdate	DATETIME ,
	@month	INT	,@nextMonth INT
	SELECT @month=MONTH(@BILLDATE)
	SELECT @nextMonth=DATEPART(MONTH,DATEADD(MONTH,1,@BILLDATE))
	
	IF ISNULL(@dzdays,0)=0
		RETURN NULL	
	
	IF (@dzdays>=DAY(@BILLDATE))    --对账日期在当月
	BEGIN
		IF (@dzdays<29) OR (@dzdays IN(29,30) AND @month<>2) OR (@dzdays=31 AND @month IN(1,3,5,7,8,10,12))
		BEGIN
			SET @accountdate=convert(nvarchar(7),@BILLDATE,120)+'-'	+ CAST (@dzdays AS VARCHAR(2))	
		END
		ELSE IF (@dzdays=31 AND @month IN(4,6,9,11)) OR  (@dzdays IN(19,30,31) AND  @month=2)
		BEGIN
			SET @accountdate=DATEADD(Day,-1,CONVERT(char(8),DATEADD(Month,1,@BILLDATE),120)+'1')   --最后一天
		END
	END
	ELSE  --下月对账
	BEGIN
		IF (@dzdays<29) OR (@dzdays IN(29,30) AND @nextMonth<>2) OR (@dzdays=31 AND @nextMonth IN(1,3,5,7,8,10,12))
		BEGIN
			SET @accountdate=convert(nvarchar(5),@BILLDATE,120)	+ CAST (@nextMonth AS VARCHAR(2))+'-'	+ CAST (@dzdays AS VARCHAR(2))		
		END
		ELSE IF (@dzdays=31 AND @nextMonth IN(4,6,9,11)) OR  (@dzdays IN(29,30,31) AND  @nextMonth=2)
		BEGIN
			SET @accountdate=CONVERT(CHAR(10),DATEADD(ms,-3,DATEADD(mm,DATEDIFF(m,0,@BILLDATE)+2,0)),120)  --最后一天
		END	
		--SET @accountdate=convert(nvarchar(5),@BILLDATE,120)	+ CAST (@nextMonth AS VARCHAR(2))+'-'	+ CAST (@dzdays AS VARCHAR(2))	
	END
	
	RETURN @accountdate--convert(nvarchar(10),@accountdate,120) 
    
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_ChangeToOriginalCurrency]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_ChangeToOriginalCurrency]
GO

/*
	用途：将凭证模板中金额来源记录的字段由本位币字段转换成原币字段，如果包含成本金额的算式，则0
*/

CREATE  FUNCTION F_ChangeToOriginalCurrency
(
	@Express	VARCHAR(MAX)
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	declare @s VARCHAR(MAX)
	,@a varchar(max)
	SET @a = ''
	SET @s = @Express
	SET	@s = replace(@s,'-',',-,')
	SET  @s = replace(@s,'+',',+,')
	SET  @s = replace(@s,'/',',/,')
	SET  @s = replace(@s,'*',',*,')
	SET  @s = replace(@s,'(','(,')
	SET  @s = replace(@s,')',',)')
	SET  @s = replace(@s,' ','')
	
	IF EXISTS( SELECT TOP 1 1 FROM f_split(@s,',') WHERE a = 'costtotal')
		SET @a = '0'
	ELSE
		SELECT @a+=CASE WHEN a NOT IN ('-','+','*','/','(',')') AND ISNUMERIC(a) = 0  THEN a+'for' ELSE a END from (SELECT a FROM f_split(@s,',') ) T

	RETURN @a
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE id = OBJECT_ID(N'[dbo].[F_ClearInvalidDecimal]') and xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_ClearInvalidDecimal]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
--清理小数后无效的0
CREATE FUNCTION dbo.F_ClearInvalidDecimal(@Value VARCHAR(50))
RETURNS VARCHAR(50)
BEGIN
	DECLARE @returnValue varchar(20)
	IF(@Value='')
	   SET @returnValue='' --空的时候为空
	ELSE IF (CHARINDEX('.',@Value) ='0')
	   SET @returnValue=@Value --针对不含小数点的
	ELSE IF ( SUBSTRING(REVERSE(@Value),PATINDEX('%[^0]%',REVERSE(@Value)),1)='.')
			  SET @returnValue =LEFT(@Value,LEN(@Value)-PATINDEX('%[^0]%',REVERSE(@Value))) --针对小数点后全是0的
		  ELSE
			  SET @returnValue =LEFT(@Value,LEN(@Value)- PATINDEX('%[^0]%.%',REVERSE(@Value))+1) --其他任何情形
	RETURN @returnValue
END

GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_Combine_PrintConfig]') and xtype in (N'FN', N'IF', N'TF'))
DROP function [dbo].[F_Combine_PrintConfig]
GO

/*
*	打印控制函数
*	2014.11.17
*/
CREATE FUNCTION   F_Combine_PrintConfig
(
	@Type   INT-- 1.addstate 2.savestate 3.passstate 4.savealert 5.passalert 6.printnum
)
RETURNS   varchar(8000)
AS
BEGIN
	DECLARE   @s   varchar(8000)
	IF @Type <> 6
	BEGIN
		SELECT   @s   =   
			ISNULL(@s,'')+ ',' + CAST(BillType AS VARCHAR(10))    
			FROM dbo.BillPrintConfig
			WHERE 
				(CASE WHEN @Type = 1 AND addState = 1  THEN 1
						WHEN @Type = 2 AND SaveState = 1 THEN 1
						WHEN @Type = 3 AND PassState = 1 THEN 1
						WHEN @Type = 4 AND SaveAlert = 1 THEN 1
						WHEN @Type = 5 AND PassAlert = 1 THEN 1
						ELSE 0 
				END) = 1
	END
	ELSE
	BEGIN
		SELECT   @s   =   
			ISNULL(@s,'')+ ',' + CAST(BillType AS VARCHAR(10)) + '=' + CAST(PrintNum AS VARCHAR(10))    
			FROM dbo.BillPrintConfig
	END
	RETURN	STUFF(@s,1,1, '')  
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_CommissionSchemeStype]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_CommissionSchemeStype]
GO

/*
	作者：杨俊
	日期：2014-8-21
	描述：提成方案分支机构纵向转横向
*/
CREATE FUNCTION F_CommissionSchemeStype
(
	@billnumberid VARCHAR(100),--单据ID
	@IsVisibleId INT = 0  --是否显示为ID
)
RETURNS NVARCHAR(100)
AS  
BEGIN  
DECLARE @S NVARCHAR(100) 
SELECT @S = ISNULL(@S+',','') + CASE @IsVisibleId   
         WHEN 0 THEN B.FullName   
         ELSE A.StypeID  
        END   
FROM CommissionSchemeStype AS A   
INNER JOIN SType AS B ON(A.StypeID = B.TypeId)  
WHERE A.BillNumberId = @BillNumberId 
RETURN @S
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_Ac_Account_UserCode]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_Ac_Account_UserCode]
GO

/*
	作者：谢吉康
	日期：2012-06-05
	描述：获取总账公式传入的AccountUserCode
	SELECT * FROM F_Get_Ac_Account_UserCode('600101-600102、500133、500101-500103')
*/
CREATE FUNCTION F_Get_Ac_Account_UserCode
(
	@ATypeId	VARCHAR(MAX)
)
RETURNS @AType TABLE(UserCode VARCHAR(MAX))
AS 
BEGIN

	DECLARE @Aid		VARCHAR(MAX),
			@i			INT,
			@j			INT	

	DECLARE Acursor CURSOR FOR
		SELECT * FROM f_split(@ATypeId,'、')
		
	OPEN Acursor

	FETCH NEXT FROM Acursor INTO @Aid

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF CHARINDEX('-',@Aid) > 0
		BEGIN
			SET @i = CAST(CAST(RIGHT(@Aid,CHARINDEX('-',@Aid)-1) AS INT) - CAST(LEFT(@Aid,CHARINDEX('-',@Aid)-1) AS INT) AS INT)
			SET @j = 0
			WHILE @j <= @i
			BEGIN			
				INSERT INTO @AType(UserCode)VALUES(LEFT(@Aid,CHARINDEX('-',@Aid)-1) + @j)		
				SET @j += 1
			END		
		END	
		ELSE 
			INSERT INTO @AType(UserCode)VALUES(@Aid)
			
		FETCH NEXT FROM Acursor INTO @Aid
	END

	CLOSE Acursor
	DEALLOCATE Acursor

	RETURN
END	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_Ac_Assist_CheckItems_Value]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_Ac_Assist_CheckItems_Value]
GO

/*
	作者：谢吉康
	日期：2012-06-05
	描述：获取总账公式传入的F_Get_Ac_Assist_CheckItems_Value
	SELECT * FROM F_Get_Ac_Assist_CheckItems_Value('分支机构=北京分公司,客户=测试客户')
*/
CREATE FUNCTION F_Get_Ac_Assist_CheckItems_Value
(
	@AssLists	VARCHAR(MAX)
)
RETURNS @Assists TABLE(Ascids INT,UserCode VARCHAR(200),FieldValue VARCHAR(MAX))
AS 
BEGIN
	DECLARE @Aid			VARCHAR(MAX),
		@i				INT,
		@j				INT,		
		@BaseType		VARCHAR(50),
		@BaseTypeValue	VARCHAR(500),
		@TableName		VARCHAR(100),
		@Sql			VARCHAR(MAX),
		@Ascids			INT,
		@UserCode		VARCHAR(200),
		@FieldValue		VARCHAR(MAX)
	
	DECLARE Acursor CURSOR FOR
		SELECT * FROM f_split(@AssLists,'%')
		
	OPEN Acursor

	FETCH NEXT FROM Acursor INTO @Aid

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF CHARINDEX('=',@Aid) > 0
		BEGIN
			SET @BaseType = LEFT(@Aid,CHARINDEX('=',@Aid)-1)
			SET @BaseTypeValue = RIGHT(@Aid,LEN(@Aid)-CHARINDEX('=',@Aid))		
			SELECT @Ascids = Ascids,@UserCode=UserCode FROM Ac_Assist_CheckItems WHERE FullName = @BaseType
			SET @FieldValue = '9999';--如果输入错误,赋值为永不可能编码
			IF @BaseType = '分支机构'
				BEGIN
					IF @BaseTypeValue = '全部'
						BEGIN
							SET @FieldValue = ''
						END
					ELSE
						BEGIN
							SELECT @FieldValue = TypeId FROM SType WHERE UserCode = @BaseTypeValue	
						END	
				END
			ELSE IF @BaseType = '往来单位'	
				BEGIN	 
					IF @BaseTypeValue = '全部'
						BEGIN
							SET @FieldValue = ''
						END
					ELSE
						BEGIN
							SELECT @FieldValue = TypeId FROM BType WHERE UserCode = @BaseTypeValue
						END	
				END
			ELSE IF @BaseType = '部门'	
				BEGIN
					IF @BaseTypeValue = '全部'
						BEGIN
							SET @FieldValue = ''
						END
					ELSE
						BEGIN
							SELECT @FieldValue = TypeId FROM Department WHERE UserCode = @BaseTypeValue			
						END	
				END
			ELSE IF @BaseType = '职员'
				BEGIN	
					IF @BaseTypeValue = '全部'
						BEGIN
							SET @FieldValue = ''
						END
					ELSE
						BEGIN
							SELECT @FieldValue = TypeId FROM Employee WHERE UserCode = @BaseTypeValue		
						END
				END
			ELSE
				BEGIN	
					IF @BaseTypeValue = '全部'
						BEGIN
							SET @FieldValue = ''
						END
					ELSE
						BEGIN
							SELECT @FieldValue = TypeId FROM Ac_Assist_CheckItemsDetail WHERE UserCode = @BaseTypeValue		
						END
				END					
				
			INSERT INTO @Assists(Ascids,FieldValue,UserCode)VALUES(@Ascids,ISNULL(@FieldValue,''),@UserCode)
		END			
			
		FETCH NEXT FROM Acursor INTO @Aid
	END

	CLOSE Acursor
	DEALLOCATE Acursor

	RETURN
END	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_AccountAscids]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_AccountAscids]
GO

/*
	用途：根据Ac_Account_Assist_CheckItems表获得科目的辅助核算组合特征值，用于比对
*/

CREATE  FUNCTION F_Get_AccountAscids
(
	@atypeid	VARCHAR(50),
	@stypeid	VARCHAR(50),
	@Cid		INT
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(MAX)
	SET @sql = ''
	SELECT @sql=@sql+CAST(ascids AS varchar(10))+',' 
		FROM dbo.Ac_Account_Assist_CheckItems
		WHERE ATypeId = @atypeid AND STypeId = @stypeid AND Cid = @cid
		ORDER BY Ascids
	RETURN @sql
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_AllAtypeids]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_AllAtypeids]
GO

/*
	用途：将所有会计科目typied拼接成一串，用于固定资产初始时自动分配科目使用
*/

CREATE  FUNCTION F_Get_AllAtypeids
(
	@SubId	INT
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(MAX)
	SET @sql = ''
	SELECT @sql=@sql+ CAST(typeid AS VARCHAR(50)) + ','
		FROM Ac_Account_Set_Detail WHERE SubId = @SubId
	RETURN @sql
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_AscidInfoByAscids]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_AscidInfoByAscids]
GO

/*
	用途：将Ac_Voucher_Bill_Assist_CheckItems辅助核算组合用于比对
*/

CREATE  FUNCTION F_Get_AscidInfoByAscids
(
	@Ascids	VARCHAR(500),
	@Ascid	INT,
	@type	INT -- 0.返回typeid， 1.返回fullname
)
RETURNS varchar(500) 
AS  
BEGIN 
	IF @Ascid = 0 OR @Ascids = ''
	BEGIN
		RETURN ''
	END
	
	DECLARE @_result VARCHAR(500)
			,@_ascids	VARCHAR(500)
			,@_ascid	VARCHAR(10)
			,@_startIndex	INT
			,@_endIndex	INT
			
	SET @_result = ''
	SET @_ascids = ''
	SET @_ascid =','+ CAST(@Ascid AS VARCHAR) + ':'
	SET @_startIndex = 0
	SET @_endIndex = 0
	
	SET @_ascids = REPLACE(','+@Ascids,@_ascid,'Я')
	SET @_startIndex = CHARINDEX('Я',@_ascids,1)
	SET @_endIndex = CHARINDEX(',',@_ascids,@_startIndex+1)
	SET @_result = SUBSTRING(@_ascids,@_startIndex+1,@_endIndex-1-@_startIndex)
	
	IF @type = 1
	BEGIN
		IF @Ascid = 1
			SELECT	@_result = FullName 
			FROM	SType
			WHERE	TypeId = @_result
		ELSE IF @Ascid = 2
			SELECT	@_result = FullName 
			FROM	Department
			WHERE	TypeId = @_result
		ELSE IF @Ascid = 3
			SELECT	@_result = FullName 
			FROM	employee
			WHERE	TypeId = @_result
		ELSE IF @Ascid = 4
			SELECT	@_result = FullName 
			FROM	btype
			WHERE	TypeId = @_result
		ELSE 
			SELECT	@_result = FullName 
			FROM	Ac_Assist_CheckItemsDetail
			WHERE	TypeId = @_result
				AND	AscIds = @Ascid
	END
	
	RETURN @_result
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_BalanceAccountAscids]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_BalanceAccountAscids]
GO

/*
	用途：将Ac_Balance_Assist_CheckItems_Detail的辅助核算组合用于比对
*/

CREATE  FUNCTION F_Get_BalanceAccountAscids
(
	@atypeid	VARCHAR(50),
	@cid		INT,
	@fyear		INT,
	@fperiod	INT,
	@initotal	 NUMERIC(24, 10) 
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(MAX)
	SET @sql = ''
	
	SELECT @sql=@sql+CAST(Ascids AS varchar(10))+':'+FieldValue+',' 
	FROM dbo.Ac_Balance_Assist_CheckItems_Detail
	WHERE FYear = @fyear AND FPeriod = @fperiod AND Cid = @cid AND ATypeId = @atypeid AND IniTotal = @initotal
	ORDER BY AscIds
		
	RETURN @sql
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_Get_FreeItem_ValueID]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_Get_FreeItem_ValueID]
GO

/*
	Create by: Haiyang, Li
	Date: 2012-08-02
	Description: 期初导入, 根据传入自由项值名称, id等获取值id
*/


CREATE FUNCTION [dbo].[F_Get_FreeItem_ValueID]
    (
      @itemId BIGINT ,
      @valueName VARCHAR(256) ,
      @isCombined BIT 
    )
RETURNS INT
AS 
    BEGIN
        DECLARE @valueId INT
        SET @valueId = -99999

        SELECT  @valueId = A.valueId
        FROM    ( SELECT    itemsid AS itemId ,
                            id AS valueId ,
                            REPLACE(fullname, 'я', '/') AS valueName ,
                            1 AS isCombined
                  FROM      dbo.CustomReferenceValue
                  UNION ALL
                  SELECT    DataTypeId AS itemId ,
                            _Id AS valueId ,
                            fullname AS valueName ,
                            0 AS isCombined
                  FROM      xw_SelfData
                ) A
        WHERE   A.itemId = @itemId
                AND A.isCombined = @isCombined
                AND A.valueName = @valueName

 
        RETURN  @valueId
    END

GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_IniAccountAscids]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_IniAccountAscids]
GO

/*
	用途：将Ac_IniAccount_Assist_CheckItems_Detail的辅助核算组合用于比对
*/

CREATE  FUNCTION F_Get_IniAccountAscids
(
	@atypeid	VARCHAR(50),
	@groupid	INT,
	@cid		INT,
	@stypeid	VARCHAR(50)
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(MAX)
	SET @sql = ''
	SELECT @sql=@sql+CAST(ascids AS varchar(10))+':'+fieldvalue+',' 
	FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail 
	WHERE ATypeId = @atypeid AND GroupId = @groupId AND Cid = @cid AND STypeId = @stypeid
	RETURN @sql
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_VoucherAscids]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_VoucherAscids]
GO

/*
	用途：将Ac_Voucher_Bill_Assist_CheckItems辅助核算组合用于比对
*/

CREATE  FUNCTION F_Get_VoucherAscids
(
	@id		INT,
	@type	INT -- 1.带具体typeid，如1：00001，2：00003， 2.只分类，如： 1，2，
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(MAX)
	SET @sql = ''
	IF @type = 1
	BEGIN
		SELECT @sql=@sql+CAST(b.ascids AS varchar(10))+':'+typeid+',' 
		FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
			INNER JOIN dbo.Ac_Assist_CheckItems b ON a.typeName = b.UserCode
		WHERE a.vBId = @id
		ORDER BY b.AscIds
	END
	IF @type = 2
	BEGIN
		SELECT @sql=@sql+CAST(b.ascids AS varchar(10))+',' 
		FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
			INNER JOIN dbo.Ac_Assist_CheckItems b ON a.typeName = b.UserCode
		WHERE a.vBId = @id
		ORDER BY b.AscIds
	END
	
	RETURN @sql
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_VoucherAscidsItem]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_VoucherAscidsItem]
GO

/*
	用途：将Ac_Voucher_Bill_Assist_CheckItems辅助核算组合用于比对
*/

CREATE  FUNCTION F_Get_VoucherAscidsItem
(
	@ascids varchar(1000)=''
)
RETURNS varchar(100) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(100)
	SET @sql = ''
	SELECT @sql=@sql+LEFT(a,1)+',' from f_split(@ascids,',')
	
	RETURN @sql
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAc_Assist_CheckItems_FullName]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAc_Assist_CheckItems_FullName]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		李灏龙
-- Create date: 2012年5月14日12:17:54
-- Description:	获取核算项目名称

-- =============================================

CREATE FUNCTION dbo.F_GetAc_Assist_CheckItems_FullName(@atypeid VARCHAR(200),@stypeid VARCHAR(200))
RETURNS VARCHAR(2000)
WITH EXECUTE AS caller
AS
BEGIN
	DECLARE @Str VARCHAR(2000)
	SET @Str = ''
	SELECT	@Str += '/' + x.FullName
	FROM (
			SELECT  DISTINCT b.FullName
			FROM	Ac_Account_Assist_CheckItems a
					INNER JOIN Ac_Assist_CheckItems b ON a.Ascids = b.AscIds
			WHERE	a.ATypeId = @atypeid
					AND A.STypeId = @stypeid
		) x
	SELECT @Str = RIGHT(@Str,LEN(@Str)-1) WHERE @Str != ''
	RETURN @Str
END
GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAc_Assist_CheckItems_Str]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAc_Assist_CheckItems_Str]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		李灏龙
-- Create date: 2012年5月30日12:59:46
-- Description:	获取辅助核算字符串

-- =============================================

CREATE FUNCTION dbo.F_GetAc_Assist_CheckItems_Str(@billnumberid VARCHAR(2000),@rowno VARCHAR(200),@OperatorId VARCHAR(200)='00001',@assistcontrol INT=1)
RETURNS VARCHAR(2000)
WITH EXECUTE AS caller
AS
BEGIN
	DECLARE @Str VARCHAR(2000)
	SET @Str = ''
	SELECT	@str +='【'+aa.Fullname+'】：'+
			CASE avb.typeName
			WHEN '01' THEN 
			(
				--CASE WHEN @OperatorId<>'00001' AND
				--NOT EXISTS(SELECT 1 FROM F_AllTreeS(@OperatorId) WHERE typeid=avb.TypeId) AND @assistcontrol=0 THEN '****'
				--ELSE
				--(
					SELECT FullName FROM SType WHERE TypeId = avb.TypeId
				--)END
			)
			WHEN '02' THEN 
			(
				--CASE WHEN @OperatorId<>'00001' AND
				--NOT EXISTS(SELECT 1 FROM F_LineD(@OperatorId) WHERE typeid=avb.TypeId) AND @assistcontrol=0 THEN '****'
				--ELSE
				--(
			
					SELECT FullName FROM Department WHERE TypeId = avb.TypeId
				--)END
			)
			WHEN '03' THEN 
			(
				--CASE WHEN @OperatorId<>'00001' AND
				--NOT EXISTS(SELECT 1 FROM F_LineE(@OperatorId) WHERE typeid=avb.TypeId) AND @assistcontrol=0 THEN '****'
				--ELSE
				--(
					SELECT FullName FROM employee WHERE TypeId = avb.TypeId
				--)END
			)
			WHEN '04' THEN 
			(
				--CASE WHEN @OperatorId<>'00001' AND
				--NOT EXISTS (SELECT 1 FROM F_LineB(@OperatorId) where typeid=avb.TypeId) AND @assistcontrol=0 THEN '****'
				--ELSE 
				--(
					SELECT FullName FROM BType b WHERE b.TypeId = avb.TypeId  
				--)END
			)
			ELSE 
			(
				ISNULL((SELECT FULLNAME FROM Ac_Assist_CheckItemsDetail WHERE TYPEID=AVB.TYPEID),'')
			) 
			END + '；'
	FROM	Ac_Assist_CheckItems aa
			LEFT JOIN Ac_Voucher_Bill_Assist_CheckItems avb ON aa.UserCode = avb.typeName
			LEFT JOIN Ac_Voucher_Bill av ON avb.BillNumberId = av.BillNumberId AND avb.vBId = av.ID
	WHERE	av.BillNumberId = @billnumberid and RowNo = @rowno
	
	SELECT @Str = LEFT(@Str,LEN(@Str)-1) WHERE @Str != ''
	RETURN @Str
END
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetAcacountIsUsed]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[F_GetAcacountIsUsed]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
--==================================================
--date: 2015-11-12
--by:glj
--fucntion:判断会计科目是否使用 凭证和财务期初
--=================================================
CREATE  FUNCTION F_GetAcacountIsUsed
(
	@STypeId		VARCHAR(50),	--分支机构
	@ATypeId		VARCHAR(50)		--科目
)
RETURNS INT 
--@Encode$--
AS
BEGIN
--科目辅助核算余额表
IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE STypeId=@STypeID AND ATypeId=@ATypeID)
	RETURN 1
--科目余额表
IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE STypeId=@STypeID AND ATypeId=@ATypeID AND (FBeginBalanceFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYtdDebitFor<>0 OR FYtdCreditFor<>0 OR FEndBalanceFor<>0 OR FBeginBalance<>0 OR FDebit<>0 OR FCredit<>0 OR FYtdDebit<>0 OR FYtdCredit<>0 OR FEndBalance<>0 OR FBeginqty<>0  OR FDebitqty<>0 OR FCreditqty<>0 OR FYtdDebitqty<>0 OR FYtdCreditqty<>0 OR FEndqty<>0))
	RETURN 1
--账务期初辅助核算表
IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId=@STypeID AND ATypeId=@ATypeID)
	RETURN 1
--期初表
IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount WHERE STypeId=@STypeID AND ATypeId=@ATypeID AND(iniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FYTotal<>0  OR iniYTotal<>0 OR iniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYTotalFor<>0 OR iniYTotalFor<>0 OR iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0 OR FYTotalDebit<>0 OR FYTotalCredit<>0 OR FYTotalDebitFor<>0 OR FYTotalCreditFor<>0))
	RETURN 1
--凭证
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher V INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.IfCheck='f' AND V.STypeId=@STypeID AND B.ATypeId=@ATypeID)
	RETURN 1
	
RETURN 0
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllManagerBaseByTypeId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllManagerBaseByTypeId]
GO

/*
	作者：谢吉康
	日期：2010-07-15
	描述：获取基本信息的节点ID，带了权限范围
*/
CREATE  FUNCTION F_GetAllManagerBaseByTypeId
(
	@TypeId			VARCHAR(MAX)='',	--需要拆分的基本信息ID
	@Flag			INT=0,			--基本信息的标识 1.商品 2.往来单位 3.职员等
	@OperatorId		VARCHAR(100)='',	--当前操作员的ID
	@StypeId		VARCHAR(50)=''		--分支机构	
)	
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)

	DECLARE @BaseTypeId		varchar(100)

	IF @Flag = 1			--商品
		BEGIN	
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.TypeId 
			FROM 	F_GetManDetailPType(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.TypeId =B.A
		END
	ELSE IF @Flag = 2		--往来单位
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.TypeId 
			FROM 	F_GetManDetailBType(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.TypeId like B.A +'%' 
		END
	ELSE IF @Flag = 3		--职员
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.TypeId 
			FROM 	F_GetManDetailEType(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.TypeId like B.A +'%' 
		END
	ELSE IF @Flag = 4		--仓库
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.TypeId 
			FROM 	F_GetManDetailKType(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.TypeId = B.A 
				
		END
	ELSE IF @Flag = 5		--现金银行
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.nTypeId 
			FROM 	F_GetManDetailAllAType(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.nTypeId =B.A 
		
	END
	ELSE IF @Flag = 6		--费用
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.nTypeId 
			FROM 	F_GetManDetailAllATypeFy(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.nTypeId = B.A
				
		END
	ELSE IF @Flag = 7		--收入
		BEGIN 
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.nTypeId 
			FROM 	F_GetManDetailAllATypeSr(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.nTypeId = B.A 
		END
	ELSE IF @Flag = 8		--资产
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.nTypeId 
			FROM 	F_GetManDetailAllATypeZc(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.nTypeId =B.A
				
		END
	ELSE IF @Flag = 9		--部门
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.TypeId 
			FROM 	F_GetManDetailAllDType(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.TypeId like  B.A+'%'					
		END
	ELSE IF @Flag = 10		--地区
		BEGIN
		INSERT INTO @Temp(TypeId)
		SELECT 	DISTINCT A.TypeId 
		FROM 	AreaType A, 
				(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
		WHERE	A.TypeId=B.A
				AND A.SonNum = 0
		END
	ELSE IF @Flag = 11			--分支机构
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	DISTINCT A.TypeId 
			FROM 	F_GetManDetailAllSType(@OperatorId) A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.TypeId like B.A +'%'
		END
	ELSE IF @Flag = 15			--凭证字
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	A.VgId 
			FROM 	Ac_Voucher_Group A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.VgId = B.A 					
		END
	ELSE IF @Flag = 16			--币别
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	A.CId 
			FROM 	Ac_Currency A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.CId =B.A 				
		END	
	ELSE IF @Flag = 18			--总账会计科目
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	A.TypeId 
			FROM 	Ac_Account A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.TypeId=B.A
					AND A.SonNum = 0
					AND A.StypeId=@StypeId								
		END										

	RETURN
END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllStype]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllStype]
GO

--得到分支机构字符串(一个字段) 的函数
--针对价格表和价格规则
--date    :2013-05-13
CREATE FUNCTION F_GetAllStype
(
	@ID				NUMERIC(18,0),
	@TableName		VARCHAR(100)
)
RETURNS VARCHAR(MAX)
AS 
BEGIN
	DECLARE @NUM INT = 0
	
	IF @TableName = 'PriceBillIndex_Stype'
		SELECT @NUM = COUNT(1) FROM PriceBillIndex_Stype WHERE PriceBillIndexID = @ID
	ELSE IF @TableName = 'PriceRule_Stype'
		SELECT @NUM = COUNT(1) FROM PriceRule_Stype WHERE PriceRuleID = @ID
	ELSE 
		SET @NUM = 0
	
    DECLARE @Result  VARCHAR(MAX)=''
    
    IF @TableName = 'PriceBillIndex_Stype'
		SELECT top 3 @Result=@Result+S.FullName+',' 
		FROM PriceBillIndex_Stype P INNER JOIN SType S ON S.TypeId = P.StypeID  
		WHERE P.PriceBillIndexID = @ID
		ORDER BY P.ID
	ELSE IF @TableName = 'PriceRule_Stype'
		SELECT top 3 @Result=@Result+S.FullName+',' 
		FROM PriceRule_Stype P INNER JOIN SType S ON S.TypeId = P.StypeID  
		WHERE P.PriceRuleID = @ID
	
	IF @NUM >= 4
		 SET @Result = SUBSTRING(@Result,1,LEN(@Result) - 1) +'...'
	ELSE
		SET @Result = SUBSTRING(@Result,1,LEN(@Result) - 1)
		
	RETURN @Result
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS(SELECT * FROM dbo.sysobjects WHERE name='F_GetAssistCheckItemsName')
	DROP FUNCTION [dbo].[F_GetAssistCheckItemsName]
GO          
-- ========================================================================
-- 描述：	返回科目辅助拼凑名称
-- 时间：	2012-05-30
-- 作者：	古丽娟
-- ========================================================================
CREATE FUNCTION [dbo].[F_GetAssistCheckItemsName]
(
	@ID			INT,			--分录号
	@operatorid	VARCHAR(50),	--操作员ID
	@StypeId	VARCHAR(50)
)
RETURNS VARCHAR(MAX)
AS 
BEGIN
	
	DECLARE 
		@RetStr			VARCHAR(MAX)='',
		@AssistLimit	INT
		
	
	SELECT @AssistLimit=SUBSTRING(lim,4690,1) FROM loginuser WHERE etypeid=@operatorid
	
	--分支机构01
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='01' AND vBId=@ID)
		BEGIN
			--SELECT @RetStr+=',【'+I.FullName+'】：'+CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN exists(select * from dbo.F_GetAllManagerBaseByTypeId(Detail.TypeId,11,@operatorid,@StypeId)) THEN Detail.FullName ELSE '****' END END
			SELECT @RetStr+=',【'+I.FullName+'】：'+Detail.FullName
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON C.typeName='01' AND C.typeName=I.UserCode AND C.vBId=@ID
			INNER JOIN SType Detail ON Detail.TypeId=C.TypeId
			--LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',11,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
		END
	--部门02
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='02' AND vBId=@ID)
		BEGIN
			--SELECT @RetStr+=',【'+I.FullName+'】：'+CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN exists(select * from dbo.F_GetAllManagerBaseByTypeId(Detail.TypeId,9,@operatorid,@StypeId)) THEN Detail.FullName ELSE '****' END END
			SELECT @RetStr+=',【'+I.FullName+'】：'+Detail.FullName
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON C.typeName='02' AND C.typeName=I.UserCode AND C.vBId=@ID
			INNER JOIN Department Detail ON Detail.TypeId=C.TypeId
			--LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',9,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
		END
	--职员
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='03' AND vBId=@ID)
		BEGIN
			--SELECT @RetStr+=',【'+I.FullName+'】：'+CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN exists(select * from dbo.F_GetAllManagerBaseByTypeId(Detail.TypeId,3,@operatorid,@StypeId)) THEN Detail.FullName ELSE '****' END END
			SELECT @RetStr+=',【'+I.FullName+'】：'+Detail.FullName
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON C.typeName='03' AND C.typeName=I.UserCode AND C.vBId=@ID
			INNER JOIN employee Detail ON Detail.TypeId=C.TypeId
			--LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',3,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
		END
	--往来单位
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='04' AND vBId=@ID)
		BEGIN
			--SELECT @RetStr+=',【'+I.FullName+'】：'+CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN exists(select * from dbo.F_GetAllManagerBaseByTypeId(Detail.TypeId,2,@operatorid,@StypeId)) THEN Detail.FullName ELSE '****' END END
			SELECT @RetStr+=',【'+I.FullName+'】：'+Detail.FullName
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON C.typeName='04' AND C.typeName=I.UserCode AND C.vBId=@ID
			INNER JOIN BType Detail ON Detail.TypeId=C.TypeId
			
			--SELECT @RetStr+=',【'+I.FullName+'】：'+CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END END
			--FROM Ac_Voucher_Bill_Assist_CheckItems C
			--INNER JOIN Ac_Assist_CheckItems I ON C.typeName='04' AND C.typeName=I.UserCode AND C.vBId=@ID
			--INNER JOIN BType Detail ON Detail.TypeId=C.TypeId
			--LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',2,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
		END
	--自定义辅助核算	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName>'04' AND vBId=@ID)
		BEGIN
			DECLARE
				@I INT=1,
				@J INT,
				@AscIds INT
			DECLARE @Temp TABLE(NID INT IDENTITY(1,1),AscIds INT,TypeName VARCHAR(200),FullName VARCHAR(200),DTypeID VARCHAR(50))
			INSERT INTO @Temp(AscIds,TypeName,FullName,DTypeID)
			SELECT
				I.AscIds,
				I.UserCode,
				I.FullName,
				C.TypeId
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON I.UserCode=C.typeName AND C.typeName>'04' AND C.vBId=@ID
			
			SELECT @J=@@ROWCOUNT
			WHILE(@I<=@J)
				BEGIN
					SELECT @AscIds=AscIds FROM @Temp WHERE NID=@I
					SELECT 
						@RetStr+=',【'+C.FullName+'】：'+Detail.FullName
					FROM @Temp C
					INNER JOIN Ac_Assist_CheckItemsDetail Detail ON Detail.TypeId=C.DTypeID AND Detail.AscIds=C.AscIds AND Detail.AscIds=@AscIds
					SET @I+=1
				END
		END
	RETURN SUBSTRING(@RetStr,2,LEN(@RetStr))	
END 		
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS(SELECT 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetAtypeFullName]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[F_GetAtypeFullName]
GO

--==========================================
--CreatedBy:	GLJ
--Date:			2012-11-06	
--Description:	凭证会计科目信息，需显示科目编号和科目名称和核算项目编号及名称，
--				科目需逐级显示，核算项目按分支机构、往来单位、部门、职员的顺序进行显示
--==========================================
CREATE FUNCTION F_GetAtypeFullName
(
	@ID				INT,			--凭证ID
	@AtypeID		VARCHAR(50),	--科目ID
	@StypeId		VARCHAR(50),	--凭证分支机构
	@OperatorID		VARCHAR(50)		--操作员ID
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
	DECLARE @RET NVARCHAR(MAX)='',@ItemName VARCHAR(MAX)=''
	
	;WITH TEMPRESULT AS
	(
	 SELECT ParID,TypeID
	 FROM Ac_Account 
	 WHERE typeId=@AtypeID AND StypeId=@StypeId
	 UNION ALL
	 SELECT a.ParID,a.TypeID
	 FROM Ac_Account a
	 INNER JOIN TEMPRESULT b ON a.typeId=b.ParId 
	 WHERE a.ParId<>'00000' AND a.StypeId=@StypeId
	)
	--得到科目编号+科目名称
	SELECT @RET+=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE A.UserCode END
				+'-'
				+CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE A.FullName END
				+'->' 
	FROM TEMPRESULT T
	INNER JOIN Ac_Account A ON A.TypeId=T.TypeId AND A.StypeId=@StypeId
	LEFT JOIN F_TreeAccount(@OperatorID,@StypeId) F ON F.TypeId=A.TypeId AND F.StypeId=A.StypeId
	ORDER BY A.TypeId
	IF(@RET<>'')
		SET @RET=SUBSTRING(@RET,1,LEN(@RET)-2)
	--辅助核算
	SET @ItemName=dbo.F_GetAssistCheckItemsName(@ID,@OperatorID,@StypeId)
	IF(@ItemName<>'')
		SET @RET+='('+@ItemName+')'
	RETURN @RET
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetAtypeFullNameNew]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[F_GetAtypeFullNameNew]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--==========================================
--CreatedBy:	GLJ
--Date:			2012-11-06	
--Description:	凭证会计科目信息，需显示科目编号和科目名称和核算项目编号及名称，
--				科目需逐级显示，核算项目按分支机构、往来单位、部门、职员的顺序进行显示

--调整：刘飞 2016-12-02 会计凭证连续打印，自定义辅助核算查询调整
--==========================================
CREATE FUNCTION F_GetAtypeFullNameNew
(
	@ID				INT,			--凭证ID
	@AtypeID		VARCHAR(50),	--科目ID
	@StypeId		VARCHAR(50),	--凭证分支机构
	@OperatorID		VARCHAR(50)		--操作员ID
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
	DECLARE 
		@RET			VARCHAR(MAX)='',
		@ItemName		VARCHAR(MAX)='',
		@AssistLimit	INT--是否受权限控制

	SELECT @AssistLimit=SUBSTRING(lim,4690,1) FROM loginuser WHERE etypeid=@operatorid

	;WITH TEMPRESULT AS
	(
	 SELECT ParID,TypeID
	 FROM Ac_Account 
	 WHERE typeId=@AtypeID AND StypeId=@StypeId
	 UNION ALL
	 SELECT a.ParID,a.TypeID
	 FROM Ac_Account a
	 INNER JOIN TEMPRESULT b ON a.typeId=b.ParId 
	 WHERE a.ParId<>'00000' AND a.StypeId=@StypeId
	)
	--得到科目编号+科目名称
	SELECT @RET+=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE A.UserCode END
				+'-'
				+CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE A.FullName END
				+'->' 
	FROM TEMPRESULT T
	INNER JOIN Ac_Account A ON A.TypeId=T.TypeId AND A.StypeId=@StypeId
	LEFT JOIN F_TreeAccount(@OperatorID,@StypeId) F ON F.TypeId=A.TypeId AND F.StypeId=A.StypeId
	ORDER BY A.TypeId
	
	IF(@RET<>'')
		SET @RET=SUBSTRING(@RET,1,LEN(@RET)-2)
		
	--辅助核算
	--分支机构01
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='01' AND vBId=@ID)
		BEGIN
			SELECT @ItemName+=CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END END+';'
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON C.typeName='01' AND C.typeName=I.UserCode AND C.vBId=@ID
			INNER JOIN SType Detail ON Detail.TypeId=C.TypeId
			LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',11,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
		END
	--部门02
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='02' AND vBId=@ID)
		BEGIN
			SELECT @ItemName+=CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END END+';'
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON C.typeName='02' AND C.typeName=I.UserCode AND C.vBId=@ID
			INNER JOIN Department Detail ON Detail.TypeId=C.TypeId
			LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',9,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
		END
	--职员
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='03' AND vBId=@ID)
		BEGIN
			SELECT @ItemName+=CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END END+';'
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON C.typeName='03' AND C.typeName=I.UserCode AND C.vBId=@ID
			INNER JOIN employee Detail ON Detail.TypeId=C.TypeId
			LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',3,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
		END
	--往来单位
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='04' AND vBId=@ID)
		BEGIN
			SELECT @ItemName+=CASE WHEN @AssistLimit=0 THEN Detail.FullName ELSE CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END END+';'
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON C.typeName='04' AND C.typeName=I.UserCode AND C.vBId=@ID
			INNER JOIN BType Detail ON Detail.TypeId=C.TypeId
			LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',2,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
		END
	--自定义辅助核算	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE CAST(typeName AS INT)>4 AND vBId=@ID)
		BEGIN

			SELECT @ItemName+=D.FullName+';'
			FROM Ac_Voucher_Bill_Assist_CheckItems C
			INNER JOIN Ac_Assist_CheckItems I ON I.UserCode=C.typeName 
			INNER JOIN Ac_Assist_CheckItemsDetail D ON D.TypeId=C.TypeId
			WHERE CAST(typeName AS INT)>4 AND C.vBId=@ID
		END
		
	--返回辅助核算字符字符串
	IF(ISNULL(@ItemName,'')<>'')
		SET @RET+='('+SUBSTRING(@ItemName,1,LEN(@ItemName)-1)+')'
	RETURN @RET
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetCostPrice]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetCostPrice]
GO



/*
	先取库存成本价,如果为负数,0或无,则取最近进价
*/

CREATE FUNCTION F_GetCostPrice
(
	@strSTypeID			VARCHAR(50),
	@strPTypeID			VARCHAR(50),
	@strKTypeID			VARCHAR(50)
)
--@Encode$--
RETURNS   NUMERIC(24, 10) 
AS
BEGIN
	DECLARE
		@decPrice		 NUMERIC(24, 10) ,
		@intCosting		 INT,
		@intPriceDot	 INT
		
	SELECT
		@intCosting=ISNULL(SubValue,0)
	FROM sysdata
	WHERE SubName='costing'
	
	SELECT	@intPriceDot = DecimalDigit
	FROM	dbo.DigitConfiguration
	WHERE	ItemId=2  --价格
		
	SELECT @decPrice=0
	
	IF EXISTS(
		SELECT PTypeID 
		FROM GOODSSTOCKS
		WHERE PTypeID=@strPTypeID
		AND KtypeId=@strKTypeID
	)
	BEGIN
		IF @intCosting=0
		BEGIN
			SELECT @decPrice=Price
			FROM GOODSSTOCKS
			WHERE PTypeID=@strPTypeID
			AND KtypeId=@strKTypeID
		END
		ELSE
		BEGIN
			SELECT @decPrice=CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(Total) AS NUMERIC(22,10))/CAST(SUM(Qty) AS NUMERIC(22,10)),@intPriceDot) END
			FROM GOODSSTOCKS
			WHERE PTypeID=@strPTypeID
			AND KtypeId=@strKTypeID
		END
	END

	IF @decPrice<=0 AND EXISTS(
		SELECT ISNULL(RecPrice,0)
		FROM PType_STypePrice
		WHERE STypeID=@strSTypeID
		AND PTypeID=@strPTypeID
	)
	BEGIN
		SELECT @decPrice=ISNULL(RecPrice,0)
		FROM PType_STypePrice
		WHERE STypeID=@strSTypeID
		AND PTypeID=@strPTypeID
	END
	
	RETURN @decPrice
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetCustomAssist]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].F_GetCustomAssist
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能：获取自定义辅助数量  注意: 请和单据GridCalcRunner_New.cs 中的SetAssistantUnitSpecial 这个方法保持一致
-- 作者：蒋奎  
-- 时间：2015-08-06
-- ========================================================================
CREATE  FUNCTION  F_GetCustomAssist
(
	@ptypeid		VARCHAR(MAX), 
	@qty			NUMERIC(24,10) 
)
RETURNS VARCHAR(MAX) 
AS  
BEGIN 

	IF EXISTS(SELECT TOP 1 1 FROM dbo.ptype WHERE Typeid=@ptypeid AND sonnum<>0)
		RETURN ''
	DECLARE @fullname1 VARCHAR(200),@fullname2 VARCHAR(200),@fullname3 VARCHAR(200)
	DECLARE @rate1 NUMERIC(24,10),@rate2 NUMERIC(24,10),@rate3 NUMERIC(24,10)
	
	DECLARE @PType_AuxiliaryUnits_Ext TABLE
	(
		ptypeid			VARCHAR(50),
		SaleUnitID1		NUMERIC(24,10),
		SaleUnitID2		NUMERIC(24,10),
		SaleUnitID3		NUMERIC(24,10),
		SaleUnitRate1	NUMERIC(24,10),
		SaleUnitRate2	NUMERIC(24,10),
		SaleUnitRate3	NUMERIC(24,10)
	)
	INSERT INTO @PType_AuxiliaryUnits_Ext
    ( 
		ptypeid,
		SaleUnitID1 ,
		SaleUnitID2 ,
		SaleUnitID3 ,
		SaleUnitRate1 ,
		SaleUnitRate2 ,
		SaleUnitRate3
    )
    SELECT	PTypeID,
			SaleUnitID1 ,
			SaleUnitID2 ,
			SaleUnitID3 ,
			SaleUnitRate1 ,
			SaleUnitRate2 ,
			SaleUnitRate3
	FROM	PType_AuxiliaryUnits_Ext
	WHERE	PTypeID=@ptypeid
	
	SELECT	@fullname1=fullname 
	FROM	PType_Units pu
	INNER JOIN @PType_AuxiliaryUnits_Ext PA ON pu.UnitsId = pa.SaleUnitID1
	
	SELECT	@fullname2=fullname 
	FROM	PType_Units pu
	INNER JOIN @PType_AuxiliaryUnits_Ext PA ON pu.UnitsId = pa.SaleUnitID2	

	SELECT	@fullname3=fullname 
	FROM	PType_Units pu
	INNER JOIN @PType_AuxiliaryUnits_Ext PA ON pu.UnitsId = pa.SaleUnitID3	

    SELECT @rate1=SaleUnitRate1,@rate2=SaleUnitRate2,@rate3=SaleUnitRate3 from @PType_AuxiliaryUnits_Ext where PTypeID=@ptypeid

	/*
	SELECT @fullname1=fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=@ptypeid) 
	SELECT @fullname2=fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=@ptypeid) 
	SELECT @fullname3=fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=@ptypeid) 
    SELECT @rate1=SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=@ptypeid
	SELECT @rate2=SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=@ptypeid  
    SELECT @rate3=SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=@ptypeid  
    */

	DECLARE @tempqty NUMERIC(24,10) 
	SET @tempqty=CONVERT(NUMERIC(24,10), ABS(@qty)) --四舍五入
	
	DECLARE @customassistantunit VARCHAR(MAX)=''
	--是否有自定义单位
	IF	(@fullname1 IS NULL OR @rate1=0 )
	BEGIN
		SET @customassistantunit=''
	END
	ELSE
	BEGIN
		DECLARE @onetemp NUMERIC(24,10)=0 , @twotemp NUMERIC(24,10)=0 , @twotempmo NUMERIC(24,10)=0 , @threemo NUMERIC(24,10)=0 
		DECLARE @twotempint NUMERIC(24,10)=0
		IF	@rate2!=0
		BEGIN	
			SET @onetemp=CONVERT(INT,
									 CONVERT(NUMERIC(24,10),@tempqty) /@rate1 
								 )
		END
		ELSE	
		BEGIN
			SET @onetemp=CONVERT(NUMERIC(24,10),
								CONVERT(NUMERIC(24,10),@tempqty) /@rate1 
								)

		END
		
		DECLARE @onetempint NUMERIC(24,10)=CONVERT(NUMERIC(24,10), @onetemp) --第一个
		IF( (@fullname2 IS NOT NULL AND @fullname2!='') OR @rate2!=0 )
			SET @onetempint=CONVERT(INT,@onetempint) --查过一个单位的时候
		DECLARE @onetempmo NUMERIC(24,10)=CONVERT(NUMERIC(24,10), @tempqty)%@rate1
		
		IF (@rate2!=0 AND @onetempmo>0) --都在的时候 
		BEGIN
			SET @twotemp= @onetempmo/@rate2
			SET @twotempint=CASE WHEN @rate3!=0 THEN CONVERT(INT,@twotemp) ELSE @twotemp END
			SET @twotempmo=@onetempmo%@rate2
		END
		
		IF(@twotempmo>0 AND @rate3!=0)
			SET @threemo=@twotempmo/@rate3
		
		IF(@twotempint=0 AND @rate3=0 AND @rate2 !=0)
		BEGIN	
			SET @twotempint=@onetempmo/@rate2
			SET @twotemp=@twotempint
		END
		
		--只有一个单位数据
		IF(@onetempint!=0)
			SET @customassistantunit += CONVERT(VARCHAR(MAX),
										dbo.ClearZero(@onetempint)
														
										
												) +@fullname1
		--只有两个单位数据
		IF(@twotempint!=0 AND @fullname2 IS NOT NULL )
			SET @customassistantunit += CONVERT(VARCHAR(MAX),
											
												 dbo.ClearZero(@twotempint)
												) +@fullname2
		--全有
		IF(@threemo!=0 AND @fullname3 IS NOT NULL )
			SET @customassistantunit += CONVERT(VARCHAR(MAX),
											
												 dbo.ClearZero(@threemo)
												) +@fullname3

									
	END
	
	RETURN @customassistantunit
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetCustomAssistDirect]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].F_GetCustomAssistDirect
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能：获取自定义辅助数量  注意: 请和单据GridCalcRunner_New.cs 中的SetAssistantUnitSpecial 这个方法保持一致
-- 作者：蒋奎  
-- 时间：2015-08-06
--SELECT @rate1=SaleUnitRate1,@rate2=SaleUnitRate2,@rate3=SaleUnitRate3 from @PType_AuxiliaryUnits_Ext where PTypeID=@ptypeid
-- ========================================================================
CREATE  FUNCTION  F_GetCustomAssistDirect
(
	@qty			NUMERIC(24,10),
	@rate1			NUMERIC(24,10),
	@fullname1		VARCHAR(200),
	@rate2			NUMERIC(24,10),
	@fullname2		VARCHAR(200),
	@rate3			NUMERIC(24,10),
	@fullname3		VARCHAR(200),
	@Digit			INT = 10
)
RETURNS VARCHAR(MAX) 
AS  
BEGIN 
	DECLARE @tempqty NUMERIC(24,10) 
	SET @tempqty=CONVERT(NUMERIC(24,10), ABS(@qty)) --四舍五入
	
	DECLARE @customassistantunit VARCHAR(MAX)=''
	--是否有自定义单位
	IF	(@fullname1 IS NULL OR @rate1=0 )
	BEGIN
		SET @customassistantunit=''
	END
	ELSE
	BEGIN
		DECLARE @onetemp NUMERIC(24,10)=0 , @twotemp NUMERIC(24,10)=0 , @twotempmo NUMERIC(24,10)=0 , @threemo NUMERIC(24,10)=0 
		DECLARE @twotempint NUMERIC(24,10)=0
		IF	@rate2!=0
		BEGIN	
			SET @onetemp=CONVERT(INT,
									 CONVERT(NUMERIC(24,10),@tempqty) /@rate1 
								 )
		END
		ELSE	
		BEGIN
			SET @onetemp=CONVERT(NUMERIC(24,10),
								CONVERT(NUMERIC(24,10),@tempqty) /@rate1 
								)

		END
		
		DECLARE @onetempint NUMERIC(24,10)=CONVERT(NUMERIC(24,10), @onetemp) --第一个
		IF( (@fullname2 IS NOT NULL AND @fullname2!='') OR @rate2!=0 )
			SET @onetempint=CONVERT(INT,@onetempint) --查过一个单位的时候
		DECLARE @onetempmo NUMERIC(24,10)=CONVERT(NUMERIC(24,10), @tempqty)%@rate1
		
		IF (@rate2!=0 AND @onetempmo>0) --都在的时候 
		BEGIN
			SET @twotemp= @onetempmo/@rate2
			SET @twotempint=CASE WHEN @rate3!=0 THEN CONVERT(INT,@twotemp) ELSE @twotemp END
			SET @twotempmo=@onetempmo%@rate2
		END
		
		IF(@twotempmo>0 AND @rate3!=0)
			SET @threemo=@twotempmo/@rate3
		
		IF(@twotempint=0 AND @rate3=0 AND @rate2 !=0)
		BEGIN	
			SET @twotempint=@onetempmo/@rate2
			SET @twotemp=@twotempint
		END
		
		--只有一个单位数据
		IF(@onetempint!=0)
			SET @customassistantunit += CONVERT(VARCHAR(MAX),
										dbo.ClearZeroDirect(@onetempint,@Digit)
														
										
												) +@fullname1
		--只有两个单位数据
		IF(@twotempint!=0 AND @fullname2 IS NOT NULL )
			SET @customassistantunit += CONVERT(VARCHAR(MAX),
											
												 dbo.ClearZeroDirect(@twotempint,@Digit)
												) +@fullname2
		--全有
		IF(@threemo!=0 AND @fullname3 IS NOT NULL )
			SET @customassistantunit += CONVERT(VARCHAR(MAX),
											
												 dbo.ClearZeroDirect(@threemo,@Digit)
												) +@fullname3

									
	END
	
	RETURN @customassistantunit
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetDefaultLeveal]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].F_GetDefaultLeveal
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能说明：根据编号长度获取级数  4-2-2-2... 初始级数为2 对应erp中的1级
-- 作者：wt   
-- 时间：2016-02-01
-- ========================================================================
CREATE  FUNCTION  F_GetDefaultLeveal
(
	@UserCode	VARCHAR(200)	
)
RETURNS VARCHAR(200) 
AS  
BEGIN 
	DECLARE @leveal	VARCHAR(200),@extralength INT 
	IF(LEN(@UserCode)<=4)
		 RETURN '2'
	SET @extralength =LEN(RIGHT(@usercode,LEN(@usercode)-4) )		
	RETURN CAST((@extralength/2+2)  AS VARCHAR(200))
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetDraftAcVoucherBillData]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetDraftAcVoucherBillData]
GO



/*
	作者：谢吉康
	日期：2012-06-05
	描述：根据方向，取指定科目和期间的借方发生额或贷方发生额
*/
CREATE FUNCTION F_GetDraftAcVoucherBillData
(
)
RETURNS @DraftBalance TABLE
(
	STypeId		VARCHAR(50),
	ATypeId		VARCHAR(50),
	FDebit		 NUMERIC(24, 10) ,
	FDebitFor	 NUMERIC(24, 10) ,
	FCredit		 NUMERIC(24, 10) ,
	FCreditFor	 NUMERIC(24, 10) ,
	Cid			VARCHAR(10),
	FYear		VARCHAR(10),
	FPeriod		VARCHAR(10)
)
AS
BEGIN
	DECLARE @Cid INT

	--获取本币ID
	SELECT	TOP 1 
			@Cid = Cid
	FROM	Ac_Currency
	WHERE	Sysrow = 1

	--本币，原币金额
	INSERT INTO @DraftBalance
	SELECT	B.STypeId,
			B.ATypeId,
			FDebit = SUM(
							CASE 
								WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) <> 0 THEN ISNULL(B.FDebitTotal,0)
								WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) = 0 THEN  -1*ISNULL(B.FCreditTotal,0)
								ELSE 0
							END
						),
			FDebitFor = SUM(
							CASE 
								WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) <> 0 THEN ISNULL(B.FDebitTotalFor,0) 							
								WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) = 0  THEN -1*ISNULL(B.FCreditTotalFor,0)							
								ELSE 0 
							END
						   ),
			FCredit = SUM(
							CASE 
								WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) <> 0 THEN ISNULL(B.FCreditTotal,0)
								WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) = 0  THEN -1*ISNULL(B.FDebitTotal,0)
								ELSE 0
							END
						 ),
			FCreditFor = SUM(
							CASE 
								WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) <> 0 THEN ISNULL(B.FCreditTotalFor,0)
								WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) = 0  THEN -1*ISNULL(B.FDebitTotalFor,0)							
								ELSE 0 
							END
							),		
			B.Cid,
			B.FYear,
			B.FPeriod
	FROM	Ac_Voucher_Bill B
	INNER JOIN Ac_Voucher V ON B.BillNumberId = V.BillNumberId
	WHERE	V.RedWord = 0 
			AND V.IfCheck = 'f'	
			AND V.FChecked <> -1	
	GROUP BY B.STypeId,
			 B.ATypeId,
			 B.Cid,
			 B.FYear,
			 B.FPeriod
	UNION ALL		 
	--本币、原币对应的综合本位币
	SELECT	B.STypeId,
			B.ATypeId,
			FDebit = SUM(
							CASE 
								WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) <> 0 THEN ISNULL(B.FDebitTotal,0)
								WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) = 0 THEN  -1*ISNULL(B.FCreditTotal,0)
								ELSE 0
							END
						),
			FDebitFor = SUM(
							CASE 
								WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) <> 0 THEN ISNULL(B.FDebitTotalFor,0) 							
								WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) = 0  THEN -1*ISNULL(B.FCreditTotalFor,0)														
								ELSE 0 
							END
							),
			FCredit = SUM(
							CASE 
								WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) <> 0 THEN ISNULL(B.FCreditTotal,0)
								WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) = 0  THEN -1*ISNULL(B.FDebitTotal,0)
								ELSE 0
							END
						 ),
			FCreditFor = SUM(
							CASE 
								WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) <> 0 THEN ISNULL(B.FCreditTotalFor,0)
								WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) = 0  THEN -1*ISNULL(B.FDebitTotalFor,0)							
								ELSE 0 
							END
							),	
			0 AS Cid,
			B.FYear,
			B.FPeriod
	FROM	Ac_Voucher_Bill B
	INNER JOIN Ac_Voucher V ON B.BillNumberId = V.BillNumberId
	WHERE	V.RedWord = 0 
			AND V.IfCheck = 'f'		
			AND V.FChecked <> -1
	GROUP BY B.STypeId,
			 B.ATypeId,
			 B.Cid,
			 B.FYear,
			 B.FPeriod
		 
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_GetDraftAuxAcVoucherBillData]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_GetDraftAuxAcVoucherBillData]
GO



/*
	作者：俞俊杰
	日期：2012-12-07
	描述：获取未过账辅助核算数据
*/
CREATE FUNCTION F_GetDraftAuxAcVoucherBillData ( )
RETURNS @DraftBalance TABLE
    (
      STypeId VARCHAR(50) ,
      ATypeId VARCHAR(50) ,
      TypeId VARCHAR(50) ,
      TypeName VARCHAR(50) ,
      INITOTAL  NUMERIC(24, 10)  ,
      INITOTALFOR  NUMERIC(24, 10)  ,
      Cid VARCHAR(10) ,
      FYear VARCHAR(10) ,
      FPeriod VARCHAR(10)
    )
AS 
    BEGIN
        INSERT  INTO @DraftBalance
                SELECT  STypeId ,
                        ATypeId ,
                        TypeId ,
                        typeName ,
                        CASE WHEN Fdc = 1
                             THEN SUM(ISNULL(debit, 0) - ISNULL(credit, 0))
                             WHEN Fdc = -1
                             THEN SUM(ISNULL(credit, 0) - ISNULL(debit, 0))
                        END AS INITOTAL ,
                        CASE WHEN Fdc = 1
                             THEN SUM(ISNULL(debitFor, 0) - ISNULL(creditFor,
                                                              0))
                             WHEN Fdc = -1
                             THEN SUM(ISNULL(creditFor, 0) - ISNULL(debitFor,
                                                              0))
                        END AS INITOTALFOR ,
                        Cid ,
                        FYear ,
                        FPeriod
                FROM    ( SELECT    t1.STypeId ,
                                    t1.ATypeId ,
                                    t3.TypeId ,
                                    t3.typeName ,
                                    t1.FDebitTotalFor AS debitFor ,
                                    t1.FDebitTotal AS debit ,
                                    t1.FCreditTotal AS credit ,
                                    t1.FCreditTotalFor AS creditFor ,
                                    t1.Cid ,
                                    t1.FYear ,
                                    t1.FPeriod ,
                                    t4.fdc
                          FROM      Ac_Voucher_Bill t1
                                    INNER JOIN Ac_Voucher t2 ON t2.BillNumberId = t1.BillNumberId
                                    INNER JOIN Ac_Voucher_Bill_Assist_CheckItems t3 ON t1.ID = t3.vBId
                                    INNER JOIN dbo.Ac_Account t4 ON t1.stypeid = t4.stypeid
                                                              AND t1.atypeid = t4.typeid
                          WHERE     t2.IfCheck = 'f'
                                    AND t2.FChecked <> '-1'
                        ) AS a
                GROUP BY STypeId ,
                        ATypeId ,
                        TypeId ,
                        typeName ,
                        fdc ,
                        cid ,
                        FYear ,
                        FPeriod
        INSERT  INTO @DraftBalance
                SELECT  STypeId ,
                        ATypeId ,
                        TypeId ,
                        typeName ,
                        SUM(ISNULL(INITOTAL, 0)) ,
                        SUM(ISNULL(INITOTALFOR, 0)) ,
                        0 AS Cid ,
                        FYear ,
                        FPeriod
                FROM    @DraftBalance
                GROUP BY STypeId ,
                        ATypeId ,
                        TypeId ,
                        typeName ,
                        FYear ,
                        FPeriod
                     
        RETURN
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='F_GetIsUseByAcItemByStypeID' )
	DROP FUNCTION [dbo].[F_GetIsUseByAcItemByStypeID]
GO
-- =============================================
-- 作者:		古丽娟
-- 日期:		2012-06-06
-- 返回:		判断是否使用
-- =============================================
CREATE FUNCTION [dbo].[F_GetIsUseByAcItemByStypeID]
(
    @id			INT,			--ID
    @StypeId	VARCHAR(50)	--分支机构 
) 
RETURNS INT     
AS 
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM MoveMoneyBill WHERE atypeid=CONVERT(VARCHAR(50),ISNULL(@id,'')) AND Stypeid=@StypeId)--单据
		RETURN 1
	IF EXISTS(SELECT TOP 1 1 FROM gatheringBill WHERE ATypeID=CONVERT(VARCHAR(50),ISNULL(@id,'')) AND Stypeid=@StypeId )--收款单
		RETURN 1
	IF EXISTS(SELECT TOP 1 1  FROM BillIndex WHERE  ATYPEID=CONVERT(VARCHAR(50),ISNULL(@id,'')) AND Stypeid=@StypeId )--收款单
		RETURN 1
	IF EXISTS(SELECT TOP 1 1  FROM PreBill WHERE  ATYPEID=CONVERT(VARCHAR(50),ISNULL(@id,'')) AND Stypeid=@StypeId )--预收预付款单
		RETURN 1	
	IF EXISTS(SELECT TOP 1 1  FROM AType_Total WHERE  ATYPEID=CONVERT(VARCHAR(50),ISNULL(@id,'')) AND Stypeid=@StypeId )--期初
		RETURN 1	
	IF EXISTS(SELECT TOP 1 1  FROM MoneyBill WHERE  ATYPEID=CONVERT(VARCHAR(50),ISNULL(@id,'')) AND Stypeid=@StypeId )--费用单
		RETURN 1	
	IF EXISTS(SELECT TOP 1 1  FROM AccountCredence WHERE (ATYPEID=CONVERT(VARCHAR(50),ISNULL(@id,'')) OR TypeATypeID=CONVERT(VARCHAR(50),ISNULL(@id,''))) AND Stypeid=@StypeId )--会计凭证
		RETURN 1
	IF EXISTS(SELECT TOP 1 1  FROM PreBill WHERE  ATYPEID=CONVERT(VARCHAR(50),ISNULL(@id,'')) AND Stypeid=@StypeId )--预收
		RETURN 1
	IF EXISTS(SELECT TOP 1 1 FROM ItemType_Item ii INNER JOIN ItemType i ON i.nId=ii.itemTypeId and ii.itemId=@id AND i.STypeid=@StypeId )--项目分类
		RETURN 1
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex b INNER JOIN OtherInOutType t ON T.ID=B.OtherInOutType WHERE T.ATypeID=CONVERT(VARCHAR(50),ISNULL(@id,'')) AND B.Stypeid=@StypeId )--其他出库单-业务类别
		RETURN 1
		
		
	RETURN 0--没有被使用
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetItemsPath]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[F_GetItemsPath]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能说明：获取项目的路径
-- 作者：glj  
-- 时间：2013-01-30
-- ========================================================================
CREATE  FUNCTION  F_GetItemsPath
(
	@TypeID		VARCHAR(50)  --项目ID
)
RETURNS VARCHAR(MAX) 
AS  
BEGIN 

	DECLARE @typePath varchar(max)='';
	With GetItemPath(nTypeId,NParID) 
	As 
	( 
		Select nTypeId,nParid From Ac_Items where nTypeId=@TypeID
		Union All 
		Select item.nTypeId,item.nParid 
		From GetItemPath ic
		Inner Join Ac_Items item ON item.nTypeId=ic.NParID  and item.nTypeId<>'00000'
	) 
	 
	Select @typePath+=item.FullName+'\'+CASE WHEN item.Deleted=1 THEN '已停用' ELSE '' END 
	From GetItemPath ip 
	INNER JOIN Ac_Items item ON ip.nTypeId=item.nTypeId and item.nTypeId<>'00000'
	ORDER BY ip.nTypeId
	
	return '\所有项目\'+@typePath
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetNewSerial]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetNewSerial]
GO

CREATE FUNCTION F_GetNewSerial
(
	@oldSerial VARCHAR(50),
	@billnumberid int
)
RETURNS VARCHAR(50)
--@Encode$--
AS 
BEGIN
    DECLARE @NewSerial VARCHAR(50),	@TmpOldSrial VARCHAR(50),@TmpNewSerial VARCHAR(50)
    
   -- IF EXISTS(SELECT TOP 1 1 FROM gp_CruPtypeSerial WHERE Serial = @oldSerial)
	--	RETURN @oldSerial
	
	SET @TmpOldSrial = 'я'+@oldSerial+'я'
	IF EXISTS(SELECT TOP 1 1 FROM SerialAdjustBill b(NOLOCK),SerialAdjustIndex i(NOLOCK) WHERE b.BillNumberId=i.BillNumberId and OldSerial=@TmpOldSrial AND i.draft=0 AND isnull(b.BillId,0)>=@billnumberid)
    BEGIN
		SET @TmpNewSerial=(SELECT TOP 1 Serial FROM SerialAdjustBill b(NOLOCK) 
											inner join SerialAdjustIndex i(NOLOCK) on i.BillNumberId=b.BillNumberId  
							WHERE  SameSearilID=(SELECT top 1  SameSearilID 
													FROM SerialAdjustBill b1(NOLOCK) INNER JOIN SerialAdjustIndex I1(NOLOCK) ON b1.BillNumberId=I1.BillNumberId 
													WHERE OldSerial=@TmpOldSrial AND I1.draft=0 AND isnull(b.BillId,0)>=@billnumberid ORDER BY ID ) AND i.draft=0 ORDER BY ID DESC)
		SET @NewSerial = (SELECT TOP 1 A FROM f_split(@TmpNewSerial,'я')B WHERE B.a<>'')
		RETURN @NewSerial
    END
    RETURN @oldSerial
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetNewUserCode]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[F_GetNewUserCode]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能说明：根据新规则或者科目编号
-- 作者：glj  
-- 时间：2016-01-29
-- ========================================================================
CREATE  FUNCTION  F_GetNewUserCode
(
	@UserCode	VARCHAR(200),  --科目编号ID
	@Leveal		VARCHAR(200)   --科目级别
)
RETURNS VARCHAR(MAX) 
AS  
BEGIN 
	DECLARE @Ac_Table TABLE (Leveal VARCHAR(10),LevealLen INT)
	INSERT INTO @Ac_Table(Leveal,LevealLen)
	SELECT 2,Len1 FROM Ac_Table union 
	SELECT 3,Len2  FROM Ac_Table union 
	SELECT 4,Len3  FROM Ac_Table union 
	SELECT 5,Len4  FROM Ac_Table union 
	SELECT 6,Len5  FROM Ac_Table union 
	SELECT 7,Len6  FROM Ac_Table union 
	SELECT 8,Len7  FROM Ac_Table union 
	SELECT 9,Len8  FROM Ac_Table union 
	SELECT 10,Len9  FROM Ac_Table union
	SELECT 11,Len10  FROM Ac_Table
	DECLARE 
		@I			INT=3,--级别
		@ILen		INT=4,--第一级的长度
		@Code		VARCHAR(200)=SUBSTRING(@UserCode,1,4),--第一级科目长度
		@LevealLen	INT
	WHILE(@I<=@Leveal)
		BEGIN
			SELECT @LevealLen=LevealLen FROM @Ac_Table WHERE Leveal=@I
			SET @Code+=ISNULL(REPLICATE('0',@LevealLen-2),'')+SUBSTRING(@UserCode,@ILen+1,2)
			SET @ILen+=2
			SET @I+=1
		END
	RETURN @Code
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetOldSerial]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetOldSerial]
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-10
-- Description: 如果序列号做过调整，找到调整前的序列号，否则返回原序列号（思路：找到上一张单据，如果是调整单则需要再往上找）
-- =============================================
CREATE FUNCTION [F_GetOldSerial]
(
	@Serial VARCHAR(50),
	@ID int
)
RETURNS VARCHAR(50)
--@Encode$--
AS 
BEGIN
    DECLARE @OldSerial VARCHAR(50),	@TmpSrial VARCHAR(50),@TmpoldSerial VARCHAR(50),@Billnumberid NUMERIC(10,0),
			@i int=50 
	
	DECLARE @nID INT
	
	WHILE @I>0
	BEGIN
		--初始化
		SET @TmpSrial = 'я'+@Serial+'я'
		SET @Billnumberid=0
		SET @nID=0
		
		--找到序列号的上一个引用
		--SELECT @nID=MAX(ID) FROM gp_inoutPtypeSerial WHERE ID< @ID AND Serial=@Serial AND  BillNumberid in(select BillNumberid from BillIndex w)
		SELECT @nID = MAX(a.ID) FROM gp_inoutPtypeSerial a WHERE ID<  @ID AND Serial = @Serial
			AND  ( BillNumberid in(select BillNumberid from BillIndex where redword=0 and a.BillType=BillType and ifcheck='t') 
					or BillNumberid in(select BillNumberid from SerialAdjustIndex where a.BillType=203 and ifcheck='t'))
		
		--判断上一个引用是否为序列号调整单
		SELECT @Billnumberid=BillNumberid FROM gp_inoutPtypeSerial WHERE ID=@nID AND BillType=203
		
		IF ISNULL(@Billnumberid,0)>0--如果是序列号调整单
		BEGIN
			SET @ID=0
			
			SELECT @TmpoldSerial=OldSerial 
			FROM SerialAdjustBill 
			WHERE  Serial=@TmpSrial and BillNumberid=@Billnumberid
			
			SET @OldSerial = SUBSTRING(@TmpoldSerial,2,LEN(@TmpoldSerial)-2)
			
			--将得到的序列号赋值给当前序列号
			SET @Serial=@OldSerial
			--取原序列号的id
			SELECT @ID=ID FROM gp_inoutPtypeSerial WHERE Serial=@Serial and BillNumberid=@Billnumberid
		END
		ELSE 
		BEGIN
			SET @I=0
		    RETURN @Serial
		END
		SET @i=@I-1
	END
	RETURN @Serial
    
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getparassistitem]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].f_getparassistitem
GO

---获取辅助核算项的父类

CREATE FUNCTION f_getparassistitem
(
	@SourceSql varchar(MAX),
	@StrSeprate varchar(10) 
)
returns @temp TABLE(a varchar(MAX))
AS 
BEGIN
    DECLARE @i INT
    DECLARE @temp1 TABLE (id INT IDENTITY(1,1), a VARCHAR(max))  
    SET @SourceSql=RTRIM(LTRIM(@SourceSql))
    SET @i=charindex(@StrSeprate,@SourceSql)
    WHILE @i>=1
	    BEGIN
	        INSERT @temp1 VALUES(LEFT(@SourceSql,@i-1))
	        SET @SourceSql=SUBSTRING(@SourceSql,@i+1,len(@SourceSql)-@i)
	        SET @i=charindex(@StrSeprate,@SourceSql)
	    END
	  
	DECLARE @temp2 TABLE (typeid VARCHAR(max))
	
    IF @SourceSql<>'' 
       INSERT @temp1 VALUES(@SourceSql)
    
    --遍历每行，找出他们的父节点
    DECLARE @index INT=1,
			@count INT,
			@typeid VARCHAR(max),
			@lenth  INT,
			@fathercount INT,
			@fatheindex INT=1,
			@fathertypeid VARCHAR(max)
			
	SELECT @count=COUNT(*) FROM @temp1
    
    WHILE @index<=@count
		BEGIN
			SELECT @typeid=a FROM @temp1 WHERE id=@index
			SET @lenth=LEN(@typeid)
			IF @lenth>5
				BEGIN
					SET @fathercount=@lenth/5-1
					WHILE @fatheindex<=@fathercount
						BEGIN
						    SET @fathertypeid=SUBSTRING(@typeid,1,5*@fatheindex)
						    INSERT INTO @temp2 SELECT @fathertypeid
							SET @fatheindex=@fatheindex+1
						END
					SET @fatheindex=1
				END
			SET @index=@index+1
		END
     
     INSERT INTO @temp
     SELECT typeid FROM @temp2
     UNION 
     SELECT a FROM @temp1
     
    RETURN 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_getparatypeitem]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].f_getparatypeitem
GO

---获取符合条件的科目

CREATE FUNCTION f_getparatypeitem
(
	@SourceSql varchar(MAX),
	@StrSeprate varchar(10),
	@stypeid	VARCHAR(50),
	@aacategorytypeid  VARCHAR(10),
	@cid	  INT
)
returns @temp TABLE(a varchar(MAX))
AS 
BEGIN
    DECLARE @i INT
    DECLARE @temp1 TABLE (id INT IDENTITY(1,1), a VARCHAR(max))  
    SET @SourceSql=RTRIM(LTRIM(@SourceSql))
    SET @i=charindex(@StrSeprate,@SourceSql)
    WHILE @i>=1
	    BEGIN
	        INSERT @temp1 VALUES(LEFT(@SourceSql,@i-1))
	        SET @SourceSql=SUBSTRING(@SourceSql,@i+1,len(@SourceSql)-@i)
	        SET @i=charindex(@StrSeprate,@SourceSql)
	    END
	  
	DECLARE @temp2 TABLE (typeid VARCHAR(50))
	
    IF @SourceSql<>'' 
       INSERT @temp1 VALUES(@SourceSql)
    
    ---找出那些是有此类辅助核算项的科目
    INSERT INTO @temp2(typeid)
    SELECT t.a           
    FROM @temp1 t 
    JOIN dbo.Ac_Account_Assist_CheckItems ac 
    ON t.a=ac.ATypeId AND ac.STypeId=@stypeid AND ascids=@aacategorytypeid AND ((@cid>0 AND cid=@cid) OR @cid<=0)
    
    INSERT INTO @temp
    SELECT DISTINCT b.a FROM @temp2 a JOIN @temp1 b ON a.typeid LIKE b.a+'%'
    RETURN 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
  
 



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetPriceBillStype]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetPriceBillStype]
GO

/*
========================================================================
	功能说明： 	价格表分支机构名称连接函数
	作者： 		李灏龙
	时间：		2013年5月14日 15:05:07
========================================================================
*/

CREATE  FUNCTION F_GetPriceBillStype
(
	@id		INT
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(MAX)
	SET @sql = ''
	SELECT	@sql=@sql+s.FullName+';' 
	FROM	PriceRule_Stype prs 
	INNER JOIN stype s ON s.TypeId = prs.StypeID
	WHERE	prs.PriceRuleID = @id
	ORDER BY s.FullName
	IF @sql = ''
		RETURN ''
	RETURN LEFT(@sql,LEN(@sql)-1)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetPriceTrack]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetPriceTrack]
GO



/*
-- 功能说明：	根据商品、往来单位、仓库、经手人判断有么有促销价
-- 作者：毛欣蓉
-- 最后修改时间：2012-04-25
*/

CREATE FUNCTION F_GetPriceTrack
(
	@chvPTypeID			varchar(50)	= '',	-- 商品 ID，只允许叶子数据
	@chvBTypeID			varchar(50)	= '',	-- 往来单位 ID
	@chvKTypeID			varchar(50)	= '',	-- 仓库 ID
	@chvETypeID			varchar(50)	= '',	-- 职员 ID
	@chvBillDate		varchar(100)= ''	-- 单据日期
)
--@Encode$--
RETURNS  VARCHAR(50) 
AS
BEGIN
	DECLARE  @intPromotePrice INT=0
	-- 若没有符合时间段内的商品记录，则促销价为 0
	IF NOT EXISTS(
		SELECT	TOP 1 1
		FROM	PromotePrice
		WHERE	PTypeID = @chvPTypeID
			AND StartDate <= @chvBillDate
			AND EndDate >= @chvBillDate
			AND (@chvKTypeID LIKE KtypeId +'%' OR KtypeId = '00000')
			AND (@chvETypeID LIKE EtypeId +'%' OR EtypeId = '00000')
			AND (@chvBTypeID LIKE btypeId +'%' OR BtypeId = '00000')
		)
		BEGIN
			SET @intPromotePrice = 0
		END
	ELSE
		BEGIN
			SET @intPromotePrice = 1
			
		END
    RETURN @intPromotePrice
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetPtypeBasePrice]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetPtypeBasePrice]
GO



/*
-- 功能说明：	获取商品的基础价格信息
*/

CREATE FUNCTION F_GetPtypeBasePrice
(
	@chvPriceFlag		INT,				-- 价格标识：0：成本均价；1：最低售价；2：最高售价；3：最高进价；
	@chvPTypeID			varchar(50)	,		-- 商品 ID
	@chvMunitID			INT = 0,			-- 大单位 ID
	@chvKTypeID			varchar(50)	= '',	-- 仓库 ID
	@chvSTypeID			varchar(50)	= '',	-- 分支机构 ID
	@chvBTypeID			varchar(50)	= '',	-- 往来单位 ID
	@chvETypeID			varchar(50)	= ''	-- 职员 ID
)
--@Encode$--
RETURNS  NUMERIC(24,10) 
AS
BEGIN
	DECLARE  @BasePrice NUMERIC(24,10)=0
	
	IF @chvPriceFlag = 0
	BEGIN
		SELECT TOP 1 @BasePrice = CAST(ISNULL(CAST(SUM(Total) AS NUMERIC(24,10))/CASE WHEN SUM(QTY)=0 THEN NULL ELSE SUM(QTY) END,0) AS numeric(24,10))
        FROM GoodsStocks WHERE PTypeID=@chvPTypeID and KTypeID=@chvKTypeID
	END
	ELSE IF @chvPriceFlag = 1
	BEGIN
		IF EXISTS(SELECT pricetype FROM stype WHERE TypeId=@chvSTypeID AND PriceType = 1)
		BEGIN
			select TOP 1 @BasePrice = lowsaleprice from ptype_stypeprice where ptypeid=@chvPTypeID and stypeid=@chvSTypeID and UnitID=@chvMunitID
		END
		ELSE
		BEGIN
			select TOP 1 @BasePrice = lowsaleprice from ptype_price where ptypeid=@chvPTypeID and UnitID=@chvMunitID
		END
	END
	ELSE IF @chvPriceFlag = 2
	BEGIN
		IF EXISTS(SELECT pricetype FROM stype WHERE TypeId=@chvSTypeID AND PriceType = 1)
		BEGIN
			select TOP 1 @BasePrice = TopSalePrice from ptype_stypeprice where ptypeid=@chvPTypeID and stypeid=@chvSTypeID and IsDefaultUnit=1
		END
		ELSE
		BEGIN
			select TOP 1 @BasePrice = TopSalePrice from ptype_price where ptypeid=@chvPTypeID and IsDefaultUnit=1
		END
	END 
	ELSE IF @chvPriceFlag = 3
	BEGIN
		IF EXISTS(SELECT pricetype FROM stype WHERE TypeId=@chvSTypeID AND PriceType = 1)
		BEGIN
			select TOP 1 @BasePrice = TopBuyPrice from ptype_stypeprice where ptypeid=@chvPTypeID and stypeid=@chvSTypeID and IsDefaultUnit=1
		END
		ELSE
		BEGIN
			select TOP 1 @BasePrice = TopBuyPrice from ptype_price where ptypeid=@chvPTypeID and IsDefaultUnit=1
		END
	END 
	ELSE
		SET @BasePrice = 0
	
    RETURN @BasePrice
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetPTypeInCategoryIDStr]') AND xtype in (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].F_GetPTypeInCategoryIDStr
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/*
by:glj
date:2018-06-26
function:获取商品线性表 使用规则,只给表连接，查询字段，where条件请自行添加
*/
CREATE FUNCTION F_GetPTypeInCategoryIDStr
(
	@OperatorId	VARCHAR(50),-- 操作员ID
	@PTypeId	VARCHAR(MAX),--商品ID
	@PCTypeId	VARCHAR(MAX)--商品分类ID
)
RETURNS VARCHAR(MAX)
--@Encode$--
AS
BEGIN
	DECLARE 
		@SQL VARCHAR(MAX)
	
	--拥有所有权限
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000')
		BEGIN
			IF ISNULL(@ptypeid,'') IN('00000','','%') AND ISNULL(@PCTypeId,'')=''--查询全部
				BEGIN
					SET @SQL='
					FROM ptype P'
				END
			ELSE IF ISNULL(@ptypeid,'') IN('00000','','%') AND ISNULL(@PCTypeId,'')<>''--商品类别不为空
				BEGIN
					SET @SQL='
					FROM ptype P 
					INNER JOIN f_split('''+@PCTypeId+''','','') FC ON FC.a=LEFT(P.PtypeCategoryID,LEN(FC.a))'
				END
			ELSE IF ISNULL(@ptypeid,'') NOT IN ('00000','','%') AND ISNULL(@PCTypeId,'')=''--商品类别为空 商品ID不为空
				BEGIN
					SET @SQL='
					FROM ptype P 
					INNER JOIN f_split('''+@PTypeId+''','','') FP ON FP.a=LEFT(P.typeId,LEN(FP.a))'
				END
			ELSE IF ISNULL(@ptypeid,'') NOT IN ('00000','','%') AND ISNULL(@PCTypeId,'')<>''--商品类别、商品ID都不为空
				BEGIN
					SET @SQL='
					FROM ptype P 
					INNER JOIN f_split('''+@PCTypeId+''','','') FC ON FC.a=LEFT(P.PtypeCategoryID,LEN(FC.a))
					INNER JOIN f_split('''+@PTypeId+''','','') FP ON FP.a=LEFT(P.typeId,LEN(FP.a))'
				END
		END
	ELSE --权限限制
		BEGIN
			IF ISNULL(@ptypeid,'') IN('00000','','%') AND ISNULL(@PCTypeId,'')=''--查询全部
				BEGIN
					SET @SQL='
					FROM PType_L L
					INNER JOIN PType P ON L.etypeid='''+@OperatorId+''' AND L.flag=1 AND L.TypeId=LEFT(P.TypeId,LEN(L.TypeId))'
				END
			ELSE IF ISNULL(@ptypeid,'') IN('00000','','%') AND ISNULL(@PCTypeId,'')<>''--商品类别不为空
				BEGIN
					SET @SQL='
					FROM PType_L L
					INNER JOIN PType P ON L.etypeid='''+@OperatorId+''' AND L.flag=1 AND L.TypeId=LEFT(P.TypeId,LEN(L.TypeId))
					INNER JOIN f_split('''+@PCTypeId+''','','') FC ON FC.a=LEFT(P.PtypeCategoryID,LEN(FC.a))'
					
				END
			ELSE IF ISNULL(@ptypeid,'') NOT IN ('00000','','%') AND ISNULL(@PCTypeId,'')=''--商品类别为空 商品ID不为空
				BEGIN
					SET @SQL='
					FROM PType_L L
					INNER JOIN PType P ON L.etypeid='''+@OperatorId+''' AND L.flag=1 AND L.TypeId=LEFT(P.TypeId,LEN(L.TypeId))
					INNER JOIN f_split('''+@PTypeId+''','','') FP ON FP.a=LEFT(P.typeId,LEN(FP.a))'
				END
			ELSE IF ISNULL(@ptypeid,'') NOT IN ('00000','','%') AND ISNULL(@PCTypeId,'')<>''--商品类别、商品ID都不为空
				BEGIN
					SET @SQL='
					FROM PType_L L
					INNER JOIN PType P ON L.etypeid='''+@OperatorId+''' AND L.flag=1 AND L.TypeId=LEFT(P.TypeId,LEN(L.TypeId))
					INNER JOIN f_split('''+@PCTypeId+''','','') FC ON FC.a=LEFT(P.PtypeCategoryID,LEN(FC.a))
					INNER JOIN f_split('''+@PTypeId+''','','') FP ON FP.a=LEFT(P.typeId,LEN(FP.a))'
				END
		END
	RETURN @SQL
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetPtypeUnitInfo]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetPtypeUnitInfo]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		李灏龙
-- Create date: 2012年5月11日
-- Description:	获取商品单位相关信息
-- =============================================

CREATE FUNCTION dbo.F_GetPtypeUnitInfo()
RETURNS TABLE
AS
RETURN
	SELECT	
			UnitsType,
			baseUnitId AS unitid,
			ISNULL(AssistantUnitId,0) AS nunitid,
			BuyUnitId,
			SaleUnitId,
			StockUnitId,
			typeId,
			ifusegoodsnum,
			dbo.F_GetUnitName(BaseUnitId,0) AS unit,--基本计量单位
			dbo.F_GetUnitName(AssistantUnitId,1) AS nunit,--辅助计量单位名称
			dbo.F_GetUnitName(BuyUnitId,0) AS buyunitname,--采购默认单位名称
			dbo.F_GetUnitName(SaleUnitId,0) AS saleunitname,			--销售默认单位名称
			dbo.F_GetUnitName(StockUnitId,0) AS stockunitname,		--存货默认单位名称		
			ISNULL(dbo.F_GetPtypeRate(typeid,AssistantUnitId),0) AS unitrate,--浮动换算率
			ISNULL(dbo.F_GetPtypeRate(typeid,BaseUnitId),1) AS rate,--基本计量单位换算率
			ISNULL(dbo.F_GetPtypeRate(typeid,BuyUnitId),1) AS buymunitrate,	--采购默认单位换算率
			ISNULL(dbo.F_GetPtypeRate(typeid,SaleUnitId),1) AS salemunitrate,	--销售默认单位换算率
			ISNULL(dbo.F_GetPtypeRate(typeid,StockUnitId),1) AS stockmunitrate--存货默认单位换算率			
	FROM	PType
	WHERE	sonnum = 0
GO









if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetPtypeUnitInfo_TypeID]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetPtypeUnitInfo_TypeID]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		李灏龙
-- Create date: 2012年5月11日
-- Description:	获取商品单位相关信息
-- =============================================

CREATE FUNCTION dbo.F_GetPtypeUnitInfo_TypeID(@typeid VARCHAR(100))

RETURNS TABLE
AS
RETURN
	SELECT * FROM F_GetPtypeUnitInfo()	WHERE typeId=@typeid
GO








SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[F_GetRecPrice]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[F_GetRecPrice]
GO



/*

*/

CREATE FUNCTION F_GetRecPrice
(
	@strSTypeID			VARCHAR(50),
	@strPTypeID			VARCHAR(50)
)
--@Encode$--
RETURNS   NUMERIC(24, 10) 
AS
BEGIN
	DECLARE
		@decPrice	 NUMERIC(24, 10) 
		
	SELECT @decPrice=0

	IF EXISTS(
		SELECT ISNULL(a.RecPrice,0)
		FROM PType_STypePrice a
		INNER JOIN dbo.ptype b
		ON a.PTypeID=b.TypeID
		AND a.UnitID=b.baseUnitId
		WHERE a.STypeID=@strSTypeID
		AND a.PTypeID=@strPTypeID
	)
	BEGIN
		SELECT @decPrice=ISNULL(a.RecPrice,0)
		FROM PType_STypePrice a
		INNER JOIN dbo.ptype b
		ON a.PTypeID=b.TypeID
		AND a.UnitID=b.baseUnitId
		WHERE a.STypeID=@strSTypeID
		AND a.PTypeID=@strPTypeID
	END
	
	RETURN @decPrice
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetStandard_Ac_Account]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetStandard_Ac_Account]
GO


/*
	作者：谢吉康
	日期：2012-04-19
	描述：获取标准的会计科目编号格式
*/
CREATE FUNCTION F_GetStandard_Ac_Account
(
	@chvOperatorId			varchar(100) =  '' --操作员ID，用于控制权限
)
RETURNS @Temp TABLE
(
	STypeId			VARCHAR(50),
	TypeId			VARCHAR(50),
	ParId			VARCHAR(50),
	UserCode		VARCHAR(400),
	OrderUserCode	VARCHAR(400)
)
--@Encode$--
AS
BEGIN
	INSERT INTO @Temp(STypeId,TypeId,ParId,UserCode,OrderUserCode)
	SELECT	StypeId,
			TypeId,
			ParId,		
			REPLICATE('    ',FLeveal-1) + UserCode as UserCode,
			UserCode AS OrderUserCode
	FROM	Ac_Account
	WHERE   Leveal > 1 	

	RETURN
END




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetSummaryByLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].[F_GetSummaryByLimit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能说明：获取项目的路径
-- 作者：glj  
-- 时间：2013-01-30
-- ========================================================================
CREATE  FUNCTION  F_GetSummaryByLimit
(
	@ID			INT,			--分录号
	@operatorid	VARCHAR(50),	--操作员ID
	@StypeId	VARCHAR(50),
	@Summary	VARCHAR(MAX)	--摘要
)
RETURNS VARCHAR(MAX) 
AS  
BEGIN 
	DECLARE 
		@Assist			VARCHAR(MAX),--辅助核算字符串
		@RetStr			VARCHAR(MAX)='',
		@AssistLimit	INT,--辅助核算项目受权限范围控制
		@MangerSTypeID	VARCHAR(50),--分支机构是否有全部权限
		@MangerDTypeID	VARCHAR(50),--部门是否有全部权限
		@MangerETypeID	VARCHAR(50),--职员是否有全部权限
		@MangerBTypeID	VARCHAR(50),--往来单位是否有全部权限
		@MangerBTypeID1	VARCHAR(50)--往来单位是否有全部权限
	
	SELECT @AssistLimit=SUBSTRING(lim,4690,1) FROM loginuser WHERE etypeid=@operatorid
	
	IF(@AssistLimit=1)--受权限点控制
		BEGIN
			SELECT 
				@MangerSTypeID=MangerSTypeID,
				@MangerDTypeID=MangerDTypeID,
				@MangerETypeID=MangerETypeID,
				@MangerBTypeID=MangerBTypeID,
				@MangerBTypeID1=MangerBTypeID2
			FROM LoginUser
			WHERE etypeid=@operatorid

			--分支机构01
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='01' AND vBId=@ID) AND @MangerSTypeID='-99999'
				BEGIN
					SELECT @RetStr=Detail.FullName
					FROM Ac_Voucher_Bill_Assist_CheckItems C
					INNER JOIN SType Detail ON C.typeName='01' AND Detail.TypeId=C.TypeId AND C.vBId=@ID
					
					SELECT @Assist=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END
					FROM Ac_Voucher_Bill_Assist_CheckItems C
					INNER JOIN Ac_Assist_CheckItems I ON C.typeName='01' AND C.typeName=I.UserCode AND C.vBId=@ID
					INNER JOIN SType Detail ON Detail.TypeId=C.TypeId
					LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',11,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId
					
					IF CHARINDEX(@RetStr,@Summary)>0 AND @RetStr<>@Assist
						SET @Summary=REPLACE(@Summary,@RetStr,@Assist)
				END
			--部门02
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='02' AND vBId=@ID) AND @MangerDTypeID='-99999'
				BEGIN
					SELECT @RetStr=Detail.FullName
					FROM Ac_Voucher_Bill_Assist_CheckItems C
					INNER JOIN Department Detail ON C.typeName='02' AND Detail.TypeId=C.TypeId AND C.vBId=@ID
					
					SELECT @Assist=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END
					FROM Ac_Voucher_Bill_Assist_CheckItems C
					INNER JOIN Ac_Assist_CheckItems I ON C.typeName='02' AND C.typeName=I.UserCode AND C.vBId=@ID
					INNER JOIN Department Detail ON Detail.TypeId=C.TypeId
					LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',9,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId

					IF CHARINDEX(@RetStr,@Summary)>0 AND @RetStr<>@Assist
						SET @Summary=REPLACE(@Summary,@RetStr,@Assist)
				END
			--职员
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='03' AND vBId=@ID) AND @MangerETypeID='-99999'
				BEGIN
					SELECT @RetStr=Detail.FullName
					FROM Ac_Voucher_Bill_Assist_CheckItems C
					INNER JOIN employee Detail ON C.typeName='03' AND Detail.TypeId=C.TypeId AND C.vBId=@ID
					
					SELECT @Assist=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END
					FROM Ac_Voucher_Bill_Assist_CheckItems C
					INNER JOIN Ac_Assist_CheckItems I ON C.typeName='03' AND C.typeName=I.UserCode AND C.vBId=@ID
					INNER JOIN employee Detail ON Detail.TypeId=C.TypeId
					LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',3,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId

					IF CHARINDEX(@RetStr,@Summary)>0 AND @RetStr<>@Assist
						SET @Summary=REPLACE(@Summary,@RetStr,@Assist)
				END
			--往来单位
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName='04' AND vBId=@ID) AND (@MangerBTypeID='-99999' OR @MangerBTypeID1='-99999')
				BEGIN
					SELECT @RetStr=Detail.FullName
					FROM Ac_Voucher_Bill_Assist_CheckItems C
					INNER JOIN BType Detail ON C.typeName='04' AND Detail.TypeId=C.TypeId  AND C.vBId=@ID
					
					SELECT @Assist=CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE Detail.FullName END
					FROM Ac_Voucher_Bill_Assist_CheckItems C
					INNER JOIN Ac_Assist_CheckItems I ON C.typeName='04' AND C.typeName=I.UserCode AND C.vBId=@ID
					INNER JOIN BType Detail ON Detail.TypeId=C.TypeId
					LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',2,@operatorid,@StypeId) F ON F.typeid=Detail.TypeId

					IF CHARINDEX(@RetStr,@Summary)>0 AND @RetStr<>@Assist
						SET @Summary=REPLACE(@Summary,@RetStr,@Assist)
				END
		END
RETURN @Summary
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetTableFunctionName]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetTableFunctionName]
GO

/*
	作者：duguolei	
	日期：2013-01-15
	描述：通过表名获取功能提示
*/
CREATE  FUNCTION F_GetTableFunctionName
(
	@TableName			VARCHAR(800)=''	--数据库表名
)	
RETURNS  VARCHAR(200)

AS

BEGIN
    DECLARE @Fname VARCHAR(200)

    IF @TableName = 'tmpGain' 
        SET @Fname = '在月结期间数据中'
    IF @TableName = 'AuditingFlowSet' 
        SET @Fname = '在审核设置中'
    IF @TableName = 'Ac_IniAccount' 
        SET @Fname = '在账务期初中'
    IF @TableName = 'nVipConfiscateConfig' 
        SET @Fname = '在会员卡充值中'
    IF @TableName = 'FaPiaoBillIndex' 
        SET @Fname = '在发票中'
    IF @TableName = 'IntegralExchangeBill' 
        SET @Fname = '在积分兑换单中'
    IF @TableName = 'LoseBill' 
        SET @Fname = '在报损单中'
    IF @TableName = 'ToolIndex' 
        SET @Fname = '在工具中'
    IF @TableName = 'OrderIndex' 
        SET @Fname = '在订单中'
    IF @TableName = 'gp_CruPtypeSerial' 
        SET @Fname = '在当前序列号'
    IF @TableName = 'wx_Bill_Move' 
        SET @Fname = '在维修品调拨单中'
    IF @TableName = 'nVipWashCarTimesConfig' 
        SET @Fname = '在洗车次数充值配置中'
    IF @TableName = 'wx_InOutStockTable' 
        SET @Fname = '在维修商品出入库中'
    IF @TableName = 'Advantage' 
        SET @Fname = '在获利返利中'
    IF @TableName = 'PreBill' 
        SET @Fname = '在预收预付中'
    IF @TableName = 'saleBackBill' 
        SET @Fname = '在销售退货中'
    IF @TableName = 'Ac_IniAccount_Assist_CheckItems' 
        SET @Fname = '在账务期初辅助核算中'
    IF @TableName = 'wx_Bill_Out' 
        SET @Fname = '在维修品调出单中'
    IF @TableName = 'UFO_Temple' 
        SET @Fname = '在财务报表模板中'
    IF @TableName = 'PriceProtect' 
        SET @Fname = '在价保标准中'
    IF @TableName = 'Advantage_standard' 
        SET @Fname = '在获利返利标准中'
    IF @TableName = 'InOutstocktable' 
        SET @Fname = '在出入库汇总中'
    IF @TableName = 'DisassembleBill' 
        SET @Fname = '在生产拆装单中'
    IF @TableName = 'gp_initPtypeSerial' 
        SET @Fname = '在期初序列号中'
    IF @TableName = 'PriceProtectBill' 
        SET @Fname = '在价保中'
    IF @TableName = 'Stock' 
        SET @Fname = '在仓库中'
    IF @TableName = 'Ac_IniAccount_Assist_CheckItems_Detail' 
        SET @Fname = '在期初科目余额中'
    IF @TableName = 'AccountCredence' 
        SET @Fname = '在会计凭证中'
    IF @TableName = 'BillCode_Seed' 
        SET @Fname = '在单据编号中'
    IF @TableName = 'BillIndex' 
        SET @Fname = '在单据中'
    IF @TableName = 'MoneyBill' 
        SET @Fname = '在现金银行中'
    IF @TableName = 'wx_Bill_Replace' 
        SET @Fname = '在整机更换单'
    IF @TableName = 'AskPriceBill' 
        SET @Fname = '在询价单中'
    IF @TableName = 'MonthATypeHistory' 
        SET @Fname = '在月结历史中'
    IF @TableName = 'BuyGoodsExchangeBill' 
        SET @Fname = '在采购退货中'
    IF @TableName = 'PriceProtectList' 
        SET @Fname = '在价保中'
    IF @TableName = 'OtherInOutBill' 
        SET @Fname = '在其他出入库中'
    IF @TableName = 'gatheringBill' 
        SET @Fname = '在收款单中'
    IF @TableName = 'MoveBill' 
        SET @Fname = '在分支机构调拨中'
    IF @TableName = 'PriceTrack' 
        SET @Fname = '在价格跟踪中'
    IF @TableName = 'RequestBill' 
        SET @Fname = '在请购单中'
    IF @TableName = 'CommissionStock' 
        SET @Fname = '在代销库存中'
    IF @TableName = 'OrderBill' 
        SET @Fname = '在订单中'
    IF @TableName = 'wx_Bill_Call' 
        SET @Fname = '在报修单中'
    IF @TableName = 'Ac_Items_Detail' 
        SET @Fname = '在项目明细中'
    IF @TableName = 'Ac_Account' 
        SET @Fname = '在会计科目中'
    IF @TableName = 'Ac_MulColumnAccount' 
        SET @Fname = '在多栏账中'
    IF @TableName = 'GiveBill' 
        SET @Fname = '在赠送单明细'
    IF @TableName = 'Ac_OtherGains' 
        SET @Fname = ''
    IF @TableName = 'CommissionStock_Qty' 
        SET @Fname = '在期初代销库存状况中'
    IF @TableName = 'wx_Bill_Self' 
        SET @Fname = '在维修单中'
    IF @TableName = 'DtypeSaleplan' 
        SET @Fname = '在部门销售计划中'
    IF @TableName = 'Ac_ProfitAndLoss' 
        SET @Fname = '在损益类科目中'
    IF @TableName = 'btype_credit' 
        SET @Fname = '在单位信用额度中'
    IF @TableName = 'employee' 
        SET @Fname = '在职员基本信息中'
    IF @TableName = 'SaleBill' 
        SET @Fname = '在销售出库单中'
    IF @TableName = 'BuyBackBill' 
        SET @Fname = '在采购退货单中'
    IF @TableName = 'overflowBill' 
        SET @Fname = '在报溢单中'
    IF @TableName = 'Ac_ProfitAndLoss_Detail' 
        SET @Fname = '在损益类科目中'
    IF @TableName = 'IsStartOk' 
        SET @Fname = ''
    IF @TableName = 'wx_Bill_GetBack' 
        SET @Fname = '在维修取件单中'
    IF @TableName = 'ItemType' 
        SET @Fname = '项目分类中'
    IF @TableName = 'MoveBjBill' 
        SET @Fname = '在变价调拨中'
    IF @TableName = 'STypeMoveBill' 
        SET @Fname = '在分支机构调拨中'
    IF @TableName = 'Ac_Account_Assist_CheckItems' 
        SET @Fname = '在会计科目辅助核算中'
    IF @TableName = 'LendBill' 
        SET @Fname = '在借欠明细中'
    IF @TableName = 'Ac_Auditing_Template' 
        SET @Fname = '在过账模版中'
    IF @TableName = 'Vacation' 
        SET @Fname = '在考勤节假日中'
    IF @TableName = 'wx_Bill_Send' 
        SET @Fname = '在送修单中'
    IF @TableName = 'GiveFromSaleOrBuyBill' 
        SET @Fname = '在赠送获赠关联信息中'
    IF @TableName = 'WorkTime' 
        SET @Fname = '在考勤节假日中'
    IF @TableName = 'GivemeBill' 
        SET @Fname = '在获赠单中'
    IF @TableName = 'SerialAdjustIndex' 
        SET @Fname = '在序列号调整中'
    IF @TableName = 'wx_Bill_Goto' 
        SET @Fname = '在上门维修中'
    IF @TableName = 'EtypeSaleplan' 
        SET @Fname = '在人员销售计划中'
    IF @TableName = 'Ac_Balance' 
        SET @Fname = '在结算方式中'
    IF @TableName = 'BtypePriceInfo' 
        SET @Fname = ''
    IF @TableName = 'LendIndex' 
        SET @Fname = '在借欠中'
    IF @TableName = 'Ac_Voucher' 
        SET @Fname = '在凭证字中'
    IF @TableName = 'Ac_Balance_Assist_CheckItems' 
        SET @Fname = '在科目余额中'
    IF @TableName = 'RequestIndex' 
        SET @Fname = '在请购单中'
    IF @TableName = 'CashMoneyBill' 
        SET @Fname = '在现金银行中'
    IF @TableName = 'Ac_Voucher_Bill' 
        SET @Fname = '在记账凭证中'
    IF @TableName = 'FaPiaoBill' 
        SET @Fname = '在发票中'
    IF @TableName = 'PayBill' 
        SET @Fname = '在付款单中'
    IF @TableName = 'wx_Bill_SendBack' 
        SET @Fname = '在送修返回中'
    IF @TableName = 'CM_CarUseIndex' 
        SET @Fname = '在车辆使用中'
    IF @TableName = 'MoveMoneyBill' 
        SET @Fname = '在转款中'
    IF @TableName = 'CM_FeeIndex' 
        SET @Fname = '在车辆管理费中'
    IF @TableName = 'IniCommissionStock_Qty' 
        SET @Fname = '在期初代销库存中'
    IF @TableName = 'Ac_Balance_Assist_CheckItems_Detail' 
        SET @Fname = '在科目余额中'
    IF @TableName = 'StypeSaleplan' 
        SET @Fname = '在分支机构销售计划中'
    IF @TableName = 'wx_Bill_In' 
        SET @Fname = '在维修品调入中'
    IF @TableName = 'retailBill' 
        SET @Fname = '在零售单中'
    IF @TableName = 'SType_InnerARTotal' 
        SET @Fname = '在内部应收中'
    IF @TableName = 'Ac_Voucher_Bill_CashMoneyItems' 
        SET @Fname = '在会计凭证现金流量中'
    IF @TableName = 'PType_STypePrice' 
        SET @Fname = '在商品分支机构价格信息中'
    IF @TableName = 'SType_UserConfig' 
        SET @Fname = '在分支机构开账信息中'
    IF @TableName = 'PosRetailCash' 
        SET @Fname = ''
    IF @TableName = 'ListTable' 
        SET @Fname = '在钱流单据中'
    IF @TableName = 'AdDebtBill' 
        SET @Fname = '在应收应付中'
    IF @TableName = 'SaleGoodsExchangeBill' 
        SET @Fname = '在销售换货中'
    IF @TableName = 'BuyBill' 
        SET @Fname = '在采购单据中'
    IF @TableName = 'wx_Bill_JieJian' 
        SET @Fname = '在维修接件单中'
    IF @TableName = 'AdPriceBill' 
        SET @Fname = '在成本调价明细中'
    IF @TableName = 'BillAtype' 
        SET @Fname = ''
    IF @TableName = 'QuotePriceBill' 
        SET @Fname = '在报价单中'
    IF @TableName = 'CommissionBill' 
        SET @Fname = '在代销明细中'
    IF @TableName = 'RetailBackBill' 
        SET @Fname = '在零售退货中'
	IF @TableName = 'PromoRule_Stype' 
        SET @Fname = '在促销规则中'
    
    IF @TableName = 'PriceRulePriority' 
        SET @Fname = '在价格规则优先级中'
    IF @TableName = 'PriceRule_Stype' 
        SET @Fname = '在价格规则中'
    IF @TableName = 'PriceBillIndex_Stype' 
        SET @Fname = '在价格表中'
    IF @TableName = 'PosUpdatedMaxNumber' OR @TableName = 'PosReDataGlobal' OR @TableName='PosIsUpdateData' OR @TableName='PosDataUpdated'
        SET @Fname = ''
   IF @TableName = 'BeforePromoteRetailBill' 
        SET @Fname = '在促销前的零售单中'
   IF @TableName = 'PosInfo' 
        SET @Fname = 'POS档案'
   IF @TableName = 'Ac_AssetsCards' 
        SET @Fname = '在固定资产卡片中'
   IF @TableName = 'Ac_AssetsCards_History' 
        SET @Fname = '在固定资产卡片中' 
   IF @TableName = 'Ac_AssetsCategory' 
        SET @Fname = '在固定资产类别中'         
   IF @TableName = 'Ac_DepreciationPlan' 
        SET @Fname = '在折旧计划中'
   IF @TableName = 'Ac_FixedAssetsInit_Stype' 
        SET @Fname = '' 
   IF @TableName = 'BranchInfo' 
        SET @Fname = '在门店中'      
   IF @TableName = 'FrozeBusiness' 
        SET @Fname = ''    
        --Ac_AssetsCards
   IF @Fname IS NULL
	SET @Fname=''

    RETURN @Fname
 
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetVoucheridOfGoodsbill]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetVoucheridOfGoodsbill]
GO



/*
	作者：李灏龙
	日期：2017-06-29
	描述：根据业务单据id，类型和成本凭证标识，获取对应的凭证id，如果没有生成过，则返回0
*/
CREATE FUNCTION F_GetVoucheridOfGoodsbill
(
	@BillnumerId	NUMERIC(10,0),
	@BillType		INT,
	@InOutType		VARCHAR(10)='0',--库存 1：入 -1出
	@IsCost			VARCHAR(10)='0,2'--0基本 1成本结转 2：2种都包括
)
RETURNS INT 
AS
BEGIN
	DECLARE @VoucherId	INT
	
	IF @BillType IN(404,405)
	BEGIN
		SELECT TOP 1 @VoucherId = VourchBillId FROM dbo.Ac_ReceiptBill_VoucherBill WHERE GoodsBillId = @BillnumerId AND IsCost IN(SELECT a FROM dbo.f_split(@IsCost,','))
	END
	ELSE IF @BillType IN(311)
	BEGIN
		SELECT TOP 1 @VoucherId = VourchBillId FROM dbo.Ac_CommissionBill_VoucherBill WHERE GoodsBillId = @BillnumerId AND BillType = @BillType
	END 
	ELSE IF @BillType IN(310)--资金调拨单区分@InOutType
	BEGIN
		SELECT TOP 1 @VoucherId = VourchBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId = @BillnumerId AND IsCost IN(SELECT a FROM dbo.f_split(@IsCost,',')) AND InOutType IN(SELECT a FROM dbo.f_split(@InOutType,','))
	END 
	ELSE 
	BEGIN	
		SELECT TOP 1 @VoucherId = VourchBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId = @BillnumerId AND IsCost IN(SELECT a FROM dbo.f_split(@IsCost,','))
	END 
	
	RETURN ISNULL(@VoucherId,0)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_JE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_JE]
GO



/*
	作者：谢吉康
	日期：2012-06-05
	描述：取科目在指定期间当期借、贷方发生的差额
	DECLARE @Total  NUMERIC(24, 10) 
	--SET @Total = DBO.F_JE('00001','1001-1002','','2012','4',1,'','2012-01-01','2012-12-31','',0,0,'')
	--SET @Total = DBO.F_JE('00001','1001-1002','4','2012','4',1,'','2012-01-01','2012-12-31','',0,0,'分支机构=默认分支机构,客户=测试客户')	
	--SET @Total = DBO.F_JE('00001','1001-1002','','2012','4',1,'','2012-01-01','2012-12-31','',0,1,'')
	SET @Total = DBO.F_JE('00001','1001-1002','5','2012','4',1,'','2012-01-01','2012-12-31','',0,1,'分支机构=默认分支机构,客户=测试客户')	
	PRINT(@Total)
*/
CREATE FUNCTION F_JE
(
	@STypeId		VARCHAR(50),		-- 分支机构
	@AUserCode		VARCHAR(400),		-- 会计科目编号
	@Cid			VARCHAR(20) = '',	-- 币别
	@FYear			VARCHAR(10),		-- 会计年度
	@FPeriod		VARCHAR(10),		-- 会计期间
	@Fdc			INT,				-- 科目的余额方向
	@Value			VARCHAR(50),		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)	
	@AssiValue		VARCHAR(MAX),		-- 辅助核算列表  [分支机构=A,客户=B]
	@OperatorID		varchar(100)		--操作员ID
)
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS
BEGIN
	DECLARE @Total		 NUMERIC(24, 10) ,
			@ATypeId	VARCHAR(50)
	
	--分支机构权限检查
	DECLARE @GetManSTypeId TABLE 
	(TypeId	varchar(100))
	INSERT INTO @GetManSTypeId(TypeId) 
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	
	--只取本位币
	SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
	
	DECLARE @AType TABLE
	(
		TypeId	VARCHAR(50),
		Fdc		INT,
		STypeId VARCHAR(50)
	)	
	
	--会计科目
	INSERT INTO @AType(TypeId,Fdc,STypeId)
	SELECT	A.TypeId,
			A.Fdc,
			A.StypeId
	FROM	Ac_Account A
	INNER JOIN (
					SELECT	UserCode 
					FROM	F_Get_Ac_Account_UserCode(@AUserCode)
	)U ON A.UserCode = U.UserCode
	WHERE	A.StypeId LIKE @STypeId + '%'
	
	--辅助核算
	DECLARE @Assists TABLE
	(
		Ascids		INT,
		FieldValue	VARCHAR(MAX)
	)
	
	--辅助核算不为空才写入数据
	IF @AssiValue <> ''
	BEGIN
		INSERT INTO @Assists(Ascids,FieldValue) 
		SELECT	Ascids,
				FieldValue 
		FROM	DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)
	END
		
	IF @AssiValue = ''	--辅助核算为空
	BEGIN			
		SELECT	@Total = CASE Fdc
							WHEN 1 THEN ISNULL(SUM(B.FDebit),0) - ISNULL(SUM(B.FCredit),0)
							ELSE ISNULL(SUM(B.FCredit),0) - ISNULL(SUM(B.FDebit),0)
						 END
		FROM	Ac_Balance B
		INNER JOIN @AType A ON B.ATypeId = A.TypeId AND B.STypeId = A.STypeId
		INNER JOIN @GetManSTypeId G ON B.StypeId = G.TypeId
		WHERE	B.STypeId LIKE @STypeId + '%'
				AND B.Cid = 0
				AND B.FPeriod = @FPeriod
				AND B.FYear = @FYear
		GROUP BY Fdc		
	END
	ELSE
	BEGIN
		SELECT	@Total = CASE
							WHEN @Fdc = '借' THEN ISNULL(SUM(B.FDebit),0) - ISNULL(SUM(B.FCredit),0)
							ELSE ISNULL(SUM(B.FCredit),0) - ISNULL(SUM(B.FDebit),0)
						 END
		FROM	Ac_Balance_Assist_CheckItems B
		INNER JOIN @AType A ON B.ATypeId = A.TypeId AND B.STypeId = A.STypeId
		WHERE	B.Cid <> 0
				AND B.STypeId LIKE @STypeId + '%'
				AND B.Cid LIKE @Cid + '%'
				AND EXISTS(
					SELECT  D.STypeId,D.ATypeId
					FROM	Ac_Balance_Assist_CheckItems_Detail D
					INNER JOIN @Assists A ON D.Ascids = A.Ascids AND D.FieldValue = A.FieldValue
					WHERE	B.STypeId = D.STypeId
							AND B.ATypeId = D.ATypeId
							AND B.FPeriod = @FPeriod
							AND B.FYear = @FYear
				)
				AND B.FPeriod = @FPeriod
				AND B.FYear = @FYear
	END
	
	RETURN @Total
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_LFS]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_LFS]
GO



/*
	作者：谢吉康
	日期：2012-05-23
	描述：取会计科目的期初余额数据
	DECLARE @Total  NUMERIC(24, 10) 
	SET @Total = DBO.F_LFS('00001','1003','1','2016','10',1,'','','00001',1,'')
	PRINT(@Total)
*/
CREATE FUNCTION F_LFS
(
	@STypeId VARCHAR(50) ,		-- 分支机构
	@AUserCode VARCHAR(400) ,		-- 会计科目编号
	@Cid VARCHAR(20) = '' ,	-- 币别只取综合本位币
	@FYear VARCHAR(10) ,		-- 会计年度
	@FPeriod VARCHAR(10) ,		-- 会计期间
	@Fdc INT ,				-- 科目的余额方向
	@Value VARCHAR(50) ,		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
	@AssiValue VARCHAR(MAX) ,		-- 辅助核算列表  [分支机构=A,客户=B]
	@OperatorID VARCHAR(100) ,		--操作员ID
	@Draft INT,					-- 包含未记账的凭证 0.不包含  1.包含
	@DepartmentID VARCHAR(50)		--辅助核算 部门ID
)
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
--如果分支机构不在权限范围类
IF NOT EXISTS(SELECT TOP 1 1 FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID))
	RETURN 0
	
--查询条件选择部门
IF @DepartmentID<>''
	BEGIN
		DECLARE @DUserCode	VARCHAR(200)=''
		SELECT @DUserCode=usercode FROM Department WHERE TypeId=@DepartmentID
		DECLARE @RET INT=0
		SELECT @RET=CHARINDEX('%',@AssiValue,1)
		IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1
			SET @AssiValue='部门='+@DUserCode+'%'+SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
		ELSE 
			SET @AssiValue=@AssiValue+'部门='+@DUserCode+'%'
	END

DECLARE 
	@Total		NUMERIC(24, 10)= 0 ,--返回值
    @ATypeId	VARCHAR(50)='',		--科目ID
    @AFdc			INT,				--节点方向
	@AssistsCount	INT=0				--辅助核算个数
	
--获取科目余额方向--获取科目余额方向
IF NOT EXISTS(SELECT  TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode)
	RETURN 0 
ELSE 
	SELECT  @ATypeId=TypeId,@AFdc=Fdc FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode=@AUserCode

--会计科目
DECLARE @AType TABLE(TypeId VARCHAR(50),Fdc INT,STypeId VARCHAR(50))	
INSERT  INTO @AType(TypeId,Fdc,STypeId)SELECT TypeId,Fdc,StypeId FROM Ac_Account WHERE StypeId=@STypeId AND TypeId LIKE @ATypeId+'%' 

--辅助核算
DECLARE @Assists TABLE(Ascids INT,FieldValue VARCHAR(MAX),UserCode VARCHAR(200))
IF @AssiValue <> ''
	BEGIN
		INSERT  INTO @Assists(Ascids,FieldValue,UserCode)
		SELECT  Ascids,FieldValue,UserCode FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)
		SELECT @AssistsCount=@@ROWCOUNT  
	END 
	
--账务期初 本年累计
IF ISNULL(@AssiValue,'')=''
	BEGIN
        SELECT  @Total+= ISNULL(SUM(CASE WHEN A.Fdc = @Fdc AND a.TypeId LIKE '00003%'
										 THEN -I.FYTotal
										 WHEN A.Fdc <> @Fdc AND a.TypeId LIKE '00003%'
										 THEN I.FYTotal
										 WHEN @Fdc = 0
                                         THEN CASE WHEN A.Fdc = 1
                                                        OR @AFdc <> A.Fdc
                                                   THEN I.FDebit - I.FCredit
                                                   ELSE I.FCredit - I.FDebit
                                              END
                                         WHEN @Fdc = 1
                                         THEN CASE WHEN A.Fdc = 1
                                                   THEN I.FDebit
                                                   ELSE -I.FDebit
                                              END
                                         WHEN @Fdc = -1
                                         THEN CASE WHEN A.Fdc = 1
                                                   THEN I.FCredit
                                                   ELSE -I.FCredit
                                              END
                                         ELSE 0
                                    END), 0)
        FROM    Ac_IniAccount I
                INNER JOIN @AType A ON A.TypeId = I.ATypeId
                                       AND A.STypeId = I.STypeId
        WHERE   I.FYear = @FYear;
	END
ELSE IF ISNULL(@AssiValue,'')<>''
	BEGIN
        SELECT  @Total+= ISNULL(SUM(CASE WHEN F.Fdc = @Fdc AND D.ATypeId LIKE '00003%'
										 THEN -D.FYTotal
										 WHEN F.Fdc <> @Fdc AND D.ATypeId LIKE '00003%'
										 THEN D.FYTotal
										 WHEN @Fdc = 0
                                         THEN CASE WHEN F.Fdc = 1
                                                        OR @AFdc <> F.Fdc
                                                   THEN D.FDebit - D.FCredit
                                                   ELSE D.FCredit - D.FDebit
                                              END
                                         WHEN @Fdc = 1
                                         THEN CASE WHEN F.Fdc = 1
                                                   THEN D.FDebit
                                                   ELSE -D.FDebit
                                              END
                                         WHEN @Fdc = -1
                                         THEN CASE WHEN F.Fdc = 1
                                                   THEN D.FCredit
                                                   ELSE -D.FCredit
                                              END
                                         ELSE 0
                                    END), 0)
        FROM    Ac_IniAccount_Assist_CheckItems_Detail D
                INNER JOIN ( SELECT D.STypeId ,
                                    D.ATypeId ,
                                    A.Fdc ,
                                     MAX(D.Ascids) Ascids ,
                                    D.GroupId
                             FROM   Ac_IniAccount_Assist_CheckItems_Detail D
                                    INNER JOIN @AType A ON A.STypeId = D.STypeId
                                                           AND A.TypeId = D.ATypeId
                                    INNER JOIN @Assists A1 ON A1.Ascids = D.Ascids
                                                              AND ( ( A1.FieldValue <> ''
                                                              AND D.FieldValue LIKE A1.FieldValue
                                                              + '%'
                                                              )
                                                              OR A1.FieldValue = ''
                                                              )
                             WHERE  D.FYear <= @FYear
                             GROUP BY D.STypeId ,
                                    D.ATypeId ,
                                    A.Fdc,
                                    d.GroupId
                             HAVING COUNT(*) >= @AssistsCount
                           ) F ON F.STypeId = D.STypeId
                                  AND F.ATypeId = D.ATypeId
                                  AND F.Ascids = D.Ascids
                                  AND F.GroupId = D.GroupId
        WHERE   D.FYear = @FYear;
	END	
--本年财务累计
IF @AssiValue = ''--辅助核算为空
	BEGIN	
        SELECT  @Total+= ISNULL(SUM(CASE WHEN @Fdc = 0
                                         THEN CASE WHEN A.Fdc = 1
                                                        OR @AFdc <> A.Fdc
                                                   THEN I.FDebitTotal
                                                        - I.FCreditTotal
                                                   ELSE I.FCreditTotal
                                                        - I.FDebitTotal
                                              END
                                         WHEN @Fdc = 1
                                         THEN CASE WHEN A.Fdc = 1
                                                   THEN I.FDebitTotal
                                                   ELSE -I.FDebitTotal
                                              END
                                         WHEN @Fdc = -1
                                         THEN CASE WHEN A.Fdc = 1
                                                   THEN I.FCreditTotal
                                                   ELSE -I.FCreditTotal
                                              END
                                    END), 0)
        FROM    dbo.Ac_Voucher V
                INNER JOIN dbo.Ac_Voucher_Bill I ON V.BillNumberId = I.BillNumberId
                INNER JOIN @AType A ON A.TypeId = I.ATypeId
                                       AND A.STypeId = I.STypeId
        WHERE   I.STypeId = @STypeId
                AND I.FYear = @FYear
                AND I.FPeriod <= @FPeriod
                AND ( ( @Draft = 0
                        AND V.IfCheck = 't'
                      )
                      OR @Draft = 1
                    )
                AND V.VoucherType <> 2
                AND V.FChecked <> -1;    		 
	END
ELSE--辅助核算不为空
	BEGIN
        SELECT  @Total+= ISNULL(SUM(CASE WHEN @Fdc = 0
                                         THEN CASE WHEN F.Fdc = 1
                                                        OR @AFdc <> F.Fdc
                                                   THEN T1.FDebitTotal
                                                        - T1.FCreditTotal
                                                   ELSE T1.FCreditTotal
                                                        - T1.FDebitTotal
                                              END
                                         WHEN @Fdc = 1
                                         THEN CASE WHEN F.Fdc = 1
                                                   THEN T1.FDebitTotal
                                                   ELSE -T1.FDebitTotal
                                              END
                                         WHEN @Fdc = -1
                                         THEN CASE WHEN F.Fdc = 1
                                                   THEN T1.FCreditTotal
                                                   ELSE -T1.FCreditTotal
                                              END
                                    END), 0)
        FROM    Ac_Voucher_Bill T1
                INNER JOIN ( SELECT C.BillNumberId ,
                                    C.vBId ,
                                    A.Fdc
                             FROM   Ac_Voucher_Bill B
                                    INNER JOIN dbo.Ac_Voucher V ON V.BillNumberId = B.BillNumberId
                                                              AND B.FYear = @FYear
                                                              AND B.FPeriod <= @FPeriod
                                                              AND ( ( @Draft = 0
                                                              AND V.IfCheck = 't'
                                                              )
                                                              OR @Draft = 1
                                                              )
                                                              AND V.VoucherType <> 2
                                                              AND V.FChecked <> -1
                                    INNER JOIN @AType A ON A.STypeId = B.STypeId
                                                           AND A.TypeId = B.ATypeId
                                    INNER JOIN Ac_Voucher_Bill_Assist_CheckItems C ON C.BillNumberId = B.BillNumberId
                                                              AND C.vBId = B.ID
                                    INNER JOIN @Assists A1 ON A1.UserCode = C.typeName
                                                              AND ( A1.FieldValue = ''
                                                              OR ( A1.FieldValue <> ''
                                                              AND C.TypeId LIKE A1.FieldValue+'%'
                                                              )
                                                              )
                             GROUP BY C.BillNumberId ,
                                    C.vBId ,
                                    A.Fdc
                             HAVING COUNT(*) >= @AssistsCount
                           ) F ON F.BillNumberId = T1.BillNumberId
                                  AND F.vBId = T1.ID;
	END
	
RETURN @Total


END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LJE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LJE]
GO



/*
	作者：谢吉康
	日期：2012-06-05
	描述：取科目在指定期间当期借、贷方发生的差额
	DECLARE @Total  NUMERIC(24, 10) 
	--SET @Total = DBO.F_LJE('00001','1001-1002','','2012','4',1,'','2012-01-01','2012-12-31','',0,0,'')
	--SET @Total = DBO.F_LJE('00001','1001-1002','4','2012','4',1,'','2012-01-01','2012-12-31','',0,0,'分支机构=默认分支机构,客户=测试客户')	
	--SET @Total = DBO.F_LJE('00001','1001-1002','','2012','4',1,'','2012-01-01','2012-12-31','',0,1,'')
	SET @Total = DBO.F_LJE('00001','1001-1002','5','2012','4',1,'','2012-01-01','2012-12-31','',0,1,'分支机构=默认分支机构,客户=测试客户')	
	PRINT(@Total)
*/
CREATE FUNCTION F_LJE
(
	@STypeId		VARCHAR(50),		-- 分支机构
	@AUserCode		VARCHAR(400),		-- 会计科目编号
	@Cid			VARCHAR(20) = '',	-- 币别
	@FYear			VARCHAR(10),		-- 会计年度
	@FPeriod		VARCHAR(10),		-- 会计期间
	@Fdc			INT,				-- 科目的余额方向
	@Value			VARCHAR(50),		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)	
	@AssiValue		VARCHAR(MAX)		-- 辅助核算列表  [分支机构=A,客户=B]
)
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS
BEGIN
	DECLARE @Total		 NUMERIC(24, 10) ,
			@ATypeId	VARCHAR(50)
			
	--只取本位币
	SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
	
	DECLARE @AType TABLE
	(
		TypeId	VARCHAR(50),
		Fdc		INT,
		STypeId VARCHAR(50)
	)	
	
	--会计科目
	INSERT INTO @AType(TypeId,Fdc,STypeId)
	SELECT	A.TypeId,
			A.Fdc,
			A.StypeId
	FROM	Ac_Account A
	INNER JOIN (
					SELECT	UserCode 
					FROM	F_Get_Ac_Account_UserCode(@AUserCode)
	)U ON A.UserCode = U.UserCode
	WHERE	A.StypeId LIKE @STypeId + '%'
	
	--辅助核算
	DECLARE @Assists TABLE
	(
		Ascids		INT,
		FieldValue	VARCHAR(MAX)
	)
	
	--辅助核算不为空才写入数据
	IF @AssiValue <> ''
	BEGIN
		INSERT INTO @Assists(Ascids,FieldValue) 
		SELECT	Ascids,
				FieldValue 
		FROM	DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)
	END
		
	IF @AssiValue = ''	--辅助核算为空
	BEGIN			
		SELECT	@Total = CASE
							WHEN @Fdc = '借' THEN ISNULL(SUM(B.FDebit),0) - ISNULL(SUM(B.FCredit),0)
							ELSE ISNULL(SUM(B.FCredit),0) - ISNULL(SUM(B.FDebit),0)
						 END
		FROM	Ac_Balance B
		INNER JOIN @AType A ON B.ATypeId = A.TypeId AND B.STypeId = A.STypeId
		WHERE	B.Cid <> 0
				AND B.STypeId LIKE @STypeId + '%'
				AND B.Cid LIKE @Cid + '%'
				AND B.FPeriod <= @FPeriod
				AND B.FYear = @FYear			
	END
	ELSE
	BEGIN
		SELECT	@Total = CASE
							WHEN @Fdc = '借' THEN ISNULL(SUM(B.FDebit),0) - ISNULL(SUM(B.FCredit),0)
							ELSE ISNULL(SUM(B.FCredit),0) - ISNULL(SUM(B.FDebit),0)
						 END
		FROM	Ac_Balance_Assist_CheckItems B
		INNER JOIN @AType A ON B.ATypeId = A.TypeId AND B.STypeId = A.STypeId
		WHERE	B.Cid <> 0
				AND B.STypeId LIKE @STypeId + '%'
				AND B.Cid LIKE @Cid + '%'
				AND EXISTS(
					SELECT  D.STypeId,D.ATypeId
					FROM	Ac_Balance_Assist_CheckItems_Detail D
					INNER JOIN @Assists A ON D.Ascids = A.Ascids AND D.FieldValue = A.FieldValue
					WHERE	B.STypeId = D.STypeId
							AND B.ATypeId = D.ATypeId
							AND B.FPeriod = @FPeriod
							AND B.FYear = @FYear
				)
				AND B.FPeriod <= @FPeriod
				AND B.FYear = @FYear
	END
	
	RETURN @Total
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_NC]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_NC]
GO



/*
	作者：黄清
	日期：2014-06-10
	描述：取会计科目的年初余额数据
	DECLARE @Total  NUMERIC(24, 10) 
	SET @Total = DBO.F_NC('00001','1001','币种','2012','4',0,1,'','')
	PRINT(@Total)
*/
CREATE FUNCTION F_NC
    (
      @STypeId VARCHAR(50) ,		-- 分支机构
      @AUserCode VARCHAR(400) ,		-- 会计科目编号
      @Cid VARCHAR(20) = '' ,		-- 币别
      @FYear INT ,			-- 会计年度
      @FPeriod INT ,		-- 会计期间
      @Draft INT ,					-- 包含未记账的凭证 0.不包含  1.包含
      @Fdc INT ,					-- 科目的余额方向
      @Value VARCHAR(50) ,			-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
      @AssiValue VARCHAR(MAX) ,		-- 辅助核算列表  [分支机构=A,客户=B]
      @OperatorID VARCHAR(100),		--操作员ID
      @DepartmentID VARCHAR(50)		--辅助核算 部门ID
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE 
		@Total		 NUMERIC(24, 10) =0.00 ,
		@ATypeId	VARCHAR(50) ,
		@AFdc		INT 
				
	--只取本位币
	SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
	
	--分支机构权限检查
	DECLARE @SType TABLE ( TypeId VARCHAR(50) )
	--辅助核算
	DECLARE @Assists TABLE(Ascids INT ,FieldValue VARCHAR(MAX))
     --查询条件选择部门
	IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1 AND @DepartmentID<>''
	BEGIN
		DECLARE @RET INT=0
		SELECT @RET=CHARINDEX('%',@AssiValue,1)
		SELECT @AssiValue=SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
		INSERT INTO @Assists(Ascids,FieldValue)
		SELECT '02',@DepartmentID
	END
	--会计科目
	DECLARE @AType TABLE(TypeId VARCHAR(50) ,Fdc INT ,STypeId VARCHAR(50))
		
	INSERT INTO @SType(TypeId)
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID)			
	
	--如果选中分支该操作员没有权限，直接返回0
	IF NOT EXISTS(SELECT TOP 1 1 FROM @SType)
		RETURN 0
	
	--获取科目余额方向
	SELECT  
		@AFdc = Fdc,
		@ATypeId=TypeId
	FROM Ac_Account
	WHERE 
		StypeId = @STypeId 
		AND UserCode = @AUserCode
		
	INSERT INTO @AType(TypeId,Fdc,STypeId)
	SELECT  
		A.TypeId,
		A.Fdc,
		A.StypeId
	FROM Ac_Account A
	INNER JOIN @SType S ON S.TypeId=A.StypeId AND A.TypeId LIKE @ATypeId+'%'
	
	--如果辅助核算不为空
	IF(ISNULL(@AssiValue,'')<>'')
		BEGIN
			INSERT INTO @Assists(Ascids,FieldValue)
            SELECT 
				Ascids,
                FieldValue
            FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)
		END
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId) OR EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='fyear' AND CAST(SubValue AS INT)=@FYear)
		BEGIN
			IF ISNULL(@AssiValue,'')='' AND ISNULL(@DepartmentID,'')=''
				BEGIN
					SELECT @Total+=ISNULL(SUM(ISNULL(CASE WHEN @AFdc=A.Fdc THEN I.iniYTotal ELSE -I.iniYTotal END,0)),0)
					FROM Ac_IniAccount I
					INNER JOIN @SType S ON S.TypeId=I.STypeId
					INNER JOIN @AType A ON A.TypeId=I.ATypeId AND A.STypeId=S.TypeId
					WHERE 
						I.FYear=@FYear
				END
			ELSE IF ISNULL(@AssiValue,'')<>''
				BEGIN
					SELECT
						@Total+=ISNULL(SUM(ISNULL(CASE WHEN @AFdc=A.Fdc THEN D.IniYTotal ELSE -D.IniYTotal END,0)),0)
					FROM Ac_IniAccount_Assist_CheckItems_Detail D
					INNER JOIN @SType S ON S.TypeId=D.STypeId
					INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
					INNER JOIN (
								SELECT 
									D.STypeId,
									D.ATypeId,
									MAX(D.Ascids) Ascids
								FROM Ac_IniAccount_Assist_CheckItems_Detail D
								INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids AND ((A1.FieldValue<>'' AND  D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
								WHERE 
									D.FYear=@FYear
								--	AND D.FPeriod=@FPeriod
								GROUP BY D.STypeId,D.ATypeId
								) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids
					WHERE 
						D.FYear=@FYear
						--AND D.FPeriod=@FPeriod
					
				END
		END
	ELSE 
		BEGIN
			DECLARE 
				@Period INT,	--查询科目余额表期间值
				@Year INT		--查询科目余额表年度值

				
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear=@FYear)
				BEGIN
					SET @Year=@FYear
					SELECT @Period=MIN(FMonth) FROM Ac_Period WHERE FYear=@Year
				END	
			ELSE 
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear<@FYear)
						BEGIN
							SELECT @Year=MAX(FYear) FROM Ac_Balance
							SELECT @Period=MAX(FPeriod) FROM Ac_Period WHERE FYear=@Year
						END
				END
				

			IF ISNULL(@AssiValue,'')='' AND ISNULL(@DepartmentID,'')=''
				BEGIN
					SELECT
						@Total+=ISNULL(SUM(ISNULL(CASE WHEN @AFdc=A.Fdc THEN B.FBeginBalance ELSE -B.FBeginBalance END,0)),0)
					FROM Ac_Balance  B 
					INNER JOIN @SType S ON S.TypeId=B.STypeId
					INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
					WHERE 
						B.FYear=@Year
						AND B.FPeriod=@Period
						AND B.Cid=0
				END
			ELSE IF ISNULL(@AssiValue,'')<>''
				BEGIN
					SELECT
						@Total+=ISNULL(SUM(ISNULL(CASE WHEN @AFdc=A.Fdc THEN D.IniTotal ELSE -D.IniTotal END,0)),0)
					FROM Ac_Balance_Assist_CheckItems_Detail D
					INNER JOIN @SType S ON D.STypeId=S.TypeId
					INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
					INNER JOIN (
								SELECT 
									D.STypeId,
									D.ATypeId,
									MAX(D.Ascids) Ascids 
								FROM Ac_Balance_Assist_CheckItems_Detail D
								INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids AND ((A1.FieldValue<>'' AND D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
								WHERE 
									D.FYear=@Year
									AND D.FPeriod=@Period
									AND D.Cid=0
								GROUP BY D.STypeId,D.ATypeId
								) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids
					WHERE 
						D.FYear=@Year
						AND D.FPeriod=@Period
						AND D.Cid=0
				END
		END
		IF @Draft=1
			BEGIN
				IF ISNULL(@AssiValue,'')='' AND ISNULL(@DepartmentID,'')=''
					BEGIN
						SELECT 
							@Total+=ISNULL(SUM(ISNULL(CASE 
								WHEN AA.Fdc=1 THEN ISNULL(CASE WHEN B.FAdc=1 THEN B.FdebitTotal ELSE -B.FcreditTotal END,0)
								ELSE ISNULL(CASE WHEN B.FAdc=1 THEN -B.FdebitTotal ELSE B.FcreditTotal END,0)
							 END,0)),0)
						FROM Ac_Voucher_Bill B
						INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
						INNER JOIN @SType S ON S.TypeId=B.STypeId 
						INNER JOIN @AType AA ON AA.TypeId=B.ATypeId AND AA.StypeId=@StypeID
						WHERE
							B.FYear<@FYear
					END
				ELSE IF ISNULL(@AssiValue,'')<>''
					BEGIN
						SELECT 
							@Total+=ISNULL(SUM(ISNULL(CASE 
								WHEN A.Fdc=1 THEN ISNULL(CASE WHEN B.FAdc=1 THEN B.FdebitTotal ELSE -B.FcreditTotal END,0)
								ELSE ISNULL(CASE WHEN B.FAdc=1 THEN -B.FdebitTotal ELSE B.FcreditTotal END,0)
							 END,0)),0)
						FROM Ac_Voucher_Bill B
						INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
						INNER JOIN @SType S ON S.TypeId=B.STypeId 
						INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.StypeId=S.TypeId
						INNER JOIN (
										SELECT D.BillNumberId,D.vBId
										FROM Ac_Voucher_Bill_Assist_CheckItems D 
										INNER JOIN @Assists A1 ON A1.Ascids=CAST(D.typeName AS INT) AND ((A1.FieldValue<>'' AND  D.TypeId LIKE A1.FieldValue+'%') OR A1.FieldValue='')
										GROUP BY D.BillNumberId,D.vBId											
									) F ON F.BillNumberId=B.BillNumberId AND F.vBId=B.ID
						WHERE
							B.FYear<@FYear
					END
			END	
	IF @Fdc = @AFdc
		OR @Fdc = 0 
		SET @Total = @Total
	ELSE 
		SET @Total =-@Total
		
	RETURN @Total	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_QC]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_QC]
GO



/*
	作者：谢吉康
	日期：2012-05-23
	描述：取会计科目的期初余额数据
	DECLARE @Total  NUMERIC(24, 10) 
	SET @Total = DBO.F_QC('00001','1001','币种','2012','4',0,1,'','')
	PRINT(@Total)
*/
CREATE FUNCTION F_QC
(
	@STypeId VARCHAR(50) ,		-- 分支机构
	@AUserCode VARCHAR(400) ,	-- 会计科目编号
	@Cid VARCHAR(20) = '' ,		-- 币别
	@FYear INT ,				-- 会计年度
	@FPeriod INT ,				-- 会计期间
	@Draft INT ,				-- 包含未记账的凭证 0.不包含  1.包含
	@Fdc INT ,					-- 科目的余额方向
	@Value VARCHAR(50) ,		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
	@AssiValue VARCHAR(MAX) ,	-- 辅助核算列表  [分支机构=A,客户=B]
	@OperatorID VARCHAR(100),	--操作员ID
	@DepartmentID VARCHAR(50)	--辅助核算 部门ID
)
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	--查询条件选择部门
	IF @DepartmentID<>''
		BEGIN
			DECLARE @DUserCode	VARCHAR(200)=''
			SELECT @DUserCode=usercode FROM Department WHERE TypeId=@DepartmentID
			DECLARE @RET INT=0
			SELECT @RET=CHARINDEX('%',@AssiValue,1)
			IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1
				SET @AssiValue='部门='+@DUserCode+'%'+SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
			ELSE 
				SET @AssiValue=@AssiValue+'部门='+@DUserCode+'%'
		END
	DECLARE 
		@Total		 NUMERIC(24, 10) =0.00 ,
		@ATypeId	VARCHAR(50) ,
		@AFdc		INT 
				
	--只取本位币
	SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
		
	--分支机构权限检查
	DECLARE @SType TABLE ( TypeId VARCHAR(50) )
	--辅助核算
	DECLARE @Assists TABLE(Ascids INT ,FieldValue VARCHAR(50),UserCode VARCHAR(200))
	--会计科目
	DECLARE @AType TABLE(TypeId VARCHAR(50) ,Fdc INT ,STypeId VARCHAR(50))
		
	INSERT INTO @SType(TypeId)
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID)			
	
	--如果选中分支该操作员没有权限，直接返回0
	IF NOT EXISTS(SELECT TOP 1 1 FROM @SType)
		RETURN 0
	
	--获取科目余额方向--获取科目余额方向
	IF NOT EXISTS(SELECT  TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode)
		RETURN 0 
	ELSE 
		SELECT  
			@AFdc = Fdc,
			@ATypeId=TypeId
		FROM Ac_Account
		WHERE 
			StypeId = @STypeId 
			AND UserCode = @AUserCode
		
	INSERT INTO @AType(TypeId,Fdc,STypeId)
	SELECT  
		A.TypeId,
		A.Fdc,
		A.StypeId
	FROM Ac_Account A
	INNER JOIN @SType S ON S.TypeId=A.StypeId AND A.TypeId LIKE @ATypeId+'%'
	
	DECLARE @AssistCount INT=0--辅助核算个数
	--如果辅助核算不为空
	IF(ISNULL(@AssiValue,'')<>'')
		BEGIN
			INSERT INTO @Assists(Ascids,FieldValue,UserCode)
            SELECT 
				Ascids,
                FieldValue,
                UserCode
            FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)

			SELECT @AssistCount=COUNT(*) FROM @Assists
		END
	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND SFYear=@FYear)
		BEGIN
			IF ISNULL(@AssiValue,'')=''
				BEGIN
					SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND A.Fdc=@AFdc THEN I.iniYTotal ELSE -I.iniYTotal END),0)
					FROM Ac_IniAccount I
					INNER JOIN @SType S ON S.TypeId=I.STypeId
					INNER JOIN @AType A ON A.TypeId=I.ATypeId AND A.STypeId=S.TypeId
					WHERE 
						I.FYear=@FYear
				END
			ELSE IF ISNULL(@AssiValue,'')<>''
				BEGIN
					SELECT
						@Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND F.Fdc=@AFdc THEN D.iniYTotal ELSE -D.iniYTotal END),0)
					FROM Ac_IniAccount_Assist_CheckItems_Detail D
					INNER JOIN (
							SELECT 
								D.STypeId,
								D.ATypeId,
								A.Fdc,
								MAX(D.Ascids) Ascids,
								D.GroupId GroupId
							FROM Ac_IniAccount_Assist_CheckItems_Detail D
							INNER JOIN @AType A ON A.STypeId=D.STypeId AND A.TypeId=D.ATypeId
							INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids  AND ((A1.FieldValue<>'' AND  D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
							WHERE 
								D.FYear=@FYear
							GROUP BY D.STypeId,D.ATypeId,A.Fdc,d.GroupId
							HAVING COUNT(*)>=@AssistCount
						) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids AND F.GroupId=D.GroupId
				END
		END
	ELSE 
		BEGIN
			DECLARE 
				@Period INT=@FPeriod,	--查询科目余额表期间值
				@Year INT=@FYear		--查询科目余额表年度值

				
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear>=@FYear AND STypeId=@STypeId)
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear=@FYear AND STypeId=@STypeId)
					BEGIN
						SET @Year=@FYear
						SELECT @Period=MIN(FPeriod) FROM Ac_Balance WHERE FYear=@Year AND STypeId=@STypeId
						
						IF ISNULL(@AssiValue,'')=''
						BEGIN
							SELECT 
								@Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND A.Fdc=@AFdc THEN B.FBeginBalance ELSE -B.FBeginBalance END),0)
							FROM Ac_Balance  B 
							INNER JOIN @SType S ON S.TypeId=B.STypeId
							INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
							WHERE 
								B.FYear=@Year
								AND B.FPeriod=@Period
								AND B.Cid=0
						END
						ELSE IF ISNULL(@AssiValue,'')<>''
						BEGIN
							SELECT
								@Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND A.Fdc=@AFdc THEN D.IniTotal ELSE -D.IniTotal END),0)
							FROM Ac_Balance_Assist_CheckItems_Detail D
							INNER JOIN @SType S ON D.STypeId=S.TypeId
							INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
							INNER JOIN (
										SELECT 
											D.STypeId,
											D.ATypeId,
											MAX(D.Ascids) Ascids 
										FROM Ac_Balance_Assist_CheckItems_Detail D
										INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids AND ((A1.FieldValue<>'' AND D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
										WHERE 
											D.FYear=@Year
											AND D.FPeriod=@Period
											AND D.Cid=0
										GROUP BY D.STypeId,D.ATypeId
										) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids
							WHERE 
								D.FYear=@Year
								AND D.FPeriod=@Period
								AND D.Cid=0
						END	
					END	
				END	
			ELSE
				BEGIN
					SELECT @Year=MAX(FYear) FROM Ac_Balance WHERE STypeId=@STypeId
					SELECT @Period=MAX(FPeriod) FROM Ac_Balance WHERE FYear=@Year AND STypeId=@STypeId
					
					IF ISNULL(@AssiValue,'')=''
					BEGIN
						SELECT 
							@Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND A.Fdc=@AFdc THEN B.FEndBalance ELSE -B.FEndBalance END),0)
						FROM Ac_Balance  B 
						INNER JOIN @SType S ON S.TypeId=B.STypeId
						INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
						WHERE 
							B.FYear=@Year
							AND B.FPeriod=@Period
							AND B.Cid=0
					END
					ELSE IF ISNULL(@AssiValue,'')<>''
					BEGIN
						SELECT
							@Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND A.Fdc=@AFdc THEN D.FEndBalance ELSE -D.FEndBalance END),0)
						FROM Ac_Balance_Assist_CheckItems_Detail D
						INNER JOIN @SType S ON D.STypeId=S.TypeId
						INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
						INNER JOIN (
									SELECT 
										D.STypeId,
										D.ATypeId,
										MAX(D.Ascids) Ascids 
									FROM Ac_Balance_Assist_CheckItems_Detail D
									INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids AND ((A1.FieldValue<>'' AND D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
									WHERE 
										D.FYear=@Year
										AND D.FPeriod=@Period
										AND D.Cid=0
									GROUP BY D.STypeId,D.ATypeId
									) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids
						WHERE 
							D.FYear=@Year
							AND D.FPeriod=@Period
							AND D.Cid=0
					END				
				END
		END
		IF @Draft=1
			BEGIN
				IF ISNULL(@AssiValue,'')=''
					BEGIN
						SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc=0 THEN CASE WHEN AA.Fdc=1 OR @AFdc<>AA.Fdc THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END
									  WHEN @Fdc=1 THEN CASE WHEN AA.Fdc=1 THEN B.FDebitTotal ELSE -B.FDebitTotal END
									  WHEN @Fdc=-1 THEN CASE WHEN AA.Fdc=1 THEN B.FCreditTotal ELSE -B.FCreditTotal END
									END),0)
						FROM Ac_Voucher_Bill B
						INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
						INNER JOIN @SType S ON S.TypeId=B.STypeId 
						INNER JOIN @AType AA ON AA.TypeId=B.ATypeId AND AA.StypeId=@StypeID
						WHERE
							B.FYear<@FYear
					END
				ELSE IF ISNULL(@AssiValue,'')<>''
					BEGIN
						SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc=0 THEN CASE WHEN A.Fdc=1 OR @AFdc<>A.Fdc THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END
									  WHEN @Fdc=1 THEN CASE WHEN A.Fdc=1 THEN B.FDebitTotal ELSE -B.FDebitTotal END
									  WHEN @Fdc=-1 THEN CASE WHEN A.Fdc=1 THEN B.FCreditTotal ELSE -B.FCreditTotal END
									END),0)
						FROM Ac_Voucher_Bill B
						INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
						INNER JOIN @SType S ON S.TypeId=B.STypeId 
						INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.StypeId=S.TypeId
						INNER JOIN (
										SELECT D.BillNumberId,D.vBId
										FROM Ac_Voucher_Bill_Assist_CheckItems D 
										INNER JOIN @Assists A1 ON A1.UserCode=D.typeName AND ((A1.FieldValue<>'' AND  D.TypeId LIKE A1.FieldValue+'%') OR A1.FieldValue='')
										GROUP BY D.BillNumberId,D.vBId											
									) F ON F.BillNumberId=B.BillNumberId AND F.vBId=B.ID
						WHERE
							B.FYear<@FYear
						GROUP BY A.FDC
					END
			END	
			
	RETURN @Total	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_QM]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_QM]
GO



/*
	作者：谢吉康
	日期：2012-05-23
	描述：取会计科目的余额数据
	DECLARE @Total  NUMERIC(24, 10) 
	SET @Total = DBO.F_QM('00001','1001','','2012','4',0,0,'','')
	PRINT(@Total)
*/
CREATE FUNCTION F_QM
    (
      @STypeId VARCHAR(50) ,		-- 分支机构
      @AUserCode VARCHAR(400) ,		-- 会计科目编号
      @Cid VARCHAR(20) = '' ,	-- 币别
      @FYear INT ,		-- 会计年度
      @FPeriod INT ,		-- 会计期间
      @Draft INT ,				-- 包含未记账的凭证 0.不包含  1.包含
      @Fdc INT ,				-- 科目的余额方向
      @Value VARCHAR(50) ,		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
      @AssiValue VARCHAR(MAX) ,		-- 辅助核算列表  [分支机构=A,客户=B]
      @OperatorID VARCHAR(100),	--操作员ID
      @DepartmentID VARCHAR(50)		--辅助核算 部门ID
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
--如果分支机构不在权限范围类
IF NOT EXISTS(SELECT TOP 1 1 FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID))
	RETURN 0
	
--查询条件选择部门
IF @DepartmentID<>''
	BEGIN
		DECLARE @DUserCode	VARCHAR(200)=''
		SELECT @DUserCode=usercode FROM Department WHERE TypeId=@DepartmentID
		DECLARE @RET INT=0
		SELECT @RET=CHARINDEX('%',@AssiValue,1)
		IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1
			SET @AssiValue='部门='+@DUserCode+'%'+SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
		ELSE 
			SET @AssiValue=@AssiValue+'部门='+@DUserCode+'%'
	END

DECLARE 
	@Total			NUMERIC(24, 10)=0,	--总额
    @ATypeId		VARCHAR(50)='',		--科目id 
    @AFdc			INT,				--节点方向
	@AssistsCount	INT=0				--辅助核算个数
	
--获取科目余额方向
IF NOT EXISTS(SELECT  TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode)
	RETURN 0 
ELSE 
	SELECT  @ATypeId=TypeId,@AFdc=Fdc FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode

--会计科目
DECLARE @AType TABLE(TypeId VARCHAR(50) ,Fdc INT ,STypeId VARCHAR(50))	
INSERT INTO @AType(TypeId,Fdc,STypeId)
SELECT TypeId,Fdc,StypeId FROM Ac_Account WHERE StypeId=@STypeId AND TypeId LIKE @ATypeId+'%'
 
--辅助核算
DECLARE @Assists TABLE(Ascids INT ,FieldValue VARCHAR(MAX),UserCode VARCHAR(200))
--辅助核算不为空才写入数据
IF @AssiValue <> '' 
    BEGIN
        INSERT  INTO @Assists(Ascids,FieldValue,UserCode)
        SELECT  Ascids,FieldValue,UserCode FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)
        SELECT @AssistsCount=@@ROWCOUNT
    END
    
--账务期初数据
IF ISNULL(@AssiValue,'')=''
	BEGIN
		SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND A.Fdc=@AFdc  THEN I.iniTotal ELSE -I.iniTotal END),0)
		FROM Ac_IniAccount I
		INNER JOIN @AType A ON A.TypeId=I.ATypeId AND A.STypeId=I.STypeId
		WHERE 
			I.FYear<=@FYear
	END
ELSE IF ISNULL(@AssiValue,'')<>''
	BEGIN
		SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND F.Fdc=@AFdc  THEN D.iniTotal ELSE -D.iniTotal END),0)
		FROM Ac_IniAccount_Assist_CheckItems_Detail D
		INNER JOIN (
			SELECT 
				D.STypeId,
				D.ATypeId,
				A.Fdc,
				MAX(D.Ascids) Ascids,
				D.GroupId GroupId
			FROM Ac_IniAccount_Assist_CheckItems_Detail D
			INNER JOIN @AType A ON A.STypeId=D.STypeId AND A.TypeId=D.ATypeId
			INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids  AND ((A1.FieldValue<>'' AND  D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
			WHERE 
				D.FYear<=@FYear
			GROUP BY D.STypeId,D.ATypeId,A.Fdc,d.GroupId
			HAVING COUNT(*)>=@AssistsCount
		) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids AND F.GroupId=D.GroupId
		WHERE 
			D.FYear<=@FYear
	END

IF @AssiValue = ''--辅助核算为空
	BEGIN	
		SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc=0 THEN CASE WHEN @AFdc=1 THEN I.FDebitTotal-I.FCreditTotal ELSE I.FCreditTotal-I.FDebitTotal END
									  WHEN @Fdc=1 THEN CASE WHEN A.Fdc=1 THEN I.FDebitTotal ELSE -I.FDebitTotal END
									  WHEN @Fdc=-1 THEN CASE WHEN A.Fdc=1 THEN I.FCreditTotal ELSE -I.FCreditTotal END   
									END),0)
		FROM dbo.Ac_Voucher V
		INNER JOIN dbo.Ac_Voucher_Bill I ON V.BillNumberId = I.BillNumberId
		INNER JOIN @AType A ON A.TypeId = I.ATypeId AND A.STypeId = I.STypeId
		WHERE   
			I.STypeId = @STypeId
			AND (I.FYear<@FYear OR (I.FYear=@FYear AND I.FPeriod<=@FPeriod )) 
			AND ((@Draft = 0 AND v.IfCheck = 't') OR @Draft = 1)
			AND V.FChecked<>-1    		 
	END
ELSE--辅助核算不为空
	BEGIN
		SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc=0 THEN CASE WHEN @AFdc=1 THEN T1.FDebitTotal-T1.FCreditTotal ELSE T1.FCreditTotal-T1.FDebitTotal END
									  WHEN @Fdc=1 THEN CASE WHEN F.Fdc=1 THEN T1.FDebitTotal ELSE -T1.FDebitTotal END
									  WHEN @Fdc=-1 THEN CASE WHEN F.Fdc=1 THEN T1.FCreditTotal ELSE -T1.FCreditTotal END
									END),0)		
		FROM Ac_Voucher_Bill T1
		INNER JOIN
		(
			SELECT
				C.BillNumberId,
				C.vBId,
				A.Fdc
			FROM Ac_Voucher_Bill B
			INNER JOIN dbo.Ac_Voucher V ON V.BillNumberId = B.BillNumberId  AND (B.FYear<@FYear OR (B.FYear=@FYear AND B.FPeriod<=@FPeriod )) AND ((@Draft = 0 AND V.IfCheck = 't') OR @Draft = 1) AND V.FChecked<>-1 
			INNER JOIN @AType A ON A.STypeId=B.STypeId AND A.TypeId=B.ATypeId
			INNER JOIN Ac_Voucher_Bill_Assist_CheckItems C ON C.BillNumberId=B.BillNumberId AND C.vBId=B.ID
			INNER JOIN @Assists A1 ON A1.UserCode=C.typeName AND (A1.FieldValue='' OR (A1.FieldValue<>'' AND C.TypeId LIKE A1.FieldValue+'%'))
			GROUP BY C.BillNumberId,C.vBId,A.Fdc
			HAVING COUNT(*)>=@AssistsCount
		) F ON F.BillNumberId=T1.BillNumberId AND F.vBId=T1.ID
	END
RETURN @Total

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_ReplaceSchemeDataValue]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_ReplaceSchemeDataValue]
GO


/*
	作者：谢吉康
	日期：2012-02-16
	描述：特殊处理用户查询方案明细中的DataValue
	DECLARE @X VARCHAR(MAX)
	SET @X = DBO.F_ReplaceSchemeDataValue('0000100001,0000200002','00001')
	PRINT(@X)
*/
CREATE FUNCTION F_ReplaceSchemeDataValue
(
	@DataValue	VARCHAR(MAX),	--DataValue值
	@RpValue	VARCHAR(MAX)	--替换值
)
RETURNS varchar(8000)
--@encode$--
AS
BEGIN
	DECLARE @rString	varchar(6000)

	SET @rString = ''	

	SELECT @rString = @rString + ',' + a
	FROM	f_split(@DataValue,',')
	WHERE	LEFT(a,LEN(@RpValue)) <> @RpValue
	
	SET @rString = DBO.F_GetValidUserDataId(@rString)
	
	RETURN @rString 
END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_UnionAcIniAssistCheckData]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_UnionAcIniAssistCheckData]
GO

/*
	作者：谢吉康
	日期：2012-07-31
	描述：组装账务期初的辅助核算数据
	DECLARE @X VARCHAR(MAX)
	SET @X = DBO.F_UnionAcIniAssistCheckData('00001','0000100001',1,1)
	PRINT(@X)
*/

CREATE FUNCTION F_UnionAcIniAssistCheckData
(
	@STypeId	VARCHAR(50),
	@ATypeId	VARCHAR(50),
	@Cid		INT,
	@GroupId	INT
)
RETURNS VARCHAR(MAX)
AS 
BEGIN
	DECLARE @GroupValue VARCHAR(MAX),
			@Ascids		VARCHAR(10),
			@FieldValue	VARCHAR(50)
			
	SET @GroupValue = ''

	DECLARE AbcMxDetail_Cursor CURSOR FOR
		SELECT	Ascids,FieldValue 
		FROM	Ac_IniAccount_Assist_CheckItems_Detail 
		WHERE	STypeId = @STypeId 
				AND ATypeId = @ATypeId 
				AND GroupId = @GroupId 
				AND Cid = @Cid 
		ORDER BY Ascids ASC
		
		OPEN AbcMxDetail_Cursor
		
		FETCH NEXT FROM AbcMxDetail_Cursor INTO @Ascids,
												@FieldValue
												
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @GroupValue = @GroupValue + ',' + @Ascids + ':' + @FieldValue
							
			FETCH NEXT FROM AbcMxDetail_Cursor INTO @Ascids,
													@FieldValue
		END
		
		CLOSE AbcMxDetail_Cursor											
		DEALLOCATE AbcMxDetail_Cursor			
		
		IF @GroupValue <> ''
			SET @GroupValue = RIGHT(@GroupValue,LEN(@GroupValue)-1)	
				
	RETURN @GroupValue
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_XFS]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_XFS]
GO



/*
	作者：谢吉康
	日期：2012-06-05
	描述：根据方向，取指定科目和期间的借方发生额或贷方发生额
	DECLARE @Total  NUMERIC(24, 10) 
	SET @Total = DBO.F_XFS('00001','1001-1002','','2012','4',1,'','2012-01-01','2012-12-31','',0,0,'')
	PRINT(@Total)
	--SET @Total = DBO.F_XFS('00001','1001-1002','4','2012','4',1,'','2012-01-01','2012-12-31','',0,0,'分支机构=默认分支机构,客户=测试客户')	
	--SET @Total = DBO.F_XFS('00001','1003','1','2016','10',0,'','2012-01-01','2012-12-31','',0,1,'','00001','')
	SET @Total = DBO.F_XFS('00001','1001-1002','5','2012','4',1,'','2012-01-01','2012-12-31','',0,1,'分支机构=默认分支机构,客户=测试客户')	
	PRINT(@Total)
*/
CREATE FUNCTION F_XFS
    (
      @STypeId VARCHAR(50) ,		-- 分支机构
      @AUserCode VARCHAR(400) ,		-- 会计科目编号
      @Cid VARCHAR(20) = '' ,	-- 币别
      @FYear VARCHAR(10) ,		-- 会计年度
      @FPeriod VARCHAR(10) ,		-- 会计期间
      @Fdc INT ,				-- 科目的余额方向
      @Value VARCHAR(50) ,		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
      @StartDate VARCHAR(20) ,		-- 开始日期
      @EndDate VARCHAR(20) ,		-- 截止日期
      @Summary VARCHAR(500) ,		-- 摘要
      @MatchValue INT ,				-- 摘要匹配方式  0.模糊  1.精确
      @DraftBill INT ,				-- 包含未记账的凭证 0.不包含  1.包含
      @AssiValue VARCHAR(MAX) ,		-- 辅助核算列表  [分支机构=A,客户=B]
      @OperatorID VARCHAR(100),		--操作员ID
      @DepartmentID VARCHAR(50)		--辅助核算 部门ID
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
--如果分支机构不在权限范围类
IF NOT EXISTS(SELECT TOP 1 1 FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID))
	RETURN 0
	
--查询条件选择部门
IF @DepartmentID<>''
	BEGIN
		DECLARE @DUserCode	VARCHAR(200)=''
		SELECT @DUserCode=usercode FROM Department WHERE TypeId=@DepartmentID
		DECLARE @RET INT=0
		SELECT @RET=CHARINDEX('%',@AssiValue,1)
		IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1
			SET @AssiValue='部门='+@DUserCode+'%'+SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
		ELSE 
			SET @AssiValue=@AssiValue+'部门='+@DUserCode+'%'
	END

DECLARE 
	@Total			NUMERIC(24, 10)=0,	--总额
    @ATypeId		VARCHAR(50)='',		--科目id 
    @AFdc			INT,				--节点方向
	@AssistsCount	INT=0				--辅助核算个数
	
--获取科目余额方向
IF NOT EXISTS(SELECT  TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode)
	RETURN 0 
ELSE 
	SELECT  @ATypeId=TypeId,@AFdc=Fdc FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode

--会计科目
DECLARE @AType TABLE(TypeId VARCHAR(50) ,Fdc INT ,STypeId VARCHAR(50))	
INSERT INTO @AType(TypeId,Fdc,STypeId)
SELECT TypeId,Fdc,StypeId FROM Ac_Account WHERE StypeId=@STypeId AND TypeId LIKE @ATypeId+'%'
 
--辅助核算
DECLARE @Assists TABLE(Ascids INT ,FieldValue VARCHAR(MAX),UserCode VARCHAR(200))
--辅助核算不为空才写入数据
IF @AssiValue <> '' 
    BEGIN
        INSERT  INTO @Assists(Ascids,FieldValue,UserCode)
        SELECT  Ascids,FieldValue,UserCode FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)
        SELECT @AssistsCount=@@ROWCOUNT
    END
--当前分支机构未开账
IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=0)
	BEGIN
		SET @Total=0
	END
ELSE
	BEGIN
		IF @AssiValue = ''--辅助核算为空
			BEGIN	
				SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc=0 THEN CASE WHEN A.Fdc=1 OR @AFdc<>A.Fdc THEN I.FDebitTotal-I.FCreditTotal ELSE I.FCreditTotal-I.FDebitTotal END
									  WHEN @Fdc=1 THEN CASE WHEN A.Fdc=1 THEN I.FDebitTotal ELSE -I.FDebitTotal END
									  WHEN @Fdc=-1 THEN CASE WHEN A.Fdc=1 THEN I.FCreditTotal ELSE -I.FCreditTotal END   
									END),0)
				FROM    dbo.Ac_Voucher V
				INNER JOIN dbo.Ac_Voucher_Bill I ON V.BillNumberId = I.BillNumberId
				INNER JOIN @AType A ON A.TypeId = I.ATypeId AND A.STypeId = I.STypeId
				WHERE   
					I.STypeId = @STypeId
					AND I.FYear = @FYear
					AND I.FPeriod = @FPeriod
					AND ((@DraftBill = 0 AND v.IfCheck = 't') OR @DraftBill = 1)
					AND v.VoucherType <> 2
					AND V.FChecked<>-1    		 
			END
		ELSE--辅助核算不为空
			BEGIN
				SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc=0 THEN CASE WHEN F.Fdc=1 OR @AFdc<>F.Fdc THEN T1.FDebitTotal-T1.FCreditTotal ELSE T1.FCreditTotal-T1.FDebitTotal END
									  WHEN @Fdc=1 THEN CASE WHEN F.Fdc=1 THEN T1.FDebitTotal ELSE -T1.FDebitTotal END
									  WHEN @Fdc=-1 THEN CASE WHEN F.Fdc=1 THEN T1.FCreditTotal ELSE -T1.FCreditTotal END
									END),0)		
				FROM Ac_Voucher_Bill T1
				INNER JOIN
				(
					SELECT
						C.BillNumberId,
						C.vBId,
						A.Fdc
					FROM Ac_Voucher_Bill B
					INNER JOIN dbo.Ac_Voucher V ON V.BillNumberId = B.BillNumberId  AND B.FYear=@FYear AND B.FPeriod=@FPeriod AND ((@DraftBill = 0 AND V.IfCheck = 't') OR @DraftBill = 1) AND V.VoucherType <> 2 AND V.FChecked<>-1 
					INNER JOIN @AType A ON A.STypeId=B.STypeId AND A.TypeId=B.ATypeId
					INNER JOIN Ac_Voucher_Bill_Assist_CheckItems C ON C.BillNumberId=B.BillNumberId AND C.vBId=B.ID
					INNER JOIN @Assists A1 ON A1.UserCode=C.typeName AND (A1.FieldValue='' OR (A1.FieldValue<>'' AND C.TypeId LIKE A1.FieldValue+'%'))
					GROUP BY C.BillNumberId,C.vBId,A.Fdc
					HAVING COUNT(*)>=@AssistsCount
				) F ON F.BillNumberId=T1.BillNumberId AND F.vBId=T1.ID
			END
	END
RETURN @Total


END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_XJFS]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_XJFS]
GO



/*
	作者：黄清
	日期：2014-05-27
	描述：取现金流量项目在一段期间内的发生额
	DECLARE @Total  NUMERIC(24, 10) 	
	PRINT(@Total)
*/
CREATE FUNCTION F_XJFS
(
	@STypeId		VARCHAR(50),		-- 分支机构	
	@FYear			VARCHAR(10),		-- 会计年度
	@FPeriod		VARCHAR(10),		-- 会计期间
	@StartDate		VARCHAR(20),		-- 开始日期
	@EndDate		VARCHAR(20),		-- 截至日期	
	@FlowValue		VARCHAR(MAX),		-- 现金流量项目，传入编号
	@Draft			INT,				-- 包含未记账的凭证 0.不包含  1.包含
	@OperatorID		varchar(100)		--操作员ID
)
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS
BEGIN
--分支机构权限检查
	DECLARE @GetManSTypeId TABLE 
	(TypeId	varchar(100))
	INSERT INTO @GetManSTypeId(TypeId) 
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	DECLARE @Total		 NUMERIC(24, 10) ,
			@ATypeId	VARCHAR(50),
			@DraftSql   VARCHAR(50),
			@PFdc		INT=0	--父级流量项目方向
			
	IF @StartDate = '' SET @StartDate = '1900-01-01'
	IF @EndDate = '' SET @EndDate = '2500-12-31'
	
	SELECT 
		@ATypeId = I.TypeId,
		@PFdc=CASE WHEN Par.FullName LIKE '%现金流入%' THEN 1
					WHEN Par.FullName LIKE '%现金流出%' THEN 2
					ELSE 0 END
	FROM Ac_CashMoneyItems I 
	INNER JOIN Ac_CashMoneyItems Par ON Par.Leveal=2 AND I.UserCode = @FlowValue AND I.TypeId LIKE Par.TypeId+'%'
	
	
	IF @Draft = 1 	
		SELECT	@Total = SUM(ISNULL(CASE WHEN @PFdc=1 THEN CASE WHEN C.FDc=C.FAdc THEN Total ELSE -Total END
										 WHEN @PFdc=2 THEN CASE WHEN C.FDc=C.FAdc THEN -Total ELSE Total END
										  ELSE Total 
									END,0) )
		FROM	Ac_Voucher_Bill_CashMoneyItems C
		INNER JOIN Ac_Voucher V ON C.BillNumberId = V.BillNumberId	
		INNER JOIN @GetManSTypeId G ON V.StypeId = G.TypeId
		WHERE	V.BillDate >= @StartDate
				AND V.BillDate <= @EndDate
				AND V.FYear = @FYear
				AND V.FPeriod = @FPeriod
				AND (C.MATypeId LIKE @ATypeId + '%'
				OR C.DATypeId LIKE @ATypeId + '%')
				AND V.STypeId = @STypeId
				AND v.FChecked != -1
	ELSE
		SELECT	@Total =SUM(ISNULL(CASE WHEN @PFdc=1 THEN CASE WHEN C.FDc=C.FAdc THEN Total ELSE -Total END
										 WHEN @PFdc=2 THEN CASE WHEN C.FDc=C.FAdc THEN -Total ELSE Total END
										  ELSE Total 
									END,0) )
		FROM	Ac_Voucher_Bill_CashMoneyItems C
		INNER JOIN Ac_Voucher V ON C.BillNumberId = V.BillNumberId
		INNER JOIN @GetManSTypeId G ON V.StypeId = G.TypeId
		WHERE	V.BillDate >= @StartDate
				AND V.BillDate <= @EndDate
				AND V.FYear = @FYear
				AND V.FPeriod = @FPeriod
				AND ifCheck = 't'
				AND (C.MATypeId LIKE @ATypeId + '%'
				OR C.DATypeId LIKE @ATypeId + '%')
				AND V.STypeId = @STypeId
				AND v.FChecked != -1
			
	RETURN ISNULL(@Total,0)
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_XJLL]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_XJLL]
GO



/*
	作者：谢吉康
	日期：2012-06-05
	描述：取现金流量项目在一段期间内的发生额
	DECLARE @Total  NUMERIC(24, 10) 	
	PRINT(@Total)
*/
CREATE FUNCTION F_XJLL
(
	@STypeId		VARCHAR(50),		-- 分支机构	
	@FYear			VARCHAR(10),		-- 会计年度
	@FPeriod		VARCHAR(10),		-- 会计期间
	@StartDate		VARCHAR(20),		-- 开始日期
	@EndDate		VARCHAR(20),		-- 截至日期	
	@FlowValue		VARCHAR(MAX),		-- 现金流量项目，传入编号
	@Draft			INT,				-- 包含未记账的凭证 0.不包含  1.包含
	@OperatorID		varchar(100)		--操作员ID
)
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS
BEGIN
--分支机构权限检查
	DECLARE @GetManSTypeId TABLE (TypeId varchar(100))
	INSERT INTO @GetManSTypeId(TypeId) 
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	
	DECLARE @Total		 NUMERIC(24, 10) ,
			@ATypeId	VARCHAR(50),
			@DraftSql   VARCHAR(50),
			@PFdc		INT=0	--父级流量项目方向
			
	IF @StartDate = '' SET @StartDate = '1900-01-01'
	IF @EndDate = '' SET @EndDate = '2500-12-31'
	
	SELECT 
		@ATypeId = I.TypeId,
		@PFdc=CASE WHEN Par.FullName LIKE '%现金流入%' THEN 1
					WHEN Par.FullName LIKE '%现金流出%' THEN 2
					ELSE 0 END
	FROM Ac_CashMoneyItems I 
	INNER JOIN Ac_CashMoneyItems Par ON Par.Leveal=2 AND I.UserCode = @FlowValue AND I.TypeId LIKE Par.TypeId+'%'
	
		
	IF @Draft = 1 	
		SELECT	@Total =SUM(ISNULL(CASE WHEN @PFdc=1 THEN CASE WHEN C.FDc=C.FAdc THEN Total ELSE -Total END
										 WHEN @PFdc=2 THEN CASE WHEN C.FDc=C.FAdc THEN -Total ELSE Total END
										  ELSE Total 
									END,0) )
		FROM	Ac_Voucher_Bill_CashMoneyItems C
		INNER JOIN Ac_Voucher V ON C.BillNumberId = V.BillNumberId	
		INNER JOIN @GetManSTypeId G ON V.StypeId = G.TypeId
		WHERE	V.BillDate >= @StartDate
				AND V.BillDate <= @EndDate
				AND V.FYear = @FYear
				AND V.FPeriod <= @FPeriod
				AND (C.MATypeId LIKE @ATypeId + '%'
				OR C.DATypeId LIKE @ATypeId + '%')
				AND V.STypeId = @STypeId
				AND v.FChecked != -1
	ELSE
		SELECT	@Total=SUM(ISNULL(CASE WHEN @PFdc=1 THEN CASE WHEN C.FDc=C.FAdc THEN Total ELSE -Total END
										 WHEN @PFdc=2 THEN CASE WHEN C.FDc=C.FAdc THEN -Total ELSE Total END
										  ELSE Total 
									END,0) )
		FROM	Ac_Voucher_Bill_CashMoneyItems C
		INNER JOIN Ac_Voucher V ON C.BillNumberId = V.BillNumberId
		INNER JOIN @GetManSTypeId G ON V.StypeId = G.TypeId
		WHERE	V.BillDate >= @StartDate
				AND V.BillDate <= @EndDate
				AND V.FYear = @FYear
				AND V.FPeriod <= @FPeriod
				AND ifCheck = 't'
				AND (C.MATypeId LIKE @ATypeId + '%'
				OR C.DATypeId LIKE @ATypeId + '%')
				AND V.STypeId = @STypeId
				AND v.FChecked != -1
			
	RETURN ISNULL(@Total,0)
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='Fn_GetIsUse_Items' )
	DROP FUNCTION [dbo].[Fn_GetIsUse_Items]
GO
-- =============================================
-- 作者:		古丽娟
-- 日期:		2012-06-06
-- 返回:		判断是否使用
-- =============================================
CREATE FUNCTION [dbo].[Fn_GetIsUse_Items]
(
    @id			INT,			--ID 
	@type		INT				--操作类型：1：币种  6：结算方式  9:凭证字 100 存货类型 110 变更原因 ELSE项目,
) 
RETURNS INT     
AS 
BEGIN
	IF(@type=110)
		BEGIN
			RETURN 0
		END
	ELSE IF(@type=100)
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM ptype WHERE InventoryTypeID=@id)
				RETURN 1
		END
	ELSE IF(@type=1)--币种
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill WHERE Cid=@id)
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE Cid=@id)
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM AType_Total WHERE CID=@id)
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM BType_ArApTotal WHERE CID=@id)
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE CID=@id)
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance  WHERE CID=@id)--科目余额表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance_Assist_CheckItems WHERE CID=@id)--科目余额表辅助核算项目
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE CID=@id)--科目余额表辅助核算项目对照表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount WHERE CID=@id)--账务期初
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems WHERE CID=@id)--账务期初辅助核算项目
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE CID=@id)--期初科目余额表辅助核算项目对照表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_ProfitAndLoss WHERE CID=@id)--损益类科目实际发生额表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_ProfitAndLoss_Detail WHERE CID=@id)--损益类科目实际发生额明细表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_RateAdjust  WHERE CID=@id)--期末调汇表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_CashMoneyItems WHERE CID=@id)--会计凭证现金流量项目明细表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM AccountCredence WHERE CID=@id)--业务凭证
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM PriceBillIndex WHERE CID=@id)--价格表档案 
				RETURN 1
			
			 --出纳系统中使用
			IF EXISTS(SELECT TOP 1 1 FROM Te_InitDataIndex WHERE CID=@id)--出纳初始化数据录入 
				RETURN 1				
			IF EXISTS(SELECT TOP 1 1 FROM Te_AccountInTransit_Index WHERE CID=@id)--未达账 
				RETURN 1			
			IF EXISTS(SELECT TOP 1 1 FROM Te_Balance 
			WHERE CID=@id AND ( InitBalance<>0 OR InitBalanceFor<>0 
								OR InitYearBalance<>0 OR InitYearBalanceFor<>0 
								OR FDebit<>0 OR FDebitFor<>0 
								OR FCredit<>0 OR FCreditFor<>0 
								OR FEndBalance<>0 OR FEndBalanceFor<>0 
								OR FYtdDebit<>0 OR FYtdDebitFor<>0
								OR FYtdCredit<>0 OR FYtdCreditFor<>0 
								OR FYtdCredit<>0 OR FYtdCreditFor<>0))--出纳余额 
				RETURN 1			
			IF EXISTS(SELECT TOP 1 1 FROM Te_Journal WHERE CID=@id)--出纳日记账 
				RETURN 1			
			IF EXISTS(SELECT TOP 1 1 FROM Te_Journal_Detail WHERE CID=@id)--出纳日记账明细 
				RETURN 1				
		END
	ELSE IF(@type=6)--结算方式
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill WHERE FSettleTypeID=@id)
				RETURN 1
		END
	ELSE IF(@type=9)--凭证字
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE VgId=@id)--凭证主表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Auditing_Template WHERE VgId=@id )--过账模版主表
				RETURN 1
		END
	ELSE--暂时未细分
		BEGIN
			IF EXISTS(SELECT TOP 1 1 from BillMulAccount WHERE ATypeID=CONVERT(VARCHAR(50),@id) )--多账户收（付）款明细表
				RETURN 1
			DECLARE @TypeName VARCHAR(5)
			SELECT @TypeName=TypeName FROM Ac_Items WHERE nId=@id
			IF(@TypeName<>'B')
				BEGIN
					IF EXISTS(SELECT TOP 1 1 from RetailConfig WHERE ATypeID=CONVERT(VARCHAR(50),@id) )--【零售单配置】
						RETURN 1		
				END	
			IF EXISTS(SELECT TOP 1 1 from MoneyBill WHERE AtypeId=CONVERT(VARCHAR(50),@id))--费用单
				RETURN 1
			IF EXISTS(SELECT TOP 1 1  FROM AType_Total WHERE  ATYPEID=CONVERT(VARCHAR(50),@id) )--期初
				RETURN 1
			IF EXISTS(SELECT TOP 1 1  FROM PreBill WHERE  ATYPEID=CONVERT(VARCHAR(50),@id))--预收
				RETURN 1
			IF EXISTS(SELECT TOP 1 1  FROM AccountCredence WHERE ATYPEID=CONVERT(VARCHAR(50),@id) OR TypeATypeID=CONVERT(VARCHAR(50),@id))--会计凭证
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM MoveMoneyBill WHERE atypeid=CONVERT(VARCHAR(50),@id))--单据
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM gatheringBill WHERE ATypeID=CONVERT(VARCHAR(50),@id))--收款单
				RETURN 1
			IF EXISTS(SELECT TOP 1 1  FROM BillIndex WHERE  ATYPEID=CONVERT(VARCHAR(50),@id))--收款单
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM  OtherInOutType WHERE ATypeID=CONVERT(VARCHAR(50),@id) OR ATypeID1=CONVERT(VARCHAR(50),@id))--其他出库单 业务类别 date:2013-01-29
				RETURN 1 	
			IF EXISTS(SELECT TOP 1 1 FROM  PayBill WHERE ATypeID=CONVERT(VARCHAR(50),@id))--应付
				RETURN 1 
			IF EXISTS(SELECT TOP 1 1 FROM  OrderIndex WHERE ATypeID=CONVERT(VARCHAR(50),@id))--应付
				RETURN 1 	
		END
	RETURN 0--没有被使用
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='Fn_GetIsUsedAssistDetails' )
	DROP FUNCTION [dbo].[Fn_GetIsUsedAssistDetails]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- =============================================
-- 作者:		古丽娟
-- 日期:		2012-06-06
-- 返回:		判断是否使用
-- =============================================
CREATE FUNCTION [dbo].[Fn_GetIsUsedAssistDetails]
(
	@TypeID	VARCHAR(50)
) 
RETURNS INT     
AS 
BEGIN
	DECLARE 
		@AscIds		INT,
		@AUserCode	VARCHAR(200)
		
	--指定明细的类型
	SELECT 
		@AscIds=C.AscIds,
		@AUserCode=C.UserCode 
	FROM Ac_Assist_CheckItemsDetail D 
	INNER JOIN Ac_Assist_CheckItems C ON C.AscIds=D.AscIds AND D.TypeId=@TypeID
	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE Ascids=@AscIds AND FieldValue=@TypeID) OR EXISTS(SELECT TOP 1 1 FROM Ac_ProfitAndLoss_Detail WHERE Ascids=@AscIds AND FieldValue=@TypeID) OR EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE Ascids=@AscIds AND FieldValue=@TypeID) OR EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName=@AUserCode AND TypeId=@TypeID)
	BEGIN
		RETURN  1
	END
	RETURN 0--没有被使用
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetPowerRangeBCList]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[FN_GetPowerRangeBCList]
GO




--@DisPlayFlag 0不显示独立加盟店机构，1显示独立加盟店机构
CREATE    function FN_GetPowerRangeBCList(@OperatorID varchar(50),@ParID varchar(8000)='%')
RETURNS table
AS
RETURN 
( 
/*select p.* from stype p
  where  exists(select 1 from dbo.FN_GetIdStrListTable(@ParID) as b  where (p.TypeId like b.Getid +'%'  and p.sonnum =0 )) and  p.sonnum = 0 and deleted = 0
   and exists(select 1 from UserPowerRange b where  b.basetype = 5 and b.etypeid = @OperatorID and 
   (left(p.TypeId ,len(b.typeid)) = b.typeid  or  b.typeid = '00000') )
   --and not exists(select 1 from employee c where typeid =@OperatorID and left(branchid,5)='00004' and left(p.branchid,5)= '00004'and p.branchid <> c.branchid ) --加盟职员只能选本加盟机构
*/
SELECT * FROM F_GetManSTypeAll(@OperatorID)
)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_MinGetCurrentAuditETypeID]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[FN_MinGetCurrentAuditETypeID]
GO
/*
描述：获取审核顺序
*/

CREATE FUNCTION [dbo].[FN_MinGetCurrentAuditETypeID]
(
	@ETypeID			VARCHAR(50),
	@BillNumberId		BIGINT,
	@STypeId			VARCHAR(50),
	@BillType			INT
)
RETURNS INT
AS
BEGIN
	DECLARE
		@AuditingStep INT
		
		
	SELECT @AuditingStep=MIN(AuditingStep)
	FROM [dbo].FN_GetCurrentAuditETypeID(@BillNumberId,@STypeId,@BillType) 
	WHERE ETypeID = @ETypeID
	
	RETURN @AuditingStep
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_F_GetCxName]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[Pos_F_GetCxName]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年9月6日
-- Description:	根据传入的促销ID查询出促销名称
-- =============================================
CREATE FUNCTION Pos_F_GetCxName 
(
	@CxIdStr  VARCHAR(100)
)
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @Result  VARCHAR(1000)=''
DECLARE @fullname VARCHAR(1000)=''
SELECT @fullname=@fullname+','+BillName FROM CX_SalePlanIndex(NOLOCK) where BillNumberId in(select * from f_split(@CxIdStr,','))
SET @Result= SUBSTRING(@fullname,2,LEN(@fullname))
RETURN @Result

END
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_F_GetVipCode]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[Pos_F_GetVipCode]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年9月6日
-- Description:	根据传入的促销ID查询出促销名称
-- =============================================
CREATE FUNCTION Pos_F_GetVipCode 
(
	@PosVchcode  VARCHAR(MAX) --
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @Result  VARCHAR(MAX)=''
DECLARE @vipid  VARCHAR(MAX)=''
DECLARE @vipcode VARCHAR(MAX)=''
SELECT @vipid=@vipid+','+CAST(VipID AS VARCHAR)  FROM PosVipMoneyList(NOLOCK) WHERE PosVchcode=@PosVchcode
SET @vipid= SUBSTRING(@vipid,2,LEN(@vipid))
SELECT @vipcode=@vipcode+','+VipCardCode FROM nVipCardSign(NOLOCK) WHERE VipCardID IN (SELECT  * FROM f_split(@vipid,',')) 
SET @Result= SUBSTRING(@vipcode,2,LEN(@vipcode))
RETURN @Result
END
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseLineA]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseLineA
go

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseLineB]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseLineB]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseLineC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseLineC
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_BaseLineD') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseLineD
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseLineE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseLineE]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseLineF]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseLineF
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseLineI]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseLineI
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseLineK]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseLineK]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseLineP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseLineP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseAllTreeA]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseAllTreeA
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseAllTreeB]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseAllTreeB]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseAllTreeC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseAllTreeC
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_BaseAllTreeD') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseAllTreeD
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseAllTreeE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseAllTreeE]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseAllTreeF]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseAllTreeF
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseAllTreeI]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseAllTreeI
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseAllTreeK]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseAllTreeK]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseAllTreeP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseAllTreeP]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_BaseAllTreeS') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseAllTreeS
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeA]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseTreeA]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeB]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseTreeB]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseTreeC
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeD]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseTreeD]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseTreeE]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeF]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseTreeF
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeI]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_BaseTreeI
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeK]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseTreeK]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseTreeP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseTreeP]
GO

--------------------------------------------------删除废弃权限函数BEGIN-------------------------------------------------------------------------------------
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeBank]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_AllTreeBank]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeA]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeA]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeC]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeD]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeD]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeE]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeF]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeF]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeGxExpense]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeGxExpense]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeGxIncome]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeGxIncome]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeGxInDebt]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeGxInDebt]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeI]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeI]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeK]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeK]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeOwnerEquityT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeOwnerEquityT]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreePCategory]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreePCategory]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineC]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineGxAssetsT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineGxAssetsT]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineGxExpenseC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineGxExpenseC]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineGxIncomeC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineGxIncomeC]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineGxInDebtT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineGxInDebtT]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineI]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineI]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineInDebtT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineInDebtT]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineOwnerEquityT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineOwnerEquityT]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetAllBaseTypeIdFromUOrFLike]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetAllBaseTypeIdFromUOrFLike]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_BaseGetManSTypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_BaseGetManSTypeAll]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllBaseTypeIdFromUOrFLikeMatch]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllBaseTypeIdFromUOrFLikeMatch]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllBaseTypeIdFromUOrFLikeSonNum0]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllBaseTypeIdFromUOrFLikeSonNum0]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetManDetailATypeYSYF]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetManDetailATypeYSYF]
GO
---------------------------------------------------删除废弃权限函数  END------------------------------------------------------------------------------------







/****** Object:  UserDefinedFunction [dbo].[F_GetAllBaseInfoTypeId]    Script Date: 12/03/2012 17:17:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F_GetAllBaseInfoTypeId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[F_GetAllBaseInfoTypeId]
GO


/****** Object:  UserDefinedFunction [dbo].[F_GetAllBaseInfoTypeId]    Script Date: 12/03/2012 17:17:14 ******/
SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO


/*
	作者：谢吉康
	日期：2010-07-15
	描述：获取基本信息的节点ID，带了权限范围
	
	日期：2012-11-30
	作者：王伟峰
	描述：调整权限统一函数
*/
CREATE  FUNCTION [dbo].[F_GetAllBaseInfoTypeId]
(
	@TypeId			varchar(max),	--需要拆分的基本信息ID
	@Flag			int,			--基本信息的标识 1.商品 2.往来单位 3.职员等
	@OperatorId		varchar(100),	--当前操作员的ID
	@Temp			VARCHAR(50)		--临时表名称	
)	
RETURNS varchar(max)
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	DECLARE @rString	varchar(MAX)=''
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)
	 
	DECLARE @BaseTypeId		varchar(100)

	IF @Flag = 1			--商品
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000')
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM PType A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0;'+CHAR(13)
			ELSE
			BEGIN
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	PType_L L
							INNER JOIN PType  A ON A.TypeId LIKE L.TypeId + ''%'' '
				IF @TypeId<>'%'
					SET @rString=@rString+' INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%'' '
				
				SET @rString=@rString+'	WHERE	L.etypeid = '''+@OperatorId+'''
								AND L.flag = 1 
								AND A.sonnum = 0;'+CHAR(13)
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
			END					
		END
	ELSE IF @Flag = 2		--往来单位
		BEGIN
		
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND (MangerBTypeID = '00001' AND MangerBTypeID2 = '00002')) AND @TypeId='%'
			RETURN @rString
			--客户,供货商
		 	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND (MangerBTypeID = '00001' AND MangerBTypeID2 = '00002'))
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM BType A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0;'+CHAR(13)
				
			ELSE
			BEGIN
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	BType_L L
							INNER JOIN BType  A ON A.TypeId LIKE L.TypeId + ''%'''
				IF @TypeId<>'%'
					SET @rString=@rString+' INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%'' '
				
				SET @rString=@rString+'	WHERE	L.etypeid = '''+@OperatorId+'''
								AND L.flag = 1 
								AND A.sonnum = 0;'+CHAR(13)
								
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
			END
		END
	ELSE IF @Flag = 3		--职员
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeID = '00001') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeID = '00001')
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM Employee A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							UNION ALL
							SELECT ''00001'';'+CHAR(13)
				
			ELSE
			BEGIN
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	EType_L L
							INNER JOIN Employee  A ON A.TypeId LIKE L.TypeId + ''%'''
				IF @TypeId<>'%'
					SET @rString=@rString+' INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%'' '
				
				SET @rString=@rString+'	WHERE	L.etypeid = '''+@OperatorId+'''
								AND L.flag = 1 
								AND A.sonnum = 0;'+CHAR(13)	
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
			END
		END						
	ELSE IF @Flag = 4		--仓库
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerKTypeID = '00000') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerKTypeID = '00000')
			BEGIN
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM Stock A '
				IF @TypeId<>'%' AND @TypeId<>'10000'
					SET @rString=@rString+' INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%'' '
					
				SET @rString=@rString+'WHERE A.SonNum = 0'+CHAR(13)
			END	
			ELSE
			BEGIN
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	KType_L L
							INNER JOIN Stock  A ON A.TypeId LIKE L.TypeId + ''%''
							'
				IF @TypeId<>'%' AND @TypeId<>'10000'
					SET @rString=@rString+' INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%'' '
				
				SET @rString=@rString+'	WHERE	L.etypeid = '''+@OperatorId+'''
								AND L.flag = 1 
								AND A.sonnum = 0 '
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '				
			END
			IF @TypeId='10000'
				SET @rString=@rString+'UNION ALL SELECT ''10000'''+CHAR(13)
				SET @rString=@rString+';'+CHAR(13)
		END
	ELSE IF @Flag = 5		--现金银行
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '0000') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '0000')
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT nId 
							FROM Ac_Items A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							AND TypeName=''B'' AND UserCode NOT IN(''2181'',''2131'',''1151'')
							;'+CHAR(13)
				
			ELSE
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	Atype_L L
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON L.TypeId LIKE B.A+''%''
							WHERE	L.etypeid = '''+@OperatorId+'''
									AND L.Type = 0;'+CHAR(13)
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
		END
	ELSE IF @Flag = 6		--费用
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerExpense = '0000') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerExpense = '0000')
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT nId 
							FROM Ac_Items A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							AND TypeName=''E'' AND UserCode NOT IN(''0404'',''0421'',''0422'',''0423'',''0424'',''5401'')
							;'+CHAR(13)
				
			ELSE
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	Atype_L L
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON L.TypeId LIKE B.A+''%''
							WHERE	L.etypeid = '''+@OperatorId+'''
									AND L.Type = 1;'+CHAR(13)
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
		END	
	ELSE IF @Flag = 7		--收入
		BEGIN 
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerIncome = '0000') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerIncome = '0000')
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT nId 
							FROM Ac_Items A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							AND  TypeName=''G'' AND UserCode NOT IN (''0321'',''0322'',''0323'',''0324'',''0325'',''0326'',''0328'',''0329'',''5101'',''5103'')
							;'+CHAR(13)
				
			ELSE
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	Atype_L L
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON L.TypeId LIKE B.A+''%''
							WHERE	L.etypeid = '''+@OperatorId+'''
									AND L.Type = 2;'+CHAR(13)
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
		END	
	ELSE IF @Flag = 8		--资产
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerCpaital = '0000') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerCpaital = '0000')
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT nId 
							FROM Ac_Items A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							AND  TypeName=''F''
							;'+CHAR(13)
				
			ELSE
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	Atype_L L
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON L.TypeId LIKE B.A+''%''
							WHERE	L.etypeid = '''+@OperatorId+'''
									AND L.Type = 3
									AND L.flag=0;'+CHAR(13)
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
		END
	ELSE IF @Flag = 9		--部门
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerDTypeID = '00000') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerDTypeID = '00000')
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM Department A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							;'+CHAR(13)
				
			ELSE
			BEGIN
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	DType_L L
							INNER JOIN Department  A ON A.TypeId LIKE L.TypeId + ''%'''
				IF @TypeId<>'%'
					SET @rString=@rString+' INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%'' '
				
				SET @rString=@rString+'	WHERE	L.etypeid = '''+@OperatorId+'''
								AND L.flag = 1 
								AND A.sonnum = 0;'+CHAR(13)
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
			END
		END
	ELSE IF @Flag = 10		--地区
		BEGIN
			SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM AreaType A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							;'+CHAR(13)
		END
	ELSE IF @Flag = 11			--分支机构
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000') AND @TypeId='%'
			RETURN @rString
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM SType A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							;'+CHAR(13)
				
			ELSE
			BEGIN
				SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT	A.TypeId 
							FROM	SType_L L
							INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + ''%'''
				IF @TypeId<>'%'
					SET @rString=@rString+' INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%'' '
				
				SET @rString=@rString+'	WHERE	L.etypeid = '''+@OperatorId+'''
								AND L.flag = 1 
								AND A.sonnum = 0;'+CHAR(13)
				SET @rString=@rString+' IF NOT EXISTS(SELECT 1 FROM '+@Temp+') INSERT INTO '+@Temp+' VALUES(-1234) '
			END
		END
	ELSE IF @Flag = 12			--车牌号
		BEGIN
			SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM QP_RepairAutoInfo A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							;'+CHAR(13)	
		END
	ELSE IF @Flag = 13			--维修项目
		BEGIN
			SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM QP_RepairItems A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							;'+CHAR(13)		
		END			
	ELSE IF @Flag = 14			--维修车型
		BEGIN
			SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM QP_RepairAutoType A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							;'+CHAR(13)			
		END	
	ELSE IF @Flag = 15			--凭证字
		BEGIN
			SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT VgId 
							FROM Ac_Voucher_Group A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							
							;'+CHAR(13)								
		END
	ELSE IF @Flag = 16			--币别
		BEGIN
			SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT CId 
							FROM Ac_Currency A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							
							;'+CHAR(13)						
		END		
	ELSE IF @Flag = 17			--货位
		BEGIN
			SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT CargoID 
							FROM CargoType A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							
							;'+CHAR(13)				
		END
			
	ELSE IF @Flag = 18			--总账会计科目
		BEGIN
			SET @rString='INSERT INTO '+@Temp+'(TypeId) 
							SELECT TypeID 
							FROM Ac_Account A
							INNER JOIN dbo.F_Split('''+@TypeId+''','','') B ON A.TypeId LIKE B.A+''%''
							WHERE A.SonNum = 0
							;'+CHAR(13)			
		END		
						
	RETURN @rString
END

























GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS(SELECT * FROM dbo.sysobjects WHERE name='F_GetCouponTypeInfoBaseNames')
	DROP FUNCTION [dbo].[F_GetCouponTypeInfoBaseNames]
GO          

/*
	作者：谢吉康
	日期：2017-11-07
	描述：获取优惠券所辖分支机构或者适用商品
*/
CREATE FUNCTION [dbo].[F_GetCouponTypeInfoBaseNames]
(
	@CouponId			INT,			--优惠券ID	
	@Flag				INT				--标识   1.分支机构  2.商品
)
RETURNS VARCHAR(MAX)
AS 
BEGIN
	DECLARE @RetStr			VARCHAR(MAX)='',
			@I				INT,
			@nCount			INT,
			@tmpStr			VARCHAR(500),
			@ResultStr		VARCHAR(MAX)=''
		
	IF @Flag = 1
	BEGIN
		DECLARE @applyStype TABLE(nid INT IDENTITY(1,1),FullName VARCHAR(500))		
		INSERT INTO @applyStype(FullName) 
		SELECT DISTINCT S.FullName FROM dbo.coupon_ApplyStype cs INNER JOIN Stype S ON S.TypeId = Cs.StypeId
		WHERE CouponId = @CouponId
		SET @nCount = @@ROWCOUNT		
		SET @i = 1		
		WHILE @I <= @nCount
		BEGIN
			SELECT @tmpStr = FullName FROM @applyStype WHERE nid = @I
			IF @tmpStr = '总部'
			BEGIN
				SET @ResultStr = @ResultStr + ';'+ '全部分支机构'
			END
			ELSE
			BEGIN
				SET @ResultStr = @ResultStr + ';'+@tmpStr
			END
			SET @I = @I + 1
		END
	END
	
	IF @ResultStr <> ''
	BEGIN
		SET @RetStr = RIGHT(@ResultStr,LEN(@ResultStr)-1)
	END
	
	RETURN @RetStr
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F_GetPtypeUnitsAndRates]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[F_GetPtypeUnitsAndRates]
GO


SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO


/*

	日期：2012-12-14
	作者：王伟峰
	描述：返回多单位名称和汇率的函数
*/
CREATE  FUNCTION [dbo].[F_GetPtypeUnitsAndRates]
(
	@Malias			varchar(8000),	--需要连接的主表别名
	@Units			varchar(100),	--多单位名称列表：1、基本单位 2、采购单位 3、销售单位 4、库存单位 5、辅助单位
	@Rates			varchar(100)	--多单位汇率   2、采购单位 3、销售单位  4、库存单位	
)	
RETURNS varchar(8000)
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	DECLARE @rString	varchar(6000)
	SET @rString=''
		BEGIN
			
			IF CHARINDEX('1',@Units)>0
				SET @rString=@rString+' LEFT JOIN dbo.PType_Units u1 ON  u1.UnitsId = '+@Malias+'.baseUnitId'+CHAR(13)
			IF CHARINDEX('2',@Units)>0
				SET @rString=@rString+' LEFT JOIN dbo.PType_Units u2 ON  u2.UnitsId = '+@Malias+'.BuyUnitId'+CHAR(13)
			IF CHARINDEX('3',@Units)>0
				SET @rString=@rString+' LEFT JOIN dbo.PType_Units u3 ON  u3.UnitsId = '+@Malias+'.SaleUnitId'+CHAR(13)
			IF CHARINDEX('4',@Units)>0
				SET @rString=@rString+' LEFT JOIN dbo.PType_Units u4 ON  u4.UnitsId = '+@Malias+'.StockUnitId'+CHAR(13)
			IF CHARINDEX('5',@Units)>0
				SET @rString=@rString+' LEFT JOIN dbo.PType_Units u5 ON  u5.UnitsId = '+@Malias+'.AssistantUnitId'+CHAR(13)
			
			IF CHARINDEX('1',@Rates)>0
				SET @rString=@rString+' LEFT JOIN PType_Units_Ext r1 ON r1.PTypeId = '+@Malias+'.TypeId AND '+@Malias+'.baseUnitId = r1.UnitsId'+CHAR(13)
			IF CHARINDEX('2',@Rates)>0
				SET @rString=@rString+' LEFT JOIN PType_Units_Ext r2 ON r2.PTypeId = '+@Malias+'.TypeId AND '+@Malias+'.BuyUnitId = r2.UnitsId'+CHAR(13)
			IF CHARINDEX('3',@Rates)>0
				SET @rString=@rString+' LEFT JOIN PType_Units_Ext r3 ON r3.PTypeId = '+@Malias+'.TypeId AND '+@Malias+'.SaleUnitId = r3.UnitsId'+CHAR(13)	
			IF CHARINDEX('4',@Rates)>0
				SET @rString=@rString+' LEFT JOIN PType_Units_Ext r4 ON r4.PTypeId = '+@Malias+'.TypeId AND '+@Malias+'.StockUnitId = r4.UnitsId'+CHAR(13)		
					
		END
	
	RETURN @rString
END

























GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_ManPTypePageNo]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_ManPTypePageNo
GO

/*
	作者：谢吉康
	日期：2018-6-15
	描述：根据操作员，商品ID，商品类别来获取权限范围内的商品信息
	SELECT * FROM F_ManPTypePageNo('00001','00000',1,14)
*/
CREATE FUNCTION F_ManPTypePageNo
(
	@chvOperatorId	VARCHAR(100),	--操作员ID
	@parid			VARCHAR(50),	--商品父节点	
	@bPageNo		INT,			--页码
	@bCount			INT				--每页显示行数
)
RETURNS @Temp TABLE
(
	TypeId			VARCHAR(50),
	Parid			VARCHAR(50),
	UserCode		VARCHAR(200),
	FullName		VARCHAR(200),
	SonNum			INT,
	Deleted			INT,
	AssistantUnitId INT
)
--@Encode$--
AS
BEGIN
	DECLARE @sonnum INT
	
	SELECT @sonnum = sonnum FROM PType WHERE TypeId = @parid
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.loginuser WHERE etypeid = @chvOperatorId AND MangerPTypeID = '00000')
	BEGIN
		IF @sonnum = 0
		BEGIN
			INSERT INTO @Temp
			( 
				TypeId ,
				Parid ,
				UserCode ,
				FullName ,
				SonNum ,				
				Deleted ,
				AssistantUnitId 
				
			)
			SELECT  TOP (@bCount)
					TypeId ,
					Parid ,
					UserCode ,
					FullName ,
					SonNum ,				
					Deleted ,
					AssistantUnitId 
			FROM    PType 
			WHERE	TypeId = @parid
					AND UserCode NOT IN                    
					(
						SELECT  TOP ((@bPageNo-1) * @bCount) UserCode
						FROM	PType p									
						WHERE	TypeId = @parid
						ORDER BY UserCode
					) 
			ORDER BY UserCode 
		END
		ELSE
		BEGIN
			INSERT INTO @Temp
			( 
				TypeId ,
				Parid ,
				UserCode ,
				FullName ,
				SonNum ,				
				Deleted ,
				AssistantUnitId 
			)
			SELECT  TOP (@bCount)
					TypeId ,
					Parid ,
					UserCode ,
					FullName ,
					SonNum ,				
					Deleted ,
					AssistantUnitId 
			FROM    PType 
			WHERE	ParId = @parid
					AND UserCode NOT IN                    
					(
						SELECT  TOP ((@bPageNo-1) * @bCount) UserCode
						FROM	PType p									
						WHERE	ParId = @parid
						ORDER BY UserCode
					) 
			ORDER BY UserCode
		END		
	END
	ELSE
	BEGIN
		IF @sonnum = 0
		BEGIN
			INSERT INTO @Temp
			( 
				TypeId ,
				Parid ,
				UserCode ,
				FullName ,
				SonNum ,				
				Deleted ,
				AssistantUnitId 
			)	
			SELECT  TOP (@bCount)
					TypeId ,
					Parid ,
					UserCode ,
					FullName ,
					SonNum ,				
					Deleted ,
					AssistantUnitId 
			FROM    PType 
			WHERE	TypeId = @parid
					AND UserCode NOT IN                    
					(
						SELECT  TOP ((@bPageNo-1) * @bCount) UserCode
						FROM	dbo.F_GetManPTypeAll(@chvOperatorId)
						WHERE	TypeId = @parid
						ORDER BY UserCode
					) 
			ORDER BY UserCode 
		END
		ELSE
		BEGIN
			INSERT INTO @Temp
			( 
				TypeId ,
				Parid ,
				UserCode ,
				FullName ,
				AssistantUnitId ,
				Deleted ,
				SonNum
			)	
			SELECT  TOP (@bCount)
					TypeId ,
					Parid ,
					UserCode ,
					FullName ,
					SonNum ,				
					Deleted ,
					AssistantUnitId 
			FROM    PType 
			WHERE	ParId = @parid
					AND UserCode NOT IN                    
					(
						SELECT  TOP ((@bPageNo-1) * @bCount) UserCode
						FROM	dbo.F_GetManPTypeAll(@chvOperatorId)
						WHERE	ParId = @parid
						ORDER BY UserCode
					) 
			ORDER BY UserCode 	
		END
	END	
	
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineA]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_LineA
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖现金银行-线性表
	9.7 增加预收/预付
*/
CREATE FUNCTION F_LineA
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeID,nId FROM Ac_Items WHERE SonNum = 0 AND (TypeName='B' OR UserCode IN('1151','2131','2191')) --AND (nTypeId LIKE '0000100004%' OR nTypeId = '0000100003')
	ELSE	
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT DISTINCT nTypeId,nId FROM(
			SELECT	a.nTypeId ,a.nId
			FROM	AType_L L
			INNER JOIN  Ac_Items a ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
			WHERE	L.etypeid = @chvOperatorId
					AND L.type = '0' 
					AND A.sonnum = 0
					AND (TypeName='B' OR UserCode IN ('1151','2131'))
			UNION ALL
			SELECT nTypeId,nId FROM Ac_Items WHERE UserCode in('2191') AND Sysrow=1
		) F
	RETURN
END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineAccount]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineAccount]
GO


/*
	作者：wg 
	日期：2014-11-14
	描述：获取所有管辖的会计科目-线性表
*/
CREATE FUNCTION F_LineAccount
(
	@OperatorId			VARCHAR(50),
	@Stypeid			VARCHAR(MAX)
)
RETURNS @Temp TABLE(Stypeid VARCHAR(50),Typeid VARCHAR(50))
--@Encode$--
AS
BEGIN

	IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_L WHERE etypeid=@OperatorId AND stypeid='00000' AND typeid='00000' AND flag=1)
	BEGIN
		INSERT INTO @Temp(Stypeid,Typeid)
			SELECT S.TypeId,A.TypeId
			FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) S
			INNER JOIN Ac_Account A ON A.StypeId = S.TypeId
			WHERE A.SonNum = 0
	END
	ELSE
	BEGIN
		INSERT INTO @Temp(Stypeid,Typeid)
		SELECT L.stypeid,A.TypeId
		FROM Ac_Account_L L
		INNER JOIN F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) S ON S.TypeId = L.stypeid
		INNER JOIN Ac_Account  A ON A.StypeId=L.stypeid AND A.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @OperatorId
				AND L.typeid <> '00000'
				AND L.flag = 1 
				AND A.sonnum = 0
		GROUP BY L.stypeid,A.TypeId  --去一次重复，因为ac_account_l里面可能会同时有父类和其子类，而关联条件里面用的是like，那么这个子类就会重复统计，参考mj2229。2016-09-29 11:34:27
				
		UNION ALL
		
		SELECT L.stypeid,A.TypeId
		FROM Ac_Account_L L
		INNER JOIN Ac_Account A ON A.StypeId = L.stypeid
		INNER JOIN F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) S ON S.TypeId = L.stypeid
		WHERE	L.etypeid = @OperatorId
				AND L.typeid = '00000'
				AND L.flag = 1 
				AND A.sonnum = 0
		
	END
		
		
	RETURN
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineAssetsT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineAssetsT]
GO


/*
	作者：duguolei	
	日期：2013-05-16
	描述：获取所有管辖(其他资产+固定资产+银行账户)-线性表
*/
CREATE FUNCTION F_LineAssetsT
(
	@chvOperatorId			varchar(100)
)
RETURNS @table TABLE(NID INT,typeid VARCHAR(50))
--@Encode$--
AS
BEGIN

DECLARE @ver VARCHAR(5) --判断是否是V3
SELECT @ver=s.subvalue FROM dbo.sysdata s WHERE s.SubName='proinfo'


DECLARE @cardmode VARCHAR(5)  --是否是卡片模式
SELECT  @cardmode=SubValue FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1'


	INSERT INTO @table
		SELECT  nId ,
				nTypeId 
		FROM  (
						SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '0000')
								AND TypeName ='C'
								AND nTypeId <> '00000' 
								AND nTypeId LIKE '00001%' 
								AND SonNum=0
								AND nTypeId<>'0000100009'
					    UNION ALL 
					    SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID  = '0000')
								AND (TypeName ='B'   OR  nTypeId='0000100009')
								AND nTypeId <> '00000' 
								AND nTypeId LIKE '00001%'
								AND SonNum=0
						UNION ALL 
					    SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
								AND	(CASE @cardmode WHEN 1 THEN '3' ELSE '2' END )='2'  --如果卡片模式不差固定资产所有权限0000
							    AND TypeName ='F'
								AND nTypeId <> '00000' 
								AND nTypeId LIKE '0000100002%' 
						UNION ALL
						SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '-99999')
								AND SonNum=0
								AND l.etypeid=@chvOperatorId
								AND TypeName='F'
								AND L.type='3'
						UNION ALL
						SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID  = '-99999')
								AND SonNum=0
								AND l.etypeid=@chvOperatorId
								AND (TypeName='B' OR  a.nTypeId='0000100009' )
								AND  L.type='0'
								
						UNION ALL
						SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '-99999')
								AND SonNum=0
								AND l.etypeid=@chvOperatorId
								AND TypeName='C'
								AND L.type='4'
								AND a.nTypeId<>'0000100009'
					) a
		 WHERE  
				(CASE @ver WHEN 1 THEN a.UserCode ELSE '99999' END )<>'1132' 
				AND (CASE @cardmode WHEN 1 THEN a.nId ELSE '99999' END )<>'46'--卡片模式去掉固定资产
				AND (CASE @cardmode WHEN 1 THEN a.nId ELSE '99999' END )<>'26'--卡片模式去掉固定资产
				AND UserCode<>'SYC-1602' 
				AND UserCode<>'SYC-1601' 
		

	RETURN
END




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineB]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineB]
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-线性表
*/
CREATE FUNCTION F_LineB
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @TypeId varchar(100)
	--客户
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE  SonNum = 0 AND TypeId LIKE '00001%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND B.sonnum = 0
				AND B.typeId LIKE '00001%'

	--供货商
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE  SonNum = 0 AND TypeId LIKE '00002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND B.sonnum = 0
				AND B.typeId LIKE '00002%'

	RETURN
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineBank]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineBank]
GO

/*------------------------------------------
	作者：王刚
	日期：2011-07-02
	描述：获取所有管辖 出纳管理银行账户-线性表
-------------------------------------------*/
CREATE FUNCTION F_LineBank
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBankID = '00000')
		INSERT INTO @Temp(TypeId) SELECT id  FROM Te_BankAccount 
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	L.TypeID
		FROM	bank_l L
		WHERE	L.etypeid = @chvOperatorId 
				AND L.flag=1
	RETURN
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_LineD') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_LineD
GO



/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖部门-线性表
*/
CREATE FUNCTION F_LineD
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerDTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Department WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	D.TypeId 
		FROM	DType_L L
		INNER JOIN Department D ON D.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND D.sonnum = 0

	RETURN
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineE]
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有权限范围内管辖职员-线性表
*/
CREATE FUNCTION F_LineE
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '00001')		
		BEGIN
			INSERT INTO @Temp(TypeId)VALUES('00001')
			INSERT INTO @Temp(TypeId) SELECT TypeID FROM Employee WHERE SonNum = 0
		END
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	E.TypeId 
		FROM	EType_L L
		INNER JOIN Employee  E ON E.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND E.sonnum = 0

	RETURN
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineExpenseC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_LineExpenseC
GO


/*
	作者：duguolei	
	日期：2013-05-16
	描述：获取所有支出类(费用类型+管辖支出)-线性表
*/
CREATE FUNCTION F_LineExpenseC
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nid INT,typeid VARCHAR(50))
--@Encode$--
AS
BEGIN
	
		INSERT INTO @Temp(nid,typeid) 
			SELECT  nid,ntypeid
			FROM  (
						SELECT nId,nTypeId 
						FROM dbo.Ac_Items 
						WHERE  EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
							   AND SonNum = 0 
							   AND TypeName='E' 
								AND (nTypeId LIKE '0000400003%'  OR nParId LIKE '0000400003%' OR nTypeId='00004')
								AND UserCode NOT IN ('042','0404','5401')
								AND nTypeId NOT LIKE '0000400002%'
						UNION 
						SELECT nId,nTypeId 
						FROM dbo.Ac_Items 
						WHERE  EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPay = '0000')
							   AND SonNum = 0 
							   AND TypeName='E' 
								AND (nTypeId LIKE '00004%' OR nTypeId LIKE '0000400002%' OR nTypeId LIKE '0000400001' OR nTypeId LIKE '0000400004' OR nParId='00004' OR nParId LIKE '0000400002%')
								AND UserCode NOT IN ('043')
								AND nTypeId NOT LIKE '0000400003%'
						UNION 
						SELECT	A.nId,nTypeId
						FROM	AType_L L
								INNER JOIN  Ac_Items A ON ( (L.flag=0 AND a.nTypeId=L.typeid AND A.sonnum = 0) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%' AND A.sonnum = 0))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '-99999')
								AND L.etypeid =@chvOperatorId
								AND L.type = '1' 
								AND A.nTypeId LIKE '00004%'
						UNION 
						SELECT	A.nId,nTypeId
						FROM	AType_L L
								INNER JOIN  Ac_Items A ON ( (L.flag=0 AND a.nTypeId=L.typeid AND A.sonnum = 0) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%' AND A.sonnum = 0))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPay = '-99999')
								AND L.etypeid =@chvOperatorId
								AND L.type='7'
								AND A.nTypeId LIKE '00004%'
			) a

	RETURN
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineF]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_LineF
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有费用类型-线性表
*/
CREATE FUNCTION F_LineF
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nTypeId varchar(100),nid INT)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
		INSERT INTO @Temp(nTypeId,nid) SELECT nTypeId,nId FROM dbo.Ac_Items WHERE  SonNum = 0 AND TypeName='E' AND nTypeId LIKE '0000400003%'
	ELSE
		INSERT INTO @Temp(nTypeId,nid) 
		SELECT	a.nTypeId,A.nId 
		FROM	AType_L L
		INNER JOIN Ac_Items A ON A.nTypeId LIKE L.TypeId +'%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND A.sonnum = 0
				AND L.type = '1'
				AND A.nTypeId LIKE '0000400003%'
	RETURN
END





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineIncomeC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_LineIncomeC
GO


/*
	作者：duguolei	
	日期：2013-05-16
	描述：获取所有收入类(管辖其他收入+管辖收入)-线性表
*/
CREATE FUNCTION F_LineIncomeC
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nid INT,typeid VARCHAR(50))
--@Encode$--
AS
BEGIN
	 INSERT  INTO @Temp( nid,TypeId)
            SELECT  nid ,
                    TypeId
            FROM    ( SELECT    nid ,
                                nTypeId AS typeid
                      FROM      dbo.Ac_Items
                      WHERE     EXISTS ( SELECT TOP 1 1 FROM  LoginUser WHERE  ETypeId = @chvOperatorId AND MangerIncome = '0000' )
								AND SonNum=0
                                AND TypeName = 'G'
                                AND nTypeId <> '00000'
								AND (nTypeId LIKE '0000300003%' OR nTypeId = '00003' OR nParId LIKE '0000300003%') 
								AND UserCode NOT IN ('5103','5101','032')
								AND nTypeId NOT LIKE '0000300002%'
                      UNION 
                      SELECT    nid ,
                                nTypeId AS typeid
                      FROM      dbo.Ac_Items
                      WHERE     EXISTS ( SELECT TOP 1 1 FROM   LoginUser WHERE  ETypeId = @chvOperatorId AND MangerRevenue = '0000' )
								AND SonNum=0
                                AND TypeName = 'G'
                                AND nTypeId <> '00000'
								AND (nTypeId LIKE '00003%' OR nTypeId LIKE '0000300002%' OR nTypeId LIKE '0000300001%' OR nParId='00003' OR nTypeId LIKE '0000300004%'  OR nParId LIKE '0000300002%')
								AND UserCode NOT IN ('5102')
								AND nTypeId NOT LIKE '0000300003%'
                      UNION 
                      SELECT	DISTINCT
                                nid ,
                                ac.nTypeId AS typeid
                      FROM      dbo.Ac_Items ac
                                INNER JOIN AType_L L ON ( ( L.flag = 0 AND ac.nTypeId = L.typeid) OR ( L.Flag = 1 AND ac.nTypeId LIKE L.TypeId + '%' ) )
                      WHERE     EXISTS ( SELECT TOP 1 1 FROM   LoginUser WHERE  ETypeId = @chvOperatorId AND MangerIncome = '-99999' )
								AND SonNum=0
                                AND l.etypeid = @chvOperatorId
                                AND TypeName = 'G'
                                AND L.type = '2'
                      UNION 
                      SELECT	DISTINCT
                                nid ,
                                ac.nTypeId AS typeid
                      FROM      dbo.Ac_Items ac
                                INNER JOIN AType_L L ON ( ( L.flag = 0 AND ac.nTypeId = L.typeid) OR ( L.Flag = 1 AND ac.nTypeId LIKE L.TypeId + '%' ) )
                      WHERE     EXISTS ( SELECT TOP 1 1 FROM   LoginUser WHERE  ETypeId = @chvOperatorId AND MangerRevenue = '-99999' )
								AND SonNum=0
                                AND l.etypeid = @chvOperatorId
                                AND TypeName = 'G'
                                AND L.type = '6'
                    ) a

				
	RETURN
END





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineK]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineK]
GO



/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有权限范围内仓库-线性表
*/
CREATE FUNCTION F_LineK
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM Stock WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	K.TypeId 
		FROM	KType_L L
		INNER JOIN Stock  K ON K.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND K.sonnum = 0

	RETURN
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LineP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_LineP]
GO




/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖商品-线性表
*/
CREATE FUNCTION F_LineP
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	TypeId varchar(100)
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType WHERE SonNum = 0
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	P.TypeId 
		FROM	PType_L L
		INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag = 1 
				AND P.sonnum = 0

	RETURN
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LinePC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_LinePC
GO




/*

*/
CREATE FUNCTION F_LinePC
(
	@chvOperatorId	varchar(100),
	@pctypeid		VARCHAR(max)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
	BEGIN
		IF ISNULL(@pctypeid,'')<>''
			INSERT INTO @Temp(TypeId) 
			SELECT p.TypeID FROM PType p,dbo.F_Split(@pctypeid,',') b WHERE p.SonNum = 0 AND p.PTypeCategoryid LIKE b.a+'%'
		ELSE
			INSERT INTO @Temp(TypeId) 
			SELECT p.TypeID FROM PType p WHERE p.SonNum = 0 
		
	END
	ELSE
	BEGIN
		IF ISNULL(@pctypeid,'')<>''
			INSERT INTO @Temp(TypeId) 
			SELECT	P.TypeId 
			FROM	PType_L L
			INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
			INNER JOIN  dbo.F_Split(@pctypeid,',') b ON p.PtypeCategoryID LIKE b.a+'%'
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag = 1 
					AND P.sonnum = 0
		ELSE
			INSERT INTO @Temp(TypeId) 
			SELECT	P.TypeId 
			FROM	PType_L L
			INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
			WHERE	L.etypeid = @chvOperatorId
					AND L.flag = 1 
					AND P.sonnum = 0
	END			
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_LinePC_Copy]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_LinePC_Copy
GO

/*
	作者：陈强
	日期：2019-09-23
	描述：获取所有管辖商品-线性表
	对应版本：9.91
*/
CREATE FUNCTION F_LinePC_Copy
(
	@chvOperatorId	varchar(100),
	@pctypeid		VARCHAR(max),
	@stopBuy		int=0
)
RETURNS @Temp TABLE(TypeId varchar(100),NID VARCHAR(50))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
	BEGIN
		IF ISNULL(@pctypeid,'')<>''
			IF @stopBuy=0
			BEGIN
				INSERT INTO @Temp(TypeId,NID) 
				SELECT p.TypeID,p.InventoryTypeID FROM PType p,dbo.F_Split(@pctypeid,',') b WHERE p.SonNum = 0 
				AND p.PTypeCategoryid LIKE b.a+'%' AND p.StopBuy=@stopBuy
			END
			ELSE
			BEGIN
				INSERT INTO @Temp(TypeId,NID) 
				SELECT p.TypeID,p.InventoryTypeID FROM PType p,dbo.F_Split(@pctypeid,',') b WHERE p.SonNum = 0 
				AND p.PTypeCategoryid LIKE b.a+'%' 
			END
		ELSE
			IF @stopBuy=0
				INSERT INTO @Temp(TypeId,NID) 
				SELECT p.TypeID,p.InventoryTypeID FROM PType p WHERE p.SonNum = 0  AND p.StopBuy=@stopBuy
			ELSE
				INSERT INTO @Temp(TypeId,NID) 
				SELECT p.TypeID,p.InventoryTypeID FROM PType p WHERE p.SonNum = 0 
		
	END
	ELSE
	BEGIN
		IF ISNULL(@pctypeid,'')<>''
			IF @stopBuy=0
				INSERT INTO @Temp(TypeId,NID) 
				SELECT	P.TypeId ,p.InventoryTypeID
				FROM	PType_L L
				INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
				INNER JOIN  dbo.F_Split(@pctypeid,',') b ON p.PtypeCategoryID LIKE b.a+'%'
				WHERE	L.etypeid = @chvOperatorId
						AND L.flag = 1 
						AND P.sonnum = 0
						AND p.StopBuy=@stopBuy
			ELSE
				INSERT INTO @Temp(TypeId,NID) 
				SELECT	P.TypeId ,p.InventoryTypeID
				FROM	PType_L L
				INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
				INNER JOIN  dbo.F_Split(@pctypeid,',') b ON p.PtypeCategoryID LIKE b.a+'%'
				WHERE	L.etypeid = @chvOperatorId
						AND L.flag = 1 
						AND P.sonnum = 0
		ELSE
			IF @stopBuy=0
				INSERT INTO @Temp(TypeId,NID) 
				SELECT	P.TypeId ,p.InventoryTypeID
				FROM	PType_L L
				INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
				WHERE	L.etypeid = @chvOperatorId
						AND L.flag = 1 
						AND P.sonnum = 0
						AND p.StopBuy=@stopBuy
			ELSE
				INSERT INTO @Temp(TypeId,NID) 
					SELECT	P.TypeId ,p.InventoryTypeID
					FROM	PType_L L
					INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
					WHERE	L.etypeid = @chvOperatorId
							AND L.flag = 1 
							AND P.sonnum = 0
	END			
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_ManPTypeInCategoryID_Copy]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_ManPTypeInCategoryID_Copy
GO

/*
	author:chenqiang
	commen:库存状态线性表

*/
CREATE FUNCTION F_ManPTypeInCategoryID_Copy
(
	@chvOperatorId	varchar(100),
	@ptypeid		VARCHAR(max),
	@pctypeid		VARCHAR(max),
	@stopBuy		int=0
)
RETURNS @Temp TABLE(TypeId varchar(100),NID VARCHAR(50))
--@Encode$--
AS
BEGIN
	IF @ptypeid = '00000' OR @ptypeid = '' OR @ptypeid = '%'
			INSERT INTO @Temp(TypeId,NID) SELECT TypeId,NID FROM F_LinePC_Copy(@chvOperatorId,@pctypeid,@stopBuy)
	ELSE
		BEGIN					
			INSERT INTO @Temp(TypeId,NID)
				SELECT 	DISTINCT A.TypeId ,NID
				FROM 	F_LinePC_Copy(@chvOperatorId,@pctypeid,@stopBuy) A, 
							(SELECT A FROM dbo.F_Split(@ptypeid,',')) B 
				WHERE	A.TypeId LIKE B.A + '%'
		END	
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Ac_BalanceAssistByStype]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_Ac_BalanceAssistByStype
GO

/*
	作者：谢吉康
	日期：2010-07-15
	描述：获取基本信息的节点ID，带了权限范围
*/
CREATE  FUNCTION F_Ac_BalanceAssistByStype
(
	@STypeId		VARCHAR(50),	--独立分支机构ID
	@TypeId			VARCHAR(50),	--需要拆分的基本信息ID
	@Flag			INT,			--基本信息的标识 1.分支机构 2.部门 3.职员 4往来单位
	@OperatorId		VARCHAR(50)		--当前操作员的ID
		
)	
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)

	DECLARE @BaseTypeId		varchar(100)
	
	IF @Flag = 1			--分支机构
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT TypeId FROM F_AssistByStype(@STypeId,@TypeId,@OperatorId)
		END								
	ELSE IF @Flag = 2		--部门
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailDType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailAllDType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'						
				END
		END
	ELSE IF @Flag = 3		--职员
		BEGIN
			IF @TypeId = '00001' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailEType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END
	ELSE IF @Flag = 4		--往来单位
		BEGIN
			IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
				INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_GetManDetailBType(@OperatorId)
			ELSE
				BEGIN
					INSERT INTO @Temp(TypeId)
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailBType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%'
				END
		END

	RETURN
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetAtypeFullNamePath]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].F_GetAtypeFullNamePath
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能说明：获取科目全路径
-- 作者：glj  
-- 时间：2013-08-20
-- ========================================================================
CREATE  FUNCTION  F_GetAtypeFullNamePath
(
	@TypeID		VARCHAR(50),	--科目ID
	@StypeID	VARCHAR(50)	--分支机构
)
RETURNS VARCHAR(MAX)
AS  
BEGIN 

	DECLARE @FullNamePath VARCHAR(MAX)=''
	;With GetAtypeFullNamePath(TypeID,ParId) 
	As 
	( 
		SELECT TypeId,ParId FROM Ac_Account WHERE TypeId=@TypeID AND StypeId=@StypeID
		UNION ALL 
		SELECT A.TypeID,A.ParId
		FROM GetAtypeFullNamePath ic
		INNER JOIN Ac_Account A ON A.TypeId=ic.ParId AND A.TypeId<>'00000' AND StypeId=@StypeID
	) 
	 
	SELECT @FullNamePath+=A.FullName+'/'
	FROM GetAtypeFullNamePath ip 
	INNER JOIN Ac_Account A ON A.TypeId=IP.TypeID AND A.TypeId<>'00000' AND StypeId=@StypeID
	ORDER BY IP.TypeID
	
	IF SUBSTRING(@FullNamePath,LEN(@FullNamePath),1)='/'
		SET @FullNamePath=SUBSTRING(@FullNamePath,1,LEN(@FullNamePath)-1)
	RETURN @FullNamePath
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetBIllNumberOfType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetBIllNumberOfType
GO
-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	根据自定义表单定义的单据类型编号返回表名称  
--	            有出入库信息从InOutstocktable表取值，不包含出入库信息从BillIndex表取值，
--              调前、调后金额是特殊从AdpriceBill表取值
-- =============================================
CREATE FUNCTION F_GetBIllNumberOfType
(
	@numberOfType Varchar(200), --函数取值名称（以前用的这个很坑）
	@BillType int  --单据类型编号（BillType.xml对照 ）
)
RETURNS VARCHAR(100)
AS 
BEGIN
    DECLARE @tableName VARCHAR(100);
    
    --包含出入库信息
	if(@numberOfType in ('金额','折后金额','价税合计','成本金额','调拨金额','入库金额','入库折后金额','入库价税合计','入库成本','出库金额','出库折后金额','出库价税合计','出库成本'))
		set @tableName = 'InOutstocktable';	
		
	--不包含出入库信息	
	else if (@numberOfType in ('抹零金额','收款金额','抹零后金额','付款金额','调价差额','维修费','优惠金额','返利金额','价保金额','分摊金额'))	
		set @tableName = 'billindex';
		
	--9.4 bug 3751,3754
	--不包含出入库信息	(主要是金额字段的2张表都有)
	if(@BillType in (116,158,181,84,4,93,85,78,66,190,189,36,77,115,128,129,5,10))	
	  set @tableName = 'billindex';	
	  
	  -- 9.4 bug 3874 特殊的问题调价前，调价后金额取值方式不一样
	 --特殊类型取值 
	 if(@numberOfType in ('调前金额','调后金额'))
		set @tableName = 'AdpriceBill';	
		
	if(@numberOfType in ('调价差额') and @BillType in (147))	
	  set @tableName = 'InOutstocktable';	
		
    RETURN @tableName;
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='F_GetIsUse_Te' )
	DROP FUNCTION [dbo].F_GetIsUse_Te
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- =============================================
-- 作者:		GLJ
-- 日期:		2014-05-16  出纳管理
-- 返回:		判断是否使用 1:使用 0未使用 2：资金调拨单未生成凭证 3：凭证未生成日记账
-- =============================================
CREATE FUNCTION dbo.F_GetIsUse_Te
(
    @id			INT,			--ID 
	@Type		INT				--操作类型：1：银行账户 2：金融机构  3:银行账户判断能否销户
) 
RETURNS INT     
AS 
BEGIN
	IF @Type=1
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Te_AccountInTransit_Index WHERE AccountId=@id)--未达账表头
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Te_Balance WHERE AccountId=@id)--出纳余额表
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Te_BankStatement WHERE AccountId=@id)--银行对账单
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Te_BankStatementDetail WHERE AccountId=@id)--银行对账单明细
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Te_InitDataDetail WHERE AccountId=@id)--出纳期初明细
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM  Te_Journal WHERE AccountId=@id)--出纳——日记账
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM  Te_Journal_Detail WHERE AccountId=@id)--出纳——日记账明细
				RETURN 1	
			IF EXISTS(SELECT TOP 1 1 FROM BillIndex I INNER JOIN dbo.CapitalTransfer_Bill B ON B.BillNumberId=I.BillNumberId AND I.TransferType = 2 AND I.BillType = 310 AND(B.BankAccountOut=CAST(@id AS VARCHAR(50)) OR B.BankAccountIn=CAST(@id AS VARCHAR(50))))
				RETURN 1	
		END
	ELSE IF @Type=2
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Te_BankAccount WHERE BankId=@id)
				RETURN 1
		END
	ELSE IF @Type=3
		BEGIN
			--资金调拨单未生成凭证
			IF EXISTS(SELECT TOP 1 1 
				FROM dbo.BillIndex I 
				INNER JOIN CapitalTransfer_Bill C ON C.BillNumberId=I.BillNumberId AND I.BillType = 310 AND I.TransferType=2 
				INNER JOIN Te_BankAccount BA ON (C.BankAccountOut=CAST(BA.ID AS VARCHAR(50)) OR C.BankAccountIn=CAST(BA.ID AS VARCHAR(50))) AND BA.ID=CAST(@id AS VARCHAR(50)) AND I.BillNumberId NOT IN(SELECT GoodsBillId FROM  Ac_GoodsBill_VoucherBill))
				BEGIN
					RETURN 2
				END	
			--凭证未生成日记账
			IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher T1 
						INNER JOIN dbo.Ac_Voucher_Bill T2 ON T1.BillNumberId = T2.BillNumberId
						INNER JOIN dbo.Ac_Account T3 ON T2.ATypeId = T3.TypeId AND T2.STypeId = T3.StypeId
						INNER JOIN dbo.Te_BankAccount T4 ON T2.ATypeId = T4.ATypeId AND T4.STypeId=T1.STypeId
					WHERE (T3.IsCash = 1 OR T3.IsBank = 1)
						AND T4.Id = @id
						AND T2.ID NOT IN (SELECT VoucherId FROM Te_Journal_Detail)
						)
				BEGIN
					RETURN 3
				END	
			--IF (SELECT ISNULL(SUM(ISNULL(InitBalance,0)),0) FEndBalance FROM dbo.Te_InitDataDetail WHERE AccountId=@id)>0--是否有余额
			--	BEGIN
			--		RETURN 1
			--	END   9.8稳定版本bug307 销户只判断账户余额为0即可销户，无需判断期初余额；
-----------------------------------郝华 2017-05-02 10:03:06
			IF (SELECT ISNULL(SUM(ISNULL(FEndBalance,0)),0) FEndBalance FROM dbo.Te_Balance T 
			INNER JOIN Te_Period P ON P.STypeId=T.STypeId AND P.FYear=T.FYear AND P.FPeriod=T.FPeriod
			 WHERE T.AccountId=@id AND T.BUId IN(2,3))>0--是否有余额
				BEGIN
					RETURN 1
				END
			
		END
	RETURN 0--没有被使用
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetNumberOfType]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetNumberOfType
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	根据自定义表单定义的单据类型编号取值字段名称
--	            有出入库信息从InOutstocktable表取字段，不包含出入库信息从BillIndex表取字段，
--              调前、调后金额是特殊从AdpriceBill表取字段
-- =============================================

CREATE FUNCTION F_GetNumberOfType
(
	@numberOfType Varchar(200),
	@ifuse int ,
	@BillType int  --单据类型编号（BillType.xml对照 ）
)
RETURNS VARCHAR(100)
AS 
BEGIN
    DECLARE
		@selectName	VARCHAR(100),
		@isN varchar(10)=''
	if(@ifuse <> 0)
		set @isN = 'n'
	if(@numberOfType in ('金额'))
		set @selectName = 'isnull(sum(bill.'+ @isN +'saletotal),0)'
		
	else if(@numberOfType in ('成本金额')) 
		set @selectName = 'isnull(sum(bill.CostTotal),0)'
		
	else if(@numberOfType in ('入库金额'))
	   set @selectName = ' sum((case when bill.qty>0 then isnull(bill.'+@isN+'saletotal,0) end))  '
	 
	else if(@numberOfType in ('出库金额'))
	   set @selectName = ' sum((case when bill.qty<0 then isnull(-bill.'+@isN+'saletotal,0) end))  '

	else if(@numberOfType in ('折后金额'))
		set @selectName = 'isnull(sum(bill.'+ @isN +'total),0)'
		
	else if(@numberOfType in ('入库折后金额'))
	    set @selectName = ' sum((case when bill.qty>0 then isnull(bill.'+@isN+'total,0) end))  '
		
    else if(@numberOfType in ('出库折后金额'))
		set @selectName = ' sum((case when bill.qty<0 then isnull(-bill.'+@isN+'total,0) end))  '
		
	else if(@numberOfType in ('价税合计'))
		set @selectName = 'isnull(sum(bill.'+ @isN +'taxtotal),0)'
		
	else if(@numberOfType in ('入库价税合计'))	
		set @selectName = ' sum((case when bill.qty>0 then isnull(bill.'+@isN+'taxtotal,0) end))  '
		
	else if(@numberOfType in ('出库价税合计'))	
		set @selectName = ' sum((case when bill.qty<0 then isnull(-bill.'+@isN+'taxtotal,0) end))  '
		
    else if(@numberOfType in ('入库成本'))
		set @selectName = ' sum((case when bill.qty>0 then isnull(bill.CostTotal,0) end))  '
				
	else if(@numberOfType in ('出库成本'))
		set @selectName = ' sum((case when bill.qty<0 then isnull(-bill.CostTotal,0) end))  '
				
			
	else if(@numberOfType in ('抹零金额','优惠金额'))
		set @selectName = 'isnull(sum(bill.'+ @isN +'preferencemoney),0)'
		
	else if(@numberOfType in ('收款金额','付款金额'))
		set @selectName = 'isnull(sum(bill.'+ @isN +'totalinmoney),0)'
		
	else if(@numberOfType = '抹零后金额')
		set @selectName = 'isnull(sum(bill.'+ @isN +'totalmoney-bill.'+@isN+'preferencemoney),0)'
		
	else if(@numberOfType in ('调价差额','维修费','返利金额','价保金额','分摊金额'))
		set @selectName = 'isnull(sum(bill.'+ @isN +'totalmoney),0)'
		
	  -- 9.4 bug 3874 特殊的问题调价前，调价后金额取值方式不一样
	else if(@numberOfType = '调前金额')
		set @selectName = 'isnull(sum(bill.BeforeTotal),0)'
	else if(@numberOfType = '调后金额')
		set @selectName = 'isnull(sum(bill.total),0)'
		
		
		
	else if(@numberOfType='项目借方金额')
		set @selectName = 'isnull(sum(bill.'+ @isN +'J_Total),0)'
		
	else if(@numberOfType='项目贷方金额')
		set @selectName = 'isnull(sum(bill.'+ @isN +'D_Total),0)'
		
		   
	--9.4 bug 3751,3754
	--不包含出库信息的单据
	if(@numberOfType in ('金额') and @BillType in (116,158,181,84,4,93,85,78,66,190,189,36,77,115,128,129,5,10))	
	 set @selectName = 'isnull(sum(bill.'+ @isN +'totalmoney),0)'
	
	--包含出库信息的单据
	if(@numberOfType in ('金额') and @BillType in (187,11,6,140,141,145,146,305) )
		set @selectName = 'isnull(sum(-bill.'+ @isN +'saletotal),0)'
		
	if(@numberOfType in ('折后金额') and @BillType in (11,6,140,141,145,146,305) )
		set @selectName = 'isnull(sum(-bill.'+ @isN +'total),0)'
		
	if(@numberOfType in ('价税合计') and @BillType in (11,6,140,141,145,146))
		set @selectName = 'isnull(sum(-bill.'+ @isN +'taxtotal),0)'

    if(@numberOfType in ('成本金额') and @BillType in (21,139,183,187,11,173,9,140,141,168,172,305))	
	 set @selectName = ' sum((case when bill.qty<0 then isnull(-bill.CostTotal,0) end))  '
	 
	if(@numberOfType in ('调拨金额') and @BillType in (21))	
	 set @selectName = ' sum((case when bill.qty>0 then isnull(bill.CostTotal,0) end))  '
	 
	if(@numberOfType in ('金额') and @BillType in (202))
		set @selectName = 'isnull(sum(-bill.nSaletotal),0)'
		
	if(@numberOfType in ('金额') and @BillType in (201))
		set @selectName = 'isnull(sum(bill.nSaletotal),0)'
		
	if(@numberOfType in ('成本金额') and @BillType in (17))	
	 set @selectName = ' sum((case when bill.qty>0 then isnull(bill.CostTotal,0) end))  '
	 
	 
	  if(@numberOfType in ('调价差额') and  @BillType in (147) )
		set @selectName = 'isnull(sum(bill.'+ @isN +'total),0)'
	 
	     
    RETURN @selectName
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[F_GetStypeFullName]') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION [dbo].F_GetStypeFullName
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能说明：获取分支机构名称字符串
-- 作者：glj  
-- 时间：2013-09-17
-- ========================================================================
CREATE  FUNCTION  F_GetStypeFullName
(
	@StypeID	VARCHAR(MAX)	--分支机构
)
RETURNS VARCHAR(MAX)
AS  
BEGIN 
	DECLARE @FullName VARCHAR(MAX)=''
	
	SELECT @FullName+=S.FullName+',' 
	FROM SType S
	INNER JOIN f_split(@StypeID,',') F ON F.a=S.TypeId
	
	IF @FullName<>'' AND SUBSTRING(@FullName,LEN(@FullName),1)=','
		RETURN SUBSTRING(@FullName,1,LEN(@FullName)-1) 
		
	RETURN @FullName
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='F_GetVoucherNeedCashFlow' )
	DROP FUNCTION [dbo].F_GetVoucherNeedCashFlow
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- =============================================
-- 作者:		GLJ
-- 日期:		2015-03-31
-- 返回:		判断指定凭证是否指定流量 1:已制定 0：未指定 -1:不需要指定 
-- =============================================
CREATE FUNCTION dbo.F_GetVoucherNeedCashFlow
(
    @BillNumberId	NUMERIC(18,0)			--凭证 
) 
RETURNS INT     
AS 
BEGIN

IF EXISTS(SELECT TOP 1 B.ATypeId FROM Ac_Voucher_Bill B
INNER JOIN Ac_Account A ON A.StypeId=B.STypeId AND A.TypeId=B.ATypeId AND (A.IsBank=1 OR A.IsCash=1 OR IsOther=1) AND B.BillNumberId=@BillNumberId GROUP BY B.ATypeId)
BEGIN
	IF(SELECT ISNULL(SUM(B.FDebitTotal-B.FCreditTotal),0) 
FROM Ac_Voucher_Bill B
INNER JOIN Ac_Account A ON A.StypeId=B.STypeId AND A.TypeId=B.ATypeId AND (A.IsBank=1 OR A.IsCash=1 OR IsOther=1) AND B.BillNumberId=@BillNumberId)=0.0
		RETURN -1
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_CashMoneyItems WHERE BillNumberId=@BillNumberId AND MATypeId<>'') OR (SELECT SUM(ISNULL(B.FDebitTotal,0)+ISNULL(B.FCreditTotal,0)-ISNULL(I.Total,0))
	FROM Ac_Voucher_Bill B
	INNER JOIN Ac_Account A ON A.StypeId=B.STypeId AND A.TypeId=B.ATypeId AND (A.IsBank=1 OR A.IsCash=1 OR IsOther=1) AND B.BillNumberId=@BillNumberId
	LEFT JOIN  (SELECT BillNumberId,RowNo,SUM(Total)total FROM  Ac_Voucher_Bill_CashMoneyItems where MATypeId<>'' GROUP BY BillNumberId,RowNo) I ON I.BillNumberId=B.BillNumberId AND I.RowNo=B.RowNo )<>0.0
		RETURN 0
		
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_CashMoneyItems WHERE BillNumberId=@BillNumberId AND MATypeId<>'') AND (SELECT SUM(ISNULL(B.FDebitTotal,0)+ISNULL(B.FCreditTotal,0)-ISNULL(I.Total,0))
	FROM Ac_Voucher_Bill B
	INNER JOIN Ac_Account A ON A.StypeId=B.STypeId AND A.TypeId=B.ATypeId AND (A.IsBank=1 OR A.IsCash=1 OR IsOther=1) AND B.BillNumberId=@BillNumberId
	LEFT JOIN (SELECT BillNumberId,RowNo,SUM(Total)total FROM  Ac_Voucher_Bill_CashMoneyItems where MATypeId<>'' GROUP BY BillNumberId,RowNo) I ON I.BillNumberId=B.BillNumberId AND I.RowNo=B.RowNo)=0.0
		RETURN 1
	END
END

RETURN -1
END
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_IsHasVoucher]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_IsHasVoucher
GO
-- =============================================
-- Author:		
-- Create date: 
-- Description: 检查单据是否生成凭证	
-- return: int 2=未生成 1=已生成
-- =============================================
CREATE FUNCTION F_IsHasVoucher
(
	@billnumberid INT,
	@billtype	 INT
)
RETURNS INT
AS 
BEGIN
	IF @billtype=310
	BEGIN
		 IF dbo.F_GetVoucheridOfGoodsbill(@billnumberid,@billtype,'1','2')=0
		 OR dbo.F_GetVoucheridOfGoodsbill(@billnumberid,@billtype,'-1','2')=0
			RETURN 2
		 ELSE 
			RETURN 1
	END
	ELSE IF(@billtype=450)
	BEGIN
		IF dbo.F_GetVoucheridOfGoodsbill(@billnumberid,@billtype,'0,1,2,3,4,5','0,2') >0 
			RETURN 1
		 ELSE 
			RETURN 2
	END
	ELSE
	BEGIN
		 IF dbo.F_GetVoucheridOfGoodsbill(@billnumberid,@billtype,'0','0,2') >0 
			RETURN 1
		 ELSE 
			RETURN 2
	END
	RETURN 2
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_ManPTypeInCategoryID]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_ManPTypeInCategoryID
GO

/*

*/
CREATE FUNCTION F_ManPTypeInCategoryID
(
	@chvOperatorId	varchar(100),
	@ptypeid		VARCHAR(max),
	@pctypeid		VARCHAR(max)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF @ptypeid = '00000' OR @ptypeid = '' OR @ptypeid = '%'
		INSERT INTO @Temp(TypeId) SELECT TypeId FROM F_LinePC(@chvOperatorId,@pctypeid)
	ELSE
		BEGIN					
			INSERT INTO @Temp(TypeId)
				SELECT 	DISTINCT A.TypeId 
				FROM 	F_LinePC(@chvOperatorId,@pctypeid) A, 
							(SELECT A FROM dbo.F_Split(@ptypeid,',')) B 
				WHERE	A.TypeId LIKE B.A + '%'
		END	
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






/*
仅用于单据审核记录升级 
拆分审核明细时使用
*/

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'[dbo].[F_SplitAuditDetail]') AND [Type]='TF')
BEGIN
	DROP FUNCTION [dbo].[F_SplitAuditDetail]
END
GO

CREATE FUNCTION [dbo].[F_SplitAuditDetail](
	@Detail VARCHAR(MAX),
	@Ch		CHAR(2)
)

RETURNS @Return TABLE
(	
	AuditingStep INT,
	Explain	VARCHAR(255),
	AuditingDate DATETIME,
	StepName	VARCHAR(100),
	AuditingEmployee VARCHAR(20),
	IfAudit		CHAR(1),
	AuditType	CHAR(2)
)
AS 
BEGIN
    DECLARE @Index INT,
			@AuditingStep INT,
			@Explain	VARCHAR(255),
			@AuditingDate DATETIME,
			@StepName	VARCHAR(100),
			@AuditingEmployee VARCHAR(20),
			@IfAudit  CHAR(1),
			@AuditType	CHAR(2),
			@Count INT,
			@Mod INT,
			@Len INT,
			@teamCount INT,--总共有多少组
			@valueCount INT;--总共有多少值 
			
    SET @Ch=RTRIM(LTRIM(@CH));
	SET @teamCount=LEN(@Detail)-LEN(REPLACE(@Detail,'и',''));
	SET @valueCount=LEN(@Detail)-LEN(REPLACE(@Detail,@Ch,''));
    SET @Detail=REPLACE(@Detail,'и','');
    SET @Index=CHARINDEX(@Ch,@Detail);
    SET @Len=LEN(@Detail);
    SET @Count=1;
    SET @AuditingStep=0;
    IF @teamCount=0
    RETURN 
    SET @Mod=@valueCount/@teamCount; --获取每组有多少值（较低版本每组只有6个值）
    
    IF @Mod=7
    BEGIN
		WHILE @Index>=1
		BEGIN
			IF @Count%@Mod=1
				SET @AuditingDate=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=2
				SET @StepName=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=3
				SET @AuditingEmployee=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=4
				SET @IfAudit=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=5
				SET @Explain=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=6
				SET @AuditType= LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=0
			BEGIN
				SET @AuditingStep=LEFT(@Detail,@Index-1);
				INSERT @Return VALUES(@AuditingStep,@Explain,@AuditingDate,@StepName,@AuditingEmployee,@IfAudit,@AuditType)
			END
			SET @Len-=@Index;
			SET @Detail=STUFF(@Detail,1,@Index,'');
			SET @Index=CHARINDEX(@Ch,@Detail)
			SET @Count+=1;
		END
    END
    IF @Mod=6
    BEGIN
		WHILE @Index>=1
		BEGIN
			IF @Count%@Mod=1
				SET @AuditingDate=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=2
				SET @StepName=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=3
				SET @AuditingEmployee=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=4
				SET @IfAudit=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=5
				SET @Explain=LEFT(@Detail,@Index-1);
			ELSE IF @Count%@Mod=0
			BEGIN
				SET @AuditType= LEFT(@Detail,@Index-1);
				SET @AuditingStep=@AuditingStep+1;
				INSERT @Return VALUES(@AuditingStep,@Explain,@AuditingDate,@StepName,@AuditingEmployee,@IfAudit,@AuditType)
			END
			SET @Len-=@Index;
			SET @Detail=STUFF(@Detail,1,@Index,'');
			SET @Index=CHARINDEX(@Ch,@Detail)
			SET @Count+=1;
		END
    END
    RETURN
END

GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='F_XMFS' )
	DROP FUNCTION [dbo].F_XMFS
GO
-- =============================================
-- 作者:		glj
-- 日期:		2013-05-31
-- 返回:		项目发生额
-- =============================================
CREATE FUNCTION [dbo].F_XMFS
(
    @StypeId	VARCHAR(MAX),	--分支机构 
    @ItemCode	VARCHAR(50),	--项目编号
    @BeginDate	VARCHAR(20),	--开始时间
    @EndDate	VARCHAR(20),	--结束日期
    @OperatorId	VARCHAR(50)		--当前操作员
)
RETURNS  NUMERIC(24, 10)      
AS 
BEGIN
	DECLARE 
		@total_End  NUMERIC(24, 10) ,
		@total_Begin  NUMERIC(24, 10) 
	SELECT @total_End= DBO.F_XMQM(@StypeId,@ItemCode,@BeginDate,@EndDate,@OperatorId)
	SELECT @total_Begin=DBO.F_XMQC(@StypeId,@ItemCode,@BeginDate,@EndDate,@OperatorId)
	
	RETURN @total_End-@total_Begin
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='F_XMQC' )
	DROP FUNCTION [dbo].F_XMQC
GO
-- =============================================
-- 作者:		glj
-- 日期:		2013-05-31
-- 返回:		项目期初余额
-- =============================================
CREATE FUNCTION [dbo].F_XMQC
(
    @StypeId	VARCHAR(MAX),	--分支机构 
    @ItemCode	VARCHAR(50),	--项目编号
    @BeginDate	DATETIME,		--开始时间
    @EndDate	DATETIME,		--结束日期
    @OperatorId	VARCHAR(50)		--当前操作员
) 
RETURNS  NUMERIC(24, 10)      
AS 
BEGIN
	DECLARE  @total  NUMERIC(24, 10) =0.00--期初返回值

	DECLARE
	@NTypeID	VARCHAR(50),	--固定资产合计ntypeid
	@NTypeID1	VARCHAR(50),	--固定资产自己ntypeid
	@Assets		VARCHAR(1)=''	--固定资产管理模式

	SELECT @Assets=SubValue FROM sysdata WHERE SubName='assets'		--是否启用卡片模式
	SELECT @NTypeID=nTypeId FROM Ac_Items WHERE UserCode='1501@SYS'	--固定资产合计ntypeid
	SELECT @NTypeID1=nTypeId FROM Ac_Items WHERE UserCode=@ItemCode	--固定资产合计ntypeid


	--===============================创建临时数据表并取值【BEGIN】===================================

	DECLARE @AcItems TABLE(nid VARCHAR(50),nTypeId	VARCHAR(50))-- 项目 nid ntypeid
	DECLARE @Stype	TABLE(TypeId VARCHAR(50))--分支机构  typeid

	--选中项目及其子级项目
	;With T1(nTypeId,Nid) 
	As 
	( 
		Select nTypeId,nId From Ac_Items where UserCode=@ItemCode
		Union All 
		Select item.nTypeId,item.nId 
		From T1 ic
		Inner Join Ac_Items item ON item.nParId=ic.nTypeId  and item.nTypeId<>'00000'
	)
	INSERT INTO @AcItems(nid,nTypeId)
	SELECT Nid,nTypeId FROM T1	

	--得到满足条件的分支机构
	INSERT INTO @Stype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	--===============================创建临时数据表并取值【END】===================================



	--===============================得到期初数据并返回结果============================================
	--非固定资产项目 取期初总和
	IF(@NTypeID1 NOT LIKE @NTypeID+'%')
	BEGIN
		--特殊科目期初没有保存在atype_total表里面 需特殊处理
		IF EXISTS(SELECT TOP 1 1 FROM @Stype S INNER JOIN SType S1 ON S.TypeId=S.TypeId AND S1.VerifyID NOT IN(SELECT Stypeid FROM Ac_AccountsPeroid_Stype))
		BEGIN
			IF @ItemCode='1241'--库存商品总值
			BEGIN
				SET @total+=(SELECT ISNULl(SUM(ISNULL(I.Total,0)),0) 
					FROM inigoodsstocks I 
					INNER JOIN stock s on i.KtypeId=s.typeId 
					INNER JOIN @Stype S1 ON S1.typeId=S.STypeID
					INNER JOIN SType S2 ON S2.TypeId=S1.TypeId AND S2.VerifyID NOT IN(SELECT STypeID FROM Ac_AccountsPeroid_Stype)
				)
			END
			ELSE IF @ItemCode='1261'--委托代销商品
			BEGIN
				SET @total+=(SELECT ISNULl(SUM(ISNULL(I.Total,0)),0) 
					FROM inicommissionstock  I
					INNER JOIN @Stype S1 ON S1.typeId=I.STypeID 
					INNER JOIN SType S2 ON S2.TypeId=S1.TypeId AND S2.VerifyID NOT IN(SELECT STypeID FROM Ac_AccountsPeroid_Stype)
				)
			END
			ELSE IF @ItemCode='2141'-- 修改代销商品期初
			BEGIN
				SET @total+=(SELECT ISNULl(SUM(ISNULL(Total,0)),0) as total 
					FROM inicommissionstock I
					INNER JOIN @Stype S1 ON S1.typeId=I.STypeID  AND I.[TYPE]=144
					INNER JOIN SType S2 ON S2.TypeId=S1.TypeId AND S2.VerifyID NOT IN(SELECT STypeID FROM Ac_AccountsPeroid_Stype)
				)	
			END
		END
		--内部应收特殊处理
		IF EXISTS(SELECT TOP 1 1 FROM @AcItems WHERE nTypeId=(SELECT TOP 1 nParId FROM Ac_Items WHERE UserCode='1132') OR @ItemCode='1132')
			BEGIN
				SELECT 
					@total+=ISNULL(SUM(ISNULL(T.InnerARTotal00,0)),0)
				FROM SType_InnerARTotal T
				INNER JOIN @Stype S ON S.TypeId=T.STypeID
			END
			
		--正常业务项目期初数据处理
		SELECT 
		@total+=ISNULL(SUM(ISNULL(total.Total00,0)),0)
		FROM AType_Total total 
		INNER JOIN @AcItems item ON item.nId=Total.AtypeId
		INNER JOIN @Stype S ON S.TypeId=total.STypeID

		--得到查询时间以前的业务发生额
		SELECT
		@total+=ISNULL(SUM(ISNULL(total.Total,0)),0)
		FROM ListTable total
		INNER JOIN @AcItems item ON item.nId=Total.AtypeId
		INNER JOIN @Stype S ON S.TypeId=total.STypeID
		WHERE
		total.BillDate<@BeginDate
	END
	ELSE	--固定资产科目数据
	BEGIN
		DECLARE 
		@nStypeID		VARCHAR(50),	--循环分支机构
		@Accounts		INT,			--是否开账 1:开账 0：未开账
		@AccountsDate	DATETIME='',	--开账日期
		@FixedInit		INT,			--是否初始化 1：初始 0未初始
		@FixedInitDate	DATETIME		--初始时间
		

		DECLARE checkCur CURSOR READ_ONLY FOR
		SELECT TypeId FROM @Stype

		OPEN checkCur
		FETCH NEXT FROM checkCur INTO @nStypeID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			---判断分支机构是否开账
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=(SELECT VerifyID FROM SType WHERE TypeId=@nStypeID))
			BEGIN
				SET @Accounts=1
				--开账日期
				SELECT TOP 1 @AccountsDate=StartDate FROM MonthProc ORDER BY period ASC
			END
			ELSE
				SET @Accounts=0
				
			--判断是否初始化 
			IF EXISTS(SELECT TOP 1 1 FROM Ac_FixedAssetsInit_Stype WHERE StypeId=(SELECT VerifyID FROM SType WHERE TypeId=@nStypeID))
				BEGIN		
					SET @FixedInit=1
					--初始时间
					SELECT @FixedInitDate=InitDate FROM Ac_FixedAssetsInit_Stype WHERE StypeId=(SELECT VerifyID FROM SType WHERE TypeId=@nStypeID)
				END
			ELSE
				SET @FixedInit=0
			--已经开账	
			IF @Accounts=1
			BEGIN
				IF (@FixedInit=1) AND ((@BeginDate>=@FixedInitDate AND @FixedInitDate>@AccountsDate) OR(@BeginDate>@FixedInitDate AND @FixedInitDate=@AccountsDate))--卡片余额
				BEGIN
					IF(@ItemCode='1501@SYS')
					BEGIN
						SELECT @total+=ISNULL(SUM(ISNULL(NetValue,0)),0)
						FROM Ac_AssetsCards_History H
						INNER JOIN (
							SELECT
								ROW_NUMBER() OVER (PARTITION BY AssertsCardId ORDER BY BusinessDate DESC,ID DESC) Nid,
								ID
							FROM Ac_AssetsCards_History
							WHERE 
								STypeId=@nStypeID
								AND BusinessDate<@BeginDate
								AND BillType<>-3
						) F ON F.Nid=1 AND F.Id=H.Id
						AND H.AssetsState<>5--除去已清理	
					END
					ELSE 
						SET @total+=0
				END
				ELSE IF(@FixedInit=1) AND (@BeginDate<=@FixedInitDate AND @FixedInitDate=@AccountsDate)--卡片期初
				BEGIN
					IF(@ItemCode='1501@SYS')
					BEGIN
						SELECT @total+=ISNULL(SUM(ISNULL(NetValue,0)),0)
						FROM Ac_AssetsCards_History  H
						INNER JOIN (
							SELECT
								ROW_NUMBER() OVER (PARTITION BY AssertsCardId ORDER BY BusinessDate DESC,ID DESC) Nid,
								ID
							FROM Ac_AssetsCards_History
							WHERE 
								STypeId=@nStypeID
								AND BillType=0
						) F ON F.Nid=1 AND F.Id=H.Id
					END
					ELSE 
						SET @total+=0
				END
				ELSE --项目
				BEGIN
					SELECT 
						@total+=ISNULL(SUM(ISNULL(total.Total00,0)),0)
					FROM AType_Total total 
					INNER JOIN @AcItems item ON total.STypeID=@nStypeID AND item.nId=Total.AtypeId 
						
					IF(
						(@FixedInit=1 AND (@FixedInitDate>@BeginDate AND @BeginDate>=@AccountsDate)) --@FixedInitDate>@BeginDate>=@AccountsDate
						OR(@FixedInit=0 AND @BeginDate>@AccountsDate)
					  )
					BEGIN
						SELECT
						@total+=ISNULL(SUM(ISNULL(total.Total,0)),0)
						FROM ListTable total
						INNER JOIN @AcItems item ON total.STypeID=@nStypeID AND total.BillDate<@BeginDate AND item.nId=Total.AtypeId
					END
				END
			END	
			--未开账
			ELSE IF @Accounts=0
			BEGIN
				--已初始化  卡片期初
				IF @FixedInit=1
				BEGIN
					IF(@ItemCode='1501@SYS')
					BEGIN
						SELECT @total+=ISNULL(SUM(ISNULL(NetValue,0)),0)
						FROM Ac_AssetsCards_History H
						INNER JOIN (
							SELECT
								ROW_NUMBER() OVER (PARTITION BY AssertsCardId ORDER BY BusinessDate DESC,ID DESC) Nid,
								ID
							FROM Ac_AssetsCards_History
							WHERE 
								STypeId=@nStypeID
								AND BillType=0
						) F ON F.Nid=1 AND F.Id=H.Id
					END
					ELSE 
						SET @total+=0
				END			
				--未初始化
				IF @FixedInit=0
				BEGIN 
					--根据当前系统配置，若是项目管理则取项目期初
					IF @Assets='0'
					BEGIN
						--正常业务项目期初数据处理
						SELECT 
							@total+=ISNULL(SUM(ISNULL(total.Total00,0)),0)
						FROM AType_Total total 
						INNER JOIN @AcItems item ON total.STypeID=@nStypeID AND item.nId=Total.AtypeId	
					END	
					--卡片期初(未初始化)
					ELSE IF @Assets='1'
					BEGIN
						IF(@ItemCode='1501@SYS')
						BEGIN
							SELECT @total+=ISNULL(SUM(ISNULL(NetValue,0)),0)
							FROM Ac_AssetsCards
							WHERE
								STypeId=@nStypeID
								AND AssetsState IN(1,4)
						END
						ELSE 
							SET @total+=0
					END					
				END
			END						
			FETCH NEXT FROM checkCur INTO @nStypeID
		END
		CLOSE checkCur
		DEALLOCATE checkCur
	END
	RETURN @total
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='F_XMQM' )
	DROP FUNCTION [dbo].F_XMQM
GO
-- =============================================
-- 作者:		glj
-- 日期:		2013-05-31
-- 返回:		项目期末余额
-- =============================================
CREATE FUNCTION [dbo].F_XMQM
(
    @StypeId	VARCHAR(MAX),	--分支机构 
    @ItemCode	VARCHAR(50),	--项目编号
    @BeginDate	DATETIME,		--开始时间
    @EndDate	DATETIME,		--结束日期
    @OperatorId	VARCHAR(50)		--当前操作员
) 
RETURNS  NUMERIC(24, 10)      
AS 
BEGIN
	DECLARE  @total  NUMERIC(24, 10) =0.00--期初返回值

	DECLARE
	@NTypeID	VARCHAR(50),	--固定资产合计ntypeid
	@NTypeID1	VARCHAR(50),	--固定资产自己ntypeid
	@Assets		VARCHAR(1)=''	--固定资产管理模式

	SELECT @Assets=SubValue FROM sysdata WHERE SubName='assets'		--是否启用卡片模式
	SELECT @NTypeID=nTypeId FROM Ac_Items WHERE UserCode='1501@SYS'	--固定资产合计ntypeid
	SELECT @NTypeID1=nTypeId FROM Ac_Items WHERE UserCode=@ItemCode	--固定资产合计ntypeid


	--===============================创建临时数据表并取值【BEGIN】===================================

	DECLARE @AcItems TABLE(nid VARCHAR(50),nTypeId	VARCHAR(50))-- 项目 nid ntypeid
	DECLARE @Stype	TABLE(TypeId VARCHAR(50))--分支机构  typeid

	--选中项目及其子级项目
	;With T1(nTypeId,Nid) 
	As 
	( 
		Select nTypeId,nId From Ac_Items where UserCode=@ItemCode
		Union All 
		Select item.nTypeId,item.nId 
		From T1 ic
		Inner Join Ac_Items item ON item.nParId=ic.nTypeId  and item.nTypeId<>'00000'
	)
	INSERT INTO @AcItems(nid,nTypeId)
	SELECT Nid,nTypeId FROM T1	

	--得到满足条件的分支机构
	INSERT INTO @Stype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	--===============================创建临时数据表并取值【END】===================================



	--===============================得到期初数据并返回结果============================================
	--非固定资产项目 取期初总和
	IF(@NTypeID1 NOT LIKE @NTypeID+'%')
	BEGIN
		--特殊科目期初没有保存在atype_total表里面 需特殊处理
		IF EXISTS(SELECT TOP 1 1 FROM @Stype S INNER JOIN SType S1 ON S.TypeId=S.TypeId AND S1.VerifyID NOT IN(SELECT Stypeid FROM Ac_AccountsPeroid_Stype))
		BEGIN
			IF @ItemCode='1241'--库存商品总值
			BEGIN
				SET @total+=(SELECT ISNULl(SUM(ISNULL(I.Total,0)),0) 
					FROM inigoodsstocks I 
					INNER JOIN stock s on i.KtypeId=s.typeId 
					INNER JOIN @Stype S1 ON S1.typeId=S.STypeID
					INNER JOIN SType S2 ON S2.TypeId=S1.TypeId AND S2.VerifyID NOT IN(SELECT STypeID FROM Ac_AccountsPeroid_Stype)
				)
			END
			ELSE IF @ItemCode='1261'--委托代销商品
			BEGIN
				SET @total+=(SELECT ISNULl(SUM(ISNULL(I.Total,0)),0) 
					FROM inicommissionstock  I
					INNER JOIN @Stype S1 ON S1.typeId=I.STypeID 
					INNER JOIN SType S2 ON S2.TypeId=S1.TypeId AND S2.VerifyID NOT IN(SELECT STypeID FROM Ac_AccountsPeroid_Stype)
				)
			END
			ELSE IF @ItemCode='2141'-- 修改代销商品期初
			BEGIN
				SET @total+=(SELECT ISNULl(SUM(ISNULL(Total,0)),0)
					FROM inicommissionstock I
					INNER JOIN @Stype S1 ON S1.typeId=I.STypeID  AND I.[TYPE]=144
					INNER JOIN SType S2 ON S2.TypeId=S1.TypeId AND S2.VerifyID NOT IN(SELECT STypeID FROM Ac_AccountsPeroid_Stype)
				)	
			END
		END
		--内部应收特殊处理
		IF EXISTS(SELECT TOP 1 1 FROM @AcItems WHERE nTypeId=(SELECT TOP 1 nParId FROM Ac_Items WHERE UserCode='1132') OR @ItemCode='1132')
			BEGIN
				SELECT 
					@total+=ISNULL(SUM(ISNULL(T.InnerARTotal00,0)),0)
				FROM SType_InnerARTotal T
				INNER JOIN @Stype S ON S.TypeId=T.STypeID
			END
		
		--正常业务项目期初数据处理
		SELECT 
		@total+=ISNULL(SUM(ISNULL(total.Total00,0)),0)
		FROM AType_Total total 
		INNER JOIN @AcItems item ON item.nId=Total.AtypeId
		INNER JOIN @Stype S ON S.TypeId=total.STypeID

		--得到查询时间以前的业务发生额
		SELECT
		@total+=ISNULL(SUM(ISNULL(total.Total,0)),0)
		FROM ListTable total
		INNER JOIN @AcItems item ON item.nId=Total.AtypeId
		INNER JOIN @Stype S ON S.TypeId=total.STypeID
		WHERE
			total.BillDate<=@EndDate
	END
	ELSE	--固定资产科目数据
	BEGIN
		DECLARE 
		@nStypeID		VARCHAR(50),	--循环分支机构
		@Accounts		INT,			--是否开账 1:开账 0：未开账
		@AccountsDate	DATETIME='',	--开账日期
		@FixedInit		INT,			--是否初始化 1：初始 0未初始
		@FixedInitDate	DATETIME		--初始时间
		

		DECLARE checkCur CURSOR READ_ONLY FOR
		SELECT TypeId FROM @Stype

		OPEN checkCur
		FETCH NEXT FROM checkCur INTO @nStypeID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			---判断分支机构是否开账
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=(SELECT VerifyID FROM SType WHERE TypeId=@nStypeID))
			BEGIN
				SET @Accounts=1
				--开账日期
				SELECT TOP 1 @AccountsDate=StartDate FROM MonthProc ORDER BY period ASC
			END
			ELSE
				SET @Accounts=0
				
			--判断是否初始化 
			IF EXISTS(SELECT TOP 1 1 FROM Ac_FixedAssetsInit_Stype WHERE StypeId=(SELECT VerifyID FROM SType WHERE TypeId=@nStypeID))
				BEGIN		
					SET @FixedInit=1
					--初始时间
					SELECT @FixedInitDate=InitDate FROM Ac_FixedAssetsInit_Stype WHERE StypeId=(SELECT VerifyID FROM SType WHERE TypeId=@nStypeID)
				END
			ELSE
				SET @FixedInit=0
			--已经开账	
			IF @Accounts=1
			BEGIN
				IF (@FixedInit=1) AND ((@EndDate>=@FixedInitDate AND @FixedInitDate>@AccountsDate) OR(@EndDate>@FixedInitDate AND @FixedInitDate=@AccountsDate))--卡片余额
				BEGIN
					IF(@ItemCode='1501@SYS')
					BEGIN
						SELECT @total+=ISNULL(SUM(ISNULL(NetValue,0)),0)
						FROM Ac_AssetsCards_History H
						INNER JOIN (
							SELECT
								ROW_NUMBER() OVER (PARTITION BY AssertsCardId ORDER BY BusinessDate DESC,ID DESC) Nid,
								ID
							FROM Ac_AssetsCards_History
							WHERE 
								STypeId=@nStypeID
								AND BusinessDate<=@EndDate
								AND BillType<>-3
						) F ON F.Nid=1 AND F.Id=H.Id
						AND H.AssetsState<>5--除去已清理
					END
					ELSE 
						SET @total+=0
				END
				ELSE IF(@FixedInit=1) AND (@EndDate<=@FixedInitDate AND @FixedInitDate=@AccountsDate)--卡片期初
				BEGIN
					IF(@ItemCode='1501@SYS')
					BEGIN
						SELECT @total+=ISNULL(SUM(ISNULL(NetValue,0)),0)
						FROM Ac_AssetsCards_History  H
						INNER JOIN (
							SELECT
								ROW_NUMBER() OVER (PARTITION BY AssertsCardId ORDER BY BusinessDate DESC,ID DESC) Nid,
								ID
							FROM Ac_AssetsCards_History
							WHERE 
								STypeId=@nStypeID
								AND BillType=0
						) F ON F.Nid=1 AND F.Id=H.Id
					END
					ELSE 
						SET @total+=0
				END
				ELSE --项目
				BEGIN
					SELECT 
						@total+=ISNULL(SUM(ISNULL(total.Total00,0)),0)
					FROM AType_Total total 
					INNER JOIN @AcItems item ON total.STypeID=@nStypeID AND item.nId=Total.AtypeId 
						
					IF(
						(@FixedInit=1 AND (@FixedInitDate>@EndDate AND @EndDate>=@AccountsDate)) --@FixedInitDate>@EndDate>=@AccountsDate
						OR(@FixedInit=0 AND @EndDate>@AccountsDate)
					  )
					BEGIN
						SELECT
						@total+=ISNULL(SUM(ISNULL(total.Total,0)),0)
						FROM ListTable total
						INNER JOIN @AcItems item ON total.STypeID=@nStypeID AND total.BillDate<=@EndDate AND item.nId=Total.AtypeId
					END
				END
			END	
			--未开账
			ELSE IF @Accounts=0
			BEGIN
				--已初始化  卡片期初
				IF @FixedInit=1
				BEGIN
					IF(@ItemCode='1501@SYS')
					BEGIN
						SELECT @total+=ISNULL(SUM(ISNULL(NetValue,0)),0)
						FROM Ac_AssetsCards_History  H
						INNER JOIN (
							SELECT
								ROW_NUMBER() OVER (PARTITION BY AssertsCardId ORDER BY BusinessDate DESC,ID DESC) Nid,
								ID
							FROM Ac_AssetsCards_History
							WHERE 
								STypeId=@nStypeID
								AND BillType=0
						) F ON F.Nid=1 AND F.Id=H.Id
					END
					ELSE 
						SET @total+=0
				END			
				--未初始化
				IF @FixedInit=0
				BEGIN 
					--根据当前系统配置，若是项目管理则取项目期初
					IF @Assets='0'
					BEGIN
						--正常业务项目期初数据处理
						SELECT 
							@total+=ISNULL(SUM(ISNULL(total.Total00,0)),0)
						FROM AType_Total total 
						INNER JOIN @AcItems item ON total.STypeID=@nStypeID AND item.nId=Total.AtypeId	
					END	
					--卡片期初(未初始化)
					ELSE IF @Assets='1'
					BEGIN
						IF(@ItemCode='1501@SYS')
						BEGIN
							SELECT @total+=ISNULL(SUM(ISNULL(NetValue,0)),0)
							FROM Ac_AssetsCards
							WHERE
								STypeId=@nStypeID
								AND AssetsState IN(1,4)
						END
						ELSE 
							SET @total+=0
					END					
				END
			END						
			FETCH NEXT FROM checkCur INTO @nStypeID
		END
		CLOSE checkCur
		DEALLOCATE checkCur
	END
	RETURN @total
END 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='Fn_GetIsUse_Assets' )
	DROP FUNCTION [dbo].Fn_GetIsUse_Assets
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- =============================================
-- 作者:		古丽娟
-- 日期:		2013-05-15
-- 返回:		判断是否使用 1:使用 0未使用
-- =============================================
CREATE FUNCTION dbo.Fn_GetIsUse_Assets
(
    @id			INT,			--ID 
	@Type		INT				--操作类型：1：资产类别 2：存放地点 3：使用状况 
) 
RETURNS INT     
AS 
BEGIN
	IF @Type=1
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards WHERE CategoryId=@id)
				RETURN 1
		END
	ELSE IF @Type=2
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards_History WHERE LocationId=@id)
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards WHERE LocationId=@id)
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsModifyRecords WHERE LocationId=@id)
				RETURN 1
		END
	ELSE IF @Type=3
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards_History WHERE ConditionId=@id)
				RETURN 1
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards WHERE ConditionId=@id)
				RETURN 1
		END
	RETURN 0--没有被使用
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetUnInvoiceMoney]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[FN_GetUnInvoiceMoney]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




CREATE FUNCTION [FN_GetUnInvoiceMoney] (
	@intBillType		INT,  --单据类型
	@intBillNumberID	INT,  --主ID
	@intID				INT   --明细ID
)  
RETURNS  NUMERIC(24, 10) 
--@Encode$--
AS  
BEGIN 
	DECLARE
		@decUnInvoiceMoney	 NUMERIC(24, 10) ,
		@decAdjustMoney		 NUMERIC(24, 10) 
		
	SELECT
		@decUnInvoiceMoney=0,
		@decAdjustMoney=0
		
	IF @intBillType=400
	BEGIN
		SELECT @decUnInvoiceMoney=a.total-a.InvoiceMoneyEX
		FROM AppraisalBill a
		WHERE a.BillNumberId=@intBillNumberID AND a.ID=@intID
		
		IF EXISTS(
			SELECT b.ID
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN AppraisalBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		)
		BEGIN
			SELECT @decAdjustMoney=SUM(b.total)
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN AppraisalBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		END
			 
	END
	ELSE IF @intBillType=401
	BEGIN
		SELECT @decUnInvoiceMoney=a.total-a.InvoiceMoneyEX
		FROM AppraisalBackBill a
		WHERE a.BillNumberId=@intBillNumberID AND a.ID=@intID
		
		IF EXISTS(
			SELECT b.ID
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN AppraisalBackBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		)
		BEGIN
			SELECT @decAdjustMoney=SUM(b.total)
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN AppraisalBackBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		END
		
		
	END
	ELSE IF @intBillType=402
	BEGIN
		SELECT @decUnInvoiceMoney=a.total-a.InvoiceMoneyEX
		FROM SendBill a
		WHERE a.BillNumberId=@intBillNumberID AND a.ID=@intID
		
		IF EXISTS(
			SELECT b.ID
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN SendBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		)
		BEGIN
			SELECT @decAdjustMoney=SUM(b.total)
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN SendBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		END
	END
	ELSE IF @intBillType=403
	BEGIN
		SELECT @decUnInvoiceMoney=a.total-a.InvoiceMoneyEX
		FROM SendBackBill a
		WHERE a.BillNumberId=@intBillNumberID AND a.ID=@intID
		
		IF EXISTS(
			SELECT b.ID
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN SendBackBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		)
		BEGIN
			SELECT @decAdjustMoney=SUM(b.total)
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN SendBackBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		END
	END
   
	RETURN @decUnInvoiceMoney+@decAdjustMoney
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_GetUnNInvoiceMoney]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[FN_GetUnNInvoiceMoney]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




CREATE FUNCTION [FN_GetUnNInvoiceMoney] (
	@intBillType		INT,  --单据类型
	@intBillNumberID	INT,  --主ID
	@intID				INT   --明细ID
)  
RETURNS  NUMERIC(24, 10) 
--@Encode$--
AS  
BEGIN 
	DECLARE
		@decUnNInvoiceMoney	 NUMERIC(24, 10) ,
		@decNAdjustMoney		 NUMERIC(24, 10) 
		
	SELECT
		@decUnNInvoiceMoney=0,
		@decNAdjustMoney=0
		
	IF @intBillType=400
	BEGIN
		SELECT @decUnNInvoiceMoney=a.Ntotal-a.NInvoiceMoneyEX
		FROM AppraisalBill a
	
		WHERE a.BillNumberId=@intBillNumberID AND a.ID=@intID
		
		IF EXISTS(
			SELECT b.ID
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN AppraisalBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		)
		BEGIN
			SELECT @decNAdjustMoney=SUM(b.NTotal)
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN AppraisalBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		END
			 
	END
	ELSE IF @intBillType=401
	BEGIN
		SELECT @decUnNInvoiceMoney=a.Ntotal-a.NInvoiceMoneyEX
		FROM AppraisalBackBill a
		WHERE a.BillNumberId=@intBillNumberID AND a.ID=@intID
		
		IF EXISTS(
			SELECT b.ID
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN AppraisalBackBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		)
		BEGIN
			SELECT @decNAdjustMoney=SUM(b.NTotal)
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN AppraisalBackBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		END
		
		
	END
	ELSE IF @intBillType=402
	BEGIN
		SELECT @decUnNInvoiceMoney=a.Ntotal-a.NInvoiceMoneyEX
		FROM SendBill a
		WHERE a.BillNumberId=@intBillNumberID AND a.ID=@intID
		
		IF EXISTS(
			SELECT b.ID
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN SendBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		)
		BEGIN
			SELECT @decNAdjustMoney=SUM(b.NTotal)
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN SendBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		END
	END
	ELSE IF @intBillType=403
	BEGIN
		SELECT @decUnNInvoiceMoney=a.Ntotal-a.NInvoiceMoneyEX
		FROM SendBackBill a
		WHERE a.BillNumberId=@intBillNumberID AND a.ID=@intID
		
		IF EXISTS(
			SELECT b.ID
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN SendBackBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		)
		BEGIN
			SELECT @decNAdjustMoney=SUM(b.NTotal)
			FROM AdPriceBill b
			INNER JOIN Billindex c
			ON b.BillNumberId=c.BillNumberId
			INNER JOIN ReceiptBill d
			ON b.FromBillID=d.ID
			INNER JOIN SendBackBill e
			ON d.RecordedItemId=e.ID AND d.MainBillNumberID=e.BillNumberId
			WHERE e.BillNumberId=@intBillNumberID AND e.ID=@intID
			AND c.ifcheck='t' AND c.RedWord=0
		END
	END
   
	RETURN @decUnNInvoiceMoney+@decNAdjustMoney
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeA]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeA
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：MaoXinrong
	日期：2013-04-08
	描述：得到管辖范围内现金+银行详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeA
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  nId AS Typeid,
				nId,
				TypeId as atypeid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment,
				IsWmsSync
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
				--AND (nTypeId LIKE '0000100004%' OR (UserCode LIKE '1001%' AND Sysrow=1)) 
				AND (TypeName='B' OR nTypeId='0000100009'  OR nTypeId='0000200006')
		UNION ALL
		SELECT  A.nId AS Typeid,
				a.nid,
				A.TypeId as atypeid,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment,
				IsWmsSync
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '-99999')
				AND l.etypeid=@chvOperatorId
				AND L.Type = '0'
				--AND (a.nTypeId LIKE '0000100004%' OR (UserCode LIKE '1001%' AND Sysrow=1)) 
				AND (TypeName='B' OR nTypeId='0000100009'  OR nTypeId='0000200006')
				
	)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeAssetsT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeAssetsT
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-05-16
	描述：得到管辖范围内资产合计(固定资产+银行账户+其他资产)详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeAssetsT
(
	@chvOperatorId			varchar(100)
)
RETURNS  @table  TABLE 
(
	nId			VARCHAR(10),
	nTypeId		VARCHAR(60),
	nParId		VARCHAR(60),
	ParId		VARCHAR(60),
	SonNum		VARCHAR(10),
	SonCount	VARCHAR(10),
	UserCode	VARCHAR(500),
	FullName	VARCHAR(500),
	Name		VARCHAR(500),
	CreateBank  VARCHAR(200),
	BankType	VARCHAR(100),
	IsBank		VARCHAR(10),
	PyCode		VARCHAR(200),
	Deleted		VARCHAR(5),
	TypeName	VARCHAR(5),
	XiWaMaxNumber  VARCHAR(10),
	Sysrow		VARCHAR(10),
	ismodify	VARCHAR(5)
)
AS
BEGIN

DECLARE @ver VARCHAR(5) --判断是否是V3
SELECT @ver=s.subvalue FROM dbo.sysdata s WHERE s.SubName='proinfo'


DECLARE @cardmode VARCHAR(5)  --是否是卡片模式 1卡片，0项目
SELECT  @cardmode=SubValue FROM dbo.sysdata WHERE SubName='assets' --AND SubValue='1'


DECLARE @shacitems VARCHAR(MAX)
SELECT @shacitems=nId FROM Ac_Items WHERE UserCode='3001' --实收资本

DECLARE @gdacitems VARCHAR(MAX)
SELECT @gdacitems=nId FROM Ac_Items WHERE UserCode='1501' --固定资产


		INSERT INTO @table

		SELECT  DISTINCT nId ,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify
				FROM  (
						SELECT  nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(
											SELECT TOP 1 1 FROM LoginUser 
											WHERE ETypeId = @chvOperatorId AND( MangerOtherCpaital = '0000' OR MangerATypeID='0000' OR MangerCpaital='0000')
											UNION
											SELECT TOP 1 1 FROM atype_l WHERE etypeid = @chvOperatorId AND TypeId='00001' AND flag IN(0,3,4)
										)
								AND nTypeId = '00001'
								
						UNION ALL 
						SELECT  nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '0000')
								AND TypeName ='C'
								AND nTypeId <> '00000' 
								AND (nTypeId ='00001' OR nTypeId LIKE '00001%')
								AND nTypeId<>'0000100009'
					    UNION ALL 
					    SELECT  nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID  = '0000')
								AND (TypeName ='B' OR    nTypeId='0000100009'  )
								AND nTypeId <> '00000' 
								AND nTypeId LIKE '00001%'
						UNION ALL 
					    SELECT  nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items 
						WHERE 	 EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
								AND	(CASE @cardmode WHEN 1 THEN '3' ELSE '2' END )='2'  --如果卡片模式不差固定资产所有权限0000
							    AND TypeName ='F'
								AND nTypeId <> '00000' 
								AND nTypeId LIKE '0000100002%' 
						UNION ALL
						SELECT  DISTINCT nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '-99999')
								AND l.etypeid=@chvOperatorId
								AND TypeName='F'
								AND L.type='3'
						UNION ALL
						SELECT  DISTINCT nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID  = '-99999')
								AND l.etypeid=@chvOperatorId
								AND (TypeName='B' OR a.nTypeId='0000100009')
								AND  L.type='0'
						UNION ALL
						SELECT  DISTINCT nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '-99999')
								AND l.etypeid=@chvOperatorId
								AND TypeName='C'
								AND L.type='4'
						) a
			 WHERE (CASE @ver WHEN 1 THEN a.UserCode WHEN 4 THEN a.UserCode ELSE '99999' END )<>'1132' 
					AND (CASE @cardmode WHEN 1 THEN a.nId ELSE '99999' END )<>@shacitems --卡片模式去掉实收资本
					AND (CASE @cardmode WHEN 1 THEN a.nId ELSE '99999' END )<>@gdacitems --卡片模式去掉固定资产
					AND UserCode<>'SYC-1602' 
					AND UserCode<>'SYC-1601' 
	
	RETURN 
	


END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeB]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_AllTreeB]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据权限范围来确定管辖往来单位范围，包含etypeid关联职员功能，包含denominatedid为查询出权限以外的字段
*/



CREATE FUNCTION F_AllTreeB
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT	typeId,
				parid,
				leveal,
				soncount,
				sonnum,
				UserCode,
				FullName,
				Name,
				Area,
				TelAndAddress,
				PostCode,
				Person,
				TaxNumber,
				BankAndAcount,
				Comment,
				CreateDate,
				ARTotal,
				APTotal,
				ARTotal00,
				APTotal00,
				deleted,
				Client,
				ARLimit,
				initcomment,
				arapexplain,
				Tel1,
				Tel2,
				Tel3,
				Fax,
				WWW,
				Bank,
				BankName,
				Email,
				LinkMan1,
				LinkSex1,
				LinkBirthDay1,
				LinkJob1,
				LinkCall1,
				LinkTel1,
				LinkMobile1,
				LinkPost1,
				LinkAddress1,
				LinkEmail1,
				LinkComment1,
				LinkMan2,
				LinkSex2,
				LinkBirthDay2,
				LinkJob2,
				LinkCall2,
				LinkTel2,
				LinkMobile2,
				LinkPost2,
				LinkAddress2,
				LinkEmail2,
				LinkComment2,
				ARLimitTime,
				paymentLTime,
				SaleZekou,
				BuyZekou,
				PyCode,
				Price,
				AreaTypeID,
				smsMobile,
				smsComment,
				XiWaMaxNumber,
				etypeid,
				buyprice,
				ConsigneeAddress,
				Consignee,
				ConsigneeTel,
				cannotmodifyprice,
				denominatedid
		FROM 	BType 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
				AND TypeId <> '00000' 
				AND TypeId LIKE '00001%' 
		UNION ALL
		SELECT	B.typeId,
				B.parid,
				B.leveal,
				B.soncount,
				B.sonnum,
				B.UserCode,
				B.FullName,
				B.Name,
				B.Area,
				B.TelAndAddress,
				B.PostCode,
				B.Person,
				B.TaxNumber,
				B.BankAndAcount,
				B.Comment,
				B.CreateDate,
				B.ARTotal,
				B.APTotal,
				B.ARTotal00,
				B.APTotal00,
				B.deleted,
				B.Client,
				B.ARLimit,
				B.initcomment,
				B.arapexplain,
				B.Tel1,
				B.Tel2,
				B.Tel3,
				B.Fax,
				B.WWW,
				B.Bank,
				B.BankName,
				B.Email,
				B.LinkMan1,
				B.LinkSex1,
				B.LinkBirthDay1,
				B.LinkJob1,
				B.LinkCall1,
				B.LinkTel1,
				B.LinkMobile1,
				B.LinkPost1,
				B.LinkAddress1,
				B.LinkEmail1,
				B.LinkComment1,
				B.LinkMan2,
				B.LinkSex2,
				B.LinkBirthDay2,
				B.LinkJob2,
				B.LinkCall2,
				B.LinkTel2,
				B.LinkMobile2,
				B.LinkPost2,
				B.LinkAddress2,
				B.LinkEmail2,
				B.LinkComment2,
				B.ARLimitTime,
				B.paymentLTime,
				B.SaleZekou,
				B.BuyZekou,
				B.PyCode,
				B.Price,
				B.AreaTypeID,
				B.smsMobile,
				B.smsComment,
				B.XiWaMaxNumber,
				B.etypeid,
				B.buyprice,
				B.ConsigneeAddress,
				B.Consignee,
				B.ConsigneeTel,
				B.cannotmodifyprice,
				denominatedid
		FROM 	BType B INNER JOIN F_GetManDetailAllBType(@chvOperatorId) M ON B.TypeId = M.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '-99999')
				AND B.TypeId LIKE '00001%' 
		UNION ALL		
		SELECT	typeId,
				parid,
				leveal,
				soncount,
				sonnum,
				UserCode,
				FullName,
				Name,
				Area,
				TelAndAddress,
				PostCode,
				Person,
				TaxNumber,
				BankAndAcount,
				Comment,
				CreateDate,
				ARTotal,
				APTotal,
				ARTotal00,
				APTotal00,
				deleted,
				Client,
				ARLimit,
				initcomment,
				arapexplain,
				Tel1,
				Tel2,
				Tel3,
				Fax,
				WWW,
				Bank,
				BankName,
				Email,
				LinkMan1,
				LinkSex1,
				LinkBirthDay1,
				LinkJob1,
				LinkCall1,
				LinkTel1,
				LinkMobile1,
				LinkPost1,
				LinkAddress1,
				LinkEmail1,
				LinkComment1,
				LinkMan2,
				LinkSex2,
				LinkBirthDay2,
				LinkJob2,
				LinkCall2,
				LinkTel2,
				LinkMobile2,
				LinkPost2,
				LinkAddress2,
				LinkEmail2,
				LinkComment2,
				ARLimitTime,
				paymentLTime,
				SaleZekou,
				BuyZekou,
				PyCode,
				Price,
				AreaTypeID,
				smsMobile,
				smsComment,
				XiWaMaxNumber,
				etypeid,
				buyprice,
				ConsigneeAddress,
				Consignee,
				ConsigneeTel,
				cannotmodifyprice,
				denominatedid
		FROM 	BType
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
				AND TypeId <> '00000' 
				AND TypeId LIKE '00002%' 
		UNION ALL
		SELECT	B.typeId,
				B.parid,
				B.leveal,
				B.soncount,
				B.sonnum,
				B.UserCode,
				B.FullName,
				B.Name,
				B.Area,
				B.TelAndAddress,
				B.PostCode,
				B.Person,
				B.TaxNumber,
				B.BankAndAcount,
				B.Comment,
				B.CreateDate,
				B.ARTotal,
				B.APTotal,
				B.ARTotal00,
				B.APTotal00,
				B.deleted,
				B.Client,
				B.ARLimit,
				B.initcomment,
				B.arapexplain,
				B.Tel1,
				B.Tel2,
				B.Tel3,
				B.Fax,
				B.WWW,
				B.Bank,
				B.BankName,
				B.Email,
				B.LinkMan1,
				B.LinkSex1,
				B.LinkBirthDay1,
				B.LinkJob1,
				B.LinkCall1,
				B.LinkTel1,
				B.LinkMobile1,
				B.LinkPost1,
				B.LinkAddress1,
				B.LinkEmail1,
				B.LinkComment1,
				B.LinkMan2,
				B.LinkSex2,
				B.LinkBirthDay2,
				B.LinkJob2,
				B.LinkCall2,
				B.LinkTel2,
				B.LinkMobile2,
				B.LinkPost2,
				B.LinkAddress2,
				B.LinkEmail2,
				B.LinkComment2,
				B.ARLimitTime,
				B.paymentLTime,
				B.SaleZekou,
				B.BuyZekou,
				B.PyCode,
				B.Price,
				B.AreaTypeID,
				B.smsMobile,
				B.smsComment,
				B.XiWaMaxNumber,
				B.etypeid,
				B.buyprice,
				B.ConsigneeAddress,
				B.Consignee,
				B.ConsigneeTel,
				B.cannotmodifyprice,
				denominatedid
		FROM 	BType B INNER JOIN F_GetManDetailAllBType(@chvOperatorId) M ON B.TypeId = M.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '-99999')
				AND B.TypeId LIKE '00002%' 
)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeC
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：MaoXinrong
	日期：2013-04-08
	描述：得到管辖范围内固定资产详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeC
(
	@chvOperatorId			varchar(100)
)
RETURNS  @table  TABLE 
(
	Typeid			VARCHAR(60),
	nId				VARCHAR(5),
	atypeid			VARCHAR(60),
	nTypeId			VARCHAR(60),
	nParId			VARCHAR(60),
	ParId			VARCHAR(60),
	SonNum			VARCHAR(5),
	SonCount		VARCHAR(5),
	UserCode		VARCHAR(200),
	FullName		VARCHAR(200),
	Name			VARCHAR(200),
	CreateBank		VARCHAR(200),
	BankType		VARCHAR(200),
	IsBank			VARCHAR(200),
	PyCode			VARCHAR(200),
	Deleted			VARCHAR(5),
	TypeName		VARCHAR(5),
	XiWaMaxNumber	VARCHAR(5),
	Sysrow			VARCHAR(5),
	ismodify		VARCHAR(5),
	Comment			VARCHAR(MAX)
)
AS
BEGIN

DECLARE @cardmode VARCHAR(5)  --是否是卡片模式
SELECT  @cardmode=SubValue FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1'
	
			INSERT INTO @table
			SELECT 
				Typeid,
				nId,
				atypeid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
			FROM 
			(
					SELECT  nId AS Typeid,
							nId,
							TypeId as atypeid,
							nTypeId,
							nParId,
							ParId ,
							SonNum ,
							SonCount ,
							UserCode ,
							FullName ,
							Name ,
							CreateBank ,
							BankType ,
							IsBank ,
							PyCode ,
							Deleted ,
							TypeName ,
							XiWaMaxNumber ,
							Sysrow ,
							ismodify,
							Comment
					FROM 	dbo.Ac_Items 
					WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
							AND TypeName='F' 
							AND nTypeId <> '00000' 
							AND nTypeId LIKE '0000100002%' 
					UNION ALL
					SELECT  a.nId AS typeid,
							a.nId,
							a.TypeId AS atypeid,
							a.nTypeId,
							a.nParId,
							ParId ,
							SonNum ,
							SonCount ,
							UserCode ,
							FullName ,
							Name ,
							CreateBank ,
							BankType ,
							IsBank ,
							PyCode ,
							Deleted ,
							TypeName ,
							XiWaMaxNumber ,
							Sysrow ,
							ismodify,
							Comment
					FROM 	dbo.Ac_Items  A 
					INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
					WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '-99999')
						AND L.etypeid = @chvOperatorId 
						AND a.TypeName='F' 
						AND l.type='3'			
	
			) a
	
			 WHERE 
					(CASE @cardmode WHEN 1 THEN a.nId ELSE '99999' END )<>'46'--卡片模式去掉固定资产
					AND (CASE @cardmode WHEN 1 THEN a.nId ELSE '99999' END )<>'26'--卡片模式去掉固定资产
	
	RETURN
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_AllTreeD') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeD
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据权限范围来确定所管辖部门范围
*/
CREATE FUNCTION F_AllTreeD
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE
(
	typeid    		varchar(150),
	parid    		varchar(150),
	leveal    		varchar(10),
	sonnum    		varchar(10),
	soncount    	varchar(10),
	usercode    	varchar(200),
	FullName    	varchar(200),
	Name    		varchar(200),
	Comment    		varchar(200),
	deleted    		varchar(10),
	Tel    			varchar(150),
	LinkMan    		varchar(150),
	Fax    			varchar(150),
	rec    			varchar(10),
	namepy    		varchar(200),
	parrec    		varchar(10),
	OrderNo    		varchar(10),
	PyCode    		varchar(600),
	XiWaMaxNumber    NUMERIC(24, 10) 
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerDTypeID = '00000')
		INSERT INTO @Temp	
		SELECT 	typeid,
				parid,
				leveal,
				sonnum,
				soncount,
				usercode,
				FullName,
				Name,
				Comment,
				deleted,
				Tel,
				LinkMan,
				Fax,
				rec,
				namepy,
				parrec,
				OrderNo,
				PyCode,
				XiWaMaxNumber 
		FROM 	Department
		WHERE 	TypeId <> '00000' 
	ELSE
		INSERT INTO @Temp		
		SELECT 	typeid,
				parid,
				leveal,
				sonnum,
				soncount,
				usercode,
				FullName,
				Name,
				Comment,
				deleted,
				Tel,
				LinkMan,
				Fax,
				rec,
				namepy,
				parrec,
				OrderNo,
				PyCode,
				XiWaMaxNumber 
		FROM 	Department
		WHERE	TypeId IN (SELECT T.TypeId FROM 
											( SELECT	DISTINCT D.TypeId
											  FROM      DType_l L 
														INNER JOIN Department D ON ( L.Flag = 1AND D.TypeId LIKE L.TypeId+ '%')
											  WHERE     L.etypeid = @chvOperatorId
											  UNION
											  SELECT    L.TypeID
											  FROM      dtype_l L
											  WHERE     L.etypeid = @chvOperatorId AND L.flag = 0
											) T
							)


	RETURN
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeE]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_AllTreeE]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据权限来确定职员范围
*/
CREATE FUNCTION F_AllTreeE
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
	 	SELECT 	BtypeID,
				typeId,
				Parid,
				leveal,
				soncount,
				sonnum,
				FullName,
				Name,
				UserCode,
				Department,
				Tel,
				Address,
				Comment,
				deleted,
				Sex,
				Nation,
				Knowledge,
				Blood,
				Health,
				IDcard,
				Birthday,
				Marriage,
				Job,
				Job2,
				JobTime,
				Tel2,
				Mob,
				Mail,
				political,
				nat_place,
				college,
				for_language,
				reg_place,
				com_level,
				weight,
				stature,
				fam_status,
				informer,
				speciality,
				for_lan_level,
				PostCode,
				Email,
				DtypeID,
				PyCode,
				MaxPre,
				smsMobile,
				smsComment,
				tichengRate,
				XiWaMaxNumber,
				STypeId,
				QQ,
				MSN,
				Blog,
				mBlog,
				Team,
				HrpostionId,
				HrPersonStatu
		FROM 	Employee 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '00001')
				AND TypeId <> '00000' 
		UNION ALL
		SELECT 	E.BtypeID,
				E.typeId,
				E.Parid,
				E.leveal,
				E.soncount,
				E.sonnum,
				E.FullName,
				E.Name,
				E.UserCode,
				E.Department,
				E.Tel,
				E.Address,
				E.Comment,
				E.deleted,
				E.Sex,
				E.Nation,
				E.Knowledge,
				E.Blood,
				E.Health,
				E.IDcard,
				E.Birthday,
				E.Marriage,
				E.Job,
				E.Job2,
				E.JobTime,
				E.Tel2,
				E.Mob,
				E.Mail,
				E.political,
				E.nat_place,
				E.college,
				E.for_language,
				E.reg_place,
				E.com_level,
				E.weight,
				E.stature,
				E.fam_status,
				E.informer,
				E.speciality,
				E.for_lan_level,
				E.PostCode,
				E.Email,
				E.DtypeID,
				E.PyCode,
				E.MaxPre,
				E.smsMobile,
				E.smsComment,
				E.tichengRate,
				E.XiWaMaxNumber,
				E.STypeId,
				E.QQ,
				E.MSN,
				E.Blog,
				E.mBlog,
				E.Team,
				E.HrpostionId,
				E.HrPersonStatu
		FROM	Employee E INNER JOIN 
				(
					SELECT	DISTINCT
							E.TypeId
					FROM    EType_L L
							INNER JOIN Employee E ON ( L.Flag = 1 AND E.TypeId LIKE L.TypeId + '%')
					WHERE   L.etypeid = @chvOperatorId
					UNION
					SELECT  L.TypeID
					FROM    etype_l L
					WHERE   L.etypeid = @chvOperatorId AND L.flag = 0
				) M ON M.TypeId = E.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerETypeID = '-99999')
)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeExpenseC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeExpenseC
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-05-16
	描述：得到管辖范围内支出类(费用类型+管辖支出详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeExpenseC
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT  nId ,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				IsWmsSync
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
				AND TypeName='E' 
				AND nTypeId <> '00000' 
				AND (nTypeId LIKE '0000400003%'  OR nParId LIKE '0000400003%' OR nTypeId='00004')
				AND UserCode NOT IN ('042','0404','5401')
				AND nTypeId NOT LIKE '0000400002%'
		UNION 
		SELECT  nId ,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				IsWmsSync
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPay = '0000')
				AND TypeName='E' 
				AND nTypeId <> '00000' 
				AND (nTypeId LIKE '00004%' OR nTypeId LIKE '0000400002%' OR nTypeId LIKE '0000400001' OR nTypeId LIKE '0000400004' OR nParId='00004' OR nParId LIKE '0000400002%')
				AND UserCode NOT IN ('043')
				AND nTypeId NOT LIKE '0000400003%'
		UNION 
		SELECT  DISTINCT nId ,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				IsWmsSync
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '-99999')
			AND a.TypeName='E' 
				AND L.etypeid =@chvOperatorId
				AND L.type = '1'
		UNION 
		SELECT  DISTINCT nId ,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				IsWmsSync
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPay = '-99999')
			AND a.TypeName='E' 
				AND L.etypeid =@chvOperatorId
				AND L.type='7'
	)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeF]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeF
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：MaoXinrong
	日期：2013-04-08
	描述：得到费用类型详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeF
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  nId AS Typeid,
				nid,
				TypeId as atypeid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
				AND TypeName='E' 
				AND nTypeId <> '00000' 
				AND nTypeId LIKE '0000400003%' 
		UNION ALL
		SELECT  a.nId AS typeid,
				a.nId,
				a.TypeId AS atypeid,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '-99999')
			AND a.TypeName='E' 
			AND L.Type = '1'
			AND l.etypeid=@chvOperatorId
			AND nTypeId LIKE '0000400003%' 
	)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeGxAssets]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeGxAssets
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-06-07
	描述：得到管辖范围内管辖其他资产树形结构
*/
CREATE FUNCTION F_AllTreeGxAssets
(
	@chvOperatorId			varchar(100)
)
RETURNS  @table  TABLE 
(
	nId			VARCHAR(10),
	nTypeId		VARCHAR(60),
	nParId		VARCHAR(60),
	ParId		VARCHAR(60),
	SonNum		VARCHAR(10),
	SonCount	VARCHAR(10),
	UserCode	VARCHAR(500),
	FullName	VARCHAR(500),
	Name		VARCHAR(500),
	CreateBank  VARCHAR(200),
	BankType	VARCHAR(100),
	IsBank		VARCHAR(10),
	PyCode		VARCHAR(200),
	Deleted		VARCHAR(5),
	TypeName	VARCHAR(5),
	XiWaMaxNumber  VARCHAR(10),
	Sysrow		VARCHAR(10),
	ismodify	VARCHAR(5)
)
AS
BEGIN

DECLARE @ver VARCHAR(5)

SELECT @ver=s.subvalue FROM dbo.sysdata s WHERE s.SubName='proinfo'


		INSERT INTO  @table

		SELECT  nId ,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify
				FROM  (
						SELECT  nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '0000')
								AND TypeName ='C'
								AND nTypeId <> '00000' 
								AND nTypeId LIKE '00001%' 
								AND UserCode<>'SYC-1602' 
								AND UserCode<>'SYC-1601' 
						UNION ALL
						SELECT  nId ,
								nTypeId,
								nParId,
								ParId ,
								SonNum ,
								SonCount ,
								UserCode ,
								FullName ,
								Name ,
								CreateBank ,
								BankType ,
								IsBank ,
								PyCode ,
								Deleted ,
								TypeName ,
								XiWaMaxNumber ,
								Sysrow ,
								ismodify
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '-99999')
								AND TypeName='C'
								AND l.etypeid=@chvOperatorId
								AND UserCode<>'SYC-1602' 
								AND UserCode<>'SYC-1601' 
								AND L.Type = '4'
						)  a 
				WHERE (CASE @ver WHEN 1 THEN a.UserCode ELSE '99999' END )<>'1132' 
				
	RETURN 
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeGxExpense]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeGxExpense
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-06-07
	描述：得到管辖范围内管辖支出详细信息树形结构
*/
CREATE FUNCTION F_AllTreeGxExpense
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN	(
		SELECT  nId ,
				nTypeId,
				nParId,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId =@chvOperatorId AND MangerPay = '0000')
				AND TypeName='E' 
				AND nTypeId <> '00000' 
				AND (nTypeId LIKE '00004%' OR nTypeId LIKE '0000400002%' OR nTypeId LIKE '0000400001' OR nTypeId LIKE '0000400004')
				AND ntypeid NOT LIKE '0000400003%'
		UNION ALL
		SELECT  nId ,
				nTypeId,
				nParId,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId =@chvOperatorId AND MangerPay = '-99999')
			AND a.TypeName='E' 
			AND l.etypeid=@chvOperatorId
			AND l.type='7'
			
	)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeGxIncome]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeGxIncome
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-05-16
	描述：得到管辖范围内收入类(管辖其他收入+管辖收入)详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeGxIncome
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  
				nid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerRevenue = '0000')
				AND TypeName='G' 
				AND nTypeId <> '00000' 
				AND (nTypeId LIKE '00003%' OR nTypeId LIKE '0000300002%' OR nTypeId LIKE '0000300001%'  OR nTypeId LIKE '0000300004%'  OR nParId LIKE '0000300002%' ) 
				AND UserCode NOT IN ('5102')
				AND ntypeid NOT LIKE '0000300003%'
		UNION ALL
		SELECT  
				a.nId,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A  
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.ntypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerRevenue = '-99999')
			AND a.TypeName='G' 
			AND l.etypeid=@chvOperatorId
			AND L.Type = '6'
	)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeGxInDebt]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeGxInDebt
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-06-07
	描述：获取所有权限范围内管辖负债树形表
*/
CREATE FUNCTION F_AllTreeGxInDebt
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  
				nid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerLiabilities = '0000')
				AND TypeName='L' 
				AND nTypeId <> '00000' 
				AND nTypeId LIKE '00002%' 
		UNION ALL
		SELECT  
				a.nId,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.typeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerLiabilities = '-99999')
			AND a.TypeName='L' 
			AND l.etypeid=@chvOperatorId
			AND L.Type = '5'
	)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeI]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeI
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：MaoXinrong
	日期：2013-04-08
	描述：得到管辖范围内其他收入详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeI
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  nId  AS typeid,
				TypeId AS Atypeid ,
				nId,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '0000')
				AND TypeName='G' 
				AND nTypeId <> '00000' 
				AND (nTypeId = '00003' OR nTypeId LIKE '0000300003%')
		UNION ALL
		SELECT  a.nId  AS typeid,
				a.TypeId AS Atypeid ,
				a.nId,
				a.nTypeId,
				a.nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '-99999')
				AND L.type = '2'
				AND L.etypeid=@chvOperatorId
	)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeIncomeC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeIncomeC
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-05-16
	描述：得到管辖范围内收入类(管辖其他收入+管辖收入)详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeIncomeC
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  
				nid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '0000')
				AND TypeName='G' 
				AND nTypeId <> '00000' 
				AND (nTypeId LIKE '0000300003%' OR nTypeId = '00003' OR nParId LIKE '0000300003%') 
				AND UserCode NOT IN ('5103','5101','032')
				AND nTypeId NOT LIKE '0000300002%'
		UNION 
		SELECT  
				nid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerRevenue = '0000')
				AND TypeName='G' 
				AND nTypeId <> '00000' 
				AND (nTypeId LIKE '00003%' OR nTypeId LIKE '0000300002%' OR nTypeId LIKE '0000300001%' OR nParId='00003' OR nTypeId LIKE '0000300004%'  OR nParId LIKE '0000300002%') 
				AND UserCode NOT IN ('5102')
				AND nTypeId NOT LIKE '0000300003%'
		UNION 
		SELECT  
				DISTINCT a.nId,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerIncome = '-99999')
			AND a.TypeName='G' 
			AND L.Type='2'
			AND l.etypeid=@chvOperatorId
		UNION 
		SELECT  
				DISTINCT a.nId,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerRevenue = '-99999')
			AND a.TypeName='G' 
			AND L.Type='6'
			AND l.etypeid=@chvOperatorId
	)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeInDebtT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeInDebtT
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-05-16
	描述：得到管辖范围内负债合计(管辖负债)详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeInDebtT
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  
				nid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerLiabilities = '0000')
				AND TypeName='L' 
				AND nTypeId <> '00000' 
				AND nTypeId LIKE '00002%' 
				AND nTypeId<>'0000200006'
		UNION ALL
		SELECT  
				nid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '0000')
				AND nTypeId='0000200006'
		UNION ALL
		SELECT  
				a.nId,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerLiabilities = '-99999')
				AND l.etypeid = @chvOperatorId 
			AND a.TypeName='L' 
			AND L.Type = '5'
		UNION ALL
		SELECT  
				a.nId,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID = '-99999')
				AND l.etypeid = @chvOperatorId 
			AND L.Type = '0'
			AND a.nTypeId='0000200006'
	)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeK]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_AllTreeK]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据权限范围来确定职员的管辖仓库范围
*/
CREATE FUNCTION F_AllTreeK
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT 	typeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				Name,
				UserCode,
				Comment,
				deleted,
				[Add],
				Tel,
				LinkMan,
				PyCode,
				STypeId,
				XiWaMaxNumber
		FROM 	Stock 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '00000')
				AND TypeId <> '00000' 
		UNION ALL
		SELECT 	K.typeId,
				K.parid,
				K.leveal,
				K.sonnum,
				K.soncount,
				K.FullName,
				K.Name,
				K.UserCode,
				K.Comment,
				K.deleted,
				K.[Add],
				K.Tel,
				K.LinkMan,
				K.PyCode,
				K.STypeId,
				K.XiWaMaxNumber
		FROM 	Stock K INNER JOIN 
				(
					SELECT	DISTINCT
							K.TypeId
					FROM    KType_L L
							INNER JOIN Stock K ON ( L.Flag = 1 AND K.TypeId LIKE L.TypeId + '%')
					WHERE   L.etypeid = @chvOperatorId
					UNION
					SELECT  L.TypeID
					FROM    ktype_l L
					WHERE   L.etypeid = @chvOperatorId AND L.flag = 0
				) M ON M.TypeId = K.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerKTypeID = '-99999')

	)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeOwnerEquityT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeOwnerEquityT
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-11-29
	描述：得到权限范围内所有者权益详细信息-树形结构
*/
CREATE FUNCTION F_AllTreeOwnerEquityT
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (
		SELECT  
				nid,
				nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items 
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOwnerEquity = '0000')
				AND TypeName='A' 
				AND nTypeId <> '00000' 
				AND nTypeId LIKE '00005%' 
		UNION ALL
		SELECT  
				a.nId,
				a.nTypeId,
				nParId,
				ParId ,
				SonNum ,
				SonCount ,
				UserCode ,
				FullName ,
				Name ,
				CreateBank ,
				BankType ,
				IsBank ,
				PyCode ,
				Deleted ,
				TypeName ,
				XiWaMaxNumber ,
				Sysrow ,
				ismodify,
				Comment
		FROM 	dbo.Ac_Items  A 
		INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOwnerEquity = '-99999')
				AND l.etypeid = @chvOperatorId 
			AND a.TypeName='A' 
			AND L.Type = '8'
	)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_AllTreeP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_AllTreeP]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/*
	作者：谢吉康
	日期：2009-9-8
	描述：根据职员权限确定管辖商品范围（包含自由项字段）
*/



CREATE FUNCTION F_AllTreeP
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
AS
RETURN (  	
		SELECT 	P.typeId,
				P.ParId,
				P.leveal,
				P.sonnum,
				p.customitemid,
				p.customitemfrom,
				p.customitemname,
				p.customitemrefid,
				P.soncount,
				P.CanModify,
				P.UserCode,
				P.FullName,
				P.Name,
				P.Standard,
				P.Type,
				P.Area,
				P.Unit1,
				P.Unit2,
				p.BuyUnitId,
				p.SaleUnitId,
				p.StockUnitId,
				p.baseUnitId,
				P.UnitRate1,
				P.UnitRate2,
				P.preprice1,
				P.preprice2,
				P.preprice3,
				P.preprice4,
				P.preprice5,
				P.UsefulLifeMonth,
				P.UsefulLifeDay,
				P.Comment,
				P.recPrice,
				P.deleted,
				P.ColorGroupID,
				P.SizeGroupID,
				P.EntryCode,
				P.IfSerial,
				P.PyCode,
				P.SerialCount,
				P.ValidDays,
				P.DwgNo,
				P.XiWaMaxNumber,
				P.ifuseentrycode,
				R.PreBuyPrice1,
				R.PreBuyPrice2,
				R.PreBuyPrice3,
				R.PreBuyPrice4,
				R.PreBuyPrice5,
				R.PreSalePrice1,
				R.PreSalePrice2,
				R.PreSalePrice3,
				R.PreSalePrice4,
				R.PreSalePrice5,
				R.PreSalePrice6,
				R.PreSalePrice7,
				R.PreSalePrice8,
				R.PreSalePrice9,
				R.PreSalePrice10,
				R.RetailPrice,
				R.TopSalePrice,
				R.LowSalePrice,
				p.stopbuy,
				R.TopBuyPrice,
				p.AssistantUnitId,
				p.ProduceUnitId,
				p.SortID ,
				p.iscombinationproduct,
				p.PtypeCategoryID  ,
				p.IsService
		FROM 	PType P
		INNER JOIN (
			SELECT	PTypeId,
			        unitid,
					PreBuyPrice1,
					PreBuyPrice2,
					PreBuyPrice3,
					PreBuyPrice4,
					PreBuyPrice5,
					PreSalePrice1,
					PreSalePrice2,
					PreSalePrice3,
					PreSalePrice4,
					PreSalePrice5,
					PreSalePrice6,
					PreSalePrice7,
					PreSalePrice8,
					PreSalePrice9,
					PreSalePrice10,
					RetailPrice,
					TopSalePrice,
					LowSalePrice,
					TopBuyPrice
			FROM 	PType_Price
		)R ON R.PTypeId = P.TypeId and p.baseunitid=R.unitid
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
				AND P.TypeId <> '00000' 
		UNION ALL		
		SELECT 	P.typeId,
				P.ParId,
				P.leveal,
				P.sonnum,
				p.customitemid,
				p.customitemfrom,
				p.customitemname,
				p.customitemrefid,
				P.soncount,
				P.CanModify,
				P.UserCode,
				P.FullName,
				P.Name,
				P.Standard,
				P.Type,
				P.Area,
				P.Unit1,
				P.Unit2,
				p.BuyUnitId,
				p.SaleUnitId,
				p.StockUnitId,
				p.baseUnitId,
				P.UnitRate1,
				P.UnitRate2,
				P.preprice1,
				P.preprice2,
				P.preprice3,
				P.preprice4,
				P.preprice5,
				P.UsefulLifeMonth,
				P.UsefulLifeDay,
				P.Comment,
				P.recPrice,
				P.deleted,
				P.ColorGroupID,
				P.SizeGroupID,
				P.EntryCode,
				P.IfSerial,
				P.PyCode,
				P.SerialCount,
				P.ValidDays,
				P.DwgNo,
				P.XiWaMaxNumber,
				P.ifuseentrycode,
				R.PreBuyPrice1,
				R.PreBuyPrice2,
				R.PreBuyPrice3,
				R.PreBuyPrice4,
				R.PreBuyPrice5,
				R.PreSalePrice1,
				R.PreSalePrice2,
				R.PreSalePrice3,
				R.PreSalePrice4,
				R.PreSalePrice5,
				R.PreSalePrice6,
				R.PreSalePrice7,
				R.PreSalePrice8,
				R.PreSalePrice9,
				R.PreSalePrice10,
				R.RetailPrice,
				R.TopSalePrice,
				R.LowSalePrice,
				p.stopbuy,
				R.TopBuyPrice,
				p.AssistantUnitId,
				p.ProduceUnitId,
				p.SortID,
				p.iscombinationproduct,
				p.PtypeCategoryID,
				p.IsService
		FROM 	
			( SELECT	DISTINCT
						P.TypeId
			  FROM      PType_L L
						INNER JOIN PType P ON ( L.Flag = 1
												AND P.TypeId LIKE L.TypeId + '%'
											  )
			  WHERE     L.etypeid = @chvOperatorId
			  UNION
			  SELECT    L.TypeID
			  FROM      ptype_l L
			  WHERE     L.etypeid = @chvOperatorId
						AND L.flag = 0
			) M
		INNER JOIN PType P ON P.TypeId = M.TypeId
		INNER JOIN (
			SELECT	PTypeId,
			        unitid,
					PreBuyPrice1,
					PreBuyPrice2,
					PreBuyPrice3,
					PreBuyPrice4,
					PreBuyPrice5,
					PreSalePrice1,
					PreSalePrice2,
					PreSalePrice3,
					PreSalePrice4,
					PreSalePrice5,
					PreSalePrice6,
					PreSalePrice7,
					PreSalePrice8,
					PreSalePrice9,
					PreSalePrice10,
					RetailPrice,
					TopSalePrice,
					LowSalePrice,
					TopBuyPrice
			FROM 	PType_Price
		)R ON R.PTypeId = P.TypeId and p.baseunitid=R.unitid
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '-99999')
	)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].F_AllTreeS') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_AllTreeS
GO

/*
	作者：MaoXinrong
	日期：2013-04-03
	描述：得到管辖范围内分支机构详细信息-树形结构
*/

CREATE FUNCTION F_AllTreeS
(
	@chvOperatorId	VARCHAR(100)
)
RETURNS @Temp TABLE
(
	TypeId			VARCHAR(50),
	parid			VARCHAR(50),
	leveal			VARCHAR(10),
	sonnum			VARCHAR(10),
	soncount		VARCHAR(10),
	FullName		VARCHAR(66),
	[Name]			VARCHAR(30),
	UserCode		VARCHAR(26),
	Comment			VARCHAR(256),
	LinkMan			VARCHAR(100),
	Address			VARCHAR(100),
	Tel				VARCHAR(100),
	PostCode		VARCHAR(100),
	TaxNo			VARCHAR(100),
	Bank			VARCHAR(100),
	Account			VARCHAR(100),
	deleted			VARCHAR(10),
	PyCode			VARCHAR(500),
	BTypeId1		VARCHAR(50),
	BTypeId2		VARCHAR(50),
	PriceType		tinyint,
	XiWaMaxNumber	NUMERIC(18,0),
	ATypeID			VARCHAR(50),  
	ATypeID2		VARCHAR(50), 
	ATypeID3		VARCHAR(50), 
	IsSelfVerify	VARCHAR(2),
	VerifyID		VARCHAR(50),  
	ATypeID4		VARCHAR(50),  
	calcFullName	VARCHAR(100)  
)
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')
		INSERT INTO @Temp	
		SELECT 	TypeId,
				parid,
				leveal,
				sonnum,
				soncount,
				FullName,
				[Name],
				UserCode,
				Comment,
				LinkMan,
				Address,
				Tel,
				PostCode,
				TaxNo,
				Bank,
				Account,
				deleted,
				PyCode,
				BTypeId1,
				BTypeId2,
				PriceType,
				XiWaMaxNumber,
				ATypeID,
				ATypeID2,
				ATypeID3,
				IsSelfVerify,
				VerifyID,
				ATypeID4,
				calcFullName
		FROM 	SType 		
		WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '00000')
				AND TypeId <> '00000' 		
	ELSE
		INSERT INTO @Temp		
		SELECT 	S.TypeId,
				S.parid,
				S.leveal,
				S.sonnum,
				S.soncount,
				S.FullName,
				S.[Name],
				S.UserCode,
				S.Comment,
				S.LinkMan,
				S.Address,
				S.Tel,
				S.PostCode,
				S.TaxNo,
				S.Bank,
				S.Account,
				S.deleted,
				S.PyCode,
				S.BTypeId1,
				S.BTypeId2,
				S.PriceType,
				S.XiWaMaxNumber,
				S.ATypeID,
				S.ATypeID2,
				S.ATypeID3,
				S.IsSelfVerify,
				S.VerifyID,
				S.ATypeID4,
				S.calcFullName
		FROM 	SType S
		INNER JOIN  SType_l L ON ( (L.flag=0 AND S.typeId=L.typeid) OR (L.Flag=1 AND S.TypeId LIKE L.TypeId + '%'))
		--INNER JOIN F_GetManDetailAllSType(@chvOperatorId) M ON M.TypeId = S.TypeId
		WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerSTypeID = '-99999')
				AND	 L.etypeid = @chvOperatorId			
	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeAccount]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_TreeAccount
GO


/*
	作者：wg 
	日期：2014-11-14
	描述：获取所有管辖的会计科目-树形表
*/
CREATE FUNCTION F_TreeAccount
(
	@OperatorId			VARCHAR(50),
	@Stypeid			VARCHAR(MAX)
)
RETURNS @Temp TABLE(Stypeid VARCHAR(50),Typeid VARCHAR(50))
--@Encode$--
AS
BEGIN
	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_L WHERE etypeid=@OperatorId AND stypeid='00000' AND typeid='00000' AND flag=1)
	BEGIN
		INSERT INTO @Temp(Stypeid,Typeid)
			SELECT S.TypeId,A.TypeId
			FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) S
			INNER JOIN Ac_Account A ON A.StypeId = S.TypeId
			WHERE A.TypeId <> '00000'
	END
	ELSE
	BEGIN
		INSERT INTO @Temp(Stypeid,TypeId) 
			SELECT	DISTINCT L.stypeid, A.TypeId 
			FROM	Ac_Account_L L
			INNER JOIN Ac_Account  A ON (L.Flag=1 AND A.TypeId LIKE L.TypeId + '%') AND A.StypeId = L.stypeid
			INNER JOIN F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) S ON S.TypeId = L.stypeid
			WHERE	L.etypeid = @OperatorId
					AND L.typeid <> '00000'
			UNION
			SELECT	L.stypeid ,L.TypeID
			FROM	Ac_Account_L L
			INNER JOIN F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) S ON S.TypeId = L.stypeid
			WHERE	L.etypeid = @OperatorId
					AND L.typeid <> '00000'
					AND L.flag=0   
			UNION ALL
			SELECT	L.stypeid ,A.TypeId
			FROM	Ac_Account A
			INNER JOIN Ac_Account_L L ON L.stypeid =A.StypeId
			INNER JOIN F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) S ON S.TypeId = L.stypeid
			WHERE	L.etypeid = @OperatorId
					AND L.typeid = '00000'
					AND A.TypeId <> '00000'
	
	END


	RETURN
		
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeAssetsT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeAssetsT]
GO



/*
	作者：duguolei
	日期：2013-05-16
	描述：得到管辖范围内资产(固定资产+银行账户+其他资产)--树形表
*/
CREATE FUNCTION F_TreeAssetsT
(
	@chvOperatorId			varchar(100)
)
RETURNS @table TABLE(nid int,TypeId varchar(100))
--@Encode$--
AS
BEGIN

DECLARE @ver VARCHAR(5)  --判断是否是V3
SELECT @ver=s.subvalue FROM dbo.sysdata s WHERE s.SubName='proinfo'

DECLARE @cardmode VARCHAR(5)  --是否是卡片模式
SELECT  @cardmode=SubValue FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1'

INSERT INTO @table
		SELECT  nId ,
				nTypeId
		FROM  (
						SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '0000')
								AND TypeName ='C'
								AND nTypeId <> '00000' 
								AND (nTypeId='00001' OR nTypeId LIKE '00001%')
								AND nTypeId<>'0000100009'
					    UNION ALL 
					    SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items 
						WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID  = '0000')
								AND (TypeName ='B'   OR  nTypeId='0000100009')
								AND nTypeId <> '00000' 
								AND nTypeId LIKE '00001%'
						UNION ALL 
					    SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items 
						WHERE 	 EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '0000')
								AND	(CASE @cardmode WHEN 1 THEN '3' ELSE '2' END )='2'  --如果卡片模式不差固定资产所有权限0000
							    AND TypeName ='F'
								AND nTypeId <> '00000' 
								AND nTypeId LIKE '0000100002%'  
						UNION ALL
						SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerCpaital = '-99999')
								AND l.etypeid=@chvOperatorId
								AND TypeName='F'
								AND L.type='3'
						UNION ALL
						SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID  = '-99999')
								AND l.etypeid=@chvOperatorId
								AND (TypeName='B'  OR a.nTypeId='0000100009' )
								AND  L.type='0'
								
						UNION ALL
						SELECT  nId ,
								nTypeId,
								UserCode 
						FROM 	dbo.Ac_Items  A 
						INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '-99999')
								AND l.etypeid=@chvOperatorId
								AND TypeName='C'
								AND nTypeId<>'0000100009'
								AND L.type='4'
					) a
		 WHERE (CASE @ver WHEN 1 THEN a.UserCode ELSE '99999' END )<>'1132' 
				AND (CASE @cardmode WHEN 1 THEN a.nId ELSE '99999' END )<>'46'--卡片模式去掉固定资产
				AND (CASE @cardmode WHEN 1 THEN a.nId ELSE '99999' END )<>'26'--卡片模式去掉固定资产
				AND UserCode<>'SYC-1602' 
				AND UserCode<>'SYC-1601' 
		

	RETURN
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeB]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeB]
GO




/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有管辖往来单位-树形
*/
CREATE FUNCTION F_TreeB
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	DECLARE @TypeId varchar(100),
			@Flag	char(1)

	--客户
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID = '00001')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE   TypeId LIKE '00001%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND B.typeId LIKE '00001%'
		UNION
		SELECT L.TypeID
		FROM	btype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0
				AND L.typeId LIKE '00001%'
		
				

	--供货商
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerBTypeID2 = '00002')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM BType WHERE TypeId LIKE '00002%'
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
				AND B.typeId LIKE '00002%'
		UNION
		SELECT L.TypeID
		FROM	btype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0
				AND L.typeId LIKE '00002%'

	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeExpenseC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_TreeExpenseC
GO

/*
	作者：duguolei
	日期：2013-05-16
	描述：获取所有管辖支出类(费用类型+管辖支出)-树形表
*/
CREATE FUNCTION F_TreeExpenseC
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nid INT,TypeId varchar(100))
--@Encode$--
AS
BEGIN

        INSERT  INTO @Temp(nid, TypeId)
			SELECT  nid,TypeId
			FROM  (
						SELECT  nid,nTypeId AS typeid
						FROM    dbo.Ac_Items
						WHERE   EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '0000')
								AND TypeName='E'
								AND nTypeId <> '00000'
								AND (nTypeId LIKE '0000400003%'  OR nParId LIKE '0000400003%' OR nTypeId='00004')
								AND UserCode NOT IN ('042','0404','5401')
								AND nTypeId NOT LIKE '0000400002%'
						UNION 
						SELECT  nid,nTypeId AS typeid
						FROM    dbo.Ac_Items
						WHERE   EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPay = '0000')
								AND TypeName='E'
								AND nTypeId <> '00000'
								AND (nTypeId LIKE '00004%' OR nTypeId LIKE '0000400002%' OR nTypeId LIKE '0000400001' OR nTypeId LIKE '0000400004' OR nParId='00004' OR nParId LIKE '0000400002%')
								AND UserCode NOT IN ('043')
								AND nTypeId NOT LIKE '0000400003%'
						UNION 
						SELECT	DISTINCT nid,ac.nTypeId AS typeid
						FROM	dbo.Ac_Items ac
								INNER JOIN  AType_l L ON ( (L.flag=0 AND ac.nTypeId=L.typeid) OR (L.Flag=1 AND ac.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerExpense = '-99999')
								AND ac.TypeName='E' 
								AND L.etypeid =@chvOperatorId
								AND L.type = '1' 
						UNION 
						SELECT	DISTINCT nid,ac.nTypeId AS typeid
						FROM	dbo.Ac_Items ac
								INNER JOIN  AType_l L ON ( (L.flag=0 AND ac.nTypeId=L.typeid) OR (L.Flag=1 AND ac.nTypeId LIKE L.TypeId + '%'))
						WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPay = '-99999')
								AND ac.TypeName='E' 
								AND L.etypeid =@chvOperatorId
								AND L.type='7'
                   ) a
	RETURN
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeGxAssets]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_TreeGxAssets
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：duguolei
	日期：2013-06-07
	描述：得到管辖范围内管辖其他资产树形结构
*/
CREATE FUNCTION F_TreeGxAssets
(
	@chvOperatorId			varchar(100)
)
RETURNS  @table  TABLE 
(
	nId			VARCHAR(10),
	nTypeId		VARCHAR(60)
)
AS
BEGIN
	
DECLARE @ver VARCHAR(5)

SELECT @ver=s.subvalue FROM dbo.sysdata s WHERE s.SubName='proinfo'


		INSERT INTO @table
		SELECT  nId ,
				nTypeId
		FROM  
		(		
			SELECT  nId ,
					nTypeId
			FROM 	dbo.Ac_Items 
			WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '0000')
					--AND SonNum=0
					AND TypeName ='C'
					AND nTypeId <> '00000' 
					AND nTypeId LIKE '00001%' 
					AND UserCode<>'SYC-1602' 
					AND UserCode<>'SYC-1601' 
					AND nTypeId<>'0000100009' 
			UNION ALL
			SELECT  nId ,
					nTypeId
			FROM 	dbo.Ac_Items  A 
			INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
			WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerOtherCpaital = '-99999')
					AND TypeName='C'
					AND l.etypeid=@chvOperatorId
					AND UserCode<>'SYC-1602' 
					AND UserCode<>'SYC-1601' 
					AND L.Type = '4'
			) a 
			WHERE (CASE @ver WHEN 1 THEN a.nId ELSE '99999' END )<>'28' 

RETURN 

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeIncomeC]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeIncomeC]
GO



/*
	作者：duguolei
	日期：2013-05-16
	描述：获取所有权限范围内 收入类(管辖其他收入+管辖收入)--树形表
*/
CREATE FUNCTION F_TreeIncomeC
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nid INT,TypeId varchar(100))
--@Encode$--
AS
BEGIN
        INSERT  INTO @Temp( nid,TypeId)
            SELECT  nid ,
                    TypeId
            FROM    ( SELECT    nid ,
                                nTypeId AS typeid
                      FROM      dbo.Ac_Items
                      WHERE     EXISTS ( SELECT TOP 1 1 FROM  LoginUser WHERE  ETypeId = @chvOperatorId AND MangerIncome = '0000' )
                                AND TypeName = 'G'
                                AND nTypeId <> '00000'
								AND (nTypeId LIKE '0000300003%' OR nTypeId = '00003' OR nParId LIKE '0000300003%') 
								AND UserCode NOT IN ('5103','5101','032')
								AND nTypeId NOT LIKE '0000300002%'
                      UNION 
                      SELECT    nid ,
                                nTypeId AS typeid
                      FROM      dbo.Ac_Items
                      WHERE     EXISTS ( SELECT TOP 1 1 FROM   LoginUser WHERE  ETypeId = @chvOperatorId AND MangerRevenue = '0000' )
                                AND TypeName = 'G'
                                AND nTypeId <> '00000'
								AND (nTypeId LIKE '00003%' OR nTypeId LIKE '0000300002%' OR nTypeId LIKE '0000300001%' OR nParId='00003' OR nTypeId LIKE '0000300004%'  OR nParId LIKE '0000300002%')
								AND UserCode NOT IN ('5102')
								AND nTypeId NOT LIKE '0000300003%'
                      UNION 
                      SELECT	DISTINCT
                                nid ,
                                ac.nTypeId AS typeid
                      FROM      dbo.Ac_Items ac
                                INNER JOIN AType_L L ON ( ( L.flag = 0 AND ac.nTypeId = L.typeid) OR ( L.Flag = 1 AND ac.nTypeId LIKE L.TypeId + '%' ) )
                      WHERE     EXISTS ( SELECT TOP 1 1 FROM   LoginUser WHERE  ETypeId = @chvOperatorId AND MangerIncome = '-99999' )
                                AND l.etypeid = @chvOperatorId
                                AND TypeName = 'G'
                                AND L.type = '2'
                      UNION 
                      SELECT	DISTINCT
                                nid ,
                                ac.nTypeId AS typeid
                      FROM      dbo.Ac_Items ac
                                INNER JOIN AType_L L ON ( ( L.flag = 0 AND ac.nTypeId = L.typeid) OR ( L.Flag = 1 AND ac.nTypeId LIKE L.TypeId + '%' ) )
                      WHERE     EXISTS ( SELECT TOP 1 1 FROM   LoginUser WHERE  ETypeId = @chvOperatorId AND MangerRevenue = '-99999' )
                                AND l.etypeid = @chvOperatorId
                                AND TypeName = 'G'
                                AND L.type = '6'
                    ) a


	RETURN
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeInDebtT]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeInDebtT]
GO



/*
	作者：duguolei
	日期：2013-05-16
	描述：获取所有权限范围内负债合计(管辖其他负债+账户中的预收)--树形表
*/
CREATE FUNCTION F_TreeInDebtT
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(nid INT,TypeId varchar(100))
--@Encode$--
AS
BEGIN
	INSERT INTO @Temp
		SELECT  nId ,
				ntypeid	AS typeid
		FROM  (
				SELECT  nid,nTypeId 
                FROM    dbo.Ac_Items
                WHERE  	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerLiabilities  = '0000')
						AND TypeName='L'
                        AND nTypeId <> '00000'
                        AND nTypeId LIKE '00002%'  
			    UNION ALL 
				SELECT  nId ,
						nTypeId
				FROM 	dbo.Ac_Items 
				WHERE 	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID  = '0000')
					 AND nTypeId='0000200006'
				UNION ALL
				SELECT  nId ,
						nTypeId	 
				FROM 	dbo.Ac_Items  A 
				INNER JOIN  AType_l L ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
				WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerATypeID  = '-99999')
						AND l.etypeid=@chvOperatorId
						AND a.nTypeId='0000200006' 
						AND  L.type='0'
				UNION ALL
				SELECT  nid,
						ac.nTypeId
				FROM	dbo.Ac_Items ac
				INNER JOIN  AType_l L ON ( (L.flag=0 AND ac.nTypeId=L.typeid) OR (L.Flag=1 AND ac.nTypeId LIKE L.TypeId + '%'))
				WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerLiabilities  = '-99999')
						AND l.etypeid = @chvOperatorId 
						AND TypeName='L'
						AND L.type = '5'
			)a	
			
		RETURN	  
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_TreeP]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_TreeP]
GO



/*
	作者：谢吉康
	日期：2009-9-8
	描述：获取所有权限范围内商品-树形表
*/
CREATE FUNCTION F_TreeP
(
	@chvOperatorId			varchar(100)
)
RETURNS @Temp TABLE(TypeId varchar(100))
--@Encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorId AND MangerPTypeID = '00000')
		INSERT INTO @Temp(TypeId) SELECT TypeID FROM PType 
	ELSE
		INSERT INTO @Temp(TypeId) 
		SELECT	DISTINCT P.TypeId 
		FROM	PType_L L
		INNER JOIN PType  P ON (L.Flag=1 AND P.TypeId LIKE L.TypeId + '%')
		WHERE	L.etypeid = @chvOperatorId
		UNION
		SELECT	L.TypeID
		FROM	ptype_l L
		WHERE	L.etypeid = @chvOperatorId
				AND L.flag=0

	RETURN
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





--数字显示格式化
--用于数据库中提示将数字嵌入字符串中
IF EXISTS ( SELECT  1
            FROM    SysObjects
            WHERE   ID = OBJECT_ID(N'F_DecimalDisplay')
                    AND XType IN ( N'FN', N'IF', N'TF' ) )
    BEGIN
        DROP FUNCTION F_DecimalDisplay
    END
GO
/*
*  @Value 显示的值
*  @Type  类型    DigitConfiguration表中对应ItemName 
*  该函数不处理精度
*/
CREATE FUNCTION dbo.F_DecimalDisplay
    (
      @Value NUMERIC(24, 10) ,
      @Type VARCHAR(50)
    )
RETURNS VARCHAR(50)
AS
    BEGIN
        DECLARE @DecimalLen INT ,
				@ShowType BIT ,
				@Result VARCHAR(50) ,
				@Len INT 
					
        SELECT  @DecimalLen = DecimalDigit ,
                @ShowType = NumberFormat
        FROM    dbo.DigitConfiguration
        WHERE   ItemName = @Type
        SET @Result = LTRIM(STR(ROUND(@Value, @DecimalLen), 38, @DecimalLen))
		--补零
        IF @ShowType = 1
            RETURN @Result
        --末尾0
        SET @Len = LEN(@Result)
        WHILE CHARINDEX('0', @Result, @Len) <> 0
            BEGIN
                SET @Result = SUBSTRING(@Result, 1, @Len - 1)
                SET @Len = @Len - 1
            END
        --无小数
        IF CHARINDEX('.', @Result, @Len) = @Len
            SET @Result = SUBSTRING(@Result, 1, @Len - 1)
        RETURN @Result
    END
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundData]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundData]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理数据小数位数
*/
CREATE FUNCTION F_RoundData
    (
      @Data  NUMERIC(24, 10)  ,		-- 处理数据
      @DigitType VARCHAR(20) 		-- 类型 qty:数量 price:单价 total:金额 discount:扣率 tax:税率 exchangeRate:汇率 percentage:百分比 translateRate:换算率
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE 
		@RESULT	 NUMERIC(24, 10) =@Data ,
		@Digit int=10
	SELECT @Digit=DecimalDigit FROM DigitConfiguration WHERE ItemName=@DigitType
	SELECT @RESULT=ROUND(@Data, @Digit)
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundDataToDisplay]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundDataToDisplay]
GO



/*
*/
CREATE FUNCTION F_RoundDataToDisplay
    (
      @Data  NUMERIC(24, 10)  ,		-- 处理数据
      @DigitType VARCHAR(20) 		-- 类型 qty:数量 price:单价 total:金额 discount:扣率 tax:税率 exchangeRate:汇率 percentage:百分比 translateRate:换算率
    )
returns varchar(50)
as
begin
declare @returnValue varchar(50),
		@ZeroCount	 int,
		@Digit int=10,
		@numberType int=1

if @Data is null
	set @Data = 0
		
SELECT @Digit=DecimalDigit,@numberType = numberformat FROM DigitConfiguration WHERE ItemName=@DigitType
SELECT @returnValue=ltrim(STR(@Data,50,@Digit)) --ROUND(@Data, @Digit)

if @numberType = 1 return @returnValue

if (charindex('.',@returnValue) ='0')--不含小数点的
	return @returnValue 

set @ZeroCount = patindex('%[^0]%',REVERSE(@returnValue)) - 1
set @returnValue = left(@returnValue,len(@returnValue)-@ZeroCount)

if right(@returnValue,1) <> '.'
	return @returnValue
	
return left(@returnValue,len(@returnValue)-1)

end
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundDiscount]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundDiscount]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理扣率小数位数
*/
CREATE FUNCTION F_RoundDiscount
    (
      @Data  NUMERIC(24, 10)  		-- 处理数据
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE @RESULT	 NUMERIC(24, 10) =@Data 
	SELECT @RESULT=dbo.F_RoundData(@Data, 'discount')
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundExchangeRate]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundExchangeRate]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理汇率小数位数
*/
CREATE FUNCTION F_RoundExchangeRate
    (
      @Data  NUMERIC(24, 10)  		-- 处理数据
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE @RESULT	 NUMERIC(24, 10) =@Data 
	SELECT @RESULT=dbo.F_RoundData(@Data, 'exchangeRate')
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundPercentage]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundPercentage]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理百分比小数位数
*/
CREATE FUNCTION F_RoundPercentage
    (
      @Data  NUMERIC(24, 10)  		-- 处理数据
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE @RESULT	 NUMERIC(24, 10) =@Data 
	SELECT @RESULT=dbo.F_RoundData(@Data, 'percentage')
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundPrice]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundPrice]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理单价小数位数
*/
CREATE FUNCTION F_RoundPrice
    (
      @Data  NUMERIC(24, 10)  		-- 处理数据
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE @RESULT	 NUMERIC(24, 10) =@Data 
	SELECT @RESULT=dbo.F_RoundData(@Data, 'price')
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundQty]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundQty]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理数量小数位数
*/
CREATE FUNCTION F_RoundQty
    (
      @Data  NUMERIC(24, 10)  		-- 处理数据
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE @RESULT	 NUMERIC(24, 10) =@Data 
	SELECT @RESULT=dbo.F_RoundData(@Data, 'qty')
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundTax]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundTax]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理税率小数位数
*/
CREATE FUNCTION F_RoundTax
    (
      @Data  NUMERIC(24, 10)  		-- 处理数据
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE @RESULT	 NUMERIC(24, 10) =@Data 
	SELECT @RESULT=dbo.F_RoundData(@Data, 'tax')
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundTotal]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundTotal]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理金额小数位数
*/
CREATE FUNCTION F_RoundTotal
    (
      @Data  NUMERIC(24, 10)  		-- 处理数据
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE @RESULT	 NUMERIC(24, 10) =@Data 
	SELECT @RESULT=dbo.F_RoundData(@Data, 'total')
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_RoundTranslateRate]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_RoundTranslateRate]
GO



/*
	作者：施训果
	日期：2015-09-30
	描述：处理换算率小数位数
*/
CREATE FUNCTION F_RoundTranslateRate
    (
      @Data  NUMERIC(24, 10)  		-- 处理数据
    )
RETURNS  NUMERIC(24, 10) 
--@encode$--
AS 
BEGIN
	DECLARE @RESULT	 NUMERIC(24, 10) =@Data 
	SELECT @RESULT=dbo.F_RoundData(@Data, 'translateRate')
	RETURN @RESULT	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[F_CheckDecimal]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[F_CheckDecimal]
GO


/*
描述：检查小数位数 返回值小于0 
	  小数位数超出系统配置位数
*/
CREATE FUNCTION F_CheckDecimal
    (
      @Str  VARCHAR(50) ,	
      @Type INT	,
      @Length INT = 0 --默认小数位数 
      /*
		1	数量	qty
		2	单价	price
		3	金额	total
		4	扣率	discount
		5	税率	tax
		6	汇率	exchangeRate
		7	百分比	percentage
		8	换算率	translateRate
      */	
    )
RETURNS  INT 
--@encode$--
AS 
BEGIN
	
	DECLARE @RESULT	 INT=0
	
	IF @Length IS NULL OR @Length = 0
	BEGIN
			SELECT	@Length = DecimalDigit
			FROM	dbo.DigitConfiguration
			WHERE	ItemId=@Type
	END
	
	IF @Str IS NULL OR @Str = ''
		RETURN @RESULT
		
	IF(CHARINDEX('.',@Str) > 0)
	BEGIN
		RETURN @Length - (LEN(@Str) - CHARINDEX('.',@Str)) 
	END

	RETURN @RESULT
	
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_ConcatSerial]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_ConcatSerial]
GO


--实现序列号分类拼接功能 的函数
--date    :2015-05-14
CREATE FUNCTION F_ConcatSerial
(
	@KtypeID VARCHAR(50) ,		
	@ItemID VARCHAR(50) ,
	@CargoID VARCHAR(50) ,
	@ProduceDate VARCHAR(50) ,
	@ValidDate VARCHAR(50) ,
	@CostPrice  NUMERIC(24, 10) ,
	@GoodsNumber VARCHAR(50),
	@PtypeID VARCHAR(50) ,
	@BTypeId VARCHAR(50) , 	
	@STypeId VARCHAR(50) ,	
	@Type INT ,	
	@SerialType INT 
)

returns VARCHAR(MAX)
AS 
BEGIN
    DECLARE @Str VARCHAR(MAX)
    SET @Str = ''  
    IF @Type=140
    SELECT @Str=@Str+'я'+[Serial] 
    FROM gp_initPtypeSerial
    WHERE PtypeID=@PtypeID AND STypeId=@STypeId AND [State]=@SerialType AND BTypeID1=@BTypeId AND [KtypeID]=@KtypeID AND [ItemID]=@ItemID 
    AND CargoID=@CargoID AND ProduceDate=@ProduceDate AND ValidDate=@ValidDate AND CostPrice=@CostPrice AND GoodsNumber=@GoodsNumber
    
	ELSE 
	
	SELECT @Str=@Str+'я'+[Serial] 
    FROM gp_initPtypeSerial
    WHERE PtypeID=@PtypeID AND STypeId=@STypeId AND [State]=@SerialType AND BTypeID2=@BTypeId AND [KtypeID]=@KtypeID AND [ItemID]=@ItemID 
    AND CargoID=@CargoID AND ProduceDate=@ProduceDate AND ValidDate=@ValidDate AND CostPrice=@CostPrice AND GoodsNumber=@GoodsNumber
    -- 删除字符串最前面的‘я’
    IF LEN(@Str)>0
    SET @Str=RIGHT(@Str,LEN(@Str)-1);
    RETURN @Str
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[f_get_LastDayDate]')
                    AND xtype IN ( N'FN', N'IF', N'TF' ) ) 
    DROP FUNCTION [dbo].[f_get_LastDayDate]
GO


 CREATE FUNCTION f_get_LastDayDate(@dateString NVARCHAR(25))
     RETURNS DATETIME
 AS
 BEGIN
     
     SELECT @dateString = 
     DATEADD(
         /** 将参数3指定的时间加上参数2的天数 **/
         DAY,
 
         /** 
             例如：@dateString = 2015-10-23 23:59:59
            获取 @dateString 的时间 天 部分，因为第三个参数，把@dateString加了一个月，得到的时间就是 2015-11-23 23:59:59
            这个时间的 DAY 部分,也就是 23 就是下个月 1-23号的天数，第三个参数 减去 这个天数，得到的就是前一个月的最后一天  
        **/
         -(DATEPART(DAY,@dateString)),

         /* 将@date 加上一个月，得到的就是下个月的今天的具体时间 */
        DATEADD(MONTH,1,@dateString)
     )
     RETURN @dateString
 END
 GO
 SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetBillCode]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetBillCode]
GO

/*
	作者：duguolei	
	日期：2013-01-15
	描述：通过表名获取功能提示
*/
CREATE  FUNCTION F_GetBillCode
(
	@BType		INT,
	@MONTH		VARCHAR(500), 		--自动产生编号时为月份，自定义编号时是经手人名字
	@DAY		VARCHAR(500),		--自动产生编号时为日期，自定义编号时为仓库名
	@BillFlag	VARCHAR(100),
	@BillDate	VARCHAR(100)='',
	@Stypeid	VARCHAR(500)='',	--分支机构名称	
	@DFullName  VARCHAR(500)='',	--部门
	@BillNumberId	INT = -1,
	@groupid	int	,	--增长id
	@maxseed   int      --基础种子数
)	
returns varchar(500)
AS 
BEGIN
	
DECLARE @BillCodeConfig varchar(1),@FlowLen INT, @BCode		VARCHAR(500) 
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置

DECLARE @IfBillCode INT
SELECT @IfBillCode=Value FROM UserConfig WHERE ConfigName='IfBillCode'
IF @BillNumberId=-999 ---库存预警生单 强行置为空
SET @BCode=''
--提车规则单不需要分支机构，强行置为空
IF @BType=164 OR @BType=309
	SET @Stypeid=''

IF @IfBillCode=0
BEGIN
	SET @BCode=''
	RETURN ''
END

IF @BillDate=''
BEGIN
	SELECT @BillDate=CAST(YEAR(GETDATE()) AS VARCHAR(4))+'-'+CAST(MONTH(GETDATE()) AS VARCHAR(2))+'-'+CAST(DAY(GETDATE()) AS VARCHAR(2))
END

--增加的判断。当已保存的单据（草稿、全面修改）切换再切换时，如果影响单据编号的条件没有变，直接返回已有单据编号，不更新种子数
DECLARE @yetypeid VARCHAR(50),@yktypeid VARCHAR(50),@ydtypeid VARCHAR(50)
SET @yetypeid = ''
SET @yktypeid = ''
SET @ydtypeid = ''
--如果是经手人，就按经手人、仓库查询
IF EXISTS(SELECT TOP 1 1 FROM dbo.employee WHERE FullName = @MONTH)
BEGIN
	SELECT @yetypeid = typeId FROM dbo.employee WHERE FullName = @MONTH
	SELECT @yktypeid = typeId FROM dbo.Stock WHERE FullName = @DAY
END

SELECT @ydtypeid = typeid FROM dbo.Department WHERE FullName = @DFullName
IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex 
			WHERE BillNumberId = @BillNumberId
				AND (etypeid = @yetypeid  OR @yetypeid = '')
				AND (ktypeid = @yktypeid OR @yktypeid = '')
				AND (BillDate = @BillDate OR @BillDate = '')
				AND (Stypeid = @Stypeid OR @Stypeid = '')
				AND (DTypeId = @ydtypeid OR @ydtypeid = '') )
		AND @BType NOT IN (300,301,404,405,311,306)
BEGIN
	SELECT @BCode = BillCode FROM dbo.BillIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillCode = @BCode AND BillNumberId <> @BillNumberId)
		SET @BCode = ''
END
	
ELSE IF	EXISTS(SELECT TOP 1 1 FROM dbo.OrderIndex 
		WHERE BillNumberId = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (ktypeid = @yktypeid OR @yktypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			AND (Stypeid = @Stypeid OR @Stypeid = '')
			AND (DTypeId = @ydtypeid OR @ydtypeid = '') )
	AND @BType IN (300,301)
BEGIN
	SELECT @BCode = BillCode FROM dbo.OrderIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.OrderIndex WHERE Billcode = @BCode AND billNumberId <> @BillNumberId)
		SET @BCode = ''
END
ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex 
		WHERE BillNumberId = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			AND (Stypeid = @Stypeid OR @Stypeid = '')
			AND (DTypeId = @ydtypeid OR @ydtypeid = '') )
	AND @BType IN (404,405)
BEGIN
	SELECT @BCode = BillCode FROM dbo.ReceiptBillIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex WHERE BillCode = @BCode AND BillNumberID <> @BillNumberId)
		SET @BCode = ''
END
ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.CommissionBillNew 
		WHERE BillNumberId = @BillNumberId
			AND (BillDate = @BillDate OR @BillDate = '')
			)
	AND @BType IN (311)
BEGIN		
	SELECT @BCode = BillCode FROM dbo.CommissionBillNew WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.CommissionBillNew WHERE BillCode = @BCode AND BillNumberId <> @BillNumberId)
		SET @BCode = ''
END
ELSE IF	EXISTS(SELECT TOP 1 1 FROM dbo.StockCheckIndex 
		WHERE StockCheckID = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			)
	AND @BType IN (306)
BEGIN		
	SELECT @BCode = BillCode FROM dbo.StockCheckIndex WHERE StockCheckID = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.StockCheckIndex WHERE BillCode = @BCode AND StockCheckID <> @BillNumberId)
		SET @BCode = ''
END

IF isnull(@BCode,'') <> ''
	 RETURN ''


SELECT @FlowLen=CAST(Value AS INT)+3 FROM UserConfig WHERE ConfigName='FlowLen'

DECLARE
	@FlowDate				VARCHAR(100)
	
--单据编号配置
DECLARE @BillcodeCreateTime varchar(5),@FlowSet varchar(5),@BillcodeDateSeparator varchar(5),
		@monthSeparator varchar(5),@daySeparator varchar(5),@yearSeparator varchar(5)
SELECT  @BillcodeCreateTime=value FROM Userconfig WHERE ConfigName='BillcodeCreateTime' 
SELECT  @FlowSet=value FROM Userconfig WHERE ConfigName='FlowSet'
SELECT  @BillcodeDateSeparator=Value FROM Userconfig WHERE ConfigName='BillcodeDateSeparator' 

DECLARE @ProInfo varchar(5),@QpEdit VARCHAR(5)
SELECT  @ProInfo=SubValue FROM sysdata WHERE SubName='ProInfo'
SELECT  @QpEdit=SubValue FROM sysdata WHERE SubName='QPEdition'


IF @BillcodeDateSeparator='0'
	SELECT @monthSeparator='-',@daySeparator='',@yearSeparator='-'
ELSE IF @BillcodeDateSeparator='1'
	SELECT @monthSeparator='.',@daySeparator='',@yearSeparator='.'
ELSE IF @BillcodeDateSeparator='2'
	SELECT @monthSeparator='月',@daySeparator='日',@yearSeparator='年'
ELSE IF @BillcodeDateSeparator='3'
	SELECT @monthSeparator='',@daySeparator='',@yearSeparator=''
ELSE IF @BillcodeDateSeparator='4'
	SELECT @monthSeparator=' ',@daySeparator='',@yearSeparator=' '
	
IF @FlowSet=0
BEGIN
	--按日
	SELECT @FlowDate=DBO.FN_FixStr(4,CAST(YEAR(@BillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@BillDate) AS VARCHAR(2)),'0')+DBO.FN_FixStr(2,CAST(DAY(@BillDate) AS VARCHAR(2)),'0')
END
ELSE IF @FlowSet=1
BEGIN
	--按月
	SELECT @FlowDate=DBO.FN_FixStr(4,CAST(YEAR(@BillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@BillDate) AS VARCHAR(2)),'0')
END
ELSE IF @FlowSet=2
BEGIN
	--按年
	SELECT @FlowDate=DBO.FN_FixStr(4,CAST(YEAR(@BillDate) AS VARCHAR(4)),'0')
END

DECLARE @szSUsercode varchar(500)
SET @szSUserCode=''
IF EXISTS( SELECT * FROM SType WHERE TypeId=@Stypeid)
		SELECT @szSUserCode=UserCode FROM SType WHERE TypeId=@Stypeid

IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@BType ) AND @BillCodeConfig='1'
 --单据采用自定义编号 #02
BEGIN

	DECLARE @Code1 varchar(100),@Code2 varchar(100),@Code3 varchar(100),@Code4 varchar(100),@Code5 varchar(100),
			@Code6 varchar(100),@Code7 varchar(100),@Code8 varchar(100),@Code9 varchar(100),@Code10 varchar(100),
			@Code11 varchar(100),@Code12 varchar(100)
	DECLARE @szEUsercode varchar(100)
	DECLARE @szKusercode varchar(100)
	DECLARE @szDUsercode VARCHAR(100)

	SET @szEUsercode=''
	SET @szKusercode=''
	SET @szDUsercode=''
	
	
	IF EXISTS( SELECT * FROM employee WHERE FullName=@MONTH)
		SELECT @szEUserCode=UserCode FROM employee WHERE FullName=@MONTH
	IF EXISTS( SELECT * FROM stock WHERE FullName=@DAY)
		SELECT @szKUserCode=UserCode FROM stock WHERE FullName=@DAY
	IF EXISTS(SELECT * FROM dbo.Department WHERE FullName=@DFullName )
		SELECT @szDUserCode=UserCode FROM dbo.Department WHERE FullName=@DFullName
	
	DECLARE
		@intFlowType			INT,		--1，按日，2按月，3按年
		@TempCode				VARCHAR(1000)


	SELECT 	@Code1=code1,@Code2=code2,@Code3=code3,@Code4=code4,@Code5=code5,@Code6=code6,@Code7=code7,@Code8=code8,
			@Code9=code9,@Code10=code10,@Code11=code11,@Code12=code12  FROM CodeConfig WHERE BillType = @BType

	SET @TempCode = @Code1 +'%'+ @Code2 +'%'+ @Code3 +'%'+ @Code4 +'%'+ @Code5 +'%'+ @Code6 +'%'+ @Code7 +'%'+ @Code8 +'%'+ @Code9 +'%'+ @Code10 +'%'+ @Code11 +'%'+ @Code12

	--dbo.F_Get_YMD_NEW为自定义转换函数
	SELECT 	@Code1=dbo.F_Get_YMD_NEW(code1,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code2=dbo.F_Get_YMD_NEW(code2,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code3=dbo.F_Get_YMD_NEW(code3,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)
	,@Code4=dbo.F_Get_YMD_NEW(code4,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code5=dbo.F_Get_YMD_NEW(code5,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
	@Code6=dbo.F_Get_YMD_NEW(code6,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code7=dbo.F_Get_YMD_NEW(code7,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
	@Code8=dbo.F_Get_YMD_NEW(code8,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
			@Code9=dbo.F_Get_YMD_NEW(code9,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code10=dbo.F_Get_YMD_NEW(code10,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
			@Code11=dbo.F_Get_YMD_NEW(code11,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code12=dbo.F_Get_YMD_NEW(code12,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)  FROM CodeConfig WHERE BillType = @BType
	DECLARE @Code varchar(500)
	SET @Code = @Code1 +'%'+ @Code2 +'%'+ @Code3 +'%'+ @Code4 +'%'+ @Code5 +'%'+ @Code6 +'%'+ @Code7 +'%'+ @Code8 +'%'+ @Code9 +'%'+ @Code10 +'%'+ @Code11 +'%'+ @Code12
	
	DECLARE
		@intByKTypeID		INT,
		@intByETypeID		INT,
		@intByDTypeID		INT,
		@intBySTypeID		INT,
		@KTypeID			VARCHAR(50),
		@ETypeID			VARCHAR(50)
		,@DTypeId VARCHAR(50)
		
	--是否更新种子数
	DECLARE @UpdateSeed int
	SET @UpdateSeed = 1
	IF UPPER(@Code1)='#KK#' OR UPPER(@Code2)='#KK#' OR UPPER(@Code3)='#KK#' OR UPPER(@Code4)='#KK#' OR UPPER(@Code5)='#KK#' OR UPPER(@Code6)='#KK#' OR UPPER(@Code7)='#KK#' OR UPPER(@Code8)='#KK#' OR UPPER(@Code9)='#KK#' OR UPPER(@Code10)='#KK#' OR UPPER(@Code11)='#KK#' OR UPPER(@Code12)='#KK#'
	BEGIN
		SET @intByKTypeID=1

		IF @szKUserCode=''
		BEGIN
			SELECT @KTypeID=''
		END
		ELSE
		BEGIN
			SELECT @KTypeID=TypeID
			FROM Stock
			WHERE UserCode=@szKUserCode
		END
	END
	ELSE
	BEGIN
		SET @intByKTypeID=0
	END

	IF UPPER(@Code1)='#EE#' OR UPPER(@Code2)='#EE#' OR UPPER(@Code3)='#EE#' OR UPPER(@Code4)='#EE#' OR UPPER(@Code5)='#EE#' OR UPPER(@Code6)='#EE#' OR UPPER(@Code7)='#EE#' OR UPPER(@Code8)='#EE#' OR UPPER(@Code9)='#EE#' OR UPPER(@Code10)='#EE#' OR UPPER(@Code11)='#EE#' OR UPPER(@Code12)='#EE#'
	BEGIN
		SET @intByETypeID=1

		IF @szEUserCode=''
		BEGIN
			SELECT @ETypeID=''
		END
		ELSE
		BEGIN
			SELECT @ETypeID=TypeID
			FROM Employee
			WHERE UserCode=@szEUserCode
		END
	END
	ELSE
	BEGIN
		SET @intByETypeID=0
	END

	IF UPPER(@Code1)='#BM#' OR UPPER(@Code2)='#BM#' OR UPPER(@Code3)='#BM#' OR UPPER(@Code4)='#BM#' OR UPPER(@Code5)='#BM#' OR UPPER(@Code6)='#BM#' OR UPPER(@Code7)='#BM#' OR UPPER(@Code8)='#BM#' OR UPPER(@Code9)='#BM#' OR UPPER(@Code10)='#BM#' OR UPPER(@Code11)='#BM#' OR UPPER(@Code12)='#BM#'
	BEGIN
		SET @intByDTypeID=1

		IF @szDUserCode=''
		BEGIN
			SELECT @DTypeId=''
		END
		ELSE
		BEGIN
			SELECT @DTypeId=TypeID
			FROM dbo.Department
			WHERE UserCode=@szDUserCode
		END
	END
	ELSE 
		SET @intByDTypeID=0
	
	--提成规则单不要分支机构
	IF (@Stypeid=''OR @Stypeid=NULL) AND @BType<>164
		SET @UpdateSeed = 0
		
	--参照计划提成不要分支机构
	IF (@Stypeid=''OR @Stypeid=NULL) AND @BType<>309
		SET @UpdateSeed = 0

	--生成单据编号的要素不够，返回空单据编号
	--IF @UpdateSeed=0
	--BEGIN
	--	SELECT @BCode=''
	--	RETURN  ''
	--END
	
	SELECT 
		@KTypeID=ISNULL(@KTypeID,''),
		@ETypeID=ISNULL(@ETypeID,''),
		@DTypeId=ISNULL(@DTypeId,'')

	--若有仓库，替换为仓库编号
	SET @Code = REPLACE(@Code,'#KK#',@szKUserCode)
	--若有经手人，替换为经手人编号
	SET @Code = REPLACE(@Code,'#EE#',@szEusercode)
	--若有部门，替换
	SET @Code=REPLACE(@Code,'#BM#',@szDUsercode)
	
	SET @Code = REPLACE(@Code,'%','')
	SET @Code = RTRIM(@Code)
	--没有编号设置返回空字符串
	IF @Code = '' 
	BEGIN
		SET @BCode = ''
		RETURN ''
	END

	
	--长度超过96位截断成96位
	IF LEN(@Code)>96 
	BEGIN
		SELECT @Code=SUBSTRING(@Code,1,96)
	END
	
	

	DECLARE @MaxNumber varchar(20)
	
	declare @MaxNumber_T int
	
	--SELECT @MaxNumber_T=isnull(MAX(Seed),0)
	--FROM BillCode_Seed
	--WHERE BillType=@BType
	--	and STypeID=@STYpeID
	--	and FlowDate =@FlowDate
	--	and ((@intByKTypeID=1 and KTypeID=@KTypeID)or (@intByKTypeID<>1 and KTypeID=''))
	--	and ((@intByETypeID=1 and ETypeID='')or (@intByETypeID<>1 and ETypeID=''))
	--	and ((@intByDTypeID=1 and DTypeID='')or (@intByDTypeID<>1 and DTypeID=''))
		
	set @MaxNumber_T=@maxseed+@groupid
	
	
	SELECT @MaxNumber=CAST(@MaxNumber_T AS VARCHAR(100))

	--A8
	--IF @ProInfo='2' OR (@ProInfo='3' AND @QpEdit IN('2','4','5'))
	
	IF @ProInfo='2'
		SELECT @BCode =@BillFlag+'-'+@szSUsercode+'-'+@Code+'-'+DBO.FN_FixStr(@FlowLen,CAST(@MaxNumber AS VARCHAR(100)),'0')
	ELSE
		SELECT @BCode =@BillFlag+'-'+@Code+'-'+DBO.FN_FixStr(@FlowLen,CAST(@MaxNumber AS VARCHAR(100)),'0')
END
ELSE
BEGIN
     -- chen_qihua 单据编号自定义改为 200 长度 -- #&**&#	
	 -- DECLARE @BCFirstChar VARCHAR(50),@bMon bit,@bDay bit,@billcode VARCHAR(25),@temp VARCHAR(4),@t INT,@AutoBillCode VARCHAR(50)
	 DECLARE @BCFirstChar VARCHAR(50),@bMon bit,@bDay bit,@billcode VARCHAR(200),@temp VARCHAR(4),@t INT,@AutoBillCode VARCHAR(200)

	 DECLARE @tYear VarChar(4), @tMonth VARCHAR(2),@tday VARCHAR(2)
	 Set @tYear = Year(@BillDate)
	 IF len(@tYear) <> 4 
		Set @tYear = '20' + @tYear


	 SELECT @MONTH=MONTH(@BillDate),@DAY=DAY(@BillDate)

	
	 SELECT @tmonth=RIGHT(CAST(@MONTH+100 AS VARCHAR(10)),2)
	 SELECT @tday=RIGHT(CAST(@DAY+100 AS VARCHAR(10)),2)



	
	 SELECT @BCode=''
	 SELECT @AutoBillCode=Value FROM Userconfig WHERE ConfigName='IfBillCode'
	 IF @AutoBillCode='0' RETURN ''
	
	 SELECT @BCFirstChar=Value FROM Userconfig WHERE ConfigName='Billcodeindex'
	 
	--判断编号的日期规则
	--判断是否按仓库或经手人来计数
	SELECT @billcode=CAST(@maxseed+@groupid AS VARCHAR(100))
	--FROM BillCode_Seed
	--WHERE BillType=@BType AND FlowDate=@FlowDate AND ETypeID='' AND KTypeID='' AND STypeID=@STYpeID


	--对长度进行限定
	
	IF @billcode IS NULL
	Begin
	   Select @billcode='1'
	End

	SELECT @billcode=@tYear + @yearSeparator + @tmonth + @monthSeparator + @tday + @daySeparator + '-' + DBO.FN_FixStr(@FlowLen,@billcode,'0')

	--A8或者提成规则单,汽配3S有分支机构
	--IF (@ProInfo='2' AND @BType<>164) OR (@ProInfo='3' AND @QpEdit IN('2','4','5') AND @BType<>164)
	IF (@ProInfo='2' AND @BType<>164 AND @BType<>309 AND @BType<>410)
	BEGIN
		IF @szSUserCode='' OR @szSUserCode=null
		BEGIN
			SELECT @BCode=''
			RETURN ''
		END
		ELSE
		BEGIN
			IF ISNULL(@BCFirstChar,'')=''
				SELECT @BCode=@BillFlag+'-'+@szSUserCode+'-'+@billcode
			ELSE
				SELECT @BCode=@BillFlag+'-'+@szSUserCode+'-'+ISNULL(@BCFirstChar,'')+'-'+@billcode
		END
	END
	ELSE
	
	BEGIN

		IF ISNULL(@BCFirstChar,'')=''
			SELECT @BCode=@BillFlag+'-'+@billcode
		ELSE
			SELECT @BCode=@BillFlag+'-'+ISNULL(@BCFirstChar,'')+'-'+@billcode

	END
END


SELECT @BCode=SUBSTRING(@BCode,1,200)
	
	return @BCode
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetRequestQTY]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetRequestQTY
GO

-- ========================================================================
-- 功能说明：
-- 作者：  
-- 时间：
-- ========================================================================
CREATE  FUNCTION  F_GetRequestQTY
(
	@RequestBillID  [numeric] (10, 0)
)
RETURNS INT
AS  
BEGIN 
   DECLARE @RequestQTY NUMERIC(24,10)
  
   SELECT @RequestQTY=SUM((CASE WHEN o.BillOver=1 THEN ReachQty ELSE qty END)) FROM dbo.OrderBill o WHERE RequestBillID=@RequestBillID
   
    
   RETURN ISNULL(@RequestQTY,0)
  
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE name='F_GetVipTemplateCardTypeName' )
	DROP FUNCTION [dbo].F_GetVipTemplateCardTypeName
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- =============================================
-- 作者:		得到指定会员短信模板 发送对象
-- 日期:		2017-10-26
-- =============================================
CREATE FUNCTION dbo.F_GetVipTemplateCardTypeName
(
    @smsId		INT,--ID 
    @Type		INT --1:typeid,2:fullname
) 
RETURNS VARCHAR(MAX)     
AS 
BEGIN
	DECLARE @FullName VARCHAR(MAX)=''
	IF EXISTS(SELECT * FROM SMSInfo_Template_CardType WHERE smsId=@smsId)
		BEGIN
			SELECT @FullName+=CASE WHEN @Type=1 THEN CAST(S.VipCardTypeID AS VARCHAR(50))+',' 
									WHEN @Type=2 THEN  S.TypeName+',' 
									ELSE '' 
								END
			FROM  SMSInfo_Template_CardType  C
			INNER JOIN nVipCardSet S ON S.VipCardTypeID=C.vipCardTypeID
			WHERE C.smsId=@smsId
		END
	
	IF(@FullName<>'')
		SET @FullName=SUBSTRING(@FullName,1,LEN(@FullName)-1)
	ELSE IF(@FullName='' AND @Type=2)
		SET @FullName='全部卡类型'
	ELSE IF(@FullName='' AND @Type=1)
		SET @FullName='0'
		
	RETURN @FullName
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_splitBy829]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_splitBy829]
GO












--实现split功能 的函数
--date    :2003-10-14
CREATE FUNCTION f_splitBy829
(
	@SourceSql varchar(MAX),
	@StrSeprate varchar(10)
)
returns @temp TABLE(s int identity(1,1), a varchar(MAX))
AS 
BEGIN
    DECLARE @i int
    SET @SourceSql=RTRIM(LTRIM(@SourceSql))
    SET @i=charindex(@StrSeprate,@SourceSql)
    WHILE @i>=1
	    BEGIN
	        INSERT @temp VALUES(LEFT(@SourceSql,@i-1))
	        SET @SourceSql=SUBSTRING(@SourceSql,@i+1,len(@SourceSql)-@i)
	        SET @i=charindex(@StrSeprate,@SourceSql)
	    END
    IF @SourceSql<>'' 
       INSERT @temp VALUES(@SourceSql)
    RETURN 
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getDateFormat1]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].getDateFormat1
GO

create function getDateFormat1(@dt datetime)    
returns varchar(10)    
as    
begin    
    DECLARE @now VARCHAR(10)    
    set @now = STUFF(STUFF(  
      CONVERT(char(8),@dt,112),  
      5,0,N'-'),8,0,N'-')+N''  
    return @now    
end  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇	
	日期：2014-5-6
	描述：业务级别的添加与删除
*/
CREATE PROCEDURE AddandDelCommissionType
(
	@typeid					VARCHAR(50),
	@fullname				VARCHAR(256) ,--类别名称
	@etypeid				VARCHAR(50),  --负责人
	@tag					int --1为添加，--2为删除
	
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE @nReturntype INT,
	@EtypeId_1 [varchar](50),
	@nSoncount INT,
	@nSonnum INT

IF @tag=1
 BEGIN 
	IF EXISTS(SELECT TypeID FROM CommissionType WHERE EtypeID=@etypeid)
	  BEGIN
		   RAISERROR ('当前所选负责人已被其它业务级别使用！',16,1) 
		   RETURN;
	  END
	 IF EXISTS(SELECT id FROM EtypeCommissionType WHERE CommissionTypeID=@typeid)
	  BEGIN
		   RAISERROR ('当前业务级别已被添加职员使用过,不能再分类!',16,1) 
		   RETURN;
	  END 
-- 获得新的typeid
    EXEC @nReturntype= Gp_createId @typeid, 'CommissionType', @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT	  
    IF @nReturntype=-1 
		BEGIN
			RAISERROR('业务级别的分类不能超过10层',16,1)return
		END
		IF @nReturntype=-2 
		BEGIN
			RAISERROR('无法添加基本信息',16,1)return
		END	  
	  INSERT INTO dbo.CommissionType
	          ( TypeID ,
	            ParID ,
	            Sonnum ,
	            soncount,
	            FullName ,
	            EtypeID ,
	            IsSystem
	          )
	  VALUES  ( @EtypeId_1 , -- TypeID - varchar(50)
	            @typeid , -- ParID - varchar(50)
	            0 , -- Sonnum - int
	            0,
	            @fullname , -- FullName - varchar(256)
	            @etypeid , -- EtypeID - varchar(50)
	            1  -- IsSystem - int
	          )
	      UPDATE   CommissionType
            SET     sonnum = @nSonnum + 1,
                    soncount = @nSoncount + 1
            WHERE   typeid = @typeid
            UPDATE  Ptype
            SET     preprice1 = 0,
                    preprice2 = 0,
                    preprice3 = 0,
                    preprice4 = 0,
                    preprice5 = 0,
                    SerialCount = 0,
                    recprice = 0
            WHERE   Typeid = @typeid     
	          
	          
 END
ELSE
 BEGIN
   IF  @typeid='00000'
      BEGIN
		   RAISERROR ('系统内置业务类别不能删除!',16,1) 
		   RETURN;
	  END
   IF EXISTS(SELECT ID FROM EtypeCommissionType WHERE CommissionTypeID=@typeid) OR EXISTS(SELECT ID FROM CommissionRuleLeader WHERE CommissionTypeID=@typeid) OR EXISTS( SELECT ID FROM CommissionRuleLeader WHERE CommissionTypeID='00000')
	  BEGIN
		   RAISERROR ('当前业务类别已被使用不能删除!',16,1) 
		   RETURN;
	  END
	SELECT @nSonnum=Sonnum FROM CommissionType WHERE TypeID=@typeid
	 IF @nSonnum!=0
	  BEGIN
		   RAISERROR ('父节点不能删除,如需要删除请先删除子节点!',16,1) 
		   RETURN;
	  END 
	          IF len(@typeid)>5
						UPDATE CommissionType SET sonNum=sonNum-1,SonCount-=1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
			  IF len(@typeid)=5
						UPDATE CommissionType SET sonNum=sonNum-1,SonCount-=1 WHERE typeid='00000'
					
              DELETE dbo.CommissionType WHERE TypeID=@typeid
 END 	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇	
	日期：2015-09-30
	描述：改了小数点后，保存里更新基本资料
*/
CREATE PROCEDURE ChangeDigitUpdateBasicData
--@encode$--
AS
SET NOCOUNT ON
DECLARE @qtydigit INT ,@pricedigit INT ,@totaldigit INT ,@discountdigit INT , @taxdigit INT ,@exchangeRatedigit INT ,@percentagedigit INT ,@translateRatedigit INT 
SELECT @qtydigit=DecimalDigit FROM DigitConfiguration WHERE  itemname='qty'
SELECT @pricedigit=DecimalDigit FROM DigitConfiguration WHERE  itemname='price'
SELECT @totaldigit=DecimalDigit FROM DigitConfiguration WHERE  itemname='total'
SELECT @discountdigit=DecimalDigit FROM DigitConfiguration WHERE  itemname='discount'
SELECT @taxdigit=DecimalDigit FROM DigitConfiguration WHERE  itemname='tax'
SELECT @exchangeRatedigit=DecimalDigit FROM DigitConfiguration WHERE  itemname='exchangeRate'
SELECT @percentagedigit=DecimalDigit FROM DigitConfiguration WHERE  itemname='percentage'
SELECT @translateRatedigit=DecimalDigit FROM DigitConfiguration WHERE  itemname='translateRate'
---商品价格信息表
UPDATE dbo.PType_Price SET  PreBuyPrice1=CAST(ROUND(PreBuyPrice1, @pricedigit) AS  NUMERIC(24, 10) ),
							PreBuyPrice2=CAST(ROUND(PreBuyPrice2, @pricedigit) AS  NUMERIC(24, 10) ),
							PreBuyPrice3=CAST(ROUND(PreBuyPrice3, @pricedigit) AS  NUMERIC(24, 10) ),
							PreBuyPrice4=CAST(ROUND(PreBuyPrice4, @pricedigit) AS  NUMERIC(24, 10) ),
							PreBuyPrice5=CAST(ROUND(PreBuyPrice5, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice1=CAST(ROUND(PreSalePrice1, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice2=CAST(ROUND(PreSalePrice2, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice3=CAST(ROUND(PreSalePrice3, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice4=CAST(ROUND(PreSalePrice4, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice5=CAST(ROUND(PreSalePrice5, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice6=CAST(ROUND(PreSalePrice6, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice7=CAST(ROUND(PreSalePrice7, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice8=CAST(ROUND(PreSalePrice8, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice9=CAST(ROUND(PreSalePrice9, @pricedigit) AS  NUMERIC(24, 10) ),
							PreSalePrice10=CAST(ROUND(PreSalePrice10, @pricedigit) AS  NUMERIC(24, 10) ),
							RetailPrice=CAST(ROUND(RetailPrice, @pricedigit) AS  NUMERIC(24, 10) ),
							TopSalePrice=CAST(ROUND(TopSalePrice, @pricedigit) AS  NUMERIC(24, 10) ),
							LowSalePrice=CAST(ROUND(LowSalePrice, @pricedigit) AS  NUMERIC(24, 10) ),
							TopBuyPrice=CAST(ROUND(TopBuyPrice, @pricedigit) AS  NUMERIC(24, 10) ),
							ReferPrice=CAST(ROUND(ReferPrice, @pricedigit) AS  NUMERIC(24, 10) )

---商品分支机构价格信息表
 UPDATE dbo.PType_STypePrice SET PreBuyPrice1=CAST(ROUND(PreBuyPrice1, @pricedigit) AS  NUMERIC(24, 10) ),
								PreBuyPrice2=CAST(ROUND(PreBuyPrice2, @pricedigit) AS  NUMERIC(24, 10) ),
								PreBuyPrice3=CAST(ROUND(PreBuyPrice3, @pricedigit) AS  NUMERIC(24, 10) ),
								PreBuyPrice4=CAST(ROUND(PreBuyPrice4, @pricedigit) AS  NUMERIC(24, 10) ),
								PreBuyPrice5=CAST(ROUND(PreBuyPrice5, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice1=CAST(ROUND(PreSalePrice1, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice2=CAST(ROUND(PreSalePrice2, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice3=CAST(ROUND(PreSalePrice3, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice4=CAST(ROUND(PreSalePrice4, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice5=CAST(ROUND(PreSalePrice5, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice6=CAST(ROUND(PreSalePrice6, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice7=CAST(ROUND(PreSalePrice7, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice8=CAST(ROUND(PreSalePrice8, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice9=CAST(ROUND(PreSalePrice9, @pricedigit) AS  NUMERIC(24, 10) ),
								PreSalePrice10=CAST(ROUND(PreSalePrice10, @pricedigit) AS  NUMERIC(24, 10) ),
								RetailPrice=CAST(ROUND(RetailPrice, @pricedigit) AS  NUMERIC(24, 10) ),
								TopSalePrice=CAST(ROUND(TopSalePrice, @pricedigit) AS  NUMERIC(24, 10) ),
								LowSalePrice=CAST(ROUND(LowSalePrice, @pricedigit) AS  NUMERIC(24, 10) ),
								TopBuyPrice=CAST(ROUND(TopBuyPrice, @pricedigit) AS  NUMERIC(24, 10) ),
								ReferPrice=CAST(ROUND(ReferPrice, @pricedigit) AS  NUMERIC(24, 10) ),
								RecPrice=CAST(ROUND(RecPrice, @pricedigit) AS  NUMERIC(24, 10) ),
								RecSalePrice=CAST(ROUND(RecSalePrice, @pricedigit) AS  NUMERIC(24, 10) ),
								RecSendPrice=CAST(ROUND(RecSendPrice, @pricedigit) AS  NUMERIC(24, 10) ),
								RecAppraisalPrice=CAST(ROUND(RecAppraisalPrice, @pricedigit) AS  NUMERIC(24, 10) )

--简易价格促销
UPDATE dbo.PromotePrice SET PromotePrice=CAST(ROUND(PromotePrice, @pricedigit) AS  NUMERIC(24, 10) ) 
-- --往来单位信用额度
--UPDATE dbo.btype_credit SET Credit=CAST(ROUND(Credit, @qtydigit) AS  NUMERIC(24, 10) ) 
--币种
UPDATE dbo.Ac_Currency SET Rate=CAST(ROUND(Rate, @exchangeRatedigit) AS  NUMERIC(24, 10) ) 
---商品单位换算率

UPDATE dbo.PType_Units_Ext SET Rate=CAST(ROUND(Rate, @translateRatedigit) AS  NUMERIC(24, 10) ) 

---分支机构销售计划百分比

UPDATE dbo.StypeSaleplan SET ApportionScale=CAST(ROUND(ApportionScale, @percentagedigit) AS  NUMERIC(24, 10) ) 
--部门销售计划百分比

UPDATE dbo.DtypeSaleplan SET ApportionScale=CAST(ROUND(ApportionScale, @percentagedigit) AS  NUMERIC(24, 10) ) 
--职员销售计划百分比

UPDATE dbo.EtypeSaleplan SET ApportionScale=CAST(ROUND(ApportionScale, @percentagedigit) AS  NUMERIC(24, 10) ) 
--库存预警设置的数量
UPDATE  dbo.StockAlarm
SET     UplimitQty = CAST(ROUND(UplimitQty, @qtydigit) AS  NUMERIC(24, 10) ) ,
        DownLimitQty = CAST(ROUND(DownLimitQty, @qtydigit) AS  NUMERIC(24, 10) ) ,
        OrderQty = CAST(ROUND(OrderQty, @qtydigit) AS  NUMERIC(24, 10) )
--会员卡积分设置
UPDATE dbo.nVipJfSet SET Total=CAST(ROUND(Total, @totaldigit) AS  NUMERIC(24, 10) ) 
--商品会员信息设置
UPDATE  dbo.nVipGoodsSign
SET     VipDiscount1 = CAST(ROUND(VipDiscount1, @discountdigit) AS  NUMERIC(24, 10) ) ,
        VipDiscount2 = CAST(ROUND(VipDiscount2, @discountdigit) AS  NUMERIC(24, 10) ) ,
        VipDiscount3 = CAST(ROUND(VipDiscount3, @discountdigit) AS  NUMERIC(24, 10) ),
        VipDiscount4 = CAST(ROUND(VipDiscount4, @discountdigit) AS  NUMERIC(24, 10) ),
        VipPrice1 = CAST(ROUND(VipPrice1, @pricedigit) AS  NUMERIC(24, 10) ),
        VipPrice2 = CAST(ROUND(VipPrice2, @pricedigit) AS  NUMERIC(24, 10) ),
        VipPrice3 = CAST(ROUND(VipPrice3, @pricedigit) AS  NUMERIC(24, 10) ),
        VipPrice4 = CAST(ROUND(VipPrice4, @pricedigit) AS  NUMERIC(24, 10) ),
        VipPrice5 = CAST(ROUND(VipPrice5, @pricedigit) AS  NUMERIC(24, 10) )
--系统默认的税率与扣率

UPDATE dbo.Userconfig SET Value= CAST(ROUND(Value, @discountdigit) AS  NUMERIC(24, 10) )
		WHERE ConfigName='zekouvalue'
UPDATE dbo.Userconfig SET Value= CAST(ROUND(Value, @taxdigit) AS  NUMERIC(24, 10) )
		WHERE ConfigName='alltaxrate'

--商品默认税率 	
UPDATE dbo.ptype SET BuyDefaultRate= CAST(ROUND(BuyDefaultRate, @taxdigit) AS  NUMERIC(24, 10) ) WHERE BuyDefaultRate IS NOT NULL 

UPDATE dbo.ptype SET SaleDefaultRate= CAST(ROUND(SaleDefaultRate, @taxdigit) AS  NUMERIC(24, 10) ) WHERE SaleDefaultRate IS  NOT NULL 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckCargoCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CheckCargoCount]
GO
/****** Object:  StoredProcedure [dbo].[CheckCargoCount]    Script Date: 05/25/2012 10:53:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[CheckCargoCount] 
(
	@OperatorId			VARCHAR(50),	
	@cargoid			varchar(max)='00000',
	@ptypeid			varchar(max)='00000',
	@ktypeid			varchar(max)
)
--@encode$--	
AS
	SET NOCOUNT ON;
	DECLARE @Sql varchar(8000)
	DECLARE @ReSql varchar(8000)
	DECLARE @SqlWhere varchar(8000)
	create table #ptype( typeid varchar(100))
	insert into #ptype select a from dbo.f_split(@ptypeid,',')
	create table #cargotype( typeid varchar(100))
	insert into #cargotype select a from dbo.f_split(@cargoid,',')
	if @cargoid=''
		set @SqlWhere=@SqlWhere+'gtc.CargoID<>''00000'''
	else
		set @SqlWhere=@SqlWhere+'gtc.CargoID in(select typeid from #cargotype)'
	if @ptypeid=''
		set @SqlWhere=@SqlWhere+' and gtc.PTypeID<>''00000'''
	else
		set @SqlWhere=@SqlWhere+' and gtc.PTypeID in(select typeid from #ptype)'


	select COUNT(*) as count from GOODSSTOCKS_QTY gtc 
				inner join ptype p on p.typeId=gtc.PTypeID
				inner join stock s on s.typeId=gtc.KTypeID
				where gtc.KTypeID=@ktypeid and (gtc.PTypeID<>'00000' or gtc.PTypeID in(select typeid from #ptype))
				and (gtc.CargoID<>'00000' or gtc.CargoID in(select typeid from #cargotype))
				
go
		


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




CREATE    PROCEDURE CheckExpression 
(	
@szSql varchar(8000)
)
--@encode$--
AS
set nocount on
set ANSI_WARNINGS  off
SET ARITHABORT OFF
DECLARE @SQL varchar(8000)
CREATE TABLE #TT(SubValue int)
SET @SQL='INSERT INTO #TT SELECT '+@szSql+' AS GS '
EXEC(@SQL)
IF @@rowcount=0 
BEGIN
	return -2
END
ELSE
BEGIN
	IF EXISTS(SELECT * FROM #TT WHERE SubValue is null)
		RETURN -1
	ELSE
		Return 0
END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  * FROM   dbo.sysobjects  WHERE   id = OBJECT_ID(N'CheckFapiao')  AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE CheckFapiao
GO

CREATE    PROCEDURE CheckFapiao
    (
      @actiontype VARCHAR(100) = '' ,-- 修改 or 删除
      @stypeids  VARCHAR(MAX)='',
      @billcodes VARCHAR(MAX)
    )
    --@encode$--
AS
    SET NOCOUNT ON
    SET ANSI_WARNINGS  OFF

    BEGIN
        IF EXISTS ( SELECT TOP 1  1   FROM
                    dbo.MonthProc a
                    JOIN dbo.f_splitAN(@billcodes, ',') b ON CAST(b.a AS DATE) < a.StartDate 
                    JOIN dbo.f_splitAN(@stypeids,',') C ON b.ID=c.ID AND a.STypeID=c.a
                    WHERE a.MonthNo='本期' )
            BEGIN
                RAISERROR('单据日期小于本期开始日期，不允许%s！',16,1, @actiontype) 
            END
            SELECT 0
 
    END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇	
	日期：2015-09-30
	描述：检测是否可以更改小数位数
*/
CREATE PROCEDURE CheckIsChangeDigit
--@encode$--
AS
SET NOCOUNT ON
DECLARE @msg NVARCHAR(50)
SET @msg='系统已有了相关业务数据，不能更改小数位数，请确认后再试！'

IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE  IsIni=1 )
RAISERROR('系统已存在期初单据，不能直接更改小数位数，如需更改，请先删除期初单据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE  draft=1 AND IsIni=0 AND BillType NOT IN(185,184) )
RAISERROR('系统已存在草稿单据，不能直接更改小数位数，如需更改，请先删除草稿单据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE  draft=0 AND IsIni=0 )
RAISERROR(@msg,16,1)

IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE  draft=1 AND IsIni=0 AND BillType=185 )
RAISERROR('系统已存在询价单，不能直接更改小数位数，如需更改，请先删除询价单后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE  draft=1 AND IsIni=0 AND BillType=184)
RAISERROR('系统已存在报价单，不能直接更改小数位数，如需更改，请先删除报价单后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.OrderIndex) --订单
RAISERROR('系统已存在订单数据，不能直接更改小数位数，如需更改，请先删除订单后再试！',16,1)


IF EXISTS(SELECT 1 FROM dbo.RequestIndex ) --请购单
RAISERROR('系统已存在请购单，不能直接更改小数位数，如需更改，请先删除请购单后再试！',16,1)


IF EXISTS(SELECT 1 FROM   dbo.ReceiptBillIndex ) --暂估发票
RAISERROR('系统已存在暂估发票，不能直接更改小数位数，如需更改，请先删除暂估发票后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PType_STypePrice WHERE recPrice!=0) AND EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'ProInfo' AND SubValue = 2) 
RAISERROR('系统已存在分支机构最近进价，不能直接更改小数位数，如需更改，请先删除分支机构最近进价后再试！',16,1)

--IF EXISTS(SELECT 1 FROM dbo.PType_STypePrice WHERE recPrice!=0) AND EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'ProInfo' AND SubValue<>2) 
--RAISERROR('系统已存在最近进价，不能直接更改小数位数，如需更改，请先删除最近进价后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PType_Price WHERE RecAmgSTypeBuyPrice !=0 )
RAISERROR('系统已存在商品最近进价，不能直接更改小数位数，如需更改，请先删除商品最近进价后再试！',16,1)
IF EXISTS(SELECT 1 FROM dbo.PType_Price WHERE RecAmgSTypeSalePrice !=0 )
RAISERROR('系统已存在商品最近售价，不能直接更改小数位数，如需更改，请先删除商品最近售价后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PType_STypePrice WHERE RecSalePrice!=0  ) AND EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'ProInfo' AND SubValue = 2) 
RAISERROR('系统已存在分支机构最近售价，不能直接更改小数位数，如需更改，请先删除分支机构最近售价后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.LendIndex WHERE  draft=1 AND IsIni=0 )
RAISERROR('系统已存在借欠草稿单据，不能直接更改小数位数，如需更改，请先删除草稿单据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.LendIndex WHERE  draft=0 AND IsIni=0 )
RAISERROR('系统已存在借欠类单据，不能直接更改小数位数，如需更改，请先删除借欠类后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PriceBillIndex ) --高价信息
RAISERROR('系统已存在高价信息，不能直接更改小数位数，如需更改，请先删除高价信息后再试！',16,1)

--价格跟踪
IF EXISTS(SELECT 1 FROM dbo.PriceTrack_SaleOrder )
RAISERROR('系统已存在销售订单价格跟踪，不能直接更改小数位数，如需更改，请先删除销售订单价格跟踪后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PriceTrack_Sale )
RAISERROR('系统已存在销售出库价格跟踪，不能直接更改小数位数，如需更改，请先删除销售出库价格跟踪后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PriceTrack_BuyOrder )
RAISERROR('系统已存在采购订单价格跟踪，不能直接更改小数位数，如需更改，请先删除采购订单价格跟踪后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PriceTrack_Buy )
RAISERROR('系统已存在采购入库价格跟踪，不能直接更改小数位数，如需更改，请先删除采购入库价格跟踪后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PriceTrack_Quote )
RAISERROR('系统已存在报价单价格跟踪，不能直接更改小数位数，如需更改，请先删除报价单价格跟踪后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PriceTrack_AskPrice )
RAISERROR('系统已存在询价单价格跟踪，不能直接更改小数位数，如需更改，请先删除询价单价格跟踪后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PriceTrack_Send )
RAISERROR('系统已存在发出商品价格跟踪，不能直接更改小数位数，如需更改，请先删除发出商品价格跟踪后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.PriceTrack_Appraisal )
RAISERROR('系统已存在暂估入库价格跟踪，不能直接更改小数位数，如需更改，请先删除暂估入库价格跟踪后再试！',16,1)
--价格跟踪 end----

IF EXISTS(SELECT 1 FROM dbo.PromoRule ) --促销
RAISERROR('系统已存在促销政策，不能直接更改小数位数，如需更改，请先删除促销政策后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.ProduceModelIndex ) --生产模版
RAISERROR('系统已存在生产组装模板，不能直接更改小数位数，如需更改，请先删除生产组装模板后再试！',16,1)

IF EXISTS(SELECT 1 FROM  dbo.CommissionBillNew ) --新提成
RAISERROR('系统已存在提成单数据，不能直接更改小数位数，如需更改，请先删除提成单后再试！',16,1)

IF EXISTS(SELECT 1 FROM  dbo.TCBillindex ) --基础提成
RAISERROR('系统已存在基础提成数据，不能直接更改小数位数，如需更改，请先删除基础提成后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.CommissionRule ) --新提成规则
RAISERROR('系统已存在高级提成规则，不能直接更改小数位数，如需更改，请先删除高级提成规则后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.DiyIndex ) --电脑装机配置单
RAISERROR('系统已存在电脑装机配置单，不能直接更改小数位数，如需更改，请先删除电脑装机配置单后再试！',16,1)

----期初建账  
IF EXISTS(SELECT 1 FROM dbo.IniBType_ArApTotal ) --期初分支机构往来部门职员应收应付预收预付数据
RAISERROR('系统已存在往来期初数据，不能直接更改小数位数，如需更改，请先清除往来期初数据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.IniGoodsStocks ) --库存期初
RAISERROR('系统已存在库存期初数据，不能直接更改小数位数，如需更改，请先清除库存期初数据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.IniCommissionStock WHERE Type=140 ) --委托
RAISERROR('系统已存在委托库存期初数据，不能直接更改小数位数，如需更改，请先清除委托库存期初数据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.IniCommissionStock WHERE Type=144 ) --受托
RAISERROR('系统已存在受托库存期初数据，不能直接更改小数位数，如需更改，请先清除受托库存期初数据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.SType_InnerARTotal ) --内部应收期初
RAISERROR('系统已存在内部应收期初数据，不能直接更改小数位数，如需更改，请先清除内部应收期初数据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.inigoodslend ) --借欠
RAISERROR('系统已存在借欠期初数据，不能直接更改小数位数，如需更改，请先清除借欠期初数据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.Wx_IniGoodsStocks ) --维修期初
RAISERROR('系统已存在维修品库存期初数据，不能直接更改小数位数，如需更改，请先清除维修品库存期初数据后再试！',16,1)


IF EXISTS(SELECT 1 FROM dbo.AType_Total WHERE ATypeID=2) --现金银行期初
RAISERROR('系统已存在现金银行期初数据，不能直接更改小数位数，如需更改，请先清除现金银行期初数据后再试！',16,1)

IF EXISTS(SELECT  1
FROM    dbo.Ac_IniAccount
WHERE   iniTotal != 0
        OR iniTotalFor != 0
        OR FDebit != 0
        OR FDebitFor != 0
        OR FCredit != 0
        OR FCreditFor != 0
        OR iniTotal != 0
        OR iniTotalFor != 0
        OR FYTotal != 0
        OR FYTotalFor != 0
        OR FYTotalDebit != 0
        AND FYTotalCreditFor != 0
        OR FYTotalCredit != 0
        OR FYTotalCreditFor != 0 )   --账务期初
RAISERROR('系统已存在账务期初数据，不能直接更改小数位数，如需更改，请先清除账务期初数据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.AType_Total WHERE ATypeID!=2) --其他期初
RAISERROR('系统已存在其他业务期初数据，不能直接更改小数位数，如需更改，请先清除其他业务期初数据后再试！',16,1)

DECLARE @count int 
SELECT @count=COUNT(1)  FROM dbo.PosInfo WHERE IsBinding=1---pos
IF @count>0
RAISERROR('系统已存在绑定的POS客户端，不能直接更改小数位数，如需更改，请先解除绑定POS客户端后再试！',16,1)

---期初建账 end -----

---销售计划
IF EXISTS(SELECT 1 FROM dbo.StypeSaleAllPlan ) AND EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName = 'ProInfo' AND SubValue = 2) --分支机构销售计划
RAISERROR('系统已存在分支机构销售计划数据，不能直接更改小数位数，如需更改，请先清除分支机构销售计划数据后再试！',16,1)


IF EXISTS(SELECT 1 FROM dbo.EtypeSaleAllPlan ) --职员销售计划
RAISERROR('系统已存在职员销售计划数据，不能直接更改小数位数，如需更改，请先清除职员销售计划数据后再试！',16,1)

IF EXISTS(SELECT 1 FROM dbo.DtypeSaleAllPlan ) --部门销售计划
RAISERROR('系统已存在部门销售计划数据，不能直接更改小数位数，如需更改，请先清除部门销售计划数据后再试！',16,1)

---销售计划---end


IF EXISTS (SELECT 1 FROM dbo.Coupon_TypeInfo WHERE CouponType IN (2,3)) --优惠券信息：折扣券有折扣信息，兑换券有商品价格数量金额信息
RAISERROR('系统已存在优惠券名称数据，不能直接更改小数位数，如需更改，请先清除优惠券名称数据后再试！',16,1)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2006-6-6
	描述：打印优化
	
	Comm_StockChangeRep '00001','2000-6-5','2009-6-7','','','','P',0,'','','',14,1,1,'one','','00001','4'

	Comm_StockChangeRep '00001','2000-1-1','2009-6-7','','','','A',0,'','','',14,1,1,'one'

	Comm_StockChangeRep '00001','2000-1-1','2009-6-6','','','','A',0,'','','',14,1,1,'Type'
*/

/*
	修改：赵斌
	日期：2011-07-08
	描述：增加单据类型
*/

/*
	修改：赵斌
	日期：2011-08-29
	描述：增加单据类型(其他出入库)
*/
/*
	修改：hqing	
	日期：2015-05-20
	描述：增加单据类型:[暂估入库 400][暂估退货 401][发出商品出库 402][发出商品退货 403][成本调价 57]
*/
CREATE               PROCEDURE Comm_StockChangeRep
(
	@OperatorID		VARCHAR(100),       		------------操作员id
	@startdate     	varchar(50),
	@EndDate        varchar(50),
	@szPtypeId     	VARCHAR(8000)='',        	--商品ID
	@szKtypeId     	VARCHAR(8000)='',        	--仓库ID
	@szEtypeId      VARCHAR(8000)='',         --经手人     --#-01
	@strBdSp         CHAR(1)='1',
	@Web            INT=0,
	@UserCode       VARCHAR(26)='',
	@FullName       VARCHAR(66)='',
	@PTypeid        VARCHAR(100)='00000',
	@PageRows     	INT=14,
	@GoPageFlag    	INT=0,
	@PageNo         INT=1,
	@szPTypeKind  	VARCHAR(10),     		--'One'是具体商品,'Type'是大类商品
	@szPEntryCode	varchar(200)='',
	@stypeid		VARCHAR(8000),
	@unitconvert    VARCHAR(10),
	@ptypeCategoryid   VARCHAR(max)=''
)
--@encode$--
AS

SET ANSI_WARNINGS OFF
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)


--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX #GetManPTypeId_P_K ON #GetManPTypeId(TypeId)
INSERT INTO #GetManPTypeId(TypeId) 
SELECT TypeId FROM dbo.F_ManPTypeInCategoryID(@OperatorID,@szPtypeId,@ptypeCategoryid)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) SELECT e.TypeId FROM F_GetManDetailEType(@OperatorID) e INNER JOIN  F_GetAllBaseTypeId(@szETypeId,3) se ON e.TypeId=se.TypeId
ELSE
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@szETypeId,3)
	

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@szKtypeId,4) sk ON k.typeid=sk.typeid
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@szKtypeId,4)


DELETE FROM #GetManKTypeId WHERE TypeId NOT IN( SELECT TypeId FROM stock WHERE STypeID IN(SELECT TypeId FROM #GetSelectSTypeId)) --删除分支机构以外的仓库

--自动生成的成本调价,InOutStockTable中Ktypeid=''
INSERT INTO #GetManKTypeId(TypeId) VALUES('')


--单据类型筛选
DECLARE @billtype VARCHAR(MAX)
CREATE TABLE #billtypeTable(Billtype VARCHAR(50))
SELECT @billtype=BillTypes FROM StockTotalConfig WHERE ETypeId=@OperatorID

INSERT INTO #billtypeTable(Billtype)
SELECT DISTINCT CASE WHEN a in(171,172,211,212,1611,1612,1601,1602,1722,571,572,161,162) THEN  SUBSTRING(a,1,len(a)-1) ELSE a  END AS a   
FROM dbo.f_split(@billtype,',') 
WHERE a IS NOT NULL 

	
IF EXISTS(SELECT TOP 1 1 FROM   #billtypeTable WHERE Billtype=34 ) AND  NOT EXISTS( SELECT TOP 1 1 FROM   #billtypeTable WHERE Billtype=205	)
	INSERT INTO	  #billtypeTable VALUES (205)

IF NOT EXISTS(SELECT TOP 1 * FROM #billtypeTable)
BEGIN
	INSERT INTO #billtypeTable(Billtype) VALUES(0)
END

--------------------------------------多单位计算Start-------------------------------------------------------
DECLARE @unitrate    NVARCHAR(200),
		@tmptab      NVARCHAR(2000)
--SET @tmptab=' INNER JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') f ON i.ptypeID=f.typeID '
IF @unitconvert=0
BEGIN
SELECT  @unitrate = 'isnull(r3.rate,1)'
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p1','','3')
END
IF @unitconvert=1
BEGIN
SELECT  @unitrate = 'isnull(r2.rate,1)'
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p1','','2')
END
IF @unitconvert=2
BEGIN
SELECT  @unitrate = 'isnull(r4.rate,1)'
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p1','','4')
END
IF @unitconvert=3 OR @unitconvert=4
BEGIN
SELECT  @unitrate = '1'
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p1','','1')
END
-------------------------------------------多单位计算End--------------------------------------------------
CREATE CLUSTERED INDEX CIX_GetManKTypeID ON #GetManKTypeId(TypeID)

CREATE CLUSTERED INDEX CIX_GetManETypeID ON #GetManETypeId(TypeID)

CREATE CLUSTERED INDEX CIX_GetManSTypeID ON #GetSelectSTypeId(TypeID)


--///////////////////////////////////
           --      查询具体商品
--///////////////////////////////////
IF @szPTypeKind='one'
	BEGIN
		DECLARE @OPTypeIdMx varchar(100)

		IF @PtypeId='' OR @PtypeId IS NULL 
			SET @PtypeId='00000'

		IF @szPTypeId = '' OR @szPTypeId IS NULL
			SET @OPTypeIdMx = '%'
		ELSE
			SET @OPTypeIdMx = @szPTypeId
	
		IF @UserCode IS NULL OR @UserCode=''
	 		SELECT @UserCode='%'
		ELSE
	 		SELECT @UserCode='%'+@UserCode+'%'
	
		IF @FullName IS NULL OR @FullName=''
	 		SELECT @FullName='%'
		ELSE
	 		SELECT @FullName='%'+@FullName+'%'
	
		IF @szKtypeId IS NULL OR @szKtypeId=''
	 		SELECT @szKtypeId='%'
	
	
		DECLARE @Sql VARCHAR(8000),@Condition VARCHAR(300)
		DECLARE @NNN varchar(MAX)
		CREATE TABLE #SumInOutStockTable
		(
			BillType 		int,
			PTypeId			varchar(100),
			Qty				 NUMERIC(24, 10) ,
			CostTotal		 NUMERIC(24, 10) ,
			AdPriceType		INT
		)
	
		SET @NNN = 'INSERT INTO #SumInOutStockTable 
					SELECT 	i.BillType,
							i.PTypeId,
							SUM(i.Qty/'+@unitrate+') AS Qty,
							SUM(i.CostTotal) AS CostTotal,
							CASE WHEN i.BILLTYPE<>57 THEN 0
								 WHEN i.BILLTYPE=57 AND BILLNUMBERID IN (SELECT BILLNUMBERID FROM BILLINDEX WHERE AdPriceType=0) THEN 0
								 WHEN i.BILLTYPE=57 AND BILLNUMBERID IN (SELECT BILLNUMBERID FROM BILLINDEX WHERE AdPriceType=1) THEN 1
								 ELSE 2 END AS AdPriceType
					FROM 	InOutStockTable i
					inner join ptype p1 on p1.typeid=i.ptypeid
					INNER JOIN #billtypeTable B on (i.billtype=b.Billtype OR b.billtype=0  )
					'+@tmptab
					
		IF @MKtypeid='-99999'  OR @szKtypeId<>''		
					SET @NNN=@NNN+'INNER JOIN #GetManKTypeId k	ON i.ktypeid=k.typeid  '
					
					SET @NNN=@NNN+'
					INNER JOIN #GetManPTypeId p ON i.ptypeid=p.typeid
					INNER JOIN #GetManETypeId e ON i.Etypeid=e.typeid
					'
		
		IF @MStypeid='-99999'  OR @StypeId<>''		
					SET @NNN=@NNN+'
					INNER JOIN #GetSelectSTypeId sk On i.stypeid=sk.typeid '
					
					SET @NNN=@NNN+'
					WHERE  	i.Audited = 1
							--AND i.KTypeId <> ''10000''
							AND i.billdate >='+char(39)+@startdate+char(39)+'
							AND i.billdate <='+char(39)+@EndDate+char(39)+'
							AND i.PTypeId LIKE '+char(39)+@OPTypeIdMx+'%'+char(39)+'
					GROUP BY i.BillType,i.PTypeId,i.Qty,i.CostTotal,BILLNUMBERID'

		EXEC(@NNN)
	
		SELECT	ptypeid,
				SUM(CASE WHEN billtype IN(11,12) THEN qty ELSE 0 END) AS [saleqty],
				SUM(CASE WHEN billtype  IN(11,12) THEN costtotal ELSE 0 END) AS [saletotal],
				SUM(CASE WHEN billtype =305 THEN qty ELSE 0 END) AS retaiqty,
				SUM(CASE WHEN billtype =305 THEN costtotal ELSE 0 END) AS retaitotal,
				SUM(CASE WHEN billtype=34 THEN qty ELSE 0 END) AS [buyqty],
				SUM(CASE WHEN billtype IN(34,205) THEN costtotal ELSE 0 END) AS [buytotal],
				SUM(CASE WHEN billtype=6 THEN qty ELSE 0 END) AS [buybackqty],
				SUM(CASE WHEN billtype=6 THEN costtotal ELSE 0 END) AS [buybacktotal],
				SUM(CASE WHEN billtype IN(45,46) THEN qty ELSE 0 END) AS [salebackqty],
				SUM(CASE WHEN billtype IN (45,46) THEN costtotal ELSE 0 END) AS [salebacktotal],
				SUM(CASE WHEN billtype=400 THEN qty ELSE 0 END) AS appraisalbillqty,
				SUM(CASE WHEN billtype=400 THEN costtotal ELSE 0 END) AS appraisalbilltotal,	--暂估入库
				SUM(CASE WHEN billtype=403 THEN qty ELSE 0 END) AS sendbackbillqty,
				SUM(CASE WHEN billtype=403 THEN costtotal ELSE 0 END) AS sendbackbilltotal,	--发出商品退货
				SUM(CASE WHEN billtype=402 THEN qty ELSE 0 END) AS sendbillqty,
				SUM(CASE WHEN billtype=402 THEN costtotal ELSE 0 END) AS sendbilltotal,	--发出商品出库
				SUM(CASE WHEN billtype=401 THEN qty ELSE 0 END) AS appraisalbackbillqty,
				SUM(CASE WHEN billtype=401 THEN costtotal ELSE 0 END) AS appraisalbackbilltotal,	--暂估退货	    
				SUM(CASE billtype WHEN 9 THEN qty ELSE 0 END) AS [loseqty],
				SUM(CASE billtype WHEN 9 THEN costtotal ELSE 0 END) AS [losetotal],
				SUM(CASE billtype WHEN 14 THEN qty ELSE 0 END) AS [overflowqty],
				SUM(CASE billtype WHEN 14 THEN costtotal ELSE 0 END) AS [overflowtotal],
				SUM(CASE billtype WHEN 139 THEN qty ELSE 0 END) AS [zengsongqty],
				SUM(CASE billtype WHEN 139 THEN costtotal ELSE 0 END) AS [zengsongtotal],
				SUM(CASE billtype WHEN 126 THEN qty ELSE 0 END) AS [huozengqty],
				SUM(CASE billtype WHEN 126 THEN costtotal ELSE 0 END) AS [huozengtotal],
				SUM(CASE billtype WHEN 16 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [packetrkqty],
				SUM(CASE billtype WHEN 16 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [packetckqty],
				SUM(CASE billtype WHEN 16 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [packetrktotal],
				SUM(CASE billtype WHEN 16 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [packetcktotal],						
				SUM(CASE billtype WHEN 57 THEN costtotal ELSE 0 END) AS kcchange,
				SUM(CASE billtype WHEN 17 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [tjdbrkqty],
				SUM(CASE billtype WHEN 17 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [tjdbckqty],
				SUM(CASE billtype WHEN 17 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [tjdbrktotal],
				SUM(CASE billtype WHEN 17 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [tjdbcktotal],
				SUM(CASE billtype WHEN 21 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [bjdbrkqty],
				SUM(CASE billtype WHEN 21 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [bjdbckqty],
				SUM(CASE billtype WHEN 21 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [bjdbrktotal],
				SUM(CASE billtype WHEN 21 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [bjdbcktotal],
				SUM(CASE billtype WHEN 140 THEN qty ELSE 0 END) AS [wtfhqty],
				SUM(CASE billtype WHEN 140 THEN costtotal ELSE 0 END) AS [wtfhtotal],
				SUM(CASE billtype WHEN 142 THEN qty ELSE 0 END) AS [wtthqty],
				SUM(CASE billtype WHEN 142 THEN costtotal ELSE 0 END) AS [wtthtotal],
				SUM(CASE billtype WHEN 144 THEN qty ELSE 0 END) AS [stshqty],
				SUM(CASE billtype WHEN 144 THEN costtotal ELSE 0 END) AS [stshtotal],
				SUM(CASE billtype WHEN 146 THEN qty ELSE 0 END) AS [stthqty],
				SUM(CASE billtype WHEN 146 THEN costtotal ELSE 0 END) AS [stthtotal],
				SUM(CASE billtype WHEN 160 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [xshrqty],
				SUM(CASE billtype WHEN 160 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [xshcqty],
				SUM(CASE billtype WHEN 160 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [xshrtotal],
				SUM(CASE billtype WHEN 160 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [xshctotal],
				SUM(CASE billtype WHEN 161 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [cghrqty],
				SUM(CASE billtype WHEN 161 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [cghcqty],
				SUM(CASE billtype WHEN 161 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [cghrtotal],
				SUM(CASE billtype WHEN 161 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [cghctotal],
				SUM(CASE billtype WHEN 174 THEN qty ELSE 0 END) AS [wxdrqty],
				SUM(CASE billtype WHEN 174 THEN costtotal ELSE 0 END) AS [wxdrtotal],
				SUM(CASE billtype WHEN 173 THEN qty ELSE 0 END) AS [wxdcqty],
				SUM(CASE billtype WHEN 173 THEN costtotal ELSE 0 END) AS [wxdctotal],
				SUM(CASE billtype WHEN 168 THEN qty ELSE 0 END) AS [zjghqty],
				SUM(CASE billtype WHEN 168 THEN costtotal ELSE 0 END) AS [zjghtotal],
				SUM(CASE billtype WHEN 166 THEN qty ELSE 0 END) AS [wxdqty],
				SUM(CASE billtype WHEN 166 THEN costtotal ELSE 0 END) AS [wxdtotal],
				SUM(CASE billtype WHEN 172 THEN qty ELSE 0 END) AS [smwxdqty],
				SUM(CASE billtype WHEN 172 THEN costtotal ELSE 0 END) AS [smwxdtotal],
				SUM(CASE WHEN qty<0 AND (BillType<>57 OR (billtype=57 AND AdPriceType=0)) THEN qty ELSE 0 END) AS [bqckQty],
				SUM(CASE WHEN qty<0 THEN costtotal ELSE 0 END) AS [bqcktotal],
				SUM(CASE WHEN qty>0 AND (BillType<>57 OR (billtype=57 AND AdPriceType=0)) THEN qty ELSE 0 END) AS [bqrkQty],
				SUM(CASE WHEN qty>=0 THEN costtotal ELSE 0 END) AS [bqrktotal],
				SUM(CASE billtype WHEN 178 THEN qty ELSE 0 END) AS [kxckqty],
				SUM(CASE billtype WHEN 178 THEN costtotal ELSE 0 END) AS [kxcktotal],			    
				SUM(CASE billtype WHEN 183 THEN qty ELSE 0 END) AS [integralckqty],
				SUM(CASE billtype WHEN 183 THEN costtotal ELSE 0 END) AS [integralcktotal],			    
				SUM(CASE billtype WHEN 188 THEN qty ELSE 0 END) AS [innerinqty],
				SUM(CASE billtype WHEN 188 THEN costtotal ELSE 0 END) AS [innerintotal],			    
				SUM(CASE billtype WHEN 187 THEN qty ELSE 0 END) AS [inneroutqty],
				SUM(CASE billtype WHEN 187 THEN costtotal ELSE 0 END) AS [innerouttotal],			    
				SUM(CASE billtype WHEN 191 THEN qty ELSE 0 END) AS [materialoutstockqty],
				SUM(CASE billtype WHEN 191 THEN costtotal ELSE 0 END) AS [materialoutstocktotal],			    
				SUM(CASE billtype WHEN 196 THEN qty ELSE 0 END) AS [jyckqty],
				SUM(CASE billtype WHEN 196 THEN costtotal ELSE 0 END) AS [jycktotal],			    
				SUM(CASE billtype WHEN 197 THEN qty ELSE 0 END) AS [materialbackstockqty],
				SUM(CASE billtype WHEN 197 THEN costtotal ELSE 0 END) AS [materialbackstocktotal],				    
				SUM(CASE billtype WHEN 201 THEN qty ELSE 0 END) AS [otherinqty],
				SUM(CASE billtype WHEN 201 THEN costtotal ELSE 0 END) AS [otherintotal],			    
				SUM(CASE billtype WHEN 202 THEN qty ELSE 0 END) AS [otheroutqty],
				SUM(CASE billtype WHEN 202 THEN costtotal ELSE 0 END) AS [otherouttotal],
				SUM(CASE billtype WHEN 215 THEN qty ELSE 0 END) AS [retailbackqty],
				SUM(CASE billtype WHEN 215 THEN costtotal ELSE 0 END) AS [retailbacktotal],
								
				SUM(CASE WHEN billtype IN(328,329) THEN qty ELSE 0 END) AS [psrqty],
				SUM(CASE WHEN billtype IN(328,329) THEN costtotal ELSE 0 END) AS [psrtotal],
				SUM(CASE WHEN billtype = 327 THEN qty ELSE 0 END) AS [pscqty],
				SUM(CASE WHEN billtype = 327 THEN costtotal ELSE 0 END) AS [psctotal]
					    
		INTO	#ResultInOutStockTable
		FROM	(
					SELECT	PTypeID,
							BillType,
							SUM(Qty) AS Qty,
							SUM(CostTotal) AS CostTotal,
							AdPriceType
					FROM	#SumInOutStockTable 
					WHERE	BillType NOT IN (17,21,57,160,161,16)
					GROUP BY PTypeID,BillType,AdPriceType
					UNION ALL
					SELECT	PTypeID,
							BillType,
							SUM(Qty) AS Qty,
							SUM(CostTotal) AS CostTotal,
							AdPriceType
					FROM	#SumInOutStockTable
					WHERE	BillType IN (17,21,57,160,161,16) 
							AND Qty>0			    
					GROUP BY PTypeID,BillType,AdPriceType
					UNION ALL
					SELECT	PTypeID,
							BillType,
							SUM(Qty) AS Qty,
							SUM(CostTotal) AS CostTotal,
							AdPriceType
					FROM	#SumInOutStockTable
					WHERE	BillType IN (17,21,57,160,161,16) 
							AND Qty<0
					GROUP BY PTypeID,BillType,AdPriceType
					UNION ALL
					SELECT	PTypeID,
							BillType,
							SUM(Qty) AS Qty,
							SUM(CostTotal) AS CostTotal,
							AdPriceType
					FROM	#SumInOutStockTable 
					WHERE	BillType=57 
							AND Qty=0
					GROUP BY PTypeID,BillType,AdPriceType

			) a
			GROUP BY ptypeid 	
			
	         -----显示全部商品
	         CREATE TABLE #AllIniGoodsStocks
			(
				ptypeid		varchar(100),
				iniqty		 NUMERIC(24, 10) ,
				initotal	 NUMERIC(24, 10) 
			)
	       DECLARE @sqltmp  VARCHAR(1000)
	       SET @sqltmp='  
	       INSERT 	INTO #AllIniGoodsStocks 
			SELECT	i.ptypeid,
					ISNULL(SUM(qty/'+@unitrate+'),0) AS iniqty,
					ISNULL(SUM(total),0) AS initotal			 
			FROM 	inigoodsstocks i
			inner join ptype p1 on p1.typeid=i.ptypeid
			INNER JOIN #GetManKTypeId k ON i.KtypeId=k.TypeId
			INNER JOIN #GetManPTypeId p ON i.PtypeId=p.TypeId
			'+@tmptab+'
			GROUP BY i.ptypeid '
	
			--PRINT @sqltmp
			EXEC(@sqltmp)

	
			-----日期以前的InOutStockTable的精简
			CREATE TABLE #PreInOutStockTable
			(
				PTypeId		varchar(100),
				PreQty		 NUMERIC(24, 10) ,
				PreTotal	 NUMERIC(24, 10) 
			)
		
			DECLARE @NNNN varchar(3000)
		
			SET @NNNN = '
				INSERT 	INTO #PreInOutStockTable 
				SELECT 	i.ptypeid,
						ISNULL(SUM( 
						case when bil.AdPriceType=0 OR i.billtype in(327,328,329) then i.qty  else 0 end /'+@unitrate+'),0) AS preqty,
						ISNULL(SUM(i.Costtotal),0) AS pretotal 		
				FROM 	inoutstocktable i 
				INNER JOIN #GetManPTypeId p ON i.Ptypeid=p.typeid
				inner join ptype p1 on p1.typeid=i.ptypeid
				--INNER JOIN #billtypeTable B on i.billtype=b.Billtype OR b.billtype=0
				INNER JOIN #GetManKTypeId  k ON i.ktypeid=k.typeid				
				INNER JOIN #GetManETypeId e ON i.Etypeid=e.typeid
				INNER JOIN #GetSelectSTypeId sk ON i.stypeid=sk.typeid
				left join billindex bil on bil.billnumberid=i.billnumberid
				'+@tmptab+'
				WHERE  	i.Audited = 1
						AND i.billdate<'+char(39)+@startdate+char(39)+'
						AND i.ptypeid LIKE  '+char(39)+@szPTypeID+'%'+char(39)+'						
				GROUP BY i.ptypeid '
		
			--PRINT(@NNNN)
			EXEC(@NNNN)
			
			-----------------------------------------------------------编辑通用查询条件[20030110]--------------------------
			SELECT @Condition='p.sonnum=0 '
			IF  @UserCode<>'%' 
			    SELECT @Condition=@Condition+' 	AND ISNULL(p.UserCode,'''') LIKE '+CHAR(39)+@UserCode+CHAR(39)
			IF @FullName<>'%'
			    SELECT @Condition=@Condition+'  AND ISNULL(p.FullName,'''') LIKE '+CHAR(39)+@fullname+CHAR(39)
			
			SELECT @Condition=@Condition+' AND p.typeid>='+CHAR(39)+@PTypeid+CHAR(39)
			
			IF @UserCode = '%' AND @FullName = '%'
				SELECT @Condition=@Condition+' 	AND P.TypeId LIKE '+char(39)+@szPTypeId+'%'+char(39)

			SET @Condition = @Condition + ' AND (
													ISNULL(P.EntryCode,'''') LIKE '+char(39)+'%'+@szPEntryCode+'%'+char(39)+'
													OR P.TypeId IN (SELECT PTypeId FROM PType_EntryCode_Ext WHERE EntryCode LIKE '+char(39)+'%'+@szPEntryCode+'%'+char(39)+')
												)'
	
	
	
	--------------------------------------------------------------------------------------------------------------------------
	
	IF @strBdSp='0'
	BEGIN	
	--------------------------不显示未变动的商品-----------
	SELECT @Sql='
		SELECT 	a.*,
				ISNULL(c.preqty,0)+ISNULL(i.iniqty,0) AS sqcQty,
				ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0) AS bqcQty,
				CASE
					WHEN ISNULL(ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0),0)=0 THEN 0
					ELSE CAST((CONVERT( NUMERIC(24, 10) ,ISNULL(c.preTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(i.iniTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqckTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqrkTotal,0)))/ISNULL(ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0),0) as  NUMERIC(24, 10) )
				END AS bqcprice,
	          	ISNULL(c.preTotal,0)+ISNULL(i.iniTotal,0) AS sqcTotal,
				(CONVERT( NUMERIC(24, 10) ,ISNULL(c.preTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(i.iniTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqckTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqrkTotal,0))) AS bqcTotal	    		
		INTO 	#LastResultOne
		FROM (	
				SELECT 	p.typeid,
						p.UserCode,
						p.fullname,
						p.saleUnitId,
						saleunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.saleunitid),
						p.BuyUnitId,
						buyunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.BuyUnitId),
						p.StockUnitId,
						stockunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.StockUnitId),
						p.baseUnitId,
						baseunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.baseUnitId),
						abs(ISNULL(b.[buyqty],0)) AS buyqty,
						abs(ISNULL(b.[buytotal],0)) AS buytotal,
						abs(ISNULL(b.[salebackqty],0)) AS salebackqty,
						abs(ISNULL(b.[salebacktotal],0)) AS salebacktotal,
						abs(ISNULL(b.overflowqty,0)) AS overflowqty,
						abs(ISNULL(b.overflowtotal,0)) AS overflowtotal ,
						abs(ISNULL(b.packetrkqty,0)) AS packetrkqty,			
						abs(ISNULL(b.packetrktotal,0)) AS packetrktotal,
						isnull(b.kcchange,0) as kcchange,
						abs(ISNULL(b.tjdbrkqty,0)) AS tjdbrkqty,
						abs(ISNULL(b.tjdbrktotal,0)) AS tjdbrktotal,
						abs(ISNULL(b.bjdbrkqty,0)) AS bjdbrkqty,			
						abs(ISNULL(b.bjdbrktotal,0)) AS bjdbrktotal,
						abs(ISNULL(b.huozengqty,0)) AS huozengqty,
						abs(ISNULL(b.huozengtotal,0)) AS huozengtotal,
						abs(ISNULL(b.wtthqty,0)) AS wtthqty,
						abs(ISNULL(b.wtthtotal,0)) AS wtthtotal,
						abs(ISNULL(b.stshqty,0)) AS stshqty,
						abs(ISNULL(b.stshtotal,0)) AS stshtotal,
						abs(ISNULL(b.cghrqty,0)) AS cghrqty,			
						abs(ISNULL(b.cghrtotal,0)) AS cghrtotal,
						abs(ISNULL(b.xshrqty,0)) AS xshrqty,
						abs(ISNULL(b.xshrtotal,0)) AS xshrtotal,
						abs(ISNULL(b.[saleqty],0)) AS saleqty,
						abs(ISNULL(b.[saletotal],0)) AS saletotal,
						abs(ISNULL(b.retaiqty,0)) AS retaiqty,
				        abs(ISNULL(b.retaitotal,0)) AS retaitotal,
						abs(ISNULL(b.[buybackqty],0)) AS buybackqty,
						abs(ISNULL(b.[buybacktotal],0)) AS buybacktotal,
						abs(ISNULL(b.loseqty,0)) AS loseqty,
						abs(ISNULL(b.losetotal,0)) AS losetotal ,
						abs(ISNULL(b.packetckqty,0)) AS packetckqty,
						abs(ISNULL(b.packetcktotal,0)) AS packetcktotal,
						abs(ISNULL(b.tjdbckqty,0)) AS tjdbckqty,
						abs(ISNULL(b.tjdbcktotal,0)) AS tjdbcktotal,
						abs(ISNULL(b.bjdbckqty,0)) AS bjdbckqty ,
						abs(ISNULL(b.bjdbcktotal,0)) AS bjdbcktotal,
						abs(ISNULL(b.zengsongqty,0)) AS zengsongqty,			
						abs(ISNULL(b.zengsongtotal,0)) AS zengsongtotal,
						abs(ISNULL(b.wtfhqty,0)) AS wtfhqty,
						abs(ISNULL(b.wtfhtotal,0)) AS wtfhtotal,
						abs(ISNULL(b.stthqty,0)) AS stthqty,
						abs(ISNULL(b.stthtotal,0)) AS stthtotal,
						abs(ISNULL(b.cghcqty,0)) AS cghcqty,
						abs(ISNULL(b.cghctotal,0)) AS cghctotal,
						abs(ISNULL(b.xshcqty,0)) AS xshcqty,
						abs(ISNULL(b.xshctotal,0)) AS xshctotal,
						abs(ISNULL(b.wxdrqty,0)) AS wxdrqty,
						abs(ISNULL(b.wxdrtotal,0)) AS wxdrtotal,
						abs(ISNULL(b.wxdcqty,0)) AS wxdcqty,
						abs(ISNULL(b.wxdctotal,0)) AS wxdctotal,
						abs(ISNULL(b.zjghqty,0)) AS zjghqty,
						abs(ISNULL(b.zjghtotal,0)) AS zjghtotal,
						abs(ISNULL(b.wxdqty,0)) AS wxdqty,
						abs(ISNULL(b.wxdtotal,0)) AS wxdtotal,
						abs(ISNULL(b.smwxdqty,0)) AS smwxdqty,
						abs(ISNULL(b.smwxdtotal,0)) AS smwxdtotal,
						ISNULL(b.bqckQty,0) AS bqckQty,
						ISNULL(b.bqcktotal,0) AS bqcktotal,
						ISNULL(b.bqrkQty,0) AS bqrkQty,
						ISNULL(b.bqrktotal,0) AS bqrktotal,
						abs(ISNULL(b.kxckqty,0)) AS kxckqty,
						abs(ISNULL(b.kxcktotal,0)) AS kxcktotal,
						abs(ISNULL(b.integralckqty,0)) AS integralckqty,
						abs(ISNULL(b.integralcktotal,0)) AS integralcktotal,						   
						abs(ISNULL(b.innerinqty,0)) AS innerinqty,
						abs(ISNULL(b.innerintotal,0)) AS innerintotal,						
						abs(ISNULL(b.inneroutqty,0)) AS inneroutqty,
						abs(ISNULL(b.innerouttotal,0)) AS innerouttotal,						
						abs(ISNULL(b.materialoutstockqty,0)) AS materialoutstockqty,
						abs(ISNULL(b.materialoutstocktotal,0)) AS materialoutstocktotal,						
						abs(ISNULL(b.jyckqty,0)) AS jyckqty,
						abs(ISNULL(b.jycktotal,0)) AS jycktotal,						
						abs(ISNULL(b.materialbackstockqty,0)) AS materialbackstockqty,
						abs(ISNULL(b.materialbackstocktotal,0)) AS materialbackstocktotal,		
						abs(ISNULL(b.otherinqty,0)) AS otherinqty,
						abs(ISNULL(b.otherintotal,0)) AS otherintotal,				
						abs(ISNULL(b.otheroutqty,0)) AS otheroutqty,
						abs(ISNULL(b.otherouttotal,0)) AS otherouttotal,
						abs(ISNULL(b.retailbackqty,0)) AS retailbackqty,
						abs(ISNULL(b.retailbacktotal,0)) AS retailbacktotal,						
						abs(ISNULL(b.appraisalbillqty,0)) AS appraisalbillqty,
						abs(ISNULL(b.appraisalbilltotal,0)) AS appraisalbilltotal,
						abs(ISNULL(b.sendbackbillqty,0)) AS sendbackbillqty,
						abs(ISNULL(b.sendbackbilltotal,0)) AS sendbackbilltotal,
						abs(ISNULL(b.sendbillqty,0)) AS sendbillqty,
						abs(ISNULL(b.sendbilltotal,0)) AS sendbilltotal,
						abs(ISNULL(b.appraisalbackbillqty,0)) AS appraisalbackbillqty,
						abs(ISNULL(b.appraisalbackbilltotal,0)) AS appraisalbackbilltotal,
						
						abs(ISNULL(b.[psrqty],0)) AS psrqty,
						abs(ISNULL(b.[psrtotal],0)) AS psrtotal,
						abs(ISNULL(b.[pscqty],0)) AS pscqty,
						abs(ISNULL(b.[psctotal],0)) AS psctotal			  
				FROM 	F_GetManPTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') p
				INNER JOIN #ResultInOutStockTable b ON  p.typeid=b.ptypeid	
	    		WHERE 	'+@Condition+'	 
	    				AND p.IsService=0			
	    				AND p.iscombinationproduct = 0
			) AS a 
			LEFT JOIN #AllIniGoodsStocks i ON (a.typeid=i.ptypeid)
			LEFT JOIN #PreInOutStockTable c ON (a.typeid=c.ptypeid) 
			ORDER BY usercode
	 '	
            IF @unitconvert = 4 
                BEGIN	
                    SET @SQL += '
						SELECT  0 AS sonnum,t1.*,t2.* FROM  #LastResultOne t1  
							left join   ( 
									SELECT  ptypeid ,
											SaleUnitRate1 ,
											( SELECT    FullName FROM      dbo.PType_Units pu WHERE     pu.UnitsId = pau.saleunitid1) AS fullname1,
											SaleUnitRate2 ,
											( SELECT    FullName FROM      dbo.PType_Units pu WHERE     pu.UnitsId = pau.saleunitid2 ) AS fullname2,
											SaleUnitRate3 ,
											( SELECT    FullName FROM      dbo.PType_Units pu	WHERE     pu.UnitsId = pau.saleunitid3) AS fullname3
									FROM    dbo.PType_AuxiliaryUnits_Ext pau ) t2 
							on t2.ptypeid=t1.typeid
						 WHERE bqckQty<>0 OR bqrkQty<>0 ORDER BY usercode '
                END
			else 
			 begin 
				set @SQL +='	SELECT * FROM #LastResultOne WHERE bqckQty<>0 OR bqrkQty<>0 ORDER BY usercode '
			 end
			 
			--print(@sql)		
			EXEC(@SQL)				
		END
	ELSE IF @strBdSp='1'
		BEGIN	
		
			ListAllPtype:
			--------------------------显示所有商品-----------
			SELECT @Sql='
			SELECT 	a.*,
					c.preTotal,i.iniTotal,--a.bqckTotal,a.bqrkTotal,
					ISNULL(c.preqty,0)+ISNULL(i.iniqty,0) AS sqcQty,
					ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0) AS bqcQty,
					CASE
						WHEN ISNULL(ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0),0)=0 THEN 0
						ELSE CAST((CONVERT( NUMERIC(24, 10) ,ISNULL(c.preTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(i.iniTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqckTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqrkTotal,0)))/ISNULL(ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0),0) as  NUMERIC(24, 10) )
					END AS bqcprice,
					ISNULL(c.preTotal,0)+ISNULL(i.iniTotal,0) AS sqcTotal,
					(CONVERT( NUMERIC(24, 10) ,ISNULL(c.preTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(i.iniTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqckTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqrkTotal,0))) AS bqcTotal
			FROM  (
					SELECT 	p.typeid,
							p.UserCode,
							p.fullname,
							p.saleUnitId,
							saleunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.saleunitid),
							p.BuyUnitId,
							buyunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.BuyUnitId),
							p.StockUnitId,
							stockunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.StockUnitId),
							p.baseUnitId,
							baseunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.baseUnitId),
							abs(ISNULL(b.[buyqty],0)) AS buyqty,
							abs(ISNULL(b.[buytotal],0)) AS buytotal,
							abs(ISNULL(b.[salebackqty],0)) AS salebackqty,
							abs(ISNULL(b.[salebacktotal],0)) AS salebacktotal,
							abs(ISNULL(b.overflowqty,0)) AS overflowqty,
							abs(ISNULL(b.overflowtotal,0)) AS overflowtotal ,
							abs(ISNULL(b.packetrkqty,0)) AS packetrkqty,			
							abs(ISNULL(b.packetrktotal,0)) AS packetrktotal,
							isnull(b.kcchange,0) as kcchange,
							abs(ISNULL(b.tjdbrkqty,0)) AS tjdbrkqty,
							abs(ISNULL(b.tjdbrktotal,0)) AS tjdbrktotal,
							abs(ISNULL(b.bjdbrkqty,0)) AS bjdbrkqty,			
							abs(ISNULL(b.bjdbrktotal,0)) AS bjdbrktotal,
							abs(ISNULL(b.huozengqty,0)) AS huozengqty,
							abs(ISNULL(b.huozengtotal,0)) AS huozengtotal,
							abs(ISNULL(b.wtthqty,0)) AS wtthqty,
							abs(ISNULL(b.wtthtotal,0)) AS wtthtotal,
							abs(ISNULL(b.stshqty,0)) AS stshqty,
							abs(ISNULL(b.stshtotal,0)) AS stshtotal,
							abs(ISNULL(b.cghrqty,0)) AS cghrqty,			
							abs(ISNULL(b.cghrtotal,0)) AS cghrtotal,
							abs(ISNULL(b.xshrqty,0)) AS xshrqty,
							abs(ISNULL(b.xshrtotal,0)) AS xshrtotal,
							abs(ISNULL(b.[saleqty],0)) AS saleqty,
							abs(ISNULL(b.[saletotal],0)) AS saletotal,
							abs(ISNULL(b.retaiqty,0)) AS retaiqty,
							abs(ISNULL(b.retaitotal,0)) AS retaitotal,
							abs(ISNULL(b.[buybackqty],0)) AS buybackqty,
							abs(ISNULL(b.[buybacktotal],0)) AS buybacktotal,
							abs(ISNULL(b.loseqty,0)) AS loseqty,
							abs(ISNULL(b.losetotal,0)) AS losetotal ,
							abs(ISNULL(b.packetckqty,0)) AS packetckqty,
							abs(ISNULL(b.packetcktotal,0)) AS packetcktotal,
							abs(ISNULL(b.tjdbckqty,0)) AS tjdbckqty,
							abs(ISNULL(b.tjdbcktotal,0)) AS tjdbcktotal,
							abs(ISNULL(b.bjdbckqty,0)) AS bjdbckqty ,
							abs(ISNULL(b.bjdbcktotal,0)) AS bjdbcktotal,
							abs(ISNULL(b.zengsongqty,0)) AS zengsongqty,			
							abs(ISNULL(b.zengsongtotal,0)) AS zengsongtotal,
							abs(ISNULL(b.wtfhqty,0)) AS wtfhqty,
							abs(ISNULL(b.wtfhtotal,0)) AS wtfhtotal,
							abs(ISNULL(b.stthqty,0)) AS stthqty,
							abs(ISNULL(b.stthtotal,0)) AS stthtotal,
							abs(ISNULL(b.cghcqty,0)) AS cghcqty,
							abs(ISNULL(b.cghctotal,0)) AS cghctotal,
							abs(ISNULL(b.xshcqty,0)) AS xshcqty,
							abs(ISNULL(b.xshctotal,0)) AS xshctotal,
							abs(ISNULL(b.wxdrqty,0)) AS wxdrqty,
							abs(ISNULL(b.wxdrtotal,0)) AS wxdrtotal,
							abs(ISNULL(b.wxdcqty,0)) AS wxdcqty,
							abs(ISNULL(b.wxdctotal,0)) AS wxdctotal,
							abs(ISNULL(b.zjghqty,0)) AS zjghqty,
							abs(ISNULL(b.zjghtotal,0)) AS zjghtotal,
							abs(ISNULL(b.wxdqty,0)) AS wxdqty,
							abs(ISNULL(b.wxdtotal,0)) AS wxdtotal,
							abs(ISNULL(b.smwxdqty,0)) AS smwxdqty,
							abs(ISNULL(b.smwxdtotal,0)) AS smwxdtotal,
							ISNULL(b.bqckQty,0) AS bqckQty,
							ISNULL(b.bqcktotal,0) AS bqcktotal,
							ISNULL(b.bqrkQty,0) AS bqrkQty,
							ISNULL(b.bqrktotal,0) AS bqrktotal,
							abs(ISNULL(b.kxckqty,0)) AS kxckqty,
							abs(ISNULL(b.kxcktotal,0)) AS kxcktotal,
							abs(ISNULL(b.integralckqty,0)) AS integralckqty,
							abs(ISNULL(b.integralcktotal,0)) AS integralcktotal,							
							abs(ISNULL(b.innerinqty,0)) AS innerinqty,
							abs(ISNULL(b.innerintotal,0)) AS innerintotal,
							abs(ISNULL(b.inneroutqty,0)) AS inneroutqty,
							abs(ISNULL(b.innerouttotal,0)) AS innerouttotal,						
							abs(ISNULL(b.materialoutstockqty,0)) AS materialoutstockqty,
							abs(ISNULL(b.materialoutstocktotal,0)) AS materialoutstocktotal,							
							abs(ISNULL(b.jyckqty,0)) AS jyckqty,
							abs(ISNULL(b.jycktotal,0)) AS jycktotal,							
							abs(ISNULL(b.materialbackstockqty,0)) AS materialbackstockqty,
							abs(ISNULL(b.materialbackstocktotal,0)) AS materialbackstocktotal,							
							abs(ISNULL(b.otherinqty,0)) AS otherinqty,
							abs(ISNULL(b.otherintotal,0)) AS otherintotal,	
							abs(ISNULL(b.otheroutqty,0)) AS otheroutqty,
							abs(ISNULL(b.otherouttotal,0)) AS otherouttotal,
							abs(ISNULL(b.retailbackqty,0)) AS retailbackqty,
							abs(ISNULL(b.retailbacktotal,0)) AS retailbacktotal,						
							abs(ISNULL(b.appraisalbillqty,0)) AS appraisalbillqty,
							abs(ISNULL(b.appraisalbilltotal,0)) AS appraisalbilltotal,
							abs(ISNULL(b.sendbackbillqty,0)) AS sendbackbillqty,
							abs(ISNULL(b.sendbackbilltotal,0)) AS sendbackbilltotal,
							abs(ISNULL(b.sendbillqty,0)) AS sendbillqty,
							abs(ISNULL(b.sendbilltotal,0)) AS sendbilltotal,
							abs(ISNULL(b.appraisalbackbillqty,0)) AS appraisalbackbillqty,
							abs(ISNULL(b.appraisalbackbilltotal,0)) AS appraisalbackbilltotal,
							
							abs(ISNULL(b.[psrqty],0)) AS psrqty,
							abs(ISNULL(b.[psrtotal],0)) AS psrtotal,
							abs(ISNULL(b.[pscqty],0)) AS pscqty,
							abs(ISNULL(b.[psctotal],0)) AS psctotal					    
			  		FROM 	F_GetManPTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') p '
			  		
			  	if isnull(@ptypeCategoryid,'')<>''
			  	   set	@Sql+='
			  		INNER JOIN #GetManPTypeId pc ON pc.typeid LIKE p.typeid +''%'' '
			  	set @Sql+=	'
			  		LEFT JOIN #ResultInOutStockTable B ON b.ptypeid = p.typeid
			    	WHERE	'+@Condition+' 
			    			AND p.IsService=0 
			    			AND p.iscombinationproduct = 0
				) AS a 
				LEFT JOIN #AllIniGoodsStocks i ON (a.typeid=i.ptypeid)
				LEFT JOIN #PreInOutStockTable c ON (a.typeid=c.ptypeid) '
			  
			  IF @unitconvert = 4 
                BEGIN	
                    SET @SQL = '
						SELECT  0 AS sonnum,t1.*,t2.* FROM  (' + @SQL + ') t1
							left join   ( 
									SELECT  ptypeid ,
											SaleUnitRate1 ,
											( SELECT    FullName FROM      dbo.PType_Units pu WHERE     pu.UnitsId = pau.saleunitid1) AS fullname1,
											SaleUnitRate2 ,
											( SELECT    FullName FROM      dbo.PType_Units pu WHERE     pu.UnitsId = pau.saleunitid2 ) AS fullname2,
											SaleUnitRate3 ,
											( SELECT    FullName FROM      dbo.PType_Units pu	WHERE     pu.UnitsId = pau.saleunitid3) AS fullname3
									FROM    dbo.PType_AuxiliaryUnits_Ext pau ) t2 
							on t2.ptypeid=t1.typeid
						 '
                END
                
                SET @SQL = @SQL + ' ORDER BY   usercode'
                
			  	--PRINT(@SQL)					
				EXEC(@SQL)
			END
	ELSE IF @strBdSp='2'
		BEGIN	
			--------------------------显示至少有一条数据不为0商品-----------
			SELECT @Sql='
			SELECT 	a.*,
					ISNULL(c.preqty,0)+ISNULL(i.iniqty,0) AS sqcQty,
					ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0) AS bqcQty,
					CASE
						WHEN ISNULL(ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0),0)=0 THEN 0
						ELSE CAST((CONVERT( NUMERIC(24, 10) ,ISNULL(c.preTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(i.iniTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqckTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqrkTotal,0)))/ISNULL(ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0),0) as  NUMERIC(24, 10) )
					END AS bqcprice,
					ISNULL(c.preTotal,0)+ISNULL(i.iniTotal,0) AS sqcTotal,
					(CONVERT( NUMERIC(24, 10) ,ISNULL(c.preTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(i.iniTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqckTotal,0))+CONVERT( NUMERIC(24, 10) ,ISNULL(a.bqrkTotal,0))) AS bqcTotal
			FROM  (
					SELECT 	p.typeid,
							p.UserCode,
							p.fullname,
							p.saleUnitId,
							saleunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.saleunitid),
							p.BuyUnitId,
							buyunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.BuyUnitId),
							p.StockUnitId,
							stockunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.StockUnitId),
							p.baseUnitId,
							baseunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.baseUnitId),
							abs(ISNULL(b.[buyqty],0)) AS buyqty,
							abs(ISNULL(b.[buytotal],0)) AS buytotal,
							abs(ISNULL(b.[salebackqty],0)) AS salebackqty,
							abs(ISNULL(b.[salebacktotal],0)) AS salebacktotal,
							abs(ISNULL(b.overflowqty,0)) AS overflowqty,
							abs(ISNULL(b.overflowtotal,0)) AS overflowtotal ,
							abs(ISNULL(b.packetrkqty,0)) AS packetrkqty,			
							abs(ISNULL(b.packetrktotal,0)) AS packetrktotal,
							isnull(b.kcchange,0) as kcchange,
							abs(ISNULL(b.tjdbrkqty,0)) AS tjdbrkqty,
							abs(ISNULL(b.tjdbrktotal,0)) AS tjdbrktotal,
							abs(ISNULL(b.bjdbrkqty,0)) AS bjdbrkqty,			
							abs(ISNULL(b.bjdbrktotal,0)) AS bjdbrktotal,
							abs(ISNULL(b.huozengqty,0)) AS huozengqty,
							abs(ISNULL(b.huozengtotal,0)) AS huozengtotal,
							abs(ISNULL(b.wtthqty,0)) AS wtthqty,
							abs(ISNULL(b.wtthtotal,0)) AS wtthtotal,
							abs(ISNULL(b.stshqty,0)) AS stshqty,
							abs(ISNULL(b.stshtotal,0)) AS stshtotal,
							abs(ISNULL(b.cghrqty,0)) AS cghrqty,			
							abs(ISNULL(b.cghrtotal,0)) AS cghrtotal,
							abs(ISNULL(b.xshrqty,0)) AS xshrqty,
							abs(ISNULL(b.xshrtotal,0)) AS xshrtotal,
							abs(ISNULL(b.[saleqty],0)) AS saleqty,
							abs(ISNULL(b.[saletotal],0)) AS saletotal,
							abs(ISNULL(b.retaiqty,0)) AS retaiqty,
							abs(ISNULL(b.retaitotal,0)) AS retaitotal,
							abs(ISNULL(b.[buybackqty],0)) AS buybackqty,
							abs(ISNULL(b.[buybacktotal],0)) AS buybacktotal,
							abs(ISNULL(b.loseqty,0)) AS loseqty,
							abs(ISNULL(b.losetotal,0)) AS losetotal ,
							abs(ISNULL(b.packetckqty,0)) AS packetckqty,
							abs(ISNULL(b.packetcktotal,0)) AS packetcktotal,
							abs(ISNULL(b.tjdbckqty,0)) AS tjdbckqty,
							abs(ISNULL(b.tjdbcktotal,0)) AS tjdbcktotal,
							abs(ISNULL(b.bjdbckqty,0)) AS bjdbckqty ,
							abs(ISNULL(b.bjdbcktotal,0)) AS bjdbcktotal,
							abs(ISNULL(b.zengsongqty,0)) AS zengsongqty,			
							abs(ISNULL(b.zengsongtotal,0)) AS zengsongtotal,
							abs(ISNULL(b.wtfhqty,0)) AS wtfhqty,
							abs(ISNULL(b.wtfhtotal,0)) AS wtfhtotal,
							abs(ISNULL(b.stthqty,0)) AS stthqty,
							abs(ISNULL(b.stthtotal,0)) AS stthtotal,
							abs(ISNULL(b.cghcqty,0)) AS cghcqty,
							abs(ISNULL(b.cghctotal,0)) AS cghctotal,
							abs(ISNULL(b.xshcqty,0)) AS xshcqty,
							abs(ISNULL(b.xshctotal,0)) AS xshctotal,
							abs(ISNULL(b.wxdrqty,0)) AS wxdrqty,
							abs(ISNULL(b.wxdrtotal,0)) AS wxdrtotal,
							abs(ISNULL(b.wxdcqty,0)) AS wxdcqty,
							abs(ISNULL(b.wxdctotal,0)) AS wxdctotal,
							abs(ISNULL(b.zjghqty,0)) AS zjghqty,
							abs(ISNULL(b.zjghtotal,0)) AS zjghtotal,
							abs(ISNULL(b.wxdqty,0)) AS wxdqty,
							abs(ISNULL(b.wxdtotal,0)) AS wxdtotal,
							abs(ISNULL(b.smwxdqty,0)) AS smwxdqty,
							abs(ISNULL(b.smwxdtotal,0)) AS smwxdtotal,
							ISNULL(b.bqckQty,0) AS bqckQty,
							ISNULL(b.bqcktotal,0) AS bqcktotal,
							ISNULL(b.bqrkQty,0) AS bqrkQty,
							ISNULL(b.bqrktotal,0) AS bqrktotal,
							abs(ISNULL(b.kxckqty,0)) AS kxckqty,
							abs(ISNULL(b.kxcktotal,0)) AS kxcktotal,
							abs(ISNULL(b.integralckqty,0)) AS integralckqty,
							abs(ISNULL(b.integralcktotal,0)) AS integralcktotal,							
							abs(ISNULL(b.innerinqty,0)) AS innerinqty,
							abs(ISNULL(b.innerintotal,0)) AS innerintotal,
							abs(ISNULL(b.inneroutqty,0)) AS inneroutqty,
							abs(ISNULL(b.innerouttotal,0)) AS innerouttotal,						
							abs(ISNULL(b.materialoutstockqty,0)) AS materialoutstockqty,
							abs(ISNULL(b.materialoutstocktotal,0)) AS materialoutstocktotal,							
							abs(ISNULL(b.jyckqty,0)) AS jyckqty,
							abs(ISNULL(b.jycktotal,0)) AS jycktotal,							
							abs(ISNULL(b.materialbackstockqty,0)) AS materialbackstockqty,
							abs(ISNULL(b.materialbackstocktotal,0)) AS materialbackstocktotal,							
							abs(ISNULL(b.otherinqty,0)) AS otherinqty,
							abs(ISNULL(b.otherintotal,0)) AS otherintotal,						
							abs(ISNULL(b.otheroutqty,0)) AS otheroutqty,
							abs(ISNULL(b.otherouttotal,0)) AS otherouttotal,
							abs(ISNULL(b.retailbackqty,0)) AS retailbackqty,
							abs(ISNULL(b.retailbacktotal,0)) AS retailbacktotal,
							abs(ISNULL(b.appraisalbillqty,0)) AS appraisalbillqty,
							abs(ISNULL(b.appraisalbilltotal,0)) AS appraisalbilltotal,
							abs(ISNULL(b.sendbackbillqty,0)) AS sendbackbillqty,
							abs(ISNULL(b.sendbackbilltotal,0)) AS sendbackbilltotal,
							abs(ISNULL(b.sendbillqty,0)) AS sendbillqty,
							abs(ISNULL(b.sendbilltotal,0)) AS sendbilltotal,
							abs(ISNULL(b.appraisalbackbillqty,0)) AS appraisalbackbillqty,
							abs(ISNULL(b.appraisalbackbilltotal,0)) AS appraisalbackbilltotal,
							
							abs(ISNULL(b.[psrqty],0)) AS psrqty,
							abs(ISNULL(b.[psrtotal],0)) AS psrtotal,
							abs(ISNULL(b.[pscqty],0)) AS pscqty,
							abs(ISNULL(b.[psctotal],0)) AS psctotal		
			  		FROM 	F_GetManPTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') p  '
			  	if isnull(@ptypeCategoryid,'')<>''
			  	  set	@Sql+='
			  		INNER JOIN #GetManPTypeId pc ON pc.typeid LIKE p.typeid +''%'' 
			  		'
			    set	@Sql+=	'
			  		LEFT JOIN #ResultInOutStockTable B ON b.ptypeid = p.typeid
			    	WHERE '+@Condition+' 
			    			AND p.IsService=0
			    			AND p.iscombinationproduct = 0
				) AS a 
				LEFT JOIN #AllIniGoodsStocks i ON (a.typeid=i.ptypeid)
				LEFT JOIN #PreInOutStockTable c ON (a.typeid=c.ptypeid) 
				WHERE (ISNULL(c.preqty,0)+ISNULL(i.iniqty,0))<>0
						OR (ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0))<>0
						OR a.bqrkqty<>0
						OR a.bqckqty<>0
						'
			  	
			  	  	
			  IF @unitconvert = 4 
                BEGIN	
                    SET @SQL = '
						SELECT  0 AS sonnum,t1.*,t2.* FROM  (' + @SQL + ') t1
							left join   ( 
									SELECT  ptypeid ,
											SaleUnitRate1 ,
											( SELECT    FullName FROM      dbo.PType_Units pu WHERE     pu.UnitsId = pau.saleunitid1) AS fullname1,
											SaleUnitRate2 ,
											( SELECT    FullName FROM      dbo.PType_Units pu WHERE     pu.UnitsId = pau.saleunitid2 ) AS fullname2,
											SaleUnitRate3 ,
											( SELECT    FullName FROM      dbo.PType_Units pu	WHERE     pu.UnitsId = pau.saleunitid3) AS fullname3
									FROM    dbo.PType_AuxiliaryUnits_Ext pau ) t2 
							on t2.ptypeid=t1.typeid
						 '
                END
                
                SET @SQL = @SQL + ' ORDER BY usercode '
			  	
				--PRINT(@SQL)
				EXEC(@SQL)
			END
		ELSE 
			RETURN 0	

		DROP TABLE #ResultInOutStockTable,#SumInOutStockTable
	END
--***********************************************************************查询大类商品************************************************************************--
ELSE       
	BEGIN	
		DECLARE @TempSonnum INT  --判断传入的商品是否是具体商品,并做相应处理
		SELECT @TempSonnum = Sonnum FROM PType WHERE TypeID=@szPtypeId
		IF @TempSonnum = 0
		   SELECT @TempSonnum = 0
		ELSE
		   SELECT @TempSonnum = 5	
	
		-----PType的精简
	 create table #TempPType
	 (
		typeid varchar(50),
		fullname varchar(200),
		usercode varchar(200),
		sonnum int,
		sortid int,
		SaleUnitId INT,
		BuyUnitId INT,
		StockUnitId INT,
		baseUnitId INT
	 )
	 IF ISNULL(@ptypeCategoryid,'')<>''
	 BEGIN
		INSERT INTO #TempPType 
		SELECT  DISTINCT 
			 	p.typeid,
				p.fullname,
				usercode,
				sonnum,
				sortid,
				SaleUnitId,
                BuyUnitId,
                StockUnitId,
                baseUnitId
		FROM 	F_GetManPTypeAll(@OperatorID) P
		INNER JOIN	#GetManPTypeId P1 ON P1.Typeid like p.typeid+'%'
		WHERE 	LEFT(p.typeid,len(p.typeid)-@TempSonnum)=@szPtypeId 
				AND p.typeid<>'00000'	
				and IsService=0
				and iscombinationproduct = 0
	END	
	ELSE 
	BEGIN
		INSERT INTO #TempPType 
		SELECT 	typeid,
				fullname,
				usercode,
				sonnum,
				sortid,
				SaleUnitId,
                BuyUnitId,
                StockUnitId,
                baseUnitId
		FROM 	F_GetManPTypeAll(@OperatorID)
		WHERE 	LEFT(typeid,len(typeid)-@TempSonnum)=@szPtypeId 
				AND typeid<>'00000'	
				and IsService=0
				and iscombinationproduct = 0
	END
			
		SELECT 	p1.typeid,
				p1.baseUnitId,
				p1.BuyUnitId,
				p1.SaleUnitId,
				p1.StockUnitId
		INTO 	#TempPType1 
		FROM 	#GetManPTypeId   p
		inner join ptype p1 on p.typeid=p1.typeid
		WHERE 	p1.typeid like @szPtypeId+'%'
				AND p1.typeid<>'00000'	
				and p1.IsService=0
				and p1.iscombinationproduct = 0
				and p1.sonnum=0
				
		----InOutStockTable的精简
		CREATE TABLE #SumInOutStockTable1
		(
			BillType 		int,
			PTypeId			varchar(100),
			Qty				NUMERIC(24, 10) ,
			CostTotal		NUMERIC(24, 10) ,
			AdPriceType		INT
		)
		
	
		DECLARE @XXX varchar(MAX)
		
		SET @XXX = '
				INSERT INTO #SumInOutStockTable1 
				SELECT 	i.BillType,
						i.PTypeId,
						SUM(i.Qty/'+@unitrate+') AS Qty,
						SUM(i.CostTotal) AS CostTotal,
						 0	AS AdPriceType
				FROM 	InOutStockTable i 
				INNER JOIN #billtypeTable B on i.billtype=b.Billtype OR b.billtype=0
				inner join #TempPType1 p1 on p1.typeid=i.ptypeid
				'+@tmptab
				
				
		IF @Mktypeid='-99999' OR @szKtypeId<>''
				SET @XXX=@XXX+'
							INNER JOIN #GetManKTypeId k ON i.ktypeid=k.typeid '
							
		IF @Mstypeid='-99999' OR @StypeId<>''
				SET @XXX=@XXX+'			
							INNER JOIN #GetSelectSTypeId sk ON i.stypeid=sk.typeid '
										
		IF @MPtypeid='-99999' 
			SET @XXX =@XXX+' INNER JOIN #GetManPTypeId p ON i.ptypeid=p.typeid '	
							
		IF  @szEtypeId<>'00001' OR @MEtypeid='-99999'
			SET @XXX =@XXX+' INNER JOIN #GetManETypeId e ON i.ETypeId=e.typeid '					
						
		SET @XXX =@XXX+'
				WHERE    i.billdate >='+char(39)+@startdate+char(39)+'
						AND i.billdate <='+char(39)+@EndDate+char(39)+'
						AND i.Audited = 1
						AND i.KTypeId <> ''10000''					
						AND i.BillType NOT IN (17,21,57,160,161,16)
				GROUP BY i.PTypeId,i.BillType,i.BILLNUMBERID '
				
		
		SET @XXX=@XXX+'UNION ALL '
		
		SET @XXX = @XXX+'
				
				SELECT 	i.BillType,
						i.PTypeId,
						SUM(i.Qty/'+@unitrate+') AS Qty,
						SUM(i.CostTotal) AS CostTotal,
						CASE WHEN i.BILLTYPE<>57 THEN 0
							 WHEN i.BILLTYPE=57 AND BILLNUMBERID IN (SELECT BILLNUMBERID FROM BILLINDEX WHERE AdPriceType=0) THEN 0
							 WHEN i.BILLTYPE=57 AND BILLNUMBERID IN (SELECT BILLNUMBERID FROM BILLINDEX WHERE AdPriceType=1) THEN 1
							 ELSE 2 END AS AdPriceType
				FROM 	InOutStockTable i 
				INNER JOIN #billtypeTable B on i.billtype=b.Billtype OR b.billtype=0
				inner join #TempPType1 p1 on p1.typeid=i.ptypeid
				'+@tmptab
				
		IF @Mktypeid='-99999' OR @szKtypeId<>''
				SET @XXX=@XXX+'
							INNER JOIN #GetManKTypeId k ON i.ktypeid=k.typeid '
							
		IF @Mstypeid='-99999' OR @StypeId<>''
				SET @XXX=@XXX+'			
							INNER JOIN #GetSelectSTypeId sk ON i.stypeid=sk.typeid '
										
		IF @MPtypeid='-99999'
			SET @XXX =@XXX+' INNER JOIN #GetManPTypeId p ON i.ptypeid=p.typeid '	
							
		IF  @szEtypeId<>'00001' OR @MEtypeid='-99999'
			SET @XXX =@XXX+' INNER JOIN #GetManETypeId e ON i.ETypeId=e.typeid '					
						
		SET @XXX =@XXX+'
		WHERE    i.billdate >='+char(39)+@startdate+char(39)+'
				AND i.billdate <='+char(39)+@EndDate+char(39)+'
				AND i.Audited = 1
				AND i.KTypeId <> ''10000''					
				AND i.BillType IN (17,21,57,160,161,16) AND Qty>=0
		GROUP BY i.PTypeId,i.BillType,i.BILLNUMBERID '

		SET @XXX=@XXX+'UNION ALL '
		
		
		SET @XXX = @XXX+'
				
				SELECT 	i.BillType,
						i.PTypeId,
						SUM(i.Qty/'+@unitrate+') AS Qty,
						SUM(i.CostTotal) AS CostTotal,
						CASE WHEN i.BILLTYPE<>57 THEN 0
							 WHEN i.BILLTYPE=57 AND BILLNUMBERID IN (SELECT BILLNUMBERID FROM BILLINDEX WHERE AdPriceType=0) THEN 0
							 WHEN i.BILLTYPE=57 AND BILLNUMBERID IN (SELECT BILLNUMBERID FROM BILLINDEX WHERE AdPriceType=1) THEN 1
							 ELSE 2 END AS AdPriceType
				FROM 	InOutStockTable i 
				INNER JOIN #billtypeTable B on i.billtype=b.Billtype OR b.billtype=0
				inner join #TempPType1 p1 on p1.typeid=i.ptypeid
				'+@tmptab
				
		IF @Mktypeid='-99999' OR @szKtypeId<>''
				SET @XXX=@XXX+'
							INNER JOIN #GetManKTypeId k ON i.ktypeid=k.typeid '
							
		IF @Mstypeid='-99999' OR @StypeId<>''
				SET @XXX=@XXX+'			
							INNER JOIN #GetSelectSTypeId sk ON i.stypeid=sk.typeid '
										
		IF @MPtypeid='-99999'
			SET @XXX =@XXX+' INNER JOIN #GetManPTypeId p ON i.ptypeid=p.typeid '	
							
		IF  @szEtypeId<>'00001' OR @MEtypeid='-99999'
			SET @XXX =@XXX+' INNER JOIN #GetManETypeId e ON i.ETypeId=e.typeid '					
						
		SET @XXX =@XXX+'
		WHERE    i.billdate >='+char(39)+@startdate+char(39)+'
				AND i.billdate <='+char(39)+@EndDate+char(39)+'
				AND i.Audited = 1
				AND i.KTypeId <> ''10000''					
				AND i.BillType IN (17,21,57,160,161,16) AND Qty<0
		GROUP BY i.PTypeId,i.BillType,i.BILLNUMBERID '
		
	
		--print(@XXX)
		EXEC(@XXX)	
		
		--select *from #SumInOutStockTable1
		CREATE CLUSTERED INDEX CIX_SumInOutStockTable_Union   ON  #SumInOutStockTable1(PTypeID,BillType)
	
		SELECT	SUBSTRING(PTypeId,1,LEN(@szPTypeId)+5) AS PTypeId,
			    SUM(CASE WHEN billtype IN(11,12) THEN qty ELSE 0 END) AS [saleqty],
			    SUM(CASE WHEN billtype IN(11,12) THEN costtotal ELSE 0 END) AS [saletotal],
			     SUM(CASE WHEN billtype =305 THEN qty ELSE 0 END) AS retaiqty,
			    SUM(CASE WHEN billtype =305 THEN costtotal ELSE 0 END) AS retaitotal,
				SUM(CASE WHEN billtype IN (34) THEN qty ELSE 0 END) AS [buyqty],
			    SUM(CASE WHEN billtype IN(34,205) THEN costtotal ELSE 0 END) AS [buytotal],
				SUM(CASE WHEN billtype IN (6) THEN qty ELSE 0 END) AS [buybackqty],
			    SUM(CASE WHEN billtype IN (6) THEN costtotal ELSE 0 END) AS [buybacktotal],
				SUM(CASE WHEN billtype IN (45,46) THEN qty ELSE 0 END) AS [salebackqty],
			    SUM(CASE WHEN billtype IN (45,46) THEN costtotal ELSE 0 END) AS [salebacktotal],
				SUM(CASE WHEN billtype=400 THEN qty ELSE 0 END) AS appraisalbillqty,
			    SUM(CASE WHEN billtype=400 THEN costtotal ELSE 0 END) AS appraisalbilltotal,	--暂估入库
				SUM(CASE WHEN billtype=403 THEN qty ELSE 0 END) AS sendbackbillqty,
			    SUM(CASE WHEN billtype=403 THEN costtotal ELSE 0 END) AS sendbackbilltotal,	--发出商品退货
				SUM(CASE WHEN billtype=402 THEN qty ELSE 0 END) AS sendbillqty,
			    SUM(CASE WHEN billtype=402 THEN costtotal ELSE 0 END) AS sendbilltotal,	--发出商品出库
				SUM(CASE WHEN billtype=401 THEN qty ELSE 0 END) AS appraisalbackbillqty,
			    SUM(CASE WHEN billtype=401 THEN costtotal ELSE 0 END) AS appraisalbackbilltotal,	--暂估退货
			    SUM(CASE billtype WHEN 9 THEN qty ELSE 0 END) AS [loseqty],
			    SUM(CASE billtype WHEN 9 THEN costtotal ELSE 0 END) AS [losetotal],
			    SUM(CASE billtype WHEN 14 THEN qty ELSE 0 END) AS [overflowqty],
			    SUM(CASE billtype WHEN 14 THEN costtotal ELSE 0 END) AS [overflowtotal],
			    SUM(CASE billtype WHEN 139 THEN qty ELSE 0 END) AS [zengsongqty],
			    SUM(CASE billtype WHEN 139 THEN costtotal ELSE 0 END) AS [zengsongtotal],
			    SUM(CASE billtype WHEN 126 THEN qty ELSE 0 END) AS [huozengqty],
			    SUM(CASE billtype WHEN 126 THEN costtotal ELSE 0 END) AS [huozengtotal],
			    SUM(CASE billtype WHEN 16 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [packetrkqty],
			    SUM(CASE billtype WHEN 16 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [packetckqty],
			    SUM(CASE billtype WHEN 16 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [packetrktotal],
			    SUM(CASE billtype WHEN 16 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [packetcktotal],
			    SUM(CASE billtype WHEN 57 THEN costtotal ELSE 0 END) AS kcchange,
			    SUM(CASE billtype WHEN 17 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [tjdbrkqty],
			    SUM(CASE billtype WHEN 17 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [tjdbckqty],
			    SUM(CASE billtype WHEN 17 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [tjdbrktotal],
			    SUM(CASE billtype WHEN 17 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [tjdbcktotal],
			    SUM(CASE billtype WHEN 21 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [bjdbrkqty],
			    SUM(CASE billtype WHEN 21 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [bjdbckqty],
			    SUM(CASE billtype WHEN 21 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [bjdbrktotal],
			    SUM(CASE billtype WHEN 21 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [bjdbcktotal],
			    SUM(CASE billtype WHEN 140 THEN qty ELSE 0 END) AS [wtfhqty],
			    SUM(CASE billtype WHEN 140 THEN costtotal ELSE 0 END) AS [wtfhtotal],
			    SUM(CASE billtype WHEN 142 THEN qty ELSE 0 END) AS [wtthqty],
			    SUM(CASE billtype WHEN 142 THEN costtotal ELSE 0 END) AS [wtthtotal],
			    SUM(CASE billtype WHEN 144 THEN qty ELSE 0 END) AS [stshqty],
			    SUM(CASE billtype WHEN 144 THEN costtotal ELSE 0 END) AS [stshtotal],
			    SUM(CASE billtype WHEN 146 THEN qty ELSE 0 END) AS [stthqty],
			    SUM(CASE billtype WHEN 146 THEN costtotal ELSE 0 END) AS [stthtotal],			
				SUM(CASE billtype WHEN 160 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [xshrqty],
				SUM(CASE billtype WHEN 160 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [xshcqty],
				SUM(CASE billtype WHEN 160 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [xshrtotal],
				SUM(CASE billtype WHEN 160 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [xshctotal],
				SUM(CASE billtype WHEN 161 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [cghrqty],
				SUM(CASE billtype WHEN 161 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [cghcqty],
				SUM(CASE billtype WHEN 161 THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [cghrtotal],
				SUM(CASE billtype WHEN 161 THEN (CASE WHEN qty<0 THEN costtotal ELSE 0 END) ELSE 0 END) AS [cghctotal],
			    SUM(CASE billtype WHEN 174 THEN qty ELSE 0 END) AS [wxdrqty],
			    SUM(CASE billtype WHEN 174 THEN costtotal ELSE 0 END) AS [wxdrtotal],
			    SUM(CASE billtype WHEN 173 THEN qty ELSE 0 END) AS [wxdcqty],
			    SUM(CASE billtype WHEN 173 THEN costtotal ELSE 0 END) AS [wxdctotal],
			    SUM(CASE billtype WHEN 168 THEN qty ELSE 0 END) AS [zjghqty],
			    SUM(CASE billtype WHEN 168 THEN costtotal ELSE 0 END) AS [zjghtotal],
			    SUM(CASE billtype WHEN 166 THEN qty ELSE 0 END) AS [wxdqty],
			    SUM(CASE billtype WHEN 166 THEN costtotal ELSE 0 END) AS [wxdtotal],
			    SUM(CASE billtype WHEN 172 THEN qty ELSE 0 END) AS [smwxdqty],
			    SUM(CASE billtype WHEN 172 THEN costtotal ELSE 0 END) AS [smwxdtotal],
			    SUM(CASE WHEN qty<0 AND (BillType<>57 OR (billtype=57 AND AdPriceType=0)) THEN qty ELSE 0 END) AS [bqckQty],
			    SUM(CASE WHEN qty<0 THEN costtotal ELSE 0 END) AS [bqcktotal],
			    SUM(CASE WHEN qty>0 AND (BillType<>57 OR (billtype=57 AND AdPriceType=0)) THEN qty ELSE 0 END) AS [bqrkQty],
				SUM(CASE WHEN qty>=0 THEN costtotal ELSE 0 END) AS [bqrktotal],
				SUM(CASE billtype WHEN 178 THEN qty ELSE 0 END) AS [kxckqty],
			    SUM(CASE billtype WHEN 178 THEN costtotal ELSE 0 END) AS [kxcktotal],
  				SUM(CASE billtype WHEN 183 THEN qty ELSE 0 END) AS [integralckqty],
			    SUM(CASE billtype WHEN 183 THEN costtotal ELSE 0 END) AS [integralcktotal],			       
			    SUM(CASE billtype WHEN 188 THEN qty ELSE 0 END) AS [innerinqty],
			    SUM(CASE billtype WHEN 188 THEN costtotal ELSE 0 END) AS [innerintotal],			    
				 SUM(CASE billtype WHEN 187 THEN qty ELSE 0 END) AS [inneroutqty],
			    SUM(CASE billtype WHEN 187 THEN costtotal ELSE 0 END) AS [innerouttotal],			    
			    SUM(CASE billtype WHEN 191 THEN qty ELSE 0 END) AS [materialoutstockqty],
			    SUM(CASE billtype WHEN 191 THEN costtotal ELSE 0 END) AS [materialoutstocktotal],			    
			    SUM(CASE billtype WHEN 196 THEN qty ELSE 0 END) AS [jyckqty],
			    SUM(CASE billtype WHEN 196 THEN costtotal ELSE 0 END) AS [jycktotal],			    
			    SUM(CASE billtype WHEN 197 THEN qty ELSE 0 END) AS [materialbackstockqty],
			    SUM(CASE billtype WHEN 197 THEN costtotal ELSE 0 END) AS [materialbackstocktotal],			    
			    SUM(CASE billtype WHEN 201 THEN qty ELSE 0 END) AS [otherinqty],
			    SUM(CASE billtype WHEN 201 THEN costtotal ELSE 0 END) AS [otherintotal],			    
			    SUM(CASE billtype WHEN 202 THEN qty ELSE 0 END) AS [otheroutqty],
			    SUM(CASE billtype WHEN 202 THEN costtotal ELSE 0 END) AS [otherouttotal],
			    SUM(CASE billtype WHEN 215 THEN qty ELSE 0 END) AS retailbackqty,
			    SUM(CASE billtype WHEN 215 THEN costtotal ELSE 0 END) AS retailbacktotal,
			    
			    SUM(CASE WHEN billtype IN(328,329) THEN qty ELSE 0 END) AS [psrqty],
				SUM(CASE WHEN billtype IN(328,329) THEN costtotal ELSE 0 END) AS [psrtotal],
				SUM(CASE WHEN billtype = 327 THEN qty ELSE 0 END) AS [pscqty],
				SUM(CASE WHEN billtype = 327 THEN costtotal ELSE 0 END) AS [psctotal]	     
		INTO 	#ResultInOutStockTable1
			FROM(
		
				SELECT  PTypeId ,
						BillType ,
						SUM(CASE WHEN   AdPriceType=0  THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) 
						WHEN  AdPriceType=1 THEN 0
						ELSE 0 END) AS Qty ,
						SUM(CASE WHEN  AdPriceType=0  THEN (CASE WHEN qty>0 THEN costtotal ELSE 0 END) 
						WHEN  AdPriceType=1	THEN   costtotal
						ELSE 0 END) AS CostTotal ,
						AdPriceType
				FROM    #SumInOutStockTable1
				WHERE   billtype = 57
				GROUP BY	PTypeId ,
							BillType ,
							AdPriceType 						
				UNION ALL 
			    SELECT  PTypeId ,
						BillType ,
						SUM(CASE WHEN   AdPriceType=0  THEN (CASE WHEN qty<=0 THEN qty ELSE 0 END) 
						WHEN  AdPriceType=2 THEN 0
						ELSE 0 END) AS Qty ,
						SUM(CASE WHEN  AdPriceType=0  THEN (CASE WHEN qty<=0 THEN costtotal ELSE 0 END) 
						WHEN  AdPriceType=2	THEN   costtotal
						ELSE 0 END) AS CostTotal ,
						AdPriceType
				FROM    #SumInOutStockTable1
				WHERE   billtype = 57
				GROUP BY	PTypeId ,
							BillType ,
							AdPriceType  
				UNION ALL
				SELECT  PTypeId ,
						BillType ,
						Qty ,
						CostTotal ,
						AdPriceType
				FROM    #SumInOutStockTable1
				WHERE   billtype != 57  		
		) A
		GROUP BY SUBSTRING(PTypeId,1,LEN(@szPTypeId)+5)	
		
		-----IniGoodsStocks的精简
		 CREATE TABLE #AllIniGoodsStocks1
			(
				ptypeid		varchar(100),
				iniqty		 NUMERIC(24, 10) ,
				initotal	 NUMERIC(24, 10) 
			)
		DECLARE @sqltemp VARCHAR(2000)
		
		SET @sqltemp='
		INSERT	INTO 	#AllIniGoodsStocks1 
		SELECT 	i.ptypeid,
				ISNULL(SUM(qty/'+@unitrate+'),0) AS iniqty,
				ISNULL(SUM(total),0) AS initotal
		FROM 	inigoodsstocks i
		inner join ptype p1 on p1.typeid=i.ptypeid
				INNER JOIN #GetManKTypeId k ON k.typeid=i.ktypeid
				INNER JOIN #GetManPTypeId p ON p.typeid=i.ptypeid
				'+@tmptab+'
		GROUP BY i.ptypeid'

		EXEC(@sqltemp)
		  
				
		-----日期以前的InOutStockTable的精简
		CREATE TABLE #PreInOutStockTable1
		(
			PTypeId		varchar(100),
			PreQty		 NUMERIC(24, 10) ,
			PreTotal	 NUMERIC(24, 10) 
		)
	
		DECLARE @XXXX varchar(3000)
	
		SET @XXXX = '
			INSERT 	INTO #PreInOutStockTable1 
			SELECT 	i.ptypeid,
					ISNULL(SUM(case when bil.AdPriceType=0 OR i.billtype in(327,328,329) then qty else 0 end/'+@unitrate+'),0)    AS preqty,
					ISNULL(SUM(Costtotal),0) AS pretotal 		
			FROM 	inoutstocktable i
			--INNER JOIN #billtypeTable B on i.billtype=b.Billtype OR b.billtype=0
			inner join #TempPType1 p1 on p1.typeid=i.ptypeid
			LEFT join billindex bil on bil.billnumberid=i.billnumberid
			'+@tmptab
			
				IF @Mktypeid='-99999' OR @szKtypeId<>''
				SET @XXXX=@XXXX+'
							INNER JOIN #GetManKTypeId k ON i.ktypeid=k.typeid '
							
		IF @Mstypeid='-99999' OR @StypeId<>''
				SET @XXXX=@XXXX+'			
							INNER JOIN #GetSelectSTypeId sk ON i.stypeid=sk.typeid '
										
		IF @MPtypeid='-99999'  OR @szPtypeId<>''
			SET @XXX =@XXXX+' INNER JOIN #GetManPTypeId p ON i.ptypeid=p.typeid '	
							
		IF  @szEtypeId<>'00001' OR @MEtypeid='-99999'
			SET @XXX =@XXXX+' INNER JOIN #GetManETypeId e ON i.ETypeId=e.typeid '	
				
		SET @XXXX=@XXXX+'			
			WHERE  	Audited = 1
					AND i.KTypeId <> ''10000''				
					AND i.billdate<'+char(39)+@startdate+char(39)+'
					
			GROUP BY i.ptypeid '
			
		print(@xxxx)
		EXEC(@XXXX)
	
		----------------------------------------正式开始运算-----------------------------------------------------------------		
		 SELECT	p.typeid,
				p.usercode,
				p.fullname,
				p.sonnum,
                p.sortid,                
                p.saleUnitId,
				saleunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.saleunitid),
				p.BuyUnitId,
				buyunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.BuyUnitId),
				p.StockUnitId,
				stockunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.StockUnitId),
				p.baseUnitId,
				baseunitname = (SELECT FullName FROM PType_Units WHERE unitsid = p.baseUnitId),
				abs(ISNULL(SUM(b.[buyqty]),0)) AS buyqty,
				abs(ISNULL(SUM(b.[buytotal]),0)) AS buytotal,
				abs(ISNULL(SUM(b.[salebackqty]),0)) AS salebackqty,
				abs(ISNULL(SUM(b.[salebacktotal]),0)) AS salebacktotal,
				abs(ISNULL(SUM(b.overflowqty),0)) AS overflowqty,
				abs(ISNULL(SUM(b.overflowtotal),0)) AS overflowtotal ,
				abs(ISNULL(SUM(b.packetrkqty),0)) AS packetrkqty,			
				abs(ISNULL(SUM(b.packetrktotal),0)) AS packetrktotal,
				isnull(SUM(b.kcchange),0) as kcchange,
				abs(ISNULL(SUM(b.tjdbrkqty),0)) AS tjdbrkqty,
				abs(ISNULL(SUM(b.tjdbrktotal),0)) AS tjdbrktotal,
				abs(ISNULL(SUM(b.bjdbrkqty),0)) AS bjdbrkqty,			
				abs(ISNULL(SUM(b.bjdbrktotal),0)) AS bjdbrktotal,
				abs(ISNULL(SUM(b.huozengqty),0)) AS huozengqty,
				abs(ISNULL(SUM(b.huozengtotal),0)) AS huozengtotal,
				abs(ISNULL(SUM(b.wtthqty),0)) AS wtthqty,
				abs(ISNULL(SUM(b.wtthtotal),0)) AS wtthtotal,
				abs(ISNULL(SUM(b.stshqty),0)) AS stshqty,
				abs(ISNULL(SUM(b.stshtotal),0)) AS stshtotal,
				abs(ISNULL(SUM(b.cghrqty),0)) AS cghrqty,			
				abs(ISNULL(SUM(b.cghrtotal),0)) AS cghrtotal,
				abs(ISNULL(SUM(b.xshrqty),0)) AS xshrqty,
				abs(ISNULL(SUM(b.xshrtotal),0)) AS xshrtotal,
				abs(ISNULL(SUM(b.[saleqty]),0)) AS saleqty,
				abs(ISNULL(SUM(b.[saletotal]),0)) AS saletotal,
				abs(ISNULL(SUM(b.retaiqty),0)) AS retaiqty,
				abs(ISNULL(SUM(b.retaitotal),0)) AS retaitotal,
				abs(ISNULL(SUM(b.[buybackqty]),0)) AS buybackqty,
				abs(ISNULL(SUM(b.[buybacktotal]),0)) AS buybacktotal,
				abs(ISNULL(SUM(b.loseqty),0)) AS loseqty,
				abs(ISNULL(SUM(b.losetotal),0)) AS losetotal ,
				abs(ISNULL(SUM(b.packetckqty),0)) AS packetckqty,
				abs(ISNULL(SUM(b.packetcktotal),0)) AS packetcktotal,
				abs(ISNULL(SUM(b.tjdbckqty),0)) AS tjdbckqty,
				abs(ISNULL(SUM(b.tjdbcktotal),0)) AS tjdbcktotal,
				abs(ISNULL(SUM(b.bjdbckqty),0)) AS bjdbckqty ,
				abs(ISNULL(SUM(b.bjdbcktotal),0)) AS bjdbcktotal,
				abs(ISNULL(SUM(b.zengsongqty),0)) AS zengsongqty,			
				abs(ISNULL(SUM(b.zengsongtotal),0)) AS zengsongtotal,
				abs(ISNULL(SUM(b.wtfhqty),0)) AS wtfhqty,
				abs(ISNULL(SUM(b.wtfhtotal),0)) AS wtfhtotal,
				abs(ISNULL(SUM(b.stthqty),0)) AS stthqty,
				abs(ISNULL(SUM(b.stthtotal),0)) AS stthtotal,
				abs(ISNULL(SUM(b.cghcqty),0)) AS cghcqty,
				abs(ISNULL(SUM(b.cghctotal),0)) AS cghctotal,
				abs(ISNULL(SUM(b.xshcqty),0)) AS xshcqty,
				abs(ISNULL(SUM(b.xshctotal),0)) AS xshctotal,
				abs(ISNULL(SUM(b.wxdrqty),0)) AS wxdrqty,
				abs(ISNULL(SUM(b.wxdrtotal),0)) AS wxdrtotal,
				abs(ISNULL(SUM(b.wxdcqty),0)) AS wxdcqty,
				abs(ISNULL(SUM(b.wxdctotal),0)) AS wxdctotal,
				abs(ISNULL(SUM(b.zjghqty),0)) AS zjghqty,
				abs(ISNULL(SUM(b.zjghtotal),0)) AS zjghtotal,
				abs(ISNULL(SUM(b.wxdqty),0)) AS wxdqty,
				abs(ISNULL(SUM(b.wxdtotal),0)) AS wxdtotal,
				abs(ISNULL(SUM(b.smwxdqty),0)) AS smwxdqty,
				abs(ISNULL(SUM(b.smwxdtotal),0)) AS smwxdtotal,
				ISNULL(SUM(b.bqckQty),0) AS bqckQty,
				ISNULL(SUM(b.bqcktotal),0) AS bqcktotal,
				ISNULL(SUM(b.bqrkQty),0) AS bqrkQty,
				ISNULL(SUM(b.bqrktotal),0) AS bqrktotal,
				abs(ISNULL(SUM(b.kxckqty),0)) AS kxckqty,
				abs(ISNULL(SUM(b.kxcktotal),0)) AS kxcktotal,
				abs(ISNULL(SUM(b.integralckqty),0)) AS integralckqty,
				abs(ISNULL(SUM(b.integralcktotal),0)) AS integralcktotal,							
				abs(ISNULL(SUM(b.innerinqty),0)) AS innerinqty,
				abs(ISNULL(SUM(b.innerintotal),0)) AS innerintotal,
				abs(ISNULL(SUM(b.inneroutqty),0)) AS inneroutqty,
				abs(ISNULL(SUM(b.innerouttotal),0)) AS innerouttotal,				
				abs(ISNULL(SUM(b.materialoutstockqty),0)) AS materialoutstockqty,
				abs(ISNULL(SUM(b.materialoutstocktotal),0)) AS materialoutstocktotal,
				abs(ISNULL(SUM(b.jyckqty),0)) AS jyckqty,
				abs(ISNULL(SUM(b.jycktotal),0)) AS jycktotal,				
				abs(ISNULL(SUM(b.materialbackstockqty),0)) AS materialbackstockqty,
				abs(ISNULL(SUM(b.materialbackstocktotal),0)) AS materialbackstocktotal,				
				abs(ISNULL(SUM(b.otherinqty),0)) AS otherinqty,
				abs(ISNULL(SUM(b.otherintotal),0)) AS otherintotal,						
				abs(ISNULL(SUM(b.otheroutqty),0)) AS otheroutqty,
				abs(ISNULL(SUM(b.otherouttotal),0)) AS otherouttotal,
				abs(ISNULL(SUM(b.retailbackqty),0)) AS retailbackqty,
				abs(ISNULL(SUM(b.retailbacktotal),0)) AS retailbacktotal,				
				abs(SUM(ISNULL(b.appraisalbillqty,0))) AS appraisalbillqty,
				abs(SUM(ISNULL(b.appraisalbilltotal,0))) AS appraisalbilltotal,
				abs(SUM(ISNULL(b.sendbackbillqty,0))) AS sendbackbillqty,
				abs(SUM(ISNULL(b.sendbackbilltotal,0))) AS sendbackbilltotal,
				abs(SUM(ISNULL(b.sendbillqty,0))) AS sendbillqty,
				abs(SUM(ISNULL(b.sendbilltotal,0))) AS sendbilltotal,
				abs(SUM(ISNULL(b.appraisalbackbillqty,0))) AS appraisalbackbillqty,
				abs(SUM(ISNULL(b.appraisalbackbilltotal,0))) AS appraisalbackbilltotal,
				abs(ISNULL(SUM(b.[psrqty]),0)) AS psrqty,
				abs(ISNULL(SUM(b.[psrtotal]),0)) AS psrtotal,
				abs(ISNULL(SUM(b.[pscqty]),0)) AS pscqty,
				abs(ISNULL(SUM(b.[psctotal]),0)) AS psctotal			
		INTO 	#LastResult1_0
		FROM 	#TempPType p
		LEFT JOIN #ResultInOutStockTable1 b ON b.ptypeid=p.typeid		
		GROUP BY  
				p.typeid,
				p.usercode,
				p.fullname,
				p.sonnum,
				p.sortid,
				p.SaleUnitId,
                p.BuyUnitId,
                p.StockUnitId,
                p.baseUnitId
	
	
		CREATE TABLE #TempResult
		(
			TypeId		varchar(200),
			PreQty		 NUMERIC(24, 10) ,
			PreTotal	 NUMERIC(24, 10) ,
			iniqty		 NUMERIC(24, 10) ,
			iniTotal	 NUMERIC(24, 10) 
		)

		INSERT INTO #TempResult
		SELECT	A.TypeId,
				ISNULL(SUM(B.PreQty),0) AS PreQty,
				ISNULL(SUM(B.PreTotal),0) AS PreTotal,
				ISNULL(SUM(B.iniqty),0) AS iniqty,
				ISNULL(SUM(B.iniTotal),0) AS iniTotal	
		FROM	#TempPType A
		LEFT JOIN (
					SELECT	B.TypeId,
							ISNULL(SUM(B.PreQty),0) AS PreQty,
							ISNULL(SUM(B.PreTotal),0) AS PreTotal,
							ISNULL(SUM(B.iniqty),0) AS iniqty,
							ISNULL(SUM(B.iniTotal),0) AS iniTotal
					FROM	(
								SELECT	PTypeId AS TypeId,
										0 AS PreQty,
										0 AS PreTotal,
										ISNULL(SUM(iniqty),0) AS iniqty,
										ISNULL(SUM(iniTotal),0) AS iniTotal			
								FROM	#AllIniGoodsStocks1
								GROUP BY PTypeId
								UNION ALL
								SELECT	PTypeId AS TypeId,
										ISNULL(SUM(preqty),0) AS PreQty,
										ISNULL(SUM(preTotal),0) AS PreTotal,
										0 AS iniqty,
										0 AS iniTotal									
								FROM	#PreInOutStockTable1
								GROUP BY PTypeId
					)B GROUP BY B.TypeId
		)B ON (LEFT(B.TypeId,len(a.typeid))=a.typeid)
		GROUP BY A.TypeId
		

		DECLARE @SQLWHERE VARCHAR(MAX)=''
		IF @strBdSp = '0' 
			SET @SQLWHERE=' b.bqrkQty <> 0 OR b.bqckQty <> 0 '
		ELSE IF @strBdSp = '2' 
			SET @SQLWHERE=' ((r.preqty+r.iniqty)<>0
							OR (R.preqty+R.iniqty+b.bqckQty+b.bqrkQty)<>0
							OR b.bqrkqty<>0
							OR b.bqckqty<>0) '
		ELSE IF @strBdSp = '1'
			SET @SQLWHERE=' 1=1 '
	
		SET @SQL='
		SELECT 	b.*,
				case 
					when (r.preqty+r.iniqty+b.bqckQty+b.bqrkQty) = 0 then 0
					else CAST((r.preTotal+r.iniTotal+b.bqckTotal+b.bqrkTotal)/(r.preqty+r.iniqty+b.bqckQty+b.bqrkQty) as  NUMERIC(24, 10) ) 
				end as bqcprice,
		      	(r.preqty+r.iniqty) AS sqcQty,
		      	(r.preqty+r.iniqty+b.bqckQty+b.bqrkQty) AS bqcQty,
		      	(r.preTotal+r.iniTotal) AS sqcTotal,
		      	(r.preTotal+r.iniTotal+b.bqckTotal+b.bqrkTotal) AS bqcTotal
		FROM	#LastResult1_0 b inner join #TempResult r on b.typeid=r.typeid
		WHERE	'+ @SQLWHERE
		
		  IF @unitconvert = 4 
                BEGIN	
                    SET @SQL = '
						SELECT  t1.*,t2.* FROM  (' + @SQL + ') t1
						LEFT JOIN( 
									SELECT  ptypeid ,
											SaleUnitRate1 ,
											(SELECT FullName FROM  dbo.PType_Units pu WHERE pu.UnitsId = pau.saleunitid1) AS fullname1,
											SaleUnitRate2 ,
											(SELECT FullName FROM  dbo.PType_Units pu WHERE pu.UnitsId = pau.saleunitid2 ) AS fullname2,
											SaleUnitRate3 ,
											(SELECT FullName FROM  dbo.PType_Units pu WHERE pu.UnitsId = pau.saleunitid3) AS fullname3
									FROM    dbo.PType_AuxiliaryUnits_Ext pau 
							)t2 ON  t2.ptypeid=t1.typeid
						 '
                END             
                SET @SQL = @SQL + ' ORDER BY sortid '	
		EXEC(@SQL)

		DROP TABLE 	#LastResult1_0,#TempPType,#AllIniGoodsStocks1,#PreInOutStockTable1--,#InOutStockTable
		DROP TABLE #ResultInOutStockTable1,#SumInOutStockTable1,#TempPType1,#TempResult
END


DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManETypeId,#GetSelectSTypeId,#billtypeTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Comm_StockChangeRep_Mx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Comm_StockChangeRep_Mx]
GO
/*
	作者：黄飞佳
	日期：2012-05-07
	描述：添加cargoid货位列查询
*/

/*
	作者：谢吉康
	日期：2009-12-03
	描述：进销存汇总明细表
*/
CREATE                  PROCEDURE Comm_StockChangeRep_Mx
( 
	 @startdate		varchar(25),
	 @EndDate		varchar(25),
	 @PtypeId		varchar(8000),
	 @ptypecategoryid	VARCHAR(50)='',--商品类别				 
	 @BtypeId		varchar(8000),
	 @KtypeId		varchar(8000),
     @EtypeId   	varchar(8000),                    --经手人   #-01
	 @cMode			varchar(2),
	 @PreQty		 NUMERIC(24, 10)  OUTPUT,
	 @PreTotal		 NUMERIC(24, 10)  OUTPUT,
	 @sortfield		varchar(25),
	 @OperatorId    varchar(100),       --操作员ID
	 @Stypeid       VARCHAR(8000)
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------

IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

				 
--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetManDetailEType(@OperatorID)

CREATE TABLE #GetSelETypeId(TypeId	varchar(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT * FROM F_GetAllBaseTypeId(@ETypeId,3)


--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.TypeId = sk.TypeId
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM  F_GetAllBaseTypeId(@KTypeId,4)

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_ManPTypeInCategoryID(@OperatorId,@PtypeId,@ptypecategoryid)

DECLARE @strQuery varchar(8000)
SELECT @strQuery=''

DECLARE @lim VARCHAR(1)
SET @lim ='0'

SELECT   @lim =SUBSTRING(b.lim,439,1) FROM loginuser b WHERE  b.etypeid=@OperatorId -- 调拔调阅 加不限经手人权限 ADD BY chen_qihua 2004-2-13 ===========

IF @OperatorId<>''
   	BEGIN
		IF @lim ='1' 
			SELECT @strQuery=' AND ((a.billtype in (17,21) and c.EtypeId like ''%'') OR (a.billtype not in (17,21) and c.ETypeId IN (SELECT * FROM #GetManETypeId) AND c.ETypeId IN (SELECT * FROM #GetSelETypeId)))'
		ELSE
			SELECT @strQuery=' AND c.EtypeId IN (SELECT * FROM #GetManETypeId) AND c.ETypeId IN (SELECT * FROM #GetSelETypeId)' --原来如此
	END

--  加经手人限制,若是全部经手人，没有该限制  徐辉  2004-3-30       #-01
IF @EtypeId<>''
  	BEGIN
		SELECT @strQuery=' AND c.EtypeId IN (SELECT * FROM #GetManETypeId) AND c.ETypeId IN (SELECT * FROM #GetSelETypeId)'
	END
	
	
-------------------------------------------------------分组-------------------------------
DECLARE @GroupBy varchar(2000)

SELECT @GroupBy ='  GROUP BY	a.BillNumberId,
								c.billdate,
								a.billtype,
								c.costprice,
								c.qty,
								a.billcode,
								a.comment,
								a.redword,
								c.ptypeid,
								c.ktypeid,
								a.btypeid,
								a.etypeid,
								a.stypeid,
								c.cargoid,
								A.AdPriceType,
								c.id,
								c.posttime '

--------------------------------------------------------排序-------------------------------

DECLARE @Sql varchar (8000)
SET @Sql ='		SELECT	a.BillNumberId,
						c.BillDate,
						a.billtype,
						CASE  WHEN a.billtype=145 THEN -ISNULL(SUM(c.qty),0)	
							  WHEN a.billtype=57 AND A.AdPriceType<>0 THEN 0
								ELSE  ISNULL(SUM(c.qty),0)	END AS qty,
						CASE  WHEN a.billtype=145 THEN -ISNULL(SUM(c.Costtotal),0)	ELSE  ISNULL(SUM(c.Costtotal),0)	END AS Costtotal,
						CASE  WHEN a.billtype=145 THEN -ISNULL(SUM(c.total),0)	ELSE  ISNULL(SUM(c.total),0)	END AS total,
						c.CostPrice,
						a.BillCode, 
						a.Comment,
						a.RedWord, 
						c.ptypeid,        			
						CASE a.billtype WHEN 145 THEN ''10000'' ELSE c.ktypeid END AS ktypeid,
						a.btypeid,
						a.stypeid,
						c.cargoid,
						c.id as customid,
						c.posttime
				FROM 	BillIndex a
				INNER JOIN inoutstocktable  c ON c.billnumberid=a.billnumberid AND a.billType=c.BillType
				INNER JOIN #GetManPTypeId p ON c.ptypeid=p.typeid
				INNER JOIN #GetSelectSTypeId sk ON c.stypeid=sk.typeid	'
							
IF @KtypeId<>'' OR @MKtypeid='-99999'				
	SET @Sql =@Sql+'	INNER JOIN #GetManKTypeId k ON k.typeid=c.ktypeid'
 						
SET @Sql =@Sql+'
				WHERE 	a.redword =0 
						AND c.billdate >='+char(39)+@startdate+char(39)+' 
						AND c.billdate <='+char(39)+@enddate+char(39)+' 
						AND c.ktypeid<>'+CHAR(39)+'10000'+CHAR(39)+ '
						AND a.ifcheck='+char(39)+'t'+char(39)
SET @Sql=@Sql + ' AND a.ifYearBill= 0 '  + @strQuery + @GroupBy  --年节存标志


SET @Sql =@Sql+'		
				UNION	All
				SELECT	a.BillNumberId,
						c.BillDate,
						a.billtype,
						ISNULL(SUM(c.qty),0) AS qty,
						CASE  WHEN a.billtype in (328,329) THEN ISNULL(SUM(c.Costtotal),0)	ELSE  ISNULL(SUM(c.Costtotal),0)	END AS Costtotal,
						CASE  WHEN a.billtype in (328,329) THEN ISNULL(SUM(c.total),0)	ELSE  ISNULL(SUM(c.total),0)	END AS total,
						c.CostPrice,
						a.BillCode, 
						a.Comment,
						a.RedWord, 
						c.ptypeid,        			
						c.ktypeid AS ktypeid,
						'''' as btypeid,
						a.stypeid,
						c.cargoid,
						c.id as customid,
						c.posttime
				FROM 	PosAllotApplyBillIndex a
				INNER JOIN inoutstocktable  c ON c.billnumberid=a.billnumberid AND a.billType=c.BillType
				INNER JOIN #GetManPTypeId p ON c.ptypeid=p.typeid
				INNER JOIN #GetSelectSTypeId sk ON c.stypeid=sk.typeid	'
							
IF @KtypeId<>'' OR @MKtypeid='-99999'				
	SET @Sql =@Sql+'	INNER JOIN #GetManKTypeId k ON k.typeid=c.ktypeid'
 						
SET @Sql =@Sql+'
				WHERE 	a.redword =0 
						AND c.billdate >='+char(39)+@startdate+char(39)+' 
						AND c.billdate <='+char(39)+@enddate+char(39)+' 
						AND c.ktypeid<>'+CHAR(39)+'10000'+CHAR(39)+ '
						AND a.ifcheck='+char(39)+'t'+char(39)
SET @Sql=@Sql + ' AND a.ifYearBill= 0 AND a.billType in(327,328,329) '  + --@strQuery +   --年节存标志
'
	 GROUP BY	a.BillNumberId,
								c.billdate,
								a.billtype,
								c.costprice,
								c.qty,
								a.billcode,
								a.comment,
								a.redword,
								c.ptypeid,
								c.ktypeid,
								c.btypeid,
								a.stypeid,
								c.cargoid,
								c.id,
								c.posttime
'


DECLARE @SQLOrder	varchar(150)
SELECT @SQLOrder = ''

IF @sortfield = 'ByDate_a'		--ORDER BY date
    SELECT @SQLOrder = ' ORDER BY c.billdate, c.billtype, c.BillCode'
ELSE IF @sortfield = 'ByBillNo_a' 	--ORDER BY Bill No.
    SELECT @SQLOrder = ' ORDER BY c.BillCode'
ELSE IF @sortfield = 'ByBillType_a'	--ORDER BY Bill type
    SELECT @SQLOrder = ' ORDER BY c.billtype, c.billdate, c.BillCode'
ELSE IF @sortfield = 'ByBillID_a'	--ORDER BY Bill ID
    SELECT @SQLOrder = ' ORDER BY c.posttime'
ELSE IF @sortfield = 'ByDate_d'		--ORDER BY date DESC 
    SELECT @SQLOrder = ' ORDER BY c.billdate DESC, c.billtype, c.BillCode'
ELSE IF @sortfield = 'ByBillNo_d' 	--ORDER BY Bill No. DESC 
    SELECT @SQLOrder = ' ORDER BY c.BillCode DESC'
ELSE IF @sortfield = 'ByBillType_d'	--ORDER BY Bill type DESC 
    SELECT @SQLOrder = ' ORDER BY c.billtype DESC, c.billdate, c.BillCode'
ELSE IF @sortfield = 'ByBillID_d'	--ORDER BY Bill ID DESC 
    SELECT @SQLOrder = ' ORDER BY c.posttime DESC'
ELSE
    SELECT @SQLOrder = ' ORDER BY c.posttime'

SET @SQL ='	SELECT	*
			FROM ('+@SQL+')c 
			left join Custom_BillIndex csindex on c.billnumberid=csindex.BillId and c.billtype=csindex.billtype
			left join Custom_BillDetails csdetail on c.billnumberid=csdetail.BillId and c.billtype=csdetail.billtype AND c.customid=csdetail.Detailid
		  '+@SQLOrder

EXEC (@SQL)



DROP TABLE #GetManETypeId,#GetManKTypeId,#GetManPTypeId,#GetSelETypeId,#GetSelectSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2009-10-27
	描述：维修进销存汇总表
*/

CREATE               PROCEDURE Comm_Wx_StockChangeRep
(
	@OperatorID		VARCHAR(100),       		------------操作员id
	@BeginDate     	varchar(50),
	@EndDate        varchar(50),
	@szPtypeId     	VARCHAR(8000)='',        	--商品ID
	@szKtypeId     	VARCHAR(8000)='',        	--仓库ID
	@szEtypeId      VARCHAR(8000)='',         --经手人     --#-01
	@szFlag         CHAR(1)='A',
	@Web            INT=0,
	@UserCode       VARCHAR(26)='',
	@FullName       VARCHAR(66)='',
	@PTypeid        VARCHAR(100)='00000',
	@PageRows     	INT=14,
	@GoPageFlag    	INT=0,
	@PageNo         INT=1,
	@szPTypeKind  	VARCHAR(10),     		--'One'是具体商品,'Type'是大类商品
	@szPEntryCode	varchar(200)='',
	@stypeid		VARCHAR(8000)
	
)
--@encode$--
AS

SET ANSI_WARNINGS OFF
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT k.typeid FROM F_GetManDetailKTypeSType(@OperatorID) k 
				INNER JOIN #GetSelectSTypeId ss ON k.STypeId=ss.TypeId
--仓库
CREATE TABLE #GetManSelKTypeId(TypeId	varchar(100))
INSERT INTO #GetManSelKTypeId(TypeId) SELECT * FROM F_GetAllBaseTypeId(@szKtypeId,4)


--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetManDetailEType(@OperatorID)

--职员
CREATE TABLE #GetManSelETypeId(TypeId	varchar(100))
INSERT INTO #GetManSelETypeId(TypeId) SELECT * FROM F_GetAllBaseTypeId(@szETypeId,3)

----------------------------------------------------------------检查仓库是叶子还是节点[20030110]------------------------
DECLARE @StockSonnum INT
IF (@szKtypeId IS NULL) OR (@szKtypeId='00000') OR (@szKtypeId='')    --全部仓库
     SELECT @StockSonnum=-1000
ELSE 
     SELECT @StockSonnum=sonnum FROM stock WHERE typeid=@szKtypeId
------------------------------------------------------------------------------------------------------------------------------------
--///////////////////////////////////
           --      查询具体商品
--///////////////////////////////////
IF @szPTypeKind='one'
	BEGIN
		DECLARE @OPTypeIdMx varchar(100)

		IF @PtypeId='' OR @PtypeId IS NULL 
			SET @PtypeId='00000'

		IF @szPTypeId = '' OR @szPTypeId IS NULL
			SET @OPTypeIdMx = '%'
		ELSE
			SET @OPTypeIdMx = @szPTypeId
	
		IF @UserCode IS NULL OR @UserCode=''
	 		SELECT @UserCode='%'
		ELSE
	 		SELECT @UserCode='%'+@UserCode+'%'
	
		IF @FullName IS NULL OR @FullName=''
	 		SELECT @FullName='%'
		ELSE
	 		SELECT @FullName='%'+@FullName+'%'
	
		IF @szKtypeId IS NULL OR @szKtypeId=''
	 		SELECT @szKtypeId='%'
	
	
		DECLARE @Sql VARCHAR(8000),@Condition VARCHAR(300)
		DECLARE @NNN varchar(1000)
	
		CREATE TABLE #SumInOutStockTable
		(
			BillType 		int,
			PTypeId			varchar(100),
			Qty				 NUMERIC(24, 10) 
		)
	
		SET @NNN = 'INSERT INTO #SumInOutStockTable 
					SELECT 	BillType,
							PTypeId,
							SUM(Qty) AS Qty
					FROM 	Wx_InOutStockTable
					WHERE  	Audited = 1
							AND Qty <> 0
							AND KTypeId <> ''10000''
							AND BillDate>='+char(39)+@BeginDate+char(39)+'
							AND BillDate<='+char(39)+@EndDate+char(39)+'
					  		AND ktypeid IN (SELECT * FROM #GetManSelKTypeId)
					  		AND ktypeid IN (SELECT * FROM #GetManKTypeId)
							AND PTypeId LIKE '+char(39)+@OPTypeIdMx+'%'+char(39)+'
							AND ptypeid IN (SELECT * FROM #GetManPTypeId)
							AND ETypeId IN (SELECT * FROM #GetManSelETypeId)
							AND ETypeId IN (SELECT * FROM #GetManETypeId)
							AND stypeid IN (SELECT typeid FROM #GetSelectSTypeId)
					GROUP BY BillType,PTypeId,Qty '
	
		EXEC(@NNN)

		SELECT	ptypeid,
				SUM(CASE billtype WHEN 165 THEN qty ELSE 0 END) AS [jjrkqty],
			    SUM(CASE billtype WHEN 166 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [zxwxrkqty],
				SUM(CASE billtype WHEN 166 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [zxwxckqty],
				SUM(CASE billtype WHEN 167 THEN qty ELSE 0 END) AS [wxqjckqty],
				SUM(CASE billtype WHEN 168 THEN qty ELSE 0 END) AS [zjghckqty],
				SUM(CASE billtype WHEN 169 THEN qty ELSE 0 END) AS [sxckqty],
				SUM(CASE billtype WHEN 170 THEN qty ELSE 0 END) AS [sxfhrkqty],
				SUM(CASE billtype WHEN 172 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [smwxrkqty],
				SUM(CASE billtype WHEN 172 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [smwxckqty],
				SUM(CASE billtype WHEN 173 THEN qty ELSE 0 END) AS [wxdrqty],
				SUM(CASE billtype WHEN 174 THEN qty ELSE 0 END) AS [wxdcqty],			    
			    SUM(CASE billtype WHEN 175 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [wxdbdrqty],
				SUM(CASE billtype WHEN 175 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [wxdbdcqty],
				SUM(CASE billtype WHEN 9 THEN qty ELSE 0 END) AS [bsqty],
				SUM(CASE billtype WHEN 14 THEN qty ELSE 0 END) AS [byqty],						
			    SUM(CASE WHEN qty<0 THEN qty ELSE 0 END) AS [bqckQty],
			    SUM(CASE WHEN qty>0 THEN qty ELSE 0 END) AS [bqrkQty]
			INTO #ResultInOutStockTable
		    FROM  #SumInOutStockTable 
			GROUP BY ptypeid 
	
	         -----显示全部商品
			SELECT	ptypeid,
					ISNULL(SUM(qty),0) AS iniqty
			INTO 	#AllIniGoodsStocks 			 
			FROM 	Wx_inigoodsstocks
			WHERE 	ktypeid IN (SELECT * FROM #GetManSelKTypeId)
					AND ktypeid IN (SELECT * FROM #GetManKTypeId)
					AND PTypeId IN (SELECT * FROM #GetManPTypeId)
					AND Qty<>0 
			GROUP BY ptypeid

	
			-----日期以前的InOutStockTable的精简
			CREATE TABLE #PreInOutStockTable
			(
				PTypeId		varchar(100),
				PreQty		 NUMERIC(24, 10) 
			)
		
			DECLARE @NNNN varchar(1000)
		
			SET @NNNN = '
				INSERT 	INTO #PreInOutStockTable 
				SELECT 	ptypeid,
						ISNULL(SUM(qty),0) AS preqty
				FROM 	Wx_inoutstocktable 
				WHERE  	Audited = 1
						AND Qty <> 0
						AND KTypeId <> ''10000''
						AND billdate<'+char(39)+@BeginDate+char(39)+'
						AND ktypeid IN (SELECT * FROM #GetManSelKTypeId)
						AND ktypeid IN (SELECT * FROM #GetManKTypeId)
						AND ptypeid LIKE  '+char(39)+@szPTypeID+'%'+char(39)+'
						AND ptypeid IN (SELECT * FROM #GetManPTypeId)
						AND ETypeId IN (SELECT * FROM #GetManSelETypeId)
						AND ETypeId IN (SELECT * FROM #GetManETypeId)
						AND stypeid IN (SELECT typeid FROM #GetSelectSTypeId)
				GROUP BY ptypeid '
		
			--PRINT(@NNNN)
			EXEC(@NNNN)

	
			-----------------------------------------------------------编辑通用查询条件[20030110]--------------------------
			SELECT @Condition='p.sonnum=0 and p.IsService=0  AND p.iscombinationproduct = 0 '
			IF  @UserCode<>'%' 
			    SELECT @Condition=@Condition+' 	AND ISNULL(p.UserCode,'''') LIKE '+CHAR(39)+@UserCode+CHAR(39)
			IF @FullName<>'%'
			    SELECT @Condition=@Condition+'  AND ISNULL(p.FullName,'''') LIKE '+CHAR(39)+@fullname+CHAR(39)
			
			SELECT @Condition=@Condition+' AND p.typeid>='+CHAR(39)+@PTypeid+CHAR(39)
			
			IF @UserCode = '%' AND @FullName = '%'
				SELECT @Condition=@Condition+' 	AND P.TypeId LIKE '+char(39)+@szPTypeId+'%'+char(39)

			SET @Condition = @Condition + ' AND ISNULL(P.EntryCode,'''') LIKE '+char(39)+'%'+@szPEntryCode+'%'+char(39)
	
	
	
	
	--------------------------------------------------------------------------------------------------------------------------
	
	IF UPPER(@szFlag)='P'
		BEGIN	
			--------------------------不显示未变动的商品-----------
			SELECT @Sql='
				SELECT 	a.*,
						ISNULL(c.preqty,0)+ISNULL(i.iniqty,0) AS sqcQty,
						ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0) AS bqcQty
				INTO 	#LastResultOne
				FROM (	
						SELECT 	p.typeid,
								p.UserCode,
								p.fullname,
								p.EntryCode,
								p.Standard,
								p.Type,
								p.Area,
								p.Unit1,
								abs(ISNULL(b.wxdrqty,0)) AS wxdrqty,
								abs(ISNULL(b.jjrkqty,0)) AS jjrkqty,
								abs(ISNULL(b.zxwxrkqty,0)) AS zxwxrkqty,
								abs(ISNULL(b.smwxrkqty,0)) AS smwxrkqty,
								abs(ISNULL(b.sxfhrkqty,0)) AS sxfhrkqty,
								abs(ISNULL(b.byqty,0)) AS byqty,			
								abs(ISNULL(b.wxdcqty,0)) AS wxdcqty,
								abs(ISNULL(b.zxwxckqty,0)) AS zxwxckqty,
								abs(ISNULL(b.zjghckqty,0)) AS zjghckqty,
								abs(ISNULL(b.wxqjckqty,0)) AS wxqjckqty,
								abs(ISNULL(b.smwxckqty,0)) AS smwxckqty,			
								abs(ISNULL(b.sxckqty,0)) AS sxckqty,
								abs(ISNULL(b.bsqty,0)) AS bsqty,
								abs(ISNULL(b.wxdbdrqty,0)) AS wxdbdrqty,
								abs(ISNULL(b.wxdbdcqty,0)) AS wxdbdcqty,
								ISNULL(b.bqckQty,0) AS bqckQty,
								ISNULL(b.bqrkQty,0) AS bqrkQty
						FROM 	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') p,
								#ResultInOutStockTable b
			    		WHERE 	'+@Condition+'
								AND p.typeid=b.ptypeid						
					) AS a 
					LEFT JOIN #AllIniGoodsStocks i ON (a.typeid=i.ptypeid)
					LEFT JOIN #PreInOutStockTable c ON (a.typeid=c.ptypeid) 
					ORDER BY usercode
			
					SELECT * FROM #LastResultOne WHERE bqckQty<>0 OR bqrkQty<>0 ORDER BY UserCode '
					EXEC(@SQL)	
			END
	ELSE IF UPPER(@szFlag)='A'
		BEGIN	
			ListAllPtype:
			--------------------------显示所有商品-----------
			SELECT @Sql='
			SELECT 	a.*,
					ISNULL(c.preqty,0)+ISNULL(i.iniqty,0) AS sqcQty,
					ISNULL(c.preqty,0)+ISNULL(i.iniqty,0)+ISNULL(a.bqckQty,0)+ISNULL(a.bqrkQty,0) AS bqcQty
			FROM  (
					SELECT 	p.typeid,
							p.UserCode,
							p.fullname,
							p.EntryCode,
							p.Standard,
							p.Type,
							p.Area,
							p.Unit1,
							abs(ISNULL(b.wxdrqty,0)) AS wxdrqty,
							abs(ISNULL(b.jjrkqty,0)) AS jjrkqty,
							abs(ISNULL(b.zxwxrkqty,0)) AS zxwxrkqty,
							abs(ISNULL(b.smwxrkqty,0)) AS smwxrkqty,
							abs(ISNULL(b.sxfhrkqty,0)) AS sxfhrkqty,
							abs(ISNULL(b.byqty,0)) AS byqty,			
							abs(ISNULL(b.wxdcqty,0)) AS wxdcqty,
							abs(ISNULL(b.zxwxckqty,0)) AS zxwxckqty,
							abs(ISNULL(b.zjghckqty,0)) AS zjghckqty,
							abs(ISNULL(b.wxqjckqty,0)) AS wxqjckqty,
							abs(ISNULL(b.smwxckqty,0)) AS smwxckqty,			
							abs(ISNULL(b.sxckqty,0)) AS sxckqty,
							abs(ISNULL(b.bsqty,0)) AS bsqty,
							abs(ISNULL(b.wxdbdrqty,0)) AS wxdbdrqty,
							abs(ISNULL(b.wxdbdcqty,0)) AS wxdbdcqty,
							ISNULL(b.bqckQty,0) AS bqckQty,
							ISNULL(b.bqrkQty,0) AS bqrkQty
			  		FROM 	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') p LEFT JOIN #ResultInOutStockTable B ON b.ptypeid = p.typeid
			    	WHERE '+@Condition+'
				) AS a 
				LEFT JOIN #AllIniGoodsStocks i ON (a.typeid=i.ptypeid)
				LEFT JOIN #PreInOutStockTable c ON (a.typeid=c.ptypeid) 
			  	ORDER BY a.UserCode '
			
				--PRINT(@SQL)
				EXEC(@SQL)
			END
		ELSE 
			RETURN 0	

		DROP TABLE #ResultInOutStockTable,#SumInOutStockTable
	END
--***********************************************************************查询大类商品************************************************************************--
ELSE       
	BEGIN	
		--IF @szKTypeID<>''  SELECT @MKTypeID=@szKTypeID
		--IF @szPTypeID<>'' SELECT @MPTypeID=@szPTypeID
		
		DECLARE @TempSonnum INT  --判断传入的商品是否是具体商品,并做相应处理
		SELECT @TempSonnum = Sonnum FROM PType WHERE TypeID=@szPtypeId
		IF @TempSonnum = 0
		   SELECT @TempSonnum = 0
		ELSE
		   SELECT @TempSonnum = 5
	
		----InOutStockTable的精简
		CREATE TABLE #SumInOutStockTable1
		(
			BillType 		int,
			PTypeId			varchar(100),
			Qty				 NUMERIC(24, 10) 
		)
	
		DECLARE @XXX varchar(1000)
	
		
		SET @XXX = '
				INSERT INTO #SumInOutStockTable1 
				SELECT 	BillType,
						PTypeId,
						SUM(Qty) AS Qty
				FROM 	Wx_InOutStockTable
				WHERE  	Qty<>0
						AND Audited = 1
						AND KTypeId <> ''10000''					
						AND BillDate>='+char(39)+@BeginDate+char(39)+'
						AND BillDate<='+char(39)+@EndDate+char(39)+'
						AND ktypeid IN (SELECT * FROM #GetManSelKTypeId)
				  		AND ktypeid IN (SELECT * FROM #GetManKTypeId)
						AND ptypeid IN (SELECT * FROM #GetManPTypeId)
						AND ETypeId IN (SELECT * FROM #GetManSelETypeId)
						AND ETypeId IN (SELECT * FROM #GetManETypeId)
				GROUP BY PTypeId,BillType,Qty '
	
		EXEC(@XXX)	
	
		SELECT	SUBSTRING(PTypeId,1,LEN(@szPTypeId)+5) AS PTypeId,
				SUM(CASE billtype WHEN 165 THEN qty ELSE 0 END) AS [jjrkqty],
			    SUM(CASE billtype WHEN 166 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [zxwxrkqty],
				SUM(CASE billtype WHEN 166 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [zxwxckqty],
				SUM(CASE billtype WHEN 167 THEN qty ELSE 0 END) AS [wxqjckqty],
				SUM(CASE billtype WHEN 168 THEN qty ELSE 0 END) AS [zjghckqty],
				SUM(CASE billtype WHEN 169 THEN qty ELSE 0 END) AS [sxckqty],
				SUM(CASE billtype WHEN 170 THEN qty ELSE 0 END) AS [sxfhrkqty],
				SUM(CASE billtype WHEN 172 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [smwxrkqty],
				SUM(CASE billtype WHEN 172 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [smwxckqty],
				SUM(CASE billtype WHEN 173 THEN qty ELSE 0 END) AS [wxdrqty],
				SUM(CASE billtype WHEN 174 THEN qty ELSE 0 END) AS [wxdcqty],			    
			    SUM(CASE billtype WHEN 175 THEN (CASE WHEN qty>0 THEN qty ELSE 0 END) ELSE 0 END) AS [wxdbdrqty],
				SUM(CASE billtype WHEN 175 THEN (CASE WHEN qty<0 THEN qty ELSE 0 END) ELSE 0 END) AS [wxdbdcqty],
				SUM(CASE billtype WHEN 9 THEN qty ELSE 0 END) AS [bsqty],
				SUM(CASE billtype WHEN 14 THEN qty ELSE 0 END) AS [byqty],						
			    SUM(CASE WHEN qty<0 THEN qty ELSE 0 END) AS [bqckQty],
			    SUM(CASE WHEN qty>0 THEN qty ELSE 0 END) AS [bqrkQty]
		INTO 	#ResultInOutStockTable1
		FROM 	#SumInOutStockTable1 		
		GROUP BY SUBSTRING(PTypeId,1,LEN(@szPTypeId)+5)	
	
		-----IniGoodsStocks的精简
		SELECT 	ptypeid,
				ISNULL(SUM(qty),0) AS iniqty
		INTO 	#AllIniGoodsStocks1 
		FROM 	Wx_inigoodsstocks 
		WHERE 	ktypeid IN (SELECT * FROM #GetManSelKTypeId)
				AND ktypeid IN (SELECT * FROM #GetManKTypeId)
				AND ptypeid IN (SELECT * FROM #GetManPTypeId)
				AND Qty<>0 

		GROUP BY ptypeid
		
		-----日期以前的InOutStockTable的精简
		CREATE TABLE #PreInOutStockTable1
		(
			PTypeId		varchar(100),
			PreQty		 NUMERIC(24, 10) 
		)
	
		DECLARE @XXXX varchar(1000)
	
		SET @XXXX = '
			INSERT 	INTO #PreInOutStockTable1 
			SELECT 	ptypeid,
					ISNULL(SUM(qty),0) AS preqty
			FROM 	Wx_inoutstocktable 
			WHERE  	Qty <> 0
					AND Audited = 1
					AND KTypeId <> ''10000''				
					AND billdate<'+char(39)+@BeginDate+char(39)+'
					AND ktypeid IN (SELECT * FROM #GetManSelKTypeId)
					AND ktypeid IN (SELECT * FROM #GetManKTypeId)
					AND ptypeid IN (SELECT * FROM #GetManPTypeId)
					AND ETypeId IN (SELECT * FROM #GetManSelETypeId)
					AND ETypeId IN (SELECT * FROM #GetManETypeId)
					AND stypeid IN (SELECT typeid FROM #GetSelectSTypeId)
			GROUP BY ptypeid '
	
		EXEC(@XXXX)
	
		-----PType的精简
		SELECT 	typeid,
				fullname,
				usercode,
				sonnum,
				EntryCode,
				Standard,
				Type,
				Area,
				Unit1,
				SortID
		INTO 	#TempPType 
		FROM 	F_GetManPTypeAll(@OperatorID) 
		WHERE 	LEFT(typeid,len(typeid)-@TempSonnum)=@szPtypeId 				
				AND typeid<>'00000' and IsService=0  AND iscombinationproduct = 0
		----------------------------------------正式开始运算-----------------------------------------------------------------
		
		 SELECT	p.typeid,
				p.usercode,
				p.fullname,
				p.sonnum,
				p.EntryCode,
				p.Standard,
				p.Type,
				p.Area,
				p.Unit1,
				p.SortID,
				abs(ISNULL(SUM(b.wxdrqty),0)) AS wxdrqty,
				abs(ISNULL(SUM(b.jjrkqty),0)) AS jjrkqty,
				abs(ISNULL(SUM(b.zxwxrkqty),0)) AS zxwxrkqty,
				abs(ISNULL(SUM(b.smwxrkqty),0)) AS smwxrkqty,
				abs(ISNULL(SUM(b.sxfhrkqty),0)) AS sxfhrkqty,
				abs(ISNULL(SUM(b.byqty),0)) AS byqty,			
				abs(ISNULL(SUM(b.wxdcqty),0)) AS wxdcqty,
				abs(ISNULL(SUM(b.zxwxckqty),0)) AS zxwxckqty,
				abs(ISNULL(SUM(b.zjghckqty),0)) AS zjghckqty,
				abs(ISNULL(SUM(b.wxqjckqty),0)) AS wxqjckqty,
				abs(ISNULL(SUM(b.smwxckqty),0)) AS smwxckqty,			
				abs(ISNULL(SUM(b.sxckqty),0)) AS sxckqty,
				abs(ISNULL(SUM(b.bsqty),0)) AS bsqty,
				abs(ISNULL(SUM(b.wxdbdrqty),0)) AS wxdbdrqty,
				abs(ISNULL(SUM(b.wxdbdcqty),0)) AS wxdbdcqty,
				ISNULL(SUM(b.bqckQty),0) AS bqckQty,
				ISNULL(SUM(b.bqrkQty),0) AS bqrkQty
		INTO 	#LastResult1_0
		FROM 	#TempPType p
		LEFT JOIN #ResultInOutStockTable1 b ON b.ptypeid=p.typeid
		GROUP BY  
				p.typeid,
				p.usercode,
				p.fullname,
				p.sonnum,
				p.EntryCode,
				p.Standard,
				p.Type,
				p.Area,
				p.Unit1,
				p.SortID
	
		CREATE TABLE #TempResult
		(
			TypeId		varchar(200),
			PreQty		 NUMERIC(24, 10) ,
			iniqty		 NUMERIC(24, 10) 
		)

		INSERT INTO #TempResult
		SELECT	A.TypeId,
				ISNULL(SUM(B.PreQty),0) AS PreQty,
				ISNULL(SUM(B.iniqty),0) AS iniqty
		FROM	#TempPType A
		LEFT JOIN (
					SELECT	B.TypeId,
							ISNULL(SUM(B.PreQty),0) AS PreQty,
							ISNULL(SUM(B.iniqty),0) AS iniqty
					FROM	(
								SELECT	PTypeId AS TypeId,
										0 AS PreQty,
										0 AS PreTotal,
										ISNULL(SUM(iniqty),0) AS iniqty
								FROM	#AllIniGoodsStocks1
								GROUP BY PTypeId
								UNION ALL
								SELECT	PTypeId AS TypeId,
										ISNULL(SUM(preqty),0) AS PreQty,
										0 AS iniqty,
										0 AS iniTotal									
								FROM	#PreInOutStockTable1
								GROUP BY PTypeId
					)B GROUP BY B.TypeId
		)B ON (LEFT(B.TypeId,len(a.typeid))=a.typeid)
		GROUP BY A.TypeId


		SELECT 	b.*,
		      	(r.preqty+r.iniqty) AS sqcQty,
		      	(r.preqty+r.iniqty+b.bqckQty+b.bqrkQty) AS bqcQty
		FROM	#LastResult1_0 b,
				#TempResult r
		WHERE	r.typeid=b.typeid
		ORDER BY B.SortID

		DROP TABLE 	#LastResult1_0,#TempPType,#AllIniGoodsStocks1,#PreInOutStockTable1
END


DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManETypeId,#GetManSelETypeId,#GetManSelKTypeId,#GetSelectSTypeId







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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









/*
	作者：谢吉康
	日期：2009-10-27
	描述：维修库存明细表
*/

CREATE                  PROCEDURE Comm_Wx_StockChangeRep_Mx
( 
	@BeginDate		VARCHAR(25),
	@EndDate		VARCHAR(25),
	@AtypeId		VARCHAR(8000),
	@PtypeId		VARCHAR(8000),
	@BtypeId		VARCHAR(8000),
	@KtypeId		VARCHAR(8000),
	@EtypeId   		VARCHAR(8000),
	@cMode			VARCHAR(2),
	@PreQty			 NUMERIC(24, 10)  OUTPUT,
	@PreTotal		 NUMERIC(24, 10)  OUTPUT,
	@OrderBy		VARCHAR(25),
	@OperatorId     VARCHAR(100),       --操作员ID
	@showRedWord	char(1)='0',
	@intType        INT='',
	@stypeid		VARCHAR(8000)
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@EtypeId,3) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailEType(@OperatorID))

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT ks.typeid FROM F_GetManDetailKTypeSType(@OperatorID) ks
				INNER JOIN #GetSelectSTypeId ss ON ks.STypeId=ss.TypeId

--仓库：
CREATE TABLE #GetSelKTypeId(TypeId varchar(100))
INSERT INTO #GetSelKTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@KTypeId,4)

DECLARE @strQuery VARCHAR(1000)
SELECT @strQuery=' AND c.EtypeId IN (SELECT * FROM #GetManETypeId)'

IF @AtypeId='' SELECT @AtypeId='0'
IF @PtypeId='' SELECT @PtypeId='0'
IF @BtypeId='' SELECT @BtypeId='0'
IF @KtypeId='' SELECT @KtypeId='0'
DECLARE @GroupBy VARCHAR(2000)
DECLARE @cz_query VARCHAR(8000),@dbname VARCHAR(100)
DECLARE @TempTotal  NUMERIC(24, 10) ,@TempQty  NUMERIC(24, 10) 
DECLARE @Sql VARCHAR (8000)
DECLARE @GOODS_ID VARCHAR(100)
SELECT @GOODS_ID='0000100001' 
SELECT @dbname='Wx_inoutstocktable'

SELECT @cz_Query=''
IF (RTRIM(@begindate) <>'' AND RTRIM(@enddate) <>'')
 SELECT @cz_Query=@cz_query+' AND  a.billdate>='+CHAR(39)+@begindate+CHAR(39)+' AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)
IF RTRIM(@ptypeid)<>'0' AND RTRIM(@atypeid)=@GOODS_ID
	BEGIN
		SELECT @cz_query=@cz_query+'AND LEFT(c.ptypeid,len('+CHAR(39)+@ptypeid+CHAR(39)+'))='+CHAR(39)+@ptypeid+CHAR(39)+' and c.ptypeid in (select typeid from #GetManPTypeId) AND c.billnumberid=a.billnumberid'
		--SELECT @cz_query=@cz_query+' AND c.atypeid='+CHAR(39)+@GOODS_ID+CHAR(39)
		SELECT @cz_query=@cz_query+' AND a.ifcheck='+CHAR(39)+'t'+CHAR(39)
	END

IF RTRIM(@ktypeid) <>'0'
 	SET @cz_query=@cz_query+' AND c.ktypeid IN (SELECT * FROM #GetSelKTypeId) AND c.billnumberid=a.billnumberid'
IF RTRIM(@btypeid) <> '0' 
 	SET @cz_query=@cz_query+' AND LEFT(c.btypeid,len('+CHAR(39)+@btypeid+CHAR(39)+'))='+CHAR(39)+@btypeid+CHAR(39) +' AND c.billnumberid=a.billnumberid'
--IF RTRIM(@atypeid) <> '0' 
-- 	SET @cz_query=@cz_query+' AND LEFT(c.atypeid,len('+CHAR(39)+@atypeid+CHAR(39)+'))='+CHAR(39)+@atypeid+CHAR(39) +' AND c.billnumberid=a.billnumberid '
IF UPPER(@cMode)='S'
 	SET @cz_query=@cz_query+' AND (c.billtype=11 OR c.billtype=141 OR c.billtype=45 OR c.billtype=305) '

IF UPPER(@cMode)='B'
  	SET @cz_query=@cz_query+' (c.billtype=34 OR c.billtype=6 OR c.billtype = 145)'

--SET @cz_query=SUBSTRING(@cz_query,1,len(@cz_query)-4)
--  OrderBy  --
DECLARE @SQLOrder	VARCHAR(150)
SELECT @SQLOrder = ''

IF @OrderBy = 'ByDate_a'		--ORDER BY date
    SET @SQLOrder = ' ORDER BY c.billdate, c.billtype, c.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 	--ORDER BY Bill No.
    SET @SQLOrder = ' ORDER BY c.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	--ORDER BY Bill type
    SET @SQLOrder = ' ORDER BY c.billtype, c.billdate, c.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	--ORDER BY Bill ID
    SET @SQLOrder = ' ORDER BY c.posttime'
ELSE IF @OrderBy = 'ByDate_d'		--ORDER BY date DESC 
    SET @SQLOrder = ' ORDER BY c.billdate DESC, c.billtype, c.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	--ORDER BY Bill No. DESC 
    SET @SQLOrder = ' ORDER BY c.BillCode DESC'
ELSE IF @OrderBy = 'ByBillType_d'	--ORDER BY Bill type DESC 
    SET @SQLOrder = ' ORDER BY c.billtype DESC, c.billdate, c.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	--ORDER BY Bill ID DESC 
    SET @SQLOrder = ' ORDER BY c.posttime DESC'
ELSE
    SET @SQLOrder = ' ORDER BY c.billdate'


 SET @Sql ='SELECT	c.BillNumberId,
					c.BillDate,
					c.billtype,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.qty),0)	else  ISNULL(SUM(c.qty),0)	end as qty,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.Costtotal),0)	else  ISNULL(SUM(c.Costtotal),0)	end as Costtotal,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.total),0)	else  ISNULL(SUM(c.total),0)	end as total,
					ISNULL(c.CostPrice,0) AS CostPrice,
					a.BillCode, 
					a.Comment,
					a.RedWord, 
					CBillType= a.billtype,
					c.ptypeid as ptypeid,
					c.Ktypeid,
					c.atypeid,		        
          			a.btypeid,
					a.etypeid,
					a.stypeid,
					a.posttime
			FROM 	'+@dbname+' c,
					BillIndex a, 
					#GetSelectSTypeId ss
			WHERE  a.stypeid=ss.typeid '

IF UPPER(@cMode) <> 'S' AND UPPER(@cMode) <> 'B'
	SET @SQL = @SQL + ' AND  c.ktypeid<>'+CHAR(39)+'10000'+CHAR(39)+ ' AND c.KTypeID IN (SELECT * FROM #GetManKTypeId)  '

IF @showRedWord = '0'
	SET @SQL = @SQL + ' AND a.redword =0 '

SET @GroupBy ='  GROUP BY 
					c.BillNumberId,
					c.billdate,
					c.billtype,
					a.billtype,
					c.costprice,
					c.qty,
					a.billcode,
					a.comment,
					a.redword,
					c.ptypeid,
					c.ktypeid,
					c.atypeid,
					a.btypeid,
					a.etypeid,
					a.stypeid, '
					

IF @OrderBy = 'ByDate_a'
    SET @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode,a.posttime'
ELSE IF @OrderBy = 'ByBillNo_a' 
    SET @GroupBy = @GroupBy + ' a.BillCode,a.posttime'
ELSE IF @OrderBy = 'ByBillType_a'	
    SET @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode,a.posttime'
ELSE IF @OrderBy = 'ByBillID_a'	
    SET @GroupBy = @GroupBy + ' a.posttime'
ELSE IF @OrderBy = 'ByDate_d'		
    SET @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode,a.posttime'
ELSE IF @OrderBy = 'ByBillNo_d' 	
    SET @GroupBy = @GroupBy + ' a.BillCode,a.posttime'
ELSE IF @OrderBy = 'ByBillType_d'	
    SET @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode,a.posttime'
ELSE IF @OrderBy = 'ByBillID_d'	
    SET @GroupBy = @GroupBy + ' a.posttime'
ELSE
    SET @GroupBy = @GroupBy + ' c.billdate'

SET @SQL = @SQL + @cz_query +@strQuery+@GroupBy

SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS c ' + @SQLOrder + 
			  ' 
				--显示最终结果
				SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head
				
					  FROM #temp1 a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype

				
				DROP TABLE #temp1
			   '
			   PRINT @SQL
	EXEC (@SQL)


DROP TABLE #GetManETypeId,#GetManKTypeId,#GetSelKTypeId,#GetManPTypeId,#GetSelectSTypeId






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

Create Procedure CxGetPriceType
(
  @EtypeId varchar(50) = '',
  @ConditionStr varchar(8000) = ''
)
--@encode$--
AS
CREATE TABLE #PRICE(
PriceTypeId  INT IDENTITY,
PriceColumn  VARCHAR(50),
DisPlayName  VARCHAR(50)
 )
DECLARE @RetailPriceLimit  VARCHAR(10)    --零售价权限
DECLARE @PreSalePrice1Limit  VARCHAR(10)  --预设售价1权限
DECLARE @PreSalePrice2Limit  VARCHAR(10)  --预设售价2权限
DECLARE @PreSalePrice3Limit  VARCHAR(10)  --预设售价3权限
DECLARE @PreSalePrice4Limit  VARCHAR(10)  --预设售价4权限
DECLARE @PreSalePrice5Limit  VARCHAR(10)  --预设售价5权限
DECLARE @PreSalePrice6Limit  VARCHAR(10)  --预设售价6权限
DECLARE @PreSalePrice7Limit  VARCHAR(10)  --预设售价7权限
DECLARE @PreSalePrice8Limit  VARCHAR(10)  --预设售价8权限
DECLARE @PreSalePrice9Limit  VARCHAR(10)  --预设售价9权限
DECLARE @PreSalePrice10Limit  VARCHAR(10)  --预设售价10权限
DECLARE @TopSalePriceLimit  VARCHAR(10)   --最高价权限
DECLARE @LowSalePriceLimit  VARCHAR(10)   --最低价权限
DECLARE @Limit  VARCHAR(2000)
SELECT @Limit=lim FROM loginuser WHERE etypeid=@EtypeId
SET @RetailPriceLimit=SUBSTRING(@Limit,708,1)
SET @PreSalePrice1Limit=SUBSTRING(@Limit,219,1)
SET @PreSalePrice2Limit=SUBSTRING(@Limit,220,1)
SET @PreSalePrice3Limit=SUBSTRING(@Limit,221,1)
SET @PreSalePrice4Limit=SUBSTRING(@Limit,222,1)
SET @PreSalePrice5Limit=SUBSTRING(@Limit,697,1)
SET @PreSalePrice6Limit=SUBSTRING(@Limit,698,1)
SET @PreSalePrice7Limit=SUBSTRING(@Limit,699,1)
SET @PreSalePrice8Limit=SUBSTRING(@Limit,700,1)
SET @PreSalePrice9Limit=SUBSTRING(@Limit,701,1)
SET @PreSalePrice10Limit=SUBSTRING(@Limit,702,1)
SET @TopSalePriceLimit=SUBSTRING(@Limit,709,1)
SET @LowSalePriceLimit=SUBSTRING(@Limit,710,1)

DECLARE @SQL VARCHAR(MAX)
SET @SQL=''
IF @RetailPriceLimit='1' OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''RetailPrice'' AS PriceColumn,''默认价格类型'' AS DisPlayName'
IF @PreSalePrice1Limit='1' OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice1'' AS PriceColumn,''预设售价1'' AS DisPlayName '
IF @PreSalePrice2Limit='1' OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice2'' AS PriceColumn,''预设售价2'' AS DisPlayName '
IF @PreSalePrice3Limit='1' OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice3'' AS PriceColumn,''预设售价3'' AS DisPlayName'
IF @PreSalePrice4Limit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice4'' AS PriceColumn,''预设售价4'' AS DisPlayName '
IF @PreSalePrice5Limit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice5'' AS PriceColumn,''预设售价5'' AS DisPlayName'
IF @PreSalePrice6Limit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice6'' AS PriceColumn,''预设售价6'' AS DisPlayName '
IF @PreSalePrice7Limit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice7'' AS PriceColumn,''预设售价7'' AS DisPlayName '
IF @PreSalePrice8Limit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice8'' AS PriceColumn,''预设售价8'' AS DisPlayName '
IF @PreSalePrice9Limit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice9'' AS PriceColumn,''预设售价9'' AS DisPlayName'
IF @PreSalePrice10Limit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''PreSalePrice10'' AS PriceColumn,''预设售价10'' AS DisPlayName'
IF @TopSalePriceLimit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''TopSalePrice'' AS PriceColumn,''最高价'' AS DisPlayName'
IF @LowSalePriceLimit='1'OR @EtypeId='00001' SET @SQL+=' INSERT INTO #PRICE SELECT ''LowSalePrice'' AS PriceColumn,''最低价'' AS DisPlayName '
IF(@RetailPriceLimit+@PreSalePrice1Limit+@PreSalePrice2Limit+@PreSalePrice3Limit+ @PreSalePrice4Limit+@PreSalePrice5Limit+@PreSalePrice6Limit+@PreSalePrice7Limit+ @PreSalePrice8Limit+@PreSalePrice9Limit+@PreSalePrice10Limit+@TopSalePriceLimit+@LowSalePriceLimit)='0000000000000' OR @EtypeId<>'00001'
	SET @SQL+= ' INSERT INTO #PRICE SELECT '''' AS PriceColumn,'''' AS DisPlayName'

SET @SQL+= '  SELECT * FROM #PRICE'
--print @SQL
EXEC(@SQL)
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年9月5日
-- Description:	促销管理中查询预设价格
-- =============================================
CREATE PROCEDURE CXGetPtypePriceValue
(
	@PtypeId  VARCHAR(50),--商品ID
	@PriceType  VARCHAR(50),--预设价格字段名
	@Price     NUMERIC(24, 10)  output  --返回价格
)
--@encode$--
AS
BEGIN
DECLARE @SQL NVARCHAR(MAX)
SET @SQL='SELECT  @Price='+@PriceType+' FROM PType_Price WHERE PTypeID='''+@PtypeId+''''
EXECUTE sp_executesql @SQL,N'@Price  NUMERIC(24, 10)  OUTPUT',@Price OUTPUT
END
GO




SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_StockNumSyncInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Web_StockNumSyncInfo];
GO

/*
	作者:颜熙
	日期:2016-10-28
	描述:库存同步查询
*/
CREATE  PROCEDURE [dbo].[Web_StockNumSyncInfo]
    (
      @edUsercode VARCHAR(100) ,		--商品编码	
      @edfullname VARCHAR(500) ,		--商品编号
      @stockname VARCHAR(500) ,		--仓库名称
      @IsDif BIT  ,               --是否只显示差异
      @OperatorID VARCHAR(100) = '' 	-- 操作员ID
    )
    --WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN

        DECLARE @sql VARCHAR(MAX);
    --未开启货位
        IF NOT EXISTS ( SELECT TOP 1
                            1
                    FROM    dbo.Userconfig
                    WHERE   ConfigName = 'mngcargospace'
                            AND Value = 1 )
            BEGIN
                SET @sql = ' SELECT p.customitemfrom, gs.ItemID as freeitemid, p.typeid,pu.FullName as baseunitname,'''' as cargousercode,
            '''' as cargofullname, pu.FullName,SUM(GS.Qty) as validqty, 
			p.Pid as goods_erpid,'''' as position_erpid,s.Kid as whs_erpid,
			s.usercode as stockusercode,s.FullName as stockfullname, 
			p.UserCode as goodsusercode,p.FullName as goodsfullname,SUM(GS.Qty) as Qty, WQ.Qty as wdvalidqty,
			WQ.EnableNum as wdenvalidqty from GOODSSTOCKS_QTY as gs inner join stock as s on gs.KtypeId = s.typeId inner join ptype as p on gs.PtypeId = p.typeid inner join PType_Units pu on p.baseUnitId = pu.UnitsId LEFT JOIN WDGOODSSTOCKS_QTY WQ ON P.pid = WQ.Ptypeid and S.kid = WQ.KtypeID AND WQ.ItemID = gs.ItemID 
			INNER JOIN F_GetAllManagerBaseTypeId('''',1,'''+@OperatorID+''') F1 ON F1.TypeId = p.typeId
			INNER JOIN F_GetAllManagerBaseTypeId('''',4,'''+@OperatorID+''') F2 ON F2.TypeId = s.typeId
		';
                IF @stockname = ''
                    BEGIN
                        IF @IsDif = 1
                            BEGIN
                                SET @sql = @sql
                                    + ' WHERE p.WdSyncFlag=1 and s.WdSyncFlag = 1 and p.usercode like ''%'
                                    + @edUsercode
                                    + '%'' and p.fullname like ''%'
                                    + @edfullname
                                    + '%'' GROUP BY gs.PTypeID,gs.KTypeID,gs.CargoID,gs.ItemID,gs.Iscombined,p.customitemfrom,p.typeId,pu.FullName,P.Pid,S.Kid,S.UserCode,S.FullName,P.UserCode,P.FullName,WQ.Qty,WQ.EnableNum
			HAVING ISNULL(WQ.Qty,0) <>SUM(GS.QTY)';
						--SELECT @sql
                            END;
                        ELSE
                            SET @sql = @sql
                                + ' where p.WdSyncFlag=1 and s.WdSyncFlag = 1 and p.usercode like ''%'
                                + @edUsercode + '%'' and p.fullname like ''%'
                                + @edfullname
                                + '%'' GROUP BY gs.PTypeID,gs.KTypeID,gs.CargoID,gs.ItemID,gs.Iscombined,p.customitemfrom,p.typeId,pu.FullName,P.Pid,S.Kid,S.UserCode,S.FullName,P.UserCode,P.FullName,WQ.Qty,WQ.EnableNum';
                    END;
                ELSE
                    BEGIN
                        IF @IsDif = 1
                            SET @sql = @sql
                                + ' WHERE p.WdSyncFlag=1 and s.WdSyncFlag = 1 and p.usercode like ''%'
                                + @edUsercode + '%'' and p.fullname like ''%'
                                + @edfullname + '%'' and s.fullname ='''
                                + @stockname + ''''
                                + ' GROUP BY gs.PTypeID,gs.KTypeID,gs.CargoID,gs.ItemID,gs.Iscombined,p.customitemfrom,p.typeId,pu.FullName,P.Pid,S.Kid,S.UserCode,S.FullName,P.UserCode,P.FullName,WQ.Qty,WQ.EnableNum
			HAVING ISNULL(WQ.Qty,0) <>SUM(GS.QTY)';
                        ELSE
                            SET @sql = @sql
                                + ' WHERE p.WdSyncFlag=1 and s.WdSyncFlag = 1 and p.usercode like ''%'
                                + @edUsercode + '%'' and p.fullname like ''%'
                                + @edfullname + '%'' and s.fullname ='''
                                + @stockname
                                + ''' GROUP BY gs.PTypeID,gs.KTypeID,gs.CargoID,gs.ItemID,gs.Iscombined,p.customitemfrom,p.typeId,pu.FullName,P.Pid,S.Kid,S.UserCode,S.FullName,P.UserCode,P.FullName,WQ.Qty,WQ.EnableNum';
                    END;
            END;
        ELSE
            BEGIN
                SET @sql = 'SELECT p.customitemfrom,GQ.ItemID as freeitemid, p.typeid,pu.FullName as baseunitname,CT.UserCode as cargousercode,
            ct.FullName as cargofullname, pu.FullName,SUM(GQ.Qty) as validqty,  
			p.Pid as goods_erpid,CT.CargoID as position_erpid,s.Kid as whs_erpid,
			s.usercode as stockusercode,s.FullName as stockfullname, 
			p.UserCode as goodsusercode,p.FullName as goodsfullname,SUM(GQ.Qty),WQ.Qty as wdvalidqty,
			WQ.EnableNum as wdenvalidqty FROM GOODSSTOCKS_QTY AS GQ INNER JOIN PType AS P ON GQ.PTypeID = P.typeId 
			INNER JOIN STOCK AS S ON GQ.KTypeID = S.typeId  INNER JOIN CargoType CT ON  GQ.CargoID = CT.CargoID 
			inner join  PType_Units pu on p.baseUnitId = pu.UnitsId LEFT JOIN WDGOODSSTOCKS_QTY WQ ON P.pid = WQ.Ptypeid 
			and S.Kid = WQ.KtypeID and CT.CargoID=WQ.CargoID and WQ.ItemID = GQ.ItemID 
			INNER JOIN F_GetAllManagerBaseTypeId('''',1,'''+@OperatorID+''') F1 ON F1.TypeId = p.typeId
			INNER JOIN F_GetAllManagerBaseTypeId('''',4,'''+@OperatorID+''') F2 ON F2.TypeId = s.typeId';
                IF @stockname = ''
                    BEGIN
                        IF @IsDif = 1
                            BEGIN
                                SET @sql = @sql
                                    + ' WHERE p.WdSyncFlag=1 and s.WdSyncFlag = 1 and p.usercode like ''%'
                                    + @edUsercode
                                    + '%'' and p.fullname like ''%'
                                    + @edfullname + '%'''
                                    + ' GROUP BY GQ.PTypeID,GQ.KTypeID,GQ.CargoID,GQ.ItemID,GQ.Iscombined,p.customitemfrom,p.typeId,pu.FullName,P.Pid,S.Kid,S.UserCode,S.FullName,P.UserCode,P.FullName,WQ.Qty,WQ.EnableNum,CT.UserCode,CT.FullName,CT.CargoID
			HAVING ISNULL(WQ.Qty,0) <>SUM(GQ.QTY)';
							--SELECT @sql
                            END;
                        ELSE
                            BEGIN
                                SET @sql = @sql
                                    + ' WHERE p.WdSyncFlag=1 and s.WdSyncFlag = 1 and p.usercode like ''%'
                                    + @edUsercode
                                    + '%'' and p.fullname like ''%'
                                    + @edfullname
                                    + '%'' GROUP BY GQ.PTypeID,GQ.KTypeID,GQ.CargoID,GQ.ItemID,GQ.Iscombined,p.customitemfrom,p.typeId,pu.FullName,P.Pid,S.Kid,S.UserCode,S.FullName,P.UserCode,P.FullName,WQ.Qty,WQ.EnableNum,CT.UserCode,CT.FullName,CT.CargoID
			';
                            END;
	   
                    END;
                ELSE
                    BEGIN
                        IF @IsDif = 1
                            SET @sql = @sql
                                + ' WHERE p.WdSyncFlag=1 and s.WdSyncFlag = 1 and p.usercode like ''%'
                                + @edUsercode + '%'' and p.fullname like ''%'
                                + @edfullname + '%'' and s.fullname ='''
                                + @stockname + ''''
                                + ' GROUP BY GQ.PTypeID,GQ.KTypeID,GQ.CargoID,GQ.ItemID,GQ.Iscombined,p.customitemfrom,p.typeId,pu.FullName,P.Pid,S.Kid,S.UserCode,S.FullName,P.UserCode,P.FullName,WQ.Qty,WQ.EnableNum,CT.UserCode,CT.FullName,CT.CargoID
			HAVING ISNULL(WQ.Qty,0) <>SUM(GQ.QTY)';
                        ELSE
                            SET @sql = @sql
                                + ' WHERE p.WdSyncFlag=1 and s.WdSyncFlag = 1 and p.usercode like ''%'
                                + @edUsercode + '%'' and p.fullname like ''%'
                                + @edfullname + '%'' and s.fullname ='''
                                + @stockname
                                + '''GROUP BY GQ.PTypeID,GQ.KTypeID,GQ.CargoID,GQ.ItemID,GQ.Iscombined,p.customitemfrom,p.typeId,pu.FullName,P.Pid,S.Kid,S.UserCode,S.FullName,P.UserCode,P.FullName,WQ.Qty,WQ.EnableNum,CT.UserCode,CT.FullName,CT.CargoID';
                    END;
            END;
         
        --PRINT @sql
		--EXEC(@Sql)
		--SELECT @sql
        
        CREATE TABLE #tempInventory
            (
              customitemfrom INT ,
              freeitemid INT ,
              typeid VARCHAR(50) ,
              baseunitname VARCHAR(500) ,
              cargousercode VARCHAR(50) ,
              cargofullname VARCHAR(500) ,
              fullname VARCHAR(500) ,
              validqty NUMERIC(24, 10) ,
              goods_erpid INT ,
              position_erpid INT ,
              whs_erpid INT ,
              stockusercode VARCHAR(50) ,
              stockfullname VARCHAR(500) ,
              goodsusercode VARCHAR(50) ,
              goodsfullname VARCHAR(500) ,
              Qty NUMERIC(24, 10) ,
              wdvalidqty NUMERIC(24, 10) ,
              wdenvalidqty NUMERIC(24, 10)
            );
        INSERT  INTO #tempInventory
                EXEC ( @Sql
                    );
		--SELECT * FROM #tempInventory
					
        SELECT  '' AS freeitem ,
                *
        FROM    #tempInventory
        WHERE   customitemfrom IS NULL
        UNION ALL
        SELECT  c.Fullname AS freeitem ,
                T.*
        FROM    #tempInventory T
                INNER JOIN CustomReferenceValue AS c ON c.id = T.freeitemid
        WHERE   customitemfrom = 1
        UNION ALL
        SELECT  c.FullName AS freeitem ,
                T.*
        FROM    #tempInventory T
                INNER JOIN xw_SelfData AS c ON c._Id = T.freeitemid
        WHERE   customitemfrom = 0;
		
        DROP TABLE #tempInventory; 
			
    END;
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2017-11-17
	描述:保存或者修改商品品牌
*/
CREATE PROCEDURE Deal_BrandarCommondity
(
	@typeId			    VARCHAR(100),
	@UserCode			VARCHAR(200),
	@FullName			VARCHAR(200),
	@Parid      		VARCHAR(200), 
	@Leveal             INT,
	@Comment			VARCHAR(500),
	@optype				VARCHAR(10)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @oldparid					VARCHAR(100),
		@oldtypeid					VARCHAR(100),
		@oldlevel					int,
		@nReturntype				INT,
		@brandartypeId_new			VARCHAR(100),
		@nSoncount					INT,
		@nSonnum					INT,
		@dbname						VARCHAR(30),
		@pSoncount					INT,
		@pSonnum					INT,
		@newleveal					INT,
		@maxXiWa					INT
		
SELECT @maxXiWa = MAX(XiWaMaxNumber)+1 FROM brandar_Commodity	

--处理默认品牌
IF EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE typeid = @typeId AND Issys = 1)
BEGIN
	--默认品牌不允许分类
	IF @Parid <> '00000'
	BEGIN
		RAISERROR('系统默认品牌不允许分类，请修改后再保存。',16,1) 
		RETURN	
	END
END
ELSE
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE TypeId = @ParId AND Issys = 1) 
		AND @Parid <> '00000'
	BEGIN
		RAISERROR('系统默认品牌不允许重新归类，请修改后再保存。',16,1) 
		RETURN	
	END
	ELSE
	BEGIN
		--父类被使用则不能分类了
		IF @Parid <> ''
		BEGIN
			DECLARE @Re			INT,
					@errMsg		VARCHAR(500)
			EXEC @Re = Web_BrandarCommondityCanDel @Parid,@errMsg OUTPUT
			IF @Re <> 0
			BEGIN
				RAISERROR('所属品牌已经被使用，不能分类，请修改后再保存。',16,1) 
				RETURN
			END
		END	
	END
END	


IF @optype = 'm' ---修改
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM brandar_Commodity WHERE FullName = @FullName AND typeId <> @typeId)
	BEGIN
		RAISERROR('名称已存在，请修改后再保存。',16,1) 
		RETURN
	END
	ELSE IF EXISTS(SELECT TOP 1 1 FROM brandar_Commodity WHERE UserCode = @usercode AND typeId <> @typeId)
	BEGIN
		RAISERROR('编号已存在，请修改后再保存。',16,1) 
		RETURN
	END
	ELSE
	BEGIN							
		--获取原来父类ID,旧typeid
		select @oldparid=parid,@oldlevel=Leveal from brandar_Commodity where typeId = @typeId 		
		set @oldtypeid=@typeId
		
		--判断是否使用，使用了就不能修改父节点了
		IF @oldparid <> @Parid
		BEGIN
			DECLARE @Rex		INT,
					@errMsgx	VARCHAR(500)

			EXEC @Rex = Web_BrandarCommondityCanDel @TypeId,@errMsgx OUTPUT
			
			IF @Rex <> 0
			BEGIN
				RAISERROR(@errMsgx,16,1) 
				RETURN
			END
		END		
		
		--获取总的soncount  sonum,createid 要改动 ，等下还原
		select @pSoncount=soncount from brandar_Commodity where typeId = '00000' 
		
		if @Parid=''
			set @Parid='00000'
				
		IF @Parid<>@oldparid
		BEGIN
			-- 获得新的ID号
			SET @dbname='brandar_Commodity'
			
			EXEC @nReturntype= Gp_createId @Parid, @dbname, @brandartypeId_new OUT,@nSonnum OUT, @nSoncount OUT
			
			IF @nReturntype=-1
			BEGIN 
				RAISERROR('商品品牌的分类不能超过10层',16,1) 
				RETURN
			END
			 
			IF @nReturntype=-2 
			BEGIN
				RAISERROR('无法添加品牌类别',16,1)
				RETURN
			END
			
			--判断是否超过10层
			IF EXISTS(SELECT TOP 1 1 FROM brandar_Commodity WHERE LEN(stuff(typeid,1,len(@typeId),@brandartypeId_new))>50 AND typeid like @typeId+'%')
			BEGIN
				RAISERROR('商品品牌的分类不能超过10层',16,1) 
				RETURN
			END
			
			--获取新父类level	
			select @newleveal=isnull(Leveal,0) from brandar_Commodity where typeId = @Parid
			
			--level 变化幅度,用于更改子类leval
			declare @levelcreasement int
			set @levelcreasement=@newleveal-@oldlevel+1			
			
			--更新当前typeid 到新的id
			UPDATE	brandar_Commodity
			SET		FullName = @FullName,
					Comment = @Comment,
					UserCode=@UserCode,
					Leveal=@newleveal+1 ,
					parid=@Parid,
					typeId=@brandartypeId_new,
					XiWaMaxNumber = @maxXiWa
			WHERE	typeId = @typeId
			
			--更新所有子类ID			
			update brandar_Commodity set typeid=stuff(typeid,1,len(@typeId),@brandartypeId_new),parid=stuff(parid,1,len(@typeId),@brandartypeId_new),Leveal=Leveal+@levelcreasement where typeid like @typeId+'%'
			
			--更新原父类 soncount,sonnum -1
			UPDATE brandar_Commodity SET soncount=soncount-1,sonnum=sonnum-1 WHERE typeId = @oldparid and @oldparid<>'00000'
			
			--更新新父类 soncount,sonnum +1
			UPDATE brandar_Commodity SET soncount=soncount+1,sonnum=sonnum+1 WHERE typeId = @Parid
			
			--更新商品档案引用的ptypebrandarid,子类ptypebrandarid
			update ptype set brandartypeid=stuff(brandartypeid,1,len(@typeId),@brandartypeId_new) where brandartypeid like @typeId+'%'
			
			--还原SONNUM,SONCOUNT 总数没有变
			select @pSonnum=count(*) from brandar_Commodity where parid='00000'
			update brandar_Commodity set soncount =@pSoncount,sonnum=@pSonnum where typeId = '00000'  	
			
			--修改明细值，相当于做了数据搬移
			UPDATE dbo.AdDebtBill SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId
			UPDATE dbo.BillMulBrand SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId
			UPDATE dbo.Brandar_ArApTotal SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId			
			UPDATE dbo.CompleteBrandarTotal SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId				
			UPDATE dbo.gatheringBill SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId			
			UPDATE dbo.ImportMoneyBillTemp SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId		
			UPDATE dbo.MoneyBill SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId		
			UPDATE dbo.PreBill SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId				
			UPDATE dbo.AccountCredence SET BrandarTypeId = @brandartypeId_new WHERE BrandarTypeId = @typeId		
		END
		ELSE --未更换父类
		BEGIN
			UPDATE	brandar_Commodity
			SET		FullName = @FullName,
					Comment = @Comment,
					UserCode=@UserCode,
					XiWaMaxNumber = @maxXiWa
			WHERE	typeId = @typeId
		END		
	END
END 

IF @optype = 'a'---新增
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM brandar_Commodity WHERE UserCode = @UserCode)
	BEGIN
		RAISERROR('编号已存在，请修改后再保存。',16,1) 
		RETURN
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM brandar_Commodity WHERE FullName = @FullName)
	BEGIN
		RAISERROR('名称已存在，请修改后再保存。',16,1)
		RETURN
	END 
	
	if @Parid=''
		set @Parid='00000'
		 
	-- 获得新的ID号
	SET @dbname='brandar_Commodity'
	
	EXEC @nReturntype= Gp_createId @Parid, @dbname, @brandartypeId_new OUT,
	@nSonnum OUT, @nSoncount OUT
	
	 IF @nReturntype=-1
	 begin 
		RAISERROR('商品品牌的分类不能超过10层',16,1)return--return -1
	 end
	 
	IF @nReturntype=-2 
	begin
		RAISERROR('无法添加品牌类别',16,1)return--return -2
	end
	
	--获取新父类level
	select @newleveal=isnull(Leveal,0) from brandar_Commodity where typeId = @Parid
	
	INSERT INTO brandar_Commodity
	(
		typeId,
		parid,
		soncount,
		sonnum,
		leveal,
		UserCode,
		FullName,
		Comment,
		XiWaMaxNumber
	)VALUES(
		@brandartypeId_new,	
		@Parid,
	    0,
	    0,
		@newleveal+1,
		@UserCode,
		@FullName,
		@Comment,
		@maxXiWa	
	)
	
	UPDATE  brandar_Commodity
	SET     sonnum = @nSonnum + 1,
			soncount = @nSoncount + 1
	WHERE   typeid = @ParId
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


 



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE DeleteAllPriceBaseDataById
(
	@pricebillindexid		varchar(50)     ='',
	@dets                   varchar(max)     =''
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL varchar(max)

CREATE TABLE #PriceDetailID(ID NUMERIC(18,0))
INSERT #PriceDetailID SELECT * FROM DBO.f_split(@dets,',')
CREATE TABLE #PriceBillindexID(ID NUMERIC(18,0))
INSERT #PriceBillindexID(ID) SELECT * FROM dbo.f_split(@pricebillindexid,',')

BEGIN TRANSACTION Oper

DELETE PriceDetail WHERE ID IN (SELECT ID FROM #PriceDetailID)

CREATE TABLE #DeleteID(ID NUMERIC(18,0))
	INSERT #DeleteID(ID)
	SELECT ID FROM #PriceBillindexID WHERE ID NOT IN(SELECT PriceBillIndexID FROM PriceDetail UNION ALL SELECT PriceBillIndexID FROM PriceDetailDeleted)
	
	CREATE TABLE #UserdPriceBillIndex(ID NUMERIC(18,0), FullName VARCHAR(200))
	INSERT INTO #UserdPriceBillIndex(ID,FullName)
	SELECT P.ID,pb.FullName FROM #DeleteID P INNER JOIN PriceRule R ON R.PriceBillIndexID = P.ID
	INNER JOIN PriceBillIndex pb ON pb.ID=p.ID
	IF EXISTS(SELECT TOP 1 1 FROM #UserdPriceBillIndex)
	BEGIN
		DECLARE @Result VARCHAR(MAX) = ''
		SELECT @Result=FullName+',' FROM #UserdPriceBillIndex
		SET @Result = SUBSTRING(@Result,1,LEN(@Result) - 1)
		DECLARE @MSG VARCHAR(MAX)='价格表【'+@Result+'】已被取价规则调用，不能将所有明细清除！'
		RAISERROR(@MSG,16,1)
		
		ROLLBACK TRANSACTION
		RETURN
	END

	DELETE PriceBillIndex WHERE ID IN (SELECT ID FROM #DeleteID)
	DELETE PriceBillIndex_Stype WHERE PriceBillIndexID IN (SELECT ID FROM #DeleteID)
	DELETE PriceDetailDeleted WHERE PriceBillIndexID IN (SELECT ID FROM #DeleteID)
	
	DROP TABLE #DeleteID,#UserdPriceBillIndex
	
IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION
	RETURN
END

COMMIT TRANSACTION  Oper


Set @SQL='
 --先删除子表
 DELETE FROM PriceDetail WHERE PriceBillIndexID='+@pricebillindexid+' and ID in (' + @dets + ')
 DELETE FROM PriceDetailDeleted WHERE PriceBillIndexID='+@pricebillindexid+' and ID in (' + @dets + ')
 --DELETE FROM PriceBillIndex_Stype WHERE PriceBillIndexID=@pricebillindexid
 --再删除主表
 --DELETE FROM PriceBillIndex WHERE ID=@pricebillindexid
 
BEGIN TRANSACTION Oper

DELETE PriceDetail WHERE ID IN (SELECT ID FROM #PriceDetailID)

 
 
if not exists (select PriceBillIndexID from  PriceDetail where PriceBillIndexID='+@pricebillindexid+' and ID in (' + @dets + ') union all select PriceBillIndexID from PriceDetailDeleted where PriceBillIndexID='+@pricebillindexid+' and ID in (' + @dets + ') )
BEGIN
DELETE FROM PriceBillIndex_Stype WHERE PriceBillIndexID='+@pricebillindexid+'
DELETE FROM PriceBillIndex WHERE ID='+@pricebillindexid+'
END
ELSE 
BEGIN
UPDATE PriceBillIndex SET [State]=3 WHERE ID='+@pricebillindexid+'
END
 
 
 '
--exec (@SQL)


 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE DeleteAllPromotionData
(
	@promotionid		varchar(500)     =''		
)
--@encode$--
AS
SET NOCOUNT ON 

--先删除子表在删除
DELETE FROM PromoRule_Detail_EConfig WHERE PromoRuleID=@promotionid
DELETE FROM PromoRule_Detail_KConfig WHERE PromoRuleID=@promotionid
DELETE FROM PromoRule_Detail_PConfig WHERE PromoRuleID=@promotionid
DELETE FROM PromoRule_Detail_PromotConfig WHERE PromoRuleID=@promotionid
DELETE FROM PromoRule_Detail_StoresConfig WHERE PromoRuleID=@promotionid
DELETE FROM PromoRule_Detail_VIPConfig WHERE PromoRuleID=@promotionid
DELETE FROM PromoRule_Stype WHERE PromoRuleID=@promotionid
--再删除主表 
DELETE FROM PromoRule WHERE ID=@promotionid



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则删除
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE DeletePriceRule
(
	@deletestate	int	output,
	@billindex varchar(max)
	
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN TRANSACTION
delete PriceRule_Detail_BConfig where PriceRuleID=@billindex
  delete PriceRule_Detail_DConfig where PriceRuleID=@billindex
  delete PriceRule_Detail_EConfig where PriceRuleID=@billindex
  delete PriceRule_Detail_KConfig where PriceRuleID=@billindex
  delete PriceRule_Detail_StoresConfig where PriceRuleID=@billindex
  delete PriceRule_Stype where PriceRuleID=@billindex
  delete PriceRule where PriceRule.ID=@billindex 
  delete PriceRulePriority where PriceRuleID=@billindex
  
IF @@error <> 0  --发生错误
   BEGIN
   set @deletestate=0
     ROLLBACK TRANSACTION
   END
ELSE
   BEGIN
     COMMIT TRANSACTION
     set   @deletestate=1
   END  
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[DeleteWdOrder]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[DeleteWdOrder];
GO

/*
	作者:颜熙
	日期:2016-12-14
	描述:批量删除
*/
CREATE  PROCEDURE DeleteWdOrder 
( 
	@wdbillnumber VARCHAR(MAX) --网店订单id
)
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
    BEGIN TRANSACTION
    DECLARE @error INT=0
    --SET @wdbillnumber = ''+@wdbillnumber+''
    --SELECT @wdbillnumber
    SELECT * INTO #tempOrder FROM (SELECT Billnumberid FROM dbo.WdShopBillRelation WHERE WdShopBillID in  (SELECT * FROM dbo.f_split(@wdbillnumber,',') billnumerid)  AND WdSyncFlag = 0 ) AS t
    DECLARE @count INT ,@count2 INT 
    SELECT @count =COUNT(*) FROM #tempOrder
    SELECT @count2 = COUNT(*) FROM (SELECT * FROM dbo.f_split(@wdbillnumber,',') WHERE a NOT IN (SELECT WdShopBillID FROM  dbo.WdShopBillRelation)) b 
    IF(@count=0 AND @count2 = 0)
    RAISERROR('该单据已过账，请勿删除！',16,1)
    
    DELETE FROM dbo.SaleBill  WHERE BillNumberId IN (SELECT * FROM #tempOrder) AND BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BillIndex WHERE draft = 0)
	SET @error=@error+@@ERROR
	DELETE FROM dbo.BillIndex WHERE BillNumberId IN (SELECT * from #tempOrder) AND draft = 1
	SET @error=@error+@@ERROR
	DELETE FROM dbo.WdOrder WHERE wdbillnumber IN(SELECT * FROM dbo.f_split(@wdbillnumber,',')) AND wdbillnumber NOT IN (SELECT WdShopBillID FROM dbo.WdShopBillRelation WHERE WdSyncFlag = 1)
	SET @error=@error+@@ERROR
    DELETE FROM dbo.WdOrderBody WHERE ordercode IN (SELECT * FROM dbo.f_split(@wdbillnumber,',')) AND ordercode NOT IN (SELECT WdShopBillID FROM dbo.WdShopBillRelation WHERE WdSyncFlag = 1)
	SET @error=@error+@@ERROR
	DELETE FROM dbo.WdCargoDetail WHERE ordercode IN (SELECT * FROM dbo.f_split(@wdbillnumber,',')) AND ordercode NOT IN (SELECT WdShopBillID FROM dbo.WdShopBillRelation WHERE WdSyncFlag = 1)
	SET @error=@error+@@ERROR
	DELETE FROM dbo.WdSerialsDetail WHERE ordercode IN (SELECT * FROM dbo.f_split(@wdbillnumber,',')) AND ordercode NOT IN (SELECT WdShopBillID FROM dbo.WdShopBillRelation WHERE WdSyncFlag = 1)
	SET @error=@error+@@ERROR
	DELETE FROM dbo.WdAccountDetail WHERE ordercode IN (SELECT * FROM dbo.f_split(@wdbillnumber,',')) AND ordercode NOT IN (SELECT WdShopBillID FROM dbo.WdShopBillRelation WHERE WdSyncFlag = 1)
	SET @error=@error+@@ERROR
	DELETE FROM dbo.WdItemsDetail WHERE ordercode IN (SELECT * FROM dbo.f_split(@wdbillnumber,',')) AND ordercode NOT IN (SELECT WdShopBillID FROM dbo.WdShopBillRelation WHERE WdSyncFlag = 1)
	SET @error=@error+@@ERROR
	--DELETE FROM dbo.WdShopBillRelation WHERE WdShopBillID IN (SELECT * FROM dbo.f_split(@wdbillnumber,',')) AND BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BillIndex WHERE draft = 0)
	DELETE FROM dbo.WdShopBillRelation WHERE Billnumberid IN (SELECT * FROM #tempOrder) AND BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BillIndex WHERE draft = 0)
	SET @error=@error+@@ERROR
	IF @error=0
		BEGIN
			COMMIT TRANSACTION
			RETURN 0
		END 
	ELSE
		BEGIN
		 ROLLBACK TRANSACTION
		 RETURN -1
		END
			
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇
	日期：2014-05-14
	描述：删除职员
*/
CREATE PROCEDURE DelEtypeCommissionType
(
	@etypeid					VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON
--IF EXISTS(SELECT * FROM CommissionRuleEtype WHERE EtypeID=@etypeid)
--	  BEGIN
--		   RAISERROR ('当前职员已被提成规则使用！',16,1) 
--		   RETURN;
--	  END
--IF EXISTS(SELECT * FROM ReferencePlanCommissionEtype WHERE EtypeID=@etypeid)
--	  BEGIN
--		   RAISERROR ('当前职员已被参照计划提成使用！',16,1) 
--		   RETURN;
--	  END 需求不要求判断了。
	  DELETE EtypeCommissionType WHERE ETypeID=@etypeid
	  
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：陈强
	日期：2020-01-07
	描述：批量删除门店配送类单据草稿
*/
CREATE    PROCEDURE DelPosAllotApplyBill
(
	@nBillIds	varchar(8000)
)
AS
SET NOCOUNT ON


--删除附件
DELETE 
FROM	BillAttachFiles 
WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		AND Billtype IN (327,328)

--删除附件日志
DELETE 
FROM	BillAttachFilesLog 
WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		AND Billtype IN (327,328)


--删除单据操作日志
DELETE 
FROM	BillOperateLog 
WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))		
		AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		AND Billtype IN (327,328)
		

		
--最后执行这步
DELETE 
FROM	PosAllotApplyBillIndex 
WHERE	IfCheck = 'f' 
		AND Draft = 1 
		AND BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		AND Billtype IN (327,328)
				
IF @@ROWCOUNT = 0
	RETURN -2
ELSE
	RETURN 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇
	日期：2014-05-14
	描述：修改职员业务类别
*/
CREATE PROCEDURE EditEtypeCommissionType
(
	@etypeid					VARCHAR(200),
	@commissiontypeid           VARCHAR(200)
)
--@encode$--
AS
SET NOCOUNT ON
--IF EXISTS(SELECT * FROM CommissionRuleEtype WHERE EtypeID=@etypeid)
--	  BEGIN
--		   RAISERROR ('当前职员已被提成规则使用！',16,1) 
--		   RETURN;
--	  END
--IF EXISTS(SELECT * FROM ReferencePlanCommissionEtype WHERE EtypeID=@etypeid)
--	  BEGIN
--		   RAISERROR ('当前职员已被参照计划提成使用！',16,1) 
--		   RETURN;
--	  END
	  UPDATE EtypeCommissionType SET CommissionTypeID=@commissiontypeid WHERE ETypeID=@etypeid
	  
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇
	日期：2015-03-24
	描述：修改操作员的Mac和硬盘号
*/
CREATE PROCEDURE EditEtypeMacAndIP
(
	
	@etypeid			VARCHAR(200),--需要修改的操作员
	@macaddress			VARCHAR(200),--mac地址
	@harddiskno			VARCHAR(200), --硬盘号
	@validatelogin      INT
)
--@encode$--
AS
SET NOCOUNT ON


/*CREATE TABLE #tem(
    etypeid			    VARCHAR(200),--需要修改的操作员
	macaddress			VARCHAR(max),--mac地址
	harddiskno			VARCHAR(max) --硬盘号
)
  DELETE  EtypeMacAndIP  WHERE etypeid=@etypeid --删除表里原来的数据
  UPDATE dbo.loginuser SET ValidateLogin=@validatelogin WHERE etypeid=@etypeid
INSERT INTO #tem
   SELECT @etypeid ,@macaddress,@harddiskno --先把这个用分号分割的数据放入临时表
  ---再把一个临时表里的分号数据给处理成一个表的形式，最后再插入。
 ; WITH    cte
          AS ( SELECT   MacAddress = CAST(LEFT(MacAddress,
                                               CHARINDEX(';', MacAddress + ';')
                                               - 1) AS NVARCHAR(100)) ,
                        Split = CAST(STUFF(MacAddress + ';', 1,
                                           CHARINDEX(';', MacAddress + ';'),
                                           '') AS NVARCHAR(100)) ,
                        HardDiskNo = CAST(LEFT(HardDiskNo,
                                               CHARINDEX(';', HardDiskNo + ';')
                                               - 1) AS NVARCHAR(100)) ,
                        Split1 = CAST(STUFF(HardDiskNo + ';', 1,
                                            CHARINDEX(';', HardDiskNo + ';'),
                                            '') AS NVARCHAR(100)),
                         a.etypeid                   
               FROM     dbo.#tem a
               UNION ALL
               SELECT   MacAddress = CAST(LEFT(Split,
                                               CHARINDEX(';', Split) - 1) AS NVARCHAR(100)) ,
                        Split = CAST(STUFF(Split, 1, CHARINDEX(';', Split), '') AS NVARCHAR(100)) ,
                        HardDiskNo = CAST(LEFT(Split1,
                                               CHARINDEX(';', Split1) - 1) AS NVARCHAR(100)) ,
                        Split1 = CAST(STUFF(Split1, 1, CHARINDEX(';', Split1),
                                            '') AS NVARCHAR(100)),
                           etypeid                 
               FROM     cte
               WHERE    split1 > ''
                        AND split > ''
             )
    

   INSERT INTO  EtypeMacAndIP  SELECT  etypeid, macaddress ,
            harddiskno  FROM cte*/
            
    UPDATE dbo.loginuser SET ValidateLogin=@validatelogin WHERE etypeid=@etypeid
    
     INSERT INTO  EtypeMacAndIP(  etypeid, macaddress ,harddiskno) values(@etypeid,@macaddress,@harddiskno) 
     EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_Get_AscidsItem]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_Get_AscidsItem]
GO


/*
	用途：将科目的辅助核算项在Ac_Assist_CheckItems中的Ascids组合用于比对
*/

CREATE  FUNCTION F_Get_AscidsItem
(
	@stypeid	VARCHAR(50),
	@atypeid	VARCHAR(50)
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(MAX)
	SET @sql = ''
	SELECT @sql=@sql+ CAST(ascids AS VARCHAR(50)) + ',' FROM 
		(
		SELECT DISTINCT b.AscIds
		FROM dbo.Ac_Account a
		INNER JOIN dbo.Ac_Account_Assist_CheckItems b ON a.TypeId = b.ATypeId AND a.StypeId = b.STypeId
		WHERE a.StypeId = @stypeid AND TypeId = @atypeid
		) a
		ORDER BY a.Ascids
	RETURN @sql
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetAllManagerBaseSTypeId]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetAllManagerBaseSTypeId]
GO

/*
	作者：谢吉康
	日期：2012-05-30
	描述：获取分支机构基本信息的节点ID，带了权限范围
*/
CREATE  FUNCTION F_GetAllManagerBaseSTypeId
(
	@TypeId			varchar(8000),	--需要拆分的基本信息ID
	@Flag			int,			--基本信息的标识 1.商品 2.往来单位 3.职员等
	@OperatorId		varchar(100),	--当前操作员的ID	
	@STypeId		varchar(100)	--分支机构ID
)	
RETURNS @Temp TABLE(TypeId varchar(100))
--@encode$--
AS
BEGIN
	--做一个标准格式的处理
	SET @TypeId = dbo.F_GetValidUserDataId(@TypeId)

	DECLARE @BaseTypeId		varchar(100)

	
	IF @TypeId = '00000' OR @TypeId = '' OR @TypeId = '%'
		INSERT INTO @Temp(TypeId) SELECT TypeId FROM Ac_Account WHERE SonNum = 0
	ELSE
		BEGIN
			INSERT INTO @Temp(TypeId)
			SELECT 	A.TypeId 
			FROM 	Ac_Account A, 
					(SELECT A FROM dbo.F_Split(@TypeId,',')) B 
			WHERE	A.TypeId LIKE B.A + '%'
					AND A.SonNum = 0
					AND A.StypeId LIKE @STypeId + '%'
		END		

	RETURN
END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetCredenceATypeAll]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].F_GetCredenceATypeAll
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-8-10
	描述：获取所有管辖会计凭证科目-树形表
*/
CREATE FUNCTION F_GetCredenceATypeAll
(
	@chvOperatorId			varchar(100)
)
RETURNS TABLE
--@encode$--
AS
RETURN (
	SELECT	*
	FROM(
		/*SELECT nTypeId,nId FROM F_GetManAtypeAll(@chvOperatorId)
		UNION
		SELECT nTypeId,nId FROM F_GetManAtypeSrAll(@chvOperatorId)		--F_AllTreeIncomeC
		UNION
		SELECT nTypeId,nId FROM  F_GetManAtypeFyAll(@chvOperatorId)
		UNION 
		SELECT nTypeId,nId FROM F_GetManAtypeZcAll(@chvOperatorId)		--F_AllTreeAssetsT
		UNION
		SELECT nTypeId,nId FROM Ac_Items WHERE nTypeId LIKE '00003%' AND LEFT(nTypeId,10) <> '0000300003' AND SonNum = 0 --收入
		UNION
		SELECT nTypeId,nId FROM Ac_Items WHERE  nTypeId LIKE '00004%' AND LEFT(nTypeId,10) <> '0000400003' AND SonNum = 0 --支出
		UNION 
		SELECT nTypeId,nId FROM Ac_Items WHERE  LEFT(ntypeId,5)='00002' OR 
		(LEFT(ntypeId,5)='00001' AND LEFT(nTypeId,10)<>'0000100003' AND LEFT(nTypeId,10)<>'0000100004' AND LEFT(nTypeId,10)<>'0000100002')
		*/
		
		SELECT nTypeId,nId from F_AllTreeAssetsT(@chvOperatorId) WHERE UserCode NOT IN ('SYC-1601','SYC-1602')   --资 产 类
		UNION 
		SELECT nTypeId,nId from F_AllTreeInDebtT(@chvOperatorId)   --负 债 类
		UNION 
		SELECT nTypeId,nId from F_AllTreeIncomeC(@chvOperatorId)   --收 入 类
		UNION 
		SELECT nTypeId,nId from F_AllTreeExpenseC(@chvOperatorId)   --支 出 类
		UNION 
		SELECT nTypeId,nId from F_AllTreeOwnerEquityT(@chvOperatorId)   --所有者权益
		)CAtype
)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[F_GetPriceBillStypeID]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[F_GetPriceBillStypeID]
GO

/*
========================================================================
	功能说明： 	价格表分支机构id连接函数
	作者： 		胡小科
	时间：		2013年5月14日 15:05:07
========================================================================
*/

CREATE  FUNCTION F_GetPriceBillStypeID
(
	@id		INT
)
RETURNS varchar(MAX) 
AS  
BEGIN 
	DECLARE @sql VARCHAR(MAX)
	SET @sql = ''
	SELECT	@sql=@sql+s.TypeId+',' 
	FROM	PriceRule_Stype prs 
	INNER JOIN stype s ON s.TypeId = prs.StypeID
	WHERE	prs.PriceRuleID = @id
	ORDER BY s.FullName
	IF @sql = ''
		RETURN ''
	RETURN LEFT(@sql,LEN(@sql)-1)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FillPtypeMultibarcode]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[FillPtypeMultibarcode];
GO

/*
	日期:2017-08-22
	描述:给商品ptypeid表填所有条码
*/
CREATE  PROCEDURE FillPtypeMultibarcode 
( 
	@Ptypeid VARCHAR(50) --商品typeid
)
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
		DECLARE @MultEntryCode NVARCHAR(MAX)='';
		SELECT @MultEntryCode=dbo.F_GetAllEntrycode(@Ptypeid,'',1)
		UPDATE ptype SET MultEntryCode=@MultEntryCode WHERE typeId=@Ptypeid
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO






IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZSalePlanManageCopy]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSalePlanManageCopy]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE FZSalePlanManageCopy
    (
      @BillNumberID NUMERIC(9, 0),
      @EtypeID VARCHAR(25),
      @JtypeID VARCHAR(25)
    )
	--@encode$--
AS 
    DECLARE @BillType INT,
        @NewBillNumberID NUMERIC(9, 0)


    SELECT  @BillType = BillType
    FROM    CX_SalePlanIndex
    WHERE   BillNumberId = @BillNumberID

    BEGIN TRAN

/*
复制的主表信息
*/
    SELECT  *
    INTO    #CX_SalePlanIndex
    FROM    CX_SalePlanIndex
    WHERE   BillNumberId = @BillNumberID --复制原来的主表
    IF @@error != 0 
        BEGIN
            ROLLBACK TRAN	
            RETURN -1
        END
    SELECT  *
    INTO    #CX_SaleStocksArea
    FROM    CX_SaleStocksArea
    WHERE   BillNumberId = @BillNumberID --复制原来的仓库表
    IF @@error != 0 
        BEGIN
            ROLLBACK TRAN	
            RETURN -1
        END

--根据BillType值 得到不同的促销单，进行复制
    IF @BillType = 1 
        BEGIN
            SELECT  *
            INTO    #CX_SpecialOfferBill
            FROM    CX_SpecialOfferBill
            WHERE   BillNumberId = @BillNumberID
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN		
                    RETURN -1
                END
        END

    IF @BillType = 2 
        BEGIN
            SELECT  *
            INTO    #CX_LargessBill
            FROM    CX_LargessBill
            WHERE   BillNumberId = @BillNumberID
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN
                    RETURN -1
                END
        END

    IF @BillType = 3 
        BEGIN
            SELECT  *
            INTO    #CX_SaleByHand
            FROM    CX_SaleByHand
            WHERE   BillNumberId = @BillNumberID
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN		
                    RETURN -1
                END
        END

    IF @BillType = 4 
        BEGIN
            SELECT  *
            INTO    #CX_CombinationBill
            FROM    CX_CombinationBill
            WHERE   BillNumberId = @BillNumberID
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN		
                    RETURN -1
                END
            SELECT  *
            INTO    #CX_CombinationDetailBill
            FROM    CX_CombinationDetailBill
            WHERE   BillNumberId = @BillNumberID
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN		
                    RETURN -1
                END
        END


    INSERT  INTO CX_SalePlanIndex
            (
              BillType,
              BillName,
              BillCode,
              BillDateTime,
              StartDate,
              EndDate,
              EtypeId,
              JTypeID,
              BillStatus,
              BreakStatus,
              DateTimeType,
              MonthDay,
              MonthWeek,
              MonthWeekDay,
              WeekDays,
              StartTime,
              EndTime,
              SalePrice,
              SaleType,
              TotalMoney,
              Remark,
              Checke,
              Breake,
              CheckeDateTime,
              BreakeDateTime
            )
            SELECT  BillType,
                    BillName,
                    BillCode,
                    BillDateTime,
                    StartDate,
                    EndDate,
                    EtypeId,
                    JTypeID,
                    BillStatus,
                    BreakStatus,
                    DateTimeType,
                    MonthDay,
                    MonthWeek,
                    MonthWeekDay,
                    WeekDays,
                    StartTime,
                    EndTime,
                    SalePrice,
                    SaleType,
                    TotalMoney,
                    Remark,
                    Checke,
                    Breake,
                    CheckeDateTime,
                    BreakeDateTime
            FROM    #CX_SalePlanIndex
    IF @@error != 0 
        BEGIN
            ROLLBACK TRAN	
            RETURN -1
        END


    SELECT  @NewBillNumberID = MAX(BillNumberID)
    FROM    CX_SalePlanIndex  --以新插入的ID，作为关键，应用于下面不同的表

    DECLARE @BDate VARCHAR(30),
        @EDate VARCHAR(30)
    SET @BDate = CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-'
        + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-'
        + CAST(DAY(GETDATE()) AS VARCHAR(2)) +' 00:00:00'
    SET @EDate = CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-'
        + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-'
        + CAST(DAY(GETDATE()) AS VARCHAR(2))  +' 23:59:59'

    UPDATE  CX_SalePlanIndex
    SET     BillName = '',
            BillCode = '',
            BillDateTime = GETDATE(),
            StartDate = @BDate,
            EndDate = @EDate,
            EtypeID = @EtypeID,
            JTypeID = @JTypeID,
            BillStatus = 0,
            BreakStatus = 0,
            Checke = '',
            Breake = '',
            CheckeDateTime = '',
            BreakeDateTime = ''
    WHERE   BillNumberID = @NewBillNumberID
    IF @@error != 0 
        BEGIN
            ROLLBACK TRAN	
            RETURN -1
        END

    INSERT  INTO CX_SaleStocksArea
            (
              BillNumberId,
              KtypeId,
              IsHQ
            )
            SELECT  @NewBillNumberID,
                    KtypeId,
                    IsHQ
            FROM    #CX_SaleStocksArea
    IF @@error != 0 
        BEGIN
            ROLLBACK TRAN	
            RETURN -1
        END

    IF @BillType = 1 
        BEGIN
            INSERT  INTO CX_SpecialOfferBill
                    (
                      BillNumberId,
                      Row,
                      PtypeId,
                      SalePrice,
                      Discount,
                      DiscountPrice,
                      MemberIntegral,
                      MemberPrice
                    )
                    SELECT  @NewBillNumberID,
                            Row,
                            PtypeId,
                            SalePrice,
                            Discount,
                            DiscountPrice,
                            MemberIntegral,
                            MemberPrice
                    FROM    #CX_SpecialOfferBill
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN	
                    RETURN -1
                END
        END

    IF @BillType = 2 
        BEGIN
            INSERT  INTO CX_LargessBill
                    (
                      BillNumberId,
                      Row,
                      PtypeId,
                      Qty,
                      LargessRow,
                      LargessPtypeId,
                      LargessAddTotal,
                      LargessQty
                    )
                    SELECT  @NewBillNumberID,
                            Row,
                            PtypeId,
                            Qty,
                            LargessRow,
                            LargessPtypeId,
                            LargessAddTotal,
                            LargessQty
                    FROM    #CX_LargessBill
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN	
                    RETURN -1
                END
        END

    IF @BillType = 3 
        BEGIN
            INSERT  INTO CX_SaleByHand
                    (
                      BillNumberId,
                      SaleType,
                      MoneyTicket,
                      GoodsPro,
                      ChoosePro,
                      TotalMoney,
                      TotalQty,
                      Discount,
                      RebateMoney,
                      MoneyAdd
                    )
                    SELECT  @NewBillNumberID,
                            SaleType,
                            MoneyTicket,
                            GoodsPro,
                            ChoosePro,
                            TotalMoney,
                            TotalQty,
                            Discount,
                            RebateMoney,
                            MoneyAdd
                    FROM    #CX_SaleByHand
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN	
                    RETURN -1
                END
        END

    IF @BillType = 4 
        BEGIN
            INSERT  INTO CX_CombinationBill
                    (
                      BillNumberId,
                      Row,
                      UserCode,
                      FullName,
                      EntryCode,
                      SalePrice,
                      Discount,
                      DiscountPrice,
                      MemberPrice
                    )
                    SELECT  @NewBillNumberID,
                            Row,
                            UserCode,
                            FullName,
                            EntryCode,
                            SalePrice,
                            Discount,
                            DiscountPrice,
                            MemberPrice
                    FROM    #CX_CombinationBill
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN	
                    RETURN -1
                END
            INSERT  INTO CX_CombinationDetailBill
                    (
                      BillNumberId,
                      Row,
                      DetailRow,
                      PtypeId,
                      Qty,
                      SalePrice,
                      Discount,
                      DiscountPrice,
                      MemberPrice
                    )
                    SELECT  @NewBillNumberID,
                            Row,
                            DetailRow,
                            PtypeId,
                            Qty,
                            SalePrice,
                            Discount,
                            DiscountPrice,
                            MemberPrice
                    FROM    #CX_CombinationDetailBill
            IF @@error != 0 
                BEGIN
                    ROLLBACK TRAN	
                    RETURN -1
                END
        END

    COMMIT TRANSACTION


    IF @BillType = 1 
        BEGIN
            DROP TABLE #CX_SpecialOfferBill
        END

    IF @BillType = 2 
        BEGIN
            DROP TABLE #CX_LargessBill
        END

    IF @BillType = 3 
        BEGIN
            DROP TABLE #CX_SaleByHand
        END

    IF @BillType = 4 
        BEGIN
            DROP TABLE #CX_CombinationBill
            DROP TABLE #CX_CombinationDetailBill
        END

    DROP TABLE #CX_SalePlanIndex
    DROP TABLE #CX_SaleStocksArea

    RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSystemVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GetSystemVersion]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年10月27
-- Description:	获取系统产品版本号
-- =============================================
CREATE PROCEDURE GetSystemVersion 
(
	@Version  VARCHAR(10) OUTPUT--产品编号
)
--@encode$--
AS
BEGIN
DECLARE @proinfo int
Select @proinfo=subvalue from sysdata where subname='ProInfo'
if(@proinfo=1)
SET @Version='V3'
IF(@proinfo=2)
SET @Version='A8'
IF(@proinfo=3)
SET @Version='QP'
SELECT @Version
END
GO




IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AcBalanceTypeEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_AcBalanceTypeEdit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：佘海源
	日期：2012-03-30
	描述：结算方式基础资料的数据库操作-添加、修改、删除
	返回：成功:1 失败：0 
-------------------------------------------*/
CREATE PROCEDURE Gp_AcBalanceTypeEdit
(
       @BtId		int,			---ID         
       @UserCode	varchar(200),	---代码      
	   @FullName	varchar(200),	---名称       
	   @ATypeId		varchar(50),	---科目代码    
       @Type		int				---操作类型：1:新增 2：编辑 3：删除
)
--@encode$--
AS 
SET NOCOUNT ON
IF(@type=3)--删除
	BEGIN
		DECLARE @Ret INT=(SELECT dbo.Fn_GetIsUse_Items(@BtId,6))
		IF(@Ret=1)
			BEGIN
				RAISERROR('该信息已经使用，不能删除！',16,1)RETURN
			END
		DELETE FROM Ac_BalanceType WHERE BtId=@BtId
	END
ELSE 
	BEGIN
		DECLARE @Name VARCHAR(200)
		
		--判断编号是否重复
		IF(ISNULL(@BtId,0)>0)
			SELECT @Name=FullName FROM Ac_BalanceType WHERE UserCode=@usercode AND BtId<>@BtId
		ELSE
			SELECT @Name=FullName FROM Ac_BalanceType WHERE UserCode=@usercode
			
		IF(ISNULL(@Name,'')<>'')
			BEGIN
				DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
				RAISERROR(@MSG,16,1)RETURN
			END
		--判断名称是否重复
		IF(ISNULL(@BtId,0)>0)
			SELECT @Name=FullName FROM Ac_BalanceType WHERE FullName=@fullname AND BtId<>@BtId
		ELSE
			SELECT @Name=FullName FROM Ac_BalanceType WHERE FullName=@fullname
			
		IF(ISNULL(@Name,'')<>'')
			BEGIN
				DECLARE @MSG1 VARCHAR(100)='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
				RAISERROR(@MSG1,16,1)RETURN
			END	
			
		IF(@type=1)--添加
			BEGIN
				INSERT INTO Ac_BalanceType
				(
					[UserCode],
					[FullName],
					[ATypeId]
				) 
				VALUES
				(
					@UserCode,
					@FullName,
					@ATypeId
				)
			END
		ELSE IF(@type=2)--修改
			BEGIN
				DECLARE @Ret1 INT=(SELECT dbo.Fn_GetIsUse_Items(@BtId,6))
				IF(@Ret1=1)
					BEGIN
						RAISERROR('该信息已经使用，不能编辑！',16,1)RETURN
					END
				
				UPDATE Ac_BalanceType 
				SET 
					UserCode=@UserCode,
					FullName=@FullName,
					ATypeId=@ATypeId
				WHERE BtId=@BtId
			END
	END
IF(@@ERROR<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='信息添加失败！'
		IF(@type=2)
			SET @MSG2='信息修改失败'
		IF(@Type=3)
			SET @MSG2='信息删除失败'
		RAISERROR(@MSG2,16,1)	
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_AccountAtypeEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[GP_AccountAtypeEdit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊
	日期：2015-01-26
	描述：分支机构科目大类-添加
*/ 
CREATE PROCEDURE GP_AccountAtypeEdit
(
	@etypeid VARCHAR(500),			--职员
	@stypeid VARCHAR(500),			--分支机构 
	@typeid VARCHAR(MAX),			--科目类
	@OperatorId VARCHAR(500)		--操作员
)
--@encode$--
AS 
---------------------------------------------------------------------------------------------------------------------------
IF((SELECT COUNT(1) FROM dbo.Ac_Account_L WHERE etypeid = @etypeid AND stypeid = '00000' AND typeid = '00000') >= 1)
BEGIN
	DELETE FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = '00000' AND typeid = '00000'
END
ELSE
BEGIN
	DELETE FROM Ac_Account_L 
	WHERE etypeid = @etypeid
		AND stypeid = @stypeid 
		AND LEN(typeid) = 5
END
		
INSERT INTO Ac_Account_L(etypeid,stypeid,typeid,flag)
SELECT @etypeid,@stypeid,a,1 
FROM F_Split(@typeid,',')
RETURN 1
--------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



				 IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_AccountMultiLevelEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[GP_AccountMultiLevelEdit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊
	日期：2014-11-20
	描述：会计科目多级权限修改
*/ 
CREATE PROCEDURE dbo.GP_AccountMultiLevelEdit
(
	@typeid VARCHAR(500),			--科目类别
	@stypeid VARCHAR(500),			--分支机构
	@etypeid VARCHAR(500),			--职员
	@accounttable AS TbType_AccountMultiLevelEdit READONLY,
	@chvOperatorID VARCHAR(500)		--操作员
)
--@encode$--
AS 
--------------------------------------------------------------权限检查-------------------------------------------------------  
IF @chvOperatorID IS NULL RETURN 1  
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),  
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)  
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT  
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------
DECLARE @ALL INT  --当前职员是否拥有所有权限
IF((SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = '00000' AND typeid = '00000') = 1
	OR (SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = @stypeid AND typeid = '00000') = 1)
	SET @ALL = 1
ELSE
	SET @ALL = 0

--清除当前科目类-已有的权限
DELETE FROM Ac_Account_L 
WHERE etypeid = @etypeid 
	AND (stypeid = @stypeid OR stypeid = '00000') 
	AND (typeid LIKE @typeid + '%' OR typeid = '00000')
IF(@@ERROR <> 0)
	RETURN -1
--重新写入当前科目类权限
IF(@typeid = '') --"拥有该分支机构下所有权限“按钮事件
BEGIN
	INSERT INTO Ac_Account_L(etypeid,stypeid,typeid,flag)
	SELECT @etypeid,@stypeid,'00000',1 
	--拥有全部权限时，不再只存储一条记录，要分别存储各大类的数据。9.5BUG 1255 确认。
	--SELECT @etypeid,@stypeid,TypeId,1 FROM Ac_Account WHERE ParId='00000' AND StypeId = '00000' AND SonCount > 0
	IF(@@ERROR <> 0)
		RETURN -1
END
ELSE
BEGIN
	INSERT INTO Ac_Account_L(etypeid,stypeid,typeid,flag)
	SELECT @etypeid,@stypeid,typeid,flag FROM @accounttable ORDER BY typeid
	IF(@@ERROR <> 0)
		RETURN -1
		
	IF(@ALL = 1) --拥有所有权限时，重新分配后将其他科目类加上
	BEGIN
		INSERT INTO Ac_Account_L(etypeid,stypeid,typeid,flag)
		SELECT @etypeid,@stypeid,TypeId,1 
		FROM Ac_Account 
		WHERE StypeId = '00001' AND ParId='00000' AND TypeId <> @typeid
	END
END
RETURN 1
--------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_AcCountStartAndStop]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_AcCountStartAndStop]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	黄清
	Date	:	2013-06-21
	Description	:停用、启用会计科目
*/
CREATE PROCEDURE GP_AcCountStartAndStop
(
	 @TypeId	VARCHAR(500), --科目ID
	 @STypeId	VARCHAR(500),
	 @mode		VARCHAR(1)  --1.停用 0.启用
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @Operatorname VARCHAR(10)
IF @mode='0'
	SET @Operatorname='启用'
ELSE 
	SET @Operatorname='停用'

IF @STypeId='00000'
	SET @STypeId='00001'


IF EXISTS(SELECT 1 FROM Ac_Account WHERE TypeId=@TypeId AND StypeId =@STypeId AND Deleted=@mode)
    BEGIN
        RAISERROR ( '要%s的记录不存在', 16, 1,@Operatorname )
        RETURN -1 ;
    END
SELECT  1 FROM    AType_Total  WHERE   ATypeID = @TypeId AND StypeId = @STypeId AND (Total<>0 OR Ntotal<>0)
IF @mode='1'
BEGIN
	IF EXISTS ( SELECT  1 FROM    Ac_Account  WHERE   TypeID = @TypeId AND StypeId = @STypeId AND SonNum>0) 
		BEGIN
			RAISERROR ( '父节点不允许停用', 15, 1 )
			RETURN -1 ;
		END
	IF EXISTS ( SELECT  1 FROM    Ac_Balance  WHERE   ATypeID = @TypeId AND StypeId = @STypeId AND (FBeginBalance<>0 OR FBeginBalanceFor<>0 OR FEndBalance<>0 OR FEndBalanceFor<>0)) 
		AND NOT EXISTS(SELECT *FROM SType_UserConfig WHERE StypeId=@STypeId and Value=1)
		BEGIN
			RAISERROR ( '当前科目有余额，不能停用', 15, 1 )
			RETURN -1 ;
		END
	IF EXISTS(SELECT *FROM SType_UserConfig WHERE StypeId=@STypeId and Value=1)
	AND EXISTS (	SELECT  1 FROM    Ac_Balance A 
					INNER JOIN Ac_AccountsPeroid_Stype P ON A.Stypeid=P.Stypeid AND A.FYear=P.FYear AND A.FPeriod=P.FPeriod   
					WHERE   ATypeID = @TypeId AND A.STypeId = @STypeId AND (FEndBalance<>0 OR FEndBalanceFor<>0)
	) 
		BEGIN
			RAISERROR ( '当前科目有期末余额，不能停用', 15, 1 )
			RETURN -1 ;
		END
	IF EXISTS ( SELECT  1 FROM    Ac_Voucher_Bill b INNER JOIN Ac_Voucher V ON B.BillNumberId=V.BillNumberId
   WHERE  ( B.ATypeID = @TypeId OR B.ATypeId2=@TypeId) AND B.STypeId = @STypeId  AND V.IfCheck='f') 
		BEGIN
			RAISERROR ( '当前科目存在未记账凭证，不能停用', 15, 1 )
			RETURN -1 ;
		END
	IF EXISTS(SELECT *FROM Ac_IniAccount WHERE STypeId=@STypeId AND ATypeId=@TypeId AND (iniTotal<>0 OR iniTotalFor<>0 OR iniYTotal<>0 OR iniYTotalFor<>0 OR FDebit<>0 OR FDebitFor<>0 OR FCredit<>0 OR FCreditFor<>0))
	AND NOT EXISTS(SELECT *FROM SType_UserConfig WHERE StypeId=@STypeId and Value=1)
		BEGIN
			RAISERROR ( '当前科目在账务期初中存在金额，请调整后再停用', 15, 1 )
			RETURN -1 ;
		END
	--IF EXISTS(SELECT *FROM Ac_IniAccount WHERE STypeId=@STypeId AND ATypeId=@TypeId AND (iniTotal<>0 OR iniTotalFor<>0 OR iniYTotal<>0 OR iniYTotalFor<>0 ))
	--AND EXISTS(SELECT *FROM SType_UserConfig WHERE StypeId=@STypeId and Value=1)
	--	BEGIN
	--		RAISERROR ( '当前科目在账务期初中存在金额，请调整后再停用', 15, 1 )
	--		RETURN -1 ;
	--	END
	IF EXISTS (SELECT *FROM Te_BankAccount WHERE STypeId=@STypeId AND ATypeId=@TypeId AND IsDestroy<>'1')
	BEGIN
		RAISERROR ( '当前科目正在被银行账户引用，请调整后再停用', 15, 1 )
		RETURN -1 ;
	END
		IF EXISTS (SELECT 1 FROM Te_InitDataDetail D INNER JOIN Te_InitDataIndex I ON I.Id=D.IndexId WHERE I.STypeId=@STypeId AND D.AtypeId=@TypeId)
	BEGIN
		RAISERROR ( '当前科目已在出纳初始化数据中使用，请调整后再停用', 15, 1 )
		RETURN -1 ;
	END
END
--SELECT *FROM Ac_IniAccount where STypeId='00001'
UPDATE Ac_Account SET Deleted=@mode WHERE TypeId=@TypeId AND StypeId=@STypeId

---V3特殊处理，启用\停用时同时停用默认分支机构科目
IF EXISTS(SELECT *FROM sysdata WHERE SubName='ProInfo' AND SubValue=1)
BEGIN
	UPDATE Ac_Account SET Deleted=@mode WHERE TypeId=@TypeId AND StypeId='00000'
END

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_AccountStypeEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[GP_AccountStypeEdit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊
	日期：2015-01-12
	描述：分支机构会计科目权限-添加
*/ 
CREATE PROCEDURE GP_AccountStypeEdit
(
	@etypeid VARCHAR(500),			--职员
	@stypeid VARCHAR(MAX),			--分支机构 
	@chvOperatorID VARCHAR(500)		--操作员
)
--@encode$--
AS 
---------------------------------------------------------------------------------------------------------------------------
DELETE FROM Ac_Account_L 
WHERE etypeid = @etypeid 
	AND stypeid NOT IN(SELECT stypeid FROM Ac_Account_L WHERE etypeid = @etypeid AND TypeId <> '00000' GROUP BY stypeid)

INSERT INTO Ac_Account_L(etypeid,stypeid,typeid,flag)
SELECT @etypeid,a,'00000',1 
FROM F_Split(@stypeid,',')
--IF((SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = '00000') = 1)
--BEGIN
--	DELETE FROM Ac_Account_L WHERE etypeid = @etypeid
	
--	INSERT INTO Ac_Account_L(etypeid,stypeid,typeid,flag)
--	SELECT @etypeid,a,'00000',1 
--	FROM F_Split(@stypeid,',')
--END
--ELSE
--BEGIN
--	DELETE FROM Ac_Account_L 
--	WHERE etypeid = @etypeid 
--		AND stypeid NOT IN(SELECT stypeid FROM Ac_Account_L WHERE etypeid = @etypeid AND TypeId <> '00000' GROUP BY stypeid)
	
--	INSERT INTO Ac_Account_L(etypeid,stypeid,typeid,flag)
--	SELECT @etypeid,a,'00000',1 
--	FROM F_Split(@stypeid,',')
--END
RETURN 1
--------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ActiveAcTable]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ActiveAcTable]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/04/10
	Description	: 启用/停用科目表
*/

CREATE PROCEDURE GP_ActiveAcTable 
(
	@AcID		INT,--科目表treeID  
	@Active		INT	--1：启用 0：停用
)
--@encode$--
AS 
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM Ac_Table WHERE IsUsed=1) AND @Active=1
	BEGIN
        RAISERROR ('仅能启用1套科目体系！', 15, 1) ;
        RETURN -1 ;
	END
IF @Active NOT IN (0, 1) 
    BEGIN
        RAISERROR ('参数Active不正确.', 15, 1) ;
        RETURN -1 ;
    END

DECLARE @isUsed INT ;
SELECT  @isUsed = IsUsed
FROM    Ac_Table
WHERE   AcId = @AcID ;

IF @isUsed IS NULL 
    BEGIN
        IF @Active = 1 
            RAISERROR ('要启用的科目表不存在.', 15, 1) ;
        ELSE 
            RAISERROR ('要停用的科目表不存在.', 15, 1) ;
        RETURN -1 ;
    END

IF @isUsed = 1
    AND @Active = 1 
    BEGIN
        RAISERROR ('科目表已经启用.', 15, 1) ;
        RETURN -1 ;
    END

IF @isUsed = 0
    AND @Active = 0 
    BEGIN
        RAISERROR ('科目表已经停用.', 15, 1) ;
        RETURN -1 ;
    END
    
IF @Active = 1
    AND NOT EXISTS (SELECT TOP 1 1 FROM Ac_Account WHERE STypeID = '00000' AND Leveal >= 2)
    BEGIN
        RAISERROR ('该科目表中没有任何科目信息，启用失败.', 15, 1) ;
        RETURN -1 ;
    END

IF @Active = 0 
    BEGIN
        IF EXISTS ( SELECT  1
                    FROM    Ac_Account
                    WHERE   StypeId <> '00000' ) 
            BEGIN
                RAISERROR ('科目表已经被分发到分支机构，在反分配之前不能停用', 15, 1) ;
                RETURN -1 ;
            END
    END

UPDATE  Ac_Table
SET     IsUsed = @Active
WHERE   AcId = @AcID ;

/*
    @rowcount   ret
    1           0(succ)
    0           -1(fail)
*/

RETURN @@RowCount - 1;


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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







/*
	作者：谢吉康
	日期：2005-4-12
	描述：单独处理调拨单的出入库审核提示
*/
CREATE PROCEDURE Gp_AddAllotCheckBillMessage
(
	@AuditingId		int,			--单据审核的Id
	@BillNumberId	int,			--单据的Id
	@BillIndexType	int,			--单据的类型	0.订单	1.借欠	2.一般物流单据
	@InOrOut		varchar(20)		--出入库审核	InOrOut.出入库审核    I.入库审核  o.出库审核
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @ETypeId 	varchar(100),	--审核人
		@MKTypeId	varchar(100),	--管辖仓库的Id
		@outKTypeId	varchar(100),	--出库仓库
		@inKTypeId	varchar(100)	--入库仓库

--获取单据的仓库信息
SELECT	@outKTypeId = KTypeId,@inKTypeId = KTypeId2 FROM BillIndex WHERE BillNumberId = @BillNumberId

--游标处理设置提示
DECLARE AuditingCursor CURSOR FOR	
	SELECT ETypeId FROM AuditingFlowDetail WHERE AuditingId = @AuditingId ORDER BY OutKty DESC
--打开游标
OPEN AuditingCursor
--处理结果
FETCH NEXT FROM AuditingCursor INTO @ETypeId
--循环结果
WHILE @@FETCH_STATUS = 0
	BEGIN
		--获取权限范围
		SELECT @MKTypeId = MangerKTypeId FROM LoginUser WHERE ETypeId = @ETypeId

		--如果有出入库审核或出库审核
		IF (@InOrOut = 'InOrOut' OR @InOrOut = 'o')
			BEGIN
				--判断权限范围
				IF (@MKTypeId = '00000' OR RTRIM(LTRIM(@MKTypeId))=RTRIM(LTRIM(@outKTypeId)) OR substring(@outKTypeId,1,LEN(@MKTypeId))=@MKTypeId)
					UPDATE	AuditingFlowDetail
					SET 	AuditingAlerm = 1
					WHERE	AuditingId = @AuditingId
							AND OutKty = 'o'
							AND (AuditingStep = 1 OR AuditingStep = 0)
							AND ETypeId = @ETypeId
			END
		ELSE
			BEGIN
				--判断权限范围
				IF (@MKTypeId = '00000' OR RTRIM(LTRIM(@MKTypeId))=RTRIM(LTRIM(@inKTypeId)) OR substring(@inKTypeId,1,LEN(@MKTypeId))=@MKTypeId)
					UPDATE	AuditingFlowDetail
					SET 	AuditingAlerm = 1
					WHERE	AuditingId = @AuditingId
							AND OutKty = 'i'
							AND (AuditingStep = 1 OR AuditingStep = 0)
							AND ETypeId = @ETypeId
			END
		FETCH NEXT FROM AuditingCursor INTO @ETypeId
	END
--关闭游标
CLOSE AuditingCursor
--是否游标资源
DEALLOCATE AuditingCursor







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

Create Procedure GP_AddCheckBIllData
(
	@corpid         nvarchar(500),
	@guid           nvarchar(500),
	@dbname         nvarchar(500),
	@operatorid     nvarchar(500),
	@auditingstep   nvarchar(500),
	@billnumberid   nvarchar(500),
	@billindextype  nvarchar(500),
	@billtype       nvarchar(500),
	@stypeid        nvarchar(500),
	@dtypeid        nvarchar(500),
	@etypeid        nvarchar(500),
	@dealbtypeid    nvarchar(500),
	@result         nvarchar(50),
	@audtype        nvarchar(50)
 
)
--@encode$--
AS

DECLARE @billcode nvarchar(500)

IF(@billindextype='2')
SELECT  @billcode=BillCode FROM Billindex where billnumberid=@billnumberid
ELSE IF(@billindextype='0')
SELECT  @billcode=BillCode FROM OrderIndex where billnumberid=@billnumberid


IF EXISTS(select * from CheckBIllData where corpid=@corpid AND @guid=@guid AND dbname=@dbname AND operatorid=@operatorid AND auditingstep=@auditingstep AND billnumberid=@billnumberid AND billindextype=@billindextype AND billtype=@billtype AND stypeid=@stypeid AND dtypeid=@dtypeid AND etypeid=@etypeid AND dealbtypeid=@dealbtypeid  AND billcode=@billcode AND audtype=@audtype)
BEGIN
UPDATE CheckBIllData SET [result]=@result where corpid=@corpid AND @guid=@guid AND dbname=@dbname AND operatorid=@operatorid AND auditingstep=@auditingstep AND billnumberid=@billnumberid AND billindextype=@billindextype AND billtype=@billtype AND stypeid=@stypeid AND dtypeid=@dtypeid AND etypeid=@etypeid AND dealbtypeid=@dealbtypeid AND billcode=@billcode AND audtype=@audtype
END
ELSE
BEGIN
IF NOT EXISTS(select * from CheckBIllData where corpid=@corpid AND @guid=@guid AND dbname=@dbname AND operatorid=@operatorid AND auditingstep=@auditingstep AND billnumberid=@billnumberid AND billindextype=@billindextype AND billtype=@billtype AND stypeid=@stypeid AND dtypeid=@dtypeid AND etypeid=@etypeid AND dealbtypeid=@dealbtypeid AND result=@result AND billcode=@billcode AND audtype=@audtype)
BEGIN
INSERT INTO CheckBIllData([corpid],[guid],[dbname],[operatorid],[auditingstep],[billnumberid],[billindextype],[billtype],[stypeid],[dtypeid],[etypeid],[dealbtypeid],[result],[billcode],[audtype]) 
VALUES (@corpid,@guid,@dbname,@operatorid,@auditingstep,@billnumberid,@billindextype,@billtype,@stypeid,@dtypeid,@etypeid,@dealbtypeid,@result,@billcode,@audtype)
END
END
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF Exists(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_CustomPlusItem' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddCustomPlusItemValue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].Gp_AddCustomPlusItemValue--删除此存储过程的引用
	
	DROP type [dbo].Type_CustomPlusItem 
END
GO
CREATE TYPE Type_CustomPlusItem AS TABLE--
(
	PtypeItemsId	INT,
	ItemStr			VARCHAR(MAX)

)
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddCustomPlusItemValue]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_AddCustomPlusItemValue]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	自定义组合项新增
-- 时间：	2017-07-26
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [Gp_AddCustomPlusItemValue]
(
	@ItemsId		INT,
	@Item			Type_CustomPlusItem Readonly,--编号
	@refid			VARCHAR(MAX)				--名称
)
WITH ENCRYPTION

AS
SET NOCOUNT ON

select * from xw_SelfData

select * from CustomReferenceValue





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2005-8-4
	描述：增加新的单据到AuditingBill中

    新Carpa平台后重新调整  卢春 2009-06
    
    添加询价单，请购单的修改状态 周华 2013-11-27
*/
CREATE              PROCEDURE Gp_AddDataToAuditingBill
(
	@BillNumberId		varchar(8000),		--单据编号
	@BillIndexType		int,				--单据类型   0.订单   1.借欠   2.一般物流单据
	@OperatorETypeID	VARCHAR(100)		--操作员ID号
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @OperatorId		varchar(100),
		@BillType 		int,
		@ETypeId		varchar(100),
		@STypeID		VARCHAR(100),
		@BillDate		datetime,
		@BillCode		varchar(256),
		@AuditingId		int,
		@AuditingLevel	int,
		@AuditingLevel1	int,
		@AuditingType	int,
		@InOrOut		varchar(10),
		@Checke			VARCHAR(50)		--制单人

BEGIN TRAN
-- 判断状态是否待审核或审核通过，是则退出
IF EXISTS(SELECT TOP 1 BillNumberId FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = @BillIndexType AND IfAudit <> -1)
BEGIN
	ROLLBACK TRAN
	RETURN -2
END

-- 审核不通过，则删除掉原记录，重新写记录
IF EXISTS(SELECT TOP 1 BillNumberId FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = @BillIndexType AND IfAudit = -1)
BEGIN
	DELETE AuditingBillDetail WHERE BillNumberId=@BillNumberId AND BillIndexType=@BillIndexType
	DELETE AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = @BillIndexType
	IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		RETURN -6
	END
END

IF @BillIndexType = 0	-- 订单
BEGIN
	--修改订单状态
	IF EXISTS(SELECT TOP 1 BillNumberId FROM OrderIndex WHERE BillNumberId = @BillNumberId)
	BEGIN
		UPDATE	OrderIndex
		SET		IfAudit = 0
		WHERE	BillNumberId = @BillNumberId

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN
				RETURN -1
			END
	END
	
	--获取单据的信息
	SELECT	@BillType = BillType,
			@ETypeId  = ETypeId,
			@STypeID  = STypeID,
			@BillDate = BillDate,
			@BillCode = BillCode,
			@Checke=Checke
	FROM	OrderIndex
	WHERE	BillNumberId = @BillNumberId
END

IF @BillIndexType = 1	-- 借欠
BEGIN
	--修改订单状态
	IF EXISTS(SELECT TOP 1 BillNumberId FROM dbo.LendIndex WHERE BillNumberId = @BillNumberId)
	BEGIN
		UPDATE	LendIndex
		SET	    IfAudit = 0
		WHERE	BillNumberId = @BillNumberId

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN
				RETURN -1
			END
	END
	
	--获取单据的信息
	SELECT	@BillType = BillType,
			@ETypeId  = ETypeId,
			@STypeID  = STypeID,
			@BillDate = BillDate,
			@BillCode = BillCode,
			@Checke=Checke
	FROM	LendIndex
	WHERE	BillNumberId = @BillNumberId
END



IF @BillIndexType = 2	-- 一般物流单据
BEGIN
	--修改184报价单状态
	IF EXISTS(SELECT TOP 1 BillNumberId FROM BillIndex WHERE BillNumberId = @BillNumberId AND BillType=184)
	BEGIN
		UPDATE	BillIndex
		SET		IfAudit = 0
		WHERE	BillNumberId = @BillNumberId AND BillType=184

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN
				RETURN -1
			END
	END
	
	-- 修改询价单状态
	IF EXISTS(SELECT TOP 1 BillNumberId FROM BillIndex WHERE BillNumberId = @BillNumberId AND BillType =185)
	BEGIN
		UPDATE	BillIndex
		SET		IfAudit = 0
		WHERE	BillNumberId = @BillNumberId 

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN
				RETURN -1
			END
	END

	--获取单据的信息
	SELECT	@BillType = BillType,
			@ETypeId  = ETypeId,
			@STypeID  = STypeID,
			@BillDate = BillDate,
			@BillCode = BillCode,
			@Checke=Checke
	FROM	BillIndex
	WHERE	BillNumberId = @BillNumberId
END

IF @BillIndexType=3 --请购单
BEGIN
	-- 修改请购单状态
	IF EXISTS(SELECT TOP 1 BillNumberId FROM RequestIndex WHERE BillNumberId = @BillNumberId AND BillType=204)
	BEGIN
		UPDATE	dbo.RequestIndex
		SET		IfAudit = 0
		WHERE	BillNumberId = @BillNumberId 

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN
				RETURN -1
			END
	END
	
	--获取单据的信息
	SELECT	@BillType = BillType,
			@ETypeId  = ETypeId,
			@STypeID  = STypeID,
			@BillDate = BillDate,
			@BillCode = BillCode,
			@Checke=Checke
	FROM	dbo.RequestIndex
	WHERE	BillNumberId = @BillNumberId
END



IF @BillIndexType=4 --提成单
BEGIN
	---- 修改请购单状

	IF EXISTS(SELECT TOP 1 BillNumberId FROM CommissionBillNew WHERE BillNumberId = @BillNumberId)
	BEGIN
		UPDATE	dbo.CommissionBillNew
		SET		BillState = 3
		WHERE	BillNumberId = @BillNumberId 

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN
				RETURN -1
			END
	END
	
	--获取单据的信息
	SELECT	@BillType = 311,
			@ETypeId  = Checke,
			@STypeID  = STypeID,
			@BillDate = BillDate,
			@BillCode = BillCode,
			@Checke=Checke
	FROM	dbo.CommissionBillNew
	WHERE	BillNumberId = @BillNumberId
END

IF @BillIndexType=5--发票单据
BEGIN
	IF EXISTS(SELECT TOP 1 BillNumberid FROM ReceiptBillIndex WHERE BillNumberID=@BillNumberId)
	BEGIN
		UPDATE dbo.ReceiptBillIndex 
		SET	   IfAudit=0
		WHERE BillNumberID=@BillNumberId
	
	IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN
				RETURN -1
			END
	END
	
	--获取单据的信息
	SELECT	@BillType = BillType,
			@ETypeId  = ETypeId,
			@STypeID  = STypeID,
			@BillDate = BillDate,
			@BillCode = BillCode,
			@Checke=Checke
	FROM	ReceiptBillIndex
	WHERE	BillNumberId = @BillNumberId
END

IF @BillIndexType = 7 --实物库存
BEGIN

	
	--获取单据的信息
	SELECT	@BillType = BillType,
			@ETypeId  = ETypeId,
			@STypeID  = STypeID,
			@BillDate = BillDate,
			@BillCode = BillCode,
			@Checke=Checke
	FROM	FactIndex
	WHERE	BillNumberId = @BillNumberId
END
IF @BillIndexType = 9--门店类
BEGIN

	
	--获取单据的信息
	SELECT	@BillType = BillType,
			@ETypeId  = ApplyEtypeId,
			@STypeID  = STypeID,
			@BillDate = BillDate,
			@BillCode = BillCode,
			@Checke=Checke
	FROM	PosAllotApplyBillIndex
	WHERE	BillNumberId = @BillNumberId
END


--判断单据是否有审核流程
SELECT  @AuditingId 	= AuditingId,
		@AuditingLevel	= AuditingLevel,
		@AuditingLevel1	= AuditingLevel1,
		@AuditingType	= AuditingType
FROM	AuditingFlowSet
WHERE	BillType = @BillType
		AND STypeID=@STypeID
		AND IfUse = 1


	
--写入审核表（AuditingBill）中
INSERT INTO AuditingBill
(
	BillNumberId,
	AuditingId,
	AuditingSteps,
	IfAudit,
	ETypeId,
	BillDate,
	BillCode,
	BillDetail,
	BillIndexType,
	PassSteps,
	Checke
)VALUES(
	@BillNumberId,
	@AuditingId,
	REPLACE(REPLICATE(@AuditingLevel,@AuditingLevel),@AuditingLevel,'2'),
	0,
	@ETypeId,
	@BillDate,
	@BillCode,
	'',
	@BillIndexType,
	REPLACE(REPLICATE(@AuditingLevel,@AuditingLevel),@AuditingLevel,'2'),
	@Checke
)

IF @@ROWCOUNT = 0
BEGIN
	ROLLBACK TRAN
	RETURN -3
END	

-- PassSteps代表整单审核通过需要经历的步骤，与原因相关
DECLARE @PassSteps VARCHAR(50)
SET @PassSteps = REPLACE(REPLICATE(@AuditingLevel,@AuditingLevel),@AuditingLevel,'2')
CREATE TABLE #temp(
	BillNumberID INT,
	BillType	 NUMERIC(4, 0),
	PassFlag 	 bit,
	Reason 		 VARCHAR(500),
	value 		 VARCHAR(500),
	AuditingStep int
)
INSERT #temp EXEC GP_BillAudtingCheckReason @BillNumberId,@OperatorETypeID,@BillIndexType,'1',-1,0


DECLARE @i INT,@j INT,@stepReason VARCHAR(500),@stepValue VARCHAR(500)

-- 处理特审原因
DECLARE CURSOR_str CURSOR FOR SELECT DISTINCT Reason,Value,AuditingStep FROM #temp WHERE PassFlag = 0 ORDER BY AuditingStep
OPEN CURSOR_str
FETCH NEXT FROM CURSOR_str INTO @stepReason,@stepValue,@i
WHILE @@FETCH_STATUS = 0
BEGIN
	UPDATE AuditingBill SET StepReasons = ISNULL(StepReasons,'') + '0ж' + RTRIM(@stepReason + ' ' + ISNULL(@stepValue,'')) + 'жи'
	WHERE BillNumberID = @BillNumberId AND BillIndexType = @BillIndexType
	FETCH NEXT FROM CURSOR_str INTO @stepReason,@stepValue,@i
END
CLOSE CURSOR_str
DEALLOCATE CURSOR_str


-- 写入每级相关原因
SET @j = 0
DECLARE CURSOR_str CURSOR FOR SELECT AuditingStep,Reason,value FROM #temp WHERE PassFlag = 0 ORDER BY AuditingStep
OPEN CURSOR_str
FETCH NEXT FROM CURSOR_str INTO @i,@stepReason,@stepValue

WHILE @@FETCH_STATUS = 0
BEGIN

	IF @stepReason<>'...'
	BEGIN
		UPDATE AuditingBill SET StepReasons = ISNULL(StepReasons,'') + CAST(@i AS VARCHAR(10)) + 'ж' + RTRIM(@stepReason + ' ' + ISNULL(@stepValue,'')) + 'жи'
		WHERE BillNumberID=@BillNumberId AND BillIndexType=@BillIndexType
		IF @i <> @j
		BEGIN
			SET @PassSteps = LEFT(@PassSteps,@i-1) + '1' + RIGHT(@PassSteps,LEN(@PassSteps)-@i)
		END

		SET @j = @i
	END

	

	FETCH NEXT FROM CURSOR_str INTO @i,@stepReason,@stepValue
END
CLOSE CURSOR_str
DEALLOCATE CURSOR_str
UPDATE AuditingBill SET PassSteps=@PassSteps WHERE BillNumberID=@BillNumberId AND BillIndexType=@BillIndexType

-- 设置灯泡提醒
IF @AuditingType = 1
	DECLARE AuditingCursor CURSOR FOR
		SELECT ETypeId FROM AuditingFlowDetail
		WHERE AuditingId = @AuditingId AND AuditingStep IN (SELECT TOP 1 AuditingStep FROM #temp WHERE PassFlag=0 ORDER BY AuditingStep)

IF @AuditingType = 3
	DECLARE AuditingCursor CURSOR FOR
		SELECT ETypeId FROM AuditingFlowDetail
		WHERE AuditingId = @AuditingId AND AuditingStep IN (SELECT AuditingStep FROM #temp WHERE PassFlag=0 GROUP BY AuditingStep)

OPEN AuditingCursor
FETCH NEXT FROM AuditingCursor INTO @OperatorId
WHILE @@FETCH_STATUS = 0
BEGIN
	-- 是否有修改他人草稿的权限  0.有 1.无
	DECLARE @ifCanEditOtherDraft INT
	EXEC @ifCanEditOtherDraft = GP_CheckLimit @OperatorId, 135
	
	-- 是否有审核他人草稿的权限  0.有 1.无
	DECLARE @AuditingOtherDraft int	
	EXEC @AuditingOtherDraft = GP_CheckLimit @OperatorID,467
	
	DECLARE @checkeWhere VARCHAR(50)
	IF @ifCanEditOtherDraft = 0 OR @AuditingOtherDraft = 0
		SET @checkeWhere = '%%'
	ELSE
		SET @checkeWhere = @OperatorId
	
	DECLARE @ifAlerm INT
	SET @ifAlerm = 0
	IF @BillType IN (17,21)-- AND @AuditingType = 1
	BEGIN
		-- 检查仓库权限是否有效   0.有效   1.无效
		DECLARE @StockLimit  INT
		EXEC @StockLimit = GP_CheckLimit @OperatorID,454
		-- 调拨单中，仓库的权限无效
		IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'MoveInOutKLimit' AND Value = '0') OR @StockLimit = 1
		BEGIN
			IF EXISTS(
				SELECT	TOP 1 1
				FROM	BillIndex
				WHERE	BillNumberId = @BillNumberId
						AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorId))
						AND (KTypeID IN (SELECT * FROM F_GetManDetailKType(@OperatorId)) OR KTypeID2 IN (SELECT * FROM F_GetManDetailKType(@OperatorId)))
						AND checke LIKE @checkeWhere
			)
				SET @ifAlerm = 1
		END
		ELSE
		BEGIN
			IF EXISTS(
				SELECT	TOP 1 1
				FROM	BillIndex
				WHERE	BillNumberId = @BillNumberId
						AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorId))
						AND (KTypeID IN (SELECT * FROM F_GetManDetailKType(@OperatorId)) AND KTypeID2 IN (SELECT * FROM F_GetManDetailKType(@OperatorId)))
						AND checke LIKE @checkeWhere
			)
				SET @ifAlerm = 1
		END
	END
	ELSE IF @BillType IN (300,301)	-- 订单
	BEGIN
		IF EXISTS(
			SELECT	TOP 1 1
			FROM	OrderIndex
			WHERE	BillNumberId = @BillNumberId
					AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorId))
					AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorId))
					AND KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorId))
		)
			SET @ifAlerm = 1
	END
	ELSE IF @BillType IN (57)
	BEGIN
		IF EXISTS(
			SELECT BillNumberId 
			FROM AdPriceBill
			WHERE BillNumberId=@BillNumberId AND ChangeAllStock=1
		)
		BEGIN
			IF EXISTS(
			SELECT	TOP 1 1
			FROM	BillIndex
			WHERE	BillNumberId = @BillNumberId
					AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorId))
					AND (BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorId)) OR ISNULL(BTypeId,'')='')
					AND (KTypeId='00000')
					AND checke LIKE @checkeWhere
			)
				SET @ifAlerm = 1
		END
		ELSE
		BEGIN
			IF EXISTS(
			SELECT	TOP 1 1
			FROM	BillIndex
			WHERE	BillNumberId = @BillNumberId
					AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorId))
					AND (BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorId)) OR ISNULL(BTypeId,'')='')
					AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorId)) OR ISNULL(KTypeId,'')='')
					AND checke LIKE @checkeWhere
			)
				SET @ifAlerm = 1
		END
	END
	ELSE IF @BillType IN (328,327)	--门店单据
	BEGIN
		IF EXISTS(
			SELECT	TOP 1 1
			FROM	PosAllotApplyBillIndex
			WHERE	BillNumberId = @BillNumberId
					AND ApplyEtypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorId))					
					AND (KTypeID IN (SELECT * FROM F_GetManDetailKType(@OperatorId)) OR InKtypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorId)))
		            AND checke LIKE @checkeWhere
		        )
			SET @ifAlerm = 1
	END
	ELSE
	BEGIN
		--2018-08-15 谢吉康 以前的算法不合理，优化
		DECLARE @BTypeId VARCHAR(500)
		
		SELECT @BTypeId = BTypeID FROM BillIndex WHERE BillNumberid = @BillNumberId		
		
		IF @BTypeId <> ''
		BEGIN
			IF EXISTS(
				SELECT	TOP 1 1
				FROM	BillIndex B
				INNER JOIN (SELECT * FROM F_GetManDetailEType(@OperatorId)) E ON B.ETypeId = E.TypeId
				INNER JOIN (SELECT * FROM F_GetManDetailBTypeForAudit(@OperatorId,@BTypeId)) MB ON MB.TypeId = B.btypeid
				INNER JOIN (SELECT * FROM F_GetManDetailKType(@OperatorId)) MK ON (MK.TypeId = B.KTypeId OR ISNULL(KTypeId,'')='')			
				WHERE	BillNumberId = @BillNumberId
						AND checke LIKE @checkeWhere
			)
			SET @ifAlerm = 1
		END
		ELSE
		BEGIN
			IF EXISTS(
				SELECT	TOP 1 1
				FROM	BillIndex B
				INNER JOIN (SELECT * FROM F_GetManDetailEType(@OperatorId)) E ON B.ETypeId = E.TypeId				
				INNER JOIN (SELECT * FROM F_GetManDetailKType(@OperatorId)) MK ON (MK.TypeId = B.KTypeId OR ISNULL(KTypeId,'')='')			
				WHERE	BillNumberId = @BillNumberId
						AND checke LIKE @checkeWhere
			)		
			SET @ifAlerm = 1
		END			
	END
	
	IF @ifAlerm = 1
	BEGIN
		IF @AuditingType = 1
		BEGIN
			UPDATE	AuditingFlowDetail
			SET 	AuditingAlerm = 1
			WHERE	AuditingId = @AuditingId
					AND ETypeId = @OperatorId
					AND AuditingStep IN (SELECT TOP 1 AuditingStep FROM #temp WHERE PassFlag=0 ORDER BY AuditingStep)
		END

		IF @AuditingType = 3
		BEGIN
			UPDATE	AuditingFlowDetail
			SET 	AuditingAlerm = 1
			WHERE	AuditingId = @AuditingId
					AND ETypeId = @OperatorId
					AND AuditingStep IN (SELECT AuditingStep FROM #temp WHERE PassFlag=0 GROUP BY AuditingStep)
		END
	END
	FETCH NEXT FROM AuditingCursor INTO @OperatorId
END
CLOSE AuditingCursor
DEALLOCATE AuditingCursor

DROP TABLE #temp
--成功，退出
COMMIT TRAN

--处理同一个人审核人的情况
IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'samepersonchecked' AND Value = '1')
BEGIN	
	IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType AND AuditingType = 3) AND EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail WHERE BillType = @BillType AND AuditingStep <> 0 AND ETypeID = @OperatorETypeID)	--会签审核
	BEGIN		
		EXEC GP_BillAuditingDeal @OperatorETypeID,@BillNumberId,'1','自动审核通过',@BillIndexType,'',''
	END
	ELSE
	BEGIN	
		--处理审核消息
		DECLARE @nextStep			INT
				
		IF EXISTS(SELECT TOP 1 AuditingStep FROM AuditingBillDetail WHERE BillNumberID = @BillNumberId AND BillIndexType = @BillIndexType)
			SELECT TOP 1 @nextStep = AuditingStep + 1 FROM AuditingBillDetail WHERE BillNumberID = @BillNumberId AND BillIndexType = @BillIndexType ORDER BY AuditingStep DESC
		ELSE 
			SET @nextStep = 1
			
		SELECT * INTO #AuditingFlowDetail FROM AuditingFlowDetail WHERE BillType = @BillType AND AuditingStep <> 0 AND ETypeID = @OperatorETypeID
		
		WHILE EXISTS(SELECT TOP 1 1 FROM #AuditingFlowDetail WHERE AuditingStep = @nextStep)
		BEGIN
			EXEC GP_BillAuditingDeal @OperatorETypeID,@BillNumberId,'1','自动审核通过',@BillIndexType,'',''
			SET @nextStep += 1
		END
		
		DROP TABLE #AuditingFlowDetail
	END		
END

--单据审核流程完成后自动过账
DECLARE @RE INT        
EXEC @RE = GP_CheckLimit @OperatorETypeID,2659

--处理价格跟踪
IF @BillType IN (184,185,300,301)
BEGIN
      EXEC dbo.GP_BatchPassPT @billnumberid=@BillNumberId,@billtype=@BillType
END
--自动过账
IF @billtype NOT IN(184,185,300,313,204,185,301,22,326,162,163) AND EXISTS(SELECT TOP 1 1 FROM dbo.AuditingBill WHERE BillNumberID = @BillNumberId AND BillIndexType = @BillIndexType AND IfAudit = 1)
	AND @RE = 0
BEGIN
	EXEC dbo.Gp_Auditing @nBillID = @BillNumberId, -- numeric
		@szCheckMan = @Checke, -- varchar(50)
		@szPID = '', -- varchar(1000)
		@chvOpID = @OperatorETypeID, -- varchar(50)
		@KTypeID = '', -- varchar(50)
		@billtype = @BillType, -- int
		@voucherMsg = '', -- varchar(50)
		@vipcentinfo='',
		@AssetMsg='',
	   @VipCardCode = '' ,--VARCHAR(200) 
       @CommissionConfirm  = 0 ,--INT
       @strReturnBillCode  = '' --VARCHAR(200)
		
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'BillCodeCreateTime' AND Value = 2)
		EXEC dbo.GP_SaveBillCode_Seed @intBillNumberID=@BillNumberId,@intBillType=@BillType,@dBillDate=@billdate,@strBillCode=@BillCode
		
	IF(@BillType IN(17,21,404,327,328))	--没有btypeid 的不要插入，否则报错
	begin
	INSERT INTO BillOperateLog(billnumberid,operatetype,etypeid,OperateTime,ip,billcode,billdate,ifcheck,ntotalmoney,billtype) 
	VALUES(@billnumberid,'自动审核过账',@OperatorETypeID,GETDATE(),'',@billcode,@billdate,'t',0,@billtype)	
	END
	ELSE
	BEGIN
	INSERT INTO BillOperateLog(billnumberid,operatetype,etypeid,OperateTime,ip,billcode,billdate,ifcheck,btypeid,ntotalmoney,billtype) 
	VALUES(@billnumberid,'自动审核过账',@OperatorETypeID,GETDATE(),'',@billcode,@billdate,'t',@btypeid,0,@billtype)	
	END
	
	--自动审核过账,反写一大堆数量,状态等.正常过账反写以前是写在代码里面的，没有在存储过程里，所以要单独写出来	
    EXEC Gp_Auditing_UpdateQtyorState @BillNumberId, @BillType
END	

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-12-15
	描述：文件管理系统新增文件夹
*/
CREATE PROCEDURE Gp_AddFolder
(
	@FullName	[varchar](200),			--文件夹名称
	@ParId		[varchar](50),			--父目录id
	@CurrentLevel [int],				--当前层级
	@etypeid	[varchar](50)			--创建者id
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @nReturntype INT,
        @nTypeid [varchar](50),
        @nSoncount INT,
        @nSonnum INT,
        @leveal SMALLINT

--生成子节点的typeid
EXEC @nReturntype= Gp_createId @ParId, 'DocFilePath', @nTypeid OUT,
        @nSonnum OUT, @nSoncount OUT
if @nReturntype=-1 
begin
	RAISERROR('V文件夹的分类层数过多!',16,1)
	RETURN
end
if @nReturntype=-2 
begin
	RAISERROR('保存文件夹发生错误!请确认后重试!',16,1)
	RETURN
end

--生成层级
SELECT  @leveal = leveal
FROM    DocFilePath
WHERE   typeid = @ParId

SELECT  @leveal = @leveal + 1

IF EXISTS (	SELECT	FullName 
			FROM	DocFilePath 
			WHERE	etypeid = @etypeid 
					AND FullName = @FullName
					AND leveal = @CurrentLevel + 1 
					AND LEFT(typeid,5) = LEFT(@ParId,5))
BEGIN
	RAISERROR('该文件夹已存在!请确认后重试!',16,1)
	RETURN
END
	
IF LEFT(@ParId,5)='00001'
SET @etypeid = ''
BEGIN TRAN insertproc
    --更改父节点的sonnum和soncount
    UPDATE  DocFilePath
    SET     sonnum = @nSonnum + 1,
            soncount = @nSoncount + 1
    WHERE   typeid = @ParId
            
	INSERT INTO [dbo].[DocFilePath] 
	  ( 
		[typeid],
		[Parid],
		[leveal],
		[sonnum],
		[soncount],
		[FullName],
		[etypeid]
	)	 
	VALUES 
	 (  
		@nTypeid,
		@ParId,
		@leveal,
		0,
		0,
		@FullName,
		@etypeid
	)
IF @@rowcount = 0 
BEGIN
    ROLLBACK TRAN insertproc 
    RAISERROR('保存文件夹发生错误!请确认后重试!',16,1)
END
COMMIT TRAN insertproc

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		添加操作员
-- 最后修改作者：	谢吉康
-- 最后修改时间：	2003-07-31
-- ========================================================================
CREATE         PROCEDURE GP_AddNewLogin
(
	@szETypeID		VARCHAR(MAX),	-- 职员 ID 值
	@operatorId     VARCHAR(50),	-- 当前操作员
	@IsSYS			BIT = 0	,		-- 是否超级管理员
	@isPos			INT =0          --添加的是什么类型的操作员 0为erp 1为pos	 9.7.1---新增
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********
-- 数据表 LoginUser 中操作员数
DECLARE @intLoginUserCount INT
DECLARE @userCount INT --新增操作员数
SELECT	@intLoginUserCount = COUNT(*)
FROM	LoginUser
WHERE	IsErp = 1
--如果添加的操作员中已有了 则返回
IF  EXISTS(SELECT	F.TypeId
FROM	F_GetAllManagerBaseTypeId(@szETypeID,3,@operatorId) F,
		Employee E
WHERE	F.TypeId = E.TypeId
		AND E.sonnum = 0
		AND E.deleted = 0
	
		AND F.TypeId  IN 
		(
			SELECT	ETypeId
			FROM	LoginUser  WHERE isErp=@isPos
		))

RETURN -99


--添加操作员支持多选，排除已经有的操作员 2012-02-23
CREATE TABLE #User(TypeId VARCHAR(50))

INSERT INTO #User(TypeId)
SELECT	F.TypeId
FROM	F_GetAllManagerBaseTypeId(@szETypeID,3,@operatorId) F,
		Employee E
WHERE	F.TypeId = E.TypeId
		AND E.sonnum = 0
		AND E.deleted = 0
		AND F.TypeId NOT IN 
		(
			SELECT	ETypeId
			FROM	LoginUser
		)
	

				    
DECLARE @N int, @intDogUserCount int, @intVersion int
-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -2

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

-- 判断软件狗用户数
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 3	-- 检查用户数

IF @N IS NULL RETURN -2

--本次新增的用户数
SELECT @userCount=COUNT(*) FROM #User

IF @intVersion IN (2,3,5,7,9,11,13,15)	-- 试用版 V3/A8是5用户 V1是3用户
	BEGIN
		IF  @isPos=0
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE subname = 'Proinfo' AND SubValue = '4')
				SET @intDogUserCount = 3		
			ELSE
				SET @intDogUserCount = 5
				
			IF @intLoginUserCount + @userCount -1 > @intDogUserCount RETURN -51
		END		
	END
ELSE
	BEGIN
		IF @isPos=0
		BEGIN	 
			SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
			IF ( 3 & @N <> 3 ) RETURN -2
			IF @intLoginUserCount - 1 >= @intDogUserCount RETURN -50
			IF @intLoginUserCount + @userCount - 1 > @intDogUserCount RETURN -50
		END	
	END		

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - End	********
IF NOT EXISTS(SELECT * FROM #User) RETURN

--判断POS操作员是否超过限制 9.7.1---新增
DECLARE @posDefine  INT,
		@posCount	INT
		
SELECT @posDefine = SubValue FROM SYSDATA WHERE SubName = 'PosDefine'
SELECT @posCount = COUNT(*) FROM LoginUser WHERE etypeid <> '00001' AND ISNULL(isPos,'0') = '1'


IF @isPos=0
	INSERT INTO LoginUser (
				ETypeID,
				BTypeID,
				SysID,isErp,isPos
	)
	SELECT	TypeID,
			BTypeID,
			@IsSYS,1,0
	FROM	Employee
	WHERE	TypeID IN (
							SELECT typeid FROM #User
					   )
ELSE
BEGIN
	INSERT INTO LoginUser (
				ETypeID,
				BTypeID,
				SysID,isErp,isPos
	)
	SELECT	TypeID,
			BTypeID,
			@IsSYS,0,1
	FROM	Employee
	WHERE	TypeID IN (
							SELECT typeid FROM #User
				   )	
end				   			   
-----9.7.1---新增
UPDATE	LoginUser
SET		Lim = ' '
WHERE	EtypeID IN (
						SELECT typeid FROM #User
				   )
		
	--END

IF @@ROWCOUNT = 0 RETURN -2

IF @IsSYS = 1
	BEGIN
		UPDATE	LoginUser
		SET		Lim = (
				SELECT	Lim
				FROM	LoginUser
				WHERE	ETypeID = '00001'
			)
		WHERE	ETypeID IN (
								SELECT typeid FROM #User
							)
	END
	
--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'

DROP TABLE #User

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddOrEditAcItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_AddOrEditAcItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_items 1:新增 2:编辑
-- 时间：	2013-01-30
-- 作者：	GLJ
--TypeName	B:现金银行 G：其他收入 E：费用类型 F：固定资产 C：资产项 L:负债项
-- ========================================================================
CREATE PROC [Gp_AddOrEditAcItems]
(
	@NId			INT,				--ID
	@ParID			VARCHAR(50),		--父级ntypeid
	@UserCode		VARCHAR(200),		--编号
	@FullName		VARCHAR(200),		--名称
	@Comment		VARCHAR(500),		--描述
	@CreateBank		VARCHAR(400)='',	--开户银行
	@BankType		VARCHAR(200)='',	--银行类型
	@IsBank			INT=0,				--是否是银行		
	@TypeName		VARCHAR(2),			--TypeNAME 类别
	@OperatorID		VARCHAR(50),		-- 操作员
	@Type			INT,				--1:新增 2：编辑
	@jmname			VARCHAR(200) = '',	--简名
	@pycode			VARCHAR(500) = ''	--拼音码
)
--@encode$--

AS
SET NOCOUNT ON

DECLARE 
	@Name VARCHAR(200),--编号、名称 是否重复 变量
	@NIDS INT,			--新增子增加ID
	@ErrorCount INT =0,	
	@XiWaMaxNumber INT=0

--处理拼音码	
IF @pycode = ''
BEGIN
	SET @pycode = (SELECT dbo.fun_getPY(@FullName))
END	
		

--===================================判断项目中编号/名称是否重复 【begin】===========================
--判断编号是否重复
IF(ISNULL(@nid,0)>0)
	SELECT @Name=FullName FROM Ac_Items WHERE  UserCode=@usercode AND nId<>@nid
ELSE
	SELECT @Name=FullName FROM Ac_Items WHERE  UserCode=@usercode
	
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同 ，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1) RETURN
	END
	
--判断名称是否重复
IF(ISNULL(@nid,0)>0)
	SELECT @Name=FullName FROM Ac_Items WHERE  FullName=@fullname AND nId<>@nid
ELSE
	SELECT @Name=FullName FROM Ac_Items WHERE  FullName=@fullname
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG1 VARCHAR(100)='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END	
--===================================判断项目中编号/名称是否重复 【begin】===========================


SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items
IF(@type=1)
	BEGIN
		IF(ISNULL(@ParID,'')<>'')
			BEGIN
				DECLARE @PNId INT=(SELECT TOP 1 NID FROM Ac_Items WHERE nTypeId=@ParID)-- 父级ID
				
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE Sysrow=1 AND nTypeId=@ParID and IsModify=0 AND @ParID<>'000010000700001')
					BEGIN
						----待摊费用项目允许分类
						--IF NOT EXISTS(SELECT TOP 1 1 FROM f_split('000010000700001',',') WHERE a IN (@ParID))
						--	BEGIN
								RAISERROR('该父级为系统项目，不允许分类！',16,1)RETURN
							--END
					END
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE Deleted=1  AND nTypeId=@ParID)
					BEGIN
						RAISERROR('该父级信息已经停用，不允许分类！',16,1)RETURN
					END	
				--判断父级是否使用
				DECLARE @RET INT=0
				SET @RET=(SELECT dbo.Fn_GetIsUse_Items(@PNId,2))
				IF @RET>0
					BEGIN
						RAISERROR('该父级信息已经使用，不允许分类！',16,1)RETURN
					END	
				IF(@TypeName='B')--现金银行
					BEGIN
						IF EXISTS(SELECT TOP 1 1 FROM PosInfo WHERE (BankCardID =@PNId OR CashID=@PNId OR alipayid=@PNId OR wxpayid=@PNId OR allinpayid=@PNId  OR JFPayId=@PNId))
							BEGIN
								RAISERROR('该信息已关联POS，不允许分类！',16,1)RETURN
							END	
					END
			ELSE 
				BEGIN
					DECLARE @RET1 INT=0
					SET @RET1=(SELECT dbo.Fn_GetIsUse_Items(@PNId,4))
					IF @RET1>0
						BEGIN
							RAISERROR('该父级已经使用，不允许分类！',16,1)RETURN
						END	
				END
			END
			 --B:现金银行 G：其他收入 E：费用类型 F：固定资产 C：资产项 L:负债项
			 --=================防止@parid为空的情况，赋值默认值
			 IF(ISNULL(@ParID,'')='')
				BEGIN
					IF (@TypeName = 'B')
						SET @ParID = '0000100004';
					ELSE IF (@TypeName= 'G')
						SET @ParID = '0000300003';
					ELSE IF  (@TypeName = 'E')
						SET @ParID = '0000400003';
					ELSE IF  (@TypeName = 'F')
						SET @ParID = '0000100002';
					ELSE IF  (@TypeName = 'C')
						SET @ParID = '00001';
					ELSE IF  (@TypeName = 'L')
						SET @ParID = '00002';
                END
                
			--声明变量
			DECLARE 
				@level				INT=(SELECT TOP 1 Leveal FROM Ac_Items WHERE nTypeId=@ParID),			-- 父级level
				
				@nReturntype		VARCHAR(50),	--
				@newTypeid			VARCHAR(50),	--新增节点表中TypeID
				@nSonnum			INT,		
				@nSoncount			INT
				
				--得到父级TypeId/level
				
				
				--得到当前新增数据TypeID
				EXEC @nReturntype= Gp_CreateId_AcItem @ParID, 'Ac_Items', @newTypeid OUT,@nSonnum OUT, @nSoncount OUT
				IF @nReturntype = -1
					BEGIN
						RAISERROR('分类不能超过10层',16,1)
						RETURN -1
					END
				ELSE IF @nReturntype = -2
					BEGIN
						RAISERROR('无法添加',16,1)
						RETURN -1	
					END
		IF(@TypeName='B' AND @ParID NOT LIKE '0000100003%') SET @IsBank=1		
		INSERT INTO Ac_Items
			(
				[nTypeId],
				[nParId],
				[UserCode],
				[FullName],
				[Comment],
				[PyCode],
				[CreateBank],
				[BankType],
				[IsBank],
				[Deleted],
				[TypeName],
				[Sysrow],
				IsModify,
				[TypeId],
				[ParId],
				[Leveal],
				[SonNum],
				[SonCount],
				[Name],
				[XiWaMaxNumber]
			)
		VALUES
			(
				@newTypeid,
				@ParID,
				@usercode,
				@fullname,
				@comment,
				@PyCode,
				@CreateBank,
				@BankType,
				@IsBank,
				0,
				@TypeName,
				0,
				1,
				'',
				'',
				@level+1,
				0,
				0,
				@jmname,
				@XiWaMaxNumber
				)
		SET @NIDS=SCOPE_IDENTITY();
		SET @ErrorCount+=@@ERROR
		
		
		--修改父级SonCount/SonNum字段
		UPDATE Ac_Items SET SonCount+=1,SonNum+=1 WHERE nTypeId=@ParID
		SET @ErrorCount+=@@ERROR
		
		----插入权限外的分支详细信息
		INSERT INTO Ac_Items_Detail(nId,STypeId,ATypeId,DepATypeId,DisATypeId)
		SELECT @NIDS,TypeId,'','','' 
		FROM SType 
		WHERE 
			TypeId<>'00000' 
			AND TypeId NOT IN(
								SELECT S.TypeId FROM SType s
								INNER JOIN dbo.F_GetAllManagerBaseTypeId('',11,@OperatorID) F ON F.TypeId=s.TypeId
								WHERE 
									s.deleted=0 AND
									s.sonnum=0
							)
		SET @ErrorCount+=@@ERROR
		IF(SELECT COUNT(*) FROM Ac_Items_Detail WHERE XiWaMaxNumber=1)>1
			BEGIN
				--修改Ac_Items_Detail缓存字段值
				SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items_Detail
				UPDATE Ac_Items_Detail SET XiWaMaxNumber=@XiWaMaxNumber,@XiWaMaxNumber+=1 WHERE XiWaMaxNumber=1
				SET @ErrorCount+=@@ERROR
			END
	END
ELSE IF(@type=2)
	BEGIN
		UPDATE Ac_Items 
		SET 
			UserCode=@UserCode,
			FullName=@FullName,
			PyCode = @pycode,
			CreateBank=@CreateBank,
			BankType=@BankType,
			Comment=@Comment,
			Name = @jmname,
			XiWaMaxNumber=@XiWaMaxNumber
		WHERE
			nId=@nid
		SET @ErrorCount+=@@ERROR
	END	

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='信息添加失败！'
		IF(@type=2)
			SET @MSG2='信息修改失败！'
		RAISERROR(@MSG2,16,1)	
	END
ELSE 
	BEGIN
		IF(@type=2)
			SET @NIDS=@nid
		----更新父级缓存
		--EXEC Gp_UpdateAcItemNParidXiWaMaxNumber @nid	
		
		RETURN @NIDS
	END
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddOrEditAssistCheckItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_AddOrEditAssistCheckItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_Assist_CheckItems 1:新增 2:编辑
-- 时间：	2015-09-28
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_AddOrEditAssistCheckItems
(
	@AscIds			INT,				--ID
	@FullName		VARCHAR(200),		--名称
	@OperatorID		VARCHAR(50),		--当前操作员ID
	@Type			INT					--1:新增 2：编辑
)
--@encode$--

AS
SET NOCOUNT ON

DECLARE
	@UserCode	VARCHAR(200),	--编号
	@Name		VARCHAR(200),	--是否重复 名称
	@Error		INT=0

--===================================判断辅助核算编号/名称是否重复 【begin】===========================
IF (SELECT COUNT(*) FROM Ac_Assist_CheckItems)>=9 AND @Type=1
	BEGIN
		RAISERROR('自定义辅助核算类型控制仅能增加5个！',16,1) RETURN
	END
--判断名称是否重复
IF(@Type=1)
	SELECT @Name=FullName FROM Ac_Assist_CheckItems WHERE  FullName=@fullname
ELSE
	SELECT @Name=FullName FROM Ac_Assist_CheckItems WHERE  FullName=@fullname AND AscIds<>@AscIds
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG1 VARCHAR(100)='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END	
--===================================判断辅助核算编号/名称是否重复 【begin】===========================
BEGIN TRAN 
IF(@Type=1)--新增
	BEGIN
		SELECT @UserCode='0'+CAST(MAX(UserCode)+1 AS VARCHAR(200)) FROM Ac_Assist_CheckItems
		INSERT INTO Ac_Assist_CheckItems(UserCode,FullName) VALUES(@UserCode,@FullName)
		SELECT @AscIds=@@IDENTITY
		SET @Error+=@@ERROR
		
		INSERT INTO Ac_Assist_CheckItemsDetail
		(
			TypeId,
			ParId,
			Leveal,
			SonNum,
			SonCount,
			AscIds,
			UserCode,
			FullName,
			CreatedBy,
			CreatedDate,
			Comment
		)
		VALUES
		(
			REPLICATE('0',3) +@UserCode ,
			'root',
			0,
			0,
			0,
			@AscIds,
			@UserCode+'root',
			@UserCode+'root',
			@OperatorID,
			GETDATE(),
			''
		)
		SET @Error+=@@ERROR
		--修改自定义公式
		UPDATE UFO_DefineFunctions SET Format=SUBSTRING(Format,1,LEN(Format)-2)+@FullName+'='+@FullName+'编号%")' WHERE Code IN('QC','QM','XFS','LFS','NCJ','NCD','QMJ','QMD')
		SET @Error+=@@ERROR
	END
ELSE IF(@Type=2)--编辑
	BEGIN
		SELECT @Name=FullName FROM Ac_Assist_CheckItems WHERE AscIds=@AscIds
		UPDATE Ac_Assist_CheckItems SET FullName=@FullName WHERE AscIds=@AscIds
		SET @Error+=@@ERROR
		
		--修改自定义公式
		UPDATE UFO_DefineFunctions SET Format=REPLACE(Format,@Name,@FullName) WHERE Code IN('QC','QM','XFS','LFS','NCJ','NCD','QMJ','QMD')
		SET @Error+=@@ERROR
	END

	
IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddOrEditAssistCheckItemsDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_AddOrEditAssistCheckItemsDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_Assist_CheckItemsDetail 1:新增 2:编辑
-- 时间：	2015-09-28
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_AddOrEditAssistCheckItemsDetail
(
	@TypeId			VARCHAR(50),		--ID
	@ParId			VARCHAR(50),
	@AscIds			INT,				--类型ID
	@UserCode		VARCHAR(200),		--编号
	@FullName		VARCHAR(200),		--名称
	@CreatedBy		VARCHAR(50),		--创建人
	@Comment		VARCHAR(1000),		--备注
	@Type			INT					--1:新增 2：编辑
)
--@encode$--

AS
SET NOCOUNT ON

DECLARE 
	@Name		VARCHAR(200),	--是否重复 名称
	@ParSonCount	INT=0,		--父级子级个数
	@MSG1		VARCHAR(500),
	@Level		INT=0,			--父级ID
	@Error		INT=0,
	@AsUserCode	VARCHAR(200)	--类型编号

SELECT @AsUserCode=UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@AscIds
--===================================判断辅助核算编号/名称是否重复 【begin】===========================
IF(ISNULL(@ParId,'')='')
	BEGIN
		SELECT @Level=Leveal,@ParSonCount=SonCount+1,@ParId=TypeId FROM Ac_Assist_CheckItemsDetail WHERE AscIds=@AscIds AND ParId='root'
		
	END
ELSE 
	BEGIN
		SELECT @Level=Leveal,@ParSonCount=SonCount+1,@ParId=TypeId FROM Ac_Assist_CheckItemsDetail WHERE AscIds=@AscIds AND TypeId=@ParId
	END
IF(@Level>=9)
	BEGIN
		RAISERROR('系统最大的子项目级别为9级！',16,1)RETURN
	END	
	
--判断编号是否重复
IF(@Type=1)
	SELECT @Name=FullName FROM Ac_Assist_CheckItemsDetail WHERE  UserCode=@UserCode
ELSE
	SELECT @Name=FullName FROM Ac_Assist_CheckItemsDetail WHERE  UserCode=@UserCode AND TypeId<>@TypeId
IF(ISNULL(@Name,'')<>'')
	BEGIN
		SET @MSG1='与【'+@Name+'】的编号相同，请另取一个编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END	
--判断名称是否重复
IF(@Type=1)
	SELECT @Name=FullName FROM Ac_Assist_CheckItemsDetail WHERE  FullName=@fullname
ELSE
	SELECT @Name=FullName FROM Ac_Assist_CheckItemsDetail WHERE  FullName=@fullname AND TypeId<>@TypeId
IF(ISNULL(@Name,'')<>'')
	BEGIN
		SET @MSG1='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END	

--===================================判断辅助核算编号/名称是否重复 【begin】===========================
BEGIN TRAN 
IF(@Type=1)--新增
	BEGIN
		UPDATE Ac_Assist_CheckItemsDetail SET SonNum+=1,SonCount+=1 WHERE TypeId=@ParId
		SET @Error+=@@ERROR
				
		EXEC Gp_CreateTypeId @ParId,@ParSonCount,@TypeId OUTPUT				
		SET @Error+=@@ERROR
		INSERT INTO Ac_Assist_CheckItemsDetail
		(
			TypeId,
			ParId,
			Leveal,
			SonNum,
			SonCount,
			AscIds,
			UserCode,
			FullName,
			CreatedBy,
			CreatedDate,
			Comment
		)
		VALUES
		(
			@TypeId,
			@ParId,
			@Level+1,
			0,
			0,
			@AscIds,
			@UserCode,
			@FullName,
			@CreatedBy,
			GETDATE(),
			@Comment
		)
		SET @Error+=@@ERROR
	END
ELSE IF(@Type=2)--编辑
	BEGIN
		UPDATE Ac_Assist_CheckItemsDetail
		SET 
			UserCode=@UserCode,
			FullName=@FullName,
			Comment=@Comment
		WHERE TypeId=@TypeId
		SET @Error+=@@ERROR
	END
	
IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddOrEditStockPickBillInput]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_AddOrEditStockPickBillInput]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	StockPickBillInput 保存拣货单 【调出库单】查询条件
-- 时间：	2018-07-16
-- 作者：	GLJ

-- ========================================================================
CREATE PROC [Gp_AddOrEditStockPickBillInput]
(
	@OperatorId		VARCHAR(50),--当前操作员
	@BillType		VARCHAR(500),--单据类型
	@BillTypeFlag	INT--查询单据类型 413-拣货 412-上架单
)
AS
SET NOCOUNT ON


IF EXISTS(SELECT TOP 1 1 FROM StockPickBillInput WHERE OperatorId=@OperatorId AND BillTypeFlag=@BillTypeFlag)
	BEGIN
		UPDATE StockPickBillInput
		SET 
			BillType=@BillType
		WHERE 
			OperatorId=@OperatorId
			AND BillTypeFlag=@BillTypeFlag
		
	END
ELSE 
	BEGIN
		INSERT INTO StockPickBillInput
		(
			OperatorId,
			BillType,
			BillTypeFlag
		)
		VALUES
		(
			@OperatorId,
			@BillType,
			@BillTypeFlag
		)
	END
	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddOrEditTe_Bank]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Gp_AddOrEditTe_Bank
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Te_Bank 新增or编辑 出纳管理-金融机构
-- 时间：	2014-05-09
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_AddOrEditTe_Bank
(
	@Id			INT=0,				--id
	@UserCode	VARCHAR(26)='',		--编号
	@FullName	VARCHAR(66)='',		--名称
	@Address	VARCHAR(1000),		--地址
	@PhoneNum	VARCHAR(50),		--电话
	@ContactMan	VARCHAR(50),				--联系人
	@Comment	VARCHAR(1000),		--备注
	@Type		INT					--1 新增  2编辑
	
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE 
	@XiWaMaxNumber INT=0,
	@Error INT=0,
	@Name VARCHAR(66)='',
	@MSG VARCHAR(100)=''

--判断编号是否重复
IF @Type=1
	SELECT @Name=FullName FROM Te_Bank WHERE UserCode=@UserCode
ELSE 
	SELECT @Name=FullName FROM Te_Bank WHERE UserCode=@UserCode AND Id<>@Id
IF ISNULL(@Name,'')<>''
BEGIN
	SET @MSG='与【'+@Name+'】的编号相同 ，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
	RAISERROR(@MSG,16,1) RETURN
END
--判断名称是否重复
IF @Type=1
	SELECT @Name=FullName FROM Te_Bank WHERE FullName=@FullName
ELSE 
	SELECT @Name=FullName FROM Te_Bank WHERE FullName=@FullName AND Id<>@Id
IF ISNULL(@Name,'')<>''
BEGIN
	SET @MSG='与【'+@Name+'】的名称相同 ，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
	RAISERROR(@MSG,16,1) RETURN
END

IF(@Type=1)
BEGIN
	INSERT INTO Te_Bank
	(
		UserCode,
		FullName,
		[Address],
		PhoneNum,
		ContactMan,
		Comment,
		IsSys
	)
	VALUES
	(
		@UserCode,
		@FullName,
		@Address,
		@PhoneNum,
		@ContactMan,
		@Comment,
		0
	)
	SELECT @Error=@@ERROR
END
ELSE
BEGIN
	UPDATE Te_Bank
	SET 
		UserCode=@UserCode,
		FullName=@FullName,
		[Address]=@Address,
		PhoneNum=@PhoneNum,
		ContactMan=@ContactMan,
		Comment=@Comment
	WHERE Id=@Id
	SELECT @Error=@@ERROR
END
IF(@Error<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='信息添加失败！'
		IF(@type=2)
			SET @MSG2='信息修改失败！'
		RAISERROR(@MSG2,16,1)
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddOrEditTe_BankAccount]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Gp_AddOrEditTe_BankAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Te_BankAccount 新增or编辑 出纳管理-银行账户
-- 时间：	2014-05-09
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_AddOrEditTe_BankAccount
(
	@Id			INT=0,				--id
	@UserCode	VARCHAR(26)='',		--编号
	@FullName	VARCHAR(66)='',		--名称
	@AccountNumber VARCHAR(50),		--银行账号
	@STypeId	VARCHAR(50),		--分支机构
	@BankId		INT,				--金融机构
	@ATypeId	VARCHAR(50),		--会计科目
	@CreateDate	DATETIME,			--开户时间
	--@Cid		INT,			--币种
	@Comment	VARCHAR(1000),		--备注
	@Type		INT					--1 新增 3编辑
	
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE 
	@XiWaMaxNumber INT=0,
	@Error INT=0,
	@Name VARCHAR(66)='',
	@MSG VARCHAR(100)='',
	@Cid	INT		--币种

IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND deleted=1)
	BEGIN
		SET @MSG='该分支机构已被停用，不能进行操作！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1) RETURN
	END
--判断编号是否重复
IF @Type=1
	SELECT @Name=FullName FROM Te_BankAccount WHERE UserCode=@UserCode
ELSE 
	SELECT @Name=FullName FROM Te_BankAccount WHERE UserCode=@UserCode AND Id<>@Id
IF ISNULL(@Name,'')<>''
BEGIN
	SET @MSG='与【'+@Name+'】的编号相同 ，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
	RAISERROR(@MSG,16,1) RETURN
END
--判断名称是否重复
IF @Type=1
	SELECT @Name=FullName FROM Te_BankAccount WHERE FullName=@FullName
ELSE 
	SELECT @Name=FullName FROM Te_BankAccount WHERE FullName=@FullName AND Id<>@Id
IF ISNULL(@Name,'')<>''
BEGIN
	SET @MSG='与【'+@Name+'】的名称相同 ，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
	RAISERROR(@MSG,16,1) RETURN
END
--判断银行账号是否重复
IF @Type=1
	SELECT @Name=FullName FROM Te_BankAccount WHERE AccountNumber=@AccountNumber
ELSE 
	SELECT @Name=FullName FROM Te_BankAccount WHERE AccountNumber=@AccountNumber AND Id<>@Id
IF ISNULL(@Name,'')<>''
BEGIN
	SET @MSG='与【'+@Name+'】的账号相同 ，请重新输入账号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
	RAISERROR(@MSG,16,1) RETURN
END
IF EXISTS(SELECT TOP 1 1 FROM AC_Account WHERE TypeId=@AtypeId AND Deleted=1 AND StypeId=@STypeId)
BEGIN
	SET @MSG='会计科目已被停用,请重新选择！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
	RAISERROR(@MSG,16,1) RETURN
END

IF @Type=1 AND EXISTS(SELECT TOP 1 1 FROM Te_BankAccount WHERE ATypeId=@AtypeId AND StypeId=@STypeId AND IsDestroy=0)
BEGIN
	SET @MSG='会计科目已被使用,请重新选择！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
	RAISERROR(@MSG,16,1) RETURN
END
IF @Type=2 AND EXISTS(SELECT TOP 1 1 FROM Te_BankAccount WHERE ATypeId=@AtypeId AND StypeId=@STypeId AND Id<>@Id AND IsDestroy=0)
BEGIN
	SET @MSG='会计科目已被使用,请重新选择！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
	RAISERROR(@MSG,16,1) RETURN
END
SELECT @Cid=Cid FROM Ac_Account WHERE TypeId=@ATypeId AND StypeId=@STypeId
SELECT @XiWaMaxNumber=XiWaMaxNumber+1 FROM Te_BankAccount
IF(@Type=1 OR @Type=2)
BEGIN
	INSERT INTO Te_BankAccount
	(
		UserCode,
		FullName,
		AccountNumber,
		STypeId,
		BankId,
		ATypeId,
		CreateDate,
		IsDestroy,
		Cid,
		Comment,
		XiWaMaxNumber
	)
	VALUES
	(
		@UserCode,
		@FullName,
		@AccountNumber,
		@STypeId,
		@BankId,
		@ATypeId,
		@CreateDate,
		0,
		@Cid,
		@Comment,
		@XiWaMaxNumber
	)
	SELECT @Error=@@ERROR
END
ELSE IF @Type=3
BEGIN
	UPDATE Te_BankAccount
	SET 
		UserCode=@UserCode,
		FullName=@FullName,
		AccountNumber=@AccountNumber,
		STypeId=@STypeId,
		BankId=@BankId,
		ATypeId=@ATypeId,
		Cid=@Cid,
		Comment=@Comment,
		XiWaMaxNumber=@XiWaMaxNumber,
		CreateDate=@CreateDate
	WHERE Id=@Id
	SELECT @Error=@@ERROR
END
IF(@Error<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='信息添加失败！'
		IF(@type=2)
			SET @MSG2='信息修改失败！'
		RAISERROR(@MSG2,16,1)
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 说明：	添加POS操作员
-- 作者：	黄清
-- 时间：	2014-01-03
-- ========================================================================
CREATE         PROCEDURE GP_AddPosUser
(
	@szETypeID		VARCHAR(5000),	-- 职员 ID 值
	@operatorId     VARCHAR(50),	-- 当前操作员
	@IsSYS			BIT = 0			-- 是否超级管理员
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********


--添加操作员支持多选，排除已经有的操作员 2012-02-23
CREATE TABLE #User(TypeId VARCHAR(50))

INSERT INTO #User(TypeId)
SELECT	F.TypeId
FROM	F_GetAllManagerBaseTypeId(@szETypeID,3,@operatorId) F,
		Employee E
WHERE	F.TypeId = E.TypeId
		AND E.sonnum = 0
		AND E.deleted = 0
		AND F.TypeId NOT IN 
		(
			SELECT	ETypeId
			FROM	LoginUser
		)
	
	
--BEGIN 判断POS用户数是否超出
DECLARE @totalPos INT,@hasPos INT,@newAdd INT

SELECT @newAdd = COUNT(*) FROM #User
SELECT @totalPos = SubValue FROM dbo.sysdata WHERE SubName = 'PosDefine'
SELECT @hasPos = COUNT(*) FROM dbo.loginuser WHERE isPos = 1 AND etypeid <> '00001'
--POS用户数超出
IF @totalPos < @hasPos + @newAdd
	RETURN 1689

--END 判断POS用户数是否超出
IF NOT EXISTS(SELECT * FROM #User) RETURN
 
INSERT INTO LoginUser (
			ETypeID,
			BTypeID,
			SysID
)
SELECT	TypeID,
		BTypeID,
		@IsSYS
FROM	Employee
WHERE	TypeID IN (
						SELECT typeid FROM #User
				   )

UPDATE	LoginUser
SET		Lim = ' ',
		isPos=1,
		isErp=0
WHERE	EtypeID IN (
						SELECT typeid FROM #User
				   )
		
	--END

IF @@ROWCOUNT = 0 RETURN -2

IF @IsSYS = 1
	BEGIN
		UPDATE	LoginUser
		SET		Lim = (
				SELECT	Lim
				FROM	LoginUser
				WHERE	ETypeID = '00001'
			),
			isErp=0,
			isPos=1
		WHERE	ETypeID IN (
								SELECT typeid FROM #User
							)
	END
	

	
--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'

DROP TABLE #User

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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


/****** Object:  StoredProcedure [dbo].[Gp_AddSerial]    Script Date: 04/01/2011 09:59:04 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO





/*
    增加一个序列号到明细
    参数：
	@BillNumberid    临时或真的商品号
	@InKtypeID       入库仓库id
	@OutKtypeID    出库仓库id
	@PtypeID          商品id
	@szSerial           序列号
	@Pre                  是否期初 0 非期初数据 1 期初数据    
	@BillType            单据类型
	@szDXType         代销期初
	
	-- 梁晰 2016-12-23 添加Id字段
*/
CREATE  PROCEDURE [dbo].[Gp_AddSerial]
( 
	@BillNumberid varchar(50),
	@InKtypeID varchar(100),
	@OutKtypeID varchar(100),
	@PtypeID varchar(100),
	@szSerial varchar(1000),
	@Pre int=0,
	@BillType int,
	@szDXType int,
	@state int,
	@szBTypeID varchar(100),
	@ToKTypeID varchar(100),
	@ETypeID varchar(100),
	@stypeID varchar(100),
	@GoodsNumber VARCHAR(100)='',
	@ItemId		 VARCHAR(100)=''
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Flag int
DECLARE @c INT=0

IF @szDXType=165 SET @state=25
IF @szDXType NOT IN (140,144,165) SET @state=1

IF @state IN(1,7,25)
SET @Flag=1
ELSE SET @Flag=0

DECLARE @serialrelation INT;
SELECT @serialrelation = Value FROM dbo.Userconfig WHERE ConfigName = 'serialrelation'

IF @serialrelation = 1
BEGIN
IF @state=7
	SELECT @c=cargoId FROM cargotype WHERE isDefault=1 AND ktypeid=@ToKTypeID;
IF @state=1
	SELECT @c=cargoId FROM cargotype WHERE isDefault=1 AND ktypeid=@InKtypeID;
END

DELETE 	
FROM 	[gp_inoutPtypeSerial]
WHERE 	[BillNumberID] LIKE '%|%'
 		AND LEFT(BillNumberID,10) < CONVERT(varchar(10),(GETDATE()-1),20)

IF @Pre=0	-- 非期初的数据加入
	INSERT 	gp_inoutPtypeSerial
	(
		[Serial],
		[PtypeID],
		[BillNumberid],
		[InKtypeID],
		[OutKtyeID],
		[IfCheck],
		[BillType]
	)VALUES(
		@szSerial,
		@PtypeID,
		@BillNumberid,
		@InKtypeID,
		@OutKtypeID,
		'f',
		@BillType
	)
ELSE            -- 期初的数据加入
	BEGIN
		IF @szDXType=140  --委托
		 	INSERT 	gp_initPtypeSerial
			(
				[Serial],
				[KtypeID],
				[PtypeID],
				[state],
				[Flag],
				[CommissionState],
				[BTypeID1],
				[Note],
				[ETypeID],
				iniFlag,
				STypeId
			)VALUES(
				@szSerial,
				@InKtypeID,
				@PtypeID,
				@state,
				@Flag,
				'',
				@szBTypeID,
				'',
				@ETypeID,1,@stypeID
			)
	      ELSE 
				IF @szDXType=144   --受托
	            	INSERT 	gp_initPtypeSerial
					(
						[Serial],
						[KtypeID],
						[PtypeID],
						[state],
						[Flag],
						[CommissionState],
						[BTypeID2],
						[Note],
						[ETypeID],
						iniFlag,
						STypeId,
						CargoID
					)VALUES(
						@szSerial,
						@ToKTypeID,
						@PtypeID,
						@state,
						@Flag,
						'0',
						@szBTypeID,
						'',
						@ETypeID,
						1,
						@stypeID,
						@c
					)
				ELSE IF @szDXType=165
				BEGIN
					INSERT 	gp_initPtypeSerial
						(
							[Serial],
							[KtypeID],
							[PtypeID],
							[state],
							[Flag],
							[CommissionState],
							[ETypeID],
							iniFlag,
							STypeId,
							GoodsNumber,
							ItemID
						)VALUES(
							@szSerial,
							@InKtypeID,
							@PtypeID,
							@state,
							@Flag,
							'',
							@ETypeID,
							1,
						    @stypeID,
						    @GoodsNumber,
						    @ItemId
						)
						END
	      		ELSE IF @szDXType=821  --SELECT * FROM gp_iniFactPtypeSerial
					INSERT 	dbo.gp_iniFactPtypeSerial					       
					(
						[Serial],
						[KtypeID],
						[PtypeID],
						[state],
						[Flag],
						[CommissionState],
						[ETypeID],
						STypeId,
						CargoID
					)VALUES(
						@szSerial,
						@InKtypeID,
						@PtypeID,
						@state,
						@Flag,
						'',
						@ETypeID,
						@stypeID,
						@c
					)
						ELSE
						BEGIN
						DECLARE @Id INT;
						SELECT @Id = Id FROM ini_goodsstocks_qty WHERE PTypeID = @PtypeID AND KTypeID = @InKtypeID AND CargoID = @c;
						
					INSERT 	gp_initPtypeSerial
					(
						[Serial],
						[KtypeID],
						[PtypeID],
						[state],
						[Flag],
						[CommissionState],
						[ETypeID],
						iniFlag,
						STypeId,
						CargoID,
						ID
					)VALUES(
						@szSerial,
						@InKtypeID,
						@PtypeID,
						@state,
						@Flag,
						'',
						@ETypeID,
						1,
						@stypeID,
						@c,
						@Id
					)
					END
	END

	RETURN @@Error

GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddTemplet]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_AddTemplet
GO          

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	新增自定义报表模板
-- 时间：	2013-05-30
-- 作者：	glj 
-- ========================================================================
CREATE PROC Gp_AddTemplet
(
	@TypeId			VARCHAR(50),		--typeid
	@TypeId1		VARCHAR(50),		--typeid
	@TempletName	VARCHAR(200),		--模板名称
	@ParentTypeId	VARCHAR(50),		--父级ID
	@IsShares		int,				--是否共享
	@Remarks		VARCHAR(100),		--备注
	@ETypeId		VARCHAR(50),		--操作员ID
	@ETypeFullName	VARCHAR(66)			--操作员名称
)

--@encode$--
AS
SET NOCOUNT ON

DECLARE @ERROR	INT=0,
		@ModeID	INT=1
IF(SUBSTRING(@TypeId,1,5)='00002')
	SET @ModeID=13
IF(SUBSTRING(@TypeId,1,5)='00003')
	SET @ModeID=5

IF EXISTS(SELECT TOP 1 1 FROM UFO_ReportCategory WHERE Name=@TempletName)
	BEGIN
		RAISERROR('名称已存在，请重新填写！',16,1)
		RETURN
	END

INSERT INTO DBO.UFO_ReportCategory
(
	TypeId,
	Name,
	ParentTypeId,
	SysType,
	IsShares,
	etypeid
) 
VALUES 
( 
	@TypeId,
	@TempletName,
	@ParentTypeId,
	0,
	@IsShares,
	@ETypeId
)
SET @ERROR+=@@ERROR

INSERT INTO DBO.UFO_ReportCategory
(
	TypeId,
	Name,
	ParentTypeId,
	SysType,
	IsShares,
	etypeid
) 
VALUES 
( 
	@TypeId1,
	@TempletName,
	@ParentTypeId,
	1,
	@IsShares,
	@ETypeId
)
SET @ERROR+=@@ERROR

INSERT INTO UFO_Temple
(
	TempleName,
	ModeID,
	CreateEtypeID,
	CreateTime,
	IsVisible,
	TempleCategoryID,
	CreateEtypeName,
	ClassId,
	IsShare,
	ReMarks
) 
VALUES 
(
	@TempletName,
	@ModeID,
	@ETypeId,
	GETDATE(),
	1,
	@TypeId,
	@ETypeFullName,
	2,
	@IsShares,
	@Remarks
)
SET @ERROR+=@@ERROR

IF(@ERROR<>0)
	BEGIN
		RAISERROR('执行异常！',16,1) 
		RETURN
	END
	
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddVipSmsTemplate]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Gp_AddVipSmsTemplate
GO

/*
	作者：谢吉康
	日期：2018-11-07
	描述：新增会员自定义短信
*/
CREATE PROC Gp_AddVipSmsTemplate
(
	@smsId						INT,					--模板ID
	@tempCode				VARCHAR(500),			--短信群发模板编号
	@tempName				VARCHAR(500),			--短信群发模板名称
	@tempTypeId			INT,					--模板类型
	@vipCardTypeID		VARCHAR(MAX),			--发送对象(卡类型)
	@tempContent			VARCHAR(MAX),			--群发内容
	@comment				VARCHAR(MAX),			--备注
	@isPostSend				BIT,					--过账时自动发送(不包含自动过账)
	@OpertiorId				VARCHAR(50)='00000',	--操作人
	@Birth_IsAutoSend	BIT=0,--（@Birth_IsAutoSend）会员生日短信提前（@SendDay）天（@SendTime）时间
	@SendDay					INT=0,
	@SendTime				TIME='00:00:00',
	
	@retcontent				VARCHAR(MAX) OUTPUT,	--返回数据
	@rettemplateid			VARCHAR(100) OUTPUT,	--返回ID
	@retsmsid					VARCHAR(100) OUTPUT		--返回SMSID
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE (tempCode = @tempCode OR tempName = @tempName))
	BEGIN
		RAISERROR('该模板信息已不存在，请确认！',16,1) RETURN
	END
	
IF ISNULL(@tempCode,'')=''
	BEGIN
		RAISERROR('模板编号不能为空，请确认！',16,1) RETURN
	END
	
IF ISNULL(@tempName,'')=''
	BEGIN
		RAISERROR('模板名称不能为空，请确认！',16,1) RETURN
	END
			
IF ISNULL(@tempContent,'')=''
	BEGIN
		RAISERROR('短信内容不能为空，请确认！',16,1) RETURN
	END		
				
IF EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE tempCode=@tempCode)
	BEGIN
		RAISERROR('系统中已经存在该模板编号，请确认！',16,1) RETURN
	END
	
IF EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE tempName=@tempName)
	BEGIN
		RAISERROR('系统中已经存在该模板名称，请确认！',16,1) RETURN
	END
	
	
DECLARE @Error INT=0

BEGIN TRAN

--翻译模版
DECLARE @returncontent	VARCHAR(MAX),
		@intReturn		NUMERIC(18,0)

EXEC Web_ConvertBillTypeOldSmsContentToHyyun '-1',@tempContent,@returncontent OUTPUT

INSERT INTO SMSInfo_Template 
(
	tempCode,
	tempName,
	tempTypeId,
	tempContent,
	comment,
	isPostSend,
	HyyunSmsTemplateContent,
	Birth_IsAutoSend,
	SendDay,
	SendTime

)VALUES(
	@tempCode,
	@tempName,
	@tempTypeId,
	@tempContent,
	@comment,
	@isPostSend,
	@returncontent,
	@Birth_IsAutoSend,
	@SendDay,
	@SendTime
)

SELECT  @intReturn = SCOPE_IDENTITY();

SET @Error+=@@ERROR

--删除发送对象关联关系
DELETE FROM SMSInfo_Template_CardType WHERE smsId=@intReturn
SET @Error+=@@ERROR

--重新插入关联关系
IF(@vipCardTypeID<>'0')
	BEGIN
		INSERT INTO SMSInfo_Template_CardType(smsId,vipCardTypeID) SELECT DISTINCT @intReturn,a FROM f_split(@vipCardTypeID,',')
		SET @Error+=@@ERROR
	END
	
--返回模版内容和ID	
SET @retcontent = @returncontent
SET @retsmsid = @intReturn
SELECT 	@rettemplateid = hyyunsmstemplateid FROM SMSInfo_Template WHERE smsId=@intReturn

IF(@@ERROR=0)--保存成功
	BEGIN
		COMMIT TRAN
		RETURN 1
	END
ELSE
	BEGIN
		ROLLBACK TRAN
		RETURN 0
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




--商品多单位
IF EXISTS(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_PTypeUnits' AND ss.name=N'dbo')
	BEGIN
		IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddWdDownLoadPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
			DROP PROCEDURE [dbo].[Gp_AddWdDownLoadPtype]--删除 新增全渠道下载商品
		DROP type [dbo].Type_PTypeUnits 
	END
GO
CREATE TYPE Type_PTypeUnits AS TABLE
(
	UnitName	VARCHAR(200),--多单位名称     
	BarCode     VARCHAR(200),--条码
	Rate        NUMERIC(24, 10)--汇率    
)
GO
--商品自由项
IF EXISTS(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_PTypeFreeItem' AND ss.name=N'dbo')
	BEGIN
		IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddWdDownLoadPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
			DROP PROCEDURE [dbo].[Gp_AddWdDownLoadPtype]--删除 新增全渠道下载商品
		DROP type [dbo].Type_PTypeFreeItem 
	END
GO
CREATE TYPE Type_PTypeFreeItem AS TABLE
(
	SkuCode		VARCHAR(200),--自由项编号
	SkuName		VARCHAR(200),--自由项名称
	BarCode		VARCHAR(200),--自由项条码
	[Weight]	NUMERIC(24, 10),--自由项重量
	Size		VARCHAR(200),--自由项 尺寸
	Price		NUMERIC(24, 10),--自由项价格1
	Price2		NUMERIC(24, 10),--自由项价格2
	Price3		NUMERIC(24, 10),--自由项价格3
	Price4		NUMERIC(24, 10),--自由项价格4
	Price5		NUMERIC(24, 10)--自由项价格5
)
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_AddWdDownLoadPtype]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_AddWdDownLoadPtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	ptype 新增全渠道下载商品
-- 时间：	2018-03-29
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [Gp_AddWdDownLoadPtype]
(
	@UserCode		VARCHAR(200),--编号
	@FullName		VARCHAR(200),--名称
	@standard		VARCHAR(200),--规格
	@baseUnitFullName VARCHAR(200),--基本单位
	@EntryCode		VARCHAR(200),--条码
	@Comment		VARCHAR(200),--备注
	@units			Type_PTypeUnits READONLY,--多单位
	@FreeItems		Type_PTypeFreeItem READONLY,--自由项
	@OperatorID		VARCHAR(50),	-- 操作员
	@ErrorMsg		VARCHAR(MAX) OUTPUT,
	@PTypeID		VARCHAR(50) OUTPUT
)
--WITH ENCRYPTION

AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM ptype WHERE UserCode=@UserCode)
	BEGIN
		SET @ErrorMsg='商品编号【'+@UserCode+'】已经存在，不能保存！';
		RETURN
	END
IF EXISTS(SELECT TOP 1 1 FROM ptype WHERE FullName=@FullName) AND EXISTS(SELECT * FROM Userconfig WHERE ConfigName='equalproname' AND Value='0')
	BEGIN
		SET @ErrorMsg='商品名称【'+@FullName+'】已经存在，不能保存！';
		RETURN
	END
--判断条码且配置 是否允许重复
IF EXISTS(SELECT * FROM PType_EntryCode_Ext E INNER JOIN f_split(@EntryCode,';') F ON F.a=E.EntryCode) 
	AND EXISTS(SELECT * FROM Userconfig WHERE ConfigName='equalentrycode' AND Value=0)
	BEGIN
		SET @ErrorMsg='商品名称【'+@FullName+'】的条码跟其他商品条码重复，不能保存！';
		RETURN
	END

DECLARE 
	@ParId		VARCHAR(50),
	@Level		INT,
	@SonCount	INT,
	@UnitsId	INT,--单位ID
	@Error		INT=0,--错误号
	@XiWaMaxNumber INT

--查询父级，便于得到当前TypeID值
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber) FROM ptype
SELECT @ParId=typeId,@Level=leveal,@SonCount=soncount FROM ptype WHERE typeId='00000'
SELECT @PTypeId=REPLICATE('0',5-LEN(@SonCount))+CAST(@SonCount+1 AS VARCHAR(5))

	
BEGIN TRAN 

--如果没有传回单位
IF(ISNULL(@baseUnitFullName,'')='')
	BEGIN
		SELECT @UnitsId=UnitsId FROM PType_Units WHERE FullName='pcs'
	END
ELSE 
	BEGIN
		IF NOT EXISTS(SELECT * FROM PType_Units WHERE FullName=@baseUnitFullName)
			BEGIN
				INSERT INTO PType_Units(UserCode,FullName,IsWdDownLoad)VALUES(@baseUnitFullName,@baseUnitFullName,1)
				SET @Error+=@@ERROR
			END
			
		SELECT @UnitsId=UnitsId FROM PType_Units WHERE FullName=@baseUnitFullName
	END

--商品 新增数据
INSERT INTO ptype
(
	typeId,
	ParId,
	leveal,
	sonnum,
	soncount,
	UserCode,
	FullName,
	PyCode,
	CreateDate,
	IsService,
	iscombinationproduct,
	IsWdDownLoad,
	SaleUnitId,
	StockUnitId,
	BuyUnitId,
	baseUnitId,
	AssistantUnitId,
	ProduceUnitId,
	BrandarTypeID,
	InventoryTypeID,
	CanModify,
	Comment,
	XiWaMaxNumber,
	--补充
	Name,
	Standard,
	type,
	Area,
	UsefulLifeMonth,
	UsefulLifeDay,
	ColorGroupID,
	SizeGroupID,
	IfUseEntryCode,
	EntryCode,
	MultEntryCode,
	DwgNo,
	SortID,
	OmPrice,
	weight,
	volume,
	StopBuy,
	UnitsType
)
VALUES
(
	@PTypeId,
	@ParId,
	@Level+1,
	0,
	0,
	@UserCode,
	@FullName,
	dbo.fun_getPY(@FullName),
	GETDATE(),
	0,
	0,
	1,
	@UnitsId,
	@UnitsId,
	@UnitsId,
	@UnitsId,
	null,
	@UnitsId,
	'00001',--默认其他品牌
	2,--存货商品
	0,
	@Comment,
	@XiWaMaxNumber+1,
	--补充
	'',
	'',
	'',
	'',
	0,
	0,
	0,
	0,
	CASE WHEN ISNULL(@EntryCode,'')='' THEN 0 ELSE 1 END,
	CASE WHEN CHARINDEX(';',@EntryCode)>0 THEN LEFT(@EntryCode,CHARINDEX(';',@EntryCode)-1) ELSE @EntryCode END,
	@EntryCode,
	'',
	1,
	0,
	0,
	0,
	0,
	1
)
SET @Error+=@@ERROR

--修改父级子级个数，和更改子级typeid基数
UPDATE ptype SET sonnum+=1,soncount+=1 WHERE typeId=@ParId
SET @Error+=@@ERROR

--商品价格处理
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber) FROM PType_Price
INSERT INTO PType_Price(PTypeID,UnitID,IsDefaultUnit,XiWaMaxNumber) VALUES(@PTypeID,@UnitsId,1,@XiWaMaxNumber)
SET @Error+=@@ERROR

--自由项
IF (SELECT COUNT(*) FROM @FreeItems)=1
BEGIN
	--修改商品值
	DECLARE 
		@Weight		NUMERIC(24,10),--重量
		@Size		VARCHAR(200),--尺寸
		@Price1		NUMERIC(24, 10),--价格1
		@Price2		NUMERIC(24, 10),--价格2
		@Price3		NUMERIC(24, 10),--价格3
		@Price4		NUMERIC(24, 10),--价格4
		@Price5		NUMERIC(24, 10)--价格5
		
		SELECT @Weight=Weight,@Size=Size,@Price1=Price,@Price2=Price2,@Price3=Price3,@Price4=Price4,@Price5=Price5 FROM @FreeItems
		
		--商品重量处理
		UPDATE ptype
		SET
			weight=@Weight,
			volume=@Size
		WHERE 
			typeId=@PTypeID
		SET @Error+=@@ERROR
		
		--商品条码处理
		INSERT INTO PType_EntryCode_Ext(Ptypeid,EntryCode,IsDefaultEntryCode)
		SELECT 
			@PTypeID,
			a,
			CASE WHEN SUBSTRING(@EntryCode,1,CHARINDEX(';',@EntryCode)-1)=a THEN 1 ELSE 0 END 
		FROM dbo.f_split(@EntryCode,';') GROUP BY a
		SET @Error+=@@ERROR
		
		--商品预设价格
		UPDATE PType_Price
		SET
			PreSalePrice1=@Price1,
			PreSalePrice2=@Price2,
			PreSalePrice3=@Price3,
			PreSalePrice4=@Price3,
			PreSalePrice5=@Price5
		WHERE 
			PTypeID=@PTypeID
		SET @Error+=@@ERROR
	END

--商品-多单位
IF EXISTS(SELECT TOP 1 1 FROM @units)
	BEGIN
		--商品-多单位
		INSERT INTO PType_Units_Ext
		(
			PtypeID,
			UnitsId,
			RateType,
			Rate,
			EntryCode,
			IsDefaultUnit,
			IsUse
		)
		SELECT
			@PTypeId,
			 PU.UnitsId,
			 0,
			 U.Rate,
			 U.BarCode,
			 CASE WHEN U.UnitName=@baseunitfullname THEN 1 ELSE 0 END IsDefaultUnit,
			 1
		FROM @units U
		INNER JOIN PType_Units PU ON PU.FullName=U.UnitName
		SET @Error+=@@ERROR
			
		--多单位条码
		INSERT INTO PType_Units_EntryCode_Ext
		(
			PtypeID,
			UnitsId,
			EntryCode,
			IsDefaultEntryCode
		)
		SELECT
			@PTypeId,
			PU.UnitsId,
			u.BarCode,
			CASE WHEN U.UnitName=@baseUnitFullName THEN 1 ELSE 0 END IsDefaultEntryCode
		FROM @units U
		INNER JOIN PType_Units PU ON PU.FullName=U.UnitName AND ISNULl(U.BarCode,'')<>''
		SET @Error+=@@ERROR
	END
ELSE 
	BEGIN
		--商品-多单位
		INSERT INTO PType_Units_Ext
		(
			PtypeID,
			UnitsId,
			RateType,
			Rate,
			EntryCode,
			IsDefaultUnit,
			IsUse
		)
		SELECT
			@PTypeID,
			UnitsId,
			0,
			1,
			'',
			1,
			1
		FROM PType_Units WHERE UnitsId=@UnitsId
		SET @Error+=@@ERROR
	END
IF(@Error=0)
	BEGIN
		COMMIT TRAN
	END
ELSE 
	BEGIN
		SET @ErrorMsg='商品编号【'+@FullName+'】保存过程中异常！';
		ROLLBACK TRAN
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

专门处理调价全部仓库

*/
CREATE   PROCEDURE GP_AdPrice_ChangeAllStock 
(
	@nBillID				numeric(10,0),					-- 1. 单据编号 ID 值
	@nBilltype				INT,
	@chvOpID				VARCHAR(50) = '',				-- 当前操作员 ID 值
	@nRet					INT	OUT,						-- 返回的出错值
	@voucherMsg				VARCHAR(50)	= '' OUTPUT			--返回凭证生成的信息
)
--@encode$--
AS

--只有移动加权下，调价全部仓库才用,QTY不变
--不启用自由项,不启用货位


		
		
SELECT @nRet=0		


DECLARE
	@decOldValue		NUMERIC(24,10),
	@decNewValue		NUMERIC(24,10),
	@strGOODS_ID		VARCHAR(50),
	@strAdjustCostID	VARCHAR(50),
	@intMoneyDot		INT,
	@intSysCID			INT
	
SELECT @strGOODS_ID=NID
FROM Ac_Items
WHERE UserCode='1241'

SELECT @strAdjustCostID=NID
FROM Ac_Items
WHERE nId='0323'

SELECT @intSysCID=CId 
FROM Ac_Currency
WHERE Sysrow=1

SELECT @intMoneyDot=2

SELECT @decOldValue=SUM(b.Total)
FROM AdPriceBill a
INNER JOIN GOODSSTOCKS b
ON a.PtypeId=b.PTypeID
WHERE a.BillNumberId=@nBillID	
	
INSERT InOutstocktable(BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,
Qty,Price,Total,CostPrice,CostTotal,Audited,GoodsNumber,ProduceDate,ValidDate,HandZeroCost,ID,
Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,DTypeID,STypeID,PostTime,CargoID,
NPrice,NTotal,NSalePrice,NSaleTotal,NTaxPrice,NTaxTotal,ItemID,IsCombined,NQty,UnitRate,MUNITID)
SELECT a.BillNumberId,b.BillDate,b.BillType,@strGOODS_ID,a.PtypeId,b.btypeid,b.etypeid,c.KtypeId,
-c.Qty,c.Price,-c.Total,c.Price,-c.Total,1,c.GoodsNumber,c.ProduceDate,c.ValidDate,0,a.ID,
1,c.Price,-c.Total,c.Price,-c.Total,b.DTypeId,b.StypeID,GETDATE(),d.CargoID,
c.Price,-c.Total,c.Price,-c.Total,c.Price,-c.Total,0,0,0,1,e.baseUnitId
FROM AdPriceBill a
INNER JOIN BillIndex b
ON a.BillNumberId=b.BillNumberId AND a.BillNumberId=@nBillID
INNER JOIN GOODSSTOCKS c
ON a.PtypeId=c.PTypeID
INNER JOIN CargoType d
ON c.KtypeId=d.KtypeID AND d.IsDefault=1
INNER JOIN PType e
ON a.PTypeID=e.typeId
WHERE a.BillNumberId=@nBillID



UPDATE GOODSSTOCKS
SET Total=ROUND(GOODSSTOCKS.Qty*a.Price,@intMoneyDot)
FROM AdPriceBill a
WHERE a.BillNumberId=@nBillID
AND a.PtypeId=GOODSSTOCKS.PtypeId	

INSERT InOutstocktable(BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,
Qty,Price,Total,CostPrice,CostTotal,Audited,GoodsNumber,ProduceDate,ValidDate,HandZeroCost,ID,
Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,DTypeID,STypeID,PostTime,CargoID,
NPrice,NTotal,NSalePrice,NSaleTotal,NTaxPrice,NTaxTotal,ItemID,IsCombined,NQty,UnitRate,MUNITID)
SELECT a.BillNumberId,b.BillDate,b.BillType,@strGOODS_ID,a.PtypeId,b.btypeid,b.etypeid,c.KtypeId,
c.Qty,a.Price,ROUND(c.Qty*a.Price,@intMoneyDot),a.Price,ROUND(c.Qty*a.Price,@intMoneyDot),1,c.GoodsNumber,c.ProduceDate,c.ValidDate,0,a.ID,
1,a.Price,ROUND(c.Qty*a.Price,@intMoneyDot),a.Price,ROUND(c.Qty*a.Price,@intMoneyDot),b.DTypeId,b.StypeID,GETDATE(),d.CargoID,
a.Price,ROUND(c.Qty*a.Price,@intMoneyDot),a.Price,ROUND(c.Qty*a.Price,@intMoneyDot),a.Price,ROUND(c.Qty*a.Price,@intMoneyDot),0,0,0,1,e.baseUnitId
FROM AdPriceBill a
INNER JOIN BillIndex b
ON a.BillNumberId=b.BillNumberId AND a.BillNumberId=@nBillID
INNER JOIN GOODSSTOCKS c
ON a.PtypeId=c.PTypeID
INNER JOIN CargoType d
ON c.KtypeId=d.KtypeID AND d.IsDefault=1
INNER JOIN PType e
ON a.PTypeID=e.typeId
WHERE a.BillNumberId=@nBillID

	
SELECT @decNewValue=SUM(b.Total)
FROM AdPriceBill a
INNER JOIN GOODSSTOCKS b
ON a.PtypeId=b.PTypeID
WHERE a.BillNumberId=@nBillID	

INSERT ListTable(BillNumberId,BillDate,BillType,AtypeId,EtypeId,Total,CostTotal,Audited,DTypeID,STypeID,CID,Ntotal,Rate)
SELECT BillNumberId,BillDate,BillType,@strGOODS_ID,etypeid,@decNewValue-@decOldValue,@decNewValue-@decOldValue,1,DTypeId,StypeID,CID,@decNewValue-@decOldValue,1
FROM BillIndex
WHERE BillNumberId=@nBillID AND BillType=57


INSERT ListTable(BillNumberId,BillDate,BillType,AtypeId,EtypeId,Total,CostTotal,Audited,DTypeID,STypeID,CID,Ntotal,Rate)
SELECT BillNumberId,BillDate,BillType,@strAdjustCostID,etypeid,@decNewValue-@decOldValue,@decNewValue-@decOldValue,1,DTypeId,StypeID,CID,@decNewValue-@decOldValue,1
FROM BillIndex
WHERE BillNumberId=@nBillID AND BillType=57

UPDATE BillIndex
SET ifcheck='t',posttime=GETDATE(),Poster=@chvOpID,draft=0
WHERE BillNumberId=@nBillID

IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
		AND	EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'postingparameter' AND SubValue = 0)--即时过账，即时生成凭证
		AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'aloneusebsys' AND SubValue = 0)--使用总账系统
		AND @nBilltype NOT IN (203)--排除序列号调整单
BEGIN
	DECLARE @atid INT
	
	
	IF @nBilltype IN (404,405)
	BEGIN
		SELECT @atid = atid FROM dbo.ReceiptBillIndex WHERE BillNumberId = @nBillID
	END
	ELSE
	BEGIN
		SELECT @atid = atid FROM dbo.BillIndex WHERE BillNumberId = @nBillID
	END
	EXEC @nRet = dbo.Gp_AutoCreate_Voucher @nBillID,@chvOpID,@atid,'',@voucherMsg OUTPUT,@nBilltype
	
	
END
ELSE
	SET @voucherMsg = ''

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBilltype			INT
	
SELECT
	@nBillID=2,
	@nBilltype=34
	
BEGIN TRAN	

EXEC	GP_AdPrice_ChangeAllStock 
	@nBillID,
	@nBilltype


COMMIT TRAN
--ROLLBACK TRAN


*/



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

-- =============================================
-- Author:		王刚
-- Create date: 05/14/2013 
-- Description:	高级价格设置保存
-- =============================================

CREATE PROCEDURE Gp_AdvancedPriceSet
(
	@iscombineprice	INT,
	@isunifiedpriority INT,
	@advancedpriceds Tb_AdvancedPriceSet	READONLY
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE PriceStyle SET IsTopPolicy = D.IsTopPolicy,IsDownPolicy = D.IsDownPolicy
FROM PriceStyle P
INNER JOIN @advancedpriceds D ON D.BillType = P.BillType

UPDATE sysdata SET SubValue = @iscombineprice WHERE SubName='IsCombinePrice'
UPDATE sysdata SET SubValue = @isunifiedpriority WHERE SubName='IsUnifiedPriority'

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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











/*
	作者：谢吉康
	日期：2005-11-24
	描述：调整格式
	
	修改：舒珊
	日期：2016年2月25日
	描述：增添表头、表体自定义显示字段
*/


CREATE  PROCEDURE [Gp_AdvantageStat]
(
	@chvOperator 	VARCHAR(100),
	@szMode     	VARCHAR(20),  --使用方式     
	@StartDate 		DATETIME,
	@EndDate 		DATETIME,
	@BUserCode 		VARCHAR(100),
	@BFullName 		VARCHAR(100),
	@PUserCode 		VARCHAR(200),
	@PFullName 		VARCHAR(200),
	@BillType 		INT,
	@STypeId		VARCHAR(MAX),
	@szSort 		CHAR(1)=''
)
--@encode$--
 AS

SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperator IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @chvOperator,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperator)	

--==================================================================================================返利查询
IF @szMode='Normal'
	BEGIN	
		IF @BUserCode='' SELECT @BUserCode='%' ELSE SELECT @BUserCode='%'+@BUserCode+'%'
		IF @BFullName='' SELECT @BFullName='%' ELSE SELECT @BFullName='%'+@BFullName+'%'
		IF @PUserCode='' SELECT @PUserCode='%' ELSE SELECT @PUserCode='%'+@PUserCode+'%'
		IF @PFullName='' SELECT @PFullName='%' ELSE SELECT @PFullName='%'+@PFullName+'%'
		
		SELECT TypeID,UserCode,FullName INTO #TempTablePType  FROM F_GetManPTypeAll(@chvOperator) WHERE (UserCode LIKE @PUserCode AND FullName LIKE @PFullName) AND (sonnum=0) --AND (TypeID LIKE @MPTypeID+'%')
		SELECT TypeID,UserCode,FullName INTO #TempTableBType  FROM F_GetManBTypeAll(@chvOperator) WHERE (UserCode LIKE @BUserCode AND FullName LIKE @BFullName) AND (sonnum=0) --AND (TypeID LIKE CASE LEFT(TypeID,5) WHEN '00001' THEN @MBTypeID+'%' WHEN '00002' THEN @MBTypeID2+'%' END)
		
		SELECT 	a.Stypeid,
				a.BTypeID,
				b.PTypeID,
				SUM(B.Total) AS Total 
		INTO 	#TempTableResult1 
		FROM 	BillIndex a
		INNER JOIN 	Advantage b ON (a.BillNumberID=b.BillNumberID)
		INNER JOIN #GetManSTypeId S ON S.TypeId = A.Stypeid
		WHERE  	a.BillDate>=@StartDate 
				AND a.BillDate<=@EndDate 
				AND a.ifcheck='t'
				AND a.RedWord = 0 
				AND a.BillType=@BillType 
				AND a.ifYearBill=0	 --年节存标志
		GROUP BY a.BTypeID,b.PTypeID,a.Stypeid
		
		SELECT 	a.Stypeid,
				a.Total,
				b.TypeID AS PTypeID,
				b.UserCode AS PUserCode,
				b.FullName AS PFullName,
				c.TypeID AS BTypeID,
				c.UserCode AS BUserCode,
				c.FullName AS BFullName
				FROM #TempTableResult1 a 
				JOIN #TempTablePType b ON (a.PTypeID=b.TypeID)
				JOIN #TempTableBType c ON (a.BTypeID=c.TypeID)
		WHERE 	b.TypeID<>'' 
				AND c.TypeID<>'' 
				AND b.TypeID<>NULL 
				AND c.TypeID<>NULL	
		DROP TABLE #TempTableResult1,#TempTablePType,#TempTableBType 
	END
ELSE IF @szMode='BillDetail'
	BEGIN	
		SELECT 	a.*,
				b.Total,
				c.UserCode,
				c.FullName,
				SysDiy1_head,
				SysDiy2_head,
				SysDiy3_head,
				SysDiy4_head, 
				SysDiy5_head,
				SysDiy6_head,
				SysDiy7_head,
				SysDiy8_head,
				SysDiy9_head,
				SysDiy10_head,
				SysDiy11_head,
				SysDiy12_head,
				SysDiy13_head,
				SysDiy14_head,
				SysDiy15_head,
				SysDiy16_head,
				SysDiy1,
				SysDiy2,
				SysDiy3,
				SysDiy4,
				SysDiy5,
				SysDiy6,
				SysDiy7,
				SysDiy8,
				SysDiy9,
				SysDiy10,
				SysDiy11,
				SysDiy12,
				SysDiy13,
				SysDiy14,
				SysDiy15,
				SysDiy16 
		INTO 	#TempTable 
		FROM 	Billindex a 
		INNER JOIN Advantage b ON (a.BillNumberID=b.BillNumberID) 
		LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
		LEFT JOIN Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND b.ID=csdetail.Detailid
		INNER JOIN BType c ON (a.BTypeID=c.TypeID)
		INNER JOIN #GetManSTypeId S ON S.TypeId = A.Stypeid
		WHERE 	a.BTypeID=@BUserCode 
				AND b.PTypeID=@PUserCode 
				AND a.BillDate>=@StartDate 
				AND a.BillDate<=@EndDate 
				AND a.BillType=@BillType 
				AND a.ifcheck='t'
				AND a.RedWord = 0
				AND a.ifYearBill=0	 --年节存标志
		IF @szSort='1'
		     SELECT * FROM #TempTable ORDER BY BillDate 
		ELSE IF @szSort='2'
		     SELECT * FROM #TempTable ORDER BY BillCode
		ELSE IF @szSort='3'
		     SELECT * FROM #TempTable ORDER BY TotalMoney
		
		DROP TABLE #TempTable 
	
	END
	
DROP TABLE #GetManSTypeId	














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2004-03-10
	描述：补录借欠的序列号

	修改：谢吉康
	日期：2004-03-30
	描述：增加参数@BFlag  借进时为1 别的为0

	修改：Wang Wei
	日期：2010-06-12
	描述：增加参数@SerialCount  返回商品序列号限制的长度
*/
CREATE    PROCEDURE Gp_AppendLendPTypeSerial
(
		@Serial			VARCHAR(1000),
		@KTypeID		VARCHAR(50),
		@PTypeID		VARCHAR(50),
		@BTypeID1		VARCHAR(50),
		@State			VARCHAR(50),				
		@Flag			VARCHAR(50),
		@BFlag 			VARCHAR(50),
		@strIfSerial	VARCHAR(1),
		@itemid			VARCHAR(200),
		@goodsnumber	VARCHAR(200),
		@iscombined		VARCHAR(200),	
		@SerialCount	varchar(50) OUTPUT --返回商品序列号限制的长度 		
)
--@encode$--
AS
BEGIN

	DECLARE @SerialLen INT,--商品序列号设置的长度
			@serialBool INT--序列号采用严密管理模式
	SET @SerialLen=0
	SET @SerialCount=@SerialLen
	SET @serialBool=0

	SELECT TOP 1 @SerialLen=SerialCount FROM PType WHERE TypeID = @PTypeID AND SonNum = 0 AND IfSerial = 1
	SELECT TOP 1 @serialBool=Value FROM UserConfig WHERE ConfigName='mngserial'	

	IF	@serialBool=1 AND @SerialLen>0
	BEGIN
		IF LEN(@Serial)<>@SerialLen 
		BEGIN
			SET @SerialCount=@SerialLen
			RETURN -11  --RAISERROR('录入的序列号长度不符',16,1)
		END
	END

	SELECT TOP 1 * FROM BType WHERE TypeID = @BTypeID1 AND SonNum = 0	
	IF @@ROWCOUNT=0
		RETURN -2	--RAISERROR('所选往来单位不正确，请确认后重试！',16,1)

	SELECT TOP 1 * FROM PType WHERE TypeID = @PTypeID AND SonNum = 0 AND IfSerial = 1
	
	IF @@ROWCOUNT=0
		RETURN -3	--RAISERROR('所选商品不正确，请确认后重试！',16,1)

	SELECT TOP 1 * FROM STock WHERE TypeID = @KTypeID AND SonNum = 0
	
	IF @@ROWCOUNT=0
		RETURN -4	--RAISERROR('所选仓库不正确，请确认后重试！',16,1)

	DECLARE @Borrow			INT,
			@BorrowBack 	INT,
			@Lend 			INT,
			@LendBack 		INT
	DECLARE @BorrowBackQty  INT,
			@LendBackQty   	INT


	IF @State=19		--借进还出
		BEGIN			
			SELECT @BorrowBackQty=ISNULL(COUNT(Serial),0) FROM GP_LendPTypeSerial WHERE State = 19

			SELECT	@Borrow=ISNULL(SUM(Borrow),0),
					@BorrowBack=ISNULL(SUM(BorrowBack),0)
			FROM	V_LendStatus 
			WHERE	PTypeID=@PTypeID
					AND BTypeId=@BTypeID1 
					AND KTypeId=@KTypeID
	

			IF @@ROWCOUNT=0
				RETURN -5	--RAISERROR('商品没有借进过，请确认后重试！',16,1)
			ELSE
				BEGIN
					IF @Borrow='0'							
						RETURN -5	--RAISERROR('商品没有借进过，请确认后重试！',16,1)
					ELSE IF @BorrowBackQty>=@BorrowBack
						RETURN -6	--RAISERROR('商品借出的数量不匹配，请确认后重试！',16,1)
				END
		END


	IF @State=20			--借出还回
		BEGIN
			SELECT @LendBackQty=ISNULL(COUNT(Serial),0) FROM GP_LendPTypeSerial WHERE State = 20

			SELECT	@Lend=ISNULL(SUM(Lend),0),
					@LendBack=ISNULL(SUM(LendBack),0)
			FROM	V_LendStatus 
			WHERE	PTypeID=@PTypeID
					AND BTypeId=@BTypeID1 
					AND KTypeId=@KTypeID
		
			IF @@ROWCOUNT='0'
				RETURN -7	--RAISERROR('商品没有借出过，请确认后重试！',16,1)
			ELSE
				BEGIN
					IF @Lend=0
						RETURN -7	--RAISERROR('商品没有借出过，请确认后重试！',16,1)
					ELSE IF @LendBackQty>=@LendBack
						RETURN -8	--RAISERROR('商品借出的数量不匹配，请确认后重试！',16,1)
				END

		END


	SELECT * FROM GP_LendPTypeSerial WHERE Serial = @Serial

	IF @@ROWCOUNT<>0
		RETURN 1	--RAISERROR('序列号已存在，请确认后重试！',16,1)
	ELSE
		BEGIN
			IF @Flag = 1							--借进,借出还回
				BEGIN
			      	IF @strIfSerial='1'
						BEGIN
						   SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @Serial AND Flag = 1 --haiquan2008-5-7
			
						   IF @@ROWCOUNT <> 0 
							RETURN -9 --失败	--RAISERROR('序列号库存状况表中有此序列号，不能入库,Flag为1！',16,1)
						END

					INSERT INTO GP_LendPTypeSerial
					(
						Serial,
						KTypeID,
						PTypeID,
						BTypeID2,
						InKTypeTime,
						State,
						Flag,
						Note,
						BFlag,ItemID,GoodsNumber,IsCombined
					)
					VALUES 
					( 
						@Serial,
						@KTypeID,
						@PTypeID,
						@BTypeID1,
						CONVERT(VARCHAR(10),GetDate(),120),
						@State,
						@Flag,
						'补录的借欠序列号',
						@BFlag,@itemid,@goodsnumber,@IsCombined
					)
				END
			ELSE	
				BEGIN								--借出,借进还出
					IF @strIfSerial='1'
						BEGIN
						   SELECT * FROM GP_LendPTypeSerial WHERE Serial = @Serial AND Flag = 0
							IF @@ROWCOUNT <> 0 --序列号已经借出
								RETURN -10	--RAISERROR('序列号已经借出，不能再次借出，请确认后重试！',16,1)
						END
				
					INSERT INTO GP_LendPTypeSerial
					(
						Serial,
						KTypeID,
						PTypeID,
						BTypeID1,
						InKTypeTime,
						State,
						Flag,
						Note,
						BFlag
					)
					VALUES 
					( 
						@Serial,
						@KTypeID,
						@PTypeID,
						@BTypeID1,
						CONVERT(VARCHAR(10),GetDate(),120),
						@State,
						@Flag,
						'补录的借欠序列号',
						@BFlag 
					)
			   END

			IF @@ROWCOUNT <> 0					
				RETURN 0	--RAISERROR('录入序列号成功！',16,1)
			ELSE				
				RETURN -1	--RAISERROR('录入序列号失败，请确认后重试！',16,1)
		END
END















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ApplyToBillCode]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_ApplyToBillCode]
GO

/*
	作者：谢吉康
	日期：2018-01-02
	描述：将单据编号格式应用到其他单据
	
	修改人:陈强
	日期：2019-11-12
	描述: 将单据编号格式应用到其他单据时(如果此时并没有设置单据的编码格式,只是应用该单据的流水号递增规则)
*/
CREATE PROCEDURE [GP_ApplyToBillCode]
(	
	@intBillType				int,	--单据类型
	@intIfKType					INT,	--当前选中的行是否设置了仓库 0为没有设置，1为设置
	@intIfDType					INT		--当前选中的行是否设置了部门
)
--@encode$--
AS

IF @intIfKType=0 AND @intIfDType=0
	BEGIN
		DELETE CodeConfig
		WHERE BillType<>@intBillType
		
		INSERT CodeConfig(Billtype,Code1,Code2,Code3,Code4,Code5,Code6,Code7,Code8,Code9,Code10,Code11,Code12,ETypeID,CodeFlowset)
		SELECT b.Billtype,a.Code1,a.Code2,a.Code3,a.Code4,a.Code5,a.Code6,a.Code7,a.Code8,a.Code9,a.Code10,a.Code11,a.Code12,a.ETypeID,a.CodeFlowset
		FROM CodeConfig a,BillName b
		WHERE a.BillType=@intBillType AND b.BillType<>@intBillType
	END
ELSE IF @intIfKType=0 AND @intIfDType!=0
	BEGIN
		DELETE CodeConfig
		WHERE BillType NOT IN (@intBillType,306)
		
		INSERT CodeConfig(Billtype,Code1,Code2,Code3,Code4,Code5,Code6,Code7,Code8,Code9,Code10,Code11,Code12,ETypeID,CodeFlowset)
		SELECT b.Billtype,a.Code1,a.Code2,a.Code3,a.Code4,a.Code5,a.Code6,a.Code7,a.Code8,a.Code9,a.Code10,a.Code11,a.Code12,a.ETypeID,a.CodeFlowset 
		FROM CodeConfig a,BillName b
		WHERE a.BillType=@intBillType AND b.BillType NOT IN  (@intBillType,306)
	
		IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='FlowSet')
			INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowSet','1','','')
		ELSE
			UPDATE UserConfig SET Value='1' WHERE ConfigName='FlowSet'
	END
ELSE  IF  @intIfKType!=0 AND  @intIfDType=0
	BEGIN
		DELETE CodeConfig
		WHERE BillType<>@intBillType AND (BillType IN (305,300,11,45,160,140,142,301,34,6,161,144,146,17,21,9,14,57,306,16,139,126,9,178,183,71,72,87,88,187,188,191,197,196,71,72,87,88,201,202,400,401,402,403,423,424,425,426) OR Billtype IN(SELECT billtype FROM BillName WHERE (Billtypes =4 OR billtypes=8)AND billtype<>171))
		
		INSERT CodeConfig(Billtype,Code1,Code2,Code3,Code4,Code5,Code6,Code7,Code8,Code9,Code10,Code11,Code12,ETypeID,CodeFlowset)
		SELECT b.Billtype,a.Code1,a.Code2,a.Code3,a.Code4,a.Code5,a.Code6,a.Code7,a.Code8,a.Code9,a.Code10,a.Code11,a.Code12,a.ETypeID,a.CodeFlowset 
		FROM CodeConfig a,BillName b
		WHERE a.BillType=@intBillType AND b.BillType<>@intBillType AND (b.BillType IN (193,194,305,300,11,45,160,140,142,301,34,6,161,144,146,17,21,9,14,57,16,139,126,9,178,183,71,72,87,88,187,188,191,197,196,71,72,87,88,201,202,306,400,401,402,403,423,424,425,426) OR b.Billtype IN(SELECT billtype FROM BillName WHERE (Billtypes =4 OR billtypes=8)AND billtype<>171))
	
		IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='FlowSet')
			INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowSet','1','','')
		ELSE
			UPDATE UserConfig SET Value='1' WHERE ConfigName='FlowSet'
	
	END	
ELSE IF @intIfKType!=0  AND @intIfDType!=0
	BEGIN
		DELETE CodeConfig
		WHERE BillType<>@intBillType AND (BillType IN (305,300,11,45,160,140,142,301,34,6,161,144,146,17,21,9,14,57,16,139,126,9,178,183,71,72,87,88,187,188,191,197,196,71,72,87,88,201,202,400,401,402,403,423,424,425,426) OR Billtype IN(SELECT billtype FROM BillName WHERE  billtypes=8))
		
		INSERT CodeConfig(Billtype,Code1,Code2,Code3,Code4,Code5,Code6,Code7,Code8,Code9,Code10,Code11,Code12,ETypeID,CodeFlowset)
		SELECT b.Billtype,a.Code1,a.Code2,a.Code3,a.Code4,a.Code5,a.Code6,a.Code7,a.Code8,a.Code9,a.Code10,a.Code11,a.Code12,a.ETypeID,a.CodeFlowset 
		FROM CodeConfig a,BillName b
		WHERE a.BillType=@intBillType AND b.BillType<>@intBillType AND (b.BillType IN (193,194,305,300,11,45,160,140,142,301,34,6,161,144,146,17,21,9,14,57,16,139,126,9,178,183,71,72,87,88,187,188,191,197,196,71,72,87,88,201,202,400,401,402,403,423,424,425,426) OR b.Billtype IN(SELECT billtype FROM BillName WHERE Billtypes =8 AND billtype<>171))
	
		IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='FlowSet')
			INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowSet','1','','')
		ELSE
			UPDATE UserConfig SET Value='1' WHERE ConfigName='FlowSet'
	END	

--特殊处理提成单，没有经手人选项
UPDATE CodeConfig
SET		Code1 = REPLACE(Code1,'经手人编号',''),
		Code2 = REPLACE(Code2,'经手人编号',''),
		Code3 = REPLACE(Code3,'经手人编号',''),
		Code4 = REPLACE(Code4,'经手人编号',''),
		Code5 = REPLACE(Code5,'经手人编号',''),
		Code6 = REPLACE(Code6,'经手人编号',''),
		Code7 = REPLACE(Code7,'经手人编号',''),
		Code8 = REPLACE(Code8,'经手人编号',''),
		Code9 = REPLACE(Code9,'经手人编号',''),
		Code10 = REPLACE(Code10,'经手人编号',''),
		Code11 = REPLACE(Code11,'经手人编号',''),
		Code12 = REPLACE(Code12,'经手人编号',''),
		Code13 = REPLACE(Code13,'经手人编号','')
WHERE	BillType = 311		
		

GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_AppraisalBackBill_CreateReciptBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_AppraisalBackBill_CreateReciptBill]
GO




/*

功能说明：		暂估退后单过帐后生成采购暂估开票的草稿

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_AppraisalBackBill_CreateReciptBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
*/

DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT


SELECT @intReturnID=0

DECLARE 
	@strFromBillCode 				VARCHAR(100),
	@datBillDate					DATETIME





DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号


DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@strETypeID			VARCHAR(50),
	@strKTypeID			VARCHAR(50),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@intBillType		INT,
	@strSTypeID			VARCHAR(50),
	@strBTypeID			VARCHAR(50),
	@intCID				INT,
	@OldRate			 NUMERIC(24, 10) ,
	@NewRate			 NUMERIC(24, 10) ,
	@ceCheckId			VARCHAR(100),
	@ceDtypeid			VARCHAR(100),
	@cefullname			VARCHAR(500)='',		--制单人
	@cdfullname			VARCHAR(500)=''			--部门
	
DECLARE 
		@strOPRate	VARCHAR(50),
		@CID		INT,
		@SysCid		INT
		
--本位币	
SELECT @SysCid= CID FROM dbo.Ac_Currency WHERE Sysrow=1	

	
	
SELECT @strETypeID=ETypeID,@strKTypeID=KTypeID,@datBillDate=BillDate,@strSTypeID=StypeID,@strFromBillCode=BillCode,@ceCheckId=checke,
	@intCID=CID,@OldRate=Rate,@ceDtypeid=DTypeId
FROM BillIndex
WHERE BillNumberID=@nBillID	

SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

SELECT @strOPRate=BasisType,@NewRate=Rate
FROM Ac_Currency				
WHERE CId=@intCID

IF @strOPRate='0'
BEGIN
	SELECT @strOPRate='*'
END
ELSE
BEGIN
	SELECT @strOPRate='/'
END
	

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT
	@strETypeID='',
	@strKTypeID='',
	@VchHead='CZG',
	@intBillType=404
	
IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = TypeId FROM Employee WHERE TypeID = @strETypeID
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @strKTypeID
END

SELECT 
	@MONTH=ISNULL(@MONTH,''),
	@DAY=ISNULL(@DAY,'')


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname

IF @Re <> 0
RETURN -2	




DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000),
	@BillName		VARCHAR(50)
	
SELECT @BillName=BillName
FROM BillName
WHERE 	Billtype=401
	
	
SELECT 
	@strComment='该采购暂估开票是从'+@BillName+@strFromBillCode+'生成而来的！'

--生成采购暂估开票单的草稿
--生成表头




DECLARE
	@strTempATypeID1		VARCHAR(100),
	@strTempATypeID2		VARCHAR(100)
	
SELECT
	@strTempATypeID1=ATypeID
FROM BillAtype
WHERE BillTypeId='404_jie'
AND StypeId=@strSTypeID

SELECT
	@strTempATypeID2=ATypeID
FROM BillAtype
WHERE BillTypeId='404_dai'
AND StypeId=@strSTypeID


SELECT @strTempATypeID1=ISNULL(@strTempATypeID1,''),@strTempATypeID2=ISNULL(@strTempATypeID2,'')


INSERT ReceiptBillIndex(BillDate,BillCode,BillType,DealBTypeID,BTypeID,STypeID,ETypeID,
Comment,totalmoney,totalqty,tax,period,explain,AlertDay,DTypeId,
ifcheck,IfAudit,draft,checke,NTotalMoney,CID,Rate,ATypeID1,ATypeID2,TaxTotalMoney,NTaxTotalMoney)
SELECT BillDate,@strBillCode,@intBillType,DealBTypeID,btypeid,@strSTypeID,
etypeid,@strComment,-totalmoney,-totalqty,tax,period,explain,AlertDay,DTypeId,
'f',0,1,@chvOpID,-NTotalMoney,CID,Rate,@strTempATypeID1,@strTempATypeID2,-totalmoney,-NTotalMoney
FROM BillIndex
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();


--生成表体



INSERT ReceiptBill(BillNumberId,BillType,MainBillNumberID,RecordedItemId,MainBillType,
KTypeID,PTypeID,Qty,Price,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,discount,Nprice,NTotal,NTaxPrice,NTaxTotal,taxmoney,NTaxMoney,
CargoID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MUnitRate,MUnitMsg,MTaxPrice,CurMPrice,CurMTaxPrice,
ItemID,IsCombined,BeforePrice,BeforeTotal,Nbeforeprice,NBeforeTotal,goodsnumber,
saleprice,saletotal,nsaleprice,nsaletotal,curmsaleprice,curmsaletotal,IsGift,ProduceDate,ValidDate,
Serial,InvoiceCostPrice,InvoiceCostTotal,MQty,ShowOrder)
SELECT @intReturnID,404,BillNumberId,ID,401,
KTypeID,PTypeID,-Qty,DiscountPrice,-Total,Tax,TaxPrice,-TaxTotal,Comment,Stypeid,1,NDiscountPrice,-NTotal,NTaxPrice,-NTaxTotal,-taxmoney,-NTaxMoney,
CargoID,UnitID,NUnitID,-NQty,UnitRate,NUnitMsg,MUnitID,MUnitRate,MUnitMsg,MTaxPrice,CurMDiscountPrice,CurMTaxPrice,
ItemID,IsCombined,DiscountPrice,-Total,NDiscountPrice,-NTotal,goodsnumber,
DiscountPrice,-total,NDiscountPrice,-NTotal,CurMDiscountPrice,-NTotal,IsGift,ProduceDate,ValidDate,
Serial,costprice,-CostTotal,-MQty,ShowOrder
FROM AppraisalBackBill
WHERE BillNumberId=@nBillID
--设置排序号
UPDATE dbo.ReceiptBill SET ShowOrder=ID WHERE BillNumberID=@intReturnID

--同步自定义字段
IF EXISTS(SELECT 1 FROM dbo.Custom_BillIndex WHERE BillId=@nBillID AND BillType=401)
BEGIN
	INSERT INTO dbo.Custom_BillIndex( BillId ,BillType ,
			  SysDiy1_head ,SysDiy2_head ,SysDiy3_head ,
			  SysDiy4_head ,SysDiy5_head ,SysDiy6_head ,
	          SysDiy7_head ,SysDiy8_head ,SysDiy9_head ,
	          SysDiy10_head ,SysDiy11_head ,SysDiy12_head ,
	          SysDiy13_head ,SysDiy14_head ,SysDiy15_head ,
	          SysDiy16_head
	        )
	SELECT	  @intReturnID ,404 ,SysDiy1_head ,SysDiy2_head ,
	          SysDiy3_head ,SysDiy4_head ,SysDiy5_head ,
	          SysDiy6_head ,SysDiy7_head ,SysDiy8_head ,
	          SysDiy9_head ,SysDiy10_head ,SysDiy11_head ,
	          SysDiy12_head ,SysDiy13_head , SysDiy14_head ,
	          SysDiy15_head ,SysDiy16_head
	FROM dbo.Custom_BillIndex WHERE BillId=@nBillID AND BillType=401
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Custom_BillDetails WHERE BillId=@nBillID AND BillType=401)
BEGIN
	INSERT INTO dbo.Custom_BillDetails( BillId ,Detailid ,BillType ,
	          SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,
	          SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,
	          SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16
	        )
	SELECT	  @intReturnID ,B.ID ,404 ,
	          A.SysDiy1 ,A.SysDiy2 ,A.SysDiy3 ,A.SysDiy4 ,A.SysDiy5 ,A.SysDiy6 ,
	          A.SysDiy7 ,A.SysDiy8 ,A.SysDiy9 ,A.SysDiy10 ,A.SysDiy11 ,A.SysDiy12 ,
	          A.SysDiy13 ,A.SysDiy14 ,A.SysDiy15 ,A.SysDiy16
	FROM dbo.Custom_BillDetails A INNER JOIN dbo.ReceiptBill B ON A.Detailid=B.RecordedItemId 
		 AND A.BillId=B.MainBillNumberID AND A.BillType=B.MainBillType
		 WHERE A.BillId=@nBillID AND A.BillType=401 AND B.BillNumberID=@intReturnID
END

DECLARE
	@decTotalmoney	 NUMERIC(24, 10) ,
	@decNTotalMoney	 NUMERIC(24, 10) ,
	@decTaxTotalMoney	 NUMERIC(24, 10) ,
	@decNTaxTotalMoney	 NUMERIC(24, 10) 
	
SELECT @decTotalmoney=SUM(-Total),@decNTotalMoney=SUM(-NTotal),@decTaxTotalMoney=SUM(-TaxTotal),@decNTaxTotalMoney=SUM(-NTaxTotal)
FROM AppraisalBackBill
WHERE BillNumberID=@nBillID	


UPDATE ReceiptBillIndex
SET TotalMoney=@decTotalmoney,NTotalMoney=@decNTotalMoney,TaxTotalMoney=@decTaxTotalMoney,NTaxTotalMoney=@decNTaxTotalMoney
WHERE BillNumberID=@intReturnID

IF @intCID<>@SysCid AND @NewRate<>@OldRate
BEGIN
	--先根据原币计算表体的本币
	IF @strOPRate='*'
	BEGIN
		UPDATE ReceiptBill
		SET Total=ROUND(Ntotal*CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot),
		TaxTotal=ROUND(NTaxTotal*CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot)
		WHERE BillNumberId=@intReturnID 
	END
	ELSE
	BEGIN
		UPDATE ReceiptBill
		SET Total=ROUND(NTotal/CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot),
		TaxTotal=ROUND(NTaxTotal/CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot)
		WHERE BillNumberId=@intReturnID 
	END
	
	UPDATE ReceiptBill
	SET Price=CASE QTY WHEN 0 THEN 0 ELSE ROUND(CAST(Total AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) END,
	TaxPrice=CASE QTY WHEN 0 THEN 0 ELSE ROUND(CAST(TaxTotal AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) END
	WHERE BillNumberId=@intReturnID 
	--再根据表体的本币得到表头的本币
	
	SELECT @decTotalmoney=SUM(Total),@decTaxTotalMoney=SUM(TaxTotal)
	FROM ReceiptBill
	WHERE BillNumberID=@intReturnID	
	
	UPDATE ReceiptBillIndex
	SET TotalMoney=@decTotalmoney,Rate=@NewRate,TaxTotalMoney=@decTaxTotalMoney
	WHERE BillNumberID=@intReturnID
END


--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END


GO


/*

DECLARE
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0),			--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100),
	@strErrMsg				VARCHAR(100)			--出错信息
	
SELECT
	@chvOpID=1,
	@nBillID=1
	
BEGIN TRAN	

EXEC	GP_AppraisalBackBill_CreateReciptBill
	@chvOpID,
	@nBillID,
	@intReturnID OUT,
	@strReturnBillCode OUT,
	@strErrMsg OUT

SELECT @strReturnBillCode,@strErrMsg

SELECT * FROM receiptbillindex

SELECT * FROM receiptBill

ROLLBACK TRAN

*/





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_AppraisalBill_CreateReciptBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_AppraisalBill_CreateReciptBill]
GO




/*

功能说明：		暂估单过帐后生成采购暂估开票的草稿

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_AppraisalBill_CreateReciptBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
*/	

DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT
		
SELECT @intReturnID=0

DECLARE 
	@strFromBillCode 				VARCHAR(100),
	@datBillDate					DATETIME





DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号


DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@strETypeID			VARCHAR(50),
	@strKTypeID			VARCHAR(50),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@intBillType		INT,
	@strSTypeID			VARCHAR(50),
	@strBTypeID			VARCHAR(50),
	@intCID				INT,
	@OldRate			 NUMERIC(24, 10) ,
	@NewRate			 NUMERIC(24, 10) ,
	@ceCheckId			VARCHAR(100),
	@ceDtypeid			VARCHAR(100),
	@cefullname			VARCHAR(500)='',		--制单人
	@cdfullname			VARCHAR(500)=''			--部门
	
DECLARE 
		@strOPRate	VARCHAR(50),
		@CID		INT,
		@SysCid		INT
		
--本位币	
SELECT @SysCid= CID FROM dbo.Ac_Currency WHERE Sysrow=1	


	
SELECT @strETypeID=ETypeID,@strKTypeID=KTypeID,@datBillDate=BillDate,@strSTypeID=StypeID,@strFromBillCode=BillCode,@ceCheckId=checke,@ceDtypeid=DTypeId,
	@intCID=CID,@OldRate=Rate
FROM BillIndex
WHERE BillNumberID=@nBillID	

SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

SELECT @strOPRate=BasisType,@NewRate=Rate
FROM Ac_Currency				
WHERE CId=@intCID

IF @strOPRate='0'
BEGIN
	SELECT @strOPRate='*'
END
ELSE
BEGIN
	SELECT @strOPRate='/'
END

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT
	@strETypeID='',
	@strKTypeID='',
	@VchHead='CZG',
	@intBillType=404
	
IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = TypeId FROM Employee WHERE TypeID = @strETypeID
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @strKTypeID
END

SELECT 
	@MONTH=ISNULL(@MONTH,''),
	@DAY=ISNULL(@DAY,'')


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname

IF @Re <> 0
RETURN -2	




DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000),
	@BillName		VARCHAR(50)
	
SELECT @BillName=BillName
FROM BillName
WHERE 	Billtype=400
	
	
SELECT 
	@strComment='该采购暂估开票是从'+@BillName+@strFromBillCode+'生成而来的！'

--生成采购暂估开票单的草稿
--生成表头




DECLARE
	@strTempATypeID1		VARCHAR(100),
	@strTempATypeID2		VARCHAR(100)
	
SELECT
	@strTempATypeID1=ATypeID
FROM BillAtype
WHERE BillTypeId='404_jie'
AND StypeId=@strSTypeID

SELECT
	@strTempATypeID2=ATypeID
FROM BillAtype
WHERE BillTypeId='404_dai'
AND StypeId=@strSTypeID


SELECT @strTempATypeID1=ISNULL(@strTempATypeID1,''),@strTempATypeID2=ISNULL(@strTempATypeID2,'')



INSERT ReceiptBillIndex(BillDate,BillCode,BillType,DealBTypeID,BTypeID,STypeID,ETypeID,
Comment,totalmoney,totalqty,tax,period,explain,AlertDay,DTypeId,
ifcheck,IfAudit,draft,checke,NTotalMoney,CID,Rate,ATypeID1,ATypeID2,TaxTotalMoney,NTaxTotalMoney)
SELECT BillDate,@strBillCode,@intBillType,DealBTypeID,btypeid,@strSTypeID,
etypeid,@strComment,totalmoney,totalqty,tax,period,explain,AlertDay,DTypeId,
'f',0,1,@chvOpID,NTotalMoney,CID,Rate,@strTempATypeID1,@strTempATypeID2,totalmoney,NTotalMoney
FROM BillIndex
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();


--生成表体



INSERT ReceiptBill(BillNumberId,BillType,MainBillNumberID,RecordedItemId,MainBillType,
KTypeID,PTypeID,Qty,Price,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,discount,Nprice,NTotal,NTaxPrice,NTaxTotal,taxmoney,NTaxMoney,
CargoID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MUnitRate,MUnitMsg,MTaxPrice,CurMPrice,CurMTaxPrice,
ItemID,IsCombined,BeforePrice,BeforeTotal,Nbeforeprice,NBeforeTotal,goodsnumber,
saleprice,saletotal,nsaleprice,nsaletotal,curmsaleprice,curmsaletotal,IsGift,ProduceDate,ValidDate,
Serial,InvoiceCostPrice,InvoiceCostTotal,MQty,ShowOrder)
SELECT @intReturnID,404,BillNumberId,ID,400,
KTypeID,PTypeID,Qty,DiscountPrice,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,1,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,taxmoney,NTaxMoney,
CargoID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MUnitRate,MUnitMsg,MTaxPrice,CurMDiscountPrice,CurMTaxPrice,
ItemID,IsCombined,DiscountPrice,Total,NDiscountPrice,NTotal,goodsnumber,
DiscountPrice,total,NDiscountPrice,NTotal,CurMDiscountPrice,NTotal,IsGift,ProduceDate,ValidDate,
Serial,DiscountPrice,total,MQty,ShowOrder
FROM AppraisalBill
WHERE BillNumberId=@nBillID


--同步自定义字段
IF EXISTS(SELECT 1 FROM dbo.Custom_BillIndex WHERE BillId=@nBillID AND BillType=400)
BEGIN
	INSERT INTO dbo.Custom_BillIndex( BillId ,BillType ,
			  SysDiy1_head ,SysDiy2_head ,SysDiy3_head ,
			  SysDiy4_head ,SysDiy5_head ,SysDiy6_head ,
	          SysDiy7_head ,SysDiy8_head ,SysDiy9_head ,
	          SysDiy10_head ,SysDiy11_head ,SysDiy12_head ,
	          SysDiy13_head ,SysDiy14_head ,SysDiy15_head ,
	          SysDiy16_head
	        )
	SELECT	  @intReturnID ,404 ,SysDiy1_head ,SysDiy2_head ,
	          SysDiy3_head ,SysDiy4_head ,SysDiy5_head ,
	          SysDiy6_head ,SysDiy7_head ,SysDiy8_head ,
	          SysDiy9_head ,SysDiy10_head ,SysDiy11_head ,
	          SysDiy12_head ,SysDiy13_head , SysDiy14_head ,
	          SysDiy15_head ,SysDiy16_head
	FROM dbo.Custom_BillIndex WHERE BillId=@nBillID AND BillType=400
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Custom_BillDetails WHERE BillId=@nBillID AND BillType=400)
BEGIN
	INSERT INTO dbo.Custom_BillDetails( BillId ,Detailid ,BillType ,
	          SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,
	          SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,
	          SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16
	        )
	SELECT	  @intReturnID ,B.ID ,404 ,
	          A.SysDiy1 ,A.SysDiy2 ,A.SysDiy3 ,A.SysDiy4 ,A.SysDiy5 ,A.SysDiy6 ,
	          A.SysDiy7 ,A.SysDiy8 ,A.SysDiy9 ,A.SysDiy10 ,A.SysDiy11 ,A.SysDiy12 ,
	          A.SysDiy13 ,A.SysDiy14 ,A.SysDiy15 ,A.SysDiy16
	FROM dbo.Custom_BillDetails A INNER JOIN dbo.ReceiptBill B ON A.Detailid=B.RecordedItemId 
		 AND A.BillId=B.MainBillNumberID AND A.BillType=B.MainBillType
		 WHERE A.BillId=@nBillID AND A.BillType=400 AND B.BillNumberID=@intReturnID
END

DECLARE
	@decTotalmoney	 NUMERIC(24, 10) ,
	@decNTotalMoney	 NUMERIC(24, 10) ,
	@decTaxTotalMoney	 NUMERIC(24, 10) ,
	@decNTaxTotalMoney	 NUMERIC(24, 10) 
	
SELECT @decTotalmoney=SUM(Total),@decNTotalMoney=SUM(NTotal),@decTaxTotalMoney=SUM(TaxTotal),@decNTaxTotalMoney=SUM(NTaxTotal)
FROM AppraisalBill
WHERE BillNumberID=@nBillID	


UPDATE ReceiptBillIndex
SET TotalMoney=@decTotalmoney,NTotalMoney=@decNTotalMoney,TaxTotalMoney=@decTaxTotalMoney,NTaxTotalMoney=@decNTaxTotalMoney
WHERE BillNumberID=@intReturnID



IF @intCID<>@SysCid AND @NewRate<>@OldRate
BEGIN
	--先根据原币计算表体的本币
	IF @strOPRate='*'
	BEGIN
		UPDATE ReceiptBill
		SET Total=ROUND(Ntotal*CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot),
		TaxTotal=ROUND(NTaxTotal*CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot)
		WHERE BillNumberId=@intReturnID 
		
		
	END
	ELSE
	BEGIN
		UPDATE ReceiptBill
		SET Total=ROUND(NTotal/CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot),
		TaxTotal=ROUND(NTaxTotal/CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot)
		WHERE BillNumberId=@intReturnID 
	END
	
	
	UPDATE ReceiptBill
	SET Price=CASE QTY WHEN 0 THEN 0 ELSE ROUND(CAST(Total AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) END,
	TaxPrice=CASE QTY WHEN 0 THEN 0 ELSE ROUND(CAST(TaxTotal AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) END
	WHERE BillNumberId=@intReturnID 
	--再根据表体的本币得到表头的本币
	
	SELECT @decTotalmoney=SUM(Total),@decTaxTotalMoney=SUM(TaxTotal)
	FROM ReceiptBill
	WHERE BillNumberID=@intReturnID	
	
	UPDATE ReceiptBillIndex
	SET TotalMoney=@decTotalmoney,Rate=@NewRate,TaxTotalMoney=@decTaxTotalMoney
	WHERE BillNumberID=@intReturnID
	
END




--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END


GO


/*

DECLARE
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0),			--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100),
	@strErrMsg				VARCHAR(100)			--出错信息
	
SELECT
	@chvOpID=1,
	@nBillID=4
	
BEGIN TRAN	

EXEC	GP_AppraisalBill_CreateReciptBill
	@chvOpID,
	@nBillID,
	@intReturnID OUT,
	@strReturnBillCode OUT,
	@strErrMsg OUT

SELECT @strReturnBillCode,@strErrMsg

SELECT totalmoney,taxtotalmoney,ntotalmoney,ntaxtotalmoney,rate,* FROM receiptbillindex

SELECT total,ntotal,taxtotal,ntaxtotal,* FROM receiptBill

ROLLBACK TRAN

*/







SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		附件保存
-- 最后修改：		冯波
-- 修改时间：		2011-06-21
-- ========================================================================
CREATE    PROCEDURE GP_Attachment_Update
(
	@BillNumberID		numeric(18,0),	-- 单据 ID 
	@BillGUID			VARCHAR(500)
)
--@encode$--
AS

	SET NOCOUNT ON
	
	UPDATE BillAttachFiles
	SET BillNumberId=@BillNumberID
	WHERE BillGuid=@BillGUID
	
	UPDATE BillAttachFilesLog
	SET BillNumberId=@BillNumberID
	WHERE BillGuid=@BillGUID
	
	




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		收付款单过账（影响应收、应付科目的部分放到gp_auditarap中了）
--					
-- 最后修改作者：	毛欣蓉
-- 最后修改时间：	2012-06-09
-- ========================================================================
CREATE	PROCEDURE GP_AType_GatherPayBill 
(
	@nBillID		NUMERIC(10,0),
	@intBillType	INT,
	@datBillDate	DATETIME,
	@chvBTypeID		VARCHAR(50),
	@chvETypeID		VARCHAR(50),
	@chvDTypeID		varchar(50),
	@chvSTypeID		varchar(50),
	@CID			BIGINT,
	@Rate			 NUMERIC(24, 10) ,
	@strErrMsg		VARCHAR(100) OUT,
	@STypeID		VARCHAR(100)

)
--@encode$--
AS

	SET NOCOUNT ON
	
	
DECLARE					
		@chvATypeID					VARCHAR(50),						
		@intReturnCode				INT,
		@Total						 NUMERIC(24, 10) ,
		@NTotal						 NUMERIC(24, 10) ,
		@intVipCardID				int,
		@chrIfVipJF					char(1),
		@chvVipIsCz					char(1),
		@numVipcZyeMoney			 NUMERIC(24, 10) ,--会员卡合计储值余额
		@StypeVipcZyeMoney			NUMERIC(24, 10),--会员卡所在分支机构储值余额
		@intVipJF					int,
		@YS_ID						VARCHAR(50),
		@YF_ID						VARCHAR(50),
		@VIP_ID						VARCHAR(50),
		@syscid						INT,
		@vipBillStoredByStypeId INT--会员储值结算使用单据所选分支机构进行储值余额判断
SELECT @vipBillStoredByStypeId=Value FROM Userconfig WHERE ConfigName='vipBillStoredByStypeId'

SELECT @VIP_ID=nId FROM Ac_Items WHERE UserCode='2181' --会员储值
SELECT @YS_ID=nId FROM Ac_Items WHERE UserCode='2131'  --预收
SELECT @YF_ID=nId FROM Ac_Items WHERE UserCode='1151'  --预付

SELECT @syscid=CId FROM Ac_Currency WHERE Sysrow = 1

SET @strErrMsg=''
IF @intBillType = 4
BEGIN
	DECLARE PreGathering_cursor CURSOR FOR
	SELECT ATypeID,Total,vipcardid,Ntotal
	FROM GatheringBill 
	WHERE BillNumberID=@nBillID
END
ELSE
BEGIN
	DECLARE PreGathering_cursor CURSOR FOR
	SELECT ATypeID,Total,vipcardid,Ntotal
	FROM PayBill 
	WHERE BillNumberID=@nBillID
END
	OPEN PreGathering_cursor

	FETCH NEXT FROM PreGathering_cursor
	INTO @chvATypeID,@total,@intVipCardID,@Ntotal

	WHILE @@FETCH_STATUS = 0 AND @strErrMsg=''
	BEGIN
		--账目
		IF @@ERROR=0 AND LTRIM(RTRIM(@strErrMsg))='' AND @total<>0
		BEGIN
			IF @chvATypeID = @VIP_ID AND @intBillType=4
			BEGIN
				IF @intVipCardID <> -1
				BEGIN
					--判断是否适用当前分支机构
					IF  NOT EXISTS(SELECT * FROM nVipCardSign WHERE VipCardID=@intVipCardID AND (isApplyAllStype=1 OR (isApplyAllStype=0 AND EXISTS(SELECT * FROM VipCard_ApplyStype APS WHERE APS.StypeId=@STypeID AND APS.VipCardId=VipCardID ))))	
						RETURN 	706	
			
					--余额为对应分支机构会员卡余额
					SELECT	@chrIfVipJF = b.ifJF,
							@chvVipIsCz = a.IsCz,
							@numVipcZyeMoney = a.cZyeMoney,
							@StypeVipcZyeMoney=ISNULL(ss.cZyeMoney,0)
					FROM	nVipCardSign a
					INNER JOIN nVipCardSet b ON a.VipCardTypeID = b.VipCardTypeID AND a.VipCardID = @intVIPCardID AND a.Deleted = 0 AND B.deleted=0 AND a.EndDate >= @datBillDate
					LEFT JOIN nVipCardSignStype ss ON SS.VipCardID=A.VipCardID AND ss.StypeId=@StypeID
							
	
					-- 1)无此VIP卡 2)过了有效期 3)VIP卡是未启用状态 4)VIP卡类型不存在或已删除
					IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN 701
					SET @intVipJF = 0
					

					IF  @chvVipIsCz <> '1' RETURN 702
					IF  @chvVipIsCz = '1'
					BEGIN
						IF @total < 0 RETURN 703
						IF @total > ISNULL(@numVipcZyeMoney,0) RETURN 704
						IF(@vipBillStoredByStypeId=1 AND @total > ISNULL(@StypeVipcZyeMoney,0)) RETURN 707
					END
					IF @chvVipIsCz = '1'
					BEGIN
						-- 过账时将VIP会员储值卡的消费前余额记入至BillIndex中
						UPDATE BillIndex SET vipCZMoney =ISNULL(@numVipcZyeMoney,0) WHERE BillNumberID = @nBillID
						IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN -10
					END
					
					-- 扣减会员储值余额
					IF @chvVipIsCz = '1' AND @total > 0
					BEGIN
						UPDATE	nVipCardSign
						SET		cZyeMoney = cZyeMoney - @total
						WHERE	VipCardID = @intVipCardID
						
						IF EXISTS(SELECT TOP 1 1 FROM nVipCardSignStype WHERE VipCardID=@intVipCardID AND StypeId=@STypeID)
						BEGIN
							UPDATE dbo.nVipCardSignStype 
							SET		cZyeMoney=cZyeMoney-@Total,
									bNxFczMoney=bNxFczMoney+@Total,
									lJxFczMoney=lJxFczMoney+@Total
							WHERE VipCardID=@intVipCardID AND StypeId=@STypeID
						END
						ELSE
						BEGIN
							INSERT INTO dbo.nVipCardSignStype
							        ( VipCardID ,
							          StypeId ,
							          qCczMoney ,
							          lJczMoney ,
							          lJxFczMoney ,
							          bNczMoney ,
							          bNxFczMoney ,
							          cZyeMoney ,
							          lJxFMoney ,
							          bNxFMoney
							        )
							VALUES  ( @intVipCardID , -- VipCardID - int
							          @STypeID , -- StypeId - varchar(50)
							          0 , -- qCczMoney - numeric
							          0 , -- lJczMoney - numeric
							          @Total , -- lJxFczMoney - numeric
							          0 , -- bNczMoney - numeric
							          @Total , -- bNxFczMoney - numeric
							          -1*@Total , -- cZyeMoney - numeric
							          0 , -- lJxFMoney - numeric
							          0  -- bNxFMoney - numeric
							        )
						END
					END
				END
				
				SELECT @total = @total*(-1)--,@NTotal = -@NTotal
				
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
					@total,null,null,@chvDTypeID,@chvSTypeID,@syscid,@total,1
					
				--EXEC @intReturnCode = GP_AType_Total_AddEdit @chvATypeID,@chvSTypeID,@CID,@total,@NTotal,@strErrMsg OUTPUT 
			END
			ELSE
			BEGIN
				IF @chvATypeID IN(@YS_ID,@YF_ID)
				 BEGIN
				   SELECT @total = -@total,@NTotal = -@NTotal 
				 END
				 ELSE IF  @intBillType = 66  
				 BEGIN
					SELECT @total = -@total,@NTotal = -@NTotal 
				 END
				
				
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
				@total,null,null,@chvDTypeID,@chvSTypeID,@CID,@NTotal,@Rate

				--EXEC @intReturnCode = GP_AType_Total_AddEdit @chvATypeID,@chvSTypeID,@CID,@total,@NTotal,@strErrMsg OUTPUT
			END
		END

		FETCH NEXT FROM PreGathering_cursor
		INTO @chvATypeID,@Total,@intVipCardID,@NTotal
	END
	CLOSE PreGathering_cursor
	DEALLOCATE PreGathering_cursor
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		
--					
-- 最后修改作者：shushan	
-- 最后修改时间：	
-- ========================================================================
CREATE	PROCEDURE GP_AType_MoneyBill 
(
	@nBillID		NUMERIC(10,0)
)
--@encode$--
AS

	SET NOCOUNT ON
 DECLARE 
	@dBcAr   NUMERIC(24, 10) , --本次应收
	@dBcAp   NUMERIC(24, 10) , --本次应付
	@NdBcAr  NUMERIC(24, 10) , --本次应收（原币）
	@ndBcAp  NUMERIC(24, 10)  , --本次应付（原币）
	@AP_ID	 VARCHAR(50),
	@szJobNumber VARCHAR(20),
	@PreGathering_ID	varchar(50),
	@OutFactoryDate DATETIME,
	@AR_ID VARCHAR(50)
	
SELECT @AP_ID =nid
FROM Ac_Items
WHERE UserCode='2121'			--应付

SELECT @PreGathering_ID =nid
FROM Ac_Items
WHERE UserCode='2131'			--预收账款


SELECT @AR_ID =nid
FROM Ac_Items
WHERE UserCode='987'			--应收

DECLARE					
		@szAtypeIdtemp VARCHAR(50),	
		@dTotal  NUMERIC(24, 10) ,					
		@nBillType NUMERIC(4, 0),
		@tBillDate DATETIME,
		@szDTypeId VARCHAR(50),
		@szAtypeId VARCHAR(50),
		@szbTypeId VARCHAR(50),
		@szEtypeId VARCHAR(50),
		@szSTypeID VARCHAR(50),
		@Npreferencemoney  NUMERIC(24, 10) ,
		@NdTotalMoney  NUMERIC(24, 10) ,
		@NdTotalinMoney  NUMERIC(24, 10) ,
		@NdTotal  NUMERIC(24, 10) ,
		@intCID	INT,
		@DecRate  NUMERIC(24, 10) ,
		@chargeOffType INT,
		@chargeOffBtypeid VARCHAR(50),
		@dTotalMoney  NUMERIC(24, 10) ,
		@dTotalinMoney  NUMERIC(24, 10) ,
		@preferencemoney  NUMERIC(24, 10) ,
		@intReturnCode				INT
 SELECT 
		@nBillType=BillType,
		@tBillDate=BillDate,
		@szDTypeId=DTypeID,
		@szAtypeId=atypeid,
		@szbTypeId=btypeid,
		@szEtypeId=etypeid,
		@dTotalMoney=totalmoney,
		@dTotalinMoney=TotalInMoney,
		@preferencemoney=preferencemoney,
		@NdTotalMoney=Ntotalmoney,
		@NdTotalinMoney=NTotalInMoney,
		@Npreferencemoney=Npreferencemoney,
		@szSTypeID=STypeID,
		@intCID=CID,
		@DecRate=Rate,
		@chargeOffType=ChargeOffType,
		@chargeOffBtypeid=ChargeOffBtypeid
 FROM BillIndex WHERE BillNumberId=@nBillId


DECLARE CreateOther_cursor CURSOR FOR
SELECT	a.atypeid,
		a.Total,
		a.NTotal,
		b.CID,
		CASE WHEN b.BillType IN (78,158,36,93) THEN a.DTypeId ELSE b.DTypeId END,
		CASE WHEN b.BillType IN( 158,36,93) THEN a.ETypeId ELSE b.ETypeId END
FROM	MoneyBill a
INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
WHERE	a.BillNumberId=@nBillId

OPEN CreateOther_cursor

FETCH NEXT FROM CreateOther_cursor INTO @szAtypeIdtemp,@dTotal,@NdTotal,@intCID,@szDTypeID,@szETypeID

WHILE @@FETCH_STATUS=0
BEGIN
	IF @nBillType IN (78,85)
	BEGIN 
			SELECT 
				@dTotal=-@dTotal,
				@NdTotal=-@NdTotal
	END 
	
	IF @@ERROR=0 AND @dTotal<>0
	BEGIN
	EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@szAtypeIdtemp,@szBtypeid,@szEtypeid,
			@dTotal,null,null,@szDTypeId,@szSTypeID,@intCID,@NdTotal,@DecRate
	END
	
	FETCH NEXT FROM CreateOther_cursor INTO @szAtypeIdtemp,@dTotal,@NdTotal,@intCID,@szDTypeID,@szETypeID	
END 

DECLARE @dTotalinMoneytemp NUMERIC(24,10),@NdTotalinMoneytemp NUMERIC(24,10) 

SELECT @dTotalinMoneytemp= -1*@dTotalinMoney,@NdTotalinMoneytemp=-1*@NdTotalinMoney

IF @nBillType =84
BEGIN 
	SELECT	@dBcAp=@dTotalMoney-@dTotalinMoney,
			@NdBcAp=@NdTotalMoney-@NdTotalinMoney
		
	IF @dBcAp<>0 OR @NdBcAp<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@AP_ID,@szBtypeid,@szEtypeid,
		@dBcAp,@szJobNumber,@OutFactoryDate,@szDTypeId,@szSTypeID,@intCID,@NdBcAp,@DecRate
	END	
		
END 
ELSE IF @nBilltype = 85
BEGIN		
	SELECT 
		@dBcAr=@dTotalMoney-@dTotalinMoney,
		@NdBcAr=@NdTotalMoney-@NdTotalinMoney
	
	IF @dBcAr<>0 OR @NdBcAr<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@AR_ID,@szBtypeid,@szEtypeid,
	   @dBcAr,@szJobNumber,@OutFactoryDate,@szDTypeId,@szSTypeID,@intCID,@NdBcAr,@DecRate
	END	
END 

CLOSE CreateOther_cursor
DEALLOCATE CreateOther_cursor

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		处理预收款单收款明细（影响预收科目的部分放到gp_auditarap中了）
--					
-- 最后修改作者：	冯波
-- 最后修改时间：	2011-01-19
-- ========================================================================
CREATE	PROCEDURE GP_AType_PreGathering 
(
	@nBillID		NUMERIC(10,0),
	@intBillType	INT,
	@datBillDate	DATETIME,
	@chvBTypeID		VARCHAR(50),
	@chvETypeID		VARCHAR(50),
	@chvDTypeID		varchar(50),
	@chvSTypeID		varchar(50),
	@CID			BIGINT,
	@Rate			 NUMERIC(24, 10) ,
	@strErrMsg		VARCHAR(100) OUTPUT

)
--@encode$--
AS

	SET NOCOUNT ON
	
	 SET @strErrMsg=''
DECLARE					
		@chvATypeID					VARCHAR(50),						
		@intReturnCode				INT,
		@Total						 NUMERIC(24, 10) ,
		@NTotal						 NUMERIC(24, 10) ,
		@intVipCardID				int,
		@chrIfVipJF					char(1),
		@chvVipIsCz					char(1),
		@numVipcZyeMoney			 NUMERIC(24, 10) ,--会员卡合计存储余额
		@StypeVipcZyeMoney			 NUMERIC(24, 10) ,--会员卡分支机构存储余额
		@intVipJF					int,
		@VIP_ID						VARCHAR(50),
		@syscid				INT,
		@StypeID					VARCHAR(50),
		@vipBillStoredByStypeId INT--会员储值结算使用单据所选分支机构进行储值余额判断

SELECT @vipBillStoredByStypeId=Value FROM Userconfig WHERE ConfigName='vipBillStoredByStypeId'

SELECT @VIP_ID=nId FROM Ac_Items WHERE UserCode='2081' --会员储值

SELECT @syscid=CId FROM Ac_Currency WHERE Sysrow = 1

	DECLARE PreGathering_cursor CURSOR FOR
	SELECT ATypeID,Total,vipcardid,Ntotal,Stypeid
	FROM PreBill 
	WHERE BillNumberID=@nBillID

	OPEN PreGathering_cursor

	FETCH NEXT FROM PreGathering_cursor
	INTO @chvATypeID,@total,@intVipCardID,@Ntotal,@StypeID

	WHILE @@FETCH_STATUS = 0 AND @strErrMsg=''
	BEGIN
		--账目
		IF @@ERROR=0 AND LTRIM(RTRIM(@strErrMsg))='' AND @total<>0
		BEGIN
			IF @chvATypeID = @VIP_ID
			BEGIN
				IF @intVipCardID <> -1
				BEGIN
					--判断是否适用当前分支机构
					IF NOT EXISTS(SELECT * FROM nVipCardSign WHERE VipCardID=@intVipCardID AND (isApplyAllStype=1 OR (isApplyAllStype=0 AND EXISTS(SELECT * FROM VipCard_ApplyStype APS WHERE APS.StypeId=@STypeID AND APS.VipCardId=VipCardID ))))
						RETURN 	706		
					
					SELECT	@chrIfVipJF = b.ifJF,
							@chvVipIsCz = a.IsCz,
							@numVipcZyeMoney =a.cZyeMoney,
							@StypeVipcZyeMoney = ISNULL(ss.cZyeMoney,0)
					FROM	nVipCardSign a
					INNER JOIN nVipCardSet b ON a.VipCardTypeID = b.VipCardTypeID AND a.VipCardID = @intVIPCardID AND a.Deleted = 0 AND B.deleted=0 AND a.EndDate >= @datBillDate
					LEFT JOIN nVipCardSignStype ss ON SS.VipCardID=A.VipCardID AND ss.StypeId=@StypeID

					-- 1)无此VIP卡 2)过了有效期 3)VIP卡是未启用状态 4)VIP卡类型不存在或已删除
					IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN 701
					SET @intVipJF = 0
					

					IF @chvATypeID = @VIP_ID AND @chvVipIsCz <> '1' RETURN 702
					IF @chvATypeID = @VIP_ID AND @chvVipIsCz = '1'
					BEGIN
						IF @total < 0 RETURN 703
						IF @total > @numVipcZyeMoney RETURN 704
						IF @vipBillStoredByStypeId=1 AND  @total > @StypeVipcZyeMoney RETURN 707
					END
					IF @chvVipIsCz = '1'
					BEGIN
						-- 过账时将VIP会员储值卡的消费前余额记入至BillIndex中
						UPDATE BillIndex SET vipCZMoney =@numVipcZyeMoney WHERE BillNumberID = @nBillID
						IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN -10
					END
					
					-- 扣减会员储值余额
					IF @chvVipIsCz = '1' AND @total > 0
					BEGIN
						UPDATE	nVipCardSign
						SET		cZyeMoney = cZyeMoney - @total
						WHERE	VipCardID = @intVipCardID
					END
				END
				
				SET @total = @total*(-1)
				
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
					@total,null,null,@chvDTypeID,@chvSTypeID,@syscid,@total,1
					
				--EXEC @intReturnCode = GP_AType_Total_AddEdit @chvATypeID,@chvSTypeID,@syscid,@total,@total,@strErrMsg OUTPUT 
			END
			ELSE
			BEGIN
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
				@total,null,null,@chvDTypeID,@chvSTypeID,@CID,@NTotal,@Rate
				--select * from ListTable where BillNumberId = 19
			--	EXEC @intReturnCode = GP_AType_Total_AddEdit @chvATypeID,@chvSTypeID,@CID,@total,@NTotal,@strErrMsg OUTPUT
			END
		END

		FETCH NEXT FROM PreGathering_cursor
		INTO @chvATypeID,@Total,@intVipCardID,@NTotal,@StypeID
	END
	CLOSE PreGathering_cursor
	DEALLOCATE PreGathering_cursor
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		处理预付款单（影响预付科目的部分放到gp_auditarap中了）
--					
-- 最后修改作者：	冯波
-- 最后修改时间：	2011-01-19
-- ========================================================================
CREATE	PROCEDURE GP_AType_PrePay 
(
	@nBillID		NUMERIC(10,0),
	@intBillType	INT,
	@datBillDate	DATETIME,
	@chvBTypeID		VARCHAR(50),
	@chvETypeID		VARCHAR(50),
	@chvDTypeID		varchar(50),
	@chvSTypeID		varchar(50),
	@CID			BIGINT,
	@Rate			 NUMERIC(24, 10) ,
	@strErrMsg		VARCHAR(100) OUTPUT
)
--@encode$--
AS

	SET NOCOUNT ON
	
	SET @strErrMsg=''
	DECLARE					
		@chvATypeID					VARCHAR(50),						
		@intReturnCode				INT,
		@Total						 NUMERIC(24, 10) ,
		@NTotal						 NUMERIC(24, 10) ,
		@intVipCardID				int,
		@chrIfVipJF					char(1),
		@chvVipIsCz					char(1),
		@numVipcZyeMoney			 NUMERIC(24, 10) ,
		@intVipJF					int
		

		DECLARE PreGathering_cursor CURSOR FOR
		SELECT ATypeID,Total*(-1),Ntotal*(-1)
		FROM PreBill 
		WHERE BillNumberID=@nBillID

		OPEN PreGathering_cursor
		
		FETCH NEXT FROM PreGathering_cursor
		INTO @chvATypeID,@Total,@ntotal
		
		WHILE @@FETCH_STATUS = 0 AND LTRIM(RTRIM(@strErrMsg))=''
		BEGIN
			--账目
			IF @@ERROR=0  AND @Total<>0
			BEGIN
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
				@total,null,null,@chvDTypeID,@chvSTypeID,@CID,@NTotal,@Rate

				--EXEC @intReturnCode = GP_AType_Total_AddEdit @chvATypeID,@chvSTypeID,@CID,@total,@NTotal,@strErrMsg OUTPUT

			END

			FETCH NEXT FROM PreGathering_cursor
			INTO @chvATypeID,@Total,@ntotal
		END
		CLOSE PreGathering_cursor
		DEALLOCATE PreGathering_cursor


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_AType_STypeMoveInBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_AType_STypeMoveInBill]
GO



/*

功能说明：      分支机构间调拨入库单

作    者：       冯波

创建日期：       2011-1-26

返回结果： 



*/

CREATE PROCEDURE [GP_AType_STypeMoveInBill]
(
	@nBillID			NUMERIC(10,0),				--单据ID
	@strErrMsg			VARCHAR(4000) OUT
)
--@encode$--        
AS




SELECT @strErrMsg=''

DELETE Listtable
WHERE BillNumberId=@nBillID AND BillType=188


DECLARE 
		@strInnerAR					VARCHAR(50),				--内部应收
		@strSTOCKGOODS				VARCHAR(50),				--库存商品
		@strMoveChangedInCome		VARCHAR(50),				--变价调拨收入
		@intMoneyDot				INT,						--金额的小数位数
		@intPriceDot				INT,						--单价的小数位数
		@intBillType				INT,						--单据类型
		@decInnerARMoney			 NUMERIC(24, 10) ,
		@decSTOCKGOODSMoney			 NUMERIC(24, 10) ,
		@chvATypeID					VARCHAR(50),				--会计科目ID
		@intReturnCode				INT,
		@datBillDate				DATETIME,
		@chvBTypeID					VARCHAR(50),
		@chvETypeID					VARCHAR(50),
		@decTotal					 NUMERIC(24, 10) ,
		@chvJobNumber				varchar(20),
		@datOutFactoryDate			datetime,
		@chvDTypeID					varchar(50),
		@chvSTypeID					varchar(50),
		@CID						 NUMERIC(24, 10) ,
		@rate						 NUMERIC(24, 10) 
		

SELECT 
	@intMoneyDot=2,
	@intPriceDot=4
	
	--SELECT 'SELECT nId FROM dbo.Ac_Items WHERE UserCode='''+UserCode+''''+'  --'+FullName+','+typeId FROM dbo.atype
	--WHERE typeId IN('0000100010','0000100001','000030000200005') 
	SELECT @strSTOCKGOODS=nId FROM dbo.Ac_Items WHERE UserCode='1241'  --『库存商品总值合计』,0000100001
	SELECT @strInnerAR=nId FROM dbo.Ac_Items WHERE UserCode='1132'  --『内部应收』,0000100010
	SELECT @strMoveChangedInCome=nId FROM dbo.Ac_Items WHERE UserCode='0325'  --变价调拨差价,000030000200005
	


DECLARE
	@intCostSale	INT

SELECT @intCostSale=CostSale
FROM BillIndex
WHERE BillNumberID=@nBillID


SELECT 
	@chvBTypeID=btypeid,@chvETypeID=etypeid,@chvDTypeID=DTypeId,
	@chvSTypeID=Stypeid,@datBillDate=BillDate,@intBillType=BillType,@CID=CID,@rate=Rate
FROM BillIndex
WHERE BillNumberId=@nBillID

	/*
	SELECT 
		@decSTOCKGOODSMoney=ROUND(ISNULL(SUM(ROUND(CostTotal,@intMoneyDot)),0),@intMoneyDot)
	FROM InOutStockTable
	WHERE BillNumberID=@nBillID
	*/
	
	SELECT
		@decSTOCKGOODSMoney=totalmoney
	FROM BillIndex
	WHERE BillNumberId=@nBillID
	
	SELECT @decTotal=@decSTOCKGOODSMoney


	IF @@ERROR=0 AND LTRIM(RTRIM(@strErrMsg))=''
	BEGIN
			SELECT
				 @chvATypeID=@strSTOCKGOODS
			
			EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
			@decTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@decTotal,@rate
	
			EXEC GP_AType_Total_AddEdit	 @chvATypeID,@chvSTypeID,@CID,@decTotal,@decTotal,@strErrMsg OUTPUT
	END	

	
	SELECT @decInnerARMoney=@decSTOCKGOODSMoney
	

	SELECT @decTotal=@decInnerARMoney*(-1)
	

	IF @@ERROR=0 AND LTRIM(RTRIM(@strErrMsg))=''
	BEGIN
			SELECT
				@chvATypeID=@strInnerAR
				
		
			EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
			@decTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@decTotal,@rate
	
			EXEC GP_AType_Total_AddEdit	@chvATypeID,@chvSTypeID,@CID,@decTotal,@decTotal,@strErrMsg OUTPUT
			
			--写内部应收
			EXEC GP_InnerARTotal_AddEdit	@nBillID,@decTotal,0,@strErrMsg OUT
	END

GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_AType_STypeMoveOutBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_AType_STypeMoveOutBill]
GO



/*

功能说明：      分支机构间调拨出库单

作    者：       冯波

创建日期：       2011-1-24

返回结果： 

备注：			



*/

CREATE PROCEDURE [GP_AType_STypeMoveOutBill]
(
	@nBillID			NUMERIC(10,0),				--单据ID
	@strErrMsg			VARCHAR(4000) OUT
	
)
--@encode$--        
AS

DELETE Listtable
WHERE BillNumberId=@nBillID AND BillType=187


DECLARE 
		@strInnerAR					VARCHAR(50),				--内部应收
		@strSTOCKGOODS				VARCHAR(50),				--库存商品
		@strMoveChangedInCome		VARCHAR(50),				--变价调拨收入
		@intMoneyDot				INT,						--金额的小数位数
		@intPriceDot				INT,						--单价的小数位数
		@intBillType				INT,						--单据类型
		@decInnerARMoney			 NUMERIC(24, 10) ,
		@decSTOCKGOODSMoney			 NUMERIC(24, 10) ,
		@chvATypeID					VARCHAR(50),				--会计科目ID
		@intReturnCode				INT,
		@datBillDate				DATETIME,
		@chvBTypeID					VARCHAR(50),
		@chvETypeID					VARCHAR(50),
		@decTotal					 NUMERIC(24, 10) ,
		@chvJobNumber				varchar(20),
		@datOutFactoryDate			datetime,
		@chvDTypeID					varchar(50),
		@chvSTypeID					varchar(50),
		@CID						 NUMERIC(24, 10) ,
		@rate						 NUMERIC(24, 10) 
		

SELECT 
	@intMoneyDot=2,
	@intPriceDot=4
	
	SELECT @strSTOCKGOODS=nId FROM dbo.Ac_Items WHERE UserCode='1241'  --『库存商品总值合计』,0000100001
	SELECT @strInnerAR=nId FROM dbo.Ac_Items WHERE UserCode='1132'  --『内部应收』,0000100010
	SELECT @strMoveChangedInCome=nId FROM dbo.Ac_Items WHERE UserCode='0325'  --变价调拨差价,000030000200005
	


DECLARE
	@intCostSale	INT

SELECT @intCostSale=CostSale
FROM BillIndex
WHERE BillNumberID=@nBillID


-- Costing Method
DECLARE @AVERAGE			smallint,
		@FIFO				smallint,
		@LIFO				smallint,
		@HAND				smallint,
		@nCostingMethod		smallint

SET @AVERAGE	= 0		-- 移动加权平均
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定

EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output



SET @strErrMsg=''
IF @intCostSale=1
BEGIN
	UPDATE STypeMoveBill
	SET Price=CASE @nCostingMethod WHEN @HAND THEN STypeMoveBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.CostTotal*(-1),@intMoneyDot) AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),@intPriceDot) END END,Total=b.CostTotal*(-1),
	MPrice=(CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.CostTotal*(-1),@intMoneyDot) AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),@intPriceDot) END)*MUnitRate
	FROM 
	(
		SELECT ID,SUM(Qty) AS Qty,SUM(CostTotal) AS CostTotal
		FROM InOutStockTable 
		WHERE BillNumberID=@nBillID 
		GROUP BY ID
	) b
	WHERE STypeMoveBill.ID=b.ID AND STypeMoveBill.BillNumberID=@nBillID


	UPDATE BillIndex
	SET TotalMoney=ROUND(ISNULL(b.TotalMoney,0),@intMoneyDot),NTotalMoney=ROUND(ISNULL(b.TotalMoney,0),@intMoneyDot)
	FROM 
	(
		SELECT BillNumberID,SUM(Total) AS TotalMoney
		FROM STypeMoveBill 
		WHERE BillNumberID=@nBillID
		GROUP BY BillNumberID
	) b
	WHERE BillIndex.BillNumberID=@nBillID AND BillIndex.BillNumberID=b.BillNumberID


	UPDATE InOutStockTable
	SET Price=CostPrice,SalePrice=CostPrice,TaxPrice=CostPrice,Discount=1,Tax=0,
	Total=CostTotal,SaleTotal=CostTotal,TaxTotal=CostTotal,
	NPrice=CostPrice,NSALEPRICE = CostPrice,NTAXPRICE=CostPrice,NTOTAL=CostTotal,NSALETOTAL=CostTotal,NTAXTOTAL=CostTotal
	WHERE InOutStockTable.BillNumberID=@nBillID
END

SELECT 
	@chvBTypeID=btypeid,@chvETypeID=etypeid,@chvDTypeID=DTypeId,
	@chvSTypeID=Stypeid,@datBillDate=BillDate,@intBillType=BillType,@CID=CID,@rate=Rate
FROM BillIndex
WHERE BillNumberId=@nBillID

	--库存商品，贷
	SELECT 
		@decSTOCKGOODSMoney=ROUND(ISNULL(SUM(ROUND(CostTotal,@intMoneyDot)),0),@intMoneyDot)
	FROM InOutStockTable
	WHERE BillNumberID=@nBillID

	SELECT @decTotal=@decSTOCKGOODSMoney


	IF @@ERROR=0 AND LTRIM(RTRIM(@strErrMsg))=''
	BEGIN
			SELECT
				 @chvATypeID=@strSTOCKGOODS
			
			EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
			@decTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@decTotal,@rate
	
			EXEC GP_AType_Total_AddEdit @chvATypeID,@chvSTypeID,@CID,@decTotal,@decTotal,@strErrMsg OUTPUT 
	END	

	IF @intCostSale=0
	BEGIN	
		SELECT @decInnerARMoney=ROUND(SUM(Total),@intMoneyDot)
		FROM STypeMoveBill
		WHERE BillNumberID=@nBillID
	END
	ELSE
	BEGIN
		SELECT @decInnerARMoney=@decSTOCKGOODSMoney*(-1)
	END

	SELECT @decTotal=@decInnerARMoney
	
	--内部应收,借
	IF @@ERROR=0 AND LTRIM(RTRIM(@strErrMsg))=''
	BEGIN
			SELECT
				@chvATypeID=@strInnerAR
				
		
			EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
			@decTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@decTotal,@rate
	
			
			EXEC GP_InnerARTotal_AddEdit @nBillID,@decTotal,0,@strErrMsg OUTPUT
	
			EXEC GP_AType_Total_AddEdit @chvATypeID,@chvSTypeID,@CID,@decTotal,@decTotal,@strErrMsg OUTPUT
	END

	
	IF @intCostSale=0
	BEGIN
		--调价调拨收入：内部应收-库存商品,贷(@decSTOCKGOODSMoney本身为负)
		SELECT @decTotal=@decInnerARMoney+@decSTOCKGOODSMoney
	
		IF @@ERROR=0 AND LTRIM(RTRIM(@strErrMsg))='' AND @decTotal<>0
		BEGIN
				SELECT
					 @chvATypeID=@strMoveChangedInCome
				
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
				@decTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@decTotal,@rate
	
			   EXEC GP_AType_Total_AddEdit	@chvATypeID,@chvSTypeID,@CID,@decTotal,@decTotal,@strErrMsg OUTPUT
		END		
	END



GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_AType_Total_AddEdit]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_AType_Total_AddEdit]
GO


/*

功能说明：      会计科目

作    者：       冯波

创建日期：       2011-1-21

返回结果：       

*/  

CREATE PROCEDURE [GP_AType_Total_AddEdit]
(
	@chvATypeID					VARCHAR(50),
	@chvSTypeID					VARCHAR(50),
	@CID						BIGINT,			
	@decTotal					 NUMERIC(24, 10) ,			--金额
	@decNTotal					 NUMERIC(24, 10) ,			--原币
	@strErrMsg					VARCHAR(4000) OUT		--返回的出错信息
)
--@encode$--        
AS
SELECT @strErrMsg=''
DECLARE @PreTotal  NUMERIC(24, 10) ,
		@NPreTotal  NUMERIC(24, 10) 


SELECT  @PreTotal=Total,@NPreTotal=Ntotal FROM dbo.AType_Total  WHERE ATypeID=@chvATypeID  AND STypeID=@chvSTypeID AND CID = @CID

SET @decTotal =  ISNULL(@preTotal,0) + @decTotal
SET @decNTotal = ISNULL(@NpreTotal,0) + @decNTotal


/*
IF @PreTotal < 0 OR @PreTotal < 0 --检查过账后余额不能为负
BEGIN
	SET @strErrMsg = @chvATypeID
	RETURN 918
END
*/
IF NOT EXISTS(
	SELECT ATypeID 
	FROM AType_Total 
	WHERE ATypeID=@chvATypeID AND STypeID=@chvSTypeID AND CID = @CID
)
BEGIN	
	INSERT INTO AType_Total(ATypeID,STypeID,Total,NTotal,CID)
	VALUES(@chvATypeID,@chvSTypeID,@decTotal,@decNTotal,@CID)
END
ELSE
BEGIN
	UPDATE AType_Total
	SET Total=@decTotal,Ntotal=@decNTotal
	WHERE ATypeID=@chvATypeID AND STypeID=@chvSTypeID AND CID=@CID
END


GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	Author:		毛欣蓉
	Create date: 2012-05-08
	Description: 1 处理往来余额和会员类余额处理
				 2 收付款、预收预付款单过账
				 3 多账户过账
				 4 单据优惠金额过账
				 涉及单据：往来：(11,45,305,160,157,141,167,168,172,181,312）（6,34,145,161,170）
				 积分：(11,305,45,181,183,312)
				 
	修改日期:2014-11-25 冯波
	描述:处理会员卡批量储值充值
	
	--修改: 冯波    日期: 2017-02-09   组合品销售退货单的优惠金额反号
*/							
CREATE   PROCEDURE GP_AuditArAp
(
	@intBillNumberID		NUMERIC(10,0),
	@isRedWord				BIT = '0',
	@numBillType			INT,
	@datBillDate			DATETIME,
	@chvATypeID				VARCHAR(50),
	@chvBTypeID				VARCHAR(50),
	@chvETypeID				VARCHAR(50),
	@chvKTypeID				VARCHAR(50),
	@chvKTypeID2			VARCHAR(50),
	@chvDTypeID				VARCHAR(50),
	@chvSTypeID				VARCHAR(50),
	@numTotalMoney			 NUMERIC(24, 10) ,
	@numTotalInMoney		 NUMERIC(24, 10) ,
	@numPreferenceMoney		 NUMERIC(24, 10) ,
	@NnumTotalMoney			 NUMERIC(24, 10) ,
	@NnumTotalInMoney		 NUMERIC(24, 10) ,
	@NnumPreferenceMoney	 NUMERIC(24, 10) ,
	@numTax					 NUMERIC(24, 10) ,
	@ifIndexWX				TINYINT,
	@intCostSale			TINYINT,
	@IfMulAccount			TINYINT,
	@wxTotal				 NUMERIC(24, 10) ,
	@intVipCardID			INT,
	@CID					INT,
	@Rate					 NUMERIC(24, 10) ,
	@AssetBusinessTypeId    INT,
	@NewPosBill				TINYINT,
	@strMsg					VARCHAR(200) OUTPUT,
	@VipCentInfo			VARCHAR(200) = '' OUTPUT,				--返回会员卡积分调整信息
	@VipCardCode			VARCHAR(200)='' OUTPUT
)
--@encode$--
AS
DECLARE	
		@nRet				INT,

-----------------------------		
		
		@numBanlanceTotal	 NUMERIC(24, 10) ,     --往来差额本币
		@NnumBanlanceTotal	 NUMERIC(24, 10) ,     --往来差额原币
		
		@chvVipIsCz			CHAR(2),	--是否储值
		@numVipcZyeMoney	 NUMERIC(24, 10) ,  --储值余额
		@numTotal			 NUMERIC(24, 10) ,  --收付款金额本币
		@NnumTotal			 NUMERIC(24, 10) ,  --收付款金额原币
		@vipXfTotal			 NUMERIC(24, 10) ,	
		
		@op					INT = 1, --用于控制金额符号（默认是1 红冲的时候-1）
-----------------------------
		@AR_ID	VARCHAR(50) = '0',--预收
		@AP_ID	VARCHAR(50) = '0',--预付
		@YS_ID	VARCHAR(50) = '0',--预收
		@YF_ID	VARCHAR(50) = '0',--预付
		@VIP_ID VARCHAR(50) = '0', --会员
		@PER_ID VARCHAR(50) = '0', --应缴税金
		@IN_ID	VARCHAR(50) = '0', --内部应收	
		@SCHD_ID VARCHAR(50)='0',--市场活动费用 
		@yhin_ID VARCHAR(50)='0',--优惠券收入 折扣券类型总金额
		@yh_ID	VARCHAR(50)='0',--优惠券     代金券面值 兑换券出库金额
------------------------------
	  @TMPNnumPreferenceMoney	 NUMERIC(24, 10) ,
	  @TMPnumPreferenceMoney	 NUMERIC(24, 10) 

--会员储值充值和积分兑换不能没有会员卡号
IF @numBillType IN(181,183) AND (@intVipCardID = -1 OR ISNULL(@intVipCardID,0) = 0 )
BEGIN
	RETURN 701
END
	
IF @numBillType=312
BEGIN
	IF EXISTS(
		SELECT BillNumberId
		FROM	VipAddMoneyBatchBill
		WHERE BillNumberId=@intBillNumberID
		AND ISNULL(VipCardId,0) IN (-1,0)
	)
		RETURN 701
END	

--根据usercode查出对应的id		
SELECT @VIP_ID=nId FROM Ac_Items WHERE UserCode='2081' --会员储值
SELECT @YS_ID=nId FROM Ac_Items WHERE UserCode='2131'  --预收
SELECT @YF_ID=nId FROM Ac_Items WHERE UserCode='1151'  --预付
SELECT @IN_ID=nId FROM Ac_Items WHERE UserCode='1132'  --内部应收
SELECT @AR_ID=nId FROM Ac_Items WHERE UserCode='987'  --应收
SELECT @AP_ID=nId FROM Ac_Items WHERE UserCode='2121'  --应付
SELECT @PER_ID=nId FROM Ac_Items WHERE UserCode='0456' --优惠
SELECT @SCHD_ID=nId FROM Ac_Items WHERE UserCode='044597' --市场活动费用 处理代金券
SELECT @yhin_ID=nId FROM Ac_Items WHERE UserCode='0334' --优惠券收入 折扣券类型总金额
SELECT @yh_ID=nId FROM Ac_Items WHERE UserCode='2191' ---优惠券     代金券面值 兑换券出库金额
DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

-- 计算是否有往来差额
SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney --本币
SET @NnumBanlanceTotal = @NnumTotalMoney - @NnumTotalInMoney - @NnumPreferenceMoney --原币

--运输配送单往来差异为  运费减去已付，往来单位为托运方
IF @numBillType=414
BEGIN
	SELECT @numBanlanceTotal=totalfreight-totalinmoney,
		   @NnumBanlanceTotal=Ntotalfreight-Ntotalinmoney,
		   @chvBTypeID=btypeid,
		   @nRet=IsFreightMoney
		   FROM dbo.BillIndex WHERE BillNumberId=@intBillNumberID
	IF @nRet=0
	BEGIN
		RETURN 0
	END
	SET @nRet=0
END

SET @vipXfTotal = @numTotalMoney

IF @numBillType IN(6,45,46,148,149,150,151,426,328) --反号
BEGIN
	SET @numBanlanceTotal=-1*@numBanlanceTotal
	SET @NnumBanlanceTotal=-1*@NnumBanlanceTotal
END

--红冲在反号
IF @isRedWord = '1'
BEGIN
	SET @op = -1
END
SET @numBanlanceTotal = @op * @numBanlanceTotal  
SET @NnumBanlanceTotal = @op * @NnumBanlanceTotal  

---------------------------------处理应收 START----------------------------------------
--只处理应收差额，收款单单独处理

--SELECT 'AR',@numBillType,@numBanlanceTotal


IF  @numBillType IN(11,12,45,46,305,160,157,141,167,168,172,181,312,424,426,328) AND @numBanlanceTotal<>0--85,93,148,149
BEGIN
	IF NOT(@intCostSale=1 AND @numBillType=11) 
	BEGIN
		--写listtable
		EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AR_ID,@CID,@NnumBanlanceTotal,@Rate
		IF @nRet <> 0  RETURN @nRet
		
		
	END
END
----------------------------处理应收 END-----------------------------------------------
----------------------------处理应付 START---------------------------------------------
--只处理应付差额，付款单单独处理
IF @numBillType IN(6,34,145,161,170,410,414,423) AND @numBanlanceTotal<>0--36,84,,150,151
BEGIN
	--写listtable
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AP_ID,@CID,@NnumBanlanceTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
	
	
END
----------------------------处理应付 END----------------------------------------------

----------------------------处理优惠（写listtable） start-----------------------------
IF @numBillType IN (11,12,6,34,45,46,305,160,181,4,66,167,168,170,172,161,215,312,424,423,426) AND @numPreferenceMoney<>0 AND @intCostSale<>1   
BEGIN
	--11,305,45,160,181,4)
	SELECT @TMPnumPreferenceMoney=@numPreferenceMoney,@TMPNnumPreferenceMoney=@NnumPreferenceMoney
	IF @numBillType  IN (34,66,170,45,161,215,46,423,426)
	BEGIN
		SELECT @TMPnumPreferenceMoney=-@numPreferenceMoney,@TMPNnumPreferenceMoney=-@NnumPreferenceMoney
	END

	EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PER_ID,@chvBTypeID,@chvETypeID,
				@TMPnumPreferenceMoney,NULL,NULL,@chvDTypeID,@chvSTypeID,@CID,@TMPNnumPreferenceMoney,@Rate
	IF @nRet<>0  RETURN @nRet
END

----------------------------处理优惠 END----------------------------------------------

----------------------------处理积分、储值 START--------------------------------------
-- 销售、零售、销售退货的VIP判断及消费、积分处理（这里的会员卡首先是用来积分的；如果是单帐户，才需要判断余额）
IF @numBillType IN (11,12,305,45,46,181,183,4,215,167,168,172,312,328,327,329) AND @intCostSale<>1	
BEGIN
	IF @intVipCardID <> -1 OR @numBillType=312
	BEGIN
		EXEC @nRet= GP_AuditVipInfo  @numBillType,@intBillNumberID,@vipXfTotal,@intVipCardID,@datBillDate,@VIP_ID,@IsRedword,@NewPosBill,@VipCentInfo OUTPUT,@VipCardCode	OUTPUT
		IF @nRet <> 0  RETURN @nRet
	END
END
----------------------------处理积分、储值 END----------------------------------------

----------------------------处理预收付款单、预收预付款单 START------------------------
			
--预收款单
IF @numBillType = 189
BEGIN
	--写listtable
	
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@YS_ID,@CID,@NnumBanlanceTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
	
	--处理预收款单收款明细
	EXEC @nRet = GP_AType_PreGathering @intBillNumberID,@numBillType,@datBillDate,@chvBTypeID,@chvETypeID,@chvDTypeID,@chvSTypeID,@CID,@Rate,@strMsg OUTPUT
	IF @nRet <> 0  RETURN @nRet
	
	
	
END
--预付款单
IF @numBillType = 190
BEGIN
	--写listtable
	
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@YF_ID,@CID,@NnumBanlanceTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
	
	--处理预收款单付款明细
	EXEC @nRet = GP_AType_PrePay @intBillNumberID,@numBillType,@datBillDate,@chvBTypeID,@chvETypeID,@chvDTypeID,@chvSTypeID,@CID,@Rate,@strMsg OUTPUT
	IF @nRet <> 0  RETURN @nRet
	
	
END
			
-----------------收款单的预收
IF @numBillType = 4
BEGIN
	--写listtable
	SELECT @numBanlanceTotal=(@numTotalInMoney + @numPreferenceMoney)*(-1)*@op,@NnumBanlanceTotal=(@NnumTotalInMoney + @NnumPreferenceMoney)*(-1)*@op
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AR_ID,@CID,@NnumBanlanceTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
	
	--处理预收款单付款明细
	EXEC @nRet = GP_AType_GatherPayBill @intBillNumberID,@numBillType,@datBillDate,@chvBTypeID,@chvETypeID,@chvDTypeID,@chvSTypeID,@CID,@Rate,@strMsg OUTPUT,@chvSTypeID
	IF @nRet <> 0  RETURN @nRet
END

----------------付款单收预付
IF @numBillType = 66
BEGIN
	--写listtable
	SELECT @numBanlanceTotal=(@numTotalInMoney + @numPreferenceMoney)*(-1)*@op,@NnumBanlanceTotal=(@NnumTotalInMoney + @NnumPreferenceMoney)*(-1)*@op
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AP_ID,@CID,@NnumBanlanceTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
	
	--处理预收款单付款明细
	EXEC @nRet = GP_AType_GatherPayBill @intBillNumberID,@numBillType,@datBillDate,@chvBTypeID,@chvETypeID,@chvDTypeID,@chvSTypeID,@CID,@Rate,@strMsg OUTPUT,@chvSTypeID
	IF @nRet <> 0  RETURN @nRet
END
----------------------------处理预收付款单、预收预付款单 END ------------------------
-----------------93其他收入单 158现金费用单 36费用单
IF @numBillType IN( 36) 
BEGIN
	--处理应收
	IF (@numBillType=36 AND @ExpenseToAr=1 AND LEFT(@chvBTypeID,5)='00001') AND @numBanlanceTotal<>0
	BEGIN
		SELECT @numBanlanceTotal=@numBanlanceTotal*-1,@NnumBanlanceTotal=@NnumBanlanceTotal*-1
		EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
				  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AR_ID,@CID,@NnumBanlanceTotal,@Rate
		IF @nRet <> 0  RETURN @nRet
	END 
	ELSE 
	BEGIN
		IF @numBanlanceTotal<>0
			EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
			  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AP_ID,@CID,@NnumBanlanceTotal,@Rate

	END 
	
	--处理明细行
	EXEC @nRet = GP_AType_MoneyBill @intBillNumberID
	IF @nRet <> 0  RETURN @nRet
END

IF @numBillType IN( 93,158) 
BEGIN
		  
	IF @numBillType=93 AND @numBanlanceTotal<>0
	BEGIN
		EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AR_ID,@CID,@NnumBanlanceTotal,@Rate
		IF @nRet <> 0  RETURN @nRet
	END
	
	--处理明细行
	EXEC @nRet = GP_AType_MoneyBill @intBillNumberID
	IF @nRet <> 0  RETURN @nRet
END

----------------------------处理固定资产项目类单据 start---------------------------------
IF @numBillType IN(212,213,214)
BEGIN
	EXEC @nRet = GP_AuditAssetBill  @intBillNumberID, @numBillType, @datBillDate,@chvBTypeID, @chvETypeID, @chvDTypeID, @chvSTypeID, 
			@numBanlanceTotal,@NnumBanlanceTotal,@NnumTotalMoney, @NnumTotalMoney, @cid, @Rate,@AssetBusinessTypeId,@NewPosBill, @strMsg 

	IF @nRet<>0 RETURN @nRet
END


----------------------------处理固定资产类单据 end-----------------------------------

----------------------------处理固定资产类(项目)单据 start---------------------------------
IF @numBillType IN(78,84,85)
BEGIN
	--处理明细行
	EXEC @nRet = GP_AType_MoneyBill @intBillNumberID
	IF @nRet <> 0  RETURN @nRet
END
----------------------------处理固定资产类(项目)单据 end-----------------------------------


IF @numBillType IN (423,424,425,426)
BEGIN


DECLARE @DJTotal NUMERIC(24,10),
		@NDJTotal NUMERIC(24,10),
		@ZKTotal NUMERIC(24,10),
		@NZKTotal NUMERIC(24,10),
		@HDTotal  NUMERIC(24,10),
		@NHDTotal  NUMERIC(24,10)	

IF @numBillType =424
BEGIN 
SELECT @ZKTotal=SUM(ISNULL(o.Total,0)),@NZKTotal=SUM(ISNULL(o.NTotal,0)) 
FROM dbo.Coupon_OutBill o
INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
WHERE BillNumberId=@intBillNumberID AND t.CouponType=2 --折扣券总金额

SELECT @DJTotal=SUM(ISNULL(total,0)),@NDJTotal=SUM(ISNULL(ntotal,0))
FROM (
	SELECT SUM(ISNULL(t.CouponValue,0)*o.Qty) AS total ,SUM(ISNULL(t.CouponValue,0)*o.Qty)  AS ntotal
	FROM dbo.Coupon_OutBill o
	INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
	WHERE BillNumberId=@intBillNumberID AND t.CouponType=1 --代金券面值
	UNION ALL
	SELECT SUM(ISNULL(o.Total,0)) AS total ,SUM(ISNULL(o.NTotal,0)) AS ntotal
	FROM  dbo.Coupon_OutBill o
	INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
	WHERE BillNumberId=@intBillNumberID AND t.CouponType=3 --兑换券出库金额
) A

SELECT @HDTotal=SUM(ISNULL(total,0)),@NHDTotal=SUM(ISNULL(ntotal,0))
FROM (
	SELECT SUM(ISNULL(t.CouponValue,0)*o.Qty) AS total ,SUM(ISNULL(t.CouponValue,0)*o.Qty)  AS ntotal
	FROM dbo.Coupon_OutBill o
	INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
	WHERE BillNumberId=@intBillNumberID AND t.CouponType=1 --代金券面值
	UNION ALL
	SELECT -SUM(ISNULL(o.Total,0)) AS total ,-SUM(ISNULL(o.NTotal,0)) AS ntotal
	FROM  dbo.Coupon_OutBill o
	INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
	WHERE BillNumberId=@intBillNumberID AND t.CouponType=1 --代金券出库金额

) A
END 
ELSE IF @numBillType =426
BEGIN
SELECT @ZKTotal=-SUM(ISNULL(o.Total,0)),@NZKTotal=-SUM(ISNULL(o.NTotal,0)) 
FROM dbo.Coupon_BackBill o
INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
WHERE BillNumberId=@intBillNumberID AND t.CouponType=2 --折扣券总金额

SELECT @DJTotal=-SUM(ISNULL(total,0)),@NDJTotal=-SUM(ISNULL(ntotal,0))
FROM (
	SELECT SUM(ISNULL(t.CouponValue,0)*o.Qty) AS total ,SUM(ISNULL(t.CouponValue,0)*o.Qty)  AS ntotal
	FROM dbo.Coupon_BackBill o
	INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
	WHERE BillNumberId=@intBillNumberID AND t.CouponType=1 --代金券面值
	UNION ALL
	SELECT SUM(ISNULL(o.Total,0)) AS total ,SUM(ISNULL(o.NTotal,0)) AS ntotal
	FROM  dbo.Coupon_BackBill o
	INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
	WHERE BillNumberId=@intBillNumberID AND t.CouponType=3 --兑换券出库金额
) A

SELECT @HDTotal=-SUM(ISNULL(total,0)),@NHDTotal=-SUM(ISNULL(ntotal,0))
FROM (
	SELECT SUM(ISNULL(t.CouponValue,0)*o.Qty) AS total ,SUM(ISNULL(t.CouponValue,0)*o.Qty)  AS ntotal
	FROM dbo.Coupon_BackBill o
	INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
	WHERE BillNumberId=@intBillNumberID AND t.CouponType=1 --代金券面值
	UNION ALL
	SELECT -SUM(ISNULL(o.Total,0)) AS total ,-SUM(ISNULL(o.NTotal,0)) AS ntotal
	FROM  dbo.Coupon_BackBill o
	INNER JOIN dbo.Coupon_TypeInfo t ON o.CouponId=t.CouponId
	WHERE BillNumberId=@intBillNumberID AND t.CouponType=1 --代金券出库金额

) A
END 
------------------------------------处理市场活动费用 begin---------------------------
IF @numbilltype IN (423)AND @numTotalMoney<>0
BEGIN
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @numTotalMoney,NULL,NULL,@chvDTypeID,@chvSTypeID,@SCHD_ID,@CID,@numTotalMoney,@Rate
	IF @nRet <> 0  RETURN @nRet
	
END 
IF @numBillType IN (424,426) AND @HDTotal<>0
BEGIN
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @HDTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@SCHD_ID,@CID,@NHDTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
END
------------------------------------处理市场活动费用 end-----------------------------
----------------------------------处理优惠券收入 begin-----------------------------
IF @numbilltype IN (424,426) AND @ZKTotal<>0 
BEGIN
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @ZKTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@yhin_ID,@CID,@NZKTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
END 
------------------------------------处理优惠券收入 end-----------------------------
------------------------------------处理优惠券 begin-----------------------------
IF @numbilltype IN (424,426) AND @DJTotal<>0 
BEGIN
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @DJTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@yh_ID,@CID,@NDJTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
END 
------------------------------------处理优惠券 end-----------------------------
END 
-------------------------多账户中写listtable和扣减余额 START--------------------------
IF @numBillType IN (305,11,12,45,46,160,141,34,6,161,145,181,157,35,167,168,170,172,148,149,150,151,215,212,213,36,158,181,77,312,168,172,170,414,423,424,426,93,84,85,78,214,328) AND @intCostSale<>1--77,85,84,93,158,36
BEGIN
	EXEC @nRet = GP_Auditing_MulAccount @intBillNumberID,@numBillType,@NewPosBill,@chvSTypeID,@strMsg OUTPUT
	IF @nRet<>0 RETURN @nRet
END
-------------------------多账户中写listtable和扣减余额 END--------------------------

----------------------------往来核销单过账 start---------------------------------
IF @numBillType=450
BEGIN
EXEC Gp_Auditing_ChargeOffBill
		@intBillNumberID,
		--@numBillType,
		@nRet OUT
		
		IF @nRet<>0
		RETURN @nRet
END

--运费,税费，运输配送单
IF @numBillType=414
BEGIN
	--运杂费
	DECLARE @TransPortPay_ID	INT,
			@TotalTransPortPay	NUMERIC(24,10),
			@NTotalTransPortPay NUMERIC(24,10),
			@Tax_ID				INT,						--税费
			@TaxTotal			NUMERIC(24,10),
			@NTaxTotal			NUMERIC(24,10)
			
	SELECT @TransPortPay_ID=Nid FROM dbo.Ac_Items WHERE UserCode='044598'
	SELECT @Tax_ID=Nid FROM dbo.Ac_Items WHERE UserCode='2171'
	
	SELECT @TotalTransPortPay=dbo.F_RoundTotal(totalfreight*(1-tax/100)),
		   @NTotalTransPortPay=dbo.F_RoundTotal(Ntotalfreight*(1-tax/100)),
		   @TaxTotal=dbo.F_RoundTotal(totalfreight*tax/100)*-1,
		   @NTaxTotal=dbo.F_RoundTotal(ntotalfreight*tax/100)*-1
	FROM dbo.BillIndex WHERE BillNumberId=@intBillNumberID
	
	--运杂费  
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
					  @TotalTransPortPay,NULL,NULL,@chvDTypeID,@chvSTypeID,@TransPortPay_ID,@CID,@NTotalTransPortPay,@Rate
	IF @nRet <> 0  RETURN @nRet
	--税金
	EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
				 @TaxTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@Tax_ID,@CID,@NTaxTotal,@Rate
	IF @nRet <> 0  RETURN @nRet
END

----------------------------往来核销单过账 start---------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	Author:		毛欣蓉
	Create date: 2013-05-28
	Description: AssetIncDecBill 增加减少。
				depBill 折旧
	修改人：    冯波
*/							
CREATE   PROCEDURE GP_AuditAssetBill
(
	@intBillNumberID		NUMERIC(10,0),
	@numBillType			INT,
	@datBillDate			DATETIME,
	@chvBTypeID				VARCHAR(50),
	@chvETypeID				VARCHAR(50),
	@chvDTypeID				VARCHAR(50),
	@chvSTypeID				VARCHAR(50),
	@numBanlanceTotal		 NUMERIC(24, 10) , --往来差额
	@NnumBanlanceTotal		 NUMERIC(24, 10) , --往来差额
	@NnumTotalMoney			 NUMERIC(24, 10) ,
	@numTotalMoney			 NUMERIC(24, 10) ,
	@CID					INT,
	@Rate					 NUMERIC(24, 10) ,
	@AssetBusinessTypeId    INT,
	@NewPosBill				TINYINT,
	@strMsg					VARCHAR(200) OUTPUT
)
--@encode$--
AS

DECLARE	
		@nRet				INT,
		@numTaxtotal		 NUMERIC(24, 10) ,  --本币含税金额
		@NnumTaxtotal		 NUMERIC(24, 10) ,  --原币含税金额
		@numTotal			 NUMERIC(24, 10) ,  --本币金额
		@Nnumtotal			 NUMERIC(24, 10) ,  --原币金额
		@dectotal			 NUMERIC(24, 10) ,	--固定资产值
		@Ndectotal			 NUMERIC(24, 10) ,
		@NDepTotal			 NUMERIC(24, 10) ,  --累计折旧金额原币
		@DepTotal			 NUMERIC(24, 10) ,  --累计折旧金额本币
		
		@numZctotal			 NUMERIC(24, 10) ,  --原值本币
		@NnumZctotal		 NUMERIC(24, 10) ,  --原值原币
		
		@numZJtotal			 NUMERIC(24, 10) ,  --卡片累计折旧
		@taxmoney			 NUMERIC(24, 10) ,  --本币税额
		@Ntaxmoney			 NUMERIC(24, 10) ,  --原币税额		
		
		@op					INT = 1, --用于控制金额符号（默认是1 红冲的时候-1）
-----------------------------
		@ZC_ID				VARCHAR(50) = '0',--固定资产原值
		@ZJGC_ID			VARCHAR(50) = '0', --在建工程
		@AR_ID				VARCHAR(50) = '0',
		@AP_ID				VARCHAR(50) = '0',--应付
		@Other_ID			VARCHAR(50) = '0' , --其他.....
		@LJ_ID				VARCHAR(50) = '0', --累计折旧
		@PAY_TAXMONEY_ID	VARCHAR(50),  --应缴税金
		@TZ_ID				VARCHAR(50),  --长期股权投资
		@OTHEROUT_ID		VARCHAR(50),  --费用\其他 
		@ZCZJ_ID			VARCHAR(50),--固定资产折旧

		
		--@AssetBusinessTypeId INT,--业务类型（0.增长1.减少 2.变更，3折旧）
		
		@syscid	INT,
		
------------------------------
	  @TMPNnumPreferenceMoney	 NUMERIC(24, 10) ,
	  @TMPnumPreferenceMoney	 NUMERIC(24, 10) 

	
--根据usercode查出对应的id		
SELECT @ZC_ID=nId FROM Ac_Items WHERE UserCode='SYC-1601'  --固定资产原值
SELECT @ZJGC_ID=nId FROM Ac_Items WHERE UserCode='SYS-1604'  --在建工程
SELECT @AR_ID=nId FROM Ac_Items WHERE UserCode='987'  --应收
SELECT @AP_ID=nId FROM Ac_Items WHERE UserCode='2121'  --应付
SELECT @Other_ID=NID FROM ac_items WHERE UserCode='0333'  -- 其他.....
SELECT @LJ_ID=NID FROM ac_items WHERE UserCode='SYC-1602'  -- 『累计折旧
SELECT @PAY_TAXMONEY_ID=NID FROM ac_items WHERE UserCode='2171'  -- 『应交税金』,0000200004
SELECT @TZ_ID=NID FROM ac_items WHERE UserCode='SYS-1511'  -- 长期股权投资
SELECT @OTHEROUT_ID=NID FROM ac_items WHERE UserCode='0455'  -- 『费用\其他 
SELECT @ZCZJ_ID=NID FROM ac_items WHERE UserCode='0432'  -- 『固定资产折旧


DECLARE
	@numDevalueReady  NUMERIC(24, 10) 

--卡片累计折旧，原值，计提减值准备
SELECT @numZctotal=SUM(a.Total),@NnumZctotal=SUM(a.F_Total),@numZJtotal=SUM(a.DepTotal),
@numDevalueReady=SUM(a.DevalueReady)
from Ac_AssetsCards a
INNER JOIN AssetIncDecBill b ON a.Id=AssetCardId
WHERE BillNumberId=@intBillNumberID

SET @numBanlanceTotal = @op * @numBanlanceTotal  
SET @NnumBanlanceTotal = @op * @NnumBanlanceTotal  

--增加单
--①固定资产购入（原值含税）
/*	固定资产卡片原值	借	价税合计  +
	单据上付款项目		贷	实付金额 -
	应付账款合计		贷	价税合计-实付金额 +
	
 ②固定资产购入（原值不含税）
	固定资产卡片原值	借	金额
	【负债合计】\『应交税金』\	借	税额 -
	单据上收付款项目	贷	实付金额
	应付账款合计	贷	价税合计-实付金额
	
 ③固定资产自建工程
	固定资产卡片原值	借	金额
	【资产合计】\在建工程	贷	金额

 ⑤固定资产接受捐赠
   固定资产卡片原值	借	金额
	【收入类】\『其他收入』\其他.....	贷	金额
	
 ⑥固定资产盘盈
  固定资产卡片原值	借	金额
  固定资产卡片原值累计折旧	贷	累计折旧
  【收入类】\『其他收入』\其他.....	贷	金额-累计折旧
*/
--含税金额
SELECT @numTaxtotal=SUM(TaxTotal),@NnumTaxtotal=SUM(NTaxTotal),
		@numTotal=SUM(Total),@Nnumtotal=SUM(NTotal), 
		@DepTotal=SUM(DepTotal),
		@taxmoney=SUM(TaxMoney),@Ntaxmoney=SUM(NTaxMoney) 
FROM AssetIncDecBill
WHERE BillNumberId=@intBillNumberID


SELECT @syscid=CID FROM dbo.Ac_Currency
WHERE Sysrow=1

IF @numBillType = 212
BEGIN
	-------------------------处理固定资产原值项目 start--------------------------------
	IF @AssetBusinessTypeId = 1 AND @numTaxtotal<>0 --购入（原值含税）
	BEGIN
		EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@ZC_ID,@chvBTypeID,@chvETypeID,
					@numTaxtotal,'',NULL,@chvDTypeID,@chvSTypeID,@cid,@NnumTaxtotal,@rate
		IF @nRet <> 0  RETURN @nRet
	END
	
	IF @AssetBusinessTypeId IN(2,3,5,6) AND @numTotal<>0 --购入（原值不含税）,固定资产自建工程,固定资产接受捐赠,固定资产盘盈
	BEGIN
		EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@ZC_ID,@chvBTypeID,@chvETypeID,
					@numTotal,'',NULL,@chvDTypeID,@chvSTypeID,@cid,@Nnumtotal,@rate
		IF @nRet <> 0  RETURN @nRet
	END
	-------------------------处理固定资产原值项目 end  --------------------------------
	
	
	------------------------往来差额 start---------------------------------------------
	IF @numBanlanceTotal<>0  AND @AssetBusinessTypeId IN(1,2)--业务类型为购买
	BEGIN
			EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
						  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AP_ID,@CID,@NnumBanlanceTotal,@Rate
			IF @nRet <> 0  RETURN @nRet
	END
	------------------------往来差额 end---------------------------------------------
	
	-- ②固定资产购入（原值不含税）---应交税金 @ZJGC_ID
	IF @AssetBusinessTypeId = 2
	BEGIN
		SELECT @dectotal=-@taxmoney,@Ndectotal=-@taxmoney
		--应交税金			
		
		IF @dectotal<>0
		BEGIN
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
						@dectotal,'',NULL,@chvDTypeID,@chvSTypeID,@CID,@Ndectotal,@Rate
			IF @nRet <> 0  RETURN @nRet
		END
	END
	
	--③固定资产自建工程---在建工程 @ZJGC_ID
	IF @AssetBusinessTypeId = 3
	BEGIN
		SELECT @numTotal=-@numTotal,@Nnumtotal=-@Nnumtotal
		
		IF @numTotal<>0
		BEGIN
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@ZJGC_ID,@chvBTypeID,@chvETypeID,
						@numTotal,'',NULL,@chvDTypeID,@chvSTypeID,@CID,@Nnumtotal,@Rate
			IF @nRet <> 0  RETURN @nRet
		END
	END
	-- ⑤固定资产接受捐赠 其他 --@Other_ID
	IF @AssetBusinessTypeId = 5
	BEGIN
		IF @DepTotal<>0
		BEGIN
			--累计折旧
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@LJ_ID,@chvBTypeID,@chvETypeID,
						@DepTotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@DepTotal,1
			IF @nRet <> 0  RETURN @nRet
		END
		
		SELECT @numTotal=@numTotal-@DepTotal
	
		IF @numTotal<>0
		BEGIN
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@Other_ID,@chvBTypeID,@chvETypeID,
						@numTotal,'',NULL,@chvDTypeID,@chvSTypeID,@CID,@Nnumtotal,@Rate
			IF @nRet <> 0  RETURN @nRet
		END
		
		
	END
	--⑥固定资产盘盈 其他 --@Other_ID 固定资产卡片原值累计折旧 @LJ_ID
	IF @AssetBusinessTypeId = 6
	BEGIN
		IF @DepTotal<>0
		BEGIN
			SELECT @DepTotal=-@DepTotal
			--累计折旧
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@LJ_ID,@chvBTypeID,@chvETypeID,
						@DepTotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@DepTotal,1
			IF @nRet <> 0  RETURN @nRet
			
			SELECT @DepTotal=-@DepTotal
		END
		--其他
		SELECT @dectotal= @numTotal-@DepTotal--,@Ndectotal=@Nnumtotal-@DepTotal
		
		IF @dectotal<>0
		BEGIN			
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@Other_ID,@chvBTypeID,@chvETypeID,
						@dectotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@dectotal,1
			IF @nRet <> 0  RETURN @nRet
		END
	END
END
/*
①固定资产变卖
	单据上收付款项目	借	实收金额
	应收款合计			借	价税合计 减 实收金额
	固定资产卡片累计折旧	借	固定资产折旧额
	【负债合计】\『应交税金』\	贷	税额
	固定资产卡片原值	贷	固定资产原值
	【收入类】\『其他收入』\其他.....	贷	价税合计+固定资产折旧额-税额-固定资产原值
②固定资产报废
	固定资产卡片累计折旧	借	固定资产折旧额
	【支出类】\『费用合计』\其他支出	借	固定资产原值-固定资产折旧额
	固定资产卡片原值	贷	固定资产原值
③固定资产投资转出
	固定资产卡片累计折旧	借	固定资产折旧额
	【资产合计】\长期股权投资	借	固定资产原值-固定资产折旧额
	固定资产卡片原值	贷	固定资产原值
④固定资产捐赠转出
	固定资产卡片累计折旧	借	固定资产折旧额
	【支出类】\『费用合计』\其他支出	借	固定资产原值-固定资产折旧额
	固定资产卡片原值	贷	固定资产原值
⑤固定资产盘亏
	固定资产卡片累计折旧	借	固定资产折旧额
	【支出类】\『费用合计』\其他支出	借	固定资产原值-固定资产折旧额
	固定资产卡片原值	贷	固定资产原值
*/
IF @numBillType = 213
BEGIN
	--累计折旧
	SELECT @dectotal=@numZJtotal
	
	IF @dectotal<>0
	BEGIN
		EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@LJ_ID,@chvBTypeID,@chvETypeID,
					@dectotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@dectotal,1
		IF @nRet <> 0  RETURN @nRet
	END
	
	--固定资产原值
	SELECT @dectotal=-(@numZctotal-@numDevalueReady)
	
	IF @dectotal<>0
	BEGIN
		EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@ZC_ID,@chvBTypeID,@chvETypeID,
					 @dectotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@dectotal,@Rate
		IF @nRet <> 0  RETURN @nRet
	END
				
	IF @AssetBusinessTypeId = 7 --变卖  其他 
	BEGIN
		------------------------往来差额 start---------------------------------------------
		IF @numBanlanceTotal<>0 --业务类型为购买或者变卖
		BEGIN
				EXEC @nRet = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
							  @numBanlanceTotal,NULL,NULL,@chvDTypeID,@chvSTypeID,@AR_ID,@CID,@NnumBanlanceTotal,@Rate
				IF @nRet <> 0  RETURN @nRet
		END
		------------------------往来差额 end---------------------------------------------
	
		SELECT @dectotal=@numTaxtotal+@numZJtotal-@taxmoney-@numZctotal+@numDevalueReady
		--其他
		
		IF @dectotal<>0
		BEGIN
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@Other_ID,@chvBTypeID,@chvETypeID,
						@dectotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@dectotal,1
			IF @nRet <> 0  RETURN @nRet
		END
		--应交税金	
		IF @taxmoney<>0
		BEGIN		
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
						@taxmoney,'',NULL,@chvDTypeID,@chvSTypeID,@CID,@Ntaxmoney,@Rate
			IF @nRet <> 0  RETURN @nRet
		END
	END
	IF @AssetBusinessTypeId IN(8,10,11)		--②固定资产报废，④固定资产捐赠转出，⑤固定资产盘亏
	BEGIN
		--其他支出 @OTHEROUT_ID  固定资产原值-固定资产折旧额
		SELECT @dectotal=@numZctotal - @numZJtotal-@numDevalueReady
		
		IF @dectotal<>0
		BEGIN
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@OTHEROUT_ID,@chvBTypeID,@chvETypeID,
						@dectotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@dectotal,1
			IF @nRet <> 0  RETURN @nRet
		END
	END	
	IF @AssetBusinessTypeId = 9		--③固定资产投资转出  --长期股权投资 +
	BEGIN
		--长期股权投资 @TZ_ID  固定资产原值-固定资产折旧额
		SELECT @dectotal=@numZctotal - @numZJtotal-@numDevalueReady
		
		IF @dectotal<>0
		BEGIN
			EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@TZ_ID,@chvBTypeID,@chvETypeID,
						@dectotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@dectotal,1
			IF @nRet <> 0  RETURN @nRet
		END
	END	
END
/*
固定资产卡片累计折旧	贷	固定资产折旧额
【支出类】\『费用合计』\固定资产折旧	借	固定资产折旧额
*/
--固定资产折旧单
IF @numBillType = 214
BEGIN
	--固定资产折旧
	
	IF @numTotalMoney<>0
	BEGIN
		EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@ZCZJ_ID,@chvBTypeID,@chvETypeID,
					@numTotalMoney,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@NnumTotalMoney,1
		IF @nRet <> 0  RETURN @nRet
	END


	--累计折旧
	SELECT 
		@NnumTotalMoney=-@NnumTotalMoney,
		@numTotalMoney=-@numTotalMoney
	
	IF @numTotalMoney<>0
	BEGIN
		EXEC @nRet = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@LJ_ID,@chvBTypeID,@chvETypeID,
					@numTotalMoney,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@NnumTotalMoney,1
		IF @nRet <> 0  RETURN @nRet
	END
	
	
END

/*
-------------------------多账户中写listtable和扣减余额 START--------------------------
IF @AssetBusinessTypeId IN(1,2,7) AND @numBillType IN(212,213)--业务类型为购买或者变卖
BEGIN
	EXEC @nRet = GP_Auditing_MulAccount @intBillNumberID,@numBillType,@NewPosBill,@strMsg OUTPUT
	IF @nRet<>0 RETURN @nRet
END
-------------------------多账户中写listtable和扣减余额 END--------------------------
*/

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	品牌应收过账
	EXEC GP_AuditBrandarArAp 7,159
*/						
CREATE   PROCEDURE GP_AuditBrandarArAp
(
	@nBillID	numeric(10,0),	-- 单据编号 ID 值
	@nBillType	INT
)
--@encode$--
AS	
	DECLARE @ExpenseToAr INT=0
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';
	DECLARE	@YS_ID INT
	SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE FullName='预收资金';		


	--零售单不挂往来 不统计
	CREATE TABLE #BrandarARAPTotal
	(
		BrandarTypeID	VARCHAR(50),
		stypeid		VARCHAR(50),
		btypeid		VARCHAR(50),
		cid			INT,
		ARTotal		NUMERIC(24, 10) ,
		YSTotal		NUMERIC(24, 10) ,
		nARTotal	NUMERIC(24, 10),
		nYSTotal	NUMERIC(24, 10) ,
		Total		NUMERIC(24, 10) ,
		NTotal		NUMERIC(24, 10)
	)
		
	
	INSERT INTO #BrandarARAPTotal
	(		
			BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			ARTotal ,
			YSTotal ,
			nARTotal ,
			nYSTotal,
			Total,
			NTotal
	)
	SELECT	BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal),
			SUM(YSTotal),
			SUM(nARTotal),
			SUM(nYSTotal),
			0,
			0
	FROM (		     	
		--销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal-s.nCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=11
		UNION ALL      
		--组合品销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.PT_Combin_SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=12
		UNION ALL
		--销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.salebackbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=45
		UNION ALL 
		--组合品销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.PT_Combin_SaleBackBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=46 
		UNION ALL 
		--销售换货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN s.InOrOut='O' THEN  s.taxtotal-s.CompleteTotal 
										ELSE -( s.taxtotal-s.CompleteTotal )
										END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN s.InOrOut='O' THEN  s.ntaxtotal-s.NCompleteTotal
										ELSE -(s.ntaxtotal-s.NCompleteTotal)
										END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.salegoodsexchangebill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=160 
		UNION ALL 
		--委托代销结算单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.commissionbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
				  AND b.BillNumberId=@nBillID AND @nBillType=141 
		UNION ALL 
		--销售发货开票
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.ReceiptBill s
			INNER JOIN  ReceiptBillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=405
		UNION ALL 
		--预收款
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS  ARTotal,
				s.total AS YSTotal ,
				0 AS nARTotal ,
				s.ntotal AS nYSTotal 
			FROM dbo.prebill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=189 
			      AND ISNULL( B.NChargeOffTotal,0)=0 	
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL 
		--应收增加单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				s.total-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntotal-s.NCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=116 				
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL 
		--应收减少单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				-(s.total-s.CompleteTotal) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntotal-s.NCompleteTotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=115 
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL 
		--其他收入单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.total AS  ARTotal,
				0 AS YSTotal ,
				s.NTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=93 
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL 
		--费用单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.total
					  ELSE 0
					  END  AS  ARTotal,
				0 AS YSTotal ,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.NTotal
					  ELSE 0
					  END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=36	
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL
		--业务凭证
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.atypeid,
				s.CID,
				CASE  WHEN s.TypeATypeID=33  THEN s.J_Total-s.D_Total ELSE 0 END ARTotal,
				CASE  WHEN s.TypeATypeID=39  THEN s.D_Total-s.J_Total ELSE 0 END YSTotal,
				CASE  WHEN s.TypeATypeID=33  THEN s.NJ_Total-s.ND_Total ELSE 0 END nARTotal,
				CASE  WHEN s.TypeATypeID=39  THEN s.ND_Total-s.NJ_Total ELSE 0 END nYSTotal
		FROM	dbo.AccountCredence s
		INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
		INNER JOIN btype bt on s.atypeid=bt.typeid and bt. IsUseBrandarType=1		
		WHERE b.IsIni=0
		      AND b.BillNumberId=@nBillID 
		      AND @nBillType=159	
		      AND ISNULL(s.BrandarTypeId,'') <> ''			      
		UNION ALL 
		--收款单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.total+s.PreferenceMoney) AS  ARTotal,
				CASE WHEN s.AtypeId=@YS_ID THEN -s.total ELSE 0 END AS YSTotal ,--预收 不包含优惠
				-(s.ntotal+s.NPreferenceMoney )AS nARTotal ,
				CASE WHEN s.AtypeId=@YS_ID THEN  -s.ntotal ELSE 0 END  AS nYSTotal  
			FROM dbo.gatheringbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1		
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=4
			      AND ISNULL(s.BrandarTypeId,'') <> ''
			      AND B.isByBrandarType=1 --勾选了 按品牌收款 才算品牌往来
		UNION ALL 
		--从多账户取出来的
		SELECT  b.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.billtype IN (215,45,142,46)
					 THEN (b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
					 WHEN b.billtype =36  THEN CASE WHEN  b.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
													THEN (b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
													ELSE 0
													END 
						 
					 ELSE -(b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
				END AS ARTotal,				
				CASE WHEN b.billtype IN (11,12,160,141,93,405) 
					THEN -(b.YSTotalInMoney  )
					ELSE b.YSTotalInMoney 
				END AS YSTotal,
				CASE WHEN b.billtype IN (215,45,142,46)
					 THEN(b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
					 WHEN b.billtype =36 THEN CASE WHEN  b.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
													THEN (b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
													ELSE 0 
													END 			
					 ELSE -(b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
				END AS nARTotal,
				CASE WHEN b.billtype IN (11,12,160,141,93,405) 
					THEN -(b.NYSTotalInMoney  )
					ELSE b.NYSTotalInMoney 
				END AS nYSTotal
		FROM	dbo.BillMulBrand b
		INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1		
		WHERE	b.BillNumberId=@nBillID 
				AND  b.BillType=@nBillType 
				AND b.isini=0 
				AND  b.BillType  NOT IN (305,215)
			UNION ALL 
		--从多账户取出来的
		SELECT  b.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS ARTotal,				
				CASE WHEN b.billtype IN (305) 
					THEN -(b.YSTotalInMoney  )
					ELSE b.YSTotalInMoney 
				END AS YSTotal,
				0 AS nARTotal,
				CASE WHEN b.billtype IN (305) 
					THEN -(b.NYSTotalInMoney  )
					ELSE b.NYSTotalInMoney 
				END AS nYSTotal
		FROM	dbo.BillMulBrand b
		INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1		
		WHERE	b.BillNumberId=@nBillID 
				AND  b.BillType=@nBillType 
				AND b.isini=0 
				AND  b.BillType   IN (305,215)
		UNION ALL 
		--品牌结算
		SELECT	s.BrandarTypeID,
				s.stypeid,
				s.btypeid,
				s.cid,
				CASE WHEN @nBillType IN (11,12,160,141,93,405) 
					THEN -s.CompleteTotal
					ELSE s.CompleteTotal 
					END  AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN @nBillType IN (11,12,160,141,93,405) 
					THEN -s.NCompleteTotal
					ELSE s.NCompleteTotal
					END  AS nARTotal ,
				0 AS nYSTotal 
			FROM CompleteBrandarTotal s
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1		
			WHERE s.GoodsBillID=@nBillID 
				   AND s.billtype=@nBillType
				   AND S.ISDraft=0  --不是草稿的
				   AND s.isini=0			     	
		
	)total
	GROUP BY BrandarTypeID,stypeid,btypeid,cid
	
    DELETE FROM #BrandarARAPTotal 
    WHERE YSTotal=0  AND ARTotal=0  AND nYSTotal=0 
    AND nARTotal=0  
	-- 写入 brandar_ArApTotal 
	UPDATE	a 
	SET		a.ARTotal=ISNULL(a.ARTotal,0)+ISNULL(b.ARTotal,0),
			a.YSTotal=ISNULL(a.YSTotal,0)+ISNULL(b.YSTotal,0),
			a.nARTotal=ISNULL(a.nARTotal,0)+ISNULL(b.nARTotal,0),
			a.nYSTotal=ISNULL(a.nYSTotal,0)+ISNULL(b.nYSTotal,0)
		
	FROM dbo.brandar_ArApTotal a JOIN #BrandarARAPTotal b 
	ON a.stypeid=b.stypeid AND a.btypeid=b.btypeid AND a.CID=b.cid and a.BrandarTypeID=b.BrandarTypeID
	
	INSERT INTO brandar_ArApTotal(
		BTypeID,
		STypeID,
		BrandarTypeID,
		CID,
		ARTotal,
		YSTotal,
		ARTotal00,
		YSTotal00,
		nARTotal,
		nYSTotal,
		nARTotal00,
		nYSTotal00

	) SELECT 
		b.btypeId,
		b.stypeid,
		B.BrandarTypeID,
		b.cid,
		b.ARTotal,
		b.YSTotal,
		0,
		0,
		b.nARTotal,
		b.nYSTotal,
		0,
		0
		
	FROM #BrandarARAPTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM brandar_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid AND a.BrandarTypeID=b.BrandarTypeID)

	DELETE  FROM brandar_ArApTotal WHERE ISNULL(ARTotal00,0)=0 AND ISNULL(YSTotal00,0)=0 
	AND ISNULL(ARTotal,0)=0  AND ISNULL(YSTotal,0)=0 
	AND ISNULL(nARTotal00,0)=0  AND ISNULL(NYSTotal00,0)=0 
	AND ISNULL(nARTotal,0)=0 AND ISNULL(nYSTotal,0)=0 

	DROP TABLE #BrandarARAPTotal;
	
	IF @@ERROR>0
	RETURN -1;
	
	ELSE
	RETURN 0;
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2018-3-1
	描述：品牌应收的单据修改
*/						
CREATE   PROCEDURE Gp_AuditBrandarArAp_Reverse
(
	@nBillID	numeric(10,0),	-- 单据编号 ID 值
	@nBillType	INT
)
--@encode$--
AS	
	DECLARE @ExpenseToAr INT=0
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';
	DECLARE	@YS_ID INT
	SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE FullName='预收资金';		


	--零售单不挂往来 不统计
	CREATE TABLE #BrandarARAPTotal
	(
		BrandarTypeID	VARCHAR(50),
		stypeid		VARCHAR(50),
		btypeid		VARCHAR(50),
		cid			INT,
		ARTotal		NUMERIC(24, 10) ,
		YSTotal		NUMERIC(24, 10) ,
		nARTotal	NUMERIC(24, 10),
		nYSTotal	NUMERIC(24, 10) ,
		Total		NUMERIC(24, 10) ,
		NTotal		NUMERIC(24, 10)
	)
			
	INSERT INTO #BrandarARAPTotal
	(		
			BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			ARTotal ,
			YSTotal ,
			nARTotal ,
			nYSTotal,
			Total,
			NTotal
	)
	SELECT	BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal),
			SUM(YSTotal),
			SUM(nARTotal),
			SUM(nYSTotal),
			0,
			0
	FROM (
		
		--销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal-s.nCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=11
		UNION ALL      
		--组合品销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_PT_Combin_SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=12
		UNION ALL
		--销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_salebackbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=45
		UNION ALL 
		--组合品销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_PT_Combin_SaleBackBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=46 
		UNION ALL 
		--销售换货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN s.InOrOut='O' THEN  s.taxtotal-s.CompleteTotal 
										ELSE -( s.taxtotal-s.CompleteTotal )
										END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN s.InOrOut='O' THEN  s.ntaxtotal-s.NCompleteTotal
										ELSE -(s.ntaxtotal-s.NCompleteTotal)
										END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_salegoodsexchangebill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID AND @nBillType=160 
		UNION ALL 
		--委托代销结算单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_commissionbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
				  AND b.BillNumberId=@nBillID AND @nBillType=141 
		UNION ALL 
		--销售发货开票
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_ReceiptBill s
			INNER JOIN  ReceiptBillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=405
		UNION ALL 
		--预收款
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS  ARTotal,
				s.total AS YSTotal ,
				0 AS nARTotal ,
				s.ntotal AS nYSTotal 
			FROM dbo.Old_prebill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=189 
			      AND ISNULL(B.NChargeOffTotal,0)=0 	
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL 
		--应收增加单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				s.total-s.CompleteTotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntotal-s.NCompleteTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=116 				
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL 
		--应收减少单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				-(s.total-s.CompleteTotal) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntotal-s.NCompleteTotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=115 
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL 
		--其他收入单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.total AS  ARTotal,
				0 AS YSTotal ,
				s.NTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=93 
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL 
		--费用单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.total
					  ELSE 0
					  END  AS  ARTotal,
				0 AS YSTotal ,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.NTotal
					  ELSE 0
					  END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.Old_moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=36	
			      AND ISNULL(s.BrandarTypeId,'') <> ''
		UNION ALL
		--业务凭证
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.atypeid,
				s.CID,
				CASE  WHEN s.TypeATypeID=33  THEN s.J_Total-s.D_Total ELSE 0 END ARTotal,
				CASE  WHEN s.TypeATypeID=39  THEN s.D_Total-s.J_Total ELSE 0 END YSTotal,
				CASE  WHEN s.TypeATypeID=33  THEN s.NJ_Total-s.ND_Total ELSE 0 END nARTotal,
				CASE  WHEN s.TypeATypeID=39  THEN s.ND_Total-s.NJ_Total ELSE 0 END nYSTotal
		FROM	dbo.AccountCredence s
		INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
		INNER JOIN btype bt ON s.ATypeID=bt.typeid and bt. IsUseBrandarType=1	
		WHERE b.IsIni=0
		      AND b.BillNumberId=@nBillID 
		      AND @nBillType=159	
		      AND ISNULL(s.BrandarTypeId,'') <> ''			      
		UNION ALL 
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.total+s.PreferenceMoney) AS  ARTotal,
				CASE WHEN s.AtypeId=@YS_ID THEN -s.total ELSE 0 END AS YSTotal ,--预收 不包含优惠
				-(s.ntotal+s.NPreferenceMoney )AS nARTotal ,
				CASE WHEN s.AtypeId=@YS_ID THEN  -s.ntotal ELSE 0 END  AS nYSTotal  
			FROM dbo.gatheringbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE b.IsIni=0
			      AND b.BillNumberId=@nBillID 
			      AND @nBillType=4
			      AND ISNULL(s.BrandarTypeId,'') <> ''
			      AND B.isByBrandarType=1 --勾选了 按品牌收款 才算品牌往来
		UNION ALL 
		--从多账户取出来的
		SELECT  b.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.billtype IN (215,45,142,46)
					 THEN (b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
					 WHEN b.billtype =36  THEN CASE WHEN  b.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
													THEN (b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
													ELSE 0
													END 
						 
					 ELSE -(b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
				END AS ARTotal,				
				CASE WHEN b.billtype IN (11,12,160,141,93,405) 
					THEN -(b.YSTotalInMoney  )
					ELSE b.YSTotalInMoney 
				END AS YSTotal,
				CASE WHEN b.billtype IN (215,45,142,46)
					 THEN(b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
					 WHEN b.billtype =36 THEN CASE WHEN  b.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
													THEN (b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
													ELSE 0 
													END 			
					 ELSE -(b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
				END AS nARTotal,
				CASE WHEN b.billtype IN (11,12,160,141,93,405) 
					THEN -(b.NYSTotalInMoney  )
					ELSE b.NYSTotalInMoney 
				END AS nYSTotal
		FROM	dbo.Old_BillMulBrand b
		INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
		WHERE	b.BillNumberId=@nBillID 
				AND  b.BillType=@nBillType 
				AND b.isini=0 
				AND  b.BillType  NOT IN (305,215)
			UNION ALL 
		--从多账户取出来的
		SELECT  b.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS ARTotal,				
				CASE WHEN b.billtype IN (305) 
					THEN -(b.YSTotalInMoney  )
					ELSE b.YSTotalInMoney 
				END AS YSTotal,
				0 AS nARTotal,
				CASE WHEN b.billtype IN (305) 
					THEN -(b.NYSTotalInMoney  )
					ELSE b.NYSTotalInMoney 
				END AS nYSTotal
		FROM	dbo.Old_BillMulBrand b
		INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
		WHERE	b.BillNumberId=@nBillID 
				AND  b.BillType=@nBillType 
				AND b.isini=0 
				AND  b.BillType  IN (305,215)
		UNION ALL 
		--品牌结算
		SELECT	s.BrandarTypeID,
				s.stypeid,
				s.btypeid,
				s.cid,
				CASE WHEN @nBillType IN (11,12,160,141,93,405) 
					THEN -s.CompleteTotal
					ELSE s.CompleteTotal 
					END  AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN @nBillType IN (11,12,160,141,93,405) 
					THEN -s.NCompleteTotal
					ELSE s.NCompleteTotal
					END  AS nARTotal ,
				0 AS nYSTotal 
			FROM  Old_CompleteBrandarTotal s
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE s.GoodsBillID=@nBillID 
				   AND s.billtype=@nBillType
				   AND S.ISDraft=0  --不是草稿的
				   AND s.isini=0			     	
		
	)total
	GROUP BY BrandarTypeID,stypeid,btypeid,cid
	
    DELETE FROM #BrandarARAPTotal WHERE YSTotal=0  AND ARTotal=0  AND nYSTotal=0 AND nARTotal=0  
    
	-- 写入 brandar_ArApTotal 
	UPDATE	a 
	SET		a.ARTotal=ISNULL(a.ARTotal,0)-ISNULL(b.ARTotal,0),
			a.YSTotal=ISNULL(a.YSTotal,0)-ISNULL(b.YSTotal,0),
			a.nARTotal=ISNULL(a.nARTotal,0)-ISNULL(b.nARTotal,0),
			a.nYSTotal=ISNULL(a.nYSTotal,0)-ISNULL(b.nYSTotal,0)		
	FROM	dbo.brandar_ArApTotal a 
	JOIN	#BrandarARAPTotal b ON a.stypeid=b.stypeid 
			AND a.btypeid=b.btypeid 
			AND a.CID=b.cid 
			AND a.BrandarTypeID=b.BrandarTypeID	
	
	INSERT INTO brandar_ArApTotal
	(
		BTypeID,
		STypeID,
		BrandarTypeID,
		CID,
		ARTotal,
		YSTotal,
		ARTotal00,
		YSTotal00,
		nARTotal,
		nYSTotal,
		nARTotal00,
		nYSTotal00

	) 
	SELECT	b.btypeId,
			b.stypeid,
			B.BrandarTypeID,
			b.cid,
			-b.ARTotal,
			-b.YSTotal,
			0,
			0,
			-b.nARTotal,
			-b.nYSTotal,
			0,
			0		
	FROM	#BrandarARAPTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM brandar_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid AND a.BrandarTypeID=b.BrandarTypeID)

	DELETE 
	FROM	brandar_ArApTotal 
	WHERE	ISNULL(ARTotal00,0)=0 AND ISNULL(YSTotal00,0)=0 
			AND ISNULL(ARTotal,0)=0  AND ISNULL(YSTotal,0)=0 
			AND ISNULL(nARTotal00,0)=0  AND ISNULL(NYSTotal00,0)=0 
			AND ISNULL(nARTotal,0)=0 AND ISNULL(nYSTotal,0)=0 

	DROP TABLE #BrandarARAPTotal;
	
	IF @@ERROR>0
	RETURN -1;
	
	ELSE
	RETURN 0;
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_AuditedAcVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_AuditedAcVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查审核
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_AuditedAcVoucherBill
(
	@BillNumberId	VARCHAR(50)='',			--单据ID
	@OpertionId		VARCHAR(50)=''			--操作人	
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@etypeid		VARCHAR(50),
	@fchecked		VARCHAR(2)='',
	@recheckid		VARCHAR(2)='',
	@ifcheck		VARCHAR(2)='',
    @markerror		VARCHAR(200)='',
	@ErrorCount		INT=0,
	@SubValue		VARCHAR(1)=''--制单人 审核 复核 过账 错误条数 制单人是否可与审核人为一个人
	
SELECT
	@etypeid=ISNULL(ETypeId,''), 
	@fchecked=ISNULL(FChecked,''),
	@recheckid=ISNULL(ReCheckId,''),
	@ifcheck=ISNULL(IfCheck,''),
    @markerror=isnull(markerror,'')
FROM Ac_Voucher
WHERE BillNumberId=@BillNumberId 
		 
IF @@ROWCOUNT = 0--判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN -1
END

SELECT @SubValue=ISNULL(SubValue,'') FROM sysdata WHERE SubName='acallowthesame'--检查制单人是否可与审核人为一个人
IF(@SubValue<>'1' AND @etypeid=@OpertionId)
	BEGIN
		RAISERROR('凭证审核人与制单人为同一人！请确认！',16,1)
		RETURN -1
	END
	
IF(@ifcheck='t')
	BEGIN
		RAISERROR('凭证已经记账!请确认！',16,1)--记账
		RETURN -1
	END
IF(@fchecked='1')
	BEGIN
		RAISERROR('凭证已经审核!请确认！',16,1)--/审核
		RETURN -1
	END
IF(@fchecked='-1')
	BEGIN
		RAISERROR('凭证已经作废!请确认！',16,1)--/作废
		RETURN -1
	END

IF(@markerror<>'')
	BEGIN
		RAISERROR('凭证已经标错!请确认！',16,1)--/审核
		RETURN -1
	END
	
UPDATE Ac_Voucher SET FChecked=1,AuditId=@OpertionId,RChecker='' WHERE BillNumberId=@BillNumberID--审核 记账凭证主表
SET @ErrorCount+=@@ERROR

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='审核凭证单据错误，请确认！'
		RAISERROR(@MSG2,16,1)
		RETURN -1
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_AuditedAllReVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_AuditedAllReVoucher
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	反审核所有已审核会计凭证
-- 时间：	2013-08-09
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_AuditedAllReVoucher
(
	@StypeID		VARCHAR(50)='',			--分支结构ID
	@OperatorID		VARCHAR(50)=''			--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON 



DECLARE	
	@PassCount		INT=0,			--成功条数
	@FailtCount		INT=0,			--失败条数
	@ErrorMsg		VARCHAR(2000),	--失败原因
	@BillNumberId	NUMERIC(18,0)=0,--凭证ID
	@BillCode		VARCHAR(500)='',--凭证编号
	@BillCount		INT,			--满足条件凭证条数
	@I				INT,			--
	@Re				INT,			--执行复核存储过程报错
	@FYear			INT,
	@FPeriod		INT

--获取当前分支机构年度、会计期间
SELECT @FYear=FYear,@FPeriod=FPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID

	
--单据
DECLARE @VoucherBill TABLE
(
	Nid				INT IDENTITY(1,1),
	BillNumberId	NUMERIC(18,0),
	BillCode		VARCHAR(500)
)

INSERT INTO @VoucherBill(BillNumberId,BillCode)
SELECT 
	BillNumberId,
	'凭证'+G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE	
	STypeId = @stypeid
	AND V.FChecked=1
	AND FYear=@FYear
	AND FPeriod=@FPeriod
	AND V.IfCheck='F'
	
SET @BillCount = @@ROWCOUNT


--展示结果
DECLARE @Result TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)

SET @I=1
WHILE @I<=@BillCount
	BEGIN
		SELECT @BillNumberId = BillNumberId,@BillCode = BillCode FROM @VoucherBill WHERE Nid = @I
		BEGIN TRY
			BEGIN
				EXEC @Re = Gp_ReAuditedAcVoucherBill @BillNumberId,@OperatorID
			
			IF @Re = 0
				BEGIN
					INSERT INTO @Result(BillCode,Msg)VALUES(@BillCode,',成功')
					SET @PassCount = @PassCount + 1
				END
			END	
		END TRY
		BEGIN CATCH
			BEGIN			
				SET @FailtCount = @FailtCount + 1
				SET @ErrorMsg = ERROR_MESSAGE()
				--处理提示
				SET @ErrorMsg = REPLACE(@ErrorMsg,'，不允许反审核，请确认！','')	
				IF @ErrorMsg <> ''
					INSERT INTO @Result(BillCode,Msg)VALUES(@BillCode,',失败,原因为'+@ErrorMsg)
			END
		END CATCH		
		SET @I = @I + 1
	END
	
--展示结果
DECLARE @showResult TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)

--第一条记录
INSERT INTO @showResult(BillCode,Msg)VALUES('成功反审核:','')
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',成功' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('成功共',CAST(@PassCount AS VARCHAR(100)) + '张')

--失败张数
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',失败' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('失败共',CAST(@FailtCount AS VARCHAR(100))+'张')

SELECT * FROM @showResult

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_AuditedAllVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_AuditedAllVoucher
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	审核所有未审核会计凭证
-- 时间：	2013-06-21
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_AuditedAllVoucher
(
	@StypeID		VARCHAR(50)='',			--分支结构ID
	@OperatorID		VARCHAR(50)=''			--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON 



DECLARE	
	@PassCount		INT=0,			--成功条数
	@FailtCount		INT=0,			--失败条数
	@ErrorMsg		VARCHAR(2000),	--失败原因
	@BillNumberId	NUMERIC(18,0)=0,--凭证ID
	@BillCode		VARCHAR(500)='',--凭证编号
	@BillCount		INT,			--满足条件凭证条数
	@I				INT,			--
	@Re				INT,			--执行复核存储过程报错
	@AcNobatchchk	VARCHAR(2)='',	--禁止成批审核凭证
	@FYear			INT,
	@FPeriod		INT
--获取当前分支机构会计期间
SELECT @FYear=FYear,@FPeriod=FPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID 

SELECT @AcNobatchchk=SubValue FROM sysdata WHERE SubName='acnobatchchk'
IF ISNULL(@AcNobatchchk,'')='1'
	BEGIN
		RAISERROR('禁止成批审核凭证！请确认后重试！',16,1)
		RETURN
	END
	
--单据
DECLARE @VoucherBill TABLE
(
	Nid				INT IDENTITY(1,1),
	BillNumberId	NUMERIC(18,0),
	BillCode		VARCHAR(500)
)

INSERT INTO @VoucherBill(BillNumberId,BillCode)
SELECT 
	BillNumberId,
	'凭证'+G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE	
	STypeId = @stypeid
	AND V.FChecked=0
	AND FYear=@FYear
	AND FPeriod=@FPeriod
	AND V.IfCheck='F'
	
SET @BillCount = @@ROWCOUNT


--展示结果
DECLARE @Result TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)

SET @I=1
WHILE @I<=@BillCount
	BEGIN
		SELECT @BillNumberId = BillNumberId,@BillCode = BillCode FROM @VoucherBill WHERE Nid = @I
		BEGIN TRY
			BEGIN
				EXEC @Re = Gp_AuditedAcVoucherBill @BillNumberId,@OperatorID
			
			IF @Re = 0
				BEGIN
					INSERT INTO @Result(BillCode,Msg)VALUES(@BillCode,',成功')
					SET @PassCount = @PassCount + 1
				END
			END	
		END TRY
		BEGIN CATCH
			BEGIN			
				SET @FailtCount = @FailtCount + 1
				SET @ErrorMsg = ERROR_MESSAGE()
				--处理提示
				SET @ErrorMsg = REPLACE(@ErrorMsg,'，不允许审核，请确认！','')	
				IF @ErrorMsg <> ''
					INSERT INTO @Result(BillCode,Msg)VALUES(@BillCode,',失败,原因为'+@ErrorMsg)
			END
		END CATCH		
		SET @I = @I + 1
	END
	
--展示结果
DECLARE @showResult TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)

--第一条记录
INSERT INTO @showResult(BillCode,Msg)VALUES('成功审核:','')
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',成功' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('成功共',CAST(@PassCount AS VARCHAR(100)) + '张')

--失败张数
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',失败' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('失败共',CAST(@FailtCount AS VARCHAR(100))+'张')

SELECT * FROM @showResult

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	系统核心过账存储过程
	作    者：	卢 春
	修改时间：	2003-07-23
	
	修改人:		冯波
*/
CREATE             PROCEDURE Gp_Auditing
(
	@nBillID				NUMERIC(10,0),					-- 单据 ID 号
	@szCheckMan				VARCHAR(50),					-- 制单人 ID 值
	@szPID					VARCHAR(1000) OUTPUT,			-- 返回出错商品 ID 值
	@chvOpID				VARCHAR(50) = '',				-- 当前操作员 ID 值
	@KTypeID				VARCHAR(50) = '' OUTPUT,		-- 返回仓库ID值，针对多仓库应用
	@billtype				INT = 0,						-- 单据类型
	@voucherMsg				VARCHAR(50)	= '' OUTPUT,		--返回凭证生成的信息
	@VipCentInfo			VARCHAR(200) = '' OUTPUT,		--返回会员卡积分调整信息
	@AssetMsg				VARCHAR(MAX)='' OUT,			--返回固定资产信息
	@VipCardCode			VARCHAR(200)='' OUT,
	@CommissionConfirm		INT=0,
	@strReturnBillCode		VARCHAR(200)='' OUT
)
AS
SET NOCOUNT ON

BEGIN TRAN audit
SAVE TRAN auditPoint	

--解锁商品
IF @billtype IN (11,12,140,402)--销售出库单、委托代销发货单、组合品销售发货单需要解锁商品
BEGIN
	EXEC GP_DoClear @nBillID,@billtype
END
	
	
DECLARE 
	@nRet					INT,						-- 返回的出错值
	@szCheck				CHAR(1),					-- 过账标志
	@chvSTypeID				VARCHAR(50)					--分支机构
	
--处理借欠开始
IF @billtype IN ( 71,72,87,88)
BEGIN

	SELECT	@chvSTypeID =Stypeid  
	FROM	dbo.LendIndex 
	WHERE	BillNumberId = @nBillID
	
	EXEC @nRet=Gp_Auditing_Control @chvSTypeID
	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	
	EXEC @nRet=Gp_CheckLimitBillType @chvOpID,0,@billtype
	IF @nRet<>1 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN 1000 --没有单据过账的权限
	END
	SELECT @nRet = 0
	--判断状态

	IF NOT EXISTS(
		SELECT BillnumberID
		FROM LendIndex
		WHERE BillNumberId=@nBillID
		AND ifcheck='f'
	)
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN 1111  --该单据不存在或已过账
	END
	DECLARE @StartDate VARCHAR(10),@StartDate1 VARCHAR(10)
	SELECT @StartDate =  CONVERT( VARCHAR(10), StartDate,120) FROM dbo.MonthProc WHERE MonthNo='本期'
	SELECT @StartDate1 = CONVERT( VARCHAR(10), BillDate,120)  FROM dbo.LendIndex WHERE BillNumberId = @nBillID

	if DATEDIFF(DAY,@StartDate,@StartDate1) < 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN 301--单据日期必须大于或等于当前会计期间的起始日期
	END
	IF EXISTS(
		SELECT AuditingID FROM AuditingFlowSet
		WHERE BillType=@billtype AND Stypeid=@chvSTypeID AND IfUse=1
	)
	BEGIN
		IF EXISTS(
			SELECT * FROM dbo.AuditingBill 
			WHERE BillNumberID = @nBillID AND IfAudit = 0 AND BillIndexType = 1
		)
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN  1122  --该单据需要审核
		END
	END 
	

	EXEC	@nRet=Gp_Auditing_Lend
									@nBillID,					-- 单据 ID 号
									@szCheckMan,				-- 制单人 ID 值
									@chvOpID,					-- 当前操作员 ID 值
									@billtype	,				-- 单据类型
									@szPID OUTPUT
									--@voucherMsg OUT				--返回凭证生成的信息
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
	END
	ELSE
	BEGIN
		COMMIT TRAN audit
	END		
	RETURN @nRet	
END
--处理借欠结束
	
/*****物流运输单据 begin
上架单
拣货单
运输配送单
******/
IF @billtype IN ( 412,413,414,415)
BEGIN
	EXEC @nRet=GP_AuditingWLBill @nBillID,@billtype,@chvOpID
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
	END
	ELSE IF @BillType IN(412,413,415)
	BEGIN
		COMMIT TRAN audit
	END
	IF @BillType IN(412,413,415) OR @nRet<>0 
	BEGIN
		RETURN @nRet
	END
END

/***门店配送单据***/
--IF @billtype IN(327,328,329) 
--BEGIN
--	EXEC @nRet=GP_AuditingDelivery @nBillID,@billtype,@chvOpID
--	IF @nRet <> 0
--	BEGIN
--		ROLLBACK TRAN auditPoint
--		COMMIT TRAN audit
--	END
--	ELSE
--	BEGIN
--		COMMIT TRAN audit
--	END
--	RETURN @nRet
--END

/*****物流运输单据 end******/

/****实物库存单据  begin
仓库入库单
仓库出库单
仓库调拨单
****/
IF @BillType IN(418,419,420)
BEGIN
	EXEC @nRet=GP_Auditing_FactBill @nBillID,@BillType,@chvOPID,@szPID OUT
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
	END
	ELSE
	BEGIN
		COMMIT TRAN audit
	END
	RETURN @nRet
END
/****实物库存单据  end*****/	

--提成单
IF @billtype=311
BEGIN
	SELECT
		@chvSTypeID=STypeID
	FROM	CommissionBillNew
	WHERE BillNumberId=@nBillID
	
	EXEC @nRet=Gp_Auditing_Control @chvSTypeID

	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	    
	EXEC @nRet=Gp_CheckLimitBillType @chvOpID,0,@billtype
	IF @nRet<>1 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN 1000 --没有单据过账的权限
	END
	SELECT @nRet = 0
	--判断状态

	IF NOT EXISTS(
		SELECT BillnumberID
		FROM CommissionBillNew
		WHERE BillNumberId=@nBillID
		AND ifcheck='f'
	)
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN 1111  --该单据不存在或已过账
	END    
	
	--2017-02-08 梁晰 判断提成单是否需要审核
	IF @billtype = 311
	BEGIN
	  DECLARE @returnval INT;
	  
	  EXEC @returnval = GP_BillAudtingCheckReason @nBillID,@chvOpID,6,'',-1,1,0;
	  
	  IF @returnval <> 0
	  BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
	    RETURN  1122  --该单据需要审核
	  END
	  
	END
	
	EXEC	@nRet=Gp_Auditing_Profit
			@nBillID,					-- 单据 ID 号
			@szCheckMan,				-- 制单人 ID 值
			@chvOpID,					-- 当前操作员 ID 值
			@billtype,					-- 单据类型
			@voucherMsg OUT				--返回凭证生成的信息
	IF @nRet <> 0
	BEGIN
		COMMIT TRAN audit
	END
	ELSE
	BEGIN
		COMMIT TRAN audit
	END		
	RETURN @nRet
END
	
-----------------------------------------优惠券过账 begin----------------------------------------------------------------------
IF @BILLTYPE IN (423,424,425,426,428,429)
BEGIN
	EXEC @nRet=GP_Auditing_CouponBill @nBillID,@BillType,@szCheckMan,@chvOPID,@szPID OUT
	
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	
	IF @BILLTYPE=429
	BEGIN
		DECLARE
			@ReturnID			BIGINT,
			@ErrMsg				VARCHAR(1000)	
		EXEC	@nRet=GP_CouponStypeOutBill_CreateBill
					@chvOpID,
					@nBillID,
					@ReturnID OUT,		--新生成的单据的ID
					@strReturnBillCode OUT,
					@ErrMsg OUT		--出错信息	
		
		IF @nRet<>0 
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN @nRet
		END
	END
	
	----业务凭证 
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
		AND	EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'postingparameter' AND SubValue = 0)--即时过账，即时生成凭证
		AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'aloneusebsys' AND SubValue = 0)--使用总账系统
		AND @billtype IN(423,424,426,428,429)--优惠券入库、出库、退货才需要生成凭证
	BEGIN
		DECLARE @atid_c INT
		SELECT @atid_c = atid FROM dbo.Coupon_BillIndex WHERE BillNumberId = @nBillID
		EXEC @nRet = dbo.Gp_AutoCreate_Voucher @nBillID,@chvOPID,@atid_c,'',@voucherMsg OUTPUT,@BillType
		IF @nRet <> 0 
		BEGIN
			COMMIT TRAN audit
			RETURN @nRet
			
		END 	
	END 
	ELSE
		SET @voucherMsg = ''
		
	COMMIT TRAN audit
	RETURN @nRet	

END
------------------------------------------优惠券过账 end  ---------------------------------------------------------------------
	
--积分转储值单
IF(@billtype=427)
BEGIN
	EXEC @nRet=GP_Auditing_VipCentToMoneyBill @nBillID,@BillType,@szCheckMan,@chvOPID,@szPID OUT
		
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	----业务凭证 
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
		AND	EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'postingparameter' AND SubValue = 0)--即时过账，即时生成凭证
		AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'aloneusebsys' AND SubValue = 0)--使用总账系统
	BEGIN
		DECLARE @atid_427 INT
		SELECT @atid_427 = atid FROM dbo.BillIndex WHERE BillNumberId = @nBillID
		EXEC @nRet = dbo.Gp_AutoCreate_Voucher @nBillID,@chvOPID,@atid_427,'',@voucherMsg OUTPUT,@BillType
		IF @nRet <> 0 
		BEGIN
			COMMIT TRAN audit
			RETURN @nRet
			
		END 	
	END 
	ELSE
		SET @voucherMsg = ''
		
	COMMIT TRAN audit
	RETURN @nRet
END
	
DECLARE
	@datBillDate			DATETIME,					-- 单据日期
	@chvATypeID				VARCHAR(50),				-- 收付款账户 ID 值
	@chvBTypeID				VARCHAR(50),				--结算单位
	@chvDealBTypeID			VARCHAR(50),				--往来单位
	@chvETypeID				VARCHAR(50),				-- 经手人 ID 值
	@chvKTypeID				VARCHAR(50),				-- 出库仓库 ID 值
	@chvKTypeID2			VARCHAR(50),				-- 入库仓库 ID 值
	@chvDTypeID				VARCHAR(50),				--部门
	@numTotalMoney			 NUMERIC(24, 10) ,				-- 单据金额合计
	@numTotalInMoney		 NUMERIC(24, 10) ,				-- 单据实收、实付金额
	@numPreferenceMoney		 NUMERIC(24, 10) ,
	@numNTotalMoney			 NUMERIC(24, 10) ,
	@numNTotalInMoney		 NUMERIC(24, 10) ,
	@numNPreferenceMoney	 NUMERIC(24, 10) ,
	@wxTotal				 NUMERIC(24, 10) ,	
	@numTax					 NUMERIC(24, 10) ,
	@ifIndexWX				TINYINT,
	@intCostSale			TINYINT,
	@intCID					INT,
	@ifCheck				VARCHAR(10),				-- 是否草稿标识，f - 草稿；t - 已过账
	@IfMulAccount			TINYINT,
	@intVipCardID			INT,
	@BillName				VARCHAR(100),
	@NumRate				 NUMERIC(24, 10) ,
	@AssetBusinessTypeId    INT,
	@intRedWord				TINYINT,
	@intNewPosBill			TINYINT,
	@AuditType				INT,
	@IfLend					INT=0,
	@datPostTime			DATETIME 

	--获取主表的相关信息
	EXEC	GP_GetBillIndexInfo @nBillID,
								@Billtype,
								@datBillDate	OUT,
								@chvATypeID	OUT,				-- 收付款账户 ID 值
								@chvBTypeID	OUT,				--结算单位
								@chvDealBTypeID	OUT,				--往来单位
								@chvETypeID	OUT,				-- 经手人 ID 值
								@chvKTypeID	OUT,				-- 出库仓库 ID 值
								@chvKTypeID2	OUT,				-- 入库仓库 ID 值
								@chvDTypeID	OUT,				--部门
								@chvSTypeID	OUT,				--分支机构
								@numTotalMoney	OUT,				-- 单据金额合计
								@numTotalInMoney	OUT,				-- 单据实收、实付金额
								@numPreferenceMoney	OUT,
								@numNTotalMoney	OUT,
								@numNTotalInMoney	OUT,
								@numNPreferenceMoney	OUT,
								@wxTotal	OUT,	
								@numTax	OUT,
								@ifIndexWX	OUT,
								@intCostSale	OUT,
								@intCID	OUT,
								@ifCheck	OUT,				-- 是否草稿标识，f - 草稿；t - 已过账
								@IfMulAccount	OUT,
								@intVipCardID	OUT,
								@NumRate		OUT,
								@AssetBusinessTypeId OUT,
								@intRedWord			OUT,
								@intNewPosBill	OUT,
								@IfLend			OUT,
								@datPostTime	OUT

	
	DECLARE
		@VerifyID	VARCHAR(50)		
	
	SELECT 
		@VerifyID=@chvSTypeID
	
	IF EXISTS(
		SELECT TypeID
		FROM SType
		WHERE TypeId=@chvSTypeID AND IsSelfVerify=0
	)
	BEGIN
		SELECT @VerifyID=VerifyID
		FROM SType
		WHERE TypeId=@chvSTypeID
	END
		
	IF ISNULL(@AssetBusinessTypeId,'')<>''
	BEGIN
		SELECT @AuditType=AuditType
		FROM Ac_AssetBusinessType
		WHERE ID=@AssetBusinessTypeId AND STypeId=@VerifyID
	END	
	
	SELECT	@BillName=detailTable
	FROM	BillName
	WHERE	Billtype=@Billtype
	
	
	--过账前控制（软件狗等）
	EXEC @nRet=Gp_Auditing_Control @chvSTypeID,@BillType	

	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	
	--985新增单据判断
	EXEC @nRet=GP_Auditing_BillInfo @nBillID,@BillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	
	IF @billtype in (305,215,11,45,12,46) AND EXISTS (SELECT TOP 1 1 FROM Coupon_BillUsed WHERE BillnumberId=@nBillID )
	BEGIN
		 --券编码在不在
		IF not EXISTS (SELECT TOP 1 1 FROM Coupon_CodeInfo C INNER JOIN Coupon_BillUsed B ON C.CouponCode=B.CouponCode WHERE b.BillnumberId=@nBillID )
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN 1121 
		END 
	END 
	
	--退货单使用优惠券 ，判断 是否整单退货
	IF @billtype IN (215,45,46)
	BEGIN
		IF EXISTS (SELECT TOP 1 1 FROM dbo.Coupon_BillUsed B INNER JOIN dbo.Coupon_CodeInfo C ON B.CouponCode=C.CouponCode WHERE B.BillnumberId=@nBillID AND B.BillType=@billtype AND C.[STATE]<>3 AND b.PosId=0  )
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN 1115
		END 
		
	END 
	--判断优惠券是否过期,出库单才判断 排除pos上传的code
	IF @billtype IN (305,11,12) AND EXISTS (SELECT TOP 1 1 FROM Coupon_BillUsed WHERE BillnumberId=@nBillID AND PosId=0 )
	BEGIN
		--失效日期>当前日期
		IF EXISTS (SELECT TOP 1 1 FROM Coupon_CodeInfo C INNER JOIN Coupon_BillUsed B ON C.CouponCode=B.CouponCode WHERE b.BillnumberId=@nBillID AND b.PosId=0 AND DATEDIFF(DAY,GETDATE(),C.Invaliddate) <0 )
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN 1116 
		END 
	END

	IF @billtype in (305,215,11,45,12,46) AND EXISTS (SELECT TOP 1 1 FROM Coupon_BillUsed WHERE BillnumberId=@nBillID )
	BEGIN 
		 --适用分支机构
		IF NOT EXISTS (
			   SELECT TOP 1 1 
                            FROM  dbo.Coupon_CodeInfo c
							INNER JOIN dbo.Coupon_BillUsed B ON B.CouponCode = c.CouponCode 
							INNER JOIN  coupon_typeinfo t ON t.CouponId = c.CouponId
                            INNER JOIN dbo.coupon_ApplyStype s ON C.CouponId=s.CouponId
                            WHERE B.BillnumberId=@nBillID AND B.BillType=@billtype 
								AND( s.stypeid='00000' OR s.stypeid=@chvSTypeID)
                          
		)
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN 1117
		END 
		 --判断优惠券状态 排除pos上传的code
		 IF  EXISTS (SELECT TOP 1 1 
		                            FROM coupon_codeinfo  c 
		                            INNER JOIN dbo.Coupon_BillUsed B ON B.CouponCode = c.CouponCode 
		                            WHERE  B.BillnumberId=@nBillID AND B.BillType=@billtype
		                            AND	   (@billtype IN (305,11,12) AND c.[state] NOT IN (2,4,5)
				                            OR @billtype IN (215,45,46) AND c.[state]  NOT IN (3))
				                   AND NOT EXISTS (SELECT  cb.couponcode  FROM coupon_billused cb WHERE cb.posid<>0 and cb.billnumberid =@nBillID and c.couponcode=cb.couponcode  )
		                           
				           )
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit                 
			RETURN 1118   
		END  
		
		IF  EXISTS (SELECT TOP 1 1
                                    FROM dbo.Coupon_BillUsed B
                                    INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = B.CouponCode AND ISNULL(B.COUPONID,0)<>C.COUPONID
                                    WHERE B.BillnumberId =@nBillID  and  b.billtype=@billtype
		                        )
		  BEGIN 
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit                 
			RETURN 1119  
		  END 
		                        
				                            
	END 	
	
	--品牌验证
	IF EXISTS(SELECT  TOP 1 1 FROM sysdata  WHERE subname='usebrandartype' AND SubValue ='1') AND @billtype IN(4,11,12,36,45,46,93,115,116,141,160,189,215,305,402,403,405,450) 
	--AND (SELECT IsUseBrandarType FROM btype WHERE typeId IN ( SELECT btypeid FROM BillIndex WHERE BillNumberId=@nBillID))=1
	--AND EXISTS(SELECT 1 FROM dbo. btype WHERE typeid =@chvBTypeID AND IsUseBrandarType=1)
	BEGIN
		--多账户有值，品牌没值的情况
		IF (SELECT IsUseBrandarType FROM btype WHERE typeId IN ( SELECT btypeid FROM BillIndex WHERE BillNumberId=@nBillID))=1
		AND EXISTS(SELECT 1 FROM dbo. btype WHERE typeid =@chvBTypeID AND IsUseBrandarType=1)
		BEGIN 
			DECLARE 
				@A_Total NUMERIC(22,10)=0,--多账户收款金额
				@B_Total NUMERIC(22,10)=0--品牌应收
			SELECT @A_Total=ISNULL(SUM(NTotalMoney),0) FROM BillMulAccount WHERE BillType=@billtype AND BillNumberId=@nBillID
			SELECT @B_Total=ISNULL(SUM(NTotalInMoney+NYSTotalInMoney),0) FROM BillMulBrand WHERE BillType=@billtype AND BillNumberId=@nBillID
			
			
			IF @A_Total<>@B_Total
			BEGIN
				ROLLBACK TRAN auditPoint
				COMMIT TRAN audit    		 
				RETURN 1123;
			END
		END 
		IF @BILLTYPE IN (36,93,189,116,115,4,159)
		BEGIN
			--1 验证为空 
			IF  EXISTS (SELECT  TOP 1 1 
						FROM  addebtbill ad 
						INNER JOIN btype b ON ad.BtypeId=b.typeId AND b.IsUseBrandarType=1
						WHERE ISNULL(ad.brandartypeid,'')='' AND ad.BillNumberId=@nBillID 
						AND  @billtype IN(115,116) 
						UNION ALL 
						SELECT  TOP 1 1 FROM  gatheringbill g 
						INNER JOIN  billindex b ON b.BillNumberId = g.BillNumberId 
						INNER JOIN btype bt ON b.btypeid=bt.typeId AND bt.IsUseBrandarType=1
						WHERE ISNULL(g.brandartypeid,'')='' AND g.BillNumberId=@nBillID AND  @billtype IN(4) AND b.isByBrandarType=1 --勾选了 按品牌收款才 验证
						UNION ALL 
						SELECT  TOP 1 1 FROM  prebill  pre
						INNER JOIN billindex b ON pre.BillNumberId=b.BillNumberId
						INNER JOIN btype bt ON b.btypeid=bt.typeId AND bt.IsUseBrandarType=1
						WHERE ISNULL(pre.brandartypeid,'')='' AND pre.BillNumberId=@nBillID AND  @billtype IN(189)
						UNION ALL 
						SELECT  TOP 1 1 FROM  moneybill pre
						INNER JOIN billindex b ON pre.BillNumberId=b.BillNumberId
						INNER JOIN btype bt ON b.btypeid=bt.typeId AND bt.IsUseBrandarType=1
						WHERE ISNULL(pre.brandartypeid,'')='' AND pre.BillNumberId=@nBillID AND  @billtype IN(36,93)
						UNION ALL--159-业务凭证；
						SELECT  TOP 1 1 FROM AccountCredence  A 
						INNER JOIN  btype bt ON a.atypeid=bt.typeId AND bt.IsUseBrandarType=1 AND a.typeatypeid in('33','27','39','35','59')
						INNER JOIN (
										SELECT F.nId 
										FROM Ac_Items  F 
										INNER JOIN Ac_Items P ON P.UserCode IN('987','2131','043') AND P.Sysrow=1 AND F.nTypeId LIKE P.nTypeId+'%' 
										) I ON A.BillNumberID=@nBillID AND I.nId=A.TypeATypeID AND ISNULL(A.BrandarTypeId,'')=''
						
					)
					BEGIN 
						ROLLBACK TRAN auditPoint
						COMMIT TRAN audit    		 
						RETURN 1120;
					END
		END 
	END	
	
	IF (@billtype=305 OR @billtype=215) AND EXISTS(SELECT TOP 1 1 FROM billindex WHERE NewPosBill=1 AND BillNumberId=@nBillID)
	BEGIN			
		if exists(select * from loginuser where etypeid=@chvOpID and sysid='1')
			SELECT @nRet=1
		ELSE
		BEGIN
			declare @right char(1) --零售单过账权限	
			select @right=substring(lim,4119,1) from loginuser where etypeid=@chvOpID 
			if @right='1' 
				SELECT @nRet = 1
			else
				SELECT @nRet = 0
		END
		IF @nRet<>1
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit 
			RETURN 1000 --没有单据过账的权限
		END
	END		
	ELSE
	begin		
		EXEC @nRet=Gp_Auditing_Control @chvSTypeID--判断版本信息+狗信息+是否开账信息
	END	
			
	SELECT @nRet = 0
	-- 创建明细
		
	IF 	@BillType NOT IN (203)
	BEGIN
		EXEC @nRet = GP_AuditingCheckBillData @nBillID,@BillType,'0'		
		IF @nRet <> 0 
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN @nRet
		END
	END
	
	--同价调拨单,变价调拨单过账前判断引用单据的状态
	IF @BillType IN (17,21)
	BEGIN
		IF EXISTS (SELECT 1 FROM PosAllotApplyBillIndex WHERE BillState IN(0,3,4,5) AND BillNumberId IN (
			SELECT FromBillNumberID FROM dbo.BillIndex WHERE BillNumberId=@nBillID 
			))
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN -499
		END 
	END
	
	IF @BillType IN (187,188,159,191,197,200,186,195,206,205,212,213,214,310,400,401,402,403,404,405,450)
	BEGIN
		EXEC @nRet=Gp_Auditing_Check @nBillID,@BillType
		
		--PRINT('11')
	END	

	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END

-- 开始事务
--BEGIN TRAN


IF @szCheck = 't'	-- return 0 --单据已经过帐
BEGIN
	SELECT @nRet = 77
	ROLLBACK TRAN auditPoint
	COMMIT TRAN audit
	RETURN @nRet
END

	
-- 销、采、采退、销退、收、付、同调、变调、零售单、会计凭证
-- 受托收货/结算/退货/调价、销售换货、采购换货、赠送单、获赠单
-- 报损/报溢单、成本调价单、商品拆装单、维修受理单
-- 委托发货/结算/退货/调价
-- 新维修相关单据

IF @BillType IN (34,4,66,11,12,45,46,402,189,190) --销售出库单  --TT 出库单本位币按结算单位取值 原本按结算单位和币种
BEGIN
	
	UPDATE BillIndex 
	SET ARTOTAL = C.ARTOTAL,APTOTAL = C.APTOTAL,YSTOTAL= C.YSTOTAL,YFTOTAL= C.YFTOTAL
	FROM 
	(
		SELECT ISNULL(SUM(b.ARTOTAL),0) AS ARTOTAL, ISNULL(SUM(b.APTOTAL),0) AS APTOTAL,
			   ISNULL(SUM(b.YSTOTAL),0) AS YSTOTAL, ISNULL(SUM(b.YFTOTAL),0) AS YFTOTAL
		FROM BType_ArApTotal B WHERE b.BTypeID=@chvBTypeID AND b.STypeID=@chvSTypeID
	) C
	WHERE BillIndex.Billnumberid=@nBillID
	
END

/******借欠转采购销售 begin******/
IF @BillType IN (11,12,34) AND @IfLend = 1
BEGIN
	EXEC @nRet = Gp_LendBuySaleCheck @nBillID, @BillType,@szPID OUTPUT
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	EXEC Gp_Auditing_LendBuySale @nBillID,@BillType
END
/******借欠转采购销售 end  ******/

IF @BillType IN (11,12,34,6,45,46,4,66,17,21,305,159,144,145,146,147,160,161,139,126,9,14,57,16,157,140,141,142,143,
	165,166,167,168,169,170,171,172,173,174,175,178,183,186,187,188,191,195,196,197,200,181,427,182,179,201,202,205,215,312,400,401,402,403,327,328,329)
BEGIN
	--产生 InOuStockTable 中明细
	EXEC @nRet = Gp_CreateMx_new	@nBillID,
									@BillType,
									@datBillDate,
									@chvATypeID,
									@chvBTypeID,
									@chvDealBTypeID,
									@chvETypeID,
									@chvKTypeID,
									@chvKTypeID2,
									@chvDTypeID,
									@chvSTypeID,
									@numTotalMoney ,
									@numTotalInMoney ,
									@numPreferenceMoney ,
									@numNPreferenceMoney ,
									@numNTotalMoney ,
									@numTax ,
									@ifIndexWX ,
									@intCostSale ,
									@intCID,
									@datPostTime

	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END
ELSE IF @BillType=206
BEGIN
	--销售出库单费用分摊
	UPDATE SaleBill
	SET ShareFee=ISNULL(SaleBill.ShareFee,0)+b.ShareFee
	From ShareSourceBill b
	WHERE b.BillNumberId=@nBillID
	AND SaleBill.ID=b.FromBillID
	AND FromBillType=11
	
	UPDATE PT_Combin_SaleBillDetail
	SET ShareFee=ISNULL(PT_Combin_SaleBillDetail.ShareFee,0)+b.ShareFee
	From ShareSourceBill b
	WHERE b.BillNumberId=@nBillID
	AND PT_Combin_SaleBillDetail.ID=b.FromBillID
	AND FromBillType=12
	
	--零售单费用分摊过账
	UPDATE dbo.retailBill
	SET ShareFee=ISNULL(retailBill.ShareFee,0)+b.ShareFee
	From ShareSourceBill b
	WHERE b.BillNumberId=@nBillID
	AND retailBill.ID=b.FromBillID
	AND FromBillType=305
	
	UPDATE InOutstocktable
	SET ShareFee=ISNULL(InOutStockTable.ShareFee,0)-b.ShareFee
	From ShareSourceBill b
	WHERE b.BillNumberId=@nBillID
	AND InOutstocktable.BillNumberId=b.FromBillNumberID
	AND InOutstocktable.ID=b.FromBillID
	
	UPDATE	BillIndex
	SET		IfCheck = 't',
			Checke = @szCheckman,
			Draft = 0,
			Poster=@chvOpID,
			PostTime=GETDATE()
	WHERE	BillNumberID = @nBillID
	COMMIT TRAN audit
	RETURN 0
END
ELSE IF @BillType=203
BEGIN
	UPDATE	SerialAdjustIndex
	SET		IfCheck = 't',
			Checke = @szCheckman,
			Draft = 0,
			Poster=@chvOpID,
			LastUpdateTime=GETDATE()
	WHERE	BillNumberID = @nBillID	
END

ELSE IF @BillType NOT IN (189,190,212,213,214,310,404,405,414,36,93,158,78,84,85,93,36 )
BEGIN
	-- 产生 ListTable 中应收应付，产生 InOuStockTable 中明细
	EXEC @nRet = Gp_CreateMx @nBillID
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

DECLARE
	@intMoneyDot	INT,
	@intPriceDot	INT
	
SELECT 
	@intMoneyDot=2,
	@intPriceDot=4
	
IF @BillType NOT IN(327,328,329)
BEGIN
	SELECT @intCostSale=CostSale
	FROM BillIndex
	WHERE BillNumberId=@nBillID
END

--受托代销收货单 按成本,回写各种价格
DECLARE  @strErrMsg1				VARCHAR(1000)			
IF @billtype=144 AND @intCostSale=1
BEGIN
  EXEC @nret=GP_Auditing_DealCostSaleCommission
													@nBillID,
													@BillType,
													@intCostSale,
													@intCID,
													@chvOpID,
													@datBillDate,
													@chvBTypeID,
													@chvETypeID,
													@chvDTypeID,
													@chvSTypeID,
													@nRet	OUT,
													@strErrMsg1 OUT

END
-------------- 核心过账 --------------------------
--SELECT 1,@nRet
--SELECT  * FROM listtable WHERE BillNumberId=10

--往来过账
IF @BillType IN(11,12,45,46,305,160,157,141,167,168,172,181,93,85,148,149,6,34,145,161,170,36,84,150,151,183,4,
66,189,190,6,161,145,151,158,77,93,85,212,213,214,215,312,450,410,414,78,327,328,329)
BEGIN
	EXEC @nRet = GP_AuditArAp	@nBillID,0,@BillType,@datBillDate,@chvATypeID,@chvBTypeID,@chvETypeID,@chvKTypeID,@chvKTypeID2,
								@chvDTypeID,@chvSTypeID,@numTotalMoney,@numTotalInMoney,@numPreferenceMoney,@numNTotalMoney,
								@numNTotalInMoney,@numNPreferenceMoney,@numTax,@ifIndexWX,@intCostSale,@IfMulAccount,@wxTotal,@intVipCardID,
								@intCID,@NumRate,@AuditType,@intNewPosBill,@szPID OUTPUT,@vipCentInfo output,@VipCardCode OUT
	
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

--处理品牌 往来过账
IF @BILLTYPE IN (305,215,11,45,160,140,142,141,12,46,36,93,405,189,116,115,4,159)
BEGIN
	EXEC @nRet = GP_AuditBrandarArAp @nBillID,@BillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END
	
DECLARE
		@intReturnID			BIGINT,
		@strErrMsg				VARCHAR(1000)	


--固定资产增加单、固定资产减少单、固定资产折旧单(新)
IF @billtype IN (212,213,214)
BEGIN
	--处理固定资产
	EXEC Gp_Auditing_DealAssest
								@nBillID,
								@chvOpID,
								@billtype,
								@intRedWord,
								@datBillDate,
								@AssetBusinessTypeId,
								@chvSTypeID,
								@nRet OUT,
								@AssetMsg OUT
	
	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

--数据检查
IF @BillType NOT IN (203,310,404,405)
BEGIN
	-- 检查账户余额，是否过账后会 < 0
	EXEC @nRet = GP_AuditingATypeBalanceCheck @nBillID,@BillType, @szPID OUTPUT
	
	--PRINT('33')
	
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END
--SELECT 2,@nRet

--库存过账
--IF @BillType NOT IN (189,190,203)
IF @BillType NOT IN (203,310)
BEGIN
	IF EXISTS(
		SELECT * FROM tempdb.sys.objects WHERE object_id = OBJECT_ID(N'tempdb..[#AuditReturnReSult]') AND type in (N'U')
	)
	BEGIN
		
		IF @BillType IN (11,12,305,17,21,187,140)
		BEGIN
			--创建一个临时表来比较库存不足的情形
			CREATE TABLE #AuditGetResult(
				PTypeID VARCHAR(50),
				KTypeID VARCHAR(50),
				BillQty  NUMERIC(24, 10) ,
				Qty  NUMERIC(24, 10) 
			)

			--先生成库存不足的信息
			EXEC GP_GetMsg_StockLack
									@nRet,
									@BillType,
									@nBillID
				
		END	
	END
	
	--核心过账，继创建明细之后的成本数据变化
	EXEC @nRet = Gp_AuditingCore	@nBillID, 
									@szCheckMan, 
									@chvOpID,
									@BillType,
									@datBillDate,
									@chvATypeID,
									@chvBTypeID,
									@chvETypeID,
									@chvKTypeID,
									@chvKTypeID2,
									@chvSTypeID,
									@numTotalMoney,
									@numTotalInMoney,
									@ifCheck,
									@szPID OUTPUT, 
									@KTypeID OUTPUT

	--SELECT 7,@nRet
	
	IF EXISTS(
		SELECT * FROM tempdb.sys.objects WHERE object_id = OBJECT_ID(N'tempdb..[#AuditReturnReSult]') AND type in (N'U')
	)
	BEGIN
		IF @nRet IN (-1) AND @BillType IN (11,12,305,17,21,187,140)
		BEGIN
		
			EXEC GP_ReturnMsg_StockLack
										@nRet,
										@BillType,
										@nBillID
				
			
			DROP TABLE #AuditGetResult	
		END
	END
			
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

--SELECT 3,@nRet

--分支机构调拨出库单、分支机构调拨入库单 处理财务数据
IF @BillType IN (187,188)
BEGIN
	EXEC @nRet = GP_Auditing_AType @nBillID,@BillType,@chvOpID,@datBillDate,@chvDealBTypeID,@chvDTypeID,@chvSTypeID,@intCID

	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END
	
--如果是基础版，就不处理序列号了(166=维修单)	
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'Edition' AND SubValue = 1)
BEGIN
	IF @Billtype IN (414,11,12,34,6,45,46,17,21,305,144,145,146,147,160,161,139,126,9,14,16,157,140,141,142,143,
	165,166,167,168,169,170,171,172,173,174,175,178,183,186,187,188,191,195,196,197,200,182,179,201,202,203,215,57,400,401,402,403,417,328,327,329)
	BEGIN
		DECLARE 
			@SQL NVARCHAR(MAX),
			@intDealSerial	TINYINT
			
		SET @SQL='IF EXISTS(SELECT BillNumberID FROM '+@BillName+' WHERE BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND CAST(Serial AS VARCHAR(MAX))<>'''') SET @intDealSerial=1 ELSE SET @intDealSerial=0'
		EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT		
		
		IF @intDealSerial=0 AND @billtype=166
		BEGIN
			SET @SQL='IF EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND CAST(Serial AS VARCHAR(MAX))<>'''') SET @intDealSerial=1 ELSE SET @intDealSerial=0'
			EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
		END		
		
		IF @intDealSerial=0
		BEGIN
			SET @SQL='IF EXISTS(SELECT a.BillNumberID FROM '+@BillName+' a 
			INNER JOIN PType b ON a.PTypeID=b.TypeID
			WHERE a.BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND b.IfSerial=1) SET @intDealSerial=1 ELSE SET @intDealSerial=0'
			EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
		END		
		
		IF @intDealSerial=0 AND @billtype=166
		BEGIN
			SET @SQL='IF EXISTS(SELECT a.BillNumberID FROM BillIndex a 
			INNER JOIN PType b ON a.PTypeID=b.TypeID
			WHERE a.BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND b.IfSerial=1) SET @intDealSerial=1 ELSE SET @intDealSerial=0'
			EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
		END 		

		IF @intDealSerial=1
		BEGIN
			EXEC @nRet = Gp_SerialOperate_Manager @nBillID,@szCheckMan,@chvOpID,
			@szCheck,@ifIndexWX,@chvBTypeID,@chvSTypeID,@szPID OUTPUT,@Billtype
			
			IF @nRet IN (-904,-907)
			BEGIN
				EXEC GP_Auditing_ReturnMsg
					@nRet,
					@BillType,
					@nBillID
			END

			IF @nRet <> 0
			BEGIN
				ROLLBACK TRAN auditPoint
				COMMIT TRAN audit
				RETURN @nRet
			END
		END
	END
END
	
--PRINT('22')

/*
处理自动生单
采购退货单
销售出库单
付款单
分支机构调拨出库单
优惠券分支机构调拨出库单

*/
IF @BillType IN (187,66,11,6)
BEGIN
	EXEC	@nRet=GP_Auditing_CreateBill
											@nBillID,
											@chvOpID,
											@BillType,
											@chvBTypeID,
											@chvSTypeID,
											@intCostSale,
											@intCID,
											@SZPID	OUT,
											@intReturnID	OUT,
											@strReturnBillCode	OUT,
											@strErrMsg	OUT
	
	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END	

--受托代销收货单 按成本
--IF @billtype=144 AND @intCostSale=1
--BEGIN
--	EXEC @nret=GP_Auditing_DealCostSaleCommission
--													@nBillID,
--													@BillType,
--													@intCostSale,
--													@intCID,
--													@chvOpID,
--													@datBillDate,
--													@chvBTypeID,
--													@chvETypeID,
--													@chvDTypeID,
--													@chvSTypeID,
--													@nRet	OUT,
--													@strErrMsg OUT

--END
	
--非物流单据，处理货位，批号，自由项等
IF @BillType NOT IN (71,72,87,88,404,405,450,84,85,78,212,213,214,307,310,312,203,116,115,128,129,4,189,66,190,148,150,149,151,162,163,36,158,77,93,5,10,159,205,206,181,311,414)
BEGIN 
	EXEC GP_Auditing_DealQty
	@nBillID,
	@BillType,
	0,
	@chvDealBTypeID,
	@chvBTypeID,
	@chvSTypeID,
	@szPID	OUT,
	@nRet	OUT
	
	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

-- 过账最后处理草稿库存
EXEC GP_AuditingORDel_DraftQTY @nBillID,@BillType

/*
过账最后处理订单库存
销售出库单
组合品销售出库单
采购入库单
委托代销发货单
受托代销收货单
暂估入库单
发出商品出库单
*/
IF @BillType IN (11,12,34,144,140,400,402)
BEGIN
	--先减去引用未过账数量,再加上过账数量
	EXEC GP_Deal_OrderReferQty @nBillID,@BillType,'-'
	
	EXEC GP_Deal_OrderReachQTY @nBillID,@BillType,'+'
END
	
-- 过账最后，对单据数据完整性进行检测
IF @BillType NOT IN (203,310,328,327,329)
BEGIN
	EXEC @nRet = GP_AuditingCheck @nBillID,@BillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

--SELECT 4,@nRet

-- 检测销售、采购单关联订单的完成状态
IF @BillType NOT IN (203,310,404,405,328,327,329)
BEGIN
	EXEC @nRet = GP_AuditingCheckOrderState @nBillID,1
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

--检测同价调拨单,变价调拨单,分支机构调拨单 关联的申请单的完成状态 991新增门店配送单调用申请单改状态
IF @BillType IN (187,17,21,327,328,329)
BEGIN
	EXEC @nRet = GP_AuditingCheckMoveBillState @nBillID,@BillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

--根据实际过账，更新成本调价单的数量（以前是在保存时，由页面写入的数量）
EXEC Gp_Auditing_Fill @nBillID,@BillType

--采购费用分摊处理
IF @billtype=205
BEGIN
	--采购费用分摊处理
	EXEC Gp_BuyShareFee_Deal @nBillID,@billtype,@nRet OUT,@szPID OUT
	
	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

--会员储值充值单
IF @billtype=181
BEGIN
	IF EXISTS(
			SELECT a.BillNumberId FROM BillIndex a
			INNER JOIN nVipCardSign b
			ON a.VipCardID=b.VipCardID
			WHERE BillNumberId=@nBillID AND b.cZyeMoney<0
		)
	BEGIN
		SELECT @nRet=-333    --该会员储值充值单过账后会导致充值余额为负,不能过账
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END

--会员批量储值充值单
IF @billtype=312
BEGIN
	IF EXISTS(
			SELECT a.BillNumberId FROM VipAddMoneyBatchBill a
			INNER JOIN nVipCardSign b
			ON a.VipCardID=b.VipCardID
			WHERE BillNumberId=@nBillID AND b.cZyeMoney<0
		)
	BEGIN
		SELECT @nRet=-333    --该会员批量储值充值单过账后会导致充值余额为负,不能过账
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	
	DECLARE
			@offset_check INT,
			@re_check INT  --0表示选中，允许
									
	SELECT @offset_check = 4513		--会员管理-其他-允许充值金额为负数
	
	EXEC @re_check=GP_CheckLimit @chvOPID,@offset_check	

	--9.7 调整权限不允许充值金额为负数->允许充值金额为负数
	IF @re_check<>0  --不允许充值金额为负
	BEGIN
		IF EXISTS(
			SELECT BillNumberId
			FROM VipAddMoneyBatchBill
			WHERE BillNumberId=@nBillID AND ChargeMoney<0
		)
		BEGIN
			ROLLBACK TRAN auditPoint
			COMMIT TRAN audit
			RETURN 705  --充值金额不允许为负
		END
	END
	
	--保证充值前金额+充值金额=充值后金额
	UPDATE	VipAddMoneyBatchBill
	SET		AfterChargeMoney=b.cZyeMoney,
			BeforeChargeMoney=b.cZyeMoney-VipAddMoneyBatchBill.ChargeMoney
	FROM	nVipCardSign b
	WHERE	VipAddMoneyBatchBill.BillNumberId=@nBillID
			AND b.VipCardID=VipAddMoneyBatchBill.VipCardId
			AND b.cZyeMoney<>VipAddMoneyBatchBill.AfterChargeMoney	
END

/*
暂估入库单
暂估退货单
发出商品出库单
发出商品退货单
采购暂估开票
销售发货开票
*/
IF @billtype IN (400,401,402,403,404,405)
BEGIN

	EXEC @nRet=Gp_CheckLimitBillType @chvOpID,0,@billtype
	IF @nRet<>1 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN 1000 --没有单据过账的权限
	END
	SELECT @nRet = 0
	
	IF @billtype IN (404,405)
	BEGIN
		IF @billtype=404
		BEGIN
			--生成成本调价单
			EXEC	GP_ReceiptBill_CreateBill
					@chvOpID,
					@nBillID,
					@intReturnID OUT,		--新生成的单据的ID
					@strReturnBillCode OUT,
					@voucherMsg OUT		--出错信息
		END
		--处理发票状态
	
		EXEC GP_Receipt_Deal @nBillID,0
		

		
		UPDATE ReceiptBillIndex
		SET ifcheck='t',draft=0,posttime=GETDATE(),Poster=@chvOpID
		WHERE BillNumberId=@nBillID
	END
	ELSE IF @billtype =400
	BEGIN
		IF EXISTS(
			SELECT ConfigName
			FROM Userconfig
			WHERE ConfigName='appraisalbillautogenerationreceiptbill' AND Value='1'
		)
		BEGIN
			EXEC GP_AppraisalBill_CreateReciptBill
				@chvOpID,
				@nBillID,
				@intReturnID,		--新生成的单据的ID
				@strReturnBillCode OUT,
				@strErrMsg 		--出错信息
		END

	END
	ELSE IF @billtype =401
	BEGIN
		IF EXISTS(
			SELECT ConfigName
			FROM Userconfig
			WHERE ConfigName='appraisalbillautogenerationreceiptbill' AND Value='1'
		)
		BEGIN
			EXEC GP_AppraisalBackBill_CreateReciptBill
				@chvOpID,
				@nBillID,
				@intReturnID,		--新生成的单据的ID
				@strReturnBillCode OUT,
				@strErrMsg 		--出错信息
		END
	END
	ELSE IF @billtype =402
	BEGIN
		IF EXISTS(
			SELECT ConfigName
			FROM Userconfig
			WHERE ConfigName='sendbillautogenerationreceiptbill' AND Value='1'
		)
		BEGIN
			EXEC GP_SendBill_CreateReciptBill
				@chvOpID,
				@nBillID,
				@intReturnID,		--新生成的单据的ID
				@strReturnBillCode OUT,
				@strErrMsg 		--出错信息
		END
	END
	ELSE IF @billtype =403
	BEGIN
		IF EXISTS(
			SELECT ConfigName
			FROM Userconfig
			WHERE ConfigName='sendbillautogenerationreceiptbill' AND Value='1'
		)
		BEGIN
			EXEC GP_SendBackBill_CreateReciptBill
				@chvOpID,
				@nBillID,
				@intReturnID,		--新生成的单据的ID
				@strReturnBillCode OUT,
				@strErrMsg 		--出错信息
		END
	END
END
	
--SELECT 6,@nRet

--序列号调整单、资金调拨单 这两种单据不检查
IF @BillType NOT IN (203,310,328,327,329)
BEGIN
	EXEC @nRet = GP_AuditingCheckBillData @nBillID,@BillType,'1'
	IF @nRet <> 0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END



--资金调拨单修改过账状态
----资金调拨单生成日记账
IF @BillType = 310
BEGIN
	UPDATE	BillIndex
	SET		ifcheck='t',
			draft=0,
			posttime=GETDATE(),
			Poster=@chvOpID
	WHERE BillNumberId=@nBillID

	--EXEC @nRet =  Gp_CapitalTransferBillToJournal @nBillID,@chvOpID,@szPID
	--IF @nRet <> 0 RETURN @nRet
END
	
DECLARE	@strTempPuserCode	VARCHAR(200)

--受托代销收货单、受托代销结算单、受托代销退货单、受托代销调价单
IF @billtype IN (144,145,146,147) AND @CommissionConfirm=0
BEGIN
	IF EXISTS(
		SELECT a.Ptypeid
		FROM CommissionStock a
		INNER JOIN 
		(
			SELECT b.*,c.Btypeid
			FROM CommissionBill b
			INNER JOIN BillIndex c
			ON b.BillNumberId=c.BillNumberId
			WHERE c.BillNumberId=@nBillID
		) b
		ON a.Ptypeid=b.PtypeId AND a.Btypeid=b.btypeid AND a.Stypeid=b.Stypeid
		WHERE a.Type=144 AND a.Qty=0 AND a.Total<>0
		
	)
	BEGIN		
		SELECT @strTempPuserCode= d.UserCode
		FROM 
		(
			SELECT TOP 1 a.PTypeID
			FROM CommissionStock a
			INNER JOIN 
			(
				SELECT b.*,c.Btypeid
				FROM CommissionBill b
				INNER JOIN BillIndex c
				ON b.BillNumberId=c.BillNumberId
				WHERE c.BillNumberId=@nBillID
			) b
			ON a.Ptypeid=b.PtypeId AND a.Btypeid=b.btypeid AND a.Stypeid=b.Stypeid
			WHERE a.Type=144 AND a.Qty=0 AND a.Total<>0
		) a
		INNER JOIN PType d
		ON a.Ptypeid=d.typeId
		
		SET @szPID='【'+@strTempPuserCode+'】过账后会出现代销库存数量为零，金额不为零的情况！'
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN -1234
		
	END

END

	
--委托代销发货单、委托代销结算单、委托代销退货单、委托代销调价单	
IF @billtype IN (140,141,142,143) AND @CommissionConfirm=0
BEGIN
	IF EXISTS(
		SELECT a.Ptypeid
		FROM CommissionStock a
		INNER JOIN 
		(
			SELECT b.*,c.Btypeid
			FROM CommissionBill b
			INNER JOIN BillIndex c
			ON b.BillNumberId=c.BillNumberId
			WHERE c.BillNumberId=@nBillID
		) b
		ON a.Ptypeid=b.PtypeId AND a.Btypeid=b.btypeid AND a.Stypeid=b.Stypeid
		WHERE a.Type=140 AND a.Qty=0 AND a.Total<>0
		
	)
	BEGIN
		
		SELECT @strTempPuserCode= d.UserCode
		FROM 
		(
			SELECT TOP 1 a.PTypeID
			FROM CommissionStock a
			INNER JOIN 
			(
				SELECT b.*,c.Btypeid
				FROM CommissionBill b
				INNER JOIN BillIndex c
				ON b.BillNumberId=c.BillNumberId
				WHERE c.BillNumberId=@nBillID
			) b
			ON a.Ptypeid=b.PtypeId AND a.Btypeid=b.btypeid AND a.Stypeid=b.Stypeid
			WHERE a.Type=140 AND a.Qty=0 AND a.Total<>0
		) a
		INNER JOIN PType d
		ON a.Ptypeid=d.typeId
		SET @szPID='【'+@strTempPuserCode+'】过账后会出现代销库存数量为零，金额不为零的情况！'
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN -1234
		
	END
END
	
--回写往来单位的几个日期
IF @BillType IN (34,144,400)
BEGIN
	--采购入库日
	UPDATE	dbo.btype
	SET		ltbuyinsday=@datBillDate
	WHERE	Typeid=@chvDealBTypeID
END
ELSE IF @BillType IN (6,146,401)
BEGIN
	--采购退货日
	UPDATE	dbo.btype
	SET		ltbuyrtday=@datBillDate
	WHERE	Typeid=@chvDealBTypeID
END
ELSE IF @BillType IN (11,140,305,402,12)
BEGIN
	--销售出库日
	UPDATE	dbo.btype
	SET		ltsaleoutsday=@datBillDate
	WHERE	Typeid=@chvDealBTypeID
END
ELSE IF @BillType IN (45,142,215,403,46)
BEGIN
	--销售退货日
	UPDATE	dbo.btype
	SET		ltsalertday=@datBillDate
	WHERE	Typeid=@chvDealBTypeID
END
	
--处理券编码信息
IF @BillType IN (305,215,11,45,12,46)
BEGIN
	IF EXISTS (SELECT  TOP 1 1 FROM  dbo.Coupon_BillUsed WHERE BillnumberId=@nBillID)
	BEGIN
		--Coupon_CodeInfo
		UPDATE	c 
		SET		[State]=CASE WHEN @BillType IN(305,11,12,327) THEN 3 --已消费
							 WHEN @BillType IN (215,45,46,328,329) THEN  5--消费退货
						END 
		FROM Coupon_CodeInfo c ,
			 Coupon_BillUsed b
		WHERE c.CouponCode=b.CouponCode AND b.BillnumberId=@nBillID AND b.PosId=0
		
	END  
END

--门店验收过账生成未完成验收数量的门店退货单草稿,单独写在最后,是因为要写到验收过账反写数量checkqrt之后
IF @BillType IN (329)
BEGIN
	EXEC	@nRet=GP_Auditing_CreateBill
											@nBillID,
											@chvOpID,
											@BillType,
											@chvBTypeID,
											@chvSTypeID,
											@intCostSale,
											@intCID,
											@SZPID	OUT,
											@intReturnID	OUT,
											@strReturnBillCode	OUT,
											@strErrMsg	OUT
	
	IF @nRet<>0 
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
END	
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
	AND	EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'postingparameter' AND SubValue = 0)--即时过账，即时生成凭证
	AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'aloneusebsys' AND SubValue = 0)--使用总账系统
	AND @BillType NOT IN (203)--排除序列号调整单
	AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id=object_id('V1ZTINFO') AND TYPe='U')
BEGIN
	DECLARE @atid INT	
	
	IF @BillType IN (404,405)
	BEGIN
		SELECT @atid = atid FROM dbo.ReceiptBillIndex WHERE BillNumberId = @nBillID
	END
	ELSE IF @BillType IN (327,328,329)
	BEGIN
		SELECT @atid = atid FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId = @nBillID
	END
	ELSE
	BEGIN
		SELECT @atid = atid FROM dbo.BillIndex WHERE BillNumberId = @nBillID
	END
	--运输单没有勾选产生运费
	IF @BillType=414 AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@nBillID AND IsFreightMoney=1)
	BEGIN
		COMMIT TRAN audit
		RETURN @nRet
	END
	--IF @BillType NOT IN(327,328,329)
		EXEC @nRet = dbo.Gp_AutoCreate_Voucher @nBillID,@chvOpID,@atid,'',@voucherMsg OUTPUT,@BillType
	
	IF @nRet <> 0 
	BEGIN
		COMMIT TRAN audit
		RETURN @nRet
	END
END
ELSE
	SET @voucherMsg = ''

COMMIT TRAN audit
RETURN @nRet
	

	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
/*



DECLARE
	@nBillID				NUMERIC(10,0),				-- 单据 ID 号
	@szCheckMan				VARCHAR(50),				-- 制单人 ID 值
	@szPID					VARCHAR(1000),				-- 返回出错商品 ID 值
	@chvOpID				VARCHAR(50) = '',			-- 当前操作员 ID 值
	@KTypeID				VARCHAR(50) = '' ,			-- 返回仓库ID值，针对多仓库应用
	@billtype				INT = 0,
	@nRet					INT,
	@voucherMsg				VARCHAR(50)	= '',			--返回凭证生成的信息
	@VipCentInfo			VARCHAR(200) = '' ,			--返回会员卡积分调整信息
	@AssetMsg				VARCHAR(MAX)='' 		

SELECT
	@nBillID=14,
	@szCheckMan='00001',
	@chvOpID='00001',
	@billtype=160
	

BEGIN TRAN



EXEC
	@nRet=
	Gp_Auditing
	@nBillID,
	@szCheckMan,
	@szPID OUT,
	@chvOpID,
	@KTypeID OUT,
	@billtype,
	@voucherMsg OUT,
	@VipCentInfo	OUT,
	@AssetMsg	OUT

SELECT @nRet,@szPID,@KTypeID,@voucherMsg,@VipCentInfo,@AssetMsg


--COMMIT TRAN


ROLLBACK TRAN




*/












if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Auditing_AType]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_Auditing_AType]
GO



/*

功能说明：      	过账影响财务数据的主过程

作    者：       冯波

创建日期：       2004-6-10

返回结果：       

*/

CREATE PROCEDURE [GP_Auditing_AType]
(
	@nBillID			NUMERIC(10,0),			--单据
	@intBillType		INT,
	@chvOpID			varchar(50) = '',
	@datBillDate		DATETIME,
	@chvBTypeID			VARCHAR(50),
	@chvDTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@CID				INT
)
--@encode$--        
AS

/*
DECLARE
	@strPreGathering	VARCHAR(100),
	@strPrePay			VARCHAR(100),
	@strInnerAR			VARCHAR(100)
	
SELECT
	@strPreGathering='0000200006',
	@strPrePay='0000100009',
	@strInnerAR='0000100010'
*/
DECLARE 
	@nRet				INT,
	@strMsg				VARCHAR(200)
	

SELECT 
	@nRet=0,
	@strMsg=''

/*
IF @intBillType=189
BEGIN
	 --EXEC @nRet =  GP_AType_PreGathering @nBillID,@chvOpID
	 EXEC @nRet =  GP_AType_PreGathering nBillID,@intBillType,@datBillDate,@chvBTypeID,chvOpID,@chvDTypeID,@chvSTypeID,@CID,@strMsg OUTPUT
END
ELSE IF @intBillType=190
BEGIN
	--EXEC GP_AType_PrePay @nBillID,@chvOpID
	EXEC GP_AType_PrePay @nBillID,@intBillType,@datBillDate,@chvBTypeID,chvOpID,@chvDTypeID,@chvSTypeID,@CID,@strMsg OUTPUT
END
ELSE */IF @intBillType=187
BEGIN
	EXEC GP_AType_STypeMoveOutBill @nBillID,@chvOpID
END
ELSE IF @intBillType=188
BEGIN
	EXEC GP_AType_STypeMoveInBill @nBillID,@chvOpID
END
IF @nRet<>0
	RETURN @nRet

UPDATE Listtable
SET Audited=1
WHERE BillNumberId=@nBillID



GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理受托收货可以按照成本价收货入库	
*/
CREATE          PROCEDURE GP_Auditing_BatchPassCostPrice
(
	@nBillID				NUMERIC(10,0),
	@billType				INT
	
)
--@encode$--
AS
		DECLARE	@AVERAGE	smallint,
				@FIFO		smallint,
				@LIFO		smallint,
				@HAND		smallint

		SET @AVERAGE	= 0		-- 移动加权平均算法
		SET @FIFO		= 1		-- 先进先出
		SET @LIFO		= 2		-- 后进先出
		SET @HAND		= 3		-- 手工指定法
		
		DECLARE	@nCostingMethod	INT
		
		EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
		
		DECLARE
		@strQtyDot			VARCHAR(10),
		@strPriceDot		VARCHAR(10),
		@strMoneyDot		VARCHAR(10),
		@strDiscountDot		VARCHAR(10),
		@strTaxDot			VARCHAR(10),
		@strCRateDot		VARCHAR(10),	
		@strTRateDot		VARCHAR(10)
		
		EXEC	GP_Post_Dot
			@strQtyDot	OUT,
			@strPriceDot	OUT,
			@strMoneyDot	OUT,
			@strDiscountDot	OUT,
			@strTaxDot	OUT,
			@strCRateDot OUT,
			@strTRateDot	OUT

		DECLARE
	@datBillDate			DATETIME,					-- 单据日期
	@chvATypeID				VARCHAR(50),				-- 收付款账户 ID 值
	@chvBTypeID				VARCHAR(50),				--结算单位
	@chvDealBTypeID			VARCHAR(50),				--往来单位
	@chvETypeID				VARCHAR(50),				-- 经手人 ID 值
	@chvKTypeID				VARCHAR(50),				-- 出库仓库 ID 值
	@chvKTypeID2			VARCHAR(50),				-- 入库仓库 ID 值
	@chvDTypeID				VARCHAR(50),				--部门
	@numTotalMoney			 NUMERIC(24, 10) ,				-- 单据金额合计
	@numTotalInMoney		 NUMERIC(24, 10) ,				-- 单据实收、实付金额
	@numPreferenceMoney		 NUMERIC(24, 10) ,
	@numNTotalMoney			 NUMERIC(24, 10) ,
	@numNTotalInMoney		 NUMERIC(24, 10) ,
	@numNPreferenceMoney	 NUMERIC(24, 10) ,
	@wxTotal				 NUMERIC(24, 10) ,	
	@numTax					 NUMERIC(24, 10) ,
	@ifIndexWX				TINYINT,
	@intCostSale			TINYINT,
	@intCID					INT,
	@ifCheck				VARCHAR(10),				-- 是否草稿标识，f - 草稿；t - 已过账
	@IfMulAccount			TINYINT,
	@intVipCardID			INT,
	@BillName				VARCHAR(100),
	@NumRate				 NUMERIC(24, 10) ,
	@AssetBusinessTypeId    INT,
	@intRedWord				TINYINT,
	@intNewPosBill			TINYINT,
	@AuditType				INT,
	@IfLend					INT=0,
	@datPostTime			DATETIME ,
   @chvSTypeID				VARCHAR(50),
   @nRet    int

	--获取主表的相关信息
	EXEC	GP_GetBillIndexInfo @nBillID,
								@billType,
								@datBillDate	OUT,
								@chvATypeID	OUT,				-- 收付款账户 ID 值
								@chvBTypeID	OUT,				--结算单位
								@chvDealBTypeID	OUT,				--往来单位
								@chvETypeID	OUT,				-- 经手人 ID 值
								@chvKTypeID	OUT,				-- 出库仓库 ID 值
								@chvKTypeID2	OUT,				-- 入库仓库 ID 值
								@chvDTypeID	OUT,				--部门
								@chvSTypeID	OUT,				--分支机构
								@numTotalMoney	OUT,				-- 单据金额合计
								@numTotalInMoney	OUT,				-- 单据实收、实付金额
								@numPreferenceMoney	OUT,
								@numNTotalMoney	OUT,
								@numNTotalInMoney	OUT,
								@numNPreferenceMoney	OUT,
								@wxTotal	OUT,	
								@numTax	OUT,
								@ifIndexWX	OUT,
								@intCostSale	OUT,
								@intCID	OUT,
								@ifCheck	OUT,				-- 是否草稿标识，f - 草稿；t - 已过账
								@IfMulAccount	OUT,
								@intVipCardID	OUT,
								@NumRate		OUT,
								@AssetBusinessTypeId OUT,
								@intRedWord			OUT,
								@intNewPosBill	OUT,
								@IfLend			OUT,
								@datPostTime	OUT


			DECLARE 
				@strTemp	VARCHAR(MAX),
				@strOPRate	VARCHAR(50),
				@sysCid		INT,
				@decRate	NUMERIC(24,10)
				
			SELECT TOP 1 @SysCid=CId FROM Ac_Currency WHERE Sysrow = 1
			
			SELECT @strOPRate=BasisType,@decRate=Rate
			FROM Ac_Currency				
			WHERE CId=@intCID
			
			DECLARE
				@GOODS_ID			VARCHAR(50),
				@DXGOODSMONEY_ID	VARCHAR(50)
				
			SELECT @GOODS_ID=NID FROM ac_items WHERE UserCode='1241'  -- 『库存商品总值合计』,0000100001
			SELECT @DXGOODSMONEY_ID=NID FROM ac_items WHERE UserCode='2141'  -- 『代销商品款』,0000200003				
			
			IF @strOPRate='0'
			BEGIN
				SELECT @strOPRate='/'
			END
			ELSE
			BEGIN
				SELECT @strOPRate='*'
			END
			
			
			
			SELECT @strTemp='
			UPDATE DeliveryBill
			SET 
				Price=ABS(ROUND(CAST(ROUND(b.CostTotal,'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+')),
				Total=ABS(b.CostTotal),								
				GoodsCostPrice=ABS(ROUND(CAST(ROUND(b.CostTotal,'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+')),
				GoodsCostTotal=ABS(b.CostTotal)
			FROM 
			(
				SELECT a.ID,SUM(a.Qty) AS Qty,SUM(a.CostTotal) AS CostTotal
				FROM InOutStockTable a
				INNER JOIN PosAllotApplyBillIndex b
				ON a.BillNumberId=b.BillNumberId
				WHERE a.BillNumberID='+CAST(@nBillID AS VARCHAR(50)) +'				
				GROUP BY a.ID
			) b
			WHERE DeliveryBill.ID=b.ID  AND DeliveryBill.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			
			


			
			
			UPDATE DeliveryBill
			SET MPrice=ROUND(Price*MUnitRate,'+@strPriceDot+')
			
			WHERE BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			
			
			

			UPDATE PosAllotApplyBillIndex
			SET Total=ROUND(ISNULL(b.Total,0),'+@strMoneyDot+')
			FROM 
			(
				SELECT BillNumberID,SUM(Total) AS Total
				FROM DeliveryBill 
				WHERE BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
				GROUP BY BillNumberID
			) b
			WHERE PosAllotApplyBillIndex.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+' AND PosAllotApplyBillIndex.BillNumberID=b.BillNumberID


			UPDATE InOutStockTable
			SET Price=b.GoodsCostPrice,SalePrice=b.GoodsCostPrice,TaxPrice=b.GoodsCostPrice,
			Total=-b.GoodsCostTotal,SaleTotal=-b.GoodsCostTotal,TaxTotal=-b.GoodsCostTotal,
			NPrice=b.GoodsCostPrice,NTotal=-b.GoodsCostTotal,NSalePrice=b.GoodsCostPrice,NSaleTotal=-b.GoodsCostTotal,NTaxPrice=b.GoodsCostPrice,NTaxTotal=-b.GoodsCostTotal	
			FROM DeliveryBill b
			WHERE InOutStockTable.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND InOutStockTable.BillNumberID=b.BillNumberId
			AND InOutStockTable.ID=b.ID
			AND InOutStockTable.IsService=0
			
			'
			
			--PRINT @strTemp
			
	
			EXEC(@strTemp)		
			
			DECLARE
				@numNoTaxTotal	NUMERIC(24,10)
			
	
			--需要写入库存商品总值
			-- ********* 处理生成 ListTable 凭证记录 *********
			SELECT	@numNoTaxTotal = ISNULL(SUM(Total),0)--,@numNNoTaxTotal = ISNULL(SUM(NTotal),0)
			FROM	InOutstocktable
			WHERE	BillNumberID = @nBillID 

			IF @numNoTaxTotal <> 0 
			BEGIN
				-- 库存商品总值
				EXEC @nRet = GP_CreateMX_InsertList @nBillID,@datBillDate,@BillType,@GOODS_ID,@chvBTypeID,@chvETypeID,
					@numNoTaxTotal,'','',@chvDTypeID,@chvSTypeID,@sysCid,@numNoTaxTotal,1

			
			END
			
			IF @nRet <> 0
			BEGIN
				--ROLLBACK TRAN
				RETURN @nRet
			END


		
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





--单据过账验证
IF  EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_Auditing_BillInfo',N'P'))
	BEGIN
		DROP PROC GP_Auditing_BillInfo
	END
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--=================================
--by:glj
--date:2018-05-24
--description:单据过账985新增判断验证  985新增return 直接985开头
--=================================
CREATE PROC GP_Auditing_BillInfo
(
	@BillNumberID	INT,
	@BillType		INT
)
AS
SET NOCOUNT ON

DECLARE
	@nRet INT=0

--零售单
IF @BillType=305 
BEGIN
	--收现不足
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId=@BillNumberID AND NTotalMoney<>(NPreferenceMoney+NTotalInMoney))
		RETURN 98502
	--账户为空
	IF NOT EXISTS(SELECT TOP 1 1 FROM BillMulAccount WHERE BillNumberId=@BillNumberID AND BillType=@BillType) AND EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId=@BillNumberID AND NTotalInMoney<>0)
		RETURN 98501
END
--================================会员卡相关信息判断===================================================
--收款单
IF(@BillType=4)
BEGIN
	IF EXISTS(SELECT TOP 1 1 
				FROM dbo.BillIndex I 
				INNER JOIN dbo.gatheringBill B ON I.BillNumberId=@BillNumberID AND I.BillNumberId=B.BillNumberId
				INNER JOIN dbo.nVipCardSign C ON  C.VipCardID=B.VipCardID AND (C.deleted<>0 OR C.EndDate<I.BillDate OR NOT EXISTS(SELECT TOP 1 1 FROM nVipCardSet WHERE VipCardTypeID=C.VipCardTypeID AND deleted=0)))
		RETURN 701
		
	IF EXISTS(SELECT TOP 1 1 
				FROM dbo.gatheringBill B
				INNER JOIN dbo.nVipCardSign C ON B.BillNumberId=@BillNumberID AND C.VipCardID=B.VipCardID AND C.isApplyAllStype=0 AND NOT EXISTS(SELECT * FROM VipCard_ApplyStype WHERE StypeId=B.Stypeid AND VipCardID=C.VipCardID))
		RETURN 706
END

--会员批量储值充值单
IF(@BillType=312)
BEGIN
	IF EXISTS(SELECT TOP 1 1 
				FROM dbo.VipAddMoneyBatchBill BB
				INNER JOIN dbo.BillIndex B ON BB.BillNumberId=@BillNumberID AND B.BillType=@BillType AND B.BillNumberId=BB.BillNumberId
				INNER JOIN dbo.nVipCardSign C ON BB.BillNumberId=@BillNumberID AND C.VipCardID=BB.VipCardID AND C.isApplyAllStype=0 AND NOT EXISTS(SELECT * FROM VipCard_ApplyStype WHERE StypeId=B.Stypeid AND VipCardID=C.VipCardID))
		RETURN 706

END

IF(@BillType IN(300,11,12,313,167,168,172,183,181,312,305,215,45,46,427))
BEGIN
	--表头
	IF EXISTS(SELECT TOP 1 1 
				FROM dbo.BillIndex B
				INNER JOIN dbo.nVipCardSign C ON B.BillNumberId=@BillNumberID AND C.VipCardID=B.VipCardID AND (C.deleted<>0 OR C.EndDate<B.BillDate OR NOT EXISTS(SELECT TOP 1 1 FROM nVipCardSet WHERE VipCardTypeID=C.VipCardTypeID AND deleted=0)))
		RETURN 701
	
	IF EXISTS(SELECT TOP 1 1
				FROM BillIndex B 
				INNER JOIN nVipCardSign C ON B.BillNumberId=@BillNumberId AND C.VipCardID=B.VipCardID AND C.isApplyAllStype=0 AND NOT EXISTS(SELECT * FROM VipCard_ApplyStype S WHERE S.VipCardId=C.VipCardID AND S.StypeId=B.StypeId))
		RETURN 706
		
	--多账户
	IF EXISTS(SELECT TOP 1 1 
				FROM BillIndex B
				INNER JOIN dbo.BillMulAccount M ON B.BillNumberId=@BillNumberID AND M.BillNumberId=B.BillNumberId
				INNER JOIN dbo.nVipCardSign C ON C.VipCardID=B.VipCardID AND (C.deleted<>0 OR C.EndDate<B.BillDate OR NOT EXISTS(SELECT TOP 1 1 FROM nVipCardSet WHERE VipCardTypeID=C.VipCardTypeID AND deleted=0)))
		RETURN 701
		
	IF EXISTS(SELECT TOP 1 1 
				FROM BillIndex B
				INNER JOIN dbo.BillMulAccount M ON B.BillNumberId=@BillNumberID AND M.BillNumberId=B.BillNumberId
				INNER JOIN nVipCardSign C ON C.VipCardID=B.VipCardID AND C.isApplyAllStype=0 AND NOT EXISTS(SELECT * FROM VipCard_ApplyStype S WHERE S.VipCardId=C.VipCardID AND S.StypeId=B.StypeId))
		RETURN 706
		
	--验证pos做的退货单（非原单退货 含有批号的商品，未选择批号问题）
	IF EXISTS(SELECT TOP 1 1 FROM Billindex B
				INNER JOIN RetailBackBill Rb ON Rb.BillNumberId=B.BillNumberId AND B.BillNumberId=@BillNumberID
				INNER JOIN Ptype P ON p.typeId=rb.PtypeId AND p.IfUseGoodsNum=1
				WHERE ISNULL(rb.GoodsNumber,'')='' )
		RETURN 	2150
END

--验证门店配送退货单退货数量是否超出
IF @BillType=328
BEGIN
	--门店配送单已经红冲
	IF EXISTS(select top  1 1 from DeliveryBill d 
		Inner join  DeliveryBackBill De on de.DeliveryID=d.ID
		INNER JOIN PosAllotApplyBillIndex bi on bi.BillNumberId=d.BillNumberId
		where de.BillNumberId=@BillNumberID and bi.RedWord<>0)
	BEGIN
		RETURN 3281
	END

	IF EXISTS(select top  1 1 from DeliveryBill d 
		Inner join  DeliveryBackBill De on de.DeliveryID=d.ID
		where de.BillNumberId=@BillNumberID and de.qty>0 and (ISNULL(d.qty,0)-ISNULL(d.CheckQty,0)-ISNULL(d.backqty,0))-ISNULL(de.qty,0)<0)
	BEGIN
		RETURN 3280
	END
END


IF @nRet <> 0
BEGIN
	RETURN @nRet
END

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	往来核销单过账
	作    者：	施训果
	修改时间：	
*/
CREATE             PROCEDURE Gp_Auditing_ChargeOffBill
(
	@intBillNumberID				NUMERIC(10,0),				-- 单据 ID 号
	--@intBilltype				INT,
	@Ret					INT	OUT
)
--@encode$--
AS
	SET NOCOUNT ON
	
	SELECT
		@Ret=0
	
	DECLARE
		-- 系统是否启用【费用单核算客户时计入应收】
		@expensetoar INT=0,
		@chargeOffValue		NUMERIC(24,10),
		@nchargeOffValue	NUMERIC(24,10),
		@chargeOffType INT, --核销类型:0：应收冲应付 1：预收冲预付 2：应收转应收 3：应付转应付 4：预收转应付 5：预付转应收
		@btypeID VARCHAR(50),
		@fromBillNumberid NUMERIC(10,0),
		@fromBillID INT,
		@fromBillType NUMERIC(4,0),
		@checkFlag INT,
		@cid INT,
		@jState INT,
		@NTotalMoney NUMERIC(24,10),
		@NTotalInMoney NUMERIC(24,10),
		@NCompleteTotal NUMERIC(24,10),
		@NPreferenceMoney	NUMERIC(24,10)
 	
	SELECT @expensetoar = SUBVALUE FROM SYSDATA WHERE SUBNAME='expensetoar'
	SELECT @chargeOffValue=totalmoney,@nchargeOffValue=NTotalMoney,@chargeOffType=ChargeOffType,@cid=CID
	FROM dbo.BillIndex 
	WHERE BillNumberId=@intBillNumberID 

	IF @chargeOffValue=0
		UPDATE BillIndex SET jsState=2,jsStyle=1 WHERE BillNumberId=@intBillNumberID 

	DECLARE chargeOffCursort CURSOR FOR SELECT ChargeOffValue,NChargeOffValue,FromBillNumberid,FromBillID,FromBillType,BTypeID FROM dbo.ChargeOffBill WHERE BillNumberId=@intBillNumberID
	OPEN  chargeOffCursort
	FETCH NEXT FROM chargeOffCursort INTO @chargeOffValue,@nchargeOffValue, @fromBillNumberid,@fromBillID,@fromBillType,@btypeID
	WHILE (@@fetch_status=0)
	BEGIN
		-- 退款类单据，保存时需要把本次核销金额置特殊处理
		IF @fromBillType IN (45,46,6,115,129,150,151,148,149,426)
		BEGIN
			SET @chargeOffValue=-@chargeOffValue
			SET @nchargeOffValue=-@nchargeOffValue
		END
		
		-- 系统是否启用【费用单核算客户时计入应收】金额为负的应收所以金额要做负号处理
		IF @expensetoar=1 AND @fromBillType=36 AND @chargeOffType IN (0,2) AND substring(@btypeID,0,6)='00001'
		BEGIN
			SET @chargeOffValue=-@chargeOffValue
			SET @nchargeOffValue=-@nchargeOffValue
		END
	
		IF @fromBillType IN (405,404)
		BEGIN
			UPDATE dbo.ReceiptBillIndex SET ChargeOffTotal=ChargeOffTotal+@chargeOffValue,NChargeOffTotal=NChargeOffTotal+@nchargeOffValue
			WHERE BillNumberId=@fromBillNumberid
			SELECT @NTotalMoney =NTaxTotalMoney,
				   @NTotalInMoney=0,
				   @NCompleteTotal=NCompleteTotal,
				   @NPreferenceMoney=0,
				   @nchargeOffValue=NChargeOffTotal FROM dbo.ReceiptBillIndex 
			WHERE BillNumberID=@fromBillNumberid
			
			IF (@NTotalMoney-@NCompleteTotal-@nchargeOffValue)<>0
				UPDATE dbo.ReceiptBillIndex SET JSStyle=1,JSState=1 WHERE BillNumberID=@fromBillNumberid
			ELSE 
				UPDATE dbo.ReceiptBillIndex SET JSStyle=1,JSState=2 WHERE BillNumberID=@fromBillNumberid
		END
		ELSE
		BEGIN
			--应收应付预收预付回写核销金额到明细
			IF @fromBillType IN (115,116,128,129)
			BEGIN
				UPDATE dbo.AdDebtBill SET ChargeOffTotal=ChargeOffTotal+@chargeOffValue,NChargeOffTotal=NChargeOffTotal+@nchargeOffValue
				WHERE BillNumberId=@fromBillNumberid AND ID = @fromBillID
			END
			IF @fromBillType NOT IN (423,424,425,426)
			BEGIN
				UPDATE dbo.BillIndex SET ChargeOffTotal=ChargeOffTotal+@chargeOffValue,NChargeOffTotal=NChargeOffTotal+@nchargeOffValue
				WHERE BillNumberId=@fromBillNumberid
			
				SELECT @NTotalMoney =NTotalMoney,
					   @NTotalInMoney=NTotalInMoney,
					   @NCompleteTotal=NCompleteTotal,
					   @NPreferenceMoney=NPreferenceMoney,
					   @nchargeOffValue=NChargeOffTotal FROM dbo.BillIndex 
				WHERE BillNumberID=@fromBillNumberid
				IF (@NTotalMoney-@NCompleteTotal-@NTotalInMoney-@NPreferenceMoney-@nchargeOffValue)<>0
				UPDATE dbo.BillIndex SET JSStyle=1,JSState=1 WHERE BillNumberID=@fromBillNumberid
				ELSE 
				UPDATE dbo.BillIndex SET JSStyle=1,JSState=2 WHERE BillNumberID=@fromBillNumberid
			END 
			ELSE 
			BEGIN	
				UPDATE dbo.Coupon_BillIndex SET ChargeOffTotal=ChargeOffTotal+@chargeOffValue,NChargeOffTotal=NChargeOffTotal+@nchargeOffValue
				WHERE BillNumberId=@fromBillNumberid
			
				SELECT @NTotalMoney =NTotalMoney,
					   @NTotalInMoney=NTotalInMoney,
					   @NCompleteTotal=NCompleteTotal,
					  @NPreferenceMoney=NPreferenceMoney,
					   @nchargeOffValue=NChargeOffTotal FROM dbo.Coupon_BillIndex 
				WHERE BillNumberID=@fromBillNumberid
				
				IF (@NTotalMoney-@NCompleteTotal-@NTotalInMoney-@NPreferenceMoney-@nchargeOffValue)<>0
					UPDATE dbo.Coupon_BillIndex SET JSState=1 WHERE BillNumberID=@fromBillNumberid
				ELSE 
					UPDATE dbo.Coupon_BillIndex SET JSState=2 WHERE BillNumberID=@fromBillNumberid			
			END 
			
			
		END
		FETCH NEXT FROM chargeOffCursort INTO @chargeOffValue,@nchargeOffValue, @fromBillNumberid,@fromBillID,@fromBillType,@btypeID
	END
	
	CLOSE chargeOffCursort
	DEALLOCATE chargeOffCursort

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*



*/





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	过账前验证
	作    者：	冯波
	修改时间：	2011-08-16
*/
CREATE             PROCEDURE Gp_Auditing_Check
(
	@nBillID				NUMERIC(10,0),				-- 单据 ID 号
	@intBillType			INT
)
--@encode$--
AS
	DECLARE
		@intQuickRepairBillID	INT,
		@intQuickRepairBillType	INT,
		@nRet					INT
		
		
	SELECT @nRet=0
		

	
	IF @intBillType=187
	BEGIN
		--分支机构调拨出库单
		IF EXISTS(
			SELECT b.STypeID 
			FROM STypeMoveBill a
			INNER JOIN Stock b
			ON a.Ktypeid2=b.typeId
			WHERE a.BillNumberId=@nBillID
			AND b.STypeID NOT IN
			(
				SELECT	STypeID
				FROM	SType_UserConfig
				WHERE	ConfigNo = 1
				AND Value = 1
			)
		)
		BEGIN
			RETURN 3
		END
	END
	ELSE IF @intBillType=188
	BEGIN
		--分支机构调拨入库单
		IF EXISTS(
			SELECT b.STypeID 
			FROM STypeMoveBill a
			INNER JOIN Stock b
			ON a.Ktypeid=b.typeId
			WHERE a.BillNumberId=@nBillID
			AND b.STypeID NOT IN
			(
				SELECT	STypeID
				FROM	SType_UserConfig
				WHERE	ConfigNo = 1
				AND Value = 1
			)
		)
		BEGIN
			RETURN 3
		END
	END
	ELSE IF @intBillType=159
	BEGIN
		--内部应收所对应的分支机构必须处于开账状态
		IF EXISTS(
			SELECT a.ATypeID
			FROM AccountCredence a
			INNER JOIN Ac_Items b
			ON a.TypeATypeID=b.nId
			WHERE a.BillNumberID=@nBillID
			AND b.UserCode='1132'
			AND a.ATypeID NOT IN
			(
				SELECT	STypeID
				FROM	SType_UserConfig
				WHERE	ConfigNo = 1
				AND Value = 1
			)
		)
		BEGIN
			RETURN 3
		END
	END
	ELSE IF @intBillType=191
	BEGIN
		--领料出库单
		IF EXISTS(
			SELECT a.QuickRepairBillID
			FROM Billindex_CarRepair a
			INNER JOIN Billindex_CarRepair b
			ON a.QuickRepairBillID=b.BillNumberId
			WHERE a.BillNumberId=@nBillID 
			AND a.QuickRepairBillID<>-1 
			AND b.BillState IN (3,4,5)
		)
		BEGIN
			RETURN -401
		END
		
	END
	ELSE IF @intBillType=197
	BEGIN
		--领料退货单
		IF EXISTS(
			SELECT a.QuickRepairBillID
			FROM Billindex_CarRepair a
			INNER JOIN Billindex_CarRepair b
			ON a.QuickRepairBillID=b.BillNumberId
			INNER JOIN Billindex_CarRepair c
			ON b.QuickRepairBillID=c.BillNumberId
			WHERE a.BillNumberId=@nBillID 
			AND c.BillState IN (3,4,5)
		)
		BEGIN
			RETURN -403
		END
		
		IF EXISTS(
			SELECT a.ID 
			FROM Qp_PickingBackBill a
			INNER JOIN Qp_PickingBill b
			ON a.PickingId=b.ID
			WHERE a.BillNumberID=@nBillID 
			AND  a.Qty>b.Qty-b.BackQty
		)
		BEGIN
			RETURN -402
		END
		
		
		IF EXISTS(
			SELECT a.QuickRepairBillID
			FROM Billindex_CarRepair a
			INNER JOIN BillIndex b
			ON a.QuickRepairBillID=b.BillNumberId
			WHERE a.BillNumberId=@nBillID 
			AND b.RedWord<>0
		)
		BEGIN
			RETURN -412
		END
	END
	ELSE IF @intBillType=200
	BEGIN
		IF EXISTS(
			SELECT a.BillNumberId
			FROM Billindex_CarRepair a
			INNER JOIN Billindex_CarRepair b
			ON a.BillNumberId=@nBillID 
			AND a.QuickRepairBillID=b.BillNumberId
			WHERE b.CounterClaimStatus=2
		)
		BEGIN
			RETURN -410
		END
		
		SELECT @intQuickRepairBillID=QuickRepairBillID
		FROM Billindex_CarRepair
		WHERE BillNumberId=@nBillID
		
		SELECT @intQuickRepairBillType=BillType
		FROM BillIndex
		WHERE BillNumberId=@intQuickRepairBillID
		
		
		
		--需要判断当前三包的配件或项目中是否有已索赔的项目
		IF @intQuickRepairBillType=178
		BEGIN
			IF EXISTS(
				SELECT a.ID
				FROM Qp_ThreePacketsBill_PType a
				INNER JOIN QP_QuickRepairBill_PType b
				ON a.QuickOrReceptionBillId=b.ID
				WHERE a.BillNumberId=@nBillID    
				AND b.BillNumberId=@intQuickRepairBillID 
				AND b.Insurance=2 
				AND b.CounterClaimStatus=2
				UNION
				SELECT a.ID
				FROM Qp_ThreePacketsBill_RepairItems a
				INNER JOIN QP_QuickRepairBill_RepairItems b
				ON a.QuickOrReceptionBillId=b.ID
				WHERE a.BillNumberId=@nBillID    
				AND b.BillNumberId=@intQuickRepairBillID 
				AND b.Insurance=2 
				AND b.CounterClaimStatus=2
				
			)
			BEGIN
				RETURN -444
			END
		END
		ELSE
		BEGIN
			IF EXISTS(
				SELECT a.ID
				FROM Qp_ThreePacketsBill_PType a
				INNER JOIN Qp_ReceptionBill_FactUsePType b
				ON a.QuickOrReceptionBillId=b.ReceptionBillPTypeId
				WHERE a.BillNumberId=@nBillID    
				AND b.ReceptionBillnumberId=@intQuickRepairBillID 
				AND b.Insurance=2 
				AND b.CounterClaimStatus=2
				UNION
				SELECT a.ID
				FROM Qp_ThreePacketsBill_RepairItems a
				INNER JOIN QP_QuickRepairBill_RepairItems b
				ON a.QuickOrReceptionBillId=b.ID
				WHERE a.BillNumberId=@nBillID    
				AND b.BillNumberId=@intQuickRepairBillID 
				AND b.Insurance=2 
				AND b.CounterClaimStatus=2
				
			)
			BEGIN
				RETURN -444
			END
		END
		
	END
	ELSE IF @intBillType=186
	BEGIN
		IF EXISTS(
			SELECT a.BillNumberId
			FROM Billindex_CarRepair a
			INNER JOIN Billindex_CarRepair b
			ON a.BillNumberId=@nBillID AND a.QuickRepairBillID=b.BillNumberId
			WHERE b.InsuranceStatus=2
		)
		BEGIN
			RETURN -411
		END
		
		IF EXISTS(
			SELECT a.BillNumberId
			FROM Billindex_CarRepair a
			INNER JOIN BillIndex b
			ON a.QuickRepairBillID=b.BillNumberId
			WHERE a.BillNumberId=@nBillID
			AND (b.ifcheck<>'t' OR b.RedWord<>0) 
		)
		BEGIN
			RETURN -420
		END
	END
	ELSE IF @intBillType=195
	BEGIN
		IF EXISTS(
			SELECT a.BillNumberId
			FROM Billindex_CarRepair a
			INNER JOIN Billindex b
			ON a.BillNumberId=@nBillID AND a.QuickRepairBillID=b.BillNumberId
			WHERE b.ifcheck='t' 
			AND b.RedWord<>0
		)
		BEGIN
			RETURN -418
		END
	END
	ELSE IF @intBillType=206
	BEGIN
		--判断是否存在月结前的物流单据
		IF EXISTS(
			SELECT a.BillNumberId
			FROM ShareSourceBill a
			INNER JOIN BillIndex b
			ON a.FromBillNumberID=b.BillNumberId AND a.FromBillType=b.BillType
			WHERE a.BillNumberId=@nBillID
			AND b.BillDate<(SELECT TOP 1 StartDate FROM MonthProc WHERE MonthNo = '本期' AND STypeID=B.StypeID)
			UNION ALL
			SELECT a.BillNumberId
			FROM ShareFeeBill a
			INNER JOIN BillIndex b
			ON a.FromBillNumberID=b.BillNumberId 
			WHERE a.BillNumberId=@nBillID
			AND b.BillDate<(SELECT TOP 1 StartDate FROM MonthProc WHERE MonthNo = '本期' AND STypeID=B.StypeID)
		)
		BEGIN
			RETURN -454
		END
	
	
		
		--判断费用单或物流单据是否已参与分摊
		IF EXISTS(
			SELECT a.BillNumberId
			FROM ShareFeeBill a
			inner JOIN  (
			
				SELECT a.FromBillID,a.FromBillNumberID
				FROM ShareFeeBill a
				INNER JOIN BillIndex b
				ON a.BillNumberId=b.BillNumberId
				WHERE a.BillNumberId<>@nBillID
				AND b.BillType IN (206,205)
				AND b.ifcheck='t' 
				AND b.RedWord=0
			) c ON c.FromBillID = a.FromBillID AND c.FromBillNumberID = a.FromBillNumberID
			
			WHERE a.BillNumberId=@nBillID
			
			/*
			UNION ALL
			SELECT a.BillNumberId
			FROM ShareSourceBill a
			WHERE a.BillNumberId=@nBillID
			AND a.FromBillID IN
			(
				SELECT a.FromBillID
				FROM ShareSourceBill a
				INNER JOIN BillIndex b
				ON a.BillNumberId=b.BillNumberId
				WHERE a.BillNumberId<>@nBillID 
				AND b.BillType IN (206)
				AND b.ifcheck='t' 
				AND b.RedWord=0
			)
			*/
		)
		BEGIN
			RETURN -450
		END
		
		--判断关联的单据是否已红冲
		IF EXISTS(
			SELECT a.BillNumberId
			FROM ShareFeeBill a
			INNER JOIN BillIndex b
			ON a.FromBillNumberID=b.BillNumberId 
			WHERE a.BillNumberId=@nBillID
			AND b.ifcheck='t'
			AND b.RedWord<>0
			UNION ALL
			SELECT a.BillNumberId
			FROM ShareSourceBill a
			INNER JOIN BillIndex b
			ON a.FromBillNumberID=b.BillNumberId AND a.FromBillType=b.BillType
			WHERE a.BillNumberId=@nBillID
			AND b.ifcheck='t'
			AND b.RedWord<>0
		)
		BEGIN
			RETURN -452
		END
	
	END
	ELSE IF @intBillType=205
	BEGIN
		--判断是否存在月结前的物流单据
		IF EXISTS(
			SELECT a.BillNumberId
			FROM ShareSourceBill a
			INNER JOIN BillIndex b
			ON a.FromBillNumberID=b.BillNumberId AND b.BillType = a.FromBillType
			WHERE a.BillNumberId=@nBillID
			AND b.BillDate<(SELECT TOP 1 StartDate FROM MonthProc WHERE MonthNo = '本期' AND STypeID=B.StypeID)
			UNION ALL
			SELECT a.BillNumberId
			FROM ShareFeeBill a
			INNER JOIN BillIndex b
			ON a.FromBillNumberID=b.BillNumberId 
			WHERE a.BillNumberId=@nBillID
			AND b.BillDate<(SELECT TOP 1 StartDate FROM MonthProc WHERE MonthNo = '本期' AND STypeID=B.StypeID)
		)
		BEGIN
			RETURN -454
		END
		
	
		--判断费用单或物流单据是否已参与分摊
		IF EXISTS(
			SELECT a.BillNumberId
			FROM ShareFeeBill a
			INNER JOIN  
			(
			   SELECT a.FromBillID,a.FromBillNumberID
				FROM ShareFeeBill a
				INNER JOIN BillIndex b
				ON a.BillNumberId=b.BillNumberId 
				WHERE a.BillNumberId<>@nBillID
				AND b.BillType IN (205,206)
				AND b.ifcheck='t' 
				AND b.RedWord=0
			) c ON  c.FromBillID = a.FromBillID AND c.FromBillNumberID = a.FromBillNumberID
			WHERE a.BillNumberId=@nBillID
			
			UNION ALL
			SELECT a.BillNumberId
			FROM ShareSourceBill a
			INNER JOIN 
			(
			
				SELECT a.FromBillID,a.FromBillType
				FROM ShareSourceBill a
				INNER JOIN BillIndex b
				ON a.BillNumberId=b.BillNumberId  AND a.FromBillType=b.BillType
				WHERE a.BillNumberId<>@nBillID 
				AND b.BillType IN (205)
				AND b.ifcheck='t' 
				AND b.RedWord=0
			) c ON  c.FromBillID = a.FromBillID AND c.FromBillType = a.FromBillType
			WHERE a.BillNumberId=@nBillID
			
		)
		BEGIN
			RETURN -451
		END
		
	
		--判断关联的单据是否已红冲
		IF EXISTS(
			SELECT a.BillNumberId
			FROM ShareFeeBill a
			INNER JOIN BillIndex b
			ON a.FromBillNumberID=b.BillNumberId
			WHERE a.BillNumberId=@nBillID
			AND b.ifcheck='t'
			AND b.RedWord<>0
			UNION ALL
			SELECT a.BillNumberId
			FROM ShareSourceBill a
			INNER JOIN BillIndex b
			ON a.FromBillNumberID=b.BillNumberId AND a.FromBillType=b.BillType
			WHERE a.BillNumberId=@nBillID
			AND b.ifcheck='t'
			AND b.RedWord<>0
		)
		BEGIN
			RETURN -453
		END
	END
	ELSE IF @intBillType IN (212,213,214)
	BEGIN
		DECLARE @Period INT,@Year INT ,@count INT=1,@billdate DATETIME,@fperiod INT,@fyear INT
		SELECT @fperiod=fperiod,@fyear=FYear FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid=(SELECT VerifyID  FROM dbo.BillIndex b INNER JOIN dbo.SType s ON b.Stypeid=s.TypeId WHERE BillNumberId=@nbillid)
		IF @fperiod IS NULL
		BEGIN
			SELECT @fperiod=SubValue FROM dbo.sysdata WHERE SubName='Fmonth' 
			SELECT @fyear=subvalue FROM dbo.sysdata WHERE SubName='fyear'
		END
		SELECT @billdate = BILLDATE FROM dbo.BillIndex WHERE BillNumberId=@nbillid
		IF @intBillType=212
		BEGIN
			SELECT @Period=MAX(Fperiod),@year=MAX(Fyear),@count=COUNT(1)
			FROM
			(
				SELECT FPeriod,FYear FROM dbo.Ac_Period  ap 
				INNER JOIN dbo.Ac_AssetsCards ac ON ap.FBegin<=ac.InAccountDate AND ap.FEnd>=ac.InAccountDate
				INNER JOIN  AssetIncDecBill ai ON ai.AssetCardId=ac.Id WHERE BillNumberId=@nbillid
				GROUP BY FPeriod,FYear
			)a
			IF @count<>1 OR @Period<@fperiod AND @year<=@Fyear OR NOT EXISTS(SELECT 1 FROM dbo.Ac_Period WHERE FPeriod=@Period AND FYear=@Year AND FBegin<=@billdate AND FEnd>=@billdate)
				RETURN 300
		END
		ELSE
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM dbo.Ac_Period WHERE FYear=@FYear AND FPeriod=@fperiod AND FBegin<=@billdate AND FEnd>=@billdate)
				RETURN 302
		END
	END
	ELSE IF @intBillType=310
	BEGIN
		--资金调拨单
		EXEC @nRet=Gp_DepBill_Check @nbillid
	END
	ELSE IF @intBillType=404
	BEGIN
		--发票关联的源单据不存在
		IF EXISTS(
			SELECT ID
			FROM ReceiptBill 
			WHERE BillNumberID=@nBillID AND MainBillNumberID NOT IN
			(
				SELECT BillNumberID
				FROM Billindex
				WHERE (ifcheck='t' AND RedWord=0) OR (IsIni=1)
				AND BillType IN (400,401)
			)
		)
		BEGIN
			SET @nRet=-4040
		END
	END
	ELSE IF @intBillType=405
	BEGIN
		--发票关联的源单据不存在
		IF EXISTS(
			SELECT ID
			FROM ReceiptBill 
			WHERE BillNumberID=@nBillID AND MainBillNumberID NOT IN
			(
				SELECT BillNumberID
				FROM Billindex
				WHERE (ifcheck='t' AND RedWord=0) OR (IsIni=1)
				AND BillType IN (402,403)
			)
		)
		BEGIN
			SET @nRet=-4040
		END
	END
	ELSE IF @intBillType=401
	BEGIN
		--退货单关联的源单据不存在
		IF EXISTS(
			SELECT ID
			FROM AppraisalBackBill 
			WHERE BillNumberID=@nBillID AND OldBillNumberID NOT IN (0,-1) AND OldBillNumberID NOT IN
			(
				SELECT BillNumberID
				FROM Billindex
				WHERE (ifcheck='t' AND RedWord=0) OR (IsIni=1)
				AND BillType=400
			)
		)
		BEGIN
			SET @nRet=-4010
		END
	END
	ELSE IF @intBillType=403
	BEGIN
		--退货单关联的源单据不存在
		IF EXISTS(
			SELECT ID
			FROM SendBackBill 
			WHERE BillNumberID=@nBillID AND OldBillNumberID NOT IN (0,-1) AND OldBillNumberID NOT IN
			(
				SELECT BillNumberID
				FROM Billindex
				WHERE (ifcheck='t' AND RedWord=0) OR (IsIni=1)
				AND BillType=402
			)
		)
		BEGIN
			SET @nRet=-4010
		END
	END
	ELSE IF @intBillType=450
	BEGIN
		IF EXISTS(
			SELECT 1 FROM dbo.BillIndex WHERE RedWord=1 AND BillNumberId IN (SELECT FromBillNumberid FROM dbo.ChargeOffBill WHERE BillNumberId=@nBillID AND FromBillType NOT IN (404,405,423,424,425,426))
		)
		SET @nRet=-800--被核销的单据已经红冲
		IF EXISTS(
			SELECT 1 FROM dbo.ReceiptBillIndex WHERE RedWord=1 AND BillNumberId IN (SELECT FromBillNumberid FROM dbo.ChargeOffBill WHERE BillNumberId=@nBillID AND FromBillType IN (404,405))
		)
		SET @nRet=-800--被核销的单据已经红冲
		
		IF EXISTS(
			SELECT 1 FROM dbo.Coupon_BillIndex WHERE RedWord=1 AND BillNumberId IN (SELECT FromBillNumberid FROM dbo.ChargeOffBill WHERE BillNumberId=@nBillID AND FromBillType  IN (423,424,425,426))
		)
		SET @nRet=-800--被核销的单据已经红冲 
		
		--存在被核销按商品结算的单据，不允许过账
		IF EXISTS(
			SELECT 1 FROM dbo.ChargeOffBill AS C INNER JOIN dbo.CompleteGoodTotal G ON C.FromBillNumberid=G.GoodsBillID AND G.BillType=C.FromBillType 
			WHERE BillNumberId=@nBillID AND G.Draft=0
		)
		SET @nRet=-801
	END
	
	
	
	
	RETURN @nRet
	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	过账前的控制
	作    者：	冯波
	修改时间：	2012-05-03
*/
CREATE             PROCEDURE Gp_Auditing_Control(
	@chvSTypeID		VARCHAR(50),
	@intBillType	INT=0
)
--@encode$--
AS
	SET NOCOUNT ON
	

	--SET ANSI_WARNINGS OFF
	

	-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********
	-- 获取数据表 LoginUser 中操作员数
	DECLARE @intLoginUserCount int
	SELECT	@intLoginUserCount = COUNT(*)
	FROM	LoginUser
	WHERE	IsErp = 1

	DECLARE @N int, @intDogUserCount int, @intVersion int
	-- 判断版本号，是否试用版
	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 2	-- 版本号

	IF @N IS NULL RETURN 1688

	DECLARE @intBit int, @intMask int
	SELECT @intBit = @N & 15
	SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
	SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

	-- 判断软件狗用户数
	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 3	-- 检查用户数

	IF @N IS NULL RETURN 1688

	IF @intVersion IN (2,3,5,7,9,11,13,15 )	-- 试用版
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE subname = 'Proinfo' AND SubValue = '4')
			SELECT @intDogUserCount = 3
		ELSE
			SELECT @intDogUserCount = 5
	END
	ELSE
	BEGIN
		SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
		IF ( 3 & @N <> 3 ) RETURN 1688
	END

	-- 若实际操作员数 > 软件狗许可用户数，则不允许过账
	IF @intLoginUserCount - 1 > @intDogUserCount RETURN 1688

	-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - End	********

	IF NOT EXISTS (
		SELECT	TOP 1 1
		FROM	SType_UserConfig
		WHERE	ConfigNo = 1
				AND Value = 1
				AND STypeID=@chvSTypeID
	)  
	BEGIN
		--启用独立开账，资金调拨单不判断业务系统开账
		IF NOT EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='stypeindependentopen' AND SubValue='1' AND @intBillType=310)
		BEGIN
			RETURN 3	-- 业务开账
		END
	END
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype A INNER JOIN dbo.SType S ON A.Stypeid=S.VerifyID
		WHERE S.TypeID=@ChvSTypeID AND IsUse=1)
		AND @IntBillType IN(84,85,78,213,212,214,307,410,411,310)
	BEGIN
		RETURN 4   --固定资产类单据总账也要开账
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/****优惠券单据过账****/
IF  EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_Auditing_CouponBill',N'P'))
BEGIN
	DROP PROC GP_Auditing_CouponBill
END
GO

CREATE PROC GP_Auditing_CouponBill
(
	@BillNumberID	INT,
	@BillType		INT,
	@szCheckMan		VARCHAR(50),
	@chvOpID		VARCHAR(50),
	@voucherMsg		VARCHAR(1000) OUT
)
AS
BEGIN
DECLARE @STypeID VARCHAR(100),
		@nRet    INT,
		@posId INT
	
	/*过账前校验*/
    SELECT  @STypeID = Stypeid,@posId=PosId FROM  dbo.Coupon_BillIndex WHERE   BillNumberId = @BillNumberID
	EXEC @nRet=Gp_Auditing_Control @STypeID
	IF @nRet<>0 RETURN @nRet
	--pos生成单据单独验证其过账权限--
	IF @posId>0
	BEGIN
	IF @BILLTYPE=424 AND EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_BillIndex WHERE PosId>0 AND BillNumberId=@BillNumberID)
		BEGIN			
			if exists(select * from loginuser where etypeid=@chvOpID and sysid='1')
				SELECT @nRet=0
			ELSE
			BEGIN
				declare @right0 char(1) --pos优惠券出库单过账权限	
				select @right0=substring(lim,5097,1) from loginuser where etypeid=@chvOpID 
				if @right0='1' 
					SELECT @nRet = 0
				else
					RETURN 1000 
			END
		END
	ELSE IF @BILLTYPE=426 AND EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_BillIndex WHERE PosId>0 AND BillNumberId=@BillNumberID)
		BEGIN			
			if exists(select * from loginuser where etypeid=@chvOpID and sysid='1')
				SELECT @nRet=0
			ELSE
			BEGIN
				declare @right1 char(1) --pos优惠券退货单过账权限	
				select @right1=substring(lim,5098,1) from loginuser where etypeid=@chvOpID 
				if @right1='1' 
					SELECT @nRet = 0
				else
					RETURN 1000 
			END
		END
	END	
	ELSE 
	BEGIN
		/*没有单据过账的权限*/
		EXEC @nRet = Gp_CheckLimitBillType @chvOpID,0,@billtype
		IF	 @nRet <> 1 RETURN 1000 
		SET	 @nRet = 0
	END
	
	
	IF NOT EXISTS(SELECT 1 FROM dbo.Coupon_BillIndex WHERE BillNumberId=@BillNumberID AND IfCheck='f')
	BEGIN
		RETURN 1111  /*该单据不存在或已过账*/
	END
	
	EXEC @nRet = GP_AuditingCheckBillData @BillNumberID,@BillType,'0'		
	IF @nRet <> 0 
	RETURN @nRet
	
	------检查单据是否存在失效，作废的优惠券---------------------------------------------------------------------------------------------------
	DECLARE  @sql VARCHAR(5000),@detailtablename VARCHAR(50),@curdate DATETIME=GETDATE()
		
	CREATE TABLE #CurCoupon_Bill 
	(	ID int,
		CouponCode varchar(200)
	)
	SELECT @sql='
	INSERT INTO #CurCoupon_Bill 
	(	ID,
		CouponCode
			
	)
	SELECT  A.ID ,  B.StrColumn AS couponcode
	FROM    (SELECT StrXml = CONVERT(XML, ''<root><v>''+REPLACE( Couponcode, ''я'', ''</v><v>'')+''</v></root>'') , ID    FROM   
			  '+CASE @BillType WHEN 423 THEN ' dbo.Coupon_InBill '
							   WHEN	424 THEN ' dbo.Coupon_OutBill '
							   WHEN 425 THEN ' dbo.Coupon_AllotBill '
							   WHEN 426 THEN ' dbo.Coupon_BackBill '
							   WHEN 428 THEN ' dbo.Coupon_AllotBillStype'
							   WHEN 429 THEN ' dbo.Coupon_AllotBillStype'
							   END 	
				
			  +'  WHERE BillNumberID='+cast (@BillNumberID AS VARCHAR(50) )+'   ) A OUTER APPLY (SELECT StrColumn = N.v.value(''.'', ''nvarchar(200)'')  FROM   A.StrXml.nodes(''/root/v'') N (v)   ) B 
		
	'
	EXEC (@sql)
	IF @BillType=423
	BEGIN
		--IF EXISTS(
		--SELECT TOP 1 1 FROM (
		--			SELECT  CASE  WHEN ct.InvalidType=1 THEN  '9999-12-31' 
		--						   WHEN ct.InvalidType=3 THEN ci.InvalidDate 
		--						   WHEN ct.InvalidType=2 THEN  CASE WHEN ct.InvalidStartDateType =1 THEN  ci.InvalidDate 
		--															WHEN ct.InvalidStartDateType =2 THEN '9999-12-31' --入库的时候 判断不到出库日期 
		--														    ELSE '9999-12-31' END 
		--							ELSE '9999-12-31'   
									
		--						END  AS Invaliddate
		--	FROM dbo.coupon_InBill  ci 
		--	INNER JOIN coupon_TypeInfo ct ON ct.CouponId=cI.CouponId
		--	WHERE ci.BillNumberId=@BillNumberID) a  WHERE DATEDIFF(DAY,GETDATE(),a.Invaliddate) <0 --当前日期超过失效日期
		--	)
		--RETURN 1112
		
		IF EXISTS (SELECT TOP 1 1 FROM coupon_typeinfo  ct 
							   INNER JOIN coupon_InBill ci on ct.couponid=ci.couponid 
							   WHERE Ct.IsDelete=1 AND ci.BillNumberId=@BillNumberID)
							   
		RETURN 1113   
				
	END
	-------------------------------------------------------单据过账 begin--------------------------------------------------
	-- 将单据状态：草稿 -> 过账单据
	UPDATE	dbo.Coupon_BillIndex
	SET		IfCheck = 't',
			Checker = '',
			Draft = 0,
			Poster=@chvOpID,
			PostTime=GETDATE()
	WHERE	BillNumberID = @BillNumberID
			AND BillType=@BillType

	
	DECLARE @billdate DATETIME,@InKtypeId	varchar(50),@OutKtypeid	varchar(50),@tmpKtypeId varchar(50)	
	
	SELECT	@billdate=billdate, 
			@InKtypeId=InKtypeid,
			@OutKtypeid=OutKTypeId  
	FROM	dbo.Coupon_BillIndex 
	WHERE	BillNumberID=@BillNumberID

	IF @BILLTYPE=423 --优惠券入库
	BEGIN
		--券编码信息处理
	
	--券编码信息处理，不能重复编码过账，这只能是添加
		INSERT INTO dbo.Coupon_CodeInfo
		        ( CouponCode ,
		          CouponId ,
		          [State] ,
		          --Dbguid ,
		          IsIni ,
		          KtypeId ,
		          CargoId ,
		          IniState ,
		          InvalidDate ,
		          IsYear,
		          outprice,
		          InDate,
		          IniKtypeId,
		          IniCargoId
		        )
		SELECT  c.CouponCode,
				ct.CouponId,
				1,--在库
				0,
				@InKtypeId,
				ci.cargoid,
				1,
				InvalidDate= CASE  WHEN ct.InvalidType=1 THEN  '9999-12-31' 
								   WHEN ct.InvalidType=3 THEN ct.InvalidDate 
								   WHEN ct.InvalidType=2 THEN  CASE WHEN ct.InvalidStartDateType =1 THEN ci.InvalidDate
																	WHEN ct.InvalidStartDateType =2 THEN '9999-12-31' --入库的时候 判断不到出库日期 不写
																    ELSE '9999-12-31' END 
									ELSE '9999-12-31'   
									
								END ,
				0,
				dbo.F_RoundPrice(0),
				ci.InDate,
				@InKtypeId,
				ci.cargoid
			FROM #CurCoupon_Bill c
			left JOIN dbo.coupon_InBill  ci ON c.id=ci.Id
			INNER JOIN coupon_TypeInfo ct ON ct.CouponId=cI.CouponId
		
			   
		INSERT INTO Coupon_CodeInOut
		        ( BillnumberId ,
		          CouponCode ,
		          BillType ,
		          billdate ,
		          DetailId ,
		          CouponId ,
		          [State] ,
		          InKtypeId ,
		          OutKtypeid ,
		          InCargoId ,
		          OutCargoId,
		          Total,
		          NTotal
		        )
		SELECT @BillNumberID,
				C.CouponCode,
				@BILLTYPE,
				@billdate,
				C.ID,
				ct.CouponId,
				1,--在库
				@InKtypeId,
				@OutKtypeid,
				CI.CargoId,
				0,
				dbo.F_RoundTotal(CI.CostPrice),
				dbo.F_RoundTotal(ci.NCostPrice)
			FROM #CurCoupon_Bill C
			LEFT JOIN COUPON_INBILL CI ON C.ID=CI.ID
			LEFT JOIN coupon_TypeInfo CT ON CT.CouponId=Ci.CouponId	
			
	END
	ELSE IF @BillType=424
	BEGIN
		--券编码信息处理，不能重复编码过账，这只能是修改
		UPDATE Coupon_CodeInfo 
		SET		 [State]=case WHEN b.FromType=2 THEN 2 WHEN b.FromType=3 THEN 6 end ,--出库  对外 则是2 报损则是6
				  InvalidDate =CASE	WHEN ct.InvalidType=1 THEN  '9999-12-31' 
									WHEN ct.InvalidType=3 THEN Ci.InvalidDate		--入库的时候就已经写了的 不需要修改
									WHEN ct.InvalidType=2 THEN  CASE WHEN InvalidStartDateType =1 THEN co.InvalidDate  --出库的时候 依据入库日期 不需要修改
																     WHEN InvalidStartDateType =2 THEN ci.InvalidDate  --出库的时候 依据出库日期  重算
																     ELSE '9999-12-31' END 
									ELSE '9999-12-31'   
								END,
				OutPrice=ISNULL(ci.NPrice,0),
				outdate=ci.OutDate
		FROM Coupon_CodeInfo CO
		INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode
		LEFT JOIN dbo.coupon_OutBill ci ON ci.id=c.Id
		left join dbo.Coupon_BillIndex b ON b.BillNumberId = ci.BillNumberId 
		INNER  JOIN coupon_TypeInfo ct ON ct.CouponId=co.CouponId
		
		--写入出入库	   
		INSERT INTO Coupon_CodeInOut
		        ( BillnumberId ,
		          CouponCode ,
		          BillType ,
		          billdate ,
		          DetailId ,
		          CouponId ,
		          State ,
		          InKtypeId ,
		          OutKtypeid ,
		          InCargoId ,
		          OutCargoId,
		          Total,
		          NTotal
		        )
		SELECT @BillNumberID,
				C.CouponCode,
				@BILLTYPE,
				@billdate,
				C.ID,
				ct.CouponId,
				2,--出库
				@InKtypeId,
				@OutKtypeid,
				0,
				CI.CargoId,
				dbo.F_RoundTotal(CI.Price),
				dbo.F_RoundTotal(ci.NPrice)
			FROM #CurCoupon_Bill C
			LEFT JOIN Coupon_OutBill CI ON C.ID=CI.ID
			LEFT JOIN coupon_TypeInfo CT ON CT.CouponId=Ci.CouponId
			
	END 
	ELSE IF @BillType=425
	BEGIN
			-- 1出 1入
	   
		--券编码信息处理，仓库改变，货位改变
		UPDATE Coupon_CodeInfo
		SET		KtypeId=@InKtypeId,
				CargoId=ci.InCargoId
		FROM Coupon_CodeInfo CO
		INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode
		LEFT JOIN dbo.coupon_AllotBill ci ON ci.id=c.Id
		
		----出库		
		INSERT INTO Coupon_CodeInOut
					( BillnumberId ,
					  CouponCode ,
					  BillType ,
					  billdate ,
					  DetailId ,
					  CouponId ,
					  State ,
					  InKtypeId ,
					  OutKtypeid ,
					  InCargoId ,
					  OutCargoId,
					  Total,
					  NTotal
					)
		SELECT		@BillNumberID,
					C.CouponCode,
					@BILLTYPE,
					@billdate,
					C.ID,
					ct.CouponId,
					2,--出库
					'',
					@OutKtypeid,
					'',
					CI.OutCargoId,
					0,
					0
				FROM #CurCoupon_Bill C
				LEFT JOIN Coupon_AllotBill CI ON C.ID=CI.ID
				LEFT JOIN coupon_TypeInfo CT ON CT.CouponId=Ci.CouponId
		--入库		
		INSERT INTO Coupon_CodeInOut
					( BillnumberId ,
					  CouponCode ,
					  BillType ,
					  billdate ,
					  DetailId ,
					  CouponId ,
					  State ,
					  InKtypeId ,
					  OutKtypeid ,
					  InCargoId ,
					  OutCargoId,
					  Total,
					  NTotal
					)
		SELECT		@BillNumberID,
					C.CouponCode,
					@BILLTYPE,
					@billdate,
					C.ID,
					ct.CouponId,
					1,--在库
					@InKtypeId,
					'',
					ci.InCargoId,
					'',
					0,
					0
				FROM #CurCoupon_Bill C
				LEFT JOIN Coupon_AllotBill CI ON C.ID=CI.ID
				LEFT JOIN coupon_TypeInfo CT ON CT.CouponId=Ci.CouponId
	
	
	 
	END 
	ELSE IF(@BillType=426)
	BEGIN 
		IF EXISTS(SELECT * FROM Coupon_CodeInfo CO
		INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode AND CO.State=1)
			BEGIN
				DECLARE @ExistsCode	VARCHAR(MAX)=''
				SELECT @ExistsCode+=CO.CouponCode+',' FROM Coupon_CodeInfo CO
		INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode AND CO.State=1
				SET @voucherMsg='券编码【'+SUBSTRING(@ExistsCode,1,LEN(@ExistsCode)-1)+'】在当前券编码库中已存在！'
				RETURN -907
			END

		--回写调出库单的数量,backqty
		UPDATE Coupon_OutBill 
		SET		backqty=backqty+cb.Qty 
		FROM Coupon_OutBill co
		INNER JOIN Coupon_BackBill cb ON  co.id=cb.OutBillId--明细行ID
		WHERE cb.BillNumberID=@BillNumberID 
		
				   
				   
		--券编码信息处理，状态改变
		UPDATE Coupon_CodeInfo
		SET		[state]=1,--在库
				ktypeid=@InKtypeId	,
				cargoid=ci.CargoId
		FROM Coupon_CodeInfo CO
		INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode
		LEFT JOIN dbo.Coupon_BackBill ci ON ci.id=c.Id
		
		--出入库		   
		INSERT INTO Coupon_CodeInOut
		        ( BillnumberId ,
		          CouponCode ,
		          BillType ,
		          billdate ,
		          DetailId ,
		          CouponId ,
		          State ,
		          InKtypeId ,
		          OutKtypeid ,
		          InCargoId ,
		          OutCargoId,
		          Total,
		          NTotal
		        )
		SELECT @BillNumberID,
				C.CouponCode,
				@BILLTYPE,
				@billdate,
				C.ID,
				ct.CouponId,
				1,--在库
				@InKtypeId,
				@OutKtypeid,
				CI.CargoId,
				0,
				dbo.F_RoundTotal(CI.Price),
				dbo.F_RoundTotal(ci.NPrice)
			FROM #CurCoupon_Bill C
			LEFT JOIN Coupon_BackBill CI ON C.ID=CI.ID
			LEFT JOIN coupon_TypeInfo CT ON CT.CouponId=Ci.CouponId
	END 
	ELSE IF(@BillType=428)
	BEGIN
		IF EXISTS(SELECT * FROM Coupon_CodeInfo CO
			INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode AND CO.State=1)
			BEGIN
				DECLARE @ExistsCode1	VARCHAR(MAX)=''
				SELECT @ExistsCode1+=CO.CouponCode+',' FROM Coupon_CodeInfo CO
				INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode AND CO.State=1
				SET @voucherMsg='券编码【'+SUBSTRING(@ExistsCode1,1,LEN(@ExistsCode1)-1)+'】在当前券编码库中已存在！'
				RETURN -907
			END
		
		SET @tmpKtypeId=@OutKtypeId
		
		UPDATE  Coupon_CodeInfo
		SET		KtypeId=@InKtypeid,
				CargoId=ci.InCargoId,
				[state]=1	--分支机构调拨入库(改成入库中就可以了) 谢吉康 991 2020-1-3
		FROM Coupon_CodeInfo CO
		INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode
		LEFT JOIN dbo.Coupon_AllotBillStype ci ON ci.id=c.Id
		
		INSERT INTO Coupon_CodeInOut
		        ( BillnumberId ,
		          CouponCode ,
		          BillType ,
		          billdate ,
		          DetailId ,
		          CouponId ,
		          [State] ,
		          InKtypeId ,
		          OutKtypeid ,
		          InCargoId ,
		          OutCargoId,
		          Total,
		          NTotal
		        )
		SELECT @BillNumberID,
				C.CouponCode,
				@BILLTYPE,
				@billdate,
				C.ID,
				ct.CouponId,
				1,--在库
				@InKtypeId,
				@OutKtypeid,
				CI.inCargoId,
				0,
				dbo.F_RoundTotal(CI.Price),
				dbo.F_RoundTotal(ci.Price)
			FROM #CurCoupon_Bill C
			LEFT JOIN Coupon_AllotBillStype CI ON C.ID=CI.ID
			LEFT JOIN coupon_TypeInfo CT ON CT.CouponId=Ci.CouponId	
		
	END
	ELSE IF(@BillType=429)
	BEGIN
		set @tmpKtypeId=@InKtypeId
		--券编码信息处理，仓库改变，货位改变，状态改变
		UPDATE  Coupon_CodeInfo
		SET		[state]=7	--分支机构调拨出库
		FROM Coupon_CodeInfo CO
		INNER JOIN #CurCoupon_Bill C ON CO.CouponCode=c.CouponCode
		LEFT JOIN dbo.Coupon_AllotBillStype ci ON ci.id=c.Id
		
		
		INSERT INTO Coupon_CodeInOut
		        ( BillnumberId ,
		          CouponCode ,
		          BillType ,
		          billdate ,
		          DetailId ,
		          CouponId ,
		          State ,
		          InKtypeId ,
		          OutKtypeid ,
		          InCargoId ,
		          OutCargoId,
		          Total,
		          NTotal
		        )
		SELECT @BillNumberID,
				C.CouponCode,
				@BILLTYPE,
				@billdate,
				C.ID,
				ct.CouponId,
				7,--出库
				@InKtypeId,
				@OutKtypeid,
				0,
				CI.outCargoId,
				dbo.F_RoundTotal(CI.Price),
				dbo.F_RoundTotal(ci.Price)
			FROM #CurCoupon_Bill C
			LEFT JOIN Coupon_AllotBillStype CI ON C.ID=CI.ID
			LEFT JOIN coupon_TypeInfo CT ON CT.CouponId=Ci.CouponId
		
	END
	
	--写listtable,SType_InnerARTotal表
	declare @ATypeID varchar(50),@ETypeID varchar(50),@DTypeID varchar(50),@strSTypeID2 varchar(50),
	@TotalMoney NUMERIC(24, 10),@strErrMsg varchar(500),@CID NUMERIC(24, 10),@rate NUMERIC(24, 10)
	
	
	SELECT @ETypeID=etypeid,@DTypeID=DTypeId,@STypeID=Stypeid,@CID=CID,@rate=Rate,@TotalMoney=totalmoney
	FROM Coupon_BillIndex
	WHERE BillNumberId=@BillNumberID

	
	DECLARE @AtypeTotalMoney NUMERIC(24, 10)
	SET @AtypeTotalMoney=@TotalMoney*(-1)
	IF @BillType=428
	BEGIN
		
		EXEC GP_CreateMX_InsertList @BillNumberID,@billdate,@BillType,56,'',@ETypeID,
		@TotalMoney,'','',@DTypeID,@STypeID,@CID,@TotalMoney,@rate
		EXEC GP_AType_Total_AddEdit	56,@STypeID,@CID,@TotalMoney,@TotalMoney,@strErrMsg OUTPUT
		
		
		EXEC GP_CreateMX_InsertList @BillNumberID,@billdate,@BillType,28,'',@ETypeID,
		@AtypeTotalMoney,'','',@DTypeID,@STypeID,@CID,@TotalMoney,@rate
		EXEC GP_AType_Total_AddEdit	28,@STypeID,@CID,@AtypeTotalMoney,@AtypeTotalMoney,@strErrMsg OUTPUT
	END
	
	IF @BillType=429
	BEGIN
		EXEC GP_CreateMX_InsertList @BillNumberID,@billdate,@BillType,56,'',@ETypeID,
		@AtypeTotalMoney,'','',@DTypeID,@STypeID,@CID,@TotalMoney,@rate
		EXEC GP_AType_Total_AddEdit	56,@STypeID,@CID,@AtypeTotalMoney,@AtypeTotalMoney,@strErrMsg OUTPUT
		
		
		EXEC GP_CreateMX_InsertList @BillNumberID,@billdate,@BillType,28,'',@ETypeID,
		@TotalMoney,'','',@DTypeID,@STypeID,@CID,@TotalMoney,@rate
		EXEC GP_AType_Total_AddEdit	28,@STypeID,@CID,@TotalMoney,@TotalMoney,@strErrMsg OUTPUT
	END
	
	
	--写内部应收
	--EXEC GP_InnerARTotal_AddEdit @BillNumberID,@TotalMoney,0,@strErrMsg OUT
	IF @BillType IN (428,429)
	BEGIN
		SELECT @strSTypeID2=STypeID FROM Stock WHERE typeId=@tmpKtypeId
	END
	
	IF NOT EXISTS(SELECT STypeID FROM SType_InnerARTotal WHERE STypeID=@STypeID AND STypeID2=@strSTypeID2)
	BEGIN
		INSERT INTO SType_InnerARTotal(STypeID,STypeID2,InnerARTotal)
		VALUES(@STypeID,@strSTypeID2,case @BillType when 429 then @TotalMoney else @AtypeTotalMoney end)		
	END
	ELSE
	BEGIN
		UPDATE SType_InnerARTotal
		SET InnerARTotal=case @BillType when 429 then ISNULL(InnerARTotal,0)+@TotalMoney else ISNULL(InnerARTotal,0)+@AtypeTotalMoney end
		WHERE STypeID=@STypeID AND STypeID2=@strSTypeID2
	END
	
	update listtable set Audited=1 where billnumberid=@BillNumberID
	
	
DROP TABLE #CurCoupon_Bill

-------------------------------------------------------单据过账 end----------------------------------------------------
-------------------------------------------------------往来过账 begin----------------------------------------------------
DECLARE
		@datBillDate			DATETIME,					-- 单据日期
		@chvATypeID				VARCHAR(50),				-- 收付款账户 ID 值
		@chvBTypeID				VARCHAR(50),				--结算单位
		@chvDealBTypeID			VARCHAR(50),				--往来单位
		@chvETypeID				VARCHAR(50),				-- 经手人 ID 值
		@chvKTypeID				VARCHAR(50),				-- 出库仓库 ID 值
		@chvKTypeID2			VARCHAR(50),				-- 入库仓库 ID 值
		@chvDTypeID				VARCHAR(50),				--部门
		@chvSTypeID				VARCHAR(50),	
		@numTotalMoney			 NUMERIC(24, 10) ,				-- 单据金额合计
		@numTotalInMoney		 NUMERIC(24, 10) ,				-- 单据实收、实付金额
		@numPreferenceMoney		 NUMERIC(24, 10) ,
		@numNTotalMoney			 NUMERIC(24, 10) ,
		@numNTotalInMoney		 NUMERIC(24, 10) ,
		@numNPreferenceMoney	 NUMERIC(24, 10) ,
		@wxTotal				 NUMERIC(24, 10) ,	
		@numTax					 NUMERIC(24, 10) ,
		@ifIndexWX				TINYINT,
		@intCostSale			TINYINT,
		@intCID					INT,
		@ifCheck				VARCHAR(10),				-- 是否草稿标识，f - 草稿；t - 已过账
		@IfMulAccount			TINYINT,
		@intVipCardID			INT,
		@BillName				VARCHAR(100),
		@NumRate				 NUMERIC(24, 10) ,
		@AssetBusinessTypeId    INT,
		@intRedWord				TINYINT,
		@intNewPosBill			TINYINT,
		@AuditType				INT,
		@IfLend					INT=0,
		@datPostTime			DATETIME ,
		@vipCentInfo			varchar(200)='' ,
		@VipCardCode			VARCHAR(200)=''
		
	SELECT	
					
				@datBillDate = BillDate,		
				@chvATypeID = ATypeID,			
				@chvBTypeID = BTypeID,				
				@chvDealBTypeID=DealBTypeID,	
				@chvETypeID = ETypeID,				
				@chvKTypeID = InKTypeId,			
				@chvKTypeID2 = OutKTypeId,			
				@chvDTypeID	=DTypeID,				
				@chvSTypeID=STypeID,				
				@numTotalMoney = TotalMoney,		
				@numTotalInMoney = TotalInMoney,
				@numPreferenceMoney = PreferenceMoney,
				@numNTotalMoney = NTotalMoney,
				@numNTotalInMoney = NTotalInMoney,
				@numNPreferenceMoney = NPreferenceMoney,
				@wxTotal=0,
				@numTax = 1,
				@ifIndexWX = 0,
				@intCostSale=0,
				@intCID = CID,
				@NumRate = Rate,
				@ifCheck =IfCheck ,			
				@IfMulAccount=IfMulAccount,
				@intVipCardID = 0,
				@AssetBusinessTypeId=0,
				@intRedWord=RedWord,
				@intNewPosBill=0,
				@IfLend = 0,
				@datPostTime=posttime
	FROM	dbo.Coupon_BillIndex
	WHERE	BillNumberID = @BillNumberID 
	--报损报溢没有往来 不计入listtable
	IF @chvBTypeID IS NOT NULL AND @chvBTypeID<>'' 		
	EXEC @nRet = GP_AuditArAp @BillNumberID,0,@BillType,@datBillDate,@chvATypeID,@chvBTypeID,@chvETypeID,@chvKTypeID,@chvKTypeID2,
			@chvDTypeID,@chvSTypeID,@numTotalMoney,@numTotalInMoney,@numPreferenceMoney,@numNTotalMoney,
			@numNTotalInMoney,@numNPreferenceMoney,@numTax,@ifIndexWX,@intCostSale,@IfMulAccount,@wxTotal,@intVipCardID,
			@intCID,@NumRate,@AuditType,@intNewPosBill,@voucherMsg OUTPUT,@vipCentInfo output,@VipCardCode OUT
		
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN auditPoint
		COMMIT TRAN audit
		RETURN @nRet
	END
	
	
EXEC @nRet = GP_AuditingATypeBalanceCheck @BillNumberID,@BillType, @voucherMsg OUTPUT				
IF @nRet <> 0
	RETURN @nRet
-------------------------------------------------------处理结算状态 begin----------------------------------------------------
IF @BILLTYPE <>425  --调拨单 jsstate 都为0
BEGIN
	IF @numTotalInMoney+@numPreferenceMoney=@numTotalMoney
	BEGIN
		IF @numTotalMoney=0
		BEGIN
			UPDATE Coupon_BillIndex
			SET JsState=2
			WHERE BillNumberID=@BillNumberID 
		END
		ELSE
		BEGIN
			UPDATE Coupon_BillIndex
			SET JsState=2
			WHERE BillNumberID=@BillNumberID
		END
	END
	ELSE
	BEGIN
		IF @numTotalInMoney=0
		BEGIN
			UPDATE Coupon_BillIndex
			SET JsState=0
			WHERE BillNumberID=@BillNumberID
		END
		ELSE
		BEGIN
			UPDATE Coupon_BillIndex
			SET JsState=1
			WHERE BillNumberID=@BillNumberID
		END
	END
END
-------------------------------------------------------处理结算状态 end----------------------------------------------------

-------------------------------------------------------往来过账 end----------------------------------------------------
EXEC @nRet = GP_AuditingCheckBillData @BillNumberID,@BillType,'1'
IF @nRet <> 0 
	RETURN @nRet
	
-------------------------------------------------------影响 BType、AType 数据表中的应收应付数据 begin----------------------------------------------------
IF @BillType IN (423,424,426) AND @chvBTypeID IS NOT NULL AND @chvBTypeID <>'' --调拨暂时不做
BEGIN 
EXEC @nRet = Gp_CreateManageRep @BillNumberID,@BillType
IF @nRet <> 0 
	RETURN @nRet

END
-------------------------------------------------------影响 BType、AType 数据表中的应收应付数据 end----------------------------------------------------



END
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	自动生单
	作    者：	冯波
	
*/
CREATE             PROCEDURE GP_Auditing_CreateBill
(
	@nBillID			NUMERIC(10,0),
	@chvOpID			VARCHAR(50),
	@BillType			INT,
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@intCostSale		TINYINT,
	@intCID				INT,
	@SZPID				VARCHAR(1000)	OUT,
	@intReturnID		BIGINT	OUT,
	@strReturnBillCode	VARCHAR(200)	OUT,
	@strErrMsg			VARCHAR(1000)	OUT
	
)
--@encode$--
AS
	SET NOCOUNT ON
	
	DECLARE @nRet INT,			-- 返回的出错值
	       @intDeliveryBack	INT, --是否勾选配置
	       @ispos INT      --是否pos过来的验收单，pos的验收是自己生成的，这里需要排除开
	
SELECT @intDeliveryBack=Value FROM Userconfig WHERE ConfigName='Postransautodraft'	
SELECT TOP (1) @ispos=PosId FROM dbo.PosAllotApplyBillIndex WHERE BillType=@BillType AND BillNumberId=@nBillID

	IF @BillType IN (187)				--分支机构间调拨出库单生成入库单
	BEGIN
		EXEC GP_STypeMoveOutBill_CreateBill
			@chvOpID,
			@nBillID,
			@intReturnID OUT,		--新生成的单据的ID
			@strReturnBillCode OUT,
			@strErrMsg OUT		--出错信息	
	END
	ELSE IF @BillType IN (66)			---分支机构间付款单生成生成收款单
	BEGIN
		EXEC GP_STypeGatherPayBill_CreateDraft
			@chvOpID,
			@BillType,
			@nBillID,
			@chvBTypeID,
			@chvSTypeID,
			@intReturnID OUT,
			@strReturnBillCode OUT,
			@strErrMsg OUT
	END
	ELSE IF @BillType=11				--分支机构间销售出库单生成采购入库单
	BEGIN
		EXEC GP_Auditing_DealInnerSale
			@nBillID,
			@BillType,
			@intCostSale,
			@intCID,
			@chvOpID,
			@nRet	OUT,
			@szPID OUT,
			@intReturnID OUT,		
			@strReturnBillCode OUT,
			@strErrMsg OUT
	END
	ELSE IF @BillType IN (6)			--分支机构间采购退货单生成销售退货单
	BEGIN
		EXEC GP_BuyBackBill_CreateBill
			@chvOpID,
			@nBillID,
			@intReturnID OUT,		--新生成的单据的ID
			@strReturnBillCode OUT,
			@strErrMsg OUT		--出错信息	
	END
	ELSE IF @BillType IN (429)				--分支机构间调拨出库单生成入库单
	BEGIN
		EXEC GP_CouponStypeOutBill_CreateBill
			@chvOpID,
			@nBillID,
			@intReturnID OUT,		--新生成的单据的ID
			@strReturnBillCode OUT,
			@strErrMsg OUT		--出错信息	
	END
	ELSE IF @BillType IN (329) AND @intDeliveryBack=1 AND @ispos=0			--验收单生成未完成数量的
	BEGIN
		EXEC GP_DeliveryBackBill_CreateBill
			@chvOpID,
			@nBillID,
			@intReturnID OUT,		--新生成的单据的ID
			@strReturnBillCode OUT,
			@strErrMsg OUT		--出错信息	
	END
	
	RETURN @nRet
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	新固定资产
	作    者：	冯波
	修改时间：	
*/
CREATE             PROCEDURE Gp_Auditing_DealAssest
(
	@nBillID				NUMERIC(10,0),				-- 单据 ID 号
	@chvOpID				VARCHAR(50) = '',			-- 当前操作员 ID 值
	@billtype				INT = 0,						-- 单据类型
	@intRedWord				TINYINT,
	@datBillDate			DATETIME,
	@AssetBusinessTypeId	INT,
	@chvSTypeID				VARCHAR(50),
	@Ret					INT	OUT,
	@AssetMsg				VARCHAR(MAX) OUT

)
--@encode$--
AS
	SET NOCOUNT ON
	
	SELECT
		@Ret=0, 
		@AssetMsg=''
	
	DECLARE
		@intAssestCardID		INT,
		@strAssestCardFullName	VARCHAR(200)
	
	IF @billtype IN (212,213,214)
	BEGIN
		IF @intRedWord=0
		BEGIN
			IF @billtype=214
			BEGIN
				--当期怎么取呢?
				
				IF EXISTS(
							SELECT a.BillNumberId
							FROM  DepBill a
							INNER JOIN Ac_AssetsCards b
							ON a.AssetCardId=b.ID
							INNER JOIN BillIndex p
							ON a.BillNumberId=p.BillNumberId
							INNER JOIN Ac_Period x
							ON p.BillDate BETWEEN x.FBegin AND x.FEnd
							WHERE a.BillNumberId=@nBillID
							AND b.DepreciationMean=5
							AND EXISTS
							(
								SELECT c.BillNumberId
								FROM  DepBill c
								INNER JOIN BillIndex d
								ON c.BillNumberId=d.BillNumberId
								INNER JOIN Ac_AssetsCards y
								ON c.AssetCardId=y.ID
								WHERE d.BillNumberId<>@nBillID
								AND y.DepreciationMean=5
								AND d.ifcheck='t'
								AND d.RedWord=0
								AND c.AssetCardId=a.AssetCardId
								AND d.BillDate BETWEEN x.FBegin AND x.FEnd
							)
				)
				BEGIN
					SET @AssetMsg='工作量法当期只能折旧一次'
					SET @Ret=222
					RETURN
				END
				
				
				IF EXISTS(
							SELECT a.BillNumberID FROM dbo.DepBill a
							INNER JOIN dbo.BillIndex b
							ON a.BillNumberId=b.BillNumberId
							INNER JOIN dbo.Ac_AssetsCards c
							ON a.AssetCardId=c.ID
							WHERE a.BillNumberId=@nBillID
							AND c.DepreciationMean=5
							AND a.WorkTime+c.FinishWork>c.ExpectWork
				)
				BEGIN
					SELECT
						@strAssestCardFullName=C.FullName
						FROM dbo.DepBill a
						INNER JOIN dbo.BillIndex b
						ON a.BillNumberId=b.BillNumberId
						INNER JOIN dbo.Ac_AssetsCards c
						ON a.AssetCardId=c.ID
						WHERE a.BillNumberId=@nBillID
						AND c.DepreciationMean=5
						AND a.WorkTime+c.FinishWork>c.ExpectWork
						AND a.id IN 
						(
							SELECT MIN(a.ID) AS ID 
							FROM dbo.DepBill a
							INNER JOIN dbo.BillIndex b
							ON a.BillNumberId=b.BillNumberId
							INNER JOIN dbo.Ac_AssetsCards c
							ON a.AssetCardId=c.ID
							WHERE a.BillNumberId=@nBillID
							AND c.DepreciationMean=5
							AND a.WorkTime+c.FinishWork>c.ExpectWork
						)
				
				
					SET @AssetMsg='固定资产'+'要提工作量将超过预计工作总量'
					SET @Ret=221
					RETURN
				END
				
			
				DECLARE AssestCursor CURSOR FOR		
					SELECT AssetCardId 
					FROM DepBill
					WHERE BillNumberId=@nBillID
					
				OPEN AssestCursor

				FETCH NEXT FROM AssestCursor INTO @intAssestCardID

				WHILE @@FETCH_STATUS = 0 AND @Ret=0
					BEGIN
						SELECT @Ret=0
						
						
						
						IF EXISTS(
							SELECT ID
							FROM Ac_AssetsCards_History
							WHERE AssertsCardId=@intAssestCardID
							AND BusinessDate>@datBillDate
							AND BillType<>0 AND BillType<>-3
						)
						BEGIN
							SELECT @strAssestCardFullName=FullName
							FROM Ac_AssetsCards
							WHERE ID=@intAssestCardID
						
							SET @AssetMsg='资产编号['+@strAssestCardFullName+']在本单据日期之后已有操作记录，不能进行该操作!'
							
							CLOSE AssestCursor
							DEALLOCATE AssestCursor
							
							SET @Ret=210
							RETURN
						END
						
						
						EXEC	@Ret=Gp_SaveAssetsCardHistory
							@chvSTypeID,
							@intAssestCardID,
							@chvOpID,
							@datBillDate,
							@billtype,
							@nBillID,
							@AssetBusinessTypeId,
							@AssetMsg OUT

						FETCH NEXT FROM AssestCursor INTO @intAssestCardID
					END
					
				CLOSE AssestCursor
				DEALLOCATE AssestCursor
				
				--WHERE BillNumberId
			END
			ELSE
			BEGIN
				DECLARE AssestCursor CURSOR FOR		
					SELECT AssetCardId 
					FROM AssetIncDecBill
					WHERE BillNumberId=@nBillID
					
				OPEN AssestCursor

				FETCH NEXT FROM AssestCursor INTO @intAssestCardID

				WHILE @@FETCH_STATUS = 0 AND @Ret=0
				BEGIN
					SELECT @Ret=0
					
					IF EXISTS(
							SELECT ID
							FROM Ac_AssetsCards_History
							WHERE AssertsCardId=@intAssestCardID
							AND BusinessDate>@datBillDate
							AND BillType<>0 AND BillType<>-3
					)
					BEGIN
						SELECT @strAssestCardFullName=FullName
						FROM Ac_AssetsCards
						WHERE ID=@intAssestCardID
						
						
						SET @AssetMsg='资产编号['+@strAssestCardFullName+']在本单据日期之后已有操作记录，不能进行该操作!'
						
						CLOSE AssestCursor
						DEALLOCATE AssestCursor
						
						
						SET @Ret=210
						RETURN 
					END
					
					
					
					EXEC	@Ret=Gp_SaveAssetsCardHistory
						@chvSTypeID,
						@intAssestCardID,
						@chvOpID,
						@datBillDate,
						@billtype,
						@nBillID,
						@AssetBusinessTypeId,
						@AssetMsg OUT
						
					IF @billtype=212 AND @Ret=0
					BEGIN
						EXEC Gp_CreateDepreciationPlan @intAssestCardID,2
					END

					FETCH NEXT FROM AssestCursor INTO @intAssestCardID
				END
					
				CLOSE AssestCursor
				DEALLOCATE AssestCursor
			END
		END
		ELSE
		BEGIN
			IF @billtype=214
			BEGIN
				DECLARE AssestCursor CURSOR FOR		
					SELECT AssetCardId 
					FROM DepBill
					WHERE BillNumberId=@nBillID
					
				OPEN AssestCursor

				FETCH NEXT FROM AssestCursor INTO @intAssestCardID

				WHILE @@FETCH_STATUS = 0 AND @Ret=0
				BEGIN
					SELECT
						@Ret=0
						
					IF EXISTS(
							SELECT ID
							FROM Ac_AssetsCards_History
							WHERE AssertsCardId=@intAssestCardID
							AND BusinessDate>@datBillDate
							AND BillType<>0 AND BillType<>-3
					)
					BEGIN
						SELECT @strAssestCardFullName=FullName
						FROM Ac_AssetsCards
						WHERE ID=@intAssestCardID
					
						SET @AssetMsg='资产编号['+@strAssestCardFullName+']在本单据日期之后已有操作记录，不能进行该操作!'
						
						CLOSE AssestCursor
						DEALLOCATE AssestCursor
						
						SET @Ret=210
						RETURN
					END
						
					EXEC	@Ret=Gp_ReturnAssetsCardHistory
						@chvSTypeID,
						@intAssestCardID,
						@billtype,
						@nBillID
						
					FETCH NEXT FROM AssestCursor INTO @intAssestCardID
				END
					
				CLOSE AssestCursor
				DEALLOCATE AssestCursor
				
				--WHERE BillNumberId
			END
			ELSE
			BEGIN
					
				DECLARE AssestCursor CURSOR FOR		
					SELECT AssetCardId 
					FROM AssetIncDecBill
					WHERE BillNumberId=@nBillID
					
				OPEN AssestCursor

				FETCH NEXT FROM AssestCursor INTO @intAssestCardID

				WHILE @@FETCH_STATUS = 0 AND @Ret=0
				BEGIN
					SELECT
						@Ret=0
						
					IF EXISTS(
							SELECT ID
							FROM Ac_AssetsCards_History
							WHERE AssertsCardId=@intAssestCardID
							AND BusinessDate>@datBillDate
							AND BillType<>0 AND BillType<>-3
					)
					BEGIN
						SELECT @strAssestCardFullName=FullName
						FROM Ac_AssetsCards
						WHERE ID=@intAssestCardID
					
						SET @AssetMsg='资产编号['+@strAssestCardFullName+']在本单据日期之后已有操作记录，不能进行该操作!'
						
						CLOSE AssestCursor
						DEALLOCATE AssestCursor
						
						SET @Ret=210
						RETURN
					END
						
					EXEC	@Ret=Gp_ReturnAssetsCardHistory
						@chvSTypeID,
						@intAssestCardID,
						@billtype,
						@nBillID

					FETCH NEXT FROM AssestCursor INTO @intAssestCardID
				END
					
				CLOSE AssestCursor
				DEALLOCATE AssestCursor
			END
		END			
	END 

	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*



*/





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理成本价销售
	返回结果：
	作    者：冯波
	创建时间：2012-07-26
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DealCostSale
(
	@nBillID				NUMERIC(10,0),
	@nBillType				INT,
	@intCostSale			INT,
	@CID					INT,
	@chvOpID				VARCHAR(50),
	@nRet					INT	OUT,
	@szPID					VARCHAR(100) OUT,
	@intReturnID			INT OUT,		
	@strReturnBillCode		VARCHAR(1000) OUT,
	@strErrMsg				VARCHAR(100) OUT
)
--@encode$--
AS
		DECLARE	@AVERAGE	smallint,
				@FIFO		smallint,
				@LIFO		smallint,
				@HAND		smallint

		SET @AVERAGE	= 0		-- 移动加权平均算法
		SET @FIFO		= 1		-- 先进先出
		SET @LIFO		= 2		-- 后进先出
		SET @HAND		= 3		-- 手工指定法
		
		DECLARE	@nCostingMethod	INT
		
		EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
		
		DECLARE
			@intQtyDot			VARCHAR(10),
			@intPriceDot		VARCHAR(10),
			@intMoneyDot		VARCHAR(10),
			@intDiscountDot		VARCHAR(10),
			@intTaxDot			VARCHAR(10),
			@intCRateDot		VARCHAR(10),
			@intTRateDot		VARCHAR(10)		
			
		EXEC	GP_Post_Dot
			@intQtyDot	OUT,
			@intPriceDot	OUT,
			@intMoneyDot	OUT,
			@intDiscountDot	OUT,
			@intTaxDot	OUT,
			@intCRateDot	OUT,
			@intTRateDot	OUT

		IF @intCostSale=1
		BEGIN
			EXEC	GP_Auditing_DealSaleBill
				@nBillID,
				11,
				1,
				@CID		
			
			
	
			--需要写入应收金额，主营业务收入，税金金额，积分等
			EXEC @nRet=GP_Auditing_SaleListTable @nBillID
			
			IF @nRet <> 0
			BEGIN
				--ROLLBACK TRAN
				RETURN @nRet
			END
		
			
			-- 检查账户余额，是否过账后会 < 0
			EXEC @nRet = GP_AuditingATypeBalanceCheck @nBillID,@nBillType, @szPID OUTPUT
			IF @nRet <> 0
			BEGIN
				--ROLLBACK TRAN
				RETURN @nRet
			END
			
			
			EXEC Gp_CreateManageRep @nBillID,@nBillType
			--销售金额，如果启用了按成本价销售，之前计算的时候是没有取到值的，所以更改了价格后需要重新计算一次应收应付
			EXEC GP_AuditBrandarArAp @nBillID,@nBillType
			
		END
		
		

	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理受托收货可以按照成本价收货入库
	返回结果：
	作    者：冯波
	创建时间：2015-10-13
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DealCostSaleCommission
(
	@nBillID				NUMERIC(10,0),
	@BillType				INT,
	@intCostSale			INT,
	@intCID					INT,
	@chvOpID				VARCHAR(50),
	@datBillDate			DATETIME,
	@chvBTypeID				VARCHAR(50),
	@chvETypeID				VARCHAR(50),
	@chvDTypeID				VARCHAR(50),
	@chvSTypeID				VARCHAR(50),
	@nRet					INT	OUT,
	@strErrMsg				VARCHAR(100) OUT
)
--@encode$--
AS
		DECLARE	@AVERAGE	smallint,
				@FIFO		smallint,
				@LIFO		smallint,
				@HAND		smallint

		SET @AVERAGE	= 0		-- 移动加权平均算法
		SET @FIFO		= 1		-- 先进先出
		SET @LIFO		= 2		-- 后进先出
		SET @HAND		= 3		-- 手工指定法
		
		DECLARE	@nCostingMethod	INT
		
		EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
		
		DECLARE
		@strQtyDot			VARCHAR(10),
		@strPriceDot		VARCHAR(10),
		@strMoneyDot		VARCHAR(10),
		@strDiscountDot		VARCHAR(10),
		@strTaxDot			VARCHAR(10),
		@strCRateDot		VARCHAR(10),	
		@strTRateDot		VARCHAR(10)
		
		EXEC	GP_Post_Dot
			@strQtyDot	OUT,
			@strPriceDot	OUT,
			@strMoneyDot	OUT,
			@strDiscountDot	OUT,
			@strTaxDot	OUT,
			@strCRateDot OUT,
			@strTRateDot	OUT

		


		IF @intCostSale=1
		BEGIN
			DECLARE 
				@strTemp	VARCHAR(MAX),
				@strOPRate	VARCHAR(50),
				@sysCid		INT,
				@decRate	NUMERIC(24,10)
				
			SELECT TOP 1 @SysCid=CId FROM Ac_Currency WHERE Sysrow = 1
			
			SELECT @strOPRate=BasisType,@decRate=Rate
			FROM Ac_Currency				
			WHERE CId=@intCID
			
			DECLARE
				@GOODS_ID			VARCHAR(50),
				@DXGOODSMONEY_ID	VARCHAR(50)
				
			SELECT @GOODS_ID=NID FROM ac_items WHERE UserCode='1241'  -- 『库存商品总值合计』,0000100001
			SELECT @DXGOODSMONEY_ID=NID FROM ac_items WHERE UserCode='2141'  -- 『代销商品款』,0000200003				
			
			IF @strOPRate='0'
			BEGIN
				SELECT @strOPRate='/'
			END
			ELSE
			BEGIN
				SELECT @strOPRate='*'
			END
			
			
			
			SELECT @strTemp='
			UPDATE CommissionBill
			SET 
				SalePrice=ROUND(CAST(ROUND(b.CostTotal,'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+'),SaleTotal=b.CostTotal,				
				DiscountPrice=ROUND(CAST(ROUND(b.CostTotal,'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+'),Total=b.CostTotal,
				TaxTotal=ROUND(b.CostTotal*(1+CommissionBill.Tax/100),'+@strMoneyDot+'),
				NSalePrice=ROUND(CAST(ROUND(b.NCostTotal,'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+') ,NSaleTotal=b.NCostTotal,				
				NDiscountPrice=ROUND(CAST(ROUND(b.NCostTotal,'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+'),
				CostPrice=ROUND(CAST(ROUND(b.CostTotal,'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+'),
				GoodsCostPrice=ROUND(CAST(ROUND(b.CostTotal,'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+')
				
			FROM 
			(
				SELECT a.ID,b.Rate,SUM(Qty) AS Qty,ROUND(SUM(a.CostTotal)'+@strOPRate+'b.Rate,'+@strMoneyDot+') AS NCostTotal,SUM(a.CostTotal) AS CostTotal
				FROM InOutStockTable a
				INNER JOIN BillIndex b
				ON a.BillNumberId=b.BillNumberId
				WHERE a.BillNumberID='+CAST(@nBillID AS VARCHAR(50)) +'
				AND a.IsService=0
				AND a.KtypeId<>''10000''
				GROUP BY a.ID,b.Rate
			) b
			WHERE CommissionBill.ID=b.ID AND CommissionBill.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			
			

			
			UPDATE CommissionBill
			SET 
				NTotal=ROUND(CommissionBill.SaleTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+'),
				NTaxTotal=ROUND(CommissionBill.TaxTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+'),
				TaxMoney=CommissionBill.TaxTotal-CommissionBill.Total,
				NTaxMoney=ROUND(CommissionBill.TaxTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+')-ROUND(CommissionBill.SaleTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+'),
				Taxprice=CASE CommissionBill.Tax WHEN 0 THEN CommissionBill.DiscountPrice ELSE CASE CommissionBill.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(CommissionBill.TaxTotal AS  NUMERIC(24, 10) )/CAST(CommissionBill.Qty AS  NUMERIC(24, 10) ),'+@strPriceDot+') END END,
				NTaxprice=CASE WHEN b.Rate=1 AND CommissionBill.Tax=0 THEN CommissionBill.DiscountPrice ELSE CASE CommissionBill.Qty WHEN 0 THEN 0 ELSE ROUND(CAST((ROUND(CommissionBill.TaxTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+')) AS  NUMERIC(24, 10) )/CAST(CommissionBill.Qty AS  NUMERIC(24, 10) ),'+@strPriceDot+') END END
			FROM BillIndex b
			WHERE CommissionBill.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND CommissionBill.BillNumberID=b.BillNumberID
			
			
			
			UPDATE CommissionBill
			SET MsalePrice=ROUND(SalePrice*MUnitRate,'+@strPriceDot+'),
			MDiscountPrice=ROUND(DiscountPrice*MUnitRate,'+@strPriceDot+'),
			MTaxPrice=ROUND(TaxPrice*MUnitRate,'+@strPriceDot+'),
			CurMSalePrice=ROUND(NSalePrice*MUnitRate,'+@strPriceDot+'),
			CurMDiscountPrice=ROUND(NDiscountPrice*MUnitRate,'+@strPriceDot+'),
			CurMTaxPrice=ROUND(NTaxPrice*MUnitRate,'+@strPriceDot+')
			WHERE BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			
			
			

			UPDATE BillIndex
			SET TotalMoney=ROUND(ISNULL(b.TotalMoney,0),'+@strMoneyDot+'),NTotalMoney=ROUND(ISNULL(b.NTotalMoney,0),'+@strMoneyDot+')
			FROM 
			(
				SELECT BillNumberID,SUM(TaxTotal) AS TotalMoney,SUM(NTaxTotal) AS NTotalMoney
				FROM CommissionBill 
				WHERE BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
				GROUP BY BillNumberID
			) b
			WHERE BillIndex.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+' AND BillIndex.BillNumberID=b.BillNumberID


			UPDATE InOutStockTable
			SET Price=b.CostPrice,SalePrice=b.CostPrice,TaxPrice=b.TaxPrice,Discount=1,
			Total=b.Total,SaleTotal=b.SaleTotal,TaxTotal=b.TaxTotal,
			NPrice=b.NSalePrice,NTotal=b.NSaleTotal,NSalePrice=b.NSalePrice,NSaleTotal=b.NSaleTotal,NTaxPrice=b.NTaxPrice,NTaxTotal=b.NTaxTotal	
			FROM CommissionBill b
			WHERE InOutStockTable.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND InOutStockTable.BillNumberID=b.BillNumberId
			AND InOutStockTable.ID=b.ID
			AND InOutStockTable.IsService=0
			
			'
			
			--PRINT @strTemp
			
	
			EXEC(@strTemp)		
			
			DECLARE
				@numNoTaxTotal	NUMERIC(24,10)
			
	
			--需要写入库存商品总值,受托代销商品款等
			-- ********* 处理生成 ListTable 凭证记录 *********
			SELECT	@numNoTaxTotal = ISNULL(SUM(Total),0)--,@numNNoTaxTotal = ISNULL(SUM(NTotal),0)
			FROM	InOutstocktable
			WHERE	BillNumberID = @nBillID AND KtypeId<>'10000'

			IF @numNoTaxTotal <> 0 AND @intCostSale=1
			BEGIN
				-- 库存商品总值
				EXEC @nRet = GP_CreateMX_InsertList @nBillID,@datBillDate,@BillType,@GOODS_ID,@chvBTypeID,@chvETypeID,
					@numNoTaxTotal,'','',@chvDTypeID,@chvSTypeID,@sysCid,@numNoTaxTotal,1
		
				
				
				-- 受托代销商品款
				EXEC @nRet = GP_CreateMX_InsertList @nBillID,@datBillDate,@BillType,@DXGOODSMONEY_ID,@chvBTypeID,@chvETypeID,
					@numNoTaxTotal,'','',@chvDTypeID,@chvSTypeID,@sysCid,@numNoTaxTotal,@decRate
			
			END

			
			IF @nRet <> 0
			BEGIN
				--ROLLBACK TRAN
				RETURN @nRet
			END
		
			
			--还需要修改COMMISSIONSTOCK中的TOTAL值,数量不需要改
			UPDATE CommissionStock
			SET Total=CommissionStock.Total+b.Total
			FROM
			(
				SELECT PtypeId,@chvBTypeID AS BTypeID,SUM(CostTotal) AS Total
				FROM InoutStockTable
				WHERE BillNumberID=@nBillID AND BillType=144 AND KTypeID<>'10000'
				GROUP BY PtypeId
			) b
			WHERE CommissionStock.Ptypeid=b.PtypeId
			AND CommissionStock.Btypeid=b.BtypeId
			AND CommissionStock.Type=144
			
		
			EXEC Gp_CreateManageRep @nBillID,@BillType
			
	
			UPDATE OrderBill 
			SET 
			ReachTotal=ISNULL(ReachTotal,0)+b.total,
			ReachTaxTotal=ISNULL(ReachTaxTotal,0)+b.TaxTotal
			FROM CommissionBill b 
			where OrderBill.OrderID=b.OrderID AND b.BillNumberId=@nBillID

		END
		
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID				NUMERIC(10,0),
	@BillType				INT,
	@intCostSale			INT,
	@intCID					INT,
	@chvOpID				VARCHAR(50),
	@datBillDate			DATETIME,
	@chvBTypeID				VARCHAR(50),
	@chvETypeID				VARCHAR(50),
	@chvDTypeID				VARCHAR(50),
	@chvSTypeID				VARCHAR(50),
	@nRet					INT,
	@strErrMsg				VARCHAR(100)
	
SELECT
	@nBillID=2,
	@BillType=144,
	@intCostSale=1,
	@intCID=1,
	@chvOpID='00001',
	@datBillDate=GETDATE(),
	@chvBTypeID='0000200001',
	@chvETypeID='00001',
	@chvDTypeID='00001',
	@chvSTypeID='00001'
	

BEGIN TRAN	

EXEC GP_Auditing_DealCostSaleCommission
	@nBillID,
	@BillType,
	@intCostSale,
	@intCID,
	@chvOpID,
	@datBillDate,
	@chvBTypeID,
	@chvETypeID,
	@chvDTypeID,
	@chvSTypeID,
	@nRet	OUT,
	@strErrMsg OUT

SELECT @nRet,@strErrMsg

ROLLBACK TRAN

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理分支机构间销售
	返回结果：
	作    者：冯波
	创建时间：2012-07-26
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DealInnerSale
(
	@nBillID				NUMERIC(10,0),
	@nBillType				INT,
	@intCostSale			INT,
	@CID					INT,
	@chvOpID				VARCHAR(50),
	@nRet					INT	OUT,
	@szPID					VARCHAR(100) OUT,
	@intReturnID			INT OUT,		
	@strReturnBillCode		VARCHAR(1000) OUT,
	@strErrMsg				VARCHAR(100) OUT
)
--@encode$--
AS
		EXEC	GP_Auditing_DealCostSale
			@nBillID,
			@nBillType,
			@intCostSale,
			@CID,
			@chvOpID,
			@nRet	OUT,
			@szPID OUT,
			@intReturnID OUT,		
			@strReturnBillCode OUT,
			@strErrMsg OUT
		
		--IF @nRet<>0 RETURN
		
		EXEC GP_SaleBill_CreateBill
			@chvOpID,
			@nBillID,
			@intReturnID OUT,		--新生成的单据的ID
			@strReturnBillCode OUT,
			@strErrMsg OUT		--出错信息	
		
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理货位，批号，自由项等
	返回结果：
	作    者：冯波
	创建时间：2012-07-26
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DealQty
(
	@nBillID			INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据,2表示红冲
	@chvDealBTypeID		VARCHAR(50),
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT  --1表示库存不足
)
--@encode$--
AS
	
	DECLARE
		@nCostingMethod				VARCHAR(50)
	
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	IF @intBillType=57
	BEGIN
		IF EXISTS(
			SELECT BillNumberId
			FROM Billindex
			WHERE BillNumberId=@nBillID AND AdPriceType<>0
		)
			RETURN
	END	
	
	IF @intBillType NOT IN (203,116,115,128,129,4,189,66,190,148,150,149,151,36,158,77,93,5,10,84,85,78,159,205,206,181,147,165,167,169,170,175,177,198,195,143,171)
	BEGIN
		IF @intBillType=57
		BEGIN			
			IF @nCostingMethod='3'
			BEGIN
				--单独处理成本调价单（只有移动加权下才能调全部仓库，所以这里不考虑）
				EXEC GP_Auditing_QTY @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
			END
			ELSE
			BEGIN
				SET @intCanDeal=0
			END
		END
		ELSE IF @intBillType NOT IN (145,141)
		BEGIN
			IF @intBillType=166
			BEGIN
				--维修单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Self
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType=168
			BEGIN
				--整机更换单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Replace
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType=172
			BEGIN
				--上门维修单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Goto
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType IN (9,14)
			BEGIN
				--报损，报溢
				IF EXISTS(
					SELECT	BillNumberiD
					FROM Billindex
					WHERE BillNumberiD=@nBillID AND ifwx=0
				)
				BEGIN
					EXEC GP_Auditing_QTY @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE 
			BEGIN
				EXEC GP_Auditing_QTY @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
			END
		END	
		
		IF ISNULL(@intCanDeal,0)=0
		BEGIN
			IF @intBillType IN (144,146,145,140,142,141)
			BEGIN
				EXEC GP_Auditing_DX_QTY @nBillID,@intBillType,@intRedWord,@chvBTypeID,@chvSTypeID,@strInfo OUT,@intCanDeal OUT
			END
		END
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvDealBTypeID		VARCHAR(50),
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=4,
	@intBillType=57,
	@intRedWord=0,
	@chvDealBTypeID='',
	@chvBTypeID='',
	@chvSTypeID=''

BEGIN TRAN

 EXEC GP_Auditing_DealQty
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@chvDealBTypeID,
	@chvBTypeID,
	@chvSTypeID,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN


SELECT * FROM BillIndex
WHERE Billcode='TD-MRFZJG-T-2012-07-25-0001'

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：修改单据,新单据过账处理货位，批号，自由项等,无论单据类型都要判断是否产生负库存
	返回结果：
	作    者：冯波
	创建时间：2015-11-30
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DealQty_NewBill
(
	@nBillID			INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据,2表示红冲
	@chvDealBTypeID		VARCHAR(50),
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT  --1表示库存不足
)
--@encode$--
AS
	
	DECLARE
		@nCostingMethod				VARCHAR(50)
	
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	IF @intBillType=57
	BEGIN
		IF EXISTS(
			SELECT BillNumberId
			FROM Billindex
			WHERE BillNumberId=@nBillID AND AdPriceType<>0
		)
			RETURN
	END
	
	
	IF @intBillType NOT IN (203,116,115,128,129,4,189,66,190,148,150,149,151,36,158,77,93,5,10,84,85,78,159,205,206,181,147,165,167,169,170,175,177,198,195,143,171)
	BEGIN
		IF @intBillType=57
		BEGIN
			
			IF @nCostingMethod='3'
			BEGIN
				--单独处理成本调价单（只有移动加权下才能调全部仓库，所以这里不考虑）
				EXEC GP_Auditing_QTY_NewBill @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
			END
			ELSE
			BEGIN
				SET @intCanDeal=0
			END
		END
		ELSE IF @intBillType NOT IN (145,141)
		BEGIN
			IF @intBillType=166
			BEGIN
				--维修单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Self
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY_NewBill @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType=168
			BEGIN
				--整机更换单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Replace
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY_NewBill @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType=172
			BEGIN
				--上门维修单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Goto
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY_NewBill @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType IN (9,14)
			BEGIN
				--报损，报溢
				IF EXISTS(
					SELECT	BillNumberiD
					FROM Billindex
					WHERE BillNumberiD=@nBillID AND ifwx=0
				)
				BEGIN
					EXEC GP_Auditing_QTY_NewBill @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE 
			BEGIN
				EXEC GP_Auditing_QTY_NewBill @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
			END
		END
		
		
		
		IF ISNULL(@intCanDeal,0)=0
		BEGIN
			IF @intBillType IN (144,146,145,140,142,141)
			BEGIN
				EXEC GP_Auditing_DX_QTY_NewBill @nBillID,@intBillType,@intRedWord,@chvBTypeID,@chvSTypeID,@strInfo OUT,@intCanDeal OUT
			END
		END
		--如果之前有錯誤，就拋出來retrun,不要往下面走了
		IF @strInfo<>''
		BEGIN
	       SELECT @strInfo=@strInfo
	       RETURN
	    END
	END
	
	DECLARE
		@nAllowNegativeStock		TINYINT  --0表示不允许,1表示允许
		
	-- 查询是否允许负库存 (适用于移动加权平均成本核算)
	EXEC GP_GetSubValue 'AllowNegativeStock', '',@nAllowNegativeStock output
	
	DECLARE
		@strTempPFullName	VARCHAR(MAX),
		@strTempKFullName	VARCHAR(MAX)
		
		
	SELECT
		@strTempPFullName='',
		@strTempKFullName=''
	
	--如果是入库类单据被修改了，还需要判断修改前单据所对应的商品，仓库是否产生负库存
	IF ((@nCostingMethod<>0) OR (@nCostingMethod=0 AND @nAllowNegativeStock=0))
	--AND @intBillType IN (34,45,126,144,142,188,201,174,14,215,400,403)
	BEGIN
		IF EXISTS(
			SELECT a.PtypeId
			FROM GOODSSTOCKS_QTY a
			INNER JOIN Old_Bill b
			ON a.PtypeId=b.PTypeID
			AND a.KtypeId=b.KTypeID
			WHERE b.BillNumberId=@nBillID AND b.BillType=@intBillType
			AND (a.Qty<0 OR a.NQty<0)
		)
		BEGIN
			SET @intCanDeal=1
			
			--这里还需要返回具体的商品仓库信息
			SELECT TOP 1 @strTempPFullName=c.FullName,@strTempKFullName=d.FullName
			FROM GOODSSTOCKS_QTY a
			INNER JOIN Old_Bill b
			ON a.PtypeId=b.PTypeID
			AND a.KtypeId=b.KTypeID
			INNER JOIN Ptype c
			ON a.PtypeId=c.typeId
			INNER JOIN Stock d
			ON a.KtypeId=d.typeId
			WHERE b.BillNumberId=@nBillID AND b.BillType=@intBillType
			AND (a.Qty<0 OR a.NQty<0)
			
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'
			
			
			
			SELECT @strInfo=@strInfo+'会产生负库存!'
			
			RETURN
		END
	END
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvDealBTypeID		VARCHAR(50),
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=4,
	@intBillType=57,
	@intRedWord=0,
	@chvDealBTypeID='',
	@chvBTypeID='',
	@chvSTypeID=''

BEGIN TRAN

 EXEC GP_Auditing_DealQty_NewBill
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@chvDealBTypeID,
	@chvBTypeID,
	@chvSTypeID,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN


SELECT * FROM BillIndex
WHERE Billcode='TD-MRFZJG-T-2012-07-25-0001'

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：修改单据时处理货位，批号，自由项等,不需要判断负库存
	返回结果：
	作    者：冯波
	创建时间：2015-11-30
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DealQty_Reverse
(
	@nBillID			INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据,2表示红冲,REVERSE应该都是用的2
	@chvDealBTypeID		VARCHAR(50),
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT  --1表示库存不足
)
--@encode$--
AS
	
	DECLARE
		@nCostingMethod				VARCHAR(50)
	
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	IF @intBillType=57
	BEGIN
		IF EXISTS(
			SELECT BillNumberId
			FROM Billindex
			WHERE BillNumberId=@nBillID AND AdPriceType<>0
		)
			RETURN
	END
	
	
	IF @intBillType NOT IN (203,116,115,128,129,4,189,66,190,148,150,149,151,36,158,77,93,5,10,84,85,78,159,205,206,181,147,165,167,169,170,175,177,198,195,143,171)
	BEGIN
		IF @intBillType=57
		BEGIN
			
			IF @nCostingMethod='3'
			BEGIN
				--单独处理成本调价单（只有移动加权下才能调全部仓库，所以这里不考虑）
				EXEC GP_Auditing_QTY_Reverse @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
			END
			ELSE
			BEGIN
				SET @intCanDeal=0
			END
		END
		ELSE IF @intBillType NOT IN (145,141)
		BEGIN
			IF @intBillType=166
			BEGIN
				--维修单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Self
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY_Reverse @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType=168
			BEGIN
				--整机更换单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Replace
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY_Reverse @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType=172
			BEGIN
				--上门维修单
				IF EXISTS(
					SELECT	BillNumberiD
					FROM wx_Bill_Goto
					WHERE BillNumberiD=@nBillID AND wxProperty=0
				)
				BEGIN
					EXEC GP_Auditing_QTY_Reverse @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE IF @intBillType IN (9,14)
			BEGIN
				--报损，报溢
				IF EXISTS(
					SELECT	BillNumberiD
					FROM Billindex
					WHERE BillNumberiD=@nBillID AND ifwx=0
				)
				BEGIN
					EXEC GP_Auditing_QTY_Reverse @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
				END
			END
			ELSE 
			BEGIN
				EXEC GP_Auditing_QTY_Reverse @nBillID,@intBillType,@intRedWord,@strInfo OUT,@intCanDeal OUT
			END
		END
		
		
		
		IF ISNULL(@intCanDeal,0)=0
		BEGIN
			IF @intBillType IN (144,146,145,140,142,141)
			BEGIN
				EXEC GP_Auditing_DX_QTY_Reverse @nBillID,@intBillType,@intRedWord,@chvBTypeID,@chvSTypeID,@strInfo OUT,@intCanDeal OUT
			END
		END
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvDealBTypeID		VARCHAR(50),
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=4,
	@intBillType=57,
	@intRedWord=0,
	@chvDealBTypeID='',
	@chvBTypeID='',
	@chvSTypeID=''

BEGIN TRAN

 EXEC GP_Auditing_DealQty_Reverse
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@chvDealBTypeID,
	@chvBTypeID,
	@chvSTypeID,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN


SELECT * FROM BillIndex
WHERE Billcode='TD-MRFZJG-T-2012-07-25-0001'

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理成本价销售的销售出库单
	返回结果：
	作    者：冯波
	创建时间：2012-07-26
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DealSaleBill
(
	@nBillID				NUMERIC(10,0),
	@nBillType				INT,
	@intCostSale			INT,
	@CID					INT
)
--@encode$--
AS
		DECLARE	@AVERAGE	smallint,
				@FIFO		smallint,
				@LIFO		smallint,
				@HAND		smallint

		SET @AVERAGE	= 0		-- 移动加权平均算法
		SET @FIFO		= 1		-- 先进先出
		SET @LIFO		= 2		-- 后进先出
		SET @HAND		= 3		-- 手工指定法
		
		DECLARE	@nCostingMethod	INT
		
		EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
		
		DECLARE
			@intQtyDot			VARCHAR(10),
			@intPriceDot		VARCHAR(10),
			@intMoneyDot		VARCHAR(10),
			@intDiscountDot		VARCHAR(10),
			@intTaxDot			VARCHAR(10),
			@intCRateDot		VARCHAR(10),
			@intTRateDot		VARCHAR(10)		
			
		EXEC	GP_Post_Dot
			@intQtyDot	OUT,
			@intPriceDot	OUT,
			@intMoneyDot	OUT,
			@intDiscountDot	OUT,
			@intTaxDot	OUT,
			@intCRateDot	OUT,
			@intTRateDot	OUT

	
			DECLARE 
				@strTemp	VARCHAR(MAX),
				@strOPRate	VARCHAR(50)
			
			SELECT @strOPRate=BasisType
			FROM Ac_Currency				
			WHERE CId=@CID
			
			
			
			IF @strOPRate='0'
			BEGIN
				SELECT @strOPRate='/'
			END
			ELSE
			BEGIN
				SELECT @strOPRate='*'
			END
			
			
			
			SELECT @strTemp='
			UPDATE SaleBill
			SET 
				SalePrice=CASE '+CAST(@nCostingMethod AS VARCHAR(10))+' WHEN '+CAST(@Hand AS VARCHAR(10))+' THEN SaleBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.CostTotal*(-1),'+@intMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@intPriceDot+') END END,SaleTotal=b.CostTotal*(-1),				
				DiscountPrice=CASE '+CAST(@nCostingMethod AS VARCHAR(10))+' WHEN '+CAST(@Hand AS VARCHAR(10))+' THEN SaleBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.CostTotal*(-1),'+@intMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@intPriceDot+') END END,Total=b.CostTotal*(-1),
				TaxTotal=ROUND(b.CostTotal*(-1)*(1+SaleBill.Tax/100),'+@intMoneyDot+'),
				NSalePrice=CASE WHEN b.Rate=1 AND '+CAST(@nCostingMethod AS VARCHAR(10))+'='+CAST(@Hand AS VARCHAR(10))+' THEN SaleBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.NCostTotal*(-1),'+@intMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@intPriceDot+') END END,NSaleTotal=b.NCostTotal*(-1),				
				NDiscountPrice=CASE WHEN b.Rate=1 AND '+CAST(@nCostingMethod AS VARCHAR(10))+'='+CAST(@Hand AS VARCHAR(10))+' THEN SaleBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.NCostTotal*(-1),'+@intMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@intPriceDot+') END	END 			
			FROM 
			(
				SELECT a.ID,b.Rate,SUM(Qty) AS Qty,ROUND(SUM(a.CostTotal)'+@strOPRate+'b.Rate,'+@intMoneyDot+') AS NCostTotal,SUM(ROUND(a.CostTotal,'+@intMoneyDot+')) AS CostTotal
				FROM InOutStockTable a
				INNER JOIN BillIndex b
				ON a.BillNumberId=b.BillNumberId
				WHERE a.BillNumberID='+CAST(@nBillID AS VARCHAR(50)) +'
				AND a.IsService=0
				GROUP BY a.ID,b.Rate
			) b
			WHERE SaleBill.ID=b.ID AND SaleBill.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND SaleBill.IsGift=0
			

			
			UPDATE SaleBill
			SET 
				NTotal=ROUND(SaleBill.SaleTotal'+@strOPRate+'b.Rate,'+@intMoneyDot+'),
				NTaxTotal=ROUND(SaleBill.TaxTotal'+@strOPRate+'b.Rate,'+@intMoneyDot+'),
				TaxMoney=SaleBill.TaxTotal-SaleBill.Total,
				NTaxMoney=ROUND(SaleBill.TaxTotal'+@strOPRate+'b.Rate,'+@intMoneyDot+')-ROUND(SaleBill.SaleTotal'+@strOPRate+'b.Rate,'+@intMoneyDot+'),
				Taxprice=CASE SaleBill.Tax WHEN 0 THEN SaleBill.DiscountPrice ELSE CASE SaleBill.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(SaleBill.TaxTotal AS  NUMERIC(24, 10) )/CAST(SaleBill.Qty AS  NUMERIC(24, 10) ),'+@intPriceDot+') END END,
				NTaxprice=CASE WHEN b.Rate=1 AND SaleBill.Tax=0 THEN SaleBill.DiscountPrice ELSE CASE SaleBill.Qty WHEN 0 THEN 0 ELSE ROUND(CAST((ROUND(SaleBill.TaxTotal'+@strOPRate+'b.Rate,'+@intMoneyDot+')) AS  NUMERIC(24, 10) )/CAST(SaleBill.Qty AS  NUMERIC(24, 10) ),'+@intPriceDot+') END END
			FROM BillIndex b
			WHERE SaleBill.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND SaleBill.BillNumberID=b.BillNumberID
			AND SaleBill.IsGift=0
			
			
			UPDATE SaleBill
			SET MsalePrice=ROUND(SalePrice*MUnitRate,'+@intPriceDot+'),
			MDiscountPrice=ROUND(DiscountPrice*MUnitRate,'+@intPriceDot+'),
			MTaxPrice=ROUND(TaxPrice*MUnitRate,'+@intPriceDot+'),
			CurMSalePrice=ROUND(NSalePrice*MUnitRate,'+@intPriceDot+'),
			CurMDiscountPrice=ROUND(NDiscountPrice*MUnitRate,'+@intPriceDot+'),
			CurMTaxPrice=ROUND(NTaxPrice*MUnitRate,'+@intPriceDot+')
			WHERE BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND SaleBill.IsGift=0
			
			

			UPDATE BillIndex
			SET TotalMoney=ROUND(ISNULL(b.TotalMoney,0),'+@intMoneyDot+'),NTotalMoney=ROUND(ISNULL(b.NTotalMoney,0),'+@intMoneyDot+')
			FROM 
			(
				SELECT BillNumberID,SUM(TaxTotal) AS TotalMoney,SUM(NTaxTotal) AS NTotalMoney
				FROM SaleBill 
				WHERE BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
				GROUP BY BillNumberID
			) b
			WHERE BillIndex.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+' AND BillIndex.BillNumberID=b.BillNumberID


			UPDATE InOutStockTable
			SET Price=InOutStockTable.CostPrice,SalePrice=InOutStockTable.CostPrice,TaxPrice=b.TaxPrice,Discount=1,
			Total=InOutStockTable.CostTotal,SaleTotal=InOutStockTable.CostTotal,TaxTotal=-b.TaxTotal,
			NPrice=b.NSalePrice,NTotal=-b.NSaleTotal,NSalePrice=b.NSalePrice,NSaleTotal=-b.NSaleTotal,NTaxPrice=b.NTaxPrice,NTaxTotal=-b.NTaxTotal	
			FROM SaleBill b
			WHERE InOutStockTable.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND InOutStockTable.BillNumberID=b.BillNumberId
			AND InOutStockTable.ID=b.ID
			AND InOutStockTable.IsService=0
			AND InOutStockTable.IsGift=0
			'
			
			--PRINT @strTemp
	
			EXEC(@strTemp)		
			
		
		
		

	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID				NUMERIC(10,0),
	@nBillType				INT,
	@intCostSale			INT,
	@CID					INT
	
SELECT
	@nBillID=14,
	@nBillType=11,
	@intCostSale=1,
	@CID=1	


BEGIN TRAN
	EXEC	GP_Auditing_DealSaleBill
	@nBillID,
	@nBillType,
	@intCostSale,
	@CID
	
SELECT TAXTOTAL,TOTAL,NTAXTOTAL,NTOTAL,* FROM dbo.SaleBill
WHERE BillNumberId=14	
	
ROLLBACK TRAN	


*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理成本价销售的发出商品单
	返回结果：
	作    者：冯波
	创建时间：2015-11-26
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DealSendBill
(
	@nBillID				NUMERIC(10,0),
	@nBillType				INT,
	@intCostSale			INT,
	@CID					INT
)
--@encode$--
AS
		DECLARE	@AVERAGE	smallint,
				@FIFO		smallint,
				@LIFO		smallint,
				@HAND		smallint

		SET @AVERAGE	= 0		-- 移动加权平均算法
		SET @FIFO		= 1		-- 先进先出
		SET @LIFO		= 2		-- 后进先出
		SET @HAND		= 3		-- 手工指定法
		
		DECLARE	@nCostingMethod	INT
		
		EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
		
		DECLARE
			@strQtyDot			VARCHAR(10),
			@strPriceDot		VARCHAR(10),
			@strMoneyDot		VARCHAR(10),
			@strDiscountDot		VARCHAR(10),
			@strTaxDot			VARCHAR(10),
			@strCRateDot		VARCHAR(10),
			@strTRateDot		VARCHAR(10)		
			
		EXEC	GP_Post_Dot
			@strQtyDot	OUT,
			@strPriceDot	OUT,
			@strMoneyDot	OUT,
			@strDiscountDot	OUT,
			@strTaxDot	OUT,
			@strCRateDot	OUT,
			@strTRateDot	OUT

	
			DECLARE 
				@strTemp	VARCHAR(MAX),
				@strOPRate	VARCHAR(50)
			
			SELECT @strOPRate=BasisType
			FROM Ac_Currency				
			WHERE CId=@CID
			
			
			
			IF @strOPRate='0'
			BEGIN
				SELECT @strOPRate='/'
			END
			ELSE
			BEGIN
				SELECT @strOPRate='*'
			END
			
			
			
			SELECT @strTemp='
			UPDATE SendBill
			SET 
				SalePrice=CASE '+CAST(@nCostingMethod AS VARCHAR(10))+' WHEN '+CAST(@Hand AS VARCHAR(10))+' THEN SendBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.CostTotal*(-1),'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+') END END,SaleTotal=b.CostTotal*(-1),				
				DiscountPrice=CASE '+CAST(@nCostingMethod AS VARCHAR(10))+' WHEN '+CAST(@Hand AS VARCHAR(10))+' THEN SendBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.CostTotal*(-1),'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+') END END,Total=b.CostTotal*(-1),
				TaxTotal=ROUND(b.CostTotal*(-1)*(1+SendBill.Tax/100),'+@strMoneyDot+'),
				NSalePrice=CASE WHEN b.Rate=1 AND '+CAST(@nCostingMethod AS VARCHAR(10))+'='+CAST(@Hand AS VARCHAR(10))+' THEN SendBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.NCostTotal*(-1),'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+') END END,NSaleTotal=b.NCostTotal*(-1),				
				NDiscountPrice=CASE WHEN b.Rate=1 AND '+CAST(@nCostingMethod AS VARCHAR(10))+'='+CAST(@Hand AS VARCHAR(10))+' THEN SendBill.GoodsCostPrice ELSE CASE b.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(ROUND(b.NCostTotal*(-1),'+@strMoneyDot+') AS  NUMERIC(24, 10) )/CAST(ABS(b.Qty) AS  NUMERIC(24, 10) ),'+@strPriceDot+') END	END 			
			FROM 
			(
				SELECT a.ID,b.Rate,SUM(Qty) AS Qty,ROUND(SUM(a.CostTotal)'+@strOPRate+'b.Rate,'+@strMoneyDot+') AS NCostTotal,SUM(a.CostTotal) AS CostTotal
				FROM InOutStockTable a
				INNER JOIN BillIndex b
				ON a.BillNumberId=b.BillNumberId
				WHERE a.BillNumberID='+CAST(@nBillID AS VARCHAR(50)) +'
				AND a.IsService=0
				GROUP BY a.ID,b.Rate
			) b
			WHERE SendBill.ID=b.ID AND SendBill.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND SendBill.IsGift=0
			

			
			UPDATE SendBill
			SET 
				NTotal=ROUND(SendBill.SaleTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+'),
				NTaxTotal=ROUND(SendBill.TaxTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+'),
				TaxMoney=SendBill.TaxTotal-SendBill.Total,
				NTaxMoney=ROUND(SendBill.TaxTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+')-ROUND(SendBill.SaleTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+'),
				Taxprice=CASE SendBill.Tax WHEN 0 THEN SendBill.DiscountPrice ELSE CASE SendBill.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(SendBill.TaxTotal AS  NUMERIC(24, 10) )/CAST(SendBill.Qty AS  NUMERIC(24, 10) ),'+@strPriceDot+') END END,
				NTaxprice=CASE WHEN b.Rate=1 AND SendBill.Tax=0 THEN SendBill.DiscountPrice ELSE CASE SendBill.Qty WHEN 0 THEN 0 ELSE ROUND(CAST((ROUND(SendBill.TaxTotal'+@strOPRate+'b.Rate,'+@strMoneyDot+')) AS  NUMERIC(24, 10) )/CAST(SendBill.Qty AS  NUMERIC(24, 10) ),'+@strPriceDot+') END END
			FROM BillIndex b
			WHERE SendBill.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND SendBill.BillNumberID=b.BillNumberID
			AND SendBill.IsGift=0
			
			
			UPDATE SendBill
			SET MsalePrice=ROUND(SalePrice*MUnitRate,'+@strPriceDot+'),
			MDiscountPrice=ROUND(DiscountPrice*MUnitRate,'+@strPriceDot+'),
			MTaxPrice=ROUND(TaxPrice*MUnitRate,'+@strPriceDot+'),
			CurMSalePrice=ROUND(NSalePrice*MUnitRate,'+@strPriceDot+'),
			CurMDiscountPrice=ROUND(NDiscountPrice*MUnitRate,'+@strPriceDot+'),
			CurMTaxPrice=ROUND(NTaxPrice*MUnitRate,'+@strPriceDot+')
			WHERE BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND SendBill.IsGift=0
			
			

			UPDATE BillIndex
			SET TotalMoney=ROUND(ISNULL(b.TotalMoney,0),'+@strMoneyDot+'),NTotalMoney=ROUND(ISNULL(b.NTotalMoney,0),'+@strMoneyDot+')
			FROM 
			(
				SELECT BillNumberID,SUM(TaxTotal) AS TotalMoney,SUM(NTaxTotal) AS NTotalMoney
				FROM SendBill 
				WHERE BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
				GROUP BY BillNumberID
			) b
			WHERE BillIndex.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+' AND BillIndex.BillNumberID=b.BillNumberID


			UPDATE InOutStockTable
			SET Price=InOutStockTable.CostPrice,SalePrice=InOutStockTable.CostPrice,TaxPrice=b.TaxPrice,Discount=1,
			Total=InOutStockTable.CostTotal,SaleTotal=InOutStockTable.CostTotal,TaxTotal=-b.TaxTotal,
			NPrice=b.NSalePrice,NTotal=-b.NSaleTotal,NSalePrice=b.NSalePrice,NSaleTotal=-b.NSaleTotal,NTaxPrice=b.NTaxPrice,NTaxTotal=-b.NTaxTotal	
			FROM SendBill b
			WHERE InOutStockTable.BillNumberID='+CAST(@nBillID AS VARCHAR(50))+'
			AND InOutStockTable.BillNumberID=b.BillNumberId
			AND InOutStockTable.ID=b.ID
			AND InOutStockTable.IsService=0
			AND InOutStockTable.IsGift=0
			'
			
			--PRINT @strTemp
	
			EXEC(@strTemp)		
			
		
		
		

	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：代销库处理核算数量的批号，自由项等
	返回结果：
	作    者：冯波
	创建时间：2012-04-18
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DX_QTY
(
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT  --1表示库存不足
)
--@encode$--
AS

	
	
	
	--要先进行数据的校验，看能否处理
	SELECT 
		@strInfo='',
		@intCanDeal=0


	DECLARE
		@DBName		VARCHAR(100)

	SELECT @DBName=DBO.F_BillTableName(@intBillType)

	DECLARE
		@strSql						NVARCHAR(MAX),
		@strTempSql					NVARCHAR(MAX),
		@strCheck					NVARCHAR(MAX),
		@AVERAGE					VARCHAR(50),
		@FIFO						VARCHAR(50),
		@LIFO						VARCHAR(50),
		@HAND						VARCHAR(50),
		@nCostingMethod				VARCHAR(50),
		@nAllowNegativeStock		TINYINT  --0表示不允许，1表示允许
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	-- 查询是否允许负库存 (适用于移动加权平均成本核算)
	EXEC GP_GetSubValue 'AllowNegativeStock', '',@nAllowNegativeStock output
		
			
	SELECT
		@AVERAGE	= '0',		-- 移动加权平均算法
		@FIFO		= '1',		-- 先进先出
		@LIFO		= '2',		-- 后进先出
		@HAND		= '3'		-- 手工指定法

		
	IF @intBillType IN (144)		
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (145,146)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (140)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (141)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (142)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END


		
	--TempResult中的QTY按入库为正，出库为负来记录
	
	DECLARE
		@strTempPFullName	VARCHAR(MAX),
		@strTempBFullName	VARCHAR(MAX),
		@strTempCFullName	VARCHAR(MAX),
		@strTempIFullName	VARCHAR(MAX)
		
	SELECT
		@strTempPFullName='',
		@strTempBFullName='',
		@strTempCFullName='',
		@strTempIFullName=''
		
	IF (
			( @intRedWord=0 AND @intBillType IN (145,146,142,141) ) OR ( @intRedWord<>0 AND @intBillType IN (144,140) 
		)
	)
	BEGIN		
		SELECT @strCheck=@strTempSql+'
		
		SELECT @intCanDeal=COUNT(*)
		FROM TempResult a
		LEFT JOIN CommissionStock_Qty b
		ON  a.PTypeID = b.PTypeID
		AND a.STypeID=b.STypeID
		AND a.BTypeID=b.BTypeID
		AND a.Type=b.Type
		AND a.ItemID=b.ItemID
		AND a.Iscombined=b.Iscombined
		AND a.GoodsNumber=b.GoodsNumber
		AND a.ProduceDate=b.ProduceDate
		AND a.ValidDate=b.ValidDate
		
		
		'
		
		/*
		IF ( ( @intRedWord=0 AND @intBillType IN (145,146,142,141) ) OR ( @intRedWord<>0 AND @intBillType IN (144,140) ) )
		BEGIN
			SELECT @strCheck=@strCheck+' WHERE (-a.Qty>ISNULL(b.Qty,0) OR -a.NQty>ISNULL(b.NQty,0)) '
		END
		*/
		
		SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) '
		
		--PRINT(@strCheck)
	
		EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
		
		IF @intCanDeal<>0
		BEGIN
			SET @intCanDeal=-18
			
			SELECT @strCheck=@strTempSql+'
		
			SELECT  TOP 1
				@strTempPFullName=p.FullName,
				@strTempBFullName=bb.FullName,
				@strTempIFullName=i.itemname
			FROM TempResult a
			LEFT JOIN CommissionStock_Qty b
			ON  a.PTypeID = b.PTypeID
			AND a.STypeID=b.STypeID
			AND a.BTypeID=b.BTypeID
			AND a.Type=b.Type
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			INNER JOIN PType p
			ON a.PTypeID=p.typeId
			INNER JOIN btype bb
			ON a.BTypeID=bb.typeId
			LEFT JOIN V_Item i
			ON a.ItemId=i.itemid
			'
			
			SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) 
			ORDER BY p.Usercode
			'
			
			--PRINT(@strCheck)
		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempBFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempBFullName OUT,@strTempIFullName OUT
			
			PRINT(@strCheck)
		
		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempBFullName+']'
			
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
			
			SELECT @strInfo=@strInfo+'会造成相应批号/自由项/浮动数量等产生负库存!'
			
		END
		
	END
	--InOrOut
	

	--换货，调拨还要单独处理
	IF @intCanDeal=0
	BEGIN
	
		SELECT @strSql=@strTempSql+'
		
		MERGE CommissionStock_Qty AS target
		USING 
		(
			SELECT PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty
			FROM TempResult
		) AS source (PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty)
		ON 
		(
			target.PTypeID = source.PTypeID
			AND target.STypeID=source.STypeID
			AND target.BTypeID=source.BTypeID
			AND target.Type=source.Type
			AND target.ItemID=source.ItemID
			AND target.Iscombined=source.Iscombined
			AND target.GoodsNumber=source.GoodsNumber
			AND target.ProduceDate=source.ProduceDate
			AND target.ValidDate=source.ValidDate
			
		)
		WHEN MATCHED AND target.Qty + source.Qty = 0 AND target.NQty + source.NQty = 0
		THEN DELETE
		WHEN MATCHED 
		THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.NQty = target.NQty + source.NQty
		WHEN NOT MATCHED BY TARGET  AND (source.Qty<>0 OR source.NQty<>0)
		THEN INSERT (PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty) 
		VALUES(source.PtypeId,source.STypeID,source.BTypeID,source.Type,source.ItemID,source.Iscombined,
		source.GoodsNumber,source.ProduceDate,source.ValidDate,source.Qty,source.NQty);
		'
		
		--PRINT @strSql
		--EXEC(@strSql)	
		EXEC  sp_executesql @strSql
		
	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=44,
	@intBillType=140,
	@intRedWord=0,
	@chvBTypeID='000010000200001',
	@chvSTypeID='00001'

BEGIN TRAN

 EXEC GP_Auditing_DX_QTY
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@chvBTypeID,
	@chvSTypeID,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN

SELECT btypeid,stypeid,* FROM BillIndex
WHERE BillCode='WF-MRFZJG-T-2012-07-25-0001'

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：修改过账后单据,新增单据处理代销库处理核算数量的批号，自由项等,无论单据类型,都要判断负库存
	返回结果：
	作    者：冯波
	创建时间：2015-11-30
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DX_QTY_NewBill
(
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT  --1表示库存不足
)
--@encode$--
AS

	
	
	
	--要先进行数据的校验，看能否处理
	SELECT 
		@strInfo='',
		@intCanDeal=0


	DECLARE
		@DBName		VARCHAR(100)

	SELECT @DBName=DBO.F_BillTableName(@intBillType)

	DECLARE
		@strSql						NVARCHAR(MAX),
		@strTempSql					NVARCHAR(MAX),
		@strCheck					NVARCHAR(MAX),
		@AVERAGE					VARCHAR(50),
		@FIFO						VARCHAR(50),
		@LIFO						VARCHAR(50),
		@HAND						VARCHAR(50),
		@nCostingMethod				VARCHAR(50),
		@nAllowNegativeStock		TINYINT  --0表示不允许，1表示允许
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	-- 查询是否允许负库存 (适用于移动加权平均成本核算)
	EXEC GP_GetSubValue 'AllowNegativeStock', '',@nAllowNegativeStock output
		
			
	SELECT
		@AVERAGE	= '0',		-- 移动加权平均算法
		@FIFO		= '1',		-- 先进先出
		@LIFO		= '2',		-- 后进先出
		@HAND		= '3'		-- 手工指定法

		
	IF @intBillType IN (144)		
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (145,146)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (140)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (141)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (142)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END


		
	--TempResult中的QTY按入库为正，出库为负来记录
	
	DECLARE
		@strTempPFullName	VARCHAR(MAX),
		@strTempBFullName	VARCHAR(MAX),
		@strTempCFullName	VARCHAR(MAX),
		@strTempIFullName	VARCHAR(MAX)
		
	SELECT
		@strTempPFullName='',
		@strTempBFullName='',
		@strTempCFullName='',
		@strTempIFullName=''
		
		
		SELECT @strCheck=@strTempSql+'
		
		SELECT @intCanDeal=COUNT(*)
		FROM TempResult a
		LEFT JOIN CommissionStock_Qty b
		ON  a.PTypeID = b.PTypeID
		AND a.STypeID=b.STypeID
		AND a.BTypeID=b.BTypeID
		AND a.Type=b.Type
		AND a.ItemID=b.ItemID
		AND a.Iscombined=b.Iscombined
		AND a.GoodsNumber=b.GoodsNumber
		AND a.ProduceDate=b.ProduceDate
		AND a.ValidDate=b.ValidDate
		
		
		'
		
		/*
		IF ( ( @intRedWord=0 AND @intBillType IN (145,146,142,141) ) OR ( @intRedWord<>0 AND @intBillType IN (144,140) ) )
		BEGIN
			SELECT @strCheck=@strCheck+' WHERE (-a.Qty>ISNULL(b.Qty,0) OR -a.NQty>ISNULL(b.NQty,0)) '
		END
		*/
		
		SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) '
		
		--PRINT(@strCheck)
	
		EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
		
		IF @intCanDeal<>0
		BEGIN
			SET @intCanDeal=-18
			
			SELECT @strCheck=@strTempSql+'
		
			SELECT  TOP 1
				@strTempPFullName=p.FullName,
				@strTempBFullName=bb.FullName,
				@strTempIFullName=i.itemname
			FROM TempResult a
			LEFT JOIN CommissionStock_Qty b
			ON  a.PTypeID = b.PTypeID
			AND a.STypeID=b.STypeID
			AND a.BTypeID=b.BTypeID
			AND a.Type=b.Type
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			INNER JOIN PType p
			ON a.PTypeID=p.typeId
			INNER JOIN btype bb
			ON a.BTypeID=bb.typeId
			LEFT JOIN V_Item i
			ON a.ItemId=i.itemid
			'
			
			SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) 
			ORDER BY p.Usercode
			'
			
			--PRINT(@strCheck)
		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempBFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempBFullName OUT,@strTempIFullName OUT
			
			--PRINT(@strCheck)
		
		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempBFullName+']'
			
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
			
			SELECT @strInfo=@strInfo+'会造成相应批号/自由项/浮动数量等产生负库存!'
			
		END
		
	--InOrOut
	

	--换货，调拨还要单独处理
	IF @intCanDeal=0
	BEGIN
	
		SELECT @strSql=@strTempSql+'
		
		MERGE CommissionStock_Qty AS target
		USING 
		(
			SELECT PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty
			FROM TempResult
		) AS source (PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty)
		ON 
		(
			target.PTypeID = source.PTypeID
			AND target.STypeID=source.STypeID
			AND target.BTypeID=source.BTypeID
			AND target.Type=source.Type
			AND target.ItemID=source.ItemID
			AND target.Iscombined=source.Iscombined
			AND target.GoodsNumber=source.GoodsNumber
			AND target.ProduceDate=source.ProduceDate
			AND target.ValidDate=source.ValidDate
			
		)
		WHEN MATCHED AND target.Qty + source.Qty = 0 AND target.NQty + source.NQty = 0
		THEN DELETE
		WHEN MATCHED 
		THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.NQty = target.NQty + source.NQty
		WHEN NOT MATCHED BY TARGET  AND (source.Qty<>0 OR source.NQty<>0)
		THEN INSERT (PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty) 
		VALUES(source.PtypeId,source.STypeID,source.BTypeID,source.Type,source.ItemID,source.Iscombined,
		source.GoodsNumber,source.ProduceDate,source.ValidDate,source.Qty,source.NQty);
		'
		
		--PRINT @strSql
		--EXEC(@strSql)	
		EXEC  sp_executesql @strSql
		
	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=44,
	@intBillType=140,
	@intRedWord=0,
	@chvBTypeID='000010000200001',
	@chvSTypeID='00001'

BEGIN TRAN

 EXEC GP_Auditing_DX_QTY_NewBill
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@chvBTypeID,
	@chvSTypeID,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN

SELECT btypeid,stypeid,* FROM BillIndex
WHERE BillCode='WF-MRFZJG-T-2012-07-25-0001'

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：修改单据时,代销库处理核算数量的批号，自由项等,不判断负库存
	返回结果：
	作    者：冯波
	创建时间：2015-11-30
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Auditing_DX_QTY_Reverse
(
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT  --1表示库存不足
)
--@encode$--
AS

	
	
	
	--要先进行数据的校验，看能否处理
	SELECT 
		@strInfo='',
		@intCanDeal=0


	DECLARE
		@DBName		VARCHAR(100)

	SELECT @DBName=DBO.F_BillTableName(@intBillType)

	DECLARE
		@strSql						NVARCHAR(MAX),
		@strTempSql					NVARCHAR(MAX),
		@strCheck					NVARCHAR(MAX),
		@AVERAGE					VARCHAR(50),
		@FIFO						VARCHAR(50),
		@LIFO						VARCHAR(50),
		@HAND						VARCHAR(50),
		@nCostingMethod				VARCHAR(50),
		@nAllowNegativeStock		TINYINT  --0表示不允许，1表示允许
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	-- 查询是否允许负库存 (适用于移动加权平均成本核算)
	EXEC GP_GetSubValue 'AllowNegativeStock', '',@nAllowNegativeStock output
		
			
	SELECT
		@AVERAGE	= '0',		-- 移动加权平均算法
		@FIFO		= '1',		-- 先进先出
		@LIFO		= '2',		-- 后进先出
		@HAND		= '3'		-- 手工指定法

		
	IF @intBillType IN (144)		
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (145,146)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,144 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (140)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (141)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END
	ELSE IF @intBillType IN (142)
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,140 AS Type,'+CHAR(39)+@chvSTypeID+CHAR(39)+' AS STypeID,'+CHAR(39)+@chvBTypeID+CHAR(39)+' AS BTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty
					FROM CommissionBill a
					INNER JOIN PType p
					ON a.PTypeID=p.TypeID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					AND p.IsService=0
				) a
				GROUP BY a.PTypeID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
			)
			'
		END
	END


	/*
	--TempResult中的QTY按入库为正，出库为负来记录
	
	DECLARE
		@strTempPFullName	VARCHAR(MAX),
		@strTempBFullName	VARCHAR(MAX),
		@strTempCFullName	VARCHAR(MAX),
		@strTempIFullName	VARCHAR(MAX)
		
	SELECT
		@strTempPFullName='',
		@strTempBFullName='',
		@strTempCFullName='',
		@strTempIFullName=''
		
	IF (
			( @intRedWord=0 AND @intBillType IN (145,146,142,141) ) OR ( @intRedWord<>0 AND @intBillType IN (144,140) 
		)
	)
	BEGIN		
		SELECT @strCheck=@strTempSql+'
		
		SELECT @intCanDeal=COUNT(*)
		FROM TempResult a
		LEFT JOIN CommissionStock_Qty b
		ON  a.PTypeID = b.PTypeID
		AND a.STypeID=b.STypeID
		AND a.BTypeID=b.BTypeID
		AND a.Type=b.Type
		AND a.ItemID=b.ItemID
		AND a.Iscombined=b.Iscombined
		AND a.GoodsNumber=b.GoodsNumber
		AND a.ProduceDate=b.ProduceDate
		AND a.ValidDate=b.ValidDate
		
		
		'
		
		/*
		IF ( ( @intRedWord=0 AND @intBillType IN (145,146,142,141) ) OR ( @intRedWord<>0 AND @intBillType IN (144,140) ) )
		BEGIN
			SELECT @strCheck=@strCheck+' WHERE (-a.Qty>ISNULL(b.Qty,0) OR -a.NQty>ISNULL(b.NQty,0)) '
		END
		*/
		
		SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) '
		
		--PRINT(@strCheck)
	
		EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
		
		IF @intCanDeal<>0
		BEGIN
			SET @intCanDeal=-18
			
			SELECT @strCheck=@strTempSql+'
		
			SELECT  TOP 1
				@strTempPFullName=p.FullName,
				@strTempBFullName=bb.FullName,
				@strTempIFullName=i.itemname
			FROM TempResult a
			LEFT JOIN CommissionStock_Qty b
			ON  a.PTypeID = b.PTypeID
			AND a.STypeID=b.STypeID
			AND a.BTypeID=b.BTypeID
			AND a.Type=b.Type
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			INNER JOIN PType p
			ON a.PTypeID=p.typeId
			INNER JOIN btype bb
			ON a.BTypeID=bb.typeId
			LEFT JOIN V_Item i
			ON a.ItemId=i.itemid
			'
			
			SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) 
			ORDER BY p.Usercode
			'
			
			--PRINT(@strCheck)
		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempBFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempBFullName OUT,@strTempIFullName OUT
			
			PRINT(@strCheck)
		
		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempBFullName+']'
			
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
			
			SELECT @strInfo=@strInfo+'会造成相应批号/自由项/浮动数量等产生负库存!'
			
		END
		
	END
	--InOrOut
	*/

	--换货，调拨还要单独处理
	IF @intCanDeal=0
	BEGIN
	
		SELECT @strSql=@strTempSql+'
		
		MERGE CommissionStock_Qty AS target
		USING 
		(
			SELECT PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty
			FROM TempResult
		) AS source (PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty)
		ON 
		(
			target.PTypeID = source.PTypeID
			AND target.STypeID=source.STypeID
			AND target.BTypeID=source.BTypeID
			AND target.Type=source.Type
			AND target.ItemID=source.ItemID
			AND target.Iscombined=source.Iscombined
			AND target.GoodsNumber=source.GoodsNumber
			AND target.ProduceDate=source.ProduceDate
			AND target.ValidDate=source.ValidDate
			
		)
		WHEN MATCHED AND target.Qty + source.Qty = 0 AND target.NQty + source.NQty = 0
		THEN DELETE
		WHEN MATCHED 
		THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.NQty = target.NQty + source.NQty
		WHEN NOT MATCHED BY TARGET  AND (source.Qty<>0 OR source.NQty<>0)
		THEN INSERT (PtypeId,STypeID,BTypeID,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty) 
		VALUES(source.PtypeId,source.STypeID,source.BTypeID,source.Type,source.ItemID,source.Iscombined,
		source.GoodsNumber,source.ProduceDate,source.ValidDate,source.Qty,source.NQty);
		'
		
		--PRINT @strSql
		--EXEC(@strSql)	
		EXEC  sp_executesql @strSql
		
	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=44,
	@intBillType=140,
	@intRedWord=0,
	@chvBTypeID='000010000200001',
	@chvSTypeID='00001'

BEGIN TRAN

 EXEC GP_Auditing_DX_QTY_Reverse
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@chvBTypeID,
	@chvSTypeID,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN

SELECT btypeid,stypeid,* FROM BillIndex
WHERE BillCode='WF-MRFZJG-T-2012-07-25-0001'

*/



IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_Auditing_Fact_DealQty',N'P'))
BEGIN
	DROP PROC GP_Auditing_Fact_DealQty
END
GO
CREATE PROC GP_Auditing_Fact_DealQty
(
	@BillNumberID   INT,
	@BillType	    INT,
	@Qty			NUMERIC(24,10),
	@NQty			NUMERIC(24,10),
	@ItemID		    INT,
	@IsCombined     INT,
	@GoodsNumber    VARCHAR(100),
	@ProduceDate    VARCHAR(50),
	@ValidDate      VARCHAR(50),
	@InKTypeID		VARCHAR(50),
	@InCargoID      INT,
	@OutKTypeID     VARCHAR(50),
	@OutCargoID     INT,
	@RowIndex       INT,
	@PTypeID		VARCHAR(100),
	@FullName       VARCHAR(100),
	@szPID		    VARCHAR(1000) OUT
)

AS
BEGIN
	DECLARE @FactNegativeStock		INT			/*允许实物库存负库存*/
	SELECT @FactNegativeStock=Value FROM dbo.Userconfig WHERE ConfigName='physicalsstocknegativestock'
	IF @BillType IN(418,420) --仓库入库单、仓库调拨单 入库
	BEGIN
		--没有库存则插入
		IF NOT EXISTS(SELECT 1 FROM dbo.FactStocks WHERE PtypeId=@PTypeID AND KtypeId=@InKTypeID)
		BEGIN
			INSERT INTO dbo.FactStocks (
									     PtypeId , KtypeId ,JobNumber ,OutFactoryDate , Qty ,GoodsOrder ,
										 GoodsNumber , ProduceDate ,ValidDate
										)
			VALUES  ( 
					  @PTypeID ,@InKTypeID, '' ,  '',  @Qty , 0 , '' ,'' ,'' 
			        )
		END
		ELSE
		BEGIN
			UPDATE dbo.FactStocks SET Qty=Qty+@Qty WHERE KtypeId=@InKTypeID AND PtypeId=@PTypeID
		END
		
		--负库存 过账不验证
		IF @FactNegativeStock=0 AND @Qty<0 AND EXISTS
		(
			SELECT 1 FROM dbo.FactStocks 	
			WHERE  PTypeID=@PTypeID AND KTypeID=@InKTypeID AND Qty<0
		)
		BEGIN
			SET @szPID=@PTypeID
			RETURN -1
		END
		
		IF NOT EXISTS(
						SELECT 1 FROM dbo.FactStocks_Qty
						WHERE PTypeID=@PTypeID AND KTypeID=@InKTypeID AND CargoID=@InCargoID AND 
						ItemID=@ItemID AND GoodsNumber=@GoodsNumber AND ISNULL(Iscombined,0)=ISNULL(@IsCombined,0) AND 
						ProduceDate=@ProduceDate AND ValidDate=@ValidDate
					)
		BEGIN
			INSERT INTO dbo.FactStocks_Qty
			        (
					  PTypeID ,KTypeID ,CargoID ,ItemID ,Iscombined ,GoodsNumber , ProduceDate ,ValidDate ,Qty ,NQty
			        )
			VALUES  ( 
					  @PTypeID, @InKTypeID,@InCargoID,@ItemID,ISNULL(@IsCombined,0),@GoodsNumber,@ProduceDate,@ValidDate,
					  @Qty,@NQty
			        )
		END
		ELSE
		BEGIN
			UPDATE dbo.FactStocks_Qty SET Qty=Qty+@Qty,NQty=NQty+@NQty 
			WHERE  PTypeID=@PTypeID AND KTypeID=@InKTypeID AND CargoID=@InCargoID AND 
				   ItemID=@ItemID AND GoodsNumber=@GoodsNumber AND ISNULL(Iscombined,0)=ISNULL(@IsCombined,0) AND 
				   ProduceDate=@ProduceDate AND ValidDate=@ValidDate
		END
		
		--负库存 过账不验证
		IF @FactNegativeStock=0 AND @Qty<0 AND EXISTS
		(
			SELECT 1 FROM dbo.FactStocks_Qty 	
			WHERE  PTypeID=@PTypeID AND KTypeID=@InKTypeID AND CargoID=@InCargoID AND 
				   ItemID=@ItemID AND GoodsNumber=@GoodsNumber AND Iscombined=ISNULL(@IsCombined,0) AND 
				   ProduceDate=@ProduceDate AND ValidDate=@ValidDate AND Qty<0
		)
		BEGIN
			SET @szPID=@PTypeID
			RETURN -1
		END
	END
	
	IF @BillType IN (419,420) --仓库出库单 仓库调拨单 出库
	BEGIN
		SET @Qty=-1*@Qty
		SET @NQty=-1*@NQty
		--没有库存则插入
		IF NOT EXISTS(SELECT 1 FROM dbo.FactStocks WHERE PtypeId=@PTypeID AND KtypeId=@OutKTypeID)
		BEGIN
			INSERT INTO dbo.FactStocks (
									     PtypeId , KtypeId ,JobNumber ,OutFactoryDate , Qty ,GoodsOrder ,
										 GoodsNumber , ProduceDate ,ValidDate
										)
			VALUES  ( 
					  @PTypeID ,@OutKTypeID, '' ,  '',  @Qty , 0 , '' ,'' ,'' 
			        )
		END
		ELSE
		BEGIN
			UPDATE dbo.FactStocks SET Qty=Qty+@Qty WHERE KtypeId=@OutKTypeID AND PtypeId=@PTypeID
		END
		
		--负库存 红冲不验证
		IF @FactNegativeStock=0 AND @Qty<0 AND EXISTS
		(
			SELECT 1 FROM dbo.FactStocks
			WHERE  PTypeID=@PTypeID AND KTypeID=@OutKTypeID AND Qty<0
		)
		BEGIN
	
			SET @szPID=@PTypeID
			RETURN -1
		END
		
		IF NOT EXISTS(
						SELECT 1 FROM dbo.FactStocks_Qty
						WHERE PTypeID=@PTypeID AND KTypeID=@OutKTypeID AND CargoID=@OutCargoID AND 
						ItemID=@ItemID AND GoodsNumber=@GoodsNumber AND ISNULL(Iscombined,0)=ISNULL(@IsCombined,0) AND 
						ProduceDate=@ProduceDate AND ValidDate=@ValidDate
					)
		BEGIN
			INSERT INTO dbo.FactStocks_Qty
			        (
					  PTypeID ,KTypeID ,CargoID ,ItemID ,Iscombined ,GoodsNumber , ProduceDate ,ValidDate ,Qty ,NQty
			        )
			VALUES  ( 
					  @PTypeID, @OutKTypeID,@OutCargoID,@ItemID,ISNULL(@IsCombined,0),@GoodsNumber,@ProduceDate,@ValidDate,
					  @Qty,@NQty
			        )
		END
		ELSE
		BEGIN
			UPDATE dbo.FactStocks_Qty SET Qty=Qty+@Qty,NQty=NQty+@NQty 
			WHERE  PTypeID=@PTypeID AND KTypeID=@OutKTypeID AND CargoID=@OutCargoID AND 
				   ItemID=@ItemID AND GoodsNumber=@GoodsNumber AND ISNULL(Iscombined,0)=ISNULL(@IsCombined,0) AND 
				   ProduceDate=@ProduceDate AND ValidDate=@ValidDate
		END
		
		--负库存 红冲不验证
		IF @FactNegativeStock=0 AND @Qty<0 AND EXISTS
		(
			SELECT 1 FROM dbo.FactStocks_Qty 	
			WHERE  PTypeID=@PTypeID AND KTypeID=@OutKTypeID AND CargoID=@OutCargoID AND 
				   ItemID=@ItemID AND GoodsNumber=@GoodsNumber AND ISNULL(Iscombined,0)=ISNULL(@IsCombined,0) AND 
				   ProduceDate=@ProduceDate AND ValidDate=@ValidDate AND Qty<0
		)
		BEGIN
			SET @szPID=@PTypeID
			RETURN -1
		END
	END
	DELETE FROM dbo.FactStocks WHERE Qty=0 
	DELETE FROM	 dbo.FactStocks_Qty WHERE Qty=0
	RETURN 0
END
GO



/****实物库存单据过账****/
IF  EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_Auditing_FactBill',N'P'))
BEGIN
	DROP PROC GP_Auditing_FactBill
END
GO

CREATE PROC GP_Auditing_FactBill
(
	@BillNumberID	INT,
	@BillType		INT,
	@chvOpID		VARCHAR(50),
	@szPID			VARCHAR(1000) OUT
)
AS
BEGIN
DECLARE @STypeID VARCHAR(100),
		@nRet    INT,
		@QuoteBillInstock			INT,			/*只有通过引用单据的仓库入库单才允许过账*/
		@QuoteBilloutStock			INT,			/*只有通过引用单据的仓库出库单才允许过账*/
		@IsGreaterQuoteBillInStock	INT,		    /*仓库出库单数量大于来源单据数量不允许过账*/
		@IsGreaterQuoteBillOutStock INT				/*仓库入库单数量大于来源单据数量不允许过账*/
	
	SELECT @QuoteBillInstock		  =Value FROM dbo.Userconfig WHERE ConfigName='quotebillinstock'
	SELECT @QuoteBilloutStock		  =Value FROM dbo.Userconfig WHERE ConfigName='quotebilloutstock'
	SELECT @IsGreaterQuoteBillInStock =Value FROM dbo.Userconfig WHERE ConfigName='isgreaterquotebilloutstock' --不要纠结于这两个名字 in,out 
	SELECT @IsGreaterQuoteBillOutStock=Value FROM dbo.Userconfig WHERE ConfigName='isgreaterquotebillinstock'  --做系统设置的人是这样设置的
	
    SELECT  @STypeID = Stypeid FROM  dbo.FactIndex WHERE   BillNumberId = @BillNumberID
	EXEC @nRet=Gp_Auditing_Control @STypeID
	IF @nRet<>0 RETURN @nRet
		
	/*没有单据过账的权限*/
	EXEC @nRet = Gp_CheckLimitBillType @chvOpID,0,@billtype
	IF	 @nRet <> 1 RETURN 1000 
	SET	 @nRet = 0
	
	IF NOT EXISTS(SELECT 1 FROM dbo.FactIndex WHERE BillNumberId=@BillNumberID AND IfCheck='f')
	BEGIN
		RETURN 1111  /*该单据不存在或已过账*/
	END
	
	
	DECLARE		@FromBillNumberID  INT,					/*来源单据编号*/
				@FromBillID		   INT,					/*来源单明细ID*/
				@FromBillType      INT,					/*来源单单据类型*/
				@FromBillQty       NUMERIC(24,10),		/*来源单据数量*/
				@FromBillName	   NVARCHAR(50),		/*来源单据名称*/
				@RowIndex          INT,					
				@RowCount          INT,					/*单明细行数*/
				@Qty			   NUMERIC(24,10),		/*数量*/
				@NQty			   NUMERIC(24,10),		/*辅助数量*/
				@PTypeID		   VARCHAR(100),		/*商品ID*/
				@FullName		   VARCHAR(100),		/*商品名称*/
				@CompletedQty	   NUMERIC(24,10),		/*已完成数量*/
				@ItemID            INT,
				@IsCombined        INT,
				@ProduceDate	   VARCHAR(50),
				@ValidDate         VARCHAR(50),
				@GoodsNumber	   VARCHAR(100),
				@InKTypeID		   VARCHAR(100),
				@InCargoID		   INT,
				@OutKTypeID		   VARCHAR(100),
				@OutCargoID		   INT,
				@SQL			   NVARCHAR(1000),
				@Return            INT,					/*返回值*/
				@UpdateSQL		   NVARCHAR(MAX),		/*更新发货数量SQL*/
				@CheckSQL          NVARCHAR(MAX)		/*验证发货数量SQL*/
				
	DECLARE	    @Tmp			   TABLE
	(
		PTypeID			 VARCHAR(100),
		FullName         VARCHAR(100),
		Qty				 NUMERIC(24,10),
		NQty		     NUMERIC(24,10),
		ItemID			 INT,
		IsCombined		 INT,
		ProduceDate      VARCHAR(50),
		ValidDate        VARCHAR(50),
		GoodsNumber		 VARCHAR(100),
		InKTypeID		 VARCHAR(100),
		InCargoID		 INT,
		OutKTypeID		 VARCHAR(100),
		OutCargoID		 INT,
		FromBillNumberID INT,
		FromBillID       INT,
		FromBillType     INT,
		RowIndex         INT
	)
	IF @BillType IN(418,419)
	BEGIN
		INSERT INTO @Tmp
					( 
					  Qty ,
					  NQty,
					  FromBillNumberID ,
					  FromBillID ,
					  FromBillType,
					  RowIndex,
					  PTypeID,
					  FullName,
					  ItemID,
					  IsCombined,
					  ProduceDate,
					  ValidDate,
					  GoodsNumber,
					  InKTypeID,
					  InCargoID,
					  OutKTypeID,
					  OutCargoID
					)
			SELECT A.Qty,
				   A.NQty,
				   A.FromBillNumberID,
				   A.FromBillID,
				   A.FromBillType,
				   ROW_NUMBER()OVER(ORDER BY A.ID ASC) AS RowIndex,
				   A.PTypeID,
				   B.FullName,
				   A.ItemID,
				   A.IsCombined,
				   A.ProduceDate,
				   A.ValidDate,
				   A.GoodsNumber,
				   CASE WHEN C.BillType=418 THEN A.ktypeid ELSE '' END,
				   CASE WHEN C.BillType=418 THEN A.CargoID ELSE 0 END,
				   CASE WHEN C.BillType=419 THEN A.ktypeid ELSE '' END,
				   CASE WHEN C.BillType=419 THEN A.CargoID ELSE 0 END
			FROM dbo.FactDepotInOut A 
			INNER JOIN dbo.ptype B ON A.ptypeid=B.typeId
			INNER JOIN dbo.FactIndex C ON A.BillNumberID=C.BillNumberID
			WHERE A.BillNumberID=@BillNumberID
	END
	ELSE	
	BEGIN
		INSERT INTO @Tmp
		        ( 
				  Qty ,
				  NQty,
		          FromBillNumberID ,
		          FromBillID ,
		          FromBillType,
		          RowIndex,
		          PTypeID,
		          FullName,
		          ItemID,
				  IsCombined,
				  ProduceDate,
				  ValidDate,
				  GoodsNumber,
				  InKTypeID,
				  InCargoID,
				  OutKTypeID,
				  OutCargoID
		        )
			SELECT A.Qty,
				   A.NQty,
				   0,
				   0,
				   0,
				   ROW_NUMBER()OVER(ORDER BY A.ID ASC) AS RowIndex,
				   A.PTypeID,
				   B.FullName,
				   A.ItemID,
				   A.IsCombined,
				   A.ProduceDate,
				   A.ValidDate,
				   A.GoodsNumber,
				   A.KTypeId2,
				   A.InCargoID,
				   A.KTypeId,
				   A.OutCargoID
			FROM dbo.FactDepotAllot A 
			INNER JOIN dbo.ptype B ON A.ptypeid=B.typeId
			WHERE BillNumberID=@BillNumberID
	END	

	/****仓库入库单 仓库出库单 引用 数量 验证 begin****/
	SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
	WHILE(@RowIndex<=@RowCount)
	BEGIN
		SELECT @FromBillNumberID=FromBillNumberID,
			   @FromBillID=FromBillID,
			   @FromBillType=FromBillType,
			   @Qty=Qty,
			   @NQty=NQty,
			   @PTypeID=PTypeID,
			   @FullName=FullName,
			   @ItemID=ItemID,
			   @IsCombined=IsCombined,
			   @ProduceDate=ProduceDate,
			   @ValidDate=ValidDate,
			   @GoodsNumber=GoodsNumber,
			   @InKTypeID=InKTypeID,
			   @InCargoID=InCargoID,
			   @OutKTypeID=OutKTypeID,
			   @OutCargoID=OutCargoID
		FROM @Tmp WHERE RowIndex=@RowIndex
		/*来源单据表*/
		SELECT @FromBillName=DetailTable FROM BIllName WHERE Billtype=@FromBillType
		
		/*仓库入库单*/
		IF @BillType=418
		BEGIN
			IF @QuoteBillInstock=1 AND @FromBillID<=0
			BEGIN
				SET @szPID='当前系统设置中配置了"只有通过引用单据的仓库入库单才能过账"'
						+'单据第['+CAST(@RowIndex AS VARCHAR)
						+']行商品【'+@FullName+'】不是引用单据的记录，不能过账'
				RETURN 4181
			END
			IF @FromBillNumberID>0
			BEGIN
				/*验证完成状态*/
				SET @CheckSQL ='IF EXISTS(
											SELECT 1 FROM ' +@FromBillName+' A INNER JOIN PType P ON A.PTypeID=P.TypeID 
											WHERE Abs(Qty)>ISNULL(InFactQty,0) AND BillNumberID=@FromBillNumberID  AND P.IsService=0 '
											+CASE WHEN @FromBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END+
										 ') 
								SET @Return=0 ELSE SET @Return=1'
								
				/*更新入库数量*/		
				SET @UpdateSQL='UPDATE '+@FromBillName +' 
								SET InFactQty=ISNULL(InFactQty,0)+@Qty 
								WHERE ID=@FromBillID ' +CASE WHEN @FromBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE '' END
				SET @Return=0

				exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@FromBillID INT',@Qty,@FromBillID
				exec sp_executesql @CheckSQL,N'@FromBillNumberID INT,@Return INT OUT',@FromBillNumberID,@Return OUT
					
				IF @FrombillType IN(71,72,87,88)
				BEGIN
					UPDATE dbo.LendIndex SET InFactState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@FromBillNumberID
				END
				ELSE IF @FrombillType IN(327,328,329)
				BEGIN
					UPDATE dbo.PosAllotApplyBillIndex SET InFactState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@FromBillNumberID
				END
				ELSE
				BEGIN
					UPDATE dbo.BillIndex SET InFactState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@FromBillNumberID
				END
			END
			IF @IsGreaterQuoteBillInStock=1
			BEGIN
				/*验证是否超过入库单数量*/
				SET @Return=0
				SET @CheckSQL=' IF EXISTS(
											SELECT 1 FROM '+ @FromBillName +'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
											WHERE ISNULL(InFactQty,0)>Abs(Qty) AND BillNumberID=@FromBillNumberID AND ID=@FromBillID  AND P.IsService=0 '
											+CASE WHEN @FromBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END
										+') 
								SET @Return=1 ELSE SET @Return=0'
				exec sp_executesql @CheckSQL,N'@FromBillNumberID INT,@FromBillID INT,@Return INT OUT',@FromBillNumberID,@FromBillID,@Return OUT
				IF @Return=1
				BEGIN
					SET @szPID='当前系统设置中配置了"仓库入库单数量大于来源单据数量不能过账"'
						+'单据第['+CAST(@RowIndex AS VARCHAR)
						+']行商品【'+@FullName+'】入库数量大于来源单据未入库数量，不能过账'
					RETURN 4182
				END
			END
		END
		/*仓库出库单*/
		ELSE IF @BillType=419
		BEGIN
			IF @QuoteBillOutstock=1 AND @FromBillID<=0
			BEGIN
				SET @szPID='当前系统设置中配置了"只有通过引用单据的仓库出库单才能过账"'
						+'单据第['+CAST(@RowIndex AS VARCHAR)
						+']行商品【'+@FullName+'】不是引用单据的记录，不能过账'
				RETURN 4191
			END
			IF @FromBillNumberID>0
			BEGIN
				/*验证完成状态*/
				SET @CheckSQL ='IF EXISTS(
											SELECT 1 FROM ' +@FromBillName+' A INNER JOIN PType P ON A.PTypeID=P.TypeID 
											WHERE Abs(Qty)>ISNULL(OutFactQty,0) AND BillNumberID=@FromBillNumberID  AND P.IsService=0 '
											+CASE WHEN @FromBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END+
										 ') 
								SET @Return=0 ELSE SET @Return=1'
				/*更新出库数量*/		
				SET @UpdateSQL='UPDATE '+@FromBillName +' 
								SET OutFactQty=ISNULL(OutFactQty,0)+@Qty 
								WHERE ID=@FromBillID ' +CASE WHEN @FromBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE '' END
				SET @Return=0
				
				exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@FromBillID INT',@Qty,@FromBillID
				exec sp_executesql @CheckSQL,N'@FromBillNumberID INT,@Return INT OUT',@FromBillNumberID,@Return OUT
			
				IF @FrombillType IN(71,72,87,88)
				BEGIN
					UPDATE dbo.LendIndex SET OutFactState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@FromBillNumberID
				END
				ELSE IF @FrombillType IN(327,328,329)
				BEGIN
					UPDATE dbo.PosAllotApplyBillIndex SET OutFactState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@FromBillNumberID
				END
				ELSE
				BEGIN
					UPDATE dbo.BillIndex SET OutFactState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@FromBillNumberID
				END
			END
			IF @IsGreaterQuoteBillOutStock=1
			BEGIN
				/*验证是否超过出库单数量*/
				SET @Return=0
				SET @CheckSQL=' IF EXISTS(
											SELECT 1 FROM '+ @FromBillName +'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
											WHERE ISNULL(OutFactQty,0)>Abs(Qty) AND BillNumberID=@FromBillNumberID AND ID=@FromBillID  AND P.IsService=0 '
											+CASE WHEN @FromBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END
										+') 
								SET @Return=1 ELSE SET @Return=0'
				exec sp_executesql @CheckSQL,N'@FromBillNumberID INT,@FromBillID INT,@Return INT OUT',@FromBillNumberID,@FromBillID,@Return OUT
				IF @Return=1
				BEGIN
					SET @szPID='当前系统设置中配置了"仓库出库单数量大于来源单据数量不能过账"'
						+'单据第['+CAST(@RowIndex AS VARCHAR)
						+']行商品【'+@FullName+'】出库数量大于来源单据未出库数量，不能过账'
					RETURN 4192
				END
			END
		END
		
		--处理库存数量
		EXEC @nRet= GP_Auditing_Fact_DealQty @BillNumberID=@BillNumberID,
									  @BillType=@BillType,
									  @Qty=@Qty,
									  @NQty=@NQty,
									  @ItemID=@ItemID,
									  @IsCombined=@IsCombined,
									  @GoodsNumber=@GoodsNumber,
									  @ProduceDate=@ProduceDate,
									  @ValidDate=@ValidDate,
									  @InKTypeID=@InKTypeID,
									  @InCargoID=@InCargoID,
									  @OutKTypeID=@OutKTypeID,
									  @OutCargoID=@OutCargoID,
									  @PTypeID=@PTypeID,
									  @FullName=@FullName,
									  @RowIndex=@RowIndex,
									  @szPID=@szPID OUT
		IF @nRet<>0 
		BEGIN
			RETURN @nRet
		END
		SET @RowIndex=@RowIndex+1
	END
	
	/****仓库入库单 仓库出库单 引用 数量 验证****/
	
	UPDATE dbo.FactIndex SET ifcheck='t',poster=@chvOpID,PostTime=GETDATE(),draft=0 WHERE BillNumberId=@BillNumberID
	
	/************inoutstocktable begin************/	
	IF @BillType=418    --仓库入库单
	BEGIN
		INSERT INTO dbo.Fact_InOutstocktable 
				( 
				   BillNumberId ,BillDate ,BillType ,PtypeId ,EtypeId ,KtypeId ,Qty ,OutFactoryDate ,
				   Audited ,GoodsNumber , ProduceDate ,ValidDate ,GoodsOrder , ID ,DTypeID ,STypeID ,PostTime ,
				   CargoID ,ItemID , IsCombined ,NQty , UnitRate , Comment,MUnitID,MUnitRate,UnitID
				)
		SELECT	   A.BillNumberID,B.BillDate,B.BillType,A.ptypeid,B.etypeid, A.ktypeid,A.qty,'',1,
				   A.GoodsNumber, A.ProduceDate,A.ValidDate,A.GoodsOrder,A.Id,'',B.Stypeid,B.PostTime,
			       A.CargoID,A.ItemID,A.IsCombined,A.NQty,A.UnitRate,A.comment,A.MUnitID,A.MUnitRate,A.UnitID
		FROM  dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId
		WHERE B.BillNumberId=@BillNumberID
	END
	ELSE IF @BillType=419 --仓库出库单
	BEGIN
		INSERT INTO dbo.Fact_InOutstocktable 
				( 
				   BillNumberId ,BillDate ,BillType ,PtypeId ,EtypeId ,KtypeId ,Qty ,OutFactoryDate ,
				   Audited ,GoodsNumber , ProduceDate ,ValidDate ,GoodsOrder , ID ,DTypeID ,STypeID ,PostTime ,
				   CargoID ,ItemID , IsCombined ,NQty , UnitRate , Comment,MUnitID,MUnitRate,UnitID
				)
		SELECT	   A.BillNumberID,B.BillDate,B.BillType,A.ptypeid,B.etypeid, A.ktypeid,-A.qty,GETDATE(),1,
				   A.GoodsNumber, A.ProduceDate,A.ValidDate,A.GoodsOrder,A.Id,'',B.Stypeid,B.PostTime,
				   A.CargoID,A.ItemID,A.IsCombined,-A.NQty,A.UnitRate,A.comment,A.MUnitID,A.MUnitRate,A.UnitID
		FROM  dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId
		WHERE B.BillNumberId=@BillNumberID
	END
	ELSE --仓库调拨单
	BEGIN
		INSERT INTO dbo.Fact_InOutstocktable 
				( 
				   BillNumberId ,BillDate ,BillType ,PtypeId ,EtypeId ,KtypeId ,Qty ,OutFactoryDate ,
				   Audited ,GoodsNumber , ProduceDate ,ValidDate ,GoodsOrder , ID ,DTypeID ,STypeID ,PostTime ,
				   CargoID ,ItemID , IsCombined ,NQty , UnitRate , Comment,MUnitID,MUnitRate,UnitID
				)
		SELECT    A.BillNumberID,B.BillDate,B.BillType,A.ptypeid,B.etypeid, A.ktypeid2,A.qty,'',1,
			      A.GoodsNumber, A.ProduceDate,A.ValidDate,A.GoodsOrder,A.Id,'',B.Stypeid,B.PostTime,
			      A.InCargoID,A.ItemID,A.IsCombined,A.NQty,A.UnitRate,A.comment,A.MUnitID,A.MUnitRate,A.UnitID
		FROM  dbo.FactDepotAllot A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId
		WHERE B.BillNumberId=@BillNumberID	
		
		INSERT INTO dbo.Fact_InOutstocktable 
				( 
				   BillNumberId ,BillDate ,BillType ,PtypeId ,EtypeId ,KtypeId ,Qty ,OutFactoryDate ,
				   Audited ,GoodsNumber , ProduceDate ,ValidDate ,GoodsOrder , ID ,DTypeID ,STypeID ,PostTime ,
				   CargoID ,ItemID , IsCombined ,NQty , UnitRate , Comment,MUnitID,MUnitRate,UnitID
				)
		SELECT    A.BillNumberID,B.BillDate,B.BillType,A.ptypeid,B.etypeid, A.ktypeid,-A.qty,GETDATE(),1,
			      A.GoodsNumber, A.ProduceDate,A.ValidDate,A.GoodsOrder,A.Id,'',B.Stypeid,B.PostTime,
			      A.OutCargoID,A.ItemID,A.IsCombined,-A.NQty,A.UnitRate,A.comment,A.MUnitID,A.MUnitRate,A.UnitID
		FROM  dbo.FactDepotAllot A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId
		WHERE B.BillNumberId=@BillNumberID	
	END	
	/************inoutstocktable end************/		
	
	/***************处理序列号 begin********************/
	EXEC @nRet=GP_SerialOperate_Fact @BillNumberID=@BillNumberID,
								     @BillType=@BillType,
								     @OperatorId=@chvOpID,
								     @szPID=@szPID OUT
	IF @nRet<>0 RETURN @nRet
	/***************处理序列号 end********************/
	
	RETURN 0
END
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	回填成本价等信息
	作    者：	冯波
	修改时间：	2011-08-16
*/
CREATE             PROCEDURE Gp_Auditing_Fill
(
	@nBillID				NUMERIC(10,0),				-- 单据 ID 号
	@intBillType			INT
	
)
----@encode$--
AS

	

	DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT
		
	DECLARE
		
		@strPriceDot		VARCHAR(10),
		@strMoneyDot		VARCHAR(10)
		
	SELECT
		@strPriceDot=@intPriceDot,
		@strMoneyDot=@intMoneyDot		
		

	DECLARE
		@intRedWord		TINYINT
		
	SELECT
		@intRedWord=RedWord
	FROM BillIndex
	WHERE BillNumberId=@nBillID
	
	
	DECLARE 
			@nCostingMethod		smallint,
			@AVERAGE			smallint,
			@FIFO				smallint,
			@LIFO				smallint,
			@HAND				smallint

	SET @AVERAGE	= 0		-- 移动加权平均
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	SET @HAND		= 3		-- 手工指定

	EXEC Gp_GetSubValue 'costing','',@nCostingMethod output

	IF @intBillType=57
	BEGIN
		DECLARE
		@intAdPriceBillType		INT
		
		SELECT @intAdPriceBillType=AdPriceType
		FROM Billindex
		WHERE BillNumberId=@nBillId
	END
------------------------------------存在关联的订单需要回填实付金额 start---------------------------------------------------
IF @intBillType IN( 4) --收款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM dbo.gatheringBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
  	BEGIN
        
		UPDATE dbo.OrderIndex  SET totalinmoney=ISNULL(G.total,0),ntotalinmoney=ISNULL(G.ntotal,0)
		FROM OrderIndex O INNER JOIN (
		
		SELECT  SUM(w.total) total,SUM(w.ntotal) ntotal,w.RelevanceBillId FROM(
		--收款单
			SELECT p.total total,p.ntotal ntotal,p.RelevanceBillId FROM dbo.gatheringBill P 
			INNER JOIN dbo.BillIndex x 
			on p.BillNumberId=x.BillNumberId
			where P.RelevanceBillId IN(SELECT RelevanceBillId FROM gatheringBill WHERE BillNumberId=@nBillId) AND RelevanceBillId>0  AND x.redword=0 AND ifcheck='t'
			UNION ALL 
		---预收款单
			SELECT G.total total,G.ntotal ntotal,RelevanceBillId FROM dbo.PreBill G
			INNER JOIN dbo.BillIndex x 
			on G.BillNumberId=x.BillNumberId			
			WHERE G.RelevanceBillId IN(SELECT RelevanceBillId FROM gatheringBill WHERE BillNumberId=@nBillId) AND G.RelevanceBillId>0  AND x.redword=0 AND ifcheck='t'
			
		)w GROUP BY w.RelevanceBillId						
		)G ON O.billNumberId=G.RelevanceBillId 
	END	
	
END
ELSE IF @intBillType IN( 189) --预收款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM dbo.PreBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
  	BEGIN
        
		UPDATE dbo.OrderIndex  SET totalinmoney=ISNULL(G.total,0),ntotalinmoney=ISNULL(G.ntotal,0)
		FROM OrderIndex O INNER JOIN (
		
		SELECT  SUM(w.total) total,SUM(w.ntotal) ntotal,w.RelevanceBillId FROM(
		--收款单
			SELECT p.total total,p.ntotal ntotal,p.RelevanceBillId FROM dbo.gatheringBill P 
			INNER JOIN dbo.BillIndex x 
			on p.BillNumberId=x.BillNumberId
			where P.RelevanceBillId IN(SELECT RelevanceBillId FROM PreBill WHERE BillNumberId=@nBillID) AND RelevanceBillId>0  AND x.redword=0 AND ifcheck='t'
			UNION ALL 
		---预收款单
			SELECT G.total total,G.ntotal ntotal,RelevanceBillId FROM dbo.PreBill G
			INNER JOIN dbo.BillIndex x 
			on G.BillNumberId=x.BillNumberId			
			WHERE G.RelevanceBillId IN(SELECT RelevanceBillId FROM PreBill WHERE BillNumberId=@nBillID) AND G.RelevanceBillId>0  AND x.redword=0 AND ifcheck='t'
			
		)w GROUP BY w.RelevanceBillId						
		)G ON O.billNumberId=G.RelevanceBillId 
	END	
	
END
ELSE IF @intBillType IN( 66 )--付款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM dbo.PayBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
	BEGIN
		UPDATE dbo.OrderIndex  SET totalinmoney=ISNULL(P.total,0),ntotalinmoney=ISNULL(P.ntotal,0)
		FROM OrderIndex O INNER JOIN (
		SELECT  SUM(w.total) total,SUM(w.ntotal) ntotal,w.RelevanceBillId FROM(
		--付款单
			SELECT p.total total,p.ntotal ntotal,p.RelevanceBillId FROM dbo.PayBill P 
			INNER JOIN dbo.BillIndex x 
			on p.BillNumberId=x.BillNumberId
			where P.RelevanceBillId IN(SELECT RelevanceBillId FROM PayBill WHERE BillNumberId=@nBillID) AND RelevanceBillId>0  AND x.redword=0 AND ifcheck='t'
			UNION ALL 
		--预付款单
			SELECT G.total total,G.ntotal ntotal,RelevanceBillId FROM dbo.PreBill G
			INNER JOIN dbo.BillIndex x 
			on G.BillNumberId=x.BillNumberId			
			WHERE G.RelevanceBillId IN(SELECT RelevanceBillId FROM PayBill WHERE BillNumberId=@nBillID) AND G.RelevanceBillId>0  AND x.redword=0 AND ifcheck='t'
			
		)w GROUP BY w.RelevanceBillId
		)P ON O.billNumberId=P.RelevanceBillId 
	END
END
ELSE IF @intBillType IN( 190)--预付款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM dbo.PreBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
	BEGIN
		UPDATE dbo.OrderIndex  SET totalinmoney=ISNULL(P.total,0),ntotalinmoney=ISNULL(P.ntotal,0)
		FROM OrderIndex O INNER JOIN (
		SELECT  SUM(w.total) total,SUM(w.ntotal) ntotal,w.RelevanceBillId FROM(
		--付款单
			SELECT p.total total,p.ntotal ntotal,p.RelevanceBillId FROM dbo.PayBill P 
			INNER JOIN dbo.BillIndex x 
			on p.BillNumberId=x.BillNumberId
			where P.RelevanceBillId IN(SELECT RelevanceBillId FROM PreBill WHERE BillNumberId=@nBillID) AND RelevanceBillId>0  AND x.redword=0 AND ifcheck='t'
			UNION ALL 
		--预付款单
			SELECT G.total total,G.ntotal ntotal,RelevanceBillId FROM dbo.PreBill G
			INNER JOIN dbo.BillIndex x 
			on G.BillNumberId=x.BillNumberId			
			WHERE G.RelevanceBillId IN(SELECT RelevanceBillId FROM PreBill WHERE BillNumberId=@nBillID) AND G.RelevanceBillId>0  AND x.redword=0 AND ifcheck='t'
			
		)w GROUP BY w.RelevanceBillId
		)P ON O.billNumberId=P.RelevanceBillId 
	END
END

------------------------------------存在关联的订单需要回填实付金额 end-----------------------------------------------------
	IF @intBillType=215
	BEGIN
		UPDATE RetailBackBill
		SET costprice=InputCostPrice
		WHERE BillNumberId=@nBillID AND OldId>0 AND InputCostPrice>0
	END
	
	


	--根据实际过账，更新成本调价单的数量（以前是在保存时，由页面写入的数量）
	IF @intBillType=57 AND @intAdPriceBillType=0
	BEGIN
		DECLARE
			@intChangeAllStock INT
			
		SELECT
			TOP 1 @intChangeAllStock=ChangeAllStock
		FROM AdPriceBill
		WHERE BillNumberId=@nBillID
		
			
		IF @intChangeAllStock=1
		BEGIN
		--勾选全部仓库的时候，基本单位数量为当前分支机构下的所有仓库的商品数量--敏捷4703
			
			BEGIN
				UPDATE AdPriceBill
				SET Qty=ROUND(ISNULL(b.csqty,0),@intQtyDot),total=ROUND(ISNULL(b.Qty,0)*Price,@intMoneyDot),NQty=ISNULL(b.NQty,0),
				UnitRate=CASE b.NQty WHEN 0 THEN 1 ELSE ROUND(CAST(b.Qty AS  NUMERIC(24, 10) )/CAST(b.NQty AS  NUMERIC(24, 10) ),@intTRateDot) END,
				BeforeTotal=CASE ISNULL(b.Qty,0) WHEN 0 THEN  0 ELSE ROUND(ISNULL(b.CostTotal,0),@intMoneyDot) END,--这里调整全部仓库 qty 为0 了 都算不出来了
				BeforePrice=CASE ISNULL(b.Qty,0) WHEN 0 THEN  dbo.F_RoundPrice(ISNULL(BeforePrice,0)) ELSE ROUND(CAST(ISNULL(b.CostTotal,0) AS  NUMERIC(24, 10) )/CAST(ISNULL(b.Qty,0) AS  NUMERIC(24, 10) ),@intPriceDot) END,
				Rate=CASE ISNULL(b.CostTotal,0) WHEN 0 THEN 100 
													ELSE CASE WHEN ISNULL(AdPriceBill.BeforePrice,0) =0 THEN 0
																ELSE ROUND(CAST(ISNULL(AdPriceBill.Price,0) /ISNULL(AdPriceBill.BeforePrice,0) AS  NUMERIC(24, 10)),@intTRateDot)*100
																END 
													 END
				
				FROM
				(
					SELECT a.ID,ABS(SUM(a.Qty)) AS Qty,ABS(SUM(a.CostTotal)) AS CostTotal,ABS(SUM(a.NQty)) AS NQty,c.qty as csqty,c.ptypeid
					FROM InOutstocktable a
					inner join 
					(select ABS(SUM(gs.Qty)) as qty,gs.ptypeid from GoodsStocks gs INNER JOIN (SELECT TypeID FROM Stock WHERE STypeID in(select stypeid FROM InOutstocktable a WHERE a.BillNumberId=@nBillID)) b ON gs.KTypeID=b.TypeID GROUP BY gs.ptypeid )c 
					on c.ptypeid=a.ptypeid
					WHERE a.BillNumberId=@nBillID AND a.HandZeroCost=0
					GROUP BY a.ID,c.qty,c.ptypeid
				) b
				WHERE AdPriceBill.BillNumberID=@nBillID 
				AND AdPriceBill.ID=b.ID
			END
		
			
			UPDATE AdPriceBill
			SET Qty=0,total=0,BeforePrice=0,BeforeTotal=0,NQty=0,Rate=100
			WHERE AdPriceBill.BillNumberID=@nBillID 
			AND AdPriceBill.ID NOT IN
			(
				SELECT a.ID
				FROM InOutstocktable a
				WHERE a.BillNumberId=@nBillID
			)
			
			
			UPDATE BillIndex
			SET totalqty=ISNULL(b.Qty,0),totalmoney=ISNULL(b.Total,0),NTotalMoney=ISNULL(b.Total,0)
			FROM
			(
				SELECT BillNumberID,ROUND(SUM(Qty),@intQtyDot) AS Qty,ROUND(SUM(Total),@intMoneyDot) AS Total
				FROM AdPriceBill
				WHERE BillNumberId=@nBillID
				GROUP BY BillNumberID
			) b
			WHERE BillIndex.BillNumberId=b.BillNumberID 
			
		END
		ELSE
		BEGIN
			IF EXISTS(
				SELECT ID
				FROM AdPriceBill
				WHERE BillNumberId=@nBillID
				
			) 
			BEGIN
				UPDATE AdPriceBill
				SET 
				BeforeTotal=ROUND(ISNULL(b.CostTotal,0),@intMoneyDot),
				BeforePrice=CASE ISNULL(b.Qty,0) WHEN 0 THEN 0 ELSE ROUND(CAST(ISNULL(b.CostTotal,0) AS  NUMERIC(24, 10) )/CAST(ISNULL(b.Qty,0) AS  NUMERIC(24, 10) ),@intPriceDot) END
				
				,
				Rate=CASE ISNULL(b.CostTotal,0) WHEN 0 THEN 100 ELSE ROUND(CAST(AdPriceBill.total AS NUMERIC(24,10))/CAST(ISNULL(b.CostTotal,0) AS NUMERIC(24,10)),@intTRateDot)*100 END
				
				FROM
				(
					SELECT a.ID,ABS(SUM(a.Qty)) AS Qty,ABS(SUM(a.CostTotal)) AS CostTotal,ABS(SUM(a.NQty)) AS NQty
					FROM InOutstocktable a
					WHERE a.BillNumberId=@nBillID  AND a.HandZeroCost=0
					GROUP BY a.ID
				) b
				WHERE AdPriceBill.BillNumberID=@nBillID 
				AND AdPriceBill.ID=b.ID
				
			
			END
		END
		
		
		
		RETURN
	END
	
	
	IF @intBillType=57 AND @intAdPriceBillType<>0
	BEGIN
		UPDATE InOutstocktable
		SET CostTotal=Total
		WHERE BillNumberId=@nBillID
	END

	
	
	IF @intBillType IN (201,202)
	BEGIN
		IF @intBillType=201
		BEGIN
			UPDATE dbo.InOutstocktable
			SET CostTotal=Total
			WHERE BillNumberId=@nBillID AND BillType=@intBillType
		END
	
		--其他出入库单
		IF @nCostingMethod=@HAND
		BEGIN
			UPDATE OtherInOutBill
			SET Total=CASE b.BillType WHEN 201 THEN  b.CostTotal ELSE -b.CostTotal END
			FROM
			(
				SELECT [ID],BillType,ROUND(SUM(CASE BILLTYPE WHEN 201 THEN Total ELSE CostTotal END),@intMoneyDot) AS CostTotal
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID],BillType
			) b
			WHERE OtherInOutBill.BillNumberID=@nBillID 
			AND OtherInOutBill.[ID]=b.ID 
			AND InputCostPrice=0
			
			
			
		END
		ELSE
		BEGIN
			
			UPDATE OtherInOutBill
			SET Total=CASE b.BillType WHEN 201 THEN  b.CostTotal ELSE -b.CostTotal END,Price=b.CostPrice
			FROM
			(
				SELECT [ID],BillType,ROUND(SUM(CASE BILLTYPE WHEN 201 THEN Total ELSE CostTotal END),@intMoneyDot) AS CostTotal,CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(CASE BILLTYPE WHEN 201 THEN Total ELSE CostTotal END) AS  NUMERIC(24, 10) ) /CAST(SUM(Qty) AS  NUMERIC(24, 10) ),@intPriceDot) END AS CostPrice
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID],BillType
			) b
			WHERE OtherInOutBill.BillNumberID=@nBillID 
			AND OtherInOutBill.[ID]=b.ID 
			AND InputCostPrice=0
			
			
			
			IF @intBillType=202
			BEGIN
				--其他出库单,大单位单价
				UPDATE OtherInOutBill
				SET MPrice=CASE WHEN MQty=Qty THEN OtherInOutBill.Price ELSE ROUND(CAST(OtherInOutBill.Total AS NUMERIC(22,10))/CAST(OtherInOutBill.MQty AS NUMERIC(22,10)),@intPriceDot) END
				WHERE OtherInOutBill.BillNumberID=@nBillID 
				
			END
		END
		
		UPDATE Billindex
		SET totalmoney=b.Total,NTotalMoney=b.Total
		FROM
		(
			SELECT SUM(Total) AS Total
			FROM OtherInOutBill
			WHERE BillNumberId=@nBillID
		) b
		WHERE Billindex.BillNumberId=@nBillID
		
		RETURN
	
	END
	
	IF @intBillType=205 AND @intRedWord=0
	BEGIN
		UPDATE BuyBill
		SET ShareFee=ISNULL(BuyBill.ShareFee,0)+b.ShareFee
		From ShareSourceBill b
		WHERE b.BillNumberId=@nBillID
		AND BuyBill.ID=b.FromBillID AND b.FromBillType=34
		
		UPDATE disassemblebill
		SET ShareFee=ISNULL(disassemblebill.ShareFee,0)+b.ShareFee
		From ShareSourceBill b
		WHERE b.BillNumberId=@nBillID
		AND disassemblebill.ID=b.FromBillID AND b.FromBillType=16
		
		UPDATE InOutstocktable
		SET ShareFee=ISNULL(InOutStockTable.ShareFee,0)+b.ShareFee
		From ShareSourceBill b
		WHERE b.BillNumberId=@nBillID
		AND InOutstocktable.BillNumberId=b.FromBillNumberID AND b.FromBillType=dbo.InOutstocktable.BillType
		AND InOutstocktable.ID=b.FromBillID
		
		RETURN
	END
	
	IF @intBillType=205 AND @intRedWord<>0
	BEGIN
		UPDATE BuyBill
		SET ShareFee=ISNULL(BuyBill.ShareFee,0)-b.ShareFee
		From ShareSourceBill b
		WHERE b.BillNumberId=@nBillID
		AND BuyBill.ID=b.FromBillID AND b.FromBillType=34
		
		UPDATE disassemblebill
		SET ShareFee=ISNULL(disassemblebill.ShareFee,0)-b.ShareFee
		From ShareSourceBill b
		WHERE b.BillNumberId=@nBillID
		AND disassemblebill.ID=b.FromBillID AND b.FromBillType=16
		
		UPDATE InOutstocktable
		SET ShareFee=ISNULL(InOutStockTable.ShareFee,0)-b.ShareFee
		From ShareSourceBill b
		WHERE b.BillNumberId=@nBillID
		AND InOutstocktable.BillNumberId=b.FromBillNumberID AND b.FromBillType=dbo.InOutstocktable.BillType
		AND InOutstocktable.ID=b.FromBillID
		
		RETURN
	END
	
	IF @intBillType=34
	BEGIN
		IF EXISTS(
			SELECT c.ID
			FROM BuyBill a
			INNER JOIN OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN RequestBill c
			ON b.RequestBillID=c.ID
			WHERE a.BillNumberId=@nBillID 
			AND a.OrderID<>-1
		)
		BEGIN
			SELECT c.ID INTO #TempBuyBill
			FROM BuyBill a
			INNER JOIN OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN RequestBill c
			ON b.RequestBillID=c.ID
			WHERE a.BillNumberId=@nBillID 
			AND a.OrderID<>-1
		
	    	--当发货完成后 才更新状态
			UPDATE RequestBill
			SET State=9
			FROM #TempBuyBill b
			WHERE RequestBill.ID=b.ID
			AND RequestBill.RequestQty >= dbo.RequestBill.Qty;
			
			DROP TABLE #TempBuyBill
		END
		RETURN
	END
	
	
	IF @intBillType=9
	BEGIN
		UPDATE Billindex
		SET totalmoney=b.Total,NTotalMoney=b.Total
		FROM 
		(	SELECT SUM(Total) AS Total
			FROM LoseBill
			WHERE BillNumberId=@nBillID
		) b
		WHERE BillIndex.BillNumberId=@nBillID
	END
	
	
	
	IF @intBillType=14
	BEGIN
		UPDATE Billindex
		SET totalmoney=b.Total,NTotalMoney=b.Total
		FROM 
		(	SELECT SUM(Total) AS Total
			FROM overflowBill
			WHERE BillNumberId=@nBillID
		) b
		WHERE BillIndex.BillNumberId=@nBillID	
	END


	IF @intBillType IN (173)
	BEGIN
		--维修调入单
		IF @nCostingMethod=@HAND
		BEGIN
			UPDATE wx_Bill_In
			SET Total=b.CostTotal
			FROM
			(
				SELECT [ID],ROUND(SUM(ABS(CostTotal)),@intMoneyDot) AS CostTotal
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID]
			) b
			WHERE wx_Bill_In.BillNumberID=@nBillID 
			AND wx_Bill_In.[ID]=b.ID 
			AND InputCostPrice=0	
		END
		ELSE
		BEGIN
			UPDATE wx_Bill_In
			SET Total=b.CostTotal,Price=b.CostPrice
			FROM
			(
				SELECT [ID],ROUND(SUM(ABS(CostTotal)),@intMoneyDot) AS CostTotal,CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS  NUMERIC(24, 10) ) /CAST(SUM(ABS(Qty)) AS  NUMERIC(24, 10) ),@intPriceDot) END AS CostPrice
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID]
			) b
			WHERE wx_Bill_In.BillNumberID=@nBillID 
			AND wx_Bill_In.[ID]=b.ID 
			AND InputCostPrice=0
		END
		
		UPDATE Billindex
		SET totalmoney=b.Total,NTotalMoney=b.Total
		FROM
		(
			SELECT SUM(Total) AS Total
			FROM wx_Bill_In
			WHERE BillNumberId=@nBillID
		) b
		WHERE Billindex.BillNumberId=@nBillID
		
		RETURN
	
	END

	IF @intBillType IN (166)
	BEGIN
		--维修单
		
		
		IF @nCostingMethod=@HAND
		BEGIN
			UPDATE wx_bill_self
			SET GoodsCostTotal=b.CostTotal
			FROM
			(
				SELECT [ID],ROUND(SUM(ABS(CostTotal)),@intMoneyDot) AS CostTotal
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID]
			) b
			WHERE wx_bill_self.BillNumberID=@nBillID 
			AND wx_bill_self.[ID]=b.ID 
			AND InputCostPrice=0	
		END
		ELSE
		BEGIN
			UPDATE wx_bill_self
			SET GoodsCostTotal=b.CostTotal,GoodsCostPrice=b.CostPrice
			FROM
			(
				SELECT [ID],ROUND(SUM(ABS(CostTotal)),@intMoneyDot) AS CostTotal,CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS  NUMERIC(24, 10) ) /CAST(SUM(ABS(Qty)) AS  NUMERIC(24, 10) ),@intPriceDot) END AS CostPrice
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID]
			) b
			WHERE wx_bill_self.BillNumberID=@nBillID 
			AND wx_bill_self.[ID]=b.ID 
			
		END
		
		
		RETURN
	
	END


	IF @intBillType IN (168)
	BEGIN
		--整机更换单 
		IF @nCostingMethod=@HAND
		BEGIN
			UPDATE wx_bill_replace
			SET GoodsCostTotal=b.CostTotal
			FROM
			(
				SELECT [ID],ROUND(SUM(ABS(CostTotal)),@intMoneyDot) AS CostTotal
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID]
			) b
			WHERE wx_bill_replace.BillNumberID=@nBillID 
			AND wx_bill_replace.[ID]=b.ID 
			AND InputCostPrice=0	
		END
		ELSE
		BEGIN
			UPDATE wx_bill_replace
			SET GoodsCostTotal=b.CostTotal,GoodsCostPrice=b.CostPrice
			FROM
			(
				SELECT [ID],ROUND(SUM(ABS(CostTotal)),@intMoneyDot) AS CostTotal,CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS  NUMERIC(24, 10) ) /CAST(SUM(ABS(Qty)) AS  NUMERIC(24, 10) ),@intPriceDot) END AS CostPrice
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID]
			) b
			WHERE wx_bill_replace.BillNumberID=@nBillID 
			AND wx_bill_replace.[ID]=b.ID 
			
		END
		
		
		RETURN
	
	END

	IF @intBillType=16
	BEGIN
		UPDATE DisassembleBill
		SET costprice=CASE DisassembleBill.InputCostPrice WHEN 0 THEN b.CostPrice ELSE DisassembleBill.InputCostPrice END,
		Total=-b.CostTotal,
		CurMSalePrice=CASE DisassembleBill.Qty WHEN 0 THEN dbo.F_RoundPrice(0) ELSE  dbo.F_RoundPrice((-b.CostTotal/DisassembleBill.Qty)*DisassembleBill.MUnitRate) END 
		FROM InOutstocktable b
		WHERE DisassembleBill.BillNumberId=@nBillID
		AND DisassembleBill.inorout='O'
		AND DisassembleBill.ID=b.ID
		AND b.BillType=16
		
	END
	
	
	
	
	IF @intBillType IN (172)
	BEGIN
		--上门维修单
		
		
		IF @nCostingMethod=@HAND
		BEGIN
			UPDATE wx_bill_goto
			SET GoodsCostTotal=b.CostTotal
			FROM
			(
				SELECT [ID],ROUND(SUM(ABS(CostTotal)),@intMoneyDot) AS CostTotal
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID]
			) b
			WHERE wx_bill_goto.BillNumberID=@nBillID 
			AND wx_bill_goto.[ID]=b.ID 
			AND InputCostPrice=0	
		END
		ELSE
		BEGIN
			UPDATE wx_bill_goto
			SET GoodsCostTotal=b.CostTotal,GoodsCostPrice=b.CostPrice
			FROM
			(
				SELECT [ID],ROUND(SUM(ABS(CostTotal)),@intMoneyDot) AS CostTotal,CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS  NUMERIC(24, 10) ) /CAST(SUM(ABS(Qty)) AS  NUMERIC(24, 10) ),@intPriceDot) END AS CostPrice
				FROM InOutStockTable
				WHERE BillNumberID=@nBillID
				GROUP BY [ID]
			) b
			WHERE wx_bill_goto.BillNumberID=@nBillID 
			AND wx_bill_goto.[ID]=b.ID 
			
		END
		
		
		RETURN
	
	END
	
	
	IF @intBillType=401
	BEGIN
		UPDATE AppraisalBackBill
		SET CostPrice=InputCostPrice,CostTotal=ROUND(InputCostPrice*Qty,@intMoneyDot)
		WHERE BillNumberId=@nBillID
	END
	
	IF @intBillType=403
	BEGIN
		--现在发出商品退货单支持手工录入了，所以取值方式变了
		UPDATE SendBackBill
		SET CostPrice=b.CostPrice,CostTotal=b.CostTotal
		FROM InOutstocktable b
		WHERE SendBackBill.BillNumberId=@nBillID
		AND b.BillNumberId=@nBillID
		AND b.BillType=@intBillType
		AND SendBackBill.ID=b.ID

	END
	
	IF @intBillType=402
	BEGIN
		UPDATE SendBill
		SET CostPrice=b.CostPrice,
			CostTotal=-b.CostTotal
		FROM InOutstocktable b
		WHERE SendBill.BillNumberId=@nBillID
		AND b.BillNumberId=@nBillID
		AND b.BillType=@intBillType
		AND SendBill.ID=b.ID
		
		DECLARE
			@intCID			INT,
			@intCostSale	TINYINT
			
		SELECT
			@intCID=CID,
			@intCostSale=CostSale
		FROM BillIndex
		WHERE 	BillNumberId=@nBillID	
				
		IF @intCostSale=1
		BEGIN
			EXEC	GP_Auditing_DealSendBill
				@nBillID,
				402,
				1,
				@intCID
			
			--处理科目
			
			EXEC	Gp_CreateQtMx	@nBillId,@intBillType,'' 
		
			EXEC Gp_CreateManageRep @nBillID,@intBillType
		END		
	END

	IF @intBillType=327
	BEGIN
		--反写门店配送单成本价
		UPDATE DeliveryBill
		SET GoodsCostPrice=b.CostPrice
		,GoodsCostTotal=-b.CostTotal
		,price=case  c.costsale when 1 then b.CostPrice else DeliveryBill.price END
        ,MPrice=case  c.costsale when 1 then dbo.F_RoundPrice(b.CostPrice*DeliveryBill.MUnitRate) else DeliveryBill.MPrice end
		,total=case  c.costsale when 1 then -b.CostTotal else DeliveryBill.total end
		FROM InOutstocktable b
		inner join PosAllotApplyBillIndex c on  b.BillNumberId=c.BillNumberId
		WHERE DeliveryBill.BillNumberId=@nBillID
		AND b.BillNumberId=@nBillID
		AND b.BillType=@intBillType
		AND DeliveryBill.ID=b.ID


	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'Gp_Auditing_Lend') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure Gp_Auditing_Lend
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	借欠过账
*/
CREATE             PROCEDURE Gp_Auditing_Lend
(
	@nBillID				NUMERIC(10,0),					-- 单据 ID 号
	@szCheckMan				VARCHAR(50),					-- 制单人 ID 值
	@chvOpID				VARCHAR(50) = '',				-- 当前操作员 ID 值
	@billtype				INT = 0	,						-- 单据类型
	@szPID 					varchar(1000)=''	output
	--@voucherMsg				VARCHAR(50)	= '' OUTPUT			--返回凭证生成的信息
)
--@encode$--
AS
	SET NOCOUNT ON
	
	--处理部分校验
	DECLARE	@nRet	INT , @FullName VARCHAR(200)
	SELECT @nRet=0	

	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngSerial' AND Value = '1')
	BEGIN
		SELECT TOP 1 @FullName = b.FullName FROM dbo.LendBill a WITH (NOLOCK)   
		JOIN dbo.ptype b ON a.PtypeId = b.typeId 
		WHERE BillNumberId = @nBillID AND a.Serial = '' AND b.IfSerial = '1'
		IF @FullName <> ''
		BEGIN
			SET @szPID = '商品【'+@FullName+'】是严格序列号商品，单据中该商品没有填写序列号！'
			RETURN -711
		END
	END
	
	--明细验证
	IF @billtype = 72 OR @billtype = 88 
	BEGIN
		EXEC @nRet = Gp_LendBillCheck @nBillID,@szPID OUTPUT
		IF @nRet <> 0
			RETURN @nRet
	END
	
	UPDATE dbo.LendIndex
	SET draft=0,ifcheck='t',Poster=@chvOpID,PostTime=GETDATE()
	WHERE BillNumberId=@nBillID
	
	IF @@ROWCOUNT = 0
	BEGIN
        SET @nRet = -1
        RETURN @nRet     
	END


	IF  EXISTS( SELECT Serial FROM dbo.LendBill WHERE BillNumberId = @nBillID  AND  Serial !='')
	BEGIN
	
		DECLARE   
		@chrOperateType		int,				-- 序列号状态
		@Serial				VARCHAR(MAX ),		
		@chvSerial			varchar(1000),		-- 序列号
		@chvBillDate		varchar(50)	= '',	-- 单据日期 
		@chvPTypeID			varchar(50)	= '',	-- 商品 ID 值
		@chvKTypeID			varchar(50)	= '',	-- 仓库 ID 值 
		@chvInKTypeID		varchar(50)	= '',	
		@chvBTypeID			varchar(50)	= '',	-- 往来单位 ID 值
		@chvItemId			int=0,				-- 自由项
		@chvGoodsNumber		varchar(100)=''	,	-- 批号
		@state				INT = 0	,			-- 退出游标标志
		@chvIsCombined		BIT = 0				-- 组合
		
		SELECT @chvBillDate = BillDate,@chvKTypeID = ktypeid,@chvBTypeID = dealbtypeid FROM dbo.LendIndex WHERE BillNumberId = @nBillID
		IF @billtype = 71
			SET @chrOperateType = 17 
		ELSE IF @billtype = 72
			SET @chrOperateType = 19
		ELSE IF @billtype = 87
			SET @chrOperateType = 18
		ELSE IF @billtype = 88
			SET @chrOperateType = 20
		
			DECLARE CURSORT CURSOR FOR
			SELECT Serial,PtypeId, ISNULL(ItemID,0),ISNULL(GoodsNumber,''),IsCombined FROM dbo.LendBill WHERE BillNumberId = @nBillID  AND  Serial !=''
			OPEN CURSORT
			FETCH NEXT FROM CURSORT INTO @Serial ,@chvPTypeID ,@chvItemId ,@chvGoodsNumber,@chvIsCombined
			WHILE @@FETCH_STATUS = 0
			BEGIN
				IF @state <> 0
					BREAK

				DECLARE CURSORT00 CURSOR FOR
				SELECT a AS 'Serial' FROM  dbo.f_split(@Serial,'я') WHERE a !='' 
				OPEN CURSORT00
				FETCH NEXT FROM CURSORT00 INTO @chvSerial 
				WHILE @@FETCH_STATUS = 0
				BEGIN
					--SELECT '@chrOperateType=',@chrOperateType,'@chvKTypeID=',@chvKTypeID
					 
					 EXEC @nRet = dbo.Gp_SerialOperateForLend 
					     @chrOperateType = @chrOperateType , -- int
					     @chvSerial = @chvSerial , -- varchar(50)
					     @chvBillNumberID = @nBillID , -- varchar(50)
					     @intBillType = @billtype , -- int
					     @chvBillDate = @chvBillDate , -- varchar(50)
					     @chvPTypeID = @chvPTypeID , -- varchar(50)
					     @chvKTypeID = @chvKTypeID , -- varchar(50)
					     @chvInKTypeID = '' , -- varchar(50)
					     @chvBTypeID = @chvBTypeID , -- varchar(50)
					     @chvItemId = @chvItemId , -- int
					     @chvGoodsNumber = @chvGoodsNumber, -- varchar(100)
						 @chvIsCombined = @chvIsCombined	-- bit
						 
					SELECT '@nRet=',@nRet						 
					 IF @nRet <> 0
					 BEGIN
						 SET @state = 1
                         IF @nRet = -1
                         BEGIN 
							IF @billtype = 87
								SET @szPID = '序列号'+@chvSerial+'已经借出，不能再次借出，请确认后重试!'
							ELSE IF @billtype = 88
								SET @szPID = '序列号'+@chvSerial+'在借欠序列号库中没有借出记录，请确认后重试!'
							ELSE IF @billtype = 71
								SET @szPID = '序列号'+@chvSerial+'已经存在，请确认后重试!'
							ELSE IF @billtype = 72
								SET @szPID = '序列号'+@chvSerial+'在当前借欠序列号库中没有借进记录存在或已被借出，请先进行借出还回，请确认后重试!'
                         END
                         ELSE IF @nRet = -2
							SET @szPID = '序列号'+@chvSerial+'在当前借欠序列号库中没有借进记录存在或已被借出，请先进行借出还回，请确认后重试!'
						 ELSE IF @nRet = -3
							SET @szPID = '更新借欠序列号库失败，请确认后重试!'
						 ELSE IF @nRet = -4
						 BEGIN
							DECLARE @chvPFullName VARCHAR(200)	= ''
							SELECT @chvPFullName = FullName FROM dbo.ptype WHERE typeId = @chvPTypeID
							--SET @szPID = '写入借欠序列号库失败，请确认后重试!'
							SET @szPID = '商品【'+@chvPFullName+'】和序列号'+@chvSerial+'关联不正确，请确认后重试!'
						 END
						 ELSE IF @nRet = -5
							SET @szPID = '序列号'+@chvSerial+'在库存中不存在，请确认后重试!'
						 ELSE IF @nRet = -77
							SET @szPID = '删除序列号'+@chvSerial+'出入库记录失败，请确认后重试!'
						 ELSE IF @nRet = -88
						 BEGIN
							IF @billtype = 71
								SET @szPID = '序列号'+@chvSerial+'借进仓库与真实仓库不一致，请确认后重试!'
							ELSE
								SET @szPID = '序列号'+@chvSerial+'仓库属性不正确，不能保存!'
						 END
						 ELSE IF @nRet = -99
						 	SET @szPID = '仓库属性不正确，不能保存!'
						 ELSE IF @nRet = -100
							SET @szPID = '在当前序列号库存中已存在，不允许入库!'
						 ELSE IF @nRet = -101
							SET @szPID = '序列号'+@chvSerial+'在当前序列号库中已存在配送在途的状态!'
						BREAK
						
					 END
					 
					 FETCH NEXT FROM CURSORT00 INTO @chvSerial
				END
				CLOSE CURSORT00
				DEALLOCATE CURSORT00
				
				
				FETCH NEXT FROM CURSORT INTO @Serial ,@chvPTypeID ,@chvItemId ,@chvGoodsNumber,@chvIsCombined
			END
			CLOSE CURSORT
			DEALLOCATE CURSORT
			
			IF @nRet<> 0
				RETURN -711
			
	END
	
			
	INSERT INTO dbo.LendCheck
			( pTypeId ,
			  pEntryCode ,
			  kTypeId ,
			  bTypeID ,
			  DealBtypeId ,
			  ETypeId ,
			  BillNumberID ,
			  BillDate ,
			  BillType ,
			  BillCode ,
			  Comment ,
			  STypeID ,
			  Qty ,
			  ItemID ,
			  IsCombined ,
			  NQty ,
			  GoodsNumber ,
			  Producedate ,
			  ValidDate ,
			  CustomdetailID
			)
	SELECT * FROM (
			SELECT 
				lb.PtypeId
				,p.EntryCode
				,li.ktypeid
				,li.btypeid
				,li.dealbtypeid
				,li.etypeid
				,li.BillNumberId
				,li.BillDate
				,li.BillType
				,li.BillCode
				,li.Comment
				--,li.ktypeid2
				,li.Stypeid,
				lb.Qty ,
				lb.ItemID ,
				lb.IsCombined ,
				lb.NQty ,
				lb.GoodsNumber ,
				lb.Producedate ,
				lb.ValidDate ,
				lb.Id 
				FROM LendIndex li 
				INNER JOIN dbo.LendBill lb ON li.BillNumberId = lb.BillNumberId
				INNER JOIN dbo.ptype p ON lb.PtypeId = p.typeId
				WHERE li.BillNumberId = @nBillID) AS T
	
	IF @@ROWCOUNT = 0
	BEGIN
        SET @nRet = -1
        RETURN @nRet     
	END
	EXEC gp_SetLendGoods @nBillID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*



DECLARE
	@nBillID				NUMERIC(10,0),					-- 单据 ID 号
	@szCheckMan				VARCHAR(50),					-- 制单人 ID 值
	@chvOpID				VARCHAR(50),					-- 当前操作员 ID 值
	@billtype				INT = 0	,						-- 单据类型
	@szPID 					varchar(1000),
	@nRet					INT	

SELECT
	@nBillID=7,
	@szCheckMan='00001',
	@chvOpID='00001',
	@billtype=87
	
BEGIN TRAN

EXEC
	@nRet=
	Gp_Auditing_Lend
	@nBillID,
	@szCheckMan,
	@chvOpID,
	@billtype,
	@szPID
	
SELECT @nRet,@szPID	
	

ROLLBACK TRAN



*/





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'Gp_Auditing_LendBuySale') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure Gp_Auditing_LendBuySale
GO


CREATE  PROCEDURE Gp_Auditing_LendBuySale
(
	@nBillID			NUMERIC(10,0),				-- 单据 ID 号
    @BillType			INT 
    --@szPID 				VARCHAR(1000)=''	OUTPUT
)
AS
	SET NOCOUNT ON 

	DECLARE 
	@BtypeID		VARCHAR(50)
	
	CREATE TABLE #tempbill
	(
		PtypeId				VARCHAR(50),
		KtypeId				VARCHAR(50),
		ItemID				INT,
		IsCombined			INT,
		GoodsNumber			VARCHAR(100),
		Qty					NUMERIC(24,10),
		NQty				NUMERIC(24,10)
	)

	SELECT @BtypeID = DealBTypeID FROM dbo.BillIndex WHERE BillNumberId = @nBillID
	
	/******借欠转采购销售功能 更新LendBill 已转采购销售数量 begin******/
	IF @BillType = 34  
	BEGIN
		UPDATE A SET A.BuyQty = ISNULL( A.BuyQty ,0) + B.Qty
		FROM LendBill A JOIN (
			 SELECT @nBillID AS BillNumberId, LendBillNumberID,SUM(qty) AS Qty 
			 FROM dbo.BuyBill
			 WHERE BillNumberId = @nBillID AND LendBillNumberID <> 0
			 GROUP BY LendBillNumberID
		) B ON A.ID=B.LendBillNumberID
	END
	
	ELSE IF @BillType = 11  
	BEGIN
		UPDATE A SET A.SaleQty = ISNULL( A.SaleQty ,0) + B.Qty
		FROM LendBill A JOIN (
			SELECT @nBillID AS BillNumberId, LendBillNumberID,SUM(qty) AS Qty 
			FROM dbo.SaleBill
			WHERE BillNumberId = @nBillID AND LendBillNumberID <> 0
			GROUP BY LendBillNumberID
		) B ON A.ID=B.LendBillNumberID
	END
	ELSE IF @BillType = 12  
	BEGIN
		UPDATE A SET A.SaleQty = ISNULL( A.SaleQty ,0) + B.Qty
		FROM LendBill A JOIN (
			SELECT @nBillID AS BillNumberId, LendBillNumberID,SUM(qty) AS Qty 
			FROM dbo.PT_Combin_SaleBillDetail
			WHERE BillNumberId = @nBillID AND LendBillNumberID <> 0
			GROUP BY LendBillNumberID
		) B ON A.ID=B.LendBillNumberID
	END
	/******借欠转采购销售功能 更新LendBill 已转采购销售数量 end  ******/
	

	
	/****** 更新借欠库存 begin******/
	IF @BillType = 11 
	BEGIN
		INSERT INTO #tempbill( PtypeId ,KtypeId, ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
		SELECT PtypeId, KtypeId,ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
		FROM dbo.SaleBill WHERE BillNumberId = @nBillID 
		GROUP BY PtypeId, KtypeId,ItemID,IsCombined,GoodsNumber
	END
	ELSE IF @BillType = 12 
	BEGIN
		INSERT INTO #tempbill( PtypeId ,KtypeId, ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
		SELECT PtypeId, KtypeId,ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
		FROM dbo.PT_Combin_SaleBillDetail WHERE BillNumberId = @nBillID 
		GROUP BY PtypeId, KtypeId,ItemID,IsCombined,GoodsNumber
	END
	ELSE 
	BEGIN
		INSERT INTO #tempbill( PtypeId , KtypeId,ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
		SELECT PtypeId, KtypeId,ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
		FROM dbo.BuyBill WHERE BillNumberId = @nBillID 
		GROUP BY PtypeId, KtypeId,ItemID,IsCombined,GoodsNumber
	END
	
	SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber,
	SUM(BorrowQty) BorrowQty,SUM(NBorrowQty) NBorrowQty,SUM(LendQty) LendQty,SUM(NLendQty) NLendQty
	INTO #goodslendtemp 
	FROM (
	
		SELECT		
			t1.PtypeId, 	
			t1.KtypeId,
			@BtypeID AS bTypeID,
			t1.ItemID,
			t1.IsCombined,
			t1.GoodsNumber,
			CASE @BillType WHEN 34 THEN  -Qty   ELSE 0 END AS BorrowQty, --借进
			CASE @BillType WHEN 34 THEN  -NQty  ELSE 0 END AS NBorrowQty,
			CASE WHEN @BillType IN (11,12) THEN  -Qty   ELSE 0 END AS LendQty,
			CASE WHEN @BillType IN (11,12) THEN  -NQty  ELSE 0 END AS NLendQty
		FROM #tempbill t1 
		
		UNION ALL
		
		SELECT a.PtypeId,a.KtypeId,a.BtypeId,a.ItemID,a.Iscombined,a.GoodsNumber,a.BorrowQty,a.NBorrowQty,a.LendQty,a.NLendQty 
		FROM dbo.GoodsLend a JOIN #tempbill b
		ON (a.PtypeId = b.PtypeId 
			AND a.KtypeId = b.KtypeId
			AND a.ItemID = b.ItemID
			AND a.Iscombined = b.IsCombined
			AND a.GoodsNumber = b.GoodsNumber
			AND a.BtypeId = @BtypeID)
		
	)AS t2 GROUP BY PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber

	DELETE b FROM #goodslendtemp a JOIN GoodsLend b 
	ON b.PtypeId = a.PtypeId 
	AND b.KtypeId = a.KtypeId
	AND b.BtypeId = a.BtypeId
	AND b.ItemID = a.ItemID
	AND b.Iscombined = a.Iscombined
	AND b.GoodsNumber = a.GoodsNumber

	INSERT INTO dbo.GoodsLend( PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,LendQty,NLendQty,Qty,NQty)
	SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,LendQty,NLendQty, 
	(BorrowQty - LendQty) AS Qty, (NBorrowQty - NLendQty) AS NQty FROM #goodslendtemp

	DROP TABLE #goodslendtemp

	--DELETE GoodsLend WHERE Qty = 0 AND NQty = 0
	--SELECT * from GoodsLend
	/****** 更新借欠库存 end  ******/
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Auditing_MulAccount]')and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop Procedure [dbo].[GP_Auditing_MulAccount]
GO



/*

功能说明：      多账户写入listtable和扣减atype_total 

作    者：       冯波

创建日期：       2004-6-10

修改日期:		 2014-05-04

返回结果：  

描    述：
		--循环过账（要特别处理预收，预付，会员储值）
		--如果用会员储值的，还要对会员卡先进行判断，判断单张的金额是否足够，合计的金额是否够会员储值
		--因为可以多选帐户，所以需要合计后来判断     

*/

CREATE PROCEDURE [GP_Auditing_MulAccount]
(
	@nBillID			NUMERIC(10,0),			--单据
	@intBillType		INT,
	@NewPosBill			TINYINT,
	@StypeID			VARCHAR(100),			--分支机构
	@strMsg				VARCHAR(200) OUTPUT
)
--@encode$--        
AS

/*

对VIP卡是否金额够的判断，需要全部改掉

对于成本价销售，还要特殊处理  GP_Auditing_SaleListTable

会员储值可以选多张会员卡，但积分是按表头的积分


*/

--没有多账户信息
IF NOT EXISTS(SELECT BillNumberID FROM BillMulAccount WHERE BillNumberID=@nBillID AND billtype=@intBillType)
BEGIN
	RETURN 0
END

DECLARE
		@PrePay_ID			varchar(50),
		@PreGathering_ID	varchar(50),
		@VIPSaving_ID		varchar(50),
		@nRet				INT,
		@syscid				INT,
		@YhSaving_ID		varchar(50),
		@DJSaving_ID		varchar(50)
		
	SELECT @PrePay_ID = nId	FROM Ac_Items WHERE UserCode='1151' --预付账款
	SELECT @PreGathering_ID = nId  FROM Ac_Items WHERE UserCode='2131' --预收账款	
	SELECT @VIPSaving_ID = nId   FROM Ac_Items WHERE UserCode='2181' --会员储值
	SELECT  @YhSaving_ID= nId  FROM  Ac_Items WHERE UserCode='2191' --优惠券
	SELECT @DJSaving_ID=nId FROM Ac_Items WHERE UserCode='044597' --市场活动费用 处理代金券
	
	SELECT @syscid=CId FROM Ac_Currency WHERE Sysrow = 1

	DECLARE
		@chvATypeID			VARCHAR(50),
		@numTotal			 NUMERIC(24, 10) ,
		@intReturnCode		INT,
		@datBillDate		DATETIME,
		@chvBTypeID			VARCHAR(50),
		@chvETypeID			VARCHAR(50),
		@chvDTypeID			VARCHAR(50),
		@chvSTypeID			VARCHAR(50),
		@CID				BIGINT,
		@Ntotal				 NUMERIC(24, 10) ,
		@NumRate			 NUMERIC(24, 10),
		@vipBillStoredByStypeId INT--会员储值结算使用单据所选分支机构进行储值余额判断
	
	SELECT @vipBillStoredByStypeId=Value FROM Userconfig WHERE ConfigName='vipBillStoredByStypeId'
		
		
	SELECT
			@datBillDate=BillDate,
			@chvBTypeID=BTypeID,
			@chvETypeID=etypeid,
			@chvDTypeID=DTypeId,
			@chvSTypeID=Stypeid,
			@CID=CID,
			@NumRate=Rate
	FROM BillIndex
	WHERE BillNumberId=@nBillID AND @intBillType NOT  IN  (423,424,425,426)

	SELECT 
			@datBillDate=BillDate,
			@chvBTypeID=BTypeID,
			@chvETypeID=etypeid,
			@chvDTypeID=DTypeId,
			@chvSTypeID=Stypeid,
			@CID=CID,
			@NumRate=Rate
	FROM dbo.Coupon_BillIndex
	WHERE BillNumberId=@nBillID AND @intBillType   IN  (423,424,425,426)
	
	DECLARE
		@intVIPCardID		INT,
		@chrIfVipJF			char(1),					-- 卡类型是否积分标识
		@intVipGridJF		int,						-- 单据GRID每行商品的积分
		@intVipJF			int,						-- 单据总积分
		@chvVipIsCz			varchar(1),					-- 是否VIP会员储值
		--@numVipTotalMoney	 NUMERIC(24, 10) ,				-- 单据消费金额 = 单据金额
		@numVipCzTotalInMoney  NUMERIC(24, 10) ,			-- 单据VIP会员储值对应的实收/付金额
		@numVipcZyeMoney	 NUMERIC(24, 10) ,				-- VIP会员储值余额
		@StypeVipcZyeMoney	 NUMERIC(24, 10) ,				-- VIP会员分支机构储值余额
		@Couponcode			VARCHAR(max),					--优惠券编码
		@yhtype				INT	,							--优惠券类型
		@VipTotal			NUMERIC(24, 10) 	
	DECLARE Account_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	ATypeID,Total,NTotalMoney,VipCardID,CouponCode,yhType,VipTotal
	FROM	BillMulAccount
	WHERE	BillNumberID = @nBillID AND billtype=@intBillType
	ORDER BY ID

	OPEN Account_CURSOR
	FETCH NEXT FROM Account_CURSOR INTO	@chvATypeID,@numTotal,@ntotal,@intVipCardID,@Couponcode,@yhtype,@VipTotal
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--写入ListTable
		--要区分ATypeID和单据类型
		IF @intBillType IN (11,12,305,160,141,167,168,178,196,179,182,195,213,167,168,172,181,312,424,93,78,84,85,213,212,214) AND @chvATypeID IN (@PreGathering_ID,@VIPSaving_ID,@YhSaving_ID) 
		BEGIN
			--只有为预收，会员储值时为负
			SELECT @numTotal=-@numTotal,@Ntotal = -@Ntotal
			--SELECT @chvATypeID, @numTotal 
		END
		ELSE IF @intBillType IN (84,85,78,213,212,214) AND @chvATypeID =@PrePay_ID
		BEGIN 
			SELECT @numTotal=-@numTotal,@Ntotal = -@Ntotal
		END 
		ELSE IF @intBillType IN (6,157)
		BEGIN
			--金额始终不变
			SELECT @numTotal=@numTotal,@Ntotal = @Ntotal
		END
		ELSE IF @intBillType IN (45,46,148,149,215,426) AND @chvATypeID NOT IN (@PreGathering_ID,@VIPSaving_ID,@YhSaving_ID)
		BEGIN
			SELECT @numTotal=-@numTotal,@Ntotal = -@Ntotal
		END
		ELSE IF @intBillType IN (34,145,161,170,212,36,158,77,414,423,84)  --增加费用单,现金费用单
		BEGIN
			--始终金额为负
			SELECT @numTotal=-@numTotal,@Ntotal = -@Ntotal
		END
		
		--具体扣减余额
		IF @chvATypeID = @VIPSaving_ID
		BEGIN
			SELECT	
					@chvVipIsCz = a.IsCz,
					@numVipcZyeMoney = a.cZyeMoney,
					@StypeVipcZyeMoney = ISNULL(ss.cZyeMoney,0)
			FROM	nVipCardSign a
			INNER JOIN nVipCardSet b ON a.VipCardTypeID = b.VipCardTypeID AND a.VipCardID = @intVIPCardID AND a.Deleted = 0 AND B.deleted=0 AND a.EndDate >= @datBillDate
			LEFT JOIN nVipCardSignStype ss ON SS.VipCardID=A.VipCardID AND ss.StypeId=@StypeID
					
			-- 1)无此VIP卡 2)过了有效期 3)VIP卡是未启用状态 4)VIP卡类型不存在或已删除
			IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			BEGIN
				CLOSE Account_CURSOR
				DEALLOCATE Account_CURSOR
				RETURN 701
			END
			
			IF @chvVipIsCz <> '1' 
			BEGIN
				CLOSE Account_CURSOR
				DEALLOCATE Account_CURSOR
				RETURN 702
			END
			
			IF @numTotal > 0 AND @intBillType NOT IN (45,46,215)  
			BEGIN
				CLOSE Account_CURSOR
				DEALLOCATE Account_CURSOR
				RETURN 703
			END
			
			IF @intBillType IN (11,12,305,6,167,168,172) AND abs(@numTotal) > @numVipcZyeMoney AND @NewPosBill=0 
			BEGIN
				CLOSE Account_CURSOR
				DEALLOCATE Account_CURSOR
				RETURN 704
			END
			
			IF @vipBillStoredByStypeId=1 AND @intBillType IN (305,11,12,167,168,172,4) AND abs(@numTotal) > @StypeVipcZyeMoney AND @NewPosBill=0 
			BEGIN
				CLOSE Account_CURSOR
				DEALLOCATE Account_CURSOR
				RETURN 707
			END
			
			IF (@NewPosBill=0 OR @chvATypeID<>@VIPSaving_ID)
			BEGIN
			
				UPDATE	nVipCardSign  
				SET 
					cZyeMoney = cZyeMoney + @numTotal
				WHERE VipCardID = @intVipCardID
				
				IF EXISTS(SELECT TOP 1 1 FROM nVipCardSignStype WHERE VipCardID=@intVipCardID AND StypeId=@STypeID)
				BEGIN
					UPDATE dbo.nVipCardSignStype
					SET 
						cZyeMoney=cZyeMoney+@numTotal,
						lJxFczMoney=lJxFczMoney-@numTotal,
						bNxFczMoney=bNxFczMoney-@numTotal
					WHERE VipCardID=@intVIPCardID AND StypeId=@STypeID
				END
				ELSE
				BEGIN
					INSERT INTO dbo.nVipCardSignStype
					        ( VipCardID ,
					          StypeId ,
					          qCczMoney ,
					          lJczMoney ,
					          lJxFczMoney ,
					          bNczMoney ,
					          bNxFczMoney ,
					          cZyeMoney ,
					          lJxFMoney ,
					          bNxFMoney
					        )
					VALUES  ( @intVipCardID , -- VipCardID - int
					          @STypeID , -- StypeId - varchar(50)
					          0 , -- qCczMoney - numeric
					          0 , -- lJczMoney - numeric
					          -1*@numTotal , -- lJxFczMoney - numeric
					          0 , -- bNczMoney - numeric
					          -1*@numTotal , -- bNxFczMoney - numeric
					          @numTotal , -- cZyeMoney - numeric
					          0 , -- lJxFMoney - numeric
					          0  -- bNxFMoney - numeric
					        )
				END
			END
			 
			IF @numTotal<>0
			BEGIN
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
					@numTotal,'',NULL,@chvDTypeID,@chvSTypeID,@syscid,@numTotal,1
			END
		END
		ELSE IF @chvATypeID = @YhSaving_ID
		BEGIN
			DECLARE @ceYhtotal NUMERIC(24, 10) ,@YhMztotal NUMERIC(24, 10)
		
			SELECT  @YhMztotal= CASE WHEN @intBillType IN (215,45,46) THEN @viptotal ELSE @viptotal*-1 END ,
					@ceYhtotal=-1*CASE WHEN ISNULL(ABS(@viptotal),0)>ABS(@numTotal) THEN SUM (ISNULL(ABS(@viptotal),0))-  ABS(@numTotal) 
									ELSE 0 
									END 
									
			SET  @ceYhtotal=CASE WHEN @intBillType IN (215,45,46) THEN @ceYhtotal*-1 ELSE @ceYhtotal END 
		
			IF @yhtype=1 ---出库 --代金券
			BEGIN
				--优惠券面值>结算金额值 差额写进项目 @DJSaving_ID
				IF @ceYhtotal<>0
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@DJSaving_ID,@chvBTypeID,@chvETypeID,
					@ceYhtotal,'',NULL,@chvDTypeID,@chvSTypeID,@CID,@ceYhtotal,@NumRate
			END 
			IF @YhMztotal<>0
			BEGIN
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
					@YhMztotal,'',NULL,@chvDTypeID,@chvSTypeID,@CID,@Ntotal,@NumRate
			END
		
		END 
		ELSE
		BEGIN
			IF @numTotal<>0
			BEGIN
				EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@datBillDate,@intBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
					@numTotal,'',NULL,@chvDTypeID,@chvSTypeID,@CID,@Ntotal,@NumRate
			END
		END
		
		
		FETCH NEXT FROM Account_CURSOR INTO	@chvATypeID,@numTotal,@ntotal,@intVipCardID,@Couponcode,@yhtype,@VipTotal
	END
	CLOSE Account_CURSOR
	DEALLOCATE Account_CURSOR


GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	提成单过账
	作    者：	冯波
	修改时间：	2014-06-23
*/
CREATE             PROCEDURE Gp_Auditing_Profit
(
	@nBillID				NUMERIC(10,0),					-- 单据 ID 号
	@szCheckMan				VARCHAR(50),					-- 制单人 ID 值
	@chvOpID				VARCHAR(50) = '',				-- 当前操作员 ID 值
	@billtype				INT = 0,						-- 单据类型
	@voucherMsg				VARCHAR(50)	= '' OUTPUT			--返回凭证生成的信息
)
--@encode$--
AS
	SET NOCOUNT ON
	
	--处理部分校验
	DECLARE	@nRet	INT
	
	SELECT @nRet=0
	
	
	
	UPDATE CommissionBillNew
	SET draft=0,ifcheck='t',Poster=@chvOpID,PostTime=GETDATE(),FPoster=NULL,FPostTime=NULL
	WHERE BillNumberId=@nBillID
	
	/*	
	 借：044599-业务提成
         贷：221199-员工提成
	*/
	DECLARE
		@intSaleCommission	INT,
		@intBonus			INT
		
	SELECT
		@intSaleCommission=NID
	FROM Ac_Items
	WHERE UserCode='044599'		
	
	SELECT
		@intBonus=NID
	FROM Ac_Items
	WHERE UserCode='221199'
	
	
	
	
	
	DECLARE
		@tBillDate			DATETIME,
		@szETypeID			VARCHAR(50),
		@dTotal				 NUMERIC(24, 10) ,
		@NdTotal			 NUMERIC(24, 10) ,
		@intCID				INT,
		@szSTypeID			VARCHAR(50),
		@szDTypeID			VARCHAR(50),
		@decRate			 NUMERIC(24, 10) ,
		@intReturnCode		INT,
		@strErrMsg			VARCHAR(1000)
		
	--提成单只有本币
		
	SELECT
		@szETypeID='',
		@szDTypeID='',
		@intCID=1,
		@decRate=1
		
	SELECT @tBillDate=BillDate,@dTotal=CommissionTotal,@szSTypeID=StypeID--,@szDTypeID=DTypeID
	FROM CommissionBillNew
	WHERE BillNumberId=@nBillID
		
	--业务提成
	INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
        Total,NTotal,CID,STypeID,DTypeID,Rate,Audited)
   VALUES(@nBillId,@tBillDate,@BillType,@intSaleCommission,'0','0',@szEtypeid,'',@dTotal,@dTotal,@intCID,@szSTypeID,@szDTypeId,@DecRate,1)
   
   --计算总额
   SELECT @intReturnCode=0
   
   EXEC @intReturnCode = GP_AType_Total_AddEdit @intSaleCommission,@szSTypeID,@intCID,@dTotal,@dTotal,@strErrMsg OUTPUT 
   
   IF @intReturnCode<>0 RETURN @intReturnCode
   
   --职员提成,暂时写一个总的,具体找需求确认
   INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
        Total,NTotal,CID,STypeID,DTypeID,Rate,Audited)
   VALUES(@nBillId,@tBillDate,@BillType,@intBonus,'0','0',@szEtypeid,'',@dTotal,@dTotal,@intCID,@szSTypeID,@szDTypeId,@DecRate,1)
   
	--计算总额
	SELECT @intReturnCode=0
	
	EXEC @intReturnCode = GP_AType_Total_AddEdit @intBonus,@szSTypeID,@intCID,@dTotal,@dTotal,@strErrMsg OUTPUT 
	
	IF @intReturnCode<>0 RETURN @intReturnCode
	  
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
		AND	EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'postingparameter' AND SubValue = 0)--即时过账，即时生成凭证
		AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'aloneusebsys' AND SubValue = 0)--使用总账系统
		AND @BillType<>203--排除序列号调整单
	BEGIN
		DECLARE @atid INT
		SET @atid = 0
		SELECT @atid = atid FROM dbo.CommissionBillNew WHERE BillNumberId = @nBillID
		EXEC @nRet = dbo.Gp_AutoCreate_Voucher @nBillID,@chvOpID,@atid,'',@voucherMsg OUTPUT,311
		IF @nRet <> 0 RETURN @nRet
	END
	ELSE
		SET @voucherMsg = ''
		
		
	
	

	RETURN @nRet
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*



DECLARE
	@nBillID				NUMERIC(10,0),				-- 单据 ID 号
	@szCheckMan				VARCHAR(50),				-- 制单人 ID 值
	@szPID					VARCHAR(1000),				-- 返回出错商品 ID 值
	@chvOpID				VARCHAR(50) = '',			-- 当前操作员 ID 值
	@KTypeID				VARCHAR(50) = '' ,			-- 返回仓库ID值，针对多仓库应用
	@billtype				INT = 0,
	@nRet					INT,
	@voucherMsg				VARCHAR(50)	= '',			--返回凭证生成的信息
	@VipCentInfo			VARCHAR(200) = '' ,			--返回会员卡积分调整信息
	@AssetMsg				VARCHAR(MAX)='' 		

SELECT
	@nBillID=1,
	@szCheckMan='00001',
	@chvOpID='00001',
	@billtype=311
	
BEGIN TRAN

EXEC
	@nRet=
	Gp_Auditing_Profit
	@nBillID,
	@szCheckMan,
	@chvOpID,
	@billtype,
	@voucherMsg OUT
	

SELECT DISTINCT B.FULLNAME,* FROM 
(
	SELECT * FROM LISTTABLE
	WHERE BILLTYPE=311
) A
INNER JOIN AC_ITEMS B
ON A.ATYPEID=B.NID
WHERE BILLNUMBERID=@NBILLID



ROLLBACK TRAN



*/

/*


DECLARE
	@nRet	INT
	

	
EXEC @nRet=Gp_Auditing_ProfitCheckBillData 23,'0'

SELECT @nRet

SELECT AssetBusinessTypeId,BILLTYPE,BILLNUMBERID,BILLCODE,NewPosBill,TOTALINMONEY,NTOTALINMONEY,TOTALMONEY,NTOTALMONEY
FROM BILLINDEX 
WHERE BILLCODE='RB-MRFZJG-T-2013-08-30-0003'
--WHERE BILLNUMBERID=18

SELECT * FROM BillMulAccount
WHERE BILLNUMBERID=8


SELECT TOTALMONEY,NTOTALMONEY,TOTALINMONEY,NTOTALINMONEY,PREFERENCEMONEY,NPREFERENCEMONEY,* FROM BILLINDEX WHERE BILLNUMBERID=8

SELECT TOTAL,* FROM RETAILBACKBILL WHERE BILLNUMBERID=8


*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	职员提成反过账
	作    者：	冯波
	修改时间：	2014-05-28
*/
CREATE             PROCEDURE Gp_Auditing_Profit_Undo
(
	@nBillID				NUMERIC(10,0),					-- 单据 ID 号
	@szCheckMan				VARCHAR(50),					-- 制单人 ID 值
	@chvOpID				VARCHAR(50) = '',				-- 当前操作员 ID 值
	@billtype				INT = 0,						-- 单据类型
	@ErrMsg					VARCHAR(50)	= '' OUTPUT			--返回凭证生成的信息
)
--@encode$--
AS
	SET NOCOUNT ON
	
	--处理部分校验
	DECLARE	@nRet	INT
	
	SELECT @nRet=0
	
	
	IF NOT EXISTS(SELECT BillNumberID FROM CommissionBillNew WHERE BillNumberId=@nBillID AND ifcheck='t')
	BEGIN
		SET @ErrMsg='该单据未过账或不存在，不能反过账！'
		RETURN -100
	END
	
	IF EXISTS(
		SELECT GoodsBillId
		FROM Ac_CommissionBill_VoucherBill
		WHERE GoodsBillId=@nBillID
		AND ISNULL(VourchBillId,0) >0
	)
	BEGIN
		SET @ErrMsg='此单据存在会计凭证,不能反过账'
		RETURN -110
	END
	

	
	--------------------得到本期开始时间 start---------------
	DECLARE
		@szPeriod1	DATETIME
	
	
	
	SELECT @szPeriod1=b.FBegin FROM Te_Period a
	INNER JOIN Ac_Period b
	ON a.FYear=b.FYear
	AND a.FPeriod=b.PeriodId
	WHERE a.STypeId=
	(SELECT VerifyID  FROM dbo.CommissionBillNew b INNER JOIN dbo.SType s ON b.Stypeid=s.TypeId WHERE BillNumberId=@nbillid)
	AND a.FYear=(SELECT YEAR(BILLDATE) FROM CommissionBillNew WHERE BillNumberId=@nBillID)
	

	
	
	
	--------------------得到本期开始时间 end---------------

	
	IF GETDATE() < @szPeriod1 RETURN -8

	
	EXEC @nRet=Gp_DestroyVoucher
		@nBillID,
		@ErrMsg OUTPUT,	-- 返回出错信息
		1

	IF @nRet<>0 RETURN @nRet
	
	SELECT @nRet=0
	
	
	--回冲业务凭证
	
	--处理会计凭证项目余额
	MERGE INTO dbo.AType_Total a
	USING(	SELECT AtypeId,STypeID,SUM(Total)AS total,SUM(Ntotal) AS ntotal,CID 
			FROM dbo.ListTable 
			WHERE BillNumberId=@nBillID AND BillType=311
			GROUP BY AtypeId,STypeID,CID
		)s
	ON a.ATypeID=s.AtypeId AND a.STypeID=s.STypeID AND a.CID=s.CID
	WHEN MATCHED THEN UPDATE SET a.Total-=s.Total,ntotal-=s.NTotal
	WHEN NOT MATCHED THEN INSERT(ATypeID,STypeID,Total,Ntotal,CID)VALUES(s.Atypeid,s.Stypeid,s.Total,s.Ntotal,s.cid)  ;
		
	DELETE ListTable
	WHERE BillNumberId=@nBillID AND BillType=311
	
	--给原来单据打上标志
	UPDATE CommissionBillNew SET draft=1,ifcheck='f',FPoster=@chvOpID,FPostTime=GETDATE(),PostTime=NULL,Poster=NULL
	 WHERE BillNumberId=@nBillID
	

	RETURN @nRet
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*



DECLARE
	@nBillID				NUMERIC(10,0),				-- 单据 ID 号
	@szCheckMan				VARCHAR(50),				-- 制单人 ID 值
	@szPID					VARCHAR(1000),				-- 返回出错商品 ID 值
	@chvOpID				VARCHAR(50) = '',			-- 当前操作员 ID 值
	@KTypeID				VARCHAR(50) = '' ,			-- 返回仓库ID值，针对多仓库应用
	@billtype				INT = 0,
	@nRet					INT,
	@voucherMsg				VARCHAR(50)	= '',			--返回凭证生成的信息
	@VipCentInfo			VARCHAR(200) = '' ,			--返回会员卡积分调整信息
	@AssetMsg				VARCHAR(MAX)='' 		

SELECT
	@nBillID=2,
	@szCheckMan='00001',
	@chvOpID='00001',
	@billtype=912
	

BEGIN TRAN

EXEC
	@nRet=
	Gp_Auditing_Profit_Undo
	@nBillID,
	@szCheckMan,
	@chvOpID,
	@billtype,
	@AssetMsg	OUT

SELECT B.FULLNAME,* FROM LISTTABLE A
INNER JOIN AC_ITEMS B
ON A.ATYPEID=B.NID
WHERE BILLNUMBERID=@NBILLID

ROLLBACK TRAN



*/

/*


DECLARE
	@nRet	INT
	

	
EXEC @nRet=Gp_Auditing_Profit_UndoCheckBillData 23,'0'

SELECT @nRet

SELECT AssetBusinessTypeId,BILLTYPE,BILLNUMBERID,BILLCODE,NewPosBill,TOTALINMONEY,NTOTALINMONEY,TOTALMONEY,NTOTALMONEY
FROM BILLINDEX 
WHERE BILLCODE='RB-MRFZJG-T-2013-08-30-0003'
--WHERE BILLNUMBERID=18

SELECT * FROM BillMulAccount
WHERE BILLNUMBERID=8


SELECT TOTALMONEY,NTOTALMONEY,TOTALINMONEY,NTOTALINMONEY,PREFERENCEMONEY,NPREFERENCEMONEY,* FROM BILLINDEX WHERE BILLNUMBERID=8

SELECT TOTAL,* FROM RETAILBACKBILL WHERE BILLNUMBERID=8


*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理只核算数量的货位,批号,自由项等
	返回结果：
	作    者：冯波
	创建时间：2012-04-18
	修改历史：
	
	
	
	还要处理维修类单据（需要区分是否从维修库出库）
	还需要处理代销类单据（需要处理代销库）
	还需要处理借欠
	
	成本调价单不用处理
	
	修改:冯波  2015-05-21
	
*/
CREATE          PROCEDURE GP_Auditing_QTY
(
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT  --1表示库存不足
)
--@encode$--
AS


	
	/*
		45	销售退货单
		160	销售换货单
		142	委托代销退货单
		34	采购入库单
		161	采购换货单
		14	报溢单
		16	生产拆装单
		126	获赠单
		17	同价调拨单	
		21	变价调拨单
		144	受托代销收货单
		215 零售退货

		
		多仓库的 45,142,34,144
		单仓库的14,126，305,215
		
		17,21 单仓库入库部分
		160,161,16,  多仓库入库部分
		
		187是分支机构调拨出库
		188是分支机构调拨入库
		197 领料退回单
		201 其他入库单

	*/
	
	--要先进行数据的校验,看能否处理
	SELECT 
		@strInfo='',
		@intCanDeal=0
		


	DECLARE
		@DBName		VARCHAR(100)

	SELECT @DBName=DBO.F_BillTableName(@intBillType)

	DECLARE
		@strSql						NVARCHAR(MAX),
		@strTempSql					NVARCHAR(MAX),
		@strCheck					NVARCHAR(MAX),
		@AVERAGE					VARCHAR(50),
		@FIFO						VARCHAR(50),
		@LIFO						VARCHAR(50),
		@HAND						VARCHAR(50),
		@nCostingMethod				VARCHAR(50),
		@nAllowNegativeStock		TINYINT,  --0表示不允许,1表示允许
		@strTempAdpriceSQL			NVARCHAR(MAX)
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	-- 查询是否允许负库存 (适用于移动加权平均成本核算)
	EXEC GP_GetSubValue 'AllowNegativeStock', '',@nAllowNegativeStock output
		
			
	SELECT
		@AVERAGE	= '0',		-- 移动加权平均算法
		@FIFO		= '1',		-- 先进先出
		@LIFO		= '2',		-- 后进先出
		@HAND		= '3'			-- 手工指定法

	IF @intBillType=57
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
			
			
			SELECT @strTempAdpriceSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
			
			SELECT @strTempAdpriceSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
	END
	ELSE IF @intBillType IN (17,21)		
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.OutCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID2 AS KTypeID,a.InCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN CASE '+CAST(@intBillType AS VARCHAR(100))+' WHEN 17 THEN a.GoodsCostPrice ELSE a.Price END ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.OutCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID2 AS KTypeID,a.InCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN CASE '+CAST(@intBillType AS VARCHAR(100))+' WHEN 17 THEN a.GoodsCostPrice ELSE a.Price END  ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
	END
	ELSE
	BEGIN
		SELECT 	@strTempSql='	
		WITH TempResult AS
		(
			SELECT a.PtypeId,'

		IF @intBillType IN (166,168,172,173,9,14,305,215)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID,'
		END
		ELSE IF @intBillType IN (174)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID2 AS KTypeID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.KTypeID2 AS KTypeID,'
		END
		ELSE IF @intBillType IN(327)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.KTypeIDOut,'
		END
		ELSE BEGIN
			IF @intBillType IN(328,329)
			BEGIN
				SELECT @strTempSql=@strTempSql+'a.InKTypeID,'
			END
		ELSE		
			SELECT @strTempSql=@strTempSql+'a.KTypeID,'
		END
		
		IF @intBillType IN (187)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.OutCargoID AS CargoID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.InCargoID AS CargoID,'
		END
		ELSE IF @intBillType IN (327)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.CargoIDout,'
		END
		ELSE
		BEGIN
			IF @intBillType IN(328,329)
			BEGIN
				SELECT @strTempSql=@strTempSql+'a.InCargoID,'
			END
		ELSE
			SELECT @strTempSql=@strTempSql+'a.CargoID,'
		END
		
		IF @intBillType IN(328,329)
		BEGIN
				SELECT @strTempSql=@strTempSql+'a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,'
		END
		ELSE
			SELECT @strTempSql=@strTempSql+'a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,'
			
		IF @intRedWord=0
		BEGIN
			IF @intBillType IN (34,45,46,126,144,142,188,201,174,14,215,400,403,328,329)
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (11,12,6,139,146,140,187,202,173,168,9,305,183,401,402,327)
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(-a.Qty) AS Qty,SUM(-a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (161,160,16,166,172)
			BEGIN
				--161,采购换货单
				--160,销售换货单
				SELECT @strTempSql=@strTempSql+'SUM(CASE a.InOrOUT WHEN ''I'' THEN a.Qty ELSE -a.QTY END) AS Qty,SUM(CASE a.InOrOUT WHEN ''I'' THEN a.NQty ELSE -a.NQTY END) AS NQty '
			END
		END
		ELSE
		BEGIN
			--红冲时
			IF @intBillType IN (34,45,46,126,144,142,188,201,174,14,215,400,403,328,329)
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(-a.Qty) AS Qty,SUM(-a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (11,12,6,139,146,140,187,202,173,168,9,305,183,401,402,327)
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (161,160,16,166,172)
			BEGIN
				--161,采购换货单
				--160,销售换货单
				SELECT @strTempSql=@strTempSql+'SUM(CASE a.InOrOUT WHEN ''I'' THEN -a.Qty ELSE a.QTY END) AS Qty,SUM(CASE a.InOrOUT WHEN ''I'' THEN -a.NQty ELSE a.NQTY END) AS NQty '
			END
		END
		
		IF @nCostingMethod=@HAND
		BEGIN
			IF @intBillType IN (305,11,12,139,140,6,146,17,21,187,202,9,173,183,168,401,402)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.GoodsCostPrice '
			END
			ELSE IF @intBillType IN (34,400)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.DiscountPrice AS GoodsCostPrice '
			END
			ELSE IF @intBillType=144
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE b.CostSale WHEN 0 THEN a.DiscountPrice ELSE DBO.FN_GetCommissionCostPrice(a.ID,a.BillNumberID) END AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (188,174, 201)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.Price AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (160) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (161) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.DiscountPrice ELSE CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  END AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (16)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.CostPrice ELSE a.GoodsCostPrice END AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (166,172)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN 0 ELSE a.GoodsCostPrice END AS GoodsCostPrice '
			END
			ELSE
			BEGIN
				SELECT @strTempSql=@strTempSql+',DBO.F_GetDetailCostPrice(a.BillNumberID,a.ID) AS GoodsCostPrice '
			END
		END
		ELSE
		BEGIN
			SELECT @strTempSql=@strTempSql+',0 AS GoodsCostPrice '
		END
			
		SELECT @strTempSql=@strTempSql+'
			FROM '+@DBName+' a	
			INNER JOIN PType p
			ON a.PTypeID=p.TypeID
			'
			
		IF @intBillType IN (166,168,172,173,174,9,14,305,215,144)
		BEGIN
			SELECT @strTempSql=@strTempSql+'
			INNER JOIN BillIndex b
			ON a.BillNumberID=b.BillNumberID
			'
		END	
			
		SELECT @strTempSql=@strTempSql+'WHERE a.BillNumberId='+CAST(@intBillNumberID AS VARCHAR(100))+'	AND p.IsService=0	'
		
		IF @intBillType IN (166,168,172)
		BEGIN
			SELECT @strTempSql=@strTempSql+' AND wxProperty=0 '
		END
		
		SELECT @strTempSql=@strTempSql+'	GROUP BY a.PtypeId,'
			
			
		IF @intBillType IN (166,168,172,173,9,14,305,215)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID,'
		END
		ELSE IF @intBillType IN (174)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID2,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.KTypeID2,'
		END
		ELSE IF @intBillType IN(327)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.KTypeIDOut,'
		END
		ELSE
		BEGIN	
			IF @intBillType IN(328,329)
			BEGIN
				SELECT @strTempSql=@strTempSql+'a.InKTypeID,'
			END
			ELSE
				SELECT @strTempSql=@strTempSql+'a.KTypeID,'
		END
		
		IF @intBillType IN (187)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.OutCargoID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.InCargoID,'
		END
		ELSE IF @intBillType IN (327)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.CargoIDOut,'
		END
		ELSE
		BEGIN
			IF @intBillType IN(328,329)
			BEGIN
				SELECT @strTempSql=@strTempSql+'a.InCargoID,'
			END
			ELSE
				SELECT @strTempSql=@strTempSql+'a.CargoID,'
		END
		
		SELECT @strTempSql=@strTempSql+'a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
		'
		
		IF @nCostingMethod=@HAND
		BEGIN
			IF @intBillType IN (305,11,12,139,140,6,146,17,21,187,202,9,173,183,168,401,402)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.GoodsCostPrice '
			END
			ELSE IF @intBillType IN (34,400)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.DiscountPrice  '
			END
			ELSE IF @intBillType=144
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE b.CostSale WHEN 0 THEN a.DiscountPrice ELSE DBO.FN_GetCommissionCostPrice(a.ID,a.BillNumberID) END '
			END
			ELSE IF @intBillType IN (188,174, 201)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.Price '
			END
			ELSE IF @intBillType IN (160) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  '
			END
			ELSE IF @intBillType IN (161) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.DiscountPrice ELSE CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  END '
			END
			ELSE IF @intBillType IN (16)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.CostPrice ELSE a.GoodsCostPrice END '
			END
			ELSE IF @intBillType IN (166,172)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN 0 ELSE a.GoodsCostPrice END '
			END
			ELSE
			BEGIN
				SELECT @strTempSql=@strTempSql+',DBO.F_GetDetailCostPrice(a.BillNumberID,a.ID) '
			END
		END
		
		SELECT @strTempSql=@strTempSql+'
		)
		'
		
	END
	
	--PRINT(@strTempSql)
			
	--TempResult中的QTY按入库为正,出库为负来记录
	DECLARE
		@strTempPFullName	VARCHAR(MAX),
		@strTempKFullName	VARCHAR(MAX),
		@strTempCFullName	VARCHAR(MAX),
		@strTempIFullName	VARCHAR(MAX)
		
	SELECT
		@strTempPFullName='',
		@strTempKFullName='',
		@strTempCFullName='',
		@strTempIFullName=''
		
	
	--	SELECT @nAllowNegativeStock,@nCostingMethod,@intRedWord,@intBillType
	IF ( (@nCostingMethod<>@AVERAGE) OR (@nCostingMethod=@AVERAGE AND @nAllowNegativeStock=0) )
	AND ( 
		( @intRedWord=0 AND @intBillType IN (11,12,6,139,146,140,187,202,173,168,305,9,183,401,402,327) ) OR ( @intRedWord<>0 AND @intBillType IN (34,45,46,126,144,142,188,201,174,14,215,400,403) ) 
		OR (@intBillType IN (161,160,16,17,21,166,168,172))
	)
	BEGIN		
	IF(@intBillType=327)
	BEGIN
		SELECT @strCheck=@strTempSql+'
		
		SELECT @intCanDeal=COUNT(*)
		FROM TempResult a
		LEFT JOIN GoodsStocks_Qty b
		ON a.PTypeID = b.PTypeID
		AND a.KTypeIDOut=b.KTypeID
		AND a.CargoIDout=b.CargoID
		AND a.ItemID=b.ItemID
		AND a.Iscombined=b.Iscombined
		AND a.GoodsNumber=b.GoodsNumber
		AND a.ProduceDate=b.ProduceDate
		AND a.ValidDate=b.ValidDate
		AND a.GoodsCostPrice=b.GoodsCostPrice
		INNER JOIN PType p
		ON a.PTypeID=p.TypeID
		
		'
		END
		ELSE
		BEGIN
		SELECT @strCheck=@strTempSql+'
		
		SELECT @intCanDeal=COUNT(*)
		FROM TempResult a
		LEFT JOIN GoodsStocks_Qty b
		ON a.PTypeID = b.PTypeID
		AND a.KTypeID=b.KTypeID
		AND a.CargoID=b.CargoID
		AND a.ItemID=b.ItemID
		AND a.Iscombined=b.Iscombined
		AND a.GoodsNumber=b.GoodsNumber
		AND a.ProduceDate=b.ProduceDate
		AND a.ValidDate=b.ValidDate
		AND a.GoodsCostPrice=b.GoodsCostPrice
		INNER JOIN PType p
		ON a.PTypeID=p.TypeID
		
		'
		END
			
		SELECT @strCheck=@strCheck+'WHERE p.IsService=0 AND (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) '

		
		PRINT(@strCheck)
	
		EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
		
		IF @intCanDeal<>0
		BEGIN
			SET @intCanDeal=-18
		IF(@intBillType=327)
	       BEGIN
			SELECT @strCheck=@strTempSql+'
			
			SELECT TOP 1
				@strTempPFullName=p.FullName,
				@strTempKFullName=k.FullName,
				@strTempCFullName=c.FullName,
				@strTempIFullName=i.itemname
			FROM TempResult a
			LEFT JOIN GoodsStocks_Qty b
			ON a.PTypeID = b.PTypeID
			AND a.KTypeIDOut=b.KTypeID
			AND a.CargoIDout=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
			ON a.PTypeID=p.typeId
			INNER JOIN Stock k
			ON a.KTypeIDOut=k.typeId
			INNER JOIN CargoType c
			ON a.CargoIDout=c.CargoID
			LEFT JOIN V_Item i
			ON a.ItemId=i.itemid
			
			'
			   END
			   ELSE
			   BEGIN
			   SELECT @strCheck=@strTempSql+'
			
			SELECT TOP 1
				@strTempPFullName=p.FullName,
				@strTempKFullName=k.FullName,
				@strTempCFullName=c.FullName,
				@strTempIFullName=i.itemname
			FROM TempResult a
			LEFT JOIN GoodsStocks_Qty b
			ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
			ON a.PTypeID=p.typeId
			INNER JOIN Stock k
			ON a.KTypeID=k.typeId
			INNER JOIN CargoType c
			ON a.CargoID=c.CargoID
			LEFT JOIN V_Item i
			ON a.ItemId=i.itemid
			
			'
			   END
			SELECT @strCheck=@strCheck+'WHERE  (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) AND p.IsService=0
			ORDER BY p.UserCode
			'

          
		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
			
			--PRINT(@strCheck)
		
		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
			
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
			
			SELECT @strInfo=@strInfo+'会造成相应';
			
			IF EXISTS(SELECT * FROM ptype WHERE IfUseGoodsNum = 1 AND FullName = @strTempPFullName)
			BEGIN
			         SELECT @strInfo = @strinfo + '批号/'
			END
			
			select @strinfo = @strinfo + '货位/自由项/浮动数量等产生负库存!';
			RETURN;
		END
		
	END
	ELSE IF ( (@nCostingMethod<>@AVERAGE) OR (@nCostingMethod=@AVERAGE AND @nAllowNegativeStock=0) ) AND @intBillType=57
	BEGIN
		IF  EXISTS(
			SELECT BillNumberID
			FROM AdPriceBill
			WHERE BillNumberId=@intBillNumberID
			AND ChangeAllStock=0
		)
		BEGIN
			SELECT @strCheck=@strTempAdpriceSQL+'
			
			SELECT @intCanDeal=COUNT(*)
			FROM TempResult a
			LEFT JOIN GoodsStocks_Qty b
			ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
			ON a.PTypeID=p.TypeID
			'
			
			SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
			AND a.Qty<0
			'

			
			--PRINT(@strCheck)
		
			EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
			
			IF @intCanDeal<>0
			BEGIN
				SET @intCanDeal=-18
				
				SELECT @strCheck=@strTempSql+'
			
			SELECT TOP 1
				@strTempPFullName=p.FullName,
				@strTempKFullName=k.FullName,
				@strTempCFullName=c.FullName,
				@strTempIFullName=i.itemname
			FROM TempResult a
			LEFT JOIN GoodsStocks_Qty b
			ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
			ON a.PTypeID=p.typeId
			INNER JOIN Stock k
			ON a.KTypeID=k.typeId
			INNER JOIN CargoType c
			ON a.CargoID=c.CargoID
			LEFT JOIN V_Item i
			ON a.ItemId=i.itemid
			'
			
			SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
			AND a.Qty<0
			'


		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
			
			--PRINT(@strCheck)
		
			IF @strTempKFullName=''
			BEGIN
				--如果所得到的结果为空，则可能可能是调价100%，需要重新查结果
				
				SELECT @strCheck=@strTempAdpriceSQL+'
			
				SELECT TOP 1
					@strTempPFullName=p.FullName,
					@strTempKFullName=k.FullName,
					@strTempCFullName=c.FullName,
					@strTempIFullName=i.itemname
				FROM TempResult a
				LEFT JOIN GoodsStocks_Qty b
				ON a.PTypeID = b.PTypeID
				AND a.KTypeID=b.KTypeID
				AND a.CargoID=b.CargoID
				AND a.ItemID=b.ItemID
				AND a.Iscombined=b.Iscombined
				AND a.GoodsNumber=b.GoodsNumber
				AND a.ProduceDate=b.ProduceDate
				AND a.ValidDate=b.ValidDate
				AND a.GoodsCostPrice=b.GoodsCostPrice
				INNER JOIN PType p
				ON a.PTypeID=p.typeId
				INNER JOIN Stock k
				ON a.KTypeID=k.typeId
				INNER JOIN CargoType c
				ON a.CargoID=c.CargoID
				LEFT JOIN V_Item i
				ON a.ItemId=i.itemid
				'
				
				SELECT @strCheck=@strCheck+'WHERE  (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
				AND a.Qty<0
				'


			
				EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
				
				--PRINT(@strCheck)
			END

		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
			
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
			
			SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项/浮动数量等产生负库存!'
				
			RETURN;	
			END
		END
	END		
	
	
	
	--InOrOut
	
	IF @intBillType IN(328,329)
	BEGIN
		--存在锁库数量大于库存总数量的商品给出提示
		SET @strCheck=@strTempSql+'
		SELECT @intCanDeal=COUNT(*) FROM TempResult a
								LEFT JOIN GoodsStocks_Qty b
									ON a.PTypeID = b.PTypeID
									AND a.InKTypeID=b.KTypeID
									AND a.InCargoID=b.CargoID
									AND a.ItemID=b.ItemID
									AND a.Iscombined=b.Iscombined
									AND a.GoodsNumber=b.GoodsNumber
									AND a.ProduceDate=b.ProduceDate
									AND a.ValidDate=b.ValidDate
									AND a.GoodsCostPrice=b.GoodsCostPrice
									INNER JOIN PType p
										ON a.PTypeID=p.typeId
							WHERE a.Qty+ISNULL(b.Qty,0)<b.LockNumber AND p.IsService=0 AND ISNULL(b.LockNumber,0)>0'
	END
	ELSE IF @intBillType IN(327)
	BEGIN
	SET @strCheck=@strTempSql+'
		SELECT @intCanDeal=COUNT(*) FROM TempResult a
								LEFT JOIN GoodsStocks_Qty b
									ON a.PTypeID = b.PTypeID
									AND a.KTypeIDout=b.KTypeID
									AND a.CargoIDout=b.CargoID
									AND a.ItemID=b.ItemID
									AND a.Iscombined=b.Iscombined
									AND a.GoodsNumber=b.GoodsNumber
									AND a.ProduceDate=b.ProduceDate
									AND a.ValidDate=b.ValidDate
									AND a.GoodsCostPrice=b.GoodsCostPrice
									INNER JOIN PType p
										ON a.PTypeID=p.typeId
							WHERE a.Qty+ISNULL(b.Qty,0)<b.LockNumber AND p.IsService=0 AND ISNULL(b.LockNumber,0)>0'
	END
	ELSE
	--存在锁库数量大于库存总数量的商品给出提示
	SET @strCheck=@strTempSql+'
	SELECT @intCanDeal=COUNT(*) FROM TempResult a
							LEFT JOIN GoodsStocks_Qty b
								ON a.PTypeID = b.PTypeID
								AND a.KTypeID=b.KTypeID
								AND a.CargoID=b.CargoID
								AND a.ItemID=b.ItemID
								AND a.Iscombined=b.Iscombined
								AND a.GoodsNumber=b.GoodsNumber
								AND a.ProduceDate=b.ProduceDate
								AND a.ValidDate=b.ValidDate
								AND a.GoodsCostPrice=b.GoodsCostPrice
								INNER JOIN PType p
									ON a.PTypeID=p.typeId
						WHERE a.Qty+ISNULL(b.Qty,0)<b.LockNumber AND p.IsService=0 AND ISNULL(b.LockNumber,0)>0'
						
	EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
	IF @intCanDeal<>0
	BEGIN
		SET @intCanDeal=-18
		SELECT @strCheck=@strTempSql+'
		SELECT TOP 1
					@strTempPFullName=p.FullName,
					@strTempKFullName=k.FullName,
					@strTempCFullName=c.FullName,
					@strTempIFullName=i.itemname
		FROM TempResult a
		LEFT JOIN GoodsStocks_Qty b
		ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
					ON a.PTypeID=p.typeId
			INNER JOIN Stock k
					ON a.KTypeID=k.typeId
			INNER JOIN CargoType c
					ON a.CargoID=c.CargoID
			LEFT JOIN V_Item i
					ON a.ItemId=i.itemid
		WHERE a.Qty+ISNULL(b.Qty,0)<b.LockNumber AND p.IsService=0 AND b.LockNumber>0'
		
		EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
		
		--需要判断货位,自由项,批号,生产日期,保质期是否启用
		SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
				
		IF ISNULL(@strTempIFullName,'')<>''
		BEGIN
			SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
		END
				
		SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项等锁库数量大于库存总数量!'
		RETURN;
	END			
	
	--换货,调拨还要单独处理
	IF @intCanDeal=0
	BEGIN
	
		IF @intBillType IN(328,329)
		BEGIN
			SELECT @strSql=@strTempSql+' 
			MERGE GoodsStocks_Qty AS target
			USING 
			(
				SELECT PtypeId,InKTypeID,InCargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice
				FROM TempResult
			) AS source (PtypeId,InKTypeID,InCargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
			ON 
			(
				target.PTypeID = source.PTypeID
				AND target.KTypeID=source.InKTypeID
				AND target.CargoID=source.InCargoID
				AND target.ItemID=source.ItemID
				AND target.Iscombined=source.Iscombined
				AND target.GoodsNumber=source.GoodsNumber
				AND target.ProduceDate=source.ProduceDate
				AND target.ValidDate=source.ValidDate
				AND target.GoodsCostPrice=source.GoodsCostPrice
			)
			WHEN MATCHED 
			THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.NQty = target.NQty + source.NQty
			WHEN NOT MATCHED BY TARGET  AND (source.Qty<>0 OR source.NQty<>0)
			THEN INSERT (PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice) 
			VALUES(source.PtypeId,source.InKTypeID,source.InCargoID,source.ItemID,source.Iscombined,
			source.GoodsNumber,source.ProduceDate,source.ValidDate,source.Qty,source.NQty,source.GoodsCostPrice);
			'
		END
		else IF @intBillType IN(327)
		BEGIN
			SELECT @strSql=@strTempSql+' 
			MERGE GoodsStocks_Qty AS target
			USING 
			(
				SELECT PtypeId,KTypeIDout,CargoIDout,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice
				FROM TempResult
			) AS source (PtypeId,KTypeIDout,CargoIDout,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
			ON 
			(
				target.PTypeID = source.PTypeID
				AND target.KTypeID=source.KTypeIDout
				AND target.CargoID=source.CargoIDout
				AND target.ItemID=source.ItemID
				AND target.Iscombined=source.Iscombined
				AND target.GoodsNumber=source.GoodsNumber
				AND target.ProduceDate=source.ProduceDate
				AND target.ValidDate=source.ValidDate
				AND target.GoodsCostPrice=source.GoodsCostPrice
			)
			WHEN MATCHED 
			THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.NQty = target.NQty +source.NQty
			WHEN NOT MATCHED BY TARGET  AND (source.Qty<>0 OR source.NQty<>0)
			THEN INSERT (PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice) 
			VALUES(source.PtypeId,source.KTypeIDout,source.CargoIDout,source.ItemID,source.Iscombined,
			source.GoodsNumber,source.ProduceDate,source.ValidDate,source.Qty,source.NQty,source.GoodsCostPrice);
			'
		END
		ELSE
			SELECT @strSql=@strTempSql+'
			
			MERGE GoodsStocks_Qty AS target
			USING 
			(
				SELECT PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice
				FROM TempResult
			) AS source (PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
			ON 
			(
				target.PTypeID = source.PTypeID
				AND target.KTypeID=source.KTypeID
				AND target.CargoID=source.CargoID
				AND target.ItemID=source.ItemID
				AND target.Iscombined=source.Iscombined
				AND target.GoodsNumber=source.GoodsNumber
				AND target.ProduceDate=source.ProduceDate
				AND target.ValidDate=source.ValidDate
				AND target.GoodsCostPrice=source.GoodsCostPrice
			)
			
			WHEN MATCHED 
			THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.NQty = target.NQty + source.NQty
			WHEN NOT MATCHED BY TARGET  AND (source.Qty<>0 OR source.NQty<>0)
			THEN INSERT (PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice) 
			VALUES(source.PtypeId,source.KTypeID,source.CargoID,source.ItemID,source.Iscombined,
			source.GoodsNumber,source.ProduceDate,source.ValidDate,source.Qty,source.NQty,source.GoodsCostPrice);
			'
		
		--PRINT (@strSql)
		--EXEC(@strSql)	
		EXEC  sp_executesql @strSql
		
			--InOrOut
	
	
		IF @intBillType IN(328,329)
		BEGIN
			--存在锁库数量大于库存总数量的商品给出提示
			SET @strCheck=@strTempSql+'
			SELECT @intCanDeal=COUNT(*) 
			FROM  GoodsStocks_Qty Q
			INNER JOIN TempResult T ON T.PTypeID = Q.PTypeID
										AND T.InKTypeID=Q.KTypeID
										AND T.InCargoID=Q.CargoID
										AND T.ItemID=Q.ItemID
										AND T.Iscombined=Q.Iscombined
										AND T.GoodsNumber=Q.GoodsNumber
										AND T.ProduceDate=Q.ProduceDate
										AND T.ValidDate=Q.ValidDate
										AND T.GoodsCostPrice=Q.GoodsCostPrice
		WHERE 
			ISNULL(Q.LockNumber,0)>0 
			AND ISNULL(Q.Qty,0)<ISNULL(Q.LockNumber,0)'
		END
		else IF @intBillType IN(327)
		BEGIN
			--存在锁库数量大于库存总数量的商品给出提示
			SET @strCheck=@strTempSql+'
			SELECT @intCanDeal=COUNT(*) 
			FROM  GoodsStocks_Qty Q
			INNER JOIN TempResult T ON T.PTypeID = Q.PTypeID
										AND T.KTypeIDout=Q.KTypeID
										AND T.CargoIDout=Q.CargoID
										AND T.ItemID=Q.ItemID
										AND T.Iscombined=Q.Iscombined
										AND T.GoodsNumber=Q.GoodsNumber
										AND T.ProduceDate=Q.ProduceDate
										AND T.ValidDate=Q.ValidDate
										AND T.GoodsCostPrice=Q.GoodsCostPrice
		WHERE 
			ISNULL(Q.LockNumber,0)>0 
			AND ISNULL(Q.Qty,0)<ISNULL(Q.LockNumber,0)'
		END
		ELSE
			--存在锁库数量大于库存总数量的商品给出提示
			SET @strCheck=@strTempSql+'
			SELECT @intCanDeal=COUNT(*) 
			FROM  GoodsStocks_Qty Q
			INNER JOIN TempResult T ON T.PTypeID = Q.PTypeID
										AND T.KTypeID=Q.KTypeID
										AND T.CargoID=Q.CargoID
										AND T.ItemID=Q.ItemID
										AND T.Iscombined=Q.Iscombined
										AND T.GoodsNumber=Q.GoodsNumber
										AND T.ProduceDate=Q.ProduceDate
										AND T.ValidDate=Q.ValidDate
										AND T.GoodsCostPrice=Q.GoodsCostPrice
		WHERE 
			ISNULL(Q.LockNumber,0)>0 
			AND ISNULL(Q.Qty,0)<ISNULL(Q.LockNumber,0)'
						
		EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
		IF @intCanDeal<>0
		BEGIN
			SET @intCanDeal=-18
			SELECT @strCheck=@strTempSql+'
			SELECT TOP 1
					@strTempPFullName=p.FullName,
					@strTempKFullName=k.FullName,
					@strTempCFullName=c.FullName,
					@strTempIFullName=i.itemname
			FROM GoodsStocks_Qty b
			INNER JOIN TempResult T ON T.PTypeID = B.PTypeID
									AND T.KTypeID=B.KTypeID
									AND T.CargoID=B.CargoID
									AND T.ItemID=B.ItemID
									AND T.Iscombined=B.Iscombined
									AND T.GoodsNumber=B.GoodsNumber
									AND T.ProduceDate=B.ProduceDate
									AND T.ValidDate=B.ValidDate
									AND T.GoodsCostPrice=B.GoodsCostPrice
			INNER JOIN PType p
					ON b.PTypeID=p.typeId
			INNER JOIN Stock k
					ON b.KTypeID=k.typeId
			INNER JOIN CargoType c
					ON b.CargoID=c.CargoID
			LEFT JOIN V_Item i
					ON b.ItemId=i.itemid
			WHERE b.LockNumber>0 AND ISNULL(b.Qty,0)<b.LockNumber AND p.IsService=0 '
		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
				
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
				
			SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项等锁库数量大于库存总数量!'
			RETURN;
		END	
	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=8,
	@intBillType=401,
	@intRedWord=0

BEGIN TRAN

 EXEC GP_Auditing_QTY
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN


SELECT * FROM BillIndex
WHERE BILLCODE='GT-SUB1-T-2015-06-01-0001'





*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：修改过账后单据,新单据处理只核算数量的货位,批号,自由项等,无论单据类型都要判断负库存
	返回结果：
	作    者：冯波
	创建时间：2015-11-30
	修改历史：
	
	
	
	还要处理维修类单据（需要区分是否从维修库出库）
	还需要处理代销类单据（需要处理代销库）
	还需要处理借欠
	
	成本调价单不用处理
	
	修改:冯波  2015-05-21
	
*/
CREATE          PROCEDURE GP_Auditing_QTY_NewBill
(
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT  --1表示库存不足
)
--@encode$--
AS


	
	/*
		45	销售退货单
		160	销售换货单
		142	委托代销退货单
		34	采购入库单
		161	采购换货单
		14	报溢单
		16	生产拆装单
		126	获赠单
		17	同价调拨单	
		21	变价调拨单
		144	受托代销收货单
		215 零售退货

		
		多仓库的 45,142,34,144
		单仓库的14,126，305,215
		
		17,21 单仓库入库部分
		160,161,16,  多仓库入库部分
		
		187是分支机构调拨出库
		188是分支机构调拨入库
		197 领料退回单
		201 其他入库单

	*/
	
	--要先进行数据的校验,看能否处理
	SELECT 
		@strInfo='',
		@intCanDeal=0
		


	DECLARE
		@DBName		VARCHAR(100)

	SELECT @DBName=DBO.F_BillTableName(@intBillType)

	DECLARE
		@strSql						NVARCHAR(MAX),
		@strTempSql					NVARCHAR(MAX),
		@strCheck					NVARCHAR(MAX),
		@AVERAGE					VARCHAR(50),
		@FIFO						VARCHAR(50),
		@LIFO						VARCHAR(50),
		@HAND						VARCHAR(50),
		@nCostingMethod				VARCHAR(50),
		@nAllowNegativeStock		TINYINT,  --0表示不允许,1表示允许
		@strTempAdpriceSQL			NVARCHAR(MAX)
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	-- 查询是否允许负库存 (适用于移动加权平均成本核算)
	EXEC GP_GetSubValue 'AllowNegativeStock', '',@nAllowNegativeStock output
		
			
	SELECT
		@AVERAGE	= '0',		-- 移动加权平均算法
		@FIFO		= '1',		-- 先进先出
		@LIFO		= '2',		-- 后进先出
		@HAND		= '3'			-- 手工指定法

	IF @intBillType=57
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
			
			
			SELECT @strTempAdpriceSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
			
			SELECT @strTempAdpriceSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
	END
	ELSE IF @intBillType IN (17,21)		
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.OutCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID2 AS KTypeID,a.InCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN CASE '+CAST(@intBillType AS VARCHAR(100))+' WHEN 17 THEN a.GoodsCostPrice ELSE a.Price END ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.OutCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID2 AS KTypeID,a.InCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN CASE '+CAST(@intBillType AS VARCHAR(100))+' WHEN 17 THEN a.GoodsCostPrice ELSE a.Price END  ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
	END
	ELSE
	BEGIN
		SELECT 	@strTempSql='	
		WITH TempResult AS
		(
			SELECT a.PtypeId,'

		IF @intBillType IN (166,168,172,173,9,14,305,215)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID,'
		END
		ELSE IF @intBillType IN (174)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID2 AS KTypeID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.KTypeID2 AS KTypeID,'
		END
		ELSE BEGIN		
			SELECT @strTempSql=@strTempSql+'a.KTypeID,'
		END
		
		IF @intBillType IN (187)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.OutCargoID AS CargoID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.InCargoID AS CargoID,'
		END
		ELSE
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.CargoID,'
		END
		
		SELECT @strTempSql=@strTempSql+'a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,'
			
		IF @intRedWord=0
		BEGIN
			IF @intBillType IN (34,45,126,144,142,188,201,174,14,215,400,403,46)--新增46 组合品销售换货单9.9.1
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (11,6,139,146,140,187,202,173,168,9,305,183,401,402,12)--新增12 组合品销售换货单9.9.1
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(-a.Qty) AS Qty,SUM(-a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (161,160,16,166,172)
			BEGIN
				--161,采购换货单
				--160,销售换货单
				SELECT @strTempSql=@strTempSql+'SUM(CASE a.InOrOUT WHEN ''I'' THEN a.Qty ELSE -a.QTY END) AS Qty,SUM(CASE a.InOrOUT WHEN ''I'' THEN a.NQty ELSE -a.NQTY END) AS NQty '
			END
		END
		ELSE
		BEGIN
			--红冲时
			IF @intBillType IN (34,45,126,144,142,188,201,174,14,215,400,403,46)--新增46 组合品销售换货单9.9.1
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(-a.Qty) AS Qty,SUM(-a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (11,6,139,146,140,187,202,173,168,9,305,183,401,402,12)--新增12 组合品销售换货单9.9.1
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (161,160,16,166,172)
			BEGIN
				--161,采购换货单
				--160,销售换货单
				SELECT @strTempSql=@strTempSql+'SUM(CASE a.InOrOUT WHEN ''I'' THEN -a.Qty ELSE a.QTY END) AS Qty,SUM(CASE a.InOrOUT WHEN ''I'' THEN -a.NQty ELSE a.NQTY END) AS NQty '
			END
		END
		
		IF @nCostingMethod=@HAND
		BEGIN
			IF @intBillType IN (305,11,139,140,6,146,17,21,187,202,9,173,183,168,401,402)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.GoodsCostPrice '
			END
			ELSE IF @intBillType IN (34,144,400)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.DiscountPrice AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (188,174, 201)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.Price AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (160) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (161) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.DiscountPrice ELSE CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  END AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (16)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.CostPrice ELSE a.GoodsCostPrice END AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (166,172)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN 0 ELSE a.GoodsCostPrice END AS GoodsCostPrice '
			END
			ELSE
			BEGIN
				SELECT @strTempSql=@strTempSql+',DBO.F_GetDetailCostPrice(a.BillNumberID,a.ID) AS GoodsCostPrice '
			END
		END
		ELSE
		BEGIN
			SELECT @strTempSql=@strTempSql+',0 AS GoodsCostPrice '
		END
			
		SELECT @strTempSql=@strTempSql+'
			FROM '+@DBName+' a	
			INNER JOIN PType p
			ON a.PTypeID=p.TypeID
			'
			
		IF @intBillType IN (166,168,172,173,174,9,14,305,215)
		BEGIN
			SELECT @strTempSql=@strTempSql+'
			INNER JOIN BillIndex b
			ON a.BillNumberID=b.BillNumberID
			'
		END	
			
		SELECT @strTempSql=@strTempSql+'WHERE a.BillNumberId='+CAST(@intBillNumberID AS VARCHAR(100))+'	AND p.IsService=0	'
		
		IF @intBillType IN (166,168,172)
		BEGIN
			SELECT @strTempSql=@strTempSql+' AND wxProperty=0 '
		END
		
		SELECT @strTempSql=@strTempSql+'	GROUP BY a.PtypeId,'
			
			
		IF @intBillType IN (166,168,172,173,9,14,305,215)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID,'
		END
		ELSE IF @intBillType IN (174)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID2,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.KTypeID2,'
		END
		ELSE
		BEGIN		
			SELECT @strTempSql=@strTempSql+'a.KTypeID,'
		END
		
		IF @intBillType IN (187)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.OutCargoID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.InCargoID,'
		END
		ELSE
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.CargoID,'
		END
		
		SELECT @strTempSql=@strTempSql+'a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
		'
		
		IF @nCostingMethod=@HAND
		BEGIN
			IF @intBillType IN (305,11,139,140,6,146,17,21,187,202,9,173,183,168,401,402)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.GoodsCostPrice '
			END
			ELSE IF @intBillType IN (34,144,400)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.DiscountPrice '
			END
			ELSE IF @intBillType IN (188,174, 201)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.Price '
			END
			ELSE IF @intBillType IN (160) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  '
			END
			ELSE IF @intBillType IN (161) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.DiscountPrice ELSE CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  END '
			END
			ELSE IF @intBillType IN (16)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.CostPrice ELSE a.GoodsCostPrice END '
			END
			ELSE IF @intBillType IN (166,172)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN 0 ELSE a.GoodsCostPrice END '
			END
			ELSE
			BEGIN
				SELECT @strTempSql=@strTempSql+',DBO.F_GetDetailCostPrice(a.BillNumberID,a.ID) '
			END
		END
		
		SELECT @strTempSql=@strTempSql+'
		)
		'
		
	END
	
		
	--TempResult中的QTY按入库为正,出库为负来记录
	DECLARE
		@strTempPFullName	VARCHAR(MAX),
		@strTempKFullName	VARCHAR(MAX),
		@strTempCFullName	VARCHAR(MAX),
		@strTempIFullName	VARCHAR(MAX)
		
	SELECT
		@strTempPFullName='',
		@strTempKFullName='',
		@strTempCFullName='',
		@strTempIFullName=''
		

		
	IF ( (@nCostingMethod<>@AVERAGE) OR (@nCostingMethod=@AVERAGE AND @nAllowNegativeStock=0) ) AND @intBillType<>57
	BEGIN		
		SELECT @strCheck=@strTempSql+'
		
		SELECT @intCanDeal=COUNT(*)
		FROM TempResult a
		LEFT JOIN GoodsStocks_Qty b
		ON a.PTypeID = b.PTypeID
		AND a.KTypeID=b.KTypeID
		AND a.CargoID=b.CargoID
		AND a.ItemID=b.ItemID
		AND a.Iscombined=b.Iscombined
		AND a.GoodsNumber=b.GoodsNumber
		AND a.ProduceDate=b.ProduceDate
		AND a.ValidDate=b.ValidDate
		AND a.GoodsCostPrice=b.GoodsCostPrice
		INNER JOIN PType p
		ON a.PTypeID=p.TypeID
		
		'
		
		SELECT @strCheck=@strCheck+'WHERE p.IsService=0 AND (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) '

		
		--PRINT(@strCheck)
	
		EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
		
		IF @intCanDeal<>0
		BEGIN
			SET @intCanDeal=-18
			
			SELECT @strCheck=@strTempSql+'
			
			SELECT TOP 1
				@strTempPFullName=p.FullName,
				@strTempKFullName=k.FullName,
				@strTempCFullName=c.FullName,
				@strTempIFullName=i.itemname
			FROM TempResult a
			LEFT JOIN GoodsStocks_Qty b
			ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
			ON a.PTypeID=p.typeId
			INNER JOIN Stock k
			ON a.KTypeID=k.typeId
			INNER JOIN CargoType c
			ON a.CargoID=c.CargoID
			LEFT JOIN V_Item i
			ON a.ItemId=i.itemid
			
			'
			
			SELECT @strCheck=@strCheck+'WHERE  (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) AND p.IsService=0
			ORDER BY p.UserCode
			'

		
			
		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
			
			--PRINT(@strCheck)
		
		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
			
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
			
			SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项/浮动数量等产生负库存!'
			RETURN;
		END
		
	END
	ELSE IF ( (@nCostingMethod<>@AVERAGE) OR (@nCostingMethod=@AVERAGE AND @nAllowNegativeStock=0) ) AND @intBillType=57
	BEGIN
		IF  EXISTS(
			SELECT BillNumberID
			FROM AdPriceBill
			WHERE BillNumberId=@intBillNumberID
			AND ChangeAllStock=0
		)
		BEGIN
			SELECT @strCheck=@strTempAdpriceSQL+'
			
			SELECT @intCanDeal=COUNT(*)
			FROM TempResult a
			LEFT JOIN GoodsStocks_Qty b
			ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
			ON a.PTypeID=p.TypeID
			'
			
			SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
			AND a.Qty<0
			'

			
			--PRINT(@strCheck)
		
			EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
			
			IF @intCanDeal<>0
			BEGIN
				SET @intCanDeal=-18
				
				SELECT @strCheck=@strTempSql+'
			
			SELECT TOP 1
				@strTempPFullName=p.FullName,
				@strTempKFullName=k.FullName,
				@strTempCFullName=c.FullName,
				@strTempIFullName=i.itemname
			FROM TempResult a
			LEFT JOIN GoodsStocks_Qty b
			ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
			ON a.PTypeID=p.typeId
			INNER JOIN Stock k
			ON a.KTypeID=k.typeId
			INNER JOIN CargoType c
			ON a.CargoID=c.CargoID
			LEFT JOIN V_Item i
			ON a.ItemId=i.itemid
			'
			
			SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
			AND a.Qty<0
			'


		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
			
			--PRINT(@strCheck)
		
			IF @strTempKFullName=''
			BEGIN
				--如果所得到的结果为空，则可能可能是调价100%，需要重新查结果
				
				SELECT @strCheck=@strTempAdpriceSQL+'
			
				SELECT TOP 1
					@strTempPFullName=p.FullName,
					@strTempKFullName=k.FullName,
					@strTempCFullName=c.FullName,
					@strTempIFullName=i.itemname
				FROM TempResult a
				LEFT JOIN GoodsStocks_Qty b
				ON a.PTypeID = b.PTypeID
				AND a.KTypeID=b.KTypeID
				AND a.CargoID=b.CargoID
				AND a.ItemID=b.ItemID
				AND a.Iscombined=b.Iscombined
				AND a.GoodsNumber=b.GoodsNumber
				AND a.ProduceDate=b.ProduceDate
				AND a.ValidDate=b.ValidDate
				AND a.GoodsCostPrice=b.GoodsCostPrice
				INNER JOIN PType p
				ON a.PTypeID=p.typeId
				INNER JOIN Stock k
				ON a.KTypeID=k.typeId
				INNER JOIN CargoType c
				ON a.CargoID=c.CargoID
				LEFT JOIN V_Item i
				ON a.ItemId=i.itemid
				'
				
				SELECT @strCheck=@strCheck+'WHERE  (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
				AND a.Qty<0
				'


			
				EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
				
				--PRINT(@strCheck)
			END

		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
			
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
			
			SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项/浮动数量等产生负库存!'
			RETURN;
				
			END
		END
	END
	
	
	--InOrOut
	
	--存在锁库数量大于库存总数量的商品给出提示
	SET @strCheck=@strTempSql+'
	SELECT @intCanDeal=COUNT(*) FROM TempResult a
							LEFT JOIN GoodsStocks_Qty b
								ON a.PTypeID = b.PTypeID
								AND a.KTypeID=b.KTypeID
								AND a.CargoID=b.CargoID
								AND a.ItemID=b.ItemID
								AND a.Iscombined=b.Iscombined
								AND a.GoodsNumber=b.GoodsNumber
								AND a.ProduceDate=b.ProduceDate
								AND a.ValidDate=b.ValidDate
								AND a.GoodsCostPrice=b.GoodsCostPrice
								INNER JOIN PType p
									ON a.PTypeID=p.typeId
						WHERE a.Qty+ISNULL(b.Qty,0)<b.LockNumber AND p.IsService=0 AND ISNULL(b.LockNumber,0)>0'
						
	EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
	IF @intCanDeal<>0
	BEGIN
		SET @intCanDeal=-18
		SELECT @strCheck=@strTempSql+'
		SELECT TOP 1
					@strTempPFullName=p.FullName,
					@strTempKFullName=k.FullName,
					@strTempCFullName=c.FullName,
					@strTempIFullName=i.itemname
		FROM TempResult a
		LEFT JOIN GoodsStocks_Qty b
		ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
					ON a.PTypeID=p.typeId
			INNER JOIN Stock k
					ON a.KTypeID=k.typeId
			INNER JOIN CargoType c
					ON a.CargoID=c.CargoID
			LEFT JOIN V_Item i
					ON a.ItemId=i.itemid
		WHERE a.Qty+ISNULL(b.Qty,0)<b.LockNumber AND p.IsService=0 AND b.LockNumber>0'
		
		EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
		
		--需要判断货位,自由项,批号,生产日期,保质期是否启用
		SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
				
		IF ISNULL(@strTempIFullName,'')<>''
		BEGIN
			SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
		END
				
		SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项等锁库数量大于库存总数量!'
		RETURN;
	END			
	
	--换货,调拨还要单独处理
	IF @intCanDeal=0
	BEGIN
	
		SELECT @strSql=@strTempSql+'
		
		MERGE GoodsStocks_Qty AS target
		USING 
		(
			SELECT PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice
			FROM TempResult
		) AS source (PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
		ON 
		(
			target.PTypeID = source.PTypeID
			AND target.KTypeID=source.KTypeID
			AND target.CargoID=source.CargoID
			AND target.ItemID=source.ItemID
			AND target.Iscombined=source.Iscombined
			AND target.GoodsNumber=source.GoodsNumber
			AND target.ProduceDate=source.ProduceDate
			AND target.ValidDate=source.ValidDate
			AND target.GoodsCostPrice=source.GoodsCostPrice
		)
		WHEN MATCHED AND target.Qty + source.Qty = 0 AND target.NQty + source.NQty = 0
		AND NOT EXISTS(
			SELECT PTypeID
			FROM GoodsStocks b
			WHERE target.PTypeID=b.PTypeID AND target.KTypeID=b.KTypeID
		)
		THEN DELETE
		WHEN MATCHED 
		THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.NQty = target.NQty + source.NQty
		WHEN NOT MATCHED BY TARGET  AND (source.Qty<>0 OR source.NQty<>0)
		THEN INSERT (PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice) 
		VALUES(source.PtypeId,source.KTypeID,source.CargoID,source.ItemID,source.Iscombined,
		source.GoodsNumber,source.ProduceDate,source.ValidDate,source.Qty,source.NQty,source.GoodsCostPrice);
		'
		
		--PRINT @strSql
		--EXEC(@strSql)	
		EXEC  sp_executesql @strSql
		
				--存在锁库数量大于库存总数量的商品给出提示
		SET @strCheck='
		SELECT @intCanDeal=COUNT(*) FROM  GoodsStocks_Qty
							WHERE ISNULL(LockNumber,0)>0 AND ISNULL(Qty,0)<ISNULL(LockNumber,0) '
						
		EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
		IF @intCanDeal<>0
		BEGIN
			SET @intCanDeal=-18
			SELECT @strCheck='
			SELECT TOP 1
					@strTempPFullName=p.FullName,
					@strTempKFullName=k.FullName,
					@strTempCFullName=c.FullName,
					@strTempIFullName=i.itemname
			FROM GoodsStocks_Qty b
			INNER JOIN PType p
					ON b.PTypeID=p.typeId
			INNER JOIN Stock k
					ON b.KTypeID=k.typeId
			INNER JOIN CargoType c
					ON b.CargoID=c.CargoID
			LEFT JOIN V_Item i
					ON b.ItemId=i.itemid
			WHERE b.LockNumber>0 AND ISNULL(b.Qty,0)<b.LockNumber AND p.IsService=0 '
		
			EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
		
			--需要判断货位,自由项,批号,生产日期,保质期是否启用
			SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
				
			IF ISNULL(@strTempIFullName,'')<>''
			BEGIN
				SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
			END
				
			SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项等锁库数量大于库存总数量!'
			RETURN;
		END	
		
	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=8,
	@intBillType=401,
	@intRedWord=0

BEGIN TRAN

 EXEC GP_Auditing_QTY_NewBill
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN


SELECT * FROM BillIndex
WHERE BILLCODE='GT-SUB1-T-2015-06-01-0001'





*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：修改单据REVERSE中处理只核算数量的货位,批号,自由项等,不判断库存
	返回结果：
	作    者：冯波
	创建时间：2015-11-30
	修改历史：
	
	
	
	还要处理维修类单据（需要区分是否从维修库出库）
	还需要处理代销类单据（需要处理代销库）
	还需要处理借欠
	
	成本调价单不用处理
	
	修改:冯波  2015-05-21
	
*/
CREATE          PROCEDURE GP_Auditing_QTY_Reverse
(
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,				--0表示正常单据
	@strInfo			VARCHAR(1000) OUT,
	@intCanDeal			INT OUT					--1表示库存不足
)
--@encode$--
AS


	
	/*
		45	销售退货单
		160	销售换货单
		142	委托代销退货单
		34	采购入库单
		161	采购换货单
		14	报溢单
		16	生产拆装单
		126	获赠单
		17	同价调拨单	
		21	变价调拨单
		144	受托代销收货单
		215 零售退货

		
		多仓库的 45,142,34,144
		单仓库的14,126，305,215
		
		17,21 单仓库入库部分
		160,161,16,  多仓库入库部分
		
		187是分支机构调拨出库
		188是分支机构调拨入库
		197 领料退回单
		201 其他入库单

	*/
	
	--要先进行数据的校验,看能否处理
	SELECT 
		@strInfo='',
		@intCanDeal=0
		


	DECLARE
		@DBName		VARCHAR(100)

	SELECT @DBName=DBO.F_BillTableName(@intBillType)

	DECLARE
		@strSql						NVARCHAR(MAX),
		@strTempSql					NVARCHAR(MAX),
		@strCheck					NVARCHAR(MAX),
		@AVERAGE					VARCHAR(50),
		@FIFO						VARCHAR(50),
		@LIFO						VARCHAR(50),
		@HAND						VARCHAR(50),
		@nCostingMethod				VARCHAR(50),
		@nAllowNegativeStock		TINYINT,  --0表示不允许,1表示允许
		@strTempAdpriceSQL			NVARCHAR(MAX)
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	-- 查询是否允许负库存 (适用于移动加权平均成本核算)
	EXEC GP_GetSubValue 'AllowNegativeStock', '',@nAllowNegativeStock output
		
			
	SELECT
		@AVERAGE	= '0',		-- 移动加权平均算法
		@FIFO		= '1',		-- 先进先出
		@LIFO		= '2',		-- 后进先出
		@HAND		= '3'			-- 手工指定法

	IF @intBillType=57
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
			
			
			SELECT @strTempAdpriceSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
			
			SELECT @strTempAdpriceSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.Price ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					INNER JOIN BillIndex b
					ON a.BillNumberID=b.BillNumberID
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
	END
	ELSE IF @intBillType IN (17,21)		
	BEGIN
		IF @intRedWord=0
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.OutCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID2 AS KTypeID,a.InCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN CASE '+CAST(@intBillType AS VARCHAR(100))+' WHEN 17 THEN a.GoodsCostPrice ELSE a.Price END ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
		ELSE
		BEGIN
			SELECT @strTempSQL='
			WITH TempResult AS
			(
				SELECT a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,
				SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty
				FROM
				(
					SELECT a.PTypeID,a.KTypeID,a.OutCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					a.Qty AS Qty,a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN a.GoodsCostPrice ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
					UNION ALL
					SELECT a.PTypeID,a.KTypeID2 AS KTypeID,a.InCargoID AS CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,
					-a.Qty AS Qty,-a.NQty AS NQty,CASE '+@nCostingMethod+' WHEN '+@HAND+' THEN CASE '+CAST(@intBillType AS VARCHAR(100))+' WHEN 17 THEN a.GoodsCostPrice ELSE a.Price END  ELSE 0 END AS GoodsCostPrice
					FROM '+@DBName+' a
					WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
				) a
				GROUP BY a.PTypeID,a.KTypeID,a.CargoID,a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice
			)
			'
		END
	END
	ELSE
	BEGIN
		SELECT 	@strTempSql='	
		WITH TempResult AS
		(
			SELECT a.PtypeId,'

		IF @intBillType IN (166,168,172,173,9,14,305,215)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID,'
		END
		ELSE IF @intBillType IN (174)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID2 AS KTypeID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.KTypeID2 AS KTypeID,'
		END
		ELSE BEGIN		
			SELECT @strTempSql=@strTempSql+'a.KTypeID,'
		END
		
		IF @intBillType IN (187)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.OutCargoID AS CargoID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.InCargoID AS CargoID,'
		END
		ELSE
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.CargoID,'
		END
		
		SELECT @strTempSql=@strTempSql+'a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate,'
			
		IF @intRedWord=0
		BEGIN
			IF @intBillType IN (34,45,126,144,142,188,201,174,14,215,400,403,46)--新增46 组合品销售换货单9.9.1
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (11,6,139,146,140,187,202,173,168,9,305,183,401,402,12)--新增12 组合品销售换货单9.9.1
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(-a.Qty) AS Qty,SUM(-a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (161,160,16,166,172)
			BEGIN
				--161,采购换货单
				--160,销售换货单
				SELECT @strTempSql=@strTempSql+'SUM(CASE a.InOrOUT WHEN ''I'' THEN a.Qty ELSE -a.QTY END) AS Qty,SUM(CASE a.InOrOUT WHEN ''I'' THEN a.NQty ELSE -a.NQTY END) AS NQty '
			END
		END
		ELSE
		BEGIN
			--红冲时
			IF @intBillType IN (34,45,126,144,142,188,201,174,14,215,400,403,46)--新增46 组合品销售换货单9.9.1
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(-a.Qty) AS Qty,SUM(-a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (11,6,139,146,140,187,202,173,168,9,305,183,401,402,12)--新增12 组合品销售换货单9.9.1
			BEGIN
				SELECT @strTempSql=@strTempSql+'SUM(a.Qty) AS Qty,SUM(a.NQty) AS NQty '
			END
			ELSE IF @intBillType IN (161,160,16,166,172)
			BEGIN
				--161,采购换货单
				--160,销售换货单
				SELECT @strTempSql=@strTempSql+'SUM(CASE a.InOrOUT WHEN ''I'' THEN -a.Qty ELSE a.QTY END) AS Qty,SUM(CASE a.InOrOUT WHEN ''I'' THEN -a.NQty ELSE a.NQTY END) AS NQty '
			END
		END
		
		IF @nCostingMethod=@HAND
		BEGIN
			IF @intBillType IN (305,11,139,140,6,146,17,21,187,202,9,173,183,168,401,402)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.GoodsCostPrice '
			END
			ELSE IF @intBillType IN (34,144,400)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.DiscountPrice AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (188,174, 201)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.Price AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (160) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (161) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.DiscountPrice ELSE CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  END AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (16)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.CostPrice ELSE a.GoodsCostPrice END AS GoodsCostPrice '
			END
			ELSE IF @intBillType IN (166,172)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN 0 ELSE a.GoodsCostPrice END AS GoodsCostPrice '
			END
			ELSE
			BEGIN
				SELECT @strTempSql=@strTempSql+',DBO.F_GetDetailCostPrice(a.BillNumberID,a.ID) AS GoodsCostPrice '
			END
		END
		ELSE
		BEGIN
			SELECT @strTempSql=@strTempSql+',0 AS GoodsCostPrice '
		END
			
		SELECT @strTempSql=@strTempSql+'
			FROM '+@DBName+' a	
			INNER JOIN PType p
			ON a.PTypeID=p.TypeID
			'
			
		IF @intBillType IN (166,168,172,173,174,9,14,305,215)
		BEGIN
			SELECT @strTempSql=@strTempSql+'
			INNER JOIN BillIndex b
			ON a.BillNumberID=b.BillNumberID
			'
		END	
			
		SELECT @strTempSql=@strTempSql+'WHERE a.BillNumberId='+CAST(@intBillNumberID AS VARCHAR(100))+'	AND p.IsService=0	'
		
		IF @intBillType IN (166,168,172)
		BEGIN
			SELECT @strTempSql=@strTempSql+' AND wxProperty=0 '
		END
		
		SELECT @strTempSql=@strTempSql+'	GROUP BY a.PtypeId,'
			
			
		IF @intBillType IN (166,168,172,173,9,14,305,215)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID,'
		END
		ELSE IF @intBillType IN (174)
		BEGIN
			SELECT @strTempSql=@strTempSql+'b.KTypeID2,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.KTypeID2,'
		END
		ELSE
		BEGIN		
			SELECT @strTempSql=@strTempSql+'a.KTypeID,'
		END
		
		IF @intBillType IN (187)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.OutCargoID,'
		END
		ELSE IF @intBillType IN (188)
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.InCargoID,'
		END
		ELSE
		BEGIN
			SELECT @strTempSql=@strTempSql+'a.CargoID,'
		END
		
		SELECT @strTempSql=@strTempSql+'a.ItemID,a.Iscombined,a.GoodsNumber,a.ProduceDate,a.ValidDate
		'
		
		IF @nCostingMethod=@HAND
		BEGIN
			IF @intBillType IN (305,11,139,140,6,146,17,21,187,202,9,173,183,168,401,402)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.GoodsCostPrice '
			END
			ELSE IF @intBillType IN (34,144,400)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.DiscountPrice '
			END
			ELSE IF @intBillType IN (188,174, 201)
			BEGIN
				SELECT @strTempSql=@strTempSql+',a.Price '
			END
			ELSE IF @intBillType IN (160) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  '
			END
			ELSE IF @intBillType IN (161) AND @intRedWord=0
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.DiscountPrice ELSE CASE ISNULL(a.InputCostPrice,0)  WHEN 0 THEN CASE a.GoodsCostPrice  WHEN -1 THEN DBO.F_GetRecPrice(a.STypeID,a.PTypeID) ELSE a.GoodsCostPrice END ELSE ISNULL(a.InputCostPrice,0) END  END '
			END
			ELSE IF @intBillType IN (16)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN a.CostPrice ELSE a.GoodsCostPrice END '
			END
			ELSE IF @intBillType IN (166,172)
			BEGIN
				SELECT @strTempSql=@strTempSql+',CASE  a.InOrOUT WHEN ''I'' THEN 0 ELSE a.GoodsCostPrice END '
			END
			ELSE
			BEGIN
				SELECT @strTempSql=@strTempSql+',DBO.F_GetDetailCostPrice(a.BillNumberID,a.ID) '
			END
		END
		
		SELECT @strTempSql=@strTempSql+'
		)
		'
		
	END
	

	/*		
	--TempResult中的QTY按入库为正,出库为负来记录
	DECLARE
		@strTempPFullName	VARCHAR(MAX),
		@strTempKFullName	VARCHAR(MAX),
		@strTempCFullName	VARCHAR(MAX),
		@strTempIFullName	VARCHAR(MAX)
		
	SELECT
		@strTempPFullName='',
		@strTempKFullName='',
		@strTempCFullName='',
		@strTempIFullName=''
		
	SELECT @intCanDeal=0
	
	
		--检查负库存开始
		IF ( (@nCostingMethod<>@AVERAGE) OR (@nCostingMethod=@AVERAGE AND @nAllowNegativeStock=0) )
		AND ( 
			( @intRedWord=0 AND @intBillType IN (11,6,139,146,140,187,202,173,168,305,9,183,401,402) ) OR ( @intRedWord<>0 AND @intBillType IN (34,45,126,144,142,188,201,174,14,215,400,403) ) 
			OR (@intBillType IN (161,160,16,17,21,166,168,172))
		)
		BEGIN		
			SELECT @strCheck=@strTempSql+'
			
			SELECT @intCanDeal=COUNT(*)
			FROM TempResult a
			LEFT JOIN GoodsStocks_Qty b
			ON a.PTypeID = b.PTypeID
			AND a.KTypeID=b.KTypeID
			AND a.CargoID=b.CargoID
			AND a.ItemID=b.ItemID
			AND a.Iscombined=b.Iscombined
			AND a.GoodsNumber=b.GoodsNumber
			AND a.ProduceDate=b.ProduceDate
			AND a.ValidDate=b.ValidDate
			AND a.GoodsCostPrice=b.GoodsCostPrice
			INNER JOIN PType p
			ON a.PTypeID=p.TypeID
			
			'
			
			SELECT @strCheck=@strCheck+'WHERE p.IsService=0 AND (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) '

			
			--PRINT(@strCheck)
		
			EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
			
			IF @intCanDeal<>0
			BEGIN
				SET @intCanDeal=-18
				
				SELECT @strCheck=@strTempSql+'
				
				SELECT TOP 1
					@strTempPFullName=p.FullName,
					@strTempKFullName=k.FullName,
					@strTempCFullName=c.FullName,
					@strTempIFullName=i.itemname
				FROM TempResult a
				LEFT JOIN GoodsStocks_Qty b
				ON a.PTypeID = b.PTypeID
				AND a.KTypeID=b.KTypeID
				AND a.CargoID=b.CargoID
				AND a.ItemID=b.ItemID
				AND a.Iscombined=b.Iscombined
				AND a.GoodsNumber=b.GoodsNumber
				AND a.ProduceDate=b.ProduceDate
				AND a.ValidDate=b.ValidDate
				AND a.GoodsCostPrice=b.GoodsCostPrice
				INNER JOIN PType p
				ON a.PTypeID=p.typeId
				INNER JOIN Stock k
				ON a.KTypeID=k.typeId
				INNER JOIN CargoType c
				ON a.CargoID=c.CargoID
				LEFT JOIN V_Item i
				ON a.ItemId=i.itemid
				
				'
				
				SELECT @strCheck=@strCheck+'WHERE  (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0) AND p.IsService=0
				ORDER BY p.UserCode
				'

			
				
			
				EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
				
				PRINT(@strCheck)
			
			
				--需要判断货位,自由项,批号,生产日期,保质期是否启用
				SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
				
				IF ISNULL(@strTempIFullName,'')<>''
				BEGIN
					SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
				END
				
				SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项/浮动数量等产生负库存!'
				
			END
			
		END
		ELSE IF ( (@nCostingMethod<>@AVERAGE) OR (@nCostingMethod=@AVERAGE AND @nAllowNegativeStock=0) ) AND @intBillType=57
		BEGIN
			IF  EXISTS(
				SELECT BillNumberID
				FROM AdPriceBill
				WHERE BillNumberId=@intBillNumberID
				AND ChangeAllStock=0
			)
			BEGIN
				SELECT @strCheck=@strTempAdpriceSQL+'
				
				SELECT @intCanDeal=COUNT(*)
				FROM TempResult a
				LEFT JOIN GoodsStocks_Qty b
				ON a.PTypeID = b.PTypeID
				AND a.KTypeID=b.KTypeID
				AND a.CargoID=b.CargoID
				AND a.ItemID=b.ItemID
				AND a.Iscombined=b.Iscombined
				AND a.GoodsNumber=b.GoodsNumber
				AND a.ProduceDate=b.ProduceDate
				AND a.ValidDate=b.ValidDate
				AND a.GoodsCostPrice=b.GoodsCostPrice
				INNER JOIN PType p
				ON a.PTypeID=p.TypeID
				'
				
				SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
				AND a.Qty<0
				'

				
				--PRINT(@strCheck)
			
				EXECUTE sp_executesql @strCheck,N'@intCanDeal INT OUTPUT',@intCanDeal OUTPUT
				
				IF @intCanDeal<>0
				BEGIN
					SET @intCanDeal=-18
					
					SELECT @strCheck=@strTempSql+'
				
				SELECT TOP 1
					@strTempPFullName=p.FullName,
					@strTempKFullName=k.FullName,
					@strTempCFullName=c.FullName,
					@strTempIFullName=i.itemname
				FROM TempResult a
				LEFT JOIN GoodsStocks_Qty b
				ON a.PTypeID = b.PTypeID
				AND a.KTypeID=b.KTypeID
				AND a.CargoID=b.CargoID
				AND a.ItemID=b.ItemID
				AND a.Iscombined=b.Iscombined
				AND a.GoodsNumber=b.GoodsNumber
				AND a.ProduceDate=b.ProduceDate
				AND a.ValidDate=b.ValidDate
				AND a.GoodsCostPrice=b.GoodsCostPrice
				INNER JOIN PType p
				ON a.PTypeID=p.typeId
				INNER JOIN Stock k
				ON a.KTypeID=k.typeId
				INNER JOIN CargoType c
				ON a.CargoID=c.CargoID
				LEFT JOIN V_Item i
				ON a.ItemId=i.itemid
				'
				
				SELECT @strCheck=@strCheck+'WHERE (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
				AND a.Qty<0
				'


			
				EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
				
				--PRINT(@strCheck)
			
				IF @strTempKFullName=''
				BEGIN
					--如果所得到的结果为空，则可能可能是调价100%，需要重新查结果
					
					SELECT @strCheck=@strTempAdpriceSQL+'
				
					SELECT TOP 1
						@strTempPFullName=p.FullName,
						@strTempKFullName=k.FullName,
						@strTempCFullName=c.FullName,
						@strTempIFullName=i.itemname
					FROM TempResult a
					LEFT JOIN GoodsStocks_Qty b
					ON a.PTypeID = b.PTypeID
					AND a.KTypeID=b.KTypeID
					AND a.CargoID=b.CargoID
					AND a.ItemID=b.ItemID
					AND a.Iscombined=b.Iscombined
					AND a.GoodsNumber=b.GoodsNumber
					AND a.ProduceDate=b.ProduceDate
					AND a.ValidDate=b.ValidDate
					AND a.GoodsCostPrice=b.GoodsCostPrice
					INNER JOIN PType p
					ON a.PTypeID=p.typeId
					INNER JOIN Stock k
					ON a.KTypeID=k.typeId
					INNER JOIN CargoType c
					ON a.CargoID=c.CargoID
					LEFT JOIN V_Item i
					ON a.ItemId=i.itemid
					'
					
					SELECT @strCheck=@strCheck+'WHERE  (a.Qty+ISNULL(b.Qty,0)<0 OR a.NQty+ISNULL(b.NQty,0)<0)  AND p.IsService=0
					AND a.Qty<0
					'


				
					EXECUTE sp_executesql @strCheck,N'@strTempPFullName VARCHAR(MAX) OUTPUT,@strTempKFullName VARCHAR(MAX) OUTPUT,@strTempCFullName VARCHAR(MAX) OUTPUT,@strTempIFullName VARCHAR(MAX) OUTPUT',@strTempPFullName OUT,@strTempKFullName OUT,@strTempCFullName OUT,@strTempIFullName OUT
					
					--PRINT(@strCheck)
				END

			
				--需要判断货位,自由项,批号,生产日期,保质期是否启用
				SELECT @strInfo='['+@strTempPFullName+']'+'['+@strTempKFullName+']'+'['+@strTempCFullName+']'
				
				IF ISNULL(@strTempIFullName,'')<>''
				BEGIN
					SELECT @strInfo=@strInfo+'['+@strTempIFullName+']'
				END
				
				SELECT @strInfo=@strInfo+'会造成相应批号/货位/自由项/浮动数量等产生负库存!'
					
					
				END
			END
		END
	
	
	--InOrOut
	*/
	
	--换货,调拨还要单独处理
	IF @intCanDeal=0
	BEGIN
	
		SELECT @strSql=@strTempSql+'
		
		MERGE GoodsStocks_Qty AS target
		USING 
		(
			SELECT PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice
			FROM TempResult
		) AS source (PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
		ON 
		(
			target.PTypeID = source.PTypeID
			AND target.KTypeID=source.KTypeID
			AND target.CargoID=source.CargoID
			AND target.ItemID=source.ItemID
			AND target.Iscombined=source.Iscombined
			AND target.GoodsNumber=source.GoodsNumber
			AND target.ProduceDate=source.ProduceDate
			AND target.ValidDate=source.ValidDate
			AND target.GoodsCostPrice=source.GoodsCostPrice
		)
		WHEN MATCHED AND target.Qty + source.Qty = 0 AND target.NQty + source.NQty = 0
		AND NOT EXISTS(
			SELECT PTypeID
			FROM GoodsStocks b
			WHERE target.PTypeID=b.PTypeID AND target.KTypeID=b.KTypeID
		)
		THEN DELETE
		WHEN MATCHED 
		THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.NQty = target.NQty + source.NQty
		WHEN NOT MATCHED BY TARGET  AND (source.Qty<>0 OR source.NQty<>0)
		THEN INSERT (PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice) 
		VALUES(source.PtypeId,source.KTypeID,source.CargoID,source.ItemID,source.Iscombined,
		source.GoodsNumber,source.ProduceDate,source.ValidDate,source.Qty,source.NQty,source.GoodsCostPrice);
		'
		
		--PRINT @strSql
		--EXEC(@strSql)	
		EXEC  sp_executesql @strSql
		
	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@intBillNumberID	INT,
	@intBillType		INT,
	@intRedWord			TINYINT,  --0表示正常单据
	@strInfo			VARCHAR(1000),
	@intCanDeal			INT   --1表示库存不足
	
SELECT
	@intBillNumberID=8,
	@intBillType=401,
	@intRedWord=0

BEGIN TRAN

 EXEC GP_Auditing_QTY_Reverse
	@intBillNumberID,
	@intBillType,
	@intRedWord,
	@strInfo OUT,
	@intCanDeal OUT

SELECT @strInfo,@intCanDeal

ROLLBACK TRAN


SELECT * FROM BillIndex
WHERE BILLCODE='GT-SUB1-T-2015-06-01-0001'





*/



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Auditing_ReturnMsg]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_Auditing_ReturnMsg]
GO




/*

功能说明：		过账不成功时，得到完整信息

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_Auditing_ReturnMsg]
(
	@intRe					INT,					--过账返回的出错代号(-1表示库存不足)
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
)
--@encode$--        
AS

--  -1表示库存不足，-907表示序列号不在库，-904表示单据数量与序列号数量不一致

--判断#AuditReturnReSult是否存在，不存在则直接退出
IF NOT EXISTS(
	SELECT * FROM tempdb.sys.objects WHERE object_id = OBJECT_ID(N'tempdb..[#AuditReturnReSult]') AND type in (N'U')
) RETURN

IF @intRe NOT IN (-1,-907,-904)
	RETURN
	
IF @intRe=-1
BEGIN
	EXEC GP_ReturnMsg_StockLack
		@intRe,
		@intBillType,
		@intBillNumberID
END
ELSE IF @intRe=-907
BEGIN
	EXEC GP_ReturnMsg_LackSerial
		@intRe,
		@intBillType,
		@intBillNumberID
END
ELSE IF @intRe=-904
BEGIN
	EXEC GP_ReturnMsg_SerialCount
		@intRe,
		@intBillType,
		@intBillNumberID
END


GO





if exists (select * from dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_Auditing_SaleListTable]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Auditing_SaleListTable]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	成本价销售过帐后处理科目
	作    者：	冯波
	修改时间：	2011-04-13
*/
CREATE             PROCEDURE GP_Auditing_SaleListTable
(
	@intBillNumberID		numeric(10,0)			-- 单据 ID 号
)
--@encode$--
AS
	SET NOCOUNT ON
	
	DECLARE	
		@chvPtypeId varchar(50),    
		@numTrackPrice  NUMERIC(24, 10) ,
		@numYSYFMoney		 NUMERIC(24, 10) ,
		@nRet				INT,
		@intReturnID		INT,				--新生成的单据的ID
		@strReturnBillCode	VARCHAR(200),
		@strErrMsg			VARCHAR(2000),		--出错信息
		@intCostSale		INT,
		@numBillType		numeric(4,0),
		@datBillDate		datetime,
		@chvATypeID			varchar(50),
		@chvBTypeID			varchar(50),
		@chvETypeID			varchar(50),
		@chvKTypeID			varchar(50),
		@chvKTypeID2		varchar(50),
		@chvDTypeID			varchar(50),
		@chvSTypeID			varchar(50),
		@numTotalMoney		 NUMERIC(24, 10) ,
		@numTotalInMoney	 NUMERIC(24, 10) ,
		@numPreferenceMoney	 NUMERIC(24, 10) ,
		@intRowCount		int,
		@intVipCardID		int,			-- VIP卡ID值
		@intVipCardTypeID	int,			-- VIP卡类型ID值
		@chrIfVipJF			char(1),		-- 卡类型是否积分标识
		@intVipGridJF		int,			-- 单据GRID每行商品的积分
		@intVipJF			int,			-- 单据总积分
		@numVipTotalMoney	 NUMERIC(24, 10) ,	-- 单据消费金额 = 单据金额
		@chvVipIsCz			varchar(1),		-- 是否VIP会员储值
		@numVipCzTotalInMoney  NUMERIC(24, 10) ,	-- 单据VIP会员储值对应的实收/付金额
		@numVipcZyeMoney	 NUMERIC(24, 10) ,	-- VIP会员储值余额
		@numTax				 NUMERIC(24, 10) ,
		@numDiscount		 NUMERIC(24, 10) ,
		@numSalePrice		 NUMERIC(24, 10) ,
		@numSaleTotal		 NUMERIC(24, 10) ,
		@numTaxPrice		 NUMERIC(24, 10) ,
		@numTaxTotal		 NUMERIC(24, 10) ,
		@wxProperty			int,	-- 维修属性，0：正常商品；1：维修商品
		@ifDetailWX			int,	-- （单据明细）是否属于维修库的出入库记录，0：正常库；1：维修库
		@ifIndexWX			int,	-- （单据索引）是否针对维修库存进行盘点、报损、报溢；0：正常库，1：维修库
		@IfMulAccount		INT,
		@strMsg				VARCHAR(50),
		@CID				BIGINT,
		@NnumBanlanceTotal	 NUMERIC(24, 10) ,
		@NnumTaxBanlance		 NUMERIC(24, 10) ,
		@NnumPreferenceMoney	 NUMERIC(24, 10) ,
		@NnumTotalInMoney	 NUMERIC(24, 10) ,
		@NnumTotalMoney		 NUMERIC(24, 10) ,
		@NnumNoTaxTotal		 NUMERIC(24, 10) ,
		@SysCid				BIGINT, --本位币id
		@numRate			 NUMERIC(24, 10) ,
		@NewPosBill			TINYINT
	
	SELECT TOP 1 @SysCid=CId FROM Ac_Currency WHERE Sysrow = 1	

	SELECT	@numBillType = BillType,
			@datBillDate = BillDate,
			@chvATypeID = ATypeID,
			@chvBTypeID = BTypeID,
			@chvETypeID = ETypeID,
			@chvKTypeID = KTypeID,
			@chvKTypeID2 = KTypeID2,
			@chvDTypeID	=DTypeID,
			@chvSTypeID=STypeID,
			@numTotalMoney = TotalMoney,
			@NnumTotalMoney = NTotalMoney,
			@numTotalInMoney = TotalInMoney,
			@NnumTotalInMoney = NTotalInMoney,
			@numPreferenceMoney = PreferenceMoney,
			@NnumPreferenceMoney = NPreferenceMoney,
			@intVipCardID = VipCardID,
			@numTax = Tax,
			@ifIndexWX = ifWX,
			@intCostSale=CostSale,
			@IfMulAccount=IfMulAccount,
			@cid= CID,
			@numRate=Rate,
			@NewPosBill=NewPosBill
	FROM	BillIndex
	WHERE	BillNumberID = @intBillNumberID
	
	

	DECLARE
		@intReturnCode			int,	
		@chvJobNumber			varchar(20),
		@datOutFactoryDate		datetime,
		@PreGathering_ID		varchar(50),
		@PREFERENCEID			varchar(50),
		@PAY_TAXMONEY_ID		varchar(50),
		@SALE_INCOME_ID			varchar(50),
		@numTaxBanlance			 NUMERIC(24, 10) ,		-- 税额
		@numBanlanceTotal		 NUMERIC(24, 10) ,		-- 差额
		@numNoTaxTotal			 NUMERIC(24, 10) ,
		@AR_ID					VARCHAR(50) = '0'--应收
		
	SELECT
		@chvJobNumber='',
		@datOutFactoryDate=NULL
		
		 
		SELECT @PAY_TAXMONEY_ID=NID FROM dbo.Ac_Items WHERE UserCode='2171'--『应交税金』,0000200004
		SELECT @PreGathering_ID=NID FROM dbo.Ac_Items WHERE UserCode='2131'--『预收账款』,0000200006
		SELECT @SALE_INCOME_ID=NID FROM dbo.Ac_Items WHERE UserCode='5101'--『销售收入』,0000300001
		SELECT @PREFERENCEID=NID FROM dbo.Ac_Items WHERE UserCode='0456'--优惠金额,000040000300004
		SELECT @AR_ID=nId FROM Ac_Items WHERE UserCode='987'  --应收
		
	SELECT @intReturnCode=0
	
	-- ********* 处理生成 ListTable 凭证记录 *********
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0),@NnumNoTaxTotal=ISNULL(SUM(NTotal),0) FROM SaleBill WHERE BillNumberID = @intBillNumberID
	
	-- 销售收入
	IF @numNoTaxTotal <> 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@SALE_INCOME_ID,@chvBTypeID,@chvETypeID,
			@numNoTaxTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@NnumNoTaxTotal,@numRate
	END


	-- 实收金额

	IF @numTotalInMoney <> 0
	BEGIN
		EXEC @intReturnCode =GP_Auditing_MulAccount	@intBillNumberID,@numBillType,@NewPosBill,@chvSTypeID,@strMsg OUTPUT
		IF @intReturnCode <> 0 RETURN @intReturnCode
	END

	-- 优惠金额
	IF @numPreferenceMoney <> 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PREFERENCEID,@chvBTypeID,@chvETypeID,
			@numPreferenceMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@NnumPreferenceMoney,@numRate
		
	END

	-- 应交税金
	
	IF @numTotalMoney - @numNoTaxTotal <> 0
	BEGIN
		SET @numTaxBanlance = @numTotalMoney - @numNoTaxTotal
		SET @NnumTaxBanlance = @NnumTotalMoney - @NnumNoTaxTotal
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@NnumTaxBanlance,@numRate
		
	END


	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	SET @NnumBanlanceTotal = @NnumTotalMoney - @NnumTotalInMoney - @NnumPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@AR_ID,@CID,@NnumBanlanceTotal,@numRate
		
	IF @intVipCardID <> -1
	BEGIN
		SELECT	@chrIfVipJF = b.ifJF,
				@chvVipIsCz = a.IsCz,
				@numVipcZyeMoney = a.cZyeMoney
		FROM	nVipCardSign a,nVipCardSET b
		WHERE	a.VipCardID = @intVipCardID
				AND a.VipCardTypeID = b.VipCardTypeID
				AND a.Deleted = '0'
				AND b.Deleted = '0'
				AND a.EndDate >= @datBillDate

		-- 1)无此VIP卡 2)过了有效期 3)VIP卡是未启用状态 4)VIP卡类型不存在或已删除
		
		SET @intVipJF = 0
		SET @numVipTotalMoney = @numTotalMoney

		
		IF @chvVipIsCz = '1'
		BEGIN
			-- 过账时将VIP会员储值卡的消费前余额记入至BillIndex中
			UPDATE BillIndex SET vipCZMoney = @numVipcZyeMoney WHERE BillNumberID = @intBillNumberID
		END
	END


	-- 处理累计消费金额和积分
	IF @intVipCardID <> -1
	BEGIN
		IF @chrIfVipJF = '1'
		BEGIN
			SELECT	@intVipJF = ISNULL(SUM(a.GridJF),0) FROM (
				SELECT	CAST((SUM(ISNULL(a.Total,0))/c.Total) AS int)*ISNULL(c.JF,0) AS GridJF
				FROM	SaleBill a,nVipGoodsSign b,nVipJfSET c
				WHERE	a.BillNumberID = @intBillNumberID
						AND a.PTypeID = b.PTypeID
						AND b.JFID = c.[ID]
						AND c.Total <> 0
						AND c.JF <> 0
				GROUP BY c.[ID],c.Total,c.[JF]
			) a

			IF @intVipJF <> 0
				UPDATE BillIndex SET JF = @intVipJF
				WHERE BillNumberID = @intBillNumberID
		END

		IF @numVipTotalMoney <> 0 OR @intVipJF <> 0
			UPDATE nVipCardSign
			SET TotalMoney = TotalMoney + @numVipTotalMoney,
				TotalCent = TotalCent + @intVipJF
			WHERE VipCardID = @intVipCardID

		-- 扣减会员储值余额
		IF @chvVipIsCz = '1' AND @chvATypeID = '0000200005' AND @numTotalInMoney > 0
		BEGIN
			UPDATE	nVipCardSign
			SET		cZyeMoney = cZyeMoney - @numTotalInMoney
			WHERE	VipCardID = @intVipCardID
		END
	END
	
	
	
	
	--处理价格跟踪（无促销价，且不是会员卡时，才进行价格跟踪）
	DECLARE
		@intPromotePrice	 NUMERIC(24, 10) 
		
	/*	IF @intVipCardID = -1
	BEGIN
	DECLARE Trace_cursor CURSOR FOR 
		SELECT PTypeID,KTypeID,DiscountPrice
		FROM SaleBill
		WHERE BillNumberID=@intBillNumberID


		OPEN Trace_cursor

		FETCH NEXT FROM Trace_cursor 
		INTO @chvPTypeID,@chvKTypeID,@numTrackPrice

		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC
				Web_CheckPromotePrice
				@intPromotePrice	output,
				@chvPTypeID,
				@chvBTypeID,
				@chvKTypeID,
				@chvETypeID,
				@datBillDate
		
			IF @intPromotePrice=0
			BEGIN
				EXEC	Gp_AuditingPriceTrack
					@intBillNumberID,
					@chvPtypeId,
					@numTrackPrice,
					@numBillType,
					@chvBTypeId,
					@chvKtypeId,
					@chvStypeId
			END
			FETCH NEXT FROM Trace_cursor 
			INTO @chvPTypeID,@chvKTypeID,@numTrackPrice
		END
		CLOSE Trace_cursor
		DEALLOCATE Trace_cursor
	END	*/
		
		
	--再处理结算状态JSSTyle,JSState
	
	IF @numTotalInMoney>=@numTotalMoney
	BEGIN
		IF @numTotalMoney=0
		BEGIN
			UPDATE BillIndex
			SET JsStyle=0,JsState=2
			WHERE BillNumberID=@intBillNumberID
		END
		ELSE
		BEGIN
			UPDATE BillIndex
			SET JsStyle=1,JsState=2
			WHERE BillNumberID=@intBillNumberID
		END
	END
	ELSE
	BEGIN
		IF @numTotalInMoney=0
		BEGIN
			UPDATE BillIndex
			SET JsStyle=0,JsState=0
			WHERE BillNumberID=@intBillNumberID
		END
		ELSE
		BEGIN
			UPDATE BillIndex
			SET JsStyle=1,JsState=1
			WHERE BillNumberID=@intBillNumberID
		END
	END
	
	
	--回写订单金额（之前是放在InsertOrder这个TRIGGER中的）
	DECLARE
		@OrderID	INT,
		@Total		 NUMERIC(24, 10) ,
		@TaxTotal	 NUMERIC(24, 10) 
	
	DECLARE CR_ReachTaxTotal CURSOR FOR
	SELECT ORDERID,Total,TaxTotal 
	FROM SaleBill
	WHERE BillNumberID=@intBillNumberID AND OrderID>0
 
	OPEN CR_ReachTaxTotal

	FETCH NEXT FROM CR_ReachTaxTotal INTO @OrderID,@Total,@TaxTotal
	WHILE @@FETCH_STATUS<>-1
	BEGIN
		UPDATE OrderBill 
		SET 
		ReachTotal=ISNULL(ReachTotal,0)+@Total,
		ReachTaxTotal=ISNULL(ReachTaxTotal,0)+@TaxTotal
		WHERE OrderID=@OrderID
		
		FETCH NEXT FROM CR_ReachTaxTotal INTO @OrderID,@Total,@TaxTotal
	END

	CLOSE CR_ReachTaxTotal
	DEALLOCATE CR_ReachTaxTotal
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	自动审核过账后反写数量和状态
	作    者：	冯波
	修改时间：	2011-08-16
*/
CREATE             PROCEDURE Gp_Auditing_UpdateQtyorState
(
	@nBillID				NUMERIC(10,0),				-- 单据 ID 号
	@intBillType			INT
	
)
----@encode$--
AS

	

	DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT
		
	DECLARE
		
		@strPriceDot		VARCHAR(10),
		@strMoneyDot		VARCHAR(10)
		
	SELECT
		@strPriceDot=@intPriceDot,
		@strMoneyDot=@intMoneyDot		
		

	DECLARE
		@intRedWord		TINYINT
		
	SELECT
		@intRedWord=RedWord
	FROM BillIndex
	WHERE BillNumberId=@nBillID
	
	
	DECLARE 
			@nCostingMethod		smallint,
			@AVERAGE			smallint,
			@FIFO				smallint,
			@LIFO				smallint,
			@HAND				smallint

	SET @AVERAGE	= 0		-- 移动加权平均
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	SET @HAND		= 3		-- 手工指定

	EXEC Gp_GetSubValue 'costing','',@nCostingMethod output

   --零售退货掉零售单，更新退货数量
	IF @intBillType=215 AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0)
	BEGIN
	UPDATE dbo.retailbill SET BackQty += D.qty 
	FROM RetailBackBill D,dbo.retailbill M
	WHERE M.ID=D.OldID 	AND M.BillNumberId=D.OldBillNumberID
	AND D.BillNumberId=@nBillID 
	AND D.OldID>0 
	
	END
  
	IF(@intBillType=401) AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0)
		--暂估退货单
	  BEGIN
		
		UPDATE AppraisalBill 
		SET    BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM   AppraisalBill A,AppraisalBackBill B 
		WHERE  A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@nBillID
	END
	
	IF(@intBillType=45) AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0)   
	--销售退货单
	  BEGIN
		UPDATE  SaleBill --对销售出库单处理
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    SaleBill A,SaleBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@nBillID
     END
     
     	IF(@intBillType=46) AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0)  
     	 --组合品销售退货单
	  BEGIN
		UPDATE  PT_Combin_SaleBillDetail --对销售出库单处理
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    PT_Combin_SaleBillDetail A,PT_Combin_SaleBackBillDetail B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@nBillID
     END
     
 --    ---委托代销退货单调委托代销入库单反写退货数量
	IF @intBillType=142 AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0)  
	BEGIN
	UPDATE D  SET BQty += M.qty 
	FROM commissionbill D,dbo.commissionbill M
	WHERE M.OldID=D.ID 	
	AND M.BillNumberId=@nBillID  
	END
	
	-----受托代销退货单调受托代销收货库单反写退货数量
	IF @intBillType=146 AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0)  
	BEGIN
	UPDATE D  SET BQty += M.qty 
	FROM commissionbill D,dbo.commissionbill M
	WHERE M.OldID=D.ID 	
	AND M.BillNumberId=@nBillID   
	END
	
	-----受托代销结算单调受托代销收货单反写结算数量
	IF @intBillType=145 AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0)  
	BEGIN
	UPDATE D  SET BackQty += M.qty 
	FROM commissionbill D,dbo.commissionbill M
	WHERE M.OldID=D.ID 	 AND D.BillNumberID=M.OldBillNumberID 
	AND M.BillNumberId=@nBillID  
	END
	
	--	---委托托代销结算单调委托代销发货单反写结算数量
	IF @intBillType=141  AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0) 
	BEGIN
	UPDATE D  SET BackQty += M.qty 
	FROM commissionbill D,dbo.commissionbill M
	WHERE M.OldID=D.ID 	 AND D.BillNumberID=M.OldBillNumberID 
	AND M.BillNumberId=@nBillID  
	END
	
		--	单据自动审核，发出商品退货单调发出商品出库单自动审核通过并过账后，发出商品出库单的“已退货数量”字段没有更新
	IF @intBillType=403  AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0) 
	BEGIN
	UPDATE  SendBill 
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    SendBill A,SendBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@nBillID 
	END
	
   --	单据自动审核，上门维修单调报修单自动审核通过并过账后，此时点击调报修单发现还可以调到该张报修单，错误；并且商品的状态应变为“已上门维修”
	IF @intBillType=172  AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0) 
	BEGIN
	UPDATE  wx_Bill_Call 
		SET     State=1 
		FROM    wx_Bill_Call A,BillIndex B 
		WHERE   A.id=B.BaoXiuID 
			AND A.BillNumberId=B.BaoXiuBillNumberID 
			AND B.Billnumberid=@nBillID AND b.ifcheck='t' AND RedWord='0' AND b.Billtype=172
	END
	
	
	  --	单据自动审核，整机更换单调接件单自动审核通过并过账后，此时点击调接件单发现还可以调到该张接件单

	IF @intBillType=168  AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0) 
	BEGIN
	UPDATE  wx_bill_jiejian 
		SET     State=1 
		FROM    wx_bill_jiejian A,wx_bill_replace B ,dbo.BillIndex C
		WHERE   A.id=B.JieJianID 
			AND A.BillNumberId=B.JieJianBillNumberID AND B.BillNumberID=C.BillNumberId
			AND B.Billnumberid=@nBillID AND C.ifcheck='t' AND C.RedWord='0' AND C.Billtype=168
	END
	
	
	 --	单据自动审核，维修取件单调接件单自动审核通过并过账后，此时点击调接件单发现还可以调到该张接件单，错误

	IF @intBillType=167  AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0) 
	BEGIN
	UPDATE  wx_bill_jiejian 
		SET     State=5 
		FROM    wx_bill_jiejian A,wx_bill_getback B ,dbo.BillIndex C
		WHERE   A.id=B.JieJianID 
			AND A.BillNumberId=B.JieJianBillNumberID AND B.BillNumberID=C.BillNumberId
			AND B.Billnumberid=@nBillID AND C.ifcheck='t' AND C.RedWord='0' AND C.Billtype=167
	END
	
	--	单据自动审核，维修取件单调接件单自动审核通过并过账后，此时点击调接件单发现还可以调到该张接件单，错误

	IF @intBillType=166  AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0) 
	BEGIN
	UPDATE  wx_bill_jiejian 
		SET     State=2 
		FROM    wx_bill_jiejian A,BillIndex B 
		WHERE   A.id=B.JieJianID 
			AND A.BillNumberId=B.JieJianBillNumberID 
			AND B.Billnumberid=@nBillID AND B.ifcheck='t' AND B.RedWord='0' AND B.Billtype=166
	END
	
	
		--	单据自动审核，维修取件单调接件单自动审核通过并过账后，此时点击调接件单发现还可以调到该张接件单，错误

	IF @intBillType=170  AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0) 
	BEGIN
	
	UPDATE  wx_bill_send 
		SET    SendBackQty += b.qty 
		FROM   dbo.wx_bill_send A , wx_bill_sendback B ,dbo.BillIndex C
		WHERE   A.id= b.SendID 
			AND A.BillNumberId=B.SendBillNumberID 
			AND B.Billnumberid=@nBillID AND C.ifcheck='t' AND C.RedWord='0' AND C.Billtype=170
	END
	
	--送修单掉维修接件单，state=3
	IF @intBillType=169  AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0) 
	BEGIN
	UPDATE  wx_bill_jiejian 
		SET     State=3
		FROM    wx_bill_jiejian A,wx_bill_send B ,dbo.BillIndex C
		WHERE   A.id=B.JieJianID 
			AND A.BillNumberId=B.JieJianBillNumberID AND B.BillNumberID=C.BillNumberId
			AND B.Billnumberid=@nBillID AND C.ifcheck='t' AND C.RedWord='0' AND C.Billtype=169
	END
	--自动审核过账反写收付款单的状态和金额
	if(@intBillType in(4,66) AND EXISTS (SELECT TOP  1 1 FROM Billindex WHERE BillNumberId=@nBillID AND BillType=@intBillType AND ifcheck='t' AND RedWord=0))
	BEGIN
	EXEC GP_BatchPassBlance @nBillID
	END
	---自动审核过账反写价格跟踪
	IF @intBillType IN(6, 11,12, 34, 45, 140, 141, 142, 144, 145, 146, 160, 161, 187, 188, 215, 305, 400, 402 )
	BEGIN
	   EXEC dbo.GP_BatchPassPT @billnumberid=@nBillID,@billtype=@intBillType
	END
	
	
	

	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





--积分转储值单过账
IF  EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_Auditing_VipCentToMoneyBill',N'P'))
	BEGIN
		DROP PROC GP_Auditing_VipCentToMoneyBill
	END
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--=================================
--by:glj
--date:2018-05-15
--description:积分转储值单过账
--=================================
CREATE PROC GP_Auditing_VipCentToMoneyBill
(
	@BillNumberID	INT,
	@BillType		INT,
	@szCheckMan		VARCHAR(50),
	@OperatorID		VARCHAR(50),
	@voucherMsg		VARCHAR(1000) OUT
)
AS
SET NOCOUNT ON

DECLARE
	@nRet				INT,						-- 返回的出错值
	@szCheck			CHAR(1),					-- 过账标志
	@STypeID			VARCHAR(50),
	@vipBillStoredByStypeId INT,--会员储值结算使用单据所选分支机构进行储值余额判断
	@VipCardID			INT,--会员卡
	@ChangeCent			INT,--兑换积分
	@ChangeMoney		NUMERIC(24,10),--兑换储值金额
	@BillDate			DATETIME,--兑换积分
	@NewPosBill			INT--是否POS单据
	
SELECT @vipBillStoredByStypeId=Value FROM Userconfig WHERE ConfigName='vipBillStoredByStypeId'
SELECT 
	@STypeID=B.StypeID,
	@VipCardID=CB.VipCardId,
	@ChangeCent=CB.ChangeCent,
	@ChangeMoney=CB.ChangeMoney,
	@BillDate=B.BillDate,
	@NewPosBill=B.NewPosBill
FROM VipCentToMoneyBill CB 
INNER JOIN BillIndex B  ON CB.BillNumberId=@BillNumberID AND CB.BillNumberId=B.BillNumberId

--判断版本，是否试用版本 是否开账等
EXEC @nRet=Gp_Auditing_Control @STypeID
IF @nRet<>0 
BEGIN
	RETURN @nRet
END

--没有单据过账的权限 
IF(@NewPosBill=0)
BEGIN
	EXEC @nRet=Gp_CheckLimitBillType @OperatorID,0,@billtype
	IF @nRet<>1 
	BEGIN
		RETURN 1000 
	END
	SELECT @nRet = 0
END

--判断状态
IF NOT EXISTS(SELECT BillnumberID FROM BillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f')
BEGIN
	RETURN 1111  --该单据不存在或已过账
END

--判断会员卡是否有效
IF NOT EXISTS(SELECT * FROM nVipCardSign a INNER JOIN nVipCardSet b ON a.VipCardID = @VipCardID AND a.VipCardTypeID = b.VipCardTypeID AND A.deleted=0 AND B.deleted=0 AND A.EndDate>=@BillDate)
BEGIN
	RETURN 701
END


--判断是否适用当前分支机构
IF NOT EXISTS(SELECT * FROM nVipCardSign WHERE VipCardID=@VipCardID AND (isApplyAllStype=1 OR (isApplyAllStype=0 AND EXISTS(SELECT * FROM VipCard_ApplyStype APS WHERE APS.StypeId=@STypeID AND APS.VipCardId=VipCardID ))))	
BEGIN
	RETURN 706
END

--过账时总积分小于当前兑换积分
IF EXISTS(SELECT * FROM nVipCardSign WHERE VipCardID=@VipCardID AND (BeginCent+totalCent)<@ChangeCent)
BEGIN
	RETURN 707
END

--更改单据状态：草稿 -> 过账单据
UPDATE	BillIndex
SET		
	IfCheck = 't',
	Checke = @szCheckman,
	Draft = 0,
	Poster=@OperatorID,
	PostTime=GETDATE()
WHERE
	BillNumberID=@BillNumberID
	AND BillType=@BillType
	
UPDATE dbo.VipCentToMoneyBill SET DraftFlag=0 WHERE BillNumberID=@BillNumberID

--影响会员卡储值金额
UPDATE nVipCardSign
SET 
	lJczMoney+=@ChangeMoney,
	cZyeMoney+=@ChangeMoney,
	totalCent-=@ChangeCent
FROM nVipCardSign
WHERE VipCardID=@VipCardID

--影响会员卡储值金额
IF EXISTS(SELECT * FROM nVipCardSignStype WHERE VipCardID=@VipCardID AND StypeId=@STypeID)
BEGIN
	UPDATE nVipCardSignStype
	SET 
		lJczMoney+=@ChangeMoney,
		bNczMoney+=@ChangeMoney,
		cZyeMoney+=@ChangeMoney
	WHERE 
		VipCardID=@VipCardID
		AND StypeId=@STypeID
END
ELSE 
BEGIN
	INSERT INTO nVipCardSignStype(VipCardID,StypeId,lJczMoney,bNczMoney,cZyeMoney)VALUES(@VipCardID,@STypeID,@ChangeMoney,@ChangeMoney,@ChangeMoney)
END

--影响listtable 项目数据
DECLARE
	@datBillDate			DATETIME,					-- 单据日期
	@chvATypeID				VARCHAR(50),				-- 收付款账户 ID 值
	@chvBTypeID				VARCHAR(50),				--结算单位
	@chvDealBTypeID			VARCHAR(50),				--往来单位
	@chvETypeID				VARCHAR(50),				-- 经手人 ID 值
	@chvKTypeID				VARCHAR(50),				-- 出库仓库 ID 值
	@chvKTypeID2			VARCHAR(50),				-- 入库仓库 ID 值
	@chvDTypeID				VARCHAR(50),				--部门
	@numTotalMoney			 NUMERIC(24, 10) ,				-- 单据金额合计
	@numTotalInMoney		 NUMERIC(24, 10) ,				-- 单据实收、实付金额
	@numPreferenceMoney		 NUMERIC(24, 10) ,
	@numNTotalMoney			 NUMERIC(24, 10) ,
	@numNTotalInMoney		 NUMERIC(24, 10) ,
	@numNPreferenceMoney	 NUMERIC(24, 10) ,
	@wxTotal				 NUMERIC(24, 10) ,	
	@numTax					 NUMERIC(24, 10) ,
	@ifIndexWX				TINYINT,
	@intCostSale			TINYINT,
	@intCID					INT,
	@ifCheck				VARCHAR(10),				-- 是否草稿标识，f - 草稿；t - 已过账
	@IfMulAccount			TINYINT,
	@intVipCardID			INT,
	@BillName				VARCHAR(100),
	@NumRate				 NUMERIC(24, 10) ,
	@AssetBusinessTypeId    INT,
	@intRedWord				TINYINT,
	@intNewPosBill			TINYINT,
	@AuditType				INT,
	@IfLend					INT=0,
	@datPostTime			DATETIME 
		
	
EXEC GP_GetBillIndexInfo
	@BillNumberID,
	@Billtype,
	@datBillDate	OUT,
	@chvATypeID	OUT,				-- 收付款账户 ID 值
	@chvBTypeID	OUT,				--结算单位
	@chvDealBTypeID	OUT,				--往来单位
	@chvETypeID	OUT,				-- 经手人 ID 值
	@chvKTypeID	OUT,				-- 出库仓库 ID 值
	@chvKTypeID2	OUT,				-- 入库仓库 ID 值
	@chvDTypeID	OUT,				--部门
	@STypeID	OUT,				--分支机构
	@numTotalMoney	OUT,				-- 单据金额合计
	@numTotalInMoney	OUT,				-- 单据实收、实付金额
	@numPreferenceMoney	OUT,
	@numNTotalMoney	OUT,
	@numNTotalInMoney	OUT,
	@numNPreferenceMoney	OUT,
	@wxTotal	OUT,	
	@numTax	OUT,
	@ifIndexWX	OUT,
	@intCostSale	OUT,
	@intCID	OUT,
	@ifCheck	OUT,				-- 是否草稿标识，f - 草稿；t - 已过账
	@IfMulAccount	OUT,
	@intVipCardID	OUT,
	@NumRate		OUT,
	@AssetBusinessTypeId OUT,
	@intRedWord			OUT,
	@intNewPosBill	OUT,
	@IfLend			OUT,
	@datPostTime	OUT
	
EXEC @nRet = Gp_CreateMx_new @BillNumberID,
							@BillType,
							@datBillDate,
							@chvATypeID,
							@chvBTypeID,
							@chvDealBTypeID,
							@chvETypeID,
							@chvKTypeID,
							@chvKTypeID2,
							@chvDTypeID,
							@STypeID,
							@ChangeMoney ,
							@ChangeMoney ,
							@numPreferenceMoney ,
							@numNPreferenceMoney ,
							@ChangeMoney ,
							@numTax ,
							@ifIndexWX ,
							@intCostSale ,
							@intCID,
							@datPostTime
					
	
					
IF @nRet <> 0
BEGIN
	RETURN @nRet
END

--处理AType_Total
EXEC @nRet = Gp_CreateManageRep @BillNumberID,@BillType	
IF @nRet <> 0
BEGIN
	RETURN @nRet
END

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_AuditingAdPriceBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_AuditingAdPriceBill]
GO
/****** Object:  StoredProcedure [dbo].[Gp_ModifyDbf]    Script Date: 11/01/2012 15:13:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
	功能说明：	成本核单过账，修改期初；修改BType对应往来余额
	作    者：	施训果
	最后修改：	2015-03-09
*/
CREATE     PROCEDURE [dbo].[Gp_AuditingAdPriceBill] 
(
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szSTypeID			varchar(50),			--分支机构
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10), 		-- 16. 批次成本单价
	@nBillID		numeric(10, 0)
)
----@encode$--
AS
SET NOCOUNT ON


-- 声明会计科目相关变量
DECLARE	@GOODS_ID				varchar(50)
SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』

-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

DECLARE	
		@szJobNumber			varchar(20),

		@dTotalTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品金额
		@dQtyTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品数量
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
		@dPricetemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@OutFactoryDate			datetime,
		@datValidDate			datetime,
		@nGoodsOrder			int


SET @dTotalTemp		= 0
SET @dCostTotalTemp	= 0

SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0

/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------
*/
DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT
		
	DECLARE @changetotal NUMERIC(24, 10)
	SELECT @changetotal=SUM(ISNULL(CostTotal,0)) FROM InOutstocktable WHERE BillNumberId=@nBillID AND BillType=57
	UPDATE dbo.BillIndex SET totalmoney=@changetotal,NTotalMoney=@changetotal WHERE BillNumberId=@nBillID AND BillType=57 AND RedWord=0
	-- 成本核算，传入的 ATypeID 参数必定为 “库存商品总值”
	IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
	BEGIN
			/*****************************************************************
				移动加权平均成本核算法
			******************************************************************/
			IF @szCostingMethod = @AVERAGE
			BEGIN
				-- （1）读取库存状况表中的对应仓库的商品数量、成本均价、成本金额
				DECLARE ModifyDbf_Cursor CURSOR FOR
					SELECT	a.Qty,
							CASE WHEN a.Qty <> 0 THEN
								ROUND(CAST(a.Total AS NUMERIC(24,10))/CAST(a.Qty AS  NUMERIC(24, 10)),@intPriceDot)
							ELSE 0
							END AS CostPrice,
							a.Total,
							a.JobNumber,
							a.OutFactoryDate,
							a.GoodsOrder
					FROM	GoodsStocks a
					INNER JOIN
					(
						SELECT TypeID
						FROM Stock
						WHERE STypeID=@szSTypeID
					) b
					ON a.KTypeID=b.TypeID
					WHERE	a.PTypeID = @szPTypeID
							AND a.KTypeID = @szKTypeID
							
				FOR UPDATE

				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,		-- 当前库存商品数量
														@dCostPriceTemp,	-- 当前库存商品成本均价
														@dCostTotalTemp,	-- 当前库存商品成本金额
														@szJobNumber,
														@OutFactoryDate,
														@nGoodsOrder
				-- 库存状况表 GoodsStocks 中有对应的商品库存记录
				IF @@FETCH_STATUS = 0
				BEGIN
					IF @dTotal < 0	-- Total 为负，代表商品降价（有可能数量小于零）
					BEGIN
						-- 当调整金额大于商品库存金额
						--IF @dCostTotalTemp < ABS(@dTotal)
						--GOTO ERROR4
						
						-- 当调整金额等于商品库存金额
						IF @dCostTotalTemp = ABS(@dTotal)
						BEGIN
							SET @dTotalTemp = @dCostTotalTemp + @dTotal
							SET @dQtyTemp = @dCostTotalTemp
						
							IF @dQtyTemp = 0 AND @dTotalTemp = 0
							BEGIN
								DELETE FROM GoodsStocks
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2
								GOTO CLEANUP
							END
							ELSE
								UPDATE	GoodsStocks
								SET		Total = ROUND(@dTotalTemp,@intMoneyDot),
										Price = ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2
								GOTO CLEANUP
						END
						-- 当调整金额小于商品库存金额
						ELSE
						BEGIN
							SET @dTotalTemp = @dCostTotalTemp + @dTotal
							SET @dQtyTemp=@dCostQtyTemp
							UPDATE	GoodsStocks
							SET		Total = ROUND(@dTotalTemp,@intMoneyDot),
									Price = CASE @dQtyTemp WHEN 0 THEN 0 ELSE ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot) END
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2
							GOTO CLEANUP
						END
					END
					ELSE	-- Total 为正，代表商品升价
					BEGIN
						SET @dTotalTemp = @dCostTotalTemp + @dTotal
						SET @dQtyTemp=@dCostQtyTemp
						UPDATE	GoodsStocks
						SET		Total	= ROUND(@dTotalTemp,@intMoneyDot),
								Price	= CASE @dQtyTemp WHEN 0 THEN 0 ELSE ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot) END
						WHERE CURRENT OF ModifyDbf_Cursor
						IF @@ROWCOUNT = 0 GOTO ERROR2
						GOTO CLEANUP
					END
				END
				-- GoodsStocks 数据表中，没有相关库存记录
				ELSE
				BEGIN
					INSERT	GoodsStocks (
							PTypeID,
							KTypeID,
							Qty,
							Total,
							Price,
							GoodsNumber,--JobNumber,
							ProduceDate,
							ValidDate,
							GoodsOrder
						)
						VALUES (
							@szPTypeID,
							@szKTypeID,
							ROUND(@dQty,@intQtyDot),
							ROUND(@dTotal,@intMoneyDot),
							ROUND(@dPriceTemp,@intPriceDot),
							@GoodsNumber,
							@ProduceDate,
							@ValidDate,
							@nGoodsOrder + 1
						)
						IF @@ROWCOUNT = 0 GOTO ERROR2
						GOTO CleanUp
				END
			END
			/*****************************************************************
				先进先出成本算法
			******************************************************************/
			--ELSE IF @szCostingMethod = @FIFO
			--BEGIN
			--	EXEC Gp_GetDbf	@GOODS_ID,
			--					@szPTypeID,
			--					'0',
			--					'0',
			--					@szKTypeID,
			--					@szSTypeID,
			--					'',
			--					'',
			--					@dQtyTemp output,
			--					@dTotalTemp output

			--	IF @dTotalTemp + @dTotal < 0
			--	BEGIN
			--		RETURN -1
			--	END
				
			--	DECLARE @adqty int
			--	SET @adqty=0
				
			--	DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
			--		SELECT	Qty,
			--		CASE WHEN Qty <> 0 THEN
			--				ROUND(CAST(Total AS  NUMERIC(24, 10))/CAST(Qty AS  NUMERIC(24, 10)),@intPriceDot)
			--			ELSE 0
			--			END AS CostPrice,
			--			Total,
			--			JobNumber,
			--			OutFactoryDate,
			--			GoodsOrder
			--		FROM	GoodsStocks
			--		WHERE	PTypeID = @szPTypeID
			--		AND KTypeID = @szKTypeID
			--		ORDER BY GoodsOrder ASC FOR UPDATE		
				
			--	OPEN ModifyDbf_Cursor
			--	FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
			--											@dCostPriceTemp,
			--											@dCostTotalTemp,
			--											@szJobNumber,
			--											@OutFactoryDate,
			--											@nGoodsOrder
														
			--	WHILE @@FETCH_STATUS = 0
			--	IF @dTotal<0
			--		BEGIN
			--			IF @dTotal+@dCostTotalTemp <= 0
			--			BEGIN
			--				SET @dTotal+=@dCostTotalTemp
			--				SET @adqty += @dCostQtyTemp
			--				DELETE FROM GoodsStocks
			--				WHERE CURRENT OF ModifyDbf_Cursor
			--				IF @@ROWCOUNT = 0 GOTO ERROR2
			--			END
			--			ELSE
			--			BEGIN
			--				SET @dTotalTemp=@dTotal+@dCostTotalTemp
			--				SET @dQtyTemp=@adqty
			--				UPDATE	GoodsStocks
			--					SET		Total	= ROUND(@dTotalTemp,@intMoneyDot),
			--							QTY		= ROUND(@dQtyTemp,@intQtyDot),
			--							Price	= ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
			--					WHERE CURRENT OF ModifyDbf_Cursor
			--					IF @@ROWCOUNT = 0 GOTO ERROR2
			--				GOTO CleanUp
			--			END
			--		END
			--	END
			--	ELSE
			--	BEGIN
			--		SET @dTotalTemp=@dTotal+@dCostTotalTemp
			--		SET @dQtyTemp=@dCostTotalTemp
			--				UPDATE	GoodsStocks
			--					SET		Total	= ROUND(@dTotalTemp,@intMoneyDot),
			--							Price	= ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
			--					WHERE CURRENT OF ModifyDbf_Cursor
			--					IF @@ROWCOUNT = 0 GOTO ERROR2
			--				GOTO CleanUp
			--	END
			--END
			--/*****************************************************************
			--	后进先出成本算法
			--******************************************************************/
			--ELSE IF @szCostingMethod = @LIFO
			--BEGIN
			--	EXEC Gp_GetDbf	@GOODS_ID,
			--					@szPTypeID,
			--					'0',
			--					'0',
			--					@szKTypeID,
			--					@szSTypeID,
			--					'',
			--					'',
			--					@dQtyTemp output,
			--					@dTotalTemp output

			--	IF @dTotalTemp + @dTotal < 0
			--	BEGIN
			--		RETURN -1
			--	END
				
			--	DECLARE @adpriceqty int
			--	SET @adpriceqty=0
				
			--	DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
			--		SELECT	Qty,
			--		CASE WHEN Qty <> 0 THEN
			--				ROUND(CAST(Total AS  NUMERIC(24, 10))/CAST(Qty AS  NUMERIC(24, 10)),@intPriceDot)
			--			ELSE 0
			--			END AS CostPrice,
			--			Total,
			--			JobNumber,
			--			OutFactoryDate,
			--			GoodsOrder
			--		FROM	GoodsStocks
			--		WHERE	PTypeID = @szPTypeID
			--		AND KTypeID = @szKTypeID
			--		ORDER BY GoodsOrder DESC FOR UPDATE		
				
			--	IF @dTotal<0
			--	BEGIN
			--		OPEN ModifyDbf_Cursor
			--		FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
			--											@dCostPriceTemp,
			--											@dCostTotalTemp,
			--											@szJobNumber,
			--											@OutFactoryDate,
			--											@nGoodsOrder
			--		WHILE @@FETCH_STATUS = 0
			--		BEGIN
			--			IF @dTotal+@dCostTotalTemp <= 0
			--			BEGIN
			--				SET @dTotal+=@dCostTotalTemp
			--				SET @adpriceqty += @dCostQtyTemp
			--				DELETE FROM GoodsStocks
			--				WHERE CURRENT OF ModifyDbf_Cursor
			--				IF @@ROWCOUNT = 0 GOTO ERROR2
			--			END
			--			ELSE
			--			BEGIN
			--				SET @dTotalTemp=@dTotal+@dCostTotalTemp
			--				SET @dQtyTemp=@adpriceqty
			--				UPDATE	GoodsStocks
			--					SET		Total	= ROUND(@dTotalTemp,@intMoneyDot),
			--							QTY		= ROUND(@dQtyTemp,@intQtyDot),
			--							Price	= ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
			--					WHERE CURRENT OF ModifyDbf_Cursor
			--					IF @@ROWCOUNT = 0 GOTO ERROR2
			--				GOTO CleanUp
			--			END
			--		END
			--	END
			--	ELSE
			--	BEGIN
			--		SET @dTotalTemp=@dTotal+@dCostTotalTemp
			--		SET @dQtyTemp=@dCostQtyTemp
			--				UPDATE	GoodsStocks
			--					SET		Total	= ROUND(@dTotalTemp,@intMoneyDot),
			--							Price	= ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
			--					WHERE CURRENT OF ModifyDbf_Cursor
			--					IF @@ROWCOUNT = 0 GOTO ERROR2
			--				GOTO CleanUp
			--	END
			--END
			/*****************************************************************
				手工指定成本算法
			******************************************************************/
			--ELSE IF @szCostingMethod = @HAND
			--BEGIN
			--	IF @dTotal < 0
			--	BEGIN
			--		DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
			--			SELECT	Qty,
			--					Price,
			--					Total,
			--					GoodsNumber,--JobNumber,
			--					ProduceDate,--OutFactoryDate,
			--					ValidDate,
			--					GoodsOrder
			--			FROM	GoodsStocks
			--			WHERE	PTypeID = @szPTypeID
			--					AND KTypeID = @szKTypeID
			--					AND GoodsNumber = @GoodsNumber
			--					AND ProduceDate = @ProduceDate
			--					AND ValidDate = @ValidDate
			--					AND ABS(Price-@GoodsCostPrice) = 0
			--			-- 如果有两个以上完全相同的批次，则先出数量大的
			--			ORDER BY Qty DESC FOR UPDATE
			--	END
			--	ELSE
			--	BEGIN
			--		DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
			--			SELECT	Qty,
			--					Price,
			--					Total,
			--					GoodsNumber,--JobNumber,
			--					ProduceDate,--OutFactoryDate,
			--					ValidDate,
			--					GoodsOrder
			--			FROM	GoodsStocks
			--			WHERE	PTypeID = @szPTypeID
			--					AND KTypeID = @szKTypeID
			--					AND GoodsNumber = @GoodsNumber
			--					AND ProduceDate = @ProduceDate
			--					AND ValidDate = @ValidDate
			--					AND Price = @dPriceTemp
			--			ORDER BY GoodsOrder DESC FOR UPDATE
			--	END

			--	OPEN ModifyDbf_Cursor
			--	FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
			--											@dCostPriceTemp,
			--											@dCostTotalTemp,
			--											@szJobNumber,
			--											@OutFactoryDate,
			--											@datValidDate,
			--											@nGoodsOrder
			--	IF @@FETCH_STATUS = 0
			--	BEGIN
			--		IF @dCostTotalTemp + @dTotal < 0
			--		BEGIN
			--			--SELECT 7
			--			GOTO ERROR1	
			--		END

			--		IF @dCostTotalTemp = ABS(@dTotal)	-- 数量相同
			--		BEGIN
			--			DELETE FROM	GoodsStocks
			--			WHERE CURRENT OF ModifyDbf_Cursor
			--			IF @@ROWCOUNT = 0 GOTO ERROR2
			--		END
			--		ELSE
			--		BEGIN
			--			SET @dCostTotalTemp = @dCostTotalTemp + @dTotal

			--			UPDATE	GoodsStocks
			--			SET		Total = ROUND(@dCostTotalTemp,@intMoneyDot)
			--			WHERE CURRENT OF ModifyDbf_Cursor
			--			IF @@ROWCOUNT = 0 GOTO ERROR2
			--		END
			--	END
			--	ELSE	-- 无该批次入库
			--	BEGIN
			--		IF @dTotal < 0 
			--		BEGIN
			--			GOTO ERROR1
			--		END
			--		ELSE
			--		BEGIN
			--			SELECT	@nGoodsOrder = ISNULL(MAX(Goodsorder),0)
			--			FROM	GoodsStocks
			--			WHERE	PTypeID = @szPTypeID
			--					AND KTypeID = @szKTypeID
						
			--			INSERT	GoodsStocks (
			--				PTypeID,
			--				KTypeID,
			--				Qty,
			--				Total,
			--				Price,
			--				GoodsNumber,--JobNumber,
			--				ProduceDate,
			--				ValidDate,
			--				GoodsOrder
			--			)
			--			VALUES (
			--				@szPTypeID,
			--				@szKTypeID,
			--				ROUND(@dQty,@intQtyDot),
			--				ROUND(@dTotal,@intMoneyDot),
			--				ROUND(@dPriceTemp,@intPriceDot),
			--				@GoodsNumber,
			--				@ProduceDate,
			--				@ValidDate,
			--				@nGoodsOrder + 1
			--			)
			--			IF @@ROWCOUNT = 0 GOTO ERROR2
			--			GOTO CleanUp
			--		END
			--	END
			--END
			-- 成本核算法到此结束
	END
	
	CLEANUP:
		-- 返回成功值并退出
		-- 释放游标
		DEALLOCATE ModifyDbf_Cursor
		-- commit tran --ModifyDbf

		RETURN 0

	ERROR1:
		DEALLOCATE ModifyDbf_Cursor
		RETURN -1

	ERROR2:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -2

	ERROR3:
		RETURN 0


	ERROR4:
		-- rollback tran --ModifyDbf
		DEALLOCATE ModifyDbf_Cursor
		RETURN -4

	ERRORINPUTCOSTPRICE:
		-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
		DEALLOCATE ModifyDbf_Cursor
		RETURN -5

	ERRORINIMODIFYDENY:
		-- 系统已正式开账，不能修改期初
		RETURN -6

	SUCCESS:
		-- 执行成功
		-- commit tran --ModifyDbf
		RETURN 0

GO




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





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





/*
	功能说明：	单据过账，检测 现金/银行 账户的余额经过扣减后，是否为负
				与系统配置相对应
	返回结果：
	作    者：卢春
	创建时间：2004-12-22
	修改历史：
*/
CREATE     PROCEDURE GP_AuditingATypeBalanceCheck
(
	@intBillNumberID	int,					-- 1. 单据编号 ID
	@intBilltype		INT,
	@chvATypeIDoutput	varchar(50) output		-- 2. 商品 ID
)

AS



DECLARE	@chrIfATypeBalanceCheck		char(1),
		@chvATypeID					varchar(50),
		@numTotal					 NUMERIC(24, 10) ,
		@numATypeBalance			 NUMERIC(24, 10) ,
		@chvSTypeID					VARCHAR(50),
		@chvBTypeID					VARCHAR(50),
		@chvTempBTypeID				VARCHAR(50),
		@YS							VARCHAR(50),
		@YF							VARCHAR(50),
		@VIP						VARCHAR(50),
		@CID						INT,
		@ChargeOffBtypeid			VARCHAR(50),
		@ChargeType					INT

SET @chrIfATypeBalanceCheck = '0'

SELECT @YS=NID FROM dbo.Ac_Items WHERE UserCode='2131'
SELECT @YF=NID FROM dbo.Ac_Items WHERE UserCode='1151'
--SELECT @VIP=NID FROM dbo.Ac_Items WHERE UserCode='2181'

CREATE TABLE #account(nid   BIGINT)



SELECT	TOP 1
		@chrIfATypeBalanceCheck = Value
FROM	UserConfig
WHERE	ConfigName = 'ATypeBalanceCheck'

IF @chrIfATypeBalanceCheck <> '1' 
BEGIN
	INSERT #account
	SELECT @YS
	UNION ALL
	SELECT @YF
END
ELSE
BEGIN
	INSERT #account
	SELECT nId FROM dbo.Ac_Items WHERE TypeName='B'
	UNION ALL
	SELECT @YS
	UNION ALL
	SELECT @YF
END

SET @numATypeBalance = 0

DECLARE
	--@intBillType	INT,
	@intRedword     INT,
	@SysCID			INT

--优惠券4张单据
IF @intBilltype IN (423,424,425,426)
BEGIN	
	SELECT	@chvSTypeID=STypeID,
			@chvBTypeID=BTypeID,
			@intRedword=RedWord,
			@CID=CID,
			@ChargeOffBtypeid='',
			@ChargeType=-1
	FROM	dbo.Coupon_BillIndex
	WHERE	BillNumberId=@intBillNumberID
END
ELSE IF @intBilltype IN (327,328,329)
BEGIN
	SELECT	@chvSTypeID=STypeID,
			@chvBTypeID='',
			@intRedword=RedWord,
			@CID=1,
			@ChargeOffBtypeid='',
			@ChargeType=-1
	FROM	dbo.PosAllotApplyBillIndex
	WHERE	BillNumberId=@intBillNumberID
END
ELSE
BEGIN	
	SELECT	@chvSTypeID=STypeID,
			@chvBTypeID=BTypeID,
			@intRedword=RedWord,
			@CID=CID,
			@ChargeOffBtypeid=ChargeOffBtypeid,
			@ChargeType=ChargeOffType
	FROM	BillIndex
	WHERE	BillNumberId=@intBillNumberID
END

--prepaycashisnegative是否允许预付资金为负数，1 允许 0不允许
--precollectcashisnegative是否允许预收资金为负数，1 允许 0不允许

DECLARE
	@intprepaycashisnegative INT,
	@intprecollectcashisnegative INT
	
SELECT 
	@intprepaycashisnegative=0,
	@intprecollectcashisnegative=0
	
SELECT @intprepaycashisnegative=Value
FROM Userconfig
WHERE ConfigName='prepaycashisnegative'
	
SELECT @intprecollectcashisnegative=Value
FROM Userconfig
WHERE ConfigName='precollectcashisnegative'	


SELECT @SysCID=CId FROM Ac_Currency WHERE Sysrow = 1

DECLARE
	@intNeedCheck	TINYINT  --0表示需要，1表示不需要
	
--SELECT * FROM dbo.ListTable

--SELECT * FROM #account

	--SELECT	L.ATypeID,
	--		L.Cid,
	--		SUM(L.nTotal) AS Total
	--FROM	ListTable  L
	--INNER JOIN #account A ON L.AtypeId = A.nid		
	--WHERE	L.BillNumberID = @intBillNumberID 
	--		GROUP BY L.ATypeID,L.Cid


DECLARE ATypeBalanceCheck_Cursor CURSOR FAST_FORWARD FOR
	SELECT	L.ATypeID,
			L.Cid,
			SUM(L.nTotal) AS Total
	FROM	ListTable  L
	INNER JOIN #account A ON L.AtypeId = A.nid		
	WHERE	L.BillNumberID = @intBillNumberID 
	AND    L.BillType=@intBillType
			GROUP BY L.ATypeID,L.Cid

OPEN ATypeBalanceCheck_Cursor
FETCH NEXT FROM ATypeBalanceCheck_Cursor INTO	@chvATypeID,
												@CID,
												@numTotal
WHILE @@FETCH_STATUS = 0
BEGIN	
	SELECT @intNeedCheck=0	--默认需要校验
	
	IF @chvBTypeID='' 
	BEGIN
		SET @chvBTypeID=@chvTempBTypeID
	END
	
	SELECT @numATypeBalance=0

	SELECT	@numATypeBalance = nTotal  FROM	AType_Total  WHERE	ATypeID = @chvATypeID AND STypeID=@chvSTypeID AND CID=@CID

	SELECT @numATypeBalance=ISNULL(@numATypeBalance,0)

	IF @chvATypeID=@YS AND @intprecollectcashisnegative=1
	BEGIN
		--允许为负，则不需要校验
		SELECT @intNeedCheck=1
	END

	IF @chvATypeID=@YF AND @intprepaycashisnegative=1
	BEGIN
		--允许为负，则不需要校验
		SELECT @intNeedCheck=1
	END

	
	IF (( @numATypeBalance + @numTotal ) < 0) AND @intNeedCheck=0
	BEGIN
		CLOSE ATypeBalanceCheck_Cursor
		DEALLOCATE ATypeBalanceCheck_Cursor

		SET @chvATypeIDoutput = @chvATypeID
		RETURN 918
	END
	FETCH NEXT FROM ATypeBalanceCheck_Cursor INTO	@chvATypeID,
													@CID,
													@numTotal
													
END

CLOSE ATypeBalanceCheck_Cursor
DEALLOCATE ATypeBalanceCheck_Cursor


--预收预付单独判断
DECLARE ATypeBalanceCheck_Cursor CURSOR FAST_FORWARD FOR
	SELECT	L.ATypeID,L.BTypeID,L.Cid,
			SUM(L.nTotal) AS Total
	FROM	ListTable  L
	INNER JOIN #account A ON L.AtypeId = A.nid		
	WHERE	L.BillNumberID = @intBillNumberID  AND l.atypeid in (@YS,@YF)
		AND BILLTYPE=@intBillType
			GROUP BY L.ATypeID,L.BTypeID,l.cid

OPEN ATypeBalanceCheck_Cursor
FETCH NEXT FROM ATypeBalanceCheck_Cursor INTO	@chvATypeID,
												@chvTempBTypeID,
												@CID,
												@numTotal
												

WHILE @@FETCH_STATUS = 0
BEGIN	
	SELECT @intNeedCheck=0	--默认需要校验

	IF @chvBTypeID='' OR  (@intBillType=159 AND @chvATypeID IN (@YS,@YF)) 
		SET @chvBTypeID=@chvTempBTypeID
	
	SELECT @numATypeBalance=0
	
	IF @chvATypeID=@YS AND @intprecollectcashisnegative=1
	BEGIN
		--允许为负，则不需要校验
		SELECT @intNeedCheck=1
	END

	IF @chvATypeID=@YF AND @intprepaycashisnegative=1
	BEGIN
		--允许为负，则不需要校验
		SELECT @intNeedCheck=1
	END
	
	IF @intNeedCheck=0
	BEGIN
		--进入校验流程
		IF @chvATypeID=@YS
		BEGIN
			IF @intBillType=450 AND @ChargeType IN (1,4) --往来核销单（1：预收冲预付，4：预收转应付）往来单位为ChargeOffBtypeid
				SET @chvBTypeID=@ChargeOffBtypeid
			SELECT	@numATypeBalance = ISNULL(nYSTotal,0)
			FROM	BType_ARAPTotal
			WHERE	BTypeID = @chvBTypeID AND STypeID=@chvSTypeID AND CID=@CID
		END
		ELSE IF @chvATypeID=@YF
		BEGIN
			IF @intBillType=450 AND @ChargeType IN (5) --往来核销单（5：预付转应收）往来单位为ChargeOffBtypeid
				SET @chvBTypeID=@ChargeOffBtypeid
			SELECT	@numATypeBalance = ISNULL(nYFTotal,0)
			FROM	BType_ARAPTotal
			WHERE	BTypeID = @chvBTypeID AND STypeID=@chvSTypeID  AND CID=@CID
		END
	
		
		IF @intBillType IN (189,190) AND @intRedword=0
		BEGIN
			IF ( @numATypeBalance + @numTotal ) < 0
			BEGIN
				CLOSE ATypeBalanceCheck_Cursor
				DEALLOCATE ATypeBalanceCheck_Cursor

				SET @chvATypeIDoutput = @chvATypeID	
				RETURN 918
			END
		END
		ELSE
		BEGIN
			IF ( @numATypeBalance + @numTotal ) < 0
			BEGIN
				CLOSE ATypeBalanceCheck_Cursor
				DEALLOCATE ATypeBalanceCheck_Cursor

				SET @chvATypeIDoutput = @chvATypeID
			
				RETURN 918
			END
		END
	END
	
	FETCH NEXT FROM ATypeBalanceCheck_Cursor INTO	@chvATypeID,
													@chvTempBTypeID,
													@CID,
													@numTotal
																						
END
CLOSE ATypeBalanceCheck_Cursor
DEALLOCATE ATypeBalanceCheck_Cursor

 --启用品牌 
	 
 IF	 EXISTS(SELECT  TOP 1 1 FROM sysdata  WHERE subname='usebrandartype' AND SubValue ='1') 
 AND EXISTS (
			 SELECT TOP 1 1 FROM  dbo.Brandar_ArApTotal 
			 WHERE BtypeID=@chvBTypeID
			 AND StypeID=@chvSTypeID
			 AND ISNULL(YSTotal,0)<0 )  AND  @intprecollectcashisnegative=0
BEGIN
	SET @chvATypeIDoutput = @YS
	RETURN 918

END 				
RETURN 0
--





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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





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





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




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：单据过账后，数据检测
	返回结果：
	作    者：卢春
	创建时间：2004-12-10
	修改历史：
*/
CREATE          PROCEDURE GP_AuditingCheck
(
	@intBillNumberID	int,
	@BillType			INT
)
--@encode$--
AS

DECLARE	@chrVersion					char(1),		-- 软件版本 1 - 基础；2 - 通讯；5 - 电脑
		@chrMngSerial				char(1),		-- 序列号管理模式 1 - 强制；0 - 非强制
		@chvBillCode				varchar(200),	-- 单据编号 #&**&#
		@chvBillDate				varchar(30),	-- 单据日期
		@intBillType				int,			-- 单据类型
		@chvPTypeID					varchar(50),	-- 商品 ID 值
		@chvBTypeID					varchar(50),	-- 往来 ID 值
		@chvETypeID					varchar(50),	-- 职员 ID 值
		@chvKTypeID					varchar(50),	-- 仓库 ID 值
		@chvATypeID					varchar(50),	-- 科目 ID 值
		@chrIfCheck					char(1),		-- 是否已过账
		@chvChecke					varchar(50),	-- 制单人 ID 值
		@numTotalMoney_BillIndex	 NUMERIC(24, 10) ,	-- 单据金额
		@numTotalInMoney_BillIndex	 NUMERIC(24, 10) ,	-- 单据实收/付金额
		@numTotalQty_BillIndex		 NUMERIC(24, 10) ,	-- 单据数量
		@intRowCount_BillIndex		int,			-- BillIndex 行数
		@intRowCount_InOut			int,			-- InOutStockTable 行数
		@intRowCount_Detail			int,			-- 明细表行数
		@intRedWord					int,			-- 单据红字标识
		@chrDraft					char(1),		-- 草稿标识
		@numTotalQty_Detail			 NUMERIC(24, 10) ,	-- 明细数量合计
		@numTotalMoney_Detail		 NUMERIC(24, 10) ,	-- 明细金额合计
		@numTotalQty_InOut			 NUMERIC(24, 10) ,	-- 出入库数量合计
		@numTotalMoney_InOut		 NUMERIC(24, 10) ,	-- 出入库金额合计
		@numSerialQty_Detail		int,			-- 明细序列号的总数
		@numTotalQty_Detail_SerialPType  NUMERIC(24, 10) 

-- (1) 读取软件版本；1 - 基础；2 - 通讯；5 - 电脑；6 - 食品；7 - 管家婆电脑行业版
SELECT	TOP 1 @chrVersion = SubValue
FROM	SysData
WHERE	SubName = 'Edition'

IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN 818

-- (2) 读取序列号管理模式
IF @chrVersion = '2' OR @chrVersion = '5' OR @chrVersion = '7'
BEGIN
	SELECT	TOP 1 @chrMngSerial = Value
	FROM	UserConfig
	WHERE	ConfigName = 'mngSerial'

	IF @@ROWCOUNT = 0 SET @chrMngSerial = '1'
	IF @@ERROR <> 0 RETURN 818
END

-- (3) 查 BillIndex 相关数据
IF @BillType IN (404,405)
BEGIN
	SELECT	TOP 1 @chvBillCode = BillCode,
		@chvBillDate = BillDate,
		@intBillType = BillType,
		@chrIfCheck = IfCheck,
		@chvChecke = Checke,
		@intRedWord = RedWord,
		@chrDraft = Draft,
		@numTotalQty_BillIndex = ISNULL(TotalQty,0),
		@numTotalMoney_BillIndex = ISNULL(TotalMoney,0)
	FROM	ReceiptBillIndex
	WHERE	BillNumberID = @intBillNumberID
		AND BillCode <> ''
		AND ( BillDate <> '' AND BillDate IS NOT NULL )
END
ELSE
BEGIN
	SELECT	TOP 1 @chvBillCode = BillCode,
			@chvBillDate = BillDate,
			@intBillType = BillType,
			@chrIfCheck = IfCheck,
			@chvChecke = Checke,
			@intRedWord = RedWord,
			@chrDraft = Draft,
			@numTotalQty_BillIndex = ISNULL(TotalQty,0),
			@numTotalMoney_BillIndex = ISNULL(TotalMoney,0),
			@numTotalInMoney_BillIndex = ISNULL(TotalInMoney,0)
	FROM	BillIndex
	WHERE	BillNumberID = @intBillNumberID
			AND BillCode <> ''
			AND ( BillDate <> '' AND BillDate IS NOT NULL )
END

IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN 818
IF @intBillType <> 17 RETURN 0
IF @chrIfCheck <> 't' AND @intRedWord <> 0 AND @chrDraft <> '0' RETURN 0

-- (4) 查 InOutStockTable 相关数据
IF @intBillType = 17	-- 同价调拨单
BEGIN
	SELECT	@numTotalQty_InOut = ISNULL(SUM(Qty),0),
			@numTotalMoney_InOut = ISNULL(SUM(Total),0)
	FROM	InOutStockTable
	WHERE	BillNumberID = @intBillNumberID
			AND Qty > 0
END
ELSE
BEGIN
	SELECT	@numTotalQty_InOut = ISNULL(SUM(Qty),0),
			@numTotalMoney_InOut = ISNULL(SUM(Total),0)
	FROM	InOutStockTable
	WHERE	BillNumberID = @intBillNumberID
END
IF @@ERROR <> 0 RETURN 818

-- (5) 查 ListTable 相关数据

-- (6) 查相关明细表的数据
DECLARE @chvDetailDataTable varchar(100), @strSQL varchar(500)
IF @intBillType = 17
BEGIN
	SELECT	@numTotalQty_Detail = ISNULL(SUM(Qty),0)
	FROM	MoveBill
	WHERE	BillNumberID = @intBillNumberID

	IF @@ERROR <> 0 RETURN 818

	IF @chrMngSerial = '1'
	BEGIN
		SELECT	a.*
		FROM	MoveBill a,
				PType b
		WHERE	a.BillNumberID = @intBillNumberID
				AND a.PTypeID = b.TypeID
				AND ( ( b.IfSerial = 1 AND a.Serial LIKE '' )
					OR ( b.Unit2 = '' AND a.IsUnit2 = 1 ) )
	
		IF @@ROWCOUNT <> 0 OR @@ERROR <> 0 RETURN 818

		SELECT	@numTotalQty_Detail_SerialPType = ISNULL(SUM(Qty),0)
		FROM	MoveBill a,
				PType b
		WHERE	BillNumberID = @intBillNumberID
				AND a.PTypeID = b.TypeID
				AND b.IfSerial = 1

		SELECT	@numSerialQty_Detail = COUNT(*)
		FROM	GP_InOutPTypeSerial
		WHERE	BillNumberID = @intBillNumberID
				AND BillType = @intBillType

		SET @numSerialQty_Detail  = @numSerialQty_Detail/2

		IF @numTotalQty_Detail_SerialPType <> @numSerialQty_Detail RETURN 818
	END
END

-- 比较数值
IF @numTotalQty_BillIndex = 0 OR @numTotalQty_InOut = 0 OR @numTotalQty_Detail = 0
	RETURN 818

IF ( @numTotalQty_BillIndex <> @numTotalQty_InOut ) OR
	( @numTotalQty_BillIndex <> @numTotalQty_Detail ) OR
	( @numTotalQty_InOut <> @numTotalQty_Detail )
	RETURN 818

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





/*
	单据索引、明细事前、事后校验
*/
CREATE                         PROCEDURE GP_AuditingCheckBillData (
	@intBillNumberID	numeric(10,0),
	@Billtype			INT,
	@chrOperateStep		char(1)			-- 0：事前校验；1：事后校验
)
--@encode$--
AS
---
IF @Billtype IN (404,405)
BEGIN
	IF EXISTS(
		SELECT	TOP 1 1
		FROM	ReceiptBillIndex
		WHERE	Draft = 0
				AND IfCheck = 't'
				AND BillNumberID = @intBillNumberID
	) AND @chrOperateStep = '0'
		RETURN 818
		
	IF NOT EXISTS(
	SELECT	TOP 1 1
	FROM	ReceiptBillIndex
	WHERE	BillNumberID = @intBillNumberID
)
	RETURN 818
END
ELSE IF @Billtype IN (423,424,425,426,428,429)
BEGIN
	IF EXISTS(
		SELECT	TOP 1 1
		FROM	dbo.Coupon_BillIndex
		WHERE	Draft = 0
				AND IfCheck = 1
				AND BillNumberID = @intBillNumberID
	) AND @chrOperateStep = '0'
		RETURN 818
		
	IF NOT EXISTS(
	SELECT	TOP 1 1
	FROM	Coupon_BillIndex
	WHERE	BillNumberID = @intBillNumberID
)
	RETURN 818

END 
ELSE IF @Billtype IN (327,328,329)
BEGIN
	IF EXISTS(SELECT 1 FROM	dbo.PosAllotApplyBillIndex
		WHERE	Draft = 0 AND IfCheck = 't' AND BillNumberID = @intBillNumberID ) AND @chrOperateStep = '0'
		RETURN 818
		
	IF NOT EXISTS(
	SELECT	TOP 1 1
	FROM	PosAllotApplyBillIndex
	WHERE	BillNumberID = @intBillNumberID
)
	RETURN 818
END
ELSE
BEGIN
	IF EXISTS(
		SELECT	TOP 1 1
		FROM	BillIndex
		WHERE	Draft = 0
				AND IfCheck = 't'
				AND BillNumberID = @intBillNumberID
	) AND @chrOperateStep = '0'
		RETURN 818
		
	IF NOT EXISTS(
	SELECT	TOP 1 1
	FROM	BillIndex
	WHERE	BillNumberID = @intBillNumberID
)
	RETURN 818
END
---


DECLARE @intBillType int,@numTotalQty  NUMERIC(24, 10) ,@numTotalMoney  NUMERIC(24, 10) 

IF @Billtype IN (404,405)
BEGIN
	SELECT	TOP 1 @intBillType = BillType,
			@numTotalQty = ISNULL(TotalQty,0),
			@numTotalMoney = ISNULL(TotalMoney,0)
	FROM	ReceiptBillIndex
	WHERE	BillNumberID = @intBillNumberID
END
ELSE IF @billtype  IN (423,424,425,426)
BEGIN
	SELECT	TOP 1 @intBillType = BillType,
			@numTotalQty = ISNULL(TotalQty,0),
			@numTotalMoney = ISNULL(TotalMoney,0)
	FROM	dbo.Coupon_BillIndex
	WHERE	BillNumberID = @intBillNumberID
END
ELSE IF @billtype IN(327,328,329)--门店配送类单据
BEGIN
	SELECT	TOP 1 @intBillType = BillType,
			@numTotalQty = ISNULL(Qty,0),
			@numTotalMoney = Total
	FROM	dbo.PosAllotApplyBillIndex
	WHERE	BillNumberID = @intBillNumberID
END
ELSE
BEGIN
	SELECT	TOP 1 @intBillType = BillType,
		@numTotalQty = ISNULL(TotalQty,0),
		@numTotalMoney = ISNULL(TotalMoney,0)
FROM	BillIndex
WHERE	BillNumberID = @intBillNumberID
END



DECLARE @chvBillName varchar(50),@chvQtyName varchar(100),@chvTotalName varchar(100)


-- 判断 BillIndex 中的 TotalQty,TotalMoney 两个值是否为零，为零就退出
IF @numTotalQty = 0 AND @intBillType IN (11,45,305,34,6,140,141,142,143,144,145,146,147,17,9,14,139,126,21,215,400,401,402,403,328,327,329)--,404,405)
BEGIN
	RETURN 818
END
------------------------------------------判断往来核销单被核销单据未结算金额是否大于本次核销金额 start------------------------------------------------------
IF @intBillType=450 AND @chrOperateStep=0
BEGIN
	DECLARE @count INT 
	SELECT @count=COUNT(1) FROM (
	SELECT c.BillNumberId FROM dbo.BillIndex b INNER JOIN dbo.ChargeOffBill c ON c.FromBillNumberid=b.BillNumberId WHERE ABS(ISNULL(b.Ntotalmoney,0)-ISNULL(b.NCompleteTotal,0)-ISNULL(b.NChargeOffTotal,0)-ISNULL(b.Ntotalinmoney,0)-ISNULL(b.Npreferencemoney,0))<ABS(c.NChargeOffValue) AND c.FromBillType NOT IN ('404','405','116','115','128','129','423','424','425','426') AND c.BillNumberId=@intBillNumberID --主表为BillIndex
	UNION ALL 
	SELECT c.BillNumberId FROM dbo.AdDebtBill b INNER JOIN dbo.ChargeOffBill c ON c.FromBillNumberid=b.BillNumberId AND c.FromBillID=b.ID WHERE ABS(ISNULL(b.Ntotal,0)-ISNULL(b.nCompleteTotal,0)-ISNULL(b.nChargeOffTotal,0))<ABS(c.nChargeOffValue) AND c.FromBillType  IN ('116','115','128','129') AND c.BillNumberId=@intBillNumberID --应收应付款单比较特殊核销的粒度为应收应付明细
	UNION ALL 
	SELECT c.BillNumberId FROM dbo.ReceiptBillIndex b INNER JOIN dbo.ChargeOffBill c ON c.FromBillNumberid=b.BillNumberId WHERE ABS(ISNULL(b.taxtotalmoney,0)-ISNULL(b.nCompleteTotal,0)-ISNULL(b.nChargeOffTotal,0))<abs(c.nChargeOffValue) AND c.FromBillType  IN ('404','405') AND c.BillNumberId=@intBillNumberID -- 主表为ReceiptBillIndex
	UNION ALL 
	SELECT c.BillNumberId FROM dbo.Coupon_BillIndex b INNER JOIN dbo.ChargeOffBill c ON c.FromBillNumberid=b.BillNumberId WHERE ABS(ISNULL(b.Ntotalmoney,0)-ISNULL(b.NCompleteTotal,0)-ISNULL(b.NChargeOffTotal,0)-ISNULL(b.Ntotalinmoney,0))<ABS(c.NChargeOffValue) AND c.FromBillType IN ('423','424','425','426') AND c.BillNumberId=@intBillNumberID --Coupon_BillIndex
	) AS checkChargeOffBill
	IF @count>0
		RETURN -802
END
------------------------------------------判断往来核销单被核销单据未结算金额是否大于本次核销金额 end--------------------------------------------------------


-- 判断 BillIndex 与明细单据的数据或金额是否一致
IF @intBillType IN (11,45,305,34,6,140,141,142,143,144,145,146,147,215,400,401,402,403)--,404,405)
BEGIN
	SET @chvBillName =
		CASE WHEN @intBillType = 11	THEN 'SaleBill'			-- 销售出库单
			WHEN @intBillType = 45	THEN 'SaleBackBill'		-- 销售退货单
			WHEN @intBillType = 305	THEN 'RetailBill'		-- 零售单
			WHEN @intBillType = 34	THEN 'BuyBill'			-- 采购入库单
			WHEN @intBillType = 6	THEN 'BuyBackBill'		-- 采购退货单
			WHEN @intBillType =215	THEN 'RetailBackBill'   --零售退货单
			WHEN @intBillType IN (140,141,142,143,144,145,146,147)
									THEN 'CommissionBill'	-- 委托、受托代销类单据
			WHEN @intBillType IN (404,405) THEN 'ReceiptBill'
			WHEN @intBillType=400 THEN 'AppraisalBill'
			WHEN @intBillType=401 THEN 'AppraisalBackBill'
			WHEN @intBillType=402 THEN 'SendBill'
			WHEN @intBillType=403 THEN 'SendBackBill'
		END
		
	SET @chvQtyName = 'Qty'
	SET @chvTotalName = 'TaxTotal'
END
ELSE IF @intBillType IN (17,139,126)
BEGIN
	SET @chvBillName =
		CASE WHEN @intBillType = 17	THEN 'MoveBill'			-- 同价调拨单
			WHEN @intBillType = 139	THEN 'GiveBill'			-- 赠送单
			WHEN @intBillType = 126	THEN 'GiveMeBill'		-- 获赠单
			END
	SET @chvQtyName = 'Qty'
	SET @chvTotalName = '0'
END
ELSE IF @intBillType IN (21,9,14)
BEGIN
	SET @chvBillName =
		CASE WHEN @intBillType = 21	THEN 'MoveBjBill'	-- 变价调拨单
			--WHEN @intBillType = 57	THEN 'AdPriceBill'	-- 成本调价单(需要回填整单调整金额不做数据完整性校验)
			WHEN @intBillType = 9	THEN 'LoseBill'			-- 报损单
			WHEN @intBillType = 14	THEN 'OverFlowBill'		-- 报溢单
			
		END
	SET @chvQtyName = 'Qty'
	SET @chvTotalName = 'Total'
END
ELSE IF @intBillType IN (4,66)
BEGIN
	SET @chvBillName =
		CASE WHEN @intBillType = 4	THEN 'GatheringBill'	-- 收款单
			WHEN @intBillType = 66	THEN 'PayBill'			-- 付款单
			END
	SET @chvQtyName = '0'
	SET @chvTotalName = 'Total'
END
ELSE IF @intBillType IN (423,424,425,426)
BEGIN
	SET @chvBillName =
		CASE WHEN @intBillType = 423	THEN 'Coupon_InBill'	-- 优惠券入库
			WHEN @intBillType = 424	THEN 'Coupon_OutBill'			-- 优惠券出库
			WHEN @intBillType = 425	THEN 'Coupon_AllotBill'			-- 优惠券调拨
			WHEN @intBillType = 426	THEN 'Coupon_BackBill'			-- 优惠券退货
			END
	SET @chvQtyName = 'Qty'
	
	SET @chvTotalName = 	CASE WHEN @intBillType = 423	THEN 'costtotal'	-- 优惠券入库
							WHEN @intBillType = 424	THEN 'total'			-- 优惠券出库
							WHEN @intBillType = 425	THEN '0'			-- 优惠券调拨
							WHEN @intBillType = 426	THEN 'total'			-- 优惠券退货
							end
END 
ELSE IF @intBillType IN (327,328,329)--门店配送类单据
BEGIN
	SET @chvBillName =
	CASE WHEN @intBillType = 327	THEN 'DeliveryBill'			-- 门店配送单
		 WHEN @intBillType = 328	THEN 'DeliveryBackBill'		-- 门店配送退货单
		 WHEN @intBillType = 329	THEN 'DeliveryCheckBill'	-- 门店验收单
	END
	SET @chvQtyName = 'Qty'	
	SET @chvTotalName = 'Total'	
END
ELSE
BEGIN
	RETURN
END


DECLARE @chvSQL Nvarchar(1000)

DECLARE @intDiff INT

IF @intBillType  IN (423,424,425,426)
BEGIN 
	SET @chvSQL = '
		IF EXISTS(
		SELECT	a.BillNumberID
		FROM	Coupon_BillIndex a
		INNER JOIN (
			SELECT	ISNULL(SUM(' + @chvQtyName + '),0) AS Qty,
					ISNULL(SUM(' + @chvTotalName + '),0) AS Total
			FROM	' + @chvBillName + '
			WHERE	BillNumberID = ' + CAST(@intBillNumberID AS varchar(100)) + '
		) b
		ON ISNULL(a.TotalQty,0) = b.Qty AND ((ISNULL(a.TotalMoney,0) = b.Total AND a.BillType<>425) OR  a.BillType=425)
		WHERE a.BillNumberID = ' + CAST(@intBillNumberID AS varchar(100))+'
		)
			SELECT @intDiff=1
		ELSE 
			SELECT @intDiff=0
		'
END 
ELSE IF  @intBillType  IN (327,328,329)
BEGIN
	SET @chvSQL = '
		IF EXISTS(
		SELECT	a.BillNumberID
		FROM	PosAllotApplyBillIndex a
		INNER JOIN (
			SELECT	ISNULL(SUM(' + @chvQtyName + '),0) AS Qty,
					ISNULL(SUM(' + @chvTotalName + '),0) AS Total
			FROM	' + @chvBillName + '
			WHERE	BillNumberID = ' + CAST(@intBillNumberID AS varchar(100)) + '
		) b
		ON ISNULL(a.Qty,0) = b.Qty WHERE a.BillNumberID = ' + CAST(@intBillNumberID AS varchar(100))+')
			SELECT @intDiff=1
		ELSE 
			SELECT @intDiff=0
		'
END
ELSE 
BEGIN 
	SET @chvSQL = '
		IF EXISTS(
		SELECT	a.BillNumberID
		FROM	BillIndex a
		INNER JOIN (
			SELECT	ISNULL(SUM(' + @chvQtyName + '),0) AS Qty,
					ISNULL(SUM(' + @chvTotalName + '),0) AS Total
			FROM	' + @chvBillName + '
			WHERE	BillNumberID = ' + CAST(@intBillNumberID AS varchar(100)) + '
		) b
		ON ISNULL(a.TotalQty,0) = b.Qty AND ((ISNULL(a.TotalMoney,0) = b.Total AND a.BillType<>17) OR  a.BillType=17)
		WHERE a.BillNumberID = ' + CAST(@intBillNumberID AS varchar(100))+'
		)
			SELECT @intDiff=1
		ELSE 
			SELECT @intDiff=0
		'
END 

--END

--PRINT (@chvSql)
EXECUTE sp_executesql @chvSQL,N'@intDiff INT OUTPUT',@intDiff OUTPUT

IF @intDiff<>1 RETURN 818


/*
--借贷不平的调试
SELECT b.fullname,a.total,a.ntotal
FROM dbo.ListTable a
INNER JOIN dbo.Ac_Items b
ON a.AtypeId=b.nId
WHERE a.BillNumberId=@intBillNumberID AND BillType=@intBillType

SELECT	a.BillNumberID,
						b.UserCode,
						b.FullName,
						CASE WHEN b.TypeName IN ('C','F','B','E')
							THEN ISNULL(a.Total,0) ELSE 0 END AS J_Total,
						CASE WHEN b.TypeName IN ('L','G')
							THEN ISNULL(a.Total,0) ELSE 0 END AS D_Total			
				FROM	ListTable a,
						Ac_Items b
				WHERE	a.Audited = '1'
						AND a.ATypeID = b.NID
						AND a.BillNumberID = @intBillNumberID
						AND a.BillType=@intBillType

SELECT	d.BillNumberID,d.J_Total,d.D_Total
		FROM (
			SELECT	c.BillNumberID,
					ISNULL(SUM(c.J_Total),0) AS J_Total,
					ISNULL(SUM(c.D_Total),0) AS D_Total
			FROM (
				
			
			
				SELECT	a.BillNumberID,
						b.UserCode,
						b.FullName,
						CASE WHEN b.TypeName IN ('C','F','B','E')
							THEN ISNULL(a.Total,0) ELSE 0 END AS J_Total,
						CASE WHEN b.TypeName IN ('L','G')
							THEN ISNULL(a.Total,0) ELSE 0 END AS D_Total			
				FROM	ListTable a,
						Ac_Items b
				WHERE	a.Audited = '1'
						AND a.ATypeID = b.NID
						AND a.BillNumberID = @intBillNumberID
						AND a.BillType=@intBillType
			
				
				
			) c
			GROUP BY c.BillNumberID
		) d
		WHERE	d.J_Total <> d.D_Total
*/

-- 判断凭证数据是否借贷平衡
IF @chrOperateStep = '1' AND @intBillType IN (11,45,305,34,6,9,14,139,126,21,57,4,66,140,141,142,144,146,159,160,161,215,84,85,68,212,213,214,400,401,402,403,404,405,158,423,424,426,427,328,327,329)
BEGIN
	IF EXISTS(
		SELECT	TOP 1 1
		FROM	ListTable
		WHERE	BillNumberID = @intBillNumberID
				AND BillType=@intBillType
				AND (Total = 0 AND Ntotal=0)
	)
		RETURN 818

	IF EXISTS(
		SELECT	d.BillNumberID
		FROM (
			SELECT	c.BillNumberID,
					ISNULL(SUM(c.J_Total),0) AS J_Total,
					ISNULL(SUM(c.D_Total),0) AS D_Total
			FROM (
				
			
			
				SELECT	a.BillNumberID,
						b.UserCode,
						b.FullName,
						CASE WHEN b.TypeName IN ('C','F','B','E')
							THEN ISNULL(a.Total,0) ELSE 0 END AS J_Total,
						CASE WHEN b.TypeName IN ('L','G','D')
							THEN ISNULL(a.Total,0) ELSE 0 END AS D_Total			
				FROM	ListTable a,
						Ac_Items b
				WHERE	a.Audited = '1'
						AND a.ATypeID = b.NID
						AND a.BillNumberID = @intBillNumberID
						AND a.BillType=@intBillType
			
				
				
			) c
			GROUP BY c.BillNumberID
		) d
		WHERE	d.J_Total <> d.D_Total
	)
		RETURN 818
	ELSE RETURN 0
END
ELSE RETURN 0






GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



/*
	作者：舒珊
	时间：2017-01-12
	内容:分支机构调拨出库单,同价调拨单,变价调拨单 过账回写申请单状态 billover 字段,   
	991新增回写门店要货申请单状态
	
*/
CREATE      PROCEDURE GP_AuditingCheckMoveBillState (
	@intBillNumberID	numeric(10,0),
	@billtype			INT
)
--@encode$--
AS

--当前调拨单所调用的申请单
create table #PosAllotApplyBill
(
	billnumberid int, --主表id	
	allotid	int		--明细id
)

--当前门店配送单所调用的申请单
create table #DeliveryApplyBill
(
	billnumberid int, --主表id	
	DeliveryApplyid	int		--明细id
)
--当前门店退货单调用的门店配送单
create table #DeliveryBackBill
(
	billnumberid int, --主表id	
	Deliveryid	int		--明细id
)

--当前门店验收单调用的门店配送单
create table #DeliveryBill
(
	billnumberid int, --主表id	
	Deliveryid	int		--明细id
)


IF @billtype=17
BEGIN
	UPDATE dbo.PosAllotApplyBill SET CallQty += M.qty 
	FROM PosAllotApplyBill P,dbo.MoveBill M
	WHERE M.AllotID=P.ID AND M.BillNumberId=@intBillNumberID AND M.AllotID>0	
	
	INSERT INTO #PosAllotApplyBill( billnumberid, allotid )
	SELECT B.FromBillNumberID, M.AllotID
	FROM MoveBill M INNER JOIN BillIndex B ON M.BillNumberId = B.BillNumberId
	WHERE M.BillNumberId=@intBillNumberID AND M.AllotID>0
END

IF @billtype=21
BEGIN
	UPDATE dbo.PosAllotApplyBill SET CallQty += M.qty 
	FROM PosAllotApplyBill P,dbo.movebjbill M
	WHERE M.AllotID=P.ID AND M.BillNumberId=@intBillNumberID AND M.AllotID>0	
	
	INSERT INTO #PosAllotApplyBill( billnumberid, allotid )
	SELECT B.FromBillNumberID, M.AllotID
	FROM movebjbill M INNER JOIN BillIndex B ON M.BillNumberId = B.BillNumberId
	WHERE M.BillNumberId=@intBillNumberID AND M.AllotID>0
END

IF @billtype =187
BEGIN
	UPDATE dbo.PosAllotApplyBill SET CallQty += M.qty 
	FROM PosAllotApplyBill P,dbo.stypemovebill M
	WHERE M.AllotID=P.ID AND M.BillNumberId=@intBillNumberID AND M.AllotID>0	
	
	INSERT INTO #PosAllotApplyBill( billnumberid, allotid )
	SELECT B.FromBillNumberID, M.AllotID
	FROM stypemovebill M INNER JOIN BillIndex B ON M.BillNumberId = B.BillNumberId
	WHERE M.BillNumberId=@intBillNumberID AND M.AllotID>0
END

--先将该单据引用的调货单全部改为已完成状态
UPDATE PosAllotApplyBillIndex SET Isdone=1 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM #PosAllotApplyBill
						)
 

--存在引用数量小于申请单数量的申请单状态改为未完成
UPDATE PosAllotApplyBillIndex SET Isdone=0 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM dbo.PosAllotApplyBill 
						WHERE CallQty<qty AND BillNumberId IN (SELECT billnumberid FROM #PosAllotApplyBill) 
						)

-------------------------------991新增关于门店配送的单据--------------------------

IF @billtype =327
BEGIN
	UPDATE dbo.DeliveryApplyBill SET DeliveryQty += M.qty 
	FROM DeliveryApplyBill D,dbo.DeliveryBill M
	WHERE M.DeliveryApplyBillId=D.ID 	
	AND M.BillNumberId=@intBillNumberID 
	AND M.DeliveryApplyBillId>0 
	
	UPDATE dbo.DeliveryBill SET UnfinishedQty =D.Qty- D.DeliveryQty 
	FROM DeliveryApplyBill D,dbo.DeliveryBill M
	WHERE M.DeliveryApplyBillId=D.ID 	
	AND M.BillNumberId=@intBillNumberID 
	AND M.DeliveryApplyBillId>0 	
	
	INSERT INTO #DeliveryApplyBill( billnumberid, DeliveryApplyid )
	SELECT B.BillNumberId, M.DeliveryApplyBillId
	FROM DeliveryBill M INNER JOIN DeliveryApplyBill B ON M.DeliveryApplyBillId = B.ID
	WHERE M.BillNumberId=@intBillNumberID AND M.DeliveryApplyBillId>0


---将过账了的门店配送单的调用的申请单改成1
UPDATE PosAllotApplyBillIndex SET Isdone=1 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM DeliveryApplyBill
						where DeliveryQty>=Qty  AND BillNumberId IN (SELECT billnumberid FROM #DeliveryApplyBill) 
						)
 UPDATE PosAllotApplyBillIndex SET Isdone=0 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM dbo.DeliveryApplyBill 
						WHERE DeliveryQty<qty AND BillNumberId IN (SELECT billnumberid FROM #DeliveryApplyBill) 
						)
 END
IF @billtype =328
begin
 UPDATE dbo.DeliveryBill SET BackQty += D.qty 
	FROM DeliveryBackBill D,dbo.DeliveryBill M
	WHERE M.ID=D.DeliveryID 	
	AND D.BillNumberId=@intBillNumberID 
	AND D.DeliveryID>0 
	
	
  INSERT INTO #DeliveryBackBill( billnumberid, Deliveryid )
	SELECT B.BillNumberId, M.DeliveryID
	FROM DeliveryBackBill M INNER JOIN DeliveryBill B ON M.DeliveryID = B.ID
	WHERE M.BillNumberId=@intBillNumberID AND M.DeliveryID>0
	
	
	UPDATE PosAllotApplyBillIndex SET Isdone=1 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM DeliveryBill
						where CheckQty+BackQty>=Qty  AND BillNumberId IN (SELECT billnumberid FROM #DeliveryBackBill) 
						)
 UPDATE PosAllotApplyBillIndex SET Isdone=0 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM dbo.DeliveryBill 
						WHERE CheckQty+BackQty<qty AND BillNumberId IN (SELECT billnumberid FROM #DeliveryBackBill) 
						)
 
end

 
IF @billtype =329
BEGIN
  UPDATE dbo.DeliveryBill SET CheckQty += M.qty 
	FROM DeliveryBill D,
	dbo.DeliveryCheckBill M
	WHERE M.DeliveryID=D.ID 	
	AND M.BillNumberId=@intBillNumberID 
	AND M.DeliveryID>0 
	
	INSERT INTO #DeliveryBill( billnumberid, Deliveryid )
	SELECT B.BillNumberId, M.DeliveryID
	FROM DeliveryCheckBill M INNER JOIN DeliveryBill B ON M.DeliveryID = B.ID
	WHERE M.BillNumberId=@intBillNumberID AND M.DeliveryID>0


UPDATE PosAllotApplyBillIndex SET Isdone=1 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM DeliveryBill
						where CheckQty+BackQty>=Qty  AND BillNumberId IN (SELECT billnumberid FROM #DeliveryBill) 
						)
 UPDATE PosAllotApplyBillIndex SET Isdone=0 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM dbo.DeliveryBill 
						WHERE CheckQty+BackQty<qty AND BillNumberId IN (SELECT billnumberid FROM #DeliveryBill) 
						)
 
 END
drop table #PosAllotApplyBill,#DeliveryApplyBill,#DeliveryBill,#DeliveryBackBill
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



/*
	作者：卢春
	时间：2006-03-18
	
	修改:冯波   暂估单据处理 2015-05-20
*/
CREATE      PROCEDURE GP_AuditingCheckOrderState (
	@intBillNumberID	numeric(10,0),
	@intIfBillIndex		int		-- 确认是否BillIndex(1)或者OrderIndex(0)过账判断处理
)
--@encode$--
AS

IF @intIfBillIndex = 1
BEGIN
	DECLARE @intBillType int
	SELECT TOP 1 @intBillType = BillType FROM BillIndex WHERE BillNumberID = @intBillNumberID
	IF @intBillType NOT IN (11,12,34,140,144,400,402) RETURN 0
	
	-- 假如明细表中不存在订单OrderID的关联，则退出
	DECLARE @intOrderBillNumberID numeric(10,0)
	IF @intBillType = 11	-- 销售
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	SaleBill
			WHERE	BillNumberID = @intBillNumberID
					AND OrderID <> -1 )
			RETURN 0

		DECLARE ORDER_CURSOR CURSOR SCROLL FOR
			SELECT	b.BillNumberID
			FROM	SaleBill a,OrderBill b
			WHERE	a.BillNumberID = @intBillNumberID
					AND a.OrderID <> -1
					AND a.OrderID = b.OrderID
			GROUP BY b.BillNumberID
	END
	IF @intBillType = 12	-- 组合品销售
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	dbo.PT_Combin_SaleBill
			WHERE	BillNumberID = @intBillNumberID
					AND OrderID <> -1 )
			RETURN 0

		DECLARE ORDER_CURSOR CURSOR SCROLL FOR
			SELECT	b.BillNumberID
			FROM	PT_Combin_SaleBill a,PT_Combin_OrderBill b
			WHERE	a.BillNumberID = @intBillNumberID
					AND a.OrderID <> -1
					AND a.OrderID = b.OrderID
			GROUP BY b.BillNumberID
	END
	ELSE IF @intBillType = 402	-- 发出商品
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	SendBill
			WHERE	BillNumberID = @intBillNumberID
					AND OrderID <> -1 )
			RETURN 0

		DECLARE ORDER_CURSOR CURSOR SCROLL FOR
			SELECT	b.BillNumberID
			FROM	SendBill a,OrderBill b
			WHERE	a.BillNumberID = @intBillNumberID
					AND a.OrderID <> -1
					AND a.OrderID = b.OrderID
			GROUP BY b.BillNumberID
	END
	ELSE IF @intBillType=140 --委托发货
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	commissionbill
			WHERE	BillNumberID = @intBillNumberID
					AND OrderID <> -1 )
			RETURN 0

		DECLARE ORDER_CURSOR CURSOR SCROLL FOR
			SELECT	b.BillNumberID
			FROM	commissionbill a,OrderBill b
			WHERE	a.BillNumberID = @intBillNumberID
					AND a.OrderID <> -1
					AND a.OrderID = b.OrderID
			GROUP BY b.BillNumberID
	END
	ELSE IF @intBillType = 34	-- 采购
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	BuyBill
			WHERE	BillNumberID = @intBillNumberID
					AND OrderID <> -1 )
			RETURN 0

		DECLARE ORDER_CURSOR CURSOR SCROLL FOR
			SELECT	b.BillNumberID
			FROM	BuyBill a,OrderBill b
			WHERE	a.BillNumberID = @intBillNumberID
					AND a.OrderID <> -1
					AND a.OrderID = b.OrderID
			GROUP BY b.BillNumberID
	END
	ELSE IF @intBillType = 400	-- 暂估
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	AppraisalBill
			WHERE	BillNumberID = @intBillNumberID
					AND OrderID <> -1 )
			RETURN 0

		DECLARE ORDER_CURSOR CURSOR SCROLL FOR
			SELECT	b.BillNumberID
			FROM	AppraisalBill a,OrderBill b
			WHERE	a.BillNumberID = @intBillNumberID
					AND a.OrderID <> -1
					AND a.OrderID = b.OrderID
			GROUP BY b.BillNumberID
	END
	ELSE IF @intBillType=144 --受托收货
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	commissionbill
			WHERE	BillNumberID = @intBillNumberID
					AND OrderID <> -1 )
			RETURN 0

		DECLARE ORDER_CURSOR CURSOR SCROLL FOR
			SELECT	b.BillNumberID
			FROM	commissionbill a,OrderBill b
			WHERE	a.BillNumberID = @intBillNumberID
					AND a.OrderID <> -1
					AND a.OrderID = b.OrderID
			GROUP BY b.BillNumberID
	END

	OPEN ORDER_CURSOR
	FETCH NEXT FROM ORDER_CURSOR INTO @intOrderBillNumberID
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @intBillType=12
		BEGIN
			IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	PT_Combin_OrderBill
			WHERE	BillNumberID = @intOrderBillNumberID
					AND ReachQty < Qty AND BillOver='0')
			BEGIN
				UPDATE	OrderIndex
				SET		OrderState = '1'	-- 已完成
				WHERE	BillNumberID = @intOrderBillNumberID
			END
			ELSE
			BEGIN
				UPDATE	OrderIndex
				SET		OrderState = '0'	-- 未完成
				WHERE	BillNumberID = @intOrderBillNumberID
			END
		END
		ELSE
		BEGIN
			IF NOT EXISTS(
				SELECT	TOP 1 1
				FROM	OrderBill
				WHERE	BillNumberID = @intOrderBillNumberID
						AND ReachQty < Qty AND BillOver='0')
			BEGIN
				UPDATE	OrderIndex
				SET		OrderState = '1'	-- 已完成
				WHERE	BillNumberID = @intOrderBillNumberID
			END
			ELSE
			BEGIN
				UPDATE	OrderIndex
				SET		OrderState = '0'	-- 未完成
				WHERE	BillNumberID = @intOrderBillNumberID
			END
		END
		FETCH NEXT FROM ORDER_CURSOR INTO @intOrderBillNumberID
	END
	CLOSE ORDER_CURSOR
	DEALLOCATE ORDER_CURSOR
END
ELSE
BEGIN
	-- 订单OrderIndex
	SET @intOrderBillNumberID = @intBillNumberID
	IF @intBillType=12
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	PT_Combin_OrderBill
			WHERE	BillNumberID = @intOrderBillNumberID
					AND ReachQty < Qty)
		BEGIN
			UPDATE	OrderIndex
			SET		OrderState = '1'	-- 已完成
			WHERE	BillNumberID = @intOrderBillNumberID
		END
		ELSE
		BEGIN
			UPDATE	OrderIndex
			SET		OrderState = '0'	-- 未完成
			WHERE	BillNumberID = @intOrderBillNumberID
		END
	END
	ELSE
	BEGIN
		IF NOT EXISTS(
			SELECT	TOP 1 1
			FROM	OrderBill
			WHERE	BillNumberID = @intOrderBillNumberID
					AND ReachQty < Qty)
		BEGIN
			UPDATE	OrderIndex
			SET		OrderState = '1'	-- 已完成
			WHERE	BillNumberID = @intOrderBillNumberID
		END
		ELSE
		BEGIN
			UPDATE	OrderIndex
			SET		OrderState = '0'	-- 未完成
			WHERE	BillNumberID = @intOrderBillNumberID
		END
	END
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	核心过账，继创建明细之后的成本数据变化
	作    者：	卢 春
	修改时间：	2004-01-12
*/
CREATE                   PROCEDURE Gp_AuditingCore
(
	@nBillID		numeric(10, 0),				-- 单据编号 ID 值
	@szCheckMan		varchar(50),				-- 制单人
	@chvOpID		varchar(50),
	@nBillType		INT,
	@tBillDate		DATETIME,
	@szATypeID		VARCHAR(50),
	@szBTypeID		VARCHAR(50),
	@szETypeID		VARCHAR(50),
	@szStockID		VARCHAR(50),
	@szStockID2		VARCHAR(50),
	@szSTypeIDTemp	VARCHAR(50),
	@dTotalMoney	 NUMERIC(24, 10) ,
	@dTotalInMoney	 NUMERIC(24, 10) ,
	@szIfCheck		VARCHAR(10),
	@szPID			varchar(50) output,			-- 返回的商品编号 ID 值
	@KTypeID		varchar(50) = '' output,	-- 返回仓库ID值，针对多仓库应用
	@intPostTime	INT=0						--是否修改过账日期
)
--@encode$--
AS
	DECLARE
		@intAdPriceType	INT
	
	SELECT @intAdPriceType=0

	IF @nBillType=57
	BEGIN
		SELECT @intAdPriceType=AdpriceType
		FROM Billindex
		WHERE BillNumberId=@nBillID
	END
	
	DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT

	SET NOCOUNT ON
	-- Some VchType
	DECLARE	@GOODS_ID		varchar(50),
			@CASH_ID		varchar(50),
			@CASH_BANK_ID	varchar(50),
			@AR_ID			varchar(50),
			@AP_ID			varchar(50),
			@GOODS_LOSS_ID	varchar(50),
			@GOODS_GET_ID	varchar(50)

	/*
	SET @GOODS_ID		= '0000100001'			-- 『库存商品总值合计』
	SET @CASH_ID		= '0000100003'			-- 现    金
	SET @CASH_BANK_ID	= '0000100004'			-- 『全部银行存款合计』
	SET @AR_ID			= '0000100005'			-- 『应收款合计』
	SET @AP_ID			= '0000200001'			-- 『应付帐款合计』
	SET @GOODS_LOSS_ID	= '000040000200001' 	-- 商品报损支出
	SET @GOODS_GET_ID	= '000030000200001'		-- 商品报溢收入
	*/
	
	SELECT
		@GOODS_ID=nid
	FROM Ac_Items
	WHERE UserCode='1241'	

	-- Costing Method
	DECLARE @AVERAGE	smallint,
			@FIFO		smallint,
			@LIFO		smallint,
			@HAND		smallint

	SET @AVERAGE	= 0		-- 移动加权平均
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	SET @HAND		= 3		-- 手工指定

	DECLARE	@DBName				varchar(30),
			@nCostingMethod		smallint,
			/*
			@tBillDate			datetime,
			@dTotalMoney		 NUMERIC(24, 10) ,
			@dTotalInMoney		 NUMERIC(24, 10) ,
			*/
			@dTotalTemp			 NUMERIC(24, 10) ,
			@dCostTotalTemp		 NUMERIC(24, 10) ,
			/*
			@nBillType			numeric(4, 0),
			@szATypeID			varchar(50),
			*/
			@szPTypeID			varchar(50),
			/*
			@szBTypeID			varchar(50),
			@szETypeID			varchar(50),
			@szStockID			varchar(50),
			@szStockID2			varchar(50),
			*/
			@szATypeIDTemp		varchar(50),
			@szPTypeIDTemp		varchar(50),
			@szBTypeIDTemp		varchar(50),
			@szETypeIDTemp		varchar(50),
			@szKTypeIDTemp		varchar(50),
			/*
			@szSTypeIDTemp		varchar(50),
			@szIfCheck			char(1),
			*/
			@nPeriod			int,
			@szJobNumber		varchar(20),
			@OutFactoryDate		datetime,
			@dPrice				 NUMERIC(24, 10) ,
			@dTotal				 NUMERIC(24, 10) ,
			@dQty				 NUMERIC(24, 10) ,
			@dCostPrice			 NUMERIC(24, 10) ,
			@dCostTotal			 NUMERIC(24, 10) ,	-- ?成本金额精度改为两位小数
			@nGoodsNo			int,
			@dCostPriceOut		 NUMERIC(24, 10) ,	-- ?成本核算，最终输出的数据，精度为两位小数
			@dTemp				 NUMERIC(24, 10) ,
			@dPricetemp			 NUMERIC(24, 10) ,
			@nRet				smallint,
			@GoodsNumber		varchar(100),
			@ProduceDate		varchar(50),
			@ValidDate			varchar(50),
			@GoodsBTypeID		varchar(50),
			@GoodsCostPrice		 NUMERIC(24, 10) ,
			@HandZeroCost		varchar(50),
			@intID				int,			-- 单据明细排序自增长ID值
			@numBillCostPrice	 NUMERIC(24, 10) ,	-- 单据明细成本价
			@numBillCostTotal	 NUMERIC(24, 10) ,	-- 单据明细成本金额,
			@intItemID			INT,
			@intIsCombined		TINYINT,
			@dNQty				 NUMERIC(24, 10) ,
			@dncostTotal		 NUMERIC(24, 10) =0,
			@cid				INT=0

	/*
	SELECT	TOP 1
			@nBillType = BillType,			-- 单据类型
			@tBillDate = BillDate,			-- 单据日期
			@szATypeID = ATypeID,			-- 收付款账户 ID 值
			@szBTypeID = BTypeID,			-- 结算单位 ID 值
			@szETypeID = ETypeID,			-- 经手人 ID 值
			@szStockID = KTypeID,			-- 出库仓库 ID 值
			@szStockID2 = KTypeID2,			-- 入库仓库 ID 值
			@szSTypeIDTemp=STypeID,
			@dTotalMoney = TotalMoney,		-- 单据金额合计
			@dTotalInMoney = TotalInMoney,	-- 单据实收、实付金额
			@szIfCheck = IfCheck			-- 是否草稿标识，f - 草稿；t - 已过账
	FROM	BillIndex
	WHERE	BillNumberID = @nBillID
	*/
	-- 若为已过账单据，则回滚事务
	IF @szIfCheck = 't' RETURN 0

	SET @dTotalTemp = 0
	-- 得到成本核算法
	EXEC Gp_GetSubValue 'costing', @szSTypeIDTemp,@nCostingMethod output

	DECLARE @TPrice  NUMERIC(24, 10) ,
			@DXTaxTotalTemp  NUMERIC(24, 10) ,
			@DXTotalTemp  NUMERIC(24, 10) 

	-- Begin Tran AuditingTrans
	
	IF @nBillType = 140
	BEGIN
		DECLARE Auditing_Cursor CURSOR SCROLL FOR
			SELECT	ATypeID,
					PTypeID,
					BTypeID,
					ETypeID,
					KTypeID,
					Qty,
					Price,
					Total,
					CostPrice,
					CostTotal,
					JobNumber,
					GoodsNo,
					OutFactoryDate,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					GoodsBTypeID,
					GoodsCostPrice,
					HandZeroCost,
					[ID]
			FROM	InOutStockTable
			WHERE	BillNumberID = @nBillID
					AND PTypeID <> '0'
					ORDER BY KTypeID, Total
			FOR UPDATE
	END
	ELSE IF @nBillType = 146
	BEGIN
		DECLARE Auditing_Cursor CURSOR SCROLL FOR
			SELECT	ATypeID,
					PTypeID,
					BTypeID,
					ETypeID,
					KTypeID,
					Qty,
					Price,
					Total,
					CostPrice,
					CostTotal,
					JobNumber,
					GoodsNo,
					OutFactoryDate,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					GoodsBTypeID,
					GoodsCostPrice,
					HandZeroCost,
					[ID]
			FROM	InOutStockTable
			WHERE	BillNumberID = @nBillID
					AND ATypeID = @GOODS_ID
					AND PTypeID <> '0'
					ORDER BY KTypeID DESC
			FOR UPDATE
	END
	ELSE IF @nBillType = 142	-- 委托退货
	BEGIN
		DECLARE Auditing_Cursor CURSOR SCROLL FOR
			SELECT	ATypeID,
					PTypeID,
					BTypeID,
					ETypeID,
					KTypeID,
					Qty,
					Price,
					Total,
					CostPrice,
					CostTotal,
					JobNumber,
					GoodsNo,
					OutFactoryDate,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					GoodsBTypeID,
					GoodsCostPrice,
					HandZeroCost,
					[ID]
			FROM	InOutStockTable
			WHERE	BillNumberID = @nBillID
					AND ATypeID = @GOODS_ID
					AND PTypeID <> '0'
					ORDER BY KTypeID DESC
			FOR UPDATE
	END
	ELSE IF @nBillType = 160 OR @nBillType = 161	-- 销售、采购换货
	BEGIN
		DECLARE Auditing_Cursor CURSOR SCROLL FOR
			SELECT	ATypeID,
					PTypeID,
					BTypeID,
					ETypeID,
					KTypeID,
					Qty,
					Price,
					Total,
					CostPrice,
					CostTotal,
					JobNumber,
					GoodsNo,
					OutFactoryDate,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					GoodsBTypeID,
					GoodsCostPrice,
					HandZeroCost,
					[ID]
			FROM	InOutStockTable
			WHERE	BillNumberID = @nBillID
					AND ATypeID = @GOODS_ID
					AND PTypeID <> '0'
					AND IsSerVice=0
					ORDER BY [ID]
			FOR UPDATE
	END
	ELSE IF @nBillType IN (17,21)
	BEGIN
		DECLARE Auditing_Cursor CURSOR SCROLL FOR
			SELECT	ATypeID,
					PTypeID,
					BTypeID,
					ETypeID,
					KTypeID,
					Qty,
					Price,
					Total,
					CostPrice,
					CostTotal,
					JobNumber,
					GoodsNo,
					OutFactoryDate,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					GoodsBTypeID,
					GoodsCostPrice,
					HandZeroCost,
					[ID]
			FROM	InOutStockTable
			WHERE	BillNumberID = @nBillID
					AND @intAdPriceType=0
					AND ATypeID = @GOODS_ID
					AND PTypeID <> '0'
					AND IsSerVice=0
					AND BillType=@nBillType
					ORDER BY
						ID,Qty
			FOR UPDATE
	END
	ELSE
	BEGIN
		DECLARE Auditing_Cursor CURSOR SCROLL FOR
			SELECT	ATypeID,
					PTypeID,
					BTypeID,
					ETypeID,
					KTypeID,
					Qty,
					Price,
					Total,
					CostPrice,
					CostTotal,
					JobNumber,
					GoodsNo,
					OutFactoryDate,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					GoodsBTypeID,
					GoodsCostPrice,
					HandZeroCost,
					[ID]
			FROM	InOutStockTable
			WHERE	BillNumberID = @nBillID
					AND @intAdPriceType=0
					AND @nBillType NOT IN (404,405,414)
					AND ATypeID = @GOODS_ID
					AND PTypeID <> '0'
					AND IsSerVice=0
					AND BillType=@nBillType
					ORDER BY
						CASE BillType
						WHEN 57 THEN BillNumberID
						ELSE Total
						END
			FOR UPDATE
	END

	OPEN Auditing_Cursor
	FETCH NEXT FROM Auditing_Cursor INTO	@szATypeIDTemp,
											@szPTypeIDTemp,
											@szBTypeIDTemp,
											@szETypeIDTemp,
											@szKTypeIDTemp,
											@dQty,
											@dPrice,
											@dTotal,
											@dCostPrice,
											@dCostTotal,
											@szJobNumber,
											@nGoodsNo,
											@OutFactoryDate,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID
											
	
	WHILE @@FETCH_STATUS <> -1
	BEGIN
		IF @@FETCH_STATUS = -2 GOTO ERROR1
		ELSE
		BEGIN
			/*-- 代销业务独立处理
			----------------------
			140 - 委托代销发货单
			141 - 委托代销结算单
			142 - 委托代销退货单
			143 - 委托代销调价单
			144 - 受托代销收货单
			145 - 受托代销结算单
			146 - 受托代销退货单
			147 - 受托代销调价单
			----------------------
			--*/ 
			IF @nBillType IN ( 140, 141, 142, 143, 144, 145, 146, 147 )
			BEGIN
				-- @ 委托退货、受托退货
				-- 退货取成本价
				IF @nBillType IN ( 142, 146, 141 )
				BEGIN
					DELETE FROM CommissionStock
					WHERE	PTypeID = @szPTypeIDTemp
							AND BTypeID = @szBTypeID
							AND STypeID =@szSTypeIDTemp
							AND Type =
								CASE @nBillType
								WHEN 142 THEN 140
								WHEN 141 THEN 140
								WHEN 146 THEN 144
								END
							AND Qty = 0
							AND CostTotal = 0
							AND Total = 0

					IF EXISTS (
						SELECT	TOP 1 1
						FROM	CommissionStock
						WHERE	PTypeID = @szPTypeIDTemp
								AND BTypeID = @szBTypeID
								AND STypeID=@szSTypeIDTemp
								AND Type =
									CASE @nBillType
									WHEN 142 THEN 140
									WHEN 141 THEN 140
									WHEN 146 THEN 144
									END
								AND Qty <> 0
					)
					BEGIN
						SELECT	@TPrice = CASE QTY WHEN 0 THEN 0 ELSE CONVERT( NUMERIC(24, 10) , CostTotal/Qty) END
						FROM	CommissionStock
						WHERE	PTypeID = @szPTypeIDTemp
								AND BTypeID = @szBTypeID
								AND STypeID=@szSTypeIDTemp
								AND Type =
									CASE @nBillType
									WHEN 142 THEN 140
									WHEN 141 THEN 140
									WHEN 146 THEN 144
									END

						IF (@nBillType = 142 AND @szKTypeIDTemp = '10000') OR @nBillType = 141
						BEGIN
								SET @dCostTotal =ROUND(CONVERT( NUMERIC(24, 10) , @dQty * @TPrice),@intMoneyDot)
						END
					END

					IF @szKTypeIDTemp <> '10000' AND ( @nCostingMethod = 1 OR @nCostingMethod = 2 OR @nCostingMethod = 3 ) AND @nBillType = 146
					BEGIN
						SET @dCostTotal = 0
					END
				END

				-- @ 委托发货、受托收货
				IF @nBillType IN (140,144)
				BEGIN
					SELECT @DXTaxTotalTemp = @dTotal
					SELECT @DXTotaltemp = @dTotal
				END
				-- @ 委托退货、受托退货
				ELSE IF @nBillType IN (142,146)
				BEGIN
					SELECT @DXTaxTotalTemp = @dTotal
					SELECT @DXTotaltemp = @dTotal
				END
				-- @ 委托结算、委托调价、受托结算、受托调价
				ELSE IF @nBillType IN (141,143,145,147)
				BEGIN
					SELECT @DXTaxTotalTemp = @dTotal
					SELECT @DXTotaltemp = @dTotal
				END

				IF @szKTypeIDTemp = '10000'	-- 代销库
				BEGIN
					EXEC @nRet = Gp_ModifyDbf_DX	@nBillType,
													@nCostingMethod,
													@szATypeIDTemp,
													@szPTypeIDTemp,
													@szBTypeID,
													@szETypeIDTemp,
													@szKTypeIDTemp,
													@szSTypeIDTemp,
													'',
													@dQty,
													@dCostTotal,
													@DXTaxTotalTemp,
													@DXTotalTemp,
													@szJobNumber,
													@nGoodsNo,
													@dCostPriceOut output,
													NULL,
													@dCostPrice
				END
				ELSE
					EXEC @nRet = Gp_ModifyDbf	@nBillType,
												@nCostingMethod,
												@szATypeIDTemp,
												@szPTypeIDTemp,
												@szBTypeIDTemp,
												@szETypeIDTemp,
												@szKTypeIDTemp,
												@szSTypeIDTemp,
												'',
												@dQty,
												@dCostTotal,
												@dncostTotal,
												@cid,
												@szJobNumber,
												@nGoodsNo,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsCostPrice,
												@HandZeroCost,
												@dCostPriceOut output,
												0,
												NULL,
												@dCostPrice
												


			END
			--成本调价单(移动加权)单独处理
			ELSE IF @nBillType=57 AND @nCostingMethod=0
			BEGIN
				EXEC Gp_AuditingAdPriceBill     @nCostingMethod,
												@szATypeIDTemp,
												@szPTypeIDTemp,
												@szBTypeIDTemp,
												@szETypeIDTemp,
												@szKTypeIDTemp,
												@szSTypeIDTemp,
												@dQty,
												@dCostTotal,
												@nGoodsNo,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsCostPrice,
												@nBillID		
			END
			ELSE
			-- 普通单据处理
			BEGIN
				EXEC @nRet = Gp_ModifyDbf	@nBillType,
											@nCostingMethod,
											@szATypeIDTemp,
											@szPTypeIDTemp,
											@szBTypeIDTemp,
											@szETypeIDTemp,
											@szKTypeIDTemp,
											@szSTypeIDTemp,
											'',
											@dQty,
											@dCostTotal,
											@dnCostTotal,
											@cid,
											@szJobNumber,
											--@nGoodsNo,
											@nBillID,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsCostPrice,
											@HandZeroCost,
											@dCostPriceOut output,
											0,
											NULL,
											@dCostPrice
											
				
			END

			IF @nRet <> 0
			BEGIN
				GOTO ERROR1
			END
			ELSE
			BEGIN
				IF @dQty < 0 AND @nBillType <> 57
					SET @dCostPriceOut = -@dCostPriceOut

				IF @dQty<>0
				BEGIN
					IF @nBillType = 57
					BEGIN
						SET @dPriceTemp = ROUND(@dCostPriceOut/@dQty,@intPriceDot)
					END
					ELSE
					BEGIN
						SET @dPriceTemp = ROUND(ABS(@dCostPriceOut/@dQty),@intPriceDot)
					END
				END

				SET @dTemp = ABS(@dCostPriceOut)
				SET @dTotalTemp = @dTotalTemp + @dCostPriceOut
	
				-- 代销结算、调价除外,
				IF @nBillType NOT IN (143,145,147,57,329) OR (@nBillType=57 AND @nCostingMethod<>0)
				BEGIN
					IF @nCostingMethod=3
					BEGIN
						IF @nBillType IN (34,161,144,400,14,201,16,57)--mj5092成本调价单total在手工指定算法中取costtotal,不然会存在小数差
						BEGIN
							UPDATE	InOutStockTable
							SET		CostPrice=CASE WHEN InOutstocktable.CostPrice IN (0,-1) THEN @dPriceTemp ELSE InOutstocktable.CostPrice END,									
									CostTotal = CASE 
													WHEN @nBillType IN (34,144,400,14,201) THEN InOutstocktable.CostTotal
													WHEN @nBillType IN (161,16,57) AND InOutstocktable.Qty > 0 THEN InOutstocktable.CostTotal
													ELSE @dCostPriceOut
												END,
									Audited = 1
							WHERE	CURRENT OF Auditing_Cursor
						END
						ELSE
						BEGIN
							UPDATE	InOutStockTable
							SET		
									CostPrice=CASE WHEN InOutstocktable.CostPrice IN (0,-1) THEN @dPriceTemp ELSE InOutstocktable.CostPrice END,
									CostTotal = @dCostPriceOut,
									Audited = 1
							WHERE	CURRENT OF Auditing_Cursor
						END
					END
					ELSE
					BEGIN
						UPDATE	InOutStockTable
						SET		CostPrice =CASE WHEN @nBillType IN(34,144,400,201,401,329) AND NPrice=0 THEN 0  ELSE @dPriceTemp END,
								CostTotal = CASE WHEN @nBillType IN(34,144,400,201,401,329) AND NPrice=0 THEN 0 ELSE @dCostPriceOut END,
								Audited = 1
						WHERE	CURRENT OF Auditing_Cursor
					END
				END
				ELSE
				BEGIN
					UPDATE	InOutStockTable
					SET		Audited = 1
					WHERE	CURRENT OF Auditing_Cursor
				END

				-- 委托退货，先从代销库确认扣除的成本后
				-- 更新InOutStockTable中对应的账面库存成本数据，以求准确入库，无差异
				IF @nBillType = 142 AND @szKTypeIDTemp = '10000'
				BEGIN
					IF @nCostingMethod=3
					BEGIN
						UPDATE	InOutStockTable
						SET
								CostTotal = -@dCostPriceOut
						WHERE	BillNumberID = @nBillID
								AND KTypeID <> '10000'
								AND JobNumber = @szJobNumber
					END
					ELSE
					BEGIN
						
						UPDATE	InOutStockTable
						SET		CostPrice = @dPriceTemp,
								CostTotal = -@dCostPriceOut
						WHERE	BillNumberID = @nBillID
								AND KTypeID <> '10000'
								AND JobNumber = @szJobNumber

					END
				END

				-- 委托代销发货；受托代销退货
				IF @nBillType IN (140,146) AND @szKTypeIDTemp <> '10000' AND ( @nCostingMethod = 1 OR @nCostingMethod = 2 OR @nCostingMethod = 3)
				BEGIN
					IF @nCostingMethod=3
					BEGIN
						UPDATE	InOutStockTable
						SET
								CostTotal = CASE @nBillType WHEN 140 THEN -@dCostPriceOut
											ELSE @dCostPriceOut END
						WHERE	KTypeID = '10000'
								AND BillNumberID = @nBillID
								AND JobNumber = @szJobNumber
					END
					ELSE
					BEGIN
						UPDATE	InOutStockTable
						SET		CostPrice = @dPriceTemp,
								CostTotal = CASE @nBillType WHEN 140 THEN -@dCostPriceOut
											ELSE @dCostPriceOut END
						WHERE	KTypeID = '10000'
								AND BillNumberID = @nBillID
								AND JobNumber = @szJobNumber
					END
				END

				-- 委托代销发货 -- 加权移动平均算法
				IF @nBillType = 140 AND @nCostingMethod = 0 AND @szKTypeIDTemp <> '10000'
				BEGIN
					UPDATE	InOutStockTable
					SET		CostPrice = @dPriceTemp,
							CostTotal = -@dCostPriceOut
					WHERE	KTypeID = '10000'
							AND BillNumberID = @nBillID
							AND JobNumber = @szJobNumber
				END
/*
				-- 同价、变价，如果出库成本金额为0时，报错返回
				IF @nBillType IN (17,21)
				BEGIN
					IF @dQty < 0 AND @dCostPriceOut = 0
					BEGIN
						SET @nRet = 1818
						GOTO ERROR1
					END
				END
*/
				-- 同价调拔单
				IF ( @nBillType = 17 )	--21 or @nBillType=14 or @nBillType=9
				BEGIN
					IF @nCostingMethod=3
					BEGIN
						UPDATE	InOutStockTable
						SET		Price = CASE GoodsCostPrice WHEN -1 THEN @dPriceTemp ELSE InOutstocktable.GoodsCostPrice END,
								Total = @dCostPriceOut
						WHERE	CURRENT OF Auditing_Cursor
						
						UPDATE dbo.MoveBill
						SET Price=b.CostPrice,total=b.CostTotal,
						MPrice= CASE WHEN MoveBill.MUnitID=MoveBill.UnitID THEN b.CostPrice 
						ELSE CASE MoveBill.MQty WHEN 0 THEN 0 
						ELSE ROUND(CAST(b.CostTotal AS  NUMERIC(24, 10) )/CAST(MQty AS  NUMERIC(24, 10) ),@intPriceDot) END END
						FROM dbo.InOutstocktable b
						WHERE dbo.MoveBill.BillNumberId=@nBillID
						AND MoveBill.BillNumberId=b.BillNumberId
						AND dbo.MoveBill.id=b.ID
						AND b.BillType=17
						AND b.Qty>0
					END
					ELSE
					BEGIN
						UPDATE	InOutStockTable
						SET		Price = @dPriceTemp,
								Total = @dCostPriceOut
						WHERE	CURRENT OF Auditing_Cursor
						
						
						IF EXISTS(
							SELECT ConfigNo
							FROM Userconfig
							WHERE ConfigName='IfUsePAllotCostPrice' AND Value<>2
						)
						BEGIN
							UPDATE MoveBill
							SET		Price = @dPriceTemp,
									Total = @dCostPriceOut,
									MPrice= CASE WHEN MUnitID=UnitID THEN @dPriceTemp ELSE CASE MQty WHEN 0 THEN 0 ELSE ROUND(CAST(@dCostPriceOut AS  NUMERIC(24, 10) )/CAST(MQty AS  NUMERIC(24, 10) ),@intPriceDot) END END
							WHERE	BillNumberID = @nBillID
									AND [ID] = @intID
						END
					END
					
					
				END

				
				IF @nBillType = 57 AND @nCostingMethod<>3
				BEGIN
					UPDATE dbo.AdPriceBill SET BeforePrice=@dPriceTemp,BeforeTotal=-@dCostPriceOut WHERE BillNumberId=@nBillID AND @dCostPriceOut<0
				END
				
					
				IF @nBillType = 187 AND @nCostingMethod=3
				BEGIN
					UPDATE dbo.stypemovebill SET goodscosttotal=ABS(@dCostPriceOut) WHERE BillNumberId=@nBillID AND id=@intID
				END
				
				-- 报损、报溢单，将InOutSotckTable中的CostPrice回写至明细表中的CostPrice、CostTotal
				IF @nBillType = 9	-- 报损
				BEGIN
					IF @nCostingMethod=3
					BEGIN
						UPDATE	LoseBill
						SET		Price = CASE GoodsCostPrice WHEN -1 THEN  CASE InputCostPrice WHEN 0 THEN ROUND(DBO.F_GetRecPrice(Stypeid,PtypeId),@intPriceDot) ELSE InputCostPrice END ELSE GoodsCostPrice END,
								Total = ABS(@dCostPriceOut)
						WHERE	BillNumberID = @nBillID
								AND [ID] = @intID
					END
					ELSE
					BEGIN
						UPDATE	LoseBill
						SET		Price = ABS(@dPriceTemp),
								Total = ABS(@dCostPriceOut)
						WHERE	BillNumberID = @nBillID
								AND [ID] = @intID
					END
				END

				IF @nBillType = 14	-- 报溢
				BEGIN
					IF @nCostingMethod=3
					BEGIN
						UPDATE	OverFlowBill
						SET		Price = CASE GoodsCostPrice WHEN -1 THEN CASE InputCostPrice WHEN 0 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE InputCostPrice END ELSE OverFlowBill.GoodsCostPrice END,
								Total = ABS(@dCostPriceOut)
						WHERE	BillNumberID = @nBillID
								AND [ID] = @intID
								AND HandZeroCost=0
					END
					ELSE
					BEGIN
						UPDATE	OverFlowBill
						SET		Price = ABS(@dPriceTemp),
								Total = ABS(@dCostPriceOut)
						WHERE	BillNumberID = @nBillID
								AND [ID] = @intID
								AND HandZeroCost=0
					END
				END
				
				
				IF @nBillType IN (202)
				BEGIN
					IF @nCostingMethod=3
					BEGIN
						UPDATE OtherInOutBill
						SET		Price=CASE GoodsCostPrice WHEN -1 THEN CASE InputCostPrice WHEN 0 THEN ROUND(DBO.F_GetRecPrice(Stypeid,PTypeID),@intPriceDot) ELSE InputCostPrice END ELSE GoodsCostPrice END,
								Total = ABS(@dCostPriceOut)
						WHERE	BillNumberID = @nBillID
								AND [ID] = @intID
					END
					ELSE
					BEGIN
						UPDATE OtherInOutBill
						SET		Price = ABS(@dPriceTemp),
								Total = ABS(@dCostPriceOut)
						WHERE	BillNumberID = @nBillID
								AND [ID] = @intID
					END
				END
				
				IF @nBillType IN (201)
				BEGIN
					UPDATE OtherInOutBill
					SET		
							Total = ABS(@dCostPriceOut)
					WHERE	BillNumberID = @nBillID
							AND [ID] = @intID
				END
			END

			FETCH NEXT FROM Auditing_Cursor INTO	@szATypeIDTemp,
													@szPTypeIDTemp,
													@szBTypeIDTemp,
													@szETypeIDTemp,
													@szKTypeIDTemp,
													@dQty,
													@dPrice,
													@dTotal,
													@dCostPrice,
													@dCostTotal,
													@szJobNumber,
													@nGoodsNo,
													@OutFactoryDate,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID
			-- 同价调拨
			IF ( @nBillType = 17 ) AND @dQty > 0	--21 or @nBillType=14 or @nBillType=9
			BEGIN
				SET @dCostTotal = @dTemp
			END
		END
	END




	-- ******** 产生 ListTable 中会计科目变化情况 ********
	-- 主要影响在 ListTable 数据表中，涉及成本数据的会计分录
	-- 原理是从 InOutStockTable 数据表中取出对应成本数据，写入 ListTable 数据表


	IF @nBillType=57 AND @intAdPriceType<>0
	BEGIN
		/*
		UPDATE GOODSSTOCKS
		SET Total=GOODSSTOCKS.Total+b.Total,
			Price=CASE GOODSSTOCKS.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(GOODSSTOCKS.Total+b.Total AS  NUMERIC(24, 10) )/CAST(GOODSSTOCKS.Qty AS  NUMERIC(24, 10) ),4) END
		FROM InOutstocktable b
		WHERE GOODSSTOCKS.KtypeId=b.KtypeId
		AND GOODSSTOCKS.PtypeId=b.PtypeId
		AND GOODSSTOCKS.GoodsNumber=b.GoodsNumber
		AND GOODSSTOCKS.ProduceDate=b.ProduceDate
		AND GOODSSTOCKS.ValidDate=b.ValidDate
		AND b.BillNumberId=@nBillID
		*/
		
		MERGE GoodsStocks AS t
		USING(
			SELECT PTypeID,KTypeID,SUM(Total) AS Total
			FROM InOutstocktable
			WHERE BillNumberID=@nBillID
			GROUP BY PTypeID,KTypeID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		WHEN MATCHED THEN 
			UPDATE SET t.Total=t.Total+s.Total,t.Price=CASE t.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(t.Total+s.Total AS  NUMERIC(24, 10) )/CAST(t.Qty AS  NUMERIC(24, 10) ),@intPriceDot) END
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,Qty,Price,Total) 
			VALUES(s.PtypeId,s.KTypeID,0,0,s.Total);
			
			
		MERGE GoodsStocks_Qty AS t
		USING(
			SELECT DISTINCT PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID
			FROM InOutstocktable
			WHERE BillNumberID=@nBillID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		AND t.GoodsNumber=s.GoodsNumber AND t.ProduceDate=s.ProduceDate AND t.ValidDate=s.ValidDate
		AND t.CargoID=s.CargoID
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,CargoID,ItemID,IsCombined) 
			VALUES(s.PtypeId,s.KTypeID,s.GoodsNumber,s.ProduceDate,s.ValidDate,0,0,0,s.CargoID,0,0);
	END

	
	
	
	
	-- ******** 影响 BType、AType 数据表中的应收应付数据 ********
	-- 引用存储过程 Gp_ModifyDbf
	

	
	IF @nBillType=402
	BEGIN
		IF NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId=@nBillID AND CostSale=1)
		BEGIN
			EXEC Gp_CreateQtMx @nBillID,@nBillType,@szPID 	
		END
	END
	ELSE
	BEGIN
		EXEC Gp_CreateQtMx @nBillID,@nBillType,@szPID 
	END
	
	EXEC @nRet = Gp_CreateManageRep @nBillID,@nBillType
	

	
	IF @nRet <> 0 GOTO ERROR2
	
	CLOSE Auditing_Cursor
	DEALLOCATE Auditing_Cursor

	/******** 处理新维修的出入库明细 - Start ********/
	-- 同时对勾选了“处理维修品”的报损、报溢单进行处理
	IF @nBillType IN (165,166,167,168,169,170,172,173,174,175,9,14)
	BEGIN
		DECLARE wx_Cursor CURSOR SCROLL FOR
			SELECT	ATypeID,PTypeID,BTypeID,ETypeID,KTypeID,Qty,Price,Total,CostPrice,CostTotal,JobNumber,GoodsNo,OutFactoryDate,GoodsNumber,
					ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,HandZeroCost,[ID],ItemID,IsCombined,NQty
			FROM	wx_InOutStockTable
			WHERE	BillNumberID = @nBillID AND ATypeID = @GOODS_ID AND PTypeID <> '0'  AND IsService=0 AND BillType=@nBillType
			ORDER BY [ID]
			FOR UPDATE
	
		OPEN wx_Cursor
		FETCH NEXT FROM wx_Cursor INTO @szATypeIDTemp,@szPTypeIDTemp,@szBTypeIDTemp,@szETypeIDTemp,@szKTypeIDTemp,@dQty,@dPrice,@dTotal,
			@dCostPrice,@dCostTotal,@szJobNumber,@nGoodsNo,@OutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,
			@HandZeroCost,@intID,@intItemID,@intIsCombined,@dNQty
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC @nRet = Gp_ModifyDbf_WX	@nBillType,
											@nCostingMethod,
											@szATypeIDTemp,
											@szPTypeIDTemp,
											@szBTypeIDTemp,
											@szETypeIDTemp,
											@szKTypeIDTemp,
											'',
											@dQty,
											@intItemID,
											@intIsCombined,
											@dNQty,
											@dCostTotal,
											@szJobNumber,
											--@nGoodsNo,
											@nBillID,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsCostPrice,
											@HandZeroCost,
											@dCostPriceOut output,
											NULL,
											@dPrice
			IF @nRet <> 0 GOTO ERROR3
			ELSE
			BEGIN
				UPDATE wx_InOutStockTable SET Audited = 1 WHERE BillNumberID = @nBillID AND PTypeID = @szPTypeIDTemp AND [ID] = @intID  AND BillType=@nBillType
			END
			FETCH NEXT FROM wx_Cursor INTO @szATypeIDTemp,@szPTypeIDTemp,@szBTypeIDTemp,@szETypeIDTemp,@szKTypeIDTemp,@dQty,@dPrice,@dTotal,
				@dCostPrice,@dCostTotal,@szJobNumber,@nGoodsNo,@OutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,
				@HandZeroCost,@intID,@intItemID,@intIsCombined,@dNQty	
		END
		CLOSE wx_Cursor
		DEALLOCATE wx_Cursor
	END
	/******** 处理新维修的出入库明细 - End ********/
	

	

	-- 将单据状态：草稿 -> 过账单据
	IF @nBillType NOT IN (404,405)
	BEGIN
		IF @intPostTime=0
		BEGIN
			IF @nBillType NOT IN(327,328,329)
			BEGIN
				UPDATE	BillIndex
				SET		IfCheck = 't',
						Checke = @szCheckman,
						Draft = 0,
						Poster=@chvOpID,
						posttime=GETDATE()
				WHERE	BillNumberID = @nBillID
						AND BillType=@nBillType
			END	
			ELSE
			BEGIN
				UPDATE dbo.PosAllotApplyBillIndex 
				SET ifcheck='t',
				draft=0 ,
				posttime=GETDATE()
				WHERE BillNumberId=@nBillID AND BillType=@nBillType
			END
			
		END
		ELSE
		BEGIN
			IF @nBillType NOT IN(327,328,329)
			BEGIN
				UPDATE	BillIndex
				SET		IfCheck = 't',
						Checke = @szCheckman,
						Draft = 0,
						Poster=@chvOpID
				WHERE	BillNumberID = @nBillID
						AND BillType=@nBillType
			END
			ELSE
			BEGIN
				UPDATE dbo.PosAllotApplyBillIndex 
				SET ifcheck='t',
				draft=0 ,
				posttime=GETDATE()
				WHERE BillNumberId=@nBillID AND BillType=@nBillType
			END
		END
	END
	
	-- commit tran AuditingTrans
	RETURN 0

	-- 错误信息，将回滚
	ERROR1:
	CLOSE Auditing_Cursor
	DEALLOCATE Auditing_Cursor
	--rollback tran AuditingTrans
	-- 返回商品 ID 值
	SET @szPID = @szPTypeIDTemp
	SET @KTypeID = @szKTypeIDTemp
	IF @nBillType = 160 AND @nRet = -5
	BEGIN
		IF @dQty < 0 SET @nRet = -15	-- 出库
		ELSE SET @nRet = -16			-- 入库
	END
	RETURN @nRet

	ERROR2:
	CLOSE Auditing_Cursor
	DEALLOCATE Auditing_Cursor
	-- rollback tran AuditingTrans
	RETURN -2

	ERROR3:
	CLOSE wx_Cursor
	DEALLOCATE wx_Cursor
	-- 返回商品 ID 值
	SET @szPID = @szPTypeIDTemp
	SET @KTypeID = @szKTypeIDTemp
	RETURN @nRet

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_AuditingDelivery',N'P'))
BEGIN
	DROP PROC GP_AuditingDelivery
END
GO
/*
	说明: 门店调拨类单据过账(门店调拨配送单、门店配送退货单、门店验收单)
	日期: 2019-12-03
	
*/
CREATE PROC GP_AuditingDelivery
(
	@BillNumberID	INT,
	@BillType		INT,
	@chvOpID		VARCHAR(50)
)
AS
BEGIN
	DECLARE @FullName VARCHAR(256),
			@STypeID VARCHAR(100),
		    @nRet    INT
		    
	/*-----------------------------------基础验证-----------------------------------*/
    IF @BillType IN(327,328,329) 
    BEGIN
        SELECT  @STypeID = Stypeid FROM dbo.PosAllotApplyBillIndex WHERE   BillNumberId = @BillNumberID
    END
		
	/*过账权限*/
	EXEC @nRet=Gp_CheckLimitBillType @chvOpID,0,@billtype
	IF @nRet<>1 RETURN 1000 /*没有单据过账的权限*/
	SET  @nRet = 0
	
	IF @BillType IN(327,328,329) AND NOT EXISTS(SELECT 1 FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f')
	BEGIN
		RETURN 1111  /*该单据不存在或已过账*/
	END

	IF EXISTS(SELECT AuditingID FROM AuditingFlowSet WHERE BillType=@BillType AND Stypeid=@STypeID AND IfUse=1)
	BEGIN
		IF EXISTS(SELECT 1 FROM dbo.AuditingBill WHERE BillNumberID = @BillNumberID AND IfAudit = 0 )
		BEGIN
			RETURN  1122  /*该单据需要审核*/
		END
	END 
	
	/*---------------------------------基础验证结束---------------------------------*/
	DECLARE
			@sql					VARCHAR(5000),
			@detailBillID			INT,						--单据明细ID
			@datBillDate			DATETIME,					-- 单据日期
			@chvATypeID				VARCHAR(50),				-- 收付款账户 ID 值
			@chvBTypeID				VARCHAR(50),				-- 结算单位
			@chvDealBTypeID			VARCHAR(50),				-- 往来单位
			@chvETypeID				VARCHAR(50),				-- 经手人 ID 值
			@chvKTypeID				VARCHAR(50),				-- 出库仓库 ID 值
			@chvKTypeID2			VARCHAR(50),				-- 入库仓库 ID 值
			@BackQty				NUMERIC(24,10),				--退货数量
			@InQty					NUMERIC(24,10),				--门店配送数量
			@chvDTypeID				VARCHAR(50),				-- 部门
			@numTotalMoney			NUMERIC(24, 10) ,			-- 单据金额合计
			@numTotalInMoney		NUMERIC(24, 10) ,			-- 单据实收、实付金额
			@numPreferenceMoney		NUMERIC(24, 10) ,
			@numNTotalMoney			NUMERIC(24, 10) ,
			@numNTotalInMoney		NUMERIC(24, 10) ,
			@numNPreferenceMoney	NUMERIC(24, 10) ,
			@wxTotal				NUMERIC(24, 10) ,	
			@numTax					NUMERIC(24, 10) ,
			@ifIndexWX				TINYINT,
			@intCostSale			TINYINT,
			@intCID					INT,
			@ifCheck				VARCHAR(10),				-- 是否草稿标识，f - 草稿；t - 已过账
			@IfMulAccount			TINYINT,
			@intVipCardID			INT,
			@BillName				VARCHAR(100),
			@NumRate				NUMERIC(24, 10) ,
			@AssetBusinessTypeId    INT,
			@intRedWord				TINYINT,
			@intNewPosBill			TINYINT,
			@AuditType				INT,
			@IfLend					INT=0,
			@datPostTime			DATETIME,
			@KTypeID				VARCHAR(50),	
			@VipCardCode			varchar(100),
			@vipCentInfo			varchar(100),
			@voucherMsg				VARCHAR(100),			--返回错误信息
			@szPID					VARCHAR(100)			-- 返回出错商品 ID 值


	SELECT @datBillDate=BillDate,@STypeID=StypeId,@BackQty=Qty,@chvKTypeID= InKtypeId,@chvKTypeID2=KtypeId,
	       @ifCheck = IfCheck,@chvBTypeID = '',@chvDealBTypeID='',@chvDTypeID = '',@intRedWord=RedWord
	FROM PosAllotApplyBillIndex  WHERE 	BillNumberID = @BillNumberID
			
				
	SELECT	@BillName=detailTable
	FROM	BillName
	WHERE	Billtype=@BillType
	
			
			
	--===================================测试======================================--
			
	--过账前控制（软件狗等）
	EXEC @nRet=Gp_Auditing_Control @STypeID,@BillType	
	IF @nRet<>0 RETURN @nRet
	
	--985新增单据判断（先取消）
	--EXEC @nRet=GP_Auditing_BillInfo @BillNumberID,@BillType
	--IF @nRet <> 0 RETURN 32863
	
	 --过账前的控制
	EXEC @nRet=Gp_Auditing_Control @STypeID
	IF @nRet<>0 RETURN @nRet
	
	
	--单据索引、明细事前、事后校验（已更改脚本）
	--EXEC @nRet = GP_AuditingCheckBillData @BillNumberID,@BillType,'1'
	--	IF @nRet<>0 RETURN @nRet
	
	--修改数据
	--UPDATE BillIndex 
	--SET ARTOTAL = C.ARTOTAL,APTOTAL = C.APTOTAL,YSTOTAL= C.YSTOTAL,YFTOTAL= C.YFTOTAL
	--FROM 
	--(
	--	SELECT ISNULL(SUM(b.ARTOTAL),0) AS ARTOTAL, ISNULL(SUM(b.APTOTAL),0) AS APTOTAL,
	--		   ISNULL(SUM(b.YSTOTAL),0) AS YSTOTAL, ISNULL(SUM(b.YFTOTAL),0) AS YFTOTAL
	--	FROM BType_ArApTotal B WHERE b.BTypeID=@chvBTypeID AND b.STypeID=@STypeID
	--) C
	--WHERE BillIndex.Billnumberid=@BillNumberID
	

	
	
	
	--产生 InOuStockTable 中明细（已更改脚本）
	EXEC @nRet = Gp_CreateMx_new	@BillNumberID,328,@datBillDate,
									'','','',
									'',@BackQty,@chvKTypeID,
									'',@STypeID,0 ,
									0 ,0 ,0 ,
									0 ,0 ,'' ,'' ,
									1,''
									
		IF @nRet <> 0 RETURN 32891
	
	
	--往来过账(已加入单据类型)
	EXEC @nRet = GP_AuditArAp	
	@BillNumberID,0,@BillType,@datBillDate,'','','',@chvKTypeID,@chvKTypeID2,
	'',@STypeID,100,10,0,100,
	100,0,1,0,0,0,0,0,
	1,0,0,0,@szPID OUTPUT,@vipCentInfo output,@VipCardCode OUT

	IF @nRet <> 0  RETURN 3284 --往来过账失败

	
	
	
	
--处理品牌 往来过账

	--EXEC @nRet = GP_AuditBrandarArAp @BillNumberID,@BillType
	--IF @nRet <> 0
	--BEGIN
	--	ROLLBACK TRAN auditPoint
	--	COMMIT TRAN audit
	--	RETURN @nRet
	--END
	
	
	


		--数据检查（已加入单据类型）
		EXEC @nRet = GP_AuditingATypeBalanceCheck @BillNumberID,328, @szPID OUTPUT
		IF @nRet <> 0 RETURN 3285 --单据过账，检测 现金/银行 账户的余额经过扣减后，是否为负 
		
					select * from ListTable
select * from atype_total
			return
			
		
	--核心过账，继创建明细之后的成本数据变化
	EXEC @nRet = Gp_AuditingCore	@BillNumberID, 
									'', 
									@chvOpID,
									@BillType,
									@datBillDate,
									@chvATypeID,
									@chvBTypeID,
									@chvETypeID,
									@chvKTypeID,
									@chvKTypeID2,
									@STypeID,
									@numTotalMoney,
									@numTotalInMoney,
									@ifCheck,
									@szPID OUTPUT, 
									@KTypeID OUTPUT

		
--如果是基础版，就不处理序列号了
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'Edition' AND SubValue = 1)
BEGIN
	DECLARE 
		@SQLS NVARCHAR(MAX),
		@intDealSerial	TINYINT
		
	SET @SQLS='IF EXISTS(SELECT BillNumberID FROM '+@BillName+' WHERE BillNumberId='+CAST(@BillNumberID AS VARCHAR(50))+' AND CAST(Serial AS VARCHAR(MAX))<>'''') SET @intDealSerial=1 ELSE SET @intDealSerial=0'
	EXECUTE sp_executesql @SQLS,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT		
		
	IF @intDealSerial=0
	BEGIN
		SET @SQLS='IF EXISTS(SELECT a.BillNumberID FROM '+@BillName+' a 
		INNER JOIN PType b ON a.PTypeID=b.TypeID
		WHERE a.BillNumberId='+CAST(@BillNumberID AS VARCHAR(50))+' AND b.IfSerial=1) SET @intDealSerial=1 ELSE SET @intDealSerial=0'
		EXECUTE sp_executesql @SQLS,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
	END		

	--IF @intDealSerial=1
	--BEGIN
	--	EXEC @nRet = Gp_SerialOperate_Manager @BillNumberID,'',@chvOpID,
	--	'',@ifIndexWX,@chvBTypeID,@STypeID,@szPID OUTPUT,@Billtype
		
	--	print @nRet
		
	--	IF @nRet IN (-904,-907)
	--	BEGIN
	--		EXEC GP_Auditing_ReturnMsg
	--			@nRet,
	--			@BillType,
	--			@BillNumberID
	--	END

	--	IF @nRet <> 0 RETURN 32882
	--END
END
	
	
	
		
--非物流单据，处理货位，批号，自由项等

	EXEC GP_Auditing_DealQty
	@BillNumberID,
	@BillType,
	0,
	@chvDealBTypeID,
	@chvBTypeID,
	@STypeID,
	@szPID	OUT,
	@nRet	OUT
	
	
	
	
	

--过账后处理草稿库存
EXEC GP_AuditingORDel_DraftQTY @BillNumberID,328

	
	
	

--过账后对单据完整性进行检测
--EXEC @nRet = GP_AuditingCheck @BillNumberID,328
--IF @nRet <> 0 RETURN 3286 
	
	
	
-- 检测销售、采购单关联订单的完成状态
--EXEC @nRet = GP_AuditingCheckOrderState @BillNumberID,1
--IF @nRet <> 0 RETURN 32861

	
--根据实际过账，更新成本调价单的数量（以前是在保存时，由页面写入的数量）
--EXEC Gp_Auditing_Fill @BillNumberID,@BillType

	

--EXEC @nRet = GP_AuditingCheckBillData @BillNumberID,328,'1'	
--IF @nRet <> 0 
--BEGIN
--	RETURN 3283 --单据索引、明细事前、事后校验 失败
--END


	
	
	--销售退货日
	--UPDATE	dbo.btype
	--SET		ltsalertday=@datBillDate
	--WHERE	Typeid=@chvDealBTypeID
	
	
	
	
--IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
--	AND	EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'postingparameter' AND SubValue = 0)--即时过账，即时生成凭证
--	AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'aloneusebsys' AND SubValue = 0)--使用总账系统
--	AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id=object_id('V1ZTINFO') AND TYPe='U')
--BEGIN
--	DECLARE @atid INT	
--	SELECT @atid = 0 FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId = @BillNumberID

--	EXEC @nRet = dbo.Gp_AutoCreate_Voucher @BillNumberID,@chvOpID,@atid,'',@voucherMsg OUTPUT,@BillType
	
--	IF @nRet <> 0 RETURN 32881
--END
--ELSE
--	SET @voucherMsg = ''
	
	
	
	
--影响 BType、AType 数据表中的应收应付数据
EXEC @nRet = GP_AuditingCheckMoveBillState @BillNumberID,328
IF @nRet <> 0	RETURN 3289

	
	
	
UPDATE dbo.PosAllotApplyBillIndex SET ifcheck='t',draft=0 WHERE BillNumberId=@BillNumberID

RETURN 0
	
END
GO




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





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：过账或删除单据处理草稿库存
	返回结果：
	作    者：施训果
	创建时间：2017-03-03
	修改历史：
	
*/
CREATE          PROCEDURE GP_AuditingORDel_DraftQTY
(
	@BillNumberID	INT,
	@BillType		INT
)

--@encode$--
AS

DECLARE @EffectFlag CHAR(4) = '-'	-- -：普通单据过账或删除单据负向影响草稿库存

EXECUTE GP_Deal_DraftQTY @BillNumberID,@BillType,@EffectFlag	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_AuditingPriceTrack]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].[Gp_AuditingPriceTrack]
GO

-- ===============================
-- 9.4 价格跟踪调整 修改存储过程
-- 三个价格都要记录，取由页面控制
-- 周华 2014-04-25
-- 2014-06-19 修改了写多条数据问题
-- 2015-04-29 新增写入销售出库单、委托代销发货单 销售价格 到 PType_STypePrice的RecSalePrice 字段(最近售价)
-- ===============================
CREATE   PROCEDURE Gp_AuditingPriceTrack 
( 
   @nBillId		NUMERIC(10, 0),
   @szBillType	NUMERIC(5),
   @szbTypeId	VARCHAR(50),
   @szStypeId	VARCHAR(50),
   @szKTypeID	VARCHAR(50),
   @szETypeID	VARCHAR(50),
   @vipcard		VARCHAR(50) = '',
   @chvBillDate	VARCHAR(100)= '',	-- 单据日期
   @cid			INT, --币别
   @btypeFlag	int=0 --结算单位还是往来单位
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	
	----如果往来/结算单位没有启用价格跟踪选项,则不跟踪
	----分支机构调拨单无往来单位，结算单位，跳过单位是否启用价格跟踪选项判断
	IF @szBillType NOT IN (187,188) AND NOT EXISTS (SELECT 1 FROM btype WHERE typeId=@szbTypeId AND PriceTrackEnable=1)
	   RETURN ;

	-- 最近进价
	-- 最近进价一直要记录
	--增加分支机构间最近进价
	IF @szBillType=34
	BEGIN
		MERGE PType_Price AS t
		USING(
			SELECT	a.PtypeId,
					MDiscountPrice,
					a.MUnitID,
					ext.IsDefaultUnit 
			FROM	dbo.BuyBill a
			INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
			WHERE	BillNumberId=@nBillId 
					AND IsGift<>1 
					AND PriceSource<>'兑换券' 
					AND PriceSource<>'折扣券'
					AND NOT EXISTS(
										SELECT	1 
										FROM	dbo.BuyBill b
										WHERE	b.BillNumberId=@nBillId 
												AND a.ID<b.ID 
												AND a.PtypeId=b.PtypeId 
												AND A.MUnitID=B.MUnitID 
												AND a.Stypeid=b.Stypeid 
												AND IsGift<>1 
												AND PriceSource<>'兑换券' 
												AND PriceSource<>'折扣券'
			)
		) AS s ON t.PTypeID=s.PtypeId AND T.UnitID=S.MUnitID
		WHEN MATCHED THEN 
			UPDATE SET t.RecAmgSTypeBuyPrice=s.MDiscountPrice,T.IsDefaultUnit=S.IsDefaultUnit
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,RecAmgSTypeBuyPrice,UnitID,ISDefaultUnit) VALUES(s.Ptypeid,s.MDiscountPrice,s.MUnitID,s.IsDefaultUnit)
		;
		
		MERGE PType_STypePrice AS t
		USING(
			SELECT	StypeId,
					a.PtypeId,
					MDiscountPrice,
					a.MUnitID,
					ext.IsDefaultUnit 
			FROM	dbo.BuyBill a
			INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
			WHERE	BillNumberId=@nBillId 
					AND IsGift<>1 
					AND PriceSource<>'兑换券' 
					AND PriceSource<>'折扣券'
					AND NOT EXISTS(
									SELECT	1 
									FROM	dbo.BuyBill b 
									WHERE	b.BillNumberId=@nBillId 
											AND a.ID<b.ID 
											AND a.PtypeId=b.PtypeId  
											AND A.MUnitID=B.MUnitID 
											AND a.Stypeid=b.Stypeid 
											AND IsGift<>1 
											AND PriceSource<>'兑换券' 
											AND PriceSource<>'折扣券'
									)
		) AS s ON t.STypeID=s.Stypeid AND t.PTypeID=s.PtypeId AND T.UnitID=S.MUnitID
		WHEN MATCHED THEN 
			UPDATE SET t.RecPrice=s.MDiscountPrice,T.IsDefaultUnit=S.IsDefaultUnit
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (STypeId,PtypeId,RecPrice,UnitID,ISDefaultUnit) VALUES(s.StypeId,s.Ptypeid,s.MDiscountPrice,s.MUnitID,s.IsDefaultUnit)
		;
		EXEC Gp_DataSaveForPosDown '-99999','PType_Price','0'
	END
	
	----------------------最近售价-------------------------
	
	DECLARE @indexPromonIds varchar(200)
	SELECT	@indexPromonIds =PromonIds 
	FROM	BillIndex 
	WHERE	BillNumberId = @nBillId 
			AND ISNULL(PromonIds,'')<>''
	
	if @szBillType in(11,12,305) and exists(select top 1 1 from PromoRule where ID in(select a from f_split(@indexPromonIds,',')) and PConfig = 0)
		RETURN
		
	CREATE TABLE #PromoRule(ID NUMERIC(18,0),CalculateStyle INT,PConfig INT)	
	
	INSERT INTO #PromoRule(ID,CalculateStyle,PConfig)
	SELECT	ID,CalculateStyle,PConfig 
	FROM	PromoRule 
	WHERE	ID IN(SELECT a FROM f_split(@indexPromonIds,',')) 
			AND ISNULL(CalculateStyle,0) = 0
	
	CREATE TABLE #ptypes (ptypeid varchar(50),billid bigint)
	
	---------------记录销售出库单商品销售价格--------------
	IF @szBillType=11
	BEGIN
		CREATE TABLE #TempSaleBill(
			BillNumberId		NUMERIC(18,0),
			PTypeId				VARCHAR(50),
			STypeId				VARCHAR(50),
			MDiscountPrice		NUMERIC(24,10),
			MUnitID				INT,
			ID					NUMERIC(18,0),
			PromonIds			VARCHAR(1000),
			IsDefaultUnit		INT
		)

		INSERT INTO #TempSaleBill(BillNumberId,PTypeId,STypeId,MDiscountPrice,MUnitID,ID,PromonIds,IsDefaultUnit) 
		SELECT	A.BillNumberId,A.PTypeId,A.STypeId,A.MDiscountPrice,A.MUnitID,A.ID,A.PromonIds,ext.IsDefaultUnit 
		FROM	SaleBill a WITH(NOLOCK) 
		INNER JOIN dbo.PType_Units_Ext ext WITH(NOLOCK) ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
		WHERE	A.BillNumberId = @nBillId
				AND A.IsGift<>1 
				AND A.PriceSource<>'兑换券' 
				AND A.PriceSource<>'折扣券'
				AND A.PriceSource<>'简易促销'

		INSERT INTO #ptypes(ptypeid,billid)
		SELECT	s.PtypeId,s.ID
		FROM	#TempSaleBill s 
		WHERE	s.BillNumberId = @nBillId 
				AND s.PromonIds = '' 
				AND NOT EXISTS(select top 1 pdp.Ptypeid from PromoRule_Detail_PConfig pdp inner join #PromoRule p on p.ID = pdp.PromoRuleID where pdp.Ptypeid= s.PtypeId)

		--分支机构间商品最近价格
		MERGE INTO PType_Price AS t
		USING(
			SELECT	DISTINCT a.PtypeId,a.MDiscountPrice,a.MUnitID,a.IsDefaultUnit 
			FROM	#TempSaleBill a
			WHERE	BillNumberId=@nBillId 				
					AND NOT EXISTS(
										SELECT	1 
										FROM	#TempSaleBill b
										WHERE	b.BillNumberId=@nBillId 
												AND a.ID<b.ID 
												AND a.PtypeId=b.PtypeId 
												AND A.MUnitID=B.MUnitID 
												AND a.Stypeid=b.Stypeid 											
								)
		) AS s ON t.PTypeID=s.PtypeId AND T.UnitID=S.MUnitID
		WHEN MATCHED THEN 
			UPDATE SET t.RecAmgSTypeSalePrice=s.MDiscountPrice,T.IsDefaultUnit=S.IsDefaultUnit
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,RecAmgSTypeSalePrice,UnitID,ISDefaultUnit) VALUES(s.Ptypeid,s.MDiscountPrice,s.MUnitID,s.IsDefaultUnit)
		;

		MERGE INTO PType_STypePrice AS T 
		USING(
			SELECT	DISTINCT a.StypeId,a.PTypeId,a.MDiscountPrice,a.MUnitID,a.IsDefaultUnit 
			FROM	#TempSaleBill A
			WHERE	BillNumberId=@nBillId 
					AND NOT EXISTS(
									SELECT	1 
									FROM	#TempSaleBill B  									
									WHERE	b.BillNumberId=@nBillId 
											AND A.Id<B.Id 
											AND a.PTypeId=b.PTypeId 
											AND A.MUnitID=B.MUnitID											
								  )
		) AS S  ON T.STypeId=S.StypeId AND T.PTypeId=S.PTypeId AND T.UnitID=S.MUnitID
		WHEN MATCHED THEN
			UPDATE SET T.RecSalePrice=S.MDiscountPrice,T.IsDefaultUnit=S.IsDefaultUnit
		WHEN NOT MATCHED BY TARGET THEN
			INSERT (StypeId,PtypeId,RecSalePrice,UnitID,IsDefaultUnit) VALUES(S.STypeId,S.PTypeId,S.MDiscountPrice,s.MUnitID,s.IsDefaultUnit);
			
		DROP TABLE #TempSaleBill	
	END
	
	--98.1 Bug 985
	IF @szBillType=305
	BEGIN
		--组合品样式
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@nBillId AND iscombinationstyle=1)
		BEGIN
			insert into #ptypes(ptypeid,billid)
			select s.PtypeId,s.ID
			from RetailCombinationBill s 
			where s.BillNumberId = @nBillId 
				and s.PromonIds = '' 
				and not exists(select top 1 pdp.Ptypeid from PromoRule_Detail_PConfig pdp inner join #PromoRule p on p.ID = pdp.PromoRuleID where pdp.Ptypeid= s.PtypeId)
		
			--分支机构间商品最近价格
			MERGE PType_Price AS t
			USING(
				SELECT distinct a.PtypeId,MDiscountPrice,a.MUnitID,ext.IsDefaultUnit FROM dbo.RetailCombinationBill a
				INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
				inner join #ptypes p on p.ptypeid = a.ptypeid and p.billid = a.id
				WHERE BillNumberId=@nBillId AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券'
				AND NOT EXISTS(SELECT 1 FROM dbo.RetailCombinationBill b  inner join #ptypes p on p.billid = b.id
				WHERE b.BillNumberId=@nBillId AND a.ID<b.ID AND a.PtypeId=b.PtypeId AND a.Stypeid=b.Stypeid  AND A.MUnitID=B.MUnitID AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券')
			) AS s ON t.PTypeID=s.PtypeId AND T.UnitID=S.MUnitID
			WHEN MATCHED THEN 
				UPDATE SET t.RecAmgSTypeSalePrice=s.MDiscountPrice,T.UnitID=S.MUnitID,T.IsDefaultUnit=S.IsDefaultUnit
			WHEN NOT MATCHED BY TARGET THEN 
				INSERT (PtypeId,RecAmgSTypeSalePrice,UnitID,ISDefaultUnit) VALUES(s.Ptypeid,s.MDiscountPrice,s.MUnitID,s.IsDefaultUnit)
			;

			MERGE INTO PType_STypePrice AS T 
			USING(
				SELECT distinct StypeId,a.PTypeId,MDiscountPrice,a.MUnitID,ext.IsDefaultUnit FROM dbo.RetailCombinationBill A 
				INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
				inner join #ptypes p on p.ptypeid = a.ptypeid and p.billid = a.id
				WHERE BillNumberId=@nBillId AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券'
				AND NOT EXISTS(SELECT 1 FROM dbo.RetailCombinationBill B  inner join #ptypes p on p.billid = b.id
				WHERE b.BillNumberId=@nBillId AND A.Id<B.Id AND a.PTypeId=b.PTypeId AND A.MUnitID=B.MUnitID AND IsGift<>1
				AND PriceSource<>'兑换券' AND PriceSource<>'折扣券')
			) AS S  ON T.STypeId=S.StypeId AND T.PTypeId=S.PTypeId AND T.UnitID=S.MUnitID
			WHEN MATCHED THEN
				UPDATE SET T.RecSalePrice=S.MDiscountPrice,T.UnitID=S.MUnitID,T.IsDefaultUnit=S.IsDefaultUnit
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (StypeId,PtypeId,RecSalePrice,UnitID,IsDefaultUnit) VALUES(S.STypeId,S.PTypeId,S.MDiscountPrice,s.MUnitID,s.IsDefaultUnit);
		END
		ELSE
		BEGIN
			insert into #ptypes(ptypeid,billid)
			select s.PtypeId,s.ID
			from retailBill s 
			where s.BillNumberId = @nBillId 
				and s.PromonIds = '' 
				and not exists(select top 1 pdp.Ptypeid from PromoRule_Detail_PConfig pdp inner join #PromoRule p on p.ID = pdp.PromoRuleID where pdp.Ptypeid= s.PtypeId)
		
			MERGE PType_Price AS t
			USING(
				SELECT distinct a.PtypeId,MDiscountPrice,a.MUnitID,ext.IsDefaultUnit FROM dbo.retailBill a
				INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
				inner join #ptypes p on p.ptypeid = a.ptypeid and p.billid = a.id
				WHERE BillNumberId=@nBillId AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券'
				AND NOT EXISTS(SELECT 1 FROM dbo.retailBill b  inner join #ptypes p on p.billid = b.id
				WHERE b.BillNumberId=@nBillId AND a.ID<b.ID AND a.PtypeId=b.PtypeId AND a.Stypeid=b.Stypeid  AND A.MUnitID=B.MUnitID AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券')
			) AS s ON t.PTypeID=s.PtypeId AND T.UnitID=S.MUnitID
			WHEN MATCHED THEN 
				UPDATE SET t.RecAmgSTypeSalePrice=s.MDiscountPrice,T.UnitID=S.MUnitID,T.IsDefaultUnit=S.IsDefaultUnit
			WHEN NOT MATCHED BY TARGET THEN 
				INSERT (PtypeId,RecAmgSTypeSalePrice,UnitID,ISDefaultUnit) VALUES(s.Ptypeid,s.MDiscountPrice,s.MUnitID,s.IsDefaultUnit)
			;

			MERGE INTO PType_STypePrice AS T 
			USING(
				SELECT distinct StypeId,a.PTypeId,MDiscountPrice,a.MUnitID,ext.IsDefaultUnit FROM dbo.retailBill A 
				INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
				inner join #ptypes p on p.ptypeid = a.ptypeid and p.billid = a.id
				WHERE BillNumberId=@nBillId AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券'
				AND NOT EXISTS(SELECT 1 FROM dbo.retailBill B  inner join #ptypes p on p.billid = b.id
				WHERE b.BillNumberId=@nBillId AND A.Id<B.Id AND a.PTypeId=b.PTypeId AND A.MUnitID=B.MUnitID AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券')
			) AS S  ON T.STypeId=S.StypeId AND T.PTypeId=S.PTypeId AND T.UnitID=S.MUnitID
			WHEN MATCHED THEN
				UPDATE SET T.RecSalePrice=S.MDiscountPrice,T.UnitID=S.MUnitID,T.IsDefaultUnit=S.IsDefaultUnit
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (StypeId,PtypeId,RecSalePrice,UnitID,IsDefaultUnit) VALUES(S.STypeId,S.PTypeId,S.MDiscountPrice,s.MUnitID,s.IsDefaultUnit);
		END
	END
	
	IF @szBillType=12
	BEGIN
		insert into #ptypes(ptypeid,billid)
		select s.PtypeId,s.ID
		from PT_Combin_SaleBill s 
		where s.BillNumberId = @nBillId 
			and s.PromonIds = '' 
			and not exists(select top 1 pdp.Ptypeid from PromoRule_Detail_PConfig pdp inner join #PromoRule p on p.ID = pdp.PromoRuleID where pdp.Ptypeid= s.PtypeId)
		
		--分支机构间商品最近价格
		MERGE PType_Price AS t
		USING(
			SELECT distinct a.PtypeId,MDiscountPrice,a.MUnitID,ext.IsDefaultUnit FROM dbo.PT_Combin_SaleBill a
			INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
			inner join #ptypes p on p.ptypeid = a.ptypeid and p.billid = a.id
			WHERE BillNumberId=@nBillId AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券'
			AND NOT EXISTS(SELECT 1 FROM dbo.PT_Combin_SaleBill b  inner join #ptypes p on p.billid = b.id
			WHERE b.BillNumberId=@nBillId AND a.ID<b.ID AND a.PtypeId=b.PtypeId AND a.Stypeid=b.Stypeid AND  A.MUnitID=B.MUnitID AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券')
		) AS s ON t.PTypeID=s.PtypeId AND T.UnitID=S.MUnitID
		WHEN MATCHED THEN 
			UPDATE SET t.RecAmgSTypeSalePrice=s.MDiscountPrice,T.UnitID=S.MUnitID,T.IsDefaultUnit=S.IsDefaultUnit
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,RecAmgSTypeSalePrice,UnitID,ISDefaultUnit) VALUES(s.Ptypeid,s.MDiscountPrice,s.MUnitID,s.IsDefaultUnit)
		;

		MERGE INTO PType_STypePrice AS T 
		USING(
			SELECT distinct StypeId,a.PTypeId,MDiscountPrice,a.MUnitID,ext.IsDefaultUnit FROM dbo.PT_Combin_SaleBill A 
			INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
			inner join #ptypes p on p.ptypeid = a.ptypeid and p.billid = a.id
			WHERE BillNumberId=@nBillId AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券'
			AND NOT EXISTS(SELECT 1 FROM dbo.PT_Combin_SaleBill B  inner join #ptypes p on p.billid = b.id
			WHERE b.BillNumberId=@nBillId AND A.Id<B.Id AND a.PTypeId=b.PTypeId AND A.MUnitID=B.MUnitID AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券')
		) AS S  ON T.STypeId=S.StypeId AND T.PTypeId=S.PTypeId AND T.UnitID=S.MUnitID
		WHEN MATCHED THEN
			UPDATE SET T.RecSalePrice=S.MDiscountPrice,T.UnitID=S.MUnitID,T.IsDefaultUnit=S.IsDefaultUnit
		WHEN NOT MATCHED BY TARGET THEN
			INSERT (StypeId,PtypeId,RecSalePrice,UnitID,IsDefaultUnit) VALUES(S.STypeId,S.PTypeId,S.MDiscountPrice,s.MUnitID,s.IsDefaultUnit);
	END
	
	---------------------最近售价结束------------------------
	
	--------------------最近暂估入库价格---------------------
	IF @szBillType=400
	BEGIN
		--UPDATE A SET a.RecAmgSTypeBuyPrice=b.DiscountPrice
		--FROM PType_Price A JOIN (
		--	SELECT PtypeId,DiscountPrice FROM dbo.AppraisalBill a WHERE BillNumberId=@nBillId AND IsGift<>1
		--	AND NOT EXISTS(SELECT 1 FROM dbo.AppraisalBill b WHERE a.ID<b.ID AND a.PtypeId=b.PtypeId AND IsGift<>1)
		--) B ON A.PtypeId=b.PtypeId
		
		MERGE INTO PType_STypePrice AS T 
		USING(
			SELECT StypeId,a.PTypeId,MDiscountPrice,a.MUnitID,ext.IsDefaultUnit FROM dbo.AppraisalBill A 
			INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
			WHERE BillNumberId=@nBillId AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券'
			AND NOT EXISTS(SELECT PTypeId FROM dbo.AppraisalBill B 
			WHERE b.BillNumberId=@nBillId AND A.Id<B.Id AND a.PTypeId=b.PTypeId AND A.MUnitID=B.MUnitID AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券')
		) AS S  ON T.STypeId=S.StypeId AND T.PTypeId=S.PTypeId AND T.UnitID=S.MUnitID
		WHEN MATCHED THEN
			UPDATE SET T.RecAppraisalPrice=S.MDiscountPrice,T.UnitID=S.MUnitID,T.IsDefaultUnit=S.IsDefaultUnit
		WHEN NOT MATCHED BY TARGET THEN
			INSERT (StypeId,PtypeId,RecAppraisalPrice,UnitID,IsDefaultUnit) VALUES(S.STypeId,S.PTypeId,S.MDiscountPrice,s.MUnitID,s.IsDefaultUnit);
		;
	END

	-------------------最近暂估入库价格结束------------------
	
	---------------------最近发出商品出库价格----------------
	
	IF @szBillType=402
	BEGIN
		--分支机构物价信息		
		MERGE INTO PType_STypePrice AS T 
		USING(
			SELECT StypeId,a.PTypeId,MDiscountPrice,a.MUnitID,ext.IsDefaultUnit FROM dbo.SendBill A 
			INNER JOIN dbo.PType_Units_Ext ext ON A.PtypeId=ext.PtypeID AND a.MUnitID=ext.UnitsId
			WHERE BillNumberId=@nBillId AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券'
			AND NOT EXISTS(SELECT PTypeId FROM dbo.SendBill B 
			WHERE b.BillNumberId=@nBillId AND A.Id<B.Id AND a.PTypeId=b.PTypeId AND A.MUnitID=B.MUnitID AND IsGift<>1 AND PriceSource<>'兑换券' AND PriceSource<>'折扣券')
		) AS S  ON T.STypeId=S.StypeId AND T.PTypeId=S.PTypeId AND T.UnitID=S.MUnitID
		WHEN MATCHED THEN
			UPDATE SET T.RecSendPrice=S.MDiscountPrice,T.UnitID=S.MUnitID,T.IsDefaultUnit=S.IsDefaultUnit
		WHEN NOT MATCHED BY TARGET THEN
			INSERT (StypeId,PtypeId,RecSendPrice,UnitID,IsDefaultUnit) VALUES(S.STypeId,S.PTypeId,S.MDiscountPrice,s.MUnitID,s.IsDefaultUnit);	
	END
	-------------------最近发出商品出库价格结束--------------
	
	---------------------分支机构调拨价格--------------------
	--调拨出库
	IF @szBillType=187 AND EXISTS(SELECT 1 FROM PriceTrackConfig WHERE Name='dbckpricetrack' AND Value=1)
	BEGIN
		MERGE INTO PriceTrack_STypeMove AS T
		USING(
			SELECT     A.UnitId,
					   A.Stypeid AS OutStypeId,
					   B.STypeId AS InStypeId,
					   A.PTypeID,
					   A.MPrice,
					   D.CID,
					   A.BillType,
					   D.tax,
					   A.MPrice*D.Tax AS TaxPrice,
					   D.Discount
			FROM STypeMoveBill A 
			INNER JOIN Stock B ON  
					   A.KTypeID2=B.typeId AND 
					   A.BillType=187 AND 
					   A.BillNumberID=@nBillID AND 
					   NOT EXISTS (SELECT PtypeId FROM dbo.STypeMoveBill C 
					   WHERE c.BillNumberId=@nBillId AND A.ID<C.ID AND a.PtypeId=C.PtypeId AND C.BillType=187)
			INNER JOIN BillIndex D ON 
					   A.BillNumberID=D.BillNumberID AND 
					   A.BillType=D.BillType
					   
			) AS S ON  T.PTypeId=S.PTypeId AND 
					   T.CID=S.CID AND 
					   T.UnitID=S.UnitID AND 
					   T.OutSTypeID=S.OutSTypeID AND 
					   T.InSTypeID=S.InSTypeID   AND
					   T.BillType=S.BillType

		WHEN MATCHED THEN
		UPDATE SET T.RecMovePrice=S.MPrice,T.DiscountRate=S.Discount,T.Tax=S.Tax,T.TaxPrice=S.TaxPrice,T.TrackTime=GETDATE()
		
		WHEN NOT MATCHED BY TARGET THEN
		INSERT (InSTypeId,OutSTypeId,PTypeId,UnitID,RecMovePrice,CID,BillType,DiscountRate,Tax,TaxPrice,TrackTime)
		VALUES (S.InSTypeID,S.OutSTypeID,S.PTypeID,S.UnitID,S.MPrice,S.CID,S.BillType,S.Discount,S.Tax,S.TaxPrice,GETDATE());
	END
	
	--调拨入库
	IF @szBillType=188 AND EXISTS(SELECT 1 FROM PriceTrackConfig WHERE Name='dbrkpricetrack' AND Value=1)
	BEGIN
		MERGE INTO PriceTrack_STypeMove AS T
		USING(
			SELECT	   A.UnitId,
					   A.Stypeid AS InStypeId,
					   B.STypeId AS OutStypeId,
					   A.PTypeID,
					   A.MPrice,
					   D.CID,
					   A.BillType,
					   D.Tax,
					   D.Tax*A.MPrice AS TaxPrice,
					   D.Discount
			FROM STypeMoveBill A 
			INNER JOIN Stock B ON 
					   A.KTypeID=B.typeId AND 
					   A.BillType=188 AND 
					   A.BillNumberID=@nbillID AND
					   NOT EXISTS (SELECT PtypeId FROM dbo.STypeMoveBill C 
					   WHERE c.BillNumberId=@nBillId AND A.ID<C.ID AND a.PtypeId=C.PtypeId AND C.BillType=188)
			
			INNER JOIN BillIndex D ON 
					   A.BillNumberID=D.BillNumberID AND 
					   A.BillType=D.BillType
					   
			) AS  S ON T.PTypeId=S.PTypeId AND 
					   T.CID=S.CID AND 
					   T.UnitID=S.UnitID AND 
					   T.OutSTypeID=S.OutSTypeID AND 
					   T.InSTypeID=S.InSTypeID   AND
					   T.BillType=S.BillType
					   
		WHEN MATCHED THEN
		UPDATE SET T.RecMovePrice=S.MPrice,T.DiscountRate=S.Discount,T.Tax=S.Tax,T.TaxPrice=S.TaxPrice,T.TrackTime=GETDATE()
		
		WHEN NOT MATCHED BY TARGET THEN
		INSERT (InSTypeId,OutSTypeId,PTypeId,UnitID,RecMovePrice,CID,BillType,DiscountRate,Tax,TaxPrice,TrackTime) 
		VALUES (S.InSTypeID,S.OutSTypeID,S.PTypeID,S.UnitID,S.MPrice,S.CID,S.BillType,S.Discount,S.Tax,S.TaxPrice,GETDATE());
	END
	
	-------------------分支机构调拨价格结束------------------
	-- 价格跟踪
	
	DECLARE  @TableName			VARCHAR(100)='',					--单据明细表
			 @TrackTbName		VARCHAR(100)='',				    --跟踪表
			 @buySaletype		INT=0,
			 @traceField		INT=0,								--跟踪字段
			 @updateFields		NVARCHAR(500)='',
			 @insertFields		NVARCHAR(500)='',
			 @selectFields_flags NVARCHAR(500)='',
			 @selectFields		NVARCHAR(500)='',
			 @where				NVARCHAR(500)='',
			 @billId			NVARCHAR(100)='id',
			 @sql				NVARCHAR(max),
			 @isgift			NVARCHAR(100)='',
			 @pt				NVARCHAR(100)='',
             @GridType			INT,--单据格式
			 @wherecoupon		NVARCHAR(100)='';--优惠券条件，折扣券、兑换券不价格跟踪
	SELECT @GridType=Value FROM dbo.Userconfig WHERE ConfigName='GridType'	
	SELECT @TrackTbName=TrackTableName,@buySaletype=BuySaleType FROM PriceTrackNameBillSet WHERE Billtype=@szBillType AND GetSetType=1;
	
	--分支机构调拨单据不能使用券，不判断
	IF @szBillType NOT IN (187,188,184)
		SET @wherecoupon=' AND PriceSource<>''兑换券'' AND PriceSource<>''折扣券''';
	
	IF @TrackTbName=''
		RETURN 
	SET @TableName=dbo.F_BillTableName(@szBillType);
	
	IF @szBillType=12		SET @TableName='PT_Combin_SaleBill'
	IF @szBillType=46		SET @TableName='PT_Combin_SaleBackBill'
	IF @szBillType=313		SET @TableName='PT_Combin_OrderBill'

	SELECT @traceField=value FROM PriceTrackConfig WHERE @buySaletype=1 AND Name='BuyPriceTrackField' OR @buySaletype=2 AND Name='SalePriceTrackField';
	
	SELECT @selectFields_flags='b.CurMSalePrice,b.Discount,b.CurMDiscountPrice,B.Tax,B.CurMTaxPrice'
		  ,@insertFields='price,discountRate,discountPrice,Tax,TaxPrice'
		  ,@updateFields='a.price=b.CurMSalePrice,a.discountRate=b.Discount,a.discountPrice=b.CurMDiscountPrice,A.Tax=b.Tax,A.TaxPrice=b.CurMTaxPrice,A.TrackTime=GETDATE()'
		  ,@selectFields='CurMSalePrice,Discount,CurMDiscountPrice,Tax,CurMTaxPrice'
		  ,@where=' AND (CurMSalePrice<>0 AND CurMDiscountPrice<>0)';
		  
	IF @GridType=3			--普通格式
	BEGIN
		SELECT @selectFields_flags='b.CurMSalePrice,1,b.CurMSalePrice,0,b.CurMSalePrice'
		SELECT @updateFields='a.price=b.CurMSalePrice,a.discountRate=1,a.discountPrice=b.CurMSalePrice,A.Tax=0,A.TaxPrice=b.CurMSalePrice,A.TrackTime=GETDATE()'
	END
	ELSE IF @GridType=2		--折扣模式
	BEGIN
		SELECT @selectFields_flags='b.CurMSalePrice,b.Discount,b.CurMDiscountPrice,0,b.CurMDiscountPrice'
		SELECT @updateFields='a.price=b.CurMSalePrice,a.discountRate=Discount,a.discountPrice=b.CurMDiscountPrice,A.Tax=0,A.TaxPrice=b.CurMDiscountPrice,A.TrackTime=GETDATE()'
	END
	ELSE IF @GridType=1		--税率模式
	BEGIN
		SELECT @selectFields_flags='b.CurMSalePrice,1,b.CurMSalePrice,b.Tax,b.CurMTaxPrice'
		SELECT @updateFields='a.price=b.CurMSalePrice,a.discountRate=1,a.discountPrice=b.CurMSalePrice,A.Tax=b.Tax,A.TaxPrice=b.CurMTaxPrice,A.TrackTime=GETDATE()'
	END
	ELSE					--全格式
	BEGIN
		SELECT @selectFields_flags='b.CurMSalePrice,b.Discount,b.CurMDiscountPrice,B.Tax,B.CurMTaxPrice'
		SELECT @updateFields='a.price=b.CurMSalePrice,a.discountRate=b.Discount,a.discountPrice=b.CurMDiscountPrice,A.Tax=b.Tax,A.TaxPrice=b.CurMTaxPrice,A.TrackTime=GETDATE()'
	END
	
	IF @szBillType IN (300,301,313)
		SET @billId='orderid';
	IF @szBillType NOT IN (184,185,140,142,141,144,146,145) --没有isgift字段的单据
		SET @isgift=' AND isgift<>1 ';
	IF @szBillType IN (11,12,30,300)
		SET @pt=' and promotype<>1'
	IF @szBillType=305
	BEGIN
		IF EXISTS(SELECT 1 FROM RetailCombinationBill WHERE BIllNumberID=@nBillId)
			SET @TableName='RetailCombinationBill'
	END		
	
	declare @innerstr varchar(100)
	set @innerstr = ''
	
	IF @szBillType in(11,12,305)
	BEGIN
		set @innerstr = ' inner join #ptypes p on p.ptypeid = t.ptypeid and p.billid = t.id '
	END

	----------------------正常价格跟踪-------------------------
	--没有启用不跟踪
	IF (@buySaletype=1 AND EXISTS(SELECT 1 FROM dbo.PriceTrackConfig WHERE Name='buypricetrack' AND Value=1))
		OR (@buySaletype=2 AND EXISTS(SELECT 1 FROM dbo.PriceTrackConfig WHERE Name='salepricetrack' AND Value=1))
	BEGIN
		SET @sql=N' MERGE ['+@TrackTbName+'] AS a 
			USING (
				SELECT @btypeid AS BtypeId,@stypeid AS STypeId,MUnitID as Uid,@cid as Cid,t.PTypeId,'+@selectFields+' 
				FROM	['+@TableName+'] t '+@innerstr+' 
				WHERE	BillNumberId=@bid '+@isgift+@where+@wherecoupon+ '
						AND '+@billId+' IN 
						(
							SELECT MAX('+@billid+') FROM ['+@TableName+'] x '
		
		--零售单、销售出库单、组合品销售出库单		
		IF @szBillType IN (11,12,305)		
		BEGIN 
			SET @SQL = @SQL +'
							INNER JOIN #ptypes p ON p.billid = x.id '
		END
		
		SET	@SQL = @SQL + '
							WHERE  BillNumberId=@bid '+@isgift+@wherecoupon+' GROUP BY x.STypeId,x.MUnitID,x.PTypeId
						)'
		
		SET @SQL = @SQL + @pt + '
			) AS b ON a.BtypeId=b.BtypeId AND a.PtypeId=b.PtypeId AND a.StypeId=b.StypeId AND a.Uid=b.Uid AND a.Cid=b.Cid AND a.BtypeFlag=@btypeFlag
			WHEN MATCHED THEN 
				UPDATE SET '+@updateFields+'
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (BtypeId,BtypeFlag,PtypeId,StypeId,UId,CId,TrackTime,'+@insertFields+') VALUES (b.BtypeId,@btypeflag,b.PtypeId,b.StypeId,b.UId,b.CId,GETDATE(),'+@selectFields_flags+');
			'	
			
		EXEC sp_executesql @sql,N'@btypeid varchar(50),@stypeid varchar(50),@cid int,@bid int,@btypeflag int',@szbTypeId,@szStypeId,@cid,@nBillId,@btypeFlag;
	END
	-------------------分支机构间价格跟踪--------------------
	SELECT @TrackTbName=TrackTableName,@buySaletype=BuySaleType FROM PriceTrackNameBillSet WHERE Billtype=@szBillType AND GetSetType=3;
	IF @TrackTbName=''
		RETURN
	
	IF (@buySaletype=1 AND EXISTS(SELECT 1 FROM dbo.PriceTrackConfig WHERE Name='buystypepricetrack' AND Value=1))
	OR (@buySaletype=2 AND EXISTS(SELECT 1 FROM dbo.PriceTrackConfig WHERE Name='salestypepricetrack' AND Value=1))
	BEGIN
		SET @sql=N' MERGE ['+@TrackTbName+'] AS a
		USING (
				SELECT @btypeid AS BtypeId,MUnitID as Uid,@cid as Cid,t.PTypeId,'+@selectFields+' FROM ['+@TableName+'] t '+@innerstr+ ' WHERE BillNumberId=@bid '+@isgift+@where+@wherecoupon+'
				AND '+@billId+' IN (SELECT MAX('+@billid+') FROM ['+@TableName+'] WHERE BillNumberId=@bid '+@isgift+@wherecoupon+' GROUP BY MUnitID,PTypeId)
				'+@pt+'
		) AS b ON a.BtypeId=b.BtypeId AND a.PtypeId=b.PtypeId AND a.Uid=b.Uid AND a.Cid=b.Cid AND a.BtypeFlag=@btypeFlag
		WHEN MATCHED THEN 
				UPDATE SET '+@updateFields+'
		WHEN NOT MATCHED BY TARGET THEN
			INSERT (BtypeId,BtypeFlag,PtypeId,UId,CId,TrackTime,'+@insertFields+') VALUES (b.BtypeId,@btypeflag,b.PtypeId,b.UId,b.CId,GETDATE(),'+@selectFields_flags+');
		'
		EXEC sp_executesql @sql,N'@btypeid varchar(50),@cid int,@bid int,@btypeflag int',@szbTypeId,@cid,@nBillId,@btypeFlag;
	END
	----------------分支机构间价格跟踪结束-----------------

	DROP TABLE #PromoRule,#ptypes	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/***
****		物流运输类单过账
****		运输配送单、上架单、拣货单
****/
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_AuditingWLBill',N'P'))
BEGIN
	DROP PROC GP_AuditingWLBill
END
GO
--物流类单据过账
CREATE PROC GP_AuditingWLBill
(
	@BillNumberID	INT,
	@BillType		INT,
	@chvOpID		VARCHAR(50)
)
AS
BEGIN
	DECLARE @STypeID VARCHAR(100),
		    @nRet    INT
	/***************验证*****************/
	/*系统验证*/
    IF @BillType IN(414,415) 
    BEGIN
        SELECT  @STypeID = Stypeid FROM    dbo.BillIndex WHERE   BillNumberId = @BillNumberID
    END
    ELSE
    BEGIN 
        SELECT  @STypeID = STypeID FROM    onShelvespickIndex  WHERE   billNumberId = @BillNumberID
	END
	EXEC @nRet=Gp_Auditing_Control @STypeID
	IF @nRet<>0 RETURN @nRet
		
	/*过账权限*/
	EXEC @nRet=Gp_CheckLimitBillType @chvOpID,0,@billtype
	IF @nRet<>1 RETURN 1000 /*没有单据过账的权限*/
	SET  @nRet = 0
	
	IF @BillType IN(414,415) AND NOT EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f')
	BEGIN
		RETURN 1111  /*该单据不存在或已过账*/
	END
	IF @BillType IN(412,413) AND NOT EXISTS(SELECT 1 FROM onShelvespickIndex WHERE BillNumberId=@BillNumberID AND IfCheck='f')
	BEGIN
		RETURN 1111  /*该单据不存在或已过账*/
	END

	IF EXISTS(SELECT AuditingID FROM AuditingFlowSet WHERE BillType=@BillType AND Stypeid=@STypeID AND IfUse=1)
	BEGIN
		IF EXISTS(SELECT 1 FROM dbo.AuditingBill WHERE BillNumberID = @BillNumberID AND IfAudit = 0 AND BillIndexType = CASE WHEN @BillType=414 THEN 2 ELSE 6 END)
		BEGIN
			RETURN  1122  /*该单据需要审核*/
		END
	END 
	/***************验证***************/
	--运输费用分摊直接过账
	IF @BillType=415
	BEGIN
		UPDATE dbo.BillIndex SET ifcheck='t',draft=0,Poster=@ChvOpID,PostTime=GETDATE() WHERE BillNumberId=@BillNumberID
		RETURN 0
	END

	DECLARE		@GoodsBillNumberID INT,					/*出库单单据编号*/
				@GoodsBillID	   INT,					/*出库单明细ID*/
				@GoodsBillType     INT,					/*出库单单据类型*/
				@RowIndex          INT,					
				@RowCount          INT,					/*运输单明细行数*/
				@Qty			   NUMERIC(24,10),		/*发货数量*/
				@Return            INT,					/*返回值*/
				@TbName            VARCHAR(100),		/*出库单明细表	*/
				@UpdateSQL		   NVARCHAR(MAX),		/*更新发货数量SQL*/
				@CheckSQL          NVARCHAR(MAX)		/*验证发货数量SQL*/
	DECLARE	    @Tmp			   TABLE
	(
		Qty				  NUMERIC(24,10),
		GoodsBillNumberID INT,
		GoodsBillID       INT,
		GoodsBillType     INT,
		RowIndex          INT
	)
	
	/*上架单*/	
	IF @BillType=412
	BEGIN
		INSERT INTO @Tmp(Qty,GoodsBillNumberID,GoodsBillID,GoodsBillType,RowIndex)
		SELECT Qty,
			   GoodsBillNumberID,
			   GoodsBillID,
			   GoodsBillType,
			   ROW_NUMBER() OVER (ORDER BY GETDATE()) 
		FROM onShelvesbill WHERE BillNumberID=@BillNumberID
		SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
		
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @Qty=Qty,@GoodsBillNumberID=GoodsBillNumberID,@GoodsBillID=GoodsBillID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
			SELECT @TbName=detailTable FROM BillName WHERE Billtype=@GoodsBillType
			/*验证完成状态*/
			SET @CheckSQL ='IF EXISTS(
										SELECT 1 FROM ' +@TbName+' A INNER JOIN PType P ON A.PTypeID=P.TypeID 
										WHERE Qty>ISNULL(InflowQty,0) AND BillNumberID=@GoodsBillNumberID  AND P.IsService=0 '
										+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END+
									 ') 
							SET @Return=0 ELSE SET @Return=1'
			/*更新入库数量*/		
			SET @UpdateSQL='UPDATE '+@TbName +' 
							SET InflowQty=ISNULL(InflowQty,0)+@Qty 
						    WHERE ID=@GoodsBillID ' +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE '' END
			SET @Return=0
			
			exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@GoodsBillID INT',@Qty,@GoodsBillID
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@Return INT OUT',@GoodsBillNumberID,@Return OUT
			UPDATE dbo.BillIndex SET ShelveState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@GoodsBillNumberID
			/*验证是否超过入库单数量*/
			SET @Return=0
			SET @CheckSQL=' IF EXISTS(
										SELECT 1 FROM '+ @TbName +'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
										WHERE ISNULL(InflowQty,0)>Qty AND BillNumberID=@GoodsBillNumberID AND ID=@GoodsBillID  AND P.IsService=0 '
										+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END
									+') 
						    SET @Return=1 ELSE SET @Return=0'
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@GoodsBillID INT,@Return INT OUT',@GoodsBillNumberID,@GoodsBillID,@Return OUT
			IF @Return=1
			BEGIN
				RETURN 4121   /*超过入库数量*/
			END
			SET @RowIndex=@RowIndex+1
		END
		UPDATE onShelvespickIndex SET ifcheck='t',draft=0,Poster=@ChvOpID,PostTime=GETDATE() WHERE BillNumberId=@BillNumberID
		RETURN 0
	END
	
	/*拣货单*/
	IF @BillType=413
	BEGIN
		INSERT INTO @Tmp(Qty,GoodsBillNumberID,GoodsBillID,GoodsBillType,RowIndex)
		SELECT Qty,
			   GoodsBillNumberID,
			   GoodsBillID,
			   GoodsBillType,
			   ROW_NUMBER() OVER (ORDER BY GETDATE()) 
		FROM PickBill WHERE BillNumberID=@BillNumberID
		SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
		
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @Qty=Qty,@GoodsBillNumberID=GoodsBillNumberID,@GoodsBillID=GoodsBillID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
			SELECT @TbName=detailTable FROM BillName WHERE Billtype=@GoodsBillType
			/*验证完成状态*/
			SET @CheckSQL ='IF EXISTS(
										SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
										WHERE Qty>ISNULL(PickedQty,0) AND BillNumberID=@GoodsBillNumberID  AND P.IsService=0 '
										+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END
								    +') 
								SET @Return=0 ELSE SET @Return=1'
			/*更新拣货数量*/
			SET @UpdateSQL='UPDATE '+@TbName +' 
							SET PickedQty=ISNULL(PickedQty,0)+@Qty 
						    WHERE ID=@GoodsBillID ' +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE '' END
			SET @Return=0
			
			exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@GoodsBillID INT',@Qty,@GoodsBillID
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@Return INT OUT',@GoodsBillNumberID,@Return OUT
			
			UPDATE dbo.BillIndex SET progressstate=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@GoodsBillNumberID
			/*验证是否超出出库单数量*/
			SET @Return=0
			SET @CheckSQL=' IF EXISTS(
										SELECT 1 FROM '+ @TbName +'  A INNER JOIN PType P ON A.PTypeID=P.TypeID  
										WHERE ISNULL(PickedQty,0)>Qty AND BillNumberID=@GoodsBillNumberID AND ID=@GoodsBillID AND P.IsService=0 '
										+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END
									+') 
						    SET @Return=1 ELSE SET @Return=0'
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@GoodsBillID INT,@Return INT OUT',@GoodsBillNumberID,@GoodsBillID,@Return OUT
			IF @Return=1
			BEGIN
				RETURN 4131   /*超过出库数量*/
			END
			SET @RowIndex=@RowIndex+1
		END
		UPDATE onShelvespickIndex SET ifcheck='t',draft=0,Poster=@ChvOpID,PostTime=GETDATE() WHERE BillNumberId=@BillNumberID
		RETURN 0
	END
	
	/*运输配送*/
	IF @BillType=414
	BEGIN
		INSERT INTO  @Tmp(Qty,GoodsBillNumberID,GoodsBillID,GoodsBillType,RowIndex)
        SELECT  A.Qty ,
                B.GoodsBillNumberID ,
                B.GoodsBillID ,
                B.GoodsBillType ,
                ROW_NUMBER() OVER ( ORDER BY GETDATE() ) AS RowIndex
        FROM    dbo.Transportbill A
                INNER JOIN dbo.pickbill B ON A.GoodsBillID = B.ID 
        WHERE A.billNumberID=@BillNumberID
        SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
        
        /*更新出库单发货数量，如果全部发货，则更改状态为已发运*/
        WHILE(@RowIndex<=@RowCount)
        BEGIN
			SELECT @Qty=Qty,@GoodsBillNumberID=GoodsBillNumberID,@GoodsBillID=GoodsBillID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
			SELECT @TbName=detailTable FROM BillName WHERE Billtype=@GoodsBillType
			/*验证完成状态*/
			SET @CheckSQL ='IF EXISTS(
										SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID  
										WHERE Qty>ISNULL(SendedQty,0) AND BillNumberID=@GoodsBillNumberID AND P.IsService=0 '
										+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END
									+') 
								SET @Return=0 ELSE SET @Return=1'
			/*更新发货数量*/
			SET @UpdateSQL='UPDATE '+@TbName +' 
							SET SendedQty=ISNULL(SendedQty,0)+@Qty 
							WHERE ID=@GoodsBillID ' +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE '' END
			SET @Return=0
			
			exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@GoodsBillID INT',@Qty,@GoodsBillID
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@Return INT OUT',@GoodsBillNumberID,@Return OUT
			
			UPDATE dbo.BillIndex SET TransPortState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@GoodsBillNumberID
			
			/*验证是否超出出库单数量*/
			SET @Return=0
			SET @CheckSQL=' IF EXISTS(
										SELECT 1 FROM '+ @TbName +' A INNER JOIN PType P ON A.PTypeID=P.TypeID  
										WHERE ISNULL(SendedQty,0)>Qty AND BillNumberID=@GoodsBillNumberID AND ID=@GoodsBillID AND P.IsService=0 '
										+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END
									+') 
						    SET @Return=1 ELSE SET @Return=0'
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@GoodsBillID INT,@GoodsBillType INT,@Return INT OUT',@GoodsBillNumberID,@GoodsBillID,@GoodsBillType,@Return OUT
		
			IF @Return=1
			BEGIN
				RETURN 4141   /*超过出库数量*/
			END
			SET @RowIndex=@RowIndex+1
        END
		RETURN 0
	END
END
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:彭勇
	日期：2014-04-30
	描述：提成规则审核与反审核
*/
CREATE PROCEDURE Gp_AuditSetCommissionRule
(
	 @BillNumberId  INT,
	 @AuditState    INT,
	 @userid        NVARCHAR(200)
)
--@encode$--
AS
SET NOCOUNT ON
IF @AuditState=0--审核
 BEGIN
   IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState=3)
   BEGIN 
	   RAISERROR ('该单据已禁用，不能审核！',16,1) 
	   RETURN;
   END 	
   IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState=2)
   BEGIN 
	   RAISERROR ('该单据已审核，不需要再次审核！',16,1) 
	   RETURN;
   END 
   
   DECLARE @billcode NVARCHAR(1000)
   
   SELECT @billcode=billcode  FROM CommissionRule WHERE BillNumberId=@billnumberid
   
   IF EXISTS(SELECT 1 count FROM CommissionRule WHERE BillNumberId!=@billnumberid AND BillCode=@billcode)
   BEGIN
			 DECLARE @Re NVARCHAR(50)
             DECLARE @bCode NVARCHAR(50)
             DECLARE @Month NVARCHAR(50)
             DECLARE @Day NVARCHAR(50)
             DECLARE @datBillDate NVARCHAR(100)
             DECLARE @checkName nvarchar(100)
             SELECT @Month=Month(GETDATE())
		     SELECT @Day=DAY(GETDATE())
		     SELECT @datBillDate=BillDate  FROM CommissionRule WHERE BillNumberId!=@billnumberid
             EXEC @Re=Gp_GetBillCode 164, @Month,@Day,'TC',@datBillDate,'0001',@bCode OUTPUT,'',@billnumberid
             SELECT TOP 1 @checkName=Fullname from employee where typeid=@userid
             EXEC GP_AutoCombneRetail_SaveBillCode_Seed @datBillDate,164,@bCode,'','','','',@checkName
               UPDATE dbo.CommissionRule SET BillCode=@bCode WHERE BillNumberId=@BillNumberId
   
   END
   
   
   UPDATE dbo.CommissionRule SET BillState=2,Checker=@userid,CheckerTime=getdate(),RChecker='',RVaildDate=NULL  WHERE BillNumberId=@BillNumberId
END 
ELSE
 BEGIN
  IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState=3 )
   BEGIN 
	   RAISERROR ('该单据已禁用，不能反审核！',16,1) 
	   RETURN;
   END 
   
    IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState=1 )
   BEGIN 
	   RAISERROR ('该单据未审核，不能反审核！',16,1) 
	   RETURN;
   END 
   
    IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND  UseState=2)
   BEGIN 
	   RAISERROR ('该单据已引用，不能反审核！',16,1) 
	   RETURN;
   END 
   UPDATE dbo.CommissionRule SET BillState=1 ,Checker='',CheckerTime=NULL,RChecker=@userid,RVaildDate=getdate() WHERE BillNumberId=@BillNumberId 
 END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:彭勇
	日期：2014-04-30
	描述：参照计划审核与反审核
*/
CREATE PROCEDURE Gp_AuditSetReferencePlanCommission
(
	 @BillNumberId  INT,
	 @AuditState    INT,
	 @userid        NVARCHAR(200)
)
--@encode$--
AS
SET NOCOUNT ON
IF @AuditState=0--审核
 BEGIN
   IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState=3)
   BEGIN 
	   RAISERROR ('该单据已禁用，不能审核！',16,1) 
	   RETURN;
   END 
    IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState=2)
   BEGIN 
	    RAISERROR ('该单据已审核，不需要再次审核！',16,1) 
	    RETURN;
   END 
   
    DECLARE @billcode NVARCHAR(1000)
   
   SELECT @billcode=billcode  FROM ReferencePlanCommission WHERE BillNumberId=@billnumberid
   
   IF EXISTS(SELECT 1 count FROM ReferencePlanCommission WHERE BillNumberId!=@billnumberid AND BillCode=@billcode)
   BEGIN
			 DECLARE @Re NVARCHAR(50)
             DECLARE @bCode NVARCHAR(50)
             DECLARE @Month NVARCHAR(50)
             DECLARE @Day NVARCHAR(50)
             DECLARE @datBillDate NVARCHAR(100)
             DECLARE @checkName nvarchar(100)
             SELECT @Month=Month(GETDATE())
		     SELECT @Day=DAY(GETDATE())
		     SELECT @datBillDate=BillDate  FROM ReferencePlanCommission WHERE BillNumberId!=@billnumberid
             EXEC @Re=Gp_GetBillCode 309, @Month,@Day,'TC',@datBillDate,'0001',@bCode OUTPUT,'',@billnumberid
             SELECT TOP 1 @checkName=Fullname from employee where typeid=@userid
             EXEC GP_AutoCombneRetail_SaveBillCode_Seed @datBillDate,164,@bCode,'','','','',@checkName
               UPDATE dbo.ReferencePlanCommission SET BillCode=@bCode WHERE BillNumberId=@BillNumberId
   
   END
   
   UPDATE dbo.ReferencePlanCommission SET BillState=2,Checker=@userid,CheckerTime=GETDATE()  WHERE BillNumberId=@BillNumberId
END 
ELSE
 BEGIN
  IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState=3)
   BEGIN 
	   RAISERROR ('该单据已禁用，不能反审核！',16,1) 
	   RETURN;
   END 
    IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState=1)
   BEGIN 
	     RAISERROR ('该单据未审核，不能反审核！',16,1) 
	   RETURN;
   END 
    IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND UseState=2)
   BEGIN 
	   RAISERROR ('该单据已引用，不能反审核！',16,1) 
	   RETURN;
   END 
   UPDATE dbo.ReferencePlanCommission SET BillState=1,Checker='',CheckerTime=NULL  WHERE BillNumberId=@BillNumberId 
 END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-05-08
-- Description: 处理会员相关的过账：
--					1）处理会员卡消费积分
--					2）扣减会员卡余额
--					3）会员储值单、积分兑换、积分调整等单据处理会员卡信息
--					4）收款单扣减会员储值

--新增维修单据的会员卡处理  冯波 2014-05-04
--处理促销商品不积分		冯波 2014-11-20
--处理会员卡批量充值		冯波 2014-11-25
-- =============================================

CREATE   PROCEDURE GP_AuditVipInfo
(
	@numBillType		INT,
	@intBillNumberID	INT,
	@numTotalMoney		NUMERIC(24, 10) ,
	@intVipCardID		INT,
	@datBillDate		DATETIME,
	@VIP_ID				VARCHAR(50)='0',
	@IsRedword			BIT = 0,
	@NewPosBill			TINYINT,
	@VipCentInfo		VARCHAR(200) = '' OUTPUT,	--返回会员卡积分调整信息
	@VipCardCode		VARCHAR(200)='' OUTPUT
)
--@encode$--
AS
DECLARE   
		@chrIfVipJF			CHAR(1),    --是否积分
		@chvVipIsCz			CHAR(1),	--是否储值
		@numVipcZyeMoney	NUMERIC(24, 10) ,  --储值余额
		@StypeVipcZyeMoney	NUMERIC(24, 10) ,  --分支机构储值余额
		@SQL				NVARCHAR(2000) = '',
		@TempEndDate		DATETIME,
		@redwordop			INT = 1,
		@Multiple			DECIMAL(7,2)=0,
		@STypeID			VARCHAR(100),
		@vipBillStoredByStypeId INT--会员储值结算使用单据所选分支机构进行储值余额判断

SELECT @vipBillStoredByStypeId=Value FROM Userconfig WHERE ConfigName='vipBillStoredByStypeId'

--BillIndex
SELECT @STypeID =STypeID FROM dbo.BillIndex WHERE BillNumberId=@intBillNumberID AND BillType=@numBillType
		  
--如果是红冲则需要反号
IF @IsRedword = 1
BEGIN
	SET @redwordop=-1	
END

SELECT @VipCardCode=''

IF @numBillType IN (181)
BEGIN	
	SELECT @TempEndDate=CompleteDate
	FROM Billindex_CarRepair
	WHERE BillNumberId=@intBillNumberID
END

DECLARE
	@intIfSalesIntegral	INT		--促销商品是否参与积分

IF @intVipCardID=0
BEGIN
	SELECT @intIfSalesIntegral=0
END
ELSE
BEGIN
	SELECT @intIfSalesIntegral=b.IfSalesIntegral
	FROM nVipCardSign a
	INNER JOIN nVipCardSet b
	ON a.VipCardTypeID=b.VipCardTypeID
	WHERE a.VipCardID=@intVipCardID
END

IF @numBillType IN (11,12,305,45,46,181,183,215,167,168,172)	-- 销售、零售、销售退货的VIP判断及消费、积分处理（这里的会员卡首先是用来积分的；如果是单帐户，才需要判断余额）
BEGIN
	--判断是否适用当前分支机构
	IF NOT EXISTS(SELECT * FROM nVipCardSign WHERE VipCardID=@intVIPCardID AND (isApplyAllStype=1 OR (isApplyAllStype=0 AND EXISTS(SELECT * FROM VipCard_ApplyStype APS WHERE APS.StypeId=@STypeID AND APS.VipCardId=VipCardID ))))	
	BEGIN
		RETURN 	706		
	END
	
	IF @numBillType = 181 AND @TempEndDate IS NOT NULL
		BEGIN
			SELECT	
				@VipCardCode=a.VipCardCode,
				@chrIfVipJF = b.ifJF,
				@chvVipIsCz = a.IsCz,
				@numVipcZyeMoney = a.cZyeMoney
			FROM nVipCardSign a
			INNER JOIN nVipCardSet b ON a.VipCardID = @intVIPCardID AND a.VipCardTypeID = b.VipCardTypeID  AND a.Deleted = 0 AND B.deleted=0 AND @TempEndDate >= @datBillDate
			LEFT JOIN nVipCardSignStype ss ON SS.VipCardID=A.VipCardID AND ss.StypeId=@StypeID
	END
		ELSE
		BEGIN
			SELECT	
				@VipCardCode=a.VipCardCode,
				@chrIfVipJF = b.ifJF,
				@chvVipIsCz = a.IsCz,
				@numVipcZyeMoney = a.cZyeMoney
			FROM nVipCardSign a
			INNER JOIN nVipCardSet b ON a.VipCardID = @intVIPCardID AND a.VipCardTypeID = b.VipCardTypeID  AND a.Deleted = 0 AND B.deleted=0 AND a.EndDate>= @datBillDate
			LEFT JOIN nVipCardSignStype ss ON SS.VipCardID=A.VipCardID AND ss.StypeId=@StypeID
		END

		-- 1)无此VIP卡 2)过了有效期 3)VIP卡是未启用状态 4)VIP卡类型不存在或已删除
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN 701
		
		--将VIP会员储值卡的消费前余额记入至BillIndex中
		IF @chvVipIsCz = '1'
		BEGIN
			UPDATE BillIndex SET vipCZMoney = ISNULL(@numVipcZyeMoney,0) WHERE BillNumberID = @intBillNumberID
			IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN -10
		END
END

--判断会员卡批量储值充值中的卡号是否有效
IF @numBillType=312
BEGIN
		--循环判断,后面要加上具体的VIP卡号来做提示
		DECLARE VIP_Cursor CURSOR FOR
		SELECT VipCardId,EndDate,ChargeMoney
		FROM VipAddMoneyBatchBill
		WHERE BillNumberId=@intBillNumberID
		
		OPEN VIP_Cursor	

		FETCH NEXT FROM VIP_Cursor INTO @intVipCardID,@TempEndDate,@numTotalMoney

		WHILE @@FETCH_STATUS = 0
		BEGIN
			--判断是否适用当前分支机构
			IF NOT EXISTS(SELECT * FROM nVipCardSign WHERE VipCardID=@intVIPCardID AND (isApplyAllStype=1 OR (isApplyAllStype=0 AND EXISTS(SELECT * FROM VipCard_ApplyStype APS WHERE APS.StypeId=@STypeID AND APS.VipCardId=VipCardID ))))	
			BEGIN
				RETURN 	706		
			END
	
			IF @TempEndDate IS NOT NULL
			BEGIN	
				SELECT	
					@chrIfVipJF = b.ifJF,
					@chvVipIsCz = a.IsCz,
					@VipCardCode=a.VipCardCode,
					@numVipcZyeMoney = a.cZyeMoney
				FROM	nVipCardSign a
				INNER JOIN nVipCardSet b ON a.VipCardID = @intVIPCardID AND a.VipCardTypeID = b.VipCardTypeID  AND a.Deleted = 0 AND B.deleted=0 AND @TempEndDate >= @datBillDate
				LEFT JOIN nVipCardSignStype ss ON SS.VipCardID=A.VipCardID AND ss.StypeId=@StypeID
			END
			ELSE
			BEGIN
				SELECT	
					@VipCardCode=a.VipCardCode,
					@chrIfVipJF = b.ifJF,
					@chvVipIsCz = a.IsCz,
					@numVipcZyeMoney = a.cZyeMoney
				FROM	nVipCardSign a
				INNER JOIN nVipCardSet b ON a.VipCardID = @intVIPCardID AND a.VipCardTypeID = b.VipCardTypeID  AND a.Deleted = 0 AND B.deleted=0 AND a.EndDate>= @datBillDate
				LEFT JOIN nVipCardSignStype ss ON SS.VipCardID=A.VipCardID AND ss.StypeId=@StypeID	
			END

			-- 1)无此VIP卡 2)过了有效期 3)VIP卡是未启用状态 4)VIP卡类型不存在或已删除
			IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN 701
			
			--将VIP会员储值卡的消费前余额记入至BillIndex中
			IF @chvVipIsCz = '1'
			BEGIN
				UPDATE VipAddMoneyBatchBill SET BeforeChargeMoney= ISNULL(@numVipcZyeMoney,0) 
				WHERE BillNumberID = @intBillNumberID AND VipCardId=@intVipCardID
				
				IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN -10
			END
		
			UPDATE nVipCardSign
			SET LJCZMoney=ISNULL(LJCZMoney,0)+@numTotalMoney,CZYEMoney=ISNULL(CZYEMoney,0)+@numTotalMoney,EndDate=@TempEndDate
			WHERE	VipCardId = @intVipCardID
			
			--储值写入分支机构
			IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSignStype WHERE VipCardID=@intVipCardID AND StypeId=@StypeID)
			BEGIN
				INSERT INTO dbo.nVipCardSignStype
						( VipCardID ,
						  StypeId ,
						  qCczMoney ,
						  lJczMoney ,
						  lJxFczMoney ,
						  bNczMoney ,
						  bNxFczMoney ,
						  cZyeMoney ,
						  lJxFMoney ,
						  bNxFMoney
						)
				VALUES  ( @intVipCardID , -- VipCardID - int
						  @STypeID , -- StypeId - varchar(50)
						  0 , -- qCczMoney - numeric
						  @numTotalMoney , -- lJczMoney - numeric
						  0 , -- lJxFczMoney - numeric
						  @numTotalMoney , -- bNczMoney - numeric
						  0 , -- bNxFczMoney - numeric
						  @numTotalMoney , -- cZyeMoney - numeric
						  0 , -- lJxFMoney - numeric
						  0  -- bNxFMoney - numeric
						)
			END
			ELSE
			BEGIN
				UPDATE dbo.nVipCardSignStype
				SET 
					lJczMoney=lJczMoney+@numTotalMoney,
					bNczMoney=bNczMoney+@numTotalMoney,
					cZyeMoney=cZyeMoney+@numTotalMoney
				WHERE VipCardID=@intVipCardID AND StypeId=@STypeID
			END
			
			FETCH NEXT FROM VIP_Cursor INTO @intVipCardID,@TempEndDate,@numTotalMoney	
		END

		CLOSE VIP_Cursor
		DEALLOCATE VIP_Cursor		
END



DECLARE @intVipJF	INT = 0,	 --单据总积分
		@tableName	VARCHAR(50)  --单据明细表
		
IF @numBillType = 11
	SET @tableName = 'SaleBill'
ELSE IF @numBillType = 12
	SET @tableName = 'PT_Combin_SaleBill'	
ELSE	IF @numBillType = 305 
	SET @tableName = 'RetailBill'	
ELSE	IF @numBillType = 45 
	SET @tableName = 'SaleBackBill'	
ELSE	IF @numBillType = 46
	SET @tableName = 'PT_Combin_SaleBackBill'		
ELSE	IF @numBillType = 215 
	SET @tableName = 'RetailBackBill'
ELSE	IF @numBillType = 167 
	SET @tableName = 'wx_bill_getback'	
ELSE	IF @numBillType = 168
	SET @tableName = 'wx_bill_replace'	
ELSE	IF @numBillType = 172
	SET @tableName = 'wx_bill_goto'	
IF @numBillType=305 AND EXISTS(SELECT 1 FROM RetailCombinationBill WHERE BillNumberID=@IntBillNumberID)
	SET @tableName='RetailCombinationBill'

IF @numBillType IN(11,12,305,45,46,215,167,168,172) AND @intVipCardID <> -1  
BEGIN
	IF @chrIfVipJF = '1'  --AND @intCostSale <> 1
	BEGIN
		IF @numBillType IN (167,168,172)
		BEGIN
			--上门维修单
			SET @SQL = 'SELECT	@intVipJF = ISNULL(SUM(a.GridJF),0) 
						FROM(
							SELECT	CAST((SUM(ISNULL(a.Total,0))/c.Total) AS int)*ISNULL(c.JF,0) AS GridJF
							FROM	'+@tableName+'  a,(	SELECT CASE WHEN JFid=0 THEN(SELECT jfgz FROM nVipCardSet ns1,NVipCardSign ns2  WHERE ns1.VipCardTypeID= ns2.VipCardTypeID AND ns2.VipCardID=@intVipCardID) ELSE JFid END AS RealJFid,* FROM dbo.nVipGoodsSign) b,nVipJfSet c,PType d
							WHERE	a.BillNumberID = '+CAST(@intBillNumberID AS VARCHAR)+'
									AND a.PTypeID = b.PTypeID
									AND b.RealJFid = c.[ID]
									AND c.Total <> 0
									AND c.JF <> 0
									AND b.PTypeID=d.TypeID AND b.UnitID=d.BaseUnitID
									
						'
			
			IF @numBillType=172
			BEGIN
				SET @SQL=@SQL+'	AND a.InOrOut=''O''	'
			END			
			
			SET @SQL=@SQL+'
							GROUP BY c.[ID],c.Total,c.[JF]
						) A '
		END
		ELSE
		BEGIN
			IF EXISTS (SELECT  TOP 1 1 FROM Coupon_BillUsed WHERE billnumberid=@intBillNumberID)
				SET @SQL = 'SELECT	@intVipJF = ISNULL(SUM(a.GridJF),0) 
							FROM(
								SELECT	CAST((SUM(ISNULL(a.TaxTotal,0))/c.Total) AS int)*ISNULL(c.JF,0) AS GridJF
								FROM	'+@tableName+'  a,
										(SELECT CASE WHEN JFid=0 THEN(SELECT jfgz FROM nVipCardSet ns1,NVipCardSign ns2  WHERE ns1.VipCardTypeID= ns2.VipCardTypeID AND ns2.VipCardID=@intVipCardID) ELSE JFid END AS RealJFid
												,* 
											FROM dbo.nVipGoodsSign) b,
										nVipJfSet c,
										PType d
										
								WHERE	a.BillNumberID = '+CAST(@intBillNumberID AS VARCHAR)+'
										AND  EXISTS  (
											 SELECT DISTINCT r.id,r.ptypeid 
											 FROM '+@tableName+'  r
											 INNER JOIN Coupon_BillUsed	b ON b.BillnumberId = r.BillNumberId
											 INNER JOIN  coupon_codeinfo c ON c.CouponCode = b.CouponCode
											 INNER JOIN  coupon_TypeInfo t ON t.CouponId = c.CouponId
											 WHERE r.billnumberid ='+CAST(@intBillNumberID AS VARCHAR)+' AND t.IsVipPoint=1 AND a.id=r.ID
										)
										AND a.PTypeID = b.PTypeID
										AND b.RealJFid = c.[ID]
										AND c.Total <> 0
										AND c.JF <> 0
										AND b.PTypeID=d.TypeID AND b.UnitID=d.BaseUnitID
							'
			ELSE 
				SET @SQL = 'SELECT	@intVipJF = ISNULL(SUM(a.GridJF),0) 
							FROM(
								SELECT	CAST((SUM(ISNULL(a.TaxTotal,0))/c.Total) AS int)*ISNULL(c.JF,0) AS GridJF
								FROM	'+@tableName+'  a,
										(SELECT CASE WHEN JFid=0 THEN(SELECT jfgz FROM nVipCardSet ns1,NVipCardSign ns2  WHERE ns1.VipCardTypeID= ns2.VipCardTypeID AND ns2.VipCardID=@intVipCardID) ELSE JFid END AS RealJFid
												,* 
											FROM dbo.nVipGoodsSign) b,
										nVipJfSet c,
										PType d
										
								WHERE	a.BillNumberID = '+CAST(@intBillNumberID AS VARCHAR)+'
										AND a.PTypeID = b.PTypeID
										AND b.RealJFid = c.[ID]
										AND c.Total <> 0
										AND c.JF <> 0
										AND b.PTypeID=d.TypeID AND b.UnitID=d.BaseUnitID
							'
			IF @intIfSalesIntegral=1
			BEGIN
				SET @SQL = @SQL+'
						AND a.promoType=0
				'
			END
						
						
			
			SET @SQL=@SQL+'
							GROUP BY c.[ID],c.Total,c.[JF]
						) A '
		END
		EXECUTE SP_EXECUTESQL @SQL,N'@intVipJF INT OUTPUT,@intVipCardID INT',@intVipJF OUTPUT,@intVipCardID
		
		IF EXISTS(SELECT 1 FROM dbo.nVipCardSet WHERE VipCardTypeID=(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@intVipCardID AND MONTH(Bbirthday)=MONTH(@datBillDate) AND DAY(Bbirthday)=DAY(@datbilldate)) AND IfBirthDay='0' AND ifJF='1')
			SELECT @Multiple=BirthDayMultiple FROM dbo.nVipCardSet WHERE VipCardTypeID=(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@intVipCardID )
		IF EXISTS(SELECT 1 FROM dbo.nVipCardSet WHERE VipCardTypeID=(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@intVipCardID) AND IfDate='0' AND ifJF='1' AND StartDate<=@datBillDate AND EndDate>=CONVERT (DATE,@datBillDate,120) AND CAST(DateMultiple AS  NUMERIC(24, 10) )>@Multiple)
			SELECT @Multiple=DateMultiple FROM dbo.nVipCardSet WHERE VipCardTypeID=(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@intVipCardID )
		IF @Multiple=0
			SET @Multiple=1
		SET @intVipJF= @intVipJF*@Multiple
	END
	
	IF @numBillType IN( 45,46,215)
	BEGIN
		SET @numTotalMoney = -@numTotalMoney
		SET @intVipJF = -@intVipJF
	END
	
	IF @intVipJF <> 0
		UPDATE BillIndex SET JF = @intVipJF
		WHERE BillNumberID = @intBillNumberID
			
	IF @NewPosBill=0
	BEGIN
		--红冲反号
		SET @numTotalMoney = @redwordop * @numTotalMoney	
		SET @intVipJF = @redwordop * @intVipJF	
		
		IF @numTotalMoney <> 0 OR @intVipJF <> 0
		BEGIN
			UPDATE nVipCardSign
			SET TotalMoney = TotalMoney + @numTotalMoney,
				TotalCent = TotalCent + @intVipJF
			WHERE VipCardID = @intVipCardID
			
			--消费写入分支机构
			--本年消费、累积消费
			IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSignStype WHERE VipCardID=@intVipCardID AND StypeId=@StypeID)
			BEGIN
				INSERT INTO dbo.nVipCardSignStype
						( VipCardID ,
						  StypeId ,
						  qCczMoney ,
						  lJczMoney ,
						  lJxFczMoney ,
						  bNczMoney ,
						  bNxFczMoney ,
						  cZyeMoney ,
						  lJxFMoney ,
						  bNxFMoney
						)
				VALUES  ( @intVipCardID , -- VipCardID - int
						  @STypeID , -- StypeId - varchar(50)
						  0 , -- qCczMoney - numeric
						  0 , -- lJczMoney - numeric
						  0 , -- lJxFczMoney - numeric
						  0 , -- bNczMoney - numeric
						  0 , -- bNxFczMoney - numeric
						  0 , -- cZyeMoney - numeric
						  @numTotalMoney , -- lJxFMoney - numeric
						  @numTotalMoney  -- bNxFMoney - numeric
						)
			END
			ELSE
			BEGIN
				UPDATE dbo.nVipCardSignStype
				SET 
					lJxFMoney=lJxFMoney+@numTotalMoney,
					bNxFMoney=bNxFMoney+@numTotalMoney
				WHERE VipCardID=@intVipCardID AND StypeId=@STypeID
			END
		END
		--自动升级会员卡	
		DECLARE @UpgradePointToVip INT=0,@UpgradePoint INT=0,@oldtypelevel INT =0,@typeName VARCHAR(200),@billcode VARCHAR(50),@billdate VARCHAR(20)
			    ,@etypeid VARCHAR(50),@validday INT,@validtype INT
		SELECT @UpgradePointToVip = Value FROM dbo.Userconfig WHERE ConfigName='UpgradePointToVip'
		SELECT @UpgradePoint = Value FROM dbo.Userconfig WHERE ConfigName='UpgradePoint'
		SELECT @oldtypelevel =TypeLevel FROM dbo.nVipCardSet WHERE  VipCardTypeID =(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@intVipCardID)
		IF @oldtypelevel>0 AND @oldtypelevel<5 AND @intVipJF>=0 AND @UpgradePoint=1
		BEGIN
			DECLARE @typelevel INT=0,@standardcent DECIMAL(10,0)=0,@deductcent DECIMAL(10,0) =0,
					@AllTotalCent  NUMERIC(24, 10) ,@oldCardtype INT =0,@newCardType INT =0,@nBillId 	numeric(18,0)
			
			SELECT	@AllTotalCent=ISNULL(TotalCent,0)+ISNULL(BeginCent,0)
			FROM	nVipCardSign a
			WHERE	a.VipCardID = @intVipCardID
					AND a.Deleted = '0'
					AND a.EndDate >= @datBillDate	
			
			SELECT *
			INTO #VipCardSet 
			FROM dbo.nVipCardSet
			WHERE TypeLevel>@oldtypelevel
			
			UPDATE #VipCardSet 
			SET StandardCent+=n2.DeductCent,
				deductcent +=n2.deductcent
			FROM 
			(
				SELECT n.TypeLevel,SUM(a.DeductCent) AS DeductCent
				FROM #VipCardSet n
				INNER JOIN #VipCardSet a ON a.TypeLevel<n.TypeLevel
				GROUP BY n.TypeLevel
			)n2
			WHERE n2.TypeLevel=#VipCardSet.TypeLevel
								
			SELECT @oldCardtype = VipCardTypeID,@etypeid=etypeid FROM dbo.nVipCardSign WHERE VipCardID=@intVipCardID
			SELECT TOP 1 @typelevel= TypeLevel,@standardcent=StandardCent,@deductcent=DeductCent FROM #VipCardSet WHERE TypeLevel>@oldtypelevel AND StandardCent<=@AllTotalCent ORDER BY TypeLevel DESC
			IF  @typelevel>1
			BEGIN
				SELECT @typeName=TypeName,@validday=ValidDate,@validtype=ValidType FROM dbo.nVipCardSet WHERE TypeLevel=@typelevel
				IF	@UpgradePointToVip=1 
				BEGIN
					SELECT @newCardType=VipCardTypeID FROM dbo.nVipCardSet WHERE TypeLevel=@typelevel
					UPDATE dbo.nVipCardSign SET totalCent=totalCent-@deductcent,VipCardTypeID=@newCardType WHERE VipCardID=@intVipCardID
					SET @sql='UPDATE dbo.nVipCardSign SET EndDate=DATEADD('+CASE WHEN @validtype=0 THEN 'YEAR' WHEN @validtype=1 THEN 'MONTH' ELSE 'DAY' END+',@validday,CAST(GETDATE() AS DATE)) WHERE VipCardID=@intVipCardID'
					EXEC sp_executesql @sql, N'@validday int,@intVipCardID int',@validday,@intVipCardId
					INSERT INTO dbo.nVipCardTypeChange
					( 
						VipCardID ,
						OldVipCardTypeID ,
						NewVipCardTypeID ,
						etypeid ,
						ChangeDate ,
						OperatStyle ,
						Comment
					)
					VALUES  
					( 
						@intVipCardID,
						@oldCardType,
						@newCardType,
						'',
						convert(varchar(10),getdate(),120) ,
						1,
						'系统自动升级会员级别'
					)
					IF @deductcent>0
					BEGIN
						IF NOT EXISTS(SELECT TOP 1 1 FROM nVipAdjust)
							SET @nBillID = 1
						ELSE
							SELECT @nBillId = ISNULL(MAX(BillNumberId),0) + 1 FROM nVipAdjust
						SET @billdate=CONVERT(varchar(10),GetDate(),120)	
						EXEC dbo.Gp_GetAdjustCode  'JFC', @billdate,  @BillCode output 
						INSERT INTO nVipAdjust
						(
							BillNumberId,
							BillDate,
							BillCode,
							ETypeId,
							Checke,
							VipNo,
							UpCost,
							DownCost,
							SumCost,
							Reason,
							IsSend,
							nType
						)VALUES(
							@nBillId,
							@BillDate,
							@BillCode,
							@etypeid,
							@etypeid,
							@intVipCardID,
							0,
							@deductcent,
							-@deductcent,
							'会员级别升级扣减',
							0,
							2
						)
					END
					SET @VipCentInfo='会员卡['+@VipCardCode+']积分已达到['+@typeName+']级别，系统已扣除['+CAST(@deductcent AS VARCHAR)+']积分，并自动升级了会员级别！'
				END
				ELSE
					SET @VipCentInfo='会员卡['+@VipCardCode+']积分已达到['+@typeName+']级别，请到会员卡信息管理中调整卡类型！'
			END
		END
	END
END

IF @numBillType = 4
BEGIN
	DECLARE		@chvATypeID	VARCHAR(50),
				@numTotal	 NUMERIC(24, 10) 
	
	DECLARE CreateMx_CURSOR CURSOR FOR
		SELECT	ATypeID,
				Total,
				VipCardID
		FROM	GatheringBill
		WHERE	BillNumberId = @intBillNumberID AND ATypeID = @VIP_ID --IN('0000200005','0000200006')

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,@numTotal,@intVipCardID
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @intVipCardID <> -1
			BEGIN
				SELECT	
						@chvVipIsCz = a.IsCz,
						@numVipcZyeMoney =a.cZyeMoney,
						@StypeVipcZyeMoney=ISNULL(ss.cZyeMoney,0)
				FROM	nVipCardSign a
				INNER JOIN nVipCardSet b ON a.VipCardTypeID = b.VipCardTypeID AND a.VipCardID = @intVIPCardID AND a.Deleted = 0 AND B.deleted=0 AND a.EndDate >= @datBillDate
				LEFT JOIN nVipCardSignStype ss ON SS.VipCardID=A.VipCardID AND ss.StypeId=@StypeID
				
				-- 1)无此VIP卡 2)过了有效期 3)VIP卡是未启用状态 4)VIP卡类型不存在或已删除
				IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN 701

				IF @chvATypeID = '0000200005' AND @chvVipIsCz <> '1' RETURN 702
				IF @numTotal < 0 RETURN 703
				IF @numTotal > ISNULL(@numVipcZyeMoney,0) RETURN 704
				
				IF @vipBillStoredByStypeId=1 AND @numTotal > ISNULL(@StypeVipcZyeMoney,0) RETURN 707
		
				IF @chvVipIsCz = '1'
				BEGIN
					-- 过账时将VIP会员储值卡的消费前余额记入至BillIndex中
					UPDATE BillIndex SET vipCZMoney = ISNULL(@numVipcZyeMoney,0) WHERE BillNumberID = @intBillNumberID
					IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN -10
				END
				
				SET @numTotal =  @redwordop * @numTotal
				-- 扣减会员储值余额
				IF  @numTotal > 0
				BEGIN
					UPDATE	nVipCardSign SET cZyeMoney = cZyeMoney - @numTotal WHERE VipCardID = @intVipCardID
					UPDATE  dbo.nVipCardSignStype SET cZyeMoney=cZyeMoney-@numTotal WHERE VipCardID=@intVipCardID AND StypeId=@STypeID
				END
			END
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,@numTotal,@intVipCardID
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
END

IF @numBillType = 181 --会员储值
BEGIN
	UPDATE nVipCardSign
	SET LJCZMoney=ISNULL(LJCZMoney,0)+@numTotalMoney,CZYEMoney=ISNULL(CZYEMoney,0)+@numTotalMoney,EndDate=@TempEndDate
	WHERE	VipCardId = @intVipCardID
	
	--储值写入分支机构
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSignStype WHERE VipCardID=@intVipCardID AND StypeId=@StypeID)
	BEGIN
		INSERT INTO dbo.nVipCardSignStype
		        ( VipCardID ,
		          StypeId ,
		          qCczMoney ,
		          lJczMoney ,
		          lJxFczMoney ,
		          bNczMoney ,
		          bNxFczMoney ,
		          cZyeMoney ,
		          lJxFMoney ,
		          bNxFMoney
		        )
		VALUES  ( @intVipCardID , -- VipCardID - int
		          @STypeID , -- StypeId - varchar(50)
		          0 , -- qCczMoney - numeric
		          @numTotalMoney , -- lJczMoney - numeric
		          0 , -- lJxFczMoney - numeric
		          @numTotalMoney , -- bNczMoney - numeric
		          0 , -- bNxFczMoney - numeric
		          @numTotalMoney , -- cZyeMoney - numeric
		          0 , -- lJxFMoney - numeric
		          0  -- bNxFMoney - numeric
		        )
	END
	ELSE
	BEGIN
		UPDATE dbo.nVipCardSignStype
		SET 
			lJczMoney=lJczMoney+@numTotalMoney,
			bNczMoney=bNczMoney+@numTotalMoney,
			cZyeMoney=cZyeMoney+@numTotalMoney
		WHERE VipCardID=@intVipCardID AND StypeId=@STypeID
	END
END

IF @numBillType = 183 --积分兑换
BEGIN
	DECLARE
			@TotalCent  NUMERIC(24, 10) ,
			@curJF	 NUMERIC(24, 10) ,
			@MinCanUseCent  NUMERIC(24, 10) 

	SELECT	@TotalCent=ISNULL(TotalCent,0)+ISNULL(BeginCent,0)
	FROM	nVipCardSign a
	WHERE	a.VipCardID = @intVipCardID
			AND a.Deleted = '0'
			AND a.EndDate >= @datBillDate

	SELECT @curJF=SUM(ISNULL(Total,0))
	FROM IntegralExchangeBill
	WHERE BillNumberID=@intBillNumberID

	IF @curJF>@TotalCent RETURN -300

	SELECT @MinCanUseCent= Value FROM userconfig where configname='MinCanUseCent'
	
	IF @TotalCent<@MinCanUseCent  RETURN -350
	
	SET @curJF = @redwordop * @curJF
	
	UPDATE nVipCardSign SET TotalCent=TotalCent-@curJF WHERE VipCardID = @intVipCardID
END


RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@numBillType		INT,
	@intBillNumberID	INT,
	@numTotalMoney		 NUMERIC(24, 10) ,
	@intVipCardID		INT,
	@datBillDate		DATETIME,
	@VIP_ID				VARCHAR(50),
	@IsRedword			BIT,
	@NewPosBill			INT,
	@nRet				INT,
	@VipCentInfo		VARCHAR(200),	--返回会员卡积分调整信息
    @VipCardCode		VARCHAR(200)
	
SELECT
	@numBillType=11,
	@intBillNumberID=12,
	@numTotalMoney=100.3400000000,
	@intVipCardID=1,
	@datBillDate=GETDATE(),
	@VIP_ID='0000200005',
	@IsRedword=0,
	@NewPosBill=1

BEGIN TRAN

SELECT cZyeMoney,TotalMoney,* FROM nVipCardSign


EXEC @nRet=GP_AuditVipInfo
	@numBillType,
	@intBillNumberID,
	@numTotalMoney,
	@intVipCardID,
	@datBillDate,
	@VIP_ID,
	@IsRedword,
	@NewPosBill,
	@VipCentInfo OUT,
	@VipCardCode OUT

SELECT @nRet,@VipCentInfo,@VipCardCode

SELECT cZyeMoney,TotalMoney,* FROM nVipCardSign

ROLLBACK TRAN

*/



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
	描述：自动合并pos小票 
	如果挂往来则生成销售/销售退货
-------------------------------------------*/
CREATE PROCEDURE [dbo].Gp_AutoCombinePosBill
(
    @resultBillnumberid		VARCHAR(8000)='' OUT	 --返回生成的单据billnumberid
)
--@encode$--
AS 
SET NOCOUNT ON
/*GP_SaveBillCode_Seed --保存单据编号种子数
Gp_GetBillCode 取单据编号
*/

/*  设计思路：
	按表头情况分组以后，循环每种情况，将当前情况的所有明细按billnumberid、明细id排序插入零时表
	并给明细一个自增的id（列名id）和按同单据为一个组的增量id（列名billid），
	计算出这个组合下需要合并的总的单据量(零时表的总数量除以配置的张数向上取整)，
	循环需要合并成的总单据量,比如循环变量为@j，配置张数变量为@size，如果合并结果明细不大于500：
	则取 where billId>@j*@Size AND billId<=(@j+1)*@Size 为当前合并结果，
	如果合并的结果大于500行，则需要在算出明细还需要拆成几张单，然后循环取每张单的明细得出结果。
	--PosSaleMergeFailed
	--零售退货307
*/

-- ********	判断是否试用版 - Start	********
    DECLARE @N INT ,
        @intVersion INT

-- 判断版本号，是否试用版
    SELECT  @N = CAST(SubValue AS INT)
    FROM    SysData1
    WHERE   SubNo = 2	-- 版本号

IF @N IS NULL RETURN -1

    DECLARE @intBit INT ,
        @intMask INT
    SELECT  @intBit = @N & 15
    SELECT  @intMask = POWER(2, @intBit) ^ POWER(2, @intBit + 1) ^ POWER(2,
                                                              @intBit + 2)
            ^ POWER(2, @intBit + 3) ^ POWER(2, @intBit + 4) ^ POWER(2,
                                                              @intBit + 5)
    SELECT  @intVersion = ( @intMask & @N ) / POWER(2, @intBit)
-- ********	判断是否试用版 - END	********

IF @resultBillnumberid IS NULL
SET @resultBillnumberid = ''


DELETE FROM dbo.PosSaleBillIndex WHERE EXISTS(SELECT TOP 1 1 FROM  PosRetailRecord WHERE PosBillNumberId = dbo.PosSaleBillIndex.BillnumberID)
DELETE FROM dbo.PosSaleBill WHERE EXISTS(SELECT TOP 1 1 FROM  PosRetailRecord WHERE PosBillNumberId = dbo.PosSaleBill.BillnumberID)
DELETE FROM dbo.PosMulAccount WHERE EXISTS(SELECT TOP 1 1 FROM  PosRetailRecord WHERE PosBillNumberId = dbo.PosMulAccount.BillnumberID)

SELECT MIN(B.BillnumberID) AS BillnumberID,B.[guid] 
INTO #T
FROM PosSaleBillIndex B 
WHERE B.[guid] IN(SELECT [guid] FROM PosSaleBillIndexAll group by [guid] having(COUNT(1))>1)
GROUP BY B.[guid]

SELECT * 
INTO #T1
FROM (
	SELECT B.BillnumberID
	FROM PosSaleBillIndex B 
	INNER JOIN #T t ON t.[guid] = B.[guid] AND t.BillnumberID <> B.BillnumberID
	UNION ALL 
	SELECT b.BillnumberID 
	FROM  PosSaleBillIndex b 
	INNER JOIN PosSaleBillIndexAll a ON a.[guid] = b.[guid]
	INNER JOIN PosRetailRecord r ON r.PosBillNumberId = a.BillNumberId
) A

DELETE FROM PosSaleBillIndex WHERE BillnumberID IN(SELECT BillnumberID FROM #T1)
DELETE FROM PosSaleBill WHERE BillnumberID IN(SELECT BillnumberID FROM #T1)
DELETE FROM PosMulAccount WHERE BillnumberID IN(SELECT BillnumberID FROM #T1)

DELETE FROM PosSaleBillIndexAll WHERE BillnumberID IN(SELECT BillnumberID FROM #T1) AND NOT EXISTS(SELECT TOP 1 1 FROM PosRetailRecord WHERE PosBillNumberId=PosSaleBillIndexAll.BillnumberID)
DELETE FROM PosSaleBillAll WHERE BillnumberID IN(SELECT BillnumberID FROM #T1) AND NOT EXISTS(SELECT TOP 1 1 FROM PosRetailRecord WHERE PosBillNumberId=PosSaleBillAll.BillnumberID)
DELETE FROM PosMulAccountAll WHERE BillnumberID IN(SELECT BillnumberID FROM #T1) AND NOT EXISTS(SELECT TOP 1 1 FROM PosRetailRecord WHERE PosBillNumberId=PosMulAccountAll.BillnumberID)

DROP TABLE #T,#T1


CREATE TABLE #PosSaleBill
	(
		BillnumberID int  NULL,
		ID int IDENTITY(1,1) NOT NULL,
		PID INT NULL,
		Qty  NUMERIC(24, 10)   NULL,
		BackQty  NUMERIC(24, 10)  NULL DEFAULT(0),
		RetailPrice  NUMERIC(24, 10)   NULL,
		Tax  NUMERIC(24, 10)  NULL DEFAULT(0),
		DisCount  NUMERIC(24, 10)   NULL DEFAULT(1),
		Price  NUMERIC(24, 10)   NULL,
		RetailTotal  NUMERIC(24, 10)   NULL,
		Total  NUMERIC(24, 10)   NULL,
		UnitID INT  NULL DEFAULT(0),
		UnitRate  NUMERIC(24, 10)  NULL Default(1),
		ItemID    bigint   NULL,
		IsCombined  int   NULL,
		BarCode	VARCHAR(200) NULL DEFAULT(''),
		IsGift INT NULL DEFAULT(0),
		Comment VARCHAR(MAX)NULL,
		posid INT,
		detailid INT,
		billId INT,
		PromoType INT NOT NULL DEFAULT(0) ,
		SaleEid INT NOT NULL DEFAULT(0),
		validdate VARCHAR(50)  NOT NULL DEFAULT(''),
		producedate VARCHAR(50)  NOT NULL DEFAULT(''),
		goodsnumber VARCHAR(100)  NOT NULL DEFAULT(''),
		serial TEXT NOT NULL DEFAULT(''),
		goodscostprice NUMERIC(24, 10)  NOT NULL Default(0),
		iscombination INT default(0),
		combinationptypeid	VARCHAR(200) NOT NULL DEFAULT(''),
		ptypeid		VARCHAR(200),
		pindexid	VARCHAR(300) NULL, 
		ktypeid	    VARCHAR(300) NULL,
		couponcode	VARCHAR(200) DEFAULT(''),--商品明细的couponcode,
		pricesource VARCHAR(200) DEFAULT(''),
		PromoIDs	VARCHAR(200) NULL--促销政策ID字符串，逗号分隔 
	)
	create clustered index cix_id on #PosSaleBill(id,billId)

	CREATE TABLE #BillMulAccount(
		[BillNumberId] INTEGER NOT NULL,
		[posBillNumberId] INTEGER NOT NULL,
		[ATypeID] INT NULL,
		 total  NUMERIC(24, 10) ,
		 ntotal  NUMERIC(24, 10) ,
		[VipCardID] INT NULL DEFAULT(-1),
		[Comment] VARCHAR(500) NULL DEFAULT(''),
		[yhType]  INT NULL DEFAULT(-1),
		[CouponCode] VARCHAR(200) DEFAULT(''),
		VipTotal NUMERIC(24, 10) DEFAULT(0)
	)
	
CREATE TABLE #daftBillNumerid(Billnumberid INT NULL)
	
DECLARE @Size  NUMERIC(24, 10) =10000,@DetialSize  NUMERIC(24, 10) =10000 -- 明细取消500分单限制 改成一张小票生成一张单

DECLARE @Sid INT,@Bid INT,@Kid INT,@Eid INT,@VipCardID INT,@BillDate VARCHAR(50),@CargoID INT,@PromoRuleId INT,@PromoIDs VARCHAR(200),@BillDescription VARCHAR(2000),@CouponCodes VARCHAR(2000)--记录单据用到的所有优惠券
DECLARE @stypeid VARCHAR(50),@btypeid VARCHAR(50),@etypeid VARCHAR(50),@ktypeid VARCHAR(50),@dtypeid VARCHAR(50),@dfullname VARCHAR(200)
DECLARE @billPage INT,@detailcount INT,@detalPage INT=1,@billcount INT,@billtype INT,@taxtotal  NUMERIC(24, 10) ,@qty  NUMERIC(24, 10) ,@premoney  NUMERIC(24, 10) ,@totalinmoney  NUMERIC(24, 10),@SaveInCzMoney NUMERIC(24,10)  
DECLARE  @i INT=0,@j INT=0
DECLARE @Bilnumberid INT,@billid INT=0,@tmp INT,@newbillnumberid INT
DECLARE @billcode VARCHAR(100),@Day varchar(100),@Month varchar(100),@Year varchar(100),@BillFlag VARCHAR(5),@cefullname VARCHAR(500)='',
		@cdfullname	VARCHAR(500)='' --单据编号相关
DECLARE @atypeid1 VARCHAR(50) --往来科目
DECLARE @tmpdetailminid INT,@tmpdetailmaxid INT,@posID INT,@tmpmaxbillnumberid INT,@tmpminbillnumberid INT,
		@MAXftotal  NUMERIC(24, 10) , --最后一张已分摊金额
		@MINftotal  NUMERIC(24, 10) , --第一张已分摊金额
		@aftotal INT,--是否分摊过
		@cBillnumberid  NUMERIC(24, 10) ,
		@rowcount  INT ,		--已经合并的明细条数
		@accountCount int=0,
		@billatypeid INT=0

DECLARE @arCount INT=0,@draft INT=0,@audit INT=0,@Posbillnumberid NUMERIC(10,0)

CREATE TABLE #tempbillid (id INT IDENTITY(1,1),detailid INT)

DECLARE Pos_cursor CURSOR FOR
SELECT  PosID,BillnumberID,KID,BID,EID,billdate,PromoRuleId,VipCardID,Billtype,1,BillDescription,CouponCode,PromoIDs
FROM PosSaleBillIndex i
WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.PosMulAccountAll WHERE BillNumberId=i.BillnumberID AND ATypeID=-1)
GROUP BY PosID,BillnumberID,KID,BID,EID,billdate,PromoRuleId,VipCardID,Billtype,BillDescription,CouponCode,PromoIDs
OPEN Pos_cursor

FETCH NEXT FROM Pos_cursor
INTO @posID,@Posbillnumberid,@Kid,@BId,@Eid,@BillDate,@PromoRuleId,@VipCardID,@billtype,@billcount,@BillDescription,@CouponCodes,@PromoIDs

WHILE @@FETCH_STATUS = 0 
BEGIN
	-------------取表头信息 start-------
	SELECT  @ktypeid=typeid,@stypeid=STypeID FROM Stock WHERE Kid=@Kid
	SELECT  @CargoID=CargoID FROM dbo.CargoType WHERE KtypeID=@ktypeid AND IsDefault=1
	SELECT  @etypeid=typeid,@dtypeid=DtypeID FROM employee WHERE eid=@eid
	SELECT	@dfullname=fullname FROM dbo.Department WHERE typeid=@dtypeid
	SELECT  @Btypeid= typeid FROM dbo.BType WHERE Bid=@Bid
	--SELECT  @btypeid=typeid FROM btype WHERE bid=@bid
	-------------取表头信息 end---------
	
	IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
	BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版最多录200条单据 ！',16,1)
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT BillNumberId,'试用版最多录200条单据','' 
			FROM PosSaleBillIndex  b
			WHERE   b.BillnumberID=@Posbillnumberid AND  b.KID=@Kid AND b.BID=@Bid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId
		GOTO Error		 		
	END
	END  
	
	------------表头验证 start-----------
	--仓库
	IF NOT EXISTS(SELECT TOP 1 1 FROM stock WHERE kid=@kid AND deleted=0) --停用或者不存在
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT BillNumberId,'该单仓库不存在或已被停用','' 
			FROM PosSaleBillIndex  b
			WHERE  b.BillnumberID=@Posbillnumberid AND b.KID=@Kid AND b.BID=@Bid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId	
		GOTO Error
	END
	--往来单位
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.btype WHERE bid=@Bid AND deleted=0) --停用或者不存在
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT BillNumberId,'该单往来单位不存在或已被停用','' 
			FROM PosSaleBillIndex b
			WHERE  b.BillnumberID=@Posbillnumberid AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate	
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId	
			
		GOTO Error
	END
	--经手人
	IF NOT EXISTS(SELECT TOP 1 1 FROM employee WHERE eid=@eid)-- AND deleted=0) --停用或者不存在
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT BillNumberId,'该单经手人不存在','' 
			FROM PosSaleBillIndex b
			WHERE   b.BillnumberID=@Posbillnumberid AND  b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate	
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId	
			
		GOTO Error
	END
	
	--账户
	IF EXISTS(SELECT TOP 1 1 FROM dbo.PosMulAccount pb INNER JOIN dbo.PosSaleBillIndex b ON b.BillnumberID=pb.BillnumberID  
	WHERE  b.Billtype=@billtype AND  b.BillnumberID=@Posbillnumberid  	AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate AND NOT EXISTS(SELECT nId FROM dbo.Ac_Items WHERE deleted=0 AND nid=pb.ATypeID)) --停用或者不存在
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT DISTINCT b.BillNumberId,'该单存在收付款账户不存在或者被停用的情况','' 
			FROM PosMulAccount a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BillnumberID=@Posbillnumberid  
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND NOT EXISTS(SELECT nId FROM dbo.Ac_Items WHERE deleted=0 AND nid=a.ATypeID)				
	END
IF EXISTS(SELECT TOP 1 1 FROM  PosSaleBillIndex b 
			INNER JOIN dbo.employee e ON b.EID=e.Eid
			WHERE  b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId AND  b.BillnumberID=@Posbillnumberid 		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND b.premoney>ISNULL(e.MaxPre,-999999999918.99) AND ISNULL(e.MaxPre,-999999999918.99)<>-999999999918.99
			)
BEGIN			
	INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
	SELECT DISTINCT b.BillNumberId,'每单抹零金额超过限额','' 
			FROM PosSaleBillIndex b 
			INNER JOIN dbo.employee e ON b.EID=e.Eid
			WHERE   b.BillnumberID=@Posbillnumberid AND  b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND b.premoney>ISNULL(e.MaxPre,-999999999918.99) AND ISNULL(e.MaxPre,-999999999918.99)<>-999999999918.99
	GOTO Error
END			
	
	------------表头验证 end-------------
	
	------------表体验证 start ---------
IF EXISTS(SELECT TOP 1 1 FROM PosSaleBill a,
		PosSaleBillIndex b 
		WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
		AND b.BillnumberID=@posbillnumberid
		AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
		AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
		AND NOT EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0))
	BEGIN	
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
		SELECT DISTINCT b.BillNumberId,'该单存在商品不存在或者被停用的情况','' 
			FROM PosSaleBill a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.BillnumberID=@posbillnumberid
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND NOT EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0)
		GOTO Error	
	END

	------------表体验证 end-------------
	
	IF EXISTS(SELECT TOP 1 1 FROM PosSaleBill a
		INNER JOIN PosSaleBillIndex b ON a.BillnumberID=b.BillnumberID
		INNER JOIN dbo.ptype p  ON p.pid = a.PID AND p.iscombinationproduct = 1
		WHERE  b.BillnumberID=@posbillnumberid
		AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
		AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
		AND NOT EXISTS(SELECT 1 FROM dbo.CombinationProductIndex c WHERE c.CombinationProductPtypeId = p.typeId AND c.IsCheck = 1 AND c.IsStop = 0)
		)
	BEGIN	
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
		SELECT DISTINCT b.BillNumberId,'该单存在组合商品被停用或没有有效明细商品的情况','' 
			FROM PosSaleBill a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.BillnumberID=@posbillnumberid
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND NOT EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0)
		GOTO Error	
	END
	
	------------表体验证 start ---------
	IF EXISTS(SELECT TOP 1 1 FROM PosSaleBill a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.BillnumberID=@posbillnumberid
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0)
			AND NOT EXISTS(SELECT 1 FROM ptype p INNER JOIN dbo.PType_Units_Ext u ON p.typeId=u.PtypeID WHERE pid=a.PID AND u.UnitsId=a.UnitID))
	BEGIN     
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT DISTINCT b.BillNumberId,'该单存在商品单位不存在的情况','' 
			FROM PosSaleBill a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.BillnumberID=@posbillnumberid
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0)
			AND NOT EXISTS(SELECT 1 FROM ptype p INNER JOIN dbo.PType_Units_Ext u ON p.typeId=u.PtypeID WHERE pid=a.PID AND u.UnitsId=a.UnitID)
	GOTO Error
	END
	------------表体验证 end-------------
	
	
	-------------单据编号start----------
	
	DECLARE @hascombination INT
	DECLARE @tempbilltype VARCHAR(50) 
	
	SET @hascombination=0
	SELECT TOP 1 @hascombination = p.iscombinationproduct FROM PosSaleBill psb 
	INNER JOIN ptype p ON psb.pid=p.pid AND p.iscombinationproduct=1
	WHERE psb.BillnumberID = @Posbillnumberid
	
	IF @billtype = 307 AND @hascombination = 1 --组合品销售退货单46
		SET @tempbilltype = 46
	ELSE IF @billtype = 307		--零售退货单215
		SET @tempbilltype=215
    ELSE IF @billtype = 305		--零售单305
		SET @tempbilltype=305
	
	SELECT @Year=YEAR(GETDATE())
	IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @tempbilltype)  AND  EXISTS( SELECT 1 FROM UserConfig WHERE ConfigName='BillCodeConfig' AND Value='1') 
	BEGIN
		SELECT @MONTH = typeId FROM Employee WHERE Eid = @Eid
		SELECT @DAY = FullName FROM Stock WHERE Kid = @Kid
		SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @ETypeId
	END
	ELSE
	BEGIN
		SELECT @Month=Month(GETDATE())
		SELECT @Day=DAY(GETDATE())
	END
	
	

	
	
	--------------单据编号end------------
	SET @billtype = @tempbilltype
		
    DECLARE @VerifyID VARCHAR(50) 
    select @VerifyID=VerifyID from stype where typeid=@stypeid
	SELECT TOP 1 @atypeid1=AtypeId FROM BillAtype WHERE StypeId=@VerifyID AND BillTypeId= CAST(@billtype AS VARCHAR)
	
	IF @atypeid1 is null
		SET @atypeid1=''
	IF len(@atypeid1) = 0
		SET @atypeid1=''
	
	IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName = 'isvirtualstock' AND Value=1)
		AND EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName = 'virtualstockmode' AND Value=2)
		AND EXISTS(SELECT 1 WHERE @billtype IN (SELECT * FROM dbo.f_split((SELECT Value FROM dbo.Userconfig WHERE ConfigName='virtualstockbilltype'),',')))
		AND EXISTS(select 1 WHERE '0' IN (SELECT * FROM dbo.f_split((SELECT Value FROM dbo.Userconfig WHERE ConfigName='draftposting'),',')))
			SET @draft=1
	--将表头合并后的明细插入到零时表，
	TRUNCATE TABLE #PosSaleBill
	INSERT INTO #PosSaleBill 
	SELECT a.BillnumberID,p.PID,ABS(qty),BackQty,RetailPrice,tax,a.DisCount,Price,ABS(RetailTotal),ABS(total),UnitID,UnitRate,ItemID,IsCombined,BarCode,IsGift,
		a.comment,b.PosID,a.ID,DENSE_RANK() over(order by b.BillnumberID),a.PromoType,a.saleeid,a.validdate,a.producedate,a.goodsnumber,a.serial,
		a.goodscostprice,0,'',p.typeid,
		p.typeid+'_'+CAST(ROW_NUMBER() OVER(ORDER BY p.PID) AS VARCHAR) + '_'+RIGHT(100000000 + CONVERT(bigint, ABS(CHECKSUM(NEWID()))), 9),
		sk.typeid,a.couponcode,ISNULL(a.pricesource,''),a.PromoIDs
	FROM  PosSaleBillIndex b INNER JOIN PosSaleBill a ON a.BillnumberID=b.BillnumberID
	INNER JOIN ptype p  ON a.pid=p.pid
	INNER JOIN stock sk ON b.kid=sk.kid
	WHERE b.BillnumberID=@posbillnumberid 
	AND b.Billtype=CASE @billtype WHEN 215 THEN 307 WHEN 46 THEN 307 ELSE 305 end	
	AND b.BID=@Bid AND b.KID=@Kid
	AND b.EID=@Eid AND b.VipCardID=@VipCardID 
	AND billdate=@BillDate AND b.PromoRuleId=@PromoRuleId 
	AND b.BillnumberID=@posbillnumberid
	AND NOT EXISTS (SELECT 1 FROM dbo.PosSaleBill a WHERE a.BillnumberID=b.BillnumberID AND (NOT EXISTS(SELECT 1 FROM  ptype  WHERE pid=a.PID AND deleted=0) OR NOT EXISTS(SELECT 1 FROM ptype p INNER JOIN dbo.PType_Units_Ext u ON p.typeId=u.PtypeID WHERE pid=a.PID AND u.UnitsId=a.UnitID)))
	AND NOT EXISTS (SELECT 1 FROM dbo.PosMulAccount a WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE Deleted=0 AND nid=a.ATypeID) AND BillNumberId=b.BillnumberID)
	AND NOT EXISTS((SELECT TOP 1 1 FROM dbo.PosMulAccountAll WHERE BillNumberId=b.BillnumberID AND ATypeID=-1))
	ORDER BY b.BillnumberID,a.id
	--SELECT * FROM #PosSaleBill
	/***********************************处理组合品Start*******************************/
	DECLARE @isauto INT
	SET @isauto=0
	SELECT @isauto=autogenerate FROM posinfo WHERE posid=@posid--是否自动带入批次批号
	
	IF @hascombination=1
	BEGIN
		--处理上表体数据
		UPDATE #PosSaleBill SET iscombination = 1
		--插入下表体数据
		INSERT INTO #PosSaleBill
		SELECT BillnumberID,psb.PID,Qty,BackQty,RetailPrice,Tax,DisCount,Price,RetailTotal,
		Total,UnitID,UnitRate,ItemID,IsCombined,BarCode,IsGift,psb.Comment,posid,detailid,
		billId,PromoType,SaleEid,validdate,producedate,goodsnumber,
		serial,goodscostprice,0,combinationptypeid,ptypeid,pindexid,ktypeid,couponcode,pricesource,PromoIDs
		FROM #PosSaleBill psb INNER JOIN ptype p ON psb.pid=p.pid AND ISNULL(p.iscombinationproduct,0)=0
		
		IF (@isauto = 0)
			BEGIN
				--获取组合品配件信息
				--金额比例计算：((cpd.Price * cpd.qty ) / cpi.price)
				INSERT INTO #PosSaleBill
				SELECT psb.BillnumberID,p.PID,dbo.F_RoundQty(CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) as qty,dbo.F_RoundQty(BackQty),
				dbo.F_RoundPrice((psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) AS RetailPrice,
				dbo.F_RoundTax(tax),dbo.F_RoundDiscount(discount),
				dbo.F_RoundPrice((psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) AS price,
				dbo.F_RoundTotal(psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) AS RetailTotal,
				dbo.F_RoundTotal(psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) AS total,
				cpd.unit AS UnitID,u.rate AS UnitRate,cpd.ItemID,CASE WHEN ISNULL(p.customitemfrom,0)=1 THEN 1 ELSE 0 END AS IsCombined,p.entrycode as BarCode,psb.IsGift,'由组合品生成的配件商品' as comment,
				psb.PosID,psb.ID,DENSE_RANK() over(order by psb.BillnumberID),0 AS PromoType,
				psb.saleeid,'' as validdate,'' as producedate,'' as goodsnumber,'' as serial,-1 as goodscostprice,0,cpi.combinationproductptypeid,
				p.typeid,psb.pindexid,psb.ktypeid,psb.couponcode,psb.pricesource,psb.PromoIDs
				FROM CombinationProductdetail cpd
				INNER JOIN CombinationProductIndex cpi ON cpd.combinationproductid=cpi.combinationproductid AND cpi.isstop=0 AND cpi.ischeck=1 
				INNER JOIN Ptype p ON cpd.ptypeid=p.typeid --AND p.deleted = 0 
				INNER JOIN #PosSaleBill psb ON cpi.combinationproductptypeid=psb.ptypeid AND ISNULL(psb.iscombination,0)=1 
				INNER JOIN PType_Units_Ext u ON u.UnitsId=cpd.Unit AND u.ptypeId = cpd.PtypeID 
			END
		ELSE
			BEGIN
			--获取组合品配件信息
				--金额比例计算：((cpd.Price * cpd.qty ) / cpi.price)
				INSERT INTO #PosSaleBill
				SELECT psb.BillnumberID,p.PID,dbo.F_RoundQty(CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) as qty,dbo.F_RoundQty(BackQty),
				dbo.F_RoundPrice((psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) AS RetailPrice,
				dbo.F_RoundTax(tax),dbo.F_RoundDiscount(discount),
				dbo.F_RoundPrice((psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) AS price,
				dbo.F_RoundTotal(psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) AS RetailTotal,
				dbo.F_RoundTotal(psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) AS total,
				cpd.unit AS UnitID,u.rate AS UnitRate,
				ISNULL((select top 1 ItemID from GOODSSTOCKS_QTY gq 
                        inner join ptype p on p.typeid=gq.ptypeid
                        inner join stock s on s.typeid=gq.ktypeid
                        inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
                        where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
                        ),'') as ItemID,
				CASE WHEN ISNULL(p.customitemfrom,0)=1 THEN 1 ELSE 0 END AS IsCombined,
				p.entrycode as BarCode,psb.IsGift,'由组合品生成的配件商品' as comment,
				psb.PosID,psb.ID,DENSE_RANK() over(order by psb.BillnumberID),0 AS PromoType,
				psb.saleeid,
				ISNULL((select top 1 ValidDate from GOODSSTOCKS_QTY gq 
					inner join ptype p on p.typeid=gq.ptypeid
					inner join stock s on s.typeid=gq.ktypeid
					inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
					where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
                ),'') as validdate,
                ISNULL((select top 1 ProduceDate from GOODSSTOCKS_QTY gq 
					inner join ptype p on p.typeid=gq.ptypeid
					inner join stock s on s.typeid=gq.ktypeid
					inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
					where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid),'') as producedate,
                ISNULL((select top 1 GoodsNumber from GOODSSTOCKS_QTY gq 
					inner join ptype p on p.typeid=gq.ptypeid
					inner join stock s on s.typeid=gq.ktypeid
					inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
					where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
                ),'') as goodsnumber,
				'' as serial,-1 as goodscostprice,0,cpi.combinationproductptypeid,
				p.typeid,psb.pindexid,psb.ktypeid,psb.couponcode,psb.pricesource,psb.PromoIDs 
				FROM CombinationProductdetail cpd
				INNER JOIN CombinationProductIndex cpi ON cpd.combinationproductid=cpi.combinationproductid AND cpi.isstop=0 AND cpi.ischeck=1 
				INNER JOIN Ptype p ON cpd.ptypeid=p.typeid --AND p.deleted = 0 
				INNER JOIN #PosSaleBill psb ON cpi.combinationproductptypeid=psb.ptypeid AND ISNULL(psb.iscombination,0)=1 
				INNER JOIN PType_Units_Ext u ON u.UnitsId=cpd.Unit AND u.ptypeId = cpd.PtypeID 
			END
		
		UPDATE #PosSaleBill SET RetailTotal=dbo.F_RoundTotal(RetailTotal),Total=dbo.F_RoundTotal(Total)
		--组合品差异
		DECLARE @Diff TABLE(
			PindexID VARCHAR(100),
			Diff	 NUMERIC(24,10),
			RowIndex INT
		)

		DECLARE @RCount INT=0,
				@RIndex INT=1,
				@PIndexID VARCHAR(100),
				@ID INT,
				@DiffTotal NUMERIC(24,10)
	
		INSERT INTO @Diff
		        ( PindexID, Diff,RowIndex )
        SELECT  A.PindexID ,
                dbo.F_RoundTotal(A.Total - B.Total),
                ROW_NUMBER() OVER(ORDER BY GETDATE())
        FROM    ( SELECT    SUM(Total) AS Total ,
                            PindexId
                  FROM      #PosSaleBill psb
                  WHERE     ISNULL(Iscombination,0) = 1
                  GROUP BY  PindexId
                ) A
                INNER JOIN ( SELECT SUM(Total) AS Total ,
                                    PindexId
                             FROM   #PosSaleBill
                             WHERE  ISNULL(Iscombination,0) = 0
                             GROUP BY PindexId
                           ) B ON A.PIndexID = B.PIndexID
		WHERE A.Total-B.Total<>0
		
		SELECT @RCount=COUNT(1) FROM @Diff
		WHILE(@RIndex<=@RCount)
		BEGIN
			 SELECT @PIndexID=PIndexID,@DiffTotal=Diff FROM @Diff WHERE RowIndex=@RIndex
			 SELECT TOP 1 @ID=ID FROM #PosSaleBill WHERE PIndexID=@PIndexID AND ISNULL(IScombination,0)=0 AND Total >= @DiffTotal ORDER BY Total
			 UPDATE #PosSaleBill SET  RetailTotal=dbo.F_RoundTotal(RetailTotal+@DiffTotal),Total=dbo.F_RoundTotal(Total+@DiffTotal) WHERE ID=@ID
			 UPDATE #PosSaleBill SET  RetailPrice=dbo.F_RoundPrice(RetailTotal/Qty),Price=dbo.F_RoundPrice(Total/Qty) WHERE ID=@ID
			 SET @RIndex=@RIndex+1
		END
	END
	/***********************************处理组合品end**********************************/
	SELECT @billcount=max(billid)  FROM #PosSaleBill
	--SELECT @billcount=@billid	
	--按表头可以合并成好多条
	SELECT @billPage=CEILING(@billcount/@Size)
	SET @j=0
	SET @arCount=0
	TRUNCATE TABLE #BillMulAccount

	WHILE @j<@billPage --AND @i<@detalPage
	BEGIN
		BEGIN TRAN SaveBill
		BEGIN TRY	
			SELECT @detailcount=COUNT(1) FROM #PosSaleBill WHERE billId>@j*@Size AND billId<=(@j+1)*@Size
			SELECT @detalPage=CEILING(@detailcount/@DetialSize) --表头合并以后表体按500行明细需要拆分的单据数量
			SET @i= 0
			SET @aftotal=0
			SET @accountCount=0
			WHILE @i<@detalPage
			BEGIN
				TRUNCATE TABLE #tempbillid	
				DECLARE @startdate VARCHAR(50)
				SELECT @startdate= CONVERT(VARCHAR(10),startdate,120) FROM dbo.MonthProc WHERE MonthNo='本期' AND STypeID = @stypeid
				IF @billdate<@startdate
					SET @billdate=@startdate
					 
					SELECT @taxtotal=CAST(SUM(a.Total)AS  NUMERIC(24, 10) ),@qty=SUM(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))
					FROM #PosSaleBill a  
					INNER JOIN ptype p ON a.PID=p.Pid
					INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
					WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
						AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(a.iscombination,0)=0 
					
					
					SELECT @premoney = dbo.F_RoundTotal(CAST(SUM(CASE @billtype WHEN 305 THEN b.premoney ELSE -b.premoney END) AS  NUMERIC(24, 10))),
					       @totalinmoney= dbo.F_RoundTotal(CAST(SUM(CASE @billtype WHEN 305 THEN b.Totalinmoney ELSE -b.Totalinmoney END) AS  NUMERIC(24, 10))),
					       @SaveInCzMoney = dbo.F_RoundTotal(CAST(SUM(CASE @billtype WHEN 305 THEN b.SaveInCzMoney ELSE -b.SaveInCzMoney END) AS  NUMERIC(24, 10)))
					FROM PosSaleBillIndex b
					WHERE BillnumberID  IN (
					SELECT a.BillnumberID
					FROM #PosSaleBill a  
					INNER JOIN ptype p ON a.PID=p.Pid
					INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
					WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
						AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(a.iscombination,0)=0 
					)
						
					SELECT @accountCount=COUNT(1),@billatypeid=MAX(ATypeID)
					FROM
					 (
						SELECT DISTINCT(ATypeID)
						FROM dbo.PosMulAccount p INNER join  #PosSaleBill a  ON p.BillNumberId=a.billnumberid
						WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
							AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size
					)b
					
					SET @BillFlag=CASE @billtype WHEN 305 THEN 'LS' WHEN 215 THEN 'RB' ELSE 'ZXT' END 	
					SET @BillCode=''					
					--单据编号
					--insert into tempCode(billtype,[MONTH],[DAY],BillFlag,BillDate,stypeid,BillCode,dfullname)
					--values(@billtype,@MONTH,@DAY,@BillFlag,@BillDate,@stypeid,@BillCode,@dfullname)
					EXEC Gp_GetBillCode @billtype, @MONTH,@DAY,@BillFlag,@BillDate,@stypeid,@BillCode OUTPUT,@dfullname,@cefullname
					
									--保存种子数(生成就生效)
					IF NOT EXISTS(SELECT ConfigNo  FROM Userconfig  WHERE ConfigName='BillcodeCreateTime'AND Value=2)
					BEGIN
						EXEC GP_AutoCombneRetail_SaveBillCode_Seed @billdate,@billtype,@billcode,@etypeid,@ktypeid,@dtypeid,@stypeid,@cefullname
						
					END
					
					IF @BillCode='' GOTO ERROR --没取到billcode不保存
					-------------------具体合并 start----------------
					
					--IF  EXISTS(select 1 from BillIndex where BillDate=CONVERT(VARCHAR(10),@BillDate,120) and BillType=@billtype and atypeid=CASE WHEN @accountCount<=1 THEN ISNULL(@billatypeid,'') ELSE -99999 END and IfMulAccount=CASE WHEN @accountCount<=1 THEN 0 ELSE 1 END
					--			and btypeid=@btypeid and etypeid=@ETypeId and ktypeid=@ktypeid and ifcheck='f' and NewPosBill=1 and checke=@ETypeId 
					--			and totalmoney=dbo.F_RoundTotal(@taxtotal) and NTotalMoney=dbo.F_RoundTotal(@taxtotal) and totalinmoney=dbo.F_RoundTotal(@totalinmoney-@premoney)
					--			and NTotalInMoney=dbo.F_RoundTotal(@totalinmoney-@premoney) and totalqty=dbo.F_RoundQty(@qty) and packway=CASE WHEN @billtype=305 THEN CAST(dbo.F_RoundTotal(@totalinmoney-@premoney) AS VARCHAR) ELSE '' END and tax=0
					--			and tax=0 and period=1 and RedWord=0 and draft=1 and Comment='该单是由POS小票自动生成' and VipCardID=@vipcardid and IfAudit='3'
					--			and preferencemoney=dbo.F_RoundTotal(@premoney) and npreferencemoney=dbo.F_RoundTotal(@premoney) and DTypeId=@DTypeId 
					--			and Stypeid=@stypeid
					--			) 
					--BEGIN
					--	--继续循环存在重复数据
					--	GOTO Error
					--END
					/*
						任泉熹 2018-02-07 11:08:58
						重复单据编号，不自动生单，bug:307
					*/
					IF EXISTS(SELECT 1 FROM BillIndex WHERE BillCode=@BillCode) 
					BEGIN 
						ROLLBACK TRAN SaveBill
						GOTO ERROR
					END 
					
					INSERT INTO BillIndex 
					(
						CheckTime,BillTime,AlertDay,BillDate,BillCode,BillType,
						atypeid,IfMulAccount,btypeid,etypeid,ktypeid,ifcheck,NewPosBill,checke,
						totalmoney,NTotalMoney,totalinmoney,NTotalInMoney,totalqty,packway,
						tax,period,RedWord,draft,Comment,VipCardID,TEL,
						IfAudit,preferencemoney,npreferencemoney,DTypeId,Explain,Stypeid,CID,Rate,ATypeID1,
						DealBTypeID,PromoRuleId,IscombinationStyle,PromonIds,posid,ktypeid2,KTypeID3
					)
					SELECT  GETDATE(),CONVERT(VARCHAR(20), GETDATE(), 24),9999,CONVERT(VARCHAR(10),@BillDate,120),@BillCode,@billtype,
					CASE WHEN @accountCount<=1 THEN ISNULL(@billatypeid,'') ELSE -99999 END,CASE WHEN @accountCount<=1 THEN 0 ELSE 1 END,@btypeid,@ETypeId,@ktypeid,'f',1,@ETypeId,
					dbo.F_RoundTotal(@taxtotal),dbo.F_RoundTotal(@taxtotal),dbo.F_RoundTotal(@totalinmoney-@premoney),dbo.F_RoundTotal(@totalinmoney-@premoney),dbo.F_RoundQty(@qty),CASE WHEN @billtype=305 THEN CAST(dbo.F_RoundTotal(@totalinmoney-@premoney) AS VARCHAR) ELSE '' END,
					0,1,0,1,'该单是由POS小票自动生成',@vipcardid,0,
					'3',dbo.F_RoundTotal(@premoney),dbo.F_RoundTotal(@premoney),@DTypeId,@BillDescription,
					@stypeid,1,1,@atypeid1,@btypeid,@promoruleid,@hascombination,@PromoIDs,@posID,'',''
									
					SELECT @newbillnumberid=SCOPE_IDENTITY();
					INSERT INTO #daftBillNumerid VALUES(@newbillnumberid)
									
					IF @billtype=305     --983零售单，新增券信息到Coupon_BillUsed表中,并更改券信息Coupon_CodeInfo状态
					BEGIN
						IF @CouponCodes<>''
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= @billtype 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										CouponId
										
										
								)
							SELECT  @newbillnumberid,
									@billtype,
									@posID,
									a.a,
									C.CouponId
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode =A.a
							WHERE ISNULL(A,'')<>''
							
							UPDATE dbo.Coupon_CodeInfo SET [State]=3
							FROM Coupon_CodeInfo cci 
							INNER JOIN 
							(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode  
						END
						--SELECT * FROM Coupon_BillUsed WHERE BillnumberId=@newbillnumberid
						
						INSERT INTO [dbo].[RetailBill] 
						( 
							[BillNumberId],[PtypeId],[Qty],[SalePrice],[discount],[DiscountPrice],[total],[TaxPrice],[TaxTotal],
							[comment],isUnit2,[GoodsBTypeID],
							Tax,SaleTotal,STypeID,
							--9.0新字段
							TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,
							CargoId,UnitId,NUnitId,NQty,UnitRate,NUnitMsg,
							MUnitId,MQty,MUnitRate,MUnitMsg,
							MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
							ItemId,IsCombined,PosID,IsGift,PromoType,ETypeID,ValidDate,ProduceDate,GoodsNumber,Serial,
							GoodsCostPrice,GoodsCostTotal,iscombination,combinationptypeid,pindexid,ktypeid,CouponCode,PriceSource,PromonIds
						) 
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								a.comment,isUnit2=0,GoodsBTypeID='',
								0,a.RetailTotal,@stypeid,
								0,CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
								CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0,
								@CargoID,p.baseUnitId,ISNULL(p.AssistantUnitId,0),
								CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(ISNULL(u1.Rate,0) AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
								ISNULL(u1.Rate,0),--浮动单位换算率
								NULL,
								a.UnitID,a.Qty,u.Rate,NULL,
								a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,a.ItemID,a.IsCombined,a.posid,a.IsGift,a.PromoType,ISNULL(salee.typeId,'') AS etypeid,
								a.ValidDate,a.ProduceDate,a.GoodsNumber,a.Serial,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)),
								a.iscombination,a.combinationptypeid,a.pindexid ,a.ktypeid,a.couponcode,a.pricesource,ISNULL(a.PromoIds,'')
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1
						WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
							AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(iscombination,0)=0
						ORDER BY a.id
						
						
						INSERT INTO [dbo].[RetailCombinationBill] 
						( 
							[BillNumberId],[PtypeId],[Qty],[SalePrice],[discount],[DiscountPrice],[total],[TaxPrice],[TaxTotal],
							[comment],isUnit2,
							Tax,SaleTotal,STypeID,
							--9.0新字段
							TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,
							CargoId,UnitId,NUnitId,NQty,UnitRate,NUnitMsg,
							MUnitId,MQty,MUnitRate,MUnitMsg,
							MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
							ItemId,IsCombined,PosID,IsGift,PromoType,ETypeID,pindexid,CouponCode,PriceSource,PromonIds
						) 
						SELECT @newbillnumberid,p.typeId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								a.comment,isUnit2=0,
								0,a.RetailTotal,@stypeid,
								0,CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
								CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0,
								@CargoID,p.baseUnitId,ISNULL(p.AssistantUnitId,0),0,0,NULL,
								a.UnitID,a.Qty,u.Rate,NULL,
								a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,a.ItemID,a.IsCombined,a.posid,a.IsGift,a.PromoType,ISNULL(salee.typeId,'') AS etypeid,
								a.pindexid,a.couponcode,a.pricesource,a.PromoIds
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
							AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(iscombination,0)=1
						ORDER BY a.id
						
						
						
						UPDATE dbo.retailBill SET ShowOrder=ID,
													Qty=dbo.F_RoundQty(Qty),
													SalePrice=dbo.F_RoundPrice(SalePrice),
													discount=dbo.F_RoundDiscount(discount),
													DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
													costprice=dbo.F_RoundPrice(costprice),
													total=dbo.F_RoundTotal(total),
													TaxPrice=dbo.F_RoundPrice(TaxPrice),
													TaxTotal=dbo.F_RoundTotal(TaxTotal),
													InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
													BackQTY=dbo.F_RoundQty(BackQTY),
													SaleTotal=dbo.F_RoundTotal(SaleTotal),
													Tax=dbo.F_RoundTax(Tax),
													TaxMoney=dbo.F_RoundTotal(TaxMoney),
													NSalePrice=dbo.F_RoundPrice(NSalePrice),
													NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
													NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
													NTotal=dbo.F_RoundTotal(NTotal),
													NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
													NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
													NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
													NQty=dbo.F_RoundQty(NQty),
													MQty=dbo.F_RoundQty(MQty),
													MSalePrice=dbo.F_RoundPrice(MSalePrice),
													MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
													MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
													CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
													CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
													CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
													InvoiceQty=dbo.F_RoundQty(InvoiceQty),
													InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
													NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney)
						 WHERE BillNumberId=@newbillnumberid
						 
						 UPDATE dbo.retailCombinationBill SET 
													Qty=dbo.F_RoundQty(Qty),
													SalePrice=dbo.F_RoundPrice(SalePrice),
													discount=dbo.F_RoundDiscount(discount),
													DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
													total=dbo.F_RoundTotal(total),
													TaxPrice=dbo.F_RoundPrice(TaxPrice),
													TaxTotal=dbo.F_RoundTotal(TaxTotal),
													BackQTY=dbo.F_RoundQty(BackQTY),
													SaleTotal=dbo.F_RoundTotal(SaleTotal),
													Tax=dbo.F_RoundTax(Tax),
													TaxMoney=dbo.F_RoundTotal(TaxMoney),
													NSalePrice=dbo.F_RoundPrice(NSalePrice),
													NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
													NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
													NTotal=dbo.F_RoundTotal(NTotal),
													NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
													NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
													NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
													NQty=dbo.F_RoundQty(NQty),
													MQty=dbo.F_RoundQty(MQty),
													MSalePrice=dbo.F_RoundPrice(MSalePrice),
													MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
													MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
													CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
													CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
													CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
													InvoiceQty=dbo.F_RoundQty(InvoiceQty),
													InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
													NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney)
						 WHERE BillNumberId=@newbillnumberid
						 
						--新加 施训国存储过程 处理草稿库存
						EXEC GP_CopyOrCreateBill_DraftQTY  @newbillnumberid,305
						 
					END
					ELSE IF @billtype = 215	----983零售退货单新增券信息
					BEGIN
						IF @CouponCodes<>''
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= 215 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										CouponId
								)
							SELECT  @newbillnumberid,
									215,
									@posID,
									a.a,
									C.CouponId
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
							WHERE ISNULL(A,'')<>''
							
							UPDATE dbo.Coupon_CodeInfo SET [State]=5
							FROM Coupon_CodeInfo cci 
							INNER JOIN 
							(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode
						END
						
						INSERT INTO RetailBackBill
							  ( BillNumberId,PtypeId ,Qty,SalePrice,discount,DiscountPrice,total,TaxPrice,TaxTotal,
								comment,isUnit2,GoodsBTypeID,
								Tax,SaleTotal,Stypeid,
								TaxMoney,NSalePrice,NSaleTotal ,NDiscountPrice ,NTotal,NTaxPrice ,NTaxTotal,NTaxMoney ,
								CargoID,UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,
								MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
								CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
								ItemID,IsCombined,IsGift,
								InputCostPrice,HandZeroCost,PosId,PromoType,ETypeID ,
								ValidDate,ProduceDate,GoodsNumber,Serial,
								GoodsCostPrice,GoodsCostTotal,ktypeid,CouponCode,PriceSource,PromonIds
								) OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),CAST(a.retailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								a.comment,isUnit2=0,GoodsBTypeID='',
								0,a.RetailTotal,@stypeid,
								0,CAST(a.retailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0,
								@CargoID,p.baseUnitId,ISNULL(p.AssistantUnitId,0),
								ISNULL(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(ISNULL(u1.Rate,0) AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),0),--浮动单位数量=基本单位数量*浮动单位换算率
								ISNULL(u1.Rate,0),--浮动单位换算率
								NULL,
								a.UnitID,a.Qty,u.Rate,NULL, 
								a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
								a.ItemID,a.IsCombined,a.IsGift,0,0,a.posid,a.PromoType,ISNULL(salee.typeId,'') AS etypeid,
								a.ValidDate,a.ProduceDate,a.GoodsNumber,a.Serial,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)),a.ktypeid,a.couponcode,a.pricesource,a.PromoIds
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1
						WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
							AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(a.iscombination,0)=0 
						ORDER BY a.id
						UPDATE dbo.RetailBackBill SET ShowOrder=ID,
							Qty=dbo.F_RoundQty(Qty),
							SalePrice=dbo.F_RoundPrice(SalePrice),
							discount=dbo.F_RoundDiscount(discount),
							DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
							costprice=dbo.F_RoundPrice(costprice),
							total=dbo.F_RoundTotal(total),
							TaxPrice=dbo.F_RoundPrice(TaxPrice),
							TaxTotal=dbo.F_RoundTotal(TaxTotal),
							InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
							SaleTotal=dbo.F_RoundTotal(SaleTotal),
							Tax=dbo.F_RoundTax(Tax),
							TaxMoney=dbo.F_RoundTotal(TaxMoney),
							NSalePrice=dbo.F_RoundPrice(NSalePrice),
							NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
							NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
							NTotal=dbo.F_RoundTotal(NTotal),
							NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
							NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
							NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
							NQty=dbo.F_RoundQty(NQty),
							MQty=dbo.F_RoundQty(MQty),
							MSalePrice=dbo.F_RoundPrice(MSalePrice),
							MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
							MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
							CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
							CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
							CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
							InvoiceQty=dbo.F_RoundQty(InvoiceQty),
							InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
							NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
							CompleteQty=dbo.F_RoundQty(CompleteQty)
							 WHERE BillNumberId=@newbillnumberid
							 
					
					--新加 施训国存储过程 处理草稿库存
					EXEC GP_CopyOrCreateBill_DraftQTY  @newbillnumberid,215
					
					END
					ELSE IF @billtype = 46     --组合品销售退货单
					BEGIN
						IF @CouponCodes<>''
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= @billtype 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										CouponId
										
										
								)
							SELECT  @newbillnumberid,
									@billtype,
									@posID,
									a.a,
									C.CouponId
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode =A.a
							WHERE ISNULL(A,'')<>''
							
							UPDATE dbo.Coupon_CodeInfo SET [State]=5
							FROM Coupon_CodeInfo cci 
							INNER JOIN 
							(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode  
						END
						--SELECT * FROM Coupon_BillUsed WHERE BillnumberId=@newbillnumberid
						
						INSERT INTO [dbo].[PT_Combin_SaleBackBillDetail] 
						( 
							[BillNumberId],[PtypeId],[Qty],[SalePrice],[discount],[DiscountPrice],[total],[TaxPrice],[TaxTotal],
							[comment],isUnit2,[GoodsBTypeID],
							Tax,SaleTotal,STypeID,
							--9.0新字段
							TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,
							CargoId,UnitId,NUnitId,NQty,UnitRate,NUnitMsg,
							MUnitId,MQty,MUnitRate,MUnitMsg,
							MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
							ItemId,IsCombined,IsGift,PromoType,ValidDate,ProduceDate,GoodsNumber,Serial,
							GoodsCostPrice,GoodsCostTotal,combinationptypeid,pindexid,ktypeid,PriceSource
						) 
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								a.comment,isUnit2=0,GoodsBTypeID='',
								0,a.RetailTotal,@stypeid,
								0,CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
								CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0,
								@CargoID,p.baseUnitId,ISNULL(p.AssistantUnitId,0),
								CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(ISNULL(u1.Rate,0) AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
								ISNULL(u1.Rate,0),--浮动单位换算率
								NULL,
								a.UnitID,a.Qty,u.Rate,NULL,
								a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,a.ItemID,a.IsCombined,a.IsGift,a.PromoType,
								a.ValidDate,a.ProduceDate,a.GoodsNumber,a.Serial,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)),
								a.combinationptypeid,a.pindexid ,a.ktypeid,a.pricesource
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1
						WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
							AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(iscombination,0)=0
						ORDER BY a.id
						
						
						INSERT INTO [dbo].[PT_Combin_SaleBackBill] 
						( 
							[BillNumberId],[PtypeId],[Qty],[SalePrice],[discount],[DiscountPrice],[total],[TaxPrice],[TaxTotal],
							[comment],isUnit2,
							Tax,SaleTotal,STypeID,
							--9.0新字段
							TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,
							CargoId,UnitId,NUnitId,NQty,UnitRate,NUnitMsg,
							MUnitId,MQty,MUnitRate,MUnitMsg,
							MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
							ItemId,IsCombined,IsGift,PromoType,pindexid,CouponCode,PriceSource,ktypeid
						) 
						SELECT @newbillnumberid,p.typeId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
						a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								a.comment,isUnit2=0,
								0,a.RetailTotal,@stypeid,
								0,CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
								CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
								CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0,
								@CargoID,p.baseUnitId,ISNULL(p.AssistantUnitId,0),0,0,NULL,
								a.UnitID,a.Qty,u.Rate,NULL,
								a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,a.ItemID,a.IsCombined,a.IsGift,a.PromoType,
								a.pindexid,a.couponcode,a.pricesource,a.ktypeid
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
							AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(iscombination,0)=1
						ORDER BY a.id
						
						
						
						UPDATE dbo.PT_Combin_SaleBackBillDetail SET ShowOrder=ID,
													Qty=dbo.F_RoundQty(Qty),
													SalePrice=dbo.F_RoundPrice(SalePrice),
													discount=dbo.F_RoundDiscount(discount),
													DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
													costprice=dbo.F_RoundPrice(costprice),
													total=dbo.F_RoundTotal(total),
													TaxPrice=dbo.F_RoundPrice(TaxPrice),
													TaxTotal=dbo.F_RoundTotal(TaxTotal),
													InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
													SaleTotal=dbo.F_RoundTotal(SaleTotal),
													Tax=dbo.F_RoundTax(Tax),
													TaxMoney=dbo.F_RoundTotal(TaxMoney),
													NSalePrice=dbo.F_RoundPrice(NSalePrice),
													NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
													NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
													NTotal=dbo.F_RoundTotal(NTotal),
													NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
													NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
													NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
													NQty=dbo.F_RoundQty(NQty),
													MQty=dbo.F_RoundQty(MQty),
													MSalePrice=dbo.F_RoundPrice(MSalePrice),
													MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
													MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
													CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
													CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
													CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
													InvoiceQty=dbo.F_RoundQty(InvoiceQty),
													InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
													NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney)
						 WHERE BillNumberId=@newbillnumberid
						 
						 UPDATE dbo.PT_Combin_SaleBackBill SET 
													Qty=dbo.F_RoundQty(Qty),
													SalePrice=dbo.F_RoundPrice(SalePrice),
													discount=dbo.F_RoundDiscount(discount),
													DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
													total=dbo.F_RoundTotal(total),
													TaxPrice=dbo.F_RoundPrice(TaxPrice),
													TaxTotal=dbo.F_RoundTotal(TaxTotal),
													SaleTotal=dbo.F_RoundTotal(SaleTotal),
													Tax=dbo.F_RoundTax(Tax),
													TaxMoney=dbo.F_RoundTotal(TaxMoney),
													NSalePrice=dbo.F_RoundPrice(NSalePrice),
													NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
													NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
													NTotal=dbo.F_RoundTotal(NTotal),
													NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
													NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
													NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
													NQty=dbo.F_RoundQty(NQty),
													MQty=dbo.F_RoundQty(MQty),
													MSalePrice=dbo.F_RoundPrice(MSalePrice),
													MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
													MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
													CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
													CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
													CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
													InvoiceQty=dbo.F_RoundQty(InvoiceQty),
													InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
													NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney)
						 WHERE BillNumberId=@newbillnumberid
						 
						--新加 施训国存储过程 处理草稿库存
						EXEC GP_CopyOrCreateBill_DraftQTY  @newbillnumberid,@billtype
						 
					END
					
				   SELECT @rowcount=@@ROWCOUNT	
					
							
					INSERT INTO PosRetailRecord
					( 
						PosSaleBillId,PosBillNumberId,RetailBillId,RetailBillNumberId,AuditingFlag,ReCordTime
					)
					SELECT c.detailid,c.billnumberid,t.detailid,@newbillnumberid,0 ,GETDATE()
					FROM
						(
							SELECT   row_number() over (order by Id) AS orderid,
							billnumberid,detailid 
							FROM #PosSaleBill 
							WHERE  ID>@arCount AND ID<=(@arCount+@DetialSize) 
									AND billId>@j*@Size AND billId<=(@j+1)*@Size
						)c
					INNER JOIN #tempbillid t ON t.ID=c.orderid
					
					SELECT @arCount=@arCount+@rowcount
					--SELECT * FROM #tempbillid
					--拆分实收金额
				   SELECT @tmpdetailmaxid=MAX(detailid) FROM #tempbillid
				   SELECT @tmpdetailminid=MIN(detailid) FROM #tempbillid
				   
				   SELECT @tmpmaxbillnumberid=PosBillNumberId FROM PosRetailRecord WHERE RetailBillId= @tmpdetailmaxid
				   SELECT @tmpminbillnumberid=PosBillNumberId FROM PosRetailRecord WHERE RetailBillId= @tmpdetailminid
				   
					
				 --一张pos单拆分多张零售单的情况（收款情况分摊）
				 --拆分后的第1到N-1张零售单
				 IF @detalPage>1
				 BEGIN		
					SELECT @Maxftotal=SUM(total) FROM #PosSaleBill 
					WHERE  ID>@arCount-@rowcount AND ID<=(@arCount+@DetialSize-@rowcount) 
					AND billId>@j*@Size AND billId<=(@j+1)*@Size
					AND billnumberid=@tmpmaxbillnumberid
					
					INSERT INTO #BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotal,posBillNumberId,yhType,CouponCode,VipTotal)
					SELECT  @newbillnumberid,ATypeID,
					CASE WHEN ATypeID=1 THEN 
					SUM(Round((@maxftotal/b.Totalinmoney),4)*a.atotal) - ISNULL(@SaveInCzMoney,0)
					ELSE 
					SUM(Round((@maxftotal/b.Totalinmoney),4)*a.atotal) END,
					a.Comment,a.VipCardID,
					CASE WHEN ATypeID=1 THEN 
					SUM(Round((@maxftotal/b.Totalinmoney),4)*a.atotal) - ISNULL(@SaveInCzMoney,0)
					ELSE 
					SUM(Round((@maxftotal/b.Totalinmoney),4)*a.atotal) END,
					a.BillNumberId,
					a.yhType,
					a.CouponCode,
					a.VipTotal
					FROM PosMulAccount a
					INNER JOIN PosSaleBillIndex b ON a.BillNumberId=b.BillnumberID
					WHERE b.BillnumberID=@tmpmaxbillnumberid AND a.ATypeID<>(SELECT TOP 1 atypeid FROM dbo.PosMulAccount WHERE BillnumberID=@tmpmaxbillnumberid ORDER BY ATypeID DESC)
					GROUP BY ATypeID,a.VipCardID,a.BillNumberId,a.yhType,a.CouponCode,a.Comment,a.VipTotal
					
					SELECT @minFtotal=ISNULL(SUM(Total),0) FROM #BillMulAccount WHERE posBillNumberId=@tmpmaxbillnumberid
					
					INSERT INTO #BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotal,posBillNumberId,yhType,CouponCode,VipTotal)
					SELECT  @newbillnumberid,ATypeID,@Maxftotal-@minFtotal,Comment,VipCardID,@Maxftotal-@minFtotal,BillNumberId,yhType,CouponCode,VipTotal
					FROM PosMulAccount 
					WHERE BillnumberID=@tmpmaxbillnumberid AND ATypeID=(SELECT TOP 1 atypeid FROM dbo.PosMulAccount WHERE BillnumberID=@tmpmaxbillnumberid ORDER BY ATypeID DESC)	
						
				    INSERT INTO BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotalMoney,Billtype,yhType,CouponCode,VipTotal)
					SELECT BillNumberId ,ATypeID ,SUM(Total) ,Comment ,VipCardID ,SUM(ntotal),billtype,yhType,CouponCode,VipTotal
					FROM
					(
						SELECT  @newbillnumberid AS BillNumberId,ATypeID,a.atotal AS total,Comment,VipCardID,a.atotal AS ntotal,(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,yhType,CouponCode,VipTotal
						FROM PosMulAccount a
						INNER JOIN (SELECT DISTINCT PosBillNumberId FROM PosRetailRecord WHERE RetailBillNumberId=@newbillnumberid ) b 
						ON a.BillNumberId=b.PosBillNumberId
						WHERE a.BillNumberId <>@tmpmaxbillnumberid AND a.BillNumberId<>@tmpminbillnumberid
						UNION ALL
						SELECT  @newbillnumberid BillNumberId,ATypeID,total,Comment,VipCardID,ntotal,(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,yhType,CouponCode ,VipTotal
						FROM #BillMulAccount a
						WHERE a.BillnumberID=@newbillnumberid
						UNION ALL
						SELECT @newbillnumberid AS BillNumberId,b.atypeid,b.atotal-ISNULL(a.total,0) AS total,b.Comment,b.VipCardID,b.atotal-ISNULL(a.total,0) AS ntota,(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,yhType,CouponCode,VipTotal
						FROM  PosMulAccount b
						LEFT JOIN
						(
							SELECT  posBillNumberId,ATypeID,SUM(Total) AS total,Comment,VipCardID,SUM(ntotal) AS ntotal,(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,yhType,CouponCode,VipTotal
							FROM #BillMulAccount a
							WHERE a.posBillNumberId=@tmpminbillnumberid
							GROUP BY posBillNumberId,ATypeID,Comment,VipCardID,yhType,CouponCode,VipTotal
						) a ON a.atypeid=b.ATypeID AND a.posBillNumberId=b.BillNumberId
						WHERE b.BillNumberId=@tmpminbillnumberid
					) a
					GROUP BY BillNumberId,ATypeID,VipCardID,Comment,yhType,CouponCode,VipTotal
				 END
				  --不用拆分的情况
				  ELSE
				  BEGIN
					INSERT INTO BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotalMoney,billtype,yhType,CouponCode,VipTotal)
					SELECT  
					@newbillnumberid,
					ATypeID,
					CASE 
						WHEN a.atypeid=1 THEN SUM(a.atotal) - ISNULL(@SaveInCzMoney,0)
						WHEN a.paystyle='现金' THEN SUM(a.atotal) - ISNULL(@SaveInCzMoney,0)
						ELSE SUM(a.atotal) 
					END,
					a.Comment,
					VipCardID,
					CASE 
						WHEN a.atypeid=1 THEN SUM(a.atotal)- ISNULL(@SaveInCzMoney,0)  
						WHEN a.paystyle='现金' THEN SUM(a.atotal)- ISNULL(@SaveInCzMoney,0)  
						ELSE SUM(a.atotal)  
					END,
					(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,
					a.yhType,
					a.CouponCode,
					a.VipTotal
					FROM PosMulAccount a
					INNER JOIN (SELECT DISTINCT PosBillNumberId FROM PosRetailRecord WHERE RetailBillNumberId=@newbillnumberid ) b 
					ON a.BillNumberId=b.PosBillNumberId
					GROUP BY ATypeID,VipCardID,paystyle,a.Comment,a.yhType,a.CouponCode,a.VipTotal
				  END	
					-------------------具体合并 end----------------
					------------------983更改启用品牌则写入品牌信息start---
					DECLARE @billtypeflag INT,@brandTypeId VARCHAR(200)
					IF EXISTS(SELECT * FROM BillMulAccount WHERE BillNumberId = @newbillnumberid) 
					AND EXISTS ( SELECT  * FROM  dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue = 1 )
					BEGIN
						SELECT @billtypeflag=billtype FROM dbo.BillIndex where billnumberid=@newbillnumberid
						IF @billtypeflag=305
						BEGIN
							/*
							* 任泉熹 2018年3月8日 15:35:21
							* 品牌应收，在选择了组合品的情况下，应该统计上表体，而不是下表体
							* 增加@hascombination=1判断，如果选择了组合品，则从RetailCombinationBill表中查询数据，而不是RetailBill
							* bug：4414
							*/
							IF @hascombination=1
							BEGIN
								INSERT INTO dbo.BillMulBrand
								( STypeID ,
								  BTypeID ,
								  BrandarTypeID ,
								  BillNumberId ,
								  BillType ,
								  Cid ,
								  Rate ,
								  TaxTotal ,
								  NTaxTotal ,
								  PreferenceMoney ,
								  NPreferenceMoney ,
								  TotalInMoney ,
								  NTotalInMoney ,
								  YSTotalInMoney ,
								  NYSTotalInMoney ,
								  TheOrderARTotal ,
								  NTheOrderARTotal ,
								  isIni
								)
								SELECT BI.Stypeid,BI.btypeid,P.BrandarTypeID,
								BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.TaxTotal),SUM(S.NTaxTotal),0,0,SUM(S.TaxTotal),SUM(S.NTaxTotal),
								0,0,0,0,0
								FROM dbo.RetailCombinationBill S INNER JOIN PTYPE P ON S.PtypeId = P.typeId
								INNER JOIN dbo.brandar_Commodity B ON B.TypeId = P.BrandarTypeID
								INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
								WHERE BI.BillNumberId = @newbillnumberid AND S.TaxTotal <> 0--如果是赠品，则不添加到多账户中 ps重新修改986bug416：不是判断赠品，而是判断是否有金额
								GROUP BY P.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate
							END
							ELSE
							BEGIN
								INSERT INTO dbo.BillMulBrand
								( STypeID ,
								  BTypeID ,
								  BrandarTypeID ,
								  BillNumberId ,
								  BillType ,
								  Cid ,
								  Rate ,
								  TaxTotal ,
								  NTaxTotal ,
								  PreferenceMoney ,
								  NPreferenceMoney ,
								  TotalInMoney ,
								  NTotalInMoney ,
								  YSTotalInMoney ,
								  NYSTotalInMoney ,
								  TheOrderARTotal ,
								  NTheOrderARTotal ,
								  isIni
								)
								SELECT BI.Stypeid,BI.btypeid,P.BrandarTypeID,
								BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.TaxTotal),SUM(S.NTaxTotal),0,0,SUM(S.TaxTotal),SUM(S.NTaxTotal),
								0,0,0,0,0
								FROM dbo.retailBill S INNER JOIN PTYPE P ON S.PtypeId = P.typeId
								INNER JOIN dbo.brandar_Commodity B ON B.TypeId = P.BrandarTypeID
								INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
								WHERE BI.BillNumberId = @newbillnumberid AND S.TaxTotal <> 0--如果是赠品，则不添加到多账户中
								GROUP BY P.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate
							END
							
							SELECT TOP 1 @brandTypeId =  BrandarTypeID FROM dbo.BillMulBrand WHERE BillNumberId = @newbillnumberid ORDER BY NTaxTotal DESC
				
							UPDATE dbo.BillMulBrand SET PreferenceMoney = BI.preferencemoney,NPreferenceMoney =BI.NPreferenceMoney,
							TotalInMoney = BB.TotalInMoney-BI.preferencemoney,NTotalInMoney = BB.NTotalInMoney - BI.NPreferenceMoney
							FROM dbo.BillMulBrand BB
							INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = BB.BillNumberId WHERE BB.BillNumberId = @newbillnumberid AND BB.BrandarTypeID=@brandTypeId
						END
						ELSE IF @billtypeflag=46 --组合品销售退货单
						BEGIN
							INSERT INTO dbo.BillMulBrand
							( STypeID ,
							  BTypeID ,
							  BrandarTypeID ,
							  BillNumberId ,
							  BillType ,
							  Cid ,
							  Rate ,
							  TaxTotal ,
							  NTaxTotal ,
							  PreferenceMoney ,
							  NPreferenceMoney ,
							  TotalInMoney ,
							  NTotalInMoney ,
							  YSTotalInMoney ,
							  NYSTotalInMoney ,
							  TheOrderARTotal ,
							  NTheOrderARTotal ,
							  isIni
							)
							SELECT BI.Stypeid,BI.btypeid,P.BrandarTypeID,
							BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.TaxTotal),SUM(S.NTaxTotal),0,0,SUM(S.TaxTotal),SUM(S.NTaxTotal),
							0,0,0,0,0
							FROM dbo.PT_Combin_SaleBackBill S INNER JOIN PTYPE P ON S.PtypeId = P.typeId
							INNER JOIN dbo.brandar_Commodity B ON B.TypeId = P.BrandarTypeID
							INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
							WHERE BI.BillNumberId = @newbillnumberid AND S.TaxTotal <> 0--如果是赠品，则不添加到多账户中
							GROUP BY P.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate
							
							SELECT TOP 1 @brandTypeId =  BrandarTypeID FROM dbo.BillMulBrand WHERE BillNumberId = @newbillnumberid ORDER BY NTaxTotal DESC
				
							UPDATE dbo.BillMulBrand SET PreferenceMoney = BI.preferencemoney,NPreferenceMoney =BI.NPreferenceMoney,
							TotalInMoney = BB.TotalInMoney-BI.preferencemoney,NTotalInMoney = BB.NTotalInMoney - BI.NPreferenceMoney
							FROM dbo.BillMulBrand BB
							INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = BB.BillNumberId WHERE BB.BillNumberId = @newbillnumberid AND BB.BrandarTypeID=@brandTypeId
						END
						ELSE
						BEGIN
							INSERT INTO dbo.BillMulBrand
								( STypeID ,
								  BTypeID ,
								  BrandarTypeID ,
								  BillNumberId ,
								  BillType ,
								  Cid ,
								  Rate ,
								  TaxTotal ,
								  NTaxTotal ,
								  PreferenceMoney ,
								  NPreferenceMoney ,
								  TotalInMoney ,
								  NTotalInMoney ,
								  YSTotalInMoney ,
								  NYSTotalInMoney ,
								  TheOrderARTotal ,
								  NTheOrderARTotal ,
								  isIni
								)
							SELECT BI.Stypeid,BI.btypeid,P.BrandarTypeID,
							BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.TaxTotal),SUM(S.NTaxTotal),0,0,SUM(S.TaxTotal),SUM(S.NTaxTotal),
							0,0,0,0,0
							FROM dbo.RetailBackBill S INNER JOIN PTYPE P ON S.PtypeId = P.typeId
							INNER JOIN dbo.brandar_Commodity B ON B.TypeId = P.BrandarTypeID
							INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
							WHERE BI.BillNumberId = @newbillnumberid AND S.TaxTotal <> 0
							GROUP BY P.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate  
				
							SELECT TOP 1 @brandTypeId =  BrandarTypeID FROM dbo.BillMulBrand WHERE BillNumberId = @newbillnumberid ORDER BY NTaxTotal DESC
				
							UPDATE dbo.BillMulBrand SET PreferenceMoney = BI.preferencemoney,NPreferenceMoney =BI.NPreferenceMoney,
							TotalInMoney = BB.TotalInMoney-BI.preferencemoney,NTotalInMoney = BB.NTotalInMoney - BI.NPreferenceMoney
							FROM dbo.BillMulBrand BB
							INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = BB.BillNumberId WHERE BB.BillNumberId = @newbillnumberid AND BB.BrandarTypeID=@brandTypeId;
						END
					END
					
					------------------983更改启用品牌则写入品牌信息end---
				
								--保存种子数(生单后生效)
				IF EXISTS(SELECT ConfigNo  FROM Userconfig  WHERE ConfigName='BillcodeCreateTime'AND Value=0)
				BEGIN
					EXEC GP_AutoCombneRetail_SaveBillCode_Seed @billdate,@billtype,@billcode,@etypeid,@ktypeid,@dtypeid,@stypeid,@cefullname
				END	
				
				SET @i=@i+1
			END
			SET @j = @j+1
		
			IF EXISTS(SELECT TOP 1 1 FROM dbo.PosRetailRecord WHERE PosBillNumberId = @Posbillnumberid AND RetailBillNumberId <> @newbillnumberid) 
			BEGIN 
				ROLLBACK TRAN SaveBill
			END 
			ELSE
			BEGIN			
				COMMIT TRAN SaveBill
			END 
		END TRY
		begin CATCH
		    SELECT ERROR_MESSAGE() AS errormessage
			ROLLBACK TRAN SaveBill
		END CATCH
	END

	ERROR:
	
	FETCH NEXT FROM Pos_cursor
	INTO @posID,@Posbillnumberid,@Kid,@Bid,@Eid,@BillDate,@PromoRuleId,@VipCardID,@billtype,@billcount,@BillDescription,@CouponCodes,@PromoIDs
END
CLOSE Pos_cursor
DEALLOCATE Pos_cursor

BEGIN
	BEGIN TRAN DelBill
	BEGIN TRY
		SELECT BillnumberID INTO #DeletedBillID FROM dbo.PosSaleBillIndex WHERE BillnumberID IN (SELECT PosBillNumberId FROM dbo.PosRetailRecord)
		DELETE FROM dbo.PosSaleBill WHERE BillnumberID IN (SELECT BillnumberID FROM #DeletedBillID)
		DELETE FROM dbo.PosMulAccount WHERE BillnumberID IN (SELECT BillnumberID FROM #DeletedBillID)
		DELETE FROM dbo.PosSaleBillIndex WHERE BillnumberID IN (SELECT BillnumberID FROM #DeletedBillID)	
		COMMIT TRAN DelBill
		DROP TABLE #DeletedBillID
	END TRY
	begin CATCH
		ROLLBACK TRAN DelBill
	END CATCH
END
DROP TABLE #PosSaleBill,#tempbillid,#BillMulAccount

DECLARE @Ret INT=0,@frozedate DATE
DECLARE AuditingCursor CURSOR FOR
SELECT BillNumberId FROM #daftBillNumerid
OPEN AuditingCursor
FETCH NEXT FROM AuditingCursor
INTO @Newbillnumberid
WHILE @@FETCH_STATUS = 0 
BEGIN	
	SET @frozedate=NULL
	SELECT @billtype=billtype,@billdate=BillDate,@stypeid=Stypeid,@billcode=BillCode,@ktypeid=ktypeid,@dtypeid=DTypeId,@etypeid=etypeid FROM dbo.BillIndex WHERE BillNumberId=@Newbillnumberid
	SELECT @frozedate=FrozeDate FROM dbo.FrozeBusiness WHERE Stypeid=@stypeid
	IF @frozedate IS NOT NULL AND @frozedate>@billdate
		GOTO ERROR1
		
	IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName = 'isvirtualstock' AND Value=1)
		AND EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName = 'virtualstockmode' AND Value=2)
		AND EXISTS(SELECT 1 WHERE @billtype IN (SELECT * FROM dbo.f_split((SELECT Value FROM dbo.Userconfig WHERE ConfigName='virtualstockbilltype'),',')))
		AND EXISTS(select 1 WHERE '1' IN (SELECT * FROM dbo.f_split((SELECT Value FROM dbo.Userconfig WHERE ConfigName='draftposting'),',')))
			SET @audit=1
	BEGIN TRAN AUDIT
	
	--保存种子数，过账后生效
	IF EXISTS(SELECT ConfigNo  FROM Userconfig  WHERE ConfigName='BillcodeCreateTime'AND Value=2)
	BEGIN
		SELECT @Month=Month(GETDATE())
		SELECT @Day=DAY(GETDATE())
		SET @BillFlag=CASE @billtype WHEN 305 THEN 'LS' WHEN 215 THEN 'RB' ELSE 'ZXT' END 	
		SET @BillCode=''	
		----单据编号
		EXEC Gp_GetBillCode @billtype, @MONTH,@DAY,@BillFlag,@BillDate,@stypeid,@BillCode OUTPUT,@dfullname,@cefullname
		
		UPDATE dbo.BillIndex SET BillCode= @billcode 
		WHERE BillNumberId=@Newbillnumberid

		--保存种子数
		EXEC GP_AutoCombneRetail_SaveBillCode_Seed @billdate,@billtype,@billcode,@etypeid,@ktypeid,@dtypeid,@stypeid,@cefullname
	END	    

	IF((SELECT Billtype FROM dbo.PosSaleBillIndexAll WHERE BillnumberID=(SELECT MAX(BillnumberID) FROM dbo.PosSaleBillIndexAll))=305)
	BEGIN
		DECLARE @countitem INT
		SET @countitem=(
			SELECT COUNT(ptypeid) FROM dbo.retailBill psb
			INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
			WHERE p.customitemid IS NOT NULL
			AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.retailBill)
			)
		IF(@countitem<>0)
		BEGIN
			DECLARE @num INT=0
			DECLARE @itemidtemp INT=0
			WHILE @num<@countitem
			BEGIN 
				SET @itemidtemp=(SELECT T1.ItemID FROM(SELECT ROW_NUMBER() OVER (ORDER BY t.ptypeid) AS rowNum,T.ptypeid,T.ItemID FROM(SELECT ItemID,ptypeid FROM dbo.retailBill WHERE ptypeid IN(
								SELECT ptypeid FROM dbo.retailBill psb
								INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
								WHERE p.customitemid IS NOT NULL
								AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.retailBill))  AND BillNumberId=(SELECT MAX(BillnumberID) FROM dbo.retailBill)) T) AS T1 WHERE T1.rowNum=@num+1)
				SET @num=@num+1
				IF(@itemidtemp=0)
				BEGIN
					ROLLBACK TRAN AUDIT
					RETURN -1
				END 
			END
		END
	END
	ELSE  IF @billtype = 46	
	BEGIN
		DECLARE @countitem2 INT
		SET @countitem2=(
		SELECT COUNT(ptypeid) FROM dbo.PT_Combin_SaleBackBillDetail psb
		INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
		WHERE p.customitemid IS NOT NULL
		AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBackBillDetail))
		IF(@countitem2<>0)
		BEGIN
			DECLARE @num2 INT=0
			DECLARE @itemidtemp2 INT=0
			WHILE @num2<@countitem2
			BEGIN 
				SET @itemidtemp2=(SELECT T1.ItemID FROM(SELECT ROW_NUMBER() OVER (ORDER BY t.ptypeid) AS rowNum,T.ptypeid,T.ItemID FROM(SELECT ItemID,ptypeid FROM dbo.PT_Combin_SaleBackBillDetail WHERE ptypeid IN(
								SELECT ptypeid FROM dbo.PT_Combin_SaleBackBillDetail psb
								INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
								WHERE p.customitemid IS NOT NULL
								AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBackBillDetail))  AND BillNumberId=(SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBackBillDetail)) T) AS T1 WHERE T1.rowNum=@num2+1)
				SET @num2=@num2+1
				IF(@itemidtemp2=0)
				BEGIN
					ROLLBACK TRAN AUDIT
					RETURN -1
				END 
			END
		END
	END
	ELSE
	BEGIN
		DECLARE @countitem1 INT
		SET @countitem1=(
		SELECT COUNT(ptypeid) FROM dbo.RetailBackBill psb
		INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
		WHERE p.customitemid IS NOT NULL
		AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.RetailBackBill))
		IF(@countitem1<>0)
		BEGIN
			DECLARE @num1 INT=0
			DECLARE @itemidtemp1 INT=0
			WHILE @num1<@countitem1
			BEGIN 
				SET @itemidtemp1=(SELECT T1.ItemID FROM(SELECT ROW_NUMBER() OVER (ORDER BY t.ptypeid) AS rowNum,T.ptypeid,T.ItemID FROM(SELECT ItemID,ptypeid FROM dbo.RetailBackBill WHERE ptypeid IN(
								SELECT ptypeid FROM dbo.RetailBackBill psb
								INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
								WHERE p.customitemid IS NOT NULL
								AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.RetailBackBill))  AND BillNumberId=(SELECT MAX(BillnumberID) FROM dbo.RetailBackBill)) T) AS T1 WHERE T1.rowNum=@num1+1)
				SET @num1=@num1+1
				IF(@itemidtemp1=0)
				BEGIN
					ROLLBACK TRAN AUDIT
					RETURN -1
				END 
			END
		END
	END
	
	--自动过账
	EXEC @Ret= dbo.Gp_Auditing  @nBillID = @Newbillnumberid, -- numeric
								@szCheckMan = @etypeid, -- varchar(50)
								@szPID = '', -- varchar(1000)
								@chvOpID = @etypeid, -- varchar(50)
								@KTypeID = '', -- varchar(50)
								@billtype = @billtype, -- int
								@voucherMsg = '', -- varchar(50)
								@vipcentinfo='',
								@AssetMsg=''
	
	
	

	if @Ret=0  OR @ret>=-227 AND @Ret<=-210 
	BEGIN
		COMMIT TRAN audit
		update PosRetailRecord SET AuditingFlag=1 WHERE RetailBillNumberId=@Newbillnumberid
		SELECT @resultBillnumberid = CAST(@Newbillnumberid AS VARCHAR)+','+@resultBillnumberid
	END
	ELSE
	BEGIN
		ROLLBACK TRAN AUDIT
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
		VALUES(@Newbillnumberid,'过账失败',@Ret)
	END
	ERROR1:
	
	
	FETCH NEXT FROM AuditingCursor
	INTO @Newbillnumberid
END
CLOSE AuditingCursor
DEALLOCATE AuditingCursor

DROP TABLE #daftBillNumerid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_AutoCombneRetail_SaveBillCode_Seed]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_AutoCombneRetail_SaveBillCode_Seed]
GO





/*

功能说明：       保存单据编号的种子数


创建日期：       2013-9-04


*/

CREATE PROCEDURE [GP_AutoCombneRetail_SaveBillCode_Seed]
(	
	@dBillDate					datetime,			--制单日期
	@intBillType				int,				--单据类型
    @strBillCode				varchar(200),		--单据编号
	@ETypeID	VARCHAR(100),
	@KTypeID	VARCHAR(100),
	@DTypeID	VARCHAR(100),
	@STypeID	VARCHAR(100),
	@CEFullName VARCHAR(100)	--制单人，因表扩展数据，这里需要同步添加，不然判断会出错
)
--@encode$--
AS

--根据单据编号得到种子数

IF ( CHARINDEX('-', @strBillCode) = 0 )
BEGIN
	RETURN
END

/**
 * 任泉熹 2018年3月12日 16:10:16
 * bug：5108
 * 因种子表BillCode_Seed扩展了一个属性，制单人编号，查询的时候做了过滤判断
 * 而插入值和更新值的时候，却没有进行判断，因此会导致编号相同无法自动过账
 * 这里统一增加传入参数@CEFullName，来获取具体制单人编号，并插入种子表中
 */
DECLARE @CETypeId VARCHAR(100)
DECLARE @szCEUsercode VARCHAR(100)=''
IF EXISTS(SELECT * FROM dbo.employee WHERE FullName=@CEFullName )
SELECT @szCEUsercode=UserCode FROM dbo.employee WHERE FullName=@CEFullName

IF @szCEUserCode=''
	BEGIN
		SELECT @CETypeId=''
	END
ELSE
	BEGIN
		SELECT @CETypeId=TypeID
		FROM dbo.employee
		WHERE UserCode=@szCEUserCode
	END




DECLARE @strSeed VARCHAR(200)

SELECT @strSeed = RTRIM(LTRIM(REVERSE(SUBSTRING(REVERSE(@strBillCode), 1 , CHARINDEX('-', REVERSE(@strBillCode))-1))))

IF ISNUMERIC(@strSeed) = 0
BEGIN
	RETURN
END


DECLARE @intSeed NUMERIC(18,0)


SELECT @intSeed = CAST(@strSeed AS NUMERIC(18,0))	


--取得数据库当前种子数
DECLARE	@intFlowMode	INT		--流水依据，1表示按日2表示按月3表示按年

DECLARE @BillCodeConfig varchar(1),@FlowLen INT
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置

SELECT @FlowLen=CAST(Value AS INT)+3 FROM UserConfig WHERE ConfigName='FlowLen'

DECLARE
	@MONTH 						VARCHAR(500), 		--自动产生编号时为月份，自定义编号时是经手人名字
	@DAY 						VARCHAR(500)		--自动产生编号时为日期，自定义编号时为仓库名

IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@intBillType ) AND @BillCodeConfig='1'
 --单据采用自定义编号 #02
BEGIN
	DECLARE @Code1 varchar(100),@Code2 varchar(100),@Code3 varchar(100),@Code4 varchar(100),@Code5 varchar(100),
			@Code6 varchar(100),@Code7 varchar(100),@Code8 varchar(100),@Code9 varchar(100),@Code10 varchar(100),
			@Code11 varchar(100),@Code12 varchar(100)

	IF @ETypeID IS NULL SET @ETypeID=''
	IF @KTypeID IS NULL SET @KTypeID=''
	IF @DTypeID IS NULL SET @DTypeID=''
	IF @STypeID IS NULL SET @STypeID=''
	IF @CETypeId IS NULL SET @CETypeId=''

	DECLARE
		@intFlowType				INT,		--1，按日，2按月，3按年
		@TempCode					VARCHAR(1000),
		@strFlowDate				VARCHAR(100)


	SELECT 	@Code1=code1,@Code2=code2,@Code3=code3,@Code4=code4,@Code5=code5,@Code6=code6,@Code7=code7,@Code8=code8,
			@Code9=code9,@Code10=code10,@Code11=code11,@Code12=code12  FROM CodeConfig WHERE BillType = @intBillType


	SET @TempCode = @Code1 +'*'+ @Code2 +'*'+ @Code3 +'*'+ @Code4 +'*'+ @Code5 +'*'+ @Code6 +'*'+ @Code7 +'*'+ @Code8 +'*'+ @Code9 +'*'+ @Code10 +'*'+ @Code11 +'*'+ @Code12	

	
	IF @Code1<>'仓库编号' AND @Code2<>'仓库编号' AND @Code3<>'仓库编号' AND @Code4<>'仓库编号' AND @Code5<>'仓库编号' AND @Code6<>'仓库编号' AND @Code7<>'仓库编号' AND @Code8<>'仓库编号' AND @Code9<>'仓库编号' AND @Code10<>'仓库编号' AND @Code11<>'仓库编号' AND @Code12<>'仓库编号'
	BEGIN
		SET @KTypeID=''
	END

	IF @Code1<>'经手人编号' AND @Code2<>'经手人编号' AND @Code3<>'经手人编号' AND @Code4<>'经手人编号' AND @Code5<>'经手人编号' AND @Code6<>'经手人编号' AND @Code7<>'经手人编号' AND @Code8<>'经手人编号' AND @Code9<>'经手人编号' AND @Code10<>'经手人编号' AND @Code11<>'经手人编号' AND @Code12<>'经手人编号'
	BEGIN
		SET @ETypeID=''
	END
	
	IF @Code1<>'部门编号' AND @Code2<>'部门编号' AND @Code3<>'部门编号' AND @Code4<>'部门编号' AND @Code5<>'部门编号' AND @Code6<>'部门编号' AND @Code7<>'部门编号' AND @Code8<>'部门编号' AND @Code9<>'部门编号' AND @Code10<>'部门编号' AND @Code11<>'部门编号' AND @Code12<>'部门编号'
	BEGIN
		SET @DTypeID=''
	END
	
	IF @Code1<>'制单人编号' AND @Code2<>'制单人编号' AND @Code3<>'制单人编号' AND @Code4<>'制单人编号' AND @Code5<>'制单人编号' AND @Code6<>'制单人编号' AND @Code7<>'制单人编号' AND @Code8<>'制单人编号' AND @Code9<>'部门编号' AND @Code10<>'制单人编号' AND @Code11<>'制单人编号' AND @Code12<>'制单人编号'
	BEGIN
		SET @CETypeId=''
	END

	/*
	IF @Code1<>'分支机构编号' AND @Code2<>'分支机构编号' AND @Code3<>'分支机构编号' AND @Code4<>'分支机构编号' AND @Code5<>'分支机构编号' AND @Code6<>'分支机构编号' AND @Code7<>'分支机构编号' AND @Code8<>'分支机构编号' AND @Code9<>'分支机构编号' AND @Code10<>'分支机构编号' AND @Code11<>'分支机构编号' AND @Code12<>'分支机构编号'
	BEGIN
		SET @STypeID=''
	END
	*/
END
ELSE
BEGIN
	SELECT 
			@ETypeID='',
			@KTypeID='',
			@DTypeID=''
	IF @STypeID IS NULL SET @STypeID=''
	
END

SELECT  @intFlowType=CodeFlowset FROM CodeConfig WHERE Billtype=@intBillType

IF @intFlowType IS NULL
BEGIN
	SELECT @intFlowType=Value
	FROM UserConfig
	WHERE ConfigName='FlowSet'
END

	
IF @intFlowType=0
BEGIN
	--按日
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@dBillDate) AS VARCHAR(2)),'0')+DBO.FN_FixStr(2,CAST(DAY(@dBillDate) AS VARCHAR(2)),'0')
END
ELSE IF @intFlowType=1
BEGIN
	--按月
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@dBillDate) AS VARCHAR(2)),'0')
END
ELSE IF @intFlowType=2
BEGIN
	--按年
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')
END

DECLARE @intDBSeed NUMERIC(18,0)

SELECT @intDBSeed = -1

SELECT @intDBSeed = ISNULL(MAX(Seed), -1) FROM BillCode_Seed 
WHERE BillType = @intBillType AND FlowDate=@strFlowDate AND ETypeID=@ETypeID AND KTypeID=@KTypeID AND DTypeID=@DTypeId AND STypeID=@STypeID AND CETypeId=@CETypeId


IF (@intDBSeed = -1)
BEGIN
	INSERT INTO BillCode_Seed(BillType,FlowDate, STypeID,ETypeID,KTypeID,DTypeID,CETypeId,Seed)
		VALUES(@intBillType, @strFlowDate,@STypeID,@ETypeID,@KTypeID,@DTypeId,@CETypeId, @intSeed)
END
ELSE
BEGIN
	IF (@intSeed > @intDBSeed)
	BEGIN
		UPDATE BillCode_Seed SET Seed = @intSeed WHERE BillType = @intBillType AND FlowDate=@strFlowDate AND ETypeID=@ETypeID AND KTypeID=@KTypeID AND DTypeID=@DTypeID AND STypeID=@STypeID AND CETypeId=@CETypeId
	END
END



GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-23
	描述：请购生单自动比价
*/

CREATE PROCEDURE Gp_AutoComparePrice 
(
	@OperatorID		varchar(100)='',
	@billidlists			VARCHAR(max)	--单据ID集合
)
--@encode$--
AS
SET NOCOUNT ON

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,'00001')	

CREATE TABLE #ptypeid1(typeid VARCHAR(100),stypeid varchar(100),itemid int,iscombined int)
INSERT INTO #ptypeid1 (stypeid,typeid,itemid,iscombined) SELECT DISTINCT(I.stypeid),B.PtypeId,B.ItemID,B.IsCombined FROM RequestBill B ,RequestIndex I WHERE B.BillNumberId=I.BillNumberId AND B.ID IN ( SELECT * FROM DBO.f_split(@billidlists,','))



DECLARE @COUNT INT =0
SELECT @COUNT=COUNT(*) FROM #ptypeid1 P 
						 INNER JOIN 
						 (
							SELECT DISTINCT A.stypeid,A.ItemID,A.IsCombined,A.Ptypeid FROM  AskPriceBill A 
							INNER JOIN dbo.BillIndex b ON b.BillNumberId=a.BillNumberID
							INNER JOIN #GetManBTypeId bb ON bb.TypeId=B.btypeid
							GROUP BY A.ItemID,A.IsCombined,A.stypeid,A.Ptypeid
						 ) ASK ON P.stypeid=ASK.Stypeid AND P.typeid=ASK.PTypeID AND p.itemid=ASK.ItemID AND p.iscombined=ASK.IsCombined
                         --GROUP BY ASK.ItemID,ASK.IsCombined,ASK.stypeid,ASK.Ptypeid


IF @COUNT<>(SELECT COUNT(*) FROM #ptypeid1)
BEGIN
	RAISERROR('有选中的商品没有询价，无法自动比价！',16,1)
	RETURN
END

DECLARE @COUNT1 INT =0
SELECT @COUNT1=COUNT(*) FROM #ptypeid1 P 
						 INNER JOIN 
						 (
							SELECT DISTINCT A.stypeid,A.ItemID,A.IsCombined,A.Ptypeid FROM  AskPriceBill A 
							INNER JOIN dbo.BillIndex b ON b.BillNumberId=a.BillNumberID
							INNER JOIN #GetManBTypeId bb ON bb.TypeId=B.btypeid
							WHERE	 (a.BillNumberID  IN (SELECT BillNumberID FROM dbo.AuditingBill A
						  INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						  WHERE													
							 F.IfUse = 1
							AND F.billtype = 185
							AND A.BillIndexType =2 
					        AND ifaudit=1 )or IfAudit='' )
							GROUP BY A.ItemID,A.IsCombined,A.stypeid,A.Ptypeid
						 ) ASK ON P.stypeid=ASK.Stypeid AND P.typeid=ASK.PTypeID AND p.itemid=ASK.ItemID AND p.iscombined=ASK.IsCombined
                         --GROUP BY ASK.ItemID,ASK.IsCombined,ASK.stypeid,ASK.Ptypeid


IF @COUNT1<>(SELECT COUNT(*) FROM #ptypeid1)
BEGIN
	RAISERROR('由于有询价单未通过审核 无法自动比价！',16,1)
	RETURN
END

	
CREATE TABLE #ptypeid
(
	typeid VARCHAR(100),
	stypeid VARCHAR(100),
	itemid int,
	iscombined int,
	discountPrice  NUMERIC(24, 10)  Default(0) NOT NULL ,
	discount  NUMERIC(24, 10)  DEFAULT (1) NULL,
	Tax  NUMERIC(24, 10)  Default(0) NOT NULL,
	btypeid VARCHAR(100)
)

INSERT INTO #ptypeid 
(
	typeid,
	stypeid,
	discountPrice,
	Tax,
	discount,
	btypeid,
	itemid,
	iscombined
) 
SELECT 
   
	a.ptypeid,
	a.Stypeid,
	a.DiscountPrice,
	a.Tax,
	a.Discount,
	b.btypeid,
	a.ItemID,
	a.IsCombined
FROM dbo.AskPriceBill a
INNER JOIN #ptypeid1 P ON P.stypeid=A.Stypeid AND P.typeid=A.PTypeID  
INNER JOIN dbo.BillIndex b ON b.BillNumberId=a.BillNumberID
INNER JOIN
(
	SELECT	a.ptypeid,
			A.Stypeid,
			b.btypeid,
			a.ItemID,
			a.IsCombined,
			MIN(a.DiscountPrice) AS discountprice
	FROM	dbo.AskPriceBill a 
	INNER JOIN dbo.BillIndex b ON b.BillNumberId=a.BillNumberID
	INNER JOIN #GetManBTypeId bb ON bb.TypeId=B.btypeid
	WHERE	A.Price>0 AND  (a.BillNumberID  IN (SELECT BillNumberID FROM dbo.AuditingBill A
						  INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						  WHERE													
							 F.IfUse = 1
							AND F.billtype = 185
							AND A.BillIndexType =2 
					        AND ifaudit=1 )or IfAudit='' ) --只找审核通过与不需要审核中最小的。
	GROUP BY a.PTypeID,A.Stypeid,b.btypeid,a.ItemID,a.IsCombined
) c
ON a.PTypeID=c.ptypeid AND A.Stypeid=C.Stypeid AND a.DiscountPrice=c.discountprice AND B.btypeid=C.btypeid AND a.ItemID=c.ItemID AND a.IsCombined=c.IsCombined
group by a.ptypeid,a.Stypeid,a.Tax,a.Discount,b.btypeid,a.ItemID,a.IsCombined,a.DiscountPrice
order by a.DiscountPrice desc
DECLARE @discountprice		 NUMERIC(24, 10) =0,
		@tax		 NUMERIC(24, 10) =0,
		@discount	 NUMERIC(24, 10) =0,
		@btypeid	VARCHAR(max),
		@stypeid	VARCHAR(max),
		@typeid		VARCHAR(max),
		@itemid       int,
	    @iscombined       int
BEGIN TRANSACTION  DEL

DECLARE IndexCursor CURSOR FOR
	SELECT stypeid,TypeId,itemid,iscombined  FROM #ptypeid
OPEN IndexCursor
FETCH NEXT FROM IndexCursor INTO @stypeid,@TypeId,@itemid,@iscombined
WHILE @@FETCH_STATUS = 0
	BEGIN
	
		SELECT	@discountprice=discountprice,
				@tax=tax,
				@discount=discount,
				@btypeid=btypeid
		FROM	#ptypeid P 
		WHERE	P.typeid=@TypeId
				AND P.stypeid=@stypeid
				AND p.itemid=@itemid 
				AND p.iscombined=@iscombined
		
		UPDATE	dbo.RequestBill
		SET		ComparePrice=@discountprice,
				comparetax=@tax,
				comparediscount=@discount,
				btypeid2=@btypeid,
				state=7
		WHERE	PtypeId=@typeid
				AND	stypeid=@stypeid
				AND ID IN (SELECT * FROM DBO.f_split(@billidlists,','))
				AND itemid=@itemid 
				AND iscombined=@iscombined
		FETCH NEXT FROM IndexCursor INTO @stypeid,@TypeId,@itemid,@iscombined
	END
	
CLOSE IndexCursor
DEALLOCATE IndexCursor
	
IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('比价失败！',16,1)
END

COMMIT TRANSACTION  DEL

DROP TABLE #ptypeid,#ptypeid1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-03-31
	描述：自动生成会计凭证
	EXEC Gp_AutoCreate_Voucher 1,'00001',0,''
*/
CREATE PROCEDURE Gp_AutoCreate_Voucher
(
	@BillNumberId	NUMERIC(18,0),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@AtId			INT = 0,				-- 凭证模版ID	
	@specifyDate	DATE = '',				-- 手工指定凭证日期
	@szPID			VARCHAR(1000) OUTPUT,	-- 返回出错信息
	@BillType		INT = 0					-- 单据类型
)
--@encode$--
AS
SET NOCOUNT ON

--如果启用了结转成本配置，那么只有成本凭证的
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1) AND @BillType IN (139,140,142,402,403)
BEGIN
	SET @szPID = '请通过成本结转功能生成凭证！'
	RETURN 0;
END

DECLARE @InOutStypeId VARCHAR(50),--调出分支机构
		@IfCommission INT --是否提成单

IF @BillType = 311
	SET @IfCommission = 1
ELSE IF @BillType IN (404,405)
	SET @IfCommission = 2
ELSE IF(@BillType IN(423,424,426,428,429))--优惠券
	SET @IfCommission = 3
ELSE IF(@BillType IN(327,328,329))--门店配送单
	SET @IfCommission = 4
ELSE
	SET @IfCommission = 0

IF @BillType IN(327,328,329)
BEGIN
	SELECT @InOutStypeId=StypeId FROM PosAllotApplyBillIndex where BillNumberId=@BillNumberId
END
ELSE
BEGIN
	SELECT @InOutStypeId = Stypeid FROM dbo.BillIndex WHERE BillNumberId = @BillNumberId
END

IF NOT EXISTS(SELECT 1 FROM Ac_Auditing_Template WHERE AtId=@AtId)
BEGIN
	SET @AtId=0
	UPDATE dbo.BillIndex SET ATID=0 WHERE BillNumberId=@BillNumberId
END

DECLARE @Return INT
SET @Return = 0
EXEC @Return = dbo.GP_Call_Voucher_Generate @BillNumberId,@szCheckMan,@AtId,@specifyDate,0,0,@InOutStypeId,@IfCommission

IF @Return <> 0 
	RETURN @Return

IF @BillType  IN (11,45,160,305,139,140,142,141,34,6,161,126,144,146,145,21,187,188,201,202,9,14,16,116,115,128,129,4,189,66,190,148,
					150,149,151,36,84,85,78,158,77,93,5,10,57,205,181,183,166,167,168,170,172,159,173,174,212,213,214,215,147,310,311,312,400,401,402,403,
					404,405,414,12,46,450,423,424,426,427,428,429,327,328,329)
SET @szPID = '生成凭证成功！'
ELSE 
	SET @szPID = ''
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.06.27
	描述：生成凭证时，合并相同的凭证明细
*/
CREATE PROCEDURE GP_CreateVoucher_MergeDetails
(
	@voucherBillId	INT--原始凭证id
)
--@encode$--
AS
SET NOCOUNT ON


--Tips：合并信息相同的明细，采用合并插入后再删除原来的凭证--
DECLARE @newVoucherId INT --临时BillNumberId
SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

SELECT	billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FCreditTotal,
		FDebitTotalFor,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		IDENTITY(INT,1,1) AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill
FROM
(
SELECT  @newVoucherId AS billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		SUM(FDebitTotal) AS FDebitTotal,
		SUM(FCreditTotal) AS FCreditTotal,
		SUM(FDebitTotalFor) AS FDebitTotalFor,
		SUM(FCreditTotalFor) AS FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod,
		MIN(rowno) AS initRowno
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @voucherBillId
GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod
)TT
ORDER BY initRowno



--用于记录明细ID，插入辅助核算使用
CREATE TABLE #tmpId
(
	id INT,
	ascids VARCHAR(500)
)

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.AscIds INTO #tmpId
SELECT  billnumberid,
		Summary ,
		STypeId ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FDebitTotalFor,
		FCreditTotal,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		FYear ,
		FPeriod,
		Comment ,
		Cid ,
		rowno,
		Rate ,
		FAdc
FROM #tmpNewVoucherBill


--辅助核算
INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
			( BillNumberId ,
			  vBId ,
			  typeName ,
			  TypeId
			)
SELECT DISTINCT	@newVoucherId,
		c.id,
		typeName,
		TypeId  
FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
INNER  JOIN dbo.Ac_Voucher_Bill b ON a.vBId = b.ID
INNER JOIN #tmpId c ON b.AscIds = c.ascids
WHERE a.BillNumberId = @voucherbillid


--更新表头分录数
UPDATE dbo.Ac_Voucher SET FEntryCount = (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherbillid)

--删除旧分录数据
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherbillid
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @voucherbillid

--替换临时BillNumberId为真实的
UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @voucherbillid WHERE BillNumberId = @newVoucherId
UPDATE dbo.Ac_Voucher_Bill_Assist_CheckItems SET BillNumberId = @voucherbillid WHERE BillNumberId = @newVoucherId
--------合并完成---------

----修正明细摘要----
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN	
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherBillId
	RETURN -225
END

DECLARE @NoSummaryRow INT
SELECT  @NoSummaryRow = RowNo FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND ISNULL(Summary,'') = '' ORDER BY RowNo DESC
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='acsummary' AND SubValue = 1)--配置要求每行分录必有摘要时，检查明细是否符合
	AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND ISNULL(Summary,'') = '')
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherBillId
	RETURN -224
END

DROP TABLE #tmpNewVoucherBill,#tmpId

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	自动生成单据摘要
*/
CREATE    PROCEDURE GP_AutoCreateBillComment (
	@intBillNumberID		numeric(10,0)			-- 老单据 ID
)
--@encode$--
AS

DECLARE	@intBillType			numeric(10,0),	-- 复制成的新单据类型值
		@chvOldComment			varchar(500),
		@chvComment				varchar(500),
		@chvPTypeFullName		varchar(50),
		@chvBTypeFullName		varchar(50),
		@chvETypeFullName		varchar(50),
		@chvKTypeFullName		varchar(50),
		@chvKTypeFullName2		varchar(50),
		@chvATypeFullName		varchar(50)

SELECT	@intBillType = a.BillType,
		@chvOldComment = ISNULL(a.Comment,''),
		@chvBTypeFullName = (SELECT FullName FROM BType WHERE TypeID = a.BTypeID),
		@chvETypeFullName = (SELECT FullName FROM Employee WHERE TypeID = a.ETypeID),
		@chvKTypeFullName = (SELECT FullName FROM Stock WHERE TypeID = a.KTypeID),
		@chvKTypeFullName2 = (SELECT FullName FROM Stock WHERE TypeID = a.KTypeID2),
		@chvATypeFullName = (SELECT FullName FROM AType WHERE TypeID = a.ATypeID)
FROM	BillIndex a
WHERE	a.BillNumberID = @intBillNumberID

IF @chvOldComment = ''
BEGIN
	IF @intBillType = 34	-- 采购入库单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	BuyBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '从【' + @chvBTypeFullName + '】购进【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 6	-- 采购退货单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	BuyBackBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '采购退货【' + @chvPTypeFullName + '】等给【' + @chvBTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 144	-- 受托代销收货单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	CommissionBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '受托【' + @chvPTypeFullName + '】等从【' + @chvBTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 146	-- 受托代销退货单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	CommissionBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '受托退货【' + @chvPTypeFullName + '】等给【' + @chvBTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 147	-- 受托代销调价单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	CommissionBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '受托调价【' + @chvPTypeFullName + '】等【' + @chvBTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 145	-- 受托代销结算单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	CommissionBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '【' + @chvBTypeFullName + '】受托结算【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 11	-- 销售出库单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	SaleBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '销售【' + @chvPTypeFullName + '】等给【' + @chvBTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 45	-- 销售退货单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	SaleBackBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '【' + @chvBTypeFullName + '】销售退货【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 140	-- 委托代销发货单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	CommissionBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '委托【' + @chvPTypeFullName + '】等给【' + @chvBTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 142	-- 委托代销退货单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	CommissionBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '委托退货【' + @chvPTypeFullName + '】等【' + @chvBTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 143	-- 委托代销调价单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	CommissionBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '委托调价【' + @chvPTypeFullName + '】等【' + @chvBTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 141	-- 委托代销结算单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	CommissionBill a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]
	
		SET @chvComment = '【' + @chvBTypeFullName + '】委托结算【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 165	-- 新维修 - 维修接件单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	wx_Bill_JieJian a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]

		SET @chvComment = '从【' + @chvBTypeFullName + '】维修接件【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 166	-- 新维修 - 维修单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	BillIndex a
		WHERE	a.BillNumberID = @intBillNumberID

		SET @chvComment = '对【' + @chvBTypeFullName + '】的【' + @chvPTypeFullName + '】维修：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 167	-- 新维修 - 维修取件单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	wx_Bill_GetBack a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]

		SET @chvComment = '【' + @chvBTypeFullName + '】维修取件【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 168	-- 新维修 - 整机更换单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	wx_Bill_Replace a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]

		SET @chvComment = '【' + @chvBTypeFullName + '】整机更换了【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 169	-- 新维修 - 送修单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	wx_Bill_Send a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]

		SET @chvComment = '【' + @chvBTypeFullName + '】送修【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 170	-- 新维修 - 送修返回单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	wx_Bill_SendBack a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]

		SET @chvComment = '【' + @chvBTypeFullName + '】送修返回【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 171	-- 新维修 - 报修单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	wx_Bill_Call a
		WHERE	a.BillNumberID = @intBillNumberID
		ORDER BY [ID]

		SET @chvComment = '【' + @chvBTypeFullName + '】报修【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
	END
	ELSE IF @intBillType = 172	-- 新维修 - 上门维修单
	BEGIN
		SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
		FROM	BillIndex a
		WHERE	a.BillNumberID = @intBillNumberID

		SET @chvComment = '【' + @chvBTypeFullName + '】上门维修【' + @chvPTypeFullName + '】：' + @chvETypeFullName
	END
	ELSE
		BEGIN
			SET @chvComment = ''
		END

	UPDATE	BillIndex
	SET		Comment = @chvComment
	WHERE	BillNumberID = @intBillNumberID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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







/*
	自动生成单据摘要
*/
CREATE   PROCEDURE GP_AutoCreateBillCommentForLend (
	@intBillNumberID		numeric(10,0)			-- 老单据 ID
)
--@encode$--
AS

DECLARE	@intBillType			numeric(10,0),	-- 复制成的新单据类型值
		@chvOldComment			varchar(500),
		@chvComment				varchar(500),
		@chvPTypeFullName		varchar(50),
		@chvBTypeFullName		varchar(50),
		@chvETypeFullName		varchar(50),
		@chvKTypeFullName		varchar(50),
		@chvKTypeFullName2		varchar(50),
		@chvATypeFullName		varchar(50)

SELECT	@intBillType = a.BillType,
		@chvOldComment = ISNULL(a.Comment,''),
		@chvBTypeFullName = (SELECT FullName FROM BType WHERE TypeID = a.BTypeID),
		@chvETypeFullName = (SELECT FullName FROM Employee WHERE TypeID = a.ETypeID),
		@chvKTypeFullName = (SELECT FullName FROM Stock WHERE TypeID = a.KTypeID),
		@chvKTypeFullName2 = (SELECT FullName FROM Stock WHERE TypeID = a.KTypeID2),
		@chvATypeFullName = (SELECT FullName FROM AType WHERE TypeID = a.ATypeID)
FROM	LendIndex a
WHERE	a.BillNumberID = @intBillNumberID

IF @chvOldComment = ''
BEGIN
	IF @intBillType = 87	-- 借出开单
		BEGIN
			SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
			FROM	LendBill a
			WHERE	a.BillNumberID = @intBillNumberID
			ORDER BY [ID]
		
			SET @chvComment = '【' + @chvBTypeFullName + '】借出【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
		END
	ELSE IF @intBillType = 71	-- 借进开单
		BEGIN
			SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
			FROM	LendBill a
			WHERE	a.BillNumberID = @intBillNumberID
			ORDER BY [ID]
		
			SET @chvComment = '从【' + @chvBTypeFullName + '】借进【' + @chvPTypeFullName + '】：' + @chvETypeFullName
		END
	ELSE IF @intBillType = 88	-- 借出还回
		BEGIN
			SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
			FROM	LendBill a
			WHERE	a.BillNumberID = @intBillNumberID
			ORDER BY [ID]
		
			SET @chvComment = '【' + @chvBTypeFullName + '】借出还回【' + @chvPTypeFullName + '】：' + @chvETypeFullName
		END
	ELSE IF @intBillType = 72	-- 借进还出
		BEGIN
			SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
			FROM	LendBill a
			WHERE	a.BillNumberID = @intBillNumberID
			ORDER BY [ID]
		
			SET @chvComment = '还回从【' + @chvBTypeFullName + '】借进的【' + @chvPTypeFullName + '】：' + @chvETypeFullName
		END
	ELSE
		BEGIN
			SET @chvComment = ''
		END

	UPDATE	LendIndex
	SET		Comment = @chvComment
	WHERE	BillNumberID = @intBillNumberID
END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	自动生成单据摘要
*/
CREATE   PROCEDURE GP_AutoCreateBillCommentForOrder (
	@intBillNumberID		numeric(10,0)			-- 老单据 ID
)
--@encode$--
AS

DECLARE	@intBillType			numeric(10,0),	-- 复制成的新单据类型值
		@chvOldComment			varchar(500),
		@chvComment				varchar(500),
		@chvPTypeFullName		varchar(50),
		@chvBTypeFullName		varchar(50),
		@chvETypeFullName		varchar(50),
		@chvKTypeFullName		varchar(50),
		@chvKTypeFullName2		varchar(50),
		@chvATypeFullName		varchar(50)

SELECT	@intBillType = a.BillType,
		@chvOldComment = ISNULL(a.Comment,''),
		@chvBTypeFullName = (SELECT FullName FROM BType WHERE TypeID = a.BTypeID),
		@chvETypeFullName = (SELECT FullName FROM Employee WHERE TypeID = a.ETypeID),
		@chvKTypeFullName = (SELECT FullName FROM Stock WHERE TypeID = a.KTypeID)
FROM	OrderIndex a
WHERE	a.BillNumberID = @intBillNumberID

IF @chvOldComment = ''
BEGIN
	IF @intBillType = 300	-- 销售订单
		BEGIN
			SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
			FROM	OrderBill a
			WHERE	a.BillNumberID = @intBillNumberID
			ORDER BY OrderId
		
			SET @chvComment = '销售订货【'+@chvPTypeFullName+'】等给【' + @chvBTypeFullName + '】等：' + @chvETypeFullName
		END
	ELSE IF @intBillType = 301	-- 采购订单
		BEGIN
			SELECT	TOP 1 @chvPTypeFullName = (SELECT FullName FROM PType WHERE TypeID = a.PTypeID)
			FROM	OrderBill a
			WHERE	a.BillNumberID = @intBillNumberID
			ORDER BY OrderId
		
			SET @chvComment = '从【' + @chvBTypeFullName + '】购进【' + @chvPTypeFullName + '】等：' + @chvETypeFullName
		END
	ELSE
		BEGIN
			SET @chvComment = ''
		END

	UPDATE	OrderIndex
	SET		Comment = @chvComment
	WHERE	BillNumberID = @intBillNumberID

	--清空Comment为NULL的值
	UPDATE	OrderIndex
	SET		Comment = ''
	WHERE	ISNULL(Comment,'')=''	
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
	描述：自动将pos小票 
	如果挂往来则生成销售/销售退货
-------------------------------------------*/
CREATE PROCEDURE [dbo].Gp_AutoCreateDealBtypeBill
(
    @resultBillnumberid		VARCHAR(8000)='' OUT	 --返回生成的单据billnumberid
)
--@encode$--
AS 
SET NOCOUNT ON


-- ********	判断是否试用版 - Start	********
    DECLARE @N INT ,
        @intVersion INT

-- 判断版本号，是否试用版
    SELECT  @N = CAST(SubValue AS INT)
    FROM    SysData1
    WHERE   SubNo = 2	-- 版本号

IF @N IS NULL RETURN -1

    DECLARE @intBit INT ,
        @intMask INT
    SELECT  @intBit = @N & 15
    SELECT  @intMask = POWER(2, @intBit) ^ POWER(2, @intBit + 1) ^ POWER(2,
                                                              @intBit + 2)
            ^ POWER(2, @intBit + 3) ^ POWER(2, @intBit + 4) ^ POWER(2,
                                                              @intBit + 5)
    SELECT  @intVersion = ( @intMask & @N ) / POWER(2, @intBit)
-- ********	判断是否试用版 - END	********
   
IF @resultBillnumberid IS NULL
SET @resultBillnumberid = ''

DELETE FROM dbo.PosSaleBillIndex WHERE EXISTS(SELECT TOP 1 1 FROM  PosRetailRecord WHERE PosBillNumberId = dbo.PosSaleBillIndex.BillnumberID)
DELETE FROM dbo.PosSaleBill WHERE EXISTS(SELECT TOP 1 1 FROM  PosRetailRecord WHERE PosBillNumberId = dbo.PosSaleBill.BillnumberID)
DELETE FROM dbo.PosMulAccount WHERE EXISTS(SELECT TOP 1 1 FROM  PosRetailRecord WHERE PosBillNumberId = dbo.PosMulAccount.BillnumberID)

SELECT MIN(B.BillnumberID) AS BillnumberID,B.[guid] 
INTO #T
FROM PosSaleBillIndex B 
WHERE B.[guid] IN(SELECT [guid] FROM PosSaleBillIndexAll group by [guid] having(COUNT(1))>1)
GROUP BY B.[guid]

SELECT * 
INTO #T1
FROM (
	SELECT B.BillnumberID
	FROM PosSaleBillIndex B 
	INNER JOIN #T t ON t.[guid] = B.[guid] AND t.BillnumberID <> B.BillnumberID
	UNION ALL 
	SELECT b.BillnumberID 
	FROM  PosSaleBillIndex b 
	INNER JOIN PosSaleBillIndexAll a ON a.[guid] = b.[guid]
	INNER JOIN PosRetailRecord r ON r.PosBillNumberId = a.BillNumberId
) A

DELETE FROM PosSaleBillIndex WHERE BillnumberID IN(SELECT BillnumberID FROM #T1)
DELETE FROM PosSaleBill WHERE BillnumberID IN(SELECT BillnumberID FROM #T1)
DELETE FROM PosMulAccount WHERE BillnumberID IN(SELECT BillnumberID FROM #T1)

DELETE FROM PosSaleBillIndexAll WHERE BillnumberID IN(SELECT BillnumberID FROM #T1) AND NOT EXISTS(SELECT TOP 1 1 FROM PosRetailRecord WHERE PosBillNumberId=PosSaleBillIndexAll.BillnumberID)
DELETE FROM PosSaleBillAll WHERE BillnumberID IN(SELECT BillnumberID FROM #T1) AND NOT EXISTS(SELECT TOP 1 1 FROM PosRetailRecord WHERE PosBillNumberId=PosSaleBillAll.BillnumberID)
DELETE FROM PosMulAccountAll WHERE BillnumberID IN(SELECT BillnumberID FROM #T1) AND NOT EXISTS(SELECT TOP 1 1 FROM PosRetailRecord WHERE PosBillNumberId=PosMulAccountAll.BillnumberID)

DROP TABLE #T,#T1

CREATE TABLE #PosSaleBill
	(
		BillnumberID int  NULL,
		ID int IDENTITY(1,1) NOT NULL,
		PID INT NULL,
		Qty  NUMERIC(24, 10)   NULL,
		BackQty  NUMERIC(24, 10)  NULL DEFAULT(0),
		RetailPrice  NUMERIC(24, 10)   NULL,
		Tax  NUMERIC(24, 10)  NULL DEFAULT(0),
		DisCount  NUMERIC(24, 10)   NULL DEFAULT(1),
		Price  NUMERIC(24, 10)   NULL,
		RetailTotal  NUMERIC(24, 10)   NULL,
		Total  NUMERIC(24, 10)   NULL,
		UnitID INT  NULL DEFAULT(0),
		UnitRate  NUMERIC(24, 10)  NULL Default(1),
		ItemID    bigint   NULL,
		IsCombined  int   NULL,
		BarCode	VARCHAR(200) NULL DEFAULT(''),
		IsGift INT NULL DEFAULT(0),
		Comment VARCHAR(MAX)NULL,
		posid INT,
		detailid INT,
		billId INT,
		PromoType INT NOT NULL DEFAULT(0) ,
		SaleEid INT NOT NULL DEFAULT(0),
		validdate VARCHAR(50)  NOT NULL DEFAULT(''),
		producedate VARCHAR(50)  NOT NULL DEFAULT(''),
		goodsnumber VARCHAR(100)  NOT NULL DEFAULT(''),
		serial TEXT NOT NULL DEFAULT(''),
		goodscostprice NUMERIC(24, 10)  NOT NULL Default(0),
		iscombination INT default(0),
		combinationptypeid	VARCHAR(200) NOT NULL DEFAULT(''),
		ptypeid		VARCHAR(200),
		pindexid	VARCHAR(300) NULL,
		ktypeid		VARCHAR(200) NULL,
		couponcode	VARCHAR(200) DEFAULT(''),
		pricesource VARCHAR(200) DEFAULT(''),
		PromoIds	VARCHAR(200) DEFAULT('')
	)
	create clustered index cix_id on #PosSaleBill(id,billId)

	CREATE TABLE #BillMulAccount(
		[BillNumberId] INTEGER NOT NULL,
		[posBillNumberId] INTEGER NOT NULL,
		[ATypeID] INT NULL,
		 total  NUMERIC(24, 10) ,
		 ntotal  NUMERIC(24, 10) ,
		[VipCardID] INT NULL DEFAULT(-1),
		[Comment] VARCHAR(500) NULL DEFAULT(''),
		[yhType]  INT NULL DEFAULT(-1),
		[CouponCode] VARCHAR(200) DEFAULT(''),
		VipTotal NUMERIC(24, 10)  DEFAULT(0)
	)
	
CREATE TABLE #daftBillNumerid(Billnumberid INT NULL)
	


DECLARE @Sid INT,@Bid INT,@Kid INT,@Eid INT,@VipCardID INT,@BillDate VARCHAR(50),@CargoID INT,@PromoRuleId INT,@BillDescription VARCHAR(2000),@CouponCodes VARCHAR(2000),@PromoIds VARCHAR(200)
DECLARE @stypeid VARCHAR(50),@btypeid VARCHAR(50),@etypeid VARCHAR(50),@ktypeid VARCHAR(50),@dtypeid VARCHAR(50),@dfullname VARCHAR(200)
DECLARE @billPage INT,@detailcount INT,@detalPage INT=1,@billcount INT,@billtype INT,@taxtotal  NUMERIC(24, 10) ,@qty  NUMERIC(24, 10) ,@premoney  NUMERIC(24, 10) ,@totalinmoney  NUMERIC(24, 10),@SaveInCzMoney NUMERIC(24,10)  
DECLARE  @i INT=0,@j INT=0
DECLARE @Bilnumberid INT,@billid INT=0,@tmp INT,@newbillnumberid INT
DECLARE @billcode VARCHAR(100),@Day varchar(100),@Month varchar(100),@Year varchar(100),@BillFlag VARCHAR(5),@cefullname VARCHAR(500)='' --单据编号相关
DECLARE @atypeid1 VARCHAR(50) --往来科目
DECLARE @dealbtypeid VARCHAR(50) --结算单位
DECLARE @createbilltype INT --生成单据billtype
DECLARE @tmpdetailminid INT,@tmpdetailmaxid INT,@posID INT,@tmpmaxbillnumberid INT,@tmpminbillnumberid INT,
		@MAXftotal  NUMERIC(24, 10) , --最后一张已分摊金额
		@MINftotal  NUMERIC(24, 10) , --第一张已分摊金额
		@aftotal INT,--是否分摊过
		@cBillnumberid  NUMERIC(24, 10) ,
		@rowcount  INT ,		--已经合并的明细条数
		@accountCount int=0,
		@billatypeid INT=0,
		@btypetotal NUMERIC(24,10),
		@errmsg NVARCHAR(4000)

DECLARE @arCount INT=0,@draft INT=0,@audit INT=0,@Posbillnumberid NUMERIC(10,0)

CREATE TABLE #tempbillid (id INT IDENTITY(1,1),detailid INT)

DECLARE Pos_cursor CURSOR FOR
SELECT  PosID,BillnumberID,KID,BID,EID,billdate,PromoRuleId,VipCardID,Billtype,1,BillDescription,CouponCode,PromoIds
FROM PosSaleBillIndex i
WHERE EXISTS(SELECT TOP 1 1 FROM dbo.PosMulAccount WHERE BillNumberId=i.BillnumberID AND ATypeID=-1)
	 AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.PosRetailRecord WHERE PosBillNumberId=i.BillnumberID)
GROUP BY PosID,BillnumberID,KID,BID,EID,billdate,PromoRuleId,VipCardID,Billtype,BillDescription,CouponCode,PromoIds
OPEN Pos_cursor

FETCH NEXT FROM Pos_cursor
INTO @posid,@Posbillnumberid,@Kid,@BId,@Eid,@BillDate,@PromoRuleId,@VipCardID,@billtype,@billcount,@BillDescription,@CouponCodes,@PromoIds

WHILE @@FETCH_STATUS = 0 
BEGIN
	-------------取表头信息 start-------
	SELECT  @ktypeid=typeid,@stypeid=STypeID FROM Stock WHERE Kid=@Kid
	SELECT  @CargoID=CargoID FROM dbo.CargoType WHERE KtypeID=@ktypeid AND IsDefault=1
	SELECT  @etypeid=typeid,@dtypeid=DtypeID FROM employee WHERE eid=@eid
	SELECT	@dfullname=fullname FROM dbo.Department WHERE typeid=@dtypeid
	--获取往来单位
	SELECT  @Btypeid= typeid FROM dbo.BType WHERE Bid=@Bid
	---获取结算单位
	SELECT @dealbtypeid =denominatedid FROM BType WHERE Bid=@BID
	-------------取表头信息 end---------
	SET @createbilltype=(CASE WHEN @billtype=305 THEN 11 ELSE 45 END)
	IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
	BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版最多录200条单据 ！',16,1)
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT BillNumberId,'试用版最多录200条单据','' 
			FROM PosSaleBillIndex  b
			WHERE   b.BillnumberID=@Posbillnumberid AND  b.KID=@Kid AND b.BID=@Bid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId
		GOTO Error		 		
	END
	END  
	
	------------表头验证 start-----------
	--仓库
	IF NOT EXISTS(SELECT TOP 1 1 FROM stock WHERE kid=@kid AND deleted=0) --停用或者不存在
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT BillNumberId,'该单仓库不存在或已被停用','' 
			FROM PosSaleBillIndex  b
			WHERE  b.BillnumberID=@Posbillnumberid AND b.KID=@Kid AND b.BID=@Bid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId	
		GOTO Error
	END
	--往来单位
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.btype WHERE bid=@Bid AND deleted=0) --停用或者不存在
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT BillNumberId,'该单往来单位不存在或已被停用','' 
			FROM PosSaleBillIndex b
			WHERE  b.BillnumberID=@Posbillnumberid AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate	
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId	
			
		GOTO Error
	END
	--经手人
	IF NOT EXISTS(SELECT TOP 1 1 FROM employee WHERE eid=@eid)-- AND deleted=0) --停用或者不存在
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT BillNumberId,'该单经手人不存在','' 
			FROM PosSaleBillIndex b
			WHERE   b.BillnumberID=@Posbillnumberid AND  b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate	
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId	
			
		GOTO Error
	END
	--账户
	IF EXISTS(SELECT TOP 1 1 FROM dbo.PosMulAccount pb INNER JOIN dbo.PosSaleBillIndex b ON b.BillnumberID=pb.BillnumberID  
	WHERE pb.ATypeID<>-1 AND  b.Billtype=@billtype AND  b.BillnumberID=@Posbillnumberid  	AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate AND NOT EXISTS(SELECT nId FROM dbo.Ac_Items WHERE deleted=0 AND nid=pb.ATypeID)) --停用或者不存在
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT DISTINCT b.BillNumberId,'该单存在收付款账户不存在或者被停用的情况','' 
			FROM PosMulAccount a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BillnumberID=@Posbillnumberid  
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND NOT EXISTS(SELECT nId FROM dbo.Ac_Items WHERE deleted=0 AND nid=a.ATypeID)				
	END
	IF EXISTS(SELECT TOP 1 1 FROM  PosSaleBillIndex b 
				INNER JOIN dbo.employee e ON b.EID=e.Eid
				WHERE  b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId AND  b.BillnumberID=@Posbillnumberid 		
				AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
				AND b.premoney>ISNULL(e.MaxPre,-999999999918.99) AND ISNULL(e.MaxPre,-999999999918.99)<>-999999999918.99
				)
	BEGIN			
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
		SELECT DISTINCT b.BillNumberId,'每单抹零金额超过限额','' 
				FROM PosSaleBillIndex b 
				INNER JOIN dbo.employee e ON b.EID=e.Eid
				WHERE   b.BillnumberID=@Posbillnumberid AND  b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
				AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
				AND b.premoney>ISNULL(e.MaxPre,-999999999918.99) AND ISNULL(e.MaxPre,-999999999918.99)<>-999999999918.99
		GOTO Error
	END			
	
    DECLARE @IsAcSystem Varchar(50)
    DECLARE @tempVerifyID VARCHAR(50) 
    DECLARE @temphascombination INT
    DECLARE @Isaloneusebsys VARCHAR(50) 
    
    select @tempVerifyID=VerifyID from stype where typeid=@stypeid
    SET @temphascombination=0
    
    SELECT TOP 1 @temphascombination = p.iscombinationproduct FROM PosSaleBill psb 
	INNER JOIN ptype p ON psb.pid=p.pid AND p.iscombinationproduct=1
	
	IF @billtype=305 AND @temphascombination=1 --组合品销售出库单
		SET @createbilltype='12'
	ELSE IF @billtype=307 AND @temphascombination=1 --组合品销售退货单
		SET @createbilltype='46'
	ELSE IF @billtype=307	--销售退货单
		SET @createbilltype='45'
		
	SELECT TOP 1 @atypeid1=AtypeId FROM BillAtype WHERE StypeId=@tempVerifyID AND BillTypeId= CAST(@createbilltype AS VARCHAR)
    SELECT @IsAcSystem=subvalue FROM dbo.sysdata WHERE SubName='IsUseAcSystem'
    --未启用《月结业务凭证不进行过账检查》配置的，才判断总账往来科目是否为空
    SELECT @Isaloneusebsys=subvalue FROM dbo.sysdata WHERE SubName='aloneusebsys'
    IF ISNULL(@atypeid1,0)=0 AND @IsAcSystem='1' AND @Isaloneusebsys='0'
    BEGIN 
		IF NOT EXISTS(SELECT TOP 1 1 from PosSaleMergeFailed WHERE PosBillNumberId=@Posbillnumberid AND Reason='总账版往来科目为空，不能结存')
		BEGIN 
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
		SELECT BillNumberId,'总账版往来科目为空，不能结存','' 
		FROM PosSaleBillIndex b
		WHERE  b.BillnumberID=@Posbillnumberid AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate	
		AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId	
		END
		GOTO ERROR --总账版往来科目为空不生单，继续循环
    END
	
	------------表头验证 end-------------
	
	------------表体验证 start ---------
	IF EXISTS(SELECT TOP 1 1 FROM PosSaleBill a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.BillnumberID=@posbillnumberid
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND NOT EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0))
	BEGIN
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
				SELECT DISTINCT b.BillNumberId,'该单存在商品不存在或者被停用的情况','' 
				FROM PosSaleBill a,
				PosSaleBillIndex b 
				WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
				AND b.BillnumberID=@posbillnumberid
				AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
				AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
				AND NOT EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0)
		GOTO Error
	END
	------------表体验证 end-------------
	
	IF EXISTS(SELECT TOP 1 1 FROM PosSaleBill a
		INNER JOIN PosSaleBillIndex b ON a.BillnumberID=b.BillnumberID
		INNER JOIN dbo.ptype p  ON p.pid = a.PID AND p.iscombinationproduct = 1
		WHERE  b.BillnumberID=@posbillnumberid
		AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
		AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
		AND NOT EXISTS(SELECT 1 FROM dbo.CombinationProductIndex c WHERE c.CombinationProductPtypeId = p.typeId AND c.IsCheck = 1 AND c.IsStop = 0)
		)
	BEGIN	
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
		SELECT DISTINCT b.BillNumberId,'该单存在组合商品被停用或没有有效明细商品的情况','' 
			FROM PosSaleBill a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.BillnumberID=@posbillnumberid
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND NOT EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0)
		GOTO Error	
	END
	
	
	------------表体验证 start ---------
	IF EXISTS(SELECT TOP 1 1 FROM PosSaleBill a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.BillnumberID=@posbillnumberid
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0)
			AND NOT EXISTS(SELECT 1 FROM ptype p INNER JOIN dbo.PType_Units_Ext u ON p.typeId=u.PtypeID WHERE pid=a.PID AND u.UnitsId=a.UnitID))
	BEGIN     
		INSERT INTO dbo.PosSaleMergeFailed( PosBillNumberId, Reason, Comment )
			SELECT DISTINCT b.BillNumberId,'该单存在商品单位不存在的情况','' 
			FROM PosSaleBill a,
			PosSaleBillIndex b 
			WHERE a.BillnumberID=b.BillnumberID --AND a.BillnumberID=1
			AND b.BillnumberID=@posbillnumberid
			AND b.Billtype=@billtype AND b.PromoRuleId=@PromoRuleId		
			AND b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate
			AND EXISTS(SELECT 1 FROM ptype WHERE pid=a.PID AND deleted=0)
			AND NOT EXISTS(SELECT 1 FROM ptype p INNER JOIN dbo.PType_Units_Ext u ON p.typeId=u.PtypeID WHERE pid=a.PID AND u.UnitsId=a.UnitID)
	GOTO Error
	END

	------------表体验证 end-------------
	
	
	-------------单据编号start----------
	SELECT @Year=YEAR(GETDATE())
	IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @createbilltype)  AND  EXISTS( SELECT 1 FROM UserConfig WHERE ConfigName='BillCodeConfig' AND Value='1') 
	BEGIN
		SELECT @MONTH = typeId FROM Employee WHERE Eid = @Eid
		SELECT @DAY = FullName FROM Stock WHERE Kid = @Kid
		SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @ETypeId
	END
	ELSE
	BEGIN
		SELECT @Month=Month(GETDATE())
		SELECT @Day=DAY(GETDATE())
	END
	--------------单据编号end------------
    DECLARE @VerifyID VARCHAR(50) 
    select @VerifyID=VerifyID from stype where typeid=@stypeid
	SELECT TOP 1 @atypeid1=AtypeId FROM BillAtype WHERE StypeId=@VerifyID AND BillTypeId= CAST(@createbilltype AS VARCHAR)
	
	IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName = 'isvirtualstock' AND Value=1)
		AND EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName = 'virtualstockmode' AND Value=2)
		AND EXISTS(SELECT 1 WHERE @billtype IN (SELECT * FROM dbo.f_split((SELECT Value FROM dbo.Userconfig WHERE ConfigName='virtualstockbilltype'),',')))
		AND EXISTS(select 1 WHERE '0' IN (SELECT * FROM dbo.f_split((SELECT Value FROM dbo.Userconfig WHERE ConfigName='draftposting'),',')))
			SET @draft=1

	--将表头合并后的明细插入到零时表，
	TRUNCATE TABLE #PosSaleBill	
	INSERT INTO #PosSaleBill 
	SELECT a.BillnumberID,p.PID,ABS(qty),BackQty,RetailPrice,tax,a.DisCount,Price,
		ABS(RetailTotal),
		ABS(total),UnitID,UnitRate,ItemID,IsCombined,BarCode,IsGift,a.comment,b.PosID,a.ID,DENSE_RANK() over(order by b.BillnumberID),a.PromoType,
		a.saleeid,a.validdate,a.producedate,a.goodsnumber,a.serial,a.goodscostprice,NULL,'',p.typeid,
		p.typeid+'_'+CAST(ROW_NUMBER() OVER(ORDER BY p.PID) AS VARCHAR) + '_'+RIGHT(100000000 + CONVERT(bigint, ABS(CHECKSUM(NEWID()))), 9),sk.typeid,a.couponcode,ISNULL(a.pricesource,''),a.PromoIds
	FROM  PosSaleBillIndex b 
	INNER JOIN PosSaleBill a ON a.BillnumberID=b.BillnumberID
	INNER JOIN ptype p  ON a.pid=p.pid 
	INNER JOIN stock sk ON b.kid=sk.kid 
	WHERE b.BillnumberID=@posbillnumberid 
	AND b.BID=@Bid AND b.KID=@Kid
	AND b.EID=@Eid AND b.VipCardID=@VipCardID 
	AND billdate=@BillDate AND b.PromoRuleId=@PromoRuleId 
	AND b.BillnumberID=@posbillnumberid
	AND NOT EXISTS (SELECT 1 FROM dbo.PosSaleBill a WHERE a.BillnumberID=b.BillnumberID AND (NOT EXISTS(SELECT 1 FROM  ptype  WHERE pid=a.PID AND deleted=0) OR NOT EXISTS(SELECT 1 FROM ptype p INNER JOIN dbo.PType_Units_Ext u ON p.typeId=u.PtypeID WHERE pid=a.PID AND u.UnitsId=a.UnitID)))
	
	
	
	
	
	/***********************************处理组合品Start*******************************/
	DECLARE @hascombination INT
	DECLARE @isauto INT
	SET @isauto=0
	SELECT @isauto=autogenerate FROM posinfo WHERE posid=@posid--是否自动带入批次批号
	SET @hascombination=0
	SELECT TOP 1 @hascombination = p.iscombinationproduct FROM PosSaleBill psb 
	INNER JOIN ptype p ON psb.pid=p.pid AND p.iscombinationproduct=1
	IF @hascombination=1
	BEGIN
		--处理上表体数据
		UPDATE #PosSaleBill SET iscombination = 1
		--插入下表体数据
		INSERT INTO #PosSaleBill
		SELECT BillnumberID,psb.PID,Qty,BackQty,RetailPrice,Tax,DisCount,Price,RetailTotal,
		Total,UnitID,UnitRate,ItemID,IsCombined,BarCode,IsGift,psb.Comment,posid,detailid,
		billId,PromoType,SaleEid,validdate,producedate,goodsnumber,
		serial,goodscostprice,0,combinationptypeid,ptypeid,pindexid,ktypeid,psb.couponcode,psb.pricesource,psb.PromoIds
		FROM #PosSaleBill psb INNER JOIN ptype p ON psb.pid=p.pid AND ISNULL(p.iscombinationproduct,0)=0
		
		IF (@isauto = 0)
			BEGIN
				--插入下表体组合品数据
				--获取组合品配件信息
				--金额比例计算：((cpd.Price * cpd.qty ) / cpi.price)
				INSERT INTO #PosSaleBill
				SELECT psb.BillnumberID,p.PID,CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) as qty,BackQty,
				(psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) AS RetailPrice,
				tax,discount,
				(psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) AS price,
				psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price) AS RetailTotal,
				psb.total * ((cpd.Price * cpd.qty ) / cpi.price) AS total,
				cpd.unit AS UnitID,u.rate AS UnitRate,cpd.ItemID,CASE WHEN ISNULL(p.customitemfrom,0)=1 THEN 1 ELSE 0 END AS IsCombined,p.entrycode as BarCode,psb.IsGift,'由组合品生成的配件商品',
				psb.PosID,psb.ID,DENSE_RANK() over(order by psb.BillnumberID),0 AS PromoType,
				psb.saleeid,psb.validdate as validdate,psb.producedate as producedate,psb.goodsnumber as goodsnumber,'' as serial,0 as goodscostprice,0,cpi.combinationproductptypeid,
				p.typeid,psb.pindexid, psb.ktypeid,psb.couponcode,psb.pricesource,psb.PromoIds
				FROM CombinationProductdetail cpd
				INNER JOIN CombinationProductIndex cpi ON cpd.combinationproductid=cpi.combinationproductid AND cpi.isstop=0 AND cpi.ischeck=1 
				INNER JOIN Ptype p ON cpd.ptypeid=p.typeid --AND p.deleted = 0 
				INNER JOIN #PosSaleBill psb ON cpi.combinationproductptypeid=psb.ptypeid AND ISNULL(psb.iscombination,0)=1 
				INNER JOIN PType_Units_Ext u ON u.UnitsId=cpd.Unit AND u.ptypeId = cpd.PtypeID 
			END
		ELSE 
			BEGIN
			--插入下表体组合品数据
				--获取组合品配件信息
				--金额比例计算：((cpd.Price * cpd.qty ) / cpi.price)
				INSERT INTO #PosSaleBill
				SELECT psb.BillnumberID,p.PID,CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) as qty,BackQty,
				(psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) AS RetailPrice,
				tax,discount,
				(psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) AS price,
				psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price) AS RetailTotal,
				psb.total * ((cpd.Price * cpd.qty ) / cpi.price) AS total,
				cpd.unit AS UnitID,u.rate AS UnitRate,
				ISNULL((select top 1 ItemID from GOODSSTOCKS_QTY gq 
                        inner join ptype p on p.typeid=gq.ptypeid
                        inner join stock s on s.typeid=gq.ktypeid
                        inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
                        where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
                        ),'') as ItemID,
				CASE WHEN ISNULL(p.customitemfrom,0)=1 THEN 1 ELSE 0 END AS IsCombined,p.entrycode as BarCode,psb.IsGift,'由组合品生成的配件商品',
				psb.PosID,psb.ID,DENSE_RANK() over(order by psb.BillnumberID),0 AS PromoType,
				psb.saleeid,
						ISNULL((select top 1 ValidDate from GOODSSTOCKS_QTY gq 
                        inner join ptype p on p.typeid=gq.ptypeid
                        inner join stock s on s.typeid=gq.ktypeid
                        inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
                        where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
                        ),'') as validdate,
                       ISNULL((select top 1 ProduceDate from GOODSSTOCKS_QTY gq 
                        inner join ptype p on p.typeid=gq.ptypeid
                        inner join stock s on s.typeid=gq.ktypeid
                        inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
                        where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid),'') as producedate,
                       ISNULL((select top 1 GoodsNumber from GOODSSTOCKS_QTY gq 
                        inner join ptype p on p.typeid=gq.ptypeid
                        inner join stock s on s.typeid=gq.ktypeid
                        inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
                        where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
                        ),'') as goodsnumber,
                        '' as serial,
                        0 as goodscostprice,
                        0,
                        cpi.combinationproductptypeid,
				p.typeid,psb.pindexid, psb.ktypeid,psb.couponcode,psb.pricesource,psb.PromoIds
				FROM CombinationProductdetail cpd
				INNER JOIN CombinationProductIndex cpi ON cpd.combinationproductid=cpi.combinationproductid AND cpi.isstop=0 AND cpi.ischeck=1 
				INNER JOIN Ptype p ON cpd.ptypeid=p.typeid --AND p.deleted = 0 
				INNER JOIN #PosSaleBill psb ON cpi.combinationproductptypeid=psb.ptypeid AND ISNULL(psb.iscombination,0)=1 
				INNER JOIN PType_Units_Ext u ON u.UnitsId=cpd.Unit AND u.ptypeId = cpd.PtypeID 
			END
		
		
		
		
		UPDATE #PosSaleBill SET RetailTotal=dbo.F_RoundTotal(RetailTotal),Total=dbo.F_RoundTotal(Total)
		--组合品差异
		DECLARE @Diff TABLE(
			PindexID VARCHAR(100),
			Diff	 NUMERIC(24,10),
			RowIndex INT
		)

		DECLARE @RCount INT=0,
				@RIndex INT=1,
				@PIndexID VARCHAR(100),
				@ID INT,
				@DiffTotal NUMERIC(24,10)
	
		INSERT INTO @Diff
		        ( PindexID, Diff,RowIndex )
        SELECT  A.PindexID ,
                dbo.F_RoundTotal(A.Total - B.Total),
                ROW_NUMBER() OVER(ORDER BY GETDATE())
        FROM    ( SELECT    SUM(Total) AS Total ,
                            PindexId
                  FROM      #PosSaleBill psb
                  WHERE     ISNULL(Iscombination,0) = 1
                  GROUP BY  PindexId
                ) A
                INNER JOIN ( SELECT SUM(Total) AS Total ,
                                    PindexId
                             FROM   #PosSaleBill
                             WHERE  ISNULL(Iscombination,0) = 0
                             GROUP BY PindexId
                           ) B ON A.PIndexID = B.PIndexID
		WHERE A.Total-B.Total<>0

		SELECT @RCount=COUNT(1) FROM @Diff
		WHILE(@RIndex<=@RCount)
		BEGIN
			 SELECT @PIndexID=PIndexID,@DiffTotal=Diff FROM @Diff WHERE RowIndex=@RIndex
			 SELECT TOP 1 @ID=ID FROM #PosSaleBill WHERE PIndexID=@PIndexID AND ISNULL(IScombination,0)=0
			 UPDATE #PosSaleBill SET  RetailTotal=dbo.F_RoundTotal(RetailTotal+@DiffTotal),Total=dbo.F_RoundTotal(Total+@DiffTotal) WHERE ID=@ID
			 UPDATE #PosSaleBill SET  RetailPrice=dbo.F_RoundPrice(RetailTotal/Qty),Price=dbo.F_RoundPrice(Total/Qty) WHERE ID=@ID
			 SET @RIndex=@RIndex+1
		END
	END
	/***********************************处理组合品end**********************************/


			
	TRUNCATE TABLE #BillMulAccount
	BEGIN TRAN SaveBill
	BEGIN TRY	
	
			
			DECLARE @startdate VARCHAR(50)
			SELECT @startdate= CONVERT(VARCHAR(10),startdate,120) FROM dbo.MonthProc WHERE MonthNo='本期'
			IF @billdate<@startdate
			BEGIN
				SET @billdate=@startdate
			END
				 
			SELECT @taxtotal=CAST(SUM(a.Total)AS  NUMERIC(24, 10) ),@qty=SUM(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))
			FROM #PosSaleBill a  
			INNER JOIN ptype p ON a.PID=p.Pid
			INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
			WHERE  ISNULL(a.iscombination,0)=0 

				
			SELECT @premoney = CAST(SUM(CASE @billtype WHEN 305 THEN b.premoney ELSE -b.premoney END) AS  NUMERIC(24, 10) ),
			       @totalinmoney= CAST(SUM(CASE @billtype WHEN 305 THEN b.Totalinmoney ELSE -b.Totalinmoney END) AS  NUMERIC(24, 10) ),
			       @SaveInCzMoney = CAST(SUM(CASE @billtype WHEN 305 THEN b.SaveInCzMoney ELSE -b.SaveInCzMoney END) AS  NUMERIC(24, 10) )
			FROM PosSaleBillIndex b
			WHERE BillnumberID  IN (
					SELECT a.BillnumberID
					FROM #PosSaleBill a  
					INNER JOIN ptype p ON a.PID=p.Pid
					INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
					WHERE ISNULL(a.iscombination,0)=0 
					)
					
			
			SELECT @accountCount=COUNT(1),@billatypeid=MAX(ATypeID)
					FROM
					 (
						SELECT DISTINCT(ATypeID)
						FROM dbo.PosMulAccount p INNER join  #PosSaleBill a  ON p.BillNumberId=a.billnumberid
					)b
					
			--SET @BillFlag=CASE @createbilltype WHEN 11 THEN 'XK' ELSE 'XT' END 
			--SET @BillCode=''					
			----单据编号
			--EXEC Gp_GetBillCode @createbilltype, @MONTH,@DAY,@BillFlag,@BillDate,@stypeid,@BillCode OUTPUT,@dfullname,@cefullname
				
			--				--保存种子数
			--IF NOT EXISTS(SELECT ConfigNo  FROM Userconfig  WHERE ConfigName='BillcodeCreateTime'AND Value=2)
			--BEGIN
			--	EXEC GP_AutoCombneRetail_SaveBillCode_Seed @billdate,@createbilltype,@billcode,@etypeid,@ktypeid,@dtypeid,@stypeid,@cefullname				
			--END

			-------------------具体合并 start----------------	
			
            --判断atypeid是否为-1
            IF @billatypeid = '-1' OR @billatypeid = -1
            SET @billatypeid=''
            DECLARE @tpAtypeId1 Varchar(50)
            
            --如果是组合品销售出库单
            IF @billtype=305 AND @hascombination=1
            BEGIN
				SET @createbilltype='12'
				SELECT TOP 1 @tpAtypeId1=AtypeId FROM BillAtype WHERE StypeId=@VerifyID AND BillTypeId='12'
				SET @atypeid1=@tpAtypeId1				
            END
            ELSE IF @billtype=307 AND @hascombination=1 --如果是组合品销售退货单
            BEGIN
				SET @createbilltype='46'
				SELECT TOP 1 @tpAtypeId1=AtypeId FROM BillAtype WHERE StypeId=@VerifyID AND BillTypeId='46'
				SET @atypeid1=@tpAtypeId1				
            END            
            ELSE IF @billtype=307  --如果是销售退货单
            BEGIN
				SET @createbilltype='45'
				SELECT TOP 1 @tpAtypeId1=AtypeId FROM BillAtype WHERE StypeId=@VerifyID AND BillTypeId='45'
				SET @atypeid1=@tpAtypeId1				
            END
            
            --如果是组合品销售出库单
-------------------放到这里来start--------------------            
            --SET @BillFlag=CASE @createbilltype WHEN 11 THEN 'XK' ELSE 'XT' END 
          
            SET @BillFlag=CASE @createbilltype WHEN 11 THEN 'XK' WHEN 12 THEN 'ZXK' WHEN 46 THEN 'ZXT' ELSE 'XT' END 
			SET @BillCode=''					
			--单据编号
			EXEC Gp_GetBillCode @createbilltype, @MONTH,@DAY,@BillFlag,@BillDate,@stypeid,@BillCode OUTPUT,@dfullname,@cefullname
				
							--保存种子数
			IF NOT EXISTS(SELECT ConfigNo  FROM Userconfig  WHERE ConfigName='BillcodeCreateTime'AND Value=2)
			BEGIN
				EXEC GP_AutoCombneRetail_SaveBillCode_Seed @billdate,@createbilltype,@billcode,@etypeid,@ktypeid,@dtypeid,@stypeid,@cefullname
			END
			-------------------放到这里来end-------------------- 
     --         IF  EXISTS(select 1 from BillIndex where BillDate=CONVERT(VARCHAR(10),@BillDate,120) and BillType=@createbilltype and atypeid=CASE WHEN @accountCount<=1 THEN ISNULL(@billatypeid,'') ELSE -99999 END and IfMulAccount=CASE WHEN @accountCount<=1 THEN 0 ELSE 1 END
					--			and btypeid=@btypeid and etypeid=@ETypeId and ktypeid=@ktypeid and ifcheck='f' and NewPosBill=1 and checke=@ETypeId 
					--			and totalmoney=@taxtotal and NTotalMoney=@taxtotal and totalinmoney=@totalinmoney
					--			and NTotalInMoney=@totalinmoney and totalqty=@qty and packway='' and tax=0
					--			and tax=0 and period=1 and RedWord=0 and draft=1 and Comment='该单是由POS小票自动生成' and VipCardID=@vipcardid and IfAudit=''
					--			and preferencemoney=@premoney and npreferencemoney=@premoney and DTypeId=@DTypeId 
					--			and Stypeid=@stypeid
					--			) 
					--BEGIN
					--	--继续循环
					--		GOTO Error
					--END
            
			
			INSERT INTO BillIndex 
			(waybillcode,ktypeid2,ptypeid,
			CheckTime,
			BillTime,
			AlertDay,
			BillDate,
			BillCode,
			BillType,
			atypeid,
			IfMulAccount,
			btypeid,
			etypeid,
			ktypeid,
			ifcheck,
			NewPosBill,
			checke,
			totalmoney,
			NTotalMoney,
			totalinmoney,
			NTotalInMoney,
			totalqty,
			packway,
			tax,
			period,
			RedWord,
			draft,
			Comment,
			VipCardID,
			TEL,
			IfAudit,
			preferencemoney,
			npreferencemoney,
			DTypeId,
			Explain,
			Stypeid,CID,Rate,ATypeID1,DealBTypeID,PromoRuleId,FeeDeductType,
				Assessor,Audit_explain,vipCZMoney,KTypeID3,OtherInOutType,TransportId,
				AssetBusinessTypeId,IscombinationStyle,
			posid
			)
			SELECT  '' AS waybillcode,'' AS ktypeid2,'' AS ptypeid,
			GETDATE(),
			CONVERT(VARCHAR(20), GETDATE(), 24),
			9999,
			CONVERT(VARCHAR(10),@BillDate,120),
			@BillCode,
			@createbilltype,
			CASE WHEN @accountCount<=1 THEN ISNULL(@billatypeid,'') ELSE -99999 END,
			CASE WHEN @accountCount<=1 THEN 0 ELSE 1 END,
			@dealbtypeid,
			@ETypeId,
			@ktypeid,
			'f',
			1,
			@ETypeId,
			@taxtotal,
			@taxtotal,
			@totalinmoney,
			@totalinmoney,
			@qty,
			'' AS packway,
			0,
			1,
			0,
			1,
			'该单是由POS小票自动生成',
			@vipcardid,
			'',
			'',
			@premoney,
			@premoney,
			@DTypeId,
			@BillDescription,
			@stypeid,
			1,1,@atypeid1,@btypeid,@promoruleid,0,
			'' AS Assessor,'' AS Audit_explain,0 AS vipCZMoney,'' AS ktypeid3,-1 AS OtherInOutType,
			 '' AS TransportId,0 AS AssetBusinessTypeId,@hascombination,
			@posID
							
			SELECT @newbillnumberid=SCOPE_IDENTITY();
			INSERT INTO #daftBillNumerid VALUES(@newbillnumberid)		
			
			UPDATE dbo.BillIndex SET totalmoney=dbo.F_RoundTotal(totalmoney),
									 NTotalMoney=dbo.F_RoundTotal(NTotalMoney),
									 totalinmoney=dbo.F_RoundTotal(totalinmoney),
									 NTotalInMoney=dbo.F_RoundTotal(NTotalInMoney),
									 preferencemoney=dbo.F_RoundTotal(preferencemoney),
									 NPreferenceMoney=dbo.F_RoundTotal(NPreferenceMoney),
									 totalqty=dbo.F_RoundQty(totalqty)
			WHERE BillNumberId=@newbillnumberid
				
			IF @billtype=305
			BEGIN
			
			
				--start处理组合品销售出库单start
				IF @billtype=305 AND @hascombination=1
				BEGIN
					IF @CouponCodes<>''
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= 12 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										COUPONID
								)
							SELECT  @newbillnumberid,
									12,
									@posID,
									a.a,
									C.COUPONID
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
							WHERE ISNULL(A,'')<>''
							
							UPDATE dbo.Coupon_CodeInfo SET [State]=3
							FROM Coupon_CodeInfo cci 
							INNER JOIN 
							(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode
						END
					INSERT INTO dbo.PT_Combin_SaleBill											
								( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
								  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,OrderID ,TeamNo ,TeamNO1 ,
								  IsUnit2 ,InputCostPrice ,GoodsOrder ,BackQty ,
								   GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
								  Tax , KTypeID ,Stypeid ,ShareFee ,TaxMoney ,NSalePrice ,NSaleTotal ,
								  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
								  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
								  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,entryCode ,InvoiceQty ,InvoiceMoney ,
								  NInvoiceMoney ,IsGift ,BeforePromoID ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
								  CompleteTotal ,NCompleteTotal ,LendBillNumberID ,LendBillID,CouponCode,PriceSource,PromonIds,pindexid
								  
								)			
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
						0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
						a.total,a.comment,-1 AS orderid,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,0 AS inputcostprice,0 AS GoodsOrder,
						NULL AS backqty,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
						0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
						0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS ShareFee,0 AS taxmoney,
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
						p.baseUnitId,p.AssistantUnitId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
						u1.Rate,--浮动单位换算率
						NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						@CargoID AS CargoID,a.ItemID,a.IsCombined,'' AS entryCode,0,0,0 AS NInvoiceMoney,a.IsGift,0,0,0 AS PriceStyle,
						a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,0,0,a.couponcode,a.pricesource,a.PromoIds,a.pindexid	
						
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
						WHERE ISNULL(a.iscombination,0)=1 
						ORDER BY a.id
						
						UPDATE dbo.PT_Combin_SaleBill SET ShowOrder=ID,
												Qty=dbo.F_RoundQty(Qty),
												SalePrice=dbo.F_RoundPrice(SalePrice),
												discount=dbo.F_RoundDiscount(discount),
												DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
												costprice=dbo.F_RoundPrice(costprice),
												total=dbo.F_RoundTotal(total),
												TaxPrice=dbo.F_RoundPrice(TaxPrice),
												TaxTotal=dbo.F_RoundTotal(TaxTotal),
												InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
												BackQty=dbo.F_RoundQty(BackQty),
												CompleteQTY=dbo.F_RoundQty(CompleteQTY),
												SaleTotal=dbo.F_RoundTotal(SaleTotal),
												Tax=dbo.F_RoundTax(Tax),
												TaxMoney=dbo.F_RoundTotal(TaxMoney),
												NSalePrice=dbo.F_RoundPrice(NSalePrice),
												NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
												NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
												NTotal=dbo.F_RoundTotal(Total),
												NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
												NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
												NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
												NQty=dbo.F_RoundQty(NQty),
												MQty=dbo.F_RoundQty(MQty),
												MSalePrice=dbo.F_RoundPrice(MSalePrice),
												MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
												MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
												CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
												CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
												CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
												InvoiceQty=dbo.F_RoundQty(InvoiceQty),
												InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
												NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
												CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
												NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					
					
					--组合品明细
						INSERT INTO dbo.PT_Combin_SaleBillDetail											
								( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
								  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,OrderID ,TeamNo ,TeamNO1 ,
								  IsUnit2 , Serial ,InputCostPrice ,GoodsOrder ,BackQty ,GoodsNumber ,ProduceDate ,
								  ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
								  Tax , KTypeID ,Stypeid ,ShareFee ,TaxMoney ,NSalePrice ,NSaleTotal ,
								  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
								  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
								  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,entryCode ,InvoiceQty ,InvoiceMoney ,
								  NInvoiceMoney ,IsGift ,BeforePromoID ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
								  CompleteTotal ,NCompleteTotal  ,LendBillNumberID ,LendBillID,combinationptypeid,PriceSource,pindexid
								  
								)			
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
						0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
						a.total,a.comment,-1 AS orderid,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,a.Serial,0 AS inputcostprice,0 AS GoodsOrder,
						NULL AS backqty,a.GoodsNumber,a.ProduceDate,a.ValidDate,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
						0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
						0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS ShareFee,0 AS taxmoney,
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
						p.baseUnitId,p.AssistantUnitId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
						u1.Rate,--浮动单位换算率
						NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						@CargoID AS CargoID,a.ItemID,a.IsCombined,'' AS entryCode,0,0,0 AS NInvoiceMoney,a.IsGift,0,0,0 AS PriceStyle,
						a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,0,0,a.combinationptypeid,a.pricesource,a.pindexid
						
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
						WHERE ISNULL(a.iscombination,0)=0 
						ORDER BY a.id
						
						UPDATE dbo.PT_Combin_SaleBillDetail SET ShowOrder=ID,
												Qty=dbo.F_RoundQty(Qty),
												SalePrice=dbo.F_RoundPrice(SalePrice),
												discount=dbo.F_RoundDiscount(discount),
												DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
												costprice=dbo.F_RoundPrice(costprice),
												total=dbo.F_RoundTotal(total),
												TaxPrice=dbo.F_RoundPrice(TaxPrice),
												TaxTotal=dbo.F_RoundTotal(TaxTotal),
												InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
												BackQty=dbo.F_RoundQty(BackQty),
												CompleteQTY=dbo.F_RoundQty(CompleteQTY),
												SaleTotal=dbo.F_RoundTotal(SaleTotal),
												Tax=dbo.F_RoundTax(Tax),
												TaxMoney=dbo.F_RoundTotal(TaxMoney),
												NSalePrice=dbo.F_RoundPrice(NSalePrice),
												NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
												NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
												NTotal=dbo.F_RoundTotal(Total),
												NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
												NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
												NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
												NQty=dbo.F_RoundQty(NQty),
												MQty=dbo.F_RoundQty(MQty),
												MSalePrice=dbo.F_RoundPrice(MSalePrice),
												MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
												MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
												CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
												CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
												CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
												InvoiceQty=dbo.F_RoundQty(InvoiceQty),
												InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
												NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
												CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
												NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					--组合品明细
					
					
					
					--新加 施训国存储过程 处理草稿库存
					EXEC GP_CopyOrCreateBill_DraftQTY  @newbillnumberid,12
					
				END
				--end处理组合品销售出库单end
			    ELSE
					BEGIN
						IF @CouponCodes<>''
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= 11 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										COUPONID
								)
							SELECT  @newbillnumberid,
									11,
									@posID,
									a.a,
									C.COUPONID
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
							WHERE ISNULL(A,'')<>''
							
							UPDATE dbo.Coupon_CodeInfo SET [State]=3
							FROM Coupon_CodeInfo cci 
							INNER JOIN 
							(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode
						END
						
						INSERT INTO dbo.SaleBill											
								( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
								  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,OrderID ,TeamNo ,TeamNO1 ,
								  IsUnit2 , Serial ,InputCostPrice ,GoodsOrder ,BackQty ,GoodsNumber ,ProduceDate ,
								  ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
								  Tax , KTypeID ,Stypeid ,ShareFee ,TaxMoney ,NSalePrice ,NSaleTotal ,
								  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
								  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
								  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,entryCode ,InvoiceQty ,InvoiceMoney ,
								  NInvoiceMoney ,IsGift ,BeforePromoID ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
								  CompleteTotal ,NCompleteTotal ,OMBillID ,LendBillNumberID ,LendBillID,
								  EtypeID,CouponCode,PriceSource,PromonIds
								)			
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
						0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
						a.total,a.comment,-1 AS orderid,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,a.Serial,0 AS inputcostprice,0 AS GoodsOrder,
						NULL AS backqty,a.GoodsNumber,a.ProduceDate,a.ValidDate,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
						0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
						0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,NULL AS ShareFee,0 AS taxmoney,
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
						p.baseUnitId,p.AssistantUnitId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
						u1.Rate,--浮动单位换算率
						NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						@CargoID AS CargoID,a.ItemID,a.IsCombined,'' AS entryCode,0,0,0 AS NInvoiceMoney,a.IsGift,0,NULL,0 AS PriceStyle,
						a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,0 AS OMBillID,NULL,NULL				
						,salee.typeId,a.couponcode,a.pricesource,a.PromoIds
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID 
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1
						WHERE ISNULL(a.iscombination,0)=0 
						ORDER BY a.id
						
						UPDATE dbo.SaleBill SET ShowOrder=ID,
												Qty=dbo.F_RoundQty(Qty),
												SalePrice=dbo.F_RoundPrice(SalePrice),
												discount=dbo.F_RoundDiscount(discount),
												DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
												costprice=dbo.F_RoundPrice(costprice),
												total=dbo.F_RoundTotal(total),
												TaxPrice=dbo.F_RoundPrice(TaxPrice),
												TaxTotal=dbo.F_RoundTotal(TaxTotal),
												InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
												BackQty=dbo.F_RoundQty(BackQty),
												CompleteQTY=dbo.F_RoundQty(CompleteQTY),
												SaleTotal=dbo.F_RoundTotal(SaleTotal),
												Tax=dbo.F_RoundTax(Tax),
												TaxMoney=dbo.F_RoundTotal(TaxMoney),
												NSalePrice=dbo.F_RoundPrice(NSalePrice),
												NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
												NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
												NTotal=dbo.F_RoundTotal(Total),
												NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
												NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
												NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
												NQty=dbo.F_RoundQty(NQty),
												MQty=dbo.F_RoundQty(MQty),
												MSalePrice=dbo.F_RoundPrice(MSalePrice),
												MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
												MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
												CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
												CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
												CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
												InvoiceQty=dbo.F_RoundQty(InvoiceQty),
												InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
												NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
												CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
												NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					
					--新加 施训国存储过程 处理草稿库存
					EXEC GP_CopyOrCreateBill_DraftQTY  @newbillnumberid,11
				END
			END
			ELSE
			BEGIN
				--start处理组合品销售出库单start
				IF @billtype=307 AND @hascombination=1
				BEGIN
					IF @CouponCodes<>''
					BEGIN
						--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= 12 

						INSERT INTO Coupon_BillUsed
							(		BillnumberId,
									BillType,
									PosID,
									CouponCode,
									COUPONID
							)
						SELECT  @newbillnumberid,
								46,
								@posID,
								a.a,
								C.COUPONID
						FROM dbo.f_split(@CouponCodes,'я') A
						INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
						WHERE ISNULL(A,'')<>''
						
						UPDATE dbo.Coupon_CodeInfo SET [State]=5
						FROM Coupon_CodeInfo cci 
						INNER JOIN 
						(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode
					END
						
					INSERT INTO dbo.PT_Combin_SaleBackBill											
								( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
								  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo ,TeamNO1 ,
								  IsUnit2 ,InputCostPrice ,GoodsOrder ,
								   GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
								  Tax , KTypeID ,Stypeid  ,TaxMoney ,NSalePrice ,NSaleTotal ,
								  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
								  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
								  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,
								  NInvoiceMoney ,IsGift ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
								  CompleteTotal ,NCompleteTotal,CouponCode,PriceSource,pindexid
								  
								)			
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
						0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
						a.total,a.comment,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,0 AS inputcostprice,0 AS GoodsOrder
						,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
						0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
						0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS taxmoney,
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
						p.baseUnitId,p.AssistantUnitId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
						u1.Rate,--浮动单位换算率
						NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						@CargoID AS CargoID,a.ItemID,a.IsCombined,0,0,0 AS NInvoiceMoney,a.IsGift,0,0 AS PriceStyle,
						a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,a.couponcode,a.pricesource,a.pindexid	
						
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
						WHERE ISNULL(a.iscombination,0)=1 
						ORDER BY a.id
						
						UPDATE dbo.PT_Combin_SaleBackBill SET ShowOrder=ID,
												Qty=dbo.F_RoundQty(Qty),
												SalePrice=dbo.F_RoundPrice(SalePrice),
												discount=dbo.F_RoundDiscount(discount),
												DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
												costprice=dbo.F_RoundPrice(costprice),
												total=dbo.F_RoundTotal(total),
												TaxPrice=dbo.F_RoundPrice(TaxPrice),
												TaxTotal=dbo.F_RoundTotal(TaxTotal),
												InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
												CompleteQTY=dbo.F_RoundQty(CompleteQTY),
												SaleTotal=dbo.F_RoundTotal(SaleTotal),
												Tax=dbo.F_RoundTax(Tax),
												TaxMoney=dbo.F_RoundTotal(TaxMoney),
												NSalePrice=dbo.F_RoundPrice(NSalePrice),
												NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
												NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
												NTotal=dbo.F_RoundTotal(Total),
												NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
												NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
												NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
												NQty=dbo.F_RoundQty(NQty),
												MQty=dbo.F_RoundQty(MQty),
												MSalePrice=dbo.F_RoundPrice(MSalePrice),
												MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
												MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
												CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
												CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
												CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
												InvoiceQty=dbo.F_RoundQty(InvoiceQty),
												InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
												NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
												CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
												NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					
					
					--组合品明细
						INSERT INTO dbo.PT_Combin_SaleBackBillDetail											
								( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
								  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo ,TeamNO1 ,
								  IsUnit2 , Serial ,InputCostPrice ,GoodsOrder ,GoodsNumber ,ProduceDate ,
								  ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
								  Tax , KTypeID ,Stypeid ,TaxMoney ,NSalePrice ,NSaleTotal ,
								  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
								  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
								  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,
								  NInvoiceMoney ,IsGift ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
								  CompleteTotal ,NCompleteTotal,combinationptypeid,PriceSource,pindexid
								  
								)			
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
						0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
						a.total,a.comment,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,a.Serial,0 AS inputcostprice,0 AS GoodsOrder
						,a.GoodsNumber,a.ProduceDate,a.ValidDate,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
						0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
						0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS taxmoney,
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
						p.baseUnitId,p.AssistantUnitId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
						u1.Rate,--浮动单位换算率
						NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						@CargoID AS CargoID,a.ItemID,a.IsCombined,0,0,0 AS NInvoiceMoney,a.IsGift,0,0 AS PriceStyle,
						a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,a.combinationptypeid,a.pricesource,a.pindexid
						
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
						WHERE ISNULL(a.iscombination,0)=0 
						ORDER BY a.id
						
						UPDATE dbo.PT_Combin_SaleBackBillDetail SET ShowOrder=ID,
												Qty=dbo.F_RoundQty(Qty),
												SalePrice=dbo.F_RoundPrice(SalePrice),
												discount=dbo.F_RoundDiscount(discount),
												DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
												costprice=dbo.F_RoundPrice(costprice),
												total=dbo.F_RoundTotal(total),
												TaxPrice=dbo.F_RoundPrice(TaxPrice),
												TaxTotal=dbo.F_RoundTotal(TaxTotal),
												InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
												CompleteQTY=dbo.F_RoundQty(CompleteQTY),
												SaleTotal=dbo.F_RoundTotal(SaleTotal),
												Tax=dbo.F_RoundTax(Tax),
												TaxMoney=dbo.F_RoundTotal(TaxMoney),
												NSalePrice=dbo.F_RoundPrice(NSalePrice),
												NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
												NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
												NTotal=dbo.F_RoundTotal(Total),
												NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
												NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
												NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
												NQty=dbo.F_RoundQty(NQty),
												MQty=dbo.F_RoundQty(MQty),
												MSalePrice=dbo.F_RoundPrice(MSalePrice),
												MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
												MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
												CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
												CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
												CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
												InvoiceQty=dbo.F_RoundQty(InvoiceQty),
												InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
												NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
												CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
												NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					--组合品明细
					
					
					
					--新加 施训国存储过程 处理草稿库存
					EXEC GP_CopyOrCreateBill_DraftQTY  @newbillnumberid,46
					
				END
				--end处理组合品销售出库单end
				ELSE
				BEGIN		
					IF @CouponCodes<>''
					BEGIN
						--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= 45 

						INSERT INTO Coupon_BillUsed
							(		BillnumberId,
									BillType,
									PosID,
									CouponCode,
									COUPONID
							)
						SELECT  @newbillnumberid,
								45,
								@posID,
								a.a,
								C.CouponId
						FROM dbo.f_split(@CouponCodes,'я') A
						INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
						WHERE ISNULL(A,'')<>''
						
						UPDATE dbo.Coupon_CodeInfo SET [State]=5
						FROM Coupon_CodeInfo cci 
						INNER JOIN 
						(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode
					END
					
					INSERT INTO dbo.saleBackBill
							( BillNumberId ,PtypeId , Qty ,SalePrice ,discount ,DiscountPrice ,
							  jobnumber ,goodsno ,total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo ,TeamNO1 ,
							  IsUnit2 ,Serial ,OldID ,CostPrice , OldBillNumberID ,InputCostPrice ,GoodsOrder ,
							  GoodsNumber ,ProduceDate ,ValidDate ,GoodsBTypeID , GoodsCostPrice ,GoodsCostTotal ,
							  HandZeroCost ,CompleteQTY ,SaleTotal ,Tax ,KTypeID ,Stypeid ,FromBillNumberID ,FromBillID ,
							  TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,
							  NTaxMoney ,UnitID , NUnitID ,NQty ,UnitRate ,NUnitMsg ,MUnitID ,MQty ,MUnitRate ,
							  MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,
							  CurMTaxPrice , CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,
							  IsGift ,ReferPrice , PriceStyle ,PromoType ,ShowOrder ,OMBillID ,CompleteTotal ,
							  NCompleteTotal,
							  EtypeID,CouponCode,PriceSource,PromoIds
							)	
					OUTPUT INSERTED.ID INTO #tempbillid			
					SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),CAST(a.retailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS discountprice,				
							'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
							a.total,a.comment,0 AS TeamNo,0 AS TeamNO1,isUnit2=0,a.Serial,'' AS oldid,0 AS costprice,0 AS OldBillNumberID,
							0 AS inputcostprice,0 AS GoodsOrder,a.GoodsNumber,a.ProduceDate,a.ValidDate,'' as GoodsBTypeID,
							a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,0 AS HandZeroCost,
							NULL AS CompleteQTY,a.RetailTotal,0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS FromBillNumberID,
							0 AS FromBillID,0 AS taxmoney,CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
							CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
							CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
							p.baseUnitId,p.AssistantUnitId,
							CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
							u1.Rate,--浮动单位换算率
							NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,
							a.RetailPrice,a.Price,a.Price,@CargoID AS CargoID,a.ItemID,a.IsCombined,0,0,0 AS NInvoiceMoney,a.IsGift,
							NULL,0 AS PriceStyle,a.PromoType,0 AS ShowOrder,0 AS OMBillID,NULL,NULL,
							salee.typeId,a.couponcode,a.pricesource,a.PromoIds									
					FROM #PosSaleBill a  
					INNER JOIN ptype p ON a.PID=p.Pid
					LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
					INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
					LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
					WHERE ISNULL(a.iscombination,0)=0 
					ORDER BY a.id
					
					--UPDATE dbo.saleBackBill SET ShowOrder=ID WHERE BillNumberId=@newbillnumberid
					
					--新加 施训国存储过程 处理草稿库存
					EXEC GP_CopyOrCreateBill_DraftQTY  @newbillnumberid,45
				END
			END
			
			SELECT @rowcount=@@ROWCOUNT											
			INSERT INTO PosRetailRecord
			( 
				PosSaleBillId,PosBillNumberId,RetailBillId,RetailBillNumberId,AuditingFlag,ReCordTime
			)
			SELECT c.detailid,c.billnumberid,t.detailid,@newbillnumberid,0 ,GETDATE()
			FROM
				(
					SELECT   row_number() over (order by Id) AS orderid,
					billnumberid,detailid 
					FROM #PosSaleBill 
				)c
			INNER JOIN #tempbillid t ON t.ID=c.orderid
			
			
			INSERT INTO BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotalMoney,billtype,yhType,CouponCode,VipTotal)
			SELECT  
			@newbillnumberid,
			ATypeID,
			CASE WHEN a.atypeid=1 THEN 
			SUM(a.atotal) - ISNULL(@SaveInCzMoney,0)
			WHEN a.paystyle='现金' THEN 
			SUM(a.atotal) - ISNULL(@SaveInCzMoney,0)
			ELSE SUM(a.atotal) END,
			a.Comment,
			VipCardID,
			CASE WHEN a.atypeid=1 THEN 
			SUM(a.atotal)- ISNULL(@SaveInCzMoney,0)  
			WHEN a.paystyle='现金' THEN 
			SUM(a.atotal) - ISNULL(@SaveInCzMoney,0)
			ELSE SUM(a.atotal) END,
			(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,
			a.yhType,
			a.CouponCode,
			a.VipTotal
			
			FROM PosMulAccount a
			INNER JOIN (SELECT DISTINCT PosBillNumberId FROM PosRetailRecord WHERE RetailBillNumberId=@newbillnumberid ) b 
			ON a.BillNumberId=b.PosBillNumberId
			WHERE a.atypeid <> -1 AND a.atypeid <> '-1' 
			GROUP BY ATypeID,VipCardID,paystyle,a.Comment,a.yhType,a.CouponCode,a.VipTotal
			
			SET @btypetotal=(
			SELECT 
			SUM(atotal) AS total FROM PosMulAccount 
			WHERE BillNumberId=@posbillnumberid AND ATypeID=-1)
			
			UPDATE dbo.BillIndex SET totalinmoney=totalinmoney-ISNULL(@btypetotal,0)-ISNULL(@premoney,0),NTotalInMoney=NTotalInMoney-ISNULL(@btypetotal,0)-ISNULL(@premoney,0)
			WHERE BillNumberId=@newbillnumberid
		
					-------------------具体合并 end----------------
			COMMIT TRAN SaveBill		
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN SaveBill
		SET @errmsg=ERROR_MESSAGE()
		RAISERROR (@errmsg, -- Message text.
                16, -- Severity.
                1 -- State.
                );
	END CATCH
	ERROR:

		
	FETCH NEXT FROM Pos_cursor
	INTO @posid,@Posbillnumberid,@Kid,@BId,@Eid,@BillDate,@PromoRuleId,@VipCardID,@billtype,@billcount,@BillDescription,@CouponCodes,@PromoIds
END
CLOSE Pos_cursor
DEALLOCATE Pos_cursor

BEGIN TRAN DelBill
BEGIN TRY
	SELECT BillnumberID INTO #DeletedBillID FROM dbo.PosSaleBillIndex WHERE BillnumberID IN (SELECT PosBillNumberId FROM dbo.PosRetailRecord)
	DELETE FROM dbo.PosSaleBill WHERE BillnumberID IN (SELECT BillnumberID FROM #DeletedBillID)
	DELETE FROM dbo.PosMulAccount WHERE BillnumberID IN (SELECT BillnumberID FROM #DeletedBillID)
	DELETE FROM dbo.PosSaleBillIndex WHERE BillnumberID IN (SELECT BillnumberID FROM #DeletedBillID)	
	COMMIT TRAN DelBill
	DROP TABLE #DeletedBillID
END TRY
begin CATCH
	ROLLBACK TRAN DelBill
END CATCH
DROP TABLE #PosSaleBill,#tempbillid,#BillMulAccount



DECLARE @Ret INT=0,@frozedate DATE
DECLARE AuditingCursor CURSOR FOR
SELECT BillNumberId FROM #daftBillNumerid
OPEN AuditingCursor
FETCH NEXT FROM AuditingCursor
INTO @Newbillnumberid
WHILE @@FETCH_STATUS = 0 
BEGIN	
	SET @frozedate=NULL
	
	SELECT @billtype=billtype,@billdate=BillDate,@stypeid=Stypeid,@billcode=BillCode,@ktypeid=ktypeid,@dtypeid=DTypeId,@etypeid=etypeid 
	FROM dbo.BillIndex WHERE BillNumberId=@Newbillnumberid
	
	SELECT @frozedate=FrozeDate FROM dbo.FrozeBusiness WHERE Stypeid=@stypeid
	
	IF @frozedate IS NOT NULL AND @frozedate>@billdate
		GOTO ERROR1
		
	IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName = 'isvirtualstock' AND Value=1)
		AND EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName = 'virtualstockmode' AND Value=2)
		AND EXISTS(SELECT 1 WHERE @billtype IN (SELECT * FROM dbo.f_split((SELECT Value FROM dbo.Userconfig WHERE ConfigName='virtualstockbilltype'),',')))
		AND EXISTS(select 1 WHERE '1' IN (SELECT * FROM dbo.f_split((SELECT Value FROM dbo.Userconfig WHERE ConfigName='draftposting'),',')))
			SET @audit=1
				
	BEGIN TRAN AUDIT
	
	IF EXISTS(SELECT ConfigNo  FROM Userconfig  WHERE ConfigName='BillcodeCreateTime'AND Value=2)
	BEGIN
		SELECT @Month=Month(GETDATE())
		SELECT @Day=DAY(GETDATE())
		SET @BillFlag=CASE @createbilltype WHEN 11 THEN 'XK' WHEN 12 THEN 'ZXK' WHEN 46 THEN 'ZXT' ELSE 'XT' END 	
		SET @BillCode=''	
		----单据编号
		EXEC Gp_GetBillCode @createbilltype, @MONTH,@DAY,@BillFlag,@BillDate,@stypeid,@BillCode OUTPUT,@dfullname,@cefullname
		
		UPDATE dbo.BillIndex SET BillCode= @billcode 
		WHERE BillNumberId=@Newbillnumberid

		--保存种子数
		EXEC GP_AutoCombneRetail_SaveBillCode_Seed @billdate,@createbilltype,@billcode,@etypeid,@ktypeid,@dtypeid,@stypeid,@cefullname
	END	    
	
	IF((SELECT Billtype FROM dbo.PosSaleBillIndexAll WHERE BillnumberID=(SELECT MAX(BillnumberID) FROM dbo.PosSaleBillIndexAll))=305)
	BEGIN
		DECLARE @countitem INT
		DECLARE @num INT=0
		DECLARE @itemidtemp INT=0
		
		IF @billtype = 11
		BEGIN 
			SET @countitem=(
				SELECT COUNT(ptypeid) FROM dbo.SaleBill psb
				INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
				WHERE p.customitemid IS NOT NULL
				AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.SaleBill)
				)
				
			IF(@countitem<>0)
			BEGIN
				WHILE @num<@countitem
				BEGIN 
					SET @itemidtemp=(SELECT T1.ItemID FROM(SELECT ROW_NUMBER() OVER (ORDER BY t.ptypeid) AS rowNum,T.ptypeid,T.ItemID FROM(SELECT ItemID,ptypeid FROM dbo.SaleBill WHERE ptypeid IN(
									SELECT ptypeid FROM dbo.SaleBill psb
									INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
									WHERE p.customitemid IS NOT NULL
									AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.SaleBill))  AND BillNumberId=(SELECT MAX(BillnumberID) FROM dbo.SaleBill)) T) AS T1 WHERE T1.rowNum=@num+1)
					SET @num=@num+1
					IF(@itemidtemp=0)
					BEGIN
						ROLLBACK TRAN AUDIT
						RETURN -1
					END 
				END
			END
		END 
		ELSE IF @billtype = 12
		BEGIN 
			SET @countitem=(
				SELECT COUNT(ptypeid) FROM dbo.PT_Combin_SaleBillDetail psb
				INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
				WHERE p.customitemid IS NOT NULL
				AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBillDetail)
				)
				
			IF(@countitem<>0)
			BEGIN
				WHILE @num<@countitem
				BEGIN 
					SET @itemidtemp=(SELECT T1.ItemID FROM(SELECT ROW_NUMBER() OVER (ORDER BY t.ptypeid) AS rowNum,T.ptypeid,T.ItemID FROM(SELECT ItemID,ptypeid FROM dbo.PT_Combin_SaleBillDetail WHERE ptypeid IN(
									SELECT ptypeid FROM dbo.PT_Combin_SaleBillDetail psb
									INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
									WHERE p.customitemid IS NOT NULL
									AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBillDetail))  AND BillNumberId=(SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBillDetail)) T) AS T1 WHERE T1.rowNum=@num+1)
					SET @num=@num+1
					IF(@itemidtemp=0)
					BEGIN
						ROLLBACK TRAN AUDIT
						RETURN -1
					END 
				END
			END
		END 
	END
	ELSE
	BEGIN
		DECLARE @countitem1 INT
		DECLARE @num1 INT=0
		DECLARE @itemidtemp1 INT=0
		
		IF @billtype = 45
		BEGIN 
			SET @countitem1=(
			SELECT COUNT(ptypeid) FROM dbo.saleBackBill psb
			INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
			WHERE p.customitemid IS NOT NULL
			AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.saleBackBill))
			IF(@countitem1<>0)
			BEGIN
				WHILE @num1<@countitem1
				BEGIN 
					SET @itemidtemp1=(SELECT T1.ItemID FROM(SELECT ROW_NUMBER() OVER (ORDER BY t.ptypeid) AS rowNum,T.ptypeid,T.ItemID FROM(SELECT ItemID,ptypeid FROM dbo.saleBackBill WHERE ptypeid IN(
									SELECT ptypeid FROM dbo.saleBackBill psb
									INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
									WHERE p.customitemid IS NOT NULL
									AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.saleBackBill))  AND BillNumberId=(SELECT MAX(BillnumberID) FROM dbo.saleBackBill)) T) AS T1 WHERE T1.rowNum=@num1+1)
					SET @num1=@num1+1
					IF(@itemidtemp1=0)
					BEGIN
						ROLLBACK TRAN AUDIT
						RETURN -1
					END 
				END
			END
		END
		ELSE IF @billtype = 46
		BEGIN 
			SET @countitem1=(
			SELECT COUNT(ptypeid) FROM dbo.PT_Combin_SaleBackBillDetail psb
			INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
			WHERE p.customitemid IS NOT NULL
			AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBackBillDetail))
			IF(@countitem1<>0)
			BEGIN
				WHILE @num1<@countitem1
				BEGIN 
					SET @itemidtemp1=(SELECT T1.ItemID FROM(SELECT ROW_NUMBER() OVER (ORDER BY t.ptypeid) AS rowNum,T.ptypeid,T.ItemID FROM(SELECT ItemID,ptypeid FROM dbo.PT_Combin_SaleBackBillDetail WHERE ptypeid IN(
									SELECT ptypeid FROM dbo.PT_Combin_SaleBackBillDetail psb
									INNER JOIN dbo.ptype p ON p.typeId=psb.ptypeid
									WHERE p.customitemid IS NOT NULL
									AND psb.BillnumberID IN (SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBackBillDetail))  AND BillNumberId=(SELECT MAX(BillnumberID) FROM dbo.PT_Combin_SaleBackBillDetail)) T) AS T1 WHERE T1.rowNum=@num1+1)
					SET @num1=@num1+1
					IF(@itemidtemp1=0)
					BEGIN
						ROLLBACK TRAN AUDIT
						RETURN -1
					END 
				END
			END
		END
	END
	
	
	DECLARE @tempatypeid1 VARCHAR(50)
	DECLARE @tempaloneusebsys VARCHAR(50)
	DECLARE @tempIsAcSystem VARCHAR(50)
	
	SELECT @tempatypeid1=atypeid1 FROM billindex WHERE billnumberid=@Newbillnumberid
	SELECT @tempaloneusebsys=subvalue FROM sysdata WHERE subname='aloneusebsys'
	SELECT @tempIsAcSystem=subvalue FROM dbo.sysdata WHERE SubName='IsUseAcSystem'
	
	IF (@tempatypeid1 IS NOT NULL AND LEN(@tempatypeid1) > 0) OR (@tempaloneusebsys = '1' OR @tempaloneusebsys = 1) OR(@tempIsAcSystem=0 OR @tempIsAcSystem='0')
	BEGIN
		EXEC @Ret= dbo.Gp_Auditing @nBillID = @Newbillnumberid, -- numeric
			@szCheckMan = @etypeid, -- varchar(50)
			@szPID = '', -- varchar(1000)
			@chvOpID = @etypeid, -- varchar(50)
			@KTypeID = '', -- varchar(50)
			@billtype = @createbilltype, -- int
			@voucherMsg = '', -- varchar(50)
			@vipcentinfo='',
			@AssetMsg=''
		

		IF @Ret=0 OR @ret>=-227 AND @Ret<=-210 
		BEGIN
			COMMIT TRAN AUDIT
			update PosRetailRecord SET AuditingFlag=1 WHERE RetailBillNumberId=@Newbillnumberid
			SELECT @resultBillnumberid = CAST(@Newbillnumberid AS VARCHAR)+','+ISNULL(@resultBillnumberid,'')
		END
		ELSE
		BEGIN
			ROLLBACK TRAN AUDIT
		END
	END
	ELSE
	BEGIN
		ROLLBACK TRAN AUDIT
	END
		
	ERROR1:
	
	FETCH NEXT FROM AuditingCursor
	INTO @Newbillnumberid
END
CLOSE AuditingCursor
DEALLOCATE AuditingCursor

DROP TABLE #daftBillNumerid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


--作    者：徐辉
--生成时间：2005-3-27
--作    用：自动生成盘点单草稿，每张草稿150行数据，可修改@detailmaxcount配置

--修    改：舒珊
--修改时间：2016-12-29
--作    用：去掉游标 添加GP_SaveBillCode_maxSeed ,F_GetBillCode 批量添加

CREATE	PROCEDURE Gp_AutoDoStockCheck
(
	@szktypeid varchar(100),
	@szPtypeid varchar(100),
	@szIfUseGoods varchar(1),
	@szEtypeid varchar(100),
	@ifwx		varchar(10),	--0.正常商品 1.维修商品
	@includep	varchar(10),	--是否包含停用商品
	@ReturnBillCode varchar(max) OUTPUT
)
WITH ENCRYPTION
AS
SET NOCOUNT ON

--=====================================================权限检查=====================================================
IF @szEtypeid IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @szEtypeid,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--==================================================================================================================
DECLARE @costing INT
declare @detailmaxcount int
set @detailmaxcount=150

SELECT  TOP 1 @costing=SubValue FROM sysdata where SubName='costing'
DECLARE @stid VARCHAR(100)
SELECT  @stid = stypeid FROM stock WHERE typeId = @szktypeid
 
DECLARE @chrSQLCursor varchar(max),
		@Comment      varchar(1000)
		
DECLARE @NowDate	DATETIME

SELECT @NowDate=GETDATE()

Create table #TempPtype(	
				ID				INT  IDENTITY (1,1),--自增长 用于判断属于哪张单
				PTYPEID			varchar(50),
				QTY				numeric(24,10),
				NQTY			numeric(24,10),
				GoodsCostPrice	numeric(24,10),
				GoodsCostTotal	numeric(24,10),
				KtypeId			varchar(50),
				GoodsNumber		varchar(100),
				ProduceDate    	varchar(50),
				ValidDate		varchar(50),
				GoodsBTypeID 	varchar(50),
				itemid			int,
				Iscombined		bit,
				cargoid			int,
				groupid			int,	--判断属于哪个单 （1-150为一单）
				StockCheckID	int,
				billcode		varchar(200)
				
				
)

CREATE CLUSTERED INDEX TempPtype_ID ON #TempPtype(ID) 
CREATE NONCLUSTERED INDEX TempPtype_groupid ON #TempPtype(groupid) 
	

IF @IfWx = '0'
	SET @Comment = '批量盘点 【正常商品】 生成'
ELSE
	SET @Comment = '批量盘点 【维修商品】 生成'

DECLARE @defaultCargoId INT
IF @szIfUseGoods = '1' AND @IfWx = '0'
	BEGIN
		SELECT @chrSQLCursor = '
		insert into #TempPtype (
						ptypeid,
						qty,
						nqty,
						goodscostprice,
						goodscosttotal,
						ktypeid,
						goodsnumber,
						producedate,
						validdate,
						goodsbtypeid,
						itemid,
						iscombined,
						cargoid	
		)
		SELECT 	p.typeid AS typeid,
				ISNULL(g.Qty,0) AS Qty,
				ISNULL(g.NQty,0) AS NQty,
				ISNULL(g.Price,-1) AS GoodsCostPrice,
				ISNULL(g.Qty,0)* ISNULL(g.Price,-1) AS GoodsCostTotal,
				g.KtypeId,
				g.GoodsNumber,
				g.ProduceDate,
				g.ValidDate,
				g.GoodsBTypeID,
				g.itemid,
				g.Iscombined,'
		IF EXISTS(SELECT TOP 1  1 FROM Userconfig  where ConfigName='mngcargospace' AND Value=0)
		BEGIN		
			SELECT @defaultCargoId=CargoID FROM CargoType where IsDefault=1 AND KtypeID=@szktypeid		
			SELECT @chrSQLCursor +=CHAR(39)+ CAST(@defaultCargoId as VARCHAR)+CHAR(39) +'	 as cargoid'
		END
		ELSE 	
			SELECT @chrSQLCursor += '		g.cargoid'
		
		SELECT @chrSQLCursor += '
		FROM 	Ptype p
		LEFT JOIN	(
						SELECT 	gq.*,g.price,'				
		SELECT @chrSQLCursor += 'g.JobNumber,g.OutFactoryDate,g.GoodsOrder,g.GoodsBTypeID
						FROM 	GoodsStocks_qty gq 
								INNER JOIN GoodsStocks g  ON	g.PtypeId=gq.PTypeID 
																AND g.ktypeid=gq.ktypeid'
																
		if @costing=3
			SELECT @chrSQLCursor += '							AND g.ProduceDate=gq.ProduceDate 
																AND g.ValidDate=gq.ValidDate 
																AND g.GoodsNumber=gq.GoodsNumber
																And g.Price=gq.GoodsCostPrice'
																																						
		SELECT @chrSQLCursor += '
								INNER JOIN  F_GetManDetailKType('+char(39)+@szEtypeid+char(39)+') mk ON g.ktypeid=mk.typeid
								INNER JOIN  F_GetManDetailPType('+char(39)+@szEtypeid+char(39)+') mp ON g.ptypeid=mp.typeid
						WHERE 	g.KtypeId = '''+@szktypeid+'''
					) g ON p.typeid = g.ptypeid
		WHERE 	p.SonNum=0 
				AND p.IsService=0 
				AND p.iscombinationproduct = 0
				AND p.TypeId LIKE '''+@szPtypeid + '%'' 
				AND p.TypeId IN (SELECT * FROM F_GetManDetailPType('+char(39)+@szEtypeid+char(39)+'))'
		IF @includep <>'true'
				SET @chrSQLCursor=@chrSQLCursor+' AND P.deleted=''0'' '
			SET @chrSQLCursor=@chrSQLCursor+' ORDER BY p.Usercode'
	END
ElSE
BEGIN
	SELECT @chrSQLCursor = '
			insert into #TempPtype (
						ptypeid,
						qty,
						nqty,
						itemid,
						Iscombined,
						GoodsNumber,
						producedate,
						validdate,
						cargoid	
			)
			SELECT 	p.typeid AS typeid,
					gg.qty as qty,
					gg.nqty as nqty,
					gg.ItemID,
					gg.Iscombined,
					gg.GoodsNumber,
					gg.ProduceDate,
					gg.ValidDate,'
		IF EXISTS(SELECT TOP 1  1 FROM Userconfig  where ConfigName='mngcargospace' AND Value=0)
		BEGIN		

			SELECT @defaultCargoId=CargoID FROM CargoType where IsDefault=1 AND KtypeID=@szktypeid		
			SELECT @chrSQLCursor +=CHAR(39)+ CAST(@defaultCargoId as VARCHAR)+CHAR(39) +'	 as cargoid'
		END
		ELSE 	
			SELECT @chrSQLCursor += 'gg.cargoid'
SELECT @chrSQLCursor +=	'							
			 FROM 	Ptype p
					INNER JOIN F_GetManDetailPType('+char(39)+@szEtypeid+char(39)+')  mp ON p.typeid=mp.typeid
					LEFT JOIN (
								SELECT	gq.QTY as qty,
										gq.nqty as nqty,
										gq.PTypeID,
										gq.KTypeID,
										gq.ItemID,
										gq.Iscombined,
										gq.CargoID,
										gq.GoodsNumber,
										gq.ProduceDate,
										gq.ValidDate
										'+CHAR(10)
	IF @IfWx = '0'
	BEGIN										
		SELECT @chrSQLCursor += 'FROM
				(
					SELECT SUM(Qty) as qty,SUM(NQty) as nqty,PTypeID,KTypeID,ItemID,Iscombined,CargoID,GoodsNumber,ProduceDate,ValidDate 
					FROM GoodsStocks_qty 
					WHERE KtypeId = '''+@szktypeid+'''
					GROUP BY PTypeID,KTypeID,ItemID,Iscombined,CargoID,GoodsNumber,ProduceDate,ValidDate
				) gq
				'--INNER JOIN GoodsStocks g ON g.PtypeId=gq.PTypeID AND g.ktypeid=gq.ktypeid 非手工下面直接统计GoodsStocks_qty
		if @costing=3
			SELECT @chrSQLCursor += '															
							AND g.ProduceDate=gq.ProduceDate 
							AND g.ValidDate=gq.ValidDate 
							AND g.GoodsNumber=gq.GoodsNumber
							And g.Price=gq.GoodsCostPrice'
	END	
	ELSE
	BEGIN
		SELECT @chrSQLCursor += 'FROM	--wx_GoodsStocks gq 
					(
						SELECT SUM(Qty) as qty,SUM(NQty) as nqty,PTypeID,KTypeID,ItemID,Iscombined,CargoID,GoodsNumber,ProduceDate,ValidDate 
						FROM wx_GoodsStocks 
						WHERE KtypeId = '''+@szktypeid+'''
						GROUP BY PTypeID,KTypeID,ItemID,Iscombined,CargoID,GoodsNumber,ProduceDate,ValidDate
					) gq '
					 		
	END
									
SELECT @chrSQLCursor += ' INNER JOIN F_GetManDetailKType('+char(39)+@szEtypeid+char(39)+') k ON k.typeid=gq.ktypeid
						  INNER JOIN F_GetManDetailPType('+char(39)+@szEtypeid+char(39)+') dp ON dp.typeid=gq.ptypeid
					) gg ON p.typeid=gg.ptypeid
			WHERE 	p.SonNum=0 
					AND p.IsService=0 
					AND p.iscombinationproduct = 0
					AND p.TypeId LIKE '''+@szPtypeid + '%'' '
			IF @includep <>'true'
				SET @chrSQLCursor=@chrSQLCursor+' AND P.deleted=''0'' '
			SET @chrSQLCursor=@chrSQLCursor+' ORDER BY p.Usercode'



END
EXEC(@chrSQLCursor)
--print @chrSQLCursor
---------------------------------构造临时表 end------------------------------------------------------------------------------------

---------------------------------操作表数据 begin------------------------------------------------------------------------------------
DECLARE @BillNum int,@BillCode varchar(300),@StockCheckID int, @BillCodeConfig varchar(1),
@Day varchar(100),@Month varchar(100),@Day_1 varchar(100),@Month_1 varchar(100),@Year varchar(100),@CargoSpace varchar(200)

SELECT @StockCheckID=isnull(max(StockCheckID),0)  from StockCheckIndex
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置

update #TempPtype set groupid=((id-1)/@detailmaxcount)+1 

update #TempPtype set StockCheckID=@StockCheckID+groupid

---------------------------------操作表数据 end------------------------------------------------------------------------------------


---------------------------------操作BILLCODE BEGIN------------------------------------------------------------------------------------

IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =306 ) AND @BillCodeConfig='1' --单据编号自定义
BEGIN
	SELECT @Month =''
	SELECT @Day = FullName FROM stock WHERE TypeId = @szktypeid
	SELECT @Year=YEAR(GETDATE())
END
ELSE
BEGIN
	SELECT @Month=Month(GETDATE())
	SELECT @Day=DAY(GETDATE())
	SELECT @Year=YEAR(GETDATE())
END

declare @maxgroupid int,@ini int=1,@minbillcode varchar(500),@curmaxseed int=0,@intFlowType int,@strFlowDate	VARCHAR(100)

select  @maxgroupid=max(groupid) from #TempPtype

SELECT @intFlowType=Value
FROM UserConfig
WHERE ConfigName='FlowSet'
	
IF @intFlowType=0
BEGIN
	--按日
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@NowDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@NowDate) AS VARCHAR(2)),'0')+DBO.FN_FixStr(2,CAST(DAY(@NowDate) AS VARCHAR(2)),'0')
END
ELSE IF @intFlowType=1
BEGIN
	--按月
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@NowDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@NowDate) AS VARCHAR(2)),'0')
END
ELSE IF @intFlowType=2
BEGIN
	--按年
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@NowDate) AS VARCHAR(4)),'0')
END

--print @maxgroupid
--保存当前的最大种子数

EXEC GP_SaveBillCode_maxSeed @NowDate,306,@NowDate,'',@szktypeid,'',@stid,@maxgroupid,@curmaxseed output

--print @curmaxseed 
---------------------------------操作BILLCODE end------------------------------------------------------------------------------------
IF @@error<>0 
	BEGIN
		RETURN -2
	END
---------------------------------StockCheckIndex 数据添加 begin------------------------------------------------------------------------------------
if @curmaxseed=-1
	set @curmaxseed=0

SELECT @Month_1=Month(GETDATE())
SELECT @Day_1=DAY(GETDATE())
INSERT INTO StockCheckIndex(	StockCheckID,
										BillDate,
										BillCode,
										ETypeID,
										KTypeID,
										Comment,
										IfWx
								)
						 select		StockCheckID,
									@Year+'-'+@Month_1+'-'+@Day_1,
									billcode=(select [dbo].F_GetBillCode(306,@Month,@Day,'PM',@NowDate,@stid,'',-1,groupid,@curmaxseed)) ,--@BillCode,
									'',
									@szktypeid,
									@Comment,
									@IfWx
							from #TempPtype group by StockCheckID,groupid


---------------------------------StockCheckIndex 数据添加 end------------------------------------------------------------------------------------
IF @@error<>0 
	BEGIN
		RETURN -2
	END
	
---------------------------------StockCheck 数据添加 BEGIN------------------------------------------------------------------------------------
IF @szIfUseGoods = '1' AND @IfWx = '0'
BEGIN
	INSERT INTO StockCheck 
	(	
		StockCheckID,
		PtypeID,
		Qty,
		StockQty,
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		GoodsCostPrice,
		GoodsCostTotal,
		nqty,
		stocknqty,
		ItemID,
		IsCombined,
		CargoID
	) 
	select			
		P.StockCheckID,
		P.PTypeID,
		P.Qty,
		P.Qty,
		ISnull(P.GoodsNumber,''),
		ISNULL(P.ProduceDate,''),
		ISNULL(P.ValidDate,''),
		ISNULL(P.GoodsBTypeID,''),
		ISNULL(P.GoodsCostPrice,-1),
		ISNULL(P.GoodsCostTotal,0),
		ISNULL(P.nqty,0),
		ISNULL(P.nqty,0),
		ISNULL(P.itemid,0),
		ISNULL(P.Iscombined,0),
		ISNULL(P.cargoid,0)
	FROM #TempPtype P
	order by p.id			
END
ELSE
BEGIN
	INSERT INTO StockCheck
	 (	
		StockCheckID,
		PtypeID,
		Qty,
		StockQty,
		GoodsCostPrice,
		nqty,
		stocknqty,
		ItemID,
		IsCombined,
		CargoID,
		GoodsNumber,
		ProduceDate,
		ValidDate
	) 
SELECT	P.StockCheckID,
		P.PTypeID,
		ISNULL(P.Qty,0),
		ISNULL(P.Qty,0),
		-1,
		ISNULL(P.nqty,0),
		ISNULL(P.nqty,0),
		ISNULL(P.itemid,0),
		ISNULL(P.Iscombined,0),
		CASE WHEN @ifwx=1  THEN 0 ELSE ISNULL(P.cargoid,0) END,--维修的货位统一为0
		ISnull(P.GoodsNumber,''),
		ISNULL(P.ProduceDate,''),
		ISNULL(P.ValidDate,'')
FROM #TempPtype P
order by p.id
			
END
IF @@error<>0 
	BEGIN
		RETURN -2
	END
	
--设置排序号
UPDATE dbo.StockCheck SET ShowOrder=ID WHERE StockCheckID=StockCheckID

---------------------------------StockCheck 数据添加 END------------------------------------------------------------------------------------

SET @ReturnBillCode = ISNULL(@ReturnBillCode,'')
SELECT @ReturnBillCode=@ReturnBillCode+'||' +p.BillCode 
from StockCheckIndex p 
where stockcheckid>=@StockCheckID+1
	and stockcheckid <=@StockCheckID+@maxgroupid


--print @ReturnBillCode

SELECT @ReturnBillCode AS A

DROP TABLE #TempPtype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
-------------------------------------------*/
CREATE PROCEDURE Gp_AutoFinishTemplate 
(
       @billids 		VARCHAR(MAX),
       @billindextype	INT,			---0:billindex 1:CommissionBillNew 2:ReceiptBillIndex
       @billtype		VARCHAR(500),	---单据类型
	   @chvOperatorID	VARCHAR(50),		---操作员ID
	   @startdate		DATE,
	   @enddate			DATE,
	   @stypeid			VARCHAR(MAX)
)
--@encode$--
AS 
SET NOCOUNT ON

SET @stypeid = ISNULL(@stypeid,'')

CREATE TABLE #temp_billInfo
(
	billnumberid	NUMERIC(10,0),
	billtype		INT,
	stypeid			VARCHAR(50)
)

------为空的时候是从【单据逐张批量生成凭证】或是【结转成本】来的
IF @billids = ''
BEGIN
	IF @billtype = '' OR  @billtype = '-1'
		SET @billtype = '147,11,45,160,305,139,140,142,141,34,6,161,126,144,146,145,21,187,188,201,202,9,14,16,116,115,128,129,4,189,66,190,148,150,149,151,36,84,85,78,158,77,93,5,10,57,205,181,183,166,167,168,170,172,159,173,174,212,213,214,215,400,401,402,403'

	INSERT #temp_billInfo(billnumberid,billtype,stypeid)
	SELECT	BillNumberId
			,BillType
			,stypeid
	FROM	BillIndex
	WHERE	BillType IN (SELECT * FROM f_split(@billtype,','))
		AND	BillDate >= @startdate AND BillDate <= @enddate
		AND (@stypeid = '' OR stypeid IN(SELECT * FROM f_split(@stypeid,',')))
	UNION ALL
	SELECT	BillNumberId
			,BillType
			,stypeid
	FROM CommissionBillNew
	WHERE	billtype IN (SELECT * FROM f_split(@billtype,','))
		AND	BillDate >= @startdate AND BillDate <= @enddate
		AND (@stypeid = '' OR stypeid IN(SELECT * FROM f_split(@stypeid,',')))
	UNION ALL
	SELECT	BillNumberId
			,BillType
			,stypeid
	FROM ReceiptBillIndex
	WHERE	billtype IN (SELECT * FROM f_split(@billtype,','))
		AND	BillDate >= @startdate AND BillDate <= @enddate
		AND (@stypeid = '' OR stypeid IN(SELECT * FROM f_split(@stypeid,',')))
END
ELSE  --选择具体单据的，根据@billindextype值判断主表
BEGIN 
	IF @billindextype = 0
	BEGIN
		INSERT #temp_billInfo(billnumberid,billtype,stypeid)
		SELECT	BillNumberId
				,BillType
				,stypeid
		FROM	BillIndex b
		INNER JOIN f_split(@billids,',') f ON f.a = b.BillNumberId
	END
	ELSE IF @billindextype = 1
	BEGIN
		INSERT #temp_billInfo(billnumberid,billtype,stypeid)
		SELECT	BillNumberId
				,BillType
				,stypeid
		FROM	CommissionBillNew b
		INNER JOIN f_split(@billids,',') f ON f.a = b.BillNumberId
	END
	ELSE IF @billindextype = 2
	BEGIN
		INSERT #temp_billInfo(billnumberid,billtype,stypeid)
		SELECT	BillNumberId
				,BillType
				,stypeid
		FROM	ReceiptBillIndex b
		INNER JOIN f_split(@billids,',') f ON f.a = b.BillNumberId
	END
END

CREATE TABLE #temp_Template
(
	BillType	INT
	,StypeId	VARCHAR(50)
	,AtId		INT
)
INSERT INTO #temp_Template(BillType,StypeId,AtId)
SELECT DISTINCT B.BillType,B.Stypeid,T.AtId
FROM	#temp_billInfo B
INNER JOIN SType S ON S.TypeId = B.Stypeid 
LEFT JOIN Ac_Auditing_Template T ON T.BillType = B.BillType AND T.STypeId=S.VerifyID
--WHERE	B.BillType NOT IN ('212','213','214')
	
--没有记录直接返回1
IF NOT EXISTS(SELECT TOP 1 1 FROM #temp_Template )
BEGIN
	SELECT	'1' AS mgs
	RETURN 1
END

--有单据类型没有凭证模板时，返回-1
IF EXISTS(SELECT TOP 1 1 FROM #temp_Template WHERE AtId IS NULL)
BEGIN
	SELECT	'【' +S1.FullName +'-'+ B.BillName +'】' AS mgs
	FROM	#temp_Template T 
	INNER JOIN SType S ON S.TypeId = T.Stypeid
	INNER JOIN SType S1 ON S1.TypeId = S.VerifyID
	INNER JOIN BillName B ON B.Billtype = T.BillType
	WHERE T.AtId IS NULL
	RETURN -1
END


--有单据类型存在1个以上的凭证模板时，返回-2
IF EXISTS (SELECT TOP 1  1 FROM (SELECT  BillType,StypeId,COUNT(AtId) AS TemplateCount  FROM  #temp_Template WHERE AtId IS NOT NULL GROUP BY BillType,StypeId) A WHERE A.TemplateCount > 1)
BEGIN
	SELECT '-2' AS mgs
	RETURN -2
END

UPDATE B SET ATID = T.AtId 
FROM	BillIndex B
INNER JOIN #temp_billInfo F ON F.billnumberid = B.BillNumberId AND f.billtype = b.BillType
INNER JOIN #temp_Template T ON T.BillType = B.BillType AND T.StypeId = B.Stypeid

UPDATE B SET ATID = T.AtId 
FROM	CommissionBillNew B
INNER JOIN #temp_billInfo F ON F.billnumberid = B.BillNumberId AND f.billtype = b.BillType
INNER JOIN #temp_Template T ON T.BillType = B.BillType AND T.StypeId = B.Stypeid

UPDATE B SET ATID = T.AtId 
FROM	ReceiptBillIndex B
INNER JOIN #temp_billInfo F ON F.billnumberid = B.BillNumberId AND f.billtype = b.BillType
INNER JOIN #temp_Template T ON T.BillType = B.BillType AND T.StypeId = B.Stypeid


SELECT '1' AS mgs
RETURN 1
	 
DROP TABLE #temp_Template,#temp_billInfo
	 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2009-06-02
	描述：盘点处理
	Gp_AutoPanDianDraft 1,'','','00001',''
*/               
CREATE  PROCEDURE Gp_AutoPanDianDraft
(
	@nid		numeric(18,0),
	@startdate	varchar(20),
	@enddate	varchar(20),
	@etypeid	varchar(100),
	@bcode		varchar(8000) output,
	@autocount	INT OUTPUT,
	@isserialcheck	INT=0--是否为序列号盘点0：否1：是
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

DECLARE @STypeID VARCHAR(100)

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid > 200
	BEGIN
		--raiserror('试用版 ！',16,1) 
		RETURN -5
	END
END  

-- ********	判断是否试用版 - END	********

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @etypeid IS NULL RETURN 1

DECLARE @ReX int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @ReX=GP_CheckOperatorRight23_Rep @etypeid,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT


IF @ReX<>0 RETURN @ReX
DECLARE @cid INT,@rate  NUMERIC(24, 10)  
SELECT @cid= CID,@rate=Rate FROM Ac_Currency WHERe Sysrow=1
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@ETypeId)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@ETypeId)

DECLARE @MONTH 				varchar(50),
		@DAY 				varchar(50),
		@BillCodeConfig		varchar(10),
		@BillCode			varchar(300),
		@Re					int,
		@Tax				 NUMERIC(24, 10) ,
		@period				int,
		@DTypeId			varchar(200),
		@nBillId			numeric(18,0),
		@recPrice			 NUMERIC(24, 10) ,
		@preprice			 NUMERIC(24, 10) ,
		@Explain			varchar(400),
		@KTypeId			varchar(200),
		@TotalQty			 NUMERIC(24, 10) ,
		@TmpByBillCode		varchar(8000),
		@TmpBsBillCode		varchar(8000),
		@Comment			varchar(600),
		@Checke				varchar(100),
		@ifWx				int

SET @Tax = 0
SET @recPrice = 0
SET @preprice = 0

--制单人是当前的操作员
SET @Checke = @ETypeId

SET @ETypeId = ''

DECLARE
	@NowDate	DATETIME

SELECT @NowDate=GETDATE()

--特殊处理盘点处理的经手人是盘点单的经手人
SELECT	@ETypeId = ETypeId,@Comment = Comment,@ifWx = ifWx FROM StockCheckIndex WHERE StockCheckId = @nid
IF @@ROWCOUNT = 0
	RETURN -1

IF EXISTS(
	SELECT Qty FROM StockCheck WHERE StockCheckID=@nid AND Qty IS NULL
)
BEGIN
	RETURN -100
END

IF @isserialcheck=1
	SET @Explain = '序列号库存盘点单草稿'
ELSE IF @ifWx = 0
	SET @Explain = '库存盘点单草稿'
ELSE
	SET @Explain = '维修品库存盘点单草稿'

SET @TmpByBillCode = ''
SET @TmpBsBillCode = ''

IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '1')
	SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'

SELECT @period = period FROM MonthProc WHERE MonthNo = '本期'
SELECT @DTypeId = D.TypeId FROM Department D,Employee E WHERE E.Department = D.FullName AND E.TypeId = @ETypeId

SET @MONTH = month(getdate())
SET @DAY = day(getdate())

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

--明细表
CREATE TABLE #Result
(
	PTypeId			varchar(200),
	Qty				 NUMERIC(24, 10) ,
	GoodsNumber		varchar(100),
	ProduceDate		varchar(100),
	ValidDate		varchar(100),
	GoodsCostPrice	varchar(100),
	sID				int,
	nQty			 NUMERIC(24, 10) ,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	Serial			 TEXT NULL,
	StockCheckSerial TEXT NULL
)

CREATE TABLE #ResultMx
(
	nID				int identity(1,1),
	PTypeId			varchar(200),
	Qty				 NUMERIC(24, 10) ,
	GoodsNumber		varchar(100),
	ProduceDate		varchar(100),
	ValidDate		varchar(100),
	GoodsCostPrice	varchar(100),
	sID				int,
	nQty			 NUMERIC(24, 10) ,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	Serial			TEXT NULL,
	StockCheckSerial TEXT NULL
)

CREATE TABLE #overflowBill
(
	NID	int identity(1,1),
	[PtypeId] varchar(50),
	[Qty] numeric(24, 10),
	[GoodsNumber] varchar(100),
	[ProduceDate] varchar(50) ,
	[ValidDate] varchar(50),
	[GoodsCostPrice] numeric(24, 10),
	[GoodsCostTotal] numeric(24, 10),
	[Price] numeric(24, 10),
	[Total] numeric(24, 10),
	STypeID varchar,
	[NQty] numeric(24, 10),
	[ItemID] bigint,
	[IsCombined] INT,
	[CargoID] int,
	[MUnitID] int ,
	NUnitID		int,
	UnitID		int,
	[MUnitRate] numeric,
	[UnitRate] numeric(24, 10),
	MQty	numeric(24, 10),
	[Serial] varchar(max)
) 

CREATE TABLE #LoseBill
(
	NID	int identity(1,1),
	[PtypeId] varchar(50),
	[Qty] numeric(24, 10),
	[GoodsNumber] varchar(100),
	[ProduceDate] varchar(50) ,
	[ValidDate] varchar(50),
	[GoodsCostPrice] numeric(24, 10),
	[GoodsCostTotal] numeric(24, 10),
	[Price] numeric(24, 10),
	[Total] numeric(24, 10),
	STypeID varchar,
	[NQty] numeric(24, 10),
	[ItemID] bigint,
	[IsCombined] INT,
	[CargoID] int,
	[MUnitID] int ,
	NUnitID		int,
	UnitID		int,
	[MUnitRate] numeric,
	[UnitRate] numeric(24, 10),
	MQty	numeric(24, 10),
	[Serial] varchar(max)
) 
--太慢了加索引
CREATE CLUSTERED INDEX #ResultMx_nid ON #ResultMx(nID);
CREATE CLUSTERED INDEX #overflowBill_nid ON #overflowBill(NID);
CREATE CLUSTERED INDEX #LoseBill_nid ON #LoseBill(NID);	
DECLARE @stockcheckid numeric(18,0),
		@RePFullName	VARCHAR(500)

IF @nid<>0
	BEGIN
		SELECT	@KTypeId = KTypeId FROM StockCheckIndex WHERE StockCheckId = @nid
		IF @@ROWCOUNT = 0
			RETURN -1

		--收集数据
		IF EXISTS(select top 1 1 from sysdata where subname = 'costing' 
				and (subvalue = '3' 
						OR 
							SubValue = '0' AND (EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'ifuseproducedate' AND Value = 1) 
												OR EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'ifusevaliddate' AND Value = 1))
					)
				) 	--手工指定法或 移动加权带生产日期/效期至
			BEGIN
				--判断批次是否为空
				CREATE TABLE #StockCheckBill
				(
					RowId	int identity(1,1),
					nID		varchar(100),
					pfullname VARCHAR(100)
				)
				DECLARE @Tip VARCHAR(500)
				
				IF @isserialcheck=1
				BEGIN
						IF EXISTS (select top 1 1 from sysdata where subname = 'costing' AND SubValue = '3')
						BEGIN
							INSERT INTO #StockCheckBill(nID,pfullname) 
							SELECT TOP 1 st.[ID],p.FullName 
							FROM	StockCheck  st 
							LEFT JOIN ptype p ON st.PTypeID=p.typeId
							WHERE	st.StockCheckId = @nid 
									AND st.GoodsCostPrice = -1 
									--AND st.StockQty > st.Qty
									AND st.StockQty > 0
							ORDER BY st.[ID] ASC				
							
							IF @@ROWCOUNT <>0
								BEGIN
									SELECT @stockcheckid = RowId,@RePFullName=pfullname FROM #StockCheckBill ORDER BY RowId ASC
									DROP TABLE #StockCheckBill
									SELECT @autocount=@stockcheckid
									
									SET @Tip = '盘点单明细中的【'+@RePFullName+'】商品，还没有选择批次，请确认后重试！'
									RAISERROR (@Tip,16, 1)
									RETURN @stockcheckid						
								END
						END
						
					
					   
                       
						INSERT INTO #Result
						SELECT	S.PTypeId,
								S.Qty,
								S.GoodsNumber,
								S.ProduceDate,
								S.ValidDate,
								--S.GoodsCostPrice,
						        CASE when s.GoodsCostPrice=-1  THEN 0 ELSE S.GoodsCostPrice END as GoodsCostPrice,
								S.ID,
								s.nQty,
								s.ItemID,
								s.IsCombined,
								s.CargoID,
								sc.Serial,
								sc.StockCheckSerial
						FROM	(
									SELECT	TOP 999999999
											S.PTypeId,
											ISNULL(SUM(S.Qty),0)-ISNULL(SUM(G.Qty),0) AS Qty,
											S.GoodsNumber,
											S.ProduceDate,
											S.ValidDate,
											S.GoodsCostPrice,
											S.ID,
											ISNULL(SUM(S.nqty),0)-ISNULL(SUM(G.nQty),0) AS nQty,
											s.ItemID,
											s.IsCombined,
											s.CargoID
									FROM	StockCheck S
									LEFT JOIN (
												SELECT	a.PTypeId,
														a.GoodsCostPrice AS Price,
														a.ValidDate,
														a.ProduceDate,
														a.GoodsNumber,
														ISNULL(MAX(a.StockQty),0) AS Qty,
														ISNULL(MAX(a.stocknqty),0) AS nQty,
														a.ItemID,
														a.IsCombined,
														a.CargoID
												FROM	StockCheck a
														INNER JOIN StockCheckIndex b	ON a.StockCheckID=b.StockCheckID
												WHERE	b.KTypeId = @KTypeId
														AND b.StockCheckID=@nid
														AND b.KTypeId IN (SELECT * FROM #GetManKTypeId)
														--AND PTypeId IN (SELECT * FROM #GetManPTypeId)
												GROUP BY a.PTypeId,
														a.GoodsCostPrice,
														a.ValidDate,
														a.ProduceDate,
														a.GoodsNumber,
														a.ItemID,
														a.IsCombined,
														a.CargoID
									)G	ON (S.PTypeId = G.PTypeId 
										AND S.GoodsNumber = G.GoodsNumber 
										AND S.ProduceDate = G.ProduceDate AND S.ValidDate = G.ValidDate 
										AND G.Price = S.GoodsCostPrice 
										AND s.ItemID=g.ItemID 
										AND s.IsCombined=g.IsCombined 
										AND s.CargoID=g.CargoID)
									WHERE	S.StockCheckId = @nid
											AND S.StockCheckId IN (SELECT StockCheckId FROM StockCheckIndex WHERE IfWx = @IfWx)
										--AND S.PTypeId IN (SELECT * FROM #GetManPTypeId)
									GROUP BY S.PTypeId,
											 S.GoodsNumber,
				 							 S.ProduceDate,
											 S.ValidDate,
											 S.GoodsCostPrice,
											 S.ID,
											 s.ItemID,
											 s.IsCombined,
											 s.CargoID
								ORDER BY S.ID
						)S LEFT JOIN dbo.StockCheck sc ON sc.Id = s.Id
						
						
						
				END
				
				--写入数据
				ELSE IF @ifWx = 0
					BEGIN
					
						IF EXISTS (select top 1 1 from sysdata where subname = 'costing' AND SubValue = '3')
						BEGIN
							INSERT INTO #StockCheckBill(nID,pfullname) 
							SELECT TOP 1 st.[ID],p.FullName 
							FROM	StockCheck  st 
							LEFT JOIN ptype p ON st.PTypeID=p.typeId
							WHERE	st.StockCheckId = @nid 
									AND st.GoodsCostPrice = -1 
									--AND st.StockQty > st.Qty
									AND st.StockQty > 0
							ORDER BY st.[ID] ASC				
							
							IF @@ROWCOUNT <>0
								BEGIN
									SELECT @stockcheckid = RowId,@RePFullName=pfullname FROM #StockCheckBill ORDER BY RowId ASC
									DROP TABLE #StockCheckBill
									SELECT @autocount=@stockcheckid
									
									SET @Tip = '盘点单明细中的【'+@RePFullName+'】商品，还没有选择批次，请确认后重试！'
									RAISERROR (@Tip,16, 1)
									RETURN @stockcheckid						
								END
						END
						
					

						INSERT INTO #Result
						SELECT	S.PTypeId,
								S.Qty,
								S.GoodsNumber,
								S.ProduceDate,
								S.ValidDate,
								S.GoodsCostPrice,
								S.ID,
								s.nQty,
								s.ItemID,
								s.IsCombined,
								s.CargoID,
								'' as Serial,
								''   as StockCheckSerial
						FROM	(
									SELECT	TOP 999999999
											S.PTypeId,
											ISNULL(SUM(S.Qty),0)-ISNULL(SUM(G.Qty),0) AS Qty,
											S.GoodsNumber,
											S.ProduceDate,
											S.ValidDate,
											S.GoodsCostPrice,
											S.ID,
											ISNULL(SUM(S.nqty),0)-ISNULL(SUM(G.nQty),0) AS nQty,
											s.ItemID,
											s.IsCombined,
											s.CargoID
									FROM	StockCheck S
									LEFT JOIN (
												SELECT	a.PTypeId,
														a.GoodsCostPrice AS Price,
														a.ValidDate,
														a.ProduceDate,
														a.GoodsNumber,
														ISNULL(MAX(a.StockQty),0) AS Qty,
														ISNULL(MAX(a.stocknqty),0) AS nQty,
														a.ItemID,
														a.IsCombined,
														a.CargoID
												FROM	StockCheck a
														INNER JOIN StockCheckIndex b	ON a.StockCheckID=b.StockCheckID
												WHERE	b.KTypeId = @KTypeId
														AND b.StockCheckID=@nid
														AND b.KTypeId IN (SELECT * FROM #GetManKTypeId)
														--AND PTypeId IN (SELECT * FROM #GetManPTypeId)
												GROUP BY a.PTypeId,
														a.GoodsCostPrice,
														a.ValidDate,
														a.ProduceDate,
														a.GoodsNumber,
														a.ItemID,
														a.IsCombined,
														a.CargoID
									)G	ON (S.PTypeId = G.PTypeId 
										AND S.GoodsNumber = G.GoodsNumber 
										AND S.ProduceDate = G.ProduceDate AND S.ValidDate = G.ValidDate 
										AND G.Price = S.GoodsCostPrice 
										AND s.ItemID=g.ItemID 
										AND s.IsCombined=g.IsCombined 
										AND s.CargoID=g.CargoID)
									WHERE	S.StockCheckId = @nid
											AND S.StockCheckId IN (SELECT StockCheckId FROM StockCheckIndex WHERE IfWx = @IfWx)
										--AND S.PTypeId IN (SELECT * FROM #GetManPTypeId)
									GROUP BY S.PTypeId,
											 S.GoodsNumber,
				 							 S.ProduceDate,
											 S.ValidDate,
											 S.GoodsCostPrice,
											 S.ID,
											 s.ItemID,
											 s.IsCombined,
											 s.CargoID
								ORDER BY S.ID
						)S
						
							
						
					END
				ELSE
					BEGIN
					
					    
					    
						INSERT INTO #Result
						SELECT	S.PTypeId,
								S.Qty,
								s.GoodsNumber,
								'' as ProduceDate,
								'' as ValidDate,
								-1 as GoodsCostPrice,
								S.ID,
								s.nQty,
								s.ItemID,
								s.IsCombined,
								0 as CargoID,
								'' as Serial,
								''   as StockCheckSerial
						FROM(
								SELECT	TOP 999999999
										S.PTypeId,
										ISNULL(SUM(S.Qty),0)-ISNULL(SUM(G.Qty),0) AS Qty,
										S.ID,
										ISNULL(SUM(S.nqty),0)-ISNULL(SUM(G.nQty),0) AS nQty,
										s.ItemID,
										s.IsCombined,
										s.GoodsNumber
								FROM	StockCheck S
								LEFT JOIN (
											SELECT	PTypeId,
													ISNULL(SUM(Qty),0) AS Qty,
													ISNULL(SUM(Nqty),0) AS nQty,
													GoodsNumber,
													ProduceDate,
													ValidDate,
													ItemID,
													Iscombined
											FROM	Wx_GoodsStocks
											WHERE	KTypeId = @KTypeId
													AND KTypeId IN (SELECT * FROM #GetManKTypeId)
											GROUP BY PTypeId,GoodsNumber,ProduceDate,ValidDate,ItemID,Iscombined					
								)G ON	S.PTypeId = G.PTypeId 
										AND s.ItemID=g.ItemID 
										AND g.Iscombined=s.IsCombined
										AND g.GoodsNumber=s.GoodsNumber
								WHERE	S.StockCheckId = @nid
										AND S.StockCheckId IN (SELECT StockCheckId FROM StockCheckIndex WHERE IfWx = @IfWx)
								GROUP BY S.PTypeId,
										 S.GoodsNumber,
										 S.ID,
										 s.ItemID,
										 s.IsCombined										 
								ORDER BY S.ID
						)S
					END
			END
		ELSE
			BEGIN
			
			     
				IF @isserialcheck=1
				BEGIN				
				INSERT INTO #Result
					SELECT	S.PTypeId,
							S.Qty,
							s.GoodsNumber as GoodsNumber,
							s.ProduceDate,
							s.ValidDate,
							s.GoodsCostPrice,
							S.ID,
							s.nQty,
							s.ItemID,
							s.IsCombined,
							s.CargoID,
							
							sc.Serial,
							sc.StockCheckSerial
					FROM	(
							SELECT	TOP 999999999
									S.PTypeId,
									ISNULL(SUM(S.Qty),0)-ISNULL(SUM(G.Qty),0) AS Qty,
									S.ProduceDate,
									S.ValidDate,
									s.GoodsCostPrice,
									S.ID,
									ISNULL(SUM(S.nqty),0)-ISNULL(SUM(G.nQty),0) AS nQty,
									s.ItemID,
									s.IsCombined,
									s.CargoID,
									s.GoodsNumber
								  
							FROM	StockCheck S
							LEFT JOIN (
								SELECT	a.PTypeId,
										ISNULL(MAX(a.StockQty),0) AS Qty,
										a.ProduceDate,
										a.ValidDate,
										a.GoodsCostPrice,
										a.ID,
										ISNULL(MAX(a.stocknqty),0) AS nQty,
										a.ItemID,
										a.IsCombined,
										a.CargoID,
										a.GoodsNumber
								FROM	StockCheck a
								INNER JOIN StockCheckIndex b ON a.StockCheckID=b.StockCheckID
								WHERE	b.KTypeId = @KTypeId
										AND b.StockCheckID=@nid
										AND b.KTypeId IN (SELECT typeid FROM #GetManKTypeId)
										--AND PTypeId IN (SELECT * FROM #GetManPTypeId)
								GROUP BY a.PTypeId,a.ItemID,a.IsCombined,a.CargoID,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsCostPrice,a.ID				
							)G ON S.PTypeId = G.PTypeId AND g.ItemID=s.ItemID AND g.IsCombined=s.IsCombined AND g.CargoID=s.CargoID AND G.GoodsNumber=s.GoodsNumber
							WHERE	S.StockCheckId = @nid
									AND S.StockCheckId IN (SELECT StockCheckId FROM StockCheckIndex WHERE IfWx = @IfWx)
									--AND S.PTypeId IN (SELECT * FROM #GetManPTypeId)
							GROUP BY S.PTypeId,
									S.ID,
									s.ItemID,
									s.IsCombined,
									s.CargoID,
									s.GoodsNumber,
									s.ProduceDate,
									s.ValidDate,
									s.GoodsCostPrice
								  
							ORDER BY S.ID
					)S LEFT JOIN dbo.StockCheck sc ON sc.Id = s.Id
					
					
				END
				ELSE IF @ifWx = 0
				 BEGIN
				 
					INSERT INTO #Result
					SELECT	S.PTypeId,
							S.Qty,
							s.GoodsNumber as GoodsNumber,
							'' as ProduceDate,
							'' as ValidDate,
							-1 as GoodsCostPrice,
							S.ID,
							s.nQty,
							s.ItemID,
							s.IsCombined,
							s.CargoID,
							sc.Serial,
							sc.StockCheckSerial
					FROM	(
							SELECT	TOP 999999999
									S.PTypeId,
									ISNULL(SUM(S.Qty),0)-ISNULL(SUM(G.Qty),0) AS Qty,
									S.ID,
									ISNULL(SUM(S.nqty),0)-ISNULL(SUM(G.nQty),0) AS nQty,
									s.ItemID,
									s.IsCombined,
									s.CargoID,
									s.GoodsNumber
							FROM	StockCheck S
							LEFT JOIN (
								SELECT	a.PTypeId,
										ISNULL(MAX(a.StockQty),0) AS Qty,
										ISNULL(MAX(a.stocknqty),0) AS nQty,
										a.ItemID,
										a.IsCombined,
										a.CargoID,
										a.GoodsNumber
								FROM	StockCheck a
								INNER JOIN StockCheckIndex b ON a.StockCheckID=b.StockCheckID
								WHERE	b.KTypeId = @KTypeId
										AND b.StockCheckID=@nid
										AND b.KTypeId IN (SELECT * FROM #GetManKTypeId)
										--AND PTypeId IN (SELECT * FROM #GetManPTypeId)
								GROUP BY a.PTypeId,a.ItemID,a.IsCombined,a.CargoID,a.GoodsNumber					
							)G ON S.PTypeId = G.PTypeId AND g.ItemID=s.ItemID AND g.IsCombined=s.IsCombined AND g.CargoID=s.CargoID AND G.GoodsNumber=s.GoodsNumber
							WHERE	S.StockCheckId = @nid
									AND S.StockCheckId IN (SELECT StockCheckId FROM StockCheckIndex WHERE IfWx = @IfWx)
									--AND S.PTypeId IN (SELECT * FROM #GetManPTypeId)
							GROUP BY S.PTypeId,
									S.ID,
									s.ItemID,
									s.IsCombined,
									s.CargoID,
									s.GoodsNumber
							ORDER BY S.ID
					)S LEFT JOIN dbo.StockCheck sc ON sc.Id = s.Id
				 END
				 
				ELSE
				BEGIN
					INSERT INTO #Result
					SELECT	S.PTypeId,
							S.Qty,
							s.GoodsNumber as GoodsNumber,
							'' as ProduceDate,
							'' as ValidDate,
							-1 as GoodsCostPrice,
							S.ID,
							s.nQty,
							s.ItemID,
							s.Iscombined,
							0 as cargoid,
							'' as Serial,
							''   as StockCheckSerial
					FROM	(
							SELECT	TOP 999999999
									S.PTypeId,
									ISNULL(ISNULL(SUM(S.Qty)-SUM(S.StockQty),0),0) AS Qty,
									S.ID,
									ISNULL(ISNULL(SUM(S.Nqty)-SUM(S.stocknqty),0),0) AS nQty,
									s.ItemID,
									s.IsCombined,
									s.GoodsNumber
							FROM	StockCheck S
							--LEFT JOIN (
							--	SELECT	PTypeId,
							--			ISNULL(SUM(Qty),0) AS Qty,
							--			ISNULL(SUM(Nqty),0) AS Nqty,
							--			ItemID,
							--			IsCombined,
							--			GoodsNumber
							--	FROM	Wx_GoodsStocks
							--	WHERE	KTypeId = @KTypeId
							--			AND KTypeId IN (SELECT * FROM #GetManKTypeId)
							--			--AND PTypeId IN (SELECT * FROM #GetManPTypeId)
							--	GROUP BY PTypeId,ItemID,Iscombined,GoodsNumber					
							--)G ON S.PTypeId = G.PTypeId AND s.ItemID=g.ItemID AND s.IsCombined=g.Iscombined AND s.GoodsNumber=g.GoodsNumber
							WHERE	S.StockCheckId = @nid
									AND S.StockCheckId IN (SELECT StockCheckId FROM StockCheckIndex WHERE IfWx = @IfWx)
									--AND S.PTypeId IN (SELECT * FROM #GetManPTypeId)
							GROUP BY S.PTypeId,
									 S.ID,
									 S.GoodsNumber,
									 s.ItemID,
									 s.IsCombined			
							ORDER BY S.ID
					)S
				END	
			END
		DECLARE @BillCount 			int,
				@bCount				int,
				@i					int,
				@datBillDate	DATETIME,
				@cefullname			VARCHAR(500)=''
				
		SELECT @datBillDate=CONVERT(varchar(10),GetDate(),120)		
	
		DECLARE @int INT=0, @SERIAL VARCHAR(max),@STOCKCHECKSERIAL VARCHAR(max),@SerialResultBy VARCHAR(max)='',@SerialResultBs VARCHAR(max)=''
			
		
		
		IF @isserialcheck=1
		BEGIN
			INSERT INTO #ResultMx SELECT * FROM #Result
		
	        WHILE @int<(SELECT COUNT(nid) FROM #ResultMx)
			BEGIN
			
				SELECT @SERIAL=Serial,@STOCKCHECKSERIAL=StockCheckSerial FROM #ResultMx a WHERE a.nID=@int+1
					
				--筛选合并序列号
				SELECT DISTINCT @SerialResultBy=stuff((select 'я' + a from 
				(SELECT a FROM dbo.f_split(@STOCKCHECKSERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(@SERIAL,'я'))) b
				where a = a for xml path('')),1,1,'')
				 FROM (SELECT a FROM dbo.f_split(@STOCKCHECKSERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(@SERIAL,'я'))) c

				--筛选合并序列号
				SELECT DISTINCT @SerialResultBs=stuff((select 'я' + a from 
				(SELECT a FROM dbo.f_split(@SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(@STOCKCHECKSERIAL,'я'))) b
				where a = a for xml path('')),1,1,'')
				 FROM (SELECT a FROM dbo.f_split(@SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(@STOCKCHECKSERIAL,'я'))) c
				
				INSERT INTO #overflowBill
					( 
						PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,GoodsCostTotal,Price,Total,STypeID,NQty,ItemID,IsCombined,CargoID,
						MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,Serial
					)
				SELECT	a.PTypeId,
						case when pt.ifserial=1 then (SELECT COUNT(*) FROM dbo.f_split(@SerialResultBy,'я') c WHERE c.a<>'')
							else a.Qty end as qty,
						a.GoodsNumber,
						a.ProduceDate,
						a.ValidDate,
						a.GoodsCostPrice,
						case when pt.ifserial=1 then  ABS(a.GoodsCostPrice)*(SELECT COUNT(*) FROM dbo.f_split(@SerialResultBY,'я') c WHERE c.a<>'')
						else 0 end as GoodsCostTotal ,
						a.GoodsCostPrice,
						case when pt.ifserial=1 then  ABS(a.GoodsCostPrice)*(SELECT COUNT(*) FROM dbo.f_split(@SerialResultBY,'я') c WHERE c.a<>'')
						else 0  end as Total ,
						@STypeID,
						ABS(a.nQty),
						ItemID,
						IsCombined,
						cargoid,
						p.StockUnitId,
						p.nunitid,
						p.unitid,
						p.stockmunitrate,
						CASE when a.nQty=0  THEN 0 else (ABS(a.Qty)/ABS(a.nQty)) END,
						case when pt.ifserial=1 then ABS((SELECT COUNT(*) FROM dbo.f_split(@SerialResultBy,'я') c WHERE c.a<>''))/p.stockmunitrate 
						else  ABS(a.Qty)/p.stockmunitrate  end as mqty,
						(SELECT DISTINCT stuff((select 'я' + a from 
						(SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(SERIAL,'я'))) b
						 where a = a for xml path('')),1,1,'')
						FROM (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(SERIAL,'я'))) c) as SerialResultBy		
				FROM 	#ResultMx a
						INNER JOIN F_GetPtypeUnitInfo() p On a.PTypeId=p.typeId
						inner join ptype pt on a.ptypeid=pt.typeid
				WHERE   a.nID=@int+1 AND 
				( (pt.ifserial=1 and (ABS((SELECT COUNT(*) FROM dbo.f_split(@SerialResultBy,'я') c WHERE c.a<>''))/p.stockmunitrate )!=0)
					or
					(pt.ifserial=0 and a.qty>0)
				
		  		)	
		  				
				INSERT INTO #LoseBill
				( 
					PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,GoodsCostTotal,Price,Total,STypeID,NQty,ItemID,IsCombined,CargoID,
					MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,Serial
				)
				SELECT	a.PTypeId,
						case when pt.ifserial=1 then  (SELECT COUNT(*) FROM dbo.f_split((SELECT DISTINCT stuff((select 'я' + a from 
						(SELECT a FROM dbo.f_split(SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я'))) b
						 where a = a for xml path('')),1,1,'')
						FROM (SELECT a FROM dbo.f_split(SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я'))) c),'я') c WHERE c.a<>'')
						else ABS(a.Qty) end as qty,
						a.GoodsNumber,
						a.ProduceDate,
						a.ValidDate,
						a.GoodsCostPrice,
						case when pt.ifserial=1 then ABS(a.GoodsCostPrice)*(SELECT COUNT(*) FROM dbo.f_split(@SerialResultBs,'я') c WHERE c.a<>'')
						else 0 end as GoodsCostTotal,
						a.GoodsCostPrice,
						case when pt.ifserial=1 then ABS(a.GoodsCostPrice)*(SELECT COUNT(*) FROM dbo.f_split(@SerialResultBs,'я') c WHERE c.a<>'')
						else 0 end as Total,
						@STypeID,
						ABS(a.nQty),
						ItemID,
						IsCombined,
						cargoid,
						p.StockUnitId,
						p.nunitid,
						p.unitid,
						p.stockmunitrate,
						CASE when a.nQty=0  THEN 0 else (ABS(a.Qty)/abs(a.nQty)) END,--p.unitrate,
						case when pt.ifserial=1 then ABS((SELECT COUNT(*) FROM dbo.f_split((SELECT DISTINCT stuff((select 'я' + a from 
						(SELECT a FROM dbo.f_split(SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я'))) b
						 where a = a for xml path('')),1,1,'')
						FROM (SELECT a FROM dbo.f_split(SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я'))) c),'я') c WHERE c.a<>''))/p.stockmunitrate 
						else ABS(a.Qty)/p.stockmunitrate end as mqty,
						(SELECT DISTINCT stuff((select 'я' + a from 
						(SELECT a FROM dbo.f_split(SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я'))) b
						 where a = a for xml path('')),1,1,'')
						FROM (SELECT a FROM dbo.f_split(SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я'))) c) as SerialResultBs	 
				FROM 	#ResultMx a
						INNER JOIN F_GetPtypeUnitInfo() p On a.PTypeId=p.typeId
						inner join ptype pt on a.ptypeid=pt.typeid
				WHERE   a.nID=@int+1 AND 
						((pt.ifserial=1 and
							(ABS((SELECT COUNT(*) FROM dbo.f_split((SELECT DISTINCT stuff((select 'я' + a from 
							(SELECT a FROM dbo.f_split(SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я'))) b
							 where a = a for xml path('')),1,1,'')
							FROM (SELECT a FROM dbo.f_split(SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(STOCKCHECKSERIAL,'я'))) c),'я') c WHERE c.a<>''))/p.stockmunitrate)!=0
							)
							or
						((pt.ifserial=0 and a.qty<0)
						)
						)
				SET @int=@int+1
			END
			
			SELECT * FROM #LoseBill
			SELECT * FROM #overflowBill
			--RETURN
			
			IF EXISTS(SELECT top 1 1 FROM #overflowBill)
			BEGIN
			        SELECT @bCount = COUNT(*) FROM #overflowBill
			   IF @bCount % 150 = 0
						SET @BillCount = @bCount / 150
					ELSE
						SET @BillCount = @bCount / 150 + 1

					SET @i =  1
					
					--select'2', @bCount, @BillCount
				WHILE @i<=@BillCount
				BEGIN	
			
			
			
					--生成单据编号
					IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 14) AND @BillCodeConfig = '1'
						BEGIN
							SELECT @MONTH = ''
							SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
							SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @Checke
						END
					SELECT @STypeID=STypeID FROM Stock
					WHERE typeId=@KTypeId
					
					EXEC @Re=Gp_GetBillCode 14, @MONTH,@DAY,'BY',@datBillDate,@STypeID,@BillCode OUTPUT,'',@cefullname
					
					IF @Re <> 0
						RETURN -2
						
					--写入单据主表
					INSERT INTO BillIndex (checktime,AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,
											btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,
											totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,
											waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,
											Comment,IfWx,Stypeid,CID,vipCZMoney,NTotalInMoney,NTotalMoney,NPreferenceMoney,NVIPCZMoney,Rate)
					VALUES(GETDATE(),9999,@datBillDate,@BillCode,14,'','','','',@ktypeid,'','f',@Checke,0,0,0,
							@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@Comment,@IfWx,@STypeID,@cid,
							0,0,0,0,0,@rate)
					
					IF @@ROWCOUNT = 0
					BEGIN
						RETURN -3
					END
					ELSE
					BEGIN
						SET @nBillId = SCOPE_IDENTITY();
					END
					
					IF EXISTS(
						SELECT ConfigNo
						FROM Userconfig
						WHERE ConfigName='BillcodeCreateTime'
						AND Value=0
					)
					BEGIN
						EXEC GP_SaveBillCode_Seed
						@nBillId,
						@datBillDate,
						14,
						@BillCode
					END
					
					--插入明细表
					INSERT INTO OverFlowBill(BillNumberId,PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,
							GoodsCostPrice,GoodsCostTotal,Price,Total,STypeID,NQty,ItemID,IsCombined,CargoID,
							MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,Serial,KTypeId,IfWx)
					SELECT	@nBillId AS BillNumberId,
							a.PTypeId,
							a.Qty,
							a.GoodsNumber,
							a.ProduceDate,
							a.ValidDate,
							a.GoodsCostPrice,
							a.GoodsCostTotal,
							a.Price,
							a.Total,
							@STypeID,
							a.NQty,
							a.ItemID,
							a.IsCombined,
							a.CargoID,
							a.MUnitID,
							a.NUnitID,
							a.UnitID,
							a.MUnitRate,
							a.UnitRate,
							a.MQty,
							a.Serial,
							@ktypeid,
							@IfWx
					FROM 	#overflowBill a
					inner join ptype p on p.typeid =a.ptypeid
					WHERE 	 a.nid > (@i-1)*150 
					   AND a.nid <=@i*150 and 
					( (p.ifserial=1 and  ISNULL(a.Serial,'')!='')
						or p.ifserial=0
						)
			  				
			  		
					--设置排序号
					UPDATE dbo.overflowBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
					
					--修改BillIndex的TotalMoney
					SELECT @TotalQty = SUM(Qty) FROM OverFlowBill WHERE BillNumberId = @nBillId
					UPDATE BillIndex SET TotalQty = @TotalQty,ifWx = @ifWx WHERE BillNumberId = @nBillId
	
					--返回单据编号
					SELECT @TmpByBillCode = @TmpByBillCode + 'я' + ISNULL(BillCode,' ') FROM BillIndex WHERE BillNumberId = @nBillId	
					
					--自定义继承（主表）
					INSERT INTO Custom_BillIndex
					(
					  [BillId],[BillType],[SysDiy1_head],[SysDiy2_head],[SysDiy3_head]
					  ,[SysDiy4_head],[SysDiy5_head],[SysDiy6_head],[SysDiy7_head]
					  ,[SysDiy8_head],[SysDiy9_head],[SysDiy10_head],[SysDiy11_head]
					  ,[SysDiy12_head],[SysDiy13_head],[SysDiy14_head],[SysDiy15_head],[SysDiy16_head]
					)
					SELECT @nBillId,14,[SysDiy1_head],[SysDiy2_head],[SysDiy3_head]
					  ,[SysDiy4_head],[SysDiy5_head],[SysDiy6_head],[SysDiy7_head]
					  ,[SysDiy8_head],[SysDiy9_head],[SysDiy10_head],[SysDiy11_head]
					  ,[SysDiy12_head],[SysDiy13_head],[SysDiy14_head],[SysDiy15_head],[SysDiy16_head]
					FROM [Custom_BillIndex] WHERE BillId=@nid and billtype=306
					
					--自定义继承（明细）
					INSERT INTO Custom_BillDetails
					(
						[BillId],[Detailid],[BillType],[SysDiy1],[SysDiy2],[SysDiy3],[SysDiy4]
						,[SysDiy5],[SysDiy6],[SysDiy7],[SysDiy8],[SysDiy9],[SysDiy10]
						,[SysDiy11],[SysDiy12],[SysDiy13],[SysDiy14],[SysDiy15],[SysDiy16]
					)
					SELECT @nBillId,t.id,14,c.[SysDiy1],c.[SysDiy2],c.[SysDiy3],c.[SysDiy4]
				  ,c.[SysDiy5],c.[SysDiy6],c.[SysDiy7],c.[SysDiy8],c.[SysDiy9],c.[SysDiy10]
				  ,c.[SysDiy11],c.[SysDiy12],c.[SysDiy13],c.[SysDiy14],c.[SysDiy15],c.[SysDiy16]
				  FROM [Custom_BillDetails] C LEFT JOIN
				  (
					SELECT o.ID,s.stockcheckid,s.id as stockdetailid FROM OVERFLOWBILL o INNER JOIN StockCheck s 
					ON o.ptypeid=s.ptypeid WHERE s.stockcheckid=@nid AND o.billnumberid=@nBillId
				  ) t ON C.detailid=t.stockdetailid
				  WHERE BillId=@nid and billtype=306
					  
				IF @@error<>0 
				BEGIN
					RETURN -2
				END 
		     	SET @i = @i + 1
				-- 自动生成的单据会影响草稿库存
				EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,14				
			END
			END
			
			SET @MONTH = month(getdate())
			SET @DAY = day(getdate())
				   
			IF EXISTS(SELECT top 1 1  FROM #LoseBill)
			BEGIN
			   SELECT @bCount = COUNT(*) FROM #LoseBill
			   IF @bCount % 150 = 0
						SET @BillCount = @bCount / 150
					ELSE
						SET @BillCount = @bCount / 150 + 1

					SET @i =  1
					
					--select'2', @bCount, @BillCount
				WHILE @i<=@BillCount
				BEGIN	
				--生成单据编号
				IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 9) AND @BillCodeConfig = '1'
					BEGIN
						SELECT @MONTH = ''
						SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
						SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @Checke
					END
				SELECT @STypeID=STypeID
				FROM STOCK
				WHERE typeId=@KTypeId
				
				SET @BillCode = ''
				EXEC @Re=Gp_GetBillCode 9, @MONTH,@DAY,'BS',@datBillDate,@STypeID,@BillCode OUTPUT,'',@cefullname
				IF @Re <> 0
					RETURN -2	

				--写入单据主表
				INSERT INTO BillIndex (checktime,AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,
										btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,
										totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,
										waybillcode,packway,TEL,IfAudit,preferencemoney,
										DTypeId,Explain,Comment,IfWx,Stypeid,CID,vipCZMoney,NTotalInMoney,NTotalMoney,NPreferenceMoney,NVIPCZMoney,Rate)
				VALUES(GETDATE(),9999,@datBillDate,@BillCode,9,'','','','',@ktypeid,'','f',@Checke,0,0,0,
						@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@Comment,@IfWx,@STypeID,@cid,
						0,0,0,0,0,@rate)
				
				IF @@ROWCOUNT = 0
				BEGIN
					RETURN -3
				END
				ELSE
					SET @nBillId = SCOPE_IDENTITY();
					
				IF EXISTS(
					SELECT ConfigNo
					FROM Userconfig
					WHERE ConfigName='BillcodeCreateTime'
					AND Value=0
				)
				BEGIN
					EXEC GP_SaveBillCode_Seed
					@nBillId,
					@datBillDate,
					9,
					@BillCode
				END

				--插入明细表
				INSERT INTO LoseBill(BillNumberId,PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,GoodsCostTotal,Price,Total,STypeID,NQty,ItemID,IsCombined,CargoID,
						MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,Serial,KTypeId,IfWx)
				SELECT	@nBillId AS BillNumberId,
						a.PTypeId,
						a.Qty,
						a.GoodsNumber,
						a.ProduceDate,
						a.ValidDate,
						a.GoodsCostPrice,
						a.GoodsCostTotal,
						a.Price,
						a.Total,
						@STypeID,
						a.NQty,
						a.ItemID,
						a.IsCombined,
						a.CargoID,
						a.MUnitID,
						a.NUnitID,
						a.UnitID,
						a.MUnitRate,
						a.UnitRate,
						a.MQty,
						a.Serial,
						@ktypeid,
						@IfWx
				FROM 	#LoseBill a
				inner join ptype p on p.typeid =a.ptypeid
			WHERE  a.nid > (@i-1)*150 
					   AND a.nid <=@i*150 and 
						( (p.ifserial=1 and  ISNULL(a.Serial,'')!='')
						or p.ifserial=0
						)
				
				UPDATE dbo.LoseBill SET ShowOrder=ID WHERE BillNumberId=@nBillID
				--修改BillIndex的TotalMoney
				SELECT @TotalQty = SUM(Qty) FROM LoseBill WHERE BillNumberId = @nBillId
				UPDATE BillIndex SET TotalQty = @TotalQty,ifWx = @ifWx WHERE BillNumberId = @nBillId

				--返回单据编号
				SELECT @TmpBsBillCode = @TmpBsBillCode + 'я' + ISNULL(BillCode,' ') FROM BillIndex WHERE BillNumberId = @nBillId	

				--自定义继承（主表）
				INSERT INTO Custom_BillIndex
				(
				  [BillId],[BillType],[SysDiy1_head],[SysDiy2_head],[SysDiy3_head]
				  ,[SysDiy4_head],[SysDiy5_head],[SysDiy6_head],[SysDiy7_head]
				  ,[SysDiy8_head],[SysDiy9_head],[SysDiy10_head],[SysDiy11_head]
				  ,[SysDiy12_head],[SysDiy13_head],[SysDiy14_head],[SysDiy15_head],[SysDiy16_head]
				)
				SELECT @nBillId,9,[SysDiy1_head],[SysDiy2_head],[SysDiy3_head]
				  ,[SysDiy4_head],[SysDiy5_head],[SysDiy6_head],[SysDiy7_head]
				  ,[SysDiy8_head],[SysDiy9_head],[SysDiy10_head],[SysDiy11_head]
				  ,[SysDiy12_head],[SysDiy13_head],[SysDiy14_head],[SysDiy15_head],[SysDiy16_head]
				FROM [Custom_BillIndex] WHERE BillId=@nid  and billtype=306
				
				--自定义继承（明细）
				INSERT INTO Custom_BillDetails
				(
					[BillId],[Detailid],[BillType],[SysDiy1],[SysDiy2],[SysDiy3],[SysDiy4]
					,[SysDiy5],[SysDiy6],[SysDiy7],[SysDiy8],[SysDiy9],[SysDiy10]
					,[SysDiy11],[SysDiy12],[SysDiy13],[SysDiy14],[SysDiy15],[SysDiy16]
				)
				SELECT @nBillId,t.id,9,c.[SysDiy1],c.[SysDiy2],c.[SysDiy3],c.[SysDiy4]
			  ,c.[SysDiy5],c.[SysDiy6],c.[SysDiy7],c.[SysDiy8],c.[SysDiy9],c.[SysDiy10]
			  ,c.[SysDiy11],c.[SysDiy12],c.[SysDiy13],c.[SysDiy14],c.[SysDiy15],c.[SysDiy16]
			  FROM [Custom_BillDetails] C LEFT JOIN
			  (
				SELECT o.ID,s.stockcheckid,s.id as stockdetailid FROM LoseBill o INNER JOIN StockCheck s 
				ON o.ptypeid=s.ptypeid WHERE s.stockcheckid=@nid AND o.billnumberid=@nBillId
			  ) t ON C.detailid=t.stockdetailid
			  WHERE BillId=@nid and billtype=306
				  
				IF @@error<>0 
				BEGIN
					RETURN -2
				END	
				SET @i = @i + 1
				-- 自动生成的单据会影响草稿库存
				EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,9
			END	
			END
		END
		ELSE
		BEGIN
		
			TRUNCATE TABLE #ResultMx

		    INSERT INTO #ResultMx SELECT * FROM #Result
		 
		
			--报溢单
			IF EXISTS(SELECT TOP 1 1 FROM #Result WHERE Qty>0)
				BEGIN
					TRUNCATE TABLE #ResultMx
					INSERT INTO #ResultMx SELECT * FROM #Result WHERE Qty>0
					
					SELECT @bCount = COUNT(*) FROM #Result WHERE Qty>0

					IF @bCount % 150 = 0
						SET @BillCount = @bCount / 150
					ELSE
						SET @BillCount = @bCount / 150 + 1

					SET @i =  1					
					
					WHILE @i<=@BillCount
						BEGIN
							--生成单据编号
							IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 14) AND @BillCodeConfig = '1'
								BEGIN
									SELECT @MONTH = ''
									SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
									SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @Checke
								END
							SELECT @STypeID=STypeID FROM Stock
							WHERE typeId=@KTypeId
							
							EXEC @Re=Gp_GetBillCode 14, @MONTH,@DAY,'BY',@datBillDate,@STypeID,@BillCode OUTPUT,'',@cefullname
							
							IF @Re <> 0
							BEGIN
								RETURN -2	
							END	
							
								
							--写入单据主表
							INSERT INTO BillIndex (checktime,AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,
													btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,
													totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,
													waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,
													Comment,IfWx,Stypeid,CID,vipCZMoney,NTotalInMoney,NTotalMoney,NPreferenceMoney,NVIPCZMoney,Rate)
							VALUES(GETDATE(),9999,@datBillDate,@BillCode,14,'','','','',@ktypeid,'','f',@Checke,0,0,0,
									@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@Comment,@IfWx,@STypeID,@cid,
									0,0,0,0,0,@rate)
							
							IF @@ROWCOUNT = 0
							BEGIN
								RETURN -3
							END
							ELSE
								SET @nBillId = SCOPE_IDENTITY();
								
							IF EXISTS(
								SELECT ConfigNo
								FROM Userconfig
								WHERE ConfigName='BillcodeCreateTime'
								AND Value=0
							)
							BEGIN
								EXEC GP_SaveBillCode_Seed
								@nBillId,
								@datBillDate,
								14,
								@BillCode
							END
							
							--插入明细表
							INSERT INTO OverFlowBill(BillNumberId,PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,
									GoodsCostPrice,STypeID,NQty,ItemID,IsCombined,CargoID,
									MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,KTypeId,IfWx)
							SELECT	@nBillId AS BillNumberId,
									a.PTypeId,
									a.Qty,
									a.GoodsNumber,
									a.ProduceDate,
									a.ValidDate,
									a.GoodsCostPrice,
									@STypeID,
									ABS(a.nQty),
									ItemID,
									IsCombined,
									cargoid,
									p.StockUnitId,
									p.nunitid,
									p.unitid,
									p.stockmunitrate,
									CASE when a.nQty=0  THEN 0 else (ABS(a.Qty)/ABS(a.nQty)) END,--p.unitrate,
									ABS(a.Qty)/p.stockmunitrate as mqty,
									@ktypeid,
									@IfWx
							FROM 	#ResultMx a
									INNER JOIN F_GetPtypeUnitInfo() p On a.PTypeId=p.typeId
							WHERE 	a.Qty > 0
							  		AND a.nid > (@i-1)*150 
							  		AND a.nid <=@i*150
							 
							--设置排序号
							UPDATE dbo.overflowBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
							
							--修改BillIndex的TotalMoney
							SELECT @TotalQty = SUM(Qty) FROM OverFlowBill WHERE BillNumberId = @nBillId
							UPDATE BillIndex SET TotalQty = @TotalQty,ifWx = @ifWx WHERE BillNumberId = @nBillId
			
							--返回单据编号
							SELECT @TmpByBillCode = @TmpByBillCode + 'я' + ISNULL(BillCode,' ') FROM BillIndex WHERE BillNumberId = @nBillId	
							
							--自定义继承（主表）
							INSERT INTO Custom_BillIndex
							(
							  [BillId],[BillType],[SysDiy1_head],[SysDiy2_head],[SysDiy3_head]
							  ,[SysDiy4_head],[SysDiy5_head],[SysDiy6_head],[SysDiy7_head]
							  ,[SysDiy8_head],[SysDiy9_head],[SysDiy10_head],[SysDiy11_head]
							  ,[SysDiy12_head],[SysDiy13_head],[SysDiy14_head],[SysDiy15_head],[SysDiy16_head]
							)
							SELECT @nBillId,14,[SysDiy1_head],[SysDiy2_head],[SysDiy3_head]
							  ,[SysDiy4_head],[SysDiy5_head],[SysDiy6_head],[SysDiy7_head]
							  ,[SysDiy8_head],[SysDiy9_head],[SysDiy10_head],[SysDiy11_head]
							  ,[SysDiy12_head],[SysDiy13_head],[SysDiy14_head],[SysDiy15_head],[SysDiy16_head]
							FROM [Custom_BillIndex] WHERE BillId=@nid and billtype=306
							
							--自定义继承（明细）
							INSERT INTO Custom_BillDetails
							(
								[BillId],[Detailid],[BillType],[SysDiy1],[SysDiy2],[SysDiy3],[SysDiy4]
								,[SysDiy5],[SysDiy6],[SysDiy7],[SysDiy8],[SysDiy9],[SysDiy10]
								,[SysDiy11],[SysDiy12],[SysDiy13],[SysDiy14],[SysDiy15],[SysDiy16]
							)
							SELECT @nBillId,t.id,14,c.[SysDiy1],c.[SysDiy2],c.[SysDiy3],c.[SysDiy4]
							  ,c.[SysDiy5],c.[SysDiy6],c.[SysDiy7],c.[SysDiy8],c.[SysDiy9],c.[SysDiy10]
							  ,c.[SysDiy11],c.[SysDiy12],c.[SysDiy13],c.[SysDiy14],c.[SysDiy15],c.[SysDiy16]
							  FROM [Custom_BillDetails] C LEFT JOIN
							  (
								SELECT o.ID,s.stockcheckid,s.id as stockdetailid FROM OVERFLOWBILL o INNER JOIN StockCheck s 
								ON o.ptypeid=s.ptypeid WHERE s.stockcheckid=@nid AND o.billnumberid=@nBillId
							  ) t ON C.detailid=t.stockdetailid
							  WHERE BillId=@nid  and billtype=306
						  
							IF @@error<>0 
								BEGIN
									RETURN -2
								END 	

							SET @i = @i + 1
							
							-- 自动生成的单据会影响草稿库存
							EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,14							
						END		
				END

			SET @MONTH = month(getdate())
			SET @DAY = day(getdate())

			--报损单
			IF EXISTS(SELECT TOP 1 1 FROM #Result WHERE Qty<0)
				BEGIN
					TRUNCATE TABLE #ResultMx

					INSERT INTO #ResultMx SELECT * FROM #Result WHERE Qty<0

					SELECT @bCount = COUNT(*) FROM #ResultMx WHERE Qty<0

					IF @bCount % 150 = 0
						SET @BillCount = @bCount / 150
					ELSE
						SET @BillCount = @bCount / 150 + 1

					SET @i =  1
					
					WHILE @i<=@BillCount
						BEGIN
							--生成单据编号
							IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 9) AND @BillCodeConfig = '1'
								BEGIN
									SELECT @MONTH = ''
									SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
									SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @Checke
								END
							SELECT @STypeID=STypeID
							FROM STOCK
							WHERE typeId=@KTypeId
							
							SET @BillCode = ''
							EXEC @Re=Gp_GetBillCode 9, @MONTH,@DAY,'BS',@datBillDate,@STypeID,@BillCode OUTPUT,'',@cefullname
							IF @Re <> 0
							BEGIN
								RETURN -2	
							END
			
							--写入单据主表 SELECT* FROM billindex where billnumberid=5
							INSERT INTO BillIndex (checktime,AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,
													btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,
													totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,
													waybillcode,packway,TEL,IfAudit,preferencemoney,
													DTypeId,Explain,Comment,IfWx,Stypeid,CID,vipCZMoney,NTotalInMoney,NTotalMoney,NPreferenceMoney,NVIPCZMoney,Rate)
							VALUES(GETDATE(),9999,@datBillDate,@BillCode,9,'','','','',@ktypeid,'','f',@Checke,0,0,0,
									@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@Comment,@IfWx,@STypeID,@cid,
									0,0,0,0,0,@rate)
						
							IF @@ROWCOUNT = 0
							BEGIN
								RETURN -3
							END
							ELSE
								SET @nBillId = SCOPE_IDENTITY();
								
							IF EXISTS(
								SELECT ConfigNo
								FROM Userconfig
								WHERE ConfigName='BillcodeCreateTime'
								AND Value=0
							)
							BEGIN
								EXEC GP_SaveBillCode_Seed
								@nBillId,
								@datBillDate,
								9,
								@BillCode
							END
			
							--插入明细表
							INSERT INTO LoseBill(BillNumberId,PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,STypeID,NQty,ItemID,IsCombined,CargoID,
									MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,KTypeId,IfWx)
							SELECT	@nBillId AS BillNumberId,
									a.PTypeId,
									ABS(a.Qty),
									a.GoodsNumber,
									a.ProduceDate,
									a.ValidDate,
									a.GoodsCostPrice,
									@STypeID,
									ABS(a.nQty),
									ItemID,
									IsCombined,
									cargoid,
									p.StockUnitId,
									p.nunitid,
									p.unitid,
									p.stockmunitrate,
									CASE when a.nQty=0  THEN 0 else (ABS(a.Qty)/abs(a.nQty)) END,--p.unitrate,
									ABS(a.Qty)/p.stockmunitrate as mqty,
									@ktypeid,
									@IfWx
							FROM 	#ResultMx a
									INNER JOIN F_GetPtypeUnitInfo() p On a.PTypeId=p.typeId
							WHERE 	a.Qty < 0
							  		AND a.nid > (@i-1)*150 
							  		AND a.nid <=@i*150
							
							UPDATE dbo.LoseBill SET ShowOrder=ID WHERE BillNumberId=@nBillID
							--修改BillIndex的TotalMoney
							SELECT @TotalQty = SUM(Qty) FROM LoseBill WHERE BillNumberId = @nBillId
							UPDATE BillIndex SET TotalQty = @TotalQty,ifWx = @ifWx WHERE BillNumberId = @nBillId
			
							--返回单据编号
							SELECT @TmpBsBillCode = @TmpBsBillCode + 'я' + ISNULL(BillCode,' ') FROM BillIndex WHERE BillNumberId = @nBillId	

							--自定义继承（主表）
							INSERT INTO Custom_BillIndex
							(
							  [BillId],[BillType],[SysDiy1_head],[SysDiy2_head],[SysDiy3_head]
							  ,[SysDiy4_head],[SysDiy5_head],[SysDiy6_head],[SysDiy7_head]
							  ,[SysDiy8_head],[SysDiy9_head],[SysDiy10_head],[SysDiy11_head]
							  ,[SysDiy12_head],[SysDiy13_head],[SysDiy14_head],[SysDiy15_head],[SysDiy16_head]
							)
							SELECT @nBillId,9,[SysDiy1_head],[SysDiy2_head],[SysDiy3_head]
							  ,[SysDiy4_head],[SysDiy5_head],[SysDiy6_head],[SysDiy7_head]
							  ,[SysDiy8_head],[SysDiy9_head],[SysDiy10_head],[SysDiy11_head]
							  ,[SysDiy12_head],[SysDiy13_head],[SysDiy14_head],[SysDiy15_head],[SysDiy16_head]
							FROM [Custom_BillIndex] WHERE BillId=@nid and billtype=306
							
							--自定义继承（明细）
							INSERT INTO Custom_BillDetails
							(
								[BillId],[Detailid],[BillType],[SysDiy1],[SysDiy2],[SysDiy3],[SysDiy4]
								,[SysDiy5],[SysDiy6],[SysDiy7],[SysDiy8],[SysDiy9],[SysDiy10]
								,[SysDiy11],[SysDiy12],[SysDiy13],[SysDiy14],[SysDiy15],[SysDiy16]
							)
							SELECT @nBillId,t.id,9,c.[SysDiy1],c.[SysDiy2],c.[SysDiy3],c.[SysDiy4]
							  ,c.[SysDiy5],c.[SysDiy6],c.[SysDiy7],c.[SysDiy8],c.[SysDiy9],c.[SysDiy10]
							  ,c.[SysDiy11],c.[SysDiy12],c.[SysDiy13],c.[SysDiy14],c.[SysDiy15],c.[SysDiy16]
							  FROM [Custom_BillDetails] C LEFT JOIN
							  (
								SELECT o.ID,s.stockcheckid,s.id as stockdetailid FROM LoseBill o INNER JOIN StockCheck s 
								ON o.ptypeid=s.ptypeid WHERE s.stockcheckid=@nid AND o.billnumberid=@nBillId
							  ) t ON C.detailid=t.stockdetailid 
							  WHERE BillId=@nid  and billtype=306
							  
							IF @@error<>0 
								BEGIN
									RETURN -2
								END				
												
							SET @i = @i + 1
							
							-- 自动生成的单据会影响草稿库存
							EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,9
						END			
				END
		END
		--修改单据的盘点状态
		UPDATE StockCheckIndex SET Pass = 1 WHERE StockCheckId = @nid
	END
ELSE
	BEGIN
		SELECT * FROM StockCheckIndex
	END

IF @TmpByBillCode = ''
	SET @bcode = @TmpBsBillCode
ELSE
	SET @bcode = @TmpByBillCode + ' ' + @TmpBsBillCode

SELECT @autocount=COUNT(*)
FROM #ResultMx

RETURN 0

DROP TABLE #Result,#ResultMx,#overflowBill,#LoseBill,#GetManPTypeId,#GetManKTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2009-06-01
	描述：生产模板生成草稿
*/
CREATE  PROCEDURE Gp_AutoProceModelCaoGao
(
	@OperatorId	varchar(200),
	@nid		numeric(18,0),
	@qty		 NUMERIC(24, 10) ,
	@ktypeid	varchar(200),
	@ktypeid1	varchar(200),
	@ntype		varchar(10),
	@outBcode	varchar(400) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL  RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -5
	END
END  

-- ********	判断是否试用版 - END	********

DECLARE @ProduceModelName	varchar(1000),
		@PTypeId			varchar(200),
		@ProduceComment		varchar(400)

SELECT @ProduceModelName = producemodelname,@PTypeId = PTypeId,@ProduceComment = Comment FROM ProduceModelIndex WHERE ProduceModelId = @nid

--判断数量不能大于99999999999999
IF EXISTS(SELECT TOP 1 1 FROM ProduceModel WHERE ProduceModelId = @nid and @qty*Qty>99999999999999)
	RETURN -1


IF  EXISTS(SELECT TOP 1 1 FROM ProduceModelIndex pm  INNER JOIN ptype p ON p.typeId=pm.PtypeID WHERE pm.ProduceModelId = @nid AND p.deleted=1)
BEGIN
	RAISERROR ('生成的商品已经被停用,请重新选择!',16, 1)
	return 
END



IF  EXISTS( SELECT TOP 1 1 FROM ProduceModel pm  INNER JOIN ptype p ON p.typeId=pm.PtypeID WHERE pm.ProduceModelId = @nid AND p.deleted=1)
BEGIN
	RAISERROR ('单据明细中存在无效或被停用的商品',16, 1)
	return 
END

IF NOT EXISTS(
	SELECT  TOP 1 1
	FROM (SELECT STypeID  FROM  stock WHERE typeid= @ktypeid) b 
			INNER JOIN  (SELECT STypeID  FROM  stock WHERE typeid= @ktypeid1) s  ON b.STypeID=s.STypeID
)
BEGIN 
	RAISERROR ('出库与入库必须属于同一分支机构',16, 1)
	return 
END 



DECLARE @stid VARCHAR(100)
SELECT @stid = stypeid FROM stock WHERE typeId=@ktypeid

--生成单据编号
DECLARE @MONTH 				varchar(50),
		@DAY 				varchar(50),
		@BillCodeConfig		varchar(10),
		@bCode				varchar(300),
		@Re					int,
		@Tax				 NUMERIC(24, 10) ,
		@period				int,
		@DTypeId			varchar(200),
		@nBillId			numeric(18,0),
		@recPrice			 NUMERIC(24, 10) ,
		@preprice			 NUMERIC(24, 10) ,
		@Explain			varchar(400),
		@cefullname			VARCHAR(500)=''

SET @Tax = 0
SET @recPrice = 0
SET @preprice = 0

IF @ntype = '1'
	SET @Explain = '由生产模板【'+@ProduceModelName+'】生成的组装单'
ELSE
	SET @Explain = '由生产模板【'+@ProduceModelName+'】生成的拆装单'

IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '1')
	SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'

SELECT @period = period FROM MonthProc WHERE MonthNo = '本期'

SELECT @DTypeId = D.TypeId FROM Department D,Employee E WHERE E.Department = D.FullName AND E.TypeId = @OperatorId
SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @OperatorId

SET @MONTH = month(getdate())
SET @DAY = day(getdate())

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 16) AND @BillCodeConfig = '1'
	BEGIN
		SELECT @MONTH = ''
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @ktypeid
	END
	
DECLARE
	@STypeID		VARCHAR(50),
	@datBillDate	DATETIME
	
SELECT
	@datBillDate=CONVERT(varchar(10),GetDate(),120)

EXEC @Re=Gp_GetBillCode 16, @MONTH,@DAY,'CZ',@datBillDate,@stid,@bCode output,'',@cefullname

--生成默认币种
DECLARE @CID	INT
DECLARE @Rate	 NUMERIC(24, 10) 
DECLARE @UnitRate  NUMERIC(24, 10)  --浮动换算率
DECLARE @UnitRate1  NUMERIC(24, 10)  --浮动换算率
DECLARE	@MunitID INT --大单位ID
DECLARE	@MunitID1 INT --大单位ID
DECLARE @MUnitrate  NUMERIC(24, 10)  --大单位换算率
DECLARE @MUnitrate1  NUMERIC(24, 10)  --大单位换算率
SELECT @CID=CID,@Rate=Rate FROM Ac_Currency WHERE Sysrow=1
SELECT @UnitRate=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.AssistantUnitId =b.UnitsId WHERE a.typeID=@ptypeid
SELECT @MunitID=baseUnitId FROM Ptype WHERE typeId = @PTypeId
SELECT @MUnitrate=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.baseUnitId =b.UnitsId WHERE a.typeID=@ptypeid
IF @Re <> 0
	RETURN -2

--写入单据主表

	
SELECT @STypeID=STypeID
FROM Stock
WHERE typeId=@ktypeid	

INSERT INTO BillIndex (AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,Comment,Stypeid,CID,Rate)
VALUES(9999,@datBillDate,@bCode,16,'','','','',@ktypeid,@ktypeid1,'f',@OperatorId,0,0,@Qty,@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@ProduceComment,@STypeID,@CID,@Rate)

IF @@ROWCOUNT = 0
	RETURN -3
ELSE
	SET @nBillId = SCOPE_IDENTITY();
	


--插入明细
DECLARE @MxPTypeId		varchar(200),
		@MxQty			 NUMERIC(24, 10) 

IF @nType = '1'
	BEGIN
		--写入库商品明细
		IF EXISTS(SELECT TOP 1 1 FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId1)
			SELECT  TOP 1 @recPrice = dbo.F_RoundData(Price,'price') FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId1 ORDER BY GoodsOrder DESC
		ELSE
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM PType WHERE TypeId = @PTypeId AND recPrice=0)
					SELECT  TOP 1 @recPrice = dbo.F_RoundData(PreBuyPrice5,'price') FROM PType_Price WHERE PTypeId = @PTypeId
				ELSE
					SELECT  TOP 1 @recPrice = dbo.F_RoundData(recPrice,'price') FROM PType WHERE TypeId = @PTypeId
			END

		INSERT INTO DisassembleBill(BillNumberId,PTypeId,Qty,CostPrice,Total,InOrOut,OutFactoryDate,JobNumber,Comment,Serial,KTypeId,STypeID,UnitRate,Nqty,MUnitId,MUnitRate,MQty,CurMSalePrice,ItemID,IsCombined,GoodsCostPrice)
		VALUES(@nBillId,@PTypeId,@Qty,@recPrice,dbo.F_RoundData(@recPrice*@Qty,'total'),'I',GetDate(),'','','',@KTypeId1,@STypeID,@UnitRate,Case @UnitRate WHEN 0 THEN 0 ELSE dbo.F_RoundData(@qty/@UnitRate,'qty') END,@MunitID,@MUnitrate,@Qty,@recPrice,'0','0','-1')
		
		UPDATE dbo.DisassembleBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
		--写入出库商品
		DECLARE ZcCursor CURSOR FOR
			SELECT PTypeId,Qty FROM ProduceModel WHERE ProduceModelId = @nid ORDER BY [ID]

		OPEN ZcCursor

		FETCH NEXT FROM ZcCursor INTO @MxPTypeId,@MxQty
	
		WHILE @@FETCH_STATUS = 0
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM GoodsStocks WHERE PTypeId = @MxPTypeId AND KTypeId = @KTypeId)
					SELECT  TOP 1 @PrePrice = dbo.F_RoundData(Price,'price') FROM GoodsStocks WHERE PTypeId = @MxPTypeId AND KTypeId = @KTypeId ORDER BY GoodsOrder DESC
				ELSE
					BEGIN
						IF EXISTS( SELECT TOP 1 1 FROM PType WHERE TypeId = @MxPTypeId AND recprice=0)
							SELECT  TOP 1 @PrePrice = dbo.F_RoundData(PreBuyPrice5,'price') FROM PType_Price WHERE PTypeId = @MxPTypeId
						ELSE
							SELECT  TOP 1 @PrePrice = dbo.F_RoundData(recprice,'price') FROM PType WHERE TypeId = @MxPTypeId	
					END
				
				SELECT @UnitRate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.AssistantUnitId =b.UnitsId WHERE a.typeID=@MxPTypeId	
				SELECT @MunitID1=baseUnitId FROM Ptype WHERE typeId = @MxPTypeId
				SELECT @MUnitrate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.baseUnitId =b.UnitsId WHERE a.typeID=@MxPTypeId

				INSERT INTO DisassembleBill(BillNumberId,PTypeId,Qty,CostPrice,Total,InOrOut,OutFactoryDate,JobNumber,Comment,Serial,KTypeId,Stypeid,UnitRate,Nqty,MUnitId,MUnitRate,MQty,CurMSalePrice,ItemID,IsCombined,GoodsCostPrice)
				VALUES(@nBillId,@MxPTypeId,dbo.F_RoundData(@Qty*@MxQty,'qty'),@PrePrice,dbo.F_RoundData(@PrePrice*@Qty*@MxQty,'total'),'O',GetDate(),'','','',@KTypeId,@STypeID,@UnitRate1,Case @UnitRate1 WHEN 0 THEN 0 ELSE dbo.F_RoundData((@Qty*@MxQty)/@UnitRate1,'qty') END,@MunitID1,@MUnitrate1,dbo.F_RoundData(@Qty*@MxQty,'qty'),@PrePrice,'0','0','-1')				
				
				UPDATE dbo.DisassembleBill SET ShowOrder=ID WHERE BillNumberId=@nBillID
				FETCH NEXT FROM ZcCursor INTO @MxPTypeId,@MxQty
			END

		CLOSE ZcCursor
		DEALLOCATE ZcCursor

		IF NOT EXISTS(SELECT TOP 1 1 FROM DisassembleBill WHERE BillNumberId = @nBillId AND InOrOut='I')
			RETURN -6

		IF NOT EXISTS(SELECT TOP 1 1 FROM DisassembleBill WHERE BillNumberId = @nBillId AND InOrOut='O')
			RETURN -6
	END
ELSE
	BEGIN
		--写入库商品明细
		IF EXISTS(SELECT TOP 1 1 FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId)
			SELECT TOP 1 @recPrice = dbo.F_RoundData(Price,'price') FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId ORDER BY GoodsOrder DESC
		ELSE
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM PType WHERE TypeId = @PTypeId AND recPrice=0)
					SELECT Top 1 @recPrice = dbo.F_RoundData(PreBuyPrice5,'price') FROM PType_Price WHERE PTypeId = @PTypeId
				ELSE
					SELECT Top 1 @recPrice = dbo.F_RoundData(recPrice,'price') FROM PType WHERE TypeId = @PTypeId
			END

		INSERT INTO DisassembleBill(BillNumberId,PTypeId,Qty,CostPrice,Total,InOrOut,OutFactoryDate,JobNumber,Comment,Serial,KTypeId,STypeID,UnitRate,Nqty,MUnitId,MUnitRate,MQty,CurMSalePrice,ItemID,IsCombined,GoodsCostPrice)
		VALUES(@nBillId,@PTypeId,@Qty,@recPrice,dbo.F_RoundData(@recPrice*@Qty,'total'),'O',GetDate(),'','','',@KTypeId,@STypeID,@UnitRate,Case @UnitRate WHEN 0 THEN 0 ELSE dbo.F_RoundData(@qty/@UnitRate,'qty') END,@MunitID,@MUnitrate,@Qty,@recPrice,'0','0','-1')
		
		UPDATE dbo.DisassembleBill SET ShowOrder=ID WHERE BillNumberId=@nBillID
		--写入出库商品
		DECLARE CzCursor CURSOR FOR
			SELECT PTypeId,Qty FROM ProduceModel WHERE ProduceModelId = @nid ORDER BY [ID]

		OPEN CzCursor

		FETCH NEXT FROM CzCursor INTO @MxPTypeId,@MxQty
	
		WHILE @@FETCH_STATUS = 0
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM GoodsStocks WHERE PTypeId = @MxPTypeId AND KTypeId = @KTypeId1)
					SELECT TOP 1 @PrePrice = dbo.F_RoundData(Price,'price') FROM GoodsStocks WHERE PTypeId = @MxPTypeId AND KTypeId = @KTypeId1 ORDER BY GoodsOrder DESC
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 1 FROM PType WHERE TypeId = @MxPTypeId AND recprice=0)
							SELECT  TOP 1 @PrePrice = dbo.F_RoundData(PreBuyPrice5,'price') FROM PType_Price WHERE PTypeId = @MxPTypeId
						ELSE
							SELECT  TOP 1 @PrePrice = dbo.F_RoundData(recprice,'price') FROM PType WHERE TypeId = @MxPTypeId
					END
				
				SELECT @UnitRate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.AssistantUnitId =b.UnitsId WHERE a.typeID=@MxPTypeId	
				SELECT @MunitID1=baseUnitId FROM Ptype WHERE typeId = @MxPTypeId
				SELECT @MUnitrate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.baseUnitId =b.UnitsId WHERE a.typeID=@MxPTypeId
				
				INSERT INTO DisassembleBill(BillNumberId,PTypeId,Qty,CostPrice,Total,InOrOut,OutFactoryDate,JobNumber,Comment,Serial,KTypeId,STypeID,UnitRate,nqty,MUnitId,MUnitRate,MQty,CurMSalePrice,ItemID,IsCombined,GoodsCostPrice)
				VALUES(@nBillId,@MxPTypeId,dbo.F_RoundData(@Qty*@MxQty,'qty'),@PrePrice,dbo.F_RoundData(@PrePrice*@Qty*@MxQty,'total'),'I',GetDate(),'','','',@KTypeId1,@STypeID,@UnitRate1,Case @UnitRate1 WHEN 0 THEN 0 ELSE dbo.F_RoundData((@Qty*@MxQty)/@UnitRate1,'qty') END,@MunitID1,@MUnitrate1,dbo.F_RoundData(@Qty*@MxQty,'qty'),@PrePrice,'0','0','-1')				
				
				UPDATE dbo.DisassembleBill SET ShowOrder=ID WHERE BillNumberId=@nBillID
				
				FETCH NEXT FROM CzCursor INTO @MxPTypeId,@MxQty
			END

		CLOSE CzCursor
		DEALLOCATE CzCursor

		IF NOT EXISTS(SELECT TOP 1 1 FROM DisassembleBill WHERE BillNumberId = @nBillId AND InOrOut='I')
			RETURN -6

		IF NOT EXISTS(SELECT TOP 1 1 FROM DisassembleBill WHERE BillNumberId = @nBillId AND InOrOut='O')
			RETURN -6		
	END
	
--处理货位
UPDATE 	DisassembleBill
SET		CargoID = ISNULL((SELECT TOP 1 CargoID FROM CargoType WHERE PTypeId = DisassembleBill.PTypeId AND KTypeId = DisassembleBill.KTypeId AND CargoType.IsDefault = 1),'')
WHERE	BillNumberId = @nBillId	

-- 自动生成的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillID,16
					
DECLARE @costing INT 
SELECT @costing=SubValue FROM dbo.sysdata WHERE SubName='costing'
IF @costing=3--手工指定时处理成本单价
 BEGIN
  UPDATE DisassembleBill SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
 
 END

SET @outBcode = @bCode	


IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed	@nBillId,@datBillDate,16,@bCode
END

IF @Re <> 0
	RETURN -2

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者:谢吉康
	日期:2004-5-10
	描述:平摊商品在所有仓库中的成本
*/
create PROCEDURE Gp_AverageAllCostPrice
(
	@PTypeID 		VARCHAR(50),
	@BillNumberID	INT
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN

DECLARE @dQty    NUMERIC(24, 10) 
DECLARE @dPrice  NUMERIC(24, 10) 
DECLARE @dTotal  NUMERIC(24, 10) 

SELECT @dPrice = Price FROM AdpriceBill WHERE BillNumberID = @BillNumberID

SELECT * FROM GoodsStocks

UPDATE	GoodsStocks
SET		Price = @dPrice
WHERE 	PTypeID = @PTypeID

IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		RETURN 9
	END

UPDATE	GoodsStocks
SET		Total = Qty * Price
WHERE 	PTypeID = @PTypeID

IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		RETURN 9
	END

COMMIT
RETURN 0








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	功能说明：	平均所有仓库中某一商品的成本
	作    者：	卢    春
	最后修改：	2004-06-08
*/
CREATE         PROCEDURE GP_AverageCostPrice
(
	@PTypeID	varchar(50)		-- 商品 ID 值
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @ReCostPrice  NUMERIC(24, 10) 
 
IF @PTypeID IS NULL RETURN 1

/*
	计算所有仓库的金额，数量合计
	只计算库存数量、库存金额同号，正数负数分开计算
*/
DECLARE	@TempQty	 NUMERIC(24, 10) ,	-- 库存数量
		@TempTotal	 NUMERIC(24, 10) ,	-- 库存金额
		@KTypeID	varchar(50),	-- 仓库 ID 值
		@TempTotal1	 NUMERIC(24, 10) ,
		@cn int,
		@i int

-- ********	计算正数 - Start	********
SELECT	@TempQty = SUM(Qty),
		@TempTotal = SUM(Total)
FROM	GoodsStocks
WHERE	PTypeID = @PTypeID
		AND Qty >= 0
		AND Total >= 0

IF @TempTotal = 0 OR @TempQty = 0 GOTO OTHER	-- 判断负数

SET @ReCostPrice = @TempTotal / @TempQty
 
-- 更新每个仓库的单价金额
SELECT	@cn = COUNT(*)
FROM	GoodsStocks
WHERE	PTypeID = @PTypeID
		AND Qty >= 0
		AND Total >= 0

DECLARE AverageStockPrice CURSOR FOR
	SELECT	KTypeID
	FROM	GoodsStocks
	WHERE	PTypeID = @PTypeID
			AND Qty >= 0
			AND Total >= 0
			ORDER BY Qty

OPEN AverageStockPrice
IF @@ERROR <> 0
BEGIN
	CLOSE AverageStockPrice
	DEALLOCATE AverageStockPrice
	RETURN 1
END
FETCH NEXT FROM AverageStockPrice INTO @KTypeID

SET @TempTotal1 = 0
SET @i = 0
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @i = @cn - 1
	BEGIN
		UPDATE	GoodsStocks
		SET		Price =
					CASE WHEN Qty = 0
					THEN @ReCostPrice
					ELSE ( @TempTotal - @TempTotal1 ) / Qty
					END,
				Total = ( @TempTotal - @TempTotal1 )
		WHERE	KTypeID = @KTypeID
				AND PTypeID = @PTypeID

		IF @@ERROR <> 0
		BEGIN
			CLOSE AverageStockPrice
			DEALLOCATE AverageStockPrice
			RETURN 1
		END
	END
	ELSE
	BEGIN
		UPDATE	GoodsStocks
		SET		Price = 
					CASE WHEN Qty = 0
					THEN 0
					ELSE @ReCostPrice
					END,
				Total = CAST(@ReCostPrice * Qty AS  NUMERIC(24, 10) )
		WHERE	KTypeID = @KTypeID
				AND PTypeID = @PTypeID

		IF @@ERROR <> 0
		BEGIN
			CLOSE AverageStockPrice
			DEALLOCATE AverageStockPrice
			RETURN 1
		END

		SELECT	@TempTotal1 = @TempTotal1 + Total
		FROM	GoodsStocks
		WHERE	KTypeID = @KTypeID
				AND PTypeID = @PTypeID
	
		SELECT @i = @i + 1
	END

	FETCH NEXT FROM AverageStockPrice INTO @KTypeID
END

CLOSE AverageStockPrice
DEALLOCATE AverageStockPrice


-- ********	计算负数 - Start	********
OTHER:

SELECT	@TempQty = SUM(Qty),
		@TempTotal = SUM(total)
FROM	GoodsStocks
WHERE	PTypeID = @PTypeID
		AND Qty < 0
		AND Total < 0

IF @TempTotal = 0 OR @TempQty = 0 RETURN 0

SET @ReCostPrice = @TempTotal / @TempQty

-- 更新每个仓库的单价金额
SELECT	@cn = COUNT(*)
FROM	GoodsStocks
WHERE	PTypeID = @PTypeID
		AND Qty < 0
		AND Total < 0

DECLARE AverageStockPrice CURSOR FOR
	SELECT	KTypeID
	FROM	GoodsStocks
	WHERE	PTypeID = @PTypeID
			AND Qty < 0
			AND Total < 0
			ORDER BY Qty DESC

OPEN AverageStockPrice
IF @@ERROR <> 0
BEGIN
	CLOSE AverageStockPrice
	DEALLOCATE AverageStockPrice
	RETURN 1
END

FETCH NEXT FROM AverageStockPrice INTO @KTypeID

SET @TempTotal1 = 0
SET @i = 0
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @i = @cn - 1
	BEGIN
		UPDATE	GoodsStocks
		SET		Price = 
					CASE WHEN Qty = 0
					THEN @ReCostPrice
					ELSE ( @TempTotal - @TempTotal1 ) / Qty
					END,
				Total = ( @TempTotal - @TempTotal1 )
		WHERE	KTypeID = @KTypeID
				AND PTypeID = @PTypeID

		IF @@ERROR <> 0
		BEGIN
			CLOSE AverageStockPrice
			DEALLOCATE AverageStockPrice
			RETURN 1
		END
	END
	ELSE
	BEGIN
		UPDATE	GoodsStocks
		SET		Price =
					CASE WHEN Qty = 0
					THEN 0
					ELSE @ReCostPrice
					END,
				Total = CAST(@ReCostPrice * Qty AS  NUMERIC(24, 10) )
		WHERE	KTypeID = @KTypeID
				AND PTypeID = @PTypeID

		IF @@ERROR <> 0
		BEGIN
			CLOSE AverageStockPrice
			DEALLOCATE AverageStockPrice
			RETURN 1
		END

		SELECT	@TempTotal1 = @TempTotal1 + Total
		FROM	GoodsStocks
		WHERE	KTypeID = @KTypeID
				AND PTypeID = @PTypeID

		SELECT @i = @i + 1
	END

	FETCH NEXT FROM AverageStockPrice INTO @KTypeID
END

CLOSE AverageStockPrice
DEALLOCATE AverageStockPrice
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*

2017-02-06  梁晰 删除,红冲,反过账回填同价调拨单状态及数量
2017-02-23  冯波 代处理9.8 稳定版BUG 39

*/
CREATE PROC Gp_BackFillAllotBillState
(
	@BillNumberId		numeric(10,0),
	@billtype			INT
)
AS

--当前调拨单所调用的申请单
create table #PosAllotApplyBill
(
	billnumberid int, --主表id	
	allotid	int		--明细id
)

IF @billtype=17
BEGIN
	UPDATE dbo.PosAllotApplyBill SET CallQty -= M.qty 
	FROM PosAllotApplyBill P,dbo.MoveBill M
	WHERE M.AllotID=P.ID AND M.BillNumberId=@BillNumberId AND M.AllotID>0	
	
	INSERT INTO #PosAllotApplyBill( billnumberid, allotid )
	SELECT B.FromBillNumberID, M.AllotID
	FROM MoveBill M INNER JOIN BillIndex B ON M.BillNumberId = B.BillNumberId
	WHERE M.BillNumberId=@BillNumberId AND M.AllotID>0
END

IF @billtype=21
BEGIN
	UPDATE dbo.PosAllotApplyBill SET CallQty -= M.qty 
	FROM PosAllotApplyBill P,dbo.movebjbill M
	WHERE M.AllotID=P.ID AND M.BillNumberId=@BillNumberId AND M.AllotID>0	
	
	INSERT INTO #PosAllotApplyBill( billnumberid, allotid )
	SELECT B.FromBillNumberID, M.AllotID
	FROM movebjbill M INNER JOIN BillIndex B ON M.BillNumberId = B.BillNumberId
	WHERE M.BillNumberId=@BillNumberId AND M.AllotID>0
END

IF @billtype=187
BEGIN
	UPDATE dbo.PosAllotApplyBill SET CallQty -= M.qty 
	FROM PosAllotApplyBill P,dbo.stypemovebill M
	WHERE M.AllotID=P.ID AND M.BillNumberId=@BillNumberId AND M.AllotID>0	
	
	INSERT INTO #PosAllotApplyBill( billnumberid, allotid )
	SELECT B.FromBillNumberID, M.AllotID
	FROM stypemovebill M INNER JOIN BillIndex B ON M.BillNumberId = B.BillNumberId
	WHERE M.BillNumberId=@BillNumberId AND M.AllotID>0
END

--存在引用数量小于申请单数量的申请单状态改为未完成
UPDATE PosAllotApplyBillIndex SET Isdone=0 
WHERE BillNumberId IN (
						SELECT BillNumberId 
						FROM dbo.PosAllotApplyBill 
						WHERE CallQty<qty AND billnumberid IN (SELECT billnumberid FROM #PosAllotApplyBill) 
						)

DROP TABLE #PosAllotApplyBill

RETURN 0;

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
 按分支机构反开账
*/
CREATE PROCEDURE Gp_BackIniAll
(
	@STypeId		VARCHAR(MAX),		--	分支机构
	@CkAccount		INT,				--	=1 总账开账
	@CkBuisness     INT,				--  =1 业务开账
    @returnValue	VARCHAR(MAX) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--业务开账
IF @CkBuisness=1
BEGIN
	DECLARE @KTypeId		VARCHAR(MAX),
			@szCanModiIni	INT,
			@Re				INT,
			@rValue			VARCHAR(MAX),
			@MxSTypeId		VARCHAR(MAX),
			@MxSFullName	VARCHAR(MAX)
			
	--判断是否未开账
	IF @stypeid='' AND NOT EXISTS(SELECT TOP 1 1 FROM SType s LEFT JOIN SType_UserConfig u ON s.TypeId=u.StypeId WHERE s.sonnum=0 AND s.deleted=0 AND u.Value = '1' AND u.ConfigNo = '1')
		GOTO ACCOUNT
	IF @stypeid <> '' AND EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeID = @STypeId AND (Value = '0' AND ConfigNo = '1' OR Value IS NULL))
		GOTO ACCOUNT
	
	--选具体分支机构开账的时候:独立核算的分支机构必须在所有以其作为记账单位的非独立分支机构开完帐后才能开账
	IF @stypeid<>'' AND EXISTS(SELECT 1 FROM dbo.SType s WHERE sonnum =0 AND TypeId = @stypeid AND VerifyID<>@STypeId AND EXISTS(SELECT 1 FROM dbo.SType_UserConfig WHERE StypeId=s.VerifyID AND ConfigNo='1' AND Value='1'))
	AND EXISTS(SELECT 1 from Sysdata WHERE SubName='IsUseAcSystem' AND SubValue='1') --总账情况下验证
	BEGIN
		SET @rValue='非独立核算的分支机构必须在其记账单位的分支机构反开账后才能反开账'
		SET @Re=-2
		GOTO ERROR
	END

	CREATE TABLE #stype(typeid VARCHAR(50))
	IF @stypeid=''
		INSERT	INTO #stype
		SELECT	s.TypeId 
		FROM F_GetAllManagerBaseTypeId(@STypeId,11,'00001') s
		INNER JOIN SType_UserConfig u ON s.TypeId=u.StypeId 
		INNER JOIN dbo.SType B ON S.TypeId=B.TypeId
		WHERE	u.Value = '1' AND u.ConfigNo = '1' 
		AND B.deleted=0
	ELSE
		INSERT INTO #stype
				( typeid )
		VALUES  ( @stypeid)
	
	
	IF EXISTS(SELECT 1 FROM dbo.MonthProc A INNER JOIN #stype B ON A.STypeID=B.typeid 
			  GROUP BY STypeID
			  HAVING COUNT(1)>1)
	BEGIN
		SET @rValue='系统已做过月结，不能进行反开账，请删除月结后再进行操作'
		SET @Re=-2
		GOTO ERROR
	END
		
	DECLARE @sfullname VARCHAR(max)='',@proinfo INT=1
	SELECT @proinfo=subvalue FROM dbo.sysdata WHERE SubName='proinfo'
	IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)AND BillType IN (181,203))
	BEGIN
		IF @proinfo=1
			SET @rValue='存在已过账的序列号调整单或者会员储值充值单，不能反开账！'
		ELSE
		BEGIN
			SELECT distinct(stypeid) AS stypeid
			INTO #stype1
			FROM billindex 
			WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype) AND BillType IN (181,203)
			SELECT @sfullname=@sfullname+','+fullname FROM dbo.SType WHERE typeid IN(SELECT stypeid FROM  #stype1)
			SET @sfullname=RIGHT(@sfullname,LEN(@sfullname)-1)
			SET @rValue =@sfullname+'存在已过账的序列号调整单或者会员储值充值单，不能反开账！'
			DROP TABLE #stype1
			
		END
		SET @Re=-2				
		GOTO ERROR
	END	

	IF EXISTS(
		SELECT 1 FROM dbo.BillIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
			AND BillType NOT IN(84,85,78,213,212,214,307,410,411)
		UNION ALL 
		SELECT 1 FROM dbo.ReceiptBillIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
		UNION ALL
		SELECT 1 FROM dbo.LendIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
		UNION ALL
		SELECT 1 FROM dbo.FactIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND Stypeid IN (SELECT typeid from #stype)
		UNION ALL
		SELECT  1 FROM dbo.onShelvespickIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND Stypeid IN (SELECT typeid from #stype)
		UNION ALL
		SELECT 1 FROM Coupon_BillIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND Stypeid IN (SELECT typeid from #stype)
	)
	BEGIN
		IF @proinfo=1
		BEGIN	
			SET @rValue='存在已过账的单据，请红冲后重试！'
		END
		ELSE
		BEGIN
			SELECT distinct(B.stypeid) AS stypeid
			INTO #stype2
			FROM (
				SELECT stypeid FROM billindex 
				WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
					AND BillType NOT IN(84,85,78,213,212,214,307,410,411)
				UNION ALL 
				SELECT stypeid FROM ReceiptBillIndex 
				WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
				UNION ALL 
				SELECT stypeid FROM LendIndex 
				WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
				UNION ALL
				SELECT stypeid FROM dbo.FactIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND Stypeid IN (SELECT typeid from #stype)
				UNION ALL
				SELECT stypeid FROM dbo.onShelvespickIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND Stypeid IN (SELECT typeid from #stype)
				UNION ALL 
				SELECT STYPEID FROM Coupon_BillIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND Stypeid IN (SELECT typeid from #stype)
			) AS B
			
			SELECT @sfullname=@sfullname+','+fullname FROM dbo.SType WHERE typeid IN(SELECT stypeid FROM  #stype2)
			SET @sfullname=RIGHT(@sfullname,LEN(@sfullname)-1)
			IF EXISTS  (SELECT  * FROM dbo.SysObjects WHERE ID = object_id(N'[A8ZTInfo]') AND OBJECTPROPERTY(ID, 'IsTable') = 1) 
			BEGIN
				SET @rValue = @sfullname+'存在已过账的单据，请红冲后重试！'
			END
			ELSE
			BEGIN
				SET @rValue = '存在已过账的单据，请红冲后重试！'
			END
			DROP TABLE #stype2
		END
		SET @Re=-2				
		GOTO ERROR
	END	
		
	--修改财务期初汇总值	
	UPDATE	AType_Total
	SET		Total00 = Total,
			Ntotal00 = Ntotal,
			Total   = 0,
			Ntotal	= 0
	WHERE	STypeID IN (SELECT  typeid FROM #stype)	

	--修改往来期初汇总值	反开账期初值置为0
	UPDATE	BType_ARAPTotal 
	SET		ARTotal00 = ARTotal,
			APTotal00 = APTotal,
			YSTotal00 = YSTotal,
			YFTotal00 = YFTotal,
			nARTotal00 = nARTotal,
			nAPTotal00 = nAPTotal,
			nYSTotal00 = nYSTotal,
			nYFTotal00 = nYFTotal,--
			GRIRTotal00 = GRIRTotal,
			NGRIRTotal00 = NGRIRTotal,
			FCTotal00 = FCTotal,
			NFCTotal00 =NFCTotal,
			ARTotal = 0,
			APTotal = 0,
			YSTotal = 0,
			YFTotal = 0,
			nARTotal = 0,
			nAPTotal = 0,
			nYSTotal = 0,
			nYFTotal = 0,
			GRIRTotal = 0,
			NGRIRTotal = 0,
			FCTotal = 0,
			NFCTotal = 0
	WHERE	STypeID IN (SELECT  typeid FROM #stype)		
	DELETE FROM dbo.BType_ArApTotal	WHERE GRIRTotal00 = 0 AND NGRIRTotal00 = 0 AND FCTotal00 = 0 AND NFCTotal00 =0 AND YSTotal00=0 AND 
									YFTotal00=0 AND ARTotal00=0 AND APTotal00=0 AND nYSTotal00=0 AND nYFTotal00=0 AND nARTotal00=0 AND 
									nAPTotal00=0 AND STypeID IN (SELECT  typeid FROM #stype)	
	--清除期初余额
	DELETE FROM dbo.IniBType_ArApTotal	WHERE STypeID IN (SELECT  typeid FROM #stype)	
	
	--修改品牌往来期初汇总值	反开账期初值置为0
	UPDATE	dbo.Brandar_ArApTotal 
	SET		ARTotal00= ARTotal,
			YSTotal00= YSTotal,
			nARTotal00 = nARTotal,
			nYSTotal00 = nYSTotal,
			ARTotal = 0,
			YSTotal = 0,
			nARTotal = 0,
			nYSTotal = 0
		  
	WHERE	STypeID IN (SELECT  typeid FROM #stype)	
		
	DELETE FROM dbo.Brandar_ArApTotal	
	WHERE   YSTotal00=0  AND ARTotal00=0 AND nYSTotal00=0  
	AND		nARTotal00=0 AND STypeID IN (SELECT  typeid FROM #stype)

	CREATE TABLE #Ktype(TypeId VARCHAR(50))
	INSERT INTO #Ktype(TypeId) SELECT TypeId FROM Stock WHERE STypeId IN (SELECT typeid FROM #stype) AND SonNum = 0
	DELETE FROM dbo.GoodsStocks WHERE KtypeId IN (SELECT typeid FROM #Ktype)
	DELETE FROM dbo.GOODSSTOCKS_QTY WHERE KtypeId IN (SELECT typeid FROM #Ktype)
	DELETE FROM dbo.wx_GoodsStocks WHERE KtypeId IN (SELECT typeid FROM #Ktype)
	
	--找出只在这些分支机构的序列号，然后把他们删除；如果这些序列号还存在于其他分支机构，则替换状态
	
	--关于当前序列号
	DELETE FROM gp_CruPTypeSerial 
	WHERE STypeId IN (SELECT  typeid FROM #stype)
	AND Serial IN
	(
		SELECT a.Serial
		FROM gp_CruPTypeSerial a
		WHERE a.STypeId IN (SELECT  typeid FROM #stype) AND NOT EXISTS(
			SELECT b.Serial
			FROM dbo.gp_inoutPtypeSerial b
			INNER JOIN dbo.BillIndex c
			ON b.BillNumberid=c.BillNumberId
			WHERE b.Serial=a.Serial
			AND c.Stypeid NOT IN (SELECT  typeid FROM #stype)
		)
	)
	
	
	
	UPDATE dbo.gp_CruPtypeSerial
	SET State=b.State,KTypeID=b.KTypeID,BTypeID1=b.BTypeID1,BTypeID2=b.BTypeID2,
	CostPrice=b.CostPrice,GoodsNumber=b.GoodsNumber,ItemID=b.ItemID,IsCombined=b.IsCombined,
	CargoID=b.CargoID,ProduceDate=b.ProduceDate,ValidDate=b.ValidDate,PtypeID=b.PtypeID
	FROM
	(
		SELECT b.Serial,b.State,CASE WHEN b.InKtypeID IS NULL THEN b.OutKtyeID ELSE b.InKTypeID END KTypeID,
		b.BTypeID1,b.BTypeID2,b.CostPrice,b.GoodsNumber,b.ItemID,b.IsCombined,
		b.CargoID,b.ProduceDate,b.ValidDate,b.PtypeID
		FROM dbo.gp_inoutPtypeSerial b
		INNER JOIN
		(
			SELECT b.Serial,MAX(b.PostTime) PostTime
			FROM dbo.gp_inoutPtypeSerial b
			INNER JOIN dbo.BillIndex c
			ON b.BillNumberid=c.BillNumberId
			WHERE c.STypeId NOT IN (SELECT  typeid FROM #stype)
			AND b.Serial IN
			(
				SELECT Serial
				FROM dbo.gp_CruPtypeSerial
				WHERE STypeId IN (SELECT  typeid FROM #stype)
			)
			GROUP BY b.Serial
		) c
		ON b.Serial=c.Serial
		WHERE b.PostTime=c.PostTime
	) b
	WHERE gp_CruPtypeSerial.STypeId IN (SELECT  typeid FROM #stype)
	
	UPDATE dbo.gp_CruPtypeSerial
	SET STypeId=b.STypeID,Flag=CASE WHEN gp_CruPtypeSerial.STATE IN (1,7) THEN 1 ELSE 0 END
	FROM dbo.Stock b
	WHERE gp_CruPtypeSerial.STypeId IN (SELECT  typeid FROM #stype)
	AND gp_CruPtypeSerial.KtypeID=b.TypeID
	
	
	--DELETE FROM GP_LendPTypeSerial WHERE KtypeId IN (SELECT typeid FROM #Ktype)
	
	
	--关于借欠序列号
	
	DELETE FROM gp_LendPtypeSerial 
	WHERE KTypeId IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT  typeid FROM #stype))
	AND Serial IN
	(
		SELECT a.Serial
		FROM gp_LendPtypeSerial a
		WHERE a.KTypeId IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT  typeid FROM #stype)) AND NOT EXISTS(
			SELECT b.Serial
			FROM dbo.gp_inoutPtypeSerial b
			INNER JOIN dbo.BillIndex c
			ON b.BillNumberid=c.BillNumberId
			WHERE b.Serial=a.Serial
			AND c.Stypeid NOT IN (SELECT  typeid FROM #stype)
		)
	)
	
	

	
	UPDATE dbo.gp_LendPtypeSerial
	SET State=b.State,KTypeID=b.KTypeID,BTypeID1=b.BTypeID1,BTypeID2=b.BTypeID2,PtypeID=b.PtypeID
	FROM
	(
		SELECT b.Serial,b.State,CASE WHEN b.InKtypeID IS NULL THEN b.OutKtyeID ELSE b.InKTypeID END KTypeID,
		b.BTypeID1,b.BTypeID2,b.PTypeID
		FROM dbo.gp_inoutPtypeSerial b
		INNER JOIN
		(
			SELECT b.Serial,MAX(c.PostTime) PostTime
			FROM dbo.gp_inoutPtypeSerial b
			INNER JOIN dbo.LendIndex c
			ON b.BillNumberid=c.BillNumberId
			WHERE c.STypeId NOT IN (SELECT  typeid FROM #stype)
			AND b.Serial IN
			(
				SELECT Serial
				FROM dbo.gp_LendPtypeSerial
				WHERE KTypeId IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT  typeid FROM #stype))
			)
			GROUP BY b.Serial
		) c
		ON b.Serial=c.Serial
		WHERE b.PostTime=c.PostTime
	) b
	WHERE gp_LendPtypeSerial.KTypeId IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT  typeid FROM #stype))
	
	
	
	
	
	
	--DELETE FROM dbo.gp_FactPtypeSerial WHERE KTypeID IN(SELECT TypeID FROM #Ktype)
	
	
	
	--关于实物序列号
	DELETE FROM gp_FactPtypeSerial 
	WHERE STypeId IN (SELECT  typeid FROM #stype)
	AND Serial IN
	(
		SELECT a.Serial
		FROM gp_FactPtypeSerial a
		WHERE a.STypeId IN (SELECT  typeid FROM #stype) AND NOT EXISTS(
			SELECT b.Serial
			FROM dbo.Fact_InoutPtypeSerial b
			INNER JOIN dbo.BillIndex c
			ON b.BillNumberid=c.BillNumberId
			WHERE b.Serial=a.Serial
			AND c.Stypeid NOT IN (SELECT  typeid FROM #stype)
		)
	)
	
	
	
	UPDATE dbo.gp_FactPtypeSerial
	SET State=b.State,KTypeID=b.KTypeID,PtypeID=b.PtypeID
	FROM
	(
		SELECT b.Serial,b.State,CASE WHEN b.InKtypeID IS NULL THEN b.OutKtyeID ELSE b.InKTypeID END KTypeID,b.PtypeID
		FROM dbo.Fact_InoutPtypeSerial b
		INNER JOIN
		(
			SELECT b.Serial,MAX(b.PostTime) PostTime
			FROM dbo.Fact_InoutPtypeSerial b
			INNER JOIN dbo.BillIndex c
			ON b.BillNumberid=c.BillNumberId
			WHERE c.STypeId NOT IN (SELECT  typeid FROM #stype)
			AND b.Serial IN
			(
				SELECT Serial
				FROM dbo.gp_FactPtypeSerial
				WHERE STypeId IN (SELECT  typeid FROM #stype)
			)
			GROUP BY b.Serial
		) c
		ON b.Serial=c.Serial
		WHERE b.PostTime=c.PostTime
	) b
	WHERE gp_FactPtypeSerial.STypeId IN (SELECT  typeid FROM #stype)
	
	
	
	
	UPDATE dbo.gp_FactPtypeSerial
	SET STypeId=b.STypeID
	FROM dbo.Stock b
	WHERE gp_FactPtypeSerial.STypeId IN (SELECT  typeid FROM #stype)
	AND gp_FactPtypeSerial.KtypeID=b.TypeID
	
	
	
	DELETE FROM dbo.FactStocks WHERE KTypeID IN(SELECT TypeID FROM #Ktype)
	DELETE FROM dbo.FactStocks_Qty WHERE KTypeID IN(SELECT TypeID FROM #Ktype)
	
	DELETE FROM dbo.CommissionStock WHERE Stypeid IN (SELECT  typeid FROM #stype)	
	DELETE FROM dbo.CommissionStock_Qty WHERE Stypeid IN (SELECT  typeid FROM #stype)	
	DELETE FROM dbo.BillIndex			WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
	AND BillType NOT IN(84,85,78,213,212,214,307,410,411)
	
	--反开账删除往来核销单
	DELETE dbo.BillIndex WHERE draft=1 AND IsIni=0 AND BillType=450

	DELETE FROM dbo.ReceiptBillIndex    WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
	DELETE FROM dbo.LendIndex			WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)

	--反开账删除物流类单据
	DELETE FROM Transportbill		WHERE BillNumberID IN (SELECT BillNumberID FROM BillIndex WHERE BillType=414 AND Stypeid IN (SELECT typeid from #stype))
	DELETE FROM BillIndex			WHERE BillType=414 AND Stypeid IN (SELECT typeid from #stype)
	DELETE FROM PickBill			WHERE BillNumberID IN (SELECT BillNumberID FROM onShelvespickIndex WHERE BillType=413 AND Stypeid IN (SELECT typeid from #stype))
	DELETE FROM onShelvesbill		WHERE BillNumberID IN (SELECT BillNumberID FROM onShelvespickIndex WHERE BillType=413 AND Stypeid IN (SELECT typeid from #stype))
	DELETE FROM onShelvespickIndex	WHERE Stypeid	   IN (SELECT typeid from #stype)

	--系统重建所有锁库数据进行解锁
	TRUNCATE TABLE PT_SaleOrderLockDetail		 		--清除订单锁库信息
	UPDATE Ini_GOODSSTOCKS_QTY SET LockNumber=0 --清楚期初锁库信息
	UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
	UPDATE OrderBill SET LockNumber=0 --清除订单锁库信息
	UPDATE PT_Combin_OrderBillDetail SET LockNumber=0 --清除组合品订单锁库信息
	--处理借欠反开账
	IF EXISTS (SELECT TOP 1 1 FROM dbo.IniGoodsLend)
	BEGIN
		--存在修改
		 UPDATE A SET	A.Qty=ISNULL(A.Qty,0)-ISNULL(B.Qty,0),
						A.NQty=ISNULL(A.NQty,0)-ISNULL(B.NQty,0),
						A.LendQty=ISNULL(A.LendQty,0)-ISNULL(B.LendQty,0),
						A.NLendQty=ISNULL(A.NLendQty,0)-ISNULL(B.NLendQty,0),
						A.BorrowQty=ISNULL(A.BorrowQty,0)-ISNULL(B.BorrowQty,0),
						A.NBorrowQty=ISNULL(A.NBorrowQty,0)-ISNULL(B.NBorrowQty,0)
		 FROM dbo.GoodsLend A INNER JOIN dbo.IniGoodsLend B ON A.BTypeID=B.BTypeID AND 
															   A.PTypeID=B.PTypeID AND 
															   A.KTypeID=B.KTypeID AND
															   A.GoodsOrder=B.GoodsOrder AND 
															   A.GoodsNumber=B.GoodsNumber AND 
															   A.ItemID=B.ItemID AND 
															   A.Iscombined=B.Iscombined AND
															   A.ProduceDate=B.ProduceDate AND
															   A.ValidDate=B.ValidDate

		DELETE FROM dbo.GoodsLend WHERE ISNULL(Qty,0)=0 AND ISNULL(NQty,0)=0 AND 
										ISNULL(LendQty,0)=0 AND ISNULL(NLendQty,0)=0 AND
										ISNULL(BorrowQty,0)=0 AND ISNULL(NBorrowQty,0)=0
	END
	-----------------
	--修改开账标识
	UPDATE SType_UserConfig SET Value = '0' WHERE STypeID IN (SELECT  typeid FROM #stype)
	UPDATE dbo.BillIndex		SET draft=1 WHERE IsIni=1 AND ifYearBill=0 AND Stypeid IN (SELECT  typeid FROM #stype)	
	AND BillType NOT IN(84,85,78,213,212,214,307,410,411)		
	UPDATE dbo.ReceiptBillIndex SET draft=1 WHERE IsIni=1 AND ifYearBill=0 AND Stypeid IN (SELECT  typeid FROM #stype)	
	UPDATE dbo.LendIndex		SET draft=1 WHERE IsIni=1 AND ifYearBill=0 AND Stypeid IN (SELECT  typeid FROM #stype)		
	--所有分支机构都反开账了
	IF NOT EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE ConfigNo = '1' AND Value = '1')
	BEGIN		
		UPDATE Sysdata SET SubValue = 'T' WHERE SubName = 'inicanmodify'
	END
	
	--------------会员储值反开账---------------
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='ProInfo' AND SubValue=2)
	BEGIN
		DECLARE @VipCardCode VARCHAR(100)
		UPDATE A 
		SET 
			A.cZyeMoney=A.cZyeMoney-B.cZyeMoney,
			A.QcCzMoney=A.QcCzMoney-B.QcCzMoney
			--A.TotalMoney=A.TotalMoney-B.LjXFMoney
			--A.LjCzMoney=A.LjCzMoney-B.LjCzMoney,
			--A.xFczMoney=A.xFczMoney-B.lJxFczMoney,
		FROM dbo.nVipCardSign A ,
		(
			SELECT ISNULL(SUM(qCczMoney),0) AS qCczMoney,
				   ISNULL(SUM(cZyeMoney),0) AS cZyeMoney,
				   VipCardID
				   --ISNULL(SUM(lJczMoney),0) AS lJczMoney,
				   --ISNULL(SUM(lJxFczMoney),0) AS lJxFczMoney,
				   --ISNULL(SUM(lJxFMoney),0) AS lJxFMoney,
			FROM dbo.nVipCardSignStype C INNER JOIN #stype S ON C.StypeID=S.TypeID
			GROUP BY VipCardID
		) B
		WHERE A.VipCardID=B.VipCardID
	END
	
	-----------------会员卡负值验证---------------
	SELECT TOP 1 
		 @VipCardCode=A.VipCardCode
	FROM dbo.nVipCardSign A 
	INNER JOIN nVipCardSignStype B ON A.VipCardID=B.VipCardID
	INNER JOIN #SType S ON B.StypeId=S.TypeID
	WHERE A.cZyeMoney<0
	
	IF ISNULL(@VipCardCode,'')<>''
	BEGIN
		IF @proinfo=2
		BEGIN
			SET @rValue='当前分支机构反开账会造成会员卡【'+@VipCardCode+'】的总计储值余额为负数，不能反开账，请确认后再试！'
		END
		ELSE
		BEGIN
			SET @rValue='当前反开账会造成会员卡【'+@VipCardCode+'】的总计储值余额为负数，不能反开账，请确认后再试！'
		END
		SET @Re=-1
		GOTO ERROR
	END
	--------------会员储值反开账---------------
	
	--------------优惠券反开账---------------
	--DELETE FROM Coupon_InBill where billnumberid in (select billnumberid  from Coupon_BillIndex  WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype))
	--DELETE FROM Coupon_OutBill where billnumberid in (select billnumberid  from Coupon_BillIndex  WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype))
	--DELETE FROM Coupon_OutBill_Ptype where billnumberid in (select billnumberid  from Coupon_BillIndex  WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype))
	--DELETE FROM Coupon_AllotBill where billnumberid in (select billnumberid  from Coupon_BillIndex  WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype))
	--DELETE FROM Coupon_BackBill where billnumberid in (select billnumberid  from Coupon_BillIndex  WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype))
	--DELETE FROM dbo.Coupon_BillIndex WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
	----不存在过账单据
	----券编码状态回写
	--DELETE FROM Coupon_CodeInfo WHERE IsIni<>1 AND  ktypeid IN (SELECT typeid FROM  stock  WHERE Stypeid IN (SELECT  typeid FROM #stype))
	----UPDATE Coupon_CodeInfo SET [STATE]=1 WHERE IsIni=1  红冲操作要处理 追溯到原始状态
	--UPDATE Coupon_CodeInfo SET inistate=[state]
	
	--DELETE FROM Coupon_BillUsed WHERE BillnumberId IN 
	--DELETE FROM dbo.Coupon_CodeInOut WHERE  billnumberid in (select billnumberid  from Coupon_BillIndex  WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)) 
	--UPDATE Coupon_BillIndex SET  draft=1 WHERE IsIni=1 AND ifYearBill=0 AND Stypeid IN (SELECT  typeid FROM #stype)	
	
	--删除红蓝单
	CREATE TABLE #Coupon_RedWord(BillNumberId NUMERIC(18,0))
	INSERT INTO #Coupon_RedWord(BillNumberId) SELECT BillNumberId FROM coupon_BillIndex WHERE redword IN (1,2) AND stypeid IN (SELECT typeid from #stype)
	DELETE FROM Coupon_InBill where billnumberid in (select billnumberid FROM #Coupon_RedWord)
	DELETE FROM Coupon_OutBill where billnumberid in (select billnumberid FROM #Coupon_RedWord)
	DELETE FROM Coupon_OutBill_Ptype where billnumberid in (select billnumberid FROM #Coupon_RedWord)
	DELETE FROM Coupon_AllotBill where billnumberid in (select billnumberid FROM #Coupon_RedWord)
	DELETE FROM Coupon_BackBill where billnumberid in (select billnumberid FROM #Coupon_RedWord)
	DELETE FROM Coupon_BillIndex where billnumberid in (select billnumberid FROM #Coupon_RedWord)
	
	--------------优惠券反开账---------------
	
	DROP TABLE #Ktype,#stype,#Coupon_RedWord	
END

ACCOUNT:
	IF @CkAccount=1
	BEGIN
		EXEC @Re=P_MF_BackIni @STypeID,@rValue OUT
		IF @Re<>0
			GOTO ERROR	
END
IF @@ERROR <> 0
BEGIN		
	SET @Re=-1				
	GOTO ERROR
END						
ELSE
	RETURN 0
	
ERROR:
	SET @ReturnValue = @rValue
	RETURN @Re	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	

/*

DECLARE
	@STypeId		VARCHAR(MAX),		--	分支机构
	@CkAccount		INT,				--	=1 总账开账
	@CkBuisness     INT,				--  =1 业务开账
    @returnValue	VARCHAR(MAX),
    @nRet			INT
    
SELECT
	@STypeId='00002000010000100001000010000100001000010000100001',
	@CkAccount=1,
	@CkBuisness=1

BEGIN TRAN

EXEC @nRet=Gp_BackIniAll
		@STypeId,
		@CkAccount,
		@CkBuisness,
		@returnValue out	--  输出信息


SELECT @nRet,@returnValue


SELECT * FROM dbo.gp_CruPtypeSerial

SELECT * FROM dbo.gp_inoutPtypeSerial

ROLLBACK TRAN

*/





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-05-13
	描述：分支机构反开账总账部分处理
*/
CREATE PROCEDURE Gp_BackOkIni_Account
(
	@MxSTypeId	VARCHAR(50),			-- 明细分支机构
	@rValue		VARCHAR(400) OUTPUT		-- 输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--非独立分支机构直接返回，没有需要处理的数据
IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId = @MxSTypeId AND IsSelfVerify = 0)
	RETURN 0

IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId AND IsUse = 0)
	RETURN 0	

--获取会计年度和会计期间
DECLARE @FYear		VARCHAR(10),
		@FPeriod	INT,
		@SFullName	VARCHAR(100),
		@Version		INT
SELECT @Version=SubValue FROM dbo.sysdata WHERE SubName='ProInfo' 
--SELECT @FYear = SubValue FROM sysdata WHERE SubName = 'FYear'
--SELECT @FPeriod = SubValue FROM sysdata WHERE SubName = 'FPeriod'
SELECT @FYear = FYear FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId
SELECT @FPeriod = FPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId
SELECT @SFullName=FullName FROM dbo.SType WHERE TypeId=@MxSTypeId

----先比较ac_balance和ac_iniaccount两表中都有的科目币别数据是否相等
IF EXISTS(SELECT TOP 1 1 FROM 
          (SELECT ATypeId,Cid,FBeginBalance,FBeginBalanceFor FROM dbo.Ac_Balance WHERE Cid<>0 AND FYear=@FYear AND FPeriod=@FPeriod AND STypeId=@MxSTypeId)  ab   --ac_balance
          JOIN (SELECT ATypeId,Cid,iniTotal,iniTotalFor FROM dbo.Ac_IniAccount WHERE STypeId=@MxSTypeId) ai   --ac_iniaccount
          ON ab.ATypeId=ai.ATypeId AND ab.Cid=ai.Cid AND  (ab.FBeginBalance!=ai.iniTotal OR ab.FBeginBalanceFor!=ai.iniTotalFor)
          )
     BEGIN
		IF @Version=2
			SET @rValue ='分支机构【'+@SFullName+ '】存在凭证，请删除后再试！'
		ELSE
			SET @rValue ='系统中存在凭证，请删除后再试！'
		RETURN -2
     END
----特殊：ac_iniaccount表中科目没有某个币别数据（某币别没录数据，所以该表没该条记录），ac_balance中科目有值的情况（做了凭证），它的期末得是0，才能反开账
IF EXISTS(SELECT TOP 1 1 FROM
		  (SELECT ATypeId,Cid,FEndBalance,FEndBalanceFor FROM dbo.Ac_Balance WHERE cid<>0 AND FYear=@FYear AND FPeriod=@FPeriod AND STypeId=@MxSTypeId)  ab   --ac_balance 
		  LEFT JOIN  (SELECT ATypeId,Cid FROM dbo.Ac_IniAccount WHERE STypeId=@MxSTypeId) ai   --ac_iniaccount
		  ON ab.ATypeId=ai.ATypeId AND ab.Cid=ai.Cid 
		  WHERE ai.ATypeId IS NULL AND (ab.FEndBalance!=0 OR ab.FEndBalanceFor!=0)
         )
  BEGIN
  	  IF @Version=2
			SET @rValue ='分支机构【'+@SFullName+ '】存在凭证，请删除后再试！'
		ELSE
			SET @rValue ='系统中存在凭证，请删除后再试！'
	  RETURN -2  
  END

-------------------------期初数据吻合，开始处理数据(删除凭证有关表的数据)
BEGIN TRANSACTION
DECLARE @errorSum INT 
SET @errorSum=0  --初始化为，即无错误

DELETE FROM dbo.Ac_Balance WHERE STypeId=@MxSTypeId 
SET @errorSum=@errorSum+@@error   

DELETE FROM dbo.Ac_Balance_Assist_CheckItems WHERE STypeId=@MxSTypeId  
SET @errorSum=@errorSum+@@error

DELETE FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE STypeId=@MxSTypeId   
SET @errorSum=@errorSum+@@error

DELETE FROM Ac_Provision_Voucher WHERE VoucherId IN (SELECT BillNumberId FROM dbo.Ac_Voucher_Bill WHERE STypeId=@MxSTypeId)
SET @errorSum=@errorSum+@@error

DELETE FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId IN (SELECT BillNumberId FROM dbo.Ac_Voucher_Bill WHERE STypeId=@MxSTypeId)
SET @errorSum=@errorSum+@@error
DELETE FROM Ac_ReceiptBill_VoucherBill WHERE VourchBillId IN (SELECT BillNumberId FROM dbo.Ac_Voucher_Bill WHERE STypeId=@MxSTypeId)
SET @errorSum=@errorSum+@@error
DELETE FROM Ac_CommissionBill_VoucherBill WHERE VourchBillId IN (SELECT BillNumberId FROM dbo.Ac_Voucher_Bill WHERE STypeId=@MxSTypeId)
SET @errorSum=@errorSum+@@error

DELETE FROM dbo.Ac_Voucher_Bill WHERE  STypeId=@MxSTypeId   
SET @errorSum=@errorSum+@@error

DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.Ac_Voucher WHERE STypeId=@MxSTypeId)  
SET @errorSum=@errorSum+@@error

DELETE FROM dbo.Ac_Voucher_Bill_CashMoneyItems WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.Ac_Voucher WHERE STypeId=@MxSTypeId)    
SET @errorSum=@errorSum+@@error

DELETE FROM dbo.Ac_Voucher WHERE STypeId=@MxSTypeId  
SET @errorSum=@errorSum+@@error

--DELETE FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid=@MxSTypeId
--SET @errorSum=@errorSum+@@error

--更新当前期间为启用期间
UPDATE Ac_AccountsPeroid_Stype SET FYear = SFYear,FPeriod = SFPeriod,IsUse = 0 WHERE Stypeid = @MxSTypeId
SET @errorSum=@errorSum+@@error

-----Ac_ProfitAndLoss，Ac_ProfitAndLoss_Detail 
 
IF @errorSum<>0  --如果有错误
  BEGIN
    ROLLBACK TRANSACTION 
    SET @rValue = '处理分支机构【'+@SFullName+ '】凭证数据或期间数据时失败，请确认后再试'
    RETURN -2  
  END  
ELSE
  BEGIN
    COMMIT TRANSACTION   
    RETURN 0
  END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *FROM    dbo.sysobjects WHERE   id = OBJECT_ID(N'[dbo].[GP_BankRange_Del]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_BankRange_Del]
GO
/*
出纳银行操作员多级权限范围删除
彭勇  2017-07-08
*/
CREATE PROCEDURE GP_BankRange_Del(
      @UserID VARCHAR(50) ,
      @Type INT ,
      @TypeID VARCHAR(200),
      @IsUserGroupLimit BIT  --是否设置角色权限
    )
--@encode$--
AS 
    SET NOCOUNT ON 

    DECLARE @ManTypeIDName VARCHAR(50) ,
        @TableName VARCHAR(50) ,
        @AllManID VARCHAR(50) ,
        @SQL VARCHAR(2000) ,
        @atypeType CHAR(1) ,
        @SchemeType VARCHAR(20)		--基本信息样式名称，如rmetype则赋值是etype

--------

IF @IsUserGroupLimit = 1
BEGIN
	IF @TypeID = '00000' 
	   BEGIN
	--清理LoginUser
		  IF EXISTS(SELECT TOP 1 1 FROM dbo.UserGroupLimit WHERE etypeid=@UserID AND MangerBankID='00000') 
			UPDATE dbo.UserGroupLimit SET MangerBankID='-99999' WHERE etypeid=@UserID           
	--清理相应的bank_l
		   DELETE FROM dbo.UgBank_l WHERE etypeid=@UserID AND typeid='00000'  
		 END
	--删除叶子节点
	ELSE 
	BEGIN
		DELETE FROM dbo.UgBank_l WHERE etypeid=@UserID AND typeid=@TypeID 
	END

	RETURN 0
	
END
ELSE 
BEGIN
	IF @TypeID = '00000' 
	   BEGIN
	--清理LoginUser
		  IF EXISTS(SELECT TOP 1 1 FROM dbo.loginuser WHERE etypeid=@UserID AND MangerBankID='00000') 
			UPDATE dbo.loginuser SET MangerBankID='-99999' WHERE etypeid=@UserID           
	--清理相应的bank_l
		   DELETE FROM dbo.Bank_l WHERE etypeid=@UserID AND typeid='00000'  
		 END
	--删除叶子节点
	ELSE 
		BEGIN
			DELETE FROM dbo.Bank_l WHERE etypeid=@UserID AND typeid=@TypeID 
		END

	--POS下载处理
	EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'
		RETURN 0
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GP_BankRange_Insert]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
  DROP PROCEDURE [dbo].[GP_BankRange_Insert]
GO
/*
出纳银行操作员多级权限范围设置
彭勇  2017-07-08
*/
CREATE PROCEDURE GP_BankRange_Insert (
	 @UserID	VARCHAR(50),---设置的操作员
	 @type      INT,
	 @TypeIDs	VARCHAR(MAX),--所选的银行id
	 @IsUserGroupLimit INT
)
--@encode$--
AS 
SET NOCOUNT ON 
-- 修改LoginUser表
--@TypeIDs 为00000表示所有当前type的权限
--'-99999'表示并非拥有所有权限

--先处理分组权限，如果UserGroupLimit中没有，则插入新记录
IF NOT EXISTS(SELECT TOP 1 1 FROM UserGroupLimit WHERE EtypeID = @UserID) AND @IsUserGroupLimit=1
BEGIN
	INSERT UserGroupLimit(EtypeID,MangerETypeID,MangerPTypeID,MangerKTypeID,MangerSTypeID,MangerDTypeID,MangerBTypeID,MangerBTypeID2,MangerATypeID,MangerRevenue,MangerOwnerEquity,MangerExpense,MangerIncome,MangerCpaital,MangerOtherCpaital,MangerLiabilities,MangerPay,MangerBankID)
				   VALUES(@UserID,'-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999','-99999')
END

CREATE TABLE #TYPEIDS(typeid VARCHAR(50))
DECLARE @TypeID VARCHAR(200)
DECLARE @numCount INT

IF @IsUserGroupLimit = 1
BEGIN
	IF @TypeIDs <> '00000' 
	 BEGIN
		UPDATE UserGroupLimit SET MangerBankID='-99999' WHERE etypeid=@UserID
		DELETE FROM  dbo.UgBank_l  WHERE ETypeID =@UserID AND typeid='00000'
	 END
	ELSE
	  BEGIN 
		UPDATE UserGroupLimit SET MangerBankID='00000' WHERE etypeid=@UserID
		DELETE FROM  dbo.UgBank_l  WHERE ETypeID =@UserID
	  END	

	INSERT INTO #Typeids SELECT a FROM f_split(@TypeIDs, ',')

	DECLARE UserRange_Cursor CURSOR FOR SELECT * FROM #Typeids
	OPEN UserRange_Cursor
	FETCH NEXT FROM UserRange_Cursor INTO @TypeID
	WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT TOP 1  1 f FROM dbo.UgBank_l WHERE etypeid=@UserID AND typeid=@TypeID 
			IF @@ROWCOUNT = 1 
			BEGIN
				CLOSE UserRange_Cursor
				DEALLOCATE UserRange_Cursor
				RETURN -2
			END
		IF NOT EXISTS( SELECT TOP 1 1 FROM  dbo.UgBank_l WHERE ETypeID=@UserID AND TypeID=@TypeID)
		  BEGIN
			INSERT INTO  dbo.UgBank_l( etypeid, typeid, flag )
			VALUES (@UserID,@TypeID,1)
		  END
		 ELSE
			BEGIN
			   UPDATE UgBank_l SET flag = 0 WHERE ETypeID = @UserID AND TypeID =@TypeID	
			END  
		FETCH NEXT FROM UserRange_Cursor INTO @TypeID
	END
	CLOSE UserRange_Cursor
	DEALLOCATE UserRange_Cursor

	-- 超过500条设置记录，不允许
	SELECT  @numCount=COUNT(1)  FROM dbo.UgBank_l WHERE etypeid=@UserID
	IF @numCount > 5000
		RETURN -4
		
	RETURN 0
END
ELSE  --loginuser 
BEGIN
	IF @TypeIDs <> '00000' 
	 BEGIN
		UPDATE LoginUser SET MangerBankID='-99999' WHERE etypeid=@UserID
		 DELETE FROM  dbo.Bank_l  WHERE ETypeID =@UserID AND typeid='00000'
	 END
	ELSE
	  BEGIN 
		UPDATE LoginUser SET MangerBankID='00000' WHERE etypeid=@UserID
		DELETE FROM  dbo.Bank_l  WHERE ETypeID =@UserID
	  END	

	INSERT INTO #Typeids SELECT a FROM f_split(@TypeIDs, ',')

	DECLARE UserRange_Cursor CURSOR FOR SELECT * FROM #Typeids
	OPEN UserRange_Cursor
	FETCH NEXT FROM UserRange_Cursor INTO @TypeID
	WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT TOP 1  1 f FROM dbo.Bank_l WHERE etypeid=@UserID AND typeid=@TypeID 
			IF @@ROWCOUNT = 1 
			BEGIN
				CLOSE UserRange_Cursor
				DEALLOCATE UserRange_Cursor
				RETURN -2
			END
		IF NOT EXISTS( SELECT TOP 1 1 FROM  dbo.Bank_l WHERE ETypeID=@UserID AND TypeID=@TypeID)
		  BEGIN
			INSERT INTO  dbo.Bank_l( etypeid, typeid, flag )
			VALUES (@UserID,@TypeID,1)
		  END
		 ELSE
			BEGIN
			   UPDATE Bank_l SET flag = 0 WHERE ETypeID = @UserID AND TypeID =@TypeID	
			END  
		FETCH NEXT FROM UserRange_Cursor INTO @TypeID
	END
	CLOSE UserRange_Cursor
	DEALLOCATE UserRange_Cursor

	-- 超过500条设置记录，不允许
	SELECT  @numCount=COUNT(1)  FROM dbo.Bank_l WHERE etypeid=@UserID
	IF @numCount > 5000
		RETURN -4
	
	--POS下载处理
	EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'
	RETURN 0
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  * FROM    dbo.sysobjects WHERE   id = OBJECT_ID(N'[dbo].[GP_BankRange_Query]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_BankRange_Query]
GO
/*
操作员出纳银行多级权限范围设置 - 查询

modify by 彭勇
date: 2014-07-08
添加多级权限子权限
*/
CREATE PROCEDURE GP_BankRange_Query(
      @UserID VARCHAR(200), 
      @Type INT,
      @IsUserGroupLimit BIT
    )
--@encode$--	
AS 
SET NOCOUNT ON 
CREATE TABLE #temp(
	  UserCode VARCHAR(200) ,
	  FullName VARCHAR(200) ,
	  TypeID VARCHAR(200) ,
	  URL VARCHAR(3000)
 )
 

IF @IsUserGroupLimit = 1
BEGIN
	--UserGroupLimit, 是否拥有所有权限			
	IF EXISTS(SELECT TOP 1 1 FROM dbo.UserGroupLimit WHERE etypeid=@UserID AND MangerBankID!='-99999')
	BEGIN
	  INSERT INTO #temp ( UserCode, FullName, TypeID, URL )
	  VALUES  ( '', '全部出纳银行','00000','全部出纳银行' )
	END					
	-- UserGroupLimit, 查询bank_l表获取数据
	IF NOT EXISTS ( SELECT TOP 1 1 FROM  #temp ) 
	BEGIN
	  INSERT INTO #temp( UserCode, FullName, TypeID )
	  SELECT b.UserCode,b.FullName,a.typeid FROM dbo.UgBank_l a 
	  INNER JOIN   Te_BankAccount b ON a.typeid=b.Id
	  AND etypeid=@UserID AND flag=1
	END
END
ELSE
BEGIN
	--查询loginUser, 是否拥有所有权限			
	IF EXISTS(SELECT TOP 1 1 FROM dbo.loginuser WHERE etypeid=@UserID AND MangerBankID!='-99999')
	BEGIN
	  INSERT INTO #temp ( UserCode, FullName, TypeID, URL )
	  VALUES  ( '', '全部出纳银行','00000','全部出纳银行' )
	END					
	-- 如果loginUser没有取到数据, 查询bank_l表获取数据
	IF NOT EXISTS ( SELECT TOP 1 1 FROM  #temp ) 
	BEGIN
	  INSERT INTO #temp( UserCode, FullName, TypeID )
	  SELECT b.UserCode,b.FullName,a.typeid FROM dbo.Bank_l a 
	  INNER JOIN   Te_BankAccount b ON a.typeid=b.Id
	  AND etypeid=@UserID AND flag=1
	END
END 


-- 如果不存在UserCode为空字符的
-- 处理'路径'信息
--公用
IF NOT EXISTS ( SELECT TOP 1 1 FROM  #temp WHERE UserCode='' )
BEGIN
	UPDATE dbo.#temp SET URL='\全部出纳银行\'+FullName
END

SELECT  * FROM    #temp ORDER BY UserCode , URL
DROP TABLE #temp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** Object:  StoredProcedure [dbo].[GP_BarCodeAdd]    Script Date: 04/25/2012 10:45:14 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_BarCodeAdd]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_BarCodeAdd]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*====================================
	作者：杜国蕾
	日期：2012-04-21
	描述：添加条形码规则
======================================*/
CREATE PROCEDURE [dbo].[GP_BarCodeAdd]
 (
	 @BarcodeId int,
	 @StartNum varchar(20),
	 @EndNum varchar(20),
	 @SourceID varchar(10)
 )
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN

	INSERT INTO dbo.BarCode_Ext VALUES (@BarcodeId,@StartNum,@EndNum,@SourceID)
	
    IF(@@ERROR<>0)
		BEGIN
			ROLLBACK TRAN 
			RAISERROR('新增条码规则失败!请确认后重试!',16,1)
			RETURN
		END
		
COMMIT TRAN

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


CREATE           PROCEDURE GP_BarCodeQueryMore 
(

@OperatorID	VARCHAR(50),
@FullName	VARCHAR(50),
@BarCode	VARCHAR(100),
@UserCode	VARCHAR(50),
@flag		VARCHAR(10)

)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--=====================================================权限检查=====================================================
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
--PRINT(@MPtypeid)
IF @Re<>0 RETURN @Re

--==================================================================================================================

IF @Re<>0 RETURN @Re
DECLARE @SQL varchar(8000)
DECLARE @PTypeID varchar(50)

SELECT @PTypeID=@MPTypeID

IF	@PTypeID=''
SET @PTypeID='%'
IF	@FullName=''
SET	@FullName='%'
IF	@UserCode=''
SET	@UserCode='%'


IF (@BarCode='')
  BEGIN
  SELECT @SQL='
         		SELECT 	TypeID,
						UserCode,
						Name,
						FullName,
						Standard,
						Area,
						EntryCode,
						preprice1,
						preprice2,
						preprice3,
						preprice4
				FROM
						PType
				WHERE
						TypeID LIKE '+char(39)+@Ptypeid+'%'+char(39)+'
						AND	sonnum=''0''
						AND	FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
						AND	UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
						AND Deleted = ''0''
  '
	END
	ElSE
	BEGIN
	SELECT @SQL='
         		SELECT 	TypeID,
						UserCode,
						Name,
						FullName,
						Standard,
						Area,
						EntryCode,
						preprice1,
						preprice2,
						preprice3,
						preprice4
				FROM
						PType
				WHERE
						TypeID LIKE '+char(39)+@Ptypeid+'%'+char(39)+'
						AND	sonnum=''0''
						AND	FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
						AND	EntryCode	LIKE '+char(39)+'%'+@BarCode+'%'+char(39)+'
						AND	UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
						AND Deleted = ''0''
  '
	
	END
	IF @Flag = '1' 
	SET @SQL = 'SELECT * FROM ('+@SQL+') X WHERE EntryCode is not Null AND EntryCode<>''''' + 'ORDER BY X.UserCode'
	ELSE	
	SET	@SQL =@SQL +'ORDER BY UserCode'
EXEC(@SQL)
--PRINT(@SQL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_BarCodeSetDefaultRule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

drop procedure [dbo].[GP_BarCodeSetDefaultRule]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*=======================================================================
	作者：杜国蕾
	日期：2012-04-27
	描述：将条形码单据规则设置为默认条码规则
========================================================================*/

CREATE PROCEDURE [dbo].[GP_BarCodeSetDefaultRule]
(
	@BarCodeID		INT		--BarCode中ID
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @id			INT       --记录原始默认规则值id


BEGIN TRAN
	--IF EXISTS(SELECT TOP 1 1 FROM dbo.BarCode WHERE dbo.BarCode.IsDefault=1)	
		--BEGIN
			SELECT @id=ID  FROM BarCode    WHERE BarCode.IsDefault=1 AND IsPrint=1	  --取原有默认规则ID  
			UPDATE BarCode SET IsDefault=1,IsPrint=1 WHERE ID = @BarCodeID			  --设置新默认规则为1
			UPDATE BarCode SET IsDefault=0 WHERE ID <> @BarCodeID			          --将原有默认值还原为0
			UPDATE BarCodeForBilltype SET BarCodeID =@BarCodeID where (BarCodeID=@id OR BarCodeID=0)		--将关联的条码规则赋值
		--END
		
		IF(@@ERROR<>0)
				BEGIN
					ROLLBACK TRAN
					RAISERROR('设置默认条码规则失败!请确认后重试!',16,1)
					RETURN
				END
		
COMMIT TRAN	 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_Base_SaveFixedReasonForChange]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_Base_SaveFixedReasonForChange
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回变更原因列表
-- 时间：	2016-05-12
-- 作者：	lxl
-- ========================================================================
CREATE PROC Gp_Base_SaveFixedReasonForChange
(
	@NID			INT,			--类型ID
	@UserCode		VARCHAR(200),	--编号
	@FullName		VARCHAR(200),	--名称
	@Comment		VARCHAR(1000),	--备注
	@GridData		Type_FixedReasonForChangeDetails READONLY,
	@Type			INT				--1新增  2：复制新增 3：编辑
)

--@encode$--
AS
SET NOCOUNT ON 

DECLARE	
	@Name	VARCHAR(200),
	@Error	INT=0
	
--判断编号是否重复
SELECT @Name=FullName FROM Base_FixedReasonForChange WHERE  UserCode=@usercode AND ((@Type=3 AND nId<>@NID) OR @Type<>3)
IF ISNULL(@Name,'')<>''
	BEGIN
		RAISERROR('与【%s】的编号相同 ，请重新进行编号！',16,1,@Name) RETURN
	END
--判断名称是否重复
SELECT @Name=FullName FROM Base_FixedReasonForChange WHERE  FullName=@FullName AND ((@Type=3 AND nId<>@NID) OR @Type<>3)
IF(ISNULL(@Name,'')<>'')
	BEGIN
		RAISERROR('与【%s】的名称相同 ，请重新进行编号！',16,1,@Name) RETURN
	END
BEGIN TRAN
--更新缓存ID
DECLARE @XiWaMaxNumber INT
IF(@Type=1)
	BEGIN
		SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Base_FixedReasonForChange
		INSERT INTO Base_FixedReasonForChange
		(
			UserCode,
			FullName,
			Comment,
			Sysrow,
			XiWaMaxNumber
		) 
		VALUES
		(
			@UserCode,
			@FullName,
			@Comment,
			0,
			@XiWaMaxNumber
		)
		SET @NID=@@IDENTITY
		SET @Error+=@@ERROR
		
		--更新缓存ID
		SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Base_FixedReasonForChangeDetails
		INSERT INTO Base_FixedReasonForChangeDetails
		(
			TID,
			STypeID,
			EnterATypeID,
			ForeignATypeID,
			RateATypeID,
			XiWaMaxNumber
		)
		SELECT
			@NID TID,
			STypeID,
			EnterATypeID,
			ForeignATypeID,
			RateATypeID,
			XiWaMaxNumber
		FROM @GridData
		UNION ALL
		SELECT 
			@NID TID,
			TypeId STypeID,
			'' EnterATypeID,
			'' ForeignATypeID,
			'' RateATypeID,
			'' XiWaMaxNumber
		FROM SType WHERE TypeId<>'00000' AND TypeId NOT IN(SELECT STypeID FROM @GridData) 
		SET @Error+=@@ERROR
		
		UPDATE Base_FixedReasonForChangeDetails
		SET 
			XiWaMaxNumber=@XiWaMaxNumber,
			@XiWaMaxNumber+=1
		WHERE TID=@NID
		SET @Error+=@@ERROR
	END
ELSE 
	BEGIN
		DECLARE @IsUsed INT=0
		SELECT @IsUsed=dbo.Fn_GetIsUse_Items(@NID,100)
		IF(@IsUsed=1)
			BEGIN
				
				SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Base_FixedReasonForChange
				UPDATE Base_FixedReasonForChange SET Comment=@Comment,XiWaMaxNumber=@XiWaMaxNumber WHERE NID=@NID
				SET @Error+=@@ERROR
			END
		ELSE 
			BEGIN
				UPDATE Base_FixedReasonForChange 
				SET 
					UserCode=@UserCode,
					FullName=@FullName,
					Comment=@Comment
				WHERE NID=@NID
				SET @Error+=@@ERROR
				
				UPDATE D
				SET 
					D.EnterATypeID=G.EnterATypeID,
					D.ForeignATypeID=G.ForeignATypeID,
					D.RateATypeID=G.RateATypeID,
					D.XiWaMaxNumber=@XiWaMaxNumber,
					@XiWaMaxNumber+=1
				FROM Base_FixedReasonForChangeDetails D
				INNER JOIN @GridData G ON G.NID=D.NID AND G.TID=D.TID
				SET @Error+=@@ERROR
			END
	END

IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_Base_SaveFixedReasonForChangeDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_Base_SaveFixedReasonForChangeDetails
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	修改存货类型核算科目明细
-- 时间：	2016-05-12
-- 作者：	lxl
-- ========================================================================
CREATE PROC Gp_Base_SaveFixedReasonForChangeDetails
(
	@GridData	Type_FixedReasonForChangeDetails READONLY
)

--@encode$--
AS
SET NOCOUNT ON 

DECLARE @Error INT=0

BEGIN TRAN

DECLARE @XiWaMaxNumber INT
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Base_FixedReasonForChangeDetails
UPDATE T
SET
	T.EnterATypeID=D.EnterATypeID,
	T.ForeignATypeID=D.ForeignATypeID,
	T.RateATypeID=D.RateATypeID,
	XiWaMaxNumber=@XiWaMaxNumber,
	@XiWaMaxNumber+=1
FROM Base_FixedReasonForChangeDetails T
INNER JOIN @GridData D ON D.TID=T.TID AND D.NID=T.NID AND D.STypeID=T.STypeID
	
SET @Error+=@@ERROR


IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_Base_SaveInventoryType]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_Base_SaveInventoryType
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回存货类型列表
-- 时间：	2016-04-27
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_Base_SaveInventoryType
(
	@NID			INT,			--类型ID
	@UserCode		VARCHAR(200),	--编号
	@FullName		VARCHAR(200),	--名称
	@Comment		VARCHAR(1000),	--备注
	@GridData		Type_InventoryTypeDetails READONLY,
	@Type			INT				--1新增  2：复制新增 3：编辑
)

--@encode$--
AS
SET NOCOUNT ON 

DECLARE	
	@Name	VARCHAR(200),
	@Error	INT=0
	
--判断编号是否重复
SELECT @Name=FullName FROM Base_InventoryType WHERE  UserCode=@usercode AND ((@Type=3 AND nId<>@NID) OR @Type<>3)
IF ISNULL(@Name,'')<>''
	BEGIN
		DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同 ，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1) RETURN
	END
--判断名称是否重复
SELECT @Name=FullName FROM Base_InventoryType WHERE  FullName=@FullName AND ((@Type=3 AND nId<>@NID) OR @Type<>3)
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG1 VARCHAR(100)='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END
BEGIN TRAN
--更新缓存ID
DECLARE @XiWaMaxNumber INT
IF(@Type IN(1,2))
	BEGIN
		SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Base_InventoryType
		INSERT INTO Base_InventoryType
		(
			UserCode,
			FullName,
			Comment,
			Sysrow,
			XiWaMaxNumber
		) 
		VALUES
		(
			@UserCode,
			@FullName,
			@Comment,
			0,
			@XiWaMaxNumber
		)
		SET @NID=@@IDENTITY
		SET @Error+=@@ERROR
		
		--更新缓存ID
		SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Base_InventoryTypeDetails
		INSERT INTO Base_InventoryTypeDetails
		(
			TID,
			STypeID,
			StockATypeID,
			IncomeATypeID,
			CostATypeID
		)
		SELECT
			@NID TID,
			STypeID,
			StockATypeID,
			IncomeATypeID,
			CostATypeID
		FROM @GridData
		UNION ALL
		SELECT 
			@NID TID,
			TypeId STypeID,
			'' StockATypeID,
			'' IncomeATypeID,
			'' CostATypeID
		FROM SType WHERE TypeId<>'00000' AND TypeId NOT IN(SELECT STypeID FROM @GridData) 
		SET @Error+=@@ERROR
		
		UPDATE Base_InventoryTypeDetails
		SET 
			XiWaMaxNumber=@XiWaMaxNumber,
			@XiWaMaxNumber+=1
		WHERE TID=@NID
		SET @Error+=@@ERROR
	END
ELSE 
	BEGIN
		DECLARE @IsUsed INT=0
		SELECT @IsUsed=dbo.Fn_GetIsUse_Items(@NID,100)
		
		SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Base_InventoryType
		UPDATE Base_InventoryType 
		SET
			UserCode=@UserCode,
			FullName=@FullName,
			Comment=@Comment,
			XiWaMaxNumber=@XiWaMaxNumber
		WHERE NID=@NID
		SET @Error+=@@ERROR
		
		UPDATE D
		SET 
			D.StockATypeID=G.StockATypeID,
			D.IncomeATypeID=G.IncomeATypeID,
			D.CostATypeID=G.CostATypeID,
			D.XiWaMaxNumber=@XiWaMaxNumber,
			@XiWaMaxNumber+=1
		FROM Base_InventoryTypeDetails D
		INNER JOIN @GridData G ON G.NID=D.NID AND G.TID=D.TID
		SET @Error+=@@ERROR
	END

IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_Base_SaveInventoryTypeDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_Base_SaveInventoryTypeDetails
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	修改存货类型核算科目明细
-- 时间：	2016-04-29
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_Base_SaveInventoryTypeDetails
(
	@GridData	Type_InventoryTypeDetails READONLY
)

--@encode$--
AS
SET NOCOUNT ON 

DECLARE @Error INT=0

BEGIN TRAN

DECLARE @XiWaMaxNumber INT
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Base_InventoryTypeDetails
UPDATE T
SET
	T.StockATypeID=D.StockATypeID,
	T.IncomeATypeID=D.IncomeATypeID,
	T.CostATypeID=D.CostATypeID,
	XiWaMaxNumber=@XiWaMaxNumber,
	@XiWaMaxNumber+=1
FROM Base_InventoryTypeDetails T
INNER JOIN @GridData D ON D.TID=T.TID AND D.NID=T.NID AND D.STypeID=T.STypeID
	
SET @Error+=@@ERROR


IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



--Category


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_BaseInfoCategoryCheck]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_BaseInfoCategoryCheck]
GO

SET QUOTED_IDENTIFIER OFF
GO

----========================
----创建者：黄 清
----日期：2013-05-10
----描述：基本信息允许分类判断
----========================
CREATE	PROCEDURE	[dbo].[Gp_BaseInfoCategoryCheck]
(
	@ParId [VARCHAR](50),
	@type  [VARCHAR](50)
)
--@encode$--
AS 
SET NOCOUNT ON

 DECLARE @nRETURNtype INT,
			@EtypeId_1 [VARCHAR](50),
			@nSoncount INT,
			@nSonnum INT,
			@leveal SMALLINT
DECLARE @parFullName VARCHAR(200)
	
DECLARE		@result			INT=0,		--自定义接收返回值
			@temptypename	VARCHAR(20)
			
DECLARE @TableName VARCHAR(128)
DECLARE @sql VARCHAR(1500)
DECLARE @basetype VARCHAR(200)
DECLARE @basetypeName VARCHAR(200)
SET @basetype=''
SET @basetypeName=''



IF @type='Ac_CashMoneyItems'
BEGIN	
	DECLARE @Ac_CashMoneyId_1 [varchar](50)
		-- 获得新的ID号
	EXEC @nReturntype=Gp_createId @ParId,'Ac_CashMoneyItems',@Ac_CashMoneyId_1 OUT,@nSonnum OUT,@nSoncount OUT
	IF @nReturntype=-1
		BEGIN
			RAISERROR('现金流量项目的分类不能超过10层',16,1)RETURN--RETURN -1
		END
	IF @nReturntype=-2
		BEGIN
			RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
		END
	RETURN
END


IF @type='P'
BEGIN
	SET @basetype='ptype'
	SET @basetypeName='商品'
	SET @TableName='ptype'
END
IF @type='s'
BEGIN
	SET @basetype='stype'
	SET @basetypeName='分支机构'
	SET @TableName='stype'
END
IF @type='b'
BEGIN
	SET @basetype='btype'
	IF substring(@parid,1,5)='00001'
		SET @basetypeName='客户'
	IF substring(@parid,1,5)='00002'
		SET @basetypeName='供货商'
	SET @TableName='btype'
END
IF @type='k'
BEGIN
	SET @basetype='stock'
	SET @basetypeName='仓库'
	SET @TableName='stock'
END
IF @type='a'
BEGIN
	SET @basetype='atype'
	SET @basetypeName='科目'
	SET @TableName='atype'
END
IF @type='d'
BEGIN
	SET @basetype='department'
	SET @basetypeName='部门'
	SET @TableName='department'
END
IF @type='e'
BEGIN
	SET @basetype='employee'
	SET @basetypeName='职员'
	SET @TableName='employee'
END
IF @type='AreaType'
BEGIN
	SET @basetype='AreaType'
	SET @basetypeName='地区'
	SET @TableName='AreaType'
END

SET @sql='SELECT TOP 1 1 FROM '+@TableName+' WHERE typeId='''+@ParId+''' '
EXEC(@SQL)
IF @@rowcount=0 
	BEGIN
		RAISERROR('该%s不存在，不能分类',16,1,@basetypeName)RETURN 
	END
IF(@ParId<>'00000')
BEGIN
	SET @sql='SELECT TOP 1 1 FROM '+@TableName+' WHERE typeId='''+@ParId+''' AND deleted=1 '
	EXEC(@SQL)
	IF @@rowcount>0 
		BEGIN
			RAISERROR('该%s已经被停用，不能分类',16,1,@basetypeName)RETURN 
		END
END
--判断是否是父类,如果是父类不执行的判断是否允许分类
IF(@ParId<>'00000')
	BEGIN
		DECLARE @count INT,@SQL1 NVARCHAR(MAX)
		SELECT @SQL1= 'SELECT @count=COUNT(*) FROM '+@TableName+' WHERE typeId='''+@ParId+''' AND SONNUM>0'
		EXECUTE sp_executesql @SQL1,N'@count INT OUTPUT',@count OUTPUT
		IF @count>0
			BEGIN
				RETURN 
			END
	END
-----------------------------判断是否在自定义中有关联信息--------------------------------------
IF @type<>'AreaType' AND @type<>'Ac_CashMoneyItems'
BEGIN
	EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@basetype,@ctypeid=@ParId,@result=0
	IF @result=1
	BEGIN
		RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
	END
END
-----------------------------判断是否在自定义中有关联信息--------------------------------------


-----------------------------判断是否在自定义中有关联信息--------------------------------------
IF @type='S' OR @type='b' OR @type='d' or @type='e'
BEGIN
	EXEC	@result=dbo.Gp_DeleteInsert_Ac_Data @Type=@basetype,@typeid=@ParId
	IF @result=1
	BEGIN
			RAISERROR('当前信息已在辅助核算中关联,不可以分类',16,1) RETURN
	END
END
-----------------------------判断是否在自定义中有关联信息--------------------------------------
DECLARE @erromsg VARCHAR(MAX)
--分类判断
BEGIN TRY
	EXEC Gp_BaseInfoCheck @basetype,@parid,'0'
END TRY
BEGIN CATCH
	SELECT @erromsg=ERROR_MESSAGE()
	RAISERROR('%s',16,1,@erromsg)RETURN
END CATCH


--往来单位特殊判断
IF  @type='b'
BEGIN
	IF @ParId='00000'
		RETURN -11
		--关联结算单位	
	IF EXISTS (SELECT typeId FROM dbo.btype WHERE denominatedid=@Parid AND typeId<>@Parid)
		BEGIN
			IF LEFT(@Parid,5) ='00001' -- 客户
				BEGIN
					RAISERROR('当前客户信息已与结算单位关联,不能再分类!',16,1) RETURN 
				END
			ELSE
				BEGIN
					RAISERROR('当前供货商信息已与结算单位关联,不能再分类!',16,1) RETURN 
				END
		END
END
	

-- 获得新的ID号
EXEC @nRETURNtype= Gp_createId @ParId, @TableName, @EtypeId_1 OUT,
    @nSonnum OUT, @nSoncount OUT
IF @nRETURNtype=-1 
BEGIN
	IF @type='b' OR @type='e'
	BEGIN
		RAISERROR('%S的分类不能超过9层',16,1,@basetypeName)RETURN--RETURN -1
	END
	ELSE
	BEGIN
		RAISERROR('%S的分类不能超过10层',16,1,@basetypeName)RETURN--RETURN -1
	END
END
IF @nRETURNtype=-2 
BEGIN
	RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
END



---商品分类判断
IF @type='P'
BEGIN
	IF NOT EXISTS (SELECT *FROM ptype WHERE typeId=@ParId)
	BEGIN
		RAISERROR('该商品不存在，不能分类',16,1)RETURN ---15  
	END
	
	SET @parFullName=(SELECT TOP 1 fullname FROM Ptype WHERE typeid=@parid)

	IF(@ParId<>'00000')
	BEGIN
		--判断停用不能分类
		DECLARE @deleted INT
		SELECT @deleted=deleted FROM Ptype WHERE typeId=@Parid
		IF(@deleted=1)
			BEGIN
				RAISERROR('该商品【%s】已经被停用，不能分类',16,1,@parFullName)RETURN ---15  
			END
	END
	-----------------------------判断是否在自定义中有关联信息--------------------------------------
	SET @temptypename='ptype'

	EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@ParId,@result=0
	IF @result=1
	BEGIN
		RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
	END
	        
	-- 获得新的ID号
    EXEC @nRETURNtype= Gp_createId @ParId, 'ptype', @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
	IF @nRETURNtype=-1 
	BEGIN
		RAISERROR('商品的分类不能超过10层',16,1)RETURN--RETURN -1
	END
	IF @nRETURNtype=-2 
	BEGIN
		RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
END

IF @type='s'
BEGIN
	IF NOT EXISTS (SELECT *FROM stype WHERE typeId=@ParId)
	BEGIN
		RAISERROR('该分支机构不存在，不能分类',16,1)RETURN ---15  
	END
		
	SELECT @parFullName=FullName FROM SType WHERE TypeId=@Parid
	--判断停用不能分类
	SELECT @deleted=deleted FROM [SType] WHERE typeId=@Parid
	IF(@deleted=1)
		BEGIN
		   RAISERROR('该分支机构【%s】已经被停用，不能分类',16,1,@parFullName)RETURN ---15  
		END

	IF EXISTS(SELECT * FROM SType_InnerARTotal WHERE STypeID2=@Parid)
		BEGIN
			 SELECT @parFullName=FullName FROM SType WHERE TypeId=@Parid
			 RAISERROR('该分支机构【%s】已经使用过不允许分类',16,1,@parFullName) RETURN
		END
	
	-----------------------------判断是否在自定义中有关联信息--------------------------------------
	SET @temptypename='stype'

	EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@ParId,@result=0
		IF @result=1
		BEGIN
			RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
		END
	EXEC	@result=dbo.Gp_DeleteInsert_Ac_Data @Type=@temptypename,@typeid=@ParId
			IF @result=1
			BEGIN
					RAISERROR('当前信息已在辅助核算中关联,不可以''分类''',16,1) RETURN
			END
	---------------------------------------- END ------------------------------------------------------
		
	--分类判断
	EXEC Gp_BaseInfoCheck 'stype',@parid,'0'	
			
	--DECLARE @nReturntype int,@EtypeId_1 [VARCHAR](50),@nSoncount int,@nSonnum int,@leveal smallint
	EXEC @nReturntype=Gp_createId @ParId,'stype',@EtypeId_1 out,@nSonnum out,@nSoncount out
	IF @nReturntype=-1 
		BEGIN
			RAISERROR('分支机构的分类不能超过10层',16,1)RETURN--RETURN -1
		END
	IF @nReturntype=-2 
		BEGIN
			RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
		END

END
 
IF @type='b'
BEGIN
	declare @typeName varchar(20)
	IF substring(@parid,1,5)='00001'
		SET @typeName='客户'
	IF substring(@parid,1,5)='00002'
		SET @typeName='供货商'
		
	IF NOT EXISTS (SELECT *FROM btype WHERE typeId=@ParId)
	BEGIN
		RAISERROR('该%s不存在，不能分类',16,1,@typeName)RETURN ---15  
	END
	
	SET @parFullName=(SELECT TOP 1 fullname FROM btype WHERE typeid=@parid)

	-- 判断单位的往来
	IF @Parid='00000'
	RETURN -11

	-----------------------------判断是否在自定义中有关联信息--------------------------------------
	SET @temptypename='Btype'

		EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@ParId,@result=0
			IF @result=1
			BEGIN
				RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
			END
			
		EXEC	@result=dbo.Gp_DeleteInsert_Ac_Data @Type=@temptypename,@typeid=@ParId
			IF @result=1
			BEGIN
					RAISERROR('当前信息已在辅助核算中关联,不可以''分类''',16,1) RETURN
			END
		---------------------------------------- END ------------------------------------------------------		

	--判断停用不能分类
	SELECT @deleted=deleted FROM btype WHERE typeId=@Parid
	IF(@deleted=1)
	BEGIN
	   RAISERROR('该%s【%s】已经被停用，不能分类',16,1,@typeName,@parFullName)RETURN ---15  
	END
	
	--关联结算单位	
	IF EXISTS (SELECT typeId FROM dbo.btype WHERE denominatedid=@Parid AND typeId<>@Parid)
		BEGIN
			IF LEFT(@Parid,5) ='00001' -- 客户
				BEGIN
					RAISERROR('当前客户信息已与结算单位关联,不能再分类!',16,1) RETURN 
				END
			ELSE
				BEGIN
					RAISERROR('当前供货商信息已与结算单位关联,不能再分类!',16,1) RETURN 
				END
		END
		
		
	--分类判断
	EXEC Gp_BaseInfoCheck 'btype',@parid,'0'
	
	-- 获得新的ID号
	EXEC @nReturntype=Gp_createId @ParId,'btype',@EtypeId_1 OUT,@nSonnum OUT,@nSoncount OUT
	IF @nReturntype=-1 
		BEGIN
			RAISERROR('客户和供货商的分类不能超过9层',16,1)RETURN-- RETURN -1
		END
	IF @nReturntype=-2 
		BEGIN
			RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
		END
END

IF @type='k'
BEGIN
	IF NOT EXISTS (SELECT *FROM stock WHERE typeId=@ParId)
	BEGIN
		RAISERROR('该仓库不存在，不能分类',16,1)RETURN ---15  
	END
	
	SET @parFullName=(SELECT TOP 1 fullname FROM stock WHERE typeid=@parid)

	IF(@ParId<>'00000')
	BEGIN
		--判断停用不能分类
		SELECT @deleted=deleted FROM stock WHERE typeId=@Parid
		IF(@deleted=1)
		BEGIN
		   RAISERROR('该仓库【%s】已经被停用，不能分类',16,1,@parFullName)RETURN ---15  
		END
	END
	-----------------------------判断是否在自定义中有关联信息--------------------------------------
	SET @temptypename='ktype'

	EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@parid,@result=0
	IF @result=1
	BEGIN
		RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
	END
	---------------------------------------- END ------------------------------------------------------	

	--分类判断
	EXEC Gp_BaseInfoCheck 'ktype',@parid,'0'
	
	-- 获得新的ID号
	EXEC @nReturntype=Gp_createId @ParId,'STOCK',@EtypeId_1 out,@nSonnum out,@nSoncount out
	IF @nReturntype=-1 
	BEGIN
		RAISERROR('仓库的分类不能超过10层',16,1)RETURN--RETURN -1
	END
	
	IF @nReturntype=-2 
	BEGIN
		RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
END

IF @type='a'
BEGIN
	IF NOT EXISTS (SELECT *FROM atype WHERE typeId=@ParId)
	BEGIN
		RAISERROR('该会计科目不存在，不能分类',16,1)RETURN ---15  
	END
		
	SET @parFullName=(SELECT TOP 1 fullname FROM atype WHERE typeid=@parid)
	SELECT @deleted=deleted FROM atype WHERE typeId=@Parid
	
	IF(@deleted=1)
	BEGIN
	   RAISERROR('该会计科目【%s】已经被停用，不能分类',16,1,@parFullName)RETURN ---15  
	END
	--分类判断
	EXEC Gp_BaseInfoCheck 'ptype',@parid,'0'

	-- 获得新的ID号
	EXEC @nRETURNtype=Gp_createId @ParId,'atype',@EtypeId_1 OUT,@nSonnum OUT,@nSoncount OUT
	IF @nRETURNtype=-1 
	BEGIN
		RAISERROR('该会计科目的分类不能超过10层',16,1)RETURN
	END--RETURN -1
	IF @nRETURNtype=-2 
	BEGIN 
	 RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
END

IF @type='d'
BEGIN
	IF NOT EXISTS (SELECT *FROM department WHERE typeId=@ParId)
	BEGIN
		RAISERROR('该部门不存在，不能分类',16,1)RETURN ---15  
	END
		
	SET @parFullName=(SELECT TOP 1 fullname FROM department WHERE typeid=@parid)
	SELECT @deleted=deleted FROM department WHERE typeId=@Parid
		
	IF(@deleted=1)
	BEGIN
	   RAISERROR('该部门【%s】已经被停用，不能分类',16,1,@parFullName)RETURN ---15  
	END
	
	EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@Parid,@result=0
		IF @result=1
		BEGIN
			RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
		END
	EXEC	@result=dbo.Gp_DeleteInsert_Ac_Data @Type='DEPARTMENT',@typeid=@ParId
		IF @result=1
		BEGIN
				RAISERROR('当前信息已在辅助核算中关联,不可以''分类''',16,1) RETURN
		END
		
	--分类判断
	EXEC Gp_BaseInfoCheck 'dtype',@parid,'0'

	-- 获得新的ID号
	EXEC @nReturntype=Gp_createId @ParId,'Department',@EtypeId_1 out,@nSonnum out,@nSoncount OUT
	IF @nReturntype=-1
	BEGIN
		RAISERROR('部门的分类不能超过10层',16,1)RETURN--RETURN -1
	END
	IF @nReturntype=-2
	BEGIN
		RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
	
END

IF @type='e'
BEGIN
	IF NOT EXISTS (SELECT *FROM employee WHERE typeId=@ParId)
	BEGIN
		RAISERROR('该职员不存在，不能分类',16,1)RETURN ---15  
	END
	
	SET @parFullName=(SELECT TOP 1 fullname FROM employee WHERE typeid=@parid)
	SELECT @deleted=deleted FROM employee WHERE typeId=@Parid
	IF(@deleted=1)
		BEGIN
		   RAISERROR('该职员【%s】已经被停用，不能分类',16,1,@parFullName)RETURN ---15  
		END
	SET @temptypename='etype'

	EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@parid,@result=0
		IF @result=1
		BEGIN
			RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
		END
	EXEC	@result=dbo.Gp_DeleteInsert_Ac_Data @Type='EMPLOYEE',@typeid=@ParId
		IF @result=1
		BEGIN
				RAISERROR('当前信息已在辅助核算中关联,不可以''分类''',16,1) RETURN
		END
		
	--分类判断
	EXEC Gp_BaseInfoCheck 'etype',@parid,'0'
	
	-- 获得新的ID号
	EXEC @nReturntype=Gp_createId @ParId,'employee',@EtypeId_1 out,@nSonnum out,@nSoncount out
	IF @nReturntype=-1 
	BEGIN
		RAISERROR('职员的分类不能超过9层',16,1)RETURN--RETURN -1
	END
	IF @nReturntype=-2 
	BEGIN
		RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
	
END

IF @type='AreaType'
BEGIN
	IF NOT EXISTS (SELECT *FROM areatype WHERE typeId=@ParId)
	BEGIN
		RAISERROR('该地区档案不存在，不能分类',16,1)RETURN ---15  
	END
	
	SET @parFullName=(SELECT TOP 1 fullname FROM areatype WHERE typeid=@parid)
	--判断停用不能分类
	SELECT @deleted=deleted FROM areatype WHERE typeId=@Parid
	IF(@deleted=1)
		BEGIN
			RAISERROR('该地区档案【%s】已经被停用，不能分类',16,1,@parFullName)RETURN ---15  
		END
		
	EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@Parid,@result=0
		IF @result=1
		BEGIN
			RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
		END
	
	--分类判断
	EXEC Gp_BaseInfoCheck 'AreaType',@parid,'0'

	-- 获得新的ID号
	EXEC @nReturntype=Gp_createId @ParId,'AreaType',@EtypeId_1 out,@nSonnum out,@nSoncount out
	IF @nReturntype=-1
	BEGIN
		RAISERROR('地区档案的分类不能超过10层',16,1)RETURN--RETURN -1
	END
	IF @nReturntype=-2 
	BEGIN
		RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
END

IF @type='Ac_CashMoneyItems'
BEGIN
	--SELECT *FROM Ac_CashMoneyItems
	
	--SELECT *FROM Ac_Account
	
	--DECLARE @Ac_CashMoneyId_1 [varchar](50)
		-- 获得新的ID号
	EXEC @nReturntype=Gp_createId @ParId,'Ac_CashMoneyItems',@Ac_CashMoneyId_1 OUT,@nSonnum OUT,@nSoncount OUT
	IF @nReturntype=-1
		BEGIN
			RAISERROR('现金流量项目的分类不能超过10层',16,1)RETURN--RETURN -1
		END
	IF @nReturntype=-2
		BEGIN
			RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
		END
END

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_BaseInfoCheck]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_BaseInfoCheck]
GO

SET QUOTED_IDENTIFIER OFF
GO

----========================
----创建者：黄 清
----日期：2013-05-10
----描述：基本信息分类，删除，使用，搬移判断
----========================
CREATE	PROCEDURE	[dbo].[Gp_BaseInfoCheck]
(
	@baseinfotype	[VARCHAR](200),
	@typeid			[VARCHAR](50),
	@mode			[VARCHAR](50) --0.分类 1.删除 2.使用 3.搬移
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @sql NVARCHAR(MAX)
DECLARE @TableName	VARCHAR(200)
DECLARE @TableColumnname VARCHAR(200)
DECLARE @Explain	VARCHAR(400)
DECLARE @Conditions VARCHAR(400)
DECLARE @modename	VARCHAR(50)
DECLARE @ifdelete VARCHAR(2)
DECLARE @IfCategory VARCHAR(2)
DECLARE @ifused VARCHAR(2)
DECLARE @IfMove VARCHAR(2)
DECLARE @count INT=0

SET @sql=''
SET @TableName=''
SET @TableColumnname=''
SET @Explain=''
SET @Conditions=''
SET @ifdelete='%'
SET @IfCategory='%'
SET @ifused='%'
SET @IfMove='%'

IF @mode=0
BEGIN
	SET @modename=',不能分类'
	SET @IfCategory=1
END
IF @mode=1
BEGIN
	SET @modename=',不能删除'
	SET @ifdelete=1
END
IF @mode=2--使用
BEGIN
	SET @modename=''
	SET @ifused=1
END
IF @mode=3
BEGIN
	SET @modename=',不能搬移'
	SET @IfMove=1
END

--SELECT *FROM BaseInfoAssitDetection

--第一层不判断
IF @baseinfotype='stype' AND @typeid='00000' 
	RETURN
IF @baseinfotype='employee' AND @typeid='00001'
	RETURN
IF @baseinfotype='ptype' AND @typeid='00000'
	RETURN
	

	
DECLARE BaseInfo_cursor cursor
FOR SELECT	TableName AS tablename, 
			TableColumnname AS tablecolumnname,
			Conditions AS Conditions
	FROM	BaseInfoAssitDetection 
	WHERE	BaseinfoType=@baseinfotype
			AND IfCategory LIKE @IfCategory
			AND IfDelete LIKE @ifdelete
			AND IfUsed LIKE @ifused
			AND IfMove LIKE @IfMove
		
FOR READ only
OPEN BaseInfo_cursor
FETCH NEXT FROM BaseInfo_cursor INTO  @TableName,@TableColumnname,@Conditions
WHILE @@fetch_status=0
	BEGIN
		IF @TableName = 'MoneyBill' AND @baseinfotype='department'
		BEGIN
			SELECT @count=COUNT(1) FROM dbo.MoneyBill m INNER JOIN dbo.BillIndex b ON b.BillNumberId = m.BillNumberId WHERE b.BillType=78 AND m.DTypeId=@typeid
			IF @count>0
			BEGIN
				RAISERROR('该部门已在固定资产(项目)折旧单中使用!',16,1)
				RETURN
			END
			SELECT @count=COUNT(1) FROM dbo.MoneyBill m INNER JOIN dbo.BillIndex b ON b.BillNumberId = m.BillNumberId WHERE b.BillType !=78 AND m.DTypeId=@typeid
			IF @count>0
			BEGIN
				RAISERROR('该部门已在现金费用单中使用!',16,1)
				RETURN
			END
		END 
		
		IF @mode=0 AND (@TableName='coupon_ApplyStype' AND @TableColumnname='STypeID')
			BEGIN
				FETCH NEXT FROM BaseInfo_cursor INTO  @TableName,@TableColumnname,@Conditions
			END
			
		 SELECT @sql= 'SELECT @count=count(1) FROM  '+ @TableName +' WHERE '+@TableColumnname+'='''+@typeid+''''
		 IF @Conditions<>''
			SET @sql=@sql+' AND ('+@Conditions+')'
		 EXECUTE sp_executesql @sql,N'@count INT OUTPUT',@count OUTPUT
		 IF @count>0 
			 BEGIN
				SELECT @Explain=Explain FROM BaseInfoAssitDetection WHERE TableName=@TableName AND TableColumnname=@TableColumnname
				RAISERROR('%s%s',16,1,@Explain,@modename) 
				Close BaseInfo_cursor
				Deallocate BaseInfo_cursor
				RETURN
			 END
		 FETCH NEXT FROM BaseInfo_cursor INTO  @TableName,@TableColumnname,@Conditions
	END
Close BaseInfo_cursor
Deallocate BaseInfo_cursor
	
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


--作者：徐辉 v50 2009-10-20添加，
--功能：多级权限，基本信息查询

-- ========================================================================
-- 修改说明：	往来单位增加联系电话1、2、3的查找
-- 修改者：		韩林
-- 最后修改时间：2011-08-09
-- ========================================================================

CREATE                PROCEDURE GP_BaseInfoQuery
(
	@dbtype				int,
	@filter				varchar(max),
	@stypeid			varchar(50)='',
	@chvOperatorID		varchar(50),
	@pretype			varchar(10)=''	,
	@cid                varchar(50)='',
	@isVoucherbill		varchar(10)='0',
	@billtype 			int = '', 		-- 单据类型编号
	@allotkflag			varchar(10)='2',  --wg 废弃 9.1砍掉了
	@gathertag			varchar(10)= '',
	@isservice          INT = 1             --是否显示服务商品
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------

DECLARE @SQL varchar(max)
IF @dbtype = 2 OR @dbtype = 3
BEGIN
	-- 客户供货商是否统一
	DECLARE @IfBtypeAll varchar(1)
	SET @IfBtypeAll = '0'
	SELECT TOP 1 @IfBtypeAll=value FROM UserConfig WHERE ConfigName = 'BtypeAll'
END

declare @preSql varchar(max)
declare @preSql1 varchar(max)
set @preSql=''
set @preSql1=''
IF @pretype='ar'
begin
--特殊处理微信支付宝不显示预收资金
	IF @gathertag <> '1'
	BEGIN
		set @preSql=' ''39'' '
		set @preSql1=' ,''39'' '
	END
end
IF @pretype='ap'
begin
	set @preSql=' ''27'' '
	set @preSql1=' ,''27'' '
end


IF @cid <> ''
BEGIN
SET @cid=@cid
END
ELSE
BEGIN
select top 1 @cid=CId  from Ac_Currency where Sysrow=1
END

IF @dbtype = 2 --客户
	BEGIN
		IF (@IfBtypeAll <>1 OR @chvMBTypeID <> '00001' OR @chvMBTypeID2 <> '00002') AND (@IfBtypeAll=1 OR @chvMBTypeID <> '00001')
			BEGIN
				CREATE TABLE #temp_Btype
				(
					Typeid	VARCHAR(200)
				)	
				--客户
				INSERT INTO #temp_Btype(TypeId) 
				SELECT	DISTINCT B.TypeId 
				FROM	BType_L L
				INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
				WHERE	L.etypeid = @chvOperatorID
						AND B.typeId LIKE '00001%'
				UNION
				SELECT	L.TypeID
				FROM	btype_l L
				WHERE	L.etypeid = @chvOperatorID
						AND L.typeId LIKE '00001%'
						AND L.flag=0

				--供货商	
				--INSERT INTO #temp_Btype(TypeId) 
				--SELECT	DISTINCT B.TypeId 
				--FROM	BType_L L
				--INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
				--WHERE	L.etypeid = @chvOperatorID
				--		AND B.typeId LIKE '00002%'
				--UNION
				--SELECT	L.TypeID
				--FROM	btype_l L
				--WHERE	L.etypeid = @chvOperatorID
				--		AND L.typeId LIKE '00002%'
				--		AND L.flag=0
			END
	END
ELSE IF @dbtype = 3	-- 供货商
	BEGIN
	IF (@IfBtypeAll <>1 OR @chvMBTypeID <> '00001' OR @chvMBTypeID2 <> '00002') AND (@IfBtypeAll=1 OR @chvMBTypeID2<> '00002')
			BEGIN
			CREATE TABLE #temp_Btype2
				(
					Typeid	VARCHAR(200)
				)	
				--客户
				--INSERT INTO #temp_Btype2(TypeId) 
				--SELECT	DISTINCT B.TypeId 
				--FROM	BType_L L
				--INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
				--WHERE	L.etypeid = @chvOperatorID
				--		AND B.typeId LIKE '00001%'
				--UNION
				--SELECT	L.TypeID
				--FROM	btype_l L
				--WHERE	L.etypeid = @chvOperatorID
				--		AND L.typeId LIKE '00001%'
				--		AND L.flag=0

				--供货商	
				INSERT INTO #temp_Btype2(TypeId) 
				SELECT	DISTINCT B.TypeId 
				FROM	BType_L L
				INNER JOIN BType B ON (L.Flag=1 AND B.TypeId LIKE L.TypeId + '%')
				WHERE	L.etypeid = @chvOperatorID
						AND B.typeId LIKE '00002%'
				UNION
				SELECT	L.TypeID
				FROM	btype_l L
				WHERE	L.etypeid = @chvOperatorID
						AND L.typeId LIKE '00002%'
						AND L.flag=0
			END
	END

--往来单位用这个字段列值
DECLARE @BTypeFields VARCHAR(max)
SET @BTypeFields = '
				B.typeId,
				B.parid,
				B.leveal,
				B.soncount,
				B.sonnum,
				B.UserCode,
				B.FullName,
				B.Name,
				B.Area,
				B.TelAndAddress,
				B.PostCode,
				B.Person,
				B.TaxNumber,
				B.BankAndAcount,
				B.Comment,
				B.CreateDate,
				ISNULL(Bc.ArTotal,0) AS ArTotal,
				ISNULL(Bc.ArTotal00,0) AS ArTotal00,
				ISNULL(Bc.ApTotal,0) AS ApTotal,
				ISNULL(Bc.ApTotal00,0) AS ApTotal00,				
				B.deleted,
				B.Client,
				B.ARLimit,
				B.initcomment,
				B.arapexplain,
				B.Tel1,
				B.Tel2,
				B.Tel3,
				B.Fax,
				B.WWW,
				B.Bank,
				B.BankName,
				B.Email,
				B.LinkMan1,
				B.LinkSex1,
				B.LinkBirthDay1,
				B.LinkJob1,
				B.LinkCall1,
				B.LinkTel1,
				B.LinkMobile1,
				B.LinkPost1,
				B.LinkAddress1,
				B.LinkEmail1,
				B.LinkComment1,
				B.LinkMan2,
				B.LinkSex2,
				B.LinkBirthDay2,
				B.LinkJob2,
				B.LinkCall2,
				B.LinkTel2,
				B.LinkMobile2,
				B.LinkPost2,
				B.LinkAddress2,
				B.LinkEmail2,
				B.LinkComment2,
				B.ARLimitTime AS selfarlimittime,
				B.paymentLTime AS selfpaymentltime,
				B.SaleZekou,
				B.BuyZekou,
				B.PyCode,
				B.Price,
				B.BuyPrice,
				B.AreaTypeID,
				B.smsMobile,
				B.smsComment,
				B.XiWaMaxNumber,
				B.denominatedid,
				(SELECT fullname FROM BTYPE WHERE typeId=B.denominatedid) as denname,
				B.cid,	
				(SELECT rate FROM Ac_Currency ac where ac.cid = b.cid) as rate,
				(SELECT sysrow FROM  Ac_Currency ac where ac.cid = b.cid) as sysrow,
				(SELECT ARLimitTime FROM BTYPE WHERE typeId=B.denominatedid) as ARLimitTime,
				(SELECT paymentLTime FROM BTYPE WHERE typeId=B.denominatedid) as paymentLTime,	
				b.chkskmonthday,
				b.skmonthday,
				b.chkfkmonthday,
				b.fkmonthday,
				b.dzdays,
				isnull(b.skmonth,0) as skmonth,
				isnull(b.skday,0) as skday,
				isnull(b.skdzdayflag,0) as skdzdayflag,
				isnull(b.skcyjartime,0) as skcyjartime,
				isnull(b.fkmonth,0) as fkmonth,
				isnull(b.fkday,0) as fkday,
				isnull(b.fkdzdayflag,0) as fkdzdayflag,
				isnull(b.fkcyjaptime,0) as fkcyjaptime,
				ISNULL(Bc.YsTotal,0) AS YsTotal,
				ISNULL(Bc.YsTotal00,0) AS YsTotal00,
				ISNULL(Bc.YfTotal,0) AS YfTotal,
				ISNULL(Bc.YfTotal00,0) AS YfTotal ,
				'+ CASE WHEN ((@dbtype=7 AND @chvMBTypeID = '00001' AND @chvMBTypeID2 = '00002') OR ((@dbtype=2 OR @dbtype=3) AND (@IfBtypeAll = '1' AND @chvMBTypeID = '00001' AND @chvMBTypeID2 = '00002')))  
				THEN '
				b.ConsigneeAddress,
				b.Consignee,
				b.ConsigneeTel	' 
				ELSE ' '''' AS ConsigneeAddress, '''' AS Consignee ,'''' AS ConsigneeTel ' 
				END 
				
		
declare @tempsql varchar(max)
set @tempsql = ''
if @billtype in (300,305,215,11,45,160,140,141,142,143)
	set @tempsql = ' or b.LinkMan1 = ''' + @filter + ''' or b.LinkMan2 = ''' + @filter + ''' or b.LinkTel1 = ''' + @filter + ''' or b.LinkTel2 = ''' + @filter + ''' or b.LinkMobile1 = ''' + @filter + ''' or b.LinkMobile2 = ''' + @filter + ''''


IF @dbtype = 0	-- 分支机构
	SET @SQL = '
	SELECT	TOP 2 *
	FROM	' + CASE WHEN @chvMStypeid = '00000' THEN 'SType' ELSE 'F_GetManStypeAll(''' + @chvOperatorID + ''')' END + '
	WHERE	(UserCode = ''' + @filter + ''' OR Fullname = ''' + @filter +''' OR PyCode = ''' + @filter + ''') AND Deleted = 0 AND SonNum = 0 AND TypeID <> ''00000''' + CASE WHEN @isVoucherbill = '1' THEN ' AND IsSelfVerify = 1' ELSE '' END
ELSE IF @dbtype = 1	-- 职员
BEGIN
	SET @SQL = '
	SELECT *,(SELECT TOP 1 FullName FROM stype WHERE TypeID = s.stypeid AND Deleted = 0 AND SonNum = 0) AS sfullname FROM (
	SELECT	TOP 2 a.TypeID,
		a.FullName,
		b.TypeID AS DTypeid,
		b.FullName AS Department,
		(select stypeid from Employee e INNER JOIN F_GetManSTypeAll(''' + @chvOperatorID + ''')  fs on fs.typeid=e.stypeid where e.typeid=a.typeId) as StypeID
	FROM	' + CASE WHEN @chvMETypeID = '00001' THEN 'Employee ' ELSE 'F_GetManEtypeAll(''' + @chvOperatorID + ''') ' END + ' a
	LEFT JOIN Department b ON a.DTypeID = b.TypeID AND b.SonNum = 0 AND b.Deleted = 0
	LEFT JOIN Stype c ON a.Stypeid = c.typeid AND c.SonNum = 0 AND c.Deleted = 0
	WHERE (a.UserCode = ''' + @filter + ''' OR a.Fullname = ''' + @filter +''' OR a.PyCode = ''' + @filter + ''') AND a.Deleted = 0 AND a.SonNum = 0 AND a.TypeID <> ''00001'' ) s'
END
ELSE IF @dbtype = 2	-- 客户
BEGIN
	SET @SQL = '
	SELECT	TOP 2 ' + @BTypeFields + '
	FROM	' + CASE WHEN (@IfBtypeAll = '1' AND @chvMBTypeID = '00001' AND @chvMBTypeID2 = '00002')
		OR (@IfBtypeAll <> '1' AND @chvMBTypeID = '00001') THEN 'BType B '
		ELSE ' BType B INNER JOIN #temp_Btype M ON b.TypeId=M.TypeId ' END + ' 
	LEFT JOIN (
				SELECT	*
				FROM	BType_ARAPTotal
				WHERE	STypeId = '''+@stypeid+''' AND cid='''+@cid+'''
	)Bc ON B.TypeId = Bc.BTypeId
	WHERE	(B.UserCode = ''' + @filter + ''' OR B.Fullname = ''' + @filter +''' OR B.PyCode = ''' + @filter + ''' OR B.Tel1 = ''' + @filter + ''' OR B.Tel2 = ''' + @filter + ''' OR B.Tel3 = ''' + @filter + ''''+ @tempsql + ') 
			AND B.Deleted = 0 
			AND B.SonNum = 0 
			AND B.TypeID NOT IN (''00001'',''00002'')
			' + CASE WHEN @IfBtypeAll <> '1' THEN ' AND B.TypeId LIKE ''00001%''' ELSE '' END
END
ELSE IF @dbtype = 3	-- 供货商
BEGIN
	SET @SQL = '
	SELECT	TOP 2 ' + @BTypeFields + '
	FROM	' + CASE WHEN (@IfBtypeAll = '1' AND @chvMBTypeID = '00001' AND @chvMBTypeID2 = '00002')
			OR (@IfBtypeAll <> '1' AND @chvMBTypeID2 = '00002') THEN 'BType B '
			ELSE ' BType B INNER JOIN #temp_Btype2 M ON b.TypeId=M.TypeId ' END + ' 
	LEFT JOIN (
				SELECT	*
				FROM	BType_ARAPTotal
				WHERE	STypeId = '''+@stypeid+''' AND cid='''+@cid+'''
	)Bc ON B.TypeId = Bc.BTypeId			
	WHERE	(B.UserCode = ''' + @filter + ''' OR B.Fullname = ''' + @filter +''' OR B.PyCode = ''' + @filter + ''' OR B.Tel1 = ''' + @filter + ''' OR B.Tel2 = ''' + @filter + ''' OR B.Tel3 = ''' + @filter + ''') 
			AND B.Deleted = 0 
			AND B.SonNum = 0 
			AND B.TypeID NOT IN (''00001'',''00002'')
			' + CASE WHEN @IfBtypeAll <> '1' THEN 'AND B.TypeId LIKE ''00002%''' ELSE '' END 
			+ CASE WHEN @billtype='414' THEN ' AND B.iscarrier=1' ELSE '' END--运输配送单查询承运商
END
ELSE IF @dbtype = 4	-- 仓库
BEGIN
	SET @SQL = '
	SELECT	TOP 2 *
	FROM	' + CASE WHEN @chvMKTypeID = '00000' THEN 'Stock' ELSE 'F_GetManKtypeAll(''' + @chvOperatorID + ''')' END + '
	WHERE	(UserCode = ''' + @filter + ''' OR Fullname = ''' + @filter +''' OR PyCode = ''' + @filter + ''') AND Deleted = 0 AND SonNum = 0 AND TypeID <> ''00000'''
	IF @stypeid<>''
		SET @SQL=@SQL+' AND StypeId='''+@stypeid+''''
END
ELSE IF @dbtype = 5	-- 调拨单仓库
BEGIN
	-- 调拨单仓库不受权限控制 0：不受
	DECLARE @MoveInOutKLimit varchar(1) 
	SET @MoveInOutKLimit = '1'
	SELECT TOP 1 @MoveInOutKLimit = Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit'
    
  --  IF @allotkflag = 0 AND @MoveInOutKLimit=0--出库
		--SET @MoveInOutKLimit = 1
	
	SET @SQL = '
	SELECT	TOP 2 *
	FROM	' + CASE WHEN @chvMKTypeID = '00000' OR @MoveInOutKLimit = '0' THEN 'Stock' ELSE 'F_GetManKtypeAll(''' + @chvOperatorID + ''')' END + '
	WHERE	(UserCode = ''' + @filter + ''' OR Fullname = ''' + @filter +''' OR PyCode = ''' + @filter + ''') AND Deleted = 0 AND SonNum = 0 AND TypeID <> ''00000'''
	IF @stypeid<>''
		SET @SQL=@SQL+' AND StypeId='''+@stypeid+''''
END
ELSE IF @dbtype = 7	-- 全部客户供货商
BEGIN
	SET @SQL = 'SELECT	TOP 2 ' + @BTypeFields + '
	FROM	' + CASE WHEN @chvMBTypeID = '00001' AND @chvMBTypeID2 = '00002' THEN 'BType' ELSE 'F_GetManBtypeAll(''' + @chvOperatorID + ''')' END + ' B
	LEFT JOIN (
				SELECT	*
				FROM	BType_ARAPTotal
				WHERE	STypeId = '''+@stypeid+''' AND cid='''+@cid+'''
	)Bc ON B.TypeId = Bc.BTypeId
	WHERE	(B.UserCode = ''' + @filter + ''' OR B.Fullname = ''' + @filter + ''' OR B.PyCode = ''' + @filter + ''' OR B.Tel1 = ''' + @filter + ''' OR B.Tel2 = ''' + @filter + ''' OR B.Tel3 = ''' + @filter + ''''+ @tempsql + ') 
			AND B.Deleted = 0 
			AND B.SonNum = 0 
			AND B.TypeID NOT IN (''00001'',''00002'')'
END
ELSE IF @dbtype = 9	-- 现金银行
BEGIN
	IF @presql<>''
	BEGIN
		SET @SQL = '
		SELECT	TOP 2 *
		FROM	' + CASE WHEN @chvMATypeID = '0000' THEN 'Ac_Items' 
					ELSE '(SELECT Typeid as nid,Typeid,ParId,SonNum,SonCount,UserCode,FullName,Name,IsBank,PyCode,Deleted,TypeName,XiWaMaxNumber,Sysrow,ismodify FROM F_AllTreeA(''' + @chvOperatorID + ''') 
					UNION SELECT nid as nid,Typeid,ParId,SonNum,SonCount,UserCode,FullName,Name,IsBank,PyCode,Deleted,TypeName,XiWaMaxNumber,Sysrow,ismodify FROM Ac_Items WHERE nid IN ('+@preSql+')) a' END + '
		WHERE	(UserCode = ''' + @filter + ''' OR PyCode = ''' + @filter + ''') AND Deleted = 0 AND SonNum = 0 AND nid <> ''34''
			' + CASE WHEN @chvMATypeID = '0000' THEN 'AND (TypeName = ''B'' OR nid in( ''0'''+@preSql1+'))' ELSE '' END
	END
	ELSE
	BEGIN
		SET @SQL = '
		SELECT	TOP 2 *
		FROM	' + CASE WHEN @chvMATypeID = '0000' THEN 'Ac_Items' ELSE '(SELECT * FROM F_AllTreeA(''' + @chvOperatorID + ''')) a' END + '
		WHERE	(UserCode = ''' + @filter + ''' OR Fullname = ''' + @filter +''' OR PyCode = ''' + @filter + ''') AND Deleted = 0 AND SonNum = 0 AND nid <> ''34''
			' + CASE WHEN @chvMATypeID = '0000' THEN 'AND (TypeName = ''B'' OR nid in( ''0'''+@preSql1+'))' ELSE '' END
	END
END
ELSE IF @dbtype = 11	-- 部门
BEGIN
	SET @SQL = '
	SELECT	TOP 2 *
	FROM	' + CASE WHEN @chvMDtypeid = '00000' THEN 'Department' ELSE 'F_GetManDtypeAll(''' + @chvOperatorID + ''')' END + '
	WHERE	(UserCode = ''' + @filter + ''' OR Fullname = ''' + @filter +''' OR PyCode = ''' + @filter + ''') AND Deleted = 0 AND SonNum = 0'
END
ELSE IF @dbtype = 14	-- 商品编号
BEGIN
	SET @SQL = '
	SELECT	TOP 2 *
	FROM	' + CASE WHEN @chvMPTypeID = '00000' THEN 'PType' ELSE 'F_GetManPtypeAll(''' + @chvOperatorID + ''')' END + '
	WHERE	(UserCode like ''%' + @filter + '%'' OR Fullname like ''%' + @filter +'%'' OR PyCode like ''%' + @filter + '%'') AND Deleted = 0 AND SonNum = 0 AND TypeID <> ''00000'''
	--IF @isservice = 0
		SET @SQL += ' AND isservice = 0 AND IscombinationProduct=0'
END
ELSE IF @dbtype = 15	-- 商品名称
BEGIN
	SET @SQL = '
	SELECT	TOP 2 *
	FROM	' + CASE WHEN @chvMPTypeID = '00000' THEN 'PType' ELSE 'F_GetManPtypeAll(''' + @chvOperatorID + ''')' END + '
	WHERE	(FullName = ''' + @filter + ''' OR Fullname = ''' + @filter +''' OR PyCode = ''' + @filter + ''') AND Deleted = 0 AND SonNum = 0 AND TypeID <> ''00000'''
END

ELSE IF @dbtype = 16	-- 查询不包括当前分支机构的仓库
BEGIN
	SET @SQL = '
		SELECT	TOP 2 *
		FROM Stock
		WHERE	(UserCode = ''' + @filter + ''' OR Fullname = ''' + @filter +''' OR PyCode = ''' + @filter + ''') AND Deleted = 0 AND SonNum = 0 AND TypeID <> ''00000'''
		IF @stypeid<>''
			SET @SQL=@SQL+' AND StypeId<>'''+@stypeid+''''
END

--PRINT @SQL
--PRINT @dbtype
--print @tempsql
EXEC(@SQL)
IF @dbtype = 2 --客户
	IF (@IfBtypeAll <>1 OR @chvMBTypeID <> '00001' OR @chvMBTypeID2 <> '00002') AND (@IfBtypeAll=1 OR @chvMBTypeID <> '00001')
		DROP TABLE #temp_Btype
ELSE 
IF @dbtype = 3 --供应商		
	IF (@IfBtypeAll <>1 OR @chvMBTypeID <> '00001' OR @chvMBTypeID2 <> '00002') AND (@IfBtypeAll=1 OR @chvMBTypeID2 <> '00002')
		DROP TABLE #temp_Btype2

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	功能说明：	
	作    者：	冯波
	最后修改：	2011-05-18
*/
CREATE               PROCEDURE Gp_Batch_CreateManageRep
(
	@nBillID	numeric(10,0)	-- 单据编号 ID 值
)
--@encode$--
AS
SET NOCOUNT ON

-- Some vchtype
DECLARE	@GOODS_ID				varchar(50),
		@CASH_ID				varchar(50),
		@CASH_BANK_ID 			varchar(50),
		@AR_ID					varchar(50),
		@AP_ID					varchar(50),
		@YF_ID					varchar(50),
		@YS_ID					varchar(50),
		@GOODS_LOSS_ID			varchar(50),
		@GOODS_GET_ID			varchar(50),
		@ALLOT_PRICE_ID			varchar(50),
		@PRICE_INCOME_ID		varchar(50),
		@BORROW_BUY_PRICE_ID	varchar(50),
		@GOODS_GIVE_ID			varchar(50),
		@GOODS_PRODUCE_ID		varchar(50),
		@SALE_COST_ID			varchar(50),
		@SALE_INCOME_ID			varchar(50),
		@LEND_GOODS_ID			varchar(50),
		@BORROW_GOODS_ID		varchar(50),
		@BALANCE_ID				varchar(50),
		@DEPRECIATION_ID		varchar(50),
		@APPORTION_EXPENSE_ID	varchar(50),
		@INIT_MONEY_ID			varchar(50),
		@ALL_INCOME_ID			varchar(50),
		@ALL_EXPENSE_ID			varchar(50),
		@PROFIT_ID				varchar(50),
		
		@ASSETS_ID				varchar(50),
		@DEBT_ID				varchar(50),
		@POWER_ID				varchar(50),
		@ADDEBT_INCOME_ID		varchar(50),
		@ADDEBT_LOSE_ID			varchar(50)		

--SET @GOODS_ID				= '0000100001'				-- 『库存商品总值合计』
--SET @CASH_ID				= '0000100003'				-- 现    金
--SET @CASH_BANK_ID			= '0000100004'				-- 『全部银行存款合计』
--SET @AR_ID					= '0000100005'				-- 『应收款合计』
--SET @AP_ID					= '0000200001'				-- 『应付帐款合计』
--SET @GOODS_LOSS_ID			= '000040000200001'			-- 商品报损支出
--SET @GOODS_GET_ID			= '000030000200001'			-- 商品报溢收入
--SET @ALLOT_PRICE_ID			= '000030000200005'			-- 变价调拨差价
--SET @PRICE_INCOME_ID		= '000030000200003'			-- 成本调价收入
--SET @GOODS_PRODUCE_ID		= '000030000200006'			-- 商品拆装差价
--SET @SALE_COST_ID			= '0000400001'				-- 『销售成本』
--SET @SALE_INCOME_ID			= '0000300001'				-- 『销售收入』
--SET @BALANCE_ID				= '000030000200004'			-- 进货退货差价
--SET @DEPRECIATION_ID		= '000040000300002'			-- 固定资产折旧
--SET @APPORTION_EXPENSE_ID	= '0000100007'				-- 『待摊费用』
--SET @ALL_INCOME_ID			= '00003'					-- 【收入类】
--SET @ALL_EXPENSE_ID			= '00004'					-- 【支出类】
--SET @ASSETS_ID				= '00001'					-- 【资产合计】
--SET @DEBT_ID				= '00002'					-- 【负债合计】
--SET @ADDEBT_INCOME_ID		= '000030000300001'			-- 调帐收入
--SET @ADDEBT_LOSE_ID			= '000040000300001'			-- 调帐亏损R
--SELECT @YF_ID				= '0000100009'			--预付账款
--SELECT @YS_ID				= '0000200006'			--预收账款

SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』
SELECT @CASH_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1001'			-- 现    金
SELECT @AR_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '987'			-- 『应收款合计』
SELECT @AP_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2121'			-- 『应付帐款合计』
SELECT @GOODS_LOSS_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0421'		-- 商品报损支出
SELECT @GOODS_GET_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0321'		-- 商品报溢收入
SELECT @ALLOT_PRICE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0325'		-- 变价调拨差价
SELECT @PRICE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0323'		-- 成本调价收入
SELECT @GOODS_PRODUCE_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0326'		-- 商品拆装差价
SELECT @SALE_COST_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5401'			-- 『销售成本』
SELECT @SALE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5101'			-- 『销售收入』
SELECT @BALANCE_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '0324'		-- 采购退货差价
SELECT @DEPRECIATION_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0432'		-- 固定资产折旧
SELECT @APPORTION_EXPENSE_ID	=nid FROM dbo.Ac_Items WHERE UserCode =  '1301'			-- 『待摊费用』
SELECT @ADDEBT_INCOME_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '03333'		-- 调帐收入
SELECT @ADDEBT_LOSE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0431'		-- 调帐亏损
SELECT @YF_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1151'			--预付账款
SELECT @YS_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2131'			--预收账款

DECLARE	@DBName				varchar(30),
		@nCostingMethod 	smallint,
		@tBillDate			datetime,
		@nBillNumberID		numeric(10,0),
		@nBillType			numeric(4,0),
		@szATypeID			varchar(50),
		@szPTypeID			varchar(50),
		@szBTypeID			varchar(50),
		@szETypeID			varchar(50),
		@szStockID			varchar(50),
		@szStockID2			varchar(50),
		@szATypeIDTemp		varchar(50),
		@szPTypeIDTemp		varchar(50),
		@szBTypeIDTemp		varchar(50),
		@szETypeIDTemp		varchar(50),
		@szKTypeIDTemp		varchar(50),
		@szSTypeIDTemp		varchar(50),
		@szIfCheck			char(1),
		@nPeriod			int,
		@szJobNumber		varchar(20),
		@OutFactoryDate		datetime,
		@dPrice				 NUMERIC(24, 10) ,
		@dTotal				 NUMERIC(24, 10) ,
		@dQty				 NUMERIC(24, 10) ,
		@dCostPrice			 NUMERIC(24, 10) ,
		@dCostTotal			 NUMERIC(24, 10) ,
		@nGoodsNo			int,
		@dCostPriceOut		 NUMERIC(24, 10) ,
		@dTemp				 NUMERIC(24, 10) ,
		@dPriceTemp			 NUMERIC(24, 10) ,
		@dntotal			 NUMERIC(24, 10) ,
		@cid				INT,
		@nRet				smallint

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@szSTypeIDTemp, @nCostingMethod output

-- begin tran Rep_Trans
DECLARE Manage_Cursor CURSOR FOR
	SELECT	BillNumberID,
			BillType,
			ATypeID,
			PTypeID,
			BTypeID,
			ETypeID,
			KTypeID,
			STypeID,
			Qty,
			Price,
			Total,
			CostPrice,
			CostTotal,
			JobNumber,
			GoodsNo,
			OutFactoryDate,
			Ntotal,
			cid
	FROM	ListTable
	WHERE	BillNumberID = @nBillID
			AND ATypeID IN ('0000100005','0000200001')
	FOR UPDATE

OPEN Manage_Cursor
FETCH NEXT FROM Manage_Cursor INTO	@nBillNumberID,
									@nBillType,
									@szATypeIDTemp,
									@szPTypeIDTemp,
									@szBTypeIDTemp,
									@szETypeIDTemp,
									@szKTypeIDTemp,
									@szSTypeIDTemp,
									@dQty,
									@dPrice,
									@dTotal,
									@dCostPrice,
									@dCostTotal,
									@szJobNumber,
									@nGoodsNo,
									@OutFactoryDate,
									@dntotal,
									@cid
WHILE @@FETCH_STATUS <> -1
BEGIN
	EXEC @nRet = Gp_ModifyDbf	@nBillType,
								@nCostingMethod,
								@szATypeIDTemp,
								@szPTypeIDTemp,
								@szBTypeIDTemp,
								@szETypeIDTemp,
								@szKTypeIDTemp,
								@szSTypeIDTemp,
								'',
								@dQty,
								@dTotal,
								@dntotal,
								@cid,
								@szJobNumber,
								@nGoodsNo,
								'',
								'',
								'',
								0,
								0,
								@dCostPriceOut output
	IF @nRet <> 0
	BEGIN
		GOTO ERROR1
	END

	IF @szATypeIDTemp = @AP_ID OR @szATypeIDTemp = @AR_ID OR @szATypeIDTemp=@YS_ID OR @szATypeIDTemp=@YF_ID
	BEGIN
		EXEC @nRet = Gp_ModifyDbf	@nBillType,
									@nCostingMethod,
									@szATypeIDTemp,
									'0',
									'0',
									'0',
									'0',
									@szSTypeIDTemp,
									'',
									@dQty,
									@dTotal,
									@dntotal,
									@cid,
									@szJobNumber,
									@nGoodsNo,
									'',
									'',
									'',
									0,
									0,
									@dCostPriceOut output

		IF @nRet <> 0
		BEGIN
			GOTO ERROR1
		END
	END



	FETCH NEXT FROM Manage_Cursor INTO	@nBillNumberID,
										@nBillType,
										@szATypeIDTemp,
										@szPTypeIDTemp,
										@szBTypeIDTemp,
										@szETypeIDTemp,
										@szKTypeIDTemp,
										@szSTypeIDTemp,
										@dQty,
										@dPrice,
										@dTotal,
										@dCostPrice,
										@dCostTotal,
										@szJobNumber,
										@nGoodsNo,
										@OutFactoryDate,
										@dntotal,
										@cid
END

CLOSE Manage_Cursor
DEALLOCATE Manage_Cursor
-- commit tran Rep_Trans
RETURN 0

ERROR1:
	CLOSE Manage_Cursor
	DEALLOCATE Manage_Cursor
	-- if @@trancount<>0 rollback tran Rep_Trans
	-- print @nret
	RETURN @nRet


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	批量处理应收,应付(用于升级)
*/
CREATE                         PROCEDURE GP_Batch_DealARAP (
	@intBillNumberID	numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@GOODS_ID			varchar(50),
		@AR_ID				varchar(50),
		@AP_ID				varchar(50),
		@SALE_INCOME_ID		varchar(50),
		@SALE_COST_ID		varchar(50),
		@PREFERENCEID		varchar(50),
		@PAY_TAXMONEY_ID	varchar(50),
		@DXGOODSMONEY_ID	varchar(50),
		@WTDXGOODS_ID		varchar(50),
		@REPAIR_INCOME_ID	varchar(50),
		@REPAIR_OUTCOME_ID	varchar(50),
		@REPAIR_PAYOUT		varchar(50),
		@PrePay_ID			varchar(50),
		@PreGathering_ID	varchar(50)

SET @GOODS_ID = '0000100001'			-- 库存商品总值
SET @AR_ID = '0000100005'				-- 应收款合计
SET @AP_ID = '0000200001'				-- 应付款合计
SET @SALE_INCOME_ID = '0000300001'		-- 销售收入
SET @SALE_COST_ID = '0000400001'		-- 销售成本
SET @PREFERENCEID = '000040000300004'	-- 优惠金额
SET @PAY_TAXMONEY_ID = '0000200004'		-- 应交税金
SET @DXGOODSMONEY_ID = '0000200003'		-- 受托代销商品款(即：『代销商品款』)
SET @WTDXGOODS_ID = '0000100008'		-- 『委托代销商品』
SET @REPAIR_INCOME_ID = '000030000200008' -- 商品维修收入
SET @REPAIR_OUTCOME_ID='000040000200003' --商品维修支出
SET @REPAIR_PAYOUT = '000040000200004'	-- 商品送修支出

SELECT
	@PrePay_ID='0000100009',			--预付账款
	@PreGathering_ID='0000200006'		--预收账款




DECLARE	
		@numYSYFMoney		 NUMERIC(24, 10) ,
		@nRet				INT,
		@intReturnID		INT,				--新生成的单据的ID
		@strReturnBillCode	VARCHAR(200),
		@strErrMsg			VARCHAR(2000),		--出错信息
		@intCostSale		INT,
		@numBillType		numeric(4,0),
		@datBillDate		datetime,
		@chvATypeID			varchar(50),
		@chvBTypeID			varchar(50),
		@chvETypeID			varchar(50),
		@chvKTypeID			varchar(50),
		@chvKTypeID2		varchar(50),
		@chvDTypeID			varchar(50),
		@chvSTypeID			varchar(50),
		@numTotalMoney		 NUMERIC(24, 10) ,
		@numTotalInMoney	 NUMERIC(24, 10) ,
		@numPreferenceMoney	 NUMERIC(24, 10) ,
		@intRowCount		int,
		@intVipCardID		int,			-- VIP卡ID值
		@intVipCardTypeID	int,			-- VIP卡类型ID值
		@chrIfVipJF			char(1),		-- 卡类型是否积分标识
		@intVipGridJF		int,			-- 单据GRID每行商品的积分
		@intVipJF			int,			-- 单据总积分
		@numVipTotalMoney	 NUMERIC(24, 10) ,	-- 单据消费金额 = 单据金额
		@chvVipIsCz			varchar(1),		-- 是否VIP会员储值
		@numVipCzTotalInMoney  NUMERIC(24, 10) ,	-- 单据VIP会员储值对应的实收/付金额
		@numVipcZyeMoney	 NUMERIC(24, 10) ,	-- VIP会员储值余额
		@numTax				 NUMERIC(24, 10) ,
		@numDiscount		 NUMERIC(24, 10) ,
		@numSalePrice		 NUMERIC(24, 10) ,
		@numSaleTotal		 NUMERIC(24, 10) ,
		@numTaxPrice		 NUMERIC(24, 10) ,
		@numTaxTotal		 NUMERIC(24, 10) ,
		@wxProperty			int,	-- 维修属性，0：正常商品；1：维修商品
		@ifDetailWX			int,	-- （单据明细）是否属于维修库的出入库记录，0：正常库；1：维修库
		@ifIndexWX			int,	-- （单据索引）是否针对维修库存进行盘点、报损、报溢；0：正常库，1：维修库
		@intRedWord			int

SELECT	@numBillType = BillType,
		@datBillDate = BillDate,
		@chvATypeID = ATypeID,
		@chvBTypeID = BTypeID,
		@chvETypeID = ETypeID,
		@chvKTypeID = KTypeID,
		@chvKTypeID2 = KTypeID2,
		@chvDTypeID	=DTypeID,
		@chvSTypeID=STypeID,
		@numTotalMoney = TotalMoney,
		@numTotalInMoney = TotalInMoney,
		@numPreferenceMoney = PreferenceMoney,
		@intVipCardID = VipCardID,
		@numTax = Tax,
		@ifIndexWX = ifWX,
		@intCostSale=CostSale,
		@intRedWord=RedWord
FROM	BillIndex
WHERE	BillNumberID = @intBillNumberID

IF @@ROWCOUNT = 0 OR @@ERROR <> 0
BEGIN
	--RAISERROR('读取BillIndex发生错误',16,1)
	RETURN -10
END

--
IF @numBillType IN (11,305,45)	-- 销售、零售、销售退货的VIP判断及消费、积分处理
BEGIN
	IF @intVipCardID <> -1
	BEGIN
		SELECT	@chrIfVipJF = b.ifJF,
				@chvVipIsCz = a.IsCz,
				@numVipcZyeMoney = a.cZyeMoney
		FROM	nVipCardSign a,nVipCardSet b
		WHERE	a.VipCardID = @intVipCardID
				AND a.VipCardTypeID = b.VipCardTypeID
				AND a.Deleted = '0'
				AND b.Deleted = '0'
				AND a.EndDate >= @datBillDate

		
		SET @numVipTotalMoney = @numTotalMoney

		
	END
END

-- 
DECLARE	@chvSQL					varchar(8000),
		@chvDBName				varchar(50),
		@numARTotal				 NUMERIC(24, 10) ,		-- 往来单位当前应收
		@numAPTotal				 NUMERIC(24, 10) ,		-- 往来单位当前应付
		@numBillARTotal			 NUMERIC(24, 10) ,		-- 单据本次应收
		@numBillAPTotal			 NUMERIC(24, 10) ,		-- 单据本次应付
		@chvPTypeID				varchar(50),
		@numQty					 NUMERIC(24, 10) ,
		@numPrice				 NUMERIC(24, 10) ,
		@numTotal				 NUMERIC(24, 10) ,
		@chvJobNumber			varchar(20),
		@datOutFactoryDate		datetime,
		@numOutPutQty			 NUMERIC(24, 10) ,
		@numInputCostPrice		 NUMERIC(24, 10) ,		-- 成本单价
		@numBanlanceTotal		 NUMERIC(24, 10) ,		-- 差额
		@numNoTaxTotal			 NUMERIC(24, 10) ,
		@numQtyTemp				 NUMERIC(24, 10) ,
		@numQtyTemp1			 NUMERIC(24, 10) ,		
		@numPriceTemp			 NUMERIC(24, 10) ,
		@numPriceTemp1			 NUMERIC(24, 10) ,
		@numTotalTemp			 NUMERIC(24, 10) ,
		@numTotalTemp1			 NUMERIC(24, 10) ,
		@numCostPriceTemp		 NUMERIC(24, 10) ,
		@numCostPriceTemp1		 NUMERIC(24, 10) ,
		@numCostTotalTemp		 NUMERIC(24, 10) ,
		@numCostTotalTemp1		 NUMERIC(24, 10) ,
		@numTaxBanlance			 NUMERIC(24, 10) ,		-- 税额
		@numTotalInMoneyTemp	 NUMERIC(24, 10) ,
		@numPreferenceMoneyTemp	 NUMERIC(24, 10) ,
		@numJTotal				 NUMERIC(24, 10) ,		-- 会计凭证 - 借方金额
		@numDTotal				 NUMERIC(24, 10) ,		-- 会计凭证 - 贷方金额
		@chvTypeATypeID			varchar(50),		-- 会计凭证 - 总账科目 ID 值
		@intReturnCode			int,
		@chrInOrOut				char(1),			-- 换货单中的出入库标记
		@GoodsNumber			varchar(100),		-- 批号
		@ProduceDate			varchar(50),		-- 生产日期
		@ValidDate				varchar(50),		-- 效期至
		@GoodsBTypeID			varchar(50),		-- 供货商ID值
		@GoodsCostPrice			 NUMERIC(24, 10) ,		-- 批次成本单价
		@HandZeroCost			int,				-- 是否为0成本入库标识
		@ChangeAllStock			int,				-- 是否调整全部仓库的成本价
		@CostingMethod			int,				-- 成本算法
		@intID					int					-- 单据明细排序自增加ID值

------------------------------ 销售出库单
IF @numBillType = 11
BEGIN
	
	-- ********* 处理生成 ListTable 凭证记录 *********
	-- 实收金额

	-- 优惠金额
	

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0) FROM SaleBill WHERE BillNumberID = @intBillNumberID
	

	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	
	
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1
	
	
	RETURN 0
END
------------------------------ 采购退货单
IF @numBillType = 6
BEGIN
	-- 实收金额
	
	-- 优惠金额
	
	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0) FROM BuyBackBill WHERE BillNumberID = @intBillNumberID
	

	-- 计算是否有往来差额
	SET @numBanlanceTotal = (@numTotalMoney - @numTotalInMoney - @numPreferenceMoney)*(-1)
	
	
	
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AP',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1
	

	RETURN 0
END
------------------------------ 采购入库单
IF @numBillType = 34
BEGIN
	
	-- 实付金额
	

	-- 优惠金额
	

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0) FROM BuyBill WHERE BillNumberID = @intBillNumberID
	

	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AP',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END
------------------------------ 销售退货单
IF @numBillType = 45
BEGIN
	
	-- 实付金额
	

	-- 优惠金额
	

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0) FROM SaleBackBill WHERE BillNumberID = @intBillNumberID
	
	-- 计算是否有往来差额
	SET @numBanlanceTotal = (@numTotalMoney - @numTotalInMoney - @numPreferenceMoney)*(-1)
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	

	RETURN 0
END
------------------------------ 收款单
IF @numBillType = 4
BEGIN
	
	-- 优惠金额


	-- 计算是否有往来差额
	SET @numBanlanceTotal = (@numTotalInMoney + @numPreferenceMoney)*(-1)
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END
-- 付款单
IF @numBillType = 66
BEGIN
	

	-- 优惠金额
	

	-- 计算是否有往来差额
	SET @numBanlanceTotal = (@numTotalInMoney + @numPreferenceMoney)*(-1)
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AP',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END
------------------------------ 零售单
IF @numBillType = 305
BEGIN
	
	-- 实收金额
	
	-- 优惠金额
	

	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	
	RETURN 0

END
------------------------------ 会计凭证
IF @numBillType = 159
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FOR
		SELECT	TypeATypeID,
				ATypeID,
				J_Total,
				D_Total,
				ID
		FROM	AccountCredence
		WHERE	BillNumberID = @intBillNumberID
		AND TypeATypeID IN ('0000100005','0000200001')

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvTypeATypeID,
											@chvATypeID,
											@numJTotal,
											@numDTotal,
											@intID
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @numJTotal > 0
		BEGIN
			IF LEFT(@chvTypeATypeID,5) IN ('00001','00004')	-- 借方科目
				SET @numTotal = @numJTotal
			ELSE
				SET @numTotal = -@numJTotal
		END
		ELSE
		BEGIN
			IF LEFT(@chvTypeATypeID,5) IN ('00001','00004')	-- 借方科目
				SET @numTotal = -@numDTotal
			ELSE
				SET @numTotal = @numDTotal
		END

		-- 循环写入 ListTable
			
		IF @chvTypeATypeID IN( '0000100005','0000200001','0000100009','0000200006','0000100010')	-- 应收/付款合计
		BEGIN
			EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@chvTypeATypeID,@chvATypeID,@chvETypeID,
				@numTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
		END
		ELSE
		BEGIN	
			EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
					@numTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID	
		END
	
		
		IF @intReturnCode <> 0 GOTO ERROR1
		
	
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvTypeATypeID,
												@chvATypeID,
												@numJTotal,
												@numDTotal,
												@intID
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END
------------------------------ 受托代销结算
IF @numBillType = 145
BEGIN
	DECLARE	@numSTDXPrice		 NUMERIC(24, 10) ,
			@numSTDXTotal		 NUMERIC(24, 10) ,
			@numSTDXCostPrice	 NUMERIC(24, 10) ,
			@numSTDXCostTotal	 NUMERIC(24, 10) ,
			@numSTDXQty			 NUMERIC(24, 10) 

	
	SELECT	@numNoTaxTotal = -ISNULL(SUM(Total),0)
	FROM	CommissionBill
	WHERE	BillNumberID = @intBillNumberID

	
	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AP',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END
------------------------------ 销售换货单
IF @numBillType = 160
BEGIN
	-- 实收金额
	-- 优惠金额

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(CASE InOrOut WHEN 'O' THEN Total ELSE -Total END),0) FROM SaleGoodsExchangeBill WHERE BillNumberID = @intBillNumberID

	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END
------------------------------ 采购换货单
IF @numBillType = 161
BEGIN
	-- 实付金额

	-- 优惠金额

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(CASE InOrOut WHEN 'I' THEN Total ELSE -Total END),0) FROM BuyGoodsExchangeBill WHERE BillNumberID = @intBillNumberID

	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AP',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END
------------------------------ 维修受理单
IF @numBillType = 157
BEGIN
	-- 实收金额
	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END
------------------------------ 委托代销结算
IF @numBillType = 141
BEGIN
	DECLARE @DXAllCostTotal  NUMERIC(24, 10) 
	SET @DXAllCostTotal = 0


	SELECT	@numNoTaxTotal = ISNULL(SUM(Total),0)
	FROM	CommissionBill
	WHERE	BillNumberID = @intBillNumberID


	-- 销售收入
	
	-- 实收金额
	
	-- 销售成本
	
	SET @DXAllCostTotal = -@DXAllCostTotal
	-- 委托代销商品款
	
	-- 应交税金
	
	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney
	IF @numBanlanceTotal <> 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
			@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
		IF @intReturnCode <> 0 GOTO ERROR1
	END

	RETURN 0
END
------------------------------ (新维修) - 维修取件单
IF @numBillType = 167
BEGIN
	-- 实收金额
	
	-- 优惠金额
	
	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	
	RETURN 0
END
------------------------------ (新维修) - 整机更换单
IF @numBillType = 168
BEGIN
	
	-- ********* 处理生成 ListTable 凭证记录 *********
	-- 实收金额
	
	-- 优惠金额
	
	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	
	RETURN 0
END
------------------------------ (新维修) - 送修返回单
IF @numBillType = 170
BEGIN
	-- 实付金额
	
	-- 优惠金额
	
	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AP',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	
	RETURN 0
END
------------------------------ (新维修) - 上门维修单
IF @numBillType = 172
BEGIN
	-- 实收金额
	
	-- 优惠金额
	
	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney
	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	
	RETURN 0
END

--------------------------(汽配)--快修单
IF @numBillType=178
BEGIN
	SELECT @numTotalMoney=TotalMoney,@numTotalInMoney=TotalInMoney
	FROM BillIndex
	WHERE BillNumberID=@intBillNumberID

	DECLARE
		@decOtherTotal  NUMERIC(24, 10) 

	SELECT @decOtherTotal=EpibolyTotal+OtherTotal
	FROM BillIndex_CarRepair
	WHERE BillNumberID=@intBillNumberID

	
	--优惠金额

	
	-- 实收金额



	-- 应交税金=工时费税额+材料费税额
	SELECT @numTaxBanlance=ManHourTaxTotal-ManHourTotal+PTypeTaxTotal-PTypeTotal
	FROM Billindex_CarRepair
	WHERE BillNumberID=@intBillNumberID

	
	-- 计算是否有往来差额
	SET @numBanlanceTotal = @numTotalMoney - @numTotalInMoney - @numPreferenceMoney


	EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
		@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID
	IF @intReturnCode <> 0 GOTO ERROR1

	
	
	RETURN 0
	
END


--------------------------(汽配)--保险理赔单

IF @numBillType=186
BEGIN
	DECLARE
		@intQuickRepairBillID INT

	SELECT @numTotal=TotalMoney,@datBillDate=BillDate,@numBillType=BillType,@chvBTypeID=BTypeID,@chvETypeID=ETypeID
	FROM BillIndex
	WHERE BillNumberID=@intBillNumberID

	SELECT @intQuickRepairBillID=ISNULL(QuickRepairBillID,0)
	FROM BillIndex_CarRepair
	WHERE BillNumberID=@intBillNumberID

	
	IF @numTotal<>0
	BEGIN	

		EXEC @intReturnCode = GP_CreateMX_InsertARAP @intBillNumberID,'AR',@datBillDate,@numBillType,@chvBTypeID,@chvETypeID,
			@numTotal,'',@datOutFactoryDate,@chvDTypeID,@chvSTypeID
		IF @intReturnCode <> 0 GOTO ERROR1
	
	

	END

	
	RETURN 0
END


------------------------------调帐单--------------------------

DECLARE
	@dbName			VARCHAR(100),
	@dBcAr			 NUMERIC(24, 10) , --本次应收
	@dBcAp			 NUMERIC(24, 10) , --本次应付
	@dTempQty		 NUMERIC(24, 10) ,
	@dTempAr		 NUMERIC(24, 10) ,
	@dTempAp		 NUMERIC(24, 10)  
 

-----应收增加 应收减少
 IF (@numBillType IN (115,116))
 BEGIN
  SELECT @dbname='Addebtbill'
--  BEGIN tran AppendMxTz
 
  SELECT @chvSQL='DECLARE CreateMxTz_cursor CURSOR FOR '
    +' SELECT btypeid,total FROM '
    +@dbname+' WHERE BillNumberId= '+CAST(@intBillNumberID AS VARCHAR(10))
  EXEC (@chvSQL)
  OPEN CreateMxTz_cursor
  FETCH NEXT FROM CreateMxTz_cursor INTO @chvBTypeID,@numTotalMoney
  WHILE @@FETCH_STATUS=0
  BEGIN
	   --得到当前应收余额
	   
	   
	   IF @numBillType=115
	   BEGIN
			 --应收减少
			 INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			   qty,price,total,STypeID,DTypeID)
			 VALUES(@intBillNumberID,@datBillDate,@numBillType,@AR_ID,'0',@chvBTypeID,@chvETypeID,'0',0
			  ,0,-@numTotalMoney,@chvSTypeID,@chvDTypeID)
	   END
	   ELSE
	   BEGIN
			 --应收增加
			 INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			   qty,price,total,STypeID,DTypeID)
			 VALUES(@intBillNumberID,@datBillDate,@numBillType,@AR_ID,'0',@chvBTypeID,@chvETypeID,'0',0
			  ,0,@numTotalMoney,@chvSTypeID,@chvDTypeID)
	   END
	   
	   FETCH NEXT FROM CreateMxTz_cursor INTO @chvBTypeID,@numTotalMoney
  END 
 
  CLOSE CreateMxTz_cursor 
  DEALLOCATE CreateMxTz_cursor

  RETURN 0

 END
 
 
 -----应付增加&应付减少
 IF (@numBillType IN (128,129))
 BEGIN
  SELECT @dbname='Addebtbill'

 
  SELECT @chvSQL='DECLARE CreateMxTz_cursor CURSOR FOR '
    +' SELECT btypeid,total FROM '
    +@dbname+' WHERE BillNumberId= '+CAST(@intBillNumberID AS VARCHAR(10))
  EXEC (@chvSQL)
  OPEN CreateMxTz_cursor
  FETCH NEXT FROM CreateMxTz_cursor INTO @chvBTypeID,@numTotalMoney
  WHILE @@FETCH_STATUS=0
  BEGIN
   ------得到当前应付余额
   
   IF @numBillType=128
   BEGIN
		--应付增加
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
		qty,price,total,STypeID,DTypeID)
		VALUES(@intBillNumberID,@datBillDate,@numBillType,@AP_ID,'0',@chvBTypeID,@chvETypeID,'0',0
		,0,@numTotalMoney,@chvSTypeID,@chvDTypeID)
   END
   ELSE
   BEGIN
		--应付减少
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
		qty,price,total,STypeID,DTypeID)
		VALUES(@intBillNumberID,@datBillDate,@numBillType,@AP_ID,'0',@chvBTypeID,@chvETypeID,'0',0
		,0,-@numTotalMoney,@chvSTypeID,@chvDTypeID)
   END
 
   
   FETCH NEXT FROM CreateMxTz_cursor INTO @chvBTypeID,@numTotalMoney
  END 
 
  CLOSE CreateMxTz_cursor 
  DEALLOCATE CreateMxTz_cursor

  RETURN 0

END
------------------------------调帐单处理结束--------------------------
DECLARE
	@chvATypeIDtemp	VARCHAR(50)
--------------------------------钱流单处理开始--------------------------
--支出类	--158 现金费用单	--36 一般费用单	--84 固定资产购买
--收入类	--93 其他收入--85 固定资产变卖
--其他		--78 固定资产折旧--5  待摊费用发生--10 待摊费用摊销 
IF @numBillType IN (5,10,35,36,78,84,85,93,158)
BEGIN		
   
	IF @numBillType IN(84,36,35)
	BEGIN
		SELECT @dBcAp=@numTotalMoney-@numTotalInMoney
		
		IF @dBcAp<>0
		BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			qty,price,total,JobNumber,OutFactoryDate,DTypeID,STypeID)
			VALUES(@intBillNumberID,@datBillDate,@numBillType,@AP_ID,'0',@chvBTypeID,@chvETypeID,'0',0
			,0,@dBcAp,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID)
			
			
		END
	END
	ELSE IF @numBillType IN (93,85) --其他收入,固定资产变卖
	BEGIN
		
		SELECT @dBcAr=@numTotalMoney-@numTotalInMoney
		
		IF @dBcAr<>0
		BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			qty,price,total,JobNumber,OutFactoryDate,DTypeID,STypeID)
			VALUES(@intBillNumberID,@datBillDate,@numBillType,@AR_ID,'0',@chvBTypeID,@chvETypeID,'0',0
			,0,@dBcAr,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID)
			
		END	
	END
	
END
--------------------------------钱流单处理结束--------------------------



--------------------------------返利执行单148、价保执行单149、获利核算执行单150,获得价保执行单151-----------------------
IF @numBillType IN (148,149,150,151)
BEGIN
		DECLARE @intATypeID VARCHAR(50)

		
		IF @numBillType IN (148,150)
			SELECT @numTotalMoney=SUM(total) FROM Advantage WHERE BillNumberId=@intBillNumberID
		ELSE
			SELECT @numTotalMoney=SUM(total) FROM PriceProtectBill WHERE BillNumberId=@intBillNumberID

		/*
		价保执行是我的应收减少，获得价格是我的应付减少
		返利是我的应收减少，获利是我的应付减少
		*/
		
		DECLARE
			@tmpATypeID		VARCHAR(50),
			@tmpTotal		 NUMERIC(24, 10) 
		
		IF @numBillType IN (148,149)
		BEGIN
			--返利执行单,价保执行单
			SELECT 
				@tmpATypeID=@AR_ID,
				@tmpTotal=(@numTotalMoney-@numTotalInMoney)*(-1)
				
			------得到当前应收余额
			EXEC Gp_Getdbf @AR_ID,'0',@chvBTypeID,'0','0',@chvSTypeID,'','',@dTempQty OUTPUT,@dTempAr OUTPUT
				
		END
		ELSE IF @numBillType IN (150,151)
		BEGIN
			--获利执行单,获得价保
			SELECT 
				@tmpATypeID=@AP_ID,
				@tmpTotal=(@numTotalMoney-@numTotalInMoney)*(-1)
				
			------得到当前应付余额
			EXEC Gp_Getdbf @AP_ID,'0',@chvBTypeID,'0','0',@chvSTypeID,'','',@dTempQty OUTPUT,@dTempAr OUTPUT		
		END
		
		IF @tmpTotal<>0
		BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			qty,price,total,JobNumber,OutFactoryDate,DTypeID,STypeID)
			VALUES(@intBillNumberID,@datBillDate,@numBillType,@tmpATypeID,'0',@chvBTypeID,@chvETypeID,'0',0
			,0,@tmpTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID)
			
		END

		RETURN 0

END
--------------------------------返利执行单处理结束--------------------------


ERROR1:
	RETURN @intReturnCode
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：吴雷
	日期：2013.11.25
	描述：乐言-业务凭证生成凭证特殊处理
			
*/
CREATE PROCEDURE GP_BatchCreateVoucher_AccountCredence
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0 ,
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				--0.即时生成凭证 1.经营历程生成	
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''


--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID			INT,				--收付款项目
	ATypeID1		VARCHAR(50),
	sharefee		 NUMERIC(24, 10)  DEFAULT 0,--分摊费用
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	balancemoney	 NUMERIC(24, 10) ,		--平衡数
	RedWord			INT			,		--红冲标识
	explain			VARCHAR(MAX),		--说明
	comment			VARCHAR(MAX),		--摘要
	isauto			INT					--1.业务调汇生成
	,AtId			INT
)

INSERT INTO #TmpBillInfo
        ( BillNumberId ,
          StypeId ,
          VerifyStypeid ,
          DTypeId ,
          BTypeId ,
          ETypeId,
          DealBTypeId ,
          ATypeID,
          ATypeID1,
          Cid ,
          Rate ,
          RateType,
          RedWord,
          explain,
          comment,
          isauto
          ,AtId
        )
SELECT  T1.BillNumberId,
		T1.Stypeid,
		T2.VerifyID,
		T1.DTypeId,
		T1.btypeid,
		T1.etypeid,
		T1.DealBTypeID,
		T1.ATypeID,
		T1.ATypeID1,
		T1.CID,
		T1.Rate,
		T3.BasisType,
		T1.RedWord,
		T1.explain,
		T1.Comment,
		ISNULL(T1.IsAuto,0)
		,@AtId
FROM dbo.BillIndex T1
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
WHERE T1.BillNumberId IN (SELECT a FROM #BillNumberId)

DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

--乐言订制 业务凭证159 特殊模板
DECLARE @BillCount		INT,				--单据数
		@Comment		VARCHAR(400),		--表头说明内容
		@FieldID		VARCHAR(100),		--表头说明字段ID
		@IsCombine		INT					--是否合并明细

--是否合并明细
SELECT @IsCombine = IsCombineRow,@FieldID = ExplainAuditType FROM dbo.Ac_Auditing_Template WHERE AtId = @AtId

--表头说明
DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)


SELECT @MinNumber = MIN(a) FROM #BillNumberId
SELECT @MaxNumber = MAX(a) FROM #BillNumberId

SELECT @BillCount = COUNT(*) FROM #TmpBillInfo
--多单据，表头说明默认“由X张业务凭证合并生成”
IF @BillCount > 1
	SET @Comment = '由'+CAST(@BillCount AS VARCHAR(10))+'张业务凭证合并生成'
--单张时按配置取
ELSE
BEGIN
	SET @Index = @MinNumber

	CREATE TABLE #TempStr
	(
		RowNo		INT IDENTITY(1,1),
		SummaryStr VARCHAR(MAX),
		SummaryType	INT
	)


	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split(@FieldID,',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		SET @Index += 1
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr
	
	IF @str <> ''
		SET @str += ';'
	
	IF ISNULL(@FieldID,'') <> '7'
		SET @Comment = SUBSTRING(@str,0,400)
	ELSE 
		SELECT @Comment = Explaintext FROM dbo.Ac_Auditing_Template WHERE AtId = @atid
	
END

--更新表头“说明”
UPDATE dbo.Ac_Voucher SET FComment = @Comment WHERE BillNumberId = @VoucherId

--将模板明细处理到临时表中,进行读取字段生成摘要
-----------------------------------------------
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

SET @Index = @MinNumber

IF @BillCount = 1
	TRUNCATE TABLE #TempStr

WHILE @MinDid <= @MaxDid
BEGIN
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		SET @Index += 1
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = @str WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	UPDATE #TmpVoucherDetails SET Summary = '业务凭证生成' WHERE ISNULL(Summary,'') = ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	SET @MinDid += 1
END

UPDATE #TmpVoucherDetails SET Summary = LEFT(Summary,197)+'...' WHERE LEN(Summary) > 200

-----------------------
--处理摘要完成


--判断摘要采用“行摘要”还是默认文字
DECLARE @useText INT
IF EXISTS (SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE ISNULL(Summary,'')= '业务合并生成')
	SET @useText = 1
ELSE
	SET @useText = 0


--业务凭证特殊处理表
CREATE TABLE #tmpAccountCredence
(
	billnumberid	INT,
	TypeAtypeID		VARCHAR(50),
	j_total			 NUMERIC(24, 10) ,
	d_total			 NUMERIC(24, 10) ,
	cid				INT,
	ratetype		INT,
	rate			 NUMERIC(24, 10) ,
	ATypeID			VARCHAR(50),
	id				INT IDENTITY(1,1),
	rowno			INT,
	comment			VARCHAR(MAX),	--摘要
	nj_total	    NUMERIC(24, 10) ,
	nd_total	    NUMERIC(24, 10) ,
	etypeid         VARCHAR(50),
	dtypeid			VARCHAR(50)
)


--凭证明细临时表,存储所有单据生成的凭证明细
CREATE TABLE #TmpVoucherBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	AtdId			INT,
	BillIndexId		INT,
	credenceId		INT,
	etypeid			VARCHAR(50),
	dtypeid			VARCHAR(50)
)

--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	fieldname			VARCHAR(100),
	BillIndexNumberId	INT			,	--单据ID
	credenceid			INT
)

DECLARE @VerifyidValue	VARCHAR(50)--核算机构
		
DECLARE @IsUseBillMoneyData INT
		,@UseBillMoneyDate_BillTypes VARCHAR(200)
		,@sql VARCHAR(MAX)

SELECT @UseBillMoneyDate_BillTypes=SubValue  FROM sysdata WHERE SubName = 'usebillmoneydate'
SET @IsUseBillMoneyData = 0

IF EXISTS (SELECT TOP 1 1 FROM F_Split(@UseBillMoneyDate_BillTypes,',') WHERE a = @BillType)
	SET @IsUseBillMoneyData = 1
	
	SELECT TOP 1 @VerifyidValue =VerifyStypeid FROM #TmpBillInfo
	
		--更新总计的分摊值
		UPDATE #TmpBillInfo
		SET sharefee = total
		FROM #TmpBillInfo T1
		INNER JOIN
		(
			SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.shareFee ELSE a.ShareFee END) AS total,
								a.BillNumberId
				FROM dbo.ShareSourceBill a
				INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
				--WHERE a.BillNumberId = @currentid
				GROUP BY a.BillNumberId
		)TT ON T1.billnumberid = TT.billnumberid
		--WHERE T1.billnumberid = @currentid
		
	
	
	
	--业务凭证对应科目生成凭证明细
	SELECT AtdId,Express,BB.Rate AS rate,BB.RateType AS ratetype,BB.BillNumberId AS billnumberid
	INTO #tmpJDItemDetail
	FROM dbo.Ac_Auditing_Template_Detail T
	INNER JOIN #TmpBillInfo BB ON BB.AtId = T.Atid
	WHERE AcFrom IN (6,7)
	
	
	INSERT INTO #tmpAccountCredence
		(
			billnumberid,
			TypeAtypeID,
			j_total,
			d_total,
			cid,
			ratetype,
			rate,
			ATypeID,
			comment,			
			nj_total,
			nd_total,
			a.etypeid,
			a.dtypeid
		)
	SELECT a.BillNumberId,TypeAtypeId,
			CASE WHEN b.RedWord = 2 THEN -J_Total ELSE J_Total END AS j_total,
			0 AS d_total,
			a.cid,
			c.BasisType,
			a.Rate,
			a.ATypeID,
			a.Comment,
			a.NJ_Total,
			a.ND_Total,
			a.etypeid,
			a.dtypeid
	FROM	dbo.AccountCredence a
	INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberID
	INNER JOIN dbo.Ac_Currency c ON a.CID = c.CId
	--WHERE	a.BillNumberId =@currentid
	UNION ALL
	SELECT a.BillNumberId,TypeAtypeId,
			0 AS j_total,
			CASE WHEN B.RedWord = 2 THEN -D_Total ELSE D_Total END AS d_total,
			a.cid,
			c.BasisType,
			a.Rate,
			a.ATypeID,
			a.Comment,
			0 AS nj_total,
			CASE WHEN B.RedWord = 2 THEN -a.ND_Total ELSE a.ND_Total END AS nd_total,
			a.etypeid,
			a.dtypeid
	FROM	dbo.AccountCredence a
	INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberID
	INNER JOIN dbo.Ac_Currency c ON a.CID = c.CId
	--WHERE	a.BillNumberId =@currentid
	

	DELETE FROM #tmpAccountCredence WHERE j_total = 0 AND d_total = 0


	INSERT INTO #TmpVoucherBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  atdid,
			  credenceId,
			  BillIndexId,
			  etypeid,
			  dtypeid
			)
	SELECT DISTINCT * FROM
	(
	SELECT	@VoucherId AS billnumberid,
			CASE @useText WHEN 1 THEN '业务合并生成' ELSE b.comment END AS explain,
			e.ATypeId AS atypeid,
			'' AS atypeid2,
			f.Fdc ,
			@f_exchid AS f_exchid,
			CASE WHEN b.cid = f.cid OR f.cid = 0 THEN b.cid ELSE fc.cid END AS f_exchidfor,
			CASE c.Fdc
				WHEN 1	THEN b.j_total
				WHEN -1 THEN 0
			END AS lendprice,
			CASE c.Fdc
				WHEN -1 THEN b.d_total
				WHEN 1	THEN 0
			END AS loanprice,
			CASE WHEN BB.isauto = 1 AND b.TypeAtypeId <> 53 THEN 0
			ELSE 
				CASE c.Fdc 
					WHEN 1 THEN 
						CASE 
						WHEN @IsUseBillMoneyData = 1 THEN b.nj_total 
						WHEN b.cid = f.cid OR f.cid = 0 THEN
							(CASE b.ratetype 
								WHEN 0 THEN b.j_total / b.rate
								WHEN 1 THEN b.j_total * b.rate
							END)
						ELSE
							(CASE fc.BasisType  
								WHEN 0 THEN b.j_total / fc.rate
								WHEN 1 THEN b.j_total* fc.rate
							END)
						END 
					ELSE 0 
				END 
			END AS lendpricefor,
			CASE WHEN BB.isauto = 1 AND b.TypeAtypeId <> 53 THEN 0
			ELSE 
				CASE c.Fdc 
					WHEN -1 THEN
						CASE 
						WHEN @IsUseBillMoneyData = 1 THEN b.nd_total 
						WHEN b.cid = f.cid OR f.cid = 0 THEN
							(CASE b.ratetype  
								WHEN 0 THEN b.d_total / b.rate
								WHEN 1 THEN b.d_total* b.rate
							END)
						ELSE
							(CASE fc.BasisType  
								WHEN 0 THEN b.d_total / fc.rate
								WHEN 1 THEN b.d_total* fc.rate
							END)
						END 
					ELSE 0 
				END 
			END AS loanpricefor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			CASE WHEN b.cid = f.cid OR f.cid = 0 THEN b.cid ELSE fc.cid END AS cid,
			CASE WHEN b.cid = f.cid OR f.cid = 0 THEN b.rate ELSE fc.rate END AS rate,
			c.Fdc AS fadc,
			@verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId,
			b.id,
			b.billnumberid AS billid,
			b.etypeid,
			b.dtypeid
	FROM	#tmpJDItemDetail a
	INNER JOIN #tmpAccountCredence b ON b.BillNumberId IN (SELECT * FROM f_split(a.billnumberid,','))
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.billnumberid
	LEFT JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	LEFT JOIN dbo.Ac_Items d ON b.TypeAtypeId = d.nid
	LEFT JOIN dbo.Ac_Items_Detail e ON d.nId = e.nId AND e.STypeId = BB.StypeId
	LEFT JOIN dbo.Ac_Account f ON e.ATypeId = f.TypeId AND f.StypeId = @verifyidvalue
	LEFT JOIN dbo.Ac_Currency fc ON fc.CId=f.Cid
	) T 
	WHERE lendprice <> 0 OR loanprice <> 0
	ORDER BY T.AtdId
	
	--Awu:调整平衡数
	DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) 

	DECLARE BalanceCur CURSOR FOR
	SELECT billnumberid FROM #tmpbillinfo
		OPEN BalanceCur
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @balancemoney = 0
		SELECT @balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
		FROM #TmpVoucherBill
		WHERE billindexid = @BalanceBillId
		
		
		UPDATE #TmpVoucherBill 
		SET #TmpVoucherBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
			#TmpVoucherBill.lendpricefor = (CASE fadc WHEN 1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN -@balancemoney / T1.rate
												WHEN 1 THEN -@balancemoney * T1.rate
											END
									ELSE 0 END ),
			#TmpVoucherBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
			#TmpVoucherBill.loanpricefor = (CASE fadc WHEN -1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN @balancemoney / T1.rate
												WHEN 1 THEN @balancemoney * T1.rate
											END
									ELSE 0 END )
		FROM #TmpVoucherBill T1
			INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
			INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
		WHERE billindexid = @BalanceBillId
			
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	END
	CLOSE BalanceCur
	DEALLOCATE BalanceCur
	
	--如果一行摘要也没有，强行填写“业务凭证生成”
	IF NOT EXISTS(SELECT TOP 1 1  FROM #TmpVoucherBill WHERE ISNULL(explain,'') <> '' )
	BEGIN
		UPDATE #TmpVoucherBill SET explain = '业务凭证生成'
	END
	
	UPDATE #TmpVoucherBill SET explain = '业务凭证生成' WHERE ISNULL(explain,'') = '' 
	
	--获取明细对应辅助核算
	SET @sql = 'INSERT INTO #TmpAssit '
	SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'
				+CAST(T2.FieldValue AS VARCHAR(20))+'  AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,
				(SELECT name FROM syscolumns WHERE id = object_id(''billindex'') AND name = '''+
				T2.fieldvalue + ''')as fieldname, BillNumberId AS BillIndexNumberId,0 as credenceid 
				FROM #TmpBillInfo
				UNION ALL '
	FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
		LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
	WHERE T1.Atid = @Atid
	IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
		EXEC(@sql)
	END


	--业务凭证辅助核算有部分来源于单据明细中，
	--调整业务凭证的辅助核算
	
	--重新复制临时表方便下一步查询并插入值
	SELECT * INTO #T FROM #TmpAssit
	
	INSERT INTO #tmpassit
	SELECT a.atdid,a.typeid,a.ascids,a.fieldname,a.billindexnumberid,B.credenceid
	FROM #T a
		INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid
	--WHERE a.billindexnumberid = @currentid
	DELETE FROM #tmpassit WHERE credenceid = 0
	

	UPDATE #Tmpassit SET typeid = c.Atypeid
	FROM #Tmpassit a
	INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.credenceid = b.credenceid
	INNER JOIN #tmpAccountCredence c ON b.credenceid = c.id AND a.billindexnumberid = c.billnumberid
	INNER JOIN dbo.Ac_Items d ON c.TypeAtypeid = d.nId AND d.UserCode = '1132'
	WHERE fieldname = 'Stypeid'
	
	UPDATE #Tmpassit SET typeid = e.denominatedid
	FROM #Tmpassit a
	INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.credenceid = b.credenceid
	INNER JOIN #tmpAccountCredence c ON b.credenceid = c.id AND a.billindexnumberid = c.billnumberid
	INNER JOIN dbo.Ac_Items d ON c.TypeAtypeid = d.nId AND d.UserCode IN ('1151','987','2121','2131','2122')
	INNER JOIN dbo.btype e ON c.Atypeid = e.typeId
	WHERE fieldname = 'btypeid'
	
	UPDATE #Tmpassit SET typeid = c.Atypeid
	FROM #Tmpassit a
	INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.credenceid = b.credenceid
	INNER JOIN #tmpAccountCredence c ON b.credenceid = c.id AND a.billindexnumberid = c.billnumberid
	INNER JOIN dbo.Ac_Items d ON c.TypeAtypeid = d.nId AND d.UserCode IN ('1151','987','2121','2131')
	WHERE fieldname = 'DealBTypeID'
	
	--表体经手人、部门
	UPDATE #Tmpassit SET typeid = b.dtypeid
	FROM #Tmpassit a
	INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.credenceId = b.credenceId
	WHERE fieldname = 'Dtypeid'
			
	UPDATE #Tmpassit SET typeid = b.etypeid
	FROM #Tmpassit a
	INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.credenceId = b.credenceId
	WHERE fieldname = 'Etypeid'

--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)
INSERT INTO #TmpDetailsAssit
SELECT DISTINCT T1.atdid,T1.rowno,T3.ascids,T3.typeid
FROM #TmpVoucherBill T1
	INNER JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	INNER JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId AND ISNULL(T1.credenceid,0) = ISNULL(T3.credenceid,0)
WHERE ISNULL(T3.ascids,'') <> ''

DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpVoucherBill 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #TmpVoucherBill SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END

--排除数据全为0的单据编号
SELECT DISTINCT BillIndexId
INTO #TmpBillNumberId
FROM #TmpVoucherBill WHERE lendprice <> 0 OR loanprice <> 0


--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)


INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT t.*
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	lendprice	AS Lend,
	loanprice	AS Loan,
	lendpricefor AS LendFor,
	loanpricefor AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmpVoucherBill
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.OrderID,T.fadc,AC.UserCode

--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT *
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit


INSERT INTO #TmpDetailsAssit
SELECT DISTINCT 0,T1.rowno,T3.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''


--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END


DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)

--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
          explain ,
          stypeid ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill

--再一次调整合并
IF @IsCombine = 1
BEGIN
	--合并信息相同的明细，采用合并插入后再删除原来的凭证--
	DECLARE @newVoucherId INT --临时BillNumberId
	SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

	SELECT	billnumberid,
			Summary ,
			ATypeId ,
			ATypeId2 ,
			Fdc ,
			F_ExchId ,
			F_ExchIdFor ,
			FDebitTotal,
			FCreditTotal,
			FDebitTotalFor,
			FCreditTotalFor,
			FCashFlowItem ,
			AscIds ,
			FSettleNo ,
			FSettleTypeID ,
			Comment ,
			Cid ,
			IDENTITY(INT,1,1) AS rowno,
			Rate ,
			FAdc ,
			STypeId ,
			FYear ,
			FPeriod
	INTO #tmpNewVoucherBill
	FROM
	(
	SELECT  @newVoucherId AS billnumberid,
			Summary ,
			ATypeId ,
			ATypeId2 ,
			Fdc ,
			F_ExchId ,
			F_ExchIdFor ,
			SUM(FDebitTotal) AS FDebitTotal,
			SUM(FCreditTotal) AS FCreditTotal,
			SUM(FDebitTotalFor) AS FDebitTotalFor,
			SUM(FCreditTotalFor) AS FCreditTotalFor,
			FCashFlowItem ,
			AscIds ,
			FSettleNo ,
			FSettleTypeID ,
			Comment ,
			Cid ,
			Rate ,
			FAdc ,
			STypeId ,
			FYear ,
			FPeriod,
			MIN(rowno) AS initRowno
	FROM dbo.Ac_Voucher_Bill
	WHERE BillNumberId = @VoucherId
	GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod
	)TT

	INSERT INTO dbo.Ac_Voucher_Bill
			( BillNumberId ,
			  Summary ,
			  STypeId ,
			  ATypeId ,
			  ATypeId2 ,
			  Fdc ,
			  F_ExchId ,
			  F_ExchIdFor ,
			  FDebitTotal ,
			  FDebitTotalFor ,
			  FCreditTotal ,
			  FCreditTotalFor ,
			  FCashFlowItem ,
			  AscIds ,
			  FSettleNo ,
			  FSettleTypeID ,
			  FYear ,
			  FPeriod ,
			  Comment ,
			  Cid ,
			  RowNo ,
			  Rate ,
			  FAdc
			)
	SELECT  billnumberid,
			 CASE 
				WHEN LTRIM(RTRIM(Summary))='' THEN ''
				WHEN RIGHT(LTRIM(RTRIM(Summary)),1) = ';' THEN LEFT(LTRIM(RTRIM(Summary)),LEN(LTRIM(RTRIM(Summary)))-1)
				ELSE LTRIM(RTRIM(Summary))
			  END ,				
			STypeId ,
			ATypeId ,
			ATypeId2 ,
			Fdc ,
			F_ExchId ,
			F_ExchIdFor ,
			FDebitTotal,
			FDebitTotalFor,
			FCreditTotal,
			FCreditTotalFor,
			FCashFlowItem ,
			AscIds ,
			FSettleNo ,
			FSettleTypeID ,
			FYear ,
			FPeriod,
			Comment ,
			Cid ,
			rowno,
			Rate ,
			FAdc
	FROM #tmpNewVoucherBill
	
	--更新表头分录数
	UPDATE dbo.Ac_Voucher SET FEntryCount = (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId)

	--删除旧分录数据
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId

	--替换临时BillNumberId为真实的
	UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @VoucherId WHERE BillNumberId = @newVoucherId
	--------合并完成--------- 
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #TmpBillInfo,#TmpVoucherBill,#TmpAssit,#TmpDetailsAssit,#TmpNewBill,#TmpDetailsRow,#BillNumberId

IF @isCombine = 1
	DROP TABLE #tmpNewVoucherBill

	
RETURN @VoucherId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.05.12
	描述：调拨单310凭证生成
			
*/
CREATE PROCEDURE GP_BatchCreateVoucher_CapitalTransfer
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期
	@Fyear			INT,
	@Fperiod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0,
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0, 				-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

--  -1.调出 1.调入
DECLARE @InOutType INT
SELECT @InOutType = InOutType FROM dbo.Ac_Auditing_Template WHERE BillType = 310 AND AtId = @AtId

DECLARE @flag INT,--是否有异常
		@AutoFlag INT --即时生成的异常
SET @flag = 0
SET @AutoFlag = 0


--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	Id				INT,				--明细id
	StypeId			VARCHAR(50),		--分支机构ID
	stypeid2		VARCHAR(50),		--调入分支
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	ETypeId			VARCHAR(50),		--职员ID
	dtypeid			VARCHAR(50),		--部门id
	RedWord			INT,
	btypeid			VARCHAR(50),
	dealbtypeid		VARCHAR(50),		
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	balancemoney	 NUMERIC(24, 10) ,		--平衡数
	transferprice	 NUMERIC(24, 10) ,		--调拨金额【三个本质是一样的值】
	transferprice_c	 NUMERIC(24, 10) ,		--调拨金额（现金）
	transferprice_b	 NUMERIC(24, 10) ,		--调拨金额（银行）
	deductprice		 NUMERIC(24, 10) ,		--手续费金额【三个本质是一样的值】
	deductprice_c	 NUMERIC(24, 10) ,		--手续费金额（现金）
	deductprice_b	 NUMERIC(24, 10) 		--手续费金额（账户）
	,Atid			INT
)

IF @InOutType = -1
	INSERT INTO #TmpBillInfo
			(
			  BillNumberId ,
			  id,
			  StypeId ,
			  VerifyStypeid ,
			  stypeid2,
			  ETypeId ,
			  dtypeid,
			  RedWord,
			  btypeid,
			  dealbtypeid,
			  Cid ,
			  Rate ,
			  RateType ,
			  balancemoney ,
			  transferprice ,
			  transferprice_c ,
			  transferprice_b,
			  deductprice,
			  deductprice_c,
			  deductprice_b
			  ,Atid
			)
	SELECT	T1.BillNumberId,
			T4.id,
			T1.Stypeid,
			T2.VerifyID,
			T1.StypeID2,
			T1.etypeid,
			T1.DTypeId,
			0,
			'',
			'',
			T1.CID,
			T1.Rate,
			T3.BasisType,
			0,
			T4.NTransferPrice,
			CASE WHEN T1.TransferType = 1 THEN T4.NTransferPrice ELSE 0 END,
			CASE WHEN T1.TransferType = 2 THEN T4.NTransferPrice ELSE 0 END,
			CASE WHEN T1.FeeDeductType = 1 
					THEN T4.NDeductPrice
				ELSE 0 
			END,
			CASE WHEN T1.FeeDeductType = 1 THEN 
				CASE WHEN T1.TransferType = 1 THEN T4.NDeductPrice ELSE 0 END
				ELSE 0
			END,
			CASE WHEN T1.FeeDeductType = 1 THEN 
				CASE WHEN T1.TransferType = 2 THEN T4.NDeductPrice ELSE 0 END
				ELSE 0
			END
			,@AtId
	FROM dbo.BillIndex T1
		INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
		INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
		INNER JOIN dbo.CapitalTransfer_Bill T4 ON T1.BillNumberId = T4.BillNumberId
	WHERE T1.BillNumberId IN (SELECT a FROM #BillNumberId)
ELSE
	INSERT INTO #TmpBillInfo
			(
			  BillNumberId ,
			  id,
			  StypeId2,
			  VerifyStypeid,
			  stypeid,
			  ETypeId ,
			  dtypeid,
			  RedWord,
			  btypeid,
			  dealbtypeid,
			  Cid ,
			  Rate ,
			  RateType ,
			  balancemoney ,
			  transferprice ,
			  transferprice_c ,
			  transferprice_b,
			  deductprice,
			  deductprice_c,
			  deductprice_b
			  ,Atid
			)
	SELECT	T1.BillNumberId,
			T4.ID,
			T1.Stypeid2,
			T2.VerifyID,
			T1.Stypeid,
			T1.etypeid,
			T1.DTypeId,
			0,
			'',
			'',
			T1.CID,
			T1.Rate,
			T3.BasisType,
			0,
			T4.NTransferPrice,
			CASE WHEN T1.TransferType = 1 THEN T4.NTransferPrice ELSE 0 END,
			CASE WHEN T1.TransferType = 2 THEN T4.NTransferPrice ELSE 0 END,
			CASE WHEN T1.FeeDeductType = 2 
					THEN T4.NDeductPrice
				ELSE 0 
			END,
			CASE WHEN T1.FeeDeductType = 2 THEN 
				CASE WHEN T1.TransferType = 1 THEN T4.NDeductPrice ELSE 0 END
				ELSE 0
			END,
			CASE WHEN T1.FeeDeductType = 2 THEN 
				CASE WHEN T1.TransferType = 2 THEN T4.NDeductPrice ELSE 0 END
				ELSE 0
			END
			,@AtId
	FROM dbo.BillIndex T1
		INNER JOIN dbo.SType T2 ON T1.StypeID2 = T2.TypeId
		INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
		INNER JOIN dbo.CapitalTransfer_Bill T4 ON T1.BillNumberId = T4.BillNumberId
	WHERE T1.BillNumberId IN (SELECT a FROM #BillNumberId)
		AND T1.IfConfirm = 1

DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1
--将模板明细处理到临时表中,进行读取字段生成摘要
-----------------------------------------------
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''

SELECT @MinNumber = MIN(a) FROM #BillNumberId
SELECT @MaxNumber = MAX(a) FROM #BillNumberId

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	RowNo		INT IDENTITY(1,1),
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

DECLARE @Id INT

WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr
	
	IF @str <> ''
		SET @str += ';'
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	--SET @MinDid += 1
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END

-----------------------
--处理摘要完成


--手工和往来对应的模板信息
CREATE TABLE #TmpExpress
(
	Atdid			INT,
	Lendloan		 NUMERIC(24, 10) ,
	Rate			 NUMERIC(24, 10) ,
	Ratetype		INT
	,billnumberid	INT
	,detailID		INT
)

--明细有调拨金额的行
CREATE TABLE #TmpItemAtypeMoney
(
	atdid			INT,
	atypeid			VARCHAR(50),
	Lendloan		 NUMERIC(24, 10) ,
	Rate			 NUMERIC(24, 10) ,
	Ratetype		INT
	,billnumberid	INT
	,detailID		INT
)

--手工及往来科目信息
CREATE TABLE #TmpBillIndexAtype
(
	Atypeid		VARCHAR(50),
	UserCode	VARCHAR(50),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Atdid		INT
	,billnumberid	INT
	,detailID		INT
)

--账户对应科目
CREATE TABLE #TmpAccountAtypeId
(
	Atypeid		VARCHAR(50),
	Fdc			INT,
	AtdId		INT
	,billnumberid	INT
	,detailID		INT
)

--项目模板明细
CREATE TABLE #TmpItemDetail
(
	AtdId				INT,			--模板明细ID
	Express				VARCHAR(1000),	--金额表达式
	Rate				 NUMERIC(24, 10) ,	--汇率
	Ratetype			INT,			--汇率计算方式
	BillIndexNumberid	INT				--单据编号
)

--收付款表体金额明细
CREATE TABLE #TmpDetailsMoney
(
	BillIndexNumberId	INT,
	AtypeId				VARCHAR(50),
	Total				 NUMERIC(24, 10) 
)

--凭证明细临时表,存储所有单据生成的凭证明细
CREATE TABLE #TmpVoucherBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	AtdId			INT,
	BillIndexId		INT,
	gbillnumberid	INT
)

--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	detailid			INT				--单据明细ID
	,billnumberid		INT
)

DECLARE @VerifyidValue	VARCHAR(50) --核算机构
		
SELECT TOP 1 @VerifyidValue=VerifyStypeid FROM	#TmpBillInfo 

DECLARE	@sql VARCHAR(MAX)

	
	--无往来科目，补空白
	IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpBillIndexAtype)
	BEGIN
		INSERT INTO #tmpBillIndexAtype
				( atypeid ,
				  usercode ,
				  fullname ,
				  fdc ,
				  atdid
				  ,billnumberid
				  ,detailID
				)
		SELECT	'','','',0,@AtdId,BB.BillNumberId,BB.Id
		FROM #TmpBillInfo BB
	END
	
		
	----处理科目来源为手工、往来、调拨账户
	SET @sql = 'insert into #tmpExpress'
	SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,('+ Express +') as lendloan,rate,ratetype,billnumberid,id
		from #TmpBillInfo 
		union all '
		FROM Ac_Auditing_Template_Detail WHERE Atid = @Atid AND AcFrom IN (1,3,12)
			
	IF LEN(@sql) > LEN('insert into #tmpExpress')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)

		EXEC(@sql)
	END
	
	IF @InOutType = -1
	BEGIN
		INSERT INTO #TmpAccountAtypeId
				(
					Atypeid
					,Fdc
					,AtdId
					,billnumberid
					,detailID
				)
		SELECT	 CASE WHEN B.TransferType = 1 THEN T1.BankAccountOut
				 ELSE T3.ATypeId
				 END
				 ,CASE WHEN B.TransferType = 1 THEN T2.Fdc
				  ELSE T4.Fdc
				  END
				 ,AtdId
				 ,BB.BillNumberId
				 ,BB.Id
		FROM dbo.Ac_Auditing_Template_Detail T
		INNER JOIN #TmpBillInfo BB ON BB.Atid = T.Atid
		INNER JOIN CapitalTransfer_Bill T1 ON T1.BillNumberId = BB.BillNumberId AND T1.ID = BB.Id
		INNER JOIN BillIndex B ON B.BillNumberId = BB.BillNumberId
		LEFT JOIN Ac_Account T2 ON T2.TypeId = T1.BankAccountOut AND T2.StypeId = BB.VerifyStypeid
		LEFT JOIN Te_BankAccount T3 ON CAST(T3.Id AS VARCHAR) = T1.BankAccountOut
		LEFT JOIN Ac_Account T4 ON T4.TypeId = T3.ATypeId AND T4.StypeId = BB.VerifyStypeid
		WHERE AcFrom = 12
	END
	ELSE
	BEGIN
		INSERT INTO #TmpAccountAtypeId
				(
					Atypeid
					,Fdc
					,AtdId
					,billnumberid
					,detailID
				)
		SELECT	 CASE WHEN B.TransferType = 1 THEN T1.BankAccountIn
				 ELSE T3.ATypeId
				 END
				 ,CASE WHEN B.TransferType = 1 THEN T2.Fdc
				  ELSE T4.Fdc
				  END
				 ,AtdId
				 ,BB.BillNumberId
				 ,BB.Id
		FROM dbo.Ac_Auditing_Template_Detail T
		INNER JOIN #TmpBillInfo BB ON BB.Atid = T.Atid
		INNER JOIN CapitalTransfer_Bill T1 ON T1.BillNumberId = BB.BillNumberId AND T1.ID = BB.Id
		INNER JOIN BillIndex B ON B.BillNumberId = BB.BillNumberId
		LEFT JOIN Ac_Account T2 ON T2.TypeId = T1.BankAccountIn AND T2.StypeId = BB.VerifyStypeid
		LEFT JOIN Te_BankAccount T3 ON CAST(T3.Id AS VARCHAR) = T1.BankAccountIn
		LEFT JOIN Ac_Account T4 ON T4.TypeId = T3.ATypeId AND T4.StypeId = BB.VerifyStypeid
		WHERE AcFrom = 12
	END
	
	--插入凭证明细 1,3 非调拨金额的
	INSERT INTO #TmpVoucherBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  AtdId,
			  BillIndexId,
			  gbillnumberid
			)
	SELECT	@VoucherId AS billnumberid,
			T1.Summary,
			CASE T3.AcFrom  WHEN 1 THEN T3.Atypeid
						 WHEN 3 THEN T3.Atypeid
						 WHEN 12 THEN T6.Atypeid
				END,
			'',
			CASE T3.AcFrom WHEN 1 THEN T4.Fdc
						WHEN 3 THEN T4.Fdc
						WHEN 12 THEN T6.Fdc
				END,
			@f_exchid,
			CASE WHEN ISNULL(T4.Cid,0) IN(-1,0) THEN BB.Cid ELSE T4.Cid END,
			CASE T1.Fdc
				WHEN 1 THEN T2.Lendloan
				ELSE 0
			END,
			CASE T1.Fdc
				WHEN -1 THEN T2.Lendloan
				ELSE 0
			END,
			CASE T1.Fdc 
				WHEN 1 THEN 
					CASE 
						WHEN ISNULL(T4.Cid,0) IN(-1,0) THEN
							CASE T2.Ratetype 
								WHEN 0 THEN T2.Lendloan /T2.Rate
								ELSE T2.Lendloan * T2.Rate
							END
						ELSE
							CASE T5.BasisType 
								WHEN 0 THEN T2.Lendloan /T5.Rate
								ELSE T2.Lendloan * T5.Rate
							END
					END
				ELSE 0 
			END,
			CASE T1.Fdc 
				WHEN -1 THEN
					CASE 
						WHEN ISNULL(T4.Cid,0) IN(-1,0) THEN
							CASE T2.Ratetype 
								WHEN 0 THEN T2.Lendloan /T2.Rate
								ELSE T2.Lendloan * T2.Rate
							END
						ELSE
							CASE T5.BasisType 
								WHEN 0 THEN T2.Lendloan /T5.Rate
								ELSE T2.Lendloan * T5.Rate
							END
					END
				ELSE 0 
			END,
			'',
			'',
			'',
			'',
			'',
			CASE WHEN ISNULL(T4.Cid,0) IN(-1,0) THEN BB.Cid ELSE T4.Cid END,
			CASE WHEN ISNULL(T4.Cid,0) IN(-1,0) THEN T2.Rate ELSE T5.Rate END,
			T1.Fdc,--模板金额方向
			@VerifyIdValue,
			@Fyear,
			@Fperiod,
			T1.AtdId,
			T2.detailID,
			T2.billnumberid
	FROM #TmpVoucherDetails T1
		LEFT JOIN #TmpExpress T2 ON T1.AtdId = T2.Atdid
		LEFT JOIN #TmpBillInfo BB ON BB.BillNumberId = T2.billnumberid AND BB.Id = T2.detailID
		LEFT JOIN dbo.Ac_Auditing_Template_Detail T3 ON T2.Atdid =T3.Atdid
		LEFT JOIN dbo.Ac_Account T4 ON T3.Atypeid = T4.TypeId AND T4.StypeId = @verifyidvalue
		LEFT JOIN dbo.Ac_Currency T5 ON T4.Cid = T5.CId
		LEFT JOIN #TmpAccountAtypeId T6 ON T1.AtdId = T6.Atdid AND T6.billnumberid = T2.billnumberid AND T6.detailID = T2.detailID
	WHERE T1.Atid = @Atid AND T1.AcFrom IN (1,3,12)

	TRUNCATE TABLE #TmpAccountAtypeId

	--Awu:调整平衡数
	DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) 

	DECLARE BalanceCur CURSOR FOR
	SELECT billnumberid FROM #tmpbillinfo
		OPEN BalanceCur
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @balancemoney = 0
		SELECT @balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
		FROM #TmpVoucherBill
		WHERE billindexid = @BalanceBillId
		
		
		UPDATE #TmpVoucherBill 
		SET #TmpVoucherBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
			#TmpVoucherBill.lendpricefor = (CASE fadc WHEN 1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN -@balancemoney / T3.rate
												WHEN 1 THEN -@balancemoney * T3.rate
											END
									ELSE 0 END ),
			#TmpVoucherBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
			#TmpVoucherBill.loanpricefor = (CASE fadc WHEN -1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN @balancemoney / T3.rate
												WHEN 1 THEN @balancemoney * T3.rate
											END
									ELSE 0 END )
		FROM #TmpVoucherBill T1
			INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
			INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
		WHERE billindexid = @BalanceBillId
			
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	END
	CLOSE BalanceCur
	DEALLOCATE BalanceCur
	
	--获取明细对应辅助核算
	SET @sql = 'INSERT INTO #TmpAssit '
	SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'
				+CAST(T2.FieldValue AS VARCHAR(20))+'  AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,billnumberid,ID AS detailid 
				FROM #TmpBillInfo
				UNION ALL '
	FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
		LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
	WHERE T1.Atid = @Atid
	IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
		EXEC(@sql)
	END


--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)
INSERT INTO #TmpDetailsAssit
SELECT DISTINCT T1.atdid,T1.rowno,T3.ascids,T3.typeid
FROM #TmpVoucherBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.detailid
WHERE ISNULL(T3.ascids,'') <> ''



DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpVoucherBill 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #TmpVoucherBill SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END

--排除数据全为0的单据编号
SELECT DISTINCT gbillnumberid
INTO #TmpBillNumberId
FROM #TmpVoucherBill WHERE lendprice <> 0 OR loanprice <> 0


--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT t.*
FROM
(
SELECT BillNumberId	,
	explain			,
	ISNULL(atypeid,'') AS atypeid,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	SUM(lendprice)	AS Lend,
	SUM(loanprice)	AS Loan,
	SUM(lendpricefor) AS LendFor,
	SUM(loanpricefor) AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmpVoucherBill
GROUP BY BillNumberId,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.OrderID,T.fadc,AC.UserCode

--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT *
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit



INSERT INTO #TmpDetailsAssit
SELECT DISTINCT 0,T1.rowno,T3.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''


--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN	
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END

DROP TABLE #tmpHasAssit
DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)

--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
         CASE 
			WHEN LTRIM(RTRIM(explain))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(explain)),1) = ';' THEN LEFT(LTRIM(RTRIM(explain)),LEN(LTRIM(RTRIM(explain)))-1)
			ELSE LTRIM(RTRIM(explain))
		  END ,
          stypeid ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill

--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails 
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(gbillnumberid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #TmpBillInfo,#TmpExpress,#TmpDetailsMoney,#TmpVoucherBill,#tmpBillIndexAtype,#TmpItemDetail,#TmpAssit,#TmpDetailsAssit,#TmpNewBill,#TmpDetailsRow
DROP TABLE #TmpBillNumberId,#BillNumberId

RETURN @VoucherId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：
*/
CREATE PROCEDURE GP_BatchCreateVoucher_ChargeOffBill
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期,
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0 ,
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0,				-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@IfCommission	INT = 0,					-- 是否提成单311 0.不是 1.是
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

DECLARE @AutoFlag INT --即时生成凭证异常
SET @AutoFlag = 0

--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID			INT,				--收付款项目
	ATypeID1		VARCHAR(50),
	sharefee		 NUMERIC(24, 10)  DEFAULT 0,--分摊费用
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	balancemoney	 NUMERIC(24, 10) ,		--平衡数
	RedWord			INT			,		--红冲标识
	OtherInOutType	INT,
	outstypeid		VARCHAR(50),		--出库分支机构
	instypeid		VARCHAR(50)			--入库分支机构
	,AtId			INT					--模板号
	,ChargeOffBtypeid	VARCHAR(50)		--转出往来  ps：更加97bug2624测试所说的，借方分录用这个字段的往来做辅助核算
)

INSERT INTO #TmpBillInfo
		( BillNumberId ,
		  StypeId ,
		  VerifyStypeid ,
		  DTypeId ,
		  BTypeId ,
		  ETypeId,
		  DealBTypeId ,
		  ATypeID,
		  ATypeID1,
		  Cid ,
		  Rate ,
		  RateType,
		  RedWord,
		  OtherInOutType,
		  outstypeid,
		  instypeid
		  ,AtId
		  ,ChargeOffBtypeid
		)
SELECT  T1.BillNumberId,
		T1.Stypeid,
		T2.VerifyID,
		T1.DTypeId,
		T1.btypeid,
		T1.etypeid,
		T1.DealBTypeID,
		T1.ATypeID,
		T1.ATypeID1,
		T1.CID,
		T1.Rate,
		T3.BasisType,
		T1.RedWord,
		T1.OtherInOutType,
		ISNULL(T4.STypeID,''),
		ISNULL(T5.STypeID,'')
		,@AtId
		,ChargeOffBtypeid
FROM dbo.BillIndex T1
INNER JOIN #BillNumberId B ON B.a= T1.BillNumberId
INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
LEFT JOIN dbo.Stock T4 ON T1.ktypeid = T4.typeId
LEFT JOIN dbo.Stock T5 ON T1.ktypeid2 = T5.typeId


DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

--统计单据明细中所有金额字段
CREATE TABLE #tmpBillMoneyDetail
(
	ChargeOffValue		NUMERIC(24, 10) DEFAULT 0	
	,balancemoney		NUMERIC(24, 10) DEFAULT 0--平衡数
	
	,rate				NUMERIC(24, 10) DEFAULT 1
	,ratetype			INT	DEFAULT 0	
	,billnumberid		INT
	,id					INT	DEFAULT 1
	
	-----9.6功能，对某些单据生成凭证时，原币金额用单据上的原币金额，而不是通过本位币反算得来
	
	,ChargeOffValueFor	NUMERIC(24, 10) DEFAULT 0
	,balancemoneyfor	NUMERIC(24, 10) DEFAULT 0--平衡数
)

--凭证明细临时表
CREATE TABLE #tmpBill
(
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rowno			INT		IDENTITY(1,1),
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		addebtid		INT,
		credenceId		INT,
		billid	INT
)

--凭证明细预处理后表（用于插入）
CREATE TABLE #tmpRow
(
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rowno			INT		IDENTITY(1,1),
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		countIndex		INT,
		addebtid		INT,
		credenceId		INT,
		billindexid		INT
)

CREATE TABLE #tmpBillID
(
	rowno	INT ,
	id		INT,
	atypeid	VARCHAR(50)
)

--------------------------
--将模板明细处理到临时表中,进行读取字段生成摘要
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作

SELECT @MinNumber = MIN(a) FROM #BillNumberId --- dbo.f_split(@billnumberid,',')
SELECT @MaxNumber = MAX(a) FROM #BillNumberId ---dbo.f_split(@Billnumberid,',')

SET @Index = @MinNumber



CREATE TABLE #TempStr
(
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

DECLARE @flag INT--是否需要用户补足
SET @flag = 0


WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		--原来累加1的方式容易产生无用的循环,故进行调整,每次获取#BillNumberId中比@Index大的最小值
		--IF NOT EXISTS (SELECT TOP 1 1 FROM #BillNumberId WHERE a = @Index) ---dbo.f_split(@billnumberid,',') 
		--BEGIN
		--	SET @Index += 1
		--	CONTINUE
		--END
	
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '
		
		IF @IfCommission = 0
			SELECT @SqlSummary +=  'SELECT '+
					CASE Filed
						WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
						ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
					END
				+'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
				CASE tablename 
					WHEN 'BillIndex' THEN ' T2 '
					WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
					WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
					WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
				END
				+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
				+' union all '
			FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		ELSE
			SELECT @SqlSummary +=  'SELECT '+
					CASE Filed
						WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
						ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
					END
				+'AS SummaryStr,' + a + ' AS SummaryType from ' + CASE TableName WHEN 'BillIndex' THEN 'CommissionBillNew' ELSE TableName END +
				CASE tablename 
					WHEN 'BillIndex' THEN ' T2 '
					WHEN 'Stype' THEN ' T1 INNER JOIN CommissionBillNew T2 ON T1.typeid = T2.stypeid '
					WHEN 'Btype' THEN ' T1 INNER JOIN CommissionBillNew T2 ON T1.typeid = T2.btypeid '
					WHEN 'employee ' THEN ' T1 INNER JOIN CommissionBillNew T2 ON T1.typeid = T2.etypeid '
				END
				+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
				+' union all '
			FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
			WHERE T1.A IN (1,2,5,6,7)
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		SELECT @str += summarystr + '  '
		FROM #TempStr
		
		IF @str <> ''
			SET @str += ';'
			
		TRUNCATE TABLE #TempStr
		
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END

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



--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	fieldname			VARCHAR(100),
	BillIndexNumberId	INT				--单据ID
)

DECLARE @BillCid	INT
		,@IsUseBillMoneyDate INT
		,@UseBillMoneyDate_BillTypes VARCHAR(200)
		,@sql VARCHAR(MAX)


SELECT TOP 1 @BillCid = Cid FROM #TmpBillInfo
SELECT @UseBillMoneyDate_BillTypes=SubValue  FROM sysdata WHERE SubName = 'usebillmoneydate'

SET @IsUseBillMoneyDate = 0
IF EXISTS (SELECT TOP 1 1 FROM F_Split(@UseBillMoneyDate_BillTypes,',') WHERE a = @BillType)
	SET @IsUseBillMoneyDate = 1

INSERT INTO #tmpBillMoneyDetail
		(
		  id
		  ,billnumberid
		  ,rate
		  ,ratetype
		  ,ChargeOffValue
		  ,ChargeOffValueFor
		)
SELECT	a.id
		,A.BillNumberId
		,C.Rate
		,C.BasisType
		,CASE WHEN d.redword = 2 THEN -a.totalmoney ELSE a.totalmoney END,
		CASE WHEN d.redword = 2 THEN -a.Ntotalmoney ELSE a.Ntotalmoney END
FROM dbo.BillIndex a 
INNER JOIN #TmpBillInfo d ON a.BillNumberId = d.billnumberid
INNER JOIN Ac_Currency C ON C.CId = D.Cid

	
	--test
	--SELECT * FROM #tmpBillMoney
	--SELECT * FROM #tmpBillMoneyDetail
	
	
	--科目来源AcFrom
	--1 手工选择
	--2 单据上收付款项目对应科目
	--3 单据上往来科目
	--4 单据上项目对应科目
	--5 单据上项目对应固定资产科目
	--6 单据上借方项目对应科目
	--7 单据上贷方项目对应科目
	--8 单据上业务类型对应科目
	CREATE TABLE #tmpExpress
	(
		atdit		INT,
		lendloan	 NUMERIC(24, 10) ,
		lendloanfor	 NUMERIC(24, 10) ,
		rate		 NUMERIC(24, 10) ,
		ratetype	INT,
		billnumberid	INT,
		iscost		INT DEFAULT 0
	)	
	
	--读取模板要求的金额（非项目类）
	SET @sql = 'insert into #tmpExpress select distinct * from('--MARK:唉，又改回来，这个也要屏蔽，要不然有报错，无语，以后再改回去，直接取消注释吧
	--SET @sql = 'insert into #tmpExpress'
	SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId, sum('+ T2.Express +') as lendloan,'+CASE WHEN @IsUseBillMoneyDate = 1 THEN 'sum('+dbo.F_ChangeToOriginalCurrency(T2.Express) +')' ELSE '0' END+' as lendloanfor,b.rate,b.ratetype,a.billnumberid,'+CASE WHEN dbo.F_ChangeToOriginalCurrency(T2.Express) = '0' THEN '1' ELSE '0' END+' as iscost
	from #tmpBillMoneyDetail a
	inner join #TmpBillInfo b on b.billnumberid = a.billnumberid
	group by a.billnumberid,b.rate,b.ratetype union all '
	FROM Ac_Auditing_Template_Detail T1
			INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
	WHERE Atid = @Atid AND (AcFrom < 4 OR AcFrom = 8)
	
	IF LEN(@sql) > LEN('insert into #tmpExpress select distinct * from(')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
		SET @sql += ')T'
		EXEC(@sql)
	END

	--取分支机构关联科目
	SELECT	*,
			CASE WHEN cid = -1 THEN @f_exchid
				 ELSE cid
			END AS rcid,
			SUBSTRING(dbo.F_Get_AscidsItem(@Verifyid,a.typeid),
					LEN(dbo.F_Get_AscidsItem(@Verifyid,a.typeid))-1,
					LEN(dbo.F_Get_AscidsItem(@Verifyid,a.typeid))) AS Item
	INTO #tmpAccount
	FROM dbo.Ac_Account a
	WHERE StypeId = @Verifyid
	
	
	DECLARE @BillTypestr VARCHAR(50)
	SET @BillTypestr = CAST(@BillType AS VARCHAR(50))



CREATE TABLE #tmpBillIndexAtypeid1
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atid		INT,
	atdid		INT,
	item		VARCHAR(500)
	,billnumberid	INT
)
--单据上的往来科目
		
INSERT INTO #tmpBillIndexAtypeid1
SELECT	b.typeId,
	b.UserCode,
	b.FullName,
	Fdc,
	CASE b.cid
		WHEN -1 THEN @f_exchid
		ELSE b.Cid
	END,
	@Atid AS atid,
	@Atdid as atdid,
	SUBSTRING(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1),
			LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))-1,
			LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))) AS Item
	,BB.BillNumberId
FROM #TmpBillInfo bb
INNER JOIN dbo.Ac_Account b ON B.TypeId = BB.ATypeID1 AND B.StypeId = BB.VerifyStypeid
--WHERE b.TypeId=@atypeid1 AND b.StypeId = @verifyid

--无科目，补空白
IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBillIndexAtypeid1)
BEGIN
	
	INSERT INTO #tmpBillIndexAtypeid1
			( atypeid ,
			  usercode ,
			  fullname ,
			  fdc ,
			  cid ,
			  atid,
			  atdid
			  ,billnumberid
			)
	SELECT  '' , -- atypeid - varchar(50)
			  '' , -- usercode - varchar(50)
			  '' , -- fullname - varchar(200)
			  0 , -- fdc - int
			  0 , -- cid - int
			  0 , -- atid - int
			  @Atdid
			,BillNumberId
	FROM #TmpBillInfo
END
	
	
	--生成凭证明细数据(科目来源1~3，8)--
	INSERT INTO #tmpBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  atdid,
			  addebtid,
			  billid
			)
	SELECT	DISTINCT @VoucherId AS billnumberid,
			Summary AS explain,
			CASE AcFrom 
				WHEN 1 THEN b.typeid
				WHEN 3 THEN e.atypeid
			END AS atypeid,
			'' AS atypeid2,
			CASE AcFrom 
				WHEN 1 THEN b.Fdc
				WHEN 3 THEN e.Fdc
				WHEN 4 THEN b.Fdc
			END AS Fdc,
			@f_exchid AS f_exchid,
			BB.Cid AS f_exchidfor,
			CASE a.Fdc 
				WHEN 1 THEN  isnull(d.lendloan,0)
				ELSE 0 
			END AS lendprice,
			CASE a.Fdc 
				WHEN -1 THEN isnull(d.lendloan,0)
				ELSE 0 
			END AS loanprice,
			CASE WHEN a.Fdc = 1 AND @IsUseBillMoneyDate = 1 AND d.iscost = 0	THEN d.lendloanfor
				 WHEN a.Fdc = 1 THEN 
						(CASE ISNULL(d.ratetype,0) 
							WHEN 0 THEN  isnull(d.lendloan,0) / ISNULL(d.rate,1)
							WHEN 1 THEN isnull(d.lendloan,0) * ISNULL(d.rate,1)
						END)
				ELSE 0 
			END AS lendpricefor,
			CASE WHEN a.Fdc = -1  AND @IsUseBillMoneyDate = 1 AND d.iscost = 0	THEN d.lendloanfor
				 WHEN a.Fdc = -1 THEN
						(CASE ISNULL(d.ratetype,0)                                                       
							WHEN 0 THEN isnull(d.lendloan,0) / isnull(d.rate,1)
							WHEN 1 THEN isnull(d.lendloan,0) * isnull(d.rate,1)
						END)
				ELSE 0 
			END AS loanpricefor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			BB.Cid,
			d.rate,
			a.Fdc AS fadc,
			@verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId,
			0,
			D.billnumberid
	FROM #TmpVoucherDetails a
	INNER JOIN #tmpExpress d ON a.AtdId = d.atdit
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = D.billnumberid
	LEFT JOIN #tmpAccount b ON a.ATypeId = b.TypeId
	LEFT JOIN #tmpBillIndexAtypeid1 e ON a.Atid = e.atid AND E.billnumberid = D.billnumberid
	WHERE a.atid = @Atid AND a.AcFrom IN (1,2,3,8)
	ORDER BY a.AtdId
	
	--往来科目为空
	IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBillIndexAtypeid1 WHERE ISNULL(atypeid,'') <> '')
	BEGIN
		IF EXISTS(	SELECT TOP 1 1
						FROM #TmpVoucherDetails T1
							LEFT JOIN #TmpExpress T2 ON T1.AtdId = T2.Atdit
							LEFT JOIN #tmpBillIndexAtypeid1 T3 ON T2.Atdit =T3.Atdid
							LEFT JOIN dbo.Ac_Account T4 ON T3.Atypeid = T4.TypeId AND T4.StypeId = @verifyid
							LEFT JOIN dbo.Ac_Currency T5 ON T4.Cid = T5.CId
						WHERE T1.Atid = @Atid AND T1.AcFrom = 3 AND T2.Lendloan <> 0)
		SET @Flag = -11
	END
	
	CREATE TABLE #tmpMoneyBill
	(
		BillNumberId	INT,
		AtypeId			VARCHAR(50),
		total			 NUMERIC(24, 10) ,
		totalfor			 NUMERIC(24, 10) ,
		STypeid			VARCHAR(50),
		billid	INT	--单据编号
	)
	
	--去除金额为0的
	DELETE FROM #tmpBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 	
	
	--调整明细异常币种	
	UPDATE #tmpbill SET f_exchidfor =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
		cid =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
		rate = CASE WHEN T2.Cid = 0 THEN T1.rate ELSE T3.rate END,
		lendpricefor =  CASE WHEN T2.Cid = 0 OR  (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid)  THEN T1.lendpricefor ELSE 
							CASE T3.BasisType WHEN 0 THEN T1.lendprice * T3.rate
											ELSE  T1.lendprice / T3.rate END
						END,
		loanpricefor =  CASE WHEN T2.Cid = 0 OR (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid) THEN T1.loanpricefor ELSE 
							CASE T3.BasisType WHEN 0 THEN T1.loanprice * T3.rate
											ELSE  T1.loanprice / T3.rate END
						END
	FROM #tmpbill T1 
		INNER JOIN dbo.Ac_Account T2 ON T1.stypeid = T2.StypeId AND T1.atypeid = T2.typeid
		LEFT JOIN dbo.Ac_Currency T3 ON T2.Cid = T3.CId
	
	--处理分录号
	INSERT INTO #tmpRow(
		billnumberid	,
		explain			,
		atypeid			,
		atypeid2		,
		Fdc				,
		f_exchid		,
		f_exchidfor		,
		lendprice		,
		loanprice		,
		lendpricefor	,
		loanpricefor	,
		FCashFlowItem	,
		ascids			,
		FSettleNo		,
		FSettleTypeID	,
		comment			,
		cid				,
		rate			,
		fadc			,
		stypeid			,
		fyear			,
		fperiod			,
		atdid			,
		countIndex		,
		addebtid		,
		credenceId		,
		billindexid
	)
	SELECT billnumberid,
			explain,
			atypeid,
			atypeid2,
			Fdc,
			f_exchid,
			f_exchidfor,
			lendprice,
			loanrice,
			lendpricefor,
			loanpricefor,
			FCashFlowItem,
			ascids,
			FSettleNo,
			FSettleTypeID,
			comment,
			cid,
			rate,
			fadc,
			stypeid,
			fyear,
			fperiod,
			atdid,
			countindex,
			addebtid,
			credenceId,
			billid
	FROM
	(
	SELECT	billnumberid,
			explain,
			atypeid,
			atypeid2,
			Fdc,
			f_exchid,
			f_exchidfor,
			SUM(lendprice) AS lendprice,
			SUM(loanprice) AS loanrice,
			SUM(lendpricefor) AS lendpricefor,
			SUM(loanpricefor) AS loanpricefor,
			FCashFlowItem,
			ascids,
			FSettleNo,
			FSettleTypeID,
			comment,
			cid,
			rate,
			fadc,
			stypeid,
			fyear,
			fperiod,
			atdid,
			@Index AS countindex,
			addebtid,
			credenceId,
			MIN(rowno) AS initrowno,
			billid
	FROM	#tmpBill
	GROUP BY billnumberid,
			explain,
			atypeid,
			atypeid2,
			Fdc,
			f_exchid,
			f_exchidfor,
			FCashFlowItem,
			ascids,
			FSettleNo,
			FSettleTypeID,
			comment,
			cid,
			rate,
			fadc,
			stypeid,
			fyear,
			fperiod,
			atdid,
			addebtid,
			credenceId,
			billid
	) AS TT ORDER BY initrowno

	--获取明细对应辅助核算
	SET @sql = 'INSERT INTO #TmpAssit '
	SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'+
				'( '+CASE WHEN (T3.Fdc = 1 AND T4.ChargeOffType IN (0,2,5)) OR (T3.Fdc = -1 AND T4.ChargeOffType IN(1,3,4)) THEN 'btypeid' ELSE 'ChargeOffBtypeid' END /* CAST(T2.FieldValue AS VARCHAR(20))*/+') AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,
				(SELECT name FROM syscolumns WHERE id = object_id(''billindex'') AND name = '''+
				cast(case T2.FieldValue 
						WHEN 'instypeid' THEN 'stypeid'
						WHEN 'outstypeid' THEN 'stypeid'
					ELSE FieldValue END AS varchar(50))+''')as filedname ,BILLNUMBERID AS BillIndexNumberId 
				FROM #TmpBillInfo 
				
				UNION ALL '
	FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
		LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
		LEFT JOIN Ac_Auditing_Template_Detail T3 ON T3.Atid = T1.Atid AND T3.AtdId = T1.AtdId
		LEFT JOIN Ac_Auditing_Template T4 ON T4.AtId = T1.Atid
	WHERE T1.Atid = @Atid
	IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
		EXEC(@sql)
	END
	
	DROP TABLE #tmpExpress,#tmpBillIndexAtypeid1,#tmpAccount,#tmpMoneyBill


--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	billindexid	INT,
	typeid	VARCHAR(50)
)
INSERT INTO #TmpDetailsAssit
SELECT DISTINCT T1.atdid,T1.rowno,T3.ascids,T1.billindexid,T3.typeid
FROM #tmprow T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId
WHERE ISNULL(T3.ascids,'') <> ''

DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #tmprow 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #tmprow SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END


--排除数据全为0的单据编号
SELECT DISTINCT BillIndexId
INTO #TmpBillNumberId
FROM #tmprow WHERE lendprice <> 0 OR loanprice <> 0


--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT T.*
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	SUM(lendprice)	AS Lend,
	SUM(loanprice)	AS Loan,
	SUM(lendpricefor) AS LendFor,
	SUM(loanpricefor) AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmprow
GROUP BY BillNumberId,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.OrderID,T.fadc,AC.UserCode



--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT atdid,rowno,ascids,typeid
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit


INSERT INTO #TmpDetailsAssit (atdid, rowno, ascids, typeid )
SELECT DISTINCT 0,T1.rowno,T3.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''



--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END



DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)


--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
         CASE 
			WHEN LTRIM(RTRIM(explain))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(explain)),1) = ';' THEN LEFT(LTRIM(RTRIM(explain)),LEN(LTRIM(RTRIM(explain)))-1)
			ELSE LTRIM(RTRIM(explain))
		  END ,
          stypeid ,
          ISNULL(atypeid,'') ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor),
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill

--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails 
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #tmpBillID,#tmpAssit,#tmpBill,#tmpRow--,#tmpaddebtForDetail
DROP TABLE #tmpBillMoneyDetail

DROP TABLE #TmpBillNumberId,#TmpBillInfo,#BillNumberId

IF @CreateType = 0
	RETURN 0
	
RETURN @VoucherId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：
*/
CREATE PROCEDURE GP_BatchCreateVoucher_CommonBill
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期,
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0,				--凭证主表Billnumberid
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0,				-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@IfCommission	INT = 0,				-- 是否提成单311 0.不是 1.是
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID			INT,				--收付款项目
	ATypeID1		VARCHAR(50),
	sharefee_index	NUMERIC(24, 10)  DEFAULT 0,--分摊费用
	Cid				INT,				--币种
	Rate			NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	RedWord			INT			,		--红冲标识
	OtherInOutType	INT,
	outstypeid		VARCHAR(50),		--出库分支机构
	instypeid		VARCHAR(50)			--入库分支机构
	,AtId			INT					--模板号
)

IF @IfCommission = 0	--普通单据
	INSERT INTO #TmpBillInfo
			( BillNumberId ,
			  StypeId ,
			  VerifyStypeid ,
			  DTypeId ,
			  BTypeId ,
			  ETypeId,
			  DealBTypeId ,
			  ATypeID,
			  ATypeID1,
			  Cid ,
			  Rate ,
			  RateType,
			  RedWord,
			  OtherInOutType,
			  outstypeid,
			  instypeid
			  ,AtId
			)
	SELECT  T1.BillNumberId,
			T1.Stypeid,
			T2.VerifyID,
			T1.DTypeId,
			T1.btypeid,
			T1.etypeid,
			T1.DealBTypeID,
			T1.ATypeID,
			T1.ATypeID1,
			T1.CID,
			T1.Rate,
			T3.BasisType,
			T1.RedWord,
			T1.OtherInOutType,
			ISNULL(T4.STypeID,''),
			ISNULL(T5.STypeID,'')
			,@AtId
	FROM dbo.BillIndex T1
	INNER JOIN #BillNumberId B ON B.a= T1.BillNumberId
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
	LEFT JOIN dbo.Stock T4 ON T1.ktypeid = T4.typeId
	LEFT JOIN dbo.Stock T5 ON T1.ktypeid2 = T5.typeId
ELSE	--提成单
	INSERT INTO #TmpBillInfo
			( BillNumberId ,
			  StypeId ,
			  VerifyStypeid ,
			  DTypeId ,
			  BTypeId ,
			  ETypeId,
			  DealBTypeId ,
			  ATypeID,
			  ATypeID1,
			  Cid ,
			  Rate ,
			  RateType,
			  RedWord,
			  OtherInOutType,
			  outstypeid,
			  instypeid
			  ,AtId
			)
	SELECT  T1.BillNumberId,
			T1.StypeID,
			T2.VerifyID,
			'',
			'',
			@szCheckMan,
			'',
			'',
			'',
			1,
			1,
			0,
			0,
			0,
			'',
			''
			,@AtId
	FROM dbo.CommissionBillNew T1
	INNER JOIN #BillNumberId B ON B.a = T1.BillNumberId
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId

DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1
--------------------------
--将模板明细处理到临时表中,进行读取字段生成摘要
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT=0,@MinDid INT=0,@SqlSummary VARCHAR(MAX)='',@MaxNumber INT=0,@MinNumber INT=0,@Index INT=0,@Str VARCHAR(MAX)=''

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作

SELECT @MinNumber = MIN(a) FROM #BillNumberId --- dbo.f_split(@billnumberid,',')
SELECT @MaxNumber = MAX(a) FROM #BillNumberId ---dbo.f_split(@Billnumberid,',')

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='8')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN	
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '
		
		IF @IfCommission = 0
		BEGIN
			SELECT @SqlSummary +=  'SELECT '+
					CASE Filed
						WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
						ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
					END
				+'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
				CASE tablename 
					WHEN 'BillIndex' THEN ' T2 '
					WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
					WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
					WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
				END
				+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
				+' union all '
			FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		END
		ELSE
		BEGIN
			SELECT @SqlSummary +=  'SELECT '+
					CASE Filed
						WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
						ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
					END
				+'AS SummaryStr,' + a + ' AS SummaryType from ' + CASE TableName WHEN 'BillIndex' THEN 'CommissionBillNew' ELSE TableName END +
				CASE tablename 
					WHEN 'BillIndex' THEN ' T2 '
					WHEN 'Stype' THEN ' T1 INNER JOIN CommissionBillNew T2 ON T1.typeid = T2.stypeid '
					WHEN 'Btype' THEN ' T1 INNER JOIN CommissionBillNew T2 ON T1.typeid = T2.btypeid '
					WHEN 'employee ' THEN ' T1 INNER JOIN CommissionBillNew T2 ON T1.typeid = T2.etypeid '
				END
				+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
				+' union all '
			FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
			WHERE T1.A IN (1,2,5,6,7)
		END
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		SELECT @str += summarystr + '  '
		FROM #TempStr
		
		IF @str <> ''
			SET @str += ';'
		TRUNCATE TABLE #TempStr
		
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END
----------------------


DECLARE @BillCid	INT
		,@IsUseBillMoneyDate INT
		,@UseBillMoneyDate_BillTypes VARCHAR(200)
		,@sql VARCHAR(MAX)


SELECT TOP 1 @BillCid = Cid FROM #TmpBillInfo
SELECT @UseBillMoneyDate_BillTypes=SubValue  FROM sysdata WHERE SubName = 'usebillmoneydate'

SET @IsUseBillMoneyDate = 0
IF EXISTS (SELECT TOP 1 1 FROM F_Split(@UseBillMoneyDate_BillTypes,',') WHERE a = @BillType)
	SET @IsUseBillMoneyDate = 1
	
--明细金额，用于乘税率、SUM方式的处理
CREATE TABLE #tmpBillMoneyDetail
(
	total				 NUMERIC(24, 10) 	DEFAULT 0,
	taxtotal			 NUMERIC(24, 10) 	DEFAULT 0,
	taxmoney			 NUMERIC(24, 10) 	DEFAULT 0,
	tax					 NUMERIC(24, 10) 	DEFAULT 0,
	costtotal			 NUMERIC(24, 10) 	DEFAULT 0,
	outcosttotal		 NUMERIC(24, 10) 	DEFAULT 0,
	incosttotal			 NUMERIC(24, 10) 	DEFAULT 0,
	outstocktaxtotal	 NUMERIC(24, 10) 	DEFAULT 0,
	instocktaxtotal		 NUMERIC(24, 10) 	DEFAULT 0,
	outstocktotal		 NUMERIC(24, 10) 	DEFAULT 0,
	instocktotal		 NUMERIC(24, 10) 	DEFAULT 0,
	preferencemoney		 NUMERIC(24, 10) 	DEFAULT 0,--按明细条数，将总额分割
	totalinmoney		 NUMERIC(24, 10) 	DEFAULT 0,
	balancemoney		 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	id					INT				DEFAULT 0,
	CommissionTotal		 NUMERIC(24, 10) 	DEFAULT 0,--提成金额
	
	costTotal_S			 NUMERIC(24, 10) 	DEFAULT 0,--成本金额（服务商品）
	inCostTotal_S		 NUMERIC(24, 10) 	DEFAULT 0,--入库成本（服务商品）换货
	outCostTotal_S		 NUMERIC(24, 10) 	DEFAULT 0,--出库成本（服务商品）换货
	total_S				 NUMERIC(24, 10) 	DEFAULT 0,--折后金额（服务商品）
	instocktotal_S		 NUMERIC(24, 10) 	DEFAULT 0,--入库折后金额(服务商品)
	outstocktotal_S		 NUMERIC(24, 10) 	DEFAULT 0 --出库折后金额（服务商品）
	,billnumberid		INT
	-----9.6功能，对某些单据生成凭证时，原币金额用单据上的原币金额，而不是通过本位币反算得来
	,totalfor				 NUMERIC(24, 10) 	DEFAULT 0,
	taxtotalfor			 NUMERIC(24, 10) 	DEFAULT 0,
	taxmoneyfor			 NUMERIC(24, 10) 	DEFAULT 0,
	preferencemoneyfor		 NUMERIC(24, 10) 	DEFAULT 0,--按明细条数，将总额分割
	totalinmoneyfor		 NUMERIC(24, 10) 	DEFAULT 0,
	Total_Sfor		 NUMERIC(24, 10) 	DEFAULT 0,
	costTotal_Sfor		 NUMERIC(24, 10) 	DEFAULT 0,--成本金额（服务商品）
	costtotalfor			 NUMERIC(24, 10) 	DEFAULT 0,
	balancemoneyfor			 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
)
	
IF @BillType = 6
BEGIN
	INSERT INTO #tmpBillMoneyDetail
			( total ,
			  taxtotal ,
			  taxmoney ,
			  tax ,
			  costtotal ,
			  costtotal_S,
			  id
			  ,billnumberid
			  ,totalfor ,
			  taxtotalfor ,
			  taxmoneyfor ,
			  costTotal_Sfor
			)
	SELECT CASE WHEN d.redword = 2 THEN -a.total ELSE a.total END,
			CASE WHEN d.redword = 2 THEN -a.TaxTotal ELSE a.TaxTotal END,
			CASE WHEN d.redword = 2 THEN -a.TaxMoney ELSE a.TaxMoney END,
			a.Tax,
			CASE WHEN e.isservice = 0 THEN
					CASE WHEN d.redword = 2 THEN -ABS(b.CostTotal) ELSE ABS(b.CostTotal) END
				ELSE 0 END,
			CASE WHEN e.isservice = 1 THEN 
					CASE WHEN d.redword = 2 THEN -a.total ELSE a.total END
				ELSE 0 END,
			a.id
			,A.BillNumberId
			,CASE WHEN d.redword = 2 THEN -a.NTotal ELSE a.NTotal END,
			CASE WHEN d.redword = 2 THEN -a.NTaxTotal ELSE a.NTaxTotal END,
			CASE WHEN d.redword = 2 THEN -a.NTaxMoney ELSE a.NTaxMoney END,
			CASE WHEN e.isservice = 1 THEN 
					CASE WHEN d.redword = 2 THEN -a.NTotal ELSE a.NTotal END
				ELSE 0 END
	FROM dbo.BuyBackBill a 
	INNER JOIN dbo.InOutstocktable b ON a.BillNumberId = b.BillNumberId AND a.ID = b.ID
	INNER JOIN dbo.BillIndex c ON a.BillNumberId = c.BillNumberId
	INNER JOIN #TmpBillInfo d ON a.BillNumberId = d.billnumberid
	INNER JOIN dbo.ptype e ON b.PtypeId = e.typeId
END
IF @BillType = 401
BEGIN
	INSERT INTO #tmpBillMoneyDetail
			( total ,
			  taxtotal ,
			  taxmoney ,
			  tax ,
			  costtotal ,
			  costtotal_S,
			  id,
			  billnumberid,
			  totalfor ,
			  taxtotalfor ,
			  taxmoneyfor ,
			  costTotal_Sfor
			)
	SELECT CASE WHEN d.redword = 2 THEN -a.total ELSE a.total END,
			CASE WHEN d.redword = 2 THEN -a.TaxTotal ELSE a.TaxTotal END,
			CASE WHEN d.redword = 2 THEN -a.TaxMoney ELSE a.TaxMoney END,
			a.Tax,
			CASE WHEN e.isservice = 0 THEN
					CASE WHEN d.redword = 2 THEN -ABS(b.CostTotal) ELSE ABS(b.CostTotal) END
				ELSE 0 END,
			CASE WHEN e.isservice = 1 THEN 
					CASE WHEN d.redword = 2 THEN -a.total ELSE a.total END
				ELSE 0 END,
			a.id,
			a.billnumberid,
			CASE WHEN d.redword = 2 THEN -a.NTotal ELSE a.NTotal END,
			CASE WHEN d.redword = 2 THEN -a.NTaxTotal ELSE a.NTaxTotal END,
			CASE WHEN d.redword = 2 THEN -a.NTaxMoney ELSE a.NTaxMoney END,
			CASE WHEN e.isservice = 1 THEN 
					CASE WHEN d.redword = 2 THEN -a.NTotal ELSE a.NTotal END
				ELSE 0 END
	FROM dbo.AppraisalBackBill a 
	INNER JOIN dbo.InOutstocktable b ON a.BillNumberId = b.BillNumberId AND a.ID = b.ID
	INNER JOIN dbo.BillIndex c ON a.BillNumberId = c.BillNumberId
	INNER JOIN #TmpBillInfo d ON a.BillNumberId = d.billnumberid
	INNER JOIN dbo.ptype e ON b.PtypeId = e.typeId
END
IF @BillType = 161
BEGIN
	INSERT INTO #tmpBillMoneyDetail
			( 
			  taxtotal ,
			  taxmoney ,
			  tax ,
			  outcosttotal ,
			  incosttotal ,
			  outcosttotal_s,
			  incosttotal_s,
			  outstocktaxtotal,
			  instocktaxtotal,
			  outstocktotal,
			  instocktotal,
			  id
			  ,billnumberid
			)
	SELECT CASE WHEN c.redword = 2 THEN -a.TaxTotal ELSE a.TaxTotal END ,
			CASE WHEN c.redword = 2 THEN -a.TaxMoney ELSE a.TaxMoney END,
			a.Tax,
			CASE WHEN d.isservice = 0 THEN
				CASE WHEN c.redword = 2 THEN -ABS(CASE WHEN b.CostTotal < 0 THEN b.CostTotal ELSE 0 END)
									ELSE ABS(CASE WHEN b.CostTotal < 0 THEN b.CostTotal ELSE 0 END)
				END
			ELSE 0 END,
			CASE WHEN d.isservice = 0 THEN
				CASE WHEN c.redword = 2 THEN -ABS(CASE WHEN b.CostTotal > 0 THEN b.CostTotal ELSE 0 END)
									ELSE ABS(CASE WHEN b.CostTotal > 0 THEN b.CostTotal ELSE 0 END)
				END
			ELSE 0 END,
			CASE WHEN d.isservice = 1 THEN				
				CASE a.InOrOut WHEN 'O' THEN (CASE WHEN c.redword = 2 THEN -a.total ELSE a.total END) ELSE 0 END
			ELSE 0 END,
			CASE WHEN d.isservice = 1 THEN
				CASE a.InOrOut WHEN 'I' THEN (CASE WHEN c.redword = 2 THEN -a.total ELSE a.total END) ELSE 0 END
			ELSE 0 END,
									
			CASE WHEN c.redword = 2 THEN -ABS(CASE WHEN b.taxtotal < 0 THEN b.taxtotal ELSE 0 END)
									ELSE ABS(CASE WHEN b.taxtotal < 0 THEN b.taxtotal ELSE 0 END)
									END,
			CASE WHEN c.redword = 2 THEN -ABS(CASE WHEN b.taxtotal > 0 THEN b.taxtotal ELSE 0 END)
									ELSE ABS(CASE WHEN b.taxtotal > 0 THEN b.taxtotal ELSE 0 END)
									END,
			CASE a.InOrOut WHEN 'O' THEN (CASE WHEN c.redword = 2 THEN -a.total ELSE a.total END) ELSE 0 END,
			CASE a.InOrOut WHEN 'I' THEN (CASE WHEN c.redword = 2 THEN -a.total ELSE a.total END) ELSE 0 END,
			a.id
			,a.BillNumberId
	FROM dbo.BuyGoodsExchangeBill a
	INNER JOIN dbo.InOutstocktable b ON a.BillNumberId = b.BillNumberId AND a.ID = b.ID
	INNER JOIN #TmpBillInfo c ON a.BillNumberId = c.billnumberid
	INNER JOIN dbo.ptype d ON b.PtypeId = d.typeId
END
	
--统计单据所有金额字段
CREATE TABLE #tmpBillMoney
(
	totalmoney				 NUMERIC(24, 10) 	DEFAULT 0,
	totalinmoney			 NUMERIC(24, 10) 	DEFAULT 0,
	preferencemoney			 NUMERIC(24, 10) 	DEFAULT 0,
	total					 NUMERIC(24, 10) 	DEFAULT 0,--折后金额
	taxTotal				 NUMERIC(24, 10) 	DEFAULT 0,
	costTotal				 NUMERIC(24, 10) 	DEFAULT 0,
	inCostTotal				 NUMERIC(24, 10) 	DEFAULT 0,--入库成本（换货、拆装、调拨）
	outCostTotal			 NUMERIC(24, 10) 	DEFAULT 0,--出库成本（换货、拆装、调拨）
	rate					 NUMERIC(24, 10) 	DEFAULT 1,
	ratetype				 INT				DEFAULT 0,
	instocktotal			 NUMERIC(24, 10) 	DEFAULT 0,--入库折后金额
	outstocktotal			 NUMERIC(24, 10) 	DEFAULT 0,--出库折后金额
	instocktaxtotal			 NUMERIC(24, 10) 	DEFAULT	0,--入库价税合计
	outstocktaxtotal		 NUMERIC(24, 10) 	DEFAULT 0,--出库价税合计
	GoodsCostTotal			 NUMERIC(24, 10) 	DEFAULT 0,--成本金额
	instockGoodsCostTotal	 NUMERIC(24, 10) 	DEFAULT 0,--入库成本金额
	outstockGoodsCostTotal	 NUMERIC(24, 10) 	DEFAULT 0,--出库成本金额
	beforetotal				 NUMERIC(24, 10) 	DEFAULT	0,--调前金额
	sharefee				 NUMERIC(24, 10) 	DEFAULT 0,--分摊金额
	j_total					 NUMERIC(24, 10) 	DEFAULT 0,
	d_total					 NUMERIC(24, 10) 	DEFAULT	0,
	balancemoney			 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	billnumberid			 INT,
	rowindex				 INT				DEFAULT 1,
	CommissionTotal			 NUMERIC(24, 10) 	DEFAULT 0,--提成单311提成金额
	
	costTotal_S				 NUMERIC(24, 10) 	DEFAULT 0,--商品成本金额（服务商品）
	inCostTotal_S			 NUMERIC(24, 10) 	DEFAULT 0,--入库成本（服务商品）换货
	outCostTotal_S			 NUMERIC(24, 10) 	DEFAULT 0,--出库成本（服务商品）换货
	total_S					 NUMERIC(24, 10) 	DEFAULT 0,--折后金额（服务商品）
	instocktotal_S			 NUMERIC(24, 10) 	DEFAULT 0,--入库折后金额(服务商品)
	outstocktotal_S			 NUMERIC(24, 10) 	DEFAULT 0,--出库折后金额（服务商品）
	
	-----9.6功能，对某些单据生成凭证时，原币金额用单据上的原币金额，而不是通过本位币反算得来
	
	totalmoneyfor			 NUMERIC(24, 10) 	DEFAULT 0,
	totalinmoneyfor			 NUMERIC(24, 10) 	DEFAULT 0,
	preferencemoneyfor		 NUMERIC(24, 10) 	DEFAULT 0,
	totalfor				 NUMERIC(24, 10) 	DEFAULT 0,--折后金额
	taxTotalfor				 NUMERIC(24, 10) 	DEFAULT 0,
	total_Sfor				 NUMERIC(24, 10) 	DEFAULT 0,
	costTotal_Sfor			 NUMERIC(24, 10) 	DEFAULT 0,
	costtotalfor			 NUMERIC(24, 10) 	DEFAULT 0,
	balancemoneyfor			 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	
	totalfreight			 NUMERIC(24, 10) 	DEFAULT 0,--运输配送单的合计运费
	tax						 NUMERIC(24, 10) 	DEFAULT 0, --运输配送单的税率
	
	--=======================优惠券调整=======================================
	CouponDifferenceValue	NUMERIC(24,10)		NOT NULL DEFAULT(0),--代金券差额
	CouponDifferenceValueFor NUMERIC(24,10)		NOT NULL DEFAULT(0),--代金券差额
	z_totalmoney			NUMERIC(24,10)		NOT NULL DEFAULT(0),--转储值的金额
	z_totalmoneyFor			NUMERIC(24,10)		NOT NULL DEFAULT(0)--代金券差额
	
)	
--Awu:调整先不合并
INSERT INTO #tmpBillMoney
(
	totalmoney,
	totalinmoney,
	preferencemoney,
	billnumberid,
	rate,
	ratetype,
	totalmoneyfor,
	totalinmoneyfor,
	preferencemoneyfor
)
SELECT	CASE WHEN a.RedWord = 2 THEN -totalmoney ELSE totalmoney END AS totalmoney,
		CASE WHEN a.RedWord = 2 THEN -totalinmoney ELSE totalinmoney END AS totalinmoney,
		CASE WHEN a.RedWord = 2 THEN -preferencemoney ELSE preferencemoney END AS preferencemoney,
		a.BillNumberId,BB.Rate,BB.RateType
		,CASE WHEN a.RedWord = 2 THEN -NTotalMoney ELSE NTotalMoney END AS totalmoneyfor,
		CASE WHEN a.RedWord = 2 THEN -NTotalInMoney ELSE NTotalInMoney END AS totalinmoneyfor,
		CASE WHEN a.RedWord = 2 THEN -NPreferenceMoney ELSE NPreferenceMoney END AS preferencemoneyfor
FROM dbo.BillIndex a
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
INNER JOIN dbo.SType S ON a.Stypeid = S.TypeId


--优惠券【代金券差额】处理 优惠券不能使用外币
IF(@BillType IN(305,215,11,45,12,46))
BEGIN
	UPDATE #tmpBillMoney 
	SET 
		CouponDifferenceValue=(CASE WHEN T.CouponValue-T.CouponTaxTotal<=0 THEN 0 ELSE T.CouponValue-T.CouponTaxTotal END),
		CouponDifferenceValueFor=(CASE WHEN T.CouponValue-T.CouponTaxTotal<=0 THEN 0 ELSE T.CouponValue-T.CouponTaxTotal END)
	FROM #tmpBillMoney B
	INNER JOIN (
			SELECT
				T.billnumberid,
				SUM(ISNULL(VipTotal,0)) CouponValue,
				SUM(ISNULL(NTotalMoney,0)) CouponTaxTotal
			FROM #tmpBillMoney T
			INNER JOIN BillMulAccount B ON B.BillNumberId=T.billnumberid AND yhType=1
			GROUP BY T.billnumberid
	) T ON T.BillNumberId=B.BillNumberId	
	
END
--inoutstock成本金额 换货、拆装两条记录，有入有出，其他的都是单条记录
IF @BillType IN (16,160,161)
BEGIN
	UPDATE #tmpBillMoney
	SET outCostTotal = TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN (CASE WHEN -CostTotal < 0 THEN -ABS(CostTotal) ELSE 0 END)
								ELSE (CASE WHEN CostTotal < 0 THEN ABS(CostTotal) ELSE 0 END)
						  END) AS Total,a.BillNumberId
		FROM  dbo.InOutstocktable a
			INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
			INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
		WHERE c.IsService = 0
		GROUP BY a.BillNumberId
	) TT ON T1.billnumberid = TT.billnumberid
	
	UPDATE #tmpBillMoney
	SET inCostTotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN (CASE WHEN -CostTotal > 0 THEN -ABS(CostTotal) ELSE 0 END)
								ELSE (CASE WHEN CostTotal > 0 THEN ABS(CostTotal) ELSE 0 END)
						 END) AS total,a.BillNumberId
			FROM dbo.InOutstocktable a
				INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
				INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
			WHERE c.IsService = 0
			GROUP BY a.BillNumberId
	) TT ON t1.billnumberid = tt.billnumberid
	
	--服务商品入库成本、出库成本
	IF @BillType = 161
	BEGIN	
		UPDATE #tmpBillMoney
		SET outCostTotal_S = TT.total
		FROM #tmpBillMoney T1
		INNER JOIN (
			SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.Total ELSE a.total END) AS Total,a.BillNumberId
			FROM  dbo.BuyGoodsExchangeBill a
				INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
				INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
			WHERE c.IsService = 1
				AND a.InOrOut = 'O'
			GROUP BY a.BillNumberId
		) TT ON T1.billnumberid = TT.billnumberid
		
		UPDATE #tmpBillMoney
		SET inCostTotal_S = TT.total
		FROM #tmpBillMoney T1
		INNER JOIN (
				SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.Total ELSE a.total END) AS Total,a.BillNumberId
				FROM dbo.BuyGoodsExchangeBill a
					INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
					INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
					INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
				WHERE c.IsService = 1
					AND a.InOrOut = 'I'
				GROUP BY a.BillNumberId
		) TT ON t1.billnumberid = tt.billnumberid
	END
END
ELSE IF @BillType IN (21)--调拨出库成本就是成本
BEGIN
	UPDATE #tmpBillMoney
	SET CostTotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN (CASE WHEN -a.CostTotal < 0 THEN -ABS(a.CostTotal) ELSE 0 END)
								ELSE (CASE WHEN a.CostTotal < 0 THEN ABS(a.CostTotal) ELSE 0 END)
						 END) AS total,a.BillNumberId
		FROM  dbo.InOutstocktable a 
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		WHERE a.KtypeId <> '10000'
		GROUP BY a.BillNumberId
	) TT ON t1.billnumberid = tt.billnumberid
END
ELSE IF @BillType IN (140,142)--委托代销出库、委托代销退货取一个
BEGIN
	UPDATE #tmpBillMoney
	SET CostTotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN-ABS(a.CostTotal)
								ELSE ABS(a.CostTotal)
						  END) AS total,a.BillNumberId
		FROM dbo.InOutstocktable a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		WHERE a.KtypeId <> '10000'
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
END
ELSE IF @BillType IN (141)--委托代销结算，只操作代销库
BEGIN
	UPDATE #tmpBillMoney
	SET CostTotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN-ABS(a.CostTotal)
								   ELSE ABS(a.CostTotal)
							  END) AS total,a.BillNumberId
		FROM  dbo.InOutstocktable a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
END
ELSE IF @BillType IN (147)--受托代销调价单
BEGIN
	UPDATE #tmpBillMoney SET total = TT.total
	FROM #tmpBillMoney T3
	INNER JOIN 
		(	SELECT T2.BillNumberId, CASE WHEN T2.RedWord = 2 THEN  -SUM(ABS(Total)) ELSE SUM(ABS(Total)) END AS total 
			FROM dbo.InOutstocktable T1
			INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = T2.BillNumberId
		WHERE  Qty < 0
		GROUP BY T2.BillNumberId, T2.RedWord) TT ON TT.BillNumberId = T3.billnumberid
END
ELSE IF @BillType IN (414)
BEGIN	
	UPDATE #tmpBillMoney
	SET totalfreight = TT.totalfreight
		,tax = TT.tax
	FROM #tmpBillMoney T1
	INNER JOIN BillIndex TT ON T1.billnumberid = TT.BillNumberId
END
ELSE IF @BillType=427--积分转储值单 只能本位币
BEGIN
	UPDATE #tmpBillMoney 
	SET 
		z_totalmoney = TT.ChangeMoney,
		z_totalmoneyFor = TT.ChangeMoney
	FROM #tmpBillMoney T1
	INNER JOIN VipCentToMoneyBill TT ON T1.billnumberid = TT.BillNumberId
END
ELSE
BEGIN
	UPDATE #tmpBillMoney
	SET costtotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN -ABS(a.CostTotal) ELSE ABS(a.CostTotal) END) AS total,a.BillNumberId
		FROM  dbo.InOutstocktable a
			INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
			INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
		WHERE a.KtypeId <> '10000'
			AND c.IsService = 0
			and a.BillType = @BillType
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
	
	--服务商品成本金额
	IF @BillType = 34--采购入库
		UPDATE #tmpBillMoney
		SET costtotal_S	= TT.total
			,costTotal_Sfor = tt.totalfor
		FROM #tmpBillMoney T1
		INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN -ABS(a.total) ELSE ABS(a.total) END) AS total
					,SUM(CASE WHEN b.RedWord = 2 THEN -ABS(a.NTotal) ELSE ABS(a.NTotal) END) AS totalfor,
					a.BillNumberId
			FROM  dbo.BuyBill a
				INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
				INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
			WHERE a.KtypeId <> '10000'
				AND c.IsService = 1
			GROUP BY a.BillNumberId
		)TT ON T1.billnumberid = TT.BillNumberId
	ELSE IF @BillType = 6--采购退货
		UPDATE #tmpBillMoney
		SET costtotal_S	= TT.total
			,costTotal_Sfor = tt.totalfor
		FROM #tmpBillMoney T1
		INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN -ABS(a.total) ELSE ABS(a.total) END) AS total,
							SUM(CASE WHEN b.RedWord = 2 THEN -ABS(a.NTotal) ELSE ABS(a.NTotal) END) AS totalfor,
							a.BillNumberId
			FROM  dbo.BuyBackBill a
				INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
				INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
			WHERE a.KtypeId <> '10000'
				AND c.IsService = 1
			GROUP BY a.BillNumberId
		)TT ON T1.billnumberid = TT.BillNumberId
END		
	
DECLARE @sql_table NVARCHAR(100),@sql_search NVARCHAR(MAX)
SET @sql_table = ''
SET @sql_search = ''

IF @BillType = 160	--销售换货单
BEGIN
	UPDATE #tmpBillMoney
	SET instocktotal		= total1,
			outstocktotal	= total2,
			instocktaxtotal	= total3,
			outstocktaxtotal= total4,
			instocktotal_S = total5,
			outstocktotal_S = total6
	FROM #tmpBillMoney T1
	INNER JOIN(SELECT	SUM(CASE WHEN c.isservice = 0 THEN 
								CASE InOrOut WHEN 'I' THEN (CASE WHEN b.RedWord = 2 THEN -total ELSE total END) ELSE 0 END
							ELSE 0 END) AS total1,
						SUM(CASE WHEN c.isservice = 0 THEN 
								CASE InOrOut WHEN 'O' THEN (CASE WHEN b.RedWord = 2 THEN -total ELSE total END) ELSE 0 END
							ELSE 0 END)AS total2,
						SUM(CASE InOrOut WHEN 'I' THEN (CASE WHEN b.RedWord = 2 THEN -taxtotal ELSE taxtotal END) ELSE 0 END) AS total3,
						SUM(CASE InOrOut WHEN 'O' THEN (CASE WHEN b.RedWord = 2 THEN -taxtotal ELSE taxtotal END) ELSE 0 END) AS total4,
						SUM(CASE WHEN c.isservice = 1 THEN 
								CASE InOrOut WHEN 'I' THEN (CASE WHEN b.RedWord = 2 THEN -total ELSE total END) ELSE 0 END
							ELSE 0 END) AS total5,
						SUM(CASE WHEN c.isservice = 1 THEN 
								CASE InOrOut WHEN 'O' THEN (CASE WHEN b.RedWord = 2 THEN -total ELSE total END) ELSE 0 END
							ELSE 0 END)AS total6,
						a.BillNumberId
		FROM  dbo.SaleGoodsExchangeBill a
			INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
			INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.billnumberid
END
ELSE IF @BillType = 139	--赠送单
BEGIN
	UPDATE #tmpBillMoney
	SET GoodsCostTotal = TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.GoodsCostTotal ELSE a.GoodsCostTotal END) AS total,a.BillNumberId
		FROM  dbo.GiveBill a 
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON t1.billnumberid = tt.billnumberid
END
ELSE IF @BillType = 161	--采购换货
BEGIN
	UPDATE #tmpBillMoney
		SET instocktotal	= total1,
			outstocktotal	= total2,
			instocktaxtotal	= total3,
			outstocktaxtotal= total4
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT	SUM(CASE InOrOut WHEN 'I' THEN (CASE WHEN b.RedWord = 2 THEN -total ELSE total END) ELSE 0 END ) AS total1,
						SUM(CASE InOrOut WHEN 'O' THEN (CASE WHEN b.RedWord = 2 THEN -total ELSE total END) ELSE 0 END) AS total2,
						SUM(CASE InOrOut WHEN 'I' THEN (CASE WHEN b.RedWord = 2 THEN -TaxTotal ELSE TaxTotal END) ELSE 0 END) AS total3,
						SUM(CASE InOrOut WHEN 'O' THEN (CASE WHEN b.RedWord = 2 THEN -TaxTotal ELSE TaxTotal END) ELSE 0 END) AS total4,
						a.BillNumberId
		FROM dbo.BuyGoodsExchangeBill a
			INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.billnumberid
END
ELSE IF @BillType = 126	--获赠单
BEGIN
	UPDATE #tmpBillMoney
	SET GoodsCostTotal = TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.GoodsCostTotal ELSE a.GoodsCostTotal END) AS total,a.BillNumberId
		FROM dbo.GiveBill a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
END
ELSE IF @BillType = 16	--生产拆装单
BEGIN
	UPDATE #tmpBillMoney
		SET instocktotal	= total1,
			outstocktotal	= total2
	FROM #tmpBillMoney T1
	INNER JOIN(SELECT SUM(CASE InOrOut WHEN 'I' THEN (CASE WHEN b.RedWord = 2 THEN -total ELSE total END) ELSE 0 END) AS total1,
						SUM(CASE InOrOut WHEN 'O' THEN (CASE WHEN b.RedWord = 2 THEN -total ELSE total END) ELSE 0 END) AS total2,
						a.BillNumberId
		FROM dbo.DisassembleBill a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
	
	UPDATE #tmpBillMoney
	SET instockGoodsCostTotal = total1,
		outstockGoodsCostTotal = total2
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 
								THEN (CASE WHEN -CostTotal > 0 THEN -ABS(CostTotal) ELSE 0 END)
							 ELSE (CASE WHEN CostTotal > 0 THEN ABS(CostTotal) ELSE 0 END)
						END) AS total1,
						SUM(CASE WHEN b.RedWord = 2 
								THEN (CASE WHEN -CostTotal < 0 THEN -ABS(CostTotal) ELSE 0 END)
							 ELSE (CASE WHEN CostTotal < 0 THEN ABS(CostTotal) ELSE 0 END)
						END) AS total2,
						a.BillNumberId
			FROM dbo.InOutstocktable a
			INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
			GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.billnumberid
END
ELSE IF @BillType = 57	--成本调价单
BEGIN
	UPDATE #tmpBillMoney
	SET total = total1,
		beforetotal = total2 
	FROM #tmpBillMoney T1
	INNER JOIN(SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.total ELSE a.total END) AS total1,
						SUM(CASE WHEN b.RedWord = 2 THEN -ABS(a.BeforeTotal) ELSE ABS(a.BeforeTotal) END) AS total2,
						a.BillNumberId
		FROM AdpriceBill a 
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
END
ELSE IF @BillType = 205	--采购费用分摊
BEGIN
	UPDATE #tmpBillMoney
	SET sharefee = tt.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.shareFee ELSE a.ShareFee END) AS total,
						a.BillNumberId
		FROM dbo.ShareSourceBill a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.billnumberid
END 
ELSE IF @BillType = 183	--积分兑换单
BEGIN
	UPDATE #tmpBillMoney
	SET GoodsCostTotal = TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.GoodsCostTotal ELSE a.GoodsCostTotal END) AS total,
					a.BillNumberId
		FROM dbo.IntegralExchangeBill a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
END
ELSE IF @BillType = 159 --业务凭证
BEGIN
	UPDATE #tmpBillMoney
	SET j_total = dbo.F_RoundTotal(J_Total),
		   d_total = dbo.F_RoundTotal(D_Total)
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(J_Total) AS total1,SUM(D_Total) AS total2,a.BillNumberID
		FROM dbo.AccountCredence a
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = a.BillNumberId
		GROUP BY a.BillNumberID
	)TT ON T1.billnumberid = TT.BillNumberID
END
ELSE
BEGIN
	SELECT @sql_table = detailTable FROM BillName WHERE Billtype = @BillType
END


/*
IF @BillType = 11	--销售出库单
BEGIN
	SET @sql_table = 'SaleBill'
END
IF @BillType = 45	--销售退货单
BEGIN
	SET @sql_table = 'saleBackBill'
END
IF @BillType = 12	--组合销售出库单
BEGIN
	SET @sql_table = 'PT_Combin_SaleBillDetail'
END
IF @BillType = 46	--组合销售退货单
BEGIN
	SET @sql_table = 'PT_Combin_SaleBackBillDetail'
END
IF @BillType = 402	--暂估销售出库单
BEGIN
	SET @sql_table = 'SendBill'
END
IF @BillType = 403	--暂估销售退货单
BEGIN
	SET @sql_table = 'SendBackBill'
END
IF @BillType = 305	--零售单
BEGIN
	SET @sql_table = 'retailBill'
END
IF @BillType = 140	--委托代销发货
BEGIN
	SET @sql_table = 'CommissionBill'
END
IF @BillType = 142	--委托代销退货
BEGIN
	SET @sql_table = 'CommissionBill'
END
IF @BillType = 141	--委托代销结算
BEGIN
	SET @sql_table = 'CommissionBill'
END
IF @BillType = 34	--采购入库单
BEGIN
	SET @sql_table = 'BuyBill'
END
IF @BillType = 6	--采购退货
BEGIN
	SET @sql_table = 'BuyBackBill'
END
IF @BillType = 400	--暂估采购入库单
BEGIN
	SET @sql_table = 'AppraisalBill'
END
IF @BillType = 401	--暂估采购退货
BEGIN
	SET @sql_table = 'AppraisalBackBill'
END
IF @BillType = 144	--受托代销收货
BEGIN
	SET @sql_table = 'CommissionBill'
END
IF @BillType = 146	--受托代销退货
BEGIN
	SET @sql_table = 'CommissionBill'
END
IF @BillType = 145	--受托代销结算
BEGIN
	SET @sql_table = 'CommissionBill'
END
IF @BillType = 21	--变价调拨单 
BEGIN
	SET @sql_table = 'MoveBjBill'
END
IF @BillType = 187	--分支机构调拨出库
BEGIN
	SET @sql_table = 'StypeMoveBill'
END
IF @BillType = 188	--分支机构调拨入库
BEGIN
	SET @sql_table = 'StypeMoveBill'
END
IF @BillType = 201	--其他入库单
BEGIN
	SET @sql_table = 'OtherInOutBill'
END
IF @BillType = 202	--其他出库单
BEGIN
	SET @sql_table = 'OtherInOutBill'
END
IF @BillType = 9	--报损单
BEGIN
	SET @sql_table = 'LoseBill'
END
IF @BillType = 14	--报溢单
BEGIN
	SET @sql_table = 'overflowBill'
END
IF @BillType = 116	--应收款增加
BEGIN
	SET @sql_table = 'AdDebtBill'
END
IF @BillType = 115	--应收款减少
BEGIN
	SET @sql_table = 'AdDebtBill'
END
IF @BillType = 128	--应付款增加
BEGIN
	SET @sql_table = 'AdDebtBill'
END
IF @BillType = 129	--应付款减少
BEGIN
	SET @sql_table = 'AdDebtBill'
END
IF @BillType = 4	--收款单
BEGIN
	SET @sql_table = 'gatheringBill'
END
IF @BillType = 189	--预收款单
BEGIN
	SET @sql_table = 'PreBill'
END
IF @BillType = 66	--付款单
BEGIN
	SET @sql_table = 'PayBill'
END
IF @BillType = 190	--预付款单
BEGIN
	SET @sql_table = 'PreBill'
END
IF @BillType = 148	--返利核算执行
BEGIN
	SET @sql_table = 'Advantage'
END
IF @BillType = 150	--获利核算执行
BEGIN
	SET @sql_table = 'Advantage'
END
IF @BillType = 149	--价保执行单
BEGIN
	SET @sql_table = 'PriceProtectBill'
END
IF @BillType = 151	--获得价保执行单
BEGIN
	SET @sql_table = 'PriceProtectBill'
END
IF @BillType = 36	--费用单
BEGIN
	SET @sql_table = 'MoneyBill'
END
IF @BillType = 84	--固定资产购买
BEGIN
	SET @sql_table = 'MoneyBill'
END
IF @BillType = 85	--固定资产变卖
BEGIN
	SET @sql_table = 'MoneyBill'
END
IF @BillType = 78	--固定资产折旧
BEGIN
	SET @sql_table = 'MoneyBill'
END
IF @BillType = 158	--现金费用单
BEGIN
	SET @sql_table = 'MoneyBill'
END
IF @BillType = 77	--转款单
BEGIN
	SET @sql_table = 'MoveMoneyBill'
END
IF @BillType = 93	--其他收入单
BEGIN
	SET @sql_table = 'MoneyBill'
END
IF @BillType = 5	--待摊费用发生
BEGIN
	SET @sql_table = 'MoneyBill'
END
IF @BillType = 10	--待摊费用摊销
BEGIN
	SET @sql_table = 'MoneyBill'
END
IF @BillType = 166	--维修单
BEGIN
	SET @sql_table = 'wx_Bill_Self'
END
IF @BillType = 167	--取件单
BEGIN
	SET @sql_table = 'wx_Bill_GetBack'
END
IF @BillType = 168	--整机更换单
BEGIN
	SET @sql_table = 'wx_Bill_Replace'
END
IF @BillType = 170	--送修返回单
BEGIN
	SET @sql_table = 'wx_Bill_SendBack'
END
IF @BillType = 172	--上门维修单
BEGIN
	SET @sql_table = 'wx_Bill_Goto'
END
IF @BillType = 215 --零售退货单
	SET @sql_table = 'RetailBackBill'
*/

DECLARE @ParmDefinition nvarchar(500);
DECLARE @total					 NUMERIC(24, 10)  =0,	--折后金额
		@taxtotal				 NUMERIC(24, 10)  =0,	--价税合计		
		@GoodsCostTotal			 NUMERIC(24, 10)  =0	--成本金额
		
--获取金额
IF @BillType IN (11,45,305,140,142,141,34,6,144,146,145,215,400,401,402,403,12,46)
BEGIN
	IF @BillType NOT IN (34,400)
		SET @sql_search =	'UPDATE #tmpBillMoney
							 SET total = total1,
								 taxtotal =	total2,
								 total_S = total3,
								 totalfor = total1for,
								 taxtotalfor =	total2for,
								 total_Sfor = total3for
							 FROM #tmpBillMoney T1
							 INNER JOIN(SELECT  SUM(CASE WHEN c.isservice = 0 THEN
														CASE WHEN b.RedWord = 2 THEN -a.total ELSE a.total END
													ELSE 0 END) AS TOTAL1,
												SUM(CASE WHEN b.RedWord = 2 THEN -a.TaxTotal ELSE a.TaxTotal END) AS TOTAL2,
												SUM(CASE WHEN c.isservice = 1 THEN
														CASE WHEN b.RedWord = 2 THEN -a.total ELSE a.total END
													ELSE 0 END) AS TOTAL3,
												SUM(CASE WHEN c.isservice = 0 THEN
														CASE WHEN b.RedWord = 2 THEN -a.ntotal ELSE a.ntotal END
													ELSE 0 END) AS TOTAL1for,
												SUM(CASE WHEN b.RedWord = 2 THEN -a.nTaxTotal ELSE a.nTaxTotal END) AS TOTAL2for,
												SUM(CASE WHEN c.isservice = 1 THEN
														CASE WHEN b.RedWord = 2 THEN -a.ntotal ELSE a.ntotal END
													ELSE 0 END) AS TOTAL3for,
											a.billnumberid
								 FROM '+@sql_table+' a
									INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
									INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
									INNER JOIN PType c ON a.PTypeId = c.TypeId
								 GROUP BY a.BillNumberId
								)TT ON T1.billnumberid = TT.billnumberid'
	ELSE
		SET @sql_search =	'UPDATE #tmpBillMoney
							 SET total = total1,
								 taxtotal =	total2,
								 totalfor = total1for,
								 taxtotalfor =	total2for
							 FROM #tmpBillMoney T1
							 INNER JOIN(SELECT  SUM(CASE WHEN b.RedWord = 2 THEN -a.total ELSE a.total END) AS TOTAL1,
												SUM(CASE WHEN b.RedWord = 2 THEN -a.TaxTotal ELSE a.TaxTotal END) AS TOTAL2,
												SUM(CASE WHEN b.RedWord = 2 THEN -a.ntotal ELSE a.ntotal END) AS TOTAL1for,
												SUM(CASE WHEN b.RedWord = 2 THEN -a.nTaxTotal ELSE a.nTaxTotal END) AS TOTAL2for,
											a.billnumberid
								 FROM '+@sql_table+' a
									INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
									INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
								 GROUP BY a.BillNumberId
								)TT ON T1.billnumberid = TT.billnumberid'
								
	SET @ParmDefinition = N'@total  NUMERIC(24, 10)  output, @taxtotal  NUMERIC(24, 10)  OUTPUT'
	EXEC sp_executesql @sql_search,@ParmDefinition,@total = @total OUTPUT,@taxtotal = @taxtotal OUTPUT
END

IF @BillType IN (17,21,201,202,9,14,166,168,172,187,188)
BEGIN
	SET @sql_search =  'UPDATE #tmpBillMoney
						SET total = TOTAL1,
							GoodsCostTotal = TOTAL2 	
						FROM #tmpBillMoney T1
						INNER JOIN(SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.total ELSE a.total END) AS TOTAL1,
											SUM(CASE WHEN b.RedWord = 2 THEN -a.GoodsCostTotal ELSE a.GoodsCostTotal END) AS TOTAL2,
											a.billnumberid
							FROM '+@sql_table+' a
							INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
									INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
							GROUP BY a.billnumberid
						)TT ON T1.billnumberid = TT.billnumberid'
	SET @ParmDefinition = N'@total  NUMERIC(24, 10)  output, @GoodsCostTotal  NUMERIC(24, 10)  OUTPUT'
	EXEC sp_executesql @sql_search,@ParmDefinition,@total = @total OUTPUT,@GoodsCostTotal = @GoodsCostTotal OUTPUT
END

IF @BillType IN (116,115,128,129,4,189,66,190,148,150,149,151,36,84,85,78,158,77,93,5,10,167,170)
BEGIN
	SET @sql_search =	'UPDATE #tmpBillMoney
						 SET total = TT.total
						 FROM #tmpBillMoney T1
						 INNER JOIN(SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.total ELSE a.total END) AS TOTAL,
											a.billnumberid
							 FROM '+@sql_table+' a
							 INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
									INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
							 GROUP BY a.billnumberid
						 )TT ON T1.billnumberid = TT.billnumberid'
	SET @ParmDefinition = N'@total  NUMERIC(24, 10)  output'
	EXEC sp_executesql @sql_search,@ParmDefinition,@total = @total OUTPUT
END

IF @billtype IN (6,161,401)
BEGIN
	UPDATE #tmpBillMoneyDetail SET preferencemoney = T.preferencemoney/TT.COUN,totalinmoney=T.totalinmoney/TT.COUN
	FROM #tmpBillMoneyDetail A
	INNER JOIN (SELECT billnumberid,SUM(preferencemoney) AS preferencemoney ,SUM(totalinmoney) AS totalinmoney FROM #tmpBillMoney GROUP BY billnumberid) T ON T.billnumberid = A.billnumberid
	INNER JOIN (SELECT billnumberid,COUNT(*) AS COUN  FROM #tmpBillMoneyDetail GROUP BY billnumberid) TT ON TT.billnumberid = T.billnumberid
END

--提成单 提成金额
IF @BillType IN (311)
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBillMoney)
		INSERT INTO #tmpBillMoney(CommissionTotal,billnumberid)
		SELECT SUM(CommissionTotal)
				,b.BillNumberId
		FROM dbo.CommissionBillNewDetail B
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY B.BillNumberId
	ELSE
		UPDATE #tmpBillMoney SET CommissionTotal = TT.CommissionTotal
		FROM #tmpBillMoney T
		INNER JOIN 
				(SELECT SUM(CommissionTotal) AS CommissionTotal
						,B.BillNumberId
				 FROM dbo.CommissionBillNewDetail B
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId 
				 GROUP BY B.BillNumberId
				 )  TT ON TT.BillNumberId = T.billnumberid
END


--应收应付的特殊处理表
CREATE TABLE #tmpAdDebt
(
	BtypeId	VARCHAR(50),
	Total	 NUMERIC(24, 10) ,
	Item	VARCHAR(100),
	id		INT IDENTITY(1,1),
	rowno	INT,
	billnumberid	INT
)
--应收应付
IF @BillType IN (115,116,128,129)
BEGIN
	INSERT INTO #tmpAdDebt( BtypeId, Total, Item,billnumberid)
	SELECT a.BtypeId,SUM(CASE WHEN b.RedWord = 2 THEN -a.total ELSE a.total END) AS total,'4,' AS Itemma,a.BillNumberId
	FROM dbo.AdDebtBill a
	INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
	GROUP BY a.BtypeId,a.BillNumberId
END

--科目来源AcFrom
--1 手工选择
--2 单据上收付款项目对应科目
--3 单据上往来科目
--4 单据上项目对应科目
--5 单据上项目对应固定资产科目
--6 单据上借方项目对应科目
--7 单据上贷方项目对应科目
--8 单据上业务类型对应科目
CREATE TABLE #tmpExpress
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) ,
	lendloanfor	 NUMERIC(24, 10) ,
	rate		 NUMERIC(24, 10) ,
	ratetype	INT,
	billnumberid	INT,
	iscost		INT DEFAULT 0
)

CREATE TABLE #tmpFExpress
(
	atdit		INT,
	nid			INT,
	lendloan	 NUMERIC(24, 10) ,
	rate		 NUMERIC(24, 10) ,
	ratetype	INT,
	rowindex	INT IDENTITY(1,1)
)

CREATE TABLE #tmpFBalance
(
	rowindex	INT DEFAULT 1,
	nid			INT,
	ac_balancea	 NUMERIC(24, 10)  DEFAULT 0,
	ac_balanceb	 NUMERIC(24, 10)  DEFAULT 0,
	ac_balancec	 NUMERIC(24, 10)  DEFAULT 0
)

CREATE TABLE #tmpFBalanceDetails--固定资产折旧使用的明细total
(
	rowindex	INT DEFAULT 1,
	nid			INT,
	ac_balancea	 NUMERIC(24, 10)  DEFAULT 0,
	ac_balanceb	 NUMERIC(24, 10)  DEFAULT 0,
	ac_balancec	 NUMERIC(24, 10)  DEFAULT 0,
	total	 NUMERIC(24, 10)  DEFAULT 0
)
--处理固定资产项目金额为“科目余额”(78，85单据暂不合并，不用考虑多单据合并问题)
IF @BillType IN (78,85)
BEGIN
	
	UPDATE #tmpbillmoney
	SET #tmpbillmoney.total = T1.total
	FROM #tmpbillmoney
	INNER JOIN (SELECT CASE d.RedWord 
				WHEN 2 THEN -total
				ELSE total
			END AS total,
			a.BillNumberId
		FROM dbo.MoneyBill a
		INNER JOIN dbo.BillIndex d ON a.BillNumberId = d.BillNumberId 
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = d.BillNumberId 
		INNER JOIN dbo.Ac_Items b ON a.AtypeId = b.nId
		LEFT JOIN dbo.Ac_Items_Detail c ON b.nId = c.DId AND a.Stypeid = c.STypeId
		) T1 ON T1.billnumberid = #tmpbillmoney.billnumberid
	
	INSERT INTO #tmpFBalanceDetails(nid,ac_balancea,ac_balanceb,ac_balancec,total)
	SELECT  b.nid,CASE e.RedWord 
				WHEN 2 THEN -ISNULL(d1.FEndBalance,0)
				ELSE ISNULL(d1.FEndBalance,0)
			END,
			CASE e.RedWord 
				WHEN 2 THEN -ISNULL(d2.FEndBalance,0)
				ELSE ISNULL(d2.FEndBalance,0)
			END,
			CASE e.RedWord 
				WHEN 2 THEN -ISNULL(d3.FEndBalance,0)
				ELSE ISNULL(d3.FEndBalance,0)
			END,
			a.total
		FROM dbo.MoneyBill a
		INNER JOIN dbo.BillIndex e ON a.BillNumberId = e.BillNumberId 
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = e.BillNumberId 
		INNER JOIN dbo.Ac_Items b ON a.AtypeId = b.nId AND b.TypeName = 'F'
		LEFT JOIN dbo.Ac_Items_Detail c ON b.nId = c.nid AND a.Stypeid = c.STypeId
		LEFT JOIN dbo.Ac_Balance d1 ON c.ATypeId = d1.ATypeId AND a.Stypeid = d1.STypeId AND d1.Cid = 0
		LEFT JOIN dbo.Ac_Balance d2 ON c.DepATypeId = d2.ATypeId AND a.Stypeid = d2.STypeId AND d2.Cid = 0
		LEFT JOIN dbo.Ac_Balance d3 ON c.DisATypeId = d3.ATypeId AND a.Stypeid = d3.STypeId AND d3.Cid = 0
	
	INSERT INTO #tmpFBalance
	        ( rowindex ,
	          nid ,
	          ac_balancea ,
	          ac_balanceb ,
	          ac_balancec
	        )
	SELECT rowindex ,nid ,ac_balancea ,ac_balanceb ,ac_balancec 
	FROM #tmpFBalanceDetails
	
	
	IF @BillType IN (78)--固定资产折旧只有金额,去除合计的total，使用明细--Awu:TODO:单据区分，需要调整此处
	SELECT 
		totalmoney				,
		totalinmoney			,
		preferencemoney			,				
		taxTotal				,
		costTotal				,
		inCostTotal				,
		outCostTotal			,
		rate					,
		ratetype				,
		instocktotal			,
		outstocktotal			,
		instocktaxtotal			,
		outstocktaxtotal		,
		GoodsCostTotal			,
		instockGoodsCostTotal	,
		outstockGoodsCostTotal	,
		beforetotal				,
		sharefee				,
		j_total					,
		d_total					,
		rowindex				
	INTO #tmpBillMoneyNoTotal
	FROM #tmpBillMoney
	
	DECLARE @sql3 VARCHAR(MAX)
	SET @sql3 = 'insert into #tmpFExpress(atdit,nid,lendloan,rate,ratetype)'
	SET @sql3 += ' SELECT * FROM ('
	IF @BillType IN (78)
		SELECT @sql3 += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,nid, ('+ T2.Express +') as lendloan,rate,ratetype
		from #tmpBillMoneyNoTotal a INNER JOIN #tmpFBalanceDetails b on a.rowindex = b.rowindex union all '
		FROM Ac_Auditing_Template_Detail T1
			INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
		WHERE Atid = @Atid AND AcFrom IN (5,9,10)
	ELSE
	SELECT @sql3 += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,nid, ('+ T2.Express +') as lendloan,rate,ratetype
		from #tmpBillMoney a INNER JOIN #tmpFBalance b on a.rowindex = b.rowindex union all '
		FROM Ac_Auditing_Template_Detail T1
			INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
		WHERE Atid = @Atid AND AcFrom IN (5,9,10)
	
	IF LEN(@sql3) > LEN('insert into #tmpFExpress(atdit,nid,lendloan,rate,ratetype) SELECT * FROM (')
	BEGIN
		SET @sql3 = SUBSTRING(@sql3,1,LEN(@sql3)-9)
		SET @SQL3 += ')T ORDER BY AtdId ASC,nid ASC'
		EXEC(@sql3)
	END
	
	IF @BillType IN (78)
		DROP TABLE #tmpBillMoneyNoTotal
END

--读取模板要求的金额（非项目类）
SET @sql = 'insert into #tmpExpress select distinct * from('--MARK:唉，又改回来，这个也要屏蔽，要不然有报错，无语，以后再改回去，直接取消注释吧
--SET @sql = 'insert into #tmpExpress'
IF @BillType IN (6,161,401)
BEGIN
	SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId, sum('+ T2.Express +') as lendloan,'
				+CASE WHEN @IsUseBillMoneyDate = 1 THEN 'sum('+dbo.F_ChangeToOriginalCurrency(T2.Express) +')' ELSE '0' END
				+' as lendloanfor,b.rate,b.ratetype,a.billnumberid,'
				+CASE WHEN dbo.F_ChangeToOriginalCurrency(T2.Express) = '0' THEN '1' ELSE '0' END+' as iscost
	from #tmpBillMoneyDetail a
	inner join #TmpBillInfo b on b.billnumberid = a.billnumberid
	group by a.billnumberid,b.rate,b.ratetype union all '
	FROM Ac_Auditing_Template_Detail T1
			INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
	WHERE Atid = @Atid AND (AcFrom < 4 OR AcFrom = 8)
END
ELSE
BEGIN
	SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,('+ T2.Express +') as lendloan,'
				+CASE WHEN @IsUseBillMoneyDate = 1 THEN '('+dbo.F_ChangeToOriginalCurrency(T2.Express) +')' ELSE '0' END 
				+' as lendloanfor,rate,ratetype,billnumberid,'
				+CASE WHEN dbo.F_ChangeToOriginalCurrency(T2.Express) = '0' THEN '1' ELSE '0' END+' as iscost
	from #tmpBillMoney a'
	+ --MARK:sp5 1454 屏蔽固定资产折旧和固定资产变卖新加的“科目余额”金额
		--如果放开后，此处不应使用#tmpBillMoney，total应该使用明细的.
	CASE WHEN @BillType IN (78,85) THEN ' INNER JOIN #tmpFBalance b on a.rowindex = b.rowindex '
		ELSE ''
	END
	+' union all '
	FROM Ac_Auditing_Template_Detail T1
			INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
	WHERE Atid = @Atid AND (AcFrom <4 OR AcFrom = 8)
END

IF LEN(@sql) > LEN('insert into #tmpExpress select distinct * from(')
BEGIN
	SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
	SET @sql += ')T'
	EXEC(@sql)
END
--取分支机构关联科目
/*SELECT	*,
		CASE WHEN cid = -1 THEN @f_exchid
			 ELSE cid
		END AS rcid,
		SUBSTRING(dbo.F_Get_AscidsItem(@Verifyid,a.typeid),
				LEN(dbo.F_Get_AscidsItem(@Verifyid,a.typeid))-1,
				LEN(dbo.F_Get_AscidsItem(@Verifyid,a.typeid))) AS Item
INTO #tmpAccount
FROM dbo.Ac_Account a
WHERE StypeId = @Verifyid
*/
SELECT	A.*,
		CASE WHEN a.Cid = -1 THEN @f_exchid
			 ELSE a.Cid
		END AS rcid,
		CAST(ISNULL(ASS.Ascids,'0') AS VARCHAR)+',' AS Item
INTO #tmpAccount
FROM dbo.Ac_Account a
left join Ac_Account_Assist_CheckItems ass on ass.STypeId = a.StypeId and ass.ATypeId = a.TypeId and ass.Ascids = 4
WHERE a.StypeId = @Verifyid


DECLARE @BillTypestr VARCHAR(50)
SET @BillTypestr = CAST(@BillType AS VARCHAR(50))


CREATE TABLE #tmpBillMulAccount
(
	Atypeid		VARCHAR(50),
	Usercode	VARCHAR(200),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Cid			INT,
	Atid		INT,
	Total		 NUMERIC(24, 10) ,
	Totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)
CREATE TABLE #tmpBillIndexAtypeid
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atid		INT,
	total		 NUMERIC(24, 10) ,
	totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)
--获取单据上的收付款科目及金额
IF @BillType IN (305,11,45,160,141,
				 34,6,161,145,150,148,
				 149,151,84,85,181,
				 167,168,170,172,36,189,190,158,77,93,215,312,400,401,402,403,12,46,414,427)
	--零售单、销售出库单、销售退货单、销售换货单、委托代销结算
	--采购入库单、采购退货单、采购换货单、受托代销结算、获利核算执行、返利核算
	--价保执行、获得价保、固定资产购买、固定资产变卖、会员储值充值
	--维修取件、整机更换、送修返回、上门维修、费用单、预收、预付、现金费用、转款单、其他收入
BEGIN
	IF @BillType IN (158)
	BEGIN
		INSERT INTO #tmpBillIndexAtypeid
		SELECT	c.ATypeID,
					b.UserCode,
					b.FullName,
					NULL,
					NULL,
					@atid AS atid,
					-1,
					0,
					BB.BillNumberId	 --e.BillNumberId
		FROM  #TmpBillInfo bb
		INNER JOIN dbo.Ac_Items b ON B.nId = BB.ATypeID
		INNER JOIN dbo.Ac_Items_Detail c ON b.nId = c.nId AND c.StypeId = BB.StypeId
		--INNER JOIN dbo.BillIndex e ON e.BillNumberId = @Currentid
		--WHERE b.nId = @atypeid
	END
	ELSE
	BEGIN
		INSERT INTO #tmpBillIndexAtypeid
		SELECT	c.ATypeID,
					b.UserCode,
					b.FullName,
					NULL,
					NULL,
					@atid AS atid,
					CASE WHEN BB.RedWord = 2 THEN -a.Total ELSE a.Total END AS total,
					CASE WHEN BB.RedWord = 2 THEN -a.NTotalMoney ELSE a.NTotalMoney END AS totalfor,
					BB.BillNumberId  --e.BillNumberId
		FROM	#TmpBillInfo BB
		INNER JOIN dbo.BillMulAccount a ON a.BillNumberId = BB.BillNumberId AND A.BillType=@BillType
		INNER JOIN dbo.Ac_Items b ON a.ATypeID = b.nId
		INNER JOIN dbo.Ac_Items_Detail c ON b.nId = c.nId AND c.StypeId = BB.StypeId
		--INNER JOIN dbo.BillIndex e ON a.BillNumberId = e.BillNumberId AND a.BillNumberId = @Currentid
	END

	--现金费用单只有一个科目，金额是表体总额，后面取值不会使用这个数据
	INSERT INTO #tmpBillMulAccount
	SELECT ATypeId,b.UserCode,b.FullName,b.Fdc,b.cid,atid,SUM(Total) AS total,SUM(totalfor) as totalfor,a.billnumberid
	FROM #tmpBillIndexAtypeid a
		LEFT JOIN Ac_Account b ON a.atypeid = b.typeid and b.stypeid = @verifyid
	GROUP BY atypeid,b.usercode,b.fullname,b.fdc,b.cid,atid,a.billnumberid
END

CREATE TABLE #tmpBillIndexAtypeid1
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atid		INT,
	atdid		INT,
	item		VARCHAR(500)
	,billnumberid	INT
)
--单据上的往来科目
IF @BillType IN (11,45,160,141,34,6,161,145,167,168,170,172,116,115,128,129,4,189,66,190,148,150,149,151,181,85,84,93,36,147,312,400,401,402,403,12,46,414,427)
	--销售出库单、销售退货单、销售换货单、委托代销结算单
	--采购入库单、采购退货单、采购换货单、受托代销结算单
	--维修取件单、整机更换单、送修返回单、上门维修单
	--应收款增加、应收款减少、应付款增加、应付款减少
	--收款单、预收款单、付款单、预付款单
	--返利执行、获利执行、价保执行、获得价保
	--会员储值充值单、固定资产变卖、固定资产购买、其他收入单、费用单（分供货商、客户）
BEGIN
	
	INSERT INTO #tmpBillIndexAtypeid1
	SELECT	b.typeId,
		b.UserCode,
		b.FullName,
		Fdc,
		CASE b.cid
			WHEN -1 THEN @f_exchid
			ELSE b.Cid
		END,
		@Atid AS atid,
		@Atdid as atdid,
		SUBSTRING(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1),
				LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))-1,
				LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))) AS Item
		,BB.BillNumberId
	FROM #TmpBillInfo bb
	INNER JOIN dbo.Ac_Account b ON B.TypeId = BB.ATypeID1 AND B.StypeId = BB.VerifyStypeid
	--WHERE b.TypeId=@atypeid1 AND b.StypeId = @verifyid
	
	--无科目，补空白
	IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBillIndexAtypeid1)
	BEGIN
		
		INSERT INTO #tmpBillIndexAtypeid1
				( atypeid ,
				  usercode ,
				  fullname ,
				  fdc ,
				  cid ,
				  atid,
				  atdid
				  ,billnumberid
				)
		SELECT  '' , -- atypeid - varchar(50)
				  '' , -- usercode - varchar(50)
				  '' , -- fullname - varchar(200)
				  0 , -- fdc - int
				  0 , -- cid - int
				  0 , -- atid - int
				  @Atdid
				,BillNumberId
		FROM #TmpBillInfo
	END
END

--凭证明细临时表
CREATE TABLE #tmpBill
(
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rowno			INT		IDENTITY(1,1),
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		addebtid		INT,
		credenceId		INT,
		billid	INT
)

--生成凭证明细数据(科目来源1~3，8)--
INSERT INTO #tmpBill
		( billnumberid ,
		  explain ,
		  atypeid ,
		  atypeid2 ,
		  Fdc ,
		  f_exchid ,
		  f_exchidfor ,
		  lendprice ,
		  loanprice ,
		  lendpricefor ,
		  loanpricefor ,
		  FCashFlowItem ,
		  ascids ,
		  FSettleNo ,
		  FSettleTypeID ,
		  comment ,
		  cid ,
		  rate ,
		  fadc ,
		  stypeid ,
		  fyear ,
		  fperiod,
		  atdid,
		  addebtid,
		  billid
		)
SELECT	DISTINCT @VoucherId AS billnumberid,
		Summary AS explain,
		CASE AcFrom 
			WHEN 1 THEN b.typeid
			WHEN 2 THEN c.atypeid
			WHEN 3 THEN e.atypeid
			WHEN 8 THEN (CASE WHEN @BillType = 201 THEN g4_1.typeid ELSE g4.typeid END)
		END AS atypeid,
		'' AS atypeid2,
		CASE AcFrom 
			WHEN 1 THEN b.Fdc
			WHEN 2 THEN c.Fdc
			WHEN 3 THEN e.Fdc
			WHEN 4 THEN b.Fdc
			WHEN 8 THEN (CASE WHEN @BillType = 201 THEN g4_1.Fdc ELSE g4.Fdc END)
		END AS Fdc,
		@f_exchid AS f_exchid,
		BB.Cid AS f_exchidfor,
		CASE a.Fdc 
			WHEN 1 THEN (CASE WHEN (AcFrom = 2 AND @BillType <> 158) THEN isnull(c.total,0) 
							  WHEN (AcFrom = 1 AND ISNULL(h.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h.total
							  WHEN (AcFrom = 3 AND ISNULL(h1.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h1.total
							  ELSE isnull(d.lendloan,0) END )
							  --现金费用单158，仅仅一个科目表示，没有多账户记录，金额还是来源于表头合计d.lendloan
							  --应收、应付，如果模板辅助是往来，那么按表体明细取值金额,后面的辅助核算也按表体来取
			ELSE 0 
		END AS lendprice,
		CASE a.Fdc 
			WHEN -1 THEN (CASE WHEN (AcFrom = 2 AND @BillType <> 158) THEN ISNULL(c.total,0) 
							   WHEN (AcFrom = 1 AND ISNULL(h.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h.total
							   WHEN (AcFrom = 3 AND ISNULL(h1.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h1.total
							   ELSE isnull(d.lendloan,0) END )
			ELSE 0 
		END AS loanprice,
		CASE WHEN a.Fdc = 1 THEN 
					(CASE ISNULL(d.ratetype,0) 
						WHEN 0 THEN  (CASE WHEN (AcFrom = 2 AND @BillType <> 158) THEN ISNULL(c.total,0) 
										   WHEN (AcFrom = 1 AND ISNULL(h.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h.total
										   WHEN (AcFrom = 3 AND ISNULL(h1.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h1.total
										   ELSE isnull(d.lendloan,0) END ) / ISNULL(d.rate,1)
						WHEN 1 THEN (CASE WHEN (AcFrom = 2 AND @BillType <> 158) THEN ISNULL(c.total,0) 
										  WHEN (AcFrom = 1 AND ISNULL(h.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h.total
										  WHEN (AcFrom = 3 AND ISNULL(h1.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h1.total
										  ELSE isnull(d.lendloan,0) END ) * ISNULL(d.rate,1)
					END)
		END AS lendpricefor,
		CASE WHEN a.Fdc = -1 THEN
					(CASE ISNULL(d.ratetype,0)                                                       
						WHEN 0 THEN (CASE WHEN (AcFrom = 2 AND @BillType <> 158) THEN ISNULL(c.total,0) 
										  WHEN (AcFrom = 1 AND ISNULL(h.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h.total
										  WHEN (AcFrom = 3 AND ISNULL(h1.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h1.total
										  ELSE isnull(d.lendloan,0) END ) / isnull(d.rate,1)
						WHEN 1 THEN (CASE WHEN (AcFrom = 2 AND @BillType <> 158) THEN ISNULL(c.total,0) 
										  WHEN (AcFrom = 1 AND ISNULL(h.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h.total
										  WHEN (AcFrom = 3 AND ISNULL(h1.total,0) <> 0 AND @BillType IN (116,115,128,129)) THEN h1.total
										  ELSE isnull(d.lendloan,0) END ) * isnull(d.rate,1)
					END)
		END AS loanpricefor,
		NULL AS FCashFlowItem,
		'' AS ascids,
		NULL AS FSettleNo,
		0 AS FSettleTypeID,
		'' AS comment,
		BB.Cid,
		d.rate,
		a.Fdc AS fadc,
		@verifyid AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod,
		a.AtdId,
		CASE AcFrom WHEN 1 THEN h.id
					WHEN 3 THEN h1.id
		END,
		D.billnumberid
FROM #TmpVoucherDetails a
INNER JOIN #tmpExpress d ON a.AtdId = d.atdit
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = D.billnumberid
LEFT JOIN #tmpAccount b ON a.ATypeId = b.TypeId
LEFT JOIN #tmpAdDebt h ON b.Item = h.item AND H.billnumberid = D.billnumberid
LEFT JOIN #tmpBillMulAccount c ON a.Atid = c.atid AND C.billnumberid = D.billnumberid
LEFT JOIN #tmpBillIndexAtypeid1 e ON a.Atid = e.atid AND E.billnumberid = D.billnumberid
LEFT JOIN #tmpAdDebt h1 ON e.Item = h1.Item AND H1.billnumberid = D.billnumberid
LEFT JOIN dbo.OtherInOutType g1 ON  g1.ID = BB.OtherInOutType -- @OtherInOutType
LEFT JOIN dbo.Ac_Items g2 ON g1.ATypeID = g2.nId --出库
LEFT JOIN dbo.Ac_Items g2_1 ON g1.ATypeID1 = g2_1.nId--入库
LEFT JOIN dbo.Ac_Items_Detail g3 ON g2.nId = g3.nId AND g3.STypeId = BB.StypeId --- @stypeidValue
LEFT JOIN dbo.Ac_Items_Detail g3_1 ON g2_1.nId = g3_1.nId AND g3_1.STypeId =BB.StypeId  --- @stypeidValue
LEFT JOIN #tmpAccount g4 ON g3.ATypeId = g4.typeid
LEFT JOIN #tmpAccount g4_1 ON g3_1.ATypeId = g4_1.typeid
WHERE a.atid = @Atid AND a.AcFrom IN (1,2,3,8)
ORDER BY a.AtdId

CREATE TABLE #tmpMoneyBill
(
	BillNumberId	INT,
	AtypeId			VARCHAR(50),
	total			 NUMERIC(24, 10) ,
	totalfor			 NUMERIC(24, 10) ,
	STypeid			VARCHAR(50),
	billid	INT	--单据编号
)

CREATE TABLE #tmpItemDetail
(
	AtdId			INT,
	Express			VARCHAR(1000),
	rate			 NUMERIC(24, 10) ,
	ratetype		INT,
	billnumberid	VARCHAR(1000),
	acfrom			INT
)

--项目对应科目生成凭证明细(4,5,9,10)
INSERT INTO #tmpItemDetail
		(AtdId,
		Express,
		rate,
		ratetype,
		billnumberid,
		acfrom)
SELECT AtdId,T2.Express,bb.Rate AS rate,bb.RateType AS ratetype,bb.BillNumberId AS billnumberid,AcFrom
FROM #TmpBillInfo BB
INNER JOIN dbo.Ac_Auditing_Template_Detail T1 ON T1.Atid = BB.AtId
INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
WHERE --AtId = @atid AND 
		AcFrom IN (4,5,9,10)

CREATE TABLE #TmpFixed
(
	nid		INT,
	atypeid	VARCHAR(50),
	fdc		INT,
	atdid	INT,
	rowindex INT IDENTITY(1,1),
	billnumberid	INT
)
--固定资产项目对应的三种科目的处理
INSERT INTO #TmpFixed(nid,atypeid,fdc, atdid,billnumberid)
SELECT 
	c.nid,
	CASE b.acfrom 
		WHEN 9 THEN d.DepATypeId
		WHEN 10 THEN d.DisATypeId
		ELSE d.AtypeId
	END,
	CASE b.acfrom 
		WHEN 9 THEN f.fdc
		WHEN 10 THEN g.fdc
		ELSE e.fdc
	END,
	b.AtdId,
	a.BillNumberId
FROM dbo.MoneyBill a 
	INNER JOIN #tmpItemDetail b ON a.BillNumberId = b.billnumberid
	INNER JOIN dbo.Ac_Items c ON a.AtypeId = c.nId
	LEFT JOIN dbo.Ac_Items_Detail d ON c.nId = d.nId AND a.Stypeid = d.STypeId
	LEFT JOIN dbo.Ac_Account e ON d.ATypeId = e.TypeId AND a.Stypeid = e.StypeId
	LEFT JOIN dbo.Ac_Account f ON d.DepATypeId = f.TypeId AND a.Stypeid = f.StypeId
	LEFT JOIN dbo.Ac_Account g ON d.DisATypeId = g.TypeId AND a.Stypeid = g.StypeId
--WHERE a.BillNumberId  = @CurrentID
ORDER BY AtdId ASC,c.nId ASC

--预收款、付款单，付款、收款单，项目来源其实是收付款，放在此处处理
IF @BillType IN (189,190,4,66)
	INSERT INTO #tmpItemDetail
		(AtdId,
		Express,
		rate,
		ratetype,
		billnumberid)
	SELECT AtdId,T2.Express,BB.Rate AS rate,BB.RateType AS ratetype,BB.BillNumberId AS billnumberid
	FROM #TmpBillInfo BB
	INNER JOIN dbo.Ac_Auditing_Template_Detail T1 ON T1.Atid = BB.AtId
			INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
	WHERE --AtId = @atid AND 
			AcFrom = 2

IF @BillType IN (77)
	INSERT INTO #tmpMoneyBill
			( BillNumberId ,
			  AtypeId ,
			  total ,
			  STypeid,
			  billid
			)
	SELECT a.BillNumberId,a.AtypeId,CASE WHEN BB.RedWord = 2 THEN -total ELSE total END AS total,a.Stypeid,a.BillNumberId
	FROM dbo.MoveMoneyBill a
	--INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
	--WHERE a.BillNumberId  = @CurrentID
IF @BillType IN (189,190)
	INSERT INTO #tmpMoneyBill
			( BillNumberId ,
			  AtypeId ,
			  total ,
			  STypeid,
			  billid
			)
	SELECT a.BillNumberId,a.AtypeId,CASE WHEN BB.RedWord = 2 THEN -total ELSE total END AS total,a.Stypeid,a.BillNumberId
	FROM dbo.PreBill a
	--INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
	--WHERE a.BillNumberId  = @CurrentID
ELSE IF @BillType IN (205)--采购费用分摊项目来自费用单
	INSERT INTO #tmpMoneyBill
			( BillNumberId ,
			  AtypeId ,
			  total ,
			  STypeid,
			  billid
			)
	SELECT b.BillNumberId,a.AtypeId,CASE WHEN BB.RedWord = 2 THEN -total ELSE total END AS total,a.Stypeid,a.BillNumberId
	FROM dbo.MoneyBill a
	INNER JOIN ShareFeeBill b ON a.BillNumberId = b.FromBillNumberID AND a.ID = b.FromBillID
	--INNER JOIN dbo.BillIndex c ON b.BillNumberId = c.BillNumberId		
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
	--WHERE b.BillNumberId  = @CurrentID
ELSE
	INSERT INTO #tmpMoneyBill
			( BillNumberId ,
			  AtypeId ,
			  total ,
			  totalfor,
			  STypeid,
			  billid
			)
	SELECT a.BillNumberId,a.AtypeId,CASE WHEN BB.RedWord = 2 THEN -total ELSE total END AS total,CASE WHEN BB.RedWord = 2 THEN -NTotal ELSE NTotal END AS totalfor,a.Stypeid,a.BillNumberId
	FROM dbo.MoneyBill a
	--INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
	--WHERE a.BillNumberId  = @CurrentID

--MARK:sp5 1454 屏蔽固定资产折旧和固定资产变卖新加的“科目余额”金额
IF @BillType IN (78,85)
	INSERT INTO #tmpBill
	( 
		billnumberid ,
		explain ,
		atypeid ,
		atypeid2 ,
		Fdc ,
		f_exchid ,
		f_exchidfor ,
		lendprice ,
		loanprice ,
		lendpricefor ,
		loanpricefor ,
		FCashFlowItem ,
		ascids ,
		FSettleNo ,
		FSettleTypeID ,
		comment ,
		cid ,
		rate ,
		fadc ,
		stypeid ,
		fyear ,
		fperiod,
		atdid
		,billid
	)
	SELECT @VoucherId
			,a.Summary,
			b.atypeid,
			'',
			b.Fdc ,@f_exchid,BB.Cid,
			CASE a.Fdc
				WHEN 1	THEN b.lendloan
				WHEN -1 THEN 0
			END,
			CASE a.Fdc
				WHEN -1 THEN b.lendloan
				WHEN 1	THEN 0
			END,
			CASE a.Fdc 
				WHEN 1 THEN 
						(CASE b.ratetype 
							WHEN 0 THEN b.lendloan / b.rate
							WHEN 1 THEN b.lendloan * b.rate
						END)
				ELSE 0 
			END,
			CASE a.Fdc
				WHEN -1 THEN
						(CASE b.ratetype  
							WHEN 0 THEN b.lendloan / b.rate
							WHEN 1 THEN b.lendloan* b.rate
						END)
				ELSE 0 
			END,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			NULL AS FSettleTypeID,
			'' AS comment,
			BB.Cid AS cid,
			b.rate,
			a.Fdc AS fadc,
			@Verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId
			,bb.BillNumberId
	FROM #TmpBillInfo bb
	INNER JOIN dbo.Ac_Auditing_Template_Detail a  ON A.Atid = BB.AtId
		INNER JOIN (SELECT T.atdit,SUM(T.lendloan) AS lendloan,T.rate,T.ratetype,c.atypeid,c.fdc FROM #tmpFExpress T 
					INNER JOIN #TmpFixed c ON T.AtdIt = c.atdid AND T.nid = c.nid AND T.rowindex = c.rowindex
					GROUP BY T.atdit,T.rate,T.ratetype,c.atypeid,c.fdc) AS b ON a.AtdId = b.atdit
	--WHERE a.atid = @Atid
	ORDER BY a.AtdId
ELSE
INSERT INTO #tmpBill
		( billnumberid ,
		  explain ,
		  atypeid ,
		  atypeid2 ,
		  Fdc ,
		  f_exchid ,
		  f_exchidfor ,
		  lendprice ,
		  loanprice ,
		  lendpricefor ,
		  loanpricefor ,
		  FCashFlowItem ,
		  ascids ,
		  FSettleNo ,
		  FSettleTypeID ,
		  comment ,
		  cid ,
		  rate ,
		  fadc ,
		  stypeid ,
		  fyear ,
		  fperiod,
		  atdid,
		  billid
		)
SELECT DISTINCT billnumberid,explain,atypeid,atypeid2,fdc,f_exchid,f_exchidfor,SUM(jie),SUM(dai),SUM(jiefor),SUM(daifor),
		FCashFlowItem,ascids,FSettleNo,FSettleTypeID,comment,cid,rate,fadc,stypeid,fyear,fperiod,AtdId,billid
FROM
(
	SELECT	@VoucherId AS billnumberid,c.Summary AS explain,
			e.ATypeId AS atypeid,
			'' AS atypeid2,
			f.Fdc ,@f_exchid AS f_exchid,BB.Cid AS f_exchidfor,
			CASE c.Fdc
				WHEN 1	THEN b.total
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN b.total
				WHEN 1	THEN 0
			END AS dai,
			CASE WHEN c.Fdc = 1 AND @IsUseBillMoneyDate = 1 THEN b.totalfor
				 WHEN c.Fdc = 1 THEN 
						(CASE a.ratetype 
							WHEN 0 THEN b.total / A.rate
							WHEN 1 THEN b.total * A.rate
						END)
				ELSE 0 
			END AS jiefor,
			CASE WHEN c.Fdc = -1 AND @IsUseBillMoneyDate = 1 THEN b.totalfor
				 WHEN c.Fdc = -1 THEN
						(CASE a.ratetype  
							WHEN 0 THEN b.total / A.rate
							WHEN 1 THEN b.total* A.rate
						END)
				ELSE 0 
			END AS daifor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			BB.Cid AS cid,
			a.rate,
			c.Fdc AS fadc,
			@verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId,
			BB.billnumberid AS billid
	FROM	#TmpBillInfo BB
	INNER JOIN #tmpItemDetail a ON A.billnumberid = BB.BillNumberId 
	INNER JOIN #tmpMoneyBill b ON b.BillNumberId =  BB.BillNumberId 
	INNER JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	INNER JOIN dbo.Ac_Items d ON b.AtypeId = d.nid
	INNER JOIN dbo.Ac_Items_Detail e ON d.nId = e.nId AND e.STypeId = BB.StypeId
	INNER JOIN dbo.Ac_Account f ON e.ATypeId = f.TypeId AND f.StypeId = BB.VerifyStypeid
)T
GROUP BY billnumberid,explain,atypeid,atypeid2,fdc,f_exchid,f_exchidfor,FCashFlowItem,ascids,FSettleNo,
			FSettleTypeID,comment,cid,rate,fadc,stypeid,fyear,fperiod,AtdId,billid
			
--业务凭证对应科目生成凭证明细
SELECT AtdId,T2.Express,BB.Rate AS rate,BB.RateType AS ratetype,bb.BillNumberId AS billnumberid
INTO #tmpJDItemDetail
FROM #TmpBillInfo BB
INNER JOIN dbo.Ac_Auditing_Template_Detail T1 ON T1.Atid = BB.AtId
			INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
WHERE --AtId = @atid AND 
		AcFrom >= 6 AND AcFrom <= 7



--业务凭证特殊处理表
CREATE TABLE #tmpAccountCredence
(
	billnumberid	INT,
	TypeAtypeID		VARCHAR(50),
	j_total			 NUMERIC(24, 10) ,
	d_total			 NUMERIC(24, 10) ,
	cid				INT,
	ratetype		INT,
	rate			 NUMERIC(24, 10) ,
	ATypeID			VARCHAR(50),
	id				INT IDENTITY(1,1),
	rowno			INT
)
INSERT INTO #tmpAccountCredence
	(
		billnumberid,
		TypeAtypeID,
		j_total,
		d_total,
		cid,
		ratetype,
		rate,
		ATypeID
	)
SELECT a.BillNumberId,TypeAtypeId,
		SUM(CASE WHEN BB.RedWord = 2 THEN -J_Total ELSE J_Total END) AS j_total,
		0 AS d_total,
		a.cid,
		c.BasisType,
		c.Rate,
		a.ATypeID
FROM	dbo.AccountCredence a
--INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
INNER JOIN dbo.Ac_Currency c ON a.CID = c.CId
--WHERE	a.BillNumberId  = @CurrentID
GROUP BY a.BillNumberId,TypeAtypeId,a.cid,c.BasisType,c.Rate,a.ATypeID
UNION ALL
SELECT a.BillNumberId,TypeAtypeId,
		0 AS j_total,
		SUM(CASE WHEN BB.RedWord = 2 THEN -D_Total ELSE D_Total END) AS d_total,
		a.cid,
		c.BasisType,
		c.Rate,
		a.ATypeID
FROM	dbo.AccountCredence a
--INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
INNER JOIN dbo.Ac_Currency c ON a.CID = c.CId
--WHERE	a.BillNumberId  = @CurrentID
GROUP BY a.BillNumberId,TypeAtypeId,a.cid,c.BasisType,c.Rate,a.ATypeID

DELETE FROM #tmpAccountCredence WHERE j_total = 0 AND d_total = 0


INSERT INTO #tmpBill
		( billnumberid ,
		  explain ,
		  atypeid ,
		  atypeid2 ,
		  Fdc ,
		  f_exchid ,
		  f_exchidfor ,
		  lendprice ,
		  loanprice ,
		  lendpricefor ,
		  loanpricefor ,
		  FCashFlowItem ,
		  ascids ,
		  FSettleNo ,
		  FSettleTypeID ,
		  comment ,
		  cid ,
		  rate ,
		  fadc ,
		  stypeid ,
		  fyear ,
		  fperiod,
		  atdid,
		  credenceId,
		  billid
		)
SELECT DISTINCT * FROM
(
SELECT	@VoucherId AS billnumberid,
		c.Summary AS explain,
		e.ATypeId AS atypeid,
		'' AS atypeid2,
		f.Fdc ,
		@f_exchid AS f_exchid,
		b.cid AS f_exchidfor,
		CASE c.Fdc
			WHEN 1	THEN b.j_total
			WHEN -1 THEN 0
		END AS lendprice,
		CASE c.Fdc
			WHEN -1 THEN b.d_total
			WHEN 1	THEN 0
		END AS loanprice,
		CASE c.Fdc 
			WHEN 1 THEN 
					(CASE b.ratetype 
						WHEN 0 THEN b.j_total / b.rate
						WHEN 1 THEN b.j_total * b.rate
					END)
			ELSE 0 
		END AS lendpricefor,
		CASE c.Fdc 
			WHEN -1 THEN
					(CASE b.ratetype  
						WHEN 0 THEN b.d_total / b.rate
						WHEN 1 THEN b.d_total* b.rate
					END)
			ELSE 0 
		END AS loanpricefor,
		NULL AS FCashFlowItem,
		'' AS ascids,
		NULL AS FSettleNo,
		0 AS FSettleTypeID,
		'' AS comment,
		b.cid AS cid,
		b.rate,
		c.Fdc AS fadc,
		@verifyid AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod,
		a.AtdId,
		b.id,
		b.billnumberid AS billid
FROM	#tmpJDItemDetail a
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.billnumberid
INNER JOIN #tmpAccountCredence b ON b.BillNumberId=a.billnumberid-- IN (SELECT * FROM f_split(a.billnumberid,','))
LEFT JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
LEFT JOIN dbo.Ac_Items d ON b.TypeAtypeId = d.nid
LEFT JOIN dbo.Ac_Items_Detail e ON d.nId = e.nId AND e.STypeId = BB.StypeId
LEFT JOIN dbo.Ac_Account f ON e.ATypeId = f.TypeId AND f.StypeId = BB.VerifyStypeid
) T 
WHERE lendprice <> 0 OR loanprice <> 0

/*
处理存货类型
15-存货
16-收入
17-成本
*/
IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AcFrom IN(15,16,17))
BEGIN
	CREATE TABLE #InventoryTypeAccount
	(
		atdid	INT
		,atypeid	VARCHAR(50)
		,billnumberid	NUMERIC(10,0)
		,lendloan		NUMERIC(24,10)
		,lendloanfor	 NUMERIC(24, 10) ,
		rate		 NUMERIC(24, 10) ,
		ratetype	INT,
		iscost		INT DEFAULT 0
	)
	
	CREATE TABLE #BillDetailsInventoryTypeAccount
	(
		billnumberid	NUMERIC(10,0)
		,PTYPEID	VARCHAR(50)
		,TID		INT
		,stypeid	VARCHAR(50)
		,CostATypeID	VARCHAR(50)
		,IncomeATypeID	VARCHAR(50)
		,StockATypeID	VARCHAR(50)
		,total		NUMERIC(24,10)
		,costtotal	NUMERIC(24,10)
		,taxtotal	NUMERIC(24,10)
		,goodscosttotal	NUMERIC(24,10)
		,incosttotal	NUMERIC(24,10)
		,outcosttotal	NUMERIC(24,10)
		,instocktotal	NUMERIC(24,10)
		,outstocktotal	NUMERIC(24,10)
		,instockgoodscosttotal	NUMERIC(24,10)
		,outstockgoodscosttotal	NUMERIC(24,10)
		
		,totalfor		NUMERIC(24,10)
		,costtotalfor	NUMERIC(24,10)
		,taxtotalfor	NUMERIC(24,10)
		,goodscosttotalfor	NUMERIC(24,10)
		,incosttotalfor	NUMERIC(24,10)
		,outcosttotalfor	NUMERIC(24,10)
		,instocktotalfor	NUMERIC(24,10)
		,outstocktotalfor	NUMERIC(24,10)
		,instockgoodscosttotalfor	NUMERIC(24,10)
		,outstockgoodscosttotalfor	NUMERIC(24,10)
		
		,totalmoney		NUMERIC(24,10)
	)
	
	CREATE TABLE #InOutstocktableSUM
	(
		BillNumberId	NUMERIC(10,0)
		,Ptypeid		VARCHAR(50)
		,Total			NUMERIC(24,10)
		,NTotal			NUMERIC(24,10)
		,CostTotal		NUMERIC(24,10)
		,TaxTotal		NUMERIC(24,10)	
		,nTaxTotal		NUMERIC(24,10)	
		,incosttotal	NUMERIC(24,10)
		,outcosttotal	NUMERIC(24,10)
		,instocktotal	NUMERIC(24,10)
		,outstocktotal	NUMERIC(24,10)
		,sharefee		NUMERIC(24,10)	
		,instockgoodscosttotal	NUMERIC(24,10)
		,outstockgoodscosttotal	NUMERIC(24,10)
		,totalmoney		NUMERIC(24,10)
	)
	
	IF @BillType = 21   --变价调拨单
	BEGIN		
		INSERT INTO #InOutstocktableSUM
			(
				billnumberid
				,ptypeid
				
				,total
				,NTotal
				,costtotal
				,taxtotal
				,ntaxtotal	
										
				,incosttotal	
				,outcosttotal	
				,instockgoodscosttotal	
				,outstockgoodscosttotal	
				
				,instocktotal
				,outstocktotal	
				
				,totalmoney			
			)
		SELECT	T.BillNumberId
				,T.ptypeid
				
				,SUM(T.Total)	--折后金额
				,SUM(T.NTotal)
				,SUM(T.CostTotal)	--成本金额
				,SUM(T.TaxTotal)	--价税合计
				,SUM(T.NTaxTotal)	--价税合计原币
				
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库商品成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库商品成本
				
				,SUM(CASE WHEN T.Total>0 THEN T.Total ELSE 0 END)	--金额 转成 入库金额
				,SUM(CASE WHEN T.Total>0 THEN 0 ELSE T.Total END)	--金额 转成 出库金额
				
				,SUM(CASE WHEN T.Total < 0 THEN 0 ELSE T.Total END)
		FROM InOutstocktable T
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
		WHERE T.Total < 0  and t.BillType=@BillType
		GROUP BY T.BillNumberId,T.PtypeId
	END
	ELSE IF @BillType IN(145,147) --受托代销结算单、受托代销调价单
	BEGIN
		INSERT INTO #InOutstocktableSUM
			(
				billnumberid
				,ptypeid
				
				,total
				,NTotal
				,costtotal
				,taxtotal
				,ntaxtotal	
										
				,incosttotal	
				,outcosttotal	
				,instockgoodscosttotal	
				,outstockgoodscosttotal	
				
				,instocktotal
				,outstocktotal	
				
				,totalmoney			
			)
		SELECT	T.BillNumberId
				,T.ptypeid
				
				,SUM(CASE WHEN T.Total > 0 THEN 0 ELSE T.Total END)	--折后金额
				,SUM(CASE WHEN T.NTotal > 0 THEN 0 ELSE T.NTotal END)
				,SUM(T.CostTotal)	--成本金额
				,SUM(T.TaxTotal)	--价税合计
				,SUM(T.NTaxTotal)	--价税合计原币
				
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库商品成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库商品成本
				
				,SUM(CASE WHEN T.Total>0 THEN T.Total ELSE 0 END)	--金额 转成 入库金额
				,SUM(CASE WHEN T.Total>0 THEN 0 ELSE T.Total END)	--金额 转成 出库金额
				
				,SUM(CASE WHEN T.Total < 0 THEN 0 ELSE T.Total END)
		FROM InOutstocktable T
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId  
		WHERE  t.BillType=@BillType
		GROUP BY T.BillNumberId,T.PtypeId
	END
	ELSE IF @BillType IN(141)
	BEGIN
		INSERT INTO #InOutstocktableSUM
			(
				billnumberid
				,ptypeid
				
				,total
				,NTotal
				,costtotal
				,taxtotal
				,ntaxtotal	
										
				,incosttotal	
				,outcosttotal	
				,instockgoodscosttotal	
				,outstockgoodscosttotal	
				
				,instocktotal
				,outstocktotal	
				
				,totalmoney			
			)
		SELECT	T.BillNumberId
				,T.ptypeid
				
				,SUM(T.Total)	--折后金额
				,SUM(T.NTotal)
				,SUM(T.CostTotal)	--成本金额
				,SUM(T.TaxTotal)	--价税合计
				,SUM(T.NTaxTotal)	--价税合计原币
				
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库商品成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库商品成本
				
				,SUM(CASE WHEN T.Total>0 THEN T.Total ELSE 0 END)	--金额 转成 入库金额
				,SUM(CASE WHEN T.Total>0 THEN 0 ELSE T.Total END)	--金额 转成 出库金额
				
				,SUM(T.Total)
		FROM InOutstocktable T
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
		INNER JOIN	PType P ON P.typeId = T.PtypeId
		WHERE	P.IsService = 0  and t.BillType=@BillType
		GROUP BY T.BillNumberId,T.PtypeId
	END
	ELSE
	BEGIN
		INSERT INTO #InOutstocktableSUM
			(
				billnumberid
				,ptypeid
				
				,total
				,NTotal
				,costtotal
				,taxtotal
				,ntaxtotal	
										
				,incosttotal	
				,outcosttotal	
				,instockgoodscosttotal	
				,outstockgoodscosttotal	
				
				,instocktotal
				,outstocktotal	
				
				,totalmoney			
			)
		SELECT	T.BillNumberId
				,T.ptypeid
				
				,SUM(T.Total)	--折后金额
				,SUM(T.NTotal)
				,SUM(T.CostTotal)	--成本金额
				,SUM(T.TaxTotal)	--价税合计
				,SUM(T.NTaxTotal)	--价税合计原币
				
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库商品成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库商品成本
				
				,SUM(CASE WHEN T.Total>0 THEN T.Total ELSE 0 END)	--金额 转成 入库金额
				,SUM(CASE WHEN T.Total>0 THEN 0 ELSE T.Total END)	--金额 转成 出库金额
				
				,SUM(T.Total)
		FROM InOutstocktable T
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
		INNER JOIN	PType P ON P.typeId = T.PtypeId
		WHERE	T.KtypeId <> '10000'
			AND	P.IsService = 0 and t.BillType=@BillType
		GROUP BY T.BillNumberId,T.PtypeId
	END
	
	
	INSERT INTO #BillDetailsInventoryTypeAccount
		(
			billnumberid
			,PTYPEID
			,stypeid
			,TID
			,CostATypeID
			,IncomeATypeID
			,StockATypeID
			,total
			,costtotal
			,taxtotal
			,goodscosttotal
			
			,totalfor
			,costtotalfor
			,taxtotalfor
			,goodscosttotalfor		
					
			,incosttotal	
			,outcosttotal	
			,instockgoodscosttotal	
			,outstockgoodscosttotal	
			,instocktotal
			,outstocktotal
			
			,incosttotalfor	
			,outcosttotalfor	
			,instockgoodscosttotalfor	
			,outstockgoodscosttotalfor	
			,instocktotalfor
			,outstocktotalfor
			
			,totalmoney
			
		)
	SELECT	T.BillNumberId
			,T.Ptypeid
			,B.Stypeid
			,PIT.InventoryTypeid
			,BITD.CostATypeID
			,BITD.IncomeATypeID
			,BITD.StockATypeID
			,ABS(CASE WHEN @BillType IN(305,215,11,45,160,140,142,141,34,6,161,144,146,147,145,12,46) THEN T.Total ELSE T.NTotal END)
			,ABS(T.CostTotal)	
			,ABS(CASE WHEN @BillType IN(305,215,11,45,160,140,142,141,34,6,161,144,146,147,145,12,46) THEN T.TaxTotal ELSE T.NTaxTotal END)
			,ABS(T.CostTotal)	
						
			,ABS(T.nTotal)	
			,ABS(T.CostTotal)	
			,ABS(T.nTaxTotal)	
			,ABS(T.CostTotal)	
			
			,ABS(T.incosttotal)	
			,ABS(T.outcosttotal)	
			,ABS(T.instockgoodscosttotal)	
			,ABS(T.outstockgoodscosttotal)
			,ABS(T.instocktotal)
			,ABS(T.outstocktotal)
			
			,ABS(T.incosttotal)	
			,ABS(T.outcosttotal)	
			,ABS(T.instockgoodscosttotal)	
			,ABS(T.outstockgoodscosttotal)
			,ABS(T.instocktotal)
			,ABS(T.outstocktotal)
			
			,ABS(T.totalmoney)
			
	FROM #InOutstocktableSUM T
	INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
	INNER JOIN	PType PIT ON PIT.typeid = T.PtypeId
	INNER JOIN	Base_InventoryTypeDetails BITD ON BITD.TID = PIT.InventoryTypeid AND BITD.STypeID = B.Stypeid
	
	DECLARE @AcFromLoop	INT
			--select * from #BillDetailsInventoryTypeAccount
			--select * from #InOutstocktableSUM
	SET @AcFromLoop = 14
	
	SET @sql = 'insert into #InventoryTypeAccount 
			(
				atdid
				,atypeid
				,lendloan
				,lendloanfor
				,rate
				,ratetype
				,billnumberid
				,iscost
			)
			select atdid
				,atypeid
				,lendloan
				,lendloanfor
				,rate
				,ratetype
				,billnumberid
				,iscost 
			from('
			
	WHILE @AcFromLoop <=17
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AcFrom = @AcFromLoop)
		BEGIN
			SET @AcFromLoop += 1
			CONTINUE
		END
			
		SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId
			,'+CASE @AcFromLoop WHEN 15 THEN 'StockATypeID' WHEN 16 THEN 'IncomeATypeID' ELSE 'CostATypeID' END +' as atypeid
			, sum('+ T2.Express +') as lendloan
			,'+CASE WHEN @IsUseBillMoneyDate = 1 THEN 'sum('+dbo.F_ChangeToOriginalCurrency(T2.Express) +')' ELSE '0' END+' as lendloanfor
			,b.rate
			,b.ratetype
			,a.billnumberid
			,'+CASE WHEN dbo.F_ChangeToOriginalCurrency(T2.Express) = '0' THEN '1' ELSE '0' END+' as iscost
		from #BillDetailsInventoryTypeAccount a
		inner join #TmpBillInfo b on b.billnumberid = a.billnumberid
		group by a.billnumberid,'+CASE @AcFromLoop WHEN 15 THEN 'StockATypeID' WHEN 16 THEN 'IncomeATypeID' ELSE 'CostATypeID' END +',b.rate,b.ratetype union all '
		FROM #TmpVoucherDetails T1
				INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
		WHERE  AcFrom = @AcFromLoop
		SET @AcFromLoop += 1
	END
	
	SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
	SET @sql += ')T'
	EXEC(@sql)
	
	INSERT INTO #tmpBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  atdid,
			  billid
			)
	SELECT DISTINCT * FROM
	(
	SELECT	@VoucherId AS billnumberid
			,c.Summary AS explain,
			a.ATypeId AS atypeid,
			'' AS atypeid2,
			Ac.Fdc 
			,@f_exchid AS f_exchid
			,BB.Cid AS f_exchidfor
			,CASE c.Fdc
				WHEN 1	THEN a.lendloan
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN a.lendloan
				WHEN 1	THEN 0
			END AS dai,
			CASE WHEN c.Fdc = 1 AND @IsUseBillMoneyDate = 1 AND a.iscost = 0 THEN a.lendloanfor
				 WHEN c.Fdc = 1 THEN 
						(CASE a.ratetype 
							WHEN 0 THEN a.lendloan / A.rate
							WHEN 1 THEN a.lendloan * A.rate
						END)
				ELSE 0 
			END AS jiefor,
			CASE WHEN c.Fdc = -1 AND @IsUseBillMoneyDate = 1 AND a.iscost = 0 THEN a.lendloanfor
				 WHEN c.Fdc = -1 THEN
						(CASE a.ratetype  
							WHEN 0 THEN a.lendloan / A.rate
							WHEN 1 THEN a.lendloan* A.rate
						END)
				ELSE 0 
			END AS daifor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			BB.Cid AS cid,
			a.rate,
			c.Fdc AS fadc,
			@verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId,
			BB.billnumberid AS billid
	FROM	#InventoryTypeAccount a
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.billnumberid
	INNER JOIN Ac_Account AC ON AC.StypeId = BB.VerifyStypeid AND AC.TypeId = A.atypeid
	LEFT JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	) T 
	WHERE jie <> 0 OR dai <> 0
	
	DROP TABLE #BillDetailsInventoryTypeAccount,#InventoryTypeAccount
END



--根据配置，对成本明细做删除
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1)
BEGIN
	DELETE FROM #TmpBill WHERE atdid IN (SELECT AtdId FROM #TmpVoucherDetails WHERE isCost = 1)
END

--Awu:调整平衡数
DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) ,@balancemoneyfor  NUMERIC(24, 10) 
IF @Billtype IN (6,161)
BEGIN
	SELECT	@balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
			,@balancemoneyfor = SUM(CASE fadc WHEN 1 THEN lendpricefor ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanpricefor ELSE 0 END) 
	FROM #tmpBill

	UPDATE #tmpBill 
	SET lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
		lendpricefor = (CASE WHEN fadc = 1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor
							 WHEN fadc = 1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN -@balancemoney / T3.rate
												WHEN 1 THEN -@balancemoney * T3.rate
											END
							 ELSE 0 END ),
		loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
		loanpricefor = (CASE WHEN fadc = -1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor 
							 WHEN fadc = -1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN @balancemoney / T3.rate
												WHEN 1 THEN @balancemoney * T3.rate
											END
									ELSE 0 END )
	FROM #tmpBill T1
	INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
	WHERE atdid IN (SELECT atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Express = 'balancemoney' AND Atid = @atid)
END
ELSE
BEGIN
	DECLARE BalanceCur CURSOR FOR
	SELECT billnumberid FROM #TmpBillInfo
		OPEN BalanceCur
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @balancemoney = 0
		SELECT	@balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
				,@balancemoneyfor = SUM(CASE fadc WHEN 1 THEN lendpricefor ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanpricefor ELSE 0 END) 
		FROM #tmpBill
		WHERE billid = @BalanceBillId
		
		
		UPDATE #tmpBill 
		SET #tmpBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
			#tmpBill.lendpricefor = (CASE WHEN fadc = 1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor 
										  WHEN fadc = 1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN -@balancemoney / T3.rate
												WHEN 1 THEN -@balancemoney * T3.rate
											END
									ELSE 0 END ),
			#tmpBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
			#tmpBill.loanpricefor = (CASE WHEN fadc = -1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor
										  WHEN fadc = -1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN @balancemoney / T3.rate
												WHEN 1 THEN @balancemoney * T3.rate
											END
									ELSE 0 END )
		FROM #tmpBill T1
			INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
			INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
		WHERE billid = @BalanceBillId
			
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	END
	CLOSE BalanceCur
	DEALLOCATE BalanceCur
END

--去除金额为0的
DELETE FROM #tmpBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 	

--调整明细异常币种	
UPDATE #tmpbill SET f_exchidfor =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
	cid =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
	rate = CASE WHEN T2.Cid = 0 THEN T1.rate ELSE T3.rate END,
	lendpricefor =  CASE WHEN T2.Cid = 0 OR  (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid)  THEN T1.lendpricefor ELSE 
						CASE T3.BasisType WHEN 0 THEN T1.lendprice / T3.rate
										ELSE  T1.lendprice * T3.rate END
					END,
	loanpricefor =  CASE WHEN T2.Cid = 0 OR (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid) THEN T1.loanpricefor ELSE 
						CASE T3.BasisType WHEN 0 THEN T1.loanprice / T3.rate
										ELSE  T1.loanprice * T3.rate END
					END
FROM #tmpbill T1 
	INNER JOIN dbo.Ac_Account T2 ON T1.stypeid = T2.StypeId AND T1.atypeid = T2.typeid
	LEFT JOIN dbo.Ac_Currency T3 ON T2.Cid = T3.CId


--凭证明细预处理后表（用于插入）
CREATE TABLE #tmpRow
(
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rowno			INT		IDENTITY(1,1),
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		countIndex		INT,
		addebtid		INT,
		credenceId		INT,
		billindexid		INT
)
--处理分录号
INSERT INTO #tmpRow(
	billnumberid	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	lendprice		,
	loanprice		,
	lendpricefor	,
	loanpricefor	,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid			,
	countIndex		,
	addebtid		,
	credenceId		,
	billindexid
)
SELECT billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		lendprice,
		loanrice,
		lendpricefor,
		loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		atdid,
		countindex,
		addebtid,
		credenceId,
		billid
FROM
(
SELECT	billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		SUM(lendprice) AS lendprice,
		SUM(loanprice) AS loanrice,
		SUM(lendpricefor) AS lendpricefor,
		SUM(loanpricefor) AS loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		min(atdid) atdid,
		@Index AS countindex,
		addebtid,
		credenceId,
		MIN(rowno) AS initrowno,
		billid
FROM	#tmpBill
GROUP BY billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		--atdid,
		addebtid,
		credenceId,
		billid
) AS TT ORDER BY initrowno


--更新业务凭证对照表行号
UPDATE #tmpAccountCredence SET rowno = b.rowno FROM #tmpAccountCredence a INNER JOIN #tmpRow b ON a.id = b.credenceId AND B.billindexid = A.billnumberid


--数据置空
TRUNCATE TABLE #tmpBillMoney
TRUNCATE TABLE #tmpBillMoneyDetail
TRUNCATE TABLE #tmpBill

DROP TABLE #tmpExpress,#tmpBillIndexAtypeid,#tmpBillMulAccount,#tmpBillIndexAtypeid1,#tmpAccount,
		#tmpMoneyBill,#tmpJDItemDetail,#tmpItemDetail,#tmpfexpress,#tmpfbalance,#TmpFixed,#tmpFBalanceDetails
	
-----------原循环结尾处



--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	fieldname			VARCHAR(100),
	BillIndexNumberId	INT				--单据ID
)
--获取明细对应辅助核算
SET @sql = 'INSERT INTO #TmpAssit '
SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'+
			'( '+CAST(T2.FieldValue AS VARCHAR(20))+') AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,
			(SELECT name FROM syscolumns WHERE id = object_id(''billindex'') AND name = '''+
			cast(case T2.FieldValue 
					WHEN 'instypeid' THEN 'stypeid'
					WHEN 'outstypeid' THEN 'stypeid'
				ELSE FieldValue END AS varchar(50))+''')as filedname ,BILLNUMBERID AS BillIndexNumberId 
			FROM #TmpBillInfo 
			
			UNION ALL '
FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
	LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
WHERE T1.Atid = @Atid
IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
BEGIN
	SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
	EXEC(@sql)
END

--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	billindexid	INT,
	typeid	VARCHAR(50)
)
INSERT INTO #TmpDetailsAssit
SELECT DISTINCT T1.atdid,T1.rowno,T2.ascids,T1.billindexid,T3.typeid
FROM #tmprow T1
LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
LEFT JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId
WHERE ISNULL(T3.ascids,'') <> ''


--调整应收应付辅助核算
IF @BillType IN (116,115,128,129)
BEGIN
	CREATE TABLE #tmpaddebtForDetail
	(
		BtypeId	VARCHAR(50),
		Total	 NUMERIC(24, 10) ,
		Item	VARCHAR(100),
		id		INT,
		rowno	INT,
		billindex	INT
	)
	--更新应收应付对照表行号
	INSERT INTO #tmpaddebtForDetail
	SELECT 	b.BtypeId,b.Total,b.Item,b.id,a.rowno,A.billindexid
	FROM #tmpRow a
	INNER JOIN #tmpaddebt b ON a.addebtid = b.id AND B.billnumberid = A.billindexid

	UPDATE #TmpDetailsAssit SET typeid = T2.btypeid 
	FROM #TmpDetailsAssit T1 
	LEFT JOIN #tmpaddebtForDetail T2 ON T1.rowno = T2.rowno AND T1.billindexid = T2.billindex
	WHERE T1.ascids = 4
	
	DROP TABLE #tmpaddebtForDetail
END

DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #tmprow 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #tmprow SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END


--排除数据全为0的单据编号
SELECT DISTINCT BillIndexId
INTO #TmpBillNumberId
FROM #tmprow WHERE lendprice <> 0 OR loanprice <> 0


--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT T.*
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	SUM(lendprice)	AS Lend,
	SUM(loanprice)	AS Loan,
	SUM(lendpricefor) AS LendFor,
	SUM(loanpricefor) AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmprow
GROUP BY BillNumberId,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.isCost,AT.OrderID,T.fadc,AC.UserCode



--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT atdid,rowno,ascids,typeid
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit


INSERT INTO #TmpDetailsAssit (atdid, rowno, ascids, typeid )
SELECT DISTINCT 0,T1.rowno,T2.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''



--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END



DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)


--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
         CASE 
			WHEN LTRIM(RTRIM(explain))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(explain)),1) = ';' THEN LEFT(LTRIM(RTRIM(explain)),LEN(LTRIM(RTRIM(explain)))-1)
			ELSE LTRIM(RTRIM(explain))
		  END ,
          stypeid ,
          ISNULL(atypeid,'') ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill

--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails 
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #tmpAssit,#tmpBill,#tmpRow
DROP TABLE #tmpBillMoneyDetail
DROP TABLE #TmpBillNumberId,#TmpBillInfo,#BillNumberId
	
RETURN @voucherid



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：lhl
	日期：2016-11-09
	描述：优惠券出入库单据凭证生成
*/
CREATE PROCEDURE GP_BatchCreateVoucher_CouponBill
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期,
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0			,
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0,				-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@IfCommission	INT = 3,				-- 3.优惠券
	@GoodsBillIds	VARCHAR(MAX)  OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

DECLARE @AutoFlag INT --即时生成凭证异常
SET @AutoFlag = 0

--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID			INT,				--收付款项目
	ATypeID1		VARCHAR(50),
	Cid				INT,				--币种
	Rate			NUMERIC(24, 10),	--汇率
	RateType		INT,				--汇率计算方式
	RedWord			INT,				--红冲标识
	OutSTypeId		VARCHAR(50),		--出库分支机构
	InSTypeId		VARCHAR(50),		--入库分支机构
	AtId			INT					--模板号
)

INSERT INTO #TmpBillInfo
( 
	BillNumberId,
	StypeId,
	VerifyStypeid,
	DTypeId,
	BTypeId,
	ETypeId,
	DealBTypeId ,
	ATypeID,
	ATypeID1,
	Cid,
	Rate,
	RateType,
	RedWord,
	OutSTypeId,
	InSTypeId,
	AtId
)
SELECT 
	T1.BillNumberId,
	T1.Stypeid,
	T2.VerifyID,
	T1.DTypeId,
	T1.btypeid,
	T1.etypeid,
	T1.DealBTypeID,
	T1.ATypeID,
	T1.ATypeID1,
	T1.CID,
	T1.Rate,
	T3.BasisType,
	T1.RedWord,
	ISNULL(T4.STypeID,''),
	ISNULL(T5.STypeID,''),
	@AtId
FROM dbo.Coupon_BillIndex T1
INNER JOIN #BillNumberId B ON B.a= T1.BillNumberId AND T1.FromType<>3--不包括报损报溢单据
INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
LEFT JOIN dbo.Stock T4 ON T4.typeId=T1.OutKTypeId
LEFT JOIN dbo.Stock T5 ON T5.typeId=T1.InKTypeId

--往来科目模板行号
DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

--------------------------
--将模板明细处理到临时表中,进行读取字段生成摘要
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT=0,@MinDid INT=0,@SqlSummary VARCHAR(MAX)='',@MaxNumber INT=0,@MinNumber INT=0,@Index INT=0,@Str VARCHAR(MAX)=''

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作

SELECT @MinNumber = MIN(a) FROM #BillNumberId --- dbo.f_split(@billnumberid,',')
SELECT @MaxNumber = MAX(a) FROM #BillNumberId ---dbo.f_split(@Billnumberid,',')

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

DECLARE @flag INT--是否需要用户补足
SET @flag = 0

WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN	
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '
	
		SELECT @SqlSummary +=  'SELECT '+
				CASE Filed
					WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
					ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
				END
			+'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'Coupon_BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Coupon_BillIndex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Coupon_BillIndex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Coupon_BillIndex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
		INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		SELECT @str += summarystr + '  '
		FROM #TempStr
		
		IF @str <> ''
			SET @str += ';'
		TRUNCATE TABLE #TempStr
		
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END

--统计单据所有金额字段
CREATE TABLE #tmpBillMoney
(
	TotalMoney			NUMERIC(24, 10) DEFAULT 0,--总金额
	TotalMoneyFor		NUMERIC(24, 10) DEFAULT 0,--原币总金额
	
	TotalInMoney		NUMERIC(24, 10) DEFAULT 0,--收付款金额(实付金额)
	TotalInMoneyFor		NUMERIC(24, 10) DEFAULT 0,--原币收付款金额(实付金额)
	
	PreferenceMoney		NUMERIC(24, 10) DEFAULT 0,--抹零金额
	PreferenceMoneyFor	NUMERIC(24, 10) DEFAULT 0,--抹零金额
	
	CostTotal			NUMERIC(24, 10) DEFAULT 0,--入库成本金额
	CostTotalFor		NUMERIC(24, 10) DEFAULT 0,--原币入库成本金额
	
	D_CouponValue		NUMERIC(24, 10) DEFAULT 0,--代金券面值
	D_CouponValueFor	NUMERIC(24, 10) DEFAULT 0,--原币代金券面值
	
	D_TotalMoney		NUMERIC(24, 10) DEFAULT 0,--代金券金额
	D_TotalMoneyFor		NUMERIC(24, 10) DEFAULT 0,--原币代金券金额
	
	Z_TotalMoney		NUMERIC(24, 10) DEFAULT 0,--折扣券金额
	Z_TotalMoneyFor		NUMERIC(24, 10) DEFAULT 0,--原币折扣券金额
	
	D_OutTotal			NUMERIC(24, 10) DEFAULT 0,--兑换券出库金额
	D_OutTotalFor		NUMERIC(24, 10) DEFAULT 0,--原币兑换券出库金额
	
	D_BackTotal			NUMERIC(24, 10) DEFAULT 0,--兑换券退货金额
	D_BackTotalFor		NUMERIC(24, 10) DEFAULT 0,--原币兑换券退货金额


	BalanceMoney		NUMERIC(24, 10) DEFAULT 0,--平衡数
	BalanceMoneyFor		NUMERIC(24, 10) DEFAULT 0,--平衡数
	
	BillNumberID		INT,--单据ID
	RowIndex			INT				DEFAULT 1,
	Rate				NUMERIC(24, 10) DEFAULT 1,--汇率
	RateType			INT				DEFAULT 0,--换算方法
)	
	
--Awu:调整先不合并
INSERT INTO #tmpBillMoney
(
	TotalMoney,
	TotalMoneyFor,
	TotalInMoney,
	TotalInMoneyFor,
	PreferenceMoney,
	PreferenceMoneyFor,
	
	BillNumberID,
	Rate,
	RateType
)
SELECT	
	ISNULL(CASE WHEN a.RedWord = 2 THEN -totalmoney ELSE totalmoney END,0) AS TotalMoney,
	ISNULL(CASE WHEN a.RedWord = 2 THEN -NTotalMoney ELSE NTotalMoney END,0) AS TotalMoneyFor,
	ISNULL(CASE WHEN a.RedWord = 2 THEN -totalinmoney ELSE totalinmoney END,0) AS TotalInMoney,
	ISNULL(CASE WHEN a.RedWord = 2 THEN -NTotalInMoney ELSE NTotalInMoney END,0) AS TotalInMoneyFor,
	ISNULL(CASE WHEN a.RedWord = 2 THEN -preferencemoney ELSE preferencemoney END,0) AS PreferenceMoney,
	ISNULL(CASE WHEN a.RedWord = 2 THEN -NPreferenceMoney ELSE NPreferenceMoney END,0) AS PreferenceMoneyFor,
	a.BillNumberId,
	BB.Rate,
	BB.RateType
FROM dbo.Coupon_BillIndex a
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
INNER JOIN dbo.SType S ON a.Stypeid = S.TypeId

--入库成本金额
IF(@BillType=423)
BEGIN
	UPDATE #tmpBillMoney
	SET 
		CostTotal=TT.CostTotal,
		CostTotalFor=TT.NCostTotal
	FROM #tmpBillMoney T1
	INNER JOIN(
		SELECT 
			SUM(CASE WHEN b.RedWord=2 THEN -I.CostTotal ELSE I.CostTotal END) CostTotal,
			SUM(CASE WHEN b.RedWord=2 THEN -I.NCostTotal ELSE I.NCostTotal END) NCostTotal,
			BB.BillNumberId
		FROM #TmpBillInfo BB
		INNER JOIN Coupon_InBill I ON I.BillNumberId = BB.BillNumberId
		INNER JOIN Coupon_BillIndex B ON B.BillNumberId=BB.BillNumberId AND B.IfCheck='t'
		GROUP BY 
			BB.BillNumberId
	) TT ON T1.billnumberid = TT.billnumberid
END

--代金券面值	
UPDATE #tmpBillMoney
SET 
	D_CouponValue=TT.CouponValue
FROM #tmpBillMoney T1
INNER JOIN(
	SELECT 
		SUM(CASE WHEN b.RedWord=2 THEN -T.CouponValue ELSE T.CouponValue END) CouponValue,
		BB.BillNumberId
	FROM #TmpBillInfo BB
	INNER JOIN Coupon_CodeInOut U ON U.BillNumberId = BB.BillNumberId
	INNER JOIN coupon_TypeInfo T ON T.CouponId=U.CouponId AND T.CouponType=1--代金券
	INNER JOIN Coupon_BillIndex B ON B.BillNumberId=BB.BillNumberId
	GROUP BY 
		BB.BillNumberId
) TT ON T1.billnumberid = TT.billnumberid
	
	
--代金券金额
--折扣券金额
IF(@BillType=424)--出库单
BEGIN
	UPDATE #tmpBillMoney
	SET 
		D_TotalMoney=TT.D_TotalMoney,
		Z_TotalMoney=TT.Z_TotalMoney,
		D_OutTotal=TT.D_OutTotal--兑换券出库金额
	FROM #tmpBillMoney T1
	INNER JOIN(
		SELECT 
			SUM(CASE WHEN T.CouponType=1 THEN CASE WHEN b.RedWord=2 THEN -U.Total ELSE U.Total END
					 ELSE 0 
				END ) D_TotalMoney,
			SUM(CASE WHEN T.CouponType=2 THEN CASE WHEN b.RedWord=2 THEN -U.Total ELSE U.Total END
					 ELSE 0 
				END ) Z_TotalMoney,
			SUM(CASE WHEN T.CouponType=3 THEN CASE WHEN b.RedWord=2 THEN -U.Total ELSE U.Total END
					 ELSE 0 
				END ) D_OutTotal,
			BB.BillNumberId
		FROM #TmpBillInfo BB
		INNER JOIN Coupon_CodeInOut U ON U.BillNumberId = BB.BillNumberId
		INNER JOIN coupon_TypeInfo T ON T.CouponId=U.CouponId
		INNER JOIN Coupon_BillIndex B ON B.BillNumberId=BB.BillNumberId
		GROUP BY 
			BB.BillNumberId
	) TT ON T1.billnumberid = TT.billnumberid
END
ELSE IF(@BillType=426)--退货单 
BEGIN
	UPDATE #tmpBillMoney
	SET 
		D_TotalMoney=TT.D_TotalMoney,--代金券金额
		Z_TotalMoney=TT.Z_TotalMoney,--折扣券金额
		D_BackTotal=TT.D_BackTotal,--兑换券退货金额
		D_OutTotal=TT.D_OutTotal--兑换券出库金额
	FROM #tmpBillMoney T1
	INNER JOIN(
		SELECT 
			SUM(CASE WHEN T.CouponType=1 THEN CASE WHEN b.RedWord=2 THEN -IOut.Total ELSE IOut.Total END
					 ELSE 0 
				END ) D_TotalMoney,
			SUM(CASE WHEN T.CouponType=2 THEN CASE WHEN b.RedWord=2 THEN -IOut.Total ELSE IOut.Total END
					 ELSE 0 
				END ) Z_TotalMoney,
			SUM(CASE WHEN T.CouponType=3 THEN CASE WHEN b.RedWord=2 THEN -IOut.Total ELSE IOut.Total END
					 ELSE 0 
				END ) D_BackTotal,
			SUM(CASE WHEN T.CouponType=3 THEN CASE WHEN b.RedWord=2 THEN -I.OutPrice ELSE I.OutPrice END
					 ELSE 0 
				END ) D_OutTotal,
			BB.BillNumberId
		FROM #TmpBillInfo BB
		INNER JOIN Coupon_CodeInOut IOut ON IOut.BillNumberId=BB.BillNumberId
		INNER JOIN Coupon_CodeInfo I ON I.CouponCode=IOut.CouponCode
		INNER JOIN coupon_TypeInfo T ON T.CouponId=I.CouponId
		INNER JOIN Coupon_BillIndex B ON B.BillNumberId=BB.BillNumberId
		GROUP BY BB.BillNumberId
	) TT ON T1.billnumberid = TT.billnumberid
END	

--凭证明细临时表
CREATE TABLE #tmpBill
(
	billnumberid	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		NUMERIC(24, 10) ,
	loanprice		NUMERIC(24, 10) ,
	lendpricefor	NUMERIC(24, 10) ,
	loanpricefor	NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT		IDENTITY(1,1),
	rate			NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT,
	addebtid		INT,
	credenceId		INT,
	billid			INT
)

--凭证明细预处理后表（用于插入）
CREATE TABLE #tmpRow
(
	billnumberid	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		NUMERIC(24, 10) ,
	loanprice		NUMERIC(24, 10) ,
	lendpricefor	NUMERIC(24, 10) ,
	loanpricefor	NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT		IDENTITY(1,1),
	rate			NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT,
	countIndex		INT,
	addebtid		INT,
	credenceId		INT,
	billindexid		INT
)

--插入凭证明细ID，用于生成辅助核算
CREATE TABLE #tmpBillID
(
	rowno	INT ,
	id		INT,
	atypeid	VARCHAR(50)
)

--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	fieldname			VARCHAR(100),
	BillIndexNumberId	INT				--单据ID
)

DECLARE 
		@BillCount	INT,--单据总数
		@detailsCount INT
		,@BillCid	INT
		,@IsUseBillMoneyDate INT
		,@UseBillMoneyDate_BillTypes VARCHAR(200)
		,@sql VARCHAR(MAX)


SELECT TOP 1 @BillCid = Cid FROM #TmpBillInfo
SELECT @UseBillMoneyDate_BillTypes=SubValue  FROM sysdata WHERE SubName = 'usebillmoneydate'

SET @IsUseBillMoneyDate = 0
IF EXISTS (SELECT TOP 1 1 FROM F_Split(@UseBillMoneyDate_BillTypes,',') WHERE a = @BillType)
	SET @IsUseBillMoneyDate = 1


DECLARE @sql_table NVARCHAR(100),@sql_search NVARCHAR(MAX)
SET @sql_table = ''
SET @sql_search = ''

--科目来源AcFrom
--1 手工选择
--2 单据上收付款项目对应科目
--3 单据上往来科目
--4 单据上项目对应科目
--5 单据上项目对应固定资产科目
--6 单据上借方项目对应科目
--7 单据上贷方项目对应科目
--8 单据上业务类型对应科目
CREATE TABLE #tmpExpress
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) ,
	lendloanfor	 NUMERIC(24, 10) ,
	rate		 NUMERIC(24, 10) ,
	ratetype	INT,
	billnumberid	INT,
	iscost		INT DEFAULT 0
)

CREATE TABLE #tmpFExpress
(
	atdit		INT,
	nid			INT,
	lendloan	 NUMERIC(24, 10) ,
	rate		 NUMERIC(24, 10) ,
	ratetype	INT,
	rowindex	INT IDENTITY(1,1)
)

--读取模板要求的金额（非项目类）
SET @sql = 'insert into #tmpExpress select distinct * from('	
SELECT @sql += 
' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,
			('+ T2.Express +') as lendloan,'
			+CASE WHEN @IsUseBillMoneyDate = 1 THEN '('+dbo.F_ChangeToOriginalCurrency(T2.Express) +')' ELSE '0' END +' as lendloanfor,
			rate,
			ratetype,
			billnumberid,'
			+CASE WHEN dbo.F_ChangeToOriginalCurrency(T2.Express) = '0' THEN '1' ELSE '0' END+' as iscost
from #tmpBillMoney a
union all '
FROM Ac_Auditing_Template_Detail T1
INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
WHERE Atid = @Atid 

IF LEN(@sql) > LEN('insert into #tmpExpress select distinct * from(')
BEGIN
	SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
	SET @sql += ')T'
	EXEC(@sql)
END

--取分支机构关联科目
SELECT	A.*,
		CASE WHEN a.Cid = -1 THEN @f_exchid
			 ELSE a.Cid
		END AS rcid,
		CAST(ISNULL(ASS.Ascids,'0') AS VARCHAR)+',' AS Item
INTO #tmpAccount
FROM dbo.Ac_Account a
left join Ac_Account_Assist_CheckItems ass on ass.STypeId = a.StypeId and ass.ATypeId = a.TypeId and ass.Ascids = 4
WHERE a.StypeId = @Verifyid

DECLARE @BillTypestr VARCHAR(50)
SET @BillTypestr = CAST(@BillType AS VARCHAR(50))

CREATE TABLE #tmpBillMulAccount
(
	Atypeid		VARCHAR(50),
	Usercode	VARCHAR(200),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Cid			INT,
	Atdid		INT,
	Total		 NUMERIC(24, 10) ,
	Totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)
CREATE TABLE #tmpBillIndexAtypeid
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atdid		INT,
	total		 NUMERIC(24, 10) ,
	totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)

--获取单据上的收付款科目及金额
INSERT INTO #tmpBillIndexAtypeid
SELECT	c.ATypeID,
		b.UserCode,
		b.FullName,
		NULL,
		NULL,
		D.AtdId,
		CASE WHEN BB.RedWord = 2 THEN -a.Total ELSE a.Total END AS total,
		CASE WHEN BB.RedWord = 2 THEN -a.NTotalMoney ELSE a.NTotalMoney END AS totalfor,
		BB.BillNumberId  
FROM	#TmpBillInfo BB
INNER JOIN #TmpVoucherDetails D ON D.Atid = BB.AtId
INNER JOIN dbo.BillMulAccount a ON a.BillNumberId = BB.BillNumberId AND A.BillType = @BillType
INNER JOIN dbo.Ac_Items b ON a.ATypeID = b.nId
INNER JOIN dbo.Ac_Items_Detail c ON b.nId = c.nId AND c.StypeId = BB.StypeId
WHERE D.AcFrom = 2

INSERT INTO #tmpBillMulAccount
SELECT	ATypeId,b.UserCode,b.FullName,b.Fdc,b.cid,atdid,SUM(Total) AS total,SUM(totalfor) as totalfor,a.billnumberid
FROM	#tmpBillIndexAtypeid a
LEFT JOIN Ac_Account b ON a.atypeid = b.typeid and b.stypeid = @verifyid
GROUP BY atypeid,b.usercode,b.fullname,b.fdc,b.cid,atdid,a.billnumberid

--单据上的往来科目
CREATE TABLE #tmpBillIndexAtypeid1
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atid		INT,
	atdid		INT,
	item		VARCHAR(500),
	billnumberid	INT
)
	
INSERT INTO #tmpBillIndexAtypeid1
SELECT	b.typeId,
		b.UserCode,
		b.FullName,
		Fdc,
		CASE b.cid
			WHEN -1 THEN @f_exchid
			ELSE b.Cid
		END,
		@Atid AS atid,
		@Atdid as atdid,
		SUBSTRING(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1),
				LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))-1,
				LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))) AS Item,
		BB.BillNumberId
FROM	#TmpBillInfo bb
INNER JOIN dbo.Ac_Account b ON B.TypeId = BB.ATypeID1 AND B.StypeId = BB.VerifyStypeid

----不存在的单据无科目，补分支机构默认值
IF EXISTS(SELECT TOP 1 1 FROM #TmpBillInfo WHERE billnumberid NOT IN(SELECT BillNumberId FROM #tmpBillIndexAtypeid1))
BEGIN
	DECLARE @TempBillNumberID TABLE(BillNumberId NUMERIC(10,0))
	INSERT INTO @TempBillNumberID(BillNumberId)
	SELECT BillNumberId FROM #TmpBillInfo WHERE billnumberid NOT IN(SELECT BillNumberId FROM #tmpBillIndexAtypeid1)
	
	INSERT INTO #tmpBillIndexAtypeid1
			( atypeid ,
			  usercode ,
			  fullname ,
			  fdc ,
			  cid ,
			  atid,
			  atdid
			  ,billnumberid
			)
	SELECT  
		'' , -- atypeid - varchar(50)
		'' , -- usercode - varchar(50)
		'' , -- fullname - varchar(200)
		0 , -- fdc - int
		0 , -- cid - int
		0 , -- atid - int
		@Atdid,
		BB.BillNumberId
	FROM #TmpBillInfo BB 
	INNER JOIN @TempBillNumberID T ON T.BillNumberId=BB.BillNumberId
END
	
--生成凭证明细数据(科目来源1~3，8)--
INSERT INTO #tmpBill
		( billnumberid ,
		  explain ,
		  atypeid ,
		  atypeid2 ,
		  Fdc ,
		  f_exchid ,
		  f_exchidfor ,
		  lendprice ,
		  loanprice ,
		  lendpricefor ,
		  loanpricefor ,
		  FCashFlowItem ,
		  ascids ,
		  FSettleNo ,
		  FSettleTypeID ,
		  comment ,
		  cid ,
		  rate ,
		  fadc ,
		  stypeid ,
		  fyear ,
		  fperiod,
		  atdid,
		  addebtid,
		  billid
		)
SELECT	DISTINCT @VoucherId AS billnumberid,
		Summary AS explain,
		CASE AcFrom 
			WHEN 1 THEN b.typeid
			WHEN 2 THEN c.atypeid
			WHEN 3 THEN e.atypeid
			WHEN 4 THEN b.TypeId
		END AS atypeid,
		'' AS atypeid2,
		CASE AcFrom 
			WHEN 1 THEN b.Fdc
			WHEN 2 THEN c.Fdc
			WHEN 3 THEN e.Fdc
			WHEN 4 THEN b.Fdc
		END AS Fdc,
		@f_exchid AS f_exchid,
		BB.Cid AS f_exchidfor,
		CASE a.Fdc 
			WHEN 1 THEN (CASE WHEN AcFrom = 2 THEN isnull(c.total,0) 
							  ELSE isnull(d.lendloan,0) END )
			ELSE 0 
		END AS lendprice,
		CASE a.Fdc 
			WHEN -1 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
							   ELSE isnull(d.lendloan,0) END )
			ELSE 0 
		END AS loanprice,
		CASE WHEN a.Fdc = 1 AND @IsUseBillMoneyDate = 1 AND d.iscost = 0	THEN d.lendloanfor
			 WHEN a.Fdc = 1 THEN 
					(CASE ISNULL(d.ratetype,0) 
						WHEN 0 THEN  (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
										   ELSE isnull(d.lendloan,0) END ) / ISNULL(d.rate,1)
						WHEN 1 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) * ISNULL(d.rate,1)
					END)
			ELSE 0 
		END AS lendpricefor,
		CASE WHEN a.Fdc = -1  AND @IsUseBillMoneyDate = 1 AND d.iscost = 0	THEN d.lendloanfor
			 WHEN a.Fdc = -1 THEN
					(CASE ISNULL(d.ratetype,0)                                                       
						WHEN 0 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) / isnull(d.rate,1)
						WHEN 1 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) * isnull(d.rate,1)
					END)
			ELSE 0 
		END AS loanpricefor,
		NULL AS FCashFlowItem,
		'' AS ascids,
		NULL AS FSettleNo,
		0 AS FSettleTypeID,
		'' AS comment,
		BB.Cid,
		d.rate,
		a.Fdc AS fadc,
		@verifyid AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod,
		a.AtdId,
		0,
		D.billnumberid
FROM	#TmpVoucherDetails a
INNER JOIN #tmpExpress d ON a.AtdId = d.atdit
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = D.billnumberid
LEFT JOIN #tmpAccount b ON a.ATypeId = b.TypeId
LEFT JOIN #tmpBillMulAccount c ON a.Atdid = c.Atdid AND C.billnumberid = D.billnumberid
LEFT JOIN #tmpBillIndexAtypeid1 e ON a.Atdid = e.atdid AND E.billnumberid = D.billnumberid
ORDER BY a.AtdId

--往来科目为空
IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBillIndexAtypeid1 WHERE ISNULL(atypeid,'') <> '')
BEGIN
	IF EXISTS(	SELECT TOP 1 1
					FROM #TmpVoucherDetails T1
						LEFT JOIN #TmpExpress T2 ON T1.AtdId = T2.Atdit
						LEFT JOIN #tmpBillIndexAtypeid1 T3 ON T2.Atdit =T3.Atdid
						LEFT JOIN dbo.Ac_Account T4 ON T3.Atypeid = T4.TypeId AND T4.StypeId = @verifyid
						LEFT JOIN dbo.Ac_Currency T5 ON T4.Cid = T5.CId
					WHERE T1.Atid = @Atid AND T1.AcFrom = 3 AND T2.Lendloan <> 0)
	SET @Flag = -11
END
		
--根据配置，对成本明细做删除
--IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1)
--BEGIN
--	DELETE FROM #TmpBill WHERE atdid IN (SELECT AtdId FROM #TmpVoucherDetails WHERE isCost = 1)
--END

--Awu:调整平衡数
DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) ,@balancemoneyfor  NUMERIC(24, 10) 

DECLARE BalanceCur CURSOR FOR
SELECT billnumberid FROM #TmpBillInfo

OPEN BalanceCur
FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @balancemoney = 0
	SELECT	@balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
			,@balancemoneyfor = SUM(CASE fadc WHEN 1 THEN lendpricefor ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanpricefor ELSE 0 END) 
	FROM #tmpBill
	WHERE billid = @BalanceBillId
	
	
	UPDATE #tmpBill 
	SET #tmpBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
		#tmpBill.lendpricefor = (CASE WHEN fadc = 1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor 
									  WHEN fadc = 1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN -@balancemoney / T3.rate
											WHEN 1 THEN -@balancemoney * T3.rate
										END
								ELSE 0 END ),
		#tmpBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
		#tmpBill.loanpricefor = (CASE WHEN fadc = -1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor
									  WHEN fadc = -1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN @balancemoney / T3.rate
											WHEN 1 THEN @balancemoney * T3.rate
										END
								ELSE 0 END )
	FROM #tmpBill T1
		INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
		INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
	WHERE billid = @BalanceBillId
		
	FETCH NEXT FROM BalanceCur INTO @BalanceBillId
END
CLOSE BalanceCur
DEALLOCATE BalanceCur

--去除金额为0的
DELETE FROM #tmpBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 	

--调整明细异常币种	
UPDATE #tmpbill SET f_exchidfor =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
	cid =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
	rate = CASE WHEN T2.Cid = 0 THEN T1.rate ELSE T3.rate END,
	lendpricefor =  CASE WHEN T2.Cid = 0 OR  (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid)  THEN T1.lendpricefor ELSE 
						CASE T3.BasisType WHEN 0 THEN T1.lendprice / T3.rate
										ELSE  T1.lendprice * T3.rate END
					END,
	loanpricefor =  CASE WHEN T2.Cid = 0 OR (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid) THEN T1.loanpricefor ELSE 
						CASE T3.BasisType WHEN 0 THEN T1.loanprice / T3.rate
										ELSE  T1.loanprice * T3.rate END
					END
FROM #tmpbill T1 
	INNER JOIN dbo.Ac_Account T2 ON T1.stypeid = T2.StypeId AND T1.atypeid = T2.typeid
	LEFT JOIN dbo.Ac_Currency T3 ON T2.Cid = T3.CId

--处理分录号
INSERT INTO #tmpRow(
	billnumberid	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	lendprice		,
	loanprice		,
	lendpricefor	,
	loanpricefor	,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid			,
	countIndex		,
	addebtid		,
	credenceId		,
	billindexid
)
SELECT billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		lendprice,
		loanrice,
		lendpricefor,
		loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		atdid,
		countindex,
		addebtid,
		credenceId,
		billid
FROM
(
SELECT	billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		SUM(lendprice) AS lendprice,
		SUM(loanprice) AS loanrice,
		SUM(lendpricefor) AS lendpricefor,
		SUM(loanpricefor) AS loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		MIN(atdid) atdid,
		@Index AS countindex,
		addebtid,
		credenceId,
		MIN(rowno) AS initrowno,
		billid
FROM	#tmpBill
GROUP BY billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		--atdid,
		addebtid,
		credenceId,
		billid
) AS TT ORDER BY initrowno

--获取明细对应辅助核算
SET @sql = 'INSERT INTO #TmpAssit '
SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'+
			'( '+CAST(T2.FieldValue AS VARCHAR(20))+') AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,
			(SELECT name FROM syscolumns WHERE id = object_id(''Coupon_BillIndex'') AND name = '''+
			cast(case T2.FieldValue 
					WHEN 'instypeid' THEN 'stypeid'
					WHEN 'outstypeid' THEN 'stypeid'
				ELSE FieldValue END AS varchar(50))+''')as filedname ,BILLNUMBERID AS BillIndexNumberId 
			FROM #TmpBillInfo 
			
			UNION ALL '
FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
	LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
WHERE T1.Atid = @Atid
IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
BEGIN
	SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
	EXEC(@sql)
END

DROP TABLE #tmpExpress,#tmpBillIndexAtypeid,#tmpBillMulAccount,#tmpBillIndexAtypeid1,#tmpAccount,#tmpfexpress
	
-----------原循环结尾处

--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	billindexid	INT,
	typeid	VARCHAR(50)
)
INSERT INTO #TmpDetailsAssit
SELECT DISTINCT T1.atdid,T1.rowno,T2.ascids,T1.billindexid,T3.typeid
FROM #tmprow T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId
WHERE ISNULL(T3.ascids,'') <> ''

DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #tmprow 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #tmprow SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END

--排除数据全为0的单据编号
SELECT DISTINCT BillIndexId
INTO #TmpBillNumberId
FROM #tmprow WHERE lendprice <> 0 OR loanprice <> 0

--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT T.*
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	SUM(lendprice)	AS Lend,
	SUM(loanprice)	AS Loan,
	SUM(lendpricefor) AS LendFor,
	SUM(loanpricefor) AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmprow
GROUP BY BillNumberId,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.isCost,AT.OrderID,T.fadc,AC.UserCode

--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT atdid,rowno,ascids,typeid
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit

INSERT INTO #TmpDetailsAssit (atdid, rowno, ascids, typeid )
SELECT DISTINCT 0,T1.rowno,T2.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''

--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END

DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)
--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
         CASE 
			WHEN LTRIM(RTRIM(explain))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(explain)),1) = ';' THEN LEFT(LTRIM(RTRIM(explain)),LEN(LTRIM(RTRIM(explain)))-1)
			ELSE LTRIM(RTRIM(explain))
		  END ,
          stypeid ,
          ISNULL(atypeid,'') ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill

--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails 
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #tmpBillID,#tmpAssit,#tmpBill,#tmpRow

DROP TABLE #TmpBillNumberId,#TmpBillInfo,#BillNumberId

IF @CreateType = 0
	RETURN 0
	
	
RETURN @VoucherId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：lhl
	日期：2016-11-09
	描述：门店配送单据凭证生成
*/
CREATE PROCEDURE GP_BatchCreateVoucher_DeliveryBill
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期,
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0			,
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0,				-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@IfCommission	INT = 3,				-- 3.优惠券
	@GoodsBillIds	VARCHAR(MAX)  OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

DECLARE @AutoFlag INT --即时生成凭证异常
SET @AutoFlag = 0

--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID			INT,				--收付款项目
	ATypeID1		VARCHAR(50),
	Cid				INT,				--币种
	Rate			NUMERIC(24, 10),	--汇率
	RateType		INT,				--汇率计算方式
	RedWord			INT,				--红冲标识
	OutSTypeId		VARCHAR(50),		--出库分支机构
	InSTypeId		VARCHAR(50),		--入库分支机构
	AtId			INT					--模板号
)

INSERT INTO #TmpBillInfo
			( BillNumberId ,
			  StypeId ,
			  VerifyStypeid ,
			  DTypeId ,
			  BTypeId ,
			  ETypeId,
			  DealBTypeId ,
			  ATypeID,
			  ATypeID1,
			  Cid ,
			  Rate ,
			  RateType,
			  RedWord,
			  outstypeid,
			  instypeid
			  ,AtId
			)
	SELECT  T1.BillNumberId,
			T1.Stypeid,
			T2.VerifyID,
			T1.DTypeId,
			'',
			T1.ApplyEtypeId,
			'',
			'',
			'',
			T1.CID,
			T3.Rate,
			T3.BasisType,
			T1.RedWord,
			ISNULL(T4.STypeID,''),
			ISNULL(T5.STypeID,'')
			,@AtId
	FROM dbo.PosAllotApplyBillIndex T1
	INNER JOIN #BillNumberId B ON B.a= T1.BillNumberId
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
	LEFT JOIN dbo.Stock T4 ON T1.ktypeid = T4.typeId
	LEFT JOIN dbo.Stock T5 ON T1.InKtypeId = T5.typeId

--往来科目模板行号
DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

--------------------------
--将模板明细处理到临时表中,进行读取字段生成摘要
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT=0,@MinDid INT=0,@SqlSummary VARCHAR(MAX)='',@MaxNumber INT=0,@MinNumber INT=0,@Index INT=0,@Str VARCHAR(MAX)=''

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作

SELECT @MinNumber = MIN(a) FROM #BillNumberId --- dbo.f_split(@billnumberid,',')
SELECT @MaxNumber = MAX(a) FROM #BillNumberId ---dbo.f_split(@Billnumberid,',')

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

DECLARE @flag INT--是否需要用户补足
SET @flag = 0

WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN	
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '
	
		SELECT @SqlSummary +=  'SELECT '+
				CASE Filed
					WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
					ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
				END
			+'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'PosAllotApplyBillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN PosAllotApplyBillIndex T2 ON T1.typeid = T2.stypeid '
				--WHEN 'Btype' THEN ' T1 INNER JOIN PosAllotApplyBillIndex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN PosAllotApplyBillIndex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
		INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		SELECT @str += summarystr + '  '
		FROM #TempStr
		
		IF @str <> ''
			SET @str += ';'
		TRUNCATE TABLE #TempStr
		
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END

--统计单据所有金额字段
CREATE TABLE #tmpBillMoney
(
	totalmoney				 NUMERIC(24, 10) 	DEFAULT 0,
	totalinmoney			 NUMERIC(24, 10) 	DEFAULT 0,
	preferencemoney			 NUMERIC(24, 10) 	DEFAULT 0,
	total					 NUMERIC(24, 10) 	DEFAULT 0,--折后金额
	taxTotal				 NUMERIC(24, 10) 	DEFAULT 0,
	costTotal				 NUMERIC(24, 10) 	DEFAULT 0,
	inCostTotal				 NUMERIC(24, 10) 	DEFAULT 0,--入库成本（换货、拆装、调拨）
	outCostTotal			 NUMERIC(24, 10) 	DEFAULT 0,--出库成本（换货、拆装、调拨）
	rate					 NUMERIC(24, 10) 	DEFAULT 1,
	ratetype				 INT				DEFAULT 0,
	instocktotal			 NUMERIC(24, 10) 	DEFAULT 0,--入库折后金额
	outstocktotal			 NUMERIC(24, 10) 	DEFAULT 0,--出库折后金额
	instocktaxtotal			 NUMERIC(24, 10) 	DEFAULT	0,--入库价税合计
	outstocktaxtotal		 NUMERIC(24, 10) 	DEFAULT 0,--出库价税合计
	GoodsCostTotal			 NUMERIC(24, 10) 	DEFAULT 0,--成本金额
	instockGoodsCostTotal	 NUMERIC(24, 10) 	DEFAULT 0,--入库成本金额
	outstockGoodsCostTotal	 NUMERIC(24, 10) 	DEFAULT 0,--出库成本金额
	beforetotal				 NUMERIC(24, 10) 	DEFAULT	0,--调前金额
	sharefee				 NUMERIC(24, 10) 	DEFAULT 0,--分摊金额
	j_total					 NUMERIC(24, 10) 	DEFAULT 0,
	d_total					 NUMERIC(24, 10) 	DEFAULT	0,
	balancemoney			 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	billnumberid			 INT,
	rowindex				 INT				DEFAULT 1,
	CommissionTotal			 NUMERIC(24, 10) 	DEFAULT 0,--提成单311提成金额
	
	
)	
	
--Awu:调整先不合并
INSERT INTO #tmpBillMoney
	(
		outCostTotal,
		billnumberid,
		rate,
		ratetype
	)
	SELECT CASE WHEN a.RedWord = 2 THEN -total ELSE total END AS total,
			a.BillNumberId,BB.Rate,BB.RateType
	FROM dbo.PosAllotApplyBillIndex a
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
	INNER JOIN dbo.SType S ON a.Stypeid = S.TypeId
IF @BillType=327
BEGIN
	UPDATE #tmpBillMoney
	SET 
		outCostTotal=TT.CostTotal
	FROM #tmpBillMoney T1
	INNER JOIN(
		SELECT 
			SUM(CASE WHEN b.RedWord=2 THEN 
					CASE WHEN b.costsale=1 THEN -i.total ELSE -(i.qty*I.GoodsCostprice) END
				ELSE 
					CASE WHEN b.costsale=1 THEN i.total ELSE (i.qty*i.GoodsCostprice) END
				END
			) CostTotal,
			BB.BillNumberId
		FROM #TmpBillInfo BB
		INNER JOIN DeliveryBill I ON I.BillNumberId = BB.BillNumberId
		INNER JOIN PosAllotApplyBillIndex B ON B.BillNumberId=BB.BillNumberId AND B.IfCheck='t'
		GROUP BY 
			BB.BillNumberId
	) TT ON T1.billnumberid = TT.billnumberid
END

IF @BillType=328
BEGIN
	UPDATE #tmpBillMoney
	SET 
		outCostTotal=TT.CostTotal
	FROM #tmpBillMoney T1
	INNER JOIN(
		SELECT 
			SUM(CASE WHEN b.RedWord=2 THEN -I.GoodsCostTotal ELSE I.GoodsCostTotal END) CostTotal,
			BB.BillNumberId
		FROM #TmpBillInfo BB
		INNER JOIN DeliveryBackBill I ON I.BillNumberId = BB.BillNumberId
		INNER JOIN PosAllotApplyBillIndex B ON B.BillNumberId=BB.BillNumberId AND B.IfCheck='t'
		GROUP BY 
			BB.BillNumberId
	) TT ON T1.billnumberid = TT.billnumberid
END

IF @BillType=329
BEGIN
	UPDATE #tmpBillMoney
	SET 
		total=TT.total,
		outCostTotal=TT.CostTotal
	FROM #tmpBillMoney T1
	INNER JOIN(
		SELECT 
			SUM(CASE WHEN b.RedWord=2 THEN 
					CASE WHEN b.costsale=1 THEN -(I.Qty*db.Price)ELSE -(I.Qty*db.Price) END
				ELSE 
					CASE WHEN b.costsale=1 THEN (I.Qty*db.Price) ELSE (I.Qty*db.Price) END  
				END ) total,
			SUM(CASE WHEN b.RedWord=2 THEN 
					CASE WHEN b.costsale=1 THEN -(I.GoodsCostPrice*I.Qty) ELSE -(db.GoodsCostPrice*I.Qty) END
				ELSE 
					CASE WHEN b.costsale=1 THEN (I.GoodsCostPrice*I.Qty) ELSE (db.GoodsCostPrice*I.Qty) END
				END) CostTotal,
			BB.BillNumberId
		FROM #TmpBillInfo BB
		INNER JOIN DeliveryCheckBill I ON I.BillNumberId = BB.BillNumberId
		INNER JOIN dbo.DeliveryBill db ON db.ID=I.DeliveryID
		INNER JOIN PosAllotApplyBillIndex B ON B.BillNumberId=BB.BillNumberId AND B.IfCheck='t'
		GROUP BY 
			BB.BillNumberId
	) TT ON T1.billnumberid = TT.billnumberid
END


--凭证明细临时表
CREATE TABLE #tmpBill
(
	billnumberid	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		NUMERIC(24, 10) ,
	loanprice		NUMERIC(24, 10) ,
	lendpricefor	NUMERIC(24, 10) ,
	loanpricefor	NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT		IDENTITY(1,1),
	rate			NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT,
	addebtid		INT,
	credenceId		INT,
	billid			INT
)

--凭证明细预处理后表（用于插入）
CREATE TABLE #tmpRow
(
	billnumberid	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		NUMERIC(24, 10) ,
	loanprice		NUMERIC(24, 10) ,
	lendpricefor	NUMERIC(24, 10) ,
	loanpricefor	NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT		IDENTITY(1,1),
	rate			NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT,
	countIndex		INT,
	addebtid		INT,
	credenceId		INT,
	billindexid		INT
)

--插入凭证明细ID，用于生成辅助核算
CREATE TABLE #tmpBillID
(
	rowno	INT ,
	id		INT,
	atypeid	VARCHAR(50)
)

--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	fieldname			VARCHAR(100),
	BillIndexNumberId	INT				--单据ID
)

DECLARE 
		@BillCount	INT,--单据总数
		@detailsCount INT
		,@BillCid	INT
		,@IsUseBillMoneyDate INT
		,@UseBillMoneyDate_BillTypes VARCHAR(200)
		,@sql VARCHAR(MAX)


SELECT TOP 1 @BillCid = Cid FROM #TmpBillInfo
SELECT @UseBillMoneyDate_BillTypes=SubValue  FROM sysdata WHERE SubName = 'usebillmoneydate'

SET @IsUseBillMoneyDate = 0
IF EXISTS (SELECT TOP 1 1 FROM F_Split(@UseBillMoneyDate_BillTypes,',') WHERE a = @BillType)
	SET @IsUseBillMoneyDate = 1


DECLARE @sql_table NVARCHAR(100),@sql_search NVARCHAR(MAX)
SET @sql_table = ''
SET @sql_search = ''

--科目来源AcFrom
--1 手工选择
--2 单据上收付款项目对应科目
--3 单据上往来科目
--4 单据上项目对应科目
--5 单据上项目对应固定资产科目
--6 单据上借方项目对应科目
--7 单据上贷方项目对应科目
--8 单据上业务类型对应科目
CREATE TABLE #tmpExpress
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) ,
	lendloanfor	 NUMERIC(24, 10) ,
	rate		 NUMERIC(24, 10) ,
	ratetype	INT,
	billnumberid	INT,
	iscost		INT DEFAULT 0
)

CREATE TABLE #tmpFExpress
(
	atdit		INT,
	nid			INT,
	lendloan	 NUMERIC(24, 10) ,
	rate		 NUMERIC(24, 10) ,
	ratetype	INT,
	rowindex	INT IDENTITY(1,1)
)

--读取模板要求的金额（非项目类）
SET @sql = 'insert into #tmpExpress select distinct * from('	
SELECT @sql += 
' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,
			('+ T2.Express +') as lendloan,'
			+CASE WHEN @IsUseBillMoneyDate = 1 THEN '('+dbo.F_ChangeToOriginalCurrency(T2.Express) +')' ELSE '0' END +' as lendloanfor,
			rate,
			ratetype,
			billnumberid,'
			+CASE WHEN dbo.F_ChangeToOriginalCurrency(T2.Express) = '0' THEN '1' ELSE '0' END+' as iscost
from #tmpBillMoney a
union all '
FROM Ac_Auditing_Template_Detail T1
INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
WHERE Atid = @Atid 

IF LEN(@sql) > LEN('insert into #tmpExpress select distinct * from(')
BEGIN
	SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
	SET @sql += ')T'
	EXEC(@sql)
	PRINT @sql
END

--取分支机构关联科目
SELECT	A.*,
		CASE WHEN a.Cid = -1 THEN @f_exchid
			 ELSE a.Cid
		END AS rcid,
		CAST(ISNULL(ASS.Ascids,'0') AS VARCHAR)+',' AS Item
INTO #tmpAccount
FROM dbo.Ac_Account a
left join Ac_Account_Assist_CheckItems ass on ass.STypeId = a.StypeId and ass.ATypeId = a.TypeId and ass.Ascids = 4
WHERE a.StypeId = @Verifyid

DECLARE @BillTypestr VARCHAR(50)
SET @BillTypestr = CAST(@BillType AS VARCHAR(50))

CREATE TABLE #tmpBillMulAccount
(
	Atypeid		VARCHAR(50),
	Usercode	VARCHAR(200),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Cid			INT,
	Atdid		INT,
	Total		 NUMERIC(24, 10) ,
	Totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)
CREATE TABLE #tmpBillIndexAtypeid
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atdid		INT,
	total		 NUMERIC(24, 10) ,
	totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)

--获取单据上的收付款科目及金额
INSERT INTO #tmpBillIndexAtypeid
SELECT	c.ATypeID,
		b.UserCode,
		b.FullName,
		NULL,
		NULL,
		D.AtdId,
		CASE WHEN BB.RedWord = 2 THEN -a.Total ELSE a.Total END AS total,
		CASE WHEN BB.RedWord = 2 THEN -a.NTotalMoney ELSE a.NTotalMoney END AS totalfor,
		BB.BillNumberId  
FROM	#TmpBillInfo BB
INNER JOIN #TmpVoucherDetails D ON D.Atid = BB.AtId
INNER JOIN dbo.BillMulAccount a ON a.BillNumberId = BB.BillNumberId AND A.BillType = @BillType
INNER JOIN dbo.Ac_Items b ON a.ATypeID = b.nId
INNER JOIN dbo.Ac_Items_Detail c ON b.nId = c.nId AND c.StypeId = BB.StypeId
WHERE D.AcFrom = 2

INSERT INTO #tmpBillMulAccount
SELECT	ATypeId,b.UserCode,b.FullName,b.Fdc,b.cid,atdid,SUM(Total) AS total,SUM(totalfor) as totalfor,a.billnumberid
FROM	#tmpBillIndexAtypeid a
LEFT JOIN Ac_Account b ON a.atypeid = b.typeid and b.stypeid = @verifyid
GROUP BY atypeid,b.usercode,b.fullname,b.fdc,b.cid,atdid,a.billnumberid

--单据上的往来科目
CREATE TABLE #tmpBillIndexAtypeid1
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atid		INT,
	atdid		INT,
	item		VARCHAR(500),
	billnumberid	INT
)
	
INSERT INTO #tmpBillIndexAtypeid1
SELECT	b.typeId,
		b.UserCode,
		b.FullName,
		Fdc,
		CASE b.cid
			WHEN -1 THEN @f_exchid
			ELSE b.Cid
		END,
		@Atid AS atid,
		@Atdid as atdid,
		SUBSTRING(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1),
				LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))-1,
				LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))) AS Item,
		BB.BillNumberId
FROM	#TmpBillInfo bb
INNER JOIN dbo.Ac_Account b ON B.TypeId = BB.ATypeID1 AND B.StypeId = BB.VerifyStypeid

----不存在的单据无科目，补分支机构默认值
IF EXISTS(SELECT TOP 1 1 FROM #TmpBillInfo WHERE billnumberid NOT IN(SELECT BillNumberId FROM #tmpBillIndexAtypeid1))
BEGIN
	DECLARE @TempBillNumberID TABLE(BillNumberId NUMERIC(10,0))
	INSERT INTO @TempBillNumberID(BillNumberId)
	SELECT BillNumberId FROM #TmpBillInfo WHERE billnumberid NOT IN(SELECT BillNumberId FROM #tmpBillIndexAtypeid1)
	
	INSERT INTO #tmpBillIndexAtypeid1
			( atypeid ,
			  usercode ,
			  fullname ,
			  fdc ,
			  cid ,
			  atid,
			  atdid
			  ,billnumberid
			)
	SELECT  
		'' , -- atypeid - varchar(50)
		'' , -- usercode - varchar(50)
		'' , -- fullname - varchar(200)
		0 , -- fdc - int
		0 , -- cid - int
		0 , -- atid - int
		@Atdid,
		BB.BillNumberId
	FROM #TmpBillInfo BB 
	INNER JOIN @TempBillNumberID T ON T.BillNumberId=BB.BillNumberId
END
	
--生成凭证明细数据(科目来源1~3，8)--
INSERT INTO #tmpBill
		( billnumberid ,
		  explain ,
		  atypeid ,
		  atypeid2 ,
		  Fdc ,
		  f_exchid ,
		  f_exchidfor ,
		  lendprice ,
		  loanprice ,
		  lendpricefor ,
		  loanpricefor ,
		  FCashFlowItem ,
		  ascids ,
		  FSettleNo ,
		  FSettleTypeID ,
		  comment ,
		  cid ,
		  rate ,
		  fadc ,
		  stypeid ,
		  fyear ,
		  fperiod,
		  atdid,
		  addebtid,
		  billid
		)
SELECT	DISTINCT @VoucherId AS billnumberid,
		Summary AS explain,
		CASE AcFrom 
			WHEN 1 THEN b.typeid
			WHEN 2 THEN c.atypeid
			WHEN 3 THEN e.atypeid
			WHEN 4 THEN b.TypeId
		END AS atypeid,
		'' AS atypeid2,
		CASE AcFrom 
			WHEN 1 THEN b.Fdc
			WHEN 2 THEN c.Fdc
			WHEN 3 THEN e.Fdc
			WHEN 4 THEN b.Fdc
		END AS Fdc,
		@f_exchid AS f_exchid,
		BB.Cid AS f_exchidfor,
		CASE a.Fdc 
			WHEN 1 THEN (CASE WHEN AcFrom = 2 THEN isnull(c.total,0) 
							  ELSE isnull(d.lendloan,0) END )
			ELSE 0 
		END AS lendprice,
		CASE a.Fdc 
			WHEN -1 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
							   ELSE isnull(d.lendloan,0) END )
			ELSE 0 
		END AS loanprice,
		CASE WHEN a.Fdc = 1 AND @IsUseBillMoneyDate = 1 AND d.iscost = 0	THEN d.lendloanfor
			 WHEN a.Fdc = 1 THEN 
					(CASE ISNULL(d.ratetype,0) 
						WHEN 0 THEN  (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
										   ELSE isnull(d.lendloan,0) END ) / ISNULL(d.rate,1)
						WHEN 1 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) * ISNULL(d.rate,1)
					END)
			ELSE 0 
		END AS lendpricefor,
		CASE WHEN a.Fdc = -1  AND @IsUseBillMoneyDate = 1 AND d.iscost = 0	THEN d.lendloanfor
			 WHEN a.Fdc = -1 THEN
					(CASE ISNULL(d.ratetype,0)                                                       
						WHEN 0 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) / isnull(d.rate,1)
						WHEN 1 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) * isnull(d.rate,1)
					END)
			ELSE 0 
		END AS loanpricefor,
		NULL AS FCashFlowItem,
		'' AS ascids,
		NULL AS FSettleNo,
		0 AS FSettleTypeID,
		'' AS comment,
		BB.Cid,
		d.rate,
		a.Fdc AS fadc,
		@verifyid AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod,
		a.AtdId,
		0,
		D.billnumberid
FROM	#TmpVoucherDetails a
INNER JOIN #tmpExpress d ON a.AtdId = d.atdit
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = D.billnumberid
LEFT JOIN #tmpAccount b ON a.ATypeId = b.TypeId
LEFT JOIN #tmpBillMulAccount c ON a.Atdid = c.Atdid AND C.billnumberid = D.billnumberid
LEFT JOIN #tmpBillIndexAtypeid1 e ON a.Atdid = e.atdid AND E.billnumberid = D.billnumberid
ORDER BY a.AtdId

--往来科目为空
IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBillIndexAtypeid1 WHERE ISNULL(atypeid,'') <> '')
BEGIN
	IF EXISTS(	SELECT TOP 1 1
					FROM #TmpVoucherDetails T1
						LEFT JOIN #TmpExpress T2 ON T1.AtdId = T2.Atdit
						LEFT JOIN #tmpBillIndexAtypeid1 T3 ON T2.Atdit =T3.Atdid
						LEFT JOIN dbo.Ac_Account T4 ON T3.Atypeid = T4.TypeId AND T4.StypeId = @verifyid
						LEFT JOIN dbo.Ac_Currency T5 ON T4.Cid = T5.CId
					WHERE T1.Atid = @Atid AND T1.AcFrom = 3 AND T2.Lendloan <> 0)
	SET @Flag = -11
END
		
--根据配置，对成本明细做删除
--IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1)
--BEGIN
--	DELETE FROM #TmpBill WHERE atdid IN (SELECT AtdId FROM #TmpVoucherDetails WHERE isCost = 1)
--END

--Awu:调整平衡数
DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) ,@balancemoneyfor  NUMERIC(24, 10) 

DECLARE BalanceCur CURSOR FOR
SELECT billnumberid FROM #TmpBillInfo

OPEN BalanceCur
FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @balancemoney = 0
	SELECT	@balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
			,@balancemoneyfor = SUM(CASE fadc WHEN 1 THEN lendpricefor ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanpricefor ELSE 0 END) 
	FROM #tmpBill
	WHERE billid = @BalanceBillId
	
	
	UPDATE #tmpBill 
	SET #tmpBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
		#tmpBill.lendpricefor = (CASE WHEN fadc = 1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor 
									  WHEN fadc = 1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN -@balancemoney / T3.rate
											WHEN 1 THEN -@balancemoney * T3.rate
										END
								ELSE 0 END ),
		#tmpBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
		#tmpBill.loanpricefor = (CASE WHEN fadc = -1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor
									  WHEN fadc = -1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN @balancemoney / T3.rate
											WHEN 1 THEN @balancemoney * T3.rate
										END
								ELSE 0 END )
	FROM #tmpBill T1
		INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
		INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
	WHERE billid = @BalanceBillId
		
	FETCH NEXT FROM BalanceCur INTO @BalanceBillId
END
CLOSE BalanceCur
DEALLOCATE BalanceCur

--去除金额为0的
DELETE FROM #tmpBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 	

--调整明细异常币种	
UPDATE #tmpbill SET f_exchidfor =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
	cid =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
	rate = CASE WHEN T2.Cid = 0 THEN T1.rate ELSE T3.rate END,
	lendpricefor =  CASE WHEN T2.Cid = 0 OR  (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid)  THEN T1.lendpricefor ELSE 
						CASE T3.BasisType WHEN 0 THEN T1.lendprice / T3.rate
										ELSE  T1.lendprice * T3.rate END
					END,
	loanpricefor =  CASE WHEN T2.Cid = 0 OR (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid) THEN T1.loanpricefor ELSE 
						CASE T3.BasisType WHEN 0 THEN T1.loanprice / T3.rate
										ELSE  T1.loanprice * T3.rate END
					END
FROM #tmpbill T1 
	INNER JOIN dbo.Ac_Account T2 ON T1.stypeid = T2.StypeId AND T1.atypeid = T2.typeid
	LEFT JOIN dbo.Ac_Currency T3 ON T2.Cid = T3.CId

--处理分录号
INSERT INTO #tmpRow(
	billnumberid	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	lendprice		,
	loanprice		,
	lendpricefor	,
	loanpricefor	,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid			,
	countIndex		,
	addebtid		,
	credenceId		,
	billindexid
)
SELECT billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		lendprice,
		loanrice,
		lendpricefor,
		loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		atdid,
		countindex,
		addebtid,
		credenceId,
		billid
FROM
(
SELECT	billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		SUM(lendprice) AS lendprice,
		SUM(loanprice) AS loanrice,
		SUM(lendpricefor) AS lendpricefor,
		SUM(loanpricefor) AS loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		MIN(atdid) atdid,
		@Index AS countindex,
		addebtid,
		credenceId,
		MIN(rowno) AS initrowno,
		billid
FROM	#tmpBill
GROUP BY billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		--atdid,
		addebtid,
		credenceId,
		billid
) AS TT ORDER BY initrowno

--获取明细对应辅助核算
SET @sql = 'INSERT INTO #TmpAssit '
SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'+
			'( '+CAST(T2.FieldValue AS VARCHAR(20))+') AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,
			(SELECT name FROM syscolumns WHERE id = object_id(''PosAllotApplyBillIndex'') AND name = '''+
			cast(case T2.FieldValue 
					WHEN 'instypeid' THEN 'stypeid'
					WHEN 'outstypeid' THEN 'stypeid'
				ELSE FieldValue END AS varchar(50))+''')as filedname ,BILLNUMBERID AS BillIndexNumberId 
			FROM #TmpBillInfo 
			
			UNION ALL '
FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
	LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
WHERE T1.Atid = @Atid
IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
BEGIN
	SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
	EXEC(@sql)
END

DROP TABLE #tmpExpress,#tmpBillIndexAtypeid,#tmpBillMulAccount,#tmpBillIndexAtypeid1,#tmpAccount,#tmpfexpress
	
-----------原循环结尾处

--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	billindexid	INT,
	typeid	VARCHAR(50)
)
INSERT INTO #TmpDetailsAssit
SELECT DISTINCT T1.atdid,T1.rowno,T2.ascids,T1.billindexid,T3.typeid
FROM #tmprow T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId
WHERE ISNULL(T3.ascids,'') <> ''

DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #tmprow 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #tmprow SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END

--排除数据全为0的单据编号
SELECT DISTINCT BillIndexId
INTO #TmpBillNumberId
FROM #tmprow WHERE lendprice <> 0 OR loanprice <> 0

--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT T.*
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	SUM(lendprice)	AS Lend,
	SUM(loanprice)	AS Loan,
	SUM(lendpricefor) AS LendFor,
	SUM(loanpricefor) AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmprow
GROUP BY BillNumberId,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.isCost,AT.OrderID,T.fadc,AC.UserCode

--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT atdid,rowno,ascids,typeid
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit

INSERT INTO #TmpDetailsAssit (atdid, rowno, ascids, typeid )
SELECT DISTINCT 0,T1.rowno,T2.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''

--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END

DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)
--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
         CASE 
			WHEN LTRIM(RTRIM(explain))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(explain)),1) = ';' THEN LEFT(LTRIM(RTRIM(explain)),LEN(LTRIM(RTRIM(explain)))-1)
			ELSE LTRIM(RTRIM(explain))
		  END ,
          stypeid ,
          ISNULL(atypeid,'') ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill

--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails 
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #tmpBillID,#tmpAssit,#tmpBill,#tmpRow,#tmpBillMoney,#TmpDetailsAssit,#TmpNewBill,#tmpHasAssit,#TmpDetailsRow

DROP TABLE #TmpBillNumberId,#TmpBillInfo,#BillNumberId,#TmpVoucherDetails,#TempStr

IF @CreateType = 0
	RETURN 0
	
	
RETURN @VoucherId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.07.01
	描述：moneybill单据36,158,93,5,10,77,84,85,78合并生成凭证
			
*/
CREATE PROCEDURE GP_BatchCreateVoucher_MoneyBill
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期
	@Fyear			INT,
	@Fperiod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0 ,
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0,				-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

DECLARE @BillFullName VARCHAR(200)

SET @BillFullName = 'moneybill'

IF @Billtype = 77
	SET @BillFullName = 'movemoneybill'

--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID			INT,				--收付款项目
	ATypeID1		VARCHAR(50),
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	Total			 NUMERIC(24, 10) ,		--金额
	Totalinmoney	 NUMERIC(24, 10) ,		--收付款金额
	PreferenceMoney	 NUMERIC(24, 10) ,		--优惠金额
	balancemoney	 NUMERIC(24, 10) ,		--平衡数
	RedWord			INT	,				--红冲标识
	AtId			INT
)

INSERT INTO #TmpBillInfo
    ( BillNumberId ,
      StypeId ,
      VerifyStypeid ,
      DTypeId ,
      BTypeId ,
      ETypeId,
      DealBTypeId ,
      ATypeID,
      ATypeID1,
      Cid ,
      Rate ,
      RateType,
      Total,
      Totalinmoney,
      PreferenceMoney,
      RedWord
      ,AtId
    )
SELECT  T1.BillNumberId,
	T1.Stypeid,
	T2.VerifyID,
	T1.DTypeId,
	T1.btypeid,
	T1.etypeid,
	T1.DealBTypeID,
	T1.ATypeID,
	T1.ATypeID1,
	T1.CID,
	T1.Rate,
	T3.BasisType,
	CASE T1.RedWord WHEN 2 THEN -T1.TotalMoney ELSE T1.totalmoney END,
	CASE T1.RedWord WHEN 2 THEN -T1.totalinmoney ELSE T1.totalinmoney END,
	CASE T1.RedWord WHEN 2 THEN -T1.preferencemoney ELSE T1.preferencemoney END,
	T1.RedWord
	,@AtId
FROM dbo.BillIndex T1
INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
WHERE T1.BillNumberId IN (SELECT a FROM #BillNumberId)


DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

--将模板明细处理到临时表中,进行读取字段生成摘要
-----------------------------------------------
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''

SELECT @MinNumber = MIN(a) FROM #BillNumberId
SELECT @MaxNumber = MAX(a) FROM #BillNumberId

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	RowNo		INT IDENTITY(1,1),
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		--SET @Index += 1
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr

	IF @str <> ''
		SET @str += ';'
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	--SET @MinDid += 1
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END

-----------------------
--处理摘要完成


--手工和往来对应的模板信息
CREATE TABLE #TmpExpress
(
	Atdid			INT,
	Lendloan		 NUMERIC(24, 10) ,
	Rate			 NUMERIC(24, 10) ,
	Ratetype		INT
	,billnumberid	INT
)

--表体项目科目及相应金额
CREATE TABLE #TmpItemAtypeMoney
(
	atdid		INT,
	atypeid		VARCHAR(50),
	Lendloan		 NUMERIC(24, 10) ,
	Rate			 NUMERIC(24, 10) ,
	Ratetype		INT,
	deltailid		INT,--明细id
	dtypeid			VARCHAR(50), --明细中部门typeid
	etypeid			VARCHAR(50), --明细中职员typeid
	billnumberid	INT --单据id
)

--手工及往来科目信息
CREATE TABLE #TmpBillIndexAtype
(
	Atypeid		VARCHAR(50),
	UserCode	VARCHAR(50),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Atdid		INT
	,billnumberid	INT
)

--项目模板明细
CREATE TABLE #TmpItemDetail
(
	AtdId				INT,			--模板明细ID
	Express				VARCHAR(1000),	--金额表达式
	Rate				 NUMERIC(24, 10) ,	--汇率
	Ratetype			INT,			--汇率计算方式
	BillIndexNumberid	INT				--单据编号
)

--收付款表体金额明细
CREATE TABLE #TmpDetailsMoney
(
	BillIndexNumberId	INT,
	AtypeId				VARCHAR(50),
	Total				 NUMERIC(24, 10) 
)

--凭证明细临时表,存储所有单据生成的凭证明细
CREATE TABLE #TmpVoucherBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	AtdId			INT,
	BillIndexId		INT,
	deltailid		INT --业务单据上的明细id 
)

--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	BillIndexNumberId	INT,				--单据ID
	fieldname		VARCHAR(500),
	deltailid		INT --业务单据上的明细id 
)

DECLARE 
		--@BillCount	INT,--单据总数
		--@CurrentID	INT,--当前单据ID
		--@RateValue	 NUMERIC(24, 10) ,--汇率值
		--@Ratetype	INT,	--汇率计算方式
		--@STypeidValue	VARCHAR(50),--分支机构
		@VerifyidValue	VARCHAR(50)--核算机构
		--@ATypeId1		VARCHAR(50),--往来科目
		--@cidvalue		INT
		


DECLARE	@sql VARCHAR(MAX)
	
	SELECT TOP 1 @VerifyidValue=VerifyStypeid FROM #TmpBillInfo
	
	--往来科目信息
	INSERT INTO #TmpBillIndexAtype
			( Atypeid ,
			  UserCode ,
			  Fullname ,
			  Fdc ,
			  Atdid 
			  ,billnumberid
			)
	SELECT	b.typeId,
		b.UserCode,
		b.FullName,
		Fdc,
		@Atdid
		,BB.BillNumberId
	FROM dbo.Ac_Account b
	INNER JOIN #TmpBillInfo BB ON BB.ATypeID1 = B.TypeId
	WHERE  b.StypeId = @verifyidvalue


	--无往来科目，补空白
	IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpBillIndexAtype)
	BEGIN
		INSERT INTO #tmpBillIndexAtype
				( atypeid ,
				  usercode ,
				  fullname ,
				  fdc ,
				  atdid
				  ,billnumberid
				)
		SELECT '','','',0,@AtdId,BillNumberId
		FROM #TmpBillInfo
	END
	
	--处理手工选择科目信息
	INSERT INTO #TmpBillIndexAtype
			( Atypeid ,
			  UserCode ,
			  Fullname ,
			  Fdc ,
			  Atdid
			  ,billnumberid
			)
	SELECT T2.TypeId,T2.UserCode,T2.FullName,T2.Fdc,T1.Atdid,BB.BillNumberId
	FROM dbo.Ac_Auditing_Template_Detail T1
	INNER JOIN #TmpBillInfo BB ON BB.AtId = T1.Atid
	INNER JOIN dbo.Ac_Account T2 ON T1.ATypeId = T2.TypeId AND T2.StypeId = @Verifyid
	WHERE T1.AcFrom = 1
	
	--2014.06.17 9.4版158,36调整为多账户收款
	--2014-11-19 9.5版本77（转账单）调整为多账户
	IF @BillType IN (158,36,77,93,84,85)--收付款为BillMulAccount中数据
	BEGIN
		INSERT INTO #TmpDetailsMoney( BillIndexNumberId, AtypeId, Total )
		SELECT T2.BillNumberId,T1.AtypeId,SUM(CASE WHEN T2.RedWord = 2 THEN -t1.total ELSE t1.total END) AS total
		FROM dbo.BillMulAccount T1
			INNER JOIN dbo.BillIndex T3 ON T1.BillNumberId = T3.BillNumberId AND T3.BillType=T1.BillType
			INNER JOIN #TmpBillInfo T2 ON T1.BillNumberId = T2.BillNumberId --AND T2.BillNumberId = @CurrentID
		GROUP BY T2.BillNumberId, T1.AtypeId
	END
	ELSE
		--获取收付款金额（Tip：收付款仅能选择totalinmoney,所以直接获取值即可）
		INSERT INTO #TmpDetailsMoney( BillIndexNumberId, AtypeId, Total )
		SELECT T2.BillNumberId,T1.AtypeId,CASE WHEN T2.RedWord = 2 THEN -t1.totalinmoney ELSE t1.totalinmoney END AS total
		FROM dbo.BillIndex T1
			INNER JOIN #TmpBillInfo T2 ON T1.BillNumberId = T2.BillNumberId --AND T2.BillNumberId = @CurrentID
	
	----处理科目来源为手工和往来的
	SET @sql = 'insert into #tmpExpress'
	SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,('+ Express +') as lendloan,rate,ratetype,billnumberid
		from #TmpBillInfo  union all '
		FROM Ac_Auditing_Template_Detail WHERE Atid = @Atid AND (AcFrom = 1 OR AcFrom = 3)
	IF LEN(@sql) > LEN('insert into #tmpExpress')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
		EXEC(@sql)
	END
	
	--test
	--SELECT * FROM #TmpDetailsMoney
	
	--插入凭证明细 1,3
	INSERT INTO #TmpVoucherBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  AtdId,
			  BillIndexId
			)
	SELECT	@VoucherId AS billnumberid,
			T1.Summary,
			T3.Atypeid,
			'',
			T3.Fdc,
			@f_exchid,
			CASE WHEN ISNULL(T4.Cid,0) IN(-1,0) THEN BB.Cid ELSE T4.Cid END,
			CASE T1.Fdc
				WHEN 1 THEN T2.Lendloan
				ELSE 0
			END,
			CASE T1.Fdc
				WHEN -1 THEN T2.Lendloan
				ELSE 0
			END,
			CASE T1.Fdc 
				WHEN 1 THEN 
					CASE 
						WHEN ISNULL(T4.Cid,0) IN(-1,0) OR BB.Cid = T4.Cid THEN
							CASE T2.Ratetype 
								WHEN 0 THEN T2.Lendloan /BB.Rate
								ELSE T2.Lendloan * BB.Rate
							END
						ELSE
							CASE T5.BasisType 
								WHEN 0 THEN T2.Lendloan /T5.Rate
								ELSE T2.Lendloan * T5.Rate
							END
					END
				ELSE 0 
			END,
			CASE T1.Fdc 
				WHEN -1 THEN
					CASE 
						WHEN ISNULL(T4.Cid,0) IN(-1,0) OR BB.Cid = T4.Cid THEN
							CASE T2.Ratetype 
								WHEN 0 THEN T2.Lendloan /BB.Rate
								ELSE T2.Lendloan * BB.Rate
							END
						ELSE
							CASE T5.BasisType 
								WHEN 0 THEN T2.Lendloan /T5.Rate
								ELSE T2.Lendloan * T5.Rate
							END
					END
				ELSE 0 
			END,
			'',
			'',
			'',
			'',
			'',
			CASE WHEN ISNULL(T4.Cid,0) IN(-1,0) OR BB.Cid = T4.Cid THEN BB.Cid ELSE T4.Cid END,
			CASE WHEN ISNULL(T4.Cid,0) IN(-1,0) OR BB.Cid = T4.Cid THEN BB.Rate ELSE T5.Rate END,
			T1.Fdc,--模板金额方向
			@VerifyIdValue,
			@Fyear,
			@Fperiod,
			T1.AtdId,
			T2.billnumberid
	FROM #TmpVoucherDetails T1
		LEFT JOIN #TmpExpress T2 ON T1.AtdId = T2.Atdid
		LEFT JOIN #TmpBillIndexAtype T3 ON T2.Atdid =T3.Atdid AND T3.billnumberid = T2.billnumberid
		LEFT JOIN #TmpBillInfo BB ON BB.BillNumberId = T2.billnumberid
		LEFT JOIN dbo.Ac_Account T4 ON T3.Atypeid = T4.TypeId AND T4.StypeId = @verifyidvalue
		LEFT JOIN dbo.Ac_Currency T5 ON T4.Cid = T5.CId
	WHERE T1.Atid = @Atid AND T1.AcFrom IN (1,3)
	
	----生成科目来源为收付款项目的模板信息
	INSERT INTO #TmpItemDetail
			(AtdId,
			Express,
			rate,
			ratetype,
			BillIndexNumberid)
	SELECT AtdId,Express,BB.Rate AS rate,BB.RateType AS ratetype,BB.BillNumberId AS billnumberid
	FROM dbo.Ac_Auditing_Template_Detail T
	INNER JOIN #TmpBillInfo BB ON BB.AtId = T.Atid 
	WHERE T.Atid = @atid AND AcFrom = 2

	--插入临时表凭证明细 2
	INSERT INTO #TmpVoucherBill
	        ( BillNumberId ,
	          explain ,
	          atypeid ,
	          atypeid2 ,
	          Fdc ,
	          f_exchid ,
	          f_exchidfor ,
	          lendprice ,
	          loanprice ,
	          lendpricefor ,
	          loanpricefor ,
	          FCashFlowItem ,
	          ascids ,
	          FSettleNo ,
	          FSettleTypeID ,
	          comment ,
	          cid ,
	          rate ,
	          fadc ,
	          stypeid ,
	          fyear ,
	          fperiod,
	          AtdId,
	          BillIndexId
	        )
	SELECT	@VoucherId AS billnumberid,c.Summary AS explain,
			e.ATypeId AS atypeid,
			'' AS atypeid2,
			f.Fdc ,@f_exchid AS f_exchid,CASE WHEN ISNULL(f.Cid,0) IN(-1,0) THEN BB.Cid ELSE f.Cid END AS f_exchidfor,
			CASE c.Fdc
				WHEN 1	THEN b.total
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN b.total
				WHEN 1	THEN 0
			END AS dai,
			CASE c.Fdc 
				WHEN 1 THEN 
						CASE WHEN ISNULL(f.Cid,0) IN(-1,0) OR BB.Cid = F.Cid THEN
							(CASE a.ratetype 
								WHEN 0 THEN b.total / BB.rate
								WHEN 1 THEN b.total * BB.rate
							END)
						ELSE
							(CASE g.BasisType
								WHEN 0 THEN b.total / g.rate
								WHEN 1 THEN b.total * g.rate
							END)
						END
				ELSE 0 
			END AS jiefor,
			CASE c.Fdc 
				WHEN -1 THEN
						CASE WHEN ISNULL(f.Cid,0) IN(-1,0) OR BB.Cid = F.Cid THEN
							(CASE a.ratetype 
								WHEN 0 THEN b.total / BB.rate
								WHEN 1 THEN b.total * BB.rate
							END)
						ELSE
							(CASE g.BasisType
								WHEN 0 THEN b.total / g.rate
								WHEN 1 THEN b.total * g.rate
							END)
						END
				ELSE 0 
			END AS daifor,
			'' AS FCashFlowItem,
			'' AS ascids,
			'' AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			CASE WHEN ISNULL(f.Cid,0) IN(-1,0) OR BB.Cid = F.Cid THEN BB.Cid ELSE f.cid END AS cid,
			CASE WHEN ISNULL(f.Cid,0) IN(-1,0) OR BB.Cid = F.Cid THEN BB.rate ELSE g.Rate END AS rate,
			c.Fdc AS fadc,
			@verifyidvalue AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			c.AtdId,
			A.BillIndexNumberid--单据ID
	FROM	#TmpItemDetail a
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillIndexNumberid
	INNER JOIN #TmpDetailsMoney b ON a.BillIndexNumberid = b.BillIndexNumberId 
	INNER JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	INNER JOIN dbo.Ac_Items d ON b.AtypeId = d.nid
	LEFT JOIN dbo.Ac_Items_Detail e ON d.nId = e.nId AND e.STypeId = BB.StypeId
	LEFT JOIN dbo.Ac_Account f ON e.ATypeId = f.TypeId AND f.StypeId = @verifyidvalue
	LEFT JOIN dbo.Ac_Currency g ON f.Cid = g.CId


	--取表体项目对应的相应金额与科目(Tip:主观认为表体只会取正确的值total，其他错误值不管)
	SET @sql = 'insert into #TmpItemAtypeMoney'
	SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,'
						+CASE WHEN AcFrom IN(4,5) THEN 'T3.atypeid' 
							 WHEN AcFrom = 9 THEN 'T3.DepATypeId'
							 WHEN AcFrom = 10 THEN 'T3.DisATypeId' END+',
					' + CASE WHEN express NOT IN ('ac_balancea','ac_balanceb') THEN +' CASE WHEN T1.redword = 2 THEN -T2.'+ Express +' ELSE T2.' + Express + ' END'
							 WHEN express = 'ac_balancea' THEN 'CASE WHEN T1.redword = 2 THEN -T4.fendbalance ELSE T4.fendbalance END'
							 WHEN express = 'ac_balanceb' THEN 'CASE WHEN T1.redword = 2 THEN -T4_1.fendbalance ELSE T4_1.fendbalance END'
						END
					+ ' as lendloan,rate,ratetype
					,T2.id '+
					CASE WHEN @BillFullName = 'moneybill' THEN '
					,T2.Dtypeid
					,T2.Etypeid
					'
					ELSE '
					,0
					,0
					'
					END +
					'
					,T2.BillNumberId
		from #TmpBillInfo T1
			INNER JOIN '+ @BillFullName +' T2 ON T1.BillNumberId = T2.BillNumberId
			LEFT JOIN dbo.Ac_Items_Detail T3 ON T2.AtypeId = T3.nId AND T1.verifyStypeid = T3.STypeId
			LEFT JOIN Ac_Items_Detail T3_1 ON T2.AtypeId = T3_1.nId AND T1.verifyStypeid = T3_1.STypeId
			LEFT JOIN Ac_Balance T4 ON T4.cid = 0 AND T3.Atypeid = T4.Atypeid AND T1.verifyStypeid = T4.stypeid AND T4.fyear = '+cast(@fyear AS varchar(10))+' AND T4.fperiod = '+cast(@fperiod AS varchar(10))+'
			LEFT JOIN Ac_Balance T4_1 ON T4_1.cid = 0 AND T3.depAtypeid = T4_1.Atypeid AND T1.verifyStypeid = T4_1.stypeid AND T4_1.fyear = '+cast(@fyear AS varchar(10))+' AND T4_1.fperiod = '+cast(@fperiod AS varchar(10))+
			' union all '
		FROM Ac_Auditing_Template_Detail WHERE Atid = @Atid AND AcFrom IN (4,5,9,10)
	IF LEN(@sql) > LEN('insert into #TmpItemAtypeMoney')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
		EXEC(@sql)
	END

	--明细 4
	INSERT INTO #TmpVoucherBill
	        ( BillNumberId ,
	          explain ,
	          atypeid ,
	          atypeid2 ,
	          Fdc ,
	          f_exchid ,
	          f_exchidfor ,
	          lendprice ,
	          loanprice ,
	          lendpricefor ,
	          loanpricefor ,
	          FCashFlowItem ,
	          ascids ,
	          FSettleNo ,
	          FSettleTypeID ,
	          comment ,
	          cid ,
	          rate ,
	          fadc ,
	          stypeid ,
	          fyear ,
	          fperiod,
	          AtdId,
	          BillIndexId
	          ,deltailid
	        )
	SELECT	@VoucherId AS billnumberid,c.Summary AS explain,
			a.ATypeId AS atypeid,
			'' AS atypeid2,
			f.Fdc ,@f_exchid AS f_exchid,CASE WHEN ISNULL(f.Cid,0) IN (-1,0) THEN BB.Cid ELSE f.Cid END AS f_exchidfor,
			CASE c.Fdc
				WHEN 1	THEN a.lendloan
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN a.lendloan
				WHEN 1	THEN 0
			END AS dai,
			CASE c.Fdc 
				WHEN 1 THEN
						CASE WHEN ISNULL(f.Cid,0) IN(-1,0) OR BB.Cid = F.Cid THEN
							(CASE a.ratetype 
								WHEN 0 THEN a.lendloan / BB.rate
								WHEN 1 THEN a.lendloan * BB.rate
							END)
						ELSE
							(CASE g.BasisType
								WHEN 0 THEN a.lendloan / g.rate
								WHEN 1 THEN a.lendloan * g.rate
							END)
						END
				ELSE 0 
			END AS jiefor,
			CASE c.Fdc 
				WHEN -1 THEN
						CASE WHEN ISNULL(f.Cid,0) IN(-1,0) OR BB.Cid = F.Cid THEN
							(CASE a.ratetype 
								WHEN 0 THEN a.lendloan / BB.rate
								WHEN 1 THEN a.lendloan * BB.rate
							END)
						ELSE
							(CASE g.BasisType
								WHEN 0 THEN a.lendloan / g.rate
								WHEN 1 THEN a.lendloan * g.rate
							END)
						END
				ELSE 0 
			END AS daifor,
			'' AS FCashFlowItem,
			'' AS ascids,
			'' AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			CASE WHEN ISNULL(f.Cid,0) IN(-1,0) OR BB.Cid = F.Cid THEN BB.Cid ELSE f.cid END AS cid,
			CASE WHEN ISNULL(f.Cid,0) IN(-1,0) OR BB.Cid = F.Cid THEN BB.rate ELSE g.Rate END AS rate,
			c.Fdc AS fadc,
			@verifyidvalue AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			c.AtdId,
			A.billnumberid--单据ID
			,A.deltailid
	FROM	#TmpItemAtypeMoney a
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.billnumberid
	INNER JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	LEFT JOIN dbo.Ac_Account f ON a.ATypeId = f.TypeId AND f.StypeId = @verifyidvalue
	LEFT JOIN dbo.Ac_Currency g ON f.Cid = g.CId

	--Awu:调整平衡数
	DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) 

	DECLARE BalanceCur CURSOR FOR
	SELECT billnumberid FROM #tmpbillinfo
		OPEN BalanceCur
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @balancemoney = 0
		SELECT @balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
		FROM #TmpVoucherBill
		WHERE billindexid = @BalanceBillId
		
		
		UPDATE #TmpVoucherBill 
		SET #TmpVoucherBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
			#TmpVoucherBill.lendpricefor = (CASE fadc WHEN 1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN -@balancemoney / T1.rate
												WHEN 1 THEN -@balancemoney * T1.rate
											END
									ELSE 0 END ),
			#TmpVoucherBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
			#TmpVoucherBill.loanpricefor = (CASE fadc WHEN -1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN @balancemoney / T1.rate
												WHEN 1 THEN @balancemoney * T1.rate
											END
									ELSE 0 END )
		FROM #TmpVoucherBill T1
			INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
			INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
		WHERE billindexid = @BalanceBillId
			
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	END
	CLOSE BalanceCur
	DEALLOCATE BalanceCur

	--获取明细对应辅助核算
	SET @sql = 'INSERT INTO #TmpAssit '
	SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'+
				'('+CAST(T2.FieldValue AS VARCHAR(20))+') AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,billnumberid AS BillIndexNumberId
				,(SELECT name FROM syscolumns WHERE id = object_id(''billindex'') AND name = '''+
				T2.fieldvalue + ''')as fieldname
				,0 AS deltailid 
				FROM #TmpBillInfo UNION ALL '
	FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
		LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
	WHERE T1.Atid = @Atid
	IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
		EXEC(@sql)
	END
	
	--现金费用单（158）辅助核算源于单据明细中
	--项目折旧的部门来源于明细
	IF @BillType IN(158,78,36,93)
	BEGIN

		INSERT INTO #tmpassit(AtdId,TypeId,Ascids,fieldname,BillIndexNumberId,deltailid)
		SELECT a.atdid,a.typeid,a.ascids,a.fieldname,a.billindexnumberid,B.deltailid
		FROM #Tmpassit a
			INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid
		--WHERE a.billindexnumberid = @currentid
		--DELETE FROM #tmpassit WHERE ISNULL(deltailid,0) = 0 AND fieldname IN('Etypeid','Dtypeid')
		
		UPDATE #Tmpassit SET typeid = C.dtypeid
		FROM #Tmpassit a
		INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.deltailid = b.deltailid
		INNER JOIN #TmpItemAtypeMoney c ON b.deltailid = c.deltailid AND a.billindexnumberid = c.billnumberid
		WHERE fieldname = 'Dtypeid'
			
		IF @BillType IN(158,36,93)
		BEGIN
			UPDATE #Tmpassit SET typeid = c.etypeid
			FROM #Tmpassit a
			INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.deltailid = b.deltailid
			INNER JOIN #TmpItemAtypeMoney c ON b.deltailid = c.deltailid AND a.billindexnumberid = c.billnumberid
			WHERE fieldname = 'Etypeid'
		END
		
	END


--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

IF @BillType IN(158,78,36,93)
BEGIN
	INSERT INTO #TmpDetailsAssit
	SELECT DISTINCT T1.atdid,T1.rowno,T3.ascids,T3.typeid
	FROM #TmpVoucherBill T1
		LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
		LEFT JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId AND ISNULL(T1.deltailid,0) = T3.deltailid
	WHERE ISNULL(T3.ascids,'') <> ''
END
ELSE
BEGIN
	INSERT INTO #TmpDetailsAssit
	SELECT DISTINCT T1.atdid,T1.rowno,T3.ascids,T3.typeid
	FROM #TmpVoucherBill T1
		LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
		LEFT JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId
	WHERE ISNULL(T3.ascids,'') <> ''
END

	
DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpVoucherBill 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #TmpVoucherBill SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END

--排除数据全为0的单据编号
SELECT DISTINCT BillIndexId
INTO #TmpBillNumberId
FROM #TmpVoucherBill WHERE lendprice <> 0 OR loanprice <> 0


--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT T.*
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	SUM(lendprice)	AS Lend,
	SUM(loanprice)	AS Loan,
	SUM(lendpricefor) AS LendFor,
	SUM(loanpricefor) AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmpVoucherBill
GROUP BY BillNumberId,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.OrderID,T.fadc,AC.UserCode

--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT *
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit



INSERT INTO #TmpDetailsAssit
SELECT DISTINCT 0,T1.rowno,T3.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''


--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN	
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END

DROP TABLE #tmpHasAssit
DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)

--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
         CASE 
			WHEN LTRIM(RTRIM(explain))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(explain)),1) = ';' THEN LEFT(LTRIM(RTRIM(explain)),LEN(LTRIM(RTRIM(explain)))-1)
			ELSE LTRIM(RTRIM(explain))
		  END ,
          stypeid ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill

--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails 
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END	

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #TmpBillInfo,#TmpExpress,#TmpDetailsMoney,#TmpVoucherBill,#tmpBillIndexAtype,#TmpItemDetail,#TmpAssit,#TmpDetailsAssit,#TmpNewBill,#TmpDetailsRow
DROP TABLE #TmpBillNumberId,#BillNumberId

	
RETURN @VoucherId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.07.01
	描述：合并生成凭证
			
*/
CREATE PROCEDURE GP_BatchCreateVoucher_OtherBill
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0 ,
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0,					-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

DECLARE @AutoFlag INT --即时生成凭证异常
SET @AutoFlag = 0

--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID			INT,				--收付款项目
	ATypeID1		VARCHAR(50),
	sharefee		 NUMERIC(24, 10)  DEFAULT 0,--分摊费用
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	balancemoney	 NUMERIC(24, 10) ,		--平衡数
	RedWord			INT					--红冲标识
	,AtId			INT
	,AdPriceType	INT		--成本调价单类型：0库存，1入库，2出库
)

INSERT INTO #TmpBillInfo
        ( BillNumberId ,
          StypeId ,
          VerifyStypeid ,
          DTypeId ,
          BTypeId ,
          ETypeId,
          DealBTypeId ,
          ATypeID,
          ATypeID1,
          Cid ,
          Rate ,
          RateType,
          RedWord
          ,AtId
          ,AdPriceType
        )
SELECT  T1.BillNumberId,
		T1.Stypeid,
		T2.VerifyID,
		T1.DTypeId,
		T1.btypeid,
		T1.etypeid,
		T1.DealBTypeID,
		T1.ATypeID,
		T1.ATypeID1,
		T1.CID,
		T1.Rate,
		T3.BasisType,
		T1.RedWord
		,@AtId
		,t1.AdPriceType
FROM dbo.BillIndex T1
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
WHERE T1.BillNumberId IN (SELECT a FROM #BillNumberId)

DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)
		,@inOutType INT --成本调价单类型 0:库存 1:入库 2:出库

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1
SELECT @inOutType = InOutType FROM dbo.Ac_Auditing_Template WHERE AtId = @AtId

--将模板明细处理到临时表中,进行读取字段生成摘要
-----------------------------------------------
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''

SELECT @MinNumber = MIN(a) FROM #BillNumberId
SELECT @MaxNumber = MAX(a) FROM #BillNumberId

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	RowNo		INT IDENTITY(1,1),
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		--SET @Index += 1
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr
	
	IF @str <> ''
		SET @str += ';'
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	--SET @MinDid += 1
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END

-----------------------
--处理摘要完成

--手工和往来对应的模板信息
CREATE TABLE #TmpExpress
(
	Atdid			INT,
	Lendloan		 NUMERIC(24, 10) ,
	Rate			 NUMERIC(24, 10) ,
	Ratetype		INT
	,billnumberid	INT
)

--表体项目科目及相应金额
CREATE TABLE #TmpItemAtypeMoney
(
	atdid		INT,
	atypeid		VARCHAR(50),
	Lendloan		 NUMERIC(24, 10) ,
	Rate			 NUMERIC(24, 10) ,
	Ratetype		INT
	,billnumberid	INT
)

--手工科目信息
CREATE TABLE #TmpBillIndexAtype
(
	Atypeid		VARCHAR(50),
	UserCode	VARCHAR(50),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Atdid		INT
	,billnumberid	INT
)

--项目模板明细
CREATE TABLE #TmpItemDetail
(
	AtdId				INT,			--模板明细ID
	Express				VARCHAR(1000),	--金额表达式
	Rate				 NUMERIC(24, 10) ,	--汇率
	Ratetype			INT,			--汇率计算方式
	BillIndexNumberid	INT				--单据编号
)

--收付款表体金额明细
CREATE TABLE #TmpDetailsMoney
(
	BillIndexNumberId	INT,
	AtypeId				VARCHAR(50),
	Total				 NUMERIC(24, 10) 
)

--业务凭证特殊处理表
CREATE TABLE #tmpAccountCredence
(
	billnumberid	INT,
	TypeAtypeID		VARCHAR(50),
	j_total			 NUMERIC(24, 10) ,
	d_total			 NUMERIC(24, 10) ,
	cid				INT,
	ratetype		INT,
	rate			 NUMERIC(24, 10) ,
	ATypeID			VARCHAR(50),
	id				INT IDENTITY(1,1),
	rowno			INT
)


--凭证明细临时表,存储所有单据生成的凭证明细
CREATE TABLE #TmpVoucherBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	AtdId			INT,
	BillIndexId		INT,
	credenceId		INT
)

--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	fieldname			VARCHAR(100),
	BillIndexNumberId	INT			,	--单据ID
	credenceid			INT
)

DECLARE @VerifyidValue	VARCHAR(50)--核算机构
		


DECLARE	@sql VARCHAR(MAX)
	
	SELECT TOP 1 @VerifyidValue = VerifyStypeid  FROM #TmpBillInfo
	
	--处理手工选择科目信息
	INSERT INTO #TmpBillIndexAtype
			( Atypeid ,
			  UserCode ,
			  Fullname ,
			  Fdc ,
			  Atdid
			  ,billnumberid
			)
	SELECT T2.TypeId,T2.UserCode,T2.FullName,T2.Fdc,T1.Atdid,BB.BillNumberId
	FROM dbo.Ac_Auditing_Template_Detail T1
	INNER JOIN #TmpBillInfo BB ON BB.AtId = T1.Atid
	INNER JOIN dbo.Ac_Account T2 ON T1.ATypeId = T2.TypeId AND T2.StypeId = @Verifyid
	WHERE T1.AcFrom = 1
	
	INSERT INTO #TmpBillIndexAtype
			( Atypeid ,
			  UserCode ,
			  Fullname ,
			  Fdc ,
			  Atdid
			  ,billnumberid
			)
	SELECT T2.TypeId,T2.UserCode,T2.FullName,T2.Fdc,T1.Atdid,BB.BillNumberId
	FROM dbo.Ac_Auditing_Template_Detail T1
	INNER JOIN #TmpBillInfo BB ON BB.AtId = T1.Atid
	INNER JOIN dbo.Ac_Account T2 ON bb.ATypeID1 = T2.TypeId AND T2.StypeId = @Verifyid
	WHERE T1.AcFrom = 3
	
	
	IF @BillType = 205
		--更新总计的分摊值
		UPDATE #TmpBillInfo
		SET sharefee = total
		FROM #TmpBillInfo T1
		INNER JOIN
		(
		SELECT SUM(CASE WHEN b.RedWord = 2 THEN -a.shareFee ELSE a.ShareFee END) AS total,
								a.BillNumberId
				FROM dbo.ShareSourceBill a
				INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
				--WHERE a.BillNumberId = @currentid
				GROUP BY a.BillNumberId
		)TT ON T1.billnumberid = TT.billnumberid
		--WHERE T1.billnumberid = @currentid
	

	IF @Billtype = 57
	BEGIN
	----处理科目来源为手工
		SET @sql = 'insert into #tmpExpress'
		SET @sql += ' SELECT atdid,SUM(ISNULL(Lendloan,0) ) AS lendloan,rate,Ratetype,billnumberid FROM ('
		SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId
			,CASE WHEN T2.redword = 2 THEN -('+ t2.Express +') 
			ELSE ('+  t2.Express  +') END as lendloan
			,T2.rate,T2.ratetype,t1.billnumberid
			from adpricebill T1
					INNER JOIN  #TmpBillInfo T2 ON T1.billnumberid = T2.billnumberid
					 union all '
			FROM #TmpVoucherDetails T1
			INNER JOIN dbo.Ac_BillMoney_List t2 ON t2.BillMoneyId = t1.BillMoneyId 
			WHERE Atid = @Atid AND AcFrom in (1,3)
		IF LEN(@sql) > LEN('insert into #tmpExpress  SELECT atdid,SUM(ISNULL(Lendloan,0) ) AS lendloan,rate,Ratetype,billnumberid FROM (')
		BEGIN
			SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
			SET @sql += ') T GROUP BY Atdid,Rate,Ratetype,billnumberid'
			EXEC(@sql)
			
			UPDATE T SET Lendloan = CASE WHEN t2.Express ='changetotal' THEN (SELECT TOP 1 CASE WHEN @inOutType = 2 THEN -Total ELSE Total END FROM dbo.ListTable WHERE BillType = 57 AND AtypeId = 30 AND BillNumberId = T.billnumberid) ELSE Lendloan END
			FROM #TmpExpress T 
			INNER JOIN #TmpVoucherDetails T1 ON T1.AtdId = T.Atdid 
			INNER JOIN dbo.Ac_BillMoney_List t2 ON t2.BillMoneyId = t1.BillMoneyId 
			
		END		
	END
	ELSE
	BEGIN
		SET @sql = 'insert into #tmpExpress'
		SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,('+ t2.Express +') as lendloan,T2.rate,T2.ratetype,t2.billnumberid
			from #TmpBillInfo T2 
			union all '
			FROM #TmpVoucherDetails T1
			INNER JOIN dbo.Ac_BillMoney_List t2 ON t2.BillMoneyId = t1.BillMoneyId 
			WHERE Atid = @Atid AND AcFrom = 1
		IF LEN(@sql) > LEN('insert into #tmpExpress')
		BEGIN
			SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
			EXEC(@sql)
		END
	END

	--插入凭证明细 1,3
	INSERT INTO #TmpVoucherBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  AtdId,
			  BillIndexId
			)
	SELECT	@VoucherId AS billnumberid,
			T1.Summary,
			ISNULL(T3.Atypeid,''),
			'',
			T3.Fdc,
			@f_exchid,
			BB.Cid,
			CASE T1.Fdc
				WHEN 1 THEN T2.Lendloan
				ELSE 0
			END,
			CASE T1.Fdc
				WHEN -1 THEN T2.Lendloan
				ELSE 0
			END,
			CASE T1.Fdc 
				WHEN 1 THEN 
					CASE 
						WHEN ISNULL(T4.cid,-1) IN (-1,0) THEN
							CASE T2.Ratetype 
								WHEN 0 THEN T2.Lendloan /T2.Rate
								ELSE T2.Lendloan * T2.Rate
							END
						ELSE
							CASE T5.BasisType 
								WHEN 0 THEN T2.Lendloan /T5.Rate
								ELSE T2.Lendloan * T5.Rate
							END
					END
				ELSE 0 
			END,
			CASE T1.Fdc 
				WHEN -1 THEN
					CASE 
						WHEN ISNULL(T4.cid,-1) IN (-1,0) THEN
							CASE T2.Ratetype 
								WHEN 0 THEN T2.Lendloan /T2.Rate
								ELSE T2.Lendloan * T2.Rate
							END
						ELSE
							CASE T5.BasisType 
								WHEN 0 THEN T2.Lendloan /T5.Rate
								ELSE T2.Lendloan * T5.Rate
							END
					END
				ELSE 0 
			END,
			'',
			'',
			'',
			'',
			'',
			CASE WHEN ISNULL(T4.cid,-1) IN (-1,0) THEN BB.Cid ELSE T4.Cid END,
			CASE WHEN ISNULL(T4.cid,-1) IN (-1,0) THEN T2.Rate ELSE T5.Rate END,
			T1.Fdc,--模板金额方向
			@VerifyIdValue,
			@Fyear,
			@Fperiod,
			T1.AtdId
			,BB.BillNumberId
	FROM #TmpVoucherDetails T1
		LEFT JOIN #TmpExpress T2 ON T1.AtdId = T2.Atdid
		LEFT JOIN #TmpBillInfo BB ON BB.BillNumberId = T2.billnumberid
		LEFT JOIN #TmpBillIndexAtype T3 ON T2.Atdid =T3.Atdid AND T3.billnumberid = BB.BillNumberId
		LEFT JOIN dbo.Ac_Account T4 ON T3.Atypeid = T4.TypeId AND T4.StypeId = @verifyidvalue
		LEFT JOIN dbo.Ac_Currency T5 ON T4.Cid = T5.CId
	WHERE T1.Atid = @Atid AND T1.AcFrom IN (1,3)
	
	
	IF @BillType  IN (205)
	BEGIN
		--取表体项目对应的相应金额与科目(Tip:主观认为表体只会取正确的值total，其他错误值不管)
		SET @sql = 'insert into #TmpItemAtypeMoney'
		SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,'
							+CASE WHEN AcFrom IN(4,5) THEN 'atypeid' 
								 WHEN AcFrom = 9 THEN 'DepATypeId'
								 WHEN AcFrom = 10 THEN 'DisATypeId' END+',
						'+ CASE WHEN Express = 'sharefee' THEN 'total'
									ELSE Express END +' as lendloan,rate,ratetype,billnumberid
			from (
			select distinct T1.BillNumberId,T1.Rate,T1.ratetype,T3.ATypeId,T3.DepATypeId,T3.DisATypeId,T5.id,CASE WHEN T1.redword = 2 THEN -T5.total ELSE T5.total END AS total from	
				#TmpBillInfo T1
				INNER JOIN sharesourcebill T2 ON T1.BillNumberId = T2.BillNumberId
				INNER JOIN ShareFeeBill T4 ON T1.BillNumberId = T4.BillNumberId
				INNER JOIN moneybill T5 ON T4.FromBillNumberID = T5.BillNumberId AND T4.frombillid = T5.id
				LEFT JOIN dbo.Ac_Items_Detail T3 ON T5.AtypeId = T3.nId AND T1.Stypeid = T3.STypeId
			)T'
			+' union all '
			FROM Ac_Auditing_Template_Detail WHERE Atid = @Atid AND AcFrom IN (4,5,9,10)
		IF LEN(@sql) > LEN('insert into #TmpItemAtypeMoney')
		BEGIN
			SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
			EXEC(@sql)
		END
	END
	
	--明细 4
	INSERT INTO #TmpVoucherBill
	        ( BillNumberId ,
	          explain ,
	          atypeid ,
	          atypeid2 ,
	          Fdc ,
	          f_exchid ,
	          f_exchidfor ,
	          lendprice ,
	          loanprice ,
	          lendpricefor ,
	          loanpricefor ,
	          FCashFlowItem ,
	          ascids ,
	          FSettleNo ,
	          FSettleTypeID ,
	          comment ,
	          cid ,
	          rate ,
	          fadc ,
	          stypeid ,
	          fyear ,
	          fperiod,
	          AtdId,
	          BillIndexId
	        )
	SELECT	@VoucherId AS billnumberid,c.Summary AS explain,
			a.ATypeId AS atypeid,
			'' AS atypeid2,
			f.Fdc ,@f_exchid AS f_exchid,CASE WHEN ISNULL(f.cid,-1) IN (-1,0) THEN BB.Cid ELSE f.Cid END AS f_exchidfor,
			CASE c.Fdc
				WHEN 1	THEN a.lendloan
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN a.lendloan
				WHEN 1	THEN 0
			END AS dai,
			CASE c.Fdc 
				WHEN 1 THEN 
						CASE WHEN ISNULL(f.cid,-1) IN (-1,0) THEN
							(CASE a.ratetype 
								WHEN 0 THEN a.lendloan / a.rate
								WHEN 1 THEN a.lendloan * a.rate
							END)
						ELSE
							(CASE g.BasisType
								WHEN 0 THEN a.lendloan / g.rate
								WHEN 1 THEN a.lendloan * g.rate
							END)
						END
				ELSE 0 
			END AS jiefor,
			CASE c.Fdc 
				WHEN -1 THEN
						CASE WHEN ISNULL(f.cid,-1) IN (-1,0) THEN
							(CASE a.ratetype 
								WHEN 0 THEN a.lendloan / a.rate
								WHEN 1 THEN a.lendloan * a.rate
							END)
						ELSE
							(CASE g.BasisType
								WHEN 0 THEN a.lendloan / g.rate
								WHEN 1 THEN a.lendloan * g.rate
							END)
						END
				ELSE 0 
			END AS daifor,
			'' AS FCashFlowItem,
			'' AS ascids,
			'' AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			CASE WHEN ISNULL(f.cid,-1) IN(-1,0) THEN BB.Cid ELSE f.cid END AS cid,
			CASE WHEN ISNULL(f.cid,-1) IN(-1,0) THEN a.rate ELSE g.Rate END AS rate,
			c.Fdc AS fadc,
			@verifyidvalue AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			c.AtdId,
			A.billnumberid--单据ID
	FROM	#TmpItemAtypeMoney a
	INNER JOIN #TmpBillInfo BB ON A.billnumberid = BB.BillNumberId
	INNER JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId 
	LEFT JOIN dbo.Ac_Account f ON a.ATypeId = f.TypeId AND f.StypeId = @verifyidvalue
	LEFT JOIN dbo.Ac_Currency g ON f.Cid = g.CId
	

	
	--业务凭证对应科目生成凭证明细
	SELECT AtdId,Express,BB.Rate AS rate,BB.RateType AS ratetype,BB.BillNumberId AS billnumberid
	INTO #tmpJDItemDetail
	FROM dbo.Ac_Auditing_Template_Detail T
	INNER JOIN #TmpBillInfo BB ON BB.AtId = T.Atid
	WHERE AcFrom IN (6,7)

	
	INSERT INTO #tmpAccountCredence
		(
			billnumberid,
			TypeAtypeID,
			j_total,
			d_total,
			cid,
			ratetype,
			rate,
			ATypeID
		)
	SELECT a.BillNumberId,TypeAtypeId,
			SUM(CASE WHEN b.RedWord = 2 THEN -J_Total ELSE J_Total END) AS j_total,
			0 AS d_total,
			a.cid,
			c.BasisType,
			c.Rate,
			a.ATypeID
	FROM	dbo.AccountCredence a
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberID
	INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
	INNER JOIN dbo.Ac_Currency c ON a.CID = c.CId
	--WHERE	a.BillNumberId =@currentid
	GROUP BY a.BillNumberId,TypeAtypeId,a.cid,c.BasisType,c.Rate,a.ATypeID
	UNION ALL
	SELECT a.BillNumberId,TypeAtypeId,
			0 AS j_total,
			SUM(CASE WHEN B.RedWord = 2 THEN -D_Total ELSE D_Total END) AS d_total,
			a.cid,
			c.BasisType,
			c.Rate,
			a.ATypeID
	FROM	dbo.AccountCredence a
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberID
	INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
	INNER JOIN dbo.Ac_Currency c ON a.CID = c.CId
	--WHERE	a.BillNumberId =@currentid
	GROUP BY a.BillNumberId,TypeAtypeId,a.cid,c.BasisType,c.Rate,a.ATypeID

	DELETE FROM #tmpAccountCredence WHERE j_total = 0 AND d_total = 0


	INSERT INTO #TmpVoucherBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  atdid,
			  credenceId,
			  BillIndexId
			)
	SELECT DISTINCT * FROM
	(
	SELECT	@VoucherId AS billnumberid,
			c.Summary AS explain,
			e.ATypeId AS atypeid,
			'' AS atypeid2,
			f.Fdc ,
			@f_exchid AS f_exchid,
			CASE WHEN ISNULL(f.cid,-1) IN (-1,0) THEN b.cid ELSE f.cid END AS f_exchidfor,
			CASE c.Fdc
				WHEN 1	THEN b.j_total
				WHEN -1 THEN 0
			END AS lendprice,
			CASE c.Fdc
				WHEN -1 THEN b.d_total
				WHEN 1	THEN 0
			END AS loanprice,
			CASE c.Fdc 
				WHEN 1 THEN 
						(CASE WHEN ISNULL(f.cid,-1) IN (-1,0) THEN
							CASE b.ratetype
							WHEN 0 THEN b.j_total / b.rate
							WHEN 1 THEN b.j_total * b.rate
							END
							ELSE
							CASE b.ratetype
							WHEN 0 THEN b.j_total / g.rate
							WHEN 1 THEN b.j_total * g.rate
							END
						END)
				ELSE 0 
			END AS lendpricefor,
			CASE c.Fdc 
				WHEN -1 THEN
						(CASE WHEN ISNULL(f.cid,-1) IN (-1,0) THEN
							CASE b.ratetype  
								WHEN 0 THEN b.d_total / b.rate
								WHEN 1 THEN b.d_total* b.rate
							END
							ELSE
							CASE b.ratetype  
								WHEN 0 THEN b.d_total / g.rate
								WHEN 1 THEN b.d_total* g.rate
							END
						END)
				ELSE 0 
			END AS loanpricefor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			CASE WHEN ISNULL(f.cid,-1) IN (-1,0) THEN b.cid ELSE f.cid END AS cid,
			b.rate,
			c.Fdc AS fadc,
			@verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId,
			b.id,
			b.billnumberid AS billid
	FROM	#tmpJDItemDetail a
	INNER JOIN #tmpAccountCredence b ON b.BillNumberId IN (SELECT * FROM f_split(a.billnumberid,','))
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.billnumberid
	LEFT JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	LEFT JOIN dbo.Ac_Items d ON b.TypeAtypeId = d.nid
	LEFT JOIN dbo.Ac_Items_Detail e ON d.nId = e.nId AND e.STypeId = BB.StypeId
	LEFT JOIN dbo.Ac_Account f ON e.ATypeId = f.TypeId AND f.StypeId = @verifyidvalue
	LEFT JOIN dbo.Ac_Currency g ON f.Cid = g.CId
	) T 
	WHERE lendprice <> 0 OR loanprice <> 0
	
	/*
	处理存货类型
	15-存货
	16-收入
	17-成本
	*/
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AcFrom IN(15,16,17))
	BEGIN
		CREATE TABLE #InventoryTypeAccount
		(
			atdid	INT
			,atypeid	VARCHAR(50)
			,billnumberid	NUMERIC(10,0)
			,lendloan		NUMERIC(24,10)
			,lendloanfor	 NUMERIC(24, 10) ,
			rate		 NUMERIC(24, 10) ,
			ratetype	INT,
			iscost		INT DEFAULT 0
		)
		
		CREATE TABLE #BillDetailsInventoryTypeAccount
		(
			billnumberid	NUMERIC(10,0)
			,PTYPEID	VARCHAR(50)
			,TID		INT
			,stypeid	VARCHAR(50)
			,CostATypeID	VARCHAR(50)
			,IncomeATypeID	VARCHAR(50)
			,StockATypeID	VARCHAR(50)
			,total		NUMERIC(24,10)
			,costtotal	NUMERIC(24,10)
			,taxtotal	NUMERIC(24,10)
			,totalfor		NUMERIC(24,10)
			,costtotalfor	NUMERIC(24,10)
			,taxtotalfor	NUMERIC(24,10)
			,sharefee	NUMERIC(24,10)
			,sharefeefor	NUMERIC(24,10)
		)
		
		CREATE TABLE #InOutstocktableSUM
		(
			BillNumberId	NUMERIC(10,0)
			,Ptypeid		VARCHAR(50)
			,Total			NUMERIC(24,10)
			,CostTotal		NUMERIC(24,10)
			,nTaxTotal		NUMERIC(24,10)	
			,sharefee		NUMERIC(24,10)	
		)
		
		INSERT INTO #InOutstocktableSUM
		(
			BillNumberId
			,Ptypeid
			,CostTotal
			,Total
			,nTaxTotal
			,sharefee
		)
		SELECT	I.BillNumberId
				,I.PtypeId
				,SUM(I.CostTotal)
				,SUM(I.Total)
				,SUM(I.NTaxTotal)
				,0
		FROM	InOutstocktable I
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = I.BillNumberId AND B.StypeId = I.STypeID AND i.BillType=@BillType
		GROUP BY I.BillNumberId,I.PtypeId
		UNION ALL
		SELECT	S.BillNumberId
				,BUY.PtypeId
				,0
				,0
				,0
				,SUM(S.ShareFee)
		FROM	sharesourcebill S
		INNER JOIN #TmpBillInfo B ON B.BillNumberId = S.BillNumberId
		INNER JOIN BuyBill BUY ON BUY.BillNumberId = S.FromBillNumberID AND BUY.ID = S.FromBillID AND s.FromBillType=34
		GROUP BY S.BillNumberId,BUY.PtypeId
		UNION ALL
		SELECT	S.BillNumberId
				,BUY.PtypeId
				,0
				,0
				,0
				,SUM(S.ShareFee)
		FROM	sharesourcebill S
		INNER JOIN #TmpBillInfo B ON B.BillNumberId = S.BillNumberId
		INNER JOIN disassemblebill BUY ON BUY.BillNumberId = S.FromBillNumberID AND BUY.ID = S.FromBillID AND s.FromBillType=16
		GROUP BY S.BillNumberId,BUY.PtypeId
		

		
		INSERT INTO #BillDetailsInventoryTypeAccount
			(
				billnumberid
				,PTYPEID
				,stypeid
				,TID
				,CostATypeID
				,IncomeATypeID
				,StockATypeID
				,total
				,costtotal
				,taxtotal
				,totalfor
				,costtotalfor
				,taxtotalfor	
				,sharefee
				,sharefeefor
			)
		SELECT	T.BillNumberId
				,T.Ptypeid
				,B.Stypeid
				,PIT.InventoryTypeid
				,BITD.CostATypeID
				,BITD.IncomeATypeID
				,BITD.StockATypeID
				,CASE WHEN B.AdPriceType = 2 THEN -T.Total ELSE T.Total	END --折后金额
				,CASE WHEN @BillType = 57 AND B.AdPriceType = 2 THEN -t.CostTotal  WHEN @BillType = 57 THEN t.CostTotal ELSE ABS(T.CostTotal) END	--成本金额
				,CASE WHEN B.AdPriceType = 2 THEN -T.nTaxTotal ELSE T.nTaxTotal END	--价税合计
				,CASE WHEN B.AdPriceType = 2 THEN -T.Total ELSE T.Total END	--折后金额
				,CASE WHEN @BillType = 57 AND B.AdPriceType = 2 THEN -t.CostTotal  WHEN @BillType = 57 THEN t.CostTotal ELSE ABS(T.CostTotal) END	--成本金额
				,CASE WHEN B.AdPriceType = 2 THEN -T.nTaxTotal ELSE T.nTaxTotal END	--价税合计
				,T.sharefee
				,T.sharefee
				
		FROM #InOutstocktableSUM T
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
		INNER JOIN	ptype PIT ON PIT.typeid = T.PtypeId
		INNER JOIN	Base_InventoryTypeDetails BITD ON BITD.TID = PIT.InventoryTypeid AND BITD.STypeID = B.Stypeid
		
		DECLARE @AcFromLoop	INT
				
		SET @AcFromLoop = 14
		
		SET @sql = 'insert into #InventoryTypeAccount 
				(
					atdid
					,atypeid
					,lendloan
					,lendloanfor
					,rate
					,ratetype
					,billnumberid
					,iscost
				)
				select atdid
					,atypeid
					,lendloan
					,lendloanfor
					,rate
					,ratetype
					,billnumberid
					,iscost 
				from('
				
		WHILE @AcFromLoop <=17
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AcFrom = @AcFromLoop)
			BEGIN
				SET @AcFromLoop += 1
				CONTINUE
			END
				
			SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId
				,'+CASE @AcFromLoop WHEN 15 THEN 'StockATypeID' WHEN 16 THEN 'IncomeATypeID' ELSE 'CostATypeID' END +' as atypeid
				, sum('+ T2.Express +') as lendloan
				,0 as lendloanfor
				,b.rate
				,b.ratetype
				,a.billnumberid
				,0 as iscost
			from #BillDetailsInventoryTypeAccount a
			inner join (select billnumberid,rate,ratetype from #TmpBillInfo) b on b.billnumberid = a.billnumberid
			group by a.billnumberid,'+CASE @AcFromLoop WHEN 15 THEN 'StockATypeID' WHEN 16 THEN 'IncomeATypeID' ELSE 'CostATypeID' END +',b.rate,b.ratetype union all '
			FROM #TmpVoucherDetails T1
			INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
			WHERE  AcFrom = @AcFromLoop
			SET @AcFromLoop += 1
		END
		
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
		SET @sql += ')T'
		EXEC(@sql)
		--select * from #BillDetailsInventoryTypeAccount
		--select * from #InventoryTypeAccount
		INSERT INTO #TmpVoucherBill
				( billnumberid ,
				  explain ,
				  atypeid ,
				  atypeid2 ,
				  Fdc ,
				  f_exchid ,
				  f_exchidfor ,
				  lendprice ,
				  loanprice ,
				  lendpricefor ,
				  loanpricefor ,
				  FCashFlowItem ,
				  ascids ,
				  FSettleNo ,
				  FSettleTypeID ,
				  comment ,
				  cid ,
				  rate ,
				  fadc ,
				  stypeid ,
				  fyear ,
				  fperiod,
				  atdid,
				  credenceId,
				  BillIndexId
				)
		SELECT DISTINCT * FROM
		(
		SELECT	@VoucherId AS billnumberid
				,c.Summary AS explain,
				a.ATypeId AS atypeid,
				'' AS atypeid2,
				Ac.Fdc 
				,@f_exchid AS f_exchid
				,BB.Cid AS f_exchidfor
				,CASE c.Fdc
					WHEN 1	THEN a.lendloan
					WHEN -1 THEN 0
				END AS jie,
				CASE c.Fdc
					WHEN -1 THEN a.lendloan
					WHEN 1	THEN 0
				END AS dai,
				CASE WHEN c.Fdc = 1 THEN 
							(CASE a.ratetype 
								WHEN 0 THEN a.lendloan / A.rate
								WHEN 1 THEN a.lendloan * A.rate
							END)
					ELSE 0 
				END AS jiefor,
				CASE WHEN c.Fdc = -1 THEN
							(CASE a.ratetype  
								WHEN 0 THEN a.lendloan / A.rate
								WHEN 1 THEN a.lendloan* A.rate
							END)
					ELSE 0 
				END AS daifor,
				NULL AS FCashFlowItem,
				'' AS ascids,
				NULL AS FSettleNo,
				0 AS FSettleTypeID,
				'' AS comment,
				BB.Cid AS cid,
				a.rate,
				c.Fdc AS fadc,
				@verifyid AS stypeid,
				@fyear AS fyear,
				@fperiod AS fperiod,
				a.AtdId,
				0 as credenceId,
				BB.billnumberid AS billid
		FROM	#InventoryTypeAccount a
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.billnumberid
		INNER JOIN Ac_Account AC ON AC.StypeId = BB.VerifyStypeid AND AC.TypeId = A.atypeid
		LEFT JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
		) T 
		WHERE jie <> 0 OR dai <> 0
		
		DROP TABLE #BillDetailsInventoryTypeAccount,#InventoryTypeAccount
	END
	
	--Awu:调整平衡数
	DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) 

	DECLARE BalanceCur CURSOR FOR
	SELECT billnumberid FROM #tmpbillinfo
		OPEN BalanceCur
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @balancemoney = 0
		SELECT @balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
		FROM #TmpVoucherBill
		WHERE billindexid = @BalanceBillId
		
		
		UPDATE #TmpVoucherBill 
		SET #TmpVoucherBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
			#TmpVoucherBill.lendpricefor = (CASE fadc WHEN 1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN -@balancemoney / T3.rate
												WHEN 1 THEN -@balancemoney * T3.rate
											END
									ELSE 0 END ),
			#TmpVoucherBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
			#TmpVoucherBill.loanpricefor = (CASE fadc WHEN -1 THEN 
											CASE T3.BasisType
												WHEN 0 THEN @balancemoney / T3.rate
												WHEN 1 THEN @balancemoney * T3.rate
											END
									ELSE 0 END )
		FROM #TmpVoucherBill T1
			INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
			INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
		WHERE billindexid = @BalanceBillId
			
		FETCH NEXT FROM BalanceCur INTO @BalanceBillId
	END
	CLOSE BalanceCur
	DEALLOCATE BalanceCur
	
	--获取明细对应辅助核算
	SET @sql = 'INSERT INTO #TmpAssit '
	SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'+
				CAST(T2.FieldValue AS VARCHAR(20))+' AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,
				(SELECT name FROM syscolumns WHERE id = object_id(''billindex'') AND name = '''+
				T2.fieldvalue + ''')as fieldname,BillNumberId AS BillIndexNumberId,0 as credenceid
				FROM #TmpBillInfo UNION ALL '
	FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
		LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
	WHERE T1.Atid = @Atid
	IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
		EXEC(@sql)
	END

	--业务凭证辅助核算有部分来源于单据明细中，
	--调整业务凭证的辅助核算
	IF @Billtype = 159
	BEGIN
		INSERT INTO #tmpassit
		SELECT a.atdid,a.typeid,a.ascids,a.fieldname,a.billindexnumberid,B.credenceid
		FROM #Tmpassit a
			INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid
			
		--WHERE a.billindexnumberid = @currentid
		DELETE FROM #tmpassit WHERE credenceid = 0
		
	
		UPDATE #Tmpassit SET typeid = c.Atypeid
		FROM #Tmpassit a
		INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.credenceid = b.credenceid
		INNER JOIN #tmpAccountCredence c ON b.credenceid = c.id AND a.billindexnumberid = c.billnumberid
		INNER JOIN dbo.Ac_Items d ON c.TypeAtypeid = d.nId AND d.UserCode = '1132'
		WHERE fieldname = 'Stypeid'
		
		UPDATE #Tmpassit SET typeid = e.denominatedid
		FROM #Tmpassit a
		INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.credenceid = b.credenceid
		INNER JOIN #tmpAccountCredence c ON b.credenceid = c.id AND a.billindexnumberid = c.billnumberid
		INNER JOIN dbo.Ac_Items d ON c.TypeAtypeid = d.nId AND d.UserCode IN ('1151','987','2121','2131')
		INNER JOIN dbo.btype e ON c.Atypeid = e.typeId
		WHERE fieldname = 'btypeid'
		
		UPDATE #Tmpassit SET typeid = c.Atypeid
		FROM #Tmpassit a
		INNER JOIN #TmpVoucherBill b ON a.atdid = b.atdid AND a.billindexnumberid = b.billindexid AND a.credenceid = b.credenceid
		INNER JOIN #tmpAccountCredence c ON b.credenceid = c.id AND a.billindexnumberid = c.billnumberid
		INNER JOIN dbo.Ac_Items d ON c.TypeAtypeid = d.nId AND d.UserCode IN ('1151','987','2121','2131')
		WHERE fieldname = 'DealBTypeID'
	END

--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)
INSERT INTO #TmpDetailsAssit
SELECT DISTINCT T1.atdid,T1.rowno,T3.ascids,T3.typeid
FROM #TmpVoucherBill T1
	INNER JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	INNER JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId AND ISNULL(T1.credenceid,0) = ISNULL(T3.credenceid,0)
WHERE ISNULL(T3.ascids,'') <> ''

DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpVoucherBill 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #TmpVoucherBill SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END


--排除数据全为0的单据编号
SELECT DISTINCT BillIndexId
INTO #TmpBillNumberId
FROM #TmpVoucherBill WHERE lendprice <> 0 OR loanprice <> 0






--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)

IF @Billtype = 159

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT *
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	lendprice	AS Lend,
	loanprice	AS Loan,
	lendpricefor AS LendFor,
	loanpricefor AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmpVoucherBill
)T
WHERE Lend <> 0 OR Loan <> 0

ELSE

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT T.*
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	SUM(lendprice)	AS Lend,
	SUM(loanprice)	AS Loan,
	SUM(lendpricefor) AS LendFor,
	SUM(loanpricefor) AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmpVoucherBill
GROUP BY BillNumberId,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.OrderID,T.fadc,AC.UserCode

--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT *
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit


INSERT INTO #TmpDetailsAssit
SELECT DISTINCT 0,T1.rowno,T3.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''


--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END


DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)

--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
          explain ,
          stypeid ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill


--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails 
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END

--插入辅助
INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
        ( BillNumberId ,
          vBId ,
          typeName ,
          TypeId
        )
SELECT @VoucherId,T2.id,T3.UserCode,T1.typeid
FROM #TmpDetailsAssit T1
	INNER JOIN #TmpDetailsRow T2 ON T1.rowno = T2.rowno
	INNER JOIN dbo.Ac_Assist_CheckItems T3 ON T1.ascids = T3.AscIds

--再一次调整合并

--修正明细辅助核算
--更新凭证明细中辅助核算字段值信息
--SELECT * FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
--UPDATE dbo.Ac_Voucher_Bill SET AscIds= dbo.F_Get_VoucherAscids(id,1) WHERE BillNumberId = @VoucherId

--SELECT * FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId

--合并信息相同的明细，采用合并插入后再删除原来的凭证--
DECLARE @newVoucherId INT --临时BillNumberId
SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

SELECT	billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FCreditTotal,
		FDebitTotalFor,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		IDENTITY(INT,1,1) AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill
FROM
(
SELECT  @newVoucherId AS billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		SUM(FDebitTotal) AS FDebitTotal,
		SUM(FCreditTotal) AS FCreditTotal,
		SUM(FDebitTotalFor) AS FDebitTotalFor,
		SUM(FCreditTotalFor) AS FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod,
		MIN(rowno) AS initRowno
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @VoucherId
GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod
)TT
ORDER BY initRowno



--用于记录明细ID，插入辅助核算使用
CREATE TABLE #tmpId
(
	id INT,
	rowno INT,
	ascids VARCHAR(500)
)

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo,INSERTED.AscIds INTO #tmpId
SELECT  billnumberid,
        CASE 
			WHEN LTRIM(RTRIM(Summary))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(Summary)),1) = ';' THEN LEFT(LTRIM(RTRIM(Summary)),LEN(LTRIM(RTRIM(Summary)))-1)
			ELSE LTRIM(RTRIM(Summary))
		END ,
		STypeId ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FDebitTotalFor,
		FCreditTotal,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		FYear ,
		FPeriod,
		Comment ,
		Cid ,
		rowno,
		Rate ,
		FAdc
FROM #tmpNewVoucherBill

--2014.02.08说明：业务凭证合并导致行号不再一致，有可能会出现辅助核算缺失，以下按合并后重写辅助核算表


--更新表头分录数
UPDATE dbo.Ac_Voucher SET FEntryCount = (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId)

--删除旧分录数据
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId

--替换临时BillNumberId为真实的
UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @VoucherId WHERE BillNumberId = @newVoucherId
--------合并完成--------- 

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #TmpBillInfo,#TmpExpress,#TmpDetailsMoney,#TmpVoucherBill,#tmpBillIndexAtype,#TmpItemDetail,#TmpAssit,#TmpDetailsAssit,#TmpNewBill,#TmpDetailsRow
DROP TABLE #tmpNewVoucherBill,#BillNumberId

RETURN @VoucherId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.02.22
	描述：经营历程中生成凭证时，处理收付款单凭证的生成。
			核算机构相同的才能合并在一张凭证内
			此处处理的已是可合并在一起的单据
			明细信息完全相同的合并为一条
			1.循环处理每张单据，生成凭证明细
			2.判定明细信息是否相同（科目、币种、辅助核算类别）合并明细信息
			3.按单据信息处理明细的辅助核算
			4.调整凭证表头信息
	Addition:2013.07.01 增加处理189，190
			
*/
CREATE PROCEDURE GP_BatchCreateVoucher_PayGatherBill
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@Type			INT	= 0,				-- 生成凭证结果处理方式
	@VoucherId		INT ,
	@szPID			VARCHAR(MAX)	OUTPUT, -- 异常信息描述
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0,					-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID1		VARCHAR(50),
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	Total			 NUMERIC(24, 10) ,		--金额	
	PreferenceMoney	 NUMERIC(24, 10) ,		--优惠金额
	balancemoney	 NUMERIC(24, 10) ,		--平衡数
	RedWord			INT					--红冲标识
	,AtId			INT
	,totalfor			 NUMERIC(24, 10) ,		--原币金额	
	PreferenceMoneyfor	 NUMERIC(24, 10) ,		--原币优惠金额
	balancemoneyfor	 NUMERIC(24, 10) ,		--原币平衡数
)

INSERT INTO #TmpBillInfo
        ( BillNumberId ,
          StypeId ,
          VerifyStypeid ,
          DTypeId ,
          BTypeId ,
          ETypeId,
          DealBTypeId ,
          ATypeID1,
          Cid ,
          Rate ,
          RateType,
          Total,
          PreferenceMoney,
          Totalfor,
          PreferenceMoneyfor,
          RedWord
          ,AtId
        )
SELECT  T1.BillNumberId,
		T1.Stypeid,
		T2.VerifyID,
		T1.DTypeId,
		T1.btypeid,
		T1.etypeid,
		T1.DealBTypeID,
		T1.ATypeID1,
		T1.CID,
		T1.Rate,
		T3.BasisType,
		CASE T1.RedWord WHEN 2 THEN -T1.TotalMoney ELSE T1.totalmoney END,
		CASE T1.RedWord WHEN 2 THEN -T1.preferencemoney ELSE T1.preferencemoney END,
		CASE T1.RedWord WHEN 2 THEN -T1.NTotalMoney ELSE T1.NTotalMoney END,
		CASE T1.RedWord WHEN 2 THEN -T1.NPreferenceMoney ELSE T1.NPreferenceMoney END,
		T1.RedWord
		,@AtId
FROM dbo.BillIndex T1
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
WHERE T1.BillNumberId IN (SELECT a FROM #BillNumberId)

DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

DECLARE @flag INT,--是否有异常
		@AutoFlag INT --即时生成异常
SET @flag = 0
SET @AutoFlag = 0

--将模板明细处理到临时表中,进行读取字段生成摘要
-----------------------------------------------
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''

SELECT @MinNumber = MIN(a) FROM #BillNumberId
SELECT @MaxNumber = MAX(a) FROM #BillNumberId

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	RowNo		INT IDENTITY(1,1),
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		--SET @Index += 1
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr
	
	IF @str <> ''
		SET @str += ';'
		
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	--SET @MinDid += 1
	
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END

-----------------------
--处理摘要完成


--手工和往来对应的模板信息
CREATE TABLE #TmpExpress
(
	Atdid			INT,
	Lendloan		 NUMERIC(24, 10) ,
	Lendloanfor		 NUMERIC(24, 10) ,
	Rate			 NUMERIC(24, 10) ,
	Ratetype		INT,
	iscost			INT
	,billnumberid	INT
)

--手工及往来科目信息
CREATE TABLE #TmpBillIndexAtype
(
	Atypeid		VARCHAR(50),
	UserCode	VARCHAR(50),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Atdid		INT
	,billnumberid	INT
)

--科目来源“收付款项目”模板明细
CREATE TABLE #TmpItemDetail
(
	AtdId				INT,			--模板明细ID
	Express				VARCHAR(1000),	--金额表达式
	Rate				 NUMERIC(24, 10) ,	--汇率
	Ratetype			INT,			--汇率计算方式
	BillIndexNumberid	INT				--单据编号
)

--收付款表体金额明细
CREATE TABLE #TmpDetailsMoney
(
	BillIndexNumberId	INT,
	AtypeId				VARCHAR(50),
	Total				 NUMERIC(24, 10) ,
	Totalfor				 NUMERIC(24, 10) 
)

--凭证明细临时表,存储所有单据生成的凭证明细
CREATE TABLE #TmpVoucherBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	AtdId			INT,
	BillIndexId		INT
)

--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	BillIndexNumberId	INT				--单据ID
)

DECLARE 
		--@BillCount	INT,--单据总数
		--@CurrentID	INT,--当前单据ID
		--@RateValue	 NUMERIC(24, 10) ,--汇率值
		--@Ratetype	INT,	--汇率计算方式
		--@STypeidValue	VARCHAR(50),--分支机构
		@VerifyidValue	VARCHAR(50)--核算机构
		--@ATypeId1		VARCHAR(50),--往来科目
		--@cidvalue		INT
		,@IsUseBillMoneyDate INT
		,@UseBillMoneyDate_BillTypes VARCHAR(500)
		,@BillCid	INT
		
SELECT TOP 1 @VerifyidValue = VerifyStypeid  FROM #TmpBillInfo

SELECT TOP 1 @BillCid = Cid FROM #TmpBillInfo
SELECT @UseBillMoneyDate_BillTypes=SubValue  FROM sysdata WHERE SubName = 'usebillmoneydate'

SET @IsUseBillMoneyDate = 0
IF EXISTS (SELECT TOP 1 1 FROM F_Split(@UseBillMoneyDate_BillTypes,',') WHERE a = @BillType)
	SET @IsUseBillMoneyDate = 1


DECLARE	@sql VARCHAR(MAX)
	
	
	--往来科目信息
	INSERT INTO #TmpBillIndexAtype
			( Atypeid ,
			  UserCode ,
			  Fullname ,
			  Fdc ,
			  Atdid 
			  ,billnumberid
			)
	SELECT	b.typeId,
		b.UserCode,
		b.FullName,
		Fdc,
		@Atdid
		,BB.BillNumberId
	FROM dbo.Ac_Account b
	INNER JOIN #TmpBillInfo BB ON BB.ATypeID1=B.TypeId AND BB.VerifyStypeid = B.StypeId
	--WHERE b.TypeId=@atypeid1 AND b.StypeId = @verifyidvalue

	--无往来科目，补空白
	IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpBillIndexAtype)
	BEGIN
		INSERT INTO #TmpBillIndexAtype
				( atypeid ,
				  usercode ,
				  fullname ,
				  fdc ,
				  atdid
				  ,billnumberid
				)
		SELECT '','','',0,@AtdId,BillNumberId
		FROM #TmpBillInfo
	END
	
	
	--处理手工选择科目信息
	INSERT INTO #TmpBillIndexAtype
			( Atypeid ,
			  UserCode ,
			  Fullname ,
			  Fdc ,
			  Atdid
			  ,billnumberid
			)
	SELECT T2.TypeId,T2.UserCode,T2.FullName,T2.Fdc,T1.Atdid,bb.BillNumberId
	FROM dbo.Ac_Auditing_Template_Detail T1
	INNER JOIN #TmpBillInfo BB ON bb.AtId = t1.Atid
	INNER JOIN dbo.Ac_Account T2 ON T1.ATypeId = T2.TypeId AND T2.StypeId = @Verifyid
	WHERE T1.AcFrom = 1
	
	----处理科目来源为手工和往来的
	SET @sql = 'insert into #tmpExpress'
	SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,('+ Express +') as lendloan,'+CASE WHEN @IsUseBillMoneyDate = 1 THEN dbo.F_ChangeToOriginalCurrency(Express)  ELSE '0' END +' as lendloanfor,rate,ratetype,'+CASE WHEN dbo.F_ChangeToOriginalCurrency(Express) = '0' THEN '1' ELSE '0' END+' as iscost
		,billnumberid
		from #TmpBillInfo  union all '
		FROM Ac_Auditing_Template_Detail WHERE Atid = @Atid AND (AcFrom = 1 OR AcFrom = 3)
	IF LEN(@sql) > LEN('insert into #tmpExpress')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
		EXEC(@sql)
	END
	
	
	--插入凭证明细
	INSERT INTO #TmpVoucherBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  AtdId,
			  BillIndexId
			)
	SELECT	@VoucherId AS billnumberid,
			T1.Summary,
			T3.Atypeid,
			'',
			T3.Fdc,
			@f_exchid,
			BB.Cid,
			CASE T1.Fdc
				WHEN 1 THEN T2.Lendloan
				ELSE 0
			END,
			CASE T1.Fdc
				WHEN -1 THEN T2.Lendloan
				ELSE 0
			END,
			CASE  WHEN T1.Fdc = 1 AND @IsUseBillMoneyDate = 1 AND (T4.Cid = @BillCid OR T4.Cid = 0) THEN T2.Lendloanfor
				  WHEN T1.Fdc = 1  THEN 
					CASE 
						WHEN T4.cid IN(-1,0) THEN
							CASE T2.Ratetype 
								WHEN 0 THEN T2.Lendloan /T2.Rate
								ELSE T2.Lendloan * T2.Rate
							END
						ELSE
							CASE T5.BasisType 
								WHEN 0 THEN T2.Lendloan /T5.Rate
								ELSE T2.Lendloan * T5.Rate
							END
					END
				ELSE 0 
			END,
			CASE WHEN T1.Fdc = -1 AND @IsUseBillMoneyDate = 1 AND (T4.Cid = @BillCid OR T4.Cid = 0)  THEN T2.Lendloanfor
				 WHEN T1.Fdc = -1  THEN
					CASE 
						WHEN T4.cid IN (-1,0) THEN
							CASE T2.Ratetype 
								WHEN 0 THEN T2.Lendloan /T2.Rate
								ELSE T2.Lendloan * T2.Rate
							END
						ELSE
							CASE T5.BasisType 
								WHEN 0 THEN T2.Lendloan /T5.Rate
								ELSE T2.Lendloan * T5.Rate
							END
					END
				ELSE 0 
			END,
			'',
			'',
			'',
			'',
			'',
			CASE  WHEN T4.Cid IN(-1,0) THEN BB.Cid ELSE T4.Cid END,
			CASE  WHEN T4.Cid IN(-1,0) THEN T2.Rate ELSE T5.Rate END,
			T1.Fdc,--模板金额方向
			@VerifyIdValue,
			@Fyear,
			@Fperiod,
			T1.AtdId,
		    BB.BillNumberId
	FROM #TmpVoucherDetails T1
		INNER JOIN #TmpExpress T2 ON T1.AtdId = T2.Atdid
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = T2.billnumberid
		LEFT JOIN #TmpBillIndexAtype T3 ON T2.Atdid =T3.Atdid AND T3.billnumberid = T2.billnumberid
		LEFT JOIN dbo.Ac_Account T4 ON T3.Atypeid = T4.TypeId AND T4.StypeId = @verifyidvalue
		LEFT JOIN dbo.Ac_Currency T5 ON T4.Cid = T5.CId
	WHERE T1.Atid = @Atid AND T1.AcFrom IN (1,3)
	
	----生成科目来源为收付款项目的模板信息
	INSERT INTO #TmpItemDetail
			(AtdId,
			Express,
			rate,
			ratetype,
			BillIndexNumberid)
	SELECT AtdId,Express,BB.Rate AS rate,BB.RateType AS ratetype,BB.BillNumberId AS billnumberid
	FROM dbo.Ac_Auditing_Template_Detail T
	INNER JOIN #TmpBillInfo BB ON BB.AtId =T.Atid 
	WHERE AcFrom = 2
	
	--获取表体对应的明细金额
	IF @BillType = 4
		INSERT INTO #TmpDetailsMoney( BillIndexNumberId, AtypeId, Total,Totalfor )
		SELECT T2.BillNumberId,T1.AtypeId,SUM(CASE WHEN T2.RedWord = 2 THEN -t1.total ELSE t1.total END) AS total,SUM(CASE WHEN T2.RedWord = 2 THEN -t1.ntotal ELSE t1.ntotal END) AS totalfor
		FROM dbo.gatheringBill T1
			INNER JOIN #TmpBillInfo T2 ON T1.BillNumberId = T2.BillNumberId 
		GROUP BY T2.BillNumberId, T1.AtypeId,T1.Stypeid
	ELSE IF @BillType = 66
		INSERT INTO #TmpDetailsMoney( BillIndexNumberId, AtypeId, Total,Totalfor )
		SELECT T2.BillNumberId,T1.AtypeId,SUM(CASE WHEN T2.RedWord = 2 THEN -t1.total ELSE t1.total END) AS total,SUM(CASE WHEN T2.RedWord = 2 THEN -t1.ntotal ELSE t1.ntotal END) AS totalfor
		FROM dbo.PayBill T1
			INNER JOIN #TmpBillInfo T2 ON T1.BillNumberId = T2.BillNumberId 
		GROUP BY T2.BillNumberId, T1.AtypeId,T1.Stypeid
	ELSE IF @BillType IN (189,190)
		INSERT INTO #TmpDetailsMoney( BillIndexNumberId, AtypeId, Total )
		SELECT T2.BillNumberId,T1.AtypeId,SUM(CASE WHEN T2.RedWord = 2 THEN -t1.total ELSE t1.total END) AS total
		FROM dbo.PreBill T1
			INNER JOIN #TmpBillInfo T2 ON T1.BillNumberId = T2.BillNumberId 
		GROUP BY T2.BillNumberId, T1.AtypeId,T1.Stypeid
		
	--插入临时表凭证明细
	INSERT INTO #TmpVoucherBill
	        ( BillNumberId ,
	          explain ,
	          atypeid ,
	          atypeid2 ,
	          Fdc ,
	          f_exchid ,
	          f_exchidfor ,
	          lendprice ,
	          loanprice ,
	          lendpricefor ,
	          loanpricefor ,
	          FCashFlowItem ,
	          ascids ,
	          FSettleNo ,
	          FSettleTypeID ,
	          comment ,
	          cid ,
	          rate ,
	          fadc ,
	          stypeid ,
	          fyear ,
	          fperiod,
	          AtdId,
	          BillIndexId
	        )
	SELECT	@VoucherId AS billnumberid,c.Summary AS explain,
			e.ATypeId AS atypeid,
			'' AS atypeid2,
			f.Fdc ,@f_exchid AS f_exchid,CASE WHEN ISNULL(f.Cid,0) IN(-1,0) THEN bb.Cid ELSE f.Cid END AS f_exchidfor,
			CASE c.Fdc
				WHEN 1	THEN b.total
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN b.total
				WHEN 1	THEN 0
			END AS dai,
			CASE WHEN c.Fdc = 1 AND @IsUseBillMoneyDate = 1 AND (F.Cid = @BillCid OR f.Cid = 0)  THEN b.Totalfor
				 WHEN c.Fdc = 1  THEN 
						CASE WHEN ISNULL(f.Cid,0) IN(-1,0) THEN
							(CASE a.ratetype 
								WHEN 0 THEN b.total / a.rate
								WHEN 1 THEN b.total * a.rate
							END)
						ELSE
							(CASE g.BasisType
								WHEN 0 THEN b.total / g.rate
								WHEN 1 THEN b.total * g.rate
							END)
						END
				ELSE 0 
			END AS jiefor,
			CASE WHEN c.Fdc = -1 AND @IsUseBillMoneyDate = 1 AND (F.Cid = @BillCid OR f.Cid = 0)  THEN b.Totalfor
				 WHEN c.Fdc = -1  THEN
						CASE WHEN ISNULL(f.Cid,0)IN(-1,0) THEN
							(CASE a.ratetype 
								WHEN 0 THEN b.total / a.rate
								WHEN 1 THEN b.total * a.rate
							END)
						ELSE
							(CASE g.BasisType
								WHEN 0 THEN b.total / g.rate
								WHEN 1 THEN b.total * g.rate
							END)
						END
				ELSE 0 
			END AS daifor,
			'' AS FCashFlowItem,
			'' AS ascids,
			'' AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			CASE WHEN ISNULL(f.Cid,0) IN(-1,0) THEN bb.Cid ELSE f.cid END AS cid,
			CASE WHEN ISNULL(f.Cid,0) IN(-1,0) THEN a.rate ELSE g.Rate END AS rate,
			c.Fdc AS fadc,
			@verifyidvalue AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			c.AtdId,
			BB.BillNumberId--单据ID
	FROM	#TmpItemDetail a
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillIndexNumberid
	INNER JOIN #TmpDetailsMoney b ON a.BillIndexNumberid = b.BillIndexNumberId --AND b.BillIndexNumberId = @CurrentID
	INNER JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	INNER JOIN dbo.Ac_Items d ON b.AtypeId = d.nid
	LEFT JOIN dbo.Ac_Items_Detail e ON d.nId = e.nId AND e.STypeId = BB.StypeId
	LEFT JOIN dbo.Ac_Account f ON e.ATypeId = f.TypeId AND f.StypeId = BB.VerifyStypeid
	LEFT JOIN dbo.Ac_Currency g ON f.Cid = g.CId
	
	
	--获取明细对应辅助核算
	SET @sql = 'INSERT INTO #TmpAssit '
	SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'+
				CAST(T2.FieldValue AS VARCHAR(20))+' AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids, billnumberid AS BillIndexNumberId
				FROM #TmpBillInfo UNION ALL '
	FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
		LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
	WHERE T1.Atid = @Atid
	IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
		EXEC(@sql)
	END



--调整平衡数
DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) ,@balancemoneyfor  NUMERIC(24, 10) 

DECLARE BalanceCur CURSOR FOR
		SELECT billnumberid FROM #Tmpbillinfo
			OPEN BalanceCur
			FETCH NEXT FROM BalanceCur INTO @BalanceBillId
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @balancemoney = 0
			SELECT @balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
				   ,@balancemoneyfor = SUM(CASE fadc WHEN 1 THEN lendpricefor ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanpricefor ELSE 0 END)
			FROM #TmpVoucherBill
			WHERE billindexid = @BalanceBillId
			
			
			UPDATE #TmpVoucherBill 
			SET #TmpVoucherBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
				#TmpVoucherBill.lendpricefor = (CASE  WHEN fadc = 1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor
												WHEN fadc = 1  THEN 
													CASE T3.BasisType
													WHEN 0 THEN -@balancemoney / T3.rate
													WHEN 1 THEN -@balancemoney * T3.rate
												END
										ELSE 0 END ),
				#TmpVoucherBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
				#TmpVoucherBill.loanpricefor = (CASE WHEN fadc = -1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor
												WHEN fadc = -1 THEN 
													CASE T3.BasisType
													WHEN 0 THEN @balancemoney / T3.rate
													WHEN 1 THEN @balancemoney * T3.rate
												END
										ELSE 0 END )
			FROM #TmpVoucherBill T1
				INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
				INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
			WHERE billindexid = @BalanceBillId
				
			FETCH NEXT FROM BalanceCur INTO @BalanceBillId
		END
		CLOSE BalanceCur
		DEALLOCATE BalanceCur



--处理辅助核算
CREATE TABLE #TmpDetailsAssit
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)
INSERT INTO #TmpDetailsAssit
SELECT DISTINCT T1.atdid,T1.rowno,T3.ascids,T3.typeid
FROM #TmpVoucherBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssit T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids AND T1.billindexid = T3.BillIndexNumberId
WHERE ISNULL(T3.ascids,'') <> ''



DECLARE @AssitSql VARCHAR(MAX)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpVoucherBill 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SELECT @AssitSql = @AssitSql + CAST(ascids AS VARCHAR(10)) + ':' + typeid +','
	FROM #TmpDetailsAssit
	WHERE rowno = @CurrentRowNo AND ISNULL(typeid,'')<>''
	ORDER BY Ascids
	
	UPDATE #TmpVoucherBill SET ascids = @AssitSql WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END

--排除数据全为0的单据编号
SELECT DISTINCT BillIndexId
INTO #TmpBillNumberId
FROM #TmpVoucherBill WHERE lendprice <> 0 OR loanprice <> 0


--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT
)

INSERT INTO #TmpNewBill
        ( BillNumberId ,
          explain ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          lendprice ,
          loanprice ,
          lendpricefor ,
          loanpricefor ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          comment ,
          cid ,
          rate ,
          fadc ,
          stypeid ,
          fyear ,
          fperiod,
          atdid
        )
SELECT T.*
FROM
(
SELECT BillNumberId	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	SUM(lendprice)	AS Lend,
	SUM(loanprice)	AS Loan,
	SUM(lendpricefor) AS LendFor,
	SUM(loanpricefor) AS LoanFor,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
FROM #tmpVoucherBill
GROUP BY BillNumberId,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid
)T
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = T.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
WHERE Lend <> 0 OR Loan <> 0
ORDER BY AT.OrderID,T.fadc,AC.UserCode

--生成合并后的辅助核算信息
CREATE TABLE #TmpAssitT
(
	atdid	INT,
	rowno	INT,
	ascids	INT,
	typeid	VARCHAR(50)
)

INSERT INTO #TmpAssitT( atdid, rowno, ascids, typeid )
SELECT *
FROM #TmpDetailsAssit

TRUNCATE TABLE #TmpDetailsAssit



INSERT INTO #TmpDetailsAssit
SELECT DISTINCT 0,T1.rowno,T3.ascids,T3.typeid
FROM #TmpNewBill T1
	LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.ATypeid = T2.ATypeId AND T2.STypeId = @verifyid --AND T2.cid = @f_exchid
	LEFT JOIN #TmpAssitT T3 ON T1.atdid = T3.atdid AND T2.Ascids=T3.ascids 
WHERE ISNULL(T3.ascids,'') <> ''


--更新明细ascids
CREATE TABLE #tmpHasAssit
(
	id	VARCHAR(50)
)

SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #TmpNewBill 

DECLARE @Ascids VARCHAR(1000),@partAscids VARCHAR(60)

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SELECT @Ascids = ascids FROM #TmpNewBill WHERE rowno = @CurrentRowNo
	
	IF ISNULL(@Ascids,'') <> ''
	BEGIN
		DECLARE ascidCur CURSOR FOR
		SELECT a FROM dbo.f_split(SUBSTRING(@Ascids,1,LEN(@ascids)-1),',')
		OPEN ascidCur
		FETCH NEXT FROM ascidCur INTO @partAscids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #tmpHasAssit 
			SELECT a FROM f_split(@partAscids,':')
			
			FETCH NEXT FROM ascidCur INTO @partAscids
		END
		
		DELETE FROM #TmpDetailsAssit WHERE typeid NOT IN (SELECT id FROM #tmpHasAssit) AND rowno = @CurrentRowNo
		TRUNCATE TABLE #tmpHasAssit
		
		CLOSE ascidCur
		DEALLOCATE ascidCur
	END
	
	
	SET @CurrentRowNo += 1
END




DROP TABLE #TmpAssitT

--正式插入
CREATE TABLE #TmpDetailsRow
(
	id		INT,
	rowno	INT
)

--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
SELECT	BillNumberId ,
          CASE 
			WHEN LTRIM(RTRIM(explain))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(explain)),1) = ';' THEN LEFT(LTRIM(RTRIM(explain)),LEN(LTRIM(RTRIM(explain)))-1)
			ELSE LTRIM(RTRIM(explain))
		  END ,
          stypeid ,
          atypeid ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #TmpNewBill

--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #TmpBillInfo,#TmpExpress,#TmpDetailsMoney,#TmpVoucherBill,#tmpBillIndexAtype,#TmpItemDetail,#TmpAssit,#TmpDetailsAssit,#TmpNewBill,#TmpDetailsRow,#TmpVoucherDetails
DROP TABLE #TmpBillNumberId,#BillNumberId

RETURN @VoucherId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：
*/
CREATE PROCEDURE GP_BatchCreateVoucher_ZanGuFaPiao
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@BillType		INT,					-- 单据类型
	@BillDate		DATE,					-- 凭证日期,
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherId		INT = 0,
	@Type			INT = 0,
	@szPID			VARCHAR(MAX)	OUTPUT,	-- 异常信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@JustRep		INT = 0,				-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

DECLARE @_AutoFlag INT --即时生成凭证异常
SET @_AutoFlag = 0

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillIndex
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	NUMERIC(18),				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	atypeid1		VARCHAR(50), --往来科目借
	atypeid2		VARCHAR(50) ---往来科目贷
)

INSERT INTO #TmpBillIndex
        ( BillNumberId ,
          StypeId ,
          VerifyStypeid ,
          DTypeId ,
          BTypeId ,
          ETypeId,
          DealBTypeId ,
          Cid ,
          Rate ,
          RateType
          ,atypeid1
          ,atypeid2
        )
SELECT  T1.BillNumberId,
		T1.Stypeid,
		T2.VerifyID,
		T1.DTypeId,
		T1.btypeid,
		T1.etypeid,
		T1.DealBTypeID,
		T1.CID,
		T1.Rate,
		T3.BasisType
		,T1.AtypeId1
		,T1.AtypeId2
FROM dbo.ReceiptBillIndex T1
INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
INNER JOIN (SELECT a FROM dbo.f_split(@BillNumberId,',')) B ON B.a = T1.BillNumberID

DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillIndex
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1
--------------------------
--将模板明细处理到临时表中,进行读取字段生成摘要
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @_MaxDid INT,@_MinDid INT,@_SqlSummary VARCHAR(MAX),@_MaxNumber INT,@_MinNumber INT,@_Index INT,@_Str VARCHAR(MAX)

SELECT @_MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作
SELECT @_MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作

SELECT @_MinNumber = MIN(BillNumberId) FROM #TmpBillIndex 
SELECT @_MaxNumber = MAX(BillNumberId) FROM #TmpBillIndex 

SET @_Index = @_MinNumber

--记录摘要信息
CREATE TABLE #TempStr
(
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

DECLARE @_flag INT--是否需要用户补足
SET @_flag = 0

WHILE @_MinDid <= @_MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @_MinDid AND SummaryType='')
	BEGIN
		SET @_MinDid += 1
		CONTINUE;
	END
	
	SET @_SqlSummary = ''
	SET @_Str = ''

	WHILE @_Index <= @_MaxNumber
	BEGIN
	
		SET @_SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '
		
		SELECT @_SqlSummary +=  'SELECT '+
				CASE Filed
					WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
					ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
				END
			+'AS SummaryStr,' + a + ' AS SummaryType from ' + 
			CASE tablename 
				WHEN 'BillIndex' THEN 'ReceiptBillIndex T2 '
				WHEN 'Stype' THEN TableName + ' T1 INNER JOIN ReceiptBillIndex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN  TableName + ' T1 INNER JOIN ReceiptBillIndex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN  TableName + ' T1 INNER JOIN ReceiptBillIndex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@_Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @_MinDid),',') T1
		INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		IF LEN(@_SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @_SqlSummary = SUBSTRING(@_SqlSummary,1,LEN(@_SqlSummary)-9)
			EXEC(@_SqlSummary)
		END
		
		SELECT @_str += summarystr + '  '
		FROM #TempStr
		
		IF @_str <> ''
			SET @_str += ';'
			
		TRUNCATE TABLE #TempStr
		
		IF @_Index = @_MaxNumber
			SET @_Index += 1
		ELSE
			SELECT @_Index = MIN(BillNumberId) FROM #TmpBillIndex WHERE BillNumberId > @_Index
	END
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@_str) > 200 THEN LEFT(@_str,197)+'...' ELSE @_str END WHERE AtdId = @_MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @_Index = @_MinNumber
	
	IF @_MinDid = @_MaxDid
		SET @_MinDid += 1
	ELSE
		SELECT @_MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @_MinDid AND ISNULL(SummaryType,'') <> ''
END

--统计单据主表所有金额字段
CREATE TABLE #tmpBillMoney_Index
(
	billnumberid			INT,
	rowindex				INT				DEFAULT 1,
	
	TotalMoney_index		 NUMERIC(24, 10) 	DEFAULT 0,  --单据金额
	TaxTotalMoney_index		 NUMERIC(24, 10) 	DEFAULT 0,   --含税金额
	TotalMoneyFor_index		 NUMERIC(24, 10) 	DEFAULT 0,  --单据原币金额
	TaxTotalMoneyFor_index	 NUMERIC(24, 10) 	DEFAULT 0, -- 原币含税金额
	CompleteTotal_index		 NUMERIC(24, 10) 	DEFAULT 0,  --本币结算金额
	CompleteTotalFor_index		 NUMERIC(24, 10) 	DEFAULT 0,  --原币结算金额
	balancemoneyfor_index			 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
)

--统计单据明细所有金额字段
CREATE TABLE #tmpBillMoney_Detail
(
	billnumberid			INT,
	InvoiceCostTotal_detail			 NUMERIC(24, 10)   DEFAULT 0, --本次开票成本
	total_detail					 NUMERIC(24, 10) 	DEFAULT 0,--折后金额
	taxTotal_detail				 NUMERIC(24, 10) 	DEFAULT 0, --含税金额	
	totalfor_detail					 NUMERIC(24, 10) 	DEFAULT 0,--折后原币金额
	taxTotalfor_detail				 NUMERIC(24, 10) 	DEFAULT 0,--原币价税合计
	CompleteTotal_detail		 NUMERIC(24, 10) 	DEFAULT 0,
	CompleteTotalFor_detail		 NUMERIC(24, 10) 	DEFAULT 0,
	balancemoneyfor_detail			 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
)

--查出主表中的金额相关数据
INSERT INTO #tmpBillMoney_Index
(
	billnumberid
	,TotalMoney_index
	,TaxTotalMoney_index
	,TotalMoneyFor_index
	,TaxTotalMoneyFor_index
	,CompleteTotal_index
	,CompleteTotalFor_index
)
SELECT	a.BillNumberID
		,a.TotalMoney
		,a.TaxTotalMoney
		,a.NTotalMoney
		,a.NTaxTotalMoney
		,a.CompleteTotal
		,a.NCompleteTotal
FROM dbo.ReceiptBillIndex a
INNER JOIN #TmpBillIndex B ON B.BillNumberId = A.BillNumberID
	
--查出明细表中金额相关数据
INSERT INTO #tmpBillMoney_Detail
(
	billnumberid
	,InvoiceCostTotal_detail
)
SELECT	a.BillNumberID
		,SUM(a.InvoiceCostTotal)
FROM dbo.ReceiptBill a
INNER JOIN #TmpBillIndex B ON B.BillNumberId = A.BillNumberID
GROUP BY A.BillNumberID
	
--模板上对应金额来源的金额值
CREATE TABLE #tmpTemplateMoney
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) ,
	lendloanfor	 NUMERIC(24, 10) ,
	billnumberid	INT,
	iscost		INT DEFAULT 0
)

DECLARE	@_sql VARCHAR(MAX)
--读取模板要求的金额（非项目类）
SET @_sql = 'insert into #tmpTemplateMoney select distinct * from('--MARK:唉，又改回来，这个也要屏蔽，要不然有报错，无语，以后再改回去，直接取消注释吧
--SET @sql = 'insert into #tmpExpress'

SELECT @_sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,('+ T2.Express +') as lendloan,0 as lendloanfor,billnumberid,0 as iscost
from (SELECT	I.BillnumberId
				,I.TotalMoney_index AS total
				,I.TaxTotalMoney_index AS taxtotal
				,D.InvoiceCostTotal_detail AS InvoiceCostTotal
	FROM	#tmpBillMoney_Index I
	INNER JOIN #tmpBillMoney_Detail D ON D.billnumberid = I.billnumberid) a
 union all '
FROM #TmpVoucherDetails T1
INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
WHERE T2.Express != 'balancemoney'


IF LEN(@_sql) > LEN('insert into #tmpTemplateMoney select distinct * from(')
BEGIN
	SET @_sql = SUBSTRING(@_sql,1,LEN(@_sql)-9)
	SET @_sql += ')T'
	EXEC(@_sql)
END
SET @_sql = ''


--凭证明细临时表
CREATE TABLE #tmpVoucherBill
(
	billnumberid	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT		IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT,
	billid	INT
)

--生成凭证明细数据
INSERT INTO #tmpVoucherBill
		( billnumberid ,
		  explain ,
		  atypeid ,
		  atypeid2 ,
		  Fdc ,
		  f_exchid ,
		  f_exchidfor ,
		  lendprice ,
		  loanprice ,
		  lendpricefor ,
		  loanpricefor ,
		  FCashFlowItem ,
		  ascids ,
		  FSettleNo ,
		  FSettleTypeID ,
		  comment ,
		  cid ,
		  rate ,
		  fadc ,
		  stypeid ,
		  fyear ,
		  fperiod,
		  atdid,
		  billid
		)
SELECT	DISTINCT @VoucherId AS billnumberid,
		a.Summary AS explain,
		CASE AcFrom 
			WHEN 1 THEN a.ATypeId
			WHEN 3 THEN b.atypeid1
			WHEN 13 THEN b.atypeid1
			WHEN 14 THEN b.atypeid2
		END AS atypeid,
		'' AS atypeid2,
		CASE AcFrom 
			WHEN 1 THEN AC1.Fdc
			WHEN 3 THEN AC13.Fdc
			WHEN 13 THEN AC13.Fdc
			WHEN 14 THEN AC14.Fdc
		END AS Fdc,
		@f_exchid AS f_exchid,
		B.Cid AS f_exchidfor,
		CASE a.Fdc 
			WHEN 1 THEN D.lendloan
			ELSE 0 
		END AS lendprice,
		CASE a.Fdc 
			WHEN -1 THEN D.lendloan
			ELSE 0 
		END AS loanprice,
		CASE WHEN  a.Fdc = 1 THEN 
					(CASE ISNULL(b.ratetype,0) 
						WHEN 0 THEN isnull(d.lendloan,0) / ISNULL(b.rate,1)
						WHEN 1 THEN isnull(d.lendloan,0) * ISNULL(b.rate,1)
					END)
			ELSE 0 
		END AS lendpricefor,
		CASE WHEN a.Fdc = -1 THEN
					(CASE ISNULL(b.ratetype,0)                                                       
						WHEN 0 THEN isnull(d.lendloan,0) / isnull(b.rate,1)
						WHEN 1 THEN isnull(d.lendloan,0) * isnull(b.rate,1)
					END)
			ELSE 0 
		END AS loanpricefor,
		NULL AS FCashFlowItem,
		'' AS ascids,
		NULL AS FSettleNo,
		0 AS FSettleTypeID,
		'' AS comment,
		b.Cid,
		b.rate,
		a.Fdc AS fadc,
		b.VerifyStypeid AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod,
		a.AtdId,
		b.BillNumberId
FROM	#TmpBillIndex b
LEFT JOIN #TmpVoucherDetails a ON 1=1
LEFT JOIN #tmpTemplateMoney d ON d.atdit = a.AtdId AND D.billnumberid = B.BillNumberId
LEFT JOIN Ac_Account AC1 ON AC1.TypeId = A.ATypeId AND AC1.StypeId = B.VerifyStypeid
LEFT JOIN Ac_Account AC13 ON AC13.TypeId = B.atypeid1 AND AC13.StypeId = B.VerifyStypeid
LEFT JOIN Ac_Account AC14 ON AC14.TypeId = B.atypeid2 AND AC14.StypeId = B.VerifyStypeid

--往来科目为空
IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpVoucherBill B INNER JOIN #TmpVoucherDetails V ON V.AtdId = B.atdid AND V.AcFrom IN (3,13,14) WHERE ISNULL(B.atypeid,'') <> '' AND B.lendprice+B.loanprice <> 0)
BEGIN
	SET @_flag = -11
END

/*
处理存货类型
15-存货
16-收入
17-成本
*/
IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AcFrom IN(15,16,17))
BEGIN
	CREATE TABLE #InventoryTypeAccount
	(
		atdid	INT
		,atypeid	VARCHAR(50)
		,billnumberid	NUMERIC(10,0)
		,lendloan		NUMERIC(24,10)
		,lendloanfor	 NUMERIC(24, 10) ,
		rate		 NUMERIC(24, 10) ,
		ratetype	INT,
		iscost		INT DEFAULT 0
	)
	
	CREATE TABLE #BillDetailsInventoryTypeAccount
	(
		billnumberid	NUMERIC(10,0)
		,goodsbilldetailid	NUMERIC(10,0)
		,TID		INT
		,stypeid	VARCHAR(50)
		,CostATypeID	VARCHAR(50)
		,IncomeATypeID	VARCHAR(50)
		,StockATypeID	VARCHAR(50)
		,total		NUMERIC(24,10)
		,costtotal	NUMERIC(24,10)
		,taxtotal	NUMERIC(24,10)
		,totalfor		NUMERIC(24,10)
		,costtotalfor	NUMERIC(24,10)
		,taxtotalfor	NUMERIC(24,10)
		,InvoiceCostTotal	NUMERIC(24,10)
		,InvoiceCostTotalfor	NUMERIC(24,10)
	)
	
	INSERT INTO #BillDetailsInventoryTypeAccount
		(
			billnumberid
			,goodsbilldetailid
			,stypeid
			,TID
			,CostATypeID
			,IncomeATypeID
			,StockATypeID
			,total
			,taxtotal
			,totalfor
			,taxtotalfor
			,InvoiceCostTotal
			,InvoiceCostTotalfor
		)
	SELECT	T.BillNumberId
			,T.ID
			,T.Stypeid
			,PIT.InventoryTypeid
			,BITD.CostATypeID
			,BITD.IncomeATypeID
			,BITD.StockATypeID
			,T.Total	--折后金额
			,T.TaxTotal	--价税合计		
			,T.nTotal	--折后金额
			,T.nTaxTotal	--价税合计
			,T.InvoiceCostTotal
			,T.InvoiceCostTotal
			
	FROM ReceiptBill T
	INNER JOIN	#TmpBillIndex B ON B.BillNumberId = T.BillNumberId
	INNER JOIN	PType PIT ON PIT.typeid = T.PtypeId
	INNER JOIN	Base_InventoryTypeDetails BITD ON BITD.TID = PIT.InventoryTypeid AND BITD.STypeID = T.Stypeid
	--INNER JOIN	InOutstocktable T2 ON T2.BillNumberId = T.BillNumberId AND T2.ID = T.ID
	
	--SET @ParmDefinition = N'@total  NUMERIC(24, 10)  output'
	--EXEC sp_executesql @sql_search--,@ParmDefinition,@total = @total OUTPUT
	
	DECLARE @AcFromLoop	INT
			
	SET @AcFromLoop = 14
	
	SET @_sql = 'insert into #InventoryTypeAccount 
			(
				atdid
				,atypeid
				,lendloan
				,lendloanfor
				,rate
				,ratetype
				,billnumberid
				,iscost
			)
			select atdid
				,atypeid
				,lendloan
				,lendloanfor
				,rate
				,ratetype
				,billnumberid
				,iscost 
			from('
			
	WHILE @AcFromLoop <=17
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AcFrom = @AcFromLoop)
		BEGIN
			SET @AcFromLoop += 1
			CONTINUE
		END
			
		SELECT @_sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId
			,'+CASE @AcFromLoop WHEN 15 THEN 'StockATypeID' WHEN 16 THEN 'IncomeATypeID' ELSE 'CostATypeID' END +' as atypeid
			, sum('+ T2.Express +') as lendloan
			,0 as lendloanfor
			,b.rate
			,b.ratetype
			,a.billnumberid
			,0 as iscost
		from #BillDetailsInventoryTypeAccount a
		inner join #TmpBillIndex b on b.billnumberid = a.billnumberid
		group by a.billnumberid,'+CASE @AcFromLoop WHEN 15 THEN 'StockATypeID' WHEN 16 THEN 'IncomeATypeID' ELSE 'CostATypeID' END +',b.rate,b.ratetype union all '
		FROM #TmpVoucherDetails T1
				INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
		WHERE  AcFrom = @AcFromLoop
		SET @AcFromLoop += 1
	END
	
	SET @_sql = SUBSTRING(@_sql,1,LEN(@_sql)-9)
	SET @_sql += ')T'
	EXEC(@_sql)
	
	INSERT INTO #tmpVoucherBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  atdid,
			  billid
			)
	SELECT DISTINCT * FROM
	(
	SELECT	@VoucherId AS billnumberid
			,c.Summary AS explain,
			a.ATypeId AS atypeid,
			'' AS atypeid2,
			Ac.Fdc 
			,@f_exchid AS f_exchid
			,BB.Cid AS f_exchidfor
			,CASE c.Fdc
				WHEN 1	THEN a.lendloan
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN a.lendloan
				WHEN 1	THEN 0
			END AS dai,
			CASE WHEN c.Fdc = 1 THEN 
						(CASE a.ratetype 
							WHEN 0 THEN a.lendloan / A.rate
							WHEN 1 THEN a.lendloan * A.rate
						END)
				ELSE 0 
			END AS jiefor,
			CASE WHEN c.Fdc = -1 THEN
						(CASE a.ratetype  
							WHEN 0 THEN a.lendloan / A.rate
							WHEN 1 THEN a.lendloan* A.rate
						END)
				ELSE 0 
			END AS daifor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			BB.Cid AS cid,
			a.rate,
			c.Fdc AS fadc,
			bb.VerifyStypeid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId,
			BB.billnumberid AS billid
	FROM	#InventoryTypeAccount a
	INNER JOIN #TmpBillIndex BB ON BB.BillNumberId = A.billnumberid
	INNER JOIN Ac_Account AC ON AC.StypeId = BB.VerifyStypeid AND AC.TypeId = A.atypeid
	LEFT JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	) T 
	WHERE jie <> 0 OR dai <> 0
	
	DROP TABLE #BillDetailsInventoryTypeAccount,#InventoryTypeAccount
END
	
--根据配置，对成本明细做删除
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1)
BEGIN
	DELETE FROM #tmpVoucherBill WHERE atdid IN (SELECT AtdId FROM #TmpVoucherDetails WHERE isCost = 1)
END

-----处理平衡数分录
UPDATE	T
SET		T.lendprice = CASE WHEN T1.Fdc = 1 THEN - T2.balancemoney ELSE 0 END
		,T.loanprice = CASE WHEN T1.Fdc = -1 THEN T2.balancemoney ELSE 0 END
		,T.lendpricefor = CASE WHEN T1.Fdc = 1 AND C.BasisType = 0 THEN -T2.balancemoney / T.rate
							   WHEN T1.Fdc = 1 AND C.BasisType = 1 THEN -T2.balancemoney * T.rate
							   ELSE 0
						  END
		,T.loanpricefor = CASE WHEN T1.Fdc = -1 AND C.BasisType = 0 THEN T2.balancemoney / T.rate
							   WHEN T1.Fdc = -1 AND C.BasisType = 1 THEN T2.balancemoney * T.rate
							   ELSE 0
						  END
FROM	#tmpVoucherBill T
INNER JOIN #TmpVoucherDetails T1 ON T1.AtdId = T.atdid AND T1.Express = 'balancemoney'
INNER JOIN (
	SELECT	billid
			,SUM(lendprice) - SUM(loanprice) AS balancemoney
	FROM	#tmpVoucherBill 
	GROUP BY billid
) T2 ON T2.billid = T.billid
INNER JOIN Ac_Currency C ON C.CId = T.cid

--记录生成凭证后整个凭证金额为0的单据id
CREATE TABLE #tmpBillnumberIdWithBillTotalMoneyIsZore
(
	BillnumberId	INT
)
INSERT INTO #tmpBillnumberIdWithBillTotalMoneyIsZore(BillnumberId)
SELECT	T.billid
FROM	(
			SELECT	billid
					,SUM(lendprice) AS lendpricetotal
					,SUM(loanprice) AS loanpricetotal
			FROM	#tmpVoucherBill
			GROUP BY billid
	) T
WHERE T.lendpricetotal = 0 AND T.loanpricetotal = 0

--去除金额为0的
DELETE FROM #tmpVoucherBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 	

--调整明细异常币种	
UPDATE T SET f_exchidfor =  CASE WHEN AC.Cid = 0 THEN T.cid ELSE AC.cid END,
	cid =  CASE WHEN AC.Cid = 0 THEN T.cid ELSE AC.cid END,
	rate = CASE WHEN AC.Cid = 0 THEN T.rate ELSE C.rate END,
	lendpricefor =  CASE WHEN AC.Cid = 0 THEN T.lendpricefor
						 WHEN C.BasisType = 0 THEN T.lendprice / C.Rate
						 WHEN C.BasisType = 1 THEN T.lendprice * C.Rate							 
					END,
	loanpricefor =  CASE WHEN AC.Cid = 0 THEN T.loanpricefor 
						 WHEN C.BasisType = 0 THEN T.loanprice / C.Rate
						 WHEN C.BasisType = 1 THEN T.loanprice * C.Rate							 
					END
FROM #tmpVoucherBill T 
INNER JOIN dbo.Ac_Account AC ON AC.StypeId = T.stypeid AND AC.TypeId = T.atypeid
LEFT JOIN dbo.Ac_Currency C ON C.CId = AC.Cid
	

--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	BillIndexNumberId	INT				--单据ID
)

--获取明细对应辅助核算
SET @_sql = 'INSERT INTO #TmpAssit '
SELECT @_sql += '
SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,
'+CAST(T2.FieldValue AS VARCHAR(20))+' AS TypeId
,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids
,billnumberid
FROM #TmpBillIndex UNION ALL '
FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId
WHERE T1.Atid = @Atid

IF LEN(@_sql) > LEN('INSERT INTO #TmpAssit')
BEGIN
	SET @_sql = SUBSTRING(@_sql,1,LEN(@_sql) - 9)
	EXEC(@_sql)
END
SET @_sql = ''

--更新明细ascids
DECLARE @_MaxRowNum INT,@_CurrentRow INT,@_ascids VARCHAR(500)
SELECT @_MaxRowNum = MAX(rowno) FROM #tmpVoucherBill 
SELECT @_CurrentRow = MIN(rowno) FROM #tmpVoucherBill 

WHILE @_CurrentRow <= @_MaxRowNum
BEGIN
	SET @_ascids = ''
	SELECT @_ascids = @_ascids + CAST(T1.Ascids AS VARCHAR(10)) + ':' + T1.TypeId +','
	FROM #tmpVoucherBill T
	INNER JOIN #TmpAssit T1 ON T1.BillIndexNumberId = T.billid AND T1.AtdId = T.atdid AND ISNULL(T1.TypeId,'')<>''
	INNER JOIN Ac_Account_Assist_CheckItems T2 ON T2.STypeId = T.stypeid AND T2.ATypeId = T.atypeid AND T2.Cid = T.cid AND T2.Ascids = T1.Ascids
	WHERE rowno = @_CurrentRow 
	ORDER BY T1.Ascids
	
	IF @_ascids <> ''
		UPDATE #tmpVoucherBill SET ascids = @_ascids WHERE rowno = @_CurrentRow
		
	SET @_CurrentRow += 1
END

---合并相同信息分录的金额，生成分录号，其结果用于直接插入凭证明细表，
CREATE TABLE #tmpVoucherBill_New
(
		rowno			INT		IDENTITY(1,1), --分录号
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT
)

INSERT INTO #tmpVoucherBill_New
(		
	billnumberid	
	,explain			
	,atypeid			
	,atypeid2		
	,Fdc				
	,f_exchid		
	,f_exchidfor		
	,lendprice		
	,loanprice		
	,lendpricefor	
	,loanpricefor	
	,FCashFlowItem	
	,ascids			
	,FSettleNo		
	,FSettleTypeID	
	,comment			
	,cid				
	,rate			
	,fadc			
	,stypeid			
	,fyear			
	,fperiod		
)
SELECT TT.billnumberid	
		,TT.explain			
		,TT.atypeid			
		,TT.atypeid2		
		,TT.Fdc				
		,TT.f_exchid		
		,TT.f_exchidfor		
		,TT.lendprice		
		,TT.loanprice		
		,TT.lendpricefor	
		,TT.loanpricefor	
		,TT.FCashFlowItem	
		,TT.ascids			
		,TT.FSettleNo		
		,TT.FSettleTypeID	
		,TT.comment			
		,TT.cid				
		,TT.rate			
		,TT.fadc			
		,TT.stypeid			
		,TT.fyear			
		,TT.fperiod
FROM	(
SELECT	billnumberid	
		,explain			
		,T.atypeid			
		,atypeid2		
		,T.Fdc				
		,f_exchid		
		,f_exchidfor		
		,SUM(lendprice)	AS lendprice
		,SUM(loanprice) AS loanprice
		,SUM(lendpricefor) AS lendpricefor
		,SUM(loanpricefor) AS loanpricefor
		,FCashFlowItem
		,T.ascids
		,FSettleNo		
		,FSettleTypeID	
		,T.comment			
		,T.cid				
		,rate			
		,fadc			
		,T.stypeid			
		,fyear			
		,fperiod
		,atdid
FROM	#tmpVoucherBill T
GROUP BY billnumberid
		,explain
		,T.atypeid			
		,atypeid2		
		,T.Fdc				
		,f_exchid		
		,f_exchidfor
		,FCashFlowItem
		,T.ascids
		,FSettleNo		
		,FSettleTypeID	
		,T.comment			
		,T.cid				
		,rate			
		,fadc			
		,T.stypeid			
		,fyear			
		,fperiod
		,atdid
	) TT
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = TT.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = TT.atypeid AND AC.StypeId = TT.stypeid
ORDER BY AT.isCost,AT.OrderID,TT.fadc,AC.UserCode

--插入明细
INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
SELECT	BillNumberId ,
         CASE 
			WHEN LTRIM(RTRIM(explain))='' THEN ''
			WHEN RIGHT(LTRIM(RTRIM(explain)),1) = ';' THEN LEFT(LTRIM(RTRIM(explain)),LEN(LTRIM(RTRIM(explain)))-1)
			ELSE LTRIM(RTRIM(explain))
		  END ,
          stypeid ,
          ISNULL(atypeid,'') ,
          atypeid2 ,
          Fdc ,
          f_exchid ,
          f_exchidfor ,
          dbo.F_RoundTotal(lendprice) ,
          dbo.F_RoundTotal(lendpricefor) ,
          dbo.F_RoundTotal(loanprice) ,
          dbo.F_RoundTotal(loanpricefor) ,
          FCashFlowItem ,
          ascids ,
          FSettleNo ,
          FSettleTypeID ,
          fyear ,
          fperiod,
          comment ,
          cid ,
          rowno,
          rate ,
          fadc 
FROM #tmpVoucherBill_New

--修正明细摘要
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails 
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId
		
		DROP TABLE #TmpSummry
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(BillNumberId AS VARCHAR) + ','
FROM	#TmpBillIndex

DROP TABLE	#tmpAssit,#TempStr,#TmpBillIndex,#TmpVoucherDetails,#tmpBillMoney_Detail,#tmpBillMoney_Index
			,#tmpBillnumberIdWithBillTotalMoneyIsZore,#tmpTemplateMoney,#tmpVoucherBill,#tmpVoucherBill_New

IF @CreateType = 0
	RETURN 0
	
RETURN @VoucherId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.01.09
	描述：单据批量逐张生成凭证
*/
CREATE PROCEDURE GP_BatchCreateVoucherOneByOne
(
	@szCheckMan			VARCHAR(50),		-- 操作员
	@atid				INT,				-- -1代表自行从单据上取
	@stypeid			VARCHAR(MAX),		-- 分支机构
	@billtype			VARCHAR(MAX),		-- 单据类型
	@startdate			DATETIME,			-- 单据起始时间
	@enddate			DATETIME,			-- 单据截止时间
	@type				INT,				-- 结果类型 0.返回错误提示 2.凭证标错，并返回提示
	@date				DATETIME = '',		-- 手工指定日期
	@checkdeficit		INT
	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @VoucherId	INT,			--生成的凭证ID
		@szPID		VARCHAR(MAX),	--返回的信息
		@return		INT,			--返回值
		@attachMsg	INT
		
SET @attachMsg = 0

--------------------------------------------------------------权限检查-------------------------------------------------------
if @szCheckMan is null return 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @szCheckMan,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @billtype = ''
BEGIN
	--SET @BillType = '147,11,45,160,305,139,140,142,141,34,6,161,126,144,146,145,21,187,188,201,202,9,14,16,116,115,128,129,4,189,66,190,148,150,149,151,36,84,85,78,158,77,93,5,10,57,205,181,183,166,167,168,170,172,159,173,174,212,213,214,215,187,188,310,400,401,402,403,12,46,414'
	
	RAISERROR('请选择需要生成凭证的单据类型！',16,1)
	RETURN 0
END

--筛选分支机构
CREATE TABLE #Stype(TypeId 	varchar(100))
SET @stypeid = LTRIM(RTRIM(@stypeid))
IF NOT (@stypeid='' AND @MStypeid = '00000')
BEGIN
	INSERT INTO #Stype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@szCheckMan)
END
ELSE
	INSERT INTO #Stype( TypeId ) SELECT TypeId FROM dbo.SType WHERE IsSelfVerify = 1



--存储生成结果
CREATE TABLE #TmpResult
(
	BillCode	VARCHAR(400),
	txt			VARCHAR(MAX),
	flag		INT
	,voucherid		NUMERIC(10,0)
	,deficitvoucher	INT
	,returnvalue	INT
)

--表变量，存储需要生成凭证的单据
DECLARE @BillIndex TABLE
(
	id				INT IDENTITY(1,1),
	billnumberid	INT,
	atid			INT,
	verfidyid		VARCHAR(50),
	billtype		INT,
	stypeid2		VARCHAR(50)
)

INSERT INTO @BillIndex(billnumberid, atid, verfidyid,billtype,stypeid2)
SELECT BillNumberId,ATID,T2.VerifyID,BillType,StypeID2
FROM dbo.BillIndex T1
INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId OR T1.StypeID2 = T2.TypeId
WHERE BillType IN (SELECT * FROM dbo.f_split(@billtype,','))
	AND BillDate >= @startdate AND BillDate <= @enddate 
	AND RedWord = 0
	AND ifcheck='t'
	AND IsIni = 0
	AND T2.TypeId IN (SELECT * FROM #Stype)
	AND (BillType <> 414 OR (BillType = 414 AND IsFreightMoney = 1))
	AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId = t1.BillNumberId AND IsCost IN(0,2))
	AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_ProvisionForImpairment WHERE BillNumberId = t1.BillNumberId)
UNION ALL
SELECT BillNumberId,ATID,T2.VerifyID,BillType,'' StypeID2
FROM dbo.Coupon_BillIndex T1
INNER JOIN dbo.f_split(@billtype,',') F ON F.a=T1.BillType
INNER JOIN #Stype S ON S.TypeId=T1.STypeId
INNER JOIN dbo.SType T2 ON T2.TypeId = S.TypeId
WHERE 
	BillDate >= @startdate 
	AND BillDate <= @enddate 
	AND RedWord = 0
	AND ifcheck='t'
	AND IsIni = 0
	AND T1.FromType<>3
	AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_CouponBill_VoucherBill WHERE CouponBillId = t1.BillNumberId)
UNION ALL
SELECT BillNumberId,ATID,T2.VerifyID,BillType,'' StypeID2
FROM dbo.PosAllotApplyBillIndex T1
INNER JOIN dbo.f_split(@billtype,',') F ON F.a=T1.BillType
INNER JOIN #Stype S ON S.TypeId=T1.STypeId
INNER JOIN dbo.SType T2 ON T2.TypeId = S.TypeId
WHERE 
	BillDate >= @startdate 
	AND BillDate <= @enddate 
	AND RedWord = 0
	AND ifcheck='t'
	AND IsIni = 0
	AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DeliveryBill_VoucherBill WHERE DeliveryBillId = t1.BillNumberId)	
	
--统计单据总量，超过2万张，不能操作
DECLARE @BillCount INT
SELECT @BillCount = COUNT(BillNumberId) 
FROM @BillIndex

IF @BillCount > 20000
BEGIN
	RAISERROR('单据数超过2万，请筛选后重试',16,1)
	RETURN 0
END

DECLARE @index INT
SET @index = 1

DECLARE @BillNumberId INT,@billatid INT,@verifyid VARCHAR(50),@singleBillType INT,@stypeid2 VARCHAR(50)
		,@deficitvoucher INT

WHILE @index <= @BillCount
BEGIN
	SET @return = 0
	SET @attachMsg = 0
	SELECT @BillNumberId = billnumberid,@billatid = atid,@verifyid = verfidyid,@singleBillType = billtype,@stypeid2 = stypeid2 FROM @BillIndex WHERE id = @index
	
	--不从单据取的，就按默认模板
	IF @atid <> -1 OR @singleBillType IN (212,213,214)
		SET @billatid = 0
	
	SET @VoucherId= -1
	
	IF @singleBillType = 311
	BEGIN
		IF @stypeid <> @stypeid2
			SET @stypeid2 = @stypeid
		EXEC @return = dbo.GP_HandCreate_Voucher @BillNumberId,@szCheckMan,@billatid,@date,@verifyid,@VoucherId OUTPUT,@type,1,@szPID OUTPUT,1,@stypeid2,1,@checkdeficit,@deficitvoucher OUTPUT
	END
	ELSE IF @singleBillType IN(423,424,426)
	BEGIN
		EXEC @return = dbo.GP_HandCreate_Voucher @BillNumberId,@szCheckMan,@billatid,@date,@verifyid,@VoucherId OUTPUT,@Type,1,@szPID OUTPUT,1,'',3,@checkdeficit,@deficitvoucher OUTPUT
	END
	ELSE IF @singleBillType IN(327,328,329)
	BEGIN
		EXEC @return = dbo.GP_HandCreate_Voucher @BillNumberId,@szCheckMan,@billatid,@date,@verifyid,@VoucherId OUTPUT,@Type,1,@szPID OUTPUT,1,'',4,@checkdeficit,@deficitvoucher OUTPUT
	END
	ELSE
		EXEC @return = dbo.GP_HandCreate_Voucher @BillNumberId,@szCheckMan,@billatid,@date,@verifyid,@VoucherId OUTPUT,@Type,1,@szPID OUTPUT,1,'',0,@checkdeficit,@deficitvoucher OUTPUT
		
	--优惠券类单据
	IF(@singleBillType IN(423,424,426))
	BEGIN
		IF @return = 0--生成成功
		BEGIN
			INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) AS txt,1 AS flag
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
			FROM dbo.Coupon_BillIndex T1
			INNER JOIN dbo.Ac_CouponBill_VoucherBill T2 ON T1.BillNumberId = T2.CouponBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T3.BillNumberId = @VoucherId
		END
		ELSE
		BEGIN
			IF @return IN(-14)
			BEGIN			
				INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
				SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +'。注：'+ @szPID AS txt,1 AS flag 
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
				FROM dbo.Coupon_BillIndex T1
				INNER JOIN dbo.f_split(@BillNumberId,',') F ON F.a=T1.BillNumberId
				INNER JOIN dbo.Ac_CouponBill_VoucherBill T2 ON T1.BillNumberId = T2.CouponBillId
				INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
				INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			END
			ELSE IF @return IN(-12,-13) OR @Type = 0-- -12:根据模板生成的凭证金额全部为0，导致凭证没有分录。-13:已生成过凭证
			BEGIN			
				INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
				SELECT TOP 1 T1.BillCode,@szPID AS txt,-2 AS flag 
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
				FROM dbo.Coupon_BillIndex T1
				INNER JOIN dbo.f_split(@BillNumberId,',') F ON F.a=T1.BillNumberId
			END
			ELSE IF @Type = 2
			BEGIN		
				INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )	
				SELECT TOP 1 T1.BillCode,'已保存标错凭证['+t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +']'+@szPID AS txt, -1 AS flag 
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
				FROM dbo.Coupon_BillIndex T1
				INNER JOIN dbo.f_split(@BillNumberId,',') F ON F.a=T1.BillNumberId
				INNER JOIN dbo.Ac_CouponBill_VoucherBill T2 ON T1.BillNumberId = T2.CouponBillId
				INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
				INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			END	
		END
	END
	--门店配送类单据
	ELSE IF(@singleBillType IN(327,328,329))
	BEGIN
		IF @return = 0--生成成功
		BEGIN
			INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) AS txt,1 AS flag
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
			FROM dbo.PosAllotApplyBillIndex T1
			INNER JOIN dbo.Ac_DeliveryBill_VoucherBill T2 ON T1.BillNumberId = T2.DeliveryBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T3.BillNumberId = @VoucherId
		END
		ELSE
		BEGIN
			IF @return IN(-14)
			BEGIN			
				INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
				SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +'。注：'+ @szPID AS txt,1 AS flag 
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
				FROM dbo.PosAllotApplyBillIndex T1
				INNER JOIN dbo.f_split(@BillNumberId,',') F ON F.a=T1.BillNumberId
				INNER JOIN dbo.Ac_DeliveryBill_VoucherBill T2 ON T1.BillNumberId = T2.DeliveryBillId
				INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
				INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			END
			ELSE IF @return IN(-12,-13) OR @Type = 0-- -12:根据模板生成的凭证金额全部为0，导致凭证没有分录。-13:已生成过凭证
			BEGIN			
				INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
				SELECT TOP 1 T1.BillCode,@szPID AS txt,-2 AS flag 
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
				FROM dbo.PosAllotApplyBillIndex T1
				INNER JOIN dbo.f_split(@BillNumberId,',') F ON F.a=T1.BillNumberId
			END
			ELSE IF @Type = 2
			BEGIN		
				INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )	
				SELECT TOP 1 T1.BillCode,'已保存标错凭证['+t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +']'+@szPID AS txt, -1 AS flag 
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
				FROM dbo.PosAllotApplyBillIndex T1
				INNER JOIN dbo.f_split(@BillNumberId,',') F ON F.a=T1.BillNumberId
				INNER JOIN dbo.Ac_DeliveryBill_VoucherBill T2 ON T1.BillNumberId = T2.DeliveryBillId
				INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
				INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			END	
		END
	END
	ELSE 
	BEGIN
		IF @return = 0--生成成功
			BEGIN
				INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
				SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) AS txt,1 AS flag
							,@VoucherId AS voucherid
							,@deficitvoucher AS deficitvoucher
							,@return AS returnvalue
				FROM dbo.BillIndex T1
					INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
					INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
					INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
				WHERE T3.BillNumberId = @VoucherId
			END
			ELSE
			BEGIN
				IF @return IN(-14)
				BEGIN			
					INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
					SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +'。注：'+ @szPID AS txt,1 AS flag 
							,@VoucherId AS voucherid
							,@deficitvoucher AS deficitvoucher
							,@return AS returnvalue
					FROM dbo.BillIndex T1
					INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
					INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
					INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
					WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
				END
				ELSE IF @return IN(-12,-13) OR @Type = 0-- -12:根据模板生成的凭证金额全部为0，导致凭证没有分录。-13:已生成过凭证
				BEGIN			
					INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )
					SELECT TOP 1 T1.BillCode,@szPID AS txt,-2 AS flag 
							,@VoucherId AS voucherid
							,@deficitvoucher AS deficitvoucher
							,@return AS returnvalue
					FROM dbo.BillIndex T1
					WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
				END
				ELSE IF @Type = 2
				BEGIN		
					INSERT INTO #TmpResult( BillCode, txt, flag,voucherid,deficitvoucher,returnvalue )	
					SELECT TOP 1 T1.BillCode,'已保存标错凭证['+t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +']'+@szPID AS txt, -1 AS flag 
							,@VoucherId AS voucherid
							,@deficitvoucher AS deficitvoucher
							,@return AS returnvalue
					FROM dbo.BillIndex T1
					INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
						INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
						INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
					WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
				END	
			END	
	END
	
	SET @index += 1
END

SELECT * FROM #TmpResult

DROP TABLE #TmpResult,#Stype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF exists (SELECT * from dbo.sysobjects where id = object_id(N'[dbo].[GP_BatchDeleteBaseInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_BatchDeleteBaseInfo]
GO


/****** Object:  StoredProcedure [dbo].[GP_DeleteBaseInfo]    Script Date: 06/01/2011 19:18:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	名称:	基本信息批量删除(只处理了商品的)
	时间:	2014年8月21日 
	版本:	9.4
	基本描述:由于商品线性表及查询数据,存储过程分页,页面上无法取到全部需要删除的节点TYPEID,故将过滤条件带入,重新查询,再执行删除
	---HQ
*/
CREATE    PROCEDURE [dbo].[GP_BatchDeleteBaseInfo]
( 
	@basetypeidlist	VARCHAR(MAX),	--基本信息表的关键字段
	@DbName			VARCHAR(50),	--基本信息关键字
	@fullname		VARCHAR(200),	--名称（过滤条件）
	@usercode		VARCHAR(200),	--编号（过滤条件）
	@entrycode		VARCHAR(200),	--条码（商品时过滤条件）
	@parentname		VARCHAR(200),	--类别名称（过滤条件）
	@ifdeleted		INT,			--是否停用（过滤条件）
	@parid			VARCHAR(50),	--父节点id（过滤条件）
	@chvOperatorID	VARCHAR(50),	--操作员ID
	@delcount		INT OUT,
	@undelcount		INT OUT
)
--@encode$--
AS
SET NOCOUNT ON

--类别查找时先查询出所有符合条件的父节点typeid
CREATE TABLE #PARTYPEID (TypeID VARCHAR(50))

--用于存放需要删除的节点的typeid
CREATE TABLE #MainType(typeid VARCHAR(50))  
  
--类别查找特殊处理
IF @parentname IS NOT NULL AND @parentname<>''
BEGIN

	DECLARE @parsql VARCHAR(MAX)
	SET @parsql='
	INSERT INTO #parTypeid (typeid)
	SELECT TypeId FROM '+@dbname+'
    WHERE FullName LIKE ''%'+@parentname+'%'' 
    AND sonnum<>0
    '
    --print @parsql
	EXEC(@parsql)
    DELETE FROM #parTypeid 
    WHERE TypeID IN (	SELECT TypeID 
						FROM PType 
						WHERE ParId IN (SELECT TypeID FROM #parTypeid) 
						AND typeId IN (SELECT TypeID FROM #parTypeid))
END

DECLARE @SQL VARCHAR(MAX)
SET @SQL=''

IF @DbName='PTYPE'
BEGIN	
	SET @SQL='			
	INSERT INTO #MainType(typeid)
	SELECT P.typeId FROM PType P 
	INNER JOIN 	F_BaseGetAllManagerBaseTypeId('''+@ParID+''',1,'''+@chvOperatorID+''') F ON P.typeId=F.TypeId
	WHERE P.sonnum=0
	'
	IF @UserCode IS NOT NULL AND @usercode<>''
		SET @SQL+=' AND p.UserCode LIKE ''%'+@UserCode+'%''
		'
	IF @FullName IS NOT NULL AND @fullname<>''
		SET @SQL+=' AND p.FullName LIKE ''%'+@FullName+'%''
		'
	IF @entrycode IS NOT NULL AND @entrycode<>''
		SET @SQL+=' AND (p.EntryCode LIKE ''%'+@entrycode+'%'' OR  EXISTS (SELECT *FROM PType_Units_Ext UE WHERE P.TYPEID=UE.PTYPEID AND UE.EntryCode LIKE ''%'+@entrycode+'%''))
		'
	IF @ifdeleted IS NOT NULL AND @ifdeleted<>''
		SET @SQL+=' AND P.DELETED LIKE ''%'+@ifdeleted+'%'' 
		'
	IF @parentname IS NOT NULL AND @parentname<>''
		SET @SQL+=' AND EXISTS (SELECT TypeID FROM #parTypeid par WHERE LEFT(P.ParId,LEN(PAR.TYPEID))=PAR.TypeID) 
		'
	EXEC (@SQL)
END

--SELECT a INTO #TYPEID FROM f_split(@basetypeidlist,',')

DECLARE @typecount INT
DECLARE @returnvalue INT
DECLARE @i INT
DECLARE @typeid VARCHAR(50)
SET @SQL=''
SET @typeid=''
SET @typecount=0
SET @returnvalue=0
SET @i=0
SELECT @typecount=COUNT(1) FROM #MainType
SET @i=@typecount
WHILE(@i>0)
BEGIN
	SELECT TOP (@i) @typeid=typeid FROM #MainType
	BEGIN TRY
		EXEC Gp_DeleteBaseInfo @TypeId=@typeid,@DbName=@DbName,@delType=-1
	END TRY
	BEGIN CATCH
		SET @undelcount=@undelcount+1
	END CATCH
	SET @i=@i-1
END

SET @delcount=@typecount-@undelcount

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO    



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_BatchInsertIniAccount]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_BatchInsertIniAccount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	glj	
	Date	:	2016-08-20
	Description	: 批量导入期初余额
*/

CREATE PROCEDURE Gp_BatchInsertIniAccount
(
	@chvOperatorID	VARCHAR(100),	--操作员id
	@STypeId		VARCHAR(50),	--分支机构id	
	@Cid			INT				--币别id	
)
--@encode$--
AS
SET NOCOUNT ON 

IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=1)
	BEGIN
		RAISERROR('当前分支机构已经开账，不允许继续操作！',16,1)
		RETURN
	END

DECLARE 
	@SQL		VARCHAR(MAX)='',--执行语句
	@RetStr		VARCHAR(MAX)='',--不满足条件科目
	@SFyear		INT,--总账分支机构启用年度	
	@SFPeriod	INT, --总账分支机构启用期间
	@Error		INT=0
	
SELECT @SFyear=SFYear,@SFPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId

DECLARE @stypeindependentopen INT 
SELECT @stypeindependentopen =  SubValue FROM dbo.sysdata WHERE SubName = 'stypeindependentopen'

IF EXISTS(SELECT TOP 1 1 FROM SType S 
	INNER JOIN SType_UserConfig SU ON SU.StypeId=S.TypeId AND S.VerifyID=@STypeId AND S.deleted=0 AND (SU.SFYear<>@SFyear OR SU.SFPeriod<>@SFPeriod) AND @stypeindependentopen=1)
	BEGIN
		RAISERROR('因业务系统与总账系统【启用期间】不一致无法引入，请手工录入科目数据！',16,1)
		RETURN
	END
--=================================业务取值【BEGIN】=================================== 
--查询包含非独立分支机构
CREATE TABLE #SType(STypeId VARCHAR(50),VerifyID VARCHAR(50))
INSERT INTO #SType(STypeId,VerifyID) SELECT TypeId,VerifyID FROM SType WHERE VerifyID=@STypeId AND deleted=0	
  
--业务数据临时表	   
CREATE TABLE #TempData
(
	ATypeId			VARCHAR(50),
	STypeId			VARCHAR(50),
	ETypeID			VARCHAR(50),
	DTypeID			VARCHAR(50),
	BTypeID			VARCHAR(50),
	BillTotal		NUMERIC(22,10),
	BillTotalFor	NUMERIC(22,10),
	GroupId			INT IDENTITY(1,1),
	TID				INT,--往来单位 2：库存 3：固定资产
)
--------提取费用单配置
DECLARE @Expensetoar INT
SELECT @Expensetoar=SUBVALUE FROM dbo.sysdata WHERE SubName='expensetoar'

INSERT INTO #TempData(ATypeId,STypeId,ETypeID,DTypeID,BTypeID,BillTotal,BillTotalFor,TID)
SELECT
	ATypeID,
	Stypeid,
	etypeid,
	DTypeId,
	btypeid,
	SUM(BillTotal) BillTotal,
	SUM(BillTotalFor) BillTotalFor,
	1 TID
FROM 
(
	SELECT
		F.TypeId ATypeID,
		A.Stypeid,
		A.etypeid,
		A.DTypeId,
		A.btypeid,
		CASE WHEN a.BillType IN(45,6,148,149,150,151,46,4,66) THEN -(ISNULL(A.totalmoney,0)-ISNULL(A.preferencemoney,0)-ISNULL(A.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))   
			ELSE ISNULL(a.totalmoney,0)-ISNULL(A.preferencemoney,0)-ISNULL(A.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
		END BillTotal,
		CASE WHEN a.BillType IN(45,6,148,149,150,151,46,4,66) THEN -(ISNULL(A.NTotalMoney,0)-ISNULL(A.NPreferenceMoney,0)-ISNULL(A.NCompleteTotal,0)-ISNULL(A.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))         
			ELSE (ISNULL(A.NTotalMoney,0)-ISNULL(A.NPreferenceMoney,0)-ISNULL(A.NCompleteTotal,0)-ISNULL(A.NTotalInMoney,0))-ISNULL(A.NChargeOffTotal,0)                             
		END BillTotalFor
	FROM #SType S 
	INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.ISINI=1 AND A.CID=@CId AND A.BillType NOT IN(116,115,128,129,36,400,401,404,405)
	INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.TypeID=A.ATypeID1
	
	UNION ALL--暂估入库单
	
	SELECT
		F.Typeid ATypeID,
		A.Stypeid,
		A.etypeid,
		A.DTypeId,
		A.btypeid,
		(AB.Qty-AB.InvoiceQty)*AB.DiscountPrice BillTotal,
		(AB.Qty-AB.InvoiceQty)*AB.NDiscountPrice BillTotalFor 
	FROM #SType S 
	INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid AND A.BillType=400
	INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.TypeID=A.ATypeID1
	INNER JOIN AppraisalBill AB ON AB.BillNumberId=A.BillNumberId
	
	UNION ALL --暂估退货单
	
	SELECT
		F.TypeId ATypeID,
		A.Stypeid,
		A.etypeid,
		A.DTypeId,
		A.btypeid,
		-(AB.total-AB.DiscountPrice*InvoiceQty) BillTotal,
		-(AB.NTotal-AB.NDiscountPrice*InvoiceQty) BillTotalFor 
	FROM #SType S 
	INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid AND A.BillType=401
	INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.TypeID=A.ATypeID1
	INNER JOIN AppraisalBackBill AB ON AB.BillNumberId=A.BillNumberId
	
	UNION ALL --(404采购暂估开票 405销售发货开票)
	
	SELECT 
		F.Typeid ATypeID,
		A.Stypeid,
		A.etypeid,
		A.DTypeId,
		A.btypeid,
		A.TaxTotalMoney-A.CompleteTotal-A.ChargeOffTotal BillTotal,
		A.NTaxTotalMoney-A.NCompleteTotal-A.NChargeOffTotal BillTotalFor 
	FROM #SType S 
	INNER JOIN ReceiptBillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid
	INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND ((A.BillType=405 AND A.ATypeID1=F.Typeid) OR (A.BillType=404 AND A.ATypeID2=F.Typeid))
	--INNER JOIN ReceiptBill AB ON AB.BillNumberId=A.BillNumberId

	UNION ALL--提取应收应付的增加，减少单

	SELECT
		F.Typeid ATypeID,
		A.Stypeid,
		A.etypeid,
		A.DTypeId,
		C.BtypeId,
		CASE WHEN A.BillType IN(129,115) THEN -(ISNULL(C.total,0)-ISNULL(A.preferencemoney,0)-ISNULL(C.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))
			ELSE ISNULL(c.total,0)-ISNULL(a.preferencemoney,0)-ISNULL(c.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
		END AS BillTotal,
		CASE WHEN A.BillType IN(129,115) THEN -(ISNULL(c.NTotal,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(c.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))
			ELSE ISNULL(c.NTotal,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(c.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0)
		END AS BillTotalFor	
	FROM #SType S 
	INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.ISINI=1 AND A.CID=@CId AND A.BillType IN (116,115,128,129)
	INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.TypeID=A.ATypeID1
	LEFT JOIN AdDebtBill C  ON C.BillNumberId=A.BillNumberId

	UNION ALL --提取费用单

	SELECT 
		F.Typeid ATypeID,
		A.Stypeid,
		A.etypeid,
		A.DTypeId,
		A.btypeid,
		CASE WHEN @Expensetoar=1 AND SUBSTRING(A.btypeid,1,5)='00001' THEN -(ISNULL(a.totalmoney,0)-ISNULL(a.preferencemoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))   
			ELSE ISNULL(a.totalmoney,0)-ISNULL(a.preferencemoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
		END AS BILLTOTAL,
		CASE WHEN @Expensetoar=1 AND SUBSTRING(A.btypeid,1,5)='00001' THEN -(ISNULL(a.NTotalMoney,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(a.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))         
			ELSE (ISNULL(a.NTotalMoney,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(a.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))                             
		END AS BILLTOTALFOR
	FROM #SType S 
	INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.ISINI=1 AND A.CID=@CId AND A.BillType=36
	INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.TypeID=A.ATypeID1
) F 
GROUP BY ATypeID,Stypeid,etypeid,DTypeId,btypeid



--库存
IF(@CId=1)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='useatypefrom' AND SubValue='1')
		BEGIN
			INSERT INTO #TempData(ATypeId,STypeId,BillTotal,BillTotalFor,TID)
			SELECT
				D.StockATypeID ATypeId,
				S.STypeId,
				SUM(ISNULL(G.Total,0)) BillTotal,
				SUM(ISNULL(G.Total,0)) BillTotalFor,
				2 TID
			FROM #SType S 
			INNER JOIN Stock ST ON ST.STypeID=S.STypeId
			INNER JOIN IniGoodsStocks G ON G.KtypeId=ST.typeId
			INNER JOIN ptype P ON P.typeId=G.PtypeId 
			INNER JOIN Base_InventoryTypeDetails D ON D.TID=P.InventoryTypeID AND D.STypeID=S.STypeId
			INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.Typeid=D.StockATypeID
			GROUP BY D.StockATypeID,S.STypeId
		END
	ELSE 
		BEGIN
			INSERT INTO #TempData(ATypeId,STypeId,BillTotal,BillTotalFor,TID)
			SELECT
				S1.ATypeID4 ATypeId,
				S.STypeId,
				SUM(ISNULL(G.Total,0)) BillTotal,
				SUM(ISNULL(G.Total,0)) BillTotalFor,
				2 TID
			FROM #SType S 
			INNER JOIN Stock ST ON ST.STypeID=S.STypeId
			INNER JOIN IniGoodsStocks G ON G.KtypeId=ST.typeId
			INNER JOIN SType S1 ON S1.TypeId=S.VerifyID
			INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.Typeid=S1.ATypeID4
			GROUP BY S1.ATypeID4,S.STypeId
		END
		
	END

IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='assets' AND SubValue='1') AND @Cid=1
	BEGIN
		--固定资产科目
		INSERT INTO #TempData(ATypeId,STypeId,DTypeID,BillTotal,BillTotalFor,TID)
		SELECT
			ATypeID,
			STypeId,
			DTypeid,
			SUM(BillTotal) BillTotal,
			SUM(BillTotalFor) BillTotalFor,
			3 TID
		FROM 
		(
			--固定资产科目
			SELECT
				F.Typeid ATypeID,
				S.STypeId,
				AC.DTypeid,
				AC.Total BillTotal,
				AC.Total BillTotalFor                                                             
			FROM #SType S 
			INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5)
			INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.Typeid=ac.AssertATypeId
			
			UNION ALL
			--累计折旧科目
			SELECT
				F.Typeid ATypeID,
				S.STypeId,
				AC.DTypeid,
				AC.DepTotal BillTotal,
				AC.DepTotal BillTotalFor                            
			FROM #SType S 
			INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5)
			INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.Typeid=ac.DepATypeId
			
			UNION ALL
			--减值准备科目
			SELECT
				F.Typeid ATypeID,
				S.STypeId,
				AC.DTypeid,
				AC.DevalueReady BillTotal,
				AC.DevalueReady BillTotalFor                     
			FROM #SType S 
			INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5)
			INNER JOIN dbo.Ac_Account F ON F.Stypeid=S.VerifyID AND F.Typeid=ac.DevalueATypeId
		) F 
		GROUP BY ATypeID,STypeId,DTypeid
	END
	
--删除相同分支机构  部门  职员 往来单位   合计为0 的数据
--业务数据临时表	   
CREATE TABLE #TempData1
(
	ATypeId			VARCHAR(50),
	STypeId			VARCHAR(50),
	ETypeID			VARCHAR(50),
	DTypeID			VARCHAR(50),
	BTypeID			VARCHAR(50),
	BillTotal		NUMERIC(22,10),
	BillTotalFor	NUMERIC(22,10),
	GroupId			INT IDENTITY(1,1)
)

DECLARE 
	@ATypeId VARCHAR(50),		--科目ID
	@GroupbyStr VARCHAR(MAX)=''--分组字段
	
DECLARE Atype_Cur CURSOR READ_ONLY FOR
SELECT ATypeId FROM #TempData GROUP BY ATypeId
OPEN Atype_Cur
FETCH NEXT FROM Atype_Cur INTO @ATypeID
WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @GroupbyStr=''
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND Ascids=1)
			SET @GroupbyStr+=',STypeId'
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND Ascids=2)
			SET @GroupbyStr+=',DTypeid'
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND Ascids=3)
			SET @GroupbyStr+=',ETypeid'
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND Ascids=4)
			SET @GroupbyStr+=',BTypeid'
		--重新获取总值
		SET @SQL='
		INSERT INTO #TempData1(ATypeId'+@GroupbyStr+',BillTotal,BillTotalFor)
		SELECT
			ATypeId
			'+@GroupbyStr+',
			SUM(ISNULL(BillTotal,0)) BillTotal,
			SUM(ISNULL(BillTotalFor,0)) BillTotalFor
		FROM #TempData
		WHERE 
			ATypeId='''+@ATypeId+'''
		GROUP BY ATypeId'+@GroupbyStr
		EXEC(@SQL)
		FETCH NEXT FROM Atype_Cur INTO @ATypeID
	END
CLOSE Atype_Cur
DEALLOCATE Atype_Cur

DELETE FROM #TempData1 WHERE BillTotal=0 AND BillTotalFor=0

--=================================业务取值  【END】===================================

--=================================更改期初表数据【BEGIN】===================================
--单据上满足条件辅助核算科目及没有辅助核算科目
CREATE TABLE #Assist(ATypeID VARCHAR(50),TID INT)
INSERT INTO #Assist(ATypeID,TID)
SELECT DISTINCT T.ATypeId,0 TID--往来
FROM #TempData T 
INNER JOIN(
	SELECT ATypeId,MAX(Ascids) Ascids FROM Ac_Account_Assist_CheckItems C WHERE C.STypeId=@STypeId --AND C.Cid=@Cid
	GROUP BY C.ATypeID
) F ON F.ATypeId=T.ATypeId AND F.Ascids<=4 AND T.TID=1


UNION ALL

SELECT DISTINCT T.ATypeID,0 TID--库存
FROM #TempData T 
INNER JOIN(
	SELECT ATypeId,MAX(Ascids) Ascids FROM Ac_Account_Assist_CheckItems C WHERE C.STypeId=@STypeId --AND C.Cid=@Cid
	GROUP BY C.ATypeID
) F ON F.ATypeId=T.ATypeId AND F.Ascids<=1 AND T.TID=2

UNION ALL

SELECT DISTINCT T.ATypeID,0 TID--固定资产
FROM #TempData T 
INNER JOIN(
	SELECT ATypeId,MAX(Ascids) Ascids FROM Ac_Account_Assist_CheckItems C WHERE C.STypeId=@STypeId --AND C.Cid=@Cid
	GROUP BY C.ATypeID
) F ON F.ATypeId=T.ATypeId AND F.Ascids<=2 AND T.TID=3

UNION ALL

SELECT DISTINCT ATypeID,1 TID 
FROM #TempData 
WHERE ATypeId NOT IN(SELECT ATypeId FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId --AND Cid=@Cid
) 
GROUP BY ATypeId

--CREATE TABLE #Assist(ATypeID VARCHAR(50),TID INT)
--INSERT INTO #Assist(ATypeID,TID)
--SELECT DISTINCT F.ATypeId ,0 TID--往来
--FROM (
--	SELECT A.TypeId AS  ATypeId FROM Ac_Account A  LEFT JOIN dbo.Ac_Account_Assist_CheckItems AC ON AC.STypeId = A.StypeId AND AC.ATypeId = A.TypeId AND AC.Cid = A.Cid 
--	WHERE A.StypeId=@STypeId AND (A.Cid = @Cid OR A.Cid = 0) 
--	AND Deleted=0 AND SonNum=0 AND FContact=1 AND (AC.Ascids <=4 OR AC.Ascids IS NULL )
--) F 
--UNION ALL
--SELECT DISTINCT F.ATypeID,0 TID--库存
--FROM (		
--		SELECT D.StockATypeID ATypeId FROM Base_InventoryTypeDetails D INNER JOIN #SType S ON S.STypeId=D.STypeID LEFT JOIN dbo.Ac_Account_Assist_CheckItems A ON A.ATypeId = D.StockATypeID AND A.StypeId = D.STypeID WHERE D.STypeID = @STypeId AND (A.Ascids <=1 OR A.Ascids IS NULL)
--		UNION ALL
--		SELECT S.ATypeID4 FROM SType S LEFT JOIN  Ac_Account_Assist_CheckItems A ON A.ATypeId = S.ATypeID AND A.STypeId =S.TypeId WHERE S.TypeId=@STypeId  AND (A.Ascids<=1 OR A.Ascids IS NULL)
--) F 
--UNION ALL
--SELECT DISTINCT F.ATypeID,0 TID--固定资产
--FROM (		
--		SELECT C.AssertATypeId ATypeId FROM Ac_AssetsCards C 
--		LEFT JOIN Ac_Account_Assist_CheckItems A ON C.STypeId = A.STypeId AND C.Cid = A.Cid AND (C.AssertATypeId = A.ATypeId OR C.DepATypeId = A.ATypeId OR C.DevalueATypeId = A.ATypeId) INNER JOIN #SType S ON C.STypeId=S.STypeId AND C.AssetsState NOT IN(2,5) 
--		WHERE  (A.Ascids <=2 OR A.Ascids IS NULL) AND S.STypeId=@STypeId  AND (C.Cid = @Cid OR C.Cid = 0)
--		UNION ALL
--		SELECT C.DepATypeId ATypeId FROM Ac_AssetsCards C 
--		LEFT JOIN Ac_Account_Assist_CheckItems A ON C.STypeId = A.STypeId AND C.Cid = A.Cid AND (C.AssertATypeId = A.ATypeId OR C.DepATypeId = A.ATypeId OR C.DevalueATypeId = A.ATypeId) INNER JOIN #SType S ON C.STypeId=S.STypeId AND C.AssetsState NOT IN(2,5) 
--		WHERE  (A.Ascids <=2 OR A.Ascids IS NULL) AND S.STypeId=@STypeId  AND (C.Cid = @Cid OR C.Cid = 0)
--		UNION ALL
--		SELECT C.DisATypeId ATypeId FROM Ac_AssetsCards C 
--		LEFT JOIN Ac_Account_Assist_CheckItems A ON C.STypeId = A.STypeId AND C.Cid = A.Cid AND (C.AssertATypeId = A.ATypeId OR C.DepATypeId = A.ATypeId OR C.DevalueATypeId = A.ATypeId) INNER JOIN #SType S ON C.STypeId=S.STypeId AND C.AssetsState NOT IN(2,5) 
--		WHERE  (A.Ascids <=2 OR A.Ascids IS NULL) AND S.STypeId=@STypeId  AND (C.Cid = @Cid OR C.Cid = 0)
--) F 
----UNION ALL
----SELECT DISTINCT ATypeID,1 TID 
----FROM #TempData 
----WHERE ATypeId NOT IN(SELECT ATypeId FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND Cid=@Cid
----) 
----GROUP BY ATypeId


BEGIN TRAN		
--删除期初表相应数据，重新导入数据

--=================================更改期初表数据【BEGIN】===================================	
---------------- 删除原数据 重新导入数据	
DELETE Ac_IniAccount
FROM Ac_IniAccount A 
INNER JOIN #Assist F ON A.STypeId=@STypeId AND F.ATypeID=A.ATypeId  AND A.FYear=@SFYear AND A.FPeriod=@SFPeriod AND A.Cid = @Cid
SELECT @Error+=@@ERROR

--期初辅助核算主表数据
DELETE Ac_IniAccount_Assist_CheckItems 
FROM Ac_IniAccount_Assist_CheckItems A
INNER JOIN #Assist S ON A.STypeId=@STypeId AND S.ATypeID=A.ATypeId  AND A.FYear=@SFYear AND A.FPeriod=@SFPeriod AND A.Cid = @Cid
SELECT @Error+=@@ERROR

--期初辅助核算明细表数据
DELETE Ac_IniAccount_Assist_CheckItems_Detail 
FROM Ac_IniAccount_Assist_CheckItems_Detail A
INNER JOIN #Assist S ON A.STypeId=@STypeId AND S.ATypeID=A.ATypeId AND A.Cid=@CId AND A.FYear=@SFYear AND A.FPeriod=@SFPeriod AND a.Cid = @Cid
SELECT @Error+=@@ERROR
--=================================更改期初表数据【END】===================================	


--DELETE Ac_IniAccount
--FROM Ac_IniAccount A 
--INNER JOIN #Assist F ON A.STypeId=@STypeId AND F.ATypeID=A.ATypeId AND A.Cid=@CId AND A.FYear=@SFYear AND A.FPeriod=@SFPeriod 
--SELECT @Error+=@@ERROR

----期初辅助核算主表数据
--DELETE Ac_IniAccount_Assist_CheckItems 
--FROM Ac_IniAccount_Assist_CheckItems A
--INNER JOIN #Assist S ON A.STypeId=@STypeId AND S.ATypeID=A.ATypeId AND A.Cid=@CId AND A.FYear=@SFYear AND A.FPeriod=@SFPeriod 
--SELECT @Error+=@@ERROR

----期初辅助核算明细表数据
--DELETE Ac_IniAccount_Assist_CheckItems_Detail 
--FROM Ac_IniAccount_Assist_CheckItems_Detail A
--INNER JOIN #Assist S ON A.STypeId=@STypeId AND S.ATypeID=A.ATypeId AND A.Cid=@CId AND A.FYear=@SFYear AND A.FPeriod=@SFPeriod 
--SELECT @Error+=@@ERROR



--=============================重新插入期初数据
--辅助核算明细表
INSERT INTO Ac_IniAccount_Assist_CheckItems_Detail
(
	STypeId,
	ATypeId,
	Cid,
	Ascids,
	FieldValue,
	IniYTotal,
	IniYTotalFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	IniTotal,
	IniTotalFor,
	GroupId,
	IniYqty,
	FDebitqty,
	FCreditqty,
	iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor
)
SELECT
	@STypeId STypeId,
	t.ATypeId,
	@CId Cid,
	C.Ascids,
	CASE WHEN C.Ascids=1 THEN ISNULL(T.STypeId,'')
			WHEN C.Ascids=2 THEN ISNULL(T.DTypeID,'')
			WHEN C.Ascids=3 THEN ISNULL(T.ETypeID,'')
			WHEN C.Ascids=4 THEN ISNULL(T.BTypeID,'')
			ELSE ''
	END FieldValue,
	ISNULL(dbo.F_RoundTotal(T.BillTotal),0) IniYTotal,
	ISNULL(dbo.F_RoundTotal(T.BillTotalFor),0) IniYTotalFor,
	0 FDebit,
	0 FDebitFor,
	0 FCredit,
	0 FCreditFor,
	dbo.F_RoundTotal(T.BillTotal) IniTotal,
	dbo.F_RoundTotal(T.BillTotalFor) IniTotalFor,
	t.GroupId,
	0 IniYqty,
	0 FDebitqty,
	0 FCreditqty,
	0 iniqty,
	@SFYear FYear,
	@SFPeriod FPeriod,
	0 FYTotal,
	0 FYTotalFor
FROM #TempData1 T
INNER JOIN Ac_Account_Assist_CheckItems C  ON C.STypeId=@STypeId AND C.ATypeId=T.ATypeId AND C.Cid=@Cid
INNER JOIN #Assist A ON A.ATypeID=C.ATypeId AND A.TID=0
SET @Error+=@@ERROR	

--辅助核算主表
INSERT INTO Ac_IniAccount_Assist_CheckItems
(
	STypeId,
	ATypeId,
	Cid,
	IniYTotal,
	IniYTotalFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	IniTotal,
	IniTotalFor,
	IniYqty,
	FDebitqty,
	FCreditqty,
	iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor
)
SELECT
	@STypeId STypeId,
	T.ATypeId,
	@CId Cid,
	ISNULL(dbo.F_RoundTotal(SUM(T.BillTotal)),0) IniYTotal,
	ISNULL(dbo.F_RoundTotal(SUM(T.BillTotalFor)),0) IniYTotalFor,
	0 FDebit,
	0 FDebitFor,
	0 FCredit,
	0 FCreditFor,
	dbo.F_RoundTotal(SUM(T.BillTotal)) IniTotal,
	dbo.F_RoundTotal(SUM(T.BillTotalFor)) IniTotalFor,
	0 IniYqty,
	0 FDebitqty,
	0 FCreditqty,
	0 iniqty,
	@SFYear FYear,
	@SFPeriod FPeriod,
	0 FYTotal,
	0 FYTotalFor
FROM #TempData1 T
WHERE EXISTS(SELECT TOP 1 1 FROM  #Assist A WHERE A.ATypeID=T.ATypeId AND A.TID=0)
--INNER JOIN dbo.Ac_Account_Assist_CheckItems C ON C.STypeId=@STypeId AND C.ATypeId=T.ATypeId AND C.Cid=@Cid
GROUP BY T.ATypeId,T.STypeId,T.DTypeID,ETypeID,BTypeID

--SELECT * FROM Ac_Account_Assist_CheckItems
SET @Error+=@@ERROR	
--账务期初表
INSERT INTO Ac_IniAccount                           
(
	STypeId,
	ATypeId,
	iniYTotal,
	iniYTotalFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	iniTotal,
	iniTotalFor,
	Cid,IniYqty,
	FDebitqty,
	FCreditqty,
	iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor,
	FYTotalDebit,
	FYTotalDebitFor,
	FYTotalCredit,
	FYTotalCreditFor
)
SELECT  
	@STypeId STypeId,
	T.ATypeId,
	ISNULL(dbo.F_RoundTotal(SUM(T.BillTotal)),0) iniYTotal,
	ISNULL(dbo.F_RoundTotal(SUM(T.BillTotalFor)),0) iniYTotalFor,
	0 FDebit,
	0 FDebitFor,
	0 FCredit,
	0 FCreditFor,
	dbo.F_RoundTotal(SUM(T.BillTotal)) iniTotal,
	dbo.F_RoundTotal(SUM(T.BillTotalFor)) iniTotalFor,
	@CId Cid,
	0 IniYqty,
	0 FDebitqty,
	0 FCreditqty,
	0 iniqty,
	@SFYear FYear,
	@SFPeriod FPeriod,
	0 FYTotal,
	0 FYTotalFor,
	0 FYTotalDebit,
	0 FYTotalDebitFor,
	0 FYTotalCredit,
	0 FYTotalCreditFor
FROM #TempData1 T
INNER JOIN #Assist A ON A.ATypeID=T.ATypeId
GROUP BY T.ATypeId
SET @Error+=@@ERROR



--返回带辅助核算科目的且在业务单据上辅助核算不满足条件的科目
SELECT @RetStr+=A.FullName+';' 
FROM #TempData T
INNER JOIN Ac_Account A ON A.StypeId=@STypeId AND A.TypeId=T.ATypeId
 WHERE T.ATypeID NOT IN(SELECT ATypeID FROM #Assist)

--SELECT * FROM #Assist

DROP TABLE #SType,#TempData,#Assist,#TempData1
--=================================更改期初表数据【BEGIN】===================================	
--事务处理
IF(@Error=0)
	COMMIT TRAN 
ELSE 
	ROLLBACK TRAN

IF(ISNULL(@RetStr,'')<>'')
	SET @RetStr=SUBSTRING(@RetStr,1,LEN(@RetStr)-1)

--SET @fullname =@RetStr

SELECT @RetStr FullName



SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



CREATE              PROCEDURE GP_BatchPassBlance
(
	@BillNumberID int
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @GoodsBillID int
DECLARE @MoneyBillID INT
DECLARE @GoodsDetailid INT
DECLARE @CompleteTotal  NUMERIC(24, 10) 
DECLARE @NCompleteTotal  NUMERIC(24, 10) 
DECLARE @SQL varchar(2000)

SET @GoodsBillID =0
SET @MoneyBillID =0
SET @CompleteTotal =0
SET @NCompleteTotal =0
SET @SQL=''

DECLARE @IFStopMoney char(1)
SET @IFStopMoney='0'

DECLARE @ReturnValue int
--Select ifstopMoney from billindex
declare @isok  NUMERIC(24, 10) 
declare @Jstatus  NUMERIC(24, 10) 
declare @Billtype int
DECLARE @GoodBillCompleteTotal  NUMERIC(24, 10) ,@GoodBillTotalMoney  NUMERIC(24, 10) 
DECLARE @GoodBillPreferencemoney  NUMERIC(24, 10) ,@GoodBillTotalInMoney  NUMERIC(24, 10) 
DECLARE @GoodBillChargeOffValue NUMERIC(24,10)	--被核销金额
DECLARE @GoodsBillType INT;  ---被结算单据类型
SELECT  GoodsBillID,MoneyBillID,GoodsBillDetailID,CompleteTotal,BillType,NCompleteTotal INTO #CompleteTotal FROM CompleteTotal WHERE MoneyBillID=@BillNumberID

SET @SQL ='DECLARE Rows_Cursor CURSOR FOR
					SELECT GoodsBillID,MoneyBillID,GoodsBillDetailID,CompleteTotal,BillType,NCompleteTotal FROM #CompleteTotal WHERE MoneyBillID='+Convert(varchar,@BillNumberID)+'
		  '

--PRINT @SQL
EXEC(@SQL)
--PRINT @SQL
OPEN Rows_Cursor
FETCH NEXT FROM Rows_Cursor INTO @GoodsBillID,@MoneyBillID,@GoodsDetailid,@CompleteTotal,@GoodsBillType,@NCompleteTotal
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
	SET @IFStopMoney='0'
	SELECT @IFStopMoney =ifStopMoney FROM Billindex where BillnumberID=@GoodsBillID
	IF @IFStopMoney ='1'
	BEGIN
		RETURN 8
	END

	IF @GoodsBillID<>0 AND @MoneyBillID<>0
	BEGIN
		IF @GoodsBillType IN (404,405)
			SELECT @BillType=billtype,
			@GoodBillCompleteTotal=ISNULL(CompleteTotal,0),
			@GoodBillTotalMoney = ISNULL(TaxTotalMoney,0),
			@GoodBillPreferencemoney = 0,
			@GoodBillTotalInMoney =0,
			@GoodBillChargeOffValue=ChargeOffTotal,
			@Jstatus=ISNULL(totalmoney, 0)-(ISNULL(CompleteTotal, 0)+ISNULL(ChargeOffTotal,0))
			FROM ReceiptBillIndex WHERE BillnumberID=@GoodsBillID
			
		ELSE IF @GoodsBillType IN (423,424,425,426)
			SELECT @BillType=billtype,
			@GoodBillCompleteTotal=ISNULL(CompleteTotal,0),
			@GoodBillTotalMoney = ISNULL(TotalMoney,0),
			@GoodBillPreferencemoney = ISNULL(Preferencemoney,0),
			@GoodBillTotalInMoney = ISNULL(TotalInMoney,0),
			@GoodBillChargeOffValue=ChargeOffTotal,
			@Jstatus=ISNULL(totalmoney, 0)-(ISNULL(totalinmoney, 0)+ISNULL(CompleteTotal, 0)+ISNULL(preferencemoney, 0)+ISNULL(ChargeOffTotal,0))
			FROM dbo.Coupon_BillIndex WHERE BillnumberID=@GoodsBillID
		ELSE 
			SELECT @BillType=billtype,
			@GoodBillCompleteTotal=ISNULL(CompleteTotal,0),
			@GoodBillTotalMoney = ISNULL(TotalMoney,0),
			@GoodBillPreferencemoney = ISNULL(Preferencemoney,0),
			@GoodBillTotalInMoney = ISNULL(TotalInMoney,0),
			@GoodBillChargeOffValue=ChargeOffTotal,
			@Jstatus=ISNULL(totalmoney, 0)-(ISNULL(totalinmoney, 0)+ISNULL(CompleteTotal, 0)+ISNULL(preferencemoney, 0)+ISNULL(ChargeOffTotal,0))
			FROM billindex WHERE BillnumberID=@GoodsBillID
		--SELECT @BillType=billtype FROM BillIndex Where BillNumberId=@GoodsBillID		
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID = @GoodsBillID AND MoneyBillID = @BillNumberID)
		BEGIN
			IF (@GoodBillTotalMoney>=0 AND (@GoodBillTotalMoney-@GoodBillPreferencemoney) < @GoodBillCompleteTotal+@CompleteTotal+@GoodBillTotalInMoney+@GoodBillChargeOffValue)
			OR (@GoodBillTotalMoney<0 AND (@GoodBillTotalMoney-@GoodBillPreferencemoney) > @GoodBillCompleteTotal+@CompleteTotal+@GoodBillTotalInMoney+@GoodBillChargeOffValue)
				RETURN 9
		END
		
		DECLARE @IsGood INT =0;
		--判断 存在按商品结算的 @IsGood=1 存在按品牌 @IsGood=2 else =0
		IF EXISTS (SELECT TOP 1 1 FROM dbo.CompleteGoodTotal WHERE GoodsBillID = @GoodsBillID AND MoneyBillID = @BillNumberID AND billtype=@GoodsBillType)
			SET  @IsGood=1
		IF EXISTS (SELECT TOP 1 1 FROM dbo.CompleteBrandarTotal WHERE GoodsBillID = @GoodsBillID AND MoneyBillID = @BillNumberID AND billtype=@GoodsBillType)
			SET  @IsGood=2
   		EXEC @ReturnValue =GP_InsertCompleteTotal @GoodsBillID,@GoodsDetailid,@MoneyBillID,@CompleteTotal,@NCompleteTotal,@IsGood,@GoodsBillType
		IF @ReturnValue<>0  -- 发生错误，提前返回
		BEGIN
			CLOSE Rows_Cursor	-- 关闭游标
			DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源
			DROP TABLE #CompleteTotal
			RETURN @ReturnValue
		END


IF (@BillType=161 OR @BillType=160)
    BEGIN
		SELECT @isok=ISNULL(totalmoney, 0)-(ISNULL(totalinmoney, 0)+ISNULL(CompleteTotal, 0)+ISNULL(preferencemoney, 0)+ISNULL(ChargeOffTotal,0))  FROM BillIndex WHERE BillNumberid=@GoodsBillID

		IF (@Jstatus*@isok<0)  --结算前未结算金额状态
	     BEGIN
			
			IF Not Exists(SELECT * FROM CompleteGoodTotal WHERE GoodsBillID=@GoodsBillID) 
			
			RETURN 3

		 END
	END

		SET @GoodsBillID =0		
		SET @MoneyBillID =0
		SET @CompleteTotal =0
		SET @NCompleteTotal =0
	END
	FETCH NEXT FROM Rows_Cursor INTO @GoodsBillID,@MoneyBillID,@GoodsDetailid,@CompleteTotal,@GoodsBillType,@NCompleteTotal
END

CLOSE Rows_Cursor	-- 关闭游标
DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源

EXEC @ReturnValue =GP_UpdateCompleteGoodTotal @BillNumberID

IF @ReturnValue<>0  -- 发生错误，提前返回
BEGIN
	--CLOSE Rows_Cursor	-- 关闭游标
	--DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源
	--DROP TABLE #CompleteTotal
	RETURN @ReturnValue
END

EXEC @ReturnValue =GP_UpdateCompleteBrandarTotal @BillNumberID
IF @ReturnValue<>0  -- 发生错误，提前返回
BEGIN
	RETURN @ReturnValue
END

DROP TABLE #CompleteTotal
RETURN 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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








Create  PROCEDURE  GP_BatchPassPT  
(
	@BillNumberID int,
	@BillType int
)
--@encode$--
AS
SET NOCOUNT  ON

DECLARE @intPromotePrice  NUMERIC(24, 10) 
DECLARE @TrackPrice  NUMERIC(24, 10)  -- 折后单价即跟踪价

DECLARE	@chvBillDate	varchar(100)
DECLARE	
	@chvBTypeID		varchar(50),
	@chvBTypeFlag INT=0----启用结算单位=0/往来单位=1 进行价格跟踪	
DECLARE	@chvKTypeID		varchar(50)	
DECLARE	@chvETypeID		varchar(50)	
DECLARE	@chvPTypeID		varchar(50),
		@chvSTypeID		varchar(50),
		@intCid			INT,
		@vipcardid		VARCHAR(50)

SET @chvBillDate =''
SET @chvBTypeID =''
SET @chvKTypeID =''
SET @chvETypeID =''
SET @chvPTypeID =''
SET @intPromotePrice =0
SET @TrackPrice =0
SET @chvSTypeID=''

-- 1结算 2往来
DECLARE @BtypeFlag INT=0;
--SELECT @PriceTrackType=Value,@BtypeFlag=CAST(value AS int)-1 FROM userconfig WHERE ConfigName='pricetracktype'

SELECT @BtypeFlag=value FROM dbo.PriceTrackConfig WHERE name='BuyBtypeFlag' 
AND EXISTS(SELECT 1 FROM dbo.PriceTrackNameBillSet WHERE  billtype=@BillType AND BuySaleType=1)
OR name='SaleBtypeFlag'
AND EXISTS(SELECT 1 FROM dbo.PriceTrackNameBillSet WHERE  billtype=@BillType AND BuySaleType=2)

--启用结算单位/往来单位 进行价格跟踪
IF EXISTS(SELECT 1 FROM dbo.PriceTrackNameBillSet WHERE  BillType=@BillType AND BuySaleType=1)
	BEGIN
		SELECT @chvBTypeFlag=Value FROM PriceTrackConfig WHERE Name='buybtypeflag'
	END
ELSE IF EXISTS(SELECT 1 FROM dbo.PriceTrackNameBillSet WHERE  billtype=@BillType AND BuySaleType=2)
	BEGIN
		SELECT @chvBTypeFlag=Value FROM PriceTrackConfig WHERE Name='salebtypeflag'
	END

IF @billtype NOT IN (300,301)
	BEGIN
		SELECT @chvBTypeID=CASE WHEN @chvBTypeFlag=0 THEN btypeid ELSE DealBTypeID END,@chvSTypeID=Stypeid,@chvKTypeID=ktypeid,@chvETypeID=etypeid
		,@chvBillDate=billDate,@intCid=cid FROM Billindex WHERE BillNumberId=@BillNumberID
	END
ELSE
	BEGIN
		SELECT @chvBTypeID=CASE WHEN @chvBTypeFlag=0 THEN btypeid ELSE DealBTypeID END,@chvSTypeID=Stypeid,@chvKTypeID=ktypeid,@chvETypeID=etypeid
		,@chvBillDate=billDate,@intCid=cid FROM dbo.OrderIndex WHERE BillNumberId=@BillNumberID
	END

IF EXISTS(SELECT 1 FROM billindex WHERE BillNumberId=@BillNumberID AND vipcardid=-1 AND costsale=0) AND @BillType NOT IN (300,301) --没有启用会员卡
	OR @BillType IN (300,301)
	EXEC Gp_AuditingPriceTrack @BillNumberID,@BillType,@chvBTypeID,@chvSTypeID,@chvKTypeID,@chvETypeID,'',@chvBillDate,@intCid,@btypeFlag

/*
DECLARE @TABLE varchar(200)
--SET @TABLE ='SaleBill'

--IF @BillType='305'
--	SET @TABLE ='RetailBill'
--IF @BillType='34'
--	SET @TABLE ='BuyBill'
	

SELECT @TABLE=detailTable FROM dbo.BillName WHERE billtype=@BillType

DECLARE @SQL varchar(2000)

SET @SQL ='DECLARE Rows_Cursor CURSOR FOR
				SELECT 
					b.BillDate,
					CASE WHEN '''+CAST(@BtypeFlag AS VARCHAR(10))+'''=''0'' THEN B.BtypeID ELSE B.DealBTypeID END AS BTypeId,
					b.KtypeID,
					b.EtypeID,
					s.PtypeID,
					s.DiscountPrice  as TrackPrice,
					b.STypeID,
					b.cid,
					b.VipCardID
				FROM 
					Billindex b,
					'+@TABLE+' s 
				WHERE 
					b.BillnumberID=s.BillnumberID
					AND b.BillnumberID ='+Convert(varchar,@BillNumberID)+'
					AND B.costsale = 0
		  '
EXEC(@SQL)
--PRINT @SQL
OPEN Rows_Cursor
FETCH NEXT FROM Rows_Cursor INTO @chvBillDate,@chvBTypeID,@chvKTypeID,@chvETypeID,@chvPTypeID,@TrackPrice,@chvSTypeID,@intCid,@vipcardid
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
	SELECT  @intPromotePrice =dbo.F_GetPriceTrack(@chvPTypeID,@chvBTypeID,@chvKTypeID,@chvETypeID,@chvBillDate)
	
	--EXEC Web_CheckPromotePrice @intPromotePrice outPut,@chvPTypeID,@chvBTypeID,@chvKTypeID,@chvETypeID,@chvBillDate
	IF @intPromotePrice=0
	BEGIN 
		IF ISNULL(@vipcardid,'')='' OR @vipcardid=-1 OR @vipcardid = 0	-- 没有使用VIP
		BEGIN
			EXEC Gp_AuditingPriceTrack @BillNumberID,@BillType,@chvBTypeID,@chvSTypeID,@chvKTypeID,@chvETypeID,'',@chvBillDate,@intCid,@btypeFlag
		END
	END
	SET @chvBillDate =''
	SET @chvBTypeID =''
	SET @chvKTypeID =''
	SET @chvETypeID =''
	SET @chvPTypeID =''
	SET @intPromotePrice =0
	SET @TrackPrice =0
	FETCH NEXT FROM Rows_Cursor INTO @chvBillDate,@chvBTypeID,@chvKTypeID,@chvETypeID,@chvPTypeID,@TrackPrice,@chvSTypeID,@intCid,@vipcardid
END

CLOSE Rows_Cursor	-- 关闭游标
DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源

RETURN 0
*/
SET QUOTED_IDENTIFIER OFF 







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE GP_BatchPassReleOrder
(
	@BillNumberID INT,
	@BillType	INT,
	@cid INT,
	@stypeid VARCHAR(50),
	@btypeid VARCHAR(50),
	@dealbtypeid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @ReleBillID INT
DECLARE @orderbillOver INT 
DECLARE @ordercid INT
DECLARE @orderatypeid VARCHAR(50)
DECLARE @orderstypeid VARCHAR(50)
DECLARE @orderbtypeid VARCHAR(50)
DECLARE @orderdealbtypeid VARCHAR(50)
DECLARE @orderTotalinmoney	NUMERIC(24, 10) 
DECLARE @orderCustomerTotal  NUMERIC(24, 10) 
DECLARE @Totalinmoney	NUMERIC(24, 10) 
DECLARE @atypeid VARCHAR(50)

SET @ReleBillID=0

IF @BillType = 4 --收款单
	SELECT @ReleBillID=ISNULL(RelevanceBillId,0),@Totalinmoney=ISNULL(total,0),@atypeid=AtypeId FROM dbo.gatheringBill WHERE BillNumberId=@BillNumberID AND RelevanceBillId>0
IF @BillType=66 --付款单
	SELECT @ReleBillID=ISNULL(RelevanceBillId,0),@Totalinmoney=ISNULL(total,0),@atypeid=AtypeId FROM dbo.paybill WHERE BillNumberId=@BillNumberID AND RelevanceBillId>0
IF @BillType IN (190,189)--预收付款单
	SELECT @ReleBillID=ISNULL(RelevanceBillId,0),@Totalinmoney=ISNULL(total,0),@atypeid=AtypeId FROM dbo.prebill WHERE BillNumberId=@BillNumberID AND RelevanceBillId>0
IF @ReleBillID>0
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE billNumberId=@ReleBillID)
	BEGIN
		SELECT @orderbillOver=billover,@orderCustomerTotal=customertotal,@orderTotalinmoney=totalinmoney,@ordercid=cid,@orderatypeid=atypeid,@orderstypeid=stypeid,@orderbtypeid=btypeid,@orderdealbtypeid=dealbtypeid 
		FROM dbo.OrderIndex WHERE billNumberId=@ReleBillID
		IF @orderbillOver=1
			RETURN 1 --订单已被中止
		IF @cid!=@ordercid
			RETURN 2 --币种不一致
		IF @stypeid!=@orderstypeid
			RETURN 3 --分支机构不一致
		IF @btypeid!=@orderbtypeid
			RETURN 4 --结算单位不一致
		IF @dealbtypeid!=@orderdealbtypeid
			RETURN 5 --往来单位不一致
		--IF @Totalinmoney>@orderCustomerTotal-@orderTotalinmoney 
		--	RETURN 6 --本次结算金额大于订单定金金额
		--IF @atypeid!=@orderatypeid AND @atypeCount < 2
		--	RETURN 7
	END
	ELSE
		RETURN 8 --关联订单不存
END
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * FROM dbo.sysobjects where id = object_id(N'[dbo].[GP_BatchSetEntryCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_BatchSetEntryCode]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：黄清
	日期：2013-05-16
	描述：批量启用条码
*/
CREATE PROCEDURE [dbo].[GP_BatchSetEntryCode]
(
    @OperatorID  		VARCHAR(50),
    @ParID              VARCHAR(MAX),
    @allcount			INT OUT, --总个数
    @resultcount		INT OUT	 --真正启用的个数
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Result (TypeID VARCHAR(50))
CREATE TABLE #Ptype (TypeID VARCHAR(50))
--商品
INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ParID,1,@OperatorID)
INSERT INTO #Result SELECT typeid FROM #Ptype

SELECT @allcount=COUNT(1) FROM #Ptype

--排除已启用条码
DELETE  #Result FROM Ptype P WHERE P.TYPEID=#Result.TypeID AND P.IfUseEntryCode=1

--排除编号与已有条码重复的
DELETE  #Result FROM Ptype P WHERE P.TYPEID=#Result.TypeID AND (p.USERCODE IN (SELECT EntryCode FROM Ptype ) OR P.USERCODE IN (SELECT EntryCode FROM PType_Units_Ext))

--符合要求的结果集启用同条码 并将商品的条码设置为编号
UPDATE PType
SET IfUseEntryCode=1,
	EntryCode=USERCODE
FROM #Result R 
WHERE R.TypeID=PType.typeId

SET @resultcount=@@ROWCOUNT

INSERT INTO dbo.PType_EntryCode_Ext
        ( Ptypeid ,
          EntryCode ,
          IsDefaultEntryCode
        )
SELECT R.TypeID,USERCODE,1 FROM #Result R INNER JOIN ptype ON R.TypeID=PType.typeId

CREATE TABLE #table
(
	id INT IDENTITY(1,1),
	ptypeid VARCHAR(50)
)
INSERT INTO #table(ptypeid )
SELECT typeId  FROM dbo.ptype

DECLARE @count INT ,@i int =1,@ptypeid VARCHAR(50)
SELECT @count = COUNT(*) FROM dbo.ptype 
WHILE(@i<=@count)
BEGIN
	SELECT @ptypeid = ptypeid FROM #table WHERE id = @i
	EXEC FillPtypeMultibarcode @ptypeid 
	SELECT @i=@i+1
END 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
GO






if exists (select * FROM dbo.sysobjects where id = object_id(N'[dbo].[GP_BatchSetGoodsNumBer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_BatchSetGoodsNumBer]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：黄清
	日期：2013-05-16
	描述：批量启用批号
*/
CREATE PROCEDURE [dbo].[GP_BatchSetGoodsNumBer]
(
    @OperatorID  		VARCHAR(50),
    @ParID              VARCHAR(MAX),
    @allcount			INT OUT, --总个数
    @resultcount		INT OUT	 --真正启用批号的个数
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Result (TypeID VARCHAR(50))
CREATE TABLE #Ptype (TypeID VARCHAR(50))
--商品
INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ParID,1,@OperatorID)
INSERT INTO #Result SELECT typeid FROM #Ptype

SELECT @allcount=COUNT(1) FROM #Ptype


--排除已启用批号的和服务商品，组合品
DELETE  #Result FROM Ptype P WHERE P.TYPEID=#Result.TypeID AND (P.IfUseGoodsNum=1 OR P.IsService=1 OR iscombinationproduct=1 )


--排除已使用过的
DECLARE @N INT
SELECT @N=COUNT(1) FROM #Result
DECLARE @inReturnValue INT
DECLARE @PtypeId VARCHAR(50)
WHILE(@N>0)
BEGIN
	SELECT TOP (@N) @PtypeId=TypeID FROM #Result
	EXEC Gp_IsUsedProduct @PtypeId,@inReturnValue OUT
	IF @inReturnValue =1
		DELETE FROM #Result WHERE TYPEID=@PtypeId
	
 	SET	@N=@N-1
END

--符合要求的结果集启用批号
UPDATE PType
SET IfUseGoodsNum=1
FROM #Result R 
WHERE R.TypeID=PType.typeId

SET @resultcount=@@ROWCOUNT

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

GO






if exists (select * FROM dbo.sysobjects where id = object_id(N'[dbo].[GP_BatchSetSetSerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_BatchSetSetSerial]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：黄清
	日期：2013-05-16
	描述：批量启用强制序列号管理
*/
CREATE PROCEDURE [dbo].[GP_BatchSetSetSerial]
(
    @OperatorID  		VARCHAR(50),
    @ParID              VARCHAR(MAX),
    @allcount			INT OUT, --总个数
    @resultcount		INT OUT	 --真正启用的个数
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Result (TypeID VARCHAR(50))
CREATE TABLE #Ptype (TypeID VARCHAR(50))
--商品
INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ParID,1,@OperatorID)
INSERT INTO #Result SELECT typeid FROM #Ptype

SELECT @allcount=COUNT(1) FROM #Ptype

--排除已启用强制序列号管理的
DELETE  #Result FROM Ptype P WHERE P.TYPEID=#Result.TypeID AND P.IfSerial=1 

--排除有库存的
DELETE FROM #Result FROM GoodsStocks G WHERE G.PtypeId=#Result.TypeID AND G.Qty<>0

--排除有期初的
DELETE FROM #Result FROM IniGoodsStocks G WHERE G.PtypeId=#Result.TypeID AND G.Qty<>0

--排除有代销库存的
DELETE FROM #Result FROM commissionstock G WHERE G.PtypeId=#Result.TypeID AND G.Qty<>0

--排除有维修库存的wx_goodsstocks
DELETE FROM #Result FROM wx_goodsstocks G WHERE G.PtypeId=#Result.TypeID AND G.Qty<>0

--排除有借欠单据的LendBill
DELETE FROM #Result FROM LendBill G WHERE G.PtypeId=#Result.TypeID

--排除服务商品
DELETE FROM #Result FROM Ptype P WHERE P.TYPEID=#Result.TypeID AND P.IsService=1 

--排除组合品
DELETE FROM #Result FROM Ptype P WHERE P.TYPEID=#Result.TypeID AND P.iscombinationproduct=1

--符合要求的结果集启用同序列号
UPDATE PType
SET IfSerial=1
FROM #Result R 
WHERE R.TypeID=PType.typeId

SET @resultcount=@@ROWCOUNT

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-30
	描述：批量修改分支机构物价信息
*/

CREATE PROCEDURE Gp_BatchUpdateStypePriceInfo
(
	@newpricetype	VARCHAR(MAX),	-- 新价格
	@pricetype		VARCHAR(MAX),	-- 老的价格类型
	@flag			VARCHAR(MAX),	-- 操作标识 + - 等
	@values			VARCHAR(MAX),	-- 操作值
	@float			VARCHAR(MAX),	-- 小数位数
	@stypeid		VARCHAR(MAX)	-- 分支机构
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @SQL VARCHAR(MAX)

--先将基本信息拷贝过来
INSERT INTO PType_STypePrice(PTypeID,STypeID) 
SELECT	TypeId,
		@stypeid as STypeId 
FROM	PType 
WHERE	typeId NOT IN (SELECT P.typeId FROM PType_STypePrice S,PType P WHERE S.PTypeID = P.typeId AND P.sonnum = 0 AND STypeID = @stypeid)
		AND sonnum = 0

SET @SQL = 'UPDATE	PType_STypePrice 
			SET		' + @newpricetype + ' = CASE
												WHEN CAST(ROUND(ISNULL(' + @pricetype + ' ' + @flag + ' ' + @values + ',0),' + @float + ') AS  NUMERIC(24, 10) )>=0 THEN CAST(ROUND(ISNULL(' + @pricetype + ' ' + @flag + ' ' + @values + ',0),' + @float + ') AS  NUMERIC(24, 10) )
												ELSE 0
											END
			WHERE	STypeId = ''' + @stypeid + ''''

BEGIN TRY
	--PRINT(@SQL)
	EXEC(@SQL)    
END TRY
BEGIN CATCH
	RAISERROR('更新价格时产生错误！',16,1)
	RETURN -1
END CATCH

RETURN 0


	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2010-10-08
	描述：价格调整
*/

CREATE PROCEDURE GP_Bill_PriceAdjust
(
	@TypeIDS	VARCHAR(MAX),
	@PriceType	VARCHAR(100),
	@Flag		VARCHAR(100),
	@Values		VARCHAR(100),
	@stypeid	VARCHAR(100),
	@D_Float	INT,
	@cid		VARCHAR(10),
	@Unitids    VARCHAR(MAX)=''
)
--@encode$--
AS
SET NOCOUNT ON

--商品信息
CREATE TABLE #PType(
	TypeID	VARCHAR(100),
	ShowOrder INT IDENTITY(1,1)
)

--单位信息
CREATE TABLE #TUnit 
(
	UnitID INT,
	ShowOrder INT IDENTITY(1,1)
)

INSERT INTO #TUnit ( UnitID ) SELECT A FROM dbo.f_splitAN(@Unitids,'|') WHERE ISNULL(a,'')<>''

DECLARE 
		@PTypeID		VARCHAR(MAX),
		@PTypeIds 		VARCHAR(MAX),
		@x				INT

SELECT @PTypeId=@TypeIDS

SET @PTypeID = RTRIM(LTRIM(@PTypeID))
SET @x = CHARINDEX('|',@PTypeID)

IF @x=0
BEGIN
	INSERT #PType(TypeID)
	SELECT @PTypeID
END
ELSE
BEGIN
	WHILE @x>=1
	BEGIN
		SET @PTypeIds = LEFT(@PTypeID,@x-1)
		
		INSERT #PType(TypeID)		
		SELECT @PTypeIDs
		
		
		SET @PTypeID=SUBSTRING(@PTypeID,@x+1,LEN(@PTypeID)-@x)

		SET @x=charindex('|',@PTypeID)
		
		IF @x=0
		BEGIN
			INSERT #PType(TypeID)		
			SELECT @PTypeID
		END
	END
END


DECLARE	@strSql	VARCHAR(MAX)


/*判断有没有启用分支机构价格*/
DECLARE @Type int
set @Type=(select top 1 pricetype from stype where typeid=@stypeid)

DECLARE @Rate VARCHAR(20)
DECLARE @RateFlag INT = 0
IF @cid = ''
	SET @Rate = 1
ELSE
BEGIN
	SELECT @Rate = rate,@RateFlag = basistype FROM Ac_Currency WHERE CID = @cid
END

IF @RateFlag = 0
	SET @Rate = '1/'+@Rate+''

CREATE TABLE #price
(
	ptypeid varchar(100),
	presaleprice1  NUMERIC(24, 10) ,
	presaleprice2  NUMERIC(24, 10) ,
	presaleprice3  NUMERIC(24, 10) ,
	presaleprice4  NUMERIC(24, 10) ,
	presaleprice5  NUMERIC(24, 10) ,
	presaleprice6  NUMERIC(24, 10) ,
	presaleprice7  NUMERIC(24, 10) ,
	presaleprice8  NUMERIC(24, 10) ,
	presaleprice9  NUMERIC(24, 10) ,
	presaleprice10  NUMERIC(24, 10) ,
	PreBuyPrice1	 NUMERIC(24, 10) ,
	PreBuyPrice2	 NUMERIC(24, 10) ,
	PreBuyPrice3	 NUMERIC(24, 10) ,
	PreBuyPrice4	 NUMERIC(24, 10) ,
	PreBuyPrice5	 NUMERIC(24, 10) ,
	retailprice		 NUMERIC(24, 10) ,
	topsaleprice	 NUMERIC(24, 10) ,
	lowsaleprice	 NUMERIC(24, 10) ,
	TopBuyPrice		 NUMERIC(24, 10) ,
	UnitID			 INT
)

IF @Type=1
BEGIN
	INSERT INTO #price
	(
			ptypeid,
			PreSalePrice1,
			PreSalePrice2,
			PreSalePrice3,
			PreSalePrice4,
			PreSalePrice5,
			PreSalePrice6,
			PreSalePrice7,
			PreSalePrice8,
			PreSalePrice9,
			PreSalePrice10,
			PreBuyPrice1,
			PreBuyPrice2,
			PreBuyPrice3,
			PreBuyPrice4,
			PreBuyPrice5,
			RetailPrice,
			TopSalePrice,
			LowSalePrice,
			TopBuyPrice,
			UnitID
	)
	select
			distinct
			a.TypeID,
			isnull(PreSalePrice1,0),
			isnull(PreSalePrice2,0),
			isnull(PreSalePrice3,0),
			isnull(PreSalePrice4,0),
			isnull(PreSalePrice5,0),
			isnull(PreSalePrice6,0),
			isnull(PreSalePrice7,0),
			isnull(PreSalePrice8,0),
			isnull(PreSalePrice9,0),
			isnull(PreSalePrice10,0),
			isnull(PreBuyPrice1,0),
			isnull(PreBuyPrice2,0),
			isnull(PreBuyPrice3,0),
			isnull(PreBuyPrice4,0),
			isnull(PreBuyPrice5,0),
			isnull(RetailPrice,0),
			isnull(TopSalePrice,0),
			isnull(LowSalePrice,0),
			ISNULL(TopBuyPrice,0),
			U.UnitID
		from #PType a
		INNER JOIN #TUnit U ON A.ShowOrder=U.ShowOrder
		LEft JOIN PType_STypePrice  b on  a.TypeID=b.PTypeID AND B.UnitID=U.UnitID AND b.STypeID=@stypeid
		--where b.STypeID=@stypeid
		
		--计算预设价格
		IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName='CalcMunitPrePriceByBaseWhenNone' AND Value=1)
		BEGIN
			UPDATE TMP SET 
				PreSalePrice1=CASE WHEN ISNULL(TMP.PreSalePrice1,0)=0 THEN ISNULL(Price.PreSalePrice1,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice1 END,
				PreSalePrice2=CASE WHEN ISNULL(TMP.PreSalePrice2,0)=0 THEN ISNULL(Price.PreSalePrice2,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice2 END,
				PreSalePrice3=CASE WHEN ISNULL(TMP.PreSalePrice3,0)=0 THEN ISNULL(Price.PreSalePrice3,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice3 END,
				PreSalePrice4=CASE WHEN ISNULL(TMP.PreSalePrice4,0)=0 THEN ISNULL(Price.PreSalePrice4,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice4 END,
				PreSalePrice5=CASE WHEN ISNULL(TMP.PreSalePrice5,0)=0 THEN ISNULL(Price.PreSalePrice5,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice5 END,
				PreSalePrice6=CASE WHEN ISNULL(TMP.PreSalePrice6,0)=0 THEN ISNULL(Price.PreSalePrice6,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice6 END,
				PreSalePrice7=CASE WHEN ISNULL(TMP.PreSalePrice7,0)=0 THEN ISNULL(Price.PreSalePrice7,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice7 END,
				PreSalePrice8=CASE WHEN ISNULL(TMP.PreSalePrice8,0)=0 THEN ISNULL(Price.PreSalePrice8,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice8 END,
				PreSalePrice9=CASE WHEN ISNULL(TMP.PreSalePrice9,0)=0 THEN ISNULL(Price.PreSalePrice9,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice9 END,
				PreSalePrice10=CASE WHEN ISNULL(TMP.PreSalePrice10,0)=0 THEN ISNULL(Price.PreSalePrice10,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice10 END,
				PreBuyPrice1=CASE WHEN ISNULL(TMP.PreBuyPrice1,0)=0 THEN ISNULL(Price.PreBuyPrice1,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice1 END,
				PreBuyPrice2=CASE WHEN ISNULL(TMP.PreBuyPrice2,0)=0 THEN ISNULL(Price.PreBuyPrice2,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice2 END,
				PreBuyPrice3=CASE WHEN ISNULL(TMP.PreBuyPrice3,0)=0 THEN ISNULL(Price.PreBuyPrice3,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice3 END,
				PreBuyPrice4=CASE WHEN ISNULL(TMP.PreBuyPrice4,0)=0 THEN ISNULL(Price.PreBuyPrice4,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice4 END,
				PreBuyPrice5=CASE WHEN ISNULL(TMP.PreBuyPrice5,0)=0 THEN ISNULL(Price.PreBuyPrice5,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice5 END,
				TopSalePrice=CASE WHEN ISNULL(TMP.TopSalePrice,0)=0 THEN ISNULL(Price.TopSalePrice,0)*ISNULL(ext.Rate,1) ELSE TMP.TopSalePrice END,
				LowSalePrice=CASE WHEN ISNULL(TMP.LowSalePrice,0)=0 THEN ISNULL(Price.LowSalePrice,0)*ISNULL(ext.Rate,1) ELSE TMP.LowSalePrice END,
				RetailPrice=CASE WHEN ISNULL(TMP.RetailPrice,0)=0 THEN ISNULL(Price.RetailPrice,0)*ISNULL(ext.Rate,1) ELSE TMP.RetailPrice END,
				TopBuyPrice=CASE WHEN ISNULL(TMP.TopBuyPrice,0)=0 THEN ISNULL(Price.TopBuyPrice,0)*ISNULL(ext.Rate,1) ELSE TMP.TopBuyPrice END
			FROM #Price TMP 
			INNER JOIN  PType_StypePrice Price ON TMP.PTypeID=Price.PTypeID AND Price.IsDefaultUnit=1 AND StypeID=@stypeid
			INNER JOIN dbo.PType_Units_Ext Ext ON TMP.PTypeID=Ext.PtypeID AND EXT.UnitsId=TMP.UnitID
		END
END
ELSE
BEGIN
	INSERT INTO #price
	(
			ptypeid,
			PreSalePrice1,
			PreSalePrice2,
			PreSalePrice3,
			PreSalePrice4,
			PreSalePrice5,
			PreSalePrice6,
			PreSalePrice7,
			PreSalePrice8,
			PreSalePrice9,
			PreSalePrice10,
			PreBuyPrice1,
			PreBuyPrice2,
			PreBuyPrice3,
			PreBuyPrice4,
			PreBuyPrice5,
			RetailPrice,
			TopSalePrice,
			LowSalePrice,
			TopBuyPrice,
			UnitID
	)
	SELECT
			distinct
			a.TypeID,
			isnull(PreSalePrice1,0),
			isnull(PreSalePrice2,0),
			isnull(PreSalePrice3,0),
			isnull(PreSalePrice4,0),
			isnull(PreSalePrice5,0),
			isnull(PreSalePrice6,0),
			isnull(PreSalePrice7,0),
			isnull(PreSalePrice8,0),
			isnull(PreSalePrice9,0),
			isnull(PreSalePrice10,0),
			isnull(PreBuyPrice1,0),
			isnull(PreBuyPrice2,0),
			isnull(PreBuyPrice3,0),
			isnull(PreBuyPrice4,0),
			isnull(PreBuyPrice5,0),
			isnull(RetailPrice,0),
			isnull(TopSalePrice,0),
			isnull(LowSalePrice,0),
			ISNULL(TopBuyPrice,0),
			U.UnitID
		from #PType a
		INNER JOIN #TUnit U ON A.ShowOrder=U.ShowOrder
		LEft JOIN PType_Price  b on  a.TypeID=b.PTypeID AND B.UnitID=U.UnitID
		
		--计算预设价格
		IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName='CalcMunitPrePriceByBaseWhenNone' AND Value=1)
		BEGIN
			UPDATE TMP SET 
				PreSalePrice1=CASE WHEN ISNULL(TMP.PreSalePrice1,0)=0 THEN ISNULL(Price.PreSalePrice1,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice1 END,
				PreSalePrice2=CASE WHEN ISNULL(TMP.PreSalePrice2,0)=0 THEN ISNULL(Price.PreSalePrice2,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice2 END,
				PreSalePrice3=CASE WHEN ISNULL(TMP.PreSalePrice3,0)=0 THEN ISNULL(Price.PreSalePrice3,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice3 END,
				PreSalePrice4=CASE WHEN ISNULL(TMP.PreSalePrice4,0)=0 THEN ISNULL(Price.PreSalePrice4,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice4 END,
				PreSalePrice5=CASE WHEN ISNULL(TMP.PreSalePrice5,0)=0 THEN ISNULL(Price.PreSalePrice5,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice5 END,
				PreSalePrice6=CASE WHEN ISNULL(TMP.PreSalePrice6,0)=0 THEN ISNULL(Price.PreSalePrice6,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice6 END,
				PreSalePrice7=CASE WHEN ISNULL(TMP.PreSalePrice7,0)=0 THEN ISNULL(Price.PreSalePrice7,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice7 END,
				PreSalePrice8=CASE WHEN ISNULL(TMP.PreSalePrice8,0)=0 THEN ISNULL(Price.PreSalePrice8,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice8 END,
				PreSalePrice9=CASE WHEN ISNULL(TMP.PreSalePrice9,0)=0 THEN ISNULL(Price.PreSalePrice9,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice9 END,
				PreSalePrice10=CASE WHEN ISNULL(TMP.PreSalePrice10,0)=0 THEN ISNULL(Price.PreSalePrice10,0)*ISNULL(ext.Rate,1) ELSE TMP.PreSalePrice10 END,
				PreBuyPrice1=CASE WHEN ISNULL(TMP.PreBuyPrice1,0)=0 THEN ISNULL(Price.PreBuyPrice1,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice1 END,
				PreBuyPrice2=CASE WHEN ISNULL(TMP.PreBuyPrice2,0)=0 THEN ISNULL(Price.PreBuyPrice2,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice2 END,
				PreBuyPrice3=CASE WHEN ISNULL(TMP.PreBuyPrice3,0)=0 THEN ISNULL(Price.PreBuyPrice3,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice3 END,
				PreBuyPrice4=CASE WHEN ISNULL(TMP.PreBuyPrice4,0)=0 THEN ISNULL(Price.PreBuyPrice4,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice4 END,
				PreBuyPrice5=CASE WHEN ISNULL(TMP.PreBuyPrice5,0)=0 THEN ISNULL(Price.PreBuyPrice5,0)*ISNULL(ext.Rate,1) ELSE TMP.PreBuyPrice5 END,
				TopSalePrice=CASE WHEN ISNULL(TMP.TopSalePrice,0)=0 THEN ISNULL(Price.TopSalePrice,0)*ISNULL(ext.Rate,1) ELSE TMP.TopSalePrice END,
				LowSalePrice=CASE WHEN ISNULL(TMP.LowSalePrice,0)=0 THEN ISNULL(Price.LowSalePrice,0)*ISNULL(ext.Rate,1) ELSE TMP.LowSalePrice END,
				RetailPrice=CASE WHEN ISNULL(TMP.RetailPrice,0)=0 THEN ISNULL(Price.RetailPrice,0)*ISNULL(ext.Rate,1) ELSE TMP.RetailPrice END,
				TopBuyPrice=CASE WHEN ISNULL(TMP.TopBuyPrice,0)=0 THEN ISNULL(Price.TopBuyPrice,0)*ISNULL(ext.Rate,1) ELSE TMP.TopBuyPrice END
			FROM #Price TMP 
			INNER JOIN PType_Price Price ON TMP.PTypeID=Price.PTypeID AND Price.IsDefaultUnit=1
			INNER JOIN dbo.PType_Units_Ext Ext ON TMP.PTypeID=Ext.PtypeID AND EXT.UnitsId=TMP.UnitID
		END
	END

		SELECT @strSql='
		SELECT a.TypeID,b.unitid,ISNULL(ROUND('+@Rate+'*b.'+@PriceType+@Flag+@Values+','+CAST(@D_Float AS VARCHAR(10))+'),0) AS NewPrice
		FROM #PType a
		INNER JOIN #price b ON a.TypeID=b.PTypeID 
		INNER JOIN #TUnit U ON A.ShowOrder=U.ShowOrder AND B.UnitID=U.UnitID
		ORDER BY a.ShowOrder,typeid
		'

--PRINT @strSql
EXEC(@strSql)

DROP TABLE #price
DROP TABLE #TUnit
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2010-10-08
	描述：价格调整2
*/

CREATE PROCEDURE GP_Bill_PriceAdjust2
(
	@TypeIDS	VARCHAR(MAX),
	@OldPrice	VARCHAR(MAX),
	@Flag		VARCHAR(100),
	@Values		VARCHAR(100),
	@D_Float	INT,
	@unitids    VARCHAR(MAX)=''
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #PType(
	TypeID	VARCHAR(100),
	ShowOrder INT IDENTITY(1,1)
)

CREATE TABLE #Munit(
	UnitID INT,
	ShowOrder INT IDENTITY(1,1)
)

CREATE TABLE #OldPrice(
	OldPrice   NUMERIC(24, 10) ,
	ShowOrder INT IDENTITY(1,1)
)


DECLARE 
		@PTypeID		VARCHAR(MAX),
		@PTypeIds 		VARCHAR(MAX),
		@x				INT

SELECT @PTypeId=@TypeIDS

SET @PTypeID = RTRIM(LTRIM(@PTypeID))
SET @x = CHARINDEX('|',@PTypeID)

IF @x=0
BEGIN
	INSERT #PType(TypeID)
	SELECT @PTypeID
END
ELSE
BEGIN
	WHILE @x>=1
	BEGIN
		SET @PTypeIds = LEFT(@PTypeID,@x-1)
		
		INSERT #PType(TypeID)		
		SELECT @PTypeIDs
		
		
		SET @PTypeID=SUBSTRING(@PTypeID,@x+1,LEN(@PTypeID)-@x)

		SET @x=charindex('|',@PTypeID)
		
		IF @x=0
		BEGIN
			INSERT #PType(TypeID)		
			SELECT @PTypeID
		END
	END
END


SELECT @PTypeId=@OldPrice

SET @PTypeID = RTRIM(LTRIM(@PTypeID))
SET @x = CHARINDEX('|',@PTypeID)

IF @x=0
BEGIN
	INSERT #OldPrice(OldPrice)
	SELECT @PTypeID
END
ELSE
BEGIN
	WHILE @x>=1
	BEGIN
		SET @PTypeIds = LEFT(@PTypeID,@x-1)
		
		INSERT #OldPrice(OldPrice)
		SELECT @PTypeIDs
		
		
		SET @PTypeID=SUBSTRING(@PTypeID,@x+1,LEN(@PTypeID)-@x)

		SET @x=charindex('|',@PTypeID)
		
		IF @x=0
		BEGIN
			INSERT #OldPrice(OldPrice)
			SELECT @PTypeID
		END
	END
END

INSERT INTO #Munit( UnitID) SELECT A FROM dbo.f_splitAN(@unitids,'|') WHERE ISNULL(A,'')<>''

DECLARE
	@strSql			VARCHAR(MAX)

SELECT @strSql='
SELECT a.TypeID,M.unitid,ROUND(b.OldPrice'+@Flag+@Values+','+CAST(@D_Float AS VARCHAR(10))+') AS NewPrice
FROM #PType a
INNER JOIN #OldPrice b
ON a.ShowOrder=b.ShowOrder
INNER JOIN #MUnit M ON A.ShowOrder=M.ShowOrder
ORDER BY a.ShowOrder
'

--PRINT @strSql

EXEC(@strSql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-------------------------------------------------------------------------
--重置单据审核流程，使未审核完成的单据返回初始状态，等待重新开始审核。
--作者：王浩源
--日期：2003-11-26
-------------------------------------------------------------------------
CREATE               PROCEDURE Gp_BillAuditingBill_ReSet
(
	@BillType		int,			--单据类型编号	
	@OperatorID 	VARCHAR(50)		--操作员ID号
)
--@encode$--
AS

SET NOCOUNT ON

--删除单据审核细节
DELETE AuditingBillDetail 
WHERE 
	EXISTS (
		SELECT billnumberid 
		FROM billindex AS b 
		WHERE b.BillType=@BillType
		AND b.BillNumberID=auditingbilldetail.BillNumberID
	)

--获取正在使用的审核流程编号
DECLARE @AuditingID INT 
SELECT @AuditingID=AuditingID 
FROM AuditingFlowSet 
WHERE IfUse=1
AND BillType=@BillType

--更新在审的单据的审核配置
UPDATE AuditingBill
SET 
	AuditingID=@AuditingID,
	AuditingSteps='',
	IfAudit='-1',
	BillDetail=IsNull(Cast(BillDetail as VARCHAR(2000)),'') + '[times][who]' + '因为审核流程改变而重新进行审核'
WHERE 
	EXISTS (
		SELECT billnumberid 
		FROM billindex AS b 
		WHERE b.BillType=@BillType
		AND b.BillNumberID=AuditingBill.BillNumberID
	)
	AND IfAudit=0 --未审核完成的单据才需要重新开始审核


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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



CREATE    PROCEDURE GP_BillAuditingCheckEType (
	@nBillID	  NUMERIC(24, 10) ,
	@ETypeId	 Varchar(100)
)
--@encode$--
AS

Declare @AuditID	 NUMERIC(24, 10) 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

-----------------------------------------------
--作者：谢吉康
--日期：2003-11-14
--描述：根据操作员的ID来判断是否有新的审核单据

--作者：谢吉康
--日期：2004-05-11
--描述：如果是特审人,则去掉小灯泡提示

--作者：谢吉康
--日期：2004-11-01
--描述：增加订单的审核提示
-----------------------------------------------
CREATE               PROCEDURE Gp_BillAuditingChkMessage
(
	@OperatorID	VARCHAR(50),
	@StartDate	DATETIME,
	@EndDate	DATETIME
	
)
--@encode$--
AS
SET NOCOUNT ON 


CREATE TABLE #Result(
	BillNumberID	VARCHAR(100),
	BillDate		DATETIME,
	BillCode		VARCHAR(300),
	BillType		INT,
	Etypeid			VARCHAR(200),
	Btypeid			VARCHAR(200),
	AudType			VARCHAR(200),
	BillIndexType	INT,
	AuditingStep	INT,
	efullname		VARCHAR(300),
	bfullname		VARCHAR(300)
)

INSERT INTO #Result EXEC Web_QueryMeAuditingBill @OperatorID,@StartDate,@EndDate,'','','','0'

DECLARE @count INT
DECLARE @output VARCHAR(100)
SET @output=''
SELECT @count=COUNT(*) FROM AuditingFlowDetail  WHERE ETypeID=@OperatorID AND  AuditingAlerm=1 --还没有查看过待审核
IF @count>0 AND ((SELECT COUNT(*) FROM #Result)>0)--当前操作员AuditingFlowDetail中AuditingAlerm的值大于零 AND 待审核数数据大于零
BEGIN
	SET @output= 'ok'		
END 
SELECT @output as 'tip'

DROP TABLE #Result


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

/*
作者：谢吉康
日期：2004-10-11
描述：加入订单的审核，同时预留借欠的审核

卢春 2009-06 重构审核

--9.6.1新增低于成本价销售审核，需求有一条如果设置了该审核条件无(允许低于成本价销售)权限时，
--不能自动过账，而如何判断是否低于成本价以及是否设置了该审核条件，在审核后判断较复杂
--因此在审核时新增@IncludeLowerCostPriceAudit辅助判断
*/
CREATE   PROCEDURE GP_BillAuditingDeal
(
	@OperatorID					VARCHAR(100),		-- 审核人 ID 值
	@nBillID					INT,				-- 单据 ID 号
	@AudStat					bit,				-- 本次审核情况：0、不通过　1、通过
	@AudExplain					VARCHAR(8000) = '',	-- 本次审核说明
	@BillIndexType				int=2,				-- 审核的单据类型  0.订单  1.借欠单据  2.一般物流单据
	@strReturnBillCode			VARCHAR(200)='' OUT,
	@IncludeLowerCostPriceAudit BIT=0 OUT			--是否有低于成本价销售审核记录

)
--@encode$--
AS

SELECT @strReturnBillCode=''


SET NOCOUNT ON

DECLARE 	@AudID INT						-- 单据审核设定ID值
DECLARE 	@CurSteps VARCHAR(50)			-- 当前审核的级数情况字串
DECLARE	 	@isAudited CHAR(2)				-- 是否已经是否经审核通过
DECLARE 	@AudLevels INT					-- 单据审核的级数
DECLARE 	@AudType INT					-- 审核的类型 0顺序审批，1任意审批，２会签审批
DECLARE 	@AudTypeName	VARCHAR(MAX)		-- 审核类型的名称
DECLARE 	@AudStep 	INT					-- 当前审核的级数
DECLARE 	@AudDesc	VARCHAR(MAX)			-- 字符表示的本次审核级别名称
DECLARE 	@strAudStat	CHAR(1)				-- 字符表示的本次审核结果
DECLARE 	@OperatorName	VARCHAR(MAX)		-- 审核人名字
DECLARE 	@ErrNo		INT					-- 返回错误码	正常为0,错误为负
DECLARE 	@TmpETypeId varchar(MAX)			--职员的ID
DECLARE 	@AllCheckCount int				--审核人的审核次数
DECLARE 	@Count	int						--审核的计数器
DECLARE 	@BillType int					--单据的类型
DECLARE 	@MaxAuditingStep int			--调拨单中的审核级数
DECLARE 	@Id		int						--调拨审核中的审核Id
DECLARE 	@AuditingStep 	int				--审核步骤
DECLARE 	@AllotFlag		int				--判断是否有出入库审核（仅限于调拨单）	1.只有出库或者是入库审核  0.两种审核都有
DECLARE 	@IsSpecialAudLevel bit		 	-- 是否特审级
DECLARE 	@UStep  int
DECLARE 	@UStep1 int
DECLARE		@PassSteps varchar(MAX)			-- 审核通过，需要完成的步骤。如21221，表示第2级和第5级需要审核通过，整张单才通过
DECLARE		@OutKty VARCHAR(1)				-- 针对调拨单，出入库审核方式下，o - 出库  i - 入库
DECLARE     @StepReasons VARCHAR(MAX)        -- 审核明细

SET @Count = 1
SET @MaxAuditingStep = 0
SET @AllotFlag = 1
SET @IsSpecialAudLevel = 0
SET @strAudStat = CAST(@AudStat AS CHAR(1))

SELECT @OperatorName = FullName FROM Employee WHERE TypeID = @OperatorID

IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberID=@nBillID AND BillIndexType=@BillIndexType)
	RETURN -18

-- 此审核方式ＩＤ号及已审的级数，是否已审核通过
SELECT	@AudID = AuditingID,
	 	@CurSteps = ISNULL(AuditingSteps,''),
		@PassSteps = ISNULL(PassSteps,''),
	 	@isAudited = IfAudit,
	 	@StepReasons=StepReasons
FROM 	AuditingBill
WHERE 	BillNumberID = @nBillID
		AND BillIndexType = @BillIndexType

SELECT @BillType = BillType FROM AuditingFlowSet WHERE AuditingID = @AudID

-- 此审核方式的总级数及审核类型
SELECT	@AudLevels = AuditingLevel,
		@AudType = AuditingType
FROM 	AuditingFlowSet
WHERE 	AuditingID = @AudID

--这里拆分字符串，还有其他方式？
IF @StepReasons LIKE N'%商品售价小于等于成本价均价审核%'
BEGIN
	SET @IncludeLowerCostPriceAudit=1
END
-- 先判断审核的状态
IF @isAudited <> '0'
BEGIN
	IF @isAudited = '1' RETURN -10		-- 此单据已审核(非待审状态退出)
	IF @isAudited = '-1' RETURN -13		-- 审核不通过
	RETURN -10
END


IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail WHERE ETypeID = @OperatorID AND AuditingID = @AudID AND AuditingStep = 0)
BEGIN
	SET @IsSpecialAudLevel = 1
	
	SELECT TOP 1 @AudDesc = AuditingDescription FROM AuditingFlowDetail
	WHERE ETypeID = @OperatorID AND AuditingID = @AudID AND AuditingStep = 0
	
	IF ISNULL(@AudDesc,'') = '' SET @AudDesc = '特审'
	SET @AudStep = 0
END





-- 特别审核处理（优先于任何形式的审核）
IF @IsSpecialAudLevel = 1
BEGIN
	SET @CurSteps = SUBSTRING(@CurSteps,1,@AudLevels) + @strAudStat
	IF @strAudStat = 0
		SET @IsAudited = -1
	IF @strAudStat = 1
		SET @IsAudited = 1
	GOTO Mark_OK			-- 审核退出
END

-- 查询当前操作员的审核级别，可能是多级情况，用游标处理
DECLARE Step_Cursor CURSOR SCROLL static FOR
	SELECT 	AuditingStep,
			AuditingDescription,
			OutKty
	FROM 	AuditingFlowDetail
	WHERE	ETypeId = @OperatorID
		 	AND AuditingID = @AudID
	ORDER BY AuditingStep

OPEN Step_Cursor
FETCH NEXT FROM Step_Cursor INTO @AudStep,@AudDesc,@OutKty
IF @@FETCH_STATUS = -1
BEGIN
	SET @ErrNo = -11	-- 没有审核权限 ,查无此人
	GOTO Mark_Error
END




-- 审核类型：1顺序审批，2任意审批，3会签审批
-- 根据审核类型处理审核处理流程
IF @AudType = 1
BEGIN

	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 顺签审核前提：本级审核前全部通过
		IF SUBSTRING(@CurSteps,@AudStep,1) = '2' AND LEFT(@CurSteps,@AudStep-1) + '1' =LEFT(@PassSteps,@AudStep)
		BEGIN								
			SET @CurSteps = LEFT(@CurSteps, @AudStep - 1) + @strAudStat + RIGHT(@CurSteps, LEN(@CurSteps) - @AudStep)

					
			IF @strAudStat = 0
				SET @IsAudited = -1			-- 审核不通过，草稿打回
			ELSE
			BEGIN
				IF @CurSteps = @PassSteps	
					SET @IsAudited = 1		-- 最后一级,本单据审核通过
				ELSE
					SET @IsAudited = 0		-- 非最后一级,本单据待审
			END

			IF @BillType IN (17,21)
			BEGIN
				IF EXISTS (SELECT TOP 1 1 FROM AuditingFlowDetail WHERE AuditingID = @AudID AND OutKty = 'i')
				BEGIN
					--如果勾选了出入库审核，则要先判断出库仓库的权限
					IF @OutKty = 'o'
					BEGIN
						IF EXISTS
						(
							SELECT BillNumberID FROM billindex
							WHERE BillNumberID=@nBillID AND Ktypeid<>'' AND Ktypeid NOT IN
							(SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
						)
						BEGIN
							SET @ErrNo = -20	-- 操作员没有出库仓库的权限，不能审核
							CLOSE Step_Cursor
							DEALLOCATE Step_Cursor
							GOTO Mark_Error
						END
					END
					ELSE
					BEGIN
						IF EXISTS
						(
							SELECT BillNumberID FROM billindex
							WHERE BillNumberID=@nBillID AND Ktypeid2<>'' AND Ktypeid2 NOT IN
							(SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
						)
						BEGIN
							SET @ErrNo = -19	-- 操作员没有入库仓库的权限，不能审核
							CLOSE Step_Cursor
							DEALLOCATE Step_Cursor
							GOTO Mark_Error
						END
					END
				END
				ELSE
				BEGIN
					--如果没有勾选出入库审核，则只要有一边仓库的权限即可
					IF EXISTS
					(
						SELECT BillNumberID FROM billindex
						WHERE BillNumberID=@nBillID AND Ktypeid<>'' AND Ktypeid NOT IN
						(SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
						AND  Ktypeid2<>'' AND Ktypeid2 NOT IN
						(SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
					)
					BEGIN
						SET @ErrNo = -21	-- 操作员既没有入库仓库的权限，也没有出库仓库的权限，不能审核
						CLOSE Step_Cursor
						DEALLOCATE Step_Cursor
						GOTO Mark_Error
					END
				END
			END

			-- 资金调拨单
			IF @BillType = 310
			BEGIN
				IF EXISTS (SELECT TOP 1 1 FROM AuditingFlowDetail WHERE AuditingID = @AudID AND OutKty = 'i')
				BEGIN
					--如果勾选了出入库审核，则要先判断调出分支机构的权限
					IF @OutKty = 'o'
					BEGIN
						IF EXISTS
						(
							SELECT BillNumberID FROM billindex
							WHERE BillNumberID=@nBillID AND Stypeid<>'' AND Stypeid NOT IN
							(SELECT typeid FROM  F_GetAllManagerBaseTypeId('','11',@OperatorID))
						)
						BEGIN
							SET @ErrNo = -22	-- 操作员没有调出机构的权限，不能审核
							CLOSE Step_Cursor
							DEALLOCATE Step_Cursor
							GOTO Mark_Error
						END
					END
					ELSE
					BEGIN
						IF EXISTS
						(
							SELECT BillNumberID FROM billindex
							WHERE BillNumberID=@nBillID AND StypeID2<>'' AND StypeID2 NOT IN
							(SELECT typeid FROM F_GetAllManagerBaseTypeId('','11',@OperatorID))
						)
						BEGIN
							SET @ErrNo = -23	-- 操作员没有调入机构的权限，不能审核
							CLOSE Step_Cursor
							DEALLOCATE Step_Cursor
							GOTO Mark_Error
						END
					END
				END
				ELSE
				BEGIN
					--如果没有勾选出入库审核，则只要有一边分支机构的权限即可
					IF EXISTS
					(
						SELECT BillNumberID FROM billindex
						WHERE BillNumberID=@nBillID AND Stypeid<>'' AND Stypeid NOT IN
						(SELECT typeid FROM F_GetAllManagerBaseTypeId('','11',@OperatorID))
						AND  StypeID2<>'' AND StypeID2 NOT IN
						(SELECT typeid FROM F_GetAllManagerBaseTypeId('','11',@OperatorID))
					)
					BEGIN
						SET @ErrNo = -24	-- 操作员既没有调出机构的权限，也没有调入机构的权限，不能审核
						CLOSE Step_Cursor
						DEALLOCATE Step_Cursor
						GOTO Mark_Error
					END
				END
			END
			
			
			

			CLOSE Step_Cursor
			DEALLOCATE Step_Cursor
			GOTO Mark_OK
		END
		FETCH NEXT FROM Step_Cursor INTO  @AudStep,@AudDesc,@OutKty
	END

	SET @ErrNo = -15		-- 非当前步骤，不可越前审核
	CLOSE Step_Cursor
	DEALLOCATE Step_Cursor
	GOTO Mark_Error
END

-- 审核类型：1顺序审批，2任意审批，3会签审批
IF @AudType = 3
BEGIN
	
	IF SUBSTRING(@CurSteps,@AudStep,1) = '2' AND SUBSTRING(@PassSteps,@AudStep,1) = '1'
	BEGIN
		-- 填入当前审核状态
		SET @CurSteps = SUBSTRING(@CurSteps,1,(@AudStep - 1)) + @strAudStat + SUBSTRING(@CurSteps,@AudStep + 1,@AudLevels - @AudStep)

		IF @strAudStat = 0
			SET @IsAudited = -1	-- 会签一人不过，全部不通过
		ELSE
			IF @CurSteps = @PassSteps
				SET @isAudited = 1
			ELSE
				SET @isAudited = 0

			IF @BillType IN (17,21)
			BEGIN
				IF EXISTS (SELECT TOP 1 1 FROM AuditingFlowDetail WHERE AuditingID = @AudID AND OutKty = 'i')
				BEGIN
					--如果勾选了出入库审核，则要先判断出库仓库的权限
					IF @OutKty = 'o'
					BEGIN
						IF EXISTS
						(
							SELECT BillNumberID FROM billindex
							WHERE BillNumberID=@nBillID AND Ktypeid<>'' AND Ktypeid NOT IN
							(SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
						)
						BEGIN
							SET @ErrNo = -20	-- 操作员没有出库仓库的权限，不能审核
							CLOSE Step_Cursor
							DEALLOCATE Step_Cursor
							GOTO Mark_Error
						END
					END
					ELSE
					BEGIN
						IF EXISTS
						(
							SELECT BillNumberID FROM billindex
							WHERE BillNumberID=@nBillID AND Ktypeid2<>'' AND Ktypeid2 NOT IN
							(SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
						)
						BEGIN
							SET @ErrNo = -19	-- 操作员没有入库仓库的权限，不能审核
							CLOSE Step_Cursor
							DEALLOCATE Step_Cursor
							GOTO Mark_Error
						END
					END
				END
				ELSE
				BEGIN
					--如果没有勾选出入库审核，则只要有一边仓库的权限即可
					IF EXISTS
					(
						SELECT BillNumberID FROM billindex
						WHERE BillNumberID=@nBillID AND Ktypeid<>'' AND Ktypeid NOT IN
						(SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
						AND  Ktypeid2<>'' AND Ktypeid2 NOT IN
						(SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
					)
					BEGIN
						SET @ErrNo = -21	-- 操作员既没有入库仓库的权限，也没有出库仓库的权限，不能审核
						CLOSE Step_Cursor
						DEALLOCATE Step_Cursor
						GOTO Mark_Error
					END
				END
			END
			
			
						-- 资金调拨单
			IF @BillType = 310
			BEGIN
				IF EXISTS (SELECT TOP 1 1 FROM AuditingFlowDetail WHERE AuditingID = @AudID AND OutKty = 'i')
				BEGIN
					--如果勾选了出入库审核，则要先判断调出分支机构的权限
					IF @OutKty = 'o'
					BEGIN
						IF EXISTS
						(
							SELECT BillNumberID FROM billindex
							WHERE BillNumberID=@nBillID AND Stypeid<>'' AND Stypeid NOT IN
							(SELECT typeid FROM  F_GetAllManagerBaseTypeId('','11',@OperatorID))
						)
						BEGIN
							SET @ErrNo = -22	-- 操作员没有调出机构的权限，不能审核
							CLOSE Step_Cursor
							DEALLOCATE Step_Cursor
							GOTO Mark_Error
						END
					END
					ELSE
					BEGIN
						IF EXISTS
						(
							SELECT BillNumberID FROM billindex
							WHERE BillNumberID=@nBillID AND StypeID2<>'' AND StypeID2 NOT IN
							(SELECT typeid FROM F_GetAllManagerBaseTypeId('','11',@OperatorID))
						)
						BEGIN
							SET @ErrNo = -23	-- 操作员没有调入机构的权限，不能审核
							CLOSE Step_Cursor
							DEALLOCATE Step_Cursor
							GOTO Mark_Error
						END
					END
				END
				ELSE
				BEGIN
					--如果没有勾选出入库审核，则只要有一边分支机构的权限即可
					IF EXISTS
					(
						SELECT BillNumberID FROM billindex
						WHERE BillNumberID=@nBillID AND Stypeid<>'' AND Stypeid NOT IN
						(SELECT typeid FROM F_GetAllManagerBaseTypeId('','11',@OperatorID))
						AND  StypeID2<>'' AND StypeID2 NOT IN
						(SELECT typeid FROM F_GetAllManagerBaseTypeId('','11',@OperatorID))
					)
					BEGIN
						SET @ErrNo = -24	-- 操作员既没有调出机构的权限，也没有调入机构的权限，不能审核
						CLOSE Step_Cursor
						DEALLOCATE Step_Cursor
						GOTO Mark_Error
					END
				END
			END
			
			
				
			CLOSE Step_Cursor
			DEALLOCATE Step_Cursor
			GOTO Mark_OK
	END

	SET @ErrNo = -16		-- 已审核，不可再审

	IF SUBSTRING(@CurSteps,@AudStep,1) = '2' AND SUBSTRING(@PassSteps,@AudStep,1) = '2'
		SET @ErrNo = -17

	CLOSE Step_Cursor
	DEALLOCATE Step_Cursor
	GOTO Mark_Error
END



Mark_OK:	
	--审核！！！！
	--字段：审核时间    审核级别名称   审 核 人   是否通过   审核说明     签呈方式		审核原因
	IF @BillType IN (17,21) AND ISNULL(@AudDesc,'') = ''
	BEGIN
		-- 检查是否有出入库审核的方式
		IF EXISTS (SELECT TOP 1 1 FROM AuditingFlowDetail WHERE AuditingID = @AudID AND OutKty = 'i')
		BEGIN
			IF @OutKty = 'o'
				SET @AudDesc = '出库审核：第' + CAST(@AudStep AS VARCHAR(5)) + '级审核'
			
			IF @OutKty = 'i'
			BEGIN	
				DECLARE @inAudStep INT
				SELECT TOP 1 @inAudStep = AuditingStep FROM AuditingFlowDetail WHERE AuditingID = @AudID AND OutKty = 'i' ORDER BY AuditingStep
				SET @AudDesc = '入库审核：第' + CAST(@AudStep - @inAudStep + 1 AS VARCHAR(5)) + '级审核'		
			END
		END
	END
	
	IF @BillType = 310 AND ISNULL(@AudDesc,'') = ''
	BEGIN
		-- 检查是否有出入库审核的方式
		IF EXISTS (SELECT TOP 1 1 FROM AuditingFlowDetail WHERE AuditingID = @AudID AND OutKty = 'i')
		BEGIN
			IF @OutKty = 'o'
				SET @AudDesc = '调出审核：第' + CAST(@AudStep AS VARCHAR(5)) + '级审核'
			
			IF @OutKty = 'i'
			BEGIN	
				DECLARE @inAudStep1 INT
				SELECT TOP 1 @inAudStep1 = AuditingStep FROM AuditingFlowDetail WHERE AuditingID = @AudID AND OutKty = 'i' ORDER BY AuditingStep
				SET @AudDesc = '调入审核：第' + CAST(@AudStep - @inAudStep1 + 1 AS VARCHAR(5)) + '级审核'		
			END
		END
	END
	
	DECLARE @CurrDate DATETIME=GETDATE();
	
	UPDATE 	AuditingBill
	SET	 	AuditingSteps = @CurSteps,
		 	IfAudit = @IsAudited,
		 	BillDetail = ISNULL(CAST(BillDetail AS VARCHAR(5000)),'') +
				CONVERT(VARCHAR(20),@CurrDate,120) + --10个字符增加到20个字符，显示时分秒
				'ж' + CASE ISNULL(@AudDesc,'') WHEN '' THEN '第' + CAST(@AudStep AS VARCHAR(5)) + '级审核'
						ELSE @AudDesc
					END +
				'ж' + @OperatorName +
				'ж' + @strAudStat +
				'ж' + @AudExplain + 
				'ж' + CAST(@AudType AS VARCHAR(2)) +
				CASE WHEN @PassSteps <> '' THEN 'ж' + CAST (@AudStep AS VARCHAR(5)) END + 'жи'
	WHERE 	BillNumberID = @nBillID
			AND BillIndexType = @BillIndexType

	-----------------AuditingBillDetail-----------------------
	INSERT INTO AuditingBillDetail(BillNumberID,
								   ETypeID,
								   BillIndexType,
								   AuditingStep,
								   AuditingFlag,
								   AuditingExplain,
								   AuditingDate)
	SELECT						   @nBillID,
								   typeid,
								   @BillIndexType,
								   @AudStep,
								   @strAudStat,
								   @AudExplain,
								   @CurrDate 
    FROM employee WHERE FullName=@OperatorName
	
	-----------------AuditingBillDetail-----------------------

	-- 关于审核消息
	--UPDATE AuditingFlowDetail SET AuditingAlerm = 0 WHERE AuditingID = @AudID AND AuditingStep = @AudStep
	UPDATE AuditingFlowDetail SET AuditingAlerm = 0 WHERE AuditingID = @AudID AND ETypeId = @OperatorID
	IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE IfAudit = 0)
		UPDATE AuditingFlowDetail SET AuditingAlerm = 0
	IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE AuditingID = @AudID AND IfAudit = 0)
		UPDATE AuditingFlowDetail SET AuditingAlerm = 0 WHERE AuditingID = @AudID

	IF @AudType = 1 AND @IsAudited = 0
	BEGIN
		CREATE TABLE #temp(
			BillNumberID INT,
			BillType	 NUMERIC(4, 0),
			PassFlag 	 bit,
			Reason 		 VARCHAR(MAX),
			value 		 VARCHAR(MAX),
			AuditingStep int
		)
		INSERT #temp EXEC GP_BillAudtingCheckReason @nBillID,@OperatorID,@BillIndexType,'',0
		DECLARE @ETypeID VARCHAR(100)

		DECLARE AuditingCursor CURSOR FOR
			SELECT ETypeId FROM AuditingFlowDetail
			WHERE AuditingId = @AudID AND AuditingStep IN (
				SELECT TOP 1 AuditingStep FROM #temp WHERE PassFlag=0 AND AuditingStep > @AudStep ORDER BY AuditingStep)
		OPEN AuditingCursor
		FETCH NEXT FROM AuditingCursor INTO @ETypeID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- 是否有修改他人草稿的权限  0.有 1.无
			DECLARE @ifCanEditOtherDraft INT
			--EXEC @ifCanEditOtherDraft = GP_CheckLimit @OperatorId, 135
			EXEC @ifCanEditOtherDraft = GP_CheckLimit @ETypeID, 135
			
			-- 是否有审核他人草稿的权限  0.有 1.无
			DECLARE @AuditingOtherDraft int	
			--EXEC @AuditingOtherDraft = GP_CheckLimit @OperatorID,467
			EXEC @AuditingOtherDraft = GP_CheckLimit @ETypeID,467
			
			DECLARE @checkeWhere VARCHAR(50)
			IF @ifCanEditOtherDraft = 0 OR @AuditingOtherDraft = 0
				SET @checkeWhere = '%%'
			ELSE
				SET @checkeWhere = @ETypeID
				--SET @checkeWhere = @OperatorId

			--print @OperatorId
			--print @ETypeID
			--print cast(@ifCanEditOtherDraft as varchar(100))
			--print cast(@AuditingOtherDraft as varchar(100))
			
			DECLARE @ifAlerm INT
			SET @ifAlerm = 0
			IF @BillType IN (17,21)	-- 处理调拨单的小灯泡提示
			BEGIN
				-- 检查仓库权限是否有效   0.有效   1.无效
				DECLARE @StockLimit  INT
				--EXEC @StockLimit = GP_CheckLimit @OperatorID,454
				EXEC @StockLimit = GP_CheckLimit @ETypeID,454
				-- 调拨单中，仓库的权限无效
				IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'MoveInOutKLimit' AND Value = '0') OR @StockLimit = 1
				BEGIN
					IF EXISTS(
						SELECT	TOP 1 1
						FROM	BillIndex
						WHERE	BillNumberId = @nBillID
								AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@ETypeID))
								AND (KTypeID IN (SELECT * FROM F_GetManDetailKType(@ETypeID)) OR KTypeID2 IN (SELECT * FROM F_GetManDetailKType(@ETypeID)))
								AND checke LIKE @checkeWhere
					)
						SET @ifAlerm = 1
				END
				ELSE
				BEGIN
					IF EXISTS(
						SELECT	TOP 1 1
						FROM	BillIndex
						WHERE	BillNumberId = @nBillID
								AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@ETypeID))
								AND (KTypeID IN (SELECT * FROM F_GetManDetailKType(@ETypeID)) AND KTypeID2 IN (SELECT * FROM F_GetManDetailKType(@ETypeID)))
								AND checke LIKE @checkeWhere
					)
						SET @ifAlerm = 1
				END
			END
			ELSE IF @BillType = 310
			BEGIN
				IF EXISTS(
					SELECT	TOP 1 1
					FROM	BillIndex
					WHERE	BillNumberId = @nBillID
							AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@ETypeID))
							AND (Stypeid IN (SELECT * FROM F_GetManDetailSType(@ETypeID)) AND StypeID2 IN (SELECT * FROM F_GetManDetailSType(@ETypeID)))
							AND checke LIKE @checkeWhere
				)
					SET @ifAlerm = 1
			END
			ELSE IF @BillType IN (328,327)	--门店单据
	        BEGIN
		    IF EXISTS(
			SELECT	TOP 1 1
			FROM	PosAllotApplyBillIndex
			WHERE	BillNumberId = @nBillID
					AND ApplyEtypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorId))					
					AND (KTypeID IN (SELECT * FROM F_GetManDetailKType(@OperatorId)) OR InKtypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorId)))
		            AND checke LIKE @checkeWhere
		        )
			SET @ifAlerm = 1
	        END
			ELSE IF @BillType IN (300,301)	-- 订单
			BEGIN
				IF EXISTS(
					SELECT	TOP 1 1
					FROM	OrderIndex
					WHERE	BillNumberId = @nBillID
							AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@ETypeID))
							AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@ETypeID))
							AND KTypeId IN (SELECT * FROM F_GetManDetailKType(@ETypeID))
				)
					SET @ifAlerm = 1
			END
			ELSE
			BEGIN
				IF EXISTS(
					SELECT	TOP 1 1
					FROM	BillIndex
					WHERE	BillNumberId = @nBillID
							AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@ETypeID))
							AND (BTypeId IN (SELECT * FROM F_GetManDetailBType(@ETypeID)) OR ISNULL(BTypeId,'')='')
							AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@ETypeID)) OR ISNULL(KTypeId,'')='')
							AND checke LIKE @checkeWhere
				)
					SET @ifAlerm = 1
			END
			
			IF @ifAlerm = 1
			BEGIN
				UPDATE	AuditingFlowDetail
				SET 	AuditingAlerm = 1
				WHERE	AuditingId = @AudID
						AND ETypeId = @ETypeID
						AND AuditingStep IN (SELECT TOP 1 AuditingStep FROM #temp WHERE PassFlag=0 AND AuditingStep > @AudStep ORDER BY AuditingStep)
			END
			
			FETCH NEXT FROM AuditingCursor INTO @ETypeID
		END
		CLOSE AuditingCursor
		DEALLOCATE AuditingCursor
		DROP TABLE #temp
	END

	--如果是订单，当审核通过后，就将OrderIndex中的IfAudit字段值改为1，否则为0
	DECLARE @OrderAudited int
	IF @BillIndexType = 0 AND @isAudited = 1
	BEGIN
		UPDATE OrderIndex SET IfAudit = 1 WHERE BillNumberId = @nBillId
		IF @BillType IN (300)
		BEGIN
			UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)+ISNULL(o.Qty,0)
			FROM QuotePriceBill q INNER JOIN (select SUM(Qty) AS Qty,askbillnumberid,askbillid FROM dbo.OrderBill WHERE billNumberID=@nBillId GROUP BY askbillnumberid,askbillid) o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.askbillid
			WHERE o.askbillnumberid<>0 AND o.askbillid<>0
			--引用数量最大不能超过报价单数量
			UPDATE QuotePriceBill SET UseQty=Qty
			WHERE BillNumberID IN (SELECT askbillnumberid FROM dbo.OrderBill WHERE billNumberID=@nBillId ) AND UseQty>Qty
			--已被引用的报价单状态改为成交
			UPDATE dbo.BillIndex SET IfBargainOn=1 
			WHERE BillNumberId IN (SELECT askbillnumberid from OrderBill WHERE billNumberID=@nBillId AND askbillnumberid<>0 AND askbillid<>0) AND BillType=184
		END
		ELSE IF @billType IN(301)
		BEGIN
		--重复了过账的时候就处理了一次Gp_UpdateOrderBillDT
			--UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)+ISNULL(o.Qty,0)
			--FROM AskPriceBill q INNER JOIN (select SUM(Qty) AS Qty,askbillnumberid,askbillid FROM dbo.OrderBill WHERE billNumberID=@nBillId GROUP BY askbillnumberid,askbillid) o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.askbillid
			--WHERE o.askbillnumberid<>0 AND o.askbillid<>0
			--引用数量最大不能超过报价单数量
			UPDATE AskPriceBill SET UseQty=Qty
			WHERE BillNumberID IN (SELECT askbillnumberid FROM dbo.OrderBill WHERE billNumberID=@nBillId ) AND UseQty>Qty
			--已被引用的询价单状态改为成交
			UPDATE dbo.BillIndex SET IfBargainOn=1 
			WHERE BillNumberId IN (SELECT askbillnumberid from OrderBill WHERE billNumberID=@nBillId AND askbillnumberid<>0 AND askbillid<>0) AND BillType=185
		END
	END
	
	--如果是报价单，当审核通过后，就将billindex中的IfAudit字段值改为1，否则为0
	IF @BillIndexType = 2 AND @BillType=184
	BEGIN
		IF @isAudited = 1 	
			UPDATE billindex SET IfAudit = 1 WHERE BillNumberId = @nBillId
		ELSE IF @isAudited = -1 	
			UPDATE billindex SET IfAudit = 0 WHERE BillNumberId = @nBillId
	END
	--提成单
	IF @BillIndexType = 4 AND @BillType=311
	BEGIN
		IF @isAudited = 1 	
			UPDATE CommissionBillNew SET BillState = 2, Checker = @OperatorID , CheckerTime = GETDATE(),FChecker = '',FCheckerTime=NULL WHERE BillNumberId = @nBillId  
		ELSE IF @isAudited = -1 	
			UPDATE CommissionBillNew SET BillState = 4, Checker = @OperatorID , CheckerTime = GETDATE(),FChecker = '',FCheckerTime=NULL WHERE BillNumberId = @nBillId
	END
	
	IF @BillIndexType =5 AND @BillType IN (404,405)
	BEGIN
			IF @isAudited = 1 	
			UPDATE ReceiptBillIndex SET  IfAudit=1,Assessor=@OperatorID WHERE BillNumberId = @nBillId  
		ELSE IF @isAudited = -1 	
			UPDATE ReceiptBillIndex SET  IfAudit=0,Assessor=@OperatorID WHERE BillNumberId = @nBillId
	END
	--借欠单据
	IF @BillIndexType = 1 
	BEGIN
		IF @isAudited = 1 	
			UPDATE dbo.LendIndex SET IfAudit = 1 WHERE BillNumberId = @nBillId  
		ELSE IF @isAudited = -1 	
			UPDATE dbo.LendIndex SET IfAudit = 0 WHERE BillNumberId = @nBillId
	END
	
	DECLARE
		@intBillType	INT
		
	SELECT @intBillType=BillType
	FROM OrderIndex
	WHERE BillNumberId = @nBillId
	
	IF @isAudited=1 AND @intBillType=301
	BEGIN
		DECLARE
			@intReturnID			numeric(10,0) ,		--新生成的单据的ID
			@strErrMsg				VARCHAR(MAX) 		--出错信息
			
		EXEC	GP_BuyOrderBill_CreateBill
			@OperatorID,
			@nBillID,
			@intReturnID OUT,
			@strReturnBillCode OUT,
			@strErrMsg OUT
		
		IF ISNULL(@strErrMsg,'')<>'' SET @strReturnBillCode='?'
		IF @strReturnBillCode='' SET @strReturnBillCode='0'
	END
		
	--生成收付款单、预收付款单
	IF @isAudited=1 AND @BillIndexType=0 AND @intBillType IN (300,313,301)
	BEGIN
		IF EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE billNumberId=@nBillID AND CustomerTotal<>0)
			BEGIN
				EXEC GP_OrderBill_CreateBill @nBillID,@intReturnID OUT,@strReturnBillCode OUT,@OperatorID
			END
	END
	
	RETURN 0
	
Mark_Error:
	RETURN @ErrNo

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@OperatorID					VARCHAR(100),		-- 审核人 ID 值
	@nBillID					INT,				-- 单据 ID 号
	@AudStat					bit,				-- 本次审核情况：0、不通过　1、通过
	@AudExplain					VARCHAR(8000),		-- 本次审核说明
	@BillIndexType				int,				-- 审核的单据类型  0.订单  1.借欠单据  2.一般物流单据
	@strReturnBillCode			VARCHAR(200),
	@IncludeLowerCostPriceAudit BIT					--是否有低于成本价销售审核记录


SELECT
	@OperatorID='00001',
	@nBillID=5,
	@AudStat=1,
	@AudExplain='',
	@BillIndexType=0
	
BEGIN TRAN

EXEC	GP_BillAuditingDeal
		@OperatorID,
		@nBillID,
		@AudStat,
		@AudExplain,
		@BillIndexType,
		@strReturnBillCode OUT,
		@IncludeLowerCostPriceAudit OUT
		
SELECT	@strReturnBillCode,	@IncludeLowerCostPriceAudit	

ROLLBACK TRAN

*/



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

/*
作者：谢吉康
日期：2019-10-30
描述：处理审核相同审核人
*/
CREATE   PROCEDURE GP_BillAuditingDealSamePerson
(
	@OperatorID					VARCHAR(100),		-- 审核人 ID 值
	@nBillID					INT,				-- 单据 ID 号
	@AudStat					bit,				-- 本次审核情况：0、不通过　1、通过
	@AudExplain					VARCHAR(8000) = '',	-- 本次审核说明
	@BillIndexType				int=2,				-- 审核的单据类型  0.订单  1.借欠单据  2.一般物流单据
	@strReturnBillCode			VARCHAR(200)='' OUT,
	@IncludeLowerCostPriceAudit BIT=0 OUT			--是否有低于成本价销售审核记录

)
--@encode$--
AS

SELECT @strReturnBillCode=''


SET NOCOUNT ON

DECLARE 	@AudID INT						-- 单据审核设定ID值
DECLARE 	@CurSteps VARCHAR(50)			-- 当前审核的级数情况字串
DECLARE	 	@isAudited CHAR(2)				-- 是否已经是否经审核通过
DECLARE 	@AudLevels INT					-- 单据审核的级数
DECLARE 	@AudType INT					-- 审核的类型 0顺序审批，1任意审批，２会签审批
DECLARE 	@AudTypeName	VARCHAR(MAX)		-- 审核类型的名称
DECLARE 	@AudStep 	INT					-- 当前审核的级数
DECLARE 	@AudDesc	VARCHAR(MAX)			-- 字符表示的本次审核级别名称
DECLARE 	@strAudStat	CHAR(1)				-- 字符表示的本次审核结果
DECLARE 	@OperatorName	VARCHAR(MAX)		-- 审核人名字
DECLARE 	@ErrNo		INT					-- 返回错误码	正常为0,错误为负
DECLARE 	@TmpETypeId varchar(MAX)			--职员的ID
DECLARE 	@AllCheckCount int				--审核人的审核次数
DECLARE 	@Count	int						--审核的计数器
DECLARE 	@BillType int					--单据的类型
DECLARE 	@MaxAuditingStep int			--调拨单中的审核级数
DECLARE 	@Id		int						--调拨审核中的审核Id
DECLARE 	@AuditingStep 	int				--审核步骤
DECLARE 	@AllotFlag		int				--判断是否有出入库审核（仅限于调拨单）	1.只有出库或者是入库审核  0.两种审核都有
DECLARE 	@IsSpecialAudLevel bit		 	-- 是否特审级
DECLARE 	@UStep  int
DECLARE 	@UStep1 int
DECLARE		@PassSteps varchar(MAX)			-- 审核通过，需要完成的步骤。如21221，表示第2级和第5级需要审核通过，整张单才通过
DECLARE		@OutKty VARCHAR(1)				-- 针对调拨单，出入库审核方式下，o - 出库  i - 入库
DECLARE     @StepReasons VARCHAR(MAX)        -- 审核明细

SET @Count = 1
SET @MaxAuditingStep = 0
SET @AllotFlag = 1
SET @IsSpecialAudLevel = 0
SET @strAudStat = CAST(@AudStat AS CHAR(1))

SELECT @OperatorName = FullName FROM Employee WHERE TypeID = @OperatorID

IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberID=@nBillID AND BillIndexType=@BillIndexType)
	RETURN -18
	
SELECT	@AudID = AuditingID,
	 	@CurSteps = ISNULL(AuditingSteps,''),
		@PassSteps = ISNULL(PassSteps,''),
	 	@isAudited = IfAudit,
	 	@StepReasons=StepReasons
FROM 	AuditingBill
WHERE 	BillNumberID = @nBillID
		AND BillIndexType = @BillIndexType	

SELECT @BillType = BillType FROM AuditingFlowSet WHERE AuditingID = @AudID

--自动调用审核,处理同一个人审核人的情况
IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'samepersonchecked' AND Value = '1')
BEGIN	
	--处理审核消息
	DECLARE @nextStep			INT,
			@sameChecke			VARCHAR(50)
		
	--获取单据的制单人 		
	SELECT @sameChecke = Checke FROM dbo.AuditingBill WHERE BillNumberID = @nBillID AND BillIndexType = @BillIndexType
	
	IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType AND AuditingType = 3) AND EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail WHERE BillType = @BillType AND AuditingStep <> 0 AND ETypeID = @sameChecke)	--会签审核
	BEGIN		
		EXEC GP_BillAuditingDeal @sameChecke,@nBillID,'1','自动审核通过',@BillIndexType,'',''
	END
	ELSE
	BEGIN	
					
		IF EXISTS(SELECT TOP 1 AuditingStep FROM AuditingBillDetail WHERE BillNumberID = @nBillID AND BillIndexType = @BillIndexType)
			SELECT TOP 1 @nextStep = AuditingStep + 1 FROM AuditingBillDetail WHERE BillNumberID = @nBillID AND BillIndexType = @BillIndexType ORDER BY AuditingStep DESC
		ELSE 
			SET @nextStep = 1
			
		SELECT * INTO #AuditingFlowDetail FROM AuditingFlowDetail WHERE BillType = @BillType AND AuditingStep <> 0 AND ETypeID = @sameChecke
		
		WHILE EXISTS(SELECT TOP 1 1 FROM #AuditingFlowDetail WHERE AuditingStep = @nextStep)
		BEGIN
			EXEC GP_BillAuditingDeal @sameChecke,@nBillID,'1','自动审核通过',@BillIndexType,'',''
			SET @nextStep += 1
		END
		
		DROP TABLE #AuditingFlowDetail
	END	
END
	
	RETURN 0
	
Mark_Error:
	RETURN @ErrNo

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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








CREATE     PROCEDURE Gp_BillAuditingDeleteInOut 
(
	@AuditingID		int,			--单据审核ID
	@ifOut 		varchar(20) 		-- i 入库 o 出库

)
--@encode$--
AS
SET NOCOUNT ON

DELETE FROM AuditingFlowDetail WHERE AuditingID =@AuditingID AND OutKty=@ifOut
IF @@ROWCOUNT>0 
BEGIN
	DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0')
	DELETE FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0'
	-- 改变出库审核的级数
	IF @ifOut ='o'
		UPDATE AuditingFlowSet Set AuditingLevel =1 WHERE AuditingID =@AuditingID
	-- 改变入库审核的级数
	IF @ifOut ='i'
		UPDATE AuditingFlowSet Set AuditingLevel1 =1 WHERE AuditingID =@AuditingID
	-- 出入库审核都没有了，将审核原因值赋初始值
	IF NOT EXISTS(SELECT AuditingID FROM AuditingFlowDetail WHERE AuditingID =@AuditingID)
		UPDATE AuditingFlowSet SET Ifuse='0',AuditingReason='10000000000000000000000000000000000000000000000000' WHERE AuditingID =@AuditingID

	IF EXISTS (SELECT * FROM AuditingFlowSet WHERE Billtype =17 AND Substring(AuditingReason,14,1)='1' AND AuditingID =@AuditingID)
	BEGIN
		EXEC('GP_CheckAuditingInOut 17')
	END
	IF EXISTS (SELECT * FROM AuditingFlowSet WHERE Billtype =21 AND Substring(AuditingReason,14,1)='1' AND AuditingID =@AuditingID)
	BEGIN
		EXEC('GP_CheckAuditingInOut 21')
	END
END

RETURN 0












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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















-------------------------------------------------------------------------
--选取单据审核流程设置基本信息的存储过程
--作者：王浩源
--日期：2003-11-18
--引用：
-------------------------------------------------------------------------
CREATE                 PROCEDURE Gp_BillAuditingFlowSet_Select
(
	@BillType		int,			--单据类型编号	
	@OperatorID 	VARCHAR(100), 	--操作员ID号
	@IfUse 			int,
	@STypeId		varchar(max)	--分支机构
)
--@encode$--
AS

SET NOCOUNT ON

IF Not Exists (Select * FROM AuditingFlowSet WHERE BillType=@BillType AND STypeID = @STypeId)
	Begin
		Insert into AuditingFlowSet(BillType,AuditingType,AuditingLevel,IfUse,ETypeID,AuditingReason,AuditingDate,AuditingLevel1,STypeID)
		Values(@BillType,0,0,@IfUse,@OperatorID,'00000000000000000000000000000000000000000000000000',getdate(),1,@STypeId)
	End

select * from AuditingFlowSet where BillType=@BillType AND STypeID = @STypeId

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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









-------------------------------------------------------------------------
--维护单据审核流程设置基本信息的存储过程
--作者：王浩源
--日期：2003-11-18
--引用：
-------------------------------------------------------------------------
CREATE                                          PROCEDURE Gp_BillAuditingFlowSet_Update
(
	@AuditingID			int,			--审核流程编号
	@BillType			int,			--单据类型编号	
	@AuditingType		int,			--审核方式类型0－顺序，1－任意，2－会签
	@AuditingLevel		int,			--审核的级数
	@IfUse				char(10),		--该审核流程是否在使用0－禁用，1－启用
	@OperatorID 		VARCHAR(100),	--操作员ID号，流程修改人员
	@AuditingReason		varchar(200),	--审核原因编号
	@AuditingValue		varchar(200),	--审核原因的值
	@AuditingReasons	varchar(200),	--审核原因编号的二进值串
	@IfOut 				varchar(10)='o'			
)
--@encode$--
AS

SET NOCOUNT ON


select [ID],a INTO #Reason from dbo.f_splitAN(@AuditingReason,',')
select [ID],a INTO #Value from dbo.f_splitAN(@AuditingValue,',')

DECLARE @IfHaveSale int -- 判断之前是否有审核
DECLARE @IfHaveBuy int
SET @IfHaveSale = 0
SET @IfHaveBuy = 0
IF @BillType =300 -- 销售订单
	BEGIN
		IF EXISTS(SELECT * FROM AuditingFlowSet where Billtype =300 AND AuditingType<>0 AND LEFT(AuditingReason,1)<>'1')
			SET @IfHaveSale = 1
	END

IF @BillType =301 -- 采购订单
	BEGIN
		IF EXISTS(SELECT * FROM AuditingFlowSet where Billtype =301 AND AuditingType<>0 AND LEFT(AuditingReason,1)<>'1')
			SET @IfHaveBuy = 1
	END

DECLARE @Count int
DECLARE @Count1 int
SET @Count =0
SET @Count1 =0
SELECT @Count=Count(*) FROM #Reason
SELECT @Count1=Count(*) FROM #Value
IF @Count<>@Count1 
	RETURN -1 -- 审核原因的个数与审核原因的值的个数不等
ELSE
	SELECT X.* INTO #TT  FROM (SELECT M.[ID] as ID1,M.a as ReasonNo,N.a as ReasonValue FROM (SELECT * FROM #Reason) M LEFT JOIN (SELECT * FROM #Value) N ON M.[ID]=N.[ID]) X

-- 审核原因值的条数
DECLARE @ReasonCount int
DECLARE @ReasonCount1 int
SET @ReasonCount=0
SET @ReasonCount1=0

DECLARE @ifFlag char(1) -- 审核原因值是否改变
SET @ifFlag='0'

IF @Count=@Count1 
	SELECT @ReasonCount=Count(*) FROM #TT WHERE ReasonValue<>'AA'

SELECT @ReasonCount1=Count(*) FROM AuditingReason WHERE AuditingID=@AuditingID

IF @ReasonCount<>@ReasonCount1
	SET @ifFlag='1'


IF @ifFlag='0'
	BEGIN
		-- 审核原因值不等
		IF EXISTS(
				SELECT * FROM 
				(
					SELECT a.ReasonNo,isnull(a.ReasonValue,-98) as ReasonValue,isnull(b.ReasonValue,-99) as ReasonValue1 
					FROM 
						(SELECT * FROM AuditingReason WHERE AuditingID=@AuditingID) a 
					LEFT JOIN 
						(SELECT * FROM #TT WHERE ReasonValue<>'AA')  b 
					ON  
						a.ReasonNo=b.ReasonNo 
				) X 
				WHERE ReasonValue<>ReasonValue1
		)
		SET @ifFlag='1'	
	END

IF @ifFlag='0'
	BEGIN
		IF EXISTS(
				SELECT * FROM 
				(
					SELECT a.ReasonNo,isnull(a.ReasonValue,-98) as ReasonValue,isnull(b.ReasonValue,-99) as ReasonValue1 
					FROM 
						(SELECT * FROM AuditingReason WHERE AuditingID=@AuditingID) a 
					RIGHT JOIN 
						(SELECT * FROM #TT WHERE ReasonValue<>'AA')  b 
					ON  
						a.ReasonNo=b.ReasonNo 
				) X 
				WHERE ReasonValue<>ReasonValue1
		)
		SET @ifFlag='1'	
	END

DECLARE @Old_AuditingType int
DECLARE @Old_AuditingLevel int
DECLARE @Old_AuditingLevel1 int
DECLARE @Old_AuditingReason varchar(200)
IF EXISTS(select * from AuditingFlowSet WHERE AuditingID=@AuditingID)
	SELECT @Old_AuditingType=AuditingType,@Old_AuditingLevel=AuditingLevel,@Old_AuditingLevel1=AuditingLevel1,@Old_AuditingReason=AuditingReason from AuditingFlowSet WHERE AuditingID=@AuditingID
ELSE
	RETURN -2
/*	--20090601 李明洋
IF @IfOut ='o'  -- 出库(一般)更新
	UPDATE 	AuditingFlowSet 
	SET 	AuditingType=@AuditingType,
			AuditingLevel=@AuditingLevel,
			IfUse=@IfUse,
			ETypeID=@OperatorID,
			AuditingReason=@AuditingReasons,
			AuditingDate=getdate()
	WHERE	AuditingID=@AuditingID 
			and BillType=@BillType
ELSE  -- 入库更新
	UPDATE 	AuditingFlowSet 
	SET 	AuditingType=@AuditingType,
			AuditingLevel1=@AuditingLevel,
			IfUse=@IfUse,
			ETypeID=@OperatorID,
			AuditingReason=@AuditingReasons,
			AuditingDate=getdate()
	WHERE	AuditingID=@AuditingID 
			and BillType=@BillType
*/

IF @ifFlag='1'
BEGIN	
	-- 删除AuditingFlowDetail 
--	DELETE AuditingFlowDetail WHERE AuditingID=@AuditingID -- 20090601，注释掉
	-- 只删除待审核单据
	DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0');
	DELETE FROM AuditingBill WHERE AuditingID=@AuditingID AND ifaudit='0'
END
-- 改变审核原因 ,删除待审核草稿及出、入库审核设置明细
IF @AuditingReasons<>@Old_AuditingReason
BEGIN	
	-- 删除AuditingFlowDetail
--	DELETE AuditingFlowDetail WHERE AuditingID=@AuditingID			--修改，20090601李明洋
	-- 只删除待审核单据
	DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0');
	DELETE FROM AuditingBill WHERE AuditingID=@AuditingID AND ifaudit='0'
END
-- 改变审核方式,删除待审核草稿及出、入库审核设置明细
IF @AuditingType<>@Old_AuditingType
BEGIN
	DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0');
	DELETE FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0'
--	DELETE AuditingFlowDetail WHERE AuditingID=@AuditingID		       --修改，20090601李明洋
END
-- 改变出库审核级数,删除待审核草稿及出库审核设置明细
IF @Old_AuditingLevel<>@AuditingLevel AND @IfOut='o'
BEGIN
	DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0');
	DELETE FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0'
--	DELETE AuditingFlowDetail WHERE AuditingID=@AuditingID AND OutKty='o' --修改，20090601李明洋
END
-- 改变入库审核级数,删除待审核草稿及入库审核设置明细
IF @Old_AuditingLevel1<>@AuditingLevel AND @IfOut='i'
BEGIN
	DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0');
	DELETE FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0'
--	DELETE AuditingFlowDetail WHERE AuditingID=@AuditingID AND OutKty='i' --修改，20090601李明洋
END

-- 审核原因或审核方式改变时，出入库审核级数置 1
IF @AuditingReasons<>@Old_AuditingReason OR @AuditingType<>@Old_AuditingType OR  @ifFlag='1'
BEGIN	
	UPDATE 	AuditingFlowSet 
	SET 	AuditingLevel=1,
			AuditingLevel1=1
	WHERE	AuditingID=@AuditingID 
			and BillType=@BillType
END
-- 改变出库审核级数时，出库审核级数置 1
IF (@Old_AuditingLevel<>@AuditingLevel AND @IfOut='o') 
BEGIN	
	UPDATE 	AuditingFlowSet 
	SET    	AuditingLevel=1
	WHERE	AuditingID=@AuditingID 
			and BillType=@BillType
END
-- 改变入库审核级数时，入库审核级数置 1
IF (@Old_AuditingLevel1<>@AuditingLevel AND @IfOut='i')
BEGIN	
	UPDATE 	AuditingFlowSet 
	SET 	AuditingLevel1=1
	WHERE	AuditingID=@AuditingID 
			and BillType=@BillType
END

-- 只改变审核人时，删除审核设置明细
-- DELETE AuditingFlowDetail WHERE AuditingID=@AuditingID AND OutKty=@IfOut	--修改，李明洋 20090601
DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0');
DELETE FROM AuditingBill WHERE AuditingID=@AuditingID AND IfAudit='0' 

IF EXISTS (SELECT * FROM AuditingFlowSet where IfUse='0' AND AuditingID=@AuditingID) OR EXISTS (SELECT * FROM AuditingFlowSet where LEFT(AuditingReason,1)=1 AND AuditingID=@AuditingID)
	BEGIN
		DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
		DELETE FROM AuditingBill WHERE AuditingID=@AuditingID 
	END


-- 写入审核原因值 --修改，李明洋 20090601，全部注释
/*
DELETE auditingReason WHERE AuditingID=@AuditingID			        
DECLARE @SQL varchar(2000)
SET @SQL =''
DECLARE @ReasonNo int
DECLARE @ReasonValue varchar(200)
SET @ReasonNo =0
SET @ReasonValue=''

SET @SQL ='DECLARE Rows_Cursor CURSOR FOR
				SELECT	ReasonNo,ReasonValue  FROM #TT
		  '
EXEC(@SQL)

OPEN Rows_Cursor
FETCH NEXT FROM Rows_Cursor INTO @ReasonNo,@ReasonValue
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
	IF isnumeric(@ReasonNo)=1 AND @ReasonNo<>0 
	BEGIN
		IF LTRIM(RTRIM(@ReasonValue))<>'' AND LTRIM(RTRIM(@ReasonValue))<>'AA' AND isnumeric(LTRIM(RTRIM(@ReasonValue)))=1
			INSERT INTO AuditingReason VALUES (@AuditingID, 0,@ReasonNo,@ReasonValue)	
	END
	SET @ReasonNo =0
	SET @ReasonValue=''
	FETCH NEXT FROM Rows_Cursor INTO @ReasonNo,@ReasonValue
END
*/

-- 如果是出入库审核的出库审核设置，则会更新入库审核情况的级数
DECLARE @IMinStep int 
SET @IMinStep =1
IF @AuditingReason ='14' AND @IfOut ='o'
BEGIN
	SELECT @IMinStep = min(AuditingStep) FROM AuditingFlowDetail WHERE AuditingID = @AuditingID AND OutKty='i'
	IF @IMinStep <> 1
	BEGIN
		UPDATE AuditingFlowDetail SET AuditingStep=AuditingStep-@IMinStep+1  WHERE AuditingID = @AuditingID AND OutKty='i'
	END
END

DROP TABLE #Reason
DROP TABLE #Value
IF @Count=@Count1 
	DROP TABLE #TT
/*

前提：系统在设置订单审核之前，已经做了多张订单。这些订单中，有部分是已完成订单，有部分是曾被调用但属于未完成的订单，还有部分是未被调用过的订单。

在设置订单审核后，审核状态变化情况如下：
（1）已完成订单：变为审核通过
（2）未完成订单：变为审核通过
（3）未被调用过的订单：变为未提交审核的订单
（4）中止订单：在启用后，按上述（1）、（2）、（3）方式处理。

*/

DECLARE @IfHaveSale1 int -- 判断之后是否有审核
DECLARE @IfHaveBuy1 int
SET @IfHaveSale1 = 0
SET @IfHaveBuy1 = 0
IF @BillType =300 -- 销售订单
	BEGIN
		IF EXISTS(SELECT * FROM AuditingFlowSet where Billtype =300 AND AuditingType<>0 AND LEFT(AuditingReason,1)<>'1')
			SET @IfHaveSale1 = 1
	END

IF @BillType =301 -- 采购订单
	BEGIN
		IF EXISTS(SELECT * FROM AuditingFlowSet where Billtype =301 AND AuditingType<>0 AND LEFT(AuditingReason,1)<>'1')
			SET @IfHaveBuy1 = 1
	END
CREATE TABLE #BillnumberID (BillnumberID INT)
CREATE TABLE #BillnumberID1 (BillnumberID INT)
CREATE TABLE #BillnumberID2 (BillnumberID INT)

IF @BillType =300 -- 销售订单
	BEGIN
		IF @IfHaveSale = 0
		BEGIN
			IF @IfHaveSale1 = 1 -- 订单审核从无到有
			BEGIN
				-- 被调用过的订单或订单状态为已完成
				INSERT INTO #BillnumberID 
					select  BillnumberID   FROM OrderBill where OrderID IN (SELECT orderid From SaleBill) 
				UNION			
					select  BillnumberID   FROM OrderIndex WHERE Billtype =300 AND orderState ='1'
	
				
				-- 没被调用的订单IfAudit置0，清除AuditingBill
				Update orderindex set ifAudit=0 WHERE OrderState ='0' AND billtype =300 AND BillnumberID NOT IN (SELECT BillnumberID FROM #BillnumberID)
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN  (SELECT BillnumberID FROM Orderindex WHERE OrderState ='0' AND billtype =300 AND ifAudit =0) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID IN (SELECT BillnumberID FROM Orderindex WHERE OrderState ='0' AND billtype =300 AND ifAudit =0) AND AuditingID =@AuditingID
			END
		END
		ELSE
		BEGIN
			IF @IfHaveSale1 = 1 -- 订单审核从有到有 审核改变
			BEGIN
				-- 审核没通过或待审单据 
				INSERT INTO #BillnumberID SELECT BillnumberID FROM AuditingBill WHERE IfAudit ='0' AND AuditingID =@AuditingID 
				-- 被调用过的订单或订单状态为已完成
				INSERT INTO #BillnumberID1 
					select  BillnumberID   FROM OrderBill where OrderID IN (SELECT orderid From SaleBill) 
				UNION			
					select  BillnumberID   FROM OrderIndex WHERE Billtype =300 AND orderState ='1'
				-- 审核通过单据
				INSERT INTO #BillnumberID2 SELECT BillnumberID FROM AuditingBill WHERE IfAudit ='1' AND AuditingID =@AuditingID 
	
				--没有审核通过，待审核的订单IfAudit置0
				Update Orderindex SET IfAudit =0 WHERE orderState='0' AND Billtype=300 AND  BillnumberID  IN (SELECT BillnumberID FROM #BillnumberID)
				-- 不在审核通过，且不在被调用过的单据之中，IfAudit置0
				Update Orderindex SET IfAudit =0 WHERE orderState='0' AND Billtype=300 AND  (BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID1)) AND (BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID2))
				--没有审核通过，待审核的订单,清除AuditingBill
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM #BillnumberID)  AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID  IN (SELECT BillnumberID FROM #BillnumberID) AND AuditingID =@AuditingID
				-- 不在审核通过，且不在被调用过的单据之中，清除AuditingBill
				DELETE FROM AuditingBillDetail WHERE BillNumberID NOT IN (SELECT BillNumberID FROM #BillnumberID1) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)  AND BillNumberID NOT IN(SELECT BillNumberID FROM #BillnumberID2)
				DELETE FROM AuditingBill WHERE BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID1) AND AuditingID =@AuditingID AND BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID2)
			END
			ELSE	-- 订单审核从有到无 
			BEGIN
				-- 所有订单的IfAudit 置 1，清除订单的 AuditingBill
				Update orderindex set ifAudit=1 WHERE  billtype =300
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex WHERE billtype=300) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID IN (SELECT BillnumberID FROM Orderindex WHERE billtype =300 ) AND AuditingID =@AuditingID
			END
		END
	END

IF @BillType =301 -- 采购订单
	BEGIN
		IF @IfHaveBuy = 0
		BEGIN
			IF @IfHaveBuy1 = 1 -- 订单审核从无到有
			BEGIN
				-- 没被调用的订单IfAudit置0，清除AuditingBill
				INSERT INTO #BillnumberID 
					select  BillnumberID   FROM OrderBill where OrderID IN (SELECT orderid From BuyBill)
				UNION
					select  BillnumberID   FROM OrderIndex WHERE Billtype =301 AND orderState ='1'
	
				Update orderindex set ifAudit=0 WHERE OrderState ='0' AND billtype =301 AND BillnumberID NOT IN (SELECT BillnumberID FROM #BillnumberID)
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex WHERE OrderState='0' AND billtype=301 AND IfAudit=0) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID IN (SELECT BillnumberID FROM Orderindex WHERE OrderState ='0' AND billtype =301 AND ifAudit =0) AND AuditingID=@AuditingID
			END
		END
		ELSE
		BEGIN
			IF @IfHaveBuy1 = 1 -- 订单审核从有到有 审核改变
			BEGIN
				-- 审核没通过或待审单据 
				INSERT INTO #BillnumberID SELECT BillnumberID FROM AuditingBill WHERE IfAudit ='0' AND AuditingID =@AuditingID 
				-- 被调用过的订单或订单状态为已完成
				INSERT INTO #BillnumberID1 
					select  BillnumberID   FROM OrderBill where OrderID IN (SELECT orderid From BuyBill) 
				UNION			
					select  BillnumberID   FROM OrderIndex WHERE Billtype =301 AND orderState ='1'
				-- 审核通过单据
				INSERT INTO #BillnumberID2 SELECT BillnumberID FROM AuditingBill WHERE IfAudit ='1' AND AuditingID =@AuditingID 
	
				--没有审核通过，待审核的订单IfAudit置0
				Update Orderindex SET IfAudit =0 WHERE orderState='0' AND Billtype=301 AND  BillnumberID  IN (SELECT BillnumberID FROM #BillnumberID)
				-- 不在审核通过，且不在被调用过的单据之中，IfAudit置0
				Update Orderindex SET IfAudit =0 WHERE orderState='0' AND Billtype=301 AND  (BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID1)) AND (BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID2))
				--没有审核通过，待审核的订单,清除AuditingBill
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM #BillnumberID) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID  IN (SELECT BillnumberID FROM #BillnumberID) AND AuditingID =@AuditingID
				-- 不在审核通过，且不在被调用过的单据之中，清除AuditingBill
				DELETE FROM AuditingBillDetail WHERE BillNumberID NOT IN(SELECT BillNumberID FROM #BillnumberID1) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID) AND BillNumberID NOT IN (SELECT BillNumberID FROM #BillnumberID2)
				DELETE FROM AuditingBill WHERE BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID1) AND AuditingID =@AuditingID AND BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID2)
			END
			ELSE	-- 订单审核从有到无
			BEGIN
				-- 所有订单的IfAudit 置 1，清除订单的 AuditingBill
				Update orderindex set ifAudit=1 WHERE  billtype =301
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex WHERE billtype=301) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID IN (SELECT BillnumberID FROM Orderindex WHERE billtype =301 ) AND AuditingID =@AuditingID
			END
		END
	END


DROP TABLE #BillnumberID
DROP TABLE #BillnumberID1
DROP TABLE #BillnumberID2
--CLOSE Rows_Cursor	-- 关闭游标					--20090601
--DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



-----------------------------------------------
--作者：谢吉康
--日期：2003-11-14
--描述：多级审核的查询
-----------------------------------------------
CREATE                      PROCEDURE Gp_BillAuditingQuery
(
	@OperatorID	varchar(50),
	@StartDate	varchar(20),
	@EndDate	varchar(20),
	@ETypeID	varchar(50),
	@BillCode	varchar(200), 	
	@BillType	varchar(10),
	@Comment	varchar(200),
	@IfAudit	varchar(10),
	@BTypeID	varchar(50),
	@KTypeID	varchar(50),
	@STypeId	varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re

DECLARE @SQL VARCHAR(8000)	--定义SQL的查询字符串
SELECT 	@SQL = ''

--修改人：谢吉康
--日  期：2005-05-17
--描  述：检查调拨当中入库仓库是否有效
DECLARE @MoveInOutKLimit  int
--SELECT @MoveInOutKLimit=Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit'
EXEC @MoveInOutKLimit = GP_CheckLimit @OperatorId,454

--是否有审核他人草稿的权限
DECLARE @AuditingOtherDraft int	
EXEC @AuditingOtherDraft = GP_CheckLimit @OperatorID,467

------------------------------处理具体的参数值
IF @BillCode = ''
	SELECT @BillCode = '%'

IF @BillType = ''
	SELECT @BillType = '%'
--------------------------------------------------------------权限检查-------------------------------------------------------

--显示待审核的单据列表的时候，清空AuditingFlowDetail中的自动提示的标志位为0  
UPDATE	AuditingFlowDetail
SET		AuditingAlerm = 0
WHERE	ETypeID = @OperatorID

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

--查询具体的待审核的单据的列表
SELECT @SQL = '
		SELECT  A.BillType,
				A.AuditingType,
				A.AuditingLevel,
				Count(A.BillNumberID) AS BillCount
		INTO	#CheckBillInfo
		FROM 
			(
				SELECT	DISTINCT
						A.BillType,
						A.AuditingType,
						A.AuditingLevel,
						C.BillNumberID
				FROM	AuditingFlowSet A,
						AuditingFlowDetail B,
						AuditingBill C,
						BillIndex Bil,
						#GetManSTypeId S,
						#GetManDTypeId D
				WHERE 	A.AuditingID = B.AuditingID
						AND A.AuditingID = C.AuditingID
						AND C.BillNumberID = Bil.BillNumberID
						AND Bil.STypeId = S.TypeId
						AND Bil.DTypeId = D.TypeId
						AND A.IfUse = 1
						AND C.BillIndexType = 2
						AND Bil.RedWord = 0
						AND Bil.Draft=1
						AND Bil.IfYearBill = 0 '

				IF @AuditingOtherDraft = 1
					SELECT @SQL = @SQL + ' AND Bil.Checke = '+CHAR(39)+@OperatorID+CHAR(39)

				SELECT @SQL = @SQL + ' 
						AND A.BillType LIKE '+CHAR(39)+@BillType+CHAR(39)+'
						AND ISNULL(B.ETypeID,'''') LIKE '+CHAR(39)+@OperatorID+'%'+CHAR(39)+'				
						AND C.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND C.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND ISNULL(C.ETypeID,'''') IN (SELECT TypeId FROM #GetManETypeId)
						AND (
								(
									(ISNULL(Bil.BTypeID,'''') IN (SELECT TypeId FROM #GetManBTypeId)) AND Bil.BillType IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''148'',''149'',''150'',''151'',''160'',''161'',''165'',''166'',''167'',''168'',''169'',''170'',''171'',''172'',''178'',''183'',''186'')
								)
								OR
								(
									Bil.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''148'',''149'',''150'',''151'',''160'',''161'',''165'',''166'',''167'',''168'',''169'',''170'',''171'',''172'',''178'',''183'',''186'')
								)
							)
						AND (
								(
									(
										( ISNULL(Bil.KTypeID,'''') IN (SELECT TypeId FROM #GetManKTypeId) OR ISNULL(Bil.KTypeID2,'''') IN (SELECT TypeId FROM #GetManKTypeId)) AND Bil.BillType IN (''16'',''160'',''161'',''173'',''174'',''175'') 
									) 
									OR 
									(
										Bil.BillType IN (''305'',''11'',''45'',''34'',''6'',''9'',''14'',''139'',''126'',''140'',''142'',''144'',''146'',''165'',''167'',''168'',''169'',''170'',''178'',''183'') AND ISNULL(Bil.KTypeID,'''') IN (SELECT TypeId FROM #GetManKTypeId)
									)'
				--特殊处理成本调价单
				IF EXISTS(SELECT TOP 1 * FROM LoginUser WHERE ETypeId = @OperatorID AND MangerKTypeId = '00000')  
					SET @SQL = @SQL + 'OR
										(
											Bil.BillType IN (''57'') AND 1=1
										)'
				ELSE
					SET @SQL = @SQL + 'OR
										(
											Bil.BillType IN (''57'') AND ISNULL(Bil.KTypeID,'''') IN (SELECT TypeId FROM #GetManKTypeId)
										)'
				SET @SQL = @SQL + '	OR 
									( '

				IF @MoveInOutKLimit = 0
					SET @SQL = @SQL + '	Bil.BillType IN (''17'',''21'') AND (ISNULL(Bil.KTypeId,'''') IN (SELECT TypeId FROM #GetManKTypeId) AND ISNULL(Bil.KTypeId2,'''') IN (SELECT TypeId FROM #GetManKTypeId)) '
				ELSE
					SET @SQL = @SQL + '	Bil.BillType IN (''17'',''21'') AND (ISNULL(Bil.KTypeId,'''') IN (SELECT TypeId FROM #GetManKTypeId) OR ISNULL(Bil.KTypeId2,'''')  IN (SELECT TypeId FROM #GetManKTypeId)) '
				
				SET @SQL = @SQL + '
									)
									OR
									('

				SET @SQL = @SQL +'  ((Bil.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bil.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND Bil.BillType IN (166,172))'
				SET @SQL = @SQL +'  OR ((Bil.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bil.KTypeId2='''') AND Bil.BillType IN (166,172))'
				SET @SQL = @SQL +'  OR ((Bil.KTypeId='''' AND Bil.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND Bil.BillType IN (166,172))'
				SET @SQL = @SQL +'  OR ((Bil.KTypeId='''' AND Bil.KTypeId2='''') AND Bil.BillType IN (166,172))'

				SET @SQL = @SQL + '
									)
									OR
									(
										ISNULL(Bil.KTypeId,'''') LIKE ''%'' AND Bil.BillType NOT IN (''16'',''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''17'',''21'',''160'',''161'',''165'',''166'',''167'',''168'',''169'',''170'',''172'',''173'',''174'',''175'',''178'',''183'')
									)
								) 
							)
						AND C.BillCode LIKE '+CHAR(39)+@BillCode+'%'+CHAR(39)+'
						AND C.IfAudit = '+CHAR(39)+@IfAudit+CHAR(39)+'
						AND Substring(A.AuditingReason,1,1)<>1
				UNION ALL
				SELECT	DISTINCT
						A.BillType,
						A.AuditingType,
						A.AuditingLevel,
						C.BillNumberID
				FROM	AuditingFlowSet A,
						AuditingFlowDetail B,
						AuditingBill C,
						LendIndex Bil,
						#GetManDTypeId D
				WHERE 	A.AuditingID = B.AuditingID
						AND A.AuditingID = C.AuditingID
						AND C.BillNumberID = Bil.BillNumberID						
						AND Bil.DTypeId = D.TypeId
						AND A.IfUse = 1
						AND C.BillIndexType = 1
						AND Bil.RedWord = 0
						AND Bil.Draft=1 '
				IF @AuditingOtherDraft = 1
					SELECT @SQL = @SQL + ' AND Bil.Checke = '+CHAR(39)+@OperatorID+CHAR(39)

				SELECT @SQL = @SQL + ' 
						AND A.BillType LIKE '+CHAR(39)+@BillType+CHAR(39)+'
						AND ISNULL(B.ETypeID,'''') LIKE '+CHAR(39)+@OperatorID+'%'+CHAR(39)+'				
						AND C.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND C.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND ISNULL(Bil.KTypeID,'''') IN (SELECT TypeId FROM #GetManKTypeId)
						AND ISNULL(C.ETypeID,'''')   IN (SELECT TypeId FROM #GetManETypeId)
						AND C.BillCode LIKE '+CHAR(39)+@BillCode+'%'+CHAR(39)+'
						AND C.IfAudit = '+CHAR(39)+@IfAudit+CHAR(39)+'
						AND Substring(A.AuditingReason,1,1)<>1
				UNION ALL
				SELECT	DISTINCT
						A.BillType,
						A.AuditingType,
						A.AuditingLevel,
						C.BillNumberID
				FROM	AuditingFlowSet A,
						AuditingFlowDetail B,
						AuditingBill C,
						OrderIndex Bil,
						#GetManSTypeId S,
						#GetManDTypeId D
				WHERE 	A.AuditingID = B.AuditingID
						AND A.AuditingID = C.AuditingID
						AND C.BillNumberID = Bil.BillNumberID
						AND Bil.STypeId = S.TypeId
						AND Bil.DTypeId = D.TypeId
						AND A.IfUse = 1
						AND C.BillIndexType = 0
						AND Bil.RedWord = 0'
				--是否有审核他人草稿的权限
				IF @AuditingOtherDraft = 1
					SELECT @SQL = @SQL + ' AND Bil.Checke = '+CHAR(39)+@OperatorID+CHAR(39)
				--处理SQL字符串
				SELECT @SQL = @SQL + ' 
						AND A.BillType LIKE '+CHAR(39)+@BillType+CHAR(39)+'
						AND ISNULL(B.ETypeID,'''') LIKE '+CHAR(39)+@OperatorID+'%'+CHAR(39)+'				
						AND C.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND C.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND ISNULL(C.ETypeID,'''') IN (SELECT TypeId FROM #GetManETypeId)
						AND ISNULL(Bil.KTypeId,'''') IN (SELECT TypeId FROM #GetManKTypeId)
						AND (ISNULL(Bil.BTypeId,'''') IN (SELECT TypeId FROM #GetManBTypeId))
						AND C.BillCode LIKE '+CHAR(39)+@BillCode+'%'+CHAR(39)+'
						AND C.IfAudit = '+CHAR(39)+@IfAudit+CHAR(39)+'
						AND Substring(A.AuditingReason,1,1)<>1
			)A
		GROUP BY
				A.BillType,
				A.AuditingType,
				A.AuditingLevel	

		--筛选结果集
		SELECT * FROM #CheckBillInfo
		
		--删除临时表
		DROP TABLE #CheckBillInfo '

--PRINT(@SQL)
EXEC(@SQL)


DROP TABLE #GetManKTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




-----------------------------------------------
--作者：谢吉康
--日期：2003-11-14
--描述：多级审核的查询[具体]
-----------------------------------------------
CREATE                    PROCEDURE Gp_BillAuditingQueryDetail
(
	@OperatorID	varchar(100),
	@StartDate	varchar(20),
	@EndDate	varchar(20),
	@ETypeID	varchar(8000),
	@BillCode	varchar(200),
	@BillType	char(10),
	@Comment	varchar(200),
	@IfAudit	char(10),
	@BTypeID	varchar(8000),
	@KTypeID	varchar(8000),
	@SortField	varchar(50),
	@SortType	varchar(10),
	@STypeId	varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re

-----------------------------------定义查询的SQL字符串
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetManDetailBType(@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetManDetailEType(@OperatorID)

--职员：
CREATE TABLE #GetSelETypeId(TypeId varchar(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeId,3)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
--删除仓库中的对于STypeId
DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

DECLARE	@SQL varchar(8000)
SELECT	@SQL = ''

IF 	@BillType = '' OR @BillType = '-1'
	SELECT @BillType = '%'

--修改人：谢吉康
--日  期：2005-25-17
--描  述：检查调拨当中入库仓库是否有效
DECLARE @MoveInOutKLimit  INT
--SELECT @MoveInOutKLimit=Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit'
EXEC @MoveInOutKLimit = GP_CheckLimit @OperatorId,454

--是否有审核他人草稿的权限
DECLARE @AuditingOtherDraft INT	
EXEC @AuditingOtherDraft = GP_CheckLimit @OperatorID,467
--------------------------------------------------------------权限检查-------------------------------------------------------
BEGIN
-----------------------------------运算开始
	SET  @SQL = '
				SELECT	DISTINCT
						A.BillType,
						A.AuditingType,
						A.AuditingLevel,
						B.BillNumberID,
						B.BillDate,
						B.BillCode,
						C.ETypeId,
						B.IfAudit,
						C.BTypeId
				FROM 	AuditingFlowSet A,
						AuditingBill B,
						BillIndex C,
						AuditingFlowDetail D,
						#GetManSTypeId S,
						#GetManDTypeId MD
				WHERE 	A.AuditingID = B.AuditingID
						AND B.BillNumberID = C.BillNumberID
						AND A.AuditingID = D.AuditingID
						AND C.STypeId = S.TypeId
						AND C.DTypeId = MD.TypeId
						AND A.IfUse = 1
						AND C.RedWord = 0
						AND C.Draft = 1
						AND C.IfYearBill = 0
						AND B.BillIndexType = 2
						AND SUBSTRING(A.AuditingReason,1,1)<>1'
				IF @AuditingOtherDraft = 1
					SET @SQL = @SQL + ' AND C.Checke = '+char(39)+@OperatorID+char(39)

				SET @SQL = @SQL + ' 
						AND A.BillType LIKE '+char(39)+RTRIM(@BillType)+char(39)+'
						AND B.BillDate >='+char(39)+@StartDate+char(39)+'
						AND B.BillDate <='+char(39)+@EndDate+char(39)+'
						AND B.BillCode LIKE '+char(39)+'%'+@BillCode+'%'+char(39)+'
						AND B.IfAudit = '+char(39)+RTRIM(@IfAudit)+char(39)+'
						AND B.ETypeID IN (SELECT * FROM #GetSelETypeId)
						AND ISNULL(B.ETypeID,'''') IN (SELECT * FROM #GetManETypeId)
						AND (
								(
									(ISNULL(C.BTypeID,'''') IN (SELECT * FROM #GetManBTypeId)) AND C.BillType IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''148'',''149'',''150'',''151'',''160'',''161'',''165'',''166'',''167'',''168'',''169'',''170'',''171'',''172'',''178'',''183'',''186'')
								)
								OR
								(
									C.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''148'',''149'',''150'',''151'',''160'',''161'',''165'',''166'',''167'',''168'',''169'',''170'',''171'',''172'',''178'',''183'',''186'')
								)
							)
						AND (
								(
									(
										( ISNULL(C.KTypeID,'''') IN (SELECT * FROM #GetManKTypeId) OR ISNULL(C.KTypeID2,'''') IN (SELECT * FROM #GetManKTypeId)) AND C.BillType IN (''16'',''160'',''161'',''173'',''174'',''175'') 
									) 
									OR 
									(
										C.BillType IN (''305'',''11'',''45'',''34'',''6'',''9'',''14'',''139'',''126'',''140'',''142'',''144'',''146'',''165'',''167'',''168'',''169'',''170'',''178'',''183'') AND ISNULL(C.KTypeID,'''') IN (SELECT * FROM #GetManKTypeId)
									)'
				--特殊处理成本调价单
				IF EXISTS(SELECT TOP 1 * FROM LoginUser WHERE ETypeId = @OperatorID AND MangerKTypeId = '00000')  
					SET @SQL = @SQL + 'OR
										(
											C.BillType IN (''57'') AND 1=1
										)'
				ELSE
					SET @SQL = @SQL + 'OR
										(
											C.BillType IN (''57'') AND ISNULL(C.KTypeID,'''') IN (SELECT TypeId FROM #GetManKTypeId)
										)'
				SET @SQL = @SQL + '	OR 
									( '

						IF @MoveInOutKLimit = 0
							SET @SQL = @SQL + '	C.BillType IN (''17'',''21'') AND (ISNULL(C.KTypeId,'''') IN (SELECT * FROM #GetManKTypeId) AND ISNULL(C.KTypeId2,'''') IN (SELECT * FROM #GetManKTypeId)) '
						ELSE
							SET @SQL = @SQL + '	C.BillType IN (''17'',''21'') AND (ISNULL(C.KTypeId,'''') IN (SELECT * FROM #GetManKTypeId) OR ISNULL(C.KTypeId2,'''') IN (SELECT * FROM #GetManKTypeId)) '
						
						SET @SQL = @SQL + '
									)
									OR
									('

						SET @SQL = @SQL +'  ((C.KTypeId IN (SELECT * FROM #GetManKTypeId) OR C.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND C.BillType IN (166,172))'
						SET @SQL = @SQL +'  OR ((C.KTypeId IN (SELECT * FROM #GetManKTypeId) AND C.KTypeId2='''') AND C.BillType IN (166,172))'
						SET @SQL = @SQL +'  OR ((C.KTypeId='''' AND C.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND C.BillType IN (166,172))'
						SET @SQL = @SQL +'  OR ((C.KTypeId='''' AND C.KTypeId2='''') AND C.BillType IN (166,172))'

				SET @SQL = @SQL + ' )
									OR
									(
										ISNULL(C.KTypeId,'''') LIKE ''%'' AND C.BillType NOT IN (''16'',''155'',''157'',''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''17'',''21'',''160'',''161'',''165'',''166'',''167'',''168'',''169'',''170'',''172'',''173'',''174'',''175'',''178'',''183'')
									)
								) 
							)'
				
				SET @SQL = @SQL + '
							AND ISNULL(D.ETypeID,'''') LIKE '+char(39)+@OperatorID+'%'+char(39)+'
							AND C.Comment LIKE '+char(39)+'%'+@Comment+'%'+char(39)+'
				UNION ALL
					SELECT	DISTINCT
							A.BillType,
							A.AuditingType,
							A.AuditingLevel,
							B.BillNumberID,
							B.BillDate,
							B.BillCode,
							C.ETypeID,
							B.IfAudit,
							C.BTypeID
					FROM 	AuditingFlowSet A,
							AuditingBill B,
							LendIndex C,
							AuditingFlowDetail D,
							#GetManDTypeId MD
					WHERE 	A.AuditingID = B.AuditingID
							AND B.BillNumberID = C.BillNumberID
							AND A.AuditingID = D.AuditingID
							AND C.DTypeId = MD.TypeId
							AND A.IfUse = 1
							AND C.RedWord = 0
							AND B.BillIndexType = 1
							AND SUBSTRING(A.AuditingReason,1,1)<>1'
					IF @AuditingOtherDraft = 1
						SELECT @SQL = @SQL + ' AND C.Checke = '+char(39)+@OperatorID+char(39)
	
					SELECT @SQL = @SQL + ' 
							AND A.BillType LIKE '+char(39)+RTRIM(@BillType)+char(39)+'
							AND B.BillDate >='+char(39)+@StartDate+char(39)+'
							AND B.BillDate <='+char(39)+@EndDate+char(39)+'
							AND B.BillCode LIKE '+char(39)+'%'+@BillCode+'%'+char(39)+'
							AND B.IfAudit = '+char(39)+RTRIM(@IfAudit)+char(39)+'
							AND B.ETypeID IN (SELECT * FROM #GetSelETypeId)
							AND C.ETypeId IN (SELECT * FROM #GetManETypeId)
							AND C.BTypeId IN (SELECT * FROM #GetManBTypeId)
							AND C.KTypeId IN (SELECT * FROM #GetManKTypeId)
							AND ISNULL(D.ETypeID,'''') LIKE '+char(39)+@OperatorID+'%'+char(39)+'
							AND C.Comment LIKE '+char(39)+'%'+@Comment+'%'+char(39)+'
				UNION ALL
					SELECT	DISTINCT
							A.BillType,
							A.AuditingType,
							A.AuditingLevel,
							B.BillNumberID,
							B.BillDate,
							B.BillCode,
							C.ETypeID,
							B.IfAudit,
							C.BTypeID
					FROM 	AuditingFlowSet A,
							AuditingBill B,
							OrderIndex C,
							AuditingFlowDetail D,
							#GetManSTypeId S,
							#GetManDTypeId MD
					WHERE 	A.AuditingID = B.AuditingID
							AND B.BillNumberID = C.BillNumberID
							AND A.AuditingID = D.AuditingID
							AND C.STypeId =S.TypeId
							AND C.DTypeId = MD.TypeId
							AND A.IfUse = 1
							AND C.RedWord = 0
							AND B.BillIndexType = 0
							AND SUBSTRING(A.AuditingReason,1,1)<>1'
					IF @AuditingOtherDraft = 1
						SELECT @SQL = @SQL + ' AND C.Checke = '+char(39)+@OperatorID+char(39)
	
					SELECT @SQL = @SQL + ' 
							AND A.BillType LIKE '+char(39)+RTRIM(@BillType)+char(39)+'
							AND B.BillDate >='+char(39)+@StartDate+char(39)+'
							AND B.BillDate <='+char(39)+@EndDate+char(39)+'
							AND B.BillCode LIKE '+char(39)+'%'+@BillCode+'%'+char(39)+'
							AND B.IfAudit = '+char(39)+RTRIM(@IfAudit)+char(39)+'
							AND B.ETypeID IN (SELECT * FROM #GetSelETypeId)
							AND C.ETypeId IN (SELECT * FROM #GetManETypeId)
							AND C.BTypeId IN (SELECT * FROM #GetManBTypeId)
							AND C.KTypeId IN (SELECT * FROM #GetManKTypeId)
							AND ISNULL(D.ETypeID,'''') LIKE '+char(39)+@OperatorID+'%'+char(39)+'
							AND C.Comment LIKE '+char(39)+'%'+@Comment+'%'+char(39)


----------------------------------构造排序字段	
	IF @SortField = 'BillDate'
		SELECT @SQL = @SQL + 'ORDER BY B.BillDate '
	IF @SortField = 'BillCode'
		SELECT @SQL = @SQL + 'ORDER BY B.BillCode '
	IF @SortField = 'BillType'
		SELECT @SQL = @SQL + 'ORDER BY A.BillType '
	IF @SortField = 'ETypeID'
		SELECT @SQL = @SQL + 'ORDER BY B.ETypeID '
	IF @SortField = 'BTypeID'
		SELECT @SQL = @SQL + 'ORDER BY C.BTypeID '
	IF @SortField = ''
		SELECT @SQL = @SQL + 'ORDER BY B.BillDate,B.BillCode'		

----------------------------------构造排序方式
	IF @SortType = '1'
		SELECT @SQL = @SQL + ' ASC'
	ELSE
		SELECT @SQL = @SQL +' DESC'

	--PRINT(@SQL)
	EXEC(@SQL)

END


DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetSelETypeId,#GetManSTypeId,#GetManDTypeId















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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





CREATE          PROCEDURE GP_BillAuditingReadDetaiSet 
(
	@nAuditingID int,
	@IfOut varchar(10)='o'
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

Declare @CurStep Int
Declare @AuditingID int
Declare @BillType int
Declare @AudDesc varchar(255)
Declare @AuditingStep int
Declare @ETypeID varchar(1000)
Declare @EName varchar (8000)
Declare @AuditingAlerm char (10)


CREATE TABLE #AudDetail (
	[AudID] [int] ,
	[BillType] [int] ,
	[Desc] [varchar] (255),
	[Step] [int],
	[ETypeID] [varchar] (2000),
	[Name] varchar (5700),
	[AuditingAlerm] [char] (10)
) ON [PRIMARY]

CREATE TABLE #AudETypeId
(
	ETypeId		varchar(6000),
	Step		int
)

CREATE TABLE #AudEName
(
	EName		varchar(7500),
	Step		int
)

-- 顺序审核，并且最小级数大于1时（由于吉康改变了审核级数）
DECLARE @OutLever int
SET @OutLever =1
IF @IfOut='i'
BEGIN
	IF EXISTS ( SELECT AuditingID FROM AuditingFlowDetail where AuditingID=@nAuditingID AND OutKty='i')
		SELECT @OutLever=min(AuditingStep) FROM AuditingFlowDetail where AuditingID=@nAuditingID AND OutKty='i'
END

Declare Step_Cursor Cursor For

select distinct auditingstep from auditingflowdetail Where AuditingID = @nAuditingID AND outKty=@IfOut Order by AuditingStep

SET NOCOUNT ON	-- 返回结果不受影响
Open Step_Cursor
Fetch Next From Step_Cursor Into  @CurStep
While @@Fetch_status = 0
Begin
	Declare Write_Cursor Cursor For

	Select a.AuditingID, a.BillType, a.AuditingDescription, a.AuditingStep, a.EtypeID, b.FullName, a.AuditingAlerm
	From AuditingFlowDetail a,Employee b
	Where	 a.AuditingID = @nAuditingID
		 And a.AuditingStep = @CurStep
		 And a.EtypeID = b.TypeID
		 AND outKty=@IfOut
	
	Open Write_Cursor
	
	Fetch Next From Write_Cursor Into @AuditingID, @BillType, @AudDesc, @AuditingStep, @ETypeID, @EName, @AuditingAlerm

	-- 顺序审核，并且最小级数大于1时（由于吉康改变了审核级数）
	IF @IfOut='i' AND @OutLever<>1
		BEGIN
			Insert #AudDetail	 ([AudID],[BillType],[Desc],[Step],[EtypeID],[Name],[AuditingAlerm])
						 Values (@AuditingID, @BillType, @AudDesc, @AuditingStep-@OutLever+1,',',',', @AuditingAlerm)


			INSERT #AudETypeId(ETypeID,Step)VALUES(',',@AuditingStep-@OutLever+1)
			INSERT #AudEName(EName,Step)VALUES(',',@AuditingStep-@OutLever+1)

			While @@Fetch_status = 0		
			Begin
				UPDATE #AudETypeId SET ETypeId = ETypeId + @ETypeId + ',' WHERE Step = @CurStep-@OutLever+1
				UPDATE #AudEName SET EName = EName + @EName + ',' WHERE Step = @CurStep-@OutLever+1
		
				Fetch Next From Write_Cursor Into @AuditingID, @BillType, @AudDesc, @AuditingStep, @ETypeID,  @EName, @AuditingAlerm
			END
		END
	ELSE
		BEGIN
			Insert #AudDetail	 ([AudID],[BillType],[Desc],[Step],[EtypeID],[Name],[AuditingAlerm])
						 Values (@AuditingID, @BillType, @AudDesc, @AuditingStep,',',',', @AuditingAlerm)

			INSERT #AudETypeId(ETypeId,Step)VALUES(',',@AuditingStep)
			INSERT #AudEName(EName,Step)VALUES(',',@AuditingStep)

			While @@Fetch_status = 0		
			Begin
				UPDATE #AudETypeId SET ETypeId = ETypeId + @ETypeId + ',' WHERE Step = @CurStep
				UPDATE #AudEName SET EName = EName + @EName + ',' WHERE Step = @CurStep
		
				Fetch Next From Write_Cursor Into @AuditingID, @BillType, @AudDesc, @AuditingStep, @ETypeID,  @EName, @AuditingAlerm
			END
		END

	Close Write_Cursor
	Deallocate Write_Cursor

	Fetch Next From Step_Cursor Into  @CurStep
End

Close Step_Cursor
Deallocate Step_Cursor

Select  A.AudId,
		A.BillType,
		A.[Desc],
		A.Step,
		B.ETypeId,
		C.EName AS [Name],
		A.AuditingAlerm
From 	#AudDetail A,
		#AudETypeId B,
		#AudEName C
WHERE	A.Step = B.Step
		AND A.Step = C.Step

Drop Table #AudDetail,#AudETypeId,#AudEName














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2003-11-25
	描述：查询特定单据的审核历史
*/
CREATE Procedure Gp_BillAuditingViewHistory
(
	@BillNumberID	VARCHAR(50),
	@BillType		VARCHAR(10)	
)
--@encode$--
AS
BEGIN
	IF @BillType IN (71,72,87,88)
		BEGIN
			SELECT 	A.BillDate, 
					A.BillCode, 
					B.BillType, 
					B.AuditingType, 
					E.FullName 
			FROM 	AuditingBill A, 
					AuditingFlowSet B, 
					Employee E 
			WHERE 	A.AuditingID = B.AuditingID 
					AND B.ETypeID = E.TypeID 
					AND B.IfUse = 1 
					AND A.BillNumberID = @BillNumberID
					AND B.BillType = @BillType 
		END
	ELSE
		BEGIN
			IF @BillType IN (300,301)
				SELECT TOP 1 * FROM OrderIndex
			ELSE
				SELECT TOP 1 * FROM BillIndex
		END



END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


CREATE   PROCEDURE [GP_BillAudtingCheck] 
(
	@BillNumberID		INT,					--单据编号	
	@OperatorID 		VARCHAR(100),			--操作员ID号
	@IfRequestCheck		INT	OUTPUT				--查询结果，为0表示不需要审核，为1表示需要审核
)
--@encode$--
AS

SET NOCOUNT ON

--查询描述单据审核原因的字符串
declare @AuditingReason varchar(100)--审核原因编码（位移编码）
select @AuditingReason=AuditingReason
from AuditingFlowSet a
inner join(
	select BillType from billindex where BillNumberID=@BillNumberID
) b
on a.BillType=b.BillType
where IfUse=1

--print '@AuditingReason=' + @AuditingReason

--如果审核原因为空或为不需要审核，那么返回不需要审核，否则返回需要审核
if isnull(@AuditingReason,'')='' or @AuditingReason='10000000000000000000000000000000000000000000000000'
	set @IfRequestCheck=0
else
	set @IfRequestCheck=1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_BillAudtingCheckReason]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_BillAudtingCheckReason]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2004-11-01
	描述：单据的多级审核
		  PassFlag=0 择需要审核

    新Carpa平台后重新调整  卢春 2009-06
    --20131126 周华 添加 询价单，请购单审核
    --20140122 周华 添加 预设价格名称对应
   
  2016-11-29	梁晰		 超期收款查询条件  
  2017-2-8		冯波		 组合品销售退货单收付款金额审核
  EXEC GP_BillAudtingCheckReason 26,'00001',2,'0',0,0,0
*/
CREATE       PROCEDURE [dbo].[GP_BillAudtingCheckReason]
    (
      @BillNumberID INT ,					--单据编号	
      @OperatorID VARCHAR(100) , 			--操作员ID号
      @BillIndexType INT = 2 ,					--单据类型   0.订单  1.借欠单据  2.一般物流单据 7实物库存 9门店类单据
      @showReasonMx VARCHAR(10) = '' ,			--显示审核提示明细
	--@CheckAllStepReason	int=0,					-- 是否检查所有步骤原因 (针对顺序审核)
      @AppointStep INT = -1 ,					-- 检查指定步骤原因，0：查全部  -1：查全部，但聚合审核原因(适用于提交审核时，显示原因)
      @ifCostLimit INT = 1,					-- 1：要限制操作员成本查看权限  0：不限制
													-- 针对写入auditingbill中的stepreasons，查看审核历史的每级原因，有些原因是与成本相关联的，
													-- 针对不同的人来看，成本数据与成本查看权限相关
	  @IsPlateAlready INT = 0				--因为新增了“我的已审核列表”，现在已审核的单据一样需要查看到 审核原因,所以增加参数，是否为已审核列表查询
    )
--@encode$--
AS 
    SET NOCOUNT ON

    CREATE TABLE #Reason
        (
          BillNumberID INT ,
          BillType NUMERIC(4, 0) ,
          PassFlag BIT ,
          Reason VARCHAR(MAX) ,
          value VARCHAR(MAX) ,
          AuditingStep INT
        )

    CREATE TABLE #ReasonMx
        (
          BillNumberID INT ,
          BillType NUMERIC(4, 0) ,
          PassFlag BIT ,
          Reason VARCHAR(MAX) ,
          value VARCHAR(MAX) ,
          AuditingStep INT
        )

--首先判断该单据是否已经审核通过
    DECLARE @IfAudit VARCHAR(2)
    SELECT  @IfAudit = IfAudit
    FROM    auditingbill
    WHERE   BillNumberID = @BillNumberID
            AND BillIndexType = @BillIndexType
            
	IF(@IsPlateAlready = 0)
		IF ISNULL(@IfAudit, '') = '1' 
			GOTO BillPass --表示单据已经通过审核

--查询描述单据审核原因的字符串
    DECLARE @AuditingReason VARCHAR(MAX)--审核原因编码（位移编码）
    DECLARE @AuditingID INT 
    DECLARE @BillType NUMERIC(4, 0)
    DECLARE @TotalMoney VARCHAR(100)
    DECLARE @TotalInMoney VARCHAR(100)
    DECLARE @preferencemoney VARCHAR(100)
    DECLARE @BTypeID VARCHAR(100) ,
        @intCount INT ,
        @STypeid VARCHAR(100)

	DECLARE @IsService INT 
	DECLARE @xsbilltypes VARCHAR(200)=',184,305,300,313,11,12,140,141,'
-- lc 2009.06
    DECLARE @AuditingType INT

    DECLARE @intCostSale INT
	
DECLARE	@RowIndex			INT=1,
		@RowCount			INT,
		@StockQty			 NUMERIC(24, 10) ,     --仓库商品数量
		@UpLimitQty		NUMERIC(24, 10) ,	  --仓库上限数量
		@PTypeId VARCHAR(50),		  --商品ID
		@Qty  NUMERIC(24, 10) ,	      --表体商品数量
		@UserCode VARCHAR(500),		  
		@FullName VARCHAR(500),
		@IfMulStock  BIT,			  --是否多仓库
		@TmpKTypeID VARCHAR(50);      --表体仓库ID
	
    SELECT  @intCostSale = CostSale
    FROM    BillIndex
    WHERE   BillNumberId = @BillNumberID

    SET @intCount = 0

-- ================================================= add by 陈启华 2004-6-25  #01 销售出库审核提示出了成本单价（而用户没有成本看权限）
    DECLARE @LIMIT_CHECKCOSTPRICE CHAR(1)
    SET @LIMIT_CHECKCOSTPRICE = '1'
    IF @OperatorID = ''
        OR @OperatorID = '00001'
        OR @ifCostLimit = 0 
        SET @LIMIT_CHECKCOSTPRICE = '1'
    ELSE 
        SELECT  @LIMIT_CHECKCOSTPRICE = SUBSTRING(LTRIM(lim), 166, 1)
        FROM    LOGINUSER
        WHERE   EtypeID = @OperatorID

    DECLARE @PriceTemp  NUMERIC(24, 10)  ,
        @TempValue INT
-- =============== end ============================================================================================================

---------------------------------最低售价权限---------------------------------------
    DECLARE @LIMIT_DEFAULT_LOWSALEPRICE CHAR(1)
    SET @LIMIT_DEFAULT_LOWSALEPRICE = '1'
    IF @OperatorID = ''
        OR @OperatorID = '00001' OR @ifCostLimit = 0
        SET @LIMIT_DEFAULT_LOWSALEPRICE = '1'
    ELSE 
        SELECT  @LIMIT_DEFAULT_LOWSALEPRICE = SUBSTRING(LTRIM(lim), 710, 1)
        FROM    LOGINUSER
        WHERE   EtypeID = @OperatorID
------------------------------------------------------------------------------------


    DECLARE @strSTypeID VARCHAR(50) ,
        @intPrcieType INT
	
    DECLARE @btypeall INT
    EXEC GP_GetSubValue 'btypeall', '', @btypeall OUTPUT	

    IF @BillIndexType = 0	-- 订单
        SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @TotalMoney = CONVERT(VARCHAR(100), ISNULL(b.TotalMoney, 0)) ,
                @BTypeID = b.BTypeID ,
                @STypeid = b.Stypeid
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT BillType ,
                                    TotalMoney ,
                                    BTypeID ,
                                    Stypeid
                             FROM   orderindex
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.STypeID
        WHERE   IfUse = 1
	
    IF @BillIndexType = 2	-- 物流单据
        SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingType = a.AuditingType ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @TotalMoney = CONVERT(VARCHAR(100), ISNULL(b.TotalMoney, 0)) ,
                @TotalInMoney = CONVERT(VARCHAR(100), ISNULL(b.TotalInMoney, 0)) ,
                @preferencemoney = CONVERT(VARCHAR(100), ISNULL(b.preferencemoney, 0)) ,
                @BTypeID = b.BTypeID ,
                @STypeid = b.Stypeid
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT BillType ,
                                    TotalMoney ,
                                    case 
										when BillType=305 then packway
										else TotalInMoney end as TotalInMoney,
                                    preferencemoney ,
                                    BTypeID ,
                                    Stypeid 
                             FROM   billindex
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.Stypeid
        WHERE   IfUse = 1	

	IF @billIndexType=3 --请购单
	BEGIN
		SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @TotalMoney = CONVERT(VARCHAR(100), ISNULL(b.TotalMoney, 0)) ,
                --@BTypeID = b.BTypeID ,
                @STypeid = b.Stypeid,
                @BillType=204
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT BillType ,
                                    TotalMoney ,
                                    --BTypeID ,
                                    Stypeid
                             FROM   dbo.RequestIndex
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.STypeID
        WHERE   IfUse = 1
	END
		
	IF @billIndexType=4 --提成单
	BEGIN
		SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @STypeid = b.Stypeid,
                @BillType=311
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT 311 as billtype ,
                                    Stypeid
                             FROM   dbo.CommissionBillNew
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.STypeID
        WHERE   IfUse = 1
	END
	
	IF @billIndexType=1 --借欠单据
	BEGIN
		SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @STypeid = b.Stypeid
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT BillType ,
                                    Stypeid
                             FROM   dbo.LendIndex
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.STypeID
        WHERE   IfUse = 1
	END
	
	IF @BillIndexType=5
	BEGIN
		SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @STypeid = b.Stypeid
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT BillType ,
                                    Stypeid
                             FROM   dbo.ReceiptBillIndex
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.STypeID
        WHERE   IfUse = 1
	END
	
	IF @BillIndexType=7
	BEGIN
		SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @STypeid = b.Stypeid
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT BillType ,
                                    Stypeid
                             FROM   dbo.FactIndex
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.STypeID
        WHERE   IfUse = 1
	END
	
	--优惠券类型的单据
	IF @BillIndexType=8
	BEGIN
		SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @STypeid = b.Stypeid
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT BillType ,
                                    Stypeid
                             FROM   dbo.Coupon_BillIndex
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.STypeID
        WHERE   IfUse = 1	
	END
	--门店类类型的单据
	IF @BillIndexType=9
	BEGIN
		SELECT  @strSTypeID = b.STypeID ,
                @AuditingID = a.AuditingID ,
                @AuditingReason = a.AuditingReason ,
                @BillType = a.BillType ,
                @STypeid = b.Stypeid
        FROM    AuditingFlowSet a
                INNER JOIN ( SELECT BillType ,
                                    Stypeid
                             FROM   dbo.PosAllotApplyBillIndex
                             WHERE  BillNumberID = @BillNumberID
                           ) b ON a.BillType = b.BillType
                                  AND a.STypeID = b.STypeID
        WHERE   IfUse = 1	
	END
    IF ISNULL(@AuditingReason, '') = '' 
        GOTO BillPass --表示单据不需要审核

    SELECT  @intPrcieType = ISNULL(PriceType, 0)	--0表示商品物价信息，1表示分支机构价格体系
    FROM    SType
    WHERE   TypeId = @strSTypeID

    DECLARE @strPriceName VARCHAR(500)

    DECLARE @i INT
    DECLARE @Length INT
    DECLARE @SQL NVARCHAR(4000)
    DECLARE @vResult BIT

    DECLARE @KeyName VARCHAR(500)
    DECLARE @Relation VARCHAR(500)
    DECLARE @Description VARCHAR(MAX)
    DECLARE @ReasonValue VARCHAR(MAX)

    DECLARE @TypeName VARCHAR(1000)
    DECLARE @KTypeID VARCHAR(100)
    DECLARE @ComputValue VARCHAR(1000)
    DECLARE @GoodsCostPrice  NUMERIC(24, 10) 
	DECLARE @SalePriceContainTax  INT,   --销售预设价格是否含税
			@BuyPriceContainTax   INT;	 --采购预设价格是否含税
	DECLARE @MUnitID  INT;   --当前商品单位
	SELECT @SalePriceContainTax=Value FROM Userconfig WHERE ConfigName='ptypetaxpresaleprice';
	SELECT @BuyPriceContainTax=Value FROM Userconfig WHERE ConfigName='ptypetaxprebuyprice';
	
-- lc 2009.06
    DECLARE @AuditingStep INT ,
        @outkty VARCHAR(1)
    IF @AppointStep IN ( 0, -1 )	-- 查全部
        DECLARE CURSOR_AuditingReason CURSOR
        FOR
            SELECT  AuditingReason ,
                    AuditingStep ,
                    outkty
            FROM    AuditingStepReason
            WHERE   AuditingID = @AuditingID
            ORDER BY AuditingStep
    ELSE 
        DECLARE CURSOR_AuditingReason CURSOR
        FOR
            SELECT  AuditingReason ,
                    AuditingStep ,
                    outkty
            FROM    AuditingStepReason
            WHERE   AuditingID = @AuditingID
                    AND AuditingStep = @AppointStep
            ORDER BY AuditingStep

    OPEN CURSOR_AuditingReason
    FETCH NEXT FROM CURSOR_AuditingReason INTO @AuditingReason, @AuditingStep,
        @outkty
    WHILE @@FETCH_STATUS = 0 
        BEGIN
			-- 游标循环 - Start 
            SET @i = 1
            SET @Length = LEN(@AuditingReason)
            WHILE @i <= @Length 
                BEGIN
                    IF SUBSTRING(@AuditingReason, @i, 1) = '1' 
                        BEGIN
                            SELECT  @KeyName = r.KeyName ,
                                    @Relation = r.relation ,
                                    @Description = r.[Description] ,
                                    @ReasonValue = ISNULL(v.ReasonValue, '')
                            FROM    AuditingRelation r
                                    LEFT JOIN ( SELECT  *
                                                FROM    AuditingReason
                                                WHERE   AuditingID = @AuditingID
                                                        AND AuditingStep = @AuditingStep
                                              ) v ON r.OffSet = v.ReasonNo
                            WHERE   OffSet = @i
                            
                            --审核流程终止/暂停
							IF EXISTS(SELECT 1 FROM dbo.AuditingFlowSet WHERE BillType=@BillType AND Stypeid=@STypeid AND Stoped=1)
							BEGIN
								BREAK;
							END
							
                            IF @i = 1 
                                BEGIN 
									-- 位移=1，表示 不需要审核
                                    INSERT  INTO #Reason
                                    VALUES  ( @BillNumberID, @BillType, 1,
                                              '无需审核', '', @AuditingStep )						
                                END 
                                
                            IF @i = 2 
                                BEGIN 
									--位移=2，表示 必须全部审核
                                    DECLARE @intInOutAuditing INT ,
                                        @strKInFullName VARCHAR(MAX) ,
                                        @strKOutFullName VARCHAR(MAX)
								
                                    SELECT  @intInOutAuditing = 0
						
                                    IF @BillType IN (17,21,310) 
                                        BEGIN
                                            IF EXISTS ( SELECT
                                                              AuditingID
                                                        FROM  AuditingFlowDetail
                                                        WHERE AuditingID = @AuditingID
                                                        GROUP BY AuditingID
                                                        HAVING
                                                              COUNT(*) > 1 ) 
                                                BEGIN
                                                    SELECT  @intInOutAuditing = 1
								
                                                    SELECT  @strKOutFullName = b.FullName ,
                                                            @strKInFullName = c.FullName
                                                    FROM    BillIndex a
                                                            INNER JOIN Stock b ON a.KTypeID = b.typeId
                                                            INNER JOIN Stock c ON a.ktypeid2 = c.typeId
                                                    WHERE   a.BillNumberId = @BillNumberID
                                                END
                                        END
                                         IF @BillType IN (327,328) 
                                        BEGIN
                                            IF EXISTS ( SELECT
                                                              AuditingID
                                                        FROM  AuditingFlowDetail
                                                        WHERE AuditingID = @AuditingID
                                                        GROUP BY AuditingID
                                                        HAVING
                                                              COUNT(*) > 1 ) 
                                                BEGIN
                                                    SELECT  @intInOutAuditing = 1
								
                                                    SELECT  @strKOutFullName = b.FullName ,
                                                            @strKInFullName = c.FullName
                                                    FROM    PosAllotApplyBillIndex a
                                                            INNER JOIN Stock b ON a.KTypeID = b.typeId
                                                            INNER JOIN Stock c ON a.InKtypeId = c.typeId
                                                    WHERE   a.BillNumberId = @BillNumberID
                                                END
                                        END
                                        
						
                                    IF @intInOutAuditing = 0 
                                        BEGIN
                                            INSERT  INTO #Reason
                                            VALUES  ( @BillNumberID, @BillType,
                                                      0, '必须全部审核', '',
                                                      @AuditingStep )
                                        END
                                    ELSE 
                                        BEGIN
											IF @BillType = 310
											BEGIN
											    IF @outkty = 'o' 
                                                BEGIN
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              '调出,必须全部审核', '',
                                                              @AuditingStep )
                                                END
												ELSE 
                                                BEGIN
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              '调入,必须全部审核', '',
                                                              @AuditingStep )
                                                END
											END
											ELSE
											BEGIN
											    IF @outkty = 'o' 
                                                BEGIN
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              '出库,必须全部审核', '',
                                                              @AuditingStep )
                                                END
												ELSE 
                                                BEGIN
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              '入库,必须全部审核', '',
                                                              @AuditingStep )
                                                END
											END
                                       
                                        END
						--IF @AuditingType = 1 AND @CheckAllStepReason = 0 GOTO BillPass
                                END
							--2015-07-30 司华山 增加发出商品、暂估影响应收应付 注意 @TotalMoney @TotalInMoney等被定义为了VARCHAR
							
							-- 位移=3，表示 超过信用额度审核
                            IF @i = 3
                                AND @BTypeID <> '' 
                                BEGIN 
									DECLARE @IncludeFc INT,
											@IncludeApprsl INT,
											@FcTotal  NUMERIC(24, 10) =0;
									--启用暂估、发出配置		
									SELECT @IncludeApprsl=Value FROM dbo.Userconfig WHERE ConfigName='araptotalstatisticyfzg';
									SELECT @IncludeFc=Value FROM dbo.Userconfig WHERE ConfigName='araptotalstatisticfcspth';
									
									IF @IncludeFc=1
									BEGIN
									--计算发出商品Total
										SELECT @FcTotal=SUM(B.FCTotal)  FROM BillIndex A INNER JOIN 
										(   
											SELECT -(Qty-InvoiceQty)*TaxPrice AS FCTotal,BillNumberId FROM SendBackBill 
											UNION ALL
											SELECT (Qty-InvoiceQty)*TaxPrice AS FCTotal,BillNumberId FROM SendBill
										) B ON A.btypeid=@BTypeID AND A.Stypeid=@STypeID AND A.BillNumberId=B.BillNumberId 
										    AND A.ifcheck='t' AND  A.isini=0 AND A.draft=0 AND A.RedWord=0
										GROUP BY STypeID,BTypeID
									END
														
                                    SELECT  @ReasonValue = btype_credit.Credit
                                    FROM    BType
                                            LEFT JOIN btype_credit ON BType.typeId = btype_credit.BtypeId
                                    WHERE   TypeID = @BTypeID
                                            AND btype_credit.StypeId = @STypeid
									
                                    SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) , ( ISNULL(CONVERT( NUMERIC(24, 10) , @TotalMoney),
                                                              0)
                                                              - ISNULL(CONVERT( NUMERIC(24, 10) , @TotalInMoney),
                                                              0)
                                                              - ISNULL(CONVERT( NUMERIC(24, 10) , @preferencemoney),
                                                              0) ))  
                                    -- 不知道为什么之前逻辑要排除为零的情况,干掉它
                                    IF  EXISTS ( SELECT BTypeID
                                                     FROM   BType_ARAPTotal
                                                     WHERE  BTypeID = @BTypeID
                                                            AND STypeID = @STypeid ) 
                                        BEGIN
                                            IF @btypeall = 0 
                                                BEGIN
                                                    SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) ,
															ISNULL(b.ARTotal,0)
                                                            -CASE WHEN @IncludeApprsl=1
																  THEN CONVERT( NUMERIC(24, 10) ,ISNULL(b.GRIRTotal,0))
															ELSE 0
															END   
															+ ISNULL(CONVERT( NUMERIC(24, 10) ,@FcTotal),0) 
                                                            - ISNULL(b.YSTotal,0)
                                                            + (ISNULL(CONVERT( NUMERIC(24, 10) , 
																  @TotalMoney),		
                                                              0)
                                                              - ISNULL(CONVERT( NUMERIC(24, 10) ,
																  @TotalInMoney),		
                                                              0)
                                                              - ISNULL(CONVERT( NUMERIC(24, 10) , 
																@preferencemoney),	
                                                              0)
                                                              ))
                                                              
                                                    FROM    BType A
                                                            LEFT JOIN BType_ARAPTotal B ON A.TypeID = B.BtypeId
                                                    WHERE   TypeID = @BTypeID
                                                            AND B.StypeId = @STypeid
                                                END
                                            ELSE 
                                                BEGIN
								--统一
                                                    SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) , 
															ISNULL(b.ARTotal,0)
                                                            -CASE WHEN @IncludeApprsl=1
																  THEN CONVERT( NUMERIC(24, 10) ,ISNULL(b.GRIRTotal,0))
															ELSE 0
															END
															+ISNULL(CONVERT( NUMERIC(24, 10) ,
                                                            @FcTotal)
                                                            ,0)
                                                            - ISNULL(b.YSTotal,0)
                                                            - ISNULL(b.APTotal,0)
                                                            + ISNULL(b.YFTotal,0)
                                                            + (ISNULL(CONVERT( NUMERIC(24, 10) , 
															  @TotalMoney),
                                                              0)
                                                              - ISNULL(CONVERT( NUMERIC(24, 10) ,
															  @TotalInMoney),
                                                              0)
                                                              - ISNULL(CONVERT( NUMERIC(24, 10) , 
															  @preferencemoney ),
                                                              0)
                                                              ))
                                                    FROM    BType A
                                                            LEFT JOIN BType_ARAPTotal B ON A.TypeID = B.BtypeId
                                                    WHERE   TypeID = @BTypeID
                                                            AND B.StypeId = @STypeid
                                                END
                                        END
											
						--信用额度为NULL则视为无限大
                                    IF @ReasonValue IS NOT NULL
                                        AND @ReasonValue <> '' 
                                        BEGIN		
							
								-- 销售订单信用额度单独处理: 9.1新需求 57
                                            IF EXISTS ( SELECT
                                                              1
                                                        FROM  ORDERINDEX
                                                        WHERE billnumberid = @billnumberid
                                                              AND billtype IN (313,300) ) --是销售订单
                                                AND EXISTS ( SELECT
                                                              1
                                                             FROM
                                                              userconfig
                                                             WHERE
                                                              ConfigName = 'SaleOrderArLimit'
                                                              AND VALUE = 1 ) -- 启用的系统配置
                                                BEGIN
                                                
                                                --SELECT @ComputValue;
									-- 计算劣迹未发货订单金额
                                                    DECLARE @UnreachTaxTotal  NUMERIC(24, 10) 
									
									--SELECT @btypeid = btypeid, @stypeid = stypeid FROM billindex WHERE billnumberid = @billnumberid 
									
									
													IF @BillType=300
													BEGIN
														SELECT  @UnreachTaxTotal = ISNULL(SUM(taxtotal),
																  0)
																- ISNULL(SUM(ReachTaxTotal),
																  0)
														FROM    dbo.OrderBill O
																INNER JOIN dbo.OrderIndex BI ON O.billNumberID = Bi.BillNumberId AND BI.BillOver <> 1
														WHERE   BI.BillType = 300
																AND O.BillOver <> 1
																AND bi.billNumberId <>@BillNumberID
																AND bi.btypeid = @btypeid
																AND BI.Stypeid = @stypeid
																AND BI.IfAudit = 1
																AND ( bi.DealBTypeID <> ''
																  OR bi.DealBTypeID <> NULL
																  ) 
																AND o.TaxTotal > o.ReachTaxTotal
													END
													ELSE
													BEGIN
														SELECT  @UnreachTaxTotal = ISNULL(SUM(taxtotal),
                                                              0)
                                                            - ISNULL(SUM(ReachTaxTotal),
                                                              0)
														FROM    dbo.PT_Combin_OrderBillDetail O
																INNER JOIN dbo.OrderIndex BI ON O.billNumberID = Bi.BillNumberId
														WHERE   BI.BillType = 313
																AND bi.billNumberId <>@BillNumberID
																AND bi.btypeid = @btypeid
																AND BI.Stypeid = @stypeid
																AND BI.IfAudit = 1
																AND ( bi.DealBTypeID <> ''
																  OR bi.DealBTypeID <> NULL
																  ) 
																AND o.TaxTotal > o.ReachTaxTotal
													END
									--如果是销售订单, 需要加上累计未发货订单金额,在于信用额度去判断
                                                    SET @ComputValue = @ComputValue
                                                        + @UnreachTaxTotal
                                                     --SELECT @ComputValue;
                                                END
								
                                            SET @SQL = 'IF ' + @ComputValue
                                                + @Relation + @ReasonValue
                                                + ' SET @vResult=0 ELSE SET @vResult=1'						
																
                                            EXECUTE sp_executesql @SQL,
                                                N'@vResult bit OUTPUT',
                                                @vResult OUTPUT
                                            IF @vResult = 0 
                                                BEGIN 
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              @Description
                                                              + '('
                                                              + ISNULL(dbo.F_DecimalDisplay(@ReasonValue,'total'),0)
                                                              + ')',
                                                              '该客户欠款'
                                                              + ISNULL(dbo.F_DecimalDisplay(@ComputValue,'total'),
                                                              0) + '元',
                                                              @AuditingStep )
                                                END 
                                            ELSE 
                                                BEGIN 
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 1,
                                                              @Description
                                                              + '('
                                                              + ISNULL(dbo.F_DecimalDisplay(@ReasonValue,'total'),0)
                                                              + ')',
                                                              '该客户欠款'
                                                              + ISNULL(dbo.F_DecimalDisplay(@ComputValue,'total'),
                                                              0) + '元',
                                                              @AuditingStep )
                                                END 
                                        END
                                END
							/*
							IF @i=4
								BEGIN 
									-- 位移=4，表示 超过信用期审核
									INSERT INTO #Reason VALUES(@BillNumberID,@BillType,0,'超过信用期审核','')
								END

							*/
                            IF ( @i = 5
                                 OR @i = 6
                               ) 
                                BEGIN 
									-- 位移=5，表示 单据金额高于____元审核
									-- 位移=6，表示 单据金额低于____元审核
									--同价调拨单需要从明细中取数据
                                    IF (@BillType IN (17,310,403,401,327,328) --新增发出商品退货单,暂估退货单,门店配送单,门店配送退货单
                                         AND @i = 5
                                       ) 
                                       BEGIN        
											IF(@BillType = 17)    
											BEGIN                         
												SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(SUM(Total),
																	  0))
												FROM    MoveBill
												WHERE   BillNumberId = @BillNumberId
											END
											ELSE IF @BillType=310
											BEGIN
												SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(SUM(NTransferPrice),
																	  0))
												FROM    CapitalTransfer_Bill
												WHERE   BillNumberId = @BillNumberId
											END
											ELSE IF @BillType=403
											BEGIN
												SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(SUM(total),
																	  0))
												FROM    SendBackBill
												WHERE   BillNumberId = @BillNumberId
											END
											ELSE IF @BillType=401
											BEGIN
												SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(SUM(total),
																	  0))
												FROM    AppraisalBackBill
												WHERE   BillNumberId = @BillNumberId	
											END
											ELSE IF @BillType=327
											BEGIN
												SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(SUM(total),
																	  0))
												FROM    DeliveryBill
												WHERE   BillNumberId = @BillNumberId
											END
											ELSE IF @BillType=328
											BEGIN
												SELECT  @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(SUM(total),
																	  0))
												FROM    DeliveryBackBill
												WHERE   BillNumberId = @BillNumberId
											END
                                        END
                                    ELSE 
                                        SET @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(@TotalMoney,
                                                              0))

                                    IF ( @Relation <> ''
                                         AND @ReasonValue <> ''
                                       ) 
                                        BEGIN 
                                        
                                             
                                            DECLARE @resonValue VARCHAR(200) ;
                                           
                                          IF @Billtype = 36
                                          BEGIN
                                             SET @resonValue = '   付款金额';
                                          END  
                                            
                                            SET @SQL = 'IF ' + @ComputValue
                                                + @Relation + @ReasonValue
                                                + ' SET @vResult=0 ELSE SET @vResult=1'
                                            EXECUTE sp_executesql @SQL,
                                                N'@vResult bit OUTPUT',
                                                @vResult OUTPUT

                                            IF @vResult = 0 
                                                BEGIN 
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(@ReasonValue,'total')),
                                                              @resonValue + dbo.F_DecimalDisplay(@ComputValue,'total'),
                                                              @AuditingStep )
                                                END 
                                            ELSE 
                                                BEGIN 
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 1,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(@ReasonValue,'total')),
                                                              @resonValue + dbo.F_DecimalDisplay(@ComputValue,'total'),
                                                              @AuditingStep )
                                                END 
                                        END
                                END				
                            IF @i = 7 
                                BEGIN 
									-- 位移=7，表示 单据单价高于最近售价审核
									--if @BillType =45 此种情况只有销售退货单才用到 chen_qihua #02 零售退货单
									--增加发出商品退货单 @BillType=403
                                  if @BillType =45 
                                    BEGIN
                                        IF EXISTS ( SELECT  1 FROM  PType_STypePrice A INNER JOIN saleBackBill B 
													ON A.PTypeID= B.PtypeId AND A.STypeID=B.Stypeid AND a.UnitID=b.MUnitID AND B.BillNumberId=@BillNumberID AND A.RecSalePrice<=B.MDiscountPrice AND A.RecSalePrice<>0 AND B.MDiscountPrice<>0) 
                                            BEGIN
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              '单据单价大于等于最近售价审核',
                                                              '',
                                                              @AuditingStep )
                                            END
										END
									if @BillType =46 
                                    BEGIN
                                        IF EXISTS ( SELECT  1 FROM  PType_STypePrice A INNER JOIN PT_Combin_SaleBackBillDetail B 
													ON A.PTypeID= B.PtypeId AND A.STypeID=B.Stypeid AND a.UnitID=b.MUnitID AND B.BillNumberId=@BillNumberID AND A.RecSalePrice<=B.MDiscountPrice AND A.RecSalePrice<>0 AND B.MDiscountPrice<>0) 
                                            BEGIN
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              '单据单价大于等于最近售价审核',
                                                              '',
                                                              @AuditingStep )
                                            END
										END
								  if @BillType = 215 
                                    BEGIN
                                        IF EXISTS (SELECT  1 FROM  PType_STypePrice A INNER JOIN RetailBackBill B 
													ON A.PTypeID= B.PtypeId AND A.STypeID=B.Stypeid AND a.UnitID=b.MUnitID AND B.BillNumberId=@BillNumberID AND A.RecSalePrice<=B.MDiscountPrice AND A.RecSalePrice<>0 AND B.MDiscountPrice<>0)
											BEGIN 
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              '单据单价大于等于最近售价审核',
                                                              '',
                                                              @AuditingStep )
                                            END
										END
								  IF @BillType=403
								  	  BEGIN
                                        IF EXISTS (SELECT  1 FROM  PType_STypePrice A INNER JOIN SendBackBill B 
													ON A.PTypeID= B.PtypeId AND A.STypeID=B.Stypeid AND a.UnitID=b.MUnitID AND B.BillNumberId=@BillNumberID AND A.RecSendPrice<=B.MDiscountPrice AND A.RecSalePrice<>0 AND B.MDiscountPrice<>0)
											BEGIN 
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              '单据单价大于等于最近售价审核',
                                                              '',
                                                              @AuditingStep )
                                            END
										END
                                END
				
                            IF @i = 8 
                                BEGIN 
								-- 位移=8，表示 商品售价低于成本价审核

								-- 计算扣率需要查询的明细表如下：
								-- BuyBackBill 
								-- BuyBill 
								-- CommissionBill 委托代销发货单
								-- retailBill 零售单
								-- saleBackBill 
								-- SaleBill 销售订单 销售出库单
								-- QuotePriceBill 报价单
                                    SET @SQL = ''
                                    SET @TypeName = ''
						
								--新增发出商品出库单  @BillType=402 SendBill
								--根据不同的的单据类型查询不同的明细表
						
                                    IF @BillType = 305 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  b.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    RetailBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                        
                                     
                                    IF ( @BillType = 11 )
                                        AND @intCostSale = 0 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    SaleBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END  
                                      IF ( @BillType = 12 )
                                        AND @intCostSale = 0 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    PT_Combin_SaleBillDetail a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END  
                                    IF ( @BillType = 300 )	--销售订单  谢吉康 2004-11-01
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        -99999 AS GoodsCostPrice
                                                FROM    OrderBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              OrderIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END	
                                        IF ( @BillType = 313 )	--组合品销售订单
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        -99999 AS GoodsCostPrice
                                                FROM    PT_Combin_OrderBillDetail a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              OrderIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END	
                                    IF ( @BillType = 184 )	--报价单  廖晨羽 2012-10-04
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  b.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        -99999 AS GoodsCostPrice
                                                FROM    QuotePriceBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              billindex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END	
                                    IF ( @BillType = 140 ) 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    CommissionBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END	
                                    IF ( @BillType = 141 ) 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  b.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        -99999 AS GoodsCostPrice
                                                FROM    CommissionBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END	
                                    IF ( @BillType = 178 ) 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    QP_QuickRepairBill_PType a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END	
                                    IF ( @BillType = 195 ) 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  b.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        CONVERT( NUMERIC(24, 10) , a.CostTotal
                                                        / a.Qty) AS GoodsCostPrice
                                                FROM    Qp_ReceptionBill_FactUsePType a
                                                        LEFT JOIN billindex b ON b.BillNumberID = a.Receptionbillnumberid
                                                WHERE   a.Receptionbillnumberid = @BillNumberID
                                            SET @SQL = 'ok'
                                        END		
                                     IF @BillType=402 AND @intCostSale=0 --发出商品出库单
                                       BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                               SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    dbo.SendBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END		
                                    IF @SQL <> '' 
                                        BEGIN
                                            OPEN DiscountCursor
                                            FETCH NEXT FROM DiscountCursor INTO @KTypeID,
                                                @TypeName, @ComputValue,
                                                @GoodsCostPrice
                                            WHILE @@fetch_status = 0 
                                                BEGIN									
                                                    IF EXISTS ( SELECT TOP 1
                                                              1
                                                              FROM
                                                              Sysdata
                                                              WHERE
                                                              SubName = 'Costing'
                                                              AND SubValue = 3 )
                                                        AND @BillType NOT IN (
                                                        141, 300, 184 )	--手工指定法
                                                        BEGIN
                                                            SET @ReasonValue = CONVERT( NUMERIC(24, 10) , ISNULL(@GoodsCostPrice,
                                                              0))
                                                            SELECT TOP 1
                                                              @TypeName = FullName,
                                                              @IsService = isService 
                                                            FROM
                                                              PType
                                                            WHERE
                                                              TypeId = @TypeName
                                                        END
                                                    ELSE 
                                                        SELECT
                                                              @TypeName = p.FullName ,
                                                              @IsService = p.isService ,
                                                              @ReasonValue = CONVERT( NUMERIC(24, 10) , ISNULL(g.CostPrice,
                                                              0))
                                                        FROM  PType p
                                                              LEFT JOIN ( SELECT
                                                              PTypeID ,
                                                              CostPrice = CONVERT( NUMERIC(24, 10) , ISNULL( SUM(Total),0))
                                                              / CASE
                                                              WHEN SUM(QTY) = 0
                                                              THEN NULL
                                                              ELSE SUM(QTY)
                                                              END 
                                                              FROM
                                                              GoodsStocks
                                                              WHERE
                                                              PTypeId = @TypeName
                                                              AND KtypeId LIKE CASE
                                                              WHEN @BillType IN (
                                                              141, 143, 145,
                                                              147 ) THEN '%'
                                                              ELSE @KTypeID
                                                              + '%'
                                                              END
                                                              GROUP BY PTypeID
                                                              ) g ON g.PTypeID = p.TypeID
                                                        WHERE TypeId = @TypeName
                                                        
													SELECT @ComputValue=dbo.F_RoundPrice(@ComputValue)
													SELECT @ReasonValue=dbo.F_RoundPrice(@ReasonValue)
                                                    
                                                    SET @SQL = 'IF '
                                                        + @ComputValue
                                                        + @Relation
                                                        + @ReasonValue
                                                        + ' SET @vResult=0 ELSE SET @vResult=1'
                                                    EXECUTE sp_executesql @SQL,
                                                        N'@vResult bit OUTPUT',
                                                        @vResult OUTPUT
											
                                                    IF(@IsService = 1 and CHARINDEX(','+ CAST(@BillType AS VARCHAR(4))+',',@xsbilltypes) <> 0)
	                                                BEGIN
														SET @vResult = 1
	                                                END
                                                    IF @vResult = 0 
                                                        BEGIN 
                                                            IF @LIMIT_CHECKCOSTPRICE = '1' 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              @Description
                                                              + '(成本均价'
                                                              + dbo.F_DecimalDisplay(@ReasonValue,'price')
                                                              + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              @Description
                                                              + '(成本均价'
                                                              + '****' + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                        END 
                                                    ELSE 
                                                        BEGIN 
                                                            IF @LIMIT_CHECKCOSTPRICE = '1' 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 1,
                                                              @Description
                                                              + '(成本均价'
                                                              + dbo.F_DecimalDisplay(@ReasonValue,'price')
                                                              + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 1,
                                                              @Description
                                                              + '(成本均价'
                                                              + '****' + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                        END 
                                                    FETCH NEXT FROM
                                                        DiscountCursor INTO @KTypeID,
                                                        @TypeName,
                                                        @ComputValue,
                                                        @GoodsCostPrice
                                                END 
                                            CLOSE DiscountCursor
                                            DEALLOCATE DiscountCursor
                                        END 
                                END

                            IF ( @i = 9
                                 OR @i = 10
                               ) 
                                BEGIN 
								-- 位移=9，表示 单据扣率高于____折审核
								-- 位移=10，表示 单据扣率低于____折审核
								-- 计算扣率需要查询的明细表如下：
								-- BuyBackBill 
								-- BuyBill 采购订单
								-- CommissionBill 委托代销发货单
								-- retailBill 零售单
								-- saleBackBill 
								-- SaleBill 销售出库单
								-- SendBill  发出商品出库单
                                    SET @SQL = ''
                                    SET @TypeName = ''
                                    IF ( @BillType = 140 ) 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  p.FullName ,
                                                        CONVERT( NUMERIC(24, 10) , s.Discount)
                                                FROM    CommissionBill s
                                                        LEFT JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                WHERE   billnumberid = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                    IF @BillType = 305 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  p.FullName ,
                                                        CONVERT( NUMERIC(24, 10) , s.Discount)
                                                FROM    retailBill s
                                                        LEFT JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                WHERE   billnumberid = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                    IF ( @BillType = 11 ) 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  p.FullName ,
                                                        CONVERT( NUMERIC(24, 10) , s.Discount)
                                                FROM    SaleBill s
                                                        LEFT JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                WHERE   billnumberid = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                        
                                    IF ( @BillType = 12 ) 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  p.FullName ,
                                                        CONVERT( NUMERIC(24, 10) , s.Discount)
                                                FROM    dbo.PT_Combin_SaleBillDetail s
                                                        LEFT JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                WHERE   billnumberid = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                    IF @BillType=402
                                       BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  p.FullName ,
                                                        CONVERT( NUMERIC(24, 10) , s.Discount)
                                                FROM    SendBill s
                                                        LEFT JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                WHERE   billnumberid = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                    IF @SQL <> '' 
                                        BEGIN
                                            OPEN DiscountCursor
                                            FETCH NEXT FROM DiscountCursor INTO @TypeName,
                                                @ComputValue
                                            WHILE @@fetch_status = 0 
                                                BEGIN
                                                    SET @SQL = 'IF '
                                                        + @ComputValue
                                                        + @Relation
                                                        + @ReasonValue
                                                        + ' SET @vResult=0 ELSE SET @vResult=1'
                                                    EXECUTE sp_executesql @SQL,
                                                        N'@vResult bit OUTPUT',
                                                        @vResult OUTPUT
	
										--单据在普通格式下如果扣率设置成1则不需要提交审核 2005-9-15 谢吉康
                                                    IF @BillType IN ( 140, 11,12 ) 
                                                        BEGIN
                                                            IF EXISTS ( SELECT TOP 1
                                                              *
                                                              FROM
                                                              UserConfig
                                                              WHERE
                                                              ConfigName = 'Gridtype'
                                                              AND Value = 3 )
                                                              AND @ComputValue = '1.0000' 
                                                              SET @vResult = 1
                                                            ELSE 
                                                              BEGIN
                                                              IF EXISTS ( SELECT TOP 1
                                                              *
                                                              FROM
                                                              UserConfig
                                                              WHERE
                                                              ConfigName = 'Gridtype'
                                                              AND ( Value = 1
                                                              OR Value = 3
                                                              ) ) 
                                                              SET @vResult = 1										
                                                              END
                                                        END

                                                    IF @vResult = 0 
                                                        INSERT
                                                              INTO #Reason
                                                        VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'discount')),
                                                              '商品：'
                                                              + @TypeName
                                                              + ',扣率'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'discount'),
                                                              @AuditingStep )
                                                    ELSE 
                                                        INSERT
                                                              INTO #Reason
                                                        VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 1,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'discount')),
                                                              '商品：'
                                                              + @TypeName
                                                              + ',扣率'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'discount'),
                                                              @AuditingStep )

                                                    FETCH NEXT FROM
                                                        DiscountCursor INTO @TypeName,
                                                        @ComputValue
                                                END 
                                            CLOSE DiscountCursor
                                            DEALLOCATE DiscountCursor
                                        END 
                                END
				
                            IF @i = 11 
                                BEGIN 
									-- 位移=11，表示 单据成本高于____元审核
									-- LoseBill 报损单明细
									-- OverflowBill 报溢单明细
									-- GiveBill 赠送单明细
                                    SET @SQL = ''
                                    SET @TypeName = ''
                                    IF @BillType = 9  -- 报损单
                                        BEGIN
                                            SELECT  @ComputValue = ( p.Price
                                                              * p.Qty )
                                            FROM    ( SELECT  SUM(g.Total)
                                                              / SUM(g.Qty) AS Price ,
                                                              l.Qty
                                                      FROM    GoodsStocks g
                                                              JOIN ( SELECT
                                                              b.KTypeID ,
                                                              l.PTypeID ,
                                                              l.Qty
                                                              FROM
                                                              BillIndex b ,
                                                              LoseBill l
                                                              WHERE
                                                              b.BillNumberID = l.BillNumberID
                                                              AND l.BillNumberID = @BillNumberID
                                                              ) l ON l.PTypeID = g.PTypeID
                                                              AND g.KTypeID = l.KTypeID
                                                      GROUP BY l.Qty
                                                    ) p
                                            SET @SQL = 'ok'
                                        END

                                    IF @BillType = 14  -- 报溢单
                                        BEGIN
                                            SELECT  @ComputValue = ( p.Price
                                                              * p.Qty )
                                            FROM    ( SELECT  SUM(g.Total)
                                                              / SUM(g.Qty) AS Price ,
                                                              l.Qty
                                                      FROM    GoodsStocks g
                                                              JOIN ( SELECT
                                                              b.KTypeID ,
                                                              l.PTypeID ,
                                                              l.Qty
                                                              FROM
                                                              BillIndex b ,
                                                              OverflowBill l
                                                              WHERE
                                                              b.BillNumberID = l.BillNumberID
                                                              AND l.BillNumberID = @BillNumberID
                                                              ) l ON l.PTypeID = g.PTypeID
                                                              AND g.KTypeID = l.KTypeID
                                                      GROUP BY l.Qty
                                                    ) p
                                            SET @SQL = 'ok'
                                        END



                                    IF @BillType = 139  -- 赠送单
                                        BEGIN
                                            SELECT  @ComputValue = ( p.Price
                                                              * p.Qty )
                                            FROM    ( SELECT  SUM(g.Total)
                                                              / SUM(g.Qty) AS Price ,
                                                              l.Qty
                                                      FROM    GoodsStocks g
                                                              JOIN ( SELECT
                                                              b.KTypeID ,
                                                              l.PTypeID ,
                                                              l.Qty
                                                              FROM
                                                              BillIndex b ,
                                                              GiveBill l
                                                              WHERE
                                                              b.BillNumberID = l.BillNumberID
                                                              AND l.BillNumberID = @BillNumberID
                                                              ) l ON l.PTypeID = g.PTypeID
                                                              AND g.KTypeID = l.KTypeID
                                                      GROUP BY l.Qty
                                                    ) p
                                            SET @SQL = 'ok'
                                        END
							
                                    IF @SQL <> '' 
                                        BEGIN
                                            SET @SQL = 'IF ' + @ComputValue
                                                + @Relation + @ReasonValue
                                                + ' SET @vResult=0 ELSE SET @vResult=1'
                                            EXECUTE sp_executesql @SQL,
                                                N'@vResult bit OUTPUT',
                                                @vResult OUTPUT
                                            IF @vResult = 0 
                                                BEGIN 
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'total')),
                                                              '单据成本'
                                                              + dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) ,@ComputValue),'total'),
                                                              @AuditingStep )
                                                END 
                                            ELSE 
                                                BEGIN 
                                                    INSERT  INTO #Reason
                                                    VALUES  ( @BillNumberID,
                                                              @BillType, 1,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'total')),
                                                              '单据成本'
                                                              + dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ComputValue),'total'),
                                                              @AuditingStep )
                                                END 
                                        END
							--INSERT INTO #Reason VALUES(@BillNumberID,@BillType,0,'单据成本高于____元审核','')
                                END

							--12.有超期应收款	
                            IF ( @i = 12 )	
                                BEGIN
									DECLARE @chvBTypeID VARCHAR(50)	-- 往来单位
									
									IF @BillType IN (11,12,402,313,300) 
									BEGIN
										IF @BillType IN (11,12,402)
										BEGIN
											SELECT  @chvBTypeID = BTypeID
											FROM    BillIndex
											WHERE   BillNumberID = @BillNumberID
										END
										
										IF @BillType IN (313,300)
										BEGIN
											SELECT  @chvBTypeID = BTypeID
											FROM    OrderIndex
											WHERE   BillNumberID = @BillNumberID
										END									
										
										IF EXISTS ( 
													SELECT	TOP 1 1
													FROM  billIndex a
														  LEFT JOIN btype b ON ( a.btypeid = b.typeid )
														  LEFT JOIN stock k ON ( a.ktypeid = k.typeid )
														  LEFT JOIN employee e ON ( a.etypeid = e.typeid )
													WHERE a.IfStopMoney = 0
														  AND a.ifcheck = 't'
														  AND (a.TotalMoney-ISNULL(a.TotalinMoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.preferencemoney,0)-ISNULL(a.ChargeOffTotal,0))> 0
														  AND DATEDIFF(DAY,DATEADD(DAY,a.AlertDay,a.BillDate),GETDATE()) > 0
														  AND a.AlertDay <> 9999
														  AND a.RedWord = 0
														  AND a.BTypeID = @chvBTypeID 
														  AND a.BillType NOT IN (34,6,145,161,400,401,402,403,148,151,404,36) 
													) 
												BEGIN
													INSERT  INTO #Reason VALUES(@BillNumberID,@BillType,0,'该结算单位有超期应收款!','',@AuditingStep )									
												END
												
										--应收增加单、应收减少单    
										IF EXISTS (  
													SELECT	TOP 1 1
													FROM	(
																SELECT	SUM(ISNULL(b.Total,0)) AS Total, 
																		SUM(ISNULL(b.CompleteTotal,0)) AS CompleteTotal,
																		SUM(ISNULL(b.ChargeOffTotal,0)) AS ChargeOffTotal
																from	dbo.BillIndex a
																INNER JOIN addebtbill b ON a.BillNumberId = b.BillNumberId
																WHERE	a.BillType IN (116,115)															
																		AND DATEDIFF(DAY,DATEADD(DAY,b.AlertDay,a.BillDate),GETDATE()) > 0
																		AND (a.IsIni = 1 OR (a.ifcheck = 't' AND a.RedWord = 0))
																		AND b.BTypeID = @chvBTypeID
															)B
													WHERE ISNULL(B.Total,0)-ISNULL(B.CompleteTotal,0)-ISNULL(B.ChargeOffTotal,0) > 0
												 )
											BEGIN
												 INSERT  INTO #Reason VALUES(@BillNumberID,@BillType,0,'该结算单位有超期应收款!','',@AuditingStep)
											END    
                                        
										 --销售发货开票
										IF EXISTS ( 
													SELECT	TOP 1 1
													FROM  ReceiptBillIndex a
														  LEFT JOIN btype b ON ( a.btypeid = b.typeid )													  
														  LEFT JOIN employee e ON ( a.etypeid = e.typeid )
													WHERE a.IfStopMoney = 0
														  AND a.ifcheck = 't'
														  AND (a.TotalMoney-ISNULL(a.CompleteTotal,0)-ISNULL(a.ChargeOffTotal,0))> 0
														  AND DATEDIFF(DAY,DATEADD(DAY,a.AlertDay,a.BillDate),GETDATE()) > 0
														  AND a.AlertDay <> 9999
														  AND a.RedWord = 0
														  AND a.BTypeID = @chvBTypeID
														  AND a.BillType NOT IN (404) 
													) 
												BEGIN
													INSERT  INTO #Reason VALUES(@BillNumberID,@BillType,0,'该结算单位有超期应收款!','',@AuditingStep )									
												END 												
										END                   
                                END

                            IF ( @i = 13 )	--13.超过预设售价
                                BEGIN
                                    DECLARE @chvUserCode VARCHAR(MAX) ,
                                        @chvFullName VARCHAR(MAX)

                                    DECLARE @chvPTypeID VARCHAR(50) ,	--商品的ID
                                        @chvPFullName VARCHAR(MAX) ,	--商品名称
                                        @fltPrice  NUMERIC(24, 10)  ,	--商品的售价
                                        @fltPrePrice  NUMERIC(24, 10) ; --预设售价
										
                                    IF @BillType IN (11,12)
                                        AND @intCostSale = 0 
                                        BEGIN
                                            SET @SQL = ''
                                             
                                            IF @BillType=11
                                            BEGIN
												DECLARE chvPTypeCuror CURSOR
												FOR
													SELECT  PTypeID ,
															CASE WHEN @SalePriceContainTax=1
																 THEN MTaxPrice
															ELSE MDiscountPrice
															END AS MDiscountPrice,
													        MUnitID
													FROM    SaleBill
													WHERE   BillNumberID = @BillNumberID
											END
											ELSE
											BEGIN
												DECLARE chvPTypeCuror CURSOR
												FOR
													SELECT  PTypeID ,
															CASE WHEN @SalePriceContainTax=1
																 THEN MTaxPrice
															ELSE MDiscountPrice
															END AS MDiscountPrice,
													        MUnitID
													FROM    dbo.PT_Combin_SaleBillDetail
													WHERE   BillNumberID = @BillNumberID
											END
											
											
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 1 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 2 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 3 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 4 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 5 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 6 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice6 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 7 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice7 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 8 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice8 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 9 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice9 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 10 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice10 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              SELECT
                                                              @fltPrePrice = LowSalePrice ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 1 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 2 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 3 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 4 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 5 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 6 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice6 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 7 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice7 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 8 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice8 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 9 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice9 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 10 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice10 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              SELECT
                                                              @fltPrePrice = LowSalePrice ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END
													
                                                    IF @ReasonValue <=10 
                                                        SET @strPriceName = '预设售价'
                                                            + @ReasonValue
                                                    ELSE 
                                                        SET @strPriceName = '最低售价'
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称
                                                    IF @fltPrice < @fltPrePrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】单价（'
                                                              + dbo.F_DecimalDisplay(@fltPrice,'price')
                                                              + '元），低于'
                                                              + @strPriceName
                                                              + '（'
                                                              + dbo.F_DecimalDisplay(@fltPrePrice,'price')
                                                              + '元）！', '',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格低于'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror
                                        END

                                    IF @BillType IN (313,300)
                                        BEGIN
                                            SET @SQL = ''
                                            
                                            IF @BillType=300
                                            BEGIN		
												DECLARE chvPTypeCuror CURSOR
												FOR
													SELECT  PTypeID ,
															CASE WHEN @SalePriceContainTax=1
																 THEN MTaxPrice
															ELSE MDiscountPrice
															END AS MDiscountPrice,
													        MUnitID
													FROM    OrderBill
													WHERE   BillNumberID = @BillNumberID
                                            END
                                            ELSE
                                            BEGIN
												DECLARE chvPTypeCuror CURSOR
												FOR
													SELECT  PTypeID ,
															CASE WHEN @SalePriceContainTax=1
																 THEN MTaxPrice
															ELSE MDiscountPrice
															END AS MDiscountPrice,
													        MUnitID
													FROM    dbo.PT_Combin_OrderBillDetail
													WHERE   BillNumberID = @BillNumberID
                                            END
		
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 1 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 2 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 3 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 4 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 5 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 6 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice6 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 7 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice7 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 8 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice8 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 9 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice9 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 10 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice10 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              SELECT
                                                              @fltPrePrice = LowSalePrice ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 1 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 2 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 3 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 4 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 5 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 6 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice6 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 7 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice7 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 8 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice8 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 9 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice9 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 10 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice10 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              SELECT
                                                              @fltPrePrice = LowSalePrice ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END


                                                    IF @ReasonValue <=10 
                                                        SET @strPriceName = '预设售价'
                                                            + @ReasonValue
                                                    ELSE 
                                                        SET @strPriceName = '最低售价'
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称	
                                                    IF @fltPrice < @fltPrePrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN 					
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】单价（'
                                                              + dbo.F_DecimalDisplay(@fltPrice,'price')
                                                              + '元），低于'
                                                              + @strPriceName
                                                              + '（'
                                                              + dbo.F_DecimalDisplay(@fltPrePrice,'price')
                                                              + '元）！', '',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格低于'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )	
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror
                                        END
						
                                    IF @BillType = 184 
                                        BEGIN
                                            SET @SQL = ''	
                                            DECLARE chvPTypeCuror CURSOR
                                            FOR
                                                SELECT  PTypeID,
														CASE WHEN @SalePriceContainTax=1
															 THEN MTaxPrice
														ELSE MSalePrice
														END AS MSalePrice,
													    MUnitID
                                                FROM    QuotePriceBill
                                                WHERE   BillNumberID = @BillNumberID
		
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 1 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 2 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 3 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 4 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 5 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 6 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice6 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 7 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice7 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 8 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice8 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 9 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice9 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 10 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice10 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              SELECT
                                                              @fltPrePrice = LowSalePrice ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 1 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 2 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 3 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 4 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 5 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 6 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice6 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 7 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice7 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 8 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice8 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 9 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice9 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 10 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice10 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              SELECT
                                                              @fltPrePrice = LowSalePrice ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END


                                                    IF @ReasonValue <= 10 
                                                        SET @strPriceName = '预设售价'
                                                            + @ReasonValue
                                                    ELSE 
                                                        SET @strPriceName = '最低售价'
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称
                                                    IF @fltPrice < @fltPrePrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN 					
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            --IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】单价（'
                                                              + dbo.F_DecimalDisplay(@fltPrice,'price')
                                                              + '元），低于'
                                                              + @strPriceName
                                                              + '（'
                                                              + dbo.F_DecimalDisplay(@fltPrePrice,'price')
                                                              + '元）！', '',
                                                              @AuditingStep )
                                                            /*ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格低于'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )*/	
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror
                                        END	
                                    
									
                                    IF @BillType=402
                                              BEGIN
                                            SET @SQL = ''						
                                            DECLARE chvPTypeCuror CURSOR
                                            FOR
                                                SELECT  PTypeID ,
                                                        CASE WHEN @SalePriceContainTax=1
															 THEN MTaxPrice
														ELSE MDiscountPrice
														END AS MDiscountPrice,
														MUnitID
                                                FROM    SendBill
                                                WHERE   BillNumberID = @BillNumberID
		
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 1 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 2 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 3 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 4 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 5 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 6 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice6 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 7 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice7 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 8 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice8 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 9 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice9 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 10 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice10 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              SELECT
                                                              @fltPrePrice = LowSalePrice ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 1 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 2 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 3 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 4 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 5 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 6 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice6 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 7 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice7 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 8 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice8 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 9 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice9 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 10 
                                                              SELECT
                                                              @fltPrePrice = PreSalePrice10 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              SELECT
                                                              @fltPrePrice = LowSalePrice ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END


                                                    IF @ReasonValue <=10 
                                                        SET @strPriceName = '预设售价'
                                                            + @ReasonValue
                                                    ELSE 
                                                        SET @strPriceName = '最低售价'
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称	
                                                    IF @fltPrice < @fltPrePrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN 					
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】单价（'
                                                              + dbo.F_DecimalDisplay(@fltPrice,'price')
                                                              + '元），低于'
                                                              + @strPriceName
                                                              + '（'
                                                              + dbo.F_DecimalDisplay(@fltPrePrice,'price')
                                                              + '元）！', '',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格低于'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )	
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror
                                        END
                                END
							--调拨单中需要出入库审核
                            IF @i = 14 
                                BEGIN
                                    IF @BillType = 17 
                                        INSERT  INTO #Reason
                                        VALUES  ( @BillNumberId, @BillType, 0,
                                                  '同价调拨单需要出、入库审核！', '',
                                                  @AuditingStep )
                                    ELSE 
                                        INSERT  INTO #Reason
                                        VALUES  ( @BillNumberId, @BillType, 0,
                                                  '变价调拨单需要出、入库审核！', '',
                                                  @AuditingStep )
                                END
				--采购订单、采购入库单超过预设进价审核
                            IF @i = 15 
                                BEGIN
                                    DECLARE @strPTypeId VARCHAR(100) ,
                                        @numPrice  NUMERIC(24, 10)  ,
                                        @intOK INT

                                    SET @intOK = 0

						--301采购订单
                                    IF @BillType = 301 
                                        BEGIN	
                                            SET @SQL = ''
		
                                            DECLARE chvPTypeCuror CURSOR
                                            FOR
                                                SELECT  PTypeID ,
                                                        CASE WHEN @BuyPriceContainTax=1
															 THEN MTaxPrice
														ELSE MDiscountPrice
														END AS MDiscountPrice,
														MUnitID
                                                FROM    OrderBill
                                                WHERE   BillNumberID = @BillNumberID
		
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END
									
                                                    SELECT  @TempValue = @ReasonValue
                                                            - 10
					
                                                    SET @strPriceName = '预设进价'
                                                        + CAST(@TempValue AS VARCHAR(10))
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称

									
                                                    IF @fltPrePrice < @fltPrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】超过'
                                                              + @strPriceName
                                                              + '！', '',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格超过'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror


								
                                        END

                                    IF @BillType = 34 
                                        BEGIN
                                            SET @SQL = ''
		
                                            DECLARE chvPTypeCuror CURSOR
                                            FOR
                                                SELECT  PTypeID ,
                                                        CASE WHEN @BuyPriceContainTax=1
															 THEN MTaxPrice
														ELSE MDiscountPrice
														END AS MDiscountPrice,
														MUnitID
                                                FROM    BuyBill
                                                WHERE   BillNumberID = @BillNumberID
		
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END
									
									
                                                    SELECT  @TempValue = @ReasonValue
                                                            - 10
                                                    SET @strPriceName = '预设进价'
                                                        + CAST(@TempValue AS VARCHAR(10))
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称

									
                                                    IF @fltPrePrice < @fltPrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】超过'
                                                              + @strPriceName
                                                              + '！', '',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格超过'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror
                                        END
                                     
                                     -- 询价单，请购单
                                     IF @BillType=185
                                     BEGIN
                                            SET @SQL = ''
		
                                            DECLARE chvPTypeCuror CURSOR
                                            FOR
                                                SELECT  PTypeID ,
                                                        CASE WHEN @BuyPriceContainTax=1
															 THEN MTaxPrice
														ELSE MDiscountPrice
														END AS MDiscountPrice,
														MUnitID
                                                FROM    askpricebill
                                                WHERE   BillNumberID = @BillNumberID
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END
									
									
                                                    SELECT  @TempValue = @ReasonValue
                                                            - 10
                                                    SET @strPriceName = '预设进价'
                                                        + CAST(@TempValue AS VARCHAR(10))
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称

									
                                                    IF @fltPrePrice < @fltPrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】超过'
                                                              + @strPriceName
                                                              + '！', '',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格超过'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror
                                     END
                                     IF @BillType=204
                                     BEGIN
										    SET @SQL = ''
		
                                            DECLARE chvPTypeCuror CURSOR
                                            FOR
                                                SELECT  PTypeID ,
                                                        CASE WHEN @BuyPriceContainTax=1
															 THEN MTaxPrice
														ELSE MDiscountPrice
														END AS MDiscountPrice,
														MUnitID
                                                FROM    requestbill
                                                WHERE   BillNumberID = @BillNumberID
                                                
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END
									
									
                                                    SELECT  @TempValue = @ReasonValue
                                                            - 10
                                                    SET @strPriceName = '预设进价'
                                                        + CAST(@TempValue AS VARCHAR(10))
									
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称
									
                                                    IF @fltPrePrice < @fltPrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】超过'
                                                              + @strPriceName
                                                              + '！', '',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格超过'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror
                                     END
                                     
                                     --暂估入库单
                                     IF @BillType=400
                                        BEGIN
										    SET @SQL = ''
		
                                            DECLARE chvPTypeCuror CURSOR
                                            FOR
                                                SELECT  PTypeID ,
                                                        CASE WHEN @BuyPriceContainTax=1
															 THEN MTaxPrice
														ELSE MDiscountPrice
														END AS MDiscountPrice,
														MUnitID
                                                FROM    AppraisalBill
                                                WHERE   BillNumberID = @BillNumberID
                                                
                                            OPEN chvPTypeCuror
								
                                            FETCH NEXT FROM chvPTypeCuror INTO @chvPTypeID,
                                                @fltPrice,@MUnitID
		
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    IF @intPrcieType = 0 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_Price a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.UnitID=@MUnitID
                                                        END
                                                    ELSE 
                                                        BEGIN
                                                            IF @ReasonValue = 11 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice1 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                            ELSE 
                                                              IF @ReasonValue = 12 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice2 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 13 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice3 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 14 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice4 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                              ELSE 
                                                              IF @ReasonValue = 15 
                                                              SELECT
                                                              @fltPrePrice = PreBuyPrice5 ,
                                                              @chvPFullName = FullName
                                                              FROM
                                                              PType_STypePrice a
                                                              INNER JOIN PType b ON a.ptypeid = b.typeid
                                                              WHERE
                                                              TypeID = @chvPTypeID
                                                              AND a.STypeID = @STypeid
                                                              AND a.UnitID=@MUnitID
                                                        END
									
									
                                                    SELECT  @TempValue = @ReasonValue
                                                            - 10
                                                    SET @strPriceName = '预设进价'
                                                        + CAST(@TempValue AS VARCHAR(10))
									
													SELECT @strPriceName=setName FROM dbo.PriceNameSet WHERE DefaultName=@strPriceName; --设置名称
									
                                                    IF @fltPrePrice < @fltPrice
                                                        AND @fltPrePrice <> 0 
                                                        BEGIN
                                                            SELECT
                                                              @chvUserCode = UserCode ,
                                                              @chvFullName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              SonNum = 0
                                                              AND Deleted = 0
                                                              AND TypeId = @chvPTypeID
                                                            IF @showReasonMx = '1' 
                                                              INSERT
                                                              INTO #ReasonMx
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '编号【'
                                                              + @chvUserCode
                                                              + '】名称【'
                                                              + @chvFullName
                                                              + '】超过'
                                                              + @strPriceName
                                                              + '！', '',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '商品的价格超过'
                                                              + @strPriceName
                                                              + '!', '',
                                                              @AuditingStep )
                                                        END 							 
		
                                                    IF @@ERROR <> 0 
                                                        BEGIN
                                                            CLOSE chvPTypeCuror
                                                            DEALLOCATE chvPTypeCuror
                                                        END
                                                    FETCH NEXT FROM
                                                        chvPTypeCuror INTO @chvPTypeID,
                                                        @fltPrice,@MUnitID
                                                END
		
                                            CLOSE chvPTypeCuror
                                            DEALLOCATE chvPTypeCuror
                                     END
                                END
					
				/*				
				商品扣率小于等于_____折审核				
				*/
                            IF @i = 16 
                                BEGIN
                                    IF @BillType IN ( 178, 195 ) --快修单、维修结算单
                                        BEGIN
                                            IF @BillType = 178 
                                                BEGIN
						--商品
                                                    DECLARE QuickPTypeDiscountCursor
                                                        CURSOR STATIC
                                                    FOR
                                                        SELECT
                                                              p.FullName ,
                                                              CONVERT( NUMERIC(24, 10) , s.Discount)
                                                        FROM  QP_QuickRepairBill_PType s
                                                              INNER JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                        WHERE billnumberid = @BillNumberID
                                                END
                                            IF @BillType = 195 
                                                BEGIN
                                                    DECLARE QuickPTypeDiscountCursor
                                                        CURSOR STATIC
                                                    FOR
                                                        SELECT
                                                              p.FullName ,
                                                              CONVERT( NUMERIC(24, 10) , s.Discount)
                                                        FROM  Qp_ReceptionBill_FactUsePType s
                                                              INNER JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                        WHERE Receptionbillnumberid = @BillNumberID
                                                END
						
                                            OPEN QuickPTypeDiscountCursor
						
                                            FETCH NEXT FROM
                                                QuickPTypeDiscountCursor INTO @TypeName,
                                                @ComputValue
						
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    SET @SQL = 'IF '
                                                        + @ComputValue
                                                        + @Relation
                                                        + @ReasonValue
                                                        + ' SET @vResult=0 ELSE SET @vResult=1'
                                                    EXECUTE sp_executesql @SQL,
                                                        N'@vResult bit OUTPUT',
                                                        @vResult OUTPUT
							
                                                    IF @vResult = 0 
                                                        BEGIN								
                                                            INSERT
                                                              INTO #Reason
                                                            VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'discount')),
                                                              '商品：'
                                                              + @TypeName
                                                              + ',扣率：'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'discount'),
                                                              @AuditingStep )
                                                        END
                                                    FETCH NEXT FROM
                                                        QuickPTypeDiscountCursor INTO @TypeName,
                                                        @ComputValue
                                                END
						
                                            CLOSE QuickPTypeDiscountCursor
                                            DEALLOCATE QuickPTypeDiscountCursor
                                        END
                                END
				
				/*
				项目扣率小于等于_____折审核
				*/
                            IF @i = 17 
                                BEGIN
                                    IF @BillType IN ( 178, 195 ) --快修单、维修结算单
                                        BEGIN
                                            IF @BillType = 178 
                                                BEGIN
						--商品
                                                    DECLARE QuickItemsDiscountCursor
                                                        CURSOR STATIC
                                                    FOR
                                                        SELECT
                                                              p.FullName ,
                                                              CONVERT( NUMERIC(24, 10) , s.Discount)
                                                        FROM  QP_QuickRepairBill_RepairItems s
                                                              INNER JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              QP_RepairItems
                                                              ) p ON p.TypeID = s.RepairItemsTypeID
                                                        WHERE billnumberid = @BillNumberID
                                                END
                                            IF @BillType = 195 
                                                BEGIN
                                                    DECLARE QuickItemsDiscountCursor
                                                        CURSOR STATIC
                                                    FOR
                                                        SELECT
                                                              p.FullName ,
                                                              CONVERT( NUMERIC(24, 10) , s.Discount)
                                                        FROM  Qp_ReceptionBill_RepairItems s
                                                              INNER JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              QP_RepairItems
                                                              ) p ON p.TypeID = s.RepairItemsTypeID
                                                END
                                            OPEN QuickItemsDiscountCursor
						
                                            FETCH NEXT FROM
                                                QuickItemsDiscountCursor INTO @TypeName,
                                                @ComputValue
						
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    SET @SQL = 'IF '
                                                        + @ComputValue
                                                        + @Relation
                                                        + @ReasonValue
                                                        + ' SET @vResult=0 ELSE SET @vResult=1'
                                                    EXECUTE sp_executesql @SQL,
                                                        N'@vResult bit OUTPUT',
                                                        @vResult OUTPUT
							
                                                    IF @vResult = 0 
                                                        BEGIN								
                                                            INSERT
                                                              INTO #Reason
                                                            VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'discount')),
                                                              '项目：'
                                                              + @TypeName
                                                              + ',扣率：'
                                                              + dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ComputValue),'discount'),
                                                              @AuditingStep )
                                                        END
                                                    FETCH NEXT FROM
                                                        QuickItemsDiscountCursor INTO @TypeName,
                                                        @ComputValue
                                                END
						
                                            CLOSE QuickItemsDiscountCursor
                                            DEALLOCATE QuickItemsDiscountCursor
                                        END
                                END
				
				/*
				工时费小于等于工时成本审核
				*/
                            IF @i = 18 
                                BEGIN
                                    IF @BillType = 178 --快修单、
                                        BEGIN
                                            INSERT  INTO #Reason
                                                    SELECT  @BillNumberID ,
                                                            @BillType ,
                                                            0 ,
                                                            '工时费小于等于工时成本审核！' ,
                                                            '' ,
                                                            @AuditingStep
                                                    FROM    QP_QuickRepairBill_RepairItems s
                                                            INNER JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              QP_RepairItems
                                                              ) p ON p.TypeID = s.RepairItemsTypeID
                                                    WHERE   S.Total <= S.CostTotal
                                                            AND billnumberid = @BillNumberID						
                                        END
                                    IF @BillType = 195 --维修结算单
                                        BEGIN
                                            INSERT  INTO #Reason
                                                    SELECT  @BillNumberID ,
                                                            @BillType ,
                                                            0 ,
                                                            '工时费小于等于工时成本审核！' ,
                                                            '' ,
                                                            @AuditingStep
                                                    FROM    Qp_ReceptionBill_RepairItems s
                                                            INNER JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              QP_RepairItems
                                                              ) p ON p.TypeID = s.RepairItemsTypeID
                                                    WHERE   S.Total <= S.CostTotal
                                                            AND billnumberid = @BillNumberID	
                                        END
                                END	
				
				/*
				商品价格低于______元审核
				*/
                            IF @i = 19 
                                BEGIN
                                    IF @BillType IN ( 178, 195 ) --快修单、维修结算单
                                        BEGIN
                                            IF @BillType = 178 
                                                BEGIN
						--商品
                                                    DECLARE QuickPTypeTotalCursor
                                                        CURSOR STATIC
                                                    FOR
                                                        SELECT
                                                              p.FullName ,
                                                              CONVERT( NUMERIC(24, 10) , s.discountprice)
                                                        FROM  QP_QuickRepairBill_PType s
                                                              INNER JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                        WHERE billnumberid = @BillNumberID
                                                END
                                            IF @BillType = 195 
                                                BEGIN
							--商品
                                                    DECLARE QuickPTypeTotalCursor
                                                        CURSOR STATIC
                                                    FOR
                                                        SELECT
                                                              p.FullName ,
                                                              CONVERT( NUMERIC(24, 10) , s.discountprice)
                                                        FROM  Qp_ReceptionBill_FactUsePType s
                                                              INNER JOIN ( SELECT
                                                              TypeID ,
                                                              FullName
                                                              FROM
                                                              PType
                                                              ) p ON p.TypeID = s.PTypeID
                                                        WHERE Receptionbillnumberid = @BillNumberID
                                                END
                                            OPEN QuickPTypeTotalCursor
						
                                            FETCH NEXT FROM
                                                QuickPTypeTotalCursor INTO @TypeName,
                                                @ComputValue
						
                                            WHILE @@FETCH_STATUS = 0 
                                                BEGIN
                                                    SET @SQL = 'IF '
                                                        + @ComputValue
                                                        + @Relation
                                                        + @ReasonValue
                                                        + ' SET @vResult=0 ELSE SET @vResult=1'
                                                    EXECUTE sp_executesql @SQL,
                                                        N'@vResult bit OUTPUT',
                                                        @vResult OUTPUT
							
                                                    IF @vResult = 0 
                                                        BEGIN								
                                                            INSERT
                                                              INTO #Reason
                                                            VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'price')),
                                                              '商品：'
                                                              + @TypeName
                                                              + ',价格：'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                        END
                                                    FETCH NEXT FROM
                                                        QuickPTypeTotalCursor INTO @TypeName,
                                                        @ComputValue
                                                END
						
                                            CLOSE QuickPTypeTotalCursor
                                            DEALLOCATE QuickPTypeTotalCursor
                                        END				
                                END
							
                            IF @i = 20 
                                BEGIN
                                    IF @BillType IN ( 300, 11, 12,301, 34, 184,185,204,400,402,313 ) --采购订单、采购入库单、销售订单、销售出库单,,询价单，请购单,暂估入库单,发出商品出库单
                                        BEGIN
                                            DECLARE @value1  NUMERIC(24, 10)  ,
                                                @value2  NUMERIC(24, 10)  ,
                                                @K INT
                                            SET @K = PATINDEX('%,%',
                                                              @ReasonValue)
                                            SET @value1 = CONVERT( NUMERIC(24, 10) , ISNULL(SUBSTRING(@ReasonValue,
                                                              1, @k - 1), 0))
                                            SET @value2 = CONVERT( NUMERIC(24, 10) , ISNULL(SUBSTRING(@ReasonValue,
                                                              @k + 1,
                                                              LEN(@ReasonValue)
                                                              - 1), 0))
                                            SET @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(@TotalMoney,
                                                              0))
                                            IF ( @Relation <> ''
                                                 AND @ReasonValue <> ''
                                               ) 
                                                BEGIN 
                                                    IF @ComputValue >= @value1
                                                        AND @ComputValue <= @value2 
                                                        BEGIN 
                                                            INSERT
                                                              INTO #Reason
                                                            VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '单据金额从'
                                                              + dbo.F_DecimalDisplay(@value1,'total')
                                                              + '到'
                                                              + dbo.F_DecimalDisplay(@value2,'total')
                                                              + '元审核',
                                                              dbo.F_DecimalDisplay(@ComputValue,'total'),
                                                              @AuditingStep )
                                                        END 
                                                END
                                        END				
                                END	
				
				/*
				比成本价低____%销售
				*/
                            IF @i = 21 
                                BEGIN
                                    SET @SQL = ''
					
                                    IF @BillType = 305 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  b.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    RetailBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                    IF ( @BillType = 11 )
                                        AND @intCostSale = 0 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    SaleBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                        
                                    IF ( @BillType = 12 )
                                        AND @intCostSale = 0 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  a.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    dbo.PT_Combin_SaleBillDetail a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END
                                    
                                    IF @BillType=402  --增加发出商品出库单 司华山 2015-05-20
                                    BEGIN
										 DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  b.KTypeID ,
                                                        a.PtypeID ,
                                                        CONVERT( NUMERIC(24, 10) , a.DiscountPrice) ,
                                                        a.GoodsCostPrice
                                                FROM    SendBill a
                                                        LEFT JOIN ( SELECT
                                                              BillNumberID ,
                                                              kTypeID
                                                              FROM
                                                              BillIndex
                                                              WHERE
                                                              BillNumberID = @BillNumberID
                                                              ) b ON b.BillNumberID = a.BillNumberID
                                                WHERE   a.BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                    END
                                    IF @SQL <> '' 
                                        BEGIN
                                            DECLARE @CostPrice DECIMAL(24, 10) ,
                                                @SalePrice VARCHAR(MAX)
                                            OPEN DiscountCursor
                                            FETCH NEXT FROM DiscountCursor INTO @KTypeID,
                                                @TypeName, @ComputValue,
                                                @GoodsCostPrice
                                            WHILE @@fetch_status = 0 
                                                BEGIN									
                                                    IF EXISTS ( SELECT TOP 1
                                                              1
                                                              FROM
                                                              Sysdata
                                                              WHERE
                                                              SubName = 'Costing'
                                                              AND SubValue = 3 )
                                                        AND @BillType NOT IN (
                                                        141, 300 )	--手工指定法
                                                        BEGIN
                                                            SET @CostPrice = CONVERT( NUMERIC(24, 10) , ISNULL(@GoodsCostPrice,
                                                              0))
                                                            SELECT TOP 1
                                                              @TypeName = FullName,
                                                              @IsService = isService 
                                                            FROM
                                                              PType
                                                            WHERE
                                                              TypeId = @TypeName
                                                        END
                                                    ELSE 
                                                        SELECT
                                                              @TypeName = p.FullName ,
                                                              @IsService = p.isService ,
                                                              @CostPrice = CONVERT( NUMERIC(24, 10) , ISNULL(g.CostPrice,
                                                              0))
                                                        FROM  PType p
                                                              LEFT JOIN ( SELECT
                                                              PTypeID ,
                                                              CostPrice = CONVERT( NUMERIC(24, 10) , ISNULL(( SUM(Total)
                                                              / CASE
                                                              WHEN SUM(QTY) = 0
                                                              THEN NULL
                                                              ELSE SUM(QTY)
                                                              END ), 0))
                                                              FROM
                                                              GoodsStocks
                                                              WHERE
                                                              PTypeId = @TypeName
                                                              AND KtypeId LIKE CASE
                                                              WHEN @BillType IN (
                                                              141, 143, 145,
                                                              147 ) THEN '%'
                                                              ELSE @KTypeID
                                                              + '%'
                                                              END
                                                              GROUP BY PTypeID
                                                              ) g ON g.PTypeID = p.TypeID
                                                        WHERE TypeId = @TypeName
											
                                                    SET @SalePrice = CONVERT( NUMERIC(24, 10) , @CostPrice
                                                        * ( 1
                                                            - CONVERT( NUMERIC(24, 10) , @ReasonValue)
                                                            / 100 ))

                                                    SET @SQL = 'IF '
                                                        + @ComputValue
                                                        + @Relation
                                                        + @SalePrice
                                                        + ' SET @vResult=0 ELSE SET @vResult=1'
                                                    EXECUTE sp_executesql @SQL,
                                                        N'@vResult bit OUTPUT',
                                                        @vResult OUTPUT
                                                    IF(@IsService = 1 and CHARINDEX(','+ CAST(@BillType AS VARCHAR(4))+',',@xsbilltypes) <> 0)
	                                                BEGIN
														SET @vResult = 1
	                                                END
                                                    IF @vResult = 0 
                                                        BEGIN 
                                                            IF @LIMIT_CHECKCOSTPRICE = '1' 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'percentage'))
                                                              + '(成本'
                                                              + dbo.F_DecimalDisplay(@CostPrice,'price')
                                                              + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'percentage'))
                                                              + '(成本' + '****'
                                                              + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                        END 
                                                    ELSE 
                                                        BEGIN 
                                                            IF @LIMIT_CHECKCOSTPRICE = '1' 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 1,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'percentage'))
                                                              + '(成本'
                                                              + dbo.F_DecimalDisplay(@CostPrice,'price')
                                                              + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 1,
                                                              REPLACE(@Description,
                                                              '____',
                                                              dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) , @ReasonValue),'percentage'))
                                                              + '(成本' + '****'
                                                              + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                        END 
                                                    FETCH NEXT FROM
                                                        DiscountCursor INTO @KTypeID,
                                                        @TypeName,
                                                        @ComputValue,
                                                        @GoodsCostPrice
                                                END 
                                            CLOSE DiscountCursor
                                            DEALLOCATE DiscountCursor
                                        END 
                                END	
				
				----毛利总额从_____到_____元审核
                            IF @i = 22 
                                BEGIN
                                    IF @BillType = 184  --报价单
                                        BEGIN
                                            DECLARE @value3  NUMERIC(24, 10)  ,
                                                @value4  NUMERIC(24, 10)  ,
                                                @K1 INT ,
                                                @ComputValue2  NUMERIC(24, 10)  ,
                                                @ComputValue3  NUMERIC(24, 10) 
                                            SELECT  @ComputValue3 = SUM(Q.Qty
                                                              * ISNULL(COSt.costprice,
                                                              0)) FROM  QuotePriceBill Q
LEFT JOIN (SELECT PtypeId,SUM(ISNULL(total,0))/SUM(Qty) AS costprice FROM GoodsStocks WHERE KtypeId IN (SELECT typeid FROM Stock s WHERE STypeID = @stypeid) GROUP BY ptypeid) cost
ON q.PTypeID = cost.PtypeId
WHERE BillNumberID=@billnumberid
                                            SET @K1 = PATINDEX('%,%',
                                                              @ReasonValue)
                                            SET @value3 = CONVERT( NUMERIC(24, 10) , ISNULL(SUBSTRING(@ReasonValue,
                                                              1, @k1 - 1), 0))
                                            SET @value4 = CONVERT( NUMERIC(24, 10) , ISNULL(SUBSTRING(@ReasonValue,
                                                              @k1 + 1,
                                                              LEN(@ReasonValue)
                                                              - 1), 0))
                                            SET @ComputValue2 = CONVERT( NUMERIC(24, 10) , ISNULL(@TotalMoney,
                                                              0)) - @ComputValue3

                                            IF ( @Relation <> ''
                                                 AND @ReasonValue <> ''
                                               ) 
                                                BEGIN 
                                                    IF @ComputValue2 >= @value3
                                                        AND @ComputValue2 <= @value4 
                                                        BEGIN 
                                                            IF @LIMIT_CHECKCOSTPRICE = '1' 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '毛利总额从'
                                                              + dbo.F_DecimalDisplay(@value3,'total')
                                                              + '到'
                                                              + dbo.F_DecimalDisplay(@value4,'total')
                                                              + '元审核',
                                                              '成本总额('
                                                              + dbo.F_DecimalDisplay(@ComputValue3,'total')
                                                              + ')',
                                                              @AuditingStep )
                                                            ELSE 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              '毛利总额从****到****元审核',
                                                              '成本总额(****)',
                                                              @AuditingStep )	
                                                        END 
                                                END
                                        END				
                                END			
				
				--商品售价低于最低售价	
				-- 2015-06-02 增加发出商品出库单 司华山
                            IF @i = 23 
                                BEGIN
									IF (SELECT CostSale FROM dbo.BillIndex WHERE BillNumberId=@BillNumberId)=0
									BEGIN
									--SELECT @LIMIT_DEFAULT_LOWSALEPRICE
                                    SET @SQL = ''
                                    SET @TypeName = ''
                                    
						--根据不同的的单据类型查询不同的明细表
                                    IF @BillType = 305 
                                        BEGIN
                                        if exists( select top 1 1 from PriceStyle where BillType=305 and IsTopPolicy=1)
											begin
												DECLARE DiscountCursor CURSOR STATIC
												FOR
													SELECT  r.PtypeID ,
															CASE WHEN @SalePriceContainTax=1
																 THEN CONVERT( NUMERIC(24, 10) , r.MTaxPrice)
															ELSE CONVERT( NUMERIC(24, 10) , r.MDiscountPrice)
															END,MUnitID
													FROM    RetailBill r
													left join
													PriceDetail p
													on r.PriceDetailId = p.ID
													WHERE   r.BillNumberID = @BillNumberID and (p.IsPriceControl = 1 or r.PriceDetailId = 0)
                                            end
                                        else
											begin
												DECLARE DiscountCursor CURSOR STATIC
												FOR
													SELECT  PtypeID ,
															CASE WHEN @SalePriceContainTax=1
																 THEN CONVERT( NUMERIC(24, 10) , MTaxPrice)
															ELSE CONVERT( NUMERIC(24, 10) , MDiscountPrice)
															END,MUnitID
													FROM    RetailBill
													WHERE   BillNumberID = @BillNumberID
											end
										SET @SQL = 'ok'	
                                        END
                                    IF ( @BillType = 11 ) --AND @intCostSale=0
                                    BEGIN
                                        if exists( select top 1 1 from PriceStyle where BillType=@BillType and IsTopPolicy=1)
										BEGIN
											DECLARE DiscountCursor CURSOR STATIC
											FOR
												SELECT  r.PtypeID ,
														CASE WHEN @SalePriceContainTax=1
															 THEN CONVERT( NUMERIC(24, 10) , r.MTaxPrice)
														ELSE CONVERT( NUMERIC(24, 10) , r.MDiscountPrice)
														END,MUnitID
												FROM    SaleBill r
												left join PriceDetail p	on r.PriceDetailId = p.ID
												WHERE   r.BillNumberID = @BillNumberID and (p.IsPriceControl = 1 or r.PriceDetailId = 0)
                                        END
                                        else
										BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  PtypeID ,
                                                        CASE WHEN @SalePriceContainTax=1
															 THEN CONVERT( NUMERIC(24, 10) , MTaxPrice)
														ELSE CONVERT( NUMERIC(24, 10) , MDiscountPrice)
														END,MUnitID
                                                FROM    SaleBill
                                                WHERE   BillNumberID = @BillNumberID
                                        END
                                        SET @SQL = 'ok'
                                    END
                                        
                                    
                                    IF ( @BillType = 12 ) --AND @intCostSale=0
                                    BEGIN
                                        if exists( select top 1 1 from PriceStyle where BillType=@BillType and IsTopPolicy=1)
										begin
											DECLARE DiscountCursor CURSOR STATIC
											FOR
												SELECT  r.PtypeID ,
														CASE WHEN @SalePriceContainTax=1
															 THEN CONVERT( NUMERIC(24, 10) , r.MTaxPrice)
														ELSE CONVERT( NUMERIC(24, 10) , r.MDiscountPrice)
														END,MUnitID
												FROM    PT_Combin_SaleBillDetail r
												left join PriceDetail p	on r.PriceDetailId = p.ID
												WHERE   r.BillNumberID = @BillNumberID and (p.IsPriceControl = 1 or r.PriceDetailId = 0)
                                        end
                                        else
										begin
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  PtypeID ,
                                                        CASE WHEN @SalePriceContainTax=1
															 THEN CONVERT( NUMERIC(24, 10) , MTaxPrice)
														ELSE CONVERT( NUMERIC(24, 10) , MDiscountPrice)
														END,MUnitID
                                                FROM    dbo.PT_Combin_SaleBillDetail
                                                WHERE   BillNumberID = @BillNumberID
                                        END
                                        SET @SQL = 'ok'
                                    end
                                    
                                    IF ( @BillType = 141 ) 
                                        BEGIN
                                            DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  PtypeID ,
                                                        CASE WHEN @SalePriceContainTax=1
															 THEN CONVERT( NUMERIC(24, 10) , MTaxPrice)
														ELSE CONVERT( NUMERIC(24, 10) , MDiscountPrice)
														END,MUnitID
										        FROM    CommissionBill
                                                WHERE   BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
                                        END	
                                        
                                    IF @BillType=402  --发出商品出库单
									BEGIN 
										  DECLARE DiscountCursor CURSOR STATIC
                                            FOR
                                                SELECT  PtypeID ,
                                                        CASE WHEN @SalePriceContainTax=1
															 THEN CONVERT( NUMERIC(24, 10) , MTaxPrice)
														ELSE CONVERT( NUMERIC(24, 10) , MDiscountPrice)
														END,MUnitID
                                                FROM    SendBill
                                                WHERE   BillNumberID = @BillNumberID
                                            SET @SQL = 'ok'
									END
									
                                    IF @SQL <> '' 
                                        BEGIN
                                            DECLARE @pricetype BIT = 0 --0商品物价,1分支机构物价
                                            SELECT  @pricetype = pricetype
                                            FROM    SType
                                            WHERE   TypeId = @STypeid 
									
                                            OPEN DiscountCursor
                                            FETCH NEXT FROM DiscountCursor INTO @TypeName,
                                                @ComputValue,@MUnitID
                                            WHILE @@fetch_status = 0 
                                                BEGIN
													SET @ReasonValue = ''
                                                    IF ( @pricetype = 0 ) 
                                                        SELECT
                                                              @ReasonValue = LowSalePrice
                                                        FROM  dbo.PType_Price
                                                        WHERE PTypeID = @TypeName
                                                              AND UnitID=@MUnitID
                                                    ELSE 
                                                        SELECT
                                                              @ReasonValue = LowSalePrice
                                                        FROM  dbo.PType_STypePrice
                                                        WHERE PTypeID = @TypeName
                                                              AND STypeID = @STypeid
                                                              AND UnitID=@MUnitID                                                             
                                                              
                                                    IF @ReasonValue=''
														SET @ReasonValue=0       
                                                    IF ( CONVERT( NUMERIC(24, 10) , @ComputValue) < CONVERT( NUMERIC(24, 10) , @ReasonValue) ) 
                                                        BEGIN    
                                                        
                                                            SELECT TOP 1
                                                              @TypeName = FullName
                                                            FROM
                                                              PType
                                                            WHERE
                                                              TypeId = @TypeName
                                                            IF @LIMIT_DEFAULT_LOWSALEPRICE = '1' 
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,'____',(SELECT TOP 1 SetName FROM dbo.PriceNameSet WHERE DefaultName='最低售价'))
                                                              + '('+(SELECT TOP 1 SetName FROM dbo.PriceNameSet WHERE DefaultName='最低售价')
                                                              + dbo.F_DecimalDisplay(@ReasonValue,'price') 
                                                              + ')',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price') ,
                                                              @AuditingStep )
                                                              
                                                            ELSE 
                         
                                                              INSERT
                                                              INTO #Reason
                                                              VALUES
                                                              ( @BillNumberID,
                                                              @BillType, 0,
                                                              REPLACE(@Description,'____',(SELECT TOP 1 SetName FROM dbo.PriceNameSet WHERE DefaultName='最低售价'))
                                                              + '('+(SELECT TOP 1 SetName FROM dbo.PriceNameSet WHERE DefaultName='最低售价')
                                                              +'****)',
                                                              '商品：'
                                                              + @TypeName
                                                              + ',售价'
                                                              + dbo.F_DecimalDisplay(@ComputValue,'price'),
                                                              @AuditingStep )
                                                        END		
										
                                                    FETCH NEXT FROM
                                                        DiscountCursor INTO @TypeName,
                                                        @ComputValue,@MUnitID			 
                                                END 
                                        END 
                                    CLOSE DiscountCursor
                                    DEALLOCATE DiscountCursor	
                                END 							
							                                             END   		
							
							----收/付款金额高于等于_____元审核
                            IF @i = 24 AND @billtype IN (305, 11, 12,160, 141, 6, 45, 34, 161, 145 ,215,46) AND @ReasonValue<>''
                                BEGIN
                                   SET @ComputValue =CONVERT( NUMERIC(24, 10) , @TotalInMoney)
                                   DECLARE @value  NUMERIC(24, 10) 
                                   select @value = CONVERT( NUMERIC(24, 10) , @ReasonValue) 
                                   IF @ComputValue>=@value
                                   BEGIN
										IF  @billtype IN (305, 11,12, 160, 141, 6)
											INSERT INTO #Reason
											VALUES ( 
											@BillNumberID,@BillType,0,
																  REPLACE(REPLACE(@Description,'____',
																  @ReasonValue),'收/付','收'), 
																  '(收款金额'+ CASE WHEN @LIMIT_CHECKCOSTPRICE='1' THEN dbo.F_DecimalDisplay(@ComputValue,'total') ELSE '****' END +')' ,
																  @AuditingStep )
                                        ELSE
											INSERT INTO #Reason
											VALUES ( 
											@BillNumberID,@BillType,0,
																  REPLACE(REPLACE(@Description,'____',
																  @ReasonValue),'收/付','付'),
																  '(付款金额'+CASE WHEN @LIMIT_CHECKCOSTPRICE='1' THEN dbo.F_DecimalDisplay(@ComputValue,'total') ELSE '****' END+')' ,
																  @AuditingStep )   
                                  END                            
								END	
		
							-- 毛利率从————到————元审核
							IF @i=25
							BEGIN
								IF @BillType = 184  --报价单
								BEGIN
									DECLARE @value3_25  NUMERIC(24, 10)  ,
										@value4_25  NUMERIC(24, 10)  ,
										@K1_25 INT ;
								        
									DECLARE @rate_25  NUMERIC(24, 10) ; -- 单据毛利率
								    
								    IF CAST(@TotalMoney AS  NUMERIC(24, 10) )=0.00
										SET @rate_25=0.00;
								    else
										SELECT  @rate_25=(@TotalMoney-ISNULL(SUM(Q.qty*G.price),0))*1.00*100/CAST(@TotalMoney AS  NUMERIC(24, 10) )
										FROM    QuotePriceBill Q
												JOIN (
													SELECT ptypeid,CASE WHEN SUM(qty) IS NULL THEN 0 ELSE ISNULL(SUM(Total),0)*1.0/SUM(Qty) END AS price FROM dbo.GoodsStocks 
													WHERE KtypeId IN (SELECT typeid FROM dbo.Stock WHERE STypeId=@stypeid)
													GROUP BY PtypeId
												)
												G ON Q.ptypeid = G.ptypeid
										WHERE   BillNumberID = @BillNumberID
									SET @K1_25 = PATINDEX('%,%',@ReasonValue)
									
								    
									SET @value3_25 = CONVERT( NUMERIC(24, 10) , ISNULL(SUBSTRING(@ReasonValue,1, @k1_25 - 1), 0))
									SET @value4_25 = CONVERT( NUMERIC(24, 10) , ISNULL(SUBSTRING(@ReasonValue,@k1_25 + 1,LEN(@ReasonValue)- 1), 0))
									IF (@Relation <> '' AND @ReasonValue <> '') 
									BEGIN 
										IF @rate_25 > @value3_25 AND @rate_25 <= @value4_25 
										BEGIN
											IF @LIMIT_CHECKCOSTPRICE='1'
											BEGIN 
												INSERT INTO #Reason VALUES
												( @BillNumberID,@BillType, 0,'毛利率从' + dbo.F_DecimalDisplay(@value3_25,'percentage')+ '%到'+ dbo.F_DecimalDisplay(@value4_25,'percentage')+ '%审核','毛利率('+ dbo.F_DecimalDisplay(@rate_25,'percentage')+ ')', @AuditingStep )
											END
											ELSE
											BEGIN
												INSERT INTO #Reason VALUES
												( @BillNumberID,@BillType, 0,'毛利率从' + dbo.F_DecimalDisplay(@value3_25,'percentage')+ '%到'+ dbo.F_DecimalDisplay(@value4_25,'percentage')+ '%审核','毛利率(****)', @AuditingStep )
											END
										END 
									END
								-- 312	 
								END	
							END	
							
								/*
				抹零金额大于充值金额的__%进行审核
				*/
                         
                            IF @i = 26
                            BEGIN 
								IF @BillType = 312 BEGIN
								--//312 批量充值单
									SET @sql ='
										if exists(select 1 from VipAddMoneyBatchBill where billnumberid=@bid and PreferenceMoney/ChargeMoney*100 '+@Relation+@ReasonValue+')
											set @vResult=0 ;
										else
											set @vResult=1 ;
										select top 1 @ComputValue=PreferenceMoney/ChargeMoney*100 from VipAddMoneyBatchBill where billnumberid=@bid and  PreferenceMoney/ChargeMoney*100'+@Relation+@ReasonValue+'
									';
									EXEC sp_executesql @sql,N'@bid int,@vResult bit OUTPUT,@ComputValue  NUMERIC(24, 10)  OUTPUT',@BillNumberID,@vResult OUTPUT,@ComputValue OUTPUT
									
									
								END ELSE BEGIN
								--//old
                                    IF  @BillType = 181                                      
                                       SELECT  @ComputValue =CONVERT( NUMERIC(24, 10) , preferencemoney/totalmoney *100) FROM dbo.BillIndex WHERE BillNumberId = @BillNumberID							   
                                    ELSE 
                                        SET @ComputValue = CONVERT( NUMERIC(24, 10) , ISNULL(@preferencemoney,0))/ CONVERT( NUMERIC(24, 10) , ISNULL(@TotalMoney,0))
	
	
                                    IF ( @Relation <> ''
                                         AND @ReasonValue <> ''
                                       ) 
                                        BEGIN 
                                            SET @SQL = 'IF ' + @ComputValue
                                                + @Relation + @ReasonValue
                                                + ' SET @vResult=0 ELSE SET @vResult=1'
                                            EXECUTE sp_executesql @SQL,
                                                N'@vResult bit OUTPUT',
                                                @vResult OUTPUT
                                        END
                                --//old
                                END 
                                --结果
                                IF @vResult = 0 
                                BEGIN 
                                    INSERT  INTO #Reason
                                    VALUES  ( @BillNumberID,
                                              @BillType, 0,
                                              REPLACE(@Description,
                                              '__',
                                              dbo.F_DecimalDisplay(@ReasonValue,'percentage')),
                                              dbo.F_DecimalDisplay(@ComputValue,'percentage')+'%',
                                              @AuditingStep )
                                END 
                                ELSE 
                                BEGIN 
                                    INSERT  INTO #Reason
                                    VALUES  ( @BillNumberID,
                                              @BillType, 1,
                                              REPLACE(@Description,
                                              '__',
                                              dbo.F_DecimalDisplay(@ReasonValue,'percentage')),
                                              dbo.F_DecimalDisplay(@ComputValue,'percentage')+'%',
                                              @AuditingStep )
                                END 
                                
                           END				
                   
				/*低于往来单位适用售价进行审核 开始*/              
				IF @i = 27
				BEGIN
				   --获取客户档案上的预设售价(0未设置，大于0开始)
				   DECLARE @price varchar(50);
				   SELECT @price=Price FROM BType  WHERE TypeId=(SELECT DealBTypeId FROM billindex WHERE BillNumberId=@BillNumberID)
				   
				   IF @price <> '0'
				   BEGIN
					
						DECLARE @PriceTypes tinyint;
						SELECT @PriceTypes=PriceType FROM Stype WHERE TypeId=(SELECT StypeId FROM BillIndex WHERE BillNumberId=@BillNumberID)
	
						--获取订单上的当前商品
						DECLARE @productId varchar(50),@productSTypeId VARCHAR(50);
						
						IF @BillType IN (11,12)
						BEGIN
						
							IF @BillType=11
							BEGIN
								SELECT @productId=PTypeId,@productSTypeId=STypeId FROM SaleBill WHERE BillNumberId=@BillNumberID
							END
							ELSE
							BEGIN
								SELECT @productId=PTypeId,@productSTypeId=STypeId FROM	dbo.PT_Combin_SaleBillDetail WHERE BillNumberId=@BillNumberID
							END
							
							SET @sql='IF EXISTS(SELECT 1 FROM dbo.SaleBill a JOIN '
									 +CASE WHEN @priceTypes=0 
										   THEN 'PType_Price ' 
									  ELSE 'PType_STypePrice ' 
									  END
									 +'b ON (a.PtypeId=b.PTypeID AND a.MUnitID=b.UnitID '
									 +CASE WHEN @priceTypes=0 
										   THEN '' 
									  ELSE ' and a.STypeID=b.STypeID ' 
									  END
									 +') WHERE a.BillNumberId='
									 +CAST(@BillNumberID AS VARCHAR(100))
									 +' AND '
									 +CASE WHEN @SalePriceContainTax=1 
										   THEN 'a.MTaxPrice' 
									  ELSE 'a.MDiscountPrice' 
									  END
									 + '<'+(SELECT TOP 1 FiledName FROM PriceNameSet WHERE id-6=@price)+')
									   INSERT INTO #Reason values('+CAST(@BillNumberID AS VARCHAR(100))+','+CAST(@BillType AS VARCHAR(10))+',0,''低于往来单位适用售价进行审核'','''','+CAST(@AuditingStep AS VARCHAR(10))+')
									  '
						END
						ELSE IF @BillType=402
						BEGIN
							SELECT @productId=PTypeId,@productSTypeId=STypeId FROM dbo.SendBill WHERE BillNumberId=@BillNumberID
							
							SET @sql='IF EXISTS(SELECT 1 FROM dbo.SendBill a JOIN '
									 +CASE WHEN @priceTypes=0 
										   THEN 'PType_Price ' 
									  ELSE 'PType_STypePrice ' 
									  END
									 +'b ON (a.PtypeId=b.PTypeID AND a.MUnitID=b.UnitID '
									 +CASE WHEN @priceTypes=0 
										   THEN '' 
									  ELSE ' and a.STypeID=b.STypeID' 
									  END
									 +') WHERE a.BillNumberId='
									 +CAST(@BillNumberID AS VARCHAR(100))
									 +' AND '
									 +CASE WHEN @SalePriceContainTax=1 
										   THEN 'a.MTaxPrice' 
									  ELSE 'a.MDiscountPrice' 
									  END
									 +'<'+(SELECT TOP 1 FiledName FROM PriceNameSet WHERE id-6=@price)+')
									   INSERT INTO #Reason values('+CAST(@BillNumberID AS VARCHAR(100))+','+CAST(@BillType AS VARCHAR(10))+',0,''低于往来单位适用售价进行审核'','''','+CAST(@AuditingStep AS VARCHAR(10))+')
									  '
						END
						EXEC(@sql)
					END
				    
				END	
					
				/*低于往来单位适用售价进行审核 结束*/   	
				
			   --发票类型等于____审核多选
			   --采购暂估开票，销售发货开票
               --司华山 2015-05-20
               
               IF @i = 28  
               BEGIN
					IF @BillType=404 OR @BillType=405
					BEGIN
						DECLARE @FaPiaoType CHAR(1);
						
						SELECT @FaPiaoType=FaPiaoType FROM ReceiptBillIndex WHERE BillNumberID=@BillNumberID AND BillType=@BillType;
						
						SET @SQL='IF '+@ReasonValue+@Relation +@FaPiaoType
                                 +' SET @vResult=0 ELSE SET @vResult=1'
						EXECUTE sp_executesql @SQL,N'@vResult bit OUTPUT',@vResult OUTPUT
						
						IF @ReasonValue=2
							SET @ReasonValue='普通发票'
						ELSE IF @ReasonValue=1
							SET @ReasonValue='增值税发票'
							
						IF @vResult = 0 
						BEGIN								
                            INSERT INTO #Reason VALUES (@BillNumberID,
                                                        @BillType, 
                                                        0,
                                                        REPLACE(@Description,'____',@ReasonValue),
                                                        '',
                                                        @AuditingStep)
                        END     
					END
		         END
		         
		         --单据价税合计总额大于等于____审核
		         --采购暂估开票，销售发货开票
		         --司华山 2015-05-20
		         IF @i=29
		         BEGIN
					IF @BillType=404 OR @BillType=405
					BEGIN
						DECLARE @TaxTotalMoney  NUMERIC(24, 10) ;
						
						SELECT @TaxTotalMoney=TaxTotalMoney FROM ReceiptBillIndex WHERE BillNumberID=@BillNumberID AND BillType=@BillType;
						
						SET @SQL='IF ' +CONVERT(VARCHAR(20),@TaxTotalMoney)+@Relation+@ReasonValue +
								 'SET @vResult=0 ELSE SET @vResult=1';
						EXECUTE sp_executesql @SQL,N'@vResult bit OUTPUT',@vResult OUTPUT
						
						IF @vResult=0
						BEGIN
							  INSERT INTO #Reason VALUES (@BillNumberID,
                                                          @BillType, 
                                                          0,
                                                          REPLACE(@Description,'____',dbo.F_DecimalDisplay(CONVERT( NUMERIC(24, 10) ,@ReasonValue),'total')),
                                                          '',
                                                          @AuditingStep)
						END
					END
		         END
		         
		         --采购单库存上限的审核条件
		         --司华山 2015-05-20
				 IF @i=30
				 BEGIN

					 
					DECLARE	@TmpQty TABLE(PTypeID VARCHAR(100),
									   	  Qty      NUMERIC(24, 10) ,
										  UserCode VARCHAR(1000),
										  FullName VARCHAR(1000),
										  KTypeID  VARCHAR(100),
										  RowIndex INT IDENTITY(1,1)
										 );			
				
					--采购入库单	
					IF @BillType=34
					BEGIN
						SELECT @KTypeID=KTypeId FROM BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType;
						
						--同表体同商品同仓库分组
						INSERT INTO @TmpQty (PTypeID,Qty,UserCode,FullName,KTypeID) 
						SELECT      A.PTypeId,SUM(A.Qty) AS Qty,B.UserCode,B.FullName,A.KTypeID 
						FROM        BuyBill A INNER JOIN PType B ON A.PtypeId=B.typeId 
						WHERE       BillNumberId=@BillNumberID 
						GROUP BY    A.PtypeId,B.UserCode,B.FullName,A.KTypeID
					END
					--采购订单
					IF @BillType=301
					BEGIN
						SELECT @KTypeID=KTypeId FROM OrderIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType;
						
						--同表体同商品同仓库分组
						INSERT INTO @TmpQty (PTypeID,Qty,UserCode,FullName,KTypeID) 
						SELECT A.PTypeId,SUM(A.Qty) AS Qty,B.UserCode,B.FullName,A.KTypeID 
						FROM OrderBill A INNER JOIN PType B ON A.PtypeId=B.typeId 
						WHERE BillNumberId=@BillNumberID 
						GROUP BY A.PtypeId,B.UserCode,B.FullName,A.KTypeID
						
					END
					--仓库入库单
					IF @BillType=418
					BEGIN
						SELECT @KTypeID=KTypeId FROM dbo.FactIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType;
						
						--同表体同商品同仓库分组
						INSERT INTO @TmpQty (PTypeID,Qty,UserCode,FullName,KTypeID) 
						SELECT A.PTypeId,SUM(A.Qty) AS Qty,B.UserCode,B.FullName,A.KTypeID 
						FROM dbo.FactDepotInOut A INNER JOIN PType B ON A.PtypeId=B.typeId 
						WHERE BillNumberId=@BillNumberID 
						GROUP BY A.PtypeId,B.UserCode,B.FullName,A.KTypeID
						
					END
					--多仓库
					SELECT @IfMulStock=IsChecked FROM Qp_MulStockConfig WHERE BillType=@BillType
					
					SET @RowIndex=1;
					SELECT @RowCount=COUNT(1) FROM @TmpQty;
						
					WHILE(@RowIndex<=@RowCount)
					BEGIN
						SELECT @PTypeId=PTypeId,@TmpKTypeID=KTypeID,@UserCode=UserCode,@FullName=FullName,@Qty=Qty FROM @TmpQty WHERE RowIndex=@RowIndex;
							
						--启用多仓库取表体仓库
						IF @IfMulStock=1
						BEGIN
							IF @BillType<>418
							BEGIN
								SELECT @UpLimitQty=UpLimitQty FROM STOCKALARM WHERE PTypeId=@PTypeId AND KTypeId=@TmpKTypeID
								SELECT @StockQty=Qty FROM GoodsStocks WHERE PtypeId=@PTypeId AND KtypeId=@TmpKTypeID;
							END
							ELSE
							BEGIN
								SELECT @UpLimitQty=UpLimitQty FROM STOCKALARM WHERE PTypeId=@PTypeId AND KTypeId=@TmpKTypeID
								SELECT @StockQty=Qty FROM FactStocks WHERE PtypeId=@PTypeId AND KtypeId=@TmpKTypeID;
							END
							
						END
						ELSE
						BEGIN
							IF @BillType<>418
							BEGIN
								SELECT @UpLimitQty=UpLimitQty FROM STOCKALARM WHERE PTypeId=@PTypeId AND KTypeId=@KTypeID
								SELECT @StockQty=Qty FROM GoodsStocks WHERE PtypeId=@PTypeId AND KtypeId=@KTypeID;
							END
							ELSE
							BEGIN
								SELECT @UpLimitQty=UpLimitQty FROM STOCKALARM WHERE PTypeId=@PTypeId AND KTypeId=@KTypeID
								SELECT @StockQty=Qty FROM FactStocks WHERE PtypeId=@PTypeId AND KtypeId=@KTypeID;
							END
						END
						
						
						--PRINT(@Qty)
						--PRINT(@StockQty)
						--PRINT(@UpLimitQty)
						IF  (ISNULL(@Qty,0)+ISNULL(@StockQty,0))>@UpLimitQty
						BEGIN
							INSERT INTO #Reason VALUES (@BillNumberID,
                                                        @BillType, 
                                                        0,
                                                        '编号【'+@UserCode+'】 名称【'+@FullName+'】',
                                                        @Description,
                                                        @AuditingStep)
						END
						SET @RowIndex+=1;
					END
				 END
				  --往来核销单核销金额高于等于__审核
				 IF @i=31
				 BEGIN
					if @BillType =450 
                    BEGIN
						SELECT @ComputValue=totalmoney FROM billIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType
						SET @SQL = 'IF ' + @ComputValue
                                                + @Relation + @ReasonValue
                                                + ' SET @vResult=0 ELSE SET @vResult=1'						
																
						EXECUTE sp_executesql @SQL,
                                                N'@vResult bit OUTPUT',
                                                @vResult OUTPUT
						IF @vResult = 0 
						BEGIN
                             INSERT  INTO #Reason
                             VALUES  ( @BillNumberID,
                             @BillType, 0,
                             REPLACE(@Description,'____',dbo.F_DecimalDisplay(@ReasonValue,'total')),
                             '核销金额:'+dbo.F_DecimalDisplay(@ComputValue,'total'),
                             @AuditingStep )
                        END
					END
				 END
				-- 出库单低于库存下限审核的审核条件
				IF @i=32
				 BEGIN
					DECLARE	
							@DownLimitQty  NUMERIC(24, 10) 	  --仓库下限数量
					DECLARE	@TmpQty1 TABLE(PTypeID VARCHAR(100),
									   	  Qty      NUMERIC(24, 10) ,
										  UserCode VARCHAR(1000),
										  FullName VARCHAR(1000),
										  KTypeID  VARCHAR(100),
										  RowIndex INT IDENTITY(1,1)
										 );			
				
					--仓库出库单	
					IF @BillType=419
					BEGIN
						SELECT @KTypeID=KTypeId FROM FactIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType;
						
						--同表体同商品同仓库分组
						INSERT INTO @TmpQty1 (PTypeID,Qty,UserCode,FullName,KTypeID) 
						SELECT      A.PTypeId,SUM(A.Qty) AS Qty,B.UserCode,B.FullName,A.KTypeID 
						FROM        FactDepotInOut A INNER JOIN PType B ON A.PtypeId=B.typeId 
						WHERE       BillNumberId=@BillNumberID 
						GROUP BY    A.PtypeId,B.UserCode,B.FullName,A.KTypeID
					END
					
					--多仓库
					SELECT @IfMulStock=IsChecked FROM Qp_MulStockConfig WHERE BillType=@BillType
					
					SET @RowIndex=1;
					SELECT @RowCount=COUNT(1) FROM @TmpQty1;
					
					WHILE(@RowIndex<=@RowCount)
					BEGIN
						SELECT @PTypeId=PTypeId,@TmpKTypeID=KTypeID,@UserCode=UserCode,@FullName=FullName,@Qty=Qty FROM @TmpQty1 WHERE RowIndex=@RowIndex;
							
						--启用多仓库取表体仓库
						IF @IfMulStock=1
						BEGIN
							SELECT @DownLimitQty=DownLimitQty FROM STOCKALARM WHERE PTypeId=@PTypeId AND KTypeId=@TmpKTypeID
							SELECT @StockQty=Qty FROM FactStocks WHERE PtypeId=@PTypeId AND KtypeId=@TmpKTypeID;
						END
						ELSE
						BEGIN
							SELECT @DownLimitQty=DownLimitQty FROM STOCKALARM WHERE PTypeId=@PTypeId AND KTypeId=@KTypeID
							SELECT @StockQty=Qty FROM FactStocks WHERE PtypeId=@PTypeId AND KtypeId=@KTypeID;
						END
						--PRINT(@Qty)
						--PRINT(@StockQty)
						--PRINT(@DownLimitQty)
						IF  (ISNULL(@StockQty,0)-ISNULL(@Qty,0))<@DownLimitQty
						BEGIN
							INSERT INTO #Reason VALUES (@BillNumberID,
                                                        @BillType, 
                                                        0,
                                                        '编号【'+@UserCode+'】 名称【'+@FullName+'】',
                                                        @Description,
                                                        @AuditingStep)
						END
						SET @RowIndex+=1;
					END
				 END
				  
             END   
			 SET @i = @i + 1
           END

            FETCH NEXT FROM CURSOR_AuditingReason INTO @AuditingReason,
                @AuditingStep, @outkty
        END
    CLOSE CURSOR_AuditingReason
    DEALLOCATE CURSOR_AuditingReason
-- 游标循环 - End
    BillPass:
    BEGIN
	--单独处理细化预设售价的提示
        SELECT  @intCount = COUNT(*)
        FROM    #ReasonMx
        IF @intCount > 10 
            BEGIN
                INSERT  INTO #Reason
                        SELECT TOP 10
                                *
                        FROM    #ReasonMx
                INSERT  INTO #Reason
                VALUES  ( @BillNumberId, @BillType, 0, '...', '', 999 ) 
            END
        ELSE 
            BEGIN
                IF EXISTS ( SELECT TOP 1
                                    1
                            FROM    #ReasonMx ) 
                    INSERT  INTO #Reason
                            SELECT  *
                            FROM    #ReasonMx
            END

        IF @AppointStep = -1 
            SELECT DISTINCT
                    BillNumberID ,
                    BillType ,
                    PassFlag ,
                    Reason ,
                    Value ,
                    AuditingStep
            FROM    #Reason
            ORDER BY AuditingStep ,
                    Reason ,
                    Value
        ELSE 
            SELECT  *
            FROM    #Reason
            ORDER BY AuditingStep ,
                    Reason ,
                    Value

        DROP TABLE #Reason,#ReasonMx

        IF ISNULL(@IfAudit, '') = '1' 
            RETURN -1
        IF ISNULL(@IfAudit, '') = '-1' 
            RETURN -2
        RETURN 0
    END


GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/*

DECLARE
	@BillNumberID INT ,					--单据编号	
	@OperatorID VARCHAR(100) , 			--操作员ID号
	@BillIndexType INT = 2 ,					--单据类型   0.订单  1.借欠单据  2.一般物流单据 7实物库存
	@showReasonMx VARCHAR(10) = '' ,			--显示审核提示明细
	@AppointStep INT = -1 ,					-- 检查指定步骤原因，0：查全部  -1：查全部，但聚合审核原因(适用于提交审核时，显示原因)
	@ifCostLimit INT = 1,					-- 1：要限制操作员成本查看权限  0：不限制
												-- 针对写入auditingbill中的stepreasons，查看审核历史的每级原因，有些原因是与成本相关联的，
												-- 针对不同的人来看，成本数据与成本查看权限相关
	@IsPlateAlready INT = 0,				--因为新增了“我的已审核列表”，现在已审核的单据一样需要查看到 审核原因,所以增加参数，是否为已审核列表查询
	@intRet	INT
	
	
SELECT
	@BillNumberID=9,					--单据编号	
	@OperatorID='00001', 			--操作员ID号
	@BillIndexType= 2 ,				--单据类型   0.订单  1.借欠单据  2.一般物流单据 7实物库存
	@showReasonMx= '' ,				--显示审核提示明细
	@AppointStep = -1 ,				-- 检查指定步骤原因，0：查全部  -1：查全部，但聚合审核原因(适用于提交审核时，显示原因)
	@ifCostLimit= 1,				-- 1：要限制操作员成本查看权限  0：不限制
												-- 针对写入auditingbill中的stepreasons，查看审核历史的每级原因，有些原因是与成本相关联的，
												-- 针对不同的人来看，成本数据与成本查看权限相关
	@IsPlateAlready = 0				--因为新增了“我的已审核列表”，现在已审核的单据一样需要查看到 审核原因,所以增加参数，是否为已审核列表查询	

BEGIN TRAN

EXEC	@intRet=GP_BillAudtingCheckReason
      @BillNumberID,					--单据编号	
      @OperatorID, 			--操作员ID号
      @BillIndexType,					--单据类型   0.订单  1.借欠单据  2.一般物流单据 7实物库存
      @showReasonMx,			--显示审核提示明细
      @AppointStep,					-- 检查指定步骤原因，0：查全部  -1：查全部，但聚合审核原因(适用于提交审核时，显示原因)
      @ifCostLimit,					-- 1：要限制操作员成本查看权限  0：不限制
													-- 针对写入auditingbill中的stepreasons，查看审核历史的每级原因，有些原因是与成本相关联的，
													-- 针对不同的人来看，成本数据与成本查看权限相关
	  @IsPlateAlready				--因为新增了“我的已审核列表”，现在已审核的单据一样需要查看到 审核原因,所以增加参数，是否为已审核列表查询
    
    
SELECT @intRet  

ROLLBACK TRAN  

*/



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：冯波
	日期：2010-04-08
	描述：系统重建或年结存时清除种子数
*/
CREATE       PROCEDURE GP_BillCode_Seed_ReBuild

--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	IF NOT EXISTS(
		SELECT BillNumberID FROM BillIndex
		UNION ALL
		SELECT BillNumberID FROM OrderIndex
		UNION ALL
		SELECT StockCheckID FROM StockCheckIndex
		UNION ALL
		SELECT BillNumberId FROM LendIndex
		UNION ALL
		SELECT BillNumberID FROM FaPiaoBillIndex
		UNION ALL
		SELECT BillnumberID FROM TCBillindex
		UNION ALL
		SELECT BillNumberID FROM ToolIndex
		UNION ALL
		SELECT BillNumberID FROM RequestIndex
		UNION ALL
		SELECT BillNumberID FROM SerialAdjustIndex
		UNION ALL
		SELECT BillNumberID FROM CM_CarUseIndex
		UNION ALL
		SELECT BillNumberID FROM CM_FeeIndex
		UNION ALL 
		SELECT BillNumberId FROM CommissionBillNew
		UNION ALL 
		SELECT BillNumberId FROM ReferencePlanCommission
		UNION ALL
		SELECT BillNumberId FROM dbo.CommissionRule
		UNION ALL 
		SELECT BillNumberID FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillNumberID FROM dbo.onShelvespickIndex
		UNION ALL
		SELECT BillNumberID FROM dbo.FactIndex
		UNION ALL
		SELECT BillNumberID FROM PosAllotApplyBillIndex
		UNION ALL 
		SELECT BillNumberID FROM  dbo.Coupon_BillIndex 
	)
	BEGIN
		TRUNCATE TABLE BillCode_Seed
	END
	ELSE
	BEGIN
		DELETE BillCode_Seed
		WHERE BillType NOT IN
		(
			SELECT BillType FROM BillIndex
			UNION ALL
			SELECT BillType FROM OrderIndex
			UNION ALL
			SELECT BillType FROM LendIndex
			UNION ALL
			SELECT BillType FROM FaPiaoBillIndex
			UNION ALL
			SELECT BillType FROM ReceiptBillIndex
			UNION ALL
			SELECT BillType FROM dbo.onShelvespickIndex
			UNION ALL 
			SELECT BillType FROM dbo.FactIndex
			UNION ALL
			SELECT BillType FROM PosAllotApplyBillIndex
			UNION ALL
			SELECT 306
			UNION ALL
			SELECT 164
			UNION ALL
			SELECT 193
			UNION ALL
			SELECT 194
			UNION ALL
			SELECT 204
			UNION ALL
			SELECT 203
			UNION ALL
			SELECT 208
			UNION ALL
			SELECT 209
			UNION ALL 
			SELECT 311
			UNION ALL
			SELECT 309
			UNION ALL
			SELECT BILLTYPE FROM dbo.Coupon_BillIndex
		)
		
		IF NOT EXISTS(SELECT StockCheckID FROM StockCheckIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=306
		END
		
		IF NOT EXISTS(SELECT BillnumberID FROM CommissionRule /*TCBillindex*/)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=164
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM ToolIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType IN (193,194)
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM SerialAdjustIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=203
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM RequestIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=204
		END
		IF NOT EXISTS(SELECT BillNumberID FROM CM_CarUseIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=208
		END
		IF NOT EXISTS(SELECT BillNumberID FROM CM_FeeIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=209
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM CommissionBillNew)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=311
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM ReferencePlanCommission)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=309
		END
	END
	
	--清掉小于系统年份的种子数
	DECLARE
		@inttmpYear	INT
		
	SELECT @inttmpYear=YEAR(MIN(BillDate)) FROM dbo.BillIndex
	
	
	DELETE BillCode_Seed
	WHERE CAST(LEFT(FlowDate,4) AS INT) <@inttmpYear
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_BillSave_CheckBillCode]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_BillSave_CheckBillCode];
GO

SET ANSI_NULLS ON;
GO

SET QUOTED_IDENTIFIER OFF;
GO

--**************************
--By: Haiyang, Li
--Date: 01-11-2012
--Description: 检测单据编号重复性
--**************************
CREATE    PROCEDURE [dbo].[GP_BillSave_CheckBillCode]
(
  @BillIndexTableName VARCHAR(20) ,
  @BillNumberID INT ,
  @BillCode VARCHAR(200)
)
--@encode$--
AS 
BEGIN
	BEGIN
		--表体在BillIndex中, 大多数单据如此
		IF @BillIndexTableName = 'BillIndex'
			BEGIN
				IF @billnumberid > 0
					SELECT  1 WHERE EXISTS (SELECT 1 FROM BillIndex WHERE BillCode = @billcode
							AND BillNumberID <> @billnumberid)
				ELSE
					SELECT  1 WHERE EXISTS (SELECT 1 FROM BillIndex WHERE BillCode = @billcode)
				RETURN ;
			END
		--OrderIndex表, 销售和采购订单
		IF @BillIndexTableName = 'OrderIndex'
			BEGIN
				IF @billnumberid > 0
					SELECT  1 WHERE EXISTS (SELECT 1 FROM OrderIndex WHERE BillCode = @billcode
							AND BillNumberID <> @billnumberid)
				ELSE
					SELECT  1 WHERE EXISTS (SELECT 1 FROM OrderIndex WHERE BillCode = @billcode)
				RETURN ;
			END
		--LendIndex表, 借欠类单据
		IF @BillIndexTableName = 'LendIndex'
			BEGIN
				IF @billnumberid > 0
					SELECT  1 WHERE EXISTS (SELECT 1 FROM LendIndex WHERE BillCode = @billcode
							AND BillNumberID <> @billnumberid)
				ELSE
					SELECT  1 WHERE EXISTS (SELECT 1 FROM LendIndex WHERE BillCode = @billcode)
				RETURN ;
			END
		--FaPiaobillindex表, 发票
		IF @BillIndexTableName = 'FaPiaobillindex'
			BEGIN
				IF @billnumberid > 0
					SELECT  1 WHERE EXISTS (SELECT 1 FROM FaPiaobillindex WHERE BillCode = @billcode
							AND BillNumberID <> @billnumberid)
				ELSE
					SELECT  1 WHERE EXISTS (SELECT 1 FROM FaPiaobillindex WHERE BillCode = @billcode)
				RETURN ;
			END
		--RequestIndex表, 请购单
		IF @BillIndexTableName = 'RequestIndex'
			BEGIN
				IF @billnumberid > 0
					SELECT  1 WHERE EXISTS (SELECT 1 FROM RequestIndex WHERE BillCode = @billcode
							AND BillNumberID <> @billnumberid)
				ELSE
					SELECT  1 WHERE EXISTS (SELECT 1 FROM RequestIndex WHERE BillCode = @billcode)
				RETURN ;
			END
		--SerialAdjustIndex表, 序列号调整单
		IF @BillIndexTableName = 'SerialAdjustIndex'
			BEGIN
				IF @billnumberid > 0
					SELECT  1 WHERE EXISTS (SELECT 1 FROM SerialAdjustIndex WHERE BillCode = @billcode
							AND BillNumberID <> @billnumberid)
				ELSE
					SELECT  1 WHERE EXISTS (SELECT 1 FROM SerialAdjustIndex WHERE BillCode = @billcode)
				RETURN ;
			END
		
	END
END

GO


SET ANSI_NULLS ON;
GO

SET QUOTED_IDENTIFIER OFF;
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_BillSaveChecker_Employee]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_BillSaveChecker_Employee]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- By: Haiyang, Li
-- Create date: 11.06.2012
-- Description: 保存服务器端职员校验
-- Return value: 0: 无错, 1: 无权限或无效

-- =============================================
CREATE PROCEDURE GP_BillSaveChecker_Employee
    (
      @UserID VARCHAR(50) ,
      @EmployeeID VARCHAR(50)  --职员ID   
       
    )
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
			-- @BtypeAll = 0
			--这里不考虑应该填写供应商填写成客户的情况, 这部分已经在服务端处理
			--这里的BtypeAll只用于权限中供应商和客户分开的情况
			
    
    IF EXISTS ( SELECT  1
                FROM    LoginUser
                WHERE   ETypeId = @UserID
                        AND MangerETypeID = '00001' )
        AND NOT EXISTS ( SELECT 1
                         FROM   dbo.employee
                         WHERE  typeId = @EmployeeID
                                AND deleted = 0
                                AND  sonnum = 0) 
        RETURN 1 
    ELSE 
        IF NOT EXISTS ( SELECT  1
                        FROM    dbo.employee E
                                INNER JOIN dbo.etype_l EL ON EL.etypeid = @UserID AND E.typeId LIKE EL.typeid
                                                          + '%'
                        WHERE   E.typeId = @EmployeeID
                                AND E.SonNum = 0
                                AND E.Deleted = 0) 
            RETURN 1	
    RETURN 0
END

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_BillSaveCheckerBtype]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_BillSaveCheckerBtype]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- By: Haiyang, Li
-- Create date: 11.06.2012
-- Description: 保存服务器端往来单位和结算单位校验
-- Return value: 0: 无错, 1: 结算单位无效或没有权限, 2: 往来单位无效或没有权限

-- =============================================
CREATE PROCEDURE GP_BillSaveCheckerBtype
    (
      @UserID VARCHAR(50) ,
      @RelatedPartyForSettlementID VARCHAR(50) ,	--结算单位ID, 为空不验证, 同时Type为0
      @RelatedPartyID VARCHAR(50) ,								--往来单位ID, 为空不验证, 同时Type为0
      @RelatedPartyForSettlementType VARCHAR(1) , -- 用于权限验证： 1: 客户 2: 供应商 0: 无需验证(为0时，对应id必定为零)
      @RelatedPartyType VARCHAR(1) ,							-- 用于权限验证： 1: 客户 2: 供应商 0: 无需验证
      @BtypeAll BIT																--0: 没有统一客户和供应商, 1: 统一客户和供应商
	--@ReturnValue	VARCHAR(max) out	--  输出信息
    )
--@encode$--
AS 
SET NOCOUNT ON

BEGIN
	-- @BtypeAll = 0
	--这里不考虑应该填写供应商填写成客户的情况, 这部分已经在服务端处理
	--这里的BtypeAll只用于权限中供应商和客户分开的情况			
    IF @RelatedPartyForSettlementID <> '' 
        BEGIN
            IF EXISTS ( SELECT  1
                        FROM    LoginUser
                        WHERE   ETypeId = @UserID
                                AND (( @RelatedPartyForSettlementType = '1' AND MangerBTypeID = '00001' )
																		OR ( @RelatedPartyForSettlementType = '2' AND MangerBTypeID2 = '00002'))
																		)
                BEGIN
                    IF NOT EXISTS ( SELECT  1
                                    FROM    btype
                                    WHERE   sonnum = 0
                                            AND deleted = 0
                                            AND leveal <> 1
                                            AND typeId = @RelatedPartyForSettlementID ) 
                        RETURN 1 
                END
            ELSE 
                IF NOT EXISTS ( SELECT  1
                                FROM    btype B
                                        INNER JOIN dbo.btype_l BL ON B.typeId LIKE BL.typeid
                                                          + '%'
                                WHERE   B.typeId = @RelatedPartyForSettlementID
                                        AND B.SonNum = 0
                                        AND B.Deleted = 0
                                        AND B.Leveal <> 1
                                        AND BL.etypeid = @UserID 
																					AND BL.flag = 1 )
                    RETURN 1	
        END
        
    IF @RelatedPartyID <> '' 
        BEGIN
            IF EXISTS ( SELECT  1
                        FROM    LoginUser
                        WHERE   ETypeId = @UserID
                                AND (( @RelatedPartyType = '1' AND MangerBTypeID = '00001' )
																		OR ( @RelatedPartyType = '2' AND MangerBTypeID2 = '00002'))
                                   )
                BEGIN
                    IF NOT EXISTS ( SELECT  1
                                    FROM    btype
                                    WHERE   sonnum = 0
                                            AND deleted = 0
                                            AND leveal <> 1
                                            AND typeId = @RelatedPartyID ) 
                        RETURN 2
                END
            ELSE 
                IF NOT EXISTS ( SELECT  1
                                FROM    btype B
                                        INNER JOIN dbo.btype_l BL ON B.typeId LIKE BL.typeid
                                                          + '%'
                                WHERE   B.typeId = @RelatedPartyID
                                        AND B.SonNum = 0
                                        AND B.Deleted = 0
                                        AND B.Leveal <> 1
                                        AND BL.etypeid = @UserID
																					AND BL.flag = 1 ) 
                    RETURN 2
        END
        
  --      DECLARE @RE VARCHAR(MAX)
		
		--EXEC Web_CheckSysValue 9,@RE OUTPUT
		
		--IF @RE = 1 RETURN 3
        		
		RETURN 0
END

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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




-- 职员创利报表设置页面保存
-- chen_qihua 2004-04-05
CREATE       PROCEDURE [GP_BillSetSave] 
(
@OperatorID varchar(50), -- 职员 ID
@ATypeIDS varchar(8000)  -- 科目 ID 串
)
--@encode$--
AS
SET NOCOUNT ON

IF @ATypeIDS= ''
	RETURN -1

DECLARE @i int                  -- ','的位置常量
DECLARE @AtypeID  varchar(1000) -- 科目变量ID

SET @AtypeIDS = RTRIM(LTRIM(@AtypeIDS))
SET @i=charindex(',',@AtypeIDS)  -- 取得'，'的位置常量
if @i >=1 
	begin
		delete from EmpIncSet where etypeid = @OperatorID  -- 删除操作员的对应科目
	end

WHILE @i>=1
    BEGIN
		
		SET @AtypeID = LEFT(@AtypeIDS,@i-1)
		if not( @AtypeID='payed' or  @AtypeID ='unpayed')
			begin
				if not exists (Select * From Ac_Items where nid =@AtypeID)
					return -2
			end
		
		Insert EmpIncSet values (@OperatorID,@AtypeID)
		SET @AtypeIDS=SUBSTRING(@AtypeIDS,@i+1,len(@AtypeIDS)-@i)
        SET @i=charindex(',',@AtypeIDS)
    END
SET @AtypeID = @AtypeIDS
IF @AtypeID<>''
	BEGIN
		if not( @ATypeID='payed' or  @ATypeID ='unpayed')
			begin
				if not exists (Select * From Ac_Items where nid =@AtypeID)
					return -2
			end
		Insert EmpIncSet values (@OperatorID,@ATypeID)

	END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

--====================================================================================
-----------------功能：将品牌往来余额应收转成期初应收增加 减少单据 
--====================================================================================

CREATE    PROC Gp_BrandarYsyfToInibill
(
	@yearendmode			CHAR(1) = '1'		-- 1 - 按余额转期初(arap_total)；0 - 按单据转期初(AccountCredence)
)	

--@encode$--
AS
SET NOCOUNT ON

IF @yearendmode=0
RETURN ;
DECLARE @Dtypeid VARCHAR(50)='',@EtypeId VARCHAR(50)=''
DECLARE @startdate DATETIME
SELECT @startdate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth
DECLARE @proinfo INT --A8=2  V3=1
SELECT @proinfo = SubValue FROM sysdata WHERE SubName = 'proinfo'

--启用品牌 逻辑 部门 职员 按最后一次销售出库单的来 (现在是不要这个逻辑)
--SELECT TOP 1 @Dtypeid=ISNULL(DTypeId,''),@EtypeId=ISNULL(ETypeId,'') FROM billindex WHERE  ifcheck='t' AND draft=0 AND RedWord=0 AND billtype= 11 ORDER BY BillDate DESC

--总的往来余额 - 按品牌的一部分的余额= 没有启用品牌的往来余额
--没有启用品牌的往来余额结转到一个不存在的品牌ID 
DECLARE @otherBrandarId VARCHAR(50)
SELECT @otherBrandarId='-99999' --不再结转到 brandar_araptotal表 

CREATE TABLE #btype_araptotalysyf
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	YSYFtotal DECIMAL(24,10),--预收预付
	nYSYFtotal DECIMAL(24,10),--预收预付
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)

CREATE TABLE #btype_araptotalarap
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	ARAPTotal DECIMAL(24,10),--应收应付
	NARAPTotal DECIMAL(24,10),--应收应付
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)

--预收预付期初单据不能结算，转余额前先删除
DELETE FROM billindex WHERE isini=1 AND BillType IN(189,190)
UPDATE dbo.BillIndex SET ifYearBill=1 WHERE BillType IN (115,116,128,129) AND IsIni=1	--将期初类单据修改年结标志，用于区分结转的期初单据

--预收 预付
--IF EXISTS(SELECT TOP 1 1 FROM dbo.BType_ArApTotal WHERE (YSTotal<>0 OR nYSTotal<>0) OR (YFTotal<>0 OR nYFTotal<>0))
--BEGIN
	INSERT INTO #btype_araptotalysyf
	( 
			BTypeID ,
			STypeID ,
			DTypeID,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			@Dtypeid,
			@EtypeId,
			CID,
			SUM(YSTotal),
			SUM(nYSTotal),
			189,
			'数据结转时预收余额按非品牌转入',
			0	
	FROM
	(
		SELECT Btypeid,stypeid,cid,Total AS YSTotal,Ntotal AS NYSTotal FROM dbo.ListTable WHERE AtypeId=39
		UNION ALL
		SELECT Btypeid,stypeid,cid,YSTotal00,nYSTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				CID
	--HAVING SUM(YSTotal)<>0 
	--	AND SUM(nYSTotal)<>0
IF EXISTS(SELECT TOP 1 1 FROM dbo.BType_ArApTotal WHERE  YFTotal<>0 OR nYFTotal<>0)
BEGIN
	INSERT INTO #btype_araptotalysyf
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			@Dtypeid,
			@EtypeId,
			CID,
			SUM(YFTotal),
			SUM(nYFTotal),
			190,
			'数据结转时预付余额按非品牌转入',
			0	
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,cid,Total AS YFTotal,Ntotal AS NYFTotal FROM dbo.ListTable WHERE AtypeId=27
		UNION ALL
		SELECT Btypeid,stypeid,cid,YFTotal00,nYFTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				CID
	HAVING SUM(YFTotal)<>0 
		OR SUM(nYFTotal)<>0

END
--应收应付

--按余额转入期初，将btype_araptotal	应收应付余额转入期初单据

DELETE FROM dbo.BillIndex WHERE IsIni=1 AND BillType NOT IN (190,189,400,401,402,403)
INSERT INTO #btype_araptotalARAP
( 
		BTypeID ,
		STypeID ,
		DtypeId,
		EtypeId,
		CID ,
		ARAPTotal,
		NARAPTotal,
		billtype ,
		Comment ,
		sort
)
SELECT	BTypeID,
		STypeID,
		@DTypeId,
		@ETypeId,
		CID,
		SUM(ARTotal),
		SUM(nARTotal),
		'',--这里暂时不写 扣减了再写
		'数据结转时应收应付余额按非品牌转入',
		0			
FROM	--BType_ArApTotal 
(
	SELECT Btypeid,stypeid,cid,Total AS ARTotal,Ntotal AS NARTotal FROM dbo.ListTable WHERE AtypeId=33
	UNION ALL
	SELECT Btypeid,stypeid,cid,ARTotal00,nARTotal00 FROM IniBType_ArApTotal 
) a
GROUP BY	BTypeID,
			STypeID,
			CID
	--HAVING SUM(ARTotal)<>0 OR SUM(nARTotal)<>0
	
IF @yearendmode='1' AND EXISTS(SELECT TOP 1 1 FROM dbo.BType_ArApTotal WHERE  (APTotal<>0 AND nAPTotal<>0)) 
BEGIN	
	INSERT INTO #btype_araptotalARAP
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			ARAPTotal,
			NARAPTotal,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			@DTypeID,
			@EtypeId,
			CID,
			ABS(SUM(APTotal)),
			ABS(SUM(nAPTotal)),
			CASE WHEN SUM(APTotal)>0 
					THEN 128
				 ELSE 129
			END,
			'数据结转时应收应付余额按非品牌转入',
			0			
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,cid,Total AS APTotal,Ntotal AS NAPTotal FROM dbo.ListTable WHERE AtypeId=35
		UNION ALL
		SELECT Btypeid,stypeid,cid,APTotal00,nAPTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				CID
	HAVING SUM(APTotal)<>0 OR SUM(nAPTotal)<>0
END

----------品牌部分


CREATE TABLE #brandar_araptotalysyf
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	BrandarTypeID  varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	YSYFTotal DECIMAL(24,10),
	NYSYFTotal DECIMAL(24,10),
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)


CREATE TABLE #brandar_araptotalarap
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	BrandarTypeID  varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	ARAPTOTAL DECIMAL(24,10),
	nARAPTOTAL DECIMAL(24,10),
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)
--按余额转入期初，将brandar_ArApTotal	往来余额结转到下一年度的期初应收增加、减少单里
IF @yearendmode='1' AND EXISTS(SELECT TOP 1 1 FROM dbo.Brandar_ArApTotal WHERE YSTotal<>0 AND nYSTotal<>0)
BEGIN

	INSERT INTO #brandar_araptotalysyf
	( 
			BTypeID ,
			STypeID ,
			BrandarTypeID,
			DtypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			BrandarTypeID,
			ISNULL(@DTypeId,''),
			ISNULL(@ETypeId,''),
			CID,
			SUM(YSTotal),
			SUM(NYSTotal),
			189,
			'数据结转时预收余额按品牌转入',
			0			
	FROM dbo.Brandar_ArApTotal

	GROUP BY	BTypeID,
				STypeID,
				BrandarTypeID,
				CID
	HAVING SUM(YSTotal)<>0 OR SUM(NYSTotal)<>0
END 

--按余额转入期初，将brandar_ArApTotal	往来余额结转到下一年度的期初应收增加、减少单里
IF @yearendmode='1' AND EXISTS(SELECT TOP 1 1 FROM dbo.Brandar_ArApTotal WHERE ARTotal<>0 AND nARTotal<>0)
BEGIN
	--余额>0 生成应收增加  116
	--余额<0 生成应收减少 115

	INSERT INTO #brandar_araptotalarap
	( 
			BTypeID ,
			STypeID ,
			BrandarTypeID,
			DtypeId,
			EtypeId,
			CID ,
			ARAPTOTAL,
			nARAPTOTAL,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			BrandarTypeID,
			ISNULL(@DTypeId,''),
			ISNULL(@ETypeId,''),
			CID,
			SUM(ARTotal),
			SUM(nARTotal),
			CASE WHEN SUM(ARTotal)>0 
					THEN 116
				 ELSE 115
			END,
			'数据结转时应收余额按品牌转入',
			0			
	FROM dbo.Brandar_ArApTotal

	GROUP BY	BTypeID,
				STypeID,
				BrandarTypeID,
				CID
	HAVING SUM(ARTotal)<>0 OR SUM(nARTotal)<>0
END 
	DELETE #btype_araptotalysyf WHERE YSYFtotal=0 AND nYSYFtotal=0 AND billtype IN  (190)
	DELETE #btype_araptotalarap WHERE  ARAPTotal=0 AND NARAPTotal=0 AND billtype IN  (128,129)
	

	--扣减品牌预收
	UPDATE b
	SET	YSYFtotal=ISNULL(b.YSYFtotal,0)-ISNULL(br.YSYFTotal,0),
		nYSYFtotal=ISNULL(b.nYSYFtotal,0)-ISNULL(br.NYSYFTotal,0)
	FROM #btype_araptotalysyf b 
	LEFT JOIN 	(	SELECT  BTypeID,STypeID,EtypeId,cid,billtype,ISNULL(SUM(YSYFTotal),0) AS YSYFtotal,ISNULL(SUM(NYSYFTotal),0) AS nYSYFtotal
			FROM #brandar_araptotalysyf 
			GROUP BY  BTypeID,STypeID,EtypeId,cid,billtype)br 
	ON  b.BTypeID=br.BTypeID 
	AND b.STypeID=br.STypeID
	AND b.EtypeId=br.EtypeId
	AND b.CID=br.cid
	AND b.billtype=br.billtype
	

	
	--更改billtype
	--UPDATE #btype_araptotalysyf SET billtype =CASE WHEN ISNULL(YSYFtotal,0)>0 THEN 116 ELSE 115 END 
	--UPDATE #btype_araptotalysyf SET  YSYFtotal=ABS(YSYFtotal),nYSYFtotal=ABS(nYSYFtotal)				
	
	DELETE #btype_araptotalysyf WHERE YSYFtotal=0 AND nYSYFtotal=0 AND billtype IN  (189,190)
	

	--扣减品牌应收 
	UPDATE b 
	SET ARAPTotal=ISNULL(b.ARAPTotal,0)-ISNULL(br.ARAPTOTAL,0),
		NARAPTotal=ISNULL(b.nARAPTOTAL,0)-ISNULL(br.nARAPTOTAL,0)
	FROM #btype_araptotalarap b 
	LEFT JOIN (	SELECT  BTypeID,STypeID,EtypeId,cid,SUM(ARAPTotal) AS ARAPTotal,SUM(nARAPTOTAL) AS nARAPTOTAL
			FROM #brandar_araptotalarap
			GROUP BY  BTypeID,STypeID,EtypeId,cid)br 
	ON  b.BTypeID=br.BTypeID 
	AND b.STypeID=br.STypeID
	AND b.EtypeId=br.EtypeId
	AND b.CID=br.CID
	--AND b.billtype=br.billtype
	WHERE b.billtype NOT IN (128,129)
	

	
	--更改billtype
	UPDATE #btype_araptotalarap SET billtype =CASE WHEN ISNULL(ARAPTotal,0)>0  THEN 116 
												   WHEN ISNULL(ARAPTotal,0)<0  THEN 115
												   ELSE  billtype END
	WHERE  billtype NOT IN (128,129)
	UPDATE #btype_araptotalarap SET ARAPTotal =abs(ARAPTotal),NARAPTotal=ABS(NARAPTotal)
	UPDATE #brandar_araptotalarap SET ARAPTotal =abs(ARAPTotal),NARAPTotal=ABS(NARAPTotal)
	
	DELETE #btype_araptotalarap WHERE  ARAPTotal=0 AND NARAPTotal=0 --AND billtype IN  (115,116,128,129)
	
	--SELECT  * FROM #btype_araptotalysyf
	--SELECT  * FROM #brandar_araptotalysyf
	--SELECT  * FROM #btype_araptotalarap
	--SELECT  * FROM #brandar_araptotalarap
	--处理sortid
	UPDATE #btype_araptotalysyf
	SET sort=b.sort
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID)sort,
				STypeID,
				BTypeID,
				cid,
				billtype
		FROM	#btype_araptotalysyf
	)b 
	WHERE	#btype_araptotalysyf.billtype=b.billtype
			AND #btype_araptotalysyf.STypeID=b.STypeID
			AND #btype_araptotalysyf.BTypeID=b.BTypeID
			AND #btype_araptotalysyf.CID=b.cid
			
	UPDATE #btype_araptotalarap
	SET sort=b.sort
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID)sort,
				STypeID,
				BTypeID,
				cid,
				billtype
		FROM	#btype_araptotalarap
	)b 
	WHERE	#btype_araptotalarap.billtype=b.billtype
			AND #btype_araptotalarap.STypeID=b.STypeID
			AND #btype_araptotalarap.BTypeID=b.BTypeID
			AND #btype_araptotalarap.CID=b.cid
	
	DECLARE @maxysID INT=0,@maxarID INT=0
	
	SELECT @maxysID=ISNULL(MAX(sort),0) FROM #btype_araptotalysyf
	SELECT @maxarID=ISNULL(MAX(sort),0) FROM #btype_araptotalarap
	
	
	-------生单
	
	DECLARE @atypeid INT=1
	--品牌预收 
	IF EXISTS (SELECT  1 FROM #brandar_araptotalysyf)
	BEGIN 
		INSERT INTO [dbo].[BillIndex] 
		(	
			[IfYearBill],
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			1,
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype WHEN 189 THEN 'IniYskBill-' ELSE 'IniYfkBill-' END 
				+ CASE WHEN @proinfo=2 THEN STypeID +'-'ELSE '' END 
				+ CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			billtype,
			Comment,
			'',
			'',
			btypeid,
			@etypeid,
			'',
			'',
			'f',
			'',
			0,
			YSYFTotal,
			0,
			0,
			1,
			'',
			1,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			@dtypeid,
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			BTypeID,
			cid,	
			CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nYSYFTotal WHEN 0 THEN 0 ELSE   YSYFTotal/nYSYFTotal END) ELSE dbo.F_RoundExchangeRate(CASE YSYFTotal WHEN 0 THEN 0 ELSE  NYSYFTotal/YSYFTotal END) END,	
			NYSYFTotal,
			0,	
			0,	
			0,	
			(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
			1,
			0,
			1
		FROM 
		(SELECT	RANK() OVER
					(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID) +@maxysID as sort,
					STypeID,
					BTypeID,
					cid,
					billtype,
					Comment,
					SUM(YSYFTotal)AS YSYFTotal,
					SUM(NYSYFTotal) AS NYSYFTotal
			FROM	#brandar_araptotalysyf
			GROUP BY billtype,STypeID,BTypeID,cid,Comment
			) b
		WHERE YSYFTotal<>0 AND NYSYFTotal<>0

		

		SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
		INSERT INTO dbo.PreBill
				( BillNumberId ,
				  BillType ,
				  Comment ,
				  AtypeId ,
				  BrandarTypeId,
				  total ,
				  Stypeid ,
				  vipcardid ,
				  ntotal,
				  ShowOrder
				)
		SELECT	  b.BillNumberId ,
				  b.BillType ,
				  ba.comment ,
				  @atypeid ,
				  ba.BrandarTypeId,
				  ba.YSYFTotal ,
				  b.Stypeid ,
				  -1 ,
				 ba.NYSYFTotal ,
				  ROW_NUMBER() OVER(ORDER BY b.ID)
		FROM	#brandar_araptotalysyf ba
		inner JOIN dbo.BillIndex b ON ba.STypeID=b.Stypeid AND ba.cid=b.CID AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid  AND b.btypeid=ba.btypeid
		INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
		WHERE	b.BillType IN (189)
				AND b.IsIni=1
				AND b.ifYearBill=1
				AND b.Comment=ba.comment
			
		IF @@ERROR<>0
			RAISERROR('处理品牌预收余额失败！',16,1)  
	END 

	--非品牌预收,预付
	IF EXISTS (SELECT 1 FROM  #btype_araptotalysyf)
	BEGIN 
	
		INSERT INTO [dbo].[BillIndex] 
		(	
			[IfYearBill],
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			1,
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype WHEN 189 THEN 'IniYskBill-' ELSE 'IniYfkBill-' END 
				+ CASE WHEN @proinfo=2 THEN STypeID +'-'ELSE '' END 
				+ CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			billtype,
			Comment,
			'',
			'',
			btypeid,
			@etypeid,
			'',
			'',
			'f',
			'',
			0,
			YSYFTotal,
			0,
			0,
			1,
			'',
			1,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			@dtypeid,
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			BTypeID,
			cid,	
			CASE(SELECT BasisType FROM dbo.Ac_Currency WHERE CId=#btype_araptotalysyf.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nYSYFTotal WHEN 0 THEN 0 ELSE   YSYFTotal/nYSYFTotal END) ELSE dbo.F_RoundExchangeRate(CASE YSYFTotal WHEN 0 THEN 0 ELSE  NYSYFTotal/YSYFTotal END) END,	
			NYSYFTotal,
			0,	
			0,	
			0,	
			(SELECT AtypeId FROM dbo.BillAtype ba WHERE ba.StypeId=#btype_araptotalysyf.stypeid AND ba.BillTypeId=#btype_araptotalysyf.billtype ),
			1,
			0,
			1
		FROM #btype_araptotalysyf
		WHERE YSYFTotal<>0 AND NYSYFTotal<>0
		
		SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
		INSERT INTO dbo.PreBill
				( BillNumberId ,
				  BillType ,
				  Comment ,
				  AtypeId ,
				  BrandarTypeId,
				  total ,
				  Stypeid ,
				  vipcardid ,
				  ntotal,
				  ShowOrder
				)
		SELECT	  b.BillNumberId ,
				  b.BillType ,
				  ba.comment ,
				  @atypeid ,
				 CASE b.billtype WHEN 189  THEN @otherBrandarId 
								ELSE ''
								END ,
				  ba.YSYFTotal ,
				  b.Stypeid ,
				  -1 ,
				 ba.NYSYFTotal ,
				  ROW_NUMBER() OVER(ORDER BY b.ID)
		FROM	#btype_araptotalysyf ba
		INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid  AND b.btypeid=ba.btypeid
		INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
		WHERE	b.BillType IN (189,190)
				AND b.IsIni=1
				AND ifYearBill=1
				AND b.Comment=ba.comment

		
	IF @@ERROR<>0
		RAISERROR('处理非品牌预收余额失败！',16,1)  
	END 
		 
		 

	--品牌应收
	IF EXISTS (SELECT  1 FROM  #brandar_araptotalarap)
	BEGIN 

		DECLARE @newid varchar(9)
		SET @newid=LEFT(NEWID(),9)   --避免同一天连续年节产生的期初单据编号相等
		INSERT INTO [dbo].[BillIndex] 
		(	
			[IfYearBill],
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			1,
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype 
				WHEN '116' THEN 'IniYzBill-' 
				WHEN '115' THEN 'IniYjBill-' 
			END + @newid +
			CASE WHEN @proinfo=2 THEN STypeID + '-' ELSE '' END + CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			b.billtype,
			b.Comment,
			'',
			'',
			'',
			@etypeid,
			'',
			'',
			'f',
			'',
			0,
			b.ARAPTOTAL,
			0,
			0,
			1,
			'',
			1,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			@dtypeid,
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			'',
			cid,	
			CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nARAPTOTAL WHEN 0 THEN 0 ELSE   ARAPTOTAL/nARAPTOTAL END) ELSE dbo.F_RoundExchangeRate(CASE ARAPTOTAL WHEN 0 THEN 0 ELSE  nARAPTOTAL/ARAPTOTAL END) END,	
			b.nARAPTOTAL,
			0,	
			0,	
			0,	
			(SELECT ba.AtypeId from dbo.BillAtype ba INNER JOIN SType s ON ba.StypeId = s.VerifyID  WHERE b.StypeId=s.typeid AND ba.BillTypeId=b.billtype ),
			1,
			0,
			1
		FROM
			(SELECT	RANK() OVER
					(PARTITION BY billtype ORDER BY STypeID,CID) +@maxarID as sort,
					STypeID,
					cid,
					billtype,
					Comment,
					SUM(ARAPTOTAL)AS ARAPTOTAL,
					SUM(nARAPTOTAL) AS nARAPTOTAL
			FROM	#brandar_araptotalarap
			GROUP BY billtype,STypeID,cid,Comment
		)b	

	INSERT INTO dbo.AdDebtBill
	( 
			  BillNumberId ,
	          Comment ,
	          BtypeId ,
	          BrandarTypeId,
	          total ,
	          CompleteTotal ,
	          Stypeid ,
	          NTotal ,
	          NCompleteTotal,
	          ShowOrder,
	          AlertDay
	)
	SELECT	  b.BillNumberId,
			  ba.Comment,
			  ba.btypeid,
			  ba.BrandarTypeID,
			  ba.ARAPTOTAL,
			  0,
			  ba.stypeid,
			  ba.nARAPTOTAL,
			  0,
			  ROW_NUMBER() OVER(ORDER BY b.ID),
			  ISNULL(bt.ARLimitTime,9999)
	FROM	#brandar_araptotalarap ba
	INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid 
	INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
	WHERE	b.BillType IN (116,115)
			AND b.IsIni=1
			AND ifYearBill=1
			AND b.Comment=ba.comment
				
	IF @@ERROR<>0
		RAISERROR('处理品牌应收余额失败！',16,1)     
	
			
	END  		
		
	--非品牌应收应付
	IF EXISTS (SELECT 1 FROM #btype_araptotalarap)	
	BEGIN
	
		DECLARE @newid_1 varchar(9)
		SET @newid_1=LEFT(NEWID(),9)   --避免同一天连续年节产生的期初单据编号相等
		
		INSERT INTO [dbo].[BillIndex] 
		(	
			[IfYearBill],
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			1,
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype 
				WHEN '116' THEN 'IniYzBill-' 
				WHEN '115' THEN 'IniYjBill-' 
				WHEN '128' THEN 'IniFzBill-'
				WHEN '129' THEN 'IniFjBill-'
			END + @newid_1 +
			CASE WHEN @proinfo=2 THEN STypeID + '-' ELSE '' END + CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			billtype,
			Comment,
			'',
			'',
			'',
			@etypeid,
			'',
			'',
			'f',
			'',
			0,
			ARAPTotal,
			0,
			0,
			1,
			'',
			1,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			@dtypeid,
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			'',
			cid,	
			CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE NARAPTotal WHEN 0 THEN 0 ELSE   ARAPTotal/NARAPTotal END) ELSE dbo.F_RoundExchangeRate(CASE ARAPTotal WHEN 0 THEN 0 ELSE  NARAPTotal/ARAPTotal END) END,	
			NARAPTotal,
			0,	
			0,	
			0,	
			(SELECT ba.AtypeId from dbo.BillAtype ba INNER JOIN SType s ON ba.StypeId = s.VerifyID  WHERE b.StypeId=s.typeid AND ba.BillTypeId=b.billtype ),
			1,
			0,
			1
		FROM
		(
			SELECT	RANK() OVER
					(PARTITION BY billtype ORDER BY stypeid,DTypeId,etypeid,cid) sort,
					Stypeid,	
					DTypeId,
					etypeid,
					CID,
					BillType,
					Comment,
					SUM(ARAPTotal) AS ARAPTotal,
					SUM(NARAPTotal) AS NARAPTotal
			FROM #btype_araptotalarap
			GROUP BY Stypeid,DTypeId,etypeid,CID,BillType,Comment
		)b	


		INSERT INTO dbo.AdDebtBill
		( 
				  BillNumberId ,
				  Comment ,
				  BtypeId ,
				  total ,
				  CompleteTotal ,
				  Stypeid ,
				  NTotal ,
				  NCompleteTotal,
				  ShowOrder,
				  AlertDay,
				  BrandarTypeID
		)
		SELECT	  b.BillNumberId,
				  ba.comment,
				  ba.btypeid,
				  ba.ARAPTotal,
				  0,
				  ba.stypeid,
				  ba.NARAPTotal,
				  0,
				  ROW_NUMBER() OVER(ORDER BY b.ID),
				  CASE
					WHEN b.BillType IN (115,116) THEN ISNULL(bt.ARLimitTime,9999)
					WHEN b.BillType IN (128,129) THEN ISNULL(bt.paymentLTime,9999)
					ELSE 9999
				  END,
				  CASE
					WHEN b.BillType IN (115,116) THEN '-99999'
					WHEN b.BillType IN (128,129) THEN ''
					ELSE ''
				  END  
		FROM	#btype_araptotalarap ba
		INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid 
		INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
		WHERE	b.BillType IN (116,115,128,129)
				AND b.IsIni=1
				AND ifYearBill=1
				AND b.Comment=ba.comment
				
				
		IF @@ERROR<>0
			RAISERROR('处理非品牌应收应付余额失败！',16,1)      
	
	END 	

DROP TABLE #brandar_araptotalysyf ,#brandar_araptotalarap,#btype_araptotalysyf,#btype_araptotalarap


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

--====================================================================================
-----------------功能：将品牌往来余额应收转成期初应收增加 减少单据 
--====================================================================================

CREATE    PROC Gp_BrandarYsyfToInibill_DateTime
(
	@yearendmode			CHAR(1) = '1'	,	-- 1 - 按余额转期初(arap_total)；0 - 按单据转期初(AccountCredence)
	@yearendDatetime        VARCHAR(20)			--   -年结存的日期		
)	

--@encode$--
AS
SET NOCOUNT ON

IF @yearendmode=0
RETURN ;
DECLARE @Dtypeid VARCHAR(50)='',@EtypeId VARCHAR(50)=''


DECLARE @newFPeriod	INT,
		@newFYear	INT,
		@BeginDate  DATETIME

SELECT TOP 1 
	@newFPeriod=FPeriod,
	@newFYear=FYear 
FROM dbo.Ac_Period 
WHERE FBegin = @yearendDatetime

DECLARE @startdate DATETIME
SET @startdate=DATEADD(day,-1,@yearendDatetime)
--SELECT @startdate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=@newFPeriod AND FYear=@newFYear


DECLARE @proinfo INT --A8=2  V3=1
SELECT @proinfo = SubValue FROM sysdata WHERE SubName = 'proinfo'

--总的往来余额 - 按品牌的一部分的余额= 没有启用品牌的往来余额
--没有启用品牌的往来余额结转到一个不存在的品牌ID 
DECLARE @otherBrandarId VARCHAR(50)
SELECT @otherBrandarId='-99999' --不再结转到 brandar_araptotal表 

--指定时间内的品牌应收余额
CREATE TABLE #BrandarARAPTotal
(
	BrandarTypeID	VARCHAR(50),
	stypeid		VARCHAR(50),
	btypeid		VARCHAR(50),
	cid			INT,
	ARTotal		NUMERIC(24, 10) ,
	YSTotal		NUMERIC(24, 10) ,
	nARTotal	NUMERIC(24, 10),
	nYSTotal	NUMERIC(24, 10) ,
	Total		NUMERIC(24, 10) ,
	NTotal		NUMERIC(24, 10),
	YSTotal00	NUMERIC(24,10),
	NYSTotal00	NUMERIC(24,10),
	ARTotal00	NUMERIC(24,10) ,
	NARTotal00	NUMERIC(24,10)
)

EXEC GP_ReCalBrandarArAp_YearProcDateTime @yearendDatetime

CREATE TABLE #btype_araptotalysyf
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	YSYFtotal DECIMAL(24,10),--预收预付
	nYSYFtotal DECIMAL(24,10),--预收预付
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)

CREATE TABLE #btype_araptotalarap
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	ARAPTotal DECIMAL(24,10),--应收应付
	NARAPTotal DECIMAL(24,10),--应收应付
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)

--预收预付期初单据不能结算，转余额前先删除
DELETE FROM billindex WHERE isini=1 AND BillType IN(189,190)
UPDATE dbo.BillIndex SET ifYearBill=1 WHERE BillType IN (115,116,128,129) AND IsIni=1 and billdate <@yearendDatetime --将期初类单据修改年结标志，用于区分结转的期初单据

------------------------------------------预收 预付 开始-------------------------------------------------------------------------------

	INSERT INTO #btype_araptotalysyf
	( 
			BTypeID ,
			STypeID ,
			DTypeID,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			@Dtypeid,
			@EtypeId,
			CID,
			SUM(YSTotal),
			SUM(nYSTotal),
			189,
			'数据结转时预收余额按非品牌转入',
			0	
	FROM
	(
		SELECT Btypeid,stypeid,cid,Total AS YSTotal,Ntotal AS NYSTotal FROM dbo.ListTable WHERE AtypeId=39 and billdate <@yearendDatetime
		UNION ALL
		SELECT Btypeid,stypeid,cid,YSTotal00,nYSTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				CID
	--HAVING SUM(YSTotal)<>0 
	--	AND SUM(nYSTotal)<>0

	INSERT INTO #btype_araptotalysyf
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			@Dtypeid,
			@EtypeId,
			CID,
			SUM(YFTotal),
			SUM(nYFTotal),
			190,
			'数据结转时预付余额按非品牌转入',
			0	
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,cid,Total AS YFTotal,Ntotal AS NYFTotal FROM dbo.ListTable WHERE AtypeId=27 and billdate <@yearendDatetime
		UNION ALL
		SELECT Btypeid,stypeid,cid,YFTotal00,nYFTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				CID
	HAVING SUM(YFTotal)<>0 
		OR SUM(nYFTotal)<>0


------------------------------------------预收 预付 结束-------------------------------------------------------------------------------
------------------------------------------应收应付  开始-------------------------------------------------------------------------------
--按余额转入期初，将btype_araptotal	应收应付余额转入期初单据

DELETE FROM dbo.BillIndex WHERE IsIni=1 AND BillType NOT IN (190,189,400,401,402,403)
INSERT INTO #btype_araptotalARAP
( 
		BTypeID ,
		STypeID ,
		DtypeId,
		EtypeId,
		CID ,
		ARAPTotal,
		NARAPTotal,
		billtype ,
		Comment ,
		sort
)
SELECT	BTypeID,
		STypeID,
		@DTypeId,
		@ETypeId,
		CID,
		SUM(ARTotal),
		SUM(nARTotal),
		'',--这里暂时不写 扣减了再写
		'数据结转时应收应付余额按非品牌转入',
		0			
FROM	--BType_ArApTotal 
(
	SELECT Btypeid,stypeid,cid,Total AS ARTotal,Ntotal AS NARTotal FROM dbo.ListTable WHERE AtypeId=33 and billdate <@yearendDatetime
	UNION ALL
	SELECT Btypeid,stypeid,cid,ARTotal00,nARTotal00 FROM IniBType_ArApTotal 
) a
GROUP BY	BTypeID,
			STypeID,
			CID
	--HAVING SUM(ARTotal)<>0 OR SUM(nARTotal)<>0
	

	INSERT INTO #btype_araptotalARAP
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			ARAPTotal,
			NARAPTotal,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			@DTypeID,
			@EtypeId,
			CID,
			ABS(SUM(APTotal)),
			ABS(SUM(nAPTotal)),
			CASE WHEN SUM(APTotal)>0 
					THEN 128
				 ELSE 129
			END,
			'数据结转时应收应付余额按非品牌转入',
			0			
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,cid,Total AS APTotal,Ntotal AS NAPTotal FROM dbo.ListTable WHERE AtypeId=35 and billdate <@yearendDatetime
		UNION ALL
		SELECT Btypeid,stypeid,cid,APTotal00,nAPTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				CID
	HAVING SUM(APTotal)<>0 OR SUM(nAPTotal)<>0


----------品牌部分


CREATE TABLE #brandar_araptotalysyf
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	BrandarTypeID  varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	YSYFTotal DECIMAL(24,10),
	NYSYFTotal DECIMAL(24,10),
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)


CREATE TABLE #brandar_araptotalarap
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	BrandarTypeID  varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	ARAPTOTAL DECIMAL(24,10),
	nARAPTOTAL DECIMAL(24,10),
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)
--按余额转入期初，将brandar_ArApTotal	往来余额结转到下一年度的期初应收增加、减少单里
IF @yearendmode='1' AND EXISTS(SELECT TOP 1 1 FROM #BrandarArApTotal WHERE YSTotal<>0 AND nYSTotal<>0)
BEGIN

	INSERT INTO #brandar_araptotalysyf
	( 
			BTypeID ,
			STypeID ,
			BrandarTypeID,
			DtypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			BrandarTypeID,
			ISNULL(@DTypeId,''),
			ISNULL(@ETypeId,''),
			CID,
			SUM(YSTotal+YStotal00),
			SUM(NYSTotal+NYSTOTAL00),
			189,
			'数据结转时预收余额按品牌转入',
			0			
	FROM #BrandarArApTotal 

	GROUP BY	BTypeID,
				STypeID,
				BrandarTypeID,
				CID
	HAVING SUM(YSTotal+YStotal00)<>0 OR SUM(NYSTotal+NYSTOTAL00)<>0
END 

--按余额转入期初，将brandar_ArApTotal	往来余额结转到下一年度的期初应收增加、减少单里
IF @yearendmode='1' AND EXISTS(SELECT TOP 1 1 FROM dbo.#BrandarArApTotal WHERE (ARTotal+ARTotal00)<>0 AND (nARTotal+nARTotal00)<>0)
BEGIN
	--余额>0 生成应收增加  116
	--余额<0 生成应收减少 115

	INSERT INTO #brandar_araptotalarap
	( 
			BTypeID ,
			STypeID ,
			BrandarTypeID,
			DtypeId,
			EtypeId,
			CID ,
			ARAPTOTAL,
			nARAPTOTAL,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			BrandarTypeID,
			ISNULL(@DTypeId,''),
			ISNULL(@ETypeId,''),
			CID,
			SUM(ARTotal+ARTOTAL00),
			SUM(nARTotal+NARTOTAL00),
			CASE WHEN SUM(ARTotal+ARTOTAL00)>0 
					THEN 116
				 ELSE 115
			END,
			'数据结转时应收余额按品牌转入',
			0			
	FROM #BrandarArApTotal

	GROUP BY	BTypeID,
				STypeID,
				BrandarTypeID,
				CID
	HAVING SUM(ARTotal+ARTOTAL00)<>0 OR SUM(nARTotal+NARTOTAL00)<>0
END 
	DELETE #btype_araptotalysyf WHERE YSYFtotal=0 AND nYSYFtotal=0 AND billtype IN  (190)
	DELETE #btype_araptotalarap WHERE  ARAPTotal=0 AND NARAPTotal=0 AND billtype IN  (128,129)
	

	--扣减品牌预收
	UPDATE b
	SET	YSYFtotal=ISNULL(b.YSYFtotal,0)-ISNULL(br.YSYFTotal,0),
		nYSYFtotal=ISNULL(b.nYSYFtotal,0)-ISNULL(br.NYSYFTotal,0)
	FROM #btype_araptotalysyf b 
	LEFT JOIN 	(	SELECT  BTypeID,STypeID,EtypeId,cid,billtype,ISNULL(SUM(YSYFTotal),0) AS YSYFtotal,ISNULL(SUM(NYSYFTotal),0) AS nYSYFtotal
			FROM #brandar_araptotalysyf 
			GROUP BY  BTypeID,STypeID,EtypeId,cid,billtype)br 
	ON  b.BTypeID=br.BTypeID 
	AND b.STypeID=br.STypeID
	AND b.EtypeId=br.EtypeId
	AND b.CID=br.cid
	AND b.billtype=br.billtype
	

	
	--更改billtype
	--UPDATE #btype_araptotalysyf SET billtype =CASE WHEN ISNULL(YSYFtotal,0)>0 THEN 116 ELSE 115 END 
	--UPDATE #btype_araptotalysyf SET  YSYFtotal=ABS(YSYFtotal),nYSYFtotal=ABS(nYSYFtotal)				
	
	DELETE #btype_araptotalysyf WHERE YSYFtotal=0 AND nYSYFtotal=0 AND billtype IN  (189,190)
	

	--扣减品牌应收 
	UPDATE b 
	SET ARAPTotal=ISNULL(b.ARAPTotal,0)-ISNULL(br.ARAPTOTAL,0),
		NARAPTotal=ISNULL(b.nARAPTOTAL,0)-ISNULL(br.nARAPTOTAL,0)
	FROM #btype_araptotalarap b 
	LEFT JOIN (	SELECT  BTypeID,STypeID,EtypeId,cid,SUM(ARAPTotal) AS ARAPTotal,SUM(nARAPTOTAL) AS nARAPTOTAL
			FROM #brandar_araptotalarap
			GROUP BY  BTypeID,STypeID,EtypeId,cid)br 
	ON  b.BTypeID=br.BTypeID 
	AND b.STypeID=br.STypeID
	AND b.EtypeId=br.EtypeId
	AND b.CID=br.CID
	--AND b.billtype=br.billtype
	WHERE b.billtype NOT IN (128,129)
	

	
	--更改billtype
	UPDATE #btype_araptotalarap SET billtype =CASE WHEN ISNULL(ARAPTotal,0)>0  THEN 116 
												   WHEN ISNULL(ARAPTotal,0)<0  THEN 115
												   ELSE  billtype END
	WHERE  billtype NOT IN (128,129)
	UPDATE #btype_araptotalarap SET ARAPTotal =abs(ARAPTotal),NARAPTotal=ABS(NARAPTotal)
	UPDATE #brandar_araptotalarap SET ARAPTotal =abs(ARAPTotal),NARAPTotal=ABS(NARAPTotal)
	
	DELETE #btype_araptotalarap WHERE  ARAPTotal=0 AND NARAPTotal=0 --AND billtype IN  (115,116,128,129)
	
	--SELECT  * FROM #btype_araptotalysyf
	--SELECT  * FROM #brandar_araptotalysyf
	--SELECT  * FROM #btype_araptotalarap
	--SELECT  * FROM #brandar_araptotalarap
	--处理sortid
	UPDATE #btype_araptotalysyf
	SET sort=b.sort
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID)sort,
				STypeID,
				BTypeID,
				cid,
				billtype
		FROM	#btype_araptotalysyf
	)b 
	WHERE	#btype_araptotalysyf.billtype=b.billtype
			AND #btype_araptotalysyf.STypeID=b.STypeID
			AND #btype_araptotalysyf.BTypeID=b.BTypeID
			AND #btype_araptotalysyf.CID=b.cid
			
	UPDATE #btype_araptotalarap
	SET sort=b.sort
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID)sort,
				STypeID,
				BTypeID,
				cid,
				billtype
		FROM	#btype_araptotalarap
	)b 
	WHERE	#btype_araptotalarap.billtype=b.billtype
			AND #btype_araptotalarap.STypeID=b.STypeID
			AND #btype_araptotalarap.BTypeID=b.BTypeID
			AND #btype_araptotalarap.CID=b.cid
	
	DECLARE @maxysID INT=0,@maxarID INT=0
	
	SELECT @maxysID=ISNULL(MAX(sort),0) FROM #btype_araptotalysyf
	SELECT @maxarID=ISNULL(MAX(sort),0) FROM #btype_araptotalarap
	
	
	-------生单
	
	DECLARE @atypeid INT=1
	--品牌预收 
	IF EXISTS (SELECT  1 FROM #brandar_araptotalysyf)
	BEGIN 
		INSERT INTO [dbo].[BillIndex] 
		(	
			[IfYearBill],
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			1,
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype WHEN 189 THEN 'IniYskBill-' ELSE 'IniYfkBill-' END 
				+ CASE WHEN @proinfo=2 THEN STypeID +'-'ELSE '' END 
				+ CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			billtype,
			Comment,
			'',
			'',
			btypeid,
			@etypeid,
			'',
			'',
			'f',
			'',
			0,
			YSYFTotal,
			0,
			0,
			1,
			'',
			1,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			@dtypeid,
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			BTypeID,
			cid,	
			CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nYSYFTotal WHEN 0 THEN 0 ELSE   YSYFTotal/nYSYFTotal END) ELSE dbo.F_RoundExchangeRate(CASE YSYFTotal WHEN 0 THEN 0 ELSE  NYSYFTotal/YSYFTotal END) END,	
			NYSYFTotal,
			0,	
			0,	
			0,	
			(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
			1,
			0,
			1
		FROM 
		(SELECT	RANK() OVER
					(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID) +@maxysID as sort,
					STypeID,
					BTypeID,
					cid,
					billtype,
					Comment,
					SUM(YSYFTotal)AS YSYFTotal,
					SUM(NYSYFTotal) AS NYSYFTotal
			FROM	#brandar_araptotalysyf
			GROUP BY billtype,STypeID,BTypeID,cid,Comment
			) b
		WHERE YSYFTotal<>0 AND NYSYFTotal<>0

		

		SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
		INSERT INTO dbo.PreBill
				( BillNumberId ,
				  BillType ,
				  Comment ,
				  AtypeId ,
				  BrandarTypeId,
				  total ,
				  Stypeid ,
				  vipcardid ,
				  ntotal,
				  ShowOrder
				)
		SELECT	  b.BillNumberId ,
				  b.BillType ,
				  ba.comment ,
				  @atypeid ,
				  ba.BrandarTypeId,
				  ba.YSYFTotal ,
				  b.Stypeid ,
				  -1 ,
				 ba.NYSYFTotal ,
				  ROW_NUMBER() OVER(ORDER BY b.ID)
		FROM	#brandar_araptotalysyf ba
		inner JOIN dbo.BillIndex b ON ba.STypeID=b.Stypeid AND ba.cid=b.CID AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid  AND b.btypeid=ba.btypeid
		INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
		WHERE	b.BillType IN (189)
				AND b.IsIni=1
				AND b.ifYearBill=1
				AND b.Comment=ba.comment
			
		IF @@ERROR<>0
			RAISERROR('处理品牌预收余额失败！',16,1)  
	END 

	--非品牌预收,预付
	IF EXISTS (SELECT 1 FROM  #btype_araptotalysyf)
	BEGIN 
	
		INSERT INTO [dbo].[BillIndex] 
		(	
			[IfYearBill],
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			1,
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype WHEN 189 THEN 'IniYskBill-' ELSE 'IniYfkBill-' END 
				+ CASE WHEN @proinfo=2 THEN STypeID +'-'ELSE '' END 
				+ CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			billtype,
			Comment,
			'',
			'',
			btypeid,
			@etypeid,
			'',
			'',
			'f',
			'',
			0,
			YSYFTotal,
			0,
			0,
			1,
			'',
			1,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			@dtypeid,
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			BTypeID,
			cid,	
			CASE(SELECT BasisType FROM dbo.Ac_Currency WHERE CId=#btype_araptotalysyf.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nYSYFTotal WHEN 0 THEN 0 ELSE   YSYFTotal/nYSYFTotal END) ELSE dbo.F_RoundExchangeRate(CASE YSYFTotal WHEN 0 THEN 0 ELSE  NYSYFTotal/YSYFTotal END) END,	
			NYSYFTotal,
			0,	
			0,	
			0,	
			(SELECT AtypeId FROM dbo.BillAtype ba WHERE ba.StypeId=#btype_araptotalysyf.stypeid AND ba.BillTypeId=#btype_araptotalysyf.billtype ),
			1,
			0,
			1
		FROM #btype_araptotalysyf
		WHERE YSYFTotal<>0 AND NYSYFTotal<>0
		
		SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
		INSERT INTO dbo.PreBill
				( BillNumberId ,
				  BillType ,
				  Comment ,
				  AtypeId ,
				  BrandarTypeId,
				  total ,
				  Stypeid ,
				  vipcardid ,
				  ntotal,
				  ShowOrder
				)
		SELECT	  b.BillNumberId ,
				  b.BillType ,
				  ba.comment ,
				  @atypeid ,
				 CASE b.billtype WHEN 189  THEN @otherBrandarId 
								ELSE ''
								END ,
				  ba.YSYFTotal ,
				  b.Stypeid ,
				  -1 ,
				 ba.NYSYFTotal ,
				  ROW_NUMBER() OVER(ORDER BY b.ID)
		FROM	#btype_araptotalysyf ba
		INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid  AND b.btypeid=ba.btypeid
		INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
		WHERE	b.BillType IN (189,190)
				AND b.IsIni=1
				AND ifYearBill=1
				AND b.Comment=ba.comment

		
	IF @@ERROR<>0
		RAISERROR('处理非品牌预收余额失败！',16,1)  
	END 
		 
		 

	--品牌应收
	IF EXISTS (SELECT  1 FROM  #brandar_araptotalarap)
	BEGIN 

		DECLARE @newid varchar(9)
		SET @newid=LEFT(NEWID(),9)   --避免同一天连续年节产生的期初单据编号相等
		INSERT INTO [dbo].[BillIndex] 
		(	
			[IfYearBill],
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			1,
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype 
				WHEN '116' THEN 'IniYzBill-' 
				WHEN '115' THEN 'IniYjBill-' 
			END + @newid +
			CASE WHEN @proinfo=2 THEN STypeID + '-' ELSE '' END + CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			b.billtype,
			b.Comment,
			'',
			'',
			'',
			@etypeid,
			'',
			'',
			'f',
			'',
			0,
			b.ARAPTOTAL,
			0,
			0,
			1,
			'',
			1,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			@dtypeid,
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			'',
			cid,	
			CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nARAPTOTAL WHEN 0 THEN 0 ELSE   ARAPTOTAL/nARAPTOTAL END) ELSE dbo.F_RoundExchangeRate(CASE ARAPTOTAL WHEN 0 THEN 0 ELSE  nARAPTOTAL/ARAPTOTAL END) END,	
			b.nARAPTOTAL,
			0,	
			0,	
			0,	
			(SELECT ba.AtypeId from dbo.BillAtype ba INNER JOIN SType s ON ba.StypeId = s.VerifyID  WHERE b.StypeId=s.typeid AND ba.BillTypeId=b.billtype ),
			1,
			0,
			1
		FROM
			(SELECT	RANK() OVER
					(PARTITION BY billtype ORDER BY STypeID,CID) +@maxarID as sort,
					STypeID,
					cid,
					billtype,
					Comment,
					SUM(ARAPTOTAL)AS ARAPTOTAL,
					SUM(nARAPTOTAL) AS nARAPTOTAL
			FROM	#brandar_araptotalarap
			GROUP BY billtype,STypeID,cid,Comment
		)b	

	INSERT INTO dbo.AdDebtBill
	( 
			  BillNumberId ,
	          Comment ,
	          BtypeId ,
	          BrandarTypeId,
	          total ,
	          CompleteTotal ,
	          Stypeid ,
	          NTotal ,
	          NCompleteTotal,
	          ShowOrder,
	          AlertDay
	)
	SELECT	  b.BillNumberId,
			  ba.Comment,
			  ba.btypeid,
			  ba.BrandarTypeID,
			  ba.ARAPTOTAL,
			  0,
			  ba.stypeid,
			  ba.nARAPTOTAL,
			  0,
			  ROW_NUMBER() OVER(ORDER BY b.ID),
			  ISNULL(bt.ARLimitTime,9999)
	FROM	#brandar_araptotalarap ba
	INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid 
	INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
	WHERE	b.BillType IN (116,115)
			AND b.IsIni=1
			AND ifYearBill=1
			AND b.Comment=ba.comment
				
	IF @@ERROR<>0
		RAISERROR('处理品牌应收余额失败！',16,1)     
	
			
	END  		
		
	--非品牌应收应付
	IF EXISTS (SELECT 1 FROM #btype_araptotalarap)	
	BEGIN
	
		DECLARE @newid_1 varchar(9)
		SET @newid_1=LEFT(NEWID(),9)   --避免同一天连续年节产生的期初单据编号相等
		
		INSERT INTO [dbo].[BillIndex] 
		(	
			[IfYearBill],
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			1,
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype 
				WHEN '116' THEN 'IniYzBill-' 
				WHEN '115' THEN 'IniYjBill-' 
				WHEN '128' THEN 'IniFzBill-'
				WHEN '129' THEN 'IniFjBill-'
			END + @newid_1 +
			CASE WHEN @proinfo=2 THEN STypeID + '-' ELSE '' END + CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			billtype,
			Comment,
			'',
			'',
			'',
			@etypeid,
			'',
			'',
			'f',
			'',
			0,
			ARAPTotal,
			0,
			0,
			1,
			'',
			1,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			@dtypeid,
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			'',
			cid,	
			CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE NARAPTotal WHEN 0 THEN 0 ELSE   ARAPTotal/NARAPTotal END) ELSE dbo.F_RoundExchangeRate(CASE ARAPTotal WHEN 0 THEN 0 ELSE  NARAPTotal/ARAPTotal END) END,	
			NARAPTotal,
			0,	
			0,	
			0,	
			(SELECT ba.AtypeId from dbo.BillAtype ba INNER JOIN SType s ON ba.StypeId = s.VerifyID  WHERE b.StypeId=s.typeid AND ba.BillTypeId=b.billtype ),
			1,
			0,
			1
		FROM
		(
			SELECT	RANK() OVER
					(PARTITION BY billtype ORDER BY stypeid,DTypeId,etypeid,cid) sort,
					Stypeid,	
					DTypeId,
					etypeid,
					CID,
					BillType,
					Comment,
					SUM(ARAPTotal) AS ARAPTotal,
					SUM(NARAPTotal) AS NARAPTotal
			FROM #btype_araptotalarap
			GROUP BY Stypeid,DTypeId,etypeid,CID,BillType,Comment
		)b	


		INSERT INTO dbo.AdDebtBill
		( 
				  BillNumberId ,
				  Comment ,
				  BtypeId ,
				  total ,
				  CompleteTotal ,
				  Stypeid ,
				  NTotal ,
				  NCompleteTotal,
				  ShowOrder,
				  AlertDay,
				  BrandarTypeID
		)
		SELECT	  b.BillNumberId,
				  ba.comment,
				  ba.btypeid,
				  ba.ARAPTotal,
				  0,
				  ba.stypeid,
				  ba.NARAPTotal,
				  0,
				  ROW_NUMBER() OVER(ORDER BY b.ID),
				  CASE
					WHEN b.BillType IN (115,116) THEN ISNULL(bt.ARLimitTime,9999)
					WHEN b.BillType IN (128,129) THEN ISNULL(bt.paymentLTime,9999)
					ELSE 9999
				  END,
				  CASE
					WHEN b.BillType IN (115,116) THEN '-99999'
					WHEN b.BillType IN (128,129) THEN ''
					ELSE ''
				  END  
		FROM	#btype_araptotalarap ba
		INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid 
		INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
		WHERE	b.BillType IN (116,115,128,129)
				AND b.IsIni=1
				AND ifYearBill=1
				AND b.Comment=ba.comment
				
				
		IF @@ERROR<>0
			RAISERROR('处理非品牌应收应付余额失败！',16,1)      
	
	END 	
	
	
	--修改品牌余额(#BrandarARAPTotal 期初+余额 转入 期初  brandar_ArApTotal余额值不变)
	
	UPDATE	a 
	SET		a.ARTotal00= b.ARTotal00+ISNULL(b.ARTotal,0),
			a.YSTotal00= b.YSTotal00+ISNULL(b.YSTotal,0),
			a.nARTotal00= b.nARTotal00+ISNULL(b.nARTotal,0),
			a.nYSTotal00= b.nYSTotal00+ISNULL(b.nYSTotal,0)
		
	FROM  dbo.brandar_ArApTotal a  JOIN  #BrandarARAPTotal b
	ON a.stypeid=b.stypeid AND a.btypeid=b.btypeid AND a.CID=b.cid and a.BrandarTypeID=b.BrandarTypeID
   --没有的则插入数据
	INSERT INTO brandar_ArApTotal (
		BTypeID,
		STypeID,
		BrandarTypeID,
		CID,
		ARTotal,
		YSTotal,
		ARTotal00,
		YSTotal00,
		nARTotal,
		nYSTotal,
		nARTotal00,
		nYSTotal00

	) SELECT 
		b.btypeId,
		b.stypeid,
		b.BrandarTypeID,
		b.cid,
		0,
		0,
		b.ARTotal00+b.ARTotal,
		b.YSTotal00+b.YSTotal,
		0,
		0,
		b.nARTotal00+ b.nARTotal,
		b.nYSTotal00+ b.nYSTotal
		
	FROM #BrandarARAPTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM brandar_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid AND a.BrandarTypeID=b.BrandarTypeID)

	DELETE FROM dbo.brandar_ArApTotal	 
	WHERE (ISNULL(YSTotal00,0)=0 OR ISNULL(nYSTotal00,0)=0)
	 AND  (ISNULL(ARTotal00,0)=0 OR ISNULL(nARTotal00,0)=0)	


DROP TABLE #brandar_araptotalysyf ,#brandar_araptotalarap,#btype_araptotalysyf,#btype_araptotalarap,#BrandarARAPTotal


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_BrandBtypeCreditSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_BrandBtypeCreditSet
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		
-- Create date: 2019-05-31
-- Description: 按品牌设置往来单位信用额度
-- =============================================
CREATE PROCEDURE Gp_BrandBtypeCreditSet
(
	@STypeId		VARCHAR(1000)='',
	@BTypeId		VARCHAR(MAX)='',
	@BrandTypeId	VARCHAR(MAX)='',
	@Credit			NUMERIC(24, 10) ,
	@IsCredit		INT=1,
	@OperateSign	VARCHAR(10)='',
	@OperatorId		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE
	@ErrorCount			INT=0,
	@Sql				NVARCHAR(MAX)='',
	@IsUseBrandarType	INT=0,--是否启用品牌
	@ProInfo			INT=0--系统版本

SELECT @ProInfo=SubValue FROM SysData WHERE SubName='ProInfo'

IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND SubValue=1)
	AND EXISTS(SELECT SubValue FROM SysData WHERE SubName='brandarcontrollineofcredit' AND SubValue=0)
	SET @IsUseBrandarType=1
	
IF(@ProInfo<>2)
	SET @STypeId='00001'

--往来单位
CREATE TABLE #BType(TypeId VARCHAR(50),FullName VARCHAR(200),SonNum INT)

IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value=1)-- 客户供货商统一  
	BEGIN
		INSERT INTO #BType(TypeId,FullName,SonNum)
		SELECT B.typeId,B.FullName,B.sonnum
		FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId  AND B.sonnum=0 AND @IsUseBrandarType=1 AND B.IsUseBrandarType=1
	END
ELSE --不统一，只需客户
	BEGIN
		INSERT INTO #BType(TypeId,FullName,SonNum)
		SELECT B.typeId,B.FullName,B.sonnum
		FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND b.typeId LIKE '00001%'  AND B.sonnum=0 AND @IsUseBrandarType=1 AND B.IsUseBrandarType=1
	END

--分支机构
CREATE TABLE #SType(TypeId VARCHAR(50))
INSERT INTO #SType(TypeId)
SELECT B.typeId
FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) F
INNER JOIN SType B ON B.typeId=F.TypeId AND B.sonnum=0 


--品牌
CREATE TABLE #Brandar(TypeId VARCHAR(50))
INSERT INTO #Brandar(TypeId)
SELECT C.TypeId
FROM brandar_Commodity C
INNER JOIN f_split(@brandtypeid,',') F ON C.TypeId LIKE F.a+'%' AND C.SonNum=0

--修改原往来单位信用额度
UPDATE C SET C.Credit=CASE WHEN @IsCredit=1 THEN CASE WHEN @OperateSign='+' THEN C.Credit+@Credit 
									WHEN @OperateSign='-' THEN CASE WHEN C.Credit-@Credit<0 THEN 0 ELSE C.Credit-@Credit END 
									WHEN @OperateSign='*' THEN C.Credit*@Credit
								END --原信用额度
		 WHEN @IsCredit=0 THEN @Credit
		 WHEN @IsCredit=2 THEN NULL--无限制
	END
FROM BrandBtype_Credit C 
INNER JOIN #BType T ON T.TypeId=C.BtypeId
INNER JOIN #SType S ON S.TypeId=C.StypeId
INNER JOIN #Brandar B ON B.TypeId=C.BrandarTypeId
SELECT @ErrorCount+=@@ERROR

--插入不存在往来单位信用额度值
IF @OperateSign <> '*' AND @IsCredit <> 2
BEGIN
	INSERT INTO BrandBtype_Credit(BtypeId,StypeId,BrandarTypeId,Credit)
	SELECT B.TypeId,S.TypeId,Br.TypeId,@Credit
	FROM #BType B,#SType S,#Brandar Br
	WHERE NOT EXISTS(SELECT * FROM BrandBtype_Credit WHERE StypeId=S.TypeId AND BtypeId=B.TypeId AND BrandarTypeId=Br.TypeId)
	GROUP BY B.TypeId,S.TypeId,Br.TypeId
	SELECT @ErrorCount+=@@ERROR
END

--删除信用额度为NULL无限制往来单位
DELETE FROM BrandBtype_Credit WHERE Credit IS NULL


--品牌信用额关联信用额度值
SELECT 
	BC.StypeId,
	BC.BtypeId,
	SUM(BC.Credit) Credit
INTO #Temp
FROM BrandBtype_Credit BC 
INNER JOIN #BType B ON B.TypeId=BC.BtypeId 
INNER JOIN #SType S ON S.TypeId=BC.StypeId
GROUP BY 
	BC.StypeId,
	BC.BtypeId

DELETE FROM C
FROM btype_credit C
INNER JOIN #Temp T ON T.BtypeId=C.BtypeId AND T.StypeId=C.StypeId
		
INSERT INTO btype_credit(BtypeId,StypeId,Credit)
SELECT BtypeId,StypeId,Credit FROM #Temp


--删除临时表
DROP TABLE #BType,#Brandar,#SType


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_BType_ARAPTotal_AddEdit]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_BType_ARAPTotal_AddEdit]
GO


/*

功能说明：       

作    者：       冯波

创建日期：       2011-1-21

返回结果：       

*/  

CREATE PROCEDURE [GP_BType_ARAPTotal_AddEdit]
(
	@chvBTypeID					VARCHAR(50),
	@chvSTypeID					VARCHAR(50),
	@intType					TINYINT,				--要修改的往来账字段，1表示应收ARTotal,2表示应付APTotal,3表示预收YSTotal,4表示预付YFTotal
	@decTotal					 NUMERIC(24, 10) ,			--金额
	@decNTotal					 NUMERIC(24, 10) ,			--原币
	@intCID						INT,
	@strErrMsg					VARCHAR(4000) OUTPUT		--返回的出错信息
)
--@encode$--        
AS

SELECT @strErrMsg=''

IF NOT EXISTS(
	SELECT BTypeID 
	FROM BType_ARAPTotal 
	WHERE BTypeID=@chvBTypeID AND STypeID=@chvSTypeID AND CID=@intCID
)
BEGIN
	IF @intType=1
	BEGIN
		INSERT INTO BType_ARAPTotal(BTypeID,STypeID,ARTotal,nARTotal,CID)
   		VALUES(@chvBTypeID,@chvSTypeID,@decTotal,@decNTotal,@intCID)
	END

	IF @intType=2
	BEGIN
		INSERT INTO BType_ARAPTotal(BTypeID,STypeID,APTotal,nApTotal,CID)
   		VALUES(@chvBTypeID,@chvSTypeID,@decTotal,@decNTotal,@intCID)
	END

	IF @intType=3
	BEGIN
		INSERT INTO BType_ARAPTotal(BTypeID,STypeID,YSTotal,nysTotal,CID)
   		VALUES(@chvBTypeID,@chvSTypeID,@decTotal,@decNTotal,@intCID)
	END

	IF @intType=4
	BEGIN
		INSERT INTO BType_ARAPTotal(BTypeID,STypeID,YFTotal,nyfTotal,CID)
   		VALUES(@chvBTypeID,@chvSTypeID,@decTotal,@decNTotal,@intCID)		
	END
END
ELSE
BEGIN
	IF @intType=1
	BEGIN
		UPDATE BType_ARAPTotal
		SET 
			ARTotal=ISNULL(ARTotal,0)+@decTotal,
			NARTotal=ISNULL(NARTotal,0)+@decNTotal
   		WHERE BTypeID=@chvBTypeID AND STypeID=@chvSTypeID AND CID=@intCID
	END

	IF @intType=2
	BEGIN
		UPDATE BType_ARAPTotal
		SET 
			APTotal=ISNULL(APTotal,0)+@decTotal,
			NAPTotal=ISNULL(NAPTotal,0)+@decNTotal
   		WHERE BTypeID=@chvBTypeID AND STypeID=@chvSTypeID AND CID=@intCID
	END

	IF @intType=3
	BEGIN
		UPDATE BType_ARAPTotal
		SET 
			YSTotal=ISNULL(YSTotal,0)+@decTotal,
			NYSTotal=ISNULL(NYSTotal,0)+@decNTotal
   		WHERE BTypeID=@chvBTypeID AND STypeID=@chvSTypeID AND CID=@intCID
	END

	IF @intType=4
	BEGIN
		UPDATE BType_ARAPTotal
		SET 
			YFTotal=ISNULL(YFTotal,0)+@decTotal,
			NYFTotal=ISNULL(NYFTotal,0)+@decNTotal
   		WHERE BTypeID=@chvBTypeID AND STypeID=@chvSTypeID AND CID=@intCID
	END
END




GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：舒珊
	日期：2016.05.18
	描述：批量修改基础资料字段值
			
*/
/*
	修改：武智均
	日期：2019.07.18 
	描述：批量修改启用或取消品牌应收加入判断
*/
CREATE PROCEDURE GP_BtypeBatchRevise
(
	@FieldName	 VARCHAR(500),	--修改字段名称
	@FieldValue	 VARCHAR(MAX),	--字段值
	@FieldText	VARCHAR(50),	--拼接的字段名称
	@MagEType	VARCHAR(50),
    @Mode		INT,
    @UserCode	VARCHAR(3000)='',
    @FullName	VARCHAR(3000)='',
    @parentname	VARCHAR(500)='',
    @FiltVal	VARCHAR(200)='',
	@ParID		VARCHAR(50)='',
	@StartDate	VARCHAR(50) ='',
	@EndDate	VARCHAR(50) ='',
	@IfTextFirst	INT=0,
	@updateCount INT = 0 OUTPUT, -- 返回修改行数
	@totalCount INT = 0 OUTPUT --总条数
)
--@encode$--
AS
SET NOCOUNT ON

-----------------------------------------------------------往来单位结果集 查询 BEGIN--------------------------------------------
CREATE TABLE #MainType (TypeID VARCHAR(50))
DECLARE @SQLDB		VARCHAR(MAx)
DECLARE @SQLWHERE	VARCHAR(MAX)
DECLARE @dbname VARCHAR(100)

SELECT @SQLWHERE = ' Where [sonnum]=0 '

IF @Mode='2' OR @Mode='3'
	SET @dbname='BTYPE'

CREATE TABLE #parTypeid(TypeID VARCHAR(50))
--类别查找特殊处理
IF @parentname IS NOT NULL AND @parentname<>''
BEGIN

	DECLARE @parsql VARCHAR(MAX)
	SET @parsql='
	INSERT INTO #parTypeid (typeid)
	SELECT TypeId FROM '+@dbname+'
    WHERE FullName LIKE ''%'+@parentname+'%'' 
    AND sonnum<>0
    '
    IF @Mode='2'
		SET @parsql+=' AND typeid like ''00001%'' '
	IF @Mode='3'
		SET @parsql+=' AND typeid like ''00002%'' '
		
	EXEC(@parsql)
    DELETE FROM #parTypeid 
    WHERE TypeID IN (	SELECT TypeID 
						FROM btype 
						WHERE ParId IN (SELECT TypeID FROM #parTypeid) 
						AND typeId IN (SELECT TypeID FROM #parTypeid))
END

IF @parentname='' OR @parentname IS NULL
	INSERT INTO #MainType(typeid) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@ParID,2,@MagEType) F
ELSE 
	INSERT INTO #MainType(typeid) 
				SELECT B.typeId FROM BType B
				INNER JOIN 	F_BaseGetAllManagerBaseTypeId(@ParID,2,@MagEType) F ON F.TypeId=B.typeId
				INNER JOIN #parTypeid bar ON B.typeId LIKE BAR.TypeID+'%'



DECLARE @whereDb VARCHAR(max)  =''  

			
	SELECT @SQLDB = '(	SELECT b.*,
							 ROW_NUMBER() OVER (ORDER BY b.usercode) AS rownum
						  FROM	btype b
						  INNER JOIN #MainType T ON T.typeid = b.typeid
						  WHERE	b.[sonnum]=0 
					'
	IF	@FiltVal='0'
		SET @whereDb+=' AND b.deleted='''+@FiltVal+''''
							  
	IF	@Mode=2 
		BEGIN
			SET @whereDb+=' AND b.TypeId LIKE ''00001%''  AND b.TypeId <> ''00001'' '
			IF @ParID ='00000'
				SET @ParID ='00001'
		END
		
	IF	@Mode=3
		BEGIN
			SET @whereDb+=' AND b.TypeId LIKE ''00002%''  AND b.TypeId <> ''00002'' '
			IF @ParID ='00000'
				SET @ParID ='00002'
		END
							  
	IF @StartDate<>''
			SET @whereDb+=	' AND b.CreateDate>='+char(39)+@StartDate+char(39)
			
	IF @EndDate<>''
			SET @whereDb+= ' AND b.CreateDate<='+char(39)+@EndDate+char(39)
	
	IF	@UserCode<>'' 
		SET @whereDb+='	AND b.UserCode LIKE ''%' + RTRIM(@UserCode) +'%'' '
		
	IF	@FullName<>''
		SET @whereDb+=' AND b.FullName LIKE ''%' + RTRIM(@FullName) +'%'' '

	SELECT @SQLDB=@SQLDB+@whereDb
	
	SET @SQLDB+='				  
					  ) p  '
	  
	
	
	--往来单位查询集合
	CREATE TABLE #BTypeTemp(
			[typeId] [varchar](50)	,				--往来单位ID
            [AreaTypeID] [varchar](50),					--地区
            [etypeid] [varchar](50),				--关联职员ID
            [BuyPrice] [varchar](50),				--适用进价
            [price] [varchar](50),					--适用售价
            [ARLimitTime] NUMERIC(24,10),			--收款期限
            [PaymentLTime] NUMERIC(24,10),			--付款期限
            [CqDays] int,							--收款超期提前预警天数
            [FkCqDays] [int] ,						--付款超期提前预警天数
            [DzWarningDays] [int],					--收款对账日提前预警
            FkDzWarningDays [int],					--付款对账日提前预警
            DzDays [int],							--收款每月对账日期
            FkDzDays [int],							--付款每月对账日期
            ChkSkMonthDay [int],					--强制序列号管理
            ChkFkMonthDay  [int] ,					--基本计量单位
            PriceTrackEnable  INT,					--销售默认单位
            SaleZeKou   NUMERIC(24,10),				--采购默认单位
            BuyZeKou NUMERIC(24,10),				--存货默认单位
			Comment [varchar](256),					--备注
			[deleted] [bit]	,						--停用
			rownum int
            
		)

DECLARE @SELTEXT VARCHAR(8000)

		SET @selText=' INSERT INTO #BTypeTemp ( typeId,AreaTypeID,etypeid,BuyPrice,price,ARLimitTime,PaymentLTime,CqDays,
												FkCqDays,DzWarningDays,FkDzWarningDays,DzDays,FkDzDays,ChkSkMonthDay,
												ChkFkMonthDay,PriceTrackEnable,SaleZeKou,BuyZeKou,Comment,deleted,rownum)
												
										SELECT 	typeId,AreaTypeID,etypeid,BuyPrice,price,ARLimitTime,PaymentLTime,CqDays,
												FkCqDays,DzWarningDays,FkDzWarningDays,DzDays,FkDzDays,ChkSkMonthDay,
												ChkFkMonthDay,PriceTrackEnable,SaleZeKou,BuyZeKou,Comment,deleted,ROW_NUMBER() OVER (ORDER BY typeId) AS rownum
										 FROM '	+ @SQLDB 
exec(@seltext) 
-----------------------------------------------------------往来单位结果集 查询 END--------------------------------------------
DECLARE 
	@MaxRowCount	INT,--最大行数
	@RowCount		INT=1,
	@TempBTypeId	VARCHAR(50)--当前行TypeId

SELECT @MaxRowCount=MAX([rownum]) FROM #BTypeTemp 
SET @totalCount = @MaxRowCount
-----------------------------------------------------------往来单位 批量修改 BEGIN--------------------------------------------
DECLARE @SQL VARCHAR(3000) =''
		
IF @FieldName ='AreaTypeID'
	BEGIN
		--存在不为’所有地区‘的 的 地区ID --AND DELETED=0 
		IF EXISTS(SELECT TYPEID FROM AREATYPE WHERE TYPEID =@FieldValue AND SONNUM=0 AND TYPEID <>'00000') OR @FieldValue='' OR @FieldValue IS NULL
			BEGIN
				SET @SQL=' update btype set AreaTypeID = ISNULL('''+@FieldValue+''' ,NULL) where typeid in (select typeid from #BTypeTemp ) AND DELETED=0 '
			END
	END
ELSE IF @FieldName ='EtypeId'
	BEGIN
		--存在不为’所有地区‘的 的 地区ID --AND DELETED=0 
		IF EXISTS(SELECT TYPEID FROM EMPLOYEE WHERE TYPEID =@FieldValue AND SONNUM=0 AND FULLNAME  NOT IN ('root','超级用户'))  OR @FieldValue='' OR @FieldValue IS NULL  
		BEGIN
			SET @SQL=' update btype set EtypeId = ISNULL('''+@FieldValue+''',NULL) where typeid in (select typeid from #BTypeTemp ) AND DELETED=0 '
		END
	END
ELSE IF @FieldName IN ('BuyPrice','Price')
	BEGIN
		SET @SQL=' update btype set '+ @FieldName + ' = '''+@FieldValue+''' where typeid in (select typeid from #BTypeTemp) AND DELETED=0 '
	END	
ELSE IF @FieldName IN ('CqDays','FkCqDays')
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set '+ @FieldName + ' = CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
														  THEN CONVERT(INT, '''+ @FieldValue+''' )
														  ELSE NULL
														  END
														  where typeid in (select typeid from #BTypeTemp) AND DELETED=0'
	END
ELSE IF @FieldName ='DzWarningDays'
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set DzWarningDays = CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
													  THEN CONVERT(INT, '''+ @FieldValue+''' )
													  ELSE NULL
													  END
													  where typeid in (select typeid from #BTypeTemp) AND DELETED=0 AND dzdays IS NOT NULL'
	END
ELSE IF @FieldName ='FkDzWarningDays'
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set FkDzWarningDays = CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
													  THEN CONVERT(INT, '''+ @FieldValue+''' )
													  ELSE NULL
													  END
													  where typeid in (select typeid from #BTypeTemp) AND DELETED=0 AND fkdzdays IS NOT NULL'
	END
ELSE IF @FieldName IN  ('DzDays','FkDzDays')
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set '+ @FieldName +' = CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
													  THEN CONVERT(INT, '''+ @FieldValue+''' )
													  ELSE NULL
													  END,
										DzWarningDays= CASE WHEN CONVERT(INT, '''+@FieldValue +''' )=-1 AND '''+@FieldName+'''=''DzDays''
														THEN NULL
														ELSE DzWarningDays
														END,
										FkDzWarningDays= CASE WHEN CONVERT(INT, '''+@FieldValue +''' )=-1 AND '''+@FieldName+'''=''FkDzDays''
															THEN NULL
															ELSE FkDzWarningDays
															END			
													   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 '
	END
--ELSE IF @FieldName ='ARLimitTime'
--	BEGIN
--		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
--		SET @FieldValue='-1'
--		SET @SQL=' update btype set ARLimitTime =CASE WHEN CONVERT(NUMERIC(24,10), '''+ @FieldValue+''' )>0
--													  THEN CONVERT(NUMERIC(24,10), '''+ @FieldValue+''' )
--													  ELSE NULL
--													  END
--													  where typeid in (select typeid from #BTypeTemp) AND DELETED=0 '
--	END	
--ELSE IF @FieldName ='PaymentLTime'
--	BEGIN
--		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
--		SET @FieldValue='-1'
--		SET @SQL=' update btype set PaymentLTime =CASE WHEN CONVERT(NUMERIC(24,10), '''+ @FieldValue+''' )>=0
--													  THEN CONVERT(NUMERIC(24,10), '''+ @FieldValue+''' )
--													  ELSE NULL
--													  END
--													  where typeid in (select typeid from #BTypeTemp) AND DELETED=0  '
--	END
ELSE IF @FieldName ='ARLimitTime' AND @FieldText='1'
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set ckarlimittime = 1,
									arlimittime=  CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
													  THEN CONVERT(INT, '''+ @FieldValue+''' )
													  ELSE NULL
													  END,
									skmonthday=NULL,
									chkskmonthday=0
					where typeid in (select typeid from #BTypeTemp) AND DELETED=0  '
	END
ELSE IF @FieldName ='ARLimitTime' AND @FieldText='0'
	BEGIN
		SET @SQL=' update btype set ckarlimittime = 0 ,
									arlimittime=NULL,
									chkskmonthday=1
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 AND ckarlimittime=1'
	END
ELSE IF @FieldName ='PaymentLTime' AND @FieldText='1'
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set ckpaymentltime = 1,
									paymentltime=  CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
													  THEN CONVERT(INT, '''+ @FieldValue+''' )
													  ELSE NULL
													  END, 
									fkmonthday=NULL,
									chkfkmonthday=0
					where typeid in (select typeid from #BTypeTemp) AND DELETED=0  '
	END
ELSE IF @FieldName ='PaymentLTime' AND @FieldText='0'
	BEGIN
		SET @SQL=' update btype set ckpaymentltime =0,
									paymentltime=NULL,
									chkfkmonthday=1
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 AND ckpaymentltime=1'
	END
ELSE IF @FieldName ='ChkSkMonthDay' AND @FieldText='1'
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set ChkSkMonthDay = 1,
									skmonthday=  CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
													  THEN CONVERT(INT, '''+ @FieldValue+''' )
													  ELSE NULL
													  END,
									arlimittime=NULL,
									ckarlimittime=0
					where typeid in (select typeid from #BTypeTemp) AND DELETED=0  '
	END
ELSE IF @FieldName ='ChkSkMonthDay' AND @FieldText='0'
	BEGIN
		SET @SQL=' update btype set ChkSkMonthDay = 0 ,
									skmonthday=NULL,
									ckarlimittime=1
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 AND ChkSkMonthDay=1'
	END
ELSE IF @FieldName ='ChkFkMonthDay' AND @FieldText='1'
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set ChkFkMonthDay = 1,
									fkmonthday=  CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
													  THEN CONVERT(INT, '''+ @FieldValue+''' )
													  ELSE NULL
													  END, 
									paymentltime=NULL,
									ckpaymentltime=0
					where typeid in (select typeid from #BTypeTemp) AND DELETED=0  '
	END
ELSE IF @FieldName ='ChkFkMonthDay' AND @FieldText='0'
	BEGIN
		SET @SQL=' update btype set ChkFkMonthDay =0,
									fkmonthday=NULL,
									ckpaymentltime=1
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 AND ChkFkMonthDay=1'
	END
ELSE IF @FieldName='PriceTrackEnable'
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set '+ @FieldName +' = CASE WHEN CONVERT(INT, '''+ @FieldValue+''' )>=0
													  THEN CONVERT(INT, '''+ @FieldValue+''' )
													  ELSE NULL
													  END
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 '
	END
ELSE IF @FieldName IN ('SaleZeKou','BuyZeKou')
	BEGIN
		IF (ISNULL(@FieldValue,'')='' OR @FieldValue='')
		SET @FieldValue='-1'
		SET @SQL=' update btype set '+ @FieldName +' = CASE WHEN CONVERT(NUMERIC(24,10), '''+ @FieldValue+''' )>=0
													  THEN CONVERT(NUMERIC(24,10), '''+ @FieldValue+''' )
													  ELSE NULL
													  END
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 '
	END
ELSE IF @FieldName ='Comment'
	BEGIN
		SET @SQL=' update btype set '+ @FieldName +' = ISNULL('''+@FieldValue+''' ,NULL)
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 '
	END
	
ELSE IF @FieldName ='Comment'
	BEGIN
		SET @SQL=' update btype set '+ @FieldName +' = ISNULL('''+@FieldValue+''' ,NULL)
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 '
	END
	
ELSE IF @FieldName = 'FullName'
	BEGIN	
		IF @IfTextFirst=1
			SET @SQL='UPDATE btype SET FULLNAME=  CASE WHEN ISNULL (SUBSTRING(convert(text, ('''+ @FieldText+'''+'+@FieldValue+')),1,200),'''')<>''''
																THEN SUBSTRING(convert(text, ('''+ @FieldText+'''+'+@FieldValue+')),1,200)
																ELSE  FULLNAME
																END,
									Pycode=CASE WHEN ISNULL(SUBSTRING(dbo.fun_getPY('''+ @FieldText+'''+'+@FieldValue+'),1,500) ,'''')<>''''
												THEN SUBSTRING(dbo.fun_getPY('''+ @FieldText+'''+'+@FieldValue+'),1,500)
												ELSE Pycode 
												END
									WHERE TYPEID IN (SELECT TYPEID FROM #BTypeTemp )'
					
		ELSE 
			SET @SQL='UPDATE btype SET FULLNAME= CASE WHEN ISNULL (SUBSTRING(convert(text, ('+ @FieldValue+'+'''+@FieldText+''')),1,200),'''')<>''''
															THEN SUBSTRING(convert(text, ('+ @FieldValue+'+'''+@FieldText+''')),1,200)
															ELSE FULLNAME
															END ,
								   Pycode=CASE WHEN ISNULL(SUBSTRING(dbo.fun_getPY('+ @FieldValue+'+'''+@FieldText+'''),1,500) ,'''')<>''''
												THEN SUBSTRING(dbo.fun_getPY('+ @FieldValue+'+'''+@FieldText+'''),1,500)
												ELSE Pycode
												END
								   WHERE TYPEID IN (SELECT TYPEID FROM #BTypeTemp )'							 
	END
ELSE IF @FieldName IN ('Name')
	BEGIN
		IF @IfTextFirst=1
			SET @SQL='UPDATE btype SET '+@FieldName+'= 
			CASE
				WHEN LEN('''+ @FieldText+'''+'+@FieldValue+') = DATALENGTH('''+ @FieldText+'''+'+@FieldValue+') THEN SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,30) 			
				ELSE SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,15)
			END
			WHERE TYPEID IN (SELECT TYPEID FROM #BTypeTemp )'
		ELSE
			SET @SQL='UPDATE btype SET '+@FieldName+'= 
			CASE
				WHEN LEN('+ @FieldValue+'+'''+@FieldText+''') = DATALENGTH('+ @FieldValue+'+'''+@FieldText+''') THEN SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,30) 			
				ELSE SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,15)
			END
			WHERE TYPEID IN (SELECT TYPEID FROM #BTypeTemp )'
					 		
			--SET @SQL='UPDATE btype SET '+@FieldName+'= SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,28) 
			--			WHERE TYPEID IN (SELECT TYPEID FROM #BTypeTemp ) '					
	END
	
ELSE IF @FieldName ='Pycode'
	BEGIN
		IF @IfTextFirst=1
			SET @SQL='UPDATE btype SET Pycode=SUBSTRING(dbo.fun_getPY('''+ @FieldText+'''+'+@FieldValue+'),1,500)			
						WHERE TYPEID IN (SELECT TYPEID FROM #BTypeTemp ) '
		ELSE 
			SET @SQL='UPDATE btype SET Pycode=SUBSTRING(dbo.fun_getPY('+ @FieldValue+'+'''+@FieldText+'''),1,500)
						WHERE TYPEID IN (SELECT TYPEID FROM #BTypeTemp )'
	END

	
ELSE IF @FieldName in('cid','blevel','linkman1','linktel1','linkmobile1','linkman2','linktel2','linkmobile2')
	BEGIN
		SET @SQL=' update btype set '+ @FieldName +' = ISNULL('''+@FieldValue+''' ,NULL)
				   where typeid in (select typeid from #BTypeTemp) AND DELETED=0 '
	END
ELSE IF(@FieldName='denominatedid')--结算单位
	BEGIN
		SET @RowCount =1
		WHILE @RowCount<=@MaxRowCount
			BEGIN
				SELECT @TempBTypeId=TypeId FROM #BTypeTemp WHERE [rownum]=@RowCount
				
				DECLARE @erromsg VARCHAR(MAX)
				--删除判断
				BEGIN TRY
					--EXEC Gp_BaseInfoCheck @dbname,@TempBTypeId,'1'
					SET @SQL +='UPDATE btype SET '+ @FieldName +'=ISNULL('''+@FieldValue+''' ,NULL) WHERE TypeId='''+@TempBTypeId+''''+CHAR(13)
				END TRY
				BEGIN CATCH
					--SELECT @erromsg=ERROR_MESSAGE()
					--RAISERROR('%s',16,1,@erromsg)RETURN
				END CATCH
				
				SET @RowCount+=1
			END
	END		
ELSE IF	@FieldName='isUseBrandarType' --品牌
	BEGIN
		SET @SQL=' update btype set '+ @FieldName +' = '''+@FieldValue+'''
				   from btype bt where typeid in (select typeid from #BTypeTemp) AND DELETED=0 
				   and not exists
				   (
				   select 1 from BillIndex a where a.btypeid = bt.typeid and (a.BillType in(11,45,12,46,141,160,36,93) OR (a.BillType in(4,189,305,215) and a.IsIni = 0) OR (a.BillType in(402,403) and a.IsIni = 1))
				   union all
				   select 1 from ReceiptBillIndex a where a.BTypeID = bt.typeid and a.BillType in(405)
				   union all
				   select 1 from BillIndex a inner join addebtbill b on a.BillNumberID = b.BillNumberID where b.btypeid = bt.typeid and ((a.IsIni = 0 and a.BillType in (115,116)) or (a.BillType in (115,116,128,129) and a.IsIni = 1))
                   union all
                   select 1 from BillIndex a inner join accountcredence b on a.BillNumberId = b.BillNumberId where  b.ATypeID = bt.typeid and b.TypeATypeID in (33,39) and a.BillType in (159) and a.IsIni = 0
                   )
				   '
	END
ELSE IF @FieldName = 'isBtypeArCyj' --收款次月结
	BEGIN
		SET @SQL='	UPDATE	dbo.btype
					SET		skcyjartime = '+@FieldValue+',
							skmonth = CASE WHEN '+@FieldValue+' = 1 THEN (SELECT a FROM dbo.f_split_table('''+@FieldText+''',''/'') WHERE nid = 1) ELSE NULL END,
							skday   = CASE WHEN '+@FieldValue+' = 1 THEN (SELECT a FROM dbo.f_split_table('''+@FieldText+''',''/'') WHERE nid = 2) ELSE NULL END
					FROM	btype b
					INNER JOIN #BTypeTemp bt ON b.typeid = bt.typeid '
	END
ELSE IF @FieldName = 'isBtypeApCyj' --付款次月结
	BEGIN
		SET @SQL='	UPDATE	dbo.btype
					SET		fkcyjaptime = '+@FieldValue+',
							fkmonth = CASE WHEN '+@FieldValue+' = 1 THEN (SELECT a FROM dbo.f_split_table('''+@FieldText+''',''/'') WHERE nid = 1) ELSE NULL END,
							fkday   = CASE WHEN '+@FieldValue+' = 1 THEN (SELECT a FROM dbo.f_split_table('''+@FieldText+''',''/'') WHERE nid = 2) ELSE NULL END
					FROM	btype b
					INNER JOIN #BTypeTemp bt ON b.typeid = bt.typeid '
	END	
	
IF @SQL<>''
	EXEC (@SQL)

SET @updateCount = @@ROWCOUNT

IF(@FieldName='denominatedid')
	SET @updateCount = @MaxRowCount
-----------------------------------------------------------往来单位 批量修改 END--------------------------------------------
--修改缓存
DECLARE @XiWaMaxNumber INT 

SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Btype

UPDATE B set B.XiWaMaxNumber=@XiWaMaxNumber,@XiWaMaxNumber=@XiWaMaxNumber+1 
FROM Btype B
INNER JOIN #BTypeTemp T ON T.typeId=B.typeId


DROP TABLE #MainType,#parTypeid,#BTypeTemp

			
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_BtypeCreditCopy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_BtypeCreditCopy
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2010-12-28
-- Description: 信用额度复制
-- =============================================
CREATE PROCEDURE Gp_BtypeCreditCopy
(
	@STypeId VARCHAR(2000)='',
	@STypeId1 varchar(2000)='',
	@OperatorId varchar(200),
	@Flag	INT--1:信用额度 2:品牌信用额度
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @IsUseBrandarType INT=0--是否启用品牌

IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND SubValue=1)
	AND EXISTS(SELECT SubValue FROM SysData WHERE SubName='brandarcontrollineofcredit' AND SubValue=0)
	SET @IsUseBrandarType=1
	
--往来单位
CREATE TABLE #BType(TypeId VARCHAR(50))
IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value=1)-- 客户供货商统一  
	BEGIN
		INSERT INTO #BType(TypeId) 
		SELECT b.typeId
		FROM F_GetAllManagerBaseTypeId('',2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND ((@Flag=1 AND (@IsUseBrandarType=0 OR (@IsUseBrandarType=1 AND B.IsUseBrandarType<>1))) OR (@Flag=2 AND @IsUseBrandarType=1 AND B.IsUseBrandarType=1)) AND B.sonnum=0
	END
ELSE --不统一，只需客户
	BEGIN
		INSERT INTO #BType(TypeId) 
		SELECT b.typeId
		FROM F_GetAllManagerBaseTypeId('',2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND b.typeId LIKE '00001%' AND ((@Flag=1 AND (@IsUseBrandarType=0 OR (@IsUseBrandarType=1 AND B.IsUseBrandarType<>1))) OR (@Flag=2 AND @IsUseBrandarType=1 AND B.IsUseBrandarType=1)) AND B.sonnum=0
	END
	
--分支机构	
CREATE TABLE #SType(TypeId VARCHAR(50))
INSERT INTO #SType(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@STypeId1,11,@OperatorID)

--信用额度复制
IF(@Flag=1)
	BEGIN
		
		DELETE FROM C
		FROM btype_credit C
		INNER JOIN #SType S ON S.TypeId=C.StypeId
		WHERE C.BtypeId IN(
					SELECT BtypeId 
					FROM btype_credit BC 
					INNER JOIN #BType B ON B.TypeId=BC.BtypeId
					WHERE BC.StypeId=@STypeId
				)
			
		INSERT INTO btype_credit(BtypeId,StypeId,Credit)
		SELECT
			B.TypeId,
			S.TypeId,
			SUM(C.Credit) Credit
		FROM btype_credit C,#BType B,#SType S
		WHERE 
			C.StypeId=@STypeId
			AND B.TypeId=C.BtypeId
		GROUP BY 
			B.TypeId,
			S.TypeId
			
		DELETE FROM Btype_Credit WHERE Credit IS NULL
		
	END
ELSE IF(@Flag=2)--品牌信用额度复制
	BEGIN
		
		DELETE FROM C
		FROM BrandBtype_Credit C
		INNER JOIN #SType S ON S.TypeId=C.StypeId
		WHERE C.BtypeId IN(
					SELECT BtypeId 
					FROM BrandBtype_Credit BC 
					INNER JOIN #BType B ON B.TypeId=BC.BtypeId
					WHERE BC.StypeId=@STypeId
				)
		
		INSERT INTO BrandBtype_Credit(BtypeId,StypeId,BrandarTypeId,Credit)
		SELECT
			B.TypeId,
			S.TypeId,
			C.BrandarTypeId,
			SUM(C.Credit) Credit
		FROM BrandBtype_Credit C,#BType B,#SType S
		WHERE 
			C.StypeId=@STypeId
			AND B.TypeId=C.BtypeId
		GROUP BY 
			B.TypeId,
			S.TypeId,
			C.BrandarTypeId
			
		DELETE FROM BrandBtype_Credit WHERE Credit IS NULL
	END



--删除临时表
DROP TABLE #BType,#SType


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_BtypeCreditSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_BtypeCreditSet
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2010-12-27
-- Description: 信用额度设置
-- =============================================
CREATE PROCEDURE Gp_BtypeCreditSet
(
	@STypeId		VARCHAR(MAX)='',
	@BTypeId		VARCHAR(MAX)='',
	@Credit			NUMERIC(24, 10) ,
	@IsCredit		INT=1,
	@OperateSign	VARCHAR(10)='',
	@OperatorId		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON
	
DECLARE
	@ErrorCount			INT=0,
	@Sql				NVARCHAR(MAX)='',
	@IsUseBrandarType	INT=0,--是否启用品牌
	@ErrorBrandarStr	VARCHAR(MAX)='',--不满足条件的品牌
	@ProInfo			INT=0--系统版本

SELECT @ProInfo=SubValue FROM SysData WHERE SubName='ProInfo'

IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND SubValue=1)
	AND EXISTS(SELECT SubValue FROM SysData WHERE SubName='brandarcontrollineofcredit' AND SubValue=0)
	SET @IsUseBrandarType=1
	
IF(@ProInfo<>2)
	SET @STypeId='00001'

--往来单位
CREATE TABLE #BType(TypeId VARCHAR(50),FullName VARCHAR(200),SonNum INT)

IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value=1)-- 客户供货商统一  
	BEGIN
		INSERT INTO #BType(TypeId,FullName,SonNum)
		SELECT B.typeId,B.FullName,B.sonnum
		FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId  AND B.sonnum=0 AND (@IsUseBrandarType=0 OR (@IsUseBrandarType=1 AND B.IsUseBrandarType=0))
	END
ELSE --不统一，只需客户
	BEGIN
		INSERT INTO #BType(TypeId,FullName,SonNum)
		SELECT B.typeId,B.FullName,B.sonnum
		FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND b.typeId LIKE '00001%'  AND B.sonnum=0 AND (@IsUseBrandarType=0 OR (@IsUseBrandarType=1 AND B.IsUseBrandarType=0))
	END

--分支机构
CREATE TABLE #SType(TypeId VARCHAR(50))
INSERT INTO #SType(TypeId)
SELECT B.typeId
FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) F
INNER JOIN SType B ON B.typeId=F.TypeId AND B.sonnum=0 


--修改原往来单位信用额度
UPDATE C SET C.Credit=CASE WHEN @IsCredit=1 THEN CASE WHEN @OperateSign='+' THEN C.Credit+@Credit 
									WHEN @OperateSign='-' THEN CASE WHEN C.Credit-@Credit<0 THEN 0 ELSE C.Credit-@Credit END 
									WHEN @OperateSign='*' THEN C.Credit*@Credit
								END --原信用额度
		 WHEN @IsCredit=0 THEN @Credit
		 WHEN @IsCredit=2 THEN NULL--无限制
	END
FROM btype_credit C 
INNER JOIN #BType T ON T.TypeId=C.BtypeId
INNER JOIN #SType S ON S.TypeId=C.StypeId
SELECT @ErrorCount+=@@ERROR


IF @OperateSign='+'
BEGIN
--插入不存在往来单位信用额度值
INSERT INTO btype_credit(StypeId,BtypeId,Credit)
SELECT S.TypeId,B.TypeId,@Credit
FROM #BType B,#SType S
WHERE NOT EXISTS(SELECT * FROM btype_credit WHERE StypeId=S.TypeId AND BtypeId=B.TypeId) 
AND @IsCredit <> 2
GROUP BY B.TypeId,S.TypeId
SELECT @ErrorCount+=@@ERROR
END
ELSE
BEGIN
--插入不存在往来单位信用额度值
INSERT INTO btype_credit(StypeId,BtypeId,Credit)
SELECT S.TypeId,B.TypeId,NULL
FROM #BType B,#SType S
WHERE NOT EXISTS(SELECT * FROM btype_credit WHERE StypeId=S.TypeId AND BtypeId=B.TypeId) 
AND @IsCredit <> 2
GROUP BY B.TypeId,S.TypeId
SELECT @ErrorCount+=@@ERROR
END


--统一了信用额度入口，但是也要兼容以前逻辑
IF @ProInfo<>2
	BEGIN
		UPDATE B SET B.ARLimit=C.Credit
		FROM #BType T
		INNER JOIN btype B ON T.TypeId=B.typeId
		INNER JOIN btype_credit C ON C.BtypeId=B.typeId
	END	
	
--删除信用额度为NULL无限制往来单位
DELETE FROM btype_credit WHERE Credit IS NULL


--删除临时表
DROP TABLE #BType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
	作者：陈强
	日期：2019-11-05
	描述：9.91新功能，供货商信息覆盖导入
*/
CREATE	PROCEDURE [dbo].[GP_BtypeGCoverImport]
(
		@usercode			varchar(256),	--供货商编号
		@fullname			varchar(256),	--供货商名称
		@name				varchar(256),	--简名
		@pycode				varchar(256),	--拼音码
		@ausercode			varchar(256),	--地区编号
		@area				varchar(256),	--地区
		@etypeid            varchar(256),	--关联职员ID
		@etypename          varchar(256),	--职员名称
		@buypride           varchar(256),	--适用进价类型
		@salezekou          varchar(256),	--销售折扣
		@buyzekou           varchar(256),	--采购折扣
		@price              varchar(256),	--适用售价类型
		@denominatedid      varchar(256),	--结算单位编号
		@dename             varchar(256),	--结算单位名称
		@pricetrackenable1  varchar(256),	--启用价格跟踪
		@tel1               varchar(256),	--电话1
		@tel2               varchar(256),	--电话2
		@tel3               varchar(256),	--电话3
		@www                varchar(256),	--网络地址
		@email              varchar(256),	--电子邮件
		@fax                varchar(256),	--传真
		@postcode           varchar(256),	--邮编
		@sheng              varchar(256),	--省
		@shi                varchar(256),	--市
		@xian               varchar(256),	--区/县
		@telandaddress      varchar(256),	--详细地址
		@blevel             varchar(256),	--单位等级
		@bank               varchar(256),	--银行户名
		@taxnumber          varchar(256),	--税号
		@bankname           varchar(256),	--开户银行
		@bankandacount      varchar(256),	--银行账号
		@comment            varchar(256),	--备注
		@linkman1           varchar(256),	--联系人1
		@linkmobile1        varchar(256),	--联系人1手机
		@linktel1           varchar(256),	--联系人1电话
		@linkman2           varchar(256),	--联系人2	
		@linkmobile2        varchar(256),	--联系人2手机
		@linktel2           varchar(256),	--联系人2电话
		@ErrMsg VARCHAR(200) OUTPUT			--返回错误信息
)
AS
SET NOCOUNT ON
---------------------------------基础验证-------------------------------------
IF(@usercode = '')
BEGIN
	SET @ErrMsg = '供货商编号不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF lower(LTrim(RTrim(Replace(@usercode,' ',''))))='abc' OR lower(LTrim(RTrim(Replace(@usercode,' ',''))))=lower('KH')
	OR lower(LTrim(RTrim(Replace(@usercode,' ',''))))=lower('DL')
	BEGIN
		SET @ErrMsg = '供货商编号与系统保留编号冲突，请检查编号是否有误!'
		RETURN -1
	END
END

IF(@fullname = '')
BEGIN
	SET @ErrMsg = '供货商名称不能为空'
	RETURN -1
END


--验证地区信息
DECLARE @dqsoncount varchar(50)
DECLARE @newdq varchar(100)

IF ISNULL(@ausercode,'')<>''
BEGIN
	SELECT @dqsoncount=sonnum from AreaType where usercode=@ausercode and parid<>'root'
	
	IF ISNULL(@dqsoncount,'')='' OR @dqsoncount<>0	--不存在地区信息 或者 是父节点
	BEGIN
		IF ISNULL(@dqsoncount,'')='' 
		BEGIN
			SET @ErrMsg = '地区信息不存在，请检查地区编号是否有误!'
			RETURN -1
		END
		
		IF @dqsoncount<>0
		BEGIN
			SET @ErrMsg = '不能选择父节点为地区信息，请检查地区编号是否有误!'
			RETURN -1
		END
	END
	SELECT @newdq=typeid from AreaType where UserCode=@ausercode
END
ELSE
BEGIN
	SET @newdq=''
END	

--验证职员信息
DECLARE @zysonnum varchar(100)
DECLARE @newzy varchar(100)

IF ISNULL(@etypeid,'')<>''
BEGIN
	SELECT @zysonnum=sonnum from employee where usercode=@etypeid and parid<>'root'

	IF ISNULL(@zysonnum,'')='' OR @zysonnum<>0	--不存在职员信息 或者 是父节点
	BEGIN
		IF ISNULL(@zysonnum,'')=''
		BEGIN
			SET @ErrMsg = '职员信息不存在，请检查职员编号是否有误!'
			RETURN -1
		END
		
		IF @zysonnum<>0
		BEGIN
			SET @ErrMsg = '职员信息不能为大类，请检查职员编号是否有误!'
			RETURN -1
		END
	END
	SELECT @newzy=typeid from employee where UserCode=@etypeid
END
ELSE
BEGIN
	SET @newzy=''
END	

--验证结算单位
DECLARE @jsdwcheck varchar(100);
DECLARE @sumNum int
DECLARE @newjsdw varchar(100)
DECLARE @parement_check int

IF @denominatedid<>''
BEGIN
	SELECT @jsdwcheck=LEFT(parid,5),@sumNum=sonnum from btype where usercode=@denominatedid
	SELECT TOP 1 @parement_check=sonnum FROM btype WHERE UserCode=@usercode
	
	IF ISNULL(@jsdwcheck,'')<>''	--代表库中存在
	BEGIN
		IF @jsdwcheck<>'00002' 
		BEGIN
			SET @ErrMsg = '该供货商选择的结算单位无效! 请确认结算单位编号是否有误!';
			RETURN -1;
		END
		
		--验证供货商是否是父类(父类不进行判断结算单位)
		IF @parement_check=0
		BEGIN
			IF @sumNum<>0
			BEGIN
				SET @ErrMsg = '该供货商选择的结算单位无效! 结算单位不能为父节点!';
				RETURN -1;
			END 
		END
	END
	ELSE	--库中不存在
	BEGIN
		SET @ErrMsg = '该结算单位不存在，请检查结算单位编号是否有误!';
		RETURN -1;
	END
	SELECT @newjsdw=typeid from btype where usercode=@denominatedid
END
ELSE
BEGIN
	SELECT TOP 1 @newjsdw=typeid from btype where usercode=@usercode
END


----销售折扣、采购折扣
DECLARE @d_discount                VARCHAR(5),   --  扣率小数位数
		@d_discount1               INT ;         --  扣率小数位数
	                          
SELECT @d_discount= DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 4
SET @d_discount1= CONVERT(INT,@d_discount)

DECLARE @salezekou1  NUMERIC(24, 4) 

IF (ISNUMERIC(@salezekou) <> 1 ) 
BEGIN
    SET @ErrMsg = '销售折扣请输入数字'
    RETURN -1
END

IF ((SELECT CHARINDEX('-', @salezekou)) <> 0 ) 
BEGIN
	SET @ErrMsg = '销售折扣不能为负数'
	RETURN -1
END
ELSE 
BEGIN
SELECT  @salezekou1 = CONVERT( NUMERIC(24, 4) , @salezekou)
IF ( @salezekou1 <= 0 OR @salezekou1 > 1) 
BEGIN
    SET @ErrMsg = '销售折扣输入错误'
    RETURN -1
END
IF dbo.F_CheckDecimal(@salezekou1,4,@d_discount1) < 0
BEGIN
	SET @ErrMsg='销售折扣值多于'+@d_discount+'位小数'
	RETURN -1;
END

IF (@salezekou = '' ) OR @salezekou1=0
BEGIN
    SET @ErrMsg = '销售折扣输入错误'
    RETURN -1
END

END


DECLARE @buyzekou1  NUMERIC(24, 4) 

IF (ISNUMERIC(@buyzekou) <> 1 ) 
BEGIN
    SET @ErrMsg = '采购折扣请输入数字'
    RETURN -1
END

IF ((SELECT   CHARINDEX('-', @buyzekou)) <> 0 ) 
BEGIN
    SET @ErrMsg = '采购折扣不能为负数'
    RETURN -1
END
ELSE 
BEGIN
SELECT  @buyzekou1 = CONVERT( NUMERIC(24, 4) , @buyzekou)
IF (@buyzekou1 <= 0 OR @buyzekou1 > 1) 
BEGIN
    SET @ErrMsg = '采购折扣输入错误'
    RETURN -1
END
IF dbo.F_CheckDecimal(@buyzekou1,4,@d_discount1) < 0
BEGIN
	SET @ErrMsg='采购折扣值多于'+@d_discount+'位小数'
	RETURN -1;
END
END

IF (@buyzekou = '') OR @buyzekou1=0
BEGIN
    SET @ErrMsg = '采购折扣输入错误'
    RETURN -1
END


DECLARE @PostCodeLen INT
SELECT  @PostCodeLen = LEN(@postcode)
IF (@PostCodeLen > 200 ) 
BEGIN
    SET @ErrMsg = '邮编不能超过200字符'
    RETURN -1
END

--适用进价判断
DECLARE @Checkbuyprice VARCHAR(50)
SELECT  @Checkbuyprice = CASE @buypride
                      WHEN '无' THEN '0'
                      WHEN '' THEN '0'
                      WHEN '预设进价1' THEN '1'
                      WHEN '预设进价2' THEN '2'
                      WHEN '预设进价3' THEN '3'
                      WHEN '预设进价4' THEN '4'
                      WHEN '预设进价5' THEN '5'
                      WHEN '最高进价' THEN '6'
                      WHEN '零售价' THEN '7'
                      ELSE 'ERROR'
                    END
IF (@Checkbuyprice = 'ERROR' ) 
    BEGIN
        SET @ErrMsg = '适用进价不匹配'
        RETURN -1
    END

--适用售价判断
DECLARE @CheckPrice VARCHAR(50)
SELECT  @CheckPrice = CASE @price
                   WHEN '无' THEN '0'
                   WHEN '' THEN '0'
                   WHEN '预设售价1' THEN '1'
                   WHEN '预设售价2' THEN '2'
                   WHEN '预设售价3' THEN '3'
                   WHEN '预设售价4' THEN '4'
                   WHEN '预设售价5' THEN '5'
                   WHEN '预设售价6' THEN '6'
                   WHEN '预设售价7' THEN '7'
                   WHEN '预设售价8' THEN '8'
                   WHEN '预设售价9' THEN '9'
                   WHEN '预设售价10' THEN '10'
                   WHEN '零售价' THEN '11'
                   WHEN '最高售价' THEN '12'
                   WHEN '最低售价' THEN '13'
                   ELSE 'ERROR'
                 END
IF (@CheckPrice = 'ERROR' ) 
BEGIN
    SET @ErrMsg = '适用售价不匹配'
    RETURN -1
END


--启用价格跟踪
DECLARE @Checkpricetrackenable1 varchar(50)
SELECT  @Checkpricetrackenable1 = CASE @pricetrackenable1
                   WHEN '是' THEN '1'
                   WHEN '否' THEN '0'
                   WHEN '' THEN '0'
                   ELSE 'ERROR'
                 END
IF (@Checkpricetrackenable1 = 'ERROR' ) 
BEGIN
    SET @ErrMsg = '启用价格跟踪不匹配!'
    RETURN -1
END

---验证客户编号、客户名称重复
DECLARE @usercf varchar(50)	--验证是否有相同的usercode
DECLARE @CheckFlag varchar(50)
select @CheckFlag=value from Userconfig where ConfigName='equalitemname'

IF @CheckFlag<>1--不允许重复
begin
	if NOT exists(select TypeID from [btype] where usercode=@usercode and deleted<>1)
	begin
		SET @ErrMsg = @fullname + '该供货商编号不存在，无法覆盖导入!'
		RETURN -1
	END
	
	if exists(select TypeID from [btype] where (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @usercode + '使用，请更换或删除该停用的编号'
		RETURN -1
	end
	
	if exists(select TypeID from [btype] where (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的'+@FullName+'客户使用，请更换或删除该停用的编号'
		RETURN -1
	end
	
	if exists(select TypeID from [btype] where UserCode<>@usercode and fullname=@fullname and deleted<>1)
	begin
		SET @ErrMsg = '该供货商名称【' + @FullName + '】已经存在，供货商名称不能相同!'
		RETURN -1
	end
	
end
else
begin
	if exists(select TypeID from [btype] where usercode=@usercode  and deleted=1)
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @usercode + '使用，请更换或删除该停用的编号'
		RETURN -1
	end
	
	if NOT exists(select TypeID from [btype] where usercode=@usercode and deleted<>1)
	begin
		SET @ErrMsg = @fullname + '该供货商编号不存在，无法覆盖导入!'
		RETURN -1
	END
	
	SELECT @usercf=COUNT(1) from btype  where usercode=@usercode 
	IF @usercf>1
	BEGIN
		SET @ErrMsg = '该【' + @FullName + '】的编号已存在!'
		RETURN -1
	END
end

--------------------------------基础验证结束----------------------------------

BEGIN TRAN insertproc

UPDATE [btype] SET 
      [FullName] =@fullname
      ,[Name] = @name
      ,[AreaTypeID] = @newdq
      ,[TelAndAddress] = @telandaddress
      ,[PostCode] = @postcode 
      ,[BankAndAcount] = @bankandacount
      ,[Comment] = @comment
	  ,[TaxNumber] = @taxnumber
      ,[Tel1] = @tel1
      ,[Tel2] = @tel2
      ,[Tel3] = @tel3
      ,[Fax] = @fax
      ,[WWW] = @www
      ,[Bank] = @bank
      ,[BankName] = @bankname
      ,[Email] = @email
      ,[LinkMan1] =@linkman1
      ,[LinkMobile1] = @linkmobile1
      ,[LinkTel1] = @linktel1
      ,[LinkMan2] = @linkman2
      ,[LinkTel2] = @linktel2
      ,[LinkMobile2] = @linkmobile2
      ,[SaleZekou] = cast(@salezekou1  as  numeric(24, 10))
      ,[BuyZekou] = cast(@buyzekou1 as  numeric(24, 10))
      ,[PyCode] = @pycode
      ,[Price] = @CheckPrice 
      ,[PriceTrackEnable] =@Checkpricetrackenable1
      ,[etypeid] = @newzy
      ,[buyprice] = @Checkbuyprice
      ,[sheng] = @sheng
      ,[shi] = @shi
      ,[xian] = @xian
      ,[blevel] = @blevel
      ,[denominatedid]=@newjsdw
 WHERE UserCode=@usercode

if @@rowcount=0 
begin
	rollback tran insertproc 
	SET @ErrMsg = '添加失败'
	RETURN -1
end 

COMMIT TRAN insertproc

GO





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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
	作者：陈强
	日期：2019-11-05
	描述：9.91新功能，客户信息覆盖导入
*/
CREATE	PROCEDURE [dbo].[GP_BtypeKCoverImport]
(
		@usercode			varchar(256),	--客户编号
		@fullname			varchar(256),	--客户名称
		@name				varchar(256),	--简名
		@pycode				varchar(256),	--拼音码
		@ausercode			varchar(256),	--地区编号
		@area				varchar(256),	--地区
		@etypeid            varchar(256),	--关联职员ID
		@etypename          varchar(256),	--职员名称
		@buypride           varchar(256),	--适用进价类型
		@salezekou          varchar(256),	--销售折扣
		@buyzekou           varchar(256),	--采购折扣
		@price              varchar(256),	--适用售价类型
		@denominatedid      varchar(256),	--结算单位编号
		@dename             varchar(256),	--结算单位名称
		@pricetrackenable1  varchar(256),	--启用价格跟踪
		@tel1               varchar(256),	--电话1
		@tel2               varchar(256),	--电话2
		@tel3               varchar(256),	--电话3
		@www                varchar(256),	--网络地址
		@email              varchar(256),	--电子邮件
		@fax                varchar(256),	--传真
		@postcode           varchar(256),	--邮编
		@sheng              varchar(256),	--省
		@shi                varchar(256),	--市
		@xian               varchar(256),	--区/县
		@telandaddress      varchar(256),	--详细地址
		@blevel             varchar(256),	--单位等级
		@bank               varchar(256),	--银行户名
		@taxnumber          varchar(256),	--税号
		@bankname           varchar(256),	--开户银行
		@bankandacount      varchar(256),	--银行账号
		@comment            varchar(256),	--备注
		@linkman1           varchar(256),	--联系人1
		@linkmobile1        varchar(256),	--联系人1手机
		@linktel1           varchar(256),	--联系人1电话
		@linkman2           varchar(256),	--联系人2	
		@linkmobile2        varchar(256),	--联系人2手机
		@linktel2           varchar(256),	--联系人2电话
		@ErrMsg VARCHAR(200) OUTPUT			--返回错误信息
)
AS
SET NOCOUNT ON
---------------------------------基础验证-------------------------------------
IF(@usercode = '')
BEGIN
	SET @ErrMsg = '客户编号不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF lower(LTrim(RTrim(Replace(@usercode,' ',''))))='abc' OR lower(LTrim(RTrim(Replace(@usercode,' ',''))))=lower('KH')
	OR lower(LTrim(RTrim(Replace(@usercode,' ',''))))=lower('DL')
	BEGIN
		SET @ErrMsg = '客户编号与系统保留编号冲突，请检查编号是否有误!'
		RETURN -1
	END
END

IF(@fullname = '')
BEGIN
	SET @ErrMsg = '客户名称不能为空'
	RETURN -1
END

--验证地区信息
DECLARE @dqsoncount varchar(50)
DECLARE @newdq varchar(100)

IF ISNULL(@ausercode,'')<>''
BEGIN
	SELECT @dqsoncount=sonnum from AreaType where usercode=@ausercode and parid<>'root'
	
	IF ISNULL(@dqsoncount,'')='' OR @dqsoncount<>0	--不存在地区信息 或者 是父节点
	BEGIN
		IF ISNULL(@dqsoncount,'')='' 
		BEGIN
			SET @ErrMsg = '地区信息不存在，请检查地区编号是否有误!'
			RETURN -1
		END
		
		IF @dqsoncount<>0
		BEGIN
			SET @ErrMsg = '不能选择父节点为地区信息，请检查地区编号是否有误!'
			RETURN -1
		END
	END
	SELECT @newdq=typeid from AreaType where UserCode=@ausercode
END
ELSE
BEGIN
	SET @newdq=''
END	

--验证职员信息
DECLARE @zysonnum varchar(100)
DECLARE @newzy varchar(100)

IF ISNULL(@etypeid,'')<>''
BEGIN
	SELECT @zysonnum=sonnum from employee where usercode=@etypeid and parid<>'root'

	IF ISNULL(@zysonnum,'')='' OR @zysonnum<>0	--不存在职员信息 或者 是父节点
	BEGIN
		IF ISNULL(@zysonnum,'')=''
		BEGIN
			SET @ErrMsg = '职员信息不存在，请检查职员编号是否有误!'
			RETURN -1
		END
		
		IF @zysonnum<>0
		BEGIN
			SET @ErrMsg = '职员信息不能为大类，请检查职员编号是否有误!'
			RETURN -1
		END
	END
	SELECT @newzy=typeid from employee where UserCode=@etypeid
END
ELSE
BEGIN
	SET @newzy=''
END	


----销售折扣、采购折扣
DECLARE @d_discount                VARCHAR(5),   --  扣率小数位数
		@d_discount1               INT ;         --  扣率小数位数
	                          
SELECT @d_discount= DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 4
SET @d_discount1= CONVERT(INT,@d_discount)

DECLARE @salezekou1  NUMERIC(24, 4) 
IF (@salezekou = '' ) 
BEGIN
    SET @salezekou1 = 1
END

IF (ISNUMERIC(@salezekou) <> 1 ) 
BEGIN
	SET @ErrMsg = '销售折扣请输入数字'
	RETURN -1
END

IF ((SELECT CHARINDEX('-', @salezekou)) <> 0 ) 
BEGIN
	SET @ErrMsg = '销售折扣不能为负数'
	RETURN -1
END
ELSE 
BEGIN
SELECT  @salezekou1 = CONVERT( NUMERIC(24, 4) , @salezekou)
IF dbo.F_CheckDecimal(@salezekou1,4,@d_discount1) < 0
BEGIN
	SET @ErrMsg='销售折扣值多于'+@d_discount+'位小数'
	RETURN -1;
END
IF ( @salezekou1 < 0 OR @salezekou1 > 1) 
BEGIN
    SET @ErrMsg = '销售折扣输入错误'
    RETURN -1
END
IF @salezekou1 = 0
BEGIN
	SET @ErrMsg = '销售折扣输入错误'
    RETURN -1
END
END

DECLARE @buyzekou1  NUMERIC(24, 4) 
IF ISNULL(@buyzekou,'') = '' 
BEGIN
    SET @buyzekou1 = 1
END

IF ISNUMERIC(@buyzekou) <> 1 
BEGIN
    SET @ErrMsg = '采购折扣请输入数字'
    RETURN -1
END

IF ((SELECT   CHARINDEX('-', @buyzekou)) <> 0 ) 
BEGIN
    SET @ErrMsg = '采购折扣不能为负数'
    RETURN -1
END
ELSE 
BEGIN
SELECT  @buyzekou1 = CONVERT( NUMERIC(24, 4) , @buyzekou)
IF (@buyzekou1 < 0 OR @buyzekou1 > 1) 
BEGIN
    SET @ErrMsg = '采购折扣输入错误'
    RETURN -1
END
IF dbo.F_CheckDecimal(@buyzekou1,4,@d_discount1) < 0
BEGIN
	SET @ErrMsg='采购折扣值多于'+@d_discount+'位小数'
	RETURN -1;
END
IF @buyzekou1=0
BEGIN
	SET @ErrMsg = '采购折扣输入错误'
    RETURN -1
END
END


DECLARE @PostCodeLen INT
SELECT  @PostCodeLen = LEN(@postcode)
IF (@PostCodeLen > 200 ) 
BEGIN
    SET @ErrMsg = '邮编不能超过200字符'
    RETURN -1
END

--适用进价判断
DECLARE @Checkbuyprice VARCHAR(50)
SELECT  @Checkbuyprice = CASE @buypride
                      WHEN '无' THEN '0'
                      WHEN '' THEN '0'
                      WHEN '预设进价1' THEN '1'
                      WHEN '预设进价2' THEN '2'
                      WHEN '预设进价3' THEN '3'
                      WHEN '预设进价4' THEN '4'
                      WHEN '预设进价5' THEN '5'
                      WHEN '最高进价' THEN '6'
                      WHEN '零售价' THEN '7'
                      ELSE 'ERROR'
                    END
IF (@Checkbuyprice = 'ERROR' ) 
    BEGIN
        SET @ErrMsg = '适用进价不匹配'
        RETURN -1
    END

--适用售价判断
DECLARE @CheckPrice VARCHAR(50)
SELECT  @CheckPrice = CASE @price
                   WHEN '无' THEN '0'
                   WHEN '' THEN '0'
                   WHEN '预设售价1' THEN '1'
                   WHEN '预设售价2' THEN '2'
                   WHEN '预设售价3' THEN '3'
                   WHEN '预设售价4' THEN '4'
                   WHEN '预设售价5' THEN '5'
                   WHEN '预设售价6' THEN '6'
                   WHEN '预设售价7' THEN '7'
                   WHEN '预设售价8' THEN '8'
                   WHEN '预设售价9' THEN '9'
                   WHEN '预设售价10' THEN '10'
                   WHEN '零售价' THEN '11'
                   WHEN '最高售价' THEN '12'
                   WHEN '最低售价' THEN '13'
                   ELSE 'ERROR'
                 END
IF (@CheckPrice = 'ERROR' ) 
BEGIN
    SET @ErrMsg = '适用售价不匹配'
    RETURN -1
END


--启用价格跟踪
DECLARE @Checkpricetrackenable1 varchar(50)
SELECT  @Checkpricetrackenable1 = CASE @pricetrackenable1
                   WHEN '是' THEN '1'
                   WHEN '否' THEN '0'
                   WHEN '' THEN '0'
                   ELSE 'ERROR'
                 END
IF (@Checkpricetrackenable1 = 'ERROR' ) 
BEGIN
    SET @ErrMsg = '启用价格跟踪不匹配!'
    RETURN -1
END

---验证客户编号、客户名称重复
DECLARE @usercf varchar(50)	--验证是否有相同的usercode
DECLARE @CheckFlag varchar(50)
select @CheckFlag=value from Userconfig where ConfigName='equalbidname'
IF @CheckFlag<>1--不允许重复
begin
	if NOT exists(select TypeID from [btype] where usercode=@usercode and deleted<>1)
	begin
		SET @ErrMsg = @fullname + '该客户编号不存在，无法覆盖导入!'
		RETURN -1
	END

	if exists(select TypeID from [btype] where (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @usercode + '使用，请更换或删除该停用的编号'
		RETURN -1
	end
	
	if exists(select TypeID from [btype] where (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的'+@FullName+'客户使用，请更换或删除该停用的编号'
		RETURN -1
	end
	
	if exists(select TypeID from [btype] where UserCode<>@usercode and fullname=@fullname and deleted<>1)
	begin
		SET @ErrMsg = '该客户名称【' + @FullName + '】已经存在，客户名称不能相同!'
		RETURN -1
	end
	
end
else
begin
	if exists(select TypeID from [btype] where usercode=@usercode  and deleted=1)
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @usercode + '使用，请更换或删除该停用的编号'
		RETURN -1
	end
	
	if NOT exists(select TypeID from [btype] where usercode=@usercode and deleted<>1)
	begin
		SET @ErrMsg = @fullname + '该客户编号不存在，无法覆盖导入!'
		RETURN -1
	END
	
	SELECT @usercf=COUNT(1) from btype  where usercode=@usercode 
	IF @usercf>1
	BEGIN
		SET @ErrMsg = '该【' + @FullName + '】的编号已存在!'
		RETURN -1
	END
end


DECLARE @jsdwcheck varchar(100);
DECLARE @sumNum int
DECLARE @newjsdw varchar(100)
DECLARE @parement_check int

--验证结算单位
IF @denominatedid<>''
BEGIN
	SELECT @jsdwcheck=LEFT(parid,5),@sumNum=sonnum from btype where usercode=@denominatedid
	SELECT TOP 1 @parement_check=sonnum FROM btype WHERE UserCode=@usercode
	
	IF ISNULL(@jsdwcheck,'')<>''	--代表库中存在
	BEGIN
		IF @jsdwcheck<>'00001' 
		BEGIN
			SET @ErrMsg = '该客户选择的结算单位无效! 请确认结算单位编号是否有误!';
			RETURN -1;
		END
		
		--验证客户是否是父类(父类不进行判断结算单位)
		IF @parement_check=0
		BEGIN
			IF @sumNum<>0
			BEGIN
				SET @ErrMsg = '该客户选择的结算单位无效! 结算单位不能为父节点!';
				RETURN -1;
			END
		END 
	END
	ELSE	--库中不存在
	BEGIN
		SET @ErrMsg = '该结算单位不存在，请检查结算单位编号是否有误!';
		RETURN -1;
	END
	SELECT @newjsdw=typeid from btype where usercode=@denominatedid
END
ELSE
BEGIN
	SELECT TOP 1 @newjsdw=typeid from btype where usercode=@usercode
END

--------------------------------基础验证结束----------------------------------
BEGIN TRAN insertproc
UPDATE [btype] SET 
      [FullName] =@fullname
      ,[Name] = @name
      ,[AreaTypeID] = @newdq
      ,[TelAndAddress] = @telandaddress
      ,[PostCode] = @postcode 
      ,[BankAndAcount] = @bankandacount
      ,[Comment] = @comment
	  ,[TaxNumber] = @taxnumber
      ,[Tel1] = @tel1
      ,[Tel2] = @tel2
      ,[Tel3] = @tel3
      ,[Fax] = @fax
      ,[WWW] = @www
      ,[Bank] = @bank
      ,[BankName] = @bankname
      ,[Email] = @email
      ,[LinkMan1] =@linkman1
      ,[LinkMobile1] = @linkmobile1
      ,[LinkTel1] = @linktel1
      ,[LinkMan2] = @linkman2
      ,[LinkTel2] = @linktel2
      ,[LinkMobile2] = @linkmobile2
      ,[SaleZekou] = cast(@salezekou1  as  numeric(24, 10))
      ,[BuyZekou] = cast(@buyzekou1 as  numeric(24, 10))
      ,[PyCode] = @pycode
      ,[Price] = @CheckPrice 
      ,[PriceTrackEnable] =@Checkpricetrackenable1
      ,[etypeid] = @newzy
      ,[buyprice] = @Checkbuyprice
      ,[sheng] = @sheng
      ,[shi] = @shi
      ,[xian] = @xian
      ,[blevel] = @blevel
      ,[denominatedid]=@newjsdw
 WHERE UserCode=@usercode

if @@rowcount=0 
begin
	rollback tran insertproc 
	SET @ErrMsg = '添加失败'
	RETURN -1
end 

COMMIT TRAN insertproc

GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_BuyBackBill_CreateBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_BuyBackBill_CreateBill]
GO




/*

功能说明：		采购退货单过帐后生成销售退货单的草稿

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_BuyBackBill_CreateBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
*/	
	
DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT


SELECT @intReturnID=0

DECLARE 
	@strBuyBTypeID					VARCHAR(50),		--采购的信息	
	@strBuySTypeID					VARCHAR(50),		--采购对应的分支机构
	@strSaleBTypeID					VARCHAR(50),		--销售
	@strSaleSTypeID					VARCHAR(50),
	@decTax							 NUMERIC(24, 10) ,
	@strFromBillCode 				VARCHAR(100),
	@datBillDate					DATETIME,
	@strSaleETypeID						VARCHAR(100),
	@ceCheckId			VARCHAR(100),
	@ceDtypeid			VARCHAR(100),
	@cefullname			VARCHAR(500)='',		--制单人
	@cdfullname			VARCHAR(500)=''			--部门

SELECT 
	@strBuyBTypeID=a.DealBTypeID,@strBuySTypeID=a.sTypeId,@ceCheckId=checke,@ceDtypeid=DTypeId,
	@strSaleBTypeID=c.BTypeID1,@strSaleSTypeID=b.typeid,
	@decTax=a.tax,@strFromBillCode=a.BillCode,@datBillDate=a.BillDate
FROM BillIndex a
INNER JOIN SType b 
ON a.Dealbtypeid=b.btypeId2
INNER JOIN SType c
ON a.Stypeid=c.TypeId 
WHERE a.BillNumberId=@nBillID

SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

--判断是否属于分支机构间的采购,销售
IF NOT EXISTS(SELECT TypeID FROM SType WHERE TypeId=@strSaleSTypeID AND @strSaleSTypeID IS NOT NULL AND sonnum=0)
BEGIN
	SET @strErrMsg='该单据不是分支机构间的采购销售！'
	RETURN
END


IF NOT EXISTS(SELECT TypeID FROM SType WHERE BTypeID1=@strSaleBTypeID AND @strSaleBTypeID IS NOT NULL)
BEGIN
	SET @strErrMsg='该单据不是分支机构间的采购销售！'
	RETURN
END


IF EXISTS(SELECT BillNumberId FROM BillIndex WHERE FromBillNumberID=@nBillID  AND BillType=45)
BEGIN
	SET @strErrMsg='该采购退货单已生成有相应的销售退货单草稿！'	
	RETURN
END

IF ISNULL(@strSaleSTypeID,'')='' OR ISNULL(@strSaleBTypeID,'')='' RETURN

DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号


DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@ETypeID			VARCHAR(100),
	@KTypeID			VARCHAR(100),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@intBillType		INT

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT
	@ETypeID='',
	@KTypeID='',
	@VchHead='XT',
	@intBillType=45

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = TypeId FROM Employee WHERE TypeID = @ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
	SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @chvOpID
END

SELECT 
	@MONTH=ISNULL(@MONTH,''),
	@DAY=ISNULL(@DAY,'')


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strSaleSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname

IF @Re <> 0
RETURN -2	



--SELECT @strBillCode='tmpxsthd'  --因为单据编号要调整，暂时屏蔽生成单据编号那段代码

DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000)
	
	
SELECT 
	@strComment='该销售退货单是从采购退货单'+@strFromBillCode+'生成而来的！'

--生成采购入库单的草稿
--生成表头

DECLARE
	@strdenominatedid VARCHAR(50)
	
SELECT 	@strdenominatedid=denominatedid
FROM BType
WHERE typeId=@strSaleBTypeID

DECLARE
	@strTempATypeID		VARCHAR(100)
	
SELECT
	@strTempATypeID=ATypeID
FROM BillAtype
WHERE BillTypeId='45'
AND StypeId=@strSaleSTypeID

SELECT @strTempATypeID=ISNULL(@strTempATypeID,'')

INSERT BillIndex(BillDate,BillCode,BillType,DealBTypeID,BTypeID,STypeID,KTypeID,ETypeID,
ATypeID,KTypeID2,KTypeID3,Comment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,AlertDay,DTypeId,CostSale,FromBillNumberID,
ifcheck,IfAudit,draft,OrderId,checke,NTotalMoney,CID,Rate,ATypeID1)
SELECT BillDate,@strBillCode,@intBillType,@strSaleBTypeID,@strdenominatedid,@strSaleSTypeID,
'','','','','',@strComment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,AlertDay,'',CostSale,BillNumberId,
'f',0,1,0,'',NTotalMoney,CID,Rate,@strTempATypeID
FROM BillIndex
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();


--生成表体

INSERT saleBackBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,OutFactoryDate,
TaxPrice,TaxTotal,comment,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,
GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,SaleTotal,Tax,KTypeID,Stypeid,
FromBillNumberID,FromBillID,
TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,
NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,ShowOrder,ETypeID)
SELECT @intReturnID,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,OutFactoryDate,
TaxPrice,TaxTotal,comment,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,
GoodsBTypeID,-1,0,SaleTotal,Tax,'',@strSaleSTypeID,
BillNumberID,ID,
TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,
NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,0,ItemID,IsCombined,IsGift,ShowOrder,''
FROM BuyBackBill
WHERE BillNumberId=@nBillID

--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END

-- 自动生成的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @intReturnID,@intBillType


GO





Go

IF EXISTS(SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'GP_BuyGoodsExchangeCheck',N'P'))
BEGIN
	DROP PROC GP_BuyGoodsExchangeCheck
END
GO
/*
	采购换货单按单退货数量检查
*/
CREATE PROC GP_BuyGoodsExchangeCheck
(
	@Details TBType_BuyGoodsExchange READONLY
)
--@encode$--
AS
BEGIN
		SELECT 1 AS RET FROM BuyBill A JOIN @Details B ON A.BillNumberId=B.OldBillNumberId AND A.Id=B.OldId
		WHERE B.OldBillNumberId<>0 AND ISNULL(A.Qty,0)-ISNULL(A.Backqty,0)<B.Qty 
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_BuyOrderBill_CreateBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_BuyOrderBill_CreateBill]
GO




/*

功能说明：		采购订单生成销售订单的草稿

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_BuyOrderBill_CreateBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
	
*/

DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT


SELECT @intReturnID=0

DECLARE 
	@strBuyBTypeID					VARCHAR(50),		--采购的信息	
	@strBuySTypeID					VARCHAR(50),		--采购对应的分支机构
	@strSaleBTypeID					VARCHAR(50),		--销售
	@strSaleSTypeID					VARCHAR(50),
	@decTax							 NUMERIC(24, 10) ,
	@strFromBillCode 				VARCHAR(100),
	@ETypeID			VARCHAR(100)='',
	@KTypeID			VARCHAR(100)='',
	@datBillDate					DATETIME,
	@ceDtypeid			VARCHAR(100),
	@cdfullname			VARCHAR(500)=''			--部门

SELECT 
	@strBuyBTypeID=a.DealBTypeID,@strBuySTypeID=a.sTypeId,@ceDtypeid=DTypeId,
	@strSaleBTypeID=c.BTypeID1,@strSaleSTypeID=b.typeid,
	@decTax=a.tax,@strFromBillCode=a.BillCode,@datBillDate=a.BillDate
FROM OrderIndex a
INNER JOIN SType b 
ON a.DealBTypeID=b.btypeId2
INNER JOIN SType c
ON a.Stypeid=c.TypeId
WHERE a.BillNumberId=@nBillID

SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

--判断是否属于分支机构间的采购,销售
IF NOT EXISTS(SELECT TypeID FROM SType WHERE TypeId=@strSaleSTypeID AND @strSaleSTypeID IS NOT NULL AND sonnum=0)
BEGIN
	SET @strErrMsg='该单据不是分支机构间的采购销售！'
	RETURN
END


IF NOT EXISTS(SELECT TypeID FROM SType WHERE BTypeID1=@strSaleBTypeID AND @strSaleBTypeID IS NOT NULL)
BEGIN
	SET @strErrMsg='该单据不是分支机构间的采购销售！'
	RETURN
END


IF EXISTS(SELECT BillNumberId FROM OrderIndex WHERE FromBillNumberID=@nBillID)
BEGIN
	SET @strErrMsg='该采购订单已生成有相应的销售订单草稿！'	
	RETURN
END

IF ISNULL(@strSaleSTypeID,'')='' OR ISNULL(@strSaleBTypeID,'')='' RETURN

DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号

/*

生成新的单据编号

DECLARE
	@strTempSID			VARCHAR(100),
	@strTempDID			VARCHAR(100),
	@strTempEID			VARCHAR(100)

SELECT @strTempSID=@strBuySTypeID

SELECT @strTempEID=''

SELECT @strTempDID='',@strTempEID=''

DECLARE
	@intNewSeed		BigInt



EXEC GP_CreateBillCode
	'',
	@strTempSID,
	@datBillDate,
	@intBillType,
	1,
    @strBillCode OUT,
    @intNewSeed OUT,
    @strErrMsg OUT
*/

DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@intBillType		INT,
	@cefullname			VARCHAR(500)=''

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT @VchHead='XD',
	@intBillType=300

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = TypeId FROM Employee WHERE TypeID = @ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
	SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
END
ELSE
BEGIN
	SELECT 
	@MONTH=ISNULL(@MONTH,''),
	@DAY=ISNULL(@DAY,'')
END


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strSaleSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname

IF @Re <> 0
RETURN -2	


--SELECT @strBillCode='tmpxsdd'  --因为单据编号要调整，暂时屏蔽生成单据编号那段代码

DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000)
	
	
SELECT 
	@strComment='该销售订单是从采购订单'+@strFromBillCode+'生成而来的！'
	
	
--生成的草稿
--生成表头

DECLARE
	@strdenominatedid VARCHAR(50)
	
SELECT 	@strdenominatedid=denominatedid
FROM BType
WHERE typeId=@strSaleBTypeID


INSERT OrderIndex(BillDate,BillCode,BillType,DealBTypeID,BTypeID,STypeID,KTypeID,ETypeID,
Comment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,DTypeId,FromBillNumberID,
IfAudit,checke,CustomerTotal,NCustomerTotal,ReachDate,NTotalMoney,CID,Rate)
SELECT BillDate,@strBillCode,@intBillType,@strSaleBTypeID,@strdenominatedid,@strSaleSTypeID,
'' AS KTypeID,'',@strComment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,'',BillNumberId,
0,checke,CustomerTotal,NCustomerTotal,ReachDate,NTotalMoney,CID,Rate
FROM OrderIndex
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();

--表头自定义
INSERT INTO Custom_BillIndex (BillId, BillType, SysDiy1_head, SysDiy2_head, SysDiy3_head, SysDiy4_head, SysDiy5_head, SysDiy6_head, SysDiy7_head, SysDiy8_head, SysDiy9_head, SysDiy10_head, SysDiy11_head, SysDiy12_head, SysDiy13_head, SysDiy14_head, SysDiy15_head, SysDiy16_head, SysDiy17_head, SysDiy18_head, SysDiy19_head, SysDiy20_head, SysDiy21_head, SysDiy22_head, SysDiy23_head, SysDiy24_head, SysDiy25_head, SysDiy26_head, SysDiy27_head, SysDiy28_head, SysDiy29_head, SysDiy30_head, SysDiy31_head, SysDiy32_head, SysDiy33_head, SysDiy34_head, SysDiy35_head, SysDiy36_head, SysDiy37_head, SysDiy38_head, SysDiy39_head, SysDiy40_head)
SELECT	@intReturnID, @intBillType, SysDiy1_head, SysDiy2_head, SysDiy3_head, SysDiy4_head, SysDiy5_head, SysDiy6_head, SysDiy7_head, SysDiy8_head, SysDiy9_head, SysDiy10_head, SysDiy11_head, SysDiy12_head, SysDiy13_head, SysDiy14_head, SysDiy15_head, SysDiy16_head, SysDiy17_head, SysDiy18_head, SysDiy19_head, SysDiy20_head, SysDiy21_head, SysDiy22_head, SysDiy23_head, SysDiy24_head, SysDiy25_head, SysDiy26_head, SysDiy27_head, SysDiy28_head, SysDiy29_head, SysDiy30_head, SysDiy31_head, SysDiy32_head, SysDiy33_head, SysDiy34_head, SysDiy35_head, SysDiy36_head, SysDiy37_head, SysDiy38_head, SysDiy39_head, SysDiy40_head
FROM	Custom_BillIndex
WHERE	BillId  = @nBillID

--生成表体
--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	INSERT OrderBill(BillNumberId,PtypeId,Price,Qty,discount,DiscountPrice,total,
	TaxPrice,TaxTotal,comment,IsUnit2,
	SaleTotal,Tax,KTypeID,Stypeid,
	FromBillNumberID,FromBillID,
	TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,
	NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
	CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,ItemID,IsCombined,GoodsNumber,IsGift,GoodsCostPrice,ShowOrder,ProduceDate,ValidDate,CargoID)
	SELECT @intReturnID,PtypeId,Price,Qty,discount,DiscountPrice,total,
	TaxPrice,TaxTotal,comment,IsUnit2,
	SaleTotal,Tax,'' AS KTypeID,@strSaleSTypeID,
	BillNumberID,OrderID,
	TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,
	NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
	CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,ItemID,IsCombined,GoodsNumber,IsGift,-1,ShowOrder,ProduceDate,ValidDate,CargoID
	FROM OrderBill
	WHERE BillNumberId=@nBillID
END
ELSE
BEGIN
	INSERT OrderBill(BillNumberId,PtypeId,Price,Qty,discount,DiscountPrice,total,
	TaxPrice,TaxTotal,comment,IsUnit2,
	SaleTotal,Tax,KTypeID,Stypeid,
	FromBillNumberID,FromBillID,
	TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,
	NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
	CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,ItemID,IsCombined,GoodsNumber,IsGift,GoodsCostPrice,ShowOrder,ProduceDate,ValidDate,CargoID)
	SELECT @intReturnID,PtypeId,Price,Qty,discount,DiscountPrice,total,
	TaxPrice,TaxTotal,comment,IsUnit2,
	SaleTotal,Tax,'' AS KTypeID,@strSaleSTypeID,
	BillNumberID,OrderID,
	TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,
	NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
	CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,ItemID,IsCombined,GoodsNumber,IsGift,-1,ShowOrder,ProduceDate,ValidDate,CargoID
	FROM OrderBill
	WHERE BillNumberId=@nBillID
END

--表体自定义
INSERT INTO Custom_BillDetails (BillId, Detailid, BillType, SysDiy1, SysDiy2, SysDiy3, SysDiy4, SysDiy5, SysDiy6, SysDiy7, SysDiy8, SysDiy9, SysDiy10, SysDiy11, SysDiy12, SysDiy13, SysDiy14, SysDiy15, SysDiy16, SysDiy17, SysDiy18, SysDiy19, SysDiy20, SysDiy21, SysDiy22, SysDiy23, SysDiy24, SysDiy25, SysDiy26, SysDiy27, SysDiy28, SysDiy29, SysDiy30, SysDiy31, SysDiy32, iscombination, InOrOut, SysDiy33, SysDiy34, SysDiy35, SysDiy36, SysDiy37, SysDiy38, SysDiy39, SysDiy40)
SELECT	O.billNumberID, O.OrderID, @intBillType, SysDiy1, SysDiy2, SysDiy3, SysDiy4, SysDiy5, SysDiy6, SysDiy7, SysDiy8, SysDiy9, SysDiy10, SysDiy11, SysDiy12, SysDiy13, SysDiy14, SysDiy15, SysDiy16, SysDiy17, SysDiy18, SysDiy19, SysDiy20, SysDiy21, SysDiy22, SysDiy23, SysDiy24, SysDiy25, SysDiy26, SysDiy27, SysDiy28, SysDiy29, SysDiy30, SysDiy31, SysDiy32, iscombination, InOrOut, SysDiy33, SysDiy34, SysDiy35, SysDiy36, SysDiy37, SysDiy38, SysDiy39, SysDiy40
FROM	OrderBill O
INNER JOIN Custom_BillDetails C ON C.BillId = O.FromBillNumberId AND O.FromBillId = C.Detailid
WHERE	O.billNumberID = @intReturnID

--影响订单库存
EXEC GP_Deal_OrderQTY @intReturnID,@intBillType,'+'

--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END


GO


/*

DECLARE
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0),			--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100),
	@strErrMsg				VARCHAR(100)			--出错信息
	
SELECT
	@chvOpID=1,
	@nBillID=3	
	
	

EXEC	GP_BuyOrderBill_CreateBill
	@chvOpID,
	@nBillID,
	@intReturnID OUT,
	@strReturnBillCode OUT,
	@strErrMsg OUT

SELECT @strReturnBillCode,@strErrMsg

*/





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_BuyOrderToBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_BuyOrderToBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：谢吉康
--	日期：2019-11-04
--	描述：未完成的采购订单生成采购入库单
---------------------------------------------
CREATE PROCEDURE GP_BuyOrderToBill
( 
	@OperatorID		VARCHAR(50),
	@orderid		VARCHAR(MAX),
	@ifetype		VARCHAR(10),
	@ifktype		VARCHAR(10),
	@clientip		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #SType(TypeId	varchar(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorID)

--往来单位
CREATE TABLE #BType(TypeId	varchar(100))
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)

--仓库
CREATE TABLE #KType(TypeId	varchar(100))
INSERT INTO #KType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)	

--职员
CREATE TABLE #EType(TypeId	varchar(100))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)	

--商品
CREATE TABLE #PType(TypeId	varchar(100))
INSERT INTO #PType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@OperatorID)	


----BEGIN---------------------判断是否存在未完成的订单，处理出库单过账后未完成订单没有刷新页面的同步操作情况-------------------------

IF EXISTS(SELECT 1 FROM dbo.OrderIndex a INNER JOIN dbo.OrderBill b ON a.billNumberId = b.billNumberID 
			WHERE OrderState='1' AND b.OrderID IN (SELECT * FROM f_split(@orderid,',')))
BEGIN
	RAISERROR('存在已完成的单据，请刷新页面重试！',16,1) 
	RETURN 
END

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

--草稿库存
CREATE TABLE #DraftGoodsStocks
(
	PTypeId			VARCHAR(100),
	KTypeId			VARCHAR(100),
	Qty				 NUMERIC(24, 10) ,
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) ,
	SaleReachQty	 NUMERIC(24, 10) ,
	BuyReachQty		 NUMERIC(24, 10) 
)


CREATE TABLE #OrderBillNumberID
(
	id	VARCHAR(1000)
)

CREATE TABLE #atypeid1(id VARCHAR(1000),NAME VARCHAR(1000),flag varchar(10))


INSERT INTO #OrderBillNumberID (id)
SELECT billNumberID FROM OrderBill WHERE OrderID IN (SELECT *FROM f_split(@orderid,',')) GROUP BY billNumberID


CREATE TABLE #MANTYPE
(	
	GoodsNumber VARCHAR(50),
	rate		VARCHAR(50),
	cid			VARCHAR(50),
	stypeid		VARCHAR(50),
	btypeid		VARCHAR(50),
	dealbtypeid VARCHAR(50),
	dtypeid		VARCHAR(50),	
	etypeid		VARCHAR(50),
	ktypeid		VARCHAR(50)	
)

DECLARE @SQL VARCHAR(MAX)
DECLARE @colname	VARCHAR(MAX)
DECLARE @GroupByCol	VARCHAR(MAX)
DECLARE @atypeid1 VARCHAR(max)

SET @colname='a.GoodsNumber,a.rate,a.cid as cid,a.stypeid AS stypeid,ISNULL(a.btypeid,'''') AS btypeid,ISNULL(a.dealbtypeid,'''') AS dealbtypeid,
				ISNULL(a.dtypeid,'''') as dtypeid '

SET @GroupByCol='a.GoodsNumber,a.rate,a.cid,a.stypeid,a.btypeid,a.dealbtypeid,a.dtypeid '

IF @ifetype='1'
	BEGIN
		SET @colname=@colname+',a.etypeid AS etypeid'
		SET @GroupByCol=@GroupByCol+',a.etypeid '
	END
ELSE
	SET @colname=@colname+','''' AS etypeid'
IF @ifktype='1'
	BEGIN
		SET @colname=@colname+',a.ktypeid AS ktypeid'
		SET @GroupByCol=@GroupByCol+',a.ktypeid '
	END
ELSE
	SET @colname=@colname+','''' AS ktypeid'

SET @SQL='
INSERT INTO #MANTYPE(GoodsNumber,rate,cid,stypeid,btypeid,dealbtypeid,dtypeid,etypeid,ktypeid)
SELECT '+@colname+'
FROM orderindex a
INNER JOIN #OrderBillNumberID b ON b.id=a.billNumberID
GROUP BY '+@GroupByCol
--PRINT(@sql)
EXEC (@SQL)

DECLARE @billdate		DATETIME,
		@billcode		VARCHAR(MAX),
		@stypeid		VARCHAR(MAX),
		@etypeid		VARCHAR(MAX),
		@btypeid		VARCHAR(MAX),
		@dtypeid		VARCHAR(max),
		@ktypeid		VARCHAR(MAX),
		@totalmoney		NUMERIC(24, 10) ,
		@totalqty		NUMERIC(24, 10) ,
		@tax			NUMERIC(24, 10) ,
		@BillNumberId	NUMERIC(24, 10) ,
		@DAY			VARCHAR(MAX),
		@MONTH			VARCHAR(MAX),
		--以下参数用于处理明细超过500条的情况
		@rowcount		INT,	--明细总行数
		@maxcount		INT,	--明细最大行数（500条）
		@pagecount		INT,		--明细页数
		@dealbtypeid	VARCHAR(100),--结算单位
		@cid			VARCHAR(100),
		@rate			VARCHAR(100),
		@GoodsNumber	VARCHAR(100),
		@intQtyDot		INT,
		@cefullname		VARCHAR(500)='',
		@dfullname		VARCHAR(500)='',
		@explain		VARCHAR(2000)=''
		
		
SET @rowcount=0
SET @maxcount=500
SET @pagecount=0

--数量的小数位数
EXEC	@intQtyDot=Gp_GetDigit 1
		
CREATE TABLE #billnumberid(ID VARCHAR(MAX))

DECLARE @billtype	VARCHAR(10)
SET @billtype='34'
--取当前时间
SET @billdate=GETDATE()
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
SET @billdate=(SELECT CONVERT (VARCHAR(10),@billdate,120))

SET @SQL='
DECLARE indexcursor CURSOR FOR 
	SELECT  '+@colname+',
			SUM(b.qty-b.ReachQty) AS totalqty,
			ROUND(SUM((b.qty-b.ReachQty)*taxprice),2) AS totalmoney
	FROM	#MANTYPE a
	INNER JOIN ORDERINDEX I ON  I.Stypeid=a.stypeid AND ISNULL(I.dealbtypeid,'''')=ISNULL(a.dealbtypeid,'''') AND ISNULL(I.btypeid,'''')=ISNULL(a.btypeid,'''') and (a.dtypeid='''' or I.dtypeid=a.dtypeid) AND (a.etypeid='''' OR I.etypeid=a.etypeid) AND (a.ktypeid='''' OR I.ktypeid=a.Ktypeid)
	INNER JOIN OrderBill B ON I.billNumberId=B.billNumberID
	WHERE (b.qty-b.ReachQty)<>0 and B.OrderID IN (SELECT *FROM f_split('''+@orderid+''','','')) 
	GROUP BY '+@GroupByCol

EXEC (@SQL)

OPEN indexcursor

FETCH NEXT FROM indexcursor INTO	@GoodsNumber,
									@rate,
									@cid,
									@sTypeID,
									@BTypeID,
									@dealbtypeid,
									@dtypeid,									
									@eTypeID,
									@kTypeID,
									@totalqty,
									@totalmoney--@tax


WHILE @@FETCH_STATUS=0
BEGIN
	--是否自定义单据编号
	IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =34)
	BEGIN
		SELECT @MONTH = Typeid  FROM employee WHERE typeId=@ETypeId
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @OperatorID
		SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId = @dtypeid
	END
		
	SELECT @rowcount=COUNT(1)
	FROM	OrderBill a
	INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
	WHERE	A.OrderID IN (SELECT * FROM f_split(@orderid,','))
	AND		I.Stypeid=@Stypeid
	AND		ISNULL(I.dealbtypeid,'')=ISNULL(@dealbtypeid,'')
	AND		ISNULL(I.DtypeId,'')=ISNULL(@dtypeid,'')
	AND		(@Etypeid='' OR I.Etypeid=@Etypeid)
	AND		(@Ktypeid='' OR I.Ktypeid=@Ktypeid)
	AND		(a.qty-a.ReachQty)>0
	
	SET @pagecount=@rowcount/@maxcount+1

	IF @rowcount%500=0
		SET @pagecount=@pagecount-1

	WHILE(@pagecount>0)
	BEGIN
		--生成单据编号
		EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'JK',@billdate,@STypeId,@billcode OUT,@dfullname,@cefullname,-999

		--主表数据写入
		SET @BillNumberId = 0
		
		INSERT INTO #atypeid1
		        ( id, NAME,flag )
		EXEC dbo.Web_GetAtype @billtypeid = @billtype, -- varchar(50)
		    @stypeid = @stypeid -- varchar(50)
		
		SELECT @atypeid1=id FROM #atypeid1
		
DECLARE @recvalue INT=0		
EXEC @recvalue=Gp_InsertBillIndex 
			@BillDate=@billdate,
			@BillCode=@billcode,
			@BillType=@billtype,
			@Comment='未完成的采购订单生成的采购入库单',
			@ATypeID='',
			@PTypeID='',
			@BTypeID=@btypeid,
			@ETypeID=@etypeid,
			@KTypeID=@ktypeid,
			@KTypeID2='',
			@IfCheck='f',
			@CheckE=@OperatorID,
			@TotalMoney=@totalmoney,
			@TotalQty=@totalqty,
			@TotalInMoney=0,
			@Tax='0',
			@szPeriod=1,
			@Explain='',	--@explain,
			@Draft='True',
			@RedWord='False',
			@OrderID=0,
			@WayBillCode='',
			@Goodsnumber=@GoodsNumber,
			@PackWay='',
			@Tel='',
			@preferencemoney=0,
			@AlertDay=9999,
			@Assessor='',
			@IfAudit='',
			@Audit_Explain='',
			@Dtypeid=@dtypeid,
			@VipCardID=-1,
			@KTypeID3='',
			@LinkMan='',
			@LinkTel='',
			@LinkAddr='',
			@wxManID='',
			@JieJianBillNumberID=-1,
			@JieJianID=-1,
			@BaoXiuBillNumberID=-1,
			@BaoXiuID=-1,
			@BuyDate='',
			@Serial='',
			@wxTotal=0,
			@ErrDes='',
			@ifHideJieJian=0,
			@ifWX=0,
			@IfBargainOn=0,
			@STypeID=@stypeid,
			@FromBillNumberID=0,
			@CostSale=0,
			@completedate='9999-12-31 23:59:59',
			@billstate=1,
			@ifmulaccount=0,
			@vipczmoney=0,
			@otherinouttype=-1,
			@czbeforetimes=0,
			@posbilltype=0,
			@TransportId=0,
			@IsFreightMoney=0,
			@FreightAddr=NULL,
			@freightperson=NULL,
			@freighttel=NULL,
			@ShareMode=0,
			@uf1='',
			@uf2='',
			@uf3='',
			@uf4='',
			@uf5='',
			--9.0新字段
			@dealbtypeid=@dealbtypeid,		--结算单位
			@cid=@cid,			--外币币种id
			@rate=@rate,			--汇率
			@ntotalmoney=@totalmoney,		--原币种金额
			@ntotalinmoney=0,	--原币收现金额
			@npreferencemoney=0,	--原币优惠金额
			@nvipczmoney=0,		--原币会员卡充值金额
			@atypeid1=@atypeid1,
			@billproperty=-1,					--单据属性
			@ncompletetotal	=0,		--原币结算金额
			@isini=0,
			@ATID=0,					--过账模板
			@CompleteTotal=0,
			@IfCargo=0,
			@IfInvoice=0,
			@promoruleid=0,
			@beforepromobillnumberid=0,
			@promotionmsg='',
			@isyapi=0,
			@yapiorderid=0	,
			@DeliveryAddress='',
			@Discount=1,
			@AdpriceType=0,	
			@checkSave='bill_allow_save'
			
 IF @recvalue = -1 
    BEGIN
        RAISERROR('试用版最多录200条单据！',16,1)
        RETURN
    END
 IF @recvalue = -2 
    BEGIN
        RAISERROR('录单日期小于本期开始日期！',16,1)
        RETURN
    END
 IF @recvalue = -3 
    BEGIN
        RAISERROR('校验错误 ！',16,1)
        RETURN
    END
 IF @recvalue = -4
    BEGIN
        RAISERROR('录单日期必须与当前日期一致！',16,1)
        RETURN
    END
 IF @recvalue = -5 
    BEGIN
        RAISERROR('更新单据发生错误！',16,1)
        RETURN
    END

		
		SET @BillNumberId = @recvalue

		IF @BillNumberId IS NULL
			RETURN -10
			
		--写单据操作日志
		INSERT INTO BillOperateLog(billnumberid,operatetype,etypeid,OperateTime,ip) values(@BillNumberId,'制单',@OperatorID,GETDATE(),@clientip)

		--保存单据编号的种子数
		EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
		
		INSERT INTO #billnumberid (ID) VALUES(@BillNumberId)
		--明细表数据写入
		INSERT INTO BuyBill 
		(
			[BillNumberId],
			[PtypeId],
			[Qty],
			[SalePrice],
			[discount],
			[DiscountPrice],
			[jobnumber],
			[total],
			[OutFactoryDate],
			[TaxPrice],
			[TaxTotal],
			[comment],
			OrderID,
			[isUnit2],
			[Serial],
			[GoodsNumber],
			[ProduceDate],
			[ValidDate],
			[GoodsBTypeID],
			Tax,
			SaleTotal,
			KTypeID,
			STypeID,--,ShareFee
			ItemID,--自由项id
			CargoID,
			CurMDiscountPrice,
			CurMSalePrice,
			CurMTaxPrice,
			UnitID,
			UnitRate,
			NTotal,
			TaxMoney,
			NDiscountPrice,
			NQty,
			NSalePrice,
			NSaleTotal,
			NTaxMoney,
			NTaxPrice,
			NTaxTotal,
			NUnitID,
			NUnitMsg,
			MDiscountPrice,
			MQty,
			MSalePrice,
			MTaxPrice,
			MUnitID,
			MUnitMsg,
			MUnitRate,
			IsCombined,
			pricesource,			
			goodscostprice
		)
		SELECT TOP (@maxcount) * 
		FROM
		(	SELECT TOP (@rowcount-@maxcount*(@pagecount-1)) *
			FROM (
					SELECT	TOP (@maxcount*@pagecount)
							@BillNumberId AS BillNumberId,
							a.ptypeid AS ptypeid,
							(a.qty-a.ReachQty) AS qty,
							a.price AS saleprice,
							a.Discount AS discount,
							a.DiscountPrice AS discountprice,
							'' AS jobnumber,
							CASE 
								WHEN a.reachqty = 0 THEN a.total
								ELSE ROUND((a.qty-a.ReachQty)*a.DiscountPrice,2)
							END AS total,
							@billdate AS OutFactoryDate,
							a.TaxPrice AS taxprice,
							CASE
								WHEN a.reachqty = 0 THEN a.TaxTotal
								ELSE ROUND((a.qty-a.ReachQty)*a.TaxPrice,2)
							END AS TaxTotal,
							CASE
								WHEN LEN(I.Billcode+';'+a.comment)>256 THEN LEFT(I.Billcode+';'+a.comment,256)
								ELSE I.Billcode+';'+a.comment
							END AS comment,--983 540 测试提的bug
							a.OrderID AS orderid,
							a.IsUnit2 AS isunit2,
							'' AS serial,
							a.GoodsNumber,
							a.ProduceDate AS ProduceDate,
							a.ValidDate AS ValidDate,
							'' AS GoodsBTypeID,
							a.Tax AS tax,
							CASE
								WHEN a.reachqty = 0 THEN a.saletotal
								ELSE ROUND((a.qty-a.ReachQty)*a.price,2)
							END AS saletotal,
							CASE @ifktype 
								WHEN '1' THEN a.KTypeID
								ELSE @ktypeid END AS ktypeid,
							a.Stypeid AS stypeid,--,'' AS ShareFeeBill
							a.ItemID,
							--a.CargoID,
							CASE @ifktype WHEN '1' THEN a.CargoID ELSE NULL END AS cargoid,
							
							a.curmdiscountprice AS curmdiscountprice,--大单位原币折后价
							a.curmsaleprice as curmsaleprice,--大单位原币单价
							a.curmtaxprice AS curmtaxprice,--大单位原币含税价
							a.UnitID,
							a.UnitRate,
							CASE
								WHEN a.reachqty = 0 THEN a.ntotal
								--ELSE a.NTotal*(1-a.ReachQty/a.qty)
								ELSE ROUND((a.qty-a.ReachQty)*a.nDiscountPrice,2)
							END AS ntotal,
							ROUND(a.TaxMoney*(a.qty-a.ReachQty)/a.qty,2) AS TaxMoney,--本币税额
							a.NDiscountPrice,--原币折后单价
							a.NQty*(1-a.ReachQty/a.qty) AS nqty,
							a.NSalePrice,--原币单价
							CASE
								WHEN a.reachqty = 0 THEN a.nsaletotal
								ELSE ROUND((a.qty-a.ReachQty)*a.NSalePrice,2)
							END AS nsaletotal,--原币金额
							ROUND(a.NTaxMoney*(a.qty-a.ReachQty)/a.qty,2) AS NTaxMoney,--原币税额
							a.NTaxPrice,--原币含税单价
							CASE
								WHEN a.reachqty = 0 THEN a.ntaxtotal
								ELSE ROUND((a.qty-a.ReachQty)*NTaxPrice,2)
							END AS ntaxtotal,						--原币价税合计
							a.NUnitID,
							a.NUnitMsg,
							a.MDiscountPrice AS MDiscountPrice,--大单位折后价							
							ROUND((a.Qty-a.ReachQty)/isnull(a.MunitRate,1),@intQtyDot) AS mqty,--大单位数量
							a.MSalePrice,--大单位单价
							a.MTaxPrice,--大单位含税价
							a.munitid ,
							a.MUnitMsg,
							a.MunitRate,
							a.IsCombined,
							'来自采购订单生成：['+a.pricesource+']' AS pricesource,
							-1 as goodscostprice
					FROM	OrderBill a
					INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
					WHERE	A.OrderID IN (SELECT *FROM f_split(@orderid,','))
							AND I.GoodsNumber=@GoodsNumber
							AND I.Rate=@rate 
							AND I.CID=@cid
							AND	I.Stypeid=@Stypeid
							AND I.btypeid=@btypeid
							AND I.DtypeId=@dtypeid
							AND	ISNULL(I.dealbtypeid,'')=ISNULL(@dealbtypeid,'')
							AND	(@Etypeid='' OR I.Etypeid=@Etypeid)
							AND	(@Ktypeid='' OR I.Ktypeid=@Ktypeid)
							AND	(a.qty-a.ReachQty)>0
					ORDER BY a.OrderID
					) A 
			ORDER BY A.orderid DESC) B 
		ORDER BY B.orderid
		
		if exists(select top 1 1 from BuyBill where BillNumberId = @BillNumberId)
		begin		
			UPDATE dbo.BuyBill SET ShowOrder=ID WHERE BillNumberId=@BillNumberId
			SET @pagecount=@pagecount-1
			
			UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
			FROM OrderBill a 
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM BuyBill b WHERE b.OrderId<>-1 AND b.billNumberID=@BillNumberId GROUP BY orderid)b ON b.orderid=a.OrderID

				
			-- 自动生成的单据会影响草稿库存
			EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,@billtype
			
			--表体自定义
			INSERT INTO Custom_BillDetails (BillId, Detailid, BillType, SysDiy1, SysDiy2, SysDiy3, SysDiy4, SysDiy5, SysDiy6, SysDiy7, SysDiy8, SysDiy9, SysDiy10, SysDiy11, SysDiy12, SysDiy13, SysDiy14, SysDiy15, SysDiy16, SysDiy17, SysDiy18, SysDiy19, SysDiy20, SysDiy21, SysDiy22, SysDiy23, SysDiy24, SysDiy25, SysDiy26, SysDiy27, SysDiy28, SysDiy29, SysDiy30, SysDiy31, SysDiy32, iscombination, InOrOut, SysDiy33, SysDiy34, SysDiy35, SysDiy36, SysDiy37, SysDiy38, SysDiy39, SysDiy40)
			SELECT	@BillNumberId, O.ID, 34, SysDiy1, SysDiy2, SysDiy3, SysDiy4, SysDiy5, SysDiy6, SysDiy7, SysDiy8, SysDiy9, SysDiy10, SysDiy11, SysDiy12, SysDiy13, SysDiy14, SysDiy15, SysDiy16, SysDiy17, SysDiy18, SysDiy19, SysDiy20, SysDiy21, SysDiy22, SysDiy23, SysDiy24, SysDiy25, SysDiy26, SysDiy27, SysDiy28, SysDiy29, SysDiy30, SysDiy31, SysDiy32, iscombination, InOrOut, SysDiy33, SysDiy34, SysDiy35, SysDiy36, SysDiy37, SysDiy38, SysDiy39, SysDiy40
			FROM	OrderBill O
			INNER JOIN dbo.BuyBill S ON S.OrderID = O.Id
			INNER JOIN Custom_BillDetails C ON C.BillId = O.BillNumberId AND O.ID = C.Detailid
			WHERE	S.billNumberID = @BillNumberId		
		end
		else
		begin
			delete from BillIndex where BillNumberId = @BillNumberId
			delete from #billnumberid where ID = @BillNumberId
		end 
	END
	---读取下一行数据
	FETCH NEXT FROM indexcursor INTO	@GoodsNumber,
										@rate,
										@cid,
										@sTypeID,
										@BTypeID,
										@dealbtypeid,
										@dtypeid,										
										@eTypeID,
										@kTypeID,
										@totalqty,
										@totalmoney--,@tax		
END
CLOSE indexcursor
DEALLOCATE  indexcursor

SELECT BillCode AS billcode FROM BillIndex BI
INNER JOIN #billnumberid B ON  BI.BillNumberId=B.ID

DROP TABLE #MANTYPE,#atypeid1,#DraftGoodsStocks,#OrderBillNumberID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_BuyOrderToWmsBuyBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_BuyOrderToWmsBuyBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：谢吉康
	日期：2018-10-19
	描述：采购订单生成WMS采购出库单
*/
CREATE PROCEDURE Gp_BuyOrderToWmsBuyBill
( 
	@OperatorID		VARCHAR(50),
	@orderid		VARCHAR(MAX),
	@ifetype		VARCHAR(10) = '1',
	@ifktype		VARCHAR(10) = '1',
	@clientip		VARCHAR(MAX) = '',
	@errormsg		VARCHAR(100) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON
SET @errormsg = ''
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #SType(TypeId	varchar(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorID)

--往来单位
CREATE TABLE #BType(TypeId	varchar(100))
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)

--仓库
CREATE TABLE #KType(TypeId	varchar(100))
INSERT INTO #KType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)	

--职员
CREATE TABLE #EType(TypeId	varchar(100))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)	

--商品
CREATE TABLE #PType(TypeId	varchar(100))
INSERT INTO #PType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@OperatorID)	


----BEGIN---------------------判断是否存在未完成的订单，处理出库单过账后未完成订单没有刷新页面的同步操作情况-------------------------

IF EXISTS(SELECT 1 FROM dbo.OrderIndex a INNER JOIN dbo.OrderBill b ON a.billNumberId = b.billNumberID 
			WHERE OrderState='1' AND b.OrderID IN (SELECT * FROM f_split(@orderid,',')))
BEGIN
	--RAISERROR('存在已完成的单据，请刷新页面重试！',16,1) 
	SET @errormsg = '存在已完成的单据，请刷新页面重试！'
	RETURN 
END

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

--草稿库存
CREATE TABLE #DraftGoodsStocks
(
	PTypeId			VARCHAR(100),
	KTypeId			VARCHAR(100),
	Qty				 NUMERIC(24, 10) ,
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) ,
	SaleReachQty	 NUMERIC(24, 10) ,
	BuyReachQty		 NUMERIC(24, 10) 
)


CREATE TABLE #OrderBillNumberID
(
	id	VARCHAR(1000)
)

CREATE TABLE #atypeid1(id VARCHAR(1000),NAME VARCHAR(1000),flag varchar(10))


INSERT INTO #OrderBillNumberID (id)
SELECT billNumberID FROM OrderBill WHERE OrderID IN (SELECT *FROM f_split(@orderid,',')) GROUP BY billNumberID


CREATE TABLE #MANTYPE
(	
	GoodsNumber VARCHAR(50),
	rate	VARCHAR(50),
	cid  VARCHAR(50),
	stypeid	VARCHAR(50),
	btypeid	VARCHAR(50),
	dealbtypeid VARCHAR(50),
	dtypeid	VARCHAR(50),
	etypeid	VARCHAR(50),
	ktypeid	VARCHAR(50)
)

DECLARE @SQL VARCHAR(MAX)
DECLARE @colname	VARCHAR(MAX)
DECLARE @GroupByCol	VARCHAR(MAX)
DECLARE @atypeid1 VARCHAR(max)

SET @colname='a.GoodsNumber,a.rate,a.cid as cid,a.stypeid AS stypeid,ISNULL(a.btypeid,'''') AS btypeid,ISNULL(a.dealbtypeid,'''') AS dealbtypeid,
				ISNULL(a.dtypeid,'''') as dtypeid '
SET @GroupByCol='a.GoodsNumber,a.rate,a.cid,a.stypeid,a.btypeid,a.dealbtypeid,a.dtypeid '
IF @ifetype='1'
	BEGIN
		SET @colname=@colname+',a.etypeid AS etypeid'
		SET @GroupByCol=@GroupByCol+',a.etypeid '
	END
ELSE
	SET @colname=@colname+','''' AS etypeid'
IF @ifktype='1'
	BEGIN
		SET @colname=@colname+',a.ktypeid AS ktypeid'
		SET @GroupByCol=@GroupByCol+',a.ktypeid '
	END
ELSE
	SET @colname=@colname+','''' AS ktypeid'

SET @SQL='
INSERT INTO #MANTYPE(GoodsNumber,rate,cid,stypeid,btypeid,dealbtypeid,dtypeid,etypeid,ktypeid)
SELECT '+@colname+'
FROM orderindex a
INNER JOIN #OrderBillNumberID b ON b.id=a.billNumberID
GROUP BY '+@GroupByCol
--PRINT(@sql)
EXEC (@SQL)

DECLARE @billdate		DATETIME,
		@billcode		VARCHAR(MAX),
		@stypeid		VARCHAR(MAX),
		@etypeid		VARCHAR(MAX),
		@btypeid		VARCHAR(MAX),
		@dtypeid		VARCHAR(max),
		@ktypeid		VARCHAR(MAX),
		@totalmoney		NUMERIC(24, 10) ,
		@totalqty		NUMERIC(24, 10) ,
		@tax			NUMERIC(24, 10) ,
		@BillNumberId	NUMERIC(24, 10) ,
		@DAY			VARCHAR(MAX),
		@MONTH			VARCHAR(MAX),
		--以下参数用于处理明细超过500条的情况
		@rowcount		INT,	--明细总行数
		@maxcount		INT,	--明细最大行数（500条）
		@pagecount		INT,		--明细页数
		@dealbtypeid	VARCHAR(100),--结算单位
		@cid			VARCHAR(100),
		@rate			VARCHAR(100),
		@GoodsNumber	VARCHAR(100),
		@intQtyDot		INT,
		@cefullname		VARCHAR(500)='',
		@dfullname		VARCHAR(500)=''
		
		
SET @rowcount=0
SET @maxcount=500
SET @pagecount=0

--数量的小数位数
EXEC	@intQtyDot=Gp_GetDigit 1
		
CREATE TABLE #billnumberid(ID VARCHAR(MAX))

DECLARE @billtype	VARCHAR(10)
SET @billtype='34'

--取当前时间
SET @billdate=GETDATE()
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
SET @billdate=(SELECT CONVERT (VARCHAR(10),@billdate,120))

SET @SQL='
DECLARE indexcursor CURSOR FOR 
	SELECT  '+@colname+',
			SUM(b.qty-b.ReachQty) AS totalqty,
			ROUND(SUM((b.qty-b.ReachQty)*taxprice),2) AS totalmoney
	FROM	#ManType a
	INNER JOIN OrderIndex I ON  I.Stypeid=a.stypeid AND ISNULL(I.dealbtypeid,'''')=ISNULL(a.dealbtypeid,'''') AND ISNULL(I.btypeid,'''')=ISNULL(a.btypeid,'''') and (a.dtypeid='''' or I.dtypeid=a.dtypeid) AND (a.etypeid='''' OR I.etypeid=a.etypeid) AND (a.ktypeid='''' OR I.ktypeid=a.Ktypeid)
	INNER JOIN OrderBill B ON I.billNumberId=B.billNumberID
	WHERE (b.qty-b.ReachQty)<>0 and B.OrderID IN (SELECT *FROM f_split('''+@orderid+''','','')) 
	GROUP BY '+@GroupByCol

EXEC (@SQL)

OPEN indexcursor

FETCH NEXT FROM indexcursor INTO	@GoodsNumber,
									@rate,
									@cid,
									@sTypeID,
									@BTypeID,
									@dealbtypeid,
									@dtypeid,
									@eTypeID,
									@kTypeID,
									@totalqty,
									@totalmoney--@tax


WHILE @@FETCH_STATUS=0
BEGIN
	--是否自定义单据编号
	IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =34)
	BEGIN
		SELECT @MONTH = TypeId  FROM employee WHERE typeId=@ETypeId
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @OperatorID
		SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId = @dtypeid
	END
		
	SELECT @rowcount=COUNT(1)
	FROM	OrderBill a
	INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
	WHERE	A.OrderID IN (SELECT * FROM f_split(@orderid,','))
	AND		I.Stypeid=@Stypeid
	AND		ISNULL(I.dealbtypeid,'')=ISNULL(@dealbtypeid,'')
	AND		ISNULL(I.DtypeId,'')=ISNULL(@dtypeid,'')
	AND		(@Etypeid='' OR I.Etypeid=@Etypeid)
	AND		(@Ktypeid='' OR I.Ktypeid=@Ktypeid)
	AND		(a.qty-a.ReachQty)<>0
	
	SET @pagecount=@rowcount/@maxcount+1

	IF @rowcount%500=0
		SET @pagecount=@pagecount-1

	WHILE(@pagecount>0)
	BEGIN
		--生成单据编号
		EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'JK',@billdate,@STypeId,@billcode OUT,@dfullname,@cefullname,-999

		--主表数据写入
		SET @BillNumberId = 0
		
		INSERT INTO #atypeid1
		        ( id, NAME,flag )
		EXEC dbo.Web_GetAtype @billtypeid = @billtype, -- varchar(50)
		    @stypeid = @stypeid -- varchar(50)
		
		SELECT @atypeid1=id FROM #atypeid1
		
		DECLARE @recvalue INT=0		
		EXEC @recvalue=Gp_InsertBillIndex 
					@BillDate=@billdate,
					@BillCode=@billcode,
					@BillType=@billtype,
					@Comment='未完成的采购订单生成的WMS采购入库单',
					@ATypeID='',
					@PTypeID='',
					@BTypeID=@btypeid,
					@ETypeID=@etypeid,
					@KTypeID=@ktypeid,
					@KTypeID2='',
					@IfCheck='f',
					@CheckE=@OperatorID,
					@TotalMoney=@totalmoney,
					@TotalQty=@totalqty,
					@TotalInMoney=0,
					@Tax='0',
					@szPeriod=1,
					@Explain='',
					@Draft='True',
					@RedWord='False',
					@OrderID=0,
					@WayBillCode='',
					@Goodsnumber=@GoodsNumber,
					@PackWay='',
					@Tel='',
					@preferencemoney=0,
					@AlertDay=9999,
					@Assessor='',
					@IfAudit='',
					@Audit_Explain='',
					@Dtypeid=@dtypeid,
					@VipCardID=-1,
					@KTypeID3='',
					@LinkMan='',
					@LinkTel='',
					@LinkAddr='',
					@wxManID='',
					@JieJianBillNumberID=-1,
					@JieJianID=-1,
					@BaoXiuBillNumberID=-1,
					@BaoXiuID=-1,
					@BuyDate='',
					@Serial='',
					@wxTotal=0,
					@ErrDes='',
					@ifHideJieJian=0,
					@ifWX=0,
					@IfBargainOn=0,
					@STypeID=@stypeid,
					@FromBillNumberID=0,
					@CostSale=0,
					@completedate='9999-12-31 23:59:59',
					@billstate=1,
					@ifmulaccount=0,
					@vipczmoney=0,
					@otherinouttype=-1,
					@czbeforetimes=0,
					@posbilltype=0,
					@TransportId=0,
					@IsFreightMoney=0,
					@FreightAddr=NULL,
					@freightperson=NULL,
					@freighttel=NULL,
					@ShareMode=0,
					@uf1='',
					@uf2='',
					@uf3='',
					@uf4='',
					@uf5='',
					--9.0新字段
					@dealbtypeid=@dealbtypeid,		--结算单位
					@cid=@cid,			--外币币种id
					@rate=@rate,			--汇率
					@ntotalmoney=@totalmoney,		--原币种金额
					@ntotalinmoney=0,	--原币收现金额
					@npreferencemoney=0,	--原币优惠金额
					@nvipczmoney=0,		--原币会员卡充值金额
					@atypeid1=@atypeid1,
					@billproperty=-1,					--单据属性
					@ncompletetotal	=0,		--原币结算金额
					@isini=0,
					@ATID=0,					--过账模板
					@CompleteTotal=0,
					@IfCargo=0,
					@IfInvoice=0,
					@promoruleid=0,
					@beforepromobillnumberid=0,
					@promotionmsg='',
					@isyapi=0,
					@yapiorderid=0	,
					@DeliveryAddress='',
					@Discount=1,
					@AdpriceType=0,	
					@checkSave='bill_allow_save'
					
		 IF @recvalue = -1 
			BEGIN
				--RAISERROR('试用版最多录200条单据！',16,1)
				SET @errormsg = '试用版最多录200条单据！'
				RETURN
			END
		 IF @recvalue = -2 
			BEGIN
				--RAISERROR('录单日期小于本期开始日期！',16,1)
				SET @errormsg = '录单日期小于本期开始日期！'
				RETURN
			END
		 IF @recvalue = -3 
			BEGIN
				--RAISERROR('校验错误 ！',16,1)
				SET @errormsg = '校验错误 ！'
				RETURN
			END
		 IF @recvalue = -4
			BEGIN
				--RAISERROR('录单日期必须与当前日期一致！',16,1)
				SET @errormsg = '录单日期必须与当前日期一致！'
				RETURN
			END
		 IF @recvalue = -5 
			BEGIN
				--RAISERROR('更新单据发生错误！',16,1)
				SET @errormsg = '更新单据发生错误！'
				RETURN
			END

		
		SET @BillNumberId = @recvalue

		IF @BillNumberId IS NULL
			RETURN -10
			
		--写单据操作日志
		INSERT INTO BillOperateLog(billnumberid,operatetype,etypeid,OperateTime,ip) values(@BillNumberId,'制单',@OperatorID,GETDATE(),@clientip)

		--保存单据编号的种子数
		EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
		
		INSERT INTO #billnumberid (ID) VALUES(@BillNumberId)
		
		--明细表数据写入
		INSERT INTO BuyBill 
		(
			[BillNumberId],
			[PtypeId],
			[Qty],
			[SalePrice],
			[discount],
			[DiscountPrice],
			[jobnumber],
			[total],
			[OutFactoryDate],
			[TaxPrice],
			[TaxTotal],
			[comment],
			OrderID,
			[isUnit2],
			[Serial],
			[GoodsNumber],
			[ProduceDate],
			[ValidDate],
			[GoodsBTypeID],
			Tax,
			SaleTotal,
			KTypeID,
			STypeID,--,ShareFee
			ItemID,--自由项id
			CargoID,
			CurMDiscountPrice,
			CurMSalePrice,
			CurMTaxPrice,
			UnitID,
			UnitRate,
			NTotal,
			TaxMoney,
			NDiscountPrice,
			NQty,
			NSalePrice,
			NSaleTotal,
			NTaxMoney,
			NTaxPrice,
			NTaxTotal,
			NUnitID,
			NUnitMsg,
			MDiscountPrice,
			MQty,
			MSalePrice,
			MTaxPrice,
			MUnitID,
			MUnitMsg,
			MUnitRate,
			IsCombined,
			pricesource,			
			goodscostprice
		)
		SELECT TOP (@maxcount) * 
		FROM
		(	SELECT TOP (@rowcount-@maxcount*(@pagecount-1)) *
			FROM (
					SELECT	TOP (@maxcount*@pagecount)
							@BillNumberId AS BillNumberId,
							a.ptypeid AS ptypeid,
							(a.qty-a.ReachQty) AS qty,
							a.price AS saleprice,
							a.Discount AS discount,
							a.DiscountPrice AS discountprice,
							'' AS jobnumber,
							CASE 
								WHEN a.reachqty = 0 THEN a.total
								ELSE ROUND((a.qty-a.ReachQty)*a.DiscountPrice,2)
							END AS total,
							@billdate AS OutFactoryDate,
							a.TaxPrice AS taxprice,
							CASE
								WHEN a.reachqty = 0 THEN a.TaxTotal
								ELSE ROUND((a.qty-a.ReachQty)*a.TaxPrice,2)
							END AS TaxTotal,
							I.Billcode AS comment,--983 540 测试提的bug
							a.OrderID AS orderid,
							a.IsUnit2 AS isunit2,
							'' AS serial,
							a.GoodsNumber,
							a.ProduceDate AS ProduceDate,
							a.ValidDate AS ValidDate,
							'' AS GoodsBTypeID,
							a.Tax AS tax,
							CASE
								WHEN a.reachqty = 0 THEN a.saletotal
								ELSE ROUND((a.qty-a.ReachQty)*a.price,2)
							END AS saletotal,
							CASE @ifktype 
								WHEN '1' THEN a.KTypeID
								ELSE @ktypeid END AS ktypeid,
							a.Stypeid AS stypeid,--,'' AS ShareFeeBill
							a.ItemID,
							--a.CargoID,
							CASE @ifktype WHEN '1' THEN a.CargoID ELSE NULL END AS cargoid,
							
							a.curmdiscountprice AS curmdiscountprice,--大单位原币折后价
							a.curmsaleprice as curmsaleprice,--大单位原币单价
							a.curmtaxprice AS curmtaxprice,--大单位原币含税价
							a.UnitID,
							a.UnitRate,
							CASE
								WHEN a.reachqty = 0 THEN a.ntotal
								--ELSE a.NTotal*(1-a.ReachQty/a.qty)
								ELSE ROUND((a.qty-a.ReachQty)*a.nDiscountPrice,2)
							END AS ntotal,
							a.TaxMoney,--本币税额
							a.NDiscountPrice,--原币折后单价
							a.NQty*(1-a.ReachQty/a.qty) AS nqty,
							a.NSalePrice,--原币单价
							CASE
								WHEN a.reachqty = 0 THEN a.nsaletotal
								ELSE ROUND((a.qty-a.ReachQty)*a.NSalePrice,2)
							END AS nsaletotal,--原币金额
							a.NTaxMoney,--原币税额
							a.NTaxPrice,--原币含税单价
							CASE
								WHEN a.reachqty = 0 THEN a.ntaxtotal
								ELSE ROUND((a.qty-a.ReachQty)*NTaxPrice,2)
							END AS ntaxtotal,						--原币价税合计
							a.NUnitID,
							a.NUnitMsg,
							a.MDiscountPrice AS MDiscountPrice,--大单位折后价							
							ROUND((a.Qty-a.ReachQty)/isnull(a.MunitRate,1),@intQtyDot) AS mqty,--大单位数量
							a.MSalePrice,--大单位单价
							a.MTaxPrice,--大单位含税价
							a.munitid ,
							a.MUnitMsg,
							a.MunitRate,
							a.IsCombined,
							'来自采购订单生成：['+a.pricesource+']' AS pricesource,							
							-1 as goodscostprice
					FROM	OrderBill a
					INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
					WHERE	
						A.OrderID IN (SELECT *FROM f_split(@orderid,','))
						AND I.GoodsNumber=@GoodsNumber
						AND I.Rate=@rate 
						AND I.CID=@cid
						AND	I.Stypeid=@Stypeid
						AND I.btypeid=@btypeid
						AND I.DtypeId=@dtypeid
						AND	ISNULL(I.dealbtypeid,'')=ISNULL(@dealbtypeid,'')
						AND	(@Etypeid='' OR I.Etypeid=@Etypeid)
						AND	(@Ktypeid='' OR I.Ktypeid=@Ktypeid)
						AND	(a.qty-a.ReachQty)<>0
					ORDER BY a.OrderID
					) A 
			ORDER BY A.orderid DESC) B 
		ORDER BY B.orderid
		
		UPDATE dbo.SaleBill SET ShowOrder=ID WHERE BillNumberId=@BillNumberId
		SET @pagecount=@pagecount-1
		
		-- 自动生成的单据会影响草稿库存
		EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,@billtype
	END
	---读取下一行数据
	FETCH NEXT FROM indexcursor INTO	@GoodsNumber,
										@rate,
										@cid,
										@sTypeID,
										@BTypeID,
										@dealbtypeid,
										@dtypeid,
										@eTypeID,
										@kTypeID,
										@totalqty,
										@totalmoney--,@tax		
END
CLOSE indexcursor
DEALLOCATE  indexcursor

UPDATE OrderBill SET WaitQty=WaitQty+qty-ReachQty WHERE	OrderID IN (SELECT *FROM f_split(@orderid,',')) 

SELECT BillCode AS billcode FROM BillIndex BI
INNER JOIN #billnumberid B ON  BI.BillNumberId=B.ID

DROP TABLE #MANTYPE,#atypeid1,#DraftGoodsStocks,#OrderBillNumberID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

采购费用分摊处理


*/
CREATE   PROCEDURE Gp_BuyShareFee_Deal 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nRet				INT OUT,		
	@strErrMsg			VARCHAR(500)='' OUT
)
--@encode$--
AS

BEGIN TRAN BuyShareFee
SAVE TRAN BuyShareFeePoint


SELECT
	@nRet=0,
	@strErrMsg=''

IF @nBillType NOT IN (205)
BEGIN
	ROLLBACK TRAN BuyShareFeePoint
	COMMIT TRAN BuyShareFee
	RETURN
END

DECLARE
	@datRelativeDate		DATETIME,		--关联的物流单据的时间
	@datMonthProc			DATETIME		--月结时间
	
--一张物流单据可以对应多账费用单，所以只能从 ShareSourceBill 中来处理

--判断单据是否月结，如果没月结，就取物流单据的日期，如果月结了，就取摊销单的日期吗？

SELECT @datMonthProc=StartDate
FROM MonthProc
WHERE MonthNo='本期'


--得到采购费用摊销单的信息

DECLARE
	@datBillDate		DATETIME,
	@datPostTime		DATETIME,
	@chvDTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@intBillType		INT,
	@chvETypeID			VARCHAR(50)
	
SELECT
	@datBillDate=BillDate,
	@datPostTime=BillDate,
	@chvDTypeID=DTypeId,
	@chvSTypeID=Stypeid,
	@intBillType=BillType,
	@chvETypeID=ETypeID
FROM BillIndex
WHERE BillNumberId=@nBillID

--本单关联的物流单据与费用分摊信息
CREATE TABLE #SourceBill(
	BillNumberID			BIGINT,
	PTypeID					VARCHAR(50),
	KTypeID					VARCHAR(50),
	ShareFee				 NUMERIC(24, 10) ,
	PostTime				DATETIME,
	BillDate				DATETIME,
	ID						BIGINT,
	FromBillNumberID		BIGINT,
	FromID					BIGINT,
	FromBilltype			INT,
	Comment					VARCHAR(500)
)

EXEC Gp_BuyShareFee_GetSourceBill 
	@nBillID,
	@nBillType,
	@datMonthProc


--SELECT '#SourceBill',* FROM #SourceBill


		
--插入InOutStockTable

EXEC Gp_BuyShareFee_InsertDetail 
	@nBillID,
	@nBillType,
	@datBillDate,
	@chvETypeID,
	@chvDTypeID,
	@chvSTypeID

--SELECT * FROM InOutstocktable WHERE BillType=205




--处理其他单据的成本（包括单据的出库部分，部分入库类单据，还有同价调拨单的连环单据）
CREATE TABLE #AfterModifyBill(
	BillNumberID	BIGINT,
	BillType		INT,
	BillID			BIGINT,
	PTypeID			VARCHAR(50),
	KTypeID			VARCHAR(50),
	SortID			BIGINT,
	Qty				 NUMERIC(24, 10) ,
	PostTime		DATETIME
)



EXEC Gp_BuyShareFee_OutBill_AlterCost
	@nBillID,
	@nBillType,
	@nRet OUT,
	@strErrMsg OUT
	

	
IF @nRet<>0 
BEGIN
	ROLLBACK TRAN BuyShareFeePoint
	COMMIT TRAN BuyShareFee
	RETURN
END	
		
	
--SELECT * FROM #AfterModifyBill


IF EXISTS(
	SELECT BillNumberID
	FROM #AfterModifyBill
)
BEGIN
	--处理库存商品总值

	EXEC Gp_BuyShareFee_DealCostTotal
		@nBillID,
		@nBillType,
		@chvSTypeID

	--处理对应的其他科目

	EXEC Gp_BuyShareFee_DealOtherTotal
		@nBillID,
		@nBillType,
		@chvSTypeID
		
	--SELECT * FROM InOutstocktable WHERE BillType=205

	--对于涉及到的单据，回写成本价，成本金额
	EXEC Gp_NeedFill
END

DECLARE @RedMonthEndFlag varchar(1) -- 是否红冲月结前的单据
SET @RedMonthEndFlag ='1' --有红冲月结前单据
	
COMMIT TRAN BuyShareFee	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

SELECT * 
FROM BillIndex
WHERE BillType=205
AND IfCheck='f'

DECLARE
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nRet				INT,		
	@strErrMsg			VARCHAR(500)
	
SELECT
	@nBillID=7,
	@nBillType=205
	

BEGIN TRAN		

EXEC	Gp_BuyShareFee_Deal 
	@nBillID,
	@nBillType,
	@nRet OUT,
	@strErrMsg OUT

SELECT @nRet,@strErrMsg

ROLLBACK TRAN

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

处理库存科目成本


*/
CREATE   PROCEDURE Gp_BuyShareFee_DealCostTotal 
(
	@nBillID			NUMERIC(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@chvSTypeID			VARCHAR(50)
	
)
--@encode$--
AS

--完后再改相关的库存商品科目和它所对应的科目（这个要分单据来查），再处理总账
--处理ListTable
--总账可以通过累计差值的办法来修改

--先改相关单据的库存起初值(之后考虑方向)
DECLARE
	@STOCKID				VARCHAR(50),
	@OldTotal				 NUMERIC(24, 10) ,
	@NewTotal				 NUMERIC(24, 10) ,
	@sysID					INT
	

SELECT @STOCKID = NID FROM Ac_Items WHERE UserCode='1241'
SELECT @sysID = CID FROM Ac_Currency WHERE Sysrow = 1


SELECT @OldTotal=SUM(Total)  --这里只需要之前的一个总值即可
FROM ListTable a
INNER JOIN 
(
	SELECT DISTINCT BillNumberID
	FROM #AfterModifyBill 
) b
ON a.BillNumberId=b.BillNumberID
WHERE AtypeId=@STOCKID

SELECT @OldTotal=ISNULL(@OldTotal,0)

UPDATE ListTable
SET Total=ISNULL(b.Total,0),Ntotal = ISNULL(b.Total,0)
FROM
(
	SELECT b.BillNumberID,a.BillType,SUM(a.CostTotal) AS Total
	FROM InOutstocktable a
	INNER JOIN 
	(
		SELECT DISTINCT BillNumberID
		FROM #AfterModifyBill 
	) b
	ON a.BillNumberId=b.BillNumberID
	WHERE a.KtypeId<>'10000'
	GROUP BY b.BillNumberID,a.BillType
) b
WHERE ListTable.BillNumberId=b.BillNumberID
AND ListTable.AtypeId=@STOCKID
AND ListTable.BillType=b.BillType


--如果库存商品之前在LISTTABLE,现在不需要写入的，可以先不管它（最多存在一条为零的数据而已）
--如果库存商品之前不在LISTTABLE，现在需要写入的，则增加
IF EXISTS(
	SELECT DISTINCT a.BillNumberID
	FROM #AfterModifyBill a
	WHERE --a.BillType IN (6,161,146,16,21,160) AND
	Not EXISTS(
		SELECT b.BillNumberId
		FROM ListTable b
		WHERE b.BillNumberId=a.BillNumberID
		AND b.AtypeId=@STOCKID
	)
)
BEGIN
	--插入库存商品科目
	--IfOut先默认为0，届时按单据类型来处理(需要核实下这个字段有没有用)
	INSERT ListTable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,
	Total,CostTotal,Audited,Ifout,DTypeID,STypeID,CID,Ntotal,Rate)
	SELECT DISTINCT b.BillNumberID,a.BillDate,a.BillType,@STOCKID,a.BTypeID,a.ETypeID,
	SUM(a.CostTotal) AS Total,SUM(a.CostTotal) AS Total,a.Audited,0,a.DTypeID,a.STypeID,@sysID,SUM(a.CostTotal) AS NTotal,1
	FROM InOutstocktable a
	INNER JOIN 
	(
		SELECT DISTINCT a.BillNumberID
		FROM #AfterModifyBill a
		WHERE --a.BillType IN (6,161,146,16,21,160) AND
		Not EXISTS(
			SELECT b.BillNumberId
			FROM ListTable b
			WHERE b.BillNumberId=a.BillNumberID
			AND b.AtypeId=@STOCKID
		)
	) b
	ON a.BillNumberId=b.BillNumberID
	WHERE a.KtypeId<>'10000'
	GROUP BY b.BillNumberID,a.BillDate,a.BillType,a.BTypeID,a.ETypeID,a.DTypeID,a.STypeID,a.Audited
	HAVING SUM(a.CostTotal)<>0
END



--改总账（减掉之前的，加上改后的即可）
SELECT @NewTotal=SUM(Total)
FROM ListTable a
INNER JOIN 
(
	SELECT DISTINCT BillNumberID
	FROM #AfterModifyBill 
) b
ON a.BillNumberId=b.BillNumberID
WHERE AtypeId=@STOCKID

SELECT @NewTotal=ISNULL(@NewTotal,0)

DECLARE
	@DiffTotal			 NUMERIC(24, 10) 
	
SELECT
	@DiffTotal=ISNULL(-@OldTotal,0)+ISNULL(@NewTotal,0)

IF @DiffTotal<>0
BEGIN
	IF EXISTS(
		SELECT ATypeID
		FROM AType_Total
		WHERE STypeID=@chvSTypeID AND ATypeID=@STOCKID AND CID=@sysID
	)
	BEGIN
		UPDATE AType_Total
		SET Total=Total+@DiffTotal,Ntotal=Ntotal+@DiffTotal
		WHERE STypeID=@chvSTypeID AND ATypeID=@STOCKID AND CID=@sysID
	END
	ELSE
	BEGIN
		INSERT AType_Total(ATypeID,STypeID,Total,CID,Ntotal)
		SELECT @STOCKID,@chvSTypeID,@DiffTotal,@sysID,@DiffTotal
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

处理跟库存科目对应的其他科目，要分单来处理


*/
CREATE   PROCEDURE Gp_BuyShareFee_DealOtherTotal 
(
	@nBillID			NUMERIC(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@chvSTypeID			VARCHAR(50)
	
)
--@encode$--
AS

--对应的科目也是这样处理（不同的单据有不同的科目）
--对应的科目主要有主营业务成本等其他科目（针对不同的单据来处理）

--会影响到的单据从#AfterModifyBill中取

--要改变ListTable和总值，最好一类类单据来处理
CREATE TABLE #ListTable(
	BillNumberID	 NUMERIC(24, 10) ,
	ATypeID			VARCHAR(50),
	OldValue		 NUMERIC(24, 10) ,
	NewValue		 NUMERIC(24, 10) ,
	STypeID			 VARCHAR(100),
	BillType		 INT,
	BTypeID	         VARCHAR(100),
	CID				 INT,
	CostSale		INT DEFAULT 0
)

DECLARE
	@intBillType		INT,
	@strATypeID			VARCHAR(50)='',
	@strSTypeID			VARCHAR(50)
	
SELECT
	@strSTypeID=STypeID
FROM BillIndex
WHERE BillNumberId=@nBillID	


DECLARE BillType_CURSOR CURSOR FOR
SELECT DISTINCT BillType
FROM #AfterModifyBill
WHERE BillType<>17			---同价调拨单不需要处理科目

OPEN BillType_CURSOR
FETCH NEXT FROM BillType_CURSOR INTO @intBillType

WHILE @@FETCH_STATUS = 0
BEGIN

	
	EXEC Gp_OutBill_GetOtherAType @intBillType,@strATypeID OUT
	
	
	IF @strATypeID<>'' OR @intBillType=202
	BEGIN
		EXEC Gp_OutBill_DealOtherAType @intBillType,@strATypeID,@strSTypeID
	END
	
	FETCH NEXT FROM BillType_CURSOR INTO @intBillType
END

CLOSE BillType_CURSOR
DEALLOCATE BillType_CURSOR


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

得到采购费用分摊单关联的采购入库单


*/
CREATE   PROCEDURE Gp_BuyShareFee_GetSourceBill 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@datMonthProc		DATETIME
)
----@encode$--
AS

/*

这里的月结时间取的是系统中的本期时间（本期是取的月结当天后的一天）

费用分摊单关联的物流单据，可以是月结前的，可以是月结后的


每个费用分摊单的单据明细ShareSourceBill都只对应一个物流单据，
如果这个物流单据的过账时间在月结前，那么插入的明细取分摊单的过账时间
如果这个物流单据的过账时间在月结后，那么插入的明细取物流单据的过账时间
单据日期都取费用单的日期



*/

--服务类商品没有成本，应该不参与费用分摊

INSERT #SourceBill(BillNumberID,PTypeID,KTypeID,ShareFee,PostTime,BillDate,ID,FromBillNumberID,FromID,FromBilltype,Comment)
SELECT a.BillNumberId,b.PtypeId,b.KTypeID,a.ShareFee,d.posttime,d.BillDate,a.ID,a.FromBillNumberID,a.FromBillID,a.FromBillType,a.Comment
FROM ShareSourceBill a
INNER JOIN BuyBill b ON a.FromBillID=b.ID AND a.FromBillType=34
INNER JOIN BillIndex c ON a.BillNumberId=c.BillNumberId 
INNER JOIN InOutstocktable d ON b.BillNumberId=d.BillNumberId AND b.ID=d.ID 
INNER JOIN PType e ON b.PtypeId=e.typeId
WHERE a.BillNumberId=@nBillID AND e.IsService=0
UNION ALL
SELECT a.BillNumberId,b.PtypeId,b.KTypeID,a.ShareFee,d.posttime,d.BillDate,a.ID,a.FromBillNumberID,a.FromBillID,a.FromBillType,a.Comment
FROM ShareSourceBill a
INNER JOIN disassemblebill b ON a.FromBillID=b.ID AND a.FromBillType=16
INNER JOIN BillIndex c ON a.BillNumberId=c.BillNumberId
INNER JOIN InOutstocktable d ON b.BillNumberId=d.BillNumberId AND b.ID=d.ID 
INNER JOIN PType e ON b.PtypeId=e.typeId
WHERE a.BillNumberId=@nBillID AND e.IsService=0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

插入分摊明细


*/
CREATE   PROCEDURE Gp_BuyShareFee_InsertDetail 
(
	@nBillID			NUMERIC(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@datBillDate		DATETIME,
	@chvETypeID			VARCHAR(50),
	@chvDTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50)
)
--@encode$--
AS

--插入到INOUTSTOCKTABLE中(BillDate插入费用分摊单的单据日期，POSTTIME取之前算的POSTTIME)

DECLARE
	@intGoodsId INT
	
SELECT 
	@intGoodsID=nID
FROM dbo.Ac_Items
WHERE UserCode='1241'	
		


INSERT InOutstocktable(BillNumberId,BillDate,BillType,AtypeId,PtypeId,BTypeID,EtypeId,KtypeId,
		Qty,Price,Total,CostPrice,CostTotal,Audited,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,
		DTypeID,STypeID,PostTime,Comment)
SELECT a.BillNumberId,a.BillDate,@nBillType,@intGoodsID,a.PTypeID,b.BTypeID,b.ETypeID,a.KTypeID,
		0,0,0,0,a.ShareFee,1,a.ID,CASE b.RedWord WHEN 0 THEN 1 END,0,0,0,0,0,@chvDTypeId,@chvSTypeID,
		a.PostTime,a.Comment
FROM #SourceBill a
INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberId
WHERE a.BillNumberId=@nBillID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

修改相关的出库单的成本明细

还需要注意同价调拨单的处理

对于变价调拨，成本调价还要测试

*/
CREATE   PROCEDURE Gp_BuyShareFee_OutBill_AlterCost 
(
	@nBillID			NUMERIC(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nRet				INT OUT,
	@strErrMsg			VARCHAR(500)='' OUT
)
--@encode$--
AS

/*

然后进行成本重算（先确定要对哪些单据进行重算，然后再批量修改成本）

费用分摊相对简单，因为不会改数量，只是改单价和成本

*/

/*
查PostTime在所影响的物流单据之后的出库类单据（先不考虑红冲）
InOutStockTable中Audited=1的就是
(因为同一仓库，同一商品可能在多张明细中出现，所以只取PostTime里最小的)
*/


/*

一张物流单据中，可能只影响其中的几行

*/
DECLARE
	@intQtyDot			INT,
	@intPriceDot		INT,
	@intMoneyDot		INT,
	@intDiscountDot		INT,
	@intTaxDot			INT,
	@intCRateDot		INT,	
	@intTRateDot		INT	
	
EXEC	GP_Post_Dot
	@intQtyDot	OUT,
	@intPriceDot	OUT,
	@intMoneyDot	OUT,
	@intDiscountDot	OUT,
	@intTaxDot	OUT,
	@intCRateDot OUT,
	@intTRateDot	OUT
	
	
DECLARE
	@intcostpricesaleback			INT	--0表示不参照销售成本，1表示参照销售成本
		
SELECT
	@intcostpricesaleback=Value
FROM Userconfig
WHERE 	ConfigName='costpricesaleback'

SELECT
	@nRet=0,
	@strErrMsg=''

CREATE TABLE #StockInfo(
	PTypeID		VARCHAR(50),
	KTypeID		VARCHAR(50)
)

INSERT #StockInfo(PTypeID,KTypeID)
SELECT DISTINCT PTypeID,KTypeID
FROM #SourceBill 

--SELECT '#StockInfo1',* FROM #StockInfo


--确定需要改哪些明细(非红冲的出库明细)（因为新插入的费用分摊单是当天的最后一个，所以按PostTime来比较，没有问题）


EXEC Gp_BuyShareFee_ReferTo @nBillID,@nBillType


--SELECT '#AfterModifyBill',* FROM #AfterModifyBill ORDER BY SortID

--SELECT '#SourceBill'
--SELECT '#SourceBill',* FROM #SourceBill
DECLARE
@decPrice  NUMERIC(24, 10) -----商品成本价


DECLARE
	@datMinPostTime		DATETIME
	
SELECT
	@datMinPostTime=MIN(PostTime)	
FROM #SourceBill	


--确定期初数据（包含采购费用分摊单）
CREATE TABLE #IniData(
	PTypeID			VARCHAR(50),
	KTypeID			VARCHAR(50),
	Qty				 NUMERIC(24, 10) ,
	CostPrice		 NUMERIC(24, 10) ,
	CostTotal		 NUMERIC(24, 10) ,
	BeginSort		INT DEFAULT 0
)

INSERT #IniData(PTypeID,KTypeID,Qty,CostPrice,CostTotal)
SELECT a.PtypeId,a.KtypeId,SUM(a.Qty),
CASE SUM(a.Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(a.CostTotal) AS  NUMERIC(24, 10) )/CAST(SUM(a.Qty) AS  NUMERIC(24, 10) ),4) END,
SUM(a.CostTotal)
FROM
(
	SELECT  DISTINCT a.BillNumberID,a.ID,a.PtypeId,a.KtypeId,a.Qty,a.CostTotal
	FROM InOutstocktable a,
	#StockInfo b
	WHERE a.PtypeId=b.PTypeID
	AND a.KtypeId=b.KTypeID			
	AND a.PostTime<@datMinPostTime
	UNION ALL
	SELECT 0,0,a.PtypeId,a.KtypeId,a.Qty,a.Total
	FROM IniGoodsStocks a,
	#StockInfo b	
	WHERE a.PtypeId=b.PTypeID	
	AND a.KtypeId=b.KTypeID		
 
) a
GROUP BY a.PtypeId,a.KtypeId

/*
SELECT '#IniData'
SELECT '#IniData',* FROM #IniData
*/

--确定后面的物流单据(减少表扫描)
CREATE TABLE #AllAfterBill(
	BillNumberID	BIGINT,
	BillType		INT,
	PTypeID			VARCHAR(50),
	KTypeID			VARCHAR(50),
	Qty				 NUMERIC(24, 10) ,
	CostPrice		 NUMERIC(24, 10) ,
	CostTotal		 NUMERIC(24, 10) ,
	PostTime		DATETIME,
	SortID			BIGINT,
	NewSortID		BIGINT
)

--考虑给临时表建立索引
INSERT #AllAfterBill(BillNumberID,BillType,PTypeID,KTypeID,Qty,CostPrice,CostTotal,PostTime,SortID,NewSortID)
SELECT a.BillNumberId,a.BillType,a.PtypeId,a.KtypeId,a.Qty,a.CostPrice,a.CostTotal,a.PostTime,a.SortID,
ROW_NUMBER() OVER(ORDER BY a.PostTime,a.SortID,a.Qty)
FROM
(
	SELECT DISTINCT a.BillNumberId,a.BillType,a.PtypeId,a.KtypeId,a.Qty,a.CostPrice,a.CostTotal,a.PostTime,a.SortID
	FROM InOutstocktable a,
	#StockInfo b
	WHERE a.PtypeId=b.PTypeID			
	AND a.KtypeId=b.KTypeID
	AND a.PostTime>=@datMinPostTime
) a
ORDER BY a.PostTime,a.SortID,a.Qty
--SELECT '#@datMinPostTime',@datMinPostTime

--SELECT '#AllAfterBill',* FROM #AllAfterBill ORDER BY SortID

--SELECT '#StockInfo',* FROM #StockInfo


--根据历史库存，来计算出库时所取的成本价
--处理InOutStockTable


--循环修改(两重循环)

DECLARE
	@decIniQty			 NUMERIC(24, 10) ,
	@decIniCostTotal	 NUMERIC(24, 10) ,
	@decNewQty			 NUMERIC(24, 10) ,
	@decNewCostTotal	 NUMERIC(24, 10) ,
	@decQty				 NUMERIC(24, 10) ,
	@decTotal			 NUMERIC(24, 10) ,
	@decCostPrice		 NUMERIC(24, 10) ,
	@decCurQty			 NUMERIC(24, 10) ,		--主要用于出库时，计算当前出库数量，金额
	@decCurCostTotal	 NUMERIC(24, 10) 
	

CREATE TABLE #SumTotal(
	Qty					 NUMERIC(24, 10) ,
	Total				 NUMERIC(24, 10) 
)

--假设#StockInfo表示所影响到的库存，#AfterModifyBill表示所影响到的单据
DECLARE
	@chvPTypeID			VARCHAR(50),
	@chvKTypeID			VARCHAR(50),
	@m					BIGINT,
	@n					BIGINT,
	@intSortID			BIGINT,
	@intTempBillType	INT,
	@strTempBillCode	VARCHAR(200),
	@strKFullName		VARCHAR(50),
	@strPFullName		VARCHAR(50),
	@strPUserCode		VARCHAR(50),
	@intGoOn			BIT,
	@chvOtherKTypeID	VARCHAR(50),
	@datOtherPostTime	DATETIME,
	@i								INT,			--记录调试步骤
	@intCostSale		TINYINT,
	@intTempBillNumberID			BIGINT,
	@intTempBillID					BIGINT,
	@intTempOldBillNumberID			BIGINT,			--关联单据的主ID
	@intTempOldID					BIGINT	--关联单据的明细ID
	
--记录有成本价销售的销售出库单(查下有没成本价退货的销售出库单)	#table_CostSaleBill
--CREATE TABLE #table_CostSaleBill(BillNumberID	BIGINT)
	
SELECT
	@intGoOn=0	,
	@i=0

--SELECT '#AfterModifyBill',* FROM #AfterModifyBill ORDER BY SortID

--SELECT SortID,BillType,KTypeID,PTypeID,BillNumberID,BillID
--FROM #AfterModifyBill
DECLARE AfterBill_CURSOR CURSOR FOR
SELECT SortID,BillType,KTypeID,PTypeID,BillNumberID,BillID
FROM #AfterModifyBill
ORDER BY PostTime,SortID,Qty

OPEN AfterBill_CURSOR
FETCH NEXT FROM AfterBill_CURSOR 
INTO @intSortID,@intTempBillType,@chvKTypeID,@chvPTypeID,@intTempBillNumberID,@intTempBillID

WHILE @@FETCH_STATUS = 0  AND @intGoOn=0
BEGIN
	--先得到期初
	SELECT
	@decIniQty=0,
	@decIniCostTotal=0,
	@decNewQty=0,
	@decNewCostTotal=0,
	@m=0,
	@n=0,
	@i=@i+1

	IF EXISTS(
		SELECT
			PTypeID
		FROM #IniData
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
	)
	BEGIN
		SELECT
			@decIniQty=Qty,
			@decIniCostTotal=CostTotal,
			@m=BeginSort
		FROM #IniData
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
		
		SELECT
			@decIniQty=ISNULL(@decIniQty,0),
			@decIniCostTotal=ISNULL(@decIniCostTotal,0),
			@m=ISNULL(@m,0)
	END
	
	/*
	SELECT '期初前'
	
	SELECT '期初前',*
	FROM #IniData
	WHERE PtypeId=@chvPTypeID
	AND KtypeId=@chvKTypeID
	*/

	--依次修改影响到的出库成本
	
	SELECT @n=NewSortID,@decCurQty=Qty
	FROM #AllAfterBill
	WHERE PtypeId=@chvPTypeID
	AND KtypeId=@chvKTypeID
	AND SortID=@intSortID
	
	SELECT 
		@n=ISNULL(@n,0),@decCurQty=ISNULL(@decCurQty,0)
		
	
	/*
	SELECT '期初',@chvPTypeID,@chvKTypeID,@decIniQty,@decIniCostTotal,'m='+CAST(@m AS VARCHAR(10)),'n='+CAST(@n AS VARCHAR(10)),@decCurQty,@intSortID
	
	SELECT '调整前'
	
	SELECT '调整前',*
	FROM #AllAfterBill
	WHERE PtypeId=@chvPTypeID
	AND KtypeId=@chvKTypeID
	ORDER BY SortID
	*/
	
	
	IF @decCurQty<0 OR (@decCurQty>0 AND @intTempBillType NOT IN (34,161,144,21,188,201,16,57,174,17) )
	BEGIN
		SELECT
			@decNewQty=SUM(Qty),
			@decNewCostTotal=SUM(CostTotal)
		FROM #AllAfterBill
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
		AND NewSortID>@m
		AND NewSortID<@n
	END
	ELSE
	BEGIN
		SELECT
			@decNewQty=SUM(Qty),
			@decNewCostTotal=SUM(CostTotal)
		FROM #AllAfterBill
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
		AND NewSortID>@m
		AND NewSortID<=@n
	END	
	
	SELECT
		@decNewQty=ISNULL(@decNewQty,0),
		@decNewCostTotal=ISNULL(@decNewCostTotal,0)
	
	
	SELECT
		@decQty=@decIniQty+@decNewQty,
		@decTotal=@decIniCostTotal+@decNewCostTotal
	
		------------------销售退货是入库,如果是调用销售出库单退货,则成本价该和销售单一致start-------
		SELECT @intTempOldID=0,@intTempOldBillNumberID=0
		IF @intTempBillType=45  and @intcostpricesaleback=1
	BEGIN
		SELECT @intTempOldID=a.OldID,@intTempOldBillNumberID=a.OldBillNumberID
		FROM saleBackBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		INNER JOIN BillIndex c
		ON a.OldBillNumberID=c.BillNumberId
		WHERE a.BillNumberId=@intTempBillNumberID AND a.ID=@intTempBillID AND b.IsIni=0 AND c.ifcheck='t'
			--select'@intTempOldBillNumberID',@intTempOldBillNumberID,'@intTempOldID',@intTempOldID
	END
		

	IF @intTempBillType=45 AND ISNULL(@intTempOldID,0)>0 AND @intcostpricesaleback=1 
	BEGIN
		--需要参考销售成本的，销售退货是入库
		SELECT @decCostPrice=ISNULL(CostPrice,0),@decCurCostTotal=ROUND(ISNULL(CostPrice,0)*@decCurQty,@intMoneyDot)
		FROM InoutStockTable  --??注意,如果是参照的期初的销售退货单呢?看下SALEBILL中有无COSTPRICE
		WHERE BillNumberID=@intTempOldBillNumberID AND ID=@intTempOldID

		UPDATE InOutstocktable
		SET 
			CostTotal=@decCurCostTotal,
			CostPrice=@decCostPrice
		WHERE SortID=@intSortID  
		
		UPDATE #AllAfterBill
		SET 
			CostTotal=@decCurCostTotal,
			CostPrice=@decCostPrice
		WHERE SortID=@intSortID 
		
		SELECT
			@decQty=@decQty+@decCurQty,
			@decTotal=@decTotal+@decCurCostTotal
		SELECT 
			@decCurQty=0,@decCurCostTotal=0
	
	END	
		------------------销售退货是入库end-------
		
		
	IF @decCurQty<0 OR (@decCurQty>0 AND @intTempBillType NOT IN (34,161,144,21,188,201,16,57,174,17) )
	BEGIN
		--SELECT '监测','@decQty=',@decQty,'@decCurQty',@decCurQty,'@decTotal=',@decTotal,'@decCostPrice=',@decCostPrice	,'类型',@intTempBillType

		--如果数量为零，则单价=金额
		SELECT
			@decCostPrice=CASE @decQty WHEN 0 THEN 0 ELSE ROUND(@decTotal/@decQty,@intPriceDot)
	 END
		--敏捷4667先计算下当前的成本价,如果为负数也需要取最近进价,没最近进价,就为0
	IF ( @decCurQty < 0 AND @decQty <= 0 )OR ( @decCostPrice <= 0  )
      BEGIN         
		SELECT @decPrice=ISNULL(a.RecPrice,0)FROM PType_STypePrice a
		INNER JOIN dbo.ptype b ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
		WHERE  a.PTypeID=@chvPTypeID
         IF ISNULL(@decPrice, 0) <> 0               
               BEGIN
                 SELECT @decCostPrice = @decPrice
                END
          else if @intTempBillType=45 and ISNULL(@decPrice, 0)=0 --如果没有最近进价,退货单取输入的成本价
               begin
                select @decCostPrice=InputCostPrice from salebackbill a WHERE a.BillNumberId=@intTempBillNumberID AND a.ID=@intTempBillID 
               end
        END
	
   
		--SELECT '监测','@decQty=',@decQty,'@decTotal=',@decTotal,'@decCostPrice=',@decCostPrice	
		--SELECT '单据ID','单据数量',@decCurQty,'SortID',@intSortID,'m',@m,'n',@n,'IniQty',@decIniQty,'IniCostTotal',@decIniCostTotal,'NewQty',@decNewQty,'NewCostTotal',@decNewCostTotal,'Total',@decTotal,'Qty',@decQty,'CostPrice',@decCostPrice
		

		
		-----判断生成凭证后就不能修改
		DECLARE @tmpBilltype INT,
				@tmpInStock   INT,
				@tmpBillnumberid	NUMERIC(18,0)
				
		 SELECT @tmpBilltype=BillType,@tmpBillnumberid=BillNumberId,@tmpInStock= (CASE WHEN Qty>0 THEN 1 ELSE 0 END)  
		 FROM InOutstocktable  
		 WHERE SortID =@intSortID
		 
		 
		IF @intTempBillType IN (327,328,329) AND (SELECT CostSale FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId=@tmpBillnumberid)=1
		BEGIN				
		
				SELECT 
					@nRet=-460,
					@strErrMsg='被分摊的入库单据中存在后续单据按成本价配送，不允许分摊或红冲！请红冲该配送单之后再试',
					@intGoOn=1
		END
		
		--启用独立结转，：
		--1.其他出库单有凭证，不能过账，
		--2.其他的单据如果有（成本，完全的凭证）不能过账
		--3.其他单据只有普通凭证的情况下才能过账
		
		--不启用独立结转，有凭证，则采购分摊不能过账
		IF EXISTS (SELECT 1 FROM Userconfig WHERE ConfigName='independentoutprice'  AND Value='1' )
		BEGIN
			IF  EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE  GoodsBillId = @tmpBillnumberid  AND VourchBillId<>-1)
			    AND @tmpBilltype=202
			BEGIN
				SET @nRet=-215
				RETURN
			END 
			IF  EXISTS(SELECT 1 FROM Ac_deliverybill_VoucherBill WHERE  DeliveryBillId = @tmpBillnumberid  AND VourchBillId<>-1)
			    AND @tmpBilltype IN(327,328,329)
			BEGIN
				SET @nRet=-215
				RETURN
			END 
			IF EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE  GoodsBillId = @tmpBillnumberid  AND VourchBillId<>-1 AND IsCost IN (1,2)) 
					AND (@tmpBilltype NOT IN(140,142,143,141,34,144,188,201,174)	
							OR (@tmpBilltype IN(161,21,16,57) AND @tmpInStock = 0))
			BEGIN 
				SET @nRet=-215
				RETURN
			END 
		  
		END 
		ELSE 
		BEGIN 
			IF EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE  GoodsBillId = @tmpBillnumberid  AND VourchBillId<>-1) 
					AND (@tmpBilltype NOT IN(140,142,143,141,34,144,188,201,174)	
							OR (@tmpBilltype IN(161,21,16,57) AND @tmpInStock = 0))
			BEGIN
				SET @nRet=-215
				RETURN
			END 
			IF  EXISTS(SELECT 1 FROM Ac_deliverybill_VoucherBill WHERE  DeliveryBillId = @tmpBillnumberid  AND VourchBillId<>-1)
			    AND @tmpBilltype IN(327,328,329)
			BEGIN
				SET @nRet=-215
				RETURN
			END
		END 
				
		--SELECT * FROM Ac_GoodsBill_VoucherBill WHERE  GoodsBillId = @tmpBillnumberid 
		
		SELECT
			@decCurCostTotal=ROUND(@decCostPrice*@decCurQty,2)
						
		IF 	@intTempBillType=187
		BEGIN
			SELECT @intCostSale=CostSale
			FROM BillIndex
			WHERE BillNumberId=@tmpBillnumberid
		END
		ELSE
		BEGIN
			SELECT @intCostSale=0
		END
		--IF 	@intTempBillType IN(327,328,329)
		--BEGIN
		--	SELECT @intCostSale=CostSale
		--	FROM dbo.PosAllotApplyBillIndex
		--	WHERE BillNumberId=@tmpBillnumberid
		--END
		--ELSE
		--BEGIN
		--	SELECT @intCostSale=0
		--END		
		IF @intCostSale=0
		BEGIN
			UPDATE InOutstocktable
			SET 
				CostTotal=@decCurCostTotal,
				CostPrice=@decCostPrice
			WHERE SortID=@intSortID 
		END  
		ELSE
		BEGIN
			UPDATE InOutstocktable
			SET 
				CostTotal=@decCurCostTotal,
				CostPrice=@decCostPrice,
				Price=@decCostPrice,
				Total=-@decCurCostTotal,
				SalePrice=@decCostPrice,
				SaleTotal=-@decCurCostTotal,
				TaxPrice=@decCostPrice,
				TaxTotal=-@decCurCostTotal,
				NPrice=@decCostPrice,
				NTotal=-@decCurCostTotal,
				NSalePrice=@decCostPrice,
				NSaleTotal=-@decCurCostTotal,
				NTaxPrice=@decCostPrice,
				NTaxTotal=-@decCurCostTotal
			WHERE SortID=@intSortID 
		END
		
		
		
		UPDATE #AllAfterBill
		SET 
			CostTotal=@decCurCostTotal,
			CostPrice=@decCostPrice
		WHERE SortID=@intSortID 
		
		--对同价调拨单的入库进行单独处理
		
		
		IF @intTempBillType=17
		BEGIN
			UPDATE InOutstocktable
			SET 
				CostTotal=-@decCurCostTotal,
				CostPrice=@decCostPrice
			WHERE SortID=@intSortID+1 
			
			--#AllAfterBill也要修改
			UPDATE #AllAfterBill
			SET 
				CostTotal=-@decCurCostTotal,
				CostPrice=@decCostPrice
			WHERE SortID=@intSortID+1 	
		END
		/*
		ELSE IF @intTempBillType=140
		BEGIN
			--要处理委托代销库
			UPDATE InOutstocktable
			SET 
				CostTotal=-@decCurCostTotal,
				CostPrice=@decCostPrice
			WHERE SortID=@intSortID+1 
			
			--#AllAfterBill也要修改
			UPDATE #AllAfterBill
			SET 
				CostTotal=-@decCurCostTotal,
				CostPrice=@decCostPrice
			WHERE SortID=@intSortID+1 
			
			--要处理CommissionStock	
		END
		*/
		
		
		
		SELECT
			@decQty=@decQty+@decCurQty,
			@decTotal=@decTotal+@decCurCostTotal
	
	END	
	
	--修改期初，不处理成本价
	IF NOT EXISTS(
		SELECT PTypeID
		FROM #IniData
		WHERE PTypeID=@chvPTypeID
		AND KTypeID=@chvKTypeID
	)
	BEGIN
		INSERT #IniData(PTypeID,KTypeID,Qty,CostTotal,BeginSort)
		SELECT @chvPTypeID,@chvKTypeID,@decQty,@decTotal,@n
	END
	ELSE
	BEGIN
		UPDATE #IniData
		SET Qty=@decQty,CostTotal=@decTotal,BeginSort=@n
		WHERE PTypeID=@chvPTypeID
		AND KTypeID=@chvKTypeID
	END
	
	/*
	SELECT '调整后',*
	FROM #IniData
	WHERE PTypeID=@chvPTypeID
	AND KTypeID=@chvKTypeID
	
	SELECT '调整后',*
	FROM #AllAfterBill
	WHERE PTypeID=@chvPTypeID
	AND KTypeID=@chvKTypeID
	*/

	FETCH NEXT FROM AfterBill_CURSOR 
	INTO @intSortID,@intTempBillType,@chvKTypeID,@chvPTypeID,@intTempBillNumberID,@intTempBillID
END

--修改GoodsStocks的成本(先直接计算，之后再改为通过之前累计的，加上后续的得到总金额，总数量)



--如果先销售2个100，再采购2个100，再报损1个，做费用分摊30，结果库存金额为0了，应该为30
--这个是因为报损单的成本价是取的30，这个不对。对于用户录入成本或取最近进价的，该怎么处理？

--如果等于0了，则直接取费用分摊单的金额 

CLOSE AfterBill_CURSOR
DEALLOCATE AfterBill_CURSOR



DECLARE Stock_CURSOR CURSOR FOR
SELECT PTypeID,KTypeID
FROM #StockInfo

OPEN Stock_CURSOR
FETCH NEXT FROM Stock_CURSOR INTO @chvPTypeID,@chvKTypeID

WHILE @@FETCH_STATUS = 0
BEGIN
	--最后算库存的成本价

	TRUNCATE TABLE #SumTotal
		
		
	--始终都把分摊单本身算上（需要测试有无问题）

	INSERT #SumTotal(Qty,Total)
	SELECT 
		ISNULL(SUM(Qty),0) AS Qty,
		ISNULL(SUM(CostTotal),0) AS Total
	FROM InOutstocktable
	WHERE  PtypeId=@chvPTypeID	
	AND KtypeId=@chvKTypeID
	UNION ALL
	SELECT 
		ISNULL(SUM(Qty),0) AS Qty,
		ISNULL(SUM(Total),0) AS Total
	FROM IniGoodsStocks
	WHERE  PtypeId=@chvPTypeID	
	AND KtypeId=@chvKTypeID


	IF EXISTS(
		SELECT PTypeID
		FROM GoodsStocks
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
	)
	BEGIN
		UPDATE GoodsStocks
		SET Qty=b.Qty,Total=b.Total,Price=b.Price
		FROM
		(
			SELECT 
				SUM(a.Qty) AS Qty,
				SUM(a.Total) AS Total,
				CASE SUM(a.Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(a.Total) AS  NUMERIC(24, 10) )/CAST(SUM(a.Qty) AS  NUMERIC(24, 10) ),4) END AS Price
			FROM #SumTotal a
		) b	
		WHERE PtypeId=@chvPTypeID	
		AND KtypeId=@chvKTypeID
	END
	ELSE
	BEGIN
		--因为现在QTY=0的，系统会删除记录，所以需要追加
		
		--如果存在同价调拨单，则不用追加，因为可能转移到其他仓库了
		IF NOT EXISTS(
			SELECT BillNumberID
			FROM #AllAfterBill
			WHERE PTypeID=@chvPTypeID
			AND KTypeID=@chvKTypeID
			AND BillType=17
		)
		BEGIN
			IF EXISTS(
				SELECT SUM(Qty)
				FROM #SumTotal
				HAVING SUM(Qty)<>0 OR SUM(Total)<>0
			)
			BEGIN
				INSERT GoodsStocks(PtypeId,KtypeId,Qty,Price,Total)
				SELECT @chvPTypeID,@chvKTypeID,b.Qty,b.Price,b.Total
				FROM
				(
					SELECT 
						SUM(a.Qty) AS Qty,
						SUM(a.Total) AS Total,
						CASE SUM(a.Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(a.Total) AS  NUMERIC(24, 10) )/CAST(SUM(a.Qty) AS  NUMERIC(24, 10) ),4) END AS Price
					FROM #SumTotal a
				) b	
			END
		END
	END
	
	FETCH NEXT FROM Stock_CURSOR INTO @chvPTypeID,@chvKTypeID
END
CLOSE Stock_CURSOR
DEALLOCATE Stock_CURSOR



--注意删除只在本过程用的表
DROP TABLE #SumTotal	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

采购费用分摊红冲之前影响过的单据


*/
CREATE   PROCEDURE Gp_BuyShareFee_RedWord 
(
	@nBillID			numeric(10,0),		--蓝单ID
	@nNewBillID			numeric(10,0),		--红单ID
	@nBillType			INT,
	@nRet				INT	OUT,
	@strErrMsg			VARCHAR(500) OUT
)
--@encode$--
AS


--得到采购费用摊销单的信息

DECLARE
	@datRelativeDate		DATETIME,		--关联的物流单据的时间
	@datMonthProc			DATETIME		--月结时间
	

SELECT @datMonthProc=StartDate
FROM MonthProc
WHERE MonthNo='本期'

DECLARE
	@datBillDate		DATETIME,
	@datPostTime		DATETIME,
	@chvDTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@intBillType		INT,
	@chvETypeID			VARCHAR(50)
	
SELECT
	@datBillDate=BillDate,
	@datPostTime=BillDate,
	@chvDTypeID=DTypeId,
	@chvSTypeID=Stypeid,
	@intBillType=BillType,
	@chvETypeID=ETypeID
FROM BillIndex
WHERE BillNumberId=@nBillID

--本单关联的物流单据与费用分摊信息(考虑下有无其他途径获取这些单据)
CREATE TABLE #SourceBill(
	BillNumberID			BIGINT,
	PTypeID					VARCHAR(50),
	KTypeID					VARCHAR(50),
	ShareFee				 NUMERIC(24, 10) ,
	PostTime				DATETIME,
	BillDate				DATETIME,
	ID						BIGINT,
	FromBillNumberID		BIGINT,
	FromBillType             BIGINT,
	FromID					BIGINT,
	Comment					VARCHAR(500)
)

EXEC Gp_BuyShareFee_GetSourceBill 
	@nBillID,
	@nBillType,
	@datMonthProc

		
--处理其他单据的成本（包括单据的出库部分，部分入库类单据，还有同价调拨单的连环单据）
CREATE TABLE #AfterModifyBill(
	BillNumberID	BIGINT,
	BillType		INT,
	BillID			BIGINT,
	PTypeID			VARCHAR(50),
	KTypeID			VARCHAR(50),
	SortID			BIGINT,
	Qty				 NUMERIC(24, 10) ,
	PostTime		DATETIME
)

SELECT
	@nRet=0,
	@strErrMsg=''

EXEC Gp_BuyShareFee_OutBill_AlterCost
	@nBillID,
	@nBillType,
	@nRet OUT,
	@strErrMsg OUT
	
IF @nRet<>0 RETURN	

--处理库存商品总值

EXEC Gp_BuyShareFee_DealCostTotal
	@nBillID,
	@nBillType,
	@chvSTypeID

--处理对应的其他科目

EXEC Gp_BuyShareFee_DealOtherTotal
	@nBillID,
	@nBillType,
	@chvSTypeID
	
--对于涉及到的单据，回写成本价，成本金额
EXEC Gp_NeedFill

UPDATE BuyBill
SET ShareFee=ISNULL(BuyBill.ShareFee,0)-b.ShareFee
From ShareSourceBill b
WHERE b.BillNumberId=@nBillID AND b.FromBillType=34
AND BuyBill.ID=b.FromBillID

--红冲回写生产拆装单
UPDATE DisassembleBill
SET ShareFee=ISNULL(DisassembleBill.ShareFee,0)-b.ShareFee
From ShareSourceBill b
WHERE b.BillNumberId=@nBillID AND b.FromBillType=16
AND DisassembleBill.ID=b.FromBillID


UPDATE InOutstocktable
SET ShareFee=ISNULL(InOutStockTable.ShareFee,0)-b.ShareFee
From ShareSourceBill b
WHERE b.BillNumberId=@nBillID
AND InOutstocktable.BillNumberId=b.FromBillNumberID
AND InOutstocktable.ID=b.FromBillID
		



DECLARE @RedMonthEndFlag varchar(1) -- 是否红冲月结前的单据
SET @RedMonthEndFlag ='1' --有红冲月结前单据

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

取出采购费用分摊单需要影响的单据

*/
CREATE   PROCEDURE Gp_BuyShareFee_ReferTo 
(
	@nBillID			NUMERIC(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT
)
--@encode$--
AS

--目前都是取的非红冲的单据

--#StockInfo是采购费用分摊单所关联的商品，仓库

--采购费用分摊单的QTY为0，所以把采购费用分摊单本身排除在外了
--确定需要改哪些明细(非红冲的出库明细)（因为新插入的费用分摊单是当天的最后一个，所以按PostTime来比较）

INSERT #AfterModifyBill(BillNumberID,BillType,BillID,PTypeID,KTypeID,SortID,Qty,PostTime)
--一般来说，出库部分的都需要处理（之后再把特殊的单据剔除）
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
FROM InOutstocktable a
INNER JOIN
(
	SELECT PTypeID,KTypeID,MIN(PostTime) AS PostTime
	FROM #SourceBill 
	GROUP BY PTypeID,KTypeID
) b
ON a.PtypeId=b.PTypeID 
AND a.KtypeId=b.KTypeID
WHERE a.PostTime>b.PostTime
AND a.Audited=1
AND a.Qty<0
AND a.BillType NOT IN (140,142,143,141)
--AND a.HandZeroCost=0
UNION ALL
/*
45	销售退货单(如果关联了销售出库单)
160	销售换货单
142	委托代销退货单（这个要注意处理相关的代销库）
146	受托代销退货单
14	报溢单
197	领料退回单(它的成本是取的领料退回的成本)
215 零售退货单
*/
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
FROM InOutstocktable a
INNER JOIN
(
	SELECT PTypeID,KTypeID,MIN(PostTime) AS PostTime
	FROM #SourceBill 
	GROUP BY PTypeID,KTypeID
) b
ON a.PtypeId=b.PTypeID 
AND a.KtypeId=b.KTypeID
WHERE a.PostTime>b.PostTime
AND a.Audited=1
AND a.Qty>0
AND a.BillType NOT IN (34,161,144,21,188,201,16,57,174,140,142,143,141)
--AND a.HandZeroCost=0

--对同价调拨单进行循环处理(直到此后没有新的同价调拨单为止，然后再把这些同价调拨单后所影响的单据列出来)

--所影响到的同价调拨单入库（同价调拨单的调入仓库始终都不同于调出仓库）

--需要涉及到其他仓库，那么对于这些仓库后面的单据，也会影响到后面


CREATE TABLE #MoveSameBill(
	BillNumberID	BIGINT,
	BillType		INT,
	BillID			BIGINT,
	PTypeID			VARCHAR(50),
	KTypeID			VARCHAR(50),
	PostTime		DATETIME,
	SortID			INT
)

INSERT #MoveSameBill
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.PostTime,a.SortID
FROM InOutstocktable a
INNER JOIN
(
	SELECT a.BillNumberId,a.ID
	FROM InOutstocktable a
	INNER JOIN
	(
		SELECT PTypeID,KTypeID,MIN(PostTime) AS PostTime
		FROM #SourceBill 
		GROUP BY PTypeID,KTypeID
	) b
	ON a.PtypeId=b.PTypeID 
	AND a.KtypeId=b.KTypeID
	WHERE a.PostTime>b.PostTime
	AND a.Audited=1
	AND a.Qty<0
	AND a.BillType=17
) b
ON a.BillNumberId=b.BillNumberId
AND a.ID=b.ID
WHERE a.BillType=17
AND a.Audited=1
AND a.Qty>0


--然后需要判断同价调拨入库后的同价调拨单（递归）
DECLARE
	@intGoOn	BIT
	
SELECT @intGoOn=0

WHILE @intGoOn=0
BEGIN
	INSERT #MoveSameBill
	SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.PostTime,a.SortID
	FROM InOutstocktable a
	INNER JOIN
	(
		--从同价调拨入库后查后续的同价调拨单
		SELECT a.BillNumberId,a.ID,a.PtypeId,a.KtypeId,a.SortID
		FROM InOutstocktable a
		INNER JOIN
		(
			SELECT PTypeID,KTypeID,MIN(SortID) AS SortID
			FROM #MoveSameBill 
			GROUP BY PTypeID,KTypeID
		) b
		ON a.PtypeId=b.PTypeID 
		AND a.KtypeId=b.KTypeID
		AND a.Audited=1
		AND a.Qty<0
		AND a.BillType=17
		WHERE a.SortID>b.SortID
	) b
	ON a.BillNumberId=b.BillNumberId
	AND a.ID=b.ID
	WHERE a.BillType=17
	AND a.Audited=1
	AND a.Qty>0
	AND NOT EXISTS
	(
		SELECT b.BillID
		FROM #MoveSameBill b
		WHERE b.BillID=a.ID
	)
	
	IF @@ROWCOUNT=0
	BEGIN
		SET @intGoOn=1
	END
END


	
--在把后续同价调拨单据都罗列后，查会影响到的后续相关单据
INSERT #AfterModifyBill(BillNumberID,BillType,BillID,PTypeID,KTypeID,SortID,a.Qty,a.PostTime)
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
FROM
(
	SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
	FROM InOutstocktable a
	INNER JOIN
	(
		SELECT PTypeID,KTypeID,MIN(SortID) AS SortID
		FROM #MoveSameBill 
		GROUP BY PTypeID,KTypeID
	) b
	ON a.PtypeId=b.PTypeID 
	AND a.KtypeId=b.KTypeID
	WHERE a.SortID>=b.SortID
	AND a.Audited=1
	AND a.Qty<0
	AND a.BillType NOT IN (140,142,143,141)
	--AND a.HandZeroCost=0
	UNION ALL
	SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
	FROM InOutstocktable a
	INNER JOIN
	(
		SELECT PTypeID,KTypeID,MIN(SortID) AS SortID
		FROM #MoveSameBill 
		GROUP BY PTypeID,KTypeID
	) b
	ON a.PtypeId=b.PTypeID 
	AND a.KtypeId=b.KTypeID
	WHERE a.SortID>=b.SortID
	AND a.Audited=1
	AND a.Qty>0
	AND a.BillType NOT IN (34,161,144,21,188,201,16,57,174,140,142,143,141)
	--AND (a.HandZeroCost=0 OR (a.HandZeroCost=1 AND a.BillType=17))
) a
WHERE NOT EXISTS
(
	SELECT b.BillID
	FROM #AfterModifyBill b
	WHERE b.SortID=a.SortID
)
--UNION ALL
--SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
--FROM InOutstocktable a
--INNER JOIN
--(
--	SELECT PTypeID,MIN(PostTime) AS PostTime
--	FROM #SourceBill 
--	GROUP BY PTypeID
--) b
--ON a.PtypeId=b.PTypeID 
--WHERE a.PostTime>b.PostTime
--AND a.Audited=1
--AND a.Qty>0
--AND a.BillType =329

--对于没在#StockInfo中的PTypeID,KTypeID，需要补充进来
INSERT #StockInfo(PTypeID,KTypeID)
SELECT DISTINCT a.PTypeID,a.KTypeID
FROM #AfterModifyBill a
WHERE NOT EXISTS(
	SELECT b.PTypeID
	FROM #StockInfo b
	WHERE b.PTypeID=a.PTypeID
	AND b.KTypeID=a.KTypeID
)


--不用把本采购费用分摊单要影响到的其他单据写到表中（因为红冲时影响的单据可能有变化，可能有部分单据已被红冲）





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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









--作者：谢吉康
--日期：2003-06-14
--描述：计算代销的总计
CREATE                PROCEDURE [GP_CalCommissionTotal] 
(
	@OperateID 	VARCHAR(50),
	@CType 	VARCHAR(20),
	@PTypeID	VARCHAR(50),
	@BTypeID	VARCHAR(50),
	@StartDate	VARCHAR(50),
	@endDate	VARCHAR(50),
	@JType 	INT,
	@showZero int =1	--1=显示库存为0    0=不显示库存为0 只针对 CType 'WB' 'WK' 'SB' 'SK' 时使用
)
--@encode$--
AS
	SET NOCOUNT ON
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperateID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperateID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)
	DECLARE @SQL_WHERE VARCHAR(8000)
	SELECT @SQL=''
	SELECT @SQL_WHERE=''
	DECLARE @CurPsonNum INT
	DECLARE @CurBsonNum INT
	SELECT @CurPsonNum=SonNum FROM PType WHERE TypeID=@PTypeID
	SELECT @CurBsonNum=SonNum FROM BType WHERE TypeID=@BTypeID
BEGIN
	IF @CType='WB' OR @CType='WK' OR @CType='SB' OR @CType='SK'
	BEGIN
		SELECT @SQL=@SQL+'
					SELECT	
						ISNULL(SUM(Qty),0) AS Qty,
						ISNULL(SUM(Total),0) AS  Total,
						ISNULL(SUM(CostTotal),0) AS  CostTotal	
					 FROM	CommissionStock'
		IF @CType='WB'	OR @CType='WK' OR @CType='WJ'
			SELECT @SQL_WHERE=@SQL_WHERE+' WHERE Type=140'
		ELSE			
			SELECT @SQL_WHERE=@SQL_WHERE+' WHERE Type=144'
		
		IF @PtypeID='00000'
			SELECT @SQL_WHERE=@SQL_WHERE+'  AND PtypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)	
		ELSE
			IF @CurPsonNum>=1 
				SELECT @SQL_WHERE=@SQL_WHERE+'  AND PtypeID LIKE '+CHAR(39)+@PTypeID+'%'+CHAR(39) +'  AND PtypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)	
			ELSE	 	
				SELECT @SQL_WHERE=@SQL_WHERE+'  AND PtypeID = '+CHAR(39)+@PTypeID+CHAR(39)	+'  AND PtypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)	

		IF @BtypeID='00000'
			SELECT @SQL_WHERE=@SQL_WHERE+'  AND ( BtypeID LIKE '+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' OR BtypeID LIKE '+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')'	
		ELSE
			IF @CurBsonNum>=1 
				SELECT @SQL_WHERE=@SQL_WHERE+'  AND  BtypeID LIKE '+CHAR(39)+@BTypeID+'%'+CHAR(39) +'  AND ( BtypeID LIKE '+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' OR BtypeID LIKE '+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')'	
			ELSE	 	
				SELECT @SQL_WHERE=@SQL_WHERE+'  AND  BtypeID = '+CHAR(39)+@BTypeID+CHAR(39) +'  AND ( BtypeID LIKE '+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' OR BtypeID LIKE '+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')'	

		SELECT @SQL=@SQL+@SQL_WHERE	
		IF @showZero=0 
			SELECT @SQL=@SQL+' AND qty<>0'
	END

	IF (@CType='WJ' OR @CType='SJ') AND (@JType=1 OR @JType=2 OR @JType=3)
	BEGIN
		SELECT @SQL=@SQL+'
			SELECT  ISNULL(SUM(a.qty),0) AS qty,ISNULL(SUM(a.costtotal),0) AS costtotal,ISNULL(SUM(a.total),0) AS total
			FROM    InOutStockTable a,
		 			BillIndex bil
			WHERE   a.billnumberid=bil.billnumberid
					AND bil.RedWord = 0
					AND bil.IfCheck = ''t'''
				IF @CType='WJ' 
					BEGIN	
						IF @JType=1										
							BEGIN
								SELECT @SQL='
											SELECT  ISNULL(SUM(-a.qty),0) AS qty,ISNULL(SUM(-a.costtotal),0) AS costtotal,ISNULL(SUM(-a.total),0) AS total
											FROM    InOutStockTable a,
										 			BillIndex bil
											WHERE   a.billnumberid=bil.billnumberid
													AND bil.RedWord = 0
													AND bil.IfCheck = ''t'''
					   			--SELECT @SQL=@SQL+' AND bil.BillType IN (140,142) AND a.KtypeId=''10000''' 
								--SELECT @SQL=@SQL+' AND a.KtypeID LIKE '+CHAR(39)+@MKtypeID+'%'+CHAR(39)
								SELECT @SQL=@SQL+' AND bil.BillType IN (140,142) ' +'
												   AND 
														(
															(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
															(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
														)'
							END
						ELSE
							BEGIN
								IF @JType = 2
									BEGIN
					   					SELECT @SQL='
											SELECT  ISNULL(SUM(-a.qty),0) AS qty,ISNULL(SUM(-a.costtotal),0) AS costtotal,ISNULL(SUM(-a.total),0) AS total
											FROM    InOutStockTable a,
										 			BillIndex bil
											WHERE   a.billnumberid=bil.billnumberid
													AND bil.RedWord = 0
													AND bil.IfCheck = ''t'''
										SELECT @SQL=@SQL+' AND bil.BillType IN (141) AND a.KtypeId=''10000''' 														
									END
								ELSE    -- 未结算 应该为发货（140）-退货（141）-结算（142） add by chen_qihua 2004-5-8
									BEGIN
										--SELECT @SQL=@SQL+' AND bil.BillType IN (141,142,140) AND a.KtypeId=''10000'''
										SELECT @SQL='
											SELECT  ISNULL(SUM(case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end ),0) AS qty,ISNULL(SUM(case a.billtype when ''140'' then -a.costtotal when ''142'' then -a.costtotal else a.costtotal end),0) AS costtotal,ISNULL(SUM(case a.billtype when ''140'' then -a.total when ''142'' then -a.total else a.total end),0) AS total
											FROM    InOutStockTable a,
										 			BillIndex bil
											WHERE   a.billnumberid=bil.billnumberid
													AND bil.RedWord = 0
													AND bil.IfCheck = ''t'''
										SELECT @SQL=@SQL+' AND bil.BillType IN (141,142,140) '	+'
													AND 
													(
														(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
														(a.billtype=141 AND a.ktypeid=''10000'') OR
														(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
													)'
									END
									
									--SELECT @SQL=@SQL+' AND bil.BillType IN (141,142,143) AND a.KtypeId<>''10000'''
							END
					END
				ELSE
					BEGIN
						IF @JType=1
							BEGIN
					   			SELECT @SQL=@SQL+' AND bil.BillType IN (144,146) AND a.KtypeId<>''10000''' 
								SELECT @SQL=@SQL+' AND a.KtypeID LIKE '+CHAR(39)+@MKtypeID+'%'+CHAR(39)
							END
						ELSE
							BEGIN
								IF @JType=2
						   			SELECT @SQL=@SQL+' AND bil.BillType IN (145)' 
								ELSE
						   			SELECT @SQL=@SQL+' AND bil.BillType IN (144,145,146,147) AND a.KtypeId=''10000'''

							END
					END

				IF @pTypeID='00000'
					SELECT @SQL=@SQL+' AND a.PtypeID LIKE '+CHAR(39)+'%'+CHAR(39)
				ELSE
					IF @CurPSonNum>=1
						SELECT @SQL=@SQL+' AND a.PtypeID LIKE '+CHAR(39)+@pTypeID+'%'+CHAR(39)
					ELSE
						SELECT @SQL=@SQL+' AND a.PtypeID = '+CHAR(39)+@pTypeID+CHAR(39)
				IF @bTypeID='00000'
					SELECT @SQL=@SQL+' AND bil.BtypeID LIKE '+CHAR(39)+'%'+CHAR(39)
				ELSE
					IF @CurBSonNum>=1
						SELECT @SQL=@SQL+' AND bil.BtypeID LIKE '+CHAR(39)+@bTypeID+'%'+CHAR(39)
					ELSE
						SELECT @SQL=@SQL+' AND bil.BtypeID = '+CHAR(39)+@bTypeID+CHAR(39)													
			
   			SELECT @SQL=@SQL+' AND bil.billdate>='+CHAR(39)+@startDate+CHAR(39)+' AND bil.billdate<='+CHAR(39)+@endDate+CHAR(39)										



			SELECT @SQL=@SQL+' AND a.PtypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						  AND bil.EtypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						  AND (bil.BtypeID LIKE '+CHAR(39)+@MBtypeID+'%'+CHAR(39)+' OR bil.BtypeID LIKE '+CHAR(39)+@MBtypeID2+'%'+CHAR(39)+')'
						  --AND bil.KtypeID LIKE '+CHAR(39)+@MKtypeID+'%'+CHAR(39)

	END
	--PRINT(@SQL)
	EXEC(@SQL)
END





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


--根据条件计算出ptypeid
--author:王跃
--LAST modified:2002-4-25
--最后修改:添加权限管理
CREATE    PROCEDURE GP_CalculateStockDistributingPtypeId23
(
	@BeginDate 		smalldatetime,
	@EndDate   		smalldatetime,
	@UserCode 		VARCHAR(26),
	@FullName 		VARCHAR(66),
	@szEntryCode	varchar(200),
	@szKtypeId 		VARCHAR(100),
	@CurPageNo 		INT,
	@PageRows 		INT,
	@szFlag    		CHAR(1),
	--权限管理
	@mangerptypeid 	VARCHAR(100),
	@mangerktypeid 	VARCHAR(100),
	--
	@PtypeId VARCHAR(100) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Row INT,@Re INT
IF @szFlag='P' AND (@BeginDate IS NULL OR @EndDate IS NULL)
	BEGIN
  		--RAISERROR('日期参数不能为空！',16,1)
  		RETURN
	END

IF @CurPageNo<1  
	SELECT @CurPageNo=1
	SELECT @Row=(@CurPageNo-1)*@PageRows+1
IF @UserCode IS NULL OR @UserCode=''  
	SELECT @UserCode='%'
ELSE  
	SELECT @UserCode='%'+@UserCode+'%'
IF @FullName IS NULL OR @FullName=''  
	SELECT @FullName='%'
ELSE 
	SELECT @FullName='%'+@FullName+'%'
	
IF ISNULL(@szEntryCode,'')=''  
	SELECT @szEntryCode='%'
ELSE 
	SELECT @szEntryCode='%'+@szEntryCode+'%'
		
IF @szKtypeId IS NULL OR @szKtypeId=''
 	SELECT @szKtypeId='%'
DECLARE @sql VARCHAR(2000)

IF @szFlag='A'
	DECLARE Cal CURSOR Scroll FOR
	SELECT 	TypeId 
	FROM 	Ptype 
	WHERE  	[UserCode] LIKE @UserCode 
			AND [FullName] LIKE @FullName 
			AND MultEntryCode LIKE @szEntryCode
			AND  Deleted=0 
			AND Sonnum=0 
			AND typeid LIKE @mangerptypeid+'%' 
	ORDER BY TypeId ASC
    FOR READ ONLY
 ELSE
    DECLARE Cal CURSOR Scroll FOR
	SELECT 	DISTINCT i.ptypeid 
	FROM  	inoutstocktable i 
		INNER JOIN ptype p ON  p.typeid=i.ptypeid   
	WHERE 	i.billdate>=@BeginDate 
			AND i.billdate<=@EndDate 
			AND i.ktypeid LIKE @szKtypeId 
			AND i.ktypeid LIKE @mangerktypeid+'%'  
			AND i.billtype<>57 
			AND p.UserCode LIKE @UserCode 
			AND p.FullName LIKE @FullName
			AND P.MultEntryCode LIKE @szEntryCode
			AND p.Deleted=0 
			AND p.Sonnum=0 
			AND p.typeid LIKE @mangerptypeid+'%' 
	ORDER BY i.pTypeId ASC
    FOR READ ONLY 

OPEN Cal
FETCH ABSOLUTE @Row  FROM Cal INTO @PtypeId
CLOSE Cal
Deallocate Cal


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.08.26
	描述：结束初始时计算余额表
		1.如果不存在日记账，仅将期初数据转入余额表
		2.如果存在日记账，在1的基础上，重新计算日记账所在期间相应余额
*/
CREATE PROCEDURE Gp_CalculateTeBalance
(
	@STypeId	VARCHAR(50),
	@FYear		INT,
	@FPeriod	INT
)
--@encode$--
AS
SET NOCOUNT ON

--最大的日记账日期
DECLARE @MaxJournalDate DATETIME
SELECT TOP 1 @MaxJournalDate = BusinessDate FROM dbo.Te_Journal_Detail ORDER BY BusinessDate DESC

--存在日记账最大的年度、期间
DECLARE @MaxYear INT,@MaxPeriod INT

SELECT @MaxYear = FYear,@MaxPeriod = FPeriod FROM dbo.Ac_Period WHERE FBegin <= @MaxJournalDate AND @MaxJournalDate <=FEnd

--当前年度、期间
DECLARE @minFPeriod	INT,@minFYear INT
SELECT @minFYear = SFYear,@minFPeriod = SFPeriod FROM dbo.Te_StartPeriod WHERE STypeId = @Stypeid

IF @MaxYear = @minFYear AND @MaxPeriod < @minFPeriod
	SET @MaxPeriod = @minFPeriod

IF @MaxYear < @minFYear
BEGIN
	SET @MaxYear = @minFYear
	SET @MaxPeriod = @minFPeriod
END

--期间总数
DECLARE @AcPeriodCount INT
SELECT @AcPeriodCount = COUNT(FPeriod) FROM dbo.Ac_Period WHERE FYear = @FYear

--循环，当前期间
DECLARE @currentFPeriod INT,@currentFyear INT
SET @currentFPeriod = @minFPeriod
SET @currentFyear = @minFYear

--指定期间开始、结束日期
DECLARE @FBegin DATETIME,@FEnd DATETIME

--BEGIN---
--2014.09.04调整为不保留已有业务数据，所以结束初始化数据仅处理期初的
SELECT @FBegin = FBegin,@FEnd = FEnd FROM dbo.Ac_Period WHERE FYear = @currentFyear AND FPeriod = @currentFPeriod

INSERT INTO dbo.Te_Balance
		( AccountId ,
		  BUId ,
		  ATypeId ,
		  STypeId ,
		  InitBalance ,
		  InitBalanceFor ,
		  InitYearBalance ,
		  InitYearBalanceFor ,
		  Cid ,
		  FYear ,
		  FPeriod ,
		  FDebit ,
		  FDebitFor ,
		  FCredit ,
		  FCreditFor ,
		  FEndBalance ,
		  FEndBalanceFor ,
		  FYtdDebit ,
		  FYtdDebitFor ,
		  FYtdCredit ,
		  FYtdCreditFor
		)
SELECT  AccountId,
		BUId,
		ATypeId,
		STypeId,
		SUM(InitBalance) AS InitBalance,
		SUM(InitBalanceFor) AS InitBalanceFor,
		SUM(InitYearBalance) AS InitYearBalance,
		SUM(InitYearBalanceFor) AS InitYearBalanceFor,
		Cid,
		FYear,
		FPeriod,
		SUM(FDebit) AS FDebit,
		SUM(FDebitFor) AS FDebitFor,
		SUM(FCredit) AS FCredit,
		SUM(FCreditFor) AS FCreditFor,
		SUM(FEndBalance) AS FEndBalance,
		SUM(FEndBalanceFor) AS FEndBalanceFor,
		SUM(FYtdDebit) AS FYtdDebit,
		SUM(FYtdDebitFor) AS FYtdDebitFor,
		SUM(FYtdCredit) AS FYtdCredit,
		SUM(FYtdCreditFor) AS FYtdCreditFor
	FROM
	(
	--期初日记账
	SELECT  ISNULL(T1.AccountId,0) AS AccountId,
			CASE WHEN T1.IsCash = 1 THEN 1 ELSE 2 END AS BUID,
			T1.ATypeId,
			T1.STypeId,
			SUM(T1.FEndBalanceOri) AS InitBalance,
			SUM(T1.FEndBalance) AS InitBalanceFor,
			SUM(T1.FEndBalanceOri + T1.FCreditOri - T1.FDebitOri) AS InitYearBalance,
			SUM(T1.FEndBalance + T1.FCredit - T1.FDebit) AS InitYearBalanceFor, 
			T1.Cid,
			@currentFyear AS FYear,
			@currentFPeriod AS FPeriod,
			0 AS FDebit,
			0 AS FDebitFor,
			0 AS FCredit,
			0 AS FCreditFor,
			SUM(T1.FEndBalanceOri) AS FEndBalance,
			SUM(T1.FEndBalance) AS FEndBalanceFor,
			0 AS FYtdDebit,
			0 AS FYtdDebitFor,
			0 AS FYtdCredit,
			0 AS FYtdCreditFor
	FROM dbo.Te_Journal_Detail T1
	WHERE T1.IsInit = 1 AND T1.STypeId = @STypeId
	GROUP BY AccountId,T1.IsCash,T1.ATypeId,T1.STypeId,T1.Cid

	UNION ALL
	--期初日记账,综合本位币
	SELECT  ISNULL(T1.AccountId,0) AS AccountId,
			CASE WHEN T1.IsCash = 1 THEN 1 ELSE 2 END AS BUID,
			T1.ATypeId,
			T1.STypeId,
			SUM(T1.FEndBalanceOri) AS InitBalance,
			SUM(T1.FEndBalanceOri) AS InitBalanceFor,
			SUM(T1.FEndBalanceOri + T1.FCreditOri - T1.FDebitOri) AS InitYearBalance,
			SUM(T1.FEndBalanceOri + T1.FCreditOri - T1.FDebitOri) AS InitYearBalanceFor, 
			0 AS Cid,
			@currentFyear AS FYear,
			@currentFPeriod AS FPeriod,
			0 AS FDebit,
			0 AS FDebitFor,
			0 AS FCredit,
			0 AS FCreditFor,
			SUM(T1.FEndBalanceOri) AS FEndBalance,
			SUM(T1.FEndBalanceOri) AS FEndBalanceFor,
			0 AS FYtdDebit,
			0 AS FYtdDebitFor,
			0 AS FYtdCredit,
			0 AS FYtdCreditFor
	FROM dbo.Te_Journal_Detail T1
	WHERE T1.IsInit = 1 AND T1.STypeId = @STypeId
	GROUP BY AccountId,T1.IsCash,T1.ATypeId,T1.STypeId

	UNION ALL
	--期初对账单
	SELECT  ISNULL(T1.AccountId,0) AS AccountId,
			3 AS BUID,
			T2.ATypeId,
			T2.STypeId,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance) * T1.rate
				ELSE SUM(T1.FEndBalance) / T1.rate
			END) AS InitBalance,
			SUM(T1.FEndBalance) AS InitBalanceFor,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance + T1.FCredit - T1.FDebit) * T1.rate
				ELSE SUM(T1.FEndBalance + T1.FCredit - T1.FDebit) / T1.Rate
			END) AS InitYearBalance,
			SUM(T1.FEndBalance + T1.FCredit - T1.FDebit) AS InitYearBalanceFor, 
			T1.Cid,
			@currentFyear AS FYear,
			@currentFPeriod AS FPeriod,
			0 AS FDebit,
			0 AS FDebitFor,
			0 AS FCredit,
			0 AS FCreditFor,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance) * T1.rate
				ELSE SUM(T1.FEndBalance) / T1.Rate
			END) AS FEndBalance,
			SUM(T1.FEndBalance) AS FEndBalanceFor,
			0 AS FYtdDebit,
			0 AS FYtdDebitFor,
			0 AS FYtdCredit,
			0 AS FYtdCreditFor
	FROM dbo.Te_BankStatementDetail T1
		INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
		INNER JOIN dbo.Ac_Currency T3 ON T1.Cid = T3.CId
	WHERE T1.IsInit = 1 AND T2.STypeId = @STypeId
	GROUP BY AccountId,T2.ATypeId,T2.STypeId,T1.Cid,T3.BasisType,T1.Rate

	UNION ALL
	--期初对账单,综合本位币
	SELECT  ISNULL(T1.AccountId,0) AS AccountId,
			3 AS BUID,
			T2.ATypeId,
			T2.STypeId,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance) * T1.rate
				ELSE SUM(T1.FEndBalance) / T1.rate
			END) AS InitBalance,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance) * T1.rate
				ELSE SUM(T1.FEndBalance) / T1.rate
			END) AS InitBalanceFor,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance + T1.FCredit - T1.FDebit) * T1.rate
				ELSE SUM(T1.FEndBalance + T1.FCredit - T1.FDebit) / T1.Rate
			END) AS InitYearBalance,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance + T1.FCredit - T1.FDebit) * T1.rate
				ELSE SUM(T1.FEndBalance + T1.FCredit - T1.FDebit) / T1.Rate
			END) AS InitYearBalanceFor, 
			0 AS cid,
			@currentFyear AS FYear,
			@currentFPeriod AS FPeriod,
			0 AS FDebit,
			0 AS FDebitFor,
			0 AS FCredit,
			0 AS FCreditFor,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance) * T1.rate
				ELSE SUM(T1.FEndBalance) / T1.Rate
			END) AS FEndBalance,
			dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN SUM(T1.FEndBalance) * T1.rate
				ELSE SUM(T1.FEndBalance) / T1.Rate
			END) AS FEndBalanceFor,
			0 AS FYtdDebit,
			0 AS FYtdDebitFor,
			0 AS FYtdCredit,
			0 AS FYtdCreditFor
	FROM dbo.Te_BankStatementDetail T1
		INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
		INNER JOIN dbo.Ac_Currency T3 ON T1.Cid = T3.CId
	WHERE T1.IsInit = 1 AND T2.STypeId = @STypeId
	GROUP BY AccountId,T2.ATypeId,T2.STypeId,T1.Cid,T3.BasisType,T1.Rate
	)T
	GROUP BY AccountId,BUId,ATypeId,STypeId,Cid,FYear,FPeriod
	
--重算年初
	UPDATE A
	SET A.InitYearBalance = B.InitYearBalance,
		A.InitYearBalanceFor = b.InitYearBalanceFor
	FROM dbo.Te_Balance A
		INNER JOIN (
			SELECT  ISNULL(AccountId,0) AS AccountId,
			CASE WHEN BUID = 3 THEN (ISNULL(InitBalanceOri,0) + ISNULL(FDebitOri,0) - ISNULL(FCreditOri,0))
				ELSE
				(ISNULL(InitBalanceOri,0) + ISNULL(FCreditOri,0) - ISNULL(FDebitOri,0)) 
			END AS InitYearBalance,
			CASE WHEN BUID = 3 THEN (ISNULL(InitBalance,0) + ISNULL(FDebit,0) - ISNULL(FCredit,0))
				ELSE
				(ISNULL(InitBalance,0) + ISNULL(FCredit,0) - ISNULL(FDebit,0)) 
			END AS InitYearBalanceFor,
			T1.Cid,
			BUId,
			AtypeId,
			STypeId
		FROM dbo.Te_InitDataIndex T1
			INNER JOIN dbo.Te_InitDataDetail T2 ON T1.Id = T2.IndexId
			INNER JOIN dbo.Ac_Currency T4 ON T1.Cid = T4.CId
		WHERE T2.FDebit <> 0 OR T2.FCredit <> 0 OR T2.InitBalance <> 0 AND T1.STypeId = @STypeId
		)B ON A.AccountId = B.AccountId AND A.ATypeId = B.AtypeId AND A.BUId = B.BUId AND A.Cid = B.Cid AND A.STypeId = B.STypeId
	
	
	UPDATE A
	SET A.InitYearBalance = B.InitYearBalance,
		A.InitYearBalanceFor = b.InitYearBalanceFor
	FROM dbo.Te_Balance A
		INNER JOIN (SELECT  SUM(InitYearBalance) AS InitYearBalance,
							SUM(InitYearBalance) AS InitYearBalanceFor,
							ATypeId,
							STypeId,
							BUId 
					FROM dbo.Te_Balance 
					WHERE STypeId = @STypeId AND Cid <> 0
					GROUP BY ATypeId,STypeId,BUId) B
				ON A.ATypeId = B.ATypeId AND A.STypeId = B.STypeId AND A.BUId = B.BUId
	WHERE A.STypeId = @STypeId AND A.Cid = 0

	--修改本年累计值本位币
	UPDATE Te_Balance
	SET 
		FYtdDebit=D.FDebitOri,
		FYtdDebitFor=D.FDebit,
		FYtdCredit=D.FCreditOri,
		FYtdCreditFor=D.FCredit
	FROM Te_Balance T
	INNER JOIN (
			SELECT 
				I.STypeId,
				D.AtypeId,
				ISNULL(D.AccountId,0) AccountId,
				I.BUId,
				I.Cid,
				SUM(D.FDebit) FDebit,
				SUM(D.FCredit) FCredit,
				SUM(D.FDebitOri) FDebitOri,
				SUM(D.FCreditOri) FCreditOri
			FROM Te_InitDataIndex I
			INNER JOIN Te_InitDataDetail D ON D.IndexId=I.Id
			GROUP BY 
				I.STypeId,
				D.AtypeId,
				D.AccountId,
				I.BUId,
				I.Cid
			UNION ALL
			SELECT 
				I.STypeId,
				D.AtypeId,
				ISNULL(D.AccountId,0) AccountId,
				I.BUId,
				0 Cid,
				SUM(D.FDebitOri) FDebit,
				SUM(D.FCreditOri) FCredit,
				SUM(D.FDebitOri) FDebitOri,
				SUM(D.FCreditOri) FCreditOri
			FROM Te_InitDataIndex I
			INNER JOIN Te_InitDataDetail D ON D.IndexId=I.Id
			GROUP BY 
				I.STypeId,
				D.AtypeId,
				D.AccountId,
				I.BUId
			) D ON D.STypeId=T.STypeId AND D.AtypeId=T.ATypeId AND D.AccountId=T.AccountId AND D.BUId=T.BUId AND D.Cid=T.Cid
			
---END---


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.1.5
	描述：调用GP_HandCreate_Voucher生成凭证，将select结果放到此处，以便GP_HandCreate_Voucher可方便用于批量生成
*/
CREATE PROCEDURE GP_Call_Voucher_Generate
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@AtId			INT = 0,				-- 凭证模版ID
	@specifyDate	DATE = '',				-- 手工指定凭证日期
	@Type			INT = 0	,				-- 结果类型 0.返回错误提示 1.返回错误凭证修改 2.凭证标错，并返回提示
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@InOutStypeId	VARCHAR(50)='',			-- 调拨单 调入/调出分支
	@IfCommission	INT = 0,				-- 单据类别：0：一般单据；1：提成单；2：暂估发票 3：优惠券 4:门店配送类单据
	@checkdeficit		INT	= 0					--是否检查赤字 0不检查，1检查提示，2检查不能保存
)
--@encode$--
AS
SET NOCOUNT ON

--非总账模式直接返回
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1)
	RETURN 0
	
--分支机构
DECLARE @STypeid VARCHAR(50)
		,@deficitvoucher INT

--会计科目多级权限表
CREATE TABLE #TmpLimit
(
	typeid	VARCHAR(50),
	stypeid	VARCHAR(50)
)

DECLARE @return INT,@verifyid VARCHAR(50),@VoucherId INT,@ErrorMsg VARCHAR(1000),@attachMsg INT,@BillType INT,@szPID VARCHAR(MAX)

IF @IfCommission = 0
	SELECT TOP 1 @BillType = BillType FROM dbo.BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
ELSE IF @IfCommission = 1
	SELECT TOP 1 @BillType = BillType FROM dbo.CommissionBillNew WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
ELSE IF @IfCommission = 2
	SELECT TOP 1 @BillType = BillType FROM dbo.ReceiptBillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
ELSE IF @IfCommission = 3--优惠券
	SELECT TOP 1 @BillType = BillType FROM dbo.Coupon_BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
ELSE IF @IfCommission = 4 --门店配送类单据
	SELECT TOP 1 @BillType = BillType FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
SET @attachMsg = 0

IF @atid = -1
BEGIN
	IF @IfCommission = 0
		SELECT @atid = atid FROM dbo.BillIndex WHERE BillNumberId IN (SELECT TOP 1 a FROM dbo.f_split(@BillNumberId,','))
	ELSE IF @IfCommission = 1
		SELECT @atid = atid FROM dbo.CommissionBillNew WHERE BillNumberId IN (SELECT TOP 1 a FROM dbo.f_split(@BillNumberId,','))
	ELSE IF @IfCommission = 2
		SELECT @atid = atid FROM dbo.ReceiptBillIndex WHERE BillNumberId IN (SELECT TOP 1 a FROM dbo.f_split(@BillNumberId,','))
	ELSE IF @IfCommission = 3--优惠券
		SELECT @atid = atid FROM dbo.Coupon_BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
	ELSE IF @IfCommission = 4 --门店配送类单据
		SELECT @atid = atid FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
END

--是否中断
DECLARE @justRep INT
SET @justRep = 0
IF @Type IN(0,2)
	SET @justRep = 1

DECLARE @InOutType INT--调拨单专用
SET @InOutType = 0
IF @BillType = 310
BEGIN
	SELECT a 
	INTO #TmpA
	FROM dbo.f_split(@BillNumberId,',')

	IF EXISTS(SELECT a FROM #TmpA WHERE a NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = -1) )
		SET @InOutType = -1
	ELSE IF EXISTS(SELECT a FROM #TmpA WHERE a NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = 1))
		SET @InOutType = 1
	ELSE 
		SET @InOutType = 0
END

EXEC @return = dbo.GP_HandCreate_Voucher	@BillNumberId,
											@szCheckMan,
											@AtId,
											@specifyDate,
											@verifyid OUTPUT,
											@VoucherId OUTPUT,
											@Type,
											@justRep,
											@szPID OUTPUT,
											@CreateType,
											@InOutStypeId,
											@IfCommission,
											@checkdeficit,
											@deficitvoucher OUTPUT

--即时生成凭证，返回相应的状态码
IF @CreateType = 0
BEGIN
	RETURN @return
END

IF @return = 0--生成成功
BEGIN
	IF @Type IN (0,2)
	BEGIN
		IF(@IfCommission=3)
		BEGIN
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) AS txt,1 AS flag
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
			FROM dbo.Coupon_BillIndex T1
			INNER JOIN dbo.Ac_CouponBill_VoucherBill T2 ON T1.BillNumberId = T2.CouponBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE 
				T3.BillNumberId = @VoucherId		
		END
		ELSE IF(@IfCommission=4)
		BEGIN
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) AS txt,1 AS flag
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
			FROM dbo.PosAllotApplyBillIndex T1
			INNER JOIN dbo.Ac_DeliveryBill_VoucherBill T2 ON T1.BillNumberId = T2.DeliveryBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE 
				T3.BillNumberId = @VoucherId	
		END
		ELSE
		BEGIN
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) AS txt,1 AS flag
						,@VoucherId AS voucherid
						,@deficitvoucher AS deficitvoucher
						,@return AS returnvalue
			FROM dbo.BillIndex T1
				INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
				INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
				INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T3.BillNumberId = @VoucherId
		END
	END
		
	ELSE
		SELECT NULL
END
ELSE IF @Type IN (0,2)
BEGIN
	IF @return IN(-14)
	BEGIN
		IF(@IfCommission=3)
		BEGIN
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +'。注：'+ @szPID AS txt,1 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.Coupon_BillIndex T1
			INNER JOIN dbo.Ac_CouponBill_VoucherBill T2 ON T1.BillNumberId = T2.CouponBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
		ELSE IF(@IfCommission=4)
		BEGIN
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +'。注：'+ @szPID AS txt,1 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.PosAllotApplyBillIndex T1
			INNER JOIN dbo.Ac_DeliveryBill_VoucherBill T2 ON T1.BillNumberId = T2.DeliveryBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
		ELSE 
		BEGIN		
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +'。注：'+ @szPID AS txt,1 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.BillIndex T1
			INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
	END
	ELSE IF @return IN(-12,-13) OR @Type = 0-- -12:根据模板生成的凭证金额全部为0，导致凭证没有分录。-13:已生成过凭证
	BEGIN
		IF(@IfCommission=3)
		BEGIN
			SELECT TOP 1 T1.BillCode,@szPID AS txt,-2 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.Coupon_BillIndex T1
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
		ELSE IF(@IfCommission=4)
		BEGIN
			SELECT TOP 1 T1.BillCode,@szPID AS txt,-2 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.PosAllotApplyBillIndex T1
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
		ELSE 
		BEGIN
			SELECT TOP 1 T1.BillCode,@szPID AS txt,-2 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.BillIndex T1
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
	END
	ELSE IF @Type = 2
	BEGIN
		IF(@IfCommission=3)
		BEGIN
			SELECT TOP 1 T1.BillCode,'已保存标错凭证['+t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +']'+@szPID AS txt, -1 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.Coupon_BillIndex T1
			INNER JOIN dbo.Ac_CouponBill_VoucherBill T2 ON T1.BillNumberId = T2.CouponBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE 
				T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
		ELSE IF(@IfCommission=4)
		BEGIN
			SELECT TOP 1 T1.BillCode,'已保存标错凭证['+t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +']'+@szPID AS txt, -1 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.PosAllotApplyBillIndex T1
			INNER JOIN dbo.Ac_CouponBill_VoucherBill T2 ON T1.BillNumberId = T2.CouponBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE 
				T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
		ELSE
		BEGIN		
			SELECT TOP 1 T1.BillCode,'已保存标错凭证['+t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +']'+@szPID AS txt, -1 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.BillIndex T1
			INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
				INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
				INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
	END	
END
ELSE IF @Type = 1
BEGIN
	IF @return = -12
	BEGIN
		--RAISERROR(@szPID,16,1)
		SELECT @szPID szPID,@return retFlag
		RETURN -1
	END
	ELSE IF @return = -13
	BEGIN
		RAISERROR('',16,1)
		RETURN
	END
		
	SELECT	BillDate,
		VgId,
		STypeId,
		FlowNo,
		@BillType AS SBillType,
		FComment,
		@InOutType AS InOutType
	FROM dbo.Ac_Voucher	
	WHERE BillNumberId = @VoucherId
	
	SELECT @STypeid = stypeid FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	
	IF @szCheckMan <> '00001'
		INSERT INTO #TmpLimit
				( typeid, stypeid )
		SELECT Typeid,Stypeid
		FROM dbo.F_LineAccount(@szCheckMan,@stypeid)
	ELSE
		INSERT INTO #TmpLimit
				( typeid, stypeid )
		SELECT TypeId,StypeId
		FROM dbo.Ac_Account
		WHERE StypeId = @stypeid
	
	SELECT	A.BillNumberId
			,a.Summary AS explain,
			b.UserCode,
			b.FullName,
			a.ATypeId AS typeid,
			ISNULL(c.Sysrow,1) AS sysrow,
			ISNULL(a.cid,1) AS cid,
			ISNULL(a.cid,1) AS moneytype,
			ISNULL(c.BasisType,0) AS BasisType,
			ISNULL(a.Rate,1) AS rate,
			CASE a.FAdc
				 WHEN 1		THEN ISNULL(a.FDebitTotalFor,FDebitTotal)
				 WHEN -1	THEN ISNULL(a.FCreditTotalFor,FCreditTotal)
			END AS balanceprice,
			CASE WHEN a.FDebitTotal = 0 THEN NULL ELSE FDebitTotal END AS lendprice,
			CASE WHEN a.FCreditTotal = 0 THEN NULL ELSE FCreditTotal END AS loanprice,
			a.FSettleNo,
			a.FSettleTypeID,
			a.Comment,
			a.STypeId,
			ISNULL(a.Fdc,a.fadc) AS fdc,
			a.FAdc,
			b.FAcnt,
			a.FCashFlowItem,
			a.RowNo,
			a.id,
			b.MainItems,
			b.AdditionItems,
			b.KeyId,
			ISNULL(b.IsCash,0) AS iscash,
			ISNULL(b.IsBank,0) AS isbank,
			b.IsDiary,
			ISNULL(b.IsOther,0) AS isother,
			--b.TypeId,
			ISNULL(b.Cid,-1) AS mcid,
			b.mainitems AS mainitemsid,--主表项目id
			b.additionitems AS additionitemsid, --附表项目id
			d.fullname AS mainitemsname,--主表项目名称
			e.fullname AS additionitemsname,--附表项目名称
			dbo.F_GetAc_Assist_CheckItems_Str(a.BillNumberId,a.RowNo,'00001',1) AS assist,
			null AS asslist,
			a.FSettleNo AS balancenum,
			ISNULL(a.FSettleTypeID,0) AS balancetype,
			c.UserCode,
			c.FullName,
			CASE WHEN ISNULL(a.ATypeId,'') <> '' AND ISNULL(f.typeid,'') = '' THEN 0 
				 WHEN ISNULL(a.ATypeId,'') = '' THEN 1
				 ELSE 1 END AS islimit_ac
	FROM dbo.Ac_Voucher_Bill a
		LEFT JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND b.StypeId = @verifyid
		LEFT JOIN dbo.Ac_Currency c ON a.Cid = c.CId
		LEFT JOIN dbo.Ac_CashMoneyItems d ON b.MainItems = d.TypeId
		LEFT JOIN dbo.Ac_CashMoneyItems e ON b.AdditionItems = e.TypeId
		LEFT JOIN #TmpLimit f ON a.ATypeId = f.typeid
	WHERE BillNumberId = @VoucherId
	
	SELECT	DISTINCT a.nid,
			a.BillNumberId,
			--@billnumberid_test,
			a.vBId,
			a.typeName AS usercode,
			a.TypeId,
			CASE a.typeName
			WHEN '01' THEN (SELECT FullName FROM SType WHERE TypeId = a.TypeId)
			WHEN '02' THEN (SELECT FullName FROM Department WHERE TypeId = a.TypeId)
			WHEN '03' THEN (SELECT FullName FROM employee WHERE TypeId = a.TypeId)
			WHEN '04' THEN (SELECT FullName FROM BType WHERE TypeId = a.TypeId)
			WHEN '05' THEN (SELECT FullName FROM dbo.Te_BankAccount WHERE Id = CAST(TypeId AS INT) )
			END AS fullname,
			CASE a.typeName
			WHEN '01' THEN 'sfullname'
			WHEN '02' THEN 'dfullname'
			WHEN '03' THEN 'efullname'
			WHEN '04' THEN 'bfullname'
			WHEN '05' THEN 'tbfullname'
			END AS displayfield,
			CASE a.typeName
			WHEN '01' THEN 'stypeid'
			WHEN '02' THEN 'dtypeid'
			WHEN '03' THEN 'etypeid'
			WHEN '04' THEN 'btypeid'
			WHEN '05' THEN 'tbtypeid'
			END AS datafield,
			b.AscIds AS value
	FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a
	INNER JOIN dbo.Ac_Assist_CheckItems b ON a.typeName = b.UserCode
	WHERE a.BillNumberId = @VoucherId
	
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId
	
	--清除对照表
	DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_CommissionBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_ReceiptBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_Provision_Voucher WHERE VoucherId = @VoucherId	
	DELETE FROM dbo.Ac_CouponBill_VoucherBill WHERE VourchBillId = @VoucherId	
	DELETE FROM dbo.Ac_DeliveryBill_VoucherBill WHERE VourchBillId = @VoucherId	
END


DROP TABLE #TmpLimit

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.1.5
	描述：调用GP_HandCreate_Voucher生成凭证，将select结果放到此处，以便GP_HandCreate_Voucher可方便用于批量生成
*/
CREATE PROCEDURE GP_Call_Voucher_Generate_BatchCreate
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@AtId			INT = 0,				-- 凭证模版ID
	@specifyDate	DATE = '',				-- 手工指定凭证日期
	@Type			INT = 0	,				-- 结果类型 0.返回错误提示 1.返回错误凭证修改 2.凭证标错，并返回提示
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@InOutStypeId	VARCHAR(50)='',			-- 调拨单 调入/调出分支
	@IfCommission	INT = 0,				-- 单据类别：0：一般单据；1：提成单；2：暂估发票
	@checkdeficit		INT	= 0					--是否检查赤字 0不检查，1检查提示，2检查不能保存
)
--@encode$--
AS
SET NOCOUNT ON

--分支机构
DECLARE @STypeid VARCHAR(50)
		,@deficitvoucher INT

--会计科目多级权限表
CREATE TABLE #TmpLimit
(
	typeid	VARCHAR(50),
	stypeid	VARCHAR(50)
)

--非总账模式直接返回
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1)
	RETURN 0

DECLARE @return INT,@verifyid VARCHAR(50),@VoucherId INT,@ErrorMsg VARCHAR(1000),@attachMsg INT,@BillType INT,@szPID VARCHAR(MAX)

SELECT TOP 1 @BillType = BillType FROM dbo.BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))

IF @IfCommission = 0
	SELECT TOP 1 @BillType = BillType FROM dbo.BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
ELSE IF @IfCommission = 1
	SELECT TOP 1 @BillType = BillType FROM dbo.CommissionBillNew WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
ELSE IF @IfCommission = 2
	SELECT TOP 1 @BillType = BillType FROM dbo.ReceiptBillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@BillNumberId,','))
		
SET @attachMsg = 0

IF @atid = -1
BEGIN
	IF @IfCommission = 0
		SELECT @atid = atid FROM dbo.BillIndex WHERE BillNumberId IN (SELECT TOP 1 a FROM dbo.f_split(@BillNumberId,','))
	ELSE IF @IfCommission = 1
		SELECT @atid = atid FROM dbo.CommissionBillNew WHERE BillNumberId IN (SELECT TOP 1 a FROM dbo.f_split(@BillNumberId,','))
	ELSE IF @IfCommission = 2
		SELECT @atid = atid FROM dbo.ReceiptBillIndex WHERE BillNumberId IN (SELECT TOP 1 a FROM dbo.f_split(@BillNumberId,','))
END

--是否中断
DECLARE @justRep INT
SET @justRep = 0
IF @Type IN(0,2)
	SET @justRep = 1

DECLARE @InOutType INT--调拨单专用
SET @InOutType = 0
IF @BillType = 310
BEGIN
	SELECT a 
	INTO #TmpA
	FROM dbo.f_split(@BillNumberId,',')

	IF EXISTS(SELECT a FROM #TmpA WHERE a NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = -1) )
		SET @InOutType = -1
	ELSE IF EXISTS(SELECT a FROM #TmpA WHERE a NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = 1))
		SET @InOutType = 1
	ELSE 
		SET @InOutType = 0
END

EXEC @return = 
	dbo.GP_HandCreate_Voucher   @BillNumberId,
								@szCheckMan,
								@AtId,
								@specifyDate,
								@verifyid OUTPUT,
								@VoucherId OUTPUT,
								@Type,
								@justRep,
								@szPID OUTPUT,
								@CreateType,
								@InOutStypeId,
								@IfCommission,
								@checkdeficit,
								@deficitvoucher OUTPUT

IF @return =  -1 SET @ErrorMsg = '存在凭证明细科目获取失败'
ELSE IF @return =  -2 SET @ErrorMsg = '生成的凭证借贷不平衡'
ELSE IF @return = -3  SET @ErrorMsg = '存在项目未设置对应科目'
ELSE IF @return = -4  SET @ErrorMsg = '辅助核算获取异常'
ELSE IF @return = -5  SET @ErrorMsg = '凭证模板中有会计科目外币核算与单据币种不符'
ELSE IF @return = -6  SET @ErrorMsg = '凭证模板中，科目来源为非手工选择的明细未设置辅助核算'
ELSE IF @return = -7  SET @ErrorMsg = '生成的凭证中辅助核算存在空值'
ELSE IF @return = -8  SET @ErrorMsg = '存在凭证明细辅助核算与对应科目辅助核算不匹配'
ELSE IF @return = -9  SET @ErrorMsg = '配置要求填写现金流量'
ELSE IF @return = -10 SET @ErrorMsg = '生成凭证中有会计科目被停用'
ELSE IF @return = -11 SET @ErrorMsg = '单据往来科目不存在'
ELSE IF @return = -12 SET @ErrorMsg = '单据生成凭证所有金额为0，无法生成或不需生成会计凭证'
ELSE IF @return = -14 SET @ErrorMsg = @szPID

IF @return = 0--生成成功
BEGIN
	IF @Type IN (0,2)
		INSERT INTO ac_BatchCreateVoucher_result(billcode,txt,flag)
		SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) AS txt,1 AS flag
		FROM dbo.BillIndex T1
			INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
		WHERE T3.BillNumberId = @VoucherId
	ELSE
		SELECT NULL
END
ELSE
BEGIN
	DECLARE @iscost INT
	IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1)
		SET @iscost = 0
	ELSE
		SET @iscost = 2
	
	IF @Type IN (0,2)
	BEGIN
		IF @return IN(-14)
		BEGIN					
			INSERT INTO ac_BatchCreateVoucher_result(billcode,txt,flag,voucherid,deficitvoucher,returnvalue)
			SELECT TOP 1 T1.BillCode,t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +'。注：'+ @szPID AS txt,1 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.BillIndex T1
			INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
			INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
		ELSE IF @Type = 0 OR @return IN(-13,-12)
		BEGIN			
			INSERT INTO ac_BatchCreateVoucher_result(billcode,txt,flag,voucherid,deficitvoucher,returnvalue)
			SELECT TOP 1 T1.BillCode,@szPID AS txt,-2 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.BillIndex T1
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END
		ELSE IF @Type = 2
		BEGIN					
			INSERT INTO ac_BatchCreateVoucher_result(billcode,txt,flag,voucherid,deficitvoucher,returnvalue)	
			SELECT TOP 1 T1.BillCode,'已保存标错凭证['+t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100)) +']'+@szPID AS txt, -1 AS flag 
					,@VoucherId AS voucherid
					,@deficitvoucher AS deficitvoucher
					,@return AS returnvalue
			FROM dbo.BillIndex T1
			INNER JOIN dbo.Ac_GoodsBill_VoucherBill T2 ON T1.BillNumberId = T2.GoodsBillId
				INNER JOIN dbo.Ac_Voucher T3 ON T2.VourchBillId = T3.BillNumberId
				INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T1.BillNumberId IN (SELECT a FROM dbo.f_split(@BillNumberId,','))
		END	
	END
	ELSE IF @Type = 1
	BEGIN

		IF @return IN(-12)
		BEGIN
			SELECT @ErrorMsg = '-1'
			RAISERROR(@ErrorMsg,16,1)
			RETURN -1
		END
		
		IF @return = -13
		BEGIN
			DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
			DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
			DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId
			DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE VourchBillId = @VoucherId
			--RAISERROR('-13',16,1)  --单据已经生成过凭证，无法再次生成！
			RETURN -13
		END
		
		declare @billnumberid_test	numeric(18,0)
		
		
		INSERT INTO Ac_Voucher_Temp
			(
				BillDate
				,VgId
				,STypeId
				,FlowNo
				,SBillType
				,FComment
				,InOutType
			)
		SELECT	BillDate,
			VgId,
			STypeId,
			FlowNo,
			@BillType AS SBillType,
			FComment,
			@InOutType AS InOutType
		FROM dbo.Ac_Voucher	
		WHERE BillNumberId = @VoucherId
		
		select @billnumberid_test = MAX(BillNumberId) from Ac_Voucher_Temp
		
		--declare @STypeid VARCHAR(50)
		
		SELECT @STypeid = stypeid FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
		
		IF @szCheckMan <> '00001'
			INSERT INTO #TmpLimit
					( typeid, stypeid )
			SELECT Typeid,Stypeid
			FROM dbo.F_LineAccount(@szCheckMan,@stypeid)
		ELSE
			INSERT INTO #TmpLimit
					( typeid, stypeid )
			SELECT TypeId,StypeId
			FROM dbo.Ac_Account
			WHERE StypeId = @stypeid
		
		INSERT INTO Ac_Voucher_Bill_Temp
				(
					BillNumberId
					,explain
					,UserCode
					,FullName
					,typeid
					,sysrow
					,cid
					,moneytype
					,BasisType
					,rate
					,balanceprice
					,lendprice
					,loanprice
					,FSettleNo
					,FSettleTypeID
					,Comment
					,STypeId
					,fdc
					,FAdc
					,FAcnt
					,FCashFlowItem
					,RowNo
					,id
					,MainItems
					,AdditionItems
					,KeyId
					,iscash
					,isbank
					,IsDiary
					,isother
					,mcid
					,mainitemsid
					,additionitemsid
					,mainitemsname
					,additionitemsname
					,assist
					,asslist
					,balancenum
					,balancetype
					,cUserCode
					,cFullName
					,islimit_ac
				)
		SELECT	@billnumberid_test
				,a.Summary AS explain,
				b.UserCode,
				b.FullName,
				a.ATypeId AS typeid,
				ISNULL(c.Sysrow,1) AS sysrow,
				ISNULL(a.cid,1) AS cid,
				ISNULL(a.cid,1) AS moneytype,
				ISNULL(c.BasisType,0) AS BasisType,
				ISNULL(a.Rate,1) AS rate,
				CASE a.FAdc
					 WHEN 1		THEN ISNULL(a.FDebitTotalFor,0)
					 WHEN -1	THEN ISNULL(a.FCreditTotalFor,0)
				END AS balanceprice,
				CASE WHEN a.FDebitTotal = 0 THEN NULL ELSE FDebitTotal END AS lendprice,
				CASE WHEN a.FCreditTotal = 0 THEN NULL ELSE FCreditTotal END AS loanprice,
				a.FSettleNo,
				a.FSettleTypeID,
				a.Comment,
				a.STypeId,
				ISNULL(a.Fdc,a.fadc) AS fdc,
				a.FAdc,
				b.FAcnt,
				a.FCashFlowItem,
				a.RowNo,
				a.id,
				b.MainItems,
				b.AdditionItems,
				b.KeyId,
				ISNULL(b.IsCash,0) AS iscash,
				ISNULL(b.IsBank,0) AS isbank,
				b.IsDiary,
				ISNULL(b.IsOther,0) AS isother,
				--b.TypeId,
				ISNULL(b.Cid,-1) AS mcid,
				b.mainitems AS mainitemsid,--主表项目id
				b.additionitems AS additionitemsid, --附表项目id
				d.fullname AS mainitemsname,--主表项目名称
				e.fullname AS additionitemsname,--附表项目名称
				dbo.F_GetAc_Assist_CheckItems_Str(a.BillNumberId,a.RowNo,'00001') AS assist,
				null AS asslist,
				a.FSettleNo AS balancenum,
				ISNULL(a.FSettleTypeID,0) AS balancetype,
				c.UserCode,
				c.FullName,
				CASE WHEN ISNULL(a.ATypeId,'') <> '' AND ISNULL(f.typeid,'') = '' THEN 0 
					 WHEN ISNULL(a.ATypeId,'') = '' THEN 1
					 ELSE 1 END AS islimit_ac
		FROM dbo.Ac_Voucher_Bill a
			LEFT JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND b.StypeId = @verifyid
			LEFT JOIN dbo.Ac_Currency c ON a.Cid = c.CId
			LEFT JOIN dbo.Ac_CashMoneyItems d ON b.MainItems = d.TypeId
			LEFT JOIN dbo.Ac_CashMoneyItems e ON b.AdditionItems = e.TypeId
			LEFT JOIN #TmpLimit f ON a.ATypeId = f.typeid
		WHERE BillNumberId = @VoucherId
		
		
		INSERT INTO Ac_Voucher_Bill_Assist_CheckItems_Temp
			(
				nid
				,billnumberid
				,vbid
				,usercode
				,typeid
				,fullname
				,displayfield
				,datafield
				,value
			)
		SELECT	DISTINCT a.nid,
				--a.BillNumberId,
				@billnumberid_test,
				a.vBId,
				a.typeName AS usercode,
				a.TypeId,
				CASE a.typeName
				WHEN '01' THEN (SELECT FullName FROM SType WHERE TypeId = a.TypeId)
				WHEN '02' THEN (SELECT FullName FROM Department WHERE TypeId = a.TypeId)
				WHEN '03' THEN (SELECT FullName FROM employee WHERE TypeId = a.TypeId)
				WHEN '04' THEN (SELECT FullName FROM BType WHERE TypeId = a.TypeId)
				WHEN '05' THEN (SELECT FullName FROM dbo.Te_BankAccount WHERE Id = CAST(TypeId AS INT) )
				END AS fullname,
				CASE a.typeName
				WHEN '01' THEN 'sfullname'
				WHEN '02' THEN 'dfullname'
				WHEN '03' THEN 'efullname'
				WHEN '04' THEN 'bfullname'
				WHEN '05' THEN 'tbfullname'
				END AS displayfield,
				CASE a.typeName
				WHEN '01' THEN 'stypeid'
				WHEN '02' THEN 'dtypeid'
				WHEN '03' THEN 'etypeid'
				WHEN '04' THEN 'btypeid'
				WHEN '05' THEN 'tbtypeid'
				END AS datafield,
				b.AscIds AS value
		FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a
		INNER JOIN dbo.Ac_Assist_CheckItems b ON a.typeName = b.UserCode
		WHERE a.BillNumberId = @VoucherId
		
		--ROLLBACK TRAN Insert_Proc
		DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
		DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
		DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId
		
		INSERT INTO Ac_Voucher_Generate_Voucherbill_GoodsBills(STYPEID,BILLNUMBERID,billnumberids)
		SELECT @STypeid 
				,@billnumberid_test
				,@BillNumberId
		
	END
	
END


DROP TABLE #TmpLimit

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	功能说明：	各仓库成本均价一致的处理
				引用存储过程 Gp_ModifyDbf
	作    者：	卢    春
	最后修改：	2004-06-09
*/
CREATE          PROC Gp_CallAverageCostPrice
(
	@BillNumberID	int		-- 单据编号 ID 值
)
--@encode$--
AS
SET NOCOUNT ON

-- 检查是否采用各仓库成本均价一致，否则回滚
IF NOT EXISTS	(
					SELECT	TOP 1 1
					FROM	UserConfig
					WHERE	ConfigName = 'AverageCostPrice'
							AND Value = '1'
							AND IsAll = 't'
				)
	RETURN 0

-- 检查是否有出入库记录，否则回滚
IF NOT EXISTS	(
					SELECT	TOP 1 1
					FROM	InOutStockTable
					WHERE	BillnumberID = @BillnumberID
							AND KTypeID <> '10000'
				)
	RETURN 0

DECLARE	@PTypeID	varchar(50),	-- 商品 ID 值
		@BillType	int,			-- 单据类型
		@nRet		int				-- 返回结果

SET @nRet = 0


/*
-- 查询单据类型  57为成本调价单
SELECT	@BillType = BillType
FROM	BillIndex
WHERE	BillNumberID = @BillNumberID
		AND IfCheck = 't'
		AND RedWord = 0
		AND Draft = 0
If (@BillType = 57 AND (EXISTS(SELECT * FROM AdPriceBill WHERE BillNumberID = @BillNumberID AND ChangeAllStock = 1) ))  --调整全部仓库的成本价格
	BEGIN
		DECLARE AdjustAllStockCostPrice CURSOR FOR
			SELECT PTypeID FROM InOutStockTable WHERE BillNumberID = @BillNumberID

		OPEN AdjustAllStockCostPrice
		
		FETCH NEXT FROM AdjustAllStockCostPrice INTO @PTypeID
		WHILE @@FETCH_STATUS<>-1
			BEGIN
				IF @@FETCH_STATUS=-2 GOTO Error1
				EXEC @nRet=Gp_AverageAllCostPrice @PTypeID,@BillNumberID
				IF @nRet<>0 GOTO Error1
				FETCH NEXT FROM AdjustAllStockCostPrice INTO @PTypeID
			END
			
	END
ELSE
*/

-- 循环读取指定单据中，所有商品的信息
DECLARE GetInOutStockTableDetail CURSOR FOR 
	SELECT	PTypeID
	FROM	InOutStockTable
	WHERE	BillNumberID = @BillNumberID

OPEN GetInOutStockTableDetail
FETCH NEXT FROM GetInOutStockTableDetail INTO @PTypeID

WHILE @@FETCH_STATUS <> -1
BEGIN
	IF @@FETCH_STATUS = -2 GOTO ERROR
	-- 平均所有仓库的成本均价，算法处理
	EXEC @nRet = GP_AverageCostPrice @PTypeID

	IF @nRet <> 0 GOTO ERROR
	FETCH NEXT FROM GetInOutStockTableDetail INTO @PTypeID
END

ERROR:
	CLOSE GetInOutStockTableDetail
	DEALLOCATE GetInOutStockTableDetail

--Error1:
-- CLOSE AdjustAllStockCostPrice
-- DEALLOCATE AdjustAllStockCostPrice
RETURN @nRet


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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









-- ========================================================================
-- 功能说明：		订单取消报警
-- 最后修改作者：     cqhua
-- 最后修改时间：	2005-08-19
-- ========================================================================
CREATE             PROCEDURE [GP_CancelAlertSave]
(
@intBillNumberID int
)
--@encode$--
AS
SET NOCOUNT ON


--select * from orderindex 

Update OrderIndex Set DelayType='0',DelayValue='0'  WHERE BillnumberID=@intBillNumberID
Update Orderindex Set CanAlert='0' WHERE BillnumberID=@intBillNumberID


RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
	作废优惠券兑换商品方案
*/
CREATE PROCEDURE Gp_CancelCoupon
(
	@billnumberid			INT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	
	@Error	INT=0
--此方案有没被使用 待添加

--没有作废的才更新 已作废的不处理
UPDATE CouponExchangePtypeIndex SET IsVaild=1 where billnumberid=@billnumberid and IsVaild=0
SET @Error+=@@ERROR


RETURN @Error

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_CanceledAcVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_CanceledAcVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查询作废
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_CanceledAcVoucherBill
(
	@BillNumberId	VARCHAR(50)=''			-- 单据ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@fchecked		VARCHAR(2)='',
	@recheckid		VARCHAR(2)='',
	@ifcheck		VARCHAR(2)='',
	@ErrorCount		INT=0--审核 复核 过账 凭证类型
	
SELECT 
	@fchecked=ISNULL(FChecked,''),
	@recheckid=ISNULL(ReCheckId,''),
	@ifcheck=ISNULL(IfCheck,'')
FROM Ac_Voucher
WHERE BillNumberId=@BillNumberId
		 
IF @@ROWCOUNT = 0--判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN
END

IF(@fchecked='1' OR @recheckid <>'' OR @ifcheck='t')
	BEGIN
		RAISERROR('您选择的凭证已经审核/复核/记账！请确认后重试！',16,1)
		RETURN
	END
	
--DELETE Ac_Voucher_Bill_CashMoneyItems WHERE BillNumberId=@BillNumberId--删除流量表

UPDATE Ac_Voucher SET FChecked=-1 WHERE BillNumberId=@BillNumberID--作废 凭证主表

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='作废凭证单据错误，请确认！'
		RAISERROR(@MSG2,16,1)
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.06.03
	描述：资金调拨单过账、入账生成日记账
*/
CREATE PROCEDURE Gp_CapitalTransferBillToJournal
(
	@BillNumberId	INT,					-- 单据编号
	@chvOpID		VARCHAR(50),			-- 操作员id
	@szPID			VARCHAR(1000) OUTPUT	-- 返回出错信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @BillType INT,
		@TransferType INT,
		@ETypeId	VARCHAR(50),
		@Comment	VARCHAR(500),
		@FeeDeductType	INT,--扣手续费账户 1.调出
		@IfConfirm		INT-- 过账、入账标识 0.过账 1.入账

DECLARE @Did	INT --生成的日记账ID

SELECT @BillType = BillType,@TransferType = TransferType,@ETypeId = etypeid,@Comment = comment,@IfConfirm = IfConfirm,@FeeDeductType = FeeDeductType
FROM dbo.BillIndex 
WHERE BillNumberId = @BillNumberId

IF @BillType <> 310
BEGIN
	SET @szPID = '单据非资金调拨单，无法处理相应业务'
	RETURN -229
END

BEGIN TRAN
	--账户转账
	IF @TransferType = 2
	BEGIN
		--过账
		IF @IfConfirm = 0
		BEGIN
			INSERT INTO dbo.Te_Journal_Detail
					( BusinessDate ,
					  SourceId ,
					  VoucherId ,
					  GoodsBillNumberId,
					  ETypeId ,
					  Summary ,
					  FDebit ,
					  FCredit ,
					  FEndBalance ,
					  AccountId ,
					  IsCash ,
					  FDC ,
					  STypeId ,
					  ATypeId ,
					  FSettleId ,
					  FSettleNo ,
					  Cid ,
					  Rate
					)
			SELECT  CONVERT(varchar(100), GETDATE(), 23),
					3,
					0,
					@BillNumberId,
					@chvOpID,
					@Comment,
					0,
					TransferPrice,
					0,
					T4.Id,
					0,
					T3.Fdc,
					T2.Stypeid,
					T4.ATypeId,
					0,
					'',
					T2.CID,
					T2.Rate
			FROM dbo.CapitalTransfer_Bill T1
					INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
					INNER JOIN dbo.Te_BankAccount T4 ON T1.BankAccountOut = T4.id
					INNER JOIN dbo.Ac_Account T3 ON T4.ATypeId = T3.TypeId AND T2.Stypeid = T3.StypeId
			WHERE T1.BillNumberId = @BillNumberId
			
			SET @Did = @@IDENTITY
			EXEC dbo.GP_TeDetailToBalance 2,@Did,1,@szPId OUTPUT
			
			IF @FeeDeductType = 1
			BEGIN
				INSERT INTO dbo.Te_Journal_Detail
					( BusinessDate ,
					  SourceId ,
					  VoucherId ,
					  GoodsBillNumberId,
					  ETypeId ,
					  Summary ,
					  FDebit ,
					  FCredit ,
					  FEndBalance ,
					  AccountId ,
					  IsCash ,
					  FDC ,
					  STypeId ,
					  ATypeId ,
					  FSettleId ,
					  FSettleNo ,
					  Cid ,
					  Rate
						)
				SELECT  CONVERT(varchar(100), GETDATE(), 23),
						3,
						0,
						@BillNumberId,
						@chvOpID,
						@Comment,
						0,
						DeductPrice,
						0,
						T4.Id,
						0,
						T3.Fdc,
						T2.Stypeid,
						T4.ATypeId,
						0,
						'',
						T2.CID,
						T2.Rate
				FROM dbo.CapitalTransfer_Bill T1
						INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
						INNER JOIN dbo.Te_BankAccount T4 ON T1.BankAccountOut = T4.Id
						INNER JOIN dbo.Ac_Account T3 ON T4.ATypeId = T3.TypeId AND T2.Stypeid = T3.StypeId
				WHERE T1.BillNumberId = @BillNumberId
				
				SET @Did = @@IDENTITY
				EXEC dbo.GP_TeDetailToBalance 2,@Did,1,@szPId OUTPUT
			END
		END
		ELSE --入账
		BEGIN
			INSERT INTO dbo.Te_Journal_Detail
					( BusinessDate ,
					  SourceId ,
					  VoucherId ,
					  GoodsBillNumberId,
					  ETypeId ,
					  Summary ,
					  FDebit ,
					  FCredit ,
					  FEndBalance ,
					  AccountId ,
					  IsCash ,
					  FDC ,
					  STypeId ,
					  ATypeId ,
					  FSettleId ,
					  FSettleNo ,
					  Cid ,
					  Rate
					)
			SELECT  CONVERT(varchar(100), GETDATE(), 23),
					3,
					0,
					@BillNumberId,
					@chvOpID,
					@Comment,
					TransferPrice,
					0,
					0,
					T4.Id,
					0,
					T3.Fdc,
					T2.Stypeid2,
					T4.ATypeId,
					0,
					'',
					T2.CID,
					T2.Rate
			FROM dbo.CapitalTransfer_Bill T1
					INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
					INNER JOIN dbo.Te_BankAccount T4 ON T1.BankAccountOut = T4.Id
					INNER JOIN dbo.Ac_Account T3 ON T4.ATypeId = T3.TypeId AND T2.Stypeid = T3.StypeId
			WHERE T1.BillNumberId = @BillNumberId
			
			SET @Did = @@IDENTITY
			EXEC dbo.GP_TeDetailToBalance 2,@Did,1,@szPId OUTPUT
			
			IF @FeeDeductType = 2
			BEGIN
				INSERT INTO dbo.Te_Journal_Detail
					( BusinessDate ,
					  SourceId ,
					  VoucherId ,
					  GoodsBillNumberId,
					  ETypeId ,
					  Summary ,
					  FDebit ,
					  FCredit ,
					  FEndBalance ,
					  AccountId ,
					  IsCash ,
					  FDC ,
					  STypeId ,
					  ATypeId ,
					  FSettleId ,
					  FSettleNo ,
					  Cid ,
					  Rate
						)
				SELECT  CONVERT(varchar(100), GETDATE(), 23),
						3,
						0,
						@BillNumberId,
						@chvOpID,
						@Comment,
						0,
						DeductPrice,
						0,
						T4.Id,
						0,
						T3.Fdc,
						T2.Stypeid,
						T4.ATypeId,
						0,
						'',
						T2.CID,
						T2.Rate
				FROM dbo.CapitalTransfer_Bill T1
						INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
						INNER JOIN dbo.Te_BankAccount T4 ON T1.BankAccountOut = T4.Id
						INNER JOIN dbo.Ac_Account T3 ON T4.ATypeId = T3.TypeId AND T2.Stypeid = T3.StypeId
				WHERE T1.BillNumberId = @BillNumberId
				
				SET @Did = @@IDENTITY
				EXEC dbo.GP_TeDetailToBalance 2,@Did,1,@szPId OUTPUT
			END
		END
	END
	ELSE --现金
		--过账
		IF @IfConfirm = 0
		BEGIN
			INSERT INTO dbo.Te_Journal_Detail
					( BusinessDate ,
					  SourceId ,
					  VoucherId ,
					  GoodsBillNumberId,
					  ETypeId ,
					  Summary ,
					  FDebit ,
					  FCredit ,
					  FEndBalance ,
					  AccountId ,
					  IsCash ,
					  FDC ,
					  STypeId ,
					  ATypeId ,
					  FSettleId ,
					  FSettleNo ,
					  Cid ,
					  Rate
					)
			SELECT  CONVERT(varchar(100), GETDATE(), 23),
					3,
					0,
					@BillNumberId,
					@chvOpID,
					@Comment,
					0,
					TransferPrice,
					0,
					0,
					1,
					T3.Fdc,
					T2.Stypeid,
					T1.BankAccountOut,
					0,
					'',
					T2.CID,
					T2.Rate
			FROM dbo.CapitalTransfer_Bill T1
				INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
				INNER JOIN dbo.Ac_Account T3 ON T1.BankAccountOut = T3.TypeId AND T2.Stypeid = T3.StypeId
			WHERE T1.BillNumberId = @BillNumberId
			
			SET @Did = @@IDENTITY
			EXEC dbo.GP_TeDetailToBalance 1,@Did,1,@szPId OUTPUT
			
			IF @FeeDeductType = 1
			BEGIN
				INSERT INTO dbo.Te_Journal_Detail
						( BusinessDate ,
						  SourceId ,
						  VoucherId ,
						  GoodsBillNumberId,
						  ETypeId ,
						  Summary ,
						  FDebit ,
						  FCredit ,
						  FEndBalance ,
						  AccountId ,
						  IsCash ,
						  FDC ,
						  STypeId ,
						  ATypeId ,
						  FSettleId ,
						  FSettleNo ,
						  Cid ,
						  Rate
						)
				SELECT  CONVERT(varchar(100), GETDATE(), 23),
						3,
						0,
						@BillNumberId,
						@chvOpID,
						@Comment,
						0,
						DeductPrice,
						0,
						0,
						1,
						T3.Fdc,
						T2.Stypeid,
						T1.BankAccountOut,
						0,
						'',
						T2.CID,
						T2.Rate
				FROM dbo.CapitalTransfer_Bill T1
					INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
					INNER JOIN dbo.Ac_Account T3 ON T1.BankAccountOut = T3.TypeId AND T2.Stypeid = T3.StypeId
				WHERE T1.BillNumberId = @BillNumberId
				
				SET @Did = @@IDENTITY
				EXEC dbo.GP_TeDetailToBalance 1,@Did,1,@szPId OUTPUT
			END
		END
		ELSE --入账
		BEGIN
			INSERT INTO dbo.Te_Journal_Detail
					( BusinessDate ,
					  SourceId ,
					  VoucherId ,
					  GoodsBillNumberId,
					  ETypeId ,
					  Summary ,
					  FDebit ,
					  FCredit ,
					  FEndBalance ,
					  AccountId ,
					  IsCash ,
					  FDC ,
					  STypeId ,
					  ATypeId ,
					  FSettleId ,
					  FSettleNo ,
					  Cid ,
					  Rate
					)
			SELECT  CONVERT(varchar(100), GETDATE(), 23),
					3,
					0,
					@BillNumberId,
					@chvOpID,
					@Comment,
					TransferPrice,
					0,
					0,
					0,
					1,
					T3.Fdc,
					T2.Stypeid2,
					T1.BankAccountIn,
					0,
					'',
					T2.CID,
					T2.Rate
			FROM dbo.CapitalTransfer_Bill T1
				INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
				INNER JOIN dbo.Ac_Account T3 ON T1.BankAccountIn = T3.TypeId AND T2.Stypeid2 = T3.StypeId
			WHERE T1.BillNumberId = @BillNumberId
			
			SET @Did = @@IDENTITY
			EXEC dbo.GP_TeDetailToBalance 1,@Did,1,@szPId OUTPUT
			
			IF @FeeDeductType = 2
			BEGIN
				INSERT INTO dbo.Te_Journal_Detail
						( BusinessDate ,
						  SourceId ,
						  VoucherId ,
						  GoodsBillNumberId,
						  ETypeId ,
						  Summary ,
						  FDebit ,
						  FCredit ,
						  FEndBalance ,
						  AccountId ,
						  IsCash ,
						  FDC ,
						  STypeId ,
						  ATypeId ,
						  FSettleId ,
						  FSettleNo ,
						  Cid ,
						  Rate
						)
				SELECT  CONVERT(varchar(100), GETDATE(), 23),
						3,
						0,
						@BillNumberId,
						@chvOpID,
						@Comment,
						0,
						DeductPrice,
						0,
						0,
						1,
						T3.Fdc,
						T2.Stypeid,
						T1.BankAccountOut,
						0,
						'',
						T2.CID,
						T2.Rate
				FROM dbo.CapitalTransfer_Bill T1
					INNER JOIN dbo.BillIndex T2 ON T1.BillNumberId = T2.BillNumberId
					INNER JOIN dbo.Ac_Account T3 ON T1.BankAccountOut = T3.TypeId AND T2.Stypeid = T3.StypeId
				WHERE T1.BillNumberId = @BillNumberId
				
				SET @Did = @@IDENTITY
				EXEC dbo.GP_TeDetailToBalance 1,@Did,1,@szPId OUTPUT
			END
		END

IF @@ERROR <> 0
	ROLLBACK TRAN

COMMIT TRAN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================    
-- 功能说明： 添加、更新或者删除货位  
-- 作者：  冯娅    
-- 最后修改时间： 2012-04-16   
-- ======================================================================== 

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_CargoTypeEdit]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    BEGIN
        DROP PROCEDURE Gp_CargoTypeEdit
    END

GO
	
CREATE PROCEDURE Gp_CargoTypeEdit
    (
      @CargoID INT ,
      @UserCode NVARCHAR(200) ,
      @FullName NVARCHAR(200) ,
      @KtypeID NVARCHAR(50) ,
      @Comment VARCHAR(500) ,
      @isDefault INT = 0 ,
      @Pathno    int=0,
	--@XWMaxNumber NUMERIC(18,0),
      @ControlType VARCHAR(20)  ---操作类型：ADD-添加、UPDATE-修改、DEL-删除
    )
--@encode$--	
AS 
    SET NOCOUNT ON

--验证仓库的有效性
    IF @ControlType IN ( 'ADD', 'UPDATE' ) 
        BEGIN
            IF NOT EXISTS ( SELECT  *
                            FROM    STOCK
                            WHERE   typeId = @KtypeID ) 
                BEGIN
                    RAISERROR('仓库无效,请重新选择！',16,1)
                    RETURN
                END
        END
     
    IF @ControlType = 'ADD' 
        BEGIN	
			
			IF  EXISTS ( SELECT  *FROM  PosInfo WHERE   KtypeId = @KtypeID ) 
			 BEGIN
					RAISERROR('仓库已关联POS,不允许新增货位！',16,1)
					RETURN
			END
			
			DECLARE @cargoidtmp INT		
            INSERT  INTO CargoType
                    ( UserCode ,
                      FullName ,
                      KtypeID ,
                      Comment ,
                      deleted ,
                      isDefault,
                      pathno
                    )
            VALUES  ( @UserCode ,
                      @FullName ,
                      @KtypeID ,
                      @Comment ,
                      0 ,
                      @isDefault,
                      isnull(@pathno,0)
                    )
            SELECT @cargoidtmp=SCOPE_IDENTITY();
            UPDATE  cargotype
            SET     XiWaMaxNumber = ( SELECT    ISNULL(MAX(XiWaMaxNumber), 0)
                                                + 1
                                      FROM      cargotype
                                    )
            WHERE   CargoID = @cargoidtmp
        END
    ELSE 
        IF @ControlType = 'UPDATE' 
            BEGIN
				IF  EXISTS ( SELECT  *FROM  PosInfo WHERE   KtypeId = @KtypeID ) 
				AND EXISTS(SELECT *FROM CargoType WHERE CargoID = @CargoID AND isDefault<>1)
				 BEGIN
						RAISERROR('仓库已关联POS,不允许新增货位！',16,1)
						RETURN
				END
				
				--商品档案已关联默认货位
				IF EXISTS(SELECT * FROM DefaultStock S INNER JOIN CargoType C ON C.CargoID=@CargoID AND C.CargoID=S.CargoId AND S.ktypeid<>@KtypeID)
				 BEGIN
					RAISERROR('所属仓库已关联商品档案默认仓库,不允许修改货位所属仓库！',16,1)
					RETURN
				END
				
                IF NOT EXISTS ( SELECT  *
                                FROM    CargoType
                                WHERE   CargoID = @CargoID ) 
                    BEGIN
                        RAISERROR('该信息已经删除！',16,1)
                        RETURN
                    END
                UPDATE  CargoType
                SET     UserCode = @UserCode ,
                        FullName = @FullName ,
                        KtypeID = @KtypeID ,
                        Comment = @Comment,
                        Pathno=isnull(@pathno,0)
                WHERE   CargoID = @CargoID
            END 
        ELSE 
            IF @ControlType = 'DELETE' 
                BEGIN
                    DELETE  CargoType
                    WHERE   @CargoID = CargoID
                END	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.08.29
	描述：结转损益
*/
CREATE PROCEDURE GP_CarryLossProfit
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@stypeid			VARCHAR(50),		-- 分支机构
	@billdate			DATETIME,			-- 凭证日期
	@vgid				INT,				-- 凭证字
	@summary			VARCHAR(400),		-- 凭证摘要
	@ascids				INT,				-- 辅助核算类别
	@checkdate			INT=1,				-- 0.按分支机构期间来 1.按指定日期来
	@CarryType			INT,				--0:原逻辑；1:借贷分开生成2张凭证
	@CompleteVoucherBillnumberIds VARCHAR(1000) OUT --结转生成的完整无误的凭证id
)
--@encode$--
AS
SET NOCOUNT ON


--异常消息
DECLARE @msg VARCHAR(1000),@sfullname VARCHAR(66)
SET @msg = ''
SELECT @sfullname = fullname FROM dbo.SType WHERE TypeId = @stypeid


--判断是否为独立分支
IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId = @stypeid AND IsSelfVerify = 0)
BEGIN
	SET @msg = '分支机构['+@sfullname+']为非独立核算分支机构，请勿选择！'
	RAISERROR(@msg,16,1)
	RETURN -1
END

--未开账
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE StypeId = @stypeid AND IsUse = 1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '未开账，操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

IF @checkdate = 0
	SELECT @billdate = T1.FEnd FROM dbo.Ac_Period T1 INNER JOIN dbo.Ac_AccountsPeroid_Stype T2 ON T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod
	WHERE T2.Stypeid = @stypeid

--取当前会计期间
DECLARE @fyear INT,@fperiod INT
SELECT @fyear = FYear,@fperiod = FPeriod FROM dbo.Ac_Period WHERE FBegin <= @billdate AND FEnd >= @billdate

--取本位币
DECLARE @syscid INT
SELECT @syscid = cid FROM dbo.Ac_Currency WHERE Sysrow = 1

--取分支机构对应的本年利润科目、利润分配科目以及相应的核算币别与借贷方向
DECLARE @lirunTypeid VARCHAR(50),@lirunTypeidFen VARCHAR(50),
		@cid INT,@cidFen INT,
		@FDC INT,@FDCFen INT
SET @lirunTypeid = ''
SET @lirunTypeidFen = ''

SELECT @lirunTypeid = a.TypeID,@cid =a.cid,@FDC = a.Fdc
FROM dbo.Ac_Account a 
INNER JOIN dbo.SType b ON (a.TypeId = b.ATypeID AND a.StypeId = b.TypeId)
WHERE b.TypeId = @stypeid

SELECT @lirunTypeidFen = a.TypeID,@cidFen =a.cid,@FDCFen = a.Fdc
FROM dbo.Ac_Account a 
INNER JOIN dbo.SType b ON (a.TypeId = b.ATypeID2 AND a.StypeId = b.TypeId)
WHERE b.TypeId = @stypeid

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



--分支相应科目未设置
IF @lirunTypeid = ''
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '未设置本年利润科目，结转操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

IF @lirunTypeidFen = ''
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '未设置利润分配科目，结转操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

--存在未过账并且未作废的凭证
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE STypeId = @stypeid AND IfCheck='F' AND FChecked <> -1 AND FYear = @fyear AND FPeriod = @fperiod)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '本期凭证未全部记账，结转操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

--------------------------------------------------------------------------------------
DECLARE @INIFYEAR INT,@INIFPERIOD INT
--IF @fperiod = 1
--BEGIN
--	SET @INIFYEAR = @fyear -1
--	SET @INIFPERIOD = 12
--END
--ELSE
--BEGIN
	SET @INIFYEAR = @fyear
	SET @INIFPERIOD = @fperiod
--END 
--------取期初------
SELECT DISTINCT a.ATypeId,a.cid,ISNULL(d.ascids,'') AS ascids,
				CASE WHEN b.fdc = 1 THEN
						CASE WHEN b.FAcnt <> 1 THEN a.iniTotal ELSE ISNULL(c.iniTotal,0) END 
					ELSE 0 END AS FDebit,
				CASE WHEN b.fdc = 1 THEN
						CASE WHEN b.FAcnt <> 1 THEN a.iniTotalFor ELSE ISNULL(c.iniTotalFor,0) END 
					ELSE 0 END AS FDebitFor,
				CASE WHEN b.fdc = -1 THEN
						CASE WHEN b.FAcnt <> 1 THEN a.iniTotal ELSE ISNULL(c.iniTotal,0) END 
					ELSE 0 END AS FCredit,
				CASE WHEN b.fdc = -1 THEN
						CASE WHEN b.FAcnt <> 1 THEN a.iniTotalFor ELSE ISNULL(c.iniTotalFor,0) END 
					ELSE 0 END AS FCreditFor,
				b.Fdc
INTO #tmpIni
FROM	Ac_IniAccount a
INNER JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND b.StypeId = @stypeid
LEFT JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail c ON c.STypeId = a.STypeId AND a.ATypeId = c.ATypeId AND a.Cid = c.Cid AND c.ATypeId LIKE '00003%'
LEFT JOIN 
(
SELECT STypeId,ATypeId,cid,dbo.F_Get_IniAccountAscids(ATypeId,groupid,cid,STypeId) ascids,GroupId 
FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail
WHERE STypeId = @stypeid
GROUP BY GroupId,STypeId,ATypeId,cid
)d ON a.stypeid = d.stypeid AND a.atypeid = d.atypeid AND a.cid = d.cid AND c.groupid = d.groupid
WHERE a.ATypeId LIKE '00003%' AND a.STypeId = @stypeid AND  A.FYear = @INIFYEAR 
--AND A.FPeriod = @INIFPERIOD  --只要是本年内，都要取期初数据，因为下面统计凭证明细的时候是统计的当前期间以前本年内的所有凭证明细

CREATE TABLE #tmpData
(
	atypeid VARCHAR(50),
	cid		INT,
	fdc		INT,
	ascids	VARCHAR(5000),
	item	VARCHAR(5000),
	fdebitfor	 NUMERIC(24, 10) ,
	fcreditfor	 NUMERIC(24, 10) ,
	fdebit		 NUMERIC(24, 10) ,
	fcredit		 NUMERIC(24, 10) 
)

--开账当年，要计算期初
--IF @fyear = @StartFyear
--------取期初和所有发生金额---
--BEGIN
	INSERT 	INTO #tmpData
	        ( atypeid ,
	          cid ,
	          fdc ,
	          ascids ,
	          item ,
	          fdebitfor ,
	          fcreditfor ,
	          fdebit ,
	          fcredit
	        )
	--VALUES  ( '' , -- atypeid - varchar(50)
	--          0 , -- cid - int
	--          0 , -- fdc - int
	--          '' , -- ascids - varchar(5000)
	--          '' , -- item - varchar(5000)
	--          NULL , -- fdebitfor - numeric
	--          NULL , -- fcreditfor - numeric
	--          NULL , -- fdebit - numeric
	--          NULL  -- fcredit - numeric
	--        )
	SELECT	T.atypeid,
			T.cid,
			T.Fadc AS fdc,
			T.ascids,
			T.item,
			SUM(T.fdebittotalfor) AS fdebitfor,
			SUM(T.fcredittotalfor)  AS fcreditfor,
			SUM(T.fdebittotal) AS fdebit,
			SUM(T.fcredittotal) AS fcredit
	FROM	
	(
		SELECT	a.atypeid,
				a.cid,
				CASE WHEN c.fdc = 1 THEN 
						SUM(a.fdebittotalfor) - SUM(a.fcredittotalfor)
					ELSE 0 END AS fdebittotalfor,
				CASE WHEN c.fdc = -1 THEN
						SUM(a.fcredittotalfor) - SUM(a.fdebittotalfor) 
					ELSE 0 END AS fcredittotalfor,
				CASE WHEN c.fdc = 1 THEN
						SUM(a.fdebittotal) - SUM(a.fcredittotal)
					ELSE 0 END AS fdebittotal,
				CASE WHEN c.fdc = -1 THEN
						SUM(a.fcredittotal) - SUM(a.fdebittotal)
					ELSE 0 END AS fcredittotal,
				dbo.f_Get_VoucherAscids(a.id,1) AS ascids,
				dbo.F_Get_VoucherAscids(a.id,2) AS item,
				c.fdc AS fadc
		FROM	dbo.Ac_Voucher_Bill a
		INNER JOIN dbo.Ac_Voucher b ON a.BillNumberId = b.BillNumberId
		INNER JOIN dbo.Ac_Account c ON (a.ATypeId = c.TypeId AND b.STypeId = c.StypeId)
		INNER JOIN dbo.Ac_Currency d ON a.Cid = d.CId
		WHERE	a.ATypeId LIKE '00003%' AND --损益类科目
				a.FYear = @Fyear AND a.FPeriod <= @Fperiod AND --到当前期间的所有发生额
				b.IfCheck='t' AND b.FChecked <> -1 AND b.STypeId = @stypeid --过账的凭证才用于统计
		GROUP BY a.atypeid,a.cid,dbo.f_Get_VoucherAscids(a.id,1),dbo.F_Get_VoucherAscids(a.id,2),a.Fdc,c.Fdc
		UNION ALL  
		SELECT ATypeId,cid,FDebitFor,FCreditFor,FDebit,FCredit,AscIds,dbo.F_Get_AccountAscids(ATypeId,@stypeid,Cid),CASE WHEN FDebit <> 0 THEN 1 ELSE -1 END AS fadc
		FROM 
		#tmpIni
		WHERE ATypeId like'00003%'
	)T
	GROUP BY t.ATypeId,T.cid,T.Fadc,T.ascids,T.item
--END
--ELSE
--BEGIN
--		INSERT 	INTO #tmpData
--	        ( atypeid ,
--	          cid ,
--	          fdc ,
--	          ascids ,
--	          item ,
--	          fdebitfor ,
--	          fcreditfor ,
--	          fdebit ,
--	          fcredit
--	        )
--		SELECT	T.atypeid,
--			T.cid,
--			T.Fadc AS fdc,
--			T.ascids,
--			T.item,
--			SUM(T.fdebittotalfor) AS fdebitfor,
--			SUM(T.fcredittotalfor)  AS fcreditfor,
--			SUM(T.fdebittotal) AS fdebit,
--			SUM(T.fcredittotal) AS fcredit
--	FROM	
--	(
--		SELECT	a.atypeid,
--				a.cid,
--				CASE WHEN c.fdc = 1 THEN 
--						SUM(a.fdebittotalfor) - SUM(a.fcredittotalfor)
--					ELSE 0 END AS fdebittotalfor,
--				CASE WHEN c.fdc = -1 THEN
--						SUM(a.fcredittotalfor) - SUM(a.fdebittotalfor) 
--					ELSE 0 END AS fcredittotalfor,
--				CASE WHEN c.fdc = 1 THEN
--						SUM(a.fdebittotal) - SUM(a.fcredittotal)
--					ELSE 0 END AS fdebittotal,
--				CASE WHEN c.fdc = -1 THEN
--						SUM(a.fcredittotal) - SUM(a.fdebittotal)
--					ELSE 0 END AS fcredittotal,
--				dbo.f_Get_VoucherAscids(a.id,1) AS ascids,
--				dbo.F_Get_VoucherAscids(a.id,2) AS item,
--				c.fdc AS fadc
--		FROM	dbo.Ac_Voucher_Bill a
--		INNER JOIN dbo.Ac_Voucher b ON a.BillNumberId = b.BillNumberId
--		INNER JOIN dbo.Ac_Account c ON (a.ATypeId = c.TypeId AND b.STypeId = c.StypeId)
--		INNER JOIN dbo.Ac_Currency d ON a.Cid = d.CId
--		WHERE	a.ATypeId LIKE '00003%' AND --损益类科目
--				a.FYear = @Fyear AND a.FPeriod <= @Fperiod AND --到当前期间的所有发生额
--				b.IfCheck = 't' AND b.FChecked <> -1 AND b.STypeId = @stypeid --过账的凭证才用于统计
--		GROUP BY a.atypeid,a.cid,dbo.f_Get_VoucherAscids(a.id,1),dbo.F_Get_VoucherAscids(a.id,2),a.Fdc,c.Fdc
--	)T
--	GROUP BY t.ATypeId,T.cid,T.Fadc,T.ascids,T.item
--END
-------------------------------------------------------------------------------------------


IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account WHERE TypeId = @lirunTypeidFen AND Deleted = 1 AND stypeid = @stypeid )
BEGIN
	RAISERROR('利润分配科目已被停用，结转损益中止',16,1)
	RETURN -1
END
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account WHERE TypeId = @lirunTypeid AND Deleted = 1 AND stypeid = @stypeid )
BEGIN
	RAISERROR('本年利润科目已被停用，结转损益中止',16,1)
	RETURN -1
END


-----------损益科目余额表---------
CREATE TABLE #tmpBalance
(
	id				INT		IDENTITY(1,1),
	fdc				INT,
	fdebit			 NUMERIC(24, 10) ,
	fdebitfor		 NUMERIC(24, 10) ,
	fcredit			 NUMERIC(24, 10) ,
	fcreditfor		 NUMERIC(24, 10) ,
	cid				INT,
	atypeid			VARCHAR(50),
	ascids			VARCHAR(1000),
	item			VARCHAR(500)
)

--调整到相反借贷方向后的数据，ps：根据配置，要么反向，要么不反向
CREATE TABLE #tmpBalance1
(
	id				INT		IDENTITY(1,1),
	fdc				INT,
	fdebit			 NUMERIC(24, 10) ,
	fdebitfor		 NUMERIC(24, 10) ,
	fcredit			 NUMERIC(24, 10) ,
	fcreditfor		 NUMERIC(24, 10) ,
	cid				INT,
	atypeid			VARCHAR(50),
	ascids			VARCHAR(1000),
	item			VARCHAR(500)
)

-- 算原币、本币余额(调整到相反借贷方向)
IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'carrylossonreversefdc' AND SubValue = '1')
BEGIN
	INSERT INTO #tmpBalance1
	SELECT	fdc,
			 fdebit ,
			fdebitfor ,
			Fcredit ,
			fcreditfor ,
			cid,
			ATypeId,
			AscIds,
			item
	FROM	#tmpData

END
ELSE
BEGIN
	INSERT INTO #tmpBalance1
	SELECT	fdc,
			CASE WHEN fdebit < 0 THEN 0 WHEN fcredit < 0  THEN ABS(fcredit) ELSE fdebit END,
			CASE WHEN fdebitfor < 0 THEN 0 WHEN fcreditfor < 0  THEN ABS(fcreditfor) ELSE fdebitfor END,
			CASE WHEN fcredit < 0 THEN 0 WHEN fdebit < 0 THEN ABS(fdebit) ELSE fcredit END,
			CASE WHEN fcreditfor < 0 THEN 0 WHEN fdebitfor < 0 THEN ABS(fdebitfor) ELSE fcreditfor END,
			cid,
			ATypeId,
			AscIds,
			item
	FROM	#tmpData
END

--去除全为0的记录
DELETE FROM #tmpBalance1 WHERE fcredit = 0 AND fdebit = 0 AND fcreditfor = 0 AND fdebitfor = 0

--检测科目是否停用
IF EXISTS(SELECT TOP 1 1 FROM #tmpBalance1 T1 INNER JOIN dbo.Ac_Account T2 ON T1.ATypeId = T2.TypeId AND T2.Deleted = 1 AND t2.StypeId = @stypeid)
BEGIN
	RAISERROR('存在已被停用的损益类科目，结转损益中止',16,1)
	RETURN -1
END


--有外币余额不平的情况，又未做期末调汇
IF EXISTS(SELECT TOP 1 1 FROM #tmpBalance1 WHERE (fcreditfor <> 0 AND fcredit = 0 ) OR (fdebitfor <> 0 AND fdebit = 0))
	 AND NOT EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Voucher  WHERE VoucherType = 1 AND IfCheck='t' ORDER BY BillNumberId DESC )
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg = '科目余额异常，结转操作中止。\n请先进行期末调汇！'
	RAISERROR(@msg,16,1)
	RETURN -1
END


--没有数据，不处理，直接返回
IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBalance1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '无可结转数据，结转操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END
-------------------------------------------------------------------------------------
--判断本年利润科目、利润分配科目,核算币别是否为不核算、本位币或者所有币别
IF @cid <> -1 AND @cid <> 0 AND @cid <> @syscid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg = '本年利润科目外币核算不应使用单一外币，结转操作中止！'
	RAISERROR(@msg,16,1)
	RETURN -1
END
IF @cidFen <> -1 AND @cidFen <> 0 AND @cidFen <> @syscid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg = '利润分配科目外币核算不应使用单一外币，结转操作中止！'
	RAISERROR(@msg,16,1)
	RETURN -1
END

DECLARE @VoucherBillnumberIds VARCHAR(100),@VoucherID INT,@OutVoucherId INT
SET @VoucherBillnumberIds = ''
SET @CompleteVoucherBillnumberIds = ''

DECLARE @TableData TbType_CLPData

DECLARE @loopcount INT
		,@loop	INT

SET @loop = 1
SET @loopcount = @CarryType+1

WHILE @loop <= @loopcount
BEGIN
	
	TRUNCATE TABLE #tmpBalance
	DELETE FROM @TableData
	
	--为1时表示借贷分开生成凭证，那么第一次全部用借方有数据的去生成，第二次则用贷方有数据的
	IF @CarryType = 1
	BEGIN
		IF @loop = 1
		BEGIN
			INSERT INTO #tmpBalance
			SELECT	fdc,
					fdebit ,
					fdebitfor ,
					fcredit ,
					fcreditfor ,
					cid,
					ATypeId,
					AscIds,
					item
			FROM	#tmpBalance1
			WHERE	fdc = 1
		END
		ELSE
		BEGIN
			INSERT INTO #tmpBalance
			SELECT	fdc,
					fdebit ,
					fdebitfor ,
					fcredit ,
					fcreditfor ,
					cid,
					ATypeId,
					AscIds,
					item
			FROM	#tmpBalance1
			WHERE	fdc = -1
			
		END
	END
	ELSE
	BEGIN
		INSERT INTO #tmpBalance
		SELECT	fdc,
				fdebit ,
				fdebitfor ,
				fcredit ,
				fcreditfor ,
				cid,
				ATypeId,
				AscIds,
				item
		FROM	#tmpBalance1
	END	
	
	SET @loop +=1
	
	IF @ascids = 0
	BEGIN
		INSERT INTO @TableData SELECT * FROM #tmpBalance
		
		EXEC @VoucherID =  
			dbo.GP_CarryLossProfit_Operate 
				@OperatorId,
				@STypeId,	
				@Billdate,	
				@Summary,	
				@vgid,
				@FYear,
				@FPeriod,
				@liruntypeid, 
				@lirunTypeidfen,
				@cid,
				@cidfen,
				@syscid,
				@fdc,
				@fdcfen,
				@TableData,
				@OutVoucherId OUT
				
		SET @CompleteVoucherBillnumberIds += CAST(@OutVoucherId AS VARCHAR) + ','
		
		IF @VoucherID <> 0
			SET @VoucherBillnumberIds += CAST(@VoucherID AS VARCHAR(50)) + ','
		
	END
	ELSE 
	BEGIN
		--具有指定辅助核算的损益数据
		CREATE TABLE #tmpBill_Assit
		(
			id		INT,
			fdc		INT,
			fdebit	 NUMERIC(24, 10) ,
			fdebitfor	 NUMERIC(24, 10) ,
			fcredit	 NUMERIC(24, 10) ,
			fcreditfor	 NUMERIC(24, 10) ,
			cid		INT,
			atypeid	VARCHAR(50),
			ascids	VARCHAR(1000),
			item	VARCHAR(100),
			typeName	VARCHAR(100),
			TypeId		VARCHAR(50),
			[Group]		VARCHAR(50)
		)

		--取具有此辅助核算的科目
		CREATE TABLE #TmpItem
		(
			id		INT IDENTITY(1,1),
			item	VARCHAR(500)
		)
		
		CREATE TABLE #TmpAscid
		(
			id	INT	IDENTITY(1,1),
			value	VARCHAR(50),
			balanceid	INT
		)
		
		DECLARE @ascStr VARCHAR(1000),@Count INT,@Item VARCHAR(500),@Index INT,@ItemId INT,@BalanceId INT
		
		DECLARE splitCur CURSOR READ_ONLY FOR
			SELECT ascids,id
			FROM #tmpBalance
		
		
		OPEN splitCur
		
		FETCH NEXT FROM splitCur INTO @ascStr,@BalanceId
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT @ascStr = SUBSTRING(@ascStr,0,LEN(@ascStr))
			INSERT INTO #TmpItem(item )
			SELECT * FROM dbo.f_split(@ascStr,',')
			
			SET @Index = 1
			SELECT @Count = COUNT(*) FROM #TmpItem
			
			WHILE @Index <= @Count
			BEGIN
				SELECT @Item = item FROM #TmpItem WHERE id = @Index
				
				INSERT INTO #TmpAscid(value,balanceid)
				SELECT *,@BalanceId FROM dbo.f_split(@item,':')
				
				SET @Index += 1
			END

			
			INSERT INTO #tmpBill_Assit
					( id ,
					  fdc ,
					  fdebit ,
					  fdebitfor ,
					  fcredit ,
					  fcreditfor ,
					  cid ,
					  atypeid ,
					  ascids ,
					  item ,
					  typeName ,
					  TypeId ,
					  [Group]
					)
			SELECT DISTINCT a.*,T3.UserCode AS typename,t2.value AS typeid,e.[Group]
			FROM #tmpBalance a 
			INNER JOIN dbo.Ac_Account e ON a.atypeid = e.typeid 
			INNER JOIN #TmpAscid T1 ON a.id = T1.balanceid
					INNER JOIN #TmpAscid t2 ON T1.id = (T2.id - 1)
					INNER JOIN dbo.Ac_Assist_CheckItems T3 ON T1.value = T3.AscIds
				WHERE T1.id % 2 <> 0
			
			TRUNCATE TABLE #TmpItem
			TRUNCATE TABLE #TmpAscid
			
			FETCH NEXT FROM splitCur INTO @ascStr,@BalanceId
		END
		CLOSE splitCur
		DEALLOCATE splitCur
		
		DELETE FROM #tmpBill_Assit WHERE typeName NOT IN (SELECT UserCode FROM dbo.Ac_Assist_CheckItems WHERE AscIds = @ascids)

		--剩余的不具有此辅助核算的科目
		SELECT DISTINCT a.*,d.[Group]
		INTO #tmpBill_NoAssit
		FROM #tmpBalance a 
		INNER JOIN dbo.Ac_Account d ON a.atypeid = d.TypeId
		WHERE d.STypeId = @stypeid  AND  NOT EXISTS (SELECT atypeid FROM #tmpBill_Assit WHERE id = a.id) AND d.StypeId = @stypeid
		
		--执行凭证生成
		DECLARE @AscidTypeid VARCHAR(50)
		DECLARE OperateCur CURSOR READ_ONLY FOR
			SELECT DISTINCT TypeId
			FROM #tmpBill_Assit
		OPEN OperateCur
		FETCH NEXT FROM OperateCur INTO @AscidTypeid
		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			DELETE FROM @TableData
			
			INSERT INTO @TableData 
			SELECT id ,
				  fdc ,
				  fdebit ,
				  fdebitfor ,
				  fcredit ,
				  fcreditfor ,
				  cid ,
				  atypeid ,
				  ascids ,
				  item  
			FROM #tmpBill_Assit 
			WHERE TypeId = @AscidTypeid
			
			IF EXISTS(SELECT TOP 1 1 FROM @TableData)
			BEGIN
				EXEC @VoucherID =  
				dbo.GP_CarryLossProfit_Operate 
					@OperatorId,
					@STypeId,	
					@Billdate,	
					@Summary,	
					@vgid,
					@FYear,
					@FPeriod,
					@liruntypeid, 
					@lirunTypeidfen,
					@cid,
					@cidfen,
					@syscid,
					@fdc,
					@fdcfen,
					@TableData,
					@OutVoucherId OUT
					
			SET @CompleteVoucherBillnumberIds = @CompleteVoucherBillnumberIds+','+ CAST(@OutVoucherId AS VARCHAR)
			
			IF @VoucherID <> 0
				SET @VoucherBillnumberIds = @VoucherBillnumberIds + ',' + CAST(@VoucherID AS VARCHAR(50))
			END
			
			FETCH NEXT FROM OperateCur INTO @AscidTypeid
		END
		CLOSE OperateCur
		DEALLOCATE OperateCur
		
		DELETE FROM  @TableData
		
		INSERT INTO @TableData 
		SELECT id ,
			  fdc ,
			  fdebit ,
			  fdebitfor ,
			  fcredit ,
			  fcreditfor ,
			  cid ,
			  atypeid ,
			  ascids ,
			  item  
		FROM #tmpBill_NoAssit
		
		IF EXISTS(SELECT TOP 1 1 FROM @TableData)
		BEGIN
			EXEC @VoucherID =  
			dbo.GP_CarryLossProfit_Operate 
				@OperatorId,
				@STypeId,	
				@Billdate,	
				@Summary,	
				@vgid,
				@FYear,
				@FPeriod,
				@liruntypeid, 
				@lirunTypeidfen,
				@cid,
				@cidfen,
				@syscid,
				@fdc,
				@fdcfen,
				@TableData,
				@OutVoucherId OUT
				
		SET @CompleteVoucherBillnumberIds = @CompleteVoucherBillnumberIds+','+ CAST(@OutVoucherId AS VARCHAR)
			
		
		IF @VoucherID <> 0
			SET @VoucherBillnumberIds = @VoucherBillnumberIds + ',' + CAST(@VoucherID AS VARCHAR(50))
		END
		
		DROP TABLE #TmpAscid,#tmpBill_Assit,#tmpBill_NoAssit,#TmpItem
	END
END

--获取需要用户补足的凭证
IF @VoucherBillnumberIds <> ''
BEGIN
	IF RIGHT(@VoucherBillnumberIds,1) = ','
	SET @VoucherBillnumberIds = SUBSTRING(@VoucherBillnumberIds,1,LEN(@VoucherBillnumberIds)- 1)
END
	
	
CREATE TABLE #tmpVoucherId
(
	billnumberid INT
)

INSERT INTO #tmpVoucherId SELECT * FROM dbo.f_split(@VoucherBillnumberIds,',')


SELECT	BillDate,
	VgId,
	STypeId,
	FlowNo,
	BillNumberId,
	FComment
FROM dbo.Ac_Voucher	
WHERE BillNumberId IN (SELECT billnumberid FROM #tmpVoucherId)

SELECT	billnumberid,
		a.Summary AS explain,
		b.UserCode,
		b.FullName,
		a.ATypeId AS typeid,
		c.Sysrow,
		a.cid,
		a.cid AS moneytype,
		c.BasisType,
		ISNULL(a.Rate,1) AS rate,
		CASE a.FAdc
			 WHEN 1		THEN a.FDebitTotalFor
			 WHEN -1	THEN a.FCreditTotalFor
		END AS balanceprice,
		CASE WHEN a.FDebitTotal = 0 THEN NULL ELSE FDebitTotal END AS lendprice,
		CASE WHEN a.FCreditTotal = 0 THEN NULL ELSE FCreditTotal END AS loanprice,
		a.FSettleNo,
		a.FSettleTypeID,
		a.Comment,
		a.STypeId,
		a.Fdc,
		a.FAdc,
		b.FAcnt,
		a.FCashFlowItem,
		a.RowNo,
		a.id,
		b.MainItems,
		b.AdditionItems,
		b.KeyId,
		b.IsCash,
		b.IsBank,
		b.IsDiary,
		b.TypeId,
		ISNULL(b.Cid,-1) AS mcid,
		b.mainitems AS mainitemsid,--主表项目id
		b.additionitems AS additionitemsid, --附表项目id
		d.fullname AS mainitemsname,--主表项目名称
		e.fullname AS additionitemsname,--附表项目名称
		dbo.F_GetAc_Assist_CheckItems_Str(a.BillNumberId,a.RowNo,'00001',1) AS assist,
		null AS asslist,
		a.FSettleNo AS balancenum,
		a.FSettleTypeID AS balancetype,
		c.UserCode,
		c.FullName
FROM dbo.Ac_Voucher_Bill a
	LEFT JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND b.StypeId = @stypeid
	LEFT JOIN dbo.Ac_Currency c ON a.Cid = c.CId
	LEFT JOIN dbo.Ac_CashMoneyItems d ON b.MainItems = d.TypeId
	LEFT JOIN dbo.Ac_CashMoneyItems e ON b.AdditionItems = e.TypeId
WHERE BillNumberId IN (SELECT billnumberid FROM #tmpVoucherId)

SELECT	DISTINCT a.nid,
		a.BillNumberId,
		a.vBId,
		a.typeName AS usercode,
		a.TypeId,
		CASE a.typeName
		WHEN '01' THEN (SELECT FullName FROM SType WHERE TypeId = a.TypeId)
		WHEN '02' THEN (SELECT FullName FROM Department WHERE TypeId = a.TypeId)
		WHEN '03' THEN (SELECT FullName FROM employee WHERE TypeId = a.TypeId)
		WHEN '04' THEN (SELECT FullName FROM BType WHERE TypeId = a.TypeId)
		END AS fullname,
		CASE a.typeName
		WHEN '01' THEN 'sfullname'
		WHEN '02' THEN 'dfullname'
		WHEN '03' THEN 'efullname'
		WHEN '04' THEN 'bfullname'
		END AS displayfield,
		CASE a.typeName
		WHEN '01' THEN 'stypeid'
		WHEN '02' THEN 'dtypeid'
		WHEN '03' THEN 'etypeid'
		WHEN '04' THEN 'btypeid'
		END AS datafield,
		b.AscIds AS value
FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a
INNER JOIN dbo.Ac_Assist_CheckItems b ON a.typeName = b.UserCode
WHERE a.BillNumberId IN (SELECT billnumberid FROM #tmpVoucherId)


DELETE FROM dbo.Ac_Voucher WHERE BillNumberId IN (SELECT billnumberid FROM #tmpVoucherId)
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId IN (SELECT billnumberid FROM #tmpVoucherId)
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId IN (SELECT billnumberid FROM #tmpVoucherId)

DROP TABLE #tmpVoucherId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.08.29
	描述：结转损益 结转操作
*/
CREATE PROCEDURE GP_CarryLossProfit_Operate
(
	@OperatorId			VARCHAR(50),			 -- 当前操作员ID
	@STypeId			VARCHAR(50),			 -- 分支机构
	@Billdate			DATETIME,				 -- 凭证日期
	@Summary			VARCHAR(MAX),			 -- 摘要
	@VGid				INT,					 -- 凭证字
	@FYear				INT,					 -- 年度
	@FPeriod			INT,					 -- 期间
	@ProfitTypeid		VARCHAR(50),			 -- 本年利润科目
	@ProfitAllotTypeid	VARCHAR(50),			 -- 利润分配科目
	@Profit_Cid			INT,					 -- 本年利润科目币别
	@ProfitAllot_Cid	INT,					 -- 利润分配科目币别
	@SCid				INT,					 -- 本位币
	@Profit_FDC			INT,					 -- 本年利润科目方向
	@ProfitAllot_FDC	INT,					 -- 利润分配科目方向
	@TableData			TbType_CLPData	READONLY, --结转数据
	@OutVoucherId		INT OUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @VoucherID	INT, -- 生成的凭证ID
		@msg		VARCHAR(MAX) -- 消息

--获取本年利润、利润分配科目的汇率、计算方式
DECLARE @Profit_Rate  NUMERIC(24, 10) ,@ProfitAllot_Rate  NUMERIC(24, 10) ,@Profit_Type INT,@ProfitAllot_Type INT
IF @Profit_Cid NOT IN (-1,0)
	SELECT @Profit_Rate = Rate,@Profit_Type=BasisType FROM dbo.Ac_Currency WHERE CId = @Profit_Cid
ELSE
BEGIN
	SELECT @Profit_Rate = Rate,@Profit_Type=BasisType FROM dbo.Ac_Currency WHERE CId = @SCid	
END
IF @ProfitAllot_Cid NOT IN (-1,0)
	SELECT @ProfitAllot_Rate = Rate,@ProfitAllot_Type = BasisType FROM dbo.Ac_Currency WHERE CId = @ProfitAllot_Cid
ELSE
	SELECT @ProfitAllot_Rate = Rate,@ProfitAllot_Type = BasisType FROM dbo.Ac_Currency WHERE CId = @SCid

--创建凭证表头
EXEC @VoucherID = dbo.GP_SaveAc_VoucherIndex 
		@stypeid = @stypeid, 
		@vgid = @vgid, 
		@billdate = @billdate,
		@flowno = 0, 
		@attachfilecount = 0,
		@fchecked = 0, 
		@etypeid = @OperatorId, 
		@fcredittotal = 0, 
		@fdebittotal = 0,
		@fentrycount = 0, 
		@audited = 0, 
		@ifcheck = 'f', 
		@type = 2
		
IF @VoucherID = -1
BEGIN
	SET @msg = '您使用的是试用版，凭证数据不能大于200'
	RAISERROR(@msg,16,1)
	RETURN -1
END


-----------损益统计，即利润金额信息------------
CREATE TABLE #Tmp_Profit
(
	id		INT	IDENTITY(1,1),
	jieben	 NUMERIC(24, 10) ,
	daiben	 NUMERIC(24, 10) ,
	jieyuan	 NUMERIC(24, 10) ,
	daiyuan	 NUMERIC(24, 10) ,
	atypeid	VARCHAR(50),
	cid		INT,
	ascids	VARCHAR(1000),
	fadc	INT,
	fdc		INT,
	item	VARCHAR(50)
)
	
---------单据处理的对应利润分配的损益科目统计-------
CREATE TABLE #Tmp_ProfitAllot
(
	id		INT	IDENTITY(1,1),
	jieben	 NUMERIC(24, 10) ,
	daiben	 NUMERIC(24, 10) ,
	jieyuan	 NUMERIC(24, 10) ,
	daiyuan	 NUMERIC(24, 10) ,
	atypeid	VARCHAR(50),
	cid		INT,
	ascids	VARCHAR(1000),
	fadc	INT,
	fdc		INT,
	item	VARCHAR(50)
)

INSERT INTO #Tmp_Profit
        ( jieben ,
          daiben ,
          jieyuan ,
          daiyuan ,
          atypeid ,
          cid ,
          ascids ,
          fadc ,
          fdc,
          item
        )
SELECT	
		SUM(fdebit) AS jieben,
		SUM(fcredit) AS daiben,
		SUM(fdebitfor) AS jieyuan,
		SUM(fcreditfor) AS daiyuan,
		atypeid,a.cid,a.ascids,a.fdc AS fadc,b.fdc,item
FROM @TableData a
INNER JOIN dbo.Ac_Account b ON a.atypeid = b.TypeId
WHERE b.StypeId = @stypeid AND [Group] <> '506'--排除掉“以前年度损益调整”科目的信息
GROUP BY atypeid,a.cid,a.ascids,a.fdc,b.fdc,item

--调整金额方向
UPDATE #Tmp_Profit SET fadc = 1 WHERE jieben <> 0
UPDATE #Tmp_Profit SET fadc = -1 WHERE daiben <> 0
UPDATE #Tmp_ProfitAllot SET fadc = 1 WHERE jieben <> 0
UPDATE #Tmp_ProfitAllot SET fadc = -1 WHERE daiben <> 0

INSERT INTO #Tmp_ProfitAllot
        ( jieben ,
          daiben ,
          jieyuan ,
          daiyuan ,
          atypeid ,
          cid ,
          ascids ,
          fadc ,
          fdc,
          item
        )
SELECT	
		SUM(fdebit) AS jieben,
		SUM(fcredit) AS daiben,
		SUM(fdebitfor) AS jieyuan,
		SUM(fcreditfor) AS daiyuan,
		atypeid,a.cid,a.ascids,a.fdc AS fadc,b.fdc,item
FROM @TableData a
INNER JOIN dbo.Ac_Account b ON a.atypeid = b.TypeId
WHERE b.StypeId = @stypeid AND [Group] = '506'--“以前年度损益调整”科目的信息
GROUP BY atypeid,a.cid,a.ascids,a.fdc,b.fdc,item

--处理0值
DELETE FROM #Tmp_Profit WHERE ISNULL(jieben,0) = 0 AND ISNULL(daiben,0) = 0 AND ISNULL(jieyuan,0) = 0 AND ISNULL(daiyuan,0) = 0
DELETE FROM #Tmp_ProfitAllot WHERE ISNULL(jieben,0) = 0 AND ISNULL(daiben,0) = 0 AND ISNULL(jieyuan,0) = 0 AND ISNULL(daiyuan,0) = 0


------凭证明细临时表------
CREATE TABLE #Tmp_VoucherDetails
(
	billnumberid	INT,
	summary			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	idfor			INT,
	fdc				INT,
	FDebitTotal		 NUMERIC(24, 10) ,
	FCreditTotal	 NUMERIC(24, 10) ,
	FDebitTotalfor	 NUMERIC(24, 10) ,
	FCreditTotalfor	 NUMERIC(24, 10) ,
	ascids			VARCHAR(1000),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT
)

--插入本年利润、利润分配数据
--插入损益类科目数据，金额反向
INSERT INTO #Tmp_VoucherDetails
SELECT	billnumberid,
		summary,
		atypeid,
		atypeid2,
		idfor,
		fdc,
		SUM(jie),
		SUM(dai),
		SUM(jiefor),
		SUM(daifor),
		ascids,
		cid,
		fadc,
		stypeid,
		fyear,
		fperiod
FROM
(
SELECT	@VoucherID	AS billnumberid,
		@summary		AS summary,
		@ProfitTypeid	AS atypeid,
		''				AS atypeid2,
		CASE WHEN @Profit_Cid IN (-1,0) THEN  a.cid
			 ELSE @Profit_Cid
		END 			AS idfor,
		@Profit_FDC		AS fdc,
		jieben			AS jie,
		daiben			AS dai,
		dbo.F_RoundTotal(CASE WHEN @Profit_Cid IN (-1,0) THEN jieyuan
			ELSE CASE WHEN @Profit_Type = 0 THEN jieben / @Profit_Rate
						ELSE jieben * @Profit_Rate	
				 END
		END 		)	AS jiefor,
		dbo.F_RoundTotal(CASE WHEN @Profit_Cid IN (-1,0) THEN daiyuan
			ELSE CASE WHEN @Profit_Type = 0 THEN daiben / @Profit_Rate
						ELSE daiben * @Profit_Rate	
				 END
		END 		)	AS daifor,
		a.AscIds,
		CASE WHEN @Profit_Cid IN (-1,0) THEN  a.cid
			 ELSE @Profit_Cid
		END				AS cid,
		fadc,
		@stypeid AS stypeid,@fyear AS fyear,@fperiod AS fperiod
FROM #Tmp_Profit a
)T
GROUP BY billnumberid,
		summary,
		atypeid,
		atypeid2,
		idfor,
		fdc,
		ascids,
		cid,
		fadc,
		stypeid,
		fyear,
		fperiod
UNION ALL
SELECT	billnumberid,
		summary,
		atypeid,
		atypeid2,
		idfor,
		fdc,
		SUM(jie),
		SUM(dai),
		SUM(jiefor),
		SUM(daifor),
		ascids,
		cid,
		fadc,
		stypeid,
		fyear,
		fperiod
FROM
(
SELECT	@VoucherID	AS billnumberid,
		@summary		AS summary,
		@ProfitAllotTypeid	AS atypeid,
		''				AS atypeid2,
		CASE WHEN @ProfitAllot_Cid IN (-1,0) THEN  a.cid
			 ELSE @ProfitAllot_Cid
		END 			AS idfor,
		@ProfitAllot_FDC		AS fdc,
		jieben			AS jie,
		daiben			AS dai,
		dbo.F_RoundTotal(CASE WHEN @ProfitAllot_Cid IN (-1,0) THEN jieyuan
			ELSE CASE WHEN @ProfitAllot_Type = 0 THEN jieben / @ProfitAllot_Rate
						ELSE jieben * @Profit_Rate	
				 END
		END 		)	AS jiefor,
		dbo.F_RoundTotal(CASE WHEN @ProfitAllot_Cid IN (-1,0) THEN daiyuan
			ELSE CASE WHEN @ProfitAllot_Type = 0 THEN daiben / @ProfitAllot_Rate
						ELSE daiben * @ProfitAllot_Rate	
				 END
		END 		)	AS daifor,
		a.AscIds,
		CASE WHEN @ProfitAllot_Cid IN (-1,0) THEN  a.cid
			 ELSE @ProfitAllot_Cid
		END				AS cid,
		fadc,
		@stypeid AS stypeid,@fyear AS fyear,@fperiod AS fperiod
FROM #Tmp_ProfitAllot a
)T
GROUP BY billnumberid,
		summary,
		atypeid,
		atypeid2,
		idfor,
		fdc,
		ascids,
		cid,
		fadc,
		stypeid,
		fyear,
		fperiod
UNION ALL
SELECT	@VoucherID	AS billnumberid,
		@summary		AS summary,
		atypeid			AS atypeid,
		''				AS atypeid2,
		a.cid			AS idfor,
		fdc				AS fdc,
		SUM(daiben)		AS jie,
		SUM(jieben)		AS dai,
		SUM(daiyuan)		AS jiefor,
		SUM(jieyuan)		AS daifor,
		a.AscIds,
		a.cid,
		-fadc,
		@stypeid AS stypeid,@fyear AS fyear,@fperiod AS fperiod
FROM #Tmp_Profit a
GROUP BY atypeid,cid,ascids,fadc,fdc
UNION ALL
SELECT	@VoucherID	AS billnumberid,
		@summary		AS summary,
		atypeid	AS atypeid,
		''				AS typeid2,
		a.cid			AS idfor,
		fdc				AS fdc,
		SUM(daiben)		AS jie,
		SUM(jieben)		AS dai,
		SUM(daiyuan)		AS jiefor,
		SUM(jieyuan)		AS daifor,
		a.AscIds,
		a.cid,
		-fadc,
		@stypeid AS stypeid,@fyear AS fyear,@fperiod AS fperiod
FROM #Tmp_ProfitAllot a
GROUP BY atypeid,cid,ascids,fadc,fdc

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
SELECT	billnumberid,
		summary,
		stypeid,
		ATypeId,
		ATypeId2,
		fdc,
		@SCid,
		idfor,
		FDebitTotal,
		FDebitTotalFor,
		FCreditTotal,
		FCreditTotalFor,
		'',
		ascids,
		'',
		'',
		fyear,
		fperiod,
		'',
		idfor,
		rowno,
		Rate,
		fadc
FROM #Tmp_VoucherDetails T1
	INNER JOIN dbo.Ac_Currency T2 ON T1.cid = T2.CId

--调整并插入辅助核算
EXEC dbo.Gp_InsertAscidsAsDetails @VoucherID

--合并相同明细
DECLARE @newVoucherId INT --临时BillNumberId
SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

SELECT  @newVoucherId AS billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		SUM(FDebitTotal) AS FDebitTotal,
		SUM(FCreditTotal) AS FCreditTotal,
		SUM(FDebitTotalFor) AS FDebitTotalFor,
		SUM(FCreditTotalFor) AS FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		IDENTITY(INT,1,1) AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @VoucherID
GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod

DELETE #tmpNewVoucherBill WHERE FDebitTotal = 0 AND FCreditTotal = 0

--用于记录明细ID，插入辅助核算使用
CREATE TABLE #tmpId
(
	id INT,
	ascids VARCHAR(1000)
)

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.AscIds INTO #tmpId
SELECT  billnumberid,
		Summary ,
		STypeId ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FDebitTotalFor,
		FCreditTotal,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		FYear ,
		FPeriod,
		Comment ,
		Cid ,
		rowno,
		Rate ,
		FAdc
FROM #tmpNewVoucherBill


--辅助核算
INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
			( BillNumberId ,
			  vBId ,
			  typeName ,
			  TypeId
			)
SELECT DISTINCT	@newVoucherId,
		c.id,
		typeName,
		TypeId  
FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
INNER  JOIN dbo.Ac_Voucher_Bill b ON a.vBId = b.ID
INNER JOIN #tmpId c ON b.AscIds = c.ascids
WHERE a.BillNumberId = @VoucherID

DROP TABLE #tmpId,#tmpNewVoucherBill

--更新表头分录数
UPDATE dbo.Ac_Voucher SET FEntryCount = (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID)

--删除旧分录数据
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherID

--替换临时BillNumberId为真实的
UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @VoucherID WHERE BillNumberId = @newVoucherId
UPDATE dbo.Ac_Voucher_Bill_Assist_CheckItems SET BillNumberId = @VoucherID WHERE BillNumberId = @newVoucherId

--------合并完成---------


--调整表头借贷总额、分录总数
DECLARE @DebitTotal  NUMERIC(24, 10) ,@CreditTotal  NUMERIC(24, 10) ,@TotolRow INT
SELECT @DebitTotal = SUM(FDebitTotal),@CreditTotal = SUM(FCreditTotal),@TotolRow = COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID
UPDATE dbo.Ac_Voucher SET FDebitTotal = @DebitTotal,FCreditTotal = @CreditTotal WHERE BillNumberId = @VoucherID

--判断是否需要用户修正
--本年利润或者利润分配科目有辅助核算，但是生成没有获取到，弹出让用户补足
DECLARE @lirunassit VARCHAR(100),@lirunassitFen VARCHAR(100)
SET @lirunassit = dbo.F_Get_AscidsItem(@stypeid,@ProfitTypeid)
SET @lirunassitFen = dbo.F_Get_AscidsItem(@stypeid,@ProfitAllotTypeid)

--如果Ac_Voucher_Bill明细表不存在，则删除主表数据
IF NOT EXISTS(SELECT * FROM Ac_Voucher_Bill WHERE BillNumberId=@VoucherID)
BEGIN
	DELETE FROM Ac_Voucher WHERE BillNumberId=@VoucherID
END

IF (LEN(@lirunassit) = 2 
	AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE ATypeId = @ProfitTypeid AND BillNumberId = @VoucherID)
	AND EXISTS(SELECT TOP 1 1 FROM 
					(SELECT b.* FROM dbo.Ac_Voucher_Bill a
					LEFT JOIN dbo.Ac_Voucher_Bill_Assist_CheckItems b ON a.ID = b.vBId
					where a.ATypeId = @ProfitTypeid AND a.BillNumberId = @VoucherID
					) c WHERE ISNULL(c.TypeId,'') = ''))
OR (LEN(@lirunassit) > 2 
	AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE ATypeId = @ProfitTypeid AND BillNumberId = @VoucherID)
	AND (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
						INNER JOIN dbo.Ac_Voucher_Bill b ON a.vBId = b.ID AND b.ATypeId = @ProfitTypeid AND b.BillNumberId = @VoucherID) <>
						(SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill b 
						LEFT JOIN dbo.Ac_Voucher_Bill_Assist_CheckItems a ON a.vBId = b.ID 
						where b.ATypeId = @ProfitTypeid AND b.BillNumberId = @VoucherID) )
OR (LEN(@lirunassitFen) =2 
		AND EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE ATypeId = @ProfitAllotTypeid AND BillNumberId = @VoucherID)
		AND EXISTS(SELECT TOP 1 1 FROM 
							(SELECT b.* FROM dbo.Ac_Voucher_Bill a
							LEFT JOIN dbo.Ac_Voucher_Bill_Assist_CheckItems b ON a.ID = b.vBId
							where a.ATypeId = @ProfitAllotTypeid AND a.BillNumberId = @VoucherID
							) c WHERE ISNULL(c.TypeId,'') = ''))
OR (LEN(@lirunassitFen) >2 
		AND EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE ATypeId = @ProfitAllotTypeid AND BillNumberId = @VoucherID)
		AND (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
						INNER JOIN dbo.Ac_Voucher_Bill b ON a.vBId = b.ID AND b.ATypeId = @ProfitAllotTypeid AND b.BillNumberId = @VoucherID) <>
						(SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill b 
						LEFT JOIN dbo.Ac_Voucher_Bill_Assist_CheckItems a ON a.vBId = b.ID 
						where b.ATypeId = @ProfitAllotTypeid AND b.BillNumberId = @VoucherID))
BEGIN
	RETURN @VoucherID
END
SET @OutVoucherId = @VoucherID
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_CarrylossProfit_VoucherAuditing]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_CarrylossProfit_VoucherAuditing]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===================================
--by:gulijuan
--date:2014-10-30
--function:损益结转后将损益凭证立即记账
	--由于现功能跟原凭证查询界面记账所有未记账功能相似，所以只做细节处理
--======================================
CREATE PROCEDURE Gp_CarrylossProfit_VoucherAuditing
(
	@BillIds		VARCHAR(MAX),		--记账凭证ID字符串
	@OperatorId		VARCHAR(50)			-- 操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @rValue			VARCHAR(2000),	--出错信息
		@BillCode		VARCHAR(500),	--凭证字号
		@I				INT,			--需要过账凭证临时表的自增ID
		@BillCount		INT,			--需要过账凭证条数
		@BillNumberId	NUMERIC(18,0),	--过账凭证ID
		@PassCount		INT,			--记账成功条数
		@FailtCount		INT,			--记账失败条数
		@BillMsg		VARCHAR(2000),	--记账出错原因说明
		@Re				INT				--凭证记账是否成功

--记账凭证临时表
DECLARE @VoucherBill TABLE
(
	Nid				INT IDENTITY(1,1),
	BillNumberId	NUMERIC(18,0),
	BillCode		VARCHAR(500)
)

--返回记账结果
DECLARE @Result TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)

--未记账的凭证
INSERT INTO @VoucherBill
(
	BillNumberId,
	BillCode
)
SELECT	BillNumberId,
		BillCode = G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
INNER JOIN f_split(@BillIds,',') F ON F.A=V.BillNumberId

SET @BillCount = @@ROWCOUNT

--过账单据
SET @I = 1
SET @PassCount = 0
SET @FailtCount = 0
WHILE @I <= @BillCount
BEGIN
	SET @BillMsg = ''
	
	SELECT @BillNumberId = BillNumberId,@BillCode = BillCode FROM @VoucherBill WHERE Nid = @I
	
	BEGIN TRY
		BEGIN
			EXEC @Re = Gp_Voucher_Auditing @BillNumberId,@OperatorId,@rValue OUTPUT
			
			IF @Re = 0
			BEGIN
				INSERT INTO @Result(BillCode,Msg)VALUES('凭证'+@BillCode,',成功！')
				SET @PassCount = @PassCount + 1
			END
		END	
	END TRY
	BEGIN CATCH
		BEGIN			
			SET @FailtCount = @FailtCount + 1
			SET @BillMsg = ERROR_MESSAGE()
			--处理提示
			SET @BillMsg = REPLACE(@BillMsg,'，不允许记账，请确认！','')	
			IF @BillMsg <> ''
				INSERT INTO @Result(BillCode,Msg)VALUES('凭证'+@BillCode,',失败,原因为'+@BillMsg)
		END
	END CATCH		
	
	SET @I = @I + 1
END

--展示结果
DECLARE @showResult TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)

--第一条记录
INSERT INTO @showResult(BillCode,Msg)VALUES('成功记账:','')
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',成功' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('成功共',CAST(@PassCount AS VARCHAR(100)) + '张')

--失败张数
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',失败' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('失败共',CAST(@FailtCount AS VARCHAR(100))+'张')

SELECT * FROM @showResult ORDER BY Nid ASC


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

--====================================================================================
-----------------功能：单据超收超付金额和收付款单未结算金额结转至期初收付款单 
-----------------作者：施训果						   
-----------------日期：2016-08-17                 
--====================================================================================

CREATE	PROC Gp_CarryOverToIniBill

--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #gather_paybill
(	
	BTypeID varchar (50) NOT NULL,
	DealBtypeid varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	total  NUMERIC(24,10),
	ntotal NUMERIC(24,10),
	billtype VARCHAR(50),
	Comment VARCHAR(50)
)
DECLARE @startdate DATETIME
SELECT @startdate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth

TRUNCATE TABLE #gather_paybill

		--超付转入期初付款单(业务员和部门取默认值)
		INSERT INTO #gather_paybill
		( 
			BTypeID,
			DealBtypeid,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			total,
			ntotal,
			billtype,
			Comment
		)SELECT 
			BtypeId,
			DealBTypeID,
			Stypeid,
			DTypeId,
			etypeid,
			CID,
			SUM(
				CASE WHEN BillType IN (6) 
					THEN -(totalinmoney + CompleteTotal  + preferencemoney - totalmoney)
				ELSE
					(totalinmoney + CompleteTotal  + preferencemoney - totalmoney)
				END
			) AS total,
			SUM(
				CASE WHEN BillType IN (6) 
					THEN -(ntotalinmoney + nCompleteTotal  + npreferencemoney - ntotalmoney)
				ELSE
					(ntotalinmoney + nCompleteTotal  + npreferencemoney - ntotalmoney)
				END
			) AS ntotal,
			66 AS billtype,
			'数据结转时原业务单据超付金额转入'
		FROM dbo.BillIndex
		WHERE RedWord=0 
		AND draft=0 
		AND
		(	
			BillType IN(6,34,145,161,84,150,151,170,128,129) 
			OR
			(BillType = 36 AND btypeid like '00002%')
		)
		AND 
		(
			(Ntotalinmoney + NCompleteTotal  + Npreferencemoney > 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney > Ntotalmoney) 
			OR 
			(Ntotalmoney < 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney < Ntotalmoney)
		)
		AND (ifYearBill<>1 OR IsIni=1)
		GROUP BY BTypeID,STypeID,CID,DealBtypeid,etypeid,DTypeId
	
	--超收转入期初收款单
	INSERT INTO #gather_paybill
	( 
			BTypeID ,
			DealBtypeid,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			total ,
			ntotal ,
			billtype ,
			Comment 
	)SELECT BtypeId,
			DealBtypeid,
			Stypeid,
			DTypeId,
			etypeid,
			CID,
			SUM(
				CASE WHEN BillType IN (45,36) 
					THEN -(totalinmoney + CompleteTotal  + preferencemoney - totalmoney)
				ELSE
						(totalinmoney + CompleteTotal  + preferencemoney - totalmoney)
				END
			),
			SUM(
				CASE WHEN BillType IN (45,36) 
					THEN -(ntotalinmoney + nCompleteTotal  + npreferencemoney - ntotalmoney)
				ELSE
						(ntotalinmoney + nCompleteTotal  + npreferencemoney - ntotalmoney)
				END
			),
			4 ,
			'数据结转时原业务单据超收金额转入'
	FROM dbo.BillIndex
	WHERE RedWord=0 
	AND draft=0 
	AND
	(
		BillType IN(11,45,141,148,85,93,148,149,181,167,168,172,115,116) 
		OR
		(BillType = 36 AND btypeid like '00001%')
	)
	AND 
	(
		(Ntotalinmoney + NCompleteTotal  + Npreferencemoney > 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney > Ntotalmoney) 
		OR 
		(Ntotalmoney < 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney < Ntotalmoney)
	)
	AND (ifYearBill<>1 OR IsIni=1)
	GROUP BY BTypeID,STypeID,CID,DealBtypeid,DTypeId,etypeid
	
	--未结算完成的付款单转入期初
	INSERT INTO #gather_paybill
	( 
			BTypeID ,
			DealBtypeid,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			total ,
			ntotal ,
			billtype ,
			Comment 
	)SELECT BtypeId,
			DealBtypeid,
			Stypeid,
			DTypeId,
			etypeid,
			CID,
			SUM(z.total-z.completotal),
			SUM(z.ntotal-z.ncompletotal),
			billtype,
			'数据结转时未结算完成收付款单金额转入'
	FROM (
			SELECT SUM(ISNULL(c.CompleteTotal,0)) AS completotal,
			SUM(ISNULL(c.NCompleteTotal,0)) AS ncompletotal,
			MAX(b.totalmoney+b.preferencemoney) AS total,
			MAX(b.ntotalmoney+b.npreferencemoney) AS ntotal,
			MAX(b.BTypeID) AS btypeid, 
			MAX(b.DealBtypeid) AS DealBtypeid,
			MAX(STypeID) AS STypeID,
			MAX(DTypeId) AS DTypeId,
			MAX(b.ETypeId) AS ETypeId,
			MAX(CID) AS	CID ,
			MAX(b.billtype) AS billtype 
			FROM dbo.CompleteTotal c RIGHT JOIN dbo.BillIndex b ON c.MoneyBillID=b.BillNumberId
			WHERE b.BillType IN (4,66) AND RedWord=0 AND b.draft=0
			GROUP BY b.BillNumberId
		) z
	WHERE z.billtype IN(4,66) AND 
	z.Ntotal!=z.Ncompletotal
	GROUP BY z.BTypeID,z.STypeID,z.DTypeId,z.etypeid,z.CID,z.BillType,z.DealBtypeid

--清除合计为零的数据
IF EXISTS(SELECT 1 FROM #gather_paybill) 
BEGIN
	--重新插入了年结期初数据，把之前的年结标志先置为0
	update BillIndex set ifYearBill=0 WHERE ifYearBill=1 AND IsIni=1
	
	INSERT INTO [dbo].[BillIndex] 
	(	
		[IfYearBill],
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DEALBTYPEID,
		cid,	
		rate,	
		ntotalmoney,
		ntotalinmoney,	
		npreferencemoney,	
		nvipczmoney,	
		atypeid1,
		billproperty,
		ncompletetotal,
		IsIni
	)

	SELECT	
		1,
		0.00,
		CONVERT(DATE, @startdate),
		CASE billtype 
			WHEN '4' THEN 'XS-T-' 
			WHEN '66' THEN 'JF-'
		END + LEFT(NEWID(),9) + s.UserCode+'-'+CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
		billtype,
		b.Comment,
		'',
		'',
		btypeid,
		etypeid,
		'',
		'',
		't',
		'',
		0,
		total,
		0,
		0,
		1,
		'',
		0,
		0,
		0,
		'',
		'',
		'',
		'',
		0,
		9999,
		0,
		'',
		'',
		'',
		dtypeid,
		'',
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		STypeID,
		0,
		0,
		0,
		-1,
		'',
		@startdate,
		NULL,
		0,
		'',
		'',
		'',
		'',
		'',
		DealBTypeID,
		B.cid,	
		CASE WHEN ntotal=0 THEN AC.RATE 
			WHEN AC.BasisType=0 THEN dbo.F_RoundExchangeRate(total/ntotal) 
			ELSE dbo.F_RoundExchangeRate(ntotal/total) END,	
		ntotal,
		0,	
		0,	
		0,	
		(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
		1,
		0,
		1
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY stypeid,DTypeId,etypeid,cid) sort,
				Stypeid,
				btypeid,	
				DealBtypeid,
				DTypeId,
				etypeid,
				CID,
				BillType,
				Comment,
				SUM(total) AS total,
				SUM(ntotal) AS ntotal
		FROM #gather_paybill
		GROUP BY Stypeid,btypeid,DTypeId,etypeid,CID,BillType,Comment,DealBtypeid
	)b	INNER JOIN dbo.SType s ON b.Stypeid=s.TypeId
	INNER JOIN dbo.Ac_Currency AC ON B.CID=AC.CId
	
	DECLARE @atypeid INT=1
	SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
	INSERT INTO dbo.PayBill
        ( BillNumberId ,
          AtypeId ,
          total ,
          Comment ,
          TeamNo ,
          TeamNO1 ,
          Stypeid ,
          ntotal ,
          ShowOrder ,
          VipCardID ,
          RelevanceBillId
        ) 
	SELECT 
		B.BillNumberId,
		@atypeid,
		ba.total,
		'',
		0,
		0,
		ba.STypeID,
		ba.ntotal,
		0,
		0,
		NULL
	FROM #gather_paybill ba 
	INNER JOIN dbo.BillIndex B ON ba.stypeid=b.Stypeid AND ba.btypeid=b.btypeid  AND ba.DealBtypeid=b.DealBtypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid
	WHERE	b.BillType = 66
			AND b.IsIni=1
			AND ifYearBill=1
			AND b.Comment=ba.comment
	
	IF @@ERROR<>0
		RAISERROR('处理超收超付转期初收付款单失败！',16,1)     
	
	--SELECT * FROM #gather_paybill
	INSERT INTO dbo.gatheringBill
        ( BillNumberId ,
          AtypeId ,
          total ,
          Comment ,
          TeamNo ,
          TeamNO1 ,
          Stypeid ,
          ntotal ,
          ShowOrder ,
          VipCardID ,
          RelevanceBillId
        )
     SELECT 
		B.BillNumberId,
		@atypeid,
		ba.total,
		'',
		0,
		0,
		ba.STypeID,
		ba.ntotal,
		0,
		0,
		NULL
	FROM #gather_paybill ba 
	INNER JOIN dbo.BillIndex B ON ba.stypeid=b.Stypeid AND ba.btypeid=b.btypeid AND ba.DealBtypeid=b.DealBtypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid
	WHERE	b.BillType = 4
			AND b.IsIni=1
			AND ifYearBill=1
			AND b.Comment=ba.comment
			
	IF @@ERROR<>0
		RAISERROR('处理超收超付转期初收付款单失败！',16,1)       
END
DROP TABLE #gather_paybill
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[gp_ChangeIniFlag]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].gp_ChangeIniFlag
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：梁晰
	时间：2016-09-20
	描述：修改实物期初序列号标识
*/
CREATE PROC gp_ChangeIniFlag

--@encode$--  	
as
DECLARE @KtypeID varchar(500),@PtypeID varchar(500),@GoodsNumber varchar(500),
@ItemID int, @IsCombined int, @ProduceDate varchar(50),@ValidDate varchar(50), @CargoID INT;

SELECT * INTO #dt FROM gp_iniFactPtypeSerial;
DECLARE CURSORT0 CURSOR FOR
SELECT   KtypeID,PtypeID,GoodsNumber,ItemID,IsCombined,CargoID,
								CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END AS 'ProduceDate',
								CASE WHEN ISNULL(ValidDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END AS 'Validdate'
					FROM #dt
					GROUP BY KtypeID,PtypeID,GoodsNumber,ItemID,IsCombined,CargoID,
						CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END ,
						CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END 
					OPEN CURSORT0
					FETCH NEXT FROM CURSORT0 INTO @KtypeID,@PtypeID,@GoodsNumber,@ItemID,@IsCombined,@CargoID,@ProduceDate,@ValidDate
					WHILE @@FETCH_STATUS = 0
					begin

SELECT * ,IDENTity(int,1,1)AS b INTO #aa FROM IniFactStocks_Qty
WHERE KtypeID =@KtypeID AND PtypeID = @PtypeID;

UPDATE gp_iniFactPtypeSerial SET iniflag = (SELECT TOP 1 b FROM(SELECT * from #aa)v
WHERE v.KtypeID = @KtypeID
AND v.PtypeID = @PtypeID
AND v.GoodsNumber = isnull(@GoodsNumber, '')
AND v.ItemID = ISNULL(@ItemID, 0)
AND v.IsCombined = ISNULL(@IsCombined, 0)
AND v.ProduceDate = ISNULL(@ProduceDate, '')
AND v.ValidDate = ISNULL(@ValidDate, '')
AND v.CargoID = ISNULL(@CargoID, 0))
WHERE  KtypeID = @KtypeID
AND PtypeID = @PtypeID
AND GoodsNumber = isnull(@GoodsNumber, '')
AND ItemID = ISNULL(@ItemID, 0)
AND IsCombined = ISNULL(@IsCombined, 0)
AND ProduceDate = ISNULL(@ProduceDate, '')
AND ValidDate = ISNULL(@ValidDate, '')
AND CargoID = ISNULL(@CargoID, 0);


DROP TABLE #aa

FETCH NEXT FROM CURSORT0 INTO @KtypeID,@PtypeID,@GoodsNumber,@ItemID,@IsCombined,@CargoID,@ProduceDate,@ValidDate
END
					CLOSE CURSORT0
					DEALLOCATE CURSORT0
					
					GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



GO
	--
	--	月结是否需要成本计算
	--  RETURN -1 需要成本计算才能月结
	--  RETURN  0 不需要成本计算
	--  取需要计算的商品、分支机构余CostReLog中的最近一条记录进行比较
	-- 校驗時去掉單據類型
	--
IF EXISTS ( SELECT  1
            FROM    SysObjects
            WHERE   ID = OBJECT_ID(N'GP_Check_MonthEnd_NeedCostCompute', N'P') )
    BEGIN
        DROP PROC GP_Check_MonthEnd_NeedCostCompute
    END
GO

CREATE PROC GP_Check_MonthEnd_NeedCostCompute
(
	 @STypeID VARCHAR(100)=''
)
AS
BEGIN
    DECLARE @StartDate DATETIME ,
			@Count INT
    SELECT  @StartDate = StartDate
    FROM    dbo.MonthProc
    WHERE   MonthNo = '本期' AND STypeID=@STypeID
    
    IF @StartDate IS NULL
    BEGIN
		SELECT @StartDate=MIN(StartDate) FROM MonthProc WHERE	Monthno = '本期'
    END
	
	IF NOT EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillDate>=@StartDate AND ifcheck='t' AND IsIni=0 AND RedWord=0 
				  AND STypeID=@STypeID
				  UNION ALL
				  SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillDate>=@StartDate AND ifcheck='t' AND IsIni=0 AND RedWord=0 
				  AND STypeID=@STypeID
				  )
		RETURN 0
	
	;WITH CTE
	AS
	(SELECT  PTypeID ,
            STypeID ,
            PostTime ,
            BillNumberId,
            BillType,
            MAX(ISNULL(DealTime,'1-1-1 00:00:00')) AS DealTime
    FROM    dbo.CostReLog
    WHERE STypeID=@STypeID
    GROUP BY PTypeID ,
             STypeID ,
             PostTime,
             BillNumberID,
             BillType
	)
	
    SELECT  @Count = COUNT(1)
    FROM    ( SELECT    
						A.BillNumberId,
						A.BillType,
                        ISNULL(B.LastUpdateTime,A.PostTime) AS PosTTime ,
                        A.PTypeID ,
                        A.STypeID,
						A.BillDate
              FROM      dbo.CostRe_Bill A 
              INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND A.BillType=B.BillType
              WHERE     A.BillType IN ( 34, 11, 45, 6, 160, 161, 9, 14, 57,
                                      17, 21, 187, 188, 201, 202, 16, 139,
                                      126, 305, 400, 401, 402, 403, 404 )
                        AND A.Stypeid=@STypeID
              /*
              UNION ALL
              SELECT    
						MIN(A.BillNumberId) AS BillNumberID,
						A.BillType,
                        A.PostTime ,
                        A.PTypeID ,
                        A.STypeID,
						A.BillDate
              FROM      Inoutstocktable  A
              INNER JOIN dbo.BillIndex B 
              ON A.BillNumberId=B.BillNumberId AND A.BillType=B.BillType AND B.RedWord=2
              WHERE     IsService = 0
                        AND Audited = 0
                        AND B.STypeID=@STypeID
                        AND A.BillType IN ( 34, 11, 45, 6, 160, 161, 9, 14,
                                          57, 17, 21, 187, 188, 201, 202,
                                          16, 139, 126, 305, 400, 401, 402,
                                          403, 404, 140, 142, 146, 183,
                                          174, 168, 172, 173 )
              GROUP BY 	A.BillType,
                        A.PostTime ,
                        A.PTypeID ,
                        A.STypeID,
                        A.BillDate
              UNION
              SELECT    
						a.BillNumberID,
						a.BillType,
                        b.PostTime ,
                        a.PTypeID ,
                        a.STypeID,
                        B.BillDate
              FROM      ReceiptBill a
                        INNER JOIN ReceiptBillIndex b ON a.BillNumberID = b.BillNumberID
              WHERE     a.BillType = 404
                        AND b.RedWord = 2
                        AND a.Stypeid=@STypeID
              */
            ) A
            
    WHERE   A.BillDate >= @StartDate
            AND (NOT EXISTS(SELECT 1 FROM CTE B WHERE B.PTypeID=A.PTypeID AND B.DealTime>A.PostTime)
				AND NOT EXISTS(SELECT 1 FROM (
					SELECT PTypeID,STypeID,MAX(DealTime) AS DealTime FROM Cost_NoReLog
					GROUP By PTypeID,STypeID
				) B WHERE A.PTypeID=B.PTypeID AND A.STypeID=B.STypeID AND B.DealTime>A.PostTime)
            )
    IF ISNULL(@Count, 0) = 0
        RETURN 0
    ELSE
        RETURN -1
END
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CheckAccountUsage]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CheckAccountUsage] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2012-06-14
----描述：检查会计科目是否使用
----========================
CREATE    PROCEDURE [dbo].[GP_CheckAccountUsage]
(
    @stypeid VARCHAR(50),
    @atypeid VARCHAR(50)
)
--@encode$--
AS 


----V3标示
DECLARE @ISv3 INT SET @ISv3=(SELECT  SubValue FROM sysdata WHERE SubName='ProInfo'  )

IF @stypeid='00000' AND @ISv3<>1
BEGIN
	IF EXISTS (SELECT 1 FROM AC_ACCOUNT WHERE stypeid > '00000' and typeid = @atypeid AND isdist = 1)
	    RETURN  1
	
	RETURN 0
END

DECLARE @isUsed INT
SET @isUsed = 0

SELECT  t.name AS tableName, c1.colname AS ColA,
        c2.colname AS ColS
INTO #t1
FROM    sys.tables t
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'atypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'atypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c1 ON c1.tblname = t.name
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'stypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'stypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c2 ON c2.tblname = t.name
WHERE   t.name NOT IN (
-- 引用科目设置
'BillAtype',
'Ac_Account_Assist_CheckItems',
-- 总长科目单独判断
'Ac_Balance','Ac_Balance_Assist_CheckItems','Ac_Balance_Assist_CheckItems_Detail','Ac_IniAccount','Ac_IniAccount_Assist_CheckItems','Ac_IniAccount_Assist_CheckItems_Detail','Ac_ProfitAndLoss','Ac_ProfitAndLoss_Detail','Ac_Voucher_Bill','Ac_Voucher_Bill')
--UNION ALL SELECT 'SType','atypeid','typeid'
--UNION ALL SELECT 'SType','atypeid2','typeid'
--UNION ALL SELECT 'SType','atypeid3','typeid'
--UNION ALL SELECT 'SType','atypeid4','typeid'
UNION ALL SELECT 'Ac_Items_Detail','DEPATYPEID','stypeid'
UNION ALL SELECT 'Ac_Items_Detail','DISATYPEID','stypeid'
UNION ALL SELECT 'Ac_Items_Detail','atypeid','stypeid'
UNION ALL SELECT '#Ac_Auditing_Template','atypeid','stypeid'
UNION ALL SELECT 'Ac_AssetsCards','AssertATypeId','stypeid'
UNION ALL SELECT 'Ac_AssetsCards','DepATypeId','stypeid'
UNION ALL SELECT 'Ac_AssetsCards','DisATypeId','stypeid'
UNION ALL SELECT 'Ac_AssetsCards','DevalueATypeId','stypeid'
ORDER BY TableName


SELECT Stypeid,atypeid 
INTO #Ac_Auditing_Template
FROM Ac_Auditing_Template t
JOIN Ac_Auditing_Template_Detail d ON d.Atid = t.AtId

SELECT IDENTITY(INT,1,1) AS rid ,*
INTO #t2
FROM #t1
------过滤无关表-------
IF  EXISTS (SELECT * FROM #t2 WHERE tableName='AccountCredence')
DELETE #t2  WHERE tableName='AccountCredence'
IF  EXISTS (SELECT * FROM #t2 WHERE tableName='Ac_Voucher_Bill_Backup')
DELETE #t2  WHERE tableName='Ac_Voucher_Bill_Backup'
IF  EXISTS (SELECT * FROM #t2 WHERE tableName='Ac_Voucher_Bill_Log')
DELETE #t2  WHERE tableName='Ac_Voucher_Bill_Log'

DECLARE @i INT
DECLARE @count INT
DECLARE @tbname NVARCHAR(200)
DECLARE @colaname NVARCHAR(200)
DECLARE @colsname NVARCHAR(200)
DECLARE @sql NVARCHAR(2000)

SELECT @count = COUNT(1) FROM #t1

SET @i = 1

WHILE @i <= @count AND @isUsed = 0
BEGIN 
        SELECT @tbname = TableName,@colaname=cola,@colsname = cols
        FROM #t2
        WHERE rid = @i
        
        SET @sql = 'SELECT @isUsed = Count(1) FROM '
                + @tbname + ' WHERE ' + @colaname
                + ' =  ''' + @ATypeId + ''''
                + ' AND ' + @colsname + ' = '''
                + @STypeId + ''''
                        
        EXECUTE sp_executesql @SQL,
            N'@isUsed INT OUTPUT', @isUsed OUTPUT
    
    SET @i += 1
END

DROP TABLE #t1,#t2,#Ac_Auditing_Template

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + @tbname + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [' + @colsname + '], ''
    ' + @ATypeId + ''' AS [' + @colaname + ']'
    
    EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FBEGINBALANCE, 0)) +
        ABS(ISNULL(FDebit, 0)) +
        ABS(ISNULL(FCredit, 0)) + 
        ABS(ISNULL(FENDBALANCE, 0)) +
        ABS(ISNULL(FYTDDEBIT, 0)) +
        ABS(ISNULL(FYTDCREDIT, 0))+
        ABS(ISNULL(FBeginqty, 0)) +
        ABS(ISNULL(FDebitqty, 0)) +
        ABS(ISNULL(FCreditqty, 0))  +
        ABS(ISNULL(FEndqty, 0)) +
        ABS(ISNULL(FYtdDebitqty, 0)) +
        ABS(ISNULL(FYtdCreditqty, 0)) > 0


IF @isUsed > 0
BEGIN
    PRINT 'TABLE [] IS USING Account ['+@STypeId+','+@ATypeId+'].'
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Balance' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance_Assist_CheckItems
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(iniYTotal, 0)) + 
        ABS(ISNULL(FDebit, 0)) +
        ABS(ISNULL(FCredit, 0)) + 
        ABS(ISNULL(iniTotal, 0)) +
        ABS(ISNULL(FEndBalance, 0)) +  
        ABS(ISNULL(IniYqty, 0))+ 
        ABS(ISNULL(FDebitqty, 0))+ 
        ABS(ISNULL(FCreditqty, 0))+ 
        ABS(ISNULL(Iniqty, 0))+ 
        ABS(ISNULL(FEndqty, 0))> 0
 
 
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Balance_Assist_CheckItems' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) +
        ABS(ISNULL(INITOTAL,0)) +
        ABS(ISNULL(FEndBalance,0))+
        ABS(ISNULL(Iniqty,0))+
        ABS(ISNULL(FDebitqty,0))+
        ABS(ISNULL(FCreditqty,0))+
        ABS(ISNULL(FEndqty,0))> 0
 
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Balance_Assist_CheckItems_Detail' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END
    
--	Ac_IniAccount
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(iniTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(iniYTotal,0)) + 
        ABS(ISNULL(FYTotal,0))+
        ABS(ISNULL(iniqty,0))+
        ABS(ISNULL(FDebitqty,0))+
        ABS(ISNULL(FCreditqty,0))+
        ABS(ISNULL(IniYqty,0))> 0

 
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END
      
--	Ac_IniAccount_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(IniYTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(IniTotal,0)) +
        ABS(ISNULL(FYTotal,0))+
        ABS(ISNULL(IniYqty,0)) +
        ABS(ISNULL(FDebitqty,0)) +
        ABS(ISNULL(FCreditqty,0)) +
        ABS(ISNULL(Iniqty,0)) > 0

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount_Assist_CheckItems' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END      
  
--	Ac_IniAccount_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(IniYTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(IniTotal,0)) +
        ABS(ISNULL(FYTotal,0)) +
        ABS(ISNULL(IniYqty,0)) +
        ABS(ISNULL(FDebitqty,0)) +
        ABS(ISNULL(FCreditqty,0))  +
        ABS(ISNULL(iniqty,0))> 0

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount_Assist_CheckItems_Detail' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END             
        
--	Ac_ProfitAndLoss
SELECT TOP 1
        @isused += 1
FROM    Ac_ProfitAndLoss
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FFTotal,0)) + 
        ABS(ISNULL(FYTOTAL,0)) > 0

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_ProfitAndLoss' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END          
        
--	Ac_ProfitAndLoss_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_ProfitAndLoss_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FFTotal,0)) + 
        ABS(ISNULL(FYTOTAL,0)) > 0
        
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_ProfitAndLoss_Detail' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END        
        
--	Ac_Voucher_Bill
SELECT TOP 1
        @isused += 1
FROM    Ac_Voucher_Bill
WHERE   STypeid = @stypeid
        AND @atypeid in (ATypeId,ATypeId2)
        AND ABS(ISNULL(FDebitTotal,0)) + 
        ABS(ISNULL(FCreditTotal,0)) + 
        ABS(ISNULL(FDebitQty,0))  + 
        ABS(ISNULL(FCreditQty,0))> 0
        
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Voucher_Bill' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END     
        
RETURN 0

GO


SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CheckAccountUsage_Dataupdate]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CheckAccountUsage_Dataupdate] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：董湛
----日期：2013-07-01
----描述：copy [GP_CheckAccountUsage],，防止6001QpErp20之前预制数据.sql中的代码出现查询结果
----========================
CREATE    PROCEDURE [dbo].[GP_CheckAccountUsage_Dataupdate]
(
    @stypeid VARCHAR(50),
    @atypeid VARCHAR(50)
)
--@encode$--
AS 


----V3标示
DECLARE @ISv3 INT SET @ISv3=(SELECT  SubValue FROM sysdata WHERE SubName='ProInfo'  )

IF @stypeid='00000' AND @ISv3<>1
BEGIN
	IF EXISTS (SELECT 1 FROM AC_ACCOUNT WHERE stypeid > '00000' and typeid = @atypeid AND isdist = 1)
	    RETURN  1
	
	RETURN 0
END



DECLARE @isUsed INT
SET @isUsed = 0

SELECT  t.name AS tableName, c1.colname AS ColA,
        c2.colname AS ColS
INTO #t1
FROM    sys.tables t
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'atypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'atypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c1 ON c1.tblname = t.name
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'stypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'stypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c2 ON c2.tblname = t.name
WHERE   t.name NOT IN (
-- 引用科目设置
'BillAtype',
'Ac_Account_Assist_CheckItems',
-- 总长科目单独判断
'Ac_Balance','Ac_Balance_Assist_CheckItems','Ac_Balance_Assist_CheckItems_Detail','Ac_IniAccount','Ac_IniAccount_Assist_CheckItems','Ac_IniAccount_Assist_CheckItems_Detail','Ac_ProfitAndLoss','Ac_ProfitAndLoss_Detail','Ac_Voucher_Bill','Ac_Voucher_Bill')
--UNION ALL SELECT 'SType','atypeid','typeid'
--UNION ALL SELECT 'SType','atypeid2','typeid'
--UNION ALL SELECT 'SType','atypeid3','typeid'
--UNION ALL SELECT 'SType','atypeid4','typeid'
UNION ALL SELECT 'Ac_Items_Detail','DEPATYPEID','stypeid'
UNION ALL SELECT 'Ac_Items_Detail','DISATYPEID','stypeid'
UNION ALL SELECT '#Ac_Auditing_Template','atypeid','stypeid'
ORDER BY TableName


SELECT Stypeid,atypeid 
INTO #Ac_Auditing_Template
FROM Ac_Auditing_Template t
JOIN Ac_Auditing_Template_Detail d ON d.Atid = t.AtId

SELECT IDENTITY(INT,1,1) AS rid ,*
INTO #t2
FROM #t1
------过滤无关表-------
IF  EXISTS (SELECT * FROM #t2 WHERE tableName='AccountCredence')
DELETE #t2  WHERE tableName='AccountCredence'


DECLARE @i INT
DECLARE @count INT
DECLARE @tbname NVARCHAR(200)
DECLARE @colaname NVARCHAR(200)
DECLARE @colsname NVARCHAR(200)
DECLARE @sql NVARCHAR(2000)

SELECT @count = COUNT(1) FROM #t1

SET @i = 1

WHILE @i <= @count AND @isUsed = 0
BEGIN 
        SELECT @tbname = TableName,@colaname=cola,@colsname = cols
        FROM #t2
        WHERE rid = @i
        
        SET @sql = 'SELECT @isUsed = Count(1) FROM '
                + @tbname + ' WHERE ' + @colaname
                + ' =  ''' + @ATypeId + ''''
                + ' AND ' + @colsname + ' = '''
                + @STypeId + ''''
                        
        EXECUTE sp_executesql @SQL,
            N'@isUsed INT OUTPUT', @isUsed OUTPUT
    
    SET @i += 1
END

DROP TABLE #t1,#t2,#Ac_Auditing_Template

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + @tbname + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [' + @colsname + '], ''
    ' + @ATypeId + ''' AS [' + @colaname + ']'
    
    --EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FBEGINBALANCE, 0)) +
        ABS(ISNULL(FDebit, 0)) +
        ABS(ISNULL(FCredit, 0)) + 
        ABS(ISNULL(FENDBALANCE, 0)) +
        ABS(ISNULL(FYTDDEBIT, 0)) +
        ABS(ISNULL(FYTDCREDIT, 0)) > 0


IF @isUsed > 0
BEGIN
    PRINT 'TABLE [] IS USING Account ['+@STypeId+','+@ATypeId+'].'
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Balance' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance_Assist_CheckItems
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(iniYTotal, 0)) + 
        ABS(ISNULL(FDebit, 0)) +
        ABS(ISNULL(FCredit, 0)) + 
        ABS(ISNULL(iniTotal, 0)) > 0
 
 
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Balance_Assist_CheckItems' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) +
        ABS(ISNULL(INITOTAL,0)) > 0
 
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Balance_Assist_CheckItems_Detail' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END
    
--	Ac_IniAccount
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(iniTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(iniYTotal,0)) + 
        ABS(ISNULL(FYTotal,0)) > 0

 
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END
      
--	Ac_IniAccount_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(IniYTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(IniTotal,0)) +
        ABS(ISNULL(FYTotal,0)) > 0

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount_Assist_CheckItems' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END      
  
--	Ac_IniAccount_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(IniYTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(IniTotal,0)) +
        ABS(ISNULL(FYTotal,0)) > 0

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount_Assist_CheckItems_Detail' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END             
        
--	Ac_ProfitAndLoss
SELECT TOP 1
        @isused += 1
FROM    Ac_ProfitAndLoss
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FFTotal,0)) + 
        ABS(ISNULL(FYTOTAL,0)) > 0

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_ProfitAndLoss' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END          
        
--	Ac_ProfitAndLoss_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_ProfitAndLoss_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FFTotal,0)) + 
        ABS(ISNULL(FYTOTAL,0)) > 0
        
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_ProfitAndLoss_Detail' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END        
        
--	Ac_Voucher_Bill
SELECT TOP 1
        @isused += 1
FROM    Ac_Voucher_Bill
WHERE   STypeid = @stypeid
        AND @atypeid in (ATypeId,ATypeId2)
        AND ABS(ISNULL(FDebitTotal,0)) + 
        ABS(ISNULL(FCreditTotal,0)) > 0
        
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Voucher_Bill' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END     
        
RETURN 0

GO


SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- 2006-04-06 
-- modify by cqhua
-- 调价单比较账面成本价和单据成本价
CREATE                 PROCEDURE GP_CheckAllotPrice
(
@BillnumberID Int,
@intRow  int output,  --行数
@intPrice  NUMERIC(24, 10)  output   , --单价
@intCostPrice  NUMERIC(24, 10)  output, --成本单价
@strBillCode varchar(200) output --单据编号
)
--@encode$--
As
SET NOCOUNT ON 
DECLARE @chvPtypeId	varchar(100)
DECLARE @chvKtypeId varchar(100)
DECLARE @decQty		 NUMERIC(24, 10) 
DECLARE @Price		 NUMERIC(24, 10) 
DECLARE @CostPrice		 NUMERIC(24, 10) 
DECLARE @intCosting	int


SELECT @strBillCode =Billcode FROM Billindex where BillnumberID = @BillnumberID
DECLARE @intRows  int -- 最小行数
SELECT @intRows =Min([ID]) FROM MoveBill where BillnumberID = @BillnumberID
DECLARE @intID   int-- 行数
-- 成本算法
SELECT @intCosting = subValue FROM sysdata   WHERE SubName='costing'
SELECT @chvKtypeId = KtypeID FROM  Billindex WHERE BillnumberID = @BillnumberID

DECLARE @SQL varchar(6000)
SET @SQL =' DECLARE Rows_Cursor  Cursor FOR  
		SELECT PtypeID,Qty,Price,[ID] 
		FROM MoveBill 
		WHERE BillnumberID= '+Convert(varchar(20),@BillnumberID)

EXEC(@SQL)

OPEN Rows_Cursor
FETCH NEXT FROM Rows_Cursor INTO @chvPtypeId,@decQty,@Price,@intID
WHILE @@FETCH_STATUS = 0 
BEGIN
	EXEC Web_CalculateCostPrice1 @chvPtypeId,@chvKtypeId,@decQty,@intCosting ,@CostPrice OUTPUT
	IF abs(@CostPrice-@Price)>0.01 -- 单价与成本单价不等
	BEGIN
		SET @intRow = @intID + 1 - @intRows
		SET @intPrice = @Price
		SET @intCostPrice = @CostPrice
		RETURN  -1
	END
	FETCH NEXT FROM Rows_Cursor INTO @chvPtypeId,@decQty,@Price,@intID
END
CLOSE Rows_Cursor	-- 关闭游标
DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_CheckAllowTransfer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_CheckAllowTransfer
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2013-05-10
-- Description: 检查是否可以进行数据转移
-- =============================================
CREATE PROCEDURE Gp_CheckAllowTransfer
(
	@CareFinanceDataCheck	INT ,	--是否关心财务数据。3:完全不关心；2:不关心验证；1：关心
	@ReturnValue	VARCHAR(max) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @startdate DATETIME,@fperiod INT,@fyear INT
IF EXISTS (SELECT * FROM SysData WHERE SubName = 'inicanmodify' and SubValue = 'T')
BEGIN
	SET @ReturnValue='系统处于期初建账，正等待系统开账,不能数据结转！'
	RETURN
END

IF EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype) 
	AND (EXISTS(SELECT 1 FROM (SELECT 1 AS a FROM Ac_AccountsPeroid_Stype WHERE IsUse = 1 GROUP BY fperiod,fyear)a HAVING COUNT(1)>1)
	OR EXISTS(SELECT 1 FROM dbo.SType s WHERE IsSelfVerify=1 AND TypeId NOT IN (SELECT stypeid FROM Ac_AccountsPeroid_Stype) AND EXISTS(SELECT 1 FROM dbo.SType_UserConfig WHERE StypeId=s.TypeId AND ConfigNo=1 AND Value=1)))
BEGIN
	SET @ReturnValue='存在不在同一期间的分支机构，请进行处理后再执行结转操作'
	RETURN
END


SELECT TOP 1 @fperiod=fperiod,@fyear=FYear FROM dbo.Ac_AccountsPeroid_Stype WHERE IsUse = 1
IF @fperiod IS NULL
BEGIN
	SELECT @fperiod=SubValue FROM dbo.sysdata WHERE SubName='Fmonth' 
	SELECT @fyear=SubValue FROM dbo.sysdata WHERE SubName='FYear' 
END

--检查年结期间往后是否还存在已记账凭证
IF @CareFinanceDataCheck < 3 AND EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE IfCheck = 't' AND FChecked <> -1 AND ((FYear = @FYear AND FPeriod > @FPeriod) OR FYear > @FYear))
BEGIN
	SET @ReturnValue='年结期间后面有已记账凭证，不能进行数据结转！'
	RETURN
END

IF @CareFinanceDataCheck>1 RETURN ''

IF EXISTS(SELECT 1 FROM dbo.Ac_Voucher WHERE FPeriod = @fperiod AND FYear=@fyear)
BEGIN
	SET @ReturnValue='当前会计期间存在会计凭证，不能进行数据结转'
	RETURN
END


SELECT @startdate =FBegin FROM dbo.Ac_Period WHERE FPeriod = @fperiod AND FYear=@fyear
IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubValue=1 AND SubName='IsUseAcSystem') AND NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='aloneusebsys' AND SubValue=1) 
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillDate>=@startdate AND draft=0 AND IsIni=0 AND RedWord=0 AND ifYearBill=0
			  UNION ALL 
			  SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillDate>=@startdate AND draft=0 AND IsIni=0 AND RedWord=0 AND ifYearBill=0
			  UNION ALL 
			  SELECT 1 FROM dbo.Coupon_BillIndex WHERE BillDate>=@startdate AND draft=0 AND IsIni=0 AND RedWord=0 AND ifYearBill=0
			  UNION ALL 
			  SELECT 1 FROM dbo.PosAllotApplyBillIndex WHERE BillDate>=@startdate AND draft=0 AND IsIni=0 AND RedWord=0 AND ifYearBill=0
			  )
	BEGIN
		SET @ReturnValue='本期开始时间以后还有已过账业务单据存在未生成凭证的情况，不能进行数据结转'
		RETURN
	END
	
	SELECT	ps.Stypeid
			,p.FBegin
	INTO #stype_SFBegin
	FROM dbo.Ac_AccountsPeroid_Stype ps 
	INNER JOIN dbo.Ac_Period p ON p.FYear = ps.SFYear AND p.FPeriod = ps.SFPeriod
	
	IF   EXISTS(SELECT 1 FROM billindex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate 
				WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 
				AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND (InOutType = -1 OR InOutType = 1)) 
				AND BillType = 310
			)
	BEGIN
		SET @ReturnValue='存在未生成凭证的单据，不能进行数据结转'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM billindex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 
			AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId)
			AND ((BillType IN (11,45,160,305,139,140,142,141,34,6,161,126,144,146,145,21,187,188,201,202,9,14,16,116,115,128,129,4,189,66,190,148,
								 150,149,151,36,84,85,78,158,77,93,5,10,57,205,181,183,166,167,168,170,172,173,174,12,46,215,147,450,312,427) AND totalmoney>0 )
					OR	(BillType = 414 AND IsFreightMoney = 1)
					OR b.BillType = 159)
			)
	BEGIN
		SET @ReturnValue='存在未生成凭证的单据，不能进行数据结转'
		RETURN
	END
	IF EXISTS (SELECT 1 FROM dbo.sysdata WHERE SubName='isinvoice') AND EXISTS (SELECT 1 FROM dbo.ReceiptBillIndex B INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE Draft=0 AND RedWord=0 AND IsIni=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS (SELECT 1 FROM dbo.Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberID) AND TotalMoney<>0)
	BEGIN 
		SET @ReturnValue='存在未生成凭证的单据，不能进行数据结转'
		RETURN
	END
	
	IF   EXISTS(SELECT 1 FROM billindex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) AND BillType IN (305,215,11,45,160,141,405,12,46) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='存在未生成基本凭证的出库类单据，不能进行数据结转'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM billindex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='存在未生成成本凭证的出库类单据，不能进行数据结转'
		RETURN
	END
	
	IF   EXISTS(SELECT 1 FROM ReceiptBillIndex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) AND BillType IN (305,215,11,45,160,141,405,12,46) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='存在未生成基本凭证的出库类单据，不能进行数据结转'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM ReceiptBillIndex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='存在未生成成本凭证的出库类单据，不能进行数据结转'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM Coupon_BillIndex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_CouponBill_VoucherBill WHERE CouponBillId=b.BillNumberId ) AND BillType IN (423,424,426,428,429) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='存在未生成凭证的优惠券分支机构调拨类单据，不能进行数据结转'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM dbo.PosAllotApplyBillIndex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_DeliveryBill_VoucherBill WHERE DeliveryBillId=b.BillNumberId ) AND BillType IN (327,328,329) AND Total>0)
	BEGIN
		SET @ReturnValue='存在未生成凭证的门店配送类单据，不能进行数据结转'
		RETURN
	END

	DROP TABLE #stype_SFBegin
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_CheckAllowTransfer_DateTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_CheckAllowTransfer_DateTime
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2013-05-10
-- Description: 检查是否可以进行数据转移
-- =============================================
CREATE PROCEDURE Gp_CheckAllowTransfer_DateTime
(
	@CareFinanceDataCheck	INT ,	--是否关心财务数据。3:完全不关心；2:不关心验证；1：关心
	@ClearNoNompleteOnshelves			INT=0,		--清除未完成上架单
	@ClearNoCompletePickAndTransport	INT=0,		--清除未完成拣货/运输配送单
	@yearendDatetime		VARCHAR(20)	,		--   -年结存的日期	
	@ReturnValue	VARCHAR(max) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

/*===============================================================================================*/
IF EXISTS (SELECT * FROM SysData WHERE SubName = 'inicanmodify' and SubValue = 'T')
BEGIN
	SET @ReturnValue='系统处于期初建账，正等待系统开账，不能按指定日期进行年结存！'
	RETURN
END

/*-----------------------------------------------------------------------------------------------*/
/*===============================================================================================*/

DECLARE @UseOnShelves INT,		--启用上架
		@UsePickgoods INT,		--启用拣货
		@UseTransport INT		--启用运输

SELECT @UseOnShelves=SubValue FROM dbo.sysdata WHERE SubName='UseOnShelves'
SELECT @UsePickgoods=SubValue FROM dbo.sysdata WHERE SubName='UsePickgoods'
SELECT @UseTransport=SubValue FROM dbo.sysdata WHERE SubName='UseTransport'

IF @UseOnShelves=1 AND @ClearNoNompleteOnshelves=0
BEGIN
	--期初单据不做上架,排除期初单据AND IsIni<>1
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillDate < @yearendDatetime AND BIlLType IN(215,45,160,142,34,161,126,144,17,21,188,201,16,400,403) AND ifcheck='t' AND RedWord=0 AND ShelveState<>2 AND IsIni<>1)
	BEGIN
		SET @ReturnValue = '在<指定年结存日期>之前，系统中存在未上架完成入库单据，不能按指定日期进行年结存'
		RETURN
	END
END

IF @UsePickgoods=1 AND @ClearNoCompletePickAndTransport=0
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillDate < @yearendDatetime AND BilLType IN(11,12,160,139,140,6,161,146,17,21,187,202,16,183,401,402) AND ifcheck='t' AND RedWord=0 AND progressstate<>2 AND IsIni<>1)
	BEGIN
		SET @ReturnValue = '在<指定年结存日期>之前，系统中存在未拣货完成出库单据，不能按指定日期进行年结存'
		RETURN
	END
END
IF @UseTransport=1 AND @ClearNoCompletePickAndTransport=0
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillDate < @yearendDatetime AND BillType IN(11,12,160,139,140,6,161,146,17,21,187,202,16,183,401,402) 
				AND ifcheck='t' AND RedWord=0 AND TransPortState<>2 AND IsNeedTransport=1 AND IsIni<>1)
	BEGIN
		SET @ReturnValue = '在<指定年结存日期>之前，系统中存在未发货完成出库单据，不能按指定日期进行年结存'
		RETURN
	END
END

/*-----------------------------------------------------------------------------------------------*/
DECLARE @startdate DATETIME,@fperiod INT,@fyear INT
SELECT @FPeriod=FPeriod,@FYear=FYear 
FROM dbo.Ac_Period 
WHERE FBegin = @yearendDatetime

/*-----------------------------------------------------------------------------------------------*/
IF EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype) 
	AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
	AND (
			EXISTS(SELECT 1 FROM  Ac_AccountsPeroid_Stype WHERE IsUse = 1 AND ((FPeriod < @fperiod AND FYear = @fyear) OR FYear < @fyear))
		 OR EXISTS(	SELECT 1 FROM dbo.SType s 
					WHERE IsSelfVerify=1 
					AND TypeId NOT IN (SELECT stypeid FROM Ac_AccountsPeroid_Stype) 
					AND EXISTS(SELECT 1 FROM dbo.SType_UserConfig WHERE StypeId=s.TypeId AND ConfigNo=1 AND Value=1)
				  )
		)
BEGIN
	IF EXISTS(select TOP 1 1 from sysdata where subname='proinfo' AND SubValue = 2 )
		SET @ReturnValue='有分支机构所处期间在<指定年结存日期>对应期间('+CAST(@fyear AS VARCHAR)+'-'+CAST(@fperiod AS VARCHAR)+')之前，不能按指定日期进行年结存'
	ELSE	
		SET @ReturnValue='当前系统所处期间在<指定年结存日期>对应期间('+CAST(@fyear AS VARCHAR)+'-'+CAST(@fperiod AS VARCHAR)+')之前，不能按指定日期进行年结存'
	
	RETURN
END
/*-----------------------------------------------------------------------------------------------*/

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'StypeIndependentOpen' AND SubValue = 0) 
AND EXISTS(SELECT TOP 1 1 FROM Te_StartPeriod b JOIN Te_Period c ON b.STypeId=c.STypeId WHERE b.IsConnect=1 AND ((c.FPeriod < @fperiod AND c.FYear = @fyear) OR c.FYear < @fyear))
BEGIN
	IF EXISTS(select TOP 1 1 from sysdata where subname='proinfo' AND SubValue = 2 )
		SET @ReturnValue = '有联用分支机构的出纳系统所处期间在<指定年结存日期>对应期间('+CAST(@fyear AS VARCHAR)+'-'+CAST(@fperiod AS VARCHAR)+')之前，不能按指定日期进行年结存'
	ELSE	
		SET @ReturnValue='当前系统的联用出纳系统所处期间在<指定年结存日期>对应期间('+CAST(@fyear AS VARCHAR)+'-'+CAST(@fperiod AS VARCHAR)+')之前，不能按指定日期进行年结存'
	RETURN
END 

IF EXISTS(SELECT TOP 1 1 FROM billindex WHERE BillDate < @yearendDatetime AND billtype=310 AND IfConfirm=0 AND draft=0 AND RedWord=0 )
BEGIN
	SET @ReturnValue = '在<指定年结存日期>之前，存在未处理完的资金调拨单，不能按指定日期进行年结存'
	RETURN
END

/*===============================================================================================*/

SELECT cb.FromBillNumberid,cb.FromBillType INTO #chargeoffbill 
FROM chargeoffbill cb 
INNER JOIN dbo.BillIndex b ON b.BillNumberId = cb.BillNumberId 
WHERE b.BillDate >= @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0

IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex b INNER JOIN #chargeoffbill c ON c.FromBillNumberid = b.BillNumberId AND c.FromBillType = b.BillType 
	WHERE b.BillDate < @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0) OR
	EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex b INNER JOIN #chargeoffbill c ON c.FromBillNumberid = b.BillNumberId AND c.FromBillType = b.BillType 
	WHERE b.BillDate < @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0) OR
	EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_BillIndex b INNER JOIN #chargeoffbill c ON c.FromBillNumberid = b.BillNumberId AND c.FromBillType = b.BillType 
	WHERE b.BillDate < @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0)
BEGIN
	DROP TABLE #chargeoffbill
	SET @ReturnValue = '有业务单据被<指定年结存日期>之后的往来核销单引用，不能按指定日期进行年结存'
	RETURN
END

/*===============================================================================================*/
TRUNCATE TABLE #chargeoffbill

INSERT INTO #chargeoffbill( FromBillNumberid, FromBillType )
SELECT cb.BillNumberId,cb.BillType 
FROM (
	SELECT b.BillNumberId,b.BillType FROM dbo.BillIndex b 
	WHERE b.BillDate >= @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0 
	UNION ALL
	SELECT b.BillNumberId,b.BillType FROM dbo.ReceiptBillIndex b  
	WHERE b.BillDate >= @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0 
	UNION ALL
	SELECT b.BillNumberId,b.BillType FROM dbo.Coupon_BillIndex b 
	WHERE b.BillDate >= @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0
) cb

IF EXISTS(	SELECT TOP 1 1 FROM dbo.ChargeOffBill cb 
			INNER JOIN dbo.BillIndex b ON b.BillNumberId = cb.BillNumberId 
			INNER JOIN #chargeoffbill c ON c.FromBillNumberid = cb.FromBillNumberid AND c.FromBillType = cb.FromBillType  
			WHERE b.BillDate < @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0)
BEGIN
	DROP TABLE #chargeoffbill
	SET @ReturnValue = '有往来核销单引用了<指定年结存日期>之后的业务单据，不能按指定日期进行年结存'
	RETURN
END

DROP TABLE #chargeoffbill

/*-----------------------------------------------------------------------------------------------*/
SELECT cb.FromBillNumberid,cb.FromBillType INTO #sharesourcebill 
FROM sharesourcebill cb 
INNER JOIN dbo.BillIndex b ON b.BillNumberId = cb.BillNumberId 
WHERE b.BillDate >= @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0

INSERT INTO #sharesourcebill( FromBillNumberID, FromBillType )
SELECT cb.FromBillNumberID,36 FROM ShareFeeBill cb 
INNER JOIN dbo.BillIndex b ON b.BillNumberId = cb.BillNumberId 
WHERE b.BillDate >= @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0

IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex b INNER JOIN #sharesourcebill c ON c.FromBillNumberid = b.BillNumberId AND c.FromBillType = b.BillType 
	WHERE b.BillDate < @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0) 
BEGIN
	DROP TABLE #sharesourcebill
	SET @ReturnValue = '有业务单据被<指定年结存日期>之后的费用分摊单引用，不能按指定日期进行年结存'
	RETURN
END

/*===============================================================================================*/
TRUNCATE TABLE #sharesourcebill

INSERT INTO #sharesourcebill( FromBillNumberid, FromBillType )
SELECT cb.BillNumberId,cb.BillType 
FROM (
	SELECT b.BillNumberId,b.BillType FROM dbo.BillIndex b 
	WHERE b.BillDate >= @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0 
) cb

IF EXISTS(	SELECT TOP 1 1 FROM dbo.sharesourcebill cb 
			INNER JOIN dbo.BillIndex b ON b.BillNumberId = cb.BillNumberId 
			INNER JOIN #sharesourcebill c ON c.FromBillNumberid = cb.FromBillNumberid AND c.FromBillType = cb.FromBillType  
			WHERE b.BillDate < @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0) OR
	EXISTS(	SELECT TOP 1 1 FROM dbo.sharefeebill cb 
			INNER JOIN dbo.BillIndex b ON b.BillNumberId = cb.BillNumberId 
			INNER JOIN #sharesourcebill c ON c.FromBillNumberid = cb.FromBillNumberid   
			WHERE b.BillDate < @yearendDatetime AND b.ifcheck = 't' AND b.RedWord = 0)
BEGIN
	DROP TABLE #sharesourcebill
	SET @ReturnValue = '有费用分摊单引用了<指定年结存日期>之后的业务单据，不能按指定日期进行年结存'
	RETURN
END

DROP TABLE #sharesourcebill

/*-----------------------------------------------------------------------------------------------*/
--直接绕开序列号的检测  谢吉康 991 2020-01-16
IF 1 = 0
BEGIN
	SELECT Serial,COUNT(1) AS instock INTO #inSerial 
	FROM (  SELECT i.Serial 
		FROM dbo.gp_inoutPtypeSerial i 
		INNER JOIN dbo.BillIndex b ON b.BillNumberId = i.BillNumberid 
		WHERE b.IfCheck = 't' AND b.RedWord = 0 AND i.BillType NOT IN(71,87,88,72,203) AND i.[State] IN('1','7') AND b.BillDate < @yearendDatetime
		UNION ALL
		SELECT Serial FROM dbo.gp_initPtypeSerial 
		UNION ALL
		SELECT REPLACE(s.Serial ,'я','')Serial
		FROM dbo.serialadjustbill s 
		INNER JOIN SerialAdjustIndex  t ON t.BillNumberId=s.BillNumberId
		WHERE t.IfCheck = 't' AND t.RedWord = 0 AND t.BillDate < @yearendDatetime

	  ) t
	GROUP BY Serial

	SELECT Serial,COUNT(1) AS outstock INTO #outSerial 
	FROM (  
	        
		SELECT i.Serial 
		FROM  dbo.gp_inoutPtypeSerial i 
		INNER JOIN dbo.BillIndex b ON b.BillNumberId = i.BillNumberid 
		WHERE  b.IfCheck = 't' AND b.RedWord = 0 AND i.BillType NOT IN(71,87,88,72,203)  AND i.[State] NOT IN('1','7') AND b.BillDate < @yearendDatetime
	  ) t
	GROUP BY Serial

	IF EXISTS(  
	SELECT TOP 1 1  FROM(
	  SELECT 
		   o.outstock,
		   i.instock
	  FROM #outSerial o 
	  LEFT JOIN #inSerial i
		ON i.Serial = o.Serial 
		)s
	  WHERE s.outstock > ISNULL(s.instock,0))
	BEGIN
	  DROP TABLE #inSerial,#outSerial
	  SET @ReturnValue='<指定年结存日期>之前的数据中，有序列号商品的出库数量大于入库数量，不能按指定日期进行年结存'
	  RETURN
	END

	DROP TABLE #inSerial,#outSerial
END
/*-----------------------------------------------------------------------------------------------*/

IF EXISTS(	SELECT TOP 1 cc1.CouponCode FROM dbo.Coupon_CodeInOut cc1 
			INNER JOIN dbo.Coupon_BillIndex cbi ON cbi.BillNumberId = cc1.BillNumberId
			WHERE cc1.BillDate < @yearendDatetime 
				AND cbi.RedWord = 0
				AND cbi.IfCheck = 't'
				AND EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_CodeInOut cc2 WHERE cc2.BillType = 423 AND cc2.BillDate >= @yearendDatetime AND cc2.CouponCode= cc1.CouponCode)
		)
BEGIN
	SET @ReturnValue='有优惠券的出库日期在<指定年结存日期>之前，而其入库日期在<指定年结存日期>之后，不能按指定日期进行年结存'
	RETURN
END

/*===============================================================================================*/

IF EXISTS(	SELECT TOP 1 dbu.CouponCode FROM dbo.Coupon_BillUsed dbu 
			INNER JOIN dbo.BillIndex b ON b.BillNumberId = dbu.BillnumberId
			WHERE b.BillDate < @yearendDatetime
				AND b.RedWord = 0
				AND b.IfCheck = 't'
				AND EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_CodeInOut ccio WHERE ccio.BillType = 424 AND ccio.BillDate >= @yearendDatetime AND ccio.CouponCode = dbu.CouponCode)			
		)
BEGIN
	SET @ReturnValue='有优惠券的消费日期在<指定年结存日期>之前，而其出库日期在<指定年结存日期>之后，不能按指定日期进行年结存'
	RETURN
END

/*===============================================================================================*/

IF @CareFinanceDataCheck>1 RETURN ''

IF EXISTS(SELECT TOP 1 1 FROM dbo.CommissionBillNew WHERE ifcheck='t' AND draft=0 AND RedWord=0 AND BillNumberId NOT IN (SELECT GoodsBillId FROM Ac_CommissionBill_VoucherBill))
BEGIN
	SET @ReturnValue='在<指定年结存日期>之前，提成单未有全部生成凭证，不能按指定日期进行年结存'
	RETURN
END

SELECT @startdate =FBegin FROM dbo.Ac_Period WHERE FPeriod = @fperiod AND FYear=@fyear
IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubValue=1 AND SubName='IsUseAcSystem') AND NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='aloneusebsys' AND SubValue=1) 
BEGIN
	--IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillDate>=@startdate AND draft=0 AND IsIni=0 AND RedWord=0 AND ifYearBill=0
	--		  UNION ALL 
	--		  SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillDate>=@startdate AND draft=0 AND IsIni=0 AND RedWord=0 AND ifYearBill=0)
	--BEGIN
	--	SET @ReturnValue='本期开始时间以后还有已过账业务单据存在未生成凭证的情况，不能进行数据结转'
	--	RETURN
	--END
	
	SELECT	ps.Stypeid
			,p.FBegin
	INTO #stype_SFBegin
	FROM dbo.Ac_AccountsPeroid_Stype ps 
	INNER JOIN dbo.Ac_Period p ON p.FYear = ps.SFYear AND p.FPeriod = ps.SFPeriod
	
	IF   EXISTS(SELECT 1 FROM billindex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate 
				WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 
				AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND (InOutType = -1 OR InOutType = 1)) 
				AND BillType = 310
			)
	BEGIN
		SET @ReturnValue='在<指定年结存日期>之前存在未生成凭证的单据，不能按指定日期进行年结存'
		RETURN
	END
	
	IF   EXISTS(SELECT 1 FROM billindex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 
			AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId)
			AND ((BillType IN (11,45,160,305,139,140,142,141,34,6,161,126,144,146,145,21,187,188,201,202,9,14,16,116,115,128,129,4,189,66,190,148,
								 150,149,151,36,84,85,78,158,77,93,5,10,57,205,181,183,166,167,168,170,172,173,174,12,46,215,147,450,312,427) AND totalmoney>0 )
					OR	(BillType = 414 AND IsFreightMoney = 1)
					OR b.BillType = 159)
			)
	BEGIN
		SET @ReturnValue='在<指定年结存日期>之前存在未生成凭证的单据，不能按指定日期进行年结存'
		RETURN
	END
	
	IF EXISTS (SELECT 1 FROM dbo.sysdata WHERE SubName='isinvoice') AND EXISTS (SELECT 1 FROM dbo.ReceiptBillIndex B INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE Draft=0 AND RedWord=0 AND IsIni=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS (SELECT 1 FROM dbo.Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberID) AND TotalMoney<>0)
	BEGIN 
		SET @ReturnValue='在<指定年结存日期>之前存在未生成凭证的单据，不能按指定日期进行年结存'
		RETURN
	END
	
	IF   EXISTS(SELECT 1 FROM billindex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) AND BillType IN (305,215,11,45,160,141,405,12,46) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='在<指定年结存日期>之前存在未生成基本凭证的出库类单据，不能按指定日期进行年结存'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM billindex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='在<指定年结存日期>之前存在未生成成本凭证的出库类单据，不能按指定日期进行年结存'
		RETURN
	END
	
	IF   EXISTS(SELECT 1 FROM ReceiptBillIndex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) AND BillType IN (305,215,11,45,160,141,405,12,46) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='在<指定年结存日期>之前存在未生成基本凭证的出库类单据，不能按指定日期进行年结存'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM ReceiptBillIndex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='在<指定年结存日期>之前存在未生成成本凭证的出库类单据，不能按指定日期进行年结存'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM Coupon_BillIndex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_CouponBill_VoucherBill WHERE CouponBillId=b.BillNumberId ) AND BillType IN (428,429) AND totalmoney>0)
	BEGIN
		SET @ReturnValue='在<指定年结存日期>之前存在未生成凭证的优惠券分支机构调拨类单据，不能按指定日期进行年结存'
		RETURN
	END
	IF   EXISTS(SELECT 1 FROM dbo.PosAllotApplyBillIndex b INNER JOIN #stype_SFBegin ss ON ss.Stypeid = b.Stypeid AND ss.FBegin <= b.BillDate  WHERE draft=0 AND RedWord=0 AND isini=0 AND BillDate<@startdate AND ifYearBill=0 AND NOT EXISTS(SELECT 1 FROM Ac_DeliveryBill_VoucherBill WHERE DeliveryBillId=b.BillNumberId ) AND BillType IN (327,328,329) AND Total>0)
	BEGIN
		SET @ReturnValue='在<指定年结存日期>之前存在未生成凭证的门店配送类单据，不能按指定日期进行年结存'
		RETURN
	END

	DROP TABLE #stype_SFBegin
END

/*===============================================================================================*/

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CheckAllRefUsage]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CheckAllRefUsage] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2017-04-24
----描述：一次性检查会计科目是否被引用
----========================
CREATE    PROCEDURE [dbo].[GP_CheckAllRefUsage]
(
    @stypeid VARCHAR(MAX),
    @atypeid VARCHAR(MAX)
)
--@encode$--
AS 

----V3标示
DECLARE @ISv3 INT 
SET @ISv3=(SELECT  SubValue FROM sysdata WHERE SubName='ProInfo'  )

IF @stypeid='00000' AND @ISv3<>1
BEGIN
	IF EXISTS (SELECT 1 FROM AC_ACCOUNT WHERE stypeid > '00000' and typeid IN (SELECT a from dbo.f_split(@atypeid,','))  AND isdist = 1)
	    RETURN  1
	
	RETURN 0
END

DECLARE @isUsed INT
SET @isUsed = 0

CREATE TABLE #t1
    (
      rowid INT IDENTITY(1, 1) ,
      tableName sysname NOT NULL ,
      ColA sysname NOT NULL ,
      ColS sysname NOT NULL
    );

--SELECT  t.name AS tableName, 
--		c1.colname AS ColA,
--		c2.colname AS ColS
INSERT INTO #t1 SELECT  t.name AS tableName, 
					  c1.colname AS ColA,
					  c2.colname AS ColS
FROM    sys.tables t
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id AND c.name LIKE 'atypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name AND s.basType = 'atypeid'
         WHERE  c.name IS NOT NULL OR s.fldname IS NOT NULL) c1 ON c1.tblname = t.name
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id AND c.name LIKE 'stypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name  AND s.basType = 'stypeid'
         WHERE  c.name IS NOT NULL OR s.fldname IS NOT NULL) c2 ON c2.tblname = t.name
WHERE t.name NOT IN ('Ac_Account_Assist_CheckItems','BillAtype',
'Ac_Balance','Ac_Balance_Assist_CheckItems','Ac_Balance_Assist_CheckItems_Detail',
'Ac_IniAccount','Ac_IniAccount_Assist_CheckItems','Ac_IniAccount_Assist_CheckItems_Detail,Ac_Voucher_Bill_Backup','AccountCredence'
,'Ac_ProfitandLoss','Ac_Voucher_Bill_Backup','Ac_Voucher_Bill_Log')
UNION ALL SELECT 'SType','atypeid','typeid'
UNION ALL SELECT 'SType','atypeid2','typeid'
UNION ALL SELECT 'SType','atypeid3','typeid'
UNION ALL SELECT 'SType','atypeid4','typeid'
UNION ALL SELECT 'Ac_Items_Detail','DEPATYPEID','stypeid'
UNION ALL SELECT 'Ac_Items_Detail','DISATYPEID','stypeid'
UNION ALL SELECT '#Ac_Auditing_Template','atypeid','stypeid'
UNION ALL SELECT 'BillAtype','AtypeId','StypeId'
UNION ALL SELECT 'Ac_AssetsCards','AssertATypeId','stypeid' --以下四行添加的目的是另一个检查科目使用的存储过程里有检查Ac_AssetsCards这张表
UNION ALL SELECT 'Ac_AssetsCards','DepATypeId','stypeid'
UNION ALL SELECT 'Ac_AssetsCards','DisATypeId','stypeid'
UNION ALL SELECT 'Ac_AssetsCards','DevalueATypeId','stypeid'
ORDER BY TableName


SELECT Stypeid,atypeid 
INTO #Ac_Auditing_Template
FROM Ac_Auditing_Template t
JOIN Ac_Auditing_Template_Detail d ON d.Atid = t.AtId

--SELECT IDENTITY(INT,1,1) AS rid ,*
--INTO #t2
--FROM #t1
------过滤无关表-------备注：如果还要保留的话，注意#t2已经不存在了，可以替换成#t1
--IF  EXISTS (SELECT * FROM #t2 WHERE tableName='AccountCredence')
--DELETE #t2  WHERE tableName='AccountCredence'
--IF  EXISTS (SELECT * FROM #t2 WHERE tableName='Ac_ProfitandLoss')
--DELETE #t2  WHERE tableName='Ac_ProfitandLoss'
--IF  EXISTS (SELECT * FROM #t2 WHERE tableName='Ac_Voucher_Bill_Backup')
--DELETE #t2  WHERE tableName='Ac_Voucher_Bill_Backup'
--IF  EXISTS (SELECT * FROM #t2 WHERE tableName='Ac_Voucher_Bill_Log')
--DELETE #t2  WHERE tableName='Ac_Voucher_Bill_Log'



DECLARE @i INT
DECLARE @count INT
DECLARE @tbname NVARCHAR(200)
DECLARE @colaname NVARCHAR(200)
DECLARE @colsname NVARCHAR(200)
DECLARE @sql NVARCHAR(MAX)

SELECT @count = COUNT(1) FROM #t1

SET @i = 1

WHILE @i <= @count AND @isUsed = 0
BEGIN 
    SELECT @tbname = TableName,@colaname=cola,@colsname = cols
    FROM #t1
    WHERE rowid = @i
    
    SET @sql = 'SELECT @isUsed = Count(1) FROM '
            + @tbname + ' WHERE ' + @colaname
            + '  IN (SELECT a from dbo.f_split('''+@ATypeId+''','',''))  '
            + ' AND ' + @colsname + ' = '''
            + @STypeId + ''''                              
    
    EXECUTE sp_executesql @SQL,
        N'@isUsed INT OUTPUT', @isUsed OUTPUT
    
    SET @i += 1
END

DROP TABLE #t1,#Ac_Auditing_Template

IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''
    --' + @tbname + ''' AS TABLENAME,''
    --' + @STypeId + ''' AS [STypeId], ''
    --' + @ATypeId + ''' AS [ATypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END
--	Ac_Balance
SELECT TOP 1
        @isused += 1
FROM    Base_InventoryTypeDetails
WHERE   
	STypeid = @stypeid
	AND	(StockATypeID IN (SELECT a FROM dbo.f_split(@atypeid,',')) OR IncomeATypeID=@atypeid OR CostATypeID=@atypeid)

IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''Base_InventoryTypeDetails'' AS TABLENAME,''
    --' + @STypeId + ''' AS [STypeId], ''
    --' + @ATypeId + ''' AS [ATypeId]'
    ----PRINT(@SQL)
    --EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance
WHERE   STypeid = @stypeid
AND		ATypeId  IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
AND (FBeginBalanceFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYtdDebitFor<>0 OR FYtdCreditFor<>0 OR FEndBalanceFor<>0 OR FBeginBalance<>0 OR FDebit<>0 OR FCredit<>0 OR FYtdDebit<>0 OR FYtdCredit<>0 OR FEndBalance<>0 OR FBeginqty<>0  OR FDebitqty<>0 OR FCreditqty<>0 OR FYtdDebitqty<>0 OR FYtdCreditqty<>0 OR FEndqty<>0)

IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''Ac_Balance'' AS TABLENAME,''
    --' + @STypeId + ''' AS [STypeId], ''
    --' + @ATypeId + ''' AS [ATypeId]'
    ----PRINT(@SQL)
    --EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance_Assist_CheckItems
WHERE   STypeid = @stypeid
AND ATypeId IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
AND (IniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FEndBalanceFor<>0 OR IniYTotalFor<>0 OR IniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FEndBalance<>0 OR IniYTotal<>0  OR IniYqty<>0  OR FDebitqty<>0 OR FCreditqty<>0 OR FEndqty<>0 OR Iniqty<>0)

IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''Ac_Balance_Assist_CheckItems'' AS TABLENAME,''
    --' + @STypeId + ''' AS [STypeId], ''
    --' + @ATypeId + ''' AS [ATypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
AND ATypeId IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
AND (IniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FEndBalanceFor<>0 OR IniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FEndBalance<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR FEndqty<>0 OR Iniqty<>0)

IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''Ac_Balance_Assist_CheckItems_Detail'' AS TABLENAME,''
    --' + @STypeId + ''' AS [STypeId], ''
    --' + @ATypeId + ''' AS [ATypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END
--	Ac_IniAccount
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount
WHERE   STypeid = @stypeid
AND ATypeId IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
 AND(iniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FYTotal<>0  OR iniYTotal<>0 OR iniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYTotalFor<>0 OR iniYTotalFor<>0 OR iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0 OR FYTotalDebit<>0 OR FYTotalCredit<>0 OR FYTotalDebitFor<>0 OR FYTotalCreditFor<>0)
 
IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''
    --' + 'Ac_IniAccount' + ''' AS TABLENAME,''
    --' + @STypeId + ''' AS [StypeId], ''
    --' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END
      
--	Ac_IniAccount_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems
WHERE   STypeid = @stypeid
AND ATypeId IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
 AND(iniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FYTotal<>0  OR iniYTotal<>0 OR iniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYTotalFor<>0 OR iniYTotalFor<>0 OR iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0)
IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''
    --' + 'Ac_IniAccount_Assist_CheckItems' + ''' AS TABLENAME,''
    --' + @STypeId + ''' AS [StypeId], ''
    --' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END      
  
--	Ac_IniAccount_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
AND ATypeId IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
AND(iniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FYTotal<>0  OR iniYTotal<>0 OR iniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYTotalFor<>0 OR iniYTotalFor<>0 OR iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0)
 
IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''
    --' + 'Ac_IniAccount_Assist_CheckItems_Detail' + ''' AS TABLENAME,''
    --' + @STypeId + ''' AS [StypeId], ''
    --' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END          


SELECT TOP 1
        @isused += 1
FROM    Te_InitDataIndex TI
INNER JOIN Te_InitDataDetail TD ON TI.Id=TD.IndexId
WHERE   TI.STypeid = @stypeid
AND TD.ATypeId IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
--AND ABS(ISNULL(IniYTotal,0)) + ABS(ISNULL(FDebit,0)) +ABS(ISNULL(FCredit,0)) + ABS(ISNULL(IniTotal,0)) +ABS(ISNULL(FYTotal,0)) > 0
IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''
    --' + 'Te_InitDataIndex' + ''' AS TABLENAME,''
    --' + @STypeId + ''' AS [StypeId], ''
    --' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END 

SELECT TOP 1
        @isused += 1
FROM    Ac_Voucher_Bill
WHERE   
	STypeid = @stypeid
	AND ATypeId IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''
    --' + 'Ac_Voucher_Bill' + ''' AS TABLENAME,''
    --' + @STypeId + ''' AS [StypeId], ''
    --' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END 

--	Ac_ProfitAndLoss_Detail 添加的原因是另一个检查科目使用的存储过程中检查过这个数据GP_CheckAccountUsage
SELECT TOP 1
        @isused += 1
FROM    Ac_ProfitAndLoss_Detail
WHERE   STypeid = @stypeid
        AND ATypeId IN (SELECT a FROM dbo.f_split(@atypeid,',')) 
        AND ABS(ISNULL(FFTotal,0)) + 
        ABS(ISNULL(FYTOTAL,0)) > 0
        
IF @isUsed > 0
BEGIN
    --SET @sql = ' 
    --SELECT +''
    --' + 'Ac_ProfitAndLoss_Detail' + ''' AS TABLENAME,''
    --' + @STypeId + ''' AS [StypeId], ''
    --' + @ATypeId + ''' AS [AtypeId]'
    
    --EXEC(@SQL)
    RETURN 1
END    

IF @isUsed > 0
BEGIN
    RETURN 1
END  

RETURN 0

GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_CheckAllReVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_CheckAllReVoucher
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	反复核所有已复核会计凭证
-- 时间：	2013-08-09
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_CheckAllReVoucher
(
	@StypeID		VARCHAR(50)='',			--分支结构ID
	@OperatorID		VARCHAR(50)=''			--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE	
	@PassCount		INT=0,			--成功条数
	@FailtCount		INT=0,			--失败条数
	@ErrorMsg		VARCHAR(2000),	--失败原因
	@BillNumberId	NUMERIC(18,0)=0,--凭证ID
	@BillCode		VARCHAR(500)='',--凭证编号
	@BillCount		INT,			--满足条件凭证条数
	@I				INT,			--
	@Re				INT,			--执行复核存储过程报错
	@FYear			INT,
	@FPeriod		INT
	
--获取当前分支机构年度、会计期间
SELECT @FYear=FYear,@FPeriod=FPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID

--单据
DECLARE @VoucherBill TABLE
(
	Nid				INT IDENTITY(1,1),
	BillNumberId	NUMERIC(18,0),
	BillCode		VARCHAR(500)
)

INSERT INTO @VoucherBill(BillNumberId,BillCode)
SELECT 
	BillNumberId,
	'凭证'+G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE	
	STypeId = @stypeid
	AND ISNULL(V.ReCheckId,'')<>''
	AND FYear=@FYear
	AND FPeriod=@FPeriod
	AND V.IfCheck='f'
	
SET @BillCount = @@ROWCOUNT
	
--展示结果
DECLARE @Result TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)
SET @I=1
WHILE @I<=@BillCount
	BEGIN
		
		SELECT @BillNumberId = BillNumberId,@BillCode = BillCode FROM @VoucherBill WHERE Nid = @I
		
		BEGIN TRY
			BEGIN
				EXEC @Re = Gp_ReCheckedAcVoucherBill @BillNumberId,@OperatorID
			
			IF @Re = 0
			BEGIN
				INSERT INTO @Result(BillCode,Msg)VALUES(@BillCode,',成功')
				SET @PassCount = @PassCount + 1
			END
		END	
	END TRY
	BEGIN CATCH
		BEGIN			
			SET @FailtCount = @FailtCount + 1
			SET @ErrorMsg = ERROR_MESSAGE()
			--处理提示
			SET @ErrorMsg = REPLACE(@ErrorMsg,'，不允许反复核，请确认！','')	
			IF @ErrorMsg <> ''
				INSERT INTO @Result(BillCode,Msg)VALUES(@BillCode,',失败,原因为'+@ErrorMsg)
		END
	END CATCH		
		SET @I = @I + 1
	END
	
--展示结果
DECLARE @showResult TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)

--第一条记录
INSERT INTO @showResult(BillCode,Msg)VALUES('成功反复核:','')
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',成功' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('成功共',CAST(@PassCount AS VARCHAR(100)) + '张')

--失败张数
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',失败' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('失败共',CAST(@FailtCount AS VARCHAR(100))+'张')

SELECT * FROM @showResult

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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















/****** Object:  Stored Procedure dbo.Gp_CheckAllType23    Script Date: 2002-6-20 10:14:45 ******/

CREATE  PROCEDURE Gp_CheckAllType23         ----根据传入的量,判断该量是否合法
(
   @typeid varchar(100),                ---以ID的形式传入 
   @typename varchar(66),          ---以NAME的形式传入
   @type int,                                 ---要鉴别的类型
   @result varchar(66)                  ---通过模糊查找得到的结果
)
--@encode$--
AS
SET NOCOUNT ON

if @type=1 
begin
   select fullname from ptype where usercode=@typeid                   --根据UserCode鉴别Ptype
   if @@Rowcount=1 return 1 
   else
   begin     
     select @result=usercode from ptype where usercode like '%'+@typeid+'%' 
     if @@Rowcount=1 return 1 else return 0        
   end
end
else if @type=2 
begin
   select usercode from ptype where fullname=@typename             --根据Fullname鉴别Ptype
   if @@Rowcount=1 return 1 
   else
   begin     
     select @result=fullname from ptype where fullname like '%'+@typename+'%' 
     if @@Rowcount=1 return 1 else return 0        
   end
end
else if @type=3 
begin
   select typeid from employee where fullname=@typename            --经手人
   if @@Rowcount=1 return 1 
   else
   begin     
     select @result=fullname from employee where fullname like '%'+@typename+'%' 
     if @@Rowcount=1 return 1 else return 0        
   end
end
else if @type=4 
begin
   select typeid from stock where fullname=@typename                  --仓库
   if @@Rowcount=1 return 1 
   else
   begin     
     select @result=fullname from ptype where fullname like '%'+@typename+'%' 
     if @@Rowcount=1 return 1 else return 0        
   end
end
--else if @type=5 
--begin
      --select --往来单位
--end















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_CheckAllVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_CheckAllVoucher
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	复核所有未复核会计凭证
-- 时间：	2013-06-21
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_CheckAllVoucher
(
	@StypeID		VARCHAR(50)='',			--分支结构ID
	@OperatorID		VARCHAR(50)=''			--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE	
	@PassCount		INT=0,			--成功条数
	@FailtCount		INT=0,			--失败条数
	@ErrorMsg		VARCHAR(2000),	--失败原因
	@BillNumberId	NUMERIC(18,0)=0,--凭证ID
	@BillCode		VARCHAR(500)='',--凭证编号
	@BillCount		INT,			--满足条件凭证条数
	@I				INT,			--
	@Re				INT,			--执行复核存储过程报错
	@FYear			INT,
	@FPeriod		INT
	
--获取当前分支机构当前会计期间	
SELECT @FYear=FYear,@FPeriod=FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE STypeId = @STypeId

--单据
DECLARE @VoucherBill TABLE
(
	Nid				INT IDENTITY(1,1),
	BillNumberId	NUMERIC(18,0),
	BillCode		VARCHAR(500)
)


INSERT INTO @VoucherBill(BillNumberId,BillCode)
SELECT 
	BillNumberId,
	'凭证'+G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE	
	STypeId = @stypeid
	AND V.ReCheckId=''
	AND FYear=@FYear
	AND FPeriod=@FPeriod
	AND V.IfCheck='f'
	
SET @BillCount = @@ROWCOUNT
	
--展示结果
DECLARE @Result TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)
SET @I=1
WHILE @I<=@BillCount
	BEGIN
		
		SELECT @BillNumberId = BillNumberId,@BillCode = BillCode FROM @VoucherBill WHERE Nid = @I
		
		BEGIN TRY
			BEGIN
				EXEC @Re = Gp_CheckedAcVoucherBill @BillNumberId,@OperatorID
			
			IF @Re = 0
			BEGIN
				INSERT INTO @Result(BillCode,Msg)VALUES(@BillCode,',成功')
				SET @PassCount = @PassCount + 1
			END
		END	
	END TRY
	BEGIN CATCH
		BEGIN			
			SET @FailtCount = @FailtCount + 1
			SET @ErrorMsg = ERROR_MESSAGE()
			--处理提示
			SET @ErrorMsg = REPLACE(@ErrorMsg,'，不允许复核，请确认！','')	
			IF @ErrorMsg <> ''
				INSERT INTO @Result(BillCode,Msg)VALUES(@BillCode,',失败,原因为'+@ErrorMsg)
		END
	END CATCH		
		SET @I = @I + 1
	END
	
--展示结果
DECLARE @showResult TABLE
(
	Nid			INT IDENTITY(1,1),
	BillCode	VARCHAR(500),
	Msg			VARCHAR(2000)
)

--第一条记录
INSERT INTO @showResult(BillCode,Msg)VALUES('成功复核:','')
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',成功' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('成功共',CAST(@PassCount AS VARCHAR(100)) + '张')

--失败张数
INSERT INTO @showResult(BillCode,Msg)SELECT BillCode,Msg FROM @Result WHERE LEFT(Msg,3) = ',失败' ORDER BY Nid ASC
INSERT INTO @showResult(BillCode,Msg)VALUES('失败共',CAST(@FailtCount AS VARCHAR(100))+'张')

SELECT * FROM @showResult

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_CheckArapIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_CheckArapIni
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2012-05-29
-- Description: 检查应收应付期初与期初单据信息是否匹配
-- =============================================
CREATE PROCEDURE Gp_CheckArapIni
(
	@stypeid		VARCHAR(50),
	@ReturnValue	VARCHAR(max) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--判断是否已经开账
IF @stypeid='' AND NOT EXISTS(SELECT TOP 1 1 FROM SType s LEFT JOIN SType_UserConfig u ON s.TypeId=u.StypeId WHERE s.sonnum=0 AND s.deleted=0 AND  ((u.Value = '0' AND u.ConfigNo = '1') OR u.Value IS NULL ))
	RETURN 0
IF @stypeid <> '' AND EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeID = @STypeId AND Value = '1' AND ConfigNo = '1')
	RETURN 0

CREATE TABLE #stype(typeid VARCHAR(50))
IF @stypeid=''
	INSERT	INTO #stype
	SELECT	s.TypeId 
	FROM	SType s 
	LEFT	JOIN SType_UserConfig u ON s.TypeId=u.StypeId 
	WHERE	s.sonnum=0 
			AND s.deleted=0 
			AND((u.Value = '0' AND u.ConfigNo = '1') OR u.Value IS NULL )
ELSE
	INSERT INTO #stype
	        ( typeid )
	VALUES  ( @stypeid)
	
DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'
							
CREATE TABLE #billindexARAPTotal
(
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		APTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		YFTotal00  NUMERIC(24, 10) ,
		FCTotal00  NUMERIC(24, 10) ,
		GRIRTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10) ,
		nAPTotal00  NUMERIC(24, 10) ,
		nYSTotal00  NUMERIC(24, 10) ,
		nYFTotal00  NUMERIC(24, 10) ,
		NFCTotal00  NUMERIC(24, 10) ,
		NGRIRTotal00  NUMERIC(24, 10) 
)
CREATE NONCLUSTERED INDEX cix_billindexARAPTotal_y ON #billindexARAPTotal(stypeid,btypeid,cid)

	INSERT INTO #billindexARAPTotal
	( 
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			APTotal00 ,
			YSTotal00 ,
			YFTotal00 ,
			FCTotal00,
			GRIRTotal00,
			nARTotal00 ,
			nAPTotal00 ,
			nYSTotal00 ,
			nYFTotal00,
			NFCTotal00,
			NGRIRTotal00
	)
	SELECT	stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(APTotal00),
			SUM(YSTotal00),
			SUM(YFTotal00),
			SUM(FCTotal00),
			SUM(GRIRTotal00),
			SUM(nARTotal00),
			SUM(nAPTotal00),
			SUM(nYSTotal00),
			SUM(nYFTotal00),
			SUM(NFCTotal00),
			SUM(NGRIRTotal00)
	FROM
	(
		SELECT	stypeid ,
				btypeid ,
				cid ,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					ELSE 0 
				END AS artotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)) 
					ELSE 0 
				END AS aptotal00,
				CASE WHEN billtype =189 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS ystotal00,
				CASE WHEN billtype =190 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS yftotal00,
				0 AS FCTotal00,
				0 AS  GRIRTotal00,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS nartotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS naptotal00,
				CASE WHEN billtype =189 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nystotal00,
				CASE WHEN billtype =190 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nyftotal00,
				0 AS NFCTotal00,
				0 AS  NGRIRTotal00
		FROM dbo.BillIndex
		WHERE	BillType IN(4,66,11,12,45,46,85,93,141,148,149,160,167,168,172,181,6,34,36,84,145,150,151,161,170,189,190,213,212,312)
				AND IsIni=1 
				AND	stypeid IN (SELECT typeid FROM #stype)
				
		UNION ALL
		SELECT  b.stypeid ,
				a.btypeid ,
				b.cid ,
				CASE WHEN b.billtype = 116
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					ELSE 0
				END AS artotal00,
				CASE WHEN b.billtype = 128
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					 ELSE 0
				END AS aptotal00,
				0 AS ystotal00,
				0 AS yftotal00,
				0 AS FCTotal00,
				0 AS GRIRTotal00,
				CASE WHEN b.billtype = 116
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					ELSE 0
				END AS nartotal00,
				CASE WHEN b.billtype = 128
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					 ELSE 0
				END AS naptotal00,
				0 AS nystotal00,
				0 AS nyftotal00,
				0 AS NFcTotal00,
				0 AS NGRIRTotal00
		FROM	AdDebtBill a 
		INNER JOIN billindex b ON a.BillNumberId =b.BillNumberId
		WHERE	BillType IN(115,116,128,129)
				AND IsIni=1 
				AND	b.stypeid IN (SELECT typeid FROM #stype)
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=402
				   THEN dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYFTotal00,
			   0 AS NYSTotal00,
			   CASE WHEN B.BillType=402
					THEN dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
				
		FROM SendBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid IN (SELECT typeid FROM #stype)
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=403
				   THEN -dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   CASE WHEN B.BillType=403
					THEN -dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
		FROM SendBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid IN (SELECT typeid FROM #stype)
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.Total
					ELSE dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.DiscountPrice )
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=400
				    THEN CASE WHEN A.InvoiceQty=0
						 THEN A.NTotal
				    ELSE dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.NDiscountPrice)
				    END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid IN (SELECT TYPEID FROM #stype)
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.Total
					ELSE dbo.F_RoundTotal(-(A.Qty-A.InvoiceQty)*A.DiscountPrice )
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.NTotal
					ELSE dbo.F_RoundTotal(-(A.Qty-A.InvoiceQty)*A.NDiscountPrice)
					END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid IN (SELECT TypeID FROM #stype)
		
		
		UNION ALL
		SELECT 
			  B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.BillType=405
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.BillType=405
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM ReceiptBillIndex B 
		WHERE B.Stypeid IN (SELECT typeid FROM #stype) AND B.IsIni=1
		
		
		UNION ALL
		SELECT 
		B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.totalmoney
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.ChargeOffType IN (3,4)
				   THEN B.totalmoney
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.NTotalMoney
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.ChargeOffType IN (3,4)
				   THEN B.NTotalMoney
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM dbo.BillIndex B 
		 WHERE B.BillType= 450 AND B.IsIni=1 AND B.Stypeid IN (SELECT typeid FROM #stype)
		
		
	) total
	GROUP BY stypeid,btypeid,cid

DELETE FROM #billindexARAPTotal WHERE ISNULL(YSTotal00,0)=0 AND ISNULL(YFTotal00,0)=0 AND ISNULL(ARTotal00,0)=0 
AND ISNULL(APTotal00,0)=0 AND ISNULL(nYSTotal00,0)=0 AND ISNULL(nYFTotal00,0)=0 AND ISNULL(nARTotal00,0)=0 AND ISNULL(nAPTotal00,0)=0
AND ISNULL(NGRIRTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0 AND ISNULL(GRIRTotal00,0)=0

DECLARE @stypeidlist VARCHAR(max)=''
SELECT @stypeidlist=@stypeidlist+','+ISNULL(a.STypeID,b.stypeid) 
FROM 
(
	SELECT	BTypeID,
			STypeID,
			CID,
			APTotal00,
			ARTotal00,
			YSTotal00,
			YFTotal00,
			nAPTotal00,
			nARTotal00,
			nYSTotal00,
			nYFTotal00,
			GRIRTotal00,
			NGRIRTotal00,
			FCTotal00,
			NFCTotal00
	FROM	dbo.BType_ArApTotal 
	WHERE	STypeID IN (SELECT typeid FROM #stype) 
) a
FULL OUTER JOIN #billindexARAPTotal b ON a.BTypeID=b.btypeid AND a.STypeID=b.stypeid AND a.CID=b.cid 
AND ISNULL(A.GRIRTotal00,0)=ISNULL(B.GRIRTotal00,0) AND ISNULL(A.NGRIRTotal00,0)=ISNULL(B.NGRIRTotal00,0) 
AND ISNULL(A.FCTotal00,0)=ISNULL(B.FCTotal00,0) AND ISNULL(A.NFCTotal00,0)=ISNULL(B.NFCTotal00,0) 
AND ISNULL(a.APTotal00,0) = ISNULL(b.APTotal00,0) AND ISNULL(a.ARTotal00,0) = ISNULL(b.ARTotal00,0) 
AND ISNULL(a.YFTotal00,0) = ISNULL(b.YFTotal00,0) AND ISNULL(a.YSTotal00,0) = ISNULL(b.YSTotal00,0) 
AND ISNULL(a.nAPTotal00,0) = ISNULL(b.nAPTotal00,0) AND ISNULL(a.nARTotal00,0) = ISNULL(b.nARTotal00,0) 
AND ISNULL(a.nYFTotal00,0) = ISNULL(b.nYFTotal00,0) AND ISNULL(a.nYSTotal00,0) = ISNULL(b.nYSTotal00,0)
WHERE a.STypeID IS NULL OR b.stypeid IS NULL

IF @stypeidlist<>''
BEGIN
	DECLARE @sfullname VARCHAR(max)='',@proinfo INT=1
	SELECT @proinfo=subvalue FROM dbo.sysdata WHERE SubName='proinfo'
	IF @proinfo=1
		SET @ReturnValue='期初单据数据与应收应付期初数据不一致，请重新录入应收应付期初！'
	ELSE
	BEGIN
		SELECT @sfullname=@sfullname+','+fullname FROM dbo.SType WHERE typeid IN (SELECT a FROM dbo.f_split(@stypeidlist,','))
		SET @sfullname=RIGHT(@sfullname,LEN(@sfullname)-1)
		SET @ReturnValue =@sfullname+'的期初单据数据与应收应付期初数据不一致，请重新录入应收应付期初！'
	END
	DROP TABLE #billindexARAPTotal,#stype
	RETURN -19 -- -2
END
ELSE
BEGIN
	DROP TABLE #billindexARAPTotal,#stype
	RETURN 0
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：陈启华
	日期：2006-03-06	
	描述：处理同价，变价调拔单的出入库审核(此审核方式要求两面都要设置)
*/
CREATE  PROCEDURE GP_CheckAuditingInOut
(
	@Billtype int -- 单据类型，此处只有 17 或 21 
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------

IF @Billtype = 17
BEGIN
	IF EXISTS (SELECT * FROM AuditingFlowSet WHERE Billtype =17 AND Substring(AuditingReason,14,1)='1')  --是出入库审核
	BEGIN  --当只设置了出库审核或入库审核时，此审核不启用
		IF (NOT EXISTS (SELECT * FROM AuditingFlowDetail WHERE Billtype =17 AND OutKty='o')) OR (NOT EXISTS (SELECT * FROM AuditingFlowDetail WHERE Billtype =17 AND OutKty='i'))
			UPDATE AuditingFlowSet SET ifuse ='0' WHERE BillType =17
	END
END
IF @Billtype = 21
BEGIN
	IF EXISTS (SELECT * FROM AuditingFlowSet WHERE Billtype =21 AND Substring(AuditingReason,14,1)='1')  --是出入库审核
	BEGIN  --当只设置了出库审核或入库审核时，此审核不启用
		IF (NOT EXISTS (SELECT * FROM AuditingFlowDetail WHERE Billtype =21 AND OutKty='o')) OR (NOT EXISTS (SELECT * FROM AuditingFlowDetail WHERE Billtype =21 AND OutKty='i'))
			UPDATE AuditingFlowSet SET ifuse ='0' WHERE BillType =21
	END
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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














----------返回指定基本信息的typeid
----------返回值：1 没有该操作员，2：符合条件的结果不唯一 3:参数错误
----------author:王跃

CREATE  PROCEDURE [dbo].[gp_CheckBaseInfo]
(
 @chvOperator varchar(100),               --操作员id
 @intFlag           int                 ,               --基本信息的类型1:atype,2:btype(客户),3:employee,4:ptype,5:stock,6:btype(供应商)
 @chvFullName varchar(66)='',
 @chvUserCode varchar(26)='',
 @chvTypeid    varchar(100) output
)
--@encode$--
AS
Set Nocount on
if not @intFlag in(1,2,3,4,5,6)  return 3

--------------------------------------------------------------权限检查-------------------------------------------------------
if @chvOperator is null return 1

declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @chvOperator,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
declare @intCount int

if @intFlag=1
begin
	select @intCount=isnull(count(typeid),0) from atype where sonnum=0 and deleted=0 and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MAtypeid+'%'
              if @intCount=0 return 1
              else if @intCount>1 return 2
	select @chvTypeid=typeid from atype where sonnum=0 and deleted=0 and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MAtypeid+'%'
end
else
if @intFlag=2
begin
	select @intCount=isnull(count(typeid),0) from btype where sonnum=0 and deleted=0 and left(typeid,5)='00001' and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MBtypeid+'%'
              if @intCount=0 return 1
              else if @intCount>1 return 2
	select @chvTypeid=typeid from btype where sonnum=0 and deleted=0 and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MBtypeid+'%'
end
else
if @intFlag=3
begin
	select @intCount=isnull(count(typeid),0) from employee where sonnum=0 and deleted=0 and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MEtypeid+'%'
              if @intCount=0 return 1
              else if @intCount>1 return 2
	select @chvTypeid=typeid from employee where sonnum=0 and deleted=0 and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MEtypeid+'%'
end
else
if @intFlag=4
begin
	select @intCount=isnull(count(typeid),0) from ptype where sonnum=0 and deleted=0 and (Usercode=@chvFullName)  and typeid like @MPtypeid+'%'
              if @intCount=0 return 1
              else if @intCount>1 return 2
	select @chvTypeid=typeid from ptype where sonnum=0 and deleted=0 and ( Usercode=@chvFullName)  and typeid like @MPtypeid+'%'
end
else
if @intFlag=5
begin
	select @intCount=isnull(count(typeid),0) from stock where sonnum=0 and deleted=0 and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MKtypeid+'%'
              if @intCount=0 return 1
              else if @intCount>1 return 2
	select @chvTypeid=typeid from stock where sonnum=0 and deleted=0 and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MKtypeid+'%'
end
else
if @intFlag=6
begin
	select @intCount=isnull(count(typeid),0) from btype where sonnum=0 and deleted=0 and  left(typeid,5)='00002' and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MBtypeid2+'%'
              if @intCount=0 return 1
              else if @intCount>1 return 2
	select @chvTypeid=typeid from btype where sonnum=0 and deleted=0 and (fullname=@chvFullName or Usercode=@chvFullName)  and typeid like @MBtypeid2+'%'
end
return 0














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_CheckBill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_CheckBill];
GO

/*
	作者:颜熙
	日期:2017-02-05
	描述:单据合法性检查
*/
CREATE  PROCEDURE Gp_CheckBill 
( 
	@billtype	INT, --单据类型
	@stypeids	VARCHAR(50),--分支机构id
	@userid		VARCHAR(50),--当前操作员
	@starttime	VARCHAR(50),--开始时间
	@endtime	VARCHAR(50),--结束时间
	@draft		BIT=0 --是否检测草稿
)
    --@encode$--
AS
    SET NOCOUNT ON;
    BEGIN
    DECLARE @sql VARCHAR(8000)
		IF @billtype = 22--调货申请单
			BEGIN
				IF(@draft = 0)
					BEGIN 
						SELECT billnumberid,1 as pass from PosAllotApplyBillIndex
						WHERE  BillType =22 and stypeid in (SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeids, 11, @userid))
						AND BillState = 2  and billdate>=@starttime and billdate<=@endtime
					END 
				ELSE
					BEGIN
						SELECT billnumberid,1 as pass from PosAllotApplyBillIndex
						WHERE BillType =22 and stypeid in (SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeids, 11, @userid))
						AND billdate>=@starttime and billdate<=@endtime
					END 
				RETURN 
			END 
		ELSE IF @billtype = 411 --固定资产拆分单
		BEGIN
			IF(@draft = 0)
			BEGIN 
				SELECT billnumberid,1 as pass from AssetIncSplit	
				WHERE  stypeid in (SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeids, 11, @userid)) 
				AND draft = 0 and billdate>= @starttime
				AND billdate<=@endtime
			END 
			ELSE
			BEGIN 
				SELECT billnumberid,1 as pass from AssetIncSplit	
				WHERE  stypeid in (SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeids, 11, @userid)) 
			    AND billdate>= @starttime AND billdate<=@endtime
			END 
			RETURN 
		END 
		ELSE IF @billtype = 410 --固定资产原值变更单
		BEGIN
			IF(@draft = 0)
			BEGIN
				SELECT ID AS billnumberid,1 AS pass FROM AssetIncChangeBill 
				WHERE stypeid in (SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeids, 11, @userid)) 
				AND draft = 0 AND billdate>=@starttime AND billdate<=@endtime --AND RedWord = 0
			END 
			ELSE 
			BEGIN
				SELECT  ID AS billnumberid,1 AS pass FROM AssetIncChangeBill 
				WHERE stypeid in (SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeids, 11, @userid)) 
                AND billdate>=@starttime and billdate<=@endtime --and RedWord = 0
			END 
			RETURN 
		END 
		ELSE IF @billtype = 311
		BEGIN
			IF(@draft = 0)
			BEGIN
				SELECT BillNumberId,1 as pass FROM CommissionBillNew
				WHERE stypeid IN (SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeids, 11, @userid))
				AND draft=0 AND ifcheck='t' AND  billdate>=@starttime and billdate<=@endtime and RedWord = 0
			END 
			ELSE 
			BEGIN
				SELECT BillNumberId,0 as pass FROM  CommissionBillNew
				WHERE stypeid IN (SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeids, 11, @userid))
				AND billdate>=@starttime and billdate<=@endtime and RedWord = 0
			END 
			RETURN 
		END 
		ELSE
			BEGIN
				DECLARE @tableName VARCHAR(200)
				IF(@billtype = 404 or @billtype = 405)
					BEGIN
						SET @tableName = 'ReceiptBillIndex' --采购暂估开票、销售发货开票单
					END
				ELSE IF(@billtype = 418 OR @billtype=419 OR @billtype = 420)
					BEGIN
						SET @tableName = 'FactIndex'
					END
				ELSE IF (@billtype = 412 OR @billtype=413)
					BEGIN
						SET @tableName = 'onShelvespickIndex'
					END
				ELSE IF(@billtype IN(423,424,425,426))
					BEGIN
						SET @tableName='Coupon_BillIndex'
					END
				ELSE 
					BEGIN
						SET @tableName = 'BillIndex'
					END
					
				SET @sql = '
				SELECT 
					BillNumberId,
					CASE WHEN B.draft=0 THEN 1 ELSE 0 END Pass 
				FROM '+@tableName +' B
				INNER JOIN dbo.F_GetAllManagerBaseTypeId('''+@stypeids+''', 11,'''+ @userid+''') F ON F.typeid=B.stypeid
				WHERE 
					BillType = '+CAST(@billtype AS VARCHAR(50))+'
					AND billdate BETWEEN '''+@starttime+''' AND '''+@endtime+'''
					AND RedWord = 0'
					
				IF(@draft=0)--不包含未记账
					BEGIN
						SET @sql+='
					AND draft = 0
					AND ifcheck = ''t'''
					END
				--print @sql
				EXEC(@sql)
			 END 
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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





/*
	作者：谢吉康
	日期：2009-06-25
	描述：检查某张单据的审核状态
*/

CREATE  PROCEDURE Gp_CheckBillAuditingState
(
	@nBillId	numeric(18,0),
	@BillType	int
)
--@encode$--
AS
SET NOCOUNT ON


CREATE TABLE #temp(
	BillNumberID INT,
	BillType	 NUMERIC(4, 0),
	PassFlag 	 bit,
	Reason 		 VARCHAR(MAX),
	value 		 VARCHAR(MAX),
	AuditingStep INT
)

DECLARE @IfAudit int

IF NOT EXISTS(SELECT TOP 1 AuditingID FROM AuditingFlowSet where BillType=@BillType and Left(AuditingReason,1)<>'1' AND ifuse='1')
	RETURN 2
ELSE
	BEGIN
		SELECT TOP 1 @IfAudit=IfAudit FROM AuditingBill where BillnumberID=@nBillId AND BillindexType='2'
		IF @@ROWCOUNT = 0
			BEGIN
				INSERT #temp EXEC GP_BillAudtingCheckReason @nBillId,'00001'				
				IF EXISTS(SELECT TOP 1 1 FROM #temp WHERE PassFlag = 0)
					RETURN 4
				ELSE
					RETURN 3				
			END
		ELSE
			BEGIN	
				IF @IfAudit = -1
					BEGIN
						INSERT #temp EXEC GP_BillAudtingCheckReason @nBillId,'00001'				
						IF EXISTS(SELECT TOP 1 1 FROM #temp WHERE PassFlag = 0)
							RETURN 4
						ELSE
							RETURN 3
					END
				ELSE
					RETURN @IfAudit
			END
	END

DROP TABLE #temp




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
*/

CREATE PROCEDURE [dbo].[GP_CheckBillDetail]
(
	@dt		Tb_BillDetailCheck readonly,
	@flag		int,					--检查标识:1批号,2自由项,3货位,4业务员,5仓库,6订单,7成本控制,8成本提示,9售价低于成本、最近进价的明细,10负库存,11最低售价
	@ispass		int,					--是否过账:0否,1是
	@costsale	int,					--是否成本销售:0否,1是
	@stypeid	varchar(50),			--分支机构typeid
	@IfMulKType INT,					--是否启用多仓库:1是0否
	@IfSType	INT,					--是否启用分支机构
    @OperatorID varchar(50)				--操作员
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #TEMP(chkError VARCHAR(2000),rowNo INT,isGift INT)

declare @costing int
		,@checkcostprice varchar(1)
		,@salepricebelowcost varchar(1)
		,@lowpricequery	varchar(1)
		,@checkrecprice varchar(1)
		,@PtypeTaxPreSalePrice int
		
--SELECT @Digit=DecimalDigit,@fillZero = numberformat FROM DigitConfiguration WHERE ItemName='price'		
select @costing = SubValue from sysdata where SubName = 'costing'
select @PtypeTaxPreSalePrice = value from userconfig where configname = 'PtypeTaxPreSalePrice'

if @OperatorID = '00001'
	SELECT @checkcostprice=1,@salepricebelowcost=1,@checkrecprice=1,@lowpricequery=1
else
	SELECT @checkcostprice=SUBSTRING(lim,166,1),@salepricebelowcost=SUBSTRING(lim,4653,1),@checkrecprice=SUBSTRING(lim,2136,1),@lowpricequery=SUBSTRING(lim,710,1) FROM dbo.loginuser WHERE etypeid = @OperatorID
	

if @flag = 1
begin
	INSERT INTO #TEMP(chkError)
	SELECT '单据第'+dt.rowno+'行商品【'+dt.fullname+'】采用批号管理，请填写批号信息' as chkError FROM  @dt dt inner join ptype p on dt.typeid = p.typeid WHERE p.IfUseGoodsNum = 1 and dt.goodsnumber = '' 
	union all               
	SELECT '单据第'+dt.rowno+'行商品【'+dt.fullname+'】没有采用批号管理，不能填写批号' as chkError FROM @dt dt inner join ptype p on dt.typeid = p.typeid WHERE p.IfUseGoodsNum = 0 and dt.goodsnumber <> ''                
end
else if @flag = 2
begin
	INSERT INTO #TEMP(chkError)
	SELECT '单据第'+dt.rowno+'行商品【'+dt.fullname+'】属于自由项管理，请填写自由项信息' as chkError FROM @dt dt inner join ptype p on dt.typeid = p.typeid WHERE p.customitemid <> ''  and dt.itemid = 0  
end
else if @flag = 3
begin 
	INSERT INTO #TEMP(chkError)
	SELECT '单据第'+dt.rowno+'行商品【'+dt.fullname+'】货位没有填写或不属于该仓库或已删除，不能保存' as chkError FROM @dt dt where not exists(select top 1 1 from  dbo.CargoType c   WHERE c.KtypeID=dt.ktypeid and c.cargoid=dt.cargoid ) 
	union all 
	SELECT '单据第'+dt.rowno+'行商品【'+dt.fullname+'】货位已停用，不能保存' as chkError FROM @dt dt where exists(select top 1 1 from  dbo.CargoType c   WHERE c.KtypeID=dt.ktypeid and c.cargoid=dt.cargoid and c.deleted = 1 ) 
end
else if @flag = 4
begin
	INSERT INTO #TEMP(chkError)
	SELECT '【'+dt.efullname+'】 不是一个有效的内部职员，或者该职员不在您的管辖范围内！' as chkError FROM @dt dt where @OperatorID <> '00001' AND not exists(select top 1 1 from dbo.employee where typeid = dt.etypeid)
	UNION ALL
	SELECT '【'+dt.efullname+'】 不是一个有效的内部职员！' as chkError  FROM @dt dt WHERE Not exists(select top 1 1 from employee e where e.typeId = dt.etypeid and e.SonNum = 0 AND e.Deleted = 0) 
end
else if @flag = 5
begin
	if @IfMulKType = 1
	begin
		INSERT INTO #TEMP(chkError)
		SELECT '单据第 ['+dt.rowno+'] 行，没有选择仓库，请确认后重试！' FROM @dt dt WHERE dt.ktypeid = ''
		UNION ALL
		SELECT '单据第 ['+dt.rowno+'] 行，['+dt.kUserCode+']'+dt.kFullName+'不是一个有效的仓库，或者该仓库不在您的管辖范围内，'+case when @IfSType = 1 then '或者仓库的分支机构属性不一致，' else '' end +'请确认后重试！' 
		FROM @dt dt 
		where dt.ktypeid <> '' and (not exists(select top 1 1 from F_GetManDetailKType(@OperatorID) a where a.TypeId = dt.ktypeid)
			or Not exists(select top 1 1 from stock s where s.typeId = dt.ktypeid and s.STypeID = @stypeid and s.sonnum = 0))		
	end
	else
	begin
		INSERT INTO #TEMP(chkError)
		select '【'+dt.kfullname+'】不是单据头所选分支机构的仓库，请确认后再试！'
		FROM @dt dt 
		where dt.ktypeid <> '' and @stypeid <> '' and Not exists(select top 1 1 from stock s where s.typeId = dt.ktypeid and s.STypeID = @stypeid )	
	end
end
else if @flag = 6
begin
	INSERT INTO #TEMP(chkError)
	select '单据第['+dt.rowno+']行商品引用的订单记录已被删除或修改，请确认后重试！'
	FROM @dt dt 
	where not exists(select top 1 1 from OrderBill where OrderID = dt.orderid)
end
else if @flag = 7
begin	
	select *,goodsnumberprice as costprice INTO #dt7 from @dt
	
	if @costing <> 3
	begin
		;with avgcostprice as
		(
			SELECT dt.typeid, CAST(ISNULL(CAST(SUM(Total) AS NUMERIC(24,10))/CASE WHEN SUM(g.QTY)=0 THEN NULL ELSE SUM(g.QTY) END,0) AS numeric(24,10)) as costprice
			FROM #dt7 dt 
			left join GoodsStocks g on dt.typeid = g.PtypeId and dt.ktypeid = g.KtypeId
			group by dt.typeId
		)
		update #dt7 set costprice = c.costprice
		from avgcostprice c
		where c.typeid = #dt7.typeid
	end
	else
	begin
		;with avgcostprice as
		(
			SELECT dt.typeid, CAST(ISNULL(CAST(SUM(Total) AS NUMERIC(24,10))/CASE WHEN SUM(g.QTY)=0 THEN NULL ELSE SUM(g.QTY) END,0) AS numeric(24,10)) as costprice
			FROM #dt7 dt 
			left join GoodsStocks g on dt.typeid = g.PtypeId and dt.ktypeid = g.KtypeId
			group by dt.typeId
		)
		update #dt7 set costprice = c.costprice
		from avgcostprice c
		where c.typeid = #dt7.typeid and #dt7.goodsnumberprice < 0
	end
	
	if @ispass = 1 and @costsale <> 1 and @salepricebelowcost <> 1
	begin	
		INSERT INTO #TEMP(chkError,isgift)
		select	'商品:'+dt.fullname+'，售价 '+dbo.F_RoundDataToDisplay(dt.discountprice,'price')+' 低于当前成本均价 '+
				case when @checkcostprice = '1' then dbo.F_RoundDataToDisplay(dt.costprice,'price') else '****' end+' ,请修改单价后再过账！',
				isgift
		from	#dt7 dt
		where dt.discountprice < dt.costprice
	end
	
	if @costsale = 1 and exists(select top 1 1 from Userconfig where ConfigName = 'SaleOrderGift' and Value = 0)
	begin
		insert into #TEMP(chkError,isgift)
		select  '按成本价销售时，商品【'+fullname+'】成本价为0，请确认后再试！',
				isgift
		from #dt7
		where isgift = 0 and costprice = 0
	END
	
	--赠品低于成本价、最近进价不提示
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'giftptypecostprepricenotalert' AND Value = '1')
	BEGIN
		DELETE FROM #TEMP WHERE isgift = 1
	END
	
	drop table #dt7
end
else if @flag = 8
begin
	if exists(select top 1 1 from @dt where IsService = 0 )
	begin
		select *,goodsnumberprice as costprice into #dt8 from @dt  where IsService = 0
		
		if @costing <> 3
		begin
			;with avgcostprice as
			(
				SELECT dt.typeid, CAST(ISNULL(CAST(SUM(Total) AS NUMERIC(24,10))/CASE WHEN SUM(g.QTY)=0 THEN NULL ELSE SUM(g.QTY) END,0) AS numeric(24,10)) as costprice
				FROM #dt8 dt 
				left join GoodsStocks g on dt.typeid = g.PtypeId and dt.ktypeid = g.KtypeId
				group by dt.typeId
			)
			update #dt8 set costprice = c.costprice
			from avgcostprice c
			where c.typeid = #dt8.typeid
		end
		else
		begin
			;with avgcostprice as
			(
				SELECT dt.typeid, CAST(ISNULL(CAST(SUM(Total) AS NUMERIC(24,10))/CASE WHEN SUM(g.QTY)=0 THEN NULL ELSE SUM(g.QTY) END,0) AS numeric(24,10)) as costprice
				FROM #dt8 dt 
				left join GoodsStocks g on dt.typeid = g.PtypeId and dt.ktypeid = g.KtypeId
				group by dt.typeId
			)
			update #dt8 set costprice = c.costprice
			from avgcostprice c
			where c.typeid = #dt8.typeid and #dt8.goodsnumberprice < 0
		END
		
		
		
		INSERT INTO #TEMP(chkError)
		select '单据第'+rowno+'行商品【'+fullname+'】： 成本价（ '+case when @checkcostprice = '1' then dbo.F_RoundDataToDisplay(costprice,'price') else '****' end +'  元）为负！'
		from #dt8
		where costprice < 0 and (@ispass <>0 or @costing <> 3 or costprice <> -1)
		
		drop table #dt8
	end
end
else if @flag = 9
BEGIN

    CREATE TABLE #dt9
    (    
		rowno                  VARCHAR(10),		--行号               
		typeid                 VARCHAR(50),		--商品typeid        
		fullname               VARCHAR(200),	--商品名称     
		ktypeid                VARCHAR(50),		--仓库typeid
		kfullname				VARCHAR(200),	--仓库名称
		kusercode				VARCHAR(200),	--仓库编号
		cargoid			       INT,				--货位id                   
		GoodsNumber            VARCHAR(100),	--批号        
		itemid				   INT,				--自由项id  
		etypeid					VARCHAR(50),	--业务员typeid  
		efullname				VARCHAR(200),	--业务员名称 
		orderid					INT				--关联订单明细表orderbill中的orderid
		,discountprice			NUMERIC(24,10)	--折扣单价
		,goodsnumberprice		NUMERIC(24,10)	--批次成本价
		,isservice				INT				--是否服务商品
		,isgift					INT				--是否赠品
		,recprice				NUMERIC(24,10)	--最近进价
		,mdiscountprice			NUMERIC(24,10)	--大单位折扣单价
		,qty					NUMERIC(24,10)	--基本单位数量
		,taxprice				NUMERIC(24,10)	--含税单价
		,mtaxprice				NUMERIC(24,10)	--大单位含税单价
		,BeforePromoID			INT				--促销记录id
		,munitid				INT				--大单位id
		,costprice				NUMERIC(24,10)
		,[Type]					VARCHAR(200)
		,[Standard]				VARCHAR(200)
		
    )
	declare @underCostPriceAlert int
			,@alertSalePriceUnderRecPrice int
	select @underCostPriceAlert = Value from Userconfig where ConfigName = 'underCostPriceAlert'
	select @alertSalePriceUnderRecPrice = Value from Userconfig where ConfigName = 'alertSalePriceUnderRecPrice'
	
	IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='giftptypecostprepricenotalert' AND Value=1)
	BEGIN
		INSERT INTO #dt9
		select d.*,d.goodsnumberprice as costprice,p.[Type],p.[Standard] from @dt d 
		INNER JOIN dbo.ptype p ON d.typeid = p.typeid
		WHERE d.isgift=0
	END
	ELSE
	BEGIN
		INSERT INTO #dt9
		select d.*,d.goodsnumberprice as costprice,p.[Type],p.[Standard] from @dt d 
		INNER JOIN dbo.ptype p ON d.typeid = p.typeid
	END
	
	if @costing <> 3
	begin
		;with avgcostprice as
		(
			SELECT dt.typeid, CAST(ISNULL(CAST(SUM(Total) AS NUMERIC(24,10))/CASE WHEN SUM(g.QTY)=0 THEN NULL ELSE SUM(g.QTY) END,0) AS numeric(24,10)) as costprice
			FROM #dt9 dt 
			left join GoodsStocks g on dt.typeid = g.PtypeId and dt.ktypeid = g.KtypeId
			group by dt.typeId
		)
		update #dt9 set costprice = c.costprice
		from avgcostprice c
		where c.typeid = #dt9.typeid
	end
	else
	begin
		;with avgcostprice as
		(
			SELECT dt.typeid, CAST(ISNULL(CAST(SUM(Total) AS NUMERIC(24,10))/CASE WHEN SUM(g.QTY)=0 THEN NULL ELSE SUM(g.QTY) END,0) AS numeric(24,10)) as costprice
			FROM #dt9 dt 
			left join GoodsStocks g on dt.typeid = g.PtypeId and dt.ktypeid = g.KtypeId
			group by dt.typeId
		)
		update #dt9 set costprice = c.costprice
		from avgcostprice c
		where c.typeid = #dt9.typeid and #dt9.goodsnumberprice < 0
	end

	select rowindex,pfullname,discountprice,case when @checkcostprice = 1 then newdispcostprice else '****' end as dispcostprice
	,mdiscountprice, case when @checkrecprice = 1 then newdisprecprice else '****' end as disprecprice,[Type],[Standard],1 showProInfo,isgift
	from
	(
		select rowno as rowindex,fullname as pfullname, discountprice,[Type],[Standard]
		,case when @underCostPriceAlert = 1 or discountprice >= costprice then '/' else dbo.F_RoundDataToDisplay(costprice , 'price') end as newdispcostprice
		, mdiscountprice
		,case when @alertSalePriceUnderRecPrice = 0 or mdiscountprice >= recprice then '/' else dbo.F_RoundDataToDisplay(recprice , 'price') end as newdisprecprice,isgift
		from #dt9
	) t9
	where newdispcostprice <> '/' or newdisprecprice <> '/'
	
	return
end
else if @flag = 10
begin
	;with stocksqty as
	(
		SELECT dt.typeid,dt.ktypeid, ISNULL(SUM(s.Qty),0) AS Qty FROM @dt dt 
		left join GoodsStocks s on dt.typeid = s.ptypeid and dt.ktypeid = s.ktypeid
		where dt.IsService = 0
		group by dt.typeid,dt.ktypeid
	)
	INSERT INTO #TEMP(chkError)
	select '单据第'+rowno+'行商品【'+fullname+'】过账后，会造成库存数量为负！'
	from @dt dt
	left join stocksqty s on s.typeid = dt.typeid and s.ktypeid = dt.ktypeid
	where dt.IsService = 0 and (s.qty <=0 or s.qty <dt.qty)
end
else if @flag = 11
begin
	IF EXISTS(SELECT TOP 1 pricetype FROM stype WHERE TypeId=@STypeID AND PriceType = 1)
	BEGIN
		;with lowsaleprice as
		(
			select dt.rowno,dt.typeid, isnull(mps.lowsaleprice,0) as mlowsaleprice, ISNULL(ps.LowSalePrice,0) as lowsaleprice from @dt dt
			left join ptype_stypeprice mps on mps.ptypeid = dt.typeid and mps.stypeid = @stypeid and mps.UnitID=dt.munitid
			left join ptype_stypeprice ps on ps.ptypeid = dt.typeid and ps.stypeid = @stypeid and ps. IsDefaultUnit=1
			where dt.BeforePromoID = 0 and dt.isgift = 0
		)
		INSERT INTO #TEMP(chkError,rowNo,isgift)
		select '单据第'+dt.rowno+'行商品【'+fullname+'】售价（ '
		+dbo.F_RoundDataToDisplay(case when @PtypeTaxPreSalePrice = 0 and lp.mlowsaleprice <= 0 then dt.discountprice 
			when @PtypeTaxPreSalePrice = 0 and lp.mlowsaleprice > 0 then dt.mdiscountprice
			when @PtypeTaxPreSalePrice = 1 and lp.mlowsaleprice <= 0 then dt.taxprice
			when @PtypeTaxPreSalePrice = 1 and lp.mlowsaleprice > 0 then dt.mtaxprice
			else dt.discountprice end , 'price')    
		+'  元）低于最低售价（ '+case when @lowpricequery = '1' then dbo.F_RoundDataToDisplay(case when lp.mlowsaleprice <=0 then lp.lowsaleprice else lp.mlowsaleprice end , 'price') else '****' end +'  元）！'
		,dt.rowno,dt.isgift
		from @dt dt
		left join lowsaleprice lp on lp.typeid = dt.typeid and lp.rowno = dt.rowno
		where dt.BeforePromoID = 0 and dt.isgift = 0 
		and ((@PtypeTaxPreSalePrice = 0 and lp.mlowsaleprice <= 0 and dt.discountprice < lp.lowsaleprice) 
				or (@PtypeTaxPreSalePrice = 0 and lp.mlowsaleprice > 0 and dt.mdiscountprice < lp.mlowsaleprice) 
				or (@PtypeTaxPreSalePrice = 1 and lp.mlowsaleprice <= 0 and dt.taxprice < lp.lowsaleprice)
				or (@PtypeTaxPreSalePrice = 1 and lp.mlowsaleprice > 0 and dt.mtaxprice < lp.mlowsaleprice)
			)
	END
	ELSE
	BEGIN
		;with lowsaleprice as
		(
			select dt.rowno, dt.typeid, isnull(mp.lowsaleprice,0) as mlowsaleprice, ISNULL(p.LowSalePrice,0) as lowsaleprice from @dt dt
			left join ptype_price mp on mp.ptypeid = dt.typeid and mp.UnitID=dt.munitid
			left join ptype_price p on p.ptypeid = dt.typeid and p.IsDefaultUnit=1
			where dt.BeforePromoID = 0 and dt.isgift = 0
		)
		INSERT INTO #TEMP(chkError,rowNo,isgift)
		select '单据第'+dt.rowno+'行商品【'+fullname+'】售价（ '
		+dbo.F_RoundDataToDisplay(case when @PtypeTaxPreSalePrice = 0 and lp.mlowsaleprice <= 0 then dt.discountprice 
			when @PtypeTaxPreSalePrice = 0 and lp.mlowsaleprice > 0 then dt.mdiscountprice
			when @PtypeTaxPreSalePrice = 1 and lp.mlowsaleprice <= 0 then dt.taxprice
			when @PtypeTaxPreSalePrice = 1 and lp.mlowsaleprice > 0 then dt.mtaxprice
			else dt.discountprice end ,'price')  
		+'  元）低于最低售价（ '+case when @lowpricequery = '1' then dbo.F_RoundDataToDisplay(case when lp.mlowsaleprice <=0 then lp.lowsaleprice else lp.mlowsaleprice end ,'price') else '****' end +'  元）！'
		,dt.rowno,dt.isgift
		from @dt dt
		left join lowsaleprice lp on lp.typeid = dt.typeid and lp.rowno = dt.rowno
		where dt.BeforePromoID = 0 and dt.isgift = 0 
		and ((@PtypeTaxPreSalePrice = 0 and lp.mlowsaleprice <= 0 and dt.discountprice < lp.lowsaleprice) 
				or (@PtypeTaxPreSalePrice = 0 and lp.mlowsaleprice > 0 and dt.mdiscountprice < lp.mlowsaleprice) 
				or (@PtypeTaxPreSalePrice = 1 and lp.mlowsaleprice <= 0 and dt.taxprice < lp.lowsaleprice)
				or (@PtypeTaxPreSalePrice = 1 and lp.mlowsaleprice > 0 and dt.mtaxprice < lp.mlowsaleprice)
			)
	END
	
	--赠品低于成本价、最近进价不提示
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'giftptypecostprepricenotalert' AND Value = '1')
	BEGIN
		DELETE FROM #TEMP WHERE isgift = 1
	END
end

SELECT * FROM #TEMP

DROP TABLE #TEMP

GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- ========================================================================
CREATE  PROCEDURE GP_CheckBillRedWord
(
	@chvBillNumberID	varchar(100),	-- 单据编号
	@chrBillType		VARCHAR(10)		-- 单据查询样式
)
--@encode$--

AS
SET NOCOUNT ON
     
CREATE  TABLE #CurCouponCode
(	couponcode VARCHAR(200)
)

IF @chrBillType=423
BEGIN
---敏捷4631 优惠券查询过慢
--优惠券入库单
	DECLARE @inBillcode VARCHAR(MAX)  
	SELECT @inBillcode = CouponCode FROM coupon_inBill WHERE BillNumberId =@chvBillNumberID  

	INSERT INTO #CurCouponCode
	        ( couponcode )
	SELECT * FROM f_split(@inBillcode,'я')
	IF EXISTS (SELECT TOP 1 1 FROM coupon_codeinfo c INNER JOIN #CurCouponCode cur ON c.couponcode=cur.couponcode WHERE c.[state] IN (2,3,5,6) )
		RETURN 1;	
END
ELSE IF @chrBillType=424
BEGIN
---敏捷4631 优惠券查询过慢
--优惠券出库单
	DECLARE @OutBillBillcode VARCHAR(MAX)  
	SELECT @OutBillBillcode = CouponCode FROM coupon_OutBill WHERE BillNumberId =@chvBillNumberID  

	INSERT INTO #CurCouponCode
	        ( couponcode )
	SELECT * FROM f_split(@OutBillBillcode,'я')
	IF EXISTS (SELECT TOP 1 1 FROM coupon_codeinfo c INNER JOIN #CurCouponCode cur ON c.couponcode=cur.couponcode WHERE c.[state] IN (3,5) )
		RETURN 2;	
		
	--如果有出库单被退货单调用，则直接返回
	IF EXISTS(SELECT TOP 1 1 FROM Coupon_OutBill cout 
								INNER JOIN Coupon_BackBill cb ON  cout.id = cb.OutBillId 
								INNER JOIN dbo.Coupon_BillIndex bi ON cb.BillNumberId=bi.BillNumberId
								WHERE  cout.BillNumberId = @chvBillNumberID AND bi.redword=0 AND bi.ifcheck='t' AND bi.draft=0)
		RETURN 6
END
ELSE IF @chrBillType=425
BEGIN
---敏捷4631 优惠券查询过慢
--优惠券调拨单
	DECLARE @AllotBillcode VARCHAR(MAX)  
	SELECT @AllotBillcode = CouponCode FROM Coupon_AllotBill WHERE BillNumberId =@chvBillNumberID  
	INSERT INTO #CurCouponCode
	        ( couponcode )
	SELECT * FROM f_split(@AllotBillcode,'я')

	DECLARE @KTYPEID VARCHAR(50)
	SELECT @KTYPEID =[InKTypeId] FROM dbo.Coupon_BillIndex WHERE BILLNUMBERID =@chvBillNumberID
	IF EXISTS (SELECT TOP 1 1 FROM coupon_codeinfo c INNER JOIN #CurCouponCode cur ON c.couponcode=cur.couponcode WHERE C.KtypeId <> @KTYPEID)
		RETURN 3; --调拨后 已经又被调到其他库去了
	IF EXISTS (SELECT TOP 1 1 FROM coupon_codeinfo c INNER JOIN #CurCouponCode cur ON c.couponcode=cur.couponcode WHERE c.[state] IN (2,3,5,6) )
		RETURN 4;

END
ELSE IF @chrBillType=426
BEGIN
---敏捷4631 优惠券查询过慢
--优惠券退货单
	DECLARE @BackBillcode VARCHAR(MAX)  
	SELECT @BackBillcode = CouponCode FROM Coupon_BackBill WHERE BillNumberId =@chvBillNumberID  
	INSERT INTO #CurCouponCode
	        ( couponcode )
      SELECT * FROM f_split(@BackBillcode,'я')
	IF EXISTS (SELECT TOP 1 1 FROM coupon_codeinfo c INNER JOIN #CurCouponCode cur ON c.couponcode=cur.couponcode WHERE c.[state] IN (2,3,5,6) )
		RETURN 5;
END
ELSE IF @chrBillType = 428 --优惠券分支机构调拨入库单
BEGIN
	DECLARE @inStypeBillcode VARCHAR(MAX)  
	SELECT @inBillcode = CouponCode FROM Coupon_AllotBillStype WHERE BillNumberId =@chvBillNumberID  

	INSERT INTO #CurCouponCode
	(
		couponcode 
	)
	SELECT * FROM f_split(@inBillcode,'я')
	
	IF EXISTS (SELECT TOP 1 1 FROM coupon_codeinfo c INNER JOIN #CurCouponCode cur ON c.couponcode=cur.couponcode WHERE c.[state] IN (2,3,5,6) )
		RETURN 8;		
END
ELSE IF @chrBillType = 429 --优惠券分支机构调拨出库单
BEGIN
	SELECT @OutBillBillcode = CouponCode FROM Coupon_AllotBillStype WHERE BillNumberId =@chvBillNumberID  

	INSERT INTO #CurCouponCode
	( 
		couponcode 
	)	
	SELECT * FROM f_split(@OutBillBillcode,'я')
	
	IF EXISTS (SELECT TOP 1 1 FROM coupon_codeinfo c INNER JOIN #CurCouponCode cur ON c.couponcode=cur.couponcode WHERE c.[state] IN (1) )
		RETURN 7;		
END	

IF EXISTS (SELECT * FROM dbo.Coupon_CodeInOut i
			INNER JOIN #CurCouponCode c on i.CouponCode=c.couponcode
			INNER JOIN dbo.Coupon_BillIndex B ON I.BillNumberId=B.BillNumberId
			WHERE B.PostTime>(SELECT PostTime FROM Coupon_BillIndex a WHERE  a.BillNumberId=@chvBillNumberID) AND B.RedWord=0 AND B.ifcheck='t' AND B.draft=0
			)
RETURN 7;

DROP TABLE #CurCouponCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_CheckBrandarBalanceByBrandar]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_CheckBrandarBalanceByBrandar];
GO

/*
	作者:shushan
	日期:
	描述:
*/
CREATE  PROCEDURE Gp_CheckBrandarBalanceByBrandar
( 
	@moneybillnumberid 	INT --收款单

)
    --@encode$--
AS
    SET NOCOUNT ON;
    BEGIN
		IF NOT EXISTS(SELECT 1 FROM billindex  WHERE BillNumberId=@moneybillnumberid AND billtype =4)
			RETURN 0;
		ELSE 
		BEGIN 
			CREATE TABLE #CurBillComplete
			( 
				brandartypeid VARCHAR(50),
				CompleteTotal NUMERIC(24,10),
				NCompleteTotal NUMERIC(24,10)
			)
					
			INSERT INTO  #CurBillComplete
					(	
						brandartypeid ,
						CompleteTotal ,
						NCompleteTotal 	
					)	
			SELECT  brandartypeid,
					sum(isnull(CompleteTotal,0)),
					sum(isnull(NCompleteTotal,0))	
			FROM (	
					SELECT	c.brandartypeid AS  brandartypeid,
						isnull(C.CompleteTotal,0)  AS  CompleteTotal,
						isnull(C.NCompleteTotal,0) AS  NCompleteTotal
				FROM dbo.CompleteBrandarTotal c
				WHERE c.MoneyBillID=@moneybillnumberid
				UNION ALL
				SELECT	P.brandartypeid AS  brandartypeid ,
						isnull(C.CompleteGoodTotal,0) AS  CompleteTotal ,
						isnull(C.NCompleteGoodTotal,0) AS  NCompleteTotal
				FROM dbo.CompleteGoodTotal c
				LEFT JOIN dbo.ptype p ON c.PtypeID=p.typeid
				WHERE c.MoneyBillID=@moneybillnumberid
			) a GROUP BY  a.brandartypeid
			declare @beEqual INT -- 必须一致
			SELECT  @beEqual=value FROM userconfig WHERE configname='gatherbillmoneynotgtcomplete'
			
			IF @beEqual=1 and EXISTS (
					SELECT 1 
					FROM #CurBillComplete C
					LEFT JOIN (SELECT brandartypeid,
										SUM(total+PreferenceMoney) AS CompleteTotal,
										SUM(ntotal+nPreferenceMoney)  AS NCompleteTotal
								FROM dbo.gatheringBill 
								WHERE BillNumberId=@moneybillnumberid
								GROUP BY brandartypeid) g ON c.brandartypeid=g.brandartypeid
					WHERE c.CompleteTotal<>ISNULL(g.CompleteTotal,0) AND c.nCompleteTotal<>ISNULL(g.nCompleteTotal,0)
					
			)
			RETURN 1 --结算界面里的各明细行品牌名称结算金额总和和收款单明细行里品牌名称的收款金额保持一致
		
		--如果不是必须一致 则不能>
		IF @beEqual=0 AND  EXISTS (
					SELECT 1 
					FROM #CurBillComplete C
					LEFT JOIN (SELECT brandartypeid,
										SUM(total+PreferenceMoney) AS CompleteTotal,
										SUM(ntotal+nPreferenceMoney)  AS NCompleteTotal
								FROM dbo.gatheringBill 
								WHERE BillNumberId=@moneybillnumberid
								GROUP BY brandartypeid) g ON c.brandartypeid=g.brandartypeid
					WHERE c.CompleteTotal>ISNULL(g.CompleteTotal,0) AND c.nCompleteTotal>ISNULL(g.nCompleteTotal,0)
					
			)
			
			RETURN 2 --
			
		END 
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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






IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CheckChildAccountUsage]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CheckChildAccountUsage] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2012-06-14
----描述：检查会计科目子节点是否使用
----========================
CREATE    PROCEDURE [dbo].[GP_CheckChildAccountUsage]
(
 @stypeid VARCHAR(50),
 @atypeid VARCHAR(50)
)
--@encode$--
AS 
DECLARE @subused INT

SET @subused = 0

SELECT IDENTITY(INT,1,1)AS rid,typeid 
INTO #t1
FROM Ac_Account
WHERE StypeId = @stypeid
AND ParId LIKE @atypeid+'%'

DECLARE @i INT
DECLARE @count INT
DECLARE @typeid VARCHAR(50)


WHILE @i <= @count AND @subused = 0
BEGIN
	SELECT @typeid = typeid FROM #t1 WHERE rid = @i
	
	EXEC @subused = GP_CheckAccountUsage @stypeid = @stypeid, -- varchar(50)
	    @atypeid = @typeid -- varchar(50)	
END

DROP TABLE #t1

IF @subused > 0
    RETURN 1
RETURN 0

GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		检验按商品结算数据是否有错误
-- 最后修改作者：	haiquan
-- 最后修改时间：	2007-04-11
-- ========================================================================
CREATE         PROCEDURE [GP_CheckCompleteGoodTotal]
(
	@GoodsBillid int,
	@BillType	int
)
--@encode$--
AS
SET NOCOUNT ON 

	DECLARE @id int
	DECLARE	@QTY  NUMERIC(24, 10) 
	DECLARE	@IsOK  NUMERIC(24, 10) 
		if @BillType=34 
			DECLARE ALLBill CURSOR FOR  SELECT [id] from buybill WHERE BillNumberid=@GoodsBillId
		if @BillType= 6 
			DECLARE ALLBill CURSOR FOR  SELECT [id] from BuyBackBill WHERE BillNumberid=@GoodsBillId --采购退货单
		if @BillType= 161 
			DECLARE ALLBill CURSOR FOR  SELECT [id] from BuyGoodsExchangeBill WHERE BillNumberid=@GoodsBillId	--采购换货单
		if @BillType= 145 
		    DECLARE ALLBill CURSOR FOR  SELECT [id] from CommissionBill WHERE BillNumberid=@GoodsBillId   --受托代销结算单
		if @BillType= 11
		    DECLARE ALLBill CURSOR FOR  SELECT [id] from SaleBill WHERE BillNumberid=@GoodsBillId   --销售出库单
		if @BillType= 12
		    DECLARE ALLBill CURSOR FOR  SELECT [id] from PT_Combin_SaleBill WHERE BillNumberid=@GoodsBillId 
		if @BillType= 45 
		    DECLARE ALLBill CURSOR FOR  SELECT [id] from SaleBackBill WHERE BillNumberid=@GoodsBillId   --销售退货单
		if @BillType= 46
		    DECLARE ALLBill CURSOR FOR  SELECT [id] from PT_Combin_SaleBackBill WHERE BillNumberid=@GoodsBillId
		if @BillType= 160
		    DECLARE ALLBill CURSOR FOR  SELECT [id] from SaleGoodsExchangeBill WHERE BillNumberid=@GoodsBillId   -- --销售换货单	
		if @BillType= 141
		    DECLARE ALLBill CURSOR FOR  SELECT [id] from CommissionBill WHERE BillNumberid=@GoodsBillId   --委托代销结算单
		IF @BillType = 167	-- 新维修 - 取件单
			DECLARE ALLBill CURSOR FOR  SELECT [id] from wx_Bill_GetBack WHERE BillNumberid=@GoodsBillId
		IF @BillType = 168	-- 新维修 - 整机更换单
			DECLARE ALLBill CURSOR FOR  SELECT [id] from wx_Bill_Replace WHERE BillNumberid=@GoodsBillId
		IF @BillType = 170	-- 新维修 - 送修返回单
			DECLARE ALLBill CURSOR FOR  SELECT [id] from wx_Bill_SendBack WHERE BillNumberid=@GoodsBillId
		IF @BillType=400
			DECLARE ALLBill	CURSOR FOR  SELECT [id] FROM AppraisalBill WHERE BillnumberID=@GoodsBillID
		IF @BillType=401
			DECLARE ALLBill CURSOR FOR  SELECT [id] FROM AppraisalBackBill WHERE BillNumberID=@GoodsBillID
		IF @BillType=402
			DECLARE ALLbill CURSOR FOR  SELECT [id] FROM SendBill     WHERE BillNUmberID=@GoodsBillID
		IF @BillType=403
			DECLARE ALLBill CURSOR FOR  SELECT [id] FROM SendBackBill  WHERE BillNumberID=@GoodsBillID
		IF @BillType IN (404,405)
			DECLARE ALLBill CURSOR FOR  SELECT [id] FROM ReceiptBill WHERE BillNumberID=@GoodsBillID
		OPEN AllBill
			 FETCH NEXT FROM AllBill INTO @id
					
				WHILE ( @@FETCH_STATUS = 0 )
				  BEGIN
					if @BillType=34 
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN BuyBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
						
					if @BillType=400
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN AppraisalBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
						
					if @BillType=6
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN BuyBackBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
						
					if @BillType=401
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN AppraisalBackBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
						
					if @BillType=161 
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN BuyGoodsExchangeBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
					if @BillType=145 
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN CommissionBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
					if @BillType=11 
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN SaleBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
					if @BillType=12 
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN PT_Combin_SaleBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
						
					if @BillType=402 
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN SendBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
						
					if @BillType=45
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN SaleBackBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
					if @BillType=46
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN PT_Combin_SaleBackBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
						
					if @BillType=403
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN SendBackBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
						
					if @BillType=160 
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN SaleGoodsExchangeBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
					if @BillType=141 
						BEGIN
									SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
									FROM CompleteGoodTotal A
										 LEFT JOIN CommissionBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
						END
					IF @BillType = 167	-- 新维修 - 取件单
					BEGIN
						SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
						FROM CompleteGoodTotal A
							 LEFT JOIN wx_Bill_GetBack B 
							 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
						WHERE B.BillNumberid=@GoodsBillId
							  AND B.[id]=@id
							  AND A.draft=0
							  AND A.BillType=@BillType
						GROUP BY B.QTY

						IF @IsOK>0
						BEGIN
							CLOSE ALLBill	-- 关闭游标
							DEALLOCATE AllBill	-- 释放游标所使用的资源		
							RETURN 4 --收付款金额大于实际金额

						END
						FETCH NEXT FROM ALLBill INTO @id
					END
					IF @BillType = 168	-- 新维修 - 整机更换单
					BEGIN
						SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
						FROM CompleteGoodTotal A
							 LEFT JOIN wx_Bill_Replace B 
							 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
						WHERE B.BillNumberid=@GoodsBillId
							  AND B.[id]=@id
							  AND A.draft=0
							  AND A.BillType=@BillType
						GROUP BY B.QTY

						IF @IsOK>0
						BEGIN
							CLOSE ALLBill	-- 关闭游标
							DEALLOCATE AllBill	-- 释放游标所使用的资源		
							RETURN 4 --收付款金额大于实际金额

						END
						FETCH NEXT FROM ALLBill INTO @id
					END
					IF @BillType = 170	-- 新维修 - 送修返回单
					BEGIN
						SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-B.QTY) 
						FROM CompleteGoodTotal A
							 LEFT JOIN wx_Bill_SendBack B 
							 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
						WHERE B.BillNumberid=@GoodsBillId
							  AND B.[id]=@id
							  AND A.draft=0
							  AND A.BillType=@BillType
						GROUP BY B.QTY

						IF @IsOK>0
						BEGIN
							CLOSE ALLBill	-- 关闭游标
							DEALLOCATE AllBill	-- 释放游标所使用的资源		
							RETURN 4 --收付款金额大于实际金额

						END
						FETCH NEXT FROM ALLBill INTO @id
					END
					
					IF @BillType IN (404,405)
					BEGIN
						SELECT @IsOK=(Sum(ABS(CompleteGoodQTY))-ABS(B.QTY)) 
									FROM CompleteGoodTotal A
										 LEFT JOIN ReceiptBill B 
										 ON(A.GoodsBillid=B.BillNumberId AND A.Billid=B.[id]) 
									WHERE B.BillNumberid=@GoodsBillId
										  AND B.[id]=@id
										  AND A.draft=0
										  AND A.BillType=@BillType
									GROUP BY B.QTY
										IF @IsOK>0
											BEGIN
												CLOSE ALLBill	-- 关闭游标
												DEALLOCATE AllBill	-- 释放游标所使用的资源		
				
												RETURN 4 --收付款金额大于实际金额
				
											END
				
										FETCH NEXT FROM ALLBill INTO @id
					END
				  END


	CLOSE ALLBill	-- 关闭游标
	DEALLOCATE AllBill	-- 释放游标所使用的资源		
--------------------------------------------- 判断按商品结算单据是否已经被核销 start--------------------------------------------
	IF @BillType IN (404,405)
		BEGIN
			IF EXISTS(SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@GoodsBillId AND ChargeOffTotal>0)
				RETURN 10 --按商品结算的单据已经被核销,不允许再按商品结算 
		END 
	ELSE 
	BEGIN
		IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillNumberID=@GoodsBillId AND ChargeOffTotal>0)
			RETURN 10 --按商品结算的单据已经被核销,不允许再按商品结算 
	END
--------------------------------------------- 判断按商品结算单据是否已经被核销    end--------------------------------------------

	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	shushan
	Date	:	
	Description	: 检查整单退货
*/
CREATE PROCEDURE Gp_CheckCouponRetireBack
(
	@billnumberids VARCHAR(MAX),
	@DetailIds		VARCHAR(MAX),
	@billtype		INT
)
--@encode$--
AS
SET NOCOUNT ON 
IF NOT EXISTS(SELECT TOP 1 1  FROM coupon_billused  WHERE BillnumberId IN (SELECT A FROM dbo.f_split(@billnumberids,',')))
SELECT 1 AS intRet; --没有使用优惠券的单据
ELSE 
BEGIN	
	IF @DetailIds=''
	SELECT 0 AS intRet --没有整单退货
	DECLARE @TABLENAME VARCHAR(50),@SQL VARCHAR(2000)
	SELECT @TABLENAME=detailTable FROM dbo.BillName WHERE billtype IN (@billtype)
	SELECT @SQL='
				IF EXISTS (SELECT TOP 1 1  
							FROM '+@TABLENAME+' A 
							INNER JOIN (	
										SELECT DISTINCT BILLNUMBERID FROM coupon_billused  WHERE BillnumberId IN ('+@billnumberids+')
										)B ON A.BillnumberId=B.BillnumberId
							 WHERE  A.id NOT IN ('+@DetailIds+'))
					SELECT 0 AS intRet --没有整单退货
				ELSE
					SELECT 1  AS intRet 
	'
	EXEC (@sql)

	
END



SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- =======================================================================================
-- 功能说明：		检查数据表 LoginUser 中操作员数是否满足版本用户数 ( 试用版为 5 用户 )
-- 最后修改作者：	卢    春
-- 最后修改时间：	2003-07-31
-- =======================================================================================
CREATE       PROCEDURE GP_CheckCurLoginUserCountForASP
(
	@chvOperator		varchar(100),	-- 操作员 ID 值
	@intOpCounter		int output,		-- 软件狗用户数
	@intCurOpCounter	int output		-- 当前数据表 LoginUser 中操作员数
)
--@encode$--
AS
	SET NOCOUNT ON
		
	-- 超级用户忽略检查用户数，其他操作员登录时将会检查
	IF EXISTS(
		SELECT	1
		FROM	LoginUser
		WHERE	ETypeID = @chvOperator
				AND SysID = '1'
				AND ETypeID = '00001'
	)
		RETURN 0

	-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********

	DECLARE @intLoginUserCount int
	SELECT	@intLoginUserCount = COUNT(*)
	FROM	LoginUser
	WHERE	IsErp = 1

	DECLARE @N int, @intVersion int
	-- 判断版本号，是否试用版
	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 2

	IF @N IS NULL RETURN 2

	DECLARE @intBit int, @intMask int
	SELECT @intBit = @N & 15
	SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
	SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

	-- 判断软件狗用户数
	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 3	-- 检查用户数

	IF @N IS NULL RETURN 2

	IF @intVersion IN (2,3,5,7,9,11,13,15 )	-- 试用版  V3/A8是5用户 V1是3用户
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE subname = 'Proinfo' AND SubValue = '4')
				SELECT @intOpCounter = 3	-- 3 用户
			ELSE			
				SELECT @intOpCounter = 5	-- 5 用户
		END
	ELSE
		BEGIN
			SELECT @intOpCounter = ( ( POWER(2,18) - 1 ) & @N ) / 4
			IF ( 3 & @N <> 3 ) RETURN 2
		END

	-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - End	********

	-- 检查数据表 LoginUser 中当前操作员数 ( 包含超级用户 Admin )
	SELECT	@intCurOpCounter = COUNT(*)
	FROM	LoginUser
	WHERE	IsErp = 1
	
	IF @intCurOpCounter - 1 > @intOpCounter
		RETURN 1	-- 当前操作数员大于软件狗用户数
	ELSE
		RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_checkDtypeIfUsed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_checkDtypeIfUsed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-08-02
--	描述：检查部门在该分支机构计划中是否引用过
---------------------------------------------
CREATE PROCEDURE GP_checkDtypeIfUsed
( 
	@OperatorID	VARCHAR(100),  			-- 操作员
	@dtypeid	VARCHAR(50),			--部门ID
	@splanid	VARCHAR(MAX),			--分支机构销售计划id
	@dplanid	VARCHAR(MAX),
	@ifmodify	VARCHAR(MAX)='1'			--是否启用分支机构
)
--@encode$--
AS
SET NOCOUNT ON
CREATE TABLE #Dtype (TypeID varchar(50))
INSERT INTO #Dtype select typeid from F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)
IF @ifmodify='1'
BEGIN
	SELECT  @splanid=SA.ID
	FROM	StypeSaleAllPlan SA
	INNER JOIN StypeSaleplan SP ON SA.ID=SP.SplanID
	INNER JOIN DtypeSaleAllPlan DA ON DA.STypePlanID=SP.ID
	WHERE DA.ID=@dplanid
END


DECLARE @SQL VARCHAR(MAX)
SET @SQL='
SELECT	DP.DtypeID,
		s.FullName AS sfullname,
		d.FullName AS dfullname
FROM	DtypeSaleAllPlan DA
INNER JOIN StypeSaleplan SP ON SP.ID=DA.STypePlanID
INNER JOIN DtypeSaleplan DP ON DA.ID=DP.DplanID
INNER JOIN Stype S ON S.TypeId=SP.StypeID
INNER JOiN Department D ON D.typeid=Dp.DtypeID
WHERE	1=1 
AND		SP.SplanID='''+@splanid+'''
AND		DP.DtypeID IN (SELECT TypeID FROM #Dtype)'
IF @dplanid<>'' OR @dplanid IS NOT NULL
BEGIN
	SET @SQL=@SQL+' AND DA.ID<>'''+@dplanid+''''
END
EXEC (@SQL)
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_CheckedAcVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_CheckedAcVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查询复核
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_CheckedAcVoucherBill
(
	@BillNumberId	VARCHAR(50)='',			--单据ID
	@OpertionId		VARCHAR(50)=''			--操作人
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@fchecked		VARCHAR(2)='',
	@recheckid		VARCHAR(2)='',
	@ifcheck		VARCHAR(2)='',
    @markerror		VARCHAR(200)='',
	@ErrorCount		INT=0 --审核 复核 过账 错误条数
	
SELECT 
	@fchecked=ISNULL(FChecked,''),
	@recheckid=ISNULL(ReCheckId,''),
	@ifcheck=ISNULL(IfCheck,''),
    @markerror=isnull(markerror,'')
FROM Ac_Voucher
WHERE BillNumberId=@BillNumberId 
		 
IF @@ROWCOUNT = 0--判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN -1
END
DECLARE @SubValue VARCHAR(2)=''
SELECT @SubValue=ISNULL(SubValue,'') FROM sysdata WHERE SubName='acvhrchk'

IF(@ifcheck='t')
	BEGIN
		RAISERROR('凭证已经记账!请确认！',16,1)--记账
		RETURN -1
	END
IF(@recheckid <>'')
	BEGIN
		RAISERROR('凭证已经复核!请确认！',16,1)--/复核
		RETURN -1
	END
IF(@fchecked='-1')
	BEGIN
		RAISERROR('凭证已经作废!请确认！',16,1)--/作废
		RETURN -1
	END

IF(@markerror<>'')
	BEGIN
		RAISERROR('凭证已经标错!请确认！',16,1)--/审核
		RETURN -1
	END
	
UPDATE Ac_Voucher SET ReCheckId=@OpertionId WHERE BillNumberId=@BillNumberID--复核 凭证主表
SET @ErrorCount+=@@ERROR
IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='复核凭证单据错误，请确认！'
		RAISERROR(@MSG2,16,1) 
		RETURN -1
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_CheckGoodBalanceByBrandar]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_CheckGoodBalanceByBrandar];
GO

/*
	作者:shushan
	日期:
	描述:
*/
CREATE  PROCEDURE Gp_CheckGoodBalanceByBrandar
( 
	@moneybillnumberid 	INT --收款单

)
    --@encode$--
AS
    SET NOCOUNT ON;
    BEGIN
		IF NOT EXISTS(SELECT 1 FROM billindex  WHERE BillNumberId=@moneybillnumberid AND billtype =4)
			RETURN 0;
		ELSE 
		BEGIN 
			CREATE TABLE #CurBillComplete
			( 
				brandartypeid VARCHAR(50),
				CompleteGoodTotal NUMERIC(24,10),
				NCompleteGoodTotal NUMERIC(24,10)
			)
					
			INSERT INTO  #CurBillComplete
					(	
						brandartypeid ,
						CompleteGoodTotal ,
						NCompleteGoodTotal 	
					)		
			SELECT	P.brandartypeid,
					SUM(C.CompleteGoodTotal) ,
					SUM(C.NCompleteGoodTotal)
			FROM dbo.CompleteGoodTotal c
			LEFT JOIN dbo.ptype p ON c.PtypeID=p.typeid
			WHERE c.MoneyBillID=@moneybillnumberid
			GROUP BY p.brandartypeid
			
			declare @beEqual INT -- 必须一致
			SELECT  @beEqual=value FROM userconfig WHERE configname='gatherbillmoneynotgtcomplete'
			
			IF @beEqual=1 and EXISTS (
					SELECT 1 
					FROM #CurBillComplete C
					LEFT JOIN (SELECT brandartypeid,
										SUM(total+PreferenceMoney) AS CompleteGoodTotal,
										SUM(ntotal+nPreferenceMoney)  AS NCompleteGoodTotal
								FROM dbo.gatheringBill 
								WHERE BillNumberId=@moneybillnumberid
								GROUP BY brandartypeid) g ON c.brandartypeid=g.brandartypeid
					WHERE c.CompleteGoodTotal<>ISNULL(g.CompleteGoodTotal,0) AND c.nCompleteGoodTotal<>ISNULL(g.nCompleteGoodTotal,0)
					
			)
			RETURN 1 --按商品结算界面里的各明细行品牌名称结算金额总和和收款单明细行里品牌名称的收款金额保持一致
		
		--如果不是必须一致 则不能>
		IF @beEqual=0 AND  EXISTS (
					SELECT 1 
					FROM #CurBillComplete C
					LEFT JOIN (SELECT brandartypeid,
										SUM(total+PreferenceMoney) AS CompleteGoodTotal,
										SUM(ntotal+nPreferenceMoney)  AS NCompleteGoodTotal
								FROM dbo.gatheringBill 
								WHERE BillNumberId=@moneybillnumberid
								GROUP BY brandartypeid) g ON c.brandartypeid=g.brandartypeid
					WHERE c.CompleteGoodTotal>ISNULL(g.CompleteGoodTotal,0) AND c.nCompleteGoodTotal>ISNULL(g.nCompleteGoodTotal,0)
					
			)
			
			RETURN 2 --
			
		END 
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_CheckGoodsNumber]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_CheckGoodsNumber
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2012-05-29
-- Description: 检查期初数据的批号/货位等是否填写
-- =============================================
CREATE PROCEDURE Gp_CheckGoodsNumber
(
	@stypeid		VARCHAR(50),
	@ReturnValue	VARCHAR(max) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--判断是否已经开账
IF @stypeid='' AND NOT EXISTS(SELECT TOP 1 1 FROM SType s LEFT JOIN SType_UserConfig u ON s.TypeId=u.StypeId WHERE s.sonnum=0 AND s.deleted=0 AND  ((u.Value = '0' AND u.ConfigNo = '1') OR u.Value IS NULL ))
	RETURN 0
IF @stypeid <> '' AND EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeID = @STypeId AND Value = '1' AND ConfigNo = '1')
	RETURN 0

CREATE TABLE #stype(typeid VARCHAR(50),fullname VARCHAR(200))
IF @stypeid=''
	INSERT	INTO #stype
	SELECT	s.TypeId,s.FullName 
	FROM	SType s 
	LEFT	JOIN SType_UserConfig u ON s.TypeId=u.StypeId 
	WHERE	s.sonnum=0 
			AND s.deleted=0 
			AND((u.Value = '0' AND u.ConfigNo = '1') OR u.Value IS NULL )
ELSE
	INSERT	INTO #stype
	SELECT	typeid,''
	FROM	stype
	WHERE	TypeId=@stypeid

	
DECLARE @mngcargospace INT=0,@ifusegoodsnumber INT=0,@pfullname VARCHAR(MAX)='',
		@kfullname VARCHAR(MAX)='',@bfullname VARCHAR(MAX)='',@sfullname varchar(max)=''
		
SELECT @mngcargospace=Value FROM dbo.Userconfig WHERE ConfigName='mngcargospace'
SELECT @ifusegoodsnumber=Value FROM dbo.Userconfig WHERE ConfigName='ifusegoodsnumber'

IF @mngcargospace=1
BEGIN
		SELECT TOP 1 @pfullname=p.fullname,@kfullname=k.fullname,@sfullname=s.FullName
		FROM dbo.Ini_GOODSSTOCKS_QTY i 
		INNER JOIN dbo.ptype p ON i.PTypeID=p.typeId 
		INNER JOIN dbo.Stock k ON k.typeId=i.KTypeID 
		INNER JOIN #stype s ON s.TypeId=k.STypeID
		WHERE i.CargoID=0
		IF @pfullname <> ''
		BEGIN
			SET @ReturnValue=@sfullname+'商品【'+@pfullname+'】在仓库【'+@kfullname+'】中库存期初未填写货位，不能开账!'
			RETURN -2
		END
END

IF @ifusegoodsnumber=1
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.Ini_GOODSSTOCKS_QTY i INNER JOIN dbo.ptype p ON i.PTypeID=p.Typeid  WHERE IfUseGoodsNum=1 AND ISNULL(i.GoodsNumber,'')='')
	BEGIN 
		SELECT @pfullname=p.fullname,@kfullname=k.fullname,@sfullname=s.FullName
		FROM dbo.Ini_GOODSSTOCKS_QTY i 
		INNER JOIN dbo.ptype p ON i.PTypeID=p.typeId 
		INNER JOIN dbo.Stock k ON k.typeId=i.KTypeID 
		INNER JOIN #stype s ON s.TypeId=k.STypeID
		WHERE	p.IfUseGoodsNum=1
				AND ISNULL(i.GoodsNumber,'')=''
		SET @ReturnValue=@sfullname+'商品【'+@pfullname+'】在仓库【'+@kfullname+'】中的库存期初未填写批号，不能开账!'
		RETURN -2
	END 
	
	IF EXISTS(SELECT 1 FROM dbo.IniCommissionStock_Qty i INNER JOIN dbo.ptype p ON i.PTypeID=p.Typeid  WHERE IfUseGoodsNum=1 AND ISNULL(i.GoodsNumber,'')='')
	BEGIN 
		SELECT @pfullname=p.fullname,@bfullname=b.fullname,@sfullname=s.FullName
		FROM dbo.IniCommissionStock_Qty i 
		INNER JOIN dbo.ptype p ON i.PTypeID=p.typeId 
		INNER JOIN dbo.btype b ON b.typeId=i.btypeid
		INNER JOIN #stype s ON s.TypeId=i.STypeID
		WHERE	p.IfUseGoodsNum=1
				AND ISNULL(i.GoodsNumber,'')=''
		SET @ReturnValue=@sfullname+'商品【'+@pfullname+'】在代销期库中与往来单位【'+@bfullname+'】关联的代销期初未填写批号，不能开账!'
		RETURN -2
	END 
	
	IF EXISTS(SELECT 1 FROM dbo.IniGoodsLend i INNER JOIN dbo.ptype p ON i.PTypeID=p.Typeid  WHERE IfUseGoodsNum=1 AND ISNULL(i.GoodsNumber,'')='')
	BEGIN 
		SELECT @pfullname=p.fullname,@bfullname=b.fullname,@kfullname=k.fullname,@sfullname=s.FullName
		FROM dbo.IniGoodsLend i 
		INNER JOIN dbo.ptype p ON i.PTypeID=p.typeId 
		INNER JOIN dbo.btype b ON b.typeId=i.btypeid
		INNER JOIN dbo.Stock k ON k.typeId=i.KtypeId
		INNER JOIN #stype s ON s.TypeId=k.STypeID
		WHERE	p.IfUseGoodsNum=1
				AND ISNULL(i.GoodsNumber,'')=''
		SET @ReturnValue=@sfullname+'商品【'+@pfullname+'】在仓库【'+@kfullname+'】中与往来单位【'+@bfullname+'】关联的借欠期初未填写批号，不能开账!'
		RETURN -2
	END 
	
	IF EXISTS(SELECT 1 FROM dbo.wx_IniGoodsStocks i INNER JOIN dbo.ptype p ON i.PTypeID=p.Typeid  WHERE IfUseGoodsNum=1 AND ISNULL(i.GoodsNumber,'')='')
	BEGIN 
		SELECT @pfullname=p.fullname,@kfullname=k.fullname,@sfullname=s.fullname
		FROM dbo.wx_IniGoodsStocks i 
		INNER JOIN dbo.ptype p ON i.PTypeID=p.typeId 
		INNER JOIN dbo.Stock k ON k.typeId=i.KtypeId
		INNER JOIN #stype s ON s.TypeId=k.STypeID
		
		WHERE	p.IfUseGoodsNum=1
				AND ISNULL(i.GoodsNumber,'')=''
		SET @ReturnValue=@sfullname+'商品【'+@pfullname+'】在仓库【'+@kfullname+'】中的维修库存期初未填写批号，不能开账!'
		RETURN -2
	END 
END

RETURN 0

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


IF EXISTS (SELECT Name FROM dbo.SysObjects WHERE ID = OBJECT_ID(N'[dbo].[Gp_CheckIniSerialInput]') AND OBJECTPROPERTY(ID, N'IsProcedure') = 1)
DROP PROC [dbo].Gp_CheckIniSerialInput
GO

/*
期初序列号录入验证
@KTypeId
@PTypeId  商品编号
@Serial	  序列号
@Flag	  1借出序列号，2借入序列号，0 普通序列号
2015-04-27 SiHuaShan
@State	序列号状态（状态内校验序列号是否重复【主要解决录入界面手动删除序列号，又添加的问题，允许序列号在同一状态内重复】，不涉及此业务可忽略）
2015-07-06 施训果
*/
CREATE  PROC Gp_CheckIniSerialInput
(
	@KTypeId VARCHAR(50),
	@PTypeId VARCHAR(50),
	@Serial	 VARCHAR(MAX),
	@Flag	 INT=0,
	@Message VARCHAR(MAX) OUTPUT,
	@State	 INT=0,
	@Btypeid VARCHAR(200)=''
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
		DECLARE @MNGLendSerial  INT,--序列号借欠出入库校验模式
				@SerialCount	INT,--序列号个数
				@RowIndex		INT,--行号
				@CurrSerial		VARCHAR(50),--当前序列号
				@ResultValue		INT;
				
		SELECT  @MNGLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'; 
		
		SELECT * INTO #TMP FROM F_SplitSerial(@Serial,'я') WHERE Serial<>'';
		SELECT @SerialCount=COUNT(1) FROM #TMP;
		
		--无数据
		IF @SerialCount=0
		BEGIN
			DROP TABLE #TMP;
			SET @Message='';
			RETURN;
		END
		
		SET @RowIndex=1;
		
		WHILE(@RowIndex<=@SerialCount)
		BEGIN
			SELECT @CurrSerial=Serial FROM #TMP WHERE ShowOrder=@RowIndex;
			IF @State<>0
			BEGIN
				IF EXISTS (SELECT Serial FROM GP_initPTypeSerial WHERE Serial = @CurrSerial AND State=@State)
				BEGIN
					SET @RowIndex+=1;
					CONTINUE
				END
			END
			
			IF @MNGLendSerial=1  --出入库序列号校验
			BEGIN
				IF @Flag=0  --其他序列号
				BEGIN
					EXEC @ResultValue=Gp_FindSerial @KTypeId,@CurrSerial,1,@PTypeId,@State;
					IF @ResultValue=1	
					BEGIN
						DROP TABLE #TMP;
						SET @Message='序列号【'+@CurrSerial+'】在借欠期初仓库或期初仓库中已存在，请确认后重试';
						RETURN;
					END
				END
				
				IF @Flag=1  --借欠期初借出序列号
				BEGIN
					IF NOT EXISTS (SELECT Serial FROM GP_initPTypeSerial WHERE Serial = @CurrSerial	AND Flag = 1 	AND State NOT IN (25,26,27,28,29))
					BEGIN
						DROP TABLE #TMP;
						SET @Message='因为采用了借欠的效验模式，借出序列号【'+@CurrSerial+'】在真实库中不存在，请确认后重试！';
						RETURN;
					END
					IF NOT EXISTS(SELECT Serial FROM GP_initPTypeSerial WHERE Serial = @CurrSerial AND Flag = 1 AND PTypeID = @PTypeID AND KTypeID = @KTypeID 	AND State not in (25,26,27,28,29))
					BEGIN
						DROP TABLE #TMP;
						SET @Message='因为采用了借欠的效验模式，录入借出序列号【'+@CurrSerial+'】的商品与仓库属性必须与真实库的一致，请确认后重试！'
						RETURN;
					END
					
					IF EXISTS (SELECT Serial FROM GP_initLendPTypeSerial WHERE Serial = @CurrSerial)
					BEGIN
						DROP TABLE #TMP;
						SET @Message='序列号【'+@CurrSerial+'】在借欠期初仓库中已存在，请确认后重试！';
						RETURN;
					END
				END
				
				IF @Flag=2  --借欠期初借入序列号
				BEGIN
					IF EXISTS(SELECT Serial FROM GP_initLendPTypeSerial WHERE Serial = @CurrSerial AND BtypeID2 = @Btypeid AND KtypeID = @KTypeId )
					BEGIN
						DROP TABLE #TMP;
						SET @Message='';
						RETURN;
					END
					IF EXISTS (	SELECT Serial FROM GP_initPTypeSerial WHERE Serial = @CurrSerial)
					BEGIN
						DROP TABLE #TMP;
						SET @Message= '序列号【'+@CurrSerial+'】在期初仓库中已存在，请确认后重试！';
						RETURN;
					END
					IF EXISTS (SELECT Serial FROM GP_initLendPTypeSerial WHERE Serial = @CurrSerial)
					BEGIN
						DROP TABLE #TMP;
						SET @Message= '序列号【'+@CurrSerial+'】在借欠期初仓库中已存在，请确认后重试！';
						RETURN;
					END
				END
			END
			
			ELSE  --未启用出入库序列号校验
			BEGIN
				IF @Flag=0
				BEGIN
					EXEC @ResultValue=Gp_FindSerial @KTypeId,@CurrSerial,1,@PTypeId,@State;
					IF @ResultValue=1
					BEGIN
						DROP TABLE #TMP;
						SET @Message= '序列号【'+@CurrSerial+'】在期初仓库中已存在，请确认后重试！';
						RETURN;
					END
				END
				IF @Flag=1 OR @Flag=2
				BEGIN
					IF EXISTS(SELECT Serial FROM GP_initLendPTypeSerial WHERE Serial = @CurrSerial)
					BEGIN
						DROP TABLE #TMP;
						SET @Message= '序列号【'+@CurrSerial+'】在借欠期初仓库中已存在，请确认后重试！';
						RETURN;
					END
				END
			END
			
			SET @RowIndex+=1;
		END
		
		DROP TABLE #TMP;
		SET @Message= '';
		RETURN;
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2004-1-12
	描述：判断软件狗的网络标识	
*/
CREATE  PROCEDURE GP_CheckLanSing
(
	@ifAccountNum	int = 0
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

DECLARE @N int, @intDogUserCount int, @intVersion int, @intAccountNum int

IF @ifAccountNum = 1
	BEGIN		
		SELECT	@N = CAST(SubValue AS INT)
		FROM	SysData1
		WHERE	SubNo = 5	-- 账套数
		
		IF @N IS NULL RETURN 3
	END
ELSE
	BEGIN
		-- 判断网络标识
		SELECT	@N = CAST(SubValue AS INT)
		FROM	SysData1
		WHERE	SubNo = 4	-- 网络标识

		IF @N IS NULL RETURN 1888
	END	

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion <> ''
	RETURN @intVersion
ELSE
	BEGIN
		IF @ifAccountNum = 1
			RETURN 3
		ELSE 
			RETURN 1888
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2007-4-12
	描述：有序列号的借欠单据就只能修改摘要和说明
*/
CREATE PROCEDURE Gp_CheckLendBillSerial
(
	@BillNumberId	varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @BillType int

SELECT @BillType = BillType FROM LendIndex WHERE BillNumberId = @BillNumberId

/*
屏蔽审核 2008-05-08 谢吉康 审核问题太多
IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 1 AND IfAudit = 0)
			RETURN -1
		ELSE
			RETURN 0
	END
ELSE
	RETURN 0
*/
IF EXISTS(SELECT TOP 1 1 FROM LendBill WHERE BillNumberId = @BillNumberId AND DataLength(Serial)<>0)
	RETURN -1
ELSE
	RETURN 0






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


------------检查某职员是否具有某项权限
CREATE   PROCEDURE GP_CheckLimit
(
 @Etypeid varchar(100),
 @OffSet int
)

--@encode$--
 AS
SET NOCOUNT ON
if @Etypeid is null or @OffSet is null return 2
if exists(select * from loginuser where etypeid=@etypeid and sysid='1') return 0


declare @right char(1)
select @right=substring(lim,@OffSet,1) from loginuser where etypeid=@etypeid
if @right='1' 
	return 0
else
	return 1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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






/*
	作者：谢吉康
	日期：2009-06-25
	描述：检查某个操作员是否有某种单据的过账权限
	2015-09-16 --9.6.1 固定资产增加/减少/折旧单 普通操作员有所有权限无法过账
*/

CREATE  PROCEDURE Gp_CheckLimitBillType
(
	@Etypeid 	varchar(100),
	@OffSet 	int,
	@BillType	int
)
--@encode$--
AS
SET NOCOUNT ON

if @Etypeid is null or @OffSet is null return 2

if exists(select * from loginuser where etypeid=@etypeid and sysid='1') return 1

--pos操作员优惠券出库退库过账权限需要单独处理,只由pos终端的相应权限决定
DECLARE @ispos INT
SELECT @ispos= count(1) from loginuser where ispos=1 and iserp=0 and etypeid=@etypeid
IF @ispos=1
BEGIN 
	IF @BillType=424
			SET @OffSet=5097
	ELSE IF @BillType=426
			SET @OffSet=5098
declare @posright char(1)

select @posright=substring(lim,@OffSet,1) from loginuser where etypeid=@etypeid

if @posright='1' 
	return 1
END
--分单据判断权限
IF @BillType = 305 
	SET @OffSet = 167
ELSE IF @BillType = 11 
	SET @OffSet = 168
ELSE IF @BillType = 45 
	SET @OffSet = 169
ELSE IF @BillType = 4 
	SET @OffSet = 170
ELSE IF @BillType = 34 
	SET @OffSet = 173
ELSE IF @BillType = 6 
	SET @OffSet = 174
ELSE IF @BillType = 66 
	SET @OffSet = 175
ELSE IF @BillType = 17 
	SET @OffSet = 176
ELSE IF @BillType = 21 
	SET @OffSet = 177
ELSE IF @BillType = 9 
	SET @OffSet = 178
ELSE IF @BillType = 14 
	SET @OffSet = 179
ELSE IF @BillType = 139 
	SET @OffSet = 180
ELSE IF @BillType = 126 
	SET @OffSet = 181
ELSE IF @BillType = 57 
	SET @OffSet = 182
ELSE IF @BillType = 16 
	SET @OffSet = 183
ELSE IF @BillType = 116 
	SET @OffSet = 184
ELSE IF @BillType = 115 
	SET @OffSet = 185
ELSE IF @BillType = 128 
	SET @OffSet = 186
ELSE IF @BillType = 129 
	SET @OffSet = 187
ELSE IF @BillType = 36 
	SET @OffSet = 188
ELSE IF @BillType = 93 
	SET @OffSet = 189
ELSE IF @BillType = 77 
	SET @OffSet = 190
ELSE IF @BillType = 84 
	SET @OffSet = 204
ELSE IF @BillType = 85 
	SET @OffSet = 205
ELSE IF @BillType = 78 
	SET @OffSet = 206
ELSE IF @BillType = 5 
	SET @OffSet = 207
ELSE IF @BillType = 10
	SET @OffSet = 208
ELSE IF @BillType = 148 
	SET @OffSet = 250
ELSE IF @BillType = 149 
	SET @OffSet = 251
ELSE IF @BillType = 140
	SET @OffSet = 267
ELSE IF @BillType = 141 
	SET @OffSet = 268
ELSE IF @BillType = 142 
	SET @OffSet = 269
ELSE IF @BillType = 143 
	SET @OffSet = 270
ELSE IF @BillType = 144 
	SET @OffSet = 271
ELSE IF @BillType = 145 
	SET @OffSet = 272
ELSE IF @BillType = 146 
	SET @OffSet = 273
ELSE IF @BillType = 147 
	SET @OffSet = 274
ELSE IF @BillType = 150 
	SET @OffSet = 387
ELSE IF @BillType = 151 
	SET @OffSet = 452
ELSE IF @BillType = 155 
	SET @OffSet = 436
ELSE IF @BillType = 158 
	SET @OffSet = 500
ELSE IF @BillType = 159 
	SET @OffSet = 549
ELSE IF @BillType = 160 
	SET @OffSet = 582
ELSE IF @BillType = 161 
	SET @OffSet = 584
ELSE IF @BillType = 165 
	SET @OffSet = 648
ELSE IF @BillType = 166 
	SET @OffSet = 650
ELSE IF @BillType = 167 
	SET @OffSet = 652
ELSE IF @BillType = 168 
	SET @OffSet = 654
ELSE IF @BillType = 169 
	SET @OffSet = 656
ELSE IF @BillType = 170 
	SET @OffSet = 658
ELSE IF @BillType = 171 
	SET @OffSet = 660
ELSE IF @BillType = 172 
	SET @OffSet = 662
ELSE IF @BillType = 173
	SET @OffSet = 664
ELSE IF @BillType = 174 
	SET @OffSet = 666
ELSE IF @BillType = 175 
	SET @OffSet = 668
ELSE IF @BillType = 178 
	SET @OffSet = 1376
ELSE IF @BillType = 183 
	SET @OffSet = 1385
ELSE IF @BillType = 186 
	SET @OffSet = 1374
ELSE IF @BillType = 187
	SET @OffSet = 717
ELSE IF @BillType = 188
	SET @OffSet = 720
ELSE IF @BillType = 189
	SET @OffSet = 726
ELSE IF @BillType = 190
	SET @OffSet = 729		
ELSE IF @BillType = 191
	SET @OffSet = 1472	
ELSE IF @BillType = 197
	SET @OffSet = 1474
ELSE IF @BillType = 195
	SET @OffSet = 1532
ELSE IF @BillType = 200
	SET @OffSet = 1478	
ELSE IF @BillType = 196
	SET @OffSet = 1477	
ELSE IF @BillType = 201
	SET @OffSet = 1552
ELSE IF @BillType = 202
	SET @OffSet = 1556
ELSE IF @BillType = 203
	SET @OffSet = 1548	
ELSE IF @BillType = 205
	SET @OffSet = 1940
ELSE IF @BillType = 206											
	SET @OffSet = 1945
ELSE IF @BillType = 71											
	SET @OffSet = 4562
ELSE IF @BillType = 72											
	SET @OffSet = 4566
ELSE IF @BillType = 87											
	SET @OffSet = 4560
ELSE IF @BillType = 88 											
	SET @OffSet = 4564
ELSE IF @BillType = 310											
	SET @OffSet = 4454
ELSE IF @BillType =  311											
	SET @OffSet = 4471
ELSE IF @BillType = 312											
	SET @OffSet = 4496
ELSE IF @BillType = 400											
	SET @OffSet = 4575
ELSE IF @BillType = 401											
	SET @OffSet = 4584
ELSE IF @BillType = 402  											
	SET @OffSet = 4596
ELSE IF @BillType = 403  											
	SET @OffSet = 4605 
ELSE IF @BillType = 404											
	SET @OffSet = 4617
ELSE IF @BillType = 405										
	SET @OffSet = 4625
ELSE IF @BillType = 181										
	SET @OffSet = 1343
ELSE IF @BillType = 215										
	SET @OffSet = 2586
ELSE IF @BillType=212
	SET @OffSet=2532
ELSE IF @BillType=213
	SET @OffSet=2537
ELSE IF @BillType=214
	SET @OffSet=2542
ELSE IF @BillType=450
	SET @OffSet=4676
ELSE IF @BillType=412
	SET @OffSet=4805
ELSE IF @BillType=413
	SET @OffSet=4797
ELSE IF @BillType=414
	SET @OffSet=4819
ELSE IF @BillType=418
	SET @OffSet=4831
ELSE IF @BillType=419
	SET @OffSet=4839
ELSE IF @BillType=420
	SET @OffSet=4847
--优惠券入库 出库 调拨 退货
ELSE IF @BillType=423
	SET @OffSet=5033
ELSE IF @BillType=424
	SET @OffSet=5041
ELSE IF @BillType=425
	SET @OffSet=5049
ELSE IF @BillType=426
	SET @OffSet=5057
--积分转储值单
ELSE IF @BillType=427
	SET @OffSet=4214
--门店调拨类(配送、配送退货、验收)
ELSE IF @BillType=327
	SET @OffSet=5238
ELSE IF @BillType=328
	SET @OffSet=5247
ELSE IF @BillType=329
	SET @OffSet=5255
--优惠券分支机构调拨入库单、优惠券分支机构调拨出库单
ELSE IF @BillType=428
	SET @OffSet=5204
ELSE IF @BillType=429
	SET @OffSet=5199		
ELSE	
	SET @OffSet = 0

declare @right char(1)

select @right=substring(lim,@OffSet,1) from loginuser where etypeid=@etypeid

if @right='1' 
	return 1
else
	return 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		
--					
-- 最后修改作者：	冯波
-- 最后修改时间：	2011-03-15
-- ========================================================================
CREATE	PROCEDURE GP_CheckOnlySType (
	@nBillID		NUMERIC(10,0),
	@nBillType		INT
)
--@encode$--
AS

SET NOCOUNT ON

DECLARE	@STypeID	VARCHAR(50)

SELECT @STypeID=STypeID
FROM BillIndex
WHERE BillNumberId=@nBillID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CheckOnlyStypeRef]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CheckOnlyStypeRef] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2012-06-14
----描述：检查会计科目是否被引用
----========================
CREATE    PROCEDURE [dbo].[GP_CheckOnlyStypeRef]
(
    @stypeid VARCHAR(50),
    @atypeid VARCHAR(50)
)
--@encode$--
AS 

----V3标示
DECLARE @ISv3 INT SET @ISv3=(SELECT  SubValue FROM sysdata WHERE SubName='ProInfo'  )

IF @stypeid='00000' AND @ISv3<>1
BEGIN
	RETURN 0
END


DECLARE @styperef INT

EXEC @styperef = GP_CheckStypeRef @stypeid = @stypeid, -- varchar(50)
    @atypeid = @atypeid -- varchar(50)

IF @styperef = 1
BEGIN
    
    DECLARE @refed INT
    SET @refed = 0
    
    SELECT  t.name AS tableName, c1.colname AS ColA,
            c2.colname AS ColS
    INTO #t1
    FROM    sys.tables t
    JOIN    (SELECT t.name AS tblname,
                    ISNULL(c.name, s.fldname) AS colname
             FROM   sys.tables t
             LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                        AND c.name LIKE 'atypeid%'
             LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                                AND s.basType = 'atypeid'
             WHERE  c.name IS NOT NULL
                    OR s.fldname IS NOT NULL) c1 ON c1.tblname = t.name
    JOIN    (SELECT t.name AS tblname,
                    ISNULL(c.name, s.fldname) AS colname
             FROM   sys.tables t
             LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                        AND c.name LIKE 'stypeid%'
             LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                                AND s.basType = 'stypeid'
             WHERE  c.name IS NOT NULL
                    OR s.fldname IS NOT NULL) c2 ON c2.tblname = t.name
    WHERE t.name NOT IN ('BillAtype','Ac_Account_Assist_CheckItems',
    'Ac_Balance','Ac_Balance_Assist_CheckItems','Ac_Balance_Assist_CheckItems_Detail')
    UNION ALL SELECT 'Ac_Items_Detail','DEPATYPEID','stypeid'
    UNION ALL SELECT 'Ac_Items_Detail','DISATYPEID','stypeid'
    UNION ALL SELECT '#Ac_Auditing_Template','atypeid','stypeid'
    UNION ALL SELECT 'BillAtype','AtypeId','StypeId'
    ORDER BY TableName


    SELECT Stypeid,atypeid 
    INTO #Ac_Auditing_Template
    FROM Ac_Auditing_Template t
    JOIN Ac_Auditing_Template_Detail d ON d.Atid = t.AtId



    SELECT IDENTITY(INT,1,1) AS rid ,*
    INTO #t2
    FROM #t1


    DECLARE @i INT
    DECLARE @count INT
    DECLARE @tbname NVARCHAR(200)
    DECLARE @colaname NVARCHAR(200)
    DECLARE @colsname NVARCHAR(200)
    DECLARE @sql NVARCHAR(2000)

    SELECT @count = COUNT(1) FROM #t1

    SET @i = 1

    WHILE @i <= @count AND @refed = 0
    BEGIN 
            SELECT @tbname = TableName,@colaname=cola,@colsname = cols
            FROM #t2
            WHERE rid = @i
            
            SET @sql = 'SELECT @refed = Count(1) FROM '
                    + @tbname + ' WHERE ' + @colaname
                    + ' =  ''' + @ATypeId + ''''
                    + ' AND ' + @colsname + ' = '''
                    + @STypeId + ''''                              
            
            EXECUTE sp_executesql @SQL,
                N'@refed INT OUTPUT', @refed OUTPUT
        
        SET @i += 1
    END

    DROP TABLE #t1,#t2,#Ac_Auditing_Template

    IF @refed > 0
    BEGIN
        SET @sql = ' 
        SELECT +''
        ' + @tbname + ''' AS TABLENAME,''
        ' + @STypeId + ''' AS [' + @colsname + '], ''
        ' + @ATypeId + ''' AS [' + @colaname + ']'
        
        EXEC(@SQL)
        RETURN 0
    END
    
    RETURN 1
END
        

RETURN 0

GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

/*
	作者：谢吉康
	日期：2005-1-26
	描述：获取当前操作员的权限范围
		  Re:0 成功
          Re:1 失败	
*/
CREATE     PROCEDURE GP_CheckOperatorRight23
(
	@OperatorID 	varchar(100),
	@MAtypeid 		varchar(100) output,		--现金银行;不检查现金权限
	@MBtypeid 		varchar(100) output,		--客户
	@MBtypeid2 		varchar(100) output,		--供应商
	@MEtypeid 		varchar(100) output,
	@MKtypeid 		varchar(100) output,
	@MPtypeid 		varchar(100) output,
	@MExpense 		varchar(100) output, 		--费用
	@MIncome 		varchar(100) output,		--收入
	@MCapital		varchar(100)='' output,		--资产
	@MDtypeid		varchar(100)='' output,		--部门机构
	@MStypeid		varchar(100)='' output		--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
IF NOT EXISTS(SELECT 1 FROM LoginUser(NOLOCK) WHERE ETypeId=@OperatorID ) RETURN 1

SELECT 	@MAtypeid='',
		@MBtypeid='00001',
		@MEtypeid='',
		@MKtypeid='',
		@MPtypeid='',
		@MBtypeid2='00002',
		@MExpense='',
		@MIncome='',
		@MCapital='',
		@MDtypeid='',
		@MStypeid=''

RETURN 0






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

/*
	描述：过账的时候按照真实的值取操作员权限范围
*/

CREATE   PROCEDURE Gp_CheckOperatorRight23_New
(
	@OperatorID varchar(100),
	@MAtypeid 	varchar(50) output,--现金银行;不检查现金权限
	@MBtypeid 	varchar(50) output,--客户
	@MBtypeid2 	varchar(50) output,--供应商
	@MEtypeid 	varchar(50) output,
	@MKtypeid 	varchar(50) output,
	@MPtypeid 	varchar(50) output,
	@MExpense 	varchar(50) output, --费用
	@MIncome 	varchar(50) output, --收入
	@MCapital 	varchar(50) output, --资产
	@MDtypeid	varchar(50) output, --部门
	@MStypeid	varchar(50) output  --分支结构
)
--@encode$--


 AS
	SET NOCOUNT ON
	IF NOT EXISTS(SELECT 1 FROM LOGINUSER(NOLOCK) WHERE ETYPEID=@OPERATORID ) RETURN 1
	-------------------------超级用户－－－－－－－－－－－－－－－
	IF EXISTS(SELECT 1 FROM LOGINUSER(NOLOCK) WHERE ETYPEID=@OPERATORID AND SYSID=1)
		BEGIN
			SELECT @MAtypeid='',@MBtypeid='00001',@MEtypeid='',@MKtypeid='',@MPtypeid='',@MBtypeid2='00002',@MExpense='',@MIncome='',@MCapital='',@MDtypeid = '',@MStypeid = ''
			RETURN 0
		END
	SELECT 	@MAtypeid=MangerATypeID,@MBtypeid=MangerBTypeID,@MEtypeid=MangerETypeID,@MKtypeid=MangerKTypeID,@MPtypeid=MangerPTypeID,
			@MBtypeid2=MangerBTypeID2,@MExpense=MangerExpense, @MIncome=MangerIncome,@MCapital=MangerCpaital,@MDtypeid=MangerDTypeId--,@MStypeid=MangerSTypeID
	FROM 	LOGINUSER(NOLOCK)
	WHERE 	ETYPEID=@OPERATORID

	IF @MKtypeid='00000' SELECT @MKtypeid=''
	IF @MPtypeid='00000' SELECT @MPtypeid=''
	IF @MDtypeid='00000' SELECT @MDtypeid=''
	IF @MStypeid='00000' SELECT @MStypeid=''


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/*
	作者：谢吉康
	日期：2010-06-13
	描述：报表检查操作员的权限范围
*/

CREATE   PROCEDURE Gp_CheckOperatorRight23_Rep
(
	@OperatorID varchar(100),
	@MAtypeid 	varchar(50) output,--现金银行;不检查现金权限
	@MBtypeid 	varchar(50) output,--客户
	@MBtypeid2 	varchar(50) output,--供应商
	@MEtypeid 	varchar(50) output,
	@MKtypeid 	varchar(50) output,
	@MPtypeid 	varchar(50) output,
	@MExpense 	varchar(50) output, --费用
	@MIncome 	varchar(50) output, --收入
	@MCapital 	varchar(50) output, --资产
	@MDtypeid	varchar(50) output, --部门
	@MStypeid	varchar(50) output  --分支结构
)
--@encode$--
AS
SET NOCOUNT ON
IF NOT EXISTS(SELECT 1 FROM LoginUser(NOLOCK) WHERE ETypeId=@OperatorID ) RETURN 1
-------------------------超级用户－－－－－－－－－－－－－－－
SELECT 	@MAtypeid=MangerATypeID,
		@MBtypeid=MangerBTypeID,
		@MEtypeid=MangerETypeID,
		@MKtypeid=MangerKTypeID,
		@MPtypeid=MangerPTypeID,
		@MBtypeid2=MangerBTypeID2,
		@MExpense=MangerExpense, 
		@MIncome=MangerIncome,
		@MCapital=MangerCpaital,
		@MDtypeid=MangerDTypeId,
		@MStypeid=MangerSTypeID
FROM 	LoginUser(NOLOCK)
WHERE 	ETypeId=@OperatorID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- 2006-04-11
-- modify by cqhua
-- 判断价保单据的正确性
CREATE                  PROCEDURE GP_CheckProtectBill
(
@BillnumberID Int,
@intRow  int output,  --行数
@strBillCode varchar(200) output --单据编号
)
--@encode$--
As
SET NOCOUNT ON 

DECLARE @chvStypeId varchar(100)
DECLARE @chvPtypeId	varchar(100)
DECLARE @chvBtypeId	varchar(100)
DECLARE @decQty		 NUMERIC(24, 10) 
DECLARE @Price		 NUMERIC(24, 10) 
DECLARE @Billtype       int

SELECT @chvSTypeID=STypeID,@chvBtypeId = BTypeID,@Billtype = Billtype,@strBillCode = BillCode 
FROM Billindex WHERE BillnumberID =@BillnumberID


DECLARE @intRows  int -- 最小行数
SELECT @intRows =Min([ID]) FROM PriceProtectBill where BillnumberID = @BillnumberID
DECLARE @intID   int-- 行数

DECLARE @SQL varchar(6000)
SET @SQL =' DECLARE Rows_Cursor  Cursor FOR  
		SELECT PtypeID,Qty,OldPrice,[ID]
		FROM PriceProtectBill 
		WHERE BillnumberID= '+Convert(varchar(20),@BillnumberID) +'
		AND Billtype ='+Convert(varchar(20),@Billtype)

EXEC(@SQL)

OPEN Rows_Cursor
FETCH NEXT FROM Rows_Cursor INTO @chvPtypeId,@decQty,@Price,@intID
WHILE @@FETCH_STATUS = 0 
BEGIN
	SET @intRow = @intID + 1 - @intRows
	IF NOT EXISTS(Select BtypeID From PriceProtect Where STypeID IN (@chvSTypeID,'') AND BTypeID=@chvBtypeId and PTypeID=@chvPtypeId and OldPrice=@Price and State='有效')
	BEGIN
		RETURN -1
	END
	FETCH NEXT FROM Rows_Cursor INTO @chvPtypeId,@decQty,@Price,@intID
END
CLOSE Rows_Cursor	-- 关闭游标
DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CheckRefUsage]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CheckRefUsage] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2012-06-14
----描述：检查会计科目是否被引用
----========================
CREATE    PROCEDURE [dbo].[GP_CheckRefUsage]
(
    @stypeid VARCHAR(50),
    @atypeid VARCHAR(50)
)
--@encode$--
AS 

----V3标示
DECLARE @ISv3 INT 
SET @ISv3=(SELECT  SubValue FROM sysdata WHERE SubName='ProInfo'  )

IF @stypeid='00000' AND @ISv3<>1
BEGIN
	IF EXISTS (SELECT 1 FROM AC_ACCOUNT WHERE stypeid > '00000' and typeid = @atypeid  AND isdist = 1)
	    RETURN  1
	
	RETURN 0
END

DECLARE @isUsed INT
SET @isUsed = 0

CREATE TABLE #t1
    (
      rowid INT IDENTITY(1, 1) ,
      tableName sysname NOT NULL ,
      ColA sysname NOT NULL ,
      ColS sysname NOT NULL
    );

--SELECT  t.name AS tableName, 
--		c1.colname AS ColA,
--		c2.colname AS ColS
INSERT INTO #t1 SELECT  t.name AS tableName, 
					  c1.colname AS ColA,
					  c2.colname AS ColS
FROM    sys.tables t
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id AND c.name LIKE 'atypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name AND s.basType = 'atypeid'
         WHERE  c.name IS NOT NULL OR s.fldname IS NOT NULL) c1 ON c1.tblname = t.name
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id AND c.name LIKE 'stypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name  AND s.basType = 'stypeid'
         WHERE  c.name IS NOT NULL OR s.fldname IS NOT NULL) c2 ON c2.tblname = t.name
WHERE t.name NOT IN ('Ac_Account_Assist_CheckItems','BillAtype',
'Ac_Balance','Ac_Balance_Assist_CheckItems','Ac_Balance_Assist_CheckItems_Detail',
'Ac_IniAccount','Ac_IniAccount_Assist_CheckItems','Ac_IniAccount_Assist_CheckItems_Detail,Ac_Voucher_Bill_Backup','AccountCredence'
,'Ac_ProfitandLoss','Ac_Voucher_Bill_Backup','Ac_Voucher_Bill_Log')
UNION ALL SELECT 'SType','atypeid','typeid'
UNION ALL SELECT 'SType','atypeid2','typeid'
UNION ALL SELECT 'SType','atypeid3','typeid'
UNION ALL SELECT 'SType','atypeid4','typeid'
UNION ALL SELECT 'Ac_Items_Detail','DEPATYPEID','stypeid'
UNION ALL SELECT 'Ac_Items_Detail','DISATYPEID','stypeid'
UNION ALL SELECT '#Ac_Auditing_Template','atypeid','stypeid'
UNION ALL SELECT 'BillAtype','AtypeId','StypeId'
UNION ALL SELECT 'Ac_AssetsCards','AssertATypeId','stypeid' --以下四行添加的目的是另一个检查科目使用的存储过程里有检查Ac_AssetsCards这张表
UNION ALL SELECT 'Ac_AssetsCards','DepATypeId','stypeid'
UNION ALL SELECT 'Ac_AssetsCards','DisATypeId','stypeid'
UNION ALL SELECT 'Ac_AssetsCards','DevalueATypeId','stypeid'
ORDER BY TableName


SELECT Stypeid,atypeid 
INTO #Ac_Auditing_Template
FROM Ac_Auditing_Template t
JOIN Ac_Auditing_Template_Detail d ON d.Atid = t.AtId

--SELECT IDENTITY(INT,1,1) AS rid ,*
--INTO #t2
--FROM #t1
------过滤无关表-------备注：如果还要保留的话，注意#t2已经不存在了，可以替换成#t1
--IF  EXISTS (SELECT * FROM #t2 WHERE tableName='AccountCredence')
--DELETE #t2  WHERE tableName='AccountCredence'
--IF  EXISTS (SELECT * FROM #t2 WHERE tableName='Ac_ProfitandLoss')
--DELETE #t2  WHERE tableName='Ac_ProfitandLoss'
--IF  EXISTS (SELECT * FROM #t2 WHERE tableName='Ac_Voucher_Bill_Backup')
--DELETE #t2  WHERE tableName='Ac_Voucher_Bill_Backup'
--IF  EXISTS (SELECT * FROM #t2 WHERE tableName='Ac_Voucher_Bill_Log')
--DELETE #t2  WHERE tableName='Ac_Voucher_Bill_Log'



DECLARE @i INT
DECLARE @count INT
DECLARE @tbname NVARCHAR(200)
DECLARE @colaname NVARCHAR(200)
DECLARE @colsname NVARCHAR(200)
DECLARE @sql NVARCHAR(2000)

SELECT @count = COUNT(1) FROM #t1

SET @i = 1

WHILE @i <= @count AND @isUsed = 0
BEGIN 
    SELECT @tbname = TableName,@colaname=cola,@colsname = cols
    FROM #t1
    WHERE rowid = @i
    
    SET @sql = 'SELECT @isUsed = Count(1) FROM '
            + @tbname + ' WHERE ' + @colaname
            + ' =  ''' + @ATypeId + ''''
            + ' AND ' + @colsname + ' = '''
            + @STypeId + ''''                              
    
    EXECUTE sp_executesql @SQL,
        N'@isUsed INT OUTPUT', @isUsed OUTPUT
    
    SET @i += 1
END

DROP TABLE #t1,#Ac_Auditing_Template

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + @tbname + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [STypeId], ''
    ' + @ATypeId + ''' AS [ATypeId]'
    
    EXEC(@SQL)
    RETURN 1
END
--	Ac_Balance
SELECT TOP 1
        @isused += 1
FROM    Base_InventoryTypeDetails
WHERE   
	STypeid = @stypeid
	AND	(StockATypeID = @atypeid OR IncomeATypeID=@atypeid OR CostATypeID=@atypeid)

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''Base_InventoryTypeDetails'' AS TABLENAME,''
    ' + @STypeId + ''' AS [STypeId], ''
    ' + @ATypeId + ''' AS [ATypeId]'
    --PRINT(@SQL)
    EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance
WHERE   STypeid = @stypeid
AND		ATypeId = @atypeid
AND (FBeginBalanceFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYtdDebitFor<>0 OR FYtdCreditFor<>0 OR FEndBalanceFor<>0 OR FBeginBalance<>0 OR FDebit<>0 OR FCredit<>0 OR FYtdDebit<>0 OR FYtdCredit<>0 OR FEndBalance<>0 OR FBeginqty<>0  OR FDebitqty<>0 OR FCreditqty<>0 OR FYtdDebitqty<>0 OR FYtdCreditqty<>0 OR FEndqty<>0)

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''Ac_Balance'' AS TABLENAME,''
    ' + @STypeId + ''' AS [STypeId], ''
    ' + @ATypeId + ''' AS [ATypeId]'
    --PRINT(@SQL)
    EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance_Assist_CheckItems
WHERE   STypeid = @stypeid
AND ATypeId = @atypeid
AND (IniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FEndBalanceFor<>0 OR IniYTotalFor<>0 OR IniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FEndBalance<>0 OR IniYTotal<>0  OR IniYqty<>0  OR FDebitqty<>0 OR FCreditqty<>0 OR FEndqty<>0 OR Iniqty<>0)

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''Ac_Balance_Assist_CheckItems'' AS TABLENAME,''
    ' + @STypeId + ''' AS [STypeId], ''
    ' + @ATypeId + ''' AS [ATypeId]'
    
    EXEC(@SQL)
    RETURN 1
END

--	Ac_Balance_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
AND ATypeId = @atypeid
AND (IniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FEndBalanceFor<>0 OR IniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FEndBalance<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR FEndqty<>0 OR Iniqty<>0)

IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''Ac_Balance_Assist_CheckItems_Detail'' AS TABLENAME,''
    ' + @STypeId + ''' AS [STypeId], ''
    ' + @ATypeId + ''' AS [ATypeId]'
    
    EXEC(@SQL)
    RETURN 1
END
--	Ac_IniAccount
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount
WHERE   STypeid = @stypeid
AND ATypeId = @atypeid
 AND(iniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FYTotal<>0  OR iniYTotal<>0 OR iniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYTotalFor<>0 OR iniYTotalFor<>0 OR iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0 OR FYTotalDebit<>0 OR FYTotalCredit<>0 OR FYTotalDebitFor<>0 OR FYTotalCreditFor<>0)
 
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END
      
--	Ac_IniAccount_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems
WHERE   STypeid = @stypeid
AND ATypeId = @atypeid
 AND(iniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FYTotal<>0  OR iniYTotal<>0 OR iniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYTotalFor<>0 OR iniYTotalFor<>0 OR iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0)
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount_Assist_CheckItems' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END      
  
--	Ac_IniAccount_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
AND ATypeId = @atypeid
AND(iniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FYTotal<>0  OR iniYTotal<>0 OR iniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYTotalFor<>0 OR iniYTotalFor<>0 OR iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0)
 
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_IniAccount_Assist_CheckItems_Detail' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END          


SELECT TOP 1
        @isused += 1
FROM    Te_InitDataIndex TI
INNER JOIN Te_InitDataDetail TD ON TI.Id=TD.IndexId
WHERE   TI.STypeid = @stypeid
AND TD.ATypeId = @atypeid
--AND ABS(ISNULL(IniYTotal,0)) + ABS(ISNULL(FDebit,0)) +ABS(ISNULL(FCredit,0)) + ABS(ISNULL(IniTotal,0)) +ABS(ISNULL(FYTotal,0)) > 0
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Te_InitDataIndex' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END 

SELECT TOP 1
        @isused += 1
FROM    Ac_Voucher_Bill
WHERE   
	STypeid = @stypeid
	AND ATypeId = @atypeid
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_Voucher_Bill' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END 

--	Ac_ProfitAndLoss_Detail 添加的原因是另一个检查科目使用的存储过程中检查过这个数据GP_CheckAccountUsage
SELECT TOP 1
        @isused += 1
FROM    Ac_ProfitAndLoss_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FFTotal,0)) + 
        ABS(ISNULL(FYTOTAL,0)) > 0
        
IF @isUsed > 0
BEGIN
    SET @sql = ' 
    SELECT +''
    ' + 'Ac_ProfitAndLoss_Detail' + ''' AS TABLENAME,''
    ' + @STypeId + ''' AS [StypeId], ''
    ' + @ATypeId + ''' AS [AtypeId]'
    
    EXEC(@SQL)
    RETURN 1
END    

IF @isUsed > 0
BEGIN
    RETURN 1
END  

RETURN 0

GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




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


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
    作者：李灏龙
	日期：2014年5月23日 14:24:06
	描述：银行存款与日记账勾对
-------------------------------------------*/
CREATE PROCEDURE GP_CheckRelevance 
(
       @JournalIds 		VARCHAR(MAX),	---日记账id
	   @StatementIds	VARCHAR(MAX),	---对账单id
	   @AccountInTransitJournalIds 		VARCHAR(MAX),	---银行未达账id
	   @AccountInTransitStatementIds	VARCHAR(MAX),	---企业未达账id
	   @BankAccountId	INT,		--银行账户id
	   @cid				INT,		--对账币种
	   @IsAuto			INT,			--是否自动对账  0：不是  1：是
	   @RelevanceDate	DATE,		--勾对时间
	   @chvOperatorID	VARCHAR(50)		---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @SQL	NVARCHAR(MAX),
	   @CheckDate		INT,
	   @CheckFsettleId		INT,
	   @CheckFsettleNo		INT,
	   @stypeid			VARCHAR(50),
	   @StartFBeginDate		DATE
	   
SELECT @CheckDate =IsUse   FROM Te_AutoCheckRules WHERE Id=2
SELECT @CheckFsettleId =IsUse   FROM Te_AutoCheckRules WHERE Id=3
SELECT @CheckFsettleNo =IsUse   FROM Te_AutoCheckRules WHERE Id=4
SELECT @stypeid = STypeId	FROM Te_BankAccount WHERE Id = @BankAccountId
SELECT @StartFBeginDate = FBegin	FROM Ac_Period ap INNER JOIN Te_StartPeriod ts ON ts.SFYear = ap.FYear AND ts.SFPeriod = ap.FPeriod AND ts.STypeId = @stypeid
	

IF NOT EXISTS(SELECT TOP 1 1 FROM Te_StartPeriod tsp WHERE TSP.STypeId = @stypeid AND IsUse = 1)
BEGIN
	RAISERROR('当前银行账户所属的分支机构的出纳系统没有结束初始化，不能进行勾对！',16,0)
	RETURN -2
END 


DECLARE @COUNTS INT,
		@LOOP	INT,
		@CURRTID	INT
DECLARE @_MAXGroupId	INT
SET @_MAXGroupId = 0 

CREATE TABLE #tempids
(
	id	INT
);

IF @IsAuto = 0  --手动对账
BEGIN

	------9.7.1新需求，按合计金额进行对比，合计金额相同，则所有相关项一起勾对

	DECLARE @_JournalFCreditTotal	NUMERIC(22,10)
			,@_JournalFDebitTotal	NUMERIC(22,10)
			,@_StatementFCreditTotal	NUMERIC(22,10)
			,@_StatementFDebitTotal	NUMERIC(22,10)

	--计算日记账类别的借贷合计		
	SELECT	@_JournalFCreditTotal=SUM(ISNULL(T.FCredit,0)) 
			,@_JournalFDebitTotal=SUM(ISNULL(T.FDebit,0))
	FROM	(
		SELECT	JD.FCredit
				,JD.FDebit
		FROM	Te_Journal_Detail JD
		INNER JOIN f_split(@JournalIds,',') I ON I.a = JD.Id
		WHERE JD.Cid = @cid
			AND JD.AccountId = @BankAccountId
		UNION ALL
		SELECT	JD.FCredit
				,JD.FDebit
		FROM	Te_AccountInTransit_Detail JD
		INNER JOIN f_split(@AccountInTransitJournalIds,',') I ON I.a = JD.Id
		INNER JOIN Te_AccountInTransit_Index JI ON JI.ID = JD.indexid AND JI.Type = 0
		WHERE	JI.Cid = @cid
			AND JI.AccountId = @BankAccountId
		
	) T

	--计算对账单类别的借贷合计
	SELECT	@_StatementFCreditTotal=SUM(ISNULL(T.FCredit,0)) 
			,@_StatementFDebitTotal=SUM(ISNULL(T.FDebit,0))
	FROM	(
		SELECT	SD.FCredit
				,SD.FDebit
		FROM	Te_BankStatementDetail SD
		INNER JOIN f_split(@StatementIds,',') I ON I.a = SD.Id
		WHERE SD.Cid = @cid
			AND SD.AccountId = @BankAccountId
		UNION ALL
		SELECT	SD.FCredit
				,SD.FDebit
		FROM	Te_AccountInTransit_Detail SD
		INNER JOIN f_split(@AccountInTransitStatementIds,',') I ON I.a = SD.Id
		INNER JOIN Te_AccountInTransit_Index SI ON SI.ID = SD.indexid AND SI.Type = 1
		WHERE	SI.Cid = @cid
			AND SI.AccountId = @BankAccountId
		
	) T
	
	IF @_JournalFCreditTotal = @_StatementFDebitTotal
	BEGIN
		SELECT @_MAXGroupId=ISNULL(MAX(GroupId),0)+1 FROM Te_CheckRelevance
		
		--插入未达账的
		INSERT INTO Te_CheckRelevance(RelevanceDate,JournalAccountInTransitId,GroupId)
		SELECT	@RelevanceDate
				,JD.Id
				,@_MAXGroupId
		FROM	Te_AccountInTransit_Detail JD
		INNER JOIN Te_AccountInTransit_Index SI ON SI.Id = JD.IndexId AND SI.Type = 0
		INNER JOIN f_split(@AccountInTransitJournalIds,',') I ON I.a = JD.Id
		WHERE JD.FCredit <> 0 
			AND JD.FDebit = 0
			
		INSERT INTO Te_CheckRelevance(RelevanceDate,StatementAccountInTransitId,GroupId)
		SELECT	@RelevanceDate
				,JD.Id
				,@_MAXGroupId
		FROM	Te_AccountInTransit_Detail JD
		INNER JOIN Te_AccountInTransit_Index SI ON SI.Id = JD.IndexId AND SI.Type = 1
		INNER JOIN f_split(@AccountInTransitStatementIds,',') I ON I.a = JD.Id
		WHERE JD.FDebit <> 0 
			AND JD.FCredit = 0
			
		--插入日记账
		INSERT INTO Te_CheckRelevance(RelevanceDate,JournalId,GroupId)
		SELECT	@RelevanceDate
				,JD.Id
				,@_MAXGroupId
		FROM	Te_Journal_Detail JD
		INNER JOIN f_split(@JournalIds,',') I ON I.a = JD.Id
		WHERE JD.FCredit <> 0 
			AND JD.FDebit = 0
			
		INSERT INTO Te_CheckRelevance(RelevanceDate,StatementId,GroupId)
		SELECT	@RelevanceDate
				,JD.Id
				,@_MAXGroupId
		FROM	Te_BankStatementDetail JD
		INNER JOIN f_split(@StatementIds,',') I ON I.a = JD.Id
		WHERE JD.FDebit <> 0 
			AND JD.FCredit = 0
	END


	IF @_JournalFDebitTotal = @_StatementFCreditTotal
	BEGIN
		SET @_MAXGroupId=0
		SELECT @_MAXGroupId=ISNULL(MAX(GroupId),0)+1 FROM Te_CheckRelevance
		
		--插入未达账的
		INSERT INTO Te_CheckRelevance(RelevanceDate,JournalAccountInTransitId,GroupId)
		SELECT	@RelevanceDate
				,JD.Id
				,@_MAXGroupId
		FROM	Te_AccountInTransit_Detail JD
		INNER JOIN Te_AccountInTransit_Index SI ON SI.Id = JD.IndexId AND SI.Type = 0
		INNER JOIN f_split(@AccountInTransitJournalIds,',') I ON I.a = JD.Id
		WHERE JD.FDebit <> 0 
			AND JD.FCredit = 0
			
		INSERT INTO Te_CheckRelevance(RelevanceDate,StatementAccountInTransitId,GroupId)
		SELECT	@RelevanceDate
				,JD.Id
				,@_MAXGroupId
		FROM	Te_AccountInTransit_Detail JD
		INNER JOIN Te_AccountInTransit_Index SI ON SI.Id = JD.IndexId AND SI.Type = 1
		INNER JOIN f_split(@AccountInTransitStatementIds,',') I ON I.a = JD.Id
		WHERE JD.FCredit <> 0 
			AND JD.FDebit = 0
			
		--插入日记账
		INSERT INTO Te_CheckRelevance(RelevanceDate,JournalId,GroupId)
		SELECT	@RelevanceDate
				,JD.Id
				,@_MAXGroupId
		FROM	Te_Journal_Detail JD
		INNER JOIN f_split(@JournalIds,',') I ON I.a = JD.Id
		WHERE JD.FDebit <> 0 
			AND JD.FCredit = 0
			
		INSERT INTO Te_CheckRelevance(RelevanceDate,StatementId,GroupId)
		SELECT	@RelevanceDate
				,JD.Id
				,@_MAXGroupId
		FROM	Te_BankStatementDetail JD
		INNER JOIN f_split(@StatementIds,',') I ON I.a = JD.Id
		WHERE JD.FCredit <> 0 
			AND JD.FDebit = 0
	END
	------9.7.1新需求end
/*
SELECT *,FDebitTotal FROM Te_AccountInTransit_Index
SELECT * FROM Te_AccountInTransit_Detail
SELECT * FROM Te_AccountInTransit_Index
SELECT * FROM Te_AccountInTransit_Detail
select * from Te_CheckRelevance
*/
----START-1------------------------------手动对账时，处理未达账的勾对----------------------------------------
/*
	IF @AccountInTransitJournalIds <> '' OR @AccountInTransitStatementIds <> ''
	BEGIN
		DECLARE @TEMPIDS VARCHAR(MAX),
				@TEMPTABLE VARCHAR(100),
				@TEMPFIELD	VARCHAR(100)
				
		----如果既有银行未达账,又有企业未达账,则先在他们之间进行勾对处理
		IF @AccountInTransitJournalIds <>'' AND @AccountInTransitStatementIds<>''
		BEGIN	
			INSERT INTO #tempids(id)
			SELECT a FROM f_split(@AccountInTransitJournalIds,',')
			
			SELECT @COUNTS = COUNT(*) FROM #tempids
			SET @LOOP = 0
			WHILE @LOOP < @COUNTS
			BEGIN
				SELECT TOP 1 @CURRTID =id  FROM #tempids
				
				SET @SQL = '
				INSERT INTO Te_CheckRelevance(JournalAccountInTransitId,StatementAccountInTransitId,RelevanceDate,JournalId,StatementId)
				SELECT TOP 1 j.id
						,s.id
						,@RelevanceDate
						,0
						,0
				FROM	Te_AccountInTransit_Detail j
				INNER JOIN Te_AccountInTransit_Index i ON i.ID = j.indexid
				INNER JOIN	Te_AccountInTransit_Detail s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit 
				INNER JOIN Te_AccountInTransit_Index ii ON ii.ID = s.indexid AND ii.type = 1
				WHERE	j.Id ='+CAST(@CURRTID AS VARCHAR)+'
					AND s.Id IN (SELECT A FROM f_split('''+@AccountInTransitStatementIds+''','',''))
					AND j.Id NOT IN (SELECT JournalAccountInTransitId FROM Te_CheckRelevance)
					AND s.Id NOT IN (SELECT StatementAccountInTransitId FROM Te_CheckRelevance)
					AND i.Cid = @cid
					AND ii.cid = @cid
					AND i.AccountId = @BankAccountId
					AND ii.AccountId = @BankAccountId
					
				'
				EXEC sp_executesql @SQL,N'@RelevanceDate	DATE,
					   @cid	INT,
					   @BankAccountId	INT ',@RelevanceDate,@cid,@BankAccountId
				
				DELETE FROM #tempids WHERE id = @CURRTID
				SET @LOOP += 1
			END
		END
		
		--如果有银行未达账，则用银行未达账与对账单进行勾对
		IF @AccountInTransitJournalIds <> ''
		BEGIN
			INSERT INTO #tempids(id)
			SELECT a FROM f_split(@AccountInTransitJournalIds,',')
			SET @TEMPIDS = @StatementIds
			SET @TEMPTABLE = 'Te_BankStatementDetail'
			SET @TEMPFIELD = 'StatementId'
			
			SELECT @COUNTS = COUNT(*) FROM #tempids
			SET @LOOP = 0
			WHILE @LOOP < @COUNTS
			BEGIN
				SELECT TOP 1 @CURRTID =id  FROM #tempids
				
				SET @SQL = '
				INSERT INTO Te_CheckRelevance(JournalAccountInTransitId,StatementId,RelevanceDate,StatementAccountInTransitId,JournalId)
				SELECT TOP 1 j.id
						,s.id
						,@RelevanceDate
						,0
						,0
				FROM	Te_AccountInTransit_Detail j
				INNER JOIN Te_AccountInTransit_Index I ON I.ID = j.indexid AND I.Type=0
				INNER JOIN	'+@TEMPTABLE+' s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit  AND s.Cid = i.Cid AND s.AccountId = i.AccountId
				WHERE	j.Id ='+CAST(@CURRTID AS VARCHAR)+'
					AND s.Id IN (SELECT A FROM f_split('''+@TEMPIDS+''','',''))
					AND j.Id NOT IN (SELECT JournalAccountInTransitId FROM Te_CheckRelevance)
					AND s.Id NOT IN (SELECT '+@TEMPFIELD+' FROM Te_CheckRelevance)
					AND i.Cid = @cid
					AND i.AccountId = @BankAccountId
					
				'
				EXEC sp_executesql @SQL,N'@RelevanceDate	DATE,
					   @cid	INT ,
					   @BankAccountId	INT ',@RelevanceDate,@cid,@BankAccountId
				
				DELETE FROM #tempids WHERE id = @CURRTID
				SET @LOOP += 1
			END
			
		END
		
		--如果有企业未达账，则用企业未达账与银行日记账进行勾对
		IF @AccountInTransitStatementIds<>''
		BEGIN
			INSERT INTO #tempids(id)
			SELECT a FROM f_split(@AccountInTransitStatementIds,',')
			SET @TEMPIDS = @JournalIds
			SET @TEMPTABLE = 'Te_Journal_Detail'
			SET @TEMPFIELD = 'JournalId'
			
			
			SELECT @COUNTS = COUNT(*) FROM #tempids
			SET @LOOP = 0
			WHILE @LOOP < @COUNTS
			BEGIN
				SELECT TOP 1 @CURRTID =id  FROM #tempids
				
				SET @SQL = '
				INSERT INTO Te_CheckRelevance(StatementAccountInTransitId,JournalId,RelevanceDate,JournalAccountInTransitId,StatementId)
				SELECT TOP 1 j.id
						,s.id
						,@RelevanceDate
						,0
						,0
				FROM	Te_AccountInTransit_Detail j
				INNER JOIN Te_AccountInTransit_Index I ON I.ID = j.indexid AND I.Type=1
				INNER JOIN	'+@TEMPTABLE+' s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit  AND s.Cid = i.Cid AND s.AccountId = i.AccountId
				WHERE	j.Id ='+CAST(@CURRTID AS VARCHAR)+'
					AND s.Id IN (SELECT A FROM f_split('''+@TEMPIDS+''','',''))
					AND j.Id NOT IN (SELECT StatementAccountInTransitId FROM Te_CheckRelevance)
					AND s.Id NOT IN (SELECT '+@TEMPFIELD+' FROM Te_CheckRelevance)
					AND i.Cid = @cid
					AND i.AccountId = @BankAccountId
				'
				EXEC sp_executesql @SQL,N'@RelevanceDate	DATE,
					   @cid	INT ,
					   @BankAccountId	INT ',@RelevanceDate,@cid,@BankAccountId
				
				DELETE FROM #tempids WHERE id = @CURRTID
				SET @LOOP += 1
			END
			
		END
		
	END
	
	DELETE FROM #tempids
----END-1---------------------------------------手动对账时，处理未达账勾对-------------------------------------------

----START-2--------------------------手动对账时，处理银行日记账和银行对账单的勾对--------------------------------------
	INSERT INTO #tempids(id)
	SELECT	a.a
	FROM	f_split(@JournalIds,',') a

	SELECT @COUNTS = COUNT(*) FROM #tempids
	SET @LOOP = 0
	WHILE @LOOP < @COUNTS
	BEGIN
		SELECT TOP 1 @CURRTID =id  FROM #tempids
		
		SET @SQL = '
		INSERT INTO Te_CheckRelevance(JournalId,StatementId,RelevanceDate,StatementAccountInTransitId,JournalAccountInTransitId)
		SELECT TOP 1 j.id
				,s.id
				,@RelevanceDate
				,0
				,0
		FROM	Te_Journal_Detail j
		INNER JOIN	Te_BankStatementDetail s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit  AND s.Cid = j.Cid AND s.AccountId = j.AccountId
		WHERE	j.Id ='+CAST(@CURRTID AS VARCHAR)+'
			AND s.Id IN (SELECT A FROM f_split('''+@StatementIds+''','',''))
			AND j.Id NOT IN (SELECT JournalId FROM Te_CheckRelevance)
			AND s.Id NOT IN (SELECT StatementId FROM Te_CheckRelevance)
			AND j.Cid = @cid
			AND j.AccountId = @BankAccountId
		'
		EXEC sp_executesql @SQL,N'@RelevanceDate	DATE,
			   @cid	INT ,
			   @BankAccountId	INT ',@RelevanceDate,@cid,@BankAccountId
		
		DELETE FROM #tempids WHERE id = @CURRTID
		SET @LOOP += 1
	END
----END-2--------------------------手动对账时，处理银行日记账和银行对账单的勾对--------------------------------------	
*/
END

/*		
SET @SQL = '
INSERT INTO Te_CheckRelevance(JournalId,StatementId,RelevanceDate)
SELECT	 j.id
		,s.id
		,@RelevanceDate
FROM	Te_Journal_Detail j
INNER JOIN	Te_BankStatementDetail s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit  AND s.Cid = j.Cid AND s.AccountId = j.AccountId
WHERE	j.Id IN ('+@JournalIds+')
	AND s.Id IN ('+@StatementIds+')
	AND j.Id NOT IN (SELECT JournalId FROM Te_CheckRelevance)
	AND s.Id NOT IN (SELECT StatementId FROM Te_CheckRelevance)
	AND j.Cid = @cid
	AND j.iscash = 0
'
*/

ELSE   --自动对账
BEGIN
----START-3---------------------------------------自动对账时，处理未达账勾对-------------------------------------------
	----如果既有银行未达账,又有企业未达账,则先在他们之间进行勾对处理
	DECLARE @JournalAccountInTransitCount INT,
			@StatementAccountInTransitCount INT
			
		DECLARE @TEMPIDS VARCHAR(MAX),
				@TEMPTABLE VARCHAR(100),
				@TEMPFIELD	VARCHAR(100)
				
	SELECT @JournalAccountInTransitCount = ISNULL(COUNT(*),0)
	FROM Te_AccountInTransit_Detail A 
	INNER JOIN Te_AccountInTransit_Index I ON I.Id = A.IndexId AND I.Type=0
	WHERE NOT EXISTS(SELECT JournalAccountInTransitId FROM Te_CheckRelevance where JournalAccountInTransitId=a.Id)
	
	SELECT @StatementAccountInTransitCount = ISNULL(COUNT(*),0) 
	FROM Te_AccountInTransit_Detail A 
	INNER JOIN Te_AccountInTransit_Index I ON I.Id = A.IndexId AND I.Type=1
	WHERE NOT EXISTS(SELECT StatementAccountInTransitId FROM Te_CheckRelevance where StatementAccountInTransitId=a.Id)
	
	IF @JournalAccountInTransitCount > 0 AND @StatementAccountInTransitCount >0
	BEGIN	
		INSERT INTO #tempids(id)
		SELECT a.Id 
		FROM Te_AccountInTransit_Detail A 
		INNER JOIN Te_AccountInTransit_Index I ON I.Id = A.IndexId AND I.Type=0
		WHERE NOT EXISTS(SELECT JournalAccountInTransitId FROM Te_CheckRelevance where JournalAccountInTransitId=a.Id)
	
		SELECT @COUNTS = COUNT(*) FROM #tempids
		SET @LOOP = 0
		WHILE @LOOP < @COUNTS
		BEGIN
			SELECT TOP 1 @CURRTID =id  FROM #tempids			
			SELECT @_MAXGroupId=ISNULL(MAX(GroupId),0)+1 FROM Te_CheckRelevance
			
			SET @SQL = '
			INSERT INTO Te_CheckRelevance(JournalAccountInTransitId,StatementAccountInTransitId,RelevanceDate,JournalId,StatementId,groupid)
			SELECT TOP 1 j.id
					,s.id
					,@RelevanceDate
					,0
					,0
					,@groupid
			FROM	Te_AccountInTransit_Detail j
			INNER JOIN Te_AccountInTransit_Index i ON i.ID = j.indexid
			INNER JOIN	Te_AccountInTransit_Detail s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit '
		
			IF @CheckDate = 1
				SET @SQL += '  AND s.createDate = j.createDate '
			IF @CheckFsettleId = 1
				SET @SQL += '  AND s.FSettleId = j.FSettleId '
			IF @CheckFsettleNo = 1
				SET @SQL += ' AND s.FSettleNo = j.FSettleNo '
				
			SET @SQL += '
			INNER JOIN Te_AccountInTransit_Index ii ON ii.ID = s.indexid AND ii.type = 1
			WHERE	j.Id ='+CAST(@CURRTID AS VARCHAR)+'
				AND NOT EXISTS(SELECT JournalAccountInTransitId FROM Te_CheckRelevance where JournalAccountInTransitId=j.Id)
				AND NOT EXISTS(SELECT StatementAccountInTransitId FROM Te_CheckRelevance where StatementAccountInTransitId=s.Id)
				AND i.Cid = @cid
				AND ii.cid = @cid
				AND i.AccountId = @BankAccountId
				AND ii.AccountId = @BankAccountId
				
			'
			EXEC sp_executesql @SQL,N'@RelevanceDate	DATE,
				   @cid	INT,
				   @BankAccountId	INT,
				   @groupid	INT ',@RelevanceDate,@cid,@BankAccountId,@_MAXGroupId
			
			DELETE FROM #tempids WHERE id = @CURRTID
			SET @LOOP += 1
		END
	END
	
	--如果有银行未达账，则用银行未达账与对账单进行勾对
	IF @JournalAccountInTransitCount > 0
	BEGIN
		INSERT INTO #tempids(id)
		SELECT a.Id 
		FROM Te_AccountInTransit_Detail A 
		INNER JOIN Te_AccountInTransit_Index I ON I.Id = A.IndexId AND I.Type=0
		WHERE NOT EXISTS(SELECT JournalAccountInTransitId FROM Te_CheckRelevance where JournalAccountInTransitId=A.Id)
		
		SET @TEMPIDS = @StatementIds
		SET @TEMPTABLE = 'Te_BankStatementDetail'
		SET @TEMPFIELD = 'StatementId'
		
		SELECT @COUNTS = COUNT(*) FROM #tempids
		SET @LOOP = 0
		WHILE @LOOP < @COUNTS
		BEGIN
			SELECT TOP 1 @CURRTID =id  FROM #tempids
			SELECT @_MAXGroupId=ISNULL(MAX(GroupId),0)+1 FROM Te_CheckRelevance
			
			SET @SQL = '
			INSERT INTO Te_CheckRelevance(JournalAccountInTransitId,StatementId,RelevanceDate,StatementAccountInTransitId,JournalId,groupid)
			SELECT TOP 1 j.id
					,s.id
					,@RelevanceDate
					,0
					,0
					,@groupid
			FROM	Te_AccountInTransit_Detail j
			INNER JOIN Te_AccountInTransit_Index I ON I.ID = j.indexid AND I.Type=0
			INNER JOIN	'+@TEMPTABLE+' s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit  AND s.Cid = i.Cid AND s.AccountId = i.AccountId'
		
			IF @CheckDate = 1
				SET @SQL += '  AND s.Businessdate = j.createDate '
			IF @CheckFsettleId = 1
				SET @SQL += '  AND s.FSettleId = j.FSettleId '
			IF @CheckFsettleNo = 1
				SET @SQL += ' AND s.FSettleNo = j.FSettleNo '
				
			SET @SQL += '
			WHERE	j.Id ='+CAST(@CURRTID AS VARCHAR)+'
				AND NOT EXISTS(SELECT JournalAccountInTransitId FROM Te_CheckRelevance where JournalAccountInTransitId=j.Id)
				AND NOT EXISTS(SELECT '+@TEMPFIELD+' FROM Te_CheckRelevance where '+@TEMPFIELD+'=s.Id)
				AND s.BusinessDate	>= @StartFBeginDate
				AND i.Cid = @cid
				AND i.AccountId = @BankAccountId
				
			'
			EXEC sp_executesql @SQL,N'@RelevanceDate	DATE,
			   @StartFBeginDate	DATE,
			   @cid	INT,
			   @BankAccountId	INT,
			   @groupid	int ',@RelevanceDate,@StartFBeginDate,@cid,@BankAccountId,@_MAXGroupId
			
			DELETE FROM #tempids WHERE id = @CURRTID
			SET @LOOP += 1
		END
		
	END
	
	--如果有企业未达账，则用企业未达账与银行日记账进行勾对
	IF @StatementAccountInTransitCount >0
	BEGIN
		INSERT INTO #tempids(id) 
		SELECT A.Id
		FROM Te_AccountInTransit_Detail A 
		INNER JOIN Te_AccountInTransit_Index I ON I.Id = A.IndexId AND I.Type=1
		WHERE NOT EXISTS(SELECT StatementAccountInTransitId FROM Te_CheckRelevance where StatementAccountInTransitId=A.Id)
		
		SET @TEMPIDS = @JournalIds
		SET @TEMPTABLE = 'Te_Journal_Detail'
		SET @TEMPFIELD = 'JournalId'
		
		SELECT * FROM #tempids
		SELECT @COUNTS = COUNT(*) FROM #tempids
		SET @LOOP = 0
		WHILE @LOOP < @COUNTS
		BEGIN
			SELECT TOP 1 @CURRTID =id  FROM #tempids
			SELECT @_MAXGroupId=ISNULL(MAX(GroupId),0)+1 FROM Te_CheckRelevance
			
			SET @SQL = '
			INSERT INTO Te_CheckRelevance(StatementAccountInTransitId,JournalId,RelevanceDate,JournalAccountInTransitId,StatementId,groupid)
			SELECT TOP 1 j.id
					,s.id
					,@RelevanceDate
					,0
					,0
					,@groupid
			FROM	Te_AccountInTransit_Detail j
			INNER JOIN Te_AccountInTransit_Index I ON I.ID = j.indexid AND I.Type=1
			INNER JOIN	'+@TEMPTABLE+' s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit  AND s.Cid = i.Cid AND s.AccountId = i.AccountId'
		
			IF @CheckDate = 1
				SET @SQL += '  AND s.Businessdate = j.createDate '
			IF @CheckFsettleId = 1
				SET @SQL += '  AND s.FSettleId = j.FSettleId '
			IF @CheckFsettleNo = 1
				SET @SQL += ' AND s.FSettleNo = j.FSettleNo '
				
			SET @SQL += '
			WHERE	j.Id ='+CAST(@CURRTID AS VARCHAR)+'
				AND NOT EXISTS(SELECT StatementAccountInTransitId FROM Te_CheckRelevance where StatementAccountInTransitId=j.Id)
				AND NOT EXISTS(SELECT '+@TEMPFIELD+' FROM Te_CheckRelevance where '+@TEMPFIELD+'=s.Id)
				AND s.BusinessDate	>= @StartFBeginDate
				AND i.Cid = @cid
				AND i.AccountId = @BankAccountId
			'
			EXEC sp_executesql @SQL,N'@RelevanceDate	DATE,
			   @StartFBeginDate	DATE,
			   @cid	INT,
			   @BankAccountId	INT,
			   @groupid	int ',@RelevanceDate,@StartFBeginDate,@cid,@BankAccountId,@_MAXGroupId
			
			DELETE FROM #tempids WHERE id = @CURRTID
			SET @LOOP += 1
		END
		
	END

	DELETE FROM #tempids
----END-3---------------------------------------自动对账时，处理未达账勾对-------------------------------------------

----START-4-----------------------------自动对账时，处理银行日记账和银行对账单的勾对------------------------------
	INSERT INTO #tempids(id)
	SELECT	j.Id
	FROM	Te_Journal_Detail j
	WHERE	NOT EXISTS(SELECT JournalId FROM Te_CheckRelevance where JournalId=j.Id)
		AND j.BusinessDate	>= @StartFBeginDate
		AND j.Cid = @cid
		AND j.iscash = 0
		AND j.AccountId = @BankAccountId
		
	SELECT @COUNTS = COUNT(*) FROM #tempids
	SET @LOOP = 0
	WHILE @LOOP < @COUNTS
	BEGIN
		SELECT TOP 1 @CURRTID =id  FROM #tempids
			SELECT @_MAXGroupId=ISNULL(MAX(GroupId),0)+1 FROM Te_CheckRelevance
		
		SET @SQL = '
		INSERT INTO Te_CheckRelevance(JournalId,StatementId,RelevanceDate,StatementAccountInTransitId,JournalAccountInTransitId,groupid)
		SELECT TOP 1 j.id
				,s.id
				,@RelevanceDate
				,0
				,0
				,@groupid
		FROM	Te_Journal_Detail j
		INNER JOIN	Te_BankStatementDetail s ON s.FDebit =j.FCredit  AND s.FCredit =j.FDebit  AND s.Cid = j.Cid AND s.AccountId = j.AccountId'
		
		IF @CheckDate = 1
			SET @SQL += '  AND s.Businessdate = j.BusinessDate '
		IF @CheckFsettleId = 1
			SET @SQL += '  AND s.FSettleId = j.FSettleId '
		IF @CheckFsettleNo = 1
			SET @SQL += ' AND s.FSettleNo = j.FSettleNo '
			
		SET @SQL += '
		WHERE	j.Id ='+CAST(@CURRTID AS VARCHAR)+'
			AND NOT EXISTS(SELECT JournalId FROM Te_CheckRelevance where JournalId=j.Id)
			AND NOT EXISTS(SELECT StatementId FROM Te_CheckRelevance where StatementId=s.Id)
			AND j.BusinessDate	>= @StartFBeginDate
			AND s.BusinessDate	>= @StartFBeginDate
			AND j.Cid = @cid
			AND j.iscash = 0
			AND j.AccountId = @BankAccountId
		'
		EXEC sp_executesql @SQL,N'@RelevanceDate	DATE,
			   @StartFBeginDate	DATE,
			   @cid	INT,
			   @BankAccountId	INT,
			   @groupid	int ',@RelevanceDate,@StartFBeginDate,@cid,@BankAccountId,@_MAXGroupId
		
		DELETE FROM #tempids WHERE id = @CURRTID
		SET @LOOP += 1
	END	
	
----END-4-----------------------------自动对账时，处理银行日记账和银行对账单的勾对------------------------------
	
	
	/*
	DECLARE @SQL_HEAD VARCHAR(500)
	SET @SQL_HEAD = 'INSERT INTO Te_CheckRelevance(JournalId,StatementId,RelevanceDate)'
	SET @SQL = '
	SELECT	TOP 1 j.id
			,s.id
			,@RelevanceDate
	FROM	Te_Journal_Detail j
	INNER JOIN	Te_BankStatementDetail s ON  s.FDebit =j.FCredit  AND s.FCredit =j.FDebit AND s.Cid = j.Cid AND s.AccountId = j.AccountId'
	
	IF @CheckDate = 1
		SET @SQL += '  AND s.Businessdate = j.BusinessDate '
	IF @CheckFsettleId = 1
		SET @SQL += '  AND s.FSettleId = j.FSettleId '
	IF @CheckFsettleNo = 1
		SET @SQL += ' AND s.FSettleNo = j.FSettleNo '
	SET @SQL += '
	WHERE	j.Id NOT IN (SELECT JournalId FROM Te_CheckRelevance)
		AND s.Id NOT IN (SELECT StatementId FROM Te_CheckRelevance)
		AND j.BusinessDate	>= @StartFBeginDate
		AND s.BusinessDate	>= @StartFBeginDate
		AND j.Cid = @cid
		AND j.iscash = 0
		AND j.AccountId = @BankAccountId
	'

	SET @SQL = 'WHILE EXISTS ('+@SQL+')
	BEGIN
		'+@SQL_HEAD+@SQL+'
	END'
	*/
END

/*
print @sql	
EXEC sp_executesql @SQL,N'@JournalIds 		VARCHAR(MAX),	
	   @StatementIds	VARCHAR(MAX),
	   @BankAccountId	INT,
	   @RelevanceDate	DATE,
	   @StartFBeginDate	DATE,
	   @cid	INT ',@JournalIds,@StatementIds,@BankAccountId,@RelevanceDate,@StartFBeginDate,@cid
*/	
	
--DROP TABLE #tempids		 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_CheckSaveSetAcPeriod]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_CheckSaveSetAcPeriod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--==========================================
--created by: glj
--date: 2016-07-08
--function description: 期间设置保存时判断是否满足条件
--==========================================
CREATE PROCEDURE Gp_CheckSaveSetAcPeriod
(
	@Fyear		INT,		--年度
	@FPeriod	INT,		--期间
	@RowCount	INT,		--设置多少期
	@STypeID	VARCHAR(50),--分支机构ID
	@Type		INT,		--0：会计期间维护 1：运维平台 2：启用期间设置
	@Flag		VARCHAR(2)	--A 总账  B 业务
)
--@encode$--
AS
SET NOCOUNT ON
--会计期间最小年度及最小期间
DECLARE 
	@BillData	DATETIME
SELECT @BillData=FBegin FROM Ac_Period WHERE FYear=@Fyear AND FPeriod=@FPeriod

--判断固定资产时用 权限范围分支机构
DECLARE @SType TABLE(STypeId VARCHAR(50))
INSERT INTO @SType(STypeId)
SELECT TypeId FROM SType WHERE (@Type IN(0,1) AND IsSelfVerify=1 AND TypeId<>'00000') OR (@Type=2 AND VerifyID=@STypeID)
--业务财务独立核算  非启用期间设置见面判断
IF EXISTS(SELECT * FROM SysData WHERE SubName='stypeindependentopen' AND SubValue=1) AND @Flag=''
	BEGIN
		--判断年度是否更改
		IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE SFYear<>@FYear AND ISNULL(SFYear,0)<>0)
			RETURN 1
		IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE SFYear=@FYear AND ISNULL(SFYear,0)<>0 AND @RowCount<SFPeriod AND ISNULL(SFPeriod,0)<>0)
			RETURN 2		
	END
IF(@Type IN(0,1) OR ISNULL(@Flag,'') IN('A',''))
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='IsUseAcSystem' AND SubValue=1)
			BEGIN
				--出纳，不需要判断分支机构
				IF EXISTS(SELECT TOP 1 1 FROM Te_StartPeriod WHERE (ISNULL(SFYear,0)<>@Fyear OR (@Flag = '' AND ISNULL(SFPeriod,0)>@RowCount)) AND (ISNULL(SFYear,0)<>0 OR ISNULL(SFPeriod,0)<>0))
					RETURN -1
					
				--总账开账状态已发生更改
				IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype P INNER JOIN @SType S ON S.STypeId=P.Stypeid AND P.IsUse=1 AND (P.SFYear<>@Fyear OR P.SFPeriod<>@FPeriod))
					RETURN 	3
					
				--年结存数据
				IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount A INNER JOIN @SType S ON S.STypeId=A.STypeId AND (FDebit<>0 OR FDebitFor<>0 OR FCredit<>0 OR FCreditFor<>0 OR FDebitqty<>0 AND FCreditqty<>0) AND (FYear<>@Fyear OR (FYear=@Fyear AND @FPeriod=1)))
					RETURN 4
						
				--总账联用 -判断修改后的年度跟出纳年度是否一致		
				IF EXISTS(SELECT TOP 1 1 FROM Te_StartPeriod A INNER JOIN @SType S ON S.STypeId=A.STypeId AND IsConnect=1 AND (SFYear<>@Fyear OR SFPeriod<>@FPeriod))
					RETURN 5
				--调整后的年度及期间必须小于等于系统内未记账会计凭证最小日期的年度和期间值
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher V INNER JOIN (SELECT MIN(BillDate) BillDate,BillNumberId FROM Ac_Voucher A INNER JOIN @SType S ON S.STypeId=A.STypeId AND IfCheck='F' GROUP BY BillNumberId) F ON F.BillNumberId=V.BillNumberId AND (FYear<@Fyear OR (FYear=@Fyear AND FPeriod<@FPeriod )))
					RETURN 6						
			END	
			
		IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='assets' AND SubValue=1)
			BEGIN

				--固定资产是否 存在初始化的
				IF EXISTS(SELECT TOP 1 1 FROM dbo.SType A INNER JOIN @SType S ON S.STypeId=A.TypeId AND IfAssetsIni=1 AND deleted=0 )
					RETURN 7
				--当前启用日期后存在初始固定资产卡片	
				IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards C INNER JOIN @SType S ON S.STypeId=C.STypeId AND C.AssetsState=1 AND InAccountDate>=@BillData)
					RETURN 8
				--修改后的启用期间与固定资产卡片折旧计划表冲突
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FYear<>@Fyear OR FMonth<>@FPeriod) AND EXISTS(SELECT TOP 1 1 FROM Ac_DepreciationPlan P INNER JOIN @SType S ON S.STypeId=P.STypeId)
					RETURN 9	
			END
	END
IF(@Type IN(0,1) OR ISNULL(@Flag,'') IN('B',''))
	BEGIN
		--业务已经开账
		IF EXISTS(SELECT TOP 1 1 FROM SType_UserConfig A INNER JOIN @SType S ON S.STypeId=A.STypeId AND Value=1 AND(SFYear<>@Fyear OR SFPeriod<>@FPeriod))
				RETURN 10
		--当前启用日期后存在期初单据	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex A INNER JOIN @SType S ON S.STypeId=A.STypeId AND IsIni=1 AND BillDate>=@BillData)
			BEGIN
				RETURN 11
			END
		
	END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
	判断序列号入库时，关联的商品是否与该序列号之前关联的商品不同
	如果不同，则返回提示信息
作者：卢春
日期：2006-05-30
*/
CREATE    PROCEDURE GP_CheckSerialRepeatIn (
	@intBillNumberID	varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @intBillType int,@chvDetailBillName varchar(20),@intID int
DECLARE @chvPTypeID varchar(50),@strSQL varchar(2000)

SELECT @intBillType = BillType FROM BillIndex WHERE BillNumberID = @intBillNumberID
SET @chvDetailBillName = CASE @intBillType
						WHEN 34 THEN 'BuyBill'
						ELSE ''
						END
IF @chvDetailBillName = '' RETURN

CREATE TABLE #TmpDetailBill (
Serial	VARCHAR(MAX),
PTypeID	varchar(50),
[ID]	int )

CREATE TABLE #TmpSerial(
nID		int identity(1,1),
Serial	varchar(200),
Serial1	varchar(200),
PTypeID	varchar(50),
[ID]	int )

CREATE TABLE #AllSerial(
nID		int identity(1,1),
Serial	varchar(200),
Serial1	varchar(200),
PTypeID	varchar(50),
[ID]	int )

SET @strSQL = '
INSERT INTO #TmpDetailBill (Serial,PTypeID,[ID])
SELECT	Serial,PTypeID,[ID] 
FROM ' + @chvDetailBillName + '
WHERE	BillNumberID = ' + CAST(@intBillNumberID AS varchar(50)) + '
		AND Serial NOT LIKE '''''
EXEC(@strSQL)

DECLARE SerialCursor CURSOR FOR
	SELECT	PTypeID,
			[ID]
	FROM	#TmpDetailBill
			ORDER BY [ID]

OPEN SerialCursor
FETCH NEXT FROM SerialCursor INTO @chvPTypeID,@intID

WHILE @@FETCH_STATUS = 0
BEGIN
	TRUNCATE TABLE #TmpSerial
	SET @strSQL = '
		DECLARE  @TmpBill TABLE
		(	
			Serial 	VARCHAR(MAX),
			PTypeId	varchar(100),
			ID		int
		)

		INSERT INTO @TmpBill(Serial,PTypeId,ID)
		SELECT	Serial,PTypeID,[ID]
		FROM	#TmpDetailBill
		WHERE	[ID] = ' + CAST(@intID AS varchar(50)) + '

		DECLARE	@i 					int,				--计数器
				@j 					int,				--计数器
				@k					int,				--计数器
				@Serial_str			varchar(8000),
				@Serial_tmp			varchar(1000),
				@TPTypeID			varchar(100),
				@TXId				int

		SELECT @i=PatIndex(''%я%'',Serial)+2,@j=DataLength(Serial),@TPTypeID=PTypeId,@TXId=[ID] FROM @TmpBill
		SET @k = 0
		WHILE @i>2 AND @i<@j
		BEGIN
			SELECT @serial_str = SUBSTRING(Serial,@i,@j-@i+1) FROM @TmpBill
			SET @k = patindex(''%я%'',@serial_str)
			SET @Serial_tmp = SUBSTRING(@serial_str,1,@k-1)
			INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,ID) VALUES(@Serial_tmp,@Serial_tmp,@TPTypeID,@TXId)
			INSERT INTO #AllSerial(Serial,Serial1,PTypeId,ID) VALUES(@Serial_tmp,@Serial_tmp,@TPTypeID,@TXId)
			SELECT @k = datalength(Serial1) FROM #TmpSerial
			SET @i = @i + @k + 2
		END '
	EXEC(@strSQL)
	FETCH NEXT FROM SerialCursor INTO @chvPTypeID,@intID
END
CLOSE SerialCursor
DEALLOCATE SerialCursor

SELECT	TOP 10 a.[ID],a.Serial,b.PTypeID
--INTO	#TmpSerialRepeat
FROM	#AllSerial a,GP_CruPTypeSerial b
WHERE	a.Serial = b.Serial AND a.PTypeID <> b.PTypeID

DROP TABLE #TmpDetailBill
DROP TABLE #AllSerial




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CheckSingleAccountUsage]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CheckSingleAccountUsage] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2012-06-14
----描述：检查会计科目是否使用
----========================
CREATE    PROCEDURE [dbo].[GP_CheckSingleAccountUsage]
(
    @stypeid VARCHAR(50),
    @atypeid VARCHAR(50)
)
--@encode$--
AS 

DECLARE @isUsed INT
SET @isUsed = 0

SELECT  t.name AS tableName, c1.colname AS ColA,
        c2.colname AS ColS
INTO #t1
FROM    sys.tables t
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'atypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'atypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c1 ON c1.tblname = t.name
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'stypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'stypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c2 ON c2.tblname = t.name
WHERE   t.name NOT IN ('Ac_Account_Assist_CheckItems','Ac_Balance','Ac_Balance_Assist_CheckItems','Ac_Balance_Assist_CheckItems_Detail','Ac_IniAccount','Ac_IniAccount_Assist_CheckItems','Ac_IniAccount_Assist_CheckItems_Detail','Ac_ProfitAndLoss','Ac_ProfitAndLoss_Detail','Ac_Voucher_Bill','Ac_Voucher_Bill')
UNION ALL SELECT 'SType','atypeid','typeid'
UNION ALL SELECT 'SType','atypeid2','typeid'
UNION ALL SELECT 'SType','atypeid3','typeid'
UNION ALL SELECT 'SType','atypeid4','typeid'
UNION ALL SELECT 'Ac_Items_Detail','DEPATYPEID','stypeid'
UNION ALL SELECT 'Ac_Items_Detail','DISATYPEID','stypeid'
ORDER BY TableName


SELECT IDENTITY(INT,1,1) AS rid ,*
INTO #t2
FROM #t1


DECLARE @i INT
DECLARE @count INT
DECLARE @tbname NVARCHAR(200)
DECLARE @colaname NVARCHAR(200)
DECLARE @colsname NVARCHAR(200)
DECLARE @sql NVARCHAR(2000)

SELECT @count = COUNT(1) FROM #t1

SET @i = 1

WHILE @i < @count AND @isUsed = 0
BEGIN 
        SELECT @tbname = TableName,@colaname=cola,@colsname = cols
        FROM #t2
        WHERE rid = @i
        
        SET @sql = 'SELECT @isUsed = Count(1) FROM '
                + @tbname + ' WHERE ' + @colaname
                + ' =  ''' + @ATypeId + ''''
                + ' AND ' + @colsname + ' = '''
                + @STypeId + ''''
                        
        EXECUTE sp_executesql @SQL,
            N'@isUsed INT OUTPUT', @isUsed OUTPUT
    
    SET @i += 1
END

DROP TABLE #t1,#t2

IF @isUsed > 0
    RETURN 1

--	Ac_Balance
SELECT TOP 1
        @isused += 1
FROM    Ac_Balance
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FBEGINBALANCE, 0)) +
        ABS(ISNULL(FDebit, 0)) +
        ABS(ISNULL(FCredit, 0)) + 
        ABS(ISNULL(FENDBALANCE, 0)) +
        ABS(ISNULL(FYTDDEBIT, 0)) +
        ABS(ISNULL(FYTDCREDIT, 0)) > 0


--	Ac_Balance_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(iniYTotal, 0)) + 
        ABS(ISNULL(FDebit, 0)) +
        ABS(ISNULL(FCredit, 0)) + 
        ABS(ISNULL(iniTotal, 0)) > 0
        
--	Ac_Balance_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) +
        ABS(ISNULL(INITOTAL,0)) > 0
        
        
--	Ac_IniAccount
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(iniTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(iniYTotal,0)) + 
        ABS(ISNULL(FYTotal,0)) > 0
        
        
--	Ac_IniAccount_Assist_CheckItems
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(IniYTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(IniTotal,0)) +
        ABS(ISNULL(FYTotal,0)) > 0
        
        
--	Ac_IniAccount_Assist_CheckItems_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_IniAccount_Assist_CheckItems_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(IniYTotal,0)) + 
        ABS(ISNULL(FDebit,0)) +
        ABS(ISNULL(FCredit,0)) + 
        ABS(ISNULL(IniTotal,0)) +
        ABS(ISNULL(FYTotal,0)) > 0
        
        
--	Ac_ProfitAndLoss
SELECT TOP 1
        @isused += 1
FROM    Ac_ProfitAndLoss
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FFTotal,0)) + 
        ABS(ISNULL(FYTOTAL,0)) > 0
        
        
--	Ac_ProfitAndLoss_Detail
SELECT TOP 1
        @isused += 1
FROM    Ac_ProfitAndLoss_Detail
WHERE   STypeid = @stypeid
        AND ATypeId = @atypeid
        AND ABS(ISNULL(FFTotal,0)) + 
        ABS(ISNULL(FYTOTAL,0)) > 0
        
        
--	Ac_Voucher_Bill
SELECT TOP 1
        @isused += 1
FROM    Ac_Voucher_Bill
WHERE   STypeid = @stypeid
        AND (ATypeId = @atypeid OR ATypeId2 = @atypeid)
        AND ABS(ISNULL(FDebitTotal,0)) + 
        ABS(ISNULL(FCreditTotal,0)) > 0
        
        
IF @isUsed > 0
BEGIN 
    RETURN 1
END
        
RETURN 0

GO


SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CheckStypeRef]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CheckStypeRef] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2012-06-14
----描述：检查会计科目是否被分支机构的往来单位设置引用
----========================
CREATE    PROCEDURE [dbo].[GP_CheckStypeRef]
(
    @stypeid VARCHAR(50),
    @atypeid VARCHAR(50)
)
--@encode$--
AS 

IF @stypeid = '00000'
BEGIN
    RETURN 0
END

SELECT atypeid INTO #tmp FROM SType WHERE TypeId = @stypeid UNION
SELECT atypeid2 FROM SType WHERE TypeId = @stypeid UNION
SELECT atypeid3 FROM SType WHERE TypeId = @stypeid UNION
SELECT atypeid4 FROM SType WHERE TypeId = @stypeid UNION
SELECT AtypeId FROM BillAtype WHERE STypeId = @stypeid


IF EXISTS(SELECT @atypeid AS a
                INTERSECT
                SELECT atypeid FROM #tmp
)
    RETURN 1
RETURN 0

GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_checkType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_checkType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-08-02
--	描述：判断基本信息是否可用
---------------------------------------------
CREATE PROCEDURE GP_checkType
( 
	@typeid		VARCHAR(50),
	@flag		VARCHAR(1)
)
--@encode$--
AS
SET NOCOUNT ON

IF @flag='s'
BEGIN
   IF @typeid NOT IN (SELECT TYPEID FROM SType WHERE deleted='0' AND sonnum=0)
   BEGIN
   		RETURN -1
   END
   RETURN 0
END
IF @flag='d'
BEGIN
   IF @typeid NOT IN (SELECT TYPEID FROM Department WHERE deleted='0' AND sonnum=0)
   BEGIN
   		RETURN -1
   END
   RETURN 0
END
IF @flag='e'
BEGIN
   IF @typeid NOT IN (SELECT TYPEID FROM employee WHERE deleted='0' AND sonnum=0)
   BEGIN
   		RETURN -1
   END
   RETURN 0
END
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-07-30
	描述：V3检查科目是否使用过
*/
CREATE PROCEDURE GP_CheckV3Account
--@encode$--
AS
SET NOCOUNT ON
 
IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId='00001')   --已经分配过
	BEGIN
		CREATE TABLE #tempAtypeid
		(
			id   INT  IDENTITY(1,1),
			atypeid VARCHAR(50)
		)
		
		--获取已导入哪些科目
		INSERT INTO #tempAtypeid
		SELECT TypeId
		FROM dbo.Ac_Account WHERE StypeId='00001'
		
		DECLARE @index INT=1,
				@count INT,
				@atypeid VARCHAR(50),
				@isUsed INT 
				
		SELECT @count=COUNT(*) FROM #tempAtypeid
		
		WHILE @index<=@count
			BEGIN
				SELECT @atypeid=atypeid FROM #tempAtypeid WHERE id=@index
				EXEC @isUsed = GP_CheckRefUsage @stypeid='00001',@atypeid = @atypeid
                IF @isUsed > 0 
                    BEGIN 
						PRINT @atypeid
                        --RAISERROR ('导入的科目在被使用，无法再进行从模板引入科目表！',16,1) ;	
                        RETURN -1 ;
                    END
				
				SET @index=@index+1		
			END
		DROP TABLE #tempAtypeid
		RETURN 0
	END
ELSE 
	RETURN 0

SELECT * FROM dbo.Ac_Account
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	
*/
CREATE PROCEDURE GP_CheckVoucherFlowNoAboutBreakingNo
(
	--@OperatorId		VARCHAR(50),		--当前操作员ID
	@Stypeid		VARCHAR(50),		--分支机构
	@Fyear			INT,				--年度
	@Fperiod		INT,				--期间
	@Vgid			VARCHAR(1000) = ''	--凭证字
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @MINFLOWNO	INT
		,@MAXFLOWNO	INT
		,@FLOWNOCOUNT	INT
		,@LASTISBREAKING INT   --上一个数字是否是断号：0不是，1是
		,@RESULTSTR	VARCHAR(MAX)
		
SET @MINFLOWNO = 0
SET @MAXFLOWNO = 0
SET @FLOWNOCOUNT = 0
SET @LASTISBREAKING = 0
SET @RESULTSTR = ''

SELECT @MINFLOWNO = ISNULL(MIN(FlowNo),0)
FROM dbo.Ac_Voucher
WHERE STypeId = @Stypeid AND FYear = @Fyear AND FPeriod = @Fperiod AND VgId = @Vgid

SELECT @MAXFLOWNO = ISNULL(MAX(FlowNo),0)
FROM dbo.Ac_Voucher
WHERE STypeId = @Stypeid AND FYear = @Fyear AND FPeriod = @Fperiod AND VgId = @Vgid

SELECT @FLOWNOCOUNT = COUNT(FlowNo)
FROM dbo.Ac_Voucher
WHERE STypeId = @Stypeid AND FYear = @Fyear AND FPeriod = @Fperiod AND VgId = @Vgid

IF @MAXFLOWNO  <= 1
BEGIN
	SELECT '没有检查到断号' AS result
	RETURN
END


IF @MINFLOWNO <> 1
	SET @RESULTSTR = '0-'+CAST(@MINFLOWNO AS VARCHAR) + ','

SET @MINFLOWNO+=1

WHILE @MINFLOWNO <= @MAXFLOWNO
BEGIN
	IF NOT EXISTS(SELECT TOP 1 FlowNo  FROM dbo.Ac_Voucher WHERE STypeId = @Stypeid AND FYear = @Fyear AND FPeriod = @Fperiod AND VgId = @Vgid AND FlowNo = @MINFLOWNO)
	BEGIN
		IF @LASTISBREAKING = 0
			SET @RESULTSTR += CAST(@MINFLOWNO-1 AS VARCHAR) + '-'
			
		SET @LASTISBREAKING = 1
	END
	ELSE
	BEGIN
		IF @LASTISBREAKING = 1
			SET @RESULTSTR += CAST(@MINFLOWNO AS VARCHAR) + ','
			
		SET @LASTISBREAKING = 0
	END
		
	SET @MINFLOWNO += 1	
	
END

IF @RESULTSTR = ''
	SELECT '没有检查到断号' AS result
ELSE
	SELECT a AS result FROM f_split(@RESULTSTR,',') 

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO

IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_CheckWLSerial',N'P'))
BEGIN
	DROP PROC GP_CheckWLSerial
END
GO
/*
*			物流单据过账判断序列号是否已过账
*/
CREATE PROC GP_CheckWLSerial
(
	@BillType				INT,
	@GoodsBillNumberID		INT,
	@GoodsBillType			INT,
	@OSerial				VARCHAR(50)='' OUT,
	@Serial					VARCHAR(MAX)
)
AS
BEGIN
	IF @BillType NOT IN(412,413,414)
		RETURN
	
	DECLARE @Tmp TABLE
	(
		Serial				VARCHAR(max),
		RowIndex            INT
	)
	
	IF @BillType=412
	BEGIN
		INSERT INTO @Tmp(Serial,RowIndex) 
		SELECT Serial,ROW_NUMBER() OVER(ORDER BY GETDATE())
		FROM dbo.onShelvesbill A INNER JOIN dbo.onShelvespickIndex B
		ON A.billNumberID=B.billNumberId
		WHERE B.RedWord=0 AND IfCheck='t' AND GoodsBillNumberID=@GoodsBillNumberID AND GoodsBillType=@GoodsBillType
		AND a.GoodsBillNumberID>0
	END
	
	IF @BillType=413
	BEGIN
		INSERT INTO @Tmp(Serial,RowIndex) 
		SELECT Serial,ROW_NUMBER() OVER(ORDER BY GETDATE())
		FROM dbo.pickbill A INNER JOIN dbo.onShelvespickIndex B
		ON A.billNumberID=B.billNumberId
		WHERE B.RedWord=0 AND IfCheck='t' AND GoodsBillNumberID=@GoodsBillNumberID AND GoodsBillType=@GoodsBillType
		AND a.GoodsBillNumberID>0 
	END
	
	IF @BillType=414
	BEGIN
		INSERT INTO @Tmp(Serial,RowIndex) 
		SELECT A.Serial,ROW_NUMBER() OVER(ORDER BY GETDATE())
		FROM dbo.Transportbill A INNER JOIN dbo.BillIndex B
		ON A.billNumberID=B.billNumberId
		WHERE B.RedWord=0 AND IfCheck='t' AND GoodsBillNumberID=@GoodsBillNumberID
		AND a.GoodsBillNumberID>0 
	END
	
	DECLARE @TmpSerial		VARCHAR(MAX),
			@RowIndex		INT,
			@RowCount		INT,
			@ErrorSerial	VARCHAR(50)
	
	SELECT @RowCount=COUNT(1),@RowIndex=1 FROM @Tmp
	
	WHILE(@RowIndex<=@RowCount)
	BEGIN
		SELECT @TmpSerial=Serial FROM @Tmp WHERE RowIndex=@RowIndex
		IF ISNULL(@TmpSerial,'')<>''
		BEGIN
			SET @ErrorSerial=''
			SELECT TOP 1 @ErrorSerial=A.a  FROM dbo.f_split(@Serial,'я') A,dbo.f_split(@TmpSerial,'я') B 
			WHERE A.a=b.a AND a.a<>'' AND b.a<>''
			IF ISNULL(@ErrorSerial,'')<>''
			BEGIN
				SET @OSerial=@ErrorSerial
				RETURN -1
			END
		END
		SET @RowIndex=@RowIndex+1
	END
END




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

CREATE  PROCEDURE Gp_ChkSdAllType
--@encode$--
AS
SET NOCOUNT ON
--EXEC('EXEC Gp_DlExtTabTr')
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 6 AND SubValue = '1')
	AND (EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 10 AND ISNULL(SubValue,'') = '')
		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 9 AND ISNULL(SubValue,'') = '')
		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 11 AND ISNULL(SubValue,'') = '')
		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 13 AND ISNULL(SubValue,'') = ''))
BEGIN
	RETURN 0
END
ELSE
BEGIN
	RETURN 1
END
	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CleanDirtyAccountData]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CleanDirtyAccountData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/07/04
	Description	: 清除总账科目中 未使用的 多余的 数据
*/
CREATE PROCEDURE GP_CleanDirtyAccountData
(
 @TypeId VARCHAR(500), --科目ID
 @STypeId VARCHAR(500)
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @used INT
 EXEC @used = GP_CheckAccountUsage @stypeid = @stypeid, -- varchar(50)
     @atypeid = @typeid -- varchar(50)
     
     
IF @used > 0
BEGIN
    RAISERROR ('该科目已经被使用。',16,1)
    RETURN     	
END

SELECT  t.name AS tableName, c1.colname AS ColA,
    c2.colname AS ColS
INTO #t1
FROM    sys.tables t
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'atypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'atypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c1 ON c1.tblname = t.name
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'stypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'stypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c2 ON c2.tblname = t.name
WHERE t.name IN ('Ac_Balance','Ac_Balance_Assist_CheckItems','Ac_Balance_Assist_CheckItems_Detail',
'Ac_IniAccount','Ac_IniAccount_Assist_CheckItems','Ac_IniAccount_Assist_CheckItems_Detail','Ac_ProfitAndLoss',
'Ac_ProfitAndLoss_Detail','Ac_Voucher_Bill','Ac_Voucher_Bill')

SELECT IDENTITY(INT,1,1) AS rid,* 
INTO #t2
FROM #t1


DECLARE @i INT
DECLARE @count INT
DECLARE @tbname VARCHAR(50)
DECLARE @colsname VARCHAR(50)
DECLARE @colaname VARCHAR(50)
DECLARE @sql VARCHAR(500)

SELECT @i = 1, @count = COUNT(1) FROM #t2

-- 清除垃圾数据
WHILE @i <= @count
BEGIN
	SELECT @tbname = tablename,@colaname=ColA,@colsname=ColS
	FROM #t2 WHERE rid = @i
	
	SET @sql = 'DELETE ['+@tbname+'] WHERE ['+@colsname+'] = '''+@stypeid+''' and ['+@colaname+'] = '''+@TypeId+'''';
	
	EXEC(@sql)
	
	SET @i += 1
END


DROP TABLE #t1,#t2
GO


    
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CleanDirtyAccountData2]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CleanDirtyAccountData2]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/07/04
	Description	: 清除总账科目中 未使用的 多余的 数据--不检查每个科目是否被使用,专用在GP_DistributeAccount反分配中,因为在这段存储过程中的有一段检查过科目是否被引用了.
*/
CREATE PROCEDURE GP_CleanDirtyAccountData2
(
 @TypeId VARCHAR(500), --科目ID
 @STypeId VARCHAR(500)
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @used INT
-- EXEC @used = GP_CheckAccountUsage @stypeid = @stypeid, -- varchar(50)
--     @atypeid = @typeid -- varchar(50)
     
     
--IF @used > 0
--BEGIN
--    RAISERROR ('该科目已经被使用。',16,1)
--    RETURN     	
--END

SELECT  t.name AS tableName, c1.colname AS ColA,
    c2.colname AS ColS
INTO #t1
FROM    sys.tables t
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'atypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'atypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c1 ON c1.tblname = t.name
JOIN    (SELECT t.name AS tblname,
                ISNULL(c.name, s.fldname) AS colname
         FROM   sys.tables t
         LEFT JOIN sys.columns c ON t.object_id = c.object_id
                                    AND c.name LIKE 'stypeid%'
         LEFT JOIN Sys_BaseInfoUsing_Tables s ON s.tblName = t.name
                                            AND s.basType = 'stypeid'
         WHERE  c.name IS NOT NULL
                OR s.fldname IS NOT NULL) c2 ON c2.tblname = t.name
WHERE t.name IN ('Ac_Balance','Ac_Balance_Assist_CheckItems','Ac_Balance_Assist_CheckItems_Detail',
'Ac_IniAccount','Ac_IniAccount_Assist_CheckItems','Ac_IniAccount_Assist_CheckItems_Detail','Ac_ProfitAndLoss',
'Ac_ProfitAndLoss_Detail','Ac_Voucher_Bill','Ac_Voucher_Bill')

SELECT IDENTITY(INT,1,1) AS rid,* 
INTO #t2
FROM #t1


DECLARE @i INT
DECLARE @count INT
DECLARE @tbname VARCHAR(50)
DECLARE @colsname VARCHAR(50)
DECLARE @colaname VARCHAR(50)
DECLARE @sql VARCHAR(500)

SELECT @i = 1, @count = COUNT(1) FROM #t2

-- 清除垃圾数据
WHILE @i <= @count
BEGIN
	SELECT @tbname = tablename,@colaname=ColA,@colsname=ColS
	FROM #t2 WHERE rid = @i
	
	SET @sql = 'DELETE ['+@tbname+'] WHERE ['+@colsname+'] = '''+@stypeid+''' and ['+@colaname+'] = '''+@TypeId+'''';
	
	EXEC(@sql)
	
	SET @i += 1
END


DROP TABLE #t1,#t2
GO


    
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：施训果
	日期：2015-06-29
	描述：清除期初信息
*/

CREATE PROCEDURE Gp_ClearInit 
(
	@STypeID			varchar(50),			--分支机构
	@Type			int			--操作类型
)
--@encode$--
AS
SET NOCOUNT ON

--获取操作的分支机构
CREATE TABLE #stype(typeid VARCHAR(50))
INSERT	INTO #stype
SELECT	TypeId 
FROM F_GetAllManagerBaseTypeId(@STypeID,11,'00001') 
DECLARE @ClearInitSQL	VARCHAR(2000)
BEGIN TRANSACTION  DEL
	DELETE IniCommissionStock WHERE STypeId IN (SELECT  typeid FROM #stype) AND Type=@Type
	DELETE IniCommissionStock_Qty WHERE STypeId IN (SELECT  typeid FROM #stype) AND Type=@Type
	IF @Type=140
	BEGIN
		UPDATE GP_initPTypeSerial SET BTypeID1='' WHERE BTypeID1 IS NOT NULL AND BTypeID1<>'' AND STypeId IN (SELECT  typeid FROM #stype) AND State=32
		DELETE GP_initPTypeSerial WHERE STypeId IN (SELECT  typeid FROM #stype) AND State=13
	END
	IF @Type=144
	DELETE GP_initPTypeSerial WHERE STypeId IN (SELECT  typeid FROM #stype) AND State IN (7,9,10,11,14,16,32)
IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('清空失败！',16,1)
END

COMMIT TRANSACTION  DEL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2019-03-08
	描述：清理操作员在线数据
*/

CREATE  PROCEDURE [dbo].Gp_ClearLoginOnlineUser
(
	@etypeid			VARCHAR(50),		--操作员ID
	@username			VARCHAR(500),		--操作员名称
	@ipAddress			VARCHAR(500),		--IP地址
	@pollingtime		INT, 				--轮询时间
	@currentTime		VARCHAR(100)		--当前时间
)
AS
SET NOCOUNT ON

--先判断条件，不满足则不进入
IF NOT (EXISTS(SELECT TOP 1 1 FROM sysdatadb.dbo.RWXsysadmin WHERE islimlogin = 1 AND ISNULL(dognumber,'')<>'')
			OR EXISTS(SELECT TOP 1 1 FROM sysdatadb.dbo.VirtualDirectoryWithAccount WHERE islimlogin = 1 AND ISNULL(dognumber,'')<>'')
	   )	
BEGIN	
	RETURN 0
END	

DECLARE @dbName			VARCHAR(500)

SET @dbName = db_name()

--自动删除当前库异常的数据
DECLARE @nCurCount INT
CREATE TABLE #curOnLineUserException
(
	nid						INT IDENTITY(1,1),
	[ETypeID_UserTypeID]	VARCHAR(100),	
	[LatestConnectTime]		DATETIME,
	[PollineTime]			INT
)

INSERT INTO #curOnLineUserException([ETypeID_UserTypeID],[LatestConnectTime],[PollineTime])
SELECT	[ETypeID_UserTypeID],		
		[LatestConnectTime],
		[PollineTime]
FROM    dbo.OA_OnlineUser

SET @nCurCount = @@ROWCOUNT

DECLARE @j						INT,
		@curLatestConnectTime	VARCHAR(50),
		@curPollineTime			INT,
		@curdelDbName			VARCHAR(100),
		@curdelETypeId			VARCHAR(100)

SET @j = 1

WHILE @j <= @nCurCount
BEGIN
	SELECT	@curLatestConnectTime	= CONVERT(VARCHAR(30),LatestConnectTime,120),
			@curPollineTime			= PollineTime,
			@curdelETypeId		    = ETypeID_UserTypeID
    FROM	#curOnLineUserException
    WHERE	nid = @j
    
    --INSERT INTO Fx_DelOnlineUser(ETypeID_UserTypeID,DbName,LatestConnectTime,LoginTime,PollineTime,clientFlag)VALUES(@curdelETypeId,@dbName,@curLatestConnectTime,@currentTime,ABS(DATEDIFF(SECOND,@curLatestConnectTime,@currentTime)),'OA_OnlineUser')    
    IF ABS(DATEDIFF(SECOND,@curLatestConnectTime,@currentTime))> @curPollineTime*2
    BEGIN
		DELETE FROM dbo.OA_OnlineUser WHERE [ETypeID_UserTypeID] = @curdelETypeId
    END
	
	SET @j = @j + 1
END

DROP TABLE #curOnLineUserException

--自动删除SysDataDb异常的数据
DECLARE @nCount INT
CREATE TABLE #onLineUserException
(
	nid						INT IDENTITY(1,1),
	[ETypeID_UserTypeID]	VARCHAR(100),
	[DbName]				VARCHAR(100),
	[LatestConnectTime]		DATETIME,
	[PollineTime]			INT
)

INSERT INTO #onLineUserException([ETypeID_UserTypeID],[DbName],[LatestConnectTime],[PollineTime])
SELECT	[ETypeID_UserTypeID],
		[DbName],
		[LatestConnectTime],
		[PollineTime]
FROM    [SysdataDb].dbo.Fx_OnlineUser

SET @nCount = @@ROWCOUNT

DECLARE @i						INT,
		@LatestConnectTime		VARCHAR(50),
		@PollineTime			INT,
		@delDbName				VARCHAR(100),
		@delETypeId				VARCHAR(100)

SET @i = 1

WHILE @i <= @nCount
BEGIN
	SELECT	@LatestConnectTime = CONVERT(VARCHAR(30),LatestConnectTime,120),
			@PollineTime	   = PollineTime,
			@delDbName		   = DbName,
			@delETypeId		   = ETypeID_UserTypeID
    FROM	#onLineUserException
    WHERE	nid = @i
    
    --INSERT INTO Fx_DelOnlineUser(ETypeID_UserTypeID,DbName,LatestConnectTime,LoginTime,PollineTime,clientFlag)VALUES(@delETypeId,@dbName,@LatestConnectTime,@currentTime,ABS(DATEDIFF(SECOND,@LatestConnectTime,@currentTime)),'Fx_OnlineUser')    
    IF ABS(DATEDIFF(SECOND,@LatestConnectTime,@currentTime))> @PollineTime*2
    BEGIN
		DELETE FROM [SysdataDb].dbo.Fx_OnlineUser WHERE DbName = @delDbName AND [ETypeID_UserTypeID] = @delETypeId
    END
	
	SET @i = @i + 1
END

DROP TABLE #onLineUserException


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_ClearPosConfigInfoByID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_ClearPosConfigInfoByID]
GO
--==========================================================
--BY:zy
--DATE:2017-06-28
--DESCRIPTION:改变分支机构时清除关联POS
--==========================================================
CREATE PROC Gp_ClearPosConfigInfoByID
(
	@ID   INT	   -- 账户ID
)
--@encode$--

AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM PayConfigInfo WHERE ID=@ID)
BEGIN
	DELETE FROM POSPayConfigInfo WHERE PayConfigID=@ID
END

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-23
	描述：请购生单自动比价
*/

CREATE PROCEDURE Gp_ClearRequestBill 
(
	@billidlists			VARCHAR(100)	--单据ID集合
)
--@encode$--
AS
SET NOCOUNT ON


BEGIN TRANSACTION  DEL
--DECLARE @config int=0
--SELECT @config=Value FROM Userconfig WHERE ConfigName='qgctrl'

UPDATE	requestbill 
SET		state			=6,
		compareprice	=-1,
		comparetax		=0,
		comparediscount	=1,
		btypeid2=''
WHERE	id IN( SELECT * FROM DBO.f_split(@billidlists,','))
	
IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('清空失败！',16,1)
END

COMMIT TRANSACTION  DEL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：施训果
	日期：2015-06-29
	描述：清除序列号关联信息
*/

CREATE PROCEDURE Gp_ClearSerialRelation 
--@encode$--
AS
SET NOCOUNT ON

--获取操作的分支机构
CREATE TABLE #IniComStock(
				Ptypeid VARCHAR(50),
				Btypeid VARCHAR(50),
				TYPE int,
				Qty  NUMERIC(24, 10) ,
				CostTotal  NUMERIC(24, 10) ,
				Total  NUMERIC(24, 10) ,
				explain varchar(256),
				Stypeid varchar(50)
				) 
				
CREATE TABLE #IniComStockQTY(
				Btypeid VARCHAR(50),
				Stypeid varchar(50),
				CargoID INT,
				DealType tinyint,
				GoodsCostPrice  NUMERIC(24, 10) ,
				GoodsNumber varchar(100),
				ItemID int,
				Iscombined bit,
				KTypeID varchar(50),
				NQty numeric,
				ProduceDate varchar(50),
				Ptypeid varchar(50),
				Qty numeric,
				SerialType tinyint,
				TYPE int,
				ValidDate varchar(50)
				)
INSERT	INTO #IniComStock
SELECT	Ptypeid ,
		Btypeid ,
		TYPE ,
		SUM(Qty) ,
		SUM(CostTotal) ,
		SUM(Total),
		max(explain) ,
		Stypeid 
FROM IniCommissionStock
GROUP BY Ptypeid,Btypeid,TYPE,Stypeid
INSERT INTO #IniComStockQTY
SELECT	Btypeid,
		Stypeid,
		0 AS CargoID,
		0 AS DealType,
		0 AS GoodsCostPrice,
		GoodsNumber,
		ItemID,
		Iscombined,
		'10000' AS KTypeID,
		SUM(NQty),
		ProduceDate,
		Ptypeid,
		SUM(Qty),
		0 AS SerialType,
		Type,
		ValidDate
FROM dbo.IniCommissionStock_Qty
GROUP BY Btypeid,Ptypeid,Type,Stypeid,GoodsNumber,ItemID,Iscombined,ProduceDate,ValidDate
--清空序列号关联对应的货位、自由项、批次批号信息
UPDATE gp_initPtypeSerial SET CargoID = 0,itemID = 0,CostPrice=0,IsCombined = 0,GoodsOrder = 0,GoodsNumber = '',ProduceDate = '',ValidDate = '' --WHERE STATE NOT IN(1,7);
UPDATE gp_iniFactPtypeSerial SET CargoID = 0,itemID = 0,IsCombined = 0,GoodsOrder = 0,GoodsNumber = '',ProduceDate = '',ValidDate = '' --WHERE STATE NOT IN(1,7);
--库存中序列号货位ID不能置为0  (9.8bug3621全部改0了）
--UPDATE gp_initPtypeSerial SET itemID = 0,IsCombined = 0,GoodsOrder = 0,GoodsNumber = '',ProduceDate = '',ValidDate = '' WHERE STATE IN (1,7);
UPDATE gp_CruPtypeSerial SET CargoID = 0,CostPrice=0,itemID = 0,IsCombined = 0,GoodsOrder = 0,GoodsNumber = '',ProduceDate = '',ValidDate = '';

--UPDATE gp_iniFactPtypeSerial SET itemID = 0,IsCombined = 0,GoodsOrder = 0,GoodsNumber = '',ProduceDate = '',ValidDate = '' WHERE STATE IN (1,7);
UPDATE gp_FactPtypeSerial SET itemID = 0,CargoID = 0,IsCombined = 0,GoodsOrder = 0,GoodsNumber = '',ProduceDate = '',ValidDate = '';

DELETE FROM IniCommissionStock;
DELETE FROM IniCommissionStock_Qty;
INSERT INTO IniCommissionStock(
		[Ptypeid]
      ,[Btypeid]
      ,[Type]
      ,[Qty]
      ,[CostTotal]
      ,[Total]
      ,[Tax]
      ,[TaxTotal]
      ,[explain]
      ,[KtypeId]
      ,[EtypeId]
      ,[Stypeid]
      ,[DealType]
      ,[SerialType])
SELECT 
	Ptypeid,
	Btypeid,
	TYPE,
	Qty,
	CostTotal,
	Total,
	0,
	0,
	explain,
	'10000',
	'',
	Stypeid,
	1,
	0
FROM #IniComStock

INSERT INTO dbo.IniCommissionStock_Qty
        ( Ptypeid ,
          Btypeid ,
          Stypeid ,
          Type ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          Qty ,
          NQty ,
          DealType ,
          KTypeID ,
          CargoID ,
          SerialType ,
          GoodsCostPrice
        )
SELECT   
	Ptypeid,
	Btypeid,
	Stypeid,
	Type,
	ItemID,
	Iscombined,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	Qty,
	NQty,
	DealType,
	KTypeID,
	CargoID,
	SerialType,
	GoodsCostPrice
FROM #IniComStockQTY

DROP TABLE #IniComStock
DROP TABLE #IniComStockQTY

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：李灏龙
	日期：2015年2月25日 10:31:11
	描述：对选择的单据进行分类，然后调用GP_Call_Voucher_Generate生成凭证
*/
CREATE PROCEDURE GP_CombineGoodsbill_Generate_Voucher
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@BillType		INT,					-- 单据类型
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@Type			INT = 0	,				-- 结果类型 0.返回错误提示 1.返回错误凭证修改 2.凭证标错，并返回提示
	@specifyDate	DATE = '',				-- 手工指定凭证日期
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@InOutStypeId	VARCHAR(50)='',			-- 调拨单 调入/调出分支
	@IfCommission	INT = 0,					-- 是否提成单311 0.不是 1.是
	@checkdeficit		INT	= 0					--是否检查赤字 0不检查，1检查提示，2检查不能保存
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE sysdata SET SubValue = 1 WHERE SubName = 'BatchCreateStart'
truncate table Ac_Voucher_temp
truncate table Ac_Voucher_Bill_temp
truncate table Ac_Voucher_Bill_Assist_CheckItems_temp
truncate table Ac_Voucher_Generate_Voucherbill_GoodsBills
truncate table ac_BatchCreateVoucher_result
TRUNCATE TABLE Ac_BatchCreatingRsult

----单据信息表
CREATE TABLE #BillsInfor
(	
	billnumerid		INT,
	ifwx			INT,
	VerifyID	VARCHAR(50),
	CID				INT,
	AtypeId		VARCHAR(50),
	AtypeId1	VARCHAR(50),
	BillDate	VARCHAR(50),
	AtId		INT,
	billtype	INT,
	AssetBusinessTypeId	INT,
	AdPriceType INT,
	ChargeOffType INT
)

----分组临时表
CREATE TABLE #GroupTabel
(
	id			INT IDENTITY(1,1),
	VerifyID	VARCHAR(50),
	CID			INT,
	AtypeId		VARCHAR(50),
	AtypeId1	VARCHAR(50),
	BillDate	VARCHAR(50),
	billtype	INT,
	AssetBusinessTypeId	INT,
	AtId		INT,
	AdPriceType	INT,
	ChargeOffType INT
)

DECLARE @voucherdatetype INT	--凭证日期类型
		,@template	INT		--凭证模板选择方式
		--,@sql	VARCHAR(MAX)

SELECT @voucherdatetype = SubValue FROM sysdata WHERE SubName = 'voucherdatetype'
SELECT @template = SubValue FROM sysdata WHERE SubName = 'template'

INSERT INTO #BillsInfor
(
	billnumerid
	,ifwx
	,VerifyID
	,CID
	,AtypeId
	,AtypeId1
	,BillDate
	,AtId
	,billtype
	,AssetBusinessTypeId
	,AdPriceType
	,ChargeOffType
)
SELECT	B.BillNumberId
		,B.ifWX
		,S.VerifyID
		,B.CID
		,ISNULL(B.atypeid,'')
		,ISNULL(B.ATypeID1,'')
		,CASE @voucherdatetype WHEN 1 THEN CAST(B.BillDate AS VARCHAR)
		 ELSE '' 
		END AS BillDate
		,b.ATID
		,b.BillType
		,ISNULL(b.AssetBusinessTypeId,0)
		,B.AdPriceType
		,B.ChargeOffType
FROM	BillIndex B
INNER JOIN SType S ON S.TypeId = B.Stypeid
WHERE B.BillNumberId IN (SELECT a FROM f_split(@BillNumberId,','))
	AND	B.BillNumberId NOT IN(SELECT  GoodsBillId	FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId <> -1 AND IsCost IN(0,2))

IF EXISTS(SELECT a FROM f_split(@BillNumberId,',') WHERE a IN(SELECT  GoodsBillId	FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId <> -1 AND IsCost IN(0,2)))
BEGIN
	INSERT INTO ac_BatchCreateVoucher_result(billcode,txt,flag)
	SELECT T1.BillCode,'【单据已经生成过凭证，无法再次生成！】' AS txt, -13
	FROM f_split(@BillNumberId,',') B
	INNER JOIN dbo.BillIndex T1 ON T1.BillNumberId = B.a
	WHERE B.a IN(SELECT  GoodsBillId	FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId <> -1 AND IsCost IN(0,2))
END


-----如果是维修类的报损、报溢（9，14）单据，是无需生成凭证的，则直接写入Ac_GoodsBill_VoucherBill表中，并删除掉这些单据
IF EXISTS (SELECT TOP 1 1 FROM #BillsInfor WHERE ifwx = 1 AND BillType IN (9,14))
BEGIN
	INSERT INTO Ac_GoodsBill_VoucherBill
	(
		GoodsBillId
		,VourchBillId
	)
	SELECT	billnumerid
			,-1
	FROM	#BillsInfor
	WHERE	ifwx = 1
	AND BillType IN (9,14)
	
	DELETE FROM #BillsInfor WHERE ifwx = 1
END

--如果启用了结转成本配置，那么只有成本凭证的
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1) AND EXISTS (SELECT TOP 1 1 FROM #BillsInfor WHERE BillType IN (139,140,142,402,403))
BEGIN
	INSERT INTO ac_BatchCreateVoucher_result(billcode,txt,flag)
	SELECT T1.BillCode,'【该单据凭证模板只有成本明细】' AS txt, -9
	FROM #BillsInfor B
	INNER JOIN dbo.BillIndex T1 ON T1.BillNumberId = B.billnumerid
	WHERE B.billtype IN(139,140,142,402,403)
	
	DELETE FROM #BillsInfor WHERE billtype IN(139,140,142,402,403)
END


INSERT INTO #GroupTabel
(
	VerifyID
	,CID
	,AtypeId
	,AtypeId1
	,BillDate
	,billtype
	,AssetBusinessTypeId
	,AtId
	,AdPriceType
	,ChargeOffType
)
SELECT	A.VerifyID
		,A.CID
		,A.atypeid
		,A.ATypeID1
		,A.BillDate
		,A.billtype
		,A.AssetBusinessTypeId
		,A.AtId
		,A.AdPriceType
		,A.ChargeOffType
FROM	#BillsInfor A
WHERE	A.ifwx = 0
GROUP BY A.billtype,a.AtId,A.VerifyID,A.CID,A.atypeid,A.ATypeID1,A.BillDate,A.AssetBusinessTypeId,A.AdPriceType,A.ChargeOffType


DECLARE	@index	INT
		,@MaxId	INT
		,@billnumerids	VARCHAR(MAX)
		,@billnumerids1	VARCHAR(MAX) --专门记录调拨单inouttype为1的单子
		,@AtId	INT
		,@Return	INT
		,@CurrCount	INT
		,@_billtype INT

SELECT @index = MIN(id),@MaxId = MAX(id) FROM #GroupTabel

INSERT INTO Ac_BatchCreatingRsult(a)
SELECT	COUNT(*)
FROM	#BillsInfor

SET @Type = 0

WHILE @index <= @MaxId
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Ac_BatchCreatingRsult WITH (NOLOCK) WHERE a < 0)
		BREAK
	
	SET @CurrCount = 0
	SET @billnumerids = ''
	SET @billnumerids1 = ''
	
	--获取本组单据的单据类型
	SELECT	@_billtype = GT.billtype
			,@AtId = GT.AtId
	FROM #GroupTabel GT 
	WHERE GT.id = @index
	
	--获取本组单据的单据数量
	SELECT	@CurrCount=COUNT(*)
	FROM #BillsInfor BI
	INNER JOIN #GroupTabel GT ON GT.VerifyID = BI.VerifyID AND GT.CID = BI.CID AND GT.AtypeId = BI.AtypeId AND GT.AtypeId1 = BI.AtypeId1 
									AND GT.BillDate = BI.BillDate AND GT.billtype = BI.billtype AND GT.AssetBusinessTypeId = BI.AssetBusinessTypeId 
									AND GT.AtId = BI.AtId AND GT.AdPriceType = BI.AdPriceType AND GT.ChargeOffType = BI.ChargeOffType
	WHERE GT.id = @index
	
	--处理调拨单310
	IF @_billtype = 310
	BEGIN
		SELECT	@billnumerids += CAST(billnumerid AS VARCHAR) + ','
		FROM #BillsInfor BI
		INNER JOIN #GroupTabel GT ON GT.VerifyID = BI.VerifyID AND GT.CID = BI.CID AND GT.AtypeId = BI.AtypeId AND GT.AtypeId1 = BI.AtypeId1 
										AND GT.BillDate = BI.BillDate AND GT.billtype = BI.billtype AND GT.AtId = BI.AtId AND GT.AdPriceType = BI.AdPriceType
		WHERE GT.id = @index
			AND	BI.billnumerid NOT IN (SELECT  GoodsBillId	FROM Ac_GoodsBill_VoucherBill WHERE InOutType = -1)
			
		SELECT	@billnumerids1 += CAST(billnumerid AS VARCHAR) + ','
		FROM #BillsInfor BI
		INNER JOIN #GroupTabel GT ON GT.VerifyID = BI.VerifyID AND GT.CID = BI.CID AND GT.AtypeId = BI.AtypeId AND GT.AtypeId1 = BI.AtypeId1 
										AND GT.BillDate = BI.BillDate AND GT.billtype = BI.billtype AND GT.AtId = BI.AtId AND GT.AdPriceType = BI.AdPriceType
		WHERE GT.id = @index
			AND	BI.billnumerid NOT IN (SELECT  GoodsBillId	FROM Ac_GoodsBill_VoucherBill WHERE InOutType = 1)
	END
	ELSE
	BEGIN
		SELECT	@billnumerids += CAST(billnumerid AS VARCHAR) + ','
		FROM #BillsInfor BI
		INNER JOIN #GroupTabel GT ON GT.VerifyID = BI.VerifyID AND GT.CID = BI.CID AND GT.AtypeId = BI.AtypeId AND GT.AtypeId1 = BI.AtypeId1 
										AND GT.BillDate = BI.BillDate AND GT.billtype = BI.billtype AND GT.AssetBusinessTypeId = BI.AssetBusinessTypeId
										AND GT.AtId = BI.AtId AND GT.AdPriceType = BI.AdPriceType AND GT.ChargeOffType = BI.ChargeOffType
		WHERE GT.id = @index
			AND	BI.billnumerid NOT IN (SELECT  GoodsBillId	FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId <> -1 AND IsCost IN(0,2))
	END
	
	SET @index += 1
	SET @AtId = ISNULL(@AtId,-1)
	
	IF @template = 0
		SET @AtId = 0
	
	--waitfor delay '00:00:10'
	IF ISNULL(@billnumerids,'') <> ''
	BEGIN		
		BEGIN TRY
			BEGIN TRAN BatchCreate
			EXEC @Return = GP_Call_Voucher_Generate_BatchCreate @billnumerids,@szCheckMan,@AtId,@specifyDate,@Type,@CreateType,@InOutStypeId,@IfCommission,@checkdeficit
			COMMIT TRAN BatchCreate
			
			IF @Return <> 0
				RETURN @Return
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN BatchCreate
			UPDATE Ac_BatchCreatingRsult SET a -= @CurrCount
			CONTINUE
		END CATCH
		
	END
	
	--继续处理InOutType为1的
	IF ISNULL(@billnumerids1,'') <> ''
	BEGIN		
		BEGIN TRY
			BEGIN TRAN BatchCreate1
			EXEC @Return = GP_Call_Voucher_Generate_BatchCreate @billnumerids1,@szCheckMan,@AtId,@specifyDate,@Type,@CreateType,@InOutStypeId,@IfCommission,@checkdeficit
			COMMIT TRAN BatchCreate1
			IF @Return <> 0
				RETURN @Return
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN BatchCreate1
			UPDATE Ac_BatchCreatingRsult SET a -= @CurrCount
			CONTINUE
		END CATCH
		
	END
	
	UPDATE Ac_BatchCreatingRsult SET a -= @CurrCount
	
	--waitfor delay '00:00:10'
	--IF EXISTS(SELECT TOP 1 1 FROM sysdata with (nolock) WHERE SubName = 'BatchCreateStart' AND SubValue = 0)
	--	BREAK
	
	
END

UPDATE sysdata SET SubValue = 0 WHERE SubName = 'BatchCreateStart'
--select '1','2','3'
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2013-6-20
	描述：手工合并pos小票
-------------------------------------------*/
CREATE PROCEDURE [dbo].Gp_CombinePosBill
(
	@billnumberidlist VARCHAR(max),
	@errcode		INT=0 OUTPUT
)
--@encode$--
AS 
SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********
    DECLARE @N INT ,
        @intVersion INT

    SELECT  @N = CAST(SubValue AS INT)
    FROM    SysData1
    WHERE   SubNo = 2	-- 版本号

IF @N IS NULL RETURN -1

    DECLARE @intBit INT ,
        @intMask INT
    SELECT  @intBit = @N & 15
    SELECT  @intMask = POWER(2, @intBit) ^ POWER(2, @intBit + 1) ^ POWER(2,
                                                              @intBit + 2)
            ^ POWER(2, @intBit + 3) ^ POWER(2, @intBit + 4) ^ POWER(2,
                                                              @intBit + 5)
    SELECT  @intVersion = ( @intMask & @N ) / POWER(2, @intBit)
-- ********	判断是否试用版 - END	********

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @billnumberid > 200
	BEGIN
		SET @errcode=-11
		RAISERROR('试用版最多录200条单据 ！',16,1) 
		RETURN
	END
END  

DECLARE @BillCode VARCHAR(50)='',@Msg VARCHAR(200)=''

SELECT top 1  @BillCode=billcode FROM dbo.PosSaleBillIndex ps  WHERE BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,',')) AND NOT EXISTS(SELECT kid FROM dbo.Stock WHERE deleted=0 AND kid=ps.KID)
IF @BillCode<>''
BEGIN
	SET @errcode=-12
	SET @Msg='流水号为【'+@billcode+'】的小票仓库不存在或者已经停用'
	RAISERROR(@msg,16,1)
	RETURN
END

SELECT top 1  @BillCode=billcode FROM dbo.PosSaleBillIndex ps  WHERE BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,',')) AND NOT EXISTS(SELECT BID FROM dbo.btype WHERE deleted=0 AND bid=ps.BID)
IF @BillCode<>''
BEGIN
	SET @errcode=-13
	SET @Msg='流水号为【'+@billcode+'】的小票往来单位不存在或者已经停用'
	RAISERROR(@msg,16,1)
	RETURN
END

SELECT top 1  @BillCode=billcode FROM dbo.PosSaleBillIndex ps  WHERE BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,',')) AND NOT EXISTS(SELECT Eid FROM dbo.employee WHERE Eid=ps.EID)
IF @BillCode<>''
BEGIN
	SET @errcode=-14
	SET @Msg='流水号为【'+@billcode+'】的小票经手人不存在'--在或者已经停用'
	RAISERROR(@msg,16,1)
	RETURN
END

SELECT top 1  @BillCode=billcode FROM dbo.PosSaleBillIndex ps INNER JOIN dbo.PosSaleBill pb ON ps.BillnumberID=pb.BillnumberID  WHERE ps.BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,',')) AND NOT EXISTS(SELECT Pid FROM dbo.ptype WHERE deleted=0 AND pid=pb.PID)
IF @BillCode<>''
BEGIN
	SET @errcode=-15
	SET @Msg='流水号为【'+@billcode+'】的小票有商品不存在或者已经停用'
	RAISERROR(@msg,16,1)
	RETURN
END

SELECT TOP 1 @BillCode=b.billcode FROM PosSaleBill a
INNER JOIN PosSaleBillIndex b ON a.BillnumberID=b.BillnumberID
INNER JOIN dbo.ptype p  ON p.pid = a.PID AND p.iscombinationproduct = 1
WHERE  b.BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,','))
AND NOT EXISTS(SELECT 1 FROM dbo.CombinationProductIndex c WHERE c.CombinationProductPtypeId = p.typeId AND c.IsCheck = 1 AND c.IsStop = 0)
		
IF @BillCode<>''
BEGIN		
	SET @errcode=-15
	SET @Msg='流水号为【'+@billcode+'】的小票存在组合商品被停用或没有有效明细商品的情况'
	RAISERROR(@msg,16,1)
	RETURN
END

SELECT top 1  @BillCode=billcode FROM dbo.PosSaleBillIndex ps INNER JOIN dbo.PosMulAccount pb ON ps.BillnumberID=pb.BillnumberID  WHERE pb.ATypeID<>-1 and ps.BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,',')) AND NOT EXISTS(SELECT nId FROM dbo.Ac_Items WHERE deleted=0 AND nid=pb.ATypeID)
IF @BillCode<>''
BEGIN
	SET @errcode=-16
	SET @Msg='流水号为【'+@billcode+'】的小票有收付款账户不存在或者已经停用'
	RAISERROR(@msg,16,1)
	RETURN
END

SELECT top 1  @BillCode=billcode FROM dbo.PosSaleBillIndex ps INNER JOIN dbo.PosSaleBill pb ON ps.BillnumberID=pb.BillnumberID  WHERE ps.BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,',')) AND NOT EXISTS(SELECT 1 FROM ptype p INNER JOIN dbo.PType_Units_Ext u ON p.typeId=u.PtypeID WHERE pid=pb.PID AND u.UnitsId=pb.UnitID)
IF @BillCode<>''
BEGIN
	SET @errcode=-17
	SET @Msg='流水号为【'+@billcode+'】的小票有商品的单位不存在'
	RAISERROR(@msg,16,1)
	RETURN
END


SELECT top 1  @BillCode=billcode FROM dbo.PosSaleBillIndex ps INNER JOIN dbo.employee e ON ps.EID=e.Eid AND ps.premoney>ISNULL(e.MaxPre,-999999999918.99) AND ISNULL(e.MaxPre,-999999999918.99)<>-999999999918.99 WHERE ps.BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,','))
IF @BillCode<>''
BEGIN
	SET @errcode=-18
	SET @Msg='流水号为【'+@billcode+'】的小票有抹零金额超过限额'
	RAISERROR(@msg,16,1)
	RETURN
END

SELECT top 1  @BillCode=billcode FROM dbo.PosSaleBillIndex ps INNER JOIN dbo.PosSaleMergeFailed e ON ps.BillnumberID=e.PosBillNumberId AND e.Reason='总账版往来科目为空，不能结存' WHERE ps.BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,','))
IF @BillCode<>''
BEGIN
	DECLARE @IsAcSystem Varchar(50)
    DECLARE @tempVerifyID VARCHAR(50) 
    DECLARE @temphascombination INT
    DECLARE @Isaloneusebsys VARCHAR(50)
    DECLARE @tempbilltype INT
    DECLARE @createbilltype VARCHAR(50)
    DECLARE @atypeid1 VARCHAR(50)
    
    select @tempVerifyID=VerifyID from stype INNER JOIN dbo.PosSaleBillIndex ps ON dbo.SType.Sid = ps.SID where BillCode=@BillCode
    SET @temphascombination=0
    SELECT TOP 1 @temphascombination = p.iscombinationproduct,@tempbilltype=psbi.Billtype FROM PosSaleBill psb 
	INNER JOIN ptype p ON psb.pid=p.pid AND p.iscombinationproduct=1 INNER JOIN dbo.PosSaleBillIndex psbi ON psb.BillnumberID=psbi.BillnumberID WHERE BillCode=@BillCode
	
	IF @tempbilltype=305 AND @temphascombination=1
		SET @createbilltype='12'
	ELSE IF @tempbilltype = 305 
		SET @createbilltype='11'
	ELSE IF @tempbilltype = 307 AND @temphascombination=1
		SET @createbilltype='46'
	ELSE IF @tempbilltype = 307 
		SET @createbilltype='45'
		
	SELECT TOP 1 @atypeid1=AtypeId FROM BillAtype WHERE StypeId=@tempVerifyID AND BillTypeId= CAST(@createbilltype AS VARCHAR)
    --PRINT @tempVerifyID
    --PRINT @createbilltype
    --PRINT @atypeid1
    SELECT @IsAcSystem=subvalue FROM dbo.sysdata WHERE SubName='IsUseAcSystem'
    --未启用《月结业务凭证不进行过账检查》配置的，才判断总账往来科目是否为空
    SELECT @Isaloneusebsys=subvalue FROM dbo.sysdata WHERE SubName='aloneusebsys'
    IF ISNULL(@atypeid1,0)=0 AND @IsAcSystem='1' AND @Isaloneusebsys='0'
	BEGIN
		SET @errcode=-10
		SET @Msg='流水号为【'+@billcode+'】总账版往来科目为空，不能结存'
		RAISERROR(@msg,16,1)
		--PRINT @Msg
		RETURN
	END
	--PRINT 1
END


CREATE TABLE #PosSaleBill
	(
		BillnumberID int  NULL,
		ID int IDENTITY(1,1) NOT NULL,
		PID INT NULL,
		Qty  NUMERIC(24, 10)   NULL,
		BackQty  NUMERIC(24, 10)  NULL DEFAULT(0),
		RetailPrice  NUMERIC(24, 10)   NULL,
		Tax  NUMERIC(24, 10)  NULL DEFAULT(0),
		DisCount  NUMERIC(24, 10)   NULL DEFAULT(1),
		Price  NUMERIC(24, 10)   NULL,
		RetailTotal  NUMERIC(24, 10)   NULL,
		Total  NUMERIC(24, 10)   NULL,
		UnitID INT  NULL DEFAULT(0),
		UnitRate  NUMERIC(24, 10)  NULL Default(1),
		ItemID    bigint   NULL,
		IsCombined  int   NULL,
		BarCode	VARCHAR(200) NULL DEFAULT(''),
		IsGift INT NULL DEFAULT(0),
		Comment VARCHAR(Max) NULL,
		posid INT,
		detailid INT,
		billId INT,
		PromoType INT NOT NULL DEFAULT(0),
		SaleEid  INT NOT NULL DEFAULT(0),
		[producedate] [varchar] (50) DEFAULT (''),
		[validdate] [varchar] (50) DEFAULT (''),
		[goodsnumber] [varchar] (100)DEFAULT (''),
		[serial] [text] DEFAULT (''),
		[goodscostprice] [numeric] (24, 10) DEFAULT(0),
		iscombination INT default(0),
		combinationptypeid	VARCHAR(200) NOT NULL DEFAULT(''),
		ptypeid		VARCHAR(200),
		pindexid	VARCHAR(300) NULL ,
		ktypeid	    VARCHAR(50) NULL,
		couponcode	VARCHAR(200) DEFAULT(''),--商品明细的couponcode
		pricesource VARCHAR(200) DEFAULT(''),
		PromoIDs VARCHAR(200) DEFAULT('')
	)

create clustered index cix_id on #PosSaleBill(id,billId)

CREATE TABLE #BillMulAccount(
	[BillNumberId] INTEGER NOT NULL,
	[posBillNumberId] INTEGER NOT NULL,
	[ATypeID] INT NULL,
	 total  NUMERIC(24, 10) ,
	 ntotal  NUMERIC(24, 10) ,
	[VipCardID] INT NULL DEFAULT(-1),
	[Comment] VARCHAR(500) NULL DEFAULT(''),
	[yhType]  INT NULL DEFAULT(-1),
	[CouponCode] VARCHAR(200) DEFAULT(''),
	VipTotal  NUMERIC(24, 10) DEFAULT(0)
)

CREATE TABLE #daftBillNumerid(billnumberid INT NULL)

BEGIN TRY
DECLARE @stypeid VARCHAR(50),@ktypeid VARCHAR(50),@etypeid VARCHAR(50),@Dtypeid varchar(50),@dfullname VARCHAR(200),
		@VipCardID INT,@billdate VARCHAR(20),@billtype INT,@CargoID INT,@taxtotal  NUMERIC(24, 10) ,@qty  NUMERIC(24, 10) ,
		@btypeid VARCHAR(50),@bid INT,@eid INT,@kid INT,@count INT,@selectbillnumerbids VARCHAR(max),@atypeid VARCHAR(100),@PromoRuleId INT,@PromoIDs VARCHAR(200),@CouponCodes VARCHAR(2000)--记录单据用到的所有优惠券
DECLARE @newbillcode VARCHAR(100),@Day varchar(100),@Month varchar(100),@Year varchar(100),@BillFlag VARCHAR(5),@cefullname VARCHAR(500)=''--单据编号相关
DECLARE @size DECIMAL=10000 ,@DetialSize DECIMAL =10000,@rowcount INT ---这里由500改成10000取消500明细分单的限制，一张小票生成一单
DECLARE @PosBillnumberid INT,@billid INT=0,@tmp INT,@billmaxid INT,@newbillnumberid INT
DECLARE @billPage INT,@detailcount INT,@detalPage INT=1,@billcount INT,@premoney  NUMERIC(24, 10) ,@totalinmoney  NUMERIC(24, 10),@SaveInCzMoney NUMERIC(24,10)   
DECLARE  @i INT=0,@j INT=0
DECLARE @tmpdetailminid INT,@tmpdetailmaxid INT,@posID INT,@tmpmaxbillnumberid INT,@tmpminbillnumberid INT,
		@MAXftotal  NUMERIC(24, 10) , --最后一张已分摊金额
		@MINftotal  NUMERIC(24, 10) , --第一张已分摊金额
		@aftotal INT,--是否分摊过
		@cBillnumberid  NUMERIC(24, 10) ,
		@accountCount int=0,
		@billatypeid INT=0,
		@DealBTypeID VARCHAR(100)     --结算单位

		
CREATE TABLE #tempbillid (id INT IDENTITY(1,1),detailid INT)	

DECLARE PosCursor CURSOR FOR
SELECT PosID,BillnumberID,bid,KID,EID,billdate,VipCardID,PromoRuleId,Billtype,1,CouponCode,PromoIDs
FROM PosSaleBillIndex i
WHERE BillnumberID IN (SELECT * FROM dbo.f_split(@billnumberidlist,',')) 
	 AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.PosRetailRecord WHERE PosBillNumberId=i.BillnumberID)
GROUP BY PosID,BillnumberID,bid,KID,EID,billdate,VipCardID,PromoRuleId,Billtype,CouponCode,PromoIDs
OPEN PosCursor
FETCH NEXT FROM PosCursor
INTO @posID,@PosBillnumberid,@Bid,@Kid,@Eid,@BillDate,@VipCardID,@PromoRuleId,@billtype,@billcount,@CouponCodes,@PromoIDs
IF @Posbillnumberid IS NULL OR @Posbillnumberid=''
BEGIN
	SET @errcode = -10
	CLOSE PosCursor
	DEALLOCATE PosCursor
	RETURN;
END

WHILE @@FETCH_STATUS = 0 
BEGIN
	BEGIN TRAN SaveBill
	
	IF(@billtype=307)
	BEGIN
		SET @billtype=215
	END
	SELECT @btypeid =typeid FROM dbo.btype WHERE bid=@bid
	--启用挂往来
	IF EXISTS(SELECT  TOP 1 1 FROM dbo.PosMulAccount WHERE BillNumberId=@Posbillnumberid AND ATypeID=-1)
	BEGIN
		SELECT @DealBTypeID=denominatedid FROM BType WHERE Bid=@BID
		SELECT TOP 1 @temphascombination = p.iscombinationproduct FROM PosSaleBill psb 
		INNER JOIN ptype p ON psb.pid=p.pid AND p.iscombinationproduct=1 WHERE psb.BillnumberID=@Posbillnumberid
		
		IF @billtype = 215 AND @temphascombination=1
			SET @billtype = 46
		ELSE IF @billtype = 215 
			SET @billtype = 45
		ELSE IF  @temphascombination=1
			SET @BillType=12
		ELSE
			SET @BillType=11
	END
	ELSE
	BEGIN
		SET @DealBTypeID=@BTypeID
	END
	--PRINT @billtype
	SELECT @stypeid=stypeid,@ktypeid=typeId FROM dbo.Stock WHERE Kid=@kid
	SELECT @CargoID=CargoID FROM dbo.CargoType WHERE KtypeID=@ktypeid AND IsDefault=1
	SELECT @etypeid=typeId,@dtypeid=DtypeID FROM dbo.employee WHERE Eid=@eid
	SELECT @dfullname=fullname FROM dbo.Department WHERE typeid=@dtypeid
	
	SELECT TOP 1 @atypeid=b.AtypeId FROM BillAtype b INNER JOIN dbo.SType s ON s.VerifyID = b.StypeId WHERE s.TypeId=@stypeid AND b.BillTypeId=CAST(@billtype AS VARCHAR)
	-------------单据编号start----------
	SELECT @Year=YEAR(GETDATE())
	IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @billtype)  AND  EXISTS( SELECT 1 FROM UserConfig WHERE ConfigName='BillCodeConfig' AND Value='1') 
	BEGIN
		SELECT @MONTH = typeId FROM Employee WHERE typeid = @etypeid
		SELECT @DAY = FullName FROM Stock WHERE typeid =@ktypeid
		SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @ETypeId
	END
	ELSE
	BEGIN
		SELECT @Month=Month(GETDATE())
		SELECT @Day=DAY(GETDATE())
	END
	--------------单据编号end------------
	--将表头合并后的明细插入到零时表，
	TRUNCATE TABLE #PosSaleBill
	INSERT INTO #PosSaleBill 
	SELECT a.BillnumberID,a.PID,CASE  WHEN @billtype IN(11,12,305) THEN CAST(Qty AS NUMERIC(24,10)) ELSE CAST(-Qty AS NUMERIC(24,10)) END AS Qty,
	        CAST(BackQty AS NUMERIC(24,10)) AS BackQty,CAST(RetailPrice AS NUMERIC(24,10)) AS RetailPrice,
	        tax,a.DisCount,CAST(Price AS NUMERIC(24,10)) AS Price,CASE WHEN  @billtype IN(11,12,305) THEN CAST(RetailTotal AS NUMERIC(24,10)) ELSE CAST(-RetailTotal AS NUMERIC(24,10)) END AS RetailTotal,
			CASE WHEN @billtype IN(11,12,305) THEN CAST(Total AS NUMERIC(24,10)) ELSE CAST(-Total AS NUMERIC(24,10)) END AS Total,UnitID,UnitRate,ItemID,IsCombined,BarCode,IsGift,a.Comment,b.PosID,a.ID,DENSE_RANK() over(order by b.BillnumberID),a.PromoType,
			a.SaleEid,a.producedate,a.validdate,a.goodsnumber,a.serial,a.goodscostprice,0,'',p.typeid,
		p.typeid+'_'+CAST(ROW_NUMBER() OVER(ORDER BY p.PID) AS VARCHAR) + '_'+RIGHT(100000000 + CONVERT(bigint, ABS(CHECKSUM(NEWID()))), 9),
		sk.typeid,a.couponcode,a.pricesource ,a.PromoIDs
	FROM PosSaleBill a
	INNER JOIN PosSaleBillIndex b ON a.BillnumberID=b.BillnumberID
	INNER JOIN ptype p ON a.pid=p.pid
	INNER JOIN stock sk ON b.kid=sk.kid
	WHERE a.BillnumberID=b.BillnumberID AND a.BillnumberID =@PosBillnumberid AND b.Billtype=CASE  WHEN @billtype IN (215,45,46) THEN 307 ELSE 305 end	--这里有坑，销售出库单是305
	AND  b.BID=@Bid AND b.KID=@Kid AND b.EID=@Eid AND b.VipCardID=@VipCardID AND billdate=@BillDate AND PromoRuleId=@PromoRuleId
	ORDER BY b.BillnumberID,a.id
	/***********************************处理组合品Start*******************************/
	DECLARE @hascombination INT
			,@isauto INT
	SET @hascombination=0
	SET @isauto=0
	SELECT @isauto=autogenerate FROM posinfo WHERE posid=@posid--是否自动带入批次批号
	SELECT TOP 1 @hascombination = p.iscombinationproduct FROM #PosSaleBill psb 
	INNER JOIN ptype p ON psb.pid=p.pid AND p.iscombinationproduct=1
	
	IF @hascombination=1
	BEGIN
		--处理上表体数据
		UPDATE #PosSaleBill SET iscombination = 1
		--插入下表体数据 
		INSERT INTO #PosSaleBill( BillnumberID ,PID ,Qty ,BackQty ,RetailPrice ,Tax ,DisCount ,Price ,RetailTotal ,Total ,UnitID ,UnitRate ,
								ItemID ,IsCombined ,BarCode ,IsGift ,Comment ,posid ,detailid ,billId ,PromoType ,SaleEid ,producedate ,validdate ,goodsnumber ,
								serial ,goodscostprice ,iscombination ,combinationptypeid ,ptypeid ,pindexid ,ktypeid ,couponcode ,pricesource ,PromoIDs )
		SELECT BillnumberID,psb.PID,CAST(Qty AS NUMERIC(24,10)) AS Qty,CAST(BackQty AS NUMERIC(24,10)) AS BackQty,
		CAST(RetailPrice AS NUMERIC(24,10)) AS RetailPrice,Tax,DisCount,CAST(Price AS NUMERIC(24,10)) AS Price,
		CAST(RetailTotal AS NUMERIC(24,10)) AS RetailTotal,
		CAST(Total AS NUMERIC(24,10)) AS Total,
		UnitID,UnitRate,ItemID,IsCombined,BarCode,IsGift,psb.Comment,posid,detailid,
		billId,PromoType,SaleEid,validdate,producedate,goodsnumber,
		serial,goodscostprice,0,combinationptypeid,ptypeid,pindexid,psb.ktypeid,couponcode,pricesource,PromoIDs
		FROM #PosSaleBill psb INNER JOIN ptype p ON psb.pid=p.pid AND ISNULL(p.iscombinationproduct,0)=0

		--获取组合品配件信息
		--金额比例计算：((cpd.Price * cpd.qty ) / cpi.price)
		IF (@isauto = 0)
		BEGIN
			INSERT INTO #PosSaleBill
			SELECT psb.BillnumberID,p.PID,CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) as qty,BackQty,
			CAST((psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) AS NUMERIC(24,10)) AS RetailPrice,
			tax,discount,
			CAST((psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10)) AS NUMERIC(24,10)) AS price,
			CAST(psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price) AS NUMERIC(24,10)) AS RetailTotal,
			CAST(psb.total * ((cpd.Price * cpd.qty ) / cpi.price) AS NUMERIC(24,10)) AS total,
			cpd.unit AS UnitID,u.rate AS UnitRate,cpd.ItemID,CASE WHEN ISNULL(p.customitemfrom,0)=1 THEN 1 ELSE 0 END AS IsCombined,p.entrycode as BarCode,psb.IsGift,'由组合品生成的配件商品' as comment,
			psb.PosID,psb.ID,DENSE_RANK() over(order by psb.BillnumberID),0 AS PromoType,
			psb.saleeid,'' as validdate,'' as producedate,'' as goodsnumber,'' as serial,0 as goodscostprice,0,cpi.combinationproductptypeid,
			p.typeid,psb.pindexid,psb.ktypeid,couponcode,pricesource,psb.PromoIDs
			FROM CombinationProductdetail cpd
			INNER JOIN CombinationProductIndex cpi ON cpd.combinationproductid=cpi.combinationproductid AND cpi.isstop=0 AND cpi.ischeck=1 
			INNER JOIN Ptype p ON cpd.ptypeid=p.typeid --AND p.deleted = 0 
			INNER JOIN #PosSaleBill psb ON cpi.combinationproductptypeid=psb.ptypeid AND ISNULL(psb.iscombination,0)=1 
			INNER JOIN PType_Units_Ext u ON u.UnitsId=cpd.Unit AND u.ptypeId = cpd.PtypeID 
		END
		ELSE
		BEGIN
			INSERT INTO #PosSaleBill
			SELECT psb.BillnumberID,p.PID,dbo.F_RoundQty(CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) as qty,dbo.F_RoundQty(BackQty),
			dbo.F_RoundPrice((psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) AS RetailPrice,
			dbo.F_RoundTax(tax),dbo.F_RoundDiscount(discount),
			dbo.F_RoundPrice((psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) / CAST(CAST(psb.qty AS NUMERIC(24,12))*CAST(cpd.qty AS NUMERIC(24,12)) AS NUMERIC(24,10))) AS price,
			dbo.F_RoundTotal(psb.retailtotal * ((cpd.Price * cpd.qty ) / cpi.price)) AS RetailTotal,
			dbo.F_RoundTotal(psb.total * ((cpd.Price * cpd.qty ) / cpi.price)) AS total,
			cpd.unit AS UnitID,u.rate AS UnitRate,
			ISNULL((select top 1 ItemID from GOODSSTOCKS_QTY gq 
                    inner join ptype p on p.typeid=gq.ptypeid
                    inner join stock s on s.typeid=gq.ktypeid
                    inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
                    where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
                    ),'') as ItemID,
			CASE WHEN ISNULL(p.customitemfrom,0)=1 THEN 1 ELSE 0 END AS IsCombined,
			p.entrycode as BarCode,psb.IsGift,'由组合品生成的配件商品' as comment,
			psb.PosID,psb.ID,DENSE_RANK() over(order by psb.BillnumberID),0 AS PromoType,
			psb.saleeid,
			ISNULL((select top 1 ValidDate from GOODSSTOCKS_QTY gq 
				inner join ptype p on p.typeid=gq.ptypeid
				inner join stock s on s.typeid=gq.ktypeid
				inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
				where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
            ),'') as validdate,
            ISNULL((select top 1 ProduceDate from GOODSSTOCKS_QTY gq 
				inner join ptype p on p.typeid=gq.ptypeid
				inner join stock s on s.typeid=gq.ktypeid
				inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
				where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid),'') as producedate,
            ISNULL((select top 1 GoodsNumber from GOODSSTOCKS_QTY gq 
				inner join ptype p on p.typeid=gq.ptypeid
				inner join stock s on s.typeid=gq.ktypeid
				inner join CargoType c on c.ktypeid=s.typeid and c.Cargoid=gq.Cargoid
				where p.typeid=cpd.ptypeid  and s.typeid=psb.ktypeid
            ),'') as goodsnumber,
			'' as serial,-1 as goodscostprice,0,cpi.combinationproductptypeid,
			p.typeid,psb.pindexid,psb.ktypeid,psb.couponcode,psb.pricesource,psb.PromoIDs 
			FROM CombinationProductdetail cpd
			INNER JOIN CombinationProductIndex cpi ON cpd.combinationproductid=cpi.combinationproductid AND cpi.isstop=0 AND cpi.ischeck=1 
			INNER JOIN Ptype p ON cpd.ptypeid=p.typeid --AND p.deleted = 0 
			INNER JOIN #PosSaleBill psb ON cpi.combinationproductptypeid=psb.ptypeid AND ISNULL(psb.iscombination,0)=1 
			INNER JOIN PType_Units_Ext u ON u.UnitsId=cpd.Unit AND u.ptypeId = cpd.PtypeID 
		END
			
		UPDATE #PosSaleBill SET RetailTotal=dbo.F_RoundTotal(RetailTotal),Total=dbo.F_RoundTotal(Total)
		--组合品差异
		DECLARE @Diff TABLE(
			PindexID VARCHAR(100),
			Diff	 NUMERIC(24,10),
			RowIndex INT
		)

		DECLARE @RCount INT=0,
				@RIndex INT=1,
				@PIndexID VARCHAR(100),
				@ID INT,
				@DiffTotal NUMERIC(24,10)
	
		INSERT INTO @Diff
		        ( PindexID, Diff,RowIndex )
        SELECT  A.PindexID ,
                dbo.F_RoundTotal(CAST(A.Total - B.Total AS NUMERIC(24,10))),
                ROW_NUMBER() OVER(ORDER BY GETDATE())
        FROM    ( SELECT    SUM(Total) AS Total ,
                            PindexId
                  FROM      #PosSaleBill psb
                  WHERE     ISNULL(Iscombination,0) = 1
                  GROUP BY  PindexId
                ) A
                INNER JOIN ( SELECT SUM(Total) AS Total ,
                                    PindexId
                             FROM   #PosSaleBill
                             WHERE  ISNULL(Iscombination,0) = 0
                             GROUP BY PindexId
                           ) B ON A.PIndexID = B.PIndexID
		WHERE A.Total-B.Total<>0
		
		SELECT @RCount=COUNT(1) FROM @Diff
		WHILE(@RIndex<=@RCount)
		BEGIN
			 SELECT @PIndexID=PIndexID,@DiffTotal=Diff FROM @Diff WHERE RowIndex=@RIndex
			 SELECT TOP 1 @ID=ID FROM #PosSaleBill WHERE PIndexID=@PIndexID AND ISNULL(IScombination,0)=0 AND Total >= @DiffTotal ORDER BY Total
			 UPDATE #PosSaleBill SET  RetailTotal=dbo.F_RoundTotal(CAST(RetailTotal+@DiffTotal AS NUMERIC(24,10))),Total=dbo.F_RoundTotal(CAST(Total+@DiffTotal AS NUMERIC(24,10))) WHERE ID=@ID
			 UPDATE #PosSaleBill SET  RetailPrice=dbo.F_RoundPrice(CAST(RetailTotal/Qty AS NUMERIC(24,10))),Price=dbo.F_RoundPrice(CAST(Total/Qty AS NUMERIC(24,10))) WHERE ID=@ID
			 SET @RIndex=@RIndex+1
		END
	END

	/***********************************处理组合品end**********************************/
	IF NOT EXISTS(SELECT TOP 1 1 FROM #PosSaleBill WHERE ISNULL(iscombination,0)=0)
	BEGIN
		ROLLBACK TRAN SaveBill
		SET @errcode=-1
		CLOSE PosCursor
		DEALLOCATE PosCursor
		RETURN;
	END
			
	--按表头可以合并成好多条  @billcount 永远为1 这里改成了单张生成 不合并生成
	SELECT @billPage=CEILING(@billcount/@Size)  
	SET @j=0
	--已经合并的明细条数
	DECLARE @arCount INT=0	
	WHILE @j<@billPage --AND @i<@detalPage
	BEGIN
		SELECT @detailcount=COUNT(1) FROM #PosSaleBill WHERE billId>@j*@Size AND billId<=(@j+1)*@Size
		SELECT @detalPage=CEILING(@detailcount/@DetialSize) --表头合并以后表体按500行明细需要拆分的单据数量
		SET @i= 0
		SET @aftotal=0
		SET @accountCount=0
		WHILE @i<@detalPage
		BEGIN
			TRUNCATE TABLE #tempbillid	
			
			SELECT @taxtotal=CAST(SUM(a.Total) AS  NUMERIC(24, 10) ),@qty=SUM(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))
			FROM #PosSaleBill a  
			INNER JOIN ptype p ON a.PID=p.Pid
			INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
			WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
				AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(a.iscombination,0)=0
			
			SELECT @premoney = CAST(SUM(CASE  WHEN @billtype IN(11,12,305) THEN b.premoney ELSE -b.premoney END) AS  NUMERIC(24, 10) ),
					       @totalinmoney= CAST(SUM(CASE  WHEN @billtype IN(11,12,305) THEN b.Totalinmoney ELSE -b.Totalinmoney END) AS  NUMERIC(24, 10) ),
					       @SaveInCzMoney = dbo.F_RoundTotal(CAST(SUM(CASE @billtype WHEN 305 THEN b.SaveInCzMoney ELSE -b.SaveInCzMoney END) AS  NUMERIC(24, 10)))
					FROM PosSaleBillIndex b
					WHERE BillnumberID  IN (
					SELECT a.BillnumberID
					FROM #PosSaleBill a  
					INNER JOIN ptype p ON a.PID=p.Pid
					INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
					WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
						AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(a.iscombination,0)=0
					)
				
			SELECT @accountCount=COUNT(1),@billatypeid=MAX(ATypeID)
			FROM
			 (
				SELECT DISTINCT(ATypeID)
				FROM dbo.PosMulAccount p INNER join  #PosSaleBill a  ON p.BillNumberId=a.billnumberid
				WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
					AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size
			)b
			--PRINT @BilLType			
			SET @BillFlag=CASE  WHEN @billtype =305 THEN 'LS' WHEN @BilLType=11 THEN 'XK' WHEN @BilLType=12 THEN 'ZXK'  WHEN @BilLType=45 THEN 'XT'  WHEN @BilLType=46 THEN 'ZXT'  ELSE 'RB' END 	
			
			DECLARE @startdate VARCHAR(50)
			SELECT @startdate= CONVERT(VARCHAR(10),startdate,120) FROM dbo.MonthProc WHERE MonthNo='本期' AND stypeid=@stypeid
			IF @billdate<@startdate
				SET @billdate=@startdate
			SET @newBillCode=''
			--单据编号
			EXEC Gp_GetBillCode @billtype, @MONTH,@DAY,@BillFlag,@BillDate,@stypeid,@newBillCode OUTPUT,@dfullname,@cefullname
			--PRINT @newBillCode
			--保存种子数
			IF NOT EXISTS(SELECT ConfigNo  FROM Userconfig  WHERE ConfigName='BillcodeCreateTime'AND Value=2)
			BEGIN
				EXEC GP_AutoCombneRetail_SaveBillCode_Seed @billdate,@billtype,@newBillCode,@etypeid,@ktypeid,@dtypeid,@stypeid,@cefullname
			END

			INSERT INTO BillIndex 
			(
				CheckTime,BillTime,AlertDay,BillDate,BillCode,BillType,
				totalmoney,NTotalMoney,totalinmoney,NTotalInMoney,totalqty,packway,
				btypeid,etypeid,ktypeid,ifcheck,NewPosBill,checke,
				tax,period,RedWord,draft,Comment,VipCardID,tel,atypeid,IfMulAccount,
				IfAudit,preferencemoney,npreferencemoney,DTypeId,Explain,Stypeid,CID,Rate,ATypeID1,
				DealBTypeID,PromoRuleId,IscombinationStyle,PromonIds,posid,ktypeid2,KTypeID3
			)
			SELECT  GETDATE(),CONVERT(VARCHAR(20), GETDATE(), 24),9999,CONVERT(VARCHAR(10),@BillDate,120),@newBillCode,@billtype,
					CAST(@taxtotal AS NUMERIC(24,10)),CAST(@taxtotal AS NUMERIC(24,10)),CAST(@totalinmoney-@premoney AS NUMERIC(24,10)),CAST(@totalinmoney-@premoney AS NUMERIC(24,10)),CAST(@qty AS NUMERIC(24,10)),CASE WHEN @billtype=305 THEN CAST(dbo.F_RoundTotal(@totalinmoney-@premoney) AS VARCHAR) ELSE '' END,
					@btypeid,@ETypeId,@ktypeid,'f',1,@ETypeId,
					0,1,0,1,'该单是由POS小票手工生成',@vipcardid,CASE WHEN @billtype IN (11,12,45,46) THEN '' ELSE '0' END,CASE WHEN @accountCount<=1 THEN ISNULL(@billatypeid,'') ELSE -99999 END,CASE WHEN @accountCount<=1 THEN 0 ELSE 1 END,
					'3',CAST(@premoney AS NUMERIC(24,10)),CAST(@premoney AS NUMERIC(24,10)),@DTypeId,'',@stypeid,1,1,
					ISNULL(@atypeid,''),@DealBTypeID,@promoruleid,@hascombination,@PromoIDs,@posID,'',''

			SELECT @newbillnumberid=SCOPE_IDENTITY();
			INSERT INTO #daftBillNumerid VALUES  ( @newbillnumberid)
			
			UPDATE dbo.BillIndex SET totalmoney=dbo.F_RoundTotal(totalmoney),
							 NTotalMoney=dbo.F_RoundTotal(NTotalMoney),
							 totalinmoney=dbo.F_RoundTotal(totalinmoney),
							 NTotalInMoney=dbo.F_RoundTotal(NTotalInMoney),
							 preferencemoney=dbo.F_RoundTotal(preferencemoney),
							 NPreferenceMoney=dbo.F_RoundTotal(NPreferenceMoney),
							 totalqty=dbo.F_RoundQty(totalqty)
			WHERE BillNumberId=@newbillnumberid

			IF @billtype=305
			BEGIN
				IF @CouponCodes<>''  --983零售单，新增券信息到Coupon_BillUsed表中,并更改券信息Coupon_CodeInfo状态
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= @billtype 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										CouponId
										
										
								)
							SELECT  @newbillnumberid,
									@billtype,
									@posID,
									a.a,
									C.CouponId
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode =A.a
							WHERE ISNULL(A,'')<>''
							
							--UPDATE dbo.Coupon_CodeInfo SET [State]=3
							--FROM Coupon_CodeInfo cci 
							--INNER JOIN 
							--(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode  
						END
				
				INSERT INTO [dbo].[RetailBill] 
				( 
					[BillNumberId],[PtypeId],[Qty],[SalePrice],[discount],[DiscountPrice],[total],[TaxPrice],[TaxTotal],
					[comment],isUnit2,Serial,[GoodsNumber],[ProduceDate],[ValidDate],[GoodsBTypeID],
					Tax,SaleTotal,STypeID,
					--9.0新字段
					TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,
					CargoId,UnitId,NUnitId,NQty,UnitRate,NUnitMsg,
					MUnitId,MQty,MUnitRate,MUnitMsg,
					MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
					ItemId,IsCombined,PosID,IsGift,PromoType,ETypeID,GoodsCostPrice,GoodsCostTotal,
					iscombination,combinationptypeid,pindexid,CouponCode,KTypeID,PriceSource,PromonIDs
				) 
				OUTPUT INSERTED.ID INTO #tempbillid	
				SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
				CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
				CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ),
				a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
						a.comment,isUnit2=0,a.Serial,a.GoodsNumber,a.ProduceDate,a.ValidDate,GoodsBTypeID='',
						0,a.RetailTotal,@stypeid,
						0,CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0,
						@CargoID,p.baseUnitId,p.AssistantUnitId,0,0,NULL,
						a.UnitID,a.Qty,u.Rate,NULL,
						a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,a.ItemID,a.IsCombined,a.posid,a.IsGift,a.PromoType,
						ISNULL(salee.typeid,'') AS etypeid,a.GoodsCostPrice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)),
						a.iscombination,a.combinationptypeid,a.pindexid,a.couponcode,@ktypeid,a.pricesource,a.PromoIDs
				FROM #PosSaleBill a  
				INNER JOIN ptype p ON a.PID=p.Pid
				LEFT JOIN  dbo.employee salee ON a.saleeid=salee.Eid
				INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
				WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
					AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(iscombination,0)=0
				ORDER BY a.id
				
			INSERT INTO [dbo].[RetailCombinationBill] 
					( 
						[BillNumberId],[PtypeId],[Qty],[SalePrice],[discount],[DiscountPrice],[total],[TaxPrice],[TaxTotal],
						[comment],isUnit2,
						Tax,SaleTotal,STypeID,
						--9.0新字段
						TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,
						CargoId,UnitId,NUnitId,NQty,UnitRate,NUnitMsg,
						MUnitId,MQty,MUnitRate,MUnitMsg,
						MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
						ItemId,IsCombined,PosID,IsGift,PromoType,ETypeID,pindexid,CouponCode,PriceSource,PromonIds
					) 
					SELECT @newbillnumberid,p.typeId,
					CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
					CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
					a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
					a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
							a.comment,isUnit2=0,
							0,a.RetailTotal,@stypeid,
							0,CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
							CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
							CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0,
							@CargoID,p.baseUnitId,p.AssistantUnitId,0,0,NULL,
							a.UnitID,a.Qty,u.Rate,NULL,
							a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,a.ItemID,a.IsCombined,a.posid,a.IsGift,a.PromoType,ISNULL(salee.typeId,'') AS etypeid,
							a.pindexid,a.couponcode,a.pricesource,a.PromoIDs
					FROM #PosSaleBill a  
					INNER JOIN ptype p ON a.PID=p.Pid
					LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
					INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
					WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
						AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(iscombination,0)=1
					ORDER BY a.id
					
				UPDATE dbo.retailBill SET ShowOrder=ID,
													Qty=dbo.F_RoundQty(Qty),
													SalePrice=dbo.F_RoundPrice(SalePrice),
													discount=dbo.F_RoundDiscount(discount),
													DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
													costprice=dbo.F_RoundPrice(costprice),
													total=dbo.F_RoundTotal(total),
													TaxPrice=dbo.F_RoundPrice(TaxPrice),
													TaxTotal=dbo.F_RoundTotal(TaxTotal),
													InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
													BackQTY=dbo.F_RoundQty(BackQTY),
													SaleTotal=dbo.F_RoundTotal(SaleTotal),
													Tax=dbo.F_RoundTax(Tax),
													TaxMoney=dbo.F_RoundTotal(TaxMoney),
													NSalePrice=dbo.F_RoundPrice(NSalePrice),
													NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
													NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
													NTotal=dbo.F_RoundTotal(NTotal),
													NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
													NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
													NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
													NQty=dbo.F_RoundQty(NQty),
													MQty=dbo.F_RoundQty(MQty),
													MSalePrice=dbo.F_RoundPrice(MSalePrice),
													MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
													MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
													CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
													CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
													CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
													InvoiceQty=dbo.F_RoundQty(InvoiceQty),
													InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
													NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney)
						 WHERE BillNumberId=@newbillnumberid
						 
				 UPDATE dbo.retailCombinationBill SET 
											Qty=dbo.F_RoundQty(Qty),
											SalePrice=dbo.F_RoundPrice(SalePrice),
											discount=dbo.F_RoundDiscount(discount),
											DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
											total=dbo.F_RoundTotal(total),
											TaxPrice=dbo.F_RoundPrice(TaxPrice),
											TaxTotal=dbo.F_RoundTotal(TaxTotal),
											BackQTY=dbo.F_RoundQty(BackQTY),
											SaleTotal=dbo.F_RoundTotal(SaleTotal),
											Tax=dbo.F_RoundTax(Tax),
											TaxMoney=dbo.F_RoundTotal(TaxMoney),
											NSalePrice=dbo.F_RoundPrice(NSalePrice),
											NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
											NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
											NTotal=dbo.F_RoundTotal(NTotal),
											NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
											NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
											NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
											NQty=dbo.F_RoundQty(NQty),
											MQty=dbo.F_RoundQty(MQty),
											MSalePrice=dbo.F_RoundPrice(MSalePrice),
											MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
											MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
											CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
											CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
											CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
											InvoiceQty=dbo.F_RoundQty(InvoiceQty),
											InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
											NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney)
				 WHERE BillNumberId=@newbillnumberid
			END
			ELSE IF @billType=11
			BEGIN
				IF @CouponCodes<>''
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= 215 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										CouponId
								)
							SELECT  @newbillnumberid,
									11,
									@posID,
									a.a,
									C.CouponId
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
							WHERE ISNULL(A,'')<>''
							
							--UPDATE dbo.Coupon_CodeInfo SET [State]=3
							--FROM Coupon_CodeInfo cci 
							--INNER JOIN 
							--(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode
						END   
				INSERT INTO dbo.SaleBill											
				        ( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
				          goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,OrderID ,TeamNo ,TeamNO1 ,
				          IsUnit2 , Serial ,InputCostPrice ,GoodsOrder ,BackQty ,GoodsNumber ,ProduceDate ,
				          ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
				          Tax , KTypeID ,Stypeid ,ShareFee ,TaxMoney ,NSalePrice ,NSaleTotal ,
				          NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
				          NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
				          CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,entryCode ,InvoiceQty ,InvoiceMoney ,
				          NInvoiceMoney ,IsGift ,BeforePromoID ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder ,PriceSource ,
				          CompleteTotal ,NCompleteTotal ,OMBillID ,LendBillNumberID ,LendBillID,EtypeID,CouponCode,PromonIDs
				        )			
				OUTPUT INSERTED.ID INTO #tempbillid	
				SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
				CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
				0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
				CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
				a.total,a.comment,-1 AS orderid,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,a.Serial,0 AS inputcostprice,0 AS GoodsOrder,
				NULL AS backqty,a.GoodsNumber,a.ProduceDate,a.ValidDate,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
				0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
				0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,NULL AS ShareFee,0 AS taxmoney,CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
				CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
				p.baseUnitId,p.AssistantUnitId,0,0,NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
				@CargoID AS CargoID,a.ItemID,a.IsCombined,'' AS entryCode,NULL,NULL,NULL AS NInvoiceMoney,a.IsGift,0,NULL,0 AS PriceStyle,
				a.PromoType,0 AS ShowOrder,'' AS PriceSource,NULL AS CompleteTotal, NULL AS NCompleteTotal,0 AS OMBillID,NULL,NULL				
				,salee.typeId,a.couponcode,a.PromoIDs
				FROM #PosSaleBill a  
				INNER JOIN ptype p ON a.PID=p.Pid
				LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
				INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID	
				WHERE ISNULL(a.iscombination,0)=0 			
				ORDER BY a.id
					UPDATE dbo.SaleBill SET ShowOrder=ID,
											Qty=dbo.F_RoundQty(Qty),
											SalePrice=dbo.F_RoundPrice(SalePrice),
											discount=dbo.F_RoundDiscount(discount),
											DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
											costprice=dbo.F_RoundPrice(costprice),
											total=dbo.F_RoundTotal(total),
											TaxPrice=dbo.F_RoundPrice(TaxPrice),
											TaxTotal=dbo.F_RoundTotal(TaxTotal),
											InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
											BackQty=dbo.F_RoundQty(BackQty),
											CompleteQTY=dbo.F_RoundQty(CompleteQTY),
											SaleTotal=dbo.F_RoundTotal(SaleTotal),
											Tax=dbo.F_RoundTax(Tax),
											TaxMoney=dbo.F_RoundTotal(TaxMoney),
											NSalePrice=dbo.F_RoundPrice(NSalePrice),
											NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
											NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
											NTotal=dbo.F_RoundTotal(Total),
											NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
											NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
											NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
											NQty=dbo.F_RoundQty(NQty),
											MQty=dbo.F_RoundQty(MQty),
											MSalePrice=dbo.F_RoundPrice(MSalePrice),
											MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
											MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
											CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
											CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
											CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
											InvoiceQty=dbo.F_RoundQty(InvoiceQty),
											InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
											NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
											CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
											NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
				WHERE BillNumberId=@newbillnumberid
			END
			ELSE  IF @billType=12
			BEGIN
			--PRINT '插入组合品销售出库单'
			IF @CouponCodes<>''
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= 12 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										COUPONID
								)
							SELECT  @newbillnumberid,
									12,
									@posID,
									a.a,
									C.COUPONID
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
							WHERE ISNULL(A,'')<>''
							
							--UPDATE dbo.Coupon_CodeInfo SET [State]=3
							--FROM Coupon_CodeInfo cci 
							--INNER JOIN 
							--(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode
						END
					INSERT INTO dbo.PT_Combin_SaleBill											
								( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
								  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,OrderID ,TeamNo ,TeamNO1 ,
								  IsUnit2 ,InputCostPrice ,GoodsOrder ,BackQty ,
								   GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
								  Tax , KTypeID ,Stypeid ,ShareFee ,TaxMoney ,NSalePrice ,NSaleTotal ,
								  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
								  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
								  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,entryCode ,InvoiceQty ,InvoiceMoney ,
								  NInvoiceMoney ,IsGift ,BeforePromoID ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
								  CompleteTotal ,NCompleteTotal ,LendBillNumberID ,LendBillID,CouponCode,PriceSource,PromonIds
								  
								)			
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
						0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
						a.total,a.comment,-1 AS orderid,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,0 AS inputcostprice,0 AS GoodsOrder,
						NULL AS backqty,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
						0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
						0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS ShareFee,0 AS taxmoney,
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
						p.baseUnitId,p.AssistantUnitId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
						u1.Rate,--浮动单位换算率
						NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						@CargoID AS CargoID,a.ItemID,a.IsCombined,'' AS entryCode,NULL,NULL,NULL AS NInvoiceMoney,a.IsGift,0,0,0 AS PriceStyle,
						a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,0,0,a.couponcode,a.pricesource,a.PromoIds		
						
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
						WHERE ISNULL(a.iscombination,0)=1 
						ORDER BY a.id
						
						UPDATE dbo.PT_Combin_SaleBill SET ShowOrder=ID,
												Qty=dbo.F_RoundQty(Qty),
												SalePrice=dbo.F_RoundPrice(SalePrice),
												discount=dbo.F_RoundDiscount(discount),
												DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
												costprice=dbo.F_RoundPrice(costprice),
												total=dbo.F_RoundTotal(total),
												TaxPrice=dbo.F_RoundPrice(TaxPrice),
												TaxTotal=dbo.F_RoundTotal(TaxTotal),
												InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
												BackQty=dbo.F_RoundQty(BackQty),
												CompleteQTY=dbo.F_RoundQty(CompleteQTY),
												SaleTotal=dbo.F_RoundTotal(SaleTotal),
												Tax=dbo.F_RoundTax(Tax),
												TaxMoney=dbo.F_RoundTotal(TaxMoney),
												NSalePrice=dbo.F_RoundPrice(NSalePrice),
												NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
												NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
												NTotal=dbo.F_RoundTotal(Total),
												NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
												NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
												NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
												NQty=dbo.F_RoundQty(NQty),
												MQty=dbo.F_RoundQty(MQty),
												MSalePrice=dbo.F_RoundPrice(MSalePrice),
												MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
												MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
												CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
												CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
												CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
												InvoiceQty=dbo.F_RoundQty(InvoiceQty),
												InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
												NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
												CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
												NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					
					
					--组合品明细
						INSERT INTO dbo.PT_Combin_SaleBillDetail											
								( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
								  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,OrderID ,TeamNo ,TeamNO1 ,
								  IsUnit2 , Serial ,InputCostPrice ,GoodsOrder ,BackQty ,GoodsNumber ,ProduceDate ,
								  ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
								  Tax , KTypeID ,Stypeid ,ShareFee ,TaxMoney ,NSalePrice ,NSaleTotal ,
								  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
								  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
								  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,entryCode ,InvoiceQty ,InvoiceMoney ,
								  NInvoiceMoney ,IsGift ,BeforePromoID ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
								  CompleteTotal ,NCompleteTotal  ,LendBillNumberID ,LendBillID,combinationptypeid,PriceSource
								  
								)			
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
						0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
						a.total,a.comment,-1 AS orderid,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,a.Serial,0 AS inputcostprice,0 AS GoodsOrder,
						NULL AS backqty,a.GoodsNumber,a.ProduceDate,a.ValidDate,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
						0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
						0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS ShareFee,0 AS taxmoney,
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
						p.baseUnitId,p.AssistantUnitId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
						u1.Rate,--浮动单位换算率
						NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						@CargoID AS CargoID,a.ItemID,a.IsCombined,'' AS entryCode,NULL,NULL,NULL AS NInvoiceMoney,a.IsGift,0,0,0 AS PriceStyle,
						a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,0,0,a.combinationptypeid,a.pricesource				
						
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
						WHERE ISNULL(a.iscombination,0)=0 
						ORDER BY a.id
						
						UPDATE dbo.PT_Combin_SaleBillDetail SET ShowOrder=ID,
												Qty=dbo.F_RoundQty(Qty),
												SalePrice=dbo.F_RoundPrice(SalePrice),
												discount=dbo.F_RoundDiscount(discount),
												DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
												costprice=dbo.F_RoundPrice(costprice),
												total=dbo.F_RoundTotal(total),
												TaxPrice=dbo.F_RoundPrice(TaxPrice),
												TaxTotal=dbo.F_RoundTotal(TaxTotal),
												InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
												BackQty=dbo.F_RoundQty(BackQty),
												CompleteQTY=dbo.F_RoundQty(CompleteQTY),
												SaleTotal=dbo.F_RoundTotal(SaleTotal),
												Tax=dbo.F_RoundTax(Tax),
												TaxMoney=dbo.F_RoundTotal(TaxMoney),
												NSalePrice=dbo.F_RoundPrice(NSalePrice),
												NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
												NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
												NTotal=dbo.F_RoundTotal(Total),
												NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
												NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
												NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
												NQty=dbo.F_RoundQty(NQty),
												MQty=dbo.F_RoundQty(MQty),
												MSalePrice=dbo.F_RoundPrice(MSalePrice),
												MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
												MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
												CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
												CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
												CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
												InvoiceQty=dbo.F_RoundQty(InvoiceQty),
												InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
												NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
												CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
												NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					--组合品明细
			END
			ELSE  IF @billType=46
			BEGIN
				IF @CouponCodes<>''
				BEGIN
					INSERT INTO Coupon_BillUsed
						(		BillnumberId,
								BillType,
								PosID,
								CouponCode,
								COUPONID
						)
					SELECT  @newbillnumberid,
							46,
							@posID,
							a.a,
							C.COUPONID
					FROM dbo.f_split(@CouponCodes,'я') A
					INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
					WHERE ISNULL(A,'')<>''
				END
				
				INSERT INTO dbo.PT_Combin_SaleBackBill											
							( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
							  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo ,TeamNO1 ,
							  IsUnit2 ,InputCostPrice ,GoodsOrder ,
							   GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
							  Tax , KTypeID ,Stypeid ,TaxMoney ,NSalePrice ,NSaleTotal ,
							  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
							  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
							  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,
							  NInvoiceMoney ,IsGift ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
							  CompleteTotal ,NCompleteTotal ,CouponCode,PriceSource,ktypeid
							  
							)			
				OUTPUT INSERTED.ID INTO #tempbillid	
				SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
				CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
				CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
				0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
				CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
				a.total,a.comment,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,0 AS inputcostprice,0 AS GoodsOrder,
				'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
				0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
				0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS taxmoney,
				CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
				CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
				CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
				p.baseUnitId,p.AssistantUnitId,
				CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
				u1.Rate,--浮动单位换算率
				NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
				@CargoID AS CargoID,a.ItemID,a.IsCombined,NULL,NULL,NULL AS NInvoiceMoney,a.IsGift,0,0 AS PriceStyle,
				a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,a.couponcode,a.pricesource,a.ktypeid		
				
				FROM #PosSaleBill a  
				INNER JOIN ptype p ON a.PID=p.Pid
				LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
				INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
				LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
				WHERE ISNULL(a.iscombination,0)=1 
				ORDER BY a.id
					
					UPDATE dbo.PT_Combin_SaleBackBill SET ShowOrder=ID,
											Qty=dbo.F_RoundQty(Qty),
											SalePrice=dbo.F_RoundPrice(SalePrice),
											discount=dbo.F_RoundDiscount(discount),
											DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
											costprice=dbo.F_RoundPrice(costprice),
											total=dbo.F_RoundTotal(total),
											TaxPrice=dbo.F_RoundPrice(TaxPrice),
											TaxTotal=dbo.F_RoundTotal(TaxTotal),
											InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
											CompleteQTY=dbo.F_RoundQty(CompleteQTY),
											SaleTotal=dbo.F_RoundTotal(SaleTotal),
											Tax=dbo.F_RoundTax(Tax),
											TaxMoney=dbo.F_RoundTotal(TaxMoney),
											NSalePrice=dbo.F_RoundPrice(NSalePrice),
											NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
											NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
											NTotal=dbo.F_RoundTotal(Total),
											NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
											NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
											NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
											NQty=dbo.F_RoundQty(NQty),
											MQty=dbo.F_RoundQty(MQty),
											MSalePrice=dbo.F_RoundPrice(MSalePrice),
											MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
											MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
											CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
											CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
											CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
											InvoiceQty=dbo.F_RoundQty(InvoiceQty),
											InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
											NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
											CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
											NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					
					
					--组合品明细
						INSERT INTO dbo.PT_Combin_SaleBackBillDetail											
								( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
								  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo ,TeamNO1 ,
								  IsUnit2 , Serial ,InputCostPrice ,GoodsOrder ,GoodsNumber ,ProduceDate ,
								  ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
								  Tax , KTypeID ,Stypeid ,TaxMoney ,NSalePrice ,NSaleTotal ,
								  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
								  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
								  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,
								  NInvoiceMoney ,IsGift ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
								  CompleteTotal ,NCompleteTotal,combinationptypeid,PriceSource
								  
								)			
						OUTPUT INSERTED.ID INTO #tempbillid	
						SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
						0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
						a.total,a.comment,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,a.Serial,0 AS inputcostprice,0 AS GoodsOrder,
						a.GoodsNumber,a.ProduceDate,a.ValidDate,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
						0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
						0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS taxmoney,
						CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
						CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
						p.baseUnitId,p.AssistantUnitId,
						CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
						u1.Rate,--浮动单位换算率
						NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						@CargoID AS CargoID,a.ItemID,a.IsCombined,NULL,NULL,NULL AS NInvoiceMoney,a.IsGift,0,0 AS PriceStyle,
						a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,a.combinationptypeid,a.pricesource				
						
						FROM #PosSaleBill a  
						INNER JOIN ptype p ON a.PID=p.Pid
						LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
						INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
						LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
						WHERE ISNULL(a.iscombination,0)=0 
						ORDER BY a.id
						
						UPDATE dbo.PT_Combin_SaleBackBillDetail SET ShowOrder=ID,
												Qty=dbo.F_RoundQty(Qty),
												SalePrice=dbo.F_RoundPrice(SalePrice),
												discount=dbo.F_RoundDiscount(discount),
												DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
												costprice=dbo.F_RoundPrice(costprice),
												total=dbo.F_RoundTotal(total),
												TaxPrice=dbo.F_RoundPrice(TaxPrice),
												TaxTotal=dbo.F_RoundTotal(TaxTotal),
												InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
												CompleteQTY=dbo.F_RoundQty(CompleteQTY),
												SaleTotal=dbo.F_RoundTotal(SaleTotal),
												Tax=dbo.F_RoundTax(Tax),
												TaxMoney=dbo.F_RoundTotal(TaxMoney),
												NSalePrice=dbo.F_RoundPrice(NSalePrice),
												NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
												NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
												NTotal=dbo.F_RoundTotal(Total),
												NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
												NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
												NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
												NQty=dbo.F_RoundQty(NQty),
												MQty=dbo.F_RoundQty(MQty),
												MSalePrice=dbo.F_RoundPrice(MSalePrice),
												MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
												MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
												CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
												CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
												CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
												InvoiceQty=dbo.F_RoundQty(InvoiceQty),
												InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
												NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
												CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
												NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
					WHERE BillNumberId=@newbillnumberid
					--组合品明细
			END
			ELSE  IF @billType=45
			BEGIN
				IF @CouponCodes<>''
					BEGIN
						INSERT INTO Coupon_BillUsed
							(		BillnumberId,
									BillType,
									PosID,
									CouponCode,
									COUPONID
							)
						SELECT  @newbillnumberid,
								45,
								@posID,
								a.a,
								C.COUPONID
						FROM dbo.f_split(@CouponCodes,'я') A
						INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
						WHERE ISNULL(A,'')<>''
					END
					
					INSERT INTO dbo.SaleBackBill											
							( BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,jobnumber ,
							  goodsno ,total , OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo ,TeamNO1 ,
							  IsUnit2 , Serial ,InputCostPrice ,GoodsOrder ,GoodsNumber ,ProduceDate ,
							  ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,
							  Tax , KTypeID ,Stypeid ,TaxMoney ,NSalePrice ,NSaleTotal ,
							  NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID , NQty ,UnitRate ,
							  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
							  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,
							  NInvoiceMoney ,IsGift ,ReferPrice ,PriceStyle ,PromoType ,ShowOrder  ,
							  CompleteTotal ,NCompleteTotal,PriceSource,PromoIds
							  
							)			
					OUTPUT INSERTED.ID INTO #tempbillid	
					SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),
					CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,
					CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ))AS  NUMERIC(24, 10) ) AS discountprice,
					0 AS costprice,'' AS jobnumber,NULL AS goodsno,a.Total,NULL AS OutFactoryDate,
					CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) AS taxprice,
					a.total,a.comment,0 AS TeamNo,0 AS TeamNO1, isUnit2=0,a.Serial,0 AS inputcostprice,0 AS GoodsOrder,
					a.GoodsNumber,a.ProduceDate,a.ValidDate,'' as GoodsBTypeID,a.goodscostprice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)) AS goodscosttotal,
					0 AS HandZeroCost,NULL AS CompleteQTY,a.RetailTotal,
					0 AS tax,@ktypeid AS ktypeid,@stypeid AS stypeid,0 AS taxmoney,
					CAST(a.RetailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,
					CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ) NDiscountPrice,a.Total AS NTotal,
					CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0 AS NTaxMoney,
					p.baseUnitId,p.AssistantUnitId,
					CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u1.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),--浮动单位数量=基本单位数量*浮动单位换算率
					u1.Rate,--浮动单位换算率
					NULL,a.UnitID,a.Qty,u.Rate,NULL,a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
					@CargoID AS CargoID,a.ItemID,a.IsCombined,NULL,NULL,NULL AS NInvoiceMoney,a.IsGift,0,0 AS PriceStyle,
					a.PromoType,0 AS ShowOrder,NULL AS CompleteTotal, NULL AS NCompleteTotal,a.pricesource,a.PromoIDs				
					
					FROM #PosSaleBill a  
					INNER JOIN ptype p ON a.PID=p.Pid
					LEFT JOIN  dbo.employee salee ON salee.Eid=a.saleeid
					INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
					LEFT JOIN PType_Units_Ext u1 ON u1.PtypeID=p.typeId AND u1.RateType=1 
					WHERE ISNULL(a.iscombination,0)=0 
					ORDER BY a.id
					
					UPDATE dbo.saleBackBill SET ShowOrder=ID,
											Qty=dbo.F_RoundQty(Qty),
											SalePrice=dbo.F_RoundPrice(SalePrice),
											discount=dbo.F_RoundDiscount(discount),
											DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
											costprice=dbo.F_RoundPrice(costprice),
											total=dbo.F_RoundTotal(total),
											TaxPrice=dbo.F_RoundPrice(TaxPrice),
											TaxTotal=dbo.F_RoundTotal(TaxTotal),
											InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
											CompleteQTY=dbo.F_RoundQty(CompleteQTY),
											SaleTotal=dbo.F_RoundTotal(SaleTotal),
											Tax=dbo.F_RoundTax(Tax),
											TaxMoney=dbo.F_RoundTotal(TaxMoney),
											NSalePrice=dbo.F_RoundPrice(NSalePrice),
											NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
											NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
											NTotal=dbo.F_RoundTotal(Total),
											NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
											NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
											NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
											NQty=dbo.F_RoundQty(NQty),
											MQty=dbo.F_RoundQty(MQty),
											MSalePrice=dbo.F_RoundPrice(MSalePrice),
											MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
											MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
											CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
											CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
											CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
											InvoiceQty=dbo.F_RoundQty(InvoiceQty),
											InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
											NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
											CompleteTotal=dbo.F_RoundTotal(CompleteTotal),
											NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal)
				WHERE BillNumberId=@newbillnumberid
					--组合品明细
			END
			ELSE			
			BEGIN
			IF @CouponCodes<>''
						BEGIN
							--DELETE FROM Coupon_BillUsed WHERE BillnumberId=@billnumberid AND billtype= 215 
	
							INSERT INTO Coupon_BillUsed
								(		BillnumberId,
										BillType,
										PosID,
										CouponCode,
										CouponId
								)
							SELECT  @newbillnumberid,
									215,
									@posID,
									a.a,
									C.CouponId
							FROM dbo.f_split(@CouponCodes,'я') A
							INNER JOIN COUPON_CODEINFO C ON  C.CouponCode = A.a
							WHERE ISNULL(A,'')<>''
							
							--UPDATE dbo.Coupon_CodeInfo SET [State]=5
							--FROM Coupon_CodeInfo cci 
							--INNER JOIN 
							--(SELECT a.a AS couponcode FROM dbo.f_split(@CouponCodes,'я') A) B ON cci.CouponCode = B.couponcode
						END  
				INSERT INTO RetailBackBill
					  ( BillNumberId,PtypeId ,Qty,SalePrice,discount,DiscountPrice,total,TaxPrice,TaxTotal,
						comment,isUnit2,GoodsBTypeID,
						Tax,SaleTotal,Stypeid,
						TaxMoney,NSalePrice,NSaleTotal ,NDiscountPrice ,NTotal,NTaxPrice ,NTaxTotal,NTaxMoney ,
						CargoID,UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,
						MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
						CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
						ItemID,IsCombined,IsGift,
						InputCostPrice,HandZeroCost,PosId,PromoType,ETypeID,
						ValidDate,ProduceDate,GoodsNumber,Serial,
						GoodsCostPrice,GoodsCostTotal,CouponCode,KTypeID,PriceSource
						) OUTPUT INSERTED.ID INTO #tempbillid	
				SELECT @newbillnumberid,p.typeId,CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) ),CAST(a.retailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.DisCount,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),
				a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,
						a.comment,isUnit2=0,GoodsBTypeID='',
						0,a.RetailTotal,@stypeid,
						0,CAST(a.retailTotal/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.RetailTotal,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,CAST(a.Total/(CAST(CAST(a.qty AS NUMERIC(24,12))*CAST(u.Rate AS NUMERIC(24,12))AS  NUMERIC(24, 10) )) AS  NUMERIC(24, 10) ),a.Total,0,
						@CargoID,p.baseUnitId,p.AssistantUnitId,0,0,NULL,
						a.UnitID,a.Qty,u.Rate,NULL, 
						a.RetailPrice,a.Price,a.Price,a.RetailPrice,a.Price,a.Price,
						a.ItemID,a.IsCombined,a.IsGift,0,0,a.posid,a.PromoType,ISNULL(salee.typeid,'') AS etypeid,
						a.validdate,a.producedate,a.goodsnumber,a.serial,
						GoodsCostPrice,CAST(a.goodscostprice*Qty AS NUMERIC(24,10)),a.couponcode,@ktypeid,a.pricesource
				FROM #PosSaleBill a  
				INNER JOIN ptype p ON a.PID=p.Pid
				LEFT JOIN  dbo.employee salee ON a.saleeid=salee.Eid
				INNER JOIN PType_Units_Ext u ON u.UnitsId=a.UnitId AND p.typeId = u.PtypeID
				WHERE  a.ID>@arCount AND a.ID<=(@arCount+@DetialSize) 
					AND a.billId>@j*@Size AND a.billId<=(@j+1)*@Size AND ISNULL(a.iscombination,0)=0 
				ORDER BY a.id
			
				UPDATE dbo.RetailBackBill SET ShowOrder=ID,
						Qty=dbo.F_RoundQty(Qty),
						SalePrice=dbo.F_RoundPrice(SalePrice),
						discount=dbo.F_RoundDiscount(discount),
						DiscountPrice=dbo.F_RoundPrice(DiscountPrice),
						costprice=dbo.F_RoundPrice(costprice),
						total=dbo.F_RoundTotal(total),
						TaxPrice=dbo.F_RoundPrice(TaxPrice),
						TaxTotal=dbo.F_RoundTotal(TaxTotal),
						InputCostPrice=dbo.F_RoundPrice(InputCostPrice),
						SaleTotal=dbo.F_RoundTotal(SaleTotal),
						Tax=dbo.F_RoundTax(Tax),
						TaxMoney=dbo.F_RoundTotal(TaxMoney),
						NSalePrice=dbo.F_RoundPrice(NSalePrice),
						NSaleTotal=dbo.F_RoundTotal(NSaleTotal),
						NDiscountPrice=dbo.F_RoundPrice(NDiscountPrice),
						NTotal=dbo.F_RoundTotal(NTotal),
						NTaxPrice=dbo.F_RoundPrice(NTaxPrice),
						NTaxTotal=dbo.F_RoundTotal(NTaxTotal),
						NTaxMoney=dbo.F_RoundTotal(NTaxMoney),
						NQty=dbo.F_RoundQty(NQty),
						MQty=dbo.F_RoundQty(MQty),
						MSalePrice=dbo.F_RoundPrice(MSalePrice),
						MDiscountPrice=dbo.F_RoundPrice(MDiscountPrice),
						MTaxPrice=dbo.F_RoundPrice(MTaxPrice),
						CurMSalePrice=dbo.F_RoundPrice(CurMSalePrice),
						CurMDiscountPrice=dbo.F_RoundPrice(CurMDiscountPrice),
						CurMTaxPrice=dbo.F_RoundPrice(CurMTaxPrice),
						InvoiceQty=dbo.F_RoundQty(InvoiceQty),
						InvoiceMoney=dbo.F_RoundTotal(InvoiceMoney),
						NInvoiceMoney=dbo.F_RoundTotal(NInvoiceMoney),
						CompleteQty=dbo.F_RoundQty(CompleteQty)
				WHERE BillNumberId=@newbillnumberid
			END
			SELECT @rowcount=@@ROWCOUNT	
							
			INSERT INTO PosRetailRecord
			( 
				PosSaleBillId,PosBillNumberId,RetailBillId,RetailBillNumberId,AuditingFlag,RecordTime
			)
			SELECT c.detailid,c.billnumberid,t.detailid,@newbillnumberid,0 ,GETDATE()
			FROM
			(
				SELECT   row_number() over (order by Id) AS orderid,
				billnumberid,detailid 
				FROM #PosSaleBill 
				WHERE  ID>@arCount AND ID<=(@arCount+@DetialSize) 
						AND billId>@j*@size AND billId<= (@j+1)*@Size
						AND ISNULL(Iscombination,0)=0
			)c
			INNER JOIN #tempbillid t ON t.ID=c.orderid
			
			SET @arCount += @rowcount
			
					--拆分实收金额
		   SELECT @tmpdetailmaxid=MAX(detailid) FROM #tempbillid
		   SELECT @tmpdetailminid=MIN(detailid) FROM #tempbillid
		   
		   SELECT @tmpmaxbillnumberid=PosBillNumberId FROM PosRetailRecord WHERE RetailBillId= @tmpdetailmaxid
		   SELECT @tmpminbillnumberid=PosBillNumberId FROM PosRetailRecord WHERE RetailBillId= @tmpdetailminid
		   
			
		 --一张pos单拆分多张零售单的情况（收款情况分摊）
		 --拆分后的第1到N-1张零售单
		 IF @detalPage>1
		 BEGIN			
			SELECT @Maxftotal=SUM(total) FROM #PosSaleBill 
			WHERE  ID>@arCount-@rowcount AND ID<=(@arCount+@DetialSize-@rowcount) 
			AND billId>@j*@Size AND billId<=(@j+1)*@Size
			AND billnumberid=@tmpmaxbillnumberid
			
			INSERT INTO #BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotal,posBillNumberId,yhType,CouponCode,VipTotal)
			SELECT  @newbillnumberid,ATypeID,SUM(Round((@maxftotal/b.Totalinmoney),4)*a.atotal),a.Comment,a.VipCardID,SUM(Round((@maxftotal/b.Totalinmoney),4)*a.atotal),a.BillNumberId,a.yhType,a.CouponCode,a.VipTotal
			FROM PosMulAccount a
			INNER JOIN PosSaleBillIndex b ON a.BillNumberId=b.BillnumberID
			WHERE b.BillnumberID=@tmpmaxbillnumberid AND a.ATypeID<>(SELECT TOP 1 atypeid FROM dbo.PosMulAccount WHERE BillnumberID=@tmpmaxbillnumberid ORDER BY ATypeID DESC)
			GROUP BY ATypeID,a.VipCardID,a.BillNumberId,a.Comment,a.yhType,a.CouponCode,a.VipTotal
			
			SELECT @minFtotal=ISNULL(SUM(Total),0) FROM #BillMulAccount WHERE posBillNumberId=@tmpmaxbillnumberid
			
			INSERT INTO #BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotal,posBillNumberId,yhType,CouponCode,VipTotal)
			SELECT  @newbillnumberid,ATypeID,@Maxftotal-@minFtotal,Comment,VipCardID,@Maxftotal-@minFtotal,BillNumberId,yhType,CouponCode,VipTotal
			FROM PosMulAccount 
			WHERE BillnumberID=@tmpmaxbillnumberid AND ATypeID=(SELECT TOP 1 atypeid FROM dbo.PosMulAccount WHERE BillnumberID=@tmpmaxbillnumberid ORDER BY ATypeID DESC)	
				
			
			INSERT INTO BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotalMoney,BillType,yhType,CouponCode,VipTotal)
			SELECT BillNumberId ,ATypeID ,SUM(Total) ,Comment ,VipCardID ,SUM(ntotal),billtype,yhType,CouponCode,VipTotal
			FROM
			(
				SELECT  @newbillnumberid AS BillNumberId,ATypeID,a.atotal AS total,a.Comment,VipCardID,a.atotal AS ntotal,(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,a.yhType,a.CouponCode,a.VipTotal
				FROM PosMulAccount a
				INNER JOIN (SELECT DISTINCT PosBillNumberId FROM PosRetailRecord WHERE RetailBillNumberId=@newbillnumberid ) b 
				ON a.BillNumberId=b.PosBillNumberId
				WHERE a.BillNumberId <>@tmpmaxbillnumberid AND a.BillNumberId<>@tmpminbillnumberid
				UNION ALL
				SELECT  @newbillnumberid BillNumberId,ATypeID,total,Comment,VipCardID,ntotal,(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,yhType,CouponCode,VipTotal 
				FROM #BillMulAccount a
				WHERE a.BillnumberID=@newbillnumberid
				UNION ALL
				SELECT @newbillnumberid AS BillNumberId,b.atypeid,b.atotal-ISNULL(a.total,0) AS total,b.Comment,b.VipCardID,b.atotal-ISNULL(a.total,0) AS ntotal,(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,yhType,CouponCode,VipTotal
					FROM  PosMulAccount b
					LEFT JOIN
					(
						SELECT  posBillNumberId,ATypeID,SUM(Total) AS total,Comment,VipCardID,SUM(ntotal) AS ntotal,(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,yhType,CouponCode,VipTotal
						FROM #BillMulAccount a
						WHERE a.posBillNumberId=@tmpminbillnumberid
						GROUP BY posBillNumberId,ATypeID,Comment,VipCardID,VipTotal
					) a ON a.atypeid=b.ATypeID AND a.posBillNumberId=b.BillNumberId
					WHERE b.BillNumberId=@tmpminbillnumberid
			) a
			WHERE a.ATypeID<>-1
			GROUP BY BillNumberId,ATypeID,VipCardID,a.Comment,a.yhType,a.CouponCode,a.VipTotal
		 END
		  --不用拆分的情况
		  ELSE
		  BEGIN
			INSERT INTO BillMulAccount( BillNumberId ,ATypeID ,Total ,Comment ,VipCardID ,NTotalMoney,billtype,yhType,CouponCode,VipTotal)
			SELECT  
			@newbillnumberid,
			ATypeID,
			CASE WHEN a.atypeid=1 THEN 
			SUM(a.atotal) - ISNULL(@SaveInCzMoney,0)
			ELSE SUM(a.atotal) END,
			a.Comment,
			VipCardID,
			CASE WHEN a.atypeid=1 THEN 
			SUM(a.atotal)- ISNULL(@SaveInCzMoney,0)  
			ELSE SUM(a.atotal) END,
			(select billtype from billindex where billnumberid=@newbillnumberid) as billtype,
			a.yhType,
			a.CouponCode,
			a.VipTotal
			FROM PosMulAccount a
			INNER JOIN (SELECT DISTINCT PosBillNumberId FROM PosRetailRecord WHERE RetailBillNumberId=@newbillnumberid ) b 
			ON a.BillNumberId=b.PosBillNumberId
			GROUP BY ATypeID,VipCardID,Comment,yhType,CouponCode,VipTotal
			
			--销售出库单和组合品销售出库单
			DECLARE @btypetotal NUMERIC(24,10)
			SET @btypetotal=(
			SELECT 
			SUM(atotal) AS total FROM PosMulAccount 
			WHERE BillNumberId=@posbillnumberid AND ATypeID=-1)
			
			UPDATE dbo.BillIndex SET totalinmoney=totalinmoney-ISNULL(@btypetotal,0),NTotalInMoney=NTotalInMoney-ISNULL(@btypetotal,0)
			WHERE BillNumberId=@newbillnumberid	 AND BillType IN (11,12,45,46)
		  END	
			-------------------具体合并----------------
			------------------983更改启用品牌则写入品牌信息start---
					DECLARE @billtypeflag INT,@brandTypeId VARCHAR(200)
					IF EXISTS(SELECT * FROM BillMulAccount WHERE BillNumberId = @newbillnumberid) 
					AND EXISTS ( SELECT  * FROM  dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue = 1 )
					BEGIN
						SELECT @billtypeflag=billtype FROM dbo.BillIndex where billnumberid=@newbillnumberid
						IF @billtypeflag=305
							BEGIN
							INSERT INTO dbo.BillMulBrand
								( STypeID ,
								  BTypeID ,
								  BrandarTypeID ,
								  BillNumberId ,
								  BillType ,
								  Cid ,
								  Rate ,
								  TaxTotal ,
								  NTaxTotal ,
								  PreferenceMoney ,
								  NPreferenceMoney ,
								  TotalInMoney ,
								  NTotalInMoney ,
								  YSTotalInMoney ,
								  NYSTotalInMoney ,
								  TheOrderARTotal ,
								  NTheOrderARTotal ,
								  isIni
								)
						SELECT BI.Stypeid,BI.btypeid,P.BrandarTypeID,
						BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.TaxTotal),SUM(S.NTaxTotal),0,0,SUM(S.TaxTotal),SUM(S.NTaxTotal),
						0,0,0,0,0
						FROM dbo.retailBill S INNER JOIN PTYPE P ON S.PtypeId = P.typeId
						INNER JOIN dbo.brandar_Commodity B ON B.TypeId = P.BrandarTypeID
						INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
						WHERE BI.BillNumberId = @newbillnumberid AND S.TaxTotal <> 0
						GROUP BY P.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate  
			
						SELECT TOP 1 @brandTypeId =  BrandarTypeID FROM dbo.BillMulBrand WHERE BillNumberId = @newbillnumberid ORDER BY NTaxTotal DESC
			
						UPDATE dbo.BillMulBrand SET PreferenceMoney = BI.preferencemoney,NPreferenceMoney =BI.NPreferenceMoney,
						TotalInMoney = BB.TotalInMoney-BI.preferencemoney,NTotalInMoney = BB.NTotalInMoney - BI.NPreferenceMoney
						FROM dbo.BillMulBrand BB
						INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = BB.BillNumberId WHERE BB.BillNumberId = @newbillnumberid AND BB.BrandarTypeID=@brandTypeId
							END
						ELSE IF @billtypeflag=215
							BEGIN
							INSERT INTO dbo.BillMulBrand
								( STypeID ,
								  BTypeID ,
								  BrandarTypeID ,
								  BillNumberId ,
								  BillType ,
								  Cid ,
								  Rate ,
								  TaxTotal ,
								  NTaxTotal ,
								  PreferenceMoney ,
								  NPreferenceMoney ,
								  TotalInMoney ,
								  NTotalInMoney ,
								  YSTotalInMoney ,
								  NYSTotalInMoney ,
								  TheOrderARTotal ,
								  NTheOrderARTotal ,
								  isIni
								)
						SELECT BI.Stypeid,BI.btypeid,P.BrandarTypeID,
						BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.TaxTotal),SUM(S.NTaxTotal),0,0,SUM(S.TaxTotal),SUM(S.NTaxTotal),
						0,0,0,0,0
						FROM dbo.RetailBackBill S INNER JOIN PTYPE P ON S.PtypeId = P.typeId
						INNER JOIN dbo.brandar_Commodity B ON B.TypeId = P.BrandarTypeID
						INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
						WHERE BI.BillNumberId = @newbillnumberid AND S.TaxTotal <> 0
						GROUP BY P.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate  
			
						SELECT TOP 1 @brandTypeId =  BrandarTypeID FROM dbo.BillMulBrand WHERE BillNumberId = @newbillnumberid ORDER BY NTaxTotal DESC
			
						UPDATE dbo.BillMulBrand SET PreferenceMoney = BI.preferencemoney,NPreferenceMoney =BI.NPreferenceMoney,
						TotalInMoney = BB.TotalInMoney-BI.preferencemoney,NTotalInMoney = BB.NTotalInMoney - BI.NPreferenceMoney
						FROM dbo.BillMulBrand BB
						INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = BB.BillNumberId WHERE BB.BillNumberId = @newbillnumberid AND BB.BrandarTypeID=@brandTypeId;
						END
					END
					
					------------------983更改启用品牌则写入品牌信息end---
			
			SET @i=@i+1
		END
		SET @j = @j+1	
	END	
	
COMMIT TRAN SaveBill

	FETCH NEXT FROM PosCursor
	INTO @posID,@PosBillnumberid,@Bid,@Kid,@Eid,@BillDate,@VipCardID,@PromoRuleId,@billtype,@billcount,@CouponCodes,@PromoIDs
END

DROP TABLE #PosSaleBill,#tempbillid,#BillMulAccount
SELECT f.* INTO #DeletedBillID 
FROM dbo.f_split(@billnumberidlist,',') f 

DELETE FROM dbo.PosSaleBill WHERE BillnumberID IN (SELECT * FROM #DeletedBillID)
DELETE FROM dbo.PosMulAccount WHERE BillnumberID IN (SELECT * FROM #DeletedBillID)
DELETE FROM dbo.PosSaleBillIndex WHERE BillnumberID IN (SELECT * FROM #DeletedBillID)
--结存成功
SET @errcode=1
CLOSE PosCursor
DEALLOCATE PosCursor

END TRY 
BEGIN CATCH

	ROLLBACK TRAN SaveBill
	DROP TABLE #PosSaleBill,#tempbillid,#BillMulAccount
	CLOSE PosCursor
	DEALLOCATE PosCursor
	
	DECLARE @ErrorMessage VARCHAR(max)  
    SELECT  @ErrorMessage = ERROR_MESSAGE() 

--	RAISERROR('合并小票失败！',16,1)
	RAISERROR(@ErrorMessage,16,1)
	RETURN
END CATCH

DECLARE @Ret INT=0,@frozedate DATE
DECLARE AuditingCursor CURSOR FOR
SELECT BillNumberId FROM #daftBillNumerid
OPEN AuditingCursor
FETCH NEXT FROM AuditingCursor
INTO @Newbillnumberid
WHILE @@FETCH_STATUS = 0 
BEGIN
	SET @frozedate=NULL
	SELECT @billtype=billtype,@billdate=BillDate,@stypeid=Stypeid,@etypeid=etypeid FROM dbo.BillIndex WHERE BillNumberId=@Newbillnumberid
	SELECT @frozedate=FrozeDate FROM dbo.FrozeBusiness WHERE Stypeid=@stypeid
	IF @frozedate IS NOT NULL AND @frozedate>@billdate
		GOTO ERROR
	
	
	IF EXISTS(SELECT ConfigNo  FROM Userconfig  WHERE ConfigName='BillcodeCreateTime'AND Value=2)
	BEGIN
		SELECT @Month=Month(GETDATE())
		SELECT @Day=DAY(GETDATE())
		SET @BillFlag=CASE  WHEN @billtype =305 THEN 'LS' WHEN @BillType=11 THEN 'XK' WHEN @BillType=12 THEN 'ZXK'  WHEN @BillType=45 THEN 'XT' WHEN @BillType=46 THEN 'ZXT'  ELSE 'RB' END 	
		SET @BillCode=''	
		----单据编号
		EXEC Gp_GetBillCode @billtype, @MONTH,@DAY,@BillFlag,@BillDate,@stypeid,@BillCode OUTPUT,@dfullname,@cefullname,@billnumberid
		
		UPDATE dbo.BillIndex SET BillCode= @billcode 
		WHERE BillNumberId=@Newbillnumberid
		
		--保存种子数
		EXEC GP_AutoCombneRetail_SaveBillCode_Seed @billdate,@billtype,@billcode,@etypeid,@ktypeid,@dtypeid,@stypeid,@cefullname
	END	    
	
	
	
	BEGIN TRAN audit
	EXEC @Ret= dbo.Gp_Auditing @nBillID = @Newbillnumberid, -- numeric
	    @szCheckMan = @etypeid, -- varchar(50)
	    @szPID = '', -- varchar(1000)
	    @chvOpID = @etypeid, -- varchar(50)
	    @KTypeID = '', -- varchar(50)
	    @billtype = @billtype, -- int
	    @voucherMsg = '', -- varchar(50)
	    @vipcentinfo='',
	    @AssetMsg=''
	if @Ret=0 OR @ret>=-227 AND @Ret<=-210
	BEGIN
		COMMIT TRAN audit
		update PosRetailRecord SET AuditingFlag=1 WHERE RetailBillNumberId=@Newbillnumberid
	END
	ELSE
		ROLLBACK TRAN audit
		
	ERROR:	
	
	FETCH NEXT FROM AuditingCursor
	INTO @Newbillnumberid
END
CLOSE AuditingCursor
DEALLOCATE AuditingCursor

DROP TABLE #daftBillNumerid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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









/*

功能说明：       得到指定存储过程的参数

作    者：       谢吉康

创建日期：       2004-10-11

返回结果：       

*/

CREATE   PROCEDURE GP_Comm_GetSPParameter
(
	@strSPName VARCHAR(100),		--存储过程名
	@intFlag INT					--1表示输入参数，2表示输出参数，3表示所有参数
)
--@encode$--
AS

DECLARE @strSQL VARCHAR(500)

SET @strSQL=' SELECT a.Name,SUBSTRING(a.Name,2,LEN(a.Name)) AS ShortName,a.Length,a.IsOutParam,c.Name As Type FROM syscolumns a '
SET @strSQL=@strSQL+' INNER JOIN sysobjects b ON a.ID=b.ID AND b.Name='+CHAR(39)+@strSPName+CHAR(39)
--SELECT XType,Name FROM systypes WHERE XType=XUserType得到的是基本的数据类型
SET @strSQL=@strSQL+' INNER JOIN ( SELECT XType,Name FROM systypes WHERE XType=XUserType ) c ON a.XType=c.XType '
DECLARE @strCondition VARCHAR(100)

SET @strCondition=''
IF @intFlag=1
BEGIN
	SET @strCondition=' AND a.IsOutParam=0 '
END

IF @intFlag=2
BEGIN
	SET @strCondition=' AND a.IsOutParam=1 '
END			

IF @strCondition<>''
BEGIN
	SET @strSQL=@strSQL+@strCondition
END

--按列顺序排列
SET @strSQL=@strSQL+' ORDER BY  a.ColOrder'

EXEC(@strSQL)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[GP_CommissionInitInsert]')
                    AND TYPE IN ( N'P', N'PC' ) ) 
    DROP PROC [dbo].[GP_CommissionInitInsert]
	
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	By：Haiyang, Li
	Date：2012-6-9
	Description：受托, 委托代销期初保存明细和库存
*/

CREATE PROCEDURE [dbo].[GP_CommissionInitInsert]
(
    @PTypeId VARCHAR(50) ,				-- 商品ID
    @KTypeId VARCHAR(50) ,				-- 仓库ID
    @BTypeId VARCHAR(50) , 				-- 往来单位ID
    @STypeId VARCHAR(50) ,				-- 分支机构
    @Type INT ,										-- 类型
    @Qty  NUMERIC(24, 10)  ,					-- 基本单位数量
    @CostTotal  NUMERIC(24, 10)  ,		-- 成本总金额
    @Total  NUMERIC(24, 10)  ,				-- 总金额
    @Explain VARCHAR(256) ,				-- 说明
    @SerialType INT ,			--序列号状态(0: 非序列号商品)
    @DealType INT,			--处理状态
    @Detail TBType_CommissionInit READONLY,
    @SerialDetail TBType_PtypeSerialInit READONLY
)
 
AS 
BEGIN
		--受托委托
    DELETE  IniCommissionStock
    WHERE   PTypeId = @pTypeId
            AND Btypeid = @BTypeId
            AND Stypeid = @STypeId
            AND SerialType= @SerialType 
            AND Type = @Type;
    IF @Qty>0
    INSERT  INTO IniCommissionStock
            ( btypeid ,
              ptypeid ,
              ktypeid ,
              etypeid ,
              stypeid ,
              type ,
              qty ,
              CostTotal ,
              Total ,
	      SerialType ,
	      DealType ,
              explain 
            )
    VALUES  ( @BTypeId ,
              @PTypeId ,
              @KTypeId ,
              '' ,
              @STypeId ,
              @Type ,
              @Qty ,
              @CostTotal ,
              @Total ,
	      @SerialType,
	      @DealType,
              @Explain
		        )
		
		--明细
    DELETE  IniCommissionStock_Qty
    WHERE   PTypeId = @pTypeId
            AND Btypeid = @BTypeId
            AND Stypeid = @STypeId
            AND SerialType= @SerialType 
            AND Type = @Type;
    INSERT  INTO IniCommissionStock_Qty
            ( PTypeId ,
              Btypeid ,
              Stypeid ,
              Type ,
	      SerialType,
	      DealType,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              Qty ,
              NQty,	
              ProduceDate,
              ValidDate,
	          KTypeID,
	          CargoID,
	          GoodsCostPrice
            )
            SELECT  @PTypeId ,
                    @BTypeId ,
                    @Stypeid ,
                    @Type ,
	            @SerialType,
	            @DealType,
                    itemId ,
                    isCombined ,
                    goodsNumber ,
                    qty ,
                    nQty,
                    ProduceDate,
                    ValidDate,
		            KTypeID,
		            CargoID,
  		            GoodsCostPrice
            FROM    @Detail WHERE qty>0;
     IF @SerialType<>0 --序列号状态不为零，说明要录入序列号
     BEGIN 
     DECLARE 
		@DeleteSerialSql VARCHAR(3000),
        @BTypeID1 VARCHAR(200) ,	
        @BTypeID2 VARCHAR(200) ,	
        @Flag int
        IF @Type=140 AND @SerialType=32
			SET @DeleteSerialSql='UPDATE gp_initPtypeSerial SET BTypeID1='''' WHERE STypeId='''+@STypeId+''' AND PtypeID='''+@PTypeId+''' AND BTypeID1='''+@BTypeId+''' AND State=32 ';
        ELSE
        BEGIN
            SET @DeleteSerialSql='Delete From Gp_InitPTypeSerial Where PtypeID='''+@PTypeId+''' AND STypeId='''+@STypeId+'''  AND State=''' + convert(nvarchar(50),@SerialType) + '''';
            
			IF @Type=140 
			BEGIN
				SET @DeleteSerialSql=@DeleteSerialSql+' AND BTypeID1='''+@BTypeId+ ''''
				SET @BTypeID1=@BTypeId
				SET @BTypeID2=''
			END
			ELSE
			BEGIN
			--当状态为受托委托已发货时，关联了委托结算单位的序列号不能删除
				IF @SerialType=32
				SET @DeleteSerialSql=@DeleteSerialSql+' AND (BTypeID1 IS NULL OR BTypeID1='''')';
				
				SET @DeleteSerialSql=@DeleteSerialSql+' AND BTypeID2='''+@BTypeId + '''';
				SET @BTypeID1=''
				SET @BTypeID2=@BTypeId
			END
		END
        --PRINT @DeleteSerialSql;
		EXEC(@DeleteSerialSql)
		
		IF @Type=140 AND @SerialType=32
		BEGIN
			DECLARE @serialCount int
			
			SELECT @serialCount=COUNT(0)
			FROM @SerialDetail
			
			MERGE INTO gp_initPtypeSerial S 
			USING @SerialDetail SD 
			ON(S.CostPrice=SD.CostPrice AND S.GoodsNumber=SD.goodsNumber AND S.Serial=SD.Serial AND
			S.ProduceDate=SD.producedate AND S.ValidDate=SD.validdate AND S.ItemID=SD.itemId AND 
			S.IsCombined=SD.isCombined AND S.STypeId=@STypeId AND S.PtypeID=@PTypeId
			AND S.State=32 AND (S.BTypeID1='' OR S.BTypeID1 IS NULL))
			WHEN MATCHED THEN
			UPDATE SET BTypeID1=@BTypeId;
			
			--根据录入的基本条件去更新，处理成功条数与序列号条数不一致，说明一些序列号信息已经发生了某些改变
			IF @@ROWCOUNT<>@serialCount
				RAISERROR('委托录入受托委托已发货状态出错，存在已删除、已关联委托结算单位或者基本信息发生改变的序列号',16,1)
		END
		ELSE
		BEGIN
			IF @SerialType=7
				SET @Flag=1
			ELSE 
				SET @Flag=0
				
			DECLARE 
				@Serials VARCHAR(MAX)
				
				SET @Serials=''
				SELECT @Serials=@Serials+'я'+Serial
				FROM @SerialDetail
				
				-- 删除字符串最前面的‘,’
				IF LEN(@Serials)>0
					SET @Serials=RIGHT(@Serials,LEN(@Serials)-1)
			--判断序列号是否存在
			DECLARE 
			@CheckResult VARCHAR(max)
			EXEC Gp_CheckIniSerialInput '',@PTypeId,@Serials,0,@CheckResult OUT
			IF @CheckResult<>''
				RAISERROR(@CheckResult,16,1)
				
			INSERT INTO gp_initPtypeSerial
				(
					[Serial],
					[KtypeID],
					[PtypeID],
					[BTypeID1],
					[BtypeID2],
					[State],
					[Flag],
					[CommissionState],
					[iniFlag],
					[CostPrice],
					[GoodsNumber],
					[STypeId],
					[ItemID],
					[IsCombined],
					[CargoID],
					[ProduceDate],
					[ValidDate]
				)
				SELECT 
					Serial,
					KTypeID,
					@PTypeId,
					@BTypeID1,
					@BTypeID2,
					@SerialType,
					@Flag,
					'',
					1,
					CostPrice,
					goodsNumber,
					@STypeId,
					itemId,
					isCombined,
					CargoID,
					producedate,
					validdate
				From @SerialDetail;
		END
END
DELETE  IniCommissionStock WHERE Qty = 0
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CommissionInitQueryDetails]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CommissionInitQueryDetails]
GO

/*
By：Haiyang, Li
Date：2012-06-12
Description：委托, 受托代销期初明细查询
*/
CREATE PROCEDURE [dbo].[GP_CommissionInitQueryDetails]
(
  @PTypeId VARCHAR(50) ,		--商品ID
  @BTypeId VARCHAR(50) ,		--往来单位
  @STypeID VARCHAR(50) ,		--分支机构
  @Type VARCHAR(50)	,		--144: 受托代销; 140: 委托代销
  @SerialType INT,
  @LIMIT_CHECKCOSTPRICE int
)
--@encode$--
AS 
    SET NOCOUNT ON
    IF @SerialType=0
    SELECT  S.PTypeId ,
            S.Qty ,
            CASE WHEN LimitCostPrice=0 THEN '****' ELSE CAST(S.GoodsCostPrice AS VARCHAR(20)) END AS GoodsCostPrice,
            S.Nqty ,
            S.GoodsNumber , --批号
            V.ItemID ,
            V.Iscombined ,
            V.itemname -- 自由项
            ,s.ProduceDate
            ,s.ValidDate
    FROM    ( SELECT    PTypeId ,
                        Qty ,
                        Nqty ,
                        GoodsNumber , --批号
                        ItemID ,
                        Iscombined,
                        ProduceDate,
                        ValidDate,
                        GoodsCostPrice,
                        @LIMIT_CHECKCOSTPRICE AS LimitCostPrice
              FROM      dbo.IniCommissionStock_Qty
              WHERE     PTypeId = @PTypeId
                        AND Btypeid = @BTypeId
                        AND Stypeid = @STypeID
                        AND Type = @Type
            ) S
            LEFT JOIN dbo.V_Item V ON S.ItemID = V.itemid
                                      AND S.Iscombined = V.iscombined
    ELSE
    SELECT  
	        S.KTypeID ,
            S.CargoID ,
            CASE WHEN LimitCostPrice=0 THEN '****' ELSE CAST(S.GoodsCostPrice AS VARCHAR(20)) END AS GoodsCostPrice,
	        S.PTypeId ,
            S.Qty ,
            S.Nqty ,
            S.GoodsNumber , --批号
            V.ItemID ,
            V.Iscombined ,
            V.itemname -- 自由项
            ,ST.FullName AS kfullname --仓库名称
            ,CT.FullName AS cargofullname --货位名称
            ,s.ProduceDate
            ,s.ValidDate
            ,[dbo].[F_ConcatSerial](S.KTypeID,S.ItemID,S.CargoID,S.ProduceDate,S.ValidDate,S.GoodsCostPrice,S.GoodsNumber,@PTypeId,@BTypeId,@STypeID,@Type,@SerialType) AS serial
    FROM    ( SELECT    PTypeId ,
                        Qty ,
                        Nqty ,
                        GoodsNumber , --批号
                        ItemID ,
                        Iscombined,
                        ProduceDate,
                        ValidDate,
						KTypeID,
						CargoID,
						SerialType,
						GoodsCostPrice,
                        @LIMIT_CHECKCOSTPRICE AS LimitCostPrice
              FROM      dbo.IniCommissionStock_Qty
              WHERE     PTypeId = @PTypeId
                        AND Btypeid = @BTypeId
                        AND Stypeid = @STypeID
                        AND Type = @Type
						AND SerialType=@SerialType
            ) S
            LEFT JOIN dbo.V_Item V ON S.ItemID = V.itemid
                                      AND S.Iscombined = V.iscombined
            LEFT JOIN dbo.Stock ST ON ST.typeId = S.KTypeID 
            LEFT JOIN dbo.CargoType CT ON CT.CargoID=S.CargoID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_CommissionInitQueryPTypeInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_CommissionInitQueryPTypeInfo]
GO

/*
By：Haiyang, Li
Date：2012-06-12
Description：委托, 受托期初, 商品基本信息查询, 
*/
CREATE PROCEDURE [dbo].[GP_CommissionInitQueryPTypeInfo]
    (
      @PTypeId VARCHAR(50) ,		-- 商品ID
      @BTypeId VARCHAR(50) ,	-- 往来单位ID
      @STypeId VARCHAR(50) ,	-- 分支机构ID
      @Type VARCHAR(50) ,			--144: 受托代销; 140: 委托代销
      @State INT,
      @qty  NUMERIC(24, 10)  = 0 OUTPUT ,
      @price  NUMERIC(24, 10)  = 0 OUTPUT ,
      @costprice  NUMERIC(24, 10)  = 0 OUTPUT ,
      @costtotal  NUMERIC(24, 10)  = 0 OUTPUT ,
      @total  NUMERIC(24, 10)  = 0 OUTPUT ,
      @explain VARCHAR(256) = '' OUTPUT 
    )
--@encode$--
AS 
    SET NOCOUNT ON 
    SELECT  P.typeid ,
            P.usercode ,
            P.FullName AS ptypefullname , --P.Name, P.Standard, P.Type, P.Area, -- 基本信息
            P.customitemid ,
            P.customitemname ,
            P.customitemfrom , -- 自由项
            P.ifusegoodsnum , -- 是否启用批号
            P.IfSerial, -- 是否启用序列号标识
            P.baseunitid ,
            U.FullName AS baseunit , --基本单位
            P.assistantunitid ,
            U2.FullName AS assistantunit , -- 浮动单位
            U3.rate,
            p.usefullifeday
    FROM    ( SELECT    typeId ,
                        UserCode ,
                        FullName , --Name, Standard, Type, Area, -- 基本信息
                        customitemid ,
                        customitemname ,
                        customitemfrom ,  -- 自由项
                        ifusegoodsnum ,		-- 是否采用严格启用批号
                        baseUnitId ,			-- 基本单位id
                        AssistantUnitId,		-- 浮动单位id
                        IfSerial,				-- 是否启用序列号标识
                        usefullifeday
              FROM      dbo.ptype
              WHERE     typeId = @PTypeId
            ) P
            INNER JOIN dbo.PType_Units U ON P.baseUnitId = U.UnitsId
            LEFT JOIN dbo.PType_Units U2 ON P.AssistantUnitId = U2.UnitsId
            LEFT JOIN dbo.PType_Units_Ext U3 ON p.AssistantUnitId = U3.UnitsId
                                                 AND P.typeId = U3.PtypeID
            
    IF EXISTS ( SELECT TOP 1
                        1
                FROM    dbo.IniCommissionStock
                WHERE   Ptypeid = @PTypeId
                        AND Btypeid = @BTypeId
                        AND Stypeid = @STypeId
                        AND Type = @Type ) 
        BEGIN
            IF @State =0
            SELECT  @qty = SUM(Qty) ,
                    @costTotal = SUM(CostTotal) ,
                    @total = SUM(Total) ,
                    @costPrice = CASE WHEN @qty = 0 THEN 0 -- 成本单价	
                                      ELSE @costTotal / @qty
                                 END ,
                    @price = CASE WHEN @qty = 0 THEN 0-- 单价
                                  ELSE @total / @qty
                             END ,
                    @explain = MAX(explain)
            FROM    dbo.IniCommissionStock
            WHERE   Ptypeid = @PTypeId
                    AND Btypeid = @BTypeId
                    AND Stypeid = @STypeId
                    AND Type = @Type 
            ELSE
            SELECT  @qty = Qty ,
                    @costTotal = CostTotal ,
                    @total = Total ,
                    @costPrice = CASE WHEN Qty = 0 THEN 0 -- 成本单价	
                                      ELSE CostTotal / Qty
                                 END ,
                    @price = CASE WHEN Qty = 0 THEN 0-- 单价
                                  ELSE Total / Qty
                             END ,
                    @explain = explain
            FROM    dbo.IniCommissionStock
            WHERE   Ptypeid = @PTypeId
                    AND Btypeid = @BTypeId
                    AND Stypeid = @STypeId
                    AND Type = @Type 
                    AND SerialType=@State 
                        
        END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:彭勇
	日期：2016-01-28
	描述：提成规则复制新增
*/
CREATE PROCEDURE Gp_CopyAddBill
(
	 @BillNumberId  INT,
	 @UserTypeid	VARCHAR(100)=''		--制单人
	
)
--@encode$--
AS
SET NOCOUNT ON
INSERT  INTO CommissionRule
        ( BillCode ,
          FullName ,
          BillDate ,
          RuleStart ,
          RuleEnd ,
          CommissionStandard ,
          IsUseEtypeCommission ,
          ECommissionType ,
          CommissionStyle ,
          Checke ,
          Checker ,
          CheckeTime ,
          CheckerTime ,
          Comment ,
          BillState ,
          UseState ,
          IsStop 
        )
        SELECT  BillCode + '【copy】' BillCode ,
                FullName ,
                BillDate ,
                RuleStart ,
                RuleEnd ,
                CommissionStandard ,
                IsUseEtypeCommission ,
                ECommissionType ,
                CommissionStyle ,
                @UserTypeid ,
                '' ,
                GetDate() ,
                '' ,
                Comment ,
                1 ,
                1 ,
                IsStop
        FROM    CommissionRule
        WHERE   BillNumberId = @billnumberid
        
DECLARE @id INT
SELECT  @id = MAX(billnumberid)
FROM    CommissionRule 

INSERT  INTO CommissionRuleEtype(BillNumberId,EtypeID)
SELECT  @id ,EtypeID FROM    dbo.CommissionRuleEtype WHERE   BillNumberId = @BillNumberId 

INSERT  INTO CommissionRuleLeader
        ( BillNumberId ,
          EtypeID ,
          Proportion ,
          MaxRegion ,
          MinRegion ,
          CommissionTypeID
                    
        )
        SELECT  @id ,
                EtypeID ,
                Proportion ,
                MaxRegion ,
                MinRegion ,
                CommissionTypeID
        FROM    dbo.CommissionRuleLeader
        WHERE   BillNumberId = @BillNumberId 
        
INSERT  INTO CommissionRulePtype
        ( BillNumberId ,
          EtypeID ,
          Proportion ,
          PtypeID
                    
        )
        SELECT  @id ,
                EtypeID ,
                Proportion ,
                PtypeID
        FROM    dbo.CommissionRulePtype
        WHERE   BillNumberId = @BillNumberId 
        
INSERT  INTO CommissionRuleRegion
        ( BillNumberId ,
          EtypeID ,
          Proportion ,
          PtypeID ,
          MinRegion ,
          MaxRegion,
          Percentage          
        )
        SELECT  @id ,
                EtypeID ,
                Proportion ,
                PtypeID ,
                MinRegion ,
                MaxRegion,
                Percentage
        FROM    dbo.CommissionRuleRegion
        WHERE   BillNumberId = @BillNumberId 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



 SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2007-3-27
	描述：复制借欠单据
*/
CREATE PROCEDURE Gp_CopyLendBill(
	@BillNumberId	varchar(100),	--原始单据的ID
	@sBillType		int,			--原始单据类型
	@newBillType	int,			--目标单据类型
	@ETypeId		varchar(100),	--经手人
	@STypeId		varchar(max)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @chvETypeId		varchar(100),
		@chvBTypeId		varchar(100),
		@chvKTypeId		varchar(100),
		@numTotalQty	 NUMERIC(24, 10) ,
		@isExAudit		CHAR(1),
		@cargoid        INT

SELECT 	@chvBTypeId = BTypeId,
		@chvKTypeId = KTypeId,
		@numTotalQty= TotalQty
FROM 	LendIndex
WHERE	BillNumberId = @BillNumberId

SELECT @cargoid=CargoID from dbo.CargoType WHERE IsDefault=1 AND deleted=0 AND KtypeID=@chvKTypeId

IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @newBillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)
	SET @isExAudit = '0'
ELSE
	SET @isExAudit = ''


--强制将经手人写成当前用户
SET @chvETypeId = @ETypeId

--处理总计数量
IF @sBillType IN (71,88)
	BEGIN
		IF @newBillType IN (71,88)
			SET @numTotalQty = @numTotalQty
		ELSE
			SET @numTotalQty = -@numTotalQty
	END
ELSE
	BEGIN
		IF @newBillType IN (71,88)
			SET @numTotalQty = -@numTotalQty
		ELSE
			SET @numTotalQty = @numTotalQty
	END

BEGIN TRAN _CopyBillToDraft

DECLARE @Month 	VARCHAR(50),
		@Day 	VARCHAR(50)

SET @Month = Month(getdate())
SET @Day = Day(getdate())

DECLARE	@Re 				int,
		@bCode 				varchar(50),
		@chvBTypeAll		varchar(1),
		@BillCodeConfig		varchar(1),
		@RetVal				int,
		@Cur_BillNumberId	numeric(18,0),
		@datBillDate		DATETIME
		
SELECT 	@datBillDate=CONVERT(varchar(10),GetDate(),120)		

--处理单据自动编号的问题
DECLARE @strBillCodeHead varchar(10)
SET @strBillCodeHead = CASE 
							WHEN @newBillType = 71		THEN 'JJ'
							WHEN @newBillType = 72		THEN 'JC'
							WHEN @newBillType = 87		THEN 'CK'
							WHEN @newBillType = 88		THEN 'CH'
						END


SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @newBillType) AND @BillCodeConfig = '1'
	BEGIN
		SELECT @MONTH = ''
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @chvKTypeID
	END

DECLARE @BillCodeSTypeId VARCHAR(MAX)	--单据编号的分支机构		

SELECT @BillCodeSTypeId = STypeId FROM LendIndex WHERE BillNumberId = @BillNumberId

EXEC @Re=Gp_GetBillCode @newBillType, @MONTH,@DAY,@strBillCodeHead,@datBillDate,@BillCodeSTypeId,@bCode output

IF @Re<>0
BEGIN
   SELECT @RetVal = -2
   GOTO Error 
END

--正式复制数据，相同单据复制摘要，不同单据根据系统配子处理
IF @sBillType = @newBillType
	INSERT	INTO LendIndex(BillDate,BillCode,BillType,Comment,ATypeId,PTypeId,dealbtypeid,ETypeId,KTypeId,KTypeId2,IfCheck,Checke,TotalMoney,TotalInMoney,TotalQty,Tax,Period,Explain,RedWord,Draft,OrderId,WayBillCode,GoodsNumber,PackWay,Tel,Uploaded,Off_ID,DTypeID,STypeID,btypeid)
	SELECT	@datBillDate,@bCode,@newBillType,Comment,ATypeId,PTypeId,dealbtypeid,etypeid,KTypeId,KTypeId2,'f'/*IfCheck*/,Checke,TotalMoney,TotalInMoney,@numTotalQty,Tax,Period,Explain,RedWord,1/*Draft*/,OrderId,WayBillCode,GoodsNumber,PackWay,Tel,Uploaded,Off_ID,DTypeID,STypeID,@chvBTypeId
	FROM	LendIndex
	WHERE	BillNumberId = @BillNumberId
ELSE
	INSERT	INTO LendIndex(BillDate,BillCode,BillType,Comment,ATypeId,PTypeId,dealbtypeid,ETypeId,KTypeId,KTypeId2,IfCheck,Checke,TotalMoney,TotalInMoney,TotalQty,Tax,Period,Explain,RedWord,Draft,OrderId,WayBillCode,GoodsNumber,PackWay,Tel,Uploaded,Off_ID,DTypeID,STypeID,btypeid)
	SELECT	@datBillDate,@bCode,@newBillType,'',ATypeId,PTypeId,dealbtypeid,etypeid,KTypeId,KTypeId2,'f'/*IfCheck*/,Checke,TotalMoney,TotalInMoney,@numTotalQty,Tax,Period,Explain,RedWord,1/*Draft*/,OrderId,WayBillCode,GoodsNumber,PackWay,Tel,Uploaded,Off_ID,DTypeID,STypeID,@chvBTypeId
	FROM	LendIndex
	WHERE	BillNumberId = @BillNumberId

	

IF @@ROWCOUNT = 0
	BEGIN
		SET @RetVal = -1
		GOTO ERROR
	END 
ELSE
	SET @Cur_BillNumberId = SCOPE_IDENTITY();

IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN	
	EXEC GP_SaveBillCode_Seed @Cur_BillNumberId,@datBillDate,@newBillType,@bCode	
END

IF @sBillType = @newBillType
	BEGIN
		--写入明细
		INSERT INTO LendBill(BillNumberId,PTypeId,Qty,NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,CargoID,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder)
		SELECT	@Cur_BillNumberId,PTypeId,Qty,NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,@cargoid,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder
		FROM	LendBill
		WHERE	BillNumberId = @BillNumberId
	
		IF @@ROWCOUNT = 0
			BEGIN
				SET @RetVal = -3
				GOTO ERROR
			END
	END
ELSE
	BEGIN
		IF @sBillType IN (71,88)	--借进、借出还回
			BEGIN
				IF @newBillType IN (71,88)
					BEGIN
						--写入明细
						INSERT INTO LendBill(BillNumberId,PTypeId,Qty,NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,CargoID,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder)
						SELECT	@Cur_BillNumberId,PTypeId,Qty,NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,@cargoid,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder
						FROM	LendBill
						WHERE	BillNumberId = @BillNumberId
						
						IF @@ROWCOUNT = 0
							BEGIN
								SET @RetVal = -3
								GOTO ERROR
							END
					END
				ELSE
					BEGIN
						--写入明细
						INSERT INTO LendBill(BillNumberId,PTypeId,Qty,NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,CargoID,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder)
						SELECT	@Cur_BillNumberId,PTypeId,-Qty,-NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,@cargoid,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder
						FROM	LendBill
						WHERE	BillNumberId = @BillNumberId
						
						IF @@ROWCOUNT = 0
							BEGIN
								SET @RetVal = -3
								GOTO ERROR
							END
					END
			END
		ELSE
			BEGIN
				IF @newBillType IN (71,88)
					BEGIN
						--写入明细
						INSERT INTO LendBill(BillNumberId,PTypeId,Qty,NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,CargoID,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder)
						SELECT	@Cur_BillNumberId,PTypeId,-Qty,-NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,@cargoid,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder
						FROM	LendBill
						WHERE	BillNumberId = @BillNumberId
						
						IF @@ROWCOUNT = 0
							BEGIN
								SET @RetVal = -3
								GOTO ERROR
							END
					END
				ELSE
					BEGIN
						--写入明细
						INSERT INTO LendBill(BillNumberId,PTypeId,Qty,NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,CargoID,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder)
						SELECT	@Cur_BillNumberId,PTypeId,Qty,NQty,JobNumber,GoodsNo,OutFactoryDate,Comment,STypeID,@cargoid,GoodsNumber,IsCombined,ItemID,UnitRate,ShowOrder
						FROM	LendBill
						WHERE	BillNumberId = @BillNumberId
						
						IF @@ROWCOUNT = 0
							BEGIN
								SET @RetVal = -3
								GOTO ERROR
							END
					END
			END
	END

--源单据类型和目标单据类型不一致，则不复制摘要、说明
DECLARE @chvAutoCreateResume varchar(1)
SELECT	@chvAutoCreateResume = [Value]
FROM	UserConfig
WHERE	ConfigName = 'AutoCreateResume'

IF @sBillType <> @newBillType
	BEGIN
		IF @chvAutoCreateResume = '1'
			EXEC GP_AutoCreateBillCommentForLend @Cur_BillNumberId
		ELSE
			UPDATE	LendIndex
			SET		Comment = '',
					Explain = ''
			WHERE	BillNumberId = @Cur_BillNumberId
			
	END	

--修改最大的ID值
DECLARE @NewID numeric(10,0)
SELECT 	@NewID = ISNULL(MAX(ID),0) + 1
FROM	LendIndex

UPDATE	LendIndex SET ID = @NewID,IfAudit = @isExAudit WHERE BillNumberId = @Cur_BillNumberId

INSERT INTO BillOperateLog (BillnumberID, OperateType, EtypeID, OperateTime, IP)VALUES (@Cur_BillNumberId, '制单', @ETypeId, GETDATE(), '')


COMMIT Tran _CopyBillToDraft
RETURN 0

Error:
  ROLLBACK Tran _CopyBillToDraft 
  RETURN @RetVal















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@BillNumberId	varchar(100),	--原始单据的ID
	@sBillType		int,			--原始单据类型
	@newBillType	int,			--目标单据类型
	@ETypeId		varchar(100),	--经手人
	@STypeId		varchar(max)	--分支机构
	
SELECT
	@BillNumberId=14,
	@sBillType=87,
	@newBillType=87,
	@ETypeId='00001',
	@STypeId='00002000010000100001000010000100001000010000100001'
	
	
BEGIN TRAN
SELECT * FROM LENDINDEX

EXEC Gp_CopyLendBill
	@BillNumberId,
	@sBillType,
	@newBillType,
	@ETypeId,
	@STypeId

SELECT * FROM LENDINDEX

COMMIT TRAN

*/



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2007-3-27
	描述：复制借欠单据成其他单据
*/
CREATE   PROCEDURE Gp_CopyLendToOtherBill(
	@BillNumberId	varchar(100),	--原始单据的ID
	@sBillType		int,			--原始单据类型
	@newBillType	int,			--目标单据类型
	@ETypeId		varchar(100),	--经手人
	@STypeId		varchar(max),	--分支机构
	@Stock          varchar(100)    --仓库
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int


CREATE TABLE #GetManPTypeId1(TypeId	varchar(100),rate  NUMERIC(24, 10) ,aunitid VARCHAR(200))
INSERT INTO #GetManPTypeId1(TypeId,rate,aunitid) SELECT  a.TypeId,ISNULL(b.Rate,0)AS rate,ISNULL(b.UnitsId,0)AS UnitsId FROM dbo.ptype  a LEFT JOIN dbo.PType_Units_Ext b ON a.typeId=b.PtypeID AND a.AssistantUnitId=b.UnitsId
-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -5
	END
END  

-- ********	判断是否试用版 - END	********

DECLARE @chvETypeId		varchar(100),
		@chvBTypeId		varchar(100),
		@dealbtypeid		varchar(100),
		@chvKTypeId		varchar(100),
		@jinshourenid    VARCHAR(500),
		@jinshourenname   VARCHAR(500),
		@numTotalQty	 NUMERIC(24, 10) ,
		@cargoid        varchar(100),
		@atypeid1		varchar(100),
		@ceDtypeid			VARCHAR(100),
		@ceCheckId			VARCHAR(100),
		@cefullname			VARCHAR(500)='',		--制单人
		@cdfullname			VARCHAR(500)=''			--部门

SELECT 	@chvBTypeId = BTypeId,
        @jinshourenid=etypeid,
		@chvKTypeId = KTypeId,
		@numTotalQty= TotalQty,
		@ceCheckId=checke,
		@ceDtypeid=DTypeID

FROM 	LendIndex
WHERE	BillNumberId = @BillNumberId
SELECT @jinshourenname=TypeId FROM dbo.employee WHERE typeId=@jinshourenid
SET @dealbtypeid=(SELECT denominatedid FROM dbo.btype WHERE  typeId=@chvBTypeId)

SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @ceCheckId
SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

CREATE TABLE #temtable(atypeid1 VARCHAR(200),atypeid1name VARCHAR(200),flag VARCHAR(200))

INSERT INTO #temtable(atypeid1,atypeid1name,flag)  EXEC dbo.Web_GetAtype 
    @billtypeid=@newBillType, 
    @stypeid=@stypeid
         
set @atypeid1=(SELECT atypeid1 from #temtable)



SELECT @cargoid=CargoID from dbo.CargoType WHERE IsDefault=1 AND deleted=0 AND KtypeID=@chvKTypeId

--强制将经手人写成当前用户
SET @chvETypeId = @ETypeId

BEGIN TRAN _CopyBillToDraft

DECLARE @Month 	VARCHAR(50),
		@Day 	VARCHAR(50)

SET @Month = Month(getdate())
SET @Day = Day(getdate())

DECLARE	@Re 				int,
		@bCode 				varchar(50),
		@chvBTypeAll		varchar(1),
		@BillCodeConfig		varchar(1),
		@RetVal				int,
		@Cur_BillNumberId	numeric(18,0)

--处理单据自动编号的问题
DECLARE @strBillCodeHead varchar(10)
SET @strBillCodeHead = CASE 
							WHEN @newBillType = 34		THEN 'JK'
							WHEN @newBillType = 6		THEN 'JT'
							WHEN @newBillType = 11		THEN 'XK'
							WHEN @newBillType = 45		THEN 'XT'
							WHEN @newBillType = 300		THEN 'XD'
							WHEN @newBillType = 301		THEN 'JD'
						END


SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

--需要处理往来单位

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @newBillType) AND @BillCodeConfig = '1'
	BEGIN
		SELECT @MONTH = @jinshourenname -- 自定义时将月份写成经手人
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @chvKTypeID --自定义时将天写成仓库
	END

DECLARE @BillCodeSTypeId VARCHAR(MAX)	--单据编号的分支机构

SELECT @BillCodeSTypeId = STypeId FROM LendIndex WHERE BillNumberId = @BillNumberId

DECLARE	
	@datBillDate	DATETIME
	
SELECT
	@datBillDate=CONVERT(varchar(10),GetDate(),120)	
	
EXEC @Re=Gp_GetBillCode @newBillType, @MONTH,@DAY,@strBillCodeHead,@datBillDate,@BillCodeSTypeId,@bCode OUTPUT,@cdfullname,@cefullname

IF @Re<>0
BEGIN
   SELECT @RetVal = -2 
   GOTO Error 
END



--正式复制数据
IF @newBillType IN (300,301)
	BEGIN
		--判断订单是否有审核
		DECLARE @IfAudit int
		IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @newBillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)
			SET @IfAudit = 0
		ELSE
			SET @IfAudit = 1

		INSERT INTO OrderIndex(BTypeId,ETypeId,KTypeId,BillDate,ReachDate,BillCode,BillType,TotalMoney,TotalQty,Period,Checked,RedWord,BillOver,Comment,Explain,Checke,Tax,BillStatus,ETypeId2,WayMode,WayBillCode,GoodsNumber,PackWay,Tel,IfAudit,DTypeId,IsFinished,CanAlert,DelayType,DelayValue,OrderState,STypeID,CustomerTotal,FromBillNumberID,DealBTypeID,CID,Rate)
		SELECT	@dealbtypeid,ETypeId,@chvKTypeId,@datBillDate,CONVERT(varchar(10),GetDate(),120),@bCode,@newBillType,0,ABS(TotalQty),Period,0,0,0,'','',@ETypeId,0,0,'','','','','','',@IfAudit,DTypeId,'',1,0,0,0,StypeID,0,0,@chvBTypeID,1,1
		FROM	LendIndex
		WHERE	BillNumberId = @BillNumberId

		IF @@ROWCOUNT = 0
			BEGIN
				SET @RetVal = -1
				GOTO ERROR
			END 
		ELSE
			SET @Cur_BillNumberId = SCOPE_IDENTITY();
	END
ELSE
	BEGIN
		INSERT INTO BillIndex (AlertDay,checkTime,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,goodsnumber,packway,TEL,IfAudit,preferencemoney,DTypeId,Stypeid,FromBillNumberID,CostSale,DealBTypeID,CID,Rate,ATypeID1)
		SELECT 	9999,GetDate(),@datBillDate,BillCode=@bCode,BillType=@newBillType,atypeid='',ptypeid,@dealbtypeid,ETypeId,ktypeid,ktypeid2,'f',@ETypeId,totalmoney,totalinmoney=0,abs(totalqty),tax,period,0,1,OrderId,waybillcode,'',packway,TEL,'3',preferencemoney=0,DTypeId,STypeID,0,0,@chvBTypeId,1,1,@atypeid1
		FROM 	LendIndex
		WHERE 	[BillNumberId] = @BillNumberId
		
		IF @@ROWCOUNT = 0
			BEGIN
				SET @RetVal = -1
				GOTO ERROR
			END 
		ELSE
			SET @Cur_BillNumberId = SCOPE_IDENTITY();
	END
	
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN	
	EXEC GP_SaveBillCode_Seed
		@Cur_BillNumberId,
		@datBillDate,
		@newBillType,
		@bCode
END	

--写入明细
DECLARE @chvNewBillTableName 	varchar(50),
		@chvSQL					varchar(8000)

SET @chvNewBillTableName = CASE WHEN @newBillType = 34	THEN 'BuyBill'
								WHEN @newBillType = 6	THEN 'BuyBackBill'
								WHEN @newBillType = 11	THEN 'SaleBill'
								WHEN @newBillType = 45	THEN 'SaleBackBill'
								WHEN @newBillType = 300	THEN 'OrderBill'
								WHEN @newBillType = 301	THEN 'OrderBill'
							END
							















							
						

IF @newBillType IN (300,301)
BEGIN

--启用游标生成条码

DECLARE	@pusercode 			varchar(100),
		@pentrycode 		varchar(100),
		@punit		        varchar(100),
		@pstock		        varchar(100),
		@pprice				varchar(100),
		@snumber		    int,
		@enumber		    int,
		@tdata              varchar(200),
		@flag               int,
		@val                int,
		@id                 int,
		@tentrycode         varchar(500)
	
	
select @val=SubValue from sysdata where SubName='ifuseentrycodeext'

		
set @flag=1
set @tentrycode=''

CREATE TABLE #temtRuleData(snum VARCHAR(100),enum VARCHAR(100),data VARCHAR(200))
--先将规则数据插入零时表
INSERT INTO #temtRuleData (snum,enum,data)
SELECT startnum,endnum, sourceid FROM BarCode_Ext WHERE barcodeid=(select BarCodeid from BarCodeForBilltype where BillType=@newBillType)

--select * from #GetManPTypeId1

Declare MyCusror2 Cursor For 
Select lb.id, pp.usercode,pp.entrycode,
(select usercode from PType_Units where unitsid=pp.baseunitid) baseuint,@Stock stock,'0000' price 
From LendBill lb inner join ptype pp  on pp.typeid=lb.ptypeid
WHERE lb.BillNumberId=@BillNumberId  
Open MyCusror2;    
Fetch next From MyCusror2 Into @id, @pusercode,@pentrycode,@punit,@pstock,@pprice
While(@@Fetch_Status = 0)
BEGIN

if(@val=1)
BEGIN    
 -- 小游标
  Declare MyCusror1 Cursor
  For 
  Select snum,enum,data from #temtRuleData
  Open MyCusror1    
  Fetch next From MyCusror1 Into @snumber,@enumber,@tdata
  While(@@Fetch_Status = 0)
  Begin
  
    IF(@tdata='1')
     BEGIN
      IF((@enumber-@snumber+1) <> LEN(@punit))
      BEGIN
        set @flag=0
      END
      ELSE set @tentrycode=@tentrycode+@punit
     END
     IF(@tdata='2')
     BEGIN
      IF((@enumber-@snumber+1) <> LEN(@pusercode))
        BEGIN
        set @flag=0
       
      END
        ELSE set @tentrycode=@tentrycode+@pusercode
     END
     IF(@tdata='3')
     BEGIN
      IF((@enumber-@snumber+1) <> LEN(@pentrycode))
         BEGIN
        set @flag=0
       
      END
        ELSE set @tentrycode=@tentrycode+@pentrycode
     END
     IF(@tdata='4')
     BEGIN
      IF((@enumber-@snumber+1) <> LEN(@pstock))
      BEGIN
        set @flag=0
        
      END
        ELSE set @tentrycode=@tentrycode+@pstock
     END
     IF(@tdata='5')
     BEGIN
       set @tentrycode=@tentrycode+'0000'
     END
    Fetch next From MyCusror1 Into @snumber,@enumber,@tdata
  End
  Close MyCusror1    
  Deallocate MyCusror1
 --  小游标
 print(@flag)
 --判断后执行具体的拼接
 IF(@flag=1)--条码规则
 BEGIN
 print('进')
 SET @chvSQL = '
		INSERT INTO ' + @chvNewBillTableName + '(BillNumberId,comment,PtypeId,Qty,mqty,Price,discount,DiscountPrice,TaxPrice,TaxTotal,total,STypeID,cargoid,nqty,UnitID,NUnitID,MUnitID,UnitRate,goodsnumber,ItemID,IsCombined,entrycode)
		SELECT ' + CAST(@Cur_BillNumberId AS varchar(100)) + ','''',PTypeId,ABS(Qty),ABS(Qty),0,1,0,0,0,0,STypeID,'+@cargoid+',abs(CASE WHEN UnitRate=0 THEN 0 ELSE qty/UnitRate END),b.baseUnitId,b.AssistantUnitId,b.baseUnitId,UnitRate,a.goodsnumber,a.ItemID,a.IsCombined, ''' + @tentrycode + ''' as entrycode
		FROM	LendBill a inner join ptype b on a.ptypeid=b.typeid
		WHERE a.id = ' + CAST(@id AS varchar(100)) 
	
print(@tentrycode)
print(@chvSQL)
EXEC(@chvSQL)

 END
 ELSE 
  BEGIN
  --是否为多单位
    SET @chvSQL = '
		INSERT INTO ' + @chvNewBillTableName + '(BillNumberId,comment,PtypeId,Qty,mqty,Price,discount,DiscountPrice,TaxPrice,TaxTotal,total,STypeID,cargoid,nqty,UnitID,NUnitID,MUnitID,UnitRate,goodsnumber,ItemID,IsCombined,entrycode)
		SELECT ' + CAST(@Cur_BillNumberId AS varchar(100)) + ','''',PTypeId,ABS(Qty),ABS(Qty),0,1,0,0,0,0,STypeID,'+@cargoid+',abs(CASE WHEN UnitRate=0 THEN 0 ELSE qty/UnitRate END),b.baseUnitId,b.AssistantUnitId,b.baseUnitId,UnitRate,a.goodsnumber,a.ItemID,a.IsCombined,(select case when isnull(bu.entrycode,'''') <> '''' THEN bu.entrycode ELSE b.entrycode END from PType_Units_Ext bu where bu.ptypeid=a.ptypeid and bu.IsDefaultUnit=1)
		FROM	LendBill a inner join ptype b on a.ptypeid=b.typeid inner join #GetManPTypeId1 c on c.typeid=a.ptypeid
		WHERE a.id = ' + CAST(@id AS varchar(100))
		
    EXEC(@chvSQL)

   
  END
 
 
 
 END
 
 ELSE--未启用条码规则
 BEGIN
   --是否为多单位
    SET @chvSQL = '
		INSERT INTO ' + @chvNewBillTableName + '(BillNumberId,comment,PtypeId,Qty,mqty,Price,discount,DiscountPrice,TaxPrice,TaxTotal,total,STypeID,cargoid,nqty,UnitID,NUnitID,MUnitID,UnitRate,goodsnumber,ItemID,IsCombined,entrycode)
		SELECT ' + CAST(@Cur_BillNumberId AS varchar(100)) + ','''',PTypeId,ABS(Qty),ABS(Qty),0,1,0,0,0,0,STypeID,'+@cargoid+',abs(CASE WHEN UnitRate=0 THEN 0 ELSE qty/UnitRate END),b.baseUnitId,b.AssistantUnitId,b.baseUnitId,UnitRate,a.goodsnumber,a.ItemID,a.IsCombined,(select case when isnull(bu.entrycode,'''') <> '''' THEN bu.entrycode ELSE b.entrycode END from PType_Units_Ext bu where bu.ptypeid=a.ptypeid and bu.IsDefaultUnit=1)
		FROM	LendBill a inner join ptype b on a.ptypeid=b.typeid inner join #GetManPTypeId1 c on c.typeid=a.ptypeid
		WHERE a.id = ' + CAST(@id AS varchar(100)) 
		
EXEC(@chvSQL)

 END
 
Fetch next From MyCusror2 Into @id, @pusercode,@pentrycode,@punit,@pstock,@pprice
END    
Close MyCusror2    
Deallocate MyCusror2  

END
	--SET @chvSQL = '
	--	INSERT INTO ' + @chvNewBillTableName + '(BillNumberId,comment,PtypeId,Qty,mqty,Price,discount,DiscountPrice,TaxPrice,TaxTotal,total,STypeID,cargoid,nqty,UnitID,NUnitID,MUnitID,UnitRate,goodsnumber,ItemID,IsCombined)
	--	SELECT ' + CAST(@Cur_BillNumberId AS varchar(100)) + ','''',PTypeId,ABS(Qty),ABS(Qty),0,1,0,0,0,0,STypeID,'+@cargoid+',abs(CASE WHEN UnitRate=0 THEN 0 ELSE qty/UnitRate END),b.baseUnitId,c.aunitid,b.baseUnitId,UnitRate,a.goodsnumber,a.ItemID,a.IsCombined
	--	FROM	LendBill a inner join ptype b on a.ptypeid=b.typeid inner join #GetManPTypeId1 c on c.typeid=a.ptypeid
	--	WHERE [BillNumberId] = ' + CAST(@BillNumberId AS varchar(100)) + ' ORDER BY ID'
ELSE
BEGIN
	SET @chvSQL = '
		INSERT INTO ' + @chvNewBillTableName + '(BillNumberId,comment,PtypeId,Qty,mqty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1,GoodsCostPrice,STypeID,cargoid,nqty,UnitID,NUnitID,MUnitID,UnitRate,goodsnumber,ItemID,IsCombined)
		SELECT ' + CAST(@Cur_BillNumberId AS varchar(100)) + ','''',PTypeId,ABS(Qty),ABS(Qty),0,1,0,jobnumber,OutFactoryDate,0,0,0,0,0,-1,STypeID,'+@cargoid+',abs(CASE WHEN UnitRate=0 THEN 0 ELSE qty/UnitRate END),b.baseUnitId,b.AssistantUnitId,b.baseUnitId,UnitRate,a.goodsnumber,a.ItemID,a.IsCombined
		FROM	LendBill a inner join ptype b on a.ptypeid=b.typeid inner join #GetManPTypeId1 c on c.typeid=a.ptypeid
		WHERE [BillNumberId] = ' + CAST(@BillNumberId AS varchar(100)) + ' ORDER BY ID'


EXEC(@chvSQL)

END
DECLARE @cost INT ,
@tempsql NVARCHAR(200),
@tembillcode NVARCHAR(200)
SELECT @tembillcode=billcode FROM dbo.LendIndex WHERE BillNumberId=@BillNumberId
SELECT @cost=SubValue FROM dbo.sysdata WHERE SubName='costing'
IF @cost=3 --如果是手工指定法则把成本单价改为-1
BEGIN
SET @tempsql='UPDATE '+ @chvNewBillTableName +' SET goodscostprice=-1 where billnumberid='+CAST(@Cur_BillNumberId AS VARCHAR(100))
EXEC(@tempsql)
END
IF @newBillType=11--bug4807
BEGIN
 UPDATE dbo.SaleBill SET PriceSource=@tembillcode+'单据生成' WHERE BillNumberId =CAST(@Cur_BillNumberId AS VARCHAR(100))
END
IF @@ERROR <> 0
	BEGIN
		SET @RetVal = -3
		GOTO ERROR
	END

--处理客户和供货商不统一时的往来单位情况
IF EXISTS(SELECT * FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 0)
	BEGIN
		IF @newBillType IN (34,6,301)
			BEGIN
				IF LEFT(@chvBTypeId,5)='00001'
					BEGIN
						IF @newBillType = 301
						BEGIN
							UPDATE	OrderIndex SET BTypeId = '' WHERE BillNumberId = @Cur_BillNumberId
								UPDATE	OrderIndex SET DealBTypeID = '' WHERE BillNumberId = @Cur_BillNumberId
						END		
						ELSE
						BEGIN
							UPDATE	BillIndex SET BTypeId = '' WHERE BillNumberId = @Cur_BillNumberId
							UPDATE	BillIndex SET DealBTypeID = '' WHERE BillNumberId = @Cur_BillNumberId
						END	
					END
			END
		ELSE
			BEGIN
				IF LEFT(@chvBTypeId,5)='00002'
					BEGIN
						IF @newBillType = 300
						BEGIN
							UPDATE	OrderIndex SET BTypeId = '' WHERE BillNumberId = @Cur_BillNumberId
							UPDATE	OrderIndex SET DealBTypeID = '' WHERE BillNumberId = @Cur_BillNumberId
						END	
						ELSE
						BEGIN
							UPDATE	BillIndex SET BTypeId = '' WHERE BillNumberId = @Cur_BillNumberId
							UPDATE	BillIndex SET DealBTypeID = '' WHERE BillNumberId = @Cur_BillNumberId
						END	
					END
			END
	END

--判断是否需要自动生成摘要
DECLARE @chvAutoCreateResume varchar(1)
SELECT	@chvAutoCreateResume = [Value]
FROM	UserConfig
WHERE	ConfigName = 'AutoCreateResume'

IF @chvAutoCreateResume = '1'
	BEGIN
		IF @newBillType IN (300,301)
			EXEC GP_AutoCreateBillCommentForOrder @Cur_BillNumberId
		ELSE
			EXEC GP_AutoCreateBillComment @Cur_BillNumberId
	END
	
--修改表体仓库
SET @chvSQL = 'UPDATE '+@chvNewBillTableName+' SET KTypeId = '''+@chvKTypeId+''' WHERE BillNumberId = '+CAST(@Cur_BillNumberId AS varchar(MAX))
EXEC(@chvSQL)

--更新ShowOrder排序号
SET @chvSQL='IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(N'''+@chvNewBillTableName+''',N''U'') AND Name=''ShowOrder'')
			 BEGIN
				UPDATE '+@chvNewBillTableName+' SET ShowOrder=ID WHERE BillNumberID='+CAST(@Cur_BillNumberId AS VARCHAR(10))+'
			 END'
EXEC(@chvSQL)

-- 自动生成的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @Cur_BillNumberId,@newBillType

--自动生成订单
IF @newBillType IN (300,301)
BEGIN
	EXECUTE GP_Deal_OrderQTY @Cur_BillNumberId,@newBillType,'+'
END

INSERT INTO BillOperateLog (BillnumberID, OperateType, EtypeID, OperateTime, IP)VALUES (@Cur_BillNumberId, '制单', @ETypeId, GETDATE(), '')


COMMIT Tran _CopyBillToDraft
RETURN 0

Error:
  ROLLBACK Tran _CopyBillToDraft 
  RETURN @RetVal

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：复制草稿或生成单据处理草稿库存
	返回结果：
	作    者：施训果
	创建时间：2017-03-03
	修改历史：
	
*/
CREATE          PROCEDURE GP_CopyOrCreateBill_DraftQTY
(
	@BillNumberID	INT,
	@BillType		INT
)
AS

DECLARE	@EffectFlag CHAR(4) = '+'	-- +：普通单据复制草稿或者自动生成单据正向影响库存
		
EXECUTE GP_Deal_DraftQTY @BillNumberID,@BillType,@EffectFlag	

IF @BillType IN (11,12,34,140,144,400,402)
BEGIN
	-- 处理订单库存,引用未过账数量
	IF @BillType = 34
		EXEC GP_Deal_OrderReferQty_BuyBill @BillnumberID,@BillType,@EffectFlag
	ELSE
		EXEC GP_Deal_OrderReferQty @BillnumberID,@BillType,@EffectFlag
END
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-19
	描述：拷贝当前分支机构的价格给其他分支机构
*/

CREATE PROCEDURE Gp_CopyPriceInfoToOtherStype
(
	@OperatorID	VARCHAR(MAX),	--当前操作员ID
	@fstypeid	VARCHAR(MAX),	--当前分支机构
	@tstypeid	VARCHAR(MAX)	--目标分支机构
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DELETE FROM PType_STypePrice WHERE STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@TSTypeId,11,@OperatorID)) AND STypeID <> @fstypeid

DECLARE @STypeId VARCHAR(MAX)
declare @maxnumber int;

select @maxnumber=MAX(XiWaMaxNumber) from PType_STypePrice

DECLARE TmpCursor CURSOR FOR
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@tstypeid,11,@OperatorID) WHERE TypeId <> @fstypeid

OPEN TmpCursor

FETCH NEXT FROM TmpCursor INTO @STypeId

WHILE @@FETCH_STATUS = 0
	BEGIN
	
	
		INSERT INTO PType_STypePrice
		(
			STypeID,
			PTypeID,
			PreBuyPrice1, 
			PreBuyPrice2, 
			PreBuyPrice3, 
			PreBuyPrice4, 
			PreBuyPrice5, 
			PreSalePrice1, 
			PreSalePrice2, 
			PreSalePrice3, 
			PreSalePrice4, 
			PreSalePrice5, 
			PreSalePrice6, 
			PreSalePrice7, 
			PreSalePrice8, 
			PreSalePrice9, 
			PreSalePrice10, 
			RetailPrice, 
			TopSalePrice, 
			LowSalePrice,
			RecPrice,
			TopBuyPrice,
			XiWaMaxNumber,
			referprice,
			UnitID,
			IsDefaultUnit
			
		)
		SELECT	@STypeId AS STypeID,
				p.PTypeID,
				PreBuyPrice1, 
				PreBuyPrice2, 
				PreBuyPrice3, 
				PreBuyPrice4, 
				PreBuyPrice5, 
				PreSalePrice1, 
				PreSalePrice2, 
				PreSalePrice3, 
				PreSalePrice4, 
				PreSalePrice5, 
				PreSalePrice6, 
				PreSalePrice7, 
				PreSalePrice8, 
				PreSalePrice9, 
				PreSalePrice10, 
				RetailPrice, 
				TopSalePrice, 
				LowSalePrice,
				RecPrice,
				TopBuyPrice,
				@maxnumber as XiWaMaxNumber,
			referprice,
			p.UnitID,
			p.IsDefaultUnit
		FROM	PType_STypePrice p
		inner join ptype_units_ext ext on  p.ptypeid=ext.ptypeid and p.unitid=ext.unitsid and ext.ratetype=0
		WHERE	STypeID = @fstypeid
		
		set @maxnumber=@maxnumber+1
		FETCH NEXT FROM TmpCursor INTO @STypeId
	END
	
CLOSE TmpCursor
DEALLOCATE TmpCursor			

if exists(select * from Userconfig where ConfigName ='IsPosStart' and Value=1 )
begin
	delete  from PosReDataGlobal where stypeid=@stypeid 
	insert into  PosReDataGlobal values(1,@stypeid)
	delete  PosIsUpdateData where stypeid=@stypeid and tbType='PType_StypePrice'
	insert into  PosIsUpdateData values('PType_StypePrice',0,1,@stypeid)	

end
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2006-5-12
	描述：复制生产模板
*/
CREATE  PROCEDURE Gp_CopyProduceModel(
	@strProduceModelName	varchar(255),
	@intProduceModelIndex	int
)
--@encode$--
AS
SET NOCOUNT ON

SELECT	TOP 1 1
FROM	ProduceModelIndex
WHERE	ProduceModelName = @strProduceModelName

IF @@ROWCOUNT <> 0
	BEGIN
		--RAISERROR('查询主索引表失败！',16,1)
		RETURN -5
	END

DECLARE @MaxId 		int,
		@PTypeId	varchar(100),
		@Comment	varchar(1000)

--获取最大的ID
SELECT 	@MaxId = Max(ProduceModelId)+1 
FROM 	ProduceModelIndex

SELECT	@PTypeId = PTypeId,
		@Comment = Comment
FROM	ProduceModelIndex
WHERE	ProduceModelId = @intProduceModelIndex

IF @@ROWCOUNT = 0
	BEGIN
		--RAISERROR('查询主索引表失败！',16,1)
		RETURN -1
	END

BEGIN TRAN

--写入数据
INSERT INTO ProduceModelIndex
(
	ProduceModelId,
	ProduceModelName,
	PTypeId,
	Comment
)VALUES(
	@MaxId,
	@strProduceModelName,
	@PTypeId,
	@Comment
)

IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		--RAISERROR('写主索引表失败！',16,1)
		RETURN -2
	END

--处理明细表
SELECT	@MaxId AS ProduceModelId,
		PTypeId,
		Qty
INTO	#MxTable
FROM	ProduceModel
WHERE	ProduceModelId = @intProduceModelIndex
ORDER BY
	[ID]

IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		--RAISERROR('查询明细表失败！',16,1)
		RETURN -3
	END


INSERT INTO dbo.ProduceModel
        ( ProduceModelID ,
          PtypeID ,
          Qty 
          
        )
SELECT	*
FROM	#MxTable

IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		--RAISERROR('写入明细表失败！',16,1)
		RETURN -4
	END

--提交事务
COMMIT TRAN

--删除临时表
DROP TABLE #MxTable













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-19
	描述：物价信息的拷贝
*/

CREATE PROCEDURE Gp_CopyPTypePrice
(
	@fstypeid	VARCHAR(MAX),	--当前分支机构
	@tstypeid	VARCHAR(MAX),	--目标分支机构
	@ntype		VARCHAR(MAX)	--0.商品信息 1.分支机构物价信息
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #TmpPrice
(
	STypeId		VARCHAR(50),
	PTypeId		VARCHAR(50),
	RecPrice	 NUMERIC(24, 10),
	UnitId		INT
)

INSERT INTO #TmpPrice SELECT STypeId,PTypeId,RecPrice,UnitId FROM PType_STypePrice WHERE STypeID = @fstypeid

DELETE FROM PType_STypePrice WHERE STypeID = @fstypeid
declare @maxnumber int;

select @maxnumber=MAX(XiWaMaxNumber) from PType_STypePrice
--商品价格信息
IF @ntype = '0'
	BEGIN
		INSERT INTO PType_STypePrice
		(
			STypeID,
			PTypeID,
			PreBuyPrice1, 
			PreBuyPrice2, 
			PreBuyPrice3, 
			PreBuyPrice4, 
			PreBuyPrice5, 
			PreSalePrice1, 
			PreSalePrice2, 
			PreSalePrice3, 
			PreSalePrice4, 
			PreSalePrice5, 
			PreSalePrice6, 
			PreSalePrice7, 
			PreSalePrice8, 
			PreSalePrice9, 
			PreSalePrice10, 
			RetailPrice, 
			TopSalePrice, 
			LowSalePrice,
			TopBuyPrice,
			referprice,
			XiWaMaxNumber,
			UnitID,
			IsDefaultUnit
		)
		SELECT	@fstypeid AS STypeID,
				p.PTypeID,
				PreBuyPrice1, 
				PreBuyPrice2, 
				PreBuyPrice3, 
				PreBuyPrice4, 
				PreBuyPrice5, 
				PreSalePrice1, 
				PreSalePrice2, 
				PreSalePrice3, 
				PreSalePrice4, 
				PreSalePrice5, 
				PreSalePrice6, 
				PreSalePrice7, 
				PreSalePrice8, 
				PreSalePrice9, 
				PreSalePrice10, 
				RetailPrice, 
				TopSalePrice, 
				LowSalePrice,
				TopBuyPrice,
				referprice,
				@maxnumber+1 as  XiWaMaxNumber,
				p.UnitID,
			    p.IsDefaultUnit
		FROM	PType_Price p
		inner join ptype_units_ext ext on  p.ptypeid=ext.ptypeid and p.unitid=ext.unitsid and ext.ratetype=0
		
		--修改原来的最近进价
		UPDATE	PType_STypePrice
		SET		RecPrice = T.RecPrice
		FROM    PType_STypePrice P,
				#TmpPrice T
		WHERE	P.STypeID = T.STypeId 
				AND P.PTypeID = T.PTypeId
				AND P.UnitId = T.UnitId
				AND P.STypeID = @fstypeid
	END
ELSE
	BEGIN
		INSERT INTO PType_STypePrice
		(
			STypeID,
			PTypeID,
			PreBuyPrice1, 
			PreBuyPrice2, 
			PreBuyPrice3, 
			PreBuyPrice4, 
			PreBuyPrice5, 
			PreSalePrice1, 
			PreSalePrice2, 
			PreSalePrice3, 
			PreSalePrice4, 
			PreSalePrice5, 
			PreSalePrice6, 
			PreSalePrice7, 
			PreSalePrice8, 
			PreSalePrice9, 
			PreSalePrice10, 
			RetailPrice, 
			TopSalePrice, 
			LowSalePrice,
			RecPrice,
			TopBuyPrice,
			referprice,
			XiWaMaxNumber,
			UnitID,
			IsDefaultUnit
		)
		SELECT	@fstypeid AS STypeID,
				p.PTypeID,
				PreBuyPrice1, 
				PreBuyPrice2, 
				PreBuyPrice3, 
				PreBuyPrice4, 
				PreBuyPrice5, 
				PreSalePrice1, 
				PreSalePrice2, 
				PreSalePrice3, 
				PreSalePrice4, 
				PreSalePrice5, 
				PreSalePrice6, 
				PreSalePrice7, 
				PreSalePrice8, 
				PreSalePrice9, 
				PreSalePrice10, 
				RetailPrice, 
				TopSalePrice, 
				LowSalePrice,
				RecPrice,
				TopBuyPrice,
				referprice,
				@maxnumber+1 as  XiWaMaxNumber,
				p.UnitID,
				p.IsDefaultUnit
		FROM	PType_STypePrice p
		inner join ptype_units_ext ext on  p.ptypeid=ext.ptypeid and p.unitid=ext.unitsid and ext.ratetype=0
		WHERE	STypeID = @tstypeid
	END

if exists(select * from Userconfig where ConfigName ='IsPosStart' and Value=1 )
begin
	delete  from PosReDataGlobal where stypeid=@fstypeid 
	insert into  PosReDataGlobal values(1,@fstypeid)
	delete  PosIsUpdateData where stypeid=@fstypeid and tbType='PType_StypePrice'
	insert into  PosIsUpdateData values('PType_StypePrice',0,1,@fstypeid)	
end
RETURN 0	

DROP TABLE #TmpPrice


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[GP_Cost_Re]')
                    AND type IN ( N'P', N'PC' ) ) 
    DROP PROCEDURE [dbo].[GP_Cost_Re]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*

作者：冯波

成本重算

对于之前修改单据所默认的当时出库成本，需要写入INPUTCOSTPRICE,但是在重算时需要清除掉，那么HANDZEROCOST是否设置为2来区分之前的1呢？
*/
CREATE   PROCEDURE [dbo].[GP_Cost_Re]
    (
    @strOpID				VARCHAR(50),			--操作员ID
	@strPTypeID				VARCHAR(50),			--过滤商品，肯定有值，这个是商品叶子节点
	@strSTypeID				VARCHAR(50),			--过滤分支机构，肯定有值，这个是分支机构叶子节点
	@decInputCostPrice		NUMERIC(24,10),			--弹框录入的成本，如果没有录入，则传-1000
	@strInputPTypeID		VARCHAR(50),			--需要录入成本的商品
	@strInputKTypeID		VARCHAR(50),			--需要录入成本的仓库
	@datDealBeginDate		DATETIME,				--成本重算的起始日期
	@nRet					INT OUT,				--返回0表示成功重算，返回-100，表示需要弹出录入成本的框，录入后，继续计算,返回-200表示不需要进行成本重算
	@strOutputPTypeID		VARCHAR(50)	OUT,		--返回需要录入成本的商品
	@strOutputKTypeID		VARCHAR(50)	OUT,		--返回需要录入成本的仓库
	@oldOutBillCost			NUMERIC(24,10) OUT,		--返回需要录入成本的单据的原成本
	@strErrMsg				VARCHAR(500)='' OUT	
)
--@encode$--
AS 

BEGIN TRAN CostRe
SAVE TRAN CostRePoint

IF @datDealBeginDate IS NULL 
    SET @datDealBeginDate = CAST('1900-01-01 00:00:00.000' AS DATETIME)

DECLARE @intCountcostbybilldate INT
--根据单据日期来计算成本

SELECT  @intCountcostbybilldate = Value
FROM    Userconfig
WHERE   ConfigName = 'countcostbybilldate'

SELECT  @nRet = 0 ,
        @strErrMsg = ''

IF @strSTypeID = '' 
    BEGIN
        SELECT  @nRet = -101 ,
                @strErrMsg = '调用成本计算时，分支机构不能为空'
	
        ROLLBACK TRAN CostRePoint
        COMMIT TRAN CostRe
        RETURN
    END	

IF NOT EXISTS ( SELECT  TypeID
                FROM    SType
                WHERE   TypeId = @strSTypeID
                        AND sonnum = 0 ) 
    BEGIN
        SELECT  @nRet = -102 ,
                @strErrMsg = '调用成本计算时，需要传入的分支机构应该是叶子节点，现在TYPEID='
                + @strSTypeID + ''
	
        ROLLBACK TRAN CostRePoint
        COMMIT TRAN CostRe
        RETURN
    END

IF @strPTypeID = '' 
    BEGIN
        SELECT  @nRet = -111 ,
                @strErrMsg = '调用成本计算时，商品不能为空'
	
        ROLLBACK TRAN CostRePoint
        COMMIT TRAN CostRe
        RETURN
    END	

IF NOT EXISTS ( SELECT  TypeID
                FROM    PType
                WHERE   TypeId = @strPTypeID
                        AND sonnum = 0 ) 
    BEGIN
        SELECT  @nRet = -112 ,
                @strErrMsg = '调用成本计算时，需要传入的商品应该是叶子节点，现在TYPEID='
                + @strPTypeID + ''
	
        ROLLBACK TRAN CostRePoint
        COMMIT TRAN CostRe
        RETURN
    END
	
DECLARE @intQtyDot INT ,
		@intPriceDot INT ,
		@intMoneyDot INT ,
		@intDiscountDot INT ,
		@intTaxDot INT ,
		@intCRateDot INT ,
		@intTRateDot INT	

--获取系统配置的小数位数
EXEC GP_Post_Dot	@intQtyDot OUT, 
					@intPriceDot OUT, 
					@intMoneyDot OUT,
					@intDiscountDot OUT, 
					@intTaxDot OUT, 
					@intCRateDot OUT,
					@intTRateDot OUT	

/*	
--判断有没有修改过单据和红冲单据，是否需要重算成本，不需要则退出
--需要则判断哪些单据需要重算及其后的单据需要重算
--开始重算库存成本
--重算库存项目
--重算其他项目
--处理成本价销售等	
成本重算跟月结的关系
注意修改单据时，没改变商品时，那些取原单成本的,HANDZEROCOST是否该为2，然后才好重算成本？
*/

DECLARE @datPostTime DATETIME,
		@nBillID	 INT,
		@nBillType	 INT
	
--得到最早被红冲或全面修改的单据过账时间
EXEC GP_Cost_Re_GetInfo	@strPTypeID,
						@strSTypeID,
						@datDealBeginDate,
						@nBillID OUT,
						@nBillType OUT,
						@datPostTime OUT,
						@nRet OUT

--SELECT 'getifnfo',@nBillID,@nBillType,@datPostTime

IF @nRet <> 0 
    BEGIN
        ROLLBACK TRAN CostRePoint
        COMMIT TRAN CostRe
        RETURN
    END	

--SELECT 'GP_Cost_Re_GetInfo',@nRet

--删除相关的凭证关联信息						
EXEC GP_Cost_Re_DEL_Ac_GoodsBill_VoucherBill	@strSTypeID,
												@strPTypeID,
												@datPostTime	

--本单关联的物流单据
CREATE TABLE #SourceBill
    (
      BillNumberID BIGINT ,
      PTypeID VARCHAR(50) ,
      KTypeID VARCHAR(50) ,
      ShareFee NUMERIC(24, 10) ,
      PostTime DATETIME ,
      BillDate DATETIME ,
      ID BIGINT ,
      FromBillNumberID BIGINT ,
      FromID BIGINT ,
      Comment VARCHAR(500)
    )

--需要定义#AfterModifyBill
CREATE TABLE #AfterModifyBill
    (
      BillNumberID BIGINT ,
      BillType INT ,
      BillID BIGINT ,
      PTypeID VARCHAR(50) ,
      KTypeID VARCHAR(50) ,
      SortID BIGINT ,
      Qty NUMERIC(24, 10) ,
      PostTime DATETIME ,
      STypeID VARCHAR(50) ,
      BillDate DATETIME
    )

--所有关联的商品信息
CREATE TABLE #TMPPTypeInfo
(
  PTypeID VARCHAR(50) ,
  KTypeID VARCHAR(50)
)
CREATE CLUSTERED INDEX [IX_TEMPPTypeInfo] ON [dbo].[#TMPPTypeInfo](PTypeID,KTypeID)
    
CREATE TABLE #PTypeInfo
(
  PTypeID VARCHAR(50) ,
  KTypeID VARCHAR(50)
)
CREATE CLUSTERED INDEX [IX_PTypeInfo] ON [dbo].[#PTypeInfo](PTypeID,KTypeID)
    
CREATE TABLE #StockInfo
(
  PTypeID VARCHAR(50) ,
  KTypeID VARCHAR(50)
)
CREATE CLUSTERED INDEX [IX_StockInfo] ON [dbo].[#StockInfo](PTypeID,KTypeID)


DECLARE @strInsertPTypeInfo VARCHAR(MAX) ,
		@datMonthProc DATETIME
	--月结时间

SELECT  @datMonthProc = StartDate
FROM    MonthProc
WHERE   MonthNo = '本期'
        AND STypeID = @strstypeid
--这里还需要参考那2个不参与成本计算的配置,来过滤单据类型

--关联的红冲商品信息（这里还需要考虑过滤掉@strPTypeID,@strSTypeID）
--PRINT(@datPostTime)

CREATE TABLE #RedWordPTypeInfo
    (
      PTypeID VARCHAR(50) ,
      KTypeID VARCHAR(50)
    )

IF @intCountcostbybilldate = 1 
    BEGIN
        INSERT  #PTypeInfo
        ( 
			PTypeID ,
			KTypeID
        )
        SELECT DISTINCT
                PtypeId ,
                KtypeId
        FROM    dbo.InOutstocktable
        WHERE   BillDate >= @datPostTime
                AND Audited = 1
                AND PtypeId = @strPTypeID
                AND STypeID = @strSTypeID
    END
ELSE 
    BEGIN
        INSERT  #PTypeInfo
        ( 
			PTypeID ,
			KTypeID
        )
        SELECT DISTINCT
                PtypeId ,
                KtypeId
        FROM    dbo.InOutstocktable
        WHERE   PostTime >= @datPostTime
                AND Audited = 1
                AND PtypeId = @strPTypeID
                AND STypeID = @strSTypeID
    END

CREATE NONCLUSTERED INDEX [IX_AfterModifyBill_PSQ] ON [dbo].[#AfterModifyBill](PostTime,SortID,Qty)
CREATE NONCLUSTERED INDEX [IX_AfterModifyBill_BSQ] ON [dbo].[#AfterModifyBill](BillDate,SortID,Qty)
CREATE NONCLUSTERED INDEX [IX_AfterModifyBill_BillNumberID] ON [dbo].[#AfterModifyBill](BillNumberID)

--得到需要修改的单据
EXEC Gp_CostRe_GetSourceBill @datPostTime, 
                             @datDealBeginDate,
							 @strSTypeID, 
							 @nRet OUT,
							 @strErrMsg OUT

--SELECT 'Gp_CostRe_GetSourceBill',@nRet
--PRINT('SourceBill')
IF @nRet <> 0 
    BEGIN
        ROLLBACK TRAN CostRePoint
        COMMIT TRAN CostRe
        RETURN
    END	

--SELECT '#AfterModifyBill',* FROM #AfterModifyBill

--处理其他单据的成本（包括单据的出库部分，部分入库类单据，还有同价调拨单的连环单据）
--重算成本，如果遇到取不到成本的，需要弹出录入框来录入

IF @decInputCostPrice <> 0
    AND @strInputPTypeID <> @strPTypeID 
    SET @decInputCostPrice = -1000

--计算InOutStockTable数据
EXEC Gp_CostRe_BatchCost	@decInputCostPrice, 
							@strInputPTypeID, 
							@strSTypeID,
							@strInputKTypeID, 
							@datPostTime, 
							@datDealBeginDate,
							@nBillType, 
							@nRet OUT,
							@strOutputPTypeID OUT, 
							@strOutputKTypeID OUT, 
							@oldOutBillCost OUT,
							@strErrMsg OUT

--PRINT('BatchCost')

IF @nRet <> 0 
    BEGIN
        ROLLBACK TRAN CostRePoint
        COMMIT TRAN CostRe
        RETURN	
    END
ELSE 
    BEGIN
        IF EXISTS ( SELECT  PTypeID
                    FROM    dbo.CommissionStock
                    WHERE   Type = 140
                            AND Ptypeid = @strPTypeID ) 
            BEGIN
                DELETE  FROM CommissionStock
                WHERE   Ptypeid = @strPTypeID
						AND Type IN (140,141,142)

                INSERT  INTO dbo.CommissionStock
                ( Ptypeid ,
                  Btypeid ,
                  Type ,
                  Qty ,
                  CostTotal ,
                  Total ,
                  Stypeid ,
                  ETypeID ,
                  KTypeID
                )
                SELECT  a.PTypeID ,
                        a.BTypeID ,
                        140 ,
                        SUM(a.Qty) ,
                        SUM(a.CostTotal) ,
                        SUM(a.Total) ,
                        a.STypeID ,
                        '' ,
                        ''
                FROM    ( SELECT    PTypeID ,
                                    Btypeid ,
                                    CostTotal ,
                                    Total ,
                                    Qty ,
                                    STypeID
                          FROM      dbo.IniCommissionStock
                          WHERE     Ptypeid = @strPTypeID
                                    AND Type = 140
                          UNION ALL
                          SELECT    I.Ptypeid ,
                                    B.Btypeid ,
                                    I.CostTotal ,
                                    I.total ,
                                    I.Qty ,
                                    I.STypeID
                          FROM      dbo.InOutstocktable I
                          INNER JOIN dbo.BillIndex B ON I.BillNumberId = B.BillNumberId AND I.BillType = B.BillType
                          WHERE     I.Ptypeid = @strPTypeID
                                    AND I.BillType IN ( 140,141,142)
                                    AND I.Ktypeid = '10000'
                        ) a
                GROUP BY a.PTypeID ,
                        a.BTypeID ,
                        a.STypeID
	
            END	
    END		


IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill ) 
    BEGIN
		--处理库存商品总值
        EXEC GP_Cost_ReCostTotal @strSTypeID
	
		--PRINT('CostTotal')

		--处理对应的其他科目
        EXEC GP_Cost_ReOtherTotal @strSTypeID
	
		--PRINT('OtherTotal')	
		--SELECT * FROM InOutstocktable WHERE BillType=205

		--如果存在发出商品，则通过期初和LISTTABLE计算余额

		--重算项目余额
		IF EXISTS ( SELECT  a.ATypeID
            FROM    dbo.AType_Total a
            LEFT JOIN ( 
						SELECT  AtypeId ,
                                STypeID ,
                                CID ,
                                SUM(TOTAL) Total ,
                                SUM(NTOTAL) NTotal
                        FROM    dbo.ListTable
                        GROUP BY AtypeId ,
                                STypeID ,
                                CID
                      ) b ON a.ATypeID = b.AtypeId
                             AND a.STypeID = b.STypeID
                             AND a.CID = b.CID
                             AND a.Total <> a.Total00
                             + ISNULL(b.Total, 0) ) 
            BEGIN
                UPDATE  dbo.AType_Total
                SET     Total = AType_Total.Total00 + ISNULL(b.Total, 0) ,
                        NTotal = AType_Total.NTotal00 + ISNULL(b.NTotal, 0)
                FROM    ( SELECT    AtypeId ,
                                    STypeID ,
                                    CID ,
                                    SUM(TOTAL) Total ,
                                    SUM(NTOTAL) NTotal
                          FROM      dbo.ListTable
                          GROUP BY  AtypeId ,
                                    STypeID ,
                                    CID
                        ) b
                WHERE   AType_Total.ATypeID = b.AtypeId
                        AND AType_Total.STypeID = b.STypeID
                        AND AType_Total.CID = b.CID
                        AND AType_Total.Total <> AType_Total.Total00
                        + ISNULL(b.Total, 0)
            END

		--对于涉及到的单据，回写成本价，成本金额
        EXEC Gp_NeedFill
    END

DROP TABLE #RedWordPTypeInfo

--计算完后，需要记录红冲单据计算到哪一个了，或者记录当前最后一个红冲单号，日期，时间等
--修改了的单据，是否重算成本，可以通过参数来确定，这样方便在头一次计算错误后，再重新计算
--重新计算时，注意加上ATYPE_TOTAL的校验

--计算之后写日志
INSERT  CostReLog
( 
	PTypeID ,
	STypeID ,
	PostTime ,
	OperatorID ,
	BillNumberID ,
	BillType
)
SELECT  @strPTypeID ,
        @strSTypeID ,
        @datPostTime ,
        @strOpID ,
        @nBillID ,
        @nBillType


COMMIT TRAN CostRe

GO





IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[GP_Cost_Re_DEL_Ac_GoodsBill_VoucherBill]')
                    AND type IN ( N'P', N'PC' ) ) 
    DROP PROCEDURE [dbo].[GP_Cost_Re_DEL_Ac_GoodsBill_VoucherBill]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*
	作者：谢吉康
	日期：2019-09-11
	描述：成本计算的时候删除相关的会计凭证关联信息
*/

CREATE   PROCEDURE [dbo].[GP_Cost_Re_DEL_Ac_GoodsBill_VoucherBill]
(
	@strSTypeID		VARCHAR(50),
	@strPTypeID		VARCHAR(50),
	@datPostTime	DATETIME	
)
AS

IF EXISTS ( SELECT  B.BillNumberID
            FROM    MoveBill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    MoveBill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


IF EXISTS ( SELECT  B.BillNumberID
            FROM    movebjbill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    movebjbill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--分支机构调拨出库单
IF EXISTS ( SELECT  B.BillNumberID
            FROM    stypemovebill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND B.BillType = 303
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    stypemovebill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND B.BillType = 303
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--其他出库单
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.OtherInOutBill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND B.BillType = 202
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.OtherInOutBill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND B.BillType = 202
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--积分兑换
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.integralexchangebill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.integralexchangebill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		

	
--维修品调出
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.wx_bill_out A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.wx_bill_out A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--维修品调拨单
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.wx_Bill_Move A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.wx_Bill_Move A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--采购退货单
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.BuyBackBill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.BuyBackBill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--销售出库单
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.SaleBill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.SaleBill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--销售退货单
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.saleBackBill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.saleBackBill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--销售换货
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.salegoodsexchangebill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND A.InOrOut = 'O'
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.salegoodsexchangebill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND A.InOrOut = 'O'
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--采购换货
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.buygoodsexchangebill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND A.InOrOut = 'O'
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.buygoodsexchangebill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND A.InOrOut = 'O'
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END		


--委托受托 代销退货
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.commissionbill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND BillType IN ( 142, 146 )
                    AND b.BillDate >= @datPostTime
                    AND c.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.commissionbill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND BillType IN ( 142, 146 )
                        AND b.BillDate >= @datPostTime
                        AND c.VourchBillId = -1 )
    END		


--发出商品退货
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.SendBill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND c.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.SendBill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND c.VourchBillId = -1 )
    END		


--发出商品退货
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.SendBackBill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND c.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.SendBackBill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND c.VourchBillId = -1 )
    END		


--暂估退货
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.AppraisalBackBill A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND c.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.AppraisalBackBill A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND c.VourchBillId = -1 )
    END		


--发出商品开票
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.ReceiptBill A
                    INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_ReceiptBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND B.BillType = 405
                    AND b.BillDate >= @datPostTime
                    AND c.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_ReceiptBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.ReceiptBill A
                        INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_ReceiptBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND B.BillType = 405
                        AND b.BillDate >= @datPostTime
                        AND c.VourchBillId = -1 )
    END		

--组合品销售单		
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.PT_Combin_SaleBillDetail A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND c.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.PT_Combin_SaleBillDetail A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND c.VourchBillId = -1 )
    END		

--组合品销售退货单
IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.PT_Combin_SaleBackBillDetail A
                    INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
            WHERE   B.posttime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND c.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_GoodsBill_VoucherBill
        WHERE   GoodsBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.PT_Combin_SaleBackBillDetail A
                        INNER JOIN dbo.BillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_GoodsBill_VoucherBill C ON C.GoodsBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND c.VourchBillId = -1 )
    END	
    
    --门店配送单327

IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.DeliveryBill A
                    INNER JOIN dbo.PosAllotApplyBillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_DeliveryBill_VoucherBill C ON C.DeliveryBillId = B.BillNumberId
            WHERE   B.PostTime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_DeliveryBill_VoucherBill
        WHERE   DeliveryBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.DeliveryBill A
                        INNER JOIN dbo.PosAllotApplyBillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_DeliveryBill_VoucherBill C ON C.DeliveryBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END	
   --门店退货单328

IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.DeliveryBackBill A
                    INNER JOIN dbo.PosAllotApplyBillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_DeliveryBill_VoucherBill C ON C.DeliveryBillId = B.BillNumberId
            WHERE   B.PostTime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_DeliveryBill_VoucherBill
        WHERE   DeliveryBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.DeliveryBackBill A
                        INNER JOIN dbo.PosAllotApplyBillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_DeliveryBill_VoucherBill C ON C.DeliveryBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END	
   --门店验收单329

   IF EXISTS ( SELECT  B.BillNumberID
            FROM    dbo.DeliveryCheckBill A
                    INNER JOIN dbo.PosAllotApplyBillIndex B ON A.BillNumberId = B.BillNumberId
                    INNER JOIN dbo.Ac_DeliveryBill_VoucherBill C ON C.DeliveryBillId = B.BillNumberId
            WHERE   B.PostTime >= @datPostTime
                    AND B.RedWord = 0
                    AND B.IsIni = 0
                    AND B.Stypeid = @strSTypeID
                    AND A.PtypeId = @strPTypeID
                    AND b.BillDate >= @datPostTime
                    AND C.VourchBillId = -1 ) 
    BEGIN
        DELETE  Ac_DeliveryBill_VoucherBill
        WHERE   DeliveryBillId IN (
                SELECT  B.BillNumberID
                FROM    dbo.DeliveryCheckBill A
                        INNER JOIN dbo.PosAllotApplyBillIndex B ON A.BillNumberId = B.BillNumberId
                        INNER JOIN dbo.Ac_DeliveryBill_VoucherBill C ON C.DeliveryBillId = B.BillNumberId
                WHERE   B.posttime >= @datPostTime
                        AND B.RedWord = 0
                        AND B.IsIni = 0
                        AND B.Stypeid = @strSTypeID
                        AND A.PtypeId = @strPTypeID
                        AND b.BillDate >= @datPostTime
                        AND C.VourchBillId = -1 )
    END	


GO



GO
--
--		成本计算获取计算最小日期、单据ID，单据类型
--
IF EXISTS ( SELECT  1
            FROM    SysObjects
            WHERE   ID = OBJECT_ID(N'GP_Cost_Re_GetInfo', N'P') ) 
    BEGIN 
        DROP PROC GP_Cost_Re_GetInfo
    END
GO

CREATE PROC GP_Cost_Re_GetInfo
    (
      @strPTypeID		VARCHAR(50) ,			--过滤商品，没则为空
      @strSTypeID		VARCHAR(50) ,			--过滤分支机构，没则为空
      @datBeginDealDate DATETIME ,				--
      @nBillID			INT OUT ,
      @nBillType		INT OUT ,
      @datPostTime		DATETIME OUT ,
      @nRet				INT OUT					--返回值
    )
AS 

BEGIN
    DECLARE @datMonthProc DATETIME		--月结时间

    SELECT  @datMonthProc = StartDate
    FROM    MonthProc
    WHERE   MonthNo = '本期'
            AND stypeid = @strSTypeID

    DECLARE @intCountcostbybilldate INT   --根据单据日期来计算成本
	
    SELECT  @intCountcostbybilldate = Value
    FROM    Userconfig
    WHERE   ConfigName = 'countcostbybilldate'

    IF @datBeginDealDate < @datMonthProc 
        SET @datBeginDealDate = @datMonthProc

/*

后续注意下，成本重算跟月结存，是否生成凭证之间的关系和控制

*/

--寻找指定分支机构,指定商品的第一张入库类单据,此后的都重算
    DECLARE @datDealTime DATETIME
	
    SELECT  @datDealTime = GETDATE()	
	
    SET @nRet = 0

	--SELECT '@intCountcostbybilldate=',@intCountcostbybilldate,'@datBeginDealDate=',@datBeginDealDate		
	
    IF @intCountcostbybilldate = 1 
        BEGIN
            IF NOT EXISTS ( SELECT  BillNumberID
                            FROM    InoutStockTable
                            WHERE   BillDate >= @datBeginDealDate
                                    AND PTypeID = @strPTypeID
                                    AND Audited = 1 ) 
            BEGIN
                SET @nRet = -200
                RETURN
            END
	
            SELECT  @datPostTime = MIN(BillDate)
            FROM    dbo.InOutstocktable
            WHERE   BillDate >= @datBeginDealDate
                    AND PTypeID = @strPTypeID
                    AND Audited = 1
	
            SELECT  @nBillID = MIN(BillNumberID)
            FROM    dbo.InOutstocktable
            WHERE   BillDate = @datPostTime
                    AND PTypeID = @strPTypeID
	
	
            SELECT  @nBillType =MIN( BillType)
            FROM    dbo.InOutstocktable
            WHERE   BillNumberID = @nBillID
                    AND PTypeID = @strPTypeID
			
			--SELECT '@nBillID=',@nBillID,'@nBillType=',@nBillType,'@datPostTime=',@datPostTime
        END
    ELSE 
        BEGIN
            IF NOT EXISTS ( SELECT  BillNumberID
                            FROM    InoutStockTable
                            WHERE   PostTime >= @datBeginDealDate
                                    AND PTypeID = @strPTypeID
                                    AND Audited = 1 ) 
            BEGIN
                SET @nRet = -200
                RETURN
            END		

            SELECT  @datPostTime = MIN(PostTime)
            FROM    dbo.InOutstocktable
            WHERE   BillDate >= @datBeginDealDate
                    AND PTypeID = @strPTypeID
                    AND Audited = 1
	
            SELECT  @nBillID = MIN(BillNumberID)
            FROM    dbo.InOutstocktable
            WHERE   PostTime = @datPostTime
                    AND PTypeID = @strPTypeID
	
            SELECT  @nBillType = MIN( BillType)
            FROM    dbo.InOutstocktable
            WHERE   BillNumberID = @nBillID
                    AND PTypeID = @strPTypeID
                    AND PostTime = @datPostTime		
	--SELECT '@nBillID=',@nBillID,'@nBillType=',@nBillType,'@datPostTime=',@datPostTime
        END	
		--SELECT '@nRet=',@nRet
END
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_Cost_ReCostTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_Cost_ReCostTotal]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

处理库存科目成本


*/
CREATE   PROCEDURE GP_Cost_ReCostTotal
    (
      @chvSTypeID      VARCHAR(50)
    )
--@encode$--
AS --完后再改相关的库存商品科目和它所对应的科目（这个要分单据来查），再处理总账
--处理ListTable
--总账可以通过累计差值的办法来修改

--先改相关单据的库存起初值(之后考虑方向)
DECLARE @STOCKID VARCHAR(50) ,
        @OldTotal NUMERIC(24, 10) ,
        @NewTotal NUMERIC(24, 10) ,
        @OldTotal_DX NUMERIC(24, 10) ,
        @NewTotal_DX NUMERIC(24, 10) ,
        @sysID INT ,
        @WTDXSP_ID INT
	
	

SELECT  @STOCKID = NID
FROM    Ac_Items
WHERE   UserCode = '1241'
SELECT  @WTDXSP_ID = NID
FROM    Ac_Items
WHERE   UserCode = '1261'
SELECT  @sysID = CID
FROM    Ac_Currency
WHERE   Sysrow = 1


SELECT  @OldTotal = SUM(Total)  --这里只需要之前的一个总值即可
FROM    ListTable a
        INNER JOIN ( SELECT DISTINCT
                            BillNumberID ,
                            BillType
                     FROM   #AfterModifyBill
                   ) b ON a.BillNumberId = b.BillNumberID
                          AND a.BillType = b.BillType
WHERE   AtypeId = @STOCKID

SELECT  @OldTotal = ISNULL(@OldTotal, 0)

SELECT  @OldTotal_DX = ISNULL(SUM(Total), 0)  --billtype =141
FROM    ListTable a
        INNER JOIN ( SELECT DISTINCT
                            BillNumberID ,
                            BillType
                     FROM   #AfterModifyBill
                   ) b ON a.BillNumberId = b.BillNumberID
                          AND a.BillType = b.BillType
                          AND a.billtype = 141
WHERE   AtypeId = @WTDXSP_ID

UPDATE  ListTable
SET     Total = ISNULL(b.Total, 0) ,
        Ntotal = ISNULL(b.Total, 0)
FROM    ( SELECT    b.BillNumberID ,
                    a.BillType ,
                    SUM(a.CostTotal) AS Total
          FROM      InOutstocktable a
                    INNER JOIN ( SELECT DISTINCT
                                        BillNumberID ,
                                        BillType
                                 FROM   #AfterModifyBill
                               ) b ON a.BillNumberId = b.BillNumberID
                                      AND a.BillType = b.BillType
                                      AND a.billtype = 141
          WHERE     a.KtypeId = '10000'
          GROUP BY  b.BillNumberID ,
                    a.BillType
        ) b
WHERE   ListTable.BillNumberId = b.BillNumberID
        AND ListTable.AtypeId = @WTDXSP_ID
        AND ListTable.BillType = b.BillType


UPDATE  ListTable
SET     Total = ISNULL(b.Total, 0) ,
        Ntotal = ISNULL(b.Total, 0)
FROM    ( SELECT    b.BillNumberID ,
                    a.BillType ,
                    SUM(a.CostTotal) AS Total
          FROM      InOutstocktable a
                    INNER JOIN ( SELECT DISTINCT
                                        BillNumberID ,
                                        BillType
                                 FROM   #AfterModifyBill
                               ) b ON a.BillNumberId = b.BillNumberID
                                      AND a.BillType = b.BillType
          WHERE     a.KtypeId <> '10000'
          GROUP BY  b.BillNumberID ,
                    a.BillType
        ) b
WHERE   ListTable.BillNumberId = b.BillNumberID
        AND ListTable.AtypeId = @STOCKID
        AND ListTable.BillType = b.BillType


--如果库存商品之前在LISTTABLE,现在不需要写入的，可以先不管它（最多存在一条为零的数据而已）
--如果库存商品之前不在LISTTABLE，现在需要写入的，则增加
IF EXISTS ( SELECT DISTINCT
                    a.BillNumberID
            FROM    #AfterModifyBill a
            WHERE   --a.BillType IN (6,161,146,16,21,160) AND
                    NOT EXISTS ( SELECT b.BillNumberId
                                 FROM   ListTable b
                                 WHERE  b.BillNumberId = a.BillNumberID
                                        AND b.AtypeId = @STOCKID ) ) 
    BEGIN

--插入库存商品科目
--IfOut先默认为0，届时按单据类型来处理(需要核实下这个字段有没有用)
        INSERT  ListTable
        ( BillNumberId ,
          BillDate ,
          BillType ,
          AtypeId ,
          BtypeId ,
          EtypeId ,
          Total ,
          CostTotal ,
          Audited ,
          Ifout ,
          DTypeID ,
          STypeID ,
          CID ,
          Ntotal ,
          Rate
        )
        SELECT DISTINCT
                b.BillNumberID ,
                a.BillDate ,
                a.BillType ,
                @STOCKID ,
                ISNULL(e.BTypeID,'')+ ISNULL(f.btypeid,''),
                a.ETypeID ,
                SUM(a.CostTotal) AS Total ,
                SUM(a.CostTotal) AS Total ,
                a.Audited ,
                0 ,
                a.DTypeID ,
                a.STypeID ,
                @sysID ,
                SUM(a.CostTotal) AS NTotal ,
                1
        FROM    InOutstocktable a
                LEFT JOIN dbo.FaPiaoBillIndex e ON e.BillType=a.billtype AND a.BillNumberId = e.BillNumberID
                LEFT JOIN dbo.BillIndex f ON f.BillType=a.billtype AND a.BillNumberId =f.BillNumberID
                INNER JOIN ( SELECT DISTINCT
                                    a.BillNumberID
                             FROM   #AfterModifyBill a
                             WHERE  --a.BillType IN (6,161,146,16,21,160) AND
                                    NOT EXISTS ( SELECT
                                                  b.BillNumberId
                                                 FROM
                                                  ListTable b
                                                 WHERE
                                                  b.BillNumberId = a.BillNumberID
                                                  AND b.AtypeId = @STOCKID )
                           ) b ON a.BillNumberId = b.BillNumberID
        WHERE   a.KtypeId <> '10000'
        GROUP BY b.BillNumberID ,
                a.BillDate ,
                a.BillType ,
                --a.BTypeID ,
                a.ETypeID ,
                a.DTypeID ,
                a.STypeID ,
                a.Audited,
                e.BTypeID,
                f.btypeid
        HAVING  SUM(a.CostTotal) <> 0

    END

--billtype=141
IF EXISTS ( SELECT DISTINCT
                    a.BillNumberID
            FROM    #AfterModifyBill a
            WHERE   a.BillType IN ( 141 )
                    AND NOT EXISTS ( SELECT b.BillNumberId
                                     FROM   ListTable b
                                     WHERE  b.BillNumberId = a.BillNumberID
                                            AND b.AtypeId = @WTDXSP_ID ) ) 
    BEGIN
--插入库存商品科目
--IfOut先默认为0，届时按单据类型来处理(需要核实下这个字段有没有用)
        INSERT  ListTable
        ( BillNumberId ,
          BillDate ,
          BillType ,
          AtypeId ,
          BtypeId ,
          EtypeId ,
          Total ,
          CostTotal ,
          Audited ,
          Ifout ,
          DTypeID ,
          STypeID ,
          CID ,
          Ntotal ,
          Rate
        )
        SELECT DISTINCT
                b.BillNumberID ,
                a.BillDate ,
                a.BillType ,
                @WTDXSP_ID ,
                a.BTypeID ,
                a.ETypeID ,
                SUM(a.CostTotal) AS Total ,
                SUM(a.CostTotal) AS Total ,
                a.Audited ,
                0 ,
                a.DTypeID ,
                a.STypeID ,
                @sysID ,
                SUM(a.CostTotal) AS NTotal ,
                1
        FROM    InOutstocktable a
                INNER JOIN ( SELECT DISTINCT
                                    a.BillNumberID
                             FROM   #AfterModifyBill a
                             WHERE  a.BillType IN ( 141 )
                                    AND NOT EXISTS ( SELECT
                                                  b.BillNumberId
                                                  FROM
                                                  ListTable b
                                                  WHERE
                                                  b.BillNumberId = a.BillNumberID
                                                  AND b.AtypeId = @WTDXSP_ID )
                           ) b ON a.BillNumberId = b.BillNumberID
        WHERE   a.KtypeId = '10000'
        GROUP BY b.BillNumberID ,
                a.BillDate ,
                a.BillType ,
                a.BTypeID ,
                a.ETypeID ,
                a.DTypeID ,
                a.STypeID ,
                a.Audited
        HAVING  SUM(a.CostTotal) <> 0
    END

--改总账（减掉之前的，加上改后的即可）
SELECT  @NewTotal = SUM(Total)
FROM    ListTable a
        INNER JOIN ( SELECT DISTINCT
                            BillNumberID
                     FROM   #AfterModifyBill
                   ) b ON a.BillNumberId = b.BillNumberID
WHERE   AtypeId = @STOCKID
--billtype =141
SELECT  @NewTotal_DX = ISNULL(SUM(Total), 0)
FROM    ListTable a
        INNER JOIN ( SELECT DISTINCT
                            BillNumberID
                     FROM   #AfterModifyBill
                   ) b ON a.BillNumberId = b.BillNumberID
                          AND A.BillType = 141
WHERE   AtypeId = @WTDXSP_ID

SELECT  @NewTotal = ISNULL(@NewTotal, 0)

DECLARE @DiffTotal NUMERIC(24, 10) ,
    @DiffTotal_DX NUMERIC(24, 10) = 0

SELECT  @DiffTotal = ISNULL(-@OldTotal, 0) + ISNULL(@NewTotal, 0) ,
        @DiffTotal_DX = ISNULL(-@OldTotal_DX, 0) + ISNULL(@NewTotal_DX, 0)

IF @DiffTotal <> 0 
    BEGIN
        IF EXISTS ( SELECT  ATypeID
                    FROM    AType_Total
                    WHERE   STypeID = @chvSTypeID
                            AND ATypeID = @STOCKID
                            AND CID = @sysID ) 
            BEGIN
                UPDATE  AType_Total
                SET     Total = Total + @DiffTotal ,
                        Ntotal = Ntotal + @DiffTotal
                WHERE   STypeID = @chvSTypeID
                        AND ATypeID = @STOCKID
                        AND CID = @sysID
            END
        ELSE 
            BEGIN
                INSERT  AType_Total
                        ( ATypeID ,
                          STypeID ,
                          Total ,
                          CID ,
                          Ntotal
                        )
                        SELECT  @STOCKID ,
                                @chvSTypeID ,
                                @DiffTotal ,
                                @sysID ,
                                @DiffTotal
            END
    END
IF @DiffTotal_DX <> 0 
    BEGIN
        IF EXISTS ( SELECT  ATypeID
                    FROM    AType_Total
                    WHERE   STypeID = @chvSTypeID
                            AND ATypeID = @WTDXSP_ID
                            AND CID = @sysID ) 
            BEGIN
                UPDATE  AType_Total
                SET     Total = Total + @DiffTotal ,
                        Ntotal = Ntotal + @DiffTotal
                WHERE   STypeID = @chvSTypeID
                        AND ATypeID = @WTDXSP_ID
                        AND CID = @sysID
            END
        ELSE 
            BEGIN
                INSERT  AType_Total
                        ( ATypeID ,
                          STypeID ,
                          Total ,
                          CID ,
                          Ntotal
                        )
                        SELECT  @WTDXSP_ID ,
                                @chvSTypeID ,
                                @DiffTotal ,
                                @sysID ,
                                @DiffTotal
            END
    END 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_Cost_ReOtherTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_Cost_ReOtherTotal]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

处理跟库存科目对应的其他科目，要分单来处理


*/
CREATE   PROCEDURE GP_Cost_ReOtherTotal
    (
      @strSTypeID VARCHAR(50)
    )
--@encode$--
AS --对应的科目也是这样处理（不同的单据有不同的科目）
--对应的科目主要有主营业务成本等其他科目（针对不同的单据来处理）

--会影响到的单据从#AfterModifyBill中取

--要改变ListTable和总值，最好一类类单据来处理

CREATE TABLE #ListTable
    (
      BillNumberID			NUMERIC(24, 10) ,
      STypeID				VARCHAR(50) ,
      ATypeID				VARCHAR(50) ,
      OldValue				NUMERIC(24, 10) ,
      NewValue				NUMERIC(24, 10) ,
      CostSale				INT DEFAULT 0 ,
      BillType				INT ,
      BTypeID				VARCHAR(50) ,
      CID					INT
    )
        
DECLARE @intBillType INT ,
        @strATypeID VARCHAR(50)= ''
	
DECLARE BillType_CURSOR CURSOR
FOR
    SELECT DISTINCT
            BillType
    FROM    #AfterModifyBill
    WHERE   BillType <> 17			---同价调拨单不需要处理科目

OPEN BillType_CURSOR
FETCH NEXT FROM BillType_CURSOR INTO @intBillType

WHILE @@FETCH_STATUS = 0 
    BEGIN
        EXEC Gp_OutBill_GetOtherAType @intBillType, @strATypeID OUT	


        IF @strATypeID <> ''
            OR @intBillType = 202 
            BEGIN
                EXEC Gp_OutBill_DealOtherAType @intBillType, @strATypeID,
                    @strSTypeID
            END



        FETCH NEXT FROM BillType_CURSOR INTO @intBillType
    END

CLOSE BillType_CURSOR
DEALLOCATE BillType_CURSOR


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
/*
*		成本计算本期业务期间出库类，退货类，换货类凭证生成检查
*		0为不存在生成凭证的****单据，-1为存在生成凭证的****单据

--修改:冯波    2017-02-09   排除非成本类凭证的校验
----零售单,零售退货单,销售出库单,销售退货单,销售换货单,赠送单,委托代销发货单,委托代销退货单,委托代销结算单,组合品销售出库单,组合品销售退货单,发出商品出库单,发出商品退货单,销售发货开票  需要判断ISCOST<>0;其他直接卡死
*/
IF EXISTS(SELECT TOP 1 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_CostComputeCheck',N'P'))
BEGIN
	DROP PROC GP_CostComputeCheck
END
GO

CREATE PROC GP_CostComputeCheck
(
	@STypeID		VARCHAR(MAX),
	@PTypeID		VARCHAR(MAX),
	@StartDate		VARCHAR(100),
	@OperatorID		VARCHAR(100)	
)
AS
BEGIN 
	DECLARE @SType TABLE(STypeID VARCHAR(100))
	DECLARE @PType TABLE(PTypeID VARCHAR(100))
	
	DECLARE @DateMonthProc DATETIME
	SELECT @DateMonthProc=StartDate FROM dbo.MonthProc WHERE MonthNo='本期' AND STypeID=@STypeID
	
	IF @StartDate>@DateMonthProc
	BEGIN
		SET @DateMonthProc=@StartDate
	END
	--EXEC GP_Cost_Re_GetInfo	@PTypeID,
	--						@STypeID,
	--						0,
	--						0,
	--						@StartDate OUT,
	--						0
	IF @STypeID=''
		INSERT INTO @SType SELECT TypeID AS STypeID FROM dbo.F_GetManSType(@OperatorID) WHERE soncount=0 AND deleted=0
	ELSE 
		INSERT INTO @SType SELECT STypeID AS STypeID FROM (
			SELECT A.TypeID AS STypeID FROM SType A INNER JOIN (SELECT A AS STypeID FROM dbo.F_Split(@StypeID,N',')) B
                                     ON A.TypeID Like B.STypeID+'%'
                                     INNER JOIN 
                                     (SELECT TypeID AS STypeID FROM dbo.F_GetManSType(@OperatorID)) C
                                     ON A.TypeID=C.STypeID
                                     WHERE A.soncount=0
                                     AND A.deleted=0
		) A
	
	IF @PTypeID=''
		INSERT INTO @PType SELECT TypeID FROM dbo.PType WHERE sonnum=0 AND deleted=0 AND IsService=0 AND iscombinationproduct=0
	ELSE
		INSERT INTO @PType SELECT PTypeID FROM(
			SELECT TypeID AS PTypeID FROM PType A INNER JOIN (SELECT A AS PTypeID FROM  dbo.f_split(@PTypeID,',')
			)B ON A.TypeID LIKE B.PTypeID+'%' 
			WHERE A.soncount=0 AND A.deleted=0
		)B

	--本业务期间内存在已生成会计凭证的出库类单据、或销售发货开票、采购/销售/退换货、
	--委托/受托代销退货、发出商品退货单据，请检查删除会计凭证后，再执行成本计算操作！
	--同价调拨单
	IF EXISTS(SELECT TOP 1 1 FROM MoveBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--变价调拨单
	IF EXISTS(SELECT TOP 1 1 FROM movebjbill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			   
			  
			  )
		RETURN -1
	
	--分支机构调拨出库单
	IF EXISTS(SELECT TOP 1 1 FROM stypemovebill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND B.BillType=187
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
	
	--其他出库单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.OtherInOutBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND B.BillType=202
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
		
	
		
	--报损单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.LoseBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND B.BillType=9
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
	
	--积分兑换
	IF EXISTS(SELECT TOP 1 1 FROM dbo.integralexchangebill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
		
	--维修品调出
	IF EXISTS(SELECT TOP 1 1 FROM dbo.wx_bill_out A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
		
		
	--维修品调入
	IF EXISTS(SELECT TOP 1 1 FROM dbo.wx_bill_in A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
	
	--维修品调拨单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.wx_Bill_Move A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
	
	--采购退货单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BuyBackBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
		
	--获赠单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.GivemeBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
		
	--赠送单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.GiveBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--销售出库单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
		
	--组合品销售出库单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBillDetail A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
		
	--零售单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.retailBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--销售退货单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.saleBackBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
		
	--组合销售退货单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBackBillDetail A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
		
	--零售退货单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.retailBackBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--销售换货
	IF EXISTS(SELECT TOP 1 1 FROM dbo.salegoodsexchangebill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  --AND A.InOrOut='O'
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--采购换货
	IF EXISTS(SELECT TOP 1 1 FROM dbo.buygoodsexchangebill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  --AND A.InOrOut='O'
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			 
			  )
		RETURN -1
		
	--生产拆装
	IF EXISTS(SELECT TOP 1 1 FROM dbo.DisassembleBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  --AND A.InOrOut='O'
			  AND b.BillDate>=@DateMonthProc
			  AND C.VourchBillId<>-1
			  
			  )
		RETURN -1
	
	--受托代销退货
	IF EXISTS(SELECT TOP 1 1 FROM dbo.commissionbill A INNER JOIN dbo.BillIndex B 
		  ON A.BillNumberId=B.BillNumberId 
		  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
		  ON C.GoodsBillId=B.BillNumberId
		  WHERE B.posttime>=@DateMonthProc
		  AND B.RedWord=0
		  AND B.IsIni=0
		  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
		  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
		  AND BillType IN(146)
		  AND b.BillDate>=@DateMonthProc
		  AND c.VourchBillId<>-1
		  
		  )
	RETURN -1
	
	--委托代销退货
	IF EXISTS(SELECT TOP 1 1 FROM dbo.commissionbill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND BillType IN(142)
			  AND b.BillDate>=@DateMonthProc
			  AND c.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--委托代销出库
	IF EXISTS(SELECT TOP 1 1 FROM dbo.commissionbill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND BillType IN(140)
			  AND b.BillDate>=@DateMonthProc
			  AND c.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--委托代销结算
	IF EXISTS(SELECT TOP 1 1 FROM dbo.commissionbill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND BillType IN(141)
			  AND b.BillDate>=@DateMonthProc
			  AND c.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	/*
	--受托代销结算？
	IF EXISTS(SELECT TOP 1 1 FROM dbo.commissionbill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND BillType IN(145)
			  AND b.BillDate>=@DateMonthProc
			  AND c.VourchBillId<>-1
			  )
		RETURN -1
	*/
	
	--发出商品出库
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SendBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND c.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--发出商品退货
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SendBackBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND c.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
	
	--暂估退货
	IF EXISTS(SELECT TOP 1 1 FROM dbo.AppraisalBackBill A INNER JOIN dbo.BillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_GoodsBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND b.BillDate>=@DateMonthProc
			  AND c.VourchBillId<>-1
			 
			  )
		RETURN -1
	
	--发出商品开票
	IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B 
			  ON A.BillNumberId=B.BillNumberId 
			  INNER JOIN dbo.Ac_ReceiptBill_VoucherBill C 
			  ON C.GoodsBillId=B.BillNumberId
			  WHERE B.posttime>=@DateMonthProc
			  AND B.RedWord=0
			  AND B.IsIni=0
			  AND B.Stypeid IN (SELECT Stypeid FROM @SType)
			  AND A.PtypeId IN(SELECT PtypeId FROM @PType)
			  AND B.BillType=405
			  AND b.BillDate>=@DateMonthProc
			  AND c.VourchBillId<>-1
			  AND c.IsCost<>0
			  )
		RETURN -1
		
		
	
	--启用了按单据日期进行成本计算时跳过逻辑【单据日期在本期而过账日期在之前期间的单据，请删除上月月结记录】的校验
	IF NOT EXISTS(
			SELECT 1 FROM dbo.Userconfig WHERE ConfigName ='countcostbybilldate' AND Value='1')
	BEGIN  
		--单据日期在本期，而过账日期在本期之前
		IF EXISTS ( SELECT  1
					FROM    dbo.InOutstocktable A
							INNER JOIN @SType B ON A.STypeID = B.STypeID
							INNER JOIN @PType C ON A.PtypeId = C.PTypeID
					WHERE   BillDate >= @DateMonthProc
							AND a.Audited=1
							AND posttime < @DateMonthProc)

							
			RETURN -2
			
		IF EXISTS ( SELECT  1
					FROM    dbo.CostRe_Bill A
							INNER JOIN @SType B ON A.STypeID = B.STypeID
							INNER JOIN @PType C ON A.PtypeId = C.PTypeID
							INNER JOIN 
							(
								SELECT BillNumberID,BillType 
								FROM dbo.BillIndex
								WHERE ifcheck='t' AND RedWord=0
								UNION ALL
								SELECT BillNumberID,BillType 
								FROM dbo.ReceiptBillIndex
								WHERE ifcheck='t' AND RedWord=0
							) d
							ON a.BillNumberId=d.BillNumberId AND a.BillType=d.BillType
					WHERE   BillDate >= @DateMonthProc
							AND posttime < @DateMonthProc)
			RETURN -2
	END
	
	RETURN 0
END
GO






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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理成本价调拨的分支机构调拨入库单的成本
	返回结果：
	作    者：zyq
	创建时间：2019-11-13
	
*/
CREATE	PROCEDURE GP_CostDealStypeMoveBill
(
	@nBillID				NUMERIC(10,0),
	@nFromBillID			NUMERIC(10,0),
	@nid                    NUMERIC(10,0),
	@fromid                 NUMERIC(10,0)

	
)
--@encode$--
AS

DECLARE @strTemp	VARCHAR(MAX)

SELECT @strTemp='
			--先把应收加回去,不然内部应收报表有问题
			update SType_InnerARTotal set  InnerARTotal+=a.Total
				from  (select sum(total) as Total,stypeid from stypemovebill  where BillNumberId = '+CAST(@nBillID AS VARCHAR(50)) +' 
				AND BillType = 188 GROUP BY Stypeid )a                                             
				WHERE  a.STypeID=SType_InnerARTotal.STypeID  and SType_InnerARTotal.stypeid2 =(select top(1) stypeid 
			from stypemovebill  where BillNumberId = '+CAST(@nFromBillID AS VARCHAR(50)) +' AND BillType = 187)     

			update stypemovebill 
				set	Price = ISNULL(a.Price,0) ,
					Total = ISNULL(a.Total,0) ,
					GoodsCostPrice=ISNULL(a.GoodsCostPrice,0),
					GoodsCostTotal=ISNULL(a.GoodsCostTotal,0),
					MPrice=a.MUnitRate *ISNULL(a.GoodsCostPrice,0)
					from  (select * from stypemovebill  where BillNumberId ='+CAST(@nFromBillID AS VARCHAR(50)) +' AND BillType = 187 and id='+CAST(@fromid AS VARCHAR(50)) +')a
					WHERE  stypemovebill.BillNumberId = '+CAST(@nBillID AS VARCHAR(50)) +'
					AND stypemovebill.BillType=188
					and stypemovebill.ptypeid=a.ptypeid and  stypemovebill.id='+CAST(@nid AS VARCHAR(50)) +'		


			IF  EXISTS(   SELECT  Value FROM  Userconfig  WHERE  ConfigName = ''allowtbbillcostprice'' AND Value=0 )
			BEGIN
				UPDATE InOutstocktable SET
					Price = ISNULL(b.CostPrice,0) ,
					Total = ISNULL(b.CostTotal,0)
					FROM  (select it.ptypeid,it.costprice,it.costtotal from
					InOutstocktable  it
					INNER JOIN billindex bx on it.billnumberid=it.billnumberid and it.billtype=bx.billtype
					where it.BillNumberId ='+CAST(@nFromBillID AS VARCHAR(50)) +' AND it.BillType = 187 and bx.CostSale=1 )b 
					WHERE  InOutstocktable.BillNumberId ='+CAST(@nBillID AS VARCHAR(50)) +'
					AND InOutstocktable.BillType=187
					and InOutstocktable.ptypeid=b.ptypeid
			END
			          

			UPDATE InOutstocktable SET
				CostTotal = -ISNULL(b.CostTotal,0) ,
				CostPrice = ISNULL(b.CostPrice,0) ,
				Price = ISNULL(b.Price,0) ,
				Total = -ISNULL(b.Total,0),
				SalePrice = ISNULL(b.SalePrice,0),
				SaleTotal = -ISNULL(b.SaleTotal,0) ,
				TaxPrice = ISNULL(b.TaxPrice,0) ,
				TaxTotal = -ISNULL(b.TaxTotal,0) ,
				NPrice = ISNULL(b.NPrice,0),
				NTotal = -ISNULL(b.NTotal,0) ,
				NSalePrice =ISNULL(b.NSalePrice,0) ,
				NSaleTotal = -ISNULL(b.NSaleTotal,0) ,
				NTaxPrice =ISNULL(b.NTaxPrice,0) ,
				NTaxTotal = -ISNULL(b.NTaxTotal,0)
				FROM  (select * from
				InOutstocktable  where BillNumberId ='+CAST(@nFromBillID AS VARCHAR(50)) +' AND BillType = 187 and id='+CAST(@fromid AS VARCHAR(50)) +')b 
				WHERE  InOutstocktable.BillNumberId ='+CAST(@nBillID AS VARCHAR(50)) +'
				AND InOutstocktable.BillType=188 and InOutstocktable.id='+CAST(@nid AS VARCHAR(50)) +'																
				and InOutstocktable.ptypeid=b.ptypeid 
					 




			UPDATE BillIndex  SET 
				TotalMoney=ISNULL(b.TotalMoney,0),
				NTotalMoney=ISNULL(b.NTotalMoney,0)
				FROM (select * from BillIndex where BillNumberId='+CAST(@nFromBillID AS VARCHAR(50)) +' AND BillType = 187 and CostSale=1)b
				WHERE  BillIndex.BillNumberID='+CAST(@nBillID AS VARCHAR(50)) +'
				AND   BillIndex.BillType=188
			   

			update   listtable  SET     
				 Total = -ISNULL(b.Total,0) ,
				 Ntotal = -ISNULL( b.Ntotal,0)                                                                 
				 from (select Total as Total,Ntotal as Ntotal ,atypeid from listtable where BillNumberId='+CAST(@nFromBillID AS VARCHAR(50)) +' AND BillType = 187) b
				 where listtable.BillNumberID='+CAST(@nBillID AS VARCHAR(50)) +' and listtable.billtype=188 and listtable.atypeid=b.atypeid

			update AType_Total  set
			   Total =  AType_Total.Total+ISNULL(b.Total,0) ,
			   Ntotal =AType_Total.Ntotal+ISNULL( b.Ntotal,0)		                                                       
			   from  (select Total ,Ntotal  ,atypeid,stypeid from listtable where BillNumberId='+CAST(@nBillID AS VARCHAR(50)) +' AND BillType = 188) b

			--然后再把内部应收减了                                                            
			update SType_InnerARTotal set  InnerARTotal-=a.Total
				  from  (select sum(total) as Total ,STypeID from stypemovebill  where BillNumberId = '+CAST(@nBillID AS VARCHAR(50)) +' AND 
				  BillType = 188 GROUP BY Stypeid )a                                             
				WHERE  a.STypeID=SType_InnerARTotal.STypeID  and SType_InnerARTotal.stypeid2 =(select top(1) stypeid  from stypemovebill  
				where BillNumberId = '+CAST(@nFromBillID AS VARCHAR(50)) +' AND BillType = 187)  

			     
			update GOODSSTOCKS set  price = a.price
			from  (select * from stypemovebill  where BillNumberId = '+CAST(@nBillID AS VARCHAR(50)) +' AND BillType = 188 )a   
			WHERE  a.PtypeId=GOODSSTOCKS.PtypeId AND a.Ktypeid2= GOODSSTOCKS.KtypeId 


			update GOODSSTOCKS set  Total = GOODSSTOCKS.price * GOODSSTOCKS.qty
			from  (select * from stypemovebill  where BillNumberId = '+CAST(@nBillID AS VARCHAR(50)) +' AND BillType = 188 )a   
			WHERE  a.PtypeId=GOODSSTOCKS.PtypeId AND a.Ktypeid2= GOODSSTOCKS.KtypeId 
			                                        
			UPDATE  #AllAfterBill
			SET     CostTotal =- b.CostTotal ,
			CostPrice = b.CostPrice
			FROM  (select * from
					  InOutstocktable  where BillNumberId ='+CAST(@nFromBillID AS VARCHAR(50)) +' AND BillType = 187 and id='+CAST(@fromid AS VARCHAR(50)) +')b 
					  WHERE  #AllAfterBill.BillNumberId ='+CAST(@nBillID AS VARCHAR(50)) +'
					  AND #AllAfterBill.BillType=188																	
					 and #AllAfterBill.ptypeid=b.ptypeid    
					 and #AllAfterBill.BillID='+CAST(@nid AS VARCHAR(50)) +'
											                                                                         
			'
			
--PRINT @strTemp

EXEC(@strTemp)		
		
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_CostingTypeChange]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_CostingTypeChange]
GO


-- by hanlin
--成本算法改变要改变库存

CREATE     PROCEDURE Gp_CostingTypeChange
(
  @costing INT=0
)
--@encode$--
AS 
SET NOCOUNT ON 

DECLARE @oldcosting INT=0
SELECT @oldcosting=subvalue FROM dbo.sysdata WHERE SubName='costing'

--更新Ini_GOODSSTOCKS_QTY与gp_initPtypeSerial的关联；在系统配置前序列号可能没有建立货位、自由项等关联信息，修改系统配置的时候需要将对于的关联信息（ID）补上
UPDATE dbo.gp_initPtypeSerial SET ID=s.ID
	FROM dbo.Ini_GOODSSTOCKS_QTY s
	WHERE	s.PtypeId=gp_initPtypeSerial.PTypeID AND s.KtypeId=gp_initPtypeSerial.KTypeID AND s.CargoID=gp_initPtypeSerial.CargoID 
			AND s.ItemID=gp_initPtypeSerial.ItemID AND s.Iscombined=gp_initPtypeSerial.IsCombined AND s.GoodsNumber=gp_initPtypeSerial.GoodsNumber
			AND s.ProduceDate=gp_initPtypeSerial.ProduceDate AND s.ValidDate=gp_initPtypeSerial.ValidDate AND s.GoodsCostPrice=gp_initPtypeSerial.CostPrice
			
IF @costing=@oldcosting OR @costing IN (1,2) AND @oldcosting IN (1,2)
RETURN


DECLARE @pricenum INT=4,
		@totalNum INT=2,
		@qtyNum	  INT=4
		
SELECT @pricenum=DecimalDigit   from  DigitConfiguration  WHERE ItemName='price'

SELECT @totalNum=DecimalDigit   from  DigitConfiguration  WHERE ItemName='total'
SELECT @qtyNum=DecimalDigit   from  DigitConfiguration  WHERE ItemName='qty'		

IF @costing=0 --其他成本算法到移动加权算法
BEGIN
	--生产日期、效期至
	DECLARE @IfUseValidDate VARCHAR(10),
			@IfUserProceDate VARCHAR(10)
	SELECT @IfUseValidDate=Value FROM dbo.Userconfig WHERE ConfigName='IfUseValidDate'
	SELECT @IfUserProceDate=Value FROM dbo.Userconfig WHERE ConfigName='ifuseproducedate'
	
	SELECT	  PtypeId ,
			  KtypeId ,
			  ''AS JobNumber ,
			  MAX(OutFactoryDate) AS OutFactoryDate ,
			  SUM(Qty) AS Qty,
			  ROUND( CAST(SUM(total) AS NUMERIC(24,10))/CAST(SUM(Qty) AS NUMERIC(24,10)),@pricenum) as Price ,
			  SUM(Total) AS total,
			  0 AS GoodsOrder,
			  '' AS GoodsNumber ,
			  '' AS ProduceDate ,
			  '' AS ValidDate ,
			  '' AS GoodsBTypeID
	INTO #IniGoodsStocks          
	FROM IniGoodsStocks 
	GROUP BY  PtypeId ,
			  KtypeId
	DELETE FROM dbo.IniGoodsStocks
	

	INSERT INTO dbo.IniGoodsStocks
	( 
			PtypeId ,
			KtypeId ,
			JobNumber ,
			OutFactoryDate ,
			Qty ,
			Price ,
			Total ,
			GoodsOrder ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsBTypeID
	)
	SELECT	PtypeId ,
			KtypeId ,
			JobNumber ,
			OutFactoryDate ,
			Qty ,
			Price ,
			Total ,
			GoodsOrder ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsBTypeID
	FROM #IniGoodsStocks
	DROP TABLE #IniGoodsStocks
	
		SELECT
				row_number() over (order by PTypeID ,
				  KTypeID ,
				  CargoID ,
				  ItemID ,
				  Iscombined ,
				  GoodsNumber ,
				  ProduceDate,
				  ValidDate,
				  LockNumber) as ID,
				PTypeID ,
				KTypeID ,
				CargoID ,
				ItemID ,
				Iscombined ,
				GoodsNumber ,
				CASE WHEN @IfUserProceDate='1' THEN ProduceDate ELSE '' END AS ProduceDate ,
				CASE WHEN @IfUseValidDate='1' THEN ValidDate ELSE '' END AS ValidDate ,
				SUM(Qty) AS qty,
				SUM(NQty) AS Nqty,
				0 AS GOODSCOSTPRICE,
				SUM(LockNumber) AS LockNumber
		INTO	#GOODSSTOCKS_QTY
		FROM dbo.ini_GOODSSTOCKS_QTY
		GROUP BY PTypeID ,
				  KTypeID ,
				  CargoID ,
				  ItemID ,
				  Iscombined ,
				  GoodsNumber ,
				  ProduceDate,
				  ValidDate,
				  LockNumber
				  
		DELETE FROM dbo.Ini_GOODSSTOCKS_QTY
		 set identity_insert Ini_GOODSSTOCKS_QTY ON--打开
		INSERT INTO dbo.Ini_GOODSSTOCKS_QTY
		(       id,
				PTypeID ,
				KTypeID ,
				CargoID ,
				ItemID ,
				Iscombined ,
				GoodsNumber ,
				ProduceDate ,
				ValidDate ,
				Qty ,
				NQty ,
				GoodsCostPrice,
				LockNumber
		)
		SELECT  id,PTypeID ,
				KTypeID ,
				CargoID ,
				ItemID ,
				Iscombined ,
				GoodsNumber ,
				ProduceDate ,
				ValidDate ,
				Qty ,
				NQty ,
				GoodsCostPrice,
				LockNumber
		FROM #GOODSSTOCKS_QTY
		set identity_insert Ini_GOODSSTOCKS_QTY OFF--关闭
		DROP TABLE #GOODSSTOCKS_QTY
		
		--删除生产日期、有效期后合并IniCommissionStock_Qty
	SELECT 	Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined ,
			GoodsNumber,
			SUM(Qty) AS Qty ,
			SUM(NQty) as NQty
			,DealType
			,KTypeID
			,CargoID
			,SerialType,
			CASE WHEN @IfUserProceDate='1' THEN ProduceDate ELSE '' END AS ProduceDate ,
			CASE WHEN @IfUseValidDate='1' THEN ValidDate ELSE '' END AS ValidDate 
	INTO #IniCommissionStock_Qty1
	FROM dbo.IniCommissionStock_Qty
	GROUP BY Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined,
			GoodsNumber
			,DealType
			,KTypeID
			,CargoID
			,SerialType
			,ProduceDate
			,ValidDate
	DELETE FROM dbo.IniCommissionStock_Qty
	INSERT INTO dbo.IniCommissionStock_Qty
    ( 
			Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined ,
			GoodsNumber,
			Qty ,
			NQty
			,DealType
			,KTypeID
			,CargoID
			,SerialType
			,ProduceDate
			,ValidDate
    )
	SELECT 	Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined ,
			GoodsNumber,
			Qty ,
			NQty
			,DealType
			,KTypeID
			,CargoID
			,SerialType
			,ProduceDate
			,ValidDate
	FROM #IniCommissionStock_Qty1
	DROP TABLE #IniCommissionStock_Qty1
	
	--9.6BUG ID：3806 切换算法后，现在合并了主表，导致ID变了，现在明细表gp_initPtypeSerial没处理合并，等测试确认这是否有问题。
	--将生产日期、有效期、成本价置为初始值
	
	UPDATE gp_initPtypeSerial SET ProduceDate=CASE WHEN @IfUserProceDate='1' THEN ProduceDate ELSE '' END,ValidDate=CASE WHEN @IfUseValidDate='1' THEN ValidDate ELSE '' END,CostPrice=0
	--*********************************************************************************************************--
END
ELSE IF @costing IN (1,2)	--其他成本算法到先进先出或者后进先出
BEGIN
	--创建具有goodsNumber字段的表名临时表
	CREATE TABLE #goodsTb(tbName VARCHAR(50))
	INSERT INTO #goodsTb
	SELECT s.name 
	FROM sysobjects s 
	INNER JOIN syscolumns c ON s.id = c.id AND c.name = 'GoodsNumber' AND s.type = 'u'
	WHERE s.name NOT IN('GuestBackIndex','LendIndex','billindex','Offline_BillIndex','OrderIndex')--这几个表中的goodsnumber不是批号
	
	DECLARE @SQL VARCHAR(max)=''
	SELECT  @SQL+='update '+tbName+' set goodsnumber='''' ' FROM #goodsTb
	EXEC(@sql)
	DROP TABLE #goodsTb
	
	SELECT	RANK() OVER
			(PARTITION BY PtypeId,KtypeId ORDER BY Price) AS GoodsOrder, 
			PtypeId ,
			KtypeId ,
			''AS JobNumber ,
			MAX(OutFactoryDate) AS OutFactoryDate ,
			SUM(Qty) AS Qty,
			Price ,
			ROUND(CAST(SUM(Qty) AS NUMERIC(24,10))* Price,@totalNum) AS total,
			'' AS GoodsNumber ,
			'' AS ProduceDate ,
			'' AS ValidDate ,
			'' AS GoodsBTypeID
	INTO #IniGoodsStocks2          
	FROM IniGoodsStocks 
	GROUP BY  PtypeId ,
			  KtypeId ,
			  Price	   
	DELETE FROM dbo.IniGoodsStocks
	INSERT INTO dbo.IniGoodsStocks
	( 
			PtypeId ,
			KtypeId ,
			JobNumber ,
			OutFactoryDate ,
			Qty ,
			Price ,
			Total ,
			GoodsOrder ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsBTypeID
	)
	SELECT	PtypeId ,
			KtypeId ,
			JobNumber ,
			OutFactoryDate ,
			Qty ,
			Price ,
			Total ,
			GoodsOrder ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsBTypeID
	FROM #IniGoodsStocks2
	DROP TABLE #IniGoodsStocks2
		
	SELECT	id,
			PTypeID ,
			KTypeID ,
			CargoID ,
			ItemID ,
			Iscombined ,
			'' GoodsNumber ,
			'' AS ProduceDate ,
			'' AS ValidDate ,
			SUM(Qty) AS qty,
			SUM(NQty) AS Nqty,
			0 AS GOODSCOSTPRICE,
			SUM(LockNumber) AS LockNumber
	INTO	#GOODSSTOCKS_QTY2
	FROM dbo.ini_GOODSSTOCKS_QTY
	GROUP BY  id,
			  PTypeID ,
			  KTypeID ,
			  CargoID ,
			  ItemID ,
			  Iscombined,
			  LockNumber
			  
	DELETE FROM dbo.Ini_GOODSSTOCKS_QTY
	SET IDENTITY_INSERT Ini_GOODSSTOCKS_QTY ON--打开
	INSERT INTO dbo.Ini_GOODSSTOCKS_QTY
	( 
			id,
			PTypeID ,
			KTypeID ,
			CargoID ,
			ItemID ,
			Iscombined ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			Qty ,
			NQty ,
			GoodsCostPrice,
			LockNumber
	)
	SELECT  id,
			PTypeID ,
			KTypeID ,
			CargoID ,
			ItemID ,
			Iscombined ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			Qty ,
			NQty ,
			GoodsCostPrice,
			LockNumber
	FROM #GOODSSTOCKS_QTY2
	SET IDENTITY_INSERT Ini_GOODSSTOCKS_QTY OFF--关闭
	DROP TABLE #GOODSSTOCKS_QTY2
	
	--删除批号后合并IniGoodsLend
	SELECT 	BtypeId ,
			PtypeId ,
			KtypeId ,
			MAX(OutFactoryDate) AS OutFactoryDate,
			SUM(Qty)AS Qty ,
			ItemID ,
			Iscombined ,
			SUM(Nqty) AS Nqty ,
			SUM(LendQty) AS LendQty ,
			SUM(NLendQty) AS NLendQty ,
			SUM(BorrowQty) AS BorrowQty ,
			SUM(NBorrowQty) AS NBorrowQty
	INTO	#IniGoodsLend
	FROM	dbo.IniGoodsLend
	GROUP BY BtypeId ,
			PtypeId ,
			KtypeId ,
			ItemID ,
			Iscombined
	DELETE FROM dbo.IniGoodsLend
	INSERT INTO dbo.IniGoodsLend
	( 
			BtypeId ,
			PtypeId ,
			KtypeId ,
			OutFactoryDate ,
			Qty ,
			ItemID ,
			Iscombined ,
			Nqty ,
			LendQty ,
			NLendQty ,
			BorrowQty ,
			NBorrowQty
	 )
	 SELECT	BtypeId ,
			PtypeId ,
			KtypeId ,
			OutFactoryDate ,
			Qty ,
			ItemID ,
			Iscombined ,
			Nqty ,
			LendQty ,
			NLendQty ,
			BorrowQty ,
			NBorrowQty
	FROM #IniGoodsLend
	DROP TABLE #IniGoodsLend
	
	--删除批号后合并wx_IniGoodsStocks
	SELECT 	PtypeId ,
			KtypeId ,
			MAX(OutFactoryDate) AS OutFactoryDate,
			SUM(Qty)AS Qty ,
			ItemID ,
			Iscombined ,
			SUM(Nqty) AS Nqty 
	INTO	#wx_IniGoodsStocks
	FROM	dbo.wx_IniGoodsStocks
	GROUP BY PtypeId ,
			KtypeId ,
			ItemID ,
			Iscombined
	DELETE FROM dbo.wx_IniGoodsStocks
	INSERT INTO wx_IniGoodsStocks
	(
			PtypeId ,
			KtypeId ,
			OutFactoryDate ,
			Qty ,
			ItemID ,
			Iscombined ,
			Nqty 
	)
	SELECT 	PtypeId ,
			KtypeId ,
			OutFactoryDate ,
			Qty ,
			ItemID ,
			Iscombined ,
			Nqty
	FROM #wx_IniGoodsStocks
	DROP TABLE #wx_IniGoodsStocks
	
	--删除批号后合并IniCommissionStock_Qty
	SELECT 	Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined ,
			SUM(Qty) AS Qty ,
			SUM(NQty) as NQty
			,DealType
			,KTypeID
			,CargoID
			,SerialType
	INTO #IniCommissionStock_Qty
	FROM dbo.IniCommissionStock_Qty
	GROUP BY Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined
			,DealType
			,KTypeID
			,CargoID
			,SerialType
	DELETE FROM dbo.IniCommissionStock_Qty
	INSERT INTO dbo.IniCommissionStock_Qty
    ( 
			Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined ,
			Qty ,
			NQty
			,DealType
			,KTypeID
			,CargoID
			,SerialType
    )
	SELECT 	Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined ,
			Qty ,
			NQty
			,DealType
			,KTypeID
			,CargoID
			,SerialType
	FROM #IniCommissionStock_Qty
	DROP TABLE #IniCommissionStock_Qty
	
	--将生产日期、有效期、成本价置为初始值
	UPDATE gp_initPtypeSerial SET GoodsNumber='',CostPrice=0
END
ELSE IF @costing=3 --其他到手工指定.
BEGIN
	SELECT	  PtypeId ,
			  KtypeId ,
			  MAX(OutFactoryDate) AS OutFactoryDate ,
			  CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND( CAST(SUM(total) AS NUMERIC(24,10))/CAST(SUM(Qty) AS NUMERIC(24,10)),@priceNum) END as Price
	INTO #IniGoodsStocks1          
	FROM IniGoodsStocks 
	GROUP BY  PtypeId ,
			  KtypeId
	
	DELETE FROM dbo.IniGoodsStocks
	SELECT * FROM #IniGoodsStocks1
	INSERT INTO dbo.IniGoodsStocks
	( 
			GoodsOrder ,
			PtypeId ,
			KtypeId ,
			JobNumber ,
			OutFactoryDate ,
			Qty ,
			Price ,
			Total ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsBTypeID
	)
	SELECT	RANK() OVER
			(PARTITION BY q.ptypeid,q.KtypeId ORDER BY GoodsNumber) AS GoodsOrder, 
			q.PtypeId ,
			q.KtypeId ,
			'' AS JobNumber ,
			MAX(OutFactoryDate),
			SUM(q.Qty) AS qty ,
			Price ,
			ROUND(CAST(SUM(q.Qty) AS NUMERIC(24,10))* Price,@totalNum) AS Total ,
			GoodsNumber ,
			'' ,
			'' ,
			''
	FROM #IniGoodsStocks1 s
	INNER JOIN dbo.Ini_GOODSSTOCKS_QTY q ON s.KtypeId=q.KTypeID AND s.PtypeId=q.PTypeID
	GROUP BY  q.PtypeId ,
		  q.KtypeId,
		  s.Price,
		  q.GoodsNumber 
		  
	DROP TABLE #IniGoodsStocks1
	UPDATE dbo.Ini_GOODSSTOCKS_QTY SET GoodsCostPrice=s.Price
	FROM dbo.IniGoodsStocks s
	WHERE	s.PtypeId=Ini_GOODSSTOCKS_QTY.PTypeID 
			AND s.KtypeId=Ini_GOODSSTOCKS_QTY.KTypeID
	
	--更新成本单价信息
	UPDATE dbo.gp_initPtypeSerial SET CostPrice=s.Price
	FROM dbo.IniGoodsStocks s
	WHERE	s.PtypeId=gp_initPtypeSerial.PTypeID 
			AND s.KtypeId=gp_initPtypeSerial.KTypeID
	--更新期初代销库存状况数量核算表单价信息
	UPDATE dbo.IniCommissionStock_Qty SET GoodsCostPrice=s.Price
	FROM dbo.IniGoodsStocks s
	WHERE	s.PtypeId=IniCommissionStock_Qty.PTypeID 
			AND s.KtypeId=IniCommissionStock_Qty.KTypeID
			
END   
 
------重算期初库存状况数量核算表
--EXEC QP_Recount_IniGoodsStocksQty

--重算草稿库存的
EXEC QP_Recount_DraftQty

--BUG2160 切换成本需要重新调用订单库存重算
EXEC QP_Recount_OrderQty

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






/****** Object:  StoredProcedure [dbo].[Gp_CostRe_BatchCost]    Script Date: 08/04/2018 15:14:59 ******/
IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[Gp_CostRe_BatchCost]')
                    AND type IN ( N'P', N'PC' ) ) 
    DROP PROCEDURE [dbo].[Gp_CostRe_BatchCost]
GO

GO

/****** Object:  StoredProcedure [dbo].[Gp_CostRe_BatchCost]    Script Date: 08/04/2018 15:14:59 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*

作者：冯波

对于所影响的单据，批量修改成本

*/
CREATE   PROCEDURE [dbo].[Gp_CostRe_BatchCost]
(
      @decInputCostPrice NUMERIC(24, 10) ,
      @strInputPTypeID VARCHAR(50) ,			--需要录入成本的商品
      @strInputSTypeID VARCHAR(50) ,			--过滤分支机构，肯定有值，这个是分支机构叶子节点
      @strInputKTypeID VARCHAR(50) ,			--需要录入成本的仓库
      @datPostTime DATETIME ,
	  @datDealBeginDate DATETIME ,
      @nBillType INT ,					--最早修改或红冲的单据类型
      @nRet INT OUT ,
      @strOutputPTypeID VARCHAR(50) OUT ,		--返回需要录入成本的商品
      @strOutputKTypeID VARCHAR(50) OUT ,		--返回需要录入成本的仓库
      @oldOutBillCost NUMERIC(24, 10) OUT ,		--返回需要录入成本的单据的原成本
      @strErrMsg VARCHAR(500) = '' OUT
)
--@encode$--
AS /*

需要处理的是：
1，销售退货单，采购退货单参照成本
2，分支机构间调拨等
3，取不到成本价时，返回-100，提示录入成本

需要注意的是:
现在要按照INOUTSTOCKTABLE的SortID来更新成本,这个无索引,会很慢,要调整,这个调整成按BILLNUMBERID和ID来修改即可

*/

--统一时间
SET @datPostTime = CONVERT(VARCHAR(10), @datPostTime, 120)

DECLARE @intQtyDot INT ,
		@intPriceDot INT ,
		@intMoneyDot INT ,
		@intDiscountDot INT ,
		@intTaxDot INT ,
		@intCRateDot INT ,
		@intTRateDot INT	

EXEC GP_Post_Dot @intQtyDot OUT, @intPriceDot OUT, @intMoneyDot OUT,
    @intDiscountDot OUT, @intTaxDot OUT, @intCRateDot OUT,
    @intTRateDot OUT

SELECT  @nRet = 0 ,
        @strErrMsg = ''

DECLARE @nAllowNegativeStock INT ,
		@DateMonthProc DATETIME

SELECT  @DateMonthProc = StartDate
FROM    dbo.MonthProc
WHERE   MonthNo = '本期' AND stypeid = @strInputSTypeID 

-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', '', @nAllowNegativeStock OUTPUT

DECLARE	@intCostSaleAdjust INT ,		--成本价销售，调拨不参与成本计算，1表示勾选了不参与，0表示不勾选要参与
		@intDisassemble INT ,			--生产拆装单不参与成本计算，1表示勾选了不参与，0表示不勾选要参与
		@intStypeinandstypeout INT ,    --分支机构调拨入库单成本与分支机构调拨出库单商品相关联 1表示勾选了成本关联,0表示成本不关联
		@intCostDelivery INT			--按成本价配送的单据不参与成本计算
	        
SELECT  @intCostSaleAdjust = Value
FROM    Userconfig WHERE   ConfigName = 'allowtbbillcostprice'

SELECT  @intDisassemble = Value
FROM    Userconfig WHERE   ConfigName = 'allowczbillcostprice'

DECLARE @intcostpricesaleback INT ,	--0表示不参照销售成本，1表示参照销售成本
		@intcostpricebuyback INT	--0表示不参照采购成本，1表示参照采购成本

SELECT  @intcostpricesaleback = Value
FROM    Userconfig WHERE   ConfigName = 'costpricesaleback'

SELECT  @intcostpricebuyback = Value
FROM    Userconfig WHERE   ConfigName = 'costpricebuyback'

SELECT  @intStypeinandstypeout = Value
FROM    Userconfig WHERE   ConfigName = 'stypeinandstypeout'

DECLARE @intCountcostbybilldate INT   --根据单据日期来计算成本

SELECT  @intCountcostbybilldate = Value
FROM    Userconfig WHERE   ConfigName = 'countcostbybilldate'

SELECT  @intCostDelivery = Value
FROM    dbo.Userconfig WHERE   ConfigName = 'costdeliverycancalbill'


DECLARE @intCID INT ,
        @intCostSale INT

IF NOT EXISTS (SELECT  BillNumberID FROM  #AfterModifyBill ) 
BEGIN
    SELECT  @nRet = -200
    RETURN
END

--#AfterBill这个表示需要修改成本的单据（应该包含单据ID，PTypeID,KTypeID）
--确定期初数据（包含采购费用分摊单）
CREATE TABLE #IniData
(
	  PTypeID	VARCHAR(50) ,
	  KTypeID	VARCHAR(50) ,
	  Qty		NUMERIC(24, 10) ,
	  CostPrice NUMERIC(24, 10) ,
	  CostTotal NUMERIC(24, 10) ,
	  BeginSort INT DEFAULT 0
)
--SELECT '11  stockinfo',* FROM #StockInfo
--SELECT '@nBillType=',@nBillType,'@datPostTime=',@datPostTime,'@intCountcostbybilldate=',@intCountcostbybilldate

--是否按单据日期进行成本计算 0.否 1.是
IF @intCountcostbybilldate = 0 
BEGIN
	IF @nBillType IN ( 34, 144, 201, 400, 188 )  --入库类单据，则期初需要包括该单据
	BEGIN
		INSERT  #IniData (PTypeID,KTypeID,Qty,CostPrice,CostTotal)
        SELECT  a.PtypeId ,
                a.KtypeId ,
                SUM(a.Qty) ,
                CASE SUM(a.Qty) WHEN 0 THEN 0
                ELSE ROUND(CAST(SUM(a.CostTotal) AS NUMERIC(24,10)) / CAST(SUM(a.Qty) AS NUMERIC(24,10)),@intPriceDot) END ,
                SUM(a.CostTotal)
        FROM    ( SELECT	DISTINCT
                            a.BillNumberID ,
                            a.ID ,
                            a.PtypeId ,
                            a.KtypeId ,
                            CASE WHEN a.BillType = 57 AND c.AdPriceType <> 0 THEN 0 ELSE a.Qty END Qty ,
                            a.CostTotal
                  FROM      InOutstocktable a ,
                            #StockInfo b ,
                            billindex c
                  WHERE     a.PtypeId = b.PTypeID
                            AND a.KtypeId = b.KTypeID
                            AND a.BillNumberId = c.BillNumberId
                            AND a.BillType = c.BillType			
					--AND ( (a.BillType<>57 AND a.PostTime<=@datPostTime) OR (a.BillType=57 AND a.PostTime<@datPostTime))  
					--以前这里是用的<,如果采购了，销售，去改采购，销售的成本不变，所以这里改成等于了，需要测试
                            AND (( a.BillType <> 57 AND a.PostTime < @datPostTime )
                                  OR (a.BillType = 57 AND a.PostTime < @datPostTime ) ) 
                                  --以前这里是用的<,如果采购了，销售，去改采购，销售的成本不变，所以这里改成等于了，需要测试
                            AND a.Audited = 1
                  UNION ALL
                  SELECT    0 ,
                            0 ,
                            a.PtypeId ,
                            a.KtypeId ,
                            a.Qty ,
                            a.Total
                  FROM      IniGoodsStocks a ,
                            #StockInfo b
                  WHERE     a.PtypeId = b.PTypeID
                            AND a.KtypeId = b.KTypeID
                  UNION ALL
                  SELECT    0 ,
                            0 ,
                            a.PtypeId ,
                            '10000' ,
                            a.Qty ,
                            a.CostTotal
                  FROM      IniCommissionStock a ,
                            #StockInfo b
                  WHERE     a.PtypeId = b.PTypeID
                            AND b.KTypeID = '10000'
                ) a
        GROUP BY a.PtypeId ,
                a.KtypeId
	END
    ELSE 
		BEGIN	
			INSERT  #IniData(PTypeID,KTypeID,Qty,CostPrice,CostTotal)
            SELECT  a.PtypeId ,
                    a.KtypeId ,
                    SUM(a.Qty) ,
                    CASE SUM(a.Qty) WHEN 0 THEN 0
                    ELSE ROUND(CAST(SUM(a.CostTotal) AS NUMERIC(24,10))/ CAST(SUM(a.Qty) AS NUMERIC(24,10)),@intPriceDot) END ,
                    SUM(a.CostTotal)
            FROM    ( SELECT	DISTINCT
                                a.BillNumberID ,
                                a.ID ,
                                a.PtypeId ,
                                a.KtypeId ,
                                CASE WHEN a.BillType = 57 AND c.AdPriceType <> 0 THEN 0  ELSE a.Qty END Qty ,
                                a.CostTotal
                      FROM      InOutstocktable a ,
                                #StockInfo b ,
                                billindex c
                      WHERE     a.PtypeId = b.PTypeID
                                AND a.KtypeId = b.KTypeID
                                AND a.BillNumberId = c.BillNumberId
                                AND a.BillType = c.BillType		
						--AND a.PostTime<@datPostTime  
                                AND a.PostTime < @datPostTime
                                AND a.Audited = 1
                      UNION ALL
                      SELECT    0 ,
                                0 ,
                                a.PtypeId ,
                                a.KtypeId ,
                                a.Qty ,
                                a.Total
                      FROM      IniGoodsStocks a ,
                                #StockInfo b
                      WHERE     a.PtypeId = b.PTypeID
                                AND a.KtypeId = b.KTypeID
                      UNION ALL
                      SELECT    0 ,
                                0 ,
                                a.PtypeId ,
                                '10000' ,
                                a.Qty ,
                                a.CostTotal
                      FROM      IniCommissionStock a ,
                                #StockInfo b
                      WHERE     a.PtypeId = b.PTypeID
                                AND b.KTypeID = '10000'
                    ) a
            GROUP BY a.PtypeId ,
                    a.KtypeId
		END
    END 
ELSE 
    BEGIN
        IF @nBillType IN ( 34, 144, 201, 400, 188 )  --入库类单据，则期初需要包括该单据
		BEGIN			
			INSERT  #IniData(PTypeID,KTypeID,Qty,CostPrice,CostTotal)
			SELECT  a.PtypeId ,
					a.KtypeId ,
					SUM(a.Qty) ,
					CASE SUM(a.Qty) WHEN 0 THEN 0
					ELSE ROUND(CAST(SUM(a.CostTotal) AS NUMERIC(24,10)) / CAST(SUM(a.Qty) AS NUMERIC(24,10)),@intPriceDot) END ,
					SUM(a.CostTotal)
			FROM    (SELECT		DISTINCT
								a.BillNumberID ,
								a.ID ,
								a.PtypeId ,
								a.KtypeId ,
								CASE WHEN a.BillType = 57
										  AND c.AdPriceType <> 0
									 THEN 0
									 ELSE a.Qty
								END Qty ,
								a.CostTotal
					  FROM      InOutstocktable a ,
								#StockInfo b ,
								billindex c
					  WHERE     a.PtypeId = b.PTypeID
								AND a.KtypeId = b.KTypeID
								AND a.BillNumberId = c.BillNumberId
								AND a.BillType = c.BillType		
						--AND ((a.BillType<>57 AND ( (a.BillDate<=@datPostTime AND a.billtype =@nBillType) OR (a.BillDate<@datPostTime AND a.billtype <>@nBillType))) OR (a.BillType=57 AND a.BillDate<@datPostTime))  
						--以前这里是用的<,如果采购了，销售，去改采购，销售的成本不变，所以这里改成等于了，需要测试
								AND (
									( a.BillType <> 57 AND (
															( a.BillDate < @datPostTime  AND a.billtype = @nBillType  )
															 OR (a.BillDate < @datPostTime AND a.billtype <> @nBillType ) 
															) 
									)
									  OR (a.BillType = 57 AND a.BillDate < @DateMonthProc)
									)  --以前这里是用的<,如果采购了，销售，去改采购，销售的成本不变，所以这里改成等于了，需要测试			
								AND a.Audited = 1
						--AND NOT EXISTS ( SELECT
						--              BillNumberId
						--              FROM
						--              #AfterModifyBill
						--              WHERE
						--              #AfterModifyBill.billnumberid = a.BillNumberId
						--              OR ( a.billdate = #AfterModifyBill.billdate
						--              AND a.posttime > #AfterModifyBill.posttime
						--              ) )
					  UNION ALL
					  SELECT    0 ,
								0 ,
								a.PtypeId ,
								a.KtypeId ,
								a.Qty ,
								a.Total
					  FROM      IniGoodsStocks a ,
								#StockInfo b
					  WHERE     a.PtypeId = b.PTypeID
								AND a.KtypeId = b.KTypeID
					  UNION ALL
					  SELECT    0 ,
								0 ,
								a.PtypeId ,
								'10000' ,
								a.Qty ,
								a.CostTotal
					  FROM      IniCommissionStock a ,
								#StockInfo b
					  WHERE     a.PtypeId = b.PTypeID
								AND b.KTypeID = '10000'
					) a
			GROUP BY a.PtypeId ,
					a.KtypeId
		END
        ELSE 
        BEGIN
			INSERT  #IniData (PTypeID,KTypeID,Qty,CostPrice,CostTotal)
            SELECT  a.PtypeId ,
                    a.KtypeId ,
                    SUM(a.Qty) ,
                    CASE SUM(a.Qty) WHEN 0 THEN 0
                    ELSE ROUND(CAST(SUM(a.CostTotal) AS NUMERIC(24,10))/ CAST(SUM(a.Qty) AS NUMERIC(24,10)),@intPriceDot) END ,
                    SUM(a.CostTotal)
            FROM    ( SELECT	DISTINCT
                                a.BillNumberID ,
                                a.ID ,
                                a.PtypeId ,
                                a.KtypeId ,
                                CASE WHEN a.BillType = 57
                                          AND c.AdPriceType <> 0
                                     THEN 0
                                     ELSE a.Qty
                                END Qty ,
                                a.CostTotal
                      FROM      InOutstocktable a ,
                                #StockInfo b ,
                                billindex c
                      WHERE     a.PtypeId = b.PTypeID
                                AND a.KtypeId = b.KTypeID
                                AND a.BillNumberId = c.BillNumberId
                                AND a.BillType = c.BillType		
						--AND a.BillDate<@datPostTime  
                                AND a.BillDate < @datPostTime
                                AND NOT EXISTS ( SELECT BillNumberId
												 FROM  #AfterModifyBill WHERE #AfterModifyBill.billnumberid = a.BillNumberId
													OR ( a.billdate = #AfterModifyBill.billdate AND a.posttime > #AfterModifyBill.posttime ) )
                                AND a.Audited = 1
                      UNION ALL
                      SELECT    0 ,
                                0 ,
                                a.PtypeId ,
                                a.KtypeId ,
                                a.Qty ,
                                a.Total
                      FROM      IniGoodsStocks a ,
                                #StockInfo b
                      WHERE     a.PtypeId = b.PTypeID
                                AND a.KtypeId = b.KTypeID
                      UNION ALL
                      SELECT    0 ,
                                0 ,
                                a.PtypeId ,
                                '10000' ,
                                a.Qty ,
                                a.CostTotal
                      FROM      IniCommissionStock a ,
                                #StockInfo b
                      WHERE     a.PtypeId = b.PTypeID
                                AND b.KTypeID = '10000'
                    ) a
            GROUP BY a.PtypeId ,
                    a.KtypeId
	END
END
--SELECT '#IniData',*FROM #IniData
--SELECT * FROM  #AfterModifyBill

CREATE CLUSTERED INDEX [IX_IniData] ON [dbo].[#IniData](PTypeID,KTypeID)

--确定后面的物流单据(减少表扫描)
CREATE TABLE #AllAfterBill
(
	  BillNumberID BIGINT ,
	  BillID BIGINT ,
	  BillType INT ,
	  PTypeID VARCHAR(50) ,
	  KTypeID VARCHAR(50) ,
	  Qty NUMERIC(24, 10) ,
	  CostPrice NUMERIC(24, 10) ,
	  CostTotal NUMERIC(24, 10) ,
	  PostTime DATETIME ,
	  BillDate DATETIME ,
	  SortID BIGINT ,
	  NewSortID BIGINT
)

--select '@datPostTime',@datPostTime,'BillType=',@nBillType,'@intCountcostbybilldate=',@intCountcostbybilldate

--考虑给临时表建立索引
IF @intCountcostbybilldate = 0 
BEGIN
	IF @nBillType IN ( 34, 144, 201, 400, 188 ) 
	BEGIN
		--已包含在期初,就不要在后续单据中
        INSERT  #AllAfterBill (BillNumberID,BillID,BillType,PTypeID,KTypeID,Qty,CostPrice,CostTotal,PostTime,BillDate,SortID,NewSortID)
        SELECT  a.BillNumberId ,
                a.ID ,
                a.BillType ,
                a.PtypeId ,
                a.KtypeId ,
                a.Qty ,
                a.CostPrice ,
                a.CostTotal ,
                a.PostTime ,
                a.BillDate ,
                a.SortID ,
                ROW_NUMBER() OVER ( ORDER BY a.PostTime, a.SortID, a.Qty )
        FROM    ( SELECT	DISTINCT
                            a.BillNumberId ,
                            a.ID ,
                            a.BillType ,
                            a.PtypeId ,
                            a.KtypeId ,
                            CASE WHEN a.BillType = 57 AND c.AdPriceType <> 0 THEN 0 ELSE a.Qty END Qty ,
                            a.CostPrice ,
                            a.CostTotal ,
                            a.PostTime ,
                            a.SortID ,
                            a.BillDate
                  FROM      InOutstocktable a ,
                            #StockInfo b ,
                            billindex c
                  WHERE     a.PtypeId = b.PTypeID
                            AND a.KtypeId = b.KTypeID
                            AND a.BillNumberId = c.BillNumberId
                            AND a.BillType = c.BillType
                            AND a.BillDate >= @datDealBeginDate
                            AND a.PostTime >= @datPostTime
                            --AND a.BillDate >= @datPostTime
                            AND a.Audited = 1
                  UNION ALL
                  SELECT DISTINCT
                            a.BillNumberId ,
                            a.ID ,
                            a.BillType ,
                            a.PtypeId ,
                            a.KtypeId ,
                            a.Qty ,
                            a.CostPrice ,
                            a.CostTotal ,
                            a.PostTime ,
                            a.SortID ,
                            a.BillDate
                  FROM      InOutstocktable a ,
                            #StockInfo b ,
                            dbo.PosAllotApplyBillIndex c
                  WHERE     a.PtypeId = b.PTypeID
                            AND a.KtypeId = b.KTypeID
                            AND a.BillNumberId = c.BillNumberId
                            AND a.BillType = c.BillType
                            AND a.BillDate >= @datDealBeginDate
                            AND a.PostTime >= @datPostTime
                            --AND a.BillDate >= @datPostTime
                            AND a.Audited = 1
                           
                ) a
        ORDER BY a.PostTime, a.SortID, a.Qty
        
	END
    ELSE 
    BEGIN
        INSERT  #AllAfterBill(BillNumberID,BillID,BillType,PTypeID,KTypeID,Qty,CostPrice,CostTotal,PostTime,BillDate,SortID,NewSortID)
        SELECT  a.BillNumberId ,
                a.ID ,
                a.BillType ,
                a.PtypeId ,
                a.KtypeId ,
                a.Qty ,
                a.CostPrice ,
                a.CostTotal ,
                a.PostTime ,
                a.BillDate ,
                a.SortID ,
                ROW_NUMBER() OVER ( ORDER BY a.PostTime, a.SortID, a.Qty )
        FROM    ( SELECT	DISTINCT
                            a.BillNumberId ,
                            a.ID ,
                            a.BillType ,
                            a.PtypeId ,
                            a.KtypeId ,
                            CASE WHEN a.BillType = 57 AND c.AdPriceType <> 0 THEN 0 ELSE a.Qty END Qty ,
                            a.CostPrice ,
                            a.CostTotal ,
                            a.PostTime ,
                            a.SortID ,
                            a.BillDate
                  FROM      InOutstocktable a ,
                            #StockInfo b ,
                            billindex c
                  WHERE     a.PtypeId = b.PTypeID
                            AND a.KtypeId = b.KTypeID
                            AND a.BillNumberId = c.BillNumberId
                            AND a.BillType = c.BillType
                            AND a.BillDate >= @datDealBeginDate
                            --AND a.PostTime >= @datPostTime
                            AND a.PostTime >= @datPostTime
                            AND a.Audited = 1
                  UNION ALL
                  SELECT DISTINCT
                            a.BillNumberId ,
                            a.ID ,
                            a.BillType ,
                            a.PtypeId ,
                            a.KtypeId ,
                            a.Qty ,
                            a.CostPrice ,
                            a.CostTotal ,
                            a.PostTime ,
                            a.SortID ,
                            a.BillDate
                  FROM      InOutstocktable a ,
                            #StockInfo b ,
                            dbo.PosAllotApplyBillIndex c
                  WHERE     a.PtypeId = b.PTypeID
                            AND a.KtypeId = b.KTypeID
                            AND a.BillNumberId = c.BillNumberId
                            AND a.BillType = c.BillType
                             AND a.BillDate >= @datDealBeginDate
                            AND a.PostTime >= @datPostTime
                            --AND a.BillDate >= @datPostTime
                            AND a.Audited = 1
                          
                ) a
        ORDER BY a.PostTime ,
                a.SortID ,
                a.Qty
    END
END
ELSE 
BEGIN
	IF @nBillType IN ( 34, 144, 201, 400, 188 ) 
	BEGIN
		--已包含在期初,就不要在后续单据中
		INSERT  #AllAfterBill (BillNumberID,BillID ,BillType ,PTypeID ,KTypeID ,Qty ,CostPrice ,CostTotal ,PostTime ,BillDate ,SortID ,NewSortID)
				SELECT  a.BillNumberId ,
						a.ID ,
						a.BillType ,
						a.PtypeId ,
						a.KtypeId ,
						a.Qty ,
						a.CostPrice ,
						a.CostTotal ,
						a.PostTime ,
						a.BillDate ,
						a.SortID ,
						ROW_NUMBER() OVER ( ORDER BY a.BillDate, a.PostTime, a.SortID, a.Qty )
				FROM    ( SELECT	DISTINCT
									a.BillNumberId ,
									a.ID ,
									a.BillType ,
									a.PtypeId ,
									a.KtypeId ,
									a.Qty ,
									a.CostPrice ,
									a.CostTotal ,
									a.PostTime ,
									a.SortID ,
									a.BillDate
						  FROM      InOutstocktable a ,
									#StockInfo b ,
									billindex c
						  WHERE     a.PtypeId = b.PTypeID
									AND a.KtypeId = b.KTypeID
									AND a.BillNumberId = c.BillNumberId
									AND a.BillType = c.BillType
								    AND a.BillDate >= @datDealBeginDate
									AND ( ( a.BillDate >= @datPostTime AND a.BillType = @nBillType )
										  OR (a.BillDate >= @datPostTime AND a.BillType <> @nBillType )
										)
									--AND a.BillDate>@datPostTime
									AND a.Audited = 1
						  UNION ALL
						  SELECT DISTINCT
									a.BillNumberId ,
									a.ID ,
									a.BillType ,
									a.PtypeId ,
									a.KtypeId ,
									a.Qty ,
									a.CostPrice ,
									a.CostTotal ,
									a.PostTime ,
									a.SortID ,
									a.BillDate
						  FROM      InOutstocktable a ,
									#StockInfo b ,
									dbo.PosAllotApplyBillIndex c
						  WHERE     a.PtypeId = b.PTypeID
									AND a.KtypeId = b.KTypeID
									AND a.BillNumberId = c.BillNumberId
									AND a.BillType = c.BillType
								   AND a.BillDate >= @datDealBeginDate
									AND ( ( a.BillDate >= @datPostTime AND a.BillType = @nBillType )
										  OR ( a.BillDate >= @datPostTime AND a.BillType <> @nBillType )
										)
									--AND a.BillDate>@datPostTime
									AND a.Audited = 1
	                                
						) a
				ORDER BY a.BillDate ,
						a.PostTime ,
						a.SortID ,
						a.Qty
	END
    ELSE 
        BEGIN
			/*
			SELECT '查询',a.BillNumberId,a.ID,a.BillType,a.PtypeId,a.KtypeId,a.Qty,a.CostPrice,a.CostTotal,a.PostTime,a.BillDate,a.SortID,
			ROW_NUMBER() OVER(ORDER BY a.BillDate,a.PostTime,a.SortID,a.Qty)
			FROM
			(
				SELECT DISTINCT a.BillNumberId,a.ID,a.BillType,a.PtypeId,a.KtypeId,a.Qty,a.CostPrice,a.CostTotal,a.PostTime,a.SortID,a.BillDate
				FROM InOutstocktable a,
				#StockInfo b
				WHERE a.PtypeId=b.PTypeID			
				AND a.KtypeId=b.KTypeID
				AND a.BillDate>=@DateMonthProc	
				AND a.BillDate>=@datPostTime
				AND a.Audited=1
			) a
			ORDER BY a.BillDate,a.PostTime,a.SortID,a.Qty
			*/	

            INSERT  #AllAfterBill
                    ( BillNumberID ,
                      BillID ,
                      BillType ,
                      PTypeID ,
                      KTypeID ,
                      Qty ,
                      CostPrice ,
                      CostTotal ,
                      PostTime ,
                      BillDate ,
                      SortID ,
                      NewSortID
                    )
                    SELECT  a.BillNumberId ,
                            a.ID ,
                            a.BillType ,
                            a.PtypeId ,
                            a.KtypeId ,
                            a.Qty ,
                            a.CostPrice ,
                            a.CostTotal ,
                            a.PostTime ,
                            a.BillDate ,
                            a.SortID ,
                            ROW_NUMBER() OVER ( ORDER BY a.BillDate, a.PostTime, a.SortID, a.Qty )
                    FROM    ( SELECT DISTINCT
                                        a.BillNumberId ,
                                        a.ID ,
                                        a.BillType ,
                                        a.PtypeId ,
                                        a.KtypeId ,
                                        a.qty ,
                                        a.CostPrice ,
                                        a.CostTotal ,
                                        a.PostTime ,
                                        a.SortID ,
                                        a.BillDate
                              FROM      InOutstocktable a ,
                                        #StockInfo b ,
                                        billindex c
                              WHERE     a.PtypeId = b.PTypeID
                                        AND a.KtypeId = b.KTypeID
                                        AND a.BillNumberId = c.BillNumberId
                                        AND a.BillType = c.BillType
                                        AND a.BillDate >= @datDealBeginDate
                                        AND a.BillDate >= @datPostTime
                                        AND a.Audited = 1
                              UNION ALL
                              SELECT DISTINCT
                                        a.BillNumberId ,
                                        a.ID ,
                                        a.BillType ,
                                        a.PtypeId ,
                                        a.KtypeId ,
                                        a.Qty ,
                                        a.CostPrice ,
                                        a.CostTotal ,
                                        a.PostTime ,
                                        a.SortID ,
                                        a.BillDate
                              FROM      InOutstocktable a ,
                                        #StockInfo b ,
                                        dbo.PosAllotApplyBillIndex c
                              WHERE     a.PtypeId = b.PTypeID
                                        AND a.KtypeId = b.KTypeID
                                        AND a.BillNumberId = c.BillNumberId
                                        AND a.BillType = c.BillType
                                        AND a.BillDate >= @datDealBeginDate
                                        AND a.BillDate >= @datPostTime
                                        AND a.Audited = 1
                                      
                            ) a
                    ORDER BY a.BillDate ,
                            a.PostTime ,
                            a.SortID ,
                            a.Qty
        END

END	

--暂估生成的成本调价单的数量设置为0，免得虚增数量
IF EXISTS ( SELECT  BillNumberID FROM   #AllAfterBill  WHERE   BillType = 57 
					AND BillNumberID IN (SELECT  BillNumberID FROM   Billindex WHERE  BillType = 57 AND AdPriceType <> 0 ) ) 
BEGIN
    UPDATE  #AllAfterBill
    SET     Qty = 0
    WHERE   BillType = 57
            AND BillNumberID IN ( SELECT    BillNumberID
                                  FROM      Billindex
                                  WHERE     BillType = 57
                                            AND AdPriceType <> 0 )
END


--SELECT '#AllAfterBill',* FROM #AllAfterBill ORDER BY NewSortID

/*

SELECT '#StockInfo',* FROM #StockInfo
*/

--根据历史库存，来计算出库时所取的成本价
--处理InOutStockTable

CREATE NONCLUSTERED INDEX [IX_AllAfterBill_PKS] ON [dbo].[#AllAfterBill](PTypeID,KTypeID,SortID)
CREATE NONCLUSTERED INDEX [IX_AllAfterBill_PKNS] ON [dbo].[#AllAfterBill](PTypeID,KTypeID,NewSortID)
CREATE NONCLUSTERED INDEX [IX_AllAfterBill_SortID] ON [dbo].[#AllAfterBill](SortID)


--循环修改(两重循环)
DECLARE @decIniQty NUMERIC(24, 10) ,
		@decIniCostTotal NUMERIC(24, 10) ,
		@decNewQty NUMERIC(24, 10) ,
		@decNewCostTotal NUMERIC(24, 10) ,
		@decQty NUMERIC(24, 10) ,
		@decTotal NUMERIC(24, 10) ,
		@decCostPrice NUMERIC(24, 10) ,
		@decCurQty NUMERIC(24, 10) ,		--主要用于出库时，计算当前出库数量，金额
		@decCurCostTotal NUMERIC(24, 10) 
	

CREATE TABLE #SumTotal
(
  Qty NUMERIC(24, 10) ,
  Total NUMERIC(24, 10)
)

--假设#StockInfo表示所影响到的库存，#AfterModifyBill表示所影响到的单据
DECLARE @strPTypeID VARCHAR(50) ,
		@strKTypeID VARCHAR(50) ,
		@strSTypeID VARCHAR(50) ,
		@m BIGINT ,			--开始
		@n BIGINT ,			--截止
		@intSortID BIGINT ,
		@intTempBillType INT ,
		@strTempBillCode VARCHAR(200) ,
		@strKFullName VARCHAR(50) ,
		@strPFullName VARCHAR(50) ,
		@strPUserCode VARCHAR(50) ,
		@intGoOn BIT ,
		@chvOtherKTypeID VARCHAR(50) ,
		@datOtherPostTime DATETIME ,
		@i INT ,			--记录调试步骤
		@intAdpriceBillID INT ,
		@intTempBillNumberID BIGINT ,
		@intTempBillID BIGINT ,
		@intTempOldBillNumberID BIGINT ,			--关联单据的主ID
		@intTempOldID BIGINT ,						--关联单据的明细ID
		@intChangeAllStock INT ,					--成本调价单是否调价全部仓库
		@strBTypeID VARCHAR(50) ,
		@datTempPostTime DATETIME ,
		@oldBillCost NUMERIC(24, 10) ,				--需要录入成本的单据的原成本
		@intTempFromBillNumberID BIGINT,
		@Billid BIGINT,
		@fromid BIGINT
		
--记录有调价全部仓库的成本调价单  #table_ChangeAllStock
CREATE TABLE #table_ChangeAllStock ( BillNumberID BIGINT )

--记录有成本价销售的销售出库单(查下有没成本价退货的销售出库单)	#table_CostSaleBill
CREATE TABLE #table_CostSaleBill ( BillNumberID BIGINT )

--记录有成本价销售的发出商品出库单  #table_CostSendBill
CREATE TABLE #table_CostSendBill ( BillNumberID BIGINT )

--记录用成本价调拨出库的分支机构调拨入库单  #table_CostStypeMoveBill
CREATE TABLE #table_CostStypeMoveBill
(
  BillNumberID BIGINT ,
  FromBillNumberID BIGINT
)

--记录用成本价配送的门店配送单  #table_CostStypeMoveBill
CREATE TABLE #table_CostDeliverBill ( BillNumberID BIGINT )	
SELECT  @intGoOn = 0 ,
        @i = 0

--处理成本价的分支机构调拨入库单
--#table_CostStypeMoveBill       
                                                 
IF @intStypeinandstypeout = 1 AND EXISTS(SELECT  BillNumberID FROM  #AllAfterBill WHERE   BillType IN ( 188))
BEGIN
	
-- 需要循环处理
DECLARE CostStypeMoveBil_CURSOR CURSOR FOR
		SELECT a.BillNumberID,b.fromBillNumberID  ,a.BillID,id=(SELECT FromBillID FROM stypemovebill WHERE BillNumberId=a.BillNumberID AND id=a.BillID)
		FROM  #AllAfterBill a  
		INNER JOIN BillIndex b ON a.BillNumberID = b.BillNumberID 
	
		where a.BillType=188 and b.CostSale = 1
		
OPEN CostStypeMoveBil_CURSOR
    FETCH NEXT FROM CostStypeMoveBil_CURSOR INTO @intTempBillNumberID, @intTempFromBillNumberID ,@Billid ,@fromid                                                 
	    WHILE @@FETCH_STATUS = 0 
        BEGIN
			EXEC GP_CostDealStypeMoveBill @intTempBillNumberID,@intTempFromBillNumberID,@Billid,@fromid
                
			FETCH NEXT FROM CostStypeMoveBil_CURSOR INTO @intTempBillNumberID,@intTempFromBillNumberID,@Billid ,@fromid  
        END	
        CLOSE CostStypeMoveBil_CURSOR
    DEALLOCATE CostStypeMoveBil_CURSOR
END   


IF @intCountcostbybilldate = 0 
BEGIN
    DECLARE AfterBill_CURSOR CURSOR
    FOR
        SELECT  SortID ,
                BillType ,
                KTypeID ,
                PTypeID ,
                STypeID ,
                BillNumberID ,
                BillID
        FROM    #AfterModifyBill
        WHERE   BILLTYPE NOT IN ( 17 )
                OR ( BillType = 17  AND Qty < 0 )
        ORDER BY PostTime ,
                SortID ,
                Qty
END 
ELSE 
BEGIN
    DECLARE AfterBill_CURSOR CURSOR
    FOR
        SELECT  SortID ,
                BillType ,
                KTypeID ,
                PTypeID ,
                STypeID ,
                BillNumberID ,
                BillID
        FROM    #AfterModifyBill
        WHERE   BILLTYPE NOT IN ( 17 )
                OR ( BillType = 17 AND Qty < 0 )
        ORDER BY BillDate ,
                PostTime ,
                SortID ,
                Qty
END

OPEN AfterBill_CURSOR
FETCH NEXT FROM AfterBill_CURSOR  INTO @intSortID, @intTempBillType, @strKTypeID, @strPTypeID, @strSTypeID, @intTempBillNumberID, @intTempBillID

WHILE @@FETCH_STATUS = 0
AND @intGoOn = 0 
BEGIN
	--先得到期初
    SELECT  @decIniQty = 0 ,
            @decIniCostTotal = 0 ,
            @decNewQty = 0 ,
            @decNewCostTotal = 0 ,
            @m = 0 ,
            @n = 0 ,
            @i = @i + 1

	--请注意,这个期初数据是实际的期初数据吗?那应该只需要计算一次就行
    IF EXISTS ( SELECT  PTypeID
                FROM    #IniData
                WHERE   PtypeId = @strPTypeID
                        AND KtypeId = @strKTypeID ) 
     BEGIN
            SELECT  @decIniQty = Qty ,
                    @decIniCostTotal = CostTotal ,
                    @m = BeginSort
            FROM    #IniData
            WHERE   PtypeId = @strPTypeID
                    AND KtypeId = @strKTypeID

            SELECT  @decIniQty = ISNULL(@decIniQty, 0) ,
                    @decIniCostTotal = ISNULL(@decIniCostTotal, 0) ,
                    @m = ISNULL(@m, 0)
     END
	
	/*	
	SELECT '期初前',*
	FROM #IniData
	WHERE PtypeId=@strPTypeID
	AND KtypeId=@strKTypeID
	
	SELECT '@i=',@i,'KTYPEID=',@strKTypeID,'@decIniQty=',@decIniQty,'@decIniCostTotal=',@decIniCostTotal,'@m=',@m
	*/
	

	--依次修改影响到的出库成本	
    SELECT  @n = NewSortID ,
            @decCurQty = Qty
    FROM    #AllAfterBill
    WHERE   PtypeId = @strPTypeID
            AND KtypeId = @strKTypeID
            AND SortID = @intSortID

    SELECT  @n = ISNULL(@n, 0) ,
            @decCurQty = ISNULL(@decCurQty, 0)
	
	
	
	--SELECT '第',@i,'步','@decCurQty=',@decCurQty	
	
	--select 'newsorid m=',@m,'newsortid n=',@n,* from #AllAfterBill
	--IF @decCurQty<0 OR (@decCurQty>0 AND @intTempBillType NOT IN (34,21,188,201,16,57,174,400,14,141,145,46,143,147,403) )  --发出商品退货单是一定要刷新成本的

	--发出商品退货单是一定要刷新成本的
    IF @decCurQty < 0 OR ( @decCurQty > 0 AND @intTempBillType NOT IN ( 34, 21, 188, 201, 16, 57, 174, 400, 14, 141, 145, 46, 143, 147 ) )  
    BEGIN
       --SELECT @decCurQty,@intTempBillType,@m,@n
        SELECT  @decNewQty = SUM(Qty) ,
                @decNewCostTotal = SUM(CostTotal)
        FROM    #AllAfterBill
        WHERE   PtypeId = @strPTypeID
                AND KtypeId = @strKTypeID
                AND NewSortID > @m
                AND NewSortID < @n
    END
    ELSE 
    BEGIN
        SELECT  @decNewQty = SUM(Qty) ,
                @decNewCostTotal = SUM(CostTotal)
        FROM    #AllAfterBill
        WHERE   PtypeId = @strPTypeID
                AND KtypeId = @strKTypeID
                AND NewSortID > @m
                AND NewSortID <= @n
    END	
    
	-- SELECT @decNewQty,@decNewCostTotal

	--SELECT '@m=',@m,'@n=',@n,* FROM #allafterbill
	--ORDER BY NewSortID


    SELECT  @decNewQty = ISNULL(@decNewQty, 0) ,
            @decNewCostTotal = ISNULL(@decNewCostTotal, 0)


    SELECT  @decQty = @decIniQty + @decNewQty ,
            @decTotal = @decIniCostTotal + @decNewCostTotal
		
	--SELECT @decQty,@decTotal
	--SELECT '期初',@strPTypeID,@strKTypeID,'期初数量=',@decIniQty,'期初金额=',@decIniCostTotal,'allafterbill开始的NEWSORTID='+CAST(@m AS VARCHAR(10)),'allafterbill截止的NEWSORTID，也就是当前单据的NEWSORTID='+CAST(@n AS VARCHAR(10)),'当前单据数量=',@decCurQty,'当前单据的sortid=',@intSortID
	--SELECT 'check',@decIniCostTotal,@decNewCostTotal,@decTotal,@decIniQty,@decNewQty,ROUND(@decQty,@decTotal/@decQty,4)
	
	--select @i,'步','单据类型',@intTempBillType,'单据BILLNUMBERID=',@intTempBillNumberID,'新增数量@decNewQty=',@decNewQty,'新增金额@decNewCostTotal=',@decNewCostTotal,'期初数量@decIniQty=',@decIniQty,'期初金额@decIniCostTotal=',@decIniCostTotal,'结存数量@decQty=',@decqty,'结存金额@decTotal=',@decTotal,'@m=',@m,'@n=',@n
		

    SELECT  @intTempOldID = 0 ,
            @intTempOldBillNumberID = 0
	
    IF @intTempBillType = 160 AND @intcostpricesaleback = 1 
    BEGIN
        SELECT  @intTempOldID = a.OldID ,
                @intTempOldBillNumberID = a.OldBillNumberID
        FROM    salegoodsexchangebill a
                INNER JOIN BillIndex b ON a.BillNumberId = b.BillNumberId
                INNER JOIN BillIndex c ON a.OldBillNumberID = c.BillNumberId
        WHERE   a.BillNumberId = @intTempBillNumberID
                AND a.ID = @intTempBillID
                AND a.InOrOut = 'I'
                AND b.IsIni = 0
                AND c.ifcheck = 't'
    END
    ELSE 
        IF @intTempBillType = 161 AND @intcostpricebuyback = 1 
        BEGIN
            SELECT  @intTempOldID = a.OldID ,
                    @intTempOldBillNumberID = a.OldBillNumberID
            FROM    buygoodsexchangebill a
                    INNER JOIN BillIndex c ON a.OldBillNumberID = c.BillNumberId
            WHERE   a.BillNumberId = @intTempBillNumberID
                    AND a.ID = @intTempBillID
                    AND a.InOrOut = 'O'
                    AND c.ifcheck = 't'


        END
        ELSE 
            IF @intTempBillType = 45 AND @intcostpricesaleback = 1 
            BEGIN
                SELECT  @intTempOldID = a.OldID ,
                        @intTempOldBillNumberID = a.OldBillNumberID
                FROM    saleBackBill a
                        INNER JOIN BillIndex b ON a.BillNumberId = b.BillNumberId
                        INNER JOIN BillIndex c ON a.OldBillNumberID = c.BillNumberId
                WHERE   a.BillNumberId = @intTempBillNumberID
                        AND a.ID = @intTempBillID
                        AND b.IsIni = 0
                        AND c.ifcheck = 't'
            END
            ELSE IF @intTempBillType = 46 AND @intcostpricesaleback = 1 
            BEGIN
                SELECT  @intTempOldID = a.OldID ,
                        @intTempOldBillNumberID = a.OldBillNumberID
                FROM    PT_Combin_SaleBackBillDetail a
                        INNER JOIN BillIndex b ON a.BillNumberId = b.BillNumberId
                        INNER JOIN BillIndex c ON a.OldBillNumberID = c.BillNumberId
                WHERE   a.BillNumberId = @intTempBillNumberID
                        AND a.ID = @intTempBillID
                        AND b.IsIni = 0
                        AND c.ifcheck = 't'
            END
            ELSE IF @intTempBillType = 6 AND @intcostpricebuyback = 1 
			BEGIN
				SELECT  @intTempOldID = a.OldID ,
						@intTempOldBillNumberID = a.OldBillNumberID
				FROM    BuyBackBill a
						INNER JOIN BillIndex c ON a.OldBillNumberID = c.BillNumberId
				WHERE   a.BillNumberId = @intTempBillNumberID
						AND a.ID = @intTempBillID
						AND c.ifcheck = 't'
			END
            ELSE IF @intTempBillType = 403 
            BEGIN
                SELECT  @intTempOldID = a.OldID ,
                        @intTempOldBillNumberID = a.OldBillNumberID
                FROM    SendBackBill a
                        INNER JOIN BillIndex c ON a.OldBillNumberID = c.BillNumberId
                WHERE   a.BillNumberId = @intTempBillNumberID
                        AND a.ID = @intTempBillID
                        AND ( c.ifcheck = 't'
                              OR c.IsIni = 1
                            )
            END
            ELSE IF @intTempBillType = 215 AND @intcostpricesaleback = 1 
            BEGIN
                SELECT  @intTempOldID = a.OldID ,
                        @intTempOldBillNumberID = a.OldBillNumberID
                FROM    RetailBackBill a
                        INNER JOIN BillIndex b ON a.BillNumberId = b.BillNumberId
                        INNER JOIN BillIndex c ON a.OldBillNumberID = c.BillNumberId
                WHERE   a.BillNumberId = @intTempBillNumberID
                        AND a.ID = @intTempBillID
                        AND b.IsIni = 0
                        AND c.ifcheck = 't'
            END
            ELSE IF @intTempBillType = 328 AND @intCostDelivery = 0 
            BEGIN
                SELECT  @intTempOldID = a.DeliveryID 
                    --@intTempOldBillNumberID = a.BillNumberId
                FROM    dbo.DeliveryBackBill a
                        INNER JOIN dbo.PosAllotApplyBillIndex b ON a.BillNumberId = b.BillNumberId
                WHERE   a.BillNumberId = @intTempBillNumberID
                        AND a.ID = @intTempBillID
                        AND b.IsIni = 0
                        AND b.ifcheck = 't'
            END
			ELSE  IF @intTempBillType = 329 AND @intCostDelivery = 0 
            BEGIN
                SELECT  @intTempOldID = a.DeliveryID 
                --@intTempOldBillNumberID = a.BillNumberId
                FROM    dbo.DeliveryCheckBill a
                        INNER JOIN dbo.PosAllotApplyBillIndex b ON a.BillNumberId = b.BillNumberId
                WHERE   a.BillNumberId = @intTempBillNumberID
                        AND a.ID = @intTempBillID
                        AND b.IsIni = 0
                        AND b.ifcheck = 't'
            END
	
	
	--select '当前','当前数量=',@decCurQty,'当前单据类型=',@intTempBillType,'@intTempBillID=',@intTempBillID,
	--'@intTempOldBillNumberID=',@intTempOldBillNumberID,'当前单据编号=',@strTempBillCode,'结存数量=',@decQty,'结存金额=',@decTotal
			
            IF @intcostpricesaleback = 1 AND @intTempBillType = 160  AND ISNULL(@intTempOldID, 0) > 0 
            BEGIN
				--需要参考销售成本的，销售退货是入库
                SELECT  @decCostPrice = ISNULL(CostPrice, 0) ,
                        @decCurCostTotal = ROUND(ISNULL(CostPrice, 0)
                                                 * @decCurQty,
                                                 @intMoneyDot)
                FROM    InoutStockTable  --??注意,如果是参照的期初的销售退货单呢?看下SALEBILL中有无COSTPRICE
                WHERE   BillNumberID = @intTempOldBillNumberID
                        AND ID = @intTempOldID
	
                UPDATE  InOutstocktable
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID  
	
                UPDATE  #AllAfterBill
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID 
	
                SELECT  @decQty = @decQty + @decCurQty ,
                        @decTotal = @decTotal + @decCurCostTotal
                SELECT  @decCurQty = 0 ,
                        @decCurCostTotal = 0
            END
            ELSE IF @intcostpricebuyback = 1 AND @intTempBillType = 161 AND ISNULL(@intTempOldID, 0) > 0 
            BEGIN
				--需要参考采购成本的，采购退货是出库
                SELECT  @decCostPrice = ISNULL(DiscountPrice, 0) ,
                        @decCurCostTotal = ROUND(ISNULL(DiscountPrice,
                                                      0) * @decCurQty,
                                                 @intMoneyDot)
                FROM    BuyBill
                WHERE   BillNumberID = @intTempOldBillNumberID
                        AND ID = @intTempOldID



                UPDATE  InOutstocktable
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID  

                UPDATE  #AllAfterBill
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID 

                SELECT  @decQty = @decQty + @decCurQty ,
                        @decTotal = @decTotal + @decCurCostTotal
                SELECT  @decCurQty = 0 ,
                        @decCurCostTotal = 0

            END
            ELSE IF @intcostpricesaleback = 1 AND @intTempBillType = 45 AND ISNULL(@intTempOldID, 0) > 0 
			BEGIN
				--需要参考销售成本的，销售退货是入库
                SELECT  @decCostPrice = ISNULL(CostPrice, 0) ,
                        @decCurCostTotal = ROUND(ISNULL(CostPrice,
                                                  0) * @decCurQty,
                                                 @intMoneyDot)
                FROM    InoutStockTable  --??注意,如果是参照的期初的销售退货单呢?看下SALEBILL中有无COSTPRICE
                WHERE   BillNumberID = @intTempOldBillNumberID
                        AND ID = @intTempOldID



                UPDATE  InOutstocktable
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID  

                UPDATE  #AllAfterBill
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID 

                SELECT  @decQty = @decQty + @decCurQty ,
                        @decTotal = @decTotal + @decCurCostTotal
                SELECT  @decCurQty = 0 ,
                        @decCurCostTotal = 0

            END
            ELSE  IF @intcostpricesaleback = 1 AND @intTempBillType = 46 AND ISNULL(@intTempOldID, 0) > 0 
            BEGIN
				--需要参考销售成本的，组合品销售退货是入库
                SELECT  @decCostPrice = ISNULL(CostPrice, 0) ,
                        @decCurCostTotal = ROUND(ISNULL(CostPrice,
                                              0) * @decCurQty,
                                              @intMoneyDot)
                FROM    InoutStockTable  --??注意,如果是参照的期初的销售退货单呢?看下SALEBILL中有无COSTPRICE
                WHERE   BillNumberID = @intTempOldBillNumberID
                        AND ID = @intTempOldID



                UPDATE  InOutstocktable
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID  

                UPDATE  #AllAfterBill
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID 

                SELECT  @decQty = @decQty + @decCurQty ,
                        @decTotal = @decTotal
                        + @decCurCostTotal
                SELECT  @decCurQty = 0 ,
                        @decCurCostTotal = 0

            END
            ELSE  IF @intcostpricebuyback = 1 AND @intTempBillType = 6 AND ISNULL(@intTempOldID, 0) > 0 
            BEGIN
				--需要参考采购成本的，采购退货是出库
                SELECT  @decCostPrice = ISNULL(DiscountPrice,
                                          0) ,
                        @decCurCostTotal = ROUND(ISNULL(DiscountPrice,
                                          0) * @decCurQty,
                                          @intMoneyDot)
                FROM    BuyBill
                WHERE   BillNumberID = @intTempOldBillNumberID
                        AND ID = @intTempOldID



                UPDATE  InOutstocktable
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID  

                UPDATE  #AllAfterBill
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID 

                SELECT  @decQty = @decQty + @decCurQty ,
                        @decTotal = @decTotal
                        + @decCurCostTotal
                SELECT  @decCurQty = 0 ,
                        @decCurCostTotal = 0

            END
            ELSE  IF @intTempBillType = 403 AND ISNULL(@intTempOldID, 0) > 0 
            BEGIN
                IF EXISTS ( SELECT  BillNumberID
                            FROM    Billindex
                            WHERE   BillNumberID = @intTempOldBillNumberID
                                    AND IsIni = 1 ) 
                BEGIN
                    SELECT  @decCostPrice = ISNULL(CostPrice,
                                  0) ,
                            @decCurCostTotal = ABS(ROUND(ISNULL(CostPrice,
                                  0) * @decCurQty,
                                  @intMoneyDot))  --发出商品退货是入库，是正的
                    FROM    SendBill
                    WHERE   BillNumberID = @intTempOldBillNumberID
                            AND ID = @intTempOldID
                END
                ELSE 
                BEGIN
                    SELECT  @decCostPrice = ISNULL(CostPrice,
                                  0) ,
                            @decCurCostTotal = ABS(ROUND(ISNULL(CostPrice,
                                  0) * @decCurQty,
                                  @intMoneyDot))  --发出商品退货是入库，是正的
                    FROM    InoutStockTable
                    WHERE   BillNumberID = @intTempOldBillNumberID
                            AND ID = @intTempOldID
                END

                UPDATE  InOutstocktable
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID  

                UPDATE  #AllAfterBill
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID 


                SELECT  @decQty = @decQty + @decCurQty ,
                        @decTotal = @decTotal
                        + @decCurCostTotal
                SELECT  @decCurQty = 0 ,
                        @decCurCostTotal = 0
            END 
            ELSE  IF @intcostpricesaleback = 1  AND @intTempBillType = 215 AND ISNULL(@intTempOldID, 0) > 0 
            BEGIN
				--需要参考零售成本的，零售退货是入库
				SELECT  @decCostPrice = ISNULL(CostPrice,
								  0) ,
						@decCurCostTotal = ROUND(ISNULL(CostPrice,
								  0) * @decCurQty,
								  @intMoneyDot)
				FROM    InoutStockTable
				WHERE   BillNumberID = @intTempOldBillNumberID
						AND ID = @intTempOldID

				UPDATE  InOutstocktable
				SET     CostTotal = @decCurCostTotal ,
						CostPrice = @decCostPrice
				WHERE   SortID = @intSortID  

				UPDATE  #AllAfterBill
				SET     CostTotal = @decCurCostTotal ,
						CostPrice = @decCostPrice
				WHERE   SortID = @intSortID 

				SELECT  @decQty = @decQty
						+ @decCurQty ,
						@decTotal = @decTotal
						+ @decCurCostTotal

				SELECT  @decCurQty = 0 ,
						@decCurCostTotal = 0

			END
			ELSE  IF @intTempBillType = 328 AND @intCostDelivery = 0 AND ISNULL(@intTempOldID, 0) > 0 
            BEGIN
				--门店退货是入库，取门店配送单的成本
                SELECT  @decCostPrice = ISNULL(CostPrice,
                              0) ,
                        @decCurCostTotal = ROUND(ISNULL(CostPrice,
                              0) * @decCurQty,
                              @intMoneyDot)
                FROM    InoutStockTable
                WHERE   ID = @intTempOldID
                        AND BillType = 327



                UPDATE  InOutstocktable
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID  

                UPDATE  #AllAfterBill
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID 

                SELECT  @decQty = @decQty
                        + @decCurQty ,
                        @decTotal = @decTotal
                        + @decCurCostTotal
                SELECT  @decCurQty = 0 ,
                        @decCurCostTotal = 0	
				
            END
            ELSE IF @intTempBillType = 329 AND @intCostDelivery = 0 AND ISNULL(@intTempOldID, 0) > 0 
            BEGIN
				--门店验收是入库，取门店配送单的成本
                SELECT  @decCostPrice = ISNULL(CostPrice,
                          0) ,
                        @decCurCostTotal = ROUND(ISNULL(CostPrice,
                          0) * @decCurQty,
                          @intMoneyDot)
                FROM    InoutStockTable
                WHERE   ID = @intTempOldID
                        AND BillType = 327



                UPDATE  InOutstocktable
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID  

                UPDATE  #AllAfterBill
                SET     CostTotal = @decCurCostTotal ,
                        CostPrice = @decCostPrice
                WHERE   SortID = @intSortID 

                SELECT  @decQty = @decQty
                        + @decCurQty ,
                        @decTotal = @decTotal
                        + @decCurCostTotal
                SELECT  @decCurQty = 0 ,
                        @decCurCostTotal = 0
            END                        
            ELSE IF @intGoOn = 0 AND ( @decCurQty < 0 OR (@decCurQty > 0 AND @intTempBillType NOT IN (34,161,21,188,201,16,57,174,400,14,141,145,143,147)))
            BEGIN
         
				--如果有受托收货单据，这里要放开计算成本
	             
				--如果数量为零，则单价=金额

				--如果当前库存数量为0，又是出库，又没有录入成本，又取不到成本价，则弹框录入成本,这个逻辑还需要测试
				--select 'a1',@intTempBillType,CASE @decQty WHEN 0 THEN 0 ELSE ROUND(@decTotal/@decQty,@intPriceDot) END,@decCurQty,@decqty,@decnewqty,@						decInputCostPrice

				--先计算下当前的成本价,如果为负数也需要取最近进价,没最近进价,则需要弹框录入成本
                SELECT @decCostPrice = CASE @decQty WHEN 0 THEN 0 ELSE ROUND(@decTotal/ @decQty, @intPriceDot) END
			
                IF (@decCurQty < 0 AND @decQty <= 0 AND @decInputCostPrice = -1000)
                    OR (@decInputCostPrice = -1000 AND @intTempBillType IN (141, 142 ))
                    OR ( @decCostPrice <= 0 AND @decInputCostPrice = -1000)
                    OR ( @strKTypeID = '10000' AND @intTempBillType IN (141, 142 )) 
                BEGIN
					IF @intTempBillType IN ( 141, 142 ) 
					BEGIN
						--委托代销退货
						SELECT
						@strBTypeID = BTypeID ,
						@datTempPostTime = PostTime ,
						@oldBillCost = CostPrice
						FROM
						InOutstocktable
						WHERE
						BillNumberId = @intTempBillNumberID
						AND ID = @intTempBillID
				
				
						IF NOT EXISTS ( SELECT PTypeID FROM IniCommissionStock WHERE Ptypeid = @strPTypeID 
										AND Stypeid = @strSTypeID
										AND Btypeid = @strBTypeID
										AND Type = 140
										UNION ALL
										SELECT PTypeID FROM InOutstocktable WHERE Ptypeid = @strPTypeID
										AND Stypeid = @strSTypeID
										AND Btypeid = @strBTypeID
										AND BillType IN (140, 141, 142,143 )
										AND Audited = 1
										AND PostTime <= @datTempPostTime
										AND KTypeID = '10000' ) 
						BEGIN
							SELECT
							@nRet = -100 ,
							@strOutputPTypeID = @strPTypeID ,
							@strOutputKTypeID = @strKTypeID ,
							@oldOutBillCost = @oldBillCost
							RETURN
						END
						ELSE 
						BEGIN
							SELECT @decCostPrice = CASE SUM(QTY) WHEN 0 THEN 0 
							ELSE ROUND(CAST(SUM(CostTotal) AS NUMERIC(22,10))/ CAST(SUM(Qty) AS NUMERIC(22,10)),@intPriceDot) END
							FROM	(SELECT	PTypeID ,
											Qty ,
											CostTotal
									FROM	IniCommissionStock
									WHERE Ptypeid = @strPTypeID AND Stypeid = @strSTypeID
										AND Btypeid = @strBTypeID AND Type = 140
									UNION ALL
									SELECT	PTypeID ,
									CASE WHEN BILLTYPE = 140 THEN -Qty ELSE Qty END AS Qty ,
									CASE WHEN BillType = 140 THEN -Costtotal ELSE CostTotal END AS CostTotal
									FROM InOutstocktable
									WHERE Ptypeid = @strPTypeID AND Stypeid = @strSTypeID
										AND Btypeid = @strBTypeID AND BillType IN (140,141,142) AND Audited = 1 AND Qty < 0 AND PostTime < @datTempPostTime) a
						END
					END
					ELSE 
					BEGIN
						IF ISNULL(DBO.F_GetRecPrice(@strSTypeID, @strPTypeID), 0) = 0 
						BEGIN
							SELECT	@nRet = -100 ,
									@strOutputPTypeID = @strPTypeID ,
									@strOutputKTypeID = @strKTypeID ,
									@oldOutBillCost = @oldBillCost
							RETURN
						END
						ELSE 
						BEGIN
					
							SELECT @decCostPrice = DBO.F_GetRecPrice(@strSTypeID, @strPTypeID)
							
						END
					END
				END
				ELSE  IF @decInputCostPrice <> -1000 AND @strInputPTypeID = @strPTypeID AND ( ISNULL(@decTotal,0) <= 0 OR ISNULL(@decCostPrice,0) <= 0) 
                BEGIN
              
					--SELECT '成本价','@KTypeID=',@strKTypeID,'@decTotal=',@decTotal,'@decCostPrice=',@decCostPrice,'@decQty=',@decQty
					SELECT @decCostPrice = @decInputCostPrice
				END
                ELSE 
				BEGIN
				 
				  --SELECT '成本价2','@KTypeID=',@strKTypeID,'@decTotal=',@decTotal,'@decCostPrice=',@decCostPrice,'@decQty=',@decQty
					SELECT @decCostPrice = CASE @decQty WHEN 0 THEN 0 ELSE ROUND(@decTotal / @decQty, @intPriceDot) END
				END		

	
				IF @intGoOn = 0 
				BEGIN
					SELECT @decCurCostTotal = ROUND(@decCostPrice * @decCurQty, @intMoneyDot)
						
		--SELECT @decCurCostTotal,@decCostPrice,@decCurQty
					--SELECT '本次修改','KTYPEID=',@strKTypeID,'BILLNUMBERID=',@intTempBillNumberID,'SORTID=',@intsortid,'单据类型=',@inttempbilltype,
					--'成本价=',@decCostPrice,'成本金额=',@decCurCostTotal
		
		
					--这里可以把受托代销为10000的行的成本价也改掉，后续就不用专门处理了
					IF @intTempBillType NOT IN (17, 142, 141 ) 
					BEGIN				
						IF @intTempBillType = 187 
						BEGIN
							SELECT @intCostSale = CostSale
							FROM BillIndex WHERE BillNumberId = @intTempBillNumberID
						END
					ELSE 
					BEGIN
						SELECT @intCostSale = 0
					END
					IF @intTempBillType IN (327, 328, 329 ) 
					BEGIN
						SELECT @intCostSale = CostSale
						FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId = @intTempBillNumberID
					END
					ELSE 
					BEGIN
						SELECT @intCostSale = 0
					END
					IF @intCostSale = 0 
					BEGIN
						UPDATE InOutstocktable
							SET CostTotal = @decCurCostTotal ,
								CostPrice = @decCostPrice
							WHERE SortID = @intSortID 
					END  
					ELSE 
					BEGIN
					

						UPDATE InOutstocktable
							SET CostTotal = @decCurCostTotal ,
								CostPrice = @decCostPrice ,
								Price = @decCostPrice ,
								Total = @decCurCostTotal ,
								SalePrice = @decCostPrice ,
								SaleTotal = @decCurCostTotal ,
								TaxPrice = @decCostPrice ,
								TaxTotal = @decCurCostTotal ,
								NPrice = @decCostPrice ,
								NTotal = @decCurCostTotal ,
								NSalePrice = @decCostPrice ,
								NSaleTotal = @decCurCostTotal ,
								NTaxPrice = @decCostPrice ,
								NTaxTotal = -@decCurCostTotal
								WHERE SortID = @intSortID 


					END
				
					IF @intTempBillType = 140 
					BEGIN
						UPDATE #AllAfterBill
							SET CostTotal = CASE #AllAfterBill.KTypeID
												WHEN '10000' THEN -@decCurCostTotal
												ELSE @decCurCostTotal END ,
								CostPrice = @decCostPrice
							WHERE BillNumberID = @intTempBillNumberID AND BillID = @intTempBillID

						UPDATE dbo.InOutstocktable
							SET CostTotal = CASE InOutstocktable.KTypeID
											WHEN '10000' THEN -@decCurCostTotal
											ELSE @decCurCostTotal END ,
								CostPrice = @decCostPrice
						WHERE BillNumberID = @intTempBillNumberID AND ID = @intTempBillID
					END
					ELSE 
					BEGIN
					--SELECT @decCurCostTotal,@decCostPrice,@intSortID

						UPDATE #AllAfterBill
							SET CostTotal = @decCurCostTotal ,
							CostPrice = @decCostPrice
						WHERE SortID = @intSortID 
					END
				END
			
                IF @intTempBillType = 57 
                BEGIN
					--成本调价单的调前单价和调价比率要重写
					SELECT @intChangeAllStock = ChangeAllStock
					FROM AdPriceBill WHERE ID = @intTempBillID

					IF @intChangeAllStock = 0 
					BEGIN
						UPDATE AdPriceBill
							SET BeforePrice = @decCostPrice ,
								Rate = CASE @decCostPrice WHEN 0 THEN 0 ELSE ROUND(CAST(Price AS NUMERIC(22, 10)) / @decCostPrice, @intTRateDot)* 100 END
						WHERE ID = @intTempBillID
					END
                    ELSE 
                    BEGIN
						--先记录下来，后续统一处理，提高性能
						IF NOT EXISTS ( SELECT BillNumberID FROM #table_ChangeAllStock WHERE BillNumberID = @intTempBillNumberID ) 
						BEGIN
							INSERT #table_ChangeAllStock SELECT @intTempBillNumberID
						END
					END
				END


				--对同价调拨单的入库进行单独处理
			
			
				IF ( @intTempBillType IN (17, 142, 141 ) AND @decCurQty < 0) 
				BEGIN
					UPDATE InOutstocktable
						SET CostTotal = CASE WHEN Qty < 0 THEN @decCurCostTotal ELSE -@decCurCostTotal END ,
							CostPrice = @decCostPrice
					WHERE BillNumberId = @intTempBillNumberID AND ID = @intTempBillID AND billtype = @intTempBillType
				
				/*
				SELECT 'INOUTSTOCKTABLE调整后',KTYPEID,QTY,COSTPRICE,COSTTOTAL
				FROM dbo.InOutstocktable
				WHERE BillNumberId=@intTempBillNumberID AND ID=@intTempBillID
				*/
				--#AllAfterBill也要修改
					UPDATE #AllAfterBill
						SET CostTotal = CASE WHEN Qty < 0 THEN @decCurCostTotal ELSE -@decCurCostTotal END ,
							CostPrice = @decCostPrice
					WHERE BillNumberId = @intTempBillNumberID AND BillID = @intTempBillID
				
				END
                ELSE IF @intTempBillType = 144 
				BEGIN
					UPDATE InOutstocktable
						SET CostTotal = @decCurCostTotal ,
							CostPrice = @decCostPrice
					WHERE BillNumberId = @intTempBillNumberID AND ID = @intTempBillID AND KtypeId <> '10000'
				
				
				
					--#AllAfterBill也要修改
					UPDATE #AllAfterBill
						SET CostTotal = CASE WHEN Qty > 0 THEN @decCurCostTotal ELSE -@decCurCostTotal END ,
							CostPrice = @decCostPrice
					WHERE BillNumberId = @intTempBillNumberID AND BillID = @intTempBillID

                 END
			
				IF @intCostSaleAdjust = 0 AND @intTempBillType = 11 
				BEGIN
					--需要重算单据的单价，及后续的往来
					IF EXISTS ( SELECT BillNumberId FROM Billindex WHERE BillNumberId = @intTempBillNumberID AND CostSale = 1 ) 
					BEGIN
						IF NOT EXISTS (SELECT BillNumberID FROM #table_CostSaleBill WHERE BillNumberID = @intTempBillNumberID ) 
						BEGIN
							INSERT #table_CostSaleBill SELECT @intTempBillNumberID
						END
					END
				END
			
				IF @intCostSaleAdjust = 0 AND @intTempBillType = 402 
				BEGIN
					--需要重算单据的单价，及后续的往来
					IF EXISTS ( SELECT BillNumberId FROM Billindex WHERE BillNumberId = @intTempBillNumberID AND CostSale = 1 ) 
					BEGIN
						IF NOT EXISTS ( SELECT BillNumberID FROM #table_CostSendBill WHERE BillNumberID = @intTempBillNumberID ) 
						BEGIN
							INSERT #table_CostSendBill SELECT @intTempBillNumberID
						END
					END
                END                              			
                IF @intCostDelivery = 0 AND @intTempBillType = 327 
				BEGIN
					--需要重算单据的单价，及后续的往来
					IF EXISTS ( SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId = @intTempBillNumberID AND CostSale = 1 ) 
					BEGIN
						IF NOT EXISTS (SELECT BillNumberID FROM #table_CostDeliverBill WHERE BillNumberID = @intTempBillNumberID ) 
						BEGIN
							INSERT #table_CostDeliverBill SELECT @intTempBillNumberID
						END
					END
				END
				
				SELECT @decQty = @decQty + @decCurQty , @decTotal = @decTotal+ @decCurCostTotal
				SELECT @decCurQty = 0 , @decCurCostTotal = 0


		END
                                                    
END	
	
	--修改期初，不处理成本价
	/*	
	SELECT '调整前',*
	FROM #IniData

	SELECT '修改期初',@strPTypeID,@strKTypeID

	*/
	
    IF @intGoOn = 0 
	BEGIN
		IF NOT EXISTS ( SELECT PTypeID FROM  #IniData WHERE   PTypeID = @strPTypeID AND KTypeID = @strKTypeID ) 
		BEGIN
			INSERT  #IniData (PTypeID ,KTypeID ,Qty ,CostTotal ,BeginSort)
			SELECT  @strPTypeID ,@strKTypeID ,@decQty ,@decTotal ,@n
		END
        ELSE 
        BEGIN
            UPDATE  #IniData
            SET     Qty = @decQty ,
                    CostTotal = @decTotal ,
                    BeginSort = @n
            WHERE   PTypeID = @strPTypeID
                    AND KTypeID = @strKTypeID
        END
    END
	
	
/*
	SELECT '调整后',*
	FROM #IniData
	--WHERE PTypeID=@strPTypeID
	--AND KTypeID=@strKTypeID
	

	SELECT @i,'调整后',*
	FROM #AllAfterBill
	WHERE PTypeID=@strPTypeID
	AND KTypeID=@strKTypeID
	ORDER BY NewSortID
*/


	FETCH NEXT FROM AfterBill_CURSOR 
	INTO @intSortID, @intTempBillType, @strKTypeID, @strPTypeID, @strSTypeID,
                @intTempBillNumberID, @intTempBillID
        END

--修改GoodsStocks的成本(先直接计算，之后再改为通过之前累计的，加上后续的得到总金额，总数量)



--如果先销售2个100，再采购2个100，再报损1个，做费用分摊30，结果库存金额为0了，应该为30
--这个是因为报损单的成本价是取的30，这个不对。对于用户录入成本或取最近进价的，该怎么处理？

--如果等于0了，则直接取费用分摊单的金额 

    CLOSE AfterBill_CURSOR
    DEALLOCATE AfterBill_CURSOR


    IF EXISTS ( SELECT  PTypeID
                FROM    CommissionStock
                WHERE   Ptypeid = @strInputPTypeID ) 
        BEGIN
            DELETE  FROM CommissionStock
            WHERE   Ptypeid = @strInputPTypeID
	
            INSERT  INTO dbo.CommissionStock
                    ( Ptypeid ,
                      Btypeid ,
                      Type ,
                      Qty ,
                      CostTotal ,
                      Total ,
                      Stypeid ,
                      ETypeID ,
                      KTypeID
	                )
                    SELECT  a.PTypeID ,
                            a.BTypeID ,
                            140 ,
                            SUM(a.Qty) ,
                            SUM(a.CostTotal) ,
                            SUM(a.Total) ,
                            a.STypeID ,
                            '' ,
                            ''
                    FROM    ( SELECT    PTypeID ,
                                        Btypeid ,
                                        CostTotal ,
                                        Total ,
                                        Qty ,
                                        STypeID
                              FROM      dbo.IniCommissionStock
                              WHERE     Ptypeid = @strInputPTypeID
                                        AND Type = 140
                              UNION ALL
                              SELECT    I.Ptypeid ,
                                        B.Btypeid ,
                                        I.CostTotal ,
                                        I.total ,
                                        I.Qty ,
                                        I.STypeID
                              FROM      dbo.InOutstocktable I
                              INNER JOIN dbo.BillIndex B ON I.BillNumberId = B.BillNumberId AND I.BillType = B.BillType
                              WHERE     I.Ptypeid = @strInputPTypeID
                                        AND I.BillType IN ( 140, 141, 142 )
                                        AND I.Ktypeid = '10000'
                            ) a
                    GROUP BY a.PTypeID ,
                            a.BTypeID ,
                            a.STypeID

        END


    IF @intGoOn = 1 
        RETURN

    DECLARE Stock_CURSOR CURSOR
    FOR
        SELECT  PTypeID ,
                KTypeID
        FROM    #StockInfo

    OPEN Stock_CURSOR
    FETCH NEXT FROM Stock_CURSOR INTO @strPTypeID, @strKTypeID

    WHILE @@FETCH_STATUS = 0 
        BEGIN
	--最后算库存的成本价

            TRUNCATE TABLE #SumTotal
		
		
	--始终都把分摊单本身算上（需要测试有无问题）

            INSERT  #SumTotal
                    ( Qty ,
                      Total
                    )
                    SELECT  SUM(a.Qty) ,
                            SUM(a.Total)
                    FROM    ( SELECT    ISNULL(SUM(Qty), 0) AS Qty ,
                                        ISNULL(SUM(CostTotal), 0) AS Total
                              FROM      InOutstocktable
                              WHERE     PtypeId = @strPTypeID
                                        AND KtypeId = @strKTypeID
                              UNION ALL
                              SELECT    ISNULL(SUM(Qty), 0) AS Qty ,
                                        ISNULL(SUM(Total), 0) AS Total
                              FROM      IniGoodsStocks
                              WHERE     PtypeId = @strPTypeID
                                        AND KtypeId = @strKTypeID
                            ) a
	
            IF EXISTS ( SELECT  BillNumberId
                        FROM    InOutstocktable
                        WHERE   PtypeId = @strPTypeID
                                AND KtypeId = @strKTypeID
                                AND BillType = 57
                                AND BillNumberID IN (
                                SELECT  BillNumberID
                                FROM    Billindex
                                WHERE   BillType = 57
                                        AND AdPriceType <> 0 ) ) 
                BEGIN
		
                    UPDATE  #SumTotal
                    SET     Qty = #SumTotal.Qty - b.Qty
                    FROM    ( SELECT    SUM(Qty) AS Qty
                              FROM      InOutstocktable
                              WHERE     PtypeId = @strPTypeID
                                        AND KtypeId = @strKTypeID
                                        AND BillType = 57
                                        AND BillNumberID IN (
                                        SELECT  BillNumberID
                                        FROM    Billindex
                                        WHERE   BillType = 57
                                                AND AdPriceType <> 0 )
                            ) b
		
                END


            IF EXISTS ( SELECT  PTypeID
                        FROM    GoodsStocks
                        WHERE   PtypeId = @strPTypeID
                                AND KtypeId = @strKTypeID ) 
                BEGIN
                    UPDATE  GoodsStocks
                    SET     Qty = b.Qty ,
                            Total = b.Total ,
                            Price = b.Price
                    FROM    ( SELECT    SUM(a.Qty) AS Qty ,
                                        SUM(a.Total) AS Total ,
                                        CASE SUM(a.Qty)
                                          WHEN 0 THEN 0
                                          ELSE ROUND(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10))
                                                     / CAST(SUM(a.Qty) AS NUMERIC(24,
                                                              10)),
                                                     @intPriceDot)
                                        END AS Price
                              FROM      #SumTotal a
                            ) b
                    WHERE   PtypeId = @strPTypeID
                            AND KtypeId = @strKTypeID
                END
            ELSE 
                BEGIN
		--因为现在QTY=0的，系统会删除记录，所以需要追加
		
		--如果存在同价调拨单，则不用追加，因为可能转移到其他仓库了
                    IF NOT EXISTS ( SELECT  BillNumberID
                                    FROM    #AllAfterBill
                                    WHERE   PTypeID = @strPTypeID
                                            AND KTypeID = @strKTypeID
                                            AND BillType = 17 ) 
                        BEGIN
                            IF EXISTS ( SELECT  SUM(Qty)
                                        FROM    #SumTotal
                                        HAVING  SUM(Qty) <> 0
                                                OR SUM(Total) <> 0 ) 
                                BEGIN
                                    INSERT  GoodsStocks
                                            ( PtypeId ,
                                              KtypeId ,
                                              Qty ,
                                              Price ,
                                              Total
                                            )
                                            SELECT  @strPTypeID ,
                                                    @strKTypeID ,
                                                    b.Qty ,
                                                    b.Price ,
                                                    b.Total
                                            FROM    ( SELECT  SUM(a.Qty) AS Qty ,
                                                              SUM(a.Total) AS Total ,
                                                              CASE SUM(a.Qty)
                                                              WHEN 0 THEN 0
                                                              ELSE ROUND(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10))
                                                              / CAST(SUM(a.Qty) AS NUMERIC(24,
                                                              10)), 4)
                                                              END AS Price
                                                      FROM    #SumTotal a
                                                    ) b	
                                END
                        END
                END
	
            FETCH NEXT FROM Stock_CURSOR INTO @strPTypeID, @strKTypeID
        END
    CLOSE Stock_CURSOR
    DEALLOCATE Stock_CURSOR
 

--处理调价全部仓库的成本调价单的回写
    IF EXISTS ( SELECT  BillNumberID
                FROM    #table_ChangeAllStock ) 
        BEGIN
            UPDATE  AdPriceBill
            SET     BeforeTotal = ROUND(ISNULL(b.CostTotal, 0), @intMoneyDot) ,
                    BeforePrice = CASE ISNULL(b.Qty, 0)
                                    WHEN 0 THEN 0
                                    ELSE ROUND(CAST(ISNULL(b.CostTotal, 0) AS NUMERIC(24,
                                                              10))
                                               / CAST(ISNULL(b.Qty, 0) AS NUMERIC(24,
                                                              10)),
                                               @intPriceDot)
                                  END ,
                    Rate = CASE CASE ISNULL(b.Qty, 0)
                                  WHEN 0 THEN 0
                                  ELSE ROUND(CAST(ISNULL(b.CostTotal, 0) AS NUMERIC(24,
                                                              10))
                                             / CAST(ISNULL(b.Qty, 0) AS NUMERIC(24,
                                                              10)),
                                             @intPriceDot)
                                END
                             WHEN 0 THEN 100
                             ELSE ROUND(CAST(AdPriceBill.Price AS NUMERIC(24,
                                                              10))
                                        / ( CASE ISNULL(b.Qty, 0)
                                              WHEN 0 THEN 0
                                              ELSE ROUND(CAST(ISNULL(b.CostTotal,
                                                              0) AS NUMERIC(24,
                                                              10))
                                                         / CAST(ISNULL(b.Qty,
                                                              0) AS NUMERIC(24,
                                                              10)),
                                                         @intPriceDot)
                                            END ), @intTRateDot) * 100
                           END
            FROM    ( SELECT    a.BillNumberId ,
                                a.ID ,
                                ABS(SUM(a.Qty)) AS Qty ,
                                ABS(SUM(a.CostTotal)) AS CostTotal ,
                                ABS(SUM(a.NQty)) AS NQty
                      FROM      InOutstocktable a
                      WHERE     a.BillNumberId IN (
                                SELECT  BillNumberID
                                FROM    #table_ChangeAllStock )
                                AND a.HandZeroCost = 0
                      GROUP BY  a.BillNumberId ,
                                a.ID
                    ) b
            WHERE   AdPriceBill.BillNumberId = b.BillNumberId
                    AND AdPriceBill.ID = b.ID
        END



		
		
    DECLARE @numTotalMoney NUMERIC(22, 10) ,
        @intVipCardID INT ,
        @datVIPBillDate DATETIME ,
        @VIP_ID VARCHAR(50) ,
        @IsRedword INT ,
        @NewPosBill TINYINT ,
        @VipCentInfo VARCHAR(200) ,	--返回会员卡积分调整信息
        @VipCardCode VARCHAR(200)
	
    SELECT  @VIP_ID = nId
    FROM    Ac_Items
    WHERE   nTypeId = '0000200005'

--处理成本价重算的销售出库单，原单单价的回写
    IF @intCostSaleAdjust = 0
        AND EXISTS ( SELECT BillNumberID
                     FROM   #table_CostSaleBill ) 
        BEGIN
	--需要循环处理

            DECLARE CostSaleBill_CURSOR CURSOR
            FOR
                SELECT  a.BillNumberID ,
                        b.CID
                FROM    #table_CostSaleBill a
                        INNER JOIN BillIndex b ON a.BillNumberID = b.BillNumberID
                WHERE   b.BillType = 11
                        AND b.CostSale = 1

            OPEN CostSaleBill_CURSOR
            FETCH NEXT FROM CostSaleBill_CURSOR INTO @intTempBillNumberID,
                @intCID

            WHILE @@FETCH_STATUS = 0 
                BEGIN
		--先把之前的会员卡积分冲回去
                    IF EXISTS ( SELECT  BillNumberId
                                FROM    BillIndex
                                WHERE   BillNumberId = @intTempBillNumberID
                                        AND VipCardID > 0 ) 
                        BEGIN
                            SELECT  @numTotalMoney = TotalMoney ,
                                    @intVipCardID = VipCardID ,
                                    @datVIPBillDate = BILLDATE ,
                                    @IsRedword = 1 ,
                                    @NewPosBill = 0
                            FROM    Billindex
                            WHERE   BillNumberId = @intTempBillNumberID
			
                            EXEC GP_AuditVipInfo 11, @intTempBillNumberID,
                                @numTotalMoney, @intVipCardID, @datVIPBillDate,
                                @VIP_ID, @IsRedword, @NewPosBill,
                                @VipCentInfo OUTPUT, --返回会员卡积分调整信息
                                @VipCardCode OUTPUT	
                        END
	
                    EXEC GP_Auditing_DealSaleBill @intTempBillNumberID, 11, 1,
                        @intCID
				
                    FETCH NEXT FROM CostSaleBill_CURSOR INTO @intTempBillNumberID,
                        @intCID
		
		--再重新积分
                    IF EXISTS ( SELECT  BillNumberId
                                FROM    BillIndex
                                WHERE   BillNumberId = @intTempBillNumberID
                                        AND VipCardID > 0 ) 
                        BEGIN
                            SELECT  @numTotalMoney = TotalMoney ,
                                    @IsRedword = 0
                            FROM    Billindex
                            WHERE   BillNumberId = @intTempBillNumberID
			
                            EXEC GP_AuditVipInfo 11, @intTempBillNumberID,
                                @numTotalMoney, @intVipCardID, @datVIPBillDate,
                                @VIP_ID, @IsRedword, @NewPosBill,
                                @VipCentInfo OUTPUT, --返回会员卡积分调整信息
                                @VipCardCode OUTPUT	
                        END
		
		--需要处理它关联的订单,先把老的到货金额减掉,后续再加上新的
                    IF EXISTS ( SELECT  BillNumberID
                                FROM    SaleBill
                                WHERE   BillNumberId = @intTempBillNumberID
                                        AND OrderID > 0 ) 
                        BEGIN
                            UPDATE  OrderBill
                            SET     ReachTotal = ISNULL(ReachTotal, 0)
                                    - b.total ,
                                    ReachTaxTotal = ISNULL(ReachTaxTotal, 0)
                                    - b.TaxTotal
                            FROM    SaleBill b
                            WHERE   b.BillNumberId = @intTempBillNumberID
                                    AND OrderBill.OrderID = b.OrderID
                        END
	
                END	
	
            CLOSE CostSaleBill_CURSOR
            DEALLOCATE CostSaleBill_CURSOR
			
        END

--处理成本价的发出商品单
    IF @intCostSaleAdjust = 0
        AND EXISTS ( SELECT BillNumberID
                     FROM   #table_CostSendBill ) 
        BEGIN
            DECLARE CostSendBill_CURSOR CURSOR
            FOR
                SELECT  a.BillNumberID ,
                        b.CID
                FROM    #table_CostSendBill a
                        INNER JOIN BillIndex b ON a.BillNumberID = b.BillNumberID
                WHERE   b.BillType = 402
                        AND b.CostSale = 1

            OPEN CostSendBill_CURSOR
            FETCH NEXT FROM CostSendBill_CURSOR INTO @intTempBillNumberID,
                @intCID

            WHILE @@FETCH_STATUS = 0 
                BEGIN
                    UPDATE  SendBill
                    SET     CostPrice = b.CostPrice ,
                            CostTotal = -b.CostTotal
                    FROM    InOutstocktable b
                    WHERE   SendBill.BillNumberId = @intTempBillNumberID
                            AND b.BillNumberId = @intTempBillNumberID
                            AND b.BillType = 402
                            AND SendBill.ID = b.ID
		
                    EXEC GP_Auditing_DealSendBill @intTempBillNumberID, 402, 1,
                        @intCID
				
		--需要处理它的往来项目和往来余额
				
                    FETCH NEXT FROM CostSendBill_CURSOR INTO @intTempBillNumberID,
                        @intCID
                END	
	
            CLOSE CostSendBill_CURSOR
            DEALLOCATE CostSendBill_CURSOR
        END
        
     

--需要更改代销类单据  经确认，对于受托，以前版本10000号中，COSTPRICE,COSTTOTAL=0;对于委托，是取负数
    IF EXISTS ( SELECT  BillNumberID
                FROM    #AfterModifyBill
                WHERE   BillType IN ( 140, 142 ) --所以这里不包含146
) 
        BEGIN
            UPDATE  InOutstocktable
            SET     CostPrice = b.CostPrice ,
                    CostTotal = CASE WHEN InOutstocktable.BillType IN ( 140,
                                                              142 )
                                     THEN -b.CostTotal
                                     ELSE b.CostTotal
                                END
            FROM    ( SELECT    BillNumberID ,
                                ID ,
                                CostPrice ,
                                CostTotal
                      FROM      InOutstocktable
                      WHERE     BillType IN ( 140, 142 ) --所以这里不包含146
                                AND BillNumberId IN (
                                SELECT  BillNumberID
                                FROM    #AfterModifyBill
                                WHERE   BillType IN ( 140, 142 ) --所以这里不包含146
		)
                                AND KtypeId <> '10000'
                    ) b
            WHERE   InOutstocktable.BillNumberId = b.BillNumberId
                    AND InOutstocktable.ID = b.ID
                    AND InOutstocktable.KtypeId = '10000'
        END


--如果更改了发出商品出库单，发出商品退货单，需要更改对应的单据明细，还需要更改相关发票上的CostPrice,CostTotal
    CREATE TABLE #ReceiptList
        (
          BillNumberID BIGINT ,
          OldValue NUMERIC(24, 10) ,
          NewValue NUMERIC(24, 10) ,
          STypeID VARCHAR(50)
        )

    DECLARE @strCostID VARCHAR(50) ,
        @strSendID VARCHAR(50)
	
    SELECT  @strCostID = NID
    FROM    Ac_Items
    WHERE   UserCode = '5401'

    SELECT  @strSendID = NID
    FROM    Ac_Items
    WHERE   UserCode = '1251'


    IF EXISTS ( SELECT  BillNumberID
                FROM    #AfterModifyBill
                WHERE   BillType IN ( 402, 403 ) ) 
        BEGIN
            UPDATE  SendBill
            SET     costprice = b.CostPrice ,
                    CostTotal = -b.CostTotal
            FROM    InOutstocktable b
            WHERE   SendBill.BillNumberId = b.BillNumberId
                    AND SendBill.ID = b.ID
                    AND SendBill.BillNumberId IN ( SELECT   BillNumberID
                                                   FROM     #AfterModifyBill
                                                   WHERE    BillType = 402 )
	
	
            UPDATE  SendBackBill
            SET     costprice = b.CostPrice ,
                    CostTotal = b.CostTotal
            FROM    InOutstocktable b
            WHERE   SendBackBill.BillNumberId = b.BillNumberId
                    AND SendBackBill.ID = b.ID
                    AND SendBackBill.BillNumberId IN ( SELECT BillNumberID
                                                       FROM   #AfterModifyBill
                                                       WHERE  BillType = 403 )
	
	
            UPDATE  ReceiptBill
            SET     InvoiceCostPrice = b.costprice ,
                    InvoiceCostTotal = ROUND(b.costprice * ReceiptBill.Qty,
                                             @intMoneyDot)
            FROM    SendBill b
            WHERE   ReceiptBill.MainBillNumberID = b.BillNumberId
                    AND ReceiptBill.RecordedItemId = b.ID
                    AND ReceiptBill.MainBillNumberID IN ( SELECT
                                                              BillNumberID
                                                          FROM
                                                              #AfterModifyBill
                                                          WHERE
                                                              BillType = 402 )
                    AND dbo.ReceiptBill.BillNumberID IN (
                    SELECT  BillNumberId
                    FROM    dbo.ReceiptBillIndex
                    WHERE   ifcheck = 't'
                            AND RedWord = 0 )
	
            UPDATE  ReceiptBill
            SET     InvoiceCostPrice = b.costprice ,
                    InvoiceCostTotal = ROUND(b.costprice * ReceiptBill.Qty,
                                             @intMoneyDot)
            FROM    SendBackBill b
            WHERE   ReceiptBill.MainBillNumberID = b.BillNumberId
                    AND ReceiptBill.RecordedItemId = b.ID
                    AND ReceiptBill.MainBillNumberID IN ( SELECT
                                                              BillNumberID
                                                          FROM
                                                              #AfterModifyBill
                                                          WHERE
                                                              BillType = 403 )
                    AND dbo.ReceiptBill.BillNumberID IN (
                    SELECT  BillNumberId
                    FROM    dbo.ReceiptBillIndex
                    WHERE   ifcheck = 't'
                            AND RedWord = 0 )
	
            UPDATE  dbo.SendBill
            SET     InvoiceCostTotal = b.InvoiceCostTotal
            FROM    dbo.ReceiptBill b
            WHERE   SendBill.BillNumberID = b.MainBillNumberID
                    AND SendBill.ID = b.RecordedItemId
                    AND b.MainBillNumberID IN ( SELECT  BillNumberID
                                                FROM    #AfterModifyBill
                                                WHERE   BillType = 402 )
                    AND b.BillNumberID IN ( SELECT  BillNumberId
                                            FROM    dbo.ReceiptBillIndex
                                            WHERE   ifcheck = 't'
                                                    AND RedWord = 0 )
	
            UPDATE  dbo.SendBackBill
            SET     InvoiceCostTotal = -b.InvoiceCostTotal
            FROM    dbo.ReceiptBill b
            WHERE   SendBackBill.BillNumberID = b.MainBillNumberID
                    AND SendBackBill.ID = b.RecordedItemId
                    AND b.MainBillNumberID IN ( SELECT  BillNumberID
                                                FROM    #AfterModifyBill
                                                WHERE   BillType = 403 )
                    AND b.BillNumberID IN ( SELECT  BillNumberId
                                            FROM    dbo.ReceiptBillIndex
                                            WHERE   ifcheck = 't'
                                                    AND RedWord = 0 )
	
	
	
	
            INSERT  #ReceiptList
                    ( BillNumberID ,
                      OldValue ,
                      NewValue ,
                      STypeID
                    )
                    SELECT  a.BillNumberID ,
                            SUM(a.InvoiceCostTotal) ,
                            SUM(ROUND(c.costprice * a.Qty, @intMoneyDot)) ,
                            b.STypeID
                    FROM    ReceiptBill a
                            INNER JOIN ReceiptBillIndex b ON a.BillNumberID = b.BillNumberID
                            INNER JOIN ( SELECT BillNumberId ,
                                                ID ,
                                                Qty ,
                                                CostPrice
                                         FROM   SendBill a
                                         UNION ALL
                                         SELECT BillNumberId ,
                                                ID ,
                                                Qty ,
                                                CostPrice
                                         FROM   SendBackBill
                                       ) c ON a.MainBillNumberID = c.BillNumberId
                                              AND a.RecordedItemId = c.ID
                                              AND a.BillNumberID IN (
                                              SELECT    d.BillNumberID
                                              FROM      dbo.ReceiptBill d
                                                        INNER JOIN dbo.SendBill e ON d.MainBillNumberID = e.BillNumberId
                                              WHERE     e.BillNumberID IN (
                                                        SELECT
                                                              BillNumberID
                                                        FROM  #AfterModifyBill
                                                        WHERE BillType IN (
                                                              402, 403 ) )
                                              UNION ALL
                                              SELECT    d.BillNumberID
                                              FROM      dbo.ReceiptBill d
                                                        INNER JOIN dbo.SendBackBill e ON d.MainBillNumberID = e.BillNumberId
                                              WHERE     e.BillNumberID IN (
                                                        SELECT
                                                              BillNumberID
                                                        FROM  #AfterModifyBill
                                                        WHERE BillType IN (
                                                              402, 403 ) ) )
                    WHERE   b.ifcheck = 't'
                            AND b.RedWord = 0
                    GROUP BY a.BillNumberId ,
                            b.Stypeid
	
	
	
	--ATYPE_TOTAL
	
	
	
            UPDATE  ListTable
            SET     Total = b.NewValue ,
                    Ntotal = b.NewValue
            FROM    ( SELECT    BillNumberID ,
                                SUM(NewValue) AS NewValue
                      FROM      #ReceiptList
                      GROUP BY  BillNumberID
                    ) b
            WHERE   ListTable.BillNumberId = b.BillNumberID
                    AND ListTable.BillType = 405
                    AND ListTable.AtypeId = @strCostID  
	
            UPDATE  AType_Total
            SET     Total = AType_Total.Total + b.Total ,
                    Ntotal = AType_Total.Ntotal + b.Total
            FROM    ( SELECT    STypeID ,
                                -SUM(OldValue) + SUM(NewValue) AS Total
                      FROM      #ReceiptList
                      GROUP BY  STypeID
                    ) b
            WHERE   AType_Total.STypeID = b.STypeID
                    AND AType_Total.ATypeID = @strCostID	

	
	
            UPDATE  ListTable
            SET     Total = -b.NewValue ,
                    Ntotal = -b.NewValue ,
                    CostTotal = -b.NewValue
            FROM    ( SELECT    BillNumberID ,
                                SUM(NewValue) AS NewValue
                      FROM      #ReceiptList
                      GROUP BY  BillNumberID
                    ) b
            WHERE   ListTable.BillNumberId = b.BillNumberID
                    AND ListTable.BillType = 405
                    AND ListTable.AtypeId = @strSendID  
	
            UPDATE  AType_Total
            SET     Total = AType_Total.Total + b.Total ,
                    Ntotal = AType_Total.Ntotal + b.Total
            FROM    ( SELECT    STypeID ,
                                -SUM(OldValue) + SUM(NewValue) AS Total
                      FROM      #ReceiptList
                      GROUP BY  STypeID
                    ) b
            WHERE   AType_Total.STypeID = b.STypeID
                    AND AType_Total.ATypeID = @strSendID	
	
	
            TRUNCATE TABLE #ReceiptList
	
	
	
	
	
        END


/*
SELECT '#ReceiptList',* FROM #ReceiptList
*/
    DROP TABLE #ReceiptList
    DROP TABLE #table_ChangeAllStock
    DROP TABLE #table_CostSaleBill
    DROP TABLE #table_CostSendBill


GO








/****** Object:  StoredProcedure [dbo].[Gp_CostRe_GetSourceBill]    Script Date: 08/06/2018 16:16:23 ******/
IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[Gp_CostRe_GetSourceBill]')
                    AND type IN ( N'P', N'PC' ) ) 
    DROP PROCEDURE [dbo].[Gp_CostRe_GetSourceBill]
GO


/****** Object:  StoredProcedure [dbo].[Gp_CostRe_GetSourceBill]    Script Date: 08/06/2018 16:16:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO



/*

作者：冯波

得到采购费用分摊单关联的采购入库单


修改：冯波
备注：如果客户用了按单据日期计算成本，则需要调整

*/
CREATE   PROCEDURE [dbo].[Gp_CostRe_GetSourceBill]
    (
      @datPostTime			DATETIME ,
	  @datDealBeginDate      DATETIME ,
      @strInputSTypeID		VARCHAR(50) ,			--过滤分支机构，肯定有值，这个是分支机构叶子节点
      @nRet					INT OUT ,
      @strErrMsg			VARCHAR(500) = '' OUT
    )
----@encode$--
AS --select '修改或红冲时间',@datPostTime
    SELECT  @nRet = 0 ,
            @strErrMsg = ''

DECLARE @intCostSaleAdjust INT ,		--成本价销售，调拨不参与成本计算，1表示勾选了不参与，0表示不勾选要参与
        @intDisassemble INT ,			--生产拆装单不参与成本计算，1表示勾选了不参与，0表示不勾选要参与
        @DateMonthProc DATETIME,
        @intCostDelivery INT  --按成本价配送的单据不参与成本计算

    SELECT  @DateMonthProc = StartDate
    FROM    dbo.MonthProc
    WHERE   MonthNo = '本期'
            AND stypeid = @strInputSTypeID

    SELECT  @intCostSaleAdjust = Value
    FROM    Userconfig
    WHERE   ConfigName = 'allowtbbillcostprice'

    SELECT  @intDisassemble = Value
    FROM    Userconfig
    WHERE   ConfigName = 'allowczbillcostprice'

    SELECT @intCostDelivery=Value
    FROM dbo.Userconfig WHERE ConfigName = 'costdeliverycancalbill'
    
    
    DECLARE @intCountcostbybilldate INT   --根据单据日期来计算成本
	
    SELECT  @intCountcostbybilldate = Value
    FROM    Userconfig
    WHERE   ConfigName = 'countcostbybilldate'

--统一时间
SET @datPostTime = CONVERT(VARCHAR(10),@datPostTime,120)

--报溢单现在是取单据上录入的成本,所以也不重算

--服务类商品没有成本，应该不参与成本重算
--需要重算的商品信息在#PTypeInfo


--这里还需要按单据类型和出入库性质来具体筛选

--郝华确认：委托代销结算单，受托代销结算单,受托代销结算单，委托代销结算单都不参与重算

--SELECT  '@intCountcostbybilldate',@intCountcostbybilldate,'@datPostTime',@datPostTime,'@DateMonthProc',@DateMonthProc

--0.按过账日期算 1.按单据日期算
    IF @intCountcostbybilldate = 0 
        BEGIN
            INSERT  #AfterModifyBill
            ( 
				BillNumberID ,
				BillType ,
				BillID ,
				PTypeID ,
				KTypeID ,
				SortID ,
				Qty ,
				PostTime ,
				STypeID ,
				BillDate
            )
			--一般来说，出库部分的都需要处理
            SELECT  a.BillNumberId ,
                    a.BillType ,
                    a.ID ,
                    a.PtypeId ,
                    a.KtypeId ,
                    a.SortID ,
                    a.Qty ,
                    a.PostTime ,
                    a.STypeID ,
                    a.BillDate
            FROM    InOutstocktable a
                    INNER JOIN ( SELECT PTypeID ,
                                        KTypeID
                                 FROM   #PTypeInfo
                               ) b ON a.PtypeId = b.PTypeID
                                      AND a.KtypeId = b.KTypeID
            WHERE   a.posttime >= @datPostTime
                    AND a.Audited = 1
                    AND a.Qty < 0
                    AND a.BillType NOT IN ( 401, 141, 145, 143, 147,
                                            142, 144 )
                    AND a.KtypeId <> '10000'
            UNION ALL
            SELECT  a.BillNumberId ,
                    a.BillType ,
                    a.ID ,
                    a.PtypeId ,
                    a.KtypeId ,
                    a.SortID ,
                    a.Qty ,
                    a.PostTime ,
                    a.STypeID ,
                    a.BillDate
            FROM    InOutstocktable a
                    INNER JOIN ( SELECT PTypeID ,
                                        KTypeID
                                 FROM   #PTypeInfo
                                 WHERE  KTypeID = '10000'
                               ) b ON a.PtypeId = b.PTypeID
            WHERE   a.posttime >= @datPostTime
                    AND a.Audited = 1
                    AND a.Qty < 0
                    AND a.BillType IN ( 141, 142 )
                    AND a.KtypeId = '10000'
            UNION ALL
            SELECT  a.BillNumberId ,
                    a.BillType ,
                    a.ID ,
                    a.PtypeId ,
                    a.KtypeId ,
                    a.SortID ,
                    a.Qty ,
                    a.PostTime ,
                    a.STypeID ,
                    a.BillDate
            FROM    InOutstocktable a
                    INNER JOIN ( SELECT PTypeID ,
                                        KTypeID
                                 FROM   #PTypeInfo
                               ) b ON a.PtypeId = b.PTypeID
                                      AND a.KtypeId = b.KTypeID
            WHERE   a.posttime >= @datPostTime
			        AND a.billdate >=@datDealBeginDate
                    AND a.Audited = 1
                    AND a.Qty > 0
                    AND a.BillType NOT IN ( 34, 161, 144, 21, 201,
                                            16, 57, 174, 400, 14, 141,
                                            145, 143, 147, 142, 144 )  --最新确认不处理成本价入库的受托代销入库单 991 
                    AND a.KtypeId <> '10000'
                    --SELECT 'AfterModify @datPostTime=',@datPostTime,'@DateMonthProc=',@DateMonthProc
        END
        
    ELSE 
        BEGIN
		--SELECT 'AfterModify @datPostTime=',@datPostTime,'@DateMonthProc=',@DateMonthProc
        INSERT  #AfterModifyBill
        ( 
			BillNumberID ,
			BillType ,
			BillID ,
			PTypeID ,
			KTypeID ,
			SortID ,
			Qty ,
			PostTime ,
			STypeID ,
			BillDate
        )
		--一般来说，出库部分的都需要处理
        SELECT  a.BillNumberId ,
                a.BillType ,
                a.ID ,
                a.PtypeId ,
                a.KtypeId ,
                a.SortID ,
                a.Qty ,
                a.PostTime ,
                a.STypeID ,
                a.BillDate
        FROM    InOutstocktable a
                INNER JOIN ( SELECT PTypeID ,
                                    KTypeID
                             FROM   #PTypeInfo
                           ) b ON a.PtypeId = b.PTypeID
                                  AND a.KtypeId = b.KTypeID
        WHERE   a.BillDate >= @datPostTime
		        AND a.billdate >=@datDealBeginDate
                AND a.Audited = 1
                AND a.Qty < 0
                AND a.BillType NOT IN ( 401, 141, 145, 143, 147,
                                        142, 144 )
                AND a.KtypeId <> '10000'
        UNION ALL
        SELECT  a.BillNumberId ,
                a.BillType ,
                a.ID ,
                a.PtypeId ,
                a.KtypeId ,
                a.SortID ,
                a.Qty ,
                a.PostTime ,
                a.STypeID ,
                a.BillDate
        FROM    InOutstocktable a
                INNER JOIN ( SELECT PTypeID ,
                                    KTypeID
                             FROM   #PTypeInfo
                             WHERE  KTypeID = '10000'
                           ) b ON a.PtypeId = b.PTypeID
        WHERE   a.BillDate >= @datPostTime
                AND a.Audited = 1
                AND a.Qty < 0
                AND a.BillType IN ( 141, 142 )
                AND a.KtypeId = '10000'
        UNION ALL
        SELECT  a.BillNumberId ,
                a.BillType ,
                a.ID ,
                a.PtypeId ,
                a.KtypeId ,
                a.SortID ,
                a.Qty ,
                a.PostTime ,
                a.STypeID ,
                a.BillDate
        FROM    InOutstocktable a
                INNER JOIN ( SELECT PTypeID ,
                                    KTypeID
                             FROM   #PTypeInfo
                           ) b ON a.PtypeId = b.PTypeID
                                  AND a.KtypeId = b.KTypeID
        WHERE   a.BillDate >= @datPostTime
		        AND a.billdate >=@datDealBeginDate
                AND a.Audited = 1
                AND a.Qty > 0
                AND a.BillType NOT IN ( 34, 161, 144, 21, 201,
                                        16, 57, 174, 400, 14, 141,
                                        145, 143, 147, 142, 144 )   --最新确认不处理成本价入库的受托代销入库单
                AND a.KtypeId <> '10000'
        END
	--SELECT '1' ,* FROM #AfterModifyBill
    CREATE TABLE #MoveSameBill
        (
          BillNumberID BIGINT ,
          BillType INT ,
          BillID BIGINT ,
          PTypeID VARCHAR(50) ,
          KTypeID VARCHAR(50) ,
          PostTime DATETIME ,
          SortID INT
        )

    IF EXISTS ( 
		SELECT  a.BillNumberId ,
                a.ID ,
                a.PostTime
        FROM    InOutstocktable a
                INNER JOIN ( SELECT PTypeID ,
                                    KTypeID
                             FROM   #PTypeInfo
                           ) b ON a.PtypeId = b.PTypeID
                                  AND a.KtypeId = b.KTypeID
        WHERE   ( ( @intCountcostbybilldate = 0
                    AND a.PostTime >= @datPostTime
                    AND a.PostTime >= @DateMonthProc
                  )
                  OR ( @intCountcostbybilldate = 1
                       AND a.BillDate >= @datPostTime
                       AND a.BillDate >= @DateMonthProc
                     )
                )
                AND a.Audited = 1
                AND a.Qty < 0
                AND a.BillType = 17 
        ) 
        BEGIN
	--这里需要性能优化，且检查一下，是否按单据日期计算要开分支
            INSERT  #MoveSameBill
            SELECT  a.BillNumberId ,
                    a.BillType ,
                    a.ID ,
                    a.PtypeId ,
                    a.KtypeId ,
                    a.PostTime ,
                    a.SortID
            FROM    InOutstocktable a
            INNER JOIN #PTypeInfo c ON a.PtypeId = c.PTypeID AND a.KtypeId = c.KTypeID
            INNER JOIN ( 
						SELECT a.BillNumberId ,
                                a.ID ,
                                a.PostTime
                        FROM   InOutstocktable a
                        INNER JOIN ( SELECT
                                      PTypeID ,
                                      KTypeID
                                     FROM
                                      #PTypeInfo
                                   ) b ON a.PtypeId = b.PTypeID
                                      AND a.KtypeId = b.KTypeID
                         WHERE  ( @intCountcostbybilldate = 0
                                  AND a.PostTime >= @datPostTime
                                  AND a.PostTime >= @DateMonthProc
                                )
                                OR ( @intCountcostbybilldate = 1
                                     AND a.BillDate >= @datPostTime
                                     AND a.BillDate >= @DateMonthProc
                                   )
                                AND a.Audited = 1
                                AND a.Qty < 0
                                AND a.BillType = 17
                       ) b ON a.PostTime >= b.Posttime
                              AND a.ID = b.ID
            WHERE   a.BillType = 17
                    AND a.Audited = 1
                    AND a.Qty > 0
        END

    DECLARE @intGoOn BIT
	
    SELECT  @intGoOn = 0

    WHILE @intGoOn = 0 
        BEGIN
            INSERT  #MoveSameBill
                    SELECT  a.BillNumberId ,
                            a.BillType ,
                            a.ID ,
                            a.PtypeId ,
                            a.KtypeId ,
                            a.PostTime ,
                            a.SortID
                    FROM    InOutstocktable a
                    INNER JOIN #PTypeInfo c ON a.PtypeId = c.PTypeID AND a.KtypeId = c.KTypeID
                    INNER JOIN (
								--从同价调拨入库后查后续的同价调拨单
                                 SELECT a.BillNumberId ,
                                        a.ID ,
                                        a.PtypeId ,
                                        a.KtypeId ,
                                        a.SortID
                                 FROM   InOutstocktable a
                                        INNER JOIN ( SELECT
                                                      PTypeID ,
                                                      KTypeID ,
                                                      MIN(SortID) AS SortID
                                                     FROM
                                                      #MoveSameBill
                                                     GROUP BY PTypeID ,
                                                      KTypeID
                                                   ) b ON a.PtypeId = b.PTypeID
                                                      AND a.KtypeId = b.KTypeID
                                                      AND a.Audited = 1
                                                      AND a.Qty < 0
                                                      AND a.BillType = 17
                                 WHERE  a.SortID > b.SortID
                               ) b ON a.BillNumberId = b.BillNumberId
                                      AND a.ID = b.ID
            WHERE   a.BillType = 17
                    AND a.Audited = 1
                    AND a.Qty > 0
                    AND NOT EXISTS ( SELECT b.BillID
                                     FROM   #MoveSameBill b
                                     WHERE  b.BillID = a.ID )
	
            IF @@ROWCOUNT = 0 
                BEGIN
                    SET @intGoOn = 1
                END
        END

--SELECT '@intGoOn=',@intGoOn

    INSERT  #AfterModifyBill
	( 
		BillNumberID ,
		BillType ,
		BillID ,
		PTypeID ,
		KTypeID ,
		SortID ,
		Qty ,
		PostTime ,
		STypeID ,
		BillDate
	)
    SELECT  a.BillNumberId ,
            a.BillType ,
            a.ID ,
            a.PtypeId ,
            a.KtypeId ,
            a.SortID ,
            a.Qty ,
            a.PostTime ,
            a.STypeID ,
            a.BillDate
    FROM    ( 
		SELECT  a.BillNumberId ,
                a.BillType ,
                a.ID ,
                a.PtypeId ,
                a.KtypeId ,
                a.SortID ,
                a.Qty ,
                a.PostTime ,
                a.STypeID ,
                a.BillDate
		FROM    InOutstocktable a
        INNER JOIN ( 
						SELECT	PTypeID ,
								KTypeID ,
                                MIN(SortID) AS SortID
						FROM	#MoveSameBill
						GROUP BY	PTypeID ,
									KTypeID
						) b ON a.PtypeId = b.PTypeID AND a.KtypeId = b.KTypeID
      WHERE     a.SortID >= b.SortID
                AND a.Audited = 1
                AND a.Qty < 0
                AND a.BillType NOT IN ( 401, 141, 145, 143,
                                        147, 144 )
                AND ( ( @intCountcostbybilldate = 0
                        AND a.PostTime >= @datPostTime
                        AND a.PostTime >= @DateMonthProc
                      )
                      OR ( @intCountcostbybilldate = 1
                           AND a.BillDate >= @datPostTime
                           AND a.BillDate >= @DateMonthProc
                         )
                    )
      UNION ALL
      SELECT    a.BillNumberId ,
                a.BillType ,
                a.ID ,
                a.PtypeId ,
                a.KtypeId ,
                a.SortID ,
                a.Qty ,
                a.PostTime ,
                a.STypeID ,
                a.BillDate
      FROM      InOutstocktable a
                INNER JOIN ( SELECT PTypeID ,
                                    KTypeID ,
                                    MIN(SortID) AS SortID
                             FROM   #MoveSameBill
                             GROUP BY PTypeID ,
                                    KTypeID
                           ) b ON a.PtypeId = b.PTypeID
                                  AND a.KtypeId = b.KTypeID
      WHERE     a.SortID >= b.SortID
                AND ( ( @intCountcostbybilldate = 0
                        AND a.PostTime >= @datPostTime
                        AND a.PostTime >= @DateMonthProc
                      )
                      OR ( @intCountcostbybilldate = 1
                           AND a.BillDate >= @datPostTime
                           AND a.BillDate >= @DateMonthProc
                         )
                    )
                AND a.Audited = 1
                AND a.Qty > 0
                AND a.BillType NOT IN ( 34, 161, 144, 21,
                                        201, 16, 57, 174, 400,
                                        14, 141, 145, 143, 147,
                                        144 )
    ) a
    WHERE   NOT EXISTS ( SELECT b.BillID
                         FROM   #AfterModifyBill b
                         WHERE  b.SortID = a.SortID )

    DECLARE @strTempCostSaleBillCode VARCHAR(100)

    IF @intCostSaleAdjust = 1 
        BEGIN
    
			--成本价的不参与，删除掉，后续为了性能需要修改此处，排除掉即可
            DELETE  #AfterModifyBill
            WHERE   EXISTS ( SELECT b.BillNumberId
                             FROM   Billindex b
                             WHERE  #AfterModifyBill.BillNumberID = b.BillNumberId
                                    AND #AfterModifyBill.BillType = b.BillType
                                    AND b.CostSale = 1 )
        END
    ELSE 
        BEGIN
            IF EXISTS ( SELECT  a.BillNumberID
                        FROM    #AfterModifyBill a
                                INNER JOIN BillIndex b ON a.BillNumberID = b.BillNumberId
                        WHERE   a.BillType = 11
                                AND b.CostSale = 1
                                AND a.BillNumberId IN (
                                SELECT  BillNumberId
                                FROM    PerformanceDistribution ) ) 
                BEGIN
	
                    SELECT  @strTempCostSaleBillCode = b.BillCode
                    FROM    #AfterModifyBill a
                            INNER JOIN BillIndex b ON a.BillNumberID = b.BillNumberId
                    WHERE   a.BillType = 11
                            AND b.CostSale = 1
                            AND a.BillNumberId IN (
                            SELECT  BillNumberId
                            FROM    PerformanceDistribution )		
	
                    SELECT  @nRet = -600 ,  --表示成本价销售的单据有业绩分配不能重算
                            @strErrMsg = '您所重算的成本价销售的单据【'
                            + @strTempCostSaleBillCode
                            + '】，目前已经进行了业绩分配，不能成本重算，如需重算请先清除业绩分配后再进行重算！'
                    RETURN
		
                END
        END
  
    IF @intDisassemble = 1 
        BEGIN
            DELETE  #AfterModifyBill
            WHERE   BillType = 16 
        END
    IF @intCostDelivery=1
      BEGIN
           --成本价配送的不参与，删除掉，后续为了性能需要修改此处，排除掉即可
            DELETE  #AfterModifyBill
            WHERE   EXISTS ( SELECT b.BillNumberId
                             FROM   dbo.PosAllotApplyBillIndex b
                             WHERE  #AfterModifyBill.BillNumberID = b.BillNumberId
                                    AND #AfterModifyBill.BillType = b.BillType
                                    AND b.CostSale = 1 
                                    AND b.BillType IN(327,328,329))
      END
 ---特殊处理，删除不按成本价配送的验收单，不按成本价配送，的验收单，成本计算不会动它的成本

        DELETE  #AfterModifyBill
            WHERE   EXISTS ( SELECT b.BillNumberId
                             FROM   dbo.PosAllotApplyBillIndex b
                             WHERE  #AfterModifyBill.BillNumberID = b.BillNumberId
                                    AND #AfterModifyBill.BillType = b.BillType
                                    AND b.CostSale = 0 
                                    AND b.BillType =329)

                                    
--select '需要修改的单据3',* from #AfterModifyBill

    INSERT  #StockInfo
            ( PTypeID ,
              KTypeID
            )
            SELECT DISTINCT
                    a.PTypeID ,
                    a.KTypeID
            FROM    #AfterModifyBill a

--select '需要修改的',* from #StockInfo

--SELECT 'ddd',* FROM #AfterModifyBill

--SELECT 'CostRe_GetSourceBill'

GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
	SELECT * 
	FROM dbo.sysobjects 
	WHERE id = OBJECT_ID(N'[dbo].[GP_CouponInfo_Check]') 
		AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
	DROP PROCEDURE [dbo].[GP_CouponInfo_Check]
GO

CREATE PROCEDURE GP_CouponInfo_Check (
	 @UserID	VARCHAR(50)
	,@TableName	VARCHAR(50)
	,@TypeIDs	VARCHAR(MAX)
	,@excludeTypeId VARCHAR(50)
	,@CouponInfoTable Type_CouponInfo READONLY
)
--@encode$--
AS 
SET NOCOUNT ON 

CREATE TABLE #TYPEIDSTable
(
	typeid VARCHAR(50)
)
INSERT INTO #TYPEIDSTable SELECT a FROM f_split(@TypeIDs, ',')



CREATE TABLE #TYPEIDS
(
	typeid VARCHAR(50)
)
INSERT INTO #TYPEIDS( typeid ) SELECT typeid FROM @CouponInfoTable
DELETE FROM #TYPEIDS WHERE typeid = @excludeTypeId



DECLARE @TypeID VARCHAR(50)
DECLARE UserRange_Cursor CURSOR FOR
SELECT typeid FROM #TYPEIDSTable
FOR READ ONLY
OPEN UserRange_Cursor
FETCH NEXT FROM UserRange_Cursor 
INTO @TypeID
WHILE @@FETCH_STATUS = 0
BEGIN
IF EXISTS(SELECT * FROM #TYPEIDS WHERE @TypeID LIKE typeid+'%')
BEGIN
	RETURN -2
END


DELETE FROM #TYPEIDS WHERE Typeid LIKE @TypeID+'%'
INSERT #TYPEIDS SELECT @TypeID


FETCH NEXT FROM UserRange_Cursor INTO @TypeID
END
CLOSE UserRange_Cursor
DEALLOCATE UserRange_Cursor


IF(@tablename ='gridSp')--适用商品
BEGIN
	SELECT FullName,UserCode,Pid,iscombinationproduct AS IsCombined,customitemid AS ItemID,Standard,Type,ptype.typeId,sonnum FROM dbo.ptype INNER JOIN #TYPEIDS p ON p.typeid = ptype.typeId
END 
ELSE IF(@tablename = 'gridExp')--兑换商品
BEGIN
	SELECT FullName,UserCode,Pid,iscombinationproduct AS IsCombined,customitemid AS ItemID,Standard,Type,ptype.typeId,sonnum,IfSerial,deleted FROM dbo.ptype  INNER JOIN #TYPEIDS p ON p.typeid = ptype.typeId WHERE ptype.iscombinationproduct=0
END 
ELSE IF(@tablename = 'gridSt')--适用机构
BEGIN
	SELECT FullName,UserCode,Sid,Comment AS remark,s.typeid,s.SonNum,s.typeid AS stypeid FROM dbo.SType s INNER JOIN #TYPEIDS p ON p.typeid = s.TypeId
END 
ELSE IF(@tablename = 'gridPos')--适用pos终端
BEGIN
	SELECT s.PosID typeid,FullName,UserCode FROM dbo.PosInfo s INNER JOIN #TYPEIDS p ON p.typeid = s.PosID
END 
	
RETURN 0

DROP TABLE #TYPEIDS,#TYPEIDSTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
	SELECT * 
	FROM dbo.sysobjects 
	WHERE id = OBJECT_ID(N'[dbo].[GP_CouponInfoBeUsed_Check]') 
		AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
	DROP PROCEDURE [dbo].[GP_CouponInfoBeUsed_Check]
GO

CREATE PROCEDURE GP_CouponInfoBeUsed_Check (
	@TypeIDs	VARCHAR(MAX)
)
AS 
SET NOCOUNT ON 

CREATE TABLE #TYPEIDSTable
(
	typeid VARCHAR(50)
)
INSERT INTO #TYPEIDSTable SELECT a FROM f_split(@TypeIDs, ',')

SELECT typeInfo.CouponId,FullName FROM 
	(
	SELECT CouponId,COUNT(1) AS CouponNum FROM dbo.Coupon_BillIndex bill 
	INNER JOIN dbo.Coupon_InBill inBill ON bill.BillNumberId = inBill.BillNumberId
	GROUP BY CouponId
	HAVING COUNT(1) > 0
UNION ALL --期初单据
SELECT CouponId,COUNT(1) AS CouponNum FROM dbo.Coupon_CodeInfo
	WHERE IsIni = 1
	GROUP BY CouponId 
	HAVING COUNT(1) > 0
	) AS temp 
INNER JOIN dbo.Coupon_TypeInfo typeInfo ON temp.CouponId = typeInfo.CouponId
WHERE temp.CouponId IN (SELECT typeid FROM #TYPEIDSTable)

DROP TABLE #TYPEIDSTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_CouponStypeOutBill_CreateBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_CouponStypeOutBill_CreateBill]
GO




/*

功能说明：		优惠券分支机构调拨出库单过账生成优惠券分支机构调拨入库单的草稿

作    者：       祁丹


返回结果：       

*/

CREATE PROCEDURE [GP_CouponStypeOutBill_CreateBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS


SELECT @intReturnID=0

DECLARE 	
	@strTempKTypeID					VARCHAR(50),
	@strOutSTypeID					VARCHAR(50),		--出库对应的分支机构
	@strInSTypeID					VARCHAR(50),
	@decTax							 NUMERIC(24, 10) ,
	@strFromBillCode 				VARCHAR(100),
	@intBillType					INT,
	@datBillDate					DATETIME,
	@KTypeID						VARCHAR(100),
	@ceDtypeid						VARCHAR(100)='',
	@cdfullname						VARCHAR(500)=''

SELECT 
	@strOutSTypeID=a.sTypeId,@KTypeID=a.InKtypeId,@strFromBillCode=a.BillCode,@datBillDate=a.BillDate,@ceDtypeid=DTypeId
FROM Coupon_BillIndex a
WHERE a.BillNumberId=@nBillID

SELECT @intBillType=428

--SELECT @strTempKTypeID=KTypeID2
--FROM
--(
--	SELECT TOP 1 KTypeID2 
--	FROM STypeMoveBill
--	WHERE BillNumberId=@nBillID
--) a

SELECT @strInSTypeID=STypeID
FROM Stock
WHERE typeId=@KTypeID


--判断是否属于分支机构间的采购，销售

IF EXISTS(SELECT BillNumberId FROM Coupon_BillIndex WHERE FromBillNumberID=@nBillID)
BEGIN
	SET @strErrMsg='该优惠券分支机构调拨出库单已生成有相应的优惠券分支机构调拨入库单草稿！'	
	RETURN
END


DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号



DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@ETypeID			VARCHAR(100),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@cefullname			VARCHAR(500)=''

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT
	@ETypeID='',
	@VchHead='YDBRK'

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = TypeId FROM Employee WHERE TypeID = @ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
	SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @chvOpID
	SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid
END

SELECT 
	@MONTH=ISNULL(@MONTH,''),
	@DAY=ISNULL(@DAY,'')


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strInSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname




IF @Re <> 0
RETURN -2	

--SELECT @strBillCode='tmpfzjgrkd'  --因为单据编号要调整，暂时屏蔽生成单据编号那段代码

DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000)
	
	
SELECT 
	@strComment='该优惠券分支机构调拨入库是从优惠券分支机构调拨出库单'+@strFromBillCode+'生成而来的！',
	@intBillType=428
	
	



--生成表头

INSERT Coupon_BillIndex(BillDate, BillCode, BillType, FromType, STypeId, DTypeId, 
	ETypeId, OutKTypeId, InKTypeId, Cid, Rate, TotalQty, TotalMoney, NTotalMoney, 
	ATypeId, BTypeId,  Explain, Comment, IfAudit, Draft, IfCheck, Maker,
	Checke, PosBillCode, FromBillNumberID,ifyearbill,IsIni,RedWord,MakeTime,Posid)
SELECT BillDate,@strBillCode,@intBillType,FromType,@strInSTypeID,DTypeId,
	ETypeId,OutKTypeId,InKTypeId,Cid,Rate,TotalQty,TotalMoney,NTotalMoney,
	ATypeId,BTypeId,Explain,@strComment,0,1,'f',Maker,
	'',PosBillCode,BillNumberId,0,0,RedWord,GETDATE(),Posid
FROM Coupon_BillIndex 
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();


--生成表体

INSERT Coupon_AllotBillStype(BillNumberId, CouponId, CouponCode, InCargoId, OutCargoId, 
	Comment, Qty, Price, Total, InStockDate, InvalidDate, OutDate,FromBillNumberID,FromBillID)
SELECT @intReturnID,CouponId,CouponCode,InCargoId,OutCargoId,
	Comment,Qty,Price,Total,InStockDate,InvalidDate,OutDate,@nBillID,ID
FROM dbo.Coupon_AllotBillStype
WHERE BillNumberId=@nBillID


--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END    

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END


GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2012-06-01
	描述：会计科目生成ID
*/

CREATE     PROCEDURE Gp_Create_Ac_Account_Id 
( 
	@STypeId	VARCHAR(50),			-- 分支机构ID
	@Parid 		VARCHAR(50),
	@DbName 	VARCHAR(30),
	@CreatedId 	VARCHAR(50) OUTPUT,
	@nSon 		INT OUT,
	@nCount 	INT OUT
)
--@encode$--
AS
SET NOCOUNT ON

IF LEN(@Parid)=50	RETURN -1
IF @STypeId = ''	RETURN -3

DECLARE @execsql	VARCHAR(500)
DECLARE @szTypeId	VARCHAR(50),
		@sonnum		INT,
		@par		VARCHAR(50),
		@soncount	INT

SELECT @execsql='
	DECLARE checkid_CURSOR CURSOR FOR 	
		SELECT 	typeid,
				sonnum,
				parid,
				soncount 
		FROM 	'+@dbname+' 
		WHERE 	typeid= '+''''+@parid+'''
				AND STypeId = '''+@STypeId+''''
				

--PRINT(@execsql)
EXEC (@execsql)

OPEN checkid_CURSOR

FETCH NEXT FROM checkid_CURSOR INTO @szTypeId, @sonnum, @par,@soncount

SELECT @nSon=@sonnum
SELECT @nCount=@soncount
 
IF  @@FETCH_STATUS = -1
	BEGIN
		CLOSE checkid_CURSOR
		DEALLOCATE checkid_CURSOR
		RETURN -1
	END 
ELSE
	BEGIN
		DECLARE @tempId 	VARCHAR(5),
				@nReturn 	INT
		SELECT @soncount=@soncount+1
		EXEC @nReturn=inttostr @soncount,@tempId out
		IF @nReturn=-1  
			BEGIN
				CLOSE checkid_CURSOR
				DEALLOCATE checkid_CURSOR
				RETURN -2
			END 
		ELSE
			BEGIN
				IF @sztypeid='00000' 
					SELECT @createdid=@tempId			
				ELSE 
					SELECT @createdid=RTRIM(@szTypeid)+@tempId
			END
	END
	
 CLOSE checkid_CURSOR
 DEALLOCATE checkid_CURSOR














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/05/30
	Description	:	根据卡片生成折旧计划表
*/
CREATE PROCEDURE Gp_CreateDepreciationPlan
(
	@CardID				INT,    				--卡片ID
	@PeriodFlag				INT					--标示，1是初始化的时候生成，2是增加单的时候生成（初始化从本期，增加单从下期）
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @FYear		INT,
		@FPeriod	INT

-----如果是通过增加单进来的卡片，修改卡片折旧方式，这个时候@PeriodFlag应该是2,由于hq那边一直传的是@PeriodFlag=1,所以这边进行一个判断
IF EXISTS(SELECT * FROM dbo.Ac_AssetsCards_History ah JOIN dbo.Ac_AssetsCards aa ON ah.AssertsCardId=aa.id AND aa.AssetsState=3  WHERE AssertsCardId=@CardID AND BillType=212)
	SET @PeriodFlag=2

-----先删除该卡片折旧记录
DELETE dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType IN (0,1)

DECLARE @Stypeid VARCHAR(50)

SELECT @Stypeid=aac.StypeId 
FROM  dbo.AC_AssetsCards ac 
JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id 
WHERE ac.Id=@CardID


--调整说明：总账未开帐的时候，当前期间和启用期间一样，开帐后又需要取当前期间，所以可以不管开帐状态，直接用当前期间值
---未开账情况下 
--IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE StypeId=@Stypeid AND IsUse = 0)
--BEGIN
--	--初始化，取运维平台设置的期间
--	SELECT @FYear = SFYear,@FPeriod = SFPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Stypeid
--END
--ELSE --开账情况下，取当期
--BEGIN
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Stypeid
--END
 
IF @FPeriod=13
	BEGIN
		SET @FPeriod=1
		SET @FYear=@FYear+1
	END      
      
DECLARE ---卡片信息
        @DepreciationMonth INT,			--已计提月数
        @DurYear  INT,					--折旧年限的总年数
         @durmonth INT ,
        @DepreciationMean INT,
		@DevalueReady		 NUMERIC(24, 10) ,   
		@DepTotal            NUMERIC(24, 10) ,	  
        @Total				 NUMERIC(24, 10) ,  --原值
		@NetValue			 NUMERIC(24, 10) ,  --净值
		@NetSalvage			 NUMERIC(24, 10) ,  --账面净残值
		@Depreciation		 NUMERIC(24, 10) ,  --当期折旧额
        ---辅助参数
        @tempFyear INT=CONVERT(INT,@FYear),   
		@tempFperiod int=@FPeriod,
        @Months INT,					--折旧年限的总月次
		@PlanMonths	INT,			    --还要折旧的月数
	    @MonthOrder INT=1,              --月次
		@YearOrder INT=1,				--年次
		@tempYearOrder INT=1,
		@tempMonthOrder INT=1,
		---平均年限法参数
		@tempDepTotal		  NUMERIC(24, 10) ,	 --临时累计折旧额
		@AVGMonthValue		  NUMERIC(24, 10) ,   --月折旧额
		--双倍余额法的参数
		@tempAVGMonthValue	  NUMERIC(24, 10) ,    --临时月折旧额
		@tempAVGYearValue	  NUMERIC(24, 10) ,    --双倍折旧法中的平均年限法年折旧额  
		@tempDoubleYearValue  NUMERIC(24, 10) ,  --双倍折旧法中的年折旧额   
		@YearRate			  NUMERIC(24, 10) ,
		@LoopMonth INT=1,
        @AVGYears INT,				--当做计算平均年限法的年限除数
		@Flag INT=0,            --转换标志
		@JTFlag INT=0           --计提符合标志
		
		
SELECT @DepreciationMonth=DepreciationMonth,@DurYear=DurYear,@durmonth=durmonth,@DepreciationMean=DepreciationMean,
	   @DevalueReady=DevalueReady,@Total=total,@NetSalvage=NetSalvage,@DepTotal=DepTotal
FROM Ac_AssetsCards WHERE ID=@CardID
 
 
IF @DepreciationMean=1 OR @DepreciationMean=0 OR @DepreciationMean = 5    --手工或不折旧只录入初始数据，然后直接跳过
	BEGIN
		--已经存在就直接退出，不再插入
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=2)
			RETURN
		---录入期初数据
		INSERT INTO Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,
										YearOrder,MonthOrder,FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,
								Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,BillNumberId)
		SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,0,0,
								@FYear,@FPeriod,2,@CardID,LocationId,DisATypeId,0,dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),0,0
		FROM dbo.Ac_AssetsCards WHERE ID=@CardID
		RETURN
	END
	 
SET @Months=@DurYear*12+@durmonth
SET @PlanMonths=@Months-@DepreciationMonth
SET @YearRate=2/(@DurYear+0.0)     --+0.0才能商小数
SET @AVGYears=@DurYear


IF (@Months=@DepreciationMonth)
	RETURN
IF(@Total-@NetSalvage-@DepTotal-@DevalueReady=0)
    RETURN


CREATE TABLE #Data
(
		STypeId			VARCHAR(50),
		DTypeid			VARCHAR(50),
		CategoryId		INT,
		InAccountDate	DATETIME,
		UserCode		VARCHAR(200),
		FullName		VARCHAR(200),
		DepreciationMean	INT,
		YearOrder		INT,
		MonthOrder		INT,
		FYear			INT,
		FPeriod			INT,
		PlanType		INT,
		AssetCardId		INT,
		LocationId		INT,
		DisATypeId		VARCHAR(50),
		Depreciation	 NUMERIC(24, 10) ,
		DepTotal		 NUMERIC(24, 10) ,
		Total			 NUMERIC(24, 10) ,
		DevalueReady	 NUMERIC(24, 10) ,
		NetValue		 NUMERIC(24, 10) ,
		NetSalvage		 NUMERIC(24, 10) ,
		PlanState		INT
)

----平均年限法 

IF @DepreciationMean=2 
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=2)
			----先插入一条期初数据,plantype=2
			INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
									FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
			SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,0,0,
									@FYear,@FPeriod,2,@CardID,LocationId,DisATypeId,0,dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),0 
			FROM dbo.Ac_AssetsCards WHERE ID=@CardID
	    
		--平均年限法的月折旧额
		SET @tempAVGMonthValue=dbo.F_RoundTotal((@Total-@NetSalvage-@DepTotal-@DevalueReady)/@PlanMonths)
	    
		WHILE @MonthOrder<=@PlanMonths
			BEGIN
			    --取上一期的累计折旧额
				IF @MonthOrder=1
					SELECT @tempDepTotal=@DepTotal
				ELSE 
					SELECT @tempDepTotal=DepTotal FROM #Data  WHERE MonthOrder=@MonthOrder-1
					
				--计算月折旧额,最后一期或者每12期比较特殊 
				IF @MonthOrder=@PlanMonths  --最后一期
						set @AVGMonthValue=@Total-@NetSalvage-@tempDepTotal-@DevalueReady
				ELSE IF @MonthOrder%12=0
					SET @AVGMonthValue=dbo.F_RoundTotal((@Total-@NetSalvage-@DepTotal-@DevalueReady)*12/@PlanMonths)-dbo.F_RoundTotal(@tempAVGMonthValue*11)
				ELSE 
					SET @AVGMonthValue=@tempAVGMonthValue 
				
				--计算累计折旧额
				SET @tempDepTotal=@tempDepTotal+@AVGMonthValue 
				
				--计算账面净值
				IF @MonthOrder=1           --第一期 
					BEGIN
						SELECT @NetValue=NetValue FROM dbo.Ac_AssetsCards WHERE Id=@CardID
						SET @NetValue=@NetValue-@AVGMonthValue
					END
				ELSE IF @MonthOrder=@PlanMonths  --最后一期
					SET @NetValue=@NetSalvage
				ELSE 
					BEGIN
						SELECT @NetValue=NetValue FROM #Data  WHERE MonthOrder=@MonthOrder-1
						SET @NetValue=@NetValue-@AVGMonthValue
					END
				
				--年份，期间特殊处理
				IF @PeriodFlag=2  --增加单，从下一期算起
					BEGIN
						IF @tempFperiod>=12 
							BEGIN
								SET @tempFperiod=1
								SET @tempFyear=@tempFyear+1
								SET @YearOrder=@YearOrder+1
							END
						ELSE 
							SET @tempFperiod=@tempFperiod+1
					END
				ELSE      --初始化
					BEGIN
						IF @MonthOrder<>1  --第一期就是fperiod当期,所以第2期起每期才+1
							BEGIN
						 		IF @tempFperiod>=12 
									BEGIN
										SET @tempFperiod=1
										SET @tempFyear=@tempFyear+1
										SET @YearOrder=@YearOrder+1
									END
								ELSE 
									SET @tempFperiod=@tempFperiod+1
							END
					END
						
			
				--插入数据
				INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
						FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
				SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,@MonthOrder,@tempFyear,@tempFperiod,
					   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
				FROM Ac_AssetsCards WHERE ID=@CardID 
				
				SET @MonthOrder=@MonthOrder+1
			END
		      
		     --插入年
			 ;WITH t AS 
			(
				SELECT AssetCardId,YearOrder,SUM(Depreciation) AS Depreciation,COUNT(*) AS fperiod,fyear,MAX(MonthOrder) AS MonthOrder
				FROM #Data	WHERE PlanType=1 GROUP BY AssetCardId,YearOrder,FYear	
			)
			INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
							FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,
							NetValue,NetSalvage,PlanState)
			SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,t.YearOrder,NULL,t.FYear,t.fperiod,
							   0,n.AssetCardId,LocationId,DisATypeId,t.Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,0 
			FROM t 
			JOIN #Data n ON t.YearOrder=n.YearOrder AND t.MonthOrder=n.MonthOrder 
	END
----双倍余额法
ELSE IF @DepreciationMean=3
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=2)
			 ----先插入一条期初数据,plantype=2
			INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
									FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,
									DevalueReady,NetValue,NetSalvage,PlanState)
			SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,0,0,
									@FYear,@FPeriod,2,@CardID,LocationId,DisATypeId,0,DepTotal,Total,DevalueReady,NetValue,NetSalvage,0 
			FROM dbo.Ac_AssetsCards WHERE ID=@CardID
		ELSE 
			BEGIN
				INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
									FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,
									DevalueReady,NetValue,NetSalvage,PlanState)
				SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,0,0,
										FYear,FPeriod,2,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,0 
				FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=2
				
				DELETE dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=2 
			END
			
		
		
----------已计提折旧过
		IF @DepreciationMonth>0
			BEGIN
				--两种情况，先判断卡片上的计提折旧值是否跟算法相等, @JTFlag=1 证明计提折旧不符合双倍法计算公式，需要重新算
				DECLARE @DepreciationYear INT
				SET @DepreciationYear=@DepreciationMonth/12  
				SELECT @NetValue=NetValue,@tempDepTotal=DepTotal FROM dbo.Ac_AssetsCards WHERE ID=@CardID
				IF @DepreciationYear=0   --计提不到一年
					BEGIN
						IF @tempDepTotal<>dbo.F_RoundTotal((CAST((@Total-@DevalueReady)*@YearRate/12 AS  NUMERIC(24, 10) )*@DepreciationMonth))  --先除以12然后四舍五入到2为小数后，在乘以计提期数，这样才符合实际值
							SET @JTFlag=1                      
					END
				ELSE 
					BEGIN
						DECLARE @YearDepTotal  NUMERIC(24, 10) ,
						        @MonthDepTotal  NUMERIC(24, 10) =0,
						        @tempMonthYS   INT   --月余数
						   
						SET @YearDepTotal=dbo.F_RoundTotal(CAST((@Total-@DevalueReady)-(@Total-@DevalueReady)*POWER((1-@YearRate+0.00000000000000),@DepreciationYear) AS  NUMERIC(24, 10) ))  --扩大位数，否则当已折旧年数过大是，得出来的数据会被舍为0
						SET @tempMonthYS=@DepreciationMonth%12
						IF 	@tempMonthYS>0    --证明月份有余数
							SET @MonthDepTotal=  dbo.F_RoundTotal(CAST((@Total-@DevalueReady)*POWER((1-@YearRate+0.00000000000000),@DepreciationYear)*@YearRate/12 AS  NUMERIC(24, 10) ) *@tempMonthYS)
						
						IF @tempDepTotal<>(@YearDepTotal+@MonthDepTotal)
							SET @JTFlag=1
					END
					
				---开始重算
  ------------符合双倍法的,相当于从第一期算,最后对数据进行处理				
				IF @JTFlag=0  
					BEGIN
						CREATE TABLE #newData
						(
							STypeId			VARCHAR(50),
							DTypeid			VARCHAR(50),
							CategoryId		INT,
							InAccountDate	DATETIME,
							UserCode		VARCHAR(200),
							FullName		VARCHAR(200),
							DepreciationMean	INT,
							YearOrder		INT,
							MonthOrder		INT,
							FYear			INT,
							FPeriod			INT,
							PlanType		INT,
							AssetCardId		INT,
							LocationId		INT,
							DisATypeId		VARCHAR(50),
							Depreciation	 NUMERIC(24, 10) ,
							DepTotal		 NUMERIC(24, 10) ,
							Total			 NUMERIC(24, 10) ,
							DevalueReady	 NUMERIC(24, 10) ,
							NetValue		 NUMERIC(24, 10) ,
							NetSalvage		 NUMERIC(24, 10) ,
							PlanState		INT
						)
						INSERT INTO #newData
						SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,0,0,
								0,0,2,@CardID,LocationId,DisATypeId,0,0,Total,DevalueReady,Total-DevalueReady,NetSalvage,0 
						FROM dbo.Ac_AssetsCards WHERE ID=@CardID
						
						--先算年
						WHILE @YearOrder<=@DurYear
							BEGIN
								IF @Flag=1   --已经是平均年限法了
									BEGIN
										--先取上一期的账面净值,累计折旧额
										SELECT @NetValue=NetValue,@tempDepTotal=DepTotal FROM #newData WHERE YearOrder=@YearOrder-1
										
										--最后一年,年折旧计算
										IF @YearOrder=@DurYear
											SET @tempAVGYearValue=@Total-@tempDepTotal-@NetSalvage-@DevalueReady
											
										--计算账面净值
										IF @YearOrder=@DurYear
											SET @NetValue=@NetSalvage
										ELSE 
											SET @NetValue=@NetValue-@tempAVGYearValue
										
										--计算累计折旧额
										SET @tempDepTotal=@tempDepTotal+@tempAVGYearValue
										
										 INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,
															YearOrder,MonthOrder,FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,
															Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
										SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,12,
											   0,@CardID,LocationId,DisATypeId,@tempAVGYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
										FROM Ac_AssetsCards WHERE ID=@CardID 
									END
								ELSE 
									BEGIN
										--先取上一期的账面净值,因为双倍余额法不可能出现双倍算法到最后一期的情况，所以不用考虑最后一期
										SELECT @NetValue=NetValue FROM #newData WHERE YearOrder=@YearOrder-1
											
										--根据净值算年额度
										SET @tempDoubleYearValue=dbo.F_RoundTotal(@NetValue*@YearRate)
										SET @tempAVGYearValue=	dbo.F_RoundTotal((@NetValue-@NetSalvage)/@AVGYears)
										
										---取上一期年积累折旧额
										SELECT @tempDepTotal=DepTotal FROM #newData  WHERE YearOrder=@YearOrder-1
												
										--比较大小，看使用哪种方式
										IF (@tempDoubleYearValue<=@tempAVGYearValue) OR ((@NetValue-@tempDoubleYearValue)<@NetSalvage)    --符合转换条件，改用平均年限法
											BEGIN
												--计算累计折旧额
												SET @tempDepTotal=@tempDepTotal+@tempAVGYearValue
												
												--计算账面净值
												SET @NetValue=@NetValue-@tempAVGYearValue
												
												 INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,
																		MonthOrder,FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,
																		DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
												SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,12,
													   0,@CardID,LocationId,DisATypeId,@tempAVGYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
												FROM Ac_AssetsCards WHERE ID=@CardID 
												
												SET @Flag=1         
											END
										ELSE 
											BEGIN
												 --计算累计折旧额
												SET @tempDepTotal=@tempDepTotal+@tempDoubleYearValue 
												
												--计算账面净值
												SET @NetValue=@NetValue-@tempDoubleYearValue
												
												INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
												FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
												SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,12,
													   0,@CardID,LocationId,DisATypeId,@tempDoubleYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
												FROM Ac_AssetsCards WHERE ID=@CardID 
											END
									END
								
								SET @YearOrder=@YearOrder+1
								SET @AVGYears=@AVGYears-1
							END
						
						---根据#newData数据组装#Data数据
						INSERT INTO #Data 
						SELECT * FROM #newData WHERE YearOrder>=(@DepreciationMonth/12+1)
						DECLARE @DataYearOrder INT
						IF @DepreciationMonth%12<>0  --只需要更新期数和年折旧额就可以了
							BEGIN
								SET @DataYearOrder=@DepreciationMonth/12+1
								UPDATE #Data SET fperiod=(12-@DepreciationMonth%12),Depreciation=deptotal-(SELECT deptotal FROM #Data WHERE yearorder=0)   WHERE yearorder=@DataYearOrder
							END
							
							
						--更新年次
						DECLARE @minYearOrder INT,@maxYearOrder int
						
						SELECT @minYearOrder=MIN(yearorder) FROM #Data WHERE yearorder<>0
						
						UPDATE #Data SET yearorder=yearorder-(@minYearOrder-1) WHERE  yearorder<>0
						 
						SELECT @maxYearOrder=MAX(yearorder) FROM #Data
						
						DECLARE @FirstYearPeriod	int
						----算月,第一年特殊处理，因为可能不是12期
						WHILE   @tempYearOrder<= @maxYearOrder
							BEGIN
								 --上期年净值，累计折旧额
								 SELECT @NetValue=NetValue,@tempDepTotal=deptotal FROM #Data WHERE YearOrder=@tempYearOrder-1
								 
								 --本年的折旧额
								 SELECT @Depreciation=Depreciation FROM #Data WHERE YearOrder=@tempYearOrder
								 
								 --月折旧额
								 IF @tempYearOrder=1 
									BEGIN
										SELECT @FirstYearPeriod=fperiod FROM #Data WHERE YearOrder=@tempYearOrder
										SET @tempAVGMonthValue=dbo.F_RoundTotal(@Depreciation/@FirstYearPeriod)
									END
								 ELSE    
									BEGIN
										SET @tempAVGMonthValue=dbo.F_RoundTotal(@Depreciation/12)
									END
									
								SET @LoopMonth=1
								
								IF @tempYearOrder=1 
									BEGIN
										WHILE @LoopMonth<=@FirstYearPeriod
											BEGIN
												--月折旧额
												IF @LoopMonth=@FirstYearPeriod
													SET @AVGMonthValue=dbo.F_RoundTotal(@Depreciation-@tempAVGMonthValue*(@FirstYearPeriod-1))
												ELSE
													SET @AVGMonthValue=@tempAVGMonthValue
													
												--累计折旧额
												SET @tempDepTotal=@tempDepTotal+@AVGMonthValue
												
												--账面净值 
												SET @NetValue=@NetValue-@AVGMonthValue
												
												--年份，期间特殊处理
												IF @PeriodFlag=2
													BEGIN
														IF @tempFperiod>=12
															BEGIN
																SET @tempFperiod=1
																SET @tempFyear=@tempFyear+1
															END
														ELSE 
															SET @tempFperiod=@tempFperiod+1
													END
												ELSE
													BEGIN
														IF @tempMonthOrder<>1  --第一期就是fperiod当期,所以第2期起每期才+1
															BEGIN
																IF @tempFperiod>=12
																	BEGIN
																		SET @tempFperiod=1
																		SET @tempFyear=@tempFyear+1
																	END
																ELSE 
																	SET @tempFperiod=@tempFperiod+1
															END
													END		
													
												--插入数据
												INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
														FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
												SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@tempYearOrder,@tempMonthOrder,@tempFyear,@tempFperiod,
													   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
												FROM Ac_AssetsCards WHERE ID=@CardID 
												
												SET @LoopMonth=@LoopMonth+1
												SET @tempMonthOrder=@tempMonthOrder+1
											END
									END
								ELSE 
									BEGIN
										WHILE @LoopMonth<=12
											BEGIN
												--月折旧额
												IF @LoopMonth=12
													SET @AVGMonthValue=@Depreciation-dbo.F_RoundTotal(@tempAVGMonthValue*11)
												ELSE
													SET @AVGMonthValue=@tempAVGMonthValue
												
												--累计折旧额
												SET @tempDepTotal=@tempDepTotal+@AVGMonthValue
												
												--账面净值 
												SET @NetValue=@NetValue-@AVGMonthValue
												
												--年份，期间特殊处理
												IF @PeriodFlag=2
													BEGIN
														IF @tempFperiod>=12
															BEGIN
																SET @tempFperiod=1
																SET @tempFyear=@tempFyear+1
															END
														ELSE 
															SET @tempFperiod=@tempFperiod+1
													END
												ELSE
													BEGIN
														IF @tempMonthOrder<>1  --第一期就是fperiod当期,所以第2期起每期才+1
															BEGIN
																IF @tempFperiod>=12
																	BEGIN
																		SET @tempFperiod=1
																		SET @tempFyear=@tempFyear+1
																	END
																ELSE 
																	SET @tempFperiod=@tempFperiod+1
															END
													END		
													
												--插入数据
												INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
														FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
												SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@tempYearOrder,@tempMonthOrder,@tempFyear,@tempFperiod,
													   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
												FROM Ac_AssetsCards WHERE ID=@CardID 
												
												SET @LoopMonth=@LoopMonth+1
												SET @tempMonthOrder=@tempMonthOrder+1
											END
									END
								SET @tempYearOrder=@tempYearOrder+1
							END
					END
	-----------------------不符合双倍法的,从当期开始重算,最后对数据进行处理	
				ELSE 
					BEGIN
						DECLARE @RemainMonth INT,@tempYears INT,@YearPeriod INT=12
						SET @RemainMonth=@DurYear*12-@DepreciationMonth
						IF @RemainMonth%12=0
							SET @tempYears=@RemainMonth/12
						ELSE 
							SET @tempYears=@RemainMonth/12 + 1
                        
                        SET @AVGYears=@tempYears
                        WHILE @YearOrder<=@tempYears
							BEGIN
								IF @Flag=1   --已经是平均年限法了
									BEGIN
										--先取上一期的账面净值,累计折旧额
										SELECT @NetValue=NetValue,@tempDepTotal=DepTotal FROM #Data WHERE YearOrder=@YearOrder-1
										
										--最后一年,年折旧计算
										IF @YearOrder=@tempYears
											BEGIN
												SET @tempAVGYearValue=@Total-@tempDepTotal-@NetSalvage-@DevalueReady
												IF @RemainMonth%12<>0
													SET  @YearPeriod=@RemainMonth%12
											END
											
										--计算账面净值
										IF @YearOrder=@tempYears
											SET @NetValue=@NetSalvage
										ELSE 
											SET @NetValue=@NetValue-@tempAVGYearValue
										
										--计算累计折旧额
										SET @tempDepTotal=@tempDepTotal+@tempAVGYearValue
										
										 INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
										FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
										SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,@YearPeriod,
											   0,@CardID,LocationId,DisATypeId,@tempAVGYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
										FROM Ac_AssetsCards WHERE ID=@CardID 
									END
								ELSE 
									BEGIN
										--先取上一期的账面净值,因为双倍余额法不可能出现双倍算法到最后一期的情况，所以不用考虑最后一期
										SELECT @NetValue=NetValue FROM #Data WHERE YearOrder=@YearOrder-1
											
										--根据净值算年额度
										SET @tempDoubleYearValue=dbo.F_RoundTotal(@NetValue*@YearRate)
										SET @tempAVGYearValue=	dbo.F_RoundTotal((@NetValue-@NetSalvage)/@AVGYears)
										
										---取上一期年积累折旧额
										SELECT @tempDepTotal=DepTotal FROM #Data  WHERE YearOrder=@YearOrder-1
												
										--比较大小，看使用哪种方式
										IF (@tempDoubleYearValue<=@tempAVGYearValue) OR ((@NetValue-@tempDoubleYearValue)<@NetSalvage)    --符合转换条件，改用平均年限法
											BEGIN
												--计算累计折旧额
												SET @tempDepTotal=@tempDepTotal+@tempAVGYearValue
												
												--计算账面净值
												SET @NetValue=@NetValue-@tempAVGYearValue
										         
										         IF @YearOrder=@tempYears AND @RemainMonth%12<>0
													SET  @YearPeriod=@RemainMonth%12
										         		
												 INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
												FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
												SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,@YearPeriod,
													   0,@CardID,LocationId,DisATypeId,@tempAVGYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
												FROM Ac_AssetsCards WHERE ID=@CardID 
												
												SET @Flag=1         
											END
										ELSE 
											BEGIN
												 --计算累计折旧额
												SET @tempDepTotal=@tempDepTotal+@tempDoubleYearValue 
												
												--计算账面净值
												SET @NetValue=@NetValue-@tempDoubleYearValue
												
												INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
												FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
												SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,12,
													   0,@CardID,LocationId,DisATypeId,@tempDoubleYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
												FROM Ac_AssetsCards WHERE ID=@CardID 
											END
									END
								
								SET @YearOrder=@YearOrder+1
								SET @AVGYears=@AVGYears-1
							END
							
						----算月
						WHILE @tempYearOrder<=@tempYears
							BEGIN
								 --上期年净值，累计折旧额
								 SELECT @NetValue=NetValue,@tempDepTotal=deptotal FROM #Data WHERE YearOrder=@tempYearOrder-1
								 --本年的折旧额
								 SELECT @Depreciation=Depreciation FROM #Data WHERE YearOrder=@tempYearOrder
								 --月折旧额
								 IF (@tempYearOrder<>@tempYears OR  @RemainMonth%12=0 )
									SET @tempAVGMonthValue=dbo.F_RoundTotal(@Depreciation/12)
								 ELSE 
									SET @tempAVGMonthValue=dbo.F_RoundTotal(@Depreciation/(@RemainMonth%12))
								 
								 SET @LoopMonth=1
								 
								 IF (@tempYearOrder<>@tempYears OR  @RemainMonth%12=0 )
									BEGIN
										WHILE @LoopMonth<=12
											BEGIN
												--月折旧额
												IF @LoopMonth=12
													SET @AVGMonthValue=dbo.F_RoundTotal(@Depreciation-@tempAVGMonthValue*11)
												ELSE
													SET @AVGMonthValue=@tempAVGMonthValue
												
												--累计折旧额
												SET @tempDepTotal=@tempDepTotal+@AVGMonthValue
												
												--账面净值 
												SET @NetValue=@NetValue-@AVGMonthValue
												
												--年份，期间特殊处理
												IF @PeriodFlag=2
													BEGIN
														IF @tempFperiod>=12
															BEGIN
																SET @tempFperiod=1
																SET @tempFyear=@tempFyear+1
															END
														ELSE 
															SET @tempFperiod=@tempFperiod+1
													END
												ELSE
													BEGIN
														IF @tempMonthOrder<>1  --第一期就是fperiod当期,所以第2期起每期才+1
															BEGIN
																IF @tempFperiod>=12
																	BEGIN
																		SET @tempFperiod=1
																		SET @tempFyear=@tempFyear+1
																	END
																ELSE 
																	SET @tempFperiod=@tempFperiod+1
															END
													END		
													
												--插入数据
												INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
														FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
												SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@tempYearOrder,@tempMonthOrder,@tempFyear,@tempFperiod,
													   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
												FROM Ac_AssetsCards WHERE ID=@CardID 
												
												SET @LoopMonth=@LoopMonth+1
												SET @tempMonthOrder=@tempMonthOrder+1
											END	 
									END
								ELSE                       --最后一年且最后一年不满12个月的特殊处理
									BEGIN
											DECLARE @tempM INT
											SET @tempM=@RemainMonth%12
											
											WHILE @LoopMonth<=@tempM
												BEGIN
													--月折旧额
													IF @LoopMonth=@tempM
														SET @AVGMonthValue=@Depreciation-dbo.F_RoundTotal(@tempAVGMonthValue*(@tempM-1))
													ELSE
														SET @AVGMonthValue=@tempAVGMonthValue
													
													--累计折旧额
													SET @tempDepTotal=@tempDepTotal+@AVGMonthValue
													
													--账面净值 
													SET @NetValue=@NetValue-@AVGMonthValue
													
													--年份，期间特殊处理
													IF @PeriodFlag=2
													BEGIN
														IF @tempFperiod>=12
															BEGIN
																SET @tempFperiod=1
																SET @tempFyear=@tempFyear+1
															END
														ELSE 
															SET @tempFperiod=@tempFperiod+1
													END
												ELSE
													BEGIN
														IF @tempMonthOrder<>1  --第一期就是fperiod当期,所以第2期起每期才+1
															BEGIN
																IF @tempFperiod>=12
																	BEGIN
																		SET @tempFperiod=1
																		SET @tempFyear=@tempFyear+1
																	END
																ELSE 
																	SET @tempFperiod=@tempFperiod+1
															END
													END		
														
													--插入数据
													INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
															FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
													SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@tempYearOrder,@tempMonthOrder,@tempFyear,@tempFperiod,
														   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
													FROM Ac_AssetsCards WHERE ID=@CardID 
													
													SET @LoopMonth=@LoopMonth+1
													SET @tempMonthOrder=@tempMonthOrder+1
												END
									END
									
								SET @tempYearOrder=@tempYearOrder+1
							END
					END
					
			END
-------------------未计提折旧过
		ELSE      
			BEGIN
				--先算年
				WHILE @YearOrder<=@DurYear
					BEGIN
						IF @Flag=1   --已经是平均年限法了
							BEGIN
								----modify bug 2013.10.12  平均改双倍，重算，#data里没有数据
								--IF NOT EXISTS(SELECT TOP 1 1 FROM #Data)
								--	SELECT @NetValue=NetValue,@tempDepTotal=DepTotal FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND YearOrder=0
								--ELSE 
								--先取上一期的账面净值,累计折旧额
								SELECT @NetValue=NetValue,@tempDepTotal=DepTotal FROM #Data WHERE YearOrder=@YearOrder-1
								
								--最后一年,年折旧计算
								IF @YearOrder=@DurYear
									SET @tempAVGYearValue=@Total-@tempDepTotal-@NetSalvage-@DevalueReady
									
								--计算账面净值
								IF @YearOrder=@DurYear
									SET @NetValue=@NetSalvage
								ELSE 
									SET @NetValue=@NetValue-@tempAVGYearValue
								
								--计算累计折旧额
								SET @tempDepTotal=@tempDepTotal+@tempAVGYearValue
								
								 INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
								FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
								SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,12,
									   0,@CardID,LocationId,DisATypeId,@tempAVGYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
								FROM Ac_AssetsCards WHERE ID=@CardID 
							END
						ELSE 
							BEGIN
								--modify bug 2013.10.12  平均改双倍，重算，#data里没有数据
								--IF NOT EXISTS(SELECT TOP 1 1 FROM #Data)
								--	SELECT @NetValue=NetValue FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND YearOrder=0
								--ELSE 
								--先取上一期的账面净值,因为双倍余额法不可能出现双倍算法到最后一期的情况，所以不用考虑最后一期
								SELECT @NetValue=NetValue FROM #Data WHERE YearOrder=@YearOrder-1
									
								--根据净值算年额度
								SET @tempDoubleYearValue=dbo.F_RoundTotal(@NetValue*@YearRate)
								SET @tempAVGYearValue=	dbo.F_RoundTotal((@NetValue-@NetSalvage)/@AVGYears)
								
								--modify bug 2013.10.12  平均改双倍，重算，#data里没有数据
								IF NOT EXISTS(SELECT TOP 1 1 FROM #Data)
									SELECT @tempDepTotal=DepTotal FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND YearOrder=0
								ELSE 
								---取上一期年积累折旧额
								SELECT @tempDepTotal=DepTotal FROM #Data  WHERE YearOrder=@YearOrder-1
										
								--比较大小，看使用哪种方式
								IF (@tempDoubleYearValue<=@tempAVGYearValue) OR ((@NetValue-@tempDoubleYearValue)<@NetSalvage)    --符合转换条件，改用平均年限法
									BEGIN
										--计算累计折旧额
										SET @tempDepTotal=@tempDepTotal+@tempAVGYearValue
										
										--计算账面净值
										SET @NetValue=@NetValue-@tempAVGYearValue
										
										 INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
										FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
										SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,12,
											   0,@CardID,LocationId,DisATypeId,@tempAVGYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
										FROM Ac_AssetsCards WHERE ID=@CardID 
										
										SET @Flag=1         
									END
								ELSE 
									BEGIN
										 --计算累计折旧额
										SET @tempDepTotal=@tempDepTotal+@tempDoubleYearValue 
										
										--计算账面净值
										SET @NetValue=@NetValue-@tempDoubleYearValue
										
										INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
										FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
										SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,12,
											   0,@CardID,LocationId,DisATypeId,@tempDoubleYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
										FROM Ac_AssetsCards WHERE ID=@CardID 
									END
							END
						
						SET @YearOrder=@YearOrder+1
						SET @AVGYears=@AVGYears-1
					END
					
				----算月的
				WHILE @tempYearOrder<=@DurYear
					BEGIN
						  --上期年净值，累计折旧额
						  SELECT @NetValue=NetValue,@tempDepTotal=deptotal FROM #Data WHERE YearOrder=@tempYearOrder-1
						  
						  --本年的折旧额
						  SELECT @Depreciation=Depreciation FROM #Data WHERE YearOrder=@tempYearOrder
				          --月折旧额
				          SET @tempAVGMonthValue=dbo.F_RoundTotal(@Depreciation/12)
				          
				          SET @LoopMonth=1
				          
				          WHILE @LoopMonth<=12
							BEGIN
								--月折旧额
								IF @LoopMonth=12
									SET @AVGMonthValue=@Depreciation-dbo.F_RoundTotal(@tempAVGMonthValue*11)
								ELSE
									SET @AVGMonthValue=@tempAVGMonthValue
								
								--累计折旧额
								SET @tempDepTotal=@tempDepTotal+@AVGMonthValue
								
								--账面净值 
								SET @NetValue=@NetValue-@AVGMonthValue
								
								--年份，期间特殊处理
								IF @PeriodFlag=2
									BEGIN
										IF @tempFperiod>=12
											BEGIN
												SET @tempFperiod=1
												SET @tempFyear=@tempFyear+1
											END
										ELSE 
											SET @tempFperiod=@tempFperiod+1
									END
								ELSE
									BEGIN
										IF @tempMonthOrder<>1  --第一期就是fperiod当期,所以第2期起每期才+1
											BEGIN
												IF @tempFperiod>=12
													BEGIN
														SET @tempFperiod=1
														SET @tempFyear=@tempFyear+1
													END
												ELSE 
													SET @tempFperiod=@tempFperiod+1
											END
									END		
									
								--插入数据
								INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
										FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
								SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@tempYearOrder,@tempMonthOrder,@tempFyear,@tempFperiod,
									   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
								FROM Ac_AssetsCards WHERE ID=@CardID 
								
								SET @LoopMonth=@LoopMonth+1
								SET @tempMonthOrder=@tempMonthOrder+1
							END	 
						SET @tempYearOrder=@tempYearOrder+1
					END
			END
			
			--------按照新需求重新算年次，并且重算
			UPDATE d SET yearorder=t.yearorder FROM #Data d
			JOIN (SELECT fyear,ROW_NUMBER() OVER (ORDER BY fyear) AS yearorder FROM #Data WHERE plantype=1 GROUP BY fyear ) t
			ON d.fyear=t.fyear
			WHERE plantype=1
			
			--重算年
			DELETE FROM #Data WHERE plantype=0
			
			 ;WITH t AS 
			(
				SELECT AssetCardId,YearOrder,SUM(Depreciation) AS Depreciation,COUNT(*) AS fperiod,fyear,MAX(MonthOrder) AS MonthOrder
				FROM #Data	WHERE PlanType=1 GROUP BY AssetCardId,YearOrder,FYear	
			)
			INSERT INTO #Data(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
							FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
			SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,t.YearOrder,NULL,t.FYear,t.fperiod,
							   0,n.AssetCardId,LocationId,DisATypeId,t.Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,0 
			FROM t 
			JOIN #Data n ON t.YearOrder=n.YearOrder AND t.MonthOrder=n.MonthOrder 
	END

 
 
---写入数据到表中
IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID) 
		DELETE dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND plantype<>2  --必须是plantype<>2
		
INSERT INTO dbo.Ac_DepreciationPlan
         (STypeId,
          DTypeid,
          CategoryId,
          InAccountDate,
          UserCode,
          FullName,
          DepreciationMean,
          YearOrder,
          FYear,
          fperiod,
          MonthOrder,
          PlanType,
          AssetCardId,
          LocationId,
          DisATypeId,
          DepTotal,
          Total,
          DevalueReady,
          NetValue,
          NetSalvage,
          PlanState,
          Depreciation,
          BillNumberId)
SELECT STypeId,
          DTypeid,
          CategoryId,
          InAccountDate,
          UserCode,
          FullName,
          DepreciationMean,
          YearOrder,
          FYear,
		  FPeriod,
		  MonthOrder, 
		  PlanType,
          AssetCardId,
          LocationId,
          DisATypeId,
          dbo.F_RoundTotal(DepTotal),
          dbo.F_RoundTotal(Total),
          DevalueReady,
          dbo.F_RoundTotal(NetValue),
          dbo.F_RoundTotal(NetSalvage),
          PlanState,
          dbo.F_RoundTotal(Depreciation),
          0	 
FROM #Data ORDER BY PlanType,MonthOrder
 
DROP TABLE #Data

IF @DepreciationMean=4
BEGIN
/*---卡片参数
		@CardNetValue		 NUMERIC(24, 10) ,
		@DepreciationMean	INT,
        @DepreciationMonth	INT,             --已折旧月份
        @Depreciation		 NUMERIC(24, 10) ,
        @YearRate			 NUMERIC(24, 10) ,
        @DurYear			INT,			 --折旧年限的总年数
        @DevalueReady		 NUMERIC(24, 10) ,  --当前卡片的减值准备
		@DepTotal            NUMERIC(24, 10) ,	 --卡片上的累计折旧额
        @Total				 NUMERIC(24, 10) ,  --原值
		@NetValue			 NUMERIC(24, 10) ,  --净值
		@NetSalvage			 NUMERIC(24, 10) ,  --净残值
		
-----辅助参数
		@tempFyear INT=CONVERT(INT,@FYear),   --年份
		@tempFperiod int=@FPeriod,			--期间
		@YearOrder  INT=-1,      --当期期的年次
		@MonthOrder INT=-1,      --当前期的月次
		@PlanState  INT       --当前期是否折旧
		@tempYearOrder	INT		--年次
		@tempMonthOrder	INT	 -- 月次
		@tempDepTotal		 NUMERIC(24, 10)     --折旧额
*/
	DECLARE  @PlanMonthOrder INT    --还将折旧月次
			,@PlanNetVale	 NUMERIC(24, 10)    --还将折旧额
			,@MonthNetVale	 NUMERIC(24, 10)    --每月账面净值
			,@tempYearDepRate  NUMERIC(24, 10)     --每年次的年折旧率
			,@tempYearDep		 NUMERIC(24, 10)     --年折旧额
			,@tempMonthDep		 NUMERIC(24, 10)     --月折旧额
			,@tempMonthDepTotal		 NUMERIC(24, 10)     --月累计折旧额
			,@tempMonthCount	INT   --当前年的期间数量
			,@tempCardUsedFyear	INT  --卡片使用每年年份
			,@tempCardUsedFPeriod	INT  --卡片使用的每年中的期间
			,@tempYear	INT		--当前使用年度
			,@tempCurrentYearDep	 NUMERIC(24, 10)  --当前年份折旧额
			,@MonthLoop		INT		--月循环数
			,@currentDepTotal	 NUMERIC(24, 10)   -- 已累积折旧额
			,@isCheck			INT --是否要检测  0：是  1：否
			
	SET @PlanMonthOrder = @DurYear * 12 
	SELECT @PlanNetVale = ISNULL(NetValue - NetSalvage + DepTotal,0),@currentDepTotal = DepTotal FROM Ac_AssetsCards WHERE ID = @CardID
	
	SET @isCheck = 1	
	SET	@tempFyear =CONVERT(INT,@FYear) 
	SET	@tempCardUsedFyear =CONVERT(INT,@FYear)  
	SET	@tempFperiod =@FPeriod
	SET @tempCardUsedFPeriod = @FPeriod
	SET @tempYear = 1
	SET @tempYearOrder = 1
	SET @tempMonthOrder = 1	
	SET @tempMonthCount = 0 
	SET @tempMonthDepTotal = @DepTotal
	SET @tempCurrentYearDep = 0
	SET @MonthNetVale = @PlanNetVale  --第一个月的账面初始值，后面在月计划循环中减去当月折旧后，才是月账面净值
	
	-------------已折旧的，根据折旧月数反推对应的起始年份和期间，方便下面模拟数据进行累积折旧额的检测------------------
	IF @DepreciationMonth > 0
	BEGIN
		SET @isCheck = 0
		SET @tempCardUsedFyear -= CEILING((@DepreciationMonth-@tempCardUsedFPeriod + 0.0000000000)/12)
		SET @tempCardUsedFPeriod = 12-(@DepreciationMonth-@tempCardUsedFPeriod)%12
	END
		
	-------------新增固定资产方式入账的卡片，从下一期开始生成折旧计划-------------------
	IF @PeriodFlag = 2
		SET	@tempCardUsedFPeriod += 1
	
	--------------当前期间大于12，则说明下一年度才开始折旧了----------------------------
	IF @tempCardUsedFPeriod > 12
	BEGIN
		SET @tempCardUsedFPeriod = 1
		SET @tempCardUsedFyear += 1
	END
	
	---------------以预计的使用年数为基准进行循环，从而生成计划表---------------------	
	WHILE @tempYear <= @DurYear
	BEGIN
		-------------年数据计算-------------
		SET @tempYearDepRate = (@DurYear + 1 - @tempYear)/(@DurYear * (@DurYear + 1) / 2 + 0.0000000000)      --计算年折旧率
		SET @tempYearDep = dbo.F_RoundTotal(@PlanNetVale * @tempYearDepRate)  --计算年折旧额
		
		------------月循环参数--------------
		SET @MonthLoop = 1
		SET @tempMonthDep = dbo.F_RoundTotal(@tempYearDep / 12)   --用年折旧额除以该年总月次得到月折旧额
		
		------------月循环--------------
		WHILE @MonthLoop <= 12 AND @tempMonthOrder <= @PlanMonthOrder
		BEGIN
			-------------月数据计算-------------
			SET @tempMonthDepTotal += @tempMonthDep   --计算月累计折旧额
			SET @tempCurrentYearDep += @tempMonthDep   --计算当前年份折旧额
			SET @MonthNetVale -= @tempMonthDep   --计算月账面净值
			
			----------插入新的月折旧计划---------
			INSERT INTO Ac_DepreciationPlan(
					STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
			SELECT	STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,4,@tempYearOrder,@tempMonthOrder,@tempCardUsedFyear,@tempCardUsedFPeriod,1,n.id,LocationId,DisATypeId,dbo.F_RoundTotal(@tempMonthDep),dbo.F_RoundTotal(@tempMonthDepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(@MonthNetVale),dbo.F_RoundTotal(NetSalvage),0 
			FROM Ac_AssetsCards n
			WHERE n.Id = @CardID 
		
			----------月循环参数更新------------
			SET @tempCardUsedFPeriod += 1		--期间加1			
			SET @tempMonthCount +=1		--年月数加1
			SET @MonthLoop += 1  --月循环次数加1
			SET @tempMonthOrder += 1   --月次加1

			----------期间大于12或是到最后一个月次时,更新参数,插入年计划------------
			IF @tempCardUsedFPeriod > 12 OR @tempMonthOrder > @PlanMonthOrder		--期间大于12，则从1开始，且卡片使用年份也要加1;月次数达到总月次数时，计算一次年计划
			BEGIN
				----------插入年计划---------
				INSERT INTO Ac_DepreciationPlan(
						STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
				SELECT	STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,4,@tempYearOrder,NULL,@tempCardUsedFyear,@tempMonthCount,0,n.id,LocationId,DisATypeId,dbo.F_RoundTotal(@tempCurrentYearDep),dbo.F_RoundTotal(@tempMonthDepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(@MonthNetVale),dbo.F_RoundTotal(NetSalvage),0 
				FROM Ac_AssetsCards n
				WHERE n.Id = @CardID 
				
				----------更新参数---------
				SET @tempCurrentYearDep = 0
				SET @tempMonthCount = 0
				SET @tempCardUsedFPeriod = 1
				SET @tempCardUsedFyear +=1
				SET @tempYearOrder +=1	--年次加1
			END
		
			------------已计提折旧过的，在此检测计提的累积折旧额与计划表是否一致----------------
			IF @isCheck = 0 AND @DepreciationMonth > 0 AND @tempMonthOrder-1 = @DepreciationMonth
			BEGIN
				SET @isCheck = 1
				SET @tempMonthOrder = 1	
				DELETE FROM Ac_DepreciationPlan WHERE AssetCardId = @CardID
				
				------------一致：接着算----------------
				IF CAST(@currentDepTotal AS INT) = CAST(@tempMonthDepTotal AS INT)
				BEGIN
					SET @PlanMonthOrder -= @DepreciationMonth
				END
				------------不一致：从头再算----------------
				ELSE
				BEGIN
					SELECT @PlanNetVale = ISNULL(NetValue - NetSalvage,0) FROM Ac_AssetsCards WHERE ID = @CardID
						
					SET	@tempFyear =CONVERT(INT,@FYear) 
					SET	@tempCardUsedFyear =CONVERT(INT,@FYear)  
					SET	@tempFperiod =@FPeriod
					SET @tempCardUsedFPeriod = @FPeriod
					SET @tempYear = 0
					SET @tempYearOrder = 1
					SET @tempMonthCount = 0 
					SET @tempMonthDepTotal = @DepTotal
					SET @tempCurrentYearDep = 0
					SET @MonthNetVale = @PlanNetVale  
		
					IF @PeriodFlag = 2
						SET	@tempCardUsedFPeriod += 1
					
					IF @tempCardUsedFPeriod > 12
					BEGIN
						SET @tempCardUsedFPeriod = 1
						SET @tempCardUsedFyear += 1
					END
					
					BREAK
				END
				
				
			END
		
		
		END
		
		-----------主循环参数更新-------------
		
		SET @tempYear +=1	--年度加1
		
	END
	
	----------------先插入一条期初数据,plantype=2----------------------------
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=2)
			INSERT INTO Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
									FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,
									DevalueReady,NetValue,NetSalvage,PlanState)
			SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,0,0,
									@FYear,@FPeriod,2,@CardID,LocationId,DisATypeId,0,dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),0 
			FROM dbo.Ac_AssetsCards WHERE ID=@CardID
	
END
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	

 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE     PROCEDURE Gp_CreateId 
( 
	@Parid 		[VARCHAR](50),
	@DbName 	[VARCHAR](30),
	@CreatedId 	[VARCHAR](50) OUTPUT,
	@nSon 		INT out,
	@nCount 	INT out
)
--@encode$--
AS
SET NOCOUNT ON

IF LEN(@Parid)=50	RETURN -1

DECLARE @SysWsdValue VARCHAR(200),@ChValue INT

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 6 AND SubValue = '1')
BEGIN
	SELECT @SysWsdValue = SubValue FROM dbo.sysdata WHERE SubName = 'wsd'
	SELECT @ChValue = dbo.F_GetIsValidIData(@SysWsdValue)	
	IF @ChValue = 0
	BEGIN
		RETURN -1
	END
END

DECLARE @execsql	VARCHAR(500)
DECLARE @szTypeId	VARCHAR(50),
		@sonnum		INT,
		@par		VARCHAR(50),
		@soncount	INT

SELECT @execsql='
	DECLARE checkid_CURSOR CURSOR FOR 	
		SELECT 	typeid,
				sonnum,
				parid,
				soncount 
		FROM 	'+@dbname+' 
		WHERE 	typeid= '+''''+@parid+''''

--PRINT(@execsql)
EXEC (@execsql)

--检查游标是否存在（上面有情况会查不出来数据!）
IF cursor_status('global','checkid_CURSOR')=-3 and cursor_status('local','checkid_CURSOR')=-3
BEGIN
	--不存在该游标直接返回
	Return -2
END

OPEN checkid_CURSOR

FETCH NEXT FROM checkid_CURSOR INTO @szTypeId, @sonnum, @par,@soncount

SELECT @nSon=@sonnum
SELECT @nCount=@soncount
DECLARE @SQL NVARCHAR(MAX)

IF  @@FETCH_STATUS = -1
	BEGIN
		CLOSE checkid_CURSOR
		DEALLOCATE checkid_CURSOR
		RETURN -1
	END 
ELSE
	BEGIN
		DECLARE @tempId 	VARCHAR(5),
				@nReturn 	INT
		SELECT @soncount=@soncount+1
		EXEC @nReturn=inttostr @soncount,@tempId out
		IF @nReturn=-1  
			BEGIN
				CLOSE checkid_CURSOR
				DEALLOCATE checkid_CURSOR
				RETURN -2
			END 
		ELSE
			BEGIN
				IF @sztypeid='00000' 
					SELECT @createdid=@tempId			
				ELSE 
					SELECT @createdid=RTRIM(@szTypeid)+@tempId
			END
			
		/*检测新的typeid是否重复,如果重复就加1,直到生成一个不重复的typeid---------开始*/
		SET @SQL='
			DECLARE @newtempId 	VARCHAR(50)
			
			SET @NewTypeid=@inicreatedid  /*用输入参数初始化@NewTypeid*/
			SET @NewSoncount=@inisoncount
			WHILE(EXISTS(SELECT TOP 1 1 FROM '+@DbName+' WHERE typeid=@NewTypeid ))
			BEGIN
				SET @NewSoncount=@NewSoncount+1
				EXEC inttostr @NewSoncount,@newtempId out
				
				IF '''+@sztypeid+'''=''00000'' 
					SET @NewTypeid=@newtempId			
				ELSE 
					SET @NewTypeid=RTRIM('''+@szTypeid+''')+@newtempId
			END
			'
			
		 EXECUTE SP_EXECUTESQL
					@SQL,
					N'@NewTypeid VARCHAR(50) OUTPUT,@NewSoncount INT OUTPUT,
							@inicreatedid VARCHAR(50) ,@inisoncount INT ',
					@createdid OUTPUT,	/*输出参数(修改后的值)*/
					@soncount OUTPUT,	/*输出参数(修改后的值)*/
					@createdid ,	/*输入参数(原值)*/
					@soncount		/*输入参数(原值)*/
		/*检测新的typeid是否重复,如果重复就加1,直到生成一个不重复的typeid---------结束*/

	END
 
 SELECT @nCount=@soncount-1 --因为在基本信息插入存储过程中会加1 所以这里先减1 不然soncount 会多1
 SELECT @CreatedId=@createdid
 
 CLOSE checkid_CURSOR
 DEALLOCATE checkid_CURSOR


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_CreateId_AcItem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_CreateId_AcItem]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_items 最新项目ID
-- 时间：	2013-01-30
-- 作者：	GLJ
-- ========================================================================
CREATE PROCEDURE Gp_CreateId_AcItem 
( 
	@Parid 		[VARCHAR](50),
	@DbName 	[VARCHAR](30),
	@CreatedId 	[VARCHAR](50) OUTPUT,
	@nSon 		INT out,
	@nCount 	INT out
)
--@encode$--
AS
SET NOCOUNT ON

IF LEN(@Parid)=50	RETURN -1

IF NOT EXISTS(SELECT * FROM Ac_Items WHERE nTypeId=@Parid)
	RETURN -2

SELECT @CreatedId=nTypeId+REPLICATE('0',5-LEN(SonCount+1))+CAST(SonCount+1 AS VARCHAR(5)),@nSon=SonNum,@nCount=SonCount FROM Ac_Items WHERE nTypeId=@Parid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	功能说明：	影响 BType、AType 数据表中的应收应付数据
				引用存储过程 Gp_ModifyDbf
	作    者：	卢    春
	最后修改：	2004-06-08
*/
CREATE               PROCEDURE Gp_CreateManageRep
(
	@nBillID	numeric(10,0),	-- 单据编号 ID 值
	@nBillType	INT
)
--@encode$--
AS
SET NOCOUNT ON

-- Some vchtype
DECLARE	@GOODS_ID				varchar(50),
		@CASH_ID				varchar(50),
		@CASH_BANK_ID 			varchar(50),
		@AR_ID					varchar(50),
		@AP_ID					varchar(50),
		@YF_ID					varchar(50),
		@YS_ID					varchar(50),
		@GOODS_LOSS_ID			varchar(50),
		@GOODS_GET_ID			varchar(50),
		@ALLOT_PRICE_ID			varchar(50),
		@PRICE_INCOME_ID		varchar(50),
		@BORROW_BUY_PRICE_ID	varchar(50),
		@GOODS_GIVE_ID			varchar(50),
		@GOODS_PRODUCE_ID		varchar(50),
		@SALE_COST_ID			varchar(50),
		@SALE_INCOME_ID			varchar(50),
		@LEND_GOODS_ID			varchar(50),
		@BORROW_GOODS_ID		varchar(50),
		@BALANCE_ID				varchar(50),
		@DEPRECIATION_ID		varchar(50),
		@APPORTION_EXPENSE_ID	varchar(50),
		@INIT_MONEY_ID			varchar(50),
		@ALL_INCOME_ID			varchar(50),
		@ALL_EXPENSE_ID			varchar(50),
		@PROFIT_ID				varchar(50),
		@ASSETS_ID				varchar(50),
		@DEBT_ID				varchar(50),
		@POWER_ID				varchar(50),
		@ADDEBT_INCOME_ID		varchar(50),
		@ADDEBT_LOSE_ID			varchar(50),
		@GRIR_ID				VARCHAR(50),
		@FC_ID					VARCHAR(50)		

--SET @GOODS_ID				= '0000100001'				-- 『库存商品总值合计』
--SET @CASH_ID				= '0000100003'				-- 现    金
--SET @CASH_BANK_ID			= '0000100004'				-- 『全部银行存款合计』
--SET @AR_ID					= '0000100005'				-- 『应收款合计』
--SET @AP_ID					= '0000200001'				-- 『应付帐款合计』
--SET @GOODS_LOSS_ID			= '000040000200001'			-- 商品报损支出
--SET @GOODS_GET_ID			= '000030000200001'			-- 商品报溢收入
--SET @ALLOT_PRICE_ID			= '000030000200005'			-- 变价调拨差价
--SET @PRICE_INCOME_ID		= '000030000200003'			-- 成本调价收入
--SET @GOODS_PRODUCE_ID		= '000030000200006'			-- 商品拆装差价
--SET @SALE_COST_ID			= '0000400001'				-- 『销售成本』
--SET @SALE_INCOME_ID			= '0000300001'				-- 『销售收入』
--SET @BALANCE_ID				= '000030000200004'			-- 进货退货差价
--SET @DEPRECIATION_ID		= '000040000300002'			-- 固定资产折旧
--SET @APPORTION_EXPENSE_ID	= '0000100007'				-- 『待摊费用』
--SET @ALL_INCOME_ID			= '00003'					-- 【收入类】
--SET @ALL_EXPENSE_ID			= '00004'					-- 【支出类】
--SET @ASSETS_ID				= '00001'					-- 【资产合计】
--SET @DEBT_ID				= '00002'					-- 【负债合计】
--SET @ADDEBT_INCOME_ID		= '000030000300001'			-- 调帐收入
--SET @ADDEBT_LOSE_ID			= '000040000300001'			-- 调帐亏损R
--SELECT @YF_ID				= '0000100009'			--预付账款
--SELECT @YS_ID				= '0000200006'			--预收账款

SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』
SELECT @CASH_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1001'			-- 现    金
SELECT @AR_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '987'			-- 『应收款合计』
SELECT @AP_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2121'			-- 『应付帐款合计』
SELECT @GOODS_LOSS_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0421'		-- 商品报损支出
SELECT @GOODS_GET_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0321'		-- 商品报溢收入
SELECT @ALLOT_PRICE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0325'		-- 变价调拨差价
SELECT @PRICE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0323'		-- 成本调价收入
SELECT @GOODS_PRODUCE_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0326'		-- 商品拆装差价
SELECT @SALE_COST_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5401'			-- 『销售成本』
SELECT @SALE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5101'			-- 『销售收入』
SELECT @BALANCE_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '0324'		-- 采购退货差价
SELECT @DEPRECIATION_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0432'		-- 固定资产折旧
SELECT @APPORTION_EXPENSE_ID	=nid FROM dbo.Ac_Items WHERE UserCode =  '1301'			-- 『待摊费用』
SELECT @ADDEBT_INCOME_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '03333'		-- 调帐收入
SELECT @ADDEBT_LOSE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0431'		-- 调帐亏损
SELECT @YF_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1151'			--预付账款
SELECT @YS_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2131'			--预收账款

SELECT 	@FC_id					=nid FROM dbo.Ac_Items WHERE UserCode =  '1251'			--发出商品
SELECT 	@GRIR_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '2122'			--应付暂估



DECLARE	@DBName				varchar(30),
		@nCostingMethod 	smallint,
		@tBillDate			datetime,
		@nBillNumberID		numeric(10,0),
		@szATypeID			varchar(50),
		@szPTypeID			varchar(50),
		@szBTypeID			varchar(50),
		@szETypeID			varchar(50),
		@szStockID			varchar(50),
		@szStockID2			varchar(50),
		@szATypeIDTemp		varchar(50),
		@szPTypeIDTemp		varchar(50),
		@szBTypeIDTemp		varchar(50),
		@szETypeIDTemp		varchar(50),
		@szKTypeIDTemp		varchar(50),
		@szSTypeIDTemp		varchar(50),
		@szIfCheck			char(1),
		@nPeriod			int,
		@szJobNumber		varchar(20),
		@OutFactoryDate		datetime,
		@dPrice				 NUMERIC(24, 10) ,
		@dTotal				 NUMERIC(24, 10) ,
		@dQty				 NUMERIC(24, 10) ,
		@dCostPrice			 NUMERIC(24, 10) ,
		@dCostTotal			 NUMERIC(24, 10) ,
		@nGoodsNo			int,
		@dCostPriceOut		 NUMERIC(24, 10) ,
		@dTemp				 NUMERIC(24, 10) ,
		@dPriceTemp			 NUMERIC(24, 10) ,
		@dntotal			 NUMERIC(24, 10) ,
		@cid				INT,
		@nRet				smallint

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@szSTypeIDTemp, @nCostingMethod output

-- begin tran Rep_Trans
DECLARE Manage_Cursor CURSOR FOR
	SELECT	BillNumberID,
			ATypeID,
			PTypeID,
			BTypeID,
			ETypeID,
			KTypeID,
			STypeID,
			Qty,
			Price,
			Total,
			CostPrice,
			CostTotal,
			JobNumber,
			GoodsNo,
			OutFactoryDate,
			Ntotal,
			CID
	FROM	ListTable
	WHERE	BillNumberID = @nBillID
			AND BillType=@nBillType
			AND Audited = 0
	FOR UPDATE

OPEN Manage_Cursor
FETCH NEXT FROM Manage_Cursor INTO	@nBillNumberID,
									@szATypeIDTemp,
									@szPTypeIDTemp,
									@szBTypeIDTemp,
									@szETypeIDTemp,
									@szKTypeIDTemp,
									@szSTypeIDTemp,
									@dQty,
									@dPrice,
									@dTotal,
									@dCostPrice,
									@dCostTotal,
									@szJobNumber,
									@nGoodsNo,
									@OutFactoryDate,
									@dntotal,
									@cid

WHILE @@FETCH_STATUS <> -1
BEGIN
	EXEC @nRet = Gp_ModifyDbf	@nBillType,
								@nCostingMethod,
								@szATypeIDTemp,
								@szPTypeIDTemp,
								@szBTypeIDTemp,
								@szETypeIDTemp,
								@szKTypeIDTemp,
								@szSTypeIDTemp,
								'',
								@dQty,
								@dTotal,
								@dntotal,
								@cid,
								@szJobNumber,
								@nGoodsNo,
								'',
								'',
								'',
								0,
								0,
								@dCostPriceOut output
	IF @nRet <> 0
	BEGIN
		GOTO ERROR1
	END
	IF @szATypeIDTemp = @AP_ID OR @szATypeIDTemp = @AR_ID OR @szATypeIDTemp=@YS_ID OR @szATypeIDTemp=@YF_ID OR @szATypeIDTemp=@FC_id OR @szATypeIDTemp=@GRIR_ID
	BEGIN
		EXEC @nRet = Gp_ModifyDbf	@nBillType,
									@nCostingMethod,
									@szATypeIDTemp,
									'0',
									'0',
									'0',
									'0',
									@szSTypeIDTemp,
									'',
									@dQty,
									@dTotal,
									@dntotal,
									@cid,
									@szJobNumber,
									@nGoodsNo,
									'',
									'',
									'',
									0,
									0,
									@dCostPriceOut output

		IF @nRet <> 0
		BEGIN
			GOTO ERROR1
		END
	END

	-- 更新会计凭证数据表，改变其状态：草稿 -> 过账有效
	UPDATE	ListTable
	SET		Audited = 1
	WHERE CURRENT OF Manage_Cursor

	FETCH NEXT FROM Manage_Cursor INTO	@nBillNumberID,
										@szATypeIDTemp,
										@szPTypeIDTemp,
										@szBTypeIDTemp,
										@szETypeIDTemp,
										@szKTypeIDTemp,
										@szSTypeIDTemp,
										@dQty,
										@dPrice,
										@dTotal,
										@dCostPrice,
										@dCostTotal,
										@szJobNumber,
										@nGoodsNo,
										@OutFactoryDate,
										@dntotal,
										@cid
END

CLOSE Manage_Cursor
DEALLOCATE Manage_Cursor
-- commit tran Rep_Trans
RETURN 0

ERROR1:
	CLOSE Manage_Cursor
	DEALLOCATE Manage_Cursor
	-- if @@trancount<>0 rollback tran Rep_Trans
	-- print @nret
	RETURN @nRet


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		创建菜单项 (同时匹配软件狗版本号)
-- 最后修改作者：	谢吉康
-- 最后修改时间：	2011-03-17
-- 插件菜单更改：   王涛 2013-09-10
-- exec Gp_CreateMenuItemForAsp @chvoperator=N'0000100001',@intParentId=500,@intValue=163855,@enableplug=0
-- ========================================================================
CREATE PROCEDURE Gp_CreateMenuItemForAsp
(
	@chvOperator	VARCHAR(100),	-- 操作员 ID 值
	@intParentID	INT,			-- 父节点 ID 值
	@intValue		INT	,			-- 软件狗 DLL 通过 ASP 控件返回的加密字串	
    @enablePlug int  --1启用 0不启用  --插件添加
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断软件狗版本号 - Start	********
DECLARE @N INT, @intVersion_ASP INT, @intVersion_SQL INT
-- 判断数据表 SysData1 中的版本号
SELECT	@N = CAST(SubValue AS INT)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN 1688

DECLARE @intBit INT, @intMask INT
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion_SQL = ( @intMask & @N ) / POWER(2,@intBit)

-- 解密加密字串的软件狗版本号
SELECT @intBit = @intValue & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion_ASP = ( @intMask & @intValue ) / POWER(2,@intBit)

IF @intVersion_ASP <> @intVersion_SQL RETURN -1
-- ********	判断软件狗版本号 - END	********

IF NOT EXISTS(
	SELECT	1
	FROM	LoginUser
	WHERE	ETypeID = @chvOperator
)
RETURN 1	-- 操作员不存在 

DECLARE @btypeid VARCHAR(MAX),@sysid CHAR(1),@lim VARCHAR(MAX)
SELECT @sysid=SysID,@btypeid=BtypeID,@lim=Lim FROM Loginuser WHERE etypeid=@chvOperator


DECLARE @sql VARCHAR(MAX),@lx INT,@start INT
DECLARE @sqlm VARCHAR(MAX),@sqln VARCHAR(MAX),@sqlo VARCHAR(MAX)
DECLARE @checkSerial INT

-----检查是否可使用序列号-----
IF EXISTS(SELECT SubNo FROM sysdata WHERE SubName='Edition' AND (SubValue=2 OR SubValue=5 OR SubValue=7 OR SubValue = 8))
	SET @checkSerial=1
ELSE
	SET @checkSerial=0
	
IF @checkSerial=1
	IF  EXISTS(SELECT SubNo FROM sysdata1 WHERE SubName='OffLine' AND (SubValue=4 OR SubValue=5 OR SubValue = 6 OR SubValue = 7 OR SubValue=10 OR SubValue=11))
		SET @checkSerial=1
	ELSE
		SET @checkSerial=0
----------------------------------------------------------------------
SELECT @sqln=''
SELECT @sqlo=''

-- 谢吉康  2005-1-18 判断是否采用了“采用分支机构预设售价管理”
DECLARE @sqlG varchar(MAX)
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BatchPrePriceManage' AND Value = 1)
	SELECT @sqlG = ' offset NOT IN (484) '
ELSE
	SELECT @sqlG=' 1=1'	

IF @sysid=1
	IF @checkSerial=0
		SELECT @sqlm=' offset NOT IN (226,227,228,427)'
	ELSE
		SELECT @sqlm=' 1=1'
ELSE
	BEGIN
		IF @checkSerial=0
			SELECT @sqlm=' SUBSTRING('''+@Lim+''',offset,1)=''1'' AND offset NOT IN (226,227,228,427)'
		ELSE
			SELECT @sqlm= ' SUBSTRING('''+@Lim+''',offset,1)=''1'''

		SELECT @sqln=' OR menuid IN (SELECT a.menuid FROM webmenu a INNER JOIN (SELECT parentid FROM webmenu WHERE sysid=0 AND '+@sqlm+') b ON a.menuid=b.parentid)'
		SELECT @sqlo=' OR menuid IN (SELECT a.parentid FROM webmenu a INNER JOIN (SELECT parentid FROM webmenu WHERE sysid=0 AND '+@sqlm+') b ON a.menuid=b.parentid)'
		
	END

-- 根据 分销 和 辉煌.net 的不同，在辉煌.net 中屏蔽部份菜单项
DECLARE @chvSQLDiff varchar(MAX)
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'FxOrNet' AND SubValue = '1')
	SET @chvSQLDiff = ' 1=1'
ELSE-- 维修管理、积分返利、价格保护、换货查询、门店数据
	SET @chvSQLDiff = ' MenuID NOT IN (11003000,5095,5096,751,1205) AND ParentID NOT IN (11003000,5095,5096,751,1205)'

-- 基础版不享受 “商品近效期查询” 菜单项
DECLARE @chvSQLSP varchar(MAX)
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'Edition' AND SubValue = '1')
	OR EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'costing' AND SubValue <> '3')
	SET @chvSQLSP = '1=1'
ELSE
	SET @chvSQLSP = ' 1=1'
	
-- 判断是否启用货位
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'mngcargospace' AND Value = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (1238,799,6901304,10102007,5301080)'

--关闭现金银行报表
SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (945)' --,6901402 调拨分布

--屏蔽“基础资料”下的“公司信息”
SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (1230) '

--屏蔽“序列号库存查询”
SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (9754) '

--物流单据商品是否采用批号
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName =  'ifusegoodsnumber' AND Value = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (6901305) '

--是否启用自由项
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'isfreeitem' AND SubValue = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (6901306,502080,502090) '
	
--是否启用条码组合管理
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ifuseentrycodeext' AND SubValue = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (11004030,11004040) '

--是否启用外币 (不启用外币是关闭“期末汇差”菜单)
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'isforeigncurrency' AND SubValue = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (80062) '
	
--是否启用多单位
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='doubleunit' AND Value=1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (10102034) '
	
--管金所控制
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'isShowFinancingServices'	 AND SubValue = '1')
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (170007) '

--正式运算菜单数据	
CREATE TABLE #WebMenu
(
	MenuID 		int,
	ParentID 	int,
	Caption 	varchar(MAX),
	[Name] 		varchar(MAX),
	IsSubMenu 	bit,
	Title		varchar(MAX),
	img 		varchar(MAX),
	TabOrd		INT,
	Shortcut	VARCHAR(MAX)
)	

--查询数据
SET @SQL = 'INSERT	INTO #WebMenu 
			SELECT	menuid,
					parentid,
					caption,
					NAME,
					issubmenu,
					title,
					img,
					TabOrd,
					Shortcut  
			FROM	webmenu 
			WHERE	sysid=0 
					AND ('+@sqlm+@sqln+@sqlo+') 
					AND ('+@sqlG+') 
					AND ('+@chvSQLDiff+') 
					AND ('+@chvSQLSP+') 
							OR Caption =''开账向导'' 
							OR Caption = ''管金所|融资服务'' 
							OR Caption = ''应用中心'' 
							OR Caption = ''全渠道业务同步中心'' 
							OR Caption = ''智慧经营管理系统'' 
				    '
									
--PRINT(@sqlm+@sqln+@sqlo)
EXEC(@SQL)

--期初单据采用父菜单控制所有子菜单，父菜单不设offset,此处特殊处理控制菜单
DECLARE @Value INT
SELECT @Value = SUBSTRING(lim,2369,1) FROM dbo.loginuser WHERE etypeid = @chvOperator
IF @Value = 1
BEGIN
	SELECT @Value = SUBSTRING(lim,2360,1) FROM dbo.loginuser WHERE etypeid = @chvOperator
	IF @Value = 1
		INSERT INTO #WebMenu SELECT MenuID,ParentID,Caption,Name,IsSubMenu,Title,img,Tabord,ShortCut FROM dbo.WebMenu WHERE MenuID LIKE '101030%' ORDER BY Tabord
	ELSE
		INSERT INTO #WebMenu SELECT MenuID,ParentID,Caption,Name,IsSubMenu,Title,img,Tabord,ShortCut FROM dbo.WebMenu WHERE MenuID LIKE '101030%' AND MenuID <> '10103060' ORDER BY Tabord	
END
	
--插入无需权限的菜单
--INSERT INTO #WebMenu SELECT MenuID,ParentID,Caption,Name,IsSubMenu,Title,img,Tabord,ShortCut FROM dbo.WebMenu WHERE MenuID IN (1222)

--处理三级菜，不处理的话菜单看不见
INSERT INTO #WebMenu
SELECT	W.menuid,W.parentid,W.caption,W.NAME,W.issubmenu,W.title,W.img,W.TabOrd,W.Shortcut
FROM	WebMenu W
INNER JOIN (
			SELECT	ParentId
			FROM	#WebMenu
			--WHERE	MenuId IN (511050,62050,69013,80050,88030,1273,88050,101030)
) U ON W.MenuId = U.ParentId

-- 删除单据自定义编号的菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName ='BillCodeConfig' AND Value='1')
DELETE FROM #WebMenu WHERE Name ='LIMIT_BillCode_Config'

--V3,A8关闭汽配相关菜单
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '2' OR SubValue = '4'))
BEGIN
	DELETE FROM #WebMenu WHERE ParentId IN (690,1273,1600,160001,160002,160003)
	DELETE FROM #WebMenu WHERE MenuId IN (690,1273,6902071,1237,1238,1239,11001120,11001130,11001140,11001150,799,6902078,6902079,6902080,6902072,6902030,6902020,1600,880169)	
	--V1、V3关闭分支机构的信息 关闭“会计科目”
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '4'))
	BEGIN
		DELETE FROM #WebMenu WHERE ParentID IN (69050)	
		DELETE FROM #WebMenu WHERE MenuID IN (510311,69050,101001,11001005,883,881,882,880187,880188,1391,1392,1096)		
		--关闭【内部应收期初】菜单
		DELETE FROM #WebMenu WHERE MenuID  =501040	
		--关闭【资金调拨单】菜单
		DELETE FROM #WebMenu WHERE MenuID  =5604131	
		--关闭【科目余额汇总表】菜单
		DELETE FROM #WebMenu WHERE MenuID  =880503011	
		--关闭【分支机构使用情况检查】菜单
		DELETE FROM #WebMenu WHERE MenuID = 1100120150
		--优惠券分支机构调拨菜案
		DELETE FROM #WebMenu WHERE MenuID IN (5702011,570201101,570201102,570201103,570201104)
	END		
	--A8关闭“部门核算的报表”
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
	BEGIN
		DELETE FROM #WebMenu WHERE MenuID IN (880187,880188,1391,1392,11001005)		
	END
END	

--V1、A8关闭单据往来科目设置菜单
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '2' OR SubValue = '4'))
BEGIN
	DELETE FROM #WebMenu WHERE MenuID IN (56080)		
END


--非序列号版本，删除序列号相关菜单
IF @checkSerial=0
BEGIN
	DELETE FROM #WebMenu WHERE MenuID IN (975,53010100,53010110) OR ParentID = 975
END

--电脑行业版才有装机配置单
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '2' OR SubValue = '4')) AND NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'Edition' AND SubValue = '5') 
BEGIN
	DELETE FROM #WebMenu WHERE MenuID = 51020 OR ParentID = 51020
END

--9.4修改所有成本算法下均显示销售费用分摊
--移动加权才出“费用分摊”菜单
--9.7.1bug358非移动加权算法不显示成本计算菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'costing' AND SubValue = '0')
BEGIN
	DELETE FROM #WebMenu WHERE MenuID IN (8804010,741,8804040) OR ParentID IN (8804010,8804040)
END



--控制POS菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig  WHERE ConfigName = 'IsPosStart') 
	OR EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'IsPosStart' AND Value = '0')
BEGIN
	DELETE FROM #WebMenu WHERE  ParentID = 51010 	 
	AND MenuID<>505 AND MenuID<>5101020 AND MenuID<>5101060 AND MenuID<>5101021
	--零售单和零售退货单菜单显示
END	

--控制电子称相关
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig  WHERE ConfigName = 'userelectronweigh') 
	OR EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'userelectronweigh' AND Value = '0')
BEGIN
	DELETE FROM #WebMenu WHERE  MenuID=5101060 OR ParentID=5101060
END	

--控制分支机构销售计划
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'Proinfo' AND (SubValue = '1' OR SubValue = '3' OR SubValue = '4'))
BEGIN
	DELETE FROM #WebMenu WHERE MenuID = 51106040
END

---- 判断是否启用总账系统
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) 
BEGIN	
	DELETE FROM #WebMenu WHERE MenuID IN (560,10102002,10102004,10102001,10102005,10102006,1096,1238,65589,1210,1100120110,10102010,101040)  --1210 预制数据导入 110012010 会计科目检查
	
	--去掉基本信息出纳相关菜单
	DELETE FROM #WebMenu WHERE MenuID IN (10102091,10102092)
	
	--去掉基本信息会计科目多级权限
	DELETE FROM #WebMenu WHERE MenuID IN (1097)
	
	--去掉跨帐套总账相关菜单
	DELETE FROM #WebMenu WHERE MenuID IN(1500750) OR ParentID IN (1500750)
	
	--去掉结转成本菜单
	DELETE FROM #WebMenu WHERE MenuID IN (5500802)
END
--ELSE
--	DELETE FROM #WebMenu WHERE MenuID IN (65588)

--非手工指定移除【商品库存批号详情】菜单
IF  EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='costing' AND SubValue <> 3) 
	DELETE FROM #WebMenu WHERE MenuID =766

--9.3暂时关闭“往来对账报表”菜单“
--DELETE FROM #WebMenu WHERE MenuID=8001009

BEGIN --9.6菜单控制调整

	--系统采用序列号严密管理，序列号关联货位，自由项，批次批号时，去掉序列号调整单
	IF  EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='mngserial' AND Value = 1)  
			AND	EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='serialrelation' AND Value = 1)  
	BEGIN
		DELETE FROM #WebMenu WHERE MenuID =9753
	END
END;

BEGIN	--9.7发票立账配置处理
	IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='isinvoice' AND SubValue=1)
	BEGIN
		DELETE FROM #WebMenu WHERE MenuID IN (52061,51021,8801691,8801792,1010301050,1010301060,1010302050,1010302060,1010304092,1010304093)
		DELETE FROM #WebMenu WHERE ParentID IN (52061,51021)
	END
END

--V1产品集中关闭菜单区域
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'Proinfo' AND SubValue = '4')
BEGIN
	DELETE 
	FROM	#WebMenu 
	WHERE	ParentID IN (510730,580,11003280,10103030,511060,5095,5096,1215,170001,170002,170003,15007,1500720,1500740,1500750,69050,52061,51021,560,56041,561,51020,5500802) 
			OR MenuID IN(510730,580,11003280,11003260,10103030,511060,5095,1010304070,5096,1215,170001,170002,170003,9753,511044,502010,502020,502030,502070,502040,502050,502060,620401,15007,1500720,1500740,1500750,62924,683,51501,51502,15001,15002,69050,1100120150,101001,11001005,510311,883,501040,11003260,1010304080,1010304090,1010304091,52061,51021,880187,880188,1391,1392,881,882,560,56041,561,51020,10102035,59518,10102036,138040,138050) 
			
	--修改一级菜单名称，将“仓储运输管理”修改成“仓储管理”		
	UPDATE #WebMenu SET Caption = '仓储管理' WHERE MenuId = 530
END

--非A8产品集中关闭菜单区域
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'Proinfo' AND SubValue = '2')
BEGIN
	DELETE FROM	#WebMenu WHERE MenuID=5701021
END



--序列号销售统计
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='mngserial' AND Value = 1) OR EXISTS(SELECT * FROM SysData WHERE SubName='Edition' AND SubValue IN(1,6))
	BEGIN
		DELETE FROM	#WebMenu WHERE MenuID IN(502082)	
	END
--会员期初储值维护 V3/V1不显示此菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
	BEGIN
		DELETE FROM	#WebMenu WHERE MenuID IN(5701007)	
	END

--卡片模式和项目模式菜单处理
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='assets' AND SubValue = 1) AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) 
BEGIN
	--卡片模式去掉成本费用里的的固定资产,项目管理里的固定资产,数据搬移里的固定资产,期初单据里的成本费用(固定资产购买,变卖)
	DELETE FROM #WebMenu WHERE MenuID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040)  
	OR ParentID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040)
	
	--总账模式且 模板配置-固定资产管理无权限 去掉 一级 固定资产菜单 
	IF EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig WHERE MenuID=561 AND IsChecked=1) AND EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig WHERE MenuID=560 AND IsChecked=1)
		DELETE FROM #WebMenu WHERE MenuID LIKE '561%' 
END
 IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='assets' AND SubValue = 1) AND NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) 
 BEGIN
	--卡片模式去掉成本费用里的的固定资产,项目管理里的固定资产,数据搬移里的固定资产,期初单据里的成本费用(固定资产购买,变卖)
	DELETE FROM #WebMenu WHERE MenuID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040)  
	OR ParentID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040) 
	
	--总账管理下的固定资产
	DELETE FROM #WebMenu WHERE MenuID IN (56050) OR ParentID IN (56050) 
 END

--非卡片模式去掉固定资产相关菜单
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='assets' AND SubValue = 1) 
BEGIN
	DELETE FROM #WebMenu WHERE MenuID LIKE '561%' 
	
	DELETE FROM #WebMenu WHERE MenuID IN (56050) OR ParentID IN (56050) --项目模式去掉总账里的固定资产
END


--屏蔽财务业务对账菜单
DELETE FROM #WebMenu WHERE MenuID=56060 OR ParentID=56060


--判断OM
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='IsOM' AND SubValue = 0)
BEGIN
	--删除OM相关菜单
	DELETE FROM #WebMenu WHERE MenuID IN (516,517,1278)
END
	

--判断店账通  
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='isdzt' AND SubValue = 0)
	BEGIN
		--删除这两个菜单
		DELETE FROM #WebMenu WHERE MenuID IN (17000410,17000420,17000430,17000440,17000450,170004)
	END
	
--章鱼侠云WMS及网店解决方案  
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='usewms' AND SubValue = 0)
	BEGIN
		DELETE FROM #WebMenu WHERE MenuID IN (170011,17001101,17001102,17001103,17001104,17001105,17001106)
	END

--云分销判断
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'IsCloud' AND subValue='0') 
BEGIN
	DELETE FROM #WebMenu WHERE MenuID IN (1800,180001,180010,180020,18001001,18001002,18001003,18001004,18001005,18001006,18002001,18002002,18002003,18002004,18002005)
END
ELSE
BEGIN
	--V3 删除 云分销-上传分支机构菜单
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '4'))
	BEGIN
		DELETE FROM #WebMenu WHERE MenuID = 18001002
	END
END

--暂时关闭“往来对账报表”菜单“
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubNo = 720 AND SubValue = '1')
BEGIN
	DELETE FROM #WebMenu WHERE MenuId IN (SELECT MenuId FROM dbo.WebMenu WHERE MenuID IN (5108,511050,6209,62050,975,69013,88016,80010,80020,80050,110020,88030,560,561,633,590,600,633,62040,11003280,620,511040,110090))	
END

--未启用微信则不允许再使用微信了
--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.PayConfigInfo WHERE PayType = 2)
--BEGIN
--	DELETE FROM #WebMenu WHERE MenuId = 11001302
--END

--门店配送单
IF NOT EXISTS(SELECT TOP 1 1 FROM userconfig WHERE configname='usepostrans' AND Value = '1')
BEGIN
	DELETE FROM #WebMenu WHERE MenuId = 69015 OR ParentId = 69015
END

--是否启用账套，未启用的不显示菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsInvocation' AND SubValue = 1) --插件添加
	RETURN

--修改替换菜单显示  
UPDATE #webmenu
SET NAME = p.webmenuname,caption=p.name
FROM #webmenu w 
INNER JOIN dbo.Ord_PopUpPage p ON w.menuid =p.replacemenuid

--根据版本过滤是否过期 版本验证可能不完善
DECLARE @currentdbversion VARCHAR(100),@mversion VARCHAR(10)
SELECT @currentdbversion=SubValue FROM dbo.sysdata WHERE SubName='Version'
SELECT @mversion=SubValue FROM dbo.sysdata WHERE subname='mVersion'
SELECT p.* 
INTO #Ord_PopUpPage
FROM dbo.Ord_PopUpPage p INNER JOIN dbo.Ord_Plug i ON p.plugid=i.id
WHERE LEN(i.AppropriateVerSion)<10 
	  OR ( CHARINDEX(@currentdbversion,i.AppropriateVerSion)>0 AND CHARINDEX(@currentdbversion+'*',i.AppropriateVerSion)<=0)
	  OR ( CHARINDEX(@currentdbversion+'*'+@mversion,i.AppropriateVerSion)>0)


--杨俊添加：添加插件的上级菜单，直到顶级菜单（4级）
--插件Menu
CREATE TABLE #PlugMenu
(
	MenuID 		int,
	ParentID 	int,
	Caption 	varchar(MAX),
	[Name] 		varchar(MAX),
	IsSubMenu 	bit,
	Title		varchar(MAX),
	img 		varchar(MAX),
	TabOrd		INT,
	Shortcut	VARCHAR(MAX)
)
--写入插件Menu
INSERT #PlugMenu
SELECT  replacemenuid AS menuid,Parentmenuid AS parentid,NAME AS caption,
			p.webmenuname AS [Name],
			CAST(0 AS BIT) AS issubmenu,'' AS title,'' AS img,
			(SELECT MAX(tabord) FROM #webmenu WHERE ParentID=p.Parentmenuid) AS tabord,
			'' AS shortcut
			FROM dbo.#Ord_PopUpPage p
			INNER JOIN dbo.ord_LimitList l ON p.id=l.plugmenuid
			INNER JOIN Ord_PlugLimitFooting f ON l.Id = f.LimitId AND f.lim=1  AND etypeid=@chvOperator
			WHERE ISNULL(p.replacemenuid,'')='' AND  @chvOperator<>'00001' and L.limittype in (1,7,10,19)

--插件上级菜单ID记录
CREATE TABLE #ParentIDTemp
(
	MenuID 		int,
	ParentID 	int
)
--写入插件上级菜单游标
DECLARE @PLugParentId VARCHAR(MAX)
DECLARE PlugMenu CURSOR FOR
		SELECT DISTINCT ParentID FROM #PlugMenu
	OPEN PlugMenu
	FETCH NEXT FROM PlugMenu INTO @PLugParentId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF((SELECT COUNT(1) FROM #WebMenu WHERE menuid = @PLugParentId) = 0)
		BEGIN
			--写入
			INSERT #PlugMenu(MenuID,ParentID,Caption,[Name],IsSubMenu,Title,img,TabOrd,Shortcut)
			SELECT menuid,parentid,caption,NAME,issubmenu,title,img,TabOrd,Shortcut 
			FROM webmenu WHERE menuid = @PLugParentId
			--记录上级菜单ID 以便查找上上级
			INSERT #ParentIDTemp
			SELECT menuid,parentid 
			FROM webmenu WHERE menuid = @PLugParentId
		END
		FETCH NEXT FROM PlugMenu INTO @PLugParentId
	END
	CLOSE PlugMenu
	DEALLOCATE PlugMenu
	
	
--查看上上级是否还存在上级
INSERT #ParentIDTemp(MenuID,ParentID)
SELECT	W.menuid,W.parentid 
FROM	WebMenu W
INNER JOIN (
			SELECT	ParentId
			FROM	#ParentIDTemp PIT
			WHERE NOT EXISTS(SELECT MenuID FROM #ParentIDTemp WHERE MenuID=PIT.ParentID)
) U ON W.MenuId = U.ParentId
--将上上级与上上上级都写入#PlugMenu
INSERT #PlugMenu(MenuID,ParentID,Caption,[Name],IsSubMenu,Title,img,TabOrd,Shortcut)
SELECT	W.menuid,W.parentid,W.caption,W.NAME,W.issubmenu,W.title,W.img,W.TabOrd,W.Shortcut
FROM	WebMenu W
INNER JOIN (
			SELECT	ParentId
			FROM	#ParentIDTemp PIT
			WHERE NOT EXISTS(SELECT MenuID FROM #ParentIDTemp WHERE MenuID=PIT.ParentID)
) U ON W.MenuId = U.ParentId

--杨俊添加-----END------------

--=========================9.7.1新增系统模块配置功能 筛选不在默认的菜单【BEGIN】=======================
DECLARE @ExcludeMenuId TABLE(MenuId		VARCHAR(100))
INSERT INTO @ExcludeMenuId(MenuId) EXEC Web_GetClearMenuId
--删除不在模块中的菜单
DELETE FROM #WebMenu WHERE MenuId IN (SELECT menuId FROM @ExcludeMenuId)
--============================处理期初单据菜单
DECLARE @Limit INT
CREATE TABLE #Temp(MenuId VARCHAR(100))
--销售管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=510
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103010 OR MenuID=10103010
--采购管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=520
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103020 OR MenuID=10103020
--维修管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=580
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103030 OR MenuID=10103030 
--往来管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=540
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103040 OR MenuID=10103040 
--成本费用管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=550
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103050 OR MenuID=10103050
--会员卡券管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=570
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE MenuID=501014
--=========================9.7.1新增系统模块配置功能 筛选不在默认的菜单【END】=======================

--9.8某些功能暂停研发，暂时屏蔽有些菜单
DELETE FROM #WebMenu WHERE MenuID IN (1041)

--物流配送模块，根据系统配置控制菜单显示
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'useonshelves' AND SubValue = '0')	----没有启用上架或者拣货中的一个，则删除仓储管理菜单
	AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usepickgoods' AND SubValue = '0')
	AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usetransport' AND SubValue = '0')
BEGIN
	DELETE FROM #WebMenu WHERE MenuID IN (53003,5300302,5300304,5300301,5300303,690132110,6901321,53012,5301201,5301202,690132120,10103080,1010308001,1010308002,8804030,6901322)
END
ELSE
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'useonshelves' AND SubValue = '0')	----没有启用上架或者拣货中的一个，则删除仓储管理菜单
		AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usepickgoods' AND SubValue = '0')
	BEGIN
		DELETE FROM #WebMenu WHERE MenuID IN (53003,690132110,690132120,6901322)
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'useonshelves' AND SubValue = '1')	--启用上架
		BEGIN			
			DELETE FROM #WebMenu WHERE MenuID IN (5300302,5300304,690132120)
		END

		IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usepickgoods' AND SubValue = '1')	--启用拣货
		BEGIN			
			DELETE FROM #WebMenu WHERE MenuID IN (5300301,5300303,690132110)
		END
	END
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usetransport' AND SubValue = '1')	--启用运输配送
	BEGIN
		DELETE FROM #WebMenu WHERE MenuID IN (53012,5301201,5301202,690132130,10103080,1010308001,1010308002,8804030)
	END
END

--未启用分支机构独立开账，则关闭启用期间设置这个菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'stypeindependentopen' AND SubValue = '1')
BEGIN
	DELETE FROM #WebMenu WHERE menuid IN (6100102)
END

--是否启用实物库存
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'isphysicalsstock' AND SubValue = '1')
BEGIN
	DELETE FROM #WebMenu WHERE MenuId IN (53010,1111,10103060) OR ParentId IN (53010,10103060)
END

--是否启用组合商品
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'combinationproduct' AND SubValue = '1')
BEGIN
	DELETE FROM #WebMenu WHERE MenuId IN (511070,1010301070,1010301080) OR ParentId IN (511070)
END

--是否启用存货类型
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'useatypefrom' AND SubValue = '1')
BEGIN
	DELETE FROM #WebMenu WHERE MenuId IN (10102011)
END

--网店管理菜单
--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'iswd' AND Value = '1')
--BEGIN	
--	DELETE FROM #WebMenu WHERE MenuId IN (170006,17000604) OR parentId IN (170006,17000604)
--END

--成本核算子级不存在
IF NOT EXISTS(SELECT TOP 1 1 FROM #WebMenu WHERE parentId=55008)
	DELETE FROM #WebMenu WHERE MenuId=55008
	
--没有启用品牌管理，删除菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue = '1')
	BEGIN
		DELETE FROM #WebMenu WHERE MenuId IN(10102036,138040,138050,880302007,10102026)
	END
ELSE 
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'brandarcontrollineofcredit' AND SubValue = '0')
		BEGIN
			DELETE FROM #WebMenu WHERE MenuId IN(10102026)
		END
	END
	
--所有广告的控制
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'isshowallgg' AND SubValue = '0')
BEGIN
	DELETE FROM #WebMenu WHERE menuid IN (170007)	--170007(管金所|融资服务)
END

--1688订单管理
IF EXISTS(SELECT TOP 1 1 FROM dbo.WdShopBaseInfo WHERE Field = 'isUse1688' AND Value = '0')
BEGIN
	DELETE FROM #WebMenu WHERE menuid IN (17000606)	--1688订单管理
END

--全渠道菜单
IF NOT EXISTS(
	SELECT b.Name FROM sysobjects b	
	WHERE b.Name='Plu_SS_SysInfo'
)
BEGIN
	DELETE FROM #WebMenu WHERE menuid IN (170009)
END
	
--整理菜单
IF @chvOperator <> '00001'
BEGIN
	DECLARE @MenuId		VARCHAR(MAX),
			@ParId		VARCHAR(MAX),
			@SubMenuId	VARCHAR(MAX),
			@SubParId	VARCHAR(MAX),
			@SubMenuIdx	VARCHAR(MAX),
			@SubParIdx	VARCHAR(MAX)
			
	DECLARE MenuCursor CURSOR FOR
		SELECT DISTINCT MenuID,ParentId FROM #WebMenu WHERE IsSubMenu = '1' AND (ParentId = 500 OR MenuID IN (511050,62050,69013,80050,88030))
	OPEN MenuCursor
	FETCH NEXT FROM MenuCursor INTO @MenuId,@ParId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE SubMenuCursor CURSOR FOR
			SELECT MenuID,ParentId FROM #WebMenu WHERE ParentId = @MenuId AND IsSubMenu = '1'
		OPEN SubMenuCursor
		FETCH NEXT FROM SubMenuCursor INTO @SubMenuId,@SubParId
		WHILE @@FETCH_STATUS = 0
		BEGIN							
			--删除第三级菜单
			IF NOT EXISTS(SELECT TOP 1 1 FROM #WebMenu WHERE ParentID = @SubMenuId)
			BEGIN
				DELETE FROM #WebMenu WHERE MenuID = @SubMenuId
			END
			ELSE	
			BEGIN
				DECLARE SubMenuCursorx CURSOR FOR
					SELECT MenuID,ParentId FROM #WebMenu WHERE ParentId = @SubMenuId AND IsSubMenu = '1'
				OPEN SubMenuCursorx
				FETCH NEXT FROM SubMenuCursorx INTO @SubMenuIdx,@SubParIdx
				WHILE @@FETCH_STATUS = 0
				BEGIN							
					--删除第四级菜单
					IF NOT EXISTS(SELECT TOP 1 1 FROM #WebMenu WHERE ParentID = @SubMenuIdx)
					BEGIN
						DELETE FROM #WebMenu WHERE MenuID = @SubMenuIdx
					END		
						
					FETCH NEXT FROM SubMenuCursorx INTO @SubMenuId,@SubParIdx
				END
				CLOSE SubMenuCursorx
				DEALLOCATE SubMenuCursorx
			END		
				
			FETCH NEXT FROM SubMenuCursor INTO @SubMenuId,@SubParId
		END
		CLOSE SubMenuCursor
		DEALLOCATE SubMenuCursor		
		
		--删除第二级菜单
		IF NOT EXISTS(SELECT TOP 1 1 FROM #WebMenu WHERE ParentID = @MenuId)
			DELETE FROM #WebMenu WHERE MenuID = @MenuId		
		
		--删除第一级菜单	
		IF NOT EXISTS(SELECT TOP 1 1 FROM #WebMenu WHERE ParentID = @ParId)
			DELETE FROM #WebMenu WHERE MenuID = @ParId
				
		FETCH NEXT FROM MenuCursor INTO @MenuId,@ParId
	END
	CLOSE MenuCursor
	DEALLOCATE MenuCursor
END	

--加入插件菜单
SELECT * FROM 
(
	SELECT DISTINCT MenuID,ParentID,Caption,[Name],IsSubMenu,Title,img,TabOrd,Shortcut FROM #WebMenu 
	UNION ALL 
	SELECT MenuID,ParentID,Caption,[Name],IsSubMenu,Title,img,TabOrd,Shortcut FROM #PlugMenu
	UNION ALL  --操作员为管理员的全部显示
	SELECT replacemenuid AS menuid,Parentmenuid AS parentid,NAME AS caption,
			p.webmenuname AS [Name],
			CAST(0 AS BIT) AS issubmenu,'' AS title,'' AS img,
			ROW_NUMBER() OVER (ORDER BY ID)+ISNULL((SELECT MAX(tabord) FROM #webmenu WHERE ParentID=p.Parentmenuid),0) AS tabord,
			'' AS shortcut
			FROM dbo.#Ord_PopUpPage p
			WHERE  @chvOperator='00001' AND ISNULL(p.replacemenuid,'')=''  
) c 
WHERE Not EXISTS(SELECT TOP 1 1 FROM #Temp WHERE MenuID=C.MenuID)
ORDER BY Tabord  
  
  
DROP TABLE #Ord_PopUpPage,#WebMenu,#PlugMenu,#ParentIDTemp,#Temp



go
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		产生 ListTable 中，往来账应收或应付信息
--					
-- 最后修改作者：	卢 春
-- 最后修改时间：	2012-06-06
--修改外币

-- ========================================================================
CREATE PROCEDURE GP_CreateMx 
(
	@nBillID	NUMERIC(10,0)
)
--@encode$--
AS
	SET NOCOUNT ON
------Some vchtype
 DECLARE  
		@GOODS_ID VARCHAR(50),
		@AR_ID VARCHAR(50),
		@AP_ID VARCHAR(50),
		@GOODS_LOSS_ID VARCHAR(50),
		@GOODS_GET_ID VARCHAR(50),
		@ALLOT_PRICE_ID VARCHAR(50),
		@PRICE_INCOME_ID VARCHAR(50),     
		@BORROW_BUY_PRICE_ID VARCHAR(50), 
		@GOODS_GIVE_ID VARCHAR(50),       
		@GOODS_PRODUCE_ID VARCHAR(50),    
		@SALE_COST_ID VARCHAR(50),        
		@SALE_INCOME_ID VARCHAR(50),      
		@LEND_GOODS_ID VARCHAR(50),       
		@BORROW_GOODS_ID VARCHAR(50),     
		@BALANCE_ID VARCHAR(50),          
		@DEPRECIATION_ID VARCHAR(50),     
		@APPORTION_EXPENSE_ID VARCHAR(50),
		@INIT_MONEY_ID VARCHAR(50),       
		@PROFIT_ID VARCHAR(50),           
		@ASSETS_ID VARCHAR(50),           
		@DEBT_ID VARCHAR(50),             
		@POWER_ID VARCHAR(50),
		@GOODS_GIVE_RECNO VARCHAR(50),
		@GOODS_GIVEME_RECNO VARCHAR(50),
		@Advantage_ID VARCHAR(50),   
		@WtDxGoods_ID VARCHAR(50),   
		@DxGoodsMoney_ID VARCHAR(50),
		@preferenceID	VARCHAR(50),
		@PAY_TAXMONEY_ID	VARCHAR(50),
		@Get_Advantage_ID VARCHAR(50),
		@PrePay_ID			varchar(50),
		@PreGathering_ID	varchar(50),
		@Re					INT
		
--EXEC @re = Gp_Fz_Base '',2
--IF @re <> 0 RETURN -2		
		
/*
 SELECT @GOODS_GIVE_RECNO = '000040000200002'           --商品赠出
 SELECT @GOODS_GIVEME_RECNO = '000030000200002'          --商品获赠            
 SELECT @GOODS_ID='0000100001'
 SELECT @CASH_ID='0000100003'
 SELECT @CASH_BANK_ID='0000100004'
 SELECT @AR_ID='0000100005'
 SELECT @AP_ID='0000200001'
 SELECT @GOODS_LOSS_ID='000040000200001'   --           商品报损
 SELECT @GOODS_GET_ID='000030000200001'      --           商品报溢收入
 SELECT @ALLOT_PRICE_ID='000030000200005'   -- 变价调拨差价
 SELECT @PRICE_INCOME_ID='000030000200003' --成本调价收入
 SELECT @GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
 SELECT @SALE_COST_ID='0000400001'--              『销售成本』
 SELECT @SALE_INCOME_ID='0000300001'--            『销售收入』
 SELECT @BALANCE_ID='000030000200004'--           进货退货差价
 SELECT @DEPRECIATION_ID='000040000300002'--      固定资产折旧
 SELECT @APPORTION_EXPENSE_ID='0000100007'--      待摊费用
 SELECT @ALL_INCOME_ID='00003' --          【收入类】
 SELECT @ALL_EXPENSE_ID='00004'--                 【支出类】
 SELECT @ASSETS_ID ='00001'  --【资产合计】
 SELECT @DEBT_ID='00002'   --【负债合计】
 SELECT @Advantage_ID = '0000400004' --『销售折扣返利』
 SELECT @WtDxGoods_ID = '0000100008'  --『委托代销商品』
 SELECT @StDxGoods_ID  = '0000100009'  --『受托代销商品』
 SELECT @DxGoodsMoney_ID = '0000200003'  --『代销商品款』
 SELECT @preferenceID = '000040000300004'  		 --『优惠金额』
 SELECT @PAY_TAXMONEY_ID = '0000200004'			--『应交税金』
 SELECT @Get_Advantage_ID = '0000300004'		-- 返点获利收入
 
 SELECT
	@PrePay_ID='0000100009',			--预付账款
	@PreGathering_ID='0000200006'		--预收账款
*/


SELECT 
	@GOODS_GIVE_RECNO=nid
FROM Ac_Items
WHERE UserCode='0422'			--商品赠出


SELECT @GOODS_GIVEME_RECNO =nid
FROM Ac_Items
WHERE UserCode= '0322'			--商品获赠            

SELECT @GOODS_ID =nid
FROM Ac_Items
WHERE UserCode='1241'			--库存商品


SELECT @AR_ID =nid
FROM Ac_Items
WHERE UserCode='987'			--应收

SELECT @AP_ID =nid
FROM Ac_Items
WHERE UserCode='2121'			--应付

SELECT @GOODS_LOSS_ID =nid
FROM Ac_Items
WHERE UserCode='0421'			--商品报损

SELECT @GOODS_GET_ID =nid
FROM Ac_Items
WHERE UserCode='0321'			--商品报溢收入

SELECT @ALLOT_PRICE_ID =nid
FROM Ac_Items
WHERE UserCode='0325'			--变价调拨差价

SELECT @PRICE_INCOME_ID =nid
FROM Ac_Items
WHERE UserCode='0323'			--成本调价收入

SELECT @GOODS_PRODUCE_ID =nid
FROM Ac_Items
WHERE UserCode='0326'			--商品拆装差价

SELECT @SALE_COST_ID =nid
FROM Ac_Items
WHERE UserCode='5401'			--『销售成本』

SELECT @SALE_INCOME_ID =nid
FROM Ac_Items
WHERE UserCode='5101'			--『销售收入』

SELECT @BALANCE_ID =nid
FROM Ac_Items
WHERE UserCode='0324'			-- 进货退货差价

SELECT @DEPRECIATION_ID =nid
FROM Ac_Items
WHERE UserCode='0432'			--固定资产折旧

SELECT @APPORTION_EXPENSE_ID =nid
FROM Ac_Items
WHERE UserCode='1301'			--待摊费用

SELECT @Advantage_ID  =nid
FROM Ac_Items
WHERE UserCode= '0404'			--『销售折扣返利』

SELECT @WtDxGoods_ID  =nid
FROM Ac_Items
WHERE UserCode= '1261'			--『委托代销商品』


SELECT @DxGoodsMoney_ID  =nid
FROM Ac_Items
WHERE UserCode= '2141'			--『代销商品款』

SELECT @preferenceID  =nid
FROM Ac_Items
WHERE UserCode= '0456'			--『优惠金额』

SELECT @PAY_TAXMONEY_ID  =nid
FROM Ac_Items
WHERE UserCode= '2171'			--『应交税金』

SELECT @Get_Advantage_ID  =nid
FROM Ac_Items
WHERE UserCode= '5103'			-- 返点获利收入

SELECT @PrePay_ID =nid
FROM Ac_Items
WHERE UserCode='1151'			--预付账款

SELECT @PreGathering_ID =nid
FROM Ac_Items
WHERE UserCode='2131'			--预收账款

GOTO error188
SQLText:

 DECLARE 
		@dbname VARCHAR(30),
		@nCostingMethod SMALLINT,
		@preferencemoney  NUMERIC(24, 10) ,
		@tBillDate DATETIME,
		@dTotalMoney  NUMERIC(24, 10) ,
		@dTotalinMoney  NUMERIC(24, 10) ,
		@nBillType NUMERIC(4, 0),
		@szDTypeId VARCHAR(50),
		@szAtypeId VARCHAR(50),
		@szPtypeId VARCHAR(50),
		@szbTypeId VARCHAR(50),
		@szEtypeId VARCHAR(50),
		@szStockId VARCHAR(50),
		@szStockId2 VARCHAR(50),
		@dTotal  NUMERIC(24, 10) ,
		@dQty  NUMERIC(24, 10) ,
		@nPeriod INT,
		@szJobNumber VARCHAR(20),
		@OutFactoryDate DATETIME,
		@dPrice  NUMERIC(24, 10) ,
		@szAtypeIdtemp VARCHAR(50),
		@szPtypeIdtemp VARCHAR(50),
		@szbTypeIdtemp VARCHAR(50),
		@szEtypeIdtemp VARCHAR(50),
		@szKtypeIdtemp VARCHAR(50),
		@numNoTaxTotal  NUMERIC(24, 10) ,
		@szSTypeID VARCHAR(50),
		@Npreferencemoney  NUMERIC(24, 10) ,
		@NdTotalMoney  NUMERIC(24, 10) ,
		@NdTotalinMoney  NUMERIC(24, 10) ,
		@NdTotal  NUMERIC(24, 10) ,
		@NnumNoTaxTotal  NUMERIC(24, 10) ,
		@intCID	INT,
		@DecRate  NUMERIC(24, 10) ,
		@chargeOffType INT,
		@chargeOffBtypeid VARCHAR(50)
 
 SELECT 
		@nBillType=BillType,
		@tBillDate=BillDate,
		@szDTypeId=DTypeID,
		@szAtypeId=atypeid,
		@szbTypeId=btypeid,
		@szEtypeId=etypeid,
		@szStockId=ktypeid,
		@szStockId2=ktypeid2,  
		@dTotalMoney=totalmoney,
		@dTotalinMoney=TotalInMoney,
		@preferencemoney=preferencemoney,
		@NdTotalMoney=Ntotalmoney,
		@NdTotalinMoney=NTotalInMoney,
		@Npreferencemoney=Npreferencemoney,
		@szSTypeID=STypeID,
		@intCID=CID,
		@DecRate=Rate,
		@chargeOffType=ChargeOffType,
		@chargeOffBtypeid=ChargeOffBtypeid
 FROM BillIndex WHERE BillNumberId=@nBillId
 
 DECLARE @dTempAr  NUMERIC(24, 10) ,@dTempAp    NUMERIC(24, 10)  
 DECLARE @dTempQty  NUMERIC(24, 10) ,@dTempTotal   NUMERIC(24, 10) 
 
 DECLARE 
	@dBcAr   NUMERIC(24, 10) , --本次应收
	@dBcAp   NUMERIC(24, 10) , --本次应付
	@NdBcAr   NUMERIC(24, 10) , --本次应收（原币）
	@ndBcAp   NUMERIC(24, 10)   --本次应付（原币）
	
 DECLARE @dChange  NUMERIC(24, 10)  --本次变动
 DECLARE @nGoodsNo INT,@szJobNo VARCHAR(20),@dCostPriceout  NUMERIC(24, 10) ,@dtemp  NUMERIC(24, 10) ,@nRet SMALLINT
 DECLARE @execsql [VARCHAR](500)

DECLARE @numInputCostPrice  NUMERIC(24, 10) 	-- 成本单价

------------------------------往来核销单--------------------------
 IF @nBillType=450
 BEGIN
	IF @chargeOffType=0
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES
		(@nBillId,@tBillDate,@nBillType,@AR_ID,'0',@chargeOffBtypeid,@szEtypeid,'',-@dTotalMoney,-@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate),
		(@nBillId,@tBillDate,@nBillType,@AP_ID,'0',@szbTypeId,@szEtypeid,'',-@dTotalMoney,-@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate)
	ELSE IF @chargeOffType=1
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES
		(@nBillId,@tBillDate,@nBillType,@PreGathering_ID,'0',@chargeOffBtypeid,@szEtypeid,'',-@dTotalMoney,-@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate),
		(@nBillId,@tBillDate,@nBillType,@PrePay_ID,'0',@szbTypeId,@szEtypeid,'',-@dTotalMoney,-@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate)
	ELSE IF @chargeOffType=2
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES
		(@nBillId,@tBillDate,@nBillType,@AR_ID,'0',@chargeOffBtypeid,@szEtypeid,'',-@dTotalMoney,-@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate),
		(@nBillId,@tBillDate,@nBillType,@AR_ID,'0',@szbTypeId,@szEtypeid,'',@dTotalMoney,@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate)
	ELSE IF @chargeOffType=3
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES
		(@nBillId,@tBillDate,@nBillType,@AP_ID,'0',@chargeOffBtypeid,@szEtypeid,'',-@dTotalMoney,-@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate),
		(@nBillId,@tBillDate,@nBillType,@AP_ID,'0',@szbTypeId,@szEtypeid,'',@dTotalMoney,@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate)
	ELSE IF @chargeOffType=4
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES
		(@nBillId,@tBillDate,@nBillType,@PreGathering_ID,'0',@chargeOffBtypeid,@szEtypeid,'',-@dTotalMoney,-@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate),
		(@nBillId,@tBillDate,@nBillType,@AP_ID,'0',@szbTypeId,@szEtypeid,'',@dTotalMoney,@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate)
	ELSE IF @chargeOffType=5
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES
		(@nBillId,@tBillDate,@nBillType,@PrePay_ID,'0',@chargeOffBtypeid,@szEtypeid,'',-@dTotalMoney,-@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate),
		(@nBillId,@tBillDate,@nBillType,@AR_ID,'0',@szbTypeId,@szEtypeid,'',@dTotalMoney,@NdTotalMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate)
	
	RETURN 0
  END 
------------------------------往来核销单理结束--------------------------

------------------------------转款单--------------------------
 IF @nBillType=77
 BEGIN
  SELECT @dbname='movemoneybill'
 
  SELECT @execsql='DECLARE CreateMxZk_cursor CURSOR FOR '
    +' SELECT a.atypeid,a.Total,a.NTotal,b.CID FROM '
    +@dbname+' a
    INNER JOIN BillIndex b
    ON a.BillNumberID=b.BillNumberID
    WHERE a.BillNumberId= '+CAST(@nBillId AS VARCHAR(10))
  EXEC (@execsql)
  OPEN CreateMxZk_cursor
  FETCH NEXT FROM CreateMxZk_cursor INTO @szAtypeIdtemp,@dTotal,@NdTotal,@intCID
  WHILE @@FETCH_STATUS=0
  BEGIN
   INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
        Total,NTotal,CID,STypeID,DTypeID,Rate)
   VALUES(@nBillId,@tBillDate,@nBillType,@szAtypeIdtemp,'0','0',@szEtypeid,'',@dTotal,@NdTotal,@intCID,@szSTypeID,@szDTypeId,@DecRate)
  

   

   FETCH NEXT FROM CreateMxZk_cursor INTO @szAtypeIdtemp,@dTotal,@NdTotal,@intCID
  END 
  
  /*
  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
       Total,NTotal,CID,STypeID,DTypeID,Rate)
  VALUES(@nBillId,@tBillDate,@nBillType,@szAtypeId,'0','0',@szEtypeid,'',-@dTotalinMoney,-@NdTotalInMoney,@intCID,@szSTypeID,@szDTypeId,@DecRate)
  */
  CLOSE CreateMxZk_cursor 
  DEALLOCATE CreateMxZk_cursor

  RETURN 0
error4:  
  DEALLOCATE CreateMxZk_cursor

  RETURN -1
 END
------------------------------转款单处理结束--------------------------

------------------------------调帐单--------------------------

-----应收增加 应收减少
 IF (@nBillType IN (115,116))
 BEGIN
  SELECT @dbname='Addebtbill'
--  BEGIN tran AppendMxTz
 
  SELECT @execsql='DECLARE CreateMxTz_cursor CURSOR FOR '
    +' SELECT a.Btypeid,a.Total,a.NTotal,b.CID FROM '
    +@dbname+' a
    INNER JOIN BillIndex b
    ON a.BillNumberID=b.BillNumberID
    WHERE a.BillNumberId= '+CAST(@nBillId AS VARCHAR(10))
  EXEC (@execsql)
  OPEN CreateMxTz_cursor
  FETCH NEXT FROM CreateMxTz_cursor INTO @szBtypeId,@dTotal,@NdTotal,@intCID
  WHILE @@FETCH_STATUS=0
  BEGIN
	   --得到当前应收余额
	   
	   
	   IF @nBillType=115
	   BEGIN
			 --应收减少
			 INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			   qty,price,Total,NTotal,CID,STypeID,DTypeID,Rate)
			 VALUES(@nBillId,@tBillDate,@nBillType,@AR_ID,'0',@szBtypeid,@szEtypeid,'0',0
			  ,0,-@dTotal,-@NdTotal,@intCID,@szSTypeID,@szDTypeId,@DecRate)
	   END
	   ELSE
	   BEGIN
			 --应收增加
			 INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			   qty,price,Total,NTotal,CID,STypeID,DTypeID,Rate)
			 VALUES(@nBillId,@tBillDate,@nBillType,@AR_ID,'0',@szBtypeid,@szEtypeid,'0',0
			  ,0,@dTotal,@NdTotal,@intCID,@szSTypeID,@szDTypeId,@DecRate)
	   END
	   
	   FETCH NEXT FROM CreateMxTz_cursor INTO @szBtypeId,@dTotal,@NdTotal,@intCID
  END 
 
  CLOSE CreateMxTz_cursor 
  DEALLOCATE CreateMxTz_cursor

  RETURN 0
error5:  
  DEALLOCATE CreateMxXsTz_cursor

  RETURN -1
 END
 
 
 -----应付增加&应付减少
 IF (@nBillType IN (128,129))
 BEGIN
  SELECT @dbname='Addebtbill'

 
  SELECT @execsql='DECLARE CreateMxTz_cursor CURSOR FOR '
    +' SELECT a.Btypeid,a.Total,a.NTotal,b.CID FROM '
    +@dbname+' a
    INNER JOIN BillIndex b
    ON a.BillNumberID=b.BillNumberID
    WHERE a.BillNumberId= '+CAST(@nBillId AS VARCHAR(10))
  EXEC (@execsql)
  OPEN CreateMxTz_cursor
  FETCH NEXT FROM CreateMxTz_cursor INTO @szBtypeId,@dTotal,@NdTotal,@intCID
  WHILE @@FETCH_STATUS=0
  BEGIN
   ------得到当前应付余额
   
   IF @nBillType=128
   BEGIN
		--应付增加
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
		qty,price,Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@AP_ID,'0',@szBtypeid,@szEtypeid,'0',0
		,0,@dTotal,@NdTotal,@intCID,@szSTypeID,@szDTypeId,@DecRate)
   END
   ELSE
   BEGIN
		--应付减少
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
		qty,price,Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@AP_ID,'0',@szBtypeid,@szEtypeid,'0',0
		,0,-@dTotal,-@NdTotal,@intCID,@szSTypeID,@szDTypeId,@DecRate)
   END
 
   
   FETCH NEXT FROM CreateMxTz_cursor INTO @szBtypeId,@dTotal,@NdTotal,@intCID
  END 
 
  CLOSE CreateMxTz_cursor 
  DEALLOCATE CreateMxTz_cursor

  RETURN 0
error6:  
  DEALLOCATE CreateMxTz_cursor

  RETURN -1
 END
------------------------------调帐单处理结束--------------------------

--------------------------------钱流单处理开始--------------------------
--支出类	--158 现金费用单	--36 一般费用单	--84 固定资产购买
--收入类	--93 其他收入--85 固定资产变卖--410固定资产变更单
--其他		--78 固定资产折旧--5  待摊费用发生--10 待摊费用摊销 


DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

IF @nBillType=410
BEGIN
	declare @changereason varchar(10), @billcode varchar(50),@billtypel int,@atypeid int,@btypeid varchar(50),@etypeid varchar(50),@stypeid varchar(50),
	@rate decimal(24,10),@cid int,@billdate date;
	declare @usercode varchar(20),@Total decimal(24,10),--本币
		    @Ntotal decimal(24,10);--原币
	--SELECT * FROM Base_FixedReasonForChange 可以看ChangeReasonID的意思	
	select @billcode=BillCode,@billdate=BillDate,@billtypel=BillType,@btypeid=BtypeId,@etypeid=EtypeId,@rate=rate,@cid=CID,@stypeid=stypeid from BillIndex
	where BillNumberId=@nBillId
	select @changereason=ChangeReasonID from AssetIncChangeBill where BillCode=@billcode
	if(@changereason='BG001')--资产评估原值增
	begin		    
			--借方
		    select @atypeid=nid from Ac_Items where UserCode='SYC-1601'
		    select @Total=TotalDif,@Ntotal=F_TotalDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
		    select @atypeid=nid from Ac_Items where UserCode='0432'
		    select @Total=DepTotalDif/@rate,@Ntotal=DepTotalDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
		   
		    --贷方
		    select @atypeid=nid from Ac_Items where UserCode='3111'
		    select @Total=TotalDif-NetValueDif,@Ntotal=F_TotalDif-NetValueDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
		    select @atypeid=nid from Ac_Items where UserCode='043599'
		    select @Total=NetValueDif/@rate,@Ntotal=NetValueDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
		    select @atypeid=nid from Ac_Items where UserCode='SYC-1602'
		    select @Total=DepTotalDif/@rate,@Ntotal=DepTotalDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
	end
	else if(@changereason='BG002')--资产价值调整
	begin 
	--借方
		    select @atypeid=nid from Ac_Items where UserCode='SYC-1601'
		    select @Total=TotalDif,@Ntotal=F_TotalDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
		    select @atypeid=nid from Ac_Items where UserCode='0432'
		    select @Total=DepTotalDif/@rate,@Ntotal=DepTotalDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
		    --贷方
		    --select @atypeid=nid from Ac_Items where UserCode='2121'
		    --select @Total=TotalDif-NetValueDif,@Ntotal=F_TotalDif-NetValueDif from AssetIncChangeBill where BillCode=@billcode
		    --if(@Total!=0 and @Ntotal!=0)
		    --begin
		    --insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    --end
		    select @atypeid=nid from Ac_Items where UserCode='043599'
		    select @Total=NetValueDif/@rate,@Ntotal=NetValueDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
		    select @atypeid=nid from Ac_Items where UserCode='SYC-1602'
		    select @Total=DepTotalDif/@rate,@Ntotal=DepTotalDif from AssetIncChangeBill where BillCode=@billcode
		    if(@Total!=0 and @Ntotal!=0)
		    begin
		    insert into Listtable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,Total,Ntotal,rate,CID,stypeid) values(@nBillId,@billdate,@billtypel,@atypeid,@btypeid,@etypeid,@Total,@Ntotal,@rate,@cid,@stypeid)
		    end
	end
	RETURN 0
END
IF @nBillType IN (5,10,35) -- 78,84,85 93 36 158 变为多账户 gp_auditarap 中特殊处理
BEGIN	
	
    DECLARE CreateOther_cursor CURSOR FOR
	SELECT a.atypeid,a.Total,a.NTotal,b.CID,
	CASE WHEN b.BillType IN (78,158) THEN a.DTypeId ELSE b.DTypeId END,
	CASE b.BillType WHEN 158 THEN a.ETypeId ELSE b.ETypeId END
	FROM MoneyBill a
	INNER JOIN BillIndex b
	ON a.BillNumberID=b.BillNumberID
	WHERE a.BillNumberId=@nBillId
	OPEN CreateOther_cursor
	FETCH NEXT FROM CreateOther_cursor INTO @szAtypeIdtemp,@dTotal,@NdTotal,@intCID,@szDTypeID,@szETypeID
	WHILE @@FETCH_STATUS=0
	BEGIN
		
		IF @nBilltype IN (5)  --(78,5,85)   --#v9.9 78 85 挪到 gp_auditarap 里面去了 有多账户
		BEGIN
			SELECT 
				@dTotal=-@dTotal,
				@NdTotal=-@NdTotal
		END
		
		
		
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			    qty,price,Total,NTotal,CID,STypeID,DTypeID,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@szAtypeIdtemp,'0',@szBtypeid,@szEtypeid,'0',0
			,0,@dTotal,@NdTotal,@intCID,@szSTypeID,@szDTypeId,@DecRate)
		IF @@rowcount=0 GOTO error20
	
		FETCH NEXT FROM CreateOther_cursor INTO @szAtypeIdtemp,@dTotal,@NdTotal,@intCID,@szDTypeID,@szETypeID
	END 
		
	
	IF @nBilltype IN(36,35) --(84,36,35) --#v9.9 84 挪到 gp_auditarap 里面去了 有多账户
	BEGIN
		IF (@dTotalinMoney<>0 OR @NdTotalinMoney<>0) AND @nBillType IN (84,35)  --排除费用单
		BEGIN
				INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
						qty,price,total,Ntotal,CID,JobNumber,OutFactoryDate,DTypeID,STypeID,Rate)
				VALUES(@nBillId,@tBillDate,@nBillType,@szAtypeid,'0',@szBtypeid,@szEtypeid,'0',0
					,0,-@dTotalinMoney,-@NdTotalinMoney,@intCID,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@DecRate)
				
			IF @@rowcount=0 GOTO error20
		END
		
		SELECT 
			@dBcAp=@dTotalMoney-@dTotalinMoney,
			@NdBcAp=@NdTotalMoney-@NdTotalinMoney
			
		
		
		IF @dBcAp<>0 OR @NdBcAp<>0
		BEGIN
			IF @nBillType=36 AND @ExpenseToAr=1 AND LEFT(@szBtypeid,5)='00001'
			BEGIN
				INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,Ntotal,CID,JobNumber,OutFactoryDate,DTypeID,STypeID,Rate)
				VALUES(@nBillId,@tBillDate,@nBillType,@AR_ID,'0',@szBtypeid,@szEtypeid,'0',0
				,0,-@dBcAp,-@NdBcAp,@intCID,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@DecRate)
			END
			ELSE
			BEGIN
				INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,Ntotal,CID,JobNumber,OutFactoryDate,DTypeID,STypeID,Rate)
				VALUES(@nBillId,@tBillDate,@nBillType,@AP_ID,'0',@szBtypeid,@szEtypeid,'0',0
				,0,@dBcAp,@NdBcAp,@intCID,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@DecRate)
			END
			
			IF @@rowcount=0 GOTO error20
		END
	END
	ELSE IF @nBilltype IN (93)--(93,85) --其他收入,固定资产变卖 #v9.9 85 挪到 gp_auditarap 里面去了 有多账户
	BEGIN
		IF @dTotalinMoney<>0 OR @NdTotalinMoney<>0
		BEGIN
			IF @szAtypeId=@PreGathering_ID
			BEGIN
				INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
						qty,price,total,Ntotal,CID,JobNumber,OutFactoryDate,DTypeID,STypeID,Rate)
				VALUES(@nBillId,@tBillDate,@nBillType,@szAtypeid,'0',@szBtypeid,@szEtypeid,'0',0
					,0,-@dTotalinMoney,-@NdTotalinMoney,@intCID,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@DecRate)
			END
			ELSE
			BEGIN
				INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
						qty,price,total,Ntotal,CID,JobNumber,OutFactoryDate,DTypeID,STypeID,Rate)
				VALUES(@nBillId,@tBillDate,@nBillType,@szAtypeid,'0',@szBtypeid,@szEtypeid,'0',0
					,0,@dTotalinMoney,@NdTotalinMoney,@intCID,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@DecRate)
			END
		
			IF @@rowcount=0 GOTO error20
			
		END
		
		SELECT 
			@dBcAr=@dTotalMoney-@dTotalinMoney,
			@NdBcAr=@NdTotalMoney-@NdTotalinMoney
		
		IF @dBcAr<>0 OR @NdBcAr<>0
		BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			qty,price,total,Ntotal,CID,JobNumber,OutFactoryDate,DTypeID,STypeID,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@AR_ID,'0',@szBtypeid,@szEtypeid,'0',0
			,0,@dBcAr,@NdBcAr,@intCID,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@DecRate)
			IF @@rowcount=0 GOTO error20
		END	
	END
	/*
	ELSE IF @nBilltype=158	-- 现金费用单
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,Ntotal,CID,JobNumber,OutFactoryDate,DTypeID,STypeID,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@szAtypeId,'0','0',@szEtypeid,'0',0
			,0,-@dTotalMoney,-@NdTotalMoney,@intCID,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@DecRate)
		
		IF @@rowcount=0 GOTO error20
	END
	*/
		CLOSE CreateOther_cursor
		DEALLOCATE CreateOther_cursor
		RETURN 0
error20:		
		CLOSE CreateOther_cursor
		DEALLOCATE CreateOther_cursor
		RETURN -1
END
--------------------------------钱流单处理结束--------------------------



--------------------------------返利执行单148、价保执行单149、获利核算执行单150,获得价保执行单151-----------------------
IF @nBillType IN (148,149,150,151)
BEGIN
		DECLARE @intATypeID VARCHAR(50)

		IF @nBillType IN (150,151)
			SET @intATypeID = @Get_Advantage_ID		-- 返点获利收入
		ELSE
			SELECT @intATypeID = @Advantage_ID	-- 销售折扣返利

		IF @nBillType IN (148,150)
			SELECT @dTotal=SUM(total),@NdTotal=SUM(total) FROM Advantage WHERE BillNumberId=@nBillId
		ELSE
			SELECT @dTotal=SUM(total),@NdTotal=SUM(total) FROM PriceProtectBill WHERE BillNumberId=@nBillId
			
		

		IF @@rowcount<>0 AND (@dTotal<>0 OR @NdTotal<>0)
		BEGIN     
			INSERT INTO Listtable
						(
							BillNumberId,
							BillDate,
							BillType,
							atypeid,
							ptypeid,
							btypeid,
							etypeid,
							ktypeid,
			    			qty,
							price,
							total,
							Ntotal,
							CID,
							DTypeID,
							STypeID,
							Rate
						)
						VALUES
						(
							@nBillId,
							@tBillDate,
							@nBillType,
							@intATypeID,
							'0',
							@szBtypeid,
							@szEtypeid,
							'0',
							0,
							0,
							@dTotal,
							@NdTotal,
							@intCID,
							@szDTypeId,
							@szSTypeID,
							@DecRate
						)
			IF @@rowcount=0 GOTO error40		
		END 
		
		
	
		/*
		价保执行是我的应收减少，获得价格是我的应付减少
		返利是我的应收减少，获利是我的应付减少
		*/
		
		
		
		DECLARE
			@tmpATypeID		VARCHAR(50),
			@tmpTotal		 NUMERIC(24, 10) 
		
		IF @nBillType IN (148,149)
		BEGIN
			--返利执行单,价保执行单
			SELECT 
				@tmpATypeID=@AR_ID,
				@tmpTotal=(@dTotalMoney-@dTotalinMoney)*(-1)
				
			------得到当前应收余额
			EXEC Gp_Getdbf @AR_ID,'0',@szBtypeId,'0','0',@szSTypeID,'','',@dTempQty OUTPUT,@dTempAr OUTPUT
				
		END
		ELSE IF @nBillType IN (150,151)
		BEGIN
			--获利执行单,获得价保
			SELECT 
				@tmpATypeID=@AP_ID,
				@tmpTotal=(@dTotalMoney-@dTotalinMoney)*(-1)
				
			------得到当前应付余额
			EXEC Gp_Getdbf @AP_ID,'0',@szBtypeId,'0','0',@szSTypeID,'','',@dTempQty OUTPUT,@dTempAr OUTPUT		
		END
		
		IF @tmpTotal<>0
		BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			qty,price,total,Ntotal,CID,JobNumber,OutFactoryDate,DTypeID,STypeID,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@tmpATypeID,'0',@szBtypeid,@szEtypeid,'0',0
			,0,@tmpTotal,@tmpTotal,@intCID,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@DecRate)
			
			IF @@rowcount=0 GOTO error40
		END
		
		
		
		IF @nBillType=149 --价格保护执行单
		BEGIN    
		    DECLARE @dOldTotal  NUMERIC(24, 10) 
		    DECLARE @dNewPrice  NUMERIC(24, 10) 
		    DECLARE @dSerial VARCHAR(100)
            DECLARE @BillType INT	
		    SELECT  @szBTypeID=BTypeID,@BillType = BillType,@szSTypeID=STypeID  
		    FROM BillIndex WHERE BillNumberid=@nBillID
		    SELECT @dbname='PriceProtectBill' 
		    SELECT @execsql='DECLARE CreateMxJB_cursor CURSOR FOR '
		               +' SELECT Serial,ptypeid,total,OldTotal,NewPrice FROM '
		
		                +@dbname+' WHERE BillNumberId= '+CAST(@nBillId AS VARCHAR(10))
		    EXEC (@execsql)
		   	OPEN CreateMxJB_cursor
			FETCH NEXT FROM CreateMxJB_cursor INTO @dSerial,@szPtypeId,@dTotal,@dOldTotal,@dNewPrice
		    WHILE @@FETCH_STATUS=0
		    	BEGIN
		
			        IF EXISTS(SELECT * FROM PriceProtectList WHERE PTypeID=@szPTypeID AND BtypeId=@szBTypeID AND Serial=@dSerial AND BillType = @BillType AND STypeID=@szSTypeID)
		    	    	BEGIN 
		               		UPDATE PriceProtectList SET OldTotal=ISNULL(OldTotal,0)+@dTotal,CurPrice=@dNewPrice,NewPrice=@dNewPrice  WHERE PTypeID=@szPTypeID AND BtypeId=@szBTypeID AND Serial=@dSerial AND BillType = @BillType AND STypeID=@szSTypeID

		        		END
		        	ELSE
		              	INSERT INTO PriceProtectList (Serial,Ptypeid,Btypeid,OldTotal,CurPrice,NewPrice,BillType,STypeID) VALUES(@dSerial,@szPTypeID,@szBTypeID,@dTotal,@dNewPrice,@dNewPrice,@BillType,@szSTypeID)
		       		FETCH NEXT FROM CreateMxJB_cursor  INTO @dSerial,@szPtypeId,@dTotal,@dOldTotal,@dNewPrice
		  		END 
		     CLOSE CreateMxJB_cursor 
		     DEALLOCATE CreateMxJB_cursor 
		END
		
		IF @nBillType = 151 	--获得价保执行单
		BEGIN
			SELECT  @szBTypeID=BTypeID,@BillType = BillType,@szSTypeID=STypeID 
			FROM BillIndex WHERE BillNumberid=@nBillID
			SELECT 	@dbname='PriceProtectBill' 
			SELECT 	@execsql='DECLARE CreateMxJG_cursor CURSOR FOR '
					+' SELECT Serial,ptypeid,total,OldTotal,NewPrice FROM '				
					+@dbname+' WHERE BillNumberId= '+CAST(@nBillId AS VARCHAR(10))

			EXEC (@execsql)
			OPEN CreateMxJG_cursor
			FETCH NEXT FROM CreateMxJG_cursor INTO @dSerial,@szPtypeId,@dTotal,@dOldTotal,@dNewPrice
			WHILE @@FETCH_STATUS=0
				BEGIN				
					IF EXISTS(SELECT * FROM PriceProtectList WHERE PTypeID=@szPTypeID AND BtypeId=@szBTypeID AND Serial=@dSerial AND BillType = @BillType AND STypeID=@szSTypeID)
						BEGIN 
							UPDATE 	PriceProtectList 
							SET 	OldTotal=ISNULL(OldTotal,0)+@dTotal,
									CurPrice=@dNewPrice,
									NewPrice=@dNewPrice  
							WHERE 	PTypeID=@szPTypeID 
									AND BtypeId=@szBTypeID 
									AND Serial=@dSerial 
									AND BillType = @BillType
									AND STypeID=@szSTypeID
						END
					ELSE
						INSERT INTO PriceProtectList 
									(
										Serial,
										Ptypeid,
										Btypeid,
										OldTotal,
										CurPrice,
										NewPrice,
										BillType,
										STypeID
									) 
									VALUES
									(
										@dSerial,
										@szPTypeID,
										@szBTypeID,
										@dTotal,
										@dNewPrice,
										@dNewPrice,
										@BillType,
										@szSTypeID
									)
					FETCH NEXT FROM CreateMxJG_cursor  INTO @dSerial,@szPtypeId,@dTotal,@dOldTotal,@dNewPrice
				END 
			CLOSE CreateMxJG_cursor 
			DEALLOCATE CreateMxJG_cursor 				
		END
		
		--返利执行单，价保单，获利执行单，获得价保单的结算标志确定
		DECLARE @numTotalInMoney  NUMERIC(24, 10) ,@numTotalMoney  NUMERIC(24, 10) 
		
		
		SELECT @numTotalInMoney=totalinmoney,@numTotalMoney=totalmoney FROM dbo.BillIndex WHERE BillNumberId = @nBillID

		/*
		IF @numTotalInMoney>=@numTotalMoney
		BEGIN
			IF @numTotalMoney=0
			BEGIN
				UPDATE BillIndex
				SET JsStyle=0,JsState=2
				WHERE BillNumberID=@nBillID
			END
			ELSE
			BEGIN
				UPDATE BillIndex
				SET JsStyle=1,JsState=2
				WHERE BillNumberID=@nBillID
			END
		END
		ELSE
		BEGIN
			IF @numTotalInMoney=0
			BEGIN
				UPDATE BillIndex
				SET JsStyle=0,JsState=0
				WHERE BillNumberID=@nBillID
			END
			ELSE
			BEGIN
				UPDATE BillIndex
				SET JsStyle=1,JsState=1
				WHERE BillNumberID=@nBillID
			END
		END
		*/
		
		IF @numTotalInMoney=@numTotalMoney
		BEGIN
			IF @numTotalMoney=0
			BEGIN
				UPDATE BillIndex
				SET JsStyle=0,JsState=2
				WHERE BillNumberID=@nBillID
			END
			ELSE
			BEGIN
				UPDATE BillIndex
				SET JsStyle=1,JsState=2
				WHERE BillNumberID=@nBillID
			END
		END
		ELSE
		BEGIN
			IF @numTotalInMoney=0
			BEGIN
				UPDATE BillIndex
				SET JsStyle=0,JsState=0
				WHERE BillNumberID=@nBillID
			END
			ELSE
			BEGIN
				UPDATE BillIndex
				SET JsStyle=1,JsState=1
				WHERE BillNumberID=@nBillID
			END
		END
		
		RETURN 0
error40:				
		RETURN -1
END
--------------------------------返利执行单处理结束--------------------------

error188:
	--DECLARE @fValue INT
	--EXEC Web_CheckSysValue 8,@fValue OUTPUT
	--IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 6 AND SubValue = '1')
	--	AND (EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 10 AND ISNULL(SubValue,'') = '')
	--		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 9 AND ISNULL(SubValue,'') = '')
	--		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 11 AND ISNULL(SubValue,'') = '')
	--		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 13 AND ISNULL(SubValue,'') = '')
	--		 OR  @fValue = 1)
	--RETURN 1688	
			 
	-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********

	-- 获取数据表 LoginUser 中操作员数
	DECLARE @intLoginUserCount INT
	SELECT	@intLoginUserCount = COUNT(*)
	FROM	LoginUser
	WHERE	IsErp = 1

	DECLARE @N INT, @intDogUserCount INT, @intVersion INT
	-- 判断版本号，是否试用版
	SELECT	@N = CAST(SubValue AS INT)
	FROM	SysData1
	WHERE	SubNo = 2	-- 版本号

	IF @N IS NULL RETURN 1688

	DECLARE @intBit INT, @intMask INT
	SELECT @intBit = @N & 15
	SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
	SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

	-- 判断软件狗用户数
	SELECT	@N = CAST(SubValue AS INT)
	FROM	SysData1
	WHERE	SubNo = 3	-- 检查用户数

	IF @N IS NULL RETURN 1688
	
	--DECLARE @hValue INT
	--EXEC Gp_Hr_IsDistribute 1,@hValue OUTPUT	
	--IF @hValue = 1 RETURN 1688

	IF @intVersion IN (2,3,5,7,9,11,13,15)	-- 试用版
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE subname = 'Proinfo' AND SubValue = '4')
				SELECT @intDogUserCount = 3
			ELSE			
				SELECT @intDogUserCount = 5
		END
	ELSE
		BEGIN
			SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
			IF ( 3 & @N <> 3 ) RETURN 1688
		END

	-- 若实际操作员数 > 软件狗许可用户数，则不允许过账
	IF @intLoginUserCount - 1 > @intDogUserCount
		RETURN 1688
	ELSE
		GOTO SQLText

	-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - END	********

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



/*
	计算单据中，根据商品采用的积分规则计算积分
	卢春 2007-12-13
*/
CREATE  PROCEDURE GP_CreateMX_CalVipJF (
	@chvPTypeID		varchar(50),
	@numTotal		 NUMERIC(24, 10) ,
	@intGridJF		int output
)
--@encode$--
AS
	SET @intGridJF = 0
	DECLARE @numRuleTotal  NUMERIC(24, 10) ,@intRuleJF numeric(18,0)

	SELECT	TOP 1 @numRuleTotal = ISNULL(b.Total,0),
			@intRuleJF = ISNULL(b.JF,0)
	FROM	nVipGoodsSign a,nVipJfSet b
	WHERE	a.PTypeID = @chvPTypeID
			AND a.JFID = b.[ID]

	IF @numRuleTotal <> 0 AND @intRuleJF <> 0
	BEGIN
		SET @intGridJF = CAST(@numTotal/@numRuleTotal AS int)*@intRuleJF
	END
	RETURN 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	更新 ListTable 中应收/付凭证记录
*/
CREATE     PROCEDURE GP_CreateMX_InsertARAP (
	@intBillNumberID	varchar(50),
	@datBillDate		datetime,
	@numBillType		numeric(4,0),
	@chvBTypeID			varchar(50),
	@chvETypeID			varchar(50),
	@numBanlanceTotal	 NUMERIC(24, 10) ,
	@chvJobNumber		varchar(20),
	@datOutFactoryDate	datetime,
	@chvDTypeID			varchar(50),
	@chvSTypeID			varchar(50),
	@AtypeID			varchar(50), --传入项目id
	@CID				INT,
	@Ntotal				 NUMERIC(24, 10) ,
	@Rate				 NUMERIC(24, 10) 
)
--@encode$--
AS

IF @numBanlanceTotal = 0 RETURN 0

DECLARE	@numOutPutQty	 NUMERIC(24, 10) ,
		@numARTotal		 NUMERIC(24, 10) ,
		@numAPTotal		 NUMERIC(24, 10) 
		
		
INSERT INTO ListTable(BillNumberID,BillDate,BillType,ATypeID,PTypeID,BTypeID,ETypeID,KTypeID,
			Qty,Price,Total,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@intBillNumberID,@datBillDate,@numBillType,@AtypeID,'0',@chvBTypeID,@chvETypeID,'0',
			0,0,@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@CID,@ntotal,0,@Rate)			


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	更新 InOutStockTable 出入库明细数据
*/
CREATE                 PROCEDURE GP_CreateMX_InsertInOut (
	@intBillNumberID	numeric(10,0),
	@datBillDate		datetime,
	@numBillType		numeric(4,0),
	@chvATypeID			varchar(50),
	@chvPTypeID			varchar(50),
	@chvBTypeID			varchar(50),
	@chvETypeID			varchar(50),
	@chvKTypeID			varchar(50),
	@numQty				 NUMERIC(24, 10) ,
	@numPrice			 NUMERIC(24, 10) ,
	@numTotal			 NUMERIC(24, 10) ,
	@numCostPrice		 NUMERIC(24, 10) ,
	@numCostTotal		 NUMERIC(24, 10) ,
	@chvJobNumber		varchar(20),
	@datOutFactoryDate	datetime,
	@GoodsNumber		varchar(100) = '',
	@ProduceDate		varchar(50) = '',
	@ValidDate			varchar(50) = '',
	@GoodsBTypeID		varchar(50) = '',
	@GoodsCostPrice		 NUMERIC(24, 10)  = 0,
	@HandZeroCost		int = 0,
	@intID				int = -1,
	@numTax				 NUMERIC(24, 10)  = 0,
	@numDiscount		 NUMERIC(24, 10)  = 1,
	@numSalePrice		 NUMERIC(24, 10)  = 0,
	@numSaleTotal		 NUMERIC(24, 10)  = 0,
	@numTaxPrice		 NUMERIC(24, 10)  = 0,
	@numTaxTotal		 NUMERIC(24, 10)  = 0,
	@chvDTypeID			varchar(50),
	@chvSTypeID			varchar(50),
	@intCargoID			INT=0,
	@numNPrice			 NUMERIC(24, 10) =0,
	@numNTotal			 NUMERIC(24, 10) =0,
	@numNSalePrice		 NUMERIC(24, 10) =0,
	@numNSaleTotal		 NUMERIC(24, 10) =0,
	@numNTaxPrice		 NUMERIC(24, 10) =0,
	@numNTaxTotal		 NUMERIC(24, 10) =0,
	@intItemID			INT=0,
	@intIsCombined		INT=0,
	@NQty				 NUMERIC(24, 10) =0,
	@UnitRate			 NUMERIC(24, 10) =0,
	@intMUNITID			INT=0,
	@intIsGift			TINYINT=0,
	@intIsService		TINYINT=0,
	@strComment			VARCHAR(255)='',
	@datPostTime		DATETIME ,
	@MunitRate			NUMERIC(24,10)=0
	
)
--@encode$--
AS


IF @intIsService=1
BEGIN
	SELECT
		@numCostPrice=0,
		@numCostTotal=0
		
END



-- 更新 InOutStockTable 出入库明细数据
INSERT INTO InOutStockTable (
	BillNumberID,
	BillDate,
	BillType,
	ATypeID,
	PTypeID,
	BTypeID,
	ETypeID,
	KTypeID,
	Qty,
	Price,
	Total,
	CostPrice,
	CostTotal,
	JobNumber,
	OutFactoryDate,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	[ID],
	Tax,
	Discount,
	SalePrice,
	SaleTotal,
	TaxPrice,
	TaxTotal,
	DTypeID,
	STypeID,
	CargoID,
	NPrice,
	NTotal,
	NSalePrice,
	NSaleTotal,
	NTaxPrice,
	NTaxTotal,
	ItemID,
	IsCombined,
	NQty,
	UnitRate,
	MUNITID,
	IsGift,
	IsService,
	Audited,
	Comment,
	PostTime,
	MUnitRate
)
VALUES(
	@intBillNumberID,
	@datBillDate,
	@numBillType,
	@chvATypeID,
	@chvPTypeID,
	@chvBTypeID,
	@chvETypeID,
	@chvKTypeID,
	@numQty,
	@numPrice,
	@numTotal,
	@numCostPrice,
	@numCostTotal,
	@chvJobNumber,
	@datOutFactoryDate,
	@GoodsNumber,
	@ProduceDate,
	@ValidDate,
	@GoodsBTypeID,
	@GoodsCostPrice,
	@HandZeroCost,
	@intID,
	@numTax,
	@numDiscount,
	@numSalePrice,
	@numSaleTotal,
	@numTaxPrice,
	@numTaxTotal,
	@chvDTypeID,
	@chvSTypeId,
	@intCargoID,
	@numNPrice,
	@numNTotal,
	@numNSalePrice,
	@numNSaleTotal,
	@numNTaxPrice,
	@numNTaxTotal,
	@intItemID,
	@intIsCombined,
	@NQty,
	@UnitRate,
	@intMUNITID,
	@intIsGift,
	@intIsService,
	1,
	@strComment,
	CASE WHEN @datPostTime IS NULL OR YEAR(@datPostTime)=1900 THEN GETDATE() ELSE @datPostTime END,
	@MunitRate)

IF @@ROWCOUNT = 0 OR @@ERROR <> 0
BEGIN
	--RAISERROR('更新InOutStockTable发生错误',16,1)
	RETURN -10
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	更新 InOutStockTable 出入库明细数据
*/
CREATE                 PROCEDURE GP_CreateMX_InsertInOut_wx (
	@intBillNumberID	numeric(10,0),
	@datBillDate		datetime,
	@numBillType		numeric(4,0),
	@chvATypeID			varchar(50),
	@chvPTypeID			varchar(50),
	@chvBTypeID			varchar(50),
	@chvETypeID			varchar(50),
	@chvKTypeID			varchar(50),
	@numQty				 NUMERIC(24, 10) ,
	@numPrice			 NUMERIC(24, 10) ,
	@numTotal			 NUMERIC(24, 10) ,
	@numCostPrice		 NUMERIC(24, 10) ,
	@numCostTotal		 NUMERIC(24, 10) ,
	@chvJobNumber		varchar(20),
	@datOutFactoryDate	datetime,
	@GoodsNumber		varchar(100) = '',
	@ProduceDate		varchar(50) = '',
	@ValidDate			varchar(50) = '',
	@GoodsBTypeID		varchar(50) = '',
	@GoodsCostPrice		 NUMERIC(24, 10)  = 0,
	@HandZeroCost		int = 0,
	@intID				int = -1,
	@numTax				 NUMERIC(24, 10)  = 0,
	@numDiscount		 NUMERIC(24, 10)  = 1,
	@numSalePrice		 NUMERIC(24, 10)  = 0,
	@numSaleTotal		 NUMERIC(24, 10)  = 0,
	@numTaxPrice		 NUMERIC(24, 10)  = 0,
	@numTaxTotal		 NUMERIC(24, 10)  = 0,
	@chvDTypeID			varchar(50),
	@chvSTypeID			varchar(50),
	@intCargoID			INT=0,
	@numNPrice			 NUMERIC(24, 10) =0,
	@numNTotal			 NUMERIC(24, 10) =0,
	@numNSalePrice		 NUMERIC(24, 10) =0,
	@numNSaleTotal		 NUMERIC(24, 10) =0,
	@numNTaxPrice		 NUMERIC(24, 10) =0,
	@numNTaxTotal		 NUMERIC(24, 10) =0,
	@intItemID			INT=0,
	@intIsCombined		INT=0,
	@NQty				 NUMERIC(24, 10) =0,
	@UnitRate			 NUMERIC(24, 10) =0,
	@intMUNITID			INT=0,
	@intIsService		TINYINT=0,
	@strComment			VARCHAR(255)='',
	@datPostTime		DATETIME=NULL,
	@MunitRate			NUMERIC(24,10)=0
)
--@encode$--
AS


-- 更新 InOutStockTable 出入库明细数据
INSERT INTO wx_InOutStockTable (
	BillNumberID,
	BillDate,
	BillType,
	ATypeID,
	PTypeID,
	BTypeID,
	ETypeID,
	KTypeID,
	Qty,
	Price,
	Total,
	CostPrice,
	CostTotal,
	JobNumber,
	OutFactoryDate,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	[ID],
	Tax,
	Discount,
	SalePrice,
	SaleTotal,
	TaxPrice,
	TaxTotal,
	DTypeID,
	STypeID,
	CargoID,
	NPrice,
	NTotal,
	NSalePrice,
	NSaleTotal,
	NTaxPrice,
	NTaxTotal,
	ItemID,
	IsCombined,
	NQty,
	UnitRate,
	MUNITID,
	IsService,
	Comment,
	MunitRate
)
VALUES (
	@intBillNumberID,
	@datBillDate,
	@numBillType,
	@chvATypeID,
	@chvPTypeID,
	@chvBTypeID,
	@chvETypeID,
	@chvKTypeID,
	@numQty,
	@numPrice,
	@numTotal,
	@numCostPrice,
	@numCostTotal,
	@chvJobNumber,
	@datOutFactoryDate,
	@GoodsNumber,
	@ProduceDate,
	@ValidDate,
	@GoodsBTypeID,
	@GoodsCostPrice,
	@HandZeroCost,
	@intID,
	@numTax,
	@numDiscount,
	@numSalePrice,
	@numSaleTotal,
	@numTaxPrice,
	@numTaxTotal,
	@chvDTypeID,
	@chvSTypeId,
	@intCargoID,
	@numNPrice,
	@numNTotal,
	@numNSalePrice,
	@numNSaleTotal,
	@numNTaxPrice,
	@numNTaxTotal,
	@intItemID,
	@intIsCombined,
	@NQty,
	@UnitRate,
	@intMUNITID,
	@intIsService,
	@strComment,
	@MunitRate
)

IF @@ROWCOUNT = 0 OR @@ERROR <> 0
BEGIN
	--RAISERROR('更新InOutStockTable发生错误',16,1)
	RETURN -10
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	更新 ListTable 凭证明细数据
*/
CREATE        PROCEDURE GP_CreateMX_InsertList (
	@intBillNumberID	varchar(50),
	@datBillDate		datetime,
	@numBillType		numeric(4,0),
	@chvATypeID			varchar(50),
	@chvBTypeID			varchar(50),
	@chvETypeID			varchar(50),
	@numTotal			 NUMERIC(24, 10) ,
	@chvJobNumber		varchar(20),
	@datOutFactoryDate	datetime,
	@chvDTypeID			varchar(50),
	@chvSTypeID			varchar(50),
	@CID				BIGINT,
	@Ntotal				 NUMERIC(24, 10) ,
	@Rate				 NUMERIC(24, 10) 
)
--@encode$--
AS
	-- 更新 ListTable 出入库明细数据
	
	DECLARE @INNER_ID VARCHAR(50)
	SELECT @INNER_ID = NID FROM Ac_Items WHERE UserCode='1132'
	IF @chvATypeID=@INNER_ID
	BEGIN
		INSERT INTO ListTable (
				BillNumberID,
				BillDate,
				BillType,
				ATypeID,
				PTypeID,
				STypeID2,
				ETypeID,
				KTypeID,
				Qty,
				Price,
				Total,
				JobNumber,
				OutFactoryDate,
				DTypeID,
				STypeID,
				CID,
				Ntotal,
				Rate)
		VALUES (
				@intBillNumberID,
				@datBillDate,
				@numBillType,
				@chvATypeID,
				'0',
				@chvBTypeID,
				@chvETypeID,
				'0',
				0,
				0,
				@numTotal,
				@chvJobNumber,
				@datOutFactoryDate,
				@chvDTypeID,
				@chvSTypeID,
				@CID,
				@Ntotal ,
				@Rate                                                                   
		)
	END
	ELSE
	BEGIN
		INSERT INTO ListTable (
			BillNumberID,
			BillDate,
			BillType,
			ATypeID,
			PTypeID,
			BTypeID,
			ETypeID,
			KTypeID,
			Qty,
			Price,
			Total,
			JobNumber,
			OutFactoryDate,
			DTypeID,
			STypeID,
			CID,
			Ntotal,
			Rate
		)
		VALUES (
			@intBillNumberID,
			@datBillDate,
			@numBillType,
			@chvATypeID,
			'0',
			@chvBTypeID,
			@chvETypeID,
			'0',
			0,
			0,
			@numTotal,
			@chvJobNumber,
			@datOutFactoryDate,
			@chvDTypeID,
			@chvSTypeID,
			@CID,
			@Ntotal,
			@Rate
		)
	END
	
	
	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	BEGIN
		--RAISERROR('更新ListTable发生错误',16,1)
		RETURN -10
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	创建 InOutStockTable 出入库明细
		 ListTable 凭证明细
		 
	维修类、会员类单据不支持多单位		 
*/
CREATE   PROCEDURE GP_CreateMX_new (
	@intBillNumberID				NUMERIC(10,0),
	@numBillType					INT,
	@datBillDate					DATETIME,
	@chvATypeID						VARCHAR(50),
	@chvBTypeID						VARCHAR(50),				--结算单位
	@chvDealBTypeID					VARCHAR(50),		--往来单位
	@chvETypeID						VARCHAR(50),
	@chvKTypeID						VARCHAR(50),
	@chvKTypeID2					VARCHAR(50),
	@chvDTypeID						VARCHAR(50),
	@chvSTypeID						VARCHAR(50),
	@numTotalMoney					 NUMERIC(24, 10) ,
	@numTotalInMoney				 NUMERIC(24, 10) ,
	@numPreferenceMoney				 NUMERIC(24, 10) ,
	@numNPreferenceMoney			 NUMERIC(24, 10) ,
	@NtotalMoney					 NUMERIC(24, 10) ,
	@numTax							 NUMERIC(24, 10) ,
	@ifIndexWX						TINYINT,
	@intCostSale					TINYINT,
	@intCID							INT,
	@datPostTime					DATETIME=NULL
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@GOODS_ID			varchar(50),
		@SALE_INCOME_ID		varchar(50),
		@SALE_COST_ID		varchar(50),
		@PAY_TAXMONEY_ID	varchar(50),
		@DXGOODSMONEY_ID	varchar(50),
		@WTDXGOODS_ID		varchar(50),
		@REPAIR_INCOME_ID	varchar(50),
		@REPAIR_PAYOUT		varchar(50),
		@OtherAP_ID			varchar(50),
		@VIP_ID				VARCHAR(50),
		@VIPJF_CZId			VARCHAR(50)

SELECT @GOODS_ID=NID FROM ac_items WHERE UserCode='1241'  -- 『库存商品总值合计』,0000100001
SELECT @WTDXGOODS_ID=NID FROM ac_items WHERE UserCode='1261'  -- 『委托代销商品』,0000100008
SELECT @DXGOODSMONEY_ID=NID FROM ac_items WHERE UserCode='2141'  -- 『代销商品款』,0000200003
SELECT @PAY_TAXMONEY_ID=NID FROM ac_items WHERE UserCode='2171'  -- 『应交税金』,0000200004
SELECT @OtherAP_ID=NID FROM ac_items WHERE UserCode='2132'  -- 『其他应付款』,0000200007
SELECT @SALE_INCOME_ID=NID FROM ac_items WHERE UserCode='5101'  -- 『销售收入』,0000300001
SELECT @REPAIR_INCOME_ID=NID FROM ac_items WHERE UserCode='0328'  -- 商品维修收入,000030000200008
SELECT @SALE_COST_ID=NID FROM ac_items WHERE UserCode='5401'  -- 『销售成本』,0000400001
SELECT @REPAIR_PAYOUT=NID FROM ac_items WHERE UserCode='0424'  -- 商品送修支出,000040000200004
SELECT @VIP_ID=NID FROM ac_items WHERE UserCode='2181'  -- 会员储值,0000200005
SELECT @VIPJF_CZId=nId FROM Ac_Items WHERE UserCode='044596' AND Sysrow=1--积分转储值

DECLARE	@fValue				INT,
		@nRet				INT,
		/*
		@intCostSale		INT,
		@numBillType		numeric(4,0),
		@datBillDate		datetime,
		@chvATypeID			varchar(50),
		@chvBTypeID			varchar(50),		--结算单位
		@chvDealBTypeID		VARCHAR(50),		--往来单位
		@chvETypeID			varchar(50),
		@chvKTypeID			varchar(50),
		@chvKTypeID2		varchar(50),
		@chvDTypeID			varchar(50),
		@chvSTypeID			varchar(50),
		@numTotalMoney		 NUMERIC(24, 10) ,
		@numTotalInMoney	 NUMERIC(24, 10) ,
		@numPreferenceMoney	 NUMERIC(24, 10) ,
		@numTax				 NUMERIC(24, 10) ,
		*/
		@numDiscount		 NUMERIC(24, 10) ,
		@numSalePrice		 NUMERIC(24, 10) ,
		@numSaleTotal		 NUMERIC(24, 10) ,
		@numTaxPrice		 NUMERIC(24, 10) ,
		@numTaxTotal		 NUMERIC(24, 10) ,
		@wxProperty			int,	-- 维修属性，0：正常商品；1：维修商品
		@ifDetailWX			int,	-- （单据明细）是否属于维修库的出入库记录，0：正常库；1：维修库
		/*
		@ifIndexWX			int,	-- （单据索引）是否针对维修库存进行盘点、报损、报溢；0：正常库，1：维修库
		@intCID				BIGINT, --币种
		@numNPreferenceMoney	 NUMERIC(24, 10) , --外币优惠金额
		@NtotalMoney		 NUMERIC(24, 10) , --外币单据金额
		*/
		@SysCid				BIGINT, --本位币id
		@numJTotal			 NUMERIC(24, 10) ,
		@numDTotal			 NUMERIC(24, 10) ,
		@numNJTotal			 NUMERIC(24, 10) ,
		@numNDTotal			 NUMERIC(24, 10) ,
		@chvTypeATypeID		VARCHAR(50),
		@strErrMsg			VARCHAR(500),
		@chvTempTypeName		VARCHAR(50),
		@chvTempUserCode	VARCHAR(200),
		@chvAIDFlag			VARCHAR(50),		
		@strOPRate			VARCHAR(50),
		@decRate			 NUMERIC(24, 10) ,
		@numNPriceTemp		 NUMERIC(24, 10) 
		

SELECT @strErrMsg=''
		
SELECT TOP 1 @SysCid=CId FROM Ac_Currency WHERE Sysrow = 1
SELECT @strOPRate=BasisType,@decRate=Rate
FROM Ac_Currency				
WHERE CId=@intCID

-- 谢吉康 2019-09-26 屏蔽
--EXEC Web_CheckSysValue 8,@fValue OUTPUT
--EXEC @nRet = Gp_Fz_Base '',2
--IF @nRet <> 0 OR @fValue = 1 RETURN -2

/*
SELECT	@numBillType = BillType,
		@datBillDate = BillDate,
		@chvATypeID = ATypeID,
		@chvBTypeID = BTypeID,				--结算单位
		@chvDealBTypeID=DealBTypeID,		--往来单位
		@chvETypeID = ETypeID,
		@chvKTypeID = KTypeID,
		@chvKTypeID2 = KTypeID2,
		@chvDTypeID	=DTypeID,
		@chvSTypeID=STypeID,
		@numTotalMoney = TotalMoney,
		@numTotalInMoney = TotalInMoney,
		@numPreferenceMoney = PreferenceMoney,
		@numNPreferenceMoney = nPreferenceMoney,
		@NtotalMoney = NtotalMoney,
		@numTax = Tax,
		@ifIndexWX = ifWX,
		@intCostSale=CostSale,
		@intCID = CID
FROM	BillIndex
WHERE	BillNumberID = @intBillNumberID
*/


DECLARE 
			@nCostingMethod		smallint,
			@AVERAGE			smallint,
			@FIFO				smallint,
			@LIFO				smallint,
			@HAND				smallint

	SET @AVERAGE	= 0		-- 移动加权平均
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	SET @HAND		= 3		-- 手工指定

EXEC Gp_GetSubValue 'costing','',@nCostingMethod output

IF @@ROWCOUNT = 0 OR @@ERROR <> 0
BEGIN
	--RAISERROR('读取BillIndex发生错误',16,1)
	RETURN -10
END

-- 谢吉康 2019-09-26 屏蔽
--DECLARE @hValue INT
--EXEC Gp_Hr_IsDistribute 1,@hValue OUTPUT	
--IF @hValue = 1 RETURN -10


DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT
 
DECLARE	
		@chvPTypeID				varchar(50),
		@numQty					 NUMERIC(24, 10) ,
		@numPrice				 NUMERIC(24, 10) ,
		@numTotal				 NUMERIC(24, 10) ,
		@chvJobNumber			varchar(20),
		@datOutFactoryDate		datetime,
		@numInputCostPrice		 NUMERIC(24, 10) ,		-- 成本单价
		@numBanlanceTotal		 NUMERIC(24, 10) ,		-- 差额
		@numNoTaxTotal			 NUMERIC(24, 10) ,
		@numNNoTaxTotal			 NUMERIC(24, 10) , --外币
		@numQtyTemp				 NUMERIC(24, 10) ,
		@numQtyTemp1			 NUMERIC(24, 10) ,		
		@numPriceTemp			 NUMERIC(24, 10) ,
		@numPriceTemp1			 NUMERIC(24, 10) ,
		@numTotalTemp			 NUMERIC(24, 10) ,
		@numTotalTemp1			 NUMERIC(24, 10) ,
		@numCostPriceTemp		 NUMERIC(24, 10) ,
		@numCostPriceTemp1		 NUMERIC(24, 10) ,
		@numCostTotalTemp		 NUMERIC(24, 10) ,
		@numCostTotalTemp1		 NUMERIC(24, 10) ,
		@numTaxBanlance			 NUMERIC(24, 10) ,		-- 税额
		@numNTaxBanlance		 NUMERIC(24, 10) ,		-- 外币税额
		@intReturnCode			int,
		@chrInOrOut				char(1),			-- 换货单中的出入库标记
		@GoodsNumber			varchar(100),		-- 批号
		@ProduceDate			varchar(50),		-- 生产日期
		@ValidDate				varchar(50),		-- 效期至
		@GoodsBTypeID			varchar(50),		-- 供货商ID值
		@GoodsCostPrice			 NUMERIC(24, 10) ,		-- 批次成本单价
		@HandZeroCost			int,				-- 是否为0成本入库标识
		@ChangeAllStock			int,				-- 是否调整全部仓库的成本价
		@CostingMethod			int,				-- 成本算法
		@intID					int,				-- 单据明细排序自增加ID值
		@intCargoID				INT,
		@numNPrice				 NUMERIC(24, 10) =0,
		@numNTotal				 NUMERIC(24, 10) =0,
		@numNSalePrice			 NUMERIC(24, 10) =0,
		@numNSaleTotal			 NUMERIC(24, 10) =0,
		@numNTaxPrice			 NUMERIC(24, 10) =0,
		@numNTaxTotal			 NUMERIC(24, 10) =0,
		@intItemID				INT,
		@intInCargoID			INT,
		@intOutCargoID			INT,
		@intIsCombined			INT,
		@numNQty				 NUMERIC(24, 10) =0,
		@numUnitRate			 NUMERIC(24, 10) =0,
		@numNQtyTemp			 NUMERIC(24, 10) =0,
		@numNTotalTemp			 NUMERIC(24, 10) =0,
		@numNSaleTotalTemp		 NUMERIC(24, 10) =0,
		@numNTaxTotalTemp		 NUMERIC(24, 10) =0,
		@intMUnitID				INT=0,
		@numMunitRate			NUMERIC(24,10)=0,
		@intIsGift				TINYINT=0,
		@intIsService			TINYINT=0,
		@strComment				VARCHAR(255),
		@fCurFlagValue			INT

--EXEC Web_CheckSysValue 1,@fCurFlagValue OUTPUT
--IF @fCurFlagValue = 1 RETURN -2

------------------------------ 销售出库单
IF @numBillType = 11
BEGIN
DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	PTypeID,
			Qty,
			DiscountPrice,
			Total,
			JobNumber,
			OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			Discount,
			SalePrice,
			SaleTotal,
			TaxPrice,
			TaxTotal,
			KTypeID,
			Tax,
			CargoID,
			NDiscountPrice,
			NTotal,
			NSalePrice,
			NSaleTotal,
			NTaxPrice,
			NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			MUnitID,
			IsGift,
			b.IsService,
			a.Comment,
			a.MUnitRate
	FROM	SaleBill a
	INNER JOIN PType b
	ON a.PtypeId=b.typeId
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = ROUND(-@numQty,@intQtyDot)
		SET @numPriceTemp = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp = ROUND(-@numTotal,@intMoneyDot)
		SET @numCostPriceTemp = ROUND(@numInputCostPrice,@intPriceDot)
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		
		SELECT
			@numNTotal=ROUND(-@numNTotal,@intMoneyDot),
			@numNSaleTotal=ROUND(-@numNSaleTotal,@intMoneyDot),
			@numNTaxTotal=ROUND(-@numNTaxTotal,@intMoneyDot),
			@numNQty=ROUND(-@numNQty,@intQtyDot)
		
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate

		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
												
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
	
	-- ********* 处理生成 ListTable 凭证记录 *********
	
	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0),@numNNoTaxTotal = ISNULL(SUM(NTotal),0) FROM SaleBill WHERE BillNumberID = @intBillNumberID
	IF ((@numTotalMoney - @numNoTaxTotal <> 0)  OR (@NtotalMoney - @numNNoTaxTotal<>0)) AND @intCostSale=0
	BEGIN
		SET @numTaxBanlance = @numTotalMoney - @numNoTaxTotal
		--外币
		SET @numNTaxBanlance = @NtotalMoney - @numNNoTaxTotal
		
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@chvSTypeID,@PAY_TAXMONEY_ID,@numTaxBanlance,@numNTaxBanlance,''
	END
	
	RETURN 0
END


------------------------------ 组合品销售出库单
IF @numBillType = 12
BEGIN
DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	PTypeID,
			Qty,
			DiscountPrice,
			Total,
			JobNumber,
			OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			Discount,
			SalePrice,
			SaleTotal,
			TaxPrice,
			TaxTotal,
			KTypeID,
			Tax,
			CargoID,
			NDiscountPrice,
			NTotal,
			NSalePrice,
			NSaleTotal,
			NTaxPrice,
			NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			MUnitID,
			IsGift,
			b.IsService,
			a.Comment,
			a.MUnitRate
	FROM	PT_Combin_SaleBillDetail a
	INNER JOIN PType b
	ON a.PtypeId=b.typeId
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = ROUND(-@numQty,@intQtyDot)
		SET @numPriceTemp = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp = ROUND(-@numTotal,@intMoneyDot)
		SET @numCostPriceTemp = ROUND(@numInputCostPrice,@intPriceDot)
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		
		SELECT
			@numNTotal=ROUND(-@numNTotal,@intMoneyDot),
			@numNSaleTotal=ROUND(-@numNSaleTotal,@intMoneyDot),
			@numNTaxTotal=ROUND(-@numNTaxTotal,@intMoneyDot),
			@numNQty=ROUND(-@numNQty,@intQtyDot)
		
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate

		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
												
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
	
	-- ********* 处理生成 ListTable 凭证记录 *********
	
	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0),@numNNoTaxTotal = ISNULL(SUM(NTotal),0) FROM PT_Combin_SaleBillDetail WHERE BillNumberID = @intBillNumberID
	IF ((@numTotalMoney - @numNoTaxTotal <> 0)  OR (@NtotalMoney - @numNNoTaxTotal<>0)) AND @intCostSale=0
	BEGIN
		SET @numTaxBanlance = @numTotalMoney - @numNoTaxTotal
		--外币
		SET @numNTaxBanlance = @NtotalMoney - @numNNoTaxTotal
		
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@chvSTypeID,@PAY_TAXMONEY_ID,@numTaxBanlance,@numNTaxBanlance,''
	END
	
	RETURN 0
END


------------------------------ 采购退货单
IF @numBillType = 6
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
			SELECT	PTypeID,
					Qty,
					DiscountPrice,
					Total,
					JobNumber,
					OutFactoryDate,
					CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					GoodsBTypeID,
					GoodsCostPrice,
					HandZeroCost,
					[ID],
					Discount,
					SalePrice,
					SaleTotal,
					TaxPrice,
					TaxTotal,
					KTypeID,
					Tax,
					CargoID,
					NDiscountPrice,
					NTotal,
					NSalePrice,
					NSaleTotal,
					NTaxPrice,
					NTaxTotal,
					ItemID,
					IsCombined,
					NQty,
					UnitRate,
					MUnitID,
					IsGift,
					b.IsService,
					a.Comment,
					a.MUnitRate
			FROM	BuyBackBill a
			INNER JOIN PType b
			ON a.PtypeId=b.typeId
			WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = -@numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = -@numTotal
		SET @numCostPriceTemp = ROUND(@numInputCostPrice,@intPriceDot)
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1


		SET @numSaleTotal = -@numSaleTotal
		SET @numTaxTotal = -@numTaxTotal
		
		SELECT
			@numNTotal=-@numNTotal,
			@numNSaleTotal=-@numNSaleTotal,
			@numNTaxTotal=-@numNTaxTotal,
			@numNQty=-@numNQty
			
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
												
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0),@numNNoTaxTotal = ISNULL(SUM(NTotal),0) FROM BuyBackBill WHERE BillNumberID = @intBillNumberID
	IF ((@numTotalMoney - @numNoTaxTotal <> 0) OR (@NtotalMoney - @numNNoTaxTotal<>0))  AND @intCostSale=0
	BEGIN
		SET @numTaxBanlance = @numTotalMoney - @numNoTaxTotal
		--外币
		SET @numNTaxBanlance = @NtotalMoney - @numNNoTaxTotal
		
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		
	END

	RETURN 0
END
------------------------------ 采购入库单
IF @numBillType = 34
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				1 AS HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate
		FROM	BuyBill a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		
		
		SET @numCostPriceTemp = @numPrice
		SET @numCostTotalTemp = @numTotal

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,0,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0),@numNNoTaxTotal = ISNULL(SUM(NTotal),0) FROM BuyBill WHERE BillNumberID = @intBillNumberID
	IF ((@numTotalMoney - @numNoTaxTotal <> 0 ) OR ( @NtotalMoney - @numNNoTaxTotal<>0))
	BEGIN
		SET @numTaxBanlance = -(@numTotalMoney - @numNoTaxTotal)
		--外币
		SET @numNTaxBanlance =-( @NtotalMoney - @numNNoTaxTotal)
		
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		
	END
	
	RETURN 0
END
------------------------------ 销售退货单
IF @numBillType = 45
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate	
		FROM	SaleBackBill a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END 
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0),@numNNoTaxTotal = ISNULL(SUM(NTotal),0) FROM SaleBackBill WHERE BillNumberID = @intBillNumberID
	IF ((@numTotalMoney - @numNoTaxTotal <> 0 ) OR (@NtotalMoney - @numNNoTaxTotal<>0))
	BEGIN
		SET @numTaxBanlance = -(@numTotalMoney - @numNoTaxTotal)
		--外币
		SET @numNTaxBanlance = -(@NtotalMoney - @numNNoTaxTotal)
		
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		
	END

	RETURN 0
END

------------------------------ 组合品销售退货单
IF @numBillType = 46
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate	
		FROM	PT_Combin_SaleBackBillDetail a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END 
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(Total),0),@numNNoTaxTotal = ISNULL(SUM(NTotal),0) FROM PT_Combin_SaleBackBillDetail WHERE BillNumberID = @intBillNumberID
	IF ((@numTotalMoney - @numNoTaxTotal <> 0 ) OR (@NtotalMoney - @numNNoTaxTotal<>0))
	BEGIN
		SET @numTaxBanlance = -(@numTotalMoney - @numNoTaxTotal)
		--外币
		SET @numNTaxBanlance = -(@NtotalMoney - @numNNoTaxTotal)
		
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		
	END

	RETURN 0
END

------------------------------ 同价调拨单
IF @numBillType = 17
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				KTypeId,
				KTypeId2,
				InCargoID,
				OutCargoID,
				0 AS NPrice,
				0 AS NTotal,
				0 AS NSalePrice,
				0 AS NSaleTotal,
				0 AS NTaxPrice,
				0 AS NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				Comment,
				MUnitRate
		FROM	MoveBill
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@chvKTypeId,
											@chvKTypeID2,
											@intInCargoID,
											@intOUtCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
			
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		
		-- 出库
		SELECT 
			@numQtyTemp = -@numQty,
			@numNQtyTemp=-@numNQty
			
		SET @numPriceTemp = 0
		SET @numTotalTemp = 0
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1
		SET @chvBTypeID = '0'
		
		SET @intCargoID=@intOutCargoID

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
			@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		-- 入库
		SELECT 
			@numQtyTemp = @numQty
			
			
		SET @numPriceTemp = 0
		SET @numTotalTemp = 0
		
		IF @nCostingMethod=@HAND
		BEGIN
			SET @numCostPriceTemp = @numInputCostPrice
		END
		ELSE
		BEGIN
			SET @numCostPriceTemp = 0
		END
		
		SET @numCostTotalTemp = 0
		SET @intCargoID=@intInCargoID

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID2,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
			@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,1,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1


		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,												
												@chvKTypeId,
												@chvKTypeID2,
												@intInCargoID,
												@intOUtCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END 
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	RETURN 0
END
------------------------------ 变价调拨单
IF @numBillType = 21
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				Price,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				KTypeId,
				KTypeId2,
				InCargoID,
				OutCargoID,
				Price AS NPrice,
				Total AS NTotal,
				0 AS NSalePrice,
				0 AS NSaleTotal,
				0 AS NTaxPrice,
				0 AS NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				Comment,
				MUnitRate	
		FROM	MoveBjBill
		WHERE	BillNumberID = @intBillNumberID


	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@chvKTypeId,
											@chvKTypeID2,
											@intInCargoID,
											@intOutCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		-- 出库
		SELECT 
			@numQtyTemp = -@numQty,
			@numNQtyTemp=-@numNQty
			
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = -@numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1
		SET @chvBTypeID = '0'
		SET @intCargoID=@intOutCargoID

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
			@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		-- 入库
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numPrice
		SET @numCostTotalTemp = @numTotal
		SET @intCargoID=@intInCargoID

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID2,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
			@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,1,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@chvKTypeId,
												@chvKTypeID2,
												@intInCargoID,
												@intOutCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END 
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	RETURN 0
END
------------------------------ 零售单
IF @numBillType = 305
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate
		FROM	RetailBill a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = -@numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = -@numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SET @numSaleTotal = -@numSaleTotal
		SET @numTaxTotal = -@numTaxTotal
		
		SELECT
			@numNTotal=-@numNTotal,
			@numNSaleTotal=-@numNSaleTotal,
			@numNTaxTotal=-@numNTaxTotal,
			@numNQty=-@numNQty
			
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1


		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	

	RETURN 0

END

	

------------------------------ 会计凭证
IF @numBillType = 159
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	
				a.TypeATypeID,
				a.ATypeID,
				a.J_Total,
				a.D_Total,
				a.NJ_Total,
				a.ND_Total,
				a.CID,
				a.Rate,
				a.ID,
				a.ETypeID,
				a.DTypeID,
				c.TypeName,
				c.UserCode
		FROM	AccountCredence a
		INNER JOIN BillIndex b
		ON a.BillNumberID=b.BillNumberID
		INNER JOIN Ac_Items c
		ON a.TypeATypeID=c.nid
		WHERE	a.BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvTypeATypeID,
											@chvATypeID,
											@numJTotal,
											@numDTotal,
											@numNJTotal,
											@numNDTotal,
											@intCID,
											@decrate,
											@intID,
											@chvETypeID,
											@chvDTypeID,
											@chvTempTypeName,
											@chvTempUserCode
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @numJTotal > 0 OR @numNJTotal>0
		BEGIN
			--IF LEFT(@chvTypeATypeID,5) IN ('00001','00004')	-- 借方科目
			IF @chvTempTypeName IN ('B','E','F','C')
			BEGIN
				SELECT 
					@numTotal = @numJTotal,
					@numNTotal = @numNJTotal
			END
			ELSE
			BEGIN
				SELECT 
					@numTotal = -@numJTotal,
					@numNTotal = -@numNJTotal
			END
		END
		ELSE
		BEGIN
			--IF LEFT(@chvTypeATypeID,5) IN ('00001','00004')	-- 借方科目
			IF @chvTempTypeName IN ('B','E','F','C')
			BEGIN
				SELECT 
					@numTotal = -@numDTotal,
					@numNTotal = -@numNDTotal
			END
			ELSE
			BEGIN
				SELECT 
					@numTotal = @numDTotal,
					@numNTotal = @numNDTotal
			END
		END

		-- 循环写入 ListTable
		
		
		
			
		IF @chvTempUserCode IN( '987','2121','2131','1151','1132','1251','2122')	-- 应收/付款合计
		BEGIN
			EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@chvTypeATypeID,@chvATypeID,@chvETypeID,
				@numTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTotal,@decRate
				
			--EXEC GP_AType_Total_AddEdit @chvTypeATypeID,@chvSTypeID,@intCID,@numTotal,@numNTotal,''
			
			IF @chvTempUserCode IN( '987','2121','2131','1151')
			BEGIN
				IF @chvTempUserCode='987'
					SET @chvAIDFlag=1
				ELSE IF @chvTempUserCode='2121'
					SET @chvAIDFlag=2
				ELSE IF @chvTempUserCode='1151'
					SET @chvAIDFlag=3
				ELSE IF @chvTempUserCode='2131'
					SET @chvAIDFlag=4
			END
		END
		ELSE
		BEGIN	
			EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
					@numTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTotal,@decRate
					
			--EXEC GP_AType_Total_AddEdit @chvTypeATypeID,@chvSTypeID,@intCID,@numTotal,@numNTotal,''
		END
	
		
		IF @intReturnCode <> 0 GOTO ERROR1
		
		IF @chvTempUserCode='1132'
		BEGIN
			--内部应收
			EXEC	GP_InnerARTotal_AddEdit
			@intBillNumberID,
			@numTotal,
			@intID,
			@strErrMsg	OUT
		END
		
		
		

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvTypeATypeID,
												@chvATypeID,
												@numJTotal,
												@numDTotal,
												@numNJTotal,
												@numNDTotal,
												@intCID,
												@decrate,
												@intID,
												@chvETypeID,
											    @chvDTypeID,
												@chvTempTypeName,
												@chvTempUserCode
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	IF @intReturnCode <> 0 GOTO ERROR1

	RETURN 0
END


------------------------------ 受托代销收货
IF @numBillType = 144
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	a.PTypeID,
				Qty,
				DiscountPrice,
				Total,
				a.[ID],
				OutFactoryDate,
				CASE b.CostSale WHEN 1 THEN CASE InputCostPrice WHEN 0 THEN  ROUND(DBO.F_GetCostPrice(a.STypeID,a.PTypeID,a.KTypeID),@intPriceDot) ELSE InputCostPrice END
				ELSE
					CASE @nCostingMethod WHEN @Hand THEN 
						CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetCostPrice(a.STypeID,a.PTypeID,a.KTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END 
				ELSE ISNULL(InputCostPrice,0) END 
				END AS InputCostPrice,
				a.GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				CASE b.CostSale WHEN 1 THEN 
					CASE WHEN InputCostPrice=0 AND HandZeroCost=1 THEN 1 ELSE
					CASE ROUND(DBO.F_GetRecPrice(a.STypeID,a.PTypeID),@intPriceDot) WHEN 0 THEN 0 ELSE 1 
					END END
				ELSE HandZeroCost END,
				--CASE b.CostSale WHEN 0 THEN 1 ELSE HandZeroCost END,
				a.[ID],
				a.Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				a.KTypeID,
				a.Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				a.Comment,
				a.MUnitRate				
		FROM	CommissionBill a
		INNER JOIN Billindex b
		ON a.BillNumberId=b.BillNumberId
		WHERE	a.BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 清空无效数据行
		DELETE FROM CommissionStock
		WHERE	Type = 144
				AND Qty = 0
				AND Total = 0
				AND PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID

		-- 循环写入 InOustStockTable
		SET @numQtyTemp = ROUND(@numQty,@intQtyDot)
		SET @numPriceTemp = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp = ROUND(@numTotal,@intMoneyDot)
		
		IF @intCostSale=0 
		BEGIN
			SET @numCostPriceTemp = ROUND(@numPrice,@intPriceDot)
			SET @numCostTotalTemp = ROUND(@numTotal,@intMoneyDot)
		END
		ELSE
		BEGIN
			SET @numCostPriceTemp = ROUND(@numInputCostPrice,@intPriceDot)
			SET @numCostTotalTemp = ROUND(@numInputCostPrice*@numQty,2)
		END
		
		
		
		
		SET @numQtyTemp1 = ROUND(@numQty,@intQtyDot)
		SET @numPriceTemp1 = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp1 = ROUND(@numTotal,@intMoneyDot)
		SET @numCostPriceTemp1 = 0
		SET @numCostTotalTemp1 = 0

		-- 写账面库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		-- 写代销库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp1,@numPriceTemp1,@numTotalTemp1,@numCostPriceTemp1,@numCostTotalTemp1,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			0,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END

	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- ********* 处理生成 ListTable 凭证记录 *********
	SELECT	@numNoTaxTotal = ROUND(ISNULL(SUM(Total),0),@intMoneyDot)--,@numNNoTaxTotal = ISNULL(SUM(NTotal),0)
	FROM	CommissionBill
	WHERE	BillNumberID = @intBillNumberID

	IF @numNoTaxTotal <> 0 AND @intCostSale=0
	BEGIN
		-- 库存商品总值
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvBTypeID,@chvETypeID,
			@numNoTaxTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@sysCid,@numNoTaxTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@chvSTypeID,@sysCid,@numNoTaxTotal,@numNoTaxTotal,''
	
		-- 受托代销商品款
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@DXGOODSMONEY_ID,@chvBTypeID,@chvETypeID,
			@numNoTaxTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@sysCid,@numNoTaxTotal,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @DXGOODSMONEY_ID,@chvSTypeID,@sysCid,@numNoTaxTotal,@numNoTaxTotal,''
	END


	RETURN 0
END
------------------------------ 受托代销结算
IF @numBillType = 145
BEGIN
	DECLARE	@numSTDXPrice		 NUMERIC(24, 10) ,
			@numSTDXTotal		 NUMERIC(24, 10) ,
			@numSTDXCostPrice	 NUMERIC(24, 10) ,
			@numSTDXCostTotal	 NUMERIC(24, 10) ,
			@numSTDXQty			 NUMERIC(24, 10) 

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				GoodsNumber,
				Comment,
				MUnitRate
		FROM	CommissionBill
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@GoodsNumber,
											@strComment,
											@numMUnitRate
												
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 清空无效数据行
		DELETE FROM CommissionStock
		WHERE	Type = 144
				AND Qty = 0
				AND Total = 0
				AND PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID

		-- 循环写入 InOustStockTable
		SELECT 
			@numQtyTemp1 = ROUND(-@numQty,@intQtyDot),
			@numNQty=ROUND(-@numNQty,@intQtyDot)
			
		SET @numPriceTemp1 = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp1 = ROUND(-@numTotal,@intMoneyDot)
		SET @numCostPriceTemp1 = 0
		SET @numCostTotalTemp1 = 0

		SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		
		SELECT
			@numNTotal=ROUND(-@numNTotal,@intMoneyDot),
			@numNSaleTotal=ROUND(-@numNSaleTotal,@intMoneyDot),
			@numNTaxTotal=ROUND(-@numNTaxTotal,@intMoneyDot)
		
		-- 写代销库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp1,@numPriceTemp1,@numTotalTemp1,@numCostPriceTemp1,@numCostTotalTemp1,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			0,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@GoodsNumber,
												@strComment,
												@numMUnitRate
												
	END

	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

-- ********* 处理生成 ListTable 凭证记录 *********

	SELECT	@numNoTaxTotal = ROUND(-ISNULL(SUM(Total),0),@intMoneyDot),@numNNoTaxTotal = ROUND(-ISNULL(SUM(NTotal),0),@intMoneyDot)
	FROM	CommissionBill
	WHERE	BillNumberID = @intBillNumberID

	IF @numNoTaxTotal <> 0
	BEGIN
		-- 受托代销商品款
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@DXGOODSMONEY_ID,@chvBTypeID,@chvETypeID,
			@numNoTaxTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@syscid,@numNoTaxTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @DXGOODSMONEY_ID,@chvSTypeID,@syscid,@numNoTaxTotal,@numNoTaxTotal,''
	END

	-- 应交税金
	IF ((@numTotalMoney - ABS(@numNoTaxTotal) <> 0) OR (@nTotalMoney - ABS(@numNNoTaxTotal)<>0))
	BEGIN
		SET @numTaxBanlance = ROUND(-(@numTotalMoney - ABS(@numNoTaxTotal)),@intMoneyDot)
		SET @numNTaxBanlance = ROUND(-(@nTotalMoney - ABS(@numNNoTaxTotal)),@intMoneyDot)
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @PAY_TAXMONEY_ID,@chvSTypeID,@intCID,@numTaxBanlance,@numNTaxBanlance,''
	END
	
	RETURN 0
END
------------------------------ 受托代销退货
IF @numBillType = 146
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				[ID],
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				Comment,
				MUnitRate
		FROM	CommissionBill
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 清空无效数据行
		DELETE FROM CommissionStock
		WHERE	Type = 144
				AND Qty = 0
				AND Total = 0
				AND PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID

		-- 循环写入 InOustStockTable
		SET @numQtyTemp = ROUND(-@numQty,@intQtyDot)
		SET @numPriceTemp = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp = ROUND(-@numTotal,@intMoneyDot)
		SET @numCostPriceTemp = ROUND(@numInputCostPrice,@intPriceDot)
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SET @numQtyTemp1 = ROUND(-@numQty,@intQtyDot)
		SET @numPriceTemp1 = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp1 = ROUND(-@numTotal,@intMoneyDot)
		SET @numCostPriceTemp1 = 0
		SET @numCostTotalTemp1 = 0

		SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		
		SELECT
			@numNTotal=ROUND(-@numNTotal,@intMoneyDot),
			@numNSaleTotal=ROUND(-@numNSaleTotal,@intMoneyDot),
			@numNTaxTotal=ROUND(-@numNTaxTotal,@intMoneyDot),
			@numNQtyTemp=ROUND(-@numNQty,@intQtyDot)
			
		-- 写账面库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		-- 写代销库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp1,@numPriceTemp1,@numTotalTemp1,@numCostPriceTemp1,@numCostTotalTemp1,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			0,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END

	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	SELECT	@numNoTaxTotal = ROUND(-ISNULL(SUM(Total),0),@intMoneyDot)--,@numNNoTaxTotal = -ISNULL(SUM(NTotal),0)
	FROM	CommissionBill
	WHERE	BillNumberID = @intBillNumberID

	IF @numNoTaxTotal <> 0
	BEGIN
		-- 受托代销商品款
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@DXGOODSMONEY_ID,@chvBTypeID,@chvETypeID,
			@numNoTaxTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@syscid,@numNoTaxTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @DXGOODSMONEY_ID,@chvSTypeID,@syscid,@numNoTaxTotal,@numNoTaxTotal,''
	END


	RETURN 0
END
------------------------------ 受托代销调价
IF @numBillType = 147
BEGIN
	DECLARE @numSTDXAllOutTotal  NUMERIC(24, 10) 
	SET @numSTDXAllOutTotal = 0
	

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				[ID],
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				GoodsNumber,
				Comment,
				MUnitRate
		FROM	CommissionBill
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@intID	,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@GoodsNumber,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 清空无效数据行
		DELETE FROM CommissionStock
		WHERE	Type = 144
				AND Qty = 0
				AND Total = 0
				AND CostTotal = 0
				AND PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID


		-- 读取受托代销库的库存成本价 CostTotal
		IF EXISTS (
			SELECT Qty FROM	CommissionStock
			WHERE	Type = 144
					AND Qty <> 0
					AND BTypeID = @chvBTypeID
					AND PTypeID = @chvPTypeID
					AND STypeID=@chvSTypeID
		)
		BEGIN
			SELECT	@numSTDXPrice = ROUND(CASE QTY WHEN 0 THEN 0 ELSE CAST(Total/Qty AS  NUMERIC(24, 10) ) END,@intPriceDot),
					@numSTDXTotal = ROUND(Total,@intMoneyDot),
					@numSTDXQty = ROUND(Qty,@intQtyDot)
			FROM	CommissionStock
			WHERE	Type = 144
					AND BTypeID = @chvBTypeID
					AND PTypeID = @chvPTypeID
					AND STypeID=@chvSTypeID
			
		END
		ELSE
		BEGIN
			SET @numSTDXPrice = 0
			SET @numSTDXTotal = 0
		END

		-- 循环写入 InOustStockTable
		SELECT 
			@numQtyTemp = ROUND(-@numQty,@intQtyDot),
			@numNQtyTemp=ROUND(-@numNQty,@intQtyDot)
			
		SET @numPriceTemp = @numSTDXPrice
		IF @numSTDXQty = @numQty
			SET @numTotalTemp = ROUND(-@numSTDXTotal,@intMoneyDot)
		ELSE
			SET @numTotalTemp = ROUND(-CAST(@numSTDXPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)

		SET @numSTDXAllOutTotal = ROUND(@numSTDXAllOutTotal,@intMoneyDot) + ROUND(@numTotalTemp,@intMoneyDot)

		SET @numCostPriceTemp = 0
		SET @numCostTotalTemp = 0

		SET @numQtyTemp1 = ROUND(@numQty,@intQtyDot)
		SET @numPriceTemp1 = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp1 = ROUND(@numTotal,@intMoneyDot)
		SET @numCostPriceTemp1 = 0
		SET @numCostTotalTemp1 = 0

		
		IF @decRate<>1
		BEGIN
			IF @strOPRate='0'
			BEGIN
				SET @numNTotalTemp=ROUND((CAST(@numTotalTemp AS  NUMERIC(24, 10) ))/(CAST(@decRate AS  NUMERIC(24, 10) )),@intMoneyDot)
			END
			ELSE
			BEGIN
				SET @numNTotalTemp=ROUND((CAST(@numTotalTemp AS  NUMERIC(24, 10) ))*(CAST(@decRate AS  NUMERIC(24, 10) )),@intMoneyDot)
			END
		END
		ELSE
		BEGIN
			SET @numNTotalTemp=ROUND(@numTotalTemp,@intMoneyDot)
		END
			
		IF @decRate<>1
		BEGIN
			IF @numQtyTemp<>0
			BEGIN
				SET @numNPriceTemp=ROUND(CAST(@numNTotalTemp AS  NUMERIC(24, 10) )/CAST(@numQtyTemp AS  NUMERIC(24, 10) ),@intPriceDot)
			END
			ELSE
			BEGIN
				IF @strOPRate='0'
				BEGIN
					SET @numNPriceTemp=ROUND((CAST(@numPriceTemp AS  NUMERIC(24, 10) ))/(CAST(@decRate AS  NUMERIC(24, 10) )),@intMoneyDot)
				END
				ELSE
				BEGIN
					SET @numNPriceTemp=ROUND((CAST(@numPriceTemp AS  NUMERIC(24, 10) ))*(CAST(@decRate AS  NUMERIC(24, 10) )),@intMoneyDot)
				END
			END
		END
		ELSE
		BEGIN
			SET @numNPriceTemp=ROUND(@numPriceTemp,@intMoneyDot)
		END

		-- 写代销库存 -- 出库
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,
			0,1,@numPriceTemp,@numTotalTemp,@numPriceTemp,@numTotalTemp,@chvDTypeID,@chvSTypeID,
			0,@numNPriceTemp,@numNTotalTemp,@numNPriceTemp,@numNTotalTemp,@numNPriceTemp,@numNTotalTemp,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		-- 写代销库存 -- 入库
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp1,@numPriceTemp1,@numTotalTemp1,@numCostPriceTemp1,@numCostTotalTemp1,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,
			0,1,@numPriceTemp1,@numTotalTemp1,@numPriceTemp1,@numTotalTemp1,@chvDTypeID,@chvSTypeID,
			0,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@GoodsNumber,
												@strComment,
												@numMUnitRate
	END

	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
	SELECT	@numNoTaxTotal = ISNULL(SUM(Total),0)
	FROM	CommissionBill
	WHERE	BillNumberID = @intBillNumberID

	SET @numBanlanceTotal = ROUND(@numNoTaxTotal,@intMoneyDot) + ROUND(@numSTDXAllOutTotal,@intMoneyDot)

	IF @numBanlanceTotal <> 0
	BEGIN
		-- 受托代销商品款
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@DXGOODSMONEY_ID,@chvBTypeID,@chvETypeID,
			@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,@numBanlanceTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @DXGOODSMONEY_ID,@chvSTypeID,@SysCid,@numBanlanceTotal,@numBanlanceTotal,''
		-- 销售成本
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@SALE_COST_ID,@chvBTypeID,@chvETypeID,
			@numBanlanceTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,@numBanlanceTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @SALE_COST_ID,@chvSTypeID,@SysCid,@numBanlanceTotal,@numBanlanceTotal,''
	END

	RETURN 0
END
------------------------------ 销售换货单
IF @numBillType = 160
BEGIN
DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	PTypeID,
			Qty,
			DiscountPrice,
			Total,
			JobNumber,
			OutFactoryDate,
			InOrOut,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice ,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			Discount,
			SalePrice,
			SaleTotal,
			TaxPrice,
			TaxTotal,
			KTypeID,
			Tax,
			CargoID,
			NDiscountPrice,
			NTotal,
			NSalePrice,
			NSaleTotal,
			NTaxPrice,
			NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			MUnitID,
			IsGift,
			b.IsService,
			a.Comment,
			a.MUnitRate
	FROM	SaleGoodsExchangeBill a
	INNER JOIN PType b
	ON a.PtypeId=b.typeId
	WHERE	BillNumberID = @intBillNumberID
	ORDER BY [ID]

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@chrInOrOut,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax		,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF UPPER(@chrInOrOut)='I'	-- 销售退货入库
		BEGIN
			-- 循环写入 InOustStockTable
			SET @numQtyTemp = @numQty
			SET @numPriceTemp = @numPrice
			SET @numTotalTemp = @numTotal
			SET @numCostPriceTemp = @numInputCostPrice
			SET @numCostTotalTemp = ROUND(CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
			IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
				SET @HandZeroCost = 1
	
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
				@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
				@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END
		ELSE	-- 销售出库
		BEGIN
			-- 循环写入 InOustStockTable
			SET @numQtyTemp = -@numQty
			SET @numPriceTemp = @numPrice
			SET @numTotalTemp = -@numTotal
			SET @numCostPriceTemp = @numInputCostPrice
			SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
			IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
				SET @HandZeroCost = 1

			SET @numSaleTotal = -@numSaleTotal
			SET @numTaxTotal = -@numTaxTotal
			
			SELECT
				@numNTotal=-@numNTotal,
				@numNSaleTotal=-@numNSaleTotal,
				@numNTaxTotal=-@numNTaxTotal,
				@numNQty=-@numNQty
			
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
				@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
				@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@chrInOrOut,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax		,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
													
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(CASE InOrOut WHEN 'O' THEN Total ELSE -Total END),0), 
			@numNNoTaxTotal = ISNULL(SUM(CASE InOrOut WHEN 'O' THEN NTotal ELSE -NTotal END),0)
	FROM SaleGoodsExchangeBill WHERE BillNumberID = @intBillNumberID
	IF ((@numTotalMoney - @numNoTaxTotal <> 0) OR (@NTotalMoney - @numnNoTaxTotal<>0))
	BEGIN
		SET @numTaxBanlance = @numTotalMoney - @numNoTaxTotal
		SET @numNtaxBanlance = @NTotalMoney - @numnNoTaxTotal
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNtaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		
	END
	
	RETURN 0
END
------------------------------ 采购换货单
IF @numBillType = 161
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				InOrOut,
				CASE InOrOut WHEN 'I' THEN DiscountPrice ELSE CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END END AS InputCostPrice,
				OutFactoryDate,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				IsGift,
				b.IsService,
				a.comment,
				a.MUnitRate
		FROM	BuyGoodsExchangeBill a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID
		ORDER BY [ID]

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@chrInOrOut,
											@numInputCostPrice,
											@datOutFactoryDate,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF UPPER(@chrInOrOut)='O'	-- 采购退货出库
		BEGIN
			-- 循环写入 InOustStockTable
			SET @numQtyTemp = -@numQty
			SET @numPriceTemp = @numPrice
			SET @numTotalTemp = -@numTotal
			SET @numCostPriceTemp = @numInputCostPrice
			SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
			IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
				SET @HandZeroCost = 1

			SET @numSaleTotal = -@numSaleTotal
			SET @numTaxTotal = -@numTaxTotal
			
			SELECT
				@numNTotal=-@numNTotal,
				@numNSaleTotal=-@numNSaleTotal,
				@numNTaxTotal=-@numNTaxTotal,
				@numNQty=-@numNQty
			
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
				@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
				@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END
		ELSE	-- 采购入库
		BEGIN
			-- 循环写入 InOustStockTable
			SET @numQtyTemp = @numQty
			SET @numPriceTemp = @numPrice
			SET @numTotalTemp = @numTotal
			SET @numCostPriceTemp = @numPrice
			SET @numCostTotalTemp = @numTotal
	
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
				@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
				@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@chrInOrOut,
												@numInputCostPrice,
												@datOutFactoryDate,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
													
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- 应交税金
	SELECT @numNoTaxTotal = ISNULL(SUM(CASE InOrOut WHEN 'I' THEN Total ELSE -Total END),0) ,
			@numNNoTaxTotal = ISNULL(SUM(CASE InOrOut WHEN 'I' THEN NTotal ELSE -NTotal END),0) 
	FROM BuyGoodsExchangeBill WHERE BillNumberID = @intBillNumberID
	IF ((@numTotalMoney - @numNoTaxTotal <> 0) OR (@nTotalMoney - @numnNoTaxTotal<>0))
	BEGIN
		SET @numTaxBanlance = -(@numTotalMoney - @numNoTaxTotal)
		SET @numnTaxBanlance = -(@nTotalMoney - @numnNoTaxTotal)
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNNoTaxTotal,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
	
	END

	RETURN 0
END
------------------------------ 赠送单
IF @numBillType = 139
BEGIN
DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	PTypeID,
			Qty,
			JobNumber,
			OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			CargoID,
			0 AS NPrice,
			0 AS NTotal,
			0 AS NSalePrice,
			0 AS NSaleTotal,
			0 AS NTaxPrice,
			0 AS NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			MUnitID,
			KTypeId,
			b.IsService,
			a.Comment,
			a.MUnitRate
	FROM	GiveBill a
	INNER JOIN PType b
	ON a.PtypeId=b.typeId
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@chvKTypeID,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SELECT 
			@numQtyTemp = -@numQty,
			@numNQty=-@numNQty
			
		SET @numPriceTemp = 0
		SET @numTotalTemp = 0
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
			@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,1,@intIsService
			,@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@chvKTypeID,
												@intIsService,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ 获赠单
IF @numBillType = 126
BEGIN
DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	PTypeID,
			Qty,
			JobNumber,
			OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			CargoID,
			0 AS NPrice,
			0 AS NTotal,
			0 AS NSalePrice,
			0 AS NSaleTotal,
			0 AS NTaxPrice,
			0 AS NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			MUnitID,
			KTypeID,
			b.IsService,
			a.Comment,
			a.MUnitRate
	FROM	GiveMeBill a
	INNER JOIN PType b
	ON a.PtypeId=b.typeId
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@chvKTypeID,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = 0
		SET @numTotalTemp = 0
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
			@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,1,@intIsService,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@chvKTypeID,
												@intIsService,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ 报损单
IF @numBillType = 9
BEGIN
DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	PTypeID,
			Qty,
			JobNumber,
			OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			CargoID,
			0 AS NPrice,
			0 AS NTotal,
			0 AS NSalePrice,
			0 AS NSaleTotal,
			0 AS NTaxPrice,
			0 AS NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			MUnitID,
			Comment,
			MUnitRate
	FROM	LoseBill
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SELECT 
			@numQtyTemp = -@numQty,
			@numNQty=-@numNQty
			
		SET @numPriceTemp = 0
		SET @numTotalTemp = 0
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		IF @ifIndexWX = 0	-- 盘点正常库
		BEGIN
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
				@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
				@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END
		ELSE	-- 盘点维修库
		BEGIN
			EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,
				@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment
												,@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ 报溢单
IF @numBillType = 14
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	PTypeID,
			Qty,
			JobNumber,
			OutFactoryDate,
			Price AS InputCostPrice,
			Total AS CostTotal,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			CargoID,
			0 AS NPrice,
			0 AS NTotal,
			0 AS NSalePrice,
			0 AS NSaleTotal,
			0 AS NTaxPrice,
			0 AS NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			MUnitID,
			Comment,
			MUnitRate
	FROM	OverFlowBill
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@numCostTotalTemp,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SELECT 
			@numQtyTemp = @numQty
			
		SET @numPriceTemp = 0
		SET @numTotalTemp = 0
		SET @numCostPriceTemp = @numInputCostPrice
		
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		IF @ifIndexWX = 0	-- 盘点正常库
		BEGIN
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
				@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
				@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END
		ELSE	-- 盘点维修库
		BEGIN
			EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,
				@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@numCostTotalTemp,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ 成本调价单
IF @numBillType = 57
BEGIN
	SELECT TOP 1 @ChangeAllStock = ISNULL(ChangeAllStock,0) FROM AdPriceBill WHERE BillNumberID = @intBillNumberID
	-- 得到成本核算法
	
	DECLARE
		@AdPriceType	TINYINT
		
	SELECT @AdPriceType=AdPriceType
	FROM Billindex
	WHERE BillNumberId=@intBillNumberID
	
	EXEC Gp_GetSubValue 'costing',@chvSTypeID,@CostingMethod OUTPUT
	
	
	IF @AdPriceType=1
	BEGIN
		--入库,数量都处理为零
		DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
			SELECT	
					a.PTypeID,
					a.Qty,
					a.Price,
					a.Total,
					a.JobNumber,
					a.OutFactoryDate,
					CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
					a.GoodsNumber,
					a.ProduceDate,
					a.ValidDate,
					a.GoodsBTypeID,
					a.GoodsCostPrice,
					a.HandZeroCost,
					a.[ID],
					a.CargoID,
					a.Price AS NPrice,
					a.Total AS NTotal,
					0 AS NSalePrice,
					0 AS NSaleTotal,
					0 AS NTaxPrice,
					0 AS NTaxTotal,
					0 AS ItemID,
					0 AS IsCombined,
					0 AS NQty,
					a.UnitRate,
					b.BaseUnitID AS MUnitID,
					a.ktypeid AS KTypeID,
					a.Comment,
					1 AS MUnitRate
			FROM	AdPriceBill a
			INNER JOIN PType b
			ON a.PTypeID=b.TypeID
			WHERE	BillNumberID = @intBillNumberID
		
			OPEN CreateMx_CURSOR
			FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
													@numQty,
													@numPrice,
													@numTotal,
													@chvJobNumber,
													@datOutFactoryDate,
													@numInputCostPrice,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID,
													@intCargoID,
													@numNPrice,
													@numNTotal,
													@numNSalePrice,
													@numNSaleTotal,
													@numNTaxPrice,
													@numNTaxTotal,
													@intItemID,
													@intIsCombined,
													@numNQty,
													@numUnitRate,
													@intMUnitID,
													@chvKTypeID,
													@strComment,
													@numMUnitRate
			WHILE @@FETCH_STATUS = 0
			BEGIN
				-- 循环写入 InOustStockTable
		
				-- 入库
				SELECT 
					@numQtyTemp = @numQty
				
				SET @numPriceTemp = @numPrice
				SET @numTotalTemp = @numTotal
				SET @numCostPriceTemp = @numPrice
				SET @numCostTotalTemp = @numTotal
		
				EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
					@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,1,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
					@strComment,@datPostTime,@numMUnitRate
				IF @intReturnCode <> 0 GOTO ERROR1
		
				FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
														@numQty,
														@numPrice,
														@numTotal,
														@chvJobNumber,
														@datOutFactoryDate,
														@numInputCostPrice,
														@GoodsNumber,
														@ProduceDate,
														@ValidDate,
														@GoodsBTypeID,
														@GoodsCostPrice,
														@HandZeroCost,
														@intID,
														@intCargoID,
														@numNPrice,
														@numNTotal,
														@numNSalePrice,
														@numNSaleTotal,
														@numNTaxPrice,
														@numNTaxTotal,
														@intItemID,
														@intIsCombined,
														@numNQty,
														@numUnitRate,
														@intMUnitID,
														@chvKTypeID,
														@strComment,
														@numMUnitRate
			END
			CLOSE CreateMx_CURSOR
			DEALLOCATE CreateMx_CURSOR

			RETURN 0
	END
	ELSE IF @AdPriceType=2
	BEGIN
		--出库,数量都处理为零
		DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
			SELECT	
					a.PTypeID,
					a.Qty,
					a.Price,
					a.Total,
					a.JobNumber,
					a.OutFactoryDate,
					CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
					a.GoodsNumber,
					a.ProduceDate,
					a.ValidDate,
					a.GoodsBTypeID,
					a.GoodsCostPrice,
					a.HandZeroCost,
					a.[ID],
					a.CargoID,
					a.Price AS NPrice,
					a.Total AS NTotal,
					0 AS NSalePrice,
					0 AS NSaleTotal,
					0 AS NTaxPrice,
					0 AS NTaxTotal,
					0 AS ItemID,
					0 AS IsCombined,
					0 AS NQty,
					a.UnitRate,
					b.BaseUnitID AS MUnitID,
					a.ktypeid AS KTypeID,
					a.Comment,
					1 AS MUnitRate
			FROM	AdPriceBill a
			INNER JOIN PType b
			ON a.PTypeID=b.TypeID
			WHERE	BillNumberID = @intBillNumberID
		
			OPEN CreateMx_CURSOR
			FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
													@numQty,
													@numPrice,
													@numTotal,
													@chvJobNumber,
													@datOutFactoryDate,
													@numInputCostPrice,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID,
													@intCargoID,
													@numNPrice,
													@numNTotal,
													@numNSalePrice,
													@numNSaleTotal,
													@numNTaxPrice,
													@numNTaxTotal,
													@intItemID,
													@intIsCombined,
													@numNQty,
													@numUnitRate,
													@intMUnitID,
													@chvKTypeID,
													@strComment,
													@numMUnitRate
			WHILE @@FETCH_STATUS = 0
			BEGIN
				-- 循环写入 InOustStockTable
				-- 出库
				SELECT 
					@numQtyTemp = 0,
					@numNQtyTemp= 0
				
				SET @numPriceTemp = @numPrice
				SET @numTotalTemp = -@numTotal
				SET @numCostPriceTemp = @numInputCostPrice
				SET @numCostTotalTemp = -@numTotal
				IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
					SET @HandZeroCost = 1
				SET @chvBTypeID = '0'
		
				EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
					@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
					@strComment,@datPostTime,@numMUnitRate
				IF @intReturnCode <> 0 GOTO ERROR1
		
		
				FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
													@numQty,
													@numPrice,
													@numTotal,
													@chvJobNumber,
													@datOutFactoryDate,
													@numInputCostPrice,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID,
													@intCargoID,
													@numNPrice,
													@numNTotal,
													@numNSalePrice,
													@numNSaleTotal,
													@numNTaxPrice,
													@numNTaxTotal,
													@intItemID,
													@intIsCombined,
													@numNQty,
													@numUnitRate,
													@intMUnitID,
													@chvKTypeID,
													@strComment,
													@numMUnitRate
				
				
			END
			
			CLOSE CreateMx_CURSOR
			DEALLOCATE CreateMx_CURSOR

			RETURN 0
	END
	ELSE IF @AdPriceType=0 
	BEGIN
		IF @CostingMethod = 0 --成本调价单使用调整金额处理成本（新逻辑占时只处理移动加权）
		BEGIN
			--库存中
			IF @ChangeAllStock <> 1 
			BEGIN
				DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
				SELECT	
					a.PTypeID,
					a.Qty,
					a.Price,
					ISNULL(a.ChangeTotal,0) AS ChangeTotal,
					a.JobNumber,
					a.OutFactoryDate,
					CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
					a.GoodsNumber,
					a.ProduceDate,
					a.ValidDate,
					a.GoodsBTypeID,
					a.GoodsCostPrice,
					a.HandZeroCost,
					a.[ID],
					a.CargoID,
					a.Price AS NPrice,
					0 AS NSalePrice,
					0 AS NSaleTotal,
					0 AS NTaxPrice,
					0 AS NTaxTotal,
					0 AS ItemID,
					0 AS IsCombined,
					0 AS NQty,
					a.UnitRate,
					b.BaseUnitID AS MUnitID,
					a.ktypeid AS KTypeID,
					a.Comment,
					1 AS MUnitRate
				FROM	AdPriceBill a
				INNER JOIN PType b
				ON a.PTypeID=b.TypeID
				WHERE	BillNumberID = @intBillNumberID
		
				OPEN CreateMx_CURSOR
				FETCH NEXT FROM CreateMx_CURSOR INTO	
													@chvPTypeID,
													@numQty,
													@numPrice,
													@numTotal,
													@chvJobNumber,
													@datOutFactoryDate,
													@numInputCostPrice,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID,
													@intCargoID,
													@numNPrice,
													@numNSalePrice,
													@numNSaleTotal,
													@numNTaxPrice,
													@numNTaxTotal,
													@intItemID,
													@intIsCombined,
													@numNQty,
													@numUnitRate,
													@intMUnitID,
													@chvKTypeID,
													@strComment,
													@numMUnitRate
				WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE @stockQty INT
					DECLARE @stockPrice NUMERIC(24,10)
					DECLARE @stockToal NUMERIC(24,10)
					SELECT @stockQty=Qty,@stockPrice=Price,@stockToal=Total from dbo.GoodsStocks WHERE PtypeId=@chvPTypeID AND KtypeId=@chvKTypeID
					--IF(@stockToal+@numTotal<0)
					--	GOTO ERROR4 --产品确认放开，调整金额允许比商品总金额达
					-- 入库
					SELECT 
					@numQtyTemp = 0
				
					SET @numPriceTemp = @stockPrice
					SET @numTotalTemp = ROUND(@numTotal,@intMoneyDot)
					IF @stockQty<>0
						SET @numCostPriceTemp = ROUND((@stockToal+@numTotal)/@stockQty,@intPriceDot)
					ELSE
						SET @numCostPriceTemp=0
					SET @numCostTotalTemp = ROUND(@numTotal,@intMoneyDot)
		
					EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
					@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,1,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,0,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
					@strComment,@datPostTime,@numMUnitRate
					IF @intReturnCode <> 0 GOTO ERROR1
		
					FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
														@numQty,
														@numPrice,
														@numTotal,
														@chvJobNumber,
														@datOutFactoryDate,
														@numInputCostPrice,
														@GoodsNumber,
														@ProduceDate,
														@ValidDate,
														@GoodsBTypeID,
														@GoodsCostPrice,
														@HandZeroCost,
														@intID,
														@intCargoID,
														@numNPrice,
														@numNSalePrice,
														@numNSaleTotal,
														@numNTaxPrice,
														@numNTaxTotal,
														@intItemID,
														@intIsCombined,
														@numNQty,
														@numUnitRate,
														@intMUnitID,
														@chvKTypeID,
														@strComment,
														@numMUnitRate
				END
				CLOSE CreateMx_CURSOR
				DEALLOCATE CreateMx_CURSOR

				RETURN 0
			END
			ELSE
			BEGIN
				DECLARE	
					@numStockQty  NUMERIC(24, 10) ,@numStockTotal  NUMERIC(24, 10) ,@numStockNQty  NUMERIC(24, 10) 

				DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
				SELECT	
					a.PTypeID,
					0 AS qty,
					a.Price,
					0 AS total,
					a.JobNumber,
					a.OutFactoryDate,
					CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
					a.GoodsNumber,
					a.ProduceDate,
					a.ValidDate,
					a.GoodsBTypeID,
					a.GoodsCostPrice,
					a.HandZeroCost,
					a.[ID],
					0 AS CargoID,
					a.Price AS NPrice,
					0 AS NTotal,
					0 AS NSalePrice,
					0 AS NSaleTotal,
					0 AS NTaxPrice,
					0 AS NTaxTotal,
					0 AS ItemID,
					0 AS IsCombined,
					0 AS NQty,
					a.UnitRate,
					b.BaseUnitID AS MUnitID,
					a.ktypeid AS KTypeID,
					a.Comment,
					1 AS MUnitRate
				FROM	AdPriceBill a
				INNER JOIN PType b
				ON a.PTypeID=b.TypeID
				WHERE	BillNumberID = @intBillNumberID
		
				OPEN CreateMx_CURSOR
				FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
													@numQty,
													@numPrice,
													@numTotal,
													@chvJobNumber,
													@datOutFactoryDate,
													@numInputCostPrice,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID,
													@intCargoID,
													@numNPrice,
													@numNTotal,
													@numNSalePrice,
													@numNSaleTotal,
													@numNTaxPrice,
													@numNTaxTotal,
													@intItemID,
													@intIsCombined,
													@numNQty,
													@numUnitRate,
													@intMUnitID,
													@chvKTypeID,
													@strComment,
													@numMUnitRate
				WHILE @@FETCH_STATUS = 0
				BEGIN
					DECLARE	StockPTypeCursor CURSOR FOR
					SELECT a.KTypeID,a.Qty,a.Total,c.NQty 
					FROM GoodsStocks a
					INNER JOIN 
					(
						SELECT TypeID
						FROM Stock 
						WHERE STypeID=@chvSTypeID
					) b
					ON a.KTypeID=b.TypeID
					AND	a.PTypeID = @chvPTypeID
					INNER JOIN
					(
						SELECT PTypeID,KTypeID,SUM(Qty) AS Qty,SUM(NQty) AS NQty
						FROM GOODSSTOCKS_QTY
						GROUP BY PTypeID,KTypeID
					) c
					ON a.KtypeId=c.KTypeID
					AND c.PTypeID=@chvPTypeID
					WHERE ( a.Qty <> 0 OR ( a.Qty = 0 AND a.Total <> 0 ) )

					OPEN StockPTypeCursor
					FETCH NEXT FROM StockPTypeCursor INTO @chvKTypeID,@numStockQty,@numStockTotal,@numStockNQty
					WHILE @@FETCH_STATUS = 0
					BEGIN
						SET @numQtyTemp	= 0
						SET @numCostPriceTemp = 0
						SET @numCostTotalTemp = 0
						SET @numNQtyTemp= 0
						set @numNQty= 0
					
						IF @numStockQty = 0
						BEGIN
							SET @numPriceTemp= 0--@dPrice
							SET @numTotalTemp		= 0--CAST(@dPrice AS  NUMERIC(24, 10) )
						END
						ELSE
						BEGIN
							SET @numPriceTemp = @numPrice
							SET @numCostPriceTemp = @numPrice
							SET @numTotalTemp = ROUND((@numPrice-CAST(@numStockTotal / @numStockQty AS  NUMERIC(24, 10)))*@numStockQty,@intMoneyDot)
							SET @numCostTotalTemp=@numTotalTemp;
						END

						EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
						@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,
						@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
						@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
						@strComment,@datPostTime,@numMUnitRate
						IF @intReturnCode <> 0 GOTO ERROR1
					
						FETCH NEXT FROM StockPTypeCursor INTO @chvKTypeID,@numStockQty,@numStockTotal,@numStockNQty
					END

					CLOSE StockPTypeCursor
					DEALLOCATE StockPTypeCursor


					IF @@ERROR <> 0
					BEGIN
						CLOSE CreateMx_CURSOR
						DEALLOCATE CreateMx_CURSOR
					END
					FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
													@numQty,
													@numPrice,
													@numTotal,
													@chvJobNumber,
													@datOutFactoryDate,
													@numInputCostPrice,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID,
													@intCargoID,
													@numNPrice,
													@numNTotal,
													@numNSalePrice,
													@numNSaleTotal,
													@numNTaxPrice,
													@numNTaxTotal,
													@intItemID,
													@intIsCombined,
													@numNQty,
													@numUnitRate,
													@intMUnitID,
													@chvKTypeID,
													@strComment,
													@numMUnitRate
				END

				CLOSE CreateMx_CURSOR
				DEALLOCATE CreateMx_CURSOR

				RETURN 0
			END
		END
		ELSE 
		BEGIN
		--库存中
			DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
			SELECT	
					a.PTypeID,
					a.Qty,
					a.Price,
					a.Total,
					a.JobNumber,
					a.OutFactoryDate,
					CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
					a.GoodsNumber,
					a.ProduceDate,
					a.ValidDate,
					a.GoodsBTypeID,
					a.GoodsCostPrice,
					a.HandZeroCost,
					a.[ID],
					a.CargoID,
					a.Price AS NPrice,
					a.Total AS NTotal,
					0 AS NSalePrice,
					0 AS NSaleTotal,
					0 AS NTaxPrice,
					0 AS NTaxTotal,
					0 AS ItemID,
					0 AS IsCombined,
					a.NQty,
					a.UnitRate,
					b.BaseUnitID AS MUnitID,
					a.ktypeid AS KTypeID,
					a.Comment,
					1 AS MUnitRate
			FROM	AdPriceBill a
			INNER JOIN PType b
			ON a.PTypeID=b.TypeID
			WHERE	BillNumberID = @intBillNumberID
		
			OPEN CreateMx_CURSOR
			FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
													@numQty,
													@numPrice,
													@numTotal,
													@chvJobNumber,
													@datOutFactoryDate,
													@numInputCostPrice,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID,
													@intCargoID,
													@numNPrice,
													@numNTotal,
													@numNSalePrice,
													@numNSaleTotal,
													@numNTaxPrice,
													@numNTaxTotal,
													@intItemID,
													@intIsCombined,
													@numNQty,
													@numUnitRate,
													@intMUnitID,
													@chvKTypeID,
													@strComment,
													@numMUnitRate
			WHILE @@FETCH_STATUS = 0
			BEGIN
				-- 循环写入 InOustStockTable
				-- 出库
				SELECT 
					@numQtyTemp = -@numQty,
					@numNQtyTemp= -@numNQty
				
				SET @numPriceTemp = @numPrice
				SET @numTotalTemp = -@numTotal
				SET @numCostPriceTemp = @numInputCostPrice
				SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
				IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
					SET @HandZeroCost = 1
				SET @chvBTypeID = '0'
		
				EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
					@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
					@strComment,@datPostTime,@numMUnitRate
				IF @intReturnCode <> 0 GOTO ERROR1
		
				-- 入库
				SELECT 
					@numQtyTemp = @numQty
				
				SET @numPriceTemp = @numPrice
				SET @numTotalTemp = ROUND(@numTotal,@intMoneyDot)
				SET @numCostPriceTemp = @numPrice
				SET @numCostTotalTemp = ROUND(@numTotal,@intMoneyDot)
		
				EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
					@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,1,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
					@strComment,@datPostTime,@numMUnitRate
				IF @intReturnCode <> 0 GOTO ERROR1
		
				FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
														@numQty,
														@numPrice,
														@numTotal,
														@chvJobNumber,
														@datOutFactoryDate,
														@numInputCostPrice,
														@GoodsNumber,
														@ProduceDate,
														@ValidDate,
														@GoodsBTypeID,
														@GoodsCostPrice,
														@HandZeroCost,
														@intID,
														@intCargoID,
														@numNPrice,
														@numNTotal,
														@numNSalePrice,
														@numNSaleTotal,
														@numNTaxPrice,
														@numNTaxTotal,
														@intItemID,
														@intIsCombined,
														@numNQty,
														@numUnitRate,
														@intMUnitID,
														@chvKTypeID,
														@strComment,
														@numMUnitRate
			END
			CLOSE CreateMx_CURSOR
			DEALLOCATE CreateMx_CURSOR

			RETURN 0
		END
	END
END
------------------------------ 拆装单
IF @numBillType = 16
BEGIN
	DECLARE @InOutFlag CHAR(1)

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	
			a.PTypeID,
			a.Qty,
			a.CostPrice,
			a.Total,
			a.JobNumber,
			a.OutFactoryDate,
			a.InOrOut,
			CASE InOrOut WHEN 'I' THEN a.CostPrice ELSE CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END END AS InputCostPrice,
			a.GoodsNumber,
			a.ProduceDate,
			a.ValidDate,
			a.GoodsBTypeID,
			CASE InOrOut WHEN 'I' THEN a.CostPrice ELSE CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END END,
			a.HandZeroCost,
			a.[ID],
			a.KTypeID,
			a.CargoID,
			0 AS NDiscountPrice,
			0 AS NTotal,
			0 AS NSalePrice,
			0 AS NSaleTotal,
			0 AS NTaxPrice,
			0 AS NTaxTotal,
			a.ItemID,
			a.IsCombined,
			a.NQty,
			a.UnitRate,
			a.MUnitID,
			a.Comment,
			a.MUnitRate
	FROM	DisassembleBill a
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@InOutFlag,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@chvKTypeID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
											

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF UPPER(@InOutFlag) = 'O'
		BEGIN
			-- 循环写入 InOustStockTable
			SELECT 
				@numQtyTemp = -@numQty,
				@numNQtyTemp= -@numNQty
				
			SET @numPriceTemp = ROUND(ABS(@numTotal/@numQty),@intPriceDot)
			SET @numTotalTemp = -@numTotal
			SET @numCostPriceTemp = @numInputCostPrice
			SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
			IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
				SET @HandZeroCost = 1
	
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
				@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
				@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END
		ELSE
		BEGIN
			-- 循环写入 InOustStockTable
			SET @numQtyTemp = @numQty
			--SET @numPriceTemp = ABS(@numTotal/@numQty)
			SET @numPriceTemp=@numPrice
			SET @numTotalTemp = @numTotal
			--SET @numCostPriceTemp = ABS(@numTotal/@numQty)
			SET @numCostPriceTemp=@GoodsCostPrice
			SET @numCostTotalTemp = @numTotal
	
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
				@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
				@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@InOutFlag,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@chvKTypeID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
												
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ 委托代销发货
IF @numBillType = 140
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				[ID],
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				Comment,
				MUnitRate
		FROM	CommissionBill
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 清空无效数据行
		DELETE FROM CommissionStock
		WHERE	Type = 140
				AND Qty = 0
				AND Total = 0
				AND CostTotal = 0
				AND PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID

		-- 循环写入 InOustStockTable
		SET @numQtyTemp = ROUND(-@numQty,@intQtyDot)
		SET @numPriceTemp = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp = ROUND(-@numTotal,@intMoneyDot)
		SET @numCostPriceTemp = ROUND(@numInputCostPrice,@intPriceDot)
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SET @numQtyTemp1 = ROUND(@numQty,@intQtyDot)
		SET @numPriceTemp1 = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp1 = ROUND(@numTotal,@intMoneyDot)
		SET @numCostPriceTemp1 = 0
		SET @numCostTotalTemp1 = 0

		SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		
		
		SELECT
			@numNTotalTemp=ROUND(-@numNTotal,@intMoneyDot),
			@numNSaleTotalTemp=ROUND(-@numNSaleTotal,@intMoneyDot),
			@numNTaxTotalTemp=ROUND(-@numNTaxTotal,@intMoneyDot),
			@numNQtyTemp=-@numNQty
		
		-- 写账面库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotalTemp,@numNSalePrice,@numNSaleTotalTemp,@numNTaxPrice,@numNTaxTotalTemp,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		-- 写代销库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp1,@numPriceTemp1,@numTotalTemp1,@numCostPriceTemp1,@numCostTotalTemp1,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			0,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
												
	END

	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	-- ********* 处理生成 ListTable 凭证记录 *********

	-- 库存商品总值
	EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvBTypeID,@chvETypeID,
		0,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,0,1
	IF @intReturnCode <> 0 GOTO ERROR1
	
	-- 委托代销商品款
	EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@WTDXGOODS_ID,@chvBTypeID,@chvETypeID,
		0,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,0,1
	IF @intReturnCode <> 0 GOTO ERROR1
	
	RETURN 0
END
------------------------------ 委托代销结算
IF @numBillType = 141
BEGIN
	DECLARE @DXAllCostTotal  NUMERIC(24, 10) 
	SET @DXAllCostTotal = 0

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				Comment,
				MUnitRate
		FROM	CommissionBill
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 清空无效数据行

		DELETE FROM CommissionStock
		WHERE	Type = 140
				AND Qty = 0
				AND Total = 0
				AND CostTotal = 0
				AND PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID

		-- 循环写入 InOustStockTable
		SET @numQtyTemp1 = ROUND(-@numQty,@intQtyDot)
		SET @numPriceTemp1 = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp1 = ROUND(-@numTotal,@intMoneyDot)

		SELECT	@numCostPriceTemp1 = ROUND(CASE WHEN Qty = 0 THEN 0 ELSE CAST(CostTotal/Qty AS  NUMERIC(24, 10) ) END,@intPriceDot)
		FROM	CommissionStock
		WHERE	PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID
				AND Type = 140
				AND Qty<>0

		SET @numCostTotalTemp1 = ROUND(-CAST(@numQty * @numCostPriceTemp1 AS  NUMERIC(24, 10) ),@intMoneyDot)

		
		/*
		IF @nCostingMethod=@HAND
		BEGIN
			SET @numCostPriceTemp1=@numInputCostPrice
		END
		ELSE
		BEGIN
			SET @numCostPriceTemp1 = -CAST(@numCostTotalTemp1/@numQty AS  NUMERIC(24, 10) )
		END
		*/
		SET @numCostPriceTemp1 = ROUND(-CAST(@numCostTotalTemp1/@numQty AS  NUMERIC(24, 10) ),@intPriceDot)
		
		SET @DXAllCostTotal = ROUND(@DXAllCostTotal,@intMoneyDot) + ROUND((-@numCostTotalTemp1),@intMoneyDot)

		SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		
		SELECT
			@numNTotal=ROUND(-@numNTotal,@intMoneyDot),
			@numNSaleTotal=ROUND(-@numNSaleTotal,@intMoneyDot),
			@numNTaxTotal=ROUND(-@numNTaxTotal,@intMoneyDot),
			@numNQty=-@numNQty
		
		-- 写代销库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp1,@numPriceTemp1,@numTotalTemp1,@numCostPriceTemp1,@numCostTotalTemp1,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			0,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
												
	END

	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	SELECT	@numNoTaxTotal = ROUND(ISNULL(SUM(Total),0),@intMoneyDot),@numNNoTaxTotal = ROUND(ISNULL(SUM(NTotal),0),@intMoneyDot)
	FROM	CommissionBill
	WHERE	BillNumberID = @intBillNumberID


	-- 销售收入
	IF @numNoTaxTotal <> 0 OR @numNNoTaxTotal<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@SALE_INCOME_ID,@chvBTypeID,@chvETypeID,
			@numNoTaxTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNNoTaxTotal,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @SALE_INCOME_ID,@chvSTypeID,@intCID,@numNoTaxTotal,@numNNoTaxTotal,''
	END


	-- 销售成本
	IF @DXAllCostTotal <> 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@SALE_COST_ID,@chvBTypeID,@chvETypeID,
			@DXAllCostTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,@DXAllCostTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @SALE_COST_ID,@chvSTypeID,@SysCid,@DXAllCostTotal,@DXAllCostTotal,''
	END

	SET @DXAllCostTotal = -@DXAllCostTotal
	
	-- 委托代销商品款
	IF @DXAllCostTotal <> 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@WTDXGOODS_ID,@chvBTypeID,@chvETypeID,
			@DXAllCostTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,@DXAllCostTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @WTDXGOODS_ID,@chvSTypeID,@SysCid,@DXAllCostTotal,@DXAllCostTotal,''
	END

	-- 应交税金
	IF ((@numTotalMoney - ABS(@numNoTaxTotal) <> 0) OR (@nTotalMoney - ABS(@numNNoTaxTotal)<>0))
	BEGIN
		SET @numTaxBanlance = ROUND(@numTotalMoney,@intMoneyDot) - ROUND(ABS(@numNoTaxTotal),@intMoneyDot)
		SET @numNTaxBanlance = ROUND(@nTotalMoney,@intMoneyDot) - ROUND(ABS(@numNNoTaxTotal),@intMoneyDot)
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@PAY_TAXMONEY_ID,@chvBTypeID,@chvETypeID,
			@numTaxBanlance,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numNTaxBanlance,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @WTDXGOODS_ID,@chvSTypeID,@intCID,@numTaxBanlance,@numNTaxBanlance,''
	END

	RETURN 0
END
------------------------------ 委托代销退货
IF @numBillType = 142
BEGIN
	DECLARE @numWTDXCostPrice  NUMERIC(24, 10) 
	SET @DXAllCostTotal = 0

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				[ID],
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				Comment,
				MUnitRate
		FROM	CommissionBill
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 清空无效数据行
		DELETE FROM CommissionStock
		WHERE	Type = 140
				AND Qty = 0
				AND Total = 0
				AND CostTotal = 0
				AND PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID

		IF EXISTS (
			SELECT	Qty
			FROM	CommissionStock
			WHERE	PTypeID = @chvPTypeID
					AND BTypeID = @chvBTypeID
					AND STypeID=@chvSTypeID
					AND Type =	140
					AND Qty <> 0 )
		BEGIN
			SELECT	@numWTDXCostPrice = ROUND(CASE QTY WHEN 0 THEN 0 ELSE CONVERT( NUMERIC(24, 10) ,CostTotal/Qty) END,@intPriceDot)
			FROM	CommissionStock
			WHERE	PTypeID = @chvPTypeID
					AND BTypeID = @chvBTypeID
					AND STypeID=@chvSTypeID
					AND Type =	140
		
		END
		ELSE SET @numWTDXCostPrice = 0

		SET @DXAllCostTotal = ROUND(@DXAllCostTotal,@intMoneyDot) + ROUND(CONVERT( NUMERIC(24, 10) ,@numWTDXCostPrice * @numQty),@intMoneyDot)

		-- 循环写入 InOustStockTable
		SET @numQtyTemp = ROUND(@numQty,@intQtyDot)
		SET @numPriceTemp = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp = ROUND(@numTotal,@intMoneyDot)
		
		
		/*
		IF @nCostingMethod=@HAND
		BEGIN
			SET @numCostPriceTemp=@numInputCostPrice
		END
		ELSE
		BEGIN
			SET @numCostPriceTemp = @numWTDXCostPrice
		END
		*/
		
		SET @numCostPriceTemp = ROUND(@numWTDXCostPrice,@intPriceDot)
		
		SET @numCostTotalTemp = ROUND(CONVERT( NUMERIC(24, 10) ,@numWTDXCostPrice * @numQty),@intMoneyDot)

		SET @numQtyTemp1 = ROUND(-@numQty,@intQtyDot)
		SET @numPriceTemp1 = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp1 = ROUND(-@numTotal,@intMoneyDot)

			IF @nCostingMethod=@Hand
		BEGIN
			SET @numCostPriceTemp1 = @numCostPriceTemp
			SET @numCostTotalTemp1 = 0
		END
		ELSE
		BEGIN
			SET @numCostPriceTemp1 = 0
			SET @numCostTotalTemp1 = 0
		END

		-- 写账面库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		
		SELECT 
			@numNTotalTemp=ROUND(-@numNTotal,@intMoneyDot),
			@numNSaleTotalTemp=ROUND(-@numNSaleTotal,@intMoneyDot),
			@numNTaxTotalTemp=ROUND(-@numNTaxTotal,@intMoneyDot),
			@numNQtyTemp=-@numNQty

		-- 写代销库存
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp1,@numPriceTemp1,@numTotalTemp1,@numCostPriceTemp1,@numCostTotalTemp1,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			0,@numNPrice,@numNTotalTemp,@numNSalePrice,@numNSaleTotalTemp,@numNTaxPrice,@numNTaxTotalTemp,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
												
	END

	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- ********* 处理生成 ListTable 凭证记录 *********

	IF @DXAllCostTotal <> 0
	BEGIN
		-- 库存商品总值
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvBTypeID,@chvETypeID,
			@DXAllCostTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,@DXAllCostTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
	--	EXEC GP_AType_Total_AddEdit @GOODS_ID,@chvSTypeID,@SysCid,@DXAllCostTotal,@DXAllCostTotal,''
		SET @DXAllCostTotal = -@DXAllCostTotal
		
		--委托代销商品款
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@WTDXGOODS_ID,@chvBTypeID,@chvETypeID,
			@DXAllCostTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,@DXAllCostTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @WTDXGOODS_ID,@chvSTypeID,@SysCid,@DXAllCostTotal,@DXAllCostTotal,''
	END

	RETURN 0
END
------------------------------ 委托代销调价



IF @numBillType = 143
BEGIN
	DECLARE	@numWTDXPrice		 NUMERIC(24, 10) ,
			@numWTDXTotal		 NUMERIC(24, 10) ,
			@numWTDXQty			 NUMERIC(24, 10) 

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				[ID],
				KTypeID,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				GoodsNumber,
				Comment,
				MUnitRate
		FROM	CommissionBill
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@intID,
											@chvKTypeID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@GoodsNumber,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 清空无效数据行
		DELETE FROM CommissionStock
		WHERE	Type = 140
				AND Qty = 0
				AND Total = 0
				AND CostTotal = 0
				AND PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND STypeID=@chvSTypeID

		-- 读取委托代销库的库存成本价 CostTotal
		IF EXISTS (
			SELECT Qty FROM	CommissionStock
			WHERE	Type = 140
					AND Qty <> 0
					AND BTypeID = @chvBTypeID
					AND PTypeID = @chvPTypeID
					AND STypeID=@chvSTypeID
		)
		BEGIN
			SELECT	@numWTDXCostPrice = ROUND(CASE QTY WHEN 0 THEN 0 ELSE CAST(CostTotal/Qty AS  NUMERIC(24, 10) ) END,@intPriceDot),
					@numWTDXPrice = ROUND(CASE QTY WHEN 0 THEN 0 ELSE CAST(Total/Qty AS  NUMERIC(24, 10) ) END,@intPriceDot),
					@numWTDXTotal =ROUND(Total,@intMoneyDot),
					@numWTDXQty = ROUND(Qty,@intQtyDot)
			FROM	CommissionStock
			WHERE	Type = 140
					AND BTypeID = @chvBTypeID
					AND PTypeID = @chvPTypeID
					AND STypeID=@chvSTypeID
					AND Qty<>0
		END
		ELSE
		BEGIN
			SET @numWTDXCostPrice = 0
			SET @numWTDXPrice = 0
			SET @numWTDXTotal = 0
		END

		-- 循环写入 InOustStockTable
		SET @numQtyTemp = ROUND(-@numQty,@intQtyDot)
		
		SET @numPriceTemp = ROUND(@numWTDXPrice,@intPriceDot)
		
		IF @numWTDXQty = @numQty
			SET @numTotalTemp = ROUND(-@numWTDXTotal,@intMoneyDot)
		ELSE
			SET @numTotalTemp = ROUND(-CAST(@numWTDXPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		
		/*
		IF @nCostingMethod=@HAND
		BEGIN
			SET @numCostPriceTemp=@numInputCostPrice
		END
		ELSE
		BEGIN	
			SET @numCostPriceTemp = @numWTDXCostPrice
		END
		*/
		SET @numCostPriceTemp = ROUND(@numWTDXCostPrice,@intPriceDot)
		
		SET @numCostTotalTemp = ROUND(-CAST(@numWTDXCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)

		SET @numQtyTemp1 = ROUND(@numQty,@intQtyDot)
		SET @numPriceTemp1 = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp1 = ROUND(@numTotal,@intMoneyDot)
		SET @numCostPriceTemp1 = ROUND(@numWTDXCostPrice,@intPriceDot)
		SET @numCostTotalTemp1 = ROUND(CAST(@numWTDXCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		
		
		
		SELECT @strOPRate=BasisType,@decRate=Rate
		FROM Ac_Currency				
		WHERE CId=@intCID
		
		
		IF @decRate<>1
		BEGIN
			IF @strOPRate='0'
			BEGIN
				SET @numNTotalTemp=ROUND((CAST(@numTotalTemp AS  NUMERIC(24, 10) ))/(CAST(@decRate AS  NUMERIC(24, 10) )),@intMoneyDot)
			END
			ELSE
			BEGIN
				SET @numNTotalTemp=ROUND((CAST(@numTotalTemp AS  NUMERIC(24, 10) ))*(CAST(@decRate AS  NUMERIC(24, 10) )),@intMoneyDot)
			END
		END
		ELSE
		BEGIN
			SET @numNTotalTemp=ROUND(@numTotalTemp,@intMoneyDot)
		END
		
		SELECT 
			@numNQtyTemp=ROUND(-@numNQty,@intQtyDot)
			
		IF @decRate<>1
		BEGIN
			IF @numQtyTemp<>0
			BEGIN
				SET @numNPriceTemp=ROUND(CAST(@numNTotalTemp AS  NUMERIC(24, 10) )/CAST(@numQtyTemp AS  NUMERIC(24, 10) ),@intPriceDot)
			END
			ELSE
			BEGIN
				IF @strOPRate='0'
				BEGIN
					SET @numNPriceTemp=ROUND((CAST(@numPriceTemp AS  NUMERIC(24, 10) ))/(CAST(@decRate AS  NUMERIC(24, 10) )),@intMoneyDot)
				END
				ELSE
				BEGIN
					SET @numNPriceTemp=ROUND((CAST(@numPriceTemp AS  NUMERIC(24, 10) ))*(CAST(@decRate AS  NUMERIC(24, 10) )),@intMoneyDot)
				END
			END
		END
		ELSE
		BEGIN
			SET @numNPriceTemp=ROUND(@numPriceTemp,@intPriceDot)
		END

		-- 写代销库存 -- 出库
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,
			0,1,@numPriceTemp,@numTotalTemp,@numPriceTemp,@numTotalTemp,@chvDTypeID,@chvSTypeID,
			0,@numNPriceTemp,@numNTotalTemp,@numNPriceTemp,@numNTotalTemp,@numNPriceTemp,@numNTotalTemp,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		-- 写代销库存 -- 入库
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,'10000',
			@numQtyTemp1,@numPriceTemp1,@numTotalTemp1,@numCostPriceTemp1,@numCostTotalTemp1,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,
			0,1,@numPriceTemp1,@numTotalTemp1,@numPriceTemp1,@numTotalTemp1,@chvDTypeID,@chvSTypeID,
			0,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
			@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@intID,
												@chvKTypeID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@GoodsNumber,
												@strComment,
												@numMUnitRate
												
	END

	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ (新维修) - 接件单
IF @numBillType = 165
BEGIN		
	SELECT
		@numNPrice=0,
		@numNTotal=0,
		@numNSalePrice=0,
		@numNSaleTotal=0,
		@numNTaxPrice=0,
		@numNTaxTotal=0



	SET @numQtyTemp = 1
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT a.PTypeID,a.OutFactoryDate,a.[ID],a.CargoID,a.ItemID,a.IsCombined,a.NQty,a.UnitRate,b.BaseUnitID AS UnitID,a.GoodsNumber,a.Comment,1 AS MUnitRate
		FROM wx_Bill_JieJian a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber
	,@strComment,@numMUnitRate
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,
			@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1
		FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
		@GoodsNumber,@strComment,@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	RETURN 0
END
------------------------------ (新维修) - 维修单
IF @numBillType = 166
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	
				a.PTypeID,
				a.InOrOut,
				a.Qty,
				a.Price,
				a.Total,
				a.wxProperty,
				a.OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate,
				a.GoodsBTypeID,
				a.GoodsCostPrice,
				a.HandZeroCost,
				a.[ID],
				a.CargoID,
				a.Price AS NDiscountPrice,
				a.Total AS NTotal,
				a.Price AS NSalePrice,
				a.Total AS NSaleTotal,
				a.Price AS NTaxPrice,
				a.Total AS NTaxTotal,
				a.ItemID,
				a.IsCombined,
				a.NQty,
				a.UnitRate,
				b.BaseUnitID AS UnitID,
				b.IsService,
				a.Comment,
				1 AS MUnitRate
		FROM wx_Bill_Self  a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@chrInOrOut,
											@numQty,
											@numPrice,
											@numTotal,
											@wxProperty,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsService,
											@strComment,
											@numMUnitRate

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF UPPER(@chrInOrOut)='O'	-- 出库
		BEGIN
			IF @wxProperty = 0 SET @ifDetailWX = 0 ELSE SET @ifDetailWX = 1
			SET @numQtyTemp = -@numQty
			SET @numPriceTemp = @numPrice
			SET @numTotalTemp = -@numTotal
			
			SELECT 
				@numNTotal=-@numNTotal,
				@numNSaleTotal=-@numNSaleTotal,
				@numNTaxTotal=-@numNTaxTotal,
				@numNQtyTemp=-@numNQty						
			
			IF @ifDetailWX = 0
			BEGIN
				SET @numCostPriceTemp = @numInputCostPrice
				SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
				IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
					SET @HandZeroCost = 1

				-- 循环写入 InOustStockTable
				EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,'',@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
					0,1,@numPriceTemp,@numTotalTemp,@numPriceTemp,@numTotalTemp,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,
					@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
				IF @intReturnCode <> 0 GOTO ERROR1
			END
			ELSE
			BEGIN
				-- 循环写入 wx_InOustStockTable
				EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
					@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
				IF @intReturnCode <> 0 GOTO ERROR1
			END
		END
		ELSE	-- 入库
		BEGIN
			SET @numQtyTemp = @numQty

			-- 循环写入 InOustStockTable
			EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID2,
				@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
				@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
			IF @intReturnCode <> 0 GOTO ERROR1
		END

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@chrInOrOut,
												@numQty,
												@numPrice,
												@numTotal,
												@wxProperty,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsService,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ (新维修) - 维修取件单
IF @numBillType = 167
BEGIN
	SELECT
		@numNPrice=0,
		@numNTotal=0,
		@numNSalePrice=0,
		@numNSaleTotal=0,
		@numNTaxPrice=0,
		@numNTaxTotal=0

	SELECT 
		@numQtyTemp = -1
		
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT a.PTypeID,a.OutFactoryDate,a.[ID],a.CargoID,a.ItemID,a.IsCombined,-a.NQty,a.UnitRate,b.BaseUnitID AS UnitID,a.GoodsNumber  ,a.Comment,1 AS MUnitRate
		
		FROM wx_Bill_GetBack  a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber,@strComment,@numMUnitRate 
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1
		FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber,@strComment,@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- 贷：维修收入
	IF @numTotalMoney <> 0 OR @nTotalMoney<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@REPAIR_INCOME_ID,@chvBTypeID,@chvETypeID,
			@numTotalMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@nTotalMoney,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @REPAIR_INCOME_ID,@chvSTypeID,@intCID,@numTotalMoney,@nTotalMoney,''
	END
	

	RETURN 0
END
------------------------------ (新维修) - 整机更换单
IF @numBillType = 168
BEGIN
	SET @numQty = 1
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	
				a.PTypeID,
				a.Total,
				a.wxProperty,
				a.OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate,
				a.GoodsBTypeID,
				a.GoodsCostPrice,
				a.HandZeroCost,
				a.[ID],
				a.CargoID,
				a.Total AS NDiscountPrice,
				a.Total AS NTotal,
				a.Total AS NSalePrice,
				a.Total AS NSaleTotal,
				a.Total AS NTaxPrice,
				a.Total AS NTaxTotal,
				a.ItemID,
				a.IsCombined,
				a.NQty,
				a.UnitRate,
				b.BaseUnitID AS UnitID,
				a.Comment,
				1 AS MUnitRate
		FROM wx_Bill_Replace  a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numTotal,
											@wxProperty,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
								
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @numQtyTemp = -@numQty
		IF @wxProperty = 0 SET @ifDetailWX = 0 ELSE SET @ifDetailWX = 1
		
		SELECT 
			@numNTotal=-@numNTotal,
			@numNSaleTotal=-@numNSaleTotal,
			@numNTaxTotal=-@numNTaxTotal,
			@numNQty=-@numNQty				
			

		IF @ifDetailWX = 0
		BEGIN
			SET @numPriceTemp = @numTotal
			SET @numTotalTemp = -@numTotal
			SET @numCostPriceTemp = @numInputCostPrice
			SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
			IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
				SET @HandZeroCost = 1

			-- 循环写入 InOustStockTable
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,'',@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
				0,1,@numPriceTemp,@numTotalTemp,@numPriceTemp,@numTotalTemp,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,
				@strComment,@datPostTime,@numMUnitRate
			
			
			IF @intReturnCode <> 0 GOTO ERROR1
		END
		ELSE
		BEGIN
			-- 循环写入 wx_InOustStockTable
			SELECT
				@numNPrice=0,
				@numNTotal=0,
				@numNSalePrice=0,
				@numNSaleTotal=0,
				@numNTaxPrice=0,
				@numNTaxTotal=0
			
			EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,
				@strComment,@datPostTime,@numMUnitRate
			
			
			IF @intReturnCode <> 0 GOTO ERROR1
		END

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numTotal,
												@wxProperty,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	-- 贷：维修收入
	IF @numTotalMoney <> 0 OR @NtotalMoney<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@REPAIR_INCOME_ID,@chvBTypeID,@chvETypeID,
			@numTotalMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@NtotalMoney,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @REPAIR_INCOME_ID,@chvSTypeID,@intCID,@numTotalMoney,@nTotalMoney,''
	END

	RETURN 0
END
------------------------------ (新维修) - 送修单
IF @numBillType = 169
BEGIN
				
	SELECT
		@numNPrice=0,
		@numNTotal=0,
		@numNSalePrice=0,
		@numNSaleTotal=0,
		@numNTaxPrice=0,
		@numNTaxTotal=0

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT a.PTypeID,a.Qty,a.OutFactoryDate,a.[ID],a.CargoID,a.ItemID,a.IsCombined,a.NQty,a.UnitRate,b.BaseUnitID AS UnitID,a.GoodsNumber,a.Comment,1 AS MUnitRate
		FROM wx_Bill_Send  a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@numQty,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber,@strComment,@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT 
			@numQtyTemp = -@numQty,
			@numNQty=-@numNQty
			
		-- 循环写入 wx_InOustStockTable
		EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@strComment,@datPostTime,@numMUnitRate
			

		FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@numQty,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber ,@strComment,@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ (新维修) - 送修返回单
IF @numBillType = 170
BEGIN
	SELECT
		@numNPrice=0,
		@numNTotal=0,
		@numNSalePrice=0,
		@numNSaleTotal=0,
		@numNTaxPrice=0,
		@numNTaxTotal=0	

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT a.PTypeID,a.Qty,a.OutFactoryDate,a.[ID],a.CargoID,a.ItemID,a.IsCombined,a.NQty,a.UnitRate,b.BaseUnitID AS UnitID,a.GoodsNumber,a.Comment,1 AS MUnitRate
		FROM wx_Bill_SendBack  a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@numQty,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber,@strComment,@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @numQtyTemp = @numQty

		-- 循环写入 wx_InOustStockTable
		EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@strComment,@datPostTime,@numMUnitRate
			

		FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@numQty,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber ,@strComment,@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
	-- 借：商品送修支出
	IF @numTotalMoney <> 0 OR @NtotalMoney<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@REPAIR_PAYOUT,@chvBTypeID,@chvETypeID,
			@numTotalMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@NtotalMoney,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @REPAIR_PAYOUT,@chvSTypeID,@intCID,@numTotalMoney,@nTotalMoney,''
	END
	RETURN 0
END
------------------------------ (新维修) - 上门维修单
IF @numBillType = 172
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	
				a.PTypeID,
				a.InOrOut,
				a.Qty,
				a.Price,
				a.Total,
				a.wxProperty,
				a.OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate,
				a.GoodsBTypeID,
				a.GoodsCostPrice,
				a.HandZeroCost,
				a.[ID],
				a.CargoID,
				a.Price AS NDiscountPrice,
				a.Total AS NTotal,
				a.Price AS NSalePrice,
				a.Total AS NSaleTotal,
				a.Price AS NTaxPrice,
				a.Total AS NTaxTotal,
				a.ItemID,
				a.IsCombined,
				a.NQty,
				a.UnitRate,
				b.BaseUnitID AS UnitID,
				a.Comment,
				1 AS MUnitRate
		FROM wx_Bill_Goto  a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@chrInOrOut,
											@numQty,
											@numPrice,
											@numTotal,
											@wxProperty,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF UPPER(@chrInOrOut)='O'	-- 出库
		BEGIN
			IF @wxProperty = 0 SET @ifDetailWX = 0 ELSE SET @ifDetailWX = 1
			SET @numQtyTemp = -@numQty
			SET @numPriceTemp = @numPrice
			SET @numTotalTemp = -@numTotal
			
			SELECT 
				@numNTotal=-@numNTotal,
				@numNSaleTotal=-@numNSaleTotal,
				@numNTaxTotal=-@numNTaxTotal,
				@numNQtyTemp=-@numNQty

			IF @ifDetailWX = 0
			BEGIN
				SET @numCostPriceTemp = @numInputCostPrice
				SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
				IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
					SET @HandZeroCost = 1

				-- 循环写入 InOustStockTable
				EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,'',@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
					0,1,@numPriceTemp,@numTotalTemp,@numPriceTemp,@numTotalTemp,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,
					@strComment,@datPostTime,@numMUnitRate
			
			
				IF @intReturnCode <> 0 GOTO ERROR1
			END
			ELSE
			BEGIN
				-- 循环写入 wx_InOustStockTable
				EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
					@numQtyTemp,@numPriceTemp,@numTotalTemp,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
					@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,
					@strComment,@datPostTime,@numMUnitRate
			
			
				IF @intReturnCode <> 0 GOTO ERROR1
			END
		END
		ELSE	-- 入库
		BEGIN
			SET @numQtyTemp = @numQty
			
			SELECT
				@numNPrice=0,
				@numNTotal=0,
				@numNSalePrice=0,
				@numNSaleTotal=0,
				@numNTaxPrice=0,
				@numNTaxTotal=0

			-- 循环写入 wx_InOustStockTable
			EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID2,
				@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,
				@strComment,@datPostTime,@numMUnitRate
			IF @intReturnCode <> 0 GOTO ERROR1
		END

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@chrInOrOut,
												@numQty,
												@numPrice,
												@numTotal,
												@wxProperty,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	-- 贷：维修收入
	IF @numTotalMoney <> 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@REPAIR_INCOME_ID,@chvBTypeID,@chvETypeID,
			@numTotalMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@NtotalMoney,@decRate
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @REPAIR_PAYOUT,@chvSTypeID,@intCID,@numTotalMoney,@nTotalMoney,''
	END
	
	RETURN 0
END
------------------------------ (新维修) - 维修品调入单
IF @numBillType = 173
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	
				a.PTypeID,
				a.Qty,
				a.Price,
				a.Total,
				a.OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate,
				a.GoodsBTypeID,
				a.GoodsCostPrice,
				a.HandZeroCost,
				a.[ID],
				a.CargoID,
				a.Price AS NDiscountPrice,
				a.Total AS NTotal,
				a.Price AS NSalePrice,
				a.Total AS NSaleTotal,
				a.Price AS NTaxPrice,
				a.Total AS NTaxTotal,
				a.ItemID,
				a.IsCombined,
				a.NQty,
				a.UnitRate,
				b.BaseUnitID AS UnitID,
				a.Comment,
				1 AS MUnitRate
		FROM wx_Bill_In  a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @numQtyTemp = -@numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = -@numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1
			
		SELECT 
			@numNQtyTemp=-@numNQty,
			@numNTotalTemp=-@numNTotal,
			@numNSaleTotalTemp=-@numNSaleTotal,
			@numNTaxTotalTemp=-@numNTaxTotal
			
			
		-- 循环写入 InOustStockTable
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,'',@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			0,1,@numPriceTemp,@numTotalTemp,@numPriceTemp,@numTotalTemp,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotalTemp,@numNSalePrice,@numNSaleTotalTemp,@numNTaxPrice,@numNTaxTotalTemp,
			@intItemID,@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		SET @numQtyTemp = @numQty
		-- 循环写入 wx_InOustStockTable
		
		SELECT
			@numNPrice=0,
			@numNTotal=0,
			@numNSalePrice=0,
			@numNSaleTotal=0,
			@numNTaxPrice=0,
			@numNTaxTotal=0
			
		EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID2,
			@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ (新维修) - 维修品调出单
IF @numBillType = 174
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	
				a.PTypeID,
				a.Qty,
				a.Price,
				a.Total,
				a.OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate,
				a.GoodsBTypeID,
				a.GoodsCostPrice,
				a.HandZeroCost,
				a.[ID],
				a.CargoID,
				a.Price AS NDiscountPrice,
				a.Total AS NTotal,
				a.Price AS NSalePrice,
				a.Total AS NSaleTotal,
				a.Price AS NTaxPrice,
				a.Total AS NTaxTotal,
				a.ItemID,
				a.IsCombined,
				a.NQty,
				a.UnitRate,
				b.BaseUnitID AS UnitID,
				a.Comment,
				1 AS MUnitRate
		FROM wx_Bill_Out  a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @numQtyTemp = -@numQty
		
		SELECT 
			@numNQtyTemp=-@numNQty	
		
		-- 出库 - 循环写入 wx_InOustStockTable
		EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQtyTemp,@numUnitRate,@intMUnitID,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numPrice
		SET @numCostTotalTemp = @numTotal
		-- 入库 - 循环写入 InOustStockTable
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID2,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,'',@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,0,@HandZeroCost,@intID,
			0,1,@numPriceTemp,@numTotalTemp,@numPriceTemp,@numTotalTemp,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END
------------------------------ (新维修) - 维修品调拨单
IF @numBillType = 175
BEGIN
				
	SELECT
		@numNPrice=0,
		@numNTotal=0,
		@numNSalePrice=0,
		@numNSaleTotal=0,
		@numNTaxPrice=0,
		@numNTaxTotal=0

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT a.PTypeID,a.Qty,a.OutFactoryDate,a.[ID],a.CargoID,a.ItemID,a.IsCombined,a.NQty,a.UnitRate,b.BaseUnitID AS UnitID,a.GoodsNumber ,a.Comment,1 AS MUnitRate
		FROM wx_Bill_Move   a
		INNER JOIN PType b
		ON a.PTypeID=b.TypeID
		WHERE BillNumberID = @intBillNumberID
	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@numQty,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber,@strComment,@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT 
			@numQtyTemp = -@numQty,
			@numNQty=-@numNQty	
			
		-- 出库 - 循环写入 wx_InOustStockTable
		EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		SELECT 
			@numQtyTemp = @numQty,
			@numNQty=-@numNQty
			
		-- 入库 - 循环写入 wx_InOustStockTable
		EXEC @intReturnCode = GP_CreateMX_InsertInOut_wx @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID2,
			@numQtyTemp,0,0,0,0,'',@datOutFactoryDate,@GoodsNumber,'','','',0,0,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1
		FETCH NEXT FROM CreateMx_CURSOR INTO @chvPTypeID,@numQty,@datOutFactoryDate,@intID,@intCargoID,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@GoodsNumber,@strComment,@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	RETURN 0
END



--------------------------(汽配)--积分兑换单
IF @numBillType=183
BEGIN

				
	SELECT
		@numNPrice=0,
		@numNTotal=0,
		@numNSalePrice=0,
		@numNSaleTotal=0,
		@numNTaxPrice=0,
		@numNTaxTotal=0
	

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	
			a.PTypeID,
			a.Qty,
			'',
			'',
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			a.GoodsNumber,
			a.ProduceDate,
			a.ValidDate,
			'',
			a.GoodsCostPrice,
			a.HandZeroCost,
			a.[ID],
			a.KTypeID,
			a.CargoID,
			a.ItemID,
			a.IsCombined,
			a.NQty,
			a.UnitRate,
			b.BaseUnitID AS UnitID,
			b.IsService,
			a.Comment,
			1 AS MUnitRate
	FROM	IntegralExchangeBill  a
	INNER JOIN PType b
	ON a.PTypeID=b.TypeID
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@chvKTypeID,
											@intCargoID,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsService,
											@strComment,
											@numMUnitRate 
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SELECT
			@numQtyTemp = -@numQty,
			@numNQty=-@numNQty	
			
		SET @numPriceTemp = 0
		SET @numTotalTemp = 0
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
			@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,0,0,0,0,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@chvKTypeID,
												@intCargoID,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsService,
												@strComment,
												@numMUnitRate 
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR



	RETURN 0


END


IF @numBillType=187
BEGIN
	--出
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	
			PTypeID,
			Qty,
			Price,
			Total,
			JobNumber,
			OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			1 AS Discount,
			Price,
			Total,
			Price,
			Total,
			KTypeID,
			OutCargoID AS CargoID,
			Price AS NDiscountPrice,
			Total AS NTotal,
			Price AS NSalePrice,
			Total AS NSaleTotal,
			Price AS NTaxPrice,
			Total AS NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			UnitID,
			Comment,
			MUnitRate
	FROM	STypeMoveBill a
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = -@numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = -@numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SET @numSaleTotal = -@numSaleTotal
		SET @numTaxTotal = -@numTaxTotal
		
		SELECT 
			@numNTotal=-@numNTotal,
			@numNSaleTotal=-@numNSaleTotal,
			@numNTaxTotal=-@numNTaxTotal,
			@numNQty=-@numNQty					
			
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	
	
	
	

	RETURN 0

END


IF @numBillType=188
BEGIN
	--入
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	
			PTypeID,
			Qty,
			Price,
			Total,
			JobNumber,
			OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			1 AS Discount,
			Price,
			Total,
			Price,
			Total,
			KTypeID2,
			InCargoID AS CargoID,
			Price AS NDiscountPrice,
			Total AS NTotal,
			Price AS NSalePrice,
			Total AS NSaleTotal,
			Price AS NTaxPrice,
			Total AS NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			UnitID,
			Comment,
			MUnitRate
	FROM	STypeMoveBill
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numPrice
		SET @numCostTotalTemp = @numTotal--CAST(@numPrice * @numQty AS  NUMERIC(24, 10) )
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SET @numSaleTotal = @numSaleTotal
		SET @numTaxTotal = @numTaxTotal
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,0,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	
	

	RETURN 0
END




DECLARE
	@tempOtherATypeID		VARCHAR(50)

IF @numBillType=201
BEGIN
	--其他入库单
	IF EXISTS(
		SELECT BillNumberId FROM OtherInOutBill
		WHERE BillNumberId=@intBillNumberID
	)
	BEGIN
		DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	
				PTypeID,
				KTypeID,
				Qty,
				JobNumber,
				OutFactoryDate,
				--CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN DBO.F_GetRecPrice(STypeID,PTypeID) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				ISNULL(InputCostPrice,0) AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				Price AS GoodsCostPrice,
				1 AS HandZeroCost,
				[ID],
				Price,
				Total,
				CargoID,
				Price AS NDiscountPrice,
				Total AS NTotal,
				Price AS NSalePrice,
				Total AS NSaleTotal,
				Price AS NTaxPrice,
				Total AS NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				UnitID,
				b.IsService,
				a.Comment,
				a.MUnitRate
		FROM	OtherInOutBill a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID
		

		OPEN CreateMx_CURSOR
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@chvKTypeID,
												@numQty,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numPrice,
												@numTotal,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsService,
												@strComment,
												@numMUnitRate
												
												
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- 循环写入 InOustStockTable
			SET @numQtyTemp = @numQty
			
			SET @numCostPriceTemp = @numPrice
			SET @numCostTotalTemp = @numTotal
			
			
		
			EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
				@numQty,@numPrice,@numTotal,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
				@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
				@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
				@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
			IF @intReturnCode <> 0 GOTO ERROR1
		

			FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
													@chvKTypeID,
													@numQty,
													@chvJobNumber,
													@datOutFactoryDate,
													@numInputCostPrice,
													@GoodsNumber,
													@ProduceDate,
													@ValidDate,
													@GoodsBTypeID,
													@GoodsCostPrice,
													@HandZeroCost,
													@intID,
													@numPrice,
													@numTotal,
													@intCargoID,
													@numNPrice,
													@numNTotal,
													@numNSalePrice,
													@numNSaleTotal,
													@numNTaxPrice,
													@numNTaxTotal,
													@intItemID,
													@intIsCombined,
													@numNQty,
													@numUnitRate,
													@intMUnitID,
													@intIsService,
													@strComment,
													@numMUnitRate
		END
		CLOSE CreateMx_CURSOR
		DEALLOCATE CreateMx_CURSOR
		
		
		


	END
	
	
	
	
	
	RETURN 0
END

IF @numBillType=202
BEGIN
	--其他出库单
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	
			PTypeID,
			KTypeID,
			Qty,
			JobNumber,
			OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			CargoID,
			Price AS NDiscountPrice,
			Total AS NTotal,
			Price AS NSalePrice,
			Total AS NSaleTotal,
			Price AS NTaxPrice,
			Total AS NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			UnitID,
			b.IsService,
			a.Comment,
			a.MUnitRate
	FROM	OtherInOutBill a
	INNER JOIN PType b
	ON a.PtypeId=b.typeId
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@chvKTypeID,
											@numQty,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = -@numQty
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SELECT 
			@numSaleTotal=-@numSaleTotal,
			@numTaxTotal=-@numTaxTotal,
			@numNTotal=-@numNTotal,
			@numNSaleTotal=-@numNSaleTotal,
			@numNTaxTotal=-@numNTaxTotal,
			@numNQty=-@numNQty					
			
	
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPrice,@numTotal,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,
			@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,0,1,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,0,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1
		

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@chvKTypeID,
												@numQty,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsService,
												@strComment,
												@numMUnitRate
		END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
	
	
	RETURN 0
END

IF @numBillType=181
BEGIN
	--会员储值充值单
	
	--会员储值
	EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@VIP_ID,@chvBTypeID,@chvETypeID,
		@numTotalMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numTotalMoney,@decRate
	
	--EXEC GP_AType_Total_AddEdit @VIP_ID,@chvSTypeID,@intCID,@numTotalMoney,@NtotalMoney,''
	RETURN 0
END

IF @numBillType=312
BEGIN
	--会员储值批量充值单
	
	--会员储值
	EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@VIP_ID,@chvBTypeID,@chvETypeID,
		@numTotalMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numTotalMoney,@decRate
	
	--EXEC GP_AType_Total_AddEdit @VIP_ID,@chvSTypeID,@intCID,@numTotalMoney,@NtotalMoney,''
	RETURN 0
END
IF @numBillType=427--会员积分转储值单
BEGIN
	--会员储值
	EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@VIP_ID,@chvBTypeID,@chvETypeID,
		@numTotalMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numTotalMoney,@decRate
		
	--积分转储值
	EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@VIPJF_CZId,@chvBTypeID,@chvETypeID,
		@numTotalMoney,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@intCID,@numTotalMoney,@decRate
		
	RETURN 0
END


IF @numBillType=205
BEGIN
	--采购费用分摊
	SELECT @numTotal=SUM(ShareFee)
	FROM ShareSourceBill
	WHERE BillNumberId=@intBillNumberID

	
	EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvBTypeID,@chvETypeID,
			@numTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@SysCid,@numTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
	--EXEC GP_AType_Total_AddEdit @GOODS_ID,@chvSTypeID,@intCID,@numTotalMoney,@NtotalMoney,''
		
	--处理费用
	DECLARE BuyShareFee_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	b.ATypeID,SUM(b.Total) AS Total
	FROM	ShareFeeBill a
	INNER	JOIN MoneyBill b
	ON a.FromBillID=b.ID
	WHERE	a.BillNumberID = @intBillNumberID
	GROUP BY ATypeID

	OPEN BuyShareFee_CURSOR
	FETCH NEXT FROM BuyShareFee_CURSOR INTO	@chvATypeID,
											@numTotal
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SELECT @numTotal=-@numTotal
	
		EXEC @intReturnCode = GP_CreateMX_InsertList @intBillNumberID,@datBillDate,@numBillType,@chvATypeID,@chvBTypeID,@chvETypeID,
			@numTotal,@chvJobNumber,@datOutFactoryDate,@chvDTypeID,@chvSTypeID,@Syscid,@numTotal,1
		IF @intReturnCode <> 0 GOTO ERROR1
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@chvSTypeID,@Syscid,@numTotal,@numTotal,''
		FETCH NEXT FROM BuyShareFee_CURSOR INTO	@chvATypeID,
											@numTotal
												
	END
	CLOSE BuyShareFee_CURSOR
	DEALLOCATE BuyShareFee_CURSOR

	RETURN 0
	
	
END



------------------------------ 零售退货单
IF @numBillType = 215
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				JobNumber,
				OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate
		FROM	RetailBackBill a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		
			
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,@intIsGift,@intIsService,
			@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1


		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	

	RETURN 0

END


IF @numBillType=400		--暂估入库单
BEGIN

	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				''	AS JobNumber,
				''	AS OutFactoryDate,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				''	AS GoodsBTypeID,
				1 AS HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate
		FROM	AppraisalBill a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		
		
		SET @numCostPriceTemp = @numPrice
		SET @numCostTotalTemp = @numTotal

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,0,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
	
	
	RETURN 0
END


IF @numBillType=401		--暂估退货单
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
			SELECT	PTypeID,
					Qty,
					DiscountPrice,
					Total,
					'' AS JobNumber,
					'' AS OutFactoryDate,
					CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					'' AS GoodsBTypeID,
					GoodsCostPrice,
					HandZeroCost,
					[ID],
					Discount,
					SalePrice,
					SaleTotal,
					TaxPrice,
					TaxTotal,
					KTypeID,
					Tax,
					CargoID,
					NDiscountPrice,
					NTotal,
					NSalePrice,
					NSaleTotal,
					NTaxPrice,
					NTaxTotal,
					ItemID,
					IsCombined,
					NQty,
					UnitRate,
					MUnitID,
					IsGift,
					b.IsService,
					a.Comment,
					a.MUnitRate
			FROM	AppraisalBackBill a
			INNER JOIN PType b
			ON a.PtypeId=b.typeId
			WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = -@numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = -@numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = -@numTotal
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1


		SET @numSaleTotal = -@numSaleTotal
		SET @numTaxTotal = -@numTaxTotal
		
		SELECT
			@numNTotal=-@numNTotal,
			@numNSaleTotal=-@numNSaleTotal,
			@numNTaxTotal=-@numNTaxTotal,
			@numNQty=-@numNQty
			
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,
			@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
												
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	

	RETURN 0
END


IF @numBillType=402		--发出商品出库单
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	PTypeID,
			Qty,
			DiscountPrice,
			Total,
			'' AS JobNumber,
			'' AS OutFactoryDate,
			CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			'' AS GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			[ID],
			Discount,
			SalePrice,
			SaleTotal,
			TaxPrice,
			TaxTotal,
			KTypeID,
			Tax,
			CargoID,
			NDiscountPrice,
			NTotal,
			NSalePrice,
			NSaleTotal,
			NTaxPrice,
			NTaxTotal,
			ItemID,
			IsCombined,
			NQty,
			UnitRate,
			MUnitID,
			IsGift,
			b.IsService,
			a.Comment,
			a.MUnitRate
	FROM	SendBill a
	INNER JOIN PType b
	ON a.PtypeId=b.typeId
	WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = -@numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = -@numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		SET @numSaleTotal = -@numSaleTotal
		SET @numTaxTotal = -@numTaxTotal
		
		SELECT
			@numNTotal=-@numNTotal,
			@numNSaleTotal=-@numNSaleTotal,
			@numNTaxTotal=-@numNTaxTotal,
			@numNQty=-@numNQty
		
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate

		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
												
	END
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
	
	
	
	RETURN 0
END


IF @numBillType=403		--发出商品退货单
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				Qty,
				DiscountPrice,
				Total,
				'' AS JobNumber,
				'' AS OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				'' AS GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				Discount,
				SalePrice,
				SaleTotal,
				TaxPrice,
				TaxTotal,
				KTypeID,
				Tax,
				CargoID,
				NDiscountPrice,
				NTotal,
				NSalePrice,
				NSaleTotal,
				NTaxPrice,
				NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				UnitRate,
				MUnitID,
				IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate	
		FROM	SendBackBill a
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate
			
		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END 
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	

	RETURN 0
END

IF @numBillType =327	--门店配送单（991新单据类型）
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				a.Qty,
				Price,
				a.Total,
				'' AS JobNumber,
				po.BillDate AS OutFactoryDate,
				CASE @nCostingMethod WHEN @Hand THEN CASE WHEN ISNULL(InputCostPrice,0)=0 THEN CASE GoodsCostPrice WHEN -1 THEN ROUND(DBO.F_GetRecPrice(STypeID,PTypeID),@intPriceDot) ELSE GoodsCostPrice END ELSE ISNULL(InputCostPrice,0) END ELSE ISNULL(InputCostPrice,0) END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				'' AS GoodsBTypeID,
				 GoodsCostPrice,
				 HandZeroCost,
				[ID],
				1 as Discount,
				Price as SalePrice,
				a.Total as  SaleTotal,
				Price as TaxPrice,
				a.Total as TaxTotal,
				Ktypeidout as KTypeID,
				0 as Tax,
				cargoidout as  CargoID,
				Price as NDiscountPrice,
				a.Total as NTotal,
				Price as NSalePrice,
				a.Total as NSaleTotal,
				Price as NTaxPrice,
				a.Total as NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				0 as UnitRate,
				MUnitID,
				0 as IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate	
		FROM	DeliveryBill a
		INNER JOIN PosAllotApplyBillIndex po on po.BillNumberId=a.BillNumberID
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE a.BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = ROUND(-@numQty,@intQtyDot)
		SET @numPriceTemp = ROUND(@numPrice,@intPriceDot)
		SET @numTotalTemp = ROUND(-@numTotal,@intMoneyDot)
		SET @numCostPriceTemp = ROUND(@numInputCostPrice,@intPriceDot)
		SET @numCostTotalTemp = ROUND(-CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1
        SET @numSaleTotal = ROUND(-@numSaleTotal,@intMoneyDot)
		SET @numTaxTotal = ROUND(-@numTaxTotal,@intMoneyDot)
		
		SELECT
			@numNTotal=ROUND(-@numNTotal,@intMoneyDot),
			@numNSaleTotal=ROUND(-@numNSaleTotal,@intMoneyDot),
			@numNTaxTotal=ROUND(-@numNTaxTotal,@intMoneyDot),
			@numNQty=ROUND(-@numNQty,@intQtyDot)
			
		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate

		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END 
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	

	RETURN 0
END


IF @numBillType=328	--门店配送退货单（991新单据类型）
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				a.Qty,
				Price,
				a.Total,
				'' AS JobNumber,
				po.BillDate AS OutFactoryDate,
				CASE WHEN ISNULL(InputCostPrice,0)=0 THEN GoodsCostPrice
					 ELSE InputCostPrice END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				'' AS GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				1 as Discount,
				Price as SalePrice,
				a.Total as  SaleTotal,
				Price as TaxPrice,
				a.Total as TaxTotal,
				a.inKtypeid as KTypeID,
				0 as Tax,
				incargoid as  CargoID,
				Price as NDiscountPrice,
				a.Total as NTotal,
				Price as NSalePrice,
				a.Total as NSaleTotal,
				Price as NTaxPrice,
				a.Total as NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				0 as UnitRate,
				MUnitID,
				0 as IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate	
		FROM	DeliveryBackBill a
		INNER JOIN PosAllotApplyBillIndex po on po.BillNumberId=a.BillNumberID
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	a.BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate

		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END 
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	

	RETURN 0
END


IF @numBillType =329	--门店配送退货单（991新单据类型）
BEGIN
	DECLARE CreateMx_CURSOR CURSOR FAST_FORWARD FOR
		SELECT	PTypeID,
				a.Qty,
				Price,
				a.Total,
				'' AS JobNumber,
				po.billdate AS OutFactoryDate,
				CASE WHEN ISNULL(InputCostPrice,0)=0 THEN GoodsCostPrice
					 ELSE InputCostPrice END AS InputCostPrice,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				'' AS GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost,
				[ID],
				1 as Discount,
				Price as SalePrice,
				a.Total as  SaleTotal,
				Price as TaxPrice,
				a.Total as TaxTotal,
				a.inKtypeid as KTypeID,
				0 as Tax,
				incargoid as  CargoID,
				Price as NDiscountPrice,
				a.Total as NTotal,
				Price as NSalePrice,
				a.Total as NSaleTotal,
				Price as NTaxPrice,
				a.Total as NTaxTotal,
				ItemID,
				IsCombined,
				NQty,
				0 as UnitRate,
				MUnitID,
				0 as IsGift,
				b.IsService,
				a.Comment,
				a.MUnitRate	
		FROM	DeliveryCheckBill a
		INNER JOIN PosAllotApplyBillIndex po on po.BillNumberId=a.BillNumberID
		INNER JOIN PType b
		ON a.PtypeId=b.typeId
		WHERE	a.BillNumberID = @intBillNumberID

	OPEN CreateMx_CURSOR
	FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
											@numQty,
											@numPrice,
											@numTotal,
											@chvJobNumber,
											@datOutFactoryDate,
											@numInputCostPrice,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost,
											@intID,
											@numDiscount,
											@numSalePrice,
											@numSaleTotal,
											@numTaxPrice,
											@numTaxTotal,
											@chvKTypeID,
											@numTax,
											@intCargoID,
											@numNPrice,
											@numNTotal,
											@numNSalePrice,
											@numNSaleTotal,
											@numNTaxPrice,
											@numNTaxTotal,
											@intItemID,
											@intIsCombined,
											@numNQty,
											@numUnitRate,
											@intMUnitID,
											@intIsGift,
											@intIsService,
											@strComment,
											@numMUnitRate
											
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 循环写入 InOustStockTable
		SET @numQtyTemp = @numQty
		SET @numPriceTemp = @numPrice
		SET @numTotalTemp = @numTotal
		SET @numCostPriceTemp = @numInputCostPrice
		SET @numCostTotalTemp = ROUND(CAST(@numInputCostPrice * @numQty AS  NUMERIC(24, 10) ),@intMoneyDot)
		IF @numInputCostPrice <> 0 AND @numCostTotalTemp = 0
			SET @HandZeroCost = 1

		EXEC @intReturnCode = GP_CreateMX_InsertInOut @intBillNumberID,@datBillDate,@numBillType,@GOODS_ID,@chvPTypeID,@chvDealBTypeID,@chvETypeID,@chvKTypeID,
			@numQtyTemp,@numPriceTemp,@numTotalTemp,@numCostPriceTemp,@numCostTotalTemp,@chvJobNumber,@datOutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intID,
			@numTax,@numDiscount,@numSalePrice,@numSaleTotal,@numTaxPrice,@numTaxTotal,@chvDTypeID,@chvSTypeID,
			@intCargoID,@numNPrice,@numNTotal,@numNSalePrice,@numNSaleTotal,@numNTaxPrice,@numNTaxTotal,@intItemID,@intIsCombined,@numNQty,@numUnitRate,@intMUnitID,
			@intIsGift,@intIsService,@strComment,@datPostTime,@numMUnitRate

		IF @intReturnCode <> 0 GOTO ERROR1

		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvPTypeID,
												@numQty,
												@numPrice,
												@numTotal,
												@chvJobNumber,
												@datOutFactoryDate,
												@numInputCostPrice,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost,
												@intID,
												@numDiscount,
												@numSalePrice,
												@numSaleTotal,
												@numTaxPrice,
												@numTaxTotal,
												@chvKTypeID,
												@numTax,
												@intCargoID,
												@numNPrice,
												@numNTotal,
												@numNSalePrice,
												@numNSaleTotal,
												@numNTaxPrice,
												@numNTaxTotal,
												@intItemID,
												@intIsCombined,
												@numNQty,
												@numUnitRate,
												@intMUnitID,
												@intIsGift,
												@intIsService,
												@strComment,
												@numMUnitRate
	END 
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR

	

	RETURN 0
END



RETURN 0

ERROR1:
	RETURN ISNULL(@intReturnCode,0)
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
	
ERROR4:
	RETURN -4
	CLOSE CreateMx_CURSOR
	DEALLOCATE CreateMx_CURSOR
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON
GO





IF exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_CreateOftenMenuItem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[gp_CreateOftenMenuItem]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		创建常用菜单项 
-- WANG WEI 
-- exec gp_CreateOftenMenuItem @chvoperator=N'0000100001',@intParentId=500,@enableplug=0
-- ========================================================================
CREATE PROCEDURE gp_CreateOftenMenuItem
(
	@chvOperator	VARCHAR(100),	-- 操作员 ID 值
	@intParentID	INT,			-- 父节点 ID 值
	@enableplug INT  --1启用 0不启用  --插件添加
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(
	SELECT	1
	FROM	LoginUser
	WHERE	ETypeID = @chvOperator
)
RETURN 1	-- 操作员不存在 

DECLARE @btypeid VARCHAR(MAX),@sysid CHAR(1),@lim VARCHAR(MAX),@ReCv INT
SELECT @sysid=SysID,@btypeid=BtypeID,@lim=Lim FROM Loginuser WHERE etypeid=@chvOperator


DECLARE @sql VARCHAR(MAX),@lx INT,@start INT
DECLARE @sqlm VARCHAR(MAX),@sqln VARCHAR(MAX),@sqlo VARCHAR(MAX)
DECLARE @checkSerial INT

-----检查是否可使用序列号-----
IF EXISTS(SELECT SubNo FROM sysdata WHERE SubName='Edition' AND (SubValue=2 OR SubValue=5 OR SubValue=7 OR SubValue = 8))
	SET @checkSerial=1
ELSE
	SET @checkSerial=0
	
IF @checkSerial=1
	IF  EXISTS(SELECT SubNo FROM sysdata1 WHERE SubName='OffLine' AND (SubValue=4 OR SubValue=5 OR SubValue = 6 OR SubValue = 7 OR SubValue=10 OR SubValue=11))
		SET @checkSerial=1
	ELSE
		SET @checkSerial=0
----------------------------------------------------------------------
SELECT @sqln=''
SELECT @sqlo=''

-- 谢吉康  2005-1-18 判断是否采用了“采用分支机构预设售价管理”
DECLARE @sqlG varchar(MAX)
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BatchPrePriceManage' AND Value = 1)
	SELECT @sqlG = ' offset NOT IN (484) '
ELSE
	SELECT @sqlG=' 1=1'	


IF @sysid=1
	IF @checkSerial=0
		SELECT @sqlm=' offset NOT IN (226,227,228,427)'
	ELSE
		SELECT @sqlm=' 1=1'
ELSE
	BEGIN
		IF @checkSerial=0
			SELECT @sqlm=' SUBSTRING('''+@Lim+''',offset,1)=''1'' AND offset NOT IN (226,227,228,427)'
		ELSE
			SELECT @sqlm= ' SUBSTRING('''+@Lim+''',offset,1)=''1'''

		SELECT @sqln=' OR menuid IN (SELECT a.menuid FROM webmenu a INNER JOIN (SELECT parentid FROM webmenu WHERE sysid=0 AND '+@sqlm+') b ON a.menuid=b.parentid)'
		SELECT @sqlo=' OR menuid IN (SELECT a.parentid FROM webmenu a INNER JOIN (SELECT parentid FROM webmenu WHERE sysid=0 AND '+@sqlm+') b ON a.menuid=b.parentid)'
	END

-- 基础版不享受 “商品近效期查询” 菜单项
DECLARE @chvSQLSP varchar(MAX)
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'Edition' AND SubValue = '1')
	OR EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'costing' AND SubValue <> '3')
	SET @chvSQLSP = '1=1'
ELSE
	SET @chvSQLSP = ' 1=1'

--9.4.1 提成不再区分基础版、通讯版、电脑版
-- 基础版，屏蔽提成管理模块
--IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'Edition' AND SubValue = '1')
--	SET @chvSQLSP = @chvSQLSP + ' AND MenuID NOT IN (5107,510701,510702,510703,510704)'

-- 判断是否启用货位
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'mngcargospace' AND Value = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (1238,799,6901304,10102007,5301080)'

--关闭现金银行报表
SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (945)' --,6901402 调拨分布

--屏蔽“基础资料”下的“公司信息”
SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (1230) '

--屏蔽“序列号库存查询”
SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (9754) '

--屏蔽“数据搬移”下的“银行账户”、“其他收入”、“费用类型”、“固定资产”
--SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (11001060,11001070,11001080,11001090) '

--物流单据商品是否采用批号
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName =  'IFusegoodsnumber' AND Value = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (6901305) '

--是否启用自由项
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'isfreeitem' AND SubValue = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (6901306,502080,502090) '

--是否启用条码组合管理
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IFuseentrycodeext' AND SubValue = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (11004030,11004040) '
	
--是否启用外币 (不启用外币是关闭“期末汇差”菜单)
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'isforeigncurrency' AND SubValue = 1)
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (80062) '
	
--管金所控制
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'isShowFinancingServices'	 AND SubValue = '1')
	SET @chvSQLSP = @chvSQLSP + ' AND MenuId NOT IN (170007) '	

EXEC @ReCv = Gp_ChkSdAllType
IF (@ReCv = 0) RETURN	
	
--正式运算菜单数据	
CREATE TABLE #WebOfterMenu
(
	MenuID 		int,
	ParentID 	int,
	Caption 	varchar(MAX),
	[Name] 		varchar(MAX),
	IsSubMenu 	bit,
	Title		varchar(MAX),
	img 		varchar(MAX),
	TabOrd		int,
	ShortCut	VARCHAR(200)
)	

--查询数据
SET @SQL = 'INSERT INTO #WebOfterMenu 
			SELECT	menuid,
					parentid,
					caption,
					NAME,
					issubmenu,
					title,
					img,
					TabOrd,
					ShortCut 
			FROM	webmenu 
			WHERE	sysid=0 
					AND ('+@sqlm+@sqln+@sqlo+') 
					AND ('+@sqlG+') 					
					AND ('+@chvSQLSP+') 
							OR Caption =''开账向导''  
							OR Caption = ''管金所|融资服务'' 
							OR Caption = ''应用中心''
							OR Caption = ''全渠道业务同步中心'' 
							OR Caption = ''智慧经营管理系统''  
					'
					
--PRINT(@SQL)					
EXEC(@SQL)

--期初单据采用父菜单控制所有子菜单，父菜单不设offset,此处特殊处理控制菜单
DECLARE @Value INT
SELECT @Value = SUBSTRING(lim,2369,1) FROM dbo.loginuser WHERE etypeid = @chvOperator
IF @Value = 1
BEGIN
	SELECT @Value = SUBSTRING(lim,2360,1) FROM dbo.loginuser WHERE etypeid = @chvOperator
	IF @Value = 1
		INSERT INTO #WebOfterMenu SELECT MenuID,ParentID,Caption,Name,IsSubMenu,Title,img,Tabord,ShortCut FROM dbo.WebMenu WHERE MenuID LIKE '101030%' ORDER BY Tabord
	ELSE
		INSERT INTO #WebOfterMenu SELECT MenuID,ParentID,Caption,Name,IsSubMenu,Title,img,Tabord,ShortCut FROM dbo.WebMenu WHERE MenuID LIKE '101030%' AND MenuID <> '10103060' ORDER BY Tabord	
END

--处理三级菜，不处理的话菜单看不见
INSERT INTO #WebOfterMenu
SELECT	W.menuid,W.parentid,W.caption,W.NAME,W.issubmenu,W.title,W.img,W.TabOrd,W.ShortCut
FROM	WebMenu W
INNER JOIN (
			SELECT	ParentId
			FROM	#WebOfterMenu
			--WHERE	MenuId IN (511050,62050,69013,80050,88030,1273,88050,101030)
) U ON W.MenuId = U.ParentId
			
-- 删除单据自定义编号的菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName ='BillCodeConfig' AND Value='1')
DELETE FROM #WebOfterMenu WHERE Name ='LIMIT_BillCode_Config'


DELETE FROM #WebOfterMenu WHERE ParentId IN (690,1273,1600,160001,160002,160003)
DELETE FROM #WebOfterMenu WHERE MenuId IN (690,1273,6902071,1237,1238,1239,11001120,11001130,11001140,11001150,799,6902078,6902079,6902080,6902072,6902030,6902020,1600,880169)	

--V1、V3关闭分支机构的信息 关闭“会计科目”
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '4'))
BEGIN
	DELETE FROM #WebOfterMenu WHERE ParentID IN (69050)	
	DELETE FROM #WebOfterMenu WHERE MenuID IN (510311,69050,101001,11001005,883,881,882,880187,880188,1391,1392,1096)	
	--关闭【内部应收期初】菜单
	DELETE FROM #WebOfterMenu WHERE MenuID  =501040	
	--关闭【资金调拨单】菜单
	DELETE FROM #WebOfterMenu WHERE MenuID  =5604131	
	--关闭【科目余额汇总表】菜单
	DELETE FROM #WebOfterMenu WHERE MenuID  =880503011			
	--关闭【分支机构使用情况检查】菜单
	DELETE FROM #WebOfterMenu WHERE MenuID = 1100120150
	--优惠券分支机构调拨菜案
	DELETE FROM #WebOfterMenu WHERE MenuID IN (5702011,570201101,570201102,570201103,570201104)	
END

--V1、A8关闭单据往来科目设置菜单
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '2' OR SubValue = '4'))
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID IN (56080)		
END
	
--A8关闭“部门核算的报表”
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID IN (880187,880188,1391,1392,11001005)		
END

--非序列号版本，删除序列号相关菜单
IF @checkSerial=0
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID IN (975,53010100,53010110) OR ParentID = 975	
END

--电脑行业版才有装机配置单
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '2' OR SubValue = '4')) AND NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'Edition' AND SubValue = '5') 
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID = 51020 OR ParentID = 51020
END

--9.4修改所有成本算法下均显示销售费用分摊
--移动加权才出“费用分摊”菜单
--9.7.1bug358非移动加权算法不显示成本计算菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'costing' AND SubValue = '0')
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID IN (8804010,741,8804040) OR ParentID IN (8804010,8804040)
END

--控制POS菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig  WHERE ConfigName = 'IsPosStart') 
	OR EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'IsPosStart' AND Value = '0')
BEGIN
	DELETE FROM #WebOfterMenu WHERE  ParentID = 51010 	 
	AND MenuID<>505 AND MenuID<>5101020 AND MenuID<>5101060 AND MenuID<>5101021
	--零售单和零售退货单菜单显示
END	

--控制电子称相关
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig  WHERE ConfigName = 'userelectronweigh') 
	OR EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'userelectronweigh' AND Value = '0')
BEGIN
	DELETE FROM #WebOfterMenu WHERE  MenuID=5101060 OR ParentID=5101060
END	

--控制分支机构销售计划
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'Proinfo' AND (SubValue = '1' OR SubValue = '3' OR SubValue = '4'))
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID = 51106040
END

---- 判断是否启用总账系统
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1)
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID IN (560,10102002,10102004,10102001,10102005,10102006,1096,1238,65589,1210,110012010,1097,10102010,101040)  --1210 预制数据导入 110012010 会计科目检查 --1097 会计科目多级权限
	--去掉基本信息出纳相关菜单
	DELETE FROM #WebOfterMenu WHERE MenuID IN (10102091,10102092)
		
	--去掉基本信息会计科目多级权限
	DELETE FROM #WebOfterMenu WHERE MenuID IN (1097)
	
	--去掉跨帐套总账相关菜单
	DELETE FROM #WebOfterMenu WHERE MenuID IN(1500750) OR ParentID IN (1500750)
	
	--去掉结转成本菜单
	DELETE FROM #WebOfterMenu WHERE MenuID IN (5500802)
END
--ELSE
--	DELETE FROM #WebOfterMenu WHERE MenuID IN (65588)

--非手工指定移除【商品库存批号详情】菜单
IF  EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='costing' AND SubValue <> 3) 
	DELETE FROM #WebOfterMenu WHERE MenuID =766
	
BEGIN --9.6菜单控制调整

	--系统采用序列号严密管理，序列号关联货位，自由项，批次批号时，去掉序列号调整单
	IF  EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='mngserial' AND Value = 1)  
			AND	EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='serialrelation' AND Value = 1)  
	BEGIN
		DELETE FROM #WebOfterMenu WHERE MenuID =9753
	END
END;

BEGIN	--9.7发票立账配置处理
	IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='isinvoice' AND SubValue=1)
	BEGIN
		DELETE FROM #WebOfterMenu WHERE MenuID IN (52061,51021,8801691,8801792,1010301050,1010301060,1010302050,1010302060,1010304092,1010304093)
		DELETE FROM #WebOfterMenu WHERE ParentID IN (52061,51021)
	END
END

--V1产品集中关闭菜单区域
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'Proinfo' AND SubValue = '4')
BEGIN
	DELETE 
	FROM	#WebOfterMenu 
	WHERE	ParentID IN (510730,580,11003280,10103030,511060,5095,5096,1215,170001,170002,170003,15007,1500720,1500740,1500750,69050,52061,51021,560,56041,561,51020,5500802) 
			OR MenuID IN(510730,580,11003280,11003260,10103030,511060,5095,1010304070,5096,1215,170001,170002,170003,9753,511044,502010,502020,502030,502070,502040,502050,502060,620401,15007,1500720,1500740,1500750,62924,683,51501,51502,15001,15002,69050,1100120150,101001,11001005,510311,883,501040,11003260,1010304080,1010304090,1010304091,52061,51021,880187,880188,1391,1392,881,882,560,56041,561,51020,10102035,59518,10102036,138040,138050) 
			
	--修改一级菜单名称，将“仓储运输管理”修改成“仓储管理”		
	UPDATE #WebOfterMenu SET Caption = '仓储管理' WHERE MenuId = 530
END
--非A8产品集中关闭菜单区域
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'Proinfo' AND SubValue = '2')
BEGIN
	
	DELETE FROM	#WebOfterMenu WHERE MenuID=5701021
END

--序列号销售统计
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='mngserial' AND Value = 1) OR EXISTS(SELECT * FROM SysData WHERE SubName='Edition' AND SubValue IN(1,6))
	BEGIN
		DELETE FROM	#WebOfterMenu WHERE MenuID IN(502082)	
	END
--会员期初储值维护 V3/V1不显示此菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
	BEGIN
		DELETE FROM	#WebOfterMenu WHERE MenuID IN(5701007)	
	END

--云分销判断
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'IsCloud' AND subValue='0') 
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID IN (1800,180001,180010,180020,18001001,18001002,18001003,18001004,18001005,18001006,18002001,18002002,18002003,18002004,18002005)
END
ELSE
BEGIN
	--V3 删除 云分销-上传分支机构菜单
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1'  OR SubValue = '4'))
	BEGIN
		DELETE FROM #WebOfterMenu WHERE MenuID = 18001002
	END
END

--V3 删除 资金调拨单菜单
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '4'))
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID = 5604131
END

--卡片模式和项目模式菜单处理
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='assets' AND SubValue = 1) AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) 
BEGIN
	--卡片模式去掉成本费用里的的固定资产,项目管理里的固定资产,数据搬移里的固定资产,期初单据里的成本费用(固定资产购买,变卖)
	DELETE FROM #WebOfterMenu 
	WHERE MenuID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040) 
	OR ParentID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040) 
	
	--总账模式且 模板配置-固定资产管理无权限 去掉 一级 固定资产菜单 
	IF EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig WHERE MenuID=561 AND IsChecked=1) AND EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig WHERE MenuID=560 AND IsChecked=1)
		DELETE FROM #WebOfterMenu WHERE MenuID LIKE '561%' 
END
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='assets' AND SubValue = 1) AND NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) 
BEGIN
	--卡片模式去掉成本费用里的的固定资产,项目管理里的固定资产,数据搬移里的固定资产,期初单据里的成本费用(固定资产购买,变卖)
	DELETE FROM #WebOfterMenu WHERE MenuID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040)  
	OR ParentID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040) 

	--总账管理下的固定资产
	DELETE FROM #WebOfterMenu WHERE MenuID IN (56050) OR ParentID IN (56050) 
END

--非卡片模式去掉固定资产相关菜单
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='assets' AND SubValue = 1) 
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID LIKE '561%' 
	
	DELETE FROM #WebOfterMenu WHERE MenuID IN (56050) OR ParentID IN (56050) --项目模式去掉总账里的固定资产
END

--是否启用多单位
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='doubleunit' AND Value=1)
	DELETE FROM #WebOfterMenu WHERE MenuID IN (10102034)
		
--屏蔽财务业务对账菜单
DELETE FROM #WebOfterMenu WHERE MenuID=56060 OR ParentID=56060

--判断OM
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='IsOM' AND SubValue = 0)
BEGIN
	--删除OM相关菜单
	DELETE FROM #WebOfterMenu WHERE MenuID IN (516,517,1278)
END
	
	
--判断店账通
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='isdzt' AND SubValue = 0)
	BEGIN
		--删除这两个菜单
		DELETE FROM #WebOfterMenu WHERE MenuID IN (17000410,17000420,17000430,17000440,17000450,170004)
	END
--章鱼侠云WMS及网店解决方案  
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='usewms' AND SubValue = 0)
	BEGIN
		DELETE FROM #WebOfterMenu WHERE MenuID IN (170011,17001101,17001102,17001103,17001104,17001105,17001106)
	END
--判断是否是OM add by dongzhan 2013.10.30
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='isom' AND SubValue = 0)
	BEGIN
		--删除这两个菜单
		DELETE FROM #WebOfterMenu WHERE MenuID IN (1276,1277,516)
	END
	
--暂时关闭“往来对账报表”菜单“
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubNo = 720 AND SubValue = '1')
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuId IN (SELECT MenuId FROM dbo.WebMenu WHERE MenuID IN (5108,511050,6209,62050,975,69013,88016,80010,80020,80050,110020,88030,560,561,633,590,600,633,62040,11003280,620,511040,110090))	
END

--网店管理菜单
--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'iswd' AND Value = '1')
--BEGIN	
--	DELETE FROM #WebOfterMenu WHERE MenuId IN (170006,17000604) OR parentId IN (170006,17000604)
--END
DELETE FROM #WebOfterMenu WHERE MenuId IN (170006,17000604) OR parentId IN (170006,17000604)
--是否启用账套，未启用的不显示常用菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsInvocation' AND SubValue = 1) --插件添加
	RETURN

--修改替换菜单显示  
UPDATE #WebOfterMenu
SET NAME = p.webmenuname,caption=p.name
FROM #WebOfterMenu w 
INNER JOIN dbo.Ord_PopUpPage p ON w.menuid =p.replacemenuid

--根据版本过滤是否过期 版本验证可能不完善
DECLARE @currentdbversion VARCHAR(100),@mversion VARCHAR(10)
SELECT @currentdbversion=SubValue FROM dbo.sysdata WHERE SubName='Version'
SELECT @mversion=SubValue FROM dbo.sysdata WHERE subname='mVersion'

SELECT identity(int,1,10) as seedid,p.* 
INTO #Ord_PopUpPage
FROM dbo.Ord_PopUpPage p INNER JOIN dbo.Ord_Plug i ON p.plugid=i.id
WHERE LEN(i.AppropriateVerSion)<10 
	  OR ( CHARINDEX(@currentdbversion,i.AppropriateVerSion)>0 AND CHARINDEX(@currentdbversion+'*',i.AppropriateVerSion)<=0)
	  OR ( CHARINDEX(@currentdbversion+'*'+@mversion,i.AppropriateVerSion)>0)



--杨俊添加：添加插件的上级菜单，直到顶级菜单（4级）
--插件Menu
CREATE TABLE #PlugMenu
(
	MenuID 		int,
	ParentID 	int,
	Caption 	varchar(MAX),
	[Name] 		varchar(MAX),
	IsSubMenu 	bit,
	Title		varchar(MAX),
	img 		varchar(MAX),
	TabOrd		INT,
	Shortcut	VARCHAR(MAX)
)
--写入插件Menu
INSERT #PlugMenu
SELECT  CAST(Parentmenuid AS VARCHAR(10))+CAST(seedid AS VARCHAR(10)) AS menuid,Parentmenuid AS parentid,NAME AS caption,
			p.webmenuname AS [Name],
			CAST(0 AS BIT) AS issubmenu,'' AS title,'' AS img,
			(SELECT MAX(tabord) FROM #WebOfterMenu WHERE ParentID=p.Parentmenuid) AS tabord,
			'' AS shortcut
			FROM dbo.#Ord_PopUpPage p
			INNER JOIN dbo.ord_LimitList l ON p.id=l.plugmenuid
			INNER JOIN Ord_PlugLimitFooting f ON l.Id = f.LimitId AND f.lim=1  AND etypeid=@chvOperator
			WHERE ISNULL(p.replacemenuid,'')='' AND  @chvOperator<>'00001' AND L.limittype IN (1,7,10,19)
--插件上级菜单ID记录
CREATE TABLE #ParentIDTemp
(
	MenuID 		int,
	ParentID 	int
)
--写入插件上级菜单游标
DECLARE @PLugParentId VARCHAR(MAX)
DECLARE PlugMenu CURSOR FOR
		SELECT DISTINCT ParentID FROM #PlugMenu
	OPEN PlugMenu
	FETCH NEXT FROM PlugMenu INTO @PLugParentId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF((SELECT COUNT(1) FROM #WebOfterMenu WHERE menuid = @PLugParentId) = 0)
		BEGIN
			--写入
			INSERT #PlugMenu(MenuID,ParentID,Caption,[Name],IsSubMenu,Title,img,TabOrd,Shortcut)
			SELECT menuid,parentid,caption,NAME,issubmenu,title,img,TabOrd,Shortcut 
			FROM webmenu WHERE menuid = @PLugParentId
			--记录上级菜单ID 以便查找上上级
			INSERT #ParentIDTemp
			SELECT menuid,parentid 
			FROM webmenu WHERE menuid = @PLugParentId
		END
		FETCH NEXT FROM PlugMenu INTO @PLugParentId
	END
	CLOSE PlugMenu
	DEALLOCATE PlugMenu
--查看上上级是否还存在上级
INSERT #ParentIDTemp(MenuID,ParentID)
SELECT	W.menuid,W.parentid 
FROM	WebMenu W
INNER JOIN (
			SELECT	ParentId
			FROM	#ParentIDTemp
) U ON W.MenuId = U.ParentId
--将上上级与上上上级都写入#PlugMenu
INSERT #PlugMenu(MenuID,ParentID,Caption,[Name],IsSubMenu,Title,img,TabOrd,Shortcut)
SELECT	W.menuid,W.parentid,W.caption,W.NAME,W.issubmenu,W.title,W.img,W.TabOrd,W.Shortcut
FROM	WebMenu W
INNER JOIN (
			SELECT	ParentId
			FROM	#ParentIDTemp
) U ON W.MenuId = U.ParentId

--杨俊添加-----END------------
--=========================9.7.1新增系统模块配置功能 筛选不在默认的菜单【BEGIN】=======================
DECLARE @ExcludeMenuId TABLE(MenuId		VARCHAR(100))
INSERT INTO @ExcludeMenuId(MenuId) EXEC Web_GetClearMenuId	
--删除不在模块中的菜单
DELETE FROM #WebOfterMenu WHERE MenuId IN (SELECT menuId FROM @ExcludeMenuId)
--============================处理期初单据菜单
DECLARE @Limit INT
CREATE TABLE #Temp(MenuId VARCHAR(100))
--销售管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=510
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103010 OR MenuID=10103010
--采购管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=520
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103020 OR MenuID=10103020
--维修管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=580
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103030 OR MenuID=10103030 
--往来管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=540
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103040 OR MenuID=10103040 
--成本费用管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=550
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103050 OR MenuID=10103050
--会员卡券管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=570
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE MenuID=501014
--=========================9.7.1新增系统模块配置功能 筛选不在默认的菜单【END】=======================

--9.8某些功能暂停研发，暂时屏蔽有些菜单
DELETE FROM #WebOfterMenu WHERE MenuID IN (1041)

--物流配送模块，根据系统配置控制菜单显示
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'useonshelves' AND SubValue = '0')	----没有启用上架或者拣货中的一个，则删除仓储管理菜单
	AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usepickgoods' AND SubValue = '0')
	AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usetransport' AND SubValue = '0')
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuID IN (53003,5300302,5300304,5300301,5300303,690132110,6901321,53012,5301201,5301202,690132120,10103080,1010308001,1010308002,8804030,6901322)
END
ELSE
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'useonshelves' AND SubValue = '0')	----没有启用上架或者拣货中的一个，则删除仓储管理菜单
		AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usepickgoods' AND SubValue = '0')
	BEGIN
		DELETE FROM #WebOfterMenu WHERE MenuID IN (53003,690132110,690132120,6901322)
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'useonshelves' AND SubValue = '1')	--启用上架
		BEGIN			
			DELETE FROM #WebOfterMenu WHERE MenuID IN (5300302,5300304,690132120)
		END

		IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usepickgoods' AND SubValue = '1')	--启用拣货
		BEGIN			
			DELETE FROM #WebOfterMenu WHERE MenuID IN (5300301,5300303,690132110)
		END
	END
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usetransport' AND SubValue = '1')	--启用运输配送
	BEGIN
		DELETE FROM #WebOfterMenu WHERE MenuID IN (53012,5301201,5301202,690132130,10103080,1010308001,1010308002,8804030)
	END
END

--未启用分支机构独立开账，则关闭启用期间设置这个菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'stypeindependentopen' AND SubValue = '1')
BEGIN
	DELETE FROM #WebOfterMenu WHERE menuid IN (6100102)
END

--是否启用实物库存
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'isphysicalsstock' AND SubValue = '1')
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuId IN (53010,1111,10103060) OR ParentId IN (53010,10103060)
END

--是否启用组合商品
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'combinationproduct' AND SubValue = '1')
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuId IN (511070,1010301070,1010301080) OR ParentId IN (511070)
END

--是否启用存货类型
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'useatypefrom' AND SubValue = '1')
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuId IN (10102011)
END
--成本核算子级不存在
IF NOT EXISTS(SELECT TOP 1 1 FROM #WebOfterMenu WHERE parentId=55008)
	DELETE FROM #WebOfterMenu WHERE MenuId=55008

--没有启用品牌管理，删除菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue = '1')
	BEGIN
		DELETE FROM #WebOfterMenu WHERE MenuId IN(10102036,138040,138050,880302007,10102026)
	END
ELSE 
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'brandarcontrollineofcredit' AND SubValue = '0')
		BEGIN
			DELETE FROM #WebOfterMenu WHERE MenuId IN(10102026)
		END
	END
	
--所有广告的控制
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'isshowallgg' AND SubValue = '0')
BEGIN
	DELETE FROM #WebOfterMenu WHERE menuid IN (170007)	--170007(管金所|融资服务)
END	

--1688订单管理
IF EXISTS(SELECT TOP 1 1 FROM dbo.WdShopBaseInfo WHERE Field = 'isUse1688' AND Value = '0')
BEGIN
	DELETE FROM #WebOfterMenu WHERE menuid IN (17000606)	--1688订单管理
END

--未启用微信则不允许再使用微信了
--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.PayConfigInfo WHERE PayType = 2)
--BEGIN
--	DELETE FROM #WebOfterMenu WHERE MenuId = 11001302
--END

--门店配送单
IF NOT EXISTS(SELECT TOP 1 1 FROM userconfig WHERE configname='usepostrans' AND Value = '1')
BEGIN
	DELETE FROM #WebOfterMenu WHERE MenuId = 69015 OR ParentId = 69015
END

--全渠道菜单
IF NOT EXISTS(
	SELECT b.Name FROM sysobjects b	
	WHERE b.Name='Plu_SS_SysInfo'
)
BEGIN
	DELETE FROM #WebOfterMenu WHERE menuid IN (170009)
END
	
--整理菜单
IF @chvOperator <> '00001'
BEGIN
	DECLARE @MenuId		VARCHAR(MAX),
			@ParId		VARCHAR(MAX),
			@SubMenuId	VARCHAR(MAX),
			@SubParId	VARCHAR(MAX),
			@SubMenuIdx	VARCHAR(MAX),
			@SubParIdx	VARCHAR(MAX)
			
	DECLARE MenuCursor CURSOR FOR
		SELECT MenuID,ParentId FROM #WebOfterMenu WHERE IsSubMenu = '1' AND (ParentId = 500 OR MenuID IN (511050,62050,69013,80050,88030))
	OPEN MenuCursor
	FETCH NEXT FROM MenuCursor INTO @MenuId,@ParId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE SubMenuCursor CURSOR FOR
			SELECT MenuID,ParentId FROM #WebOfterMenu WHERE ParentId = @MenuId AND IsSubMenu = '1'
		OPEN SubMenuCursor
		FETCH NEXT FROM SubMenuCursor INTO @SubMenuId,@SubParId
		WHILE @@FETCH_STATUS = 0
		BEGIN
			--删除第三级菜单
			IF NOT EXISTS(SELECT TOP 1 1 FROM #WebOfterMenu WHERE ParentID = @SubMenuId)
			BEGIN
				DELETE FROM #WebOfterMenu WHERE MenuID = @SubMenuId
			END
			ELSE
			BEGIN
				DECLARE SubMenuCursorx CURSOR FOR
					SELECT MenuID,ParentId FROM #WebOfterMenu WHERE ParentId = @SubMenuId AND IsSubMenu = '1'
				OPEN SubMenuCursorx
				FETCH NEXT FROM SubMenuCursorx INTO @SubMenuIdx,@SubParIdx
				WHILE @@FETCH_STATUS = 0
				BEGIN							
					--删除第四级菜单
					IF NOT EXISTS(SELECT TOP 1 1 FROM #WebOfterMenu WHERE ParentID = @SubMenuIdx)
					BEGIN
						DELETE FROM #WebOfterMenu WHERE MenuID = @SubMenuIdx
					END		
						
					FETCH NEXT FROM SubMenuCursorx INTO @SubMenuId,@SubParIdx
				END
				CLOSE SubMenuCursorx
				DEALLOCATE SubMenuCursorx
			END	
				
			FETCH NEXT FROM SubMenuCursor INTO @SubMenuId,@SubParId
		END
		CLOSE SubMenuCursor
		DEALLOCATE SubMenuCursor
		--删除第二级菜单
		IF NOT EXISTS(SELECT TOP 1 1 FROM #WebOfterMenu WHERE ParentID = @MenuId)
			DELETE FROM #WebOfterMenu WHERE MenuID = @MenuId
		--删除第一级菜单	
		IF NOT EXISTS(SELECT TOP 1 1 FROM #WebOfterMenu WHERE ParentID = @ParId)
			DELETE FROM #WebOfterMenu WHERE MenuID = @ParId
				
		FETCH NEXT FROM MenuCursor INTO @MenuId,@ParId
	END
	CLOSE MenuCursor
	DEALLOCATE MenuCursor
END			

--加入插件菜单
SELECT * FROM 
(
	SELECT DISTINCT MenuID,ParentID,Caption,[Name],IsSubMenu,Title,img,TabOrd,Shortcut FROM #WebOfterMenu 
	UNION ALL 
	SELECT MenuID,ParentID,Caption,[Name],IsSubMenu,Title,img,TabOrd,Shortcut FROM #PlugMenu
	UNION ALL  --操作员为管理员的全部显示
	SELECT CAST(Parentmenuid AS VARCHAR(10))+CAST(seedid AS VARCHAR(10))  AS menuid,Parentmenuid AS parentid,NAME AS caption,
			p.webmenuname AS [Name],
			CAST(0 AS BIT) AS issubmenu,'' AS title,'' AS img,
			ROW_NUMBER() OVER (ORDER BY ID)+(SELECT MAX(tabord) FROM #PlugMenu WHERE ParentID=p.Parentmenuid) AS tabord,
			'' AS shortcut
			FROM dbo.#Ord_PopUpPage p
			WHERE  @chvOperator='00001' AND ISNULL(p.replacemenuid,'')=''  
) c 
WHERE Not EXISTS(SELECT TOP 1 1 FROM #Temp WHERE MenuID=C.MenuID)
ORDER BY Tabord  


DROP TABLE #WebOfterMenu,#Ord_PopUpPage,#ParentIDTemp,#PlugMenu,#Temp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：张陈仁
	日期：2012-01-31
	描述：根据AppUtils.productName的产品标识值，更新数据库的记录
*/

CREATE PROCEDURE Gp_CreateProInfo
( 
	@proInfoValue			INT,-- 产品标识值
	@encryptProInfoValue	INT,
	@subNo					INT,
	@subNo1					INT 			
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON

DECLARE @isHaveProSysData VARCHAR(20),
        @isHaveProSysData1 VARCHAR(20),
        @bCount	INT,
        @vCount	INT

--Sysdata
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='ProInfo')
	UPDATE SysData SET SubValue=@proInfoValue WHERE SubName='ProInfo'
ELSE
	INSERT INTO SysData (SubNo,SubName,SubValue,SubComment) VALUES(@subNo,'ProInfo',@proInfoValue,'')

IF EXISTS(SELECT TOP 1 * FROM sysdata WHERE SubName = 'curdate' AND SubValue <> CONVERT(VARCHAR(10),GETDATE(),120))
BEGIN
	SELECT @bCount = COUNT(*) FROM BillIndex WHERE ifcheck = 't' AND RedWord = 0
	SELECT @vCount = COUNT(*) FROM Ac_Voucher WHERE IfCheck = 't' AND RedWord = 0
	UPDATE sysdata SET SubValue = '' WHERE SubName IN ('curdate','curflag','curinfo')
	UPDATE sysdata1 SET SubValue = '' WHERE SubName = 'curinfo'
	UPDATE Userconfig SET Value = '' WHERE ConfigName = 'curinfo'
	UPDATE sysdata SET SubValue = @bCount + @vCount WHERE SubName = 'TbCount'
END


--Sysdata1
IF EXISTS(SELECT TOP 1 1 FROM SysData1 WHERE SubName='ProInfo')
	UPDATE SysData1 SET SubValue=@encryptProInfoValue WHERE SubName='ProInfo'
ELSE
    INSERT INTO SysData1 (SubNo,SubName,SubValue,SubComment) VALUES(@subNo1,'ProInfo',@encryptProInfoValue,'')


--删除自动保存的单据的历史数据
IF EXISTS(
	SELECT	TOP 1
			BillGuid 
	FROM	BillIndexAutoDraft 
	WHERE	CONVERT(VARCHAR(10),CreateDate,120) < CONVERT(VARCHAR(10),GETDATE(),120)
)
BEGIN
	DECLARE @TempBillIndex TABLE
	(
		BillGuid		VARCHAR(100)
	)

	INSERT INTO @TempBillIndex(BillGuid) 
	SELECT	BillGuid 
	FROM	BillIndexAutoDraft 
	WHERE	CONVERT(VARCHAR(10),CreateDate,120) < CONVERT(VARCHAR(10),GETDATE(),120)

	DELETE FROM BillIndexAutoDraft WHERE BillGuid IN (SELECT BillGuid FROM @TempBillIndex)
	DELETE FROM BuyBillAutoDraft WHERE BillGuid IN (SELECT BillGuid FROM @TempBillIndex)
	DELETE FROM SaleBillAutoDraft WHERE BillGuid IN (SELECT BillGuid FROM @TempBillIndex)
	DELETE FROM dbo.BillMulAccountAutoDraft WHERE BillGuid IN (SELECT BillGuid FROM @TempBillIndex)
	DELETE FROM BillMulBrandAutoDraft WHERE BillGuid IN (SELECT BillGuid FROM @TempBillIndex)
	DELETE FROM dbo.Custom_BillIndexAutoDraft WHERE BillGuid IN (SELECT BillGuid FROM @TempBillIndex)
	DELETE FROM dbo.Custom_BillDetailsAutoDraft WHERE BillGuid IN (SELECT BillGuid FROM @TempBillIndex)
	DELETE FROM dbo.Coupon_BillUsedAutoDraft WHERE BillGuid IN (SELECT BillGuid FROM @TempBillIndex)	
END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  * FROM    dbo.sysobjects WHERE   id = OBJECT_ID(N'[dbo].[Gp_CreateQtMx]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_CreateQtMx]
GO


/*
-- 功能说明：		产生 ListTable 中，除应收、应付外的其他科目的相关信息
-- 最后修改作者：	卢 春
-- 最后修改时间：	2006-08-14


修改:冯波  2015-05-19  暂估

*/
CREATE  PROCEDURE Gp_CreateQtMx
(
    @nBillId [numeric](10, 0),
    @nBillType	INT,
    @strMsg		VARCHAR(200)  
)
--@encode$--
AS 
    SET nocount ON

    DECLARE 
		@GOODS_ID			VARCHAR(50) ,
        @GOODS_LOSS_ID		VARCHAR(50) ,
        @GOODS_GET_ID		VARCHAR(50) ,
        @ALLOT_PRICE_ID		VARCHAR(50) ,
        @PRICE_INCOME_ID	VARCHAR(50) ,
        @GOODS_PRODUCE_ID	VARCHAR(50) ,
        @SALE_COST_ID		VARCHAR(50) ,
        @SALE_INCOME_ID		VARCHAR(50) ,
        @BALANCE_ID			VARCHAR(50) ,
        @DEPRECIATION_ID	VARCHAR(50) ,
        @APPORTION_EXPENSE_ID VARCHAR(50) ,
        @ADDEBT_INCOME_ID	VARCHAR(50) ,
        @ADDEBT_LOSE_ID		VARCHAR(50) ,
        @GOODS_GIVE_RECNO	VARCHAR(50) ,
        @GOODS_GIVEME_RECNO VARCHAR(50) ,
        @REPAIR_INCOME_ID	VARCHAR(50) ,
        @DXGOODSMONEY_ID	VARCHAR(50) ,
        @STTH_BANLANCE_ID	VARCHAR(50) ,
        @WtDxGoods_ID		VARCHAR(50) ,
        @WX_PTYPE_EXPENSE	VARCHAR(50),
        @OtherGain			VARCHAR(50),
        @OtherFee			VARCHAR(50),
        @APAppraisal		VARCHAR(50),
        @SendOut			VARCHAR(50),
        @PAY_TAXMONEY_ID	VARCHAR(50),
        @AP					VARCHAR(50),
        @AR					VARCHAR(50),
        @KCSPZZ				VARCHAR(50),
        @ZZCL				VARCHAR(50),
        @PSCJ				VARCHAR(50)
        
    
	SELECT @GOODS_ID=nId FROM dbo.Ac_Items WHERE UserCode='1241'  --『库存商品总值合计』,0000100001
	SELECT @APPORTION_EXPENSE_ID=nId FROM dbo.Ac_Items WHERE UserCode='1301'  --『待摊费用』,0000100007
	SELECT @WtDxGoods_ID=nId FROM dbo.Ac_Items WHERE UserCode='1261'  --『委托代销商品』,0000100008
	SELECT @DXGOODSMONEY_ID=nId FROM dbo.Ac_Items WHERE UserCode='2141'  --『代销商品款』,0000200003
	SELECT @SALE_INCOME_ID=nId FROM dbo.Ac_Items WHERE UserCode='5101'  --『销售收入』,0000300001
	SELECT @GOODS_GET_ID=nId FROM dbo.Ac_Items WHERE UserCode='0321'  --商品报溢收入,000030000200001
	SELECT @GOODS_GIVEME_RECNO=nId FROM dbo.Ac_Items WHERE UserCode='0322'  --商品获赠收入,000030000200002
	SELECT @PRICE_INCOME_ID=nId FROM dbo.Ac_Items WHERE UserCode='0323'  --成本调价收入,000030000200003
	SELECT @BALANCE_ID=nId FROM dbo.Ac_Items WHERE UserCode='0324'  --采购退货差价,000030000200004
	SELECT @ALLOT_PRICE_ID=nId FROM dbo.Ac_Items WHERE UserCode='0325'  --变价调拨差价,000030000200005
	SELECT @GOODS_PRODUCE_ID=nId FROM dbo.Ac_Items WHERE UserCode='0326'  --商品拆装差价,000030000200006
	SELECT @REPAIR_INCOME_ID=nId FROM dbo.Ac_Items WHERE UserCode='0328'  --商品维修收入,000030000200008
	SELECT @STTH_BANLANCE_ID=nId FROM dbo.Ac_Items WHERE UserCode='0329'  --受托退货差价,000030000200009
	SELECT @ADDEBT_INCOME_ID=nId FROM dbo.Ac_Items WHERE UserCode='03333'  --调账收入,000030000300001
	SELECT @SALE_COST_ID=nId FROM dbo.Ac_Items WHERE UserCode='5401'  --『销售成本』,0000400001
	SELECT @GOODS_LOSS_ID=nId FROM dbo.Ac_Items WHERE UserCode='0421'  --商品报损,000040000200001
	SELECT @GOODS_GIVE_RECNO=nId FROM dbo.Ac_Items WHERE UserCode='0422'  --商品赠出,000040000200002
	SELECT @WX_PTYPE_EXPENSE=nId FROM dbo.Ac_Items WHERE UserCode='0423'  --商品维修支出,000040000200003
	SELECT @ADDEBT_LOSE_ID=nId FROM dbo.Ac_Items WHERE UserCode='0431'  --调账亏损,000040000300001
	SELECT @DEPRECIATION_ID=nId FROM dbo.Ac_Items WHERE UserCode='0432'  --固定资产折旧,000040000300002
	SELECT @OtherGain=nId FROM dbo.Ac_Items WHERE UserCode='0333'		--其他收入,000030000300003
	SELECT @OtherFee=nId FROM dbo.Ac_Items WHERE UserCode='0455'		--其他支出,000040000300003
	
	SELECT @APAppraisal=nId FROM dbo.Ac_Items WHERE UserCode='2122'		--应付暂估
	SELECT @SendOut=nId FROM dbo.Ac_Items WHERE UserCode='1251'			--发出商品

	SELECT @PAY_TAXMONEY_ID=NID FROM ac_items WHERE UserCode='2171'  -- 『应交税金』,0000200004
    
    SELECT @AP=NID FROM ac_items WHERE UserCode='2121'	--应付合计
    
    SELECT @AR=NID FROM ac_items WHERE UserCode='987'	--应收合计
    
    SELECT @KCSPZZ=NID FROM ac_items WHERE UserCode='1241'	--库存商品总值
    SELECT @ZZCL=NID FROM ac_items WHERE UserCode='1271'	--周转材料
    SELECT @PSCJ=NID FROM ac_items WHERE UserCode='0335'	--配送差价
 


    DECLARE 
			@tBillDate		DATETIME,
			@dTotalTemp		 NUMERIC(24, 10)  ,
			@dCostTotalTemp  NUMERIC(24, 10)  ,
			@dChange		 NUMERIC(24, 10)  ,
			@szDTypeID		VARCHAR(50) ,
			@szAtypeId		VARCHAR(50) ,
			@szPtypeId		VARCHAR(50) ,
			@szbTypeId		VARCHAR(50) ,
			@szEtypeId		VARCHAR(50) ,
			@szStockId		VARCHAR(50) ,
			@szStockId2		VARCHAR(50),
			@szJobNumber	VARCHAR(20) ,
			@OutFactoryDate DATETIME ,
			@dPrice			 NUMERIC(24, 10) ,
			@szSTypeID		VARCHAR(50),
			@CID			BIGINT,
			@Ntotal			 NUMERIC(24, 10) ,
			@dNTotalTemp	 NUMERIC(24, 10) ,
			@SysCid			BIGINT,
			@tmpTotal		 NUMERIC(24, 10) ,
			@NtmpTotal		 NUMERIC(24, 10) ,
			@intCostSale	INT,
			@NumRate		 NUMERIC(24, 10) ,
			@fValue			INT
	--本位币	
	SELECT @SysCid= CID FROM dbo.Ac_Currency WHERE Sysrow=1
	
	
	DECLARE
			@dNormalCostTotalTemp		 NUMERIC(24, 10) ,		--正常商品成本
			@dNormalTotalTemp			 NUMERIC(24, 10) ,		--正常商品金额本币
			@dNNormalTotalTemp			 NUMERIC(24, 10) ,		--正常商品金额原币
			@dServiceTotalTemp			 NUMERIC(24, 10) ,		--服务商品
			@dNServiceTotalTemp			 NUMERIC(24, 10) 		--服务商品
		
		
	IF @nBillType IN (404,405)
	BEGIN
		SELECT TOP 1
				@nBillType = BillType ,
				@tBillDate = BillDate ,
				@szDTypeID = dtypeid ,
				@szbTypeId = btypeid ,
				@szEtypeId = etypeid ,
				@szSTypeID = Stypeid,
				@CID=CID,
				@NumRate = Rate
		FROM    ReceiptBillIndex
		WHERE   BillNumberId = @nBillId
	END
	ELSE IF @nBillType IN (327,328,329)
	BEGIN
		SELECT TOP 1
				@nBillType = BillType ,
				@tBillDate = BillDate ,
				@szDTypeID = dtypeid ,
				@szSTypeID = Stypeid,
				@CID=CID,
				@szEtypeId=ApplyEtypeId
		FROM    PosAllotApplyBillIndex
		WHERE   BillNumberId = @nBillId
	END
	ELSE
	BEGIN
		SELECT TOP 1
				@nBillType = BillType ,
				@tBillDate = BillDate ,
				@szDTypeID = dtypeid ,
				@szAtypeId = atypeid ,
				@szbTypeId = btypeid ,
				@szEtypeId = etypeid ,
				@szStockId = ktypeid ,
				@szStockId2 = ktypeid2 ,
				@szSTypeID = Stypeid,
				@CID=CID,
				@NumRate = Rate,
				@intCostSale = CostSale
		FROM    BillIndex
		WHERE   BillNumberId = @nBillId
	END
 ----------------为效率着想，先进行判断
 IF @nBillType NOT IN (404,405)
 BEGIN
	 IF EXISTS(
		SELECT BillNumberId
		FROM InOutstocktable
		WHERE BillNumberId=@nBillId AND IsService=1
	 )
	 BEGIN
		SELECT  
				@dTotalTemp = ISNULL(SUM(Total), 0) ,
				@dNTotalTemp =ISNULL(SUM(nTotal), 0) ,
				@dNormalTotalTemp=ISNULL(SUM(CASE IsService WHEN 0 THEN  Total ELSE 0 END), 0),
				@dNNormalTotalTemp=ISNULL(SUM(CASE IsService WHEN 0 THEN NTotal ELSE 0 END), 0),
				@dCostTotalTemp = ISNULL(SUM(CostTotal), 0),
				@dNormalCostTotalTemp=ISNULL(SUM(CASE IsService WHEN 0 THEN  CostTotal ELSE 0 END),0),
				@dServiceTotalTemp=ISNULL(SUM(CASE IsService WHEN 1 THEN  Total ELSE 0 END),0),
				@dNServiceTotalTemp=ISNULL(SUM(CASE IsService WHEN 1 THEN  NTotal ELSE 0 END),0)
		FROM    InOutstocktable
		WHERE   BillNumberId = @nBillId
				AND BillType=@nBillType
				AND atypeid = @GOODS_ID
				AND ptypeid <> '0'
	 END
	 ELSE
	 BEGIN
		SELECT  @dTotalTemp = ISNULL(SUM(Total), 0) ,
				@dNTotalTemp =ISNULL(SUM(nTotal), 0) ,
				@dCostTotalTemp = ISNULL(SUM(CostTotal), 0)
		FROM    InOutstocktable
		WHERE   BillNumberId = @nBillId
				AND BillType=@nBillType
				AND atypeid = @GOODS_ID
				AND ptypeid <> '0'
	            
		SELECT
				@dNormalCostTotalTemp=@dCostTotalTemp,
				@dServiceTotalTemp=0,
				@dNServiceTotalTemp=0,
				@dNormalTotalTemp=@dTotalTemp,
				@dNNormalTotalTemp=@dNTotalTemp
				
	 END
END	 
 
DECLARE @No6Value	INT,
		@No10Value	VARCHAR(MAX),
		@No9Value	VARCHAR(MAX),
		@No11Value	VARCHAR(MAX),
		@No13Value	VARCHAR(MAX),
		@nRet		INT
		
SELECT TOP 1 @No6Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 6
SELECT TOP 1 @No10Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 10
SELECT TOP 1 @No9Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 9
SELECT TOP 1 @No11Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 11
SELECT TOP 1 @No13Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 13

IF @No6Value = 1 AND (ISNULL(@No10Value,'')='' OR ISNULL(@No9Value,'')='' OR ISNULL(@No11Value,'')='' OR ISNULL(@No13Value,'')='')
	RETURN -5
	
-- 谢吉康 2019-09-26 屏蔽	
--EXEC Web_CheckSysValue 8,@fValue OUTPUT	
--EXEC @nRet = Gp_Fz_Base '',2
--IF @nRet <> 0 OR @fValue = 1 RETURN -5	


            
-----------------------------销售单,零售单------------------------------
 
 IF @nBillType=11 OR @nBillType=305 OR @nBillType=12
 BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		SET @tmpTotal=-@dNormalCostTotalTemp
		  --销售成本增加
		  INSERT INTO Listtable
			 (BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES
			  (@nBillId,@tBillDate,@nBillType,@SALE_COST_ID,'0',@szBtypeid,@szEtypeid,'0',-@dNormalCostTotalTemp,
			  -@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,-@dNormalCostTotalTemp,0,1)  
			  
		
		
		  --库存商品减少
		  INSERT INTO Listtable
			(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES
				(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				 @dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,@dNormalCostTotalTemp,0,1)
				 
		
	END
	
	IF @dServiceTotalTemp<>0 OR @dNServiceTotalTemp<>0
	BEGIN
		 --其他收入
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@OtherGain,'0',@szBtypeid,@szEtypeid,'0',
			 -@dServiceTotalTemp,-@dServiceTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,-@dNServiceTotalTemp,0,@NumRate)
		 
	END
	

	IF (@dNormalTotalTemp <> 0 OR @dNNormalTotalTemp<>0) AND @intCostSale<>1--销售收入增加
	BEGIN
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@SALE_INCOME_ID,'0',@szBtypeid,@szEtypeid,'0',
			 -@dNormalTotalTemp,-@dNormalTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,-@dNNormalTotalTemp,0,@NumRate)
		
		
	END
  RETURN 0
 END
------------------------------销售单处理结束--------------------------

	-- ********	采购退货单 - Start	********
	IF @nBillType = 6
		BEGIN	
			SET @dChange = @dServiceTotalTemp+@dNormalCostTotalTemp - @dTotalTemp
	

			IF @dNormalCostTotalTemp <> 0
			BEGIN
				-- 库存商品减少
				INSERT INTO ListTable (
					BillNumberID,
					BillDate,
					BillType,
					ATypeID,
					PTypeID,
					BTypeID,
					ETypeID,
					KTypeID,
					Total,
					CostTotal,
					JobNumber,
					OutFactoryDate,
					DTypeID,
					STypeID,
					CID,
					Ntotal,
					Audited,
					Rate
				)
				VALUES (
					@nBillID,
					@tBillDate,
					@nBillType,
					@GOODS_ID,
					'0',
					@szBTypeID,
					@szETypeID,
					'0',
					@dNormalCostTotalTemp,
					@dNormalCostTotalTemp,
					@szJobNumber,
					@OutFactoryDate,
					@szDTypeID,
					@szSTypeID,
					@syscid,
					@dNormalCostTotalTemp,
					0,
					1
				)
			END


			IF @dServiceTotalTemp<>0 OR @dNServiceTotalTemp<>0
			BEGIN
				INSERT INTO ListTable (
					BillNumberID,
					BillDate,
					BillType,
					ATypeID,
					PTypeID,
					BTypeID,
					ETypeID,
					KTypeID,
					Total,
					CostTotal,
					JobNumber,
					OutFactoryDate,
					DTypeID,
					STypeID,
					CID,
					Ntotal,
					Audited,
					Rate
				)
				VALUES (
					@nBillID,
					@tBillDate,
					@nBillType,
					@OtherFee,
					'0',
					@szBTypeID,
					@szETypeID,
					'0',
					@dServiceTotalTemp,
					@dServiceTotalTemp,
					@szJobNumber,
					@OutFactoryDate,
					@szDTypeID,
					@szSTypeID,
					@CID,
					@dNServiceTotalTemp,
					0,
					@NumRate
				)
			END
			
			
			-- 采购退货差价，若不等于零，则写入 ListTable 数据表
			IF @dChange <> 0
				BEGIN
					INSERT INTO ListTable (
							BillNumberID,
							BillDate,
							BillType,
							ATypeID,
							PTypeID,
							BTypeID,
							ETypeID,
							KTypeID,
							Total,
							CostTotal,
							JobNumber,
							OutFactoryDate,
							DTypeID,
							STypeID,
							CID,
							Ntotal,
							Audited,
							Rate
					)
					VALUES (
							@nBillID,
							@tBillDate,
							@nBillType,
							@BALANCE_ID,
							'0',
							@szBTypeID,
							@szETypeID,
							'0',
							@dChange,
							@dChange,
							@szJobNumber,
							@OutFactoryDate,
							@szDTypeID,
							@szSTypeID,
							@syscid,
							@dChange,
							0,
							1
					)
						
				END

			RETURN 0
		END
	-- ********	采购退货单 - End	********

------------------------------进货单------------------------------
 IF @nBillType=34
 BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		DECLARE @Total NUMERIC(24,10)
		SELECT 
			@Total=SUM(total) 
		FROM buybill a 
		INNER JOIN ptype b ON a.ptypeid=b.typeId AND  a.BillNumberId=@nBillId AND b.IsService=0
		--库存商品增加
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
					@Total,@Total,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,@Total,0,1)
		
	END
	
	IF @dServiceTotalTemp<>0 OR @dNServiceTotalTemp<>0
	BEGIN
		--其他支出
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@OtherFee,'0',@szBtypeid,@szEtypeid,'0',
					@dServiceTotalTemp,@dServiceTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,@dNServiceTotalTemp,0,@NumRate)
		
	END
	
  RETURN 0
 END
------------------------------进货单处理结束--------------------------
 DECLARE @outCostPrice NUMERIC(24,10)

IF @nBillType=327	
BEGIN
	SELECT @outCostPrice=-1*SUM(CostTotal) FROM dbo.InOutstocktable WHERE BillNumberId=@nBillId AND BillType=327
	--库存商品总值
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@KCSPZZ,'0',@szBtypeid,@szEtypeid,'0',
				dbo.F_RoundTotal(-@outCostPrice),dbo.F_RoundTotal(-@outCostPrice),@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,dbo.F_RoundTotal(-@outCostPrice),0,1)
				
		--周转材料
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@ZZCL,'0',@szBtypeid,@szEtypeid,'0',
				dbo.F_RoundTotal(@outCostPrice),dbo.F_RoundTotal(@outCostPrice),@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,dbo.F_RoundTotal(@outCostPrice),0,1)		

 END
 IF @nBillType =328
 BEGIN
		SELECT @outCostPrice=SUM(dbo.F_RoundTotal(QTY*GoodsCostPrice)) FROM DeliveryBackBill WHERE BillNumberId=@nBillId
		--库存商品总值
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@KCSPZZ,'0',@szBtypeid,@szEtypeid,'0',
					dbo.F_RoundTotal(@outCostPrice),dbo.F_RoundTotal(@outCostPrice),@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,dbo.F_RoundTotal(@outCostPrice),0,1)
					
			--周转材料
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@ZZCL,'0',@szBtypeid,@szEtypeid,'0',
					dbo.F_RoundTotal(-@outCostPrice),dbo.F_RoundTotal(-@outCostPrice),@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,dbo.F_RoundTotal(-@outCostPrice),0,1)		

 END
 
 IF @nBillType =329
 BEGIN
	SELECT 	@Total= SUM(dbo.F_RoundTotal(b.Qty*c.Price)),@outCostPrice= SUM(dbo.F_RoundTotal(b.Qty*c.GoodsCostPrice))
	FROM	PosAllotApplyBillIndex a 
	INNER JOIN dbo.DeliveryCheckBill b ON a.BillNumberId=b.BillNumberId
	INNER JOIN dbo.DeliveryBill c ON b.DeliveryID=c.ID
	WHERE	b.BillNumberId=@nBillId
	--SELECT @outCostPrice=SUM(QTY*GoodsCostPrice) FROM DeliveryCheckBill WHERE BillNumberId=@nBillId
		--库存商品总值
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@KCSPZZ,'0',@szBtypeid,@szEtypeid,'0',
					dbo.F_RoundTotal(@Total),dbo.F_RoundTotal(@Total),@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,dbo.F_RoundTotal(@Total),0,1)
					
			--周转材料
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@ZZCL,'0',@szBtypeid,@szEtypeid,'0',
					dbo.F_RoundTotal(-@outCostPrice),dbo.F_RoundTotal(-@outCostPrice),@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,dbo.F_RoundTotal(-@outCostPrice),0,1)
					
			--配送价差
		  IF dbo.F_RoundTotal(@Total-@outCostPrice) <> 0
		  BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@PSCJ,'0',@szBtypeid,@szEtypeid,'0',
					dbo.F_RoundTotal(@Total-@outCostPrice),dbo.F_RoundTotal(@Total-@outCostPrice),@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,dbo.F_RoundTotal(@Total-@outCostPrice),0,1)		
		  END
 END
------------------------------门店配送单--------------------------





------------------------------门店配送单结束--------------------------

------------------------------暂估入库单------------------------------
 IF @nBillType=400
 BEGIN
	IF @dNormalCostTotalTemp <> 0 OR @dNNormalTotalTemp<>0
	BEGIN
		--库存商品增加
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
					@dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,@dNormalCostTotalTemp,0,1)

		--应付暂估增加
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@APAppraisal,'0',@szBtypeid,@szEtypeid,'0',
			@dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,@dNNormalTotalTemp,0,1)

	END
	
  RETURN 0
 END
------------------------------暂估入库单处理结束--------------------------

------------------------------暂估退货单------------------------------
 IF @nBillType=401
 BEGIN
	IF @dNormalCostTotalTemp <> 0 OR @dNNormalTotalTemp<>0
	BEGIN
		--库存商品减少
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,@dNormalCostTotalTemp,0,1)

		--应付暂估增加	
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@APAppraisal,'0',@szBtypeid,@szEtypeid,'0',
				@dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,@dNNormalTotalTemp,0,1)

	END
	
  RETURN 0
 END
------------------------------暂估退货单处理结束--------------------------

 ------------------------------发出商品出库单开始-------------------------
IF @nBillType=402
 BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		SET @tmpTotal=-@dNormalCostTotalTemp
		  --发出商品增加
		  INSERT INTO Listtable
			 (BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES
			  (@nBillId,@tBillDate,@nBillType,@SendOut,'0',@szBtypeid,@szEtypeid,'0',-@dNormalCostTotalTemp,
			  -@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,-@dNormalCostTotalTemp,0,1)  
			  
		
		
		  --库存商品减少
		  INSERT INTO Listtable
			(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES
				(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				 @dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,@dNormalCostTotalTemp,0,1)
				 
		
	END
	
	
  RETURN 0
 END
 ------------------------------发出商品出库单结束--------------------------
 ------------------------------发出商品退货单------------------------------
 IF @nBillType=403
 BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		--发出商品减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@SendOut,'0',@szBtypeid,@szEtypeid,'0',
				-@dNormalCostTotalTemp,-@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,-@dNormalCostTotalTemp,0,1)
				
		SELECT @tmpTotal=-@dCostTotaltemp
		
		
		  --库存商品增加
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dNormalCostTotalTemp,0,1)
				
		
	END

  RETURN 0
 END
------------------------------发货商品退货单处理结束--------------------------


------------------------------销售退货单------------------------------
 IF @nBillType IN (45 ,46)
 BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		--销售成本减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@SALE_COST_ID,'0',@szBtypeid,@szEtypeid,'0',
				-@dNormalCostTotalTemp,-@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,-@dNormalCostTotalTemp,0,1)
				
		SELECT @tmpTotal=-@dCostTotaltemp
		
		
		  --库存商品增加
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dNormalCostTotalTemp,0,1)
				
		
	END

	IF @dNormalTotalTemp <> 0 OR @dNNormalTotalTemp<>0
	BEGIN
		  --销售收入减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@SALE_INCOME_ID,'0',@szBtypeid,@szEtypeid,'0',
				-@dNormalTotalTemp,-@dNormalTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,-@dNNormalTotalTemp,0,@NumRate)
				
		
	END
	
	IF @dServiceTotalTemp <> 0 OR @dNServiceTotalTemp<>0
	BEGIN
		  --其他收入减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@OtherGain,'0',@szBtypeid,@szEtypeid,'0',
				-@dServiceTotalTemp,-@dServiceTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,-@dNServiceTotalTemp,0,@NumRate)
				
		
	END

  RETURN 0
 END
------------------------------销售退货单处理结束--------------------------
------------------------------收款单--------------------------
 IF @nBillType=4
 BEGIN
  RETURN 0
 END
------------------------------收款单处理结束--------------------------
------------------------------付款单--------------------------
 IF @nBillType=66
 BEGIN
  RETURN 0
 END
------------------------------付款单处理结束--------------------------


--------------积分兑换单-------------
 IF @nBillType=183
 BEGIN
	IF @dCostTotalTemp <> 0
	BEGIN
		  --库存商品减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,cid,Ntotal,audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
			@dCostTotaltemp,@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dCostTotaltemp,0,1)
			
			--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
		  --赠送
		  SELECT @tmpTotal = -@dCostTotaltemp
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,cid,Ntotal,audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_GIVE_RECNO,'0',@szBtypeid,@szEtypeid,'0',
			-@dCostTotaltemp,-@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,-@dCostTotaltemp,0,@NumRate)
			
		--EXEC GP_AType_Total_AddEdit @GOODS_GIVE_RECNO,@szSTypeID,@syscid,@tmpTotal,@tmpTotal,@strMsg OUTPUT
	END
  RETURN 0
 END

-------------积分兑换单处理结束------

------------------------------ 赠送单--------------------------
 IF @nBillType=139
 BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
	  --库存商品减少
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
			@dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dNormalCostTotalTemp,0,1)
	END
	
	IF @dServiceTotalTemp<>0 OR @dNServiceTotalTemp<>0
	BEGIN
	 --其他收入减少
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	  VALUES(@nBillId,@tBillDate,@nBillType,@OtherGain,'0',@szBtypeid,@szEtypeid,'0',
			@dServiceTotalTemp,@dServiceTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,@dNServiceTotalTemp,0,@NumRate)
	END
	
	IF @dNormalCostTotalTemp+@dServiceTotalTemp<>0
	BEGIN
	 --赠送
	 SELECT @tmpTotal=(@dNormalCostTotalTemp+@dServiceTotalTemp)
	 
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_GIVE_RECNO,'0',@szBtypeid,@szEtypeid,'0',
			-@tmpTotal,-@tmpTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,-@tmpTotal,0,1)
	END
			
  RETURN 0
 END
------------------------------赠送单处理结束--------------------------

------------------------------获赠单--------------------------
 IF @nBillType=126
 BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		 --库存商品增加
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				 @dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dNormalCostTotalTemp,0,1)
	END
	
	IF @dServiceTotalTemp <> 0 OR @dNServiceTotalTemp<>0
	BEGIN
		 --服务类商品其他支出
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@OtherFee,'0',@szBtypeid,@szEtypeid,'0',
				 @dServiceTotalTemp,@dServiceTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,@dNServiceTotalTemp,0,@NumRate)
	END
	
	IF @dNormalCostTotalTemp+@dServiceTotalTemp<>0
	BEGIN
		--获赠单收入 
		SELECT @tmpTotal=@dNormalCostTotalTemp+@dServiceTotalTemp
		 
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_GIVEME_RECNO,'0',@szBtypeid,@szEtypeid,'0',
				 @tmpTotal,@tmpTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@tmpTotal,0,1)
	END
	
	
	
  RETURN 0
 END
------------------------------获赠单处理结束--------------------------

------------------------------报损单--------------------------
 IF @nBillType=9
 BEGIN
	IF @dCostTotaltemp <> 0
	BEGIN
		  --库存商品减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dCostTotaltemp,@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dCostTotaltemp,0,1)
				
			--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
		  --报损
		  SELECT @tmpTotal = -@dCostTotaltemp
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_LOSS_ID,'0',@szBtypeid,@szEtypeid,'0',
				-@dCostTotaltemp,-@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,-@dCostTotaltemp,0,1)
				
		--EXEC GP_AType_Total_AddEdit @GOODS_LOSS_ID,@szSTypeID,@syscid,@tmpTotal,@tmpTotal,@strMsg OUTPUT
	END
  RETURN 0
 END
------------------------------报损单处理结束--------------------------
------------------------------报溢单  获赠单--------------------------
 IF @nBillType=14
 BEGIN
	IF @dCostTotaltemp <> 0
	BEGIN
		  --库存商品增加
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dCostTotaltemp,@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dCostTotaltemp,0,1)
				
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
		  --报溢收入
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_GET_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dCostTotaltemp,@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dCostTotaltemp,0,1)
				
		-- EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
	END

  RETURN 0
 END
 
 DECLARE 
	@chvATypeID	VARCHAR(50)
 
 IF @nBillType=201
 BEGIN
	SELECT @chvATypeID=b.ATypeID1
	FROM Billindex a
	INNER JOIN OtherInOutType b
	ON a.OtherInOutType=b.ID
	WHERE a.BillNumberId=@nBillId
END

IF @nBillType=202
 BEGIN
	SELECT @chvATypeID=b.ATypeID
	FROM Billindex a
	INNER JOIN OtherInOutType b
	ON a.OtherInOutType=b.ID
	WHERE a.BillNumberId=@nBillId
END
 
 IF @nBillType=201
 BEGIN
	--其他入库
	IF @dCostTotaltemp <> 0
	BEGIN
	  --库存商品增加
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
	  total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
	  @dCostTotaltemp,@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dCostTotaltemp,0,1)
	  
	 -- EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
	  --
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
	  total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	  VALUES(@nBillId,@tBillDate,@nBillType,@chvATypeID,'0',@szBtypeid,@szEtypeid,'0',
	  @dCostTotaltemp,@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dCostTotaltemp,0,1)
	  
	 -- EXEC GP_AType_Total_AddEdit @chvATypeID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
	END

  RETURN 0
 END
 
 IF @nBillType=202
 BEGIN
	--其他出库
	IF @dCostTotaltemp <> 0
	BEGIN
	  --库存商品减少
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
			@dCostTotaltemp,@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dCostTotaltemp,0,1)
	  
	   --EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
	  --
	  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	  VALUES(@nBillId,@tBillDate,@nBillType,@chvATypeID,'0',@szBtypeid,@szEtypeid,'0',
			-@dCostTotaltemp,-@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,-@dCostTotaltemp,0,1)
		SELECT @tmpTotal= -@dCostTotaltemp
			
		-- EXEC GP_AType_Total_AddEdit @chvATypeID,@szSTypeID,@syscid,@tmpTotal,@tmpTotal,@strMsg OUTPUT
	END
  RETURN 0
 END
 
------------------------------报溢单处理结束--------------------------
------------------------------调价单--------------------------
 IF @nBillType=57
 BEGIN
	DECLARE
		@intAdPriceBillType		INT
		
	SELECT @intAdPriceBillType=AdPriceType
	FROM Billindex
	WHERE BillNumberId=@nBillId
 
	IF @intAdPriceBillType=0
	BEGIN
		--库存中
		SELECT @dChange=@dCostTotaltemp
		IF @dChange <> 0
		BEGIN
			--库存商品变动
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
					@dChange,@dChange,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dChange,0,1)
					
			--成本调价收入
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@PRICE_INCOME_ID,'0',@szBtypeid,@szEtypeid,'0',
					@dChange,@dChange,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dChange,0,1)	
		END	
	END
	ELSE IF @intAdPriceBillType=1
	BEGIN
		--入库
		
		SELECT @dChange=@dCostTotaltemp
		IF @dChange <> 0
		BEGIN
			--库存商品，借
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
					@dChange,@dChange,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dChange,0,1)
					
			--应付暂估，贷
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@APAppraisal,'0',@szBtypeid,@szEtypeid,'0',
					@dChange,@dChange,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dChange,0,1)	
		END	
	END
	ELSE IF @intAdPriceBillType=2
	BEGIN
		--出库
		
		SELECT @dChange=@dCostTotaltemp
		IF @dChange <> 0
		BEGIN
			--销售成本增加
			INSERT INTO Listtable
			 (BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES
			  (@nBillId,@tBillDate,@nBillType,@SALE_COST_ID,'0',@szBtypeid,@szEtypeid,'0',-@dChange,
			  -@dChange,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,-@dChange,0,1)  
			  


			--库存商品减少
			INSERT INTO Listtable
			(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES
				(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				 @dChange,@dChange,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,@dChange,0,1)
		END		 	
	END
	
	
	RETURN 0
 END
------------------------------调价单处理结束--------------------------

------------------------------同价调拨单--------------------------
 IF @nBillType=17
 BEGIN
	DECLARE @numTJCostTotal  NUMERIC(24, 10) 
	SELECT	@numTJCostTotal = ABS(ISNULL(SUM(CostTotal),0))
	FROM	InOutStockTable
	WHERE	BillNumberID = @nBillID
			AND Qty > 0

	UPDATE BillIndex SET TotalInMoney = @numTJCostTotal,NTotalInMoney=@numTJCostTotal
	WHERE BillNumberID = @nBillID
 END
------------------------------同价调拨单处理结束--------------------------

------------------------------变价调拨单--------------------------
 IF @nBillType=21
 BEGIN
	SELECT @dChange=@dCostTotaltemp

	IF @dChange <> 0
	BEGIN
		--库存商品变动
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dChange,@dChange,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dChange,0,1)
				
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@dChange,@dChange,@strMsg OUTPUT
		--变价调拨差价
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@ALLOT_PRICE_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dChange,@dChange,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dChange,0,1)
				
		--EXEC GP_AType_Total_AddEdit @ALLOT_PRICE_ID,@szSTypeID,@syscid,@dChange,@dChange,@strMsg OUTPUT
	END
  RETURN 0
 END
------------------------------变价调拨单处理结束--------------------------
/*
------------------------------转款单--------------------------
 if @nBillType=77
 begin
 end
------------------------------转款单处理结束--------------------------
*/
------------------------------调帐单--------------------------
 -----应收减少&应付增加
IF (@nBillType=115) OR (@nBillType=128)
BEGIN
	SELECT @dTotalTemp=SUM(ABS(total)),@dNtotaltemp=SUM(ABS(Ntotal)) FROM listtable WHERE billnumberid=@nbillid 
	--调帐亏损
	INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	VALUES(@nBillId,@tBillDate,@nBillType,@ADDEBT_LOSE_ID,'0',@szBtypeid,@szEtypeid,'0',
			@dTotaltemp,0,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@dNtotaltemp,0,@NumRate)
	--EXEC GP_AType_Total_AddEdit @ADDEBT_LOSE_ID,@szSTypeID,@cid,@dTotaltemp,@dNtotaltemp,@strMsg OUTPUT
	
	RETURN 0
END
 -----应收增加&应付减少
IF (@nBillType=116) OR (@nBillType=129)
BEGIN
	SELECT @dTotalTemp=SUM(ABS(total)),@dNtotaltemp=SUM(ABS(Ntotal)) FROM listtable WHERE billnumberid=@nbillid 

	--调帐收入
	INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
			total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
	VALUES(@nBillId,@tBillDate,@nBillType,@ADDEBT_INCOME_ID,'0',@szBtypeid,@szEtypeid,'0',
			@dTotaltemp,0,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@dNtotaltemp,0,@NumRate)
	--EXEC GP_AType_Total_AddEdit @ADDEBT_INCOME_ID,@szSTypeID,@cid,@dTotaltemp,@dNtotaltemp,@strMsg OUTPUT

	RETURN 0
END
------------------------------调帐单处理结束--------------------------
------------------------------拆装单------------------------------
	IF @nBillType = 16
		BEGIN
			SET @dChange = @dCostTotalTemp

			IF @dChange <> 0
				BEGIN
					-- 库存商品总值
					INSERT INTO ListTable (
						BillNumberID,
						BillDate,
						BillType,
						ATypeID,
						PTypeID,
						BTypeID,
						ETypeID,
						KTypeID,
						Total,
						CostTotal,
						JobNumber,
						OutFactoryDate,
						DTypeID,
						STypeID,
						CID,
						Ntotal,
						Audited,
						Rate
					)
					VALUES (

						@nBillID,
						@tBillDate,
						@nBillType,
						@GOODS_ID,
						'0',
						@szBTypeID,
						@szETypeID,
						'0',
						@dChange,
						@dChange,
						@szJobNumber,
						@OutFactoryDate,
						@szDTypeID,
						@szSTypeID,
						@syscid,
						@dChange,
						0,
						1
					)
				--	EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@cid,@dChange,@dChange,@strMsg OUTPUT
					-- 生产拆装差价
					INSERT INTO ListTable (
						BillNumberID,
						BillDate,
						BillType,
						ATypeID,
						PTypeID,
						BTypeID,
						ETypeID,
						KTypeID,
						Total,
						CostTotal,
						JobNumber,
						OutFactoryDate,
						DTypeID,
						STypeID,
						CID,
						Ntotal,
						Audited,
						Rate
					)
					VALUES (
						@nBillID,
						@tBillDate,
						@nBillType,
						@GOODS_PRODUCE_ID,
						'0',
						@szBTypeID,
						@szETypeID,
						'0',
						@dChange,
						@dChange,
						@szJobNumber,
						@OutFactoryDate,
						@szDTypeID,
						@szSTypeID,
						@syscid,
						@dChange,
						0,
						1
					)
				--	EXEC GP_AType_Total_AddEdit @GOODS_PRODUCE_ID,@szSTypeID,@cid,@dChange,@dChange,@strMsg OUTPUT
				END
	END
------------------------------拆装单处理结束--------------------------

------------------------------商品换货单、商品维修受理单------------------------------
IF @nBillType = 155 OR @nBillType = 157
BEGIN
			SET @dChange = @dCostTotalTemp

			IF @dChange <> 0
				BEGIN
					-- 库存商品总值
					INSERT INTO ListTable (
						BillNumberID,
						BillDate,
						BillType,
						ATypeID,
						PTypeID,
						BTypeID,
						ETypeID,
						KTypeID,
						Total,
						CostTotal,
						JobNumber,
						OutFactoryDate,
						DTypeID,
						STypeID,
						CID,
						Ntotal,
						Audited,
						Rate
					)
					VALUES (
						@nBillID,
						@tBillDate,
						@nBillType,
						@GOODS_ID,
						'0',
						@szBTypeID,
						@szETypeID,
						'0',
						@dChange,
						@dChange,
						@szJobNumber,
						@OutFactoryDate,
						@szDTypeID,
						@szSTypeID,
						@syscid,
						@dChange,
						0,
						1
					)
				--	EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@cid,@dChange,@dChange,@strMsg OUTPUT

				END

	SELECT @dTotalTemp=ISNULL(SUM(Total),0),@dCostTotalTemp=ISNULL(SUM(CostTotal),0),@dNtotalTemp= ISNULL(SUM(nTotal),0)
	FROM InOutstocktable 
	WHERE BillNumberId=@nBillId AND atypeid=@GOODS_ID AND ptypeid<>'0' AND Qty < 0

	IF @dCostTotaltemp <> 0
	BEGIN
		SELECT @tmpTotal=-@dCostTotaltemp
		--销售成本增加
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@SALE_COST_ID,'0',@szBtypeid,@szEtypeid,'0',
				-@dCostTotaltemp,-@dCostTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,-@dCostTotaltemp,0,1) 
				
		--EXEC GP_AType_Total_AddEdit @SALE_COST_ID,@szSTypeID,@syscid,@tmpTotal,@tmpTotal,@strMsg OUTPUT 
	END
	--销售收入增加
	IF @dTotaltemp <> 0
	BEGIN
		SELECT @tmpTotal=-@dTotaltemp,@Ntmptotal=-@dnTotaltemp
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@SALE_INCOME_ID,'0',@szBtypeid,@szEtypeid,'0',
				-@dTotaltemp,-@dTotaltemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,-@dnTotaltemp,0,@NumRate)
		
		--EXEC GP_AType_Total_AddEdit @SALE_INCOME_ID,@szSTypeID,@cid,@tmpTotal,@Ntmptotal,@strMsg OUTPUT 
	END
	
	-- 商品维修收入增加
	DECLARE @intWSFY  NUMERIC(24, 10) 
	SELECT @intWSFY = MoneyRepair FROM RepairDeal WHERE billnumberid = @nbillid
	IF @intWSFY <> 0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		VALUES(@nBillId,@tBillDate,@nBillType,@REPAIR_INCOME_ID,'0',@szBtypeid,@szEtypeid,'0',
				@intWSFY,@intWSFY,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@intWSFY,0,1)
				
		--EXEC GP_AType_Total_AddEdit @REPAIR_INCOME_ID,@szSTypeID,@syscid,@intWSFY,@intWSFY,@strMsg OUTPUT 
	END
	RETURN 0
END
------------------------------商品换货单处理结束--------------------------

--------------------------------钱流单处理开始--------------------------
--	--78 固定资产折旧--5  待摊费用发生--10 待摊费用摊销
IF @nBilltype IN (78,5,10)
	BEGIN
		SELECT @dTotalTemp=ABS(SUM(total)),@dnTotalTemp=ABS(SUM(Ntotal)) FROM listtable WHERE billnumberid=@nbillid 
		--固定资产折旧
		IF @nBillType=78
		BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@DEPRECIATION_ID,'0',@szBtypeid,@szEtypeid,'0',
					@dTotaltemp,0,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@dnTotalTemp,0,@NumRate)
			IF @@rowcount=0 GOTO ERROR
			--EXEC GP_AType_Total_AddEdit @DEPRECIATION_ID,@szSTypeID,@cid,@dTotaltemp,@dnTotalTemp,@strMsg OUTPUT 
		END
		--待摊费用增加
		IF @nBillType=5
		BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@APPORTION_EXPENSE_ID,'0',@szBtypeid,@szEtypeid,'0',
					@dTotaltemp,0,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@dnTotalTemp,0,@NumRate)
			IF @@rowcount=0 GOTO ERROR
			--EXEC GP_AType_Total_AddEdit @APPORTION_EXPENSE_ID,@szSTypeID,@cid,@dTotaltemp,@dnTotalTemp,@strMsg OUTPUT 
		END
		--待摊费用减少
		IF @nBillType=10
		BEGIN
			INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			VALUES(@nBillId,@tBillDate,@nBillType,@APPORTION_EXPENSE_ID,'0',@szBtypeid,@szEtypeid,'0',
					-@dTotaltemp,0,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,-@dnTotalTemp,0,@NumRate)
			IF @@rowcount=0 GOTO ERROR
		--	EXEC GP_AType_Total_AddEdit @APPORTION_EXPENSE_ID,@szSTypeID,@cid,@dTotaltemp,@dnTotalTemp,@strMsg OUTPUT
		END
		RETURN 0
	END 
--------------------------------钱流单处理结束--------------------------

/* 受托代销退货单 - START */
IF @nBillType = 146
BEGIN
	SELECT	@dCostTotalTemp = ABS(ISNULL(SUM(CostTotal),0))
	FROM	InOutStockTable
	WHERE	BillNumberID = @nBillID
			AND ATypeID = @GOODS_ID
			AND KTypeID <> '10000'
			AND PTypeID <> '0'

	SELECT	@dTotalTemp = ABS(ISNULL(SUM(Total),0)),@dnTotalTemp= ABS(ISNULL(SUM(nTotal),0))
	FROM	ListTable
	WHERE	BillNumberID = @nBillID
			AND ATypeID = @DXGOODSMONEY_ID

	DECLARE @intReturnCode INT,@numSTTHBanlance  NUMERIC(24, 10) ,@numGoodsTotal  NUMERIC(24, 10) 
	IF @dCostTotalTemp <> 0
	BEGIN
		-- 库存商品总值
		SET @numGoodsTotal = -@dCostTotalTemp
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@GOODS_ID,@szBTypeID,@szETypeID,
			@numGoodsTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@numGoodsTotal,1
		IF @intReturnCode <> 0 GOTO ERROR
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@numGoodsTotal,@numGoodsTotal,@strMsg OUTPUT
	END
	-- 受托退货差价
	SET @numSTTHBanlance = @dTotalTemp-@dCostTotalTemp
	IF @numSTTHBanlance <> 0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@STTH_BANLANCE_ID,@szBTypeID,@szETypeID,
			@numSTTHBanlance,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@numSTTHBanlance,1
		IF @intReturnCode <> 0 GOTO ERROR
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@numSTTHBanlance,@numSTTHBanlance,@strMsg OUTPUT
	END

	RETURN 0
END
/* 受托代销退货单 - END */

/* 委托代销发货 140 - Start */
IF @nBillType = 140
BEGIN
	SELECT	@dCostTotalTemp = ABS(ISNULL(SUM(CostTotal),0))
	FROM	InOutStockTable
	WHERE	BillNumberID = @nBillID
			AND ATypeID = @GOODS_ID
			AND KTypeID <> '10000'
			AND PTypeID <> '0'

	IF @dCostTotalTemp <> 0
	BEGIN
		-- 更新“库存商品总值”科目的值
		UPDATE	ListTable
		SET		Total = -@dCostTotalTemp,Ntotal= -@dCostTotalTemp
		WHERE	ATypeID = @GOODS_ID
				AND BillNumberID = @nBillID
				AND BillType=@nBillType
			
		SELECT @tmptotal = 	-@dCostTotalTemp
		
		
		-- 更新“委托商品代销商品”科目的值
		UPDATE	ListTable
		SET		Total = @dCostTotalTemp,Ntotal=@dCostTotalTemp
		WHERE	ATypeID = @WtDxGoods_ID
				AND BillNumberID = @nBillID
				AND BillType=@nBillType
				
		
	END
	ELSE
	BEGIN
		DELETE FROM ListTable
		WHERE	BillNumberID = @nBillID
				AND (ATypeID = @GOODS_ID OR ATypeID = @WtDxGoods_ID)
	END
END
/* 委托代销发货 140 - End */

/* 委托代销结算 141 - Start */
IF @nBillType = 141
BEGIN
	SELECT	@dCostTotalTemp = ISNULL(SUM(CostTotal),0)
	FROM	InOutStockTable
	WHERE	BillNumberID = @nBillID
			AND ATypeID = @GOODS_ID
			AND KTypeID = '10000'
			AND PTypeID <> '0'

	IF @dCostTotalTemp <> 0
	BEGIN
		-- 更新“销售成本”科目的值
		UPDATE	ListTable
		SET		Total = -@dCostTotalTemp,Ntotal=-@dCostTotalTemp
		WHERE	ATypeID = @SALE_COST_ID
				AND BillNumberID = @nBillID
				AND BillType=@nBillType
				
		SELECT @tmptotal = 	-@dCostTotalTemp
		
		
		-- 更新“委托商品代销商品”科目的值
		UPDATE	ListTable
		SET		Total = @dCostTotalTemp,Ntotal=@dCostTotalTemp
		WHERE	ATypeID = @WtDxGoods_ID
				AND BillNumberID = @nBillID
				AND BillType=@nBillType
		
	END
	ELSE
	BEGIN
		DELETE FROM ListTable
		WHERE	BillNumberID = @nBillID
				AND (ATypeID = @SALE_COST_ID OR ATypeID = @WtDxGoods_ID)
	END
END
/* 委托代销结算 141 - End */

/* 委托代销退货 142 - Start */
IF @nBillType = 142
BEGIN
	SELECT	@dCostTotalTemp = ISNULL(SUM(CostTotal),0)
	FROM	InOutStockTable
	WHERE	BillNumberID = @nBillID
			AND ATypeID = @GOODS_ID
			AND KTypeID <> '10000'
			AND PTypeID <> '0'

	IF @dCostTotalTemp <> 0
	BEGIN
		-- 更新“库存商品总值”科目的值
		UPDATE	ListTable
		SET		Total = @dCostTotalTemp,Ntotal=@dCostTotalTemp
		WHERE	ATypeID = @GOODS_ID
				AND BillNumberID = @nBillID
				AND BillType=@nBillType		
		
	
		-- 更新“委托商品代销商品”科目的值
		UPDATE	ListTable
		SET		Total = -@dCostTotalTemp,Ntotal=-@dCostTotalTemp
		WHERE	ATypeID = @WtDxGoods_ID
				AND BillNumberID = @nBillID
				AND BillType=@nBillType
				
		SELECT @tmptotal = 	-@dCostTotalTemp
		
	END
	ELSE
	BEGIN
		DELETE FROM ListTable
		WHERE	BillNumberID = @nBillID
				AND (ATypeID = @GOODS_ID OR ATypeID = @WtDxGoods_ID)
	END
END
/* 委托代销退货 142 - End */

/* 销售换货单 160 - Start */
IF @nBillType = 160
BEGIN
	DECLARE @numSaleCostTotal  NUMERIC(24, 10) ,@numSaleInComeTotal  NUMERIC(24, 10) 
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		-- 销售成本增加
		SET @numSaleCostTotal = -@dNormalCostTotalTemp
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@SALE_COST_ID,@szBTypeID,@szETypeID,
			@numSaleCostTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@numSaleCostTotal,1
		IF @intReturnCode <> 0 GOTO ERROR
		
		-- 库存商品减少
		SET @numGoodsTotal = @dNormalCostTotalTemp
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@GOODS_ID,@szBTypeID,@szETypeID,
			@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dNormalCostTotalTemp,1
		IF @intReturnCode <> 0 GOTO ERROR
		
	END

	IF @dNormalTotalTemp <> 0 OR @dNNormalTotalTemp<>0
	BEGIN
		-- 销售收入增加
		SELECT @numSaleInComeTotal = -@dNormalTotalTemp,@Ntmptotal=-@dNNormalTotalTemp
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@SALE_INCOME_ID,@szBTypeID,@szETypeID,
			@numSaleInComeTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,@Ntmptotal,@NumRate
		IF @intReturnCode <> 0 GOTO ERROR
		
	END
	
	
	IF @dServiceTotalTemp <> 0 OR @dNServiceTotalTemp<>0
	BEGIN
		-- 其他收入增加
		SELECT @tmptotal=-@dServiceTotalTemp,@Ntmptotal=-@dNServiceTotalTemp
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@OtherGain,@szBTypeID,@szETypeID,
			@tmptotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,@Ntmptotal,@NumRate
		IF @intReturnCode <> 0 GOTO ERROR
		
	END

	RETURN 0
END
/* 销售换货单 160 - End */

/* 采购换货单 161 - Start */
IF @nBillType = 161
BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		-- 库存商品
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@GOODS_ID,@szBTypeID,@szETypeID,
			@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dNormalCostTotalTemp,1
		IF @intReturnCode <> 0 GOTO ERROR
		
	END
	
	IF @dServiceTotalTemp<>0 OR @dNServiceTotalTemp<>0
	BEGIN
		-- 其他支出
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@OtherFee,@szBTypeID,@szETypeID,
			@dServiceTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@CID,@dNServiceTotalTemp,@NumRate
		IF @intReturnCode <> 0 GOTO ERROR
	END

	IF @dNormalCostTotalTemp+@dServiceTotalTemp - @dTotaltemp <> 0
	BEGIN
		DECLARE @numBuyBackPriceDifference  NUMERIC(24, 10) 
		SET @numBuyBackPriceDifference = @dServiceTotalTemp+@dCostTotalTemp - @dTotaltemp
		-- 采购退货差价增加
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@BALANCE_ID,@szBTypeID,@szETypeID,
			@numBuyBackPriceDifference,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@numBuyBackPriceDifference,1
		IF @intReturnCode <> 0 GOTO ERROR
		
	END

	RETURN 0
END
/* 采购换货单 161 - End */

-- 新维修 - 自行维修单 166、整机更换单 168、维修品调入单 173、维修品调出单 174
IF @nBillType IN (166,168,172,173,174)
BEGIN
	IF @dCostTotalTemp <> 0
	BEGIN
		DECLARE @TotalTemp  NUMERIC(24, 10) 
		-- 库存商品减少 - 贷方
		SET @TotalTemp = @dCostTotaltemp
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@GOODS_ID,@szBTypeID,@szETypeID,
			@TotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@TotalTemp,1
		IF @intReturnCode <> 0 GOTO ERROR
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@TotalTemp,@TotalTemp,@strMsg OUTPUT
		
		-- 商品维修支出增加 - 借方
		SET @TotalTemp = -@dCostTotaltemp
		EXEC @intReturnCode = GP_CreateMX_InsertList @nBillID,@tBillDate,@nBillType,@WX_PTYPE_EXPENSE,@szBTypeID,@szETypeID,
			@TotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@TotalTemp,1
		IF @intReturnCode <> 0 GOTO ERROR
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@TotalTemp,@TotalTemp,@strMsg OUTPUT
	END

	RETURN 0
END


------------------------------零售退货单------------------------------
 IF @nBillType=215 
 BEGIN
	IF @dNormalCostTotalTemp <> 0
	BEGIN
		--销售成本减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@SALE_COST_ID,'0',@szBtypeid,@szEtypeid,'0',
				-@dNormalCostTotalTemp,-@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,-@dNormalCostTotalTemp,0,1)
				
		SELECT @tmpTotal=-@dNormalCostTotalTemp
		--EXEC GP_AType_Total_AddEdit @SALE_COST_ID,@szSTypeID,@syscid,@tmpTotal,@tmpTotal,@strMsg OUTPUT
		
		  --库存商品增加
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@GOODS_ID,'0',@szBtypeid,@szEtypeid,'0',
				@dNormalCostTotalTemp,@dNormalCostTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@syscid,@dNormalCostTotalTemp,0,1)
				
		--EXEC GP_AType_Total_AddEdit @GOODS_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
	END

	IF @dNormalTotalTemp <> 0 OR @dNNormalTotalTemp<>0
	BEGIN
		  SELECT @NtmpTotal = -@dNNormalTotalTemp,@tmpTotal=-@dNormalTotalTemp
		  --销售收入减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@SALE_INCOME_ID,'0',@szBtypeid,@szEtypeid,'0',
				-@dNormalTotalTemp,-@dNormalTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@NtmpTotal,0,@NumRate)
				
		--EXEC GP_AType_Total_AddEdit @SALE_INCOME_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
	END

	IF @dServiceTotalTemp <> 0 OR @dNServiceTotalTemp<>0
	BEGIN
		  SELECT @NtmpTotal = -@dNServiceTotalTemp,@tmpTotal=-@dServiceTotalTemp
		  --销售收入减少
		  INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
		  VALUES(@nBillId,@tBillDate,@nBillType,@OtherGain,'0',@szBtypeid,@szEtypeid,'0',
				-@dServiceTotalTemp,-@dServiceTotalTemp,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@NtmpTotal,0,@NumRate)
				
		--EXEC GP_AType_Total_AddEdit @SALE_INCOME_ID,@szSTypeID,@syscid,@dCostTotaltemp,@dCostTotaltemp,@strMsg OUTPUT
	END

  RETURN 0
 END
------------------------------销售退货单处理结束--------------------------


DECLARE
	@NDiscountTotal	 NUMERIC(24, 10) ,@DiscountTotal  NUMERIC(24, 10) ,@NTaxTotal  NUMERIC(24, 10) ,@TaxTotal  NUMERIC(24, 10) ,
	@NTaxMoney  NUMERIC(24, 10) ,@TaxMoney  NUMERIC(24, 10) ,@InvoiceCostTotal  NUMERIC(24, 10) 
	


IF @nBillType=404		--采购暂估开票
BEGIN
	SELECT @NDiscountTotal=SUM(NTotal),@DiscountTotal=SUM(Total),@NTaxTotal=SUM(NTaxTotal),@TaxTotal=SUM(TaxTotal),@NTaxMoney=SUM(NTaxMoney),@TaxMoney=SUM(Taxmoney)
	FROM ReceiptBill
	WHERE BillNumberID=@nBillId
	

	
	--应付暂估,借
	IF @NDiscountTotal<>0 OR @DiscountTotal<>0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			  VALUES(@nBillId,@tBillDate,@nBillType,@APAppraisal,'0',@szBtypeid,@szEtypeid,'0',
					-@DiscountTotal,-@DiscountTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,-@NDiscountTotal,0,@NumRate)
	END		
		
	
	--应交税金,借
	IF @NTaxMoney<>0 OR @TaxMoney<>0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			  VALUES(@nBillId,@tBillDate,@nBillType,@PAY_TAXMONEY_ID,'0',@szBtypeid,@szEtypeid,'0',
					-@TaxMoney,-@TaxMoney,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,-@NTaxMoney,0,@NumRate)
	END
	
	--应付合计,贷
	IF @NTaxTotal<>0 OR @TaxTotal<>0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			  VALUES(@nBillId,@tBillDate,@nBillType,@AP,'0',@szBtypeid,@szEtypeid,'0',
					@TaxTotal,@TaxTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@NTaxTotal,0,@NumRate)
	END
	
	RETURN 0
END



IF @nBillType=405		--销售发货开票
BEGIN
	SELECT @NDiscountTotal=SUM(NTotal),@DiscountTotal=SUM(Total),@NTaxTotal=SUM(NTaxTotal),@TaxTotal=SUM(TaxTotal),@NTaxMoney=SUM(NTaxMoney),@TaxMoney=SUM(Taxmoney),
	@InvoiceCostTotal=SUM(InvoiceCostTotal)
	FROM ReceiptBill
	WHERE BillNumberID=@nBillId
	

	--应收合计	借
	IF @NTaxTotal<>0 OR @TaxTotal<>0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			  VALUES(@nBillId,@tBillDate,@nBillType,@AR,'0',@szBtypeid,@szEtypeid,'0',
					@TaxTotal,@TaxTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@NTaxTotal,0,@NumRate)
	END
	--销售收入	贷
	IF @NDiscountTotal<>0 OR @DiscountTotal<>0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			  VALUES(@nBillId,@tBillDate,@nBillType,@SALE_INCOME_ID,'0',@szBtypeid,@szEtypeid,'0',
					@DiscountTotal,@DiscountTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@NDiscountTotal,0,@NumRate)
	END
	
	
	--应交税金	贷
	IF @NTaxMoney<>0 OR @TaxMoney<>0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			  VALUES(@nBillId,@tBillDate,@nBillType,@PAY_TAXMONEY_ID,'0',@szBtypeid,@szEtypeid,'0',
					@TaxMoney,@TaxMoney,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@cid,@NTaxMoney,0,@NumRate)
	END
	
	--销售成本	借
	IF @InvoiceCostTotal<>0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			  VALUES(@nBillId,@tBillDate,@nBillType,@SALE_COST_ID,'0',@szBtypeid,@szEtypeid,'0',
					@InvoiceCostTotal,@InvoiceCostTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,@InvoiceCostTotal,0,@NumRate)
	END
	
	
	--发出商品	贷
	IF @InvoiceCostTotal<>0
	BEGIN
		INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
					 total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
			  VALUES(@nBillId,@tBillDate,@nBillType,@SendOut,'0',@szBtypeid,@szEtypeid,'0',
					-@InvoiceCostTotal,@InvoiceCostTotal,@szJobNumber,@OutFactoryDate,@szDTypeID,@szSTypeID,@SysCid,-@InvoiceCostTotal,0,@NumRate)
	END
	
	RETURN 0
END



	RETURN 0
error:
	RETURN -1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillId [numeric](10, 0),
    @nBillType	INT,
    @strMsg		VARCHAR(500)
    
SELECT
	@nBillId=1,
    @nBillType=400  

BEGIN TRAN

EXEC Gp_CreateQtMx
    @nBillId,
    @nBillType,
    @strMsg


SELECT @strMsg

SELECT * FROM LISTTABLE WHERE BILLNUMBERID=@nBillId AND BILLTYPE=400

ROLLBACK TRAN 

*/



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_CreateTypeId]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC[dbo].[Gp_CreateTypeId]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC Gp_CreateTypeId
( 
	@ParId 		VARCHAR(50),	--父节点
	@nSoncount	INT,			--父节点的子级个数
	@CreatedId 	VARCHAR(50) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE 
	@I		INT=1,
	@J		INT=5-LEN(@nSoncount),
	@TypeID	VARCHAR(5)=''
	
WHILE(@I<=@J)
	BEGIN
		SET @TypeID+='0'
		SET @I+=1
	END
SET @CreatedId=@ParId+@TypeID+CAST(@nSoncount AS VARCHAR(5))

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.06。28
	描述：固定资产单据212，213生成凭证
*/
CREATE PROCEDURE Gp_CreateVoucher_AssetIncDecBill
(
	@Id				VARCHAR(MAX),			-- 单据编号
	@BillType		INT = 0,				-- 单据类型 212.增加单 213.减少单 214.折旧单
	@AtId			INT = 0,				-- 模板Id，0代表取单据默认模板
	@BillDate		DATE = '',				-- 凭证日期
	@Fyear			INT,					-- 年度
	@Fperiod		INT,					-- 期间
	@ETypeid		VARCHAR(50),			-- 职员
	@CreateType		INT = 0,				-- 0.Auto 1.Hand
	@szPID			VARCHAR(1000) OUTPUT,	-- 返回出错信息
	@VoucherID		INT,				-- 凭证ID 用于凭证标错使用
	@Type			INT	= 0,				-- 生成凭证结果处理方式
	@JustRep		INT = 0,					-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON


SET @szPID = ''

--因为后面多次使用到SELECT a FROM dbo.f_split(@Id,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@Id,',')

--将模板明细处理到临时表中,进行读取字段生成摘要
-----------------------------------------------
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''

SELECT @MinNumber = MIN(a) FROM #BillNumberId
SELECT @MaxNumber = MAX(a) FROM #BillNumberId

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	RowNo		INT IDENTITY(1,1),
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)



WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		--SET @Index += 1
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr

	IF @str <> ''
		SET @str += ';'
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	--SET @MinDid += 1
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END


-----------------------
--处理摘要完成

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID1		VARCHAR(50),
	Cid				INT,				--币种
	RedWord			INT,
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT					--汇率计算方式
)

INSERT INTO #TmpBillInfo
        ( BillNumberId ,
          StypeId ,
          VerifyStypeid ,
          DTypeId ,
          BTypeId ,
          ETypeId,
          DealBTypeId ,
          ATypeID1,
          Cid ,
          RedWord,
          Rate ,
          RateType
        )
SELECT  T1.BillNumberId,
		T1.Stypeid,
		T2.VerifyID,
		T1.DTypeId,
		T1.btypeid,
		T1.etypeid,
		T1.DealBTypeID,
		T1.ATypeID1,
		T1.CID,
		T1.RedWord,
		T1.Rate,
		T3.BasisType
FROM dbo.BillIndex T1
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
WHERE T1.BillNumberId IN (SELECT a FROM #BillNumberId)

DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1


CREATE TABLE #tmpBillMulAccount
(
	Atypeid		VARCHAR(50),
	Usercode	VARCHAR(200),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Cid			INT,
	Atid		INT,
	Total		 NUMERIC(24, 10) ,
	Totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT,
	BillMoneyId		INT
)

CREATE TABLE #tmpBillIndexAtypeid
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atid		INT,
	total		 NUMERIC(24, 10) ,
	totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)


INSERT INTO #tmpBillIndexAtypeid
		SELECT	c.ATypeID,
					b.UserCode,
					b.FullName,
					NULL,
					NULL,
					@atid AS atid,
					CASE WHEN BB.RedWord = 2 THEN -a.Total ELSE a.Total END AS total,
					CASE WHEN BB.RedWord = 2 THEN -a.NTotalMoney ELSE a.NTotalMoney END AS totalfor,
					BB.BillNumberId  --e.BillNumberId
		FROM	#TmpBillInfo BB
		INNER JOIN dbo.BillMulAccount a ON a.BillNumberId = BB.BillNumberId AND A.BillType=@BillType
		INNER JOIN dbo.Ac_Items b ON a.ATypeID = b.nId
		INNER JOIN dbo.Ac_Items_Detail c ON b.nId = c.nId AND c.StypeId = BB.StypeId


INSERT INTO #tmpBillMulAccount
	SELECT ATypeId,b.UserCode,b.FullName,b.Fdc,b.cid,atid,SUM(Total) AS total,SUM(totalfor) as totalfor,a.billnumberid,(SELECT BillMoneyId FROM #TmpVoucherDetails WHERE Express='totalinmoney')
	FROM #tmpBillIndexAtypeid a
		LEFT JOIN Ac_Account b ON a.atypeid = b.typeid and b.stypeid = @verifyid
	GROUP BY atypeid,b.usercode,b.fullname,b.fdc,b.cid,atid,a.billnumberid



CREATE TABLE #tmpBillMoney_Bill
(
	ac_balanceB 		 NUMERIC(24, 10) 	DEFAULT 0, --累计折旧额 ac_balanceB
	TaxTotal			 NUMERIC(24, 10) 	DEFAULT 0,--价税合计
	Total				 NUMERIC(24, 10) 	DEFAULT 0,--金额
	TotalInMoney		 NUMERIC(24, 10) 	DEFAULT 0, --实收\实付金额
	balancemoney		 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	cardtotal			 NUMERIC(24, 10) 	DEFAULT 0, --固定资产原值
	devalueready		 NUMERIC(24, 10) 	DEFAULT 0,--固定资产减值准备
	CardId				INT
	,billnumberid		INT
)

DECLARE @MinCarId	INT--为了防止世界被破坏。其实是为了防止billindex上取的金额翻倍，只将billindex上取的金额，如“收付款”更新到第一行


--科目来源AcFrom
--1 手工选择
--2 单据上收付款项目对应科目
--3 单据上往来科目
--5 固定资产
--9 累计折旧
--10 折旧分配
--11 固定资产减值准备科目
CREATE TABLE #tmpExpress
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) 
	,billnumberid	INT
)

CREATE TABLE #tmpExpress_Bill
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) ,
	CardId		INT,
	express		VARCHAR(1000)
	,billnumberid	INT
)


DECLARE @Sql	VARCHAR(MAX)	-- 动态SQL


--取固定资产卡片相应科目
--如果是单据，同时取出单据收付款、往来科目
CREATE TABLE #TmpAssetTypeid
(
	ATypeId		VARCHAR(50),
	Usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	Fdc			INT,
	Cid			INT,
	AtId		INT,
	AcFrom		INT,--科目来源
	CardId		INT,--卡片ID
	Item		VARCHAR(100)
	,billnumberid	INT
)

--生成凭证明细数据
CREATE TABLE #tmpBill
(
		acfrom			INT,
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rowno			INT		IDENTITY(1,1),
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		billindexid		INT,
		cardid			INT
)

	
	SELECT TOP 1 @Verifyid = verifyStypeid
	FROM #TmpBillInfo
	
	--取金额
	INSERT INTO #tmpBillMoney_Bill
			( ac_balanceB ,
			  TaxTotal ,
			  Total ,
			  cardtotal,
			  devalueready,
			  CardId
			  ,billnumberid
			)
	SELECT	CASE WHEN T3.RedWord = 2 THEN -SUM(T2.DepTotal) ELSE SUM(T2.DepTotal) END AS ac_balanceB,--累计折旧
			CASE WHEN T3.RedWord = 2 THEN -SUM(T1.TaxTotal) ELSE SUM(T1.TaxTotal) END AS TaxTotal,--价税合计
			CASE WHEN T3.RedWord = 2 THEN -SUM(T1.Total) ELSE SUM(T1.Total) END AS Total,--金额
			CASE WHEN T3.RedWord = 2 THEN -SUM(T2.Total) ELSE SUM(T2.Total) END,--原值
			CASE WHEN T3.RedWord = 2 THEN -SUM(T2.DevalueReady) ELSE SUM(T2.DevalueReady) END,--减值准备
			T2.Id
			,T1.BillNumberId
	FROM AssetIncDecBill T1
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = T1.BillNumberId
		INNER JOIN dbo.Ac_AssetsCards T2 ON T1.AssetCardId = T2.Id
		INNER JOIN dbo.BillIndex T3 ON T1.BillNumberId = T3.BillNumberId
	--WHERE T1.BillNumberId = @CurrentID
	GROUP BY T1.BillNumberId, T2.Id,T3.RedWord
	
	--SELECT @MinCarId = MIN(CardId) FROM #tmpBillMoney_Bill
	
	UPDATE #tmpBillMoney_Bill SET TotalInMoney= (CASE WHEN T1.RedWord = 2 THEN -T1.totalinmoney ELSE T1.totalinmoney END) 
	FROM dbo.BillIndex T1 
	INNER JOIN ( SELECT BillNumberId,MIN(CARDID) AS MINCARDID
				 FROM #tmpBillMoney_Bill
				 GROUP BY billnumberid
				 ) T2 ON T2.billnumberid = T1.BillNumberId
	WHERE #tmpBillMoney_Bill.CardId = T2.MINCARDID


	
	SET @Sql = 'INSERT INTO #tmpExpress_Bill '
	
	SELECT @Sql += ' SELECT '+CAST(AtdId AS VARCHAR(50)) + ' AS AtdId,'
						+'SUM('+Express+') AS lendloan,'
						+'MAX(CardId),'''+cast(express AS varchar(1000))+''' as express
						,billnumberid '
				   +' FROM #tmpBillMoney_Bill GROUP BY billnumberid'
				   +' UNION ALL '
	FROM dbo.Ac_Auditing_Template_Detail
	WHERE Atid = @Atid
	
	IF LEN(@Sql) > LEN('INSERT INTO #tmpExpress_Bill ')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
		EXEC(@sql)
	END

	
	--只保留一条平衡数记录
	DELETE FROM #tmpExpress_Bill WHERE express = 'balancemoney' AND CardId > ( SELECT MIN(CardId) FROM #tmpExpress_Bill WHERE express = 'balancemoney')
	
	SET @sql = 'SELECT  T1.BillNumberId,  
						T1.AssetCardId,
						T2.TypeId AS StypeId,
						T2.VerifyID,
						T1_1.AssertATypeId,
						T1_1.DepATypeId,
						T1_1.DisATypeId,
						T1_1.DevalueATypeId,
						T1_1.Id
				INTO #TmpTable
				FROM AssetIncDecBill T1
				INNER JOIN #TmpBillInfo BB ON BB.billnumberid = T1.billnumberid
					INNER JOIN dbo.Ac_AssetsCards T1_1 ON T1.AssetCardId = T1_1.Id
					INNER JOIN dbo.SType T2 ON T1_1.Stypeid = T2.TypeId 
					'
	

		
	SET @sql +=
		'INSERT INTO #TmpAssetTypeid
		SELECT	T3.TypeId,
				T3.UserCode,
				T3.FullName,
				T3.Fdc,
				T3.cid,'+
				CAST(@Atid AS VARCHAR(10)) +' AS atid,
				5,
				T1.id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
				,t1.billnumberid
		FROM #TmpTable T1
		INNER JOIN dbo.Ac_Account T3 ON T1.AssertATypeId = T3.TypeId AND T1.VerifyID = T3.StypeId	--5
		WHERE T1.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+'''
		GROUP BY T3.TypeId,T3.UserCode,T3.FullName,T3.Fdc,T3.Cid,T1.Id,t1.billnumberid
		'
		+
		'
		UNION ALL

		SELECT	T3.TypeId,
				T3.UserCode,
				T3.FullName,
				T3.Fdc,
				T3.cid,'+
				CAST(@Atid AS VARCHAR(10)) +' AS atid,
				9,
				T1.id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
				,t1.billnumberid
		FROM #TmpTable T1
		INNER JOIN dbo.Ac_Account T3 ON T1.DepATypeId = T3.TypeId AND T1.VerifyID = T3.StypeId		--9
		WHERE T1.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+'''
		GROUP BY T3.TypeId,T3.UserCode,T3.FullName,T3.Fdc,T3.Cid,T1.Id,t1.billnumberid
		'
		+
		'
		UNION ALL

		SELECT	T3.TypeId,
				T3.UserCode,
				T3.FullName,
				T3.Fdc,
				T3.cid,'+
				CAST(@Atid AS VARCHAR(10)) +'AS atid,
				10,
				T1.id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
				,t1.billnumberid
		FROM #TmpTable T1
		INNER JOIN dbo.Ac_Account T3 ON T1.DisATypeId = T3.TypeId AND T1.VerifyID = T3.StypeId		--10
		WHERE T1.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+'''
		GROUP BY T3.TypeId,T3.UserCode,T3.FullName,T3.Fdc,T3.Cid,T1.Id,t1.billnumberid
		'
		+
		'
		UNION ALL

		SELECT	T3.TypeId,
				T3.UserCode,
				T3.FullName,
				T3.Fdc,
				T3.cid,'+
				CAST(@Atid AS VARCHAR(10)) +'AS atid,
				11,
				T1.id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
				,t1.billnumberid
		FROM #TmpTable T1
		INNER JOIN dbo.Ac_Account T3 ON T1.DevalueATypeId = T3.TypeId AND T1.VerifyID = T3.StypeId	--11
		WHERE T1.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+'''
		GROUP BY T3.TypeId,T3.UserCode,T3.FullName,T3.Fdc,T3.Cid,T1.Id,t1.billnumberid
		'

		+
		'
		UNION ALL
		SELECT	T4.TypeId,
				T4.UserCode,
				T4.FullName,
				T4.Fdc,
				T4.Cid,
				'+CAST(@atid AS VARCHAR(10))+',
				2,
				T5.Id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T4.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T4.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T4.TypeId))) AS Item
				,t5.billnumberid
		FROM	dbo.BillMulAccount T1
			INNER JOIN #TmpTable T5 ON T1.BillNumberId = T5.BillNumberId AND T1.BillType='+CAST(@BillType AS VARCHAR(50))+'
			INNER JOIN dbo.Ac_Items T2 ON T1.ATypeID = T2.nId
			INNER JOIN dbo.Ac_Items_Detail T3 ON T2.nId = T3.nId AND T3.StypeId = t5.stypeid
			INNER JOIN dbo.Ac_Account T4 ON T3.ATypeId = T4.typeId AND T4.StypeId = '''+ CAST(@Verifyid AS VARCHAR(50))+'''
			GROUP BY T4.TypeId,T4.UserCode,T4.FullName,T4.Fdc,T4.Cid,T5.Id,t5.billnumberid
			 '
		+'

		UNION ALL
		SELECT	T2.TypeId,
				T2.UserCode,
				T2.FullName,
				T2.Fdc,
				T2.cid,
				'+CAST(@Atid AS VARCHAR(10)) + ' AS atid,
				3,
				T5.Id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T2.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T2.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T2.TypeId))) AS Item
				,t5.billnumberid
			FROM dbo.BillIndex T1
			INNER JOIN dbo.Ac_Account T2 ON T1.ATypeID1 = T2.TypeId 
			INNER JOIN #TmpTable T5 ON T1.BillNumberId = T5.BillNumberId AND T1.Stypeid = T5.STypeId AND T5.VerifyID = T2.StypeId
			WHERE T5.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50)) + '''
			GROUP BY T2.TypeId,T2.UserCode,T2.FullName,T2.Fdc,T2.Cid,T5.Id,t5.billnumberid
			'
			
	SET @sql +=' DROP TABLE #TmpTable '
	EXEC(@sql)
	
	INSERT INTO #tmpBill
	( 
		acfrom,
		billnumberid ,
		explain ,
		atypeid ,
		atypeid2 ,
		Fdc ,
		f_exchid ,
		f_exchidfor ,
		lendprice ,
		loanprice ,
		lendpricefor ,
		loanpricefor ,
		FCashFlowItem ,
		ascids ,
		FSettleNo ,
		FSettleTypeID ,
		comment ,
		cid ,
		rate ,
		fadc ,
		stypeid ,
		fyear ,
		fperiod,
		atdid,
		billindexid,
		cardid
	)

	SELECT  T1.acfrom,
			@VoucherId AS billnumberid,
			Summary AS explain,
			CASE T1.AcFrom 
				WHEN 1 THEN	T1.ATypeId 
				ELSE T3.ATypeId
			END AS atypeid,
			'' AS atypeid2,
			CASE T1.AcFrom 
				WHEN 1 THEN T4.Fdc
				ELSE T3.Fdc
			END AS Fdc,
			@f_exchid AS f_exchid,
			@f_exchid AS f_exchidfor,
			CASE T1.Fdc 
				WHEN 1 THEN CASE WHEN T1.AcFrom=2 then isnull(c.total,0) else T2.lendloan end
				ELSE 0 
			END AS lendprice,
			CASE T1.Fdc 
				WHEN -1 THEN CASE WHEN T1.AcFrom=2 then isnull(c.total,0) else T2.lendloan end
				ELSE 0 
			END AS loanprice,
			CASE T1.Fdc 
				WHEN 1 THEN CASE WHEN T1.AcFrom=2 then isnull(c.total,0) else T2.lendloan end
				ELSE 0 
			END AS lendpricefor,
			CASE T1.Fdc 
				WHEN -1 THEN CASE WHEN T1.AcFrom=2 then isnull(c.total,0) else T2.lendloan end
				ELSE 0 
			END AS loanpricefor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			NULL AS FSettleTypeID,
			'' AS comment,
			@f_exchid AS cid,
			1 AS Rate,
			T1.Fdc AS fadc,
			@Verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			T1.AtdId,
			T2.billnumberid,
			T2.cardid
	FROM #TmpVoucherDetails T1
	LEFT JOIN #tmpExpress_Bill T2 ON T1.AtdId = T2.atdit
	LEFT JOIN #TmpAssetTypeid T3 ON T2.cardid = T3.cardid and t3.billnumberid = t2.billnumberid and  T1.AcFrom = T3.AcFrom
	LEFT JOIN #tmpBillMulAccount c ON T1.billmoneyid = c.billmoneyid AND c.atypeid = T3.atypeid
	LEFT JOIN Ac_account  T4 ON T1.ATypeId = T4.TypeId and T4.stypeid = @verifyid
	WHERE T1.atid = @Atid

--调整“平衡数”明细金额
DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) 

DECLARE BalanceCur CURSOR FOR
SELECT billnumberid FROM #TmpBillInfo
	OPEN BalanceCur
	FETCH NEXT FROM BalanceCur INTO @BalanceBillId
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @balancemoney = 0
	SELECT @balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
	FROM #tmpBill
	WHERE billindexid = @BalanceBillId

	
	UPDATE #tmpBill 
	SET #tmpBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
		#tmpBill.lendpricefor = (CASE fadc WHEN 1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN -@balancemoney / T3.rate
											WHEN 1 THEN -@balancemoney * T3.rate
										END
								ELSE 0 END ),
		#tmpBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
		#tmpBill.loanpricefor = (CASE fadc WHEN -1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN @balancemoney / T3.rate
											WHEN 1 THEN @balancemoney * T3.rate
										END
								ELSE 0 END )
	FROM #tmpBill T1
		INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
		INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
	WHERE billindexid = @BalanceBillId
		
	FETCH NEXT FROM BalanceCur INTO @BalanceBillId
END
CLOSE BalanceCur
DEALLOCATE BalanceCur

--去除金额为0的
DELETE FROM #tmpBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 


--排除数据全为0的单据编号
SELECT distinct BillIndexId
INTO #TmpBillNumberId
FROM #tmpbill WHERE lendprice <> 0 OR loanprice <> 0

--处理分录号
SELECT	billnumberid,
		explain,
		a.atypeid,
		atypeid2,
		a.Fdc,
		f_exchid,
		CASE WHEN b.cid = -1 THEN @f_exchid 
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0)= 0 THEN f_exchidfor 
			 ELSE b.Cid 
		END AS f_exchidfor,
		lendprice,
		loanprice,
		CASE WHEN b.cid = -1 THEN lendprice
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0)= 0 THEN lendpricefor
			 ELSE--取科目币种
				CASE c.BasisType --汇率计算方式
					WHEN 0 THEN lendprice / c.Rate
					ELSE lendprice * c.Rate
				END
		END AS lendpricefor,
		CASE WHEN b.cid = -1 THEN loanprice
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0) = 0 THEN loanpricefor
			 ELSE--取科目币种
				CASE c.BasisType --汇率计算方式
					WHEN 0 THEN loanprice / c.Rate
					ELSE loanprice * c.Rate
				END
		END AS loanpricefor,
		FCashFlowItem,
		a.ascids,
		FSettleNo,
		FSettleTypeID,
		a.comment,
		CASE WHEN b.cid = -1 THEN 1
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0) = 0 THEN a.rate
			 ELSE c.Rate
		END AS rate,
		IDENTITY(INT,1,1) AS RowNo,
		CASE WHEN b.cid = -1 THEN @f_exchid
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0) = 0 THEN a.cid
			 ELSE b.cid
		END AS cid,
		fadc,
		a.stypeid,
		fyear,
		fperiod,
		a.atdid,
		a.acfrom,
		cardid,
		billindexid
INTO #tmpRow
FROM 
(
	select T.*
	from
		(SELECT BillNumberId	,
			explain			,
			atypeid			,
			atypeid2		,
			Fdc				,
			f_exchid		,
			f_exchidfor		,
			SUM(lendprice)	AS lendprice,
			SUM(loanprice)	AS Loanprice,
			SUM(lendpricefor) AS lendpriceFor,
			SUM(loanpricefor) AS LoanpriceFor,
			FCashFlowItem	,
			ascids			,
			FSettleNo		,
			FSettleTypeID	,
			comment			,
			cid				,
			rate			,
			fadc			,
			stypeid			,
			fyear			,
			fperiod			,
			atdid			,
			acfrom,
			cardid,
			billindexid
		FROM #tmpBill
		GROUP BY BillNumberId,
			explain			,
			atypeid			,
			atypeid2		,
			Fdc				,
			f_exchid		,
			f_exchidfor		,
			FCashFlowItem	,
			ascids			,
			FSettleNo		,
			FSettleTypeID	,
			comment			,
			cid				,
			rate			,
			fadc			,
			stypeid			,
			fyear			,
			fperiod			,
			atdid			,
			acfrom,
			cardid,
			billindexid
		)T 
	WHERE lendprice <> 0 OR Loanprice <> 0
) as a
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = A.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = A.atypeid AND AC.StypeId = A.stypeid
LEFT JOIN dbo.Ac_Account b ON a.stypeid = b.StypeId AND a.atypeid = b.TypeId
LEFT JOIN dbo.Ac_Currency c ON b.Cid = c.CId
ORDER BY AT.OrderID,A.fadc,AC.UserCode

--生成的凭证明细ID
CREATE TABLE #tmpBillID
(
	rowno	INT ,
	id		INT,
	atypeid	VARCHAR(50)
)

----正式插入明细----
INSERT INTO dbo.Ac_Voucher_Bill
( 
	BillNumberId,
	Summary ,
	ATypeId ,
	ATypeId2 ,
	Fdc ,
	F_ExchId ,
	F_ExchIdFor ,
	FDebitTotal ,
	FCreditTotal ,
	FDebitTotalFor ,
	FCreditTotalFor ,
	FCashFlowItem ,
	AscIds ,
	FSettleNo ,
	FSettleTypeID ,
	Comment ,
	Cid ,
	RowNo ,
	Rate ,
	FAdc ,
	STypeId ,
	FYear ,
	FPeriod
)
OUTPUT INSERTED.rowno,INSERTED.ID,INSERTED.atypeid INTO #tmpBillID
SELECT	billnumberid,
		explain,
		ISNULL(atypeid,''),
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		dbo.F_RoundTotal(lendprice),
		dbo.F_RoundTotal(loanprice),
		dbo.F_RoundTotal(lendpricefor),
		dbo.F_RoundTotal(loanpricefor),
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		RowNo,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod
FROM #tmpRow
ORDER BY AtdId

--生成凭证与辅助对应关系
--非手工选择的科目来源，设置辅助核算的话必须全部设置，这样只要科目有辅助核算就肯定取得到值
SELECT DISTINCT id,e.Ascids,f.UserCode,h.FieldValue,b.acfrom,b.cardid,b.billindexid
INTO #tmpIDAscids
FROM #tmpBillID a
INNER JOIN #tmpRow b ON a.rowno = b.rowno
INNER JOIN dbo.Ac_Auditing_Template_Detail c ON b.atdid = c.AtdId
INNER JOIN dbo.Ac_Account d ON a.atypeid = d.TypeId
INNER JOIN dbo.Ac_Account_Assist_CheckItems e ON (d.TypeId = e.ATypeId AND d.StypeId = e.STypeId)
INNER JOIN dbo.Ac_Assist_CheckItems f ON e.Ascids = f.AscIds
INNER JOIN dbo.Ac_Auditing_Template_Detail_Assist_CheckItems g ON (e.Ascids = g.AscIds AND b.atdid = g.AtdId)
INNER JOIN dbo.Ac_Assist_CheckItems_BillType h ON g.AscIds = h.AscIds AND h.nId = g.AscIdsDetailId
WHERE d.StypeId = @Verifyid AND h.BillType = @Billtype


--单据用于凭证辅助核算的具体的字段值
CREATE TABLE #tmpDetail
(
	fieldvalue	VARCHAR(50),
	id			INT,
	fieldname	VARCHAR(50),
	acfrom		INT,
	cardid		INT
)

DECLARE @sql2 VARCHAR(MAX)
SET @sql2 = 'SELECT T2.*
		INTO #Tmp
		FROM AssetIncDecBill T1
		LEFT JOIN BillIndex T2 ON T1.billnumberid = T2.billnumberid
		where T1.billnumberid in (select * from f_split(''' + CAST(@Id AS varchar(1000)) + ''','','') ) '
		
SET @sql2 += 'insert into #tmpDetail '


SELECT @sql2 +=  'select '+ cast(FieldValue AS varchar(50))+ ',' + 
			CAST(id AS varchar(50)) +' as id, (SELECT name FROM syscolumns WHERE id = object_id(''BillIndex'') AND name = '''+
			cast(FieldValue AS varchar(50))+''')as filedname,' +cast(acfrom AS varchar(50)) +' as acfrom,'+ cast(cardid AS varchar(50)) +' as cardid 
				FROM #Tmp
				where billnumberid = '+cast(BillIndexid as varchar)+'
				union all '
FROM #tmpIDAscids
	
IF LEN(@sql2) > LEN('SELECT T2.*
		INTO #Tmp
		FROM AssetIncDecBill T1
		LEFT JOIN BillIndex T2 ON T1.billnumberid = T2.billnumberid
		where T1.billnumberid in (select * from f_split(''' + CAST(@Id AS varchar(1000)) + ''','','') ) '+'insert into #tmpDetail ')
BEGIN
	SET @sql2 = SUBSTRING(@sql2,1,LEN(@sql2)-9)
	EXEC(@sql2)
END

DELETE FROM #tmpDetail WHERE ISNULL(fieldvalue,'')=''

IF @BillType = 214    --折旧单部门取明细部门值
BEGIN
	UPDATE T1 
	SET fieldvalue = 
		CASE WHEN T1.fieldname = 'stypeid' THEN T2.STypeId 
			 WHEN T1.fieldname = 'dtypeid' THEN T3.DTypeid
			 WHEN T1.fieldname = 'etypeid' THEN T1.fieldvalue
			 WHEN T1.fieldname = 'btypeid' THEN T1.fieldvalue
		END 
	FROM #tmpDetail T1 
	INNER JOIN DepBill T3 ON T3.AssetCardId = T1.cardid
	INNER JOIN dbo.Ac_AssetsCards T2 ON T2.Id =T1.cardid 
	INNER JOIN #tmpIDAscids T4 ON T4.billindexid = T3.BillNumberId
END
ELSE     ----来自卡片的科目辅助核算‘分支机构’ ‘部门’按卡片上的来
BEGIN
	UPDATE #tmpDetail 
	SET fieldvalue = 
		CASE WHEN T1.fieldname = 'stypeid' THEN T2.STypeId 
			 WHEN T1.fieldname = 'dtypeid' THEN T2.DTypeid
			 WHEN T1.fieldname = 'etypeid' THEN T1.fieldvalue
			 WHEN T1.fieldname = 'btypeid' THEN T1.fieldvalue
		END 
	FROM #tmpDetail T1 
	INNER JOIN dbo.Ac_AssetsCards T2 ON T1.cardid = T2.Id
	WHERE T1.acfrom IN (5,9,10,11) 
END

--插入辅助核算值
SELECT	DISTINCT @VoucherId AS billnumberid,
		a.id AS vBId,
		a.UserCode AS typeName,
		b.fieldvalue AS TypeId
INTO	#tmpAssit
FROM #tmpIDAscids a INNER JOIN #tmpDetail b ON a.id = b.id AND a.FieldValue=b.fieldname
WHERE ISNULL(b.fieldvalue,'') <> ''


INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
( 
	BillNumberId ,
	vBId ,
	typeName ,
	TypeId
)
SELECT	*
FROM	#tmpAssit


--更新凭证明细中辅助核算字段值信息
UPDATE dbo.Ac_Voucher_Bill SET AscIds= dbo.F_Get_VoucherAscids(id,1) WHERE BillNumberId = @VoucherId


--合并信息相同的明细，采用合并插入后再删除原来的凭证--
DECLARE @newVoucherId INT --临时BillNumberId
SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

SELECT	billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FCreditTotal,
		FDebitTotalFor,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		IDENTITY(INT,1,1) AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill
FROM
(
SELECT  @newVoucherId AS billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		SUM(FDebitTotal) AS FDebitTotal,
		SUM(FCreditTotal) AS FCreditTotal,
		SUM(FDebitTotalFor) AS FDebitTotalFor,
		SUM(FCreditTotalFor) AS FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod,
		MIN(rowno) AS initRowno
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @VoucherId
GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod
)TT
ORDER BY initRowno

--去除金额为0的
DELETE FROM #tmpNewVoucherBill WHERE ISNULL(FDebitTotal,0) = 0  AND ISNULL(FCreditTotal,0) = 0 

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
SELECT  billnumberid,
		Summary ,
		STypeId ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FDebitTotalFor,
		FCreditTotal,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		FYear ,
		FPeriod,
		Comment ,
		Cid ,
		rowno,
		Rate ,
		FAdc
FROM #tmpNewVoucherBill

--删除旧分录数据
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId

--替换临时BillNumberId为真实的
UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @VoucherId WHERE BillNumberId = @newVoucherId
--------合并完成---------

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN	
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId	
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #tmpBillID,#tmpIDAscids,#tmpDetail,#tmpAssit,#tmpExpress,#tmpBill,#tmpRow
DROP TABLE #TmpVoucherDetails,#TempStr
DROP TABLE #TmpAssetTypeid,#tmpExpress_Bill,#tmpBillMoney_Bill
DROP TABLE #TmpBillNumberId,#BillNumberId,#TmpBillInfo,#tmpNewVoucherBill,#tmpBillMulAccount,#tmpBillIndexAtypeid

	
RETURN @VoucherId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013-05-22
	描述：固定资产卡片相关生成会计凭证
*/
CREATE PROCEDURE Gp_CreateVoucher_Assets
(
	@Id				INT,					-- 单据编号
	@BillType		INT = 0,				-- 类型  1.计提减值 2.部门转移
	@AtId			INT = 0,				-- 模板Id，0代表取单据默认模板
	@specifyDate	DATE = '',				-- 手工指定凭证日期
	@szPID			VARCHAR(1000)	OUTPUT,	-- 返回出错信息
	@VoucherId		INT	= -1		OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

--非总账模式直接返回
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1)
	RETURN 0

DECLARE @BillDate			VARCHAR(20),	-- 单据日期
		@STypeid			VARCHAR(50),	-- 分支机构
		@Verifyid			VARCHAR(50),	-- 核算单位
		@etypeid			VARCHAR(50) 	-- 操作职员
IF @BillType = 1
	SELECT  @BillDate = T1.BusinessDate,
			@STypeid = T2.STypeId,
			@Verifyid = T3.VerifyID,
			@etypeid = T1.ETypeId
	FROM dbo.Ac_ProvisionForImpairment T1
		INNER JOIN dbo.Ac_AssetsCards T2 ON T1.CardId = T2.Id
		INNER JOIN dbo.SType T3 ON T2.STypeId = T3.TypeId
	WHERE T1.Id = @Id
ELSE IF @BillType = 2
	SELECT  @BillDate = T1.BusinessDate,
			@STypeid = T2.STypeId,
			@Verifyid = T3.VerifyID,
			@etypeid = T1.ETypeId
	FROM dbo.Ac_AssetsModifyRecords T1
		INNER JOIN dbo.Ac_AssetsCards T2 ON T1.CardId = T2.Id
		INNER JOIN dbo.SType T3 ON T2.STypeId = T3.TypeId
	WHERE T1.Id = @Id

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType_UserConfig WHERE StypeId = @Verifyid AND Value = 1)
BEGIN
	SELECT -228 AS error
	RETURN -228 --分支机构对应核算分支未开账
END

----统计单据金额字段----
CREATE TABLE #tmpBillMoney
(
	DevalueReady		 NUMERIC(24, 10) 	DEFAULT 0,--计提减持金额
	Total				 NUMERIC(24, 10) 	DEFAULT 0,--资产卡片原值
	DepTotal			 NUMERIC(24, 10) 	DEFAULT 0, --资产卡片累计折旧值
	NetValue			 NUMERIC(24, 10) 	DEFAULT 0,--净值
	CardId				INT	--卡片id
)

CREATE TABLE #tmpBillMoney_Bill
(
	ac_balanceB 		 NUMERIC(24, 10) 	DEFAULT 0, --累计折旧额 ac_balanceB
	TaxTotal			 NUMERIC(24, 10) 	DEFAULT 0,--价税合计
	Total				 NUMERIC(24, 10) 	DEFAULT 0,--金额
	TotalInMoney		 NUMERIC(24, 10) 	DEFAULT 0, --实收\实付金额
	balancemoney		 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	cardtotal			 NUMERIC(24, 10) 	DEFAULT 0, --固定资产原值
	devalueready		 NUMERIC(24, 10) 	DEFAULT 0,--固定资产减值准备
	CardId				INT
)

DECLARE @MinCarId	INT--为了防止世界被破坏。其实是为了防止billindex上取的金额翻倍，只将billindex上取的金额，如“收付款”更新到第一行


IF @BillType = 1
--插入金额
	INSERT INTO #tmpBillMoney
		(
			DevalueReady
		)
	SELECT	DevalueReady
	FROM dbo.Ac_ProvisionForImpairment
	WHERE Id = @Id
ELSE IF @BillType = 2
	INSERT INTO #tmpBillMoney
	        (Total, DepTotal,DevalueReady)
	SELECT T2.Total,T2.DepTotal,T2.DevalueReady
	FROM dbo.Ac_AssetsModifyRecords T1
		INNER JOIN dbo.Ac_AssetsCards T2 ON T1.CardId = T2.Id
	WHERE T1.Id = @Id

--获取业务类型中凭证模版
IF @AtId = 0
BEGIN
	IF @BillType = 1
		SELECT @Atid = AT.AtId
		FROM Ac_AssetBusinessType AB 
		INNER JOIN Ac_Auditing_Template AT ON AT.STypeId = AB.STypeId AND AT.AuditType=AB.AuditType AND AT.IsDefault = 1
		WHERE AB.AuditType = 13 AND AB.STypeId = @Verifyid
	ELSE IF @BillType = 2
		SELECT @Atid = AT.AtId
		FROM Ac_AssetBusinessType AB 
		INNER JOIN Ac_Auditing_Template AT ON AT.STypeId = AB.STypeId AND AT.AuditType=AB.AuditType AND AT.IsDefault = 1
		WHERE AB.AuditType = 12 AND AB.STypeId = @Verifyid

	--无默认凭证模版
	IF @@ROWCOUNT = 0
		BEGIN
			SELECT -232 AS error
			RETURN -232--模板不存在
		END
		
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE AtId = @AtId)
		BEGIN
			SELECT -232 AS error
			RETURN -232--模板不存在
		END
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE AtId = @AtId)--无此模板
	BEGIN
		BEGIN
			SELECT -232 AS error
			RETURN -232--模板不存在
		END
	END
END

--将模板明细处理到临时表中,进行读取字段生成摘要
-----------------------------------------------
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails

SELECT @MinNumber = MIN(a) FROM dbo.f_split(@Id,',')
SELECT @MaxNumber = MAX(a) FROM dbo.f_split(@Id,',')

SET @Index = @MinNumber



CREATE TABLE #TempStr
(
	RowNo		INT IDENTITY(1,1),
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)


WHILE @MinDid <= @MaxDid
BEGIN
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		SET @Index += 1
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = @str WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	SET @MinDid += 1
END

UPDATE #TmpVoucherDetails SET Summary = LEFT(Summary,197)+'...' WHERE LEN(Summary) > 200

-----------------------
--处理摘要完成


--配置要求每行分录必有摘要时，检查模板是否符合
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='acsummary' AND SubValue = 1)
BEGIN
	DECLARE @countAudit INT,@countSummary INT
	SELECT @countAudit = COUNT(*) FROM dbo.Ac_Auditing_Template_Detail WHERE atid = @atid
	SELECT @countSummary = COUNT(*) FROM dbo.Ac_Auditing_Template_Detail WHERE atid = @atid AND Summary <> ''
	IF @countAudit > @countSummary
	BEGIN
		BEGIN
			SELECT -233 AS error
			RETURN -233--配置要求每行必有摘要，生成失败，请检查模板
		END
	END
END

--判断是否有凭证字
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Group)
BEGIN
	BEGIN
		BEGIN
			SELECT -234 AS error
			RETURN -234--不存在模板上凭证字，生成失败
		END
	END
END

--取会计期间
DECLARE @fyear		INT,
		@fperiod	INT,
		@period		INT,
		@beginDate	DATE,
		@endYearDate	DATE


--调整为获取分支机构各自的当前会计期间
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Verifyid)
BEGIN
	SELECT @fperiod = FPeriod,@fyear = FYear FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Verifyid
END
ELSE
BEGIN
	SELECT @fperiod = SubValue FROM dbo.sysdata WHERE SubName = 'fmonth'
	SELECT @fyear = SubValue FROM dbo.sysdata WHERE SubName= 'fyear'
END

	
SELECT TOP 1 @endYearDate = FEnd FROM dbo.Ac_Period WHERE FYear = @fyear ORDER BY FPeriod DESC 

SELECT @beginDate = FBegin FROM dbo.Ac_Period WHERE FPeriod = @fperiod AND FYear = @fyear

DECLARE @datetype INT
SELECT @datetype = subvalue FROM dbo.sysdata WHERE SubName = 'voucherdatetype'

--若单据日期小于当前会计期间起始日期，则取当前系统日期，若当前系统日期也小于当前会计期间起始日期，则取当前会计期间起始日期。
IF @billdate < @beginDate
	SET @billdate = GETDATE()
IF @billdate < @beginDate
	SET @billdate = @beginDate
--如果时间超出了本年末期结束，按本年末期为准
IF @billdate > @endYearDate
	SET @billdate = @endYearDate

SELECT @fperiod = FPeriod FROM dbo.Ac_Period WHERE @billdate >= FBegin AND @billdate <= FEnd

--获取凭证字
DECLARE @vgid INT 

SELECT @vgid = vgid FROM dbo.Ac_Auditing_Template WHERE AtId = @AtId

--获取本位币
DECLARE	 @f_exchid		VARCHAR(50)
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

--凭证类型 4.固定资产系统生成
--5.部门转移
--6.计提减值
DECLARE @Type INT
SET @Type = 3
IF @BillType  = 2
	SET @Type = 5
ELSE IF @BillType = 1
	SET @Type = 6

DECLARE @VoucherBillId NUMERIC(18,0)
--插入凭证主表
EXEC @VoucherBillId =   dbo.GP_SaveAc_VoucherIndex 
						@Verifyid, -- varchar(50)
						@vgid, -- int
						@BillDate, -- datetime
						'', -- varchar(400)
						0, -- int
						0, -- int
						'', -- varchar(50)
						0, -- int
						'', -- varchar(50)
						@etypeid, -- varchar(50)
						'', -- varchar(50)
						'', -- varchar(200)
						0, -- numeric
						0, -- numeric
						0, -- int
						0, -- int
						'',
						'',
						'',
						'f', -- varchar(1)
						0,
						@type

DECLARE @countRow INT
SET @countRow = @@ROWCOUNT

IF @VoucherBillId = -1
BEGIN
	BEGIN
		SELECT -230 AS error
		RETURN -230--您使用的是试用版，凭证数据不能大于200
	END
END

IF  @countRow = 0
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
	SELECT -231 AS error
	RETURN -231--创建表头失败
END

SET @VoucherId = @VoucherBillId



--科目来源AcFrom
--1 手工选择
--2 单据上收付款项目对应科目
--3 单据上往来科目
--5 固定资产
--9 累计折旧
--10 折旧分配
--11 固定资产减值准备科目
CREATE TABLE #tmpExpress
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) 
)

CREATE TABLE #tmpExpress_Bill
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) ,
	CardId		INT
)


DECLARE @Sql	VARCHAR(MAX)	-- 动态SQL

IF @BillType = 1 OR @BillType = 2
BEGIN
	--读取模板要求的金额
	SET @sql = 'insert into #tmpExpress '

		SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId, ('+ Express +') as lendloan
		from #tmpBillMoney a'
		+' union all '
		FROM Ac_Auditing_Template_Detail
		WHERE Atid = @Atid

	IF LEN(@sql) > LEN('insert into #tmpExpress ')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
		EXEC(@sql)
	END
END


--取固定资产卡片相应科目
--如果是单据，同时取出单据收付款、往来科目
CREATE TABLE #TmpAssetTypeid
(
	ATypeId		VARCHAR(50),
	Usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	Fdc			INT,
	Cid			INT,
	AtId		INT,
	AcFrom		INT,--科目来源
	CardId		INT,--卡片ID
	Item		VARCHAR(100)
)

DECLARE @Table VARCHAR(2000)

IF @BillType = 1--计提减持
	SET @Table = 'Ac_ProvisionForImpairment'
ELSE IF @BillType = 2--固定资产变更
	SET @Table = 'Ac_AssetsModifyRecords'
	
	
SET @sql =
'INSERT INTO #TmpAssetTypeid
SELECT	T3.TypeId,
		T3.UserCode,
		T3.FullName,
		T3.Fdc,
		T3.cid,'+
		CAST(@Atid AS VARCHAR(10)) +'AS atid,
		5,
		T1_1.id,
		SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
				LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
				LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
FROM '+ @Table +' T1
INNER JOIN dbo.Ac_AssetsCards T1_1 ON T1.'+ CASE WHEN @BillType IN (1,2)  THEN 'CardId' ELSE 'AssetCardId' END+' = T1_1.Id
INNER JOIN dbo.SType T2 ON T1_1.STypeId = T2.TypeId
INNER JOIN dbo.Ac_Account T3 ON T1_1.AssertATypeId = T3.TypeId AND T2.VerifyID = T3.StypeId	--5
WHERE T2.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+''' AND T1.'+ CASE WHEN @BillType IN (1,2) THEN 'Id' ELSE 'BillNumberId' END+' = '+CAST(@Id AS VARCHAR(10))
+
'
UNION ALL

SELECT	T3.TypeId,
		T3.UserCode,
		T3.FullName,
		T3.Fdc,
		T3.cid,'+
		CAST(@Atid AS VARCHAR(10)) +' AS atid,
		9,
		T1_1.id,
		SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
				LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
				LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
FROM '+ @Table +' T1
INNER JOIN dbo.Ac_AssetsCards T1_1 ON T1.'+ CASE WHEN @BillType IN (1,2) THEN 'CardId' ELSE 'AssetCardId' END+' = T1_1.Id
INNER JOIN dbo.SType T2 ON T1_1.Stypeid = T2.TypeId
INNER JOIN dbo.Ac_Account T3 ON T1_1.DepATypeId = T3.TypeId AND T2.VerifyID = T3.StypeId		--9
WHERE T2.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+''' AND T1.'+ CASE WHEN @BillType IN (1,2) THEN 'Id' ELSE 'BillNumberId' END+' = '+CAST(@Id AS VARCHAR(10))
+
'
UNION ALL

SELECT	T3.TypeId,
		T3.UserCode,
		T3.FullName,
		T3.Fdc,
		T3.cid,'+
		CAST(@Atid AS VARCHAR(10)) +'AS atid,
		10,
		T1_1.id,
		SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
				LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
				LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
FROM '+ @Table +' T1
INNER JOIN dbo.Ac_AssetsCards T1_1 ON T1.'+ CASE WHEN @BillType IN (1,2) THEN 'CardId' ELSE 'AssetCardId' END+' = T1_1.Id
INNER JOIN dbo.SType T2 ON T1_1.Stypeid = T2.TypeId
INNER JOIN dbo.Ac_Account T3 ON T1_1.DisATypeId = T3.TypeId AND T2.VerifyID = T3.StypeId		--10
WHERE T2.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+''' AND T1.'+ CASE WHEN @BillType IN (1,2) THEN 'Id' ELSE 'BillNumberId' END+' = '+CAST(@Id AS VARCHAR(10))
+
'
UNION ALL

SELECT	T3.TypeId,
		T3.UserCode,
		T3.FullName,
		T3.Fdc,
		T3.cid,'+
		CAST(@Atid AS VARCHAR(10)) +'AS atid,
		11,
		T1_1.id,
		SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
				LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
				LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
FROM ' + @Table +' T1
INNER JOIN dbo.Ac_AssetsCards T1_1 ON T1.'+ CASE WHEN @BillType IN (1,2) THEN 'CardId' ELSE 'AssetCardId' END+' = T1_1.Id
INNER JOIN dbo.SType T2 ON T1_1.Stypeid = T2.TypeId
INNER JOIN dbo.Ac_Account T3 ON T1_1.DevalueATypeId = T3.TypeId AND T2.VerifyID = T3.StypeId	--TODO:11
WHERE T2.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+''' AND T1.'+ CASE WHEN @BillType IN (1,2) THEN 'Id' ELSE 'BillNumberId' END+' = '+CAST(@Id AS VARCHAR(10))


EXEC(@sql)


--生成凭证明细数据
CREATE TABLE #tmpBill
(
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rowno			INT		IDENTITY(1,1),
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT
)



IF @BillType = 1 OR @BillType = 2
INSERT INTO #tmpBill
( 
	billnumberid ,
	explain ,
	atypeid ,
	atypeid2 ,
	Fdc ,
	f_exchid ,
	f_exchidfor ,
	lendprice ,
	loanprice ,
	lendpricefor ,
	loanpricefor ,
	FCashFlowItem ,
	ascids ,
	FSettleNo ,
	FSettleTypeID ,
	comment ,
	cid ,
	rate ,
	fadc ,
	stypeid ,
	fyear ,
	fperiod,
	atdid
)
SELECT @VoucherBillId AS billnumberid,
		Summary AS explain,
		CASE T1.AcFrom 
			WHEN 1 THEN	T1.ATypeId 
			ELSE T2.ATypeId
		END AS atypeid,
		'' AS atypeid2,
		CASE T1.AcFrom 
			WHEN 1 THEN T3.Fdc
			ELSE T2.Fdc
		END AS Fdc,
		@f_exchid AS f_exchid,
		@f_exchid AS f_exchidfor,
		CASE T1.Fdc 
			WHEN 1 THEN T4.lendloan
			ELSE 0 
		END AS lendprice,
		CASE T1.Fdc 
			WHEN -1 THEN T4.lendloan
			ELSE 0 
		END AS loanprice,
		CASE T1.Fdc 
			WHEN 1 THEN T4.lendloan
			ELSE 0 
		END AS lendpricefor,
		CASE T1.Fdc 
			WHEN -1 THEN T4.lendloan
			ELSE 0 
		END AS loanpricefor,
		NULL AS FCashFlowItem,
		'' AS ascids,
		NULL AS FSettleNo,
		NULL AS FSettleTypeID,
		'' AS comment,
		@f_exchid AS cid,
		1 AS Rate,
		T1.Fdc AS fadc,
		@Verifyid AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod,
		T1.AtdId
FROM #TmpVoucherDetails T1
LEFT JOIN #TmpAssetTypeid T2 ON T1.AcFrom = T2.AcFrom
LEFT JOIN Ac_Account T3 ON T1.ATypeId = T3.TypeId AND T3.stypeid = @Verifyid
INNER JOIN #tmpExpress T4 ON T1.AtdId = T4.atdit
WHERE T1.atid = @Atid
ORDER BY T1.AtdId

		

--调整“平衡数”明细金额
DECLARE @balancemoney  NUMERIC(24, 10) 

SELECT @balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
FROM #tmpBill

UPDATE #tmpBill 
SET lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
	loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ) 
WHERE atdid IN (SELECT atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Express = 'balancemoney' AND Atid = @atid)

--去除金额为0的
DELETE FROM #tmpBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 


--处理分录号
SELECT	billnumberid,
		explain,
		atypeid,
		atypeid2,
		a.Fdc,
		f_exchid,
		CASE WHEN b.cid = -1 THEN @f_exchid 
			 WHEN b.Cid = a.cid OR b.Cid = 0 THEN f_exchidfor 
			 ELSE b.Cid 
		END AS f_exchidfor,
		lendprice,
		loanprice,
		CASE WHEN b.cid = -1 THEN lendprice
			 WHEN b.Cid = a.cid OR b.Cid = 0 THEN lendpricefor
			 ELSE--取科目币种
				CASE c.BasisType --汇率计算方式
					WHEN 0 THEN lendprice / c.Rate
					ELSE lendprice * c.Rate
				END
		END AS lendpricefor,
		CASE WHEN b.cid = -1 THEN loanprice
			 WHEN b.Cid = a.cid OR b.Cid = 0 THEN loanpricefor
			 ELSE--取科目币种
				CASE c.BasisType --汇率计算方式
					WHEN 0 THEN loanprice / c.Rate
					ELSE loanprice * c.Rate
				END
		END AS loanpricefor,
		FCashFlowItem,
		a.ascids,
		FSettleNo,
		FSettleTypeID,
		a.comment,
		CASE WHEN b.cid = -1 THEN 1
			 WHEN b.Cid = a.cid OR b.Cid = 0 THEN a.rate
			 ELSE c.Rate
		END AS rate,
		IDENTITY(INT,1,1) AS RowNo,
		CASE WHEN b.cid = -1 THEN @f_exchid
			 WHEN b.Cid = a.cid OR b.Cid = 0 THEN a.cid
			 ELSE b.cid
		END AS cid,
		fadc,
		a.stypeid,
		fyear,
		fperiod,
		atdid
INTO #tmpRow
FROM #tmpBill a
LEFT JOIN dbo.Ac_Account b ON a.stypeid = b.StypeId AND a.atypeid = b.TypeId
LEFT JOIN dbo.Ac_Currency c ON b.Cid = c.CId

IF EXISTS(SELECT * FROM #tmpRow T1 INNER JOIN dbo.Ac_Account T2 ON T1.atypeid = T2.TypeId AND T2.StypeId = @Verifyid AND Deleted = 1)
BEGIN
	SELECT -229 AS error
	RETURN -229--生成凭证中有会计科目被停用，无法生成！
END

DECLARE @Flag INT

SET @Flag = 0

--项目对应的科目不全
IF EXISTS(SELECT TOP 1 1 FROM #tmpRow WHERE ISNULL(atypeid,'') = '')
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
	SET @Flag = -222
END

--生成的凭证明细ID
CREATE TABLE #tmpBillID
(
	rowno	INT ,
	id		INT,
	atypeid	VARCHAR(50)
)

----正式插入明细----
INSERT INTO dbo.Ac_Voucher_Bill
( 
	BillNumberId,
	Summary ,
	ATypeId ,
	ATypeId2 ,
	Fdc ,
	F_ExchId ,
	F_ExchIdFor ,
	FDebitTotal ,
	FCreditTotal ,
	FDebitTotalFor ,
	FCreditTotalFor ,
	FCashFlowItem ,
	AscIds ,
	FSettleNo ,
	FSettleTypeID ,
	Comment ,
	Cid ,
	RowNo ,
	Rate ,
	FAdc ,
	STypeId ,
	FYear ,
	FPeriod
)
OUTPUT INSERTED.rowno,INSERTED.ID,INSERTED.atypeid INTO #tmpBillID
SELECT	billnumberid,
		explain,
		ISNULL(atypeid,''),
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		lendprice,
		loanprice,
		lendpricefor,
		loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		RowNo,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod
FROM #tmpRow
ORDER BY AtdId


IF @@ROWCOUNT = 0--写入单据明细数据错误
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
	SELECT -214 AS error
	RETURN -214--写入凭证明细失败
END


--判断借贷平衡
DECLARE @lend  NUMERIC(24, 10) ,@loan  NUMERIC(24, 10) 

SELECT	@lend = SUM(FDebitTotal),
		@loan = SUM(FCreditTotal)
FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId

IF @lend <> @loan--明细借贷不平衡
BEGIN
	SET @Flag = -217
END


--更新凭证借贷总额
UPDATE dbo.Ac_Voucher SET FDebitTotal = @lend,FCreditTotal = @loan WHERE BillNumberId = @VoucherBillId
--更新分录数
UPDATE dbo.Ac_Voucher SET FEntryCount = (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId)
WHERE BillNumberId = @VoucherBillId



----生成明细辅助核算----
--非手工科目有辅助核算而模板没有时，报错
IF EXISTS(
		SELECT TOP 1 1
		FROM #tmpBillID a
			INNER JOIN #tmpRow b ON a.rowno = b.rowno
			INNER JOIN dbo.Ac_Auditing_Template_Detail c ON b.atdid = c.AtdId
			INNER JOIN dbo.Ac_Account d ON a.atypeid = d.TypeId
			INNER JOIN dbo.Ac_Account_Assist_CheckItems e ON (d.TypeId = e.ATypeId AND d.StypeId = e.STypeId)
			WHERE c.AcFrom > 1 AND d.StypeId = @Verifyid
	)
	AND NOT EXISTS(
		SELECT TOP 1 1 
		FROM #tmpBillID a
			INNER JOIN #tmpRow b ON a.rowno = b.rowno
			INNER JOIN dbo.Ac_Auditing_Template_Detail c ON b.atdid = c.AtdId
			INNER JOIN dbo.Ac_Auditing_Template_Detail_Assist_CheckItems d ON c.AtdId = d.AtdId
			WHERE c.AcFrom > 1
	)
BEGIN
	SET @Flag = -216
END


--生成凭证与辅助对应关系
--非手工选择的科目来源，设置辅助核算的话必须全部设置，这样只要科目有辅助核算就肯定取得到值
SELECT DISTINCT id,e.Ascids,f.UserCode,h.FieldValue
INTO #tmpIDAscids
FROM #tmpBillID a
INNER JOIN #tmpRow b ON a.rowno = b.rowno
INNER JOIN dbo.Ac_Auditing_Template_Detail c ON b.atdid = c.AtdId
INNER JOIN dbo.Ac_Account d ON a.atypeid = d.TypeId
INNER JOIN dbo.Ac_Account_Assist_CheckItems e ON (d.TypeId = e.ATypeId AND d.StypeId = e.STypeId)
INNER JOIN dbo.Ac_Assist_CheckItems f ON e.Ascids = f.AscIds
INNER JOIN dbo.Ac_Auditing_Template_Detail_Assist_CheckItems g ON (e.Ascids = g.AscIds AND b.atdid = g.AtdId)
INNER JOIN dbo.Ac_Assist_CheckItems_BillType h ON g.AscIds = h.AscIds AND h.nId = g.AscIdsDetailId
WHERE d.StypeId = @Verifyid


--单据用于凭证辅助核算的具体的字段值
CREATE TABLE #tmpDetail
(
	fieldvalue	VARCHAR(50),
	id			INT,
	fieldname	VARCHAR(50)
)

DECLARE @sql2 VARCHAR(MAX)
SET @sql2 = 'insert into #tmpDetail '


IF @BillType = 1
	SELECT @sql2 +=  'select '
					+ CASE WHEN FieldValue = 'dealbtypeid' THEN ''''''
							WHEN FieldValue = 'etypeid' THEN 'T1.'+CAST(FieldValue AS varchar(50))
						ELSE CAST(FieldValue AS varchar(50)) END + ',' + 
					CAST(id AS varchar(50)) +' as id, '+
					CASE WHEN fieldvalue IN('stypeid','dtypeid') THEN '(SELECT name FROM syscolumns WHERE id = object_id(''Ac_AssetsCards'') AND name = '''
						ELSE '(SELECT name FROM syscolumns WHERE id = object_id(''Ac_ProvisionForImpairment'') AND name = '''
					END
					+
					cast(FieldValue AS varchar(50))+''')as filedname 
						FROM Ac_ProvisionForImpairment T1
							INNER JOIN Ac_AssetsCards T2 ON T1.CardId = T2.Id
						 where T1.id=' + 
					CAST(@Id AS varchar(1000)) +
					'union all '
	FROM #tmpIDAscids
ELSE IF @BillType = 2
	SELECT @sql2 +=  'select '+
					CASE WHEN FieldValue = 'stypeid' THEN 'T2.'+ cast(FieldValue AS varchar(50))
						WHEN FieldValue = 'dealbtypeid' THEN ''''''
						ELSE 'T1.'+ cast(FieldValue AS varchar(50))
					END + ',' + 
				CAST(id AS varchar(50)) +' as id, '+
				CASE WHEN FieldValue = 'stypeid' THEN '(SELECT name FROM syscolumns WHERE id = object_id(''Ac_AssetsCards'') AND name = '''+cast(FieldValue AS varchar(50))+''''
					 WHEN FieldValue = 'dealbtypeid' THEN '(''dealbtypeid'''
					ELSE '(SELECT name FROM syscolumns WHERE id = object_id(''Ac_AssetsModifyRecords'') AND name = '''+cast(FieldValue AS varchar(50))+''''
				END
					+' ) as filedname 
					FROM Ac_AssetsModifyRecords T1
						INNER JOIN Ac_AssetsCards T2 ON T1.CardId = T2.Id
					 where T1.id=' + 
				CAST(@Id AS varchar(1000)) + 
				'union all '
	FROM #tmpIDAscids
	
IF LEN(@sql2) > LEN('insert into #tmpDetail ')
BEGIN
	SET @sql2 = SUBSTRING(@sql2,1,LEN(@sql2)-9)
	PRINT @sql2
	EXEC(@sql2)
END

--操作员为admin，将此辅助核算值置空
UPDATE #tmpDetail SET fieldvalue = '' WHERE fieldname = 'etypeid' AND fieldvalue = '00001'	



--插入辅助核算值
SELECT	DISTINCT @voucherbillid AS billnumberid,
		a.id AS vBId,
		a.UserCode AS typeName,
		b.fieldvalue AS TypeId
INTO	#tmpAssit
FROM #tmpIDAscids a INNER JOIN #tmpDetail b ON a.id = b.id AND a.FieldValue=b.fieldname



INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
( 
	BillNumberId ,
	vBId ,
	typeName ,
	TypeId
)
SELECT	*
FROM	#tmpAssit
WHERE ISNULL(TypeId,'') <> ''



--异常的生成明细辅助核算与科目辅助核算不匹配
SELECT DISTINCT a.ATypeId,b.Ascids
INTO #tmpCheckAscids
FROM dbo.Ac_Voucher_Bill a
INNER JOIN dbo.Ac_Account_Assist_CheckItems b ON a.ATypeId = b.ATypeId AND a.STypeId = b.STypeId
WHERE a.BillNumberId = @voucherbillid

SELECT DISTINCT a.ATypeId,c.AscIds
INTO #tmpActualAscids
FROM dbo.Ac_Voucher_Bill a 
INNER JOIN dbo.Ac_Voucher_Bill_Assist_CheckItems b ON a.ID = b.vBId
INNER JOIN dbo.Ac_Assist_CheckItems c ON b.typeName = c.UserCode
WHERE a.BillNumberId = @voucherbillid


DECLARE @countC INT,@countA INT

SELECT @countC = COUNT(*)
FROM #tmpCheckAscids

SELECT @countA = COUNT(*)
FROM #tmpActualAscids a
INNER JOIN #tmpCheckAscids b ON a.ATypeId = b.ATypeId AND a.AscIds = b.Ascids


IF @countA <> @countC OR EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE ISNULL(TypeId,'') = '' AND BillNumberId = @voucherbillid)
BEGIN
	SET @Flag = -216
END

DROP TABLE #tmpCheckAscids,#tmpActualAscids


--更新凭证明细中辅助核算字段值信息
UPDATE dbo.Ac_Voucher_Bill SET AscIds= dbo.F_Get_VoucherAscids(id,1) WHERE BillNumberId = @voucherbillid


--合并信息相同的明细，采用合并插入后再删除原来的凭证--
DECLARE @newVoucherId INT --临时BillNumberId
SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

SELECT	billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FCreditTotal,
		FDebitTotalFor,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		IDENTITY(INT,1,1) AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill
FROM
(
SELECT  @newVoucherId AS billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		SUM(FDebitTotal) AS FDebitTotal,
		SUM(FCreditTotal) AS FCreditTotal,
		SUM(FDebitTotalFor) AS FDebitTotalFor,
		SUM(FCreditTotalFor) AS FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod,
		MIN(rowno) AS initRowno
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @voucherBillId
GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod
)TT
ORDER BY initRowno


--用于记录明细ID，插入辅助核算使用
CREATE TABLE #tmpId
(
	id INT,
	ascids VARCHAR(500)
)

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.AscIds INTO #tmpId
SELECT  billnumberid,
		Summary ,
		STypeId ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FDebitTotalFor,
		FCreditTotal,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		FYear ,
		FPeriod,
		Comment ,
		Cid ,
		rowno,
		Rate ,
		FAdc
FROM #tmpNewVoucherBill


--辅助核算
INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
			( BillNumberId ,
			  vBId ,
			  typeName ,
			  TypeId
			)
SELECT DISTINCT	@newVoucherId,
		c.id,
		typeName,
		TypeId  
FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
INNER  JOIN dbo.Ac_Voucher_Bill b ON a.vBId = b.ID
INNER JOIN #tmpId c ON b.AscIds = c.ascids
WHERE a.BillNumberId = @voucherbillid


--更新表头分录数
UPDATE dbo.Ac_Voucher SET FEntryCount = (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherbillid)

--删除旧分录数据
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherbillid
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @voucherbillid

--替换临时BillNumberId为真实的
UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @voucherbillid WHERE BillNumberId = @newVoucherId
UPDATE dbo.Ac_Voucher_Bill_Assist_CheckItems SET BillNumberId = @voucherbillid WHERE BillNumberId = @newVoucherId
--------合并完成---------

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN	
	SET @Flag = -225
	
END

DECLARE @NoSummaryRow INT
SELECT  @NoSummaryRow = RowNo FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND ISNULL(Summary,'') = '' ORDER BY RowNo DESC
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='acsummary' AND SubValue = 1)--配置要求每行分录必有摘要时，检查明细是否符合
	AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND ISNULL(Summary,'') = '')
BEGIN
	SET @Flag = -224
END

IF @Flag <> 0
BEGIN
		SET @VoucherId = @VoucherBillId
		
		SELECT	BillDate,
			VgId,
			STypeId,
			FlowNo,
			CASE WHEN @BillType = 1 THEN -1 ELSE -2 END AS SBilltype,
			FComment
		FROM dbo.Ac_Voucher	
		WHERE BillNumberId = @VoucherBillId
		
		SELECT	a.Summary AS explain,
				b.UserCode,
				b.FullName,
				a.ATypeId AS typeid,
				ISNULL(c.Sysrow,1) AS sysrow,
				ISNULL(a.cid,1) AS cid,
				ISNULL(a.cid,1) AS moneytype,
				ISNULL(c.BasisType,0) AS BasisType,
				ISNULL(a.Rate,1) AS rate,
				CASE a.FAdc
					 WHEN 1		THEN ISNULL(a.FDebitTotalFor,0)
					 WHEN -1	THEN ISNULL(a.FCreditTotalFor,0)
				END AS balanceprice,
				CASE WHEN a.FDebitTotal = 0 THEN NULL ELSE FDebitTotal END AS lendprice,
				CASE WHEN a.FCreditTotal = 0 THEN NULL ELSE FCreditTotal END AS loanprice,
				a.FSettleNo,
				a.FSettleTypeID,
				a.Comment,
				a.STypeId,
				ISNULL(a.Fdc,a.fadc) AS fdc,
				a.FAdc,
				b.FAcnt,
				a.FCashFlowItem,
				a.RowNo,
				a.id,
				b.MainItems,
				b.AdditionItems,
				b.KeyId,
				ISNULL(b.IsCash,0) AS iscash,
				ISNULL(b.IsBank,0) AS isbank,
				b.IsDiary,
				ISNULL(b.IsOther,0) AS isother,
				b.TypeId,
				ISNULL(b.Cid,-1) AS mcid,
				b.mainitems AS mainitemsid,--主表项目id
				b.additionitems AS additionitemsid, --附表项目id
				d.fullname AS mainitemsname,--主表项目名称
				e.fullname AS additionitemsname,--附表项目名称
				dbo.F_GetAc_Assist_CheckItems_Str(a.BillNumberId,a.RowNo,'00001',1) AS assist,
				null AS asslist,
				a.FSettleNo AS balancenum,
				ISNULL(a.FSettleTypeID,0) AS balancetype,
				c.UserCode,
				c.FullName
		FROM dbo.Ac_Voucher_Bill a
			LEFT JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND b.StypeId = @verifyid
			LEFT JOIN dbo.Ac_Currency c ON a.Cid = c.CId
			LEFT JOIN dbo.Ac_CashMoneyItems d ON b.MainItems = d.TypeId
			LEFT JOIN dbo.Ac_CashMoneyItems e ON b.AdditionItems = e.TypeId
		WHERE BillNumberId = @VoucherBillId
		
		
		SELECT	DISTINCT a.nid,
				a.BillNumberId,
				a.vBId,
				a.typeName AS usercode,
				a.TypeId,
				CASE a.typeName
				WHEN '01' THEN (SELECT FullName FROM SType WHERE TypeId = a.TypeId)
				WHEN '02' THEN (SELECT FullName FROM Department WHERE TypeId = a.TypeId)
				WHEN '03' THEN (SELECT FullName FROM employee WHERE TypeId = a.TypeId)
				WHEN '04' THEN (SELECT FullName FROM BType WHERE TypeId = a.TypeId)
				END AS fullname,
				CASE a.typeName
				WHEN '01' THEN 'sfullname'
				WHEN '02' THEN 'dfullname'
				WHEN '03' THEN 'efullname'
				WHEN '04' THEN 'bfullname'
				END AS displayfield,
				CASE a.typeName
				WHEN '01' THEN 'stypeid'
				WHEN '02' THEN 'dtypeid'
				WHEN '03' THEN 'etypeid'
				WHEN '04' THEN 'btypeid'
				END AS datafield,
				b.AscIds AS value
		FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a
		INNER JOIN dbo.Ac_Assist_CheckItems b ON a.typeName = b.UserCode
		WHERE a.BillNumberId = @VoucherBillId
		
		--ROLLBACK TRAN Insert_Proc
		DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
		DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId
		DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherBillId
		
		RETURN @flag
END

--写入对照表
INSERT INTO dbo.Ac_Provision_Voucher
		( SourceId, SourceType, VoucherId )
VALUES  ( @Id,@BillType,@VoucherBillId)


DROP TABLE #tmpBillID,#tmpIDAscids,#tmpDetail,#tmpAssit,#tmpExpress,#tmpBill,#tmpRow
DROP TABLE #TmpVoucherDetails,#TempStr
DROP TABLE #TmpAssetTypeid,#tmpExpress_Bill,#tmpBillMoney_Bill,#tmpBillMoney
SET @szPID = '生成凭证成功！'

SELECT 0 AS error
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.06。28
	描述：固定资产单据214生成凭证
*/
CREATE PROCEDURE Gp_CreateVoucher_AssetsBill
(
	@Id				VARCHAR(MAX),			-- 单据编号
	@BillType		INT = 0,				-- 单据类型 214.折旧单
	@AtId			INT = 0,				-- 模板Id，0代表取单据默认模板
	@BillDate		DATE = '',				-- 凭证日期
	@Fyear			INT,					-- 年度
	@Fperiod		INT,					-- 期间
	@ETypeid		VARCHAR(50),			-- 职员
	@CreateType		INT = 0,				-- 0.Auto 1.Hand
	@szPID			VARCHAR(1000) OUTPUT,	-- 返回出错信息
	@VoucherID		INT,				-- 凭证ID 用于凭证标错使用
	@Type			INT	= 0,				-- 生成凭证结果处理方式
	@JustRep		INT = 0,					-- 0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@GoodsbillIds	VARCHAR(MAX)	OUTPUT	--生成凭证时金额不为0的业务单据id
)
--@encode$--
AS
SET NOCOUNT ON


SET @szPID = ''

--因为后面多次使用到SELECT a FROM dbo.f_split(@Id,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@Id,',')

--将模板明细处理到临时表中,进行读取字段生成摘要
-----------------------------------------------
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''

SELECT @MinNumber = MIN(a) FROM #BillNumberId
SELECT @MaxNumber = MAX(a) FROM #BillNumberId

SET @Index = @MinNumber

CREATE TABLE #TempStr
(
	RowNo		INT IDENTITY(1,1),
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)



WHILE @MinDid <= @MaxDid
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AtdId = @MinDid AND SummaryType='')
	BEGIN
		SET @MinDid += 1
		CONTINUE;
	END
	
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '

		SELECT @SqlSummary +=  'SELECT '+
			CASE Filed
				WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(MAX), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
				ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
			END
			 +'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
			CASE tablename 
				WHEN 'BillIndex' THEN ' T2 '
				WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
				WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
				WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
			END
			+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
			+' union all '
		FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		--SET @Index += 1
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	
	SELECT @str += summarystr + '  '
	FROM #TempStr

	IF @str <> ''
		SET @str += ';'
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	--SET @MinDid += 1
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END


-----------------------
--处理摘要完成

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID1		VARCHAR(50),
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT					--汇率计算方式
)

INSERT INTO #TmpBillInfo
        ( BillNumberId ,
          StypeId ,
          VerifyStypeid ,
          DTypeId ,
          BTypeId ,
          ETypeId,
          DealBTypeId ,
          ATypeID1,
          Cid ,
          Rate ,
          RateType
        )
SELECT  T1.BillNumberId,
		T1.Stypeid,
		T2.VerifyID,
		T1.DTypeId,
		T1.btypeid,
		T1.etypeid,
		T1.DealBTypeID,
		T1.ATypeID1,
		T1.CID,
		T1.Rate,
		T3.BasisType
FROM dbo.BillIndex T1
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
WHERE T1.BillNumberId IN (SELECT a FROM #BillNumberId)

DECLARE @Atdid INT
		,@Verifyid	VARCHAR(50)
		,@f_exchid	VARCHAR(50)

--获取往来科目模板行号
SELECT @Atdid = atdid FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND AcFrom = 3
SELECT TOP 1 @Verifyid = VerifyStypeid	FROM #TmpBillInfo
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

----统计单据金额字段----
CREATE TABLE #tmpAssetsBillMoney--折旧单采用这个
(
	DevalueReady		 NUMERIC(24, 10) 	DEFAULT 0,--计提减持金额
	Total				 NUMERIC(24, 10) 	DEFAULT 0,--资产卡片原值
	DepTotal			 NUMERIC(24, 10) 	DEFAULT 0, --资产卡片累计折旧值
	NetValue			 NUMERIC(24, 10) 	DEFAULT 0,--净值
	CardId				INT						  --卡片id
	,billnumberid		INT
)

CREATE TABLE #tmpBillMoney_Bill
(
	ac_balanceB 		 NUMERIC(24, 10) 	DEFAULT 0, --累计折旧额 ac_balanceB
	TaxTotal			 NUMERIC(24, 10) 	DEFAULT 0,--价税合计
	Total				 NUMERIC(24, 10) 	DEFAULT 0,--金额
	TotalInMoney		 NUMERIC(24, 10) 	DEFAULT 0, --实收\实付金额
	balancemoney		 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	cardtotal			 NUMERIC(24, 10) 	DEFAULT 0, --固定资产原值
	devalueready		 NUMERIC(24, 10) 	DEFAULT 0,--固定资产减值准备
	CardId				INT
	,billnumberid		INT
)

DECLARE @MinCarId	INT--为了防止世界被破坏。其实是为了防止billindex上取的金额翻倍，只将billindex上取的金额，如“收付款”更新到第一行


--科目来源AcFrom
--1 手工选择
--2 单据上收付款项目对应科目
--3 单据上往来科目
--5 固定资产
--9 累计折旧
--10 折旧分配
--11 固定资产减值准备科目
CREATE TABLE #tmpExpress
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) 
	,billnumberid	INT
)

CREATE TABLE #tmpExpress_Bill
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) ,
	CardId		INT,
	express		VARCHAR(1000)
	,billnumberid	INT
)


DECLARE @Sql	VARCHAR(MAX)	-- 动态SQL


--取固定资产卡片相应科目
--如果是单据，同时取出单据收付款、往来科目
CREATE TABLE #TmpAssetTypeid
(
	ATypeId		VARCHAR(50),
	Usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	Fdc			INT,
	Cid			INT,
	AtId		INT,
	AcFrom		INT,--科目来源
	CardId		INT,--卡片ID
	Item		VARCHAR(100)
	,billnumberid	INT
)

--生成凭证明细数据
CREATE TABLE #tmpBill
(
		acfrom			INT,
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rowno			INT		IDENTITY(1,1),
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		billindexid		INT,
		cardid			INT
)

	
	SELECT TOP 1 @Verifyid = verifyStypeid
	FROM #TmpBillInfo
	
	INSERT INTO #tmpAssetsBillMoney
			( DevalueReady,
			  Total,
			  DepTotal,
			  NetValue,
			  CardId
			  ,billnumberid
			)
	SELECT	CASE WHEN T3.RedWord = 2 THEN -SUM(T2.DevalueReady) ELSE SUM(T2.DevalueReady) END AS  DevalueReady,
			CASE WHEN T3.RedWord = 2 THEN -SUM(T2.Total)  ELSE SUM(T2.Total) END AS Total,
			CASE WHEN T3.RedWord = 2 THEN -SUM(T1.Depreciation) ELSE SUM(T1.Depreciation) END AS DepTotal,
			CASE WHEN T3.RedWord = 2 THEN -SUM(T2.NetValue) ELSE SUM(T2.NetValue) END AS NetValue,
			T2.Id
			,T1.BillNumberId
	FROM dbo.DepBill T1
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = T1.BillNumberId
		INNER JOIN dbo.Ac_AssetsCards T2 ON T1.AssetCardId = T2.Id
		INNER JOIN dbo.BillIndex T3 ON T1.BillNumberId = T3.BillNumberId
	---WHERE T1.BillNumberId = @CurrentID
	GROUP BY T1.BillNumberId, T2.Id,RedWord
	
	/*--SELECT @MinCarId = MIN(CardId) FROM #tmpBillMoney_Bill*/
	
	UPDATE #tmpBillMoney_Bill SET TotalInMoney= CASE WHEN T1.RedWord = 2 THEN -T1.totalinmoney ELSE T1.totalinmoney END 
	FROM dbo.BillIndex T1 
	INNER JOIN ( SELECT billnumberid,MIN(CARDID) AS MINCARDID
				FROM #tmpBillMoney_Bill
				GROUP BY billnumberid
				) T2 ON T2.billnumberid = T1.BillNumberId
	WHERE  #tmpBillMoney_Bill.CardId = T2.MINCARDID



	--读取模板要求的金额
	SET @sql = 'insert into #tmpExpress_Bill '

		SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId, ('+ Express +') as lendloan,'
						+'CardId,'''+cast(express AS varchar(1000))+''' as express
						,billnumberid '
		+' from #tmpAssetsBillMoney a'
		+' union all '
		FROM Ac_Auditing_Template_Detail
		WHERE Atid = @Atid

	IF LEN(@sql) > LEN('insert into #tmpExpress_Bill ')
	BEGIN
		SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
		EXEC(@sql)
	END
	
	--只保留一条平衡数记录
	DELETE FROM #tmpExpress_Bill WHERE express = 'balancemoney' AND CardId > ( SELECT MIN(CardId) FROM #tmpExpress_Bill WHERE express = 'balancemoney')
	
	SET @sql = 'SELECT  T1.BillNumberId,  
						T1.AssetCardId,
						T2.TypeId AS StypeId,
						T2.VerifyID,
						T1_1.AssertATypeId,
						T1_1.DepATypeId,
						T1_1.DisATypeId,
						T1_1.DevalueATypeId,
						T1_1.Id
				INTO #TmpTable
				FROM DepBill T1
				INNER JOIN #TmpBillInfo BB ON BB.billnumberid = T1.billnumberid
					INNER JOIN dbo.Ac_AssetsCards T1_1 ON T1.AssetCardId = T1_1.Id
					INNER JOIN dbo.SType T2 ON T1_1.Stypeid = T2.TypeId 
					'
	

		
	SET @sql +=
		'INSERT INTO #TmpAssetTypeid
		SELECT	T3.TypeId,
				T3.UserCode,
				T3.FullName,
				T3.Fdc,
				T3.cid,'+
				CAST(@Atid AS VARCHAR(10)) +' AS atid,
				5,
				T1.id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
				,t1.billnumberid
		FROM #TmpTable T1
		INNER JOIN dbo.Ac_Account T3 ON T1.AssertATypeId = T3.TypeId AND T1.VerifyID = T3.StypeId	--5
		WHERE T1.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+''''
		+
		'
		UNION ALL

		SELECT	T3.TypeId,
				T3.UserCode,
				T3.FullName,
				T3.Fdc,
				T3.cid,'+
				CAST(@Atid AS VARCHAR(10)) +' AS atid,
				9,
				T1.id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
				,t1.billnumberid
		FROM #TmpTable T1
		INNER JOIN dbo.Ac_Account T3 ON T1.DepATypeId = T3.TypeId AND T1.VerifyID = T3.StypeId		--9
		WHERE T1.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+''''
		+
		'
		UNION ALL

		SELECT	T3.TypeId,
				T3.UserCode,
				T3.FullName,
				T3.Fdc,
				T3.cid,'+
				CAST(@Atid AS VARCHAR(10)) +'AS atid,
				10,
				T1.id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
				,t1.billnumberid
		FROM #TmpTable T1
		INNER JOIN dbo.Ac_Account T3 ON T1.DisATypeId = T3.TypeId AND T1.VerifyID = T3.StypeId		--10
		WHERE T1.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+''''
		+
		'
		UNION ALL

		SELECT	T3.TypeId,
				T3.UserCode,
				T3.FullName,
				T3.Fdc,
				T3.cid,'+
				CAST(@Atid AS VARCHAR(10)) +'AS atid,
				11,
				T1.id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T3.TypeId))) AS Item
				,t1.billnumberid
		FROM #TmpTable T1
		INNER JOIN dbo.Ac_Account T3 ON T1.DevalueATypeId = T3.TypeId AND T1.VerifyID = T3.StypeId	--11
		WHERE T1.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50))+''''

		+
		'
		UNION ALL
		SELECT	T4.TypeId,
				T4.UserCode,
				T4.FullName,
				T4.Fdc,
				T4.Cid,
				'+CAST(@atid AS VARCHAR(10))+',
				2,
				T5.Id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T4.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T4.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T4.TypeId))) AS Item
				,t5.billnumberid
		FROM	dbo.BillMulAccount T1
			INNER JOIN #TmpTable T5 ON T1.BillNumberId = T5.BillNumberId AND T1.BillType='+CAST(@BillType AS VARCHAR(50))+'
			INNER JOIN dbo.Ac_Items T2 ON T1.ATypeID = T2.nId
			INNER JOIN dbo.Ac_Items_Detail T3 ON T2.nId = T3.nId AND T3.StypeId = t5.stypeid
			INNER JOIN dbo.Ac_Account T4 ON T3.ATypeId = T4.typeId AND T4.StypeId = '''+ CAST(@Verifyid AS VARCHAR(50))+'''
			 '
		+'

		UNION ALL
		SELECT	T2.TypeId,
				T2.UserCode,
				T2.FullName,
				T2.Fdc,
				T2.cid,
				'+CAST(@Atid AS VARCHAR(10)) + ' AS atid,
				3,
				T5.Id,
				SUBSTRING(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T2.TypeId),
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T2.TypeId))-1,
						LEN(dbo.F_Get_AscidsItem('''+CAST(@Verifyid AS VARCHAR(50))+''',T2.TypeId))) AS Item
				,t5.billnumberid
			FROM dbo.BillIndex T1
			INNER JOIN dbo.Ac_Account T2 ON T1.ATypeID1 = T2.TypeId 
			INNER JOIN #TmpTable T5 ON T1.BillNumberId = T5.BillNumberId AND T1.Stypeid = T5.STypeId AND T5.VerifyID = T2.StypeId
			WHERE T5.VerifyID = '''+CAST(@Verifyid AS VARCHAR(50)) + ''''
			
	SET @sql +=' DROP TABLE #TmpTable '
	
	EXEC(@sql)
	
	INSERT INTO #tmpBill
	( 
		acfrom,
		billnumberid ,
		explain ,
		atypeid ,
		atypeid2 ,
		Fdc ,
		f_exchid ,
		f_exchidfor ,
		lendprice ,
		loanprice ,
		lendpricefor ,
		loanpricefor ,
		FCashFlowItem ,
		ascids ,
		FSettleNo ,
		FSettleTypeID ,
		comment ,
		cid ,
		rate ,
		fadc ,
		stypeid ,
		fyear ,
		fperiod,
		atdid,
		billindexid,
		cardid
	)

	SELECT  T1.acfrom,
			@VoucherId AS billnumberid,
			Summary AS explain,
			CASE T1.AcFrom 
				WHEN 1 THEN	T1.ATypeId 
				ELSE T3.ATypeId
			END AS atypeid,
			'' AS atypeid2,
			CASE T1.AcFrom 
				WHEN 1 THEN T4.Fdc
				ELSE T3.Fdc
			END AS Fdc,
			@f_exchid AS f_exchid,
			@f_exchid AS f_exchidfor,
			CASE T1.Fdc 
				WHEN 1 THEN T2.lendloan
				ELSE 0 
			END AS lendprice,
			CASE T1.Fdc 
				WHEN -1 THEN T2.lendloan
				ELSE 0 
			END AS loanprice,
			CASE T1.Fdc 
				WHEN 1 THEN T2.lendloan
				ELSE 0 
			END AS lendpricefor,
			CASE T1.Fdc 
				WHEN -1 THEN T2.lendloan
				ELSE 0 
			END AS loanpricefor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			NULL AS FSettleTypeID,
			'' AS comment,
			@f_exchid AS cid,
			1 AS Rate,
			T1.Fdc AS fadc,
			@Verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			T1.AtdId,
			T2.billnumberid,
			T2.cardid
	FROM #TmpVoucherDetails T1
	LEFT JOIN #tmpExpress_Bill T2 ON T1.AtdId = T2.atdit
	LEFT JOIN #TmpAssetTypeid T3 ON T2.cardid = T3.cardid and t3.billnumberid = t2.billnumberid and  T1.AcFrom = T3.AcFrom
	LEFT JOIN Ac_account  T4 ON T1.ATypeId = T4.TypeId and T4.stypeid = @verifyid
	WHERE T1.atid = @Atid

--调整“平衡数”明细金额
DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) 

DECLARE BalanceCur CURSOR FOR
SELECT billnumberid FROM #TmpBillInfo
	OPEN BalanceCur
	FETCH NEXT FROM BalanceCur INTO @BalanceBillId
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @balancemoney = 0
	SELECT @balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
	FROM #tmpBill
	WHERE billindexid = @BalanceBillId

	
	UPDATE #tmpBill 
	SET #tmpBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
		#tmpBill.lendpricefor = (CASE fadc WHEN 1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN -@balancemoney / T3.rate
											WHEN 1 THEN -@balancemoney * T3.rate
										END
								ELSE 0 END ),
		#tmpBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
		#tmpBill.loanpricefor = (CASE fadc WHEN -1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN @balancemoney / T3.rate
											WHEN 1 THEN @balancemoney * T3.rate
										END
								ELSE 0 END )
	FROM #tmpBill T1
		INNER JOIN Ac_Auditing_Template_Detail T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
		INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
	WHERE billindexid = @BalanceBillId
		
	FETCH NEXT FROM BalanceCur INTO @BalanceBillId
END
CLOSE BalanceCur
DEALLOCATE BalanceCur

--去除金额为0的
DELETE FROM #tmpBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 


--排除数据全为0的单据编号
SELECT distinct BillIndexId
INTO #TmpBillNumberId
FROM #tmpbill WHERE lendprice <> 0 OR loanprice <> 0

--处理分录号
SELECT	billnumberid,
		explain,
		a.atypeid,
		atypeid2,
		a.Fdc,
		f_exchid,
		CASE WHEN b.cid = -1 THEN @f_exchid 
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0)= 0 THEN f_exchidfor 
			 ELSE b.Cid 
		END AS f_exchidfor,
		lendprice,
		loanprice,
		CASE WHEN b.cid = -1 THEN lendprice
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0)= 0 THEN lendpricefor
			 ELSE--取科目币种
				CASE c.BasisType --汇率计算方式
					WHEN 0 THEN lendprice / c.Rate
					ELSE lendprice * c.Rate
				END
		END AS lendpricefor,
		CASE WHEN b.cid = -1 THEN loanprice
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0) = 0 THEN loanpricefor
			 ELSE--取科目币种
				CASE c.BasisType --汇率计算方式
					WHEN 0 THEN loanprice / c.Rate
					ELSE loanprice * c.Rate
				END
		END AS loanpricefor,
		FCashFlowItem,
		a.ascids,
		FSettleNo,
		FSettleTypeID,
		a.comment,
		CASE WHEN b.cid = -1 THEN 1
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0) = 0 THEN a.rate
			 ELSE c.Rate
		END AS rate,
		IDENTITY(INT,1,1) AS RowNo,
		CASE WHEN b.cid = -1 THEN @f_exchid
			 WHEN b.Cid = a.cid OR ISNULL(b.cid,0) = 0 THEN a.cid
			 ELSE b.cid
		END AS cid,
		fadc,
		a.stypeid,
		fyear,
		fperiod,
		a.atdid,
		a.acfrom,
		cardid,
		billindexid
INTO #tmpRow
FROM 
(
	select T.*
	from
		(SELECT BillNumberId	,
			explain			,
			atypeid			,
			atypeid2		,
			Fdc				,
			f_exchid		,
			f_exchidfor		,
			SUM(lendprice)	AS lendprice,
			SUM(loanprice)	AS Loanprice,
			SUM(lendpricefor) AS lendpriceFor,
			SUM(loanpricefor) AS LoanpriceFor,
			FCashFlowItem	,
			ascids			,
			FSettleNo		,
			FSettleTypeID	,
			comment			,
			cid				,
			rate			,
			fadc			,
			stypeid			,
			fyear			,
			fperiod			,
			atdid			,
			acfrom,
			cardid,
			billindexid
		FROM #tmpBill
		GROUP BY BillNumberId,
			explain			,
			atypeid			,
			atypeid2		,
			Fdc				,
			f_exchid		,
			f_exchidfor		,
			FCashFlowItem	,
			ascids			,
			FSettleNo		,
			FSettleTypeID	,
			comment			,
			cid				,
			rate			,
			fadc			,
			stypeid			,
			fyear			,
			fperiod			,
			atdid			,
			acfrom,
			cardid,
			billindexid
		)T 
	WHERE lendprice <> 0 OR Loanprice <> 0
) as a
INNER JOIN Ac_Auditing_Template_Detail AT ON AT.AtdId = A.atdid
INNER JOIN Ac_Account AC ON AC.TypeId = A.atypeid AND AC.StypeId = A.stypeid
LEFT JOIN dbo.Ac_Account b ON a.stypeid = b.StypeId AND a.atypeid = b.TypeId
LEFT JOIN dbo.Ac_Currency c ON b.Cid = c.CId
ORDER BY AT.OrderID,A.fadc,AC.UserCode

--生成的凭证明细ID
CREATE TABLE #tmpBillID
(
	rowno	INT ,
	id		INT,
	atypeid	VARCHAR(50)
)

----正式插入明细----
INSERT INTO dbo.Ac_Voucher_Bill
( 
	BillNumberId,
	Summary ,
	ATypeId ,
	ATypeId2 ,
	Fdc ,
	F_ExchId ,
	F_ExchIdFor ,
	FDebitTotal ,
	FCreditTotal ,
	FDebitTotalFor ,
	FCreditTotalFor ,
	FCashFlowItem ,
	AscIds ,
	FSettleNo ,
	FSettleTypeID ,
	Comment ,
	Cid ,
	RowNo ,
	Rate ,
	FAdc ,
	STypeId ,
	FYear ,
	FPeriod
)
OUTPUT INSERTED.rowno,INSERTED.ID,INSERTED.atypeid INTO #tmpBillID
SELECT	billnumberid,
		explain,
		ISNULL(atypeid,''),
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		dbo.F_RoundTotal(lendprice),
		dbo.F_RoundTotal(loanprice),
		dbo.F_RoundTotal(lendpricefor),
		dbo.F_RoundTotal(loanpricefor),
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		RowNo,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod
FROM #tmpRow
ORDER BY AtdId

--生成凭证与辅助对应关系
--非手工选择的科目来源，设置辅助核算的话必须全部设置，这样只要科目有辅助核算就肯定取得到值
SELECT DISTINCT id,e.Ascids,f.UserCode,h.FieldValue,b.acfrom,b.cardid,b.billindexid
INTO #tmpIDAscids
FROM #tmpBillID a
INNER JOIN #tmpRow b ON a.rowno = b.rowno
INNER JOIN dbo.Ac_Auditing_Template_Detail c ON b.atdid = c.AtdId
INNER JOIN dbo.Ac_Account d ON a.atypeid = d.TypeId
INNER JOIN dbo.Ac_Account_Assist_CheckItems e ON (d.TypeId = e.ATypeId AND d.StypeId = e.STypeId)
INNER JOIN dbo.Ac_Assist_CheckItems f ON e.Ascids = f.AscIds
INNER JOIN dbo.Ac_Auditing_Template_Detail_Assist_CheckItems g ON (e.Ascids = g.AscIds AND b.atdid = g.AtdId)
INNER JOIN dbo.Ac_Assist_CheckItems_BillType h ON g.AscIds = h.AscIds AND h.nId = g.AscIdsDetailId
WHERE d.StypeId = @Verifyid AND h.BillType = @Billtype


--单据用于凭证辅助核算的具体的字段值
CREATE TABLE #tmpDetail
(
	fieldvalue	VARCHAR(50),
	id			INT,
	fieldname	VARCHAR(50),
	acfrom		INT,
	cardid		INT
)

DECLARE @sql2 VARCHAR(MAX)
SET @sql2 = 'SELECT T2.*
		INTO #Tmp
		FROM DepBill T1
		LEFT JOIN BillIndex T2 ON T1.billnumberid = T2.billnumberid
		where T1.billnumberid in (select * from f_split(''' + CAST(@Id AS varchar(1000)) + ''','','') ) '
		
SET @sql2 += 'insert into #tmpDetail '


SELECT @sql2 +=  'select '+ cast(FieldValue AS varchar(50))+ ',' + 
			CAST(id AS varchar(50)) +' as id, (SELECT name FROM syscolumns WHERE id = object_id(''BillIndex'') AND name = '''+
			cast(FieldValue AS varchar(50))+''')as filedname,' +cast(acfrom AS varchar(50)) +' as acfrom,'+ cast(cardid AS varchar(50)) +' as cardid 
				FROM #Tmp
				where billnumberid = '+cast(BillIndexid as varchar)+'
				union all '
FROM #tmpIDAscids
	
IF LEN(@sql2) > LEN('SELECT T2.*
		INTO #Tmp
		FROM DepBill T1
		LEFT JOIN BillIndex T2 ON T1.billnumberid = T2.billnumberid
		where T1.billnumberid in (select * from f_split(''' + CAST(@Id AS varchar(1000)) + ''','','') ) '+'insert into #tmpDetail ')
BEGIN
	SET @sql2 = SUBSTRING(@sql2,1,LEN(@sql2)-9)
	EXEC(@sql2)
END

DELETE FROM #tmpDetail WHERE ISNULL(fieldvalue,'')=''

IF @BillType = 214    --折旧单部门取明细部门值
BEGIN
	UPDATE T1 
	SET fieldvalue = 
		CASE WHEN T1.fieldname = 'stypeid' THEN T2.STypeId 
			 WHEN T1.fieldname = 'dtypeid' THEN T3.DTypeid
			 WHEN T1.fieldname = 'etypeid' THEN T1.fieldvalue
			 WHEN T1.fieldname = 'btypeid' THEN T1.fieldvalue
		END 
	FROM #tmpDetail T1 
	INNER JOIN DepBill T3 ON T3.AssetCardId = T1.cardid
	INNER JOIN dbo.Ac_AssetsCards T2 ON T2.Id =T1.cardid 
	INNER JOIN #tmpIDAscids T4 ON T4.billindexid = T3.BillNumberId
END
ELSE     ----来自卡片的科目辅助核算‘分支机构’ ‘部门’按卡片上的来
BEGIN
	UPDATE #tmpDetail 
	SET fieldvalue = 
		CASE WHEN T1.fieldname = 'stypeid' THEN T2.STypeId 
			 WHEN T1.fieldname = 'dtypeid' THEN T2.DTypeid
			 WHEN T1.fieldname = 'etypeid' THEN T1.fieldvalue
			 WHEN T1.fieldname = 'btypeid' THEN T1.fieldvalue
		END 
	FROM #tmpDetail T1 
	INNER JOIN dbo.Ac_AssetsCards T2 ON T1.cardid = T2.Id
	WHERE T1.acfrom IN (5,9,10,11) 
END

--插入辅助核算值
SELECT	DISTINCT @VoucherId AS billnumberid,
		a.id AS vBId,
		a.UserCode AS typeName,
		b.fieldvalue AS TypeId
INTO	#tmpAssit
FROM #tmpIDAscids a INNER JOIN #tmpDetail b ON a.id = b.id AND a.FieldValue=b.fieldname
WHERE ISNULL(b.fieldvalue,'') <> ''


INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
( 
	BillNumberId ,
	vBId ,
	typeName ,
	TypeId
)
SELECT	*
FROM	#tmpAssit


--更新凭证明细中辅助核算字段值信息
UPDATE dbo.Ac_Voucher_Bill SET AscIds= dbo.F_Get_VoucherAscids(id,1) WHERE BillNumberId = @VoucherId


--合并信息相同的明细，采用合并插入后再删除原来的凭证--
DECLARE @newVoucherId INT --临时BillNumberId
SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

SELECT	billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FCreditTotal,
		FDebitTotalFor,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		IDENTITY(INT,1,1) AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill
FROM
(
SELECT  @newVoucherId AS billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		SUM(FDebitTotal) AS FDebitTotal,
		SUM(FCreditTotal) AS FCreditTotal,
		SUM(FDebitTotalFor) AS FDebitTotalFor,
		SUM(FCreditTotalFor) AS FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod,
		MIN(rowno) AS initRowno
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @VoucherId
GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod
)TT
ORDER BY initRowno

--去除金额为0的
DELETE FROM #tmpNewVoucherBill WHERE ISNULL(FDebitTotal,0) = 0  AND ISNULL(FCreditTotal,0) = 0 

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
SELECT  billnumberid,
		Summary ,
		STypeId ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FDebitTotalFor,
		FCreditTotal,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		FYear ,
		FPeriod,
		Comment ,
		Cid ,
		rowno,
		Rate ,
		FAdc
FROM #tmpNewVoucherBill

--删除旧分录数据
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId

--替换临时BillNumberId为真实的
UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @VoucherId WHERE BillNumberId = @newVoucherId
--------合并完成---------

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN	
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '') = 1--其他行有一个摘要，调整摘要
	BEGIN
		UPDATE dbo.Ac_Voucher_Bill SET Summary = 
					(SELECT Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> '')
				WHERE BillNumberId = @VoucherId
		UPDATE dbo.Ac_Voucher_Bill SET Summary = '' WHERE BillNumberId = @VoucherId AND RowNo <> 1 AND Summary <> ''
	END
	ELSE
	BEGIN
		CREATE TABLE #TmpSummry
		(
			rowno	INT IDENTITY(1,1),
			summary	VARCHAR(400)	
		)
		
		INSERT INTO #TmpSummry( summary )
		SELECT summary
		FROM #TmpVoucherDetails
		WHERE atid = @atid AND Summary <> ''
		ORDER BY AtdId
		
		
		UPDATE dbo.Ac_Voucher_Bill SET Summary = b.summary  FROM dbo.Ac_Voucher_Bill a INNER JOIN #TmpSummry b ON a.RowNo = b.rowno WHERE a.BillNumberId = @VoucherId	
	END
END

SET @GoodsbillIds = ''
SELECT	@GoodsbillIds += CAST(billindexid AS VARCHAR) + ','
FROM	#TmpBillNumberId

DROP TABLE #tmpBillID,#tmpIDAscids,#tmpDetail,#tmpAssit,#tmpExpress,#tmpBill,#tmpRow
DROP TABLE #TmpVoucherDetails,#TempStr
DROP TABLE #TmpAssetTypeid,#tmpExpress_Bill,#tmpBillMoney_Bill,#tmpAssetsBillMoney
DROP TABLE #TmpBillNumberId,#BillNumberId

	
RETURN @VoucherId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.06.27
	描述：生成凭证时，合并相同的凭证明细
*/
CREATE PROCEDURE GP_CreateVoucher_MergeDetails
(
	@voucherBillId	INT--原始凭证id
)
--@encode$--
AS
SET NOCOUNT ON


--Tips：合并信息相同的明细，采用合并插入后再删除原来的凭证--
DECLARE @newVoucherId INT --临时BillNumberId
SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

SELECT	billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FCreditTotal,
		FDebitTotalFor,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		initRowno AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill_Before
FROM
(
SELECT  @newVoucherId AS billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		SUM(FDebitTotal) AS FDebitTotal,
		SUM(FCreditTotal) AS FCreditTotal,
		SUM(FDebitTotalFor) AS FDebitTotalFor,
		SUM(FCreditTotalFor) AS FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod,
		MIN(rowno) AS initRowno
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @voucherBillId
GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod
)TT
ORDER BY initRowno



SELECT	billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FCreditTotal,
		FDebitTotalFor,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		IDENTITY(INT,1,1) AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill
FROM #tmpNewVoucherBill_Before WHERE FDebitTotal <> 0 OR FCreditTotal <> 0


--用于记录明细ID，插入辅助核算使用
CREATE TABLE #tmpId
(
	id INT,
	ascids VARCHAR(500)
)

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.AscIds INTO #tmpId
SELECT  billnumberid,
		Summary ,
		STypeId ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		FDebitTotal,
		FDebitTotalFor,
		FCreditTotal,
		FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		FYear ,
		FPeriod,
		Comment ,
		Cid ,
		rowno,
		Rate ,
		FAdc
FROM #tmpNewVoucherBill


--辅助核算
INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
			( BillNumberId ,
			  vBId ,
			  typeName ,
			  TypeId
			)
SELECT DISTINCT	@newVoucherId,
		c.id,
		typeName,
		TypeId  
FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
INNER  JOIN dbo.Ac_Voucher_Bill b ON a.vBId = b.ID
INNER JOIN #tmpId c ON b.AscIds = c.ascids
WHERE a.BillNumberId = @voucherbillid


--更新表头分录数
UPDATE dbo.Ac_Voucher SET FEntryCount = (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherbillid)

--删除旧分录数据
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherbillid
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @voucherbillid

--替换临时BillNumberId为真实的
UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @voucherbillid WHERE BillNumberId = @newVoucherId
UPDATE dbo.Ac_Voucher_Bill_Assist_CheckItems SET BillNumberId = @voucherbillid WHERE BillNumberId = @newVoucherId
--------合并完成---------

----修正明细摘要----
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND RowNo = 1 AND Summary <> '')--第一行没有摘要
BEGIN	
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherBillId
	RETURN -225
END

DECLARE @NoSummaryRow INT
SELECT  @NoSummaryRow = RowNo FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND ISNULL(Summary,'') = '' ORDER BY RowNo DESC
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='acsummary' AND SubValue = 1)--配置要求每行分录必有摘要时，检查明细是否符合
	AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND ISNULL(Summary,'') = '')
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherBillId
	RETURN -224
END

DROP TABLE #tmpNewVoucherBill_Before,#tmpNewVoucherBill,#tmpId

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GP_CustomerSellStat]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].GP_CustomerSellStat
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*------------------------------------------
 作者：	蒋奎
 日期：	2014-6-17
 描述：	跨帐套查询-客户销售统计-数据源获取				
 思路:	C#多线程会遍历这个存储过程,遍历一次出一个帐套的客户销售明细数据到@tbName临时表
-------------------------------------------*/
CREATE PROCEDURE GP_CustomerSellStat
(
	@accconstr  VARCHAR(1000),		--一个帐套的连接字符串
	/*@stypeid	VARCHAR(max)='',	--分支机构
	@ptypeid	VARCHAR(MAX)='',	--商品id
	@btypeid	varchar(1550)='',	--结算单位
	@dealbtypeid VARCHAR(1550)='',	--往来单位
	@ktypeid	varchar(1550)='',*/	--仓库名称
	@startdate  VARCHAR(30),		--查询起始时间
	@enddate	VARCHAR(30),		--查询结束时间
	@reportname VARCHAR(50),		--报表类型，SA_CustomerSellStat客户销售
	@tbName		VARCHAR(100),		--临时表名
	@ruletype		INT,			--规则类型: 0=系统规则,1=自定义规则的编码, 2=自定义规则的名称 , 3=自定义规则的编码和名称
	@pid		VARCHAR(max)='',
	@pusercode	VARCHAR(max)='',
	@pfullname	VARCHAR(max)='',
	@bid		VARCHAR(max)='',
	@busercode	VARCHAR(max)='',
	@bfullname	VARCHAR(max)='',
	@sid		VARCHAR(max)='',
	@susercode	VARCHAR(max)='',
	@sfullname	VARCHAR(max)='',
	@kid		VARCHAR(max)='',
	@kusercode	VARCHAR(max)='',
	@kfullname	VARCHAR(max)='',
	@dealid		VARCHAR(max)='',
	@dealusercode	VARCHAR(max)='',
	@dealfullname	VARCHAR(max)='',
	@showway			VARCHAR(30)	--统计方式 full全部，season 按季度 year 按年度

)
--@encode$--

AS
BEGIN
SET NOCOUNT ON 
	
	--将Selector选择的基本信息,根据合并规则从查询帐套出数据到临时表-----开始------------------------------
	
	CREATE TABLE #Ptype (TypeID varchar(50) )
	CREATE TABLE #Btype (TypeID varchar(50))
	CREATE TABLE #DealBtype (TypeID varchar(50),bID INT,usercode VARCHAR(200),fullname VARCHAR(200))
	CREATE TABLE #Ktype (TypeID varchar(50))
	CREATE TABLE #Stype (TypeID varchar(50))
	
	DECLARE @BaseInfoSql VARCHAR(max)

	IF @ruletype=0 --系统规则
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pid+''','','') WHERE ISNULL(A,'''')<>'''' AND pid=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@bid+''','','') WHERE ISNULL(A,'''')<>'''' AND bid=a
		INSERT INTO #DealBtype  SELECT  typeid,bid,usercode,FullName FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealid+''','','') WHERE ISNULL(A,'''')<>'''' AND bid=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kid+''','','') WHERE ISNULL(A,'''')<>'''' AND kid=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@sid+''','','') WHERE ISNULL(A,'''')<>'''' AND sid=a  '
	END
	IF @ruletype=1 --自定义规则的编码
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@busercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #DealBtype  SELECT   typeid,bid,usercode,FullName FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@susercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a  '
	END
	IF @ruletype=2 --自定义规则的名称
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@bfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #DealBtype  SELECT  typeid,bid,usercode,FullName FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@sfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a  '
	END
	IF @ruletype=3 --自定义规则的编码和名称
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype 
		SELECT   typeid
		FROM '+@accconstr+'.dbo.ptype p, f_split('''+@pusercode+''','','') u,f_split('''+@pfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND p.UserCode=u.a AND p.FullName=f.a
		
		INSERT INTO #Btype SELECT  typeid 
		FROM '+@accconstr+'.dbo.btype b, f_split('''+@busercode+''','','') u,f_split('''+@bfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND b.UserCode=u.a AND b.FullName=f.a
		
		INSERT INTO #DealBtype 
		SELECT  typeid,bid,usercode,FullName  
		FROM '+@accconstr+'.dbo.btype b, f_split('''+@dealusercode+''','','') u,f_split('''+@dealfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND b.UserCode=u.a AND b.FullName=f.a
		
		INSERT INTO #Ktype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.Stock k, f_split('''+@kusercode+''','','') u,f_split('''+@kfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND k.UserCode=u.a AND k.FullName=f.a
		
		INSERT INTO #Stype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.SType s, f_split('''+@susercode+''','','') u,f_split('''+@sfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND s.UserCode=u.a AND s.FullName=f.a	'
	END
	--PRINT @BaseInfoSql
	EXEC (@BaseInfoSql)

	--如果#ptype里面没有数据(说明没有Selector数据),就直接从帐套出数据到#ptype
	
    IF NOT EXISTS(SELECT TOP 1 1 FROM #DealBtype)
    BEGIN
    SET @BaseInfoSql='
		INSERT INTO #DealBtype 
		SELECT  typeid,bid,usercode,FullName 
		FROM  '+@accconstr+'.dbo.btype 
		WHERE sonnum=0   '
    END
	EXEC(@BaseInfoSql)
	
	--将Selector选择的基本信息,根据合并规则从帐套出数据到临时表-----结束------------------------------

	--时间字段处理
	DECLARE @sql VARCHAR(max)='',		--拼接sql
			@insertColumn VARCHAR(50),	--插入列
			@selectColumn VARCHAR(200)	--选择列

	IF @showway = 'full'	--所有
	BEGIN
		SET @insertColumn =''
		SET @selectColumn =''
	END
	IF @showway = 'season'	--季度
	BEGIN
		SET @insertColumn = 'timeType,'
		SET @selectColumn = 'CAST(YEAR(bi.BillDate) AS VARCHAR(10))+ CAST(DATEPART(qq,bi.BillDate) AS VARCHAR(10)),'
	END
	IF @showway = 'year'	--年
	BEGIN
		SET @insertColumn = 'timeType,'
		SET @selectColumn = 'YEAR(bi.BillDate),'
	END 
	

	SET @selectColumn=@selectColumn+'bi.dealbtypeid'	--客户Id
		
	
	
	--主数据 --> 从出入库表和单据主索引表里面出商品的销售明细
	
	SELECT @sql+='	INSERT INTO ['+@tbName+'] ('+@insertColumn+'TypeID,usercode,fullname,basicunit,isgift,Qty,Total,SaleTotal,TaxTotal,CostTotal,ProtectTotal,Advantagetotal,ShareFee,xid) 
					SELECT  
						'+@selectColumn+',
						d.usercode,
						d.fullname,
						basicunit='' '',
						a.isgift,
						-a.qty,
						-a.total,
						-a.SaleTotal,
						-a.TaxTotal,
						-a.CostTotal,
						ProtectTotal =0,
						Advantagetotal=0,
						-a.sharefee,
						d.bid	
					FROM '+@accconstr+'.dbo.InoutStockTable a
					INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId  
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Ptype)
			SELECT @sql=@sql+' 	INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%''  '
				
		IF EXISTS(SELECT TOP 1 1 FROM #Btype)
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype) --AND @dealbtypeid NOT IN('00001','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Ktype)
			SELECT @sql=@sql+'	INNER JOIN #Ktype k ON a.KTypeID like k.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE a.BillDate >= '''+@startdate+''' AND a.BillDate<='''+@enddate+''' 
				AND a.IsGift = 0  AND BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND a.billtype in(305,215,11,45,160,141,12,46)
					     '


	--价保 -->只出价保数据其它的不出
	CREATE TABLE #ProtectTotal
	(
		typeid VARCHAR(50),
		ProtectTotal  NUMERIC(24, 10) 
	)
	SELECT @sql+='	INSERT INTO ['+@tbName+'] ('+@insertColumn+'TypeID,usercode,fullname,basicunit,isgift,Qty,Total,SaleTotal,TaxTotal,CostTotal,ProtectTotal,Advantagetotal,ShareFee,xid) 
					SELECT  
						'+@selectColumn+',
						d.usercode,
						d.fullname,
						basicunit='' '',
						isgift=0,
						qty=0,
						total=0,
						SaleTotal=0,
						TaxTotal=0,
						CostTotal=0,
						ProtectTotal=sum(a.total), 
						Advantagetotal=0,
						sharefee=0,	
						d.bid	
					FROM '+@accconstr+'.dbo.PriceProtectBill a 
				INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
				INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Btype)
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype) --AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE bi.BillDate >= '''+@startdate+''' AND bi.BillDate<='''+@enddate+''' 
				AND  BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND bi.billtype=149
				GROUP BY 
						'	+@selectColumn+',
							d.bid,
							d.usercode,
							d.fullname
						'
	 

	
	--返利 -->只出返利数据其它的不出
	CREATE TABLE #Advantagetotal
	(
		typeid VARCHAR(50),
		Advantagetotal  NUMERIC(24, 10) 
	)
	SELECT @sql+='	INSERT INTO ['+@tbName+'] ('+@insertColumn+'TypeID,usercode,fullname,basicunit,isgift,Qty,Total,SaleTotal,TaxTotal,CostTotal,ProtectTotal,Advantagetotal,ShareFee,xid) 
					SELECT  
						'+@selectColumn+',
						d.usercode,
						d.fullname,
						basicunit='' '',
						isgift=0,
						qty=0,
						total=0,
						SaleTotal=0,
						TaxTotal=0,
						CostTotal=0,
						ProtectTotal=0,
						Advantagetotal=sum(a.total), 
						sharefee=0,	
						d.bid
					FROM '+@accconstr+'.dbo.Advantage a 
					INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
					INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
				 '
		IF EXISTS(SELECT TOP 1 1 FROM #Btype) 
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype) --AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE bi.BillDate >= '''+@startdate+''' AND bi.BillDate<='''+@enddate+''' 
				AND  BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND bi.billtype=148
				GROUP BY 
						'	+@selectColumn+',
							d.bid,
							d.usercode,
							d.fullname
						'
	
		
				
	--PRINT (@sql)				
	EXEC(@sql)
				
END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:彭勇
	日期：2016-01-28
	描述：参照计划提成规则复制新增
*/
CREATE PROCEDURE Gp_CZCopyAddBill
(
	 @BillNumberId  INT,
	 @UserTypeid	VARCHAR(100)=''		--制单人
	
)
--@encode$--
AS
SET NOCOUNT ON
INSERT  INTO ReferencePlanCommission
        ( BillCode ,
          FullName ,
          BillDate ,
          PlanStart ,
          PlanEnd ,
          CommissionStandard ,
          Checke ,
          Checker ,
          CheckeTime ,
          CheckerTime ,
          Comment ,
          BillState ,
          UseState ,
          IsStop ,
          SalePlanID
        )
        SELECT  BillCode + '【copy】' BillCode ,
                FullName ,
                BillDate ,
                PlanStart ,
                PlanEnd ,
                CommissionStandard ,
                @UserTypeid ,
                '',
                getdate() ,
                '' ,
                Comment ,
                1 ,
                1 ,
                IsStop ,
                SalePlanID
        FROM    ReferencePlanCommission
        WHERE   BillNumberId = @billnumberid
        
DECLARE @id INT
SELECT  @id = MAX(billnumberid)
FROM    ReferencePlanCommission


 
INSERT  INTO ReferencePlanCommissionEtype
        ( BillNumberId ,
          EtypeID
            
        )
        SELECT  @id ,
                EtypeID
        FROM    dbo.ReferencePlanCommissionEtype
        WHERE   BillNumberId = @BillNumberId 
INSERT  INTO ReferencePlanCommissionPlan
        ( BillNumberId ,
          EtypeID ,
          Proportion ,
          MaxRegion ,
          MinRegion ,
          IsCalculation,
          Percentage          
        )
        SELECT  @id ,
                EtypeID ,
                Proportion ,
                MaxRegion ,
                MinRegion ,
                IsCalculation  ,
                Percentage
        FROM    dbo.ReferencePlanCommissionPlan
        WHERE   BillNumberId = @BillNumberId 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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


/****** Object:  StoredProcedure [dbo].[Gp_InsertP]    Script Date: 05/17/2011 20:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
----========================
----修改者：黄清	
----日期：2013-07-08
----描述:信息更新后处理pos下载需要数据
----========================
CREATE	PROCEDURE [dbo].[Gp_DataSaveForPosDown]
(
	@stypeid		VARCHAR(50)='-99999',	--分支机构id
	@dbname			VARCHAR(200),	--基本信息表名
	@baseinfoid		VARCHAR(100)		--基本信息id，非删除操作是为0
)
--@encode$--
AS
SET NOCOUNT ON

--没有启用POS不处理
IF NOT EXISTS (SELECT 1 FROM Userconfig WHERE ConfigName='IsPosStart' AND Value='1')
	RETURN

DELETE FROM PosReDataGlobal WHERE STYPEID=@stypeid
INSERT INTO PosReDataGlobal (STYPEID,ifReData) VALUES(@stypeid,1)

IF @baseinfoid IS NULL
	RETURN

DELETE FROM PosIsUpdateData WHERE stypeid=@stypeid AND tbType=@dbname AND Tid=@baseinfoid
INSERT INTO PosIsUpdateData (tbType,Tid,ifUpdate,stypeid) VALUES(@dbname,@baseinfoid,'1',@stypeid)

--IF @dbname='ptype' AND @baseinfoid<>'0'
--BEGIN
--	DECLARE @XiWaMaxNumber numeric(18,0)
--	SELECT @XiWaMaxNumber = Max(XiWaMaxNumber) FROM PType
--	UPDATE PosUpdatedMaxNumber
--	SET XiWaMaxNumber=@XiWaMaxNumber
--	WHERE Stypeid=@stypeid
--	AND TableName=@dbname
--	AND XiWaMaxNumber>@XiWaMaxNumber
--END


GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
    年结处理内部应收
*/						
CREATE   PROCEDURE GP_DateTime_Stype_InnerARTotal
(
	@yearendDatetime VARCHAR(20)			--   -年结存的日期		
)
--@encode$--
AS	
	CREATE TABLE  #Stype_InnerARTotal
	(
		[STypeID] [varchar](50),
		[STypeID2] [varchar](50) ,
		[InnerARTotal00] [numeric](24, 10) ,
		[InnerARTotal] [numeric](24, 10),
	)
	INSERT INTO #Stype_InnerARTotal
	(
		[STypeID] ,
		[STypeID2] ,
		[InnerARTotal] 
	)
	SELECT a.STypeID ,
           a.STypeID2 ,
           SUM(a.Total) 
	FROM 
	(
		SELECT stypeid,STypeID2,Total FROM dbo.ListTable WHERE atypeid=28 AND stypeid2 <> '' AND billdate <@yearendDatetime 
		UNION ALL
		SELECT b.Stypeid,s.STypeID,CASE WHEN b.BillType = 187 THEN b.totalmoney ELSE -b.totalmoney END AS total 
		FROM dbo.BillIndex b
		INNER JOIN dbo.Stock s ON s.typeId = CASE WHEN b.BillType = 187 THEN b.ktypeid2 ELSE b.ktypeid END 
		WHERE b.RedWord = 0 AND b.ifcheck = 't' AND b.BillType IN(187,188) AND b.billdate <@yearendDatetime
	) a
	GROUP BY a.Stypeid,a.STypeID2
	
	UPDATE b 
	SET  b.InnerARTotal00=b.InnerARTotal00+a.InnerARTotal
	FROM SType_InnerARTotal b
	INNER JOIN  #Stype_InnerARTotal a ON a.STypeID=b.STypeID AND a.STypeID2=b.STypeID2
	
	--INSERT INTO SType_InnerARTotal
	--(
	--	[STypeID] ,
	--	[STypeID2] ,
	--	[InnerARTotal00] 
	--)
	--SELECT   [STypeID] ,[STypeID2] ,[InnerARTotal00] 
	--FROM #Stype_InnerARTotal a
	--WHERE NOT EXISTS (SELECT 1 FROM SType_InnerARTotal b WHERE a.STypeID=b.STypeID AND a.STypeID2=b.STypeID2  )
	--DELETE FROM SType_InnerARTotal WHERE InnerARTotal=0 AND InnerARTotal00=0
	--DROP TABLE #Stype_InnerARTotal


	IF @@ERROR>0
	RETURN -1;
	
	ELSE
	RETURN 0;
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波


红冲的其他处理

*/
CREATE   PROCEDURE Gp_Deal_All 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nNewBillID			numeric(10,0)
)
--@encode$--
AS

DECLARE
	@decTempMoney				 NUMERIC(24, 10) ,
	@decTempTotalMoney			 NUMERIC(24, 10) ,
	@strTempATypeID				VARCHAR(100),
	@numTotalMoney				 NUMERIC(24, 10) ,
	@numTotalInMoney			 NUMERIC(24, 10) ,
	@decOtherTotal 				 NUMERIC(24, 10) ,
	@intVipJF					INT,
	@chvVipIsCz  				VARCHAR(10),
	@chrIfVipJF					VARCHAR(10),
	@intVipCardID				INT,
	@strRepairItemsTypeID		VARCHAR(100),
	@intQuickRepairBillID		INT,
	@intQuickRepairBillType		INT,
	@intTempID					INT,
	@intTotalJF					INT,
	@curJF						 NUMERIC(24, 10) ,
	@strInnerAR					VARCHAR(50),				--内部应收
	@decInnerAR					 NUMERIC(24, 10) ,
	@strErrMsg					VARCHAR(500),
	@numJTotal					 NUMERIC(24, 10) ,
	@numDTotal					 NUMERIC(24, 10) 

	DECLARE		@GoodsBillNumberID INT,					/*出库单单据编号*/
				@GoodsBillID	   INT,					/*出库单明细ID*/
				@GoodsBillType     INT,					/*出库单单据类型*/
				@RowIndex          INT,					
				@RowCount          INT,					/*运输单明细行数*/
				@Qty			   NUMERIC(24,10),		/*发货数量*/
				@Return            INT,					/*返回值*/
				@TbName            VARCHAR(100),		/*出库单明细表	*/
				@UpdateSQL		   NVARCHAR(MAX),		/*更新发货数量SQL*/
				@CheckSQL          NVARCHAR(MAX)		/*验证发货数量SQL*/
	DECLARE	    @Tmp			   TABLE
	(
		Qty				  NUMERIC(24,10),
		GoodsBillNumberID INT,
		GoodsBillID       INT,
		GoodsBillType     INT,
		RowIndex          INT
	)
	
SELECT @strInnerAR=nid FROM dbo.Ac_Items WHERE FullName='内部应收'


IF @nBillType  = 11
BEGIN	-- 销售出库
	UPDATE	OrderBill
	SET		
			ReachQty = ReachQty - a.Qty,
			ReachTotal=ReachTotal-a.Total,
			ReachTaxTotal=ReachTaxTotal-a.TaxTotal
	FROM	(
				SELECT BillNumberID,OrderID,
				SUM(Qty) AS Qty,SUM(Total) AS Total,SUM(TaxTotal) AS TaxTotal
				FROM SaleBill WHERE BillNumberID = @nBillID
				GROUP BY OrderID,BillNumberID
			) a,
			OrderBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OrderID = b.OrderID
			AND b.Qty > 0
			AND b.ReachQty >= a.Qty
			
	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney - a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID			
	
	--更新对应会员卡本年消费,累计消费
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney - a.TotalMoney,
			bNxFMoney=b.bNxFMoney-a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId
	
END
ELSE IF @nBillType  = 12
BEGIN	-- 组合品销售出库
	UPDATE	PT_Combin_OrderBillDetail
	SET		
			ReachQty = ReachQty - a.Qty,
			ReachTotal=ReachTotal-a.Total,
			ReachTaxTotal=ReachTaxTotal-a.TaxTotal
	FROM	(
				SELECT BillNumberID,OrderID,
				SUM(Qty) AS Qty,SUM(Total) AS Total,SUM(TaxTotal) AS TaxTotal
				FROM PT_Combin_SaleBillDetail WHERE BillNumberID = @nBillID
				GROUP BY OrderID,BillNumberID
			) a,
	PT_Combin_OrderBillDetail b
	WHERE	a.BillNumberID = @nBillID
			AND a.OrderID = b.OrderID
			AND b.Qty > 0
			AND b.ReachQty >= a.Qty
			
			
	UPDATE	PT_Combin_OrderBill
	SET		
			ReachQty = ReachQty - a.Qty,
			ReachTotal=ReachTotal-a.Total,
			ReachTaxTotal=ReachTaxTotal-a.TaxTotal
	FROM	(
				SELECT BillNumberID,OrderID,
				SUM(Qty) AS Qty,SUM(Total) AS Total,SUM(TaxTotal) AS TaxTotal
				FROM PT_Combin_SaleBill WHERE BillNumberID = @nBillID
				GROUP BY OrderID,BillNumberID
			) a,
	PT_Combin_OrderBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OrderID = b.OrderID
			AND b.Qty > 0
			AND b.ReachQty >= a.Qty
	
	
			
	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney - a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID
			
	--更新对应会员卡本年消费,累计消费		
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney - a.TotalMoney,
			bNxFMoney=b.bNxFMoney-a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId			
	
END
ELSE IF @nBillType  = 140
BEGIN	-- 委托代销发货单
	UPDATE	OrderBill
	SET		
			ReachQty = ReachQty - a.Qty,
			ReachTotal=ReachTotal-a.Total,
			ReachTaxTotal=ReachTaxTotal-a.TaxTotal
	FROM	(
				SELECT BillNumberID,OrderID,
				SUM(Qty) AS Qty,SUM(Total) AS Total,SUM(TaxTotal) AS TaxTotal
				FROM dbo.CommissionBill WHERE BillNumberID = @nBillID
				GROUP BY OrderID,BillNumberID
			) a,
			OrderBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OrderID = b.OrderID
			AND b.Qty > 0
			AND b.ReachQty >= a.Qty
END
ELSE IF @nBillType  = 402
BEGIN	-- 发出商品出库单
	UPDATE	OrderBill
	SET		
			ReachQty = ReachQty - a.Qty,
			ReachTotal=ReachTotal-a.Total,
			ReachTaxTotal=ReachTaxTotal-a.TaxTotal
	FROM	(
				SELECT BillNumberID,OrderID,
				SUM(Qty) AS Qty,SUM(Total) AS Total,SUM(TaxTotal) AS TaxTotal
				FROM SendBill WHERE BillNumberID = @nBillID
				GROUP BY OrderID,BillNumberID
			) a,
			OrderBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OrderID = b.OrderID
			AND b.Qty > 0
			AND b.ReachQty >= a.Qty
END
ELSE IF @nBillType  = 34
BEGIN	-- 采购入库
	IF @nNewBillID<>0
	BEGIN
		IF EXISTS(
			SELECT TOP 1 A.BillNumberID 
			FROM BuyBackBill A,BillIndex B 
			WHERE A.BillNumberID = B.BillNumberID 
			AND B.IfCheck='f' 
			AND B.Redword=0 
			AND B.Draft=1 
			AND A.OldBillNumberID = @nBillId
		)
		BEGIN
			DELETE FROM BillIndex 
			WHERE BillNumberID IN 
			(
				SELECT A.BillNumberID 
				FROM BuyBackBill A,BillIndex B 
				WHERE A.BillNumberID = B.BillNumberID 
				AND B.IfCheck='f' 
				AND B.Redword=0 
				AND B.Draft=1 
				AND A.OldBillNumberID = @nBillId
			)
		END			
	END

	UPDATE	OrderBill
	SET		
			ReachQty = ReachQty - a.Qty,
			ReachTotal=ReachTotal-a.Total,
			ReachTaxTotal=ReachTaxTotal-a.TaxTotal
	FROM	(
				SELECT BillNumberID,OrderID,
				SUM(Qty) AS Qty,SUM(Total) AS Total,SUM(TaxTotal) AS TaxTotal
				FROM BuyBill WHERE BillNumberID = @nBillID
				GROUP BY OrderID,BillNumberID
			) a,
			OrderBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OrderID = b.OrderID
			AND b.Qty > 0
			AND b.ReachQty >= a.Qty
END
ELSE IF @nBillType  = 144
BEGIN	-- 受托代销收货单
	UPDATE	OrderBill
	SET		
			ReachQty = ReachQty - a.Qty,
			ReachTotal=ReachTotal-a.Total,
			ReachTaxTotal=ReachTaxTotal-a.TaxTotal
	FROM	(
				SELECT BillNumberID,OrderID,
				SUM(Qty) AS Qty,SUM(Total) AS Total,SUM(TaxTotal) AS TaxTotal
				FROM dbo.CommissionBill WHERE BillNumberID = @nBillID
				GROUP BY OrderID,BillNumberID
			) a,
			OrderBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OrderID = b.OrderID
			AND b.Qty > 0
			AND b.ReachQty >= a.Qty
END
ELSE IF @nBillType  = 400
BEGIN	-- 暂估入库
	IF @nNewBillID<>0
	BEGIN	
		IF EXISTS(
			SELECT TOP 1 A.BillNumberID 
			FROM AppraisalBackBill A,BillIndex B 
			WHERE A.BillNumberID = B.BillNumberID 
			AND B.IfCheck='f' 
			AND B.Redword=0 
			AND B.Draft=1 
			AND A.OldBillNumberID = @nBillId
		)
		BEGIN
			DELETE FROM BillIndex 
			WHERE BillNumberID IN 
			(
				SELECT A.BillNumberID 
				FROM AppraisalBackBill A,BillIndex B 
				WHERE A.BillNumberID = B.BillNumberID 
				AND B.IfCheck='f' 
				AND B.Redword=0 
				AND B.Draft=1 
				AND A.OldBillNumberID = @nBillId
			)
		END			
	END
	UPDATE	OrderBill
	SET		
			ReachQty = ReachQty - a.Qty,
			ReachTotal=ReachTotal-a.Total,
			ReachTaxTotal=ReachTaxTotal-a.TaxTotal
	FROM	(
				SELECT BillNumberID,OrderID,
				SUM(Qty) AS Qty,SUM(Total) AS Total,SUM(TaxTotal) AS TaxTotal
				FROM AppraisalBill WHERE BillNumberID = @nBillID
				GROUP BY OrderID,BillNumberID
			) a,
			OrderBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OrderID = b.OrderID
			AND b.Qty > 0
			AND b.ReachQty >= a.Qty
END
ELSE IF @nBillType = 45  --销售退货
BEGIN
	UPDATE	SaleBill
	SET		BackQty = BackQty - a.Qty
	FROM	SaleBackBill a,
			SaleBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]

	UPDATE	RetailBill
	SET		BackQty = BackQty - a.Qty
	FROM	SaleBackBill a,
			RetailBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]
			
	
	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney + a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID
			
	--更新对应会员卡本年消费,累计消费			
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney + a.TotalMoney,
			bNxFMoney=b.bNxFMoney+a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId

END
ELSE IF @nBillType = 46  --组合品销售退货
BEGIN
	UPDATE	PT_Combin_SaleBillDetail
	SET		BackQty = BackQty - a.Qty
	FROM	PT_Combin_SaleBackBillDetail a,
			PT_Combin_SaleBillDetail b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]

	UPDATE	PT_Combin_SaleBill
	SET		BackQty = BackQty - a.Qty
	FROM	PT_Combin_SaleBackBill a,
			PT_Combin_SaleBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]
			
	
	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney + a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID
			
	--更新对应会员卡本年消费,累计消费	
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney + a.TotalMoney,
			bNxFMoney=b.bNxFMoney+a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId

END
ELSE IF @nBillType = 160  --销售换货
BEGIN
	UPDATE	SaleBill
	SET		BackQty = BackQty - a.Qty
	FROM	SaleGoodsExchangeBill a,
			SaleBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]

	UPDATE	RetailBill
	SET		BackQty = BackQty - a.Qty
	FROM	SaleGoodsExchangeBill a,
			RetailBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]

END
ELSE IF @nBillType = 403  --发出商品退货
BEGIN
	UPDATE	SendBill
	SET		BackQty = BackQty - a.Qty
	FROM	SendBackBill a,
			SendBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]
END
ELSE IF @nBillType = 6  --采购退货
BEGIN
	UPDATE	BuyBill
	SET		BackQty = BackQty - a.Qty
	FROM	BuyBackBill a,
			BuyBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]
END
ELSE IF @nBillType = 161  --采购换货
BEGIN
	UPDATE	BuyBill
	SET		BackQty = BackQty - a.Qty
	FROM	BuyGoodsExchangeBill a,
			BuyBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]
END
ELSE IF @nBillType = 401  --暂估退货
BEGIN
	UPDATE	AppraisalBill
	SET		BackQty = BackQty - a.Qty
	FROM	AppraisalBackBill a,
			AppraisalBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]
END
ELSE IF @nBillType IN (142,146)
BEGIN
	SELECT	BillNumberID,OldBillID,Qty,OldId
	INTO 	#Temp1
	FROM	CommissionBill
	WHERE	BillNumberID = @nBillID

	UPDATE	CommissionBill
	SET		BQty = BQty - a.Qty
	FROM	#Temp1 a,
			CommissionBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillID = b.BillNumberID
			AND b.BQty > 0
			AND b.BQty >= a.Qty
			AND a.OldId = B.[ID]

	DROP TABLE #Temp1
END
ELSE IF @nBillType = 141 OR @nBillType = 145
BEGIN
	SELECT	BillNumberID,OldBillNumberID,Qty,OldId
	INTO 	#Temp
	FROM	CommissionBill
	WHERE	BillNumberID = @nBillID


	UPDATE	CommissionBill
	SET		BackQty = BackQty - a.Qty
	FROM	#Temp a,
			CommissionBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]

			--AND a.OldID = b.[ID]

	DROP TABLE #Temp
END
ELSE IF @nBillType=305
BEGIN
	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney - a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID
			
	--更新对应会员卡本年消费,累计消费	
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney - a.TotalMoney,
			bNxFMoney=b.bNxFMoney-a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId
END
ELSE IF @nBillType=215
BEGIN
	UPDATE	RetailBill
	SET		BackQty = BackQty - a.Qty
	FROM	RetailBackBill a,
			RetailBill b
	WHERE	a.BillNumberID = @nBillID
			AND a.OldBillNumberID = b.BillNumberID
			AND b.BackQty > 0
			AND b.BackQty >= a.Qty
			AND a.OldId = B.[ID]

	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney + a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID
			
	--更新对应会员卡本年消费,累计消费	
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney + a.TotalMoney,
			bNxFMoney=b.bNxFMoney+a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId
END
ELSE IF @nBillType = 166	-- 新维修 - 维修单
BEGIN
	UPDATE	wx_Bill_JieJian SET State = b.JieJianState,
			AddTotal = CASE WHEN AddTotal - b.TotalMoney = 0
				AND NOT EXISTS(
					SELECT	TOP 1 1 FROM BillIndex
					WHERE	JieJianBillNumberID = a.BillNumberID
							AND JieJianID = a.[ID]
							AND RedWord = 0
				) THEN NULL ELSE AddTotal - b.TotalMoney END
	FROM	wx_Bill_JieJian a, BillIndex b
	WHERE	b.BillNumberID = @nBillID
			AND a.BillNumberID = b.JieJianBillNumberID
			AND a.[ID] = b.JieJianID
			AND a.PTypeID = b.PTypeID
END
ELSE IF @nBillType = 167	-- 新维修 - 取件单
BEGIN
	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney - a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID	
			
	--更新对应会员卡本年消费,累计消费	
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney - a.TotalMoney,
			bNxFMoney=b.bNxFMoney-a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId

	UPDATE	wx_Bill_JieJian SET State = b.JieJianState
	FROM	wx_Bill_JieJian a, wx_Bill_GetBack b
	WHERE	b.BillNumberID = @nBillID
			AND a.BillNumberID = b.JieJianBillNumberID
			AND a.[ID] = b.JieJianID
			AND a.PTypeID = b.JieJianPTypeID
END
ELSE IF @nBillType = 168	-- 新维修 - 整机更换单
BEGIN
	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney - a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID	
			
	--更新对应会员卡本年消费,累计消费
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney - a.TotalMoney,
			bNxFMoney=b.bNxFMoney-a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId		
	UPDATE	wx_Bill_JieJian SET State = b.JieJianState
	FROM	wx_Bill_JieJian a, wx_Bill_Replace b
	WHERE	b.BillNumberID = @nBillID
			AND a.BillNumberID = b.JieJianBillNumberID
			AND a.[ID] = b.JieJianID
			AND a.PTypeID = b.JieJianPTypeID
END
ELSE IF @nBillType = 169	-- 新维修 - 送修单
BEGIN
	UPDATE	wx_Bill_JieJian SET State = b.JieJianState
	FROM	wx_Bill_JieJian a, wx_Bill_Send b
	WHERE	b.BillNumberID = @nBillID
			AND a.BillNumberID = b.JieJianBillNumberID
			AND a.[ID] = b.JieJianID
			AND a.PTypeID = b.JieJianPTypeID
END
ELSE IF @nBillType = 170	-- 新维修 - 送修返回单
BEGIN
	UPDATE	wx_Bill_JieJian SET State = 3	-- 已送修
	FROM	wx_Bill_JieJian a, wx_Bill_Send b
	WHERE	b.BillNumberID IN (SELECT SendBillNumberID FROM wx_Bill_SendBack WHERE BillNumberID = @nBillID)
			AND b.[ID] IN (SELECT SendID FROM wx_Bill_SendBack WHERE BillNumberID = @nBillID)
			AND a.BillNumberID = b.JieJianBillNumberID
			AND a.[ID] = b.JieJianID
			AND a.PTypeID = b.JieJianPTypeID

	UPDATE	wx_Bill_Send SET SendBackQty = SendBackQty - b.Qty
	FROM	wx_Bill_Send a, wx_Bill_SendBack b
	WHERE	b.BillNumberID = @nBillID
			AND a.BillNumberID = b.SendBillNumberID
			AND a.[ID] = b.SendID
			AND a.PTypeID = b.SendPTypeID
END
ELSE IF @nBillType = 172	-- 新维修 - 上门维修单
BEGIN
	UPDATE	nVipCardSign
	SET		TotalMoney = b.TotalMoney - a.TotalMoney,
			TotalCent = b.TotalCent - a.JF
	FROM	BillIndex a,
			nVipCardSign b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			--AND a.JF <> 0
			AND a.VipCardID = b.VipCardID	
			
	--更新对应会员卡本年消费,累计消费
	UPDATE	nVipCardSignStype
	SET		lJxFMoney = b.lJxFMoney - a.TotalMoney,
			bNxFMoney=b.bNxFMoney-a.TotalMoney
	FROM	BillIndex a,
			nVipCardSignStype b
	WHERE	a.BillNumberID = @nBillID
			AND a.VipCardID <> -1
			AND a.VipCardID = b.VipCardID	
			AND a.Stypeid=b.StypeId
			
	UPDATE	wx_Bill_Call SET State = 0	-- 待上门维修
	FROM	wx_Bill_Call a, BillIndex b
	WHERE	b.BillNumberID = @nBillID
			AND a.BillNumberID = b.BaoXiuBillNumberID
			AND a.[ID] = b.BaoXiuID
			AND a.PTypeID = b.PTypeID
END
ELSE IF @nBillType=183	
BEGIN
		--积分兑换单
		SELECT	
				@intVipCardID = VipCardID
		FROM	BillIndex
		WHERE	BillNumberID = @nBillID

		SELECT @curJF=SUM(Total)
		FROM IntegralExchangeBill
		WHERE BillNumberID=@nBillID
		
		UPDATE nVipCardSign
		SET TotalCent=TotalCent+@curJF
		WHERE VipCardID = @intVipCardID

END
ELSE IF @nBillType IN (149,151)
BEGIN			
	UPDATE PriceProtectList
	SET OldTotal=OldTotal-ISNULL(b.Total,0)
	FROM
	(
		SELECT BillType,PTypeID,STypeID,Serial,SUM(Total) AS Total
		FROM PriceProtectBill
		WHERE BillNumberID=@nBillID
		GROUP BY BillType,PTypeID,STypeID,Serial
	) b
	WHERE PriceProtectList.BillType=b.BillType
	AND PriceProtectList.PTypeID=b.PTypeID
	AND PriceProtectList.STypeID=b.STypeID
	AND PriceProtectList.Serial=b.Serial
END	
ELSE IF @nBillType =157
BEGIN
	-- 红冲受理单的原来的接件单处理  chen_qihua 2004-08-06
	UPDATE RepairEngage SET Stat =1,ifCheck='t' where Billnumberid in (select EngageBillID From RepairDeal where BillnumberID =@nBillID)     	
END

ELSE IF @nBillType IN (187,188,159)
BEGIN
	--内部应收
	IF @nBillType IN (187,188)
	BEGIN
		SELECT @decInnerAR=-Total
		FROM ListTable
		WHERE BillNumberID=@nBillID AND AtypeId=@strInnerAR AND BillType=@nBillType
		
		--写内部应收
		IF @nNewBillID=0 SET @decInnerAR=-@decInnerAR
		
		EXEC GP_InnerARTotal_AddEdit	@nBillID,@decInnerAR,0,@strErrMsg OUT
	END
	ELSE
	BEGIN
		--会计凭证则要通过循环来得到
		DECLARE INNERAR_CURSOR CURSOR FOR
			SELECT	
					J_Total,
					D_Total,
					ID
			FROM	AccountCredence
			WHERE	BillNumberID = @nBillID AND TypeATypeID=@strInnerAR

		OPEN INNERAR_CURSOR
		FETCH NEXT FROM INNERAR_CURSOR INTO	
												@numJTotal,
												@numDTotal,
												@intTempID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @numJTotal > 0
			BEGIN
					SET @decInnerAR = -@numJTotal		
			END
			ELSE
			BEGIN
					SET @decInnerAR = @numDTotal
			END
			

			--内部应收
			EXEC	GP_InnerARTotal_AddEdit
			@nBillID,
			@decInnerAR,
			@intTempID,
			@strErrMsg	OUT
		
			FETCH NEXT FROM INNERAR_CURSOR INTO	
													@numJTotal,
													@numDTotal,
													@intTempID
		END
		CLOSE INNERAR_CURSOR
		DEALLOCATE INNERAR_CURSOR
	END
END
/*上架单、运输配送单、拣货单*/
ELSE IF @nBillType IN(412,413,414)
BEGIN
	/*上架单*/
	IF @nBillType=412
	BEGIN
		INSERT INTO @Tmp(Qty,GoodsBillNumberID,GoodsBillType,GoodsBillID,RowIndex)
		SELECT Qty,
			   GoodsBillNumberID,
			   GoodsBillType,
			   GoodsBillID,
			   ROW_NUMBER() OVER(ORDER BY GETDATE())
		FROM dbo.onShelvesbill WHERE billNumberID=@nBillID	
		SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
		
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @GoodsBillNumberID=GoodsBillNumberID,
				   @GoodsBillType=GoodsBillType,
				   @GoodsBillID=GoodsBillID,
				   @Qty=Qty 
			FROM @Tmp WHERE @RowIndex=RowIndex
			SELECT @TbName=detailTable FROM dbo.BillName WHERE Billtype=@GoodsBillType
			/*回写入库单入库数量（上架数量）*/
			SET @CheckSQL ='IF EXISTS(
										SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
										WHERE ISNULL(InflowQty,0)<>0 AND BillNumberID=@GoodsBillNumberID AND P.IsService=0 '
									    +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END
									+') 
							SET @Return=0 ELSE SET @Return=1'
			SET @UpdateSQL='UPDATE '+@TbName +' 
							SET InflowQty=ISNULL(InflowQty,0)-@Qty 
							WHERE ID=@GoodsBillID ' +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE '' END
			SET @Return=0
			
			exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@GoodsBillID INT',@Qty,@GoodsBillID
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@Return INT OUT',@GoodsBillNumberID,@Return OUT
			/*如果没有上架数量，则更新引用状态为未引用，上架状态为已开单，否则为已引用未完成，上架中*/
			UPDATE dbo.BillIndex 
			SET 
				ShelveState=CASE WHEN @Return=1 THEN 0 ELSE 1 END,
				ShelveRefState=CASE WHEN @Return=1 THEN 0 ELSE 1 END 
			WHERE BillNumberId=@GoodsBillNumberID
			SET @RowIndex=@RowIndex+1
		END
		RETURN
	END
	/*拣货单*/
	IF @nBillType=413
	BEGIN
		INSERT INTO @Tmp(Qty,GoodsBillNumberID,GoodsBillID,GoodsBillType,RowIndex)
		SELECT Qty,
			   GoodsBillNumberID,
			   GoodsBillID,
			   GoodsBillType,
			   ROW_NUMBER() OVER (ORDER BY GETDATE()) 
		FROM PickBill WHERE BillNumberID=@nBillID
		SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
		
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @Qty=Qty,@GoodsBillNumberID=GoodsBillNumberID,@GoodsBillID=GoodsBillID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
			SELECT @TbName=detailTable FROM BillName WHERE Billtype=@GoodsBillType
			/*回写出库单拣货数量，拣货状态，拣货引用状态*/
			SET @CheckSQL ='IF EXISTS(
										SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID  
										WHERE ISNULL(PickedQty,0)<>0 AND BillNumberID=@GoodsBillNumberID AND P.IsService=0 '
										+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END
									+') 
								SET @Return=0 ELSE SET @Return=1'
			SET @UpdateSQL='UPDATE '+@TbName +' 
							SET PickedQty=ISNULL(PickedQty,0)-@Qty 
							WHERE ID=@GoodsBillID ' +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE '' END
			SET @Return=0
			
			exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@GoodsBillID INT',@Qty,@GoodsBillID
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@Return INT OUT',@GoodsBillNumberID,@Return OUT
			
			UPDATE dbo.BillIndex 
			SET 
				progressstate=CASE WHEN @Return=1 THEN 0 ELSE 1 END,
				citestate=CASE WHEN @Return=1 THEN 0 ELSE 1 END 
			WHERE BillNumberId=@GoodsBillNumberID
			SET @RowIndex=@RowIndex+1
		END
		RETURN 0
	END
	/*运输配送单*/
	IF @nBillType=414
	BEGIN
		INSERT INTO  @Tmp(Qty,GoodsBillNumberID,GoodsBillID,GoodsBillType,RowIndex)
		SELECT  Qty,
				GoodsBillNumberID,
				GoodsBillID,
				GoodsBillType,
				ROW_NUMBER() OVER(ORDER BY GETDATE())
		FROM (
			  SELECT  A.Qty ,
					  B.GoodsBillNumberID ,
					  B.GoodsBillID ,
					  B.GoodsBillType 
			  FROM    dbo.Transportbill A INNER JOIN dbo.pickbill B ON A.GoodsBillID = B.ID WHERE A.billNumberID=@nBillID
			  UNION ALL
			  SELECT  Qty ,
					  GoodsBillNumberID ,
					  GoodsBillID ,
					  GoodsBillType 
			  FROM    dbo.Transportbill WHERE billNumberID=@nBillID
		) B
        SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
        
        /*回写出库单发货数量，如果全部发货，则更改状态为已发运*/
        WHILE(@RowIndex<=@RowCount)
        BEGIN
			SELECT @Qty=Qty,@GoodsBillNumberID=GoodsBillNumberID,@GoodsBillID=GoodsBillID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
			/*更新拣货单引用状态*/
			IF @GoodsBillType=413
			BEGIN
				/*还有未红冲单据引用，则更改引用状态为已引用未完成，否则未引用*/
				IF EXISTS(
							SELECT TOP 1 1 FROM Transportbill A 
							INNER JOIN BillIndex B ON A.BillNumberID=B.BillNumberID 
							INNER JOIN dbo.ptype P ON A.ptypeid=P.typeId
							WHERE A.GoodsBillNumberID=@GoodsBillNumberID AND B.RedWord=0 AND P.IsService=0
						 )
				BEGIN
					UPDATE dbo.onShelvespickIndex SET citestate=1 WHERE billNumberId=@GoodsBillNumberID
				END
				ELSE
				BEGIN
					UPDATE dbo.onShelvespickIndex SET citestate=0 WHERE billNumberId=@GoodsBillNumberID
				END
			END
			ELSE /*更新发货数量*/
			BEGIN
				SELECT @TbName=detailTable FROM BillName WHERE Billtype=@GoodsBillType
				/*更新出库单发货数量，发货状态*/
				SET @CheckSQL ='IF EXISTS(
											SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID  
											WHERE ISNULL(SendedQty,0)<>0 AND BillNumberID=@GoodsBillNumberID AND P.IsService=0 '
											+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END
										+') 
									SET @Return=0 ELSE SET @Return=1'
				SET @UpdateSQL='UPDATE '+@TbName +' 
								SET SendedQty=ISNULL(SendedQty,0)-@Qty 
								WHERE ID=@GoodsBillID ' +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE '' END
				SET @Return=0
				
				exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@GoodsBillID INT',@Qty,@GoodsBillID
				exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@Return INT OUT',@GoodsBillNumberID,@Return OUT
				
				UPDATE dbo.BillIndex 
				SET 
					TransPortState=CASE WHEN @Return=1 THEN 0 ELSE 1 END 
				WHERE BillNumberId=@GoodsBillNumberID
			END
			SET @RowIndex=@RowIndex+1
        END
		RETURN 0
	END
END
ELSE IF @nBillType IN(418,419)
BEGIN
	INSERT INTO @Tmp(Qty,GoodsBillNumberID,GoodsBillType,GoodsBillID,RowIndex)
	SELECT Qty,
		   FromBillNumberID,
		   FromBillType,
		   FromBillID,
		   ROW_NUMBER() OVER(ORDER BY GETDATE())
	FROM dbo.FactDepotInOut 
	WHERE billNumberID=@nBillID	AND FromBillNumberID>0 AND FromBillType>0
	
	SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
	/*仓库入库单*/
	IF @nBillType=418
	BEGIN
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @GoodsBillNumberID=GoodsBillNumberID,
				   @GoodsBillType=GoodsBillType,
				   @GoodsBillID=GoodsBillID,
				   @Qty=Qty 
			FROM @Tmp WHERE @RowIndex=RowIndex
			SELECT @TbName=detailTable FROM dbo.BillName WHERE Billtype=@GoodsBillType
			/*回写入库单入库数量（上架数量）*/
			SET @CheckSQL ='
							IF NOT EXISTS(
										SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
										WHERE ISNULL(InFactQty,0)<Abs(Qty) AND BillNumberID=@GoodsBillNumberID AND P.IsService=0 '
									    +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END
									+')
									SET @Return=2 
							ELSE IF EXISTS(
										SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
										WHERE ISNULL(InFactQty,0)<>0 AND BillNumberID=@GoodsBillNumberID AND P.IsService=0 '
									    +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END
									+') 
								SET @Return=1
							 ELSE SET @Return=0'
			SET @UpdateSQL='UPDATE '+@TbName +' 
							SET InFactQty=ISNULL(InFactQty,0)-@Qty 
							WHERE ID=@GoodsBillID ' +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE '' END
			SET @Return=0
			
			exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@GoodsBillID INT',@Qty,@GoodsBillID
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@Return INT OUT',@GoodsBillNumberID,@Return OUT
			/*如果没有仓库入库数量数量，则更新引用状态为未引用*/
			IF @GoodsBillType IN(71,72,87,88)
			BEGIN
				UPDATE dbo.LendIndex 
				SET 
					InFactState=@Return,
					InFactRefState=CASE WHEN @Return=0 THEN 0 ELSE 1 END 
				WHERE BillNumberId=@GoodsBillNumberID
			END
			ELSE
			BEGIN
				UPDATE dbo.BillIndex 
				SET 
					InFactState=@Return,
					InFactRefState=CASE WHEN @Return=0 THEN 0 ELSE 1 END 
				WHERE BillNumberId=@GoodsBillNumberID
			END
			SET @RowIndex=@RowIndex+1
		END
		RETURN
	END
	/*仓库出库单*/
	IF @nBillType=419
	BEGIN
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @Qty=Qty,@GoodsBillNumberID=GoodsBillNumberID,@GoodsBillID=GoodsBillID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
			SELECT @TbName=detailTable FROM BillName WHERE Billtype=@GoodsBillType

			SET @CheckSQL ='
							IF NOT EXISTS(
										SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
										WHERE ISNULL(OutFactQty,0)<Abs(Qty) AND BillNumberID=@GoodsBillNumberID AND P.IsService=0 '
									    +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END
									+')
									SET @Return=2 
							ELSE IF EXISTS(
										SELECT 1 FROM ' +@TbName+'  A INNER JOIN PType P ON A.PTypeID=P.TypeID 
										WHERE ISNULL(OutFactQty,0)<>0 AND BillNumberID=@GoodsBillNumberID AND P.IsService=0 '
									    +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END
									+') 
								SET @Return=1
							 ELSE SET @Return=0'
							 
			SET @UpdateSQL='UPDATE '+@TbName +' 
							SET OutFactQty=ISNULL(OutFactQty,0)-@Qty 
							WHERE ID=@GoodsBillID ' +CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE '' END
			SET @Return=0
			
			exec sp_executesql @UpdateSQL,N'@Qty NUMERIC(24,10),@GoodsBillID INT',@Qty,@GoodsBillID
			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@Return INT OUT',@GoodsBillNumberID,@Return OUT
			
			/*如果没有仓库出库数量数量，则更新引用状态为未引用*/
			IF @GoodsBillType IN(71,72,87,88)
			BEGIN
				UPDATE dbo.LendIndex 
				SET 
					OutFactState=@Return,
					OutFactRefState=CASE WHEN @Return=0 THEN 0 ELSE 1 END 
				WHERE BillNumberId=@GoodsBillNumberID
			END
			ELSE
			BEGIN
				UPDATE dbo.BillIndex 
				SET 
					OutFactState=@Return,
					OutFactRefState=CASE WHEN @Return=0 THEN 0 ELSE 1 END 
				WHERE BillNumberId=@GoodsBillNumberID
			END
			SET @RowIndex=@RowIndex+1
		END
		RETURN 0
	END
END
else if @nBillType IN(328) -------991---配送退货单红冲后，并回写门店配送单的“退货数量”。
begin

	UPDATE dbo.DeliveryBill 
	SET BackQty -= D.qty 
	FROM DeliveryBackBill D,
	dbo.DeliveryBill M
	WHERE M.ID=D.DeliveryID 	
	AND D.BillNumberId=@nBillID 
	AND D.DeliveryID>0 
	AND m.BackQty>0
	AND m.BackQty>=D.Qty
	
    UPDATE PosAllotApplyBillIndex SET Isdone=0
    WHERE BillNumberId IN (
						SELECT a.BillNumberId 
						FROM DeliveryBill a,
						DeliveryBackBill b 
						WHERE a.id=b.DeliveryID and (a.CheckQty+a.BackQty)<a.Qty  AND b.DeliveryID>0 AND b.BillNumberId=@nBillID
						)
end
else if @nBillType IN(329) -------991---配送验收单单红冲后，并回写门店配送单的“验收数量”。
BEGIN
    UPDATE dbo.DeliveryBill 
	SET CheckQty -= D.qty 
	FROM DeliveryCheckBill D,
	dbo.DeliveryBill M
	WHERE M.ID=D.DeliveryID 	
	AND D.BillNumberId=@nBillID 
	AND D.DeliveryID>0 
	AND m.CheckQty>0
	AND m.CheckQty>=D.Qty
	
	 UPDATE PosAllotApplyBillIndex SET Isdone=0
    WHERE BillNumberId IN (
						SELECT a.BillNumberId 
						FROM DeliveryBill a,
						DeliveryCheckBill b 
						WHERE a.id=b.DeliveryID and (a.CheckQty+a.BackQty)<a.Qty  AND b.DeliveryID>0 AND b.BillNumberId=@nBillID
						)
END
ELSE IF   @nBillType IN(327)  ----991红冲门店配送单后，回写关联的要货单的完成状态
BEGIN
	    
	UPDATE dbo.DeliveryApplyBill 
	SET DeliveryQty -= D.qty 
	FROM DeliveryBill D,
	dbo.DeliveryApplyBill M
	WHERE M.ID=D.DeliveryApplyBillId 	
	AND D.BillNumberId=@nBillID 
	AND D.DeliveryApplyBillId>0 
	AND m.DeliveryQty>0
	AND m.DeliveryQty>=D.Qty

	UPDATE PosAllotApplyBillIndex SET Isdone=0
    WHERE BillNumberId IN (
						SELECT a.BillNumberId 
						FROM DeliveryApplyBill a,
						DeliveryBill b 
						WHERE a.id=b.DeliveryApplyBillId and a.DeliveryQty<a.Qty  AND b.DeliveryApplyBillId>0 AND b.BillNumberId=@nBillID
						)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：施训果


处理核销

*/
CREATE   PROCEDURE Gp_Deal_ChargeOff 
(
	@nBillID			numeric(10,0)		-- 1. 单据编号 ID 值
)
--@encode$--
AS
	SET NOCOUNT ON
	
	DECLARE
		-- 系统是否启用【费用单核算客户时计入应收】
		@expensetoar INT=0,
		@chargeOffValue		NUMERIC(24,10),
		@nchargeOffValue	NUMERIC(24,10),
		@chargeOffType INT, --核销类型:0：应收冲应付 1：预收冲预付 2：应收转应收 3：应付转应付 4：预收转应付 5：预付转应收
		@btypeID VARCHAR(50),
		@fromBillNumberid NUMERIC(10,0),
		@fromBillID INT,
		@fromBillType NUMERIC(4,0),
		@checkFlag INT,
		@cid INT
		
		
	SELECT @expensetoar = SUBVALUE FROM SYSDATA WHERE SUBNAME='expensetoar'
	SELECT @chargeOffValue=totalmoney,@nchargeOffValue=NTotalMoney,@chargeOffType=ChargeOffType,@cid=CID
	FROM dbo.BillIndex 
	WHERE BillNumberId=@nBillID
	
	
	DECLARE chargeOffCursort CURSOR FOR SELECT ChargeOffValue,NChargeOffValue,FromBillNumberid,FromBillID,FromBillType,BTypeID FROM dbo.ChargeOffBill WHERE BillNumberId=@nBillID
	OPEN  chargeOffCursort
	FETCH NEXT FROM chargeOffCursort INTO @chargeOffValue,@nchargeOffValue, @fromBillNumberid,@fromBillID,@fromBillType,@btypeID
	WHILE (@@fetch_status=0)
	BEGIN
	
		-- 退款类单据，保存时需要把本次核销金额置特殊处理
		IF @fromBillType IN (45,46,6,115,129,150,151,148,149,426)
		BEGIN
			SET @chargeOffValue=-@chargeOffValue
			SET @nchargeOffValue=-@nchargeOffValue
		END
		
		-- 系统是否启用【费用单核算客户时计入应收】金额为负的应收所以金额要做负号处理
		IF @expensetoar=1 AND @fromBillType=36 AND @chargeOffType IN (0,2) AND substring(@btypeID,0,6)='00001'
		BEGIN
			SET @chargeOffValue=-@chargeOffValue
			SET @nchargeOffValue=-@nchargeOffValue
		END
	
		IF @fromBillType IN (405,404)
			UPDATE dbo.ReceiptBillIndex SET 
			JSState=(CASE CompleteTotal+ChargeOffTotal-@chargeOffValue WHEN 0 THEN 0 ELSE 1 END ),
			jsStyle=(CASE CompleteTotal+ChargeOffTotal-@chargeOffValue WHEN 0 THEN 0 ELSE 1 END ),
			ChargeOffTotal=ChargeOffTotal-@chargeOffValue,
			NChargeOffTotal=NChargeOffTotal-@nchargeOffValue
			WHERE BillNumberId=@fromBillNumberid
		ELSE
		BEGIN
			IF @fromBillType IN (423,424,426)
				UPDATE dbo.Coupon_BillIndex SET 
				JSState=(CASE CompleteTotal+ChargeOffTotal+preferencemoney-@chargeOffValue WHEN 0 THEN 0 ELSE 1 END ),
				ChargeOffTotal=ChargeOffTotal-@chargeOffValue,
				NChargeOffTotal=NChargeOffTotal-@nchargeOffValue
				WHERE BillNumberId=@fromBillNumberid
			ELSE 
			BEGIN
				IF @fromBillType IN (115,116,128,129)
					UPDATE dbo.AdDebtBill SET 
					ChargeOffTotal=ChargeOffTotal-@chargeOffValue,
					NChargeOffTotal=NChargeOffTotal-@nchargeOffValue
					WHERE BillNumberId=@fromBillNumberid AND ID = @fromBillID

				UPDATE dbo.BillIndex 
				SET 
					JSState=(CASE CompleteTotal+ChargeOffTotal+preferencemoney-@chargeOffValue WHEN 0 THEN 0 ELSE 1 END ),
					jsStyle=(CASE CompleteTotal+ChargeOffTotal+preferencemoney-@chargeOffValue WHEN 0 THEN 0 ELSE 1 END ),
					ChargeOffTotal=ChargeOffTotal-@chargeOffValue,
					NChargeOffTotal=NChargeOffTotal-@nchargeOffValue
				WHERE BillNumberId=@fromBillNumberid
			END
			
		END
		FETCH NEXT FROM chargeOffCursort INTO @chargeOffValue,@nchargeOffValue, @fromBillNumberid,@fromBillID,@fromBillType,@btypeID
	END
	
	CLOSE chargeOffCursort
	DEALLOCATE chargeOffCursort
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*



*/





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：复制草稿或生成单据处理草稿库存
	返回结果：
	作    者：施训果
	创建时间：2017-03-03
	修改历史：
	
*/
CREATE          PROCEDURE GP_Deal_DraftQTY
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT,
	@EffectFlag CHAR(4) = '+'	-- +：保存草稿、自动生成单据正向影响库存，-：单据过账、删除草稿负向影响库存
)

--@encode$--
AS

DECLARE @SQL VARCHAR(1280),
		@IsIn BIT = 0,	-- 0:不影响入库 1：影响入库
		@IsOut BIT = 0, 	-- 0:不影响入库 1：影响出库
		@TableName VARCHAR(100),	--明细表名
		@Where	 VARCHAR(100),		--查询条件
		@IndexName VARCHAR(50),		--主表名
		@InCargoIDField  VARCHAR(10)='CargoID',	--入库货位ID
		@OutCargoIDField VARCHAR(10)='CargoID',	--出库货位ID
		@KtypeIDField	VARCHAR(10)='KtypeID'	--仓库ID	

SET @Where=' '; --设置查询条件为空
		
--	会影响入库库存的单据
IF	@BillType IN (34,45,215,161,160,17,21,16,14,144,142,126,174,188,201,400,403,46,328)
BEGIN
	SET @IsIn = 1
END
--	会影响出库库存的单据
IF @BillType IN (6,11,161,160,17,21,16,9,146,140,305,139,166,168,172,173,183,187,202,401,402,12,327)
BEGIN
	SET @IsOut=1
END
--  调拨类单据，出入库货位字段是分开的InCargoID\OutCargoID
IF @BillType IN (420,188,21,187,17,328)
BEGIN
	SET @InCargoIDField='InCargoID'
	SET @OutCargoIDField='OutCargoID'
END

IF @BillType=327
BEGIN
	SET @InCargoIDField='CargoIDin'
	SET @OutCargoIDField='CargoIDout'
END

-- 设置明细表表名
SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType

--判断是否手工指定
DECLARE @COST VARCHAR(10)='',@CostPrice varchar(50)='PTypeId'
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	SET @CostPrice='GoodsCostPrice'
END

-- 处理影响入库类单据的草稿库存
IF @IsIn = 1
BEGIN

	IF @BillType IN (17,21,188)
	BEGIN
		SET @KtypeIDField='KTypeId2'
	END
	
	IF @BillType IN (327,328)
	BEGIN
		SET @KtypeIDField='InKtypeId'
	END

	--换货类单据入库数据需要添加条件InOrOut='I'
	IF @BillType IN (161,160,16)
	BEGIN
		SET @Where +=' AND InOrOut = ''I'' '
	END
	
	IF @BillType IN (144,142)
	BEGIN
		SET @Where +=' AND [Type] = ' + CAST(@BillType AS VARCHAR)
	END
	
	IF @BillType IN (188,201)
	BEGIN
		SET @Where +=' AND BillType = '+ CAST(@BillType AS VARCHAR)
	END
	
	IF @BillType IN (14)
	BEGIN
		SET @Where +=' AND ifWX = 0 '
	END
	
	-- 不存在该维度的记录插入数据，存在该维度的记录则叠加修改库存数据
	SET @SQL = '
		MERGE INTO GOODSSTOCKS_Draft AS T
		USING 
			(
				SELECT PTypeId,' + @KtypeIDField + ' AS KtypeID,ISNULL(GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
						ISNULL('+@InCargoIDField+',0) AS '+@InCargoIDField+',ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,SUM(QTY) AS QTY 
				FROM ' + @TableName + ' WHERE BillNumberId = ' + @BillNumberID + ' AND ' + @KtypeIDField + ' <> ' + CHAR(39) + CHAR(39) + @Where + '
				GROUP BY PTypeId,' + @KtypeIDField + ',GoodsNumber,ProduceDate,ValidDate,'+@InCargoIDField+',ItemID,IsCombined,'+@CostPrice+'
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.'+@InCargoIDField+' AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.RQty=T.RQty'+ @effectflag +'S.QTY,T.QTY=T.QTY'+ @effectflag +'S.QTY
		WHEN NOT MATCHED BY TARGET
		THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,RQty,CQty,Qty) 
		VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.'+@InCargoIDField+',S.ItemID,S.IsCombined,S.GoodsCostPrice,'+@effectflag+'S.Qty,0,'+@effectflag+'S.Qty);'
	EXEC (@SQL)
END

SET @Where=' '; --设置查询条件为空

-- 处理影响出库类单据的草稿库存
IF @IsOut = 1
BEGIN
	IF @BillType=327
	BEGIN
		SET @KtypeIDField='KTypeIdOut'
	END
	ELSE
		SET @KtypeIDField='KTypeId'

	--换货类等单据出库数据需要添加条件InOrOut='O'
	IF @BillType IN (161,160,16,166,172)
	BEGIN
		SET @Where +=' AND InOrOut = ''O'' '
	END
	
	-- 维修类单据需要校验维修属性字段
	IF @BillType IN (166,168,172)
	BEGIN
		SET @Where +=' AND WxProperty = 0 '
	END
	
	IF @BillType IN (146,140)
	BEGIN
		SET @Where +=' AND [Type] = ' + CAST(@BillType AS VARCHAR)
	END
	
	IF @BillType IN (187,202)
	BEGIN
		SET @Where +=' AND BillType = ' + CAST(@BillType AS VARCHAR)
	END
	
	IF @BillType IN (9)
	BEGIN
		SET @Where +=' AND ifWX = 0 '
	END
	
	-- 不存在该维度的记录插入数据，存在该维度的记录则叠加修改库存数据
	SET @SQL = '
		MERGE INTO GOODSSTOCKS_Draft AS T           
		USING 
			(
				SELECT PTypeId,' + @KtypeIDField + ' AS KtypeID,ISNULL(GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(ProduceDate,' + CHAR(39) + CHAR(39) + ') AS ProduceDate,ISNULL(ValidDate,' + CHAR(39) + CHAR(39) + ') AS ValidDate,
						ISNULL('+@OutCargoIDField+',0) AS '+@OutCargoIDField+',ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,SUM(QTY) AS QTY 
				FROM ' + @TableName + ' WHERE BillNumberId = ' + @BillNumberID + ' AND ' + @KtypeIDField + ' <> ' + CHAR(39) + CHAR(39) + @Where + '
				GROUP BY PTypeId,' + @KtypeIDField + ',GoodsNumber,ProduceDate,ValidDate,'+@OutCargoIDField+',ItemID,IsCombined,'+@CostPrice+'
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.'+@OutCargoIDField+' AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.CQty=T.CQty'+ @effectflag +'S.QTY,T.QTY=T.QTY'+ @effectflag +'(-S.QTY)
		WHEN NOT MATCHED BY TARGET
		THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,RQty,CQty,Qty) 
		VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.'+@OutCargoIDField+',S.ItemID,S.IsCombined,GoodsCostPrice,0,'+@effectflag+'S.Qty,'+@effectflag+'(-S.Qty));'
	EXEC (@SQL)
END

--删除各维度数量为0的商品
--DELETE dbo.GoodsStocks_Draft WHERE CQty=0 AND RQty=0 AND Qty=0

--将主表状态与明细的状态调整为一致
IF @IndexName='BillIndex'
BEGIN
	DECLARE @DraftFlag BIT = 1,
			@IsiniFlag BIT = 0
			
	SELECT @DraftFlag=draft,@IsiniFlag=IsIni FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@billtype

	-- 处理单据明细与主表的过账及期初字段
	SET @SQL = 'UPDATE ' + @TableName + ' SET DraftFlag=' + CAST(@DraftFlag as varchar(4)) + ',IsIniFlag=' + CAST(@IsiniFlag as varchar(4)) + '
	
		WHERE BillNumberId=' + @BillNumberID + ' AND (DraftFlag!=' + CAST(@DraftFlag as varchar(4)) + ' OR IsIniFlag!=' + CAST(@IsiniFlag as varchar(4))+')';
	EXEC (@SQL)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波


处理结算

*/
CREATE   PROCEDURE Gp_Deal_JS 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT
)
--@encode$--
AS

DECLARE
	@Sql				VARCHAR(8000),
	@numTotal			 NUMERIC(24, 10) ,
	@intVipCardID		INT,
	@chvATypeID			VARCHAR(50),
	@Goodsbillnumberid	numeric(10,0),
	@GoodsbillDetailid	INT,
	@completetotal		 NUMERIC(24, 10) ,
	@ncompletetotal		 NUMERIC(24, 10) 

DECLARE @typeid  INT,
		@STypeID VARCHAR(100)

--BillType (4,66,189)
SELECT @STypeID=StypeID FROM dbo.BillIndex WHERE BillNumberId=@nBillID AND BillType=@nBillType
SELECT @typeid=nid FROM dbo.Ac_Items WHERE UserCode='2181'

IF @nBillType = 4 --收款单
BEGIN
	--修改关联单据的实付金额，并将关联ID置为0
	--UPDATE dbo.OrderIndex SET totalinmoney=totalinmoney-g.total,ntotalinmoney=ntotalinmoney-g.ntotal
	--FROM dbo.gatheringBill g,dbo.OrderIndex o
	--WHERE g.RelevanceBillId=o.billNumberId AND g.BillNumberId=@nBillID 
	
	--会员储值时还要红冲会员卡的金额（需要判断能否红冲）
	--UPDATE dbo.gatheringBill SET RelevanceBillId=0 WHERE BillNumberId=@nBillID
	IF EXISTS(
		SELECT BillNumberId 
		FROM gatheringBill
		WHERE BillNumberId=@nBillID AND ATypeID=@typeid AND VipCardID>0
	)
	BEGIN
		DECLARE CreateMx_CURSOR CURSOR FOR
		SELECT	ATypeID,Total,VipCardID
		FROM	GatheringBill
		WHERE	BillNumberId = @nBillID AND ATypeID=@typeid AND VipCardID>0

		OPEN CreateMx_CURSOR
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,
												@numTotal,
												@intVipCardID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- 循环写入 ListTable
			UPDATE	nVipCardSign
			SET		cZyeMoney = cZyeMoney + @numTotal
			WHERE	VipCardID = @intVipCardID
			
			--更新对应分支机构会员卡储值余额
			UPDATE dbo.nVipCardSignStype
			SET
				cZyeMoney=cZyeMoney+@numTotal,
				lJxFczMoney=lJxFczMoney-@numTotal,
				bNxFczMoney=bNxFczMoney-@numTotal
			WHERE StypeID=@STypeID AND VipCardID = @intVipCardID
				
			FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,
													@numTotal,
													@intVipCardID
		END
		CLOSE CreateMx_CURSOR
		DEALLOCATE CreateMx_CURSOR
	END
END	

IF @nBillType = 189 --
BEGIN
	--会员储值时还要红冲会员卡的金额（需要判断能否红冲）
	
	IF EXISTS(
		SELECT BillNumberId 
		FROM PreBill
		WHERE BillNumberId=@nBillID AND ATypeID=@typeid AND VipCardID>0
	)
	BEGIN
		DECLARE CreateMx_CURSOR CURSOR FOR
		SELECT	ATypeID,Total,VipCardID
		FROM	PreBill
		WHERE	BillNumberId = @nBillID AND ATypeID=@typeid AND VipCardID>0

		OPEN CreateMx_CURSOR
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,
												@numTotal,
												@intVipCardID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- 循环写入 ListTable
			UPDATE	nVipCardSign
			SET		cZyeMoney = cZyeMoney + @numTotal
			WHERE	VipCardID = @intVipCardID
			
			--更新对应分支机构会员卡储值余额
			UPDATE dbo.nVipCardSignStype
			SET
				cZyeMoney=cZyeMoney+@numTotal,
				bNxFczMoney=bNxFczMoney-@numTotal,
				lJxFczMoney=lJxFczMoney-@numTotal
			WHERE StypeID=@STypeID AND VipCardID = @intVipCardID
				
			FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,
													@numTotal,
													@intVipCardID
		END
		CLOSE CreateMx_CURSOR
		DEALLOCATE CreateMx_CURSOR
	END
END	

-- 处理按单结算的收付款红冲返回问题
-- ***********************************************************
IF @nBillType IN (4,66)
BEGIN
	SELECT GoodsBillID AS BillNumberID,BillType INTO #BillIDTable
	FROM CompleteTotal WHERE MoneyBillID = @nBillID AND Draft = 0
	
	--红冲应收\应付增加\减少单要回写到明细
	DECLARE WRITEBACKMx_CURSOR CURSOR FOR
	SELECT	GoodsBillID,
			GoodsBillDetailID,
			CompleteTotal,
			NCompleteTotal
	FROM	dbo.CompleteTotal
	WHERE	MoneyBillID = @nBillID 
			AND GoodsBillDetailID is NOT NULL
			AND GoodsBillDetailID <>0
	
	OPEN WRITEBACKMx_CURSOR
	FETCH NEXT FROM WRITEBACKMx_CURSOR INTO	@Goodsbillnumberid,@goodsbilldetailid,@completetotal,@ncompletetotal
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@Goodsbillnumberid AND BillType IN (115,129))
		BEGIN
			UPDATE	dbo.AdDebtBill
			SET		CompleteTotal=CompleteTotal + @completetotal,
					NCompleteTotal=NCompleteTotal + @ncompletetotal
			WHERE   ID=@goodsbilldetailid
			
			UPDATE	dbo.AdDebtBill
			SET		JsStyle=CASE WHEN CompleteTotal=0 THEN 0 ELSE  JsStyle END  ,
					jsState=CASE WHEN CompleteTotal=0 THEN 0
								 WHEN CompleteTotal<>0 AND  ABS(total)<= ABS(ISNULL(CompleteTotal,0)+ ISNULL(ChargeOffTotal,0)) THEN 2
								 WHEN CompleteTotal<>0 AND  ABS(total)> ABS(ISNULL(CompleteTotal,0)+ ISNULL(ChargeOffTotal,0)) THEN 1
								 END 
			WHERE   ID=@goodsbilldetailid
			
			
		END
		
		IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@Goodsbillnumberid AND BillType IN (116,128))
		BEGIN
			UPDATE	dbo.AdDebtBill
			SET		CompleteTotal=CompleteTotal-@completetotal,
					NCompleteTotal=NCompleteTotal-@ncompletetotal
			WHERE   ID=@goodsbilldetailid
		
			UPDATE	dbo.AdDebtBill
			SET		JsStyle=CASE WHEN ISNULL(NCompleteTotal,0)+ ISNULL(NChargeOffTotal,0)=0 THEN 0 ELSE JsStyle END  ,
					jsState=CASE WHEN ISNULL(NCompleteTotal,0)+ ISNULL(NChargeOffTotal,0)=0 THEN 0
								 WHEN NTotal> ISNULL(NCompleteTotal,0)+ ISNULL(NChargeOffTotal,0) THEN 1
								 ELSE 2
							END 
			WHERE   ID=@goodsbilldetailid
		END
		FETCH NEXT FROM WRITEBACKMx_CURSOR INTO	@Goodsbillnumberid,@goodsbilldetailid,@completetotal,@ncompletetotal
	END
	CLOSE WRITEBACKMx_CURSOR
	DEALLOCATE WRITEBACKMx_CURSOR
END


/* 处理按商品结算 - Start */
IF @nBillType IN (4,66)
BEGIN
	DECLARE @numGoodsBillID numeric(10,0),@numCompleteGoodQty  NUMERIC(24, 10) ,@intID int
	DECLARE @intDetailBillType int,@chvDetailDBName varchar(50)
	DECLARE	@numCompleteGoodTotal  NUMERIC(24, 10) ,@numNCompleteGoodTotal  NUMERIC(24, 10) 



	DECLARE Complete_Cursor CURSOR FOR
		SELECT GoodsBillID,CompleteGoodQty,BillID,CompleteGoodTotal,NCompleteGoodTotal,BillType 
		FROM CompleteGoodTotal
		WHERE MoneyBillID = @nBillID
	OPEN Complete_Cursor
	FETCH NEXT FROM Complete_Cursor INTO @numGoodsBillID,@numCompleteGoodQty,@intID,@numCompleteGoodTotal,@numNCompleteGoodTotal,@intDetailBillType
	WHILE @@FETCH_STATUS = 0
	BEGIN
		

		IF @intDetailBillType IN (11, 203)		SET @chvDetailDBName = 'SaleBill'
		ELSE IF @intDetailBillType = 12			SET @chvDetailDBName = 'PT_Combin_SaleBill'
		ELSE IF @intDetailBillType = 45			SET @chvDetailDBName = 'SaleBackBill'
		ELSE IF @intDetailBillType = 46			SET @chvDetailDBName = 'PT_Combin_SaleBackBill'
		ELSE IF @intDetailBillType = 4			SET @chvDetailDBName = 'GatheringBill'
		ELSE IF @intDetailBillType = 34			SET @chvDetailDBName = 'BuyBill'
		ELSE IF @intDetailBillType = 6			SET @chvDetailDBName = 'BuyBackBill'
		ELSE IF @intDetailBillType = 66			SET @chvDetailDBName = 'PayBill'
		ELSE IF @intDetailBillType = 77			SET @chvDetailDBName = 'MoveMoneyBill'
		ELSE IF @intDetailBillType IN (115,116,128,129)	SET @chvDetailDBName = 'adDebtBill'
		ELSE IF @intDetailBillType = 57			SET @chvDetailDBName = 'adPriceBill'
		ELSE IF @intDetailBillType = 17			SET @chvDetailDBName = 'MoveBill'
		ELSE IF @intDetailBillType = 21			SET @chvDetailDBName = 'MoveBjBill'
		ELSE IF @intDetailBillType IN (36,93,5,10,78,84,85,158)	SET @chvDetailDBName = 'MoneyBill'
		ELSE IF @intDetailBillType = 77			SET @chvDetailDBName = 'MoveMoneyBill'
		ELSE IF @intDetailBillType = 305		SET @chvDetailDBName = 'RetailBill'
		ELSE IF @intDetailBillType = 215		SET @chvDetailDBName = 'RetailBackBill'
		ELSE IF @intDetailBillType = 139		SET @chvDetailDBName = 'GiveBill'
		ELSE IF @intDetailBillType =126			SET @chvDetailDBName = 'GivemeBill'
		ELSE IF @intDetailBillType = 148		SET @chvDetailDBName = 'Advantage'
		ELSE IF @intDetailBillType IN (149,151)	SET @chvDetailDBName = 'PriceProtectBill'
		ELSE IF @intDetailBillType = 150		SET @chvDetailDBName = 'Advantage'
		ELSE IF @intDetailBillType IN (140,141,142,143,144,145,146,147)	SET @chvDetailDBName = 'CommissionBill'
		ELSE IF @intDetailBillType = 155		SET @chvDetailDBName = 'GoodsExchangeBill'
		ELSE IF @intDetailBillType = 157		SET @chvDetailDBName = 'RepairDealDetail'
		ELSE IF @intDetailBillType = 159		SET @chvDetailDBName = 'AccountCredence'	-- 会计凭证
		ELSE IF @intDetailBillType = 160		SET @chvDetailDBName = 'SaleGoodsExchangeBill'	-- 销售换货单
		ELSE IF @intDetailBillType = 161		SET @chvDetailDBName = 'BuyGoodsExchangeBill'	-- 采购换货单
		ELSE IF @intDetailBillType = 167		SET @chvDetailDBName = 'wx_Bill_GetBack'	-- 新维修 - 取件单
		ELSE IF @intDetailBillType = 168		SET @chvDetailDBName = 'wx_Bill_Replace'	-- 新维修 - 整机更换单
		ELSE IF @intDetailBillType = 170		SET @chvDetailDBName = 'wx_Bill_SendBack'	-- 新维修 - 送修返回单
		ELSE IF @intDetailBillType IN (404,405) SET @chvDetailDBName = 'ReceiptBill'
		ELSE SET @chvDetailDBName = ''
		
		IF @chvDetailDBName <> ''
		BEGIN
			--红冲开票可能数量、金额负数，新增分支不取绝对值
			IF @intDetailBillType IN (404,405)
			BEGIN
				SET @Sql = '
				UPDATE	' + @chvDetailDBName + '
				SET		CompleteQty = ISNULL(CompleteQty,0) - ' + CAST((ISNULL(@numCompleteGoodQty,0)) AS varchar(50)) + ',
						CompleteTotal = ISNULL(CompleteTotal,0) - ' + CAST((ISNULL(@numCompleteGoodTotal,0)) AS varchar(50)) + ',
						NCompleteTotal = ISNULL(NCompleteTotal,0) - ' + CAST((ISNULL(@numNCompleteGoodTotal,0)) AS varchar(50)) + '
				WHERE	BillNumberID = ' + CAST(@numGoodsBillID AS varchar(50)) + '
						AND [ID] = ' + CAST(@intID AS varchar(50))
			END
			ELSE
			BEGIN
				SET @Sql = '
				UPDATE	' + @chvDetailDBName + '
				SET		CompleteQty = ISNULL(CompleteQty,0) - ' + CAST(ABS(ISNULL(@numCompleteGoodQty,0)) AS varchar(50)) + ',
						CompleteTotal = ISNULL(CompleteTotal,0) - ' + CAST(ABS(ISNULL(@numCompleteGoodTotal,0)) AS varchar(50)) + ',
						NCompleteTotal = ISNULL(NCompleteTotal,0) - ' + CAST(ABS(ISNULL(@numNCompleteGoodTotal,0)) AS varchar(50)) + '
				WHERE	BillNumberID = ' + CAST(@numGoodsBillID AS varchar(50)) + '
						AND [ID] = ' + CAST(@intID AS varchar(50))
			END
			EXEC(@Sql)
			
			
		END
		FETCH NEXT FROM Complete_Cursor INTO @numGoodsBillID,@numCompleteGoodQty,@intID,@numCompleteGoodTotal,@numNCompleteGoodTotal,@intDetailBillType
	END
	CLOSE Complete_Cursor
	DEALLOCATE Complete_Cursor
END

/* 处理按商品结算 - End */

---------- 处理按单结算的收付款红冲返回问题----------------------

IF @nBillType IN (4,66,189)
BEGIN
	DELETE FROM CompleteTotal WHERE  MoneyBillID = @nBillID	-- 处理按单结算的问题
	DELETE FROM CompleteGoodTotal WHERE  MoneyBillID = @nBillID
	DELETE FROM dbo.CompleteBrandarTotal WHERE  MoneyBillId=@nBillID

END 
ELSE
BEGIN
	DELETE FROM CompleteTotal WHERE GoodsBillID = @nBillID  AND BillType=@nBillType	-- 处理按单结算的问题
	DELETE FROM CompleteGoodTotal WHERE GoodsBillID = @nBillID AND BillType=@nBillType
	DELETE FROM dbo.CompleteBrandarTotal WHERE GoodsBillID=@nBillID AND BillType=@nBillType
END 

------------------- 处理按商品结算 - End ---------------------

IF @nBillType IN (4,66)
BEGIN
	-- *** 处理九种单据结算状态 - Start ***
	DECLARE @intComBillType int,@TotalMoney  NUMERIC(24, 10) ,@TotalInMoney  NUMERIC(24, 10) ,@isini INT =1
	DECLARE @numPreferencemoney  NUMERIC(24, 10) ,@numCompleteTotal  NUMERIC(24, 10) ,@intGoodsNumberId int
	
	-- jsStyle：0 - 无，1 - 按单结算，2 - 按商品结算,3--按品牌结算
	-- jsState：0 - 未结算，1 - 未完成结算，2 - 结算完成
	DECLARE @jsStyle char(1),@jsState char(1)
	
	DECLARE Bill_Cursor CURSOR FOR
		SELECT BillNumberID,BillType FROM #BillIDTable
	OPEN Bill_Cursor
	FETCH NEXT FROM Bill_Cursor INTO @intGoodsNumberId,@intComBillType
	WHILE ( @@FETCH_STATUS = 0 )
	BEGIN
		IF @intComBillType IN (404,405)
		BEGIN
			SELECT @isini=IsIni,@TotalMoney=TotalMoney,@TotalInMoney=0,
			@numPreferencemoney=0,@numCompleteTotal=CompleteTotal,@jsStyle=JSStyle
			FROM ReceiptBillIndex WHERE BillnumberID=@intGoodsNumberId
		END
		IF @intComBillType IN (423,424,425,426)
		BEGIN
			SELECT @isini=IsIni,@TotalMoney=TotalMoney,@TotalInMoney=TotalInMoney,
			@numPreferencemoney=preferencemoney,@numCompleteTotal=CompleteTotal
			FROM dbo.Coupon_BillIndex WHERE BillnumberID=@intGoodsNumberId
		END
		ELSE
		BEGIN
			SELECT @isini=IsIni,@TotalMoney=TotalMoney,@TotalInMoney=TotalInMoney,
			@numPreferencemoney=preferencemoney,@numCompleteTotal=CompleteTotal,@jsStyle=JSStyle
			FROM BillIndex WHERE BillnumberID=@intGoodsNumberId
		END
		
		DECLARE @ifBrandar INT=0
		IF EXISTS (SELECT TOP 1 1 FROM  dbo.BillMulBrand WHERE BillNumberId=@intGoodsNumberId AND BillType=@intComBillType )
			SELECT @ifBrandar=1
			
		DECLARE @ExpenseToAr INT=0
		SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';

		DECLARE @btypeid VARCHAR(50)
		SELECT @btypeid=BTYPEID FROM BILLINDEX WHERE BillNumberId=@intGoodsNumberId AND BillType=36 
		IF @intComBillType=36 AND NOT (@ExpenseToAr=1 AND LEFT(@btypeid,5)='00001')
			SELECT @ifBrandar=0 --没配置的 或者 不是客户的 都是 按单结算
		
		IF @isini=0 --非期初单据保留原来逻辑
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsBillID=@intGoodsNumberId AND Draft = 0 AND CompleteTotal<>0)
			BEGIN
				--IF @numCompleteTotal <> 0 OR @numPreferencemoney <> 0
				--BEGIN
					IF (@TotalMoney>=0 AND (@TotalMoney-@numPreferencemoney) <= @numCompleteTotal+@TotalInMoney)
					OR (@TotalMoney<0 AND (@TotalMoney-@numPreferencemoney) >= @numCompleteTotal+@TotalInMoney)
					BEGIN
						IF @TotalInMoney <> 0
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = CASE WHEN @ifBrandar=0 THEN  '1' ELSE '3' END,jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE IF  @intComBillType IN (423,424,425,426)
							BEGIN
								UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = CASE WHEN @ifBrandar=0 THEN  '1' ELSE '3' END,jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
						END
						ELSE
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE IF  @intComBillType IN (423,424,425,426)
							BEGIN
								UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '0',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
						END
					END
					ELSE 
					BEGIN
						IF @TotalInMoney <> 0
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = CASE WHEN @ifBrandar=0 THEN  '1' ELSE '3' END,jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE IF  @intComBillType IN (423,424,425,426)
							BEGIN
								UPDATE dbo.Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle =  CASE WHEN @ifBrandar=0 THEN  '1' ELSE '3' END,jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
						END
						ELSE
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE IF  @intComBillType IN (423,424,425,426)
							BEGIN
								UPDATE dbo.Coupon_BillIndex SET jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
						END
					END
				--END
				--ELSE
				--	UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
			END
			ELSE 
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=@intGoodsNumberId AND Draft = 0 AND CompleteGoodQTY<>0)
				AND NOT EXISTS (SELECT TOP 1 1 FROM dbo.CompleteBrandarTotal WHERE GoodsBillID=@intGoodsNumberId AND isDraft = 0 AND CompleteTotal<>0)
				BEGIN
					IF (@TotalMoney>=0 AND (@TotalMoney-@numPreferencemoney) <= @numCompleteTotal+@TotalInMoney)
					OR (@TotalMoney<0 AND (@TotalMoney-@numPreferencemoney) >= @numCompleteTotal+@TotalInMoney)
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle =  CASE WHEN @ifBrandar=0 THEN  '1' ELSE '3' END,jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE IF  @intComBillType IN (423,424,425,426)
							BEGIN
								UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle =  CASE WHEN @ifBrandar=0 THEN  '1' ELSE '3' END,jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
					END
					ELSE
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = CASE WHEN @ifBrandar=0 THEN  '1' ELSE '3' END,jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE IF  @intComBillType IN (423,424,425,426)
							BEGIN
								UPDATE dbo.Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle =  CASE WHEN @ifBrandar=0 THEN  '1' ELSE '3' END,jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
					END
				END
				ELSE IF  EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=@intGoodsNumberId AND Draft = 0 AND CompleteGoodQTY<>0)
				BEGIN
					IF @intComBillType NOT IN (160,161)
					BEGIN
						IF(@TotalMoney-@numPreferencemoney)=(@numCompleteTotal+@TotalInMoney)
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
						END
						ELSE
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
						END
					END
					ELSE
					BEGIN
						DECLARE @sumComGoodQtyOut  NUMERIC(24, 10) ,@sumBillGoodQtyOut  NUMERIC(24, 10) 
						DECLARE @sumComGoodQtyIn  NUMERIC(24, 10) ,@sumBillGoodQtyIn  NUMERIC(24, 10) 
						SELECT @sumComGoodQtyOut=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
						WHERE GoodsBillID=@intGoodsNumberId AND InOrOut = 'O' AND Draft = 0
						SELECT @sumComGoodQtyIn=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
						WHERE GoodsBillID=@intGoodsNumberId AND InOrOut = 'I' AND Draft = 0
						IF @intComBillType = 160
						BEGIN
							SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
							WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
							SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
							WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
						END
						IF @intComBillType = 161
						BEGIN
							SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
							WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
							SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
							WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
						END
						IF (@TotalMoney-@numPreferencemoney)=(@numCompleteTotal+@TotalInMoney) AND
							(@sumComGoodQtyOut+@sumComGoodQtyIn)=(@sumBillGoodQtyOut+@sumBillGoodQtyIn)
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
						END
						ELSE
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
						END
					END
				END
				ELSE IF EXISTS (SELECT TOP 1 1 FROM dbo.CompleteBrandarTotal WHERE GoodsBillID=@intGoodsNumberId AND isDraft = 0 AND CompleteTotal<>0)
				BEGIN 
					IF (@TotalMoney>=0 AND (@TotalMoney-@numPreferencemoney) <= @numCompleteTotal+@TotalInMoney)
					OR (@TotalMoney<0 AND (@TotalMoney-@numPreferencemoney) >= @numCompleteTotal+@TotalInMoney)
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
					END
					ELSE
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
					END
				END 
			END
		END
		ELSE--期初单据
		BEGIN
			IF (@TotalMoney>=0 AND (@TotalMoney-@numPreferencemoney) <= @numCompleteTotal+@TotalInMoney)
					OR (@TotalMoney<0 AND (@TotalMoney-@numPreferencemoney) >= @numCompleteTotal+@TotalInMoney)
				BEGIN
					IF @numCompleteTotal=0
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '0' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '0' WHERE BillNumberID=@intGoodsNumberId
							END
					END
				END
				ELSE 
				BEGIN
					IF @numCompleteTotal <> 0
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
					END
					ELSE
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
					END
				END
		END
		
		IF @intComBillType IN (115,116,128,129)
		BEGIN 
			--重算表头的结算方式
			UPDATE a
			SET  jsstyle= 0
			FROM billindex a
			WHERE NOT  EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsstyle IN (1,3)
				AND a.BillNumberId=AdDebtBill.BillNumberId
			) AND a.BillNumberId=@intGoodsNumberId

			UPDATE a
			SET  jsstyle= 1
			FROM billindex a
			WHERE EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsstyle =1
				AND a.BillNumberId=AdDebtBill.BillNumberId
			)
			AND NOT EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsstyle =3
				AND a.BillNumberId=AdDebtBill.BillNumberId
			) AND a.BillNumberId=@intGoodsNumberId
			
			UPDATE a
			SET  jsstyle= 4
			FROM billindex a
			WHERE EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsstyle =1
				AND a.BillNumberId=AdDebtBill.BillNumberId
			)
			AND EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsstyle =3
				AND a.BillNumberId=AdDebtBill.BillNumberId
			) AND a.BillNumberId=@intGoodsNumberId
			
			UPDATE a
			SET  jsstyle= 3
			FROM billindex a
			WHERE NOT EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsstyle =1
				AND a.BillNumberId=AdDebtBill.BillNumberId
			)
			AND EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsstyle =3
				AND a.BillNumberId=AdDebtBill.BillNumberId
			)AND a.BillNumberId=@intGoodsNumberId
		
			UPDATE a
			SET  jsState= 2
			FROM billindex a
			WHERE EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsState =2
				AND a.BillNumberId=AdDebtBill.BillNumberId
			)
			AND NOT EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsState IN (0,1)
				AND a.BillNumberId=AdDebtBill.BillNumberId
			)AND a.BillNumberId=@intGoodsNumberId
			
			UPDATE a
			SET  jsState= 1
			FROM billindex a
			WHERE EXISTS (
				SELECT  BillNumberId
				FROM AdDebtBill
				WHERE jsState IN (0,1)
				AND a.BillNumberId=AdDebtBill.BillNumberId
			) AND a.jsStyle<>0 AND a.BillNumberId=@intGoodsNumberId
		END 

		FETCH NEXT FROM Bill_Cursor INTO @intGoodsNumberId,@intComBillType
	END
	CLOSE Bill_Cursor	-- 关闭游标
	DEALLOCATE Bill_Cursor	-- 释放游标所使用的资源
	
	DROP TABLE #BillIDTable
	IF @@ERROR <> 0 RETURN -7
	-- *** 处理九种单据结算状态 - End ***
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波


处理结算

*/
CREATE   PROCEDURE Gp_Deal_JS_OldBill 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT
)
--@encode$--
AS

DECLARE
	@Sql				VARCHAR(8000),
	@numTotal			 NUMERIC(24, 10) ,
	@intVipCardID		INT,
	@chvATypeID			VARCHAR(50),
	@STypeID			VARCHAR(50)
	
DECLARE @typeid INT
SELECT @typeid=nid FROM dbo.Ac_Items WHERE UserCode='2181'	

IF @nBillType = 4 --收款单
BEGIN
	--会员储值时还要红冲会员卡的金额（需要判断能否红冲）
	SELECT @STypeID=STypeID FROM dbo.BillIndex WHERE BillNumberId=@nBillId
	
	IF EXISTS(
		SELECT BillNumberId 
		FROM Old_GatheringBill
		WHERE BillNumberId=@nBillID AND ATypeID=@typeid AND VipCardID>0
	)
	BEGIN
		DECLARE CreateMx_CURSOR CURSOR FOR
		SELECT	ATypeID,Total,VipCardID
		FROM	Old_GatheringBill
		WHERE	BillNumberId = @nBillID AND ATypeID=@typeid AND VipCardID>0

		OPEN CreateMx_CURSOR
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,
												@numTotal,
												@intVipCardID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- 循环写入 ListTable
			UPDATE	nVipCardSign
			SET		cZyeMoney = cZyeMoney + @numTotal
			WHERE	VipCardID = @intVipCardID
			
			UPDATE dbo.nVipCardSignStype
			SET 
				cZyeMoney=cZyeMoney+@numTotal,
				lJxFczMoney=lJxFczMoney-@numTotal,
				bNxFczMoney=bNxFczMoney-@numTotal
			WHERE VipCardID=@intVipCardId AND StypeId=@STypeID
			
			FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,
													@numTotal,
													@intVipCardID
		END
		CLOSE CreateMx_CURSOR
		DEALLOCATE CreateMx_CURSOR
	END	
END		

IF @nBillType = 189 --
BEGIN
	--会员储值时还要红冲会员卡的金额（需要判断能否红冲）
	SELECT @STypeID=STypeID FROM dbo.BillIndex WHERE BillNumberId=@nBillId
	
	IF EXISTS(
		SELECT BillNumberId 
		FROM Old_PreBill
		WHERE BillNumberId=@nBillID AND ATypeID=@typeid AND VipCardID>0
	)
	BEGIN
		DECLARE CreateMx_CURSOR CURSOR FOR
		SELECT	ATypeID,Total,VipCardID
		FROM	Old_PreBill
		WHERE	BillNumberId = @nBillID AND ATypeID=@typeid AND VipCardID>0

		OPEN CreateMx_CURSOR
		FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,
												@numTotal,
												@intVipCardID
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- 循环写入 ListTable
			UPDATE	nVipCardSign
			SET		cZyeMoney = cZyeMoney + @numTotal
			WHERE	VipCardID = @intVipCardID
			
			UPDATE dbo.nVipCardSignStype
			SET 
				cZyeMoney=cZyeMoney+@numTotal,
				lJxFczMoney=lJxFczMoney-@numTotal,
				bNxFczMoney=bNxFczMoney-@numTotal
			WHERE VipCardID=@intVipCardId AND StypeId=@STypeID
				
			FETCH NEXT FROM CreateMx_CURSOR INTO	@chvATypeID,
													@numTotal,
													@intVipCardID
		END
		CLOSE CreateMx_CURSOR
		DEALLOCATE CreateMx_CURSOR
	END
END	
------------------------------------存在关联的订单需要把订单的实付金额抵消掉 start---------------------------------------------------
DECLARE @total NUMERIC(24,10)
DECLARE @ntotal NUMERIC(24,10)
DECLARE @relevanceBillId NUMERIC(10,0)
IF @nBillType = 4 --收款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM Old_gatheringBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
	BEGIN
		UPDATE dbo.OrderIndex  SET totalinmoney=ISNULL(totalinmoney,0)-ISNULL(G.total,0),ntotalinmoney=ISNULL(ntotalinmoney,0)-ISNULL(G.ntotal,0)
		FROM OrderIndex O INNER JOIN dbo.Old_gatheringBill G ON O.billNumberId=G.RelevanceBillId 
		WHERE G.BillNumberId=@nBillID AND G.RelevanceBillId>0
		UPDATE dbo.gatheringBill SET RelevanceBillId=0 WHERE BillNumberId=@nBillID
	END
END
ELSE IF @nBillType = 66 --付款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM Old_PayBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
	BEGIN
		UPDATE dbo.OrderIndex  SET totalinmoney=ISNULL(totalinmoney,0)-ISNULL(P.total,0),ntotalinmoney=ISNULL(ntotalinmoney,0)-ISNULL(P.ntotal,0)
		FROM OrderIndex O INNER JOIN dbo.Old_PayBill P ON O.billNumberId=P.RelevanceBillId 
		WHERE P.BillNumberId=@nBillID AND P.RelevanceBillId>0
		UPDATE dbo.PayBill SET RelevanceBillId=0 WHERE BillNumberId=@nBillID
	END
END
ELSE IF @nBillType IN (189,190)--预收、付款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM Old_PreBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
	BEGIN
		UPDATE dbo.OrderIndex  SET totalinmoney=ISNULL(totalinmoney,0)-ISNULL(P.total,0),ntotalinmoney=ISNULL(ntotalinmoney,0)-ISNULL(P.ntotal,0)
		FROM OrderIndex O INNER JOIN dbo.Old_PreBill P ON O.billNumberId=P.RelevanceBillId 
		WHERE P.BillNumberId=@nBillID AND P.RelevanceBillId>0
		UPDATE dbo.PreBill SET RelevanceBillId=0 WHERE BillNumberId=@nBillID
	END
END
------------------------------------存在关联的订单需要把订单的实付金额抵消掉 end-----------------------------------------------------


-- 处理按单结算的收付款红冲返回问题
-- ***********************************************************
IF @nBillType IN (4,66)
BEGIN
	SELECT GoodsBillID AS BillNumberID,BillType INTO #BillIDTable
	FROM Old_CompleteTotal WHERE MoneyBillID = @nBillID AND Draft = 0
END



/* 处理按商品结算 - Start */
IF @nBillType IN (4,66)
BEGIN
	DECLARE @numGoodsBillID numeric(10,0),@numCompleteGoodQty  NUMERIC(24, 10) ,@intID int
	DECLARE @intDetailBillType int,@chvDetailDBName varchar(50)
	DECLARE	@numCompleteGoodTotal  NUMERIC(24, 10) ,@numNCompleteGoodTotal  NUMERIC(24, 10) 

	DECLARE Complete_Cursor CURSOR FOR
		SELECT GoodsBillID,CompleteGoodQty,BillID,CompleteGoodTotal,NCompleteTotal,BillType  FROM Old_CompleteGoodTotal
		WHERE MoneyBillID = @nBillID
	OPEN Complete_Cursor
	FETCH NEXT FROM Complete_Cursor INTO @numGoodsBillID,@numCompleteGoodQty,@intID,@numCompleteGoodTotal,@numNCompleteGoodTotal,@intDetailBillType
	WHILE @@FETCH_STATUS = 0
	BEGIN
		

		IF @intDetailBillType IN (11, 203)		SET @chvDetailDBName = 'SaleBill'
		ELSE IF @intDetailBillType = 45			SET @chvDetailDBName = 'SaleBackBill'
		ELSE IF @intDetailBillType = 4			SET @chvDetailDBName = 'GatheringBill'
		ELSE IF @intDetailBillType = 34			SET @chvDetailDBName = 'BuyBill'
		ELSE IF @intDetailBillType = 6			SET @chvDetailDBName = 'BuyBackBill'
		ELSE IF @intDetailBillType = 66			SET @chvDetailDBName = 'PayBill'
		ELSE IF @intDetailBillType = 9			SET @chvDetailDBName = 'LoseBill'
		ELSE IF @intDetailBillType = 14			SET @chvDetailDBName = 'OverFlowBill'
		ELSE IF @intDetailBillType = 16			SET @chvDetailDBName = 'DisassembleBill'
		ELSE IF @intDetailBillType = 77			SET @chvDetailDBName = 'MoveMoneyBill'
		ELSE IF @intDetailBillType IN (115,116,128,129)	SET @chvDetailDBName = 'adDebtBill'
		ELSE IF @intDetailBillType = 57			SET @chvDetailDBName = 'adPriceBill'
		ELSE IF @intDetailBillType = 17			SET @chvDetailDBName = 'MoveBill'
		ELSE IF @intDetailBillType = 21			SET @chvDetailDBName = 'MoveBjBill'
		ELSE IF @intDetailBillType IN (36,93,5,10,78,84,85,158)	SET @chvDetailDBName = 'MoneyBill'
		ELSE IF @intDetailBillType = 77			SET @chvDetailDBName = 'MoveMoneyBill'
		ELSE IF @intDetailBillType = 305		SET @chvDetailDBName = 'RetailBill'
		ELSE IF @intDetailBillType = 215		SET @chvDetailDBName = 'RetailBackBill'
		ELSE IF @intDetailBillType = 139		SET @chvDetailDBName = 'GiveBill'
		ELSE IF @intDetailBillType =126			SET @chvDetailDBName = 'GivemeBill'
		ELSE IF @intDetailBillType = 148		SET @chvDetailDBName = 'Advantage'
		ELSE IF @intDetailBillType IN (149,151)	SET @chvDetailDBName = 'PriceProtectBill'
		ELSE IF @intDetailBillType = 150		SET @chvDetailDBName = 'Advantage'
		ELSE IF @intDetailBillType IN (140,141,142,143,144,145,146,147)	SET @chvDetailDBName = 'CommissionBill'
		ELSE IF @intDetailBillType = 155		SET @chvDetailDBName = 'GoodsExchangeBill'
		ELSE IF @intDetailBillType = 157		SET @chvDetailDBName = 'RepairDealDetail'
		ELSE IF @intDetailBillType = 159		SET @chvDetailDBName = 'AccountCredence'	-- 会计凭证
		ELSE IF @intDetailBillType = 160		SET @chvDetailDBName = 'SaleGoodsExchangeBill'	-- 销售换货单
		ELSE IF @intDetailBillType = 161		SET @chvDetailDBName = 'BuyGoodsExchangeBill'	-- 采购换货单
		ELSE IF @intDetailBillType = 167		SET @chvDetailDBName = 'wx_Bill_GetBack'	-- 新维修 - 取件单
		ELSE IF @intDetailBillType = 168		SET @chvDetailDBName = 'wx_Bill_Replace'	-- 新维修 - 整机更换单
		ELSE IF @intDetailBillType = 170		SET @chvDetailDBName = 'wx_Bill_SendBack'	-- 新维修 - 送修返回单
		ELSE IF @intDetailBillType IN (404,405) SET @chvDetailDBName = 'ReceiptBill'
		ELSE SET @chvDetailDBName = ''

		IF @chvDetailDBName <> ''
		BEGIN
			SET @Sql = '
			UPDATE	' + @chvDetailDBName + '
			SET		CompleteQty = ISNULL(CompleteQty,0) - ' + CAST(ISNULL(@numCompleteGoodQty,0) AS varchar(50)) + ',
					CompleteTotal = ISNULL(CompleteTotal,0) - ' + CAST(ABS(ISNULL(@numCompleteGoodTotal,0)) AS varchar(50)) + ',
					NCompleteTotal = ISNULL(NCompleteTotal,0) - ' + CAST(ABS(ISNULL(@numNCompleteGoodTotal,0)) AS varchar(50)) + '
			WHERE	BillNumberID = ' + CAST(@numGoodsBillID AS varchar(50)) + '
					AND [ID] = ' + CAST(@intID AS varchar(50))
			EXEC(@Sql)
		END
		FETCH NEXT FROM Complete_Cursor INTO @numGoodsBillID,@numCompleteGoodQty,@intID,@numCompleteGoodTotal,@numNCompleteGoodTotal,@intDetailBillType
	END
	CLOSE Complete_Cursor
	DEALLOCATE Complete_Cursor
END

/* 处理按商品结算 - End */


IF @nBillType IN (4,66)
BEGIN
	-- *** 处理九种单据结算状态 - Start ***
	DECLARE @intComBillType int,@TotalMoney  NUMERIC(24, 10) ,@TotalInMoney  NUMERIC(24, 10) ,@isini INT
	DECLARE @numPreferencemoney  NUMERIC(24, 10) ,@numCompleteTotal  NUMERIC(24, 10) ,@intGoodsNumberId int
	
	-- jsStyle：0 - 无，1 - 按单结算，2 - 按商品结算
	-- jsState：0 - 未结算，1 - 未完成结算，2 - 结算完成
	DECLARE @jsStyle char(1),@jsState char(1)
	
	DECLARE Bill_Cursor CURSOR FOR
		SELECT BillNumberID,BillType FROM #BillIDTable
	OPEN Bill_Cursor
	FETCH NEXT FROM Bill_Cursor INTO @intGoodsNumberId,@intComBillType
	WHILE ( @@FETCH_STATUS = 0 )
	BEGIN
		IF @intComBillType IN (404,405)
		BEGIN
			SELECT @isini=IsIni,@TotalMoney=TotalMoney,@TotalInMoney=0,
			@numPreferencemoney=0,@numCompleteTotal=CompleteTotal
			FROM ReceiptBillIndex WHERE BillnumberID=@intGoodsNumberId
		END
		ELSE
		BEGIN
			SELECT @isini=IsIni,@TotalMoney=TotalMoney,@TotalInMoney=TotalInMoney,
			@numPreferencemoney=preferencemoney,@numCompleteTotal=CompleteTotal
			FROM BillIndex WHERE BillnumberID=@intGoodsNumberId
		END
		
		IF @isini=0 --非期初单据保留原来逻辑
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsBillID=@intGoodsNumberId AND Draft = 0 AND CompleteTotal<>0)
			BEGIN
				--IF @numCompleteTotal <> 0 OR @numPreferencemoney <> 0
				--BEGIN
					IF (@TotalMoney>=0 AND (@TotalMoney-@numPreferencemoney) <= @numCompleteTotal+@TotalInMoney)
					OR (@TotalMoney<0 AND (@TotalMoney-@numPreferencemoney) >= @numCompleteTotal+@TotalInMoney)
					BEGIN
						IF @TotalInMoney <> 0
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
						END
						ELSE
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '0',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
						END
					END
					ELSE 
					BEGIN
						IF @TotalInMoney <> 0
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
						END
						ELSE
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
						END
					END
				--END
				--ELSE
				--	UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
			END
			ELSE 
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=@intGoodsNumberId AND Draft = 0 AND CompleteGoodQTY<>0)
				BEGIN
					IF (@TotalMoney>=0 AND (@TotalMoney-@numPreferencemoney) <= @numCompleteTotal+@TotalInMoney)
					OR (@TotalMoney<0 AND (@TotalMoney-@numPreferencemoney) >= @numCompleteTotal+@TotalInMoney)
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
					END
					ELSE
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
					END
				END
				ELSE 
				BEGIN
					IF @intComBillType NOT IN (160,161)
					BEGIN
						IF(@TotalMoney-@numPreferencemoney)=(@numCompleteTotal+@TotalInMoney)
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
						END
						ELSE
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
						END
					END
					ELSE
					BEGIN
						DECLARE @sumComGoodQtyOut  NUMERIC(24, 10) ,@sumBillGoodQtyOut  NUMERIC(24, 10) 
						DECLARE @sumComGoodQtyIn  NUMERIC(24, 10) ,@sumBillGoodQtyIn  NUMERIC(24, 10) 
						SELECT @sumComGoodQtyOut=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
						WHERE GoodsBillID=@intGoodsNumberId AND InOrOut = 'O' AND Draft = 0
						SELECT @sumComGoodQtyIn=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
						WHERE GoodsBillID=@intGoodsNumberId AND InOrOut = 'I' AND Draft = 0
						IF @intComBillType = 160
						BEGIN
							SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
							WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
							SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
							WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
						END
						IF @intComBillType = 161
						BEGIN
							SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
							WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
							SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
							WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
						END
						IF (@TotalMoney-@numPreferencemoney)=(@numCompleteTotal+@TotalInMoney) AND
							(@sumComGoodQtyOut+@sumComGoodQtyIn)=(@sumBillGoodQtyOut+@sumBillGoodQtyIn)
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
							END
						END
						ELSE
						BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
						END
					END
				END
			END
		END
		ELSE--期初单据
		BEGIN
			IF (@TotalMoney>=0 AND (@TotalMoney-@numPreferencemoney) <= @numCompleteTotal+@TotalInMoney)
					OR (@TotalMoney<0 AND (@TotalMoney-@numPreferencemoney) >= @numCompleteTotal+@TotalInMoney)
				BEGIN
					IF @numCompleteTotal=0
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '0' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '0' WHERE BillNumberID=@intGoodsNumberId
							END
					END
				END
				ELSE 
				BEGIN
					IF @numCompleteTotal <> 0
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
							END
					END
					ELSE
					BEGIN
							IF @intComBillType IN (404,405)
							BEGIN
								UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
							ELSE
							BEGIN
								UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
							END
					END
				END
		END
		FETCH NEXT FROM Bill_Cursor INTO @intGoodsNumberId,@intComBillType
	END
	CLOSE Bill_Cursor	-- 关闭游标
	DEALLOCATE Bill_Cursor	-- 释放游标所使用的资源
	
	DROP TABLE #BillIDTable
	IF @@ERROR <> 0 RETURN -7
	-- *** 处理九种单据结算状态 - End ***
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：订单处理库存
	
*/
CREATE          PROCEDURE GP_Deal_OrderQTY
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT,
	@EffectFlag CHAR(4) = '+'	-- +：正向影响库存，-：负向影响库存
)

--@encode$--
AS

DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(100),	--明细表名
		@IndexName VARCHAR(50),		--主表名
		@OrderQtyName VARCHAR(50)='SaleOrderQty',
		@CostPrice varchar(50)='PTypeId'

IF @BillType=301
BEGIN
	SET @OrderQtyName='BuyOrderQty'
END

-- 设置明细表表名
SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType

IF @BillType=313
BEGIN
	SET @TableName='PT_Combin_OrderBillDetail'
END

--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	IF @BillType=301 
	BEGIN
		SET @CostPrice='DiscountPrice'
	END
	ELSE
	BEGIN
		SET @CostPrice='GoodsCostPrice'
	END
END
	
	-- 不存在该维度的记录插入数据，存在该维度的记录则叠加修改库存数据
	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT PTypeId,KTypeID,ISNULL(GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
						ISNULL(CargoID,0) AS CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL('+@CostPrice+',0) ELSE -1 END AS GoodsCostPrice,SUM(QTY) AS QTY 
				FROM ' + @TableName + ' WHERE BillNumberId = ' + @BillNumberID + ' AND BILLOVER=0 AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=ptypeid AND IsService=0) AND KTypeID<>'''' AND CargoID<>0
				GROUP BY PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,'+@CostPrice+'
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@OrderQtyName+'=T.'+@OrderQtyName+''+ @effectflag +'S.QTY
		WHEN NOT MATCHED BY TARGET
		THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,'+@OrderQtyName+') 
		VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.CargoID,S.ItemID,S.IsCombined,S.GoodsCostPrice,'+@effectflag+'S.Qty);'
	EXEC (@SQL)

--处理冗余数据
IF @EffectFlag='-'
BEGIN
	DECLARE @TEMPSQL VARCHAR(8000)=''
	IF @COST='3' 
	BEGIN
		SET @TEMPSQL=@TEMPSQL+'
		DELETE FROM GoodsStocks_Order 
		WHERE PtypeId IN (SELECT ptypeid FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND KtypeId IN (SELECT KTypeID FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsNumber IN (SELECT GoodsNumber FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ProduceDate IN (SELECT ProduceDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ValidDate IN (SELECT ValidDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND CargoID IN (SELECT ISNULL(CargoID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ItemID IN (SELECT ISNULL(ItemID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND IsCombined IN (SELECT ISNULL(IsCombined,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsCostPrice IN (SELECT '+@CostPrice+' FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0'
	END
	ELSE
	BEGIN
		SET @TEMPSQL=@TEMPSQL+'
		DELETE FROM GoodsStocks_Order 
		WHERE PtypeId IN (SELECT ptypeid FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND KtypeId IN (SELECT KTypeID FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsNumber IN (SELECT GoodsNumber FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ProduceDate IN (SELECT ProduceDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ValidDate IN (SELECT ValidDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND CargoID IN (SELECT ISNULL(CargoID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ItemID IN (SELECT ISNULL(ItemID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND IsCombined IN (SELECT ISNULL(IsCombined,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0'
	END
	EXEC(@TEMPSQL)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：订单处理库存
	
*/
CREATE          PROCEDURE GP_Deal_OrderQTY_Stop
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT,
	@OrderID		INT,		--明细ID
	@EffectFlag CHAR(4) = '+'	-- +：正向影响库存，-：负向影响库存
)

--@encode$--
AS

DECLARE @SQL VARCHAR(8000),
		@ConvertOrderID varchar(8000)=cast(@orderid as varchar),
		@TableName VARCHAR(100),	--明细表名
		@IndexName VARCHAR(50),		--主表名
		@OrderQtyName VARCHAR(50)='SaleOrderQty',
		@CostPrice varchar(50)='PTypeId',
		@Type varchar(50)=''

IF @BillType=301
BEGIN
	SET @OrderQtyName='BuyOrderQty'
END

-- 设置明细表表名
SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType

IF @BillType=313
BEGIN
	SET @TableName='PT_Combin_OrderBillDetail'
	SELECT  @ConvertOrderID=stuff
			((SELECT     ',' + CAST(t.OrderID AS varchar)
            FROM     PT_Combin_OrderBillDetail AS t
            WHERE t.billNumberID=A.billNumberID FOR xml path('')), 1, 1, '')
			FROM PT_Combin_OrderBillDetail A
			WHERE A.billNumberID=@BillNumberID
			GROUP BY A.billNumberID
END


--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	IF @BillType=301
	BEGIN
		SET @CostPrice='DiscountPrice'
	END
	ELSE
	BEGIN
		SET @CostPrice='GoodsCostPrice'
	END
END

--处理重复数据，如先中止明细再整单中止
DECLARE @OPERATE VARCHAR(10)=''
IF @effectflag='-'
BEGIN
	--中止
	SET @OPERATE=' = 0 '
END
ELSE
BEGIN
	--解除中止
	SET @OPERATE=' = 1 '
END

IF (@OrderID = -1)--整单
BEGIN

	-- 不存在该维度的记录插入数据，存在该维度的记录则叠加修改库存数据
	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT A.PTypeId,A.KTypeID,ISNULL(A.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(A.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(A.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
						ISNULL(A.CargoID,0) AS CargoID,ISNULL(A.ItemID,0) AS ItemID,ISNULL(A.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(A.'+@CostPrice+',0) ELSE -1 END AS GoodsCostPrice,
						SUM(CASE WHEN ISNULL(A.QTY,0)-ISNULL(A.ReachQty,0)-ISNULL(A.WaitQty,0)>=0 
						THEN ISNULL(A.QTY,0)-ISNULL(A.ReachQty,0)-ISNULL(A.WaitQty,0)
						ELSE 0 END) AS QTY 
				FROM ' + @TableName + ' A   
				WHERE A.BillNumberId = ' + @BillNumberID + ' AND A.BILLOVER '+@OPERATE+' AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=A.ptypeid AND IsService=0) AND A.KTypeID<>'''' AND A.CargoID<>0
				GROUP BY A.PTypeId,A.KTypeID,A.GoodsNumber,A.ProduceDate,A.ValidDate,A.CargoID,A.ItemID,A.IsCombined,A.'+@CostPrice+'
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@OrderQtyName+'=T.'+@OrderQtyName+''+ @effectflag +'S.QTY
		WHEN NOT MATCHED BY TARGET
		THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,'+@OrderQtyName+') 
		VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.CargoID,S.ItemID,S.IsCombined,S.GoodsCostPrice,'+@effectflag+'S.Qty);'
	EXEC (@SQL)
END
ELSE
BEGIN
	
	-- 不存在该维度的记录插入数据，存在该维度的记录则叠加修改库存数据
	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT A.PTypeId,A.KTypeID,ISNULL(A.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(A.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(A.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
						ISNULL(A.CargoID,0) AS CargoID,ISNULL(A.ItemID,0) AS ItemID,ISNULL(A.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(A.'+@CostPrice+',0) ELSE -1 END AS GoodsCostPrice,
						SUM(CASE WHEN ISNULL(A.QTY,0)-ISNULL(A.ReachQty,0)-ISNULL(A.WaitQty,0)>=0 
						THEN ISNULL(A.QTY,0)-ISNULL(A.ReachQty,0)-ISNULL(A.WaitQty,0)
						ELSE 0 END) AS QTY 
				FROM ' + @TableName + ' A    
				WHERE A.BillNumberId = ' + @BillNumberID + ' AND A.OrderID in ('+@ConvertOrderID+') AND A.BILLOVER '+@OPERATE+' AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=A.ptypeid AND IsService=0) AND A.KTypeID<>'''' AND A.CargoID<>0
				GROUP BY A.PTypeId,A.KTypeID,A.GoodsNumber,A.ProduceDate,A.ValidDate,A.CargoID,A.ItemID,A.IsCombined,A.'+@CostPrice+'
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@OrderQtyName+'=T.'+@OrderQtyName+''+ @effectflag +'S.QTY
		WHEN NOT MATCHED BY TARGET
		THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,'+@OrderQtyName+') 
		VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.CargoID,S.ItemID,S.IsCombined,S.GoodsCostPrice,'+@effectflag+'S.Qty);'
	EXEC (@SQL)
END

--处理冗余数据
IF @EffectFlag='-'
BEGIN
	DECLARE @TEMPSQL VARCHAR(8000)=''
	IF @COST='3' 
	BEGIN
		SET @TEMPSQL=@TEMPSQL+'
		DELETE FROM GoodsStocks_Order 
		WHERE PtypeId IN (SELECT ptypeid FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND KtypeId IN (SELECT KTypeID FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsNumber IN (SELECT GoodsNumber FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ProduceDate IN (SELECT ProduceDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ValidDate IN (SELECT ValidDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND CargoID IN (SELECT ISNULL(CargoID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ItemID IN (SELECT ISNULL(ItemID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND IsCombined IN (SELECT ISNULL(IsCombined,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsCostPrice IN (SELECT '+@CostPrice+' FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0'
	END
	ELSE
	BEGIN
		SET @TEMPSQL=@TEMPSQL+'
		DELETE FROM GoodsStocks_Order 
		WHERE PtypeId IN (SELECT ptypeid FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND KtypeId IN (SELECT KTypeID FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsNumber IN (SELECT GoodsNumber FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ProduceDate IN (SELECT ProduceDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ValidDate IN (SELECT ValidDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND CargoID IN (SELECT ISNULL(CargoID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ItemID IN (SELECT ISNULL(ItemID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND IsCombined IN (SELECT ISNULL(IsCombined,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0'
	END
	EXEC(@TEMPSQL)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：订单处理库存:被引用已过账数量
	
*/
CREATE          PROCEDURE GP_Deal_OrderReachQTY
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT,
	@EffectFlag CHAR(4) = '+',	-- +：正向影响库存，-：负向影响库存
	@isaudit INT=0,		--是否全面修改单据
	@isdelete INT=0		--是否删除、红冲单据
)

--@encode$--
AS

DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(100),	--明细表名
		@IndexName VARCHAR(50),		--主表名
		@OrderReachQtyName VARCHAR(50)='SaleReachQty',
		@LimitOrderReachQtyName VARCHAR(50)='LimitSaleQty',
		@LimitOrderQtyName VARCHAR(50)='SaleOrderQty',
		@OrderTableName VARCHAR(100)='OrderBill',	--订单明细表名
		@Groupby varchar(100)='PTypeId'

IF @BillType=34 OR @BillType=144 OR @BillType=400
BEGIN
	SET @OrderReachQtyName='BuyReachQty'
	SET @LimitOrderReachQtyName='LimitBuyQty'
	SET @LimitOrderQtyName='BuyOrderQty'
END
IF @BillType=12
BEGIN
	SET @OrderTableName='PT_Combin_OrderBillDetail'
END

--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	IF @BillType=34 OR @BillType=144 OR @BillType=400
	BEGIN
		SET @Groupby='DiscountPrice'
	END
	ELSE
	BEGIN
		SET @Groupby='GoodsCostPrice'
	END
END

-- 设置明细表表名
SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType
		
-- 不存在该维度的记录插入数据，存在该维度的记录则叠加修改库存数据
SET @SQL = '
	MERGE INTO GoodsStocks_Order AS T
	USING 
		(
			SELECT B.PTypeId,B.KTypeID,ISNULL(B.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(B.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(B.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
					ISNULL(B.CargoID,0) AS CargoID,ISNULL(B.ItemID,0) AS ItemID,ISNULL(B.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(B.'+@Groupby+',0) ELSE -1 END AS GoodsCostPrice,
					SUM(ISNULL(A.QTY,0)) AS QTY
			FROM ' + @TableName + ' A
			LEFT JOIN '+@OrderTableName+' B ON B.ORDERID=A.ORDERID 
			WHERE A.BillNumberId = ' + @BillNumberID + ' AND A.OrderID <> -1 AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'''' AND B.CargoID<>0
			GROUP BY B.PTypeId,B.KTypeID,B.GoodsNumber,B.ProduceDate,B.ValidDate,B.CargoID,B.ItemID,B.IsCombined,B.'+@Groupby+'
		) AS S  
	ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
	AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
	WHEN MATCHED
	THEN UPDATE SET T.'+@OrderReachQtyName+'=T.'+@OrderReachQtyName+''+ @effectflag +'S.QTY
	WHEN NOT MATCHED BY TARGET
	THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,'+@OrderReachQtyName+') 
	VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.CargoID,S.ItemID,S.IsCombined,S.GoodsCostPrice,'+@effectflag+'S.Qty);'
EXEC (@SQL)

--处理LimitSaleQty/LimitBuyQty
DECLARE @LimitCOUNT INT=0,@NLimitSQL NVARCHAR(800)
SET @NLimitSQL = 'SELECT @a=COUNT(*) FROM ' + @OrderTableName + ' A WHERE A.ORDERID IN (SELECT ORDERID FROM ' + @TableName + ' WHERE BillNumberId =  ' + @BillNumberID + ') '
EXEC sp_executesql @NLimitSQL,N'@a int output',@LimitCOUNT output
IF @LimitCOUNT>0
BEGIN
	IF @effectflag='+'
	BEGIN
		EXEC QP_Recount_LimitQty @BillNumberID,@BillType
	END
	ELSE IF  @effectflag='-' --and @isdelete=1 
	BEGIN
		EXEC QP_Recount_LimitQty @BillNumberID,@BillType
	END
END

--处理删除单据，当单据调用了中止订单需要处理订单数量
IF @effectflag='-' and @isaudit=0
BEGIN
	DECLARE @COUNT INT=0,@NSQL NVARCHAR(800)
	SET @NSQL = 'SELECT @a=COUNT(*) FROM ' + @OrderTableName + ' A WHERE A.ORDERID IN (SELECT ORDERID FROM ' + @TableName + ' WHERE BillNumberId =  ' + @BillNumberID + ') AND A.BILLOVER=1 '
	EXEC sp_executesql @NSQL,N'@a int output',@COUNT output
	IF @COUNT>0
	BEGIN
	DECLARE @OrderQtyName VARCHAR(50)='SaleOrderQty'
	IF @BillType=34 OR @BillType=144 OR @BillType=400
	BEGIN
		SET @OrderQtyName='BuyOrderQty'
	END

	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT A.PTypeId,A.KTypeID,ISNULL(A.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(A.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(A.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
						ISNULL(A.CargoID,0) AS CargoID,ISNULL(A.ItemID,0) AS ItemID,ISNULL(A.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(A.'+@Groupby+',0) ELSE -1 END AS GoodsCostPrice,
						SUM(CASE WHEN ISNULL(A.QTY,0)-ISNULL(A.ReachQty,0)-ISNULL(A.WaitQty,0)-ISNULL(B.Qty,0)>0 
						THEN ISNULL(B.Qty,0)
						ELSE CASE WHEN ISNULL(A.QTY,0)-(ISNULL(A.ReachQty,0)+ISNULL(A.WaitQty,0))<=0 THEN 0
						ELSE ISNULL(A.QTY,0)-(ISNULL(A.ReachQty,0)+ISNULL(A.WaitQty,0)) END END) AS QTY
				FROM ' + @OrderTableName + ' A 
				LEFT JOIN
				(
					SELECT ORDERID,SUM(ISNULL(B.Qty,0)) AS QTY FROM '+@TableName+' B WHERE B.BillNumberId = ' + @BillNumberID + ' AND B.OrderID <> -1 GROUP BY ORDERID
				)B ON B.ORDERID=A.ORDERID 
				WHERE A.BILLOVER=1 AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=A.ptypeid AND IsService=0) AND A.KTypeID<>'''' AND A.CargoID<>0
				GROUP BY A.PTypeId,A.KTypeID,A.GoodsNumber,A.ProduceDate,A.ValidDate,A.CargoID,A.ItemID,A.IsCombined,A.'+@Groupby+'
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@OrderQtyName+'=T.'+@OrderQtyName+''+ @effectflag +'S.QTY
		WHEN NOT MATCHED BY TARGET
		THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,'+@OrderQtyName+') 
		VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.CargoID,S.ItemID,S.IsCombined,S.GoodsCostPrice,'+@effectflag+'S.Qty);'
	EXEC (@SQL)
	END
END


--处理冗余数据
IF @EffectFlag='-'
BEGIN
	DECLARE @TEMPSQL VARCHAR(8000)=''
	IF @COST='3' 
	BEGIN
		SET @TEMPSQL=@TEMPSQL+'
		DELETE FROM GoodsStocks_Order 
		WHERE PtypeId IN (SELECT ptypeid FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND KtypeId IN (SELECT KTypeID FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsNumber IN (SELECT GoodsNumber FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ProduceDate IN (SELECT ProduceDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ValidDate IN (SELECT ValidDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND CargoID IN (SELECT ISNULL(CargoID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ItemID IN (SELECT ISNULL(ItemID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND IsCombined IN (SELECT ISNULL(IsCombined,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsCostPrice IN (SELECT GoodsCostPrice FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0'
	END
	ELSE
	BEGIN
		SET @TEMPSQL=@TEMPSQL+'
		DELETE FROM GoodsStocks_Order 
		WHERE PtypeId IN (SELECT ptypeid FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND KtypeId IN (SELECT KTypeID FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsNumber IN (SELECT GoodsNumber FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ProduceDate IN (SELECT ProduceDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ValidDate IN (SELECT ValidDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND CargoID IN (SELECT ISNULL(CargoID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ItemID IN (SELECT ISNULL(ItemID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND IsCombined IN (SELECT ISNULL(IsCombined,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0'
	END
	EXEC(@TEMPSQL)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：订单处理库存:被引用未过账数量
	
*/
CREATE          PROCEDURE GP_Deal_OrderReferQty
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT,
	@EffectFlag CHAR(4) = '+',	-- +：正向影响库存，-：负向影响库存
	@isdelete INT=0		--是否删除、红冲单据
)

--@encode$--
AS

DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(100),	--明细表名
		@IndexName VARCHAR(50),		--主表名
		@OrderReferQtyName VARCHAR(50)='SaleReferQty',
		@LimitOrderReferQtyName VARCHAR(50)='LimitSaleQty',
		@LimitOrderQtyName VARCHAR(50)='SaleOrderQty',
		@OrderTableName VARCHAR(100)='OrderBill',	--订单明细表名
		@Groupby varchar(100)='PTypeId'


IF @BillType=34 OR @BillType=144 OR @BillType=400
BEGIN
	SET @OrderReferQtyName='BuyReferQty'
	SET @LimitOrderReferQtyName='LimitBuyQty'
	SET @LimitOrderQtyName='BuyOrderQty'
END

IF @BillType=12
BEGIN
	SET @OrderTableName='PT_Combin_OrderBillDetail'
END

--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	IF @BillType=34 OR @BillType=144 OR @BillType=400
	BEGIN
		SET @Groupby='DiscountPrice'
	END
	ELSE
	BEGIN
		SET @Groupby='GoodsCostPrice'
	END
END

-- 设置明细表表名
SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType
	
-- 不存在该维度的记录插入数据，存在该维度的记录则叠加修改库存数据
SET @SQL = '
	MERGE INTO GoodsStocks_Order AS T
	USING 
		(
			SELECT  DISTINCT B.PTypeId,B.KTypeID,ISNULL(B.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(B.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(B.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
					ISNULL(B.CargoID,0) AS CargoID,ISNULL(B.ItemID,0) AS ItemID,ISNULL(B.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(B.'+@Groupby+',0) ELSE -1 END AS GoodsCostPrice,
					SUM(ISNULL(A.QTY,0)) AS QTY
			FROM ' + @TableName + ' A
			LEFT JOIN '+@OrderTableName+' B ON B.ORDERID=A.ORDERID 
			WHERE A.BillNumberId = ' + @BillNumberID + ' AND A.OrderID <> -1 AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'''' AND B.CargoID<>0
			GROUP BY B.PTypeId,B.KTypeID,B.GoodsNumber,B.ProduceDate,B.ValidDate,B.CargoID,B.ItemID,B.IsCombined,B.'+@Groupby+'
		) AS S  
	ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND isnull(T.GoodsNumber,'''')=S.GoodsNumber AND isnull(T.ProduceDate,'''')=S.ProduceDate 
	AND isnull(T.ValidDate,'''')=S.ValidDate AND isnull(T.CargoID,0)=S.CargoID AND isnull(T.ItemID,0)=S.ItemID AND isnull(T.IsCombined,0)=S.IsCombined AND isnull(T.GoodsCostPrice,0)=S.GoodsCostPrice
	WHEN MATCHED
	THEN UPDATE SET T.'+@OrderReferQtyName+'=T.'+@OrderReferQtyName+''+ @effectflag +'S.QTY
	WHEN NOT MATCHED BY TARGET
	THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,'+@OrderReferQtyName+') 
	VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.CargoID,S.ItemID,S.IsCombined,S.GoodsCostPrice,'+@effectflag+'S.Qty);'
EXEC (@SQL)

--处理LimitSaleQty/LimitBuyQty
DECLARE @LimitCOUNT INT=0,@NLimitSQL NVARCHAR(800)
SET @NLimitSQL = 'SELECT @a=COUNT(*) FROM ' + @OrderTableName + ' A WHERE A.ORDERID IN (SELECT ORDERID FROM ' + @TableName + ' WHERE BillNumberId =  ' + @BillNumberID + ') '
EXEC sp_executesql @NLimitSQL,N'@a int output',@LimitCOUNT output
IF @LimitCOUNT>0
BEGIN
	IF @effectflag='+'
	BEGIN
		EXEC QP_Recount_LimitQty @BillNumberID,@BillType
	END
	ELSE IF  @effectflag='-' --and @isdelete=1
	BEGIN
		EXEC QP_Recount_LimitQty @BillNumberID,@BillType
	END
END

--处理删除单据，当单据调用了中止订单需要处理订单数量
IF @effectflag='-'
BEGIN
	DECLARE @COUNT INT=0,@NSQL NVARCHAR(800)
	SET @NSQL = 'SELECT @a=COUNT(*) FROM ' + @OrderTableName + ' A WHERE A.ORDERID IN (SELECT ORDERID FROM ' + @TableName + ' WHERE BillNumberId =  ' + @BillNumberID + ') AND A.BILLOVER=1 '
	EXEC sp_executesql @NSQL,N'@a int output',@COUNT output
	IF @COUNT>0
	BEGIN
	DECLARE @OrderQtyName VARCHAR(50)='SaleOrderQty'
	IF @BillType=34 OR @BillType=144 OR @BillType=400
	BEGIN
		SET @OrderQtyName='BuyOrderQty'
	END

	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT  DISTINCT A.PTypeId,A.KTypeID,ISNULL(A.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(A.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(A.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
						ISNULL(A.CargoID,0) AS CargoID,ISNULL(A.ItemID,0) AS ItemID,ISNULL(A.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(A.'+@Groupby+',0) ELSE -1 END AS GoodsCostPrice,
						SUM(CASE WHEN ISNULL(A.QTY,0)-ISNULL(A.ReachQty,0)-ISNULL(A.WaitQty,0)-ISNULL(B.Qty,0)>0 
						THEN ISNULL(B.Qty,0)
						ELSE CASE WHEN ISNULL(A.QTY,0)-(ISNULL(A.ReachQty,0)+ISNULL(A.WaitQty,0))<=0 THEN 0
						ELSE ISNULL(A.QTY,0)-(ISNULL(A.ReachQty,0)+ISNULL(A.WaitQty,0)) END END) AS QTY  
				FROM ' + @OrderTableName + ' A  
				LEFT JOIN
				(
					SELECT ORDERID,SUM(ISNULL(B.Qty,0)) AS QTY FROM '+@TableName+' B WHERE B.BillNumberId = ' + @BillNumberID + ' AND B.OrderID <> -1 GROUP BY ORDERID
				)B ON B.ORDERID=A.ORDERID 
				WHERE A.BILLOVER=1 AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=A.ptypeid AND IsService=0) AND A.KTypeID<>'''' AND A.CargoID<>0
				GROUP BY A.PTypeId,A.KTypeID,A.GoodsNumber,A.ProduceDate,A.ValidDate,A.CargoID,A.ItemID,A.IsCombined,A.'+@Groupby+'
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND isnull(T.GoodsNumber,'''')=S.GoodsNumber AND isnull(T.ProduceDate,'''')=S.ProduceDate 
		AND isnull( T.ValidDate,'''')=S.ValidDate AND isnull( T.CargoID,0)=S.CargoID AND isnull(T.ItemID,0)=S.ItemID AND isnull( T.IsCombined,0)=S.IsCombined AND isnull(T.GoodsCostPrice,0)=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@OrderQtyName+'=T.'+@OrderQtyName+''+ @effectflag +'S.QTY
		WHEN NOT MATCHED BY TARGET
		THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,'+@OrderQtyName+') 
		VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.CargoID,S.ItemID,S.IsCombined,S.GoodsCostPrice,'+@effectflag+'S.Qty);'
	EXEC (@SQL)
	END
END		

--处理冗余数据
IF @EffectFlag='-'
BEGIN
	DECLARE @TEMPSQL VARCHAR(8000)=''
	IF @COST='3' 
	BEGIN
		SET @TEMPSQL=@TEMPSQL+'
		DELETE FROM GoodsStocks_Order 
		WHERE PtypeId IN (SELECT ptypeid FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND KtypeId IN (SELECT KTypeID FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsNumber IN (SELECT GoodsNumber FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ProduceDate IN (SELECT ProduceDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ValidDate IN (SELECT ValidDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND CargoID IN (SELECT ISNULL(CargoID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ItemID IN (SELECT ISNULL(ItemID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND IsCombined IN (SELECT ISNULL(IsCombined,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsCostPrice IN (SELECT GoodsCostPrice FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0'
	END
	ELSE
	BEGIN
		SET @TEMPSQL=@TEMPSQL+'
		DELETE FROM GoodsStocks_Order 
		WHERE PtypeId IN (SELECT ptypeid FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND KtypeId IN (SELECT KTypeID FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND GoodsNumber IN (SELECT GoodsNumber FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ProduceDate IN (SELECT ProduceDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ValidDate IN (SELECT ValidDate FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND CargoID IN (SELECT ISNULL(CargoID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND ItemID IN (SELECT ISNULL(ItemID,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND IsCombined IN (SELECT ISNULL(IsCombined,0) FROM '+@TableName+' WHERE billNumberID=' + @BillNumberID + ')
		AND SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0'
	END
	EXEC(@TEMPSQL)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：销售出库单生成采购入库单处理订单库存
	
*/
CREATE          PROCEDURE GP_Deal_OrderReferQty_BuyBill
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT,
	@EffectFlag CHAR(4) = '+',	-- +：正向影响库存，-：负向影响库存
	@isdelete INT=0		--是否删除、红冲单据
)

--@encode$--
AS

DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(100),	--明细表名
		@IndexName VARCHAR(50),		--主表名
		@OrderReferQtyName VARCHAR(50)='SaleReferQty',
		@LimitOrderReferQtyName VARCHAR(50)='LimitSaleQty',
		@LimitOrderQtyName VARCHAR(50)='SaleOrderQty',
		@OrderTableName VARCHAR(100)='OrderBill',	--订单明细表名
		@Groupby varchar(100)='PTypeId'


IF @BillType=34
BEGIN
	SET @OrderReferQtyName='BuyReferQty'
	SET @LimitOrderReferQtyName='LimitBuyQty'
	SET @LimitOrderQtyName='BuyOrderQty'
END

--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	IF @BillType=34
	BEGIN
		SET @Groupby='DiscountPrice'
	END	
END

-- 设置明细表表名 
SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType
	
-- 不存在该维度的记录插入数据，存在该维度的记录则叠加修改库存数据
SET @SQL = '
	MERGE INTO GoodsStocks_Order AS T
	USING 
		(
			SELECT  DISTINCT B.PTypeId,B.KTypeID,ISNULL(B.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(B.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(B.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
					ISNULL(B.CargoID,0) AS CargoID,ISNULL(B.ItemID,0) AS ItemID,ISNULL(B.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(B.'+@Groupby+',0) ELSE -1 END AS GoodsCostPrice,
					SUM(ISNULL(A.QTY,0)) AS QTY
			FROM BuyBill A
			LEFT JOIN OrderBill B ON B.ORDERID=A.ORDERID 
			WHERE A.BillNumberId = ' + @BillNumberID + ' AND A.OrderID <> -1 AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'''' AND B.CargoID<>0
			GROUP BY B.PTypeId,B.KTypeID,B.GoodsNumber,B.ProduceDate,B.ValidDate,B.CargoID,B.ItemID,B.IsCombined,B.'+@Groupby+'
		) AS S  
	ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND isnull(T.GoodsNumber,'''')=S.GoodsNumber AND isnull(T.ProduceDate,'''')=S.ProduceDate 
	AND isnull(T.ValidDate,'''')=S.ValidDate AND isnull(T.CargoID,0)=S.CargoID AND isnull(T.ItemID,0)=S.ItemID AND isnull(T.IsCombined,0)=S.IsCombined AND isnull(T.GoodsCostPrice,0)=S.GoodsCostPrice
	WHEN MATCHED
	THEN UPDATE SET T.BuyReferQty=T.BuyReferQty + S.QTY
	WHEN NOT MATCHED BY TARGET
	THEN INSERT (PTypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined,GoodsCostPrice,BuyReferQty) 
	VALUES (S.PTypeId,S.KTypeID,S.GoodsNumber,S.ProduceDate,S.ValidDate,S.CargoID,S.ItemID,S.IsCombined,S.GoodsCostPrice,S.Qty);'
EXEC (@SQL)

--处理LimitSaleQty/LimitBuyQty
DECLARE @LimitCOUNT INT=0,@NLimitSQL NVARCHAR(800)
SET @NLimitSQL = 'SELECT @a=COUNT(*) FROM ' + @OrderTableName + ' A WHERE A.ORDERID IN (SELECT ORDERID FROM ' + @TableName + ' WHERE BillNumberId =  ' + @BillNumberID + ') '
EXEC sp_executesql @NLimitSQL,N'@a int output',@LimitCOUNT OUTPUT

IF @LimitCOUNT>0
BEGIN
	IF @effectflag='+'
	BEGIN
		EXEC QP_Recount_LimitQty_BuyBill @BillNumberID,@BillType
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
	作者：谢吉康
	日期：2007-4-10
	描述：账龄分析配置
*/
CREATE PROCEDURE Gp_DealAccountTimeConfig
(
	@OperatorId		varchar(100),
	@ColName		varchar(10),
	@ColValue		varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

IF @ColValue = ''
	SET @ColValue = 0

--修改记录
DECLARE @SQL varchar(8000)

SET @SQL = 'UPDATE	AccountTimeConfig
			SET		Col'+@ColName+'='+char(39)+@ColValue+char(39)+'
			WHERE	ETypeId = '+char(39)+@OperatorId+char(39)

--PRINT(@SQL)
EXEC(@SQL)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DealAdjust]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_DealAdjust]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2007-11-22
	描述：VIP消费调整和积分调整
	SELECT * FROM nVipAdjust
	
	2012-07-18
	录单日期不能小于开帐日期 调整
*/
CREATE PROCEDURE Gp_DealAdjust
(
	@Checke		VARCHAR(100),--制单人
	@BillCode	VARCHAR(200),--单据编号
	@BillDate	VARCHAR(20),--录单日期
	@Employee	VARCHAR(200),--经手人
	@CardNo		VARCHAR(max),--卡号
	@UpMoney	VARCHAR(20),--本次调增积分
	@DownMoney	VARCHAR(20),--本次调减积分
	@SumMoney	VARCHAR(20),--调整积分合计
	@Reason		VARCHAR(300),--调整原因
	@isSend		VARCHAR(10),
	@nType		int	--1：消费调整 2：积分调整 3：清零
)
--@encode$--
AS
SET NOCOUNT ON

--排除积分清零
IF(@nType<>3)
	BEGIN
		--开账前不能过账
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'inicanmodify' AND SubValue = 'T')
			RETURN -5

		--判断单据编号是否为空
		IF RTRIM(LTRIM(@BillCode))=''
			RETURN -4
			
		--录单日期不能小于开帐日期
		IF EXISTS(SELECT TOP 1 1 FROM MonthProc WHERE Period =(select subvalue from sysdata where subname='period') AND StartDate>@BillDate)
			RETURN -3
						
		--判断编号是否重复
		IF EXISTS(SELECT TOP 1 1 FROM nVipAdjust WHERE BillCode = @BillCode)
			RETURN -2	
			
		--判断是否存在该会员卡号
		IF NOT EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardCode=@CardNo)
			RETURN -6		
	END

--积分清零
IF(@nType=3)
	BEGIN
		UPDATE N 
		SET 
			TotalCent=0,
			BeginCent=0 
		FROM nVipCardSign N 
		INNER JOIN f_split(@CardNo,',') C ON C.a=N.VipCardCode
		
		INSERT INTO VipClearLog
		(
			LogTime,--日期
			Comment,--备注
			checker,--制单人
			CardNo--会员卡号
		)
		VALUES
		(
			@BillDate,
			'积分清零',
			@Checke,
			@CardNo
		)
	END
ELSE IF(@nType IN(1,2))--1：消费调整 2：积分调整
	BEGIN
		DECLARE 
			@nBillId 	NUMERIC(18,0)=1,--单据id
			@CardNoId	VARCHAR(100)--会员卡ID
			
		----单据id
		IF EXISTS(SELECT TOP 1 1 FROM nVipAdjust)
			SELECT @nBillId = ISNULL(MAX(BillNumberId),0)+ 1 FROM nVipAdjust
			
		--经手人ID
		SELECT @Employee = TypeId FROM Employee WHERE FullName = @Employee AND Deleted = 0 AND SonNum = 0

		--会员卡ID
		SELECT @CardNoId = VipCardID FROM nVipCardSign WHERE VipCardCode = @CardNo
		
		INSERT INTO nVipAdjust
		(
			BillNumberId,
			BillDate,
			BillCode,
			ETypeId,
			Checke,
			VipNo,
			UpCost,
			DownCost,
			SumCost,
			Reason,
			IsSend,
			nType
		)
		VALUES
		(
			@nBillId,
			@BillDate,
			@BillCode,
			@Employee,
			@Checke,
			@CardNoId,
			@UpMoney,
			@DownMoney,
			@SumMoney,
			@Reason,
			@isSend,
			@nType
		)
		IF @@ROWCOUNT = 0
			RETURN -1
		ELSE
			BEGIN
				IF @nType=1--消费调整
					BEGIN
						UPDATE nVipCardSign SET TotalMoney = ISNULL(TotalMoney,0) + @SumMoney WHERE VipCardID = @CardNoId
						RETURN @nBillId
					END
				IF @nType=2--积分调整
					BEGIN
						UPDATE nVipCardSign SET TotalCent = ISNULL(TotalCent,0) + @SumMoney WHERE VipCardID = @CardNoId
						RETURN @nBillId
					END
					
				RETURN 0
			END
	END
	
RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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











/*
	作者：谢吉康
	日期：2009-06-09
	描述：返利标准的处理
	SELECT * FROM Advantage_standard WHERE StandardCode = '006'
*/
CREATE PROCEDURE Gp_DealAdvantage
(
	@code		varchar(400),
	@name		varchar(400),
	@etypeid	varchar(200),
	@type		varchar(10),
	@dates		varchar(20),
	@lowqty		varchar(20),
	@highqty	varchar(20),
	@total		varchar(20),
	@explain	varchar(400),
	@mode		varchar(100),
	@stypeid	varchar(max),
	@retValue	varchar(2000) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @lqty	 NUMERIC(24, 10) ,
		@hqty	 NUMERIC(24, 10) 

IF @mode = 'A'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Advantage_standard WHERE StandardCode = @code)
			BEGIN
				SET @retValue = '已经存在编号为【'+@code+'】的返利标准设置！'
				RETURN -1
			END
		
		IF EXISTS(SELECT TOP 1 1 FROM Advantage_standard WHERE StandardName = @name)
			BEGIN
				SET @retValue = '已经存在名称为【'+@name+'】的返利标准设置！'
				RETURN -1
			END

		Insert Into Advantage_standard (StandardCode,StandardName,Etypeid,Type,Dates,LowQty,HighQty,Advantage_Total,explain,stypeid)
		Values(@code,@name,@etypeid,@type,@dates,@lowqty,@highqty,@total,@explain,@stypeid)

		IF @@ROWCOUNT = 0
			BEGIN
				SET @retValue = '数据保存失败！'
				RETURN -2
			END
		ELSE 
			BEGIN
				SET @retValue = '数据保存成功！'
				RETURN 0
			END
	END

IF @mode = 'M'
	BEGIN	
		IF EXISTS(SELECT TOP 1 1 FROM Advantage_standard WHERE StandardName = @name AND StandardCode <> @code)
			BEGIN
				SET @retValue = '已经存在名称为【'+@name+'】的返利标准设置！'
				RETURN -1
			END

		SELECT TOP 1 @lqty=lowqty,@hqty=highqty FROM Advantage_standard WHERE StandardCode = @code AND (lowqty = @lowqty OR highqty = @lowqty)
		IF @@ROWCOUNT <> 0		
			BEGIN
                IF(ISNULL(@type,'1')='1')
				SET @retValue = '输入低限数值【' + @lowqty +'】不允许与已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10)),'qty') as varchar(100)) + ' 和 ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10)),'qty') as varchar(100)) +'】重复！'
                ELSE
                SET @retValue = '输入低限数值【' + @lowqty +'】不允许与已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10)),'qty') as varchar(100)) + ' 和 ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10)),'qty') as varchar(100)) +'】重复！'
				RETURN -3
			END

		SELECT TOP 1 @lqty=lowqty,@hqty=highqty FROM Advantage_standard WHERE StandardCode = @code AND (lowqty = @highqty OR highqty = @highqty)
		IF @@ROWCOUNT <> 0
			BEGIN
                IF(ISNULL(@type,'1')='1')
				SET @retValue = '输入高限数值【' + @highqty +'】不允许与已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10)),'qty') as varchar(100)) + ' 和 ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10)),'qty') as varchar(100)) +'】重复！'
                ELSE
                SET @retValue = '输入高限数值【' + @highqty +'】不允许与已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10)),'qty') as varchar(100)) + ' 和 ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10)),'qty') as varchar(100)) +'】重复！'
                RETURN -4
			END

		SELECT TOP 1 @lqty=lowqty,@hqty=highqty FROM Advantage_standard WHERE StandardCode = @code AND lowqty <= @lowqty AND highqty >= @highqty
		IF @@ROWCOUNT <> 0
			BEGIN	
                IF(ISNULL(@type,'1')='1')
				SET @retValue = '输入低、高限数值范围【' + @lowqty + '-' + @highqty +'】不允许包含在已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) + ' - ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) +'】内！'
				ELSE
                SET @retValue = '输入低、高限数值范围【' + @lowqty + '-' + @highqty +'】不允许包含在已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) + ' - ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) +'】内！'
                RETURN -5
			END

		SELECT TOP 1 @lqty=lowqty,@hqty=highqty FROM Advantage_standard WHERE StandardCode = @code AND lowqty >= @lowqty AND highqty <= @highqty
		IF @@ROWCOUNT <> 0
			BEGIN	
                IF(ISNULL(@type,'1')='1')
				SET @retValue = '输入低、高限数值范围【' + @lowqty + '-' + @highqty +'】不允许包含已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) + ' - ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) +'】！'
				ELSE
                SET @retValue = '输入低、高限数值范围【' + @lowqty + '-' + @highqty +'】不允许包含已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) + ' - ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) +'】！'
                RETURN -6
			END

		SELECT TOP 1 @lqty=lowqty,@hqty=highqty FROM Advantage_standard WHERE StandardCode = @code AND lowqty >= @lowqty AND highqty >= @highqty AND lowqty < @highqty
		IF @@ROWCOUNT <> 0
			BEGIN
                IF(ISNULL(@type,'1')='1')	
				SET @retValue = '输入低、高限数值范围【' + @lowqty + '-' + @highqty +'】不允许与已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) + ' - ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) +'】交叉！'
				ELSE
                SET @retValue = '输入低、高限数值范围【' + @lowqty + '-' + @highqty +'】不允许与已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) + ' - ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) +'】交叉！'
                RETURN -7
			END

		SELECT TOP 1 @lqty=lowqty,@hqty=highqty FROM Advantage_standard WHERE StandardCode = @code AND lowqty <= @lowqty AND highqty <= @highqty AND highqty > @lowqty
		IF @@ROWCOUNT <> 0
			BEGIN
                IF(ISNULL(@type,'1')='1')	
				SET @retValue = '输入低、高限数值范围【' + @lowqty + '-' + @highqty +'】不允许与已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) + ' - ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) +'】交叉！'
                ELSE
                SET @retValue = '输入低、高限数值范围【' + @lowqty + '-' + @highqty +'】不允许与已有的低、高限数值范围【' + CAST(dbo.F_DecimalDisplay(CAST(@lqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) + ' - ' + CAST(dbo.F_DecimalDisplay(CAST(@hqty as  NUMERIC(24, 10) ),'qty') as varchar(100)) +'】交叉！'
				RETURN -8
			END
		
		IF EXISTS(SELECT TOP 1 1 FROM Advantage_standard WHERE StandardCode = @code)
			BEGIN
				UPDATE	Advantage_standard SET ETypeId = @ETypeId WHERE StandardCode = @code
			END		

		INSERT INTO Advantage_standard (StandardCode,StandardName,Etypeid,Type,Dates,LowQty,HighQty,Advantage_Total,explain,stypeid)
		VALUES(@code,@name,@etypeid,@type,@dates,@lowqty,@highqty,@total,@explain,@stypeid)

		IF @@ROWCOUNT = 0
			BEGIN
				RETURN -9
			END

		UPDATE Advantage_standard SET StandardName = @name,Dates = @dates,explain = @explain WHERE StandardCode = @code

		IF @@ROWCOUNT = 0
			BEGIN
				SET @retValue = '数据保存失败！'
				RETURN -10
			END
		ELSE
			BEGIN
				SET @retValue = '数据保存成功！'
				RETURN 0
			END

	END

IF @mode = 'D'
	BEGIN
		IF EXISTS(SELECT TOP 1 * FROM Advantage WHERE StandardCode=@code)
			BEGIN
				SET @retValue = '标准已经使用，不能删除，请确认！'
				RETURN -11
			END

		Delete From Advantage_standard Where StandardCode=@code and lowqty = @lowqty AND highqty = @highqty

		IF @@ROWCOUNT = 0
			BEGIN
				SET @retValue = '删除数据失败！'
				RETURN -12
			END
		ELSE
			BEGIN
				SET @retValue = '删除数据成功！'
				RETURN 0
			END
	END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-04-21
	描述：删除返修单据
*/
CREATE PROCEDURE Gp_DealBackOutBill
(
	@nBillIds	VARCHAR(MAX)	--单据列表
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN DEL

DELETE FROM Billindex_CarRepair WHERE BillNumberId IN (SELECT * FROM DBO.f_split(@nBillIds,','))

IF @@ROWCOUNT <> 0
	BEGIN
		DELETE FROM Billindex WHERE BillNumberId IN (SELECT * FROM DBO.f_split(@nBillIds,','))
		DELETE FROM dbo.PrintRecord WHERE BillNumberId IN (SELECT * FROM DBO.f_split(@nBillIds,',')) AND BillType = '192'
	END

COMMIT TRAN DEL

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GO
/*
	作者：谢吉康
	日期：2019-03-08
	描述：添加操作员在线数据
*/

CREATE  PROCEDURE [dbo].Gp_DealCheckLoginOnlineUser
(
	@etypeid			VARCHAR(50),		--操作员ID
	@username			VARCHAR(500),		--操作员名称
	@ipAddress			VARCHAR(500),		--IP地址
	@pollingtime		INT 				--轮询时间
)
AS
SET NOCOUNT ON

--先判断条件，不满足则不进入
IF NOT (EXISTS(SELECT TOP 1 1 FROM sysdatadb.dbo.RWXsysadmin WHERE islimlogin = 1 AND ISNULL(dognumber,'')<>'')
			OR EXISTS(SELECT TOP 1 1 FROM sysdatadb.dbo.VirtualDirectoryWithAccount WHERE islimlogin = 1 AND ISNULL(dognumber,'')<>'')
	   )	
BEGIN	
	RETURN 0
END	

DECLARE @currentTime	VARCHAR(100),
		@dbName			VARCHAR(500),
		@dogNo			VARCHAR(100)

SET @currentTime = CONVERT(VARCHAR(30),GETDATE(),120)
SET @dbName = db_name()

--带账套清除主表异常数据
DELETE FROM [SysdataDb].dbo.Fx_OnlineUser WHERE dbName = @DbName AND [ETypeID_UserTypeID] NOT IN (SELECT ETypeId FROM loginUser)
DELETE FROM dbo.OA_OnlineUser WHERE [ETypeID_UserTypeID] NOT IN (SELECT ETypeId FROM loginUser)

SET @dogNo = ''
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubName = 'ZCFlag' AND SubValue = '1')
BEGIN
	SELECT @dogNo = SubValue FROM dbo.sysdata1 WHERE SubName = 'DogNo'
END

--写入当前账套的数据库表
IF NOT EXISTS(SELECT TOP 1 1 FROM OA_OnlineUser WHERE ETypeID_UserTypeID = @etypeid)
BEGIN
	INSERT INTO OA_OnlineUser 
	(
		[ETypeID_UserTypeID],
		[LatestConnectTime],
		[LoginTime],
		[UserName],
		[IP],
		[Status],
		[PollineTime]
	)VALUES(
		@etypeID, 
		@currentTime, 
		@currentTime, 
		@userName, 
		@ipAddress, 
		'正常',
		@pollingtime
	)
	
	--删除SysdataDb中记录的数据
	DELETE FROM [SysdataDb].dbo.Fx_OnlineUser WHERE ETypeID_UserTypeID = @etypeid AND dbName = @dbName
END
ELSE
BEGIN
	UPDATE	OA_OnlineUser 
	SET		[LatestConnectTime] = @currentTime, 
			[IP] = @ipAddress, 
			[Status] = '正常',
			[pollineTime] = @pollingtime
	WHERE	[ETypeID_UserTypeID] = @etypeID
END

--写入SysdataDb数据库表
IF NOT EXISTS(SELECT TOP 1 1 FROM [SysdataDb].dbo.Fx_OnlineUser WHERE ETypeID_UserTypeID = @etypeid AND dbName = @dbName)
BEGIN
	INSERT INTO [SysdataDb].dbo.Fx_OnlineUser 
	(
		[ETypeID_UserTypeID],
		[DbName],
		[DogNo],
		[LatestConnectTime],
		[LoginTime],
		[UserName],
		[IP],
		[Status],
		[pollineTime]
	)VALUES(
		@etypeID, 
		@DbName,
		@DogNo,
		@currentTime, 
		@currentTime, 
		@userName, 
		@ipAddress, 
		'正常',
		@pollingtime
	)
END
ELSE
BEGIN
	UPDATE	[SysdataDb].dbo.Fx_OnlineUser 
	SET		[LatestConnectTime] = @currentTime, 
			[IP] = @ipAddress, 
			[Status] = '正常',
			[pollineTime] = @pollingtime
	WHERE	[ETypeID_UserTypeID] = @etypeID
			AND [DbName] = @DbName
END

--清理操作员在线数据
EXEC Gp_ClearLoginOnlineUser @etypeid,@username,@ipAddress,@pollingtime,@currentTime

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：谢吉康
	日期：2017-11-06
	描述：优惠券名称保存
*/
CREATE PROCEDURE Gp_DealCouponInfo
(
	@operatorid				VARCHAR(50),			--操作员ID
	@ntype					VARCHAR(20),			--操作类型   new.新增  copynew.复制新增 modify.修改 del.删除 zf.作废 fzf.反作废
	@couponid				VARCHAR(MAX),			--优惠券ID
	@usercode				VARCHAR(200)='',		--券名称编码
	@fullname				VARCHAR(200)='',		--券名称
	@coupontype				VARCHAR(10)='1',		--券类型  1.代金券 2.折扣券 3.兑换券
	@mz						NUMERIC(24,10)=0,		--面值
	@invalidtype			VARCHAR(10)='1',		--失效方式  1.不失效 2.固定期限 3.固定时间
	@mlhje					NUMERIC(24,10)=0,		--抹零后金额
	@sxsj					VARCHAR(30)='',			--失效时间
	@invalidstartdatetype	INT = 1,				--失效开始类型 1.入库日期 2.出库日期 3.自定义
	@sxksdate				VARCHAR(30)='',			--失效开始
	@sxqx					VARCHAR(10)='1',		--失效期限
	@sxqxtype				VARCHAR(10)='0',		--失效期限  年 月 日
	@cyzx					VARCHAR(10)='0',		--参与促销
	@hyjf					VARCHAR(10)='0',		--参与积分
	@comment				VARCHAR(255)='',		--备注
	@stypeids				VARCHAR(50)='',		--适用分支机构标识
	@ptypeids				VARCHAR(50)='',		--适用商品标识
	@IsPosAll				INT=1,				--适用Pos终端 1:所有 0部分
	@discount				NUMERIC(24,10)=0,		--折扣		
	@moneytype				INT = 1,				--参与价格的方式  1.抹零后金额  2.价税合计
	@isexchange				INT=0,					--兑换商品标识
	@stypetable				Type_CouponStypeInfo READONLY,
	@ptypetable				Type_CouponPtypeInfo READONLY,
	@PosTable				Type_CouponPosInfo READONLY
)
AS
SET NOCOUNT ON

DECLARE @insertCouponId	INT,
		@Cid			INT
		
--获取本位币		
SELECT @Cid = CId FROM dbo.Ac_Currency WHERE Sysrow = 1		

IF @ntype='new' OR @ntype='copynew'
BEGIN
	--判断要修改的基本信息是否存在
	IF @ntype='copynew' OR @ntype = 'new'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.coupon_TypeInfo WHERE (usercode = @usercode OR fullname = @fullname))
			OR EXISTS(SELECT TOP 1 1 FROM dbo.coupon_TypeInfo WHERE (usercode = @fullname OR fullname = @usercode))
		BEGIN
			RAISERROR('已存在相关的优惠券信息！',16,1)
			RETURN -1
		END
	END
	
	--写入信息
	INSERT INTO coupon_typeinfo
	(
		UserCode, 
		FullName, 
		CouponType, 
		Discount, 
		CouponValue, 
		Cid, 
		Maker, 
		CreateDate, 
		InvalidType, 
		InvalidDate, 
		InvalidStartDateType,
		InvalidStartDate, 
		InvalidTermType, 
		InvalidTerm, 
		MoneyType,
		MinMoney, 
		IsPromotion, 
		IsVipPoint, 
		Comment, 
		IsDelete,
		IsPosAll
	)VALUES(
		@usercode,
		@fullname,
		@coupontype,
		CASE @coupontype WHEN 1 THEN 0 WHEN 2 THEN @discount WHEN 3 THEN 0 END,--Discount,
		@mz,--CouponValue,
		@Cid,--Cid,
		@operatorid,
		CONVERT(VARCHAR(30),GETDATE(),120),--CreateDate,
		@invalidtype,--InvalidType,
		CASE WHEN @invalidtype IN (1,2) THEN NULL ELSE @sxsj END,--InvalidDate,
		CASE WHEN @invalidtype = 2 THEN @InvalidStartDateType ELSE 1 END,
		CASE WHEN (@invalidtype = 2 AND @invalidstartdatetype = 3) THEN @sxksdate ELSE NULL END ,--InvalidStartDate,
		CASE WHEN @invalidtype = 2 THEN @sxqxtype ELSE 0 END,--InvalidTermType,
		CASE WHEN @invalidtype = 2 THEN @sxqx ELSE NULL END,--InvalidTerm,
		@moneytype,
		@mlhje,--MinMoney,
		CASE WHEN @coupontype = 1 THEN 1 ELSE @cyzx END,--IsPromotion,
		CASE WHEN @coupontype = 1 THEN 1 ELSE @hyjf END,--IsVipPoint,
		@Comment,
		0,
		@IsPosAll
	)
	
	SET @insertCouponId = SCOPE_IDENTITY()
	
	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('数据保存失败',16,1)
		RETURN -1		
	END
	
	--写入默认分支机构数据,如果用表值参数的话，在表里写00000就可以了
	IF @stypeids = '0'
	BEGIN
		INSERT INTO coupon_ApplyStype(CouponId,STypeId)VALUES(@insertCouponId,'00000')
	END
	ELSE
	BEGIN--写入表值参数和@insertCouponId
		EXEC Gp_UpdateCouponStype @stypetable,@insertCouponId
	END
	--写入适用商品数据
	IF @ptypeids = '0'
	BEGIN
		INSERT INTO coupon_ApplyPtype(CouponId,PTypeId,Qty,Price,Total,IsExchangePtype)VALUES(@insertCouponId,'00000',0,0,0,@isexchange)
	END
	ELSE
	BEGIN--写入表值参数和@insertCouponId
		EXEC Gp_UpdateCouponPtype @ptypetable,@insertCouponId,@isexchange
	END
	
	--写入POS终端数据
	DELETE FROM Coupon_ApplyPos  WHERE CouponId=@insertCouponId
	IF @IsPosAll= '1'
	BEGIN
		INSERT INTO Coupon_ApplyPos(CouponId,PosId)VALUES(@insertCouponId,0)
	END
	ELSE
	BEGIN
		INSERT INTO Coupon_ApplyPos(CouponId,PosId)
		SELECT @insertCouponId CouponId,PosId FROM @PosTable
	END
END
ELSE IF @ntype='modify'
BEGIN
	--判断要修改的基本信息是否存在
	IF EXISTS(SELECT TOP 1 1 FROM dbo.coupon_TypeInfo WHERE (usercode = @usercode OR fullname = @fullname) AND Couponid <> @couponid)
		OR EXISTS(SELECT TOP 1 1 FROM dbo.coupon_TypeInfo WHERE (usercode = @fullname OR fullname = @usercode) AND Couponid <> @couponid)
	BEGIN
		RAISERROR('已存在相关的优惠券信息！',16,1)
		RETURN -1
	END
	
	--修改信息
	UPDATE	coupon_TypeInfo
	SET		usercode	= @usercode,
			fullname	= @fullname,
			CouponType	= @coupontype,
			Discount	= CASE @coupontype WHEN 1 THEN 0 WHEN 2 THEN @discount WHEN 3 THEN 0 END,
			CouponValue	= @mz,
			InvalidType = @invalidtype,
			MinMoney    = @mlhje,
			IsPromotion = CASE WHEN @coupontype = 1 THEN 1 ELSE @cyzx END, 
			IsVipPoint  = CASE WHEN @coupontype = 1 THEN 1 ELSE @hyjf END, 
			Comment		= @comment,			
			InvalidStartDateType = CASE WHEN @invalidtype = 2 THEN @invalidstartdatetype ELSE 1 END,
			InvalidStartDate = CASE WHEN (@invalidtype = 2 AND @invalidstartdatetype = 3) THEN @sxksdate ELSE NULL END,
			InvalidDate = CASE WHEN @invalidtype IN (1,2) THEN NULL ELSE @sxsj END,
			InvalidTermType = CASE WHEN @invalidtype = 2 THEN @sxqxtype ELSE 0 END,
			InvalidTerm = CASE WHEN @invalidtype = 2 THEN @sxqx ELSE NULL END,
			MoneyType = @moneytype,
			IsPosAll=@IsPosAll
	WHERE	CouponId = @couponid
	
	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('数据保存失败',16,1)
		RETURN -1		
	END
	
	--写入默认分支机构数据,如果用表值参数的话，在表里写00000就可以了
	IF @stypeids = '0'
	BEGIN
		--删除原有机构，添加默认机构
	    DELETE FROM coupon_ApplyStype WHERE CouponId = @couponid
		INSERT INTO coupon_ApplyStype(CouponId,STypeId) VALUES (@couponid,'00000')
	END
	ELSE
	BEGIN--写入表值参数和@insertCouponId
		EXEC Gp_UpdateCouponStype @stypetable,@couponid
	END
	--写入适用商品数据
	IF @ptypeids = '0'
	BEGIN
		DELETE FROM coupon_ApplyPtype WHERE CouponId = @couponid
		INSERT INTO coupon_ApplyPtype(CouponId,PTypeId,Qty,Price,Total,IsExchangePtype)VALUES(@couponid,'00000',0,0,0,@isexchange)
	END
	ELSE
	BEGIN--写入表值参数和@insertCouponId
		EXEC Gp_UpdateCouponPtype @ptypetable,@couponid,@isexchange
	END
	
	--写入POS终端数据
	--删除原信息
	DELETE FROM Coupon_ApplyPos  WHERE CouponId = @couponid
	IF @IsPosAll= '1'
	BEGIN
		INSERT INTO Coupon_ApplyPos(CouponId,PosId)VALUES(@couponid,0)
	END
	ELSE
	BEGIN
		--重新插入信息
		INSERT INTO Coupon_ApplyPos(CouponId,PosId)
		SELECT @couponid CouponId,PosId FROM @PosTable
	END
	
END
ELSE IF @ntype='del'
BEGIN
	DELETE FROM coupon_typeinfo WHERE couponid IN (SELECT A FROM DBO.f_split(@couponid,',') WHERE ISNULL(a,'')<>'')
	DELETE FROM Coupon_ApplyStype WHERE couponid IN (SELECT A FROM DBO.f_split(@couponid,',') WHERE ISNULL(a,'')<>'')
	DELETE FROM Coupon_ApplyPtype WHERE couponid IN (SELECT A FROM DBO.f_split(@couponid,',') WHERE ISNULL(a,'')<>'')
	DELETE FROM Coupon_ApplyPos WHERE couponid IN (SELECT A FROM DBO.f_split(@couponid,',') WHERE ISNULL(a,'')<>'')
END
ELSE IF @ntype='zf'
BEGIN
	UPDATE Coupon_typeInfo SET IsDelete = 1 WHERE couponid IN (SELECT A FROM DBO.f_split(@couponid,',') WHERE ISNULL(a,'')<>'')
END
ELSE IF @ntype='fzf'
BEGIN
	UPDATE Coupon_typeInfo SET IsDelete = 0 WHERE couponid IN (SELECT A FROM DBO.f_split(@couponid,',') WHERE ISNULL(a,'')<>'')
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_DealDbf]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_DealDbf]
GO
/****** Object:  StoredProcedure [dbo].[Gp_DealDbf]    Script Date: 11/01/2012 15:13:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
	功能说明：	成本核算，三种算法；修改期初；修改BType对应往来余额
	作    者：	卢  春
	最后修改：	2004-06-09
*/
CREATE     PROCEDURE [dbo].[Gp_DealDbf] 
(
	@nVchType			numeric(4, 0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szSTypeID			varchar(50),			--分支机构
	@szPeriod			varchar(2),				-- 8. 期号 (暂时不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
	@dntotal			 NUMERIC(24, 10) ,			-- 23. 原币成本金额
	@cid				INT,					-- 24.币别
	@szJobNo			varchar(20),			-- 11. (暂时不用)
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10) ,			-- 16. 批次成本单价
	@HandZeroCost		int,					-- 17. 是否为手工输入0成本标志
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 18. 成本单价 (输出)
	@ModifyAuditBill	int=0,					-- 0表示正常单据，1表示修改过账后单据
	@MakeDate			datetime = null,		-- 19. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0,		-- 20. (暂时不用)
	@IfRedWord			TINYINT
)
--@encode$--
AS
SET NOCOUNT ON


-- 声明会计科目相关变量
DECLARE	@GOODS_ID				varchar(50),
		@CASH_ID				varchar(50),
		@CASH_BANK_ID			varchar(50),
		@AR_ID					varchar(50),
		@AP_ID					varchar(50),
		@YF_ID					varchar(50),
		@YS_ID					 varchar(50),
		@GOODS_LOSS_ID			varchar(50),
		@GOODS_GET_ID			varchar(50),
		@ALLOT_PRICE_ID			varchar(50),
		@PRICE_INCOME_ID		varchar(50),
		@BORROW_BUY_PRICE_ID	varchar(50),
		@GOODS_GIVE_ID			varchar(50),
		@GOODS_PRODUCE_ID		varchar(50),
		@SALE_COST_ID			varchar(50),
		@SALE_INCOME_ID			varchar(50),
		@LEND_GOODS_ID			varchar(50),
		@BORROW_GOODS_ID		varchar(50),
		@BALANCE_ID				varchar(50),
		@DEPRECIATION_ID		varchar(50),
		@APPORTION_EXPENSE_ID	varchar(50),
		@INIT_MONEY_ID			varchar(50),
		@ALL_INCOME_ID			varchar(50),
		@ALL_EXPENSE_ID			varchar(50),
		@PROFIT_ID				varchar(50),
		@ASSETS_ID				varchar(50),
		@DEBT_ID				varchar(50),
		@POWER_ID				varchar(50),
		@ADDEBT_INCOME_ID		varchar(50),
		@ADDEBT_LOSE_ID			varchar(50),
		@GOODS_GIVE_RECNO		varchar(50),
		@GOODS_GIVEME_RECNO		varchar(50),
		@GOODS_REPAIR_ID		varchar(50),
		@SALE_JKFL_EXPENSE_ID	varchar(50),
		@PreferenceID			varchar(50),
		@REPAIR_INCOME_ID		varchar(50),
		@REPAIR_OUTCOME_ID		varchar(50)


SELECT @SALE_JKFL_EXPENSE_ID	=nid FROM dbo.Ac_Items WHERE UserCode = '0404'			-- 销售折扣返利支出
SELECT	@GOODS_REPAIR_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0423'		-- 商品维修收入
SELECT @GOODS_GIVE_RECNO		=nid FROM dbo.Ac_Items WHERE UserCode =  '0422'		-- 商品赠送支出
SELECT @GOODS_GIVEME_RECNO		=nid FROM dbo.Ac_Items WHERE UserCode =  '0322'		-- 商品获赠收入
SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』
SELECT @CASH_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1001'			-- 现    金
SELECT @AR_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '987'			-- 『应收款合计』
SELECT @AP_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2121'			-- 『应付帐款合计』
SELECT @GOODS_LOSS_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0421'		-- 商品报损支出
SELECT @GOODS_GET_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0321'		-- 商品报溢收入
SELECT @ALLOT_PRICE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0325'		-- 变价调拨差价
SELECT @PRICE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0323'		-- 成本调价收入
SELECT @GOODS_PRODUCE_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0326'		-- 商品拆装差价
SELECT @SALE_COST_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5401'			-- 『销售成本』
SELECT @SALE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5101'			-- 『销售收入』
SELECT @BALANCE_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '0324'		-- 采购退货差价
SELECT @DEPRECIATION_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0432'		-- 固定资产折旧
SELECT @APPORTION_EXPENSE_ID	=nid FROM dbo.Ac_Items WHERE UserCode =  '1301'			-- 『待摊费用』
--SELECT @ALL_INCOME_ID			= '00003'				-- 【收入类】
--SELECT @ALL_EXPENSE_ID			= '00004'				-- 【支出类】
--SELECT @ASSETS_ID				= '00001'				-- 【资产合计】
--SELECT @DEBT_ID					= '00002'				-- 【负债合计】
SELECT @ADDEBT_INCOME_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '03333'		-- 调帐收入
SELECT @ADDEBT_LOSE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0431'		-- 调帐亏损
SELECT @PreferenceID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0456'		-- 『优惠金额』
SELECT @REPAIR_INCOME_ID 		=nid FROM dbo.Ac_Items WHERE UserCode =  '0328' 	-- 商品维修收入
SELECT @REPAIR_OUTCOME_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0423' 	--商品维修支出
SELECT @YF_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1151'			--预付账款
SELECT @YS_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2131'			--预收账款
------------------

-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

DECLARE	@szSql					varchar(500),
		@DBName					varchar(20),
		@szJobNumber			varchar(20),
		@nAllowNegativeStock	int,

		@dTotalTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品金额
		@dQtyTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品数量
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
		@dPricetemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@nPeriod				int,
		@OutFactoryDate			datetime,
		@datValidDate			datetime,
		@nGoodsOrder			int

SET @dCostPrice		= 0

SET @dTotalTemp		= 0
SET @dQtyTemp		= 0
SET @dCostTotalTemp	= 0

SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0


-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', @szSTypeID,@nAllowNegativeStock output

DECLARE
	@intRet INT

-- begin tran Modifydbf
-- save tran Modifydbf
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------
*/
	-- 成本核算，传入的 ATypeID 参数必定为 “库存商品总值”
	IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
	BEGIN
		-- 若商品数量为 0 且 商品成本金额不等于 0，则回滚报错
		IF @dQty = 0 AND (@dTotal <> 0 OR @dntotal <>0)
		BEGIN
			--RAISERROR('数据出错！',16,1)
			RETURN -7	-- 异常
		END

		

		IF @szPeriod = ''
		BEGIN
			EXEC @intRet=Gp_DealGoods 
			@nVchType,
			@szCostingMethod,
			@szATypeID,
			@szPTypeID,
			@szBTypeID,
			@szETypeID,
			@szKTypeID,
			@szSTypeID,
			@szPeriod,
			@dQty,
			@dTotal,
			@szJobNo,
			@nGoodsNo,
			@GoodsNumber,
			@ProduceDate,
			@ValidDate,
			@GoodsCostPrice,
			@HandZeroCost,
			@dCostPrice output,
			@ModifyAuditBill,
			@MakeDate,
			@dPrice,
			@IfRedWord

			RETURN @intRet
		END
	END
	/* 修改往来单位对应的往来余额 */
	ELSE IF @szATypeID = @AR_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,ARTotal,nARTotal,cid)
				SELECT @szBTypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		ArTotal = ISNULL(ARTotal,0) + @dtotal,
						nARTotal = ISNULL(nARTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND CID = @cid
			END
			
			
			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END
	ELSE IF @szATypeID = @YF_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,YFTotal,nYFTotal,CID)
				SELECT @szBTypeID,@szSTypeID,@dtotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		YFTotal = ISNULL(YFTotal,0) + @dtotal,
						nYFTotal = ISNULL(nYFTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND cid =@cid
			END

			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END
	ELSE IF @szATypeID = @AP_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,APTotal,nAPTotal,cid)
				SELECT @szBTypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		APTotal = ISNULL(APTotal,0) + @dtotal,
						nAPTotal = ISNULL(nAPTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND CID = @cid
			END
			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END
	ELSE IF @szATypeID = @YS_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,YSTotal,nYSTotal,cid)
				SELECT @szBTypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		YSTotal =ISNULL(YSTotal,0) + @dtotal,
						nYSTotal = ISNULL(nYSTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND CID = @cid
			END

			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END 
	ELSE 
		BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT ATypeID
				FROM AType_Total
				WHERE ATypeID=@szATypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT AType_Total(ATypeID,STypeID,Total,Ntotal,CID)
				SELECT @szATypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	AType_Total 
				SET		Total = ISNULL(Total,0)+@dTotal,
						Ntotal = ISNULL(Ntotal,0) + @dntotal
				WHERE	ATypeID = @szATypeID 
						AND STypeID=@szSTypeID
						AND CID=@cid
			END
			
			IF @@ROWCOUNT = 0 GOTO ERROR4 ELSE GOTO SUCCESS
		END 
	END

	CLEANUP:
		-- 返回成功值并退出
		-- 释放游标
		DEALLOCATE ModifyDbf_Cursor
		-- commit tran --ModifyDbf

		RETURN 0

	ERROR1:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -1

	ERROR2:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -2

	ERROR3:
		-- 当数量为 0 时，回滚
		-- 一般非物流单据过账时会出现这种情况
		-- rollback tran --ModifyDbf
		RETURN 0


	ERROR4:
		-- rollback tran --ModifyDbf
		DEALLOCATE ModifyDbf_Cursor
		RETURN -4

	ERRORINPUTCOSTPRICE:
		-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
		DEALLOCATE ModifyDbf_Cursor
		RETURN -5

	ERRORINIMODIFYDENY:
		-- 系统已正式开账，不能修改期初
		RETURN -6

	SUCCESS:
		-- 执行成功
		-- commit tran --ModifyDbf
		RETURN 0

GO




/*******
*******				实物库存单据红冲处理库存
*******		
******/

IF EXISTS(SELECT TOP 1 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_DealFactQty_Reverse',N'P'))
BEGIN
	DROP PROC GP_DealFactQty_Reverse
END
GO

CREATE PROC GP_DealFactQty_Reverse
(
	@BillNumberID INT,
	@BillType     INT,
	@szPID        VARCHAR(1000) OUT
)
AS
BEGIN
	DECLARE		@FromBillNumberID  INT,					/*来源单据编号*/
				@FromBillID		   INT,					/*来源单明细ID*/
				@FromBillType      INT,					/*来源单单据类型*/
				@FromBillQty       NUMERIC(24,10),		/*来源单据数量*/
				@FromBillName	   NVARCHAR(50),		/*来源单据名称*/
				@RowIndex          INT,					
				@RowCount          INT,					/*单明细行数*/
				@Qty			   NUMERIC(24,10),		/*数量*/
				@NQty			   NUMERIC(24,10),		/*辅助数量*/
				@PTypeID		   VARCHAR(100),		/*商品ID*/
				@FullName		   VARCHAR(100),		/*商品名称*/
				@ItemID            INT,
				@IsCombined        INT,
				@ProduceDate	   VARCHAR(50),
				@ValidDate         VARCHAR(50),
				@GoodsNumber	   VARCHAR(100),
				@InKTypeID		   VARCHAR(100),
				@InCargoID		   INT,
				@OutKTypeID		   VARCHAR(100),
				@OutCargoID		   INT,
				@nRet			   INT
	
	DECLARE	    @Tmp			   TABLE
	(
		PTypeID			 VARCHAR(100),
		FullName         VARCHAR(100),
		Qty				 NUMERIC(24,10),
		NQty		     NUMERIC(24,10),
		ItemID			 INT,
		IsCombined		 INT,
		ProduceDate      VARCHAR(50),
		ValidDate        VARCHAR(50),
		GoodsNumber		 VARCHAR(100),
		InKTypeID		 VARCHAR(100),
		InCargoID		 INT,
		OutKTypeID		 VARCHAR(100),
		OutCargoID		 INT,
		FromBillNumberID INT,
		FromBillID       INT,
		FromBillType     INT,
		RowIndex         INT
	)
	
	IF @BillType IN(418,419)
	BEGIN
		INSERT INTO @Tmp
					( 
					  Qty ,
					  NQty,
					  FromBillNumberID ,
					  FromBillID ,
					  FromBillType,
					  RowIndex,
					  PTypeID,
					  FullName,
					  ItemID,
					  IsCombined,
					  ProduceDate,
					  ValidDate,
					  GoodsNumber,
					  InKTypeID,
					  InCargoID,
					  OutKTypeID,
					  OutCargoID
					)
			SELECT A.Qty,
				   A.NQty,
				   A.FromBillNumberID,
				   A.FromBillID,
				   A.FromBillType,
				   ROW_NUMBER()OVER(ORDER BY A.ID ASC) AS RowIndex,
				   A.PTypeID,
				   B.FullName,
				   A.ItemID,
				   A.IsCombined,
				   A.ProduceDate,
				   A.ValidDate,
				   A.GoodsNumber,
				   CASE WHEN C.BillType=418 THEN A.ktypeid ELSE '' END,
				   CASE WHEN C.BillType=418 THEN A.CargoID ELSE 0 END,
				   CASE WHEN C.BillType=419 THEN A.ktypeid ELSE '' END,
				   CASE WHEN C.BillType=419 THEN A.CargoID ELSE 0 END
			FROM dbo.FactDepotInOut A 
			INNER JOIN dbo.ptype B ON A.ptypeid=B.typeId
			INNER JOIN dbo.FactIndex C ON A.BillNumberID=C.BillNumberID
			WHERE C.BillNumberID=@BillNumberID
	END
	ELSE	
	BEGIN
		INSERT INTO @Tmp
		        ( 
				  Qty ,
				  NQty,
		          FromBillNumberID ,
		          FromBillID ,
		          FromBillType,
		          RowIndex,
		          PTypeID,
		          FullName,
		          ItemID,
				  IsCombined,
				  ProduceDate,
				  ValidDate,
				  GoodsNumber,
				  InKTypeID,
				  InCargoID,
				  OutKTypeID,
				  OutCargoID
		        )
			SELECT A.Qty,
				   A.NQty,
				   0,
				   0,
				   0,
				   ROW_NUMBER()OVER(ORDER BY A.ID ASC) AS RowIndex,
				   A.PTypeID,
				   B.FullName,
				   A.ItemID,
				   A.IsCombined,
				   A.ProduceDate,
				   A.ValidDate,
				   A.GoodsNumber,
				   A.KTypeId2,
				   A.InCargoID,
				   A.KTypeId,
				   A.OutCargoID
			FROM dbo.FactDepotAllot A 
			INNER JOIN dbo.ptype B ON A.ptypeid=B.typeId
			WHERE BillNumberID=@BillNumberID
	END	
	
	/****仓库入库单 仓库出库单 引用 数量 验证 begin****/
	SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
	WHILE(@RowIndex<=@RowCount)
	BEGIN
		SELECT @FromBillNumberID=FromBillNumberID,
			   @FromBillID=FromBillID,
			   @FromBillType=FromBillType,
			   @Qty=Qty,
			   @NQty=NQty,
			   @PTypeID=PTypeID,
			   @FullName=FullName,
			   @ItemID=ItemID,
			   @IsCombined=IsCombined,
			   @ProduceDate=ProduceDate,
			   @ValidDate=ValidDate,
			   @GoodsNumber=GoodsNumber,
			   @InKTypeID=InKTypeID,
			   @InCargoID=InCargoID,
			   @OutKTypeID=OutKTypeID,
			   @OutCargoID=OutCargoID
		FROM @Tmp WHERE RowIndex=@RowIndex
		--处理库存数量
		SET @Qty=-1*@Qty
		SET @NQty=1*@NQty
		--处理库存数量
		EXEC @nRet= GP_Auditing_Fact_DealQty @BillNumberID=@BillNumberID,
									  @BillType=@BillType,
									  @Qty=@Qty,
									  @NQty=@NQty,
									  @ItemID=@ItemID,
									  @IsCombined=@IsCombined,
									  @GoodsNumber=@GoodsNumber,
									  @ProduceDate=@ProduceDate,
									  @ValidDate=@ValidDate,
									  @InKTypeID=@InKTypeID,
									  @InCargoID=@InCargoID,
									  @OutKTypeID=@OutKTypeID,
									  @OutCargoID=@OutCargoID,
									  @PTypeID=@PTypeID,
									  @FullName=@FullName,
									  @RowIndex=@RowIndex,
									  @szPID=@szPID OUT
		IF @nRet<>0 
		BEGIN
			RETURN @nRet
		END
		SET @RowIndex=@RowIndex+1
	END
END
Go



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	功能说明：	成本核算，三种算法；修改期初；修改BType对应往来余额
	作    者：	卢  春
	最后修改：	2004-06-09
*/
CREATE     PROCEDURE Gp_DealGoods 
(
	@nVchType			numeric(4, 0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szSTypeID			varchar(50),			--分支机构
	@szPeriod			varchar(2),				-- 8. 期号 (暂时不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
												--     最新改为两位精度
	@szJobNo			varchar(20),			-- 11. (暂时不用)
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10) ,			-- 16. 批次成本单价
	@HandZeroCost		int,					-- 17. 是否为手工输入0成本标志
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 18. 成本单价 (输出)
	@ModifyAuditBill	int=0,					-- 0表示正常单据，1表示修改过账后单据
	@MakeDate			datetime = null,		-- 19. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0,		-- 20. (暂时不用)
	@IfRedWord			TINYINT					--红冲标志
	--@ValidDate		varchar(50),			-- 21. 有效期至(手工指定)
	--@GoodsBTypeID		varchar(50)				-- 22. 供货商ID值(手工指定)
	
)
--@encode$--
AS
SET NOCOUNT ON



-- 声明会计科目相关变量
DECLARE	@GOODS_ID				varchar(50)


SET @GOODS_ID				= '0000100001'			-- 『库存商品总值合计』

-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

DECLARE	@szSql					varchar(500),
		@DBName					varchar(20),
		@szJobNumber			varchar(20),
		@nAllowNegativeStock	int,

		@dTotalTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品金额
		@dQtyTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品数量
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
		@dPricetemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@nPeriod				int,
		@OutFactoryDate			datetime,
		@datValidDate			datetime,
		@nGoodsOrder			int,
		@intRet					INT

SET @dCostPrice		= 0

SET @dTotalTemp		= 0
SET @dQtyTemp		= 0
SET @dCostTotalTemp	= 0

SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0

SELECT
	@intRet=0

-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', @szSTypeID,@nAllowNegativeStock output

-- begin tran Modifydbf
-- save tran Modifydbf
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------
*/
	IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
	BEGIN
		
	
		-- 若商品数量为 0 且 商品成本金额不等于 0，则回滚报错
		IF @dQty = 0 AND @dTotal <> 0
		BEGIN
			--RAISERROR('数据出错！',16,1)
			RETURN -7	-- 异常
		END

		IF @szPeriod = ''
		BEGIN
			/*****************************************************************
				移动加权平均成本核算法
			******************************************************************/
			IF @szCostingMethod = @AVERAGE
			BEGIN
				
				EXEC	@intRet=Gp_DealGoodsAVE 
				@nVchType,
				@szCostingMethod,
				@szATypeID,
				@szPTypeID,
				@szBTypeID,
				@szETypeID,
				@szKTypeID,
				@szSTypeID,
				@szPeriod,
				@dQty,
				@dTotal,
				@szJobNo,
				@nGoodsNo,
				@GoodsNumber,
				@ProduceDate,
				@ValidDate,
				@GoodsCostPrice	OUT,
				@HandZeroCost,
				@dCostPrice,
				@ModifyAuditBill,
				@MakeDate,
				@dPrice,
				@IfRedWord
				
				
				RETURN @intRet
				
			END
			/*****************************************************************
				先进先出成本算法
			******************************************************************/
			ELSE IF @szCostingMethod = @FIFO
			BEGIN
				EXEC	@intRet=Gp_DealGoodsFIFO
				@nVchType,
				@szCostingMethod,
				@szATypeID,
				@szPTypeID,
				@szBTypeID,
				@szETypeID,
				@szKTypeID,
				@szSTypeID,
				@szPeriod,
				@dQty,
				@dTotal,
				@szJobNo,
				@nGoodsNo,
				@GoodsNumber,
				@ProduceDate,
				@ValidDate,
				@GoodsCostPrice	OUT,
				@HandZeroCost,
				@dCostPrice,
				@ModifyAuditBill,
				@MakeDate,
				@dPrice,
				@IfRedWord
			
				RETURN @intRet	
			END
			/*****************************************************************
				后进先出成本算法
			******************************************************************/
			ELSE IF @szCostingMethod = @LIFO
			BEGIN
				EXEC	@intRet=Gp_DealGoodsLIFO 
				@nVchType,
				@szCostingMethod,
				@szATypeID,
				@szPTypeID,
				@szBTypeID,
				@szETypeID,
				@szKTypeID,
				@szSTypeID,
				@szPeriod,
				@dQty,
				@dTotal,
				@szJobNo,
				@nGoodsNo,
				@GoodsNumber,
				@ProduceDate,
				@ValidDate,
				@GoodsCostPrice	OUT,
				@HandZeroCost,
				@dCostPrice,
				@ModifyAuditBill,
				@MakeDate,
				@dPrice,
				@IfRedWord
				
				RETURN @intRet
			END
			/*****************************************************************
				手工指定成本算法
			******************************************************************/
			ELSE IF @szCostingMethod = @HAND
			BEGIN
				EXEC	@intRet=Gp_DealGoodsHand 
				@nVchType,
				@szCostingMethod,
				@szATypeID,
				@szPTypeID,
				@szBTypeID,
				@szETypeID,
				@szKTypeID,
				@szSTypeID,
				@szPeriod,
				@dQty,
				@dTotal,
				@szJobNo,
				@nGoodsNo,
				@GoodsNumber,
				@ProduceDate,
				@ValidDate,
				@GoodsCostPrice	OUT,
				@HandZeroCost,
				@dCostPrice,
				@ModifyAuditBill,
				@MakeDate,
				@dPrice,
				@IfRedWord
				
				RETURN @intRet
			END
			-- 成本核算法到此结束
		END
	END

	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	功能说明：	移动加权
	作    者：	
	最后修改：	
*/
CREATE     PROCEDURE Gp_DealGoodsAVE 
(
	@nVchType			numeric(4, 0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szSTypeID			varchar(50),			--分支机构
	@szPeriod			varchar(2),				-- 8. 期号 (暂时不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
	@szJobNo			varchar(20),			-- 11. (暂时不用)
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10) ,			-- 16. 批次成本单价
	@HandZeroCost		int,					-- 17. 是否为手工输入0成本标志
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 18. 成本单价 (输出)
	@ModifyAuditBill	int=0,					-- 0表示正常单据，1表示修改过账后单据
	@MakeDate			datetime = null,		-- 19. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0,		-- 20. (暂时不用)
	@IfRedWord			TINYINT					--红冲标志
	--@ValidDate		varchar(50),			-- 21. 有效期至(手工指定)
	--@GoodsBTypeID		varchar(50)				-- 22. 供货商ID值(手工指定)
	
)
--@encode$--
AS
SET NOCOUNT ON


-- 声明会计科目相关变量
DECLARE	@GOODS_ID				varchar(50)



SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』


-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

DECLARE	@szSql					varchar(500),
		@DBName					varchar(20),
		@szJobNumber			varchar(20),
		@nAllowNegativeStock	int,

		@dTotalTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品金额
		@dQtyTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品数量
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
		@dPricetemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@nPeriod				int,
		@OutFactoryDate			datetime,
		@datValidDate			datetime,
		@nGoodsOrder			int

SET @dCostPrice		= 0

SET @dTotalTemp		= 0
SET @dQtyTemp		= 0
SET @dCostTotalTemp	= 0

SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0


-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', @szSTypeID,@nAllowNegativeStock output

-- begin tran Modifydbf
-- save tran Modifydbf
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------
*/
	-- 成本核算，传入的 ATypeID 参数必定为 “库存商品总值”
	IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
	BEGIN
		-- 若商品数量为 0 且 商品成本金额不等于 0，则回滚报错
		IF @dQty = 0 AND (@dTotal <> 0)
		BEGIN
			--RAISERROR('数据出错！',16,1)
			RETURN -7	-- 异常
		END

		

		IF @szPeriod = ''
		BEGIN
			/*****************************************************************
				移动加权平均成本核算法
			******************************************************************/
			IF @szCostingMethod = @AVERAGE
			BEGIN
				IF @dQty = 0 GOTO ERROR3

				-- 判断系统是否采用 “各仓库成本均价一致”
				DECLARE @chrAverageCostPrice varchar(1)

				SELECT	TOP 1 @chrAverageCostPrice = Value
				FROM	UserConfig
				WHERE	ConfigName = 'AverageCostPrice'

				-- 针对具体商品在所有仓库的成本均价
				-- 且库存记录必须同时满足数量和金额都大于等于 0
				DECLARE @numAverageCostPrice  NUMERIC(24, 10) 
				IF @chrAverageCostPrice = '1'
				BEGIN
					SELECT	@numAverageCostPrice =
								CASE WHEN ISNULL(SUM(Qty),0) = 0 OR ISNULL(SUM(Total),0) = 0 THEN 0
									 ELSE SUM(Total)/SUM(Qty)
								END
					FROM	GoodsStocks
					WHERE	PTypeID = @szPTypeID
							AND Qty >= 0
							AND Total >= 0
				END
				ELSE
				BEGIN
					SET @numAverageCostPrice = 0
				END

				-- 判断是否是　“调价全部仓库”　的操作
				DECLARE @ChangeAllStock int
				
				SET @ChangeAllStock = 0
				
				

				IF @nVchType = 57
				BEGIN
					SELECT	TOP 1 @ChangeAllStock = ChangeAllStock
					FROM	AdPriceBill
					WHERE	BillNumberID = @nGoodsNo
					
				END

				-- （1）读取库存状况表中的对应仓库的商品数量、成本均价、成本金额
				DECLARE ModifyDbf_Cursor CURSOR FOR
					SELECT	a.Qty,
							CASE WHEN a.Qty <> 0 THEN
								CAST(a.Total/a.Qty AS  NUMERIC(24, 10) )
							ELSE 0
							END AS CostPrice,
							a.Total,
							a.JobNumber,
							a.OutFactoryDate,
							a.GoodsOrder
					FROM	GoodsStocks a
					INNER JOIN
					(
						SELECT TypeID
						FROM Stock
						WHERE STypeID=@szSTypeID
					) b
					ON a.KTypeID=b.TypeID
					WHERE	a.PTypeID = @szPTypeID
							AND a.KTypeID = @szKTypeID
							
				FOR UPDATE

				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,		-- 当前库存商品数量
														@dCostPriceTemp,	-- 当前库存商品成本均价
														@dCostTotalTemp,	-- 当前库存商品成本金额
														@szJobNumber,
														@OutFactoryDate,
														@nGoodsOrder

			

				-- 库存状况表 GoodsStocks 中有对应的商品库存记录
				IF @@FETCH_STATUS = 0
				BEGIN
					-- 确定需核算的商品成本均价
					IF @dTotal <> 0
						-- 从传入参数：金额、数量，来确定成本均价
						SELECT @dCostPriceTemp = @dTotal / @dQty
					ELSE
					BEGIN
						-- 若传入参数：金额 = 0，且当前库存商品成本均价 <= 0，则成本单价取商品最近进价
						IF ( @dCostPricetemp = 0 OR @dCostQtyTemp = 0 OR @dCostTotalTemp = 0 ) AND @HandZeroCost = 0
							IF @dCostTotalTemp = 0 AND @dCostQtyTemp <> 0 --AND @dQty < 0	-- 出入库，数量不为零，成本金额为0，特殊处理
							BEGIN
								SET @HandZeroCost = 1
								SET @dCostPriceTemp = @dCostTotalTemp / @dCostQtyTemp
							END
							ELSE
							BEGIN
								SELECT	@dCostPriceTemp = RecPrice
								FROM	PType_STypePrice
								WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID
							END
						ELSE
						BEGIN
							IF @HandZeroCost = 1
								SET @dCostPriceTemp = 0
							ELSE
								SET @dCostPriceTemp = @dCostTotalTemp / @dCostQtyTemp
						END

						-- 成本调价单，且数量 > 0，成本金额 = 0
						IF @nVchType = 57 AND @dCostQtyTemp > 0 AND @dCostTotalTemp = 0
							SET @dCostPriceTemp = 0
					END

					-- 若最终得出的成本均价 = 0，则页面会提示输入成本价
					IF @dCostPriceTemp <= 0 AND @nVchType <> 57 AND @HandZeroCost = 0 AND @nVchType<>188
						GOTO ERRORINPUTCOSTPRICE

					-- 若成本单价不为零，乘数量后等于零，此种情况不允许过账
					--IF @dCostPriceTemp <> 0 AND CAST(@dCostPriceTemp * @dQty AS  NUMERIC(24, 10) ) = 0
					--	RETURN 818

					IF @dQty < 0	-- Qty 为负，代表商品出库
					BEGIN
						-- 出库数量大于当前库存商品数量
						IF @dCostQtyTemp < ABS(@dQty)
						BEGIN
							-- 库存数量不够时，调价单不能修改库存数据
							IF @nVchType = 57 AND @ChangeAllStock <> 1 GOTO ERROR4

							-- 不允许负库存，则进行提示
							IF @nAllowNegativeStock = 0 AND @ChangeAllStock <> 1 AND (@ModifyAuditBill=0 OR (@ModifyAuditBill=1 AND @nVchType NOT IN (34,144,21,188,201,57,174,17))) 
							BEGIN
								--SELECT '1'
								GOTO ERROR1
							END
							ELSE
							BEGIN
								IF @nVchType = 57 AND @dTotal = 0 AND @ChangeAllStock = 1 AND @IfRedWord = 2
								BEGIN
									SET @dCostPriceTemp = 0
								END
								-- 最终商品库存数量
								SET @dQtyTemp = @dCostQtyTemp + @dQty
								-- 最终商品库存金额
								IF @dTotal <> 0
									SET @dTotalTemp = @dCostTotalTemp + @dTotal
								ELSE
									SET @dTotalTemp = @dCostTotalTemp + CAST((@dQty * @dCostPriceTemp) AS  NUMERIC(24, 10) )

								-- 更新库存状况表商品具体数据：库存数量、库存金额
								UPDATE	GoodsStocks
								SET		Total = @dTotalTemp,
										Qty = @dQtyTemp,
										Price = @dTotalTemp / @dQtyTemp
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2

								IF @nVchType = 57
								BEGIN
									IF @dTotal <> 0
										SET @dCostPrice = @dTotal
									ELSE
										SET @dCostPrice = CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) )
								END
								ELSE
								BEGIN
									IF @dTotal <> 0
										SET @dCostPrice = ABS(@dTotal)
									ELSE
										SET @dCostPrice = ABS(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) ))
								END
								GOTO CLEANUP	-- 执行成功并退出
							END
						END

						-- 出库数量等于当前库存商品数量
						IF @dCostQtyTemp = ABS(@dQty)
						BEGIN
							IF @dTotal = 0	-- 出库金额 = 0
							BEGIN
								IF @dCostTotalTemp > 0
								BEGIN
									IF @HandZeroCost = 1	-- 2009.12 发现红冲采购单，单价为0的情况
									BEGIN
										SET @dQtyTemp = 0
										SET @dTotalTemp = @dCostTotalTemp

										UPDATE	GoodsStocks
										SET		Total	= @dTotalTemp,
												Qty		= @dQtyTemp,
												Price	= 0
										WHERE CURRENT OF ModifyDbf_Cursor
										IF @@ROWCOUNT = 0 GOTO ERROR2

										SET @dCostPrice = @dTotal
									END
									ELSE
									BEGIN
										DELETE FROM GoodsStocks
										WHERE CURRENT OF ModifyDbf_Cursor
										IF @@ROWCOUNT = 0 GOTO ERROR2
	
										IF @nVchType = 57
											SET @dCostPrice = -ABS(@dCostTotalTemp)
										ELSE
											SET @dCostPrice = ABS(@dCostTotaltemp)
									END
								END
								ELSE	-- @dCostTotalTemp <= 0
								BEGIN
									IF @nVchType = 57
									BEGIN
										SET @dTotal = -@dCostTotalTemp
									END
									ELSE
									BEGIN
										IF @HandZeroCost = 0
										BEGIN
											SELECT	@dTotal = CAST(@dQty * RecPrice AS  NUMERIC(24, 10) )
											FROM	PType_STypePrice
											WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID
	
											IF @dTotal >= 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE
										END
									END

									SELECT @dTotalTemp = @dCostTotalTemp + @dTotal
									SELECT @dQtyTemp = @dCostQtyTemp + @dQty	-- 0

									IF @dQtyTemp = 0 AND @dTotalTemp = 0
									BEGIN
										DELETE FROM GoodsStocks
										WHERE CURRENT OF ModifyDbf_Cursor
										IF @@ROWCOUNT = 0 GOTO ERROR2
									END
									ELSE
									BEGIN
										UPDATE	GoodsStocks
										SET		Total	= @dTotalTemp,
												Qty		= @dQtyTemp,
												price	= 0
										WHERE CURRENT OF ModifyDbf_Cursor
										IF @@ROWCOUNT = 0 GOTO ERROR2
									END

									IF @nVchType = 57
										SELECT @dCostPrice = @dTotal
									ELSE
										SELECT @dCostPrice = ABS(@dTotal)
								END
							END
							ELSE	-- Total <> 0
							BEGIN
								-- 若传入参数：金额不等于 0，则更新 GoodsStocks 中对应的库存记录：数量、单价、金额
								SET @dTotalTemp = @dCostTotalTemp + @dTotal
								SET @dQtyTemp = @dCostQtyTemp + @dQty
								SET @dCostPrice = ABS(@dTotal)

								-- 若最终计算出来的成本金额 = 0，则删除 GoodsStocks 中的库存记录
								IF @dTotalTemp = 0 AND @dQtyTemp = 0
								BEGIN
									DELETE FROM GoodsStocks
									WHERE CURRENT OF ModifyDbf_Cursor
									IF @@ROWCOUNT = 0 GOTO ERROR2
								END
								ELSE
								BEGIN
									UPDATE	GoodsStocks
									SET		Total = @dTotalTemp,
											Qty = @dQtyTemp,
											Price = 0
									WHERE CURRENT OF ModifyDbf_Cursor
									IF @@ROWCOUNT = 0 GOTO ERROR2
								END
							END

							GOTO CLEANUP
						END
						-- 出库数量小于当前库存商品数量
						ELSE
						BEGIN
							IF @nVchType = 57 AND @dCostPriceTemp < 0 GOTO ERRORINPUTCOSTPRICE

							IF @dTotal <> 0
								SET @dTotalTemp = @dCostTotalTemp + @dTotal
							ELSE
								SET @dTotalTemp = @dCostTotalTemp + CAST((@dQty * @dCostPriceTemp) AS  NUMERIC(24, 10) )
							SET @dQtyTemp = @dCostQtyTemp + @dQty


							UPDATE	GoodsStocks
							SET		Total = @dTotalTemp,
									Qty = @dQtyTemp,
									Price = @dTotalTemp / @dQtyTemp
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							IF @nVchType = 57
							BEGIN
								IF @dTotal <> 0
									SET @dCostPrice = @dTotal
								ELSE
									SET @dCostPrice = CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) )
							END
							ELSE
							BEGIN
								IF @dTotal <> 0
									SET @dCostPrice = ABS(@dTotal)
								ELSE
									SET @dCostPrice = ABS(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) ))
							END
							GOTO CLEANUP
						END
					END
					ELSE	-- Qty 为正，代表商品入库
					BEGIN
						-- 若传入成本金额为 0(如：报溢、获赠)，且非成本调价单
						IF @dTotal = 0 AND @nVchType <> 57 AND @HandZeroCost = 0
						BEGIN
							-- 库存中，若数量 或 成本金额为 0，则取最近进价
							IF @dCostQtyTemp = 0 OR @dCostTotalTemp = 0
							BEGIN
								IF @numAverageCostPrice = 0
								BEGIN
									SELECT	TOP 1 @dCostPriceTemp = RecPrice
									FROM	PType_STypePrice
									WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID
								END
								ELSE
								BEGIN
									SET @dCostPriceTemp = @numAverageCostPrice
								END
							END
							ELSE
							BEGIN
								-- 计算成本单价：库存金额 / 库存数量
								SELECT @dCostPriceTemp = @dCostTotalTemp / @dCostQtyTemp

								-- 若成本价 <= 0，则取最近进价
								IF @dCostPriceTemp <= 0
								BEGIN
									IF @numAverageCostPrice = 0
									BEGIN
										SELECT	TOP 1 @dCostPriceTemp = RecPrice
										FROM	PType_STypePrice
										WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID
									END
									ELSE
									BEGIN
										SET @dCostPriceTemp = @numAverageCostPrice
									END
								END
							END

							-- 若此时计算出的成本价仍 <= 0，则说明最近进价为 0 或有问题
							-- 则页面会提示输入成本价，该价格会写入商品最近进价
							IF @dCostPriceTemp <= 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE

							-- 最终计算出的商品成本单价 * 传入商品数量
							SET @dTotal = CAST(@dCostPriceTemp * @dQty AS  NUMERIC(24, 10) )
							IF @dTotal < 0 GOTO ERROR2
						END

						SET @dTotalTemp = @dCostTotalTemp + @dTotal
						SET @dQtyTemp = @dCostQtyTemp + @dQty

						-- 若最终计算出的库存商品数量不等于 0，则商品成本单价 = 最终库存金额 / 商品数量
						IF @dQtyTemp <> 0
						BEGIN
							SET @dCostPriceTemp = @dTotalTemp / @dQtyTemp
						END
						ELSE
						BEGIN
							-- ?若计算出的最终库存数量结果 = 0，则成本单价 = 0
							SET @dCostPriceTemp = 0
						END

						IF @dQtyTemp = 0 AND @dTotalTemp = 0
						BEGIN
							DELETE FROM GoodsStocks
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2
						END
						ELSE
						BEGIN
							UPDATE	GoodsStocks
							SET		Total	= @dTotalTemp,
									Qty		= @dQtyTemp,
									Price	= @dCostPriceTemp
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2
						END
						SET @dCostPrice = @dTotal
						GOTO CLEANUP
					END
				END
				-- GoodsStocks 数据表中，没有相关库存记录
				ELSE
				BEGIN
					IF @dQty < 0	-- Qty 为负，代表商品出库，此时为负库存设置才允许出库
					BEGIN
						-- 不允许负库存，则进行提示
						IF @nAllowNegativeStock = 0 AND @ChangeAllStock <> 1 AND (@ModifyAuditBill=0 OR (@ModifyAuditBill=1 AND @nVchType NOT IN (34,144,21,188,201,57,174,17)))
						BEGIN
							--SELECT 2
							GOTO ERROR1
						END
						-- 库存数量不够时，调价单不能修改库存数据
						IF @nVchType = 57 AND @ChangeAllStock <> 1 GOTO ERROR4
						ELSE
						BEGIN
							IF @nVchType = 57 AND @dTotal = 0 AND @ChangeAllStock = 1 AND @IfRedWord = 2
							BEGIN
								SET @dCostPriceTemp = 0
							END
							ELSE
							BEGIN
								IF @dTotal = 0 AND @HandZeroCost = 0
								BEGIN
									-- ?若输入参数：金额 = 0，则金额 = 最近进价 * 数量
									SELECT	@dTotal = CAST((RecPrice * @dQty) AS  NUMERIC(24, 10) )
									FROM	PType_STypePrice
									WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID
	
									-- 若最终得出的成本金额 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
									IF @dTotal = 0 AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE
								END
							END

							SET @dCostPriceTemp = @dTotal / @dQty
							SET @dTotalTemp = @dTotal

							INSERT	GoodsStocks (
								PTypeID,
								KTypeID,
								Qty,
								Total,
								Price
							)
							VALUES (
								@szPTypeID,
								@szKTypeID,
								@dQty,
								@dTotal,
								@dCostPriceTemp
							)
							IF @@ROWCOUNT = 0 GOTO ERROR2


							IF @nVchType = 57
								SET @dCostPrice = @dTotal
							ELSE
								SET @dCostPrice = ABS(@dTotal)
							GOTO CLEANUP
						END
					END

					IF @dTotal = 0 AND @HandZeroCost = 0
					BEGIN
						IF @numAverageCostPrice = 0
						BEGIN
							SELECT	@dTotal = CAST((RecPrice * @dQty) AS  NUMERIC(24, 10) )
							FROM	PType_STypePrice
							WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID
						END
						ELSE
						BEGIN
							SET @dTotal = CAST(@numAverageCostPrice * @dQty AS  NUMERIC(24, 10) )
						END

						-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
						IF @dTotal = 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE
					END

					SET @dCostPriceTemp = @dTotal / @dQty
					SET @dTotalTemp = @dTotal

					INSERT	GoodsStocks (
						PTypeID,
						KTypeID,
						Qty,
						Total,
						Price
					)
					VALUES (
						@szPTypeID,
						@szKTypeID,
						@dQty,
						@dTotal,
						@dCostPriceTemp
					)
					IF @@ROWCOUNT = 0 GOTO ERROR2

					SET @dCostPrice = ABS(@dTotal)
					GOTO CLEANUP
				END
			-- select @dCostPrice=@dTotaltemp*@dQty
			-- goto CleanUp
			END
			
		END
	END
	

	CLEANUP:
		-- 返回成功值并退出
		-- 释放游标
		DEALLOCATE ModifyDbf_Cursor
		-- commit tran --ModifyDbf

		RETURN 0

	ERROR1:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -1

	ERROR2:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -2

	ERROR3:
		-- 当数量为 0 时，回滚
		-- 一般非物流单据过账时会出现这种情况
		-- rollback tran --ModifyDbf
		RETURN 0


	ERROR4:
		-- rollback tran --ModifyDbf
		DEALLOCATE ModifyDbf_Cursor
		RETURN -4

	ERRORINPUTCOSTPRICE:
		-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
		DEALLOCATE ModifyDbf_Cursor
		RETURN -5

	ERRORINIMODIFYDENY:
		-- 系统已正式开账，不能修改期初
		RETURN -6

	SUCCESS:
		-- 执行成功
		-- commit tran --ModifyDbf
		RETURN 0

GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	功能说明：	先进先出
	作    者：	
	最后修改：	
*/
CREATE     PROCEDURE Gp_DealGoodsFIFO 
(
	@nVchType			numeric(4, 0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szSTypeID			varchar(50),			--分支机构
	@szPeriod			varchar(2),				-- 8. 期号 (暂时不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
	@szJobNo			varchar(20),			-- 11. (暂时不用)
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10) ,			-- 16. 批次成本单价
	@HandZeroCost		int,					-- 17. 是否为手工输入0成本标志
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 18. 成本单价 (输出)
	@ModifyAuditBill	int=0,					-- 0表示正常单据，1表示修改过账后单据
	@MakeDate			datetime = null,		-- 19. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0,		-- 20. (暂时不用)
	@IfRedWord			TINYINT					--红冲标志
	--@ValidDate		varchar(50),			-- 21. 有效期至(手工指定)
	--@GoodsBTypeID		varchar(50)				-- 22. 供货商ID值(手工指定)
	
)
--@encode$--
AS
SET NOCOUNT ON


-- 声明会计科目相关变量
DECLARE	@GOODS_ID				varchar(50)


SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』

-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

DECLARE	@szSql					varchar(500),
		@DBName					varchar(20),
		@szJobNumber			varchar(20),
		@nAllowNegativeStock	int,

		@dTotalTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品金额
		@dQtyTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品数量
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
		@dPricetemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@nPeriod				int,
		@OutFactoryDate			datetime,
		@datValidDate			datetime,
		@nGoodsOrder			int

SET @dCostPrice		= 0

SET @dTotalTemp		= 0
SET @dQtyTemp		= 0
SET @dCostTotalTemp	= 0

SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0


-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', @szSTypeID,@nAllowNegativeStock output

-- begin tran Modifydbf
-- save tran Modifydbf
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------
*/
	-- 成本核算，传入的 ATypeID 参数必定为 “库存商品总值”
	IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
	BEGIN
		-- 若商品数量为 0 且 商品成本金额不等于 0，则回滚报错
		IF @dQty = 0 AND (@dTotal <> 0)
		BEGIN
			--RAISERROR('数据出错！',16,1)
			RETURN -7	-- 异常
		END

		

		IF @szPeriod = ''
		BEGIN
			/*****************************************************************
				先进先出成本算法
			******************************************************************/
			IF @szCostingMethod = @FIFO
			BEGIN
				IF @dQty = 0 GOTO ERROR3

				EXEC Gp_GetDbf	@GOODS_ID,
								@szPTypeID,
								'0',
								'0',
								@szKTypeID,
								@szSTypeID,
								'',
								'',
								@dQtyTemp output,
								@dTotalTemp output

				IF @dQtyTemp + @dQty < 0
				BEGIN
					RETURN -1
				END
				SET @dQtyTemp = @dQty
				SET @dTotalTemp = 0

				IF @dQty < 0
				BEGIN
					IF @dTotal <> 0 OR (@dTotal = 0 AND @HandZeroCost = 1)
					BEGIN
						DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
							SELECT	Qty,
									CASE WHEN Qty <> 0 THEN
										CAST(Total/Qty AS  NUMERIC(24, 10) )
									ELSE 0
									END AS CostPrice,
									Total,
									JobNumber,
									OutFactoryDate,
									GoodsOrder
							FROM	GoodsStocks
							WHERE	PTypeID = @szPTypeID
									AND KTypeID = @szKTypeID
									AND ABS( CAST(Total/Qty AS  NUMERIC(24, 10) ) - CAST(@dTotal/@dQty AS  NUMERIC(24, 10) ) ) <= 0.001
							ORDER BY GoodsOrder ASC FOR UPDATE		-- 出库，则升序查询
					END
					ELSE
					BEGIN
						DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
							SELECT	Qty,
									CASE WHEN Qty <> 0 THEN
										CAST(Total/Qty AS  NUMERIC(24, 10) )
									ELSE 0
									END AS CostPrice,
									Total,
									JobNumber,
									OutFactoryDate,
									GoodsOrder
							FROM	GoodsStocks
							WHERE	PTypeID = @szPTypeID
									AND KTypeID = @szKTypeID
							ORDER BY GoodsOrder ASC FOR UPDATE		-- 出库，则升序查询
					END
				END
				ELSE
				BEGIN
					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								CASE WHEN Qty <> 0 THEN
									CAST(Total/Qty AS  NUMERIC(24, 10) )
								ELSE 0
								END AS CostPrice,
								Total,
								JobNumber,
								OutFactoryDate,
								GoodsOrder
						FROM	GoodsStocks 
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
						ORDER BY GoodsOrder DESC FOR UPDATE		-- 入库，则倒序查询
				END

				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
														@dCostPriceTemp,
														@dCostTotalTemp,
														@szJobNumber,
														@OutFactoryDate,
														@nGoodsOrder
				WHILE @@FETCH_STATUS = 0
				BEGIN
					-- 若成本单价不为零，乘数量后等于零，此种情况不允许过账
					--IF @dCostPriceTemp <> 0 AND CAST(@dCostPriceTemp * @dQty AS  NUMERIC(24, 10) ) = 0
					--	RETURN 818
					IF @dQty < 0
					BEGIN
						-- if @nVchType=57 select @nGoodsOrdertemp=@nGoodsOrder,@szJobNotemp=@szJobNumber
						SET @dQty = @dCostQtyTemp + @dQty
						-- print @dQty
						IF @dQty <= 0
						BEGIN
							SET @dTotalTemp = @dTotalTemp + @dCostTotalTemp
							-- print @dTotaltemp

							IF @dQty = 0 AND @dTotal <> 0
							BEGIN
								IF @dCostTotalTemp = ABS(@dTotal) - ( ABS(@dTotalTemp) - @dCostTotalTemp )
								BEGIN
									DELETE FROM GoodsStocks
									WHERE CURRENT OF ModifyDbf_Cursor
									IF @@ROWCOUNT = 0 GOTO ERROR2
								END
								ELSE
								BEGIN
									--SELECT 3
									GOTO ERROR1
								END
							END
							ELSE
							BEGIN
								DELETE FROM GoodsStocks
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2
							END

							IF @dQty <> 0
							BEGIN
								FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
																		@dCostPriceTemp,
																		@dCostTotalTemp,
																		@szJobNumber,
																		@OutFactoryDate,
																		@nGoodsOrder
								CONTINUE
							END
							ELSE IF @dQty = 0
							BEGIN
								IF @nVchType = 57
									SET @dCostPrice = -CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
								ELSE
									SET @dCostPrice = CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
								GOTO CleanUp
							END
						END
						ELSE
						BEGIN
							IF @dTotal <> 0
								SET @dTotalTemp = @dTotalTemp
							ELSE
								SET @dTotalTemp = @dTotalTemp + CAST( ( (@dCostQtyTemp - @dQty) * CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) ) AS  NUMERIC(24, 10) )
							IF @nVchType = 57
								SET @dCostPrice = -CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
							ELSE
							BEGIN
								IF @dTotal <> 0
									SET @dCostPrice = CAST(ABS(@dTotal) AS  NUMERIC(24, 10) )
								ELSE
									SET @dCostPrice = CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
							END

							IF @dTotal <> 0
							BEGIN
								UPDATE	GoodsStocks
								SET		Qty		= @dQty,
										Total	= @dCostTotalTemp + @dTotalTemp + @dTotal,
										Price	= ( @dCostTotalTemp + @dTotalTemp + @dTotal )/@dQty
								WHERE	CURRENT OF ModifyDbf_Cursor
							END
							ELSE
							BEGIN
								UPDATE	GoodsStocks
								SET		Qty		= @dQty,
										Total	= @dCostTotalTemp - CAST( ( (@dCostQtyTemp - @dQty) * CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) ) AS  NUMERIC(24, 10) ),
										Price	= ( @dCostTotalTemp - CAST( ( (@dCostQtyTemp - @dQty) * CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) ) AS  NUMERIC(24, 10) ) )/@dQty
								WHERE	CURRENT OF ModifyDbf_Cursor
							END
							IF @@ROWCOUNT = 0 GOTO ERROR2

							GOTO CLEANUP
						END
					END
					ELSE
					BEGIN
						IF @dTotal = 0 AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = CAST(RecPrice * @dQty AS  NUMERIC(24, 10) )
							FROM	PType_STypePrice
							WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID

							IF @dTotal <= 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE
						END

						SET @dPriceTemp = @dTotal / @dQty
						IF @dPriceTemp < 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE

						IF @nVchType = 57	-- 调价单处理
						BEGIN
							FETCH LAST FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
																	@dCostPriceTemp,
																	@dCostTotalTemp,
																	@szJobNumber,
																	@OutFactoryDate,
																	@nGoodsOrder

							IF @dPriceTemp = CASE WHEN @dCostQtyTemp = 0 THEN 0 ELSE CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) END
							BEGIN
								SET @dTotalTemp = @dCostTotalTemp + @dTotal
								SET @dQtyTemp = @dCostQtyTemp + @dQty

								UPDATE	GoodsStocks
								SET		Qty		= @dQtyTemp,
										Total	= @dTotalTemp,
										Price	= @dTotalTemp / @dQtyTemp
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2

								SET @dCostPrice = ABS(@dTotal)
								GOTO CLEANUP
							END
							ELSE
							BEGIN
								SET @dCostPrice = ABS(@dTotal)

								INSERT GoodsStocks (
									PTypeID,
									KTypeID,
									Qty,
									Total,
									Price,
									GoodsOrder,
									JobNumber
								)
								VALUES (
									@szPTypeID,
									@szKTypeID,
									@dQty,
									@dTotal,
									@dPricetemp,
									@nGoodsOrder - 1,
									@szJobNo
								)
								IF @@ROWCOUNT = 0 GOTO ERROR2

								GOTO CLEANUP
							END
						END

						IF @dPriceTemp = CASE WHEN @dCostQtyTemp = 0 THEN 0 ELSE CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) END
						BEGIN
							SET @dTotalTemp = @dCostTotalTemp + @dTotal
							SET @dQtyTemp = @dCostQtyTemp + @dQty


							UPDATE	GoodsStocks
							SET		Qty		= @dQtyTemp,
									Total	= @dTotalTemp,
									Price	= @dTotalTemp / @dQtyTemp
							WHERE	CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							SET @dCostPrice = ABS(@dTotal)
							GOTO CLEANUP
						END
						ELSE
						BEGIN
							SET @dCostPrice = ABS(@dTotal)

							INSERT GoodsStocks (
								PTypeID,
								KTypeID,
								Qty,
								Total,
								Price,
								GoodsOrder,
								JobNumber
							)
							VALUES (
								@szPTypeID,
								@szKTypeID,
								@dQty,
								@dTotal,
								@dPriceTemp,
								@nGoodsOrder + 1,
								@szJobNo
							)
							IF @@ROWCOUNT = 0 GOTO ERROR2

							GOTO CLEANUP
						END
					END
				END

				IF @@FETCH_STATUS <> 0
				BEGIN
					IF @dQty < 0 
					BEGIN
						--SELECT 4
						GOTO ERROR1	-- 负库存
					END
					ELSE
					BEGIN
						IF @dTotal = 0 AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = CAST(RecPrice * @dQty AS  NUMERIC(24, 10) )
							FROM	PType_STypePrice
							WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID

							-- 若最终无法获取成本金额，则提示手工输入
							IF @dTotal = 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE
						END
	
						SET @dPriceTemp = @dTotal / @dQty
						IF @dPriceTemp < 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE

						SET @dCostPrice = ABS(@dTotal)
	
						INSERT GoodsStocks (
							PTypeID,
							KTypeID,
							Qty,
							Total,
							Price,
							GoodsOrder,
							JobNumber
						)
						VALUES (
							@szPTypeID,
							@szKTypeID,
							@dQty,
							@dTotal,
							@dPriceTemp,
							1,					-- 新生成的批次默认为 1
							@szJobNo
						)
						IF @@ROWCOUNT = 0 GOTO ERROR2

						GOTO CLEANUP
					END
				END
			END
			-- 成本核算法到此结束
		END
		/*---------------------修改期初--------------------*/
	END
	
	CLEANUP:
		-- 返回成功值并退出
		-- 释放游标
		DEALLOCATE ModifyDbf_Cursor
		-- commit tran --ModifyDbf

		RETURN 0

	ERROR1:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -1

	ERROR2:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -2

	ERROR3:
		-- 当数量为 0 时，回滚
		-- 一般非物流单据过账时会出现这种情况
		-- rollback tran --ModifyDbf
		RETURN 0


	ERROR4:
		-- rollback tran --ModifyDbf
		DEALLOCATE ModifyDbf_Cursor
		RETURN -4

	ERRORINPUTCOSTPRICE:
		-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
		DEALLOCATE ModifyDbf_Cursor
		RETURN -5

	ERRORINIMODIFYDENY:
		-- 系统已正式开账，不能修改期初
		RETURN -6

	SUCCESS:
		-- 执行成功
		-- commit tran --ModifyDbf
		RETURN 0

GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	功能说明：	手工指定
	作    者：	
	最后修改：	
*/
CREATE     PROCEDURE Gp_DealGoodsHand 
(
	@nVchType			numeric(4, 0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szSTypeID			varchar(50),			--分支机构
	@szPeriod			varchar(2),				-- 8. 期号 (暂时不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
	@szJobNo			varchar(20),			-- 11. (暂时不用)
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10) ,			-- 16. 批次成本单价
	@HandZeroCost		int,					-- 17. 是否为手工输入0成本标志
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 18. 成本单价 (输出)
	@ModifyAuditBill	int=0,					-- 0表示正常单据，1表示修改过账后单据
	@MakeDate			datetime = null,		-- 19. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0,		-- 20. (暂时不用)
	@IfRedWord			TINYINT					--红冲标志
	--@ValidDate		varchar(50),			-- 21. 有效期至(手工指定)
	--@GoodsBTypeID		varchar(50)				-- 22. 供货商ID值(手工指定)
	
)
--@encode$--
AS
SET NOCOUNT ON


-- 声明会计科目相关变量
DECLARE	@GOODS_ID				varchar(50)


SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』

-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

DECLARE	@szSql					varchar(500),
		@DBName					varchar(20),
		@szJobNumber			varchar(20),
		@nAllowNegativeStock	int,

		@dTotalTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品金额
		@dQtyTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品数量
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
		@dPricetemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@nPeriod				int,
		@OutFactoryDate			datetime,
		@datValidDate			datetime,
		@nGoodsOrder			int

SET @dCostPrice		= 0

SET @dTotalTemp		= 0
SET @dQtyTemp		= 0
SET @dCostTotalTemp	= 0

SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0


-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', @szSTypeID,@nAllowNegativeStock output

-- begin tran Modifydbf
-- save tran Modifydbf
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------
*/
	-- 成本核算，传入的 ATypeID 参数必定为 “库存商品总值”
	IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
	BEGIN
		-- 若商品数量为 0 且 商品成本金额不等于 0，则回滚报错
		IF @dQty = 0 AND (@dTotal <> 0)
		BEGIN
			--RAISERROR('数据出错！',16,1)
			RETURN -7	-- 异常
		END

		

		IF @szPeriod = ''
		BEGIN
			/*****************************************************************
				手工指定成本算法
			******************************************************************/
			IF @szCostingMethod = @HAND
			BEGIN
				-- 解决手工指定法单价太小，造成误差太大的问题
				
				/*
				UPDATE	GoodsStocks
				SET		Price = Total/Qty
				WHERE	Qty <> 0
						AND PTypeID = @szPTypeID
						AND KTypeID = @szKTypeID
				*/
				
				
				IF @dQty = 0 GOTO ERROR3

				-- 批次成本价不为零，乘数量后等于零，此种情况不允许过账
				--IF @GoodsCostPrice <> 0 AND CAST(@GoodsCostPrice * @dQty AS  NUMERIC(24, 10) ) = 0
				--	RETURN 818

				IF @dQty < 0
				BEGIN
					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								GoodsNumber,--JobNumber,
								ProduceDate,--OutFactoryDate,
								ValidDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
								AND GoodsNumber = @GoodsNumber
								AND ProduceDate = @ProduceDate
								AND ValidDate = @ValidDate
								AND ABS(Price-@GoodsCostPrice) = 0
						-- 如果有两个以上完全相同的批次，则先出数量大的
						ORDER BY Qty DESC FOR UPDATE
				END
				ELSE
				BEGIN
					-- 入库金额为0，且不能指定入库单价的单据
					IF @dTotal = 0 AND @HandZeroCost = 0
					BEGIN
						SELECT	@dTotal = CAST(RecPrice * @dQty AS  NUMERIC(24, 10) )
						FROM	PType_STypePrice
						WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID

						IF @dTotal <= 0 
						BEGIN
							--PRINT('1')
							--PRINT(@dTotal)
							RETURN -5--GOTO ERRORINPUTCOSTPRICE基础通讯版有区别
						END
					END
					
					/*
					SELECT TOP 1 @dPricetemp = price FROM InOutstocktable 
					WHERE PTypeID=@szPTypeID AND btypeid=@szBTypeID AND EtypeId=@szETypeID AND ktypeid=@szKTypeID AND BillType=34 AND AtypeId=@szATypeID AND stypeid=@szSTypeID  ORDER BY billnumberid DESC
					
					SET @dPriceTemp = @dTotal/@dQty
					*/
					
					SET @dPricetemp=@dPrice

					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								GoodsNumber,--JobNumber,
								ProduceDate,--OutFactoryDate,
								ValidDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
								AND GoodsNumber = @GoodsNumber
								AND ProduceDate = @ProduceDate
								AND ValidDate = @ValidDate
								AND Price = @dPriceTemp
						ORDER BY GoodsOrder DESC FOR UPDATE
				END

				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
														@dCostPriceTemp,
														@dCostTotalTemp,
														@szJobNumber,
														@OutFactoryDate,
														@datValidDate,
														@nGoodsOrder
				IF @@FETCH_STATUS = 0
				BEGIN
					IF @dQty < 0	-- 出库
					BEGIN
						IF @dCostQtyTemp < ABS(@dQty) 
						BEGIN
							--SELECT 7
							GOTO ERROR1	-- 数量不够，返回错误
						END

						IF @dCostQtyTemp = ABS(@dQty)	-- 数量相同
						BEGIN
							DELETE FROM	GoodsStocks
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							IF @nVchType = 57
								SET @dCostPrice = -ABS(@dCostTotalTemp)
							ELSE
								SET @dCostPrice = ABS(@dCostTotalTemp)
							GOTO CleanUp
						END
						ELSE
						BEGIN
							SET @dCostTotalTemp = @dCostTotalTemp + CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) )
							SET @dQtyTemp = @dCostQtyTemp + @dQty

							UPDATE	GoodsStocks
							SET		Total = @dCostTotalTemp,
									--Price = @dCostTotalTemp/@dQtyTemp,
									Qty = @dQtyTemp
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							IF @nVchType = 57
								SET @dCostPrice = -ABS(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) ))
							ELSE
								SET @dCostPrice = ABS(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) ))
							GOTO CleanUp
						END
					END
					ELSE	-- 有指定批次入库
					BEGIN
						SET @dTotalTemp	= @dCostTotalTemp + @dTotal
						SET @dQtyTemp	= @dCostQtyTemp + @dQty

						UPDATE	GoodsStocks
						SET		Qty = @dQtyTemp,
								Total = @dTotalTemp
								--Price = @dTotalTemp/@dQtyTemp
						WHERE CURRENT OF ModifyDbf_Cursor
						IF @@ROWCOUNT = 0 GOTO ERROR2

						SET @dCostPrice = @dTotal
						GOTO CleanUp
					END
				END
				ELSE	-- 无该批次入库
				BEGIN
					IF @dQty < 0 
					BEGIN
						--SELECT 8
						GOTO ERROR1
					END
					ELSE
					BEGIN
						IF @dTotal IN ( 0,-1) AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = CAST(RecPrice * @dQty AS  NUMERIC(24, 10) ),@dPrice=RecPrice
							FROM	PType_STypePrice
							WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID
	
							IF @dTotal <= 0  AND @nVchType<>188 
							BEGIN
								--PRINT('2')
								--PRINT(@dTotal)
								GOTO ERRORINPUTCOSTPRICE
							END
						END

						SELECT	@nGoodsOrder = ISNULL(MAX(Goodsorder),0)
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
						
						/*
						SELECT TOP 1 @dPricetemp = price FROM InOutstocktable 
						WHERE PTypeID=@szPTypeID AND btypeid=@szBTypeID AND EtypeId=@szETypeID AND ktypeid=@szKTypeID AND BillType=34 AND AtypeId=@szATypeID AND stypeid=@szSTypeID  ORDER BY billnumberid DESC
						
						SET @dPriceTemp	= @dTotal/@dQty
						*/
						
						SET @dPricetemp=@dPrice
						
						IF @dPriceTemp < 0  AND @nVchType<>188 
						BEGIN
							--PRINT('3')
							--PRINT(@dPriceTemp)
							GOTO ERRORINPUTCOSTPRICE
						END
						SET @dCostPrice	= @dTotal

						INSERT	GoodsStocks (
							PTypeID,
							KTypeID,
							Qty,
							Total,
							Price,
							GoodsNumber,--JobNumber,
							ProduceDate,
							ValidDate,
							GoodsOrder
						)
						VALUES (
							@szPTypeID,
							@szKTypeID,
							@dQty,
							@dTotal,
							@dPriceTemp,
							@GoodsNumber,
							@ProduceDate,
							@ValidDate,
							@nGoodsOrder + 1
						)
						IF @@ROWCOUNT = 0 GOTO ERROR2
						GOTO CleanUp
					END
				END
			END
			-- 成本核算法到此结束
		END
		/*---------------------修改期初--------------------*/
	END
	
	CLEANUP:
		-- 返回成功值并退出
		-- 释放游标
		DEALLOCATE ModifyDbf_Cursor
		-- commit tran --ModifyDbf

		RETURN 0

	ERROR1:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -1

	ERROR2:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -2

	ERROR3:
		-- 当数量为 0 时，回滚
		-- 一般非物流单据过账时会出现这种情况
		-- rollback tran --ModifyDbf
		RETURN 0


	ERROR4:
		-- rollback tran --ModifyDbf
		DEALLOCATE ModifyDbf_Cursor
		RETURN -4

	ERRORINPUTCOSTPRICE:
		-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
		DEALLOCATE ModifyDbf_Cursor
		RETURN -5

	ERRORINIMODIFYDENY:
		-- 系统已正式开账，不能修改期初
		RETURN -6

	SUCCESS:
		-- 执行成功
		-- commit tran --ModifyDbf
		RETURN 0

GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	功能说明：	后进先出
	作    者：	
	最后修改：	
*/
CREATE     PROCEDURE Gp_DealGoodsLIFO 
(
	@nVchType			numeric(4, 0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szSTypeID			varchar(50),			--分支机构
	@szPeriod			varchar(2),				-- 8. 期号 (暂时不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
	@szJobNo			varchar(20),			-- 11. (暂时不用)
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10) ,			-- 16. 批次成本单价
	@HandZeroCost		int,					-- 17. 是否为手工输入0成本标志
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 18. 成本单价 (输出)
	@ModifyAuditBill	int=0,					-- 0表示正常单据，1表示修改过账后单据
	@MakeDate			datetime = null,		-- 19. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0,		-- 20. (暂时不用)
	@IfRedWord			TINYINT					--红冲标志
	--@ValidDate		varchar(50),			-- 21. 有效期至(手工指定)
	--@GoodsBTypeID		varchar(50)				-- 22. 供货商ID值(手工指定)
	
)
--@encode$--
AS
SET NOCOUNT ON


-- 声明会计科目相关变量
DECLARE	@GOODS_ID				varchar(50)

SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』

-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

DECLARE	@szSql					varchar(500),
		@DBName					varchar(20),
		@szJobNumber			varchar(20),
		@nAllowNegativeStock	int,

		@dTotalTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品金额
		@dQtyTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品数量
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
		@dPricetemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@nPeriod				int,
		@OutFactoryDate			datetime,
		@datValidDate			datetime,
		@nGoodsOrder			int

SET @dCostPrice		= 0

SET @dTotalTemp		= 0
SET @dQtyTemp		= 0
SET @dCostTotalTemp	= 0

SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0


-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', @szSTypeID,@nAllowNegativeStock output

-- begin tran Modifydbf
-- save tran Modifydbf
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------
*/
	-- 成本核算，传入的 ATypeID 参数必定为 “库存商品总值”
	IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
	BEGIN
		-- 若商品数量为 0 且 商品成本金额不等于 0，则回滚报错
		IF @dQty = 0 AND (@dTotal <> 0)
		BEGIN
			--RAISERROR('数据出错！',16,1)
			RETURN -7	-- 异常
		END

		

		IF @szPeriod = ''
		BEGIN
			
			/*****************************************************************
				后进先出成本算法
			******************************************************************/
			IF @szCostingMethod = @LIFO
			BEGIN
				IF @dQty = 0 GOTO ERROR3

				EXEC Gp_GetDbf	@GOODS_ID,
								@szPTypeID,
								'0',
								'0',
								@szKTypeID,
								@szSTypeID,
								'',
								'',
								@dQtyTemp output,
								@dTotalTemp output

				IF ( @dQtyTemp + @dQty ) < 0
				BEGIN
					RETURN -1
				END

				SET @dQtyTemp = @dQty
				SET @dTotalTemp = 0

				IF @dQty < 0 AND (@dTotal <> 0 OR (@dTotal = 0 AND @HandZeroCost = 1))
				BEGIN
					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								JobNumber,
								OutFactoryDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
								AND ABS( CAST(Total/Qty AS  NUMERIC(24, 10) ) - CAST(@dTotal/@dQty AS  NUMERIC(24, 10) ) ) <= 0.001
						ORDER BY GoodsOrder DESC FOR UPDATE
				END
				ELSE
				BEGIN
					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								JobNumber,
								OutFactoryDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
						ORDER BY GoodsOrder DESC FOR UPDATE

				END

				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
														@dCostPriceTemp,
														@dCostTotalTemp,
														@szJobNumber,
														@OutFactoryDate,
														@nGoodsOrder
				WHILE @@FETCH_STATUS = 0
				BEGIN
					-- 若成本单价不为零，乘数量后等于零，此种情况不允许过账
					--IF @dCostPriceTemp <> 0 AND CAST(@dCostPriceTemp * @dQty AS  NUMERIC(24, 10) ) = 0
					--	RETURN 818

					IF @dQty < 0
					BEGIN
						-- if @nVchType=57 select @nGoodsOrdertemp=@nGoodsOrder,@szJobNotemp=@szJobNumber
						SET @dQty = @dCostQtyTemp + @dQty
						-- print @dQty
						IF @dQty <= 0
						BEGIN
							SET @dTotalTemp = @dTotalTemp + @dCostTotalTemp
							-- print @dTotaltemp

							IF @dQty = 0 AND @dTotal <> 0
							BEGIN
								IF @dCostTotalTemp = ABS(@dTotal) - ( ABS(@dTotalTemp) - @dCostTotalTemp )
								BEGIN
									DELETE FROM GoodsStocks
									WHERE CURRENT OF ModifyDbf_Cursor
									IF @@ROWCOUNT = 0 GOTO ERROR2
								END
								ELSE
								BEGIN
									--SELECT 5
									GOTO ERROR1
								END
							END
							ELSE
							BEGIN
								DELETE FROM GoodsStocks
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2
							END

							IF @dQty <> 0
							BEGIN
								FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
																		@dCostPriceTemp,
																		@dCostTotalTemp,
																		@szJobNumber,
																		@OutFactoryDate,
																		@nGoodsOrder
								CONTINUE
							END
							ELSE IF @dQty = 0
							BEGIN
								IF @nVchType = 57
									SET @dCostPrice = -CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
								ELSE
									SET @dCostPrice = CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
								GOTO CLEANUP
							END
						END
						ELSE
						BEGIN
							IF @dTotal <> 0
								SET @dTotalTemp = @dTotalTemp
							ELSE
								SET @dTotalTemp = @dTotalTemp + CAST( ( (@dCostQtyTemp - @dQty) * CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) ) AS  NUMERIC(24, 10) )
							IF @nVchType = 57
								SET @dCostPrice = -CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
							ELSE
							BEGIN
								IF @dTotal <> 0
									SET @dCostPrice = CAST(ABS(@dTotal) AS  NUMERIC(24, 10) )
								ELSE
									SET @dCostPrice = CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
							END

							IF @dTotal <> 0
							BEGIN
								UPDATE	GoodsStocks
								SET		Qty = @dQty,
										Total	= @dCostTotalTemp + @dTotalTemp + @dTotal,
										Price	= ( @dCostTotalTemp + @dTotalTemp + @dTotal )/@dQty
								WHERE CURRENT OF ModifyDbf_Cursor
							END
							ELSE
							BEGIN
								UPDATE	GoodsStocks
								SET		Qty = @dQty,
										Total	= @dCostTotalTemp - CAST( ( (@dCostQtyTemp - @dQty) * CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) ) AS  NUMERIC(24, 10) ),
										Price	= ( @dCostTotalTemp - CAST( ( (@dCostQtyTemp - @dQty) * CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) ) AS  NUMERIC(24, 10) ) )/@dQty
								WHERE CURRENT OF ModifyDbf_Cursor
							END
							IF @@ROWCOUNT = 0 GOTO ERROR2

							GOTO CLEANUP
						END
					END
					ELSE
					BEGIN
						IF @dTotal = 0 AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = CAST(RecPrice * @dQty AS  NUMERIC(24, 10) )
							FROM	PType_STypePrice
							WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID

							IF @dTotal = 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE
						END

						SET @dPriceTemp = @dTotal / @dQty
						IF @dPriceTemp < 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE

						IF @dPriceTemp = CASE WHEN @dCostQtyTemp = 0 THEN 0 ELSE CAST(@dCostTotalTemp/@dCostQtyTemp AS  NUMERIC(24, 10) ) END
						BEGIN
							SET @dTotalTemp	= @dCostTotalTemp + @dTotal
							SET @dQtyTemp	= @dCostQtyTemp + @dQty

							UPDATE	GoodsStocks
							SET		Qty		= @dQtyTemp,
									Total	= @dTotalTemp,
									Price	= @dTotalTemp / @dQtyTemp
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							SET @dCostPrice = ABS(@dTotal)
							GOTO CleanUp

						END
						ELSE
						BEGIN
							SET @dCostPrice = ABS(@dTotal)

							INSERT	GoodsStocks (
								PTypeID,
								KTypeID,
								Qty,
								Total,
								Price,
								GoodsOrder,
								JobNumber
							)
							VALUES (
								@szPTypeID,
								@szKTypeID,
								@dQty,
								@dTotal,
								@dPriceTemp,
								@nGoodsOrder + 1,
								@szJobNo
							)
							IF @@ROWCOUNT = 0 GOTO ERROR2

							GOTO CleanUp
						END
					END
				END

				-- 库存无记录
				IF @@FETCH_STATUS <> 0
				BEGIN
					IF @dQty < 0 
					BEGIN
						--SELECT 6
						GOTO ERROR1	-- 负库存回滚
					END
					ELSE
					BEGIN
						IF @dTotal = 0 AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = CAST( RecPrice * @dQty AS  NUMERIC(24, 10) )
							FROM	PType_STypePrice
							WHERE	PTypeID = @szPTypeID AND STypeID=@szSTypeID

							IF @dTotal = 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE
						END

						SET @dPriceTemp	= @dTotal / @dQty
						IF @dPriceTemp < 0  AND @nVchType<>188 GOTO ERRORINPUTCOSTPRICE

						SET @dCostPrice	= ABS(@dTotal)

						INSERT GoodsStocks (
							PTypeID,
							KTypeID,
							Qty,
							Total,
							Price,
							GoodsOrder,
							JobNumber
						)
						VALUES (
							@szPTypeID,
							@szKTypeID,
							@dQty,
							@dTotal,
							@dPriceTemp,

							1,					--  新生成的批次默认为 1
							@szJobNo
						)
						IF @@ROWCOUNT = 0 GOTO ERROR2

						GOTO CleanUp
					END
				END

			END
			
			-- 成本核算法到此结束
		END
		/*---------------------修改期初--------------------*/
	END
	

	CLEANUP:
		-- 返回成功值并退出
		-- 释放游标
		DEALLOCATE ModifyDbf_Cursor
		-- commit tran --ModifyDbf

		RETURN 0

	ERROR1:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -1

	ERROR2:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -2

	ERROR3:
		-- 当数量为 0 时，回滚
		-- 一般非物流单据过账时会出现这种情况
		-- rollback tran --ModifyDbf
		RETURN 0


	ERROR4:
		-- rollback tran --ModifyDbf
		DEALLOCATE ModifyDbf_Cursor
		RETURN -4

	ERRORINPUTCOSTPRICE:
		-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
		DEALLOCATE ModifyDbf_Cursor
		RETURN -5

	ERRORINIMODIFYDENY:
		-- 系统已正式开账，不能修改期初
		RETURN -6

	SUCCESS:
		-- 执行成功
		-- commit tran --ModifyDbf
		RETURN 0

GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



/*
	作者：谢吉康
	日期：2007-4-11
	描述：处理手工指定法的期初
	TRUNCATE TABLE iniGoodsStocks
*/
CREATE   PROCEDURE Gp_DealHandCostIniData
(
	@nType		varchar(10),		-- A.新增   M.修改  D.删除
	@PTypeId	varchar(100),
	@KTypeId	varchar(100),
	@Qty		 NUMERIC(24, 10) ,
	@Price		 NUMERIC(24, 10) ,
	@Total		 NUMERIC(24, 10) ,
	@gNumber	varchar(1000),
	@pDate		varchar(50),
	@vDate		varchar(50),
	@GoodsOrder	int = '0'
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @MaxGoodsOrderId	int

--新增
IF @nType = 'A'
	BEGIN
		--判断是否存在相同的记录
		IF EXISTS(SELECT TOP 1 1 FROM iniGoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId AND Price = @Price AND GoodsNumber = @gNumber AND ProduceDate = @pDate AND ValidDate = @vDate)
			BEGIN			
				UPDATE	iniGoodsStocks
				SET 	Qty 	= Qty + @Qty,
						Total	= Total + @Total
				WHERE	PTypeId = @PTypeId 
						AND KTypeId = @KTypeId 
						AND Price = @Price 
						AND GoodsNumber = @gNumber 
						AND ProduceDate = @pDate 
						AND ValidDate = @vDate

				IF @@ROWCOUNT = 0
					RETURN -1
			END
		ELSE
			BEGIN
				SELECT	@MaxGoodsOrderId = ISNULL(MAX(GoodsOrder),0)+1 FROM iniGoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId
				
				INSERT INTO iniGoodsStocks
				(
					PTypeId,
					KTypeId,
					Qty,
					Price,
					Total,
					GoodsOrder,
					GoodsNumber,
					ProduceDate,
					ValidDate
				)VALUES(
					@PTypeId,
					@KTypeId,
					@Qty,
					@Price,
					@Total,
					@MaxGoodsOrderId,
					@gNumber,
					CONVERT(varchar(10),@pDate,120),
					CONVERT(varchar(10),@vDate,120)
				)

				IF @@ROWCOUNT = 0
					RETURN -2
			END
		RETURN 0
	END
ELSE IF @nType = 'M'
	BEGIN
		--判断是否存在相同的记录
		IF EXISTS(SELECT TOP 1 1 FROM iniGoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId AND Price = @Price AND GoodsNumber = @gNumber AND ProduceDate = @pDate AND ValidDate = @vDate AND GoodsOrder <> @GoodsOrder)
			BEGIN
				--删除当前记录
				DELETE FROM iniGoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId AND GoodsOrder = @GoodsOrder

				--重新整理GoodsOrder
				UPDATE	iniGoodsStocks
				SET		GoodsOrder = GoodsOrder - 1
				WHERE	PTypeId = @PTypeId 
						AND KTypeId = @KTypeId 
						AND GoodsOrder>@GoodsOrder
			
				--累计金额
				UPDATE	iniGoodsStocks
				SET 	Qty 	= Qty + @Qty,
						Total	= Total + @Total
				WHERE	PTypeId = @PTypeId 
						AND KTypeId = @KTypeId 
						AND Price = @Price 
						AND GoodsNumber = @gNumber 
						AND ProduceDate = @pDate 
						AND ValidDate = @vDate

				IF @@ROWCOUNT = 0
					RETURN -1
			END
		ELSE
			BEGIN
				--修改数据
				UPDATE	iniGoodsStocks
				SET 	Qty 		= @Qty,
						Price   	= @Price,
						Total		= @Total,
						GoodsNumber = @gNumber, 
						ProduceDate = CONVERT(varchar(10),@pDate,120),
						ValidDate 	= CONVERT(varchar(10),@vDate,120)
				WHERE	PTypeId = @PTypeId 
						AND KTypeId = @KTypeId 
						AND GoodsOrder = @GoodsOrder

				IF @@ROWCOUNT = 0
					RETURN -2
			END
		RETURN 0
	END
ELSE
	BEGIN
		DELETE FROM iniGoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId AND GoodsOrder = @GoodsOrder

		IF @@ROWCOUNT = 0
			RETURN -1

		--重新整理GoodsOrder
		UPDATE	iniGoodsStocks
		SET		GoodsOrder = GoodsOrder - 1
		WHERE	PTypeId = @PTypeId 
				AND KTypeId = @KTypeId 
				AND GoodsOrder>@GoodsOrder

		RETURN 0
	END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2005-6-14
	描述：新增、修改价格跟踪信息
*/
CREATE  PROCEDURE Gp_DealPriceTrackInfo
(
	@OperatorId		varchar(100),		--操作员ID
	@BTypeId		varchar(100),		--往来单位ID
	@PTypeId		varchar(100),		--商品ID
	@STypeId		varchar(max),		--分支机构
	@Price			 NUMERIC(24, 10) ,		--价格信息
	@nType			int,				--价格类型  0.销售订单  1.销售出库单  2.采购订单  3.采购入库单 4.报价单  5.询价单 6.发出商品出库单 7.暂估入库单
	@SBTypeId		varchar(100),		--待修改的往来单位ID
	@SPTypeId		varchar(100),		--待修改的商品ID
	@cid			INT,
	@uid			INT,
	@scid			INT,
	@suid			INT,
	--@btypeflag		VARCHAR(20),			--0结算单位，1往来单位
	@discountrate	 NUMERIC(24, 10) ,
	@discountprice	 NUMERIC(24, 10) ,
	@tax			 NUMERIC(24, 10),
	@taxprice		 NUMERIC(24, 10)	
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT * FROM Userconfig WHERE ConfigName='doubleunit' AND Value='1')
BEGIN
	SELECT @uid=baseUnitId FROM ptype WHERE typeId = @PTypeId
END

IF NOT EXISTS(SELECT TOP 1 * FROM BType WHERE TypeId = @BTypeId AND SonNum = 0)
	BEGIN
		--RAISERROR('选择了往来单位的父节点，不能写入！',16,1)
		RETURN -5
	END

IF NOT EXISTS(SELECT TOP 1 * FROM PType WHERE TypeId = @PTypeId AND SonNum = 0)
	BEGIN
		--RAISERROR('选择了商品的父节点，不能写入！',16,1)
		RETURN -6
	END
	
	
	DECLARE @TrackTime DATETIME 
	
	SELECT @TrackTime= GETDATE()
	
--获取跟踪类型：往来单位/结算单位   0 结算单位 1往来单位
DECLARE @btypeflag INT
IF(@nType = 0 OR @nType = 1 OR @nType = 4 OR @nType = 6)
	SELECT @BtypeFlag = Value FROM PriceTrackConfig WHERE Name = 'SaleBtypeFlag'
ELSE IF(@nType = 2 OR @nType = 3 OR @nType = 5 OR @nType = 7)
	SELECT @btypeflag = Value FROM PriceTrackConfig WHERE Name = 'BuyBtypeFlag'

IF(@btypeflag = -1)
	SET @btypeflag = 0

IF @SBTypeId<>'' AND @SPTypeId<>'' 	--修改往来单位的物价信息
	BEGIN
		--如果待修改的记录在表中已经存在，则不允许修改
		IF NOT (@SBTypeId=@BTypeId AND @SPTypeID=@PTypeId AND @scid = @cid AND @suid = @uid)
			BEGIN
				IF(@nType = 0)
				BEGIN
					IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_SaleOrder WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
						RETURN -7
				END
				ELSE IF(@nType = 1)
				BEGIN
					IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Sale WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
						RETURN -7
				END
				ELSE IF(@nType = 2)
				BEGIN
					IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_BuyOrder WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
						RETURN -7
				END
				ELSE IF(@nType = 3)
				BEGIN
					IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Buy WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
						RETURN -7
				END
				ELSE IF(@nType = 4)
				BEGIN
					IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Quote WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
						RETURN -7
				END
				ELSE IF(@nType = 5)
				BEGIN
					IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_AskPrice WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
						RETURN -7
				END
				ELSE IF(@nType = 6)
				BEGIN
					IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Send WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
						RETURN -7
				END
				ELSE IF(@nType = 7)
				BEGIN
					IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Appraisal WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
						RETURN -7
				END
			END

		IF @nType = 0
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_SaleOrder WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
				BEGIN
					UPDATE PriceTrack_SaleOrder SET Price = @Price 
					,DiscountRate = @discountrate
					,DiscountPrice = @discountprice ,
					 Tax=@tax,
					 TaxPrice=@taxprice,
					 TrackTime=@TrackTime
					WHERE BTypeId = @BTypeId AND PTypeId = @PTypeId AND STypeID = @STypeId  AND cid = @cid AND UID = @uid  AND  BTypeFlag = @btypeflag
				END
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_SaleOrder WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag)
							UPDATE PriceTrack_SaleOrder SET Price = @Price,BTypeId = @BTypeId,PTypeId = @PTypeId,UID=@uid,CID=@cid 
							,DiscountRate = @discountrate
							,DiscountPrice = @discountprice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
					        TrackTime=@TrackTime
							WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid  AND  BTypeFlag = @btypeflag
						ELSE
							INSERT PriceTrack_SaleOrder(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime) VALUES(@BTypeId,@PTypeId,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
					END

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('修改销售订单价格信息失败！',16,1)
						RETURN -1
					END
			END

		IF @nType = 1
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Sale WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND CID = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
					UPDATE PriceTrack_Sale SET Price = @Price  
					,DiscountRate = @discountrate
					,DiscountPrice = @discountprice
					,Tax=@tax
					,TaxPrice=@taxprice ,
					TrackTime=@TrackTime
					WHERE BTypeId = @BTypeId AND PTypeId = @PTypeId AND STypeID = @STypeId AND cid=@cid AND uid=@uid AND  BTypeFlag = @btypeflag
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Sale WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag)
							UPDATE PriceTrack_Sale SET Price = @Price,BTypeId = @BTypeId,PTypeId = @PTypeId  
							,DiscountRate = @discountrate
							,DiscountPrice = @discountprice
							,Tax=@tax
					        ,TaxPrice=@taxprice ,
					        TrackTime=@TrackTime
							WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag
						ELSE
							INSERT PriceTrack_Sale(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime) VALUES(@BTypeId,@PTypeId,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
					END

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('修改销售出库单价格信息失败！',16,1)
						RETURN -1
					END
			END

		IF @nType = 2
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_BuyOrder WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND CID = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
					UPDATE PriceTrack_BuyOrder SET Price = @Price 
					,DiscountRate = @discountrate
					,DiscountPrice = @discountprice
					,Tax=@tax
					,TaxPrice=@taxprice ,
					TrackTime=@TrackTime
					WHERE BTypeId = @BTypeId AND PTypeId = @PTypeId AND STypeID = @STypeId AND cid=@cid AND uid=@uid  AND  BTypeFlag = @btypeflag
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_BuyOrder WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag)
							UPDATE PriceTrack_BuyOrder SET Price = @Price,BTypeId = @BTypeId,PTypeId = @PTypeId 
							,DiscountRate = @discountrate
							,DiscountPrice = @discountprice
							,Tax=@tax
					        ,TaxPrice=@taxprice ,
					        TrackTime=@TrackTime
							WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid  AND  BTypeFlag = @btypeflag
						ELSE
							INSERT PriceTrack_BuyOrder(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime) VALUES(@BTypeId,@PTypeId,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
					END

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('修改销售出库单价格信息失败！',16,1)
						RETURN -1
					END
			END

		IF @nType = 3
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Buy WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND CID = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
					UPDATE PriceTrack_Buy SET Price = @Price 
					,DiscountRate = @discountrate
					,DiscountPrice = @discountprice ,
					Tax=@tax,
					TaxPrice=@taxprice,
					TrackTime=@TrackTime
					WHERE BTypeId = @BTypeId AND PTypeId = @PTypeId AND STypeID = @STypeId AND cid=@cid AND uid=@uid AND BTypeFlag=@btypeflag
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Buy WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag)
							UPDATE PriceTrack_Buy SET Price = @Price,BTypeId = @BTypeId,PTypeId = @PTypeId  
							,DiscountRate = @discountrate
							,DiscountPrice = @discountprice
							,Tax=@tax
					        ,TaxPrice=@taxprice ,
							TrackTime=@TrackTime
							WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid  AND  BTypeFlag = @btypeflag
						ELSE
							INSERT PriceTrack_Buy(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime) VALUES(@BTypeId,@PTypeId,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
					END

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('修改销售出库单价格信息失败！',16,1)
						RETURN -1
					END
			END
		IF @nType = 4
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Quote WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND CID = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
					UPDATE PriceTrack_Quote SET Price = @Price  
					,DiscountRate = @discountrate
					,DiscountPrice = @discountprice ,
					tax=@tax,
					TaxPrice=@taxprice,
					TrackTime=@TrackTime
					WHERE BTypeId = @BTypeId AND PTypeId = @PTypeId AND STypeID = @STypeId AND cid=@cid AND uid=@uid AND  BTypeFlag = @btypeflag
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Quote WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag)
							UPDATE PriceTrack_Quote SET Price = @Price,BTypeId = @BTypeId,PTypeId = @PTypeId 
							,DiscountRate = @discountrate
							,DiscountPrice = @discountprice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							 TrackTime=@TrackTime
							WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag
						ELSE
							INSERT PriceTrack_Quote(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime) VALUES(@BTypeId,@PTypeId,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
					END

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('修改销售出库单价格信息失败！',16,1)
						RETURN -1
					END
			END
		IF @nType = 5
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_AskPrice WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND CID = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
					UPDATE PriceTrack_AskPrice SET Price = @Price  
					,DiscountRate = @discountrate
					,DiscountPrice = @discountprice ,
					tax=@tax,
					TaxPrice=@taxprice,
					TrackTime=@TrackTime
					WHERE BTypeId = @BTypeId AND PTypeId = @PTypeId AND STypeID = @STypeId AND cid=@cid AND uid=@uid AND  BTypeFlag = @btypeflag
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_AskPrice WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag)
							UPDATE PriceTrack_AskPrice SET Price = @Price,BTypeId = @BTypeId,PTypeId = @PTypeId  
							,DiscountRate = @discountrate
							,DiscountPrice = @discountprice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid  AND  BTypeFlag = @btypeflag
						ELSE
							INSERT PriceTrack_AskPrice(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime) VALUES(@BTypeId,@PTypeId,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
					END

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('修改销售出库单价格信息失败！',16,1)
						RETURN -1
					END
			END
		IF @nType = 6
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Send WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND CID = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
					UPDATE PriceTrack_Send SET Price = @Price  
					,DiscountRate = @discountrate
					,DiscountPrice = @discountprice ,
					Tax=@tax,
					TaxPrice=@taxprice,
					TrackTime=@TrackTime
					WHERE BTypeId = @BTypeId AND PTypeId = @PTypeId AND STypeID = @STypeId AND cid=@cid AND uid=@uid AND  BTypeFlag = @btypeflag
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Send WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag)
							UPDATE PriceTrack_Send SET Price = @Price,BTypeId = @BTypeId,PTypeId = @PTypeId  
							,DiscountRate = @discountrate
							,DiscountPrice = @discountprice
							,Tax=@tax
					        ,TaxPrice=@taxprice ,
							TrackTime=@TrackTime
							WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid  AND  BTypeFlag = @btypeflag
						ELSE
							INSERT PriceTrack_Send(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime) VALUES(@BTypeId,@PTypeId,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
					END

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('修改销售出库单价格信息失败！',16,1)
						RETURN -1
					END
			END
		IF @nType = 7
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Appraisal WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND CID = @cid AND UID = @uid AND  BTypeFlag = @btypeflag)
					UPDATE PriceTrack_Appraisal SET Price = @Price  
					,DiscountRate = @discountrate
					,DiscountPrice = @discountprice ,
					tax=@tax,
					TaxPrice=@taxprice,
					TrackTime=@TrackTime
					WHERE BTypeId = @BTypeId AND PTypeId = @PTypeId AND STypeID = @STypeId AND cid=@cid AND uid=@uid AND  BTypeFlag = @btypeflag
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Appraisal WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid AND  BTypeFlag = @btypeflag)
							UPDATE PriceTrack_Appraisal SET Price = @Price,BTypeId = @BTypeId,PTypeId = @PTypeId  
							,DiscountRate = @discountrate
							,DiscountPrice = @discountprice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @SPTypeId AND BTypeId = @SBTypeId AND STypeID = @STypeId AND cid = @scid AND uid = @suid  AND  BTypeFlag = @btypeflag
						ELSE
							INSERT PriceTrack_Appraisal(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime) VALUES(@BTypeId,@PTypeId,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
					END

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('修改销售出库单价格信息失败！',16,1)
						RETURN -1
					END
			END
	END
ELSE
	BEGIN
		IF @nType = 0
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_SaleOrder WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag)
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_SaleOrder WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND ISNULL(Price,0)<>0 AND  BTypeFlag = @btypeflag)
							RETURN -7
						ELSE
							UPDATE PriceTrack_SaleOrder SET Price = @Price
							,DiscountRate=@discountrate
							,DiscountPrice=@DiscountPrice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid  AND  BTypeFlag = @btypeflag
					END
				ELSE
					INSERT INTO PriceTrack_SaleOrder(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime)VALUES(@BTypeId,@PTypeID,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
		
				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('新增或修改销售订单价格信息失败！',16,1)
						RETURN -1
					END
			END
		
		IF @nType = 1
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Sale WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag)
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Sale WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND ISNULL(Price,0)<>0 AND  BTypeFlag = @btypeflag)
							RETURN -7
						ELSE
							UPDATE PriceTrack_Sale SET Price = @Price  
							,DiscountRate=@discountrate
							,DiscountPrice=@DiscountPrice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid  AND  BTypeFlag = @btypeflag
					END
				ELSE
					INSERT INTO PriceTrack_Sale(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime)VALUES(@BTypeId,@PTypeID,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
		
				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('新增或修改销售出库单价格信息失败！',16,1)
						RETURN -2
					END
			END
		
		IF @nType = 2
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_BuyOrder WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag)
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_BuyOrder WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND ISNULL(Price,0)<>0 AND  BTypeFlag = @btypeflag)
							RETURN -7
						ELSE
							UPDATE PriceTrack_BuyOrder SET Price = @Price
							,DiscountRate=@discountrate
							,DiscountPrice=@DiscountPrice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid  AND  BTypeFlag = @btypeflag 
					END
				ELSE
					INSERT INTO PriceTrack_BuyOrder(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime)VALUES(@BTypeId,@PTypeID,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
		
				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('新增或修改采购订单价格信息失败！',16,1)
						RETURN -3
					END
			END
		
		IF @nType = 3
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Buy WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag)
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Buy WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND ISNULL(Price,0)<>0 AND  BTypeFlag = @btypeflag)
							RETURN -7
						ELSE
							UPDATE PriceTrack_Buy SET Price = @Price 
							,DiscountRate=@discountrate
							,DiscountPrice=@DiscountPrice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag
					END
				ELSE
					INSERT INTO PriceTrack_Buy(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime)VALUES(@BTypeId,@PTypeID,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
		
				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('新增或修改采购入库单价格信息失败！',16,1)
						RETURN -4
					END
			END
		IF @nType = 4
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Quote WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag)
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Quote WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND ISNULL(Price,0)<>0 AND  BTypeFlag = @btypeflag)
							RETURN -7
						ELSE
							UPDATE PriceTrack_Quote SET Price = @Price  
							,DiscountRate=@discountrate
							,DiscountPrice=@DiscountPrice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag
					END
				ELSE
					INSERT INTO PriceTrack_Quote(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime)VALUES(@BTypeId,@PTypeID,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
		
				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('新增或修改报价价格信息失败！',16,1)
						RETURN -5
					END
			END
		IF @nType = 5
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_AskPrice WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag)
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_AskPrice WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND ISNULL(Price,0)<>0 AND  BTypeFlag = @btypeflag)
							RETURN -7
						ELSE
							UPDATE PriceTrack_AskPrice SET Price = @Price  
							,DiscountRate=@discountrate
							,DiscountPrice=@DiscountPrice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag
					END
				ELSE
					INSERT INTO PriceTrack_AskPrice(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime)VALUES(@BTypeId,@PTypeID,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
		
				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('新增或修改询价价格信息失败！',16,1)
						RETURN -6
					END
			END
		IF @nType = 6
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Send WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag)
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Send WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND ISNULL(Price,0)<>0 AND  BTypeFlag = @btypeflag)
							RETURN -7
						ELSE
							UPDATE PriceTrack_Send SET Price = @Price  
							,DiscountRate=@discountrate
							,DiscountPrice=@DiscountPrice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag
					END
				ELSE
					INSERT INTO PriceTrack_Send(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime)VALUES(@BTypeId,@PTypeID,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
		
				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('新增或修改询价价格信息失败！',16,1)
						RETURN -6
					END
			END
		IF @nType = 7
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Appraisal WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag)
					BEGIN
						IF EXISTS(SELECT TOP 1 * FROM  PriceTrack_Appraisal WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND ISNULL(Price,0)<>0 AND  BTypeFlag = @btypeflag)
							RETURN -7
						ELSE
							UPDATE PriceTrack_Appraisal SET Price = @Price  
							,DiscountRate=@discountrate
							,DiscountPrice=@DiscountPrice 
							,Tax=@tax
					        ,TaxPrice=@taxprice,
							TrackTime=@TrackTime
							WHERE PTypeId = @PTypeId AND BTypeId = @BTypeId AND STypeID = @STypeId AND UID=@uid AND CID=@cid AND  BTypeFlag = @btypeflag
					END
				ELSE
					INSERT INTO PriceTrack_Appraisal(BTypeId,PTypeId,Price,STypeID,BTypeFlag,CID,UID,DiscountRate,DiscountPrice,tax,TaxPrice,TrackTime)VALUES(@BTypeId,@PTypeID,@Price,@STypeId,@btypeflag,@cid,@uid,@discountrate,@discountprice,@tax,@taxprice,@TrackTime)
		
				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('新增或修改询价价格信息失败！',16,1)
						RETURN -6
					END
			END
	END

	IF(@nType = 0)
		DELETE FROM   PriceTrack_SaleOrder WHERE Price<=0 OR DiscountPrice<=0 
	ELSE IF(@nType = 1)
		DELETE FROM   PriceTrack_Sale WHERE Price<=0 OR DiscountPrice<=0
	ELSE IF(@nType = 2)
		DELETE FROM   PriceTrack_BuyOrder WHERE Price<=0 OR DiscountPrice<=0
	ELSE IF(@nType = 3)
		DELETE FROM   PriceTrack_Buy WHERE Price<=0 OR DiscountPrice<=0
	ELSE IF(@nType = 4)
		DELETE FROM   PriceTrack_Quote WHERE Price<=0 OR DiscountPrice<=0
	ELSE IF(@nType = 5)
		DELETE FROM   PriceTrack_AskPrice WHERE Price<=0 OR DiscountPrice<=0
	ELSE IF(@nType = 6)
		DELETE FROM   PriceTrack_Send WHERE Price<=0 OR DiscountPrice<=0
	ELSE IF(@nType = 7)
		DELETE FROM   PriceTrack_Appraisal WHERE Price<=0 OR DiscountPrice<=0

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





/*
	作者：谢吉康
	日期：2009-06-10
	描述：促销价格的处理
*/
CREATE PROCEDURE Gp_DealPromotePrice
(
	@nid		varchar(20),
	@btypeid	varchar(200),
	@ptypeid	varchar(200),
	@etypeid	varchar(200),
	@ktypeid	varchar(200),
	@price		varchar(200),
	@startdate	varchar(20),
	@enddate	varchar(20),
	@unitsid	int
)
--@encode$--
AS
SET NOCOUNT ON

IF @nid = 0	--新增
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM PromotePrice WHERE Ptypeid = @ptypeid and btypeid = @btypeid and etypeid = @etypeid and ktypeid = @ktypeid and enddate>=@startdate and startdate<=@enddate and unitid=@unitsid )
			RETURN -1

		INSERT INTO PromotePrice(ptypeid,startdate,enddate,promoteprice,etypeid,writedate,btypeid,ktypeid,unitid)values(@ptypeid,@startdate,@enddate,@price,@etypeid,convert(varchar(10),getdate(),120),@btypeid,@ktypeid,@unitsid)

		IF @@ROWCOUNT = 0
			RETURN -2
		ELSE
			RETURN 0
	END
ELSE		--修改
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM PromotePrice WHERE ptypeid = @ptypeid and btypeid = @btypeid and etypeid = @etypeid and ktypeid = @ktypeid and enddate>=@startdate and startdate<=@enddate and PromoteId<>@nid and unitid=@unitsid)
			RETURN -1

		UPDATE 	PromotePrice
		SET		ptypeid 	= @ptypeid,
				startdate 	= @startdate,
				enddate 	= @enddate,
				promoteprice= @price,
				etypeid 	= @etypeid,
				writedate 	= convert(varchar(10),getdate(),120),
				btypeid 	= @btypeid,
				ktypeid 	= @ktypeid,
				unitid		= @unitsid
		WHERE	promoteid 	= @nid
			

		IF @@ROWCOUNT = 0
			RETURN -2
		ELSE
			RETURN 0
	END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





/*
	作者：谢吉康
	日期：2009-06-12
	描述：商品自定义编号处理
*/
CREATE PROCEDURE Gp_DealPTypeMultiCode
(
	@pcode			varchar(600),
	@bname			varchar(600),
	@btypeid		VARCHAR(50),
	@code			varchar(200),
	@rvalue			varchar(1000) output
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @pfullname 		varchar(1000),
		--@btypeid		varchar(200),
		@ptypeid		varchar(200)

SELECT typeid FROM BType WHERE FullName = @bname AND typeId =@btypeid
IF @@ROWCOUNT = 0
	BEGIN
		SET @rvalue = '往来单位无效！'
		RETURN -3
	END

SELECT @ptypeid = typeid FROM PType WHERE UserCode = @pcode
IF @@ROWCOUNT = 0
	BEGIN
		SET @rvalue = '商品无效！'
		RETURN -4
	END

SELECT 	@pfullname=(SELECT UserCode FROM Ptype WHERE typeid = p.PtypeID) 
FROM 	PUserCode p 
WHERE 	p.BTypeId=@btypeid AND p.UserCode = @code AND p.PtypeId <> @ptypeid

IF @@ROWCOUNT<>0
	BEGIN
		SET @rvalue = @pfullname
		RETURN -1
	END

IF EXISTS(SELECT * FROM PUserCode WHERE BTypeId=@btypeid AND PTypeId=@ptypeid)
	UPDATE PUserCode SET UserCode = @code WHERE BTypeId=@btypeid AND PTypeId=@ptypeid
ELSE
	INSERT INTO PUserCode(UserCode,BTypeId,PTypeId)VALUES(@code,@btypeid,@ptypeid)

IF @@ROWCOUNT = 0
	BEGIN
		SET @rvalue = '保存失败！'
		RETURN -2
	END


SET @rvalue = '保存成功！'
RETURN 0






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
	作者：谢吉康
	日期：2009-06-03
	描述：库存上下限报警数据保存
	select * from F_BaseGetManKType('00001')
	EXEC Gp_DealStockAlermSetData	'',0,0,8,'0000100001',1
*/
CREATE PROCEDURE Gp_DealStockAlermSetData
(
	@ptypeid			varchar(max),
	@sx					NUMERIC(24, 10) ,
	@xx					NUMERIC(24, 10) ,
	@kc					NUMERIC(24, 10) ,
	@ktypeid			varchar(max),
	@type				INT=0,				--1 商品多选仓库单选,0 仓库多选商品单选	
	@operatorid			VARCHAR(50)=''		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ktype
( 
	ptypeid  VARCHAR(50),
	ktypeid  VARCHAR(50)	, 
	flag     int
)
CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(ptypeid,ktypeid)

/*
INSERT INTO #Ktype(ptypeid,ktypeid, flag )
SELECT	b.a,
		a.a,
		0 
FROM	dbo.f_split(@ktypeid,',') a,
		dbo.f_split(@ptypeid,',') b		
*/

IF @ktypeid = '00000'
BEGIN
	INSERT INTO #Ktype(ptypeid,ktypeid, flag )
	SELECT	b.a,
			a.a,
			0 
	FROM	dbo.f_split(@ktypeid,',') a,
			(SELECT typeid AS a FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@operatorid)) b
END
ELSE
BEGIN
	INSERT INTO #Ktype(ptypeid,ktypeid, flag )
	SELECT	b.a,
			a.a,
			0 
	FROM	(SELECT typeid AS a FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@operatorid)) a,
			(SELECT typeid AS a FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@operatorid)) b
END		
		

UPDATE	#Ktype 
SET		flag=1 
FROM	#Ktype 
INNER JOIN StockAlarm a ON #Ktype.ktypeid = a.KTypeId AND a.PTypeId=#Ktype.ptypeid

UPDATE	StockAlarm 
SET		UpLimitQty = @sx,
		DownLimitQty = @xx,
		OrderQty = @kc 
FROM	#Ktype  a
WHERE	a.KTypeId = STOCKALARM.KTypeId 
		AND STOCKALARM.PTypeId = a.ptypeid 
		AND flag=1
	
INSERT INTO StockAlarm(PTypeId,KTypeId,UpLimitQty,DownLimitQty,OrderQty)
SELECT	PTypeId,
		ktypeid,
		@sx,
		@xx,
		@kc 
FROM	#Ktype 
WHERE	flag=0

DELETE FROM StockAlarm WHERE UpLimitQty=0 AND DownLimitQty=0 AND OrderQty=0


RETURN 0
--END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2013-10-30
	描述：处理配置信息
*/

CREATE PROCEDURE Gp_dealSysdata
(	
	@SubValue		VARCHAR(100),	
	@SubValue1		VARCHAR(100),
	@Flag			INT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SubName	VARCHAR(100),
		@SubName1	VARCHAR(100)
		
IF @Flag = 1
BEGIN
	UPDATE sysdata SET SubValue = @SubValue WHERE SubName = 'PosDefine'
	UPDATE sysdata1 SET SubValue = @SubValue1 WHERE SubName = 'PosValid'
END
ELSE IF @Flag = 2
BEGIN
	UPDATE sysdata SET SubValue = @SubValue WHERE SubName = 'OmDefine'
	UPDATE sysdata1 SET SubValue = @SubValue1 WHERE SubName = 'OmValid'
END


RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-05-19
	描述：预留存储过程，处理其他信息从EXCEL导入
*/
CREATE PROCEDURE Gp_DealSystemOtherData
--@encode$--
AS
SET NOCOUNT ON

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO











/*
	作者:谢吉康
	日期:2007-11-21
	描述:积分设置
*/
CREATE  PROCEDURE Gp_DealVipJfSet
(
	@nType			varchar(10),
	@nID			varchar(50),
	@strTitle		varchar(100),
	@strXf			 NUMERIC(24, 10) ,
	@strJf			numeric(18,0),
	@strComment		varchar(256),
	---2012.3.27 新添加 A8-9.0----
	@strTvalue		datetime
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @maxTitle 	int,
		@ID			int,
		@i			int

SET @i = 1

IF @nType = 'A'
	BEGIN
		SELECT * FROM nVipJfSet
		
		IF @@ROWCOUNT>=8
			RETURN -99

		IF EXISTS(SELECT TOP 1 1 FROM nVipJfSet WHERE (Total = @strXf AND Jf = @strJf) OR Title = @strTitle)
			RETURN -1
		ELSE
			BEGIN
				INSERT INTO nVipJfSet
				(
					Title,
					Total,
					Jf,
					Comment,
					TimeValue
		
				)VALUES(
					@strTitle,
					@strXf,
					@strJf,
					@strComment,
					@strTvalue
				)
				IF @@ROWCOUNT = 0
					RETURN -2
				ELSE
					RETURN 0
			END
	END
ELSE IF @nType = 'M'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM nVipJfSet WHERE ((Total = @strXf AND Jf = @strJf) OR Title = @strTitle) AND ID <> @nID)
			RETURN -1
		ELSE
			BEGIN
				UPDATE nVipJfSet SET Title = @strTitle,Total = @strXf,Jf = @strJf,Comment = @strComment,TimeValue=@strTvalue WHERE ID = @nID

				IF @@ROWCOUNT = 0
					RETURN -2
				ELSE
					RETURN 0
			END
	END
ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IfQP' AND SubValue='1')
		BEGIN
			--汽配积分规则使用和v3不一样
			IF EXISTS(SELECT TOP 1 1 FROM userconfig WHERE ConfigName = 'RepairItemsIntegral' AND Value = @nID)
				RETURN -2
		END
		ELSE
		BEGIN
			--如果积分已经被使用，则不能被删除 
			IF EXISTS(SELECT TOP 1 1 FROM nVipGoodsSign WHERE JfID = @nID)
				RETURN -2
			IF EXISTS(SELECT TOP 1 1 FROM nVipCardSet WHERE jfgz = @nID)
				RETURN -2
		END
		
		
		DELETE FROM nVipJfSet WHERE ID = @nID
				
		IF @@ROWCOUNT = 0
			RETURN -1
		ELSE
		BEGIN					
			RETURN 0
		END
	END


/*
	--整理顺序
	SET @i = 1
	DECLARE DelCursor CURSOR FOR
		SELECT ID FROM nVipJfSet ORDER BY ID
	
	OPEN DelCursor
	
	FETCH NEXT FROM DelCursor INTO @ID
	
	WHILE @@FETCH_STATUS = 0
		BEGIN
			UPDATE	nVipJfSet SET Title = @i WHERE ID = @ID
			SET @i = @i + 1
			FETCH NEXT FROM DelCursor INTO @ID
		END
	
	CLOSE DelCursor
	DEALLOCATE DelCursor
*/









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DelAc_AssetsCards]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[Gp_DelAc_AssetsCards]
GO


/****** Object:  StoredPROCEDURE [dbo].[Gp_InsertAc_AssetsCards]    Script Date: 05/17/2011 20:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

----========================
----修改者：黄清
----日期：2013-05-20
----描述：固定资产卡片删除
----========================
CREATE    PROCEDURE [dbo].[Gp_DelAc_AssetsCards]
(
	@cardids		[VARCHAR](MAX),
	@etypeid		[VARCHAR](50),
	@notexists		[VARCHAR](MAX) OUT,
	@used			[VARCHAR](MAX) OUT,
	@errorstate		[VARCHAR](MAX) OUT,
	@delusercode	[VARCHAR](MAX) OUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @fullname VARCHAR(200)
DECLARE @AssetsStateName VARCHAR(50)
DECLARE @errorcardid VARCHAR(MAX)
CREATE TABLE #CardIdList (cardid VARCHAR(50),Stypeid	VARCHAR(50))
INSERT INTO #CardIdList(cardid,Stypeid) 
SELECT Id,STypeId FROM Ac_AssetsCards WHERE Id IN (SELECT A FROM f_split(@cardids,','))

SET @notexists=''
SET @used=''
SET @errorstate=''
SET @delusercode=''

--去掉不存在的
SELECT @notexists=@notexists+'【'+(SELECT UserCode FROM Ac_AssetsCards WHERE Id=cardid)+'】' FROM #CardIdList WHERE cardid NOT IN (SELECT Id FROM Ac_AssetsCards)
DELETE FROM #CardIdList WHERE cardid NOT IN (SELECT Id FROM Ac_AssetsCards)

--去掉被增加单调用的
SELECT @used=@used+'【'+UserCode+'】' 
FROM Ac_AssetsCards 
WHERE Id IN (SELECT cardid FROM #CardIdList) 
AND Id IN (SELECT AssetCardId FROM AssetIncDecBill)
AND STypeId IN (SELECT TypeId FROM SType WHERE IfAssetsIni=1)
DELETE FROM #CardIdList WHERE cardid IN (SELECT AssetCardId FROM AssetIncDecBill) AND STypeId IN (SELECT TypeId FROM SType WHERE IfAssetsIni=1)

--去掉状态不正确的
SELECT @errorstate=@errorstate+'【'+UserCode+'】' 
FROM Ac_AssetsCards 
WHERE Id IN (SELECT cardid FROM #CardIdList) AND AssetsState IN (3,4)
		AND STypeId IN (SELECT TypeId FROM SType WHERE IfAssetsIni=1)
DELETE FROM #CardIdList WHERE cardid IN (SELECT Id FROM Ac_AssetsCards WHERE AssetsState IN (3,4)) AND STypeId IN (SELECT TypeId FROM SType WHERE IfAssetsIni=1)

SELECT @errorstate=@errorstate+'【'+UserCode+'】' 
FROM Ac_AssetsCards 
WHERE Id IN (SELECT cardid FROM #CardIdList) AND AssetsState=5
DELETE FROM #CardIdList WHERE cardid IN (SELECT Id FROM Ac_AssetsCards WHERE AssetsState=5)

SELECT @delusercode=@delusercode+'【'+UserCode+'】' FROM Ac_AssetsCards WHERE Id IN (SELECT cardid FROM #CardIdList)
DELETE FROM Ac_AssetsCards WHERE Id IN (SELECT cardid FROM #CardIdList)
DELETE FROM Ac_SubsidiaryEquipment WHERE CardId IN (SELECT cardid FROM #CardIdList)

--删除卡片时删除历史及折旧计划
DELETE FROM Ac_AssetsCards_History WHERE AssertsCardId IN (SELECT cardid FROM #CardIdList)
DELETE FROM Ac_DepreciationPlan WHERE AssetCardId IN (SELECT cardid FROM #CardIdList)

GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








-- 陈启华 2006-05-15
-- 删除单据编号自定义


CREATE      PROCEDURE GP_DelAllCodeSet

--@encode$--

AS
SET NOCOUNT ON 

-- 删除单据编号自定义

TRUNCATE TABLE CodeConfig

RETURN 1








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-09-02
	描述：删除考勤数据
*/

CREATE PROCEDURE Gp_DelAttendanceTime 
(
	@month			VARCHAR(max),	--删除的月份
	@stypeid		varchar(max)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

DELETE FROM ManualRegist
WHERE AttendanceTimeId in (select id from AttendanceTime
						   where etypeid in (
												SELECT E.typeId FROM employee E 
												INNER JOIN SType S ON E.STypeID=S.TypeId
												WHERE S.TypeId=@stypeid
											)
							AND DATE LIKE @month+'%'
							)

DELETE FROM AttendanceTime
WHERE	etypeid in (
					SELECT E.typeId FROM employee E 
					INNER JOIN SType S ON E.STypeID=S.TypeId
					WHERE S.TypeId=@stypeid
					)
		AND DATE LIKE @month+'%'

IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('删除失败！',16,1)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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













-- ========================================================================
-- 功能说明：		重新按单结算
-- 最后修改作者：  cqhua
-- 最后修改时间：	2005-07-29
-- 添加对草稿所对应的按单结算物流单据进行删除
-- ========================================================================
CREATE                PROCEDURE [GP_DelayAlertSave]
(
@intBillNumberID int,
@chvDelayType 	 char(10),
@chvDelayValue 	 varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @ReachDate datetime
DECLARE @CurDate   Varchar(200)

--SET @CurDate =Year(getdate())+'-'+Month(getdate())+'-'+Day(getdate())
SET @CurDate =Convert(char(4),Year(getdate()))+'-'+ltrim(Rtrim(convert(char(2),Month(getdate()))))+'-'+ltrim(rtrim(Convert(char(2),Day(getdate()))))

IF EXISTS (SELECT BillnumberID FROM OrderIndex WHERE BillnumberID =@intBillNumberID)
	SELECT @ReachDate=ReachDate FROM OrderIndex WHERE BillnumberID =@intBillNumberID

/*--  当前日期+延期天数不能小于交货日期
IF @chvDelayType='1'
BEGIN
	IF dateadd(day,Convert(int,@chvDelayValue),Convert(datetime,@CurDate))<@ReachDate
	RETURN 1
END 
*/
--  延期日期不能小于交货日期
IF @chvDelayType='2'
BEGIN
	IF convert(Datetime,@chvDelayValue)<@ReachDate
		RETURN 2
END
--SELECT * FROM orderindex 
UPDATE Orderindex Set CanAlert='1' WHERE BillnumberID=@intBillNumberID
Update Orderindex Set DelayType=@chvDelayType ,DelayValue=@chvDelayValue WHERE BillnumberID=@intBillNumberID


RETURN 0











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_DelBeginningBill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_DelBeginningBill]
GO




/*
	作者：俞俊杰
	日期：2012-07-09
	描述：删除期初单据
*/
CREATE    PROCEDURE GP_DelBeginningBill
    (
      @nBillIds VARCHAR(8000)
    )
--@encode$--
AS 
    SET NOCOUNT ON
    BEGIN TRANSACTION DEL

    DELETE  FROM BillIndex
    WHERE   billnumberid IN ( SELECT    *
                              FROM      DBO.f_split(@nBillIds, ',') )
	
    IF @@ERROR <> 0 
        BEGIN
            ROLLBACK TRANSACTION DEL
            RAISERROR ( '删除失败！', 16, 1 )
        END

    COMMIT TRANSACTION DEL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_DelBillIndexAutoDraft]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_DelBillIndexAutoDraft]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE Gp_DelBillIndexAutoDraft
(
	@billguid			VARCHAR(100)		--单据的billguid
)
AS
SET NOCOUNT ON

--删除品牌多账户
DELETE FROM dbo.BillMulBrandAutoDraft WHERE BillGuid = @billguid

--删除多账户
DELETE FROM dbo.BillMulAccountAutoDraft WHERE BillGuid = @billguid

--删除采购明细
DELETE FROM dbo.BuyBillAutoDraft WHERE BillGuid = @billguid

--删除销售明细
DELETE FROM dbo.SaleBillAutoDraft WHERE BillGuid = @billguid

--删除自定义明细
DELETE FROM dbo.Custom_BillDetailsAutoDraft WHERE BillGuid = @billguid

--删除优惠券使用信息
DELETE FROM Coupon_BillUsedAutoDraft WHERE BillGuid = @billguid

--删除自定义主表
DELETE FROM dbo.Custom_BillIndexAutoDraft WHERE BillGuid = @billguid

--删除主表数据
DELETE FROM dbo.BillIndexAutoDraft WHERE BillGuid = @billguid

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








-- 陈启华 2006-05-15
-- 删除单据编号自定义


CREATE      PROCEDURE GP_DelCodeSet
(
	@Billtype			INT
)
--@encode$--

AS
SET NOCOUNT ON 

-- 删除单据编号自定义

DELETE FROM CodeConfig WHERE Billtype = @Billtype

RETURN 1








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DelCouponAllotBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DelCouponAllotBill
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	删除调拨单信息
-- 时间：	2017-11-20
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_DelCouponAllotBill
(
	@BillNumberId	NUMERIC(10,0),--单据ID
	@OperatorId		VARCHAR(200)--当前操作员
)

WITH ENCRYPTION
AS
SET NOCOUNT ON 

--不允许删除过账调拨单
IF EXISTS(SELECT TOP 1 1FROM Coupon_BillIndex WHERE IfCheck='t' AND BillNumberId=@BillNumberId)
	RETURN -1
	

DECLARE @Error INT=0
BEGIN TRAN

--删除调拨明细表
DELETE FROM Coupon_AllotBill WHERE BillNumberId=@BillNumberId
SET @Error+=@@ERROR

--删除调拨主表
DELETE FROM Coupon_BillIndex WHERE BillNumberId=@BillNumberId
SET @Error+=@@ERROR

IF(@Error=0)
	BEGIN
		COMMIT TRAN 
	END
ELSE 
	BEGIN
		ROLLBACK TRAN
	END
 
RETURN @Error
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





/*
	作者：谢吉康
	日期：2009-06-08
	描述：删除序列号
*/
CREATE PROCEDURE Gp_DelCruSerial
(
	@serial		varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @KTypeId	varchar(200),
		@PTypeId	varchar(200),
		@State		varchar(20),
		@Qty		 NUMERIC(24, 10) ,
		@sQty		 NUMERIC(24, 10) 

SELECT @KTypeId = KTypeId,@PTypeId = PTypeId,@State = State FROM Gp_CruPTypeSerial WHERE Serial = @Serial

--序列号严密管理
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'mngSerial' AND Value = 1)
	BEGIN
		IF @State IN (1,7)
			BEGIN
				SELECT @Qty = SUM(Qty) FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId
				SELECT @sQty = COUNT(*) FROM Gp_CruPTypeSerial WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId AND State IN (1,7)

				IF @sQty>@Qty
					DELETE FROM Gp_CruPTypeSerial WHERE Serial = @Serial
				ELSE
					RETURN -2
			END
		ELSE IF @State IN (25)
			BEGIN
				SELECT @Qty = SUM(Qty) FROM Wx_GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId
				SELECT @sQty = COUNT(*) FROM Gp_CruPTypeSerial WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId AND State IN (25)

				IF @sQty>@Qty
					DELETE FROM Gp_CruPTypeSerial WHERE Serial = @Serial
				ELSE
					RETURN -3
			END
		ELSE
			RETURN -1
	END
ELSE
	BEGIN
		DELETE FROM Gp_CruPTypeSerial WHERE Serial = @Serial
	END

RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_DeleteAcAccount]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_DeleteAcAccount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/31
	Description	:	删除科目
*/

CREATE PROCEDURE GP_DeleteAcAccount
(
 @AcTypeId VARCHAR(50),
 @StypeId VARCHAR(50)
)
--@encode$--
AS 
SET NOCOUNT ON

IF EXISTS (SELECT TOP 1 1 FROM Ac_Account WHERE StypeId >'00000' AND typeid =@actypeid)
BEGIN
	RAISERROR('该科目已经分发，删除失败。',16,1);
	RETURN -1;
END

IF EXISTS (SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@StypeId AND ParId like @AcTypeId + '%')
BEGIN
	RAISERROR('该科目存在下级科目，删除失败。',16,1);
	RETURN -1;
END

DECLARE @ThisXiWaNo INT ;
SELECT @ThisXiWaNo = ISNULL(MAX(XiWaMaxNumber),0)+1 FROM Ac_Account 


DECLARE @parid VARCHAR(50);
--先保存其父节点的typeid，以便后面更新数据
SELECT @parid = parid FROM Ac_Account
WHERE   StypeId = @StypeId
        AND TypeId = @AcTypeId ;
        
IF @parid IS NULL 
    BEGIN
        RAISERROR ('指定的科目不存在', 16, 1) ;
        RETURN -1 ;
    END

--删除选择节点和其子节点
DELETE  FROM [Ac_Account]
WHERE   StypeId = @StypeId
        AND TypeId = @AcTypeId ;
		
--操作失败，返回
IF @@ROWCOUNT = 0 
    RETURN -1 ;

UPDATE  Ac_Account
SET     SonNum = (SELECT  COUNT(1)
FROM    Ac_Account
WHERE   ParId = @parid
        AND StypeId = @StypeId),
        XiWaMaxNumber = @ThisXiWaNo
WHERE   typeid = @parid
        AND StypeId = @StypeId ;

RETURN 0 ;

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_DeleteAcCount]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_DeleteAcCount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	俞俊杰
	Date	:	2012/05/03
	Description	: 删除会计科目
*/
CREATE PROCEDURE GP_DeleteAcCount
(
 @TypeId VARCHAR(500), --科目ID
 @STypeId VARCHAR(500)
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @SonCount INT,				--子节点数量
    @intRowCount INT,			--是否存在使用过该科目
    @sql NVARCHAR(MAX),			--SQL语句
    @TableName VARCHAR(500),	--TABLE的名字
    @ColumnsNameA VARCHAR(500),	--列名
    @ColumnsNameS VARCHAR(500),	--列名
    @Parid VARCHAR(500),		--父节点ID
    @tableCount INT,
    @tableSet INT				


---查询父节点ID
SELECT  @Parid = ParId
FROM    Ac_Account
WHERE   TypeId = @TypeId
        AND StypeId = @STypeId
---查询是否有子节点

IF EXISTS ( SELECT  1
            FROM    Ac_Account
            WHERE   ParId = @TypeId
                    AND StypeId = @STypeId ) 
    BEGIN
        RAISERROR ( '该科目存在下级科目，删除失败！', 15, 1 ) ;
        RETURN -1 ;
    END
---查询该科目是否有数据

--账务期初
IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount WHERE STypeId=@stypeid AND ATypeId=@TypeId AND (iniYTotal<>0 OR iniYTotalFor<>0 OR IniYqty<>0 OR FDebit<>0 OR FDebitFor<>0 OR FDebitqty<>0 OR FCredit<>0 OR FCreditFor<>0 OR FCreditqty<>0 OR iniTotal<>0 OR iniTotalFor<>0 OR iniqty<>0 OR FYTotal<>0 OR FYTotalFor<>0 ))
	BEGIN
		RAISERROR ( '该科目已在账务期初中使用，删除失败！', 15, 1 ) ;
		RETURN -1
	END
	
---查询凭证是否使用
IF EXISTS ( SELECT TOP 1
                    1
            FROM    dbo.Ac_Voucher t1
            LEFT JOIN dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId
            WHERE   t1.STypeId = @STypeId
                    AND t2.ATypeId = @TypeId ) 
    BEGIN
        RAISERROR ( '该科目已在凭证中使用，删除失败！', 15, 1 ) ;
        RETURN -1
    END	
    ------------------------------9.2新加判断BEGIN--------------------------------------------
    IF EXISTS ( SELECT TOP 1 1 FROM    dbo.Ac_AssetsCards WHERE STypeId=@STypeId AND (AssertATypeId=@TypeId OR DepATypeId=@TypeId OR DisATypeId=@TypeId OR DevalueATypeId=@TypeId)) 
    BEGIN
        RAISERROR ( '该科目已在资产卡片中使用，删除失败！', 15, 1 ) ;
        RETURN -1
    END	
    IF EXISTS ( SELECT TOP 1 1 FROM    dbo.Ac_AssetsCards_History WHERE STypeId=@STypeId AND ( AssertATypeId=@TypeId OR DepATypeId=@TypeId OR DisATypeId=@TypeId OR DevalueATypeId=@TypeId)) 
    BEGIN
        RAISERROR ( '该科目已在资产卡片历史中存在，删除失败！', 15, 1 ) ;
        RETURN -1
    END	
    IF EXISTS ( SELECT TOP 1 * FROM    dbo.Ac_AssetsCategory WHERE AssertATypeId=@TypeId OR DepATypeId=@TypeId OR ExpenseATypeId=@TypeId ) 
    BEGIN
        RAISERROR ( '该科目已在资产类别中使用，删除失败！', 15, 1 ) ;
        RETURN -1
    END	
    IF EXISTS ( SELECT  1 FROM    Ac_Items_Detail  WHERE   ATypeID = @TypeId AND StypeId = @STypeId ) 
	BEGIN
		RAISERROR ( '该科目已被项目关联，删除失败！', 15, 1 )
		RETURN -1 ;
	END
	IF EXISTS (SELECT * FROM Ac_Auditing_Template_Detail D INNER JOIN Ac_Auditing_Template A ON A.AtId=D.Atid  WHERE D.ATypeId =@TypeId AND A.STypeId=@STypeId)
	BEGIN
		RAISERROR ( '该科目已被凭证模板使用，删除失败！', 15, 1 )
		RETURN -1 ;
	END
	IF EXISTS(SELECT TOP 1 1 FROM Base_InventoryTypeDetails WHERE (StockATypeID=@TypeId OR IncomeATypeID=@TypeId OR CostATypeID=@TypeId) AND StypeId = @STypeId ) 
		BEGIN
			RAISERROR ( '该科目已被存货类型关联，删除失败！', 15, 1 )
			RETURN -1 ;
		END
     ------------------------------9.2新加判断END --------------------------------------------
     
     ------------------------------9.4新加判断BEGIN--------------------------------------------

     
     
     IF EXISTS (
					SELECT 1 FROM BillIndex B 
					INNER JOIN CapitalTransfer_Bill C ON B.BillNumberId=C.BillNumberId 
					WHERE (BankAccountOut=@TypeId AND B.Stypeid=@STypeId) OR (BankAccountIn=@TypeId AND b.StypeID2=@STypeId)
				 )
     BEGIN
		RAISERROR ( '该科目已在资金调拨单中使用，删除失败！', 15, 1 )
		RETURN -1 ;
     END
     IF EXISTS (SELECT *FROM Te_BankAccount WHERE ATypeId=@TypeId AND STypeId=@STypeId AND IsDestroy=0)
     BEGIN
		RAISERROR ( '该科目已在银行账户中使用，删除失败！', 15, 1 )
		RETURN -1 ;
     END
          IF EXISTS (SELECT *FROM Te_BankAccount WHERE ATypeId=@TypeId AND STypeId=@STypeId AND IsDestroy=1 AND YearClose=1)
     BEGIN
		RAISERROR ( '该科目已在银行账户，请先删除对应的银行账户再删除此科目！', 15, 1 )
		RETURN -1 ;
     END
     ------------------------------9.4新加判断END --------------------------------------------
IF EXISTS ( SELECT TOP 1
                    1
            FROM    AC_ACCOUNT
            WHERE   StypeId = @STypeId
                    AND TypeId = @TypeId
                    AND IsDist = 1
            AND EXISTS(select TOP 1 1 from sysdata WHERE SubName='ProInfo' AND SubValue=2)) --V3没有分支机构
    BEGIN
        RAISERROR ( '从上级分支机构分配的科目不允许删除，删除失败！', 15, 1 ) ;
        RETURN -1
    END
DECLARE @ThisXiWaNo INT ;
SELECT  @ThisXiWaNo = ISNULL(MAX(XiWaMaxNumber), 0) + 1
FROM    Ac_Account 
	
	--判断是否被使用
DECLARE @Isused INT
EXEC @isUsed = GP_CheckRefUsage @stypeid = @stypeid, -- varchar(50)
    @atypeid = @typeid -- varchar(50)
IF @Isused > 0 
    BEGIN
		--IF EXISTS(select TOP 1 1 from sysdata WHERE SubName='ProInfo' AND SubValue=1))
		--	RAISERROR ( '该会计科目已经分支机构引用，删除失败！', 15, 1 ) ;
		--ELSE
			RAISERROR ( '该会计科目已经被使用，删除失败！', 15, 1 ) ;
        RETURN -1
    END 
            
---删除会计科目辅助核算
BEGIN TRAN

DELETE  FROM Ac_Account_Assist_CheckItems
WHERE   ATypeId = @TypeId
        AND StypeId = @STypeId
    ---删除会计科目
DELETE  FROM Ac_Account
WHERE   TypeId = @TypeId
        AND StypeId = @STypeId
    ---如果删除失败返回 - 1
IF @@ROWCOUNT = 0 
    BEGIN
    ROLLBACK TRANSACTION
        RETURN -1 ;
    END
---如果删除成功返回0，更新SONNUM,SONCOUNT
EXEC GP_CleanDirtyAccountData @STypeId = @stypeid, @typeid = @typeid 
    
UPDATE  Ac_Account
SET     SonNum = (SELECT    COUNT(1)
                  FROM      Ac_Account
                  WHERE     ParId = @parid
                            AND StypeId = @StypeId),
        XiWaMaxNumber = @ThisXiWaNo
WHERE   typeid = @parid
        AND StypeId = @StypeId ;
COMMIT TRAN
RETURN 0 ;
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_DeleteAccountInitailTransit]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[GP_DeleteAccountInitailTransit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--==================================================
--by:glj
--date:2016-02-17
--description:期初未达账保存
--==================================================
CREATE PROCEDURE GP_DeleteAccountInitailTransit
(
	@IndexId		INT				--ID
)
--@encode$--
AS
SET NOCOUNT ON

--检测数据有效性
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_AccountInTransit_Index WHERE Id = @IndexId)
BEGIN
	RAISERROR('未达账记录不存在',16,1)
	RETURN
END
BEGIN TRAN

DECLARE @Error	INT=0
--删除明细
DELETE FROM Te_AccountInTransit_Detail WHERE IndexId=@IndexId
SET @Error+=@@ERROR
--删除主表
DELETE FROM Te_AccountInTransit_Index WHERE Id=@IndexId
SET @Error+=@@ERROR

IF(@Error=0)
	BEGIN
		COMMIT TRAN 
		RETURN 1
	END
ELSE 
	BEGIN
		ROLLBACK TRAN 
		RETURN 0
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.05.20
	描述：未达账删除
*/
CREATE PROCEDURE GP_DeleteAccountInTransit
(
	@OperatorId			VARCHAR(50),	-- 当前操作员ID
	@RowId				INT				--明细ID
)
--@encode$--
AS
SET NOCOUNT ON

--检测数据有效性
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_AccountInTransit_Detail WHERE Id = @RowId)
BEGIN
	RAISERROR('未达账记录不存在',16,1)
	RETURN
END

--获取表头Id、该记录借贷额
DECLARE @IndexId	INT,
		@FDebit		 NUMERIC(24, 10) ,
		@FCredit	 NUMERIC(24, 10) 
		
SELECT  @IndexId = IndexId,
		@FDebit = FDebit,
		@FCredit = FCredit 
FROM dbo.Te_AccountInTransit_Detail WHERE Id = @RowId


--删除记录
DELETE FROM dbo.Te_AccountInTransit_Detail WHERE Id = @RowId

--更新表头合计借贷
UPDATE dbo.Te_AccountInTransit_Index 
	SET FDebitTotal = FDebitTotal - @FDebit,
		FCreditTotal = FCreditTotal - @FCredit
WHERE Id = @IndexId

--如果同一表头明细删除完，清除表头
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_AccountInTransit_Detail WHERE IndexId = @IndexId)
BEGIN
	DELETE FROM dbo.Te_AccountInTransit_Index WHERE id = @IndexId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_DeleteAcTable]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_DeleteAcTable]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/31
	Description	:	删除科目表
*/

CREATE PROCEDURE GP_DeleteAcTable
(
	@AcId	INT  --科目表ID
)
--@encode$--
AS 
SET NOCOUNT ON
--删除科目表信息
DECLARE @RowCount INT ;
---判断版本信息
DECLARE @IsA8 INT ;
SET @IsA8 = (SELECT TOP 1 1 from sysdata WHERE SubName='ProInfo' AND SubValue=2)

IF NOT EXISTS( SELECT 1 FROM Ac_Table WHERE AcId=@acid)
	BEGIN
		RAISERROR ('指定的科目表不存在，删除失败。', 15, 1) ;
		RETURN ;
	END
IF EXISTS( SELECT 1 FROM Ac_Table WHERE AcId=@acid AND IsUsed <> 0 AND @IsA8=1)
	BEGIN
		RAISERROR ('科目表被启用，删除失败。', 15, 1) ;
		RETURN ;
	END
IF EXISTS ( SELECT  1 FROM Ac_Account WHERE StypeId<>'00000' AND @IsA8=1 AND AcId=@AcId ) 
    BEGIN
        RAISERROR ('科目表已经分发并被使用，不能删除。', 15, 1) ;
        RETURN ;
    END

BEGIN TRANSACTION

DECLARE @Error	INT=0
--删除科目表
DELETE  FROM Ac_Table WHERE AcId = @acid ;
SET @Error+=@@ERROR
--删除科目分配表
DELETE Ac_Account WHERE StypeId = '00000' AND AcId=@AcId;
SET @Error+=@@ERROR

--修改模板使用字段                     
UPDATE Ac_Account_Set_List SET IsUse = 0  
SET @Error+=@@ERROR 

--删除固化报表公式
TRUNCATE TABLE ThreeFinancialItem_SType
SET @Error+=@@ERROR 
TRUNCATE TABLE ThreeFinancialFormula_Stype
SET @Error+=@@ERROR 
TRUNCATE TABLE ThreeFinancialItemParent_Stype
SET @Error+=@@ERROR 

--提交事务及返回值
IF(@Error=0)
	BEGIN
		COMMIT TRANSACTION ;
		RETURN 0
	END
ELSE 
	BEGIN
		ROLLBACK TRANSACTION ;
		RETURN -1
	END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DeleteAppraisalBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DeleteAppraisalBill
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊	
	日期：2014-07-24
	描述：取消【启用发票立账】后删除已红冲的暂估等单据
*/
CREATE PROCEDURE Gp_DeleteAppraisalBill
--@encode$--
AS
SET NOCOUNT ON 

--删除单据
DELETE FROM BillIndex WHERE BillType IN(400,401,402,403)
DELETE FROM BillIndex WHERE BillType = 57 AND AdPriceType = 2
DELETE FROM adpricebill
FROM BillIndex AS A
WHERE BillType = 57 AND AdPriceType = 2
DELETE FROM ReceiptBillIndex WHERE BillType IN(404,405)
DELETE FROM ListTable WHERE BillType IN(400,401,402,403,404,405)
DELETE FROM InOutstocktable WHERE BillType IN(400,401,402,403,404,405)
DELETE FROM AppraisalBill
DELETE FROM AppraisalBackBill
DELETE FROM SendBill
DELETE FROM SendBackBill
DELETE FROM ReceiptBill

--删除查询方案
DECLARE @billtype VARCHAR(MAX),@SchemeId INT
DECLARE InDataValue CURSOR FOR 
SELECT SchemeId,DataValue FROM dbo.SchemeDetail WHERE DataField = 'billtype'
OPEN InDataValue 
FETCH NEXT FROM InDataValue INTO @SchemeId,@billtype
WHILE(@@FETCH_STATUS = 0)
BEGIN 
	IF(@billtype <> '')
	BEGIN
		DECLARE @inicount INT,@invoicecount INT
		IF EXISTS(SELECT A.a FROM F_Split(@billtype,',') AS A WHERE A.a IN(400,401,402,403,404,405))
		BEGIN
			SET @inicount = (SELECT COUNT(A.a) FROM F_Split(@billtype,',') AS A)
			SET @invoicecount = (SELECT COUNT(A.a) FROM F_Split(@billtype,',') AS A WHERE A.a IN(400,401,402,403,404,405))
			
			IF (@inicount = @invoicecount)
			BEGIN
				DELETE FROM scheme WHERE SchemeId = @SchemeId
				DELETE FROM SchemeDetail WHERE SchemeId = @SchemeId
			END
			ELSE
			BEGIN
				UPDATE SchemeDetail SET DataValue = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@billtype,'400,',''),'401,',''),'402,',''),'403,',''),'404,',''),'405,',''),',400',''),',401',''),',402',''),',403',''),',404',''),',405','')
				WHERE SchemeId = @SchemeId AND DataField = 'billtype'
			END
		END
	END
	FETCH NEXT FROM InDataValue INTO @SchemeId,@billtype
END
CLOSE InDataValue
DEALLOCATE InDataValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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














/****** Object:  Stored Procedure dbo.Gp_DeleteAreaDept    Script Date: 2002-6-20 10:14:46 ******/

CREATE  PROCEDURE [Gp_DeleteAreaDept]
(
 @DbName varchar(50),
 @TypeId [varchar](25)
)
--@encode$--
AS 
SET NOCOUNT ON
declare @sql  varchar(500)
select @sql='update '+@dbname+' set deleted=1  WHERE  typeid = '+char(39)+@typeid+char(39)
--print @sql
exec (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF exists (SELECT * from dbo.sysobjects where id = object_id(N'[dbo].[GP_DeleteBaseInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_DeleteBaseInfo]
GO


/****** Object:  StoredProcedure [dbo].[GP_DeleteBaseInfo]    Script Date: 06/01/2011 19:18:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*
最后改动吴德水20003-06-13 停用往来单位与借欠关联。
改动：吴德水  2002年12月26日下午13：00
改动原因：限制被删除的基本信息被再次删除，从来导致sonNum为负.
改动原因：先前判断往来单位是否可以被删除的条件是往来余额是否为零！这是不对的，将这一条件改成“是否有经营历程 ”
         即到listtable中查对应当往来单位的记录！ 
===
修改：吴德水
时间：2003-07-18 17:00
内容：加上商品的停用或删除中经营历程
位置：99行起
作者：谢吉康
日期：2004-09-20
描述：删除仓库信息时增加经营历程的判断 返回值＝-101

修改：毛欣蓉
时间：2010-06-24
内容：判断商品、客户、职员、仓库是否有价格促销信息 返回值-350 -351 -352 -353 

修改：彭勇	
时间：2012-04-20
内容：判断商品是否被OM发布过。发布过了则不能删除。

修改：舒珊	
时间：2016-02-25
内容：判断基本信息是否为单个删除,单个删除有子节点则不能删除,批量删除不检查子节点

修改：赵燕琴
时间：2019-05-09
内容：删除商品时，同时删除掉商品附件信息
*/
CREATE    PROCEDURE [dbo].[GP_DeleteBaseInfo]
( @TypeId VARCHAR(50),	--基本信息表的关键字段
  @DbName VARCHAR(50),	--基本信息关键字
  @delType INT=0,	--1代表启用，0代表停用，-1代表删除
  @ifdeleteson INT=0 --0 代表单个删除（有子节点则不能删除），1代表非单个删除（不检查子节点）
)
--@encode$--
AS
SET NOCOUNT ON
--DECLARE @sql VARCHAR (500)
DECLARE @GOODS_ID VARCHAR(50)
DECLARE @dTempQty  NUMERIC(24, 10) 
DECLARE @dTempTotal  NUMERIC(24, 10) 
DECLARE @sonnum NUMERIC (10)
DECLARE @parid VARCHAR(50)
DECLARE @deleted INT	--是否停用标志(1代表停用，0代表不停用)
DECLARE	@result		INT=0		--自定义接收返回值
DECLARE	@result1	INT=0		--自定义接收返回值
SELECT @GOODS_ID='0000100001'
DECLARE @ifqp VARCHAR(1)	--判断是否为汽配(1代表汽配,0代表其它)
DECLARE @XiWaMaxNumber  NUMERIC(24, 10) 
SET @ifqp=(SELECT subvalue from sysdata where subname='ifqp')
DECLARE @delTypeName VARCHAR(10)	--@delTypeName和@delType分别一一对应
IF @deltype=0
	SET @delTypeName='停用'
IF @deltype=-1
	SET @delTypeName='删除'
	
	

------------全局判断"自定义"是否关联基本信息，如果关联基本信息里相关项不能被删除------------
DECLARE @temptypename	VARCHAR(20)
	SET @temptypename=''
IF @deltype=-1
BEGIN
	IF @DbName='ptype'
		SET @temptypename='Ptype'
	IF @DbName='btype'
		SET @temptypename='btype'
	IF @DbName='stock'
		SET @temptypename='stock'
	IF @DbName='DepartMent'
		SET @temptypename='DepartMent'
	IF @DbName='AreaType'
		SET @temptypename='Areatype'
	IF @DbName='SType'
		SET @temptypename='Stype'
	IF @DbName='employee'
		SET @temptypename='employee'
		
	exec @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@TypeId,@result=0
	IF @result=1
	BEGIN
		RAISERROR('当前信息已在自定义中关联,不可以''删除''',16,1) return
	END

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

--------------------------------------判断基本信息被辅助核算，凭证录入使用后不能删除------------------------
--辅助核算
	DECLARE @typename VARCHAR(100)
IF @deltype=-1
BEGIN
	
	IF @DbName='btype'
		SET @typename='BTYPE'
	IF @DbName='DepartMent'
		SET @typename='DEPARTMENT'
	IF @DbName='SType'
		SET @typename='STYPE'
	IF @DbName='employee'
		SET @typename='EMPLOYEE'
		
		EXEC	@result1=dbo.Gp_DeleteInsert_Ac_Data @Type=@typename,@typeid=@TypeId
		IF @result1=1
		BEGIN
				RAISERROR('当前信息已在辅助核算中关联,不可以''删除''',16,1) return
		END
END

---启用已停用的基本信息
IF @deltype=1
BEGIN
	IF @DbName='SType' AND EXISTS(SELECT TOP 1 1 FROM SType S WHERE deleted=1 AND TypeId=(SELECT VerifyID FROM SType WHERE TypeId=@TypeId AND IsSelfVerify=0))
		BEGIN						
			RAISERROR('当前分支机构对应记账单位的独立核算分支机构为停用机构，不能启用当前非独立核算的分支机构！',16,1)RETURN  
		END	
		
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL='
	UPDATE '+@DbName+' SET deleted=0 WHERE Typeid= '''+@TypeId+''' AND deleted=1
	UPDATE '+@DbName+' SET XiWaMaxNumber = PP.XiWaMaxNumber+1 FROM (SELECT MAX(XiWaMaxNumber) AS XiWaMaxNumber FROM '+@DbName+') PP WHERE typeId='''+@TypeId+''''
	
	--print @sql
	EXEC (@SQL)

	IF @DbName='PTYPE' OR @DbName='employee' 
	BEGIN
		--POS下载处理
		EXEC Gp_DataSaveForPosDown '-99999',@DbName,'0'
	END	
	
	IF @DbName='PTYPE'
	BEGIN
		DECLARE @pospid INT 
		SELECT @pospid =pid FROM ptype  WHERE typeId=@typeid
		EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext',@pospid
	END
	
	IF @DbName='BTYPE'
	BEGIN
		--清空停用日期
		UPDATE BTYPE SET stopdate=null  WHERE typeId=@typeid 
	END	RETURN 0
END
-----------------------------------------------------END-----------------------------------------------	

DECLARE @erromsg VARCHAR(MAX)
--删除判断
BEGIN TRY
	EXEC Gp_BaseInfoCheck @dbname,@TypeId,'1'
END TRY
BEGIN CATCH
	SELECT @erromsg=ERROR_MESSAGE()
	RAISERROR('%s',16,1,@erromsg)RETURN
END CATCH

	
-- 商品停用删除判断
IF @dbname= 'ptype'
	BEGIN

		SELECT @parid=ParId FROM ptype WHERE typeId=@TypeId
		--已停用的基本信息，不能停用
		IF EXISTS(SELECT TypeID FROM ptype WHERE TypeID=@TypeId AND deleted=1)
			BEGIN
				IF @deltype=0	--RETURN -3
					BEGIN
						RAISERROR('该商品信息已经被停用，不能再停用',16,1) RETURN
					END
			END
	END
	

-- 判断当前金额
IF @dbname= 'atype'
	BEGIN		
		--判断至少有一个基本信息不能删除
		DECLARE @num int
		IF EXISTS(SELECT TypeID FROM atype WHERE TypeID=@TypeId AND deleted=0 AND leveal=3)
		BEGIN
		  DECLARE @aparid VARCHAR(100)
		  SET @aparid=LEFT(@TypeId,10)
		  IF(@aparid='0000100002' or @aparid='0000100004') --固定资产和银行合计
		    BEGIN
				SELECT @num=COUNT(*) from atype where parid=@aparid AND deleted=0
				IF(@num=1)
				BEGIN
			     IF @deltype=0 OR @deltype=-1
				BEGIN
					 RAISERROR('删除至少要保留一个启用的基本信息，请重新操作',16,1,@delTypeName)RETURN--RETURN-8
			    END
		       END
		    END
		END
	END

IF @dbname='LType'
	BEGIN
		---启用已停用的基本信息
		IF @deltype=1
			BEGIN
				UPDATE LType SET deleted=0 WHERE Typeid=@Typeid AND deleted=1
				RETURN 0
			END
		-- ==============停用货位基本信息
		IF @deltype=0 
			BEGIN
				IF EXISTS(SELECT TypeID FROM stock WHERE TypeID=@TypeId AND deleted=1)
					BEGIN
						--print '已停用的基本信息，不能停用!'
						IF @deltype=0  
							BEGIN
								RAISERROR('该货位信息已经被停用',16,1)RETURN--RETURN-3
							END
					END
				IF exists(SELECT Ltypeid from GoodsLocal where Ltypeid=@TypeId AND Qty<>0)
						BEGIN
							--print '['+@FullName+']货位库存余量不为零，不能停用'
							RAISERROR('该货位库存余量不为零，禁止%s',16,1,@delTypeName) RETURN--return -104
						END 
						
						
						--判断序列号
				IF exists(SELECT LTypeID from gp_CruPtypeSerial where LTypeID=@TypeId)
						BEGIN
							--print '此货位有序列号，不能停用'
							RAISERROR('该货位有序列号，禁止%s',16,1,@delTypeName)RETURN-- return -105
						END
						
						
						-- 判断经营
--				IF exists( (SELECT LTypeID from LocalDetail where (LTypeID=@TypeId or LTypeID2=@TypeId) AND Qty<>0)) or (exists(SELECT LTypeID from LocalIndex where (LTypeID=@TypeId or LTypeID2=@TypeId) AND totalQty<>0)))
				IF (exists(SELECT LTypeID from LocalDetail where (LTypeID=@TypeId or LTypeID2=@TypeId) AND Qty<>0)) 
						BEGIN
							--print '['+@FullName+']货位已经经营过，不能停用'
							RAISERROR('该货位已经经营过，禁止%s',16,1,@delTypeName)RETURN--return -106
						END 
				/*IF exists(SELECT LTypeID from LocalIndex where (LTypeID=@TypeId or LTypeID2=@TypeId) AND totalQty<>0)
						BEGIN
							--print '['+@FullName+']货位已经经营过，不能停用'
							return -106
						END */
				UPDATE LType SET deleted=1 WHERE typeid=@typeid 
				--IF len(@typeid)>5
				--	UPDATE LType SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
				--IF len(@typeid)=5
				--	UPDATE LType SET sonNum=sonNum-1 WHERE typeid='00000'
				RETURN 0
	
			END
		-- ==============删除货位基本信息
		IF @deltype=-1 
			BEGIN
				--单个删除时检查子节点，有 则不能删除
				IF @ifdeleteson=0
					BEGIN
						IF exists(SELECT SONNUM from LType where typeid=@TypeId AND SONNUM>0)
							BEGIN
								RAISERROR('有节点信息不能删除！',16,1) RETURN
							END
					END
				IF exists(SELECT Ltypeid from GoodsLocal where Ltypeid=@TypeId AND Qty<>0)
						BEGIN
							--print '['+@FullName+']货位库存余量不为零，不能删除'
							RAISERROR('该货位库存余量不为零，禁止%s',16,1,@delTypeName)RETURN-- return -104
						END 				
				--判断序列号
				IF exists(SELECT LTypeID from gp_CruPtypeSerial where LTypeID=@TypeId)
						BEGIN
							--print '此货位有序列号，不能删除'
							 RAISERROR('该货位有序列号，禁止%s',16,1,@delTypeName)RETURN--return -105
						END			
				-- 判断经营
				IF exists(SELECT LTypeID from LocalDetail where (LTypeID=@TypeId or LTypeID2=@TypeId) AND Qty<>0)
					-- or exists(SELECT LTypeID from LocalIndex where (LTypeID=@TypeId or LTypeID2=@TypeId) AND totalQty<>0)
					BEGIN
						--print '['+@FullName+']货位已经经营过，不能删除'
						RAISERROR('该货位已经经营过，禁止%s',16,1,@delTypeName)RETURN--return -106
					END 
				DELETE LType WHERE typeid=@typeid 
				IF len(@typeid)>5
					UPDATE LType SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
				IF len(@typeid)=5
					UPDATE LType SET sonNum=sonNum-1 WHERE typeid='00000'
				RETURN 0
			END
		
	END

--账务信息
IF @dbname= 'atype' 
	BEGIN
		IF EXISTS(SELECT typeid  FROM atype WHERE deleted=1 AND  typeid=@typeid)
			IF @delType=0
				BEGIN
              		--print '此数据已被停用!'
					RAISERROR('该基本信息已经被停用，不能再停用',16,1)RETURN--RETURN -3
				END
		IF @delType=0
			BEGIN
				 UPDATE atype SET deleted = 1 WHERE typeid=@typeid AND total=0  AND sysrow=0 
				 RETURN 0
			END
		IF @delType=-1
			BEGIN
				--单个删除时检查子节点，有 则不能删除
				IF @ifdeleteson=0
					BEGIN
						IF exists(SELECT SONNUM from atype where typeid=@TypeId AND SONNUM>0)
							BEGIN
								RAISERROR('有节点信息不能删除！',16,1) RETURN
							END
					END
				SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM atype
				DELETE atype WHERE typeid=@typeid AND total=0  AND sysrow=0 
				
				--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
				UPDATE atype
				SET xiwamaxnumber=@XiWaMaxNumber 
				WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM atype)
				
				--更新父节点的sonnum
				IF len(@typeid)>5
					UPDATE atype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
				IF len(@typeid)=5
					UPDATE atype SET sonNum=sonNum-1 WHERE typeid='00000'
				
				--更新父节点的xiwamaxnumber，已使父节点的缓存得到更新
				SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM atype
				UPDATE atype SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeid=LEFT(@typeid,len(@typeid)-5)
					
				EXEC GP_DeleteBaseL 'A',@typeid --删除相关多级权限范围记录
				
				--删除职员创利表数据					
			    delete from	EmpIncSet where AtypeID=@TypeId
				RETURN 0
			END 
		IF @@rowcount = 0 
			BEGIN 
				RAISERROR('%s该记录失败',16,1)RETURN--RETURN -2 
			END
	END

--往来单位(客户和供货商)删除和更新
IF @dbname= 'btype' 
	BEGIN
		IF EXISTS(SELECT  typeid FROM btype WHERE deleted=1 AND typeid=@typeid)
			BEGIN
				--print '此数据已被停用！'
				IF @deltype=0  
				BEGIN
					RAISERROR('该往来单位信息已经被停用，不能删除',16,1)RETURN--RETURN-3
				END
			END
		IF @delType=0
			BEGIN
				UPDATE btype SET deleted = 1 WHERE typeid=@typeid AND artotal=0 AND aptotal=0  
					RETURN 0
			END
		IF @delType=-1
			BEGIN
				--单个删除时检查子节点，有 则不能删除
				IF @ifdeleteson=0
					BEGIN
						IF exists(SELECT SONNUM from btype where typeid=@TypeId AND SONNUM>0)
							BEGIN
								RAISERROR('有节点信息不能删除！',16,1) RETURN
							END
					END
				--检测有木有作为其他单位的结算单位
				IF EXISTS(SELECT denominatedid FROM dbo.btype WHERE denominatedid=@TypeId AND typeId <> @TypeId /*找除自己以外的记录*/ )
				BEGIN 
					RAISERROR('该往来单位已作为其他客户或供应商的结算单位,不能删除',16,1)RETURN
				END
				
				--删除 信用额度设置/品牌信用额度设置
				Delete FROM btype_credit WHERE BtypeId=@TypeId
				Delete FROM BrandBtype_Credit WHERE BtypeId=@TypeId
				
				
				--删除往来单位对应的商品多编码
				DELETE PuserCode WHERE btypeId = @typeid
				
				--删除价格跟踪表的信息--开始--
				DELETE FROM dbo.PriceTrack WHERE BtypeID=@typeid
				DELETE FROM dbo.PriceTrack_AskPrice  WHERE BtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Buy WHERE BtypeID=@typeid
				DELETE FROM dbo.PriceTrack_BuyOrder WHERE BtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Quote WHERE BtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Sale WHERE BtypeID=@typeid
				DELETE FROM dbo.PriceTrack_SaleOrder WHERE BtypeID=@typeid
				--删除价格跟踪表的信息--结束--
				

				SELECT @deleted=deleted FROM btype WHERE typeid=@typeid
				IF @deleted=0
					BEGIN
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM btype	
					
						DELETE btype WHERE typeid=@typeid AND artotal=0 AND aptotal=0 
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE btype
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM btype)
						 
						DELETE Btype_CustomColumns WHERE typeid=@typeid
						--delete  from btype_l where typeid=@typeid
						IF len(@typeid)>5
							BEGIN
								UPDATE btype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
							END
						IF len(@typeid)=5
							UPDATE btype SET sonNum=sonNum-1 WHERE typeid='00000'
							EXEC GP_DeleteBaseL 'B',@typeid --删除相关多级权限范围记录
							RETURN 0
					END
				IF @deleted=1
					BEGIN
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM btype	
					
						DELETE btype WHERE typeid=@typeid AND artotal=0 AND aptotal=0 AND deleted=1
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE btype
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM btype)
						
						DELETE Btype_CustomColumns WHERE typeid=@typeid
						IF len(@typeid)>5
							BEGIN
								UPDATE btype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
							END
						IF len(@typeid)=5
							BEGIN
								UPDATE btype SET sonNum=sonNum-1 WHERE typeid='00000'	
							END
						--delete  from btype_l where typeid=@typeid
						EXEC GP_DeleteBaseL 'B',@typeid --删除相关多级权限范围记录
						RETURN 0
					END
			END
		IF @@rowcount = 0  
			BEGIN
				RAISERROR('%s该记录失败',16,1)RETURN--RETURN -2 
			END
	END

--职员信息停用、删除判断和处理
IF @dbname= 'employee' 
	BEGIN
		IF EXISTS(SELECT TypeID FROM employee WHERE deleted=1 AND  TypeID=@TypeId)
			BEGIN
				IF @deltype=0     
				BEGIN
					RAISERROR('该职员信息已经被停用，不能再停用',16,1)RETURN    
				END--RETURN     END-3
			END
		---------------------------------------------- 9.2新增判断END ------------------------------------------------
		IF @delType=0
			BEGIN
				UPDATE employee SET deleted = 1 WHERE typeid=@typeid
				DELETE FROM  loginuser WHERE etypeid=@typeid
				RETURN 0
			END
		IF @delType=-1
			BEGIN
				--单个删除时检查子节点，有 则不能删除
				IF @ifdeleteson=0
					BEGIN
						IF exists(SELECT SONNUM from employee where typeid=@TypeId AND SONNUM>0)
							BEGIN
								RAISERROR('有节点信息不能删除！',16,1) RETURN
							END
					END
				SELECT @deleted=deleted FROM employee WHERE typeid=@typeid
				IF @deleted=0
					BEGIN
						SELECT @parid=parid FROM employee WHERE typeid = @typeid
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM employee
						
						DELETE dbo.POSEmployee WHERE Etypeid = @TypeId
						
						DELETE employee WHERE typeid=@typeid
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE employee
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM employee)
						
						DELETE Etype_CustomColumns WHERE typeid=@typeid
						DELETE Etype_Picture WHERE etypeid=@typeid
						IF LEN(@TypeId)>5
							BEGIN
								update employee SET sonnum=sonnum-1 where typeId=LEFT(@TypeId,LEN(@TypeId)-5)	
							END
						IF LEN(@TypeId)=5
							BEGIN
								update employee SET sonnum=sonnum-1 where typeId='00000'
							END
						EXEC GP_DeleteBaseL 'E',@typeid --删除相关多级权限范围记录
						--UPDATE employee SET sonnum= sonnum-1 WHERE typeid =@parid 
						DELETE FROM  loginuser WHERE etypeid=@typeid
						EXEC Gp_DataSaveForPosDown '-99999',@dbname,0
						RETURN 0
					END
				IF @deleted=1
					BEGIN
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM employee
						
						DELETE dbo.POSEmployee WHERE Etypeid = @TypeId
						
						DELETE employee WHERE typeid=@typeid  AND deleted=1
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE employee
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM employee)
						
						DELETE Etype_CustomColumns WHERE typeid=@typeid
						DELETE Etype_Picture WHERE etypeid=@typeid
						IF LEN(@TypeId)>5
							BEGIN
								update employee SET sonnum=sonnum-1 where typeId=LEFT(@TypeId,LEN(@TypeId)-5)	
							END
						IF LEN(@TypeId)=5
							BEGIN
								update employee SET sonnum=sonnum-1 where typeId='00000'
							END
						--delete  from etype_l where typeid=@typeid
						EXEC GP_DeleteBaseL 'E',@typeid --删除相关多级权限范围记录
						EXEC Gp_DataSaveForPosDown '-99999',@dbname,0
						RETURN 0
					END
			END
			RETURN -99
	END

--仓库信息
IF @dbname='stock'
	BEGIN 
		IF EXISTS(SELECT typeid  FROM stock WHERE deleted=1 AND typeid=@typeid)
			BEGIN
			--print '此数据已被停用！'
        		IF @deltype=0 
					BEGIN
						RAISERROR('该仓库信息已经被停用，不能再停用',16,1)RETURN--RETURN-3	
					END
			--IF @deltype=0  RETURN-31
			END
		
		
		---------------------------------------------- 9.2新增判断END --------------------------------------------------
		--肖伟 2002年11月27日 修改 因为库存状况表中当数量为0,金额为0的时候,该行数据也应该被删除,而不是存在这行数据就不删除 
		IF EXISTS(SELECT ktypeid FROM goodsstocks WHERE ktypeid=@typeid AND (qty<>0 OR total<>0)) 
			BEGIN
				RAISERROR('该仓库数量或金额不为0,不能%s该记录',16,1,@delTypeName)RETURN--RETURN -119
			END
		ELSE
			BEGIN
				IF @delType=0
					BEGIN
						UPDATE stock SET deleted=1 WHERE typeid=@typeid 
						RETURN 0
					END
				IF @delType=-1
					BEGIN
						--单个删除时检查子节点，有 则不能删除
						IF @ifdeleteson=0
							BEGIN
								IF exists(SELECT SONNUM from stock where typeid=@TypeId AND SONNUM>0)
									BEGIN
										RAISERROR('有节点信息不能删除！',16,1) RETURN
									END
							END
						SELECT @deleted=deleted FROM stock WHERE typeid=@typeid
						IF @deleted=1
							BEGIN
								
								SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM stock
								
								DELETE stock WHERE typeid=@typeid 
								
								--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
								UPDATE stock
								SET xiwamaxnumber=@XiWaMaxNumber 
								WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM stock)
								
								DELETE Ktype_CustomColumns WHERE typeid=@typeid
								IF len(@typeid)>5
									BEGIN
										UPDATE stock SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
									END
								IF len(@typeid)=5
									BEGIN
										UPDATE stock SET sonNum=sonNum-1 WHERE typeid='00000'
									END	
								--delete  from ktype_l where typeid=@typeid
								EXEC GP_DeleteBaseL 'K',@typeid --删除相关多级权限范围记录
								DELETE dbo.CargoType WHERE KtypeID = @typeid --删除货位
								RETURN 0
							END 
						IF @deleted=0	
							BEGIN
								SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM stock	
								DELETE stock WHERE typeid=@typeid 
								--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
								UPDATE stock
								SET xiwamaxnumber=@XiWaMaxNumber 
								WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM stock)
								DELETE Ktype_CustomColumns WHERE typeid=@typeid
								IF len(@typeid)>5
									UPDATE stock SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
								IF len(@typeid)=5
									UPDATE stock SET sonNum=sonNum-1 WHERE typeid='00000'
								EXEC GP_DeleteBaseL 'K',@typeid --删除相关多级权限范围记录		
								DELETE dbo.CargoType WHERE KtypeID = @typeid --删除货位
									RETURN 0
							END
					END
				IF @@rowcount = 0 
					BEGIN
						 RAISERROR('%s记录失败',16,1,@delTypeName)RETURN--RETURN -2 
					END
			END
	END

--部门信息删除和更新
IF @dbname='DepartMent'
	BEGIN 
		IF @delType=0
			BEGIN
				UPDATE DepartMent SET deleted=1 WHERE typeid=@typeid 
				RETURN 0
			END
		IF @delType=-1
			BEGIN
				--单个删除时检查子节点，有 则不能删除
				IF @ifdeleteson=0
					BEGIN
						IF exists(SELECT SONNUM from DepartMent where typeid=@TypeId AND SONNUM>0)
							BEGIN
								RAISERROR('有节点信息不能删除！',16,1) RETURN
							END
					END
				SELECT @deleted=deleted FROM DepartMent WHERE typeid=@typeid
				IF @deleted=1
					BEGIN
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM DepartMent	
						
						DELETE DepartMent WHERE typeid=@typeid 
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE DepartMent
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM DepartMent)
						
						DELETE Dtype_CustomColumns WHERE typeid=@typeid
						IF len(@typeid)>5
							UPDATE DepartMent SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
						IF len(@typeid)=5
							UPDATE DepartMent SET sonNum=sonNum-1 WHERE typeid='00000'
							
						--删除后更新父节点的xiwamaxnumber
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM AreaType
						UPDATE AreaType SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeid=LEFT(@typeid,len(@typeid)-5)
						RETURN 0
					END 
				IF @deleted=0	
					BEGIN
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM DepartMent	
						
						DELETE DepartMent WHERE typeid=@typeid 
							
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE DepartMent
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM DepartMent)
						
						DELETE Dtype_CustomColumns WHERE typeid=@typeid
						IF len(@typeid)>5
							UPDATE DepartMent SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
						IF len(@typeid)=5
							UPDATE DepartMent SET sonNum=sonNum-1 WHERE typeid='00000'
							
						--删除后更新父节点的xiwamaxnumber
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM AreaType
						UPDATE AreaType SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeid=LEFT(@typeid,len(@typeid)-5)
							
						RETURN 0
					END
			END
		IF @@rowcount = 0  
			BEGIN
				RAISERROR('%s该记录失败',16,1,@delTypeName)RETURN--RETURN -2 
			END
	END
-- =================================================================================================================
--地区信息删除和更新
IF @dbname='AreaType'
	BEGIN 
		IF @delType=0
			BEGIN
				UPDATE AreaType SET deleted=1 WHERE typeid=@typeid 
				RETURN 0
			END
		IF @delType=-1
			BEGIN
				BEGIN
					--单个删除时检查子节点，有 则不能删除
					IF @ifdeleteson=0
						BEGIN
							IF exists(SELECT SONNUM from AreaType where typeid=@TypeId AND SONNUM>0)
								BEGIN
									RAISERROR('有节点信息不能删除！',16,1) RETURN
								END
						END
					SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM AreaType
					DELETE AreaType WHERE typeid=@typeid 
					--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
					UPDATE AreaType
					SET xiwamaxnumber=@XiWaMaxNumber 
					WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM AreaType)
					
					DELETE Areatype_CustomColumns WHERE typeid=@typeid
					IF len(@typeid)>5
						UPDATE AreaType SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
					IF len(@typeid)=5
						UPDATE AreaType SET sonNum=sonNum-1 WHERE typeid='00000'
					
					--删除后更新父节点的xiwamaxnumber
					SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM AreaType
					UPDATE AreaType SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeid=LEFT(@typeid,len(@typeid)-5)
					RETURN 
				END
			END
		IF @@rowcount = 0 
			BEGIN
			RAISERROR('%s该记录失败',16,1,@delTypeName)RETURN-- RETURN -2
			END 
	END
-- =================================================================================================================
----分支机构删除条件
IF @dbname='SType'
	BEGIN 
		IF @delType=-1
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM SType WHERE IsSelfVerify=0 AND VerifyID=@TypeId)
					BEGIN					
						RAISERROR('您所要删除的分支机构为独立核算分支机构，且该分支机构被非独立核算分支机构所调用，不能删除，请核对后再试！',16,1) RETURN
					END
				--单个删除时检查子节点，有 则不能删除
				IF @ifdeleteson=0
				BEGIN
					IF exists(SELECT SONNUM from SType where typeid=@TypeId AND SONNUM>0)
					BEGIN
						RAISERROR('有节点信息不能删除！',16,1) RETURN
					END
					
					--判断优惠券是否使用
					IF EXISTS(SELECT TOP 1 1  FROM coupon_ApplyStype WHERE stypeid = @typeid)
					BEGIN
						RAISERROR('分支机构信息已经被优惠券使用，不能删除！',16,1) RETURN
					END	
				END
				SELECT @deleted=deleted FROM SType WHERE typeid=@typeid
				
				IF @deleted=1
					BEGIN
						DELETE Ac_Items_Detail WHERE STypeId=@TypeId--删除Ac_Items_Detail 关联数据
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM SType
						DELETE SType WHERE typeid=@typeid 
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE SType
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM SType)
							
						DELETE Stype_CustomColumns WHERE typeid=@typeid
						DELETE PType_STypePrice WHERE stypeid=@typeid
						DELETE FrozeBusiness WHERE Stypeid=@TypeId
						
						IF len(@typeid)>5
							UPDATE SType SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
						IF len(@typeid)=5
							UPDATE SType SET sonNum=sonNum-1 WHERE typeid='00000'
							
						--删除期间
						DELETE from Ac_AccountsPeroid_Stype WHERE STYPEID=@typeid
						DELETE from SType_UserConfig WHERE STYPEID=@typeid
						
						--删除Base_InventoryTypeDetails 关联
						DELETE FROM Base_InventoryTypeDetails WHERE STYPEID=@typeid
						--删除PType_InventoryType关联 暂时不要
						--DELETE FROM PType_InventoryType WHERE STYPEID=@typeid
						--删除Base_FixedReasonForChangeDetails关联
						DELETE FROM Base_FixedReasonForChangeDetails WHERE STYPEID=@typeid
						
						--删除后更新父节点的xiwamaxnumber
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM SType
						UPDATE SType SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeid=LEFT(@typeid,len(@typeid)-5)
					END 
					IF @deleted=0	
					BEGIN
						DELETE Ac_Items_Detail WHERE STypeId=@TypeId--删除Ac_Items_Detail 关联数据
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM SType
						
						DELETE SType WHERE typeid=@typeid 
						
						DELETE ThreeFinancialItem_SType WHERE STypeID=@TypeId--删除固化报表公式
						DELETE ThreeFinancialFormula_Stype WHERE STypeID=@TypeId
						DELETE ThreeFinancialItemParent_Stype WHERE STypeID=@TypeId
						
							--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
							UPDATE SType
							SET xiwamaxnumber=@XiWaMaxNumber 
							WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM SType)
						
						DELETE Stype_CustomColumns WHERE typeid=@typeid
						DELETE PType_STypePrice WHERE stypeid=@typeid
						DELETE FrozeBusiness WHERE Stypeid=@TypeId
						--9.4新加，删除该分支机构出纳管理启用期间
						DELETE FROM Te_StartPeriod WHERE STypeId=@typeid
						
						--删除期间
						DELETE from Ac_AccountsPeroid_Stype WHERE STYPEID=@typeid
						DELETE from SType_UserConfig WHERE STYPEID=@typeid
						
						--删除Base_InventoryTypeDetails 关联
						DELETE FROM Base_InventoryTypeDetails WHERE STYPEID=@typeid
						--删除PType_InventoryType关联 暂时不要！！
						--DELETE FROM PType_InventoryType WHERE STYPEID=@typeid
						--删除Base_FixedReasonForChangeDetails关联
						DELETE FROM Base_FixedReasonForChangeDetails WHERE STYPEID=@typeid
						
						IF len(@typeid)>5
							UPDATE SType SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
						IF len(@typeid)=5
							UPDATE SType SET sonNum=sonNum-1 WHERE typeid='00000'
						
						--删除后更新父节点的xiwamaxnumber
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM SType
						UPDATE SType SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeid=LEFT(@typeid,len(@typeid)-5)
						
						--处理业务类型
						IF EXISTS(SELECT *FROM SType WHERE TypeId=LEFT(@typeid,len(@typeid)-5) AND sonnum=0)
						BEGIN
							UPDATE Ac_AssetBusinessType
							SET STypeId=LEFT(@typeid,len(@typeid)-5)
							WHERE STypeId=@TypeId
						END
						ELSE
						BEGIN
							DELETE FROM Ac_AssetBusinessType WHERE STypeId=@TypeId
						END
					END
					
			--期间信息
			IF LEN(@typeid)>5
			BEGIN
				DECLARE @ParentTypeID VARCHAR(100)=LEFT(@TypeID,len(@TypeID)-5)
				--父节点无子节点
				IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE   TypeId=@ParentTypeID AND sonnum=0)
				BEGIN
					INSERT INTO dbo.MonthProc
							( STypeID ,
							  MonthNo ,
							  StartDate ,
							  EndDate ,
							  period ,
							  Year ,
							  comment
							)
					SELECT	  @ParentTypeID,
							  MonthNo ,
							  StartDate ,
							  EndDate ,
							  period ,
							  Year ,
							  comment
					FROM dbo.MonthProc WHERE STypeID=@typeid
				END
			END
			--删除原分支机构期间表信息
			DELETE FROM dbo.MonthProc WHERE STypeID=@TypeID
			
		END
		IF @@rowcount = 0  
		BEGIN
		RAISERROR('%s该记录失败',16,1,@delTypeName)RETURN--RETURN -2 
		END
	END
-- =================================================================================================================
--商品删除和更新
IF @dbname='ptype'
	BEGIN
		IF EXISTS(SELECT typeid FROM ptype WHERE deleted=1 AND typeid=@typeid)
			BEGIN
				IF @deltype=0
				BEGIN
					RAISERROR('该商品信息已被停用，禁止%s',16,1,@delTypeName)RETURN  	
				END
			END
		----有价格跟踪信息，禁止删除
		--IF EXISTS (SELECT PtypeID FROM PriceTrack WHERE PtypeID=@TypeId AND (SalePrice<>NULL OR	CostPrice<>NULL OR	SaleOrderPrice<>NULL 
		--       OR	BuyOrderPrice<>NULL OR   QueryPrice<>NULL OR	ResponsePrice<>NULL))
		--	BEGIN
		--		IF @delType=-1
		--			BEGIN
		--				RAISERROR('该商品有价格跟踪信息，禁止%s',16,1,@delTypeName)RETURN    
		--			END--RETURN -352
		--	END
		IF @delType=-1
		BEGIN
			--单个删除时检查子节点，有 则不能删除
			IF @ifdeleteson=0
				BEGIN
					IF exists(SELECT SONNUM from ptype where typeid=@TypeId AND SONNUM>0)
					BEGIN
						RAISERROR('有节点信息不能删除！',16,1) RETURN
					END
						
					--判断优惠券是否使用
					IF EXISTS(SELECT TOP 1 1  FROM coupon_ApplyPtype WHERE ptypeid = @typeid)
					BEGIN
						RAISERROR('商品信息已经被优惠券使用，不能删除！',16,1) RETURN
					END	
				END
		END
		
		DECLARE @tempStock VARCHAR(50)
		DECLARE stock_cursor CURSOR FOR 
		SELECT typeid FROM stock WHERE sonnum=0 AND deleted<>1 AND typeid<>'00000'
		OPEN stock_cursor
 		FETCH NEXT FROM stock_cursor INTO @tempstock
		WHILE @@fetch_status =0 
			BEGIN
				EXEC gp_Getdbf @GOODS_ID,@typeid,'0','0',@tempstock,'','','',@dTempQty OUTPUT,@dTempTotal OUTPUT
  				IF @dTempQty<>0 
   					GOTO ERROR1 
				ELSE
  					FETCH NEXT FROM stock_cursor INTO @tempstock
 			END  
 		CLOSE stock_cursor
	 	DEALLOCATE stock_cursor
		IF @delType=0
 			UPDATE ptype SET deleted=1 WHERE typeid=@typeid 
		IF @delType=-1
			BEGIN
				IF exists (SELECT * from PType_Units_Ext where PtypeID=@typeid)
					BEGIN
						delete from PType_Units_Ext where ptypeid=@typeid
					END
				---删除商品对应附件
				if exists (select * from dbo.baseAttachFile where PID=(select pid from dbo.ptype where typeid=@typeid))
				begin
				DELETE FROM dbo.baseAttachFile WHERE PID=(select pid from dbo.ptype where typeid=@typeid)
				end
				
				DELETE FROM PType_TranslateRates WHERE ptypeid=@typeid
				
				-- 删除nVipGoodsSign中对应商品的信息
				DELETE FROM nVipGoodsSign WHERE ptypeid=@typeid 	
				--停用，删除商品相应的多编码删除
				DELETE PuserCode WHERE PtypeId = @typeid
				DELETE productpic WHERE ptypeid=@TypeId
				--删除自定义中关联信息
				DELETE FROM Ptype_CustomColumns WHERE typeid=@typeid
				--删除商品的辅助销售单位
				DELETE FROM PType_AuxiliaryUnits_Ext WHERE PtypeID=@typeid
				--删除价格跟踪表的信息--开始--
				DELETE FROM dbo.PriceTrack WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_AskPrice  WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Buy WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_BuyOrder WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Quote WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Sale WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_SaleOrder WHERE PtypeID=@typeid
				--删除商品时，清空商品多条码，单位多条码信息
				DELETE FROM dbo.PType_EntryCode_Ext WHERE Ptypeid=@TypeId
				DELETE FROM dbo.PType_Units_EntryCode_Ext WHERE PtypeID = @TypeId
				--删除价格跟踪表的信息--结束--
				
				
				
				/*-------------价格表的特殊处理--开始--9.6 批量删除基础资料功能调整 文档---------------------------*/
				IF EXISTS(SELECT TOP 1 1 FROM dbo.PriceDetail WHERE Ptypeid=@typeid)
				BEGIN
 					--可以直接删除的集合
					SELECT a.PriceBillIndexID
					INTO #DirectList 
					FROM dbo.PriceDetail a 
					INNER JOIN (SELECT PriceBillIndexID FROM dbo.PriceDetail WHERE Ptypeid=@typeid) b ON a.PriceBillIndexID=b.PriceBillIndexID
					GROUP BY a.PriceBillIndexID HAVING COUNT(Ptypeid)=1
					
					IF EXISTS(SELECT TOP 1 1 FROM dbo.#DirectList )
					BEGIN
						--直接删除
						DELETE FROM dbo.PriceBillIndex		WHERE ID IN (SELECT PriceBillIndexID FROM #DirectList)
						DELETE FROM dbo.PriceDetail			WHERE PriceBillIndexID IN (SELECT PriceBillIndexID FROM #DirectList)
						DELETE FROM dbo.PriceBillIndex_Stype		WHERE PriceBillIndexID IN (SELECT PriceBillIndexID FROM #DirectList)
						--并删除对应的取价规则
						DELETE FROM dbo.PriceRulePriority WHERE PriceRuleID IN (SELECT ID FROM PriceRule WHERE PriceBillIndexID IN (SELECT PriceBillIndexID FROM #DirectList))
						DELETE FROM dbo.PriceRule_Stype WHERE PriceRuleID IN (SELECT ID FROM PriceRule WHERE PriceBillIndexID IN (SELECT PriceBillIndexID FROM #DirectList))
						DELETE FROM PriceRule WHERE PriceBillIndexID IN (SELECT PriceBillIndexID FROM #DirectList)
 					END 
					-------------------------------------
 					--可以删除明细商品的集合
 					SELECT a.PriceBillIndexID
					INTO #DelDetailList
					FROM dbo.PriceDetail a 
					INNER JOIN (SELECT PriceBillIndexID FROM dbo.PriceDetail WHERE Ptypeid=@typeid) b ON a.PriceBillIndexID=b.PriceBillIndexID
					GROUP BY a.PriceBillIndexID HAVING COUNT(Ptypeid)>1
					
					--删除对应的明细商品
					DELETE FROM dbo.PriceDetail		
					WHERE PriceBillIndexID IN (SELECT PriceBillIndexID FROM #DelDetailList) AND Ptypeid=@typeid
					
					DROP TABLE #DirectList,#DelDetailList
				END
				/*-------------价格表的特殊处理--结束-----------------------------*/

				SELECT @deleted=deleted FROM ptype WHERE typeid=@typeid
				
				--更新POS下载信息
				DECLARE @PID VARCHAR(100)

				IF @deleted=1	
					BEGIN

						--更新POS下载信息

						SELECT @PID=Pid FROM PType WHERE typeId=@TypeId
						EXEC Gp_DataSaveForPosDown '-99999','Ptype',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_Price',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_STypePrice',@PID
						
						EXEC Gp_DataSaveForPosDown '-99999','PosIsUpdateData_P',@PID
						select @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
						update PType_Price set XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@PID

						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM PType

		 				DELETE ptype WHERE typeid=@typeid 
		 															
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE PType
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM PType)
						
						
						IF len(@typeid)>5
							BEGIN
								UPDATE Ptype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
								UPDATE Ptype SET sonNum=0 WHERE typeid=LEFT(@typeid,len(@typeid)-5) AND sonNum<0				
							END
						IF len(@typeid)=5
							BEGIN
								UPDATE ptype SET sonNum=sonNum-1 WHERE typeid='00000'
								UPDATE ptype SET sonNum=0 WHERE typeid='00000' AND sonNum<0			
							END
						EXEC GP_DeleteBaseL 'P',@typeid --删除相关多级权限范围记录	
						--删除价格信息
						DELETE dbo.PType_Price WHERE PTypeID=@typeid
						
						DELETE dbo.PType_stypePrice WHERE PTypeID=@typeid
						
						
						--删除图片
						DELETE dbo.PType_Picture WHERE PTypeID=@typeid
						--删除汽配商品扩展信息
						DELETE QP_PType_Ext WHERE PTypeID=@TypeId
						--删除PType_InventoryType 关联
						--DELETE PType_InventoryType WHERE PTYPEID=@TypeId
											
						---删除所有的子节点时，更新ptype_price的XiWaMaxNumber，以便pos下载
						IF EXISTS(SELECT *FROM PType WHERE typeId=@parid AND sonnum=0)
						BEGIN
							select @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
							update PType_Price set XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@parid
						END
						
		 				RETURN 0
					END
				IF @deleted=0
					BEGIN
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM PType
						--更新POS下载信息
						SELECT @PID=Pid FROM PType WHERE typeId=@TypeId
						
						EXEC Gp_DataSaveForPosDown '-99999','Ptype',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_Price',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_STypePrice',@PID						
						EXEC Gp_DataSaveForPosDown '-99999','PosIsUpdateData_P',@PID
						
						DELETE ptype WHERE typeid=@typeid
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE PType
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM PType)
						
						--delete  from ptype_l where typeid=@typeid
						IF len(@typeid)>5
							BEGIN
								UPDATE Ptype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
								UPDATE Ptype SET sonNum=0 WHERE typeid=LEFT(@typeid,len(@typeid)-5) AND sonNum<0				
							END
						--更新父节点中的xiwamaxnumber
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM PType
						UPDATE ptype SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeid=LEFT(@typeid,len(@typeid)-5)
							
						IF len(@typeid)=5
							BEGIN
								UPDATE ptype SET sonNum=sonNum-1 WHERE typeid='00000'
								UPDATE ptype SET sonNum=0 WHERE typeid='00000' AND sonNum<0			
							END
						EXEC GP_DeleteBaseL 'P',@typeid --删除相关多级权限范围记录
						
						--删除价格信息
						DELETE dbo.PType_Price WHERE PTypeID=@typeid
						DELETE dbo.PType_stypePrice WHERE PTypeID=@typeid
						--删除图片
						DELETE dbo.PType_Picture WHERE PTypeID=@typeid
						--删除汽配商品扩展信息
						DELETE QP_PType_Ext WHERE PTypeID=@TypeId
						--设置POS产品删除标志
						EXEC Pos_A8_UpDateSystemRebuildGuid
						--删除PType_InventoryType 关联
						--DELETE PType_InventoryType WHERE PTYPEID=@TypeId
						
						---删除所有的子节点时，更新ptype_price的XiWaMaxNumber，以便pos下载
						IF EXISTS(SELECT *FROM PType WHERE typeId=@parid AND sonnum=0)
						BEGIN
							SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
							update PType_Price SET XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@parid
						END
						
						RETURN 0
					END 	
			END 
					
 		GOTO SUCCESS

		SUCCESS:
	 		--CLOSE stock_cursor
	 		--deallocate stock_cursor
	 		SELECT @parid=parid FROM ptype WHERE typeid = @typeid 
	 		SELECT @sonnum=sonnum FROM ptype WHERE typeid=@parid
	 		SELECT @sonnum=@sonnum-1
	 		IF(@sonnum<0) SET @sonnum=0
	 		UPDATE ptype SET sonnum= @sonnum WHERE typeid =@parid 
	 		RETURN 0

		ERROR1:
	 		CLOSE stock_cursor
	 		DEALLOCATE stock_cursor
	 		RAISERROR('发生错误不能%s该基本信息',16,1,@delTypeName)RETURN--RETURN -1
	END
-- ==========================================================================================
----现金流量项目删除条件
IF @dbname='Ac_CashMoneyItems'
 BEGIN
 	IF @delType=-1
			BEGIN
				BEGIN
					--单个删除时检查子节点，有 则不能删除
					IF @ifdeleteson=0
						BEGIN
							IF exists(SELECT SONNUM from Ac_CashMoneyItems where typeid=@TypeId AND SONNUM>0)
								BEGIN
									RAISERROR('有节点信息不能删除！',16,1) RETURN
								END
						END
					IF EXISTS(SELECT TOP 1 1 FROM Ac_CashMoneyItems WHERE TypeId=@TypeId AND Sysrow=1)
						BEGIN
							RAISERROR('系统默认数据，不能删除！',16,1)RETURN
						END
					IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_CashMoneyItems WHERE MATypeId=@TypeId)
						BEGIN
							RAISERROR('该信息已经使用，不能删除！',16,1)RETURN
						END
					IF EXISTS (SELECT *FROM Ac_Account WHERE MainItems=@TypeId OR AdditionItems=@TypeId)
						BEGIN
							RAISERROR('该信息已被科目使用，不能删除！',16,1)return--return -1
						END
					DELETE Ac_CashMoneyItems WHERE typeid=@typeid 
					IF len(@typeid)>5
						UPDATE Ac_CashMoneyItems SET sonNum=sonNum-1,SonCount-=1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
					IF len(@typeid)=5
						UPDATE Ac_CashMoneyItems SET sonNum=sonNum-1,SonCount-=1 WHERE typeid='00000'
						RETURN 
				END
			END
		IF @@rowcount = 0 
			BEGIN
			RAISERROR('%s该记录失败',16,1,@delTypeName)RETURN-- RETURN -2
			END 
 END
	--处理查询方案中的值
IF @delType =-1
BEGIN
DECLARE @sqls VARCHAR(5000)=''
SET @sqls = 'EXEC Gp_ReplaceSchemeDetailValue '''+@TypeID+''','' AND BaseType LIKE ''''%'+@dbname+'%'''''''
EXEC (@sqls)
END
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：	删除基本信息相关多级权限范围
-- 作    者：	cqhua
-- 2010-01-05
-- ========================================================================
CREATE         PROCEDURE GP_DeleteBaseL
(
	@table varchar(100),
	@typeid varchar(50)
)	
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

DECLARE @DBName varchar(100)
DECLARE @TableName varchar(100)

SET @DbName=CASE @table
	WHEN 'P' THEN 'PType'
	WHEN 'B' THEN 'BType'
	WHEN 'E' THEN 'Employee'
	WHEN 'K' THEN 'Stock'
	WHEN 'A' THEN 'AType'
	END

-- 处理多级权限范围数据
IF @DBName IN ('PType','Employee','BType','Stock','AType')
BEGIN
	DECLARE @Type varchar(10)
	SET @TableName = CASE @DBName
		WHEN 'PType' THEN 'PType_L'
		WHEN 'Employee' THEN 'EType_L'
		WHEN 'BType' THEN 'BType_L'
		WHEN 'Stock' THEN 'KType_L'
		WHEN 'AType' THEN 'AType_L'
		END

	SET @Type = CASE WHEN @DBName = 'PType' THEN '2'
		WHEN @DBName = 'Employee' THEN '4'
		WHEN @DBName = 'BType' AND LEFT(@TypeID,5) = '00001' THEN '0'
		WHEN @DBName = 'BType' AND LEFT(@TypeID,5) = '00002' THEN '1'
		WHEN @DBName = 'Stock' THEN '3'
		WHEN @DBName = 'AType' AND (LEFT(@TypeID,10) = '0000100003' OR LEFT(@TypeID,10) = '0000100004') THEN '5'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000400003' THEN '6'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000300003' THEN '7'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000100002' THEN '8'
		END
	DECLARE @SQL varchar(2000)	
	SET @SQL = '
		DECLARE @ETypeID varchar(50), @TypeID varchar(50), @tempTypeID varchar(50), @Flag int, @nRet int
		DECLARE Lim_Cursor CURSOR FOR
			SELECT ETypeID FROM ' + @TableName + ' WHERE Flag=1 AND  TypeID = ''' + @TypeID + '''
		OPEN Lim_Cursor
		FETCH NEXT FROM Lim_Cursor INTO @ETypeID
		WHILE @@FETCH_STATUS=0
		BEGIN
			EXEC @nRet = GP_UserRange_Del @ETypeID,' + @Type + ',''' + @TypeID + ''',0
			FETCH NEXT FROM Lim_Cursor INTO @ETypeID
		END
		CLOSE Lim_Cursor
		DEALLOCATE Lim_Cursor
	'
	EXEC(@SQL)
END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_DeleteBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_DeleteBill]
GO







CREATE      PROCEDURE [Gp_DeleteBill]
(
	@BillNumberId  numeric(18,0)
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM billindex WHERE ifcheck='t' and [BillNumberId]  = @BillNumberId)
	RETURN -1

-- 删除维修受理单  chen_qihua 2004-08-30
DECLARE @Billtype numeric(4,0)
SELECT @Billtype = billtype FROM Billindex WHERE BillNumberID = @BillNumberId
IF @Billtype =157
BEGIN
	UPDATE RepairEngage SET Stat =1 Where BillnumberID in (SELECT EngageBillID FROM RepairDeal WHERE BillNumberID = @BillNumberId)
	DELETE FROM RepairDeal WHERE BillnumberID = @BillNumberId
END
-- end 

--处理按单结算的问题
DELETE FROM CompleteTotal where (GoodsBillID=@BillNumberId  or MoneyBillID=@BillNumberId) AND BillType=@Billtype 

--处理按商品结算
DELETE FROM CompleteGoodTotal WHERE(GoodsBillID=@BillNumberId  or MoneyBillID=@BillNumberId) AND BillType=@Billtype

-- 处理按品牌结算
DELETE FROM dbo.CompleteBrandarTotal WHERE (GoodsBillID=@BillNumberId OR MoneyBillID=@BillNumberId) AND BillType=@Billtype

-- 删除发票
DELETE FROM invoiceBill WHERE BillNumberID = @BillNumberID

--删除快修单
DELETE FROM Billindex_CarRepair WHERE BillNumberID = @BillNumberID

--删除附件
DELETE FROM BillAttachFiles WHERE BillNumberId = @BillNumberId and BillType not in(404,405)

--删除过账户信息
DELETE FROM BillMulAccount WHERE BillNumberId = @BillNumberId AND BillType=@Billtype

--删除过账品牌信息
DELETE FROM BillMulBrand WHERE BillNumberId = @BillNumberId AND BillType=@Billtype

--删除销售出库单时，删除调用电脑配置单的记录
IF EXISTS (SELECT *FROM BillIndex WHERE BillNumberId=@BillNumberId AND BillType='11')
BEGIN
	DELETE DiyBillTypePSaleTypeID WHERE SalebillNumberId=@BillNumberId
END

--删除单据（最后执行这步骤）
DELETE FROM billindex WHERE billnumberid=@BillNumberId and ifcheck = 'f'

IF @@ROWCOUNT = 0 
	RETURN -2 
ELSE 
	RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2017-11-26
	描述：批量删除品牌ID
*/
CREATE PROCEDURE Gp_DeleteBrandarCommodityParId
(
	@TypeId			VARCHAR(500)			--品牌ID	
)
AS
SET NOCOUNT ON

--先把父节点全部收集
CREATE TABLE #BrandarCommodity
(
	TypeId			VARCHAR(50)
)
INSERT INTO #BrandarCommodity
( 
	TypeId 
)
SELECT	TypeId 
FROM	brandar_Commodity
WHERE	TypeId LIKE @TypeId + '%'
		AND SonNum <> 0
		
SELECT * FROM #BrandarCommodity	

DECLARE @brandTypeId	VARCHAR(50),
		@brandParId		VARCHAR(50),
		@sonNum			INT

DECLARE TmpCursor CURSOR FOR
	SELECT TypeId,ParId,SonNum FROM dbo.brandar_Commodity WHERE TypeId LIKE @TypeId + '%' ORDER BY typeid DESC
	
OPEN TmpCursor

FETCH NEXT FROM TmpCursor INTO @brandTypeId,@brandParId,@sonNum

WHILE @@FETCH_STATUS = 0
BEGIN
	IF @sonNum = 0
	BEGIN
		EXEC Gp_DeleteBrandarTypeId @brandTypeId,@brandParId
	END
	
	FETCH NEXT FROM TmpCursor INTO @brandTypeId,@brandParId,@sonNum
END

CLOSE TmpCursor
DEALLOCATE TmpCursor

--最后把没有子节点的父节点全部删除
DELETE FROM dbo.brandar_Commodity 
WHERE	TypeId IN 
		(
			SELECT	T.TypeId 
			FROM	#BrandarCommodity T,
					brandar_Commodity B
			WHERE	T.TypeId = B.TypeId
					AND B.SonNum = 0
		)

SELECT TOP 1 * FROM brandar_Commodity

DROP TABLE #BrandarCommodity

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2017-11-26
	描述：批量删除品牌ID
*/
CREATE PROCEDURE Gp_DeleteBrandarTypeId
(
	@TypeId			VARCHAR(50),			--品牌ID	
	@ParId			VARCHAR(50)				--父类ID
)
AS
SET NOCOUNT ON

--子节点直接删除
DECLARE @Re			INT,
		@errMsg		VARCHAR(500)

EXEC @Re = Web_BrandarCommondityCanDel @TypeId,@errMsg OUTPUT

IF @Re = 0
BEGIN
	DELETE FROM dbo.brandar_Commodity WHERE TypeId = @TypeId
	
	UPDATE dbo.brandar_Commodity SET SonNum = SonNum - 1 WHERE TypeId = @ParId	
	
	--现金费用单 直接删除相关品牌信息
	UPDATE MoneyBill SET BrandarTypeId='' WHERE BrandarTypeId=@TypeId 
	AND EXISTS(SELECT * FROM BillIndex B WHERE B.BillNumberId=BillNumberId AND B.BillType=158)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-16
	描述：删除汽车基本信息表中的一条记录
*/

CREATE PROCEDURE GP_DeleteCarInfo
(
	@typeid  varchar(50)  --汽车基本信息表唯一标识
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE @Count1 int,
			@Count2 int
			
	SELECT @Count1=COUNT(*) FROM CM_CarUseBill WHERE CarId=@typeid
	SELECT @Count2=COUNT(*) FROM CM_FeeIndex WHERE CarId=@typeid
	--判断:如果使用登记单上没有记录且费用单上也没有记录
	IF @Count1=0 AND @Count2=0
		BEGIN
			DELETE FROM CM_CarInfo WHERE TypeId=@typeid  --删除车辆基本信息
		END
	ELSE
		RETURN -1



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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















/****** Object:  Stored Procedure dbo.Gp_DeleteCheckStock    Script Date: 2002-6-20 10:14:46 ******/

CREATE  PROCEDURE Gp_DeleteCheckStock 
( @ktypeid varchar(100))
--@encode$--
AS
SET NOCOUNT ON
delete from CheckStock where ktypeid=ltrim(@ktypeid)
if @@rowcount=0 return -1 else return 0
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：杨俊
	日期：2014-05-20
	描述：提成方案--删除
-------------------------------------------*/
CREATE PROCEDURE Gp_DeleteCommissionScheme
(
	@BillNumberId  INT
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
-----------------------------------------------------------------------------------------------------------------------------
--是否已审核
IF((SELECT BillState FROM CommissionScheme WHERE billnumberid = @BillNumberId) = 2)
	RETURN -2

DECLARE @RowCount int
BEGIN TRAN

--改回提成规则状态
UPDATE CommissionRule SET UseState = 1 
FROM CommissionRule AS A 
INNER JOIN CommissionScheme AS B ON(A.BillNumberId = B.CommissionRuleID)
WHERE B.BillNumberId = @BillNumberId

--改回参照计划提成状态
UPDATE ReferencePlanCommission SET UseState = 1 
FROM ReferencePlanCommission AS A 
INNER JOIN CommissionScheme AS B ON(A.BillNumberId = B.ReferencePlanID)
WHERE B.BillNumberId = @BillNumberId

--删除提成规则
DELETE FROM CommissionScheme WHERE BillNumberId = @BillNumberId
SET @RowCount = @@rowcount
IF @RowCount = 0 
BEGIN
	ROLLBACK TRAN
	RETURN -1 
END
ELSE
BEGIN
	--删除提成规则分支机构
	DELETE FROM CommissionSchemeStype WHERE BillNumberId = @BillNumberId
	SET @RowCount = @@rowcount
	IF @RowCount = 0 
	BEGIN
		ROLLBACK TRAN
		RETURN -1
	END
END
COMMIT TRAN	-- 提交事务
RETURN 0
-----------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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






CREATE  PROCEDURE GP_DeleteCRMLinkMan
(
@intId int
)
--@encode$--
AS
SET NOCOUNT ON 

DELETE CRM_LinkMan WHERE [Id] = @intId

DELETE FROM CRM_LinkManShared WHERE CRMLinkManID = @intId

IF EXISTS( SELECT * FROM CRM_Btype WHERE LinkManId1 = @intId )
BEGIN
 UPDATE CRM_Btype
 SET
 [LinkManId1]='',
 [LinkMan1]='',
 [LinkSex1]='',
 [LinkBirthDay1]='',
 [LinkJob1]='',
 [LinkCall1]='',
 [LinkTel1]='',
 [LinkMobile1]='',
 [LinkEMail1]='',
 [LinkPost1]='',
 [LinkAddress1]='',
 [LinkComment1]=''
 WHERE
  LinkManId1 = @intId
END
IF EXISTS( SELECT * FROM CRM_Btype WHERE LinkManId2 = @intId )
BEGIN
 UPDATE CRM_Btype
 SET
 [LinkManId2]='',
 [LinkMan2]='',
 [LinkSex2]='',
 [LinkBirthDay2]='',
 [LinkJob2]='',
 [LinkCall2]='',
 [LinkTel2]='',
 [LinkMobile2]='',
 [LinkEMail2]='',
 [LinkPost2]='',
 [LinkAddress2]='',
 [LinkComment2]=''
 WHERE
  LinkManId2 = @intId
END

 





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_Deleted_Invalid_VoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_Deleted_Invalid_VoucherBill
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	作废凭证删除
-- 时间：	2013-06-26
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_Deleted_Invalid_VoucherBill
(
	@BillNumberId	VARCHAR(50)=''			-- 单据ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @ErrorCount		INT=0,
		@vouchertype	INT
	
	 
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE BillNumberId=@BillNumberId) --判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN
END

SELECT @vouchertype=VoucherType FROM Ac_Voucher WHERE BillNumberId=@BillNumberId

--DELETE FROM PrintRecord WHERE BillNumberId=@BillNumberId AND BillType=210--打印记录
UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId=@BillNumberId AND BillType=210

SET @ErrorCount+=@@ERROR

UPDATE BillIndex SET TallyId='' 
FROM BillIndex bi
INNER JOIN Ac_GoodsBill_VoucherBill vi ON VI.GoodsBillId=bi.BillNumberId
WHERE vi.VourchBillId=@BillNumberId--更新单据表中对应的Id记账人为空
SET @ErrorCount+=@@ERROR

DELETE FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId=@BillNumberId--物流单据和会计凭证对照表
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId=@BillNumberId--删除凭证主表
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher_Bill WHERE BillNumberId=@BillNumberId--删除凭证明细
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher WHERE BillNumberId=@BillNumberId--删除凭证主表
SET @ErrorCount+=@@ERROR

IF(@vouchertype=3 OR @vouchertype=4)--3.业务单据生成
	BEGIN
		DELETE FROM Ac_CommissionBill_VoucherBill WHERE VourchBillId=@BillNumberId
		SET @ErrorCount+=@@ERROR
		DELETE FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId=@BillNumberId
		SET @ErrorCount+=@@ERROR
	END
IF(@vouchertype=5 OR @vouchertype=6)--4. 固定资产系统生成
	BEGIN
		DELETE FROM Ac_Provision_Voucher WHERE VoucherId=@BillNumberId
		SET @ErrorCount+=@@ERROR
	END

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='删除选中作废凭证错误，请确认！'
		RAISERROR(@MSG2,16,1)
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DeletedAc_Assist_CheckItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_DeletedAc_Assist_CheckItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_Assist_CheckItems 删除指定辅助核算类型数据
-- 时间：	2015-09-29
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_DeletedAc_Assist_CheckItems
(
	@AscIds		INT		--类型ID
)

--@encode$--

AS
SET NOCOUNT ON
DECLARE 
	@Error		INT=0,
	@FullName	VARCHAR(200)=''
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Assist_CheckItems WHERE AscIds=@AscIds)
	BEGIN
		RAISERROR('该条信息已不存在，请确认!',16,1) RETURN 
	END
	
--判断是否被使用
IF EXISTS(SELECT TOP 1 1 FROM Ac_Assist_CheckItemsDetail WHERE Ascids=@AscIds AND ParId<>'root')
	BEGIN
		RAISERROR('此核算类型已经存在核算项目明细，不允许删除！',16,1) RETURN 
	END
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE Ascids=@AscIds)
	BEGIN
		RAISERROR('此类型已被科目使用，不允许删除！',16,1) RETURN 
	END
	
--类别名称
SELECT @FullName=FullName FROM Ac_Assist_CheckItems WHERE AscIds=@AscIds

BEGIN TRAN
--删除指定类型数据
DELETE FROM Ac_Assist_CheckItems WHERE AscIds=@AscIds
SET @Error+=@@ERROR
--删除明细父级节点
DELETE FROM Ac_Assist_CheckItemsDetail WHERE AscIds=@AscIds
SET @Error+=@@ERROR

--修改自定义公式
UPDATE UFO_DefineFunctions SET Format=REPLACE(Format,@FullName+'='+@FullName+'编号%','') WHERE Code IN('QC','QM','XFS','LFS','NCJ','NCD','QMJ','QMD')
SET @Error+=@@ERROR

IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN 
	
RETURN @@ERROR

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DeletedAc_Assist_CheckItemsDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_DeletedAc_Assist_CheckItemsDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_Assist_CheckItems 删除指定辅助核算类型数据
-- 时间：	2015-09-29
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_DeletedAc_Assist_CheckItemsDetail
(
	@TypeID		VARCHAR(50)		--类型ID
)

--@encode$--

AS
SET NOCOUNT ON

DECLARE 
	@Error		INT=0,
	@IsUsed		INT,			--是否被使用过
	@ParId		VARCHAR(50)=''	--父节点
	
SET @Error=0

--=============================================判断该条信息是否满足被删除的条件【BEGIN】===============================================
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Assist_CheckItemsDetail WHERE TypeId=@TypeID)
	BEGIN
		RAISERROR('该条信息已不存在，请确认!',16,1) RETURN 
	END
IF EXISTS(SELECT TOP 1 1 FROM Ac_Assist_CheckItemsDetail WHERE ParId=@TypeID)
	BEGIN
		RAISERROR('该明细存在下级明细，请先删除下级明细！',16,1) RETURN 
	END
	
SELECT @IsUsed=DBO.Fn_GetIsUsedAssistDetails(@TypeID)
IF @IsUsed=1
	BEGIN
		RAISERROR('该明细正在使用！',16,1) RETURN 
	END

--=============================================判断该条信息是否满足被删除的条件【END】   ===============================================
BEGIN TRAN
SELECT @ParId=ParId FROM Ac_Assist_CheckItemsDetail WHERE TypeId=@TypeID
--删除指定类型数据
DELETE FROM Ac_Assist_CheckItemsDetail WHERE TypeId=@TypeID
SET @Error+=@@ERROR

--修改父级 子级个数
UPDATE Ac_Assist_CheckItemsDetail SET SonNum-=1 WHERE TypeId=@ParId
SET @Error+=@@ERROR

IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN 

RETURN @Error

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_DeletedAcVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_DeletedAcVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查询删除
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_DeletedAcVoucherBill
(
	@BillNumberId	VARCHAR(50)=''			-- 单据ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@fchecked		VARCHAR(2)='',
	@recheckid		VARCHAR(2)='',
	@ifcheck		VARCHAR(2)='',
	@ErrorCount		INT=0--审核 复核 过账 凭证类型
	
SELECT 
	@fchecked=ISNULL(FChecked,''),
	@recheckid=ISNULL(ReCheckId,''),
	@ifcheck=ISNULL(IfCheck,'')
FROM Ac_Voucher vc
WHERE vc.BillNumberId=@BillNumberId
		 
IF @@ROWCOUNT = 0--判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN
END

IF(@fchecked='1' OR @recheckid <>'' OR @ifcheck='t')
	BEGIN
		RAISERROR('您选择的凭证已经审核/复核/记账！请确认后重试！',16,1)
		RETURN
	END

--将DELETE 更改为UPDATE
--DELETE FROM PrintRecord WHERE BillNumberId=@BillNumberId AND BillType=210--打印记录
UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId=@BillNumberId AND BillType=210
SET @ErrorCount+=@@ERROR

UPDATE BillIndex SET TallyId='' 
FROM BillIndex bi
INNER JOIN Ac_GoodsBill_VoucherBill vi ON VI.GoodsBillId=bi.BillNumberId
WHERE vi.VourchBillId=@BillNumberId--更新单据表中对应的Id记账人为空
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId=@BillNumberId--物流单据和会计凭证对照表
SET @ErrorCount+=@@ERROR

UPDATE ReceiptBillIndex SET TallyId='' 
FROM ReceiptBillIndex bi
INNER JOIN Ac_ReceiptBill_VoucherBill vi ON VI.GoodsBillId=bi.BillNumberId
WHERE vi.VourchBillId=@BillNumberId--更新单据表中对应的Id记账人为空
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_ReceiptBill_VoucherBill WHERE VourchBillId = @BillNumberId  --暂估发票单据和会计凭证对照表
SET @ErrorCount+=@@ERROR

UPDATE Coupon_BillIndex SET TallyId='' 
FROM Coupon_BillIndex bi
INNER JOIN Ac_CouponBill_VoucherBill vi ON VI.CouponBillId=bi.BillNumberId
WHERE vi.VourchBillId=@BillNumberId--更新优惠券表中对应的Id记账人为空
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_CouponBill_VoucherBill WHERE VourchBillId = @BillNumberId  --优惠券单据和会计凭证对照表
SET @ErrorCount+=@@ERROR

DELETE FROM Ac_DeliveryBill_VoucherBill WHERE VourchBillId = @BillNumberId  --门店配送单和会计凭证对照表
SET @ErrorCount+=@@ERROR
	
DELETE FROM Ac_Voucher_Bill_CashMoneyItems WHERE BillNumberId=@BillNumberId
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId=@BillNumberId--删除凭证辅助核算表
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher_Bill WHERE BillNumberId=@BillNumberId--删除凭证明细
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher WHERE BillNumberId=@BillNumberId--删除凭证主表
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_CommissionBill_VoucherBill WHERE VourchBillId=@BillNumberId
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Provision_Voucher WHERE VoucherId=@BillNumberId
SET @ErrorCount+=@@ERROR		

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='删除凭证单据错误，请确认！'
		RAISERROR(@MSG2,16,1)
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_DeletedAll_Invalid_VoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DeletedAll_Invalid_VoucherBill
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	作废凭证全部删除
-- 时间：	2013-06-26
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_DeletedAll_Invalid_VoucherBill
(
	@StypeID				VARCHAR(50),	--分支机构ID
	@OperatorID				VARCHAR(50)		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @ErrorCount INT=0

--所有作废的凭证
SELECT BillNumberId,VoucherType
INTO #BillNumberId
FROM Ac_Voucher 
WHERE 
	FChecked=-1
	AND STypeId=@StypeID
	
--将DELETE 更改为UPDATE
--DELETE FROM PrintRecord
--FROM PrintRecord P
--INNER JOIN #BillNumberId B ON B.BillNumberId=P.BillNumberId AND BillType=210--打印记录
UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId IN (SELECT BillNumberId FROM #BillNumberId) AND BillType=210

SET @ErrorCount+=@@ERROR

UPDATE BillIndex SET TallyId='' 
FROM BillIndex bi
INNER JOIN Ac_GoodsBill_VoucherBill vi ON VI.GoodsBillId=bi.BillNumberId
INNER JOIN #BillNumberId B ON B.BillNumberId=vi.VourchBillId --更新单据表中对应的Id记账人为空
SET @ErrorCount+=@@ERROR

DELETE FROM Ac_GoodsBill_VoucherBill 
FROM Ac_GoodsBill_VoucherBill AGV
INNER JOIN #BillNumberId B ON B.BillNumberId=AGV.VourchBillId --物流单据和会计凭证对照表
SET @ErrorCount+=@@ERROR

DELETE FROM Ac_Voucher_Bill_Assist_CheckItems 
FROM Ac_Voucher_Bill_Assist_CheckItems CI
INNER JOIN #BillNumberId B ON B.BillNumberId=CI.BillNumberId --删除凭证主表
SET @ErrorCount+=@@ERROR

DELETE FROM Ac_Voucher_Bill
FROM Ac_Voucher_Bill Bill
INNER JOIN #BillNumberId B ON B.BillNumberId=Bill.BillNumberId--删除凭证明细
SET @ErrorCount+=@@ERROR

DELETE FROM Ac_Voucher 
FROM Ac_Voucher AC
INNER JOIN #BillNumberId B ON B.BillNumberId=AC.BillNumberId--删除凭证主表
SET @ErrorCount+=@@ERROR

--=================================恢复相应单据未生成凭证状态=================================
--业务单据生成
DELETE FROM Ac_GoodsBill_VoucherBill
FROM Ac_GoodsBill_VoucherBill GB
INNER JOIN #BillNumberId B ON B.BillNumberId=GB.VourchBillId AND (B.VoucherType=3 OR B.VoucherType=4)
SET @ErrorCount+=@@ERROR

DELETE FROM Ac_CommissionBill_VoucherBill
FROM Ac_CommissionBill_VoucherBill GB
INNER JOIN #BillNumberId B ON B.BillNumberId=GB.VourchBillId AND (B.VoucherType=3 OR B.VoucherType=4)
SET @ErrorCount+=@@ERROR

--暂估发票
DELETE FROM Ac_ReceiptBill_VoucherBill
FROM Ac_ReceiptBill_VoucherBill GB
INNER JOIN #BillNumberId B ON B.BillNumberId=GB.VourchBillId
SET @ErrorCount+=@@ERROR


--固定资产系统生成
DELETE FROM Ac_Provision_Voucher
FROM Ac_Provision_Voucher PB
INNER JOIN #BillNumberId B ON B.BillNumberId=PB.VoucherId AND (B.VoucherType=5 OR B.VoucherType=6)
SET @ErrorCount+=@@ERROR
IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='删除全部作废凭证错误，请确认！'
		RAISERROR(@MSG2,16,1)
	END


DROP TABLE #BillNumberId
RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DeletedAssetsCategory]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DeletedAssetsCategory
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-资产类别 删除操作
-- 时间：2013-05-15
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Gp_DeletedAssetsCategory
(
	@OperatorId			VARCHAR(50),		--操作人
	@ID					INT				--ID	
)
--@encode$--

AS
SET NOCOUNT ON 

DELETE FROM Ac_AssetsCategory WHERE Id=@ID

IF(@@ERROR<>0)
	BEGIN
		RAISERROR('信息删除失败！',16,1) RETURN -1
	END
ELSE 
	RETURN 1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DeletedBillHistory]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DeletedBillHistory
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：资产变更记录查询 删除选中历史记录
-- 时间：2013-07-03
-- 作者：glj	
-- ========================================================================
CREATE PROC Gp_DeletedBillHistory
(
	@IDStr			VARCHAR(MAX),	--ID字符串
	@BillType		INT,			--变更类型 -1:计提减值准备 -2:部门转移
	@OperatorID		VARCHAR(50)		--操作员
)
--@encode$--

AS
SET NOCOUNT ON 

DECLARE
	@ID				INT,			--历史记录ID
	@CardId			INT,			--资产卡片ID
	@BusinessDate	DATETIME,		--业务时间
	@OperationDate	DATETIME,		--操作时间
	@CardUserCode	VARCHAR(26),
	@STypeID		VARCHAR(50),	--当前分支机构
	@DTypeId		VARCHAR(50),	--部门
	@LocationId		INT,			--存放地点
	@DisATypeId		VARCHAR(50),	--折旧分配科目
	@ChangeValue	 NUMERIC(24, 10) ,	--计提减值准备金额
	@IfRecalculate	INT,			--是否重算
	@BillNumberID	NUMERIC(18,0),	--凭证ID
	@ErrorMsg		VARCHAR(500),	--红冲业务凭证时返回出错信息
	@StarDate		DATETIME,	--当前分支机构会计期间开始时间
	@BillCode		VARCHAR(200),	--单据编号
	@I				INT=1,
	@RowCount		INT=0
	
--根据需求规则排序数据
CREATE TABLE #Temp(NId INT IDENTITY(1,1),ID INT,CardId INT,BusinessDate DATETIME,BillType INT,OperationDate DATETIME)--创建临时表 
IF(@BillType=-1)
	BEGIN
		INSERT INTO #Temp(ID,CardId,BusinessDate,BillType,OperationDate)
		SELECT
			 D.Id,
			 D.CardId,
			 D.BusinessDate,
			 -2 BillType,
			 H.OperationDate
		FROM Ac_ProvisionForImpairment D
		INNER JOIN f_split(@IDStr,',') F ON F.a=D.Id
		LEFT JOIN Ac_AssetsCards_History H ON H.BILLID = D.ID
		WHERE H.BILLTYPE = -1
		ORDER BY D.BusinessDate DESC,D.Id DESC
		SELECT @RowCount=@@ROWCOUNT
	END
ELSE IF(@BillType=-2)
	BEGIN
		INSERT INTO #Temp(ID,CardId,BusinessDate,BillType,OperationDate)
		SELECT
			 D.Id,
			 D.CardId,
			 D.BusinessDate,
			 -2 BillType,
			 H.OperationDate
		FROM Ac_AssetsModifyRecords D
		INNER JOIN f_split(@IDStr,',') F ON F.a=D.Id
		LEFT JOIN Ac_AssetsCards_History H ON H.BILLID = D.ID
		WHERE H.BILLTYPE = -2
		ORDER BY D.BusinessDate DESC,D.Id DESC
		SELECT @RowCount=@@ROWCOUNT
	END	
	
WHILE(@I<=@RowCount)
	BEGIN
		SELECT @ID=ID,@CardId=CardId,@BusinessDate=BusinessDate,@OperationDate = OperationDate FROM #Temp WHERE NId=@I
		--卡片编号
		SELECT @CardUserCode=UserCode,@STypeID=STypeId FROM Ac_AssetsCards  WHERE Id=@CardId

		--判断是否已经做过减少单
		IF EXISTS(SELECT TOP 1 1 FROM billindex I INNER JOIN AssetIncDecBill B ON B.billnumBerid = I.billnumberid WHERE B.AssetCardId=@CardId AND I.BillType=213 AND I.IfCheck = 't' AND I.RedWord = 0)
			BEGIN
				RAISERROR('资产编号 %s 已进行过减少处理，不能进行删除！',16,1,@CardUserCode)
				RETURN
			END
			
		--判断是否存在业务日期大于本单据日期的记录
		IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards_History WHERE (BusinessDate>@BusinessDate OR (BusinessDate=@BusinessDate AND OperationDate>@OperationDate)) AND AssertsCardId=@CardId AND BillType<>-3)
			BEGIN
				RAISERROR('资产编号 %s 在本单据日期之后已有操作记录，不能进行删除！',16,1,@CardUserCode)
				RETURN
			END
		--判断业务时间是否小于当前分支机构会计期间
		IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeID)
			SELECT @StarDate=FBegin FROM Ac_Period P INNER JOIN Ac_AccountsPeroid_Stype  S ON S.FPeriod=P.FPeriod AND S.FYear=P.FYear WHERE s.Stypeid = @STypeID
		ELSE
			BEGIN
				SELECT @StarDate=FBegin FROM Ac_Period WHERE FPeriod=(SELECT SubValue FROM sysdata WHERE SubName='FPeriod') AND FYear=(SELECT SubValue FROM sysdata WHERE SubName='fyear')
			END		
			
		IF(@BusinessDate<@StarDate)
			BEGIN
				RAISERROR('选中信息中有业务时间小于当前会计期间的记录不允许删除,请确认！',16,1)
				RETURN 
			END

		--计提减值准备
		IF @BillType=-1 
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Provision_Voucher WHERE SourceId=@ID AND SourceType=1)
					BEGIN
						RAISERROR('选中信息中有已经生成凭证的记录不允许删除,请确认！',16,1)
						RETURN 
					END
				
				--删除时先清除掉存在于当前单据业务日期之后的折旧计划变更单
				DELETE FROM Ac_AssetsCards_History 
				WHERE 
					BusinessDate>@BusinessDate 
					AND AssertsCardId=@CardId 
					AND  BillType=-3
					
				--删除折旧计划变更记录
				DELETE FROM Ac_DepreciationAlteration 
				WHERE 
					CardId=@CardId 
					AND BusinessDate>@BusinessDate
				
				SELECT @ChangeValue=DevalueReady,@IfRecalculate=IfRecalculate,@BillNumberID=BillnumberId FROM Ac_ProvisionForImpairment WHERE Id=@ID
				
				--得到要删除业务单据的编号	
				SELECT @BillCode=BillCode FROM BillIndex WHERE BillNumberId=@BillNumberID
				
				 EXEC Gp_Zc_RedWord @BillNumberID,@OperatorID,0,@ErrorMsg,'删除计提减值准备时红冲单据'
				IF ISNULL(@ErrorMsg,'')=''
					BEGIN
						DELETE FROM AccountCredence 
						FROM AccountCredence AC 
						INNER JOIN BillIndex B ON B.BillNumberId=AC.BillNumberID AND B.BillCode=@BillCode
						
						DELETE FROM BillIndex WHERE BillCode=@BillCode
					END
				ELSE
					BEGIN
						RAISERROR('选中信息中有信息删除失败,请确认！',16,1)
						RETURN
					END
				
				--删除计提减值准备 变更记录
				DELETE Ac_ProvisionForImpairment WHERE Id=@ID
				
				--更新恢复卡片减值准备值
				UPDATE dbo.AC_AssetsCards SET DevalueReady-=@ChangeValue,NetValue+=@ChangeValue WHERE Id=@CardID
				
				--重新计算
				IF @IfRecalculate=1
					EXEC Gp_ReCreateDepreciationPlan @CardId,0

			END
			
		--部门转移
		IF @BillType=-2
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Provision_Voucher WHERE SourceId=@ID AND SourceType=2)
					BEGIN
						RAISERROR('选中信息中有已经生成凭证的记录不允许删除,请确认！',16,1)
						RETURN 
					END
				
				--得到删除记录之前的原信息，恢复卡片信息
				SELECT TOP 1 @DTypeId=OldDTypeId,@LocationId=OldLocationId,@DisATypeId=OldDisATypeId  FROM Ac_AssetsModifyRecords WHERE Id=@ID
				
				--删除变更记录
				DELETE Ac_AssetsModifyRecords WHERE Id=@ID
				
				--卡片信息
				UPDATE Ac_AssetsCards SET DTypeid=@DTypeId,LocationId=@LocationId,DisATypeId=@DisATypeId WHERE Id=@CardId
				
				--折旧表的影响
				UPDATE Ac_DepreciationPlan SET DTypeid=@DTypeId,LocationId=@LocationId,DisATypeId=@DisATypeId WHERE AssetCardId=@CardId AND PlanState=0

				
			END

		--删除历史卡片记录
		DELETE FROM Ac_AssetsCards_History WHERE BillId=@ID AND BillType=@BillType
		
		SET @I+=1
	END
DROP TABLE #Temp
RETURN -1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE   PROCEDURE [Gp_DeleteDetail]
(
 @BillNumberId  int,
 @DbName varchar(50)
)
--@encode$--
AS 
SET NOCOUNT ON
declare @Sql   varchar (500)
select @sql ='delete from '+@DbName+' where billnumberid='+convert(varchar(15),@BillNumberId)
exec(@Sql)
if @@rowcount=0 or @@error<>0
--RAISERROR('删除单据发生错误',16,1)
RETURN -1




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_DeletedFixedReasonForChange]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].GP_DeletedFixedReasonForChange
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	删除指定变更原因
-- 时间：	2016-05-12
-- 作者：	lxl
-- ========================================================================
CREATE PROC GP_DeletedFixedReasonForChange
(
	@NId			INT			--变更原因ID
	
)
--@encode$--
AS
SET NOCOUNT ON 

IF EXISTS(SELECT Sysrow FROM Base_FixedReasonForChange WHERE NID=@NID and Sysrow=1)
	BEGIN
		RAISERROR('系统预制数据,不允许删除！',16,1) RETURN
	END
DECLARE 
	@IsUsed		INT=0,	--是否被使用
	@Error		INT=0	--再删除过程中是否报错
SELECT @IsUsed=dbo.Fn_GetIsUse_Items(@NId,110) 
IF(@IsUsed=1)
	BEGIN
		RAISERROR('该信息已被使用,不允许删除！',16,1) RETURN
	END
	
BEGIN TRAN 	
DELETE FROM Base_FixedReasonForChange WHERE NID=@NId
SET @Error+=@@ERROR

DELETE FROM Base_FixedReasonForChangeDetails WHERE TID=@NId	
SET @Error+=@@ERROR

IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_DeletedInventoryType]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].GP_DeletedInventoryType
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	删除指定存货类型
-- 时间：	2016-04-27
-- 作者：	glj
-- ========================================================================
CREATE PROC GP_DeletedInventoryType
(
	@NId			INT			--存货类型ID
	
)
--@encode$--
AS
SET NOCOUNT ON 

IF EXISTS(SELECT TOP 1 1 FROM Base_InventoryType WHERE NID=@NId AND Sysrow=1)
	BEGIN
		RAISERROR('系统预制数据,不允许删除！',16,1) RETURN
	END
DECLARE 
	@IsUsed		INT=0,	--是否被使用
	@Error		INT=0	--再删除过程中是否报错
SELECT @IsUsed=dbo.Fn_GetIsUse_Items(@NId,100) 
IF(@IsUsed=1)
	BEGIN
		RAISERROR('该信息已被使用,不允许删除！',16,1) RETURN
	END
	
BEGIN TRAN 	
DELETE FROM Base_InventoryType WHERE NID=@NId
SET @Error+=@@ERROR

DELETE FROM Base_InventoryTypeDetails WHERE TID=@NId	
SET @Error+=@@ERROR

IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_DeletedTe_Bank]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DeletedTe_Bank
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	删除出纳管理-金融机构
-- 时间：	2014-05-15
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_DeletedTe_Bank
(
	@Id		INT		--ID
)
--@encode$--
AS
SET NOCOUNT ON
IF NOT EXISTS(SELECT TOP 1 1 FROM Te_Bank WHERE Id=@Id)
BEGIN
	RAISERROR('该信息已经不存在,不能执行该操作！',16,1) RETURN
END
	
IF EXISTS(SELECT TOP 1 1 FROM Te_Bank WHERE Id=@Id AND IsSys=1)
BEGIN
	RAISERROR('系统默认数据，不执行该操作！',16,1) RETURN
END

IF EXISTS(SELECT TOP 1 1 FROM Te_BankAccount WHERE BankId=@Id)--出纳管理-银行账户
BEGIN
	RAISERROR('该金融机构已经使用,不能删除！',16,1) RETURN
END

DELETE FROM Te_Bank WHERE Id=@Id
IF @@ERROR<>0
BEGIN
	RAISERROR('执行异常,信息删除失败！',16,1)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_DeletedTe_BankAccount]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DeletedTe_BankAccount
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	删除出纳管理-银行账户
-- 时间：	2014-05-09
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_DeletedTe_BankAccount
(
	@Id		INT		--ID
)
--@encode$--
AS
SET NOCOUNT ON
IF NOT EXISTS(SELECT TOP 1 1 FROM Te_BankAccount WHERE Id=@Id)
BEGIN
	RAISERROR('该信息已经不存在,不能执行该操作！',16,1) RETURN
END	

IF(SELECT dbo.F_GetIsUse_Te(@Id,1))=1
	BEGIN
		RAISERROR('该银行账户已被使用,不能删除！',16,1) RETURN
	END

IF (SELECT ISNULL(SUM(ISNULL(FEndBalance,0)),0) FROM Te_Balance WHERE AccountId=@Id AND BUId IN(2,3))<>0
	BEGIN
		RAISERROR('该银行账户还有余额,不能删除！',16,1) RETURN
	END

DELETE FROM Te_BankAccount WHERE Id=@Id
IF @@ERROR<>0
	BEGIN
		RAISERROR('执行异常,信息删除失败！',16,1) 
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：
	日期：2016-06-16
	描述：系统配置取消勾选实物库存删除相关数据
-------------------------------------------*/
CREATE PROCEDURE  Gp_DeleteFactStockData

--@encode$--
AS
SET NOCOUNT ON

DELETE  FactStocks
DELETE  FactStocks_Qty
DELETE  dbo.gp_FactPtypeSerial
DELETE FactInOut
DELETE  FactIndex WHERE IsIni=1

--库存期初  
DELETE dbo.IniFactStocks
DELETE dbo.IniFactStocks_Qty
DELETE dbo.gp_iniFactPtypeSerial

CREATE TABLE #bill(billnumberid INT)

INSERT INTO #bill( billnumberid )
	SELECT billnumberid 
	FROM  FactIndex 
	WHERE draft=1

DELETE FactIndex WHERE BillNumberId IN(SELECT BillNumberId FROM #bill)

DELETE FactDepotInOut  WHERE BillNumberId IN(SELECT BillNumberId FROM #bill)

DELETE FactDepotAllot  WHERE BillNumberId IN(SELECT BillNumberId FROM #bill)

DROP TABLE #bill

RETURN 1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-17
	描述：删除费用基本信息表中的一条记录
*/

CREATE PROCEDURE GP_DeleteFeeType
(
	@feetypeid  int  --费用基本信息表唯一标识
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE @Count int
			
	SELECT @Count=COUNT(*) FROM CM_FeeBill WHERE FeetypeId=@feetypeid
	--判断:如果使用登记单上没有记录且费用单上也没有记录
	IF @Count=0
		BEGIN
			DELETE FROM CM_FeeType WHERE FeetypeId=@feetypeid  --删除车辆基本信息
		END
	ELSE
		RETURN -1



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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














/****** Object:  Stored Procedure dbo.Gp_DeleteGuestBack    Script Date: 2002-6-20 10:14:46 ******/

CREATE  PROCEDURE [Gp_DeleteGuestBack]
(
 @BillNumberId  int
)
--@encode$--
AS
Set Nocount on
--declare @nret int
--exec @nret=gp_zc_auditingmx @BillNumberId,1
--if @nret<>0 return -1
delete from guestbackindex where billnumberid=@BillNumberId 
if @@rowcount=0 return -1 else return 0















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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














/****** Object:  Stored Procedure dbo.Gp_DeleteGuestPayBill    Script Date: 2002-6-20 10:14:46 ******/

CREATE  PROCEDURE [Gp_DeleteGuestPayBill]
(
 @BillNumberId  int,
 @nBillType		INT
)
--@encode$--
AS
SET NOCOUNT ON
declare @nret int
exec @nret=gp_zc_auditingmx @BillNumberId,@nBillType,1
if @nret<>0 return -1
delete from GuestPayindex where billnumberid=@BillNumberId 
if @@rowcount=0 return -1 else return 0















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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











CREATE   PROCEDURE GP_DeleteInfoFixUp 
(
	@chvETypeID	varchar(50)
)
--@encode$--
AS
	DECLARE @chvLim varchar(2000)

	SELECT	@chvLim = Lim
	FROM	LoginUser
	WHERE	ETypeID = @chvETypeID

	IF SUBSTRING(@chvLim,480,1) <> '1' RETURN -2

	UPDATE	LoginUser
	SET		InfoFixUp = ''
	WHERE	ETypeID = @chvETypeID

	IF @@ROWCOUNT = 0 OR @@ERROR <> 0 RETURN -1










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


CREATE PROCEDURE [Gp_DeleteInsert_Ac_Data]
(
	@Type			VARCHAR(20),	-- 基本信息类型 1.分支机构 2.部门 3.职员 4.往来单位
	@typeid			VARCHAR(50)  	-- 替换前基本信息ID
)
--@encode$--
AS
SET NOCOUNT ON

IF @Type = 'STYPE'
BEGIN	
	--UPDATE	Ac_Voucher_Bill 
	--SET		AscIds = REPLACE(AscIds,'1:'+@oldTypeId,'1:'+@newTypeId)
	
	
	IF EXISTS( SELECT 1 FROM Ac_Voucher_Bill WHERE AscIds LIKE '%1:'+@typeid+',%' )
		RETURN 1
			
	IF EXISTS(SELECT 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE TypeId=@typeid AND typeName = '01')
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE FieldValue=@typeid AND Ascids = 1)
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE FieldValue=@typeid AND Ascids = 1)
		RETURN 1			
END
ELSE IF @Type = 'DEPARTMENT'
BEGIN
	IF EXISTS( SELECT 1 FROM Ac_Voucher_Bill WHERE AscIds LIKE '%2:'+@typeid+',%' )
		RETURN 1
		
	IF EXISTS(SELECT 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE TypeId=@typeid AND typeName = '02')
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE FieldValue=@typeid AND Ascids = 2)
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE FieldValue=@typeid AND Ascids = 2)
		RETURN 1	
END
ELSE IF @Type = 'EMPLOYEE'
BEGIN
	IF EXISTS( SELECT 1 FROM Ac_Voucher_Bill WHERE AscIds LIKE '%3:'+@typeid+',%' )
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE TypeId=@typeid AND typeName = '03')
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE FieldValue=@typeid AND Ascids = 3)
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE FieldValue=@typeid AND Ascids = 3)
		RETURN 1	
END
ELSE IF @Type = 'BTYPE'
BEGIN
	IF EXISTS( SELECT 1 FROM Ac_Voucher_Bill WHERE AscIds LIKE '%4:'+@typeid+',%' )
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE TypeId=@typeid AND typeName = '04')
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE FieldValue=@typeid AND Ascids = 4)
		RETURN 1
	
	IF EXISTS(SELECT 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE FieldValue=@typeid AND Ascids = 4)
		RETURN 1	
END

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.11.23
	描述：删除项目分类
*/
CREATE PROCEDURE GP_DeleteItemType
(
	@typeid		VARCHAR(50),
	@stypeid	VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @parid VARCHAR(50)

SELECT @parid = parid FROM dbo.ItemType WHERE typeId = @typeid AND STypeid = @stypeid

BEGIN TRAN deleTran

	DELETE FROM dbo.ItemType WHERE typeId = @typeid AND STypeid = @stypeid
	
	UPDATE dbo.ItemType SET sonnum = sonnum - 1 WHERE typeId = @parid AND STypeid = @stypeid
	
	--不存在分类项目，清除根结点
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemType WHERE STypeid = @stypeid AND typeId <> '00000')
		DELETE FROM dbo.ItemType WHERE STypeid = @stypeid AND typeId = '00000'
	
IF @@ERROR <> 0
	ROLLBACK TRAN deleTran
ELSE
	COMMIT TRAN deleTran


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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










/*
	--编程：Roamer Wu
	--时间：2003-12-29
	--功能：删除货位单据明细
*/

CREATE PROCEDURE Gp_DeleteLocalDetail
(
@nBillID		 Int
)
--@encode$--
AS
SET NOCOUNT ON

Delete From LocalDetail Where BillNumberId = @nBillID

IF @@RowCount > 0
	return 0
else
	Return -1








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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














/****** Object:  Stored Procedure dbo.Gp_DeleteOrderIndex    Script Date: 2002-6-20 10:14:46 ******/

CREATE  PROCEDURE [Gp_DeleteOrderIndex]
(
 @BillNumberId  int
)
--@encode$--
AS 
SET NOCOUNT ON
delete from orderIndex where billnumberid=@BillNumberId 
if @@rowcount=0 or @@error<>0 
	RAISERROR('删除单据发生错误',16,1)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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








CREATE       PROCEDURE [Gp_DeleteRuleBill]
(
 @BillNumberId  int
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @RowCount int
DECLARE @RowCount1 int

SET @RowCount=0
SET @RowCount1=0

IF EXISTS(SELECT * FROM TCBillindex where EtypeID<>'' AND billnumberid=@BillNumberId)
	RETURN -2

-- 开始事务
BEGIN TRAN
DELETE FROM TCBillindex where billnumberid=@BillNumberId 
SET @RowCount=@@rowcount
IF @RowCount=0 
BEGIN
	ROLLBACK TRAN
	return -1 
END
ELSE
BEGIN
	DELETE FROM TCBill where billnumberid=@BillNumberId 	
	SET @RowCount1=@@rowcount
	IF @RowCount1=0 
	BEGIN
		ROLLBACK TRAN
		return -1
	END
END

--DELETE FROM PrintRecord WHERE BillType=164 AND BillNumberId=@BillNumberId
UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId=@BillNumberId AND BillType=164
COMMIT TRAN	-- 提交事务
RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:彭勇
	日期：2014-04-30
	描述：删除提成规则设置
*/
CREATE PROCEDURE Gp_DeleteSetCommissionRule
(
	 @BillNumberId  int
)
--@encode$--
AS
SET NOCOUNT ON
   IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState=2)
   BEGIN 
	   RAISERROR ('该单据已审核，不允许删除！',16,1) 
	   RETURN;
   END 
   IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState=3)
   BEGIN 
	   RAISERROR ('该单据已禁用，不允许删除！',16,1) 
	   RETURN;
   END 
   IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND UseState=2)
   BEGIN 
	   RAISERROR ('该单据已引用，不允许删除！',16,1) 
	   RETURN;
   END 
 DELETE dbo.CommissionRule WHERE BillNumberId=@BillNumberId
 DELETE dbo.CommissionRuleEtype WHERE BillNumberId=@BillNumberId
 DELETE dbo.CommissionRulePtype WHERE BillNumberId=@BillNumberId
 DELETE dbo.CommissionRuleRegion WHERE BillNumberId=@BillNumberId
 DELETE dbo.CommissionRuleLeader WHERE BillNumberId=@BillNumberId
  --DELETE FROM PrintRecord WHERE BillType=164 AND BillNumberId=@BillNumberId
 UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId=@BillNumberId AND BillType=164
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:彭勇
	日期：2014-04-30
	描述：删除参照计划提成设置
*/
CREATE PROCEDURE Gp_DeleteSetReferencePlanCommission
(
	 @BillNumberId  int
)
--@encode$--
AS
SET NOCOUNT ON
   IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState=3)
   BEGIN 
	    RAISERROR ('该单据已禁用，不允许删除！',16,1) 
	    RETURN;
   END 
    IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState=2)
   BEGIN 
	   RAISERROR ('该单据已审核，不允许删除！',16,1) 
	   RETURN;
   END 
   IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND UseState=2)
   BEGIN 
	   RAISERROR ('该单据已引用，不允许删除！',16,1) 
	   RETURN;
   END 
   
 DELETE dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId
 DELETE dbo.ReferencePlanCommissionEtype WHERE BillNumberId=@BillNumberId
 DELETE dbo.ReferencePlanCommissionPlan WHERE BillNumberId=@BillNumberId

 --DELETE FROM PrintRecord WHERE BillType=164 AND BillNumberId=@BillNumberId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/****** Object:  Stored Procedure dbo.Gp_DeleteTemplate    Script Date: 2002-6-20 10:14:46 ******/

CREATE  PROCEDURE [Gp_DeleteTemplate]
(
 @TemplateId  [int],
 @DbName  varchar(30)
)
--@encode$--
AS 
SET NOCOUNT ON
declare @sql varchar(500)
select @sql='DELETE '+@dbname+' WHERE  Templateid = '+cast(@Templateid as varchar)
exec(@sql)
if @@rowcount=0 return -1 else return 0















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_DeleteUFO_Templet]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DeleteUFO_Templet
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	删除自定义报表模板
-- 时间：	2013-06-26
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_DeleteUFO_Templet
(
	@Id				INT					--模板ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@ErrorCount			INT=0,		--执行时出错
	@TempleCategoryID	VARCHAR(50),--对应节点ID
	@TempleName		VARCHAR(200)
--得到要删除模板的名称及左边树的ID
SELECT @TempleCategoryID=TempleCategoryID,@TempleName=TempleName FROM UFO_Temple WHERE ID=@Id
--判断是否在报表查询时保存过
IF(SELECT COUNT(id) FROM UFO_Temple WHERE TempleCategoryID=(SELECT TOP 1 TypeId FROM dbo.UFO_ReportCategory WHERE [Name]=@TempleName AND SysType=1) AND ClassId=3)>0
	BEGIN
		RETURN 1
	END
--判断改左边树节点在模板中是否只有一个模板，是的话就可以删除当前节点
IF(SELECT COUNT(*) FROM UFO_Temple WHERE TempleCategoryID=@TempleCategoryID AND ClassId=2)=1
	BEGIN
		DELETE FROM UFO_ReportCategory WHERE TypeId=@TempleCategoryID AND SysType=0 AND etypeid IS NOT NULL
		SET @ErrorCount+=@@ERROR
	END
--得到保存查询条件方案的ID
SELECT @TempleCategoryID=TypeId FROM UFO_ReportCategory WHERE Name=@TempleName AND SysType=1 AND etypeid IS NOT NULL
--删除在报表界面的对应模板名称的节点
DELETE FROM UFO_ReportCategory WHERE Name=@TempleName AND SysType=1 AND etypeid IS NOT NULL
SET @ErrorCount+=@@ERROR

--删除默认方案明细表
DELETE FROM SchemeDetail WHERE SchemeId IN(SELECT SchemeId FROM Scheme WHERE inputtype=@TempleCategoryID)
SET @ErrorCount+=@@ERROR
--删除默认方案主表
DELETE FROM Scheme WHERE inputtype=@TempleCategoryID
SET @ErrorCount+=@@ERROR
--删除方案
DELETE UFO_Temple WHERE ID=@Id
SET @ErrorCount+=@@ERROR

IF(@ErrorCount<>0)
	BEGIN
		RAISERROR('模板删除过程中出错，请稍后再试！',16,1)
	END
RETURN @ErrorCount
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-16
	描述：删除用户组信息
*/

CREATE PROCEDURE GP_DeleteUserGroup
(
	@ugid  varchar(50)  --用户组id
)
--@encode$--
AS
SET NOCOUNT ON

--删除该用户组下相应的操作员信息
IF EXISTS (SELECT ugid FROM UserGroupManage WHERE UgId=@ugid)
	BEGIN
		RAISERROR('当前角色已在管辖角色中使用，不能删除！',16,1)return
	END

UPDATE	loginuser 
SET		belongToGroup=0 
WHERE	etypeid IN (
						SELECT	etypeid
						FROM	loginuser
						WHERE	belongToGroup=@ugid
					)
					
--删除用户组信息
DELETE FROM UserGroup WHERE UGId=@ugid

DELETE FROM UgBType_L WHERE etypeid = @ugid
DELETE FROM UgPType_L WHERE etypeid = @ugid
DELETE FROM UgKType_L WHERE etypeid = @ugid
DELETE FROM UgEType_L WHERE etypeid = @ugid
DELETE FROM UgDType_L WHERE etypeid = @ugid
DELETE FROM UgSType_L WHERE etypeid = @ugid
DELETE FROM UgAType_L WHERE etypeid = @ugid
DELETE FROM UgBank_l WHERE etypeid = @ugid

DELETE FROM UserGroupManage WHERE UgId = @ugid	

DELETE FROM UserGroupLimit 		WHERE etypeid = @ugid		

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DeleteVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_DeleteVoucher]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON    
GO

/*
	作者：鲁大林
	日期：2012-4-6
	描述：删除凭证字
*/
CREATE PROCEDURE [dbo].[Gp_DeleteVoucher]
(
	@vgid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON
-------------------判断是否存在
IF NOT EXISTS(SELECT * FROM Ac_Voucher_Group WHERE Ac_Voucher_Group.VgId=@vgid)
BEGIN
	RETURN -1 
END
-------------------判断该凭证字是否是默认凭证字
IF EXISTS(SELECT * FROM dbo.Ac_Voucher_Group WHERE IsDefault=1 AND VgId=@vgid)
BEGIN
	RETURN -2
END

IF @vgid = 1
BEGIN
	RAISERROR('该信息已在常用凭证模版中使用，不能删除！',16,1)
	RETURN
END 

IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Commonly WHERE VgId=@vgid)
BEGIN
	RAISERROR('系统预置的凭证字，不能删除！',16,1)
	RETURN
END
--判断是否使用
DECLARE @Ret INT=0
SET @Ret=(SELECT dbo.Fn_GetIsUse_Items(@vgid,9))
IF(@Ret=1)
	BEGIN
		RAISERROR('该信息已经使用，不能删除！',16,1)RETURN
	END
DELETE FROM Ac_Voucher_Group_Detail WHERE Ac_Voucher_Group_Detail.VgId=@vgid
DELETE FROM Ac_Voucher_Group WHERE Ac_Voucher_Group.VgId=@vgid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





/*
	作者：谢吉康
	日期：2009-06-08
	描述：删除序列号
*/
CREATE PROCEDURE Gp_DelFactStockSerial
(
	@serial		varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @KTypeId	varchar(200),
		@PTypeId	varchar(200),
		@State		varchar(20),
		@Qty		 NUMERIC(24, 10) ,
		@sQty		 NUMERIC(24, 10) 

SELECT @KTypeId = KTypeId,@PTypeId = PTypeId,@State = State FROM gp_FactPtypeSerial WHERE Serial = @Serial

--序列号严密管理
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'mngSerial' AND Value = 1)
	BEGIN
		IF @State IN (1)
			BEGIN
				SELECT @Qty = SUM(Qty) FROM FactStocks_Qty WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId
				SELECT @sQty = COUNT(*) FROM gp_FactPtypeSerial WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId AND State IN (1,7)

				IF @sQty>@Qty
					DELETE FROM gp_FactPtypeSerial WHERE Serial = @Serial
				ELSE
					RETURN -2
			END
		ELSE
			RETURN -1
	END
ELSE
	BEGIN
		DELETE FROM gp_FactPtypeSerial WHERE Serial = @Serial
	END

RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_DelIniBillEffect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Gp_DelIniBillEffect
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =======================================
-- 描述：期初单据删除，更改用到的存储过程
--		 参考Gp_IniToArApTotal
-- 时间：2013-06-26 09:44:02.900
-- 作者：周华
-- 2013-09-04 修改 写入atype_total表有误的bug
-- 2014-01-08 修改 删除没有写回atype_arpatotal,atype_total为空记录的数据
-- =======================================
CREATE PROCEDURE Gp_DelIniBillEffect
(	
	@billNumberId	NUMERIC(18,0),
	@BillType		INT=-1
)
--@encode$--
AS
BEGIN
	DECLARE @stypeid VARCHAR(50)='';
	DECLARE @btypeid VARCHAR(50)='';
	DECLARE @ExpenseToAr INT=0,
			@TotalDigit  INT;
	DECLARE	@AR_ID INT,@AP_ID INT,@YS_ID INT,@YF_ID INT,@APP_ID INT,@SEND_ID INT;
	
	IF @BillType IN(404,405)
		SELECT @stypeid=Stypeid,@btypeid=btypeid FROM dbo.ReceiptBillIndex WHERE BillNumberId=@billNumberId;
	ELSE	
		SELECT @stypeid=Stypeid,@btypeid=btypeid FROM dbo.BillIndex WHERE BillNumberId=@billNumberId;
		
	IF EXISTS(SELECT 1 FROM dbo.SType_UserConfig WHERE StypeId=@stypeid AND Value='1' AND ConfigNo='1')
		RETURN ;
		
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';
	SELECT @TotalDigit=DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName='total'
	CREATE TABLE #billindexARAPTotal
	(	
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		APTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		YFTotal00  NUMERIC(24, 10) ,
		FCTotal00  NUMERIC(24, 10) ,
		GRIRTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10) ,
		nAPTotal00  NUMERIC(24, 10) ,
		nYSTotal00  NUMERIC(24, 10) ,
		nYFTotal00  NUMERIC(24, 10) ,
		NFCTotal00  NUMERIC(24, 10) ,
		NGRIRTotal00  NUMERIC(24, 10) 
	)

	INSERT INTO #billindexARAPTotal
	( 
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			APTotal00 ,
			YSTotal00 ,
			YFTotal00 ,
			FCTotal00,
			GRIRTotal00,
			nARTotal00 ,
			nAPTotal00 ,
			nYSTotal00 ,
			nYFTotal00,
			NFCTotal00,
			NGRIRTotal00
	)
	SELECT	stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(APTotal00),
			SUM(YSTotal00),
			SUM(YFTotal00),
			SUM(FCTotal00),
			SUM(GRIRTotal00),
			SUM(nARTotal00),
			SUM(nAPTotal00),
			SUM(nYSTotal00),
			SUM(nYFTotal00),
			SUM(NFCTotal00),
			SUM(NGRIRTotal00)
	FROM
	(
		SELECT	stypeid ,
				btypeid ,
				cid ,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney -ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					ELSE 0 
				END AS artotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney -ISNULL(ChargeOffTotal,0)
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)) 
					ELSE 0 
				END AS aptotal00,
				CASE WHEN billtype =189 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS ystotal00,
				CASE WHEN billtype =190 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS yftotal00,
				0 AS FCTotal00,
				0 AS  GRIRTotal00,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney -ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS nartotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney -ISNULL(NChargeOffTotal,0)
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS naptotal00,
				CASE WHEN billtype =189 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney 
					ELSE 0
				END AS nystotal00,
				CASE WHEN billtype =190 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney 
					ELSE 0
				END AS nyftotal00,
				0 AS NFCTotal00,
				0 AS NGRIRTotal00
		FROM dbo.BillIndex
		WHERE	BillType IN(4,66,11,12,45,46,85,93,141,148,149,160,167,168,172,181,6,34,36,84,145,150,151,161,170,189,190,213,212,312)
				AND IsIni=1 
				AND	stypeid =@stypeid
				AND BillNumberId=@billNumberId  AND BillType=@billType
		UNION ALL
		SELECT  b.stypeid ,
				a.btypeid ,
				b.cid ,
				CASE WHEN b.billtype = 116
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					ELSE 0
				END AS artotal00,
				CASE WHEN b.billtype = 128
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					 ELSE 0
				END AS aptotal00,
				0 AS ystotal00,
				0 AS yftotal00,
				0 AS FCTotal00,
				0 AS GRIRTotal00,
				CASE WHEN b.billtype = 116
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					ELSE 0
				END AS nartotal00,
				CASE WHEN b.billtype = 128
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					 ELSE 0
				END AS naptotal00,
				0 AS nystotal00,
				0 AS nyftotal00,
				0 AS NFcTotal00,
				0 AS NGRIRTotal00
		FROM	AdDebtBill a 
		INNER JOIN billindex b ON a.BillNumberId =b.BillNumberId
		WHERE	BillType IN(115,116,128,129)
				AND IsIni=1 
				AND	b.stypeid =@stypeid
				AND b.BillNumberId=@billNumberId  AND BillType=@billType
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=402
				   THEN ROUND((A.Qty-A.InvoiceQty)*A.costprice ,@TotalDigit)
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYFTotal00,
			   0 AS NYSTotal00,
			   CASE WHEN B.BillType=402
					THEN ROUND((A.Qty-A.InvoiceQty)*A.costprice ,@TotalDigit)
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
				
		FROM SendBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid=@stypeid AND B.BillNumberId=@billNumberId AND BillType=@billType
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=403
				   THEN -ROUND((A.Qty-A.InvoiceQty)*A.costprice ,@TotalDigit)
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   CASE WHEN B.BillType=403
					THEN -ROUND((A.Qty-A.InvoiceQty)*A.costprice ,@TotalDigit)
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
		FROM SendBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid=@stypeid AND B.BillNumberId=@billNumberId AND BillType=@billType
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.Total
					ELSE ROUND((A.Qty-A.InvoiceQty)*A.DiscountPrice ,@TotalDigit)
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.NTotal
					ELSE ROUND((A.Qty-A.InvoiceQty)*A.NDiscountPrice ,@TotalDigit)
					END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid=@stypeid AND B.BillNumberId=@billNumberId AND BillType=@billType
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=401
				    THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.Total
					ELSE ROUND(-(A.Qty-A.InvoiceQty)*A.DiscountPrice ,@TotalDigit)
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.NTotal
					ELSE ROUND(-(A.Qty-A.InvoiceQty)*A.NDiscountPrice ,@TotalDigit)
					END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid=@stypeid AND B.BillNumberId=@billNumberId AND BillType=@billType
		
		UNION ALL
		SELECT 
			  B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.BillType=405
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.BillType=405
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM ReceiptBillIndex B 
		WHERE B.BillNumberID=@billNumberId AND BillType=@billType AND B.IsIni=1 AND B.Stypeid=@stypeid
		
		UNION ALL
		SELECT 
		B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.totalmoney
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.ChargeOffType IN (3,4)
				   THEN B.totalmoney
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.NTotalMoney
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.ChargeOffType IN (3,4)
				   THEN B.NTotalMoney
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM dbo.BillIndex B 
		 WHERE B.BillNumberId=@billNumberId AND BillType=450 AND B.IsIni=1 AND B.Stypeid=@stypeid
		 
		
	) total
	GROUP BY stypeid,btypeid,cid

	
	DELETE FROM #billindexARAPTotal WHERE 
		ISNULL(YSTotal00,0)=0 AND ISNULL(YFTotal00,0)=0 AND 
		ISNULL(ARTotal00,0)=0 AND ISNULL(APTotal00,0)=0 AND 
		ISNULL(nYSTotal00,0)=0 AND ISNULL(nYFTotal00,0)=0 AND 
		ISNULL(nARTotal00,0)=0 AND ISNULL(nAPTotal00,0)=0  AND 
		ISNULL(NGRIRTotal00,0)=0 AND ISNULL(GRIRTotal00,0)=0 AND 
		ISNULL(FCTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0

	-- 回冲 BType_ArApTotal 期初
	UPDATE	a 
	SET		a.ARTotal00=a.ARTotal00-b.ARTotal00,
			a.APTotal00=a.APTotal00-b.APTotal00,
			a.YSTotal00=a.YSTotal00-b.YSTotal00,
			a.YFTotal00=a.YFTotal00-b.YFTotal00,
			a.nARTotal00=a.nARTotal00-b.nARTotal00,
			a.nAPTotal00=a.nAPTotal00-b.nAPTotal00,
			a.nYSTotal00=a.nYSTotal00-b.nYSTotal00,
			a.nYFTotal00=a.nYFTotal00-b.nYFTotal00,
			a.NGRIRTotal00=a.NGRIRTotal00-b.NGRIRTotal00,
			a.GRIRTotal00=a.GRIRTotal00-b.GRIRTotal00,
			a.FCTotal00=a.FCTotal00-b.FCTotal00,
			a.NFCTotal00=a.NFCTotal00-b.NFCTotal00
	FROM	dbo.BType_ArApTotal a 
	JOIN	#billindexARAPTotal b ON a.stypeid=b.stypeid 
		AND a.btypeid=b.btypeid 
		AND a.CID=b.cid

	INSERT INTO BType_ArApTotal(
		BTypeID,
		STypeID,
		ARTotal,
		APTotal,
		YSTotal,
		YFTotal,
		ARTotal00,
		APTotal00,
		YSTotal00,
		YFTotal00,
		nARTotal,
		nAPTotal,
		nYSTotal,
		nYFTotal,
		nARTotal00,
		nAPTotal00,
		nYSTotal00,
		nYFTotal00,
		CID,
		FCTotal00,
		NFCTotal00,
		GRIRTotal00,
		NGRIRTotal00
	) SELECT 
		b.btypeId,
		b.stypeid,
		0,0,0,0,
		-b.ARTotal00,-b.APTotal00,-b.YSTotal00,-b.YFTotal00,
		0,0,0,0,
		-b.nARTotal00,-b.nAPTotal00,-b.nYSTotal00,-b.nYFTotal00,
		b.cid,
		-B.FCTotal00,
		-B.NFCTotal00,
		-B.GRIRTotal00,
		-B.NGRIRTotal00
	FROM #billindexARAPTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM BType_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid)

	DELETE 
	FROM	BType_ArApTotal 
	WHERE	ISNULL(ARTotal,0)=0 AND ISNULL(APTotal,0)=0 AND ISNULL(YSTotal,0)=0 AND ISNULL(YFTotal,0)=0 
			AND ISNULL(ARTotal00,0)=0 AND ISNULL(APTotal00,0)=0 AND ISNULL(YSTotal00,0)=0 AND ISNULL(YFTotal00,0)=0
			AND ISNULL(nARTotal,0)=0 AND ISNULL(nAPTotal,0)=0 AND ISNULL(NYSTotal,0)=0 AND ISNULL(NYFTotal,0)=0
			AND ISNULL(NARTotal00,0)=0 AND ISNULL(NAPTotal00,0)=0 AND ISNULL(NYSTotal00,0)=0 AND ISNULL(NYFTotal00,0)=0
			AND ISNULL(FCTotal,0)=0 AND ISNULL(NFCTotal,0)=0 AND ISNULL(NGRIRTotal,0)=0 AND ISNULL(GRIRTotal,0)=0
			AND ISNULL(FCTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0 AND ISNULL(NGRIRTotal00,0)=0 AND ISNULL(GRIRTotal00,0)=0
		
	SELECT @AR_ID=nid FROM dbo.Ac_Items WHERE FullName='应收合计';		
	SELECT @AP_ID=nid FROM dbo.Ac_Items WHERE FullName='应付合计';		
	SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE FullName='预收资金';		
	SELECT @YF_ID=nid FROM dbo.Ac_Items WHERE FullName='预付资金';
	SELECT @APP_ID=NID FROM dbo.Ac_Items WHERE FullName='应付暂估';
	SELECT @SEND_ID=NID FROM dbo.Ac_Items WHERE FullName='发出商品';

	-- 回冲期初余额
	SELECT	stypeid,
			cid
			,ISNULL(SUM(artotal00),0) AS artotal00
			,ISNULL(SUM(nartotal00),0) AS nartotal00 
			,ISNULL(SUM(aptotal00),0) AS aptotal00
			,ISNULL(SUM(naptotal00),0) AS naptotal00
			,ISNULL(SUM(ystotal00),0) AS ystotal00
			,ISNULL(SUM(nystotal00),0) AS nystotal00
			,ISNULL(SUM(yftotal00),0) AS yftotal00
			,ISNULL(SUM(nyftotal00),0) AS nyftotal00
			,ISNULL(SUM(GRIRTotal00),0) AS GRIRTotal00
			,ISNULL(SUM(NGRIRTotal00),0) AS NGRIRTotal00
			,ISNULL(SUM(FCTotal00),0) AS FCTotal00
			,ISNULL(SUM(NFCTotal00),0) AS NFCTotal00
	INTO	#atype_total 
	FROM	#billindexARAPTotal GROUP BY stypeid,cid
	
	UPDATE a 
	SET		a.total00=a.total00-b.artotal00,
			a.ntotal00=a.ntotal00-b.nartotal00
	FROM	AType_Total a 
	JOIN	#atype_total b ON a.STypeID=b.stypeid AND a.CID=b.cid
	WHERE a.ATypeID=@AR_ID; --应收
	
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)
	SELECT	@AR_ID,
			b.StypeId,
			-b.artotal00,
			-b.nartotal00,
			b.cid 
	FROM	#atype_total b
	LEFT JOIN AType_Total a ON a.stypeid=b.stypeid AND a.CID=b.cid AND a.ATypeID=@AR_ID
	WHERE	a.STypeID IS NULL 
			AND b.artotal00<>0 ;
	
	UPDATE a SET a.total00=a.total00-b.aptotal00,a.ntotal00=a.ntotal00-b.naptotal00
	FROM AType_Total a JOIN #atype_total b ON a.STypeID=b.stypeid AND a.CID=b.cid
	WHERE a.ATypeID=@AP_ID; --应付
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @AP_ID,b.StypeId,-b.aptotal00,-b.naptotal00,b.cid FROM #atype_total b LEFT JOIN  AType_Total a ON a.stypeid=b.stypeid AND a.CID=b.cid AND a.ATypeID=@AP_ID
	WHERE a.ATypeID IS NULL AND b.aptotal00<>0;
	
	UPDATE a SET a.total00=a.total00-b.ystotal00,a.ntotal00=a.ntotal00-b.nystotal00
	FROM AType_Total a JOIN #atype_total b ON a.STypeID=b.stypeid AND a.CID=b.cid
	WHERE a.ATypeID=@YS_ID; --预收

	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @YS_ID,b.StypeId,-b.ystotal00,-b.nystotal00,b.cid FROM #atype_total b LEFT JOIN AType_Total a ON a.stypeid=b.stypeid AND a.CID=b.cid AND a.ATypeID=@YS_ID
	WHERE a.ATypeID IS NULL AND b.ystotal00<>0;

	UPDATE a SET a.total00=a.total00-b.yftotal00,a.ntotal00=a.ntotal00-b.nyftotal00
	FROM AType_Total a JOIN #atype_total b ON a.STypeID=b.stypeid AND a.CID=b.cid
	WHERE a.ATypeID=@YF_ID; --预付

	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @YF_ID,b.StypeId,-b.yftotal00,-b.nyftotal00,b.cid FROM #atype_total b LEFT JOIN AType_Total a ON a.stypeid=b.stypeid AND a.CID=b.cid AND a.ATypeID=@YF_ID
	WHERE a.ATypeID IS NULL AND b.yftotal00<>0;

	
	UPDATE A SET A.Total00=A.Total00-B.GRIRTotal00,
				 A.Ntotal00=A.Ntotal00-B.NGRIRTotal00
	FROM AType_Total A JOIN #atype_total B ON A.STypeID=B.STypeID AND a.CID=b.CID
	WHERE a.ATypeID=@APP_ID; --应付暂付
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @APP_ID,b.StypeId,-b.GRIRTotal00,-b.NGRIRTotal00,b.CID FROM #atype_total b 
	LEFT JOIN AType_Total A ON A.STypeID=A.STypeID AND a.CID=b.CID AND A.ATypeID=@APP_ID
	WHERE a.ATypeID IS NULL AND b.GRIRTotal00<>0;
	
	UPDATE A SET A.Total00=A.Total00-B.FCTotal00,
				 A.Ntotal00=A.Ntotal00-B.NFCTotal00
	FROM AType_Total A JOIN #atype_total B ON A.STypeID=B.STypeID AND a.CID=b.CID
	WHERE a.ATypeID=@SEND_ID; --发出商品
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @SEND_ID,B.StypeId,-B.FCTotal00,-B.NFCTotal00,B.CID FROM #atype_total B 
	LEFT JOIN AType_Total A ON A.STypeID=A.STypeID AND A.CID=B.CID AND A.ATypeID=@SEND_ID
	WHERE a.ATypeID IS NULL AND b.FCTotal00<>0;

	DELETE FROM AType_Total WHERE total00=0 AND Total=0 AND Ntotal00=0 AND Ntotal=0;
-----------------------------------------删除期初往来核销影响原单据核销金额处理 start---------------------------------------------------
IF @BillType=450
BEGIN
	DECLARE @fromBillType INT
	DECLARE @fromBillNumberID NUMERIC(10,0)
	DECLARE @fromBillID INT
	DECLARE @chargeOffValue NUMERIC(24,10)
	DECLARE @nchargeOffValue NUMERIC(24,10)
	DECLARE @NTotalMoney NUMERIC(24,10)
	DECLARE @NTotalInMoney NUMERIC(24,10)
	DECLARE @NCompleteTotal NUMERIC(24,10)
	DECLARE @NPreferenceMoney NUMERIC(24,10)
	
	SELECT @chargeOffValue=ChargeOffTotal,@nchargeOffValue=NChargeOffTotal
	FROM dbo.BillIndex 
	WHERE BillNumberId=@billNumberId
	
	SELECT @fromBillType=@fromBillType,@fromBillNumberID=@fromBillNumberID,@fromBillID=FromBillID 
	FROM dbo.ChargeOffBill 
	WHERE BillNumberId=@billNumberId
	IF @fromBillType IN (405,404)
	BEGIN
		UPDATE dbo.ReceiptBillIndex SET ChargeOffTotal=ChargeOffTotal-@chargeOffValue,NChargeOffTotal=NChargeOffTotal-@nchargeOffValue
		WHERE BillNumberId=@fromBillNumberid
		SELECT @NTotalMoney =NTaxTotalMoney,
				@NTotalInMoney=0,
				@NCompleteTotal=NCompleteTotal,
				@NPreferenceMoney=0,
				@nchargeOffValue=NChargeOffTotal FROM dbo.ReceiptBillIndex 
		WHERE BillNumberID=@fromBillNumberid
			
		IF (@NTotalMoney-@NCompleteTotal-@nchargeOffValue)<>@NTotalMoney
			UPDATE dbo.ReceiptBillIndex SET JSStyle=1,JSState=1 WHERE BillNumberID=@fromBillNumberid
		ELSE 
			UPDATE dbo.ReceiptBillIndex SET JSStyle=1,JSState=0 WHERE BillNumberID=@fromBillNumberid
	END
	ELSE
	BEGIN
		--应收应付预收预付回写核销金额到明细
		IF @fromBillType IN (115,116,128,129)
		BEGIN
			UPDATE dbo.AdDebtBill SET ChargeOffTotal=ChargeOffTotal-@chargeOffValue,NChargeOffTotal=NChargeOffTotal-@nchargeOffValue
			WHERE BillNumberId=@fromBillNumberid AND ID = @fromBillID
		END
		
		UPDATE dbo.BillIndex SET ChargeOffTotal=ChargeOffTotal-@chargeOffValue,NChargeOffTotal=NChargeOffTotal-@nchargeOffValue
		WHERE BillNumberId=@fromBillNumberid
			
		SELECT @NTotalMoney =NTotalMoney,
				@NTotalInMoney=NTotalInMoney,
				@NCompleteTotal=NCompleteTotal,
				@NPreferenceMoney=NPreferenceMoney,
				@nchargeOffValue=NChargeOffTotal FROM dbo.BillIndex 
		WHERE BillNumberID=@fromBillNumberid
			
		IF (@NTotalMoney-@NCompleteTotal-@NTotalInMoney-@NPreferenceMoney-@nchargeOffValue)<>@NTotalMoney
				UPDATE dbo.BillIndex SET JSStyle=1,JSState=1 WHERE BillNumberID=@fromBillNumberid
			ELSE 
				UPDATE dbo.BillIndex SET JSStyle=1,JSState=0 WHERE BillNumberID=@fromBillNumberid
		END
END
-----------------------------------------删除期初往来核销影响原单据核销金额处理 end-----------------------------------------------------
	DROP TABLE #billindexARAPTotal;
	DROP TABLE #atype_total;
	--------------------------------------------品牌应收 begin --------------------------------
	--IF NOT EXISTS(SELECT 1 FROM dbo. btype WHERE typeid =@btypeid and IsUseBrandarType=1)
    -- RETURN ;--如果该往来单位不启用品牌应收 则 返回不计算

	CREATE TABLE #BrandarARAPTotal
	(
		BrandarTypeID VARCHAR(50),
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10),
		nYSTotal00  NUMERIC(24, 10) ,
		Total00		NUMERIC(24, 10) ,
		NTotal00	NUMERIC(24, 10)
	)

	INSERT INTO #BrandarARAPTotal
	(		
			BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			YSTotal00 ,
			nARTotal00 ,
			nYSTotal00,
			Total00,
			NTotal00
	)
	SELECT	BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(YSTotal00),
			SUM(nARTotal00),
			SUM(nYSTotal00),
			0,
			0
			
	FROM
	(	--销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=11
		UNION ALL      
		--组合品销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.PT_Combin_SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=12
		UNION ALL
		--销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal00,
				0 AS YSTotal00 ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.salebackbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=45
		UNION ALL 
		--组合品销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal00,
				0 AS YSTotal00 ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.PT_Combin_SaleBackBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=46 
		UNION ALL 
		--销售换货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN s.InOrOut='O' THEN s.taxtotal-s.CompleteTotal
										ELSE -( s.taxtotal-s.CompleteTotal) 
										END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN s.InOrOut='O' THEN s.ntaxtotal-s.NCompleteTotal 
										ELSE -(s.ntaxtotal-s.NCompleteTotal )
										END AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.salegoodsexchangebill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=160 
		UNION ALL 
		--委托代销结算单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.commissionbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
				  AND  b.Stypeid=@stypeid
				  AND b.BillNumberId=@billNumberId AND @billType=141 
		UNION ALL 
		--销售发货开票
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.ReceiptBill s
			INNER JOIN  ReceiptBillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=405 	
		UNION ALL 
		--期初预收款
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS  ARTotal00,
				s.total AS YSTotal00 ,
				0 AS nARTotal00 ,
				s.ntotal AS nYSTotal00 
			FROM dbo.prebill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=189 
			      AND ISNULL(B.NChargeOffTotal,0)=0 
			      AND ISNULL(s.BrandarTypeID,'')<>'-99999'
		UNION ALL 
		--应收增加单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				s.total-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=116 
			      AND  ISNULL(s.BrandarTypeID,'')<>'-99999'				
		UNION ALL 
		--应收减少单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				-(s.total-s.CompleteTotal) AS  ARTotal00,
				0 AS YSTotal00 ,
				-(s.ntotal-s.NCompleteTotal) AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=115 
			      AND  ISNULL(s.BrandarTypeID,'')<>'-99999'		
		UNION ALL 
		--其他收入单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.total AS  ARTotal00,
				0 AS YSTotal00 ,
				s.NTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=93 
		UNION ALL 
		--费用单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.total
					  ELSE 0
					  END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.NTotal
					  ELSE 0
					  END  AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1	
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=36	
		UNION ALL 
		--收款单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.total+s.PreferenceMoney) AS  ARTotal00,
				CASE WHEN s.AtypeId=@YS_ID THEN -s.total ELSE 0 END AS YSTotal00 , --预收 不包含优惠
				-(s.ntotal+s.NPreferenceMoney) AS nARTotal00 ,
				CASE WHEN s.AtypeId=@YS_ID THEN -s.ntotal ELSE 0 END AS nYSTotal00 
			FROM dbo.gatheringbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1	
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=4	
			      AND ISNULL(s.BrandarTypeID,'')<>''
		UNION ALL 
		--多账户
		SELECT	s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.PreferenceMoney+S.TotalInMoney+s.YSTotalInMoney )
					ELSE s.PreferenceMoney+S.TotalInMoney+s.YSTotalInMoney 
					END  AS  ARTotal00,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.YSTotalInMoney  )
					ELSE s.YSTotalInMoney 
					END AS YSTotal00 ,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.NPreferenceMoney+S.NTotalInMoney+s.NYSTotalInMoney )
					ELSE s.NPreferenceMoney+S.NTotalInMoney+s.NYSTotalInMoney 
					END  AS nARTotal00 ,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.NYSTotalInMoney  )
					ELSE s.NYSTotalInMoney 
					END AS nYSTotal00  
			FROM BillMulBrand s
			INNER JOIN BILLINDEX B ON s.billnumberid=b.billnumberid
			WHERE s.BillNumberId=@billNumberId 
				   AND s.billtype=@billType
				   AND b.Stypeid=@stypeid
				   AND b.isini=1
				   AND b.BillType NOT  IN (305,215)
		UNION ALL 
		--多账户
		SELECT	s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS  ARTotal00,
				CASE WHEN @billtype IN (305) 
					THEN -(s.YSTotalInMoney  )
					ELSE s.YSTotalInMoney 
					END AS YSTotal00 ,
				0 AS nARTotal00 ,
				CASE WHEN @billtype IN (305) 
					THEN -(s.NYSTotalInMoney  )
					ELSE s.NYSTotalInMoney 
					END AS nYSTotal00  
			FROM BillMulBrand s
			INNER JOIN BILLINDEX B ON s.billnumberid=b.billnumberid
			WHERE s.BillNumberId=@billNumberId 
				   AND s.billtype=@billType
				   AND b.Stypeid=@stypeid
				   AND b.isini=1
				   AND b.BillType NOT  IN (305,215)
		UNION ALL 
		--品牌结算
		SELECT	s.BrandarTypeID,
				s.stypeid,
				s.btypeid,
				s.cid,
				CASE 
					WHEN @billtype IN (11,12,160,141,93,405,45,46) THEN -s.CompleteTotal
					ELSE s.CompleteTotal 
				END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE 
					WHEN @billtype IN (11,12,160,141,93,405,45,46) THEN -s.NCompleteTotal
					ELSE s.NCompleteTotal
				END  AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM CompleteBrandarTotal s
			WHERE s.GoodsBillID=@billNumberId 
				   AND s.billtype=@billType
				   AND s.Stypeid=@stypeid
				   AND S.isdraft=0  --不是草稿的
				   AND s.isini=1		
	)total
	GROUP BY BrandarTypeID,stypeid,btypeid,cid

	DELETE FROM #BrandarARAPTotal WHERE YSTotal00=0  AND ARTotal00=0  AND nYSTotal00=0 AND nARTotal00=0 
	
	-- 写入 brandar_ArApTotal 期初
	UPDATE	a 
	SET		a.ARTotal00=ISNULL(a.ARTotal00,0)-ISNULL(b.ARTotal00,0),
			a.YSTotal00=ISNULL(a.YSTotal00,0)-ISNULL(b.YSTotal00,0),
			a.nARTotal00=ISNULL(a.nARTotal00,0)-ISNULL(b.nARTotal00,0),
			a.nYSTotal00=ISNULL(a.nYSTotal00,0)-ISNULL(b.nYSTotal00,0)
	FROM	dbo.brandar_ArApTotal a 
	JOIN	#BrandarARAPTotal b ON a.stypeid=b.stypeid 
			AND a.btypeid=b.btypeid 
			AND a.CID=b.cid 
			AND a.BrandarTypeID=b.BrandarTypeID

	INSERT INTO brandar_ArApTotal
	(
		BTypeID,
		STypeID,
		BrandarTypeID,
		CID,
		ARTotal,
		YSTotal,
		ARTotal00,
		YSTotal00,
		nARTotal,
		nYSTotal,
		nARTotal00,
		nYSTotal00
	) 
	SELECT	b.btypeId,
			b.stypeid,
			B.BrandarTypeID,
			b.cid,
			0,
			0,
			-b.ARTotal00,
			-b.YSTotal00,
			0,
			0,
			-b.nARTotal00,
			-b.nYSTotal00	
	FROM	#BrandarARAPTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM brandar_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid AND a.BrandarTypeID=b.BrandarTypeID)

	DELETE  
	FROM	Brandar_ArApTotal 
	WHERE	ISNULL(ARTotal,0)=0 AND ISNULL(YSTotal,0)=0 
			AND ISNULL(ARTotal00,0)=0  AND ISNULL(YSTotal00,0)=0 
			AND ISNULL(nARTotal,0)=0  AND ISNULL(NYSTotal,0)=0 
			AND ISNULL(NARTotal00,0)=0 AND ISNULL(NYSTotal00,0)=0 


	DELETE FROM CompleteBrandarTotal WHERE GoodsBillID = @billNumberId AND billtype =@BillType
	DELETE FROM completeTotal WHERE GoodsBillID = @billNumberId AND billtype =@BillType
				
	DROP TABLE #BrandarARAPTotal;
	--------------------------------------------品牌应收 end --------------------------------	
		
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_DeliveryBackBill_CreateBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_DeliveryBackBill_CreateBill]
GO




/*

功能说明：		配送验收单过账自动生成剩余数量的门店配送退货单

作    者：       赵燕琴


返回结果：       

*/

CREATE PROCEDURE [GP_DeliveryBackBill_CreateBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
      
AS

SELECT @intReturnID=0  --生成返回的退货billnumberid

DECLARE 	
	@strInKTypeID					VARCHAR(50),--生成的退货单的入库仓库
	@strOutKTypeID					VARCHAR(50),		--出库对应的分支机构
	@strFromBillCode 				VARCHAR(100),--配送单的billcode
	@intBillType					INT,  --生成单据类型
	@datBillDate					DATETIME, --配送单日期
    @deliveryID                     VARCHAR(50), --引用门店配送明细id
    @allbackqty                     numeric(24,10),	 --所以退货数量（退货单主表）
    @strInSTypeID                   VARCHAR(50), --分支机构
    @deliveryBillID                 VARCHAR(50), --引用门店配送billnumberid
    @checkqty                       numeric(24,10),	--本单验收单数量
    @ceDtypeid						VARCHAR(100)='',
    @ETypeID						VARCHAR(100)=''


SET @deliveryID = (Select TOP 1 DeliveryID FROM dbo.DeliveryCheckBill WHERE BillNumberId=@nBillID) --找验收单关联的门店配送单deliveryid
SET @deliveryBillID=(Select TOP 1 BillNumberId FROM dbo.DeliveryBill WHERE id=@deliveryID) --验收关联的门店配送单billnumberid
SET @allbackqty= (select SUM(Qty-BackQty-CheckQty) FROM dbo.DeliveryBill WHERE BillNumberId=@deliveryBillID)--退货单主表总退货数量

IF(@allbackqty<=0)RETURN  --没有未完成验收数量则返回
SELECT 
	 @strInKTypeID=CASE WHEN ISNULL(KTypeID,'')='' THEN InKtypeId ELSE KtypeId END,
	 @strOutKTypeID=a.KtypeId,	
	 @strFromBillCode=a.BillCode,
	 @datBillDate=a.BillDate,
	 @strInSTypeID=a.StypeId,
	 @ceDtypeid=a.DtypeId,
	 @ETypeID=ApplyEtypeId
     FROM PosAllotApplyBillIndex a WHERE a.BillNumberId=@nBillID

SELECT @intBillType=328


DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号


DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@cefullname			VARCHAR(500)='',
	@cdfullname			VARCHAR(500)=''

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT @VchHead='MT'

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = TypeId FROM Employee WHERE TypeID = @ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @strInKTypeID
	SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
	SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid
END
ELSE
BEGIN
	SELECT 
		@MONTH=ISNULL(@MONTH,''),
		@DAY=ISNULL(@DAY,'')
END


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strInSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname




IF @Re <> 0
RETURN -2	

DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000)
	
	
SELECT 
	@strComment='该门店配送退货单是从门店验收单'+@strFromBillCode+'生成而来的！',
	@intBillType=328
	
	



--生成门店退货单的草稿
--生成表头

INSERT INTO [dbo].[PosAllotApplyBillIndex]
				   ([BillType] ,[BillCode],[BillDate],[ApplyEtypeId],[StypeId],[DtypeId],[KtypeId],[InKtypeId],[Qty],[Total],[Comment],[Explain],[BillState],[checkE],[IsAutoGenerate],[BillOver],[StopReason],[Isdone],[checkTime],[RedWord],[ifcheck],[draft],[Checker] ,[CheckerTime],[Updater],[UpdaterTime],[IsIni] ,[ifYearBill],[CID] ,[WarehouseOutDay],[LinkTel],[LinkAddr] ,[LinkMan],CostSale,IsNeedTransport,Atid )
			SELECT @intBillType ,@strBillCode,[BillDate],[ApplyEtypeId],[StypeId],[DtypeId],[InKtypeId],[KtypeId],@allbackqty,[Total],@strComment,[Explain],0,[checkE],[IsAutoGenerate],0,[StopReason],0,GETDATE(),[RedWord],'f',1,[Checker] ,[CheckerTime],[Updater],[UpdaterTime],[IsIni] ,[ifYearBill],[CID] ,[WarehouseOutDay],[LinkTel],[LinkAddr] ,[LinkMan],CostSale,IsNeedTransport,Atid
			 FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId=@nBillID
SELECT @intReturnID=SCOPE_IDENTITY();


--生成表体
INSERT INTO [dbo].[DeliveryBackBill]
   ([ShowOrder],[BillNumberId] ,[Serial],[outktypeid],[outCargoID],[inktypeid],[inCargoID]
   ,[PtypeId],[ItemID],[IsCombined],[GoodsNumber],[ProduceDate],[ValidDate],[Qty],[Price],[Total],[UnitID],[MUnitID] ,[MQty],
    [MUnitRate],[MUnitMsg] ,[MPrice],[NUnitID],[NUnitRate],[NQty],[NUnitMsg],[Comment],[InflowQty],[DeliveryID],[GoodsCostPrice]
   ,[GoodsCostTotal],[HandZeroCost])
SELECT	ShowOrder ,@intReturnID,Serial,ktypeidin,CargoIDin,ktypeidout,CargoIDout
   ,PtypeId,ItemID,IsCombined,GoodsNumber,ProduceDate,ValidDate,Qty-BackQty-CheckQty,Price,(Qty-BackQty-CheckQty)*Price,UnitID,MUnitID,(Qty-BackQty-CheckQty)/MUnitRate
   ,MUnitRate,MUnitMsg,MPrice,NUnitID,NUnitRate,CASE WHEN NUnitRate=0 THEN 0 ELSE(Qty-BackQty-CheckQty)/NUnitRate END,NUnitMsg,Comment,0,id,GoodsCostPrice,(Qty-BackQty-CheckQty)*GoodsCostPrice,HandZeroCost
FROM dbo.DeliveryBill WHERE  BillNumberId=@deliveryBillID AND Qty-BackQty-CheckQty>0

--修改主表合计金额
UPDATE dbo.PosAllotApplyBillIndex SET Total=(SELECT SUM(Total) FROM DeliveryBackBill WHERE BillNumberId=@intReturnID) WHERE BillNumberId=@intReturnID

--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END    

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END

-- Costing Method
--DECLARE @AVERAGE			smallint,
--		@FIFO				smallint,
--		@LIFO				smallint,
--		@HAND				smallint,
--		@nCostingMethod		smallint

--SET @AVERAGE	= 0		-- 移动加权平均
--SET @FIFO		= 1		-- 先进先出
--SET @LIFO		= 2		-- 后进先出
--SET @HAND		= 3		-- 手工指定

--EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output



--IF @nCostingMethod<>@HAND
--BEGIN
--	--修改价格
--	UPDATE STypeMoveBill
--	SET GoodsCostPrice=a.CostPrice,GoodsCostTotal=a.CostTotal
--	FROM
--	(
--		SELECT ID,SUM(CostTotal)*(-1) AS CostTotal,CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(CostTotal) AS  NUMERIC(24, 10) )/CAST(SUM(Qty) AS  NUMERIC(24, 10) ),4) END AS CostPrice
--		FROM InOutstocktable
--		WHERE BillNumberId=@nBillID
--		GROUP BY ID
--	) a
--	WHERE STypeMoveBill.BillNumberId=@nBillID AND STypeMoveBill.ID=a.ID
--END

---- 自动生成的单据会影响草稿库存
--EXECUTE GP_CopyOrCreateBill_DraftQTY @intReturnID,@intBillType

--GO


/*

DECLARE
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0),			--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100),
	@strErrMsg				VARCHAR(100)			--出错信息
	
SELECT
	@chvOpID=1,
	@nBillID=6
	
	

EXEC	GP_STypeMoveOutBill_CreateBill
	@chvOpID,
	@nBillID,
	@intReturnID OUT,
	@strReturnBillCode OUT,
	@strErrMsg OUT

SELECT @strReturnBillCode,@strErrMsg


SELECT * FROM BillIndex WHERE BillType=187

*/




GO
IF EXISTS(SELECT Name FROM SysObjects WHERE ID=OBJECT_ID('dbo.GP_DeliveryBackBillDTCheck',N'P'))
BEGIN
	DROP PROC dbo.GP_DeliveryBackBillDTCheck;
END
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON;
GO
/*
	作者：陈强
	日期：2019-12-02
	描述：门店调货退货单保存前检查退货商品数量与原单商品数量
*/
CREATE PROC dbo.GP_DeliveryBackBillDTCheck
(
	@Details TbType_DeliveryBackBill READONLY
)
AS
BEGIN
	
	SELECT 1 AS Ret FROM DeliveryBackBill b JOIN 
	@Details d on b.BillNumberId=d.BillNumberId AND b.Id=d.Id
	WHERE d.BillNumberId <>0 AND ISNULL(b.Qty,0)-ISNULL(b.InflowQty,0)<d.Qty 
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


CREATE      PROCEDURE   GP_DelMonthEnd 
(
	@STypeID VARCHAR(100)=''
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @iniCanModify varchar(5) --是否已开帐，开帐 subValue ='F' 则可以删除上一次月结
DECLARE @period INT,
		@count INT,
		@year INT

SELECT @iniCanModify =SubValue FROM SysData WHERE SubName = 'inicanmodify'
if @iniCanModify ='t'
	BEGIN
		return -1 --未开帐，不能删除上一次月结
	END
	
select @count =COUNT(1) from monthproc WHERE STypeID=@STypeID
IF @count <2  -- period =1 还没有月结过，也就无法删除上一次月结
	BEGIN
		return -2 
	END
	
-- 得到最近一次月结的期号
SELECT TOP 1 @period=period,@Year=Year 
FROM monthproc 
WHERE monthno<>'本期' AND STypeID=@STypeID
ORDER BY StartDate DESC

declare @endDate DATETIME,@startdate datetime
select @startdate =startDate,@endDate=EndDate from monthproc where period=@period AND Year=@Year AND STypeID=@STypeID -- 最近一次月结的起始时间-1 就是上次月结的截止时间

-- 删除最近一次月结记录
DELETE  from monthproc where period =@period AND STypeID=@STypeID AND Year=@Year AND StartDate=@startdate AND EndDate=@endDate

--独立开账
DECLARE @StypeIndependentOpen INT
SELECT  @StypeIndependentOpen=SubValue FROM Sysdata WHERE SubName='StypeIndependentOpen'

--13 期间
DECLARE @IsThirtyPeriod INT=0
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE IsNature=0 AND IsDynamic=0 AND NatureCount=13)
BEGIN
	SET @IsThirtyPeriod=1
END

UPDATE	MonthProc
SET		StartDate =@startdate,
		Period = CASE WHEN @StypeIndependentOpen=1 AND Period=1 
					  THEN CASE WHEN @IsThirtyPeriod=1 THEN 13 ELSE 12 END
				 ELSE period-1
				 END,
		Year=@Year
WHERE	Monthno = '本期' AND STypeID=@STypeID
SELECT MAX(Period)FROM dbo.MonthProc WHERE MonthNo='本期'

-- 删除财务报表会计期间数据记录
DELETE FROM MonthATypeHistory
WHERE period = @period AND Stypeid=@STypeID AND Year=@year

DELETE FROM dbo.Ac_AssetsCards_History
WHERE BusinessDate=@endDate AND AuditType=-4 AND STypeId=@STypeID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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



/**********************************************************
作者:肖伟
日期:2002-11-5日
功能:取消做错的订单
**********************************************************/
CREATE      PROCEDURE [Gp_DelOrderBill] 
(
   @OrderBillNumberID numeric(10,0),          --订单BillNumberid号   
   @OrderBilltype   VARCHAR(4),			--订单类型
   @ordertype       INT,                --订单类型 0：销售订单 1：组合品销售订单
   @chvExcType		varchar(20),		-- 操作类型
   @stopreason		VARCHAR(max),		--中止原因
   @deldate		    VARCHAR(20)='',		--删除日期
   @deletypeid		VARCHAR(50)='',		--删除人
   @delip		    VARCHAR(20)=''		--删除IP
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------订单删除或终止执行解锁 start---------------------------------------------------------
IF @chvExcType IN ('Del','Stop')
BEGIN
	DECLARE @ClearDetail TbType_ClearDetail
	DECLARE @lockDetail TbType_LockDetail
	
	IF @OrderBilltype=313
	BEGIN
		INSERT INTO @ClearDetail (BillNumberId,OrderID) 
		SELECT billNumberID,OrderID
		FROM dbo.PT_Combin_OrderBillDetail
		WHERE billNumberID=@OrderBillNumberID
	END
	ELSE 
	BEGIN
		INSERT INTO @ClearDetail (BillNumberId,OrderID) 
		SELECT billNumberID,OrderID
		FROM dbo.OrderBill
		WHERE billNumberID=@OrderBillNumberID
	END
	
	EXEC dbo.GP_DoLock 0,@ordertype,@ClearDetail,@lockDetail
END
--------------------------------------------------------订单删除或终止执行解锁	 end---------------------------------------------------------

--------------------------------------------------------订单已关联收付款单不允许删除或终止 start---------------------------------------------------------
--IF @chvExcType IN ('Del','Stop')
--BEGIN
--	IF EXISTS(SELECT 1 FROM paybill WHERE RelevanceBillId=@OrderBillNumberID 
--				UNION ALL SELECT 1 FROM gatheringbill WHERE RelevanceBillId=@OrderBillNumberID 
--				UNION ALL SELECT 1 FROM prebill WHERE RelevanceBillId=@OrderBillNumberID
--			  )
--	RETURN 6
--END
--------------------------------------------------------订单已关联收付款单不允许删除或终止	 end---------------------------------------------------------
---------------删除订单 判断明细行是否被其他单调用 ,如果没有调用关系了 则为 未成交状态  如果还有调用关系 则为已成交状态start-------------
IF @chvExcType IN ('Del')
BEGIN
   IF @OrderBilltype IN (301)
   	begin
       update a set IfBargainOn=0
       from askpricebill a
       inner join (select AskBillNumberID,askbillid  from orderbill where billnumberid=@OrderBillNumberID)aa
       on a.billnumberid=aa.AskBillNumberID and a.id=aa.askbillid
       where not exists(select top 1 1 from orderbill cc where billnumberid<>@OrderBillNumberID
       and a.billnumberid=cc.AskBillNumberID and a.id=cc.askbillid )   
    end
    IF @OrderBilltype IN (300)
   	begin
      update a set IfBargainOn=0	
      from QuotePriceBill a
      inner join (select AskBillNumberID,askbillid  from orderbill where billnumberid=@OrderBillNumberID)aa
      on a.billnumberid=aa.AskBillNumberID and a.id=aa.askbillid
      where not exists(select top 1 1 from orderbill cc where billnumberid<>@OrderBillNumberID
      and a.billnumberid=cc.AskBillNumberID and a.id=cc.askbillid ) 
     end
END

-----------------删除订单 判断明细行是否被其他单调用 ,如果没有调用关系了 则为 未成交状态  如果还有调用关系 则为已成交状态end---------------

Declare @orderState char(1),@chvBillType int
IF @chvExcType = 'Del'
BEGIN
	Declare @ReachQty  NUMERIC(24, 10) 
	Declare @TotalQty  NUMERIC(24, 10) 
	DECLARE @qgCtrl VARCHAR(2)
	
	SET @qgCtrl= (select Value from Userconfig where ConfigName='qgctrl')
	SET @orderState ='0'

	select @orderState=orderState,@chvBillType=BillType from orderIndex where BillNumberid =@OrderBillNumberID
	IF @orderState='1' --已完成订单
		RETURN 1
	ELSE
	BEGIN
	    IF @ordertype=0
		    SELECT @ReachQty=sum(b.ReachQty),@TotalQty=a.TotalQty from OrderIndex a join OrderBill b on (a.BillNumberid=b.BillNumberid) where a.BillNumberid=@OrderBillNumberID group by a.TotalQty
		ELSE
		    SELECT @ReachQty=sum(b.ReachQty),@TotalQty=a.TotalQty from OrderIndex a join dbo.PT_Combin_OrderBill b on (a.BillNumberid=b.BillNumberid) where a.BillNumberid=@OrderBillNumberID group by a.TotalQty
		if @ReachQty<>0
		Begin

		         Return 2    --该单未完成,但是已有发货数量,已参与经营了
		End
		Else     --可以取消的订单
		Begin
			--处理订单库存
			IF @OrderBilltype IN (300,301,313)
			BEGIN
				CREATE TABLE #TEMPID
				(
					BillNumberID [numeric](18, 0) NOT NULL,
					BillType	INT NOT NULL
				)
				DECLARE @Billtype INT,@BillNumberID	INT
				IF @OrderBilltype=300
				BEGIN
					--销售出库
					INSERT INTO #TEMPID SELECT BillNumberId,11 FROM SaleBill WHERE OrderID IN (SELECT OrderID FROM OrderBill WHERE billNumberID=@OrderBillNumberID)
					--委托代销发货
					INSERT INTO #TEMPID SELECT BillNumberId,140 FROM commissionbill WHERE OrderID IN (SELECT OrderID FROM OrderBill WHERE billNumberID=@OrderBillNumberID) and Type=140
					--发出商品出库
					INSERT INTO #TEMPID SELECT BillNumberId,402 FROM SendBill WHERE OrderID IN (SELECT OrderID FROM OrderBill WHERE billNumberID=@OrderBillNumberID)
				END
				ELSE IF @OrderBilltype=301
				BEGIN
					--采购入库
					INSERT INTO #TEMPID SELECT BillNumberId,34 FROM BuyBill WHERE OrderID IN (SELECT OrderID FROM OrderBill WHERE billNumberID=@OrderBillNumberID)
					--受托代销收货
					INSERT INTO #TEMPID SELECT BillNumberId,144 FROM commissionbill WHERE OrderID IN (SELECT OrderID FROM OrderBill WHERE billNumberID=@OrderBillNumberID) and Type=144
					--暂估入库
					INSERT INTO #TEMPID SELECT BillNumberId,400 FROM AppraisalBill WHERE OrderID IN (SELECT OrderID FROM OrderBill WHERE billNumberID=@OrderBillNumberID)
				END
				ELSE
				BEGIN
					SET @Billtype=12
					INSERT INTO #TEMPID SELECT BillNumberId,12 FROM PT_Combin_SaleBill WHERE OrderID IN (SELECT OrderID FROM PT_Combin_OrderBill WHERE billNumberID=@OrderBillNumberID)
				END
				WHILE(EXISTS(SELECT 1 FROM #TEMPID))
				BEGIN
					SELECT TOP 1 @BillnumberID=BillnumberID,@Billtype=BillType FROM #TEMPID
					--先处理被引用未过账数量
					EXEC GP_Deal_OrderReferQty @BillNumberID,@Billtype,'-'
					
					DELETE #TEMPID WHERE BillnumberID=@BillnumberID
				END
				--处理订单库存limit数量
				EXEC QP_Recount_LimitQty_ByOrder @OrderBillNumberID,@OrderBilltype	
				EXEC GP_Deal_OrderQTY @OrderBillNumberID,@OrderBilltype,'-'
				
				DROP TABLE #TEMPID
			END
			
			IF @chvBillType = 300
			BEGIN
				UPDATE	SaleBill SET OrderID = -1
				WHERE	OrderID IN (
					SELECT	OrderID FROM OrderBill
					WHERE	BillNumberID = @OrderBillNumberID)
				
				UPDATE	dbo.SendBill SET OrderID = -1,OldBillNumberID=-1
				WHERE	OrderID IN (
					SELECT	OrderID FROM OrderBill
					WHERE	BillNumberID = @OrderBillNumberID)
					
				UPDATE	commissionbill SET OrderID = -1
				WHERE	OrderID IN (
					SELECT	OrderID FROM OrderBill
					WHERE	BillNumberID = @OrderBillNumberID) and Type=140
					
				--将订单引用的报价单数量修正
				UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)-ISNULL(o.Qty,0)
				FROM QuotePriceBill q
				INNER JOIN (
				SELECT  askbillnumberid,askbillid,SUM(ISNULL(o.Qty,0)) AS qty
				FROM OrderBill o
				WHERE o.billNumberID=@OrderBillNumberID AND o.askbillnumberid<>0 AND o.askbillid<>0
				GROUP BY o.billNumberID,o.askbillnumberid,o.askbillid
				) o ON q.BillNumberID=o.askbillnumberid AND q.id=o.AskBillID
				
				IF EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE IsYapi=1 AND billNumberId=@OrderBillNumberID)
				BEGIN
					DECLARE @yapiorderid VARCHAR(20)=''
					SELECT @yapiorderid=yapiorderid FROM dbo.OrderIndex WHERE billNumberId=@OrderBillNumberID
					DELETE FROM dbo.Yapi_OrderBillIndex WHERE orderid=@yapiorderid
					DELETE FROM dbo.Yapi_OrderBill WHERE orderid=@yapiorderid
				END
					
			END
			ELSE IF @OrderBilltype=313
			BEGIN 
			    UPDATE	dbo.PT_Combin_SaleBill SET OrderID = -1
				WHERE	OrderID IN (
					SELECT	OrderID FROM dbo.PT_Combin_OrderBill
					WHERE	BillNumberID = @OrderBillNumberID)
					
				UPDATE	PT_Combin_SaleBillDetail SET OrderID = -1
				WHERE	OrderID IN (
					SELECT	OrderID FROM dbo.PT_Combin_OrderBillDetail
					WHERE	BillNumberID = @OrderBillNumberID)
					
				--删除组合品销售订单 去除关联关系	
	          	UPDATE OrderBill SET PTCombinOrderBillDetailID =-1
		        WHERE PTCombinOrderBillDetailID IN (
		             SELECT ORDERID FROM PT_Combin_OrderBillDetail 
		             WHERE  billNumberID = @OrderBillNumberID)												
			END 
			ELSE
			BEGIN
				UPDATE	BuyBill SET OrderID = -1
				WHERE	OrderID IN (
					SELECT	OrderID FROM OrderBill
					WHERE	BillNumberID = @OrderBillNumberID)
					
				UPDATE dbo.AppraisalBill SET OrderID=-1,OldBillNumberID=-1
				WHERE	OrderID IN (
					SELECT	OrderID FROM OrderBill
					WHERE	BillNumberID = @OrderBillNumberID)
					
				UPDATE	commissionbill SET OrderID = -1
				WHERE	OrderID IN (
					SELECT	OrderID FROM OrderBill
					WHERE	BillNumberID = @OrderBillNumberID) and Type=144
				
				--将订单引用的询价单数量修正
				UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)-ISNULL(o.Qty,0)
				FROM AskPriceBill q
				INNER JOIN (
				SELECT  askbillnumberid,askbillid,SUM(ISNULL(o.Qty,0)) AS qty 
				FROM OrderBill o
				WHERE o.billNumberID=@OrderBillNumberID AND o.askbillnumberid<>0 AND o.askbillid<>0
				GROUP BY o.billNumberID,o.AskBillNumberID,o.askbillid
				) o ON q.BillNumberID=o.askbillnumberid  AND q.id=o.AskBillID
			END
			IF @OrderBilltype = 301 
			BEGIN
				--将订单引用的请购单数量修正
				UPDATE dbo.RequestBill SET RequestQty=ISNULL(RequestQty,0)-ISNULL(o.Qty,0)
				FROM RequestBill q
				INNER JOIN (
				SELECT  RequestBillNumberID,RequestBillID,SUM(ISNULL(o.Qty,0)) AS qty 
				FROM OrderBill o
				WHERE o.billNumberID=@OrderBillNumberID AND o.RequestBillNumberID<>0 AND o.RequestBillID<>0
				GROUP BY o.billNumberID,o.RequestBillNumberID,o.RequestBillID
				) o ON q.BillNumberID=o.RequestBillNumberID AND q.id=o.RequestBillID
				
				--回写销售订单的已采购订货数量--除开中止的单据 中止操作会及时去回写的
				UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
				FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID=@OrderBillNumberID and billover<>1 GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId
		        
		        --回写组合品销售订单的已采购订货数量--除开中止的单据 中止操作会及时去回写的		
		       UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		       FROM PT_Combin_OrderBillDetail A JOIN (select SUM(Qty) AS Qty,PTCombinOrderBillDetailID FROM dbo.OrderBill
		       WHERE billNumberID=@OrderBillNumberID and billover<>1 GROUP BY PTCombinOrderBillDetailID) B on A.ORDERID=B.PTCombinOrderBillDetailID
			END
			
			IF @chvBillType<>300 AND @OrderBilltype<>313
			BEGIN
				IF @qgCtrl='1'
				BEGIN
					UPDATE	RequestBill 
					SET		State=7,
							Etypeid=''
					FROM	OrderBill O 
					WHERE	RequestBill.ID=O.RequestBillID 
							AND O.BillNumberId=@OrderBillNumberID
							AND RequestBill.RequestQty=0--bug3460,只当RequestQty=0时，才把状态改为请购或者比价
				END 
				ELSE
				BEGIN
					UPDATE	RequestBill 
					SET		State=1,
							Etypeid=''
					FROM	OrderBill O 
					WHERE	RequestBill.ID=O.RequestBillID 
							AND O.BillNumberId=@OrderBillNumberID
							AND RequestBill.RequestQty=0--bug3460,只当RequestQty=0时，才把状态改为请购或者比价
				END
			END
			
			--删除日志记录,由于删除验证及删除动作都在这个存储过程中,所以记录日志也只能在这里面记录
			INSERT INTO BillDeleteLog(BillNumberID,BillType,BillCode,BillDate,StypeID,BtypeID,DealBTypeID,Checke,DelDate,DelEtypeID,DelIP)
            --VALUES(@billnumberid,@billtype,@billcode,@billdate,@stypeid,@btypeid,@dealbtypeid,@checke,@deldate,@deletypeid,@delip)
			SELECT BillNumberId,BillType,BillCode,BillDate,STypeID,BtypeID,DealBTypeID,Checke,@deldate,@deletypeid,@delip
            FROM OrderIndex
            WHERE BillNumberId=@OrderBillNumberID;
            
		    Delete from orderIndex where BillNumberID=@OrderBillNumberID
		    DELETE FROM BillMulAccount WHERE BillNumberId=@OrderBillNumberID AND BillType=@OrderBilltype--删除多账户
		    DELETE FROM dbo.PrintRecord WHERE BillNumberId = @OrderBillNumberID AND BillType = @OrderBilltype   --删除打印记录
		    DELETE FROM dbo.AddPrintCountRecord WHERE BillNumberId = @OrderBillNumberID AND BillType = @OrderBilltype    --删除增加的打印次数记录
		    --删除附件日志
            DELETE FROM dbo.BillAttachFilesLog WHERE BillNumberId = @OrderBillNumberID AND BillType = @OrderBilltype;
            DELETE FROM dbo.BillAttachFiles WHERE BillNumberId = @OrderBillNumberID AND BillType = @OrderBilltype;
		    UPDATE  orderIndex SET FromBillNumberID=null Where FromBillNumberID=@OrderBillNumberID
		    IF @ordertype=0
		        UPDATE  orderbill SET FromBillNumberId=0, FromBillId=0 Where FromBillNumberId=@OrderBillNumberID and FromBillId=@OrderBillNumberID
		    ELSE
		        UPDATE  dbo.PT_Combin_OrderBill SET FromBillNumberId=0, FromBillId=0 Where FromBillNumberId=@OrderBillNumberID and FromBillId=@OrderBillNumberID			        
		End
	END
END

DECLARE @chvBillOver varchar(1)
IF @chvExcType = 'Stop'
BEGIN
	SELECT	@chvBillOver = BillOver
	FROM	OrderIndex
	WHERE	BillNumberID = @OrderBillNumberID

	IF @chvBillOver <> 0 RETURN 3	-- 已是中止订单，不用再中止
	
	select @orderState=orderState,@chvBillType=BillType from orderIndex where BillNumberid =@OrderBillNumberID
	IF @orderState='1' --已完成订单
		RETURN 5
	
	--处理订单库存
	IF @OrderBilltype IN (300,301,313)
	BEGIN
		EXEC GP_Deal_OrderQTY_Stop @OrderBillNumberID,@OrderBilltype,-1,'-'
	END

	UPDATE	OrderIndex
	SET	BillOver = '1', OrderState='1'
	WHERE	BillNumberID = @OrderBillNumberID
	
	--中止明细
	IF @ordertype=0
	BEGIN 
		UPDATE OrderBill
		SET BillOver = '1',stopreason=@stopreason
		WHERE	BillNumberID = @OrderBillNumberID
	END
	BEGIN 
		UPDATE dbo.PT_Combin_OrderBill
		SET BillOver = '1',stopreason=@stopreason
		WHERE	BillNumberID = @OrderBillNumberID
		
		UPDATE dbo.PT_Combin_OrderBillDetail
		SET BillOver = '1',stopreason=@stopreason
		WHERE	BillNumberID = @OrderBillNumberID
	END
	--将订单引用的报价单数量修正
	UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)-ISNULL(o.Qty,0)
	FROM QuotePriceBill q
	INNER JOIN (
	SELECT  askbillnumberid,askbillid,SUM(ISNULL(o.Qty,0)) AS qty 
	FROM OrderBill o
	WHERE o.billNumberID=@OrderBillNumberID AND o.askbillnumberid<>0 AND o.askbillid<>0
	GROUP BY o.billNumberID,o.askbillnumberid,o.askbillid
	) o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.AskBillID

	--将订单引用的询价单数量修正
	UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)-ISNULL(o.Qty,0)
	FROM AskPriceBill q
	INNER JOIN (
	SELECT  askbillnumberid,askbillid,SUM(ISNULL(o.Qty,0)) AS qty 
	FROM OrderBill o
	WHERE o.billNumberID=@OrderBillNumberID AND o.askbillnumberid<>0 AND o.askbillid<>0
	GROUP BY o.billNumberID,o.AskBillNumberID,o.askbillid
	) o ON q.BillNumberID=o.askbillnumberid   AND q.ID=o.AskBillID
	
	--将订单引用的请购单数量修正
	UPDATE dbo.RequestBill SET RequestQty=ISNULL(RequestQty,0)-ISNULL(o.Qty,0)
	FROM RequestBill q
	INNER JOIN (
	SELECT  RequestBillNumberID,RequestBillID,SUM(ISNULL(o.Qty,0)) AS qty 
	FROM OrderBill o
	WHERE o.billNumberID=@OrderBillNumberID AND o.RequestBillNumberID<>0 AND o.RequestBillID<>0
	GROUP BY o.billNumberID,o.RequestBillNumberID,o.RequestBillID
	) o ON q.BillNumberID=o.RequestBillNumberID  and q.ID=o.RequestBillID
	
	--中止采购订单 修正销售订单的已采购数量 - 关联关系不处理
	IF @OrderBilltype = 301 
	begin
		UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID=@OrderBillNumberID GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId				
       --中止采购订单 修正组合品销售订单的已采购数量 - 关联关系不处理
	           UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		       FROM PT_Combin_OrderBillDetail A JOIN (select SUM(Qty) AS Qty,PTCombinOrderBillDetailID FROM dbo.OrderBill
		       WHERE billNumberID=@OrderBillNumberID GROUP BY PTCombinOrderBillDetailID) B on A.ORDERID=B.PTCombinOrderBillDetailID
	end
	
END

IF @chvExcType = 'StopFree'
BEGIN
	SELECT	@chvBillOver = BillOver
	FROM	OrderIndex
	WHERE	BillNumberID = @OrderBillNumberID

	IF @chvBillOver <> 1 RETURN 4	-- 非已中止订单，无法解除中止
	
	DECLARE @qtyOver INT =0;
	;WITH CurORDERQTY AS (
	SELECT c.RequestBillNumberID, c.RequestBillID,ISNULL((ISNULL(c.qty,0)+isnull(o.qty,0)),0) AS qty
	FROM
	(
	SELECT  billNumberID, RequestBillNumberID,RequestBillID,SUM(ISNULL(qty,0)) AS QTY
	FROM orderbill 
	WHERE billNumberID=@OrderBillNumberID AND RequestBillNumberID<>0 AND BillOver=1
	GROUP BY  billNumberID,RequestBillNumberID,RequestBillID
	)c
	left JOIN 
	(
	SELECT  b.billNumberID,b.RequestBillNumberID,b.RequestBillID,SUM(ISNULL(b.qty,0)) AS QTY
	FROM  orderbill b 
	INNER JOIN dbo.OrderIndex c ON b.billNumberID = c.billNumberId
	WHERE b.RequestBillNumberID<>0 AND b.RequestBillID<>0 AND b.BillOver = 0 AND c.IfAudit = 1
	GROUP BY b.billNumberID,b.RequestBillNumberID,b.RequestBillID
	)o  ON c.RequestBillNumberID=o.RequestBillNumberID AND c.RequestBillID=o.RequestBillID

	)

	SELECT  @qtyOver=COUNT(*)
	FROM  RequestBill b 
	INNER JOIN CurORDERQTY c ON b.BillNumberId=c.RequestBillNumberID AND b.ID=c.RequestBillID AND ISNULL(c.qty,0) > ISNULL(b.Qty,0)

	IF ISNULL(@qtyOver,0)>0 AND EXISTS (SELECT TOP 1 1 FROM userconfig WHERE ConfigName='notorderqtybiggerrequest' AND Value= '1')
		RETURN 7; 
	
	IF @ordertype=0
	BEGIN 
	IF exists(SELECT 1 FROM OrderBill WHERE billNumberID=@OrderBillNumberID AND ReachQty<qty) --存在发货数量小于订货数量，既未完成
	BEGIN
		UPDATE	OrderIndex
		SET	BillOver = '0',OrderState='0'
		WHERE	BillNumberID = @OrderBillNumberID
	END
	ELSE
	BEGIN
		UPDATE	OrderIndex
		SET	BillOver = '0',OrderState='1'
		WHERE	BillNumberID = @OrderBillNumberID
	END
	END 
	ELSE
	BEGIN 
	IF exists(SELECT 1 FROM dbo.PT_Combin_OrderBill WHERE billNumberID=@OrderBillNumberID AND ReachQty<qty) --存在发货数量小于订货数量，既未完成
	BEGIN
		UPDATE	OrderIndex
		SET	BillOver = '0',OrderState='0'
		WHERE	BillNumberID = @OrderBillNumberID
	END
	ELSE
	BEGIN
		UPDATE	OrderIndex
		SET	BillOver = '0',OrderState='1'
		WHERE	BillNumberID = @OrderBillNumberID
	END
	END 
	
	--处理订单库存
	IF @OrderBilltype IN (300,301,313)
	BEGIN
		EXEC GP_Deal_OrderQTY_Stop @OrderBillNumberID,@OrderBilltype,-1,'+'
	END
	
	--解除明细中止
	IF @ordertype=0
	BEGIN
	UPDATE OrderBill
	SET BillOver = '0',stopreason=''
	WHERE	BillNumberID = @OrderBillNumberID
	END 
	ELSE 
	BEGIN
	UPDATE dbo.PT_Combin_OrderBill
	SET BillOver = '0',stopreason=''
	WHERE	BillNumberID = @OrderBillNumberID
	
	UPDATE dbo.PT_Combin_OrderBillDetail
	SET BillOver = '0',stopreason=''
	WHERE	BillNumberID = @OrderBillNumberID
	END 
	--将订单引用的报价单数量修正
	UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)+ISNULL(o.Qty,0)
	FROM QuotePriceBill q
	INNER JOIN (
	SELECT  askbillnumberid,askbillid,SUM(ISNULL(o.Qty,0)) AS qty 
	FROM OrderBill o
	WHERE o.billNumberID=@OrderBillNumberID AND o.askbillnumberid<>0 AND o.askbillid<>0
	GROUP BY o.billNumberID,o.askbillnumberid,o.askbillid
	) o ON q.BillNumberID=o.askbillnumberid  AND q.id=o.AskBillID
	
	----将所有未引用的报价单改为未成交
	--UPDATE dbo.BillIndex SET IfBargainOn=1
	--FROM dbo.BillIndex b
	--WHERE b.BillNumberId IN ( SELECT AskBillNumberID 
	--							from dbo.OrderBill 
	--							WHERE billNumberID=@OrderBillNumberID AND AskBillNumberID<>0 AND AskBillID<>0) 
	--			AND b.BillType=184
	
	--将订单引用的询价单数量修正
	UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)+ISNULL(o.Qty,0)
	FROM AskPriceBill q
	INNER JOIN (
	SELECT  askbillnumberid,askbillid,SUM(ISNULL(o.Qty,0)) AS qty 
	FROM OrderBill o
	WHERE o.billNumberID=@OrderBillNumberID AND o.askbillnumberid<>0 AND o.askbillid<>0
	GROUP BY o.billNumberID,o.AskBillNumberID,o.askbillid
	) o ON q.BillNumberID=o.askbillnumberid  AND q.id=o.AskBillID
	
	--将所有未引用的询价单改为成交
	--UPDATE dbo.BillIndex SET IfBargainOn=1
	--FROM dbo.BillIndex b
	--WHERE b.BillNumberId IN ( SELECT AskBillNumberID 
	--							from dbo.OrderBill 
	--							WHERE billNumberID=@OrderBillNumberID AND AskBillNumberID<>0 AND AskBillID<>0) 
	--			AND b.BillType=185	

    		
	--将订单引用的请购单数量修正
	UPDATE dbo.RequestBill SET RequestQty=ISNULL(RequestQty,0)+ISNULL(o.Qty,0)
	FROM RequestBill q
	INNER JOIN (
	SELECT  RequestBillNumberID,RequestBillID,SUM(ISNULL(o.Qty,0)) AS qty 
	FROM OrderBill o
	WHERE o.billNumberID=@OrderBillNumberID AND o.RequestBillNumberID<>0 AND o.RequestBillID<>0
	GROUP BY o.billNumberID,o.RequestBillNumberID, o.RequestBillID
	) o ON q.BillNumberID=o.RequestBillNumberID AND q.id=o.RequestBillID
	
	--解除中止采购订单 修正销售订单的已采购数量 + 关联关系不处理
	IF @OrderBilltype = 301 
	begin
		UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)+ISNULL( B.qty,0)
		FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID=@OrderBillNumberID GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId		
		
	--解除中止采购订单 修正组合品销售订单的已采购数量 + 关联关系不处理
		 UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)+ISNULL( B.qty,0)
		 FROM PT_Combin_OrderBillDetail A JOIN (select SUM(Qty) AS Qty,PTCombinOrderBillDetailID FROM dbo.OrderBill
		 WHERE billNumberID=@OrderBillNumberID GROUP BY PTCombinOrderBillDetailID) B on A.ORDERID=B.PTCombinOrderBillDetailID

	end
							
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2019-01-25
	描述：删除已盘点过的单据并记录删除者信息
*/
CREATE PROCEDURE Gp_DelPassBill
(
	@ktypeid			VARCHAR(MAX),		-- 仓库id
	@ifwx				VARCHAR(1),			-- 是否维修
	@deldate			VARCHAR(50),		-- 删除日期
	@deletypeid			VARCHAR(50),		-- 删除操作员ID
	@delip				VARCHAR(100)		-- 删除的IP
	
)
--@encode$--
AS
SET NOCOUNT ON
IF @ktypeid=''
    IF  NOT EXISTS(SELECT * FROM StockCheckIndex where ifwx=@ifwx AND  pass = 1)
    BEGIN
		RAISERROR('没有已盘点的盘点单！',16,1)
		RETURN     
    END 
    ELSE
	BEGIN
		--记录删除日志
		INSERT INTO BillDeleteLog
		(
			BillNumberID, 
			BillType, 
			BillCode, 
			BillDate, 
			StypeID, 
			BtypeID, 
			DealBTypeID, 
			Checke, 
			DelDate, 
			DelEtypeID, 
			DelIP
		)
		SELECT	StockCheckId AS BillNumberId,
				306 AS BillType,
				BillCode,
				BillDate,
				'' AS STypeId,
				'' AS BtypeID,
				'' AS DealBTypeID,
				checke,
				@deldate,
				@deletypeid,
				@delip
		FROM	StockCheckIndex
		WHERE stockcheckid in (SELECT stockcheckid FROM StockCheckIndex WHERE ifwx=@ifwx AND  pass = 1)

		--删除数据
		DELETE FROM StockCheck WHERE stockcheckid in (SELECT stockcheckid FROM StockCheckIndex WHERE ifwx=@ifwx AND  pass = 1)
		DELETE FROM StockCheckIndex WHERE ifwx=0 AND  pass = 1 
	END
ELSE
    IF  NOT EXISTS(SELECT * FROM StockCheckIndex WHERE ifwx=@ifwx AND  pass = 1 AND KTypeID IN (SELECT a FROM dbo.f_split(@ktypeid,',')))
    BEGIN
		RAISERROR('没有已盘点的盘点单！',16,1)
		RETURN    
    END 
    ELSE
	BEGIN
		--记录删除日志
		INSERT INTO BillDeleteLog
		(
			BillNumberID, 
			BillType, 
			BillCode, 
			BillDate, 
			StypeID, 
			BtypeID, 
			DealBTypeID, 
			Checke, 
			DelDate, 
			DelEtypeID, 
			DelIP
		)
		SELECT	StockCheckId AS BillNumberId,
				306 AS BillType,
				BillCode,
				BillDate,
				'' AS STypeId,
				'' AS BtypeID,
				'' AS DealBTypeID,
				checke,
				@deldate,
				@deletypeid,
				@delip
		FROM	StockCheckIndex
		WHERE	ifwx=0 
				AND  pass = 1 
				AND KTypeID IN (SELECT a FROM dbo.f_split(@ktypeid,','))
		
		--删除数据
		DELETE 
		FROM	StockCheck 
		WHERE	stockcheckid IN (SELECT stockcheckid FROM  StockCheckIndex WHERE ifwx=@ifwx AND  pass = 1 
		AND		KTypeID IN (
								SELECT a FROM dbo.f_split(@ktypeid,','))
				)
					
		DELETE FROM StockCheckIndex WHERE ifwx=0 AND  pass = 1 AND KTypeID IN (SELECT a FROM dbo.f_split(@ktypeid,','))
	END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DelPayConfigInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_DelPayConfigInfo]
GO
--==========================================================
--BY:zy
--DATE:2017-07-03
--DESCRIPTION:删除账户配置
--==========================================================
CREATE PROC Gp_DelPayConfigInfo
(
	@id			INT,
	@paytype   INT	   -- 账户类型：1---支付宝，2---微信
)
--@encode$--

AS
SET NOCOUNT ON

IF EXISTS(SELECT 1 FROM PayConfigInfo WHERE ID=@id AND PayType=@paytype)
BEGIN
	DELETE FROM POSPayConfigInfo WHERE PayConfigID=@id
	
	DELETE FROM StypePayConfigInfo WHERE PayConfigID=@id
	
	IF @@ERROR=0
	BEGIN
		DELETE FROM PayConfigInfo WHERE ID=@id
	END
END
	
	
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2009-06-10
	描述：删除价保通知
	SELECT * FROM PriceProtect
*/
CREATE PROCEDURE Gp_DelPriceProtect
(
	@nid		varchar(20),
	@state		varchar(10),
	@chk		varchar(10),
	@startdate	varchar(20),
	@enddate	varchar(20)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @nbillids 	varchar(8000),
		@nPriceId	varchar(1000)

IF @state = '1'
	BEGIN
		SELECT @nbillids = Billids FROM PriceProtect WHERE PriceId = @nid

		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@nbillids,',') WHERE ISNULL(a,'')<>''))
			RETURN -1

		DELETE FROM PriceProtect WHERE PriceId = @nid
	END
ELSE IF @state = '2'
	BEGIN		
		IF @chk = '0'	--无效
			DECLARE Del2Cursor CURSOR FOR	
				SELECT PriceId,Billids FROM PriceProtect WHERE [Date]<=CONVERT(varchar(10),GetDate(),120)
		ELSE
			DECLARE Del2Cursor CURSOR FOR	
				SELECT PriceId,Billids FROM PriceProtect WHERE [Date]>=CONVERT(varchar(10),GetDate(),120)

		OPEN Del2Cursor

		FETCH NEXT FROM Del2Cursor INTO @nPriceId,@nBillIds

		WHILE @@FETCH_STATUS  = 0
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@nbillids,',') WHERE ISNULL(a,'')<>''))
					DELETE FROM PriceProtect WHERE PriceId = @nPriceId
				ELSE
					RETURN -1

				FETCH NEXT FROM Del2Cursor INTO @nPriceId,@nBillIds
			END

		CLOSE Del2Cursor
		DEALLOCATE Del2Cursor
	END
ELSE
	BEGIN
		DECLARE Del3Cursor CURSOR FOR
			SELECT PriceId,Billids FROM PriceProtect WHERE [Date]>=@startdate AND [Date]<=@enddate

		OPEN Del3Cursor

		FETCH NEXT FROM Del3Cursor INTO @nPriceId,@nBillIds

		WHILE @@FETCH_STATUS  = 0
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@nbillids,',') WHERE ISNULL(a,'')<>''))
					DELETE FROM PriceProtect WHERE PriceId = @nPriceId
				ELSE
					RETURN -1
				
				FETCH NEXT FROM Del3Cursor INTO @nPriceId,@nBillIds
			END

		CLOSE Del3Cursor
		DEALLOCATE Del3Cursor
	END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
	删除计量单位
*/
CREATE PROCEDURE Gp_DelPtypeUnit
(
	@Unitsid			INT
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM PType_Units_Ext WHERE UnitsId = @Unitsid)
BEGIN
	RAISERROR('计量单位已被商品使用，禁止删除!',16,1) 
	RETURN
END

IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE adjustaccounts=1 and unitid = @Unitsid )
BEGIN
	RAISERROR('计量单位已被数量核算使用，禁止删除!',16,1) 
	RETURN
END

IF EXISTS(SELECT TOP 1 1 FROM PType WHERE baseUnitId = @Unitsid OR BuyUnitId = @Unitsid OR SaleUnitId = @Unitsid OR AssistantUnitId = @Unitsid OR StockUnitId = @Unitsid)
BEGIN
	RAISERROR('计量单位已被商品使用，禁止删除!',16,1) 
	RETURN
END

DELETE Ptype_Units WHERE Unitsid = @Unitsid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		重新按单结算前删除已经结算的情况
-- 最后修改作者：    cqhua
-- 最后修改时间：	2005-09-07
-- ========================================================================
CREATE                              PROCEDURE [GP_DelReInsertCompleteTotal]
(
@intMoneyNumberId int,
@todel  varchar(1)
)

AS
SET NOCOUNT ON

-------------指定的单据不存在
IF NOT EXISTS(SELECT BillnumberID FROM Billindex WHERE BillnumberID=@intMoneyNumberId)
	RETURN 1

--Select * from Billindex
--select * from completeTotal
DECLARE @Billtype  int -- 收、付款单据类型
DECLARE @Billtype1 int -- 物流单据类型
DECLARE @szBtypeid VARCHAR(50) --结算单位
DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

SELECT @Billtype =Billtype,@szBtypeid=btypeid FROM Billindex WHERE  BillnumberID=@intMoneyNumberId

DECLARE @SQL varchar(2000)
DECLARE @intGoodsNumberId INT
DECLARE @intGoodsDetailId int
--DECLARE @Billtype int
DECLARE @decCompleteTotal  NUMERIC(24, 10) 
DECLARE @decNCompleteTotal  NUMERIC(24, 10) 
DECLARE @isini bit

CREATE TABLE #BillIDTable (BillNumberID int,BillType INT)

SELECT @SQL = '
			DECLARE Rows_Cursor CURSOR FOR
				SELECT	
						b.BillNumberID,
						b.Billtype,
						c.GoodsBillDetailID,
						-isnull(c.CompleteTotal,0) as decCompleteTotal,
						-isnull(c.NCompleteTotal,0) as decNCompleteTotal 
				FROM Billindex b,completeTotal c
				WHERE b.BillnumberID =c.GoodsBillID AND c.MoneyBillID='+convert(varchar(20),@intMoneyNumberId) 
				+'  AND B.BillType=C.BillType
				UNION ALL
				SELECT	
						b.BillNumberID,
						b.Billtype,
						c.GoodsBillDetailID,
						-isnull(c.CompleteTotal,0) as decCompleteTotal,
						-isnull(c.NCompleteTotal,0) as decNCompleteTotal 
				FROM ReceiptBillIndex b,completeTotal c
				WHERE b.BillnumberID =c.GoodsBillID AND c.MoneyBillID='+convert(varchar(20),@intMoneyNumberId)
				+'  AND B.BillType=C.BillType
				UNION ALL
				SELECT	
						b.BillNumberID,
						b.Billtype,
						c.GoodsBillDetailID,
						-isnull(c.CompleteTotal,0) as decCompleteTotal,
						-isnull(c.NCompleteTotal,0) as decNCompleteTotal 
				FROM dbo.Coupon_BillIndex b,completeTotal c
				WHERE b.BillnumberID =c.GoodsBillID AND c.MoneyBillID='+convert(varchar(20),@intMoneyNumberId)
				+'  AND B.BillType=C.BillType'
EXEC(@SQL)
OPEN Rows_Cursor
FETCH NEXT FROM Rows_Cursor INTO @intGoodsNumberId,@Billtype1,@intGoodsDetailId,@decCompleteTotal,@decNCompleteTotal

WHILE ( @@FETCH_STATUS = 0 )
BEGIN
	INSERT INTO #BillIDTable (BillNumberID,BillType) VALUES(@intGoodsNumberId,@Billtype1)
	-- =====================================================收款单
	IF @Billtype=4
	BEGIN
		IF @Billtype1 IN(45,46) OR @Billtype1=148 OR @Billtype1=115 OR @Billtype1=149 OR (@Billtype1=36 AND @ExpenseToAr=1 AND LEFT(@szBtypeid,5)='00001') -- 销售退货单45 返利执行单148  价保执行单149 启用了配置后的费用单
		BEGIN
			UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+(-@decCompleteTotal),NCompleteTotal = isnull(NCompleteTotal,0)+(-@decNCompleteTotal)
			WHERE BillnumberID=@intGoodsNumberId

			IF @BillType1=45  --商品结算
			   Update saleBackBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
									   CompleteTotal=ISNULL(A.Completetotal,0)-ABS(C.CompleteGoodTotal),
									   NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
			        FROM saleBackBill A,CompleteGoodTotal C  
				WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0  AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
				AND C.BillType=@Billtype1
				
			IF @BillType1=46  --商品结算
			   Update dbo.PT_Combin_SaleBackBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
									   CompleteTotal=ISNULL(A.Completetotal,0)-ABS(C.CompleteGoodTotal),
									   NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
			        FROM PT_Combin_SaleBackBill A,CompleteGoodTotal C  
				WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0  AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
				AND C.BillType=@Billtype1
		END
		ELSE IF @Billtype1=405
		BEGIN
			UPDATE ReceiptBillIndex SET CompleteTotal=ISNULL(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = ISNULL(NCompleteTotal,0)+@decNCompleteTotal
			WHERE BillNumberID=@intGoodsNumberId
			
			Update ReceiptBill SET CompleteQTY = ISNULL(A.CompleteQTY,0)-C.CompleteGoodQTY,
								   CompleteTotal=ISNULL(A.CompleteTotal,0)-C.CompleteGoodTotal,
								   NCompleteTotal=ISNULL(A.NCompleteTotal,0)- C.NCompleteGoodTotal
			FROM ReceiptBill A,CompleteGoodTotal C  
			WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY<>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
			AND C.BillType=A.BillType
		END
		ELSE IF @Billtype1 =424
		BEGIN
			UPDATE dbo.Coupon_BillIndex SET CompleteTotal=ISNULL(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = ISNULL(NCompleteTotal,0)+@decNCompleteTotal
			WHERE BillNumberID=@intGoodsNumberId
			
		END
		ELSE IF @Billtype1 = 426
		BEGIN		
			UPDATE Coupon_BillIndex SET CompleteTotal = isnull(CompleteTotal,0)+(-@decCompleteTotal),NCompleteTotal = isnull(NCompleteTotal,0)+(-@decNCompleteTotal)
			WHERE BillnumberID=@intGoodsNumberId
		END 
		ELSE  -- 销售出库单11  委托代销结算141 其他收入单93 固定资产变卖85
		BEGIN
			UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = isnull(NCompleteTotal,0)+@decNCompleteTotal
			WHERE BillnumberID=@intGoodsNumberId
			
			IF @BillType1=11  --商品结算
			   Update saleBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
								   CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
								   NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
			        FROM saleBill A,CompleteGoodTotal C  
				WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
				AND C.BillType=@Billtype1
				
			IF @BillType1=12  --商品结算
			   Update dbo.PT_Combin_SaleBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
								   CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
								   NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
			        FROM PT_Combin_SaleBill A,CompleteGoodTotal C  
				WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
				AND C.BillType=@Billtype1
				
			IF @BillType1=145 OR @Billtype1 = 141  --商品结算

			   Update CommissionBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY) ,
										 CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
										 NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
			        FROM CommissionBill A, CompleteGoodTotal C  
				WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
				AND C.BillType=@Billtype1
			IF @BillType1=160  --销售换货单 按商品结算

			   Update SaleGoodsExchangeBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
			   									CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
												NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
			        FROM SaleGoodsExchangeBill A, CompleteGoodTotal C  
				WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
				AND C.BillType=@Billtype1
			IF @BillType1=167	-- 新维修 - 取件单

			   Update wx_Bill_GetBack SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
			   							  CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
									      NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
			        FROM wx_Bill_GetBack A, CompleteGoodTotal C  
				WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
				AND C.BillType=@Billtype1
			IF @BillType1=168	-- 新维修 - 整机更换单
			
			   Update wx_Bill_Replace SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
										  CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
										  NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
			        FROM wx_Bill_Replace A, CompleteGoodTotal C  
				WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
			AND C.BillType=@Billtype1
		END
	END
	
	-- 付款单
	IF @Billtype=66
	BEGIN
		IF @Billtype1 =6 OR @Billtype1=150 OR @Billtype1=151 OR @Billtype1=129 -- 采购退货单6 获利核算执行单150 获得价保执行单151  
		BEGIN
			UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+(-@decCompleteTotal),NCompleteTotal = isnull(NCompleteTotal,0)+(-@decNCompleteTotal) WHERE BillnumberID=@intGoodsNumberId
	
				IF @BillType1=6
				   Update BuyBackBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),  ---退货单，结算数量为负
										  CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
										  NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
				        FROM BuyBackBill A,CompleteGoodTotal C  
					WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID  AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
					AND C.BillType=@Billtype1

		END
		ELSE IF @Billtype1=404
		BEGIN
			UPDATE ReceiptBillIndex SET CompleteTotal = ISNULL(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = ISNULL(NCompleteTotal,0)+@decNCompleteTotal	
			WHERE BillnumberID=@intGoodsNumberId
			
			Update ReceiptBill SET CompleteQTY = ISNULL(A.CompleteQTY,0)-C.CompleteGoodQTY,
								   CompleteTotal=ISNULL(A.CompleteTotal,0)-C.CompleteGoodTotal,
								   NCompleteTotal=ISNULL(A.NCompleteTotal,0)- C.NCompleteGoodTotal
			FROM ReceiptBill A,CompleteGoodTotal C  
			WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY<>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
			AND A.BillType=C.BillType
		END
		ELSE IF @Billtype1=423
		BEGIN
			UPDATE dbo.Coupon_BillIndex SET CompleteTotal=ISNULL(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = ISNULL(NCompleteTotal,0)+@decNCompleteTotal
			WHERE BillNumberID=@intGoodsNumberId
			
		END
		ELSE  -- 采购入库单34  受托代销结算145 费用单36 固定资产购买84
		BEGIN
			UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = isnull(NCompleteTotal,0)+@decNCompleteTotal			WHERE BillnumberID=@intGoodsNumberId
				
				IF @BillType1=34   --商品结算
				   Update BuyBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
									  CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
								      NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal)
				        FROM BuyBill A,CompleteGoodTotal C  
					WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
					AND C.BillType=@Billtype1
				IF @BillType1=145  --商品结算

				   Update CommissionBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
											 CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
											 NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal) 
				        FROM CommissionBill A, CompleteGoodTotal C  
					WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
					AND C.BillType=@Billtype1
				IF @BillType1=161  --采购换货单 按商品结算
	
				   Update BuyGoodsExchangeBill SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
												   CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
											       NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal) 		   
				        FROM BuyGoodsExchangeBill A, CompleteGoodTotal C  
					WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
					AND C.BillType=@Billtype1
				IF @BillType1=170	-- 新维修 - 送修返回单

				   Update wx_Bill_SendBack SET CompleteQTY = isnull(A.CompleteQTY,0)-ABS(C.CompleteGoodQTY),
											   CompleteTotal=ISNULL(A.CompleteTotal,0)-ABS(C.CompleteGoodTotal),
											   NCompleteTotal=ISNULL(A.NCompleteTotal,0)-ABS(C.NCompleteGoodTotal) 
				        FROM wx_Bill_SendBack A, CompleteGoodTotal C  
					WHERE A.BillNumberID=C.GoodsBillid AND A.[ID]=C.BillID AND A.CompleteQTY>0 AND C.GoodsBillid=@intGoodsNumberId AND C.MoneyBillID=@intMoneyNumberId
					AND C.BillType=@Billtype1
		END
	END
	IF @Billtype1 IN (115,116,128,129)--重现结算应收\应付增加\减少单要回写明细的计算金额
	BEGIN
		UPDATE	dbo.AdDebtBill
		SET		CompleteTotal=CompleteTotal - ABS(@decCompleteTotal),
				NCompleteTotal=NCompleteTotal - ABS(@decNCompleteTotal)
		WHERE   ID=@intGoodsDetailId 
	END
	FETCH NEXT FROM Rows_Cursor INTO @intGoodsNumberId,@Billtype1,@intGoodsDetailId,@decCompleteTotal,@decNCompleteTotal
END

DELETE FROM CompleteTotal WHERE MoneyBillID=@intMoneyNumberId

IF (@todel='Y')
BEGIN	
	DELETE FROM CompleteGoodTotal WHERE MoneyBillID=@intMoneyNumberId
	DELETE FROM dbo.CompleteBrandarTotal WHERE MoneyBillID=@intMoneyNumberId
END		
ELSE
BEGIN 
	UPDATE CompleteGoodTotal SET draft=1 WHERE MoneyBillID=@intMoneyNumberId		--haiquan添加删除按商品结算内容
	UPDATE CompleteBrandarTotal SET IsDraft=1 WHERE MoneyBillID=@intMoneyNumberId
END 

CLOSE Rows_Cursor	-- 关闭游标
DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源

-- *** 处理九种单据结算状态 - Start ***
DECLARE @intBillType int,@TotalMoney  NUMERIC(24, 10) ,@TotalInMoney  NUMERIC(24, 10) 
DECLARE @preferencemoney  NUMERIC(24, 10) ,@CompleteTotal  NUMERIC(24, 10) 

-- jsStyle：0 - 无，1 - 按单结算，2 - 按商品结算
-- jsState：0 - 未结算，1 - 未完成结算，2 - 结算完成
DECLARE @jsStyle char(1),@jsState char(1)
DECLARE @isgoodscomplete int --是否为按商品结算
DECLARE @isbrandarcomplete INT --是否按品牌
DECLARE @GoodsBillType INT
DECLARE Bill_Cursor CURSOR FOR
	SELECT BillNumberID,BillType FROM #BillIDTable
OPEN Bill_Cursor
FETCH NEXT FROM Bill_Cursor INTO @intGoodsNumberId,@GoodsBillType
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
	IF @GoodsBillType IN (404,405)
		SELECT @intBillType=BillType,@TotalMoney=TaxTotalMoney,@TotalInMoney=0,
		@preferencemoney=0,@CompleteTotal=CompleteTotal,@isini=IsIni
		FROM ReceiptBillIndex WHERE BillnumberID=@intGoodsNumberId	
	ELSE IF @GoodsBillType IN (423,424,426)
		SELECT @intBillType=BillType,@TotalMoney=TotalMoney,@TotalInMoney=TotalInMoney,
		@preferencemoney=PreferenceMoney,@CompleteTotal=CompleteTotal,@isini=IsIni
		FROM dbo.Coupon_BillIndex WHERE BillnumberID=@intGoodsNumberId	
	ELSE 
		SELECT @intBillType=BillType,@TotalMoney=TotalMoney,@TotalInMoney=TotalInMoney,
		@preferencemoney=preferencemoney,@CompleteTotal=CompleteTotal,@isini=IsIni
		FROM BillIndex WHERE BillnumberID=@intGoodsNumberId
	
	SET @isgoodscomplete=0
	IF EXISTS (SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=@intGoodsNumberId AND billtype =@GoodsBillType)
		SET @isgoodscomplete=1
		
	SET @isbrandarcomplete = 0	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteBrandarTotal WHERE GoodsBillID = @intGoodsNumberId AND BillType=@GoodsBillType)
		OR EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId = @intGoodsNumberId AND jsStyle = 3 AND billtype=@GoodsBillType)
		SET @isbrandarcomplete = 1
			
	IF @isini=1 AND @intBillType NOT IN (85,115,116,128,129,150)--期初单据
	BEGIN
	/******************处理期初填写了结算数量的单据*********************/
			DECLARE @iniTableName varchar(200)
			DECLARE @iniCompleteQty decimal(18,4)
			DECLARE @iniSQL varchar(2000)
			-- 这几张单据没有结算数量，排除判断
			IF @intBillType NOT IN (36,93,148,149,172,213,116,115,128,129,151,150,167,168,172,450,84,85,212,213,181,312,423,424,426)
			BEGIN
				CREATE TABLE #iniTempTable
				(
					CompleteQty DECIMAL(18,4)
				) 
				
				SELECT  @iniTableName = detailTable FROM BILLNAME WHERE BillType=@intBillType
				SET @iniSQL = '
				INSERT INTO #iniTempTable
				SELECT ISNULL(sum(completeqty),0) as completeqty 
				FROM '+@iniTableName+' WHERE billnumberid='''+CAST(@intGoodsNumberId AS VARCHAR(20))+''''
				EXEC(@iniSQL)
				SELECT @iniCompleteQty = CompleteQty FROM #iniTempTable
				
				IF @iniCompleteQty <> 0
				BEGIN
					SELECT @isgoodscomplete=1
				END
				DROP TABLE #iniTempTable				
			END
			
			IF (@TotalMoney>=0 AND (@TotalMoney-@Preferencemoney) <= @CompleteTotal)
			OR (@TotalMoney<0 AND (@TotalMoney-@Preferencemoney) >= @CompleteTotal)
			BEGIN
				IF @isgoodscomplete=1
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET JSState='2',JSStyle='2' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE IF @isbrandarcomplete = 1
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
					ELSE IF @intBillType IN (423,424,426)
						UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE IF @CompleteTotal <> 0
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
					ELSE IF @intBillType IN (423,424,426)
						UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE 
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '2' WHERE BillNumberID=@intGoodsNumberId	
					ELSE IF @intBillType IN (423,424,426)
						UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId	
					ELSE
						UPDATE BillIndex SET jsStyle = '0',jsState = '2' WHERE BillNumberID=@intGoodsNumberId	
			END
			ELSE
			BEGIN
				IF @CompleteTotal<>0 
				BEGIN
					IF @isgoodscomplete=1
						IF @intBillType IN (404,405)
							UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
						ELSE IF @intBillType IN (423,424,426)
							UPDATE dbo.Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
						ELSE 
							UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
					ELSE IF @isbrandarcomplete = 1
						IF @intBillType IN (404,405)
							UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
						ELSE IF @intBillType IN (423,424,426)
							UPDATE dbo.Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
						ELSE
							UPDATE BillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
					ELSE 
						IF @intBillType IN (404,405)
							UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
						ELSE IF @intBillType IN (423,424,426)
							UPDATE dbo.Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId	
						ELSE
							UPDATE BillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId	
				END	
				ELSE
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId	
					ELSE IF @intBillType IN (423,424,426)
						UPDATE dbo.Coupon_BillIndex SET jsState = '0' WHERE BillNumberID=@intGoodsNumberId	
					ELSE 
						UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId			
			END
	END
	ELSE
	IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsBillID=@intGoodsNumberId AND BillType = @intBillType AND Draft = 0)
	BEGIN
		--IF @TotalInMoney <> 0 OR @Preferencemoney <> 0
		--BEGIN
			IF (@TotalMoney>=0 AND (@TotalMoney-@Preferencemoney) <= @TotalInMoney)
			OR (@TotalMoney<0 AND (@TotalMoney-@Preferencemoney) >= @TotalInMoney)
			BEGIN
				IF @TotalInMoney <> 0
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET JSStyle=CASE WHEN @isbrandarcomplete = 1 THEN '3' ELSE '1' END ,JSState='2' WHERE BillNumberID=@intGoodsNumberId
					ELSE IF @intBillType IN (423,424,426)
						UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = CASE WHEN @isbrandarcomplete = 1 THEN '3' ELSE '1' END ,jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
					ELSE IF @intBillType IN (423,424,426)
						UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = '0',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			END
			ELSE 
			BEGIN
				IF @TotalInMoney <> 0
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = CASE WHEN @isbrandarcomplete = 1 THEN '3' ELSE '1' END ,jsState = '1' WHERE BillNumberID=@intGoodsNumberId
					ELSE IF @intBillType IN (423,424,426)
						UPDATE dbo.Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = CASE WHEN @isbrandarcomplete = 1 THEN '3' ELSE '1' END ,jsState = '1' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
					ELSE IF @intBillType IN (423,424,426)
						UPDATE dbo.Coupon_BillIndex SET jsState = '0' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
			END
		--END
		--ELSE
		--	UPDATE BillIndex SET jsStyle = '0',jsState = '0' WHERE BillNumberID=@intGoodsNumberId
	END
	ELSE 
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=@intGoodsNumberId AND billtype =@GoodsBillType AND Draft = 0)
			AND @isbrandarcomplete = 0
		BEGIN
			IF (@TotalMoney>=0 AND (@TotalMoney-@Preferencemoney) <= @CompleteTotal+@TotalInMoney)
			OR (@TotalMoney<0 AND (@TotalMoney-@Preferencemoney) >= @CompleteTotal+@TotalInMoney)
				IF @intBillType IN (423,424,426)
					UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE 
					UPDATE BillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			ELSE
				IF @intBillType IN (404,405)
					UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
				ELSE IF @intBillType IN (423,424,426)
					UPDATE dbo.Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					UPDATE BillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId					
		END
		ELSE IF @isbrandarcomplete = 1
		BEGIN
			IF(@TotalMoney-@Preferencemoney)=(@CompleteTotal+@TotalInMoney)
				IF @intBillType IN (404,405)
					UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE IF @intBillType IN (423,424,426)
					UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					UPDATE BillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			ELSE
				IF @intBillType IN (404,405)
					UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
				ELSE IF @intBillType IN (423,424,426)
					UPDATE dbo.Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					UPDATE BillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@intGoodsNumberId			
		END
		ELSE IF @intBillType NOT IN(423,424,426)
		BEGIN 
			IF @intBillType NOT IN (160,161)
			BEGIN
				IF(@TotalMoney-@Preferencemoney)=(@CompleteTotal+@TotalInMoney)
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					IF @intBillType IN (404,405)
						UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
					ELSE
						UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
			END
			ELSE
			BEGIN
				DECLARE @sumComGoodQtyOut  NUMERIC(24, 10) ,@sumBillGoodQtyOut  NUMERIC(24, 10) 
				DECLARE @sumComGoodQtyIn  NUMERIC(24, 10) ,@sumBillGoodQtyIn  NUMERIC(24, 10) 
				SELECT @sumComGoodQtyOut=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
				WHERE GoodsBillID=@intGoodsNumberId AND InOrOut = 'O' AND Draft = 0
				SELECT @sumComGoodQtyIn=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
				WHERE GoodsBillID=@intGoodsNumberId AND InOrOut = 'I' AND Draft = 0
				IF @intBillType = 160
				BEGIN
					SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
					WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
					SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
					WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
				END
				IF @intBillType = 161
				BEGIN
					SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
					WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
					SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
					WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
				END
				IF (@TotalMoney-@Preferencemoney)=(@CompleteTotal+@TotalInMoney) AND
					(@sumComGoodQtyOut+@sumComGoodQtyIn)=(@sumBillGoodQtyOut+@sumBillGoodQtyIn)
					UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
			END
		END
	END
	
	IF @GoodsBillType IN(115,116)
	BEGIN
		UPDATE t SET t.jsState = CASE WHEN CompleteTotal+ChargeOffTotal = 0 THEN 0 WHEN total -CompleteTotal-ChargeOffTotal = 0 THEN 2 ELSE 1 END ,
					 t.jsStyle = CASE WHEN CompleteTotal = 0 THEN 0 ELSE t.jsStyle END 
		FROM AdDebtBill t
		WHERE BillNumberId = @intGoodsNumberId
		--INNER JOIN dbo.CompleteTotal c ON c.GoodsBillID = @intGoodsNumberId AND c.MoneyBillID = @intMoneyNumberId AND c.GoodsBillDetailID = t.ID
	END 
	
	FETCH NEXT FROM Bill_Cursor INTO @intGoodsNumberId,@GoodsBillType
END
CLOSE Bill_Cursor	-- 关闭游标
DEALLOCATE Bill_Cursor	-- 释放游标所使用的资源

DROP TABLE #BillIDTable
-- *** 处理九种单据结算状态 - End ***
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-09-02
	描述：删除请购单
*/

CREATE PROCEDURE Gp_DelRequestBill 
(
	@billnumberidlist			VARCHAR(max)	--单据ID集合
)
--@encode$--
AS
SET NOCOUNT ON
--判断请购单是否执行（状态为请购或取消的时候为未执行。防止开多个窗口，其中一个窗口把状态已经修改了）
IF  Exists(SELECT * FROM RequestBill where billnumberid in(select * from DBO.f_split(@billnumberidlist,',')) AND state not in (1,5))
BEGIN
	RAISERROR('有选中的请购单已经被执行，请刷新后重试！',16,1)
	RETURN 
END

BEGIN TRANSACTION  DEL

DELETE FROM requestindex WHERE billnumberid in(select * from DBO.f_split(@billnumberidlist,','))
DELETE FROM dbo.RequestBill WHERE BillNumberId in(select * from DBO.f_split(@billnumberidlist,','))
DELETE FROM dbo.PrintRecord WHERE BillNumberId IN (select * from DBO.f_split(@billnumberidlist,',')) AND BillType = '204' --删除打印记录
DELETE FROM dbo.AddPrintCountRecord WHERE BillNumberId IN (select * from DBO.f_split(@billnumberidlist,',')) AND BillType = '204'  --删除增加的打印次数记录	

--删除自定义
DELETE FROM CustomBillColumns	WHERE  billnumberid in(select * from DBO.f_split(@billnumberidlist,',')) AND BillType=204
DELETE FROM [CustomBillDetailColumns]WHERE billnumberid in(select * from DBO.f_split(@billnumberidlist,',')) AND BillType=204

IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('删除失败！',16,1)
END

COMMIT TRANSACTION  DEL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-09-09
	描述：处理保养档案信息
*/
CREATE PROCEDURE Gp_DelVacation
(
	@id	varchar(100)	--节假日ID
)
--@encode$--
AS
SET NOCOUNT ON

DELETE FROM Vacation WHERE ID=@id
DELETE FROM VacationDetails WHERE IndexId = @id
IF @@ERROR<>0
	RAISERROR('删除节假日信息失败！',16,1)	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





/*
	作者：谢吉康
	日期：2009-06-04
	描述：删除VIP卡类型
*/
CREATE PROCEDURE Gp_DelVipCardLx
(
	@nid		numeric(18,0)
)
--@encode$--
AS
SET NOCOUNT ON

--判断是否已经使用
IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardTypeId = @nid and deleted<>'1' and VipCardID in (select vipcardid From BillIndex))
	RETURN -1

--判断是否有初始金额
IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardTypeId = @nid and deleted<>'1' and (BeginMoney<>0 OR BeginCent<>0 OR qCczMoney <> 0))
	RETURN -2
	
--判断是否在取价规则中使用
IF EXISTS(SELECT top 1 1 FROM pricerule_detail_vipconfig where VipTypeID=@nid)
	RETURN -3
	
--判断是否在新的促销体系中使用
IF EXISTS(SELECT top 1 1 FROM PromoRule_Detail_VIPConfig where VipTypeID=@nid)
	RETURN -4

--删除会员短信发送对象关联关系
DELETE FROM SMSInfo_Template_CardType WHERE vipCardTypeID=@nid

--积分类型-积分转储值设置表
DELETE FROM nVipCardSet_IntegralExchange WHERE VipCardTypeID=@nid

DELETE FROM nVipCardSign WHERE VipCardTypeId = @nid
DELETE FROM nVipCardSet WHERE VipCardTypeId = @nid


RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：谢吉康
	日期：2009-06-04
	描述：删除VIP卡
*/
CREATE   PROCEDURE Gp_DelVipCardNo
(
	@nid		numeric(18,0)
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE vipcardid = @nid)
	RETURN -4
IF EXISTS(SELECT TOP 1 1 FROM PayBill WHERE VipCardID=@nid)
	RETURN -3
IF EXISTS(SELECT TOP 1 1 FROM PreBill WHERE VipCardID=@nid)
	RETURN -3
IF EXISTS(SELECT TOP 1 1 FROM OrderIndex WHERE VipCardID=@nid)
	RETURN -3	

IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE subname = 'inicanmodify' and subvalue = 'T')
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE IsCz = 1 AND qCczMoney<>0 AND VipCardId = @nid)
			RETURN -1
			
		IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE IsWashTimes = 1 AND CanWashTimes00<>0 AND VipCardId = @nid)
			RETURN -5
	END
ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE cZyeMoney<>0 AND VipCardId = @nid)
			RETURN -1
		
		--所有分支机构的余额为0才能删除
		IF EXISTS(SELECT TOP 1 1 FROM nVipCardSignStype WHERE cZyeMoney<>0 AND VipCardId = @nid)
			RETURN -1
			
		IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE CanWashTimes<>0 AND VipCardId = @nid)
			RETURN -5
	END

--所有分支机构的期初储值金额为0才能删除
IF EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSignStype WHERE qCczMoney<>0 AND VipCardId = @nid)
	RETURN -1
	
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE VipCardId = @nid)
	RETURN -3
	
IF EXISTS(SELECT TOP 1 1 FROM OrderIndex WHERE VipCardId = @nid)
	RETURN -3	

IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardId = @nid AND (beginmoney<>0 OR begincent<>0))
	RETURN -2

--删除数据
DELETE FROM nVipCardSign WHERE VipCardId = @nid
DELETE FROM dbo.nVipCardSignStype WHERE VipCardId = @nid

--删除明细(汽配版本添加)
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[QP_nVipCardSign_RemindEvent]') AND type in (N'U'))
BEGIN
	delete from QP_nVipCardSign_RemindEvent WHERE VipCardId = @nid
END
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[QP_nVipCardSign_RepairItems]') AND type in (N'U'))
BEGIN
	delete from QP_nVipCardSign_RepairItems WHERE VipCardId = @nid
END

DELETE FROM dbo.VipCard_ApplyPOS  WHERE VipCardId = @nid
DELETE FROM dbo.VipCard_ApplyStype  WHERE VipCardId = @nid

--刷新数据
EXEC Gp_nFreshVipCardNum

RETURN 0












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_DelWmsBaseSyncInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Gp_DelWmsBaseSyncInfo]
GO

/*
	作者：谢吉康
	日期：2018-10-17
	描述：删除选择的基本信息同步信息
*/
CREATE PROCEDURE Gp_DelWmsBaseSyncInfo
(
	@typeids				VARCHAR(MAX),			--基本信息ID
	@tablename				VARCHAR(100)			--基本信息类型
)
AS
SET NOCOUNT ON

IF @tablename = 'ptype'
BEGIN
	UPDATE 	dbo.ptype
	SET		iswmssync = 0
	WHERE	typeid IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
	
	DELETE  FROM WmsErpPtypeContrastSetting
	WHERE   ERP_TypeId IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
END
ELSE IF @tablename = 'btype'
BEGIN
	UPDATE 	dbo.btype
	SET		iswmssync = 0
	WHERE	typeid IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
	
	DELETE  FROM WmsErpBtypeContrastSetting
	WHERE   ERP_TypeId IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
END
ELSE IF @tablename = 'employee'
BEGIN
	UPDATE 	dbo.employee
	SET		iswmssync = 0
	WHERE	typeid IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
	
	DELETE  FROM WmsErpEmployeeContrastSetting
	WHERE   ERP_TypeId IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
END
ELSE IF @tablename = 'stock'
BEGIN
	UPDATE 	dbo.stock
	SET		iswmssync = 0
	WHERE	typeid IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
	
	DELETE  FROM WmsErpStockContrastSetting
	WHERE   ERP_TypeId IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
END
ELSE IF @tablename = 'ac_items'
BEGIN
	UPDATE 	dbo.ac_items
	SET		iswmssync = 0
	WHERE	typeid IN (SELECT A FROM DBO.F_Split(@typeids,',') WHERE ISNULL(A,'')<>'')
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Gp_DelWMSBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_DelWMSBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	删除本地网店信息
-- 时间：	2018-10-12
-- 作者：	GLJ
-- ========================================================================
CREATE PROCEDURE Gp_DelWMSBill
(
	@BillIds		VARCHAR(MAX)='',--单据ID	
	@BillType		INT--单据类型
)
--@encode$--
AS
SET NOCOUNT ON

--已经生成ERP单据
CREATE TABLE #ErpBill(BillNumberID NUMERIC(24,0))
INSERT INTO #ErpBill(BillNumberID)
SELECT DISTINCT r.WMS_BillNumberID
FROM WMS_ERPBillRelation R  
INNER JOIN f_split(@BillIds,';') F ON F.a=R.WMS_BillNumberID AND R.BillType=@BillType


--要删除的单据ID
CREATE TABLE #DelBill(BillNumberID NUMERIC(24,0))
INSERT INTO #DelBill(BillNumberID)
SELECT DISTINCT a FROM f_split(@BillIds,';') WHERE a NOT IN(SELECT BillNumberID FROM #ErpBill)

--删除主表
DELETE FROM WMSOrderIndex
WHERE BillNumberID IN(SELECT BillNumberID FROM #DelBill)
	
--删除没有生成ERP单据的网店草稿明细
IF(@BillType=11)--销售出库单
	BEGIN
	
		DELETE FROM WMSSaleBill WHERE BillNumberID IN(SELECT BillNumberID FROM #DelBill)

		SELECT '单据编号['+I.BillCode+'] 商品名称['+D.FullName +'];'+CHAR(13)
		FROM #ErpBill F
		INNER JOIN WMSSaleBill D ON F.BillNumberID=D.BillNumberID
		INNER JOIN WMSOrderIndex I ON I.BillNumberID=D.BillNumberID
		FOR XML PATH('')
	END
ELSE IF(@BillType=45)--销售退货单
	BEGIN
	
		DELETE FROM WMSSaleBackBill WHERE BillNumberID IN(SELECT BillNumberID FROM #DelBill)

		SELECT '单据编号['+I.BillCode+'] 商品名称['+D.FullName +'];'+CHAR(13)
		FROM #ErpBill F
		INNER JOIN WMSSaleBackBill D ON F.BillNumberID=D.BillNumberID
		INNER JOIN WMSOrderIndex I ON I.BillNumberID=D.BillNumberID
		FOR XML PATH('')

	END
ELSE IF(@BillType=36)--费用单
	BEGIN	
	
		DELETE FROM WMSExpenseBill WHERE BillNumberID IN(SELECT BillNumberID FROM #DelBill)

		SELECT '单据编号['+I.BillCode+'] 项目编号['+D.FullName +'];'+CHAR(13)
		FROM #ErpBill F
		INNER JOIN WMSExpenseBill D ON F.BillNumberID=D.BillNumberID
		INNER JOIN WMSOrderIndex I ON I.BillNumberID=D.BillNumberID
		FOR XML PATH('')

	END
ELSE IF(@BillType=4)--收款
	BEGIN
	
		DELETE FROM WMSGatherBill WHERE BillNumberID IN(SELECT BillNumberID FROM #DelBill)
		
		SELECT '单据编号['+I.BillCode+'] 项目编号['+D.FullName +'];'+CHAR(13)
		FROM #ErpBill F
		INNER JOIN WMSGatherBill D ON F.BillNumberID=D.BillNumberID
		INNER JOIN WMSOrderIndex I ON I.BillNumberID=D.BillNumberID
		FOR XML PATH('')
	END
	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DeparmentChange_CreateVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DeparmentChange_CreateVoucher
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：部门转移 单据凭证的生成规则和方式
-- 时间：2013-07-03
-- 作者：glj	
-- ========================================================================
CREATE PROC Gp_DeparmentChange_CreateVoucher
(
	@ID				INT,		--记录ID
	@BusinessDate	DATETIME,	--操作日期
	@TempletID		INT			--模板ID
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE 
	@Ret INT=0, --ret=0 成功  ret=-2 可在变更查询中生成凭证  ret=-1 让用户自行选择对应单据类型中的凭证模板
	@ReturnValue VARCHAR(1000)='',
	@VoucherId	INT

EXEC @Ret=Gp_CreateVoucher_Assets @ID,2,0,@BusinessDate,@ReturnValue output,@VoucherId OUTPUT
IF @Ret=-255
	BEGIN
		DELETE FROM Ac_Voucher WHERE BillNumberId=@VoucherId
		DELETE FROM Ac_Voucher_Bill WHERE BillNumberId=@VoucherId
	END

RETURN @Ret

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2005-1-20
	描述：处理分支机构预设售价
		  新增、修改
*/
CREATE PROCEDURE Gp_DepartmentPrePriceDeal
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(100),	--商品ID
	@DTypeId		varchar(100),	--分支机构ID
	@PrePrice1		 NUMERIC(24, 10) ,	--预设售价1
	@PrePrice2		 NUMERIC(24, 10) ,	--预设售价2
	@PrePrice3		 NUMERIC(24, 10) ,	--预设售价3
	@PrePrice4		 NUMERIC(24, 10) ,	--预设售价4
	@recPrice		 NUMERIC(24, 10) ,	--预设进价
	@Explain		varchar(300)	--备注
)
--@encode$--
AS
DECLARE @DuserCode	varchar(256),	--分支机构编号
		@DfullName	varchar(256),	--分支机构名称
		@PuserCode	varchar(256),	--商品编号
		@PfullName	varchar(256),	--商品名称
		@PEntryCode	varchar(256),	--商品条形码
		@PStandard	varchar(256),	--商品规格
		@PType		varchar(256)	--商品型号


IF NOT EXISTS(SELECT TOP 1 * FROM PType WHERE TypeId = @PTypeId AND Deleted = 0 AND SonNum = 0)
	BEGIN
		--RAISERROR('商品名称无效！',16,1)
		RETURN -1
	END
ELSE
	BEGIN
		SELECT @PuserCode = UserCode,@PfullName = FullName,@PEntryCode = EntryCode,@PStandard = Standard,@PType = Type FROM PType WHERE TypeId = @PTypeId AND Deleted = 0 AND SonNum = 0
	END

IF NOT EXISTS(SELECT TOP 1 * FROM Department WHERE TypeId = @DTypeId AND Deleted = 0 AND SonNum = 0)
	BEGIN
		--RAISERROR('分支机构名称无效！',16,1)
		RETURN -2
	END
ELSE
	BEGIN
		SELECT @DuserCode = UserCode,@DfullName = FullName FROM Department WHERE TypeId = @DTypeId AND Deleted = 0 AND SonNum = 0
	END


IF NOT EXISTS(SELECT TOP 1 * FROM BatchPrice WHERE PTypeId = @PTypeId AND DepartId = @DTypeId)	--写入新记录
	BEGIN
		INSERT INTO BatchPrice
		(
			DepartId,
			DepartUserCode,
			DepartFullName,
			PTypeId,
			PUserCode,
			PFullName,
			PEntryCode,
			PStandard,
			PType,
			PrePrice1,
			PrePrice2,
			PrePrice3,
			PrePrice4,
			recPrice,
			Explain
		)VALUES(
			@DTypeId,
			@DuserCode,
			@DfullName,
			@PTypeId,
			@PUserCode,
			@PFullName,
			@PEntryCode,
			@PStandard,
			@PType,
			@PrePrice1,
			@PrePrice2,
			@PrePrice3,
			@PrePrice4,
			@recPrice,
			@Explain
		)

		IF @@ROWCOUNT = 0
			BEGIN
				--RAISERROR('录入记录失败！',16,1)
				RETURN -3
			END
		ELSE
			BEGIN
				--RAISERROR('录入记录成功！',16,1)
				RETURN 0
			END
	END
ELSE	--修改旧记录
	BEGIN
		UPDATE	BatchPrice
		SET		PrePrice1 = @PrePrice1,
				PrePrice2 = @PrePrice2,
				PrePrice3 = @PrePrice3,
				PrePrice4 = @PrePrice4,
				recPrice  = @recPrice,
				Explain   = @Explain
		WHERE	DepartId  = @DTypeId
				AND PTypeId	  = @PTypeId	

		IF @@ROWCOUNT = 0
			BEGIN
				--RAISERROR('修改记录失败！',16,1)
				RETURN -3
			END
		ELSE
			BEGIN
				--RAISERROR('修改记录成功！',16,1)
				RETURN 0
			END
	END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	资金调拨单保存或过账检查，判断资金调拨单调出分支机构是否满足条件
	作    者：	冯波
	修改时间：	2014-08-21
*/
CREATE             PROCEDURE Gp_DepBill_Check
(
	@nBillID				NUMERIC(10,0)					-- 单据 ID 号
	
)
--@encode$--
AS
	DECLARE
		@nRet	INT
		
	SELECT
		@nRet=0
		
	IF EXISTS(
			SELECT a.Id FROM Te_Period a
			INNER JOIN Ac_Period b
			ON a.FYear=b.FYear
			AND a.FPeriod=b.FPeriod
			WHERE a.STypeId=(SELECT VerifyID  FROM dbo.BillIndex b INNER JOIN dbo.SType s ON b.Stypeid=s.TypeId WHERE BillNumberId=@nbillid)
			)
	BEGIN
		IF NOT EXISTS(
			SELECT c.BillNumberId 
			FROM BillIndex c
			WHERE c.BillNumberId=@nbillid
			AND EXISTS(
					SELECT a.Id 
					FROM Te_Period a
					INNER JOIN Ac_Period b
					ON a.FYear=b.FYear
					AND a.FPeriod=b.FPeriod
					WHERE a.STypeId=(SELECT VerifyID  FROM dbo.BillIndex b INNER JOIN dbo.SType s ON b.Stypeid=s.TypeId WHERE BillNumberId=@nbillid)
					AND c.BillDate BETWEEN b.FBegin AND b.FEnd
				) 
		)
		BEGIN
			--SET @ErrMsg='出纳系统已月结，不能过账！'
			RETURN  303 
		END
	END
	ELSE
	BEGIN
		--SET @ErrMsg='出纳系统还未初始化，不能过账！'
		RETURN 304
	END
	
	RETURN @nRet
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*




*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/06/17
	Description	:	改变折旧方式
*/
CREATE PROCEDURE GP_DepreciationChange
(
	@CardID			INT,					--卡片ID
	@NetSalvage		 NUMERIC(24, 10) ,
	@NetSalvageRate	 NUMERIC(24, 10) ,
	@DepreciationMean INT,
	@DurYear		INT,
	@durmonth		INT,
	@ExpectWork		VARCHAR(50),
	@FinishWork		VARCHAR(50),
	@WorkUnit		VARCHAR(50),
	@Businessdate	DATE,                  --业务日期
	@UserID			VARCHAR(50),			--操作员
    @ReturnValue	VARCHAR(MAX) out		--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Re			INT=0
DECLARE @newID			INT
SET @ReturnValue='保存成功'     
DECLARE @date DATE=GETDATE()
DECLARE @Stypeid VARCHAR(50)

IF @ExpectWork = ''
BEGIN
	SET @ExpectWork = NULL
	SET @FinishWork = NULL
	SET @WorkUnit = NULL
END

SELECT @Stypeid=aac.StypeId 
FROM  dbo.AC_AssetsCards ac 
JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id 
WHERE ac.Id=@CardID


--删除变更单记录，这个必须最先执行
DELETE Ac_DepreciationAlteration WHERE CardId=@CardID AND BusinessDate>=@businessdate
DELETE dbo.Ac_AssetsCards_History WHERE AssertsCardId=@CardID AND BillType=-3 AND  BusinessDate>=@businessdate

---先插入数据
INSERT INTO Ac_DepreciationAlteration(CardId,OldNetSalvage,NetSalvage,OldNetSalvageRate,NetSalvageRate,OldDepreciationMean,
									  DepreciationMean,OldDurYear,DurYear,durmonth,OperationDate,ETypeId,Businessdate,OldExpectWork,ExpectWork,OldFinishWork,FinishWork,OldWorkUnit,WorkUnit)
SELECT  @CardID,dbo.F_RoundTotal(NetSalvage),dbo.F_RoundTotal(@NetSalvage),NetSalvageRate,@NetSalvageRate,DepreciationMean,@DepreciationMean,DurYear,@DurYear,@durmonth,@date,@UserID,@Businessdate,@ExpectWork,ExpectWork,@FinishWork,FinishWork,@WorkUnit,WorkUnit
FROM Ac_AssetsCards WHERE Id=@CardID
SELECT @newID=SCOPE_IDENTITY(); 
IF @@ERROR <> 0
	BEGIN						
		SET @Re=-2      
		SET @ReturnValue='保存失败'                                                                 
		RETURN @Re	
	END		 

---再更新卡片资料
DECLARE @maxXiwa INT
SELECT @maxXiwa=MAX(XiWaMaxNumber)+1 FROM dbo.Ac_AssetsCards 

UPDATE dbo.Ac_AssetsCards SET NetSalvage=@NetSalvage,NetSalvageRate=@NetSalvageRate, DepreciationMean=@DepreciationMean,DurYear=@DurYear,durmonth=@durmonth,ExpectWork=@ExpectWork,FinishWork=@FinishWork,WorkUnit=@WorkUnit ,XiWaMaxNumber=@maxXiwa WHere ID= @CardID
IF @@ERROR <> 0
	BEGIN						
		SET @Re=-2     
		SET @ReturnValue='保存失败'                                                                       
		RETURN @Re	
	END	

---保存历史记录
DECLARE @tempRe VARCHAR(max)
EXEC Gp_SaveAssetsCardHistory @Stypeid,@CardID,@UserID,@Businessdate,-3,@newID,0,@tempRe OUT

---重新生成折旧单
--该卡片本期是否折旧
DECLARE @Fyear INT,@Fperiod INT  --业务日期肯定是落到该期间的
SELECT @Fyear=FYear,@Fperiod=FPeriod FROM dbo.Ac_Period WHERE FBegin<=@Businessdate AND FEnd>=@Businessdate
IF @Fperiod=13 
	SET @Fperiod=12
IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND PlanState=1 AND FYear=@Fyear AND FPeriod=@Fperiod)
	EXEC @Re=Gp_ReCreateDepreciationPlan @CardID,0
ELSE 
	EXEC @Re=Gp_ReCreateDepreciationPlan @CardID,1

RETURN @Re

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.05.29
	描述：业务单据反过账时，凭证删除
*/
CREATE PROCEDURE Gp_DestroyVoucher
(
	@BillNumberId	INT,					--单据ID
	@szPID			VARCHAR(1000) OUTPUT,	-- 返回出错信息
	@IsCommission	INT = 0					-- 1.是提成单
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPID = ''

--凭证ID
DECLARE @VoucherId INT
SET @VoucherId = 0

IF @IsCommission = 0
	SELECT @VoucherId = VourchBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId = @BillNumberId
ELSE
	SELECT @VoucherId = VourchBillId FROM dbo.Ac_CommissionBill_VoucherBill WHERE GoodsBillId = @BillNumberId

--有凭证才处理
IF ISNULL(@VoucherId,0)<>0
BEGIN
	--已过账，无法删除
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId AND IfCheck = 't')
	BEGIN
		SET @szPID = '单据生成凭证已记账，请先对凭证反记账'
		RETURN -1
	END
	
	--已出纳签字，无法删除
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId AND ISNULL(Teller,'') <> '')
	BEGIN
		SET @szPID = '单据生成凭证已出纳签字，请先对凭证取消签字'
		RETURN -2
	END
	--已复核
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId AND ISNULL(ReCheckId,'') <> '')
	BEGIN
		SET @szPID = '单据生成凭证已复核，请先对凭证反复核'
		RETURN -3
	END
	--已审核
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId AND ISNULL(AuditId,'') <> '')
	BEGIN
		SET @szPID = '单据生成凭证已审核，请先对凭证反审核'
		RETURN -4
	END
		
	--删除相应凭证数据
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId = @BillNumberId
	
	RETURN 0
END

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET	QUOTED_IDENTIFIER OFF 
GO
SET	ANSI_NULLS ON 
GO


/*

作者：冯波

采购换货单的处理
*/
CREATE   PROCEDURE Gp_DiffExchange_Else 
(		
	@intBillType				INT,
	@strATypeID					VARCHAR(50),
	@strSTypeID					VARCHAR(50)
)

--@encode$--
AS

--要改ListTable,AType_Total,AType

--填入原值，现值  #ListTable



--定义一堆常量
DECLARE	
		@GOODS_ID				varchar(50),
		@strInnerAR				VARCHAR(50),				--内部应收
		@sysID					INT,
		@GRIRID					INT,
		@WTDXSP_ID				INT
	
	

SELECT @WTDXSP_ID = NID FROM Ac_Items WHERE UserCode='1261'

SELECT @sysID = CID FROM Ac_Currency WHERE Sysrow = 1

		

SELECT @GOODS_ID=NID FROM Ac_Items WHERE UserCode='1241'
SELECT @strInnerAR=NID FROM Ac_Items WHERE UserCode='1132'  --『内部应收』,0000100010

SELECT @GRIRID=NID FROM dbo.Ac_Items WHERE UserCode='2122'



IF @intBillType IN (6,161,146,16,21)
BEGIN
	INSERT #ListTable(BillNumberID,OldValue,NewValue,STypeID,BillType,BTypeID,CID)
	SELECT a.BillNumberID,ISNULL(SUM(CASE b.AtypeId WHEN @strATypeID THEN b.Total ELSE 0 END),0),
	ISNULL(SUM(CASE b.AtypeId WHEN @strATypeID THEN 0 
		ELSE CASE WHEN  C.TypeName IN ('B','F','C','E') THEN b.Total ELSE -b.Total END  END),0),
		@strSTypeID,@intBillType,b.BtypeId,1 CID
	FROM 
	(
		SELECT DISTINCT BillNumberId
		FROM #AfterModifyBill 
		WHERE BillType=@intBillType
	) a
	LEFT JOIN ListTable b ON a.BillNumberID=b.BillNumberId
	LEFT JOIN Ac_Items C ON B.AtypeId = C.nId
	WHERE b.BillType=@intBillType 
	GROUP BY a.BillNumberID,b.BtypeId
END
ELSE IF @intBillType IN (57,126,14)
BEGIN
	--其他单据
	
	
	
	INSERT #ListTable(BillNumberID,OldValue,NewValue,STypeID,BillType,BTypeID,CID)
	SELECT a.BillNumberID,ISNULL(SUM(CASE b.AtypeId WHEN @strATypeID THEN b.Total ELSE 0 END),0),
	ISNULL(SUM(CASE b.AtypeId WHEN @GOODS_ID THEN b.Total WHEN  @GRIRID THEN -b.Total ELSE 0 END),0),
	@strSTypeID,@intBillType,b.BtypeId,b.CID
	FROM 
	(
		SELECT DISTINCT BillNumberId
		FROM #AfterModifyBill 
		WHERE BillType=@intBillType
	) a
	LEFT JOIN ListTable b
	ON a.BillNumberID=b.BillNumberId
	WHERE b.BillType=@intBillType 
	GROUP BY a.BillNumberID,b.BtypeId,b.CID
END
ELSE IF @intBillType=187
BEGIN

	INSERT #ListTable(BillNumberID,ATypeID,OldValue,NewValue,STypeID,BillType,BTypeID,CID)
	SELECT a.BillNumberID,CASE a.CostSale WHEN 0 THEN @strATypeID ELSE @strInnerAR END,
	ISNULL(SUM(CASE b.AtypeId WHEN @strATypeID THEN b.Total ELSE 0 END),0),
	ISNULL(SUM(CASE b.AtypeId WHEN @strATypeID THEN 0 ELSE CASE WHEN   C.TypeName IN ('B','F','C','E') THEN b.Total ELSE -b.Total END  END),0),
	@strSTypeID,@intBillType,'',b.CID
	FROM 
	(
		SELECT DISTINCT a.BillNumberId,b.CostSale
		FROM #AfterModifyBill a
		INNER JOIN BillIndex b
		ON a.BillNumberID=b.BillNumberId
		WHERE b.BillType=@intBillType
	) a
	LEFT JOIN ListTable b ON a.BillNumberID=b.BillNumberId
	LEFT JOIN Ac_Items C ON B.AtypeId = C.nId
	WHERE b.BillType=@intBillType 
	GROUP BY a.BillNumberID,a.CostSale,b.CID
END
ELSE IF @intBillType=141
	INSERT #ListTable(BillNumberID,OldValue,NewValue,STypeID,BillType,BTypeID,CID)
	SELECT a.BillNumberID,ISNULL(SUM(CASE b.AtypeId WHEN @strATypeID THEN b.Total ELSE 0 END),0),
	ISNULL(SUM(CASE b.AtypeId WHEN @WTDXSP_ID THEN -b.Total ELSE 0 END),0),
	@strSTypeID,@intBillType,b.BtypeId,b.CID
	FROM 
	(
		SELECT DISTINCT BillNumberId
		FROM #AfterModifyBill 
		WHERE BillType=@intBillType
	) a
	LEFT JOIN ListTable b
	ON a.BillNumberID=b.BillNumberId
	WHERE b.BillType=@intBillType 
	GROUP BY a.BillNumberID,b.BtypeId,b.CID
ELSE
BEGIN
	--其他单据
	INSERT #ListTable(BillNumberID,OldValue,NewValue,STypeID,BillType,BTypeID,CID)
	SELECT a.BillNumberID,ISNULL(SUM(CASE b.AtypeId WHEN @strATypeID THEN b.Total ELSE 0 END),0),
	ISNULL(SUM(CASE b.AtypeId WHEN @GOODS_ID THEN -b.Total ELSE 0 END),0),
	@strSTypeID,@intBillType,b.BtypeId,b.CID
	FROM 
	(
		SELECT DISTINCT BillNumberId
		FROM #AfterModifyBill 
		WHERE BillType=@intBillType
	) a
	LEFT JOIN ListTable b
	ON a.BillNumberID=b.BillNumberId
	WHERE b.BillType=@intBillType AND b.CID=1
	GROUP BY a.BillNumberID,b.BtypeId,b.CID
END

UPDATE ListTable SET btypeid='' WHERE (btypeid='0'OR btypeid IS NULL)

--如果之前不存在此科目，则添加
	IF EXISTS(
		SELECT a.BillNumberID
		FROM #ListTable a
		WHERE a.NewValue<>0
		AND Not EXISTS(
			SELECT b.BillNumberID
			FROM ListTable b
			WHERE b.BillNumberId=a.BillNumberID
			AND a.BillType=b.BillType
			AND b.AtypeId=@strATypeID
			AND b.BillType=@intBillType
			AND B.CID=@sysID
		)
	)
	BEGIN
		
	
		INSERT ListTable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,
		Total,CostTotal,Audited,Ifout,DTypeID,STypeID,CID,Ntotal,Rate)
		SELECT DISTINCT a.BillNumberId,a.BillDate,a.BillType,@strATypeID,
		CASE a.BtypeId WHEN '' THEN '' ELSE a.BtypeId END,a.EtypeId,
		b.NewValue,0,a.Audited,0,a.DTypeID,a.STypeID,@sysID,b.NewValue,1
		FROM ListTable a
		INNER JOIN #ListTable b
		ON a.BillNumberId=b.BillNumberID
		AND a.BillType=b.BillType
		WHERE a.BillType=@intBillType
		AND Not EXISTS(
			SELECT b.BillNumberID
			FROM ListTable b
			WHERE b.BillNumberId=a.BillNumberID
			AND b.AtypeId=@strATypeID
			AND b.BillType=@intBillType
		)
		GROUP BY a.BillNumberId,a.BillDate,a.BillType,
		CASE a.BtypeId WHEN '' THEN '' ELSE a.BtypeId END,a.EtypeId,
		a.DTypeID,a.STypeID,b.NewValue,a.Audited
	END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF exists (SELECT * from dbo.sysobjects where id = object_id(N'[dbo].[GP_DirectDeleteBaseInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_DirectDeleteBaseInfo
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*------------------------------------------
 作者：蒋奎
 日期：2015-4-16
 描述：直接删除基本信息(不判断有木有使用)(除了自定义和辅助核算外)
-------------------------------------------*/
 
CREATE    PROCEDURE [dbo].GP_DirectDeleteBaseInfo
( @TypeId VARCHAR(50),	--基本信息表的关键字段
  @DbName VARCHAR(50),	--基本信息关键字
  @delType INT=0	--1代表启用，0代表停用，-1代表删除
)
--@encode$--
AS
SET NOCOUNT ON
--DECLARE @sql VARCHAR (500)
DECLARE @GOODS_ID VARCHAR(50)
DECLARE @dTempQty  NUMERIC(24, 10) 
DECLARE @dTempTotal  NUMERIC(24, 10) 
DECLARE @sonnum NUMERIC (10)
DECLARE @parid VARCHAR(50)
DECLARE @deleted INT	--是否停用标志(1代表停用，0代表不停用)
DECLARE	@result		INT=0		--自定义接收返回值
DECLARE	@result1	INT=0		--自定义接收返回值
SELECT @GOODS_ID='0000100001'
DECLARE @ifqp VARCHAR(1)	--判断是否为汽配(1代表汽配,0代表其它)
DECLARE @XiWaMaxNumber  NUMERIC(24, 10) 
SET @ifqp=(SELECT subvalue from sysdata where subname='ifqp')
DECLARE @delTypeName VARCHAR(10)	--@delTypeName和@delType分别一一对应

IF @deltype=-1
	SET @delTypeName='删除'


------------全局判断"自定义"是否关联基本信息，如果关联基本信息里相关项不能被删除------------
DECLARE @temptypename	VARCHAR(20)
	SET @temptypename=''
IF @deltype=-1
BEGIN
	IF @DbName='ptype'
		SET @temptypename='Ptype'
	IF @DbName='btype'
		SET @temptypename='Btype'
	IF @DbName='stock'
		SET @temptypename='stock'
	IF @DbName='DepartMent'
		SET @temptypename='DepartMent'
	IF @DbName='AreaType'
		SET @temptypename='Areatype'
	IF @DbName='SType'
		SET @temptypename='Stype'
	IF @DbName='employee'
		SET @temptypename='employee'
		
	exec @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@TypeId,@result=0
	IF @result=1
	BEGIN
		RAISERROR('当前信息已在自定义中关联,不可以''删除''',16,1) return
	END

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

--------------------------------------判断基本信息被辅助核算，凭证录入使用后不能删除---开始---------------------
DECLARE @typename VARCHAR(100)
IF @deltype=-1
BEGIN
	
	IF @DbName='btype'
		SET @typename='BTYPE'
	IF @DbName='DepartMent'
		SET @typename='DEPARTMENT'
	IF @DbName='SType'
		SET @typename='STYPE'
	IF @DbName='employee'
		SET @typename='EMPLOYEE'
		
		EXEC	@result1=dbo.Gp_DeleteInsert_Ac_Data @Type=@typename,@typeid=@TypeId
		IF @result1=1
		BEGIN
				RAISERROR('当前信息已在辅助核算中关联,不可以''删除''',16,1) return
		END
END
--------------------------------------判断基本信息被辅助核算，凭证录入使用后不能删除---结束---------------------
	
		
--商品删除和更新
IF @dbname='ptype'
	BEGIN
		IF @delType=-1
			BEGIN
				IF exists (SELECT * from PType_Units_Ext where PtypeID=@typeid)
					BEGIN
						delete from PType_Units_Ext where ptypeid=@typeid
					END
				-- 删除nVipGoodsSign中对应商品的信息
				DELETE FROM nVipGoodsSign WHERE ptypeid=@typeid 	
				--停用，删除商品相应的多编码删除
				DELETE PuserCode WHERE PtypeId = @typeid
				DELETE productpic WHERE ptypeid=@TypeId
				--删除自定义中关联信息
				DELETE FROM Ptype_CustomColumns WHERE typeid=@typeid
				--删除商品的辅助销售单位
				DELETE FROM PType_AuxiliaryUnits_Ext WHERE PtypeID=@typeid
				--删除价格跟踪表的信息
				DELETE FROM dbo.PriceTrack WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_AskPrice  WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Buy WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_BuyOrder WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Quote WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_Sale WHERE PtypeID=@typeid
				DELETE FROM dbo.PriceTrack_SaleOrder WHERE PtypeID=@typeid

				SELECT @deleted=deleted FROM ptype WHERE typeid=@typeid
				--更新POS下载信息
				DECLARE @PID VARCHAR(100)

				IF @deleted=1	
					BEGIN

						--更新POS下载信息

						SELECT @PID=Pid FROM PType WHERE typeId=@TypeId
						EXEC Gp_DataSaveForPosDown '-99999','Ptype',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_Price',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_STypePrice',@PID
						
						EXEC Gp_DataSaveForPosDown '-99999','PosIsUpdateData_P',@PID
						select @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
						update PType_Price set XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@PID

						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM PType

		 				DELETE ptype WHERE typeid=@typeid 
		 															
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE PType
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM PType)
						
						
						IF len(@typeid)>5
							BEGIN
								UPDATE Ptype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
								UPDATE Ptype SET sonNum=0 WHERE typeid=LEFT(@typeid,len(@typeid)-5) AND sonNum<0				
							END
						IF len(@typeid)=5
							BEGIN
								UPDATE ptype SET sonNum=sonNum-1 WHERE typeid='00000'
								UPDATE ptype SET sonNum=0 WHERE typeid='00000' AND sonNum<0			
							END
						EXEC GP_DeleteBaseL 'P',@typeid --删除相关多级权限范围记录	
						--删除价格信息
						DELETE dbo.PType_Price WHERE PTypeID=@typeid
						--删除图片
						DELETE dbo.PType_Picture WHERE PTypeID=@typeid
						--删除汽配商品扩展信息
						DELETE QP_PType_Ext WHERE PTypeID=@TypeId
											
						---删除所有的子节点时，更新ptype_price的XiWaMaxNumber，以便pos下载
						IF EXISTS(SELECT *FROM PType WHERE typeId=@parid AND sonnum=0)
						BEGIN
							select @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
							update PType_Price set XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@parid
						END
						
		 				RETURN 0
					END
				IF @deleted=0
					BEGIN
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM PType
						--更新POS下载信息
						SELECT @PID=Pid FROM PType WHERE typeId=@TypeId
						
						EXEC Gp_DataSaveForPosDown '-99999','Ptype',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_Price',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext',@PID
						EXEC Gp_DataSaveForPosDown '-99999','PType_STypePrice',@PID						
						EXEC Gp_DataSaveForPosDown '-99999','PosIsUpdateData_P',@PID
						
						DELETE ptype WHERE typeid=@typeid
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE PType
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM PType)
						
						--delete  from ptype_l where typeid=@typeid
						IF len(@typeid)>5
							BEGIN
								UPDATE Ptype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
								UPDATE Ptype SET sonNum=0 WHERE typeid=LEFT(@typeid,len(@typeid)-5) AND sonNum<0				
							END
						--更新父节点中的xiwamaxnumber
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM PType
						UPDATE ptype SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeid=LEFT(@typeid,len(@typeid)-5)
							
						IF len(@typeid)=5
							BEGIN
								UPDATE ptype SET sonNum=sonNum-1 WHERE typeid='00000'
								UPDATE ptype SET sonNum=0 WHERE typeid='00000' AND sonNum<0			
							END
						EXEC GP_DeleteBaseL 'P',@typeid --删除相关多级权限范围记录
						
						--删除价格信息
						DELETE dbo.PType_Price WHERE PTypeID=@typeid
						--删除图片
						DELETE dbo.PType_Picture WHERE PTypeID=@typeid
						--删除汽配商品扩展信息
						DELETE QP_PType_Ext WHERE PTypeID=@TypeId
						--设置POS产品删除标志
						EXEC Pos_A8_UpDateSystemRebuildGuid
						
						---删除所有的子节点时，更新ptype_price的XiWaMaxNumber，以便pos下载
						IF EXISTS(SELECT *FROM PType WHERE typeId=@parid AND sonnum=0)
						BEGIN
							SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
							update PType_Price SET XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@parid
						END
						
						RETURN 0
					END 	
			END 
					
 		GOTO SUCCESS

		SUCCESS:
	 		SELECT @parid=parid FROM ptype WHERE typeid = @typeid 
	 		SELECT @sonnum=sonnum FROM ptype WHERE typeid=@parid
	 		SELECT @sonnum=@sonnum-1
	 		IF(@sonnum<0) SET @sonnum=0
	 		UPDATE ptype SET sonnum= @sonnum WHERE typeid =@parid 
	 		RETURN 0
		
	END
	
--往来单位(客户和供货商)删除和更新
IF @dbname= 'btype' 
	BEGIN
		 
		IF @delType=-1
			BEGIN
				IF EXISTS(select btypeid from btype_credit where BtypeId=@TypeId)
					BEGIN
						Delete FROM btype_credit WHERE BtypeId=@TypeId
					END
					
				--删除往来单位对应的商品多编码
				DELETE PuserCode WHERE btypeId = @typeid
	
				SELECT @deleted=deleted FROM btype WHERE typeid=@typeid
				IF @deleted=0
					BEGIN
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM btype	
					
						DELETE btype WHERE typeid=@typeid AND artotal=0 AND aptotal=0 
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE btype
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM btype)
						 
						DELETE Btype_CustomColumns WHERE typeid=@typeid
						--delete  from btype_l where typeid=@typeid
						IF len(@typeid)>5
							BEGIN
								UPDATE btype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
							END
						IF len(@typeid)=5
							UPDATE btype SET sonNum=sonNum-1 WHERE typeid='00000'
							EXEC GP_DeleteBaseL 'B',@typeid --删除相关多级权限范围记录
							RETURN 0
					END
				IF @deleted=1
					BEGIN
						
						SELECT @XiWaMaxNumber=MAX(xiwamaxnumber) FROM btype	
					
						DELETE btype WHERE typeid=@typeid AND artotal=0 AND aptotal=0 AND deleted=1
						
						--将当前XiWaMaxNumber最大值更新为删除前XiWaMaxNumber最大值
						UPDATE btype
						SET xiwamaxnumber=@XiWaMaxNumber 
						WHERE XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber) FROM btype)
						
						DELETE Btype_CustomColumns WHERE typeid=@typeid
						IF len(@typeid)>5
							BEGIN
								UPDATE btype SET sonNum=sonNum-1 WHERE typeid=LEFT(@typeid,len(@typeid)-5)
							END
						IF len(@typeid)=5
							BEGIN
								UPDATE btype SET sonNum=sonNum-1 WHERE typeid='00000'	
							END
						--delete  from btype_l where typeid=@typeid
						EXEC GP_DeleteBaseL 'B',@typeid --删除相关多级权限范围记录
						RETURN 0
					END
			END
		IF @@rowcount = 0  
			BEGIN
				RAISERROR('%s该记录失败',16,1)RETURN--RETURN -2 
			END
	END
	
IF @delType =-1
BEGIN
	DECLARE @sqls VARCHAR(5000)=''
	SET @sqls = 'EXEC Gp_ReplaceSchemeDetailValue '''+@TypeID+''','' AND BaseType LIKE ''''%'+@dbname+'%'''''''
	EXEC (@sqls)
END

GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

功能：		反过账
作者：		冯波
时间：		2016-05-17


*/


CREATE  PROCEDURE GP_Dis_Auditing 
(
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@EtypeID        	varchar(50) = '00001',	-- 2. 红冲单据的操作员ID
	@IsRepairBill		INT=0,
	@strPTypeIDOutPut	varchar(500) OUTPUT,	-- 3. 返回出错商品 ID 值
	@billType			INT =0
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN TRAN
--------------定义变量---------------
DECLARE @Sql				varchar(256)
DECLARE @SqlItem			varchar(256)
DECLARE @szDate				varchar(12)
DECLARE @dbName				varchar(30)
DECLARE @nNewBillID			numeric(10,0)
DECLARE @tBillDate				datetime		--单据日期
DECLARE @nRet					int				--返回值
DECLARE	@nBillType				int				--单据类型
DECLARE	@bRedWord				char(1)			--红冲标志
DECLARE @szIfCheck				char(1)			--是否过账
DECLARE @szPeriod1				datetime		--本期时间
DECLARE @cwcheck				INT
DECLARE @strInfoOUT				VARCHAR(1000),
		@chvBTypeID				VARCHAR(50),
		@chvDealBTypeID			VARCHAR(50),
		@chvSTypeID				VARCHAR(50),
		@FrozeDate				DATETIME,
		@AssetBusinessTypeId	INT,
		@VerifyID				VARCHAR(50),
		@chargeOffValue			numeric(24,10)


----------------先将红冲标志置为1--------------------------------------
IF @billType IN (71,72,87,88)
BEGIN
	UPDATE dbo.LendIndex SET ifcheck='f' WHERE BillNumberId=@nBillID AND ifcheck='t' AND RedWord=0
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN
		RETURN -100 --已红冲或未过账
	END
	
	
END
ELSE IF @BillType IN (404,405)
BEGIN
	UPDATE ReceiptBillIndex SET ifcheck='f' WHERE BillNumberId=@nBillID AND ifcheck='t' AND RedWord=0
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN
		RETURN -100 --已红冲或未过账
	END
	SELECT  @nBillType = BillType,
			@tBillDate=BillDate,
			@bRedWord=redword,
			@szIfCheck=ifcheck,
			@cwcheck=0,
			@chvBTypeID=btypeid,
			@chvDealBTypeID=DealBTypeID,
			@chvSTypeID=stypeid,
			@VerifyID=stypeid,
			@AssetBusinessTypeId=0,
			@chargeOffValue=ChargeOffTotal
	FROM	ReceiptBillIndex 
	WHERE	BillNumberId=@nBillID
	IF @chargeOffValue <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -600 --已核销
	END
END
ELSE
BEGIN

	UPDATE BillIndex SET ifcheck='f' WHERE BillNumberId=@nBillID AND ifcheck='t' AND RedWord=0
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN
		RETURN -100 --已红冲或未过账
	END
	SELECT  @nBillType = BillType,
			@tBillDate=BillDate,
			@bRedWord=redword,
			@szIfCheck=ifcheck,
			@cwcheck=CWCheck,
			@chvBTypeID=btypeid,
			@chvDealBTypeID=DealBTypeID,
			@chvSTypeID=stypeid,
			@VerifyID=stypeid,
			@AssetBusinessTypeId=AssetBusinessTypeId,
			@chargeOffValue=ChargeOffTotal
	FROM	BillIndex 
	WHERE	BillNumberId=@nBillID
	IF @chargeOffValue<>0
	BEGIN
		ROLLBACK TRAN
		RETURN -600 --已核销
	END
END

IF @nBillType IN (115,116,128,129)
BEGIN
	IF EXISTS(SELECT 1 FROM AdDebtBill WHERE BillNumberId=@nBillID AND ChargeOffTotal>0)
	BEGIN
		ROLLBACK TRAN
		RETURN -600 --已核销
	END
END

--写反过账的日志，这个很重要

--如果存在审核历程的，这个表保留，但是要区分一下这个是老的审核历史


IF EXISTS(
		SELECT TypeID
		FROM SType
		WHERE TypeId=@chvSTypeID AND IsSelfVerify=0
	)
BEGIN
	SELECT @VerifyID=VerifyID
	FROM SType
	WHERE TypeId=@chvSTypeID
END	
	
--------------------得到本期开始时间 start---------------
IF @nBillType=310
BEGIN
	--资金调拨单
	SELECT @szPeriod1=b.FBegin
	FROM Te_Period a
	INNER JOIN Ac_Period b
	ON a.FPeriod=b.FPeriod
	WHERE a.STypeId=@VerifyID
	AND a.FYear=YEAR(@tBillDate)
END
ELSE
BEGIN
	SELECT	@szPeriod1 = StartDate
	FROM	MonthProc
	WHERE	MonthNo = '本期'	
END	
--------------------得到本期开始时间 end---------------

------------------------------------------开始判断-------------------------------------------
IF @nBillType<>310
BEGIN
	IF GETDATE() < @szPeriod1 
	BEGIN
		ROLLBACK TRAN
		RETURN -8
	END
END



IF @tBillDate < @szPeriod1
BEGIN
	ROLLBACK TRAN
	RETURN -2 --不能红冲月结前单据
END
--------------------判断冻结时间 start---------------
IF @nBillType<>310
BEGIN
	SET @FrozeDate=@tBillDate
	SELECT	@FrozeDate =FrozeDate  FROM FrozeBusiness WHERE stypeid=@chvSTypeID

	IF @tBillDate<@FrozeDate
	BEGIN
		ROLLBACK TRAN
		RETURN -705	
	END
END	
--------------------判断冻结时间 end---------------

IF @szIfCheck = 'f' 
BEGIN
	ROLLBACK TRAN
	RETURN -100 --已红冲或未过账
END
IF @cwcheck = 1 
BEGIN
	ROLLBACK TRAN
	RETURN -9 --已被财务审核
END
--红冲前检查关联关系
EXEC @nRet = Gp_RedWordValidate @nbillid,@nbilltype,@szPeriod1
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	RETURN @nRet
END
--select 1,@nRet

-------------------------------------------判断结束-------------------------------------------------------



/*-------------------------------------红冲序列号 start----------------------------------------------------*/
--零售单、销售出库单、销售退货单、委托发货、委托结算、委托退货、采购入库、采购退货、
--受托收货、受托结算、受托退货、同价调拨、变价调拨、报损单、报溢单、拆装单、换货单、维修受理单、赠送单、获赠单、
--销售换货单、采购换货单、维修接件单、维修单、维修取件单、整机更换单、送修单、送修返回单、上门维修单、维修品调入单、维修品调出单、维修品调拨单
--积分兑换单、分支机构调拨出库单、分支机构调拨入库单,其他入库单，其他出库单,零售退货单
IF @nBillType IN (305,11,6,140,141,142,34,45,144,145,146,17,21,9,14,16,155,157,139,126,160,161,165,166,167,168,169,170,172,173,174,175,183,187,188,201,202,215,57,400,401,402,403)
BEGIN
	EXEC @nRet = GP_SerialRedWord @nBillID,@nBillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN @nRet
	END
END
ELSE IF @nBillType IN (71,72,87,88)
BEGIN
	EXEC @nRet = Gp_SerialRedWordForLend @nBillID,@nBillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN @nRet
	END
END
--借欠转采购or销售序列号红冲回去
IF @nBillType IN (11,34) AND EXISTS( SELECT TOP 1 1  FROM dbo.BillIndex WHERE BillNumberId = @nBillID AND IsLend= 1)
BEGIN
	
	DECLARE		
	@cmdSQL			NVARCHAR(MAX),
	@intDealSerial	TINYINT,
	@BillName		VARCHAR(100)
					
	SELECT @BillName=detailTable
			FROM BillName
			WHERE Billtype=@nBillType
			
	SET @cmdSQL='IF EXISTS(SELECT BillNumberID FROM '+@BillName+' WHERE BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND CAST(Serial AS VARCHAR(MAX))<>'''') SET @intDealSerial=1 ELSE SET @intDealSerial=0'
	EXECUTE sp_executesql @cmdSQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
	SELECT @intDealSerial AS '@intDealSerial'

	IF @intDealSerial=1 
	BEGIN
		UPDATE a SET a.STATE = b.STATE FROM gp_LendPtypeSerial a JOIN (
		SELECT * FROM (
			SELECT ROW_NUMBER() OVER(PARTITION BY Serial ORDER BY id DESC) AS rn,State,Serial FROM gp_inoutPtypeSerial
			WHERE Serial IN (
				SELECT Serial FROM gp_inoutPtypeSerial WHERE BillType = @nBillType AND BillNumberid = @nBillID
			)
		) AS t WHERE t.rn = 2 ) b ON a.Serial = b.Serial WHERE b.STATE != CASE @nBillType WHEN 34 THEN 18 ELSE 0 END
		--序列号的状态为：借出时，不回写序列号的状态，只将状态为“借进”、“借出还回”的状态更改为“已转采购”。 18 借出
	END 
END
--select 2,@nRet	
/*----------------------------------------红冲序列号 end-----------------------------------------------------*/	



------------------------------红冲自由项 start--------------------------------------------------------
IF @billType NOT IN (71,72,87,88,404,405,450,84,85,78,212,213,214,307,310,312,203,116,115,128,129,4,189,66,190,148,150,149,151,162,163,36,158,77,93,5,10,159,205,206,181,311)
BEGIN
	EXEC GP_Auditing_DealQty
			@nBillID,
			@nBillType,
			2,
			@chvDealBTypeID,
			@chvBTypeID,
			@chvSTypeID,
			@strPTypeIDOutPut	OUT,
			@nRet	OUT
			
	IF ISNULL(@nRet,0)<>0
	BEGIN
		ROLLBACK TRAN
		RETURN -18
	END
END

--select 4,@nRet
-------------------------------红冲自由项 end---------------------------------------------------------


	
	
-----------------------------处理关联的数据 start------------------------------------------

--这个地方要注意，只有老单据，没有@nNewBillID，这个地方需要注意测试下，看代码的话，@nNewBillID本身也没有什么用
EXEC @nRet = Gp_RedWordPostmortem @nBillID,@nBillID,@nBillType

--select 4.5,@nRet

IF ISNULL(@nRet,0)<>0
BEGIN
	ROLLBACK TRAN
	RETURN -1
END
-----------------------------处理关联的数据 end------------------------------------------
	
------------------------------单据红冲反向插入InOutStockTable，wx_InOutStockTable,listtable明细 start---------------------

IF @nBillType NOT IN (71,72,87,88)
BEGIN
	--这里把LISTTABLE,INOUTSTOCKTABLE这些的数量，金额变负
	
	IF EXISTS(
		SELECT BillNumberID
		FROM dbo.InOutstocktable
		WHERE BillNumberId=@nBillID AND BillType=@nBillType
	)
	BEGIN
		UPDATE a 
		SET QTY=-a.Qty,NQty=-a.NQty,Total=-a.Total,NTotal=-a.NTotal,SaleTotal=-a.SaleTotal,NSaleTotal=-a.NSaleTotal,
		CostTotal=-a.CostTotal,TaxTotal=-a.TaxTotal,NTaxTotal=-a.NTaxTotal
		FROM dbo.InOutstocktable a
		WHERE a.BillNumberId=@nBillID AND a.BillType=@nBillType
	END
	
	IF EXISTS(
		SELECT BillNumberID
		FROM dbo.wx_InOutstocktable
		WHERE BillNumberId=@nBillID AND BillType=@nBillType
	)
	BEGIN
		UPDATE a 
		SET QTY=-a.Qty,NQty=-a.NQty,Total=-a.Total,NTotal=-a.NTotal,SaleTotal=-a.SaleTotal,NSaleTotal=-a.NSaleTotal,
		TaxTotal=-a.TaxTotal,NTaxTotal=-a.NTaxTotal
		FROM dbo.wx_InOutStockTable a
		WHERE a.BillNumberId=@nBillID AND a.BillType=@nBillType
	END
	

	IF EXISTS(
		SELECT BillNumberID
		FROM dbo.ListTable
		WHERE BillNumberId=@nBillID AND BillType=@nBillType
	)
	BEGIN
		UPDATE a 
		SET Total=-a.Total,NTotal=-a.NTotal,
		CostTotal=-a.CostTotal
		FROM dbo.ListTable a
		WHERE a.BillNumberId=@nBillID AND a.BillType=@nBillType
	END
	


	IF ISNULL(@nRet,0)<>0
	BEGIN
		ROLLBACK TRAN
		RETURN @nRet
	END

END

--select 5,@nRet
------------------------------单据红冲反向插入InOutStockTable，wx_InOutStockTable,listtable明细 end------------------------


DECLARE		
	@intAdPriceBillNumberID		INT,
	@intAdPriceNewBillNumberID	INT,
	@strSTypeID					VARCHAR(50),
	@strBTypeID					VARCHAR(50),
	@intCID						INT

--针对暂估发票的特殊处理  start
IF @billtype IN (404,405)
BEGIN
	--对成本调价单的红冲要在调用后处理
	IF EXISTS(
		SELECT a.ID
		FROM AdPriceBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID
	)
	BEGIN

		SELECT @intAdPriceBillNumberID=a.BillNumberId,@strSTypeID=b.StypeID,@strBTypeID=b.Btypeid,@intCID=CID
		FROM AdPriceBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID

		
		
		
		MERGE GoodsStocks AS t
		USING(
			SELECT PTypeID,KTypeID,SUM(-Total) AS Total
			FROM AdPriceBill
			WHERE BillNumberID=@intAdPriceBillNumberID
			GROUP BY PTypeID,KTypeID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		WHEN MATCHED THEN 
			UPDATE SET t.Total=t.Total+s.Total,t.Price=CASE t.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(t.Total+s.Total AS  NUMERIC(24, 10) )/CAST(t.Qty AS  NUMERIC(24, 10) ),4) END
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,Qty,Price,Total) 
			VALUES(s.PtypeId,s.KTypeID,0,0,s.Total)
		;
		
		
		MERGE GoodsStocks_Qty AS t
		USING(
			SELECT DISTINCT PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID
			FROM AdPriceBill
			WHERE BillNumberID=@intAdPriceBillNumberID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		AND t.GoodsNumber=s.GoodsNumber AND t.ProduceDate=s.ProduceDate AND t.ValidDate=s.ValidDate
		AND t.CargoID=s.CargoID
	WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,CargoID,ItemID,IsCombined) 
			VALUES(s.PtypeId,s.KTypeID,s.GoodsNumber,s.ProduceDate,s.ValidDate,0,0,0,s.CargoID,0,0)
		;

		--GOODSSTOCKS_QTY不变

		

		UPDATE ListTable
		SET Total=-Total,Ntotal=-Ntotal,CostTotal=-CostTotal
		WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57
		
		EXEC @nRet = Gp_ModifyBAndAtype_Total @intAdPriceBillNumberID,57
		

		
		DELETE ListTable WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57
		
		DELETE AdPriceBill WHERE BillNumberId=@intAdPriceBillNumberID
		
		DELETE BillIndex WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57

	END		
		
	
	
	
	--处理发票状态
	EXEC GP_Receipt_Deal @nBillID,1
END
--end

--select 6,@nRet

-------------------------------inoutstocktable反算----------------------------------------
IF @nBillType NOT IN (205,206,71,72,87,88,404,405)
BEGIN
	EXEC @nRet = Gp_Zc_AuditingInOut @nBillID,@nBillType, 0, @strPTypeIDOutPut output
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -1
	END
END

-- 检查账户余额，是否过账后会 < 0
IF @nBillType NOT IN (71,72,87,88,400,401,402,403,404,405)
BEGIN
	EXEC @nRet = GP_AuditingATypeBalanceCheck @nBillID,@nBillType, @strPTypeIDOutPut output
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN 918
	END
END
-------------------------------listtable反算---------------------------------- 

--select 7,@nRet

IF @nBillType NOT IN (206,143) --listtable过账
BEGIN
	
	EXEC @nRet = Gp_ModifyBAndAtype_Total @nBillID,@nBillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -1
	END
END


--删除LISTTABLE,INOUTSTOCKTABLE

DELETE dbo.ListTable WHERE BillNumberId=@nBillID AND BillType=@nBillType

DELETE dbo.InOutstocktable WHERE BillNumberId=@nBillID AND BillType=@nBillType

DELETE dbo.wx_InOutStockTable WHERE BillNumberId=@nBillID AND BillType=@nBillType

--select 8,@nRet
--检查是否需要平均库存成本
EXEC @nRet = Gp_CallAverageCostPrice @nBillID
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	RETURN -1
END



IF @nBillType IN (212,213,214)
BEGIN
	--处理固定资产
	EXEC Gp_Auditing_DealAssest
	@nBillID,
	'00001',
	@nBillType,
	1,
	@tBillDate,
	@AssetBusinessTypeId,
	@chvSTypeID,
	@nRet OUT,
	@strPTypeIDOutPut OUT
	
	IF @nRet<>0
	BEGIN
		ROLLBACK TRAN
		RETURN @nRet
	END
END
--------------------------------------------------------------------------------------------------



IF @BillType=404
BEGIN
	EXEC GP_ReceiptBill_AfterRedWord @chvOpID=@ETypeID,@nBillID=@nBillID
END
--------------------------------------------------------------------------------------------------
COMMIT TRAN
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*


DECLARE
	@nBillID			numeric(10,0),
	@EtypeID        	varchar(50),
	@IsRepairBill		INT,
	@strPTypeIDOutPut	varchar(500),
	@redreason			VARCHAR(500),
	@billtype			INT,
	@nRet				INT
	
SELECT
	@nBillID=2,
	@EtypeID='00001',
	@IsRepairBill=0,
	@redreason='',
	@billtype=161,
	@NRET=0

EXEC @nRet=GP_Dis_Auditing 
	@nBillID,
	@EtypeID,
	@IsRepairBill,
	@strPTypeIDOutPut OUT,
	@redreason,
	@billtype
	
SELECT @nRet,@strPTypeIDOutPut	




*/




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇		
	日期：2014-08-26
	描述：提成规则设置的启用禁用
*/
CREATE PROCEDURE Gp_DisableAndEnableSetCommissionRule
(
	 @BillNumberId  INT,
	 @DisableAndEnablestate    INT
	 
)
--@encode$--
AS
SET NOCOUNT ON
IF @DisableAndEnablestate=0--禁用
 BEGIN
   IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState=1)
   BEGIN 
	   RAISERROR ('该规则未审核，不允许禁用!',16,1) 
	   RETURN;
   END 
   IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState=3)
   BEGIN 
	   RAISERROR ('该规则已禁用，不需要再禁用!',16,1) 
	   RETURN;
   END 
   UPDATE dbo.CommissionRule SET IsStop=BillState,BillState=3  WHERE BillNumberId=@BillNumberId
   
  
END 
ELSE
 BEGIN
  IF EXISTS(SELECT * FROM dbo.CommissionRule WHERE BillNumberId=@BillNumberId AND BillState!=3 )
   BEGIN 
	   RAISERROR ('该规则已是启用状态，不需要启用!',16,1) 
	   RETURN;
   END 
     UPDATE dbo.CommissionRule SET IsStop=0,BillState=IsStop  WHERE BillNumberId=@BillNumberId
 END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇		
	日期：2014-08-26
	描述：参照计划提成设置的启用禁用
*/
CREATE PROCEDURE Gp_DisableAndEnabletSetReferencePlanCommission
(
	 @BillNumberId  INT,
	 @DisableAndEnablestate    INT
	 
)
--@encode$--
AS
SET NOCOUNT ON
IF @DisableAndEnablestate=0--禁用
 BEGIN
   IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState=1)
   BEGIN 
	   RAISERROR ('该计划未审核，不允许禁用!',16,1) 
	   RETURN;
   END 
   IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState=3)
   BEGIN 
	   RAISERROR ('该计划已禁用，不需要再禁用!',16,1) 
	   RETURN;
   END 
   UPDATE dbo.ReferencePlanCommission SET IsStop=BillState,BillState=3  WHERE BillNumberId=@BillNumberId
   
  
END 
ELSE
 BEGIN
  IF EXISTS(SELECT * FROM dbo.ReferencePlanCommission WHERE BillNumberId=@BillNumberId AND BillState!=3 )
   BEGIN 
	   RAISERROR ('该计划已是启用状态，不需要启用!',16,1) 
	   RETURN;
   END 
     UPDATE dbo.ReferencePlanCommission SET IsStop=0,BillState=IsStop  WHERE BillNumberId=@BillNumberId
 END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID('GP_DistributeAccount')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE GP_DistributeAccount ;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	Created	:	喻堂
	Date	:	2012/05/04
	Description	: 分配/反分配会计科目
*/
CREATE PROCEDURE GP_DistributeAccount
(
	--@chvOperatorId VARCHAR(50),
	@isdist		INT,			--1：分配 0 ：反分配
	@stypeid	VARCHAR(MAX),	--分支机构
	@atypeid	VARCHAR(MAX),	--科目
	@AcId		INT				--科目表TREE
)
--@encode$--
AS 
SET NOCOUNT ON

CREATE TABLE #temp_stype
(
stypeid NVARCHAR(50)
)

SELECT  a AS typeid
INTO    #temp_account
FROM    dbo.f_split(@atypeid, ',') ;

IF EXISTS ( SELECT  typeid
            FROM    #temp_account
            EXCEPT
            SELECT  typeid
            FROM    Ac_Account WHERE AcId=@AcId ) 
    BEGIN
        RAISERROR ('选择了无效的会计科目。',16,1) ;	
        RETURN -1 ;
    END


--临时保存需要添加的数据
CREATE TABLE #temp_NeedHandle
(
 stypeid VARCHAR(50),
 actypeid VARCHAR(50)
) ;

DECLARE @ThisXiWaNo INT ;
SELECT  @ThisXiWaNo = ISNULL(MAX(XiWaMaxNumber), 0) + 1
FROM    Ac_Account WHERE AcId=@AcId

--分配科目表
IF @isdist = 1 
    BEGIN
        
        
    -- 插入其选择的节点及其父节点
    INSERT INTO    #temp_stype
    SELECT DISTINCT
            typeid AS stypeid
    FROM    SType s
    JOIN    dbo.f_split(@stypeid, ',') t ON t.a = s.TypeId
    UNION
    SELECT  a
    FROM    dbo.f_split(@stypeid, ',')

    IF EXISTS ( SELECT  stypeid FROM    #temp_stype
                EXCEPT
                SELECT  typeid FROM    SType ) 
        BEGIN
            RAISERROR ('选择了无效的分支机构。',16,1) ;	
            RETURN -1 ;
        END

		--用所选分支机构和所选会计科目进行JOIN
		--得到的结果集再减去他现在有的，就是这次操作应该添加的		
        INSERT  INTO #temp_NeedHandle (stypeid, actypeid)
                SELECT  ts.Stypeid, ta.typeID
                FROM    #temp_account ta, #temp_stype ts
                EXCEPT
                SELECT  aa.stypeid, aa.TypeId
                FROM    Ac_Account aa
                JOIN    #temp_stype ts ON ts.stypeid = aa.StypeId AND AA.AcId=@AcId
                JOIN    SType s ON s.TypeId = aa.StypeId AND s.soncount > 0
                
		
		--检查是否存在子分支机构已经拥有某会计科目
        DECLARE @verify_stypeid     VARCHAR(50)
        DECLARE @verify_actypeid    VARCHAR(50)
        DECLARE @verify_usercode    VARCHAR(50)
        DECLARE @verify_stypename   VARCHAR(50)
        DECLARE @verify_actypename  VARCHAR(50)
        --检查是否存在相同TYPEID
        
        SELECT TOP 1 @verify_stypeid = nh.stypeid, @verify_actypeid = nh.actypeid
        FROM    #temp_NeedHandle nh
        JOIN    Ac_Account ac ON ac.StypeId = nh.stypeid AND ac.TypeId = nh.actypeid AND AC.AcId=@AcId
        JOIN    SType s ON s.TypeId = nh.stypeid AND s.soncount = 0 ;                                           
        
        IF @verify_stypeid IS NOT NULL AND @verify_actypeid IS NOT	NULL 
            BEGIN
                SELECT TOP 1 @verify_stypename = s.fullname, @verify_actypename = ac.fullname
                FROM    SType s
                JOIN    Ac_Account ac ON ac.TypeId = @verify_actypeid AND ac.stypeid = @verify_stypeid AND AC.AcId=@AcId
                WHERE   s.TypeId = @verify_stypeid ;
                                         
                RAISERROR('分支机构【%s】已经有会计科目【%s】。',16,1,@verify_stypename,@verify_actypename) ;
                RETURN -1 ;
            END
            
        --检查是否存在相同USERCODE
        SELECT TOP 1 @verify_stypeid = stypeid, @verify_usercode = UserCode
        FROM    (SELECT nh.stypeid, ac.UserCode
                 FROM   #temp_NeedHandle nh
                 JOIN   Ac_Account ac ON nh.actypeid = ac.TypeId AND ac.StypeId = '00000'  AND AC.AcId=@AcId
                 INTERSECT
                 SELECT nh.stypeid, ac.UserCode
                 FROM   #temp_NeedHandle nh
                 JOIN   Ac_Account ac ON ac.StypeId = nh.stypeid  AND AC.AcId=@AcId) t ;
                
        IF @verify_stypeid IS NOT NULL
            AND @verify_usercode IS NULL 
            BEGIN
                SELECT TOP 1 @verify_stypename = s.fullname, @verify_actypename = ac.fullname
                FROM    SType s
                JOIN    Ac_Account ac ON ac.UserCode = @verify_usercode AND ac.stypeid = @verify_stypeid AND AC.AcId=@AcId
                WHERE   s.TypeId = @verify_stypeid
                
                RAISERROR('分支机构【%s】已经有编码为【%s】的会计科目【%s】。',16,1,@verify_stypeid,@verify_usercode,@verify_actypename) ;
                RETURN -1 ;
            END
        
        
        --为没有分类的分支机构添加分类
        INSERT  INTO #temp_NeedHandle (stypeid, actypeid)
                SELECT  s.stypeid, a.actypeid
                FROM    (SELECT typeid AS actypeid
                         FROM   Ac_Account ac
                         WHERE  StypeId = '00000' AND Leveal = 1 AND AC.AcId=@AcId) a,
                        #temp_stype s
                EXCEPT
                SELECT  s.stypeid, aa.TypeId
                FROM    Ac_Account aa
                JOIN    #temp_stype s ON s.stypeid = aa.StypeId  AND AA.AcId=@AcId
                WHERE   Leveal = 1 ;
		
        INSERT  INTO Ac_Account (StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,Fdc,IsCash,IsBank,IsDiary,
        Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,
        FintRate,FLeveal,Deleted,XiWaMaxNumber,IsOther,Cid,IsDist,[Group],IsPreGather,IsPrePay,IsGather,IsPay,IsVip,CheckType,AdjustAccounts,UnitID,AcId)
        SELECT  nh.StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,Fdc,IsCash,IsBank,IsDiary,
        Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,
        FintRate,FLeveal,Deleted,@ThisXiWaNo,IsOther,Cid,1,[Group],IsPreGather,IsPrePay,IsGather,IsPay,IsVip,CheckType,AdjustAccounts,UnitID,AcId
        FROM    Ac_Account ac
        JOIN    #temp_NeedHandle nh ON nh.actypeid = ac.TypeId
        WHERE   ac.StypeId = '00000' AND AC.AcId=@AcId;
                
                
                
        --更新sonnum,soncount
        UPDATE  Ac_Account
        SET     sonnum = (SELECT    COUNT(1)
                          FROM      Ac_Account a
                          WHERE     a.StypeId = ac.StypeId AND a.ParId = ac.TypeId AND a.AcId=@AcId),
                soncount = ISNULL(CAST((SELECT MAX(Right(TypeID,5))
                    FROM    Ac_Account a
                    WHERE   a.ParId = ac.TypeId AND a.Leveal = ac.Leveal + 1 AND a.StypeId = ac.StypeId  AND a.AcId=@AcId) AS INT),0),
                XiWaMaxNumber = @ThisXiWaNo
        FROM    Ac_Account ac
        JOIN    #temp_stype s ON ac.StypeId = s.Stypeid  AND AC.AcId=@AcId;
        
       
        
      
        --处理相关的辅助核算项目        
        INSERT  INTO Ac_Account_Assist_CheckItems (STypeId, ATypeId, Cid, Ascids,AcId)
        SELECT  nh.stypeid, nh.acTypeId, Cid, Ascids,AcId
        FROM    Ac_Account_Assist_CheckItems ci
        JOIN    #temp_NeedHandle nh ON nh.actypeid = ci.ATypeId
        WHERE   ci.STypeId = '00000' AND CI.AcId=@AcId; 
        
         --更新FACNT
         
         UPDATE Ac_Account
         SET FAcnt=1
         FROM Ac_Account
         JOIN #temp_NeedHandle nh ON nh.actypeid = Ac_Account.TypeId AND nh.stypeid=Ac_Account.StypeId AND Ac_Account.AcId=@AcId
         AND  EXISTS(SELECT TOP 1 Ascids FROM Ac_Account_Assist_CheckItems AAC WHERE AAC.STypeId=nh.stypeid AND AAC.ATypeId=nh.actypeid AND AAC.AcId=@AcId) 
         
         
               
    END
ELSE --反分配
    BEGIN
   
        -- 插入其选择的节点及其父节点
          
		INSERT  INTO #temp_stype
        SELECT  a
        FROM    dbo.f_split(@stypeid, ',')
      

        IF EXISTS ( SELECT stypeid FROM #temp_stype
                    EXCEPT
                    SELECT typeid FROM SType ) 
            BEGIN
                RAISERROR ('选择了无效的分支机构。',16,1) ;	
                RETURN -1 ;
            END
         IF EXISTS(SELECT *FROM Ac_Account_L WHERE typeid='00000' AND stypeid<>'00000')
         BEGIN
			IF EXISTS(SELECT *FROM sysdata WHERE SubName='Proinfo' AND SubValue='1') --v3
			BEGIN
				RAISERROR ('会计科目在多级权限被引用,操作失败!如欲是删除科目表,请到【会计科目多级权限-删除全部科目】中取消会计科目多级权限，再重新操作！',16,1) ;	
			END
			ELSE
			BEGIN
				RAISERROR ('此分支机构下会计科目在多级权限被引用,反分配失败!如欲反分配,请到【会计科目多级权限-添加分支机构】中取消此分支机构会计科目多级权限',16,1) ;	
			END
			RETURN -1 ;
         END        
                 
	    --用所选分支机构和所选会计科目进行JOIN
	    --得到的结果集再 ∩ 他现在有的，就是这次操作应该反分配的
	    ;
        WITH    temp_account
                  AS (SELECT    a.typeid
                      FROM      Ac_Account a
                      JOIN      #temp_account t ON a.typeid LIKE t.typeid
                                            + '%' AND AcId=@AcId)
            INSERT  INTO #temp_NeedHandle (stypeid, actypeid)
                    SELECT  ts.Stypeid, ta.typeID
                    FROM    temp_account ta, #temp_stype ts
                    INTERSECT
                    SELECT  s.stypeid, aa.TypeId
                    FROM    Ac_Account aa
                    JOIN    #temp_stype s ON s.stypeid = aa.StypeId AND AA.AcId=@AcId;

        --IF EXISTS ( SELECT TOP 1 1 FROM    #temp_needhandle ) 
        --    BEGIN
                --DECLARE @chck_stypeid VARCHAR(50)
                --DECLARE @chck_atypeid VARCHAR(50)
                --DECLARE @isUsed INT
        
                --SELECT  ROW_NUMBER() OVER (ORDER BY stypeid)
                --        AS row_id, stypeid,
                --        actypeid AS atypeid
                --INTO    #temp_check
                --FROM    #temp_needhandle n
                --JOIN SType s ON s.sonnum > 0
        
                --DECLARE @row_current INT
                --DECLARE @row_total INT
        
                --SELECT  @row_current = 1,
                --        @row_total = MAX(row_id)
                --FROM    #temp_check
			   --PRINT CAST(GETDATE() AS DATETIME)
						--WHILE @row_current <= @row_total 
						--	BEGIN
						--		SELECT  @chck_stypeid = stypeid, @chck_atypeid = atypeid
						--		FROM    #temp_check
						--		WHERE   row_id = @row_current
		            
								--EXEC @isUsed = GP_CheckRefUsage @stypeid=@chck_stypeid,@atypeid = @chck_atypeid -- varchar(50)
								--IF @isUsed > 0 
								--	BEGIN      	
								--		RAISERROR ('科目在被使用，操作失败。',16,1) ;	
								--		RETURN -1 ;
								--	END
    				--			IF EXISTS(SELECT *FROM Ac_Account_L WHERE typeid=@atypeid)  
								--BEGIN
								--	RAISERROR ('已设置会计科目多级权限，不能反分配',16,1) ;	
								--	RETURN -1 ;
								--END
							--	SET @row_current += 1
							--END
							
				IF EXISTS ( SELECT TOP 1 1 FROM    #temp_needhandle ) 
				BEGIN
					DECLARE @isUsed INT		            
					EXEC @isUsed = GP_CheckAllRefUsage @stypeid,@atypeid -- varchar(max)
					IF @isUsed > 0 
						BEGIN      	
							RAISERROR ('科目在被使用，操作失败。',16,1) ;	
							RETURN -1 ;
						END
					IF EXISTS(SELECT *FROM Ac_Account_L WHERE typeid IN (SELECT a FROM dbo.f_split(@atypeid,',')))  
					BEGIN
						RAISERROR ('已设置会计科目多级权限，不能反分配',16,1) ;	
						RETURN -1 ;
					END
				
		                    
							--PRINT CAST(GETDATE() AS DATETIME)
				BEGIN TRANSACTION
                        
                --反分配会计科目
                DELETE  Ac_Account
                FROM    Ac_Account ac
                JOIN    #temp_NeedHandle nh ON ac.StypeId = nh.stypeid
                                            AND ac.TypeId = nh.actypeid  AND AC.AcId=@AcId;
				
				----删除对应的会计科目权限
				--DELETE FROM Ac_Account_L
				--FROM Ac_Account_L AC
				--JOIN  #temp_NeedHandle nh ON ac.StypeId = nh.stypeid AND ac.TypeId = nh.actypeid
				
                --删除相关的辅助核算项目
                DELETE  Ac_Account_Assist_CheckItems
                FROM    Ac_Account_Assist_CheckItems ci
                JOIN    #temp_NeedHandle nh ON ci.StypeId = nh.stypeid
                                            AND ci.ATypeId = nh.actypeid AND CI.AcId=@AcId ;
        
                WITH    deletestype
                          AS (
                      -- 因为反分配的时候不能选择 资产 负债 这些分类
                      -- 所以在反分配的时候 判断 如果只剩下 分类 则删除掉分类。
                      -- CTE表达式中选出的是在这次反分配的分支机构中，只剩下分类的分支机构
                              SELECT    stypeid
                              FROM      Ac_Account WHERE AcId=@AcId
                              GROUP BY  StypeId
                              HAVING    MAX(Leveal) <= 1)
                    DELETE  Ac_Account
                    FROM    Ac_Account ac
                    JOIN    deletestype d ON d.stypeid = ac.stypeid AND AC.AcId=@AcId;
                
                --处理分支机构的往来单位设置
                DELETE BillAtype
                FROM BillAtype b
                JOIN #temp_NeedHandle n ON n.actypeid = b.AtypeId AND n.stypeid = b.StypeId
                
                UPDATE SType SET ATypeID ='' FROM SType s
                JOIN #temp_NeedHandle n ON n.stypeid = s.typeid AND n.actypeid = s.ATypeID
                UPDATE SType SET ATypeID2 ='' FROM SType s
                JOIN #temp_NeedHandle n ON n.stypeid = s.typeid AND n.actypeid = s.ATypeID2
                UPDATE SType SET ATypeID3 ='' FROM SType s
                JOIN #temp_NeedHandle n ON n.stypeid = s.typeid AND n.actypeid = s.ATypeID3
                UPDATE SType SET ATypeID4 ='' FROM SType s
                JOIN #temp_NeedHandle n ON n.stypeid = s.typeid AND n.actypeid = s.ATypeID4
                
                DECLARE @sstypeid   VARCHAR(50) 
                DECLARE @satypeid   VARCHAR(50)
                DECLARE @i          INT
                DECLARE @count      INT
                
                SELECT IDENTITY(int,1,1) AS rid,* INTO #tmp1 FROM #temp_NeedHandle
                
                SELECT @i = 1, @count = COUNT(1) FROM #tmp1

                WHILE @i <= @count
                BEGIN
                	EXEC GP_CleanDirtyAccountData2 @STypeId = @sstypeid, @typeid = @satypeid
                	
                	SET @i += 1
                END
                DROP TABLE #tmp1
                               
                /*-----------------------------------------------------------------------------------------------------------------
                为了在所有节点被反分配的时候能够正确停用科目表，所以要在此处理反分配分支机构的父节点信息
                -----------------------------------------------------------------------------------------------------------------*/

                SELECT  ROW_NUMBER() OVER (ORDER BY LEN(s.TypeId) DESC)
                        AS rid, s.typeid AS stypeid
                INTO    #TEMP_PARENT_STYPE
                FROM    SType s
                JOIN    dbo.f_split(@stypeid, ',') t ON t.a LIKE s.typeid
                                            + '%'
                                            AND s.sonnum > 0 -- 只选父节点
       
                DECLARE @current_row INT
                DECLARE @total_rows INT
       
                SELECT  @total_rows = (SELECT
                                            COUNT(1)
                                       FROM #TEMP_PARENT_STYPE)
                SET @current_row = 1
                WHILE @current_row <= @total_rows 
                    BEGIN
                        DECLARE @chk_stypeid VARCHAR(50)
                        SELECT  @chk_stypeid = stypeid
                        FROM    #TEMP_PARENT_STYPE
                        WHERE   rid = @current_row
            
                        --没有子分支机构使用该父类分支机构的项目
                        IF NOT EXISTS ( SELECT TOP 1
                                            1
                                        FROM
                                            Ac_Account
                                        WHERE
                                            stypeid LIKE @chk_stypeid
                                            + '%'
                                            AND LEN(stypeid) > LEN(@chk_stypeid) AND AcId=@AcId ) 
                            BEGIN
                                --反分配会计科目
                                DELETE  Ac_Account
                                WHERE   stypeid = @chk_stypeid AND AcId=@AcId
               
                                --删除相关的辅助核算项目
                                DELETE  Ac_Account_Assist_CheckItems
                                WHERE   STypeId = @chk_stypeid  AND AcId=@AcId
                                                           
                            END
            
                        SET @current_row += 1
                    END
                COMMIT TRANSACTION
            END

        --update sonnum;
        UPDATE  Ac_Account
        SET     sonnum = (SELECT    COUNT(1)
                          FROM      Ac_Account a
                          WHERE     a.StypeId = ac.StypeId
                                    AND a.ParId = ac.TypeId AND AcId=@AcId),
                XiWaMaxNumber = @ThisXiWaNo
        FROM    Ac_Account ac
        JOIN    #temp_stype s ON ac.StypeId = s.Stypeid  AND AC.AcId=@AcId;
    END

DROP TABLE #temp_stype,#temp_account,#temp_NeedHandle ;

RETURN 0 ;

GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-18
	描述：请购分配处理
*/
CREATE PROCEDURE Gp_DistributeBuyRequestBill
(
	@idlist	VARCHAR(MAX),		--单据ID集合
	@etypeid	int				--采购员id
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT * FROM RequestBill WHERE	ID IN (SELECT * FROM DBO.f_split(@idlist,',')) AND State>6)
BEGIN
	RAISERROR('有选中行的状态已在其他页面改变，请刷新后重试！',16,1)
	RETURN 
END
BEGIN TRANSACTION  DEL

UPDATE	RequestBill 
SET		etypeid = @etypeid 
WHERE	ID IN (SELECT * FROM DBO.f_split(@idlist,',')) 


IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('更改状态失败！',16,1)
END

COMMIT TRANSACTION  DEL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-29
	描述：新增品牌
-------------------------------------------*/
CREATE PROCEDURE GP_DIY_AddBrand
(
	@parid		VARCHAR(MAX),	---父ID
	@usercode	VARCHAR(MAX),	---编号
	@fullname	VARCHAR(MAX),	---全名
	@name		VARCHAR(MAX),	---简名
	@remark		VARCHAR(MAX)	---备注
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @nReturntype INT,@EtypeId_1 [varchar](50),@nSoncount INT,@nSonnum INT, @leveal SMALLINT
DECLARE	@dbname VARCHAR(MAX)
SET @dbname='DiyType'

IF EXISTS (SELECT Typeid FROM DiyType WHERE	FullName=@fullname	AND ParId=@parid)
BEGIN
	--print '['+@fullname+']该品牌已存在'
	RAISERROR('品牌【%s】已经存在，品牌编号或名称不能相同',16,1,@FullName)RETURN
END

IF EXISTS (SELECT Typeid FROM DiyType WHERE	TypeNumber=@usercode)
BEGIN
	--print '['+@usercode+']该品牌已存在'
	RAISERROR('品牌【%s】已经存在，品牌编号或名称不能相同',16,1,@usercode)RETURN
END
---获取新的ID号
EXEC @nReturntype=Gp_createId @parid,@dbname,@EtypeId_1 OUT,@nSonnum OUT,@nSoncount OUT
SELECT @leveal=leveal FROM DiyType WHERE typeid=@parid
SELECT @leveal=@leveal+1
INSERT INTO DiyType
(
	typeId,
	ParId,
	leveal,
	sonnum,
	soncount,
	deleted,
	FullName,
	Name,
	TypeNumber,
	Remark
)
VALUES
(
	@EtypeId_1,
	@parid,
	@leveal,
	'0',
	'0',
	'0',
	@fullname,
	@name,
	@usercode,
	@remark
)
IF @@ROWCOUNT!=1
RETURN -1
ELSE
UPDATE DiyType SET soncount=@nSoncount+1,sonnum=@nSonnum+1	WHERE typeId=@parid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-27
	描述：DIY系统删除商品与类别的指定关系
-------------------------------------------*/
CREATE PROCEDURE GP_DIY_DelApointGoods
(
	@ptypeid	varchar(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE
	@diytypeid	VARCHAR(MAX)
SELECT @diytypeid=Diytypeid FROM DiyTypePTypeID WHERE Ptypeid=@ptypeid
DELETE DiyTypePTypeID WHERE Ptypeid=@ptypeid
UPDATE DiyType SET sonnum=sonnum-1 WHERE typeId=@diytypeid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-27
	描述：删除品牌
-------------------------------------------*/
CREATE PROCEDURE GP_DIY_DelBrand
(
	@DIYtypeid	VARCHAR(MAX),
	@Parid		VARCHAR(MAX)	
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1FROM DiyTypePTypeID WHERE Diytypeid=@DIYtypeid)
	BEGIN
		RAISERROR('该品牌已有商品,不能被删除！',16,1)
		RETURN
	END	
DELETE DiyType WHERE typeId=@DIYtypeid
UPDATE DiyType SET sonnum=sonnum-1 WHERE typeId=@Parid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_Diy_GetIndexOrderId]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_Diy_GetIndexOrderId]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：自动生成编号
-------------------------------------------*/
CREATE PROCEDURE GP_Diy_GetIndexOrderId
(
    
	@BillDate DATETIME,
	@UserCode VARCHAR(50),
	@IndexOrderId VARCHAR(500) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
DECLARE  @IndexOrderstr VARCHAR(max),
         @id	        INT       
	SET @IndexOrderstr='0'
	SELECT @IndexOrderstr=IndexOrderId
	       FROM DiyIndex
	       WHERE (SELECT CONVERT (VARCHAR(10),BillDate,120))=(SELECT CONVERT (VARCHAR(10),@BillDate,120))
	       AND   (SELECT UserCode FROM employee WHERE typeId = checke) = @UserCode
	       ORDER BY IndexOrderId ASC 
    IF(@IndexOrderstr!='0')
    
		BEGIN
			SELECT @IndexOrderstr= a FROM dbo.f_split(@IndexOrderstr,'-') 
			SET @id=@IndexOrderstr	
			SET @IndexOrderId='Diy-'+@UserCode+'-'+ (SELECT CONVERT (VARCHAR(10),@BillDate,120))+'-'+ (SELECT (right((SELECT cast((10000+@id+1) AS VARCHAR)),4)) AS VARCHAR)
		END
		
		
	ELSE
		BEGIN
		   SET @IndexOrderId='Diy-'+@UserCode+'-'+(SELECT CONVERT (VARCHAR(10),@BillDate,120))+'-'+'0001'
		END	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-28
	描述：指定商品
-------------------------------------------*/
CREATE PROCEDURE GP_DIY_InsertDiyTypePTypeID
(
	@DIYApointtypeid	varchar(MAX),	---分类ID
	@Apointptypeid		varchar(MAX)	---商品ID
)
--@encode$--
AS
DECLARE
	@Ptypeid	VARCHAR(MAX),
	@Lenght		INT,
	@lenght2	INT,
	@count		INT
	
SET NOCOUNT ON
CREATE TABLE #PTYPE (TYPEID VARCHAR(50))
INSERT INTO #PTYPE
select * from dbo.f_split(@Apointptypeid,',')

SET @Lenght=@@rowcount
SET @lenght2=@Lenght
WHILE(@lenght2>0)
BEGIN
	SELECT TOP (@lenght2) @Ptypeid=TYPEID FROM #PTYPE
	IF EXISTS (SELECT *FROM DiyTypePTypeID WHERE Ptypeid=@Ptypeid)
	BEGIN
		SELECT @Ptypeid=FullName FROM PType WHERE typeId=@Ptypeid
		RAISERROR('商品【%s】已经被指定,指定失败!请重新选择',16,1,@Ptypeid)
		RETURN -1
	END
	SET	@lenght2=@lenght2-1
END

SET @count=0
WHILE(@Lenght>0)
BEGIN
	SELECT TOP (@Lenght) @Ptypeid=a FROM dbo.f_split(@Apointptypeid,',')
	INSERT INTO DiyTypePTypeID(Diytypeid,Ptypeid) VALUES(@DIYApointtypeid,@Ptypeid)
	SET	@Lenght=@Lenght-1
	SET	@count=@count+1
END
UPDATE DiyType SET soncount=soncount+@count,sonnum=sonnum+@count WHERE typeId=@DIYApointtypeid
RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：保存单据
-------------------------------------------*/
CREATE PROCEDURE GP_Diy_InsertIntoDiyIndex
(
	
	@EtypeId  VARCHAR(50),
	@CheckId  VARCHAR(50),
	@BillDate DATETIME,
	@ToTalQty  NUMERIC(24, 10) ,
	@TotalMoney  NUMERIC(24, 10) ,
	@Comment VARCHAR(500),
	@optype	VARCHAR(MAX),
	@IndexOrderId VARCHAR(500),
	@Counts INT
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	IF(@optype='MODIFY')
		BEGIN
			UPDATE	DiyIndex 
			SET		
			        EtypeId=@EtypeId,
			        ToTalQty=@ToTalQty,
			        TotalMoney=@TotalMoney,
					Comment=@Comment,
					Counts=@Counts
	       WHERE	IndexOrderId=@IndexOrderId
		   RETURN 1
		END 

	IF exists (SELECT IndexOrderId FROM DiyIndex WHERE IndexOrderId=@IndexOrderId)
	BEGIN
		--RAISERROR('该配置单编号【%s】已经存在，编号不能重复',16,1,@IndexOrderId)RETURN
		RETURN -1
	END
	INSERT INTO DiyIndex 
		(	
	      BillDate,
	      EtypeId,
	      ToTalQty,
	      TotalMoney,
	      Comment,
	      IndexOrderId,
	      Counts,
	      checke
         ) 
	VALUES
		(
		 @BillDate,
		 @EtypeId,
		 @ToTalQty,
		 @TotalMoney,
		 @Comment,
		 @IndexOrderId,
		 @Counts,
		 @CheckId
		)
END
RETURN 1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-5-6
	描述：查询装机配置单
-------------------------------------------*/
CREATE PROCEDURE GP_DIY_QueryBillIndex
(
	@OperatorID	VARCHAR(MAX),	--操作员ID
	@startdate	VARCHAR(MAX),	
	@enddate	VARCHAR(MAX),	
	@etypeid	VARCHAR(MAX),	--经手人ID
	@remark		VARCHAR(MAX)	
)
--@encode$--
AS
SET NOCOUNT ON
CREATE TABLE #Etype (TypeID varchar(50))
--限制条件 经手人
IF @etypeid=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@etypeid,',')) b where left(a.typeid,len(b.a))=b.a

DECLARE @SQL VARCHAR(MAX)
IF(@remark='' OR @remark IS NULL)
	SET @remark='%'
SET @SQL='SELECT	d.BillNumberId indexid,
					d.IndexOrderId orderid,
					d.EtypeId etypeid,
					e.FullName AS checkefullname,
					Ep.FullName AS efullname,
					d.BillDate billdate,
					d.Comment remark
			FROM	DiyIndex d
			INNER JOIN Employee E ON E.typeId=d.Checke
			INNER JOIN Employee Ep ON Ep.typeId=d.etypeid
			WHERE	1=1
			AND		(D.EtypeId IN (SELECT TypeID FROM #Etype) OR D.EtypeId='''') 
			AND		d.BillDate>='+CHAR(39)+@startdate+CHAR(39)+'
			AND		d.BillDate<='+CHAR(39)+@enddate+CHAR(39)+'
			AND		d.Comment LIKE ''%'+@remark+'%'
			
IF(@etypeid=''OR @etypeid IS NULL)
BEGIN
	SET	@SQL=@SQL+CHAR(39)+''
	EXEC (@SQL)
	RETURN
END
SET @SQL=@SQL+CHAR(39)+'
			AND		d.EtypeId in (SELECT TYPEID FROM #Etype)'
EXEC (@SQL)

DROP TABLE #Etype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-6
	描述：查询商品
-------------------------------------------*/
CREATE PROCEDURE GP_DIY_QueryGoods
(
	@usercode	VARCHAR(MAX),	---编号
	@fullname	VARCHAR(MAX),	---全名	
	@entrycode	VARCHAR(MAX)	---条码
)
--@encode$--
AS
SET NOCOUNT ON

SELECT	b.typeId	ParId,
		b.ParId		typeId,
		c.typeId	ptypeid,
		c.UserCode	TypeNumber,
		c.FullName	FullName,
		c.Name		name,
		c.Comment	Remark
FROM	DiyTypePTypeID a
INNER JOIN DiyType b ON b.typeId=a.Diytypeid
INNER JOIN ptype C ON a.Ptypeid=c.typeId
WHERE	c.UserCode	like @usercode+'%'
AND		c.FullName LIKE @fullname+'%'
AND		c.EntryCode LIKE @entrycode+'%'
AND		C.typeId NOT IN(SELECT Ptypeid from DiyTypePTypeID)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-29
	描述：修改品牌信息
-------------------------------------------*/
CREATE PROCEDURE GP_DIY_UpdateBrand
(
	@typeid		varchar(MAX),	---类型ID
	@usercode	VARCHAR(MAX),	---编号
	@fullname	VARCHAR(MAX),	---全名
	@name		VARCHAR(MAX),	---简名
	@remark		VARCHAR(MAX)	---备注
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE
	@parid	VARCHAR(MAX)
SELECT @parid=ParId FROM DiyType WHERE typeId=@typeid

IF EXISTS (SELECT Typeid FROM DiyType WHERE	FullName=@fullname AND typeId!=@typeid	AND ParId=@parid)
BEGIN
	RAISERROR('该名称【%s】已经存在，同一大类下名称不能相同',16,1,@FullName)RETURN -1
END

IF EXISTS (SELECT Typeid FROM DiyType WHERE	TypeNumber=@usercode AND typeId!=@typeid)
BEGIN
	RAISERROR('该编号【%s】已经存在，编号不能相同',16,1,@usercode)RETURN -1
END

UPDATE DiyType SET TypeNumber=@usercode,FullName=@fullname,Name=@name,Remark=@remark WHERE typeId=@typeid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DlExtTabTr]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_DlExtTabTr]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	EXEC Gp_DlExtTabTr
*/
CREATE PROCEDURE Gp_DlExtTabTr
--@encode$--
AS 
SET NOCOUNT ON

/*
DECLARE @tableList	VARCHAR(MAX),
		@i			INT,
		@nCount		INT,
		@tri		INT,
		@trnCount	INT,
		@trName		VARCHAR(MAX)
		
DECLARE @trTableList TABLE
(
	nid			INT IDENTITY(1,1),
	tName		VARCHAR(MAX)
)

DECLARE @allTableList TABLE
(
	nid			INT IDENTITY(1,1),
	tName		VARCHAR(MAX)
)

CREATE TABLE #oneTableTrigger
(
	nid			INT IDENTITY(1,1),
	tableName	VARCHAR(MAX),
	tName		VARCHAR(MAX)
)		

DECLARE @tableName VARCHAR(MAX)

INSERT INTO @allTableList(tName) SELECT DISTINCT En_Item FROM sp_SysTEnItem ORDER BY En_Item ASC

SET @nCount = @@ROWCOUNT

SET @i = 1

WHILE @i <= @nCount
BEGIN
	SELECT @tableName = tName FROM @allTableList WHERE nid = @i
	
	TRUNCATE TABLE #oneTableTrigger
	INSERT INTO #oneTableTrigger(tableName,tName) SELECT @tableName, r.name FROM sysobjects t INNER JOIN sysobjects r ON r.parent_obj = t.id AND r.xtype = 'tr' WHERE t.name = @tableName

	SET @trnCount = @@ROWCOUNT

	SET @tri = 1

	WHILE @tri <= @trnCount
	BEGIN
		SELECT @trName = tName FROM #oneTableTrigger WHERE nid = @tri
		IF NOT EXISTS(SELECT TOP 1 1 FROM sp_SysTEnItem WHERE En_Item = @tableName AND Align = @trName)
		BEGIN
			EXEC('DROP TRIGGER '+@trName)
		END
		SET @tri = @tri + 1
	END
	
	SET @i = @i + 1
END

DROP TABLE #oneTableTrigger

*/

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_DoClear]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_DoClear;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：施训果
	时间：2012-05-03 09:18:19.193
	描述：执行锁库或解锁操作
*/
CREATE PROCEDURE GP_DoClear
	@nBillID	NUMERIC(10,0),					-- 单据 ID 号
	@nBillType		INT
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @orderid INT,			--订单ID
			@clearQty NUMERIC(24,10),--需要解锁的数量
			@lockQty NUMERIC(24,10),	--锁定的数量
			@lockDetailID INT,		--锁定记录ID
			@OrderType    INT		--订单类型  0=销售订单 1=组合品销售订单
				
	CREATE TABLE #ClearDetail --创建临时表用于存放解锁数据信息
	(
		[BillNumberId]	NUMERIC(10,0),
		[OrderID]	INT,
		[Ptypeid]	VARCHAR(50),
		[Etypeid]	VARCHAR(50),
		[KTypeID]	VARCHAR(50),
		[CargoID]	INT,
		[UnitID]	INT,
		[GoodsOrder]	INT,
		[GoodsNumber]   VARCHAR(100),
		[GoodsCostPrice] NUMERIC(24,10),
		[ItemID]	BIGINT,
		[IsCombined]	INT,
		[ProduceDate]	VARCHAR(50),
		[ValidDate]	VARCHAR(50),
		[LockNumber]	NUMERIC(24,10)
	)
	
	IF @nBillType=11
	BEGIN
		UPDATE dbo.SaleBill SET ClearQty=0 WHERE BillNumberId=@nBillID	--先将本次解锁数量置为零
		SET @OrderType=0
		DECLARE Clear_Cursor CURSOR SCROLL DYNAMIC FOR
			SELECT OrderID,Qty
			FROM dbo.SaleBill
			WHERE BillNumberId=@nBillID
		FOR UPDATE
	END
	ELSE IF @nBillType=140
	BEGIN
		UPDATE dbo.CommissionBill SET ClearQty=0 WHERE BillNumberId=@nBillID --先将本次解锁数量置为零
		SET @OrderType=0
		DECLARE Clear_Cursor CURSOR SCROLL DYNAMIC FOR
			SELECT OrderID,Qty
			FROM dbo.CommissionBill
			WHERE BillNumberId=@nBillID
		FOR UPDATE
	END
	ELSE IF @nBillType=402
	BEGIN
		UPDATE dbo.SendBill SET ClearQty=0 WHERE BillNumberId=@nBillID	--先将本次解锁数量置为零
		SET @OrderType=0
		DECLARE Clear_Cursor CURSOR SCROLL DYNAMIC FOR
			SELECT OrderID,Qty
			FROM dbo.SendBill
			WHERE BillNumberId=@nBillID
		FOR UPDATE
	END
	ELSE IF @nBillType=12
	BEGIN
		UPDATE dbo.PT_Combin_SaleBillDetail SET ClearQty=0 WHERE BillNumberId=@nBillID	--先将本次解锁数量置为零
		SET @OrderType=1
		DECLARE Clear_Cursor CURSOR SCROLL DYNAMIC FOR
			SELECT OrderID,Qty
			FROM dbo.PT_Combin_SaleBillDetail
			WHERE BillNumberId=@nBillID
		FOR UPDATE
	END
		
	OPEN Clear_Cursor
	FETCH NEXT FROM Clear_Cursor INTO @orderid,@clearQty
	WHILE @@FETCH_STATUS <> -1
	BEGIN
		DECLARE Lock_Cursor CURSOR FAST_FORWARD FOR
			SELECT LockNumber,ID
			FROM dbo.PT_SaleOrderLockDetail
			WHERE OrderID=@orderid AND OrderType=@OrderType
			ORDER BY LockNumber DESC
			
		OPEN Lock_Cursor
		FETCH NEXT FROM Lock_Cursor INTO @lockQty,@lockDetailID
		WHILE @@FETCH_STATUS <> -1
		BEGIN
			IF @clearQty>=@lockQty
			BEGIN
				INSERT INTO #ClearDetail
				        ( BillNumberId ,
				          OrderID ,
				          Ptypeid ,
				          Etypeid ,
				          KTypeID ,
				          CargoID ,
				          UnitID ,
				          GoodsOrder ,
				          GoodsNumber ,
				          GoodsCostPrice ,
				          ItemID ,
				          IsCombined ,
				          ProduceDate ,
				          ValidDate ,
				          LockNumber
				        )
				SELECT 
						  BillNumberId ,
				          OrderID ,
				          Ptypeid ,
				          Etypeid ,
				          KTypeID ,
				          CargoID ,
				          UnitID ,
				          GoodsOrder ,
				          GoodsNumber ,
				          GoodsCostPrice ,
				          ItemID ,
				          IsCombined ,
				          ProduceDate ,
				          ValidDate ,
				          LockNumber
				 FROM PT_SaleOrderLockDetail
				 WHERE ID=@lockDetailID
				 
				 DELETE PT_SaleOrderLockDetail
				 WHERE ID=@lockDetailID
				 
				 IF @nBillType=11
				 BEGIN
					UPDATE SaleBill SET ClearQty=@lockQty
					WHERE CURRENT OF Clear_Cursor
				 END
				 ELSE IF @nBillType=140
				 BEGIN
					UPDATE CommissionBill SET ClearQty=@lockQty
					WHERE CURRENT OF Clear_Cursor
				 END
				 ELSE IF @nBillType=402
				 BEGIN
					UPDATE SendBill SET ClearQty=@lockQty
					WHERE CURRENT OF Clear_Cursor
				 END
				 ELSE IF @nBillType=12
				 BEGIN
					UPDATE PT_Combin_SaleBillDetail SET ClearQty=@lockQty
					WHERE CURRENT OF Clear_Cursor
				 END
			END
			ELSE
			BEGIN
				INSERT INTO #ClearDetail
				        ( BillNumberId ,
				          OrderID ,
				          Ptypeid ,
				          Etypeid ,
				          KTypeID ,
				          CargoID ,
				          UnitID ,
				          GoodsOrder ,
				          GoodsNumber ,
				          GoodsCostPrice ,
				          ItemID ,
				          IsCombined ,
				          ProduceDate ,
				          ValidDate ,
				          LockNumber
				        )
				SELECT 
						  BillNumberId ,
				          OrderID ,
				          Ptypeid ,
				          Etypeid ,
				          KTypeID ,
				          CargoID ,
				          UnitID ,
				          GoodsOrder ,
				          GoodsNumber ,
				          GoodsCostPrice ,
				          ItemID ,
				          IsCombined ,
				          ProduceDate ,
				          ValidDate ,
				          @clearQty
				 FROM PT_SaleOrderLockDetail
				 WHERE ID=@lockDetailID
				 
				 UPDATE PT_SaleOrderLockDetail SET LockNumber-=@clearQty
				 WHERE ID=@lockDetailID
				 
				 IF @nBillType=11
				 BEGIN
					UPDATE SaleBill SET ClearQty=@clearQty
					WHERE CURRENT OF Clear_Cursor
				 END
				 ELSE IF @nBillType=140
				 BEGIN
					UPDATE CommissionBill SET ClearQty=@clearQty
					WHERE CURRENT OF Clear_Cursor
				 END
				 ELSE IF @nBillType=402
				 BEGIN
					UPDATE SendBill SET ClearQty=@clearQty
					WHERE CURRENT OF Clear_Cursor
				 END
				 ELSE IF @nBillType=12
				 BEGIN
					UPDATE PT_Combin_SaleBillDetail SET ClearQty=@clearQty
					WHERE CURRENT OF Clear_Cursor
				 END
			END
			IF @nBillType=12
			BEGIN
				IF @clearQty>@lockQty
					UPDATE dbo.PT_Combin_OrderBillDetail SET LockNumber-=@lockQty WHERE OrderID=@orderid
				ELSE 
				BEGIN
					UPDATE dbo.PT_Combin_OrderBillDetail SET LockNumber-=@clearQty WHERE OrderID=@orderid
					BREAK
				END
			END
			ELSE
			BEGIN
				IF @clearQty>@lockQty
					UPDATE dbo.OrderBill SET LockNumber-=@lockQty WHERE OrderID=@orderid
				ELSE 
				BEGIN
					UPDATE dbo.OrderBill SET LockNumber-=@clearQty WHERE OrderID=@orderid
					BREAK
				END
			END
			
			
			SET @clearQty-=@lockQty
			FETCH NEXT FROM Lock_Cursor INTO @lockQty,@lockDetailID
		END
		
		DEALLOCATE Lock_Cursor
		FETCH NEXT FROM Clear_Cursor INTO @orderid,@clearQty
	END
	
	DEALLOCATE Clear_Cursor
	
	DECLARE @sql VARCHAR(max)
	--读取成本算法  移动加权 0,先进先出 1,后进先出 2,手工指定 3
	DECLARE @costing INT
	SELECT @costing=SubValue FROM sysdata Where SubName='costing'
	-----------------------------------------开始解锁-----------------------------------------------	
	SET @sql='
	UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber-=l.LockNumber
	FROM GOODSSTOCKS_QTY g RIGHT JOIN
	(
		SELECT ISNULL(Sum(LockNumber),0) AS LockNumber,
			   GoodsNumber,
			   IsCombined,
			   ItemID,
			   CargoID,
			   KTypeID,
			   ProduceDate,
			   PTypeID,
			   ValidDate
		'+CASE WHEN @costing=3 THEN ',GoodsCostPrice ' ELSE ' 'END+'
		FROM #ClearDetail
		GROUP By 		  
			   GoodsNumber,
			   IsCombined,
			   ItemID,
			   CargoID,
			   KTypeID,
			   ProduceDate,
			   PTypeID,
			   ValidDate
		'+CASE WHEN @costing=3 THEN ',GoodsCostPrice ' ELSE ' 'END+'
	) l
	ON g.CargoID = l.CargoID AND g.GoodsNumber = l.GoodsNumber AND g.Iscombined = l.IsCombined AND g.ItemID = l.ItemID
	AND g.KTypeID = l.KTypeID AND g.ProduceDate = l.ProduceDate AND g.PTypeID = l.Ptypeid
	AND g.ValidDate = l.ValidDate '
	IF @costing=3--手工指定算法需要加上成本价维度
		SET @sql+=' AND g.GoodsCostPrice=l.GoodsCostPrice'
	EXEC(@sql)	
	
	DROP TABLE #ClearDetail
	-----------------------------------------解锁结束-----------------------------------------------
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_DoInvocationAccountManage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_DoInvocationAccountManage
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	账套启用
-- 时间：	2012-05-31
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_DoInvocationAccountManage
(
	@dataname VARCHAR(100)--使用数据库
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @EEROR INT=0--执行sql错误条数
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE Deleted=0)
	BEGIN
		RAISERROR('账套启用前必须设置会计期间!',16,1) RETURN
	END
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Currency WHERE Sysrow=1)
	BEGIN
		RAISERROR('账套启用前必须设置币种!',16,1) RETURN
	END 

BEGIN TRAN
IF EXISTS(SELECT * from sysdata WHERE SubName='IsInvocation')
	BEGIN
		UPDATE sysdata SET SubValue='1' WHERE SubName='IsInvocation'
		SET @EEROR=@@ERROR
	END
ELSE  
	BEGIN
		DECLARE @SubNo INT=(SELECT MAX(SubNo)+1 FROM SYSDATA)
		INSERT INTO sysdata([SubNo],[SubName],[SubValue],[SubComment]) VALUES(@SubNo,'IsInvocation','1',NULL)
		SET @EEROR=@@ERROR
	END

IF(@EEROR<>0)
BEGIN
	ROLLBACK TRAN
	RAISERROR('启用账套失败!',16,1)
END
ELSE 
	COMMIT TRAN
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_DoLock]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_DoLock;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：施训果
	时间：2012-05-03 09:18:19.193
	描述：执行锁库或解锁操作
*/
CREATE PROCEDURE GP_DoLock
	@isLock	INT ,
	@orderType INT ,--订单类型 0：销售订单 1：组合品销售订单
	@clearDetial TbType_ClearDetail READONLY,
	@lockDetial TbType_LockDetail READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @sql VARCHAR(max)
	--读取成本算法  移动加权 0,先进先出 1,后进先出 2,手工指定 3
	DECLARE @costing INT
	SELECT @costing=SubValue FROM sysdata Where SubName='costing'
	-----------------------------------------开始解锁-----------------------------------------------
	SELECT d.* INTO #LockDetail FROM dbo.PT_SaleOrderLockDetail d 
	INNER JOIN @clearDetial c ON d.BillNumberId=c.BillNumberId AND d.OrderID=c.OrderID AND ordertype=@ordertype

	SET @sql='
	UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber-=l.LockNumber
	FROM GOODSSTOCKS_QTY g RIGHT JOIN 
	(
		SELECT ISNULL(Sum(LockNumber),0) AS LockNumber,
			   GoodsNumber,
			   IsCombined,
			   ItemID,
			   CargoID,
			   KTypeID,
			   ProduceDate,
			   PTypeID,
			   ValidDate
		'+CASE WHEN @costing=3 THEN ',GoodsCostPrice ' ELSE ' 'END+'
		FROM #LockDetail
		GROUP By 		  
			   GoodsNumber,
			   IsCombined,
			   ItemID,
			   CargoID,
			   KTypeID,
			   ProduceDate,
			   PTypeID,
			   ValidDate
		'+CASE WHEN @costing=3 THEN ',GoodsCostPrice ' ELSE ' 'END+'
	) AS l
	ON g.CargoID = l.CargoID AND g.GoodsNumber = l.GoodsNumber AND g.Iscombined = l.IsCombined AND g.ItemID = l.ItemID
	AND g.KTypeID = l.KTypeID AND g.ProduceDate = l.ProduceDate AND g.PTypeID = l.Ptypeid
	AND g.ValidDate = l.ValidDate '
	
	IF @costing =3 --手工指定算法需要加上成本价维度
	BEGIN
		SET @sql+=' AND g.GoodsCostPrice=l.GoodsCostPrice'
	END
	
	EXEC(@sql)	

	IF @orderType=0
	BEGIN
		UPDATE dbo.OrderBill SET LockNumber=0
		FROM OrderBill o RIGHT JOIN  @clearDetial c
		ON o.billNumberID=c.BillNumberId AND o.OrderID=c.OrderID
	END
	ELSE
	BEGIN
		UPDATE dbo.PT_Combin_OrderBillDetail SET LockNumber=0
		FROM PT_Combin_OrderBillDetail o RIGHT JOIN  @clearDetial c
		ON o.billNumberID=c.BillNumberId AND o.OrderID=c.OrderID		
	END
	
	DELETE PT_SaleOrderLockDetail
	FROM dbo.PT_SaleOrderLockDetail d INNER JOIN @clearDetial c ON d.BillNumberId=c.BillNumberId AND d.OrderID=c.OrderID
	
	DROP TABLE #LockDetail
	-----------------------------------------解锁结束-----------------------------------------------
	
	-----------------------------------------锁库开始-----------------------------------------------
	IF @isLock=1 AND EXISTS( SELECT 1 FROM @lockDetial )
	BEGIN
		INSERT INTO dbo.PT_SaleOrderLockDetail
		        ( BillNumberId ,
		          OrderID ,
		          etypeid ,
		          KTypeID ,
		          CargoID ,
		          GoodsNumber ,
		          ItemID ,
		          IsCombined ,
		          ProduceDate ,
		          ValidDate ,
		          LockNumber ,
		          GoodsCostPrice,
		          Ptypeid,
		          ordertype
		        )
		SELECT 
				BillNumberId ,
		          OrderID ,
		          etypeid ,
		          KTypeID ,
		          CargoID ,
		          GoodsNumber ,
		          ItemID ,
		          IsCombined ,
		          ProduceDate ,
		          ValidDate ,
		          LockNumber ,
		          GoodsCostPrice ,
		          Ptypeid,
		          @orderType
		FROM @lockDetial
		WHERE LockNumber<>0
		
		IF @costing=3
		BEGIN
			UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber+=l.LockNumber
			FROM GOODSSTOCKS_QTY g RIGHT JOIN (SELECT GoodsCostPrice,CargoID,etypeid,GoodsNumber,IsCombined,ItemID,KTypeID,ProduceDate,Ptypeid,ValidDate,SUM(LockNumber) AS LockNumber 
			FROM @lockDetial GROUP BY CargoID,etypeid,GoodsNumber,IsCombined,ItemID,KTypeID,ProduceDate,Ptypeid,ValidDate,GoodsCostPrice) l
			ON g.CargoID = l.CargoID AND g.GoodsNumber = l.GoodsNumber AND g.Iscombined = l.IsCombined AND g.ItemID = l.ItemID
			AND g.KTypeID = l.KTypeID AND g.ProduceDate = l.ProduceDate AND g.PTypeID = l.Ptypeid
			AND g.ValidDate = l.ValidDate AND g.GoodsCostPrice=l.GoodsCostPrice
		
		END
		ELSE
		BEGIN
			UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber+=l.LockNumber
			FROM GOODSSTOCKS_QTY g RIGHT JOIN 
			(SELECT CargoID,etypeid,GoodsNumber,IsCombined,ItemID,KTypeID,ProduceDate,Ptypeid,ValidDate,SUM(LockNumber) AS LockNumber 
			FROM @lockDetial GROUP BY CargoID,etypeid,GoodsNumber,IsCombined,ItemID,KTypeID,ProduceDate,Ptypeid,ValidDate) l
			ON g.CargoID = l.CargoID AND g.GoodsNumber = l.GoodsNumber AND g.Iscombined = l.IsCombined AND g.ItemID = l.ItemID
			AND g.KTypeID = l.KTypeID AND g.ProduceDate = l.ProduceDate AND g.PTypeID = l.Ptypeid
			AND g.ValidDate = l.ValidDate
		
		END
		
		if @orderType=0
		begin
			UPDATE dbo.OrderBill SET LockNumber=c.locknumber
			FROM OrderBill o RIGHT JOIN  (select SUM(LockNumber) AS locknumber,BillNumberID,OrderID FROM @lockDetial GROUP BY BillNumberID,OrderID) c
			ON o.billNumberID=c.BillNumberId AND o.OrderID=c.OrderID
		end
		else
		begin
			UPDATE dbo.PT_Combin_OrderBillDetail SET LockNumber=c.locknumber
			FROM PT_Combin_OrderBillDetail o RIGHT JOIN  (select SUM(LockNumber) AS locknumber,BillNumberID,OrderID FROM @lockDetial GROUP BY BillNumberID,OrderID) c
			ON o.billNumberID=c.BillNumberId AND o.OrderID=c.OrderID
		end
	END
	-----------------------------------------锁库结束-----------------------------------------------
	
	-----------------------------------------锁库后校验数据是否正确-----------------------------------------------
	SELECT P.LockInfo AS lockInfo 
	FROM dbo.GoodsStocks_qty G 
	INNER JOIN @lockDetial P  ON G.CargoID = P.CargoID AND G.GoodsCostPrice = P.GoodsCostPrice 
	AND G.GoodsNumber = P.GoodsNumber AND G.Iscombined = P.IsCombined 
	AND G.ItemID = P.ItemID AND G.KTypeID = P.KTypeID
	AND G.ProduceDate = P.ProduceDate AND G.ValidDate = P.ValidDate
	WHERE G.LockNumber>g.qty AND G.PTypeID = P.Ptypeid
	-----------------------------------------锁库后校验数据是否正确-----------------------------------------------
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_DoRedWordLock]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_DoRedWordLock;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：施训果
	时间：2012-05-03 09:18:19.193
	描述：执行红冲锁库操作
*/
CREATE PROCEDURE GP_DoRedWordLock
	@nBillID	NUMERIC(10,0),					-- 单据 ID 号
	@nBillType		INT
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @orderid		INT,			 --订单ID
			@clearQty		NUMERIC(24,10),  --需要解锁的数量
			@lockQty		NUMERIC(24,10),	--锁定的数量
			@lockDetailID	INT	,	--锁定记录ID
			@Costing		INT		--成本算法
			
	SELECT @Costing=SubValue FROM dbo.sysdata WHERE SubName='costing'
	
	CREATE TABLE #LockDetail --创建临时表用于存放解锁数据信息
	(
		[BillNumberId]	NUMERIC(10,0),
		[OrderID]	INT,
		[Ptypeid]	VARCHAR(50),
		[Etypeid]	VARCHAR(50),
		[KTypeID]	VARCHAR(50),
		[CargoID]	INT,
		[UnitID]	INT,
		[GoodsOrder]	INT,
		[GoodsNumber]   VARCHAR(100),
		[GoodsCostPrice] NUMERIC(24,10),
		[ItemID]	BIGINT,
		[IsCombined]	INT,
		[ProduceDate]	VARCHAR(50),
		[ValidDate]	VARCHAR(50),
		[LockNumber]	NUMERIC(24,10),
		[OrderType]		INT
	)
	
	IF @nBillType=11
	BEGIN
		INSERT INTO #LockDetail
				        ( BillNumberId ,
				          OrderID ,
				          Ptypeid ,
				          Etypeid ,
				          KTypeID ,
				          CargoID ,
				          UnitID ,
				          GoodsOrder ,
				          GoodsNumber ,
				          GoodsCostPrice ,
				          ItemID ,
				          IsCombined ,
				          ProduceDate ,
				          ValidDate ,
				          LockNumber,
				          OrderType
				        )
				SELECT 
						  o.BillNumberId ,
				          s.OrderID ,
				          s.Ptypeid ,
				          s.ETypeID ,
				          s.KTypeID ,
				          s.CargoID ,
				          0 ,
				          s.GoodsOrder ,
				          s.GoodsNumber ,
				          CASE @Costing WHEN 3 THEN s.GoodsCostPrice ELSE 0 END,
				          s.ItemID ,
				          s.IsCombined ,
				          s.ProduceDate ,
				          s.ValidDate ,
				          s.ClearQty,
				          0
				 FROM dbo.SaleBill s LEFT JOIN dbo.OrderBill o ON s.OrderID = o.OrderID
				 WHERE s.billNumberID=@nBillID AND s.ClearQty<>0
				
				UPDATE dbo.SaleBill SET ClearQty=0 WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=140
	BEGIN
		INSERT INTO #LockDetail
				        ( BillNumberId ,
				          OrderID ,
				          Ptypeid ,
				          Etypeid ,
				          KTypeID ,
				          CargoID ,
				          UnitID ,
				          GoodsOrder ,
				          GoodsNumber ,
				          GoodsCostPrice ,
				          ItemID ,
				          IsCombined ,
				          ProduceDate ,
				          ValidDate ,
				          LockNumber,
				          OrderType
				        )
				SELECT 
						  o.BillNumberId ,
				          c.OrderID ,
				          c.Ptypeid ,
				          '' ,
				          c.KTypeID ,
				          c.CargoID ,
				          0 ,
				          c.GoodsOrder ,
				          c.GoodsNumber ,
				          CASE @Costing WHEN 3 THEN c.GoodsCostPrice ELSE 0 END,
				          c.ItemID ,
				          c.IsCombined ,
				          c.ProduceDate ,
				          c.ValidDate ,
				          c.ClearQty,
				          0
				 FROM dbo.CommissionBill c LEFT JOIN dbo.OrderBill o ON c.OrderID = o.OrderID
				 WHERE c.BillNumberId=@nBillID AND c.ClearQty<>0
				 
				 
				UPDATE dbo.CommissionBill SET ClearQty=0 WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=402
	BEGIN
		INSERT INTO #LockDetail
				        ( BillNumberId ,
				          OrderID ,
				          Ptypeid ,
				          Etypeid ,
				          KTypeID ,
				          CargoID ,
				          UnitID ,
				          GoodsOrder ,
				          GoodsNumber ,
				          GoodsCostPrice ,
				          ItemID ,
				          IsCombined ,
				          ProduceDate ,
				          ValidDate ,
				          LockNumber,
				          OrderType
				        )
				SELECT 
						  o.BillNumberId ,
				          c.OrderID ,
				          c.Ptypeid ,
				          '' ,
				          c.KTypeID ,
				          c.CargoID ,
				          0 ,
				          c.GoodsOrder ,
				          c.GoodsNumber ,
				          CASE @Costing WHEN 3 THEN c.GoodsCostPrice ELSE 0 END,
				          c.ItemID ,
				          c.IsCombined ,
				          c.ProduceDate ,
				          c.ValidDate ,
				          c.ClearQty,
				          0
				 FROM dbo.SendBill c LEFT JOIN dbo.OrderBill o ON c.OrderID = o.OrderID
				 WHERE c.BillNumberId=@nBillID AND c.ClearQty<>0
				 
				 
				UPDATE dbo.CommissionBill SET ClearQty=0 WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=12
	BEGIN
		INSERT INTO #LockDetail
				        ( BillNumberId ,
				          OrderID ,
				          Ptypeid ,
				          Etypeid ,
				          KTypeID ,
				          CargoID ,
				          UnitID ,
				          GoodsOrder ,
				          GoodsNumber ,
				          GoodsCostPrice ,
				          ItemID ,
				          IsCombined ,
				          ProduceDate ,
				          ValidDate ,
				          LockNumber,
				          OrderType
				        )
				SELECT 
						  o.BillNumberId ,
				          c.OrderID ,
				          c.Ptypeid ,
				          '' ,
				          c.KTypeID ,
				          c.CargoID ,
				          0,
				          c.GoodsOrder ,
				          c.GoodsNumber ,
				          CASE @Costing WHEN 3 THEN c.GoodsCostPrice ELSE 0 END,
				          c.ItemID ,
				          c.IsCombined ,
				          c.ProduceDate ,
				          c.ValidDate ,
				          c.ClearQty,
				          1
				 FROM dbo.PT_Combin_SaleBillDetail c LEFT JOIN dbo.PT_Combin_OrderBillDetail o ON c.OrderID = o.OrderID
				 WHERE c.BillNumberId=@nBillID AND c.ClearQty<>0
				 
				 
				UPDATE dbo.PT_Combin_SaleBillDetail SET ClearQty=0 WHERE BillNumberId=@nBillID
	END
	-----------------------------------------开始锁定-----------------------------------------------	
	DECLARE @sql VARCHAR(max)
	--读取成本算法  移动加权 0,先进先出 1,后进先出 2,手工指定 3
	SET @sql='
	MERGE INTO dbo.PT_SaleOrderLockDetail l
	USING #LockDetail d ON l.BillNumberId=d.BillNumberId AND l.OrderID=d.OrderID AND l.Ptypeid=d.Ptypeid AND l.KTypeID=d.KTypeID
	AND l.CargoID=d.CargoID AND l.GoodsOrder=d.GoodsOrder AND l.GoodsNumber=d.GoodsNumber 
	AND l.ItemID=d.ItemID AND l.IsCombined=d.IsCombined AND l.ProduceDate=d.ProduceDate AND l.ValidDate=d.ValidDate AND	l.OrderType=d.OrderType '
	IF @costing=3--手工指定算法需要加上成本价维度
		SET @sql+=' AND l.GoodsCostPrice=d.GoodsCostPrice';
	SET @sql+='
	WHEN MATCHED THEN UPDATE SET l.LockNumber+=d.LockNumber
	WHEN NOT MATCHED 
	THEN INSERT (
					BillNumberID,
					OrderID,
					ETypeID,
					KTypeID,
					CargoID,
					UnitID,
					GoodsOrder,
					GoodsNumber,
					ItemID,
					IsCombined,
					ProduceDate,
					ValidDate,
					LockNumber,
					PTypeID,
					GoodsCostPrice,
					OrderType
				) 
		VALUES  ( d.BillNumberId , -- BillNumberId - numeric
				  d.OrderID , -- OrderID - int
				  d.etypeid , -- etypeid - varchar(50)
				  d.KTypeID , -- KTypeID - varchar(50)
				  d.CargoID , -- CargoID - int
				  d.UnitID , -- UnitID - int
				  d.GoodsOrder , -- GoodsOrder - int
				  d.GoodsNumber , -- GoodsNumber - varchar(100)
				  d.ItemID , -- ItemID - bigint
				  d.IsCombined , -- IsCombined - int
				  d.ProduceDate , -- ProduceDate - varchar(50)
				  d.ValidDate , -- ValidDate - varchar(50)
				  d.LockNumber , -- LockNumber - numeric
				  d.Ptypeid , -- Ptypeid - varchar(50)
				  d.GoodsCostPrice , -- GoodsCostPrice - varchar(50)
				  d.OrderType
				);'
	EXEC(@sql)	
	     
	IF @nBillType=12
	BEGIN
		UPDATE dbo.PT_Combin_OrderBillDetail SET LockNumber+=c.locknumber
			FROM PT_Combin_OrderBillDetail o RIGHT JOIN  (select SUM(LockNumber) AS locknumber,BillNumberID,OrderID FROM #LockDetail GROUP BY BillNumberID,OrderID) c
			ON o.billNumberID=c.BillNumberId AND o.OrderID=c.OrderID
	END
	ELSE 
	BEGIN  
		UPDATE dbo.OrderBill SET LockNumber+=c.locknumber
			FROM OrderBill o RIGHT JOIN  (select SUM(LockNumber) AS locknumber,BillNumberID,OrderID FROM #LockDetail GROUP BY BillNumberID,OrderID) c
			ON o.billNumberID=c.BillNumberId AND o.OrderID=c.OrderID
	END	
	
	SET @sql='
	UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber+=l.LockNumber
	FROM GOODSSTOCKS_QTY g RIGHT JOIN
	(
		SELECT ISNULL(Sum(LockNumber),0) AS LockNumber,
			   GoodsNumber,
			   IsCombined,
			   ItemID,
			   CargoID,
			   KTypeID,
			   ProduceDate,
			   PTypeID,
			   ValidDate
		'+CASE WHEN @costing=3 THEN ',GoodsCostPrice ' ELSE ' 'END+'
		FROM #LockDetail
		GROUP By 		  
			   GoodsNumber,
			   IsCombined,
			   ItemID,
			   CargoID,
			   KTypeID,
			   ProduceDate,
			   PTypeID,
			   ValidDate
		'+CASE WHEN @costing=3 THEN ',GoodsCostPrice ' ELSE ' 'END+'
	)  l
	ON g.CargoID = l.CargoID AND g.GoodsNumber = l.GoodsNumber AND g.Iscombined = l.IsCombined AND g.ItemID = l.ItemID
	AND g.KTypeID = l.KTypeID AND g.ProduceDate = l.ProduceDate AND g.PTypeID = l.Ptypeid
	AND g.ValidDate = l.ValidDate '
	IF @costing=3--手工指定算法需要加上成本价维度
		SET @sql+=' AND g.GoodsCostPrice=l.GoodsCostPrice'
	EXEC(@sql)	
	
	DROP TABLE #LockDetail
	-----------------------------------------锁定结束-----------------------------------------------
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[del_tmpGain]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
drop trigger [dbo].[del_tmpGain]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IN_tmpGain]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
drop trigger [dbo].[IN_tmpGain]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tmpGain]') and OBJECTPROPERTY(id, N'IsTable') = 1)
truncate table [dbo].[tmpGain]
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_EditFinancialFormula]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_EditFinancialFormula]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	ThreeFinancialFormula_Stype 修改报表
-- 时间：	2019-04-15
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [Gp_EditFinancialFormula]
(
	@STypeId		VARCHAR(50),--分支机构ID
	@IsEditAll		BIT,--将此取数规则应用到所有分支机构
	@ReportType		INT,--//报表ID
	@ItemId			INT,--//项目ID
	@Formula		VARCHAR(MAX),--具体科目编号
	@FormulaType	INT,----公式类型比如利润表1：本期金额 2本年累计金额
	@isPar			BIT,--是否父类
	@OperatorID		VARCHAR(50)--当前操作员
)

AS
SET NOCOUNT ON

--修改项目为父级节点
IF(@FormulaType=1)
	UPDATE ThreeFinancialItem_SType SET Formula1IsPar=@isPar WHERE STypeID=@STypeId AND ItemID=@ItemId AND ReportType=@ReportType 
ELSE 
	UPDATE ThreeFinancialItem_SType SET Formula2IsPar=@isPar WHERE STypeID=@STypeId AND ItemID=@ItemId AND ReportType=@ReportType 

--将此取数规则应用到所有分支机构
IF(@IsEditAll=1)
	BEGIN
		DELETE FROM ThreeFinancialFormula_Stype 
		WHERE 
			ItemID=@ItemId 
			AND ReportType=@ReportType 
			AND FormulaType=@FormulaType
		--父级关系	
		DELETE FROM ThreeFinancialItemParent_Stype
		WHERE
			ParItemID=@ItemId 
			AND ReportType=@ReportType 
			AND FormulaType=@FormulaType
			
		IF(ISNULL(@Formula,'')<>'')
		BEGIN
			IF(@isPar=1)--父级关系
			BEGIN
				INSERT INTO ThreeFinancialItemParent_Stype(ReportType,STypeID,ParItemID,[Sign],SonItemID,FormulaType,UpdateTime,OperatorId)
				SELECT 
					@ReportType,
					S.TypeID STypeID,
					@ItemID,
					CASE WHEN SUBSTRING(F.Formula,1,1)='＋' THEN 1 ELSE -1 END [Sign],
					SUBSTRING(F.Formula,2,LEN(F.Formula)),
					@FormulaType,
					GETDATE(),
					@OperatorID
				FROM SType S,(SELECT ROW_NUMBER() OVER(ORDER BY getdate()) RowId,A Formula FROM f_split(@Formula,',')) F
				WHERE S.sonnum=0
				GROUP BY S.TypeId,F.Formula
			END
			ELSE 
			BEGIN
				INSERT INTO ThreeFinancialFormula_Stype(ReportType,STypeID,ItemID,[Sign],Formula,RowId,FormulaType,UpdateTime,OperatorId)
				SELECT 
					@ReportType,
					S.TypeID STypeID,
					@ItemID,
					CASE WHEN F.RowId=1 THEN 1 
						ELSE CASE WHEN SUBSTRING(F.Formula,1,1)='＋' THEN 1 ELSE -1 END END [Sign],
					SUBSTRING(F.Formula,2,LEN(F.Formula)),
					F.RowId,
					@FormulaType,
					GETDATE(),
					@OperatorID
				FROM SType S,(SELECT ROW_NUMBER() OVER(ORDER BY getdate()) RowId,A Formula FROM f_split(@Formula,',')) F
				WHERE S.sonnum=0
				GROUP BY S.TypeId,F.RowId,F.Formula
			END
		END
	END
ELSE --更改特定分支机构机构公式
	BEGIN
		DELETE FROM ThreeFinancialFormula_Stype 
		WHERE 
			ItemID=@ItemId 
			AND ReportType=@ReportType 
			AND FormulaType=@FormulaType
			AND STypeID=@STypeId
		--父级关系	
		DELETE FROM ThreeFinancialItemParent_Stype
		WHERE
			ParItemID=@ItemId 
			AND ReportType=@ReportType 
			AND FormulaType=@FormulaType
			AND STypeID=@STypeId
		
		IF(ISNULL(@Formula,'')<>'')
		BEGIN
			IF(@isPar=1)--父级关系
			BEGIN
				INSERT INTO ThreeFinancialItemParent_Stype(ReportType,STypeID,ParItemID,[Sign],SonItemID,FormulaType,UpdateTime,OperatorId)
				SELECT 
					@ReportType,
					@STypeID,
					@ItemID,
					CASE WHEN SUBSTRING(F.Formula,1,1)='＋' THEN 1 ELSE -1 END [Sign],
					SUBSTRING(F.Formula,2,LEN(F.Formula)),
					@FormulaType ,
					GETDATE(),
					@OperatorID
				FROM (SELECT ROW_NUMBER() OVER(ORDER BY getdate()) RowId,A Formula FROM f_split(@Formula,',')) F
				GROUP BY F.Formula
			END
			ELSE 
			BEGIN
				INSERT INTO ThreeFinancialFormula_Stype(ReportType,STypeID,ItemID,[Sign],Formula,RowId,FormulaType,UpdateTime,OperatorId)
				SELECT 
					@ReportType,
					@STypeID,
					@ItemID,
					CASE WHEN SUBSTRING(F.Formula,1,1)='＋' THEN 1 ELSE -1 END [Sign],
					SUBSTRING(F.Formula,2,LEN(F.Formula)),
					F.RowId,
					@FormulaType ,
					GETDATE(),
					@OperatorID
				FROM (SELECT ROW_NUMBER() OVER(ORDER BY getdate()) RowId,A Formula FROM f_split(@Formula,',')) F
				GROUP BY F.RowId,F.Formula
			END
		END
	END
	
RETURN 1
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_EditLendBorrowIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_EditLendBorrowIndex]
GO

--**********************************************
--存储过程修改记录
--修改原因:借进开单保存时未删除表头自定义值
--修改人:田小波
--LAST修改时间:2016-11-07
--**********************************************

CREATE PROCEDURE [Gp_EditLendBorrowIndex]
    (
      @BillNumberID [varchar](20) = '' ,
      @BillDate [datetime] ,
      @BillCode [varchar](200) ,  -- #&**&#
      @BillType [numeric](4, 0) ,
      @Comment [varchar](256) ,
      @AtypeId [varchar](50) ,
      @PtypeId [varchar](50) ,
      @BtypeId [varchar](50) ,
      @DealBtypeId [varchar](50) ,
      @EtypeId [varchar](50) ,
      @KtypeId [varchar](50) ,
      @KtypeId2 [varchar](50) ,
      @IfCheck [char](1) ,
      @CheckE [varchar](50) ,
      @TotalMoney  NUMERIC(24, 10)  ,
      @TotalQty  NUMERIC(24, 10)  ,
      @TotalInMoney  NUMERIC(24, 10)  ,
      @Tax [numeric] ,
      @szPeriod [smallint] ,
      @Explain [varchar](256) ,
      @Draft [bit] ,
      @RedWord [bit] ,
      @OrderId [numeric] = 0 ,
  --添加新的参数
      @WayBillCode VARCHAR(50) = NULL ,
      @Goodsnumber NUMERIC(2, 0) = NULL ,
      @PackWay VARCHAR(20) = NULL ,
      @Tel VARCHAR(60) = NULL ,
      @DTypeID VARCHAR(50) ,
      @STypeID VARCHAR(50),
      @UpdateE VARCHAR(50)
    )
--@encode$--
AS 
    SET NOCOUNT ON
    DECLARE @Re INT ,
        @Flag INT
    DECLARE @BeginDate DATETIME ,
        @szItem VARCHAR(30) ,
        @szVchCode VARCHAR(30)

    IF @BillNumberID = '' 
        BEGIN
            EXEC Gp_GetSubValue 'period', @STypeID, @szPeriod OUT
            SELECT  @BeginDate = startdate
            FROM    monthproc
            WHERE   period = @szPeriod
            IF @BillDate < @BeginDate AND @BillType NOT IN (71,72,87,88)
                BEGIN 
	 --RAISERROR('录单日期小于本期开始日期 ！',16,1) 
                    RETURN -2
                END

	-- 修改 LendIndex 的 ID 字段，写入真实的物理录单顺序
            DECLARE @NewID NUMERIC(10, 0)
            SELECT  @NewID = ISNULL(MAX(ID), 0) + 1
            FROM    LendIndex

            INSERT  INTO [dbo].[LendIndex]
                    ( [BillDate] ,
                      [BillCode] ,
                      [BillType] ,
                      [Comment] ,
                      [atypeid] ,
                      [ptypeid] ,
                      [btypeid] ,
                      [dealbtypeid],
                      [etypeid] ,
                      [ktypeid] ,
                      [ktypeid2] ,
                      [ifcheck] ,
                      [checke] ,
                      [totalqty] ,
                      [totalmoney] ,
                      [totalinmoney] ,
                      [tax] ,
                      [period] ,
                      [explain] ,
                      [draft] ,
                      [RedWord] ,
                      [orderid] ,
                      [waybillcode] ,
                      [goodsnumber] ,
                      [packway] ,
                      [Tel] ,
                      [DTypeID] ,
                      [ID] ,
                      [STypeID],
                      redreason,
                      UpdateE
	                  )
            VALUES  ( @BillDate ,
                      @BillCode ,
                      @BillType ,
                      @Comment ,
                      @atypeid ,
                      @ptypeid ,
                      @btypeid ,
                      @DealBtypeId ,
                      @etypeid ,
                      @ktypeid ,
                      @ktypeid2 ,
                      @ifcheck ,
                      @checke ,
                      @totalqty ,
                      @totalmoney ,
                      @totalinmoney ,
                      @tax ,
                      @szPeriod ,
                      @explain ,
                      @draft ,
                      @redword ,
                      @orderID ,
                      @waybillcode ,
                      @goodsnumber ,
                      @packway ,
                      @Tel ,
                      @DTypeID ,
                      @NewID ,
                      @STypeID,
                      '',
                      ''
	                  )
            IF @@rowcount = 0
                OR @@error <> 0 
                RAISERROR('更新单据发生错误！',16,1)
            ELSE 
                RETURN SCOPE_IDENTITY();
        END 
    ELSE 
        BEGIN
            IF EXISTS ( SELECT  TOP 1 1
                        FROM    LendIndex
                        WHERE   draft = 0
                                AND ifcheck = 't'
                                AND [BillNumberId] = @BillNumberId 
                        UNION ALL
                        SELECT TOP 1 1 FROM dbo.ListTable WHERE BillNumberId=@BillNumberID AND BillType=@BillType
                        UNION ALL
                        SELECT TOP 1 1 FROM dbo.ListTable WHERE BillNumberId=@BillNumberID AND BillType=@BillType
                       ) 
                RETURN -1 
			
            EXEC Gp_GetSubValue 'period', @STypeID, @szPeriod OUT
            SELECT  @BeginDate = startdate
            FROM    monthproc
            WHERE   period = @szPeriod
            IF @BillDate < @BeginDate  AND @BillType NOT IN (71,72,87,88)
                BEGIN 
	 --RAISERROR('录单日期小于本期开始日期 ！',16,1) 
                    RETURN -2
                END

	-- 修改 LendIndex 的 ID 字段，写入真实的物理录单顺序
            SELECT  @NewID = ISNULL(MAX(ID), 0) + 1
            FROM    LendIndex
			
			DELETE FROM dbo.Custom_BillDetails WHERE BillId=@BillNumberId AND BillType=@BillType
			DELETE FROM dbo.Custom_BillIndex WHERE BillId=@BillNumberId AND BillType=@BillType
            UPDATE  [dbo].[LendIndex]
            SET     [BillDate] = @BillDate ,
                    [BillCode] = @BillCode ,
                    [BillType] = @BillType ,
                    [Comment] = @Comment ,
                    [atypeid] = @atypeid ,
                    [ptypeid] = @ptypeid ,
                    [btypeid] = @btypeid ,
                    [dealbtypeid]=@DealBtypeId,
                    [etypeid] = @etypeid ,
                    [ktypeid] = @ktypeid ,
                    [ktypeid2] = @ktypeid2 ,
                    [ifcheck] = @ifcheck ,
                    [checke] = @checke ,
                    [totalmoney] = @totalmoney ,
                    [totalinmoney] = @totalinmoney ,
                    [totalqty] = @totalqty ,
                    [tax] = @tax ,
                    [period] = @szPeriod ,
                    [explain] = @Explain ,
                    [RedWord] = @RedWord ,
                    [draft] = @draft ,
                    [orderid] = @orderid ,
                    [waybillcode] = @waybillcode ,
                    [goodsnumber] = @goodsnumber ,
                    [packway] = @packway ,
                    [tel] = @tel ,
                    [DTypeID] = @DTypeID ,
                    [ID] = @NewID ,
                    [STypeID] = @STypeID,
                    [UpdateE]=@UpdateE
            WHERE   ( [BillNumberId] = @BillNumberId )
	  
            IF @@rowcount = 0
                OR @@error <> 0 
                RAISERROR('更新数据表发生错误！',16,1)
        END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_EditonShelvespickIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_EditonShelvespickIndex]
GO

--SELECT  * FROM dbo.onShelvespickIndex
 
CREATE PROCEDURE [Gp_EditonShelvespickIndex]
    (
      @BillNumberID                       [varchar](20) = '' ,
      @BillDate                           [datetime] ,
      @BillCode                           [varchar](200) ,   
      @BillType                           [numeric](6, 0) ,
      @DtypeId                           [varchar](50) ,
      @EtypeId                           [varchar](50) ,
      @StypeId                           [varchar](50) ,
      @KtypeId                           [varchar](50) ,
      @IfCheck                           [char](1) ,
      @CheckE                           [varchar](50) ,
      @Comment                           [varchar](256)='' ,
      @Explain                           [varchar](256) ,
      @Draft                           [bit] ,
      @IfAudit			CHAR(1) = '3' ,
      @IsIni                           [bit],
      @totalqty				NUMERIC(24,10),
      @updateE                           [varchar](50) 
    )
--@encode$--
AS 
    SET NOCOUNT ON
    
    DECLARE 
	@Re INT , 
	@Flag INT,
    @BeginDate DATETIME ,
    @period SMALLINT

    EXEC Gp_GetSubValue 'period', @STypeID, @period OUT
    SELECT  @BeginDate = startdate
    FROM    monthproc
    WHERE   period = @period
    IF @BillDate < @BeginDate AND @BillType NOT IN (412,413)
    BEGIN 
        RETURN -2
    END
            
    IF @BillNumberID = '' 
        BEGIN
			
			INSERT INTO dbo.onShelvespickIndex
			        ( etypeid ,
			          ktypeid ,
			          BillDate ,
			          Billcode ,
			          billtype ,
			          totalqty ,
			          period ,
			          comment ,
			          explain ,
			          Checke ,
			          IfAudit ,
			          DtypeId ,
			          Stypeid ,
			          draft ,
			          checkTime ,
			          posttime ,
			          updateE ,
			          Poster ,
			          LastUpdateTime ,
			          IsIni
			        )
			VALUES
			        ( @EtypeId , -- etypeid - varchar(50)
			          @KtypeId , -- ktypeid - varchar(50)
			          @BillDate , -- BillDate - datetime
			          @Billcode , -- Billcode - varchar(200)
			          @billtype , -- billtype - smallint
			          @totalqty , -- totalqty - numeric
			          @period   , -- period - smallint
			          @comment , -- comment - varchar(256)
			          @explain , -- explain - varchar(256)
			          @Checke , -- Checke - varchar(50)
			          '' , -- IfAudit - int
			          @DtypeId , -- DtypeId - varchar(50)
			          @Stypeid , -- Stypeid - varchar(50)
			          @draft , -- draft - bit
			          GETDATE() , -- checkTime - datetime
			          NULL , -- posttime - datetime
			          NULL , -- updateE - varchar(50)
			          '' , -- Poster - varchar(50)
			          NULL, -- LastUpdateTime - datetime
			          @IsIni  -- IsIni - bit
			        )
	
            IF @@rowcount = 0 OR @@error <> 0  
				RAISERROR('更新单据发生错误！',16,1)
            ELSE 
                RETURN SCOPE_IDENTITY();
        END 
    ELSE 
        BEGIN
            IF EXISTS ( SELECT  TOP 1 1
                        FROM    onShelvespickIndex
                        WHERE   draft = 0
                                AND ifcheck = 't'
                                AND [BillNumberId] = @BillNumberId 
                       ) 
                RETURN -1 
                
			--删除自定义表头列
			--删除自定义明细列
			DELETE FROM CustomBillColumns	WHERE billnumberid=@BillNumberId AND BillType=@BillType
			DELETE FROM CustomBillDetailColumns WHERE billnumberid=@BillNumberId AND BillType=@BillType
			DELETE FROM dbo.Custom_BillDetails WHERE BillId=@BillNumberID AND BillType=@BillType
			DELETE FROM dbo.Custom_BillIndex WHERE BillId=@BillNumberID AND BillType=@BillType
			
           UPDATE dbo.onShelvespickIndex 
		   SET     etypeid = @EtypeId, 
				   ktypeid = @ktypeid,
				   BillDate = @BillDate,
				   Billcode = @Billcode,
				   totalqty = @totalqty,
				   period = @period,
				   comment = @comment,
				   explain = @explain,
				   IfAudit = '',
				   DtypeId = @DtypeId,
				   Stypeid = @Stypeid,
				   draft = @draft,
				   updateE = @updateE,
				   Poster = '',
				   LastUpdateTime =  GETDATE() ,
				   IsIni = @IsIni
		    WHERE billNumberId = @BillNumberID
            IF @@rowcount = 0 OR @@error <> 0 
                RAISERROR('更新数据表发生错误！',16,1)
        END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	资金调拨单入账，要判断资金调拨单调入分支机构是否满足条件
	作    者：	冯波
	修改时间：	2014-08-21
*/
CREATE             PROCEDURE Gp_EnterAccount
(
	@nBillID				NUMERIC(10,0),					-- 单据 ID 号
	@ErrMsg					VARCHAR(MAX)='' OUT				--返回固定资产信息
)
--@encode$--
AS
	DECLARE
		@nRet	INT
		
	SELECT
		@nRet=0
		
	IF NOT EXISTS(
		SELECT BillNumberId
		FROM BillIndex
		WHERE BillNumberId=@nBillID AND ifcheck='t' AND RedWord=0 AND IfConfirm=0
	)	
	BEGIN
		SET @ErrMsg='该单据不存在或未过账或已红冲或已记账！'
		RETURN 333
	END	
	
	
	IF EXISTS(
			SELECT a.Id FROM Te_Period a
			INNER JOIN Ac_Period b
			ON a.FYear=b.FYear
			AND a.FPeriod=b.FPeriod
			WHERE a.STypeId=(SELECT VerifyID  FROM dbo.BillIndex b INNER JOIN dbo.SType s ON b.Stypeid2=s.TypeId WHERE BillNumberId=@nbillid)
		)
	BEGIN
		IF NOT EXISTS(
			SELECT c.BillNumberId 
			FROM BillIndex c
			WHERE c.BillNumberId=@nbillid
			AND EXISTS(
					SELECT a.Id 
					FROM Te_Period a
					INNER JOIN Ac_Period b
					ON a.FYear=b.FYear
					AND a.FPeriod=b.FPeriod
					WHERE a.STypeId=(SELECT VerifyID  FROM dbo.BillIndex b INNER JOIN dbo.SType s ON b.Stypeid2=s.TypeId WHERE BillNumberId=@nbillid)
					AND c.BillDate BETWEEN b.FBegin AND b.FEnd
				) 
		)
		BEGIN
			SET @ErrMsg='出纳系统已月结，不能过账！'
			RETURN  303 
		END
	END
	ELSE
	BEGIN
		SET @ErrMsg='出纳系统还未初始化，不能过账！'
		RETURN 304
	END

	--更改入账标志
	UPDATE BillIndex
	SET IfConfirm=1
	WHERE BillNumberId=@nBillID
		

	RETURN @nRet
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*


DECLARE
	@nBillID				NUMERIC(10,0),					-- 单据 ID 号
	@ErrMsg					VARCHAR(MAX),
	@NRET					INT
	
	
--BEGIN TRAN
	
SELECT @nBillID=48	
EXEC @NRET=Gp_EnterAccount @nBillID,@ErrMsg

SELECT @NrET,@ERRMSG

SELECT ifcheck,IfConfirm,draft,* FROM billindex
where billnumberid=@nbillid

--ROLLBACK TRAN

*/



/*------------------------------------------
    作者：董湛
	日期：2013-03-26
	描述：下载的物流单位生成供应商
-------------------------------------------*/
IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_EshopAddBtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].GP_EshopAddBtype
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE GP_EshopAddBtype
(
       @UserCode	VARCHAR(200),
       @FullName	NVARCHAR(500)
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	--------先判断是否存在
	IF EXISTS (SELECT TOP 1 1 FROM btype WHERE UserCode=@UserCode)
		RETURN
	IF EXISTS (SELECT TOP 1 1 FROM btype WHERE FullName=@FullName)
		RETURN
	BEGIN TRANSACTION
	DECLARE @errorSum INT SET @errorSum=0  
	----获取要新增的往来单位的typeid
	declare @nReturntype int,@newTypeId [varchar](50),@nSoncount INT,@nSonnum INT,@XiwaMax INT
	exec @nReturntype=Gp_createId '00002','Btype',@newTypeId out,@nSonnum out,@nSoncount OUT
	SET @errorSum=@errorSum+@@error	
    UPDATE btype SET soncount=soncount+1,sonnum=sonnum+1 WHERE typeid='00002'
    SET @errorSum=@errorSum+@@error	
    SET @XiwaMax=(SELECT TOP 1 XiWaMaxNumber FROM dbo.btype ORDER BY XiWaMaxNumber DESC)
    SET @errorSum=@errorSum+@@error	
    SET @XiwaMax=@XiwaMax+1
    
   INSERT INTO dbo.btype
				 (typeId,
				  parid,
				  leveal,
				  soncount,
				  sonnum,
				  UserCode,
				  FullName,
				  Name,
				  CreateDate,
				  ARTotal,
				  APTotal,
				  ARTotal00,
				  APTotal00,
				  deleted,
				  Client,
				  ARLimitTime,
				  paymentLTime,
				  PyCode,
				  Price,
				  buyprice,
				  BackLimitDay,
				  BackPercent,
				  denominatedid,
				  XiWaMaxNumber)
    VALUES   (@newTypeId,'00002',2,0,0,@UserCode,@FullName,'',GETDATE(),0,0,0,0,0,1,9999,9999,@UserCode,0,0,0,0,@newTypeId,@XiwaMax)
	SET @errorSum=@errorSum+@@error	
	
	IF @errorSum<>0  --如果有错误
	  BEGIN
		DECLARE @ErrorInfo Nvarchar(200) 
		SET @ErrorInfo='下载物流公司【'+@FullName+'】失败'
		RAISERROR(@ErrorInfo,16,1)
		ROLLBACK TRANSACTION 
	  END  
	ELSE
	  BEGIN
		COMMIT TRANSACTION   
	  END
END 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/*------------------------------------------
    作者：佘海源
	日期：2012-11-27
	描述：店帐通单据表头处理

	修改者:董湛
	日期:2013-03-22
	描述：动态sql
	说明：店账通销售订单本地生成单据：1 销售出库单,往来单位为配置中的单位
										   2 买家运费生成其他收入单，往来单位为配置中的单位
										   3 卖家运费生成一般费用单，往来单位为物流公司（传参btypeid进来，是usercode）
										   4 商城扣费生成一般费用单，往来单位为配置中的单位
										   9 货到付款生成一般费用单，往来单位为配置中的单位
										   
										   5.销售退货单，往来单位同销售出库单
										   6.报损单,
						                   7.退货商城扣费生成其他收入单，往来单位同为配置中的单位
						                   8.运费结算单生成一般费用单，往来单位为物流公司(传参btypeid进来)
-------------------------------------------*/
IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_EshopBillDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_EshopBillDeal]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE Gp_EshopBillDeal
(
       @BillDate	DATETIME ,			---录单日期
       @BillCode	VARCHAR(50),		---单据编号  
       @FreightNo   VARCHAR(50),		---销售出库单运单号
       @VchCode		VARCHAR(50),		---店帐通单据ID   
       @BtypeId		VARCHAR(500),		---往来单位 
	   @BillType	NUMERIC(4,0),		---单据类型       
	   @Comment		NVARCHAR(1000),		---摘要
	   @Explain	    NVARCHAR(500),	    ---说明（传入的是店账通单据号）		
       @PtypeId		VARCHAR(200)='',	---商品ID
       @ETypeId		VARCHAR(200)='',	---经手人ID
       @KTypeId		VARCHAR(200)='',	---仓库ID
       @TotalMoney	 NUMERIC(24, 10) =0,	---总金额
       @TotalNMoney	 NUMERIC(24, 10) =0,	---实收金额
       @Qty			 NUMERIC(24, 10) =0,	---总数量
       @Checke		VARCHAR(50),		---制单人
       @EshopId		VARCHAR(200),
       @TradeId     VARCHAR(100),
       @Havecargo	BIT,				---货位
       @Flag	    INT					---区分单据(数字同说明里的数字)
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
   ----数据库存在这张单，不再生成
	IF EXISTS(SELECT TOP 1 1 FROM  dbo.BillIndex b JOIN eshopbillrelation e ON b.BillNumberId=e.billnumberid AND e.eshopbillid=@VchCode AND flag=@Flag)
		BEGIN
			SELECT -1 AS id
			RETURN
		END 
		
	DECLARE @ConfigCount INT
	SELECT @ConfigCount=COUNT(*) FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId
	IF @ConfigCount!=7 AND @Flag!=8      --每个网店7个配置项
		BEGIN
			SET @Explain='店账通单据【'+@Explain+'】所属网店未进行配置，请配置完成后再进行此操作。'
			RAISERROR(@Explain,16,1)
			RETURN
		END 
	IF @Flag=8   --运费结算单没有配置
		BEGIN
			--IF EXISTS(SELECT TOP 1 1 FROM dbo.EshopBaseInfo WHERE Field='FreightPayItem' AND (Value='' OR Value IS NULL))
			--	BEGIN
			--		RAISERROR('请先配置运费结算单的付款项',16,1)
			--		RETURN
			--	END
			IF EXISTS(SELECT TOP 1 1 FROM dbo.EshopBaseInfo WHERE Field='FreightFeeItem' AND (Value='' OR Value IS NULL))
				BEGIN
					RAISERROR('请先配置运费结算单的费用项',16,1)
					RETURN
				END
		END 
	IF @Flag=3 OR @Flag=4 OR @Flag=8 OR @Flag=9
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1)
				AND EXISTS(SELECT TOP 1 1 FROM dbo.EshopBaseInfo WHERE Field='FreightAtypeItem' AND (Value='' OR Value IS NULL))
				AND EXISTS (SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='aloneusebsys' AND SubValue='0')
				BEGIN
					RAISERROR('请先配置费用单的往来科目',16,1)
					RETURN
				END 
		END
	IF (@Flag=1 OR @Flag=5 OR @Flag=6) AND EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngcargospace' AND Value=1) AND @Havecargo=0
		BEGIN
			SET @Explain='系统启用了货位，店账通单据【'+@Explain+'】有商品未设置货位，请配置完成后再进行此操作。'
			RAISERROR(@Explain,16,1)
			RETURN
		END
	
	
	DECLARE @sql NVARCHAR(max)
	DECLARE @BillNumberId NUMERIC(18,0)	
	DECLARE @AtypeId	VARCHAR(50)
	DECLARE @ATYPEID1	VARCHAR(50)=''  --往来科目
	DECLARE @cid        INT
	
	SELECT @cid=CId FROM dbo.Ac_Currency WHERE Sysrow=1																							 
	DECLARE @StypeId VARCHAR(200)   SET @StypeId=(SELECT Value FROM dbo.EshopBaseInfo WHERE Field='StypeItem')     						--分支机构 V3为00001
	IF @StypeId=''
		BEGIN
			RAISERROR('请配置分支机构',16,1)
			RETURN
		END 
		
	DECLARE @DTypeId VARCHAR(200)																										--经手人部门
	IF @ETypeid='00001'																									--店账通单据可能是admin做                     
		 BEGIN
			SET @Explain='店账通单据【'+@Explain+'】经手人为管理员，请重新做单后再进行此操作。'
			RAISERROR(@Explain,16,1)
			RETURN
		END 
	ELSE IF @ETypeId=''
		BEGIN
			SET @Explain='店账通单据【'+@Explain+'】经手人为空，请新增经手人再进行此操作。'
			RAISERROR(@Explain,16,1)
			RETURN
		END
	ELSE 
		BEGIN
			 SET @DTypeId=(SELECT B.typeid  FROM employee A JOIN Department B ON A.Department = B.FullName WHERE A.typeId=@ETypeid)	
			 IF @DTypeId='' OR @DTypeId IS NULL
				BEGIN
					SET @Explain='店账通单据【'+@Explain+'】经手人不存在，请先到操作员里面新增该操作员。'
					RAISERROR(@Explain,16,1)
					RETURN
				END  
		END
		
	DECLARE @Period INT				SET @Period = (SELECT SubValue  FROM sysdata WHERE SubName='period' )								--业务期间
	DECLARE @FullName VARCHAR(100)  SET @FullName=(SELECT DISTINCT FullName  FROM ptype WHERE typeId=@ptypeid)							--商品名称
	
	IF @BillType=9             ---报损单
		BEGIN
			IF @FullName IS NULL
				BEGIN
					SET @Explain='店账通单据【'+@Explain+'】中的商品不存在，请确认后再进行此操作。'
					RAISERROR(@Explain,16,1)
					RETURN
				END
			--ELSE 
			--	SET @Comment = '【店账通】单据【'+@Explain+'】退换商品【'+@FullName+'】'
		END 
	
	SET @Comment = '【店账通】'+@Comment
	
	--替换单引号
    SET @Comment= REPLACE(@Comment,'''','''''')
	
	---以防摘要太长，截取字符串
	DECLARE @Comment1 VARCHAR(256)=@Comment
	 
	SET @Explain='店账通单据【'+@Explain+'】'
	
	--网店销售订单生成的单据都加上网店订单号
	IF @BillType=11 OR (@BillType=93 AND @Flag=2) OR (@BillType=36 AND @Flag!=8)
		SET @Explain=@Explain+';网店订单号【'+@TradeID+'】'
		
	IF @Flag=8 OR @Flag=3   OR @Flag=4 OR @Flag=9 ---物流结算
		BEGIN
			SET @ATYPEID1=(SELECT ISNULL(Value,'') FROM dbo.EshopBaseInfo WHERE Field='FreightAtypeItem')	 
			IF @Flag=8
				SET @Explain=@Explain+'物流结算'
		END
	ELSE IF @Flag=1  --销售出库单
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM BillAtype WHERE BillTypeId='11' AND StypeId=@StypeId AND AtypeId<>'')
				SET @ATYPEID1=(SELECT ISNULL(atypeid,' ') FROM BillAtype WHERE BillTypeId='11' AND StypeId=@StypeId  )
		END
	ELSE IF @Flag=2 OR @Flag=7  ---其他收入单
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM BillAtype WHERE BillTypeId='93' AND StypeId=@StypeId AND AtypeId<>'')
				SET @ATYPEID1=(SELECT ISNULL(atypeid,' ') FROM BillAtype WHERE BillTypeId='93' AND StypeId=@StypeId)
		END
	ELSE IF @Flag=5 --退货单 
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM BillAtype WHERE BillTypeId='45' AND StypeId=@StypeId AND AtypeId<>'')
				SET @ATYPEID1=(SELECT ISNULL(atypeid,' ') FROM BillAtype WHERE BillTypeId='45' AND StypeId=@StypeId)
		END
		
	BEGIN TRANSACTION
	DECLARE @errorSum INT SET @errorSum=0  
	SET @sql='
	INSERT INTO	BillIndex 
	( 
	  BillDate ,	--录单日期
	  BillCode ,	--单据编号
	  BillType ,	--单据类型
	  Comment ,		--摘要
	  atypeid,		--收款项目ID 现金（1）
	  atypeid1,		--往来科目
	  ptypeid ,		--商品ID
	  btypeid ,		--结算单位
	  DealBTypeID,  --往来单位
	  etypeid ,		--职员ID
	  ktypeid ,		--仓库ID
	  ifcheck ,		--是否过账 f：未过账,t：过账
	  checke ,		--制单人
	  cid,
	  rate,
	  totalmoney ,	--总金额
	  totalinmoney,	--收款金额
	  ntotalmoney ,	--总金额
	  ntotalinmoney,	--收款金额
	  totalqty ,	--数量
	  RedWord ,		--红冲 0
	  draft ,		--草稿标志 1
	  DTypeId ,		--经手人部门
	  Stypeid ,		--分支机构()
	  checkTime ,	--制单时间
	  explain,		--说明
	  period ,
	  Audit_explain,	--用于存储VchCode
	  tax,
	  Assessor,
	  waybillcode    --运单号
	) VALUES 
	(
	  '''+CAST(@BillDate AS VARCHAR(50))+''',
	  '''+@BillCode+''',
	  '+CAST(@BillType AS VARCHAR(50))+',
	  @Comment1, 
	  @Atype,
	   '''+@ATYPEID1+''',
	  @Ptypeid,
	  @Btypeid,
	  @Btypeid,
	  @ETypeid,
	  @Ktypeid,
	  ''f'',
	  '''+@Checke+''',
	  '''+CAST(@cid  AS VARCHAR(50))+''',
	  1,
	  @TotalMoney,
	  CASE WHEN @Atype IS NULL OR @Atype='''' THEN 0 ELSE  @TotalNMoney END,
	  @TotalMoney,
	  CASE WHEN @Atype IS NULL OR @Atype='''' THEN 0 ELSE  @TotalNMoney END,
	  @Qty,
	  0,
	  1,
	  '''+@DTypeId+''',
	  '''+@StypeId+''',
	  '''+CAST(GETDATE() AS VARCHAR(50))+''',
	  '''+@Explain+''',
	  '+CAST(@Period AS VARCHAR(50))+',
	  '''+@VchCode+''',
	  0,
	  ''dzt'',
	  @FreightNo
	)
	SELECT @BillNumberId=SCOPE_IDENTITY();	'
	
	--Double Check
	IF EXISTS(SELECT TOP 1 1 FROM  dbo.BillIndex b JOIN eshopbillrelation e ON b.BillNumberId=e.billnumberid AND e.eshopbillid=@VchCode AND flag=@Flag)
	BEGIN
			SELECT -1 AS id
			RETURN
	END 
	IF  @BillType=11 ---销售出库单 
		BEGIN 
			SET @AtypeId=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='IncomeItem')	
			SET @BtypeID=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='InOutBtype')
			EXEC sp_executesql @sql,N'@Atype VARCHAR(50),@Ptypeid VARCHAR(50),@Btypeid VARCHAR(50),@ETypeid VARCHAR(50),
								   @Ktypeid VARCHAR(50),@TotalMoney NUMERIC(18,4),@TotalNMoney NUMERIC(18,4),@Qty NUMERIC(18,4),@FreightNo VARCHAR(50),@Comment1 VARCHAR(256), @BillNumberId NUMERIC(18,0) out',
								   @AtypeId,@PtypeId,@BtypeID,@ETypeid,@KTypeId,@TotalNMoney,@TotalNMoney,@Qty,@FreightNo,@Comment1, @BillNumberId OUT
		END 
	ELSE IF @BillType=36  ---一般费用单(卖家运费成本/物流结算/商城模式/货到付款)
		BEGIN	
			 IF @Flag=3		   --卖家运费
				BEGIN
				    IF @BtypeId=''    --传进来的参数是空
						BEGIN
							SET @Explain=@Explain+'卖家运费成本生成的一般费用单在本地没有对应的往来单位，请先下载物流公司后再进行此操作'
							RAISERROR(@Explain,16,1)
							RETURN
						END 
					SET @BtypeId=(SELECT ISNULL(TypeId,'') FROM dbo.btype WHERE UserCode=@BtypeId)   
					IF @BtypeId='' OR @BtypeId IS NULL  --根据usercode查询没有对应的typeid
						BEGIN
							SET @Explain=@Explain+'卖家运费成本生成的一般费用单在本地没有对应的往来单位，请先下载物流公司后再进行此操作'
							RAISERROR(@Explain,16,1)
							RETURN
						END 
				END
			 ELSE IF @Flag=4 OR @Flag=9  --商城扣费/货到付款
				SET @BtypeId=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='MallBtype')
			 
			 IF @Flag=8 ----物流结算
				BEGIN
					SET @AtypeId=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='FreightPayItem')
					IF @AtypeId='' OR @AtypeId IS NULL
						BEGIN
							SET @Explain=@Explain+'生成的一般费用单未配置物流运费结算付款项，请先配置后再进行此操作'
							RAISERROR(@Explain,16,1)
							RETURN
						END
				END 
			 ELSE 
				 SET @AtypeId=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='FeeItem')
				 
				 PRINT @TotalMoney
				 PRINT @TotalNMoney
			 EXEC sp_executesql @sql,N'@Atype VARCHAR(50),@Ptypeid VARCHAR(50),@Btypeid VARCHAR(50),@ETypeid VARCHAR(50),
									   @Ktypeid VARCHAR(50),@TotalMoney NUMERIC(18,4),@TotalNMoney NUMERIC(18,4),@Qty NUMERIC(18,4),@FreightNo VARCHAR(50),@Comment1 VARCHAR(256), @BillNumberId NUMERIC(18,0) out',
									   @AtypeId,@PtypeId,@BtypeId,@ETypeId,'',@TotalMoney,@TotalNMoney,0,'',@Comment1, @BillNumberId out
		END
	ELSE IF @BillType=93  ---其他收入单(买家运费/退货商城扣费)
		 BEGIN
		 	IF @Flag=2     --买家运费
		 		SET @BtypeID=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='OtherBuyBtype')
		 	ELSE           --商城扣费
		 		SET @BtypeID=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='MallBtype')
		 	
		 	SET @AtypeId=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='IncomeItem')
		 	EXEC sp_executesql @sql,N'@Atype VARCHAR(50),@Ptypeid VARCHAR(50),@Btypeid VARCHAR(50),@ETypeid VARCHAR(50),
								   @Ktypeid VARCHAR(50),@TotalMoney NUMERIC(18,4),@TotalNMoney NUMERIC(18,4),@Qty NUMERIC(18,4),@FreightNo VARCHAR(50),@Comment1 VARCHAR(256), @BillNumberId NUMERIC(18,0) out',
								   @AtypeId,'',@BtypeID,@ETypeId,'',@TotalMoney,@TotalNMoney,0,'',@Comment1, @BillNumberId out
		 END
	ELSE IF @BillType=45  ---退货单
		BEGIN
			SET @AtypeId=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='FeeItem')	
			SET @BtypeID=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='InOutBtype')
			EXEC sp_executesql @sql,N'@Atype VARCHAR(50),@Ptypeid VARCHAR(50),@Btypeid VARCHAR(50),@ETypeid VARCHAR(50),
								   @Ktypeid VARCHAR(50),@TotalMoney NUMERIC(18,4),@TotalNMoney NUMERIC(18,4),@Qty NUMERIC(18,4),@FreightNo VARCHAR(50),@Comment1 VARCHAR(256), @BillNumberId NUMERIC(18,0) out',
								   @AtypeId,@Ptypeid,@BtypeID,@ETypeid,@KTypeid,@TotalNMoney,@TotalNMoney,@Qty,'',@Comment1, @BillNumberId  out
		END 
	ELSE IF @BillType=9    ---报损单
		 EXEC sp_executesql @sql,N'@Atype VARCHAR(50),@Ptypeid VARCHAR(50),@Btypeid VARCHAR(50),@ETypeid VARCHAR(50),
								   @Ktypeid VARCHAR(50),@TotalMoney NUMERIC(18,4),@TotalNMoney NUMERIC(18,4),@Qty NUMERIC(18,4),@FreightNo VARCHAR(50),@Comment1 VARCHAR(256), @BillNumberId NUMERIC(18,0) out',
								   '','','',@ETypeid,@KTypeid,0,0,@Qty,'',@Comment1, @BillNumberId  out
								   
	SET @errorSum=@errorSum+@@error			
	--将billnumberid的获取调整到@sql里面去了				   
	--SELECT @BillNumberId=SCOPE_IDENTITY();																----获取生成的id
	SET @errorSum=@errorSum+@@error	
	EXEC GP_SaveBillCode_Seed @BillNumberId,@BillDate,@BillType,@BillCode						----更新编号种子数
	SET @errorSum=@errorSum+@@error
	IF EXISTS(SELECT 1 FROM eshopbillrelation a inner join billindex b on a.billnumberid=b.billnumberid where eshopbillid=@VchCode AND flag=@Flag )
	BEGIN
		SET @errorSum=-1
	END	
	Delete eshopbillrelation where eshopbillid=@VchCode AND flag=@Flag                          ----删除关系对应
	SET @errorSum=@errorSum+@@error
	insert into eshopbillrelation select @VchCode,@BillNumberId,@Flag                           ----重新建立关系
	SET @errorSum=@errorSum+@@error
	---------------------------多账户收款插入（现金）------------
	IF @TotalNMoney <>0 AND @AtypeId IS NOT NULL AND @AtypeId<>''
	BEGIN
		IF @BillType=11           --出库单
			INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
								VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【店账通销售出库单】商品收款',-1,@TotalNMoney,@BillType)
		ELSE IF @BillType=45	  --退货单
			INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
								VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【店账通销售退货单】商品退款',-1,@TotalNMoney,@BillType)
		ELSE IF @BillType=36       --一般费用单
			begin
				if @flag=3
					INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
								VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【店账通一般费用单】卖家运费',-1,@TotalNMoney,@BillType)
				IF @flag=4
					INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
								VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【店账通一般费用单】商城扣费',-1,@TotalNMoney,@BillType)	
				IF @flag=8 
					INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
								VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【店账通一般费用单】运费结算',-1,@TotalNMoney,@BillType)				
				IF @flag=9 
					INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
								VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【店账通一般费用单】货到付款',-1,@TotalNMoney,@BillType)
			end 
		ELSE IF @BillType=93       --其他收入单
			IF @flag=2
				INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
								VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【店账通其他收入单】买家运费',-1,@TotalNMoney,@BillType)
			IF @flag=7
				INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
								VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【店账通其他收入单】物流运费结算',-1,@TotalNMoney,@BillType)
	END
	-----------------------------------------------------------------
	SET @errorSum=@errorSum+@@error
	
	SET @errorSum=@errorSum+@@error
	IF @errorSum<>0  --如果有错误
	  BEGIN
		DECLARE @ErrorInfo Nvarchar(200) 
		declare @BillName NVarchar(200)
		IF @Flag=1
			SET @BillName='生成本地销售出库单'
		ELSE IF @Flag=2
			SET @BillName='买家运费生成本地其他收入单'
		ELSE IF @Flag=3
			SET @BillName='卖家运费生成本地一般费用单'
		ELSE IF @Flag=4
			SET @BillName='商城扣费生成本地一般费用单'
		ELSE IF @Flag=9
			SET @BillName='货到付款服务费生成本地一般费用单'
		ELSE IF @Flag=5
			SET @BillName='生成本地销售退货单'
		ELSE IF @Flag=6
			SET @BillName='生成本地报损单'
		ELSE IF @Flag=7
			SET @BillName='商城扣费生成本地其他收入单'
		ELSE IF @Flag=8
			SET @BillName='生成本地一般费用单'
		SET @ErrorInfo=@Explain+@BillName+'失败，请检查订单信息后再试'
		RAISERROR(@ErrorInfo,16,1)
		ROLLBACK TRANSACTION 
		SELECT -1 AS id
	  END  
	ELSE
	  BEGIN
		COMMIT TRANSACTION   
		SELECT @BillNumberId AS id     --返回结果
	  END
	
END 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/*------------------------------------------
    作者：佘海源
	日期：2012-11-27
	描述：店帐通单据明细处理
	
	修改者:董湛
	日期:2013-03-22
	描述：动态sql
-------------------------------------------*/
IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_EshopBillDealDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_EshopBillDealDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE Gp_EshopBillDealDetail
(
		@BillDate		DATETIME,			---单据日期
		@BillType		NUMERIC(4,0),		---单据类型  
        @BillNumberId	NUMERIC(10,0),		---单据ID
		@PtypeId		VARCHAR(50)='',		---商品ID     
		@Qty			 NUMERIC(24, 10) =0,	---数量 
		@KTypeId		VARCHAR(50)='00001',---仓库ID    
		@Total			 NUMERIC(24, 10) =0,	---总价/实付金额
	    @Price			 NUMERIC(24, 10) =0,	---单价
		@FreightFee		 NUMERIC(24, 10) =0,	---物流费(卖家物流费)
		@Cargo			VARCHAR(max),		---货位
		@ItemID		    INT,				---自由项
		@Comment		VARCHAR(100)='',	---摘要     
		@EshopId		VARCHAR(200),		---网店id
		@Flag			INT
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	DECLARE @CargoID INT,@CargoCount INT=0,@tempCargoStr VARCHAR(max),@tempCargoIDQty  NUMERIC(24, 10) =0
	  --先默认一个货位id
    SELECT @CargoID=CargoID FROM dbo.CargoType WHERE KtypeID=@KTypeId AND IsDefault=1
	DECLARE @feeatypeid VARCHAR(100)		SET @feeatypeid=(SELECT ISNULL(Value,'') FROM  EshopBaseInfo WHERE Field='FYItem' AND EshopID=@EshopId)		----费用项-------
	DECLARE @incometypeid VARCHAR(100)		SET @incometypeid=(SELECT ISNULL(Value,'') FROM  EshopBaseInfo WHERE Field='SRItem' AND EshopID=@EshopId)	----收入项---------
    DECLARE @Stypeid	VARCHAR(50)			SET @Stypeid=(SELECT Value FROM dbo.EshopBaseInfo WHERE Field='StypeItem')
    
    --货位
    IF @Cargo<>''
		BEGIN
			CREATE TABLE #tempCargo
			(
				id   INT IDENTITY(1,1),
				cargostr    VARCHAR(100)
			)
			INSERT INTO #tempCargo
			SELECT a 
			FROM dbo.f_split(@Cargo,',')	
			
			SELECT @CargoCount=COUNT(*) FROM #tempCargo
		END
    
    --是否有自由项或组合项
    DECLARE @iscombined   INT=0 
    IF EXISTS(SELECT TOP 1 1 FROM dbo.ptype WHERE typeId=@PtypeId AND (customitemfrom=0 OR customitemfrom=1))
		 SELECT @iscombined=customitemfrom FROM  dbo.ptype WHERE typeId=@PtypeId   
	IF @ItemID=NULL
			SET @ItemID=0
		
	---商品信息
	DECLARE @entrycode VARCHAR(200)='',
	@UnitID INT,@MUnitID INT,@NUnitID INT,
	@MQty  NUMERIC(24, 10) ,@Mrate  NUMERIC(24, 10) ,@MSale  NUMERIC(24, 10) ,
	@Nrate  NUMERIC(24, 10) 
	,@EtypeId	VARCHAR(50)
	
	SELECT  @entrycode=EntryCode,@UnitID=baseUnitId,@MUnitID=SALEUNITID,@NUnitID=ASSISTANTUNITID 
	FROM dbo.ptype WHERE typeId=@PtypeId
	---销售换算率，数量,销售单价
	SELECT @Mrate=rate FROM PType_Units_Ext WHERE ptypeid=@PtypeId AND unitsid=@MUnitID
	SET @MQty=@Qty/@Mrate
	SET @MSale=@Price*@Mrate
	---浮动换算率
	SELECT @Nrate=rate FROM PType_Units_Ext WHERE ptypeid=@PtypeId AND unitsid=@NUnitID
	SELECT @EtypeId = etypeid	FROM BillIndex WHERE BillNumberId = @BillNumberId
	IF @BillType=11				----销售出库单明细
		BEGIN
			 IF @Cargo='' OR  @CargoCount=0  OR @CargoCount=1
				BEGIN
					IF @CargoCount=1 
						BEGIN
							SELECT @tempCargoStr=cargostr FROM #tempCargo
							SELECT @CargoID=c.cargoid FROM 
							(
								SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я')  
							) f JOIN CargoType c ON f.a=c.usercode
						END
					INSERT INTO	SaleBill
					( 
					  BillNumberId ,	--从表头获取
					  OutFactoryDate ,	--单据日期  
					  Stypeid ,			--分支机构
					  KTypeID ,			--仓库ID
					  CargoID ,			--货位
					  --序列号Serial
					  --批次GoodsOrder
					  --成本单价costprice
					  PtypeId ,			--商品ID
					  entryCode ,		--条形码
					  
					  Qty ,				--基本数量
					  SalePrice ,		--基本单价
					  UnitID	,		--基本单位
					  
					  MQty ,             --销售数量
					  MSalePrice,		--销售单价
					  MUnitID	,		--销售单位
					  MUnitRate,		--销售换算率
					  
					  NQty ,			--浮动数量
					  NUnitID	,		--浮动单位
					  UnitRate ,		--浮动换算率
					  
					  discount,			--折扣率
					  Tax	,			--税率
					  TaxMoney,			--税额
					  DiscountPrice ,	--折后单价，按基本单价算折后
					  MDiscountPrice,	--折后单价，按销售单价算折后
					  TaxPrice,			--含税价，按基本单价算
					  MTaxPrice,		--含税价，按销售单价算
					  
					  SaleTotal,		--总金额
					  total,			--折后总金额
					  TaxTotal,			--价税合计
					  
					  NSalePrice,       --原币基本单价
					  CurMSalePrice,	--原币销售单价
					  NTaxMoney,		--原币税额
					  NDiscountPrice,	--原币折后单价
					  CurMDiscountPrice,--原币折后单价
					  NTaxPrice,        --原币含税价
					  CurMTaxPrice,		--原币含税价
			         
					  NSaleTotal,
					  NTotal,
					  NTaxTotal,		  
					  comment,
					  IsCombined ,
					  ItemID ,
					  PriceSource,
					  ETypeID
					)
					VALUES
					( 
					  @BillNumberId,
					  @BillDate,        --单据日期
					  @Stypeid,         --分支机构
					  @KTypeId,			--仓库
					  @CargoID,			--货位
					  @PtypeId,			--商品
					  @entrycode,		--条形码
					  @Qty,             --基本数量
					  @Price,           --基本单价
					  @UnitID,			--基本单位
					  @MQty,			--销售数量
					  @MSale,           --销售单价
					  @MUnitID,			--销售单位
					  @Mrate,			--销售换算率
					  0,				--浮动数量
					  @NUnitID,			--浮动单位
					  0,			--浮动换算率@Nrate
					  1,				--折扣率
					  0,				--税率
					  0,				--税额
					  @Price,			--折后单价，按基本单价算
					  @MSale,			--折后单价，按销售单价算
					  @Price,			--含税价，按基本单价算
					  @MSale,			--含税价，按销售单价算
					  @Total,			--总金额
					  @Total,			--折后总金额
					  @Total,			--含税总金额
					  @Price,			--原币基本单价
					  @MSale,			--原币销售单价
					  0,				--原币税额
					  @Price,			--原币折后单价，按基本单价算折后
					  @MSale,			--原币折后单价，按销售单价算折后
					  @Price,			--原币含税价，按基本单价算
					  @MSale,			--原币含税价，按销售单价算
					  @Total,			--原币总金额
					  @Total,			--原币折后总金额
					  @Total,			--原币含税总金额
					  @Comment,
					  @iscombined,
					  @ItemID,
					  '店账通生成',
					  @EtypeId
					)
				END
					
			ELSE         ---遍历每个货位，分拆他们
				BEGIN
					 DECLARE @index INT=1,@tempTotal  NUMERIC(24, 10) 
					 WHILE @index<=@CargoCount
						BEGIN
							SELECT @tempCargoStr=cargostr FROM #tempCargo WHERE id=@index
							--SELECT TOP 1 @CargoID=CAST(a AS INT) FROM dbo.f_split(@tempCargoStr,'-') 
							SELECT @CargoID=c.cargoid FROM 
							(
								SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я')  
							) f JOIN CargoType c ON f.a=c.usercode
							
							SELECT @tempCargoIDQty=CAST(a AS  NUMERIC(24, 10) ) FROM dbo.f_split(@tempCargoStr,'я') 
							WHERE a NOT IN (SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я'))
							
							SET @MQty=@tempCargoIDQty/@Mrate
							SET @tempTotal=@Total*@tempCargoIDQty/@Qty 
							INSERT INTO	SaleBill
							( 
							  BillNumberId ,	--从表头获取
							  OutFactoryDate ,	--单据日期  
							  Stypeid ,			--分支机构
							  KTypeID ,			--仓库ID
							  CargoID ,			--货位
							  --序列号Serial
							  --批次GoodsOrder
							  --成本单价costprice
							  PtypeId ,			--商品ID
							  entryCode ,		--条形码
							  
							  Qty ,				--基本数量
							  SalePrice ,		--基本单价
							  UnitID	,		--基本单位
							  
							  MQty ,             --销售数量
							  MSalePrice,		--销售单价
							  MUnitID	,		--销售单位
							  MUnitRate,		--销售换算率
							  
							  NQty ,			--浮动数量
							  NUnitID	,		--浮动单位
							  UnitRate ,		--浮动换算率
							  
							  discount,			--折扣率
							  Tax	,			--税率
							  TaxMoney,			--税额
							  DiscountPrice ,	--折后单价，按基本单价算折后
							  MDiscountPrice,	--折后单价，按销售单价算折后
							  TaxPrice,			--含税价，按基本单价算
							  MTaxPrice,		--含税价，按销售单价算
							  
							  SaleTotal,		--总金额
							  total,			--折后总金额
							  TaxTotal,			--价税合计
							  
							  NSalePrice,       --原币基本单价
							  CurMSalePrice,	--原币销售单价
							  NTaxMoney,		--原币税额
							  NDiscountPrice,	--原币折后单价
							  CurMDiscountPrice,--原币折后单价
							  NTaxPrice,        --原币含税价
							  CurMTaxPrice,		--原币含税价
					         
							  NSaleTotal,
							  NTotal,
							  NTaxTotal,		  
							  comment,
							  IsCombined ,
							  ItemID ,
							  PriceSource,
							  ETypeID
							)
							VALUES
							( 
							  @BillNumberId,
							  @BillDate,        --单据日期
							  @Stypeid,         --分支机构
							  @KTypeId,			--仓库
							  @CargoID,			--货位
							  @PtypeId,			--商品
							  @entrycode,		--条形码
							  @tempCargoIDQty,  --基本数量
							  @Price,           --基本单价
							  @UnitID,			--基本单位
							  @MQty,			--销售数量
							  @MSale,           --销售单价
							  @MUnitID,			--销售单位
							  @Mrate,			--销售换算率
							  0,				--浮动数量
							  @NUnitID,			--浮动单位
							  0,			--浮动换算率@Nrate
							  1,				--折扣率
							  0,				--税率
							  0,				--税额
							  @Price,			--折后单价，按基本单价算
							  @MSale,			--折后单价，按销售单价算
							  @Price,			--含税价，按基本单价算
							  @MSale,			--含税价，按销售单价算
							  @tempTotal,			--总金额
							  @tempTotal,			--折后总金额
							  @tempTotal,			--含税总金额
							  @Price,			--原币基本单价
							  @Price,			--原币销售单价
							  0,				--原币税额
							  @Price,			--原币折后单价，按基本单价算折后
							  @MSale,			--原币折后单价，按销售单价算折后
							  @Price,			--原币含税价，按基本单价算
							  @MSale,			--原币含税价，按销售单价算
							  @tempTotal,			--原币总金额
							  @tempTotal,			--原币折后总金额
							  @tempTotal,			--原币含税总金额
							  @Comment,
							  @iscombined,
							  @ItemID,
							  '店账通生成',
							  @EtypeId
							)
							SET @index=@index+1
						END
				END
		END
	 ELSE IF @BillType=45		----销售退货单
		BEGIN
			IF @Cargo='' OR  @CargoCount=0  OR @CargoCount=1
				BEGIN
					IF @CargoCount=1 
						BEGIN
							SELECT @tempCargoStr=cargostr FROM #tempCargo
							SELECT @CargoID=c.cargoid FROM 
							(
								SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я')  
							) f JOIN CargoType c ON f.a=c.usercode
						END
					INSERT INTO	saleBackBill
					(  
					  BillNumberId,
					  OutFactoryDate ,	--date
					  Stypeid ,			--分支机构
					  KTypeID ,			--仓库ID
					  CargoID,
					  PtypeId ,
					  
					  Qty ,				--基本数量
					  SalePrice ,		--基本单价
					  UnitID	,		--基本单位
					  
					  MQty ,             --销售数量
					  MSalePrice,		--销售单价
					  MUnitID	,		--销售单位
					  MUnitRate,		--销售换算率
					  
					  NQty ,			--浮动数量
					  NUnitID	,		--浮动单位
					  UnitRate ,		--浮动换算率
					  
					  discount,			--折扣率
					  Tax	,			--税率
					  TaxMoney,			--税额
					  DiscountPrice ,	--折后单价，按基本单价算折后
					  MDiscountPrice,	--折后单价，按销售单价算折后
					  TaxPrice,			--含税价，按基本单价算
					  MTaxPrice,		--含税价，按销售单价算
					  
					  SaleTotal,		--总金额
					  total,			--折后总金额
					  TaxTotal,			--价税合计
					  
					  NSalePrice,       --原币基本单价
					  CurMSalePrice,	--原币销售单价
					  NTaxMoney,		--原币税额
					  NDiscountPrice,	--原币折后单价
					  CurMDiscountPrice,--原币折后单价
					  NTaxPrice,        --原币含税价
					  CurMTaxPrice,		--原币含税价
			         
					  NSaleTotal,
					  NTotal,
					  NTaxTotal,		  
					  IsCombined ,
					  ItemID  ,
					  ETypeID
					)
					VALUES 
					 (@BillNumberId,
					  @BillDate,
					  @Stypeid,         --分支机构
					  @KTypeId,			--仓库
					  @CargoID,			--货位
					  @PtypeId,			--商品
					  @Qty,             --基本数量
					  @Price,           --基本单价
					  @UnitID,			--基本单位
					  @MQty,			--销售数量
					  @MSale,           --销售单价
					  @MUnitID,			--销售单位
					  @Mrate,			--销售换算率
					  0,				--浮动数量
					  @NUnitID,			--浮动单位
					  0,				--浮动换算率@Nrate
					  1,				--折扣率
					  0,				--税率
					  0,				--税额
					  @Price,			--折后单价，按基本单价算
					  @MSale,			--折后单价，按销售单价算
					  @Price,			--含税价，按基本单价算
					  @MSale,			--含税价，按销售单价算
					  @Total,			--总金额
					  @Total,			--折后总金额
					  @Total,			--含税总金额
					  @Price,			--原币基本单价
					  @MSale,			--原币销售单价
					  0,				--原币税额
					  @Price,			--原币折后单价，按基本单价算折后
					  @MSale,			--原币折后单价，按销售单价算折后
					  @Price,			--原币含税价，按基本单价算
					  @MSale,			--原币含税价，按销售单价算
					  @Total,			--原币总金额
					  @Total,			--原币折后总金额
					  @Total,			--原币含税总金额
					  @iscombined,
					  @ItemID,
					  @EtypeId
					  )	
				END
			ELSE 
				BEGIN
					 DECLARE @index1 INT=1,@tempTotal1  NUMERIC(24, 10) 
					 WHILE @index1<=@CargoCount
						BEGIN
							SELECT @tempCargoStr=cargostr FROM #tempCargo WHERE id=@index1
							SELECT @CargoID=c.cargoid FROM 
							(
								SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я')  
							) f JOIN CargoType c ON f.a=c.usercode
							SELECT @tempCargoIDQty=CAST(a AS  NUMERIC(24, 10) ) FROM dbo.f_split(@tempCargoStr,'я') 
							WHERE a NOT IN (SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я'))
							SET @MQty=@tempCargoIDQty/@Mrate
							SET @tempTotal1=@Total*@tempCargoIDQty/@Qty 
							
							INSERT INTO	saleBackBill
							(  
							  BillNumberId,
							  OutFactoryDate ,	--date
							  Stypeid ,			--分支机构
							  KTypeID ,			--仓库ID
							  CargoID,
							  PtypeId ,
							  
							  Qty ,				--基本数量
							  SalePrice ,		--基本单价
							  UnitID	,		--基本单位
							  
							  MQty ,             --销售数量
							  MSalePrice,		--销售单价
							  MUnitID	,		--销售单位
							  MUnitRate,		--销售换算率
							  
							  NQty ,			--浮动数量
							  NUnitID	,		--浮动单位
							  UnitRate ,		--浮动换算率
							  
							  discount,			--折扣率
							  Tax	,			--税率
							  TaxMoney,			--税额
							  DiscountPrice ,	--折后单价，按基本单价算折后
							  MDiscountPrice,	--折后单价，按销售单价算折后
							  TaxPrice,			--含税价，按基本单价算
							  MTaxPrice,		--含税价，按销售单价算
							  
							  SaleTotal,		--总金额
							  total,			--折后总金额
							  TaxTotal,			--价税合计
							  
							  NSalePrice,       --原币基本单价
							  CurMSalePrice,	--原币销售单价
							  NTaxMoney,		--原币税额
							  NDiscountPrice,	--原币折后单价
							  CurMDiscountPrice,--原币折后单价
							  NTaxPrice,        --原币含税价
							  CurMTaxPrice,		--原币含税价
					         
							  NSaleTotal,
							  NTotal,
							  NTaxTotal,		  
							  IsCombined ,
							  ItemID  ,
							  ETypeID
							)
							VALUES 
							 (@BillNumberId,
							  @BillDate,
							  @Stypeid,         --分支机构
							  @KTypeId,			--仓库
							  @CargoID,			--货位
							  @PtypeId,			--商品
							  @tempCargoIDQty,  --基本数量
							  @Price,           --基本单价
							  @UnitID,			--基本单位
							  @MQty,			--销售数量
							  @MSale,           --销售单价
							  @MUnitID,			--销售单位
							  @Mrate,			--销售换算率
							  0,				--浮动数量
							  @NUnitID,			--浮动单位
							  0,				--浮动换算率@Nrate
							  1,				--折扣率
							  0,				--税率
							  0,				--税额
							  @Price,			--折后单价，按基本单价算
							  @MSale,			--折后单价，按销售单价算
							  @Price,			--含税价，按基本单价算
							  @MSale,			--含税价，按销售单价算
							  @tempTotal1,			--总金额
							  @tempTotal1,			--折后总金额
							  @tempTotal1,			--含税总金额
							  @Price,			--原币基本单价
							  @MSale,			--原币销售单价
							  0,				--原币税额
							  @Price,			--原币折后单价，按基本单价算折后
							  @MSale,			--原币折后单价，按销售单价算折后
							  @Price,			--原币含税价，按基本单价算
							  @MSale,			--原币含税价，按销售单价算
							  @tempTotal1,			--原币总金额
							  @tempTotal1,			--原币折后总金额
							  @tempTotal1,			--原币含税总金额
							  @iscombined,
							  @ItemID,
							  @EtypeId
							)	
							  SET @index1=@index1+1
						END
				END
		END
				
	  ELSE IF @BillType=9       ----------------报损单
		BEGIN
			IF @Cargo='' OR  @CargoCount=0  OR @CargoCount=1
				BEGIN
					IF @CargoCount=1 
						BEGIN
							SELECT @tempCargoStr=cargostr FROM #tempCargo
							SELECT @CargoID=c.cargoid FROM 
							(
								SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я')  
							) f JOIN CargoType c ON f.a=c.usercode
						END
					INSERT INTO dbo.LoseBill
					( 
						BillNumberId , 
						OutFactoryDate ,
						Stypeid,
						PtypeId , 
						CargoID,
						
						Qty,		--基本数量
						MQty,		--库存数量
						NQty,		--浮动数量
						UnitID,		--基本单位
						MUnitID,    --库存数量
						NUnitID,	--浮动数量
						UnitRate,
						MUnitRate,
						Price,
						Total,
						MPrice,
						InputCostPrice ,
						GoodsOrder , 
						GoodsCostPrice ,
						comment,
						IsCombined ,
						ItemID  
					)
					VALUES
					(
						@BillNumberId,
						@BillDate,
						@Stypeid,
						@PtypeId,
						@CargoID,			--货位
						@Qty,
						@MQty,
						0,
						@UnitID,
						@MUnitID,
						@NUnitID,
						0,--@Nrate,
						@Mrate,
						0,
						0,
						0,
						0,
						-1,
						-1,
						@comment,
						@iscombined,
						@ItemID
					)         --叫客户自己修改成本单价，总金额等
				END 
			ELSE 
				BEGIN
					DECLARE @index2 INT=1,@tempTotal2  NUMERIC(24, 10) 
					 WHILE @index2<=@CargoCount
						BEGIN
							SELECT @tempCargoStr=cargostr FROM #tempCargo WHERE id=@index2
							SELECT @CargoID=c.cargoid FROM 
							(
								SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я')  
							) f JOIN CargoType c ON f.a=c.usercode
							SELECT @tempCargoIDQty=CAST(a AS  NUMERIC(24, 10) ) FROM dbo.f_split(@tempCargoStr,'я') 
							WHERE a NOT IN (SELECT TOP 1 a FROM dbo.f_split(@tempCargoStr,'я'))
							SET @MQty=@tempCargoIDQty/@Mrate
							SET @tempTotal2=@Total*@tempCargoIDQty/@Qty 
							
							INSERT INTO dbo.LoseBill
							( 
								BillNumberId , 
								OutFactoryDate ,
								Stypeid,
								PtypeId , 
								CargoID,
								
								Qty,		--基本数量
								MQty,		--库存数量
								NQty,		--浮动数量
								UnitID,		--基本单位
								MUnitID,    --库存数量
								NUnitID,	--浮动数量
								UnitRate,
								MUnitRate,
								Price,
								Total,
								MPrice,
								InputCostPrice ,
								GoodsOrder , 
								GoodsCostPrice ,
								comment,
								IsCombined ,
								ItemID  
							)
							VALUES
							(
								@BillNumberId,
								@BillDate,
								@Stypeid,
								@PtypeId,
								@CargoID,			--货位
								@Qty,
								@MQty,
								0,
								@UnitID,
								@MUnitID,
								@NUnitID,
								0,--@Nrate,
								@Mrate,
								0,
								0,
								0,
								0,
								-1,
								-1,
								@comment,
								@iscombined,
								@ItemID
							)         --叫客户自己修改成本单价，总金额等
							SET @index2=@index2+1
						END 
				END
		END
					
	  ELSE 
			BEGIN 
				DECLARE @sql NVARCHAR(max)
				SET @sql='INSERT INTO MoneyBill
						 ( 
						  BillNumberId ,
						  AtypeId , 
						  total ,
						  ntotal ,
						  Comment,
						  Stypeid 
						 )
						VALUES('+CAST(@BillNumberId AS VARCHAR(50))+',@atypeid,@Total,@Total,'''+@Comment+''','''+@Stypeid+''' )'
				IF @BillType=36				
					BEGIN
						IF @Flag=3  --卖家运费
							EXEC sp_executesql @SQL,N'@atypeid VARCHAR(50),@Total  NUMERIC(24, 10) ',@feeatypeid,@FreightFee
						ELSE IF @Flag=8   --物流运费结算
							BEGIN	
								DECLARE @Freightid Varchar(50)
								SET @Freightid=(SELECT ISNULL(Value,'') FROM  EshopBaseInfo WHERE Field='FreightFeeItem')	
								EXEC sp_executesql @SQL,N'@atypeid VARCHAR(50),@Total  NUMERIC(24, 10) ',@Freightid,@FreightFee
							END 
						ELSE        ------商城扣费/货到付款
							EXEC sp_executesql @SQL,N'@atypeid VARCHAR(50),@Total  NUMERIC(24, 10) ',@feeatypeid,@Total
					END 
				ELSE IF  @BillType=93      ------收入单
							EXEC sp_executesql @SQL,N'@atypeid VARCHAR(50),@Total  NUMERIC(24, 10) ',@incometypeid,@Total
			END 
END 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


IF EXISTS ( SELECT  * FROM    dbo.sysobjects WHERE   id = OBJECT_ID(N'[dbo].[GP_ExactMatchInfoQuery]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ExactMatchInfoQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


--作者：duguolei-52ly
--功能：精确匹配信息查询，9.2版本加的功能
--时间：2013-07-18 HBD-LY

CREATE  PROCEDURE GP_ExactMatchInfoQuery
(
	@Flag				INT,			--匹配类型:1商品，2，往来单位。。。。
	@filter				VARCHAR(max),	--匹配关键字
	@OperatorId			VARCHAR(100),	--管理员id
	@verifyid			VARCHAR(50)='',	--辅助核算选择分支机构时使用
	@showStopk			VARCHAR(10)='1',		--是否显示停用的仓库 0不显示
	@isservice			INT = 1,             --是否显示服务商品
	@iscombination int = 1 --是否显示组合品			
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @OperatorId IS NULL 
    RETURN 1
DECLARE @intRe INT ,
    @chvMATypeID VARCHAR(50) ,
    @chvMBTypeID VARCHAR(50) ,
    @chvMBTypeID2 VARCHAR(50) ,
    @chvMETypeID VARCHAR(50) ,
    @chvMKTypeID VARCHAR(50) ,
    @chvMPTypeID VARCHAR(50) ,
    @chvMExpense VARCHAR(50) ,
    @chvMIncome VARCHAR(50) ,
    @chvMCapital VARCHAR(50) ,
    @chvMDtypeid VARCHAR(50) ,
    @chvMStypeid VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorId, @chvMATypeID OUTPUT,
    @chvMBTypeID OUTPUT, @chvMBTypeID2 OUTPUT, @chvMETypeID OUTPUT,
    @chvMKTypeID OUTPUT, @chvMPTypeID OUTPUT, @chvMExpense OUTPUT,
    @chvMIncome OUTPUT, @chvMCapital OUTPUT, @chvMDtypeid OUTPUT,
    @chvMStypeid OUTPUT
IF @intRe <> 0 
    RETURN @intRe
--------	权限检查 - End		--------


IF @Flag = 1			--商品
		BEGIN
			DECLARE @service VARCHAR(50)
			DECLARE @combination VARCHAR(50)
			IF @isservice = 1
				SET @service = '0,1'
			ELSE IF @isservice=0
			SET @service = '0'
		ELSE 	
			SET @service = '1'
			
			IF @iscombination = 1
			BEGIN
			    SET @combination = '0,1'
			END
			ELSE IF @iscombination = 0
			BEGIN
			   SET @combination = '0'
			END
			ELSE BEGIN
			   SET @combination = '1'
			END
			
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000')
				BEGIN
						SELECT typeId,FullName,UserCode 
						FROM PType 
						WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' )  AND SonNum = 0 AND TypeID <> '00000'
							   AND IsService IN (SELECT a from  f_split(@service,',')) AND IsService = 0 AND deleted = 0   
							  AND iscombinationproduct IN  (SELECT a from  f_split(@combination,','))
				END
			ELSE
				BEGIN
								SELECT	A.TypeId ,A.FullName,A.UserCode 
								FROM	PType_L L
										INNER JOIN PType  A ON A.TypeId LIKE L.TypeId + '%'
								WHERE	L.etypeid = ''+@OperatorId+''
										AND L.flag = 1 
										AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
										--AND A.Deleted = 0 
										AND A.SonNum = 0 
										AND A.TypeID <> '00000'
										AND IsService IN (SELECT a from  f_split(@service,','))
										AND A.IsService = 0 AND A.deleted = 0 
										AND iscombinationproduct IN  (SELECT a from  f_split(@combination,','))
				END					
		END
ELSE IF @Flag = 2		--往来单位
	BEGIN
		--客户,供货商
	 	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND (MangerBTypeID = '00001' AND MangerBTypeID2 = '00002'))
	 		BEGIN
				SELECT DISTINCT FullName,typeId,UserCode 
				FROM BType 
				WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND TypeID <> '00000'
	 		END
		ELSE
			BEGIN
							SELECT	DISTINCT A.FullName,A.TypeId ,A.UserCode  
							FROM	BType_L L
									INNER JOIN BType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
			END
	END
ELSE IF @Flag = 21		--客户
	BEGIN
	 	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerBTypeID = '00001' )
	 		BEGIN
				SELECT DISTINCT FullName,typeId,UserCode 
				FROM BType 
				WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
				AND typeId LIKE '00001%'
				AND Deleted = 0 
				AND SonNum = 0 
				AND TypeID <> '00000'
	 		END
		ELSE
			BEGIN
							SELECT	DISTINCT A.FullName,A.TypeId ,A.UserCode  
							FROM	BType_L L
									INNER JOIN BType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
									AND A.typeId LIKE '00001%'
			END
	END	
ELSE IF @Flag = 22		--供货商
	BEGIN
 		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId  AND MangerBTypeID2 = '00002')
 			BEGIN
				SELECT	DISTINCT FullName,typeId,UserCode 
				FROM	BType 
				WHERE	 (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
						AND Deleted = 0 
						AND SonNum = 0 
						AND TypeID <> '00000'
						AND typeId LIKE '00002%'
 			END
		ELSE
			BEGIN
							SELECT	DISTINCT A.FullName,A.TypeId ,A.UserCode  
							FROM	BType_L L
									INNER JOIN BType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND A.typeId LIKE '00002%'
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
									
			END
	END	
ELSE IF @Flag = 3		--职员
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeID = '00001')
			BEGIN
					SELECT typeId,FullName,UserCode  
					FROM Employee A
					WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND TypeID <> '00000'
			END		
		ELSE 
			BEGIN
					SELECT	A.TypeId ,A.FullName,A.UserCode  
					FROM	EType_L L INNER JOIN Employee  A ON A.TypeId LIKE L.TypeId + '%'
					WHERE	L.etypeid = ''+@OperatorId+''
							AND L.flag = 1 
							AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
							AND A.Deleted = 0 
							AND A.SonNum = 0 
							AND A.TypeID <> '00000' 
			END
	END						
ELSE IF @Flag = 4		--仓库
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerKTypeID = '00000')
			BEGIN
					SELECT typeId,FullName,UserCode  
					FROM Stock A 
					WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND SonNum = 0 AND TypeID <> '00000'
						 AND (@showStopk=1 OR (@showStopk=0 AND A.deleted=0) )
			END	
		ELSE
			BEGIN
					SELECT	A.TypeId ,A.FullName,A.UserCode 
					FROM	KType_L L INNER JOIN Stock  A ON A.TypeId LIKE L.TypeId + '%'
					WHERE	L.etypeid = ''+@OperatorId+''
							AND L.flag = 1 
							AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
							AND A.SonNum = 0 
							AND A.TypeID <> '00000'
							AND (@showStopk=1 OR (@showStopk=0 AND A.deleted=0) )
			END
	END
ELSE IF @Flag = 5		--现金银行
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '0000')
			BEGIN
					SELECT	nId AS typeid,UserCode,FullName
					FROM	Ac_Items A
					WHERE	TypeName='B'
							AND A.SonNum=0
							AND (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND nTypeId <> '00000'
							AND UserCode NOT IN('2181','2131','1151')
			END
		ELSE
			BEGIN
					SELECT	A.nId AS typeid,A.UserCode,A.FullName 
					FROM	Atype_L L
							INNER JOIN dbo.Ac_Items A  ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
					WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '-99999')
							AND l.etypeid=@OperatorId
							AND L.Type = '0'
							AND (a.nTypeId LIKE '0000100004%' OR a.nTypeId = '0000100003')
							AND (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 
							AND SonNum = 0 
							AND nTypeId <> '00000' 
							
			END	
	END
ELSE IF @Flag = 6		--费用
	BEGIN
		
		 SELECT A.nId AS typeid ,
                    A.UserCode ,
                    A.FullName
             FROM   dbo.F_AllTreeExpenseC(@OperatorId) a
             WHERE  ( UserCode = '' + @filter + ''
                      OR Fullname = '' + @filter + ''
                    )
                    AND A.SonNum = 0
                    AND Deleted = 0 
					
	END	
ELSE IF @Flag = 7		--收入
	BEGIN 
             SELECT A.nId AS typeid ,
                    A.UserCode ,
                    A.FullName
             FROM   dbo.F_AllTreeIncomeC(@OperatorId) a
             WHERE  ( UserCode = '' + @filter + ''
                      OR Fullname = '' + @filter + ''
                    )
                    AND A.SonNum = 0
                    AND Deleted = 0 
	END	
ELSE IF @Flag = 8		--资产
	BEGIN
		 SELECT  A.nId AS typeid ,
                A.UserCode ,
                A.FullName
        FROM    dbo.F_AllTreeAssetsT(@OperatorId) a
        WHERE   ( UserCode = '' + @filter + '' OR Fullname = '' + @filter + '')
                AND A.SonNum = 0
                AND Deleted = 0 
	END
ELSE IF @Flag = 9		--部门
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerDTypeID = '00000')
			BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode  
						FROM Department A
						WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND TypeID <> '00000'
			END
		ELSE
			BEGIN
							SELECT	A.TypeId ,A.FullName,A.UserCode   
							FROM	DType_L L
									INNER JOIN Department  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
							AND L.flag = 1 
							AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
							AND A.Deleted = 0 
							AND A.SonNum = 0 
							AND A.TypeID <> '00000'
			END
	END
ELSE IF @Flag = 10		--地区
	BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode  
						FROM	AreaType A
						WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
								AND Deleted = 0 
								AND SonNum = 0 
								AND TypeID <> '00000'
	END
ELSE IF @Flag = 11			--分支机构
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
			BEGIN
					SELECT	A.TypeId ,A.FullName,A.UserCode,PS.SFYear,PS.SFPeriod   
						FROM	SType A
						INNER JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=A.TypeId AND PS.SFYear<>0 AND PS.SFPeriod<>0
						WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
								AND Deleted = 0 
								AND SonNum = 0 
								AND TypeID <> '00000'
			END
		ELSE
			BEGIN
							SELECT	A.TypeId ,A.FullName,A.UserCode,PS.SFYear,PS.SFPeriod    
							FROM	SType_L L
							INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
							INNER JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=A.TypeId AND PS.SFYear<>0 AND PS.SFPeriod<>0
							WHERE	L.etypeid = ''+@OperatorId+''
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
			END
	END
ELSE IF @Flag = 30	AND @verifyid =''		--独立分支机构
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
			BEGIN
					SELECT	A.TypeId ,A.FullName,A.UserCode   
						FROM	SType A
						WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
								AND Deleted = 0 
								AND SonNum = 0 
								AND TypeID <> '00000'
								AND IsSelfVerify=1
			END
		ELSE
			BEGIN
							SELECT	A.TypeId ,A.FullName,A.UserCode    
							FROM	SType_L L
							INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
									AND A.IsSelfVerify=1
			END
	END
ELSE IF @Flag = 30	AND @verifyid <>''
	BEGIN
	
	    CREATE TABLE #SFType
	    (
				TypeId		VARCHAR(50),
				ParId		VARCHAR(50),
				SonNum		VARCHAR(10),
				UserCode	VARCHAR(200),
				FullName	VARCHAR(200),
				PyCode		VARCHAR(100),
				DELETED		VARCHAR(10)
	    )
	  
		--modify by dongzhan 2013.7.17 配置中新增“独立分支间只允许存在买卖关系”，sysdata下SubName='innerstypesaleralation'
        DECLARE @result VARCHAR(30)
        SELECT @result=SubValue FROM dbo.sysdata WHERE SubName='innerstypesaleralation'
        
        --判断权限范围
		IF @result='1'
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT f.TypeId,f.ParId,f.SonNum,f.UserCode,f.FullName,f.PyCode,f.Deleted FROM F_GetManSTypeAll(@OperatorId) f
					JOIN dbo.SType s ON  s.TypeId=f.TypeId AND s.VerifyID=@verifyid
				ELSE
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM SType WHERE VerifyID=@verifyid		
			END
		ELSE 
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM F_GetManSTypeAll(@OperatorId)
				ELSE
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM SType
			END

			SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE Deleted = 0 AND SonNum = 0 AND (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND TypeId <> '00000'  ORDER BY UserCode

		DROP TABLE #SFType			
        
	END
ELSE IF @Flag = 31			--辅助核算分支机构
	BEGIN
		IF @verifyid =''
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
				BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode   
							FROM	SType A
							WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
									AND Deleted = 0 
									AND SonNum = 0 
									AND TypeID <> '00000'
				END
			ELSE
				BEGIN
								SELECT	A.TypeId ,A.FullName,A.UserCode    
								FROM	SType_L L
								INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
								WHERE	L.etypeid = ''+@OperatorId+''
										AND L.flag = 1 
										AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
										AND A.Deleted = 0 
										AND A.SonNum = 0 
										AND A.TypeID <> '00000'
				END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
				BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode   
							FROM	SType A
							WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
									AND Deleted = 0 
									AND SonNum = 0 
									AND TypeID <> '00000'
									AND A.VerifyID = @verifyid
				END
			ELSE
				BEGIN
								SELECT	A.TypeId ,A.FullName,A.UserCode    
								FROM	SType_L L
								INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
								WHERE	L.etypeid = ''+@OperatorId+''
										AND L.flag = 1 
										AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
										AND A.Deleted = 0 
										AND A.SonNum = 0 
										AND A.TypeID <> '00000'
										AND A.VerifyID = @verifyid
				END
		END
	END
ELSE IF @Flag = 12			--车牌号
	BEGIN
						SELECT	A.TypeId ,A.PlateNumber     
						FROM	QP_RepairAutoInfo A
						WHERE	A.SonNum = 0
								AND (A.PYCode = '' + @filter + '' OR A.PlateNumber = '' + @filter +'' ) 
	END
ELSE IF @Flag = 13			--维修项目
	BEGIN
						SELECT A.TypeId ,A.FullName,A.UserCode
						FROM QP_RepairItems A
						WHERE A.SonNum = 0
							AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
							AND A.TypeID <> '00000'
	END			
ELSE IF @Flag = 14			--维修车型
	BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode
						FROM	QP_RepairAutoType A
						WHERE	 A.SonNum = 0
								AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
								AND A.TypeID <> '00000'	
	END
ELSE IF @Flag = 15			--凭证字
	BEGIN
						SELECT	VgId AS typeid ,FullName
						FROM	Ac_Voucher_Group A
						WHERE	A.Fullname = '' + @filter +'' 							
	END	
ELSE IF @Flag = 151			--凭证类型
	BEGIN
		CREATE TABLE #ResultTable 
		(
			Id INT NOT NULL,
			FullName VARCHAR(80) NOT NULL
		)
		INSERT INTO #ResultTable(Id,FullName)
		SELECT 0,'手工录入' UNION 
		SELECT 1,'期末调汇' UNION 
		SELECT 2,'结转损益' UNION 
		SELECT 3,'业务单据生成' UNION 
		SELECT 4,'固定资产系统生成' 

		SELECT A.id AS typeid ,A.FullName FROM #ResultTable A WHERE A.Fullname = '' + @filter +'' 
		DROP TABLE #ResultTable							
	END
ELSE IF @Flag = 16			--币别
	BEGIN
						SELECT	CId AS typeid,A.FullName,A.UserCode
						FROM	Ac_Currency A
						WHERE   (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
								AND A.Deleted = 0 			
	END		
ELSE IF @Flag = 17			--货位
	BEGIN
						SELECT	 CargoID AS typeid,A.FullName,A.UserCode
						FROM	 CargoType A
						WHERE	 (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
								AND A.Deleted = 0 				
	END
ELSE IF @Flag = 18			--总账会计科目
	BEGIN
						SELECT	DISTINCT A.TypeID ,A.FullName,A.UserCode
						FROM	Ac_Account A
						WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
								AND Deleted = 0 
								AND SonNum = 0 
								AND TypeID <> '00000'
	END		
ELSE IF @Flag = 19			--辅助核算类别
	BEGIN
		DECLARE @field VARCHAR(50)
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
			BEGIN
					SELECT  AscIds AS typeid, usercode, fullname
					FROM    Ac_Assist_CheckItems
					WHERE   (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
							AND UserCode <> '01'
			END
		ELSE
			BEGIN
				SELECT  AscIds AS typeid, usercode, fullname
					FROM    Ac_Assist_CheckItems
					WHERE   (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
			END		
	END
ELSE IF @Flag = 20			--商品自由项
	BEGIN
		 SELECT  A.itemid ,a.NAME,a.fullname
		 FROM
			 ( SELECT	 CASE WHEN IsCombined = 1 THEN 'C_' + CAST(T.id AS VARCHAR(10))
						 ELSE 'B_' + CAST(T.id AS VARCHAR(10))
						 END AS itemID ,
						( CASE WHEN t.IsCombined = 1 THEN '组合项' ELSE '基本项' END ) AS itemTypeName ,
						t.NAME ,
						t.iscombined ,
						t.fullname ,
						t.id
				FROM    (
						SELECT    1 AS IsCombined ,
									c2.fullname AS NAME ,
									REPLACE(c1.FullName, 'я', '/') AS FullName ,
									c1.id
						FROM		CustomReferenceValue c1
									INNER JOIN customPtypeItems c2 ON c1.itemsid = c2.id
						UNION ALL
						SELECT    0 AS IsCombined ,
								  s2.NAME AS NAME ,
								  s1.FullName ,
								  s1._Id AS id
						FROM      xw_SelfData s1
								  INNER JOIN xw_SelfDataType s2 ON s1.datatypeid = s2._id
						WHERE     ParTypeId <> 'root'
						 ) t
			) A
		WHERE (NAME = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
	END
ELSE IF @Flag = 23		-------会员卡号
	BEGIN
		CREATE TABLE #tmp
		(
			vipcardid INT
		)	
		INSERT INTO #tmp( vipcardid )
		SELECT DISTINCT nvs.VipCardId FROM dbo.VipCard_ApplyStype nvs
		INNER JOIN dbo.F_BaseGetAllManagerBaseTypeId(@verifyid,11,@operatorid) f ON f.TypeId = nvs.StypeId
		UNION ALL
		SELECT VipCardID FROM dbo.nVipCardSign WHERE isApplyAllStype = 1
		
		SELECT  s.vipcardid AS id ,
				s.vipcardcode AS fullname
		FROM    nVipCardSign s ,
				nVipCardSet n,
				#tmp t 
		WHERE   s.vipcardtypeid = n.vipcardtypeid
				AND t.vipcardid = s.VipCardID
				AND s.vipcardcode LIKE '%%'
				AND ( isCz = '1' OR iswashtimes = '1')
				AND   vipcardcode = '' + @filter +'' 
				
		DROP TABLE #tmp
	END
ELSE IF @Flag = 24		-------会员卡类型
	BEGIN
				SELECT  VipCardTypeID AS id,TypeName AS fullname
				FROM    nVipCardSet
				WHERE   deleted <> '1'
						AND TypeName = '' + @filter +'' 
	END
ELSE IF @Flag = 25	-------说明
	BEGIN
				SELECT 	[ID] AS typeid,
				UserCode,
				Content AS fullname
		FROM 	OftenExplain 
		WHERE 	(UserCode = '' + @filter + '' OR Content = '' + @filter +'' ) 

	END
ELSE IF @Flag = 33	-------常用承运单位
	BEGIN
				SELECT 	*
		FROM 	CarriageUnit 
		WHERE 	(fullname = '' + @filter + '' OR usercode = '' + @filter +'' ) 

	END
ELSE IF @Flag = 26	-------摘要
	BEGIN
				SELECT 	[ID] AS typeid,
				UserCode,
				Content,
				Content AS fullname
		FROM 	OftenComment
		WHERE 	(UserCode = '' + @filter + '' OR Content = '' + @filter +'' ) 
	END
ELSE IF @Flag = 27	-------固定资产卡片名称
	BEGIN
		SELECT 
			Id AS typeid,
			UserCode, 
			FullName
		FROM	Ac_AssetsCards 
		WHERE 	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
	END
ELSE IF @Flag = 28	-------固定资产卡片类别
	BEGIN
		SELECT 
			Id AS typeid,
			UserCode,
			FullName
		FROM	Ac_AssetsCategory 
		WHERE 	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
	END
ELSE IF @Flag = 29		--资产
	BEGIN
        SELECT  A.nId AS typeid ,
                A.UserCode ,
                A.FullName
        FROM    F_AllTreeExpenseC(@OperatorId) a
        WHERE   ( UserCode = '' + @filter + '' OR Fullname = '' + @filter + '')
                AND A.SonNum = 0
                AND Deleted = 0 
	END
ELSE IF @Flag = 32		--操作员
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeID = '00001')
			BEGIN
					SELECT typeId,FullName,UserCode  
					FROM Employee A INNER JOIN dbo.loginuser L ON L.etypeid = A.typeId
					WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND TypeID <> '00000'
			END		
		ELSE
			BEGIN
					SELECT	A.TypeId ,A.FullName,A.UserCode  
					FROM	EType_L L INNER JOIN Employee  A ON A.TypeId LIKE L.TypeId + '%'
							INNER JOIN dbo.loginuser lo ON lo.etypeid = A.typeId
					WHERE	L.etypeid = ''+@OperatorId+''
							AND L.flag = 1 
							AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
							AND A.Deleted = 0 
							AND A.SonNum = 0 
							AND A.TypeID <> '00000'
			END
	END						
ELSE IF @Flag = 35		--存款账户POS管辖账户使用
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '0000')
			BEGIN
					SELECT	A.nTypeId AS typeid,UserCode,FullName
					FROM	Ac_Items A
					WHERE	TypeName='B'
							AND A.SonNum=0
							AND (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND nTypeId <> '00000'
							AND UserCode NOT IN('2181','2131','1151') AND (a.nTypeId LIKE '0000100004%' )
			END
		ELSE
			BEGIN
					SELECT	A.nTypeId AS typeid,A.UserCode,A.FullName 
					FROM	Atype_L L
							INNER JOIN dbo.Ac_Items A  ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
					WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '-99999')
							AND l.etypeid=@OperatorId
							AND L.Type = '0'
							AND (a.nTypeId LIKE '0000100004%' )
							AND (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 
							AND SonNum = 0 
							AND nTypeId <> '00000' 
							
			END	
END 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


IF EXISTS ( SELECT  * FROM    dbo.sysobjects WHERE   id = OBJECT_ID(N'[dbo].[GP_ExactMatchInfoQueryByNewTC]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ExactMatchInfoQueryByNewTC]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


--作者：duguolei-52ly
--功能：精确匹配信息查询，9.2版本加的功能
--时间：2013-07-18 HBD-LY

CREATE  PROCEDURE GP_ExactMatchInfoQueryByNewTC
(
	@Flag				INT,			--匹配类型:1商品，2，往来单位。。。。
	@filter				VARCHAR(max),	--匹配关键字
	@OperatorId			VARCHAR(100),	--管理员id
	@verifyid			VARCHAR(50)='',	--辅助核算选择分支机构时使用
	@showStopk			VARCHAR(10)='1'		--是否显示停用的仓库 0不显示			
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @OperatorId IS NULL 
    RETURN 1
DECLARE @intRe INT ,
    @chvMATypeID VARCHAR(50) ,
    @chvMBTypeID VARCHAR(50) ,
    @chvMBTypeID2 VARCHAR(50) ,
    @chvMETypeID VARCHAR(50) ,
    @chvMKTypeID VARCHAR(50) ,
    @chvMPTypeID VARCHAR(50) ,
    @chvMExpense VARCHAR(50) ,
    @chvMIncome VARCHAR(50) ,
    @chvMCapital VARCHAR(50) ,
    @chvMDtypeid VARCHAR(50) ,
    @chvMStypeid VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorId, @chvMATypeID OUTPUT,
    @chvMBTypeID OUTPUT, @chvMBTypeID2 OUTPUT, @chvMETypeID OUTPUT,
    @chvMKTypeID OUTPUT, @chvMPTypeID OUTPUT, @chvMExpense OUTPUT,
    @chvMIncome OUTPUT, @chvMCapital OUTPUT, @chvMDtypeid OUTPUT,
    @chvMStypeid OUTPUT
IF @intRe <> 0 
    RETURN @intRe
--------	权限检查 - End		--------


IF @Flag = 1			--商品
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000')
				BEGIN
						SELECT typeId,FullName,UserCode ,parid,sonnum
						FROM PType 
						WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
						and Deleted = 0
				END
			ELSE
				BEGIN
								SELECT	A.TypeId ,A.FullName,A.UserCode ,A.parid,A.sonnum
								FROM	PType_L L
										INNER JOIN PType  A ON A.TypeId LIKE L.TypeId + '%'
								WHERE	L.etypeid = ''+@OperatorId+''
										AND L.flag = 1 
										AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
										and A.Deleted = 0
										
				END					
		END
		
IF @Flag = 99			--级别
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000')
				BEGIN
				        SELECT typeId,FullName,parid,sonnum
				        from
				        (
						SELECT typeId,CASE WHEN FullName='业务提成' THEN '全部级别' ELSE FullName END AS FullName,parid,sonnum
						FROM CommissionType 
						) A
						
						WHERE Fullname = '' + @filter +'' 
				END
			ELSE
				BEGIN
				 SELECT typeId,FullName,parid,sonnum
				        from
				        (
								SELECT	A.TypeId ,CASE WHEN A.FullName='业务提成' THEN '全部级别' ELSE A.FullName END AS FullName ,A.parid,A.sonnum
								FROM	CommissionType A
						) B
								WHERE
									 Fullname = '' + @filter +'' 
										
				END					
		END
		
		
ELSE IF @Flag = 2		--往来单位
	BEGIN
		--客户,供货商
	 	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND (MangerBTypeID = '00001' AND MangerBTypeID2 = '00002'))
	 		BEGIN
				SELECT DISTINCT FullName,typeId,UserCode 
				FROM BType 
				WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND TypeID <> '00000'
	 		END
		ELSE
			BEGIN
							SELECT	DISTINCT A.FullName,A.TypeId ,A.UserCode  
							FROM	BType_L L
									INNER JOIN BType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
			END
	END
ELSE IF @Flag = 21		--客户
	BEGIN
	 	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerBTypeID = '00001' )
	 		BEGIN
				SELECT DISTINCT FullName,typeId,UserCode 
				FROM BType 
				WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
				AND typeId LIKE '00001%'
				AND Deleted = 0 
				AND SonNum = 0 
				AND TypeID <> '00000'
	 		END
		ELSE
			BEGIN
							SELECT	DISTINCT A.FullName,A.TypeId ,A.UserCode  
							FROM	BType_L L
									INNER JOIN BType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
									AND A.typeId LIKE '00001%'
			END
	END	
ELSE IF @Flag = 22		--供货商
	BEGIN
 		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId  AND MangerBTypeID2 = '00002')
 			BEGIN
				SELECT	DISTINCT FullName,typeId,UserCode 
				FROM	BType 
				WHERE	 (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
						AND Deleted = 0 
						AND SonNum = 0 
						AND TypeID <> '00000'
						AND typeId LIKE '00002%'
 			END
		ELSE
			BEGIN
							SELECT	DISTINCT A.FullName,A.TypeId ,A.UserCode  
							FROM	BType_L L
									INNER JOIN BType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND A.typeId LIKE '00002%'
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
									
			END
	END	
ELSE IF @Flag = 3		--职员
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeID = '00001')
			BEGIN
			       select typeId,FullName,UserCode ,parid ,sonnum,dtypeid,dfullname
			       from(
					SELECT A.typeId,CASE WHEN A.FullName='root' THEN '全部提成人' ELSE A.FullName END AS FullName ,A.UserCode ,A.parid ,A.sonnum,td.fullname as dfullname,td.typeid as dtypeid
					FROM Employee A 
					INNER JOIN Employee te ON  te.typeid=A.TypeId
					LEFT  JOIN Department td ON td.typeid=te.dtypeid
					where  A.Deleted = 0
					) B
					WHERE UserCode = '' + @filter + '' OR Fullname = '' + @filter +''   
			END		
		ELSE
			BEGIN
			       select TypeId,FullName,UserCode,parid,sonnum,dtypeid,dfullname
			       from
			       (
					SELECT	A.TypeId ,CASE WHEN A.FullName='root' THEN '全部提成人' ELSE A.FullName END AS FullName ,A.UserCode ,A.parid ,A.sonnum,td.fullname as dfullname,td.typeid as dtypeid
					FROM	EType_L L INNER JOIN Employee  A ON A.TypeId LIKE L.TypeId + '%'
					INNER JOIN Employee te ON  te.typeid=A.TypeId
					LEFT  JOIN Department td ON td.typeid=te.dtypeid
					WHERE	L.etypeid = ''+@OperatorId+'' AND L.flag = 1 AND A.Deleted = 0 
					) C
					where 
					 UserCode = '' + @filter + '' OR Fullname = '' + @filter +''  
							
							
			END
	END						
ELSE IF @Flag = 4		--仓库
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerKTypeID = '00000')
			BEGIN
					SELECT typeId,FullName,UserCode  
					FROM Stock A 
					WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND TypeID <> '00000'
						 AND (@showStopk=1 OR (@showStopk=0 AND A.deleted=0) )
			END	
		ELSE
			BEGIN
					SELECT	A.TypeId ,A.FullName,A.UserCode 
					FROM	KType_L L INNER JOIN Stock  A ON A.TypeId LIKE L.TypeId + '%'
					WHERE	L.etypeid = ''+@OperatorId+''
							AND L.flag = 1 
							AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
							AND A.Deleted = 0 
							AND A.SonNum = 0 
							AND A.TypeID <> '00000'
							AND (@showStopk=1 OR (@showStopk=0 AND A.deleted=0) )
			END
	END
ELSE IF @Flag = 5		--现金银行
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '0000')
			BEGIN
					SELECT	nId AS typeid,UserCode,FullName
					FROM	Ac_Items A
					WHERE	TypeName='B'
							AND A.SonNum=0
							AND (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND nTypeId <> '00000'
							AND UserCode NOT IN('2181','2131','1151')
			END
		ELSE
			BEGIN
					SELECT	A.nId AS typeid,A.UserCode,A.FullName 
					FROM	Atype_L L
							INNER JOIN dbo.Ac_Items A  ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
					WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '-99999')
							AND l.etypeid=@OperatorId
							AND L.Type = '0'
							AND (a.nTypeId LIKE '0000100004%' OR a.nTypeId = '0000100003')
							AND (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 
							AND SonNum = 0 
							AND nTypeId <> '00000' 
							
			END	
	END
ELSE IF @Flag = 6		--费用
	BEGIN
		
		 SELECT A.nId AS typeid ,
                    A.UserCode ,
                    A.FullName
             FROM   dbo.F_AllTreeExpenseC(@OperatorId) a
             WHERE  ( UserCode = '' + @filter + ''
                      OR Fullname = '' + @filter + ''
                    )
                    AND A.SonNum = 0
                    AND Deleted = 0 
					
	END	
ELSE IF @Flag = 7		--收入
	BEGIN 
             SELECT A.nId AS typeid ,
                    A.UserCode ,
                    A.FullName
             FROM   dbo.F_AllTreeIncomeC(@OperatorId) a
             WHERE  ( UserCode = '' + @filter + ''
                      OR Fullname = '' + @filter + ''
                    )
                    AND A.SonNum = 0
                    AND Deleted = 0 
	END	
ELSE IF @Flag = 8		--资产
	BEGIN
		 SELECT  A.nId AS typeid ,
                A.UserCode ,
                A.FullName
        FROM    dbo.F_AllTreeAssetsT(@OperatorId) a
        WHERE   ( UserCode = '' + @filter + '' OR Fullname = '' + @filter + '')
                AND A.SonNum = 0
                AND Deleted = 0 
	END
ELSE IF @Flag = 9		--部门
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerDTypeID = '00000')
			BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode  
						FROM Department A
						WHERE (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND Deleted = 0 AND SonNum = 0 AND TypeID <> '00000'
			END
		ELSE
			BEGIN
							SELECT	A.TypeId ,A.FullName,A.UserCode   
							FROM	DType_L L
									INNER JOIN Department  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
							AND L.flag = 1 
							AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
							AND A.Deleted = 0 
							AND A.SonNum = 0 
							AND A.TypeID <> '00000'
			END
	END
ELSE IF @Flag = 10		--地区
	BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode  
						FROM	AreaType A
						WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
								AND Deleted = 0 
								AND SonNum = 0 
								AND TypeID <> '00000'
	END
ELSE IF @Flag = 11			--分支机构
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
			BEGIN
					SELECT	A.TypeId ,A.FullName,A.UserCode   
						FROM	SType A
						WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
								AND Deleted = 0 
								AND SonNum = 0 
								AND TypeID <> '00000'
			END
		ELSE
			BEGIN
							SELECT	A.TypeId ,A.FullName,A.UserCode    
							FROM	SType_L L
							INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
			END
	END
ELSE IF @Flag = 30	AND @verifyid =''		--独立分支机构
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
			BEGIN
					SELECT	A.TypeId ,A.FullName,A.UserCode   
						FROM	SType A
						WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
								AND Deleted = 0 
								AND SonNum = 0 
								AND TypeID <> '00000'
								AND IsSelfVerify=1
			END
		ELSE
			BEGIN
							SELECT	A.TypeId ,A.FullName,A.UserCode    
							FROM	SType_L L
							INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
							WHERE	L.etypeid = ''+@OperatorId+''
									AND L.flag = 1 
									AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
									AND A.Deleted = 0 
									AND A.SonNum = 0 
									AND A.TypeID <> '00000'
									AND A.IsSelfVerify=1
			END
	END
ELSE IF @Flag = 30	AND @verifyid <>''
	BEGIN
	
	    CREATE TABLE #SFType
	    (
				TypeId		VARCHAR(50),
				ParId		VARCHAR(50),
				SonNum		VARCHAR(10),
				UserCode	VARCHAR(200),
				FullName	VARCHAR(200),
				PyCode		VARCHAR(100),
				DELETED		VARCHAR(10)
	    )
	  
		--modify by dongzhan 2013.7.17 配置中新增“独立分支间只允许存在买卖关系”，sysdata下SubName='innerstypesaleralation'
        DECLARE @result VARCHAR(30)
        SELECT @result=SubValue FROM dbo.sysdata WHERE SubName='innerstypesaleralation'
        
        --判断权限范围
		IF @result='1'
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT f.TypeId,f.ParId,f.SonNum,f.UserCode,f.FullName,f.PyCode,f.Deleted FROM F_GetManSTypeAll(@OperatorId) f
					JOIN dbo.SType s ON  s.TypeId=f.TypeId AND s.VerifyID=@verifyid
				ELSE
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM SType WHERE VerifyID=@verifyid		
			END
		ELSE 
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM F_GetManSTypeAll(@OperatorId)
				ELSE
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM SType
			END

			SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE Deleted = 0 AND SonNum = 0 AND (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) AND TypeId <> '00000'  ORDER BY UserCode

		DROP TABLE #SFType			
        
	END
ELSE IF @Flag = 31			--辅助核算分支机构
	BEGIN
		IF @verifyid =''
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
				BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode   
							FROM	SType A
							WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
									AND Deleted = 0 
									AND SonNum = 0 
									AND TypeID <> '00000'
				END
			ELSE
				BEGIN
								SELECT	A.TypeId ,A.FullName,A.UserCode    
								FROM	SType_L L
								INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
								WHERE	L.etypeid = ''+@OperatorId+''
										AND L.flag = 1 
										AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
										AND A.Deleted = 0 
										AND A.SonNum = 0 
										AND A.TypeID <> '00000'
				END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000')
				BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode   
							FROM	SType A
							WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
									AND Deleted = 0 
									AND SonNum = 0 
									AND TypeID <> '00000'
									AND A.VerifyID = @verifyid
				END
			ELSE
				BEGIN
								SELECT	A.TypeId ,A.FullName,A.UserCode    
								FROM	SType_L L
								INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
								WHERE	L.etypeid = ''+@OperatorId+''
										AND L.flag = 1 
										AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
										AND A.Deleted = 0 
										AND A.SonNum = 0 
										AND A.TypeID <> '00000'
										AND A.VerifyID = @verifyid
				END
		END
	END
ELSE IF @Flag = 12			--车牌号
	BEGIN
						SELECT	A.TypeId ,A.PlateNumber     
						FROM	QP_RepairAutoInfo A
						WHERE	A.SonNum = 0
								AND (A.PYCode = '' + @filter + '' OR A.PlateNumber = '' + @filter +'' ) 
	END
ELSE IF @Flag = 13			--维修项目
	BEGIN
						SELECT A.TypeId ,A.FullName,A.UserCode
						FROM QP_RepairItems A
						WHERE A.SonNum = 0
							AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
							AND A.TypeID <> '00000'
	END			
ELSE IF @Flag = 14			--维修车型
	BEGIN
						SELECT	A.TypeId ,A.FullName,A.UserCode
						FROM	QP_RepairAutoType A
						WHERE	 A.SonNum = 0
								AND (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
								AND A.TypeID <> '00000'	
	END
ELSE IF @Flag = 15			--凭证字
	BEGIN
						SELECT	VgId AS typeid ,FullName
						FROM	Ac_Voucher_Group A
						WHERE	A.Fullname = '' + @filter +'' 							
	END	
ELSE IF @Flag = 151			--凭证类型
	BEGIN
		CREATE TABLE #ResultTable 
		(
			Id INT NOT NULL,
			FullName VARCHAR(80) NOT NULL
		)
		INSERT INTO #ResultTable(Id,FullName)
		SELECT 0,'手工录入' UNION 
		SELECT 1,'期末调汇' UNION 
		SELECT 2,'结转损益' UNION 
		SELECT 3,'业务单据生成' UNION 
		SELECT 4,'固定资产系统生成' 

		SELECT A.id AS typeid ,A.FullName FROM #ResultTable A WHERE A.Fullname = '' + @filter +'' 
		DROP TABLE #ResultTable							
	END
ELSE IF @Flag = 16			--币别
	BEGIN
						SELECT	CId AS typeid,A.FullName,A.UserCode
						FROM	Ac_Currency A
						WHERE   (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
								AND A.Deleted = 0 			
	END		
ELSE IF @Flag = 17			--货位
	BEGIN
						SELECT	 CargoID AS typeid,A.FullName,A.UserCode
						FROM	 CargoType A
						WHERE	 (A.UserCode = '' + @filter + '' OR A.Fullname = '' + @filter +'' ) 
								AND A.Deleted = 0 				
	END
ELSE IF @Flag = 18			--总账会计科目
	BEGIN
						SELECT	DISTINCT A.TypeID ,A.FullName,A.UserCode
						FROM	Ac_Account A
						WHERE	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
								AND Deleted = 0 
								AND SonNum = 0 
								AND TypeID <> '00000'
	END		
ELSE IF @Flag = 19			--辅助核算类别
	BEGIN
		DECLARE @field VARCHAR(50)
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
			BEGIN
					SELECT  AscIds AS typeid, usercode, fullname
					FROM    Ac_Assist_CheckItems
					WHERE   (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
							AND UserCode <> '01'
			END
		ELSE
			BEGIN
				SELECT  AscIds AS typeid, usercode, fullname
					FROM    Ac_Assist_CheckItems
					WHERE   (UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
			END		
	END
ELSE IF @Flag = 20			--商品自由项
	BEGIN
		 SELECT  A.itemid ,a.NAME,a.fullname
		 FROM
			 ( SELECT	 CASE WHEN IsCombined = 1 THEN 'C_' + CAST(T.id AS VARCHAR(10))
						 ELSE 'B_' + CAST(T.id AS VARCHAR(10))
						 END AS itemID ,
						( CASE WHEN t.IsCombined = 1 THEN '组合项' ELSE '基本项' END ) AS itemTypeName ,
						t.NAME ,
						t.iscombined ,
						t.fullname ,
						t.id
				FROM    (
						SELECT    1 AS IsCombined ,
									c2.fullname AS NAME ,
									REPLACE(c1.FullName, 'я', '/') AS FullName ,
									c1.id
						FROM		CustomReferenceValue c1
									INNER JOIN customPtypeItems c2 ON c1.itemsid = c2.id
						UNION ALL
						SELECT    0 AS IsCombined ,
								  s2.NAME AS NAME ,
								  s1.FullName ,
								  s1._Id AS id
						FROM      xw_SelfData s1
								  INNER JOIN xw_SelfDataType s2 ON s1.datatypeid = s2._id
						WHERE     ParTypeId <> 'root'
						 ) t
			) A
		WHERE (NAME = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
	END
ELSE IF @Flag = 23		-------会员卡号
	BEGIN
				SELECT  s.vipcardid AS id ,
						s.vipcardcode AS fullname
				FROM    nVipCardSign s ,
						nVipCardSet n
				WHERE   s.vipcardtypeid = n.vipcardtypeid
						AND s.vipcardcode LIKE '%%'
						AND ( isCz = '1' OR iswashtimes = '1')
						AND   vipcardcode = '' + @filter +'' 

	END
ELSE IF @Flag = 24		-------会员卡类型
	BEGIN
				SELECT  VipCardTypeID AS id,TypeName AS fullname
				FROM    nVipCardSet
				WHERE   deleted <> '1'
						AND TypeName = '' + @filter +'' 
	END
ELSE IF @Flag = 25	-------说明
	BEGIN
				SELECT 	[ID] AS typeid,
				UserCode,
				Content AS fullname
		FROM 	OftenExplain 
		WHERE 	(UserCode = '' + @filter + '' OR Content = '' + @filter +'' ) 

	END
ELSE IF @Flag = 26	-------摘要
	BEGIN
				SELECT 	[ID] AS typeid,
				UserCode,
				Content,
				Content AS fullname
		FROM 	OftenComment
		WHERE 	(UserCode = '' + @filter + '' OR Content = '' + @filter +'' ) 
	END
ELSE IF @Flag = 27	-------固定资产卡片名称
	BEGIN
		SELECT 
			Id AS typeid,
			UserCode, 
			FullName
		FROM	Ac_AssetsCards 
		WHERE 	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
	END
ELSE IF @Flag = 28	-------固定资产卡片类别
	BEGIN
		SELECT 
			Id AS typeid,
			UserCode,
			FullName
		FROM	Ac_AssetsCategory 
		WHERE 	(UserCode = '' + @filter + '' OR Fullname = '' + @filter +'' ) 
	END
ELSE IF @Flag = 29		--资产
	BEGIN
        SELECT  A.nId AS typeid ,
                A.UserCode ,
                A.FullName
        FROM    F_AllTreeExpenseC(@OperatorId) a
        WHERE   ( UserCode = '' + @filter + '' OR Fullname = '' + @filter + '')
                AND A.SonNum = 0
                AND Deleted = 0 
	END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	建立：刘飞
	日期：2018年8月7日 
	描述：单独修改选序列号
*/
CREATE           PROCEDURE GP_ExactMatchingSerial
(
	@OperatorID		varchar(50),
	@DBName			varchar(128),
	@UserCode		varchar(500) = '',
	@FullName		varchar(500) = '',
	@GridID			int, 				-- 销售换货单出入库区别标志
	@Condition		varchar(500),
	@BTypeTrack		varchar(500),		-- 往来单位名称
	@IfTrack		int,
	@chvBillType	varchar(50)	= '',	-- 单据类型
	@chvKTypeName	varchar(500) = '',	-- 仓库名称
	@chvCargoID		varchar(500),		--zs002：货位ID
	@useCargo		INT = 1,			--zs010: 是否启用货位 1：是   0：否
	@chvETypeName	varchar(500) = '',	-- 经手人名称
	@chvBillDate	varchar(100) = '',	-- 单据日期
	@chvDTypeName	varchar(500) = '',	-- 部门名称
	@wxproperty		int = 0,			-- 维修属性（erp5.0添加）
	@EntryCode		varchar(500) = '',	-- 配件条码(qp20 Wang Wei Add)
	@stid			VARCHAR(50)='00001',
	@cargoktypeid	VARCHAR(20),				--暂时不用了
	@cid			VARCHAR(50) = '0',
	@chvDenominated VARCHAR(500)='',		--zs003:结算单位id
	@chvDealBtypeID VARCHAR(500)='',		--zs003:往来单位id
	@mcid				VARCHAR(50)='',		--当前单据的币种
	@isservice          INT = 1,             --是否显示服务商品
	@chvitemid			    VARCHAR(100) = '',
	@chvcargoiddata		    VARCHAR(100) = '',
	@chviscombined		    VARCHAR(100) = '',
	@chvproducedate		VARCHAR(100) = '',
	@chvvaliddate		    VARCHAR(100) = '',
	@chvgoodsnumber		VARCHAR(100) = '',
	@chvcostprice       VARCHAR(100) = '',
	@existcombination	int =   0,
	@chvlendtosale      int	=   0     --是否勾选借出转销售：0未勾选，1勾选
)
--@encode$--
AS
SET NOCOUNT ON	-- 返回结果不受影响
IF @DBName IS NULL  RETURN 1
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @OperatorID
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------

DECLARE @cKtypeID varchar(50)

select @cKtypeID=typeid from stock where fullname= @chvKTypeName

IF @cKtypeID is null or @cKtypeID = ''
SET @cKtypeID='00001'

--没有分支机构，强行赋值默认分支机构
IF @stid=NULL OR @stid=''
	SET @stid='00001'

-- 系统配置采用价格跟踪
DECLARE @numSalePrice  NUMERIC(24, 10) , @numCostPrice  NUMERIC(24, 10) 	--#-01
SET @numSalePrice = 0
SET @numCostPrice = 0

--系统配置是否使用多编码
DECLARE @MultiCode varchar(1)
SET @MultiCode = '0'
SELECT TOP 1 @MultiCode = Value FROM UserConfig WHERE ConfigName = 'IfMultiCode'

-- 声明 SQL 语句变量
DECLARE @SQL varchar(MAX) 
SELECT @SQL = ''

--如果没有cid，unitid,则cid默认为本位币,unitid为商品默认单位
IF @cid = ''
	SELECT @mcid = cid FROM Ac_Currency WHERE Sysrow = 1
	
DECLARE @unittype VARCHAR(50) 
SELECT	@unittype = CASE WHEN @chvBillType IN (11,12,300,313,184,305,45,46,160,140,142,141,215,402) THEN 'SaleUnitId'		--销售单,销售订单,报价单等销售类单据
					     WHEN @chvBillType IN (34,301,185,6,161,144,145,146,400) THEN 'BuyUnitId'		--采购单,采购订单,询价单等采购类单据
						 WHEN @chvBillType IN(17,21,187,188,175,310,420) THEN 'StockUnitId'
					ELSE 'baseunitid' END 

IF not exists(select top 1 1 from CargoType c inner join STOCK s on s.typeId = c.KtypeID where c.CargoID=@chvCargoID and s.FullName=''+@chvKTypeName+'') and @chvCargoID !=''
	SELECT TOP 1 @chvCargoID = c.CargoID from STOCK k inner join CargoType c on k.typeId = c.KtypeID where c.IsDefault = 1 and k.FullName = ''+@chvKTypeName+''

declare @pricetracktype varchar(5)
select @pricetracktype=isnull(Value,1)-1   from Userconfig where ConfigName = 'pricetracktype'

DECLARE @SalePriceTrack varchar(50),@SaleOrderPriceTrack varchar(50),
		@BuyPriceTrack varchar(50),@BuyOrderPriceTrack varchar(50),@QueryPrice VARCHAR(50),@ResponsePrice VARCHAR(50),
		@BuyOrBackOriginalPrice varchar(100),
		@BuyOrBackDiscountRate varchar(100),
		@SaleOrBackOriginalPrice varchar(100),
		@SaleOrBackDiscountRate varchar(100),
		@DiscountTrack varchar(100),	
		@DiscountPriceTrack varchar(100),
		@PriceTrack varchar(100),
		@TaxTrack	varchar(100),
		@TaxPriceTrack	varchar(100),
		@TrackTableSql VARCHAR(MAX)		
		
		SET @SalePriceTrack = '0 AS SalePriceTrack'
		SET @SaleOrderPriceTrack = '0 AS SaleOrderPriceTrack'
		SET @BuyPriceTrack = '0 AS BuyPriceTrack'
		SET @BuyOrderPriceTrack = '0 AS BuyOrderPriceTrack'
		SET @QueryPrice = '0 AS QueryPrice'
		SET @ResponsePrice = '0 AS ResponsePrice'
		SET @BuyOrBackOriginalPrice = '0 AS BuyOrBackOriginalPrice'
		SET @BuyOrBackDiscountRate ='0 AS BuyOrBackDiscountRate'
		SET @SaleOrBackOriginalPrice ='0 AS SaleOrBackOriginalPrice'
		SET @SaleOrBackDiscountRate ='0 AS SaleOrBackDiscountRate'
		SET @DiscountTrack ='0 AS DiscountTrack'
		SET @DiscountPriceTrack ='0 AS DiscountPriceTrack'
		SET @PriceTrack ='0 AS PriceTrack'
		SET @TaxTrack='0 AS TaxTrack'
		SET @TaxPriceTrack='0 AS TaxPriceTrack'
		SET @TrackTableSql = ''


DECLARE @PriceType varchar(5)
SELECT @PriceType=PriceType FROM SType WHERE TypeId=@stid
IF @stid = '' OR @stid = null
SET @PriceType='0'
			
IF LEFT(@DBName, 6) = 'Serial'
BEGIN
	DECLARE @ifequal  INT		--序列号是否能精确匹配到，精确匹配到，则精确查询

	--2008-02-19 序列号关联货位
	DECLARE @serialrelation  INT		--序列号借欠出入库校验模式
	SELECT TOP 1 @serialrelation = VALUE FROM UserConfig WHERE ConfigName = 'serialrelation'

	--2008-02-19 徐辉添加序列号可以查询%
	SET @UserCode=REPLACE(@UserCode,'%','[%]')

	--2008-02-19 徐辉添加序列号可以查询%
	DECLARE @mngLendSerial  INT		--序列号借欠出入库校验模式
	SELECT TOP 1 @mngLendSerial = VALUE FROM UserConfig WHERE ConfigName = 'mngLendSerial'

	-- 确认仓库 ID 值 ( 参数通过 @FullName 来传递 )
	-- 若先选择了商品，则确认商品 ID 值 ( 参数通过 @DBName 传递，而 @DBName 最前面是 Serial )
	DECLARE @chvKTypeID varchar(50), @chvPTypeID varchar(50)
	DECLARE @szPtypeid varchar(50) --价格跟踪序列号所对应的商品ID 徐辉 2004-10-14
	SET @szPtypeid  = ''
	SET @chvKTypeID = ''
	SET @chvPTypeID = ''

	-- 非委托、受托代销结算
	IF @FullName <> 'CommissionWTJS' AND @FullName <> 'CommissionSTJS' AND  @FullName <> 'CommissionSTTH'
	BEGIN
		SELECT	TOP 1 @chvKTypeID = TypeID
		FROM (
		SELECT TypeID
		FROM	Stock
		WHERE	UserCode = @FullName
		UNION
		SELECT TypeID
		FROM	Stock
		WHERE	FullName = @FullName
			) AA
	END

	IF @FullName = 'CommissionSTTH'
	BEGIN
		SELECT	TOP 1 @chvKTypeID = TypeID
		FROM	Stock
		WHERE	UserCode = @chvKTypeName
			OR FullName = @chvKTypeName
	END

	IF RIGHT(@DBName, LEN(@DBName) - 6) <> ''
	BEGIN
		SELECT	TOP 1 @chvPTypeID = TypeID
		FROM	PType
		WHERE	UserCode = RIGHT(@DBName, LEN(@DBName) - 6)
	END

	-- 判断系统的成本算法；0：移动加权平均；1：先进先出；2：后进先出；3：手工指定法
	DECLARE @strCosting char(1)
	SELECT TOP 1 @strCosting = SubValue FROM SysData WHERE SubName = 'costing'
	
	IF @chvBillType='16'	-- 拆装出库
	BEGIN
		SET @SQL = '
					SELECT	a.*,
						   (select fullname from stock where typeid=a.Ktypeid ) as kfullname,
							b.*,
							
							'''' AS CustomerCode,
							f.unitid,
							f.unit,
							f.unitrate,
							f.nunitid,
							f.nunit,
							f.rate,
							f.buyunitname,
							f.buymunitrate,
							f.saleunitname,
							f.salemunitrate,
							f.stockunitname,
							f.stockmunitrate,
							(dbo.F_GetAllEntrycode(b.TypeID,b.SaleUnitId,2)) AS salemunitcode,
							(dbo.F_GetAllEntrycode(b.TypeID,b.BuyUnitId,2)) AS buymunitcode,
							(dbo.F_GetAllEntrycode(b.TypeID,b.StockUnitId,2)) AS stockmunitcode,
							(dbo.F_GetAllEntrycode(b.typeid,b.BaseUnitId,2)) AS basemunitcode,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname1,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname2,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname3,
							(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate1,
							(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate2,
							(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate3
					FROM (
						SELECT TOP 2 a.Serial,
									a.PTypeID,
									a.Ktypeid,
									itemid=a.ItemId,
									itemname= CASE WHEN a.IsCombined = 0  THEN
									(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
									ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
									iscombined=a.IsCombined,
									CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
									CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
									a.ProduceDate,
									a.ValidDate,
									a.goodsnumber as goodsnumber ,
									a.costprice
						FROM		GP_CruPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
						LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
						WHERE	a.State IN (1,7)
								AND a.KTypeID = ''' + @chvKTypeID + '''
								AND a.Serial LIKE ''%' + @UserCode + '%'''
				
					-- 子查询增加商品筛选，避免TOP时，取出不相干的数据，导致后面INNER JOIN不到
					IF RIGHT(@DBName, LEN(@DBName) - 6) <> ''
					BEGIN
						SET @SQL = @SQL + '
						AND a.PTypeID = ''' + @chvPTypeID + ''''
					END	
					
					SET @SQL = @SQL + '
					) a INNER JOIN PType b ON a.PTypeID = b.TypeID  and b.deleted=0
					LEFT JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = a.Ptypeid
					' + CASE WHEN @strCosting = '3' THEN '' ELSE 'LEFT JOIN (
						SELECT	g.PTypeID,
							CostPrice = SUM(g.Total) / CASE WHEN SUM(g.QTY) = 0 THEN NULL ELSE SUM(g.QTY) END
						FROM	GoodsStocks g, Stock s
						WHERE	g.KTypeID = s.TypeID
							AND (s.FullName = ''' + @chvKTypeName + ''' OR s.UserCode = ''' + @chvKTypeName + ''')
						GROUP BY g.PTypeID
					) g ON g.PTypeID = a.PTypeID '
	END
	
	SET @SQL=@SQL+' where 1=1 '
	--9.6新加 参数判断
	IF @chvitemid <> ''
	SET @SQL = @SQL + '
		AND a.ItemID = ''' + @chvitemid + ''''

	IF @chvcargoid <> ''
	SET @SQL = @SQL + '
		AND a.CargoID = ''' + @chvcargoid + ''''
		
	IF @chviscombined <> ''
	SET @SQL = @SQL + '
		AND a.IsCombined = ''' + @chviscombined + ''''
		
	IF @chvproducedate <> ''
	SET @SQL = @SQL + '
		AND a.ProduceDate = ''' + @chvproducedate + ''''
		
	IF @chvvaliddate <> ''
	SET @SQL = @SQL + '
		AND a.ValidDate  = ''' + @chvvaliddate + ''''

	IF @chvgoodsnumber <> ''
	SET @SQL = @SQL + '
		AND a.goodsnumber  = ''' + @chvgoodsnumber + ''''
		
	IF @chvcostprice <> ''
    SET @SQL = @SQL + '
	AND a.costprice  = ''' + @chvcostprice + ''''
	
	END
	ELSE
	BEGIN
		-- 获取往来单位 ID 值,仓库ID值(没用了),价格跟踪使用
		DECLARE @chvBTypeTrackID varchar(50)
		SET @chvBTypeTrackID = ''
		IF @BTypeTrack <> ''
		BEGIN
			SELECT	TOP 1 @chvBTypeTrackID = TypeID
			FROM	BType
			WHERE	UserCode = @BTypeTrack
				OR FullName = @BTypeTrack
		END

		-----------------------------------------往来单位适用价----------------------------------------------
		DECLARE @BtypePrice VARCHAR(50)
		SELECT	TOP 1 @BtypePrice = ISNULL(Price,'')
		FROM	BType 
		WHERE	FullName = @BTypeTrack
		IF @BtypePrice IS NULL SET @BtypePrice = ''

		-- 获取销售出库单、采购入库单价格跟踪配置
		DECLARE @chvPriceTrack varchar(1)
		SELECT	TOP 1 @chvPriceTrack = Value
		FROM	UserConfig
		WHERE	ConfigName = 'PriceTrack'

		--系统采用多编码
		DECLARE @IfMultiCodeBill int
		SET @IfMultiCodeBill = 0
		IF @MultiCode = '1' AND @chvBillType IN ('305','11','6','160','140','141','142','143','144','145','146','147','34','45','161','201','202','215','46')
			SET @IfMultiCodeBill = 1
		
	SET @SQL = '
	SELECT	TOP 2			
			a.*,	    
			(select fullname from stock where typeid=a.Ktypeid ) as kfullname,
			p.*,
			brandarfullname = (SELECT TOP 1 fullname FROM dbo.brandar_Commodity WHERE typeid = p.brandartypeid),
			''' + @BtypePrice+''' AS BtypePrice,
			PromotePrice = 0,
			f.unitid,
			f.unit,
			f.unitrate,
			f.nunitid,
			f.nunit,
			f.rate,
			f.buyunitname,
			f.buymunitrate,
			f.saleunitname,
			f.salemunitrate,
			f.stockunitname,
			f.stockmunitrate,
			(dbo.F_GetAllEntrycode(p.TypeID,p.SaleUnitId,2)) AS salemunitcode,
			(dbo.F_GetAllEntrycode(p.TypeID,p.BuyUnitId,2)) AS buymunitcode,
			(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
			(' + CASE WHEN @IfMultiCodeBill = 1 THEN 'SELECT TOP 1 UserCode FROM PUserCode WHERE PTypeID=a.PTypeID AND BTypeID='''+ @chvBTypeTrackID + '''' ELSE '''''' END + ') AS CustomerCode
	FROM (
		SELECT	TOP 100 PERCENT  
				a.Serial,
				a.PTypeID,
				a.Ktypeid,
				(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname1,
				(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname2,
				(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname3,
				(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate1,
				(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate2,
				(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate3
				--,CASE WHEN a.Serial = ''' + @UserCode + ''' THEN 0 ELSE 1 END AS ShowOrder'
				
				IF @chvBillType = '87'
				SET @SQL = @SQL + '
				,a.ItemId
				,a.itemname
				,a.iscombined
				,a.CargoID
				,a.cargofullname
				,a.ProduceDate
				,a.ValidDate
				,a.costprice
				,a.goodsnumber
				'
        
		IF @chvBillType = '72'	-- 借进还出 Roamer Wu 2004-03-02 加入借欠返回的控制
			SET @SQL = @SQL + '
				,itemid=a.ItemId,
				itemname= CASE WHEN a.IsCombined = 0  THEN
				(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
				iscombined=a.IsCombined,
				
				CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
				CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
				a.ProduceDate,
				a.ValidDate,
				a.goodsnumber ,
				null as costprice
		FROM	GP_LendPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.Serial LIKE ''%' + @UserCode + '%''
				AND a.BTypeID2 = ''' + CASE WHEN @chvDealBtypeID IS NOT NULL AND LEN(@chvDealBtypeID)>0 THEN @chvDealBtypeID ELSE @chvBTypeTrackID END + '''
				AND a.State IN (17,20)
				AND a.Flag = 1
				AND a.BFlag = 1'
		ELSE IF @chvBillType = '88'	-- 借出还回
			SET @SQL = @SQL + '
				,itemid=a.ItemId,
				itemname= CASE WHEN a.IsCombined = 0  THEN
				(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
				iscombined=a.IsCombined,

				a.CargoID,
				a.ProduceDate,
				a.ValidDate,
				ct.fullname AS cargofullname,
				a.goodsnumber,
				null as costprice
		FROM	GP_LendPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.Serial LIKE ''%' + @UserCode + '%''
				AND a.State = 18
				AND a.BTypeID1 = ''' + CASE WHEN @chvDealBtypeID IS NOT NULL AND LEN(@chvDealBtypeID)>0 THEN @chvDealBtypeID ELSE @chvBTypeTrackID END + '''
				AND a.Flag = 0'
		ELSE IF @chvBillType = '87'	-- 借出开单
		BEGIN
			SET @SQL = @SQL + '
		FROM (
			SELECT	a.Serial,
					a.PTypeID,
					a.KTypeID,
					itemid=a.ItemId,
					itemname= CASE WHEN a.IsCombined = 0  THEN
					(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
					iscombined=a.IsCombined,
					CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
					CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
					a.ProduceDate,
					a.ValidDate,
					a.goodsnumber as goodsnumber,
					a.costprice
			FROM	GP_CruPTypeSerial a
			LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
			WHERE	a.Serial LIKE ''%' + @UserCode + '%''
				AND a.State IN (1,7)
				AND a.KTypeID = ''' + @chvKTypeID + '''
				--v5.0  徐辉，借出的不能再借了
				AND a.Serial NOT IN (SELECT Serial FROM GP_LendPTypeSerial WHERE Flag = 0 AND State = 18)
		) a
		WHERE	a.Serial LIKE ''%' + @UserCode + '%'''
		END
		ELSE IF @chvBillType IN ('419','420')	-- 实物库存
			BEGIN
			  SET  @SQL = @SQL + ' 
						,XFullName,GFullName,
						itemid,itemname,
						iscombined,
						a.cargoid,
						producedate,
						validdate,cargofullname,goodsnumber,costprice  from (select 
						a.Serial,
						a.PTypeID,
						a.KTypeID,
						(SELECT FullName FROM stock WHERE SonNum=0 AND TypeID = A.Ktypeid) as Kfullname,
						(select BuyDefaultRate from ptype where typeid=a.PTypeID) as BuyDefaultRate,
						(select SaleDefaultRate from ptype where typeid=a.PTypeID) as SaleDefaultRate,
						a.InKtypeTime,
						a.OutKtypeTime,
						null as Note,
						a.State,
						null as BTypeID1,
						null as  BTypeID2,
						null as XFullName,
						null as GFullName,
						itemid,
						itemname =  CASE WHEN a.IsCombined = 0  THEN
							(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
							ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId )  END,
						iscombined,
						a.cargoid,
						producedate,
						validdate,
						ct.fullname AS cargofullname,
						goodsnumber,
						null as costprice,a.Flag
				from dbo.gp_FactPtypeSerial a
				LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
			    WHERE a.Serial LIKE ''%' + @UserCode + '%'' 
			) a'
			END
		ELSE
		BEGIN
			--先精确匹配
			SELECT @ifequal=1 FROM dbo.gp_CruPtypeSerial WHERE Serial=@UserCode AND Flag = 1
			-- 判断系统序列号关联货位等信息；
			DECLARE @strSerialrelation char(1)
			SELECT @strSerialrelation = Value FROM UserConfig WHERE ConfigName = 'serialrelation'

			SET @SQL = @SQL + '
			   ,itemid=a.ItemId,
				itemname= CASE WHEN a.IsCombined = 0  THEN
				(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
				iscombined=a.IsCombined,
				CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
			    CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
				a.ProduceDate,
				a.ValidDate,
				a.goodsnumber as goodsnumber,
				'+
				CASE WHEN @strCosting=3 AND @strSerialrelation=1
				THEN 'a.costprice'
				ELSE
					CASE WHEN @chvBillType = '17' THEN '(SELECT TOP 1 SUM(Price*Qty)/SUM(Qty) FROM dbo.GoodsStocks 
							WHERE PtypeId=a.PtypeId AND KtypeId=a.KTypeID
							GROUP BY PtypeId,KtypeId) AS costprice'
					ELSE
						'a.costprice'
					END
				END
				+'
		FROM	GP_CruPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID '
		
		IF @ifequal = 1
		BEGIN
			SET @SQL = @SQL + ' WHERE a.Serial = ''' + @UserCode + ''''
		END
		ELSE
		BEGIN
			SET @SQL = @SQL + ' WHERE CHARINDEX('''+@UserCode+''',a.Serial) > 0 '
		END
		/* 991调整算法，不要用LIKE，无法走索引 谢吉康 2020-1-3
		WHERE	a.Serial'+
			--如果精确匹配到,则精确匹配
			CASE 
				WHEN @ifequal=1 THEN '=''' + @UserCode + ''''
				ELSE ' LIKE ''%' + @UserCode + '%'''
			END '
		*/
			
			IF @chvBillType = '413' 
			BEGIN
				SET @SQL = @SQL+'AND a.State IN (2,3,9,11,13,14,15,30,21,31)'
			END
			ELSE IF @chvBillType = '412' 
			BEGIN
				SET @SQL = @SQL+'AND a.State IN (1,7,40)'
			END
			ELSE IF @chvBillType = '45' OR @chvBillType = '46' OR @chvBillType = '215' OR @chvBillType = '403' OR (@chvBillType = '160' AND @GridID = 2)	-- 销售退货单
			BEGIN
				SET @SQL = @SQL + '
				AND a.State IN (2,9,14,21)'	-- 销售退货单只查询已销售序列号,受托代销已销售 徐辉2005-01-15
				
				IF @chvBillType = '215'
				BEGIN
					SET @SQL = @SQL + '
					AND a.Serial IN (SELECT Serial FROM gp_inoutPtypeSerial WHERE (BillType=11 OR BillType=402 OR BillType=305) and ptypeid=a.PTypeID and ifcheck=''t'' 
					and BTypeID1=a.BTypeID1)'
				END
				
				/*
				--销售退货单也要看到销售换货单出库的序列号 991屏蔽，扫描的时候无需判断，等过账判断 2020-1-3 谢吉康
				IF @chvBillType = '160' OR @chvBillType = '45' OR @chvBillType = '46'
				BEGIN
					SET @SQL = @SQL + '
					AND a.Serial IN (
										SELECT	Serial 
										FROM	gp_inoutPtypeSerial 
										WHERE	(BillType=160 OR BillType=305 OR BillType=402 OR BillType=11) 
												and ptypeid=a.PTypeID 
												and ifcheck=''t'' 
												and BTypeID1=a.BTypeID1
									)'
				END
				*/
			
			END
			ElSE IF @chvBillType = '6' OR  @chvBillType = 401		-- 采购退货不能选受托代销入库的商品
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 1 AND a.Flag = 1'
			ELSE IF @chvBillType = '166' OR @chvBillType = '168' OR @chvBillType = '172'	-- 维修单、整机更换单、上门维修单
			BEGIN
				IF @wxproperty = 0	-- 正常商品
					SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 1 AND a.Flag = 1'
				ELSE	-- 维修品
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 25 AND a.Flag = 1'
			END
			ELSE IF @chvBillType = '167' OR @chvBillType = '169'	-- 维修取件单、送修单
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 25
			AND a.Flag = 1'
			ELSE IF @chvBillType = '170'	-- 送修返回单
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 29 AND a.Flag = 0'
			ELSE if  @chvBillType = '202'  --其他出库单
			SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State =1  AND a.Flag = 1'
			ELSE IF @chvBillType = '175' OR @chvBillType = '174'	-- 维修品调拨单、维修品调出单
			BEGIN
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 25 AND a.Flag = 1'
			END
			ELSE IF @chvBillType = '173'	-- 维修品调入单
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 1 AND a.Flag = 1'
			ELSE IF @chvBillType='187' --OR @chvBillType='140' --分支机构调拨出库单
			BEGIN
				SET @SQL = @SQL + '
					AND a.KTypeID = ''' + @chvKTypeID + '''
					AND	a.State = 1
					AND a.Flag = 1'
			END
			ELSE IF @chvBillType = '9'	-- 报损单（报损维维修品）
			BEGIN
				IF @wxproperty = 0	-- 正常商品
					SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State IN (1,7)
			AND a.Flag = 1'
				ELSE	-- 维修品
					SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 25 AND a.Flag = 1'
			END						
			ElSE IF @chvBillType <> '46' AND @chvBillType <> '45' AND @chvBillType <> '6' AND @chvBillType <> '142' AND @FullName <> 'CommissionWTJS' AND @FullName <> 'CommissionSTJS' AND @FullName <> 'CommissionSTTH' AND @FullName <> 'CommissionWTTH'
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State IN (1,7,40) AND a.Flag = 1'
			ELSE IF @FullName = 'CommissionWTJS' OR @FullName = 'CommissionWTTH' OR @chvBillType = '142'
				SET @SQL = @SQL + '
			AND a.BTypeID1 = ''' + @chvBTypeTrackID + '''
			AND (a.Ktypeid IN (SELECT TypeId FROM Stock WHERE stypeid=''' + @stid + ''') OR (a.ktypeid=''10000'' AND  stypeid='''+@stid +'''))
			AND a.State IN (13,32)'
			ELSE IF @FullName = 'CommissionSTJS'
				SET @SQL = @SQL + '
			AND a.BTypeID2 = ''' + @chvBTypeTrackID + '''
			AND a.State IN (7,9,10,11,13,14,16,22,23,31,32)
			AND (a.Ktypeid IN (SELECT TypeId FROM Stock WHERE stypeid=''' + @stid + ''') OR (a.ktypeid=''10000'' AND  stypeid='''+@stid+''') )
			AND a.CommissionState = 0'
			ELSE IF @FullName = 'CommissionSTTH'
				SET @SQL = @SQL + '
			AND a.BTypeID2 = ''' + @chvBTypeTrackID + '''
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State IN (7) '
		END
		
		SET @SQL = @SQL + '
	) a INNER JOIN PType p ON a.PTypeID = p.TypeID  and p.deleted=0
	LEFT JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = a.Ptypeid
	LEFT JOIN gp_LendPtypeSerial LPS ON a.Serial=LPS.Serial 
	WHERE	1=1 '
	END
	
	-- 商品编号不为空
	IF RIGHT(@DBName, LEN(@DBName) - 6) <> ''
		SET @SQL = @SQL + '
		AND a.PTypeID = ''' + @chvPTypeID + ''''
	
    IF LEFT(@DBName, 6) = 'Serial'
    BEGIN
		--9.6新加 参数判断
		IF @chvitemid <> ''
		SET @SQL = @SQL + '
			AND a.ItemID = ''' + @chvitemid + ''''

		IF @chvcargoid <> ''
		SET @SQL = @SQL + '
			AND a.CargoID = ''' + @chvcargoid + ''''
			
		IF @chviscombined <> ''
		SET @SQL = @SQL + '
			AND a.IsCombined = ''' + @chviscombined + ''''
			
		IF @chvproducedate <> ''
		SET @SQL = @SQL + '
			AND a.ProduceDate = ''' + @chvproducedate + ''''
			
		IF @chvvaliddate <> ''
		SET @SQL = @SQL + '
			AND a.ValidDate  = ''' + @chvvaliddate + ''''

		IF @chvgoodsnumber <> ''
		SET @SQL = @SQL + '
			AND a.goodsnumber  = ''' + @chvgoodsnumber + ''''
		
		IF @chvcostprice <> ''
        SET @SQL = @SQL + '
	        AND a.costprice  = ''' + @chvcostprice + ''''
		
        --是否勾选借出转销售
        IF @chvBillType = 11
        BEGIN
		    IF @chvlendtosale = 1
            BEGIN
                SET @SQL = @SQL + '
	                AND LPS.State = 18
	                AND LPS.BTypeID1 = ''' + CASE WHEN @chvDealBtypeID IS NOT NULL AND LEN(@chvDealBtypeID)>0 THEN @chvDealBtypeID ELSE @chvBTypeTrackID END + ''''
            END
            ELSE
            BEGIN
                SET @SQL = @SQL + '
	                AND ISNULL(LPS.State,-1) <> ''18'''
            END
        END
	END

    --盘点单306,可选借出库存中序列号
	IF @mngLendSerial = 1 AND @chvBillType NOT IN (71,72,87,88,203,306) AND @chvlendtosale = 0	-- 序列号借欠出入库校验模式
		SET @SQL = @SQL + '
		AND a.Serial NOT IN (SELECT Serial FROM GP_LendPTypeSerial WHERE Flag = 0 AND State = 18)'
END

IF @chvBillType = '203'	 AND @DBName='serial'	-- 序列号调整单
BEGIN
			SET @SQL =
			 '
			   SELECT	a.*,
						p.*,
						''' + @BtypePrice+''' AS BtypePrice,
						PromotePrice = 0,
						(' + CASE WHEN @IfMultiCodeBill = 1 THEN 'SELECT TOP 1 UserCode FROM PUserCode WHERE PTypeID=a.PTypeID AND BTypeID='''+ @chvBTypeTrackID + '''' ELSE '''''' END + ') AS CustomerCode
	FROM (
		SELECT	TOP 2 a.Serial,
				a.PTypeID,
				(SELECT FullName FROM BType WHERE SonNum=0 AND TypeID = a.BTypeID1) as XFullName, 
				a.BTypeID1,
				a.BTypeID2,
				(SELECT FullName FROM BType WHERE SonNum=0 AND TypeID = a.BTypeID2) as GFullName,
				a.InKtypeTime,
				a.OutKtypeTime,
				a.State,
				a.State AS nstate,
				a.KtypeID,
				a.CargoID,
				ct.fullname as cargofullname
				,(SELECT fullname FROM Stock WHERE typeid = a.KtypeID) AS kfullname
				--,CASE WHEN a.Serial = ''' + @UserCode + ''' THEN 0 ELSE 1 END AS ShowOrder
		FROM	GP_CruPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.Serial LIKE ''%' + @UserCode + '%''
		--ORDER BY ShowOrder
		) a INNER JOIN PType p ON a.PTypeID = p.TypeID  and p.deleted=0
		WHERE	1=1 '
END		
	 
DECLARE @cargoid1		NUMERIC(18,0)
DECLARE @cargoid1name	VARCHAR(100)

if @serialrelation<>1
BEGIN
	SELECT TOP 1 @cargoid1 = c.CargoID,@cargoid1name = c.FullName from STOCK k inner join CargoType c on k.typeId = c.KtypeID where c.IsDefault = 1 and k.FullName = ''+@chvKTypeName+''
	IF (@DBName='serial' OR LEFT(@DBName, 6) = 'Serial') AND @UserCode <>'' 
	BEGIN
		SELECT TOP 1 @cargoid1 = c.CargoID,@cargoid1name = c.FullName 
		from STOCK k 
		inner join CargoType c  on k.typeId = c.KtypeID 
		INNER JOIN dbo.gp_CruPtypeSerial g ON g.CargoID = c.CargoID
		where k.FullName = ''+@chvKTypeName+'' AND g.Serial=@UserCode
		IF @cargoid1 IS NULL
				SELECT TOP 1 @cargoid1 = c.CargoID,@cargoid1name = c.FullName 
				from STOCK k 
				inner join CargoType c  on k.typeId = c.KtypeID 
				INNER JOIN dbo.gp_LendPtypeSerial g ON g.CargoID = c.CargoID
				where  k.FullName = ''+@chvKTypeName+'' AND g.Serial=@UserCode
	END
END

IF @cargoid1 IS NULL
SET @cargoid1 = 0
IF @cargoid1name IS NULL
SET @cargoid1name = ''
DECLARE @exSql Nvarchar(max)

SELECT @exSql = 'SELECT T.*, ''00000'' AS xxx'

if @serialrelation<>1 
BEGIN
SET @exSql += '
            	    ,'''+CONVERT(VARCHAR(10),@cargoid1)+''' as cargoid
					,'''+@cargoid1name+''' as cargoidname
					,'''+@cargoid1name+''' as cargofullname '
END
SET @exSql += '	,'''+ISNULL(CONVERT(VARCHAR(10),@PriceType),'')+''' as PriceType,'

SET @exSql += '
		(select isnull(SUM(ISNULL(fa.QTY,0)),0) from FactStocks fa  where fa.PtypeId  = T.typeid  AND  fa.KTypeID LIKE ''' + @cKtypeID + '%'' AND  fa.KTypeId IN (SELECT TypeId FROM F_GetMANDetailKType('''+@OperatorID+'''))) + ( select  isnull(SUM(ISNULL(v.QTY,0)),0) from GoodsLend v where v.PTypeID like T.typeid+''%'' 
							AND v.KTypeID = ''' + @cKtypeID + ''' ) AS FactQty	-- 实际数量= 库存量+借出/借进
	FROM ('+@SQL+') T '

--PRINT @SQL 
EXEC(@exSql)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
实物库存期初入出/库单保存
2016-07-16
*/
CREATE   PROCEDURE GP_FactInOroutSaveDetail
(
    	@details Tb_NoinKindBill READONLY
)
--@encode$--
AS
SET NOCOUNT ON 

--select * from FactIndex
--取出表的billnumber根据billcode
--declare @ptypeid varchar(200),@GoodsOrder varchar(50)
--select @billnumberid =BillNumberId from FactIndex where billcode=@billcode
--select @ptypeid =typeid from ptype where usercode=@usercode and fullname=@goodsname 


--插入详细信息
--insert into FactInOut([billNumberID],[billtype],[Stypeid],[ptypeid],[ktypeid],[qty],[UnitID],[NQty],[NUnitID],[ItemID],[IsCombined],[GoodsOrder],[ProduceDate]
--      ,[ValidDate],[CargoID],[Serial],[comment],[IsUnit2],[GoodsNumber],[NUnitMsg],[MUnitMsg],[entryCode],[UnitRate]
--      ,[MQty],[MUnitRate],[MUnitID],[Base],[sqty],FromBillNumberID,FromBillID,FromBillType)
--SELECT billnumberid,billtype,Stypeid,ptypeid,ktypeid,qty,unitid,nqty,nunitid,itemid,null,null,productdate,validate,cargoid,serial,null,NULL,GoodsNumber,
--NULL,NULL,NULL,unitrate,NULL,NULL,NULL,base,Sqty,NULL,NULL,FromBillType FROM @details

MERGE FactInOut AS d 
USING 
    @details 
AS s 
ON s.[billNumberID] = d.[billNumberID] and s.[id]=d.[id] 
WHEN NOT MATCHED THEN 
    INSERT( [billNumberID],[billtype],[Stypeid],[ptypeid],[ktypeid],[qty],[UnitID],[NQty],[NUnitID],[ItemID],[IsCombined],[GoodsOrder],[ProduceDate]
      ,[ValidDate],[CargoID],[Serial],[comment],[IsUnit2],[GoodsNumber],[NUnitMsg],[MUnitMsg],[entryCode],[UnitRate]
      ,[MQty],[MUnitRate],[MUnitID],[Base],[sqty],FromBillNumberID,FromBillID,FromBillType) 
        VALUES( s.billnumberid,s.[billtype],s.Stypeid,s.ptypeid,s.ktypeid,s.qty,s.unitid,s.nqty,s.nunitid,s.itemid,s.iscombined,null,s.productdate,s.validate,s.cargoid,s.serial,null,NULL,s.GoodsNumber,
NULL,NULL,NULL,s.[UnitRate],NULL,NULL,NULL,s.base,s.Sqty,NULL,NULL,s.FromBillType) 
WHEN MATCHED THEN 
    UPDATE SET d.[billNumberID] = s.billnumberid, d.[billtype] = s.[billtype],d.[Stypeid]=s.Stypeid,d.[ptypeid]=s.ptypeid,d.[ktypeid]=s.ktypeid,d.[qty]=s.qty,
			   d.[UnitID]=s.unitid,d.[NQty]=s.nqty,d.[NUnitID]=s.nunitid,d.[ItemID]=s.itemid,d.[iscombined]=s.iscombined,d.[ProduceDate]=s.productdate
      ,d.[ValidDate]=s.validate,d.[CargoID]=s.cargoid,d.[Serial]=s.serial,d.[GoodsNumber]=s.GoodsNumber,d.[UnitRate]=s.unitrate
     ,d.[Base]=s.base,d.[sqty]=s.Sqty,d.FromBillType=s.FromBillType;
    
    
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--SELECT * FROM FactInOut



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
	作者：魏伟
	时间：2016-07-14
	描述：实物仓库历程批量删除
*/
CREATE    PROCEDURE Gp_FactOldBill_DelBill
(
	@nBillID		varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON
IF EXISTS(SELECT TOP 1 1 FROM dbo.FactIndex WHERE IfCheck = 'f' AND BillNumberId IN (SELECT * FROM F_Split(@nBillID,',') ))
	RETURN -1

-- 删除维修受理单
UPDATE 	RepairEngage 
SET 	Stat =1 
WHERE 	BillnumberID IN
(
		Select 	EngageBillID 
		From 	RepairDeal 
		WHERE 	BillNumberID=@nBillID
)

DELETE FROM RepairDeal 
WHERE BillnumberID IN 
(
	SELECT BillNumberID 
	FROM BillIndex 
	WHERE BillType = 157 AND BillNumberID=@nBillID
)

DELETE FROM CompleteTotal 
WHERE GoodsBillID=@nBillID
OR MoneyBillID=@nBillID
--处理按单结算的问题

DELETE FROM CompleteGoodTotal 
WHERE GoodsBillID=@nBillID
OR MoneyBillID=@nBillID


-- 删除发票
DELETE FROM invoiceBill 
WHERE BillNumberID=@nBillID

--删除QP单据信息
DELETE FROM Billindex_CarRepair 
WHERE BillNumberID=@nBillID

--删除附件
DELETE FROM BillAttachFiles 
WHERE BillNumberID=@nBillID

--删除多账户信息
DELETE FROM BillMulAccount 
WHERE BillNumberID=@nBillID

--删除单据操作日志
DELETE FROM BillOperateLog 
WHERE BillNumberID=@nBillID

--删除打印日志
--DELETE FROM PrintRecord 
--WHERE BillNumberID=@nBillID
UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId=@nBillID


--删除增加打印次数日志
DELETE FROM AddPrintCountRecord 
WHERE BillNumberID=@nBillID

--删除销售出库单时，删除调用电脑配置单的记录
IF EXISTS (
	SELECT BillNumberId
	FROM BillIndex 
	WHERE BillNumberId=@nBillID 
	AND BillType='11'
)
BEGIN
	DELETE DiyBillTypePSaleTypeID 
	WHERE SalebillNumberId=@nBillID	
END	

--最后执行这步
DELETE FROM dbo.FactIndex 
WHERE BillNumberID=@nBillID
		
IF @@ROWCOUNT = 0
	RETURN -2
ELSE
	RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/*	
*	仓库物流单据 处理引用状态
*/
IF  EXISTS (SELECT * FROM SysObjects WHERE ID = OBJECT_ID(N'[Gp_FactUpdateBillState]',N'P') )
BEGIN
	DROP PROCEDURE [dbo].[Gp_FactUpdateBillState]
END
GO

CREATE  PROCEDURE [dbo].[Gp_FactUpdateBillState]
(
	@BillNumberID INT,
	@BillType	  INT
)

AS
BEGIN
	/*拣货单、运输配送单、上架单*/
	IF @BillType NOT IN(418,419) RETURN 0
	DECLARE		@FromBillNumberID INT,					/*出库单单据编号*/
				@FromBillType     INT,					/*出库单单据类型*/
				@RowIndex          INT,					
				@RowCount          INT,					/*运输单明细行数*/
				@TbName            VARCHAR(100)			/*出库单明细表	*/
				
	DECLARE	    @Tmp			   TABLE
	(
		FromBillNumberID INT,
		FromBillType     INT,
		RowIndex         INT
	)
	
	INSERT INTO @Tmp(FromBillNumberID,FromBillType,RowIndex)
	SELECT
		   FromBillNumberID,
		   FromBillType,
		   ROW_NUMBER() OVER (ORDER BY GETDATE()) 
	FROM dbo.FactDepotInOut WHERE BillNumberID=@BillNumberID
	AND FromBillNumberID>0 AND FromBillType>0
	GROUP BY FromBillNumberID,FromBillType
	
	SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
	
	WHILE(@RowIndex<=@RowCount)
	BEGIN
		SELECT @FromBillNumberID=FromBillNumberID,@FromBillType=FromBillType FROM @Tmp WHERE RowIndex=@RowIndex
		IF @BillType=418
		BEGIN
			IF @FromBillType IN(71,72,87,88)
			BEGIN
				UPDATE dbo.LendIndex SET InFactRefState=1 WHERE BillNumberId=@FromBillNumberID
			END
			ELSE IF @FromBillType IN(327,328,329)
			BEGIN
				UPDATE dbo.PosAllotApplyBillIndex SET InFactRefState=1 WHERE BillNumberId=@FromBillNumberID
			END
			ELSE
			BEGIN
				UPDATE dbo.BillIndex SET InFactRefState=1 WHERE BillNumberId=@FromBillNumberID
			END
		END
		ELSE
		BEGIN
			IF @FromBillType IN(71,72,87,88)
			BEGIN
				UPDATE dbo.LendIndex SET OutFactRefState=1 WHERE BillNumberId=@FromBillNumberID
			END
			ELSE IF @FromBillType IN(327,328,329)
			BEGIN
				UPDATE dbo.PosAllotApplyBillIndex SET OutFactRefState=1 WHERE BillNumberId=@FromBillNumberID
			END
			ELSE
			BEGIN
				UPDATE dbo.BillIndex SET OutFactRefState=1 WHERE BillNumberId=@FromBillNumberID
			END
		END
		SET @RowIndex=@RowIndex+1
	END
	RETURN 0
END
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_FillMultibarocde]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_FillMultibarocde];
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:颜熙
	日期:2017-08-27
	描述:用于修改商品时填充商品多条码
*/
CREATE  PROCEDURE Gp_FillMultibarocde
( 
	  @Ptypeid VARCHAR(50) ---商品typeid
)
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
		SELECT A.Ptypeid,0 AS unitsid, STUFF((SELECT ';' + t.EntryCode+'_'+CAST(t.IsDefaultEntryCode AS VARCHAR) 
        FROM  PType_EntryCode_Ext AS t
        WHERE t.Ptypeid=A.Ptypeid ORDER BY t.IsDefaultEntryCode DESC,t.Nid FOR xml path(''),TYPE).value('.','NVARCHAR(MAX)'), 1, 1, '') AS multibarcode
		FROM PType_EntryCode_Ext A
		WHERE A.Ptypeid=@Ptypeid
		GROUP BY A.Ptypeid
		UNION ALL 			
		SELECT	a.PtypeID,A.UnitsId,STUFF((SELECT  ';' + t.EntryCode+'_'+CAST(t.IsDefaultEntryCode AS VARCHAR)
		FROM  PType_Units_EntryCode_Ext AS t
		WHERE t.Ptypeid=A.Ptypeid and t.UnitsId=A.UnitsId ORDER BY t.IsDefaultEntryCode DESC,t.Nid FOR xml path(''),TYPE).value('.','NVARCHAR(MAX)'), 1, 1, '')
		AS multibarcode
		FROM PType_Units_EntryCode_Ext A
		WHERE A.Ptypeid=@Ptypeid
		GROUP BY A.Ptypeid,A.UnitsId
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



/*
    是否在仓库中有此序列号
    参数：
       @KtypeID   仓库ID号 空时代表所有仓库
       @szSerial  序列号
       @Pre       是否期初 0 非期初数据 1 期初数据
*/
CREATE      PROCEDURE Gp_FindSerial
( 
	@KtypeID 	varchar(50),
	@szSerial 	varchar(50),
	@Pre 		int=0,
	@PtypeID 	varchar(50)='',
	@State		int=0
)
--@encode$--
AS
SET NOCOUNT ON
--系统采用序列号借欠出入库校验模式  谢吉康  2004-7-19
DECLARE @mngLendSerial 	int
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

IF @Pre=0 
BEGIN
	SELECT	* 
	FROM 	[gp_CruPtypeSerial]
	WHERE 	[Serial]=@szSerial
			AND [KtypeID]=CASE @KtypeID WHEN '' THEN KtypeID ELSE @KtypeID END 
	RETURN @@RowCount
END
ELSE
BEGIN

	IF @State=0 AND EXISTS (SELECT  top 1 1	FROM 	gp_initPtypeSerial	WHERE 	Serial = @szSerial	AND Flag = 1 AND 
	PtypeID=CASE @PtypeID WHEN '' THEN PtypeID ELSE @PtypeID END AND
	KtypeID=CASE @KtypeID WHEN '' THEN KtypeID ELSE @KtypeID END) 
	BEGIN
		RETURN 0
	END
	
	--实物库存期初 select * from gp_FactPtypeSerial
	IF @State=0 AND EXISTS (SELECT  top 1 1	FROM 	dbo.gp_FactPtypeSerial	WHERE 	Serial = @szSerial	AND Flag = 1 AND 
	PtypeID=CASE @PtypeID WHEN '' THEN PtypeID ELSE @PtypeID END AND
	KtypeID=CASE @KtypeID WHEN '' THEN KtypeID ELSE @KtypeID END) 
	BEGIN
		RETURN 0
	END

	IF EXISTS (SELECT  top 1 1	FROM 	GP_initLendPTypeSerial	WHERE 	Serial = @szSerial AND Flag = 1) 
	BEGIN
		RETURN 1
	END
	
	IF EXISTS (SELECT 	top 1 1 	FROM 	[gp_initPtypeSerial] WHERE 	[Serial]=@szSerial )
	BEGIN
		RETURN 1
	END
		
	RETURN 0
			
	IF @mngLendSerial = 1  --系统采用序列号借欠出入库校验模式
	BEGIN
	
		IF EXISTS (SELECT  top 1 1	FROM 	GP_initLendPTypeSerial	WHERE 	Serial = @szSerial	AND Flag = 1 AND 
		PtypeID=CASE @PtypeID WHEN '' THEN PtypeID ELSE @PtypeID END
		) 
		BEGIN
			RETURN 0
		END
		IF EXISTS (SELECT  top 1 1	FROM 	GP_initLendPTypeSerial	WHERE 	Serial = @szSerial	AND Flag = 1) 
		BEGIN
			RETURN 1
		END
		ELSE
		BEGIN
			IF EXISTS (SELECT 	top 1 1 	FROM 	[gp_initPtypeSerial] WHERE 	[Serial]=@szSerial	AND [KtypeID]=CASE @KtypeID WHEN '' THEN KtypeID ELSE @KtypeID END)
				RETURN 1
		END
			
	END
	ELSE --系统不采用序列号借欠出入库校验模式
	BEGIN
		IF EXISTS (SELECT 	top 1 1 	FROM 	[gp_initPtypeSerial] WHERE 	[Serial]=@szSerial	AND [KtypeID]=CASE @KtypeID WHEN '' THEN KtypeID ELSE @KtypeID END)
				RETURN 1
	END


END
-- ================================= 陈启华  由于录入期初时可以重复录入（在序列号严密管理模式下，并且 系统采用序列号借欠出入库校验模式  ）
/*	IF @mngLendSerial = 1
		BEGIN
			SELECT  Flag
			FROM 	GP_initLendPTypeSerial
			WHERE 	Serial = @szSerial
					AND Flag = 1
		END
	ELSE
		BEGIN
			SELECT 	* 
			FROM 	[gp_initPtypeSerial]
			WHERE 	[Serial]=@szSerial
					AND [KtypeID]=CASE @KtypeID WHEN '' THEN KtypeID ELSE @KtypeID END 
		END
RETURN @@RowCount
*/



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：董湛
	日期：2013-07-25
	描述：系统重建对固定资产卡片的操作
*/
CREATE  PROCEDURE GP_FixedAssets_ReBuild
(
	@bRebulidIni		BIT,	-- 是否清除期初；0 - 不清除，1 - 清除
	@bRebulidDraft		BIT  	-- 是否清除草稿；0 - 不清除，1 - 清除
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
--固定资产的判断
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
	BEGIN
		--清空现有卡片数据，恢复初始卡片数据
		CREATE TABLE #tempID
		(
			id INT
		)
		INSERT INTO #tempID(id)
		SELECT AssertsCardId FROM dbo.Ac_AssetsCards_History WHERE BillType=0
		
		IF @bRebulidIni=0 --不清期初
			BEGIN
				INSERT INTO #tempID(id)
			    SELECT a.AssetCardId 
			    FROM  dbo.BillIndex b 
			    JOIN AssetIncDecBill a ON b.BillNumberId=a.BillNumberId AND b.BillType=a.BillType  WHERE b.BillType IN (212,213) AND IsIni=1
			    
			    INSERT INTO #tempID(id)
			    SELECT d.AssetCardId 
			    FROM  dbo.BillIndex b 
			    JOIN DepBill d ON b.BillNumberId=d.BillNumberId  WHERE BillType=214 AND IsIni=1
			END
		
		--删除固定资产初始化以后的卡片(即在历史记录表中没初始化记录的卡片都要删除,且得初始化了的分支机构)
		DELETE FROM dbo.Ac_AssetsCards 
		WHERE id NOT IN (SELECT id FROM #tempID) AND 
			  STypeId IN (SELECT TypeId FROM dbo.SType WHERE IfAssetsIni=1)  
			   
			  
		--------恢复卡片初始化以前的数据
		--特殊处理，已折旧的卡片数据结转过来，历史表中已有初始数据，再次初始化后又写一条，所以重建的时候需要删除结转前初始化的记录（跟反初始化一样）		  
		DELETE FROM Ac_AssetsCards_History 
		WHERE Id NOT IN (SELECT MAX(Id) FROM Ac_AssetsCards_History WHERE BillType=0 GROUP BY AssertsCardId)
		--这时候再根据历史表更新卡片数据
		UPDATE ac SET  ac.usercode=ah.usercode,
					   ac.fullname=ah.fullname,
					   ac.stypeid=ah.stypeid,
					   ac.AssertATypeId=ah.AssertATypeId,
					   ac.DepATypeId=ah.DepATypeId,
					   ac.DisATypeId=ah.DisATypeId,
					   ac.DevalueATypeId=ah.DevalueATypeId,
					   ac.CategoryId=ah.CategoryId,
					   ac.LocationId=ah.LocationId,
					   ac.ConditionId=ah.ConditionId,
					   ac.SIZE=ah.SIZE,
					   ac.DTypeid=ah.DTypeid,
					   ac.InAccountDate=ah.InAccountDate,
					   ac.BusinessTypeId=ah.BusinessTypeId,
					   ac.Total=ah.Total,
					   ac.Cid=ah.Cid,
					   ac.F_Total=ah.F_Total,
					   ac.Rate=ah.Rate,
					   ac.DepTotal=ah.DepTotal,
					   ac.DevalueReady=ah.DevalueReady,
					   ac.NetValue=ah.NetValue,
					   ac.NetSalvage=ah.NetSalvage,
					   ac.NetSalvageRate=ah.NetSalvageRate,
					   ac.DepreciationMean=ah.DepreciationMean,
					   ac.DurYear=ah.DurYear,
					   ac.DepreciationMonth=ah.DepreciationMonth,
					   ac.Comment=ah.Comment,
					   ac.AssetsState=1,   --初始状态
					   ac.OperationDate=ah.OperationDate,
					   ac.Etypeid=ah.Etypeid
		FROM dbo.Ac_AssetsCards ac 
		JOIN dbo.Ac_AssetsCards_History ah ON ac.Id=ah.AssertsCardId AND ah.BillType=0
		WHERE ac.STypeId IN (SELECT TypeId FROM dbo.SType WHERE IfAssetsIni=1)
		
		--将没有初始化的分支机构中的已折旧卡片状态重置为初始化卡片状态
		UPDATE Ac_AssetsCards SET AssetsState = 1 WHERE AssetsState = 4 AND STypeId IN (SELECT TypeId FROM SType WHERE IfAssetsIni = 0)
		
		
		--清掉所有单据：固定资产增加单、固定资产减少单、固定资产折旧单、计提减值准备单、部门转移单、折旧方式变更单(除了期初单)
		IF @bRebulidIni=1 AND @bRebulidDraft=1  --全清
			DELETE FROM dbo.BillIndex WHERE BillType IN (212,213,214) 
		ELSE IF @bRebulidIni=0 --只不清期初
			DELETE FROM dbo.BillIndex WHERE BillType IN (212,213,214) AND IsIni<>1
		ELSE    --只不清草稿
			DELETE FROM dbo.BillIndex WHERE  BillType IN (212,213,214) AND draft=0
		
		IF @bRebulidIni=1 AND @bRebulidDraft=1  --全清
			TRUNCATE TABLE AssetIncDecBill
		ELSE 
			DELETE FROM dbo.AssetIncDecBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BillIndex WHERE BillType IN (212,213))
			
		IF @bRebulidIni=1 AND @bRebulidDraft=1  --全清	
			TRUNCATE TABLE dbo.DepBill
		ELSE 
			DELETE FROM dbo.DepBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BillIndex WHERE BillType=214)
			
		TRUNCATE TABLE Ac_AssetsModifyRecords  --部门转移
		TRUNCATE TABLE Ac_ProvisionForImpairment --计提减值
		TRUNCATE TABLE Ac_DepreciationAlteration--变更
		--清掉所有折旧计划表、历史记录
		TRUNCATE TABLE dbo.Ac_DepreciationPlan
		TRUNCATE TABLE dbo.Ac_AssetsCards_History
		--所有分支机构固定资产置为未初始化状态
		UPDATE dbo.SType SET IfAssetsIni=0 
		TRUNCATE TABLE Ac_FixedAssetsInit_Stype
		--清除模版
		--UPDATE dbo.Ac_AssetBusinessType SET atid=''
		--DELETE FROM  Ac_Auditing_Template_Detail_Assist_CheckItems  WHERE atid IN (SELECT AtId FROM Ac_Auditing_Template WHERE  BillType IN (213,212,214,-1,-2)) 
		--DELETE FROM  Ac_Auditing_Template_Detail  WHERE atid IN (SELECT AtId FROM Ac_Auditing_Template WHERE BillType IN (213,212,214,-1,-2)) 
		--DELETE FROM Ac_Auditing_Template  WHERE  BillType IN (213,212,214,-1,-2)
	END

	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/05/14
	Description	: 固定资产按分支机构反初始化
*/
CREATE PROCEDURE Gp_FixedAssetsBackIniAll
(
	@STypeId		VARCHAR(MAX),		--	分支机构
	@EtypeID        varchar(50),
    @ReturnValue	VARCHAR(MAX) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--判断所选分支机构是否设置了启用期间
IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype PS INNER JOIN F_GetAllManagerBaseTypeId(@STypeId,11,'00001') F ON F.TypeId=PS.Stypeid AND (ISNULL(PS.SFYear,0)=0 OR ISNULL(PS.SFPeriod,0)=0))
	BEGIN
		DECLARE @MSG VARCHAR(MAX)=''
		SELECT @MSG+=S.FullName+'；' FROM Ac_AccountsPeroid_Stype PS INNER JOIN F_GetAllManagerBaseTypeId(@STypeId,11,'00001') F ON F.TypeId=PS.Stypeid AND (ISNULL(PS.SFYear,0)=0 OR ISNULL(PS.SFPeriod,0)=0) INNER JOIN SType S ON S.TypeId=PS.Stypeid
		IF(ISNULL(@MSG,'')<>'')
			SET @MSG=SUBSTRING(@MSG,1,LEN(@MSG)-1)
		SET @MSG='【'+@MSG+'】未设置启用期间，不允许此操作！'
		RAISERROR(@MSG,16,1) 
		RETURN
	END

DECLARE @Re				INT=0,
		@rValue			VARCHAR(MAX),
		@MxSTypeId		VARCHAR(MAX),
		@MxSFullName	VARCHAR(MAX),
		@version		INT
SELECT @version=SubValue FROM dbo.sysdata WHERE SubName='ProInfo' 

 CREATE TABLE #stype(typeid VARCHAR(50))
				  
DECLARE SType_Cursor CURSOR FOR
	SELECT f.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,'00001') f JOIN dbo.SType s ON f.TypeId=s.TypeId AND s.IsSelfVerify=1 
OPEN SType_Cursor
FETCH NEXT FROM SType_Cursor INTO @MxSTypeId
WHILE @@FETCH_STATUS = 0
	BEGIN   
		SELECT @MxSFullName=FullName FROM dbo.SType WHERE TypeId=@MxSTypeId
	    
	    TRUNCATE TABLE #stype
		INSERT INTO #stype(typeid)
		SELECT typeid FROM dbo.SType WHERE VerifyID=@MxSTypeId 

	
        ---未初始化
        IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE IfAssetsIni=0 AND TypeId=@MxSTypeId)
			BEGIN
				IF @STypeId<>''
					BEGIN
						IF @version=1 --v3
							SET @rValue= '未初始化,不能进行反初始化，请确认'
						ELSE IF @version=2 --A8
							SET @rValue= '分支机构【'+@MxSFullName+'】未初始化,不能进行反初始化，请确认'
						SET @Re=-2
						CLOSE SType_Cursor
						DEALLOCATE SType_Cursor
						SET @ReturnValue = @rValue
						RETURN @Re	
					END   
			END
        ELSE	
			BEGIN
				IF EXISTS (SELECT TOP 1 1 FROM SType_UserConfig WHERE StypeId IN (SELECT TypeId FROM SType WHERE VerifyID = @MxSTypeId) AND Value=1)
					BEGIN
						IF @version=1 --v3
							SET @rValue= '为确保业务期初资产负债的固定资产与固定资产卡片期初数据相等，业务系统必须先反开账！'
						ELSE IF @version=2 --A8
							BEGIN
								--独立分支机构下所有非独立及本身分支名称
								DECLARE @A_Stype	VARCHAR(MAX)=''
								SELECT @A_Stype+=FullName+',' FROM SType S INNER JOIN SType_UserConfig SU ON SU.StypeId=S.TypeId AND S.VerifyID=@MxSTypeId AND SU.Value=1
								SET @A_Stype=SUBSTRING(@A_Stype,1,LEN(@A_Stype)-1)
								
								SET @rValue= '为确保业务期初资产负债的固定资产与固定资产卡片期初数据相等，'+char(10)+'业务分支机构【'+@A_Stype+'】必须先反开账！'		
							END
							
							SET @Re=-2
							CLOSE SType_Cursor
							DEALLOCATE SType_Cursor
							SET @ReturnValue = @rValue
							RETURN @Re	
						END
								
					--9.5 BUG230 新增判断
					--1）期初固定资产卡片净值=0时，允许反初始化；
					--2）期初固定资产卡片净值≠0时，控制不允许反初始化操作；
				IF EXISTS (SELECT TOP 1 1 FROM SType_UserConfig WHERE StypeId IN (SELECT TypeId FROM SType WHERE VerifyID = @MxSTypeId) AND Value=1) AND EXISTS(SELECT 1 FROM Ac_AssetsCards WHERE NetValue<>0 AND STypeId IN (SELECT TypeId FROM SType WHERE VerifyID = @MxSTypeId))
					BEGIN
						IF (SELECT COUNT(*) FROM SType WHERE VerifyID=@MxSTypeId)=1
							SET @ReturnValue='该分支机构的期初固定资产卡片净值不为0'
						ELSE 
							SET @ReturnValue='该分支机构及与之关联的非独立核算分支机构的期初固定资产卡片净值不为0'
						SET @Re=-2
						CLOSE SType_Cursor
						DEALLOCATE SType_Cursor
						SET @ReturnValue = @rValue
						RETURN @Re	
					END
-------------------------------------判断关联非独立核算分支机构期初卡片值----------------
                --DECLARE @UnionSTypeFullName VARCHAR(1000)= ''
                --SELECT  @UnionSTypeFullName = @UnionSTypeFullName + B.FullName
                --        + ','
                --FROM    dbo.Ac_AssetsCards A
                --        INNER JOIN dbo.SType B ON A.STypeID = B.TypeId
                --WHERE   B.VerifyID = @MxSTypeId
                --        AND B.TypeId <> @MxSTypeId
                --GROUP BY B.TypeId ,
                --        B.FullName
                --IF ISNULL(@UnionSTypeFullName, '') <> ''
                --BEGIN
                --        SET @ReturnValue = '与之关联的非独立核算分支机构['
                --            + SUBSTRING(@UnionSTypeFullName, 1,
                --                        LEN(@UnionSTypeFullName) - 1)
                --            + ']的期初固定资产卡片净值不为0'
                --        RETURN -2
                --END
-------------------------------------判断关联非独立核算分支机构期初卡片值----------------

			      --判断单据
				  IF EXISTS(SELECT TOP 1 1 FROM Ac_ProvisionForImpairment ap JOIN dbo.Ac_AssetsCards aa ON ap.CardId=aa.Id JOIN #stype s ON aa.STypeId=s.typeid)
			 		BEGIN
			 			IF @version=1 --v3
							SET @rValue= '含有减值准备记录,不能进行反初始化，请确认' 
						ELSE IF @version=2 --A8
							SET @rValue= '分支机构【'+@MxSFullName+'】含有减值准备记录,不能进行反初始化，请确认' 
						SET @Re=-2
						CLOSE SType_Cursor
						DEALLOCATE SType_Cursor
						SET @ReturnValue = @rValue
						RETURN @Re	
					END
				 IF EXISTS(SELECT TOP 1 1 FROM Ac_Assetsmodifyrecords ap JOIN dbo.Ac_AssetsCards aa ON ap.CardId=aa.Id JOIN #stype s ON aa.STypeId=s.typeid)
			 		BEGIN
			 			IF @version=1 --v3
							SET @rValue= '含有部门转移记录,不能进行反初始化，请确认' 
						ELSE IF @version=2 --A8
							SET @rValue= '分支机构【'+@MxSFullName+'】含有部门转移记录,不能进行反初始化，请确认' 
						SET @Re=-2
						CLOSE SType_Cursor
						DEALLOCATE SType_Cursor
						SET @ReturnValue = @rValue
						RETURN @Re	
					END
			     IF EXISTS (SELECT TOP 1 1 FROM dbo.BillIndex b JOIN #stype s ON b.STypeId=s.typeid WHERE BillType IN (212,213,214) AND RedWord=0 AND IsIni=0)  --蓝单是1，红单是2，所以redword=0,排除期初单据
					BEGIN
						IF @version=1 --v3
							SET @rValue= '含有固定资产单据,不能进行反初始化，请确认' 
						ELSE IF @version=2 --A8
							SET @rValue= '分支机构【'+@MxSFullName+'】含有固定资产单据,不能进行反初始化，请确认' 
						SET @Re=-2
						CLOSE SType_Cursor
						DEALLOCATE SType_Cursor
						SET @ReturnValue = @rValue
						RETURN @Re	
					END
				 IF EXISTS (SELECT TOP 1 1 FROM Ac_Provision_Voucher apv JOIN dbo.Ac_ProvisionForImpairment ap ON apv.SourceId=ap.Id 
																		 JOIN dbo.Ac_AssetsCards aa ON  ap.cardid=aa.Id 
																		 JOIN #stype s ON aa.STypeId=s.typeid
																		 WHERE apv.SourceType=1)   
					BEGIN
						IF @version=1 --v3
							SET @rValue= '含有减值准备生成的凭证,不能进行反初始化，请确认' 
						ELSE IF @version=2 --A8
							SET @rValue= '分支机构【'+@MxSFullName+'】含有减值准备生成的凭证,不能进行反初始化，请确认' 
						SET @Re=-2
						CLOSE SType_Cursor
						DEALLOCATE SType_Cursor
						SET @ReturnValue = @rValue
						RETURN @Re	
					END
					
				 IF EXISTS (SELECT TOP 1 1 FROM Ac_Provision_Voucher apv JOIN dbo.Ac_AssetsModifyRecords ap ON apv.SourceId=ap.Id 
																		 JOIN dbo.Ac_AssetsCards aa ON  ap.cardid=aa.Id 
																		 JOIN #stype s ON aa.STypeId=s.typeid
																		 WHERE apv.SourceType=2)   
					BEGIN
						IF @version=1 --v3
							SET @rValue= '含有部门转移生成的凭证,不能进行反初始化，请确认' 
						ELSE IF @version=2 --A8
							SET @rValue= '分支机构【'+@MxSFullName+'】含有部门转移生成的凭证,不能进行反初始化，请确认' 
						SET @Re=-2
						CLOSE SType_Cursor
						DEALLOCATE SType_Cursor
						SET @ReturnValue = @rValue
						RETURN @Re	
					END
				 IF EXISTS (SELECT TOP 1 1 FROM Ac_Provision_Voucher apv JOIN dbo.BillIndex b ON apv.SourceId=b.BillNumberId AND apv.SourceType=b.BillType  AND RedWord!=0  
							 JOIN #stype s ON b.STypeId=s.typeid WHERE apv.SourceType IN (212,213,214))  --蓝单是1，红单是2，所以redword!=0的才是红冲了的单据
					BEGIN
						IF @version=1 --v3
							SET @rValue= '含有红冲单据生成的凭证,不能进行反初始化，请确认' 
						ELSE IF @version=2 --A8
							SET @rValue= '分支机构【'+@MxSFullName+'】含有红冲单据生成的凭证,不能进行反初始化，请确认' 
						SET @Re=-2
						CLOSE SType_Cursor
						DEALLOCATE SType_Cursor
						SET @ReturnValue = @rValue
						RETURN @Re	
					END 
				
				 ----修改分支机构状态
				 UPDATE Stype SET IfAssetsIni=0 WHERE VerifyID=@MxSTypeId
				 ---修改卡片状态（只修改已入账的卡片）
				 UPDATE ac SET AssetsState=1 FROM dbo.Ac_AssetsCards ac JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId WHERE ac.AssetsState=3
				 
				 ----删除记录
				DELETE FROM AC_FixedAssetsInit_Stype WHERE stypeid=@MxSTypeId   --初始化期间
				DELETE FROM AssetIncDecBill WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.BillIndex b JOIN #stype s ON b.Stypeid=s.typeid  WHERE BillType IN (212,213,214))
				DELETE FROM DepBill WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.BillIndex b JOIN #stype s ON b.Stypeid=s.typeid  WHERE  BillType IN (212,213,214)) 
				DELETE FROM dbo.BillIndex   WHERE BillType IN (212,213,214) AND stypeid IN (SELECT typeid FROM  #stype)
				DELETE FROM dbo.Ac_DepreciationPlan  
				WHERE STypeId IN (SELECT typeid FROM  #stype) AND 
					  AssetCardId NOT IN (SELECT Id FROM dbo.Ac_AssetsCards ac JOIN #stype s ON ac.STypeId=s.typeid WHERE ac.AssetsState=4)  --折旧计划表(已计提的卡片记录不删除)
				DELETE FROM Ac_AssetsCards_History 
				WHERE stypeid IN (SELECT typeid FROM #stype) AND 
					  AssertsCardId NOT IN (SELECT Id FROM dbo.Ac_AssetsCards ac JOIN #stype s ON ac.STypeId=s.typeid WHERE ac.AssetsState=4)
				--特殊处理，已折旧的卡片数据结转过来，历史表中已有初始数据，再次初始化后又写一条，所以反初始化的时候需要删除最近一条初始化的记录		  
				DELETE FROM Ac_AssetsCards_History 
				WHERE stypeid IN (SELECT typeid FROM #stype) AND 
					  AssertsCardId IN (SELECT Id FROM dbo.Ac_AssetsCards ac JOIN #stype s ON ac.STypeId=s.typeid WHERE ac.AssetsState=4) AND 
					  BillType=0 AND 	  
					  Id IN (SELECT MAX(Id) FROM Ac_AssetsCards_History WHERE AssetsState=4 AND BillType=0 GROUP BY AssertsCardId)
					  
				DELETE FROM Ac_DepreciationAlteration WHERE CardId IN (SELECT Id FROM dbo.Ac_AssetsCards ac JOIN #stype s ON ac.STypeId=s.typeid)  --折旧方式变更单
				
				--982bug610
				--UPDATE dbo.Ac_AssetBusinessType SET atid='' WHERE STypeId=@MxSTypeId  --反初始化时清除掉对应凭证模板以及业务类型与之的对应关系
				--DELETE FROM  Ac_Auditing_Template_Detail_Assist_CheckItems  WHERE atid IN (SELECT AtId FROM Ac_Auditing_Template WHERE STypeId=@MxSTypeId AND BillType IN (213,212,214,-1,-2)) 
				--DELETE FROM  Ac_Auditing_Template_Detail  WHERE atid IN (SELECT AtId FROM Ac_Auditing_Template WHERE STypeId=@MxSTypeId AND BillType IN (213,212,214,-1,-2)) 
				--DELETE FROM Ac_Auditing_Template  WHERE STypeId=@MxSTypeId AND BillType IN (213,212,214,-1,-2)
			END   
		
		FETCH NEXT FROM SType_Cursor INTO @MxSTypeId
	END
	
CLOSE SType_Cursor
DEALLOCATE SType_Cursor

	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.04.11
	描述：固定资产盘点单处理
*/
CREATE PROCEDURE Gp_FixedAssetsCheck
(
	@OperatorId			VARCHAR(50),			-- 当前操作员ID
	@BillNumberId		INT,					-- 单据编号
	@szPid				VARCHAR(1000) OUTPUT,	-- 返回信息
	@isContinue			INT = 0					-- 表体没有盘亏数据时，是否继续盘点处理
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------

SET @szPid = ''

--未启用盘亏类型
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetBusinessType WHERE Id = 10 AND Deleted = 1)
	RETURN -3

--表体没有盘亏数据时，返回提示
IF @isContinue = 0 
	AND NOT EXISTS(SELECT TOP 1 1 FROM FixedAssetsDetails T1
			WHERE T1.BillNumberID = @BillNumberId AND T1.panstate = 3)
BEGIN
	RETURN -4
END

DECLARE @billcode	VARCHAR(200),
		@Dfullname	VARCHAR(500),
		@dtypeid	VARCHAR(50),
		@Stypeid	VARCHAR(50),
		@businessdate	DATETIME,
		@Comment	VARCHAR(200),
		@AtypeID	VARCHAR(50),
		@ETypeId	VARCHAR(50),
		@cefullname			VARCHAR(500)=''		--制单人
		

--单据日期 当前系统日期
SET @businessdate = CONVERT(VARCHAR,GETDATE(),23)

--获取部门、分支机构信息、经手人
SELECT @Dfullname=d.FullName,@dtypeid=aa.DTypeid,@Stypeid = aa.stypeid,@ETypeId = etypeId
FROM dbo.FixedAssetsIndex aa 
INNER JOIN dbo.Department d ON aa.DTypeid=d.typeid
WHERE BillNumberID = @BillNumberId


--生成单据摘要
SELECT @Comment = '盘点单'+ billCode +'自动生成'
FROM dbo.FixedAssetsIndex
WHERE BillNumberID = @BillNumberId

--单据往来科目
SELECT @AtypeID = AtypeId FROM dbo.BillAtype 
WHERE BillTypeId = '213'
	AND StypeId = (SELECT VerifyID FROM dbo.SType WHERE TypeId = @Stypeid)

--总账下，单据未设置往来科目
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
	AND @AtypeID = ''
BEGIN
	RETURN -2
END

BEGIN TRAN

IF @isContinue = 0
BEGIN

	--生成单据编号
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='ifbillcode' AND Value=0)  --用户手工录入单据编号
		SET @billcode=''
	ELSE 
	BEGIN
		--用户自定义单据编号
		IF EXISTS(SELECT TOP 1 1 FROM CodeConfig WHERE BillType=213) 
		AND EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName='BillCodeConfig' AND Value=1)
			BEGIN
				DECLARE @etypename VARCHAR(200)
				SELECT @etypename=typeId FROM dbo.employee WHERE typeId=@ETypeId
				SELECT @cefullname=fullname FROM dbo.employee WHERE typeId=@OperatorId
				EXEC Gp_GetBillCode @BType=213,@Month=@etypename,@Day='',@BillFlag='GJ',@BillDate=@businessdate,@STypeid=@Stypeid,@DFullName=@Dfullname,@BCode=@billcode OUTPUT,@DFullName=@Dfullname,@CEFullName=@cefullname
			END
		ELSE --自动生成
			DECLARE @tMonthe VARCHAR(500),@tDay VARCHAR(50)
			SET @tMonthe=DateName(month,@businessdate)
			SET @tDay=DateName(day,@businessdate)

			EXEC Gp_GetBillCode @BType=213,@Month=@tMonthe,@Day=@tDay,@BillFlag='GJ',@BillDate=@businessdate,@STypeid=@Stypeid,@DFullName=@Dfullname,@BCode=@billcode OUTPUT,@DFullName=@Dfullname,@CEFullName=@cefullname
	END

	SET @szPid = @billcode



	--1.插入表头，并生成表头单据编号
	DECLARE @returnId INT
	EXEC @returnId = Gp_InsertBillIndex 
		@BillDate= @businessdate,--单据日期
		@BillCode = @billcode,	--单据编号
		@BillType = 213,		--单据类型 减少单
		@Comment = @Comment,	--备注
		@ATypeID='',
		@PTypeID='',
		@BTypeID='',
		@ETypeID = @ETypeId,	--职员
		@KTypeID='',
		@KTypeID2='',
		@IfCheck='f',
		@CheckE = @OperatorId,	--职员
		@TotalMoney=0,@TotalQty=0,@TotalInMoney=0.00,@Tax=0,@szPeriod=1,@Explain='',
		@Draft='1',				--草稿
		@RedWord='0',			--非红冲
		@OrderID=0,@WayBillCode='',@Goodsnumber='',@PackWay='',@Tel='',
		@preferencemoney=0.00,@AlertDay=9999,@Assessor='',@IfAudit='',@Audit_Explain='',
		@Dtypeid = @dtypeid,	--部门
		@VipCardID=-1,@KTypeID3='',@LinkMan='',@LinkTel='',@LinkAddr='',@wxManID='',
		@JieJianBillNumberID=-1,@JieJianID=-1,@BaoXiuBillNumberID=-1,@BaoXiuID=-1,
		@BuyDate='',@Serial='',@wxTotal=0,@ErrDes='',@ifHideJieJian=0,@ifWX=0,@IfBargainOn=0,
		@STypeID = @Stypeid,	--分支机构
		@FromBillNumberID=0,@CostSale=0,
		@completedate='9999-12-31 23:59:59',
		@billstate=1,@ifmulaccount=0,@vipczmoney=0,@otherinouttype=-1,@czbeforetimes=0,@posbilltype=0,@sharemode=0,@TransportId='',
		@IsFreightMoney=0,@FreightAddr=NULL,@freightperson=NULL,@freighttel=NULL,@uf1='',@uf2='',@uf3='',@uf4='',@uf5='',@DEALBTYPEID='',
		@cid=1,@rate=1.0000,@ntotalmoney=0,@ntotalinmoney=0,@npreferencemoney=0,@nvipczmoney=0,
		@ATYPEID1 = @AtypeID,	--往来科目
		@billproperty=-1,@ncompletetotal=0,@isini=0,@ATID=0,@completetotal=0,
		@IfCargo='0',
		@IfInvoice=0,@invoicemoney=0,@ninvoicemoney=0,@importtype=0,
		@AssetBusinessTypeId = 10,--业务类型，盘亏
		@promoruleid=0,@beforepromobillnumberid=0,@promotionmsg='',
		@STypeID2 ='',@ifconfirm =0,@FeeDeductType =0,@TransferType =0,@isyapi =0,@yapiorderid = 0,@checkSave='bill_allow_save',
		@ChargeOffTotal=0,
		@nchargeofftotal=0


	--生成单据出现异常，不再继续
	IF @returnId < 0
	BEGIN
		SET @szPid = ''
		ROLLBACK TRAN
		RETURN -1
	END
		
	--2.更新种子
	EXEC GP_SaveBillCode_Seed @returnId,@businessdate,213,@billcode

	--3.插入明细
	INSERT INTO dbo.AssetIncDecBill
				( BillNumberId ,
				  AssetCardId ,
				  BillType ,
				  NTotal ,
				  Total ,
				  Tax ,
				  NTaxMoney ,
				  TaxMoney ,
				  NTaxTotal ,
				  TaxTotal ,
				  NDepTotal ,
				  DepTotal ,
				  NNetValue ,
				  NetValue ,
				  Comment
				)
			SELECT    
				  @returnId,
				  T1.AssertsCardId ,
				  213,
				  0,
				  0, 
				  0, 
				  0,
				  0,
				  0,
				  0,
				  0,
				  0,
				  T2.NetValue , -- NNetValue - numeric
				  T2.NetValue , -- NetValue - numeric
				  T1.comment  -- Comment - varchar(255)
				FROM FixedAssetsDetails T1
					INNER JOIN dbo.Ac_AssetsCards T2 ON T1.AssertsCardId = T2.Id
				WHERE T1.BillNumberID = @BillNumberId AND T1.panstate = 3
					AND T2.AssetsState IN (3,4)

	IF @@ROWCOUNT = 0
	BEGIN
		SET @szPid = ''
		ROLLBACK TRAN
		RETURN -1
	END
END

--更新盘点单状态
UPDATE dbo.FixedAssetsIndex SET [state] = 3 WHERE BillNumberID = @BillNumberId 

COMMIT TRAN

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/05/14
	Description	: 固定资产按分支机构初始化
	Modify	:   Awu 2014.04.09
	Description:	增加非总账下，启用固定资产，已开账分支初始化判断；未开账分支不判断余额一致
*/
CREATE PROCEDURE Gp_FixedAssetsIniAll
(
	@STypeId		VARCHAR(MAX),		--	分支机构
	@EtypeID        varchar(50),
	@isReCreate		INT,
    @ReturnValue	VARCHAR(MAX) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON
--判断所选分支机构是否设置了启用期间
IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype PS INNER JOIN F_GetAllManagerBaseTypeId(@STypeId,11,'00001') F ON F.TypeId=PS.Stypeid AND (ISNULL(PS.SFYear,0)=0 OR ISNULL(PS.SFPeriod,0)=0))
	BEGIN
		DECLARE @MSG VARCHAR(MAX)=''
		SELECT @MSG+=S.FullName+'；' FROM Ac_AccountsPeroid_Stype PS INNER JOIN F_GetAllManagerBaseTypeId(@STypeId,11,'00001') F ON F.TypeId=PS.Stypeid AND (ISNULL(PS.SFYear,0)=0 OR ISNULL(PS.SFPeriod,0)=0) INNER JOIN SType S ON S.TypeId=PS.Stypeid
		IF(ISNULL(@MSG,'')<>'')
			SET @MSG=SUBSTRING(@MSG,1,LEN(@MSG)-1)
		SET @MSG='【'+@MSG+'】未设置启用期间，不允许此操作！'
		RAISERROR(@MSG,16,1) 
		RETURN
	END

DECLARE @Re				INT=0,
		@MxSTypeId		VARCHAR(MAX),
		@MxSFullName	VARCHAR(MAX),
		@FYear			VARCHAR(10),
		@FPeriod		INT,
		@Cid			INT

DECLARE @SubId		INT, --使用的会计科目表Id
		@Atypeid	VARCHAR(MAX)--要导入的会计科目typeid
DECLARE @version INT,
		@isac		INT--是否总账
SET @SubId = 0
SELECT @version=SubValue FROM dbo.sysdata WHERE SubName='ProInfo' 
SELECT @Cid=cid FROM dbo.Ac_Currency WHERE Sysrow=1

SELECT @isac = SubValue FROM dbo.sysdata WHERE SubName = 'IsUseAcSystem'

SELECT @SubId = SubId FROM dbo.Ac_Account_Set_List WHERE IsUse = 1
IF ISNULL(@SubId,0) = 0 AND @isac = 1
	RETURN -4
ELSE IF ISNULL(@SubId,0) = 29 AND @isac = 1--不支持GRASP科目表
BEGIN
	RETURN -5
END
ELSE 


	
DECLARE @index INT=1,@Count INT,@tempcardid INT,@OutValue INT
CREATE TABLE #tempCard
(
	cardid INT,
	orderid INT,
	stypeid VARCHAR(50),
	cardstate INT
)
DECLARE @DateTime DATETIME  --历史记录中初始化的业务时间


DECLARE FixedSType_Cursor CURSOR FOR
	SELECT f.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,'00001') f JOIN dbo.SType s ON f.TypeId=s.TypeId AND s.IsSelfVerify=1 
OPEN FixedSType_Cursor
FETCH NEXT FROM FixedSType_Cursor INTO @MxSTypeId
WHILE @@FETCH_STATUS = 0
	BEGIN   
		--获取指定分支机构当前年度,财务期间	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId)
			SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId
		ELSE 
			BEGIN
				SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName='fyear'
				SELECT @FPeriod=SubValue FROM dbo.sysdata WHERE SubName='fperiod'
			END
	
		SELECT @MxSFullName=FullName FROM dbo.SType WHERE TypeId=@MxSTypeId
		SELECT @DateTime=FBegin FROM dbo.Ac_Period WHERE FYear=@FYear AND FPeriod=@FPeriod
		
		---已经初始化
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE IfAssetsIni=1 AND TypeId=@MxSTypeId)
			BEGIN
				IF @STypeId<>''			--单个分支开账
					BEGIN
						IF @version=2 --A8
							SET @ReturnValue= '分支机构【'+@MxSFullName+'】已经初始化'
						ELSE IF @version=1 --v3
							SET @ReturnValue= '已经初始化'
						SET @Re=-3
						CLOSE FixedSType_Cursor
						DEALLOCATE FixedSType_Cursor
						RETURN @Re	
					END   
				ELSE					--全部开账，直接循环下一个
					BEGIN
						FETCH NEXT FROM FixedSType_Cursor INTO @MxSTypeId   
					END
			END
		ELSE    ---未初始化
			BEGIN
				DECLARE @A  NUMERIC(24, 10) --固定资产科目之和
				DECLARE @B  NUMERIC(24, 10) --累计折旧科目之和
				DECLARE @C  NUMERIC(24, 10) --减值准备科目之和
				DECLARE @NetValueTotal  NUMERIC(24, 10)  --净值之和
				DECLARE @ATypeTotal		 NUMERIC(24, 10)  --固定资产项目合计
				
				---取出净值之和(带上结转过来的已折旧的卡片)
				SELECT @NetValueTotal=ISNULL(SUM(ISNULL(NetValue,0)),0)
				FROM dbo.AC_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
				WHERE AssetsState=1 OR AssetsState=4
					
				---未开账情况下,查看期初表
				IF (EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@MxSTypeId AND IsUse = 0) )
					BEGIN
						IF @isac = 1
						BEGIN				
						---取出固定资产科目之和
						SELECT @A=ISNULL(SUM(ISNULL(iniTotal,0)),0)
						FROM dbo.Ac_IniAccount ab 
						JOIN (  SELECT DISTINCT ac.AssertATypeId AS typeid    
								FROM AC_AssetsCards ac 
								JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
								WHERE AssetsState=1 OR AssetsState=4
							 ) ac  ON ab.ATypeId=ac.typeid
						 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
						
						---取出累计折旧科目之和
						SELECT @B=ISNULL(SUM(ISNULL(iniTotal,0)),0)
						FROM dbo.Ac_IniAccount ab 
						JOIN (  SELECT DISTINCT ac.DepATypeId AS typeid    
								FROM AC_AssetsCards ac 
								JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
								WHERE AssetsState=1 OR AssetsState=4
							 ) ac  ON ab.ATypeId=ac.typeid
						 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
						
						---取出减值准备科目之和
						SELECT @C=ISNULL(SUM(ISNULL(iniTotal,0)),0)
						FROM dbo.Ac_IniAccount ab 
						JOIN (  SELECT DISTINCT ac.DevalueATypeId AS typeid    
								FROM AC_AssetsCards ac 
								JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
								WHERE AssetsState=1 OR AssetsState=4
							 ) ac  ON ab.ATypeId=ac.typeid
						 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
						END
					END
				---开账情况下,查看ac_balance表
				ELSE   
					BEGIN
						---@datetime 开账情况下，如果系统时间落在该期间，取系统时间
						DECLARE @tempdateTime DATETIME= CONVERT(varchar(100), GETDATE(), 23)  --历史记录中初始化的业务时间
						IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FYear=@FYear AND FPeriod=@FPeriod AND @tempdateTime>=FBegin AND @tempdateTime<=FEnd)
						       SET @DateTime=@tempdateTime
						ELSE
							SELECT @DateTime=FEnd FROM dbo.Ac_Period WHERE FYear=@FYear AND FPeriod=@FPeriod
						
						
						---判断下卡片日期
						IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AssetsCards ac 
									JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
									JOIN (SELECT FBegin AS b FROM dbo.Ac_Period WHERE FYear=@Fyear AND FPeriod=@Fperiod) t ON ac.InAccountDate>=t.b
									WHERE AssetsState=1)
							BEGIN
								IF @version=2 --A8
									SET @ReturnValue= '分支机构【'+@MxSFullName+'】期初固定资产卡片入账日期大于当前会计期起始日期，不能进行初始化'
								ELSE IF @version=1 --v3
									SET @ReturnValue= '期初固定资产卡片入账日期大于当前会计期起始日期，不能进行初始化'
								SET @Re=-3
								CLOSE FixedSType_Cursor
								DEALLOCATE FixedSType_Cursor
								RETURN @Re	
							END
						
						--2014.04.09非总账，开账分支，初始化时比较固定资产卡片与相应固定资产项目
						IF @isac = 0
						BEGIN
							--初始卡片净值总计
							SELECT @NetValueTotal=ISNULL(SUM(ISNULL(NetValue,0)),0)
							FROM dbo.AC_AssetsCards
							
							--固定资产项目总计
							SELECT @ATypeTotal = SUM(Total) 
							FROM dbo.Ac_Items T1
								INNER JOIN dbo.AType_Total T2 ON T1.nId = T2.ATypeID
							WHERE nTypeId LIKE '0000100002%' AND T2.STypeID = @MxSTypeId
							
							--两值不等，返回提示
							IF @NetValueTotal <> @ATypeTotal
							BEGIN
								SET @ReturnValue= @MxSTypeId   --返回分支机构id
								SET @Re = -1
								CLOSE FixedSType_Cursor
								DEALLOCATE FixedSType_Cursor
								RETURN @Re
							END
						END
						ELSE--总账下
						BEGIN
							---取出固定资产科目之和
							SELECT @A=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
							FROM dbo.Ac_Balance ab 
							JOIN (  SELECT DISTINCT ac.AssertATypeId AS typeid    
									FROM AC_AssetsCards ac 
									JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
									WHERE AssetsState=1 OR AssetsState=4
								 ) ac  ON ab.ATypeId=ac.typeid
							 WHERE ab.STypeId=@MxSTypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
						    
							---取出累计折旧科目之和
							SELECT @B=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
							FROM dbo.Ac_Balance ab 
							JOIN (  SELECT DISTINCT ac.DepATypeId AS typeid    
									FROM AC_AssetsCards ac 
									JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
									WHERE AssetsState=1 OR AssetsState=4
								 ) ac  ON ab.ATypeId=ac.typeid
							 WHERE ab.STypeId=@MxSTypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
							 
							---取出减值准备科目之和
							SELECT @C=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
							FROM dbo.Ac_Balance ab 
							JOIN (  SELECT DISTINCT ac.DevalueATypeId AS typeid    
									FROM AC_AssetsCards ac 
									JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
									WHERE AssetsState=1 OR AssetsState=4
								 ) ac  ON ab.ATypeId=ac.typeid
							 WHERE ab.STypeId=@MxSTypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
						END
					END   
			    
				IF @NetValueTotal!=@A-@B-@C AND @isac = 1
					BEGIN                                
						SET @ReturnValue= @MxSTypeId   --返回分支机构id
						SET @Re=-1            
						CLOSE FixedSType_Cursor
						DEALLOCATE FixedSType_Cursor
						RETURN @Re	  
					END
				
				IF @@ERROR <> 0
				BEGIN						
					CLOSE FixedSType_Cursor
					DEALLOCATE FixedSType_Cursor
					SET @Re=-2                                                                        
					RETURN @Re	
				END		
				
				---特殊情况处理
				IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards aa JOIN dbo.Ac_AssetsCategory aac ON aa.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId WHERE aa.AssetsState=4)
					BEGIN
						 DECLARE @tempFperiod INT,@tempFyear INT
						 IF @Fperiod=1
							BEGIN
								SET @tempFperiod=12
								SET @tempFyear=@Fyear-1
							END
						ELSE 
							BEGIN
								SET @tempFperiod=@Fperiod-1
								SET @tempFyear=@Fyear
							END
						IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AssetsCards ac 
								   JOIN dbo.Ac_AssetsCategory acc ON ac.CategoryId=acc.Id AND acc.StypeId=@MxSTypeId
								   JOIN dbo.Ac_DepreciationPlan ap ON ac.Id=ap.AssetCardId AND ap.FPeriod=@tempFperiod AND ap.FYear=@tempFyear AND PlanType=1 AND PlanState=0
								   WHERE ac.AssetsState=4)
							BEGIN
								IF @isReCreate=0
									BEGIN
										SET @ReturnValue= @MxSTypeId   --返回分支机构id
										SET @Re=-8            
										CLOSE FixedSType_Cursor
										DEALLOCATE FixedSType_Cursor
										RETURN @Re	
									END 
							END
					END
				
				---初始卡片生成折旧表，并记录卡片历史记录(已折旧卡片只保存历史记录)
				INSERT INTO #tempCard(cardid, orderid, stypeid,cardstate)
				SELECT aa.id AS cardid,ROW_NUMBER() over(ORDER BY aa.id) AS orderid,@MxSTypeId,aa.AssetsState
				FROM dbo.Ac_AssetsCards aa
				JOIN dbo.Ac_AssetsCategory aac ON aa.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
				WHERE AssetsState=1 OR AssetsState=4
				
				SELECT @Count=COUNT(*) FROM #tempCard WHERE stypeid=@MxSTypeId
				--select * from #tempCard
				DECLARE @state  INT
				WHILE @index <= @Count
					BEGIN
						SELECT @tempcardid=cardid,@state=cardstate FROM #tempCard WHERE orderid=@index AND stypeid=@MxSTypeId
					 
						
						---生成折旧表
						IF @state=1
							EXEC Gp_CreateDepreciationPlan @tempcardid,1
		                
		                IF @state=4 AND @isReCreate=1
							BEGIN
								--先删除
								DELETE  dbo.Ac_DepreciationPlan WHERE AssetCardId=@tempcardid
								--后重新生成
								EXEC Gp_CreateDepreciationPlan @tempcardid,1
							END
							
		                
						---记录卡片历史记录
						DECLARE @tempRe VARCHAR(max)
						EXEC Gp_SaveAssetsCardHistory  @MxSTypeId,@tempcardid,@EtypeID,@DateTime,0,0,0,@tempRe OUT
						
						SET @index = @index + 1
					END
		            
				SET @index=1 
				 
				----记录初始化日期
				IF EXISTS (SELECT TOP 1 1 FROM Ac_FixedAssetsInit_Stype WHERE stypeid=@MxSTypeId)
				  UPDATE Ac_FixedAssetsInit_Stype SET fyear=@FYear,fperiod=@FPeriod,etypeid=@EtypeID,InitDate=@DateTime WHERE stypeid=@MxSTypeId
				ELSE 
				  INSERT INTO Ac_FixedAssetsInit_Stype(stypeid,fyear,fperiod,etypeid,InitDate)
				  SELECT @MxSTypeId,@Fyear,@FPeriod,@EtypeID,@DateTime
				
				----修改分支机构状态(包括它下面的非独立核算机构)
				 UPDATE Stype SET IfAssetsIni=1 WHERE  VerifyID=@MxSTypeId
				
				IF @isac = 1
				BEGIN
				
					--导入相关会计科目、凭证模板、插入业务类型对应默认模板
					
					IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId= @MxSTypeId)
					BEGIN
						SELECT @Atypeid = 
						CASE WHEN @subid = 1 THEN '0000100028,0000100043,000020000900001,000010002800002,0000100036,000010004300002,000010004300002,00002000090000100001,00002000090000100005,0000300005,0000300005,0000300012'
							WHEN @subid = 2 THEN '0000100021,0000100024,0000100032,0000200006,0000300004,0000300011'
							WHEN @subid = 28 THEN '0000100025,0000100033,0000100042,0000200007,0000300005,0000300013,0000300014'
						END
						--EXEC GP_DistributeAccount 1,@MxSTypeId,@Atypeid	
					END
					
					EXEC dbo.GP_ImportVoucherTemplate_Inner @EtypeID,@MxSTypeId,@SubId,1,@OutValue OUTPUT
				END
				
				UPDATE dbo.Ac_AssetBusinessType
					SET Atid = T2.AtId
					FROM dbo.Ac_AssetBusinessType T1
						INNER JOIN dbo.Ac_Auditing_Template T2 ON T1.AuditType = T2.AuditType AND T1.STypeId = T2.STypeId
					WHERE T1.STypeId = @MxSTypeId
				
				 
				 ---修改卡片状态（只处理初始状态的）
				 UPDATE ac SET AssetsState=3 FROM dbo.Ac_AssetsCards ac JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId WHERE AssetsState=1
				
				FETCH NEXT FROM FixedSType_Cursor INTO @MxSTypeId
			END
		
	END
	
CLOSE FixedSType_Cursor
DEALLOCATE FixedSType_Cursor
IF @OutValue<>0  --生成凭证又失败的地方
	SET @Re=1
	
RETURN @Re

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	

 



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/05/14
	Description	: 固定资产分支机构初始化数据校验
*/
CREATE PROCEDURE Gp_FixedAssetsIniVerifyData
(
	@STypeId		VARCHAR(50),		--	分支机构
	@Flag			INT                 -- 1 初始化用 2 开账用 3 期末结账
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @FYear			VARCHAR(10),
		@FPeriod		INT,
		@Cid			INT
		
SELECT @Cid=cid FROM dbo.Ac_Currency WHERE Sysrow=1
--获取指定分支机构当前年度,财务期间	
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @STypeId)
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @stypeid
ELSE 
	BEGIN
		SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName='fyear'
		SELECT @FPeriod=SubValue FROM dbo.sysdata WHERE SubName='fperiod'
	END

DECLARE @A  NUMERIC(24, 10) 
DECLARE @B  NUMERIC(24, 10) 
DECLARE @C  NUMERIC(24, 10) 
DECLARE @NetValueTotal  NUMERIC(24, 10) 

--根据flag的不同，取卡片的状态不同
CREATE TABLE #tempACState
(
	AssetsState INT
)

---取出净值之和
IF @Flag=1          --初始化
	BEGIN
		SELECT @NetValueTotal=ISNULL(SUM(ISNULL(NetValue,0)) ,0)
		FROM dbo.AC_AssetsCards ac
		JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
		WHERE AssetsState=1 OR AssetsState=4
		
		INSERT INTO #tempACState
		SELECT 1
		UNION 
		SELECT 4
	END
	
ELSE IF @Flag=2     --开账
	BEGIN
		SELECT @NetValueTotal=ISNULL(SUM(ISNULL(NetValue,0)),0)
		FROM dbo.AC_AssetsCards ac
		JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
		WHERE AssetsState=3 OR AssetsState=4
		
		INSERT INTO #tempACState
		SELECT 3
		UNION 
		SELECT 4
	END
	
ELSE        --期末过账
	BEGIN
		--获取固定资产当前期间开始时间
		DECLARE @AssetEnd	DATE
		SELECT @AssetEnd=FEnd FROM dbo.Ac_Period WHERE FYear=@FYear AND FPeriod=@FPeriod

		   SELECT DISTINCT A.*
            INTO #s 
      FROM dbo.Ac_AssetsCards_History a 
      INNER JOIN dbo.AC_AssetsCards ac ON AC.Id=A.AssertsCardId AND AC.AssetsState IN(3,4) 
      --INNER JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=A.STypeId AND aac.StypeId=@STypeId
      INNER JOIN dbo.Ac_AssetsCategory aac ON aac.StypeId=@STypeId AND AAC.Id = AC.CategoryId
      INNER JOIN SType S ON S.TypeId = A.STypeId AND S.VerifyID = aac.STYPEID
      WHERE 
        a.BusinessDate<=@AssetEnd 
        AND A.AuditType !=-4  ------这里要排除掉-4的情况，-4是业务月结存的时候写入的数据，月结存的时候净值取的是结存期间的值，而不是财务系统中卡片最新折旧后的净值
        AND NOT EXISTS (SELECT 1 FROM Ac_AssetsCards_History b WHERE b.AssertsCardId= a.AssertsCardId AND b.DepreciationMonth>a.DepreciationMonth  AND b.BusinessDate<=@AssetEnd  AND AuditType !=-4) 
          

        SELECT @NetValueTotal=ISNULL(SUM(a.NetValue),0) FROM #s a
        INNER JOIN (              
           SELECT AssertsCardId,DepreciationMonth,MIN(id)id  FROM #s GROUP BY AssertsCardId,DepreciationMonth HAVING COUNT(*)>1
           UNION ALL
           SELECT AssertsCardId,DepreciationMonth,MIN(id)id  FROM #s GROUP BY AssertsCardId,DepreciationMonth HAVING COUNT(*)=1)b
        ON a.AssertsCardId=b.AssertsCardId AND a.DepreciationMonth=b.DepreciationMonth AND a.id=b.id

        DROP TABLE #s
		INSERT INTO #tempACState
		SELECT 3 
		UNION 
		SELECT 4
	END
	
	    
---未开账情况下,查看期初表
IF EXISTS(SELECT TOP 1 1 FROM SType_Config C,SType_UserConfig U 
		  WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND ISNULL(U.STypeID,'') = @STypeId AND U.Value='0')
	OR NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType_UserConfig WHERE StypeId=@STypeId)
	BEGIN
		---取出固定资产科目之和
		SELECT @A=ISNULL(SUM(ISNULL(iniTotal,0)),0)
		FROM dbo.Ac_IniAccount ab 
		JOIN (  SELECT DISTINCT ac.AssertATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  ON ab.ATypeId=ac.typeid
		 WHERE ab.STypeId=@STypeId AND ab.Cid=@Cid AND FYear=@FYear
		
		---取出累计折旧科目之和
		SELECT @B=ISNULL(SUM(ISNULL(iniTotal,0)),0)
		FROM dbo.Ac_IniAccount ab 
		JOIN (  SELECT DISTINCT ac.DepATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  ON ab.ATypeId=ac.typeid
		 WHERE ab.STypeId=@STypeId AND ab.Cid=@Cid AND FYear=@FYear
		
		---取出减值准备科目之和
		SELECT @C=ISNULL(SUM(ISNULL(iniTotal,0)),0)
		FROM dbo.Ac_IniAccount ab 
		JOIN (  SELECT DISTINCT ac.DevalueATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  ON ab.ATypeId=ac.typeid
		 WHERE ab.STypeId=@STypeId AND ab.Cid=@Cid AND FYear=@FYear
		 
		  ----取出结果集
		SELECT 0 AS Flag,'A' AS Result,@A AS VALUE
			UNION ALL 
		SELECT 0 AS Flag,'B' AS Result,@B AS VALUE
			UNION ALL
		SELECT 0 AS Flag,'C' AS Result,@C AS VALUE
		    UNION ALL
		SELECT 0 AS Flag,'D' AS Result,@A-@B-@C AS VALUE 
			UNION ALL
		SELECT 0 AS Flag,'Net' AS Result,@NetValueTotal AS VALUE
			UNION ALL
		SELECT 1 AS Flag, aa.FullName AS Result,ISNULL(SUM(ISNULL(iniTotal,0)),0) AS VALUE    
		FROM 
			 (  SELECT DISTINCT ac.AssertATypeId AS typeid    
				FROM dbo. Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  
		 JOIN dbo.Ac_Account aa ON aa.StypeId=@STypeId AND ac.typeid=aa.TypeId 
		 LEFT JOIN dbo.Ac_IniAccount ab ON ab.ATypeId=ac.typeid AND ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
		 GROUP BY aa.FullName
			UNION ALL
		SELECT 2 AS Flag, aa.FullName AS Result,ISNULL(SUM(ISNULL(iniTotal,0)),0) AS VALUE    
		FROM 
			(  SELECT DISTINCT ac.DepATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  
		 JOIN dbo.Ac_Account aa ON aa.StypeId=@STypeId AND ac.typeid=aa.TypeId 
		 LEFT JOIN dbo.Ac_IniAccount ab ON ab.ATypeId=ac.typeid AND ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
		 GROUP BY aa.FullName
			UNION ALL
		SELECT 3 AS Flag, aa.FullName AS Result,ISNULL(SUM(ISNULL(iniTotal,0)),0) AS VALUE    
		FROM 
		     (  SELECT DISTINCT ac.DevalueATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  
		 JOIN dbo.Ac_Account aa ON aa.StypeId=@STypeId AND ac.typeid=aa.TypeId 
		 LEFT JOIN dbo.Ac_IniAccount ab ON ab.ATypeId=ac.typeid AND ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
		 GROUP BY aa.FullName
	END
ELSE 
	BEGIN
		---取出固定资产科目之和
		SELECT @A=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
		FROM dbo.Ac_Balance ab 
		JOIN (  SELECT DISTINCT ac.AssertATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  ON ab.ATypeId=ac.typeid
		 WHERE ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
	    
		---取出累计折旧科目之和
		SELECT @B=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
		FROM dbo.Ac_Balance ab 
		JOIN (  SELECT DISTINCT ac.DepATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  ON ab.ATypeId=ac.typeid
		 WHERE ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
		 
		---取出减值准备科目之和
		SELECT @C=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
		FROM dbo.Ac_Balance ab 
		JOIN (  SELECT DISTINCT ac.DevalueATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  ON ab.ATypeId=ac.typeid
		 WHERE ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear		
	    
	    ----取出结果集
		SELECT 0 AS Flag,'A' AS Result,@A AS VALUE
			UNION ALL 
		SELECT 0 AS Flag,'B' AS Result,@B AS VALUE
			UNION ALL
		SELECT 0 AS Flag,'C' AS Result,@C AS VALUE
		    UNION ALL
		SELECT 0 AS Flag,'D' AS Result,@A-@B-@C AS VALUE 
			UNION ALL
		SELECT 0 AS Flag,'Net' AS Result,@NetValueTotal AS VALUE
			UNION ALL
		SELECT 1 AS Flag, aa.FullName AS Result,ISNULL(SUM(ISNULL(FEndBalance,0)),0) AS VALUE    
		FROM  
			(  SELECT DISTINCT ac.AssertATypeId AS typeid    
				FROM Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  
		 JOIN dbo.Ac_Account aa ON aa.StypeId=@STypeId AND ac.typeid=aa.TypeId 
		 LEFT JOIN dbo.Ac_Balance ab ON ab.ATypeId=ac.typeid AND ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
		 GROUP BY aa.FullName
			UNION ALL
		SELECT 2 AS Flag, aa.FullName AS Result,ISNULL(SUM(ISNULL(FEndBalance,0)),0) AS VALUE    
		FROM  
		    (  SELECT DISTINCT ac.DepATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  
		 JOIN dbo.Ac_Account aa ON aa.StypeId=@STypeId AND ac.typeid=aa.TypeId 
		 LEFT JOIN dbo.Ac_Balance ab ON ab.ATypeId=ac.typeid AND ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
		 GROUP BY aa.FullName
			UNION ALL
		SELECT 3 AS Flag, aa.FullName AS Result,ISNULL(SUM(ISNULL(FEndBalance,0)),0) AS VALUE    
		FROM  
		    (  SELECT DISTINCT ac.DevalueATypeId AS typeid    
				FROM  Ac_AssetsCards ac 
				JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
				JOIN #tempACState t ON ac.AssetsState=t.AssetsState
			 ) ac  
		 JOIN dbo.Ac_Account aa ON aa.StypeId=@STypeId AND ac.typeid=aa.TypeId 
		 LEFT JOIN dbo.Ac_Balance ab ON ab.ATypeId=ac.typeid AND ab.STypeId=@STypeId AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
		 GROUP BY aa.FullName
	END	    
	   DROP TABLE #tempACState
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2013-5-24
	描述：业务冻结
*/
CREATE PROCEDURE Gp_FrozeBusiness
(
	@stypeid	Varchar(50),
	@frozedate	DATETIME			
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #stype(typeid varchar(50))
INSERT INTO #stype
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,'00001')

BEGIN TRAN froze
MERGE FrozeBusiness AS target
USING #stype AS source
ON TARGET.stypeid=source.typeid
WHEN MATCHED
THEN UPDATE SET TARGET.frozedate=@frozedate
WHEN NOT MATCHED
THEN INSERT(stypeid,frozedate)VALUES(SOURCE.typeid,@frozedate);

IF @@ERROR<>0 OR @@ROWCOUNT=0
BEGIN
	RAISERROR('业务冻结失败！',16,1)
	ROLLBACK TRAN froze
	RETURN
END
COMMIT TRAN froze

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：张陈仁
	日期：2011-7-19
	描述：全局打印控制
*/
CREATE  PROCEDURE Gp_FullPrintControl
(
    @printCountFiledName      varchar(100)='fullPrintCount',  --打印次数字段名
    @printPasswordFiledName   varchar(100)='fullPrintPassword',  --打印控制解锁密码
    @printCount               int,           --打印次数值
    @printPassword            varchar(200)   --解锁密码值
)
--@encode$--

AS
SET NOCOUNT ON 

--判断打印次数是否存在相关记录
IF NOT EXISTS (SELECT ConfigName FROM Userconfig WHERE ConfigName=@printCountFiledName)
  BEGIN 
      INSERT INTO Userconfig (ConfigName,Value) VALUES (@printCountFiledName,@printCount)
  END
ELSE
  BEGIN
      UPDATE Userconfig SET Value=@printCount WHERE ConfigName=@printCountFiledName
  END
  
--判断解锁密码是否存在相关记录
IF NOT EXISTS (SELECT ConfigName FROM Userconfig WHERE ConfigName=@printPasswordFiledName)
  BEGIN 
      INSERT INTO Userconfig (ConfigName,Value) VALUES (@printPasswordFiledName,@printPassword)
  END
ELSE
  BEGIN
      UPDATE Userconfig SET Value=@printPassword WHERE ConfigName=@printPasswordFiledName
  END   


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

CREATE PROCEDURE Gp_Fz_Base
(
	@baseinfo	VARCHAR(MAX),
	@flag		INT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL NVARCHAR(4000)

IF @flag = 1
BEGIN
	SET @SQL = 'TRUNCATE TABLE dbo.FZ_Color
				INSERT INTO dbo.FZ_Color(ColorID,ColorName,Del) SELECT a * 2 AS colorid,''红'' + CAST(a * 12 AS VARCHAR(10)) AS colorname,0 AS Del FROM dbo.f_split_table('''+@baseinfo+''',''.'') WHERE nid = 1
				INSERT INTO dbo.FZ_Color(ColorID,ColorName,Del) SELECT a * 4 AS colorid,''橙'' + CAST(a * 24 AS VARCHAR(10)) AS colorname,0 AS Del FROM dbo.f_split_table('''+@baseinfo+''',''.'') WHERE nid = 2
				INSERT INTO dbo.FZ_Color(ColorID,ColorName,Del) SELECT a * 6 AS colorid,''黄'' + CAST(a * 36 AS VARCHAR(10)) AS colorname,0 AS Del FROM dbo.f_split_table('''+@baseinfo+''',''.'') WHERE nid = 3
				INSERT INTO dbo.FZ_Color(ColorID,ColorName,Del) SELECT a * 8 AS colorid,''绿'' + CAST(a * 48 AS VARCHAR(10)) AS colorname,0 AS Del FROM dbo.f_split_table('''+@baseinfo+''',''.'') WHERE nid = 4 '
	EXEC(@SQL)
END
ELSE
BEGIN
	EXEC('EXEC Gp_DlExtTabTr')
	DECLARE @wDefine	VARCHAR(MAX),@ColorId1	VARCHAR(MAX),@ColorId2	VARCHAR(MAX),@ColorId3	VARCHAR(MAX),@ColorId4	VARCHAR(MAX),
			@wDefineV   VARCHAR(MAX),@ColorId1V	VARCHAR(MAX),@ColorId2V	VARCHAR(MAX),@ColorId3V	VARCHAR(MAX),@ColorId4V	VARCHAR(MAX)

	SET @SQL = 'EXEC Web_CheckSysValue 3,@wDefine  OUTPUT '
	EXEC sp_executesql @SQL, N'@wDefine varchar(max) out', @wDefineV OUT
	
	SET @SQL = 'EXEC Web_CheckSysValue 4,@ColorId1 OUTPUT'
	EXEC sp_executesql @SQL, N'@ColorId1 varchar(max) out', @ColorId1V OUT
	
	SET @SQL = 'EXEC Web_CheckSysValue 5,@ColorId2 OUTPUT'
	EXEC sp_executesql @SQL, N'@ColorId2 varchar(max) out', @ColorId2V OUT
	
	SET @SQL = 'EXEC Web_CheckSysValue 6,@ColorId3 OUTPUT'
	EXEC sp_executesql @SQL, N'@ColorId3 varchar(max) out', @ColorId3V OUT
	
	SET @SQL = 'EXEC Web_CheckSysValue 7,@ColorId4 OUTPUT'
	EXEC sp_executesql @SQL, N'@ColorId4 varchar(max) out', @ColorId4V OUT
		
	IF @wDefineV <> LEFT(@ColorId1V + @ColorId2V + @ColorId3V + @ColorId4V,LEN(@ColorId1V + @ColorId2V + @ColorId3V + @ColorId4V) - 1)
		RETURN -1		
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_Fz_Control]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Fz_Control]
GO

/*
	
*/
CREATE  PROCEDURE Gp_Fz_Control
(
	@rFlag			VARCHAR(MAX),
	@rInfo1			VARCHAR(MAX),
	@rInfo2			VARCHAR(MAX),
	@rInfo3			VARCHAR(MAX),
	@rNewAddress	VARCHAR(MAX),
	@rDsql			VARCHAR(MAX),
	@ntype			VARCHAR(MAX),
	@isIntelNet		VARCHAR(MAX),
	@rValue1		VARCHAR(MAX) OUTPUT,
	@rValue2		VARCHAR(MAX) OUTPUT,
	@rValue3		VARCHAR(MAX) OUTPUT,
	@rValue4		VARCHAR(MAX) OUTPUT,
	@rValue5		VARCHAR(MAX) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)

IF @ntype = '1'
BEGIN
	TRUNCATE TABLE dbo.Fz_Size
	SET @SQL = ' UPDATE SYSDATA SET subvalue = ''' + @rFlag + '''   WHERE SubNo  =   720'	
	SET @SQL = @SQL + ' UPDATE SYSDATA SET subvalue = ''' + @rNewAddress + '''   WHERE SubNo  =   722'	
	SET @SQL = @SQL + '	UPDATE userconfig SET value = CONVERT(VARCHAR(10),GETDATE(),120) WHERE configname = ''curdate'''							
	SET @SQL = @SQL + ' EXEC Gp_Fz_Base ''' + @rNewAddress	+ ''',1'
	SET @SQL = @SQL + ' TRUNCATE TABLE dbo.Fz_Size 
						INSERT INTO dbo.Fz_Size(SizeID,SizeName,Del)VALUES(719, CONVERT(VARCHAR(10),GETDATE(),120), 0)
						INSERT INTO dbo.Fz_Size(SizeID,SizeName,Del)VALUES(720, ''' + @rFlag + ''', 0)
						INSERT INTO dbo.Fz_Size(SizeID,SizeName,Del)VALUES(722, 1, 0)
						INSERT INTO dbo.Fz_Size(SizeID,SizeName,Del)VALUES(754, ''' + @isIntelNet + ''', 0)'
	--PRINT(@SQL)
	EXEC(@SQL)
END
ELSE IF @ntype = '2'
BEGIN
	SET @rValue1 = 'http://' + @rInfo1 + '/GraspWebServer/GWS.asmx'
	SET @rValue2 = 'MainService.getVersion()'
	SET @rValue3 = 'Ac_Define.uf'
	SET @rValue4 = 'AppUtils.uData()'
	SET @rValue5 = 'StockUtils.getFzColor()'
END
	



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_GenIniBtype_ArAPTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_GenIniBtype_ArAPTotal]
GO

CREATE PROCEDURE GP_GenIniBtype_ArAPTotal
(
	@STypeId		VARCHAR(50)		--	分支机构
)

--@encode$--
AS
BEGIN

	DECLARE @ExpenseToAr INT=0
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'	
	
	CREATE TABLE #t
	(
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		dtypeid VARCHAR(50),
		etypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		APTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		YFTotal00  NUMERIC(24, 10) ,
		FCTotal00  NUMERIC(24, 10) ,
		GRIRTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10) ,
		nAPTotal00  NUMERIC(24, 10) ,
		nYSTotal00  NUMERIC(24, 10) ,
		nYFTotal00  NUMERIC(24, 10) ,
		NFCTotal00  NUMERIC(24, 10) ,
		NGRIRTotal00  NUMERIC(24, 10) 
	)
	
	INSERT INTO #t
	( 
			stypeid,
			btypeid,
			dtypeid,
			etypeid,
			cid,
			ARTotal00,
			APTotal00,
			YSTotal00,
			YFTotal00,
			FCTotal00,
			GRIRTotal00,
			nARTotal00,
			nAPTotal00,
			nYSTotal00,
			nYFTotal00,
			NFCTotal00,
			NGRIRTotal00
	)
	SELECT	stypeid,
			btypeid,
			dtypeid,
			etypeid,
			cid ,
			SUM(ARTotal00),
			SUM(APTotal00),
			SUM(YSTotal00),
			SUM(YFTotal00),
			SUM(FCTotal00),
			SUM(GRIRTotal00),
			SUM(nARTotal00),
			SUM(nAPTotal00),
			SUM(nYSTotal00),
			SUM(nYFTotal00),
			SUM(NFCTotal00),
			SUM(NGRIRTotal00)
	FROM
	(
		SELECT	stypeid ,
				btypeid ,
				cid ,
				DTypeId,
				etypeid,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					ELSE 0 
				END AS artotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0) 
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)) 
					ELSE 0 
				END AS aptotal00,
				CASE WHEN billtype =189 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS ystotal00,
				CASE WHEN billtype =190 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS yftotal00,
				0 AS FCTotal00,
				0 AS  GRIRTotal00,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0) 
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0) )
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0) ) 
					ELSE 0 
				END AS nartotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)  
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0) 
					 WHEN BillType IN (66,6,150,151) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0) ) 
					ELSE 0 
				END AS naptotal00,
				CASE WHEN billtype =189 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nystotal00,
				CASE WHEN billtype =190 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nyftotal00,
				0 AS NFCTotal00,
				0 AS  NGRIRTotal00
		FROM dbo.BillIndex
		WHERE	BillType IN(4,66,11,12,45,46,85,93,141,148,149,160,167,168,172,181,6,34,36,84,145,150,151,161,170,189,190,213,212,312)
				AND IsIni=1 AND stypeid=@STypeId
		UNION ALL
		SELECT  b.stypeid ,
				a.btypeid ,
				b.cid ,
				b.DTypeId,
				b.etypeid,
				CASE WHEN b.billtype = 116
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0) 
					 WHEN b.billtype = 115
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0) )
					ELSE 0
				END AS artotal00,
				CASE WHEN b.billtype = 128
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0) 
					 WHEN b.billtype = 129
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0) )
					 ELSE 0
				END AS aptotal00,
				0 AS ystotal00,
				0 AS yftotal00,
				0 AS FCTotal00,
				0 AS GRIRTotal00,
				CASE WHEN b.billtype = 116
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0) 
					 WHEN b.billtype = 115
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0) )
					ELSE 0
				END AS nartotal00,
				CASE WHEN b.billtype = 128
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					 ELSE 0
				END AS naptotal00,
				0 AS nystotal00,
				0 AS nyftotal00,
				0 AS NFcTotal00,
				0 AS NGRIRTotal00
		FROM	AdDebtBill a 
		INNER JOIN billindex b ON a.BillNumberId =b.BillNumberId
		WHERE	BillType IN(115,116,128,129)
				AND IsIni=1 AND b.stypeid=@STypeId
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   B.DTypeId,
			   B.etypeid,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=402
				   THEN dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   CASE WHEN B.BillType=402
					THEN dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice)
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
				
		FROM SendBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.stypeid=@STypeId
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   B.DTypeId,
			   B.etypeid,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=403
				   THEN -dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice)
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   CASE WHEN B.BillType=403
					THEN -dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice)
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
		FROM SendBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.stypeid=@STypeId
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   B.DTypeId,
			   B.etypeid,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=400
				    THEN CASE WHEN A.InvoiceQty=0
						 THEN A.Total
					ELSE dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.DiscountPrice)
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=400
				    THEN CASE WHEN A.InvoiceQty=0
						 THEN A.NTotal
				    ELSE dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.NDiscountPrice)
				    END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.stypeid=@STypeId
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   B.DTypeId,
			   B.etypeid,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.Total
					ELSE dbo.F_RoundTotal(-(A.Qty-A.InvoiceQty)*A.DiscountPrice)
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.NTotal
					ELSE dbo.F_RoundTotal(-(A.Qty-A.InvoiceQty)*A.NDiscountPrice)
					END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.stypeid=@STypeId
		
		
		UNION ALL
		SELECT 
			  B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  B.DTypeID,
			  B.ETypeID,
			  CASE WHEN B.BillType=405
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.BillType=405
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM ReceiptBillIndex B 
		WHERE  B.IsIni=1 AND stypeid=@STypeId
		UNION ALL
		SELECT 
		B.Stypeid,
			  B.BTypeID,
			  B.CID, 
			  B.DTypeID,
			  B.ETypeID,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.totalmoney-b.CompleteTotal-b.ChargeOffTotal
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.ChargeOffType IN (3,4)
				   THEN B.totalmoney-b.CompleteTotal-b.ChargeOffTotal
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN  B.NTotalMoney-b.nCompleteTotal-b.nChargeOffTotal
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.ChargeOffType IN (3,4)
				   THEN  B.NTotalMoney-b.nCompleteTotal-b.nChargeOffTotal
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM dbo.BillIndex B 
		 WHERE B.BillType= 450 AND B.IsIni=1 AND stypeid=@STypeId
	) total
	GROUP BY stypeid,btypeid,DTypeId,etypeid,cid
	
	DELETE IniBType_ArApTotal WHERE stypeid=@STypeId;
	INSERT INTO IniBType_ArApTotal(
			  StypeId,BtypeId,DtypeId,EtypeId,
			  ARTotal00,
			  APTotal00,
			  YSTotal00,
			  YFTotal00,
			  nARTotal00,
			  nAPTotal00,
			  nYSTotal00,
			  nYFTotal00,
			  CId,
			  FCTotal00,
			  NFCTotal00,
			  GRIRTotal00,
			  NGRIRTotal00
			  ) SELECT 
			  StypeId,
			  BtypeId,
			  DtypeId,
			  EtypeId,
			  ARTotal00,
			  APTotal00,
			  YSTotal00,
			  YFTotal00,
			  nARTotal00,
			  nAPTotal00,
			  nYSTotal00,
			  nYFTotal00,
			  Cid,
			  FCTotal00,
			  NFCTotal00,
			  GRIRTotal00,
			  NGRIRTotal00
			  FROM #t;
	          
	DROP TABLE #t;      

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE Gp_GenProcTestCase
(
	@procName	VARCHAR(1000),	--存储过程名称
	@flag		INT				--标识 1.ExecuteProcedure 2.ExecuteProcedureAndReturnValue 3.ExecuteProcedureAndOutputParameter
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Result
(
	Result		VARCHAR(8000)	
)

DECLARE @SQL 			VARCHAR(8000),
		@queryParams	VARCHAR(1000),
		@itemParams		VARCHAR(1000),
		@i				INT,
		@maxRowCount	INT,
		@url			VARCHAR(8000),
		@Service		VARCHAR(1000)

SET @i = 1

SELECT TOP 1 @SQL = _sql,@url = url FROM sqllog WHERE _sql LIKE '%'+@procName+'%' AND _sql NOT LIKE '%Gp_GenProcTestCase%' ORDER BY [ID] DESC

SELECT @Service = LEFT(A,LEN(A)-5) FROM DBO.F_Split(@url,'/') WHERE ISNULL(A,'')<>'' AND A LIKE '%.gspx'

INSERT INTO #Result(Result)VALUES('/// <summary>')
INSERT INTO #Result(Result)VALUES('/// ')
INSERT INTO #Result(Result)VALUES('/// '+CONVERT(VARCHAR(10),GetDate(),120))
INSERT INTO #Result(Result)VALUES('/// </summary>')
INSERT INTO #Result(Result)VALUES('public void '+@Service+'_Test()')
INSERT INTO #Result(Result)VALUES('{')
INSERT INTO #Result(Result)VALUES('	//'+@SQL)
INSERT INTO #Result(Result)VALUES(' 	IHashObject queryParams = new HashObject();')

IF @@ROWCOUNT <> 0
	BEGIN
		SELECT @maxRowCount = COUNT(*) FROM DBO.F_Split(@SQL,',')
		
		DECLARE queryCursor CURSOR FOR
			SELECT * FROM DBO.F_Split(@SQL,',')
		
		OPEN queryCursor
		
		FETCH NEXT FROM queryCursor INTO @queryParams
		
		WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @queryParams = RTRIM(LTRIM(REPLACE(@queryParams,'output','')))

				SET @queryParams = REPLACE(@queryParams,'NULL','''''')
		
				SET @itemParams = SUBSTRING(@queryParams,CHARINDEX('@',@queryParams)+1,LEN(@queryParams))
		
				SET @itemParams = REPLACE(@itemParams,'''','"')

				INSERT INTO #Result(Result)VALUES('	queryParams['+'"'+REPLACE(@itemParams,'=','"]=')+';')
		
				SET @i = @i + 1
		
				FETCH NEXT FROM queryCursor INTO @queryParams
			END
		
		CLOSE queryCursor
		DEALLOCATE queryCursor
	END

IF @flag = 1
	INSERT INTO #Result(Result)VALUES('	DataTable dt = AppUtilsFunction.ExecuteProcedure("'+@procName+'", queryParams);')
ELSE IF @flag = 2
	BEGIN
		INSERT INTO #Result(Result)VALUES(' int intReturnValue = 0;')
		INSERT INTO #Result(Result)VALUES('	AppUtilsFunction.ExecuteProcedureAndReturnValue("'+@procName+'", out intReturnValue, queryParams);')
	END
ELSE IF @flag = 3
	BEGIN
		INSERT INTO #Result(Result)VALUES('	IHashObject obj = null;')
		INSERT INTO #Result(Result)VALUES('	AppUtilsFunction.ExecuteProcedureAndOutputParameter("'+@procName+'", out obj, queryParams);')
	END
ELSE IF @flag = 4
	INSERT INTO #Result(Result)VALUES('int intReturnValue = AppUtilsFunction.ExecuteReturnValueProcedure("'+@procName+'", queryParams);')
ELSE IF @flag = 5
	BEGIN
		INSERT INTO #Result(Result)VALUES('	IHashObject obj = null;')
		INSERT INTO #Result(Result)VALUES('DataTable dt = DbHelper.ExecuteProcedureAndOutputParameter(procName, out obj, queryParams);')
	END
ELSE IF @flag=6
	BEGIN		
		INSERT INTO #Result(Result)VALUES('IHashObjectList list = DbHelper.ProcedureSelect(procName, queryParams);')
	END	
ELSE IF @flag=7
	BEGIN		
		INSERT INTO #Result(Result)VALUES('IHashObject list = DbHelper.ExecuteOutputParameterProcedure(procName, queryParams);')
	END		
	
INSERT INTO #Result(Result)VALUES('}')

SELECT * FROM #Result

DROP TABLE #Result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/31
	Description	:	获取系统预置科目表
*/

CREATE PROCEDURE GP_GetAcAccountSetList
--@encode$--
AS
SET NOCOUNT ON
SELECT	SubId, 
		case 
			when SubId < 10 then ('0000' + CAST( SubId as varchar(10))) 
			else ('000' + CAST( SubId as varchar(10))) 
		end as TypeId, 
		'00000' as ParId,
		FullName 
from	Ac_Account_Set_List
WHERE	IsVisible = 1

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_GetAccountCategroy]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[GP_GetAccountCategroy] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2012-06-14
----描述：查询会计科目辅助核算分类
----========================
CREATE    PROCEDURE [dbo].[GP_GetAccountCategroy]
(
	@Filter		VARCHAR(50)='',		--查询字符串
	@STypeID	VARCHAR(50) = '',	--分支机构ID	
	@ATypeID	VARCHAR(50)='',		--科目ID
	@Type		INT					--1:查询所有 2：查询指定科目
)
--@encode$--
AS

DECLARE 
	@SQL		VARCHAR(MAX)='',
	@IsUsed		INT=0				--判断指定科目是否被使用
	
DECLARE @Temp TABLE(TableName VARCHAR(200),STypeId VARCHAR(200),ATypeId VARCHAR(200))
INSERT INTO @Temp(TableName,STypeId,ATypeId)
EXEC GP_CheckAccountUsage @STypeID,@ATypeID
SELECT @IsUsed=@@ROWCOUNT

SET @SQL+='
SELECT  
	AscIds AS typeid, 
	UserCode, 
	FullName
FROM Ac_Assist_CheckItems
WHERE 
	(UserCode like ''%'+@filter+'%'' 
	OR FullName like ''%'+@filter+'%'')'
IF(@Type=2 AND @IsUsed>0)--指定科目剩余类别
	SET @SQL+='	AND AscIds NOT IN(SELECT AscIds FROM Ac_Account_Assist_CheckItems WHERE STypeId='''+@STypeID+''' AND ATypeId='''+@ATypeID+''' GROUP BY AscIds)'
	
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
	SET @SQL+='	AND AscIds<>1'
	
EXEC(@SQL)
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetAccountType]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_GetAccountType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--==========================================================
--BY:GLJ
--DATE:2016-09-01
--DESCRIPTION:判断该科目类型 1：往来:2：库存:3：固定资产
--==========================================================
CREATE PROC Gp_GetAccountType
(
	@STypeId		VARCHAR(50),	--分支机构id
	@ATypeId		VARCHAR(50),	--科目id
	@CId			INT,			--币种
	@Flag			INT,			--1：往来 2：库存 3：固定资产
	@OperatorID		VARCHAR(50)		--操作员id
)
--@encode$--

AS
SET NOCOUNT ON

DECLARE 
	@IsExists	INT=0,	--该科目是否是指定类型 
	@InputType	INT=1	--指定类型下 辅助核算格式是否正确

--查询包含非独立分支机构
DECLARE @SType TABLE(STypeId VARCHAR(50),VerifyID VARCHAR(50))
INSERT INTO @SType(STypeId,VerifyID) SELECT TypeId,VerifyID FROM SType WHERE VerifyID=@STypeId AND deleted=0
	
--1：往来科目
IF @Flag=1
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND TypeId=@ATypeId AND Deleted=0 AND SonNum=0 AND FContact=1)
			SET @IsExists=1
		
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Ascids>4)
			SET @InputType=0
	END
--2：库存科目	
IF @Flag=2
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='useatypefrom' AND SubValue='1') AND EXISTS(SELECT * FROM Base_InventoryTypeDetails D INNER JOIN @SType S ON S.STypeId=D.STypeID AND D.StockATypeID=@ATypeId)
			SET @IsExists=1
		ELSE IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='useatypefrom' AND SubValue='0') AND EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND ATypeID4=@ATypeId)
			SET @IsExists=1
		
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Ascids>1)
			SET @InputType=0
	END
--3：固定资产科目
IF @Flag=3 
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='assets' AND SubValue='1') AND EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards C INNER JOIN @SType S ON C.STypeId=S.STypeId AND C.AssetsState NOT IN(2,5) AND (C.AssertATypeId=@ATypeId OR C.DepATypeId=@ATypeId OR C.DevalueATypeId=@ATypeId))
			SET @IsExists=1
		
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Ascids>2)
			SET @InputType=0
	END
--返回结果 
SELECT @IsExists IsExists,@InputType InputType

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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










/*
	作者：谢吉康
	日期：2007-11-22
	描述：VIP消费调整和积分调整
	SELECT * FROM nVipAdjust

	declare @x varchar(1000)

	exec Gp_GetAdjustCode 'XFT','2008-9-5',@x output 

	print(@x)
*/
CREATE PROCEDURE Gp_GetAdjustCode
(
	@nFlag		varchar(100),
	@strDate	varchar(100),
	@BillCode	varchar(1000) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @TmpBillCode 	varchar(1000),
		@FlowNo			numeric(18,0),
		@Month			VARCHAR(10),
		@Day			VARCHAR(10)
		
----处理日期
IF LEN(MONTH(@strDate)) = 1
BEGIN
	SET @Month = '0'+CAST(MONTH(@strDate) AS VARCHAR)
END
ELSE
BEGIN
	SET @Month = MONTH(@strDate)
END
	
IF LEN(DAY(@strDate)) = 1
BEGIN
	SET @Day = '0'+CAST(DAY(@strDate) AS VARCHAR)	
END
ELSE
BEGIN
	SET @Day = CAST(DAY(@strDate) AS VARCHAR)	
END	
		
SET @strDate = CAST(YEAR(@strDate) AS VARCHAR)+'-'+@Month+'-'+@Day


--运算单据编号
IF @nFlag = 'XFT'
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM nVipAdjust WHERE nType = 1)
			SET @BillCode = 'XFT'+'-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-'+'0001'
		ELSE
			BEGIN
				SELECT	TOP 1 @TmpBillCode = BillCode FROM nVipAdjust WHERE nType = 1 AND BillDate=CONVERT(varchar(10),@strDate,120) ORDER BY BillNumberId DESC

				IF LEFT(RIGHT(@TmpBillCode,13),8)=Replace(CONVERT(varchar(10),@strDate,120),'-','')
					BEGIN
						IF RIGHT(@TmpBillCode,4)='9999'
							SET @BillCode = 'XFT'+'-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-'+'0001'
						ELSE
							BEGIN
								SET @FlowNo = CAST(RIGHT(@TmpBillCode,4) AS numeric(18,0)) + 1
				
								IF LEN(@FlowNo)=1
									SET @BillCode = 'XFT-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-000'+CAST(@FlowNo AS varchar(100))
								ELSE IF LEN(@FlowNo)=2
									SET @BillCode = 'XFT-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-00'+CAST(@FlowNo AS varchar(100))
								ELSE IF LEN(@FlowNo)=3
									SET @BillCode = 'XFT-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-0'+CAST(@FlowNo AS varchar(100))
								ELSE
									SET @BillCode = 'XFT-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-'+CAST(@FlowNo AS varchar(100))
							END
					END
				ELSE
					BEGIN
						SET @BillCode = 'XFT'+'-'++Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-'+'0001'
					END
			END
	END
ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM nVipAdjust WHERE nType = 2)
			SET @BillCode = 'JFC'+'-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-'+'0001'
		ELSE
			BEGIN
				SELECT	TOP 1 @TmpBillCode = BillCode FROM nVipAdjust WHERE nType = 2 AND BillDate=CONVERT(varchar(10),@strDate,120) ORDER BY BillNumberId DESC

				IF LEFT(RIGHT(@TmpBillCode,13),8)=Replace(CONVERT(varchar(10),@strDate,120),'-','')
					BEGIN
						IF RIGHT(@TmpBillCode,4)='9999'
							SET @BillCode = 'JFC'+'-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-'+'0001'
						ELSE
							BEGIN
								SET @FlowNo = CAST(RIGHT(@TmpBillCode,4) AS numeric(18,0)) + 1
				
								IF LEN(@FlowNo)=1
									SET @BillCode = 'JFC-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-000'+CAST(@FlowNo AS varchar(100))
								ELSE IF LEN(@FlowNo)=2
									SET @BillCode = 'JFC-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-00'+CAST(@FlowNo AS varchar(100))
								ELSE IF LEN(@FlowNo)=3
									SET @BillCode = 'JFC-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-0'+CAST(@FlowNo AS varchar(100))
								ELSE
									SET @BillCode = 'JFC-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-'+CAST(@FlowNo AS varchar(100))
							END
					END
				ELSE
					BEGIN
						SET @BillCode = 'JFC'+'-'+Replace(CONVERT(varchar(10),@strDate,120),'-','')+'-'+'0001'
					END
			END
	END










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetAllPayConfigInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_GetAllPayConfigInfo]
GO
--==========================================================
--BY:zy
--DATE:2017-06-28
--DESCRIPTION:获取所有支付账户配置
--==========================================================
CREATE PROC Gp_GetAllPayConfigInfo
(
	@paytype   INT,	   -- 账户类型：1---支付宝，2---微信,3---通联收银宝
	@chvOperatorId			varchar(100)
)
--@encode$--

AS
SET NOCOUNT ON

CREATE TABLE #temp
(
	PayConfigID		INT				NOT NULL,
	stypeids		VARCHAR(8000)	,
	stypenames		VARCHAR(8000)	
)

INSERT INTO #temp 
SELECT A.ID,
	   'stypeid' = stuff
                          ((SELECT     ',' + B.TypeId
                              FROM         PayConfigInfo AS t
                              LEFT JOIN StypePayConfigInfo D ON t.ID=D.PayConfigID
							  LEFT JOIN SType B ON D.StypeID=B.TypeId
                              WHERE t.ID=A.ID FOR xml path('')), 1, 1, ''),
       'sfullname' = stuff
                          ((SELECT     ',' + B.FullName
                              FROM         PayConfigInfo AS t
                              LEFT JOIN StypePayConfigInfo D ON t.ID=D.PayConfigID
							  LEFT JOIN SType B ON D.StypeID=B.TypeId
                              WHERE t.ID=A.ID FOR xml path('')), 1, 1, '')
FROM PayConfigInfo A
LEFT JOIN StypePayConfigInfo D ON A.ID=D.PayConfigID OR A.IsDefault=1
LEFT JOIN (SELECT B.TypeId FROM SType B INNER JOIN F_GetManDetailAllSType(@chvOperatorId) M ON M.TypeId = B.TypeID
)C ON D.StypeID = C.TypeId
WHERE A.PayType=@paytype
GROUP BY A.ID

SELECT 
	A.ID,
	A.UserCode,
	A.FullName,
	A.PID,
	A.AppID,
	C.nId AS 'nid',
	C.FullName AS 'afullname',
	B.stypeids AS 'stypeid',
	B.stypenames AS 'sfullname',
	A.Comment,
	CASE WHEN A.IsDefault=1 THEN '是' ELSE '否' END AS 'default'
FROM PayConfigInfo A
INNER JOIN #temp B ON A.ID=B.PayConfigID
LEFT JOIN Ac_Items C ON A.BankCardID=C.nId
WHERE A.PayType=@paytype
ORDER BY A.ID

DROP TABLE #temp

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


----------------------------------------取得操作ID相应的商品权限
----------------------------------------肖伟2002-3-25
CREATE   PROCEDURE GP_GetAllTypeLimit23
(
 @OperatorID varchar(100),  	    ----------------操作员ID号
 @PTypeLimit varchar(50) output,    ----------------商品权限
 @KTypeLimit varchar(50) output     ----------------库存权限
)
--@encode$--
AS
set nocount on
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re

select @PTypeLimit =  @MPtypeid
select @KTypeLimit =  @MKtypeid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE       PROCEDURE Gp_GetALoginUserLim 
(
 @szEtypeId varchar(100)
)

AS
SET NOCOUNT ON

--********判断是否被完全破解**********
	--IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'LoginCheck' AND SubValue = CONVERT(varchar(100), GETDATE(), 112))
		--RETURN -99
/*	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ControlFlag' AND SubValue = 'ssct')
	BEGIN
		DECLARE @Cost INT 
		SET @Cost=-1 
		SELECT @Cost=subvalue FROM sysdata WHERE subname='costing' 
		IF (@Cost=0) 
		BEGIN
			UPDATE goodsstocks_qty SET QTY=0,NQTY=0 
		END
		UPDATE atype_total SET total=0,ntotal=0
		UPDATE btype_araptotal SET ARtotal=0,APTotal=0,YSTotal=0,YFTotal=0,nARTotal=0,nAPTotal=0,nYSTotal=0,nYFTotal=0
		DELETE FROM WebMenu
		RETURN
	END
	
	
	DECLARE @DiffDay INT
	SELECT @DiffDay = DATEDIFF(DAY,SubValue,GETDATE()) FROM sysdata WHERE SubName = 'LoginCheck'
	
	IF @DiffDay > 333
		RETURN -99
*/		
--查询相关信息
SELECT TOP 1 
		a.FullName as 'fullname', 
		a.UserCode as 'usercode', 
		cast(b.password as varchar(32)) as 'password', 
		b.etypeid, 
		b.lim,
		b.btypeid as 'btypeid',		
		'00001'  as mbtypeid,
		'00002' as mbtypeid2,
		'00000'  as mPtypeid,
		'00001'  as metypeid,
		'00000'  as mktypeid,
		'0000'  as matypeid,
		'0000'  as mftypeid,
		'0000'   as mitypeid,
		'0000'  as mctypeid,
		'00000'  as mdtypeid,
		'00000' as mstypeid,
		--追加多级权限用于过账
		b.MangerBtypeID  as mbtypeidm,
		b.MangerBtypeID2 as mbtypeid2m,
		b.MangerPtypeID  as mPtypeidm,
		b.MangerEtypeID  as metypeidm,
		b.MangerKtypeID  as mktypeidm,
		b.MangerATypeID  as matypeidm,
		b.MangerExpense  as mftypeidm,
		b.MangerIncome   as mitypeidm,
		b.MangerCpaital  as mctypeidm,
		b.MangerDtypeID  as mdtypeidm,
		b.MangerSTypeID  as mstypeidm,
		--追加多级权限用于过账
		b.sysid As issys,
		b.UserDeRowCount,
		c.fullname AS 'comname',
		ISNULL(b.InfoFixUp,'') AS InfoFixUp,
		a.DTypeID,
		a.STypeID
FROM 	employee a inner join loginuser b on (a.typeid=b.etypeid)
INNER JOIN btype c on (b.btypeid=c.typeid)
WHERE  b.etypeid=@szEtypeId
		AND b.isErp = 1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	Author:		毛欣蓉
	Create date: 2012-05-17
	Description: 得到往来余额
*/	
CREATE   PROCEDURE GP_GetArApTotal
(
	@AID		INT,		
	@szBtypeId	VARCHAR(50),		--往来单位的ID
	@szSTypeID	VARCHAR(50),		--分支机构ID
	@CID		INT,				--币种id
	@dtotal		 NUMERIC(24, 10)  OUTPUT, --本币
	@Ndtotal	 NUMERIC(24, 10)  OUTPUT  --原币
)
--@encode$--
AS
			
	--应付
	IF @AID=2
	BEGIN
			SELECT 	@dtotal=SUM(APTotal), 
					@Ndtotal=SUM(NAPTotal) 
			FROM 	BType_ARAPTotal 
			WHERE 	BTypeID = @szBtypeId
					AND STypeID=@szSTypeID
					AND CID = @CID                                                                               
			IF 	@dtotal IS null SELECT @dtotal=0
			RETURN
	END 

	--预付
	IF @AID=4
	BEGIN
			SELECT 	@dtotal=SUM(YFtotal),
					@Ndtotal=SUM(NYFTotal)  
			FROM 	BType_ARAPTotal 
			WHERE 	BTypeID = @szBtypeId 
					AND STypeID=@szSTypeID
					AND CID = @CID
			IF 	@dtotal IS null SELECT @dtotal=0
			RETURN
	END 

	--应收
	IF @AID=1
	BEGIN
			SELECT 	@dtotal=SUM(artotal),
					@Ndtotal=SUM(NARTotal)  
			FROM 	BType_ARAPTotal 
			WHERE 	BTypeID = @szBtypeId
					AND STypeID=@szSTypeID
					AND CID = @CID
			IF 	@dtotal IS null SELECT @dtotal=0
			RETURN
	END
	
	--预收
	IF @AID=3 	
	BEGIN	
			SELECT 	@dtotal=SUM(YSTotal),
					@Ndtotal=SUM(NYSTotal)  
			FROM 	BType_ARAPTotal 
			WHERE 	BTypeID = @szBtypeId
					AND STypeID=@szSTypeID
					AND CID = @CID
			IF 	@dtotal IS null SELECT @dtotal=0
			
			RETURN
	END
IF @@ERROR <> 0  RETURN -4

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_GetAtypeIdByAssetsCategory]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_GetAtypeIdByAssetsCategory]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*	作者：黄清	
	日期：2014-05-16
	描述：获取出纳系统初始化数据

*/
CREATE PROCEDURE [dbo].[GP_GetAtypeIdByAssetsCategory]
(
	@stypeid		VARCHAR(50),	--分支机构ID
	@categoryid		VARCHAR(5),		--资产类别ID
	@OperatorID		VARCHAR(50)		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200))
	INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName) 
	SELECT L.Typeid,L.Stypeid,A.FullName FROM F_LineAccount(@OperatorID,@stypeid) L
	INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
	--WHERE L.Stypeid=@stypeid AND A.Deleted<>'1' 
		--写入空数据
	INSERT INTO #Ac_Account_L(TypeId,StypeId,FullName)VALUES
	('',@stypeid,'')
END;

SELECT  AC.FullName AS  categoryfullname,
        units AS units,
        duryear,
        depreciationmean,
        RemainsRate AS netsalvagerate,
        AssertATypeId,
        ISNULL(Ass.FullName,'****') AS assertfullname,
        DepATypeId,
        ISNULL(Dep.FullName,'****') AS depfullname,
        ExpenseATypeId AS 	DisATypeId,
        ISNULL(Expe.FullName,'****') AS disfullname
FROM Ac_AssetsCategory AC
LEFT JOIN #Ac_Account_L Ass ON Ass.TypeId=ac.AssertATypeId AND ASS.StypeId=AC.StypeId
LEFT JOIN #Ac_Account_L Dep ON DEP.TypeId=AC.DepATypeId AND Dep.StypeId=ac.StypeId
LEFT JOIN #Ac_Account_L Expe	ON Expe.TypeId=AC.ExpenseATypeId AND Expe.StypeId=AC.StypeId
WHERE AC.StypeId=@stypeid AND AC.Id=@categoryid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE       PROCEDURE Gp_GetAUserLim 
(
 @szEtypeId varchar(100)
)
--@encode$--
AS
set nocount on
SELECT TOP 1 
		a.FullName as 'fullname', 
		a.UserCode as 'usercode', 
		cast(b.password as varchar(10)) as 'password', 
		b.etypeid, 
		b.lim,
        b.AutoWindow,	
        b.playmsg,
		b.btypeid as 'btypeid',		
		'00001'  as mbtypeid,
		'00002' as mbtypeid2,
		'00000'  as mPtypeid,
		'00001'  as metypeid,
		'00000'  as mktypeid,
		'0000'  as matypeid,
		'0000'  as mftypeid,
		'0000'   as mitypeid,
		'0000'  as mctypeid,
		'00000'  as mdtypeid,
		'00000' as mstypeid,
		--追加多级权限用于过账
		b.MangerBtypeID  as mbtypeidm,
		b.MangerBtypeID2 as mbtypeid2m,
		b.MangerPtypeID  as mPtypeidm,
		b.MangerEtypeID  as metypeidm,
		b.MangerKtypeID  as mktypeidm,
		b.MangerATypeID  as matypeidm,
		b.MangerExpense  as mftypeidm,
		b.MangerIncome   as mitypeidm,
		b.MangerCpaital  as mctypeidm,
		b.MangerDtypeID  as mdtypeidm,
		b.MangerSTypeID  as mstypeidm,
		--追加多级权限用于过账
		b.sysid As issys,
		b.UserDeRowCount,
		c.fullname AS 'comname',
		ISNULL(b.InfoFixUp,'') AS InfoFixUp,
		a.DTypeID,
		a.STypeID,
		b.LockScreenTime 
FROM 	employee a inner join loginuser b on (a.typeid=b.etypeid)
INNER JOIN btype c on (b.btypeid=c.typeid)
WHERE  b.etypeid=@szEtypeId		



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




-- 得到销售分布表的基本信息条数
-- cqhua 2009-12-04

CREATE        PROCEDURE GP_GetBaseCount 
(
 @OperatorId varchar(50),
 @Flag char(1),
 @BaseTypeID varchar(1550)
)
--@encode$--
AS
set nocount on

CREATE TABLE  #BaseType (typeid varchar(50))
IF @Flag ='B'
	IF @BaseTypeID =''
		INSERT INTO #BaseType select a.typeid from F_GetManDetailBType(@OperatorID) a
	ELSE
		INSERT INTO #BaseType select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BaseTypeID,',')) b where left(a.typeid,len(b.a))=b.a
ELSE IF @Flag ='E'
	IF @BaseTypeID=''
		INSERT INTO #BaseType select typeid from F_GetManDetailEType(@OperatorID)  where TypeId<>'00001'
	ELSE
		INSERT INTO #BaseType select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@BaseTypeID,',')) b where left(a.typeid,len(b.a))=b.a 
ELSE IF @Flag ='K'
	IF @BaseTypeID=''
	BEGIN
		INSERT INTO #BaseType select typeid from F_GetManDetailKType(@OperatorID)
		insert into #BaseType select '10000'
	END
	ELSE
		INSERT INTO #BaseType select a.typeid from F_GetManDetailKType(@OperatorID) a,  (select * from  dbo.f_split(@BaseTypeID,',')) b where left(a.typeid,len(b.a))=b.a
ELSE IF @Flag ='D'	
	IF @BaseTypeID=''
	BEGIN
		INSERT INTO #BaseType select typeid from F_GetManDetailDType(@OperatorID)
		--INSERT INTO #BaseType SELECT ''
	END
	ELSE
		INSERT INTO #BaseType select a.typeid from F_BaseGetManDType(@OperatorID) a ,(select * from  dbo.f_split(@BaseTypeID,',')) b where left(a.typeid,len(b.a))=b.a and a.deleted =0 and a.sonnum =0
        and a.typeid<>'00000'
ELSE IF @Flag ='A'	
	IF @BaseTypeID=''
	BEGIN
		INSERT INTO #BaseType select typeid from F_GetAllManagerBaseTypeId(@BaseTypeID,10,@OperatorID) 
		insert into #BaseType select '99999'
	END
	ELSE
		INSERT INTO #BaseType select a.typeid from F_GetAllManagerBaseTypeId(@BaseTypeID,10,@OperatorID) a 
ELSE IF @Flag ='I'	--现金银行
	BEGIN
		INSERT INTO #BaseType(typeid)
		SELECT i.nTypeId
		FROM dbo.F_GetAllManagerBaseTypeId(@BaseTypeID,5,@OperatorId) F
		INNER JOIN Ac_Items I ON I.nId=F.TypeId AND I.SonNum=0 AND F.TypeId NOT IN(27,39)--排除(1151-预付资金 2131-预收资金)
	END
ELSE IF @Flag ='S'	--分支机构
	BEGIN
		INSERT INTO #BaseType(typeid)
		SELECT 
			S.TypeId
		FROM dbo.F_GetAllManagerBaseTypeId(@BaseTypeID,11,@OperatorId) F
		INNER JOIN SType S ON S.TypeId=F.TypeId AND S.SonNum=0
	END
declare @re int 
set @re =0

SELECT  @re =COUNT(*) FROM #BaseType
DROP TABLE  #BaseType 
return @re




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_GetBaseInforCustomData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_GetBaseInforCustomData]
GO
/*
	作者：张陈仁
	日期：2012-06-26
	描述：基本信息获取自定义数据
*/
CREATE PROCEDURE GP_GetBaseInforCustomData
(
	@BaseType VARCHAR(50),
	@TypeId VARCHAR(50)
)
--@encode$--
AS
BEGIN
	DECLARE
			@CusType VARCHAR(50),
			@CusOrder INT,
			@Alias	  VARCHAR(10),
			@sqlselect VARCHAR(MAX)='',
			@sqlfrom VARCHAR(MAX)='',
			@sqlWhere VARCHAR(Max)='',
			@newBasetype VARCHAR(50),
			@insertSql VARCHAR(Max)=''
			
	IF(@TypeId<>'')
		SET @sqlWhere=' WHERE A.typeid='''+@TypeId+''''	
				
	CREATE TABLE #T1
	(
		BaseType	    VARCHAR(50), --基本信息类型
		CustomerType	VARCHAR(50), --自定义类型
		CustomerOrder	INT,         --自定义列编号
		Alias           VARCHAR(10)  --连接查询表别名
	)
	IF(@BaseType='gbtype')
		SET @newBasetype='gtype'
	ELSE
		SET @newBasetype=@BaseType
		
	INSERT INTO #T1 SELECT BaseType,CustomerType,CustomerOrder,LEFT(CustomerType,3)+CAST(CustomerOrder AS VARCHAR(10)) 
	FROM CustomBaseInforColumnsDefines
	WHERE BaseType=@newBasetype
	
	CREATE CLUSTERED INDEX CIX_T1_Alias ON #T1(BaseType,CustomerType,CustomerOrder,Alias)
	
	SET @sqlselect='SELECT '
	SET @sqlfrom=' FROM '+@BaseType+'_CustomColumns A'		
	DECLARE CUSTOMER_CURSOR CURSOR FORWARD_ONLY STATIC FOR
	SELECT CustomerType,CustomerOrder,Alias FROM #T1 ORDER BY CustomerOrder
	OPEN CUSTOMER_CURSOR 
	FETCH NEXT FROM CUSTOMER_CURSOR INTO @CusType,@CusOrder,@Alias
		 WHILE @@FETCH_STATUS = 0
		 BEGIN
			IF @CusType NOT IN ('Number','Text','Date')--自定义为selector类型时
				BEGIN
					SET @sqlselect=@sqlselect+' '+@Alias+'.'+'Typeid Costom'+CAST(@CusOrder AS varchar(10))+','+@Alias+'.'+'Fullname as FullName'+CAST(@CusOrder AS CHAR(2))+','
				    IF CHARINDEX('SelfDataType',@CusType)>0--自定义为自由项时
						BEGIN
						    DECLARE @datatypeid VARCHAR(10)
						    SET @datatypeid=REPLACE(@CusType,'__SelfDataType','')
							SET @sqlfrom=@sqlfrom+' LEFT JOIN xw_SelfData '+@Alias+' ON A.Costom'+CAST(@CusOrder AS varchar(10))+'='+@Alias+'.Typeid and '+@Alias+'.DataTypeId= '+@datatypeid+' '
							--SET @sqlWhere=@sqlWhere+' and '+@Alias+'.DataTypeId= '+@datatypeid+''
						END
				    ELSE
						BEGIN
							SET @sqlfrom=@sqlfrom+' LEFT JOIN '+@CusType+' '+@Alias+' ON A.Costom'+CAST(@CusOrder AS CHAR(2))+'='+@Alias+'.Typeid'
						END
				END
			ELSE
				IF @CusType IN ('Date')
					SET @sqlselect=@sqlselect+' case when ISNULL(A.Costom'+CAST(@CusOrder AS CHAR(2))+','''')<>'''' then CONVERT(VARCHAR(100),convert(datetime,A.Costom'+CAST(@CusOrder AS CHAR(2))+'),23) else '''' end as Costom'+CAST(@CusOrder AS CHAR(2))+','+'case when ISNULL(A.Costom'+CAST(@CusOrder AS CHAR(2))+','''')<>'''' then CONVERT(VARCHAR(100),convert(datetime,A.Costom'+CAST(@CusOrder AS CHAR(2))+'),23) else '''' end as FullName'+CAST(@CusOrder AS CHAR(2))+''+','
			    ELSE
					SET @sqlselect=@sqlselect+' A.Costom'+CAST(@CusOrder AS CHAR(2))+','+'A.Costom'+CAST(@CusOrder AS CHAR(2))+' as FullName'+CAST(@CusOrder AS CHAR(2))+''+','			
			FETCH NEXT FROM CUSTOMER_CURSOR INTO @CusType,@CusOrder,@Alias
		 END
	CLOSE CUSTOMER_CURSOR
	DEALLOCATE CUSTOMER_CURSOR
    --PRINT @sqlselect+'A.typeid '+@sqlfrom+@sqlWhere
	EXEC(@sqlselect+'A.typeid '+@sqlfrom+@sqlWhere)
	DROP TABLE #T1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.1.5
	描述：调用GP_HandCreate_Voucher生成凭证，将select结果放到此处，以便GP_HandCreate_Voucher可方便用于批量生成
*/
CREATE PROCEDURE GP_GetBatchCreateResult
(
	@BillNumberId	numeric(18,0)			-- 单据编号
)
--@encode$--
AS
SET NOCOUNT ON

select * from Ac_Voucher_Temp where billnumberid = @BillNumberId
select * from Ac_Voucher_Bill_Temp where billnumberid = @BillNumberId
select * from Ac_Voucher_Bill_Assist_CheckItems_Temp where billnumberid = @BillNumberId
select stypeid,billnumberids from Ac_Voucher_Generate_Voucherbill_GoodsBills where billnumberid = @BillNumberId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetBeforeAROrAP]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_GetBeforeAROrAP]
GO

/*
	作者:毛欣蓉
	日期:2011-03-1
	描述:应收应付查询此前余额
	
	作者：黄清
	日期：2012-06-07
	描述：增加币别条件，增加返回原币余额
*/
CREATE  PROCEDURE Gp_GetBeforeAROrAP
(
	@OperatorID 	VARCHAR(100),  	            --操作员ID号
	@nType        	INT=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@StartDate 		VARCHAR(20),	            --时间点
	@BtypeID 		VARCHAR(MAX),               --客户typeid
	@showRedWord	INT=1,						--是否显示红冲单据
	@stypeid		VARCHAR(MAX),
	@includePre		INT,
	@cid			VARCHAR(10),				--币别
	@PreTotal 		 NUMERIC(24, 10)  OUTPUT,     	--返回余额(本币)
	@nPreTotal 		 NUMERIC(24, 10)  OUTPUT     	--返回余额(原币)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MDTypeId VARCHAR(50),@MSTypeId VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
DECLARE @CurToal         NUMERIC(24, 10) ,
		@nCurToal        NUMERIC(24, 10) ,
		@SumARTotal      NUMERIC(24, 10) ,
		@nSumARTotal     NUMERIC(24, 10) ,
		@aratypeID	    VARCHAR(50),
		@ysatypeID	    VARCHAR(50),
		@apatypeID	    VARCHAR(50),
		@yfatypeID	    VARCHAR(50)

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

IF LEFT(@btypeid,5)='00001'
	IF LEN(@btypeid)<LEN(@MBtypeid)
		SET @btypeid=@MBtypeid
IF LEFT(@btypeid,5)='00002'
	IF LEN(@btypeid)<LEN(@MBtypeid2)
		SET @btypeid=@MBtypeid2
		
CREATE TABLE #listtable
(
	billnumberid	INT,
	billtype		INT,
	atypeid			VARCHAR(100),
	redword			INT,
	total			 NUMERIC(24, 10) ,
	ntotal			 NUMERIC(24, 10) 
)

--分支机构
CREATE TABLE #stype(typeid	VARCHAR(100))
INSERT INTO #stype(typeid) 
SELECT  A.typeid FROM	F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

CREATE TABLE #tmpBefore(Total  NUMERIC(24, 10) ,nTotal  NUMERIC(24, 10) )

DECLARE @SQL VARCHAR(MAX)

IF @nType=1
BEGIN
	IF @includePre = 0
	BEGIN
		SELECT	@CurToal= SUM(ISNULL(b.ARTotal,0)),
				@nCurToal= SUM(ISNULL(b.nARTotal,0)) 
		FROM	BType_ARAPTotal b 
		INNER JOIN #stype s ON s.typeid=b.STypeID 
		WHERE	btypeId = @Btypeid  
			AND (@cid='0' OR B.CID=@cid) 
			GROUP BY b.BTypeID  --期初应收余额
		
		INSERT INTO #tmpbefore (Total,nTotal)
			SELECT SUM(l.Total) AS total,SUM(l.NTotal) AS ntotal
			FROM Listtable   L
			INNER JOIN #stype S ON S.typeid=L.STypeID
			WHERE L.BtypeId = @Btypeid AND L.BillDate>=@StartDate
				AND	 L.ATypeID IN(@aratypeID)
				AND  L.Audited = 1 
				AND (@cid='0'  OR L.CID=@cid)
	END
	ELSE
	BEGIN
		SELECT	@CurToal= SUM(ISNULL(ISNULL(b.ARTotal,0)-ISNULL(b.YSTotal,0),0)),
				@nCurToal= SUM(ISNULL(ISNULL(b.nARTotal,0)-ISNULL(b.nYSTotal,0),0)) 
		FROM	BType_ARAPTotal b 
		INNER JOIN #stype s ON s.typeid=b.STypeID 
		WHERE	btypeId = @Btypeid 
				AND (@cid='0'  OR b.CID=@cid) 
	
		
		INSERT INTO #tmpbefore (Total,nTotal)
			SELECT SUM(CASE WHEN l.AtypeId=@aratypeID THEN l.Total ELSE -l.Total END) AS total,
				   SUM(CASE WHEN l.AtypeId=@aratypeID THEN l.NTotal  ELSE -l.nTotal END) AS ntotal
			FROM Listtable   L
			INNER JOIN #stype S ON S.typeid=L.STypeID
			WHERE L.BtypeId = @Btypeid AND L.BillDate>=@StartDate
				AND	 L.ATypeID IN(@aratypeID,@ysatypeID)
				AND  L.Audited = 1 
				AND (@cid='0'  OR L.CID=@cid)
	END
END
ELSE
BEGIN
	IF @includePre = 0
	BEGIN
		SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal,0),0)),
				@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal,0),0)) 
		FROM	BType_ARAPTotal b 
		INNER JOIN #stype s ON s.typeid=b.STypeID 
		WHERE	btypeId = @Btypeid  
				AND (@cid='0'  OR b.CID=@cid)
		GROUP BY b.BTypeID  --期初应收余额
		
		 	
		INSERT INTO #tmpbefore (Total,nTotal)
			SELECT SUM(l.Total) AS total,SUM(l.NTotal) AS ntotal
			FROM Listtable   L
			INNER JOIN #stype S ON S.typeid=L.STypeID
			WHERE L.BtypeId = @Btypeid AND L.BillDate>=@StartDate
				AND	 L.ATypeID IN(@apatypeID)
				AND  L.Audited = 1 
				AND (@cid='0'  OR L.CID=@cid)
	END
	ELSE
	BEGIN

		SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal,0)-ISNULL(b.YFTotal,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal,0)-ISNULL(b.nYFTotal,0),0)) 
		FROM	BType_ARAPTotal b 
		INNER JOIN #stype s ON s.typeid=b.STypeID 
		WHERE	btypeId = @Btypeid  
			AND (@cid='0'  OR CID=@cid)
		GROUP BY b.BTypeID  --期初应收余额
			
		
		INSERT INTO #tmpbefore (Total,nTotal)
			SELECT SUM(CASE WHEN l.AtypeId=@apatypeID THEN l.Total ELSE -l.Total END) AS total,
				   SUM(CASE WHEN l.AtypeId=@apatypeID THEN l.NTotal  ELSE -l.nTotal END) AS ntotal
			FROM Listtable   L
			INNER JOIN #stype S ON S.typeid=L.STypeID
			WHERE L.BtypeId = @Btypeid AND L.BillDate>=@StartDate
				AND	 L.ATypeID IN(@apatypeID,@yfatypeID)
				AND  L.Audited = 1 
				AND (@cid='0'  OR L.CID=@cid)
	END
END


SELECT	@SumARTotal=SUM(ISNULL(Total,0)), 
		@nSumARTotal=SUM(ISNULL(nTotal,0))
FROM #tmpBefore


SELECT @PreTotal=ISNULL(@CurToal,0)-ISNULL(@SumARTotal,0)  ---期初应收余额+(这段日期的应收变化量[本币])

SELECT @nPreTotal=ISNULL(@nCurToal,0)-ISNULL(@nSumARTotal,0)  ---期初应收余额+(这段日期的应收变化量[原币])

DROP TABLE #tmpbefore,#stype,#listtable


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetBeforeArOrApAdd]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_GetBeforeArOrApAdd]
GO

/*
	作者:王刚
	日期:2014-10-18【存储过程从Gp_GetBeforeAROrAP复制过来】
	描述:应收应付查询此前余额 以加的方式(期初与职员有关),之前的Gp_GetBeforeAROrAP(期初与职员无关)是减的方式
*/
CREATE  PROCEDURE Gp_GetBeforeArOrApAdd
(
	@OperatorID 	VARCHAR(100),  	            --操作员ID号
	@nType        	INT=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@StartDate 		VARCHAR(20),	            --时间点
	@BtypeID 		VARCHAR(MAX),               --客户typeid
	@showRedWord	INT=1,						--是否显示红冲单据
	@stypeid		VARCHAR(MAX),
	@includePre		INT,
	@cid			VARCHAR(10),				--币别
	@PreTotal 		 NUMERIC(24, 10)  OUTPUT,     	--返回余额(本币)
	@nPreTotal 		 NUMERIC(24, 10)  OUTPUT,     	--返回余额(原币)
	@Etypeid		VARCHAR(MAX),
	@EtypeFlag		INT							--职员往来中进入的明细 1=往来单位关联职员  单据职员
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MDTypeId VARCHAR(50),@MSTypeId VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
DECLARE @CurToal         NUMERIC(24, 10) ,
		@nCurToal        NUMERIC(24, 10) ,
		@SumARTotal      NUMERIC(24, 10) ,
		@nSumARTotal     NUMERIC(24, 10) ,
		@aratypeID	    VARCHAR(50),
		@ysatypeID	    VARCHAR(50),
		@apatypeID	    VARCHAR(50),
		@yfatypeID	    VARCHAR(50)

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

IF LEFT(@btypeid,5)='00001'
	IF LEN(@btypeid)<LEN(@MBtypeid)
		SET @btypeid=@MBtypeid
IF LEFT(@btypeid,5)='00002'
	IF LEN(@btypeid)<LEN(@MBtypeid2)
		SET @btypeid=@MBtypeid2
		
CREATE TABLE #listtable
(
	billnumberid	INT,
	billtype		INT,
	atypeid			VARCHAR(100),
	redword			INT,
	total			 NUMERIC(24, 10) ,
	ntotal			 NUMERIC(24, 10) 
)

--分支机构
CREATE TABLE #stype(typeid	VARCHAR(100))
INSERT INTO #stype(typeid) 
SELECT  A.typeid FROM	F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

--职员
CREATE TABLE #etype(etypeid	VARCHAR(100),btypeid VARCHAR(100))
IF @EtypeFlag = 1
BEGIN
	INSERT #etype
	SELECT ISNULL(a.TypeId,''),@BtypeID
	FROM F_GetAllManagerBaseTypeId(@Etypeid,3,@OperatorID) A,btype B
	WHERE B.typeId=@BtypeID AND A.TypeId = B.etypeid
END
ELSE
BEGIN
	INSERT #etype
	SELECT TypeId,@BtypeID FROM F_GetAllManagerBaseTypeId(@Etypeid,3,@OperatorID)
END

DECLARE @EtypeIsEmpty INT = 0

IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	SELECT TOP 1 @EtypeIsEmpty = 1 
	FROM IniBType_ArApTotal I
	INNER JOIN #stype S ON S.TypeId = I.STypeID
	WHERE I.ETypeId = '' OR I.ETypeId IS NULL
ELSE
	SELECT TOP 1 @EtypeIsEmpty = 1 FROM IniBType_ArApTotal WHERE ETypeId = '' OR ETypeId IS NULL

CREATE TABLE #tmpBefore(Total  NUMERIC(24, 10) ,nTotal  NUMERIC(24, 10) )

DECLARE @SQL VARCHAR(MAX)

IF @nType=1
BEGIN
	IF @includePre = 0
	BEGIN
	SET @SQL='
		INSERT INTO #listtable
		(
			billnumberid,
			billtype,
			atypeid,
			redword,
			total,
			ntotal
		)
		SELECT  l.BillNumberId,
				l.BillType,
				l.AtypeId,
				bi.RedWord,
				l.Total,
				L.Ntotal 
		FROM Listtable l
		INNER JOIN BillIndex bi ON L.BillNumberId=BI.BillNumberId '
	
	IF @EtypeFlag = 1
		SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId '
	ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
		SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId'	
		
	SET @SQL += ' INNER JOIN #stype S ON S.typeid=L.STypeID
			WHERE	L.BtypeId = '+CHAR(39)+@Btypeid+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'
					AND	 L.ATypeID IN('+@aratypeID+')
					AND  L.Audited = 1
					AND	 bi.redword=0 '
		IF @cid<>'0'
			SET @SQL=@SQL+'AND	 L.CID='+@cid
		EXEC(@SQL)	
		
		IF @EtypeIsEmpty = 1
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(b.ARTotal00,0)),
					@nCurToal= SUM(ISNULL(b.nARTotal00,0)) 
			FROM	BType_ARAPTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	btypeId = @Btypeid  
			AND (B.CID=@cid OR @cid='0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		ELSE
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(b.ARTotal00,0)),
					@nCurToal= SUM(ISNULL(b.nARTotal00,0)) 
			FROM	IniBType_ArApTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID
			INNER JOIN #etype E ON E.btypeid = b.BTypeID AND E.etypeid = b.ETypeId
			WHERE	b.BTypeID = @Btypeid  
			AND (b.CID=@cid OR @cid='0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		
		INSERT INTO #tmpbefore (Total,nTotal)
		SELECT	ISNULL(SUM(ISNULL(a.addtotal,0)-ISNULL(a.rectotal,0)),0) AS total,
				ISNULL(SUM(ISNULL(a.naddtotal,0)-ISNULL(a.nrectotal,0)),0) AS ntotal
		FROM (SELECT  SUM(CASE  WHEN l.billtype=45 AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.Total
								WHEN l.BillType=11  AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.Total
								WHEN l.billtype=160  AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.Total
								WHEN  l.AtypeId=@aratypeID AND l.Total>0 AND l.BillType NOT IN(45,11,160) AND l.RedWord IN(0,1) THEN l.Total 
								WHEN l.billtype=45 AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.Total
								WHEN l.BillType=11  AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.Total
								WHEN l.billtype=160  AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.Total
								WHEN  l.AtypeId=@aratypeID AND l.Total>0 AND l.BillType NOT IN(45,11,160) AND l.RedWord=2 THEN -l.Total 
								ELSE 0
							END) AS addtotal,
					SUM(CASE	WHEN l.billtype=45 AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.nTotal
								WHEN l.BillType=11  AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.nTotal
								WHEN l.billtype=160  AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.nTotal
								WHEN  l.AtypeId=@aratypeID AND l.nTotal>0 AND l.BillType NOT IN(45,11,160) AND l.RedWord IN(0,1) THEN l.nTotal 
								WHEN l.billtype=45 AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.nTotal
								WHEN l.BillType=11  AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.nTotal
								WHEN l.billtype=160  AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.nTotal
								WHEN  l.AtypeId=@aratypeID AND l.nTotal>0 AND l.BillType NOT IN(45,11,160) AND l.RedWord=2 THEN -l.nTotal 
								ELSE 0
							END) AS naddtotal,
					SUM(CASE WHEN  l.AtypeId=@aratypeID AND l.Total<0 AND  l.BillType NOT IN(45,11,160) AND l.redword IN(0,1) THEN ABS(l.Total)
							WHEN  l.AtypeId=@aratypeID AND l.Total<0 AND  l.BillType NOT IN(45,11,160) AND l.redword IN(2) THEN l.Total 
						 ELSE 0
					END) AS rectotal,
					SUM(CASE WHEN  l.AtypeId=@aratypeID AND l.nTotal<0 AND  l.BillType NOT IN(45,11,160) AND l.redword IN(0,1) THEN ABS(l.nTotal)
							WHEN  l.AtypeId=@aratypeID AND l.nTotal<0 AND  l.BillType NOT IN(45,11,160) AND l.redword IN(2) THEN l.nTotal 
						 ELSE 0
					END) AS nrectotal
				FROM #listtable l	
			)A  
	END
	ELSE
	BEGIN
		SET @SQL='
		INSERT INTO #listtable
		(
			billnumberid,
			billtype,
			atypeid,
			redword,
			total,
			ntotal
		)
		SELECT  l.BillNumberId,
				l.BillType,
				l.AtypeId,
				bi.RedWord,
				l.Total,
				l.Ntotal 
		FROM Listtable l
		INNER JOIN BillIndex bi ON L.BillNumberId=BI.BillNumberId
		INNER JOIN #stype S ON S.typeid=L.STypeID '
		
		IF @EtypeFlag = 1
			SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId '
		ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
			SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId'	
		
		SET @SQL += ' WHERE L.BtypeId ='+CHAR(39)+ @Btypeid+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+' 
			AND	 L.ATypeID IN('+@aratypeID+','+@ysatypeID+')
			AND  L.Audited = 1
			AND  bi.redword=0 '
		IF @cid<>'0'
			SET @SQL=@SQL+'AND	 L.CID='+@cid
		EXEC(@SQL)	
		
		IF @EtypeIsEmpty = 1
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.ARTotal00,0)-ISNULL(b.YSTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nARTotal00,0)-ISNULL(b.nYSTotal00,0),0)) 
			FROM	BType_ARAPTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	btypeId = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		ELSE
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.ARTotal00,0)-ISNULL(b.YSTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nARTotal00,0)-ISNULL(b.nYSTotal00,0),0)) 
			FROM	IniBType_ArApTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID
			INNER JOIN #etype E ON E.btypeid = b.BTypeID AND E.etypeid = b.ETypeId
			WHERE	b.BTypeID = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		
		
		INSERT INTO #tmpbefore (Total,nTotal)
		SELECT	ISNULL(SUM(ISNULL(a.addtotal,0)-ISNULL(a.rectotal,0)),0) AS total,
				ISNULL(SUM(ISNULL(a.naddtotal,0)-ISNULL(a.nrectotal,0)),0) AS ntotal
		FROM (SELECT  SUM(CASE	 WHEN l.billtype=45 AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.Total
								 WHEN l.BillType=11  AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.Total
								 WHEN l.billtype=160  AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.Total
								 WHEN  l.AtypeId=@aratypeID AND l.Total>0 AND l.BillType NOT IN(45,11,160) AND l.RedWord IN(0,1) THEN l.Total 
								 WHEN l.billtype=45 AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.Total
								 WHEN l.BillType=11  AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.Total
								 WHEN l.billtype=160  AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.Total
								 WHEN  l.AtypeId=@aratypeID AND l.Total>0 AND l.BillType NOT IN(45,11,160) AND l.RedWord=2 THEN -l.Total 
								 WHEN  l.AtypeId=@ysatypeID AND l.Total<0  AND l.redword IN(0,1)  THEN ABS(l.Total) 
								 WHEN  l.AtypeId=@ysatypeID AND l.Total<0  AND l.redword=2  THEN l.Total
								 ELSE 0
								END) AS addtotal,
						SUM(CASE	 WHEN l.billtype=45 AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.nTotal
								 WHEN l.BillType=11  AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.nTotal
								 WHEN l.billtype=160  AND l.AtypeId=@aratypeID AND l.RedWord IN(0,1) THEN l.nTotal
								 WHEN  l.AtypeId=@aratypeID AND l.Total>0 AND l.BillType NOT IN(45,11,160) AND l.RedWord IN(0,1) THEN l.nTotal 
								 WHEN l.billtype=45 AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.nTotal
								 WHEN l.BillType=11  AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.nTotal
								 WHEN l.billtype=160  AND l.AtypeId=@aratypeID AND l.RedWord=2 THEN -l.nTotal
								 WHEN  l.AtypeId=@aratypeID AND l.nTotal>0 AND l.BillType NOT IN(45,11,160) AND l.RedWord=2 THEN -l.nTotal 
								 WHEN  l.AtypeId=@ysatypeID AND l.nTotal<0  AND l.redword IN(0,1)  THEN ABS(l.nTotal) 
								 WHEN  l.AtypeId=@ysatypeID AND l.nTotal<0  AND l.redword=2  THEN l.nTotal
								 ELSE 0
								END) AS naddtotal,
						SUM(CASE WHEN  l.AtypeId=@aratypeID AND l.Total<0 AND  l.BillType NOT IN(45,11,160) AND l.redword IN(0,1) THEN ABS(l.Total)
								 WHEN  l.AtypeId=@aratypeID AND l.Total<0 AND  l.BillType NOT IN(45,11,160) AND l.redword IN(2) THEN l.Total
								 WHEN  l.AtypeId=@ysatypeID AND l.Total>0 THEN l.Total 
								 WHEN  l.AtypeId=@ysatypeID AND l.Total>0 THEN -l.Total 
								ELSE 0
							END) AS rectotal,
						SUM(CASE WHEN  l.AtypeId=@aratypeID AND l.nTotal<0 AND  l.BillType NOT IN(45,11,160) AND l.redword IN(0,1) THEN ABS(l.nTotal)
								 WHEN  l.AtypeId=@aratypeID AND l.nTotal<0 AND  l.BillType NOT IN(45,11,160) AND l.redword IN(2) THEN l.nTotal
								 WHEN  l.AtypeId=@ysatypeID AND l.nTotal>0 THEN l.nTotal 
								 WHEN  l.AtypeId=@ysatypeID AND l.nTotal>0 THEN -l.nTotal 
								ELSE 0
							END) AS nrectotal
				FROM #listtable l	
			)a
	END
END
ELSE
BEGIN
	IF @includePre = 0
	BEGIN
		SET @SQL='
		INSERT INTO #listtable
		(
			billnumberid,
			billtype,
			atypeid,
			redword,
			total,
			ntotal
		)
		SELECT	l.BillNumberId,
				l.BillType,
				l.AtypeId,
				bi.RedWord,
				l.Total,
				l.Ntotal
		FROM Listtable l
		INNER JOIN BillIndex bi ON L.BillNumberId=BI.BillNumberId
		INNER JOIN #stype S ON S.typeid=L.STypeID '
		
		IF @EtypeFlag = 1
			SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId '
		ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
			SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId'	
		
		SET @SQL += '
			WHERE L.BtypeId = '+CHAR(39)+@Btypeid+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+' 
				  AND L.ATypeID IN('+@apatypeID+')
				  AND L.Audited = 1
				  AND bi.redword=0 '
		IF @cid<>'0'
			SET @SQL=@SQL+'AND	 L.CID='+@cid
	
		EXEC(@SQL)
				
		IF @EtypeIsEmpty = 1
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal00,0),0)) 
			FROM	BType_ARAPTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	btypeId = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		ELSE
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal00,0),0)) 
			FROM	IniBType_ArApTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			INNER JOIN #etype E ON E.btypeid = b.BTypeID AND E.etypeid = b.ETypeId
			WHERE	B.BTypeID = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		
		
		INSERT INTO #tmpbefore (Total,nTotal)
		SELECT	ISNULL(SUM(ISNULL(a.addtotal,0)-ISNULL(a.rectotal,0)),0) AS total,
				ISNULL(SUM(ISNULL(a.naddtotal,0)-ISNULL(a.nrectotal,0)),0) AS ntotal
		FROM (SELECT	SUM(CASE  WHEN l.billtype=6 AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.Total
								  WHEN l.BillType=34  AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.Total
								  WHEN l.billtype=161  AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.Total
								  WHEN  l.AtypeId=@apatypeID AND l.Total>0 AND l.BillType NOT IN(6,34,161) AND l.redword IN (0,1) THEN l.Total 
								  WHEN l.billtype=6 AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.Total
								  WHEN l.BillType=34  AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.Total
								  WHEN l.billtype=161  AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.Total
								  WHEN  l.AtypeId=@apatypeID AND l.Total>0 AND l.BillType NOT IN(6,34,161) AND l.redword=2 THEN -l.Total 
								  ELSE 0
							END) AS addtotal,
						SUM(CASE  WHEN l.billtype=6 AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.nTotal
								  WHEN l.BillType=34  AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.nTotal
								  WHEN l.billtype=161  AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.nTotal
								  WHEN  l.AtypeId=@apatypeID AND l.Total>0 AND l.BillType NOT IN(6,34,161) AND l.redword IN (0,1) THEN l.nTotal 
								  WHEN l.billtype=6 AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.nTotal
								  WHEN l.BillType=34  AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.nTotal
								  WHEN l.billtype=161  AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.nTotal
								  WHEN  l.AtypeId=@apatypeID AND l.nTotal>0 AND l.BillType NOT IN(6,34,161) AND l.redword=2 THEN -l.nTotal 
								  ELSE 0
							END) AS naddtotal,
						SUM(CASE WHEN  l.AtypeId=@apatypeID AND l.Total<0 AND  l.BillType NOT IN(6,34,161) AND l.redword IN (0,1) THEN ABS(l.Total)
								 WHEN  l.AtypeId=@apatypeID AND l.Total<0 AND  l.BillType NOT IN(6,34,161) AND l.redword=2 THEN -1*ABS(l.Total) 
								 ELSE 0
							END) AS rectotal,
						SUM(CASE WHEN  l.AtypeId=@apatypeID AND l.nTotal<0 AND  l.BillType NOT IN(6,34,161) AND l.redword IN (0,1) THEN ABS(l.nTotal)
								 WHEN  l.AtypeId=@apatypeID AND l.nTotal<0 AND  l.BillType NOT IN(6,34,161) AND l.redword=2 THEN -1*ABS(l.nTotal) 
								 ELSE 0
							END) AS nrectotal		
				FROM #listtable l	
				)a
	END
	ELSE
	BEGIN
		SET @SQL='
		INSERT INTO #listtable
		(
			billnumberid,
			billtype,
			atypeid,
			redword,
			total,
			ntotal
		)
		SELECT  l.BillNumberId,
				l.BillType,
				l.AtypeId,
				bi.RedWord,
				l.Total,
				l.nTotal 
		FROM Listtable l
		INNER JOIN BillIndex bi ON L.BillNumberId=BI.BillNumberId
		INNER JOIN #stype S ON S.typeid=L.STypeID '
		
		IF @EtypeFlag = 1
			SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId '
		ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
			SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId'	
		
		SET @SQL += '
			WHERE L.BtypeId ='+CHAR(39)+ @Btypeid+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+' 
				AND	 L.ATypeID IN('+@apatypeID+','+@yfatypeID+')
				AND  L.Audited = 1
				AND  bi.redword=0 '
		IF @cid<>'0'
			SET @SQL=@SQL+'AND	 L.CID='+@cid
			
		EXEC(@SQL)
		
		IF @EtypeIsEmpty = 1
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal00,0)-ISNULL(b.YFTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal00,0)-ISNULL(b.nYFTotal00,0),0)) 
			FROM	BType_ARAPTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	btypeId = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		ELSE
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal00,0)-ISNULL(b.YFTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal00,0)-ISNULL(b.nYFTotal00,0),0)) 
			FROM	IniBType_ArApTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	B.BTypeID = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
				
		INSERT INTO #tmpbefore (Total,nTotal)
		SELECT	ISNULL(SUM(ISNULL(a.addtotal,0)-ISNULL(a.rectotal,0)),0) AS total,
				ISNULL(SUM(ISNULL(a.naddtotal,0)-ISNULL(a.nrectotal,0)),0) AS ntotal
		FROM (SELECT	SUM(CASE  WHEN l.billtype=6 AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.Total
								  WHEN l.BillType=34  AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.Total
								  WHEN l.billtype=161  AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.Total
								  WHEN  l.AtypeId=@apatypeID AND l.Total>0 AND l.BillType NOT IN(6,34,161) AND l.redword IN (0,1) THEN l.Total 
								  WHEN l.billtype=6 AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.Total
								  WHEN l.BillType=34  AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.Total
								  WHEN l.billtype=161  AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.Total
								  WHEN  l.AtypeId=@apatypeID AND l.Total>0 AND l.BillType NOT IN(6,34,161) AND l.redword=2 THEN -l.Total 
								  WHEN  l.AtypeId=@yfatypeID AND l.Total<0 AND l.redword IN (0,1) THEN ABS(l.Total) 
								  WHEN  l.AtypeId=@yfatypeID AND l.Total<0 AND l.redword=2  THEN l.Total
								  ELSE 0
							END) AS addtotal,
						SUM(CASE  WHEN l.billtype=6 AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.nTotal
								  WHEN l.BillType=34  AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.nTotal
								  WHEN l.billtype=161  AND l.AtypeId=@apatypeID AND l.redword IN (0,1) THEN l.nTotal
								  WHEN  l.AtypeId=@apatypeID AND l.Total>0 AND l.BillType NOT IN(6,34,161) AND l.redword IN (0,1) THEN l.nTotal 
								  WHEN l.billtype=6 AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.nTotal
								  WHEN l.BillType=34  AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.nTotal
								  WHEN l.billtype=161  AND l.AtypeId=@apatypeID AND l.redword=2 THEN -l.nTotal
								  WHEN  l.AtypeId=@apatypeID AND l.nTotal>0 AND l.BillType NOT IN(6,34,161) AND l.redword=2 THEN -l.nTotal 
								  WHEN  l.AtypeId=@yfatypeID AND l.nTotal<0 AND l.redword IN (0,1) THEN ABS(l.nTotal) 
								  WHEN  l.AtypeId=@yfatypeID AND l.nTotal<0 AND l.redword=2  THEN l.nTotal
								  ELSE 0
							END) AS naddtotal,
						SUM(CASE WHEN  l.AtypeId=@apatypeID AND l.Total<0 AND  l.BillType NOT IN(6,34,161) AND l.redword IN (0,1) THEN ABS(l.Total)
								 WHEN  l.AtypeId=@apatypeID AND l.Total<0 AND  l.BillType NOT IN(6,34,161) AND l.redword=2 THEN -1*ABS(l.Total) 
								 WHEN  l.AtypeId=@yfatypeID AND l.Total>0 AND l.redword IN (0,1) THEN l.Total 
								 WHEN  l.AtypeId=@yfatypeID AND l.Total>0 AND l.redword=2 THEN -l.Total
								 ELSE 0
							END) AS rectotal,
						SUM(CASE WHEN  l.AtypeId=@apatypeID AND l.nTotal<0 AND  l.BillType NOT IN(6,34,161) AND l.redword IN (0,1) THEN ABS(l.nTotal)
								 WHEN  l.AtypeId=@apatypeID AND l.nTotal<0 AND  l.BillType NOT IN(6,34,161) AND l.redword=2 THEN -1*ABS(l.nTotal) 
								 WHEN  l.AtypeId=@yfatypeID AND l.nTotal>0 AND l.redword IN (0,1) THEN l.nTotal 
								 WHEN  l.AtypeId=@yfatypeID AND l.nTotal>0 AND l.redword=2 THEN -l.nTotal
								 ELSE 0
							END) AS nrectotal
				FROM #listtable l	
				)a
	END
END


SELECT	@SumARTotal=SUM(ISNULL(Total,0)), 
		@nSumARTotal=SUM(ISNULL(nTotal,0))
FROM #tmpBefore


SELECT @PreTotal=ISNULL(@CurToal,0) + ISNULL(@SumARTotal,0)  ---期初应收余额+(这段日期的应收变化量[本币])

SELECT @nPreTotal=ISNULL(@nCurToal,0) + ISNULL(@nSumARTotal,0)  ---期初应收余额+(这段日期的应收变化量[原币])

DROP TABLE #tmpbefore,#stype,#listtable,#etype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetBeforeArOrApYsYf]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_GetBeforeArOrApYsYf]
GO

/*
	作者:王刚
	日期:2014-11-19
	描述:应收应付查询此前余额 (期初中,需要与部门相关联)
	备注:从存储过程Gp_GetBeforeArOrAp中复制过来的

*/
CREATE  PROCEDURE Gp_GetBeforeArOrApYsYf
(
	@OperatorID 	VARCHAR(100),  	            --操作员ID号
	@nType        	INT=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@StartDate 		VARCHAR(20),	            --时间点
	@BtypeID 		VARCHAR(MAX),               --客户typeid
	@showRedWord	INT=1,						--是否显示红冲单据
	@stypeid		VARCHAR(MAX),
	@includePre		BIT,
	@cid			VARCHAR(10),				--币别
	@PreTotal 		 NUMERIC(24, 10)  OUTPUT,     	--返回余额(本币)
	@nPreTotal 		 NUMERIC(24, 10)  OUTPUT,     	--返回余额(原币)
	@dtypeid		VARCHAR(MAX),	--部门
	@DtypeIsVisible	INT				--1=使用部门 0=不使用部门
	)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MDTypeId VARCHAR(50),@MSTypeId VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
DECLARE @CurToal         NUMERIC(24, 10) ,
		@nCurToal        NUMERIC(24, 10) ,
		@SumARTotal      NUMERIC(24, 10) ,
		@nSumARTotal     NUMERIC(24, 10) ,
		@aratypeID	    VARCHAR(50),
		@ysatypeID	    VARCHAR(50),
		@apatypeID	    VARCHAR(50),
		@yfatypeID	    VARCHAR(50)

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

IF LEFT(@btypeid,5)='00001'
	IF LEN(@btypeid)<LEN(@MBtypeid)
		SET @btypeid=@MBtypeid
IF LEFT(@btypeid,5)='00002'
	IF LEN(@btypeid)<LEN(@MBtypeid2)
		SET @btypeid=@MBtypeid2
		
CREATE TABLE #listtable
(
	billnumberid	INT,
	billtype		INT,
	atypeid			VARCHAR(100),
	redword			INT,
	total			 NUMERIC(24, 10) ,
	ntotal			 NUMERIC(24, 10) 
)
CREATE NONCLUSTERED INDEX cix_listtable_typeid ON #listtable(billnumberid)

--分支机构
CREATE TABLE #stype(typeid	VARCHAR(100))
CREATE NONCLUSTERED INDEX cix_stype_typeid ON #stype(typeid)

INSERT INTO #stype(typeid) SELECT  A.typeid FROM	F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

CREATE TABLE #dtype(typeid VARCHAR(100))
CREATE NONCLUSTERED INDEX cix_dtype_typeid ON #dtype(typeid)

IF @DtypeIsVisible = 1 AND @dtypeid <> ''
	INSERT #dtype(typeid) SELECT TypeId FROM F_GetAllBaseTypeId(@dtypeid,9)

CREATE TABLE #tmpBefore(Total  NUMERIC(24, 10) ,nTotal  NUMERIC(24, 10) )

DECLARE @SQL VARCHAR(MAX)

IF @nType=1
BEGIN
	IF @includePre = 0
	BEGIN
	SET @SQL='
		INSERT INTO #listtable
		(
			billnumberid,
			billtype,
			atypeid,
			redword,
			total,
			ntotal
		)
		SELECT  l.BillNumberId,
				l.BillType,
				l.AtypeId,
				0,
				l.Total,
				L.Ntotal 
		FROM Listtable l
		--INNER JOIN BillIndex bi ON L.BillNumberId=BI.BillNumberId
		INNER JOIN #stype S ON S.typeid=L.STypeID '
		
		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @SQL += ' INNER JOIN #dtype D ON D.typeid=L.DTypeID '
		
		SET @SQL += '
			WHERE L.BtypeId = '+CHAR(39)+@Btypeid+CHAR(39)+' AND L.BillDate <'+CHAR(39)+@StartDate+CHAR(39)+'
					AND	 L.ATypeID IN('+@aratypeID+')
					AND  L.Audited = 1
					'
		IF @cid<>'0'
			SET @SQL=@SQL+'AND	 L.CID='+@cid
		
		
		EXEC(@SQL)	
		
		IF @dtypeid = ''
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(b.ARTotal00,0)),
					@nCurToal= SUM(ISNULL(b.nARTotal00,0)) 
			FROM	BType_ARAPTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	btypeId = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		ELSE
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(b.ARTotal00,0)),
					@nCurToal= SUM(ISNULL(b.nARTotal00,0)) 
			FROM	IniBType_ArApTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID
			INNER JOIN #dtype D ON D.typeid = B.DTypeId
			WHERE	b.BTypeID = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		
		INSERT INTO #tmpbefore (Total,nTotal)
			SELECT SUM(l.Total) AS total,SUM(l.NTotal) AS ntotal
			FROM #listtable   L
			
	 

	END
	ELSE
	BEGIN
		SET @SQL='
		INSERT INTO #listtable
		(
			billnumberid,
			billtype,
			atypeid,
			redword,
			total,
			ntotal
		)
		SELECT  l.BillNumberId,
				l.BillType,
				l.AtypeId,
				0,
				l.Total,
				l.Ntotal 
		FROM Listtable l
		--INNER JOIN BillIndex bi ON L.BillNumberId=BI.BillNumberId
		INNER JOIN #stype S ON S.typeid=L.STypeID '
		
		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @SQL += ' INNER JOIN #dtype D ON D.typeid=L.DTypeID '
		
		SET @SQL += '
			WHERE L.BtypeId ='+CHAR(39)+ @Btypeid+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+' 
				AND	 L.ATypeID IN('+@aratypeID+','+@ysatypeID+')
				AND  L.Audited = 1
				--AND  bi.redword=0 '
		IF @cid<>'0'
			SET @SQL=@SQL+'AND	 L.CID='+@cid
		EXEC(@SQL)	
		
		IF @dtypeid = ''
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.ARTotal00,0)-ISNULL(b.YSTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nARTotal00,0)-ISNULL(b.nYSTotal00,0),0)) 
			FROM	BType_ARAPTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	btypeId = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		ELSE
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.ARTotal00,0)-ISNULL(b.YSTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nARTotal00,0)-ISNULL(b.nYSTotal00,0),0)) 
			FROM	IniBType_ArApTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID
			INNER JOIN #dtype d ON d.typeid = b.DTypeId
			WHERE	b.BTypeID = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		  INSERT INTO #tmpbefore (Total,nTotal)
			SELECT SUM(CASE WHEN l.AtypeId=@aratypeID THEN l.Total ELSE -l.Total END) AS total,
				   SUM(CASE WHEN l.AtypeId=@aratypeID THEN l.NTotal  ELSE -l.nTotal END) AS ntotal
			FROM #listtable   L
	END
END
ELSE
BEGIN
	IF @includePre = 0
	BEGIN
		SET @SQL='
		INSERT INTO #listtable
		(
			billnumberid,
			billtype,
			atypeid,
			redword,
			total,
			ntotal
		)
		SELECT	l.BillNumberId,
				l.BillType,
				l.AtypeId,
				0,
				l.Total,
				l.Ntotal
		FROM Listtable l
		--INNER JOIN BillIndex bi ON L.BillNumberId=BI.BillNumberId
		INNER JOIN #stype S ON S.typeid=L.STypeID  '
		
		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @SQL += ' INNER JOIN #dtype D ON D.typeid=L.DTypeID '
		
		SET @SQL += '
			WHERE L.BtypeId = '+CHAR(39)+@Btypeid+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+' 
				AND	 L.ATypeID IN('+@apatypeID+')
				AND  L.Audited = 1
				--AND bi.redword=0 '
		IF @cid<>'0'
			SET @SQL=@SQL+'AND	 L.CID='+@cid
	
		EXEC(@SQL)
		
		IF @dtypeid = ''
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal00,0),0)) 
			FROM	BType_ARAPTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	btypeId = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		ELSE
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal00,0),0)) 
			FROM	IniBType_ArApTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			INNER JOIN #dtype d ON d.typeid = b.DTypeId
			WHERE	B.BTypeID = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		
		INSERT INTO #tmpbefore (Total,nTotal)
			SELECT SUM(l.Total) AS total,SUM(l.NTotal) AS ntotal
			FROM #Listtable   L
	END
	ELSE
	BEGIN
		SET @SQL='
		INSERT INTO #listtable
		(
			billnumberid,
			billtype,
			atypeid,
			redword,
			total,
			ntotal
		)
		SELECT  l.BillNumberId,
				l.BillType,
				l.AtypeId,
				0,
				l.Total,
				l.nTotal 
		FROM Listtable l
		--INNER JOIN BillIndex bi ON L.BillNumberId=BI.BillNumberId
		INNER JOIN #stype S ON S.typeid=L.STypeID '
		
		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @SQL += ' INNER JOIN #dtype D ON D.typeid=L.DTypeID '
		
		
		SET @SQL += '
			WHERE L.BtypeId ='+CHAR(39)+ @Btypeid+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+' 
				AND	 L.ATypeID IN('+@apatypeID+','+@yfatypeID+')
				AND  L.Audited = 1
				--AND  bi.redword=0 '
		IF @cid<>'0'
			SET @SQL=@SQL+'AND	 L.CID='+@cid
			
		EXEC(@SQL)
		
		IF @dtypeid = ''
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal00,0)-ISNULL(b.YFTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal00,0)-ISNULL(b.nYFTotal00,0),0)) 
			FROM	BType_ARAPTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	btypeId = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
		ELSE
		BEGIN
			SELECT	@CurToal= SUM(ISNULL(ISNULL(b.APTotal00,0)-ISNULL(b.YFTotal00,0),0)),
					@nCurToal= SUM(ISNULL(ISNULL(b.nAPTotal00,0)-ISNULL(b.nYFTotal00,0),0)) 
			FROM	IniBType_ArApTotal b 
			INNER JOIN #stype s ON s.typeid=b.STypeID 
			WHERE	B.BTypeID = @Btypeid  
			AND (B.CID=@cid OR @cid = '0')
			GROUP BY b.BTypeID  --期初应收余额
		END
				
		INSERT INTO #tmpbefore (Total,nTotal)
			SELECT SUM(CASE WHEN l.AtypeId=@apatypeID THEN l.Total ELSE -l.Total END) AS total,
				   SUM(CASE WHEN l.AtypeId=@apatypeID THEN l.NTotal  ELSE -l.nTotal END) AS ntotal
			FROM #Listtable   L
	END
END

	
SELECT	@SumARTotal=SUM(ISNULL(Total,0)), 
		@nSumARTotal=SUM(ISNULL(nTotal,0))
FROM #tmpBefore

SELECT @PreTotal=ISNULL(@CurToal,0) + ISNULL(@SumARTotal,0)  ---期初应收余额+(这段日期的应收变化量[本币])

SELECT @nPreTotal=ISNULL(@nCurToal,0) + ISNULL(@nSumARTotal,0)  ---期初应收余额+(这段日期的应收变化量[原币])

DROP TABLE #tmpbefore,#stype,#listtable,#dtype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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








/*
	作者:谢吉康
	日期:2005-5-18
	描述:处理经手人查询
*/
CREATE  PROCEDURE Gp_GetBeforeDateAROrAPBalance23
(
	@OperatorID 	varchar(100),  	            --操作员ID号
	@nType        	int=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@StartDate 		varchar(20),	            --时间点
	@BtypeID 		varchar(100),               --客户typeid
	@ETypeId		varchar(8000)='',			--经手人Id
	@showZero		int=1,						--是否显示红冲单据
	@stypeid		varchar(50),
	@PreTotal 		 NUMERIC(24, 10)  OUTPUT     	--返回余额
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId varchar(50), @MBTypeid varchar(50), @MBTypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MDTypeId VARCHAR(50),@MSTypeId VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------

DECLARE @CurToal  NUMERIC(24, 10) ,@SumARTotal  NUMERIC(24, 10) ,@SumAPTotal  NUMERIC(24, 10) 
IF LEFT(@btypeid,5)='00001'
	IF len(@btypeid)<len(@MBtypeid)
		SET @btypeid=@MBtypeid
IF LEFT(@btypeid,5)='00002'
	IF len(@btypeid)<len(@MBtypeid2)
		SET @btypeid=@MBtypeid2
	
create table #stype
(
	typeid		varchar(50)
)

--分支机构
INSERT INTO #stype(typeid) 
SELECT  A.typeid
FROM	F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

CREATE TABLE #EmpResult(TypeId	varchar(100))

SELECT	@CurToal= sum(isnull(b.ARTotal00-b.ApTotal00,0)) 
FROM	BType_ARAPTotal b 
INNER JOIN #stype s on s.typeid=b.STypeID 
WHERE	btypeId = @Btypeid  
group by b.STypeID,b.BTypeID--期初应收余额

--IF @@RowCount=0  RETURN 1 --没有客户

CREATE TABLE #tmpArBefore(Total  NUMERIC(24, 10) )

CREATE TABLE #tmpApBefore(Total  NUMERIC(24, 10) )

IF @MSTypeId='00000' AND @stypeid=''
BEGIN
	IF @showZero = 0
		BEGIN
			IF @ETypeId<>''
				INSERT INTO #tmpARbefore SELECT total FROM ListTable WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000100005' AND Audited = 1 AND ETypeId IN (SELECT TypeId FROM #EmpResult) 
			ELSE
				INSERT INTO #tmpARbefore SELECT total FROM ListTable WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000100005' AND Audited = 1
		END
	ELSE
		BEGIN
			IF @ETypeId<>''
				INSERT INTO #tmpARbefore SELECT total FROM ListTable WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000100005' AND ETypeId IN (SELECT TypeId FROM #EmpResult)
			ELSE
				INSERT INTO #tmpARbefore SELECT total FROM ListTable WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000100005'
		END
END
ELSE
BEGIN
	IF @showZero = 0
	BEGIN
		IF @ETypeId<>''
			INSERT INTO #tmpARbefore SELECT total FROM ListTable INNER JOIN #stype S ON S.typeid=Listtable.STypeID WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000100005' AND Audited = 1 AND ETypeId IN (SELECT TypeId FROM #EmpResult) 
		ELSE
			INSERT INTO #tmpARbefore SELECT total FROM ListTable INNER JOIN #stype S ON S.typeid=Listtable.STypeID WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000100005' AND Audited = 1
	END
ELSE
	BEGIN
		IF @ETypeId<>''
			INSERT INTO #tmpARbefore SELECT total FROM ListTable INNER JOIN #stype S ON S.typeid=Listtable.STypeID WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000100005' AND ETypeId IN (SELECT TypeId FROM #EmpResult)
		ELSE
			INSERT INTO #tmpARbefore SELECT total FROM ListTable INNER JOIN #stype S ON S.typeid=Listtable.STypeID WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000100005'
	END
END

SELECT @SumARTotal=SUM(ISNULL(Total,0)) FROM #tmpARbefore
IF @MSTypeId='00000' AND @stypeid=''
BEGIN
	IF @showZero = 0
		BEGIN
			IF @ETypeId<>''
				INSERT INTO #tmpAPbefore SELECT total FROM ListTable WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000200001'  AND Audited = 1 AND ETypeId IN (SELECT TypeId FROM #EmpResult)
			ELSE
				INSERT INTO #tmpAPbefore SELECT total FROM ListTable WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000200001'  AND Audited = 1
		END
	ELSE
		BEGIN
			IF @ETypeId<>''
				INSERT INTO #tmpAPbefore SELECT total FROM ListTable WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000200001' AND ETypeId IN (SELECT TypeId FROM #EmpResult)
			ELSE
				INSERT INTO #tmpAPbefore SELECT total FROM ListTable WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000200001'
		END
end
else
begin
	IF @showZero = 0
		BEGIN
			IF @ETypeId<>''
				INSERT INTO #tmpAPbefore SELECT total FROM ListTable INNER JOIN #stype S ON S.typeid=Listtable.STypeID WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000200001'  AND Audited = 1 AND ETypeId IN (SELECT TypeId FROM #EmpResult)
			ELSE
				INSERT INTO #tmpAPbefore SELECT total FROM ListTable INNER JOIN #stype S ON S.typeid=Listtable.STypeID WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000200001'  AND Audited = 1
		END
	ELSE
		BEGIN
			IF @ETypeId<>''
				INSERT INTO #tmpAPbefore SELECT total FROM ListTable INNER JOIN #stype S ON S.typeid=Listtable.STypeID WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000200001' AND ETypeId IN (SELECT TypeId FROM #EmpResult)
			ELSE
				INSERT INTO #tmpAPbefore SELECT total FROM ListTable INNER JOIN #stype S ON S.typeid=Listtable.STypeID WHERE BtypeId = @Btypeid AND BillDate<@StartDate AND ATypeID='0000200001'
		END
end
SELECT @SumAPTotal=SUM(ISNULL(Total,0)) FROM #tmpAPbefore

SELECT @PreTotal=isnull(@CurToal,0)+ISNULL(@SumARTotal,0)-ISNULL(@SumAPTotal,0)---期初应收余额+(这段日期的应收变化量)

DROP TABLE #tmpARbefore,#tmpAPbefore,#EmpResult,#stype

IF @nType=2 OR @nType=4
	SET @PreTotal=-@PreTotal














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

---------------------------------------------------------------
--获取单据的自动编号
	--修改记录#01----------------------------------------------
	--人员：王浩源
	--日期：2003-09-24
	--说明：修改自动编号的bug，案例如下：
	--如果用户输入的一个单据编号如下FY-test-0924-0925-0001
	--那么在0925日录入的单据会自动编号为FY-test-0925-0002
	--这样是不对的，应该产生的自动编号为FY-test-0925-0001
---------------------------------------------------------------
---------------------------------------------------------------
--获取单据的自定义编号
	--修改记录#02----------------------------------------------
	--人员：徐辉
	--日期：2004-12-15
	--说明：客户系统采用自定义编号，且改种单据设了自定义编号
	
	--#2019-11-12 陈强(版本991)
	--#263行
---------------------------------------------------------------
CREATE                           PROCEDURE Gp_GetBillCode
(
	@BType		INT,
	@MONTH		VARCHAR(500), 		--自动产生编号时为月份，自定义编号时是经手人名字
	@DAY		VARCHAR(500),		--自动产生编号时为日期，自定义编号时为仓库名
	@BillFlag	VARCHAR(100),
	@BillDate	VARCHAR(100)='',
	@Stypeid	VARCHAR(500)='',	--分支机构名称	
	@BCode		VARCHAR(500) OUTPUT,
	@DFullName VARCHAR(500)='',	--部门
	@CEFullName VARCHAR(500)='',	--制单人
	@BillNumberId	INT = -1
)
 
AS
SET NOCOUNT ON
DECLARE @BillCodeConfig varchar(1),@FlowLen INT
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置

DECLARE @IfBillCode INT
SELECT @IfBillCode=Value FROM UserConfig WHERE ConfigName='IfBillCode'
IF @BillNumberId=-999 ---库存预警生单 强行置为空
SET @BCode=''
--提车规则单不需要分支机构，强行置为空
IF @BType=164 OR @BType=309 OR @BType=410
	SET @Stypeid=''

IF @IfBillCode=0
BEGIN
	SET @BCode=''
	RETURN
END


IF @BillDate=''
BEGIN
	SELECT @BillDate=CAST(YEAR(GETDATE()) AS VARCHAR(4))+'-'+CAST(MONTH(GETDATE()) AS VARCHAR(2))+'-'+CAST(DAY(GETDATE()) AS VARCHAR(2))
END


--增加的判断。当已保存的单据（草稿、全面修改）切换再切换时，如果影响单据编号的条件没有变，直接返回已有单据编号，不更新种子数
DECLARE @yetypeid VARCHAR(50),@yktypeid VARCHAR(50),@ydtypeid VARCHAR(50)
SET @yetypeid = ''
SET @yktypeid = ''
SET @ydtypeid = ''
--如果是经手人，就按经手人、仓库查询
IF EXISTS(SELECT TOP 1 1 FROM dbo.employee WHERE typeId = @MONTH)
BEGIN
	SELECT @yetypeid = typeId FROM dbo.employee WHERE typeId = @MONTH
	SELECT @yktypeid = typeId FROM dbo.Stock WHERE FullName = @DAY
END

SELECT @ydtypeid = typeid FROM dbo.Department WHERE FullName = @DFullName

IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex 
			WHERE BillNumberId = @BillNumberId
				AND (etypeid = @yetypeid  OR @yetypeid = '')
				AND (ktypeid = @yktypeid OR @yktypeid = '')
				AND (BillDate = @BillDate OR @BillDate = '')
				AND (Stypeid = @Stypeid OR @Stypeid = '')
				AND (DTypeId = @ydtypeid OR @ydtypeid = '') )
		AND @BType NOT IN (300,301,313,404,405,311,418,419,420,421,422,423,424,425,426)
BEGIN
	SELECT @BCode = BillCode FROM dbo.BillIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillCode = @BCode AND BillNumberId <> @BillNumberId)
		SET @BCode = ''
END

ELSE IF	EXISTS(SELECT TOP 1 1 FROM dbo.OrderIndex 
		WHERE BillNumberId = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (ktypeid = @yktypeid OR @yktypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			AND (Stypeid = @Stypeid OR @Stypeid = '')
			AND (DTypeId = @ydtypeid OR @ydtypeid = '') )
	AND @BType IN (300,301,313)
BEGIN
	SELECT @BCode = BillCode FROM dbo.OrderIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.OrderIndex WHERE Billcode = @BCode AND billNumberId <> @BillNumberId)
		SET @BCode = ''
END
ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex 
		WHERE BillNumberId = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			AND (Stypeid = @Stypeid OR @Stypeid = '')
			AND (DTypeId = @ydtypeid OR @ydtypeid = '') )
	AND @BType IN (404,405)
BEGIN
	SELECT @BCode = BillCode FROM dbo.ReceiptBillIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex WHERE BillCode = @BCode AND BillNumberID <> @BillNumberId)
		SET @BCode = ''
END
ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.CommissionBillNew 
		WHERE BillNumberId = @BillNumberId
			AND (BillDate = @BillDate OR @BillDate = '')
			)
	AND @BType IN (311)
BEGIN		
	SELECT @BCode = BillCode FROM dbo.CommissionBillNew WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.CommissionBillNew WHERE BillCode = @BCode AND BillNumberId <> @BillNumberId)
		SET @BCode = ''
END
ELSE IF	EXISTS(SELECT TOP 1 1 FROM dbo.StockCheckIndex 
		WHERE StockCheckID = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			)
	AND @BType IN (306)
BEGIN		
	SELECT @BCode = BillCode FROM dbo.StockCheckIndex WHERE StockCheckID = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.StockCheckIndex WHERE BillCode = @BCode AND StockCheckID <> @BillNumberId)
		SET @BCode = ''
END
ELSE IF	EXISTS(SELECT TOP 1 1 FROM dbo.onShelvespickIndex 
		WHERE BillNumberId = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (ktypeid = @yktypeid OR @yktypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			AND (Stypeid = @Stypeid OR @Stypeid = '')
			AND (DTypeId = @ydtypeid OR @ydtypeid = '')
			)
	AND @BType IN (412,413)
BEGIN		
	SELECT @BCode = BillCode FROM dbo.onShelvespickIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.onShelvespickIndex WHERE BillCode = @BCode AND BillNumberId <> @BillNumberId)
		SET @BCode = ''
END
--实物库存	
ELSE IF	EXISTS(SELECT TOP 1 1 FROM dbo.FactIndex 
		WHERE BillNumberId = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (ktypeid = @yktypeid OR @yktypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			AND (Stypeid = @Stypeid OR @Stypeid = '')
			AND (DTypeId = @ydtypeid OR @ydtypeid = '')
			)
	AND @BType IN (418,419,420,421,422)
BEGIN		

	SELECT @BCode = BillCode FROM dbo.FactIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.FactIndex WHERE BillCode = @BCode AND BillNumberId <> @BillNumberId)

		SET @BCode = ''
END
ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_BillIndex 
		WHERE BillNumberId = @BillNumberId
			AND (etypeid = @yetypeid  OR @yetypeid = '')
			AND (OutKTypeId = @yktypeid OR @yktypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			AND (Stypeid = @Stypeid OR @Stypeid = '')
			AND (DTypeId = @ydtypeid OR @ydtypeid = '') )
	AND @BType IN (423,424,425,426,428,429)
BEGIN
	SELECT @BCode = BillCode FROM dbo.Coupon_BillIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_BillIndex WHERE BillCode = @BCode AND BillNumberID <> @BillNumberId)
		SET @BCode = ''
END
ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.PosAllotApplyBillIndex 
		WHERE BillNumberId = @BillNumberId
			AND (ApplyEtypeId = @yetypeid  OR @yetypeid = '')
			AND (KtypeId = @yktypeid OR @yktypeid = '')
			AND (BillDate = @BillDate OR @BillDate = '')
			AND (Stypeid = @Stypeid OR @Stypeid = '')
			AND (DTypeId = @ydtypeid OR @ydtypeid = '') )
	AND @BType IN (326,327,328,329)
BEGIN
	SELECT @BCode = BillCode FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.PosAllotApplyBillIndex WHERE BillCode = @BCode AND BillNumberID <> @BillNumberId)
		SET @BCode = ''
END


IF @BCode <> ''
	 RETURN

SELECT @FlowLen=CAST(Value AS INT)+3 FROM UserConfig WHERE ConfigName='FlowLen'

DECLARE
	@FlowDate				VARCHAR(100)
	
--单据编号配置
DECLARE @BillcodeCreateTime varchar(5),@FlowSet varchar(5),@BillcodeDateSeparator varchar(5),
		@monthSeparator varchar(5),@daySeparator varchar(5),@yearSeparator varchar(5)
SELECT  @BillcodeCreateTime=value FROM Userconfig WHERE ConfigName='BillcodeCreateTime' 
---9.91更新，Flowset取每个单据自己设置的值，(废弃UserConfig的FlowSet)
--SELECT  @FlowSet=value FROM Userconfig WHERE ConfigName='FlowSet'
SELECT  @FlowSet=CodeFlowset FROM CodeConfig WHERE Billtype=@BType

IF @FlowSet IS NULL
BEGIN
	SELECT @FlowSet=Value
	FROM UserConfig
	WHERE ConfigName='FlowSet'
END

SELECT  @BillcodeDateSeparator=Value FROM Userconfig WHERE ConfigName='BillcodeDateSeparator' 

DECLARE @ProInfo varchar(5),@QpEdit VARCHAR(5)
SELECT  @ProInfo=SubValue FROM sysdata WHERE SubName='ProInfo'
SELECT  @QpEdit=SubValue FROM sysdata WHERE SubName='QPEdition'


IF @BillcodeDateSeparator='0'
	SELECT @monthSeparator='-',@daySeparator='',@yearSeparator='-'
ELSE IF @BillcodeDateSeparator='1'
	SELECT @monthSeparator='.',@daySeparator='',@yearSeparator='.'
ELSE IF @BillcodeDateSeparator='2'
	SELECT @monthSeparator='月',@daySeparator='日',@yearSeparator='年'
ELSE IF @BillcodeDateSeparator='3'
	SELECT @monthSeparator='',@daySeparator='',@yearSeparator=''
ELSE IF @BillcodeDateSeparator='4'
	SELECT @monthSeparator=' ',@daySeparator='',@yearSeparator=' '
	
IF @FlowSet=0
BEGIN
	--按日
	SELECT @FlowDate=DBO.FN_FixStr(4,CAST(YEAR(@BillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@BillDate) AS VARCHAR(2)),'0')+DBO.FN_FixStr(2,CAST(DAY(@BillDate) AS VARCHAR(2)),'0')
END
ELSE IF @FlowSet=1
BEGIN
	--按月
	SELECT @FlowDate=DBO.FN_FixStr(4,CAST(YEAR(@BillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@BillDate) AS VARCHAR(2)),'0')
END
ELSE IF @FlowSet=2
BEGIN
	--按年
	SELECT @FlowDate=DBO.FN_FixStr(4,CAST(YEAR(@BillDate) AS VARCHAR(4)),'0')
END
	
DECLARE @szSUsercode varchar(500)
SET @szSUserCode=''
IF EXISTS( SELECT * FROM SType WHERE TypeId=@Stypeid)
		SELECT @szSUserCode=UserCode FROM SType WHERE TypeId=@Stypeid

IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@BType  AND (Code1<>'' or Code2<>'' OR Code3<>'' OR Code4<>''
OR Code5<>'' OR Code6<>'' OR Code7<>'' OR Code8<>'' OR Code9<>'' OR Code10<>'' OR Code11<>'' OR Code12<>'' OR Code13<>'' )) AND @BillCodeConfig='1'
 --单据采用自定义编号 #02
BEGIN	
	DECLARE @Code1 varchar(100),@Code2 varchar(100),@Code3 varchar(100),@Code4 varchar(100),@Code5 varchar(100),
			@Code6 varchar(100),@Code7 varchar(100),@Code8 varchar(100),@Code9 varchar(100),@Code10 varchar(100),
			@Code11 varchar(100),@Code12 varchar(100)
	DECLARE @szEUsercode varchar(100)
	DECLARE @szKusercode varchar(100)
	DECLARE @szDUsercode VARCHAR(100)
	DECLARE @szCEUsercode VARCHAR(100)

	SET @szEUsercode=''
	SET @szKusercode=''
	SET @szDUsercode=''
	SET @szCEUsercode=''
	
	IF EXISTS( SELECT * FROM employee WHERE typeId=@MONTH)
		SELECT @szEUserCode=UserCode FROM employee WHERE typeId=@MONTH
	IF EXISTS( SELECT * FROM stock WHERE FullName=@DAY)
		SELECT @szKUserCode=UserCode FROM stock WHERE FullName=@DAY
	IF EXISTS(SELECT * FROM dbo.Department WHERE FullName=@DFullName )
		SELECT @szDUserCode=UserCode FROM dbo.Department WHERE FullName=@DFullName
	IF ISNULL(@CEFullName,'')=''
	BEGIN
		SELECT @szCEUsercode=@szEUserCode
	END
	ELSE
		IF EXISTS(SELECT * FROM dbo.employee WHERE FullName=@CEFullName )
			SELECT @szCEUsercode=UserCode FROM dbo.employee WHERE FullName=@CEFullName
	
	DECLARE
		@intFlowType			INT,		--1，按日，2按月，3按年
		@TempCode				VARCHAR(1000)


	SELECT 	@Code1=code1,@Code2=code2,@Code3=code3,@Code4=code4,@Code5=code5,@Code6=code6,@Code7=code7,@Code8=code8,
			@Code9=code9,@Code10=code10,@Code11=code11,@Code12=code12  FROM CodeConfig WHERE BillType = @BType

	SET @TempCode = @Code1 +'%'+ @Code2 +'%'+ @Code3 +'%'+ @Code4 +'%'+ @Code5 +'%'+ @Code6 +'%'+ @Code7 +'%'+ @Code8 +'%'+ @Code9 +'%'+ @Code10 +'%'+ @Code11 +'%'+ @Code12
	
	--dbo.F_Get_YMD_NEW为自定义转换函数
	SELECT 	@Code1=dbo.F_Get_YMD_NEW(code1,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code2=dbo.F_Get_YMD_NEW(code2,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code3=dbo.F_Get_YMD_NEW(code3,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)
	,@Code4=dbo.F_Get_YMD_NEW(code4,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code5=dbo.F_Get_YMD_NEW(code5,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
	@Code6=dbo.F_Get_YMD_NEW(code6,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code7=dbo.F_Get_YMD_NEW(code7,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
	@Code8=dbo.F_Get_YMD_NEW(code8,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
			@Code9=dbo.F_Get_YMD_NEW(code9,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code10=dbo.F_Get_YMD_NEW(code10,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
			@Code11=dbo.F_Get_YMD_NEW(code11,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),@Code12=dbo.F_Get_YMD_NEW(code12,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)  FROM CodeConfig WHERE BillType = @BType
	DECLARE @Code varchar(500)
	SET @Code = @Code1 +'%'+ @Code2 +'%'+ @Code3 +'%'+ @Code4 +'%'+ @Code5 +'%'+ @Code6 +'%'+ @Code7 +'%'+ @Code8 +'%'+ @Code9 +'%'+ @Code10 +'%'+ @Code11 +'%'+ @Code12

	DECLARE
		@intByKTypeID		INT,
		@intByETypeID		INT,
		@intByDTypeID		INT,
		@intByCETypeID		INT,
		@intBySTypeID		INT,
		@KTypeID			VARCHAR(50),
		@ETypeID			VARCHAR(50),
		@DTypeId			VARCHAR(50),
		@CETypeId			VARCHAR(50)
		
	--是否更新种子数
	DECLARE @UpdateSeed int
	SET @UpdateSeed = 1
	
	IF UPPER(@Code1)='#KK#' OR UPPER(@Code2)='#KK#' OR UPPER(@Code3)='#KK#' OR UPPER(@Code4)='#KK#' OR UPPER(@Code5)='#KK#' OR UPPER(@Code6)='#KK#' OR UPPER(@Code7)='#KK#' OR UPPER(@Code8)='#KK#' OR UPPER(@Code9)='#KK#' OR UPPER(@Code10)='#KK#' OR UPPER(@Code11)='#KK#' OR UPPER(@Code12)='#KK#'
	BEGIN
		SET @intByKTypeID=1

		IF @szKUserCode=''
		BEGIN
		    --print ' @szKUserCode=null '
			SELECT @KTypeID=''
			SET @UpdateSeed = 0
		END
		ELSE
		BEGIN
			SELECT @KTypeID=TypeID
			FROM Stock
			WHERE UserCode=@szKUserCode
		END
	END
	ELSE
	BEGIN
		SET @intByKTypeID=0
	END

	IF UPPER(@Code1)='#EE#' OR UPPER(@Code2)='#EE#' OR UPPER(@Code3)='#EE#' OR UPPER(@Code4)='#EE#' OR UPPER(@Code5)='#EE#' OR UPPER(@Code6)='#EE#' OR UPPER(@Code7)='#EE#' OR UPPER(@Code8)='#EE#' OR UPPER(@Code9)='#EE#' OR UPPER(@Code10)='#EE#' OR UPPER(@Code11)='#EE#' OR UPPER(@Code12)='#EE#'
	BEGIN
		SET @intByETypeID=1

		IF @szEUserCode=''
		BEGIN
		    --print ' @szEUserCode=null '
			SELECT @ETypeID=''
			SET @UpdateSeed = 0
		END
		ELSE
		BEGIN
			SELECT @ETypeID=TypeID
			FROM Employee
			WHERE UserCode=@szEUserCode
		END
	END
	ELSE
	BEGIN
		SET @intByETypeID=0
	END

	IF UPPER(@Code1)='#BM#' OR UPPER(@Code2)='#BM#' OR UPPER(@Code3)='#BM#' OR UPPER(@Code4)='#BM#' OR UPPER(@Code5)='#BM#' OR UPPER(@Code6)='#BM#' OR UPPER(@Code7)='#BM#' OR UPPER(@Code8)='#BM#' OR UPPER(@Code9)='#BM#' OR UPPER(@Code10)='#BM#' OR UPPER(@Code11)='#BM#' OR UPPER(@Code12)='#BM#'
	BEGIN
		SET @intByDTypeID=1

		IF @szDUserCode=''
		BEGIN
		    --print ' @szDUserCode=null '
			SELECT @DTypeId=''
			SET @UpdateSeed = 0
		END
		ELSE
		BEGIN
			SELECT @DTypeId=TypeID
			FROM dbo.Department
			WHERE UserCode=@szDUserCode
		END
	END
	ELSE 
		SET @intByDTypeID=0
		
	IF UPPER(@Code1)='#ZDR#' OR UPPER(@Code2)='#ZDR#' OR UPPER(@Code3)='#ZDR#' OR UPPER(@Code4)='#ZDR#' OR UPPER(@Code5)='#ZDR#' OR UPPER(@Code6)='#ZDR#' OR UPPER(@Code7)='#ZDR#' OR UPPER(@Code8)='#ZDR#' OR UPPER(@Code9)='#ZDR#' OR UPPER(@Code10)='#ZDR#' OR UPPER(@Code11)='#ZDR#' OR UPPER(@Code12)='#ZDR#'
	BEGIN
		SET @intByCETypeID=1

		IF @szCEUserCode=''
		BEGIN
			SELECT @CETypeId=''
			SET @UpdateSeed = 0
		END
		ELSE
		BEGIN
			SELECT @CETypeId=TypeID
			FROM dbo.employee
			WHERE UserCode=@szCEUserCode
		END
	END
	ELSE 
		SET @intByCETypeID=0		
	
	--提成规则单不要分支机构
	IF (@Stypeid=''OR @Stypeid=NULL) AND @BType<>164
	BEGIN
	    ----print ' 提成规则单不要分支机构 '
		SET @UpdateSeed = 0
	END
	--参照计划提成不要分支机构
	IF (@Stypeid=''OR @Stypeid=NULL) AND @BType<>309
	BEGIN
	    ----print ' 参照计划提成不要分支机构 '
		SET @UpdateSeed = 0
	END	
  --固定资产变更单
	IF (@Stypeid=''OR @Stypeid=NULL) AND @BType<>410
	BEGIN
	    ----print ' 固定资产变更单 '
		SET @UpdateSeed = 0
    END
	--生成单据编号的要素不够，返回空单据编号
	IF @UpdateSeed=0
	BEGIN
		SELECT @BCode=''
		RETURN 
	END
	
	SELECT 
		@KTypeID=ISNULL(@KTypeID,''),
		@ETypeID=ISNULL(@ETypeID,''),
		@DTypeId=ISNULL(@DTypeId,''),
		@CETypeId=ISNULL(@CETypeId,'')

	--若有仓库，替换为仓库编号
	SET @Code = REPLACE(@Code,'#KK#',@szKUserCode)
	
	--若有经手人，替换为经手人编号
	SET @Code = REPLACE(@Code,'#EE#',@szEusercode)
	
	--若有部门，替换
	SET @Code=REPLACE(@Code,'#BM#',@szDUsercode)
	
	--若有制单人，替换
	SET @Code=REPLACE(@Code,'#ZDR#',@szCEUsercode)
	
	SET @Code = REPLACE(@Code,'%','')
	SET @Code = RTRIM(@Code)
	
	--没有编号设置返回空字符串
	IF @Code = '' 
	BEGIN
		SET @BCode = ''
		RETURN
	END
	
	--长度超过96位截断成96位
	IF LEN(@Code)>96 
	BEGIN
		SELECT @Code=SUBSTRING(@Code,1,96)
	END
		
	DECLARE @MaxNumber varchar(20)
	

	DECLARE
		@strSql		NVARCHAR(4000)

	SELECT @strSql='
	SELECT @MaxNumber=MAX(Seed) 
	FROM BillCode_Seed
	WHERE BillType='+CAST(@BType AS VARCHAR(100))
	
	IF @intByKTypeID=1
	BEGIN
		SELECT @strSql=@strSql+'	AND KTypeID='+CHAR(39)+@KTypeID+CHAR(39)+CHAR(13)
	END
	ELSE
	BEGIN
		SELECT @strSql=@strSql+'	AND KTypeID='''''
	END

	IF @intByETypeID=1
	BEGIN
		SELECT @strSql=@strSql+'	AND ETypeID='+CHAR(39)+@ETypeID+CHAR(39)+CHAR(13)
	END
	ELSE
	BEGIN
		SELECT @strSql=@strSql+'	AND ETypeID='''''
	END
	
	IF @intByDTypeID=1
	BEGIN
		SELECT @strSql=@strSql+'	AND DTypeID='+CHAR(39)+@DTypeID+CHAR(39)+CHAR(13)
	END
	ELSE
	BEGIN
		SELECT @strSql=@strSql+'	AND DTypeID='''''
	END
	
	IF @intByCETypeID=1
	BEGIN
		SELECT @strSql=@strSql+'	AND CETypeID='+CHAR(39)+@CETypeID+CHAR(39)+CHAR(13)
	END
	ELSE
	BEGIN
		SELECT @strSql=@strSql+'	AND CETypeID='''''
	END

	SELECT @strSql=@strSql+'	AND STypeID='+CHAR(39)+@STYpeID+CHAR(39)+CHAR(13)
	
	SELECT @strSql=@strSql+'	AND FlowDate = '+CHAR(39)+@FlowDate+CHAR(39)+CHAR(13)
	
	EXECUTE sp_executesql @strSql,N'@MaxNumber NUMERIC(18,0) OUTPUT',@MaxNumber OUTPUT
	
	SELECT @MaxNumber=CAST( CAST(ISNULL(@MaxNumber,'0') AS NUMERIC(18,0))+1 AS VARCHAR(20))
	
	--流水号单据编号生成后生效
	IF @BillcodeCreateTime='1' AND @UpdateSeed = 1
	BEGIN
		SET @strSql=''
		IF @MaxNumber='1'
		BEGIN
			SELECT @strSql='
			INSERT BillCode_Seed (BillType,Ktypeid,Etypeid,DTypeID,CETypeID,Stypeid,FlowDate,Seed)
			VALUES(' +CAST(@BType AS VARCHAR(100))
			IF @intByKTypeID=1
			BEGIN
				SELECT @strSql=@strSql+','+CHAR(39)+@KTypeID+CHAR(39)+CHAR(13)
			END
			ELSE
			BEGIN
				SELECT @strSql=@strSql+','''''
			END
			IF @intByETypeID=1
			BEGIN
				SELECT @strSql=@strSql+','+CHAR(39)+@ETypeID+CHAR(39)+CHAR(13)
			END
			ELSE
			BEGIN
				SELECT @strSql=@strSql+','''''
			END
			
			IF @intByDTypeID=1
			BEGIN
				SELECT @strSql=@strSql+','+CHAR(39)+@DTypeID+CHAR(39)+CHAR(13)
			END
			ELSE
			BEGIN
				SELECT @strSql=@strSql+','''''
			END
			
			IF @intByCETypeID=1
			BEGIN
				SELECT @strSql=@strSql+','+CHAR(39)+@CETypeID+CHAR(39)+CHAR(13)
			END
			ELSE
			BEGIN
				SELECT @strSql=@strSql+','''''
			END
			
			SELECT @strSql=@strSql+','+CHAR(39)+@STYpeID+CHAR(39)+CHAR(13)
			SELECT @strSql=@strSql+','+CHAR(39)+@FlowDate+CHAR(39)+CHAR(13)
			SELECT @strSql=@strSql+','+@MaxNumber+')'
		END
		IF @MaxNumber<>'1' AND @BillcodeCreateTime='1'
		BEGIN
			SELECT @strSql='
			UPDATE BillCode_Seed SET Seed='+@MaxNumber+'
			WHERE BillType='+CAST(@BType AS VARCHAR(100))
			

			IF @intByKTypeID=1
			BEGIN
				SELECT @strSql=@strSql+'	AND KTypeID='+CHAR(39)+@KTypeID+CHAR(39)+CHAR(13)
			END
			ELSE
			BEGIN
				SELECT @strSql=@strSql+'	AND KTypeID='''''
			END

			IF @intByETypeID=1
			BEGIN
				SELECT @strSql=@strSql+'	AND ETypeID='+CHAR(39)+@ETypeID+CHAR(39)+CHAR(13)
			END
			ELSE
			BEGIN
				SELECT @strSql=@strSql+'	AND ETypeID='''''
			END
			
			IF @intByDTypeID=1
			BEGIN
				SELECT @strSql=@strSql+'	AND DTypeID='+CHAR(39)+@DTypeID+CHAR(39)+CHAR(13)
			END
			ELSE
			BEGIN
				SELECT @strSql=@strSql+'	AND DTypeID='''''
			END
			
			IF @intByCETypeID=1
			BEGIN
				SELECT @strSql=@strSql+'	AND CETypeID='+CHAR(39)+@CETypeID+CHAR(39)+CHAR(13)
			END
			ELSE
			BEGIN
				SELECT @strSql=@strSql+'	AND CETypeID='''''
			END
					
			SELECT @strSql=@strSql+'	AND STypeID='+CHAR(39)+@STYpeID+CHAR(39)+CHAR(13)
		
			SELECT @strSql=@strSql+'	AND FlowDate='+CHAR(39)+@FlowDate+CHAR(39)+CHAR(13)
			
		END
		EXEC(@strSql)
	END
	
	--A8
	--IF @ProInfo='2' OR (@ProInfo='3' AND @QpEdit IN('2','4','5'))
	
	IF @ProInfo='2'
		SELECT @BCode =@BillFlag+'-'+@szSUsercode+'-'+@Code+'-'+DBO.FN_FixStr(@FlowLen,CAST(@MaxNumber AS VARCHAR(100)),'0')
	ELSE
		SELECT @BCode =@BillFlag+'-'+@Code+'-'+DBO.FN_FixStr(@FlowLen,CAST(@MaxNumber AS VARCHAR(100)),'0')
END
ELSE
BEGIN
     -- chen_qihua 单据编号自定义改为 200 长度 -- #&**&#	
	 -- DECLARE @BCFirstChar VARCHAR(50),@bMon bit,@bDay bit,@billcode VARCHAR(25),@temp VARCHAR(4),@t INT,@AutoBillCode VARCHAR(50)
	 DECLARE @BCFirstChar VARCHAR(50),@bMon bit,@bDay bit,@billcode VARCHAR(200),@temp VARCHAR(4),@t INT,@AutoBillCode VARCHAR(200)

	 DECLARE @tYear VarChar(4), @tMonth VARCHAR(2),@tday VARCHAR(2)
	 Set @tYear = Year(@BillDate)
	 IF len(@tYear) <> 4 
		Set @tYear = '20' + @tYear

	 SELECT @MONTH=MONTH(@BillDate),@DAY=DAY(@BillDate)
	
	 SELECT @tmonth=RIGHT(CAST(@MONTH+100 AS VARCHAR(10)),2)
	 SELECT @tday=RIGHT(CAST(@DAY+100 AS VARCHAR(10)),2)



	
	 SELECT @BCode=''
	 SELECT @AutoBillCode=Value FROM Userconfig WHERE ConfigName='IfBillCode'
	 IF @AutoBillCode='0' RETURN
	
	 SELECT @BCFirstChar=Value FROM Userconfig WHERE ConfigName='Billcodeindex'
	 


	--判断编号的日期规则
	--判断是否按仓库或经手人来计数
	SELECT @billcode=CAST(ISNULL(MAX(Seed),0)+1 AS VARCHAR(100))
	FROM BillCode_Seed
	WHERE BillType=@BType AND FlowDate=@FlowDate AND ETypeID='' AND KTypeID='' AND STypeID=@STYpeID
  --  IF(@BType=311)
  --  BEGIN
  --   SELECT @billcode=CAST(MAX(Seed)+1 AS VARCHAR(100))
	 --FROM BillCode_Seed
	 --WHERE BillType=@BType
  --  END


	--对长度进行限定
	
	IF @billcode IS NULL
	Begin
	   Select @billcode='1'
	End
	--流水号单据编号生成后生效(提车规则单不要分支机构)

	IF (@BillcodeCreateTime='1' AND @STYpeID<>'') OR  (@BillcodeCreateTime='1' AND @BType=164) OR  (@BillcodeCreateTime='1' AND @BType=309) OR  (@BillcodeCreateTime='1' AND @BType=410)
	BEGIN
		IF @billcode='1'
		BEGIN
			SELECT @strSql='
			INSERT BillCode_Seed (BillType,Ktypeid,Etypeid,Dtypeid,CETypeid,Stypeid,FlowDate,Seed)
			VALUES(' +CAST(@BType AS VARCHAR(100))+','''','''','''','''','+CHAR(39)+@STYpeID+CHAR(39)+','+CHAR(39)+@FlowDate+CHAR(39)+',1)'
		END
		ELSE
		BEGIN
			SELECT @strSql='
			UPDATE BillCode_Seed SET Seed='+@billcode+'
			WHERE BillType='+CAST(@BType AS VARCHAR(100))
			
			SELECT @strSql=@strSql+'	AND KTypeID='''' AND ETypeID='''' AND DTypeID='''' AND CETypeID=''''  AND STypeID='+CHAR(39)+@STYpeID+CHAR(39)+CHAR(13)
		
			SELECT @strSql=@strSql+'	AND FlowDate='+CHAR(39)+@FlowDate+CHAR(39)+CHAR(13)
			
		END
		EXEC(@strSql)
	END
	
	SELECT @billcode=@tYear + @yearSeparator + @tmonth + @monthSeparator + @tday + @daySeparator + '-' + DBO.FN_FixStr(@FlowLen,@billcode,'0')

	--A8或者提成规则单,汽配3S有分支机构
	--IF (@ProInfo='2' AND @BType<>164) OR (@ProInfo='3' AND @QpEdit IN('2','4','5') AND @BType<>164)
	IF (@ProInfo='2' AND @BType<>164 AND @BType<>309 AND @BType<>410)
	BEGIN
		IF @szSUserCode='' OR @szSUserCode=null
		BEGIN
			SELECT @BCode=''
			RETURN
		END
		ELSE
		BEGIN
			IF ISNULL(@BCFirstChar,'')=''
				SELECT @BCode=@BillFlag+'-'+@szSUserCode+'-'+@billcode
			ELSE
				SELECT @BCode=@BillFlag+'-'+@szSUserCode+'-'+ISNULL(@BCFirstChar,'')+'-'+@billcode
		END
	END
	ELSE
	
	BEGIN

		IF ISNULL(@BCFirstChar,'')=''
			SELECT @BCode=@BillFlag+'-'+@billcode
		ELSE
			SELECT @BCode=@BillFlag+'-'+ISNULL(@BCFirstChar,'')+'-'+@billcode

	END
END


SELECT @BCode=SUBSTRING(@BCode,1,200)

--print @BCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	Author:		冯波
	Create date: 2012-12-01
	Description: 
*/							
CREATE   PROCEDURE GP_GetBillIndexInfo
(
	@nBillID				NUMERIC(10,0),
	@numBillType			INT,						-- 单据类型
	@datBillDate			DATETIME	OUT,					-- 单据日期
	@chvATypeID				VARCHAR(50)	OUT,				-- 收付款账户 ID 值
	@chvBTypeID				VARCHAR(50)	OUT,				--结算单位
	@chvDealBTypeID			VARCHAR(50)	OUT,				--往来单位
	@chvETypeID				VARCHAR(50)	OUT,				-- 经手人 ID 值
	@chvKTypeID				VARCHAR(50)	OUT,				-- 出库仓库 ID 值
	@chvKTypeID2			VARCHAR(50)	OUT,				-- 入库仓库 ID 值
	@chvDTypeID				VARCHAR(50)	OUT,				--部门
	@chvSTypeID				VARCHAR(50)	OUT,				--分支机构
	@numTotalMoney			 NUMERIC(24, 10) 	OUT,				-- 单据金额合计
	@numTotalInMoney		 NUMERIC(24, 10) 	OUT,				-- 单据实收、实付金额
	@numPreferenceMoney		 NUMERIC(24, 10) 	OUT,
	@numNTotalMoney			 NUMERIC(24, 10) 	OUT,
	@numNTotalInMoney		 NUMERIC(24, 10) 	OUT,
	@numNPreferenceMoney	 NUMERIC(24, 10) 	OUT,
	@wxTotal				 NUMERIC(24, 10) 	OUT,	
	@numTax					 NUMERIC(24, 10) 	OUT,
	@ifIndexWX				TINYINT	OUT,
	@intCostSale			TINYINT	OUT,
	@intCID					INT	OUT,
	@ifCheck				VARCHAR(10)	OUT,				-- 是否草稿标识，f - 草稿；t - 已过账
	@IfMulAccount			TINYINT	OUT,
	@intVipCardID			INT	OUT,
	@NumRate				 NUMERIC(24, 10)  OUT,
	@AssetBusinessTypeId	INT OUT,
	@intRedWord				TINYINT	OUT,
	@intNewPosBill			TINYINT OUT,
	@IfLend					INT OUT,
	@datPostTime			DATETIME OUT
)
--@encode$--
AS


SELECT @intCID=0

IF @numBillType=203
BEGIN
	SELECT	
				@ifCheck = IfCheck,
				@chvBTypeID = BTypeID,
				@chvDealBTypeID=BTypeID,
				@chvSTypeID = STypeID,
				@chvDTypeID = DTypeID,
				@intRedWord=RedWord
	FROM	SerialAdjustIndex
	WHERE	BillNumberID = @nBillID
END
ELSE IF @numBillType IN (404,405)
BEGIN
	SELECT	
				@numBillType = BillType,		
				@datBillDate = BillDate,				
				@chvBTypeID = BTypeID,				
				@chvDealBTypeID=DealBTypeID,	
				@chvETypeID = ETypeID,							
				@chvDTypeID	=DTypeID,				
				@chvSTypeID=STypeID,				
				@numTotalMoney = TotalMoney,		
				@numNTotalMoney = NTotalMoney,
				@numTax = Tax,
				@intCID = CID,
				@NumRate = Rate,
				@ifCheck = IfCheck,			
				@intRedWord=RedWord,
				@datPostTime=Posttime
	FROM	ReceiptBillIndex
	WHERE	BillNumberID = @nBillID
END
ELSE IF @numBillType IN (327,328,329)
BEGIN
	SELECT	
				@numBillType = BillType,		
				@datBillDate = BillDate,			
				@chvKTypeID = KTypeID,		
				@chvETypeID = applyEtypeID,
				@chvKTypeID2 = InKTypeID,			
				@chvDTypeID	=DTypeID,				
				@chvSTypeID=STypeID,				
				@ifCheck = IfCheck,			
				@intRedWord=RedWord
	FROM	PosAllotApplyBillIndex
	WHERE	BillNumberID = @nBillID
END
ELSE
BEGIN
	SELECT	
				@numBillType = BillType,		
				@datBillDate = BillDate,		
				@chvATypeID = ATypeID,			
				@chvBTypeID = BTypeID,				
				@chvDealBTypeID=DealBTypeID,	
				@chvETypeID = ETypeID,				
				@chvKTypeID = KTypeID,			
				@chvKTypeID2 = KTypeID2,			
				@chvDTypeID	=DTypeID,				
				@chvSTypeID=STypeID,				
				@numTotalMoney = TotalMoney,		
				@numTotalInMoney = TotalInMoney,
				@numPreferenceMoney = PreferenceMoney,
				@numNTotalMoney = NTotalMoney,
				@numNTotalInMoney = NTotalInMoney,
				@numNPreferenceMoney = nPreferenceMoney,
				@wxTotal=wxTotal,
				@numTax = Tax,
				@ifIndexWX = ifWX,
				@intCostSale=CostSale,
				@intCID = CID,
				@NumRate = Rate,
				@ifCheck = IfCheck,			
				@IfMulAccount=IfMulAccount,
				@intVipCardID = VipCardID,
				@AssetBusinessTypeId=AssetBusinessTypeId,
				@intRedWord=RedWord,
				@intNewPosBill=NewPosBill,
				@IfLend = IsLend,
				@datPostTime=posttime
	FROM	BillIndex
	WHERE	BillNumberID = @nBillID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetBillItemsMinAutoId]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Gp_GetBillItemsMinAutoId
GO
/*
	作者：周华
	时间：2012-06-28
	描述：用于返回对应单据明细的最小明细id
	2013.06.08 周华 添加固定资产几张单据
	乱乱乱
	2017.07.05 刘飞 增加组合品上下表体分离
*/
CREATE PROCEDURE Gp_GetBillItemsMinAutoId
	 @BillNumberId BIGINT
	,@BillType  INT
	,@IOMode   VARCHAR(10)=''
	,@DetailID INT=-1 OUT 
	,@ShowOrder INT=1 OUT
--@encode$--
AS
BEGIN
	DECLARE @tb VARCHAR(100)='',
		    @sql NVARCHAR(MAX)='',
		    @conField NVARCHAR(100)='',
		    @con NVARCHAR(1000)='',
		    @ret BIGINT=-1,
		    @OrderBy VARCHAR(MAX)=''
	SET @tb = CASE
		WHEN @billType IN (300,301) THEN 'OrderBill' --采购，销售订单
		WHEN @billType = 313 and @IOMode = 'I' THEN 'PT_Combin_OrderBill' --组合品销售订单上表体
		WHEN @billType = 313 and @IOMode = 'O' THEN 'PT_Combin_OrderBillDetail' --组合品销售订单下表体
		WHEN @BillType = 305 and @IOMode = 'I' THEN 'RetailCombinationBill'		-- 零售单上表体
		WHEN @BillType = 305 and @IOMode = 'O' THEN 'RetailBill'				-- 零售单下表体
		WHEN @BillType = 11		THEN 'SaleBill'				-- 销售出库单
		WHEN @BillType = 12 and @IOMode = 'I' THEN 'PT_Combin_SaleBill'	-- 组合品销售出库单上表体
		WHEN @BillType = 12 and @IOMode = 'O' THEN 'PT_Combin_SaleBillDetail'	-- 组合品销售出库单下表体
		WHEN @BillType = 45		THEN 'SaleBackBill'			-- 销售退货单
		WHEN @BillType = 46 and @IOMode = 'I' THEN 'PT_Combin_SaleBackBill'	-- 组合品销售退货单上表体
		WHEN @BillType = 46 and @IOMode = 'O' THEN 'PT_Combin_SaleBackBillDetail'	-- 组合品销售退货单下表体
		WHEN @BillType = 34		THEN 'BuyBill'				-- 采购入库单
		WHEN @BillType = 6		THEN 'BuyBackBill'			-- 采购退货单
		WHEN @BillType IN (140,141,142,143,144,145,146,147)
								THEN 'CommissionBill'		-- 委托/受托代销单据(7种)
		WHEN @BillType = 4		THEN 'GatheringBill'		-- 收款单
		WHEN @BillType = 66		THEN 'PayBill'				-- 付款单
		WHEN @BillType = 17		THEN 'MoveBill'				-- 同价调拨单
		WHEN @BillType = 21		THEN 'MoveBjBill'			-- 变价调拨单
		WHEN @BillType = 9		THEN 'LoseBill'				-- 报损单
		WHEN @BillType = 14		THEN 'OverFlowBill'			-- 报溢单
		WHEN @BillType = 57		THEN 'AdPriceBill'			-- 成本调价单
		WHEN @BillType = 16		THEN 'DisassembleBill'		-- 生产拆装单
		WHEN @BillType = 155	THEN 'GoodsExchangeBill'	-- 换货单
		WHEN @BillType = 157	THEN 'RepairDeal'			-- 维修受理单
		WHEN @BillType IN (115,116,128,129)
								THEN 'AdDebtBill'			-- 往来调账单(4种)
		WHEN @BillType IN (5,10,36,78,84,85,93,158)
								THEN 'MoneyBill'			-- 待摊费用类单据(2种)
															-- 费用单
															-- 固定资产类单据(3种)
															-- 其他收入单
															-- 现金费用单
		WHEN @BillType = 77		THEN 'MoveMoneyBill'		-- 转款单
		WHEN @BillType = 139	THEN 'GiveBill'				-- 赠送单
		WHEN @BillType = 126	THEN 'GiveMeBill'			-- 获赠单
		WHEN @BillType IN (148,150)
								THEN 'Advantage'			-- 返利/获利核算执行单据
		WHEN @BillType IN (149,151)
								THEN 'PriceProtectBill'		-- 价保执行单/获得价保
		WHEN @BillType = 159	THEN 'AccountCredence'		-- 会计凭证
		WHEN @BillType = 160	THEN 'SaleGoodsExchangeBill'-- 销售换货单
		WHEN @BillType = 161	THEN 'BuyGoodsExchangeBill'	-- 采购换货单
		WHEN @BillType = 165	THEN 'wx_Bill_JieJian'		-- 新维修 - 接件单
		WHEN @BillType = 166	THEN 'wx_Bill_Self'			-- 新维修 - 自行维修单
		WHEN @BillType = 167	THEN 'wx_Bill_GetBack'		-- 新维修 - 维修取件单
		WHEN @BillType = 168	THEN 'wx_Bill_Replace'		-- 新维修 - 整机更换单
		WHEN @BillType = 169	THEN 'wx_Bill_Send'			-- 新维修 - 送修单
		WHEN @BillType = 170	THEN 'wx_Bill_SendBack'		-- 新维修 - 送修返回单
		WHEN @BillType = 171	THEN 'wx_Bill_Call'			-- 新维修 - 报修单
		WHEN @BillType = 172	THEN 'wx_Bill_Goto'			-- 新维修 - 上门维修单
		WHEN @BillType = 173	THEN 'wx_Bill_In'			-- 新维修 - 维修品调入单
		WHEN @BillType = 174	THEN 'wx_Bill_Out'			-- 新维修 - 维修品调出单
		WHEN @BillType = 175	THEN 'wx_Bill_Move'			-- 新维修 - 维修品调拨单
		WHEN @BillType = 180	THEN 'QP_RecycleBill'		-- 旧件回收单
		WHEN @BillType = 177    THEN 'QP_EvaluationBill_RepairItems'	--维修估价单
		WHEN @BillType = 178    THEN 'QP_QuickRepairBill_RepairItems'
		WHEN @BillType = 183    THEN 'IntegralExchangeBill'	--积分兑换单
		WHEN @BillType = 184    THEN 'QuotePriceBill'		--报价单
		WHEN @BillType = 185    THEN 'AskPriceBill'			--询价单
		WHEN @BillType = 186    THEN 'QP_InsuranceBill_RepairItems' --保险理赔单_维修项目明细表
		WHEN @BillType = 187    THEN 'STypeMoveBill'		--分支机构调拨出库单
		WHEN @BillType = 188    THEN 'STypeMoveBill'		--分支机构调拨入库单
		WHEN @BillType = 189	THEN 'PreBill'				--预收款单
		WHEN @BillType = 190	THEN 'PreBill'				--预付款单
		WHEN @BillType = 191	THEN 'Qp_PickingBill'		--领料出库单
		WHEN @BillType = 192	THEN 'Qp_BackingOut_Bill'	--返修单
		WHEN @BillType = 195	THEN 'Qp_ReceptionBill_RepairItems'	--接待登记单,维修结算单
		WHEN @BillType = 196	THEN 'Qp_SuccorBill_RepairItems'	--救援单
		WHEN @BillType = 197    THEN 'Qp_PickingBackBill'	--领料退回单
		WHEN @BillType = 200    THEN 'Qp_ThreePacketsBill_RepairItems' --三包索赔单
		WHEN @BillType = 198    THEN 'Qp_IntendingTalkBack_Bill' --回访单
		WHEN @BillType = 179    THEN 'QP_WashCarBill' --洗车结算
		WHEN @BillType = 201    THEN 'OtherInOutBill' --其他入库单
		WHEN @BillType = 202    THEN 'OtherInOutBill' --其他出库单
		WHEN @BillType=203	THEN 'SerialAdjustBill' --序列号调整单
		WHEN @BillType = 205 and @IOMode = 'I' THEN 'ShareFeeBill' --采购费用分摊
		WHEN @BillType = 205 and @IOMode = 'O' THEN 'ShareSourceBill' --采购费用分摊
		WHEN @BillType = 206 and @IOMode = 'I' THEN 'ShareFeeBill' --销售费用分摊
		WHEN @BillType = 206 and @IOMode = 'O' THEN 'ShareSourceBill' --销售费用分摊
		WHEN @BillType = 415 and @IOMode = 'I' THEN 'ShareFeeBill' --运输费用分摊
		WHEN @BillType = 415 and @IOMode = 'O' THEN 'ShareSourceBill' --运输费用分摊
		WHEN @BillType IN (87,71,88,72) THEN 'LendBill'
		WHEN @BillType = 306 THEN 'StockCheck' --库存盘点单
		WHEN @BillType IN (162,163) THEN 'FaPiaoBill' --采购，销售发票
		WHEN @BillType = 204 THEN 'RequestBill' --请购单
		WHEN @BillType IN (212,213) THEN 'AssetIncDecBill'--固定资产增加减少
		WHEN @BillType=214 THEN 'DepBill' --固定资产折旧单
		WHEN @BillType IN(404,405) THEN 'ReceiptBill'
		WHEN @BillType=450 THEN 'ChargeOffBill' --往来核销单
		WHEN @BillType=326 THEN 'DeliveryApplyBill' --要货申请单
		ELSE (SELECT MAX(detailTable) FROM billname WHERE Billtype=@billType) --没有写到的单据
	END
	IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(@tb,N'U') AND Name='ShowOrder')
	BEGIN
		SET @ShowOrder=-1
	END

	IF @ShowOrder<>-1
	BEGIN
		SET @con=' AND ShowOrder=@ShowOrder  '
		SET @OrderBy='  Order By ShowOrder ASc  '
	END
	ELSE 
	BEGIN
		SET @OrderBy ='  Order By ID ASC  '
	END
	 
	IF @BillType IN (300,301,313)  --订单查orderid
		SET @sql='SELECT TOP 1 @r=orderID FROM '+@tb+' WHERE BillNumberId=@b '+@con+@OrderBy;
	ELSE IF @BillType IN (12,46,305,414)  --组合品销售出库单\组合品销售退货单\零售单查id
		SET @sql='SELECT TOP 1 @r=ID FROM '+@tb+' WHERE BillNumberId=@b '+@con+@OrderBy;
	ELSE IF @BillType = 306
		SET @sql='SELECT TOP 1 @r=id FROM '+@tb+' WHERE StockCheckID=@b '+@con+@OrderBy;
	ELSE
	 BEGIN 
		SET @conField=@conField+ ' AND InOrOut' 
		IF LTRIM(RTRIM(@IOMode))<>'' and @BillType not in (205,206,415)
		SET @con=@con+@conField+'='''+@IOMode + '''';
		SET @sql='SELECT TOP 1 @r=ID FROM '+@tb+' WHERE BillNumberId=@b '+@con+@OrderBy;
	 END	

    --print @sql
	EXEC SP_EXECUTESQL @sql,N'@r bigint OUTPUT,@b BIGINT,@ShowOrder INT ',@ret OUTPUT,@BillNumberId,@ShowOrder;
	SET @DetailID=@ret
	--print @DetailID
END
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetBillItemsMinAutoIdAutoDraft]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Gp_GetBillItemsMinAutoIdAutoDraft
GO
/*
	作者：周华
	时间：2012-06-28
	描述：用于返回对应单据明细的最小明细id
	2013.06.08 周华 添加固定资产几张单据
	乱乱乱
	2017.07.05 刘飞 增加组合品上下表体分离
*/
CREATE PROCEDURE Gp_GetBillItemsMinAutoIdAutoDraft
	 @BillGuid		VARCHAR(100)
	,@BillType		INT
	,@IOMode		VARCHAR(10)=''
	,@DetailID		INT=-1 OUT 
	,@ShowOrder		INT=1 OUT
--@encode$--
AS
BEGIN
	DECLARE @tb			VARCHAR(100)='',
		    @sql		NVARCHAR(MAX)='',
		    @conField	NVARCHAR(100)='',
		    @con		NVARCHAR(1000)='',
		    @ret		BIGINT=-1,
		    @OrderBy	VARCHAR(MAX)=''
	SET @tb = CASE
		WHEN @billType IN (300,301) THEN 'OrderBill' --采购，销售订单
		WHEN @billType = 313 and @IOMode = 'I' THEN 'PT_Combin_OrderBill' --组合品销售订单上表体
		WHEN @billType = 313 and @IOMode = 'O' THEN 'PT_Combin_OrderBillDetail' --组合品销售订单下表体
		WHEN @BillType = 305 and @IOMode = 'I' THEN 'RetailCombinationBill'		-- 零售单上表体
		WHEN @BillType = 305 and @IOMode = 'O' THEN 'RetailBill'				-- 零售单下表体
		WHEN @BillType = 11		THEN 'SaleBillAutoDraft'				-- 销售出库单 - 自动保存单据
		WHEN @BillType = 12 and @IOMode = 'I' THEN 'PT_Combin_SaleBill'	-- 组合品销售出库单上表体
		WHEN @BillType = 12 and @IOMode = 'O' THEN 'PT_Combin_SaleBillDetail'	-- 组合品销售出库单下表体
		WHEN @BillType = 45		THEN 'SaleBackBill'			-- 销售退货单
		WHEN @BillType = 46 and @IOMode = 'I' THEN 'PT_Combin_SaleBackBill'	-- 组合品销售退货单上表体
		WHEN @BillType = 46 and @IOMode = 'O' THEN 'PT_Combin_SaleBackBillDetail'	-- 组合品销售退货单下表体
		WHEN @BillType = 34		THEN 'BuyBillAutoDraft'		-- 采购入库单 - 自动保存单据
		WHEN @BillType = 6		THEN 'BuyBackBill'			-- 采购退货单
		WHEN @BillType IN (140,141,142,143,144,145,146,147)
								THEN 'CommissionBill'		-- 委托/受托代销单据(7种)
		WHEN @BillType = 4		THEN 'GatheringBill'		-- 收款单
		WHEN @BillType = 66		THEN 'PayBill'				-- 付款单
		WHEN @BillType = 17		THEN 'MoveBill'				-- 同价调拨单
		WHEN @BillType = 21		THEN 'MoveBjBill'			-- 变价调拨单
		WHEN @BillType = 9		THEN 'LoseBill'				-- 报损单
		WHEN @BillType = 14		THEN 'OverFlowBill'			-- 报溢单
		WHEN @BillType = 57		THEN 'AdPriceBill'			-- 成本调价单
		WHEN @BillType = 16		THEN 'DisassembleBill'		-- 生产拆装单
		WHEN @BillType = 155	THEN 'GoodsExchangeBill'	-- 换货单
		WHEN @BillType = 157	THEN 'RepairDeal'			-- 维修受理单
		WHEN @BillType IN (115,116,128,129)
								THEN 'AdDebtBill'			-- 往来调账单(4种)
		WHEN @BillType IN (5,10,36,78,84,85,93,158)
								THEN 'MoneyBill'			-- 待摊费用类单据(2种)
															-- 费用单
															-- 固定资产类单据(3种)
															-- 其他收入单
															-- 现金费用单
		WHEN @BillType = 77		THEN 'MoveMoneyBill'		-- 转款单
		WHEN @BillType = 139	THEN 'GiveBill'				-- 赠送单
		WHEN @BillType = 126	THEN 'GiveMeBill'			-- 获赠单
		WHEN @BillType IN (148,150)
								THEN 'Advantage'			-- 返利/获利核算执行单据
		WHEN @BillType IN (149,151)
								THEN 'PriceProtectBill'		-- 价保执行单/获得价保
		WHEN @BillType = 159	THEN 'AccountCredence'		-- 会计凭证
		WHEN @BillType = 160	THEN 'SaleGoodsExchangeBill'-- 销售换货单
		WHEN @BillType = 161	THEN 'BuyGoodsExchangeBill'	-- 采购换货单
		WHEN @BillType = 165	THEN 'wx_Bill_JieJian'		-- 新维修 - 接件单
		WHEN @BillType = 166	THEN 'wx_Bill_Self'			-- 新维修 - 自行维修单
		WHEN @BillType = 167	THEN 'wx_Bill_GetBack'		-- 新维修 - 维修取件单
		WHEN @BillType = 168	THEN 'wx_Bill_Replace'		-- 新维修 - 整机更换单
		WHEN @BillType = 169	THEN 'wx_Bill_Send'			-- 新维修 - 送修单
		WHEN @BillType = 170	THEN 'wx_Bill_SendBack'		-- 新维修 - 送修返回单
		WHEN @BillType = 171	THEN 'wx_Bill_Call'			-- 新维修 - 报修单
		WHEN @BillType = 172	THEN 'wx_Bill_Goto'			-- 新维修 - 上门维修单
		WHEN @BillType = 173	THEN 'wx_Bill_In'			-- 新维修 - 维修品调入单
		WHEN @BillType = 174	THEN 'wx_Bill_Out'			-- 新维修 - 维修品调出单
		WHEN @BillType = 175	THEN 'wx_Bill_Move'			-- 新维修 - 维修品调拨单
		WHEN @BillType = 180	THEN 'QP_RecycleBill'		-- 旧件回收单
		WHEN @BillType = 177    THEN 'QP_EvaluationBill_RepairItems'	--维修估价单
		WHEN @BillType = 178    THEN 'QP_QuickRepairBill_RepairItems'
		WHEN @BillType = 183    THEN 'IntegralExchangeBill'	--积分兑换单
		WHEN @BillType = 184    THEN 'QuotePriceBill'		--报价单
		WHEN @BillType = 185    THEN 'AskPriceBill'			--询价单
		WHEN @BillType = 186    THEN 'QP_InsuranceBill_RepairItems' --保险理赔单_维修项目明细表
		WHEN @BillType = 187    THEN 'STypeMoveBill'		--分支机构调拨出库单
		WHEN @BillType = 188    THEN 'STypeMoveBill'		--分支机构调拨入库单
		WHEN @BillType = 189	THEN 'PreBill'				--预收款单
		WHEN @BillType = 190	THEN 'PreBill'				--预付款单
		WHEN @BillType = 191	THEN 'Qp_PickingBill'		--领料出库单
		WHEN @BillType = 192	THEN 'Qp_BackingOut_Bill'	--返修单
		WHEN @BillType = 195	THEN 'Qp_ReceptionBill_RepairItems'	--接待登记单,维修结算单
		WHEN @BillType = 196	THEN 'Qp_SuccorBill_RepairItems'	--救援单
		WHEN @BillType = 197    THEN 'Qp_PickingBackBill'	--领料退回单
		WHEN @BillType = 200    THEN 'Qp_ThreePacketsBill_RepairItems' --三包索赔单
		WHEN @BillType = 198    THEN 'Qp_IntendingTalkBack_Bill' --回访单
		WHEN @BillType = 179    THEN 'QP_WashCarBill' --洗车结算
		WHEN @BillType = 201    THEN 'OtherInOutBill' --其他入库单
		WHEN @BillType = 202    THEN 'OtherInOutBill' --其他出库单
		WHEN @BillType=203	THEN 'SerialAdjustBill' --序列号调整单
		WHEN @BillType = 205 and @IOMode = 'I' THEN 'ShareFeeBill' --采购费用分摊
		WHEN @BillType = 205 and @IOMode = 'O' THEN 'ShareSourceBill' --采购费用分摊
		WHEN @BillType = 206 and @IOMode = 'I' THEN 'ShareFeeBill' --销售费用分摊
		WHEN @BillType = 206 and @IOMode = 'O' THEN 'ShareSourceBill' --销售费用分摊
		WHEN @BillType = 415 and @IOMode = 'I' THEN 'ShareFeeBill' --运输费用分摊
		WHEN @BillType = 415 and @IOMode = 'O' THEN 'ShareSourceBill' --运输费用分摊
		WHEN @BillType IN (87,71,88,72) THEN 'LendBill'
		WHEN @BillType = 306 THEN 'StockCheck' --库存盘点单
		WHEN @BillType IN (162,163) THEN 'FaPiaoBill' --采购，销售发票
		WHEN @BillType = 204 THEN 'RequestBill' --请购单
		WHEN @BillType IN (212,213) THEN 'AssetIncDecBill'--固定资产增加减少
		WHEN @BillType=214 THEN 'DepBill' --固定资产折旧单
		WHEN @BillType IN(404,405) THEN 'ReceiptBill'
		WHEN @BillType=450 THEN 'ChargeOffBill' --往来核销单
		WHEN @BillType=326 THEN 'DeliveryApplyBill' --要货申请单
		ELSE (SELECT MAX(detailTable) FROM billname WHERE Billtype=@billType) --没有写到的单据
	END
	IF NOT EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(@tb,N'U') AND Name='ShowOrder')
	BEGIN
		SET @ShowOrder=-1
	END

	IF @ShowOrder<>-1
	BEGIN
		SET @con=' AND ShowOrder=@ShowOrder  '
		SET @OrderBy='  Order By ShowOrder ASc  '
	END
	ELSE 
	BEGIN
		SET @OrderBy ='  Order By ID ASC  '
	END
	 
	IF @BillType IN (300,301,313)  --订单查orderid
		SET @sql='SELECT TOP 1 @r=orderID FROM '+@tb+' WHERE BillGuid=@b '+@con+@OrderBy;
	ELSE IF @BillType IN (12,46,305,414)  --组合品销售出库单\组合品销售退货单\零售单查id
		SET @sql='SELECT TOP 1 @r=ID FROM '+@tb+' WHERE BillGuid=@b '+@con+@OrderBy;
	ELSE IF @BillType = 306
		SET @sql='SELECT TOP 1 @r=id FROM '+@tb+' WHERE StockCheckID=@b '+@con+@OrderBy;
	ELSE
	 BEGIN 
		SET @conField=@conField+ ' AND InOrOut' 
		IF LTRIM(RTRIM(@IOMode))<>'' and @BillType not in (205,206,415)
		SET @con=@con+@conField+'='''+@IOMode + '''';
		SET @sql='SELECT TOP 1 @r=ID FROM '+@tb+' WHERE BillGuid=@b '+@con+@OrderBy;
	 END	
	 
	PRINT(@ShowOrder) 

    --print @sql
	EXEC SP_EXECUTESQL @sql,N'@r bigint OUTPUT,@b varchar(100),@ShowOrder INT ',@ret OUTPUT,@BillGuid,@ShowOrder;
	SET @DetailID=@ret	
END
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

明细表


*/
CREATE   PROCEDURE Gp_GetBillName 
(
	@nBillType		INT,
	@chvBillName	VARCHAR(50)='' OUT
)
--@encode$--
AS

IF @nBillType=34
BEGIN
	--采购入库单
	SET @chvBillName='BuyBill'
END
ELSE IF @nBillType=11
BEGIN
	--销售出库单
	SET @chvBillName='SaleBill'
END
ELSE IF @nBillType=17
BEGIN
	--同价调拨单
	SET @chvBillName='MoveBill'
END
ELSE IF @nBillType=21
BEGIN
	--变价调拨单
	SET @chvBillName='MoveBjBill'
END
ELSE IF @nBillType=6
BEGIN
	--采购退货单
	SET @chvBillName='BuyBackBill'
END
ELSE IF @nBillType=45
BEGIN
	--销售退货单
	SET @chvBillName='SaleBackBill'
END
ELSE IF @nBillType=160
BEGIN
	--销售换货单
	SET @chvBillName='SaleGoodsExchangeBill'
END
ELSE IF @nBillType=161
BEGIN
	--采购换货单
	SET @chvBillName='BuyGoodsExchangeBill'
END
ELSE IF @nBillType=9
BEGIN
	--报损单
	SET @chvBillName='LoseBill'
END
ELSE IF @nBillType=14
BEGIN
	--报溢单
	SET @chvBillName='OverFlowBill'
END
ELSE IF @nBillType=16
BEGIN
	--生产拆装单
	SET @chvBillName='DisassembleBill'
END
ELSE IF @nBillType=57
BEGIN
	--成本调价单
	SET @chvBillName='AdPriceBill'
END
ELSE IF @nBillType IN (187,188)
BEGIN
	--分支机构调拨出，入库单
	SET @chvBillName='STypeMoveBill'
END
ELSE IF @nBillType=400	SET @chvBillName='AppraisalBill'
ELSE IF @nBillType=401	SET @chvBillName='AppraisalBackBill'
ELSE IF @nBillType=402	SET @chvBillName='SendBill'
ELSE IF @nBillType=403	SET @chvBillName='SendBackBill'
	



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetBrandArAndYsDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_GetBrandArAndYsDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:李德强
	日期:2018-01-12
	描述:获取往来单位品牌应收预收明细
*/
CREATE  PROCEDURE Gp_GetBrandArAndYsDetail
(
	@OperatorID 	VARCHAR(50),	            --操作员ID号 
	@StypeId		VARCHAR(MAX),				--分支机构
	@BtypeId		VARCHAR(MAX),				--结算单位ID
	@DTypeId		VARCHAR(MAX),				--部门ID
	@BrandarTypeId	VARCHAR(MAX),				--品牌ID
	@StartDate		VARCHAR(50),
	@EndDate		VARCHAR(50),
	@IncludePre		VARCHAR(10),				--包含预收
	@CId			INT,						--币种
	@ShowRedWord	INT = 0						--是否显示红冲  0.不显示 1.显示
)
AS
SET NOCOUNT ON 

--=======================================基本信息【BEGIN】=======================================
DECLARE @SQL VARCHAR(MAX)=''
IF @IncludePre = 'True'
SET  @IncludePre = '1'
IF @IncludePre = 'False'
SET  @IncludePre = '0'
--分支机构
CREATE TABLE #Stype(TypeId VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
INSERT INTO #Stype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID)

--结算单位
CREATE TABLE #DealBType(TypeId	VARCHAR(50)) CREATE CLUSTERED INDEX #DealBType_P_K ON #DealBType(TypeId)
INSERT INTO #DealBType(TypeId) 
SELECT a.TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) a
INNER JOIN dbo.btype b ON a.TypeId=b.typeId AND b.IsUseBrandarType='1'

--品牌
CREATE TABLE #Commodity(TypeId VARCHAR(50),UserCode VARCHAR(50),FullName VARCHAR(200))CREATE CLUSTERED INDEX #Commodity_P_K ON #Commodity(TypeId)
SET @SQL='
INSERT INTO #Commodity(TypeId,UserCode,FullName) 
SELECT  
	A.TypeId,UserCode,FullName
FROM brandar_Commodity A'+CHAR(13)

--品牌不为空
IF ISNULL(@BrandarTypeId,'')<>''
  	SET @SQL+=' INNER JOIN f_split('''+@BrandarTypeId+''','','') F  ON A.TypeId LIKE F.a+''%'''+CHAR(13)

SET @SQL+='WHERE A.SonNum=0'+CHAR(13)

EXEC(@SQL)

--部门
CREATE TABLE #Dtype(TypeId VARCHAR(50)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
INSERT INTO #Dtype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--币种
CREATE TABLE #Currency(CId INT)  CREATE CLUSTERED INDEX #Currency_P_K ON #Currency(CId)
IF @cid = 0
	INSERT INTO #Currency(CId) SELECT CId FROM dbo.Ac_Currency
ELSE
	INSERT INTO #Currency(CId) VALUES(@cid)

DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';

--=======================================基本信息【END】=======================================



--=======================================业务逻辑【BEGIN】=======================================

CREATE TABLE #Bill(

	BillNumberId	INT,
	StypeId			VARCHAR(50),
	BillDate		DATETIME,
	BillCode		VARCHAR(200),
	BillType		INT, 
	BrandarTypeId	VARCHAR(50),
	BrandUserCode   VARCHAR(50), -- 品牌code
	BrandFullName	VARCHAR(200), -- 品牌名称
	DealBTypeID		VARCHAR(50),--结算单位
	DTypeID			VARCHAR(50),--部门ID
	ARAddTotal		NUMERIC(24,10), 
	nARAddTotal		NUMERIC(24,10), 
	ARDecTotal		NUMERIC(24,10), 
	nARDecTotal		NUMERIC(24,10), 
	Comment			VARCHAR(MAX),
	CId				INT, 
	Rate			NUMERIC(24,10),
	IsIni			INT, 
	ifcheck 		VARCHAR(5),
	RedWord 		INT
)

INSERT INTO #Bill
(	
	BillNumberId,
	StypeId,
	BillDate,
	BillCode,
	BillType, 
	BrandarTypeId,
	BrandUserCode,
	BrandFullName,
	DealBTypeID,--结算单位
	DTypeID,
	ARAddTotal, 
	nARAddTotal, 
	ARDecTotal, 
	nARDecTotal, 
	Comment,
	CId, 
	Rate,
	IsIni, 
	ifcheck,
	RedWord
)
--159-业务凭证;
SELECT
	B.BillNumberId,
	B.Stypeid,
	B.BillDate,
	B.BillCode,
	B.BillType,
	S.BrandarTypeId,
	BC.UserCode,
	BC.FullName,
	S.ATypeID DealBTypeID,
	B.DTypeId,
	S.J_Total ARAddTotal,
	S.NJ_Total nARAddTotal ,
	S.D_Total ARDecTotal,
	S.ND_Total nARDecTotal,
	B.Comment,
	S.CID,
	B.Rate,
	B.IsIni,
	B.ifcheck,
	B.RedWord
FROM  AccountCredence S
INNER JOIN #Commodity BC ON BC.TypeId=S.BrandarTypeId
INNER JOIN BillIndex B ON ((B.BillDate<=@EndDate AND B.ifcheck='t' AND B.redword='0' ) ) AND B.BillType=159 AND S.BillNumberID=B.BillNumberId
INNER JOIN F_TreeGxAssets(@OperatorID) F ON F.nId=S.TypeATypeID
INNER JOIN Ac_Items I ON I.nId=F.nId AND I.UserCode='987' AND I.Sysrow=1
INNER JOIN #DealBType BB ON BB.TypeId=S.ATypeID
INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
INNER JOIN #Currency BC1 ON BC1.CId=S.CID
UNION ALL
--11-销售出库单;45-销售退货单;160-销售换货单;141-委托代销结算单;12-组合品销售出库单;46-组合品销售退货单;36-费用单;93-其他收入单;
SELECT 
	B.BillNumberId,
	B.Stypeid,
	B.BillDate,
	B.BillCode,
	B.BillType,
	D.BrandarTypeId,
	BC.UserCode,
	BC.FullName,
	B.DealBTypeID,
	B.DTypeId,
	CASE WHEN B.BillType IN(11,12,141,93) THEN D.TaxTotal-ISNULL(BM.TotalInMoney,0)-ISNULL(BM.YSTotalInMoney,0) - ISNULL(BM.PreferenceMoney,0) 
		 WHEN B.BillType=160 AND D.TaxTotal-ISNULL(BM.TotalInMoney,0)-ISNULL(BM.YSTotalInMoney,0) - ISNULL(BM.PreferenceMoney,0)>0 THEN D.TaxTotal-ISNULL(BM.TotalInMoney,0)-ISNULL(BM.YSTotalInMoney,0) - ISNULL(BM.PreferenceMoney,0)
		 ELSE 0 END ARAddTotal,
	CASE WHEN B.BillType IN(11,12,141,93) THEN D.NTaxTotal-ISNULL(BM.NTotalInMoney,0)-ISNULL(BM.NYSTotalInMoney,0) - ISNULL(BM.NPreferenceMoney,0) 
		 WHEN B.BillType=160 AND D.NTaxTotal-ISNULL(BM.NTotalInMoney,0)-ISNULL(BM.NYSTotalInMoney,0) - ISNULL(BM.NPreferenceMoney,0)>0 THEN D.NTaxTotal-ISNULL(BM.NTotalInMoney,0)-ISNULL(BM.NYSTotalInMoney,0) - ISNULL(BM.NPreferenceMoney,0)
		 ELSE 0 END nARAddTotal ,
	 
	CASE WHEN B.BillType IN(45,46) THEN D.TaxTotal-ISNULL(BM.TotalInMoney,0)-ISNULL(BM.YSTotalInMoney,0) - ISNULL(BM.PreferenceMoney,0)
		 WHEN B.BillType=160 AND D.TaxTotal-ISNULL(BM.TotalInMoney,0)-ISNULL(BM.YSTotalInMoney,0) - ISNULL(BM.PreferenceMoney,0)<0 THEN ABS(D.TaxTotal-ISNULL(BM.TotalInMoney,0)-ISNULL(BM.YSTotalInMoney,0) - ISNULL(BM.PreferenceMoney,0))
		 WHEN B.BillType=36 AND B.btypeid like '00001%' AND @ExpenseToAr=1 THEN D.TaxTotal-ISNULL(BM.TotalInMoney,0)-ISNULL(BM.YSTotalInMoney,0) - ISNULL(BM.PreferenceMoney,0)
		 ELSE 0 END ARDecTotal,
		 
	CASE WHEN B.BillType IN(45,46) THEN D.NTaxTotal-ISNULL(BM.NTotalInMoney,0)-ISNULL(BM.NYSTotalInMoney,0) - ISNULL(BM.NPreferenceMoney,0)
		 WHEN B.BillType=160 AND D.NTaxTotal-ISNULL(BM.NTotalInMoney,0)-ISNULL(BM.NYSTotalInMoney,0) - ISNULL(BM.NPreferenceMoney,0)<0 THEN  ABS(D.NTaxTotal-ISNULL(BM.NTotalInMoney,0)-ISNULL(BM.NYSTotalInMoney,0) - ISNULL(BM.NPreferenceMoney,0))
		 WHEN B.BillType=36 AND B.btypeid like '00001%' AND @ExpenseToAr=1 THEN D.NTaxTotal-ISNULL(BM.NTotalInMoney,0)-ISNULL(BM.NYSTotalInMoney,0) - ISNULL(BM.NPreferenceMoney,0)
		 ELSE 0 END nARDecTotal,
	
	B.Comment,
	B.CID,
	B.Rate,
	B.IsIni,
	B.ifcheck,
	B.RedWord
FROM BillIndex B 
INNER JOIN #Stype BS ON BS.TypeId=B.Stypeid AND (( B.BillDate<=@EndDate AND B.ifcheck='t'  AND B.redword='0' )) AND B.BillType IN(11,12,45,46,141,93,160,36)
INNER JOIN #DealBType BB ON BB.TypeId=B.DealBTypeID 
INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
INNER JOIN #Currency BC1 ON BC1.CId=B.CID
INNER JOIN (
		--11=销售出库单
		SELECT 
			BillNumberId,
			BrandarTypeID,
			SUM(TaxTotal) TaxTotal,
			SUM(NTaxTotal) NTaxTotal
		FROM dbo.SaleBill S
		INNER JOIN dbo.ptype P ON P.typeId = S.PtypeId
		GROUP BY 
			BrandarTypeID,
			BillNumberId
			
		UNION ALL--12=组合品销售出库单
		SELECT 
			BillNumberId,
			BrandarTypeID,
			SUM(TaxTotal) TaxTotal,
			SUM(NTaxTotal) NTaxTotal
		FROM dbo.PT_Combin_SaleBill S
		INNER JOIN dbo.ptype P ON P.typeId = S.PtypeId
		GROUP BY 
			BrandarTypeID,
			BillNumberId
			
		UNION ALL--45	销售退货单
		SELECT 
			BillNumberId,
			BrandarTypeID,
			SUM(TaxTotal) TaxTotal,
			SUM(NTaxTotal) NTaxTotal
		FROM dbo.saleBackBill S
		INNER JOIN dbo.ptype P ON P.typeId = S.PtypeId
		GROUP BY 
			BrandarTypeID,
			BillNumberId	
			
		UNION ALL--46	组合品销售退货单
		SELECT 
			BillNumberId,
			BrandarTypeID,
			SUM(TaxTotal) TaxTotal,
			SUM(NTaxTotal) NTaxTotal
		FROM dbo.PT_Combin_SaleBackBill S
		INNER JOIN dbo.ptype P ON P.typeId = S.PtypeId
		GROUP BY 
			BrandarTypeID,
			BillNumberId	
			
		UNION ALL--141	委托代销结算单
		SELECT 
			BillNumberId,
			BrandarTypeID,
			SUM(TaxTotal) TaxTotal,
			SUM(NTaxTotal) NTaxTotal
		FROM dbo.CommissionBill S
		INNER JOIN dbo.ptype P ON P.typeId = S.PtypeId
		WHERE S.type = 141
		GROUP BY 
			BrandarTypeID,
			BillNumberId
			
		UNION ALL--93	其他收入单 36	费用单
		SELECT 
			BillNumberId,
			BrandarTypeId,
			SUM(total) TaxTotal,
			SUM(NTotal) NTaxTotal
		FROM dbo.MoneyBill
		GROUP BY 
			BrandarTypeID,
			BillNumberId	
		
		UNION ALL--160	销售换货单
		SELECT 
			BillNumberId,
			BrandarTypeID,
			SUM(CASE WHEN S.InOrOut='I' THEN -S.TaxTotal ELSE S.TaxTotal END) TaxTotal,
			SUM(CASE WHEN S.InOrOut='I' THEN -S.NTaxTotal ELSE S.NTaxTotal END) NTaxTotal
		FROM dbo.SaleGoodsExchangeBill S
		INNER JOIN dbo.ptype P ON P.typeId = S.PtypeId
		GROUP BY 
			BrandarTypeID,
			BillNumberId
) D ON  D.BillNumberId = B.BillNumberId 
INNER JOIN #Commodity BC ON BC.TypeId=D.BrandarTypeID
LEFT JOIN dbo.BillMulBrand BM ON BM.BillNumberId = B.BillNumberId AND BM.BrandarTypeID = D.BrandarTypeID
WHERE 
	D.TaxTotal-ISNULL(BM.TotalInMoney,0)-ISNULL(BM.YSTotalInMoney,0) - ISNULL(BM.PreferenceMoney,0)<>0
	
UNION ALL 
--405-销售发货开票;
SELECT  
	B.BillNumberId,
	B.Stypeid,
	B.BillDate,
	B.BillCode,
	B.BillType,
	p.BrandarTypeID,
	BC.UserCode,
	BC.FullName,
	B.DealBTypeID,
	B.DTypeId,
	S.TaxTotal ARAddTotal,
	S.NTaxTotal nARAddTotal ,
	0 ARDecTotal,
	0 nARDecTotal,
	B.Comment,
	B.CID,
	B.Rate,
	B.IsIni,
	B.ifcheck,
	B.RedWord
FROM dbo.ReceiptBill s
INNER JOIN ReceiptBillIndex b ON (( B.BillDate<=@EndDate AND B.ifcheck='t'  AND B.redword='0' )) AND b.BillType=405 AND b.BillNumberId=s.BillNumberId
INNER JOIN ptype P ON p.typeid=s.PtypeId 
INNER JOIN #Commodity BC ON BC.TypeId=P.BrandarTypeID
INNER JOIN #Stype BS ON BS.TypeId=B.Stypeid
INNER JOIN #DealBType BB ON BB.TypeId=B.DealBTypeID 
INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
INNER JOIN #Currency BC1 ON BC1.CId=B.CID

UNION ALL 
--116-应收增加单;115-应收减少单;
SELECT 
	B.BillNumberId,
	B.Stypeid,
	B.BillDate,
	B.BillCode,
	B.BillType,
	S.BrandarTypeID,
	BC.UserCode,
	BC.FullName,
	S.BtypeId DealBTypeID,
	B.DTypeId,
	CASE WHEN B.BillType=116 THEN S.total ELSE 0 END ARAddTotal,
	CASE WHEN B.BillType=116 THEN S.NTotal ELSE 0 END nARAddTotal ,
	CASE WHEN B.BillType=115 THEN S.total ELSE 0 END ARDecTotal,
	CASE WHEN B.BillType=115 THEN S.NTotal ELSE 0 END nARDecTotal,
	B.Comment,
	B.CID,
	B.Rate,
	B.IsIni,
	B.ifcheck,
	B.RedWord
FROM dbo.AdDebtBill S
INNER JOIN BillIndex  b  ON (( B.BillDate<=@EndDate AND B.ifcheck='t' AND B.redword='0' )) AND b.BillType In(115,116) AND B.BillNumberId=S.BillNumberId
INNER JOIN #Commodity BC ON BC.TypeId=S.BrandarTypeID
INNER JOIN #Stype BS ON BS.TypeId=B.Stypeid
INNER JOIN #DealBType BB ON BB.TypeId=S.BtypeId
INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
INNER JOIN #Currency BC1 ON BC1.CId=B.CID

UNION ALL 
--4-收款单;
SELECT  
	B.BillNumberId,
	B.Stypeid,
	B.BillDate,
	B.BillCode,
	B.BillType,
	S.BrandarTypeID,
	BC.UserCode,
	BC.FullName,
	B.DealBTypeID,
	B.DTypeId,
	0 ARAddTotal,
	0 nARAddTotal ,
	S.total+S.PreferenceMoney ARDecTotal,
	S.ntotal+S.nPreferenceMoney nARDecTotal,
	B.Comment,
	B.CID,
	B.Rate,
	B.IsIni,
	B.ifcheck,
	B.RedWord
FROM BillIndex b
INNER JOIN gatheringBill S ON (( B.BillDate<=@EndDate AND B.ifcheck='t' AND B.redword='0' )) AND b.BillNumberId=S.BillNumberId AND B.BillType=4 
--AND S.AtypeId <> 39
INNER JOIN #Commodity BC ON BC.TypeId=S.BrandarTypeID
INNER JOIN #Stype BS ON BS.TypeId=B.Stypeid
INNER JOIN #DealBType BB ON BB.TypeId=B.DealBTypeID 
INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
INNER JOIN #Currency BC1 ON BC1.CId=B.CID

--包含预收
IF @IncludePre = '1'
BEGIN
	INSERT INTO #Bill
	(	
		BillNumberId,
		StypeId,
		BillDate,
		BillCode,
		BillType, 
		BrandarTypeId,
		BrandUserCode,
		BrandFullName,
		DealBTypeID,--结算单位
		DTypeID,
		ARAddTotal, 
		nARAddTotal, 
		ARDecTotal, 
		nARDecTotal, 
		Comment,
		CId, 
		Rate,
		IsIni, 
		ifcheck,
		RedWord
	)
	--159-业务凭证;
	SELECT
		B.BillNumberId,
		B.Stypeid,
		B.BillDate,
		B.BillCode,
		B.BillType,
		S.BrandarTypeId,
		BC.UserCode,
		BC.FullName,
		S.ATypeID DealBTypeID,
		B.DTypeId,
		S.J_Total ARAddTotal,
		S.NJ_Total nARAddTotal ,
		S.D_Total ARDecTotal,
		S.ND_Total nARDecTotal,
		B.Comment,
		S.CID,
		B.Rate,
		B.IsIni,
		B.ifcheck,
		B.RedWord
	FROM  AccountCredence S
	INNER JOIN #Commodity BC ON BC.TypeId=S.BrandarTypeId
	INNER JOIN BillIndex B ON ((B.BillDate<=@EndDate AND B.ifcheck='t' AND B.redword='0' )) AND B.BillType=159 AND S.BillNumberID=B.BillNumberId
	INNER JOIN F_AllTreeA(@OperatorID) F  ON F.nId=S.TypeATypeID
	INNER JOIN Ac_Items I ON I.nId=F.nId AND I.UserCode='2131' AND I.Sysrow=1 
	INNER JOIN #DealBType BB ON BB.TypeId=S.ATypeID
	INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
	INNER JOIN #Currency BC1 ON BC1.CId=S.CID
	

	UNION ALL
--11-销售出库单;45-销售退货单;160-销售换货单;141-委托代销结算单;12-组合品销售出库单;46-组合品销售退货单;36-费用单;93-其他收入单;
	SELECT 
		B.BillNumberId,
		B.Stypeid,
		B.BillDate,
		B.BillCode,
		B.BillType,
		M.BrandarTypeId,
		BC.UserCode,
		BC.FullName,
		B.DealBTypeID,
		B.DTypeId,
		CASE WHEN B.BillType IN(11,12,141,93) THEN M.YSTotalInMoney 
			 WHEN B.BillType=160 AND M.YSTotalInMoney>0 THEN M.YSTotalInMoney
			 ELSE 0 END ARAddTotal,
		CASE WHEN B.BillType IN(11,12,141,93) THEN M.NYSTotalInMoney
			 WHEN B.BillType=160 AND M.NYSTotalInMoney>0 THEN M.NYSTotalInMoney
			 ELSE 0 END nARAddTotal ,
			 
		CASE WHEN B.BillType IN(45,46) THEN M.YSTotalInMoney 
			 WHEN B.BillType=160 AND M.YSTotalInMoney<0 THEN ABS(M.YSTotalInMoney)
			 WHEN B.BillType=36 AND B.btypeid like '00001%' AND @ExpenseToAr=1 THEN M.YSTotalInMoney
			 ELSE 0 END ARDecTotal,
		CASE WHEN B.BillType IN(45,46) THEN M.NYSTotalInMoney
			 WHEN B.BillType=160 AND M.NYSTotalInMoney<0 THEN ABS(M.NYSTotalInMoney)
			 WHEN B.BillType=36 AND B.btypeid like '00001%' AND @ExpenseToAr=1 THEN M.NYSTotalInMoney
			 ELSE 0 END nARDecTotal,
		B.Comment,
		B.CID,
		B.Rate,
		B.IsIni,
		B.ifcheck,
		B.RedWord
	FROM dbo.BillMulBrand M
	INNER JOIN BillIndex B ON (( B.BillDate <=@EndDate AND B.ifcheck='t' AND B.redword='0' )) AND B.BillType IN(11,12,45,46,141,93,160,36) AND M.YSTotalInMoney<>0  AND B.BillNumberId = M.BillNumberId
	INNER JOIN #Commodity BC ON BC.TypeId=M.BrandarTypeID
	INNER JOIN #Stype BS ON BS.TypeId=B.Stypeid
	INNER JOIN #DealBType BB ON BB.TypeId=B.DealBTypeID 
	INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
	INNER JOIN #Currency BC1 ON BC1.CId=B.CID
	
	UNION ALL
	--189-预收款单;
	SELECT 
		B.BillNumberId,
		B.Stypeid,
		B.BillDate,
		B.BillCode,
		B.BillType,
		M.BrandarTypeId,
		BC.UserCode,
		BC.FullName,
		B.DealBTypeID,
		B.DTypeId,
		0 ARAddTotal,
		0 nARAddTotal,
		M.total ARDecTotal,
		M.ntotal nARDecTotal,
		B.Comment,
		B.CID,
		B.Rate,
		B.IsIni,
		B.ifcheck,
		B.RedWord
	FROM dbo.prebill M
	INNER JOIN BillIndex B ON (( B.BillDate <=@EndDate AND B.ifcheck='t'  AND B.redword='0' ) OR B.isIni=1) AND B.BillType=189 AND B.BillNumberId = M.BillNumberId
	INNER JOIN #Commodity BC ON BC.TypeId=M.BrandarTypeID
	INNER JOIN #Stype BS ON BS.TypeId=B.Stypeid
	INNER JOIN #DealBType BB ON BB.TypeId=B.DealBTypeID 
	INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
	INNER JOIN #Currency BC1 ON BC1.CId=B.CID
	
	UNION ALL
	--4-收款单--项目预收资金
	SELECT  
		B.BillNumberId,
		B.Stypeid,
		B.BillDate,
		B.BillCode,
		B.BillType,
		S.BrandarTypeID,
		BC.UserCode,
		BC.FullName,
		B.DealBTypeID,
		B.DTypeId,
		S.total ARAddTotal,
		S.ntotal nARAddTotal ,
		0 ARDecTotal,
		0 nARDecTotal,
		B.Comment,
		B.CID,
		B.Rate,
		B.IsIni,
		B.ifcheck,
		B.RedWord
	FROM BillIndex b
	INNER JOIN gatheringBill S ON (( B.BillDate<=@EndDate AND B.ifcheck='t' AND B.redword='0' )) AND b.BillNumberId=S.BillNumberId AND B.BillType=4 AND S.AtypeId=39
	INNER JOIN #Commodity BC ON BC.TypeId=S.BrandarTypeID
	INNER JOIN #Stype BS ON BS.TypeId=B.Stypeid
	INNER JOIN #DealBType BB ON BB.TypeId=B.DealBTypeID 
	INNER JOIN #Dtype BD ON BD.TypeId=B.DTypeId
	INNER JOIN #Currency BC1 ON BC1.CId=B.CID

END

--=======================================业务逻辑【END】=======================================


--=======================================返回结果集及删除临时表【BEGIN】=======================================

SELECT	
	BillNumberId,
	Stypeid,
	BillDate,
	BillCode,
	BillType,
	BrandarTypeId,
	BrandUserCode,
	BrandFullName,
	DealBTypeID BTypeID,
	DTypeId,
	SUM(ARAddTotal) ARAddTotal,
	SUM(nARAddTotal) nARAddTotal ,
	SUM(ARDecTotal) ARDecTotal,
	SUM(nARDecTotal) nARDecTotal,
	Comment,
	CID,
	Rate,
	IsIni,
	ifcheck,
	RedWord
FROM #Bill 
WHERE 
	(@ShowRedWord=0 AND RedWord=0) OR @ShowRedWord<>0	 
GROUP BY BillNumberId,
		Stypeid,
		BillDate,
		BillCode,
		BillType,
		BrandarTypeId,
		BrandUserCode,
		BrandFullName,
		DealBTypeID,
		DTypeId,
		ARAddTotal,
		nARAddTotal ,
		ARDecTotal,
		nARDecTotal,
		Comment,
		CID,
		Rate,
		IsIni,
		ifcheck,
		RedWord 

DROP TABLE #Bill,#Commodity,#Currency,#DealBType,#Dtype,#Stype

--=======================================返回结果集及删除临时表【END】=======================================
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_GetBtypeAllUsage]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_GetBtypeAllUsage]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/07/06
	Description	:	获取科目表中是否使用了【客户】【供货商】【往来单位】
*/

CREATE PROCEDURE GP_GetBtypeAllUsage
--@encode$--
AS 
SET NOCOUNT ON

IF EXISTS (SELECT TOP 1 1 FROM Ac_Account a
JOIN Ac_Account_Assist_CheckItems c ON c.STypeId = a.StypeId AND c.ATypeId = a.TypeId
JOIN Ac_Assist_CheckItems i ON i.AscIds = c.Ascids
WHERE i.FullName IN ('客户','供货商'))
    RETURN 1
    
    
IF EXISTS (SELECT TOP 1 1 FROM Ac_Account a
JOIN Ac_Account_Assist_CheckItems c ON c.STypeId = a.StypeId AND c.ATypeId = a.TypeId
JOIN Ac_Assist_CheckItems i ON i.AscIds = c.Ascids
WHERE i.FullName IN ('往来单位'))
    RETURN 2
    
    
RETURN 0
    

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetCancelCheckLimit]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_GetCancelCheckLimit
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--==========================================
--CreatedBy:	GLJ
--Date:			2012-12-03	
--Description:	得到系统配置中-物流单据商品采用批号-是否可以取消选中的权限
--==========================================
CREATE PROC Gp_GetCancelCheckLimit
(
	@flag INT --1 查批号 2 查生产日期 3有效期至
)
--@encode$--
AS
SET NOCOUNT ON 
--创建具有goodsNumber字段的表名临时表
CREATE TABLE #goodsTb(tbName VARCHAR(50))
DECLARE @SQLWhere VARCHAR(2000)
		
IF @flag=1
	SELECT	 @SQLWhere='goodsnumber'
IF @flag=2
	SELECT	 @SQLWhere='ProduceDate'
IF @flag=3
	SELECT	 @SQLWhere='ValidDate'

	INSERT INTO #goodsTb
	SELECT s.name 
	FROM sysobjects s 
	INNER JOIN syscolumns c ON s.id = c.id AND c.name = @SQLWhere AND s.type = 'u'
	WHERE s.name NOT IN('GuestBackIndex','LendIndex','billindex','Offline_BillIndex','OrderIndex','BeforePromoteSaleBill','nVipCardSet')--这几个表中的goodsnumber不是批号 BeforePromoteSaleBill排查，这个是销售出库单中点击促销保存临时数据的



DECLARE 
		@tbName VARCHAR(50),
		@SQL	NVARCHAR(500),
		@RET	INT

		
WHILE EXISTS(SELECT TOP 1 1 FROM #goodsTb)
	BEGIN
		SELECT @tbName=tbName FROM #goodsTb
		
		SELECT @SQL=N'IF EXISTS(SELECT TOP 1 1 FROM '+@tbName+' WHERE ISNULL('+@SQLWhere+','''')<>'''')
			BEGIN
				SET @RetCount =1
			END
		ELSE 
			DELETE FROM #goodsTb WHERE tbName='''+@tbName+''''
						
		EXEC sp_executesql @SQL,N'@RetCount INT OUT',@RET OUT
		
		IF(@RET=1)
		BEGIN
			PRINT (@SQL)
			BREAK
		END
	END
RETURN @RET
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	杨鑫
	Date	:	2017/11/10
	Description	: 优惠券基本信息精确匹配
*/
CREATE PROCEDURE Gp_GetCouponInfo
(
	@filter VARCHAR(50) , --信息过滤
	@tablename  VARCHAR(50),
	@OperatorId VARCHAR(50) 
)
--@encode$--
AS
SET NOCOUNT ON 


IF(@tablename = 'Sptype') --适用商品
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000')
	BEGIN  
		SELECT FullName,UserCode,Pid,iscombinationproduct AS IsCombined,customitemid AS ItemID,Standard,Type,typeId,sonnum FROM dbo.ptype WHERE (UserCode = @filter OR FullName = @filter) AND typeId<>'00000' AND deleted = 0
	END 
	ELSE
	BEGIN
		SELECT	FullName,UserCode,Pid,iscombinationproduct AS IsCombined,customitemid AS ItemID,Standard,Type,A.typeId,sonnum
		FROM	PType_L L
				INNER JOIN PType  A ON A.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @OperatorId
				AND L.flag = 1 
				AND (A.UserCode = @filter OR A.Fullname = @filter ) 
				AND A.Deleted = 0 
				AND A.TypeID <> '00000'
	END			
END 
ELSE IF(@tablename = 'ExPtype')--兑换商品
BEGIN 
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000' )
	BEGIN 
		SELECT FullName,UserCode,Pid,iscombinationproduct AS IsCombined,customitemid AS ItemID,Standard,Type,typeId,sonnum FROM dbo.ptype WHERE (UserCode = @filter OR FullName = @filter) AND typeId<>'00000' AND iscombinationproduct=0 AND deleted = 0
	END 
	ELSE
	BEGIN
		SELECT	FullName,UserCode,Pid,iscombinationproduct AS IsCombined,customitemid AS ItemID,A.typeId,sonnum
		FROM	dbo.ptype_l L
				INNER JOIN PType  A ON A.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = ''+@OperatorId+''
				AND L.flag = 1 
				AND (A.UserCode = @filter OR A.Fullname = @filter ) 
				AND A.TypeID <> '00000'
				AND A.iscombinationproduct=0
				AND A.typeId LIKE '00000%'
				AND A.deleted = 0
	END 
END 
ELSE IF(@tablename = 'Stype')--分支机构
BEGIN 
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeID = '00000' )
	BEGIN 
		SELECT FullName,UserCode,Comment AS remark,typeId,sonnum,SType.typeid AS stypeid FROM dbo.SType WHERE (UserCode = @filter OR FullName = @filter) AND typeId<>'00000' 
	END 
	ELSE
	BEGIN
		SELECT	FullName,UserCode,Comment AS remark,A.typeId,sonnum,A.typeid AS stypeid
		FROM	dbo.stype_l L
				INNER JOIN SType  A ON A.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = ''+@OperatorId+''
				AND L.flag = 1 
				AND (A.UserCode = @filter OR A.Fullname = @filter ) 
				AND A.TypeID <> '00000'
				AND A.typeId LIKE '00000%'
	END 
END 


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_GetCustomData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_GetCustomData]
GO
/*
	作者：张陈仁
	日期：2012-06-26
	描述：获取自定义数据
	
*/
CREATE PROCEDURE GP_GetCustomData
(
	@BillNumberId INT,
	@BillType INT,
	@WhichCustom INT, --1单据头  2单据体,
	@InOrOut CHAR(1)=''---双表体
)
--@encode$--
AS
BEGIN
	DECLARE @BID INT,
			@CusType VARCHAR(50),
			@CusOrder INT,
			@Alias	  VARCHAR(10),
			@sqlselect VARCHAR(MAX)='',
			@sqlfrom VARCHAR(MAX)='',
			@sqlWhere VARCHAR(Max)=''
						
	IF @InOrOut=''
		SET @sqlWhere=' WHERE A.billtype='+CHAR(39)+ CAST(@BillType as varchar)+CHAR(39)+'  AND  A.BillNumberId='+CAST(@BillNumberId AS VARCHAR(50))+' '	
	ELSE 
	BEGIN
		IF @WhichCustom=2
			SET @sqlWhere=' WHERE  A.billtype='+CHAR(39)+ CAST(@BillType as varchar)+CHAR(39)+'  AND A.BillNumberId='+CAST(@BillNumberId AS VARCHAR(50))+' AND InOrOut='''+@InOrOut+''' '	
		ELSE
			SET @sqlWhere=' WHERE A.billtype='+CHAR(39)+ CAST(@BillType as varchar)+CHAR(39)+'  AND A.BillNumberId='+CAST(@BillNumberId AS VARCHAR(50))+' '
	END
		
	CREATE TABLE #T1
	(
		BillType		INT,
		CustomerType	VARCHAR(50),
		CustomerOrder	INT,
		Alias			VARCHAR(10),
		InOrOut			varchar(10)
	)
	IF @WhichCustom=1
	BEGIN
		INSERT INTO #T1 SELECT BillType,CustomerType,CustomerOrder,LEFT(CustomerType,3)+CAST(CustomerOrder AS VARCHAR(2)),NULL
		FROM CustomBillColumnsDefines 
		WHERE BillType=@BillType
		SET @sqlselect='SELECT A.BillNumberId,A.BillType'
		SET @sqlfrom=' FROM CustomBillColumns A'
	END				
	ELSE IF @WhichCustom=2
	BEGIN
		IF @InOrOut=''
			BEGIN
				INSERT INTO #T1 SELECT BillType,CustomerType,CustomerOrder,LEFT(CustomerType,3)+CAST(CustomerOrder AS VARCHAR(10)),InOrOut  
				FROM CustomBillDetailColumnsDefines 
				WHERE BillType=CASE @BillType WHEN 9999 THEN 305 ELSE @BillType END --9999为零售促销前数据billtype,取自定义列的时候去零售单的		
			END
		ELSE
			BEGIN
			    INSERT INTO #T1 SELECT BillType,CustomerType,CustomerOrder,LEFT(CustomerType,3)+CAST(CustomerOrder AS VARCHAR(10)),InOrOut  
				FROM CustomBillDetailColumnsDefines 
				WHERE BillType=@BillType AND InOrOut=@InOrOut
			END

		
		SET @sqlselect='SELECT A.BillNumberId,A.DetailId,A.BillType,A.InOrOut'
		SET @sqlfrom=' FROM CustomBillDetailColumns A'
	END
	--sELECT * FROM #T1 ORDER BY CustomerOrder
	DECLARE CUSTOMER_CURSOR CURSOR FORWARD_ONLY STATIC FOR
	SELECT CustomerType,CustomerOrder,Alias FROM #T1 ORDER BY CustomerOrder
	OPEN CUSTOMER_CURSOR 
	FETCH NEXT FROM CUSTOMER_CURSOR INTO @CusType,@CusOrder,@Alias
		 WHILE @@FETCH_STATUS = 0
		 BEGIN
			IF @CusType NOT IN ('Number','Text','Date')
			BEGIN
				SET @sqlselect=@sqlselect+','+@Alias+'.'+'Fullname as FullName'+CAST(@CusOrder AS varchar(10))+','+@Alias+'.'+'Typeid Costom'+CAST(@CusOrder AS varchar(10))
				IF CHARINDEX('SelfDataType',@CusType)>0--自定义为自由项时
					BEGIN
						DECLARE @datatypeid VARCHAR(10)
				        SET @datatypeid=REPLACE(@CusType,'__SelfDataType','')
				        SET @sqlfrom=@sqlfrom+' LEFT JOIN xw_SelfData '+@Alias+' ON A.Costom'+CAST(@CusOrder AS varchar(10))+'='+@Alias+'.Typeid and '+@Alias+'.DataTypeId= '+@datatypeid+' '
				        --SET @sqlWhere=@sqlWhere+' and '+@Alias+'.DataTypeId= '+@datatypeid+''
					END
					ELSE
						BEGIN
							SET @sqlfrom=@sqlfrom+' LEFT JOIN '+@CusType+' '+@Alias+' ON A.Costom'+CAST(@CusOrder AS varchar(10))+'='+@Alias+'.Typeid'
						END					
			END
			ELSE
				IF @CusType IN ('Date')
					SET @sqlselect=@sqlselect+','+' case when ISNULL(A.Costom'+CAST(@CusOrder AS CHAR(2))+','''')<>'''' then CONVERT(VARCHAR(100),convert(DATE,A.Costom'+CAST(@CusOrder AS CHAR(2))+'),23) else '''' end as Costom'+CAST(@CusOrder AS CHAR(2))+','+'case when ISNULL(A.Costom'+CAST(@CusOrder AS CHAR(2))+','''')<>'''' then CONVERT(VARCHAR(100),convert(DATE,A.Costom'+CAST(@CusOrder AS CHAR(2))+'),23) else '''' end as FullName'+CAST(@CusOrder AS CHAR(2))+' '
			    ELSE
					SET @sqlselect=@sqlselect+','+' A.Costom'+CAST(@CusOrder AS CHAR(2))+','+'A.Costom'+CAST(@CusOrder AS CHAR(2))+' as FullName'+CAST(@CusOrder AS CHAR(2))+' '
									
			FETCH NEXT FROM CUSTOMER_CURSOR INTO @CusType,@CusOrder,@Alias
		 END
	CLOSE CUSTOMER_CURSOR
	DEALLOCATE CUSTOMER_CURSOR
	PRINT @sqlselect+@sqlfrom+@sqlWhere
	EXEC(@sqlselect+@sqlfrom+@sqlWhere)
	DROP TABLE #T1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2005-3-24
	描述：取期初的算法出现了问题，改
*/
CREATE      PROCEDURE Gp_GetDbf 
(	
	@szAtypeId varchar(50),		--财务科目的ID
	@szPtypeId varchar(50),		--商品的ID
	@szBtypeId varchar(50),		--往来单位的ID
	@szEtypeId varchar(50),		--经手人的ID
	@szKtypeId varchar(50),		--仓库的ID
	@szSTypeID varchar(50),		--分支机构ID
	@szPeriod  varchar(2),		--
	@szJobNumber varchar(20),	--
	--	@OutFactoryDate datetime,
	@dqty    NUMERIC(24, 10)  output,
	@dtotal  NUMERIC(24, 10)  output
)
--@encode$--
AS
set nocount on
------Some vchtype
DECLARE	@GOODS_ID varchar(50),
	@CASH_ID  varchar(50),
	@CASH_BANK_ID varchar(50),
	@AR_ID varchar(50),
	@AP_ID varchar(50),
	@YF_ID varchar(50),
	@YS_ID varchar(50),
	@GOODS_LOSS_ID varchar(50),
	@GOODS_GET_ID varchar(50),
	@ALLOT_PRICE_ID varchar(50),
	@PRICE_INCOME_ID varchar(50),
	@BORROW_BUY_PRICE_ID varchar(50), 
	@GOODS_GIVE_ID varchar(50),       
	@GOODS_PRODUCE_ID varchar(50),    
	@SALE_COST_ID varchar(50),        
	@SALE_INCOME_ID varchar(50),      
	@LEND_GOODS_ID varchar(50),       
	@BORROW_GOODS_ID varchar(50),     
	@BALANCE_ID varchar(50),          
	@DEPRECIATION_ID varchar(50),     
	@APPORTION_EXPENSE_ID varchar(50),
	@INIT_MONEY_ID varchar(50),       
	@ALL_INCOME_ID varchar(50),       
	@ALL_EXPENSE_ID varchar(50),      
	@PROFIT_ID varchar(50),           
	@ASSETS_ID varchar(50),           
	@DEBT_ID varchar(50),             
	@POWER_ID varchar(50),
	@ADDEBT_INCOME_ID varchar(50),
	@ADDEBT_LOSE_ID varchar(50)
	
/*	
SELECT 	@GOODS_ID='0000100001'
SELECT 	@CASH_ID='0000100003'
SELECT 	@CASH_BANK_ID='0000100004'
SELECT 	@AR_ID='0000100005'
SELECT 	@AP_ID='0000200001'
SELECT 	@GOODS_LOSS_ID='000040000200001' --           商品报损
SELECT 	@GOODS_GET_ID='000030000200001'  --           商品报溢收入
SELECT 	@ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
SELECT 	@PRICE_INCOME_ID='000030000200003'--成本调价收入
--	SELECT @BORROW_BUY_PRICE_RECNO varchar(50)= 28;
--	SELECT @GOODS_GIVE_RECNO = 000040000200002           商品赠出
SELECT 	@GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
SELECT 	@SALE_COST_ID='0000400001'--              『销售成本』
SELECT 	@SALE_INCOME_ID='0000300001'--            『销售收入』
--	SELECT @LEND_GOODS_RECNO varchar(50),       = 21;
--	SELECT @BORROW_GOODS_RECNO varchar(50),     = 24;
SELECT 	@BALANCE_ID='000030000200004'--           进货退货差价
SELECT 	@DEPRECIATION_ID='000040000300002'--      固定资产折旧
SELECT 	@APPORTION_EXPENSE_ID='0000100007'--      待摊费用
--	SELECT @INIT_MONEY_RECNO varchar(50),       = 18;
SELECT 	@ALL_INCOME_ID='00003'	--          【收入类】
SELECT 	@ALL_EXPENSE_ID='00004'--                 【支出类】
--	SELECT @PROFIT_RECNO varchar(50),           = 19;
SELECT 	@ASSETS_ID ='00001'		--【资产合计】
SELECT 	@DEBT_ID='00002'			--【负债合计】
--	SELECT @POWER_RECNO varchar(50)            = 4;
SELECT 	@ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
SELECT 	@ADDEBT_LOSE_ID='000040000300001' --调帐亏损


SELECT @YF_ID='0000100009'	--预付账款
SELECT @YS_ID='0000200006'  --预收账款
*/

SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』
SELECT @CASH_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1001'			-- 现    金
SELECT @AR_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '987'			-- 『应收款合计』
SELECT @AP_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2121'			-- 『应付帐款合计』
SELECT @GOODS_LOSS_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0421'		-- 商品报损支出
SELECT @GOODS_GET_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0321'		-- 商品报溢收入
SELECT @ALLOT_PRICE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0325'		-- 变价调拨差价
SELECT @PRICE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0323'		-- 成本调价收入
SELECT @GOODS_PRODUCE_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0326'		-- 商品拆装差价
SELECT @SALE_COST_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5401'			-- 『销售成本』
SELECT @SALE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5101'			-- 『销售收入』
SELECT @BALANCE_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '0324'		-- 采购退货差价
SELECT @DEPRECIATION_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0432'		-- 固定资产折旧
SELECT @APPORTION_EXPENSE_ID	=nid FROM dbo.Ac_Items WHERE UserCode =  '1301'			-- 『待摊费用』
SELECT @ADDEBT_INCOME_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '03333'		-- 调帐收入
SELECT @ADDEBT_LOSE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0431'		-- 调帐亏损
SELECT @YF_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1151'			--预付账款
SELECT @YS_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2131'			--预收账款

------------------
DECLARE @szSql varchar(8000)


--==========================获取库存的余量  谢吉康　　　2003-07-22
IF @szatypeid=@GOODS_ID AND @szptypeid<>'0'
	BEGIN	
		IF @szperiod='' ---取当前库存数量
			BEGIN			
				IF @szJobNumber<>'' 		
					BEGIN
						IF @szktypeid<>'0'	--具体仓库 
							BEGIN
								SELECT 	@dqty=(SUM(qty)),
										@dtotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND ktypeid=@szktypeid 
									AND JobNumber=@szJobNumber
								IF 	@dqty IS null SELECT @dqty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END 
						ELSE			--全部仓库
							BEGIN
								SELECT 	@dqty=(SUM(qty)),
									@dtotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND JobNumber=@szJobNumber
								IF 	@dqty IS null SELECT @dqty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END
			
					END 
				ELSE
					BEGIN
						IF @szktypeid<>'0' 	--具体仓库
							BEGIN
								SELECT 	@dqty=(SUM(qty)),
									@dtotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND ktypeid=@szktypeid
								IF 	@dqty IS null SELECT @dqty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END 
						ELSE			--全部仓库
							BEGIN
								SELECT 	@dqty=(SUM(qty)),
									@dtotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
								IF 	@dqty IS null SELECT @dqty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END
					END
			END 
	ELSE ---取期初库存数量
		BEGIN
			IF @szktypeid<>'0'	--具体的仓库
				BEGIN
					SELECT 	@dqty = SUM(qty),
							@dtotal = SUM(total)
					FROM 	inigoodsstocks 
					WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
							AND KTypeId=@szKTypeId
					
					IF 	@dqty IS null SELECT @dqty=0
					IF 	@dtotal IS null SELECT @dtotal=0
					RETURN
				END 
			ELSE			--全部仓库
				BEGIN
					SELECT 	@dqty = SUM(qty),
							@dtotal = SUM(total)
					FROM 	inigoodsstocks 
					WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid										

					IF 	@dqty IS null SELECT @dqty=0
					IF 	@dtotal IS null SELECT @dtotal=0
					RETURN
				END
		END
	END 
ELSE 
BEGIN
--==========================获取应收应付的信息  谢吉康　　　2003-07-22
	-- 查具体往来单位“应付余额” 或 期初余额
	IF @szatypeid=@AP_ID AND @szbtypeid<>'0'
	BEGIN	
		IF @szperiod='' ---取当前应付余额
		BEGIN
			--EXEC GP_CheckBTypeTotal @szBTypeID,@szSTypeID

			SELECT 	@dtotal=SUM(aptotal) 
			FROM 	BType_ARAPTotal 
			WHERE 	LEFT(btypeid,LEN(@szbtypeid))=@szbtypeid  
			AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT @dqty=0
			RETURN
		END 
		ELSE ---取期初应付余额
		BEGIN
			SELECT 	@dtotal=SUM(aptotal00) 
			FROM 	BType_ARAPTotal 
			WHERE 	LEFT(btypeid,LEN(@szbtypeid))=@szbtypeid 
			AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT @dqty=0
			RETURN
		END
	END 
	
	--预付
	IF @szatypeid=@YF_ID AND @szbtypeid<>'0'
	BEGIN	
		IF @szperiod='' ---取当前预付余额
		BEGIN
			--EXEC GP_CheckBTypeTotal @szBTypeID,@szSTypeID

			SELECT 	@dtotal=SUM(YFtotal) 
			FROM 	BType_ARAPTotal 
			WHERE 	LEFT(btypeid,LEN(@szbtypeid))=@szbtypeid  
			AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT @dqty=0
			RETURN
		END 
		ELSE ---取期初应付余额
		BEGIN
			SELECT 	@dtotal=SUM(YFTotal00) 
			FROM 	BType_ARAPTotal 
			WHERE 	LEFT(btypeid,LEN(@szbtypeid))=@szbtypeid 
			AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT @dqty=0
			RETURN
		END
	END 

	-- 查具体往来单位“应收余额” 或 期初余额
	IF @szatypeid=@AR_ID AND @szbtypeid<>'0'	
	BEGIN	
		IF @szperiod='' ---取当前应收余额
		BEGIN
			--EXEC GP_CheckBTypeTotal @szBTypeID,@szSTypeID

			SELECT 	@dtotal=SUM(artotal) 
			FROM 	BType_ARAPTotal 
			WHERE 	LEFT(btypeid,LEN(@szbtypeid))=@szbtypeid 
				AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT @dqty=0
			RETURN
		END 
		ELSE ---取期初应收余额
		BEGIN
			SELECT 	@dtotal=SUM(artotal00) 
			FROM 	BType_ARAPTotal 
			WHERE 	LEFT(btypeid,LEN(@szbtypeid))=@szbtypeid 
				AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT 	@dqty=0
			RETURN
		END
	END
	
	--预收
	IF @szatypeid=@YS_ID AND @szbtypeid<>'0'	
	BEGIN	
		IF @szperiod='' ---取当前预收余额
		BEGIN
			--EXEC GP_CheckBTypeTotal @szBTypeID,@szSTypeID

			SELECT 	@dtotal=SUM(YSTotal) 
			FROM 	BType_ARAPTotal 
			WHERE 	LEFT(btypeid,LEN(@szbtypeid))=@szbtypeid 
				AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT @dqty=0
			RETURN
		END 
		ELSE ---取期初应收余额
		BEGIN
			SELECT 	@dtotal=SUM(YSTotal00) 
			FROM 	BType_ARAPTotal 
			WHERE 	LEFT(btypeid,LEN(@szbtypeid))=@szbtypeid 
				AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT 	@dqty=0
			RETURN
		END
	END

	-- 取AType中具体科目的余额 或期初余额
	IF @szAtypeid<>'0' AND @szPtypeid='0'
	BEGIN
		IF @szperiod='' ---取当前余额
		BEGIN
			SELECT 	@dtotal=SUM(total) 
			FROM 	AType_Total 
			WHERE 	LEFT(atypeid,LEN(@szatypeid))=@szatypeid 
				AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT @dqty=0
			RETURN
		END 
		ELSE ---取期初余额
		BEGIN
			SELECT 	@dtotal=SUM(total00) 
			FROM 	AType_Total
			WHERE 	LEFT(atypeid,LEN(@szatypeid))=@szatypeid 
				AND STypeID=@szSTypeID
				
			IF 	@dtotal IS null SELECT @dtotal=0
			SELECT 	@dqty=0
			RETURN
		END
	END 
 
	-- 取具体仓库的库存余额 或 期初余额
	IF @szAtypeid='0' AND @szKtypeid<>'0'
	BEGIN
		IF @szperiod='' ---取当前某仓库库存余额
		BEGIN
			SELECT 	@dqty=(SUM(qty)),
				@dtotal=(SUM(total)) 
			FROM 	goodsstocks 
			WHERE 	LEFT(ktypeid,LEN(@szktypeid))=@szktypeid 
			IF 	@dqty IS null SELECT @dqty=0
			IF 	@dtotal IS null SELECT @dtotal=0
			RETURN
		END 
		ELSE ---取期初某仓库库存余额
		BEGIN
			SELECT 	@dqty=(SUM(qty)),
				@dtotal=(SUM(total)) 
			FROM 	inigoodsstocks 
			WHERE 	LEFT(ktypeid,LEN(@szktypeid))=@szktypeid 
			IF 	@dqty IS null SELECT @dqty=0
			IF 	@dtotal IS null SELECT @dtotal=0
			RETURN
		END
	END
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：谢吉康
	日期：2005-3-24
	描述：取期初的算法出现了问题，改
*/

CREATE     PROCEDURE Gp_GetDbf_InOutStockTable 
(	
	@szAtypeId varchar(50),		--财务科目的ID
	@szPtypeId varchar(50),		--商品的ID
	@szBtypeId varchar(50),		--往来单位的ID
	@szEtypeId varchar(50),		--经手人的ID
	@szKtypeId varchar(50),		--仓库的ID
	@szPeriod  varchar(2),		--
	@szJobNumber varchar(20),	--
	--	@OutFactoryDate datetime,
	@dQty    NUMERIC(24, 10)  output,
	@dTotal  NUMERIC(24, 10)  output
)
--@encode$--
AS
set nocount on
------Some vchtype
DECLARE	@GOODS_ID varchar(50),
	@CASH_ID  varchar(50),
	@CASH_BANK_ID varchar(50),
	@AR_ID varchar(50),
	@AP_ID varchar(50),
	@GOODS_LOSS_ID varchar(50),
	@GOODS_GET_ID varchar(50),
	@ALLOT_PRICE_ID varchar(50),
	@PRICE_INCOME_ID varchar(50),
	@BORROW_BUY_PRICE_ID varchar(50), 
	@GOODS_GIVE_ID varchar(50),       
	@GOODS_PRODUCE_ID varchar(50),    
	@SALE_COST_ID varchar(50),        
	@SALE_INCOME_ID varchar(50),      
	@LEND_GOODS_ID varchar(50),       
	@BORROW_GOODS_ID varchar(50),     
	@BALANCE_ID varchar(50),          
	@DEPRECIATION_ID varchar(50),     
	@APPORTION_EXPENSE_ID varchar(50),
	@INIT_MONEY_ID varchar(50),       
	@ALL_INCOME_ID varchar(50),       
	@ALL_EXPENSE_ID varchar(50),      
	@PROFIT_ID varchar(50),           
	@ASSETS_ID varchar(50),           
	@DEBT_ID varchar(50),             
	@POWER_ID varchar(50),
	@ADDEBT_INCOME_ID varchar(50),
	@ADDEBT_LOSE_ID varchar(50)
SELECT 	@GOODS_ID='0000100001'
SELECT 	@CASH_ID='0000100003'
SELECT 	@CASH_BANK_ID='0000100004'
SELECT 	@AR_ID='0000100005'
SELECT 	@AP_ID='0000200001'
SELECT 	@GOODS_LOSS_ID='000040000200001' --           商品报损
SELECT 	@GOODS_GET_ID='000030000200001'  --           商品报溢收入
SELECT 	@ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
SELECT 	@PRICE_INCOME_ID='000030000200003'--成本调价收入
--	SELECT @BORROW_BUY_PRICE_RECNO varchar(50)= 28;
--	SELECT @GOODS_GIVE_RECNO = 000040000200002           商品赠出
SELECT 	@GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
SELECT 	@SALE_COST_ID='0000400001'--              『销售成本』
SELECT 	@SALE_INCOME_ID='0000300001'--            『销售收入』
--	SELECT @LEND_GOODS_RECNO varchar(50),       = 21;
--	SELECT @BORROW_GOODS_RECNO varchar(50),     = 24;
SELECT 	@BALANCE_ID='000030000200004'--           进货退货差价
SELECT 	@DEPRECIATION_ID='000040000300002'--      固定资产折旧
SELECT 	@APPORTION_EXPENSE_ID='0000100007'--      待摊费用
--	SELECT @INIT_MONEY_RECNO varchar(50),       = 18;
SELECT 	@ALL_INCOME_ID='00003'	--          【收入类】
SELECT 	@ALL_EXPENSE_ID='00004'--                 【支出类】
--	SELECT @PROFIT_RECNO varchar(50),           = 19;
SELECT 	@ASSETS_ID ='00001'		--【资产合计】
SELECT 	@DEBT_ID='00002'			--【负债合计】
--	SELECT @POWER_RECNO varchar(50)            = 4;
SELECT 	@ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
SELECT 	@ADDEBT_LOSE_ID='000040000300001' --调帐亏损
------------------
DECLARE @szSql varchar(500)
--==========================获取库存的余量  谢吉康　　　2003-07-22
IF @szatypeid=@GOODS_ID AND @szptypeid<>'0'
	BEGIN	
		IF @szperiod='' ---取当前库存数量
			BEGIN			
				IF @szJobNumber<>'' 		
					BEGIN
						IF @szktypeid<>'0'	--具体仓库 
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND ktypeid=@szktypeid 
									AND JobNumber=@szJobNumber
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END 
						ELSE			--全部仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND JobNumber=@szJobNumber
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END
			
					END 
				ELSE
					BEGIN
						IF @szktypeid<>'0' 	--具体仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND ktypeid=@szktypeid
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END 
						ELSE			--全部仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END
					END
			END 
	ELSE ---取期初库存数量
		BEGIN
			IF @szktypeid<>'0'	--具体的仓库
				BEGIN
					SELECT	@dQty = SUM(B.Qty),
							@dTotal = SUM(B.Total)
					FROM	(
								SELECT 	SUM(qty) AS Qty,
										SUM(total) AS Total
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
										AND KTypeId=@szKTypeId
								UNION ALL
								SELECT 	0 AS Qty,
										0 AS Total 
								FROM 	iniCommissionStock
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
										AND KTypeId=@szKTypeId
										AND Type = 144
							)B			
					
					IF 	@dQty IS null SELECT @dQty=0
					IF 	@dtotal IS null SELECT @dtotal=0
					RETURN
				END 
			ELSE			--全部仓库
				BEGIN
					SELECT	@dQty = SUM(B.Qty),
							@dTotal = SUM(B.Total)
					FROM	(
								SELECT 	SUM(qty) AS Qty,
										SUM(total) AS Total
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid										
								UNION ALL
								SELECT 	0 AS Qty,
										0 AS Total 
								FROM 	iniCommissionStock
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid										
										AND Type = 144
							)B		

					IF 	@dQty IS null SELECT @dQty=0
					IF 	@dtotal IS null SELECT @dtotal=0
					RETURN
				END
		END
	END 
ELSE 
--==========================获取应收应付的信息  谢吉康　　　2003-07-22
	IF @szatypeid=@AP_ID AND @szbtypeid<>'0'
		BEGIN	
			IF @szperiod='' ---取当前应付余额
				BEGIN
					SELECT 	@dTotal=SUM(aptotal) 
					FROM 	btype 
					WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid  
						AND deleted=0 
						AND sonnum=0
					IF 	@dtotal IS null SELECT @dtotal=0
					SELECT @dQty=0
					RETURN
				END 
			ELSE ---取期初应付余额
				BEGIN
					SELECT 	@dTotal=SUM(aptotal00) 
					FROM 	btype 
					WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
						AND deleted=0 
						AND sonnum=0
					IF 	@dtotal IS null SELECT @dtotal=0
					SELECT @dQty=0
					RETURN
				END
		END 
	ELSE 
		IF @szatypeid=@AR_ID AND @szbtypeid<>'0'	
			BEGIN	
				IF @szperiod='' ---取当前应收余额
					BEGIN
						SELECT 	@dTotal=SUM(artotal) 
						FROM 	btype 
						WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
							AND deleted=0 
							AND sonnum=0
						IF 	@dtotal IS null SELECT @dtotal=0
						SELECT @dQty=0
						RETURN
					END 
				ELSE ---取期初应收余额
					BEGIN
						SELECT 	@dTotal=SUM(artotal00) 
						FROM 	btype 
						WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
							AND deleted=0 
							AND sonnum=0
						IF 	@dtotal IS null SELECT @dtotal=0
						SELECT 	@dQty=0
						RETURN
					END
			END 
		ELSE 
			IF @szAtypeid<>'0' AND @szPtypeid='0'
				BEGIN
					IF @szperiod='' ---取当前余额
						BEGIN
							SELECT 	@dTotal=SUM(total) 
							FROM 	atype 
							WHERE 	LEFT(typeid,LEN(@szatypeid))=@szatypeid 
								AND deleted=0 
								AND sonnum=0
							IF 	@dtotal IS null SELECT @dtotal=0
							SELECT @dQty=0
							RETURN
						END 
					ELSE ---取期初余额
						BEGIN
							SELECT 	@dTotal=SUM(total00) 
							FROM 	atype
							WHERE 	LEFT(typeid,LEN(@szatypeid))=@szatypeid 
								AND deleted=0 
								AND sonnum=0
							IF 	@dtotal IS null SELECT @dtotal=0
							SELECT 	@dQty=0
							RETURN
						END
				END 
			ELSE 
				IF @szAtypeid='0' AND @szKtypeid<>'0'
					BEGIN
						IF @szperiod='' ---取当前某仓库库存余额
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ktypeid,LEN(@szktypeid))=@szktypeid 
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dTotal IS null SELECT @dTotal=0
								RETURN
							END 
						ELSE ---取期初某仓库库存余额
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ktypeid,LEN(@szktypeid))=@szktypeid 
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dTotal IS null SELECT @dTotal=0
								RETURN
							END
					END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：谢吉康
	日期：2005-3-24
	描述：取期初的算法出现了问题，改
*/

CREATE     PROCEDURE Gp_GetDbf_Stock 
(		
	@OperatorId				varchar(50),		--操作员Id
	@szAtypeId 				varchar(50),		--财务科目的ID
	@szPtypeId 				varchar(50),		--商品的ID
	@szBtypeId 				varchar(50),		--往来单位的ID
	@szEtypeId 				varchar(50),		--经手人的ID
	@szKtypeId 				varchar(50),		--仓库的ID
	@szPeriod  				varchar(2),		--
	@szJobNumber 			varchar(20),	--
	--	@OutFactoryDate datetime,
	@dQty    NUMERIC(24, 10)  	output,
	@dTotal  NUMERIC(24, 10)  	output
)
--@encode$--
AS
set nocount on

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

------Some vchtype
DECLARE	@GOODS_ID varchar(50),
	@CASH_ID  varchar(50),
	@CASH_BANK_ID varchar(50),
	@AR_ID varchar(50),
	@AP_ID varchar(50),
	@GOODS_LOSS_ID varchar(50),
	@GOODS_GET_ID varchar(50),
	@ALLOT_PRICE_ID varchar(50),
	@PRICE_INCOME_ID varchar(50),
	@BORROW_BUY_PRICE_ID varchar(50), 
	@GOODS_GIVE_ID varchar(50),       
	@GOODS_PRODUCE_ID varchar(50),    
	@SALE_COST_ID varchar(50),        
	@SALE_INCOME_ID varchar(50),      
	@LEND_GOODS_ID varchar(50),       
	@BORROW_GOODS_ID varchar(50),     
	@BALANCE_ID varchar(50),          
	@DEPRECIATION_ID varchar(50),     
	@APPORTION_EXPENSE_ID varchar(50),
	@INIT_MONEY_ID varchar(50),       
	@ALL_INCOME_ID varchar(50),       
	@ALL_EXPENSE_ID varchar(50),      
	@PROFIT_ID varchar(50),           
	@ASSETS_ID varchar(50),           
	@DEBT_ID varchar(50),             
	@POWER_ID varchar(50),
	@ADDEBT_INCOME_ID varchar(50),
	@ADDEBT_LOSE_ID varchar(50)
SELECT 	@GOODS_ID='0000100001'
SELECT 	@CASH_ID='0000100003'
SELECT 	@CASH_BANK_ID='0000100004'
SELECT 	@AR_ID='0000100005'
SELECT 	@AP_ID='0000200001'
SELECT 	@GOODS_LOSS_ID='000040000200001' --           商品报损
SELECT 	@GOODS_GET_ID='000030000200001'  --           商品报溢收入
SELECT 	@ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
SELECT 	@PRICE_INCOME_ID='000030000200003'--成本调价收入
--	SELECT @BORROW_BUY_PRICE_RECNO varchar(50)= 28;
--	SELECT @GOODS_GIVE_RECNO = 000040000200002           商品赠出
SELECT 	@GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
SELECT 	@SALE_COST_ID='0000400001'--              『销售成本』
SELECT 	@SALE_INCOME_ID='0000300001'--            『销售收入』
--	SELECT @LEND_GOODS_RECNO varchar(50),       = 21;
--	SELECT @BORROW_GOODS_RECNO varchar(50),     = 24;
SELECT 	@BALANCE_ID='000030000200004'--           进货退货差价
SELECT 	@DEPRECIATION_ID='000040000300002'--      固定资产折旧
SELECT 	@APPORTION_EXPENSE_ID='0000100007'--      待摊费用
--	SELECT @INIT_MONEY_RECNO varchar(50),       = 18;
SELECT 	@ALL_INCOME_ID='00003'	--          【收入类】
SELECT 	@ALL_EXPENSE_ID='00004'--                 【支出类】
--	SELECT @PROFIT_RECNO varchar(50),           = 19;
SELECT 	@ASSETS_ID ='00001'		--【资产合计】
SELECT 	@DEBT_ID='00002'			--【负债合计】
--	SELECT @POWER_RECNO varchar(50)            = 4;
SELECT 	@ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
SELECT 	@ADDEBT_LOSE_ID='000040000300001' --调帐亏损
------------------
DECLARE @szSql varchar(500)
--==========================获取库存的余量  谢吉康　　　2003-07-22
IF @szatypeid=@GOODS_ID AND @szptypeid<>'0'
	BEGIN	
		IF @szperiod='' ---取当前库存数量
			BEGIN			
				IF @szJobNumber<>'' 		
					BEGIN
						IF @szktypeid<>'0'	--具体仓库 
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
										@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
										AND ktypeid=@szktypeid 
										AND JobNumber=@szJobNumber
										AND KTypeId LIKE @MKTypeId + '%'
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END 
						ELSE			--全部仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
										@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
										AND JobNumber=@szJobNumber
										AND KTypeId LIKE @MKTypeId + '%'
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END
			
					END 
				ELSE
					BEGIN
						IF @szktypeid<>'0' 	--具体仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
										@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
										AND ktypeid=@szktypeid
										AND KTypeId LIKE @MKTypeId + '%'
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END 
						ELSE			--全部仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
										@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
										AND KTypeId LIKE @MKTypeId + '%'
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END
					END
			END 
	ELSE ---取期初库存数量
		BEGIN
			IF @szktypeid<>'0'	--具体的仓库
				BEGIN
					SELECT	@dQty = SUM(B.Qty),
							@dTotal = SUM(B.Total)
					FROM	(
								SELECT 	SUM(qty) AS Qty,
										SUM(total) AS Total
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
										AND KTypeId=@szKTypeId
										AND KTypeId LIKE @MKTypeId + '%'
							)B			
					
					IF 	@dQty IS null SELECT @dQty=0
					IF 	@dtotal IS null SELECT @dtotal=0
					RETURN
				END 
			ELSE			--全部仓库
				BEGIN
					SELECT	@dQty = SUM(B.Qty),
							@dTotal = SUM(B.Total)
					FROM	(
								SELECT 	SUM(qty) AS Qty,
										SUM(total) AS Total
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid	
										AND KTypeId LIKE @MKTypeId + '%'									
							)B		

					IF 	@dQty IS null SELECT @dQty=0
					IF 	@dtotal IS null SELECT @dtotal=0
					RETURN
				END
		END
	END 
ELSE 
--==========================获取应收应付的信息  谢吉康　　　2003-07-22
	IF @szatypeid=@AP_ID AND @szbtypeid<>'0'
		BEGIN	
			IF @szperiod='' ---取当前应付余额
				BEGIN
					SELECT 	@dTotal=SUM(aptotal) 
					FROM 	btype 
					WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid  
						AND deleted=0 
						AND sonnum=0
					IF 	@dtotal IS null SELECT @dtotal=0
					SELECT @dQty=0
					RETURN
				END 
			ELSE ---取期初应付余额
				BEGIN
					SELECT 	@dTotal=SUM(aptotal00) 
					FROM 	btype 
					WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
						AND deleted=0 
						AND sonnum=0
					IF 	@dtotal IS null SELECT @dtotal=0
					SELECT @dQty=0
					RETURN
				END
		END 
	ELSE 
		IF @szatypeid=@AR_ID AND @szbtypeid<>'0'	
			BEGIN	
				IF @szperiod='' ---取当前应收余额
					BEGIN
						SELECT 	@dTotal=SUM(artotal) 
						FROM 	btype 
						WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
							AND deleted=0 
							AND sonnum=0
						IF 	@dtotal IS null SELECT @dtotal=0
						SELECT @dQty=0
						RETURN
					END 
				ELSE ---取期初应收余额
					BEGIN
						SELECT 	@dTotal=SUM(artotal00) 
						FROM 	btype 
						WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
							AND deleted=0 
							AND sonnum=0
						IF 	@dtotal IS null SELECT @dtotal=0
						SELECT 	@dQty=0
						RETURN
					END
			END 
		ELSE 
			IF @szAtypeid<>'0' AND @szPtypeid='0'
				BEGIN
					IF @szperiod='' ---取当前余额
						BEGIN
							SELECT 	@dTotal=SUM(total) 
							FROM 	atype 
							WHERE 	LEFT(typeid,LEN(@szatypeid))=@szatypeid 
								AND deleted=0 
								AND sonnum=0


							IF 	@dtotal IS null SELECT @dtotal=0
							SELECT @dQty=0
							RETURN
						END 
					ELSE ---取期初余额
						BEGIN
							SELECT 	@dTotal=SUM(total00) 
							FROM 	atype
							WHERE 	LEFT(typeid,LEN(@szatypeid))=@szatypeid 
								AND deleted=0 
								AND sonnum=0
							IF 	@dtotal IS null SELECT @dtotal=0
							SELECT 	@dQty=0
							RETURN
						END
				END 
			ELSE 
				IF @szAtypeid='0' AND @szKtypeid<>'0'
					BEGIN
						IF @szperiod='' ---取当前某仓库库存余额
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ktypeid,LEN(@szktypeid))=@szktypeid 
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dTotal IS null SELECT @dTotal=0
								RETURN
							END 
						ELSE ---取期初某仓库库存余额
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ktypeid,LEN(@szktypeid))=@szktypeid 
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dTotal IS null SELECT @dTotal=0
								RETURN
							END
					END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：谢吉康
	日期：2005-3-24
	描述：取期初的算法出现了问题，改
*/

CREATE     PROCEDURE Gp_GetDbf1 
(	
	@szAtypeId varchar(50),		--财务科目的ID
	@szPtypeId varchar(50),		--商品的ID
	@szBtypeId varchar(50),		--往来单位的ID
	@szEtypeId varchar(50),		--经手人的ID
	@szKtypeId varchar(50),		--仓库的ID
	@szPeriod  varchar(2),		--
	@szJobNumber varchar(20),	--
	--	@OutFactoryDate datetime,
	@dQty    NUMERIC(24, 10)  output,
	@dTotal  NUMERIC(24, 10)  output
)
--@encode$--
AS
set nocount on
------Some vchtype
DECLARE	@GOODS_ID varchar(50),
	@CASH_ID  varchar(50),
	@CASH_BANK_ID varchar(50),
	@AR_ID varchar(50),
	@AP_ID varchar(50),
	@GOODS_LOSS_ID varchar(50),
	@GOODS_GET_ID varchar(50),
	@ALLOT_PRICE_ID varchar(50),
	@PRICE_INCOME_ID varchar(50),
	@BORROW_BUY_PRICE_ID varchar(50), 
	@GOODS_GIVE_ID varchar(50),       
	@GOODS_PRODUCE_ID varchar(50),    
	@SALE_COST_ID varchar(50),        
	@SALE_INCOME_ID varchar(50),      
	@LEND_GOODS_ID varchar(50),       
	@BORROW_GOODS_ID varchar(50),     
	@BALANCE_ID varchar(50),          
	@DEPRECIATION_ID varchar(50),     
	@APPORTION_EXPENSE_ID varchar(50),
	@INIT_MONEY_ID varchar(50),       
	@ALL_INCOME_ID varchar(50),       
	@ALL_EXPENSE_ID varchar(50),      
	@PROFIT_ID varchar(50),           
	@ASSETS_ID varchar(50),           
	@DEBT_ID varchar(50),             
	@POWER_ID varchar(50),
	@ADDEBT_INCOME_ID varchar(50),
	@ADDEBT_LOSE_ID varchar(50)
SELECT 	@GOODS_ID='0000100001'
SELECT 	@CASH_ID='0000100003'
SELECT 	@CASH_BANK_ID='0000100004'
SELECT 	@AR_ID='0000100005'
SELECT 	@AP_ID='0000200001'
SELECT 	@GOODS_LOSS_ID='000040000200001' --           商品报损
SELECT 	@GOODS_GET_ID='000030000200001'  --           商品报溢收入
SELECT 	@ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
SELECT 	@PRICE_INCOME_ID='000030000200003'--成本调价收入
--	SELECT @BORROW_BUY_PRICE_RECNO varchar(50)= 28;
--	SELECT @GOODS_GIVE_RECNO = 000040000200002           商品赠出
SELECT 	@GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
SELECT 	@SALE_COST_ID='0000400001'--              『销售成本』
SELECT 	@SALE_INCOME_ID='0000300001'--            『销售收入』
--	SELECT @LEND_GOODS_RECNO varchar(50),       = 21;
--	SELECT @BORROW_GOODS_RECNO varchar(50),     = 24;
SELECT 	@BALANCE_ID='000030000200004'--           进货退货差价
SELECT 	@DEPRECIATION_ID='000040000300002'--      固定资产折旧
SELECT 	@APPORTION_EXPENSE_ID='0000100007'--      待摊费用
--	SELECT @INIT_MONEY_RECNO varchar(50),       = 18;
SELECT 	@ALL_INCOME_ID='00003'	--          【收入类】
SELECT 	@ALL_EXPENSE_ID='00004'--                 【支出类】
--	SELECT @PROFIT_RECNO varchar(50),           = 19;
SELECT 	@ASSETS_ID ='00001'		--【资产合计】
SELECT 	@DEBT_ID='00002'			--【负债合计】
--	SELECT @POWER_RECNO varchar(50)            = 4;
SELECT 	@ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
SELECT 	@ADDEBT_LOSE_ID='000040000300001' --调帐亏损
------------------
DECLARE @szSql varchar(500)
--==========================获取库存的余量  谢吉康　　　2003-07-22
IF @szatypeid=@GOODS_ID AND @szptypeid<>'0'
	BEGIN	
		IF @szperiod='' ---取当前库存数量
			BEGIN			
				IF @szJobNumber<>'' 		
					BEGIN
						IF @szktypeid<>'0'	--具体仓库 
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND ktypeid=@szktypeid 
									AND JobNumber=@szJobNumber
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END 
						ELSE			--全部仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND JobNumber=@szJobNumber
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END
			
					END 
				ELSE
					BEGIN
						IF @szktypeid<>'0' 	--具体仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid 
									AND ktypeid=@szktypeid
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END 
						ELSE			--全部仓库
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dtotal IS null SELECT @dtotal=0
								RETURN 0
							END
					END
			END 
	ELSE ---取期初库存数量
		BEGIN
			IF @szktypeid<>'0'	--具体的仓库
				BEGIN
					SELECT	@dQty = SUM(B.Qty),
							@dTotal = SUM(B.Total)
					FROM	(
								SELECT 	SUM(qty) AS Qty,
										SUM(total) AS Total
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
										AND KTypeId=@szKTypeId
								UNION ALL
								SELECT 	SUM(qty) AS Qty,
										SUM(CostTotal) AS Total 
								FROM 	iniCommissionStock
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
										AND KTypeId=@szKTypeId
										AND Type = 144
							)B			
					
					IF 	@dQty IS null SELECT @dQty=0
					IF 	@dtotal IS null SELECT @dtotal=0
					RETURN
				END 
			ELSE			--全部仓库
				BEGIN
					SELECT	@dQty = SUM(B.Qty),
							@dTotal = SUM(B.Total)
					FROM	(
								SELECT 	SUM(qty) AS Qty,
										SUM(total) AS Total
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid										
								UNION ALL
								SELECT 	SUM(qty) AS Qty,
										SUM(CostTotal) AS Total 
								FROM 	iniCommissionStock
								WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid										
										AND Type = 144
							)B		

					IF 	@dQty IS null SELECT @dQty=0
					IF 	@dtotal IS null SELECT @dtotal=0
					RETURN
				END
		END
	END 
ELSE 
--==========================获取应收应付的信息  谢吉康　　　2003-07-22
	IF @szatypeid=@AP_ID AND @szbtypeid<>'0'
		BEGIN	
			IF @szperiod='' ---取当前应付余额
				BEGIN
					SELECT 	@dTotal=SUM(aptotal) 
					FROM 	btype 
					WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid  
						AND deleted=0 
						AND sonnum=0
					IF 	@dtotal IS null SELECT @dtotal=0
					SELECT @dQty=0
					RETURN
				END 
			ELSE ---取期初应付余额
				BEGIN
					SELECT 	@dTotal=SUM(aptotal00) 
					FROM 	btype 
					WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
						AND deleted=0 
						AND sonnum=0
					IF 	@dtotal IS null SELECT @dtotal=0
					SELECT @dQty=0
					RETURN
				END
		END 
	ELSE 
		IF @szatypeid=@AR_ID AND @szbtypeid<>'0'	
			BEGIN	
				IF @szperiod='' ---取当前应收余额
					BEGIN
						SELECT 	@dTotal=SUM(artotal) 
						FROM 	btype 
						WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
							AND deleted=0 
							AND sonnum=0
						IF 	@dtotal IS null SELECT @dtotal=0
						SELECT @dQty=0
						RETURN
					END 
				ELSE ---取期初应收余额
					BEGIN
						SELECT 	@dTotal=SUM(artotal00) 
						FROM 	btype 
						WHERE 	LEFT(typeid,LEN(@szbtypeid))=@szbtypeid 
							AND deleted=0 
							AND sonnum=0
						IF 	@dtotal IS null SELECT @dtotal=0
						SELECT 	@dQty=0
						RETURN
					END
			END 
		ELSE 
			IF @szAtypeid<>'0' AND @szPtypeid='0'
				BEGIN
					IF @szperiod='' ---取当前余额
						BEGIN
							SELECT 	@dTotal=SUM(total) 
							FROM 	atype 
							WHERE 	LEFT(typeid,LEN(@szatypeid))=@szatypeid 
								AND deleted=0 
								AND sonnum=0
							IF 	@dtotal IS null SELECT @dtotal=0
							SELECT @dQty=0
							RETURN
						END 
					ELSE ---取期初余额
						BEGIN
							SELECT 	@dTotal=SUM(total00) 
							FROM 	atype
							WHERE 	LEFT(typeid,LEN(@szatypeid))=@szatypeid 
								AND deleted=0 
								AND sonnum=0
							IF 	@dtotal IS null SELECT @dtotal=0
							SELECT 	@dQty=0
							RETURN
						END
				END 
			ELSE 
				IF @szAtypeid='0' AND @szKtypeid<>'0'
					BEGIN
						IF @szperiod='' ---取当前某仓库库存余额
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	goodsstocks 
								WHERE 	LEFT(ktypeid,LEN(@szktypeid))=@szktypeid 
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dTotal IS null SELECT @dTotal=0
								RETURN
							END 
						ELSE ---取期初某仓库库存余额
							BEGIN
								SELECT 	@dQty=(SUM(qty)),
									@dTotal=(SUM(total)) 
								FROM 	inigoodsstocks 
								WHERE 	LEFT(ktypeid,LEN(@szktypeid))=@szktypeid 
								IF 	@dQty IS null SELECT @dQty=0
								IF 	@dTotal IS null SELECT @dTotal=0
								RETURN
							END
					END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	获取小数位数
	作    者：	施训果
	修改时间：
*/
CREATE             PROCEDURE Gp_GetDigit(
	@digitType		INT -- 1：数量（Qty）2：单价(Price) 3：金额(Total) 4：扣率(Discount) 5：税率(Tax) 6：汇率(ExchangeRate) 7：百分比(ExchangeRate) 8：换算率(TranslateRate)
)
--@encode$--
AS
	SET NOCOUNT ON
	
	-- 获取小数位数
	DECLARE @digit int
	SELECT	@digit = DecimalDigit
	FROM	dbo.DigitConfiguration
	WHERE	ItemId=@digitType

	RETURN @digit	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：  毛欣蓉
--日期： 2015-11-03 
--描述：获取自定义数据
--

-------------------------------------------------------------------------
CREATE   PROCEDURE Gp_GetDiyDateConfig
(
	@billtype INT,
	@InOut	VARCHAR(10),
	@ifindex	INT,
	@ifstype		INT
)
--@encode$--
AS
SET NOCOUNT ON
	--DECLARE @isinvoice INT
	--SELECT @isinvoice=SubValue FROM dbo.sysdata WHERE SubName='isinvoice'
	IF @ifindex=1
	BEGIN
		 SELECT 0 AS isdisplay,a.id AS CustomColumnId,0 AS CustomDisColumnId,ISNULL(b.Label,a.Comment) AS Label,a.Comment AS sysdiyname,ISNULL(b.IsVisible,0) AS IsVisible,ISNULL(b.IsRequired,0) AS  IsRequired,'' AS baseinfocolumn
		 FROM Custom_Column a
		 LEFT JOIN Custom_Column_BillIndex b ON b.CustomColumnId=a.id   AND  b.BillType=@billtype   -- AND (@isinvoice=1 OR b.BillType NOT IN(400,401,402,403,404))
		 WHERE (@ifstype=1 OR a.ColumnType<>8)
		 UNION ALL
		 SELECT  1 AS isdisplay,a.id AS CustomColumnId, b.CustomDisColumnId AS CustomDisColumnId,ISNULL(b.Label,a.Comment) AS Label,a.Comment AS sysdiyname,ISNULL(b.IsVisible,0) AS IsVisible,0 AS  IsRequired,c.Comment AS baseinfocolumn
		 FROM Custom_DisplayColumnOrder a
		 LEFT JOIN Custom_DisplayColumn_BillIndex b ON a.id=b.orderid	AND  b.BillType=@billtype  -- AND (@isinvoice=1 OR b.BillType NOT IN(400,401,402,403,404))
		 LEFT JOIN
		 ( 
			SELECT * FROM  Custom_DisplayColumn  WHERE ( @billtype<>305  OR  BaseInfo NOT IN('employee','stype','btype','Stock','dbtype'))
		 )
		 c  ON b.CustomDisColumnId=c.id						    
		 WHERE (@ifstype=1 OR a.id NOT IN(17,18))
		 AND ( @billtype<>305  OR  a.id  IN(4,5,6))
	 END
	 ELSE
	 BEGIN
		--增加组合品313,12,46,零售单305
		IF @billtype IN(160,161,16,166,172,313,12,46,305)
		BEGIN
			 SELECT 0 AS isdisplay,a.id AS CustomColumnId,0 AS CustomDisColumnId,ISNULL(b.Label,a.Comment) AS Label,a.Comment AS sysdiyname,ISNULL(b.IsVisible,0) AS IsVisible,ISNULL(b.IsRequired,0) AS  IsRequired,'' AS baseinfocolumn ,@InOut AS InOut
			 FROM Custom_Column a
			 LEFT JOIN Custom_Column_BillDetail b ON b.CustomColumnId=a.id   AND  b.BillType=@billtype	AND b.InOut=@InOut	   --  AND (@isinvoice=1 OR b.BillType NOT IN(400,401,402,403,404))
			 WHERE (@ifstype=1 OR a.ColumnType<>8)
			-- AND (@isinvoice=1 OR b.BillType NOT IN(400,401,402,403,404))
		END
		ELSE
		BEGIN
			 SELECT 0 AS isdisplay,a.id AS CustomColumnId,0 AS CustomDisColumnId,ISNULL(b.Label,a.Comment) AS Label,a.Comment AS sysdiyname,ISNULL(b.IsVisible,0) AS IsVisible,ISNULL(b.IsRequired,0) AS  IsRequired,'' AS baseinfocolumn ,@InOut AS InOut
			 FROM Custom_Column a
			 LEFT JOIN Custom_Column_BillDetail b ON b.CustomColumnId=a.id   AND  b.BillType=@billtype	  -- AND (@isinvoice=1 OR b.BillType NOT IN(400,401,402,403,404))
			 WHERE (@ifstype=1 OR a.ColumnType<>8)	
			--  AND (@isinvoice=1 OR b.BillType NOT IN(400,401,402,403,404))
		END
		 
	 END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：
--日期： 2015-10-20 
--描述：
--

-------------------------------------------------------------------------
CREATE   PROCEDURE Gp_GetDiyDisplayInfo
(
	@type VARCHAR(50),
	@ifstype INT
)
--@encode$--
AS
SET NOCOUNT ON
	 
	  SELECT id AS customdiscolumnid,DataField, Comment AS baseinfocolumn, BaseInfo
	  FROM  Custom_DisplayColumn
	  WHERE BaseInfo=@type
	  AND (@ifstype=1 OR DataField NOT IN('de_sfullname','dst_sfullname')  )
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：
--日期： 2015-10-20 
--描述：
--

-------------------------------------------------------------------------
CREATE   PROCEDURE Gp_GetDiyInfoTreeSource

--@encode$--
AS
SET NOCOUNT ON
	CREATE TABLE #result
	(
		id INT IDENTITY(1,1),
		parid varchar(10),
		BaseInfo  varchar(50),
		NAME varchar(50)
	) 
	  INSERT INTO #result
	  SELECT '0', '','基本信息'
	  UNION ALL
	  SELECT DISTINCT '1',BaseInfo, 
		  CASE  WHEN BaseInfo='employee'	THEN '职员'
				WHEN BaseInfo='btype' THEN '往来单位'
				WHEN BaseInfo='dbtype' THEN '结算单位'
				WHEN BaseInfo='Department'    THEN '部门'
				WHEN BaseInfo='Stock'   THEN '仓库'
				WHEN BaseInfo='stype'   THEN '分支机构'
			END 
	  FROM Custom_DisplayColumn
	
	 
	 SELECT * FROM #result
	 
	 DROP TABLE #result
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_GetEntryCodeRepeat]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_GetEntryCodeRepeat
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2015-11-02
-- Description: 商品条码重复检查
-- =============================================
CREATE PROCEDURE Gp_GetEntryCodeRepeat
(
	@typeid	VARCHAR(50),
	@EntryCodes VARCHAR(max)  --
)
AS
BEGIN
	
	SET NOCOUNT ON
	
	DECLARE @result VARCHAR(max) =''
	
	SELECT @result=@result+'商品条码【'+entrycode+'】重复，该条码已重复'+CAST(pnum AS VARCHAR(50))+'条 
	 ' 
	FROM(
	  SELECT COUNT(entrycode) AS pnum,entrycode,flag
	  FROM (
	  SELECT  entrycode,1 AS flag FROM  dbo.ptype WHERE EntryCode IN (SELECT a FROM dbo.f_split(@EntryCodes,',') WHERE a<>'' )  And typeid <>   @typeid	  
	  UNION ALL
	  SELECT entrycode,2 AS flag FROM  dbo.PType_Units_Ext WHERE EntryCode IN (SELECT a FROM dbo.f_split(@EntryCodes,',') WHERE a<>'')    And ptypeid <>   @typeid
	  )a
	  GROUP BY entrycode,flag
	  HAVING(COUNT(	entrycode)>0)
	  )a
	SELECT @result AS result
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROCEDURE Gp_GetFactPreDateQty
(
	@OperatorID	varchar(200),
	@StartDate	varchar(20),
	@PTypeId	varchar(200),
	@KTypeId	varchar(8000),
	@etypeid	VARCHAR(8000)='',--注意：如果etypeid=''表示没有受职员权限范围控制，如果全部请为00001
	@stypeid	VARCHAR(8000)=''
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid <> '-99999'
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE TypeId IN (SELECT * FROM F_GetAllBaseTypeId(@KTypeId,4))
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailKType(@OperatorID)) AND TypeId IN (SELECT * FROM F_GetAllBaseTypeId(@KTypeId,4))

IF @etypeid IS NULL  SELECT @etypeid=''

IF @PTypeId = '00000'
	SET @PTypeId = '%'

DECLARE @TypeId 	varchar(100)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @etypeid<>'' 
	INSERT INTO #GetManETypeId(TypeId) SELECT e.typeid FROM F_GetManDetailEType(@OperatorID) e  INNER JOIN F_GetAllBaseTypeId(@etypeid,3) fe ON e.TypeId = fe.TypeId

--分支机构
CREATE TABLE #GetManSTypeid(TYpeid VARCHAR(100))
INSERT INTO #GetManSTypeid(TYpeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DELETE FROM #GetManKTypeId WHERE TypeId NOT IN( SELECT TypeId FROM stock WHERE STypeID IN(SELECT TypeId FROM #GetManSTypeid)) --删除分支机构以外的仓库

CREATE TABLE #PType
(
	TypeId		VARCHAR(50)
)
INSERT INTO #PType SELECT TypeId FROM F_GetManDetailPType(@OperatorID)

DECLARE  @SQL VARCHAR(8000)

--计算数据
SET @SQL='
			SELECT 	ISNULL(SUM(B.Qty),0) AS Qty
			FROM	( 
						SELECT 	ISNULL(SUM(a.qty),0) AS Qty
						FROM 	Fact_InOutstocktable a,
						        FactIndex bil  , 
								#PType p,
								#GetManKTypeId K
						WHERE 	a.PtypeId = p.TypeId
						        and a.billnumberid=bil.billnumberid
						       
								AND a.KTypeId = K.TypeId
								AND a.BillDate<'+CHAR(39)+@StartDate+CHAR(39)+'
								AND a.KTypeID<>''10000'' 
								AND a.PTypeID LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)
if @etypeid<>''
	SET @SQL=@SQL+' AND a.EtypeId IN(SELECT typeid FROM #GetManETypeId) '

SET @SQL=@SQL+'
						UNION ALL 
						SELECT 	ISNULL(SUM(a.Qty),0) AS Qty
						FROM 	IniFactStocks a,
								#PType p,
								#GetManKTypeId K
						WHERE 	a.KTypeId = K.TypeId
								AND a.PTypeId = P.TypeId
								AND PTypeID LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)+'  
								AND a.KTypeID<>''10000''
								AND a.KTypeID LIKE ''%'' '

SET @SQL=@SQL+'	) B '

--print(@SQL)
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#PType,#GetManETypeId,#GetManSTypeid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetFactStocksQtyOrTotal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_GetFactStocksQtyOrTotal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	实物库存商品库存
-- 时间：	2017-06-28
-- 作者：	古丽娟
-- ========================================================================
CREATE PROCEDURE Gp_GetFactStocksQtyOrTotal
(	
	@PtypeCategoryid	VARCHAR(50)='',
	@PTypeId			VARCHAR(50)='',--商品ID 
	@StartDate			VARCHAR(20)='',--查询时间
	@KTypeId			VARCHAR(MAX)='',--仓库
	@ETypeId			VARCHAR(MAX)='',--经手人
	@STypeId			VARCHAR(MAX)='',--分支机构
	@OperatorID			VARCHAR(50)=''--操作员
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品
CREATE TABLE #PType(TypeId VARCHAR(50))
INSERT INTO #PType(TypeId) 
SELECT TypeId FROM dbo.F_ManPTypeInCategoryID(@OperatorID,@PtypeId,@PtypeCategoryid) F

--仓库
CREATE TABLE #STock(STypeId VARCHAR(50),TypeId VARCHAR(50),FullName VARCHAR(200))
INSERT INTO #STock(STypeId,TypeId,FullName) 
SELECT S.STypeID,F.TypeId,FullName FROM Stock S INNER JOIN F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorId) F ON F.TypeId=S.typeId

--经手人
CREATE TABLE #Etype(TypeId VARCHAR(50),FullName VARCHAR(200))
INSERT INTO #Etype(TypeId,FullName) 
SELECT F.TypeId,FullName FROM employee S INNER JOIN F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorId) F ON F.TypeId=S.typeId

--分支机构
CREATE TABLE #SType(TypeId VARCHAR(50),FullName VARCHAR(200))
INSERT INTO #SType(TypeId,FullName) 
SELECT F.TypeId,FullName FROM SType S INNER JOIN F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorId) F ON F.TypeId=S.typeId

--418	仓库入库单
--419	仓库出库单
--420	仓库调拨单
SELECT
	p.TypeId PTypeId,
	SUM(ISNULL(sumResult.Qty,0)) IniQty
FROM #PType P
LEFT JOIN 
(
	SELECT
		P.TypeId,
		SUM(CASE WHEN I.BillType=418 THEN O.qty ELSE -O.qty END) Qty
	FROM FactIndex I
	INNER JOIN FactDepotInOut O ON O.BillNumberID=I.BillNumberId AND I.BillDate<@StartDate AND I.ifcheck='t' AND I.RedWord=0
	INNER JOIN #PType P ON P.TypeId=O.PtypeId 
	INNER JOIN #STock ST ON ST.TypeId=O.ktypeid
	INNER JOIN #Etype E ON E.TypeId=I.etypeid
	INNER JOIN #SType S ON S.TypeId=I.STypeId
	WHERE 
		I.BillType IN(418,419)
	GROUP BY P.TypeId
		
	UNION ALL--------------仓库挑拨单   出库

	SELECT
		P.TypeId,
		-SUM(O.qty) Qty
	FROM FactIndex I
	INNER JOIN FactDepotAllot O ON O.BillNumberID=I.BillNumberId AND I.BillDate<@StartDate AND I.ifcheck='t' AND I.RedWord=0
	INNER JOIN #PType P ON P.TypeId=O.PtypeId 
	INNER JOIN #STock ST ON ST.TypeId=O.ktypeid
	INNER JOIN #Etype E ON E.TypeId=I.etypeid
	INNER JOIN #SType S ON S.TypeId=I.Stypeid
	WHERE 
		I.BillType=420
	GROUP BY P.TypeId

	UNION ALL--------------仓库挑拨单   入库

	SELECT
		P.TypeId,
		SUM(O.qty) Qty
	FROM FactIndex I
	INNER JOIN FactDepotAllot O ON O.BillNumberID=I.BillNumberId AND I.BillDate<@StartDate AND I.ifcheck='t' AND I.RedWord=0
	INNER JOIN #PType P ON P.TypeId=O.PtypeId 
	INNER JOIN #STock ST ON ST.TypeId=O.ktypeid2
	INNER JOIN #Etype E ON E.TypeId=I.etypeid
	INNER JOIN #SType S ON S.TypeId=I.Stypeid
	WHERE 
		I.BillType=420
	GROUP BY P.TypeId
		
	UNION ALL --期初

	SELECT
		P.TypeId,
		SUM(Qty) Qty
	FROM IniFactStocks I
	INNER JOIN #PType P ON P.TypeId=I.PtypeId
	INNER JOIN #STock ST ON ST.TypeId=I.KtypeId
	INNER JOIN #SType S ON S.TypeId=ST.Stypeid
	GROUP BY P.TypeId
) sumResult ON  sumResult.TypeId=P.TypeId
GROUP BY P.TypeId


-----------------------------------删除临时表============================
DROP TABLE #SType,#PType,#Etype,#STock



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王珏
	日期：2014-11-14
	描述：获取商品的默认仓库
*/
CREATE  PROCEDURE GP_GetGoodsDefaultStock
( 
	@stypeid		VARCHAR(50),
	@ptypeid		VARCHAR(50),
	@OperatorID		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数

DECLARE @chvMKTypeID varchar(50)

IF @OperatorID = '00001' --超级管理员
	SET @chvMKTypeID = '00000'
ELSE	
	SELECT 	@chvMKTypeID=MangerKTypeID FROM LoginUser(NOLOCK) WHERE ETypeId=@OperatorID

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@OperatorID)

	SELECT a.ktypeid,b.FullName AS kfullname,c.cargoid,c.fullname AS cargofullname 
	FROM DefaultStock a 
	INNER JOIN ptype p ON a.Ptypeid = p.typeId
	INNER JOIN Stock b ON a.ktypeid = b.typeId 
	INNER JOIN CargoType c ON b.typeId = c.KtypeID
	INNER JOIN #F_BaseGetManDetailKType K ON a.ktypeid = K.TypeID  
	WHERE b.deleted = 0 AND c.IsDefault = 1 AND p.deleted = 0 AND a.stypeid = @stypeid AND a.ptypeid = @ptypeid
END	
ELSE 
	SELECT a.ktypeid,b.FullName AS kfullname,c.cargoid,c.fullname AS cargofullname 
	FROM DefaultStock a 
	INNER JOIN ptype p ON a.Ptypeid = p.typeId
	INNER JOIN Stock b ON a.ktypeid = b.typeId 
	INNER JOIN CargoType c ON b.typeId = c.KtypeID
	WHERE b.deleted = 0 AND c.IsDefault = 1 AND p.deleted = 0 AND a.stypeid = @stypeid AND a.ptypeid = @ptypeid
                                
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO                              



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：
--日期： 2015-04-26 
--描述：报警簿红色提示功能
--
/*
upstockhit 库存上限
downstockhit 库存下限
gatheringhit 超期应收
payhit --超期应付
buyOrderhit  采购订单
saleOrderhit 销售订单
ptypezbqht --质保期
ptypejxq --近效期
btypealarmht --往来单位预警
*/
-------------------------------------------------------------------------
CREATE   PROCEDURE Gp_GetHitInfo
(
	@OperatorId	VARCHAR(100),		--操作员ID
	@STypeID	VARCHAR(8000),		--分支机构
	@startdate   	varchar(30),		-- 录单开始日期
	@enddate 	  	varchar(30),		-- 录单结束日期
	@startdate1		varchar(30),		-- 交货开始日期
	@ifstype	VARCHAR(50)  --是否有分支机构
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Result(hitType VARCHAR(100),ishit INT)

--超期收款
DECLARE @re_re INT
EXEC @re_re=GP_CheckLimit @OperatorId,163
IF @re_re=0
	INSERT INTO #Result EXEC dbo.Web_OutDate_Gathering @OperatorId,  @startdate,@enddate,  '','','', '', '', @STypeID,'','','',1,0,-1,'','',1
	
--超期付款	
EXEC @re_re=GP_CheckLimit @OperatorId,472
IF @re_re=0
	INSERT INTO #Result EXEC dbo.Web_OutDate_Pay @OperatorId ,@startdate,@enddate,'','','','','',@STypeID,'','','',1,0,'','',1  

--库存上限
EXEC @re_re=GP_CheckLimit @OperatorId,1348	
IF @re_re=0																											
	INSERT INTO #Result EXEC dbo.Web_QueryStockAlermUpOrDownData @OperatorId,'', '00000','','','',2,1,0,'false',1,''	 

--库存下限
EXEC @re_re=GP_CheckLimit @OperatorId,1349
IF @re_re=0
	INSERT INTO #Result EXEC dbo.Web_QueryStockAlermUpOrDownData @OperatorId,'', '00000','','','',3,3,0,'false',1,''

--采购订单	
EXEC @re_re=GP_CheckLimit @OperatorId,536
IF @re_re=0
	INSERT INTO #Result EXEC dbo.Web_QueryOrderALert @OperatorID,'buy',@startdate,@enddate,@startdate1,'','','','','',0,@stypeid,0,1
--销售订单

EXEC @re_re=GP_CheckLimit @OperatorId,534
IF @re_re=0
	INSERT INTO #Result EXEC dbo.Web_QueryOrderALert @OperatorID,'sale',@startdate,@enddate,@startdate1,'','','','','',0,@stypeid,0,1
--商品保质期查询

EXEC @re_re=GP_CheckLimit @OperatorId,607
IF @re_re=0
	INSERT INTO #Result EXEC dbo.Web_QueryPTypeBZQ @OperatorId, '00000', '00000',0,0,'','',@stypeid,1
	
--商品近效期查询
EXEC @re_re=GP_CheckLimit @OperatorId,611
IF @re_re=0
	INSERT INTO #Result EXEC dbo.Web_QueryPTypeJXQ @OperatorId = @OperatorId, -- varchar(100)
    @PTypeId = '', -- varchar(100)
    @KTypeId = '', -- varchar(100)
    @SortField = '', -- varchar(100)
    @SortType = '', -- varchar(100)
    @stypeid = '', -- varchar(8000)
    @isLoginHit=1 --int
    
    
EXEC @re_re=GP_CheckLimit @OperatorId,2925
IF @re_re=0
	INSERT INTO #Result EXEC Web_QueryArApAuditAccountDetail @OperatorId=@OperatorId,
	@StartDate=@startdate,@EndDate=@enddate,
	@STypeId='00001',@BTypeId='',@Cid=0,
	@IsDetail='True',
	@BillType='215,11,45,160,141,34,6,161,145,116,115,128,129,4,189,66,190,148,150,149,151,36,93,84,85,159,167,168,170,172,181,312,213,212,305,404,405',
	@WhichDetail='B',@queryinvoice='1',@IsAccountDate=1,
	@QueryAccountDate=1,@isLoginHit=1
					   
--往来单位预警
 INSERT INTO #Result EXEC dbo.Web_GetIntercourseSetting @OperatorId = @OperatorId, @ifstype = @ifstype, @isLoginHit=1


SELECT * FROM #Result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_GetIniCommissionStock]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_GetIniCommissionStock]
GO

/****** Object:  StoredProcedure [dbo].[GP_GetIniCommissionStock]    Script Date: 05/18/2011 12:22:27 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*委托, 受托期初, 线性树形查询*/
CREATE PROCEDURE [dbo].[GP_GetIniCommissionStock]
    (
      @OperatorID VARCHAR(50) ,
      @PtypeID VARCHAR(50) ,
      @BtypeID VARCHAR(50) ,
      @KtypeID VARCHAR(50) ,
      @EtypeID VARCHAR(50) ,
      @Type VARCHAR(10) ,
      @sonNum INT = 0 ,
      @Zero INT = 0 ,
      @searchMode VARCHAR(20) = 'TreeSearch' ,
      @usercode VARCHAR(120) = '%%' ,
      @fullname VARCHAR(100) = '%%' ,
      @entryCode VARCHAR(100) = '%%' ,
      @stypeid VARCHAR(8000)
    )
--@encode$--
AS 
    SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
    IF @OperatorID IS NULL 
        RETURN 1
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT
    IF @Re <> 0 
        RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

    DECLARE @SQL VARCHAR(8000)
    DECLARE @stateCountSql VARCHAR(8000)
    DECLARE @BtypeAll VARCHAR(10)
    SET @BtypeAll = '0'
    SELECT  @BtypeAll = value
    FROM    Userconfig
    WHERE   ConfigName = 'BtypeAll'


    CREATE TABLE #Ptype
        (
          TypeID VARCHAR(50) ,
          Usercode VARCHAR(200) ,
          fullname VARCHAR(200)
        )
    CREATE TABLE #Btype ( TypeID VARCHAR(50) )
    CREATE TABLE #stype ( TypeID VARCHAR(50) )

    /*序列号委托, 受托期初,状态值统计临时表*/
    CREATE TABLE #InitPtypeSerialStateCount
        (
  	  PtypeID VARCHAR(50) ,
          State7 INT ,
          State9 INT ,
          State10 INT ,
          State11 INT ,
          State13 INT ,
          State14 INT ,
          State16 INT ,
          State32 INT
        )

    CREATE TABLE #MainType
        (
          TypeID VARCHAR(50) ,
          usercode VARCHAR(200) ,
          fullname VARCHAR(200) ,
          sonnum INT ,
          deleted INT ,
          entrycode VARCHAR(200),
          SortID INT
        )



--商品
    INSERT  INTO #Ptype
            ( typeid ,
              usercode ,
              fullname
            )
            SELECT  P.typeid ,
                    usercode ,
                    fullname
            FROM    ptype P ,
                    F_GetAllManagerBaseTypeId(@PtypeID, 1, @OperatorID) W
            WHERE   P.typeid = W.typeid AND IsService=0
            AND p.iscombinationproduct=0
--往来单位   
    INSERT  INTO #Btype
            ( typeid
            )
            SELECT  typeid
            FROM    F_GetAllManagerBaseTypeId(@BtypeID, 2, @OperatorID)
--分支机构   
    INSERT  INTO #stype
            ( typeid
            )
            SELECT  typeid
            FROM    F_GetAllManagerBaseTypeId(@stypeid, 11, @OperatorID)


    SET @sonnum = 0
    SELECT  @sonnum = sonnum
    FROM    Ptype
    WHERE   Typeid = @PtypeID

    IF @searchMode <> 'TreeSearch' -- 线性表
        BEGIN
            IF @PtypeID = '00000' 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          entrycode
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.entrycode
                        FROM    Ptype p ,
                                F_GetManDetailPType(@OperatorID) W
                        WHERE   p.typeid = W.typeid
                                AND W.typeid <> '00000' AND p.IsService=0
                                AND p.iscombinationproduct=0
            ELSE 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          entrycode
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.entrycode
                        FROM    Ptype p ,
                                F_GetManDetailPType(@OperatorID) W
                        WHERE   p.typeid = W.typeid
                                AND W.typeid LIKE @PtypeID + '%' AND p.IsService=0
                                AND p.iscombinationproduct=0
        END
    ELSE 
        BEGIN
            IF @sonnum = 0 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          entrycode,
                          SortID
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.entrycode,
                                p.SortID
                        FROM    Ptype p ,
                                F_GetManPTypeAll(@OperatorID) W
                        WHERE   p.typeid = W.typeid
                                AND W.typeid = @PtypeID
                                AND W.typeid <> '00000' AND p.IsService=0
                                AND p.iscombinationproduct=0
            ELSE 
                IF @PtypeID = '00000' 
                    INSERT  INTO #MainType
                            ( typeid ,
                              usercode ,
                              fullname ,
                              sonnum ,
                              deleted ,
                              entrycode,
                              SortID
                         )
                            SELECT  p.typeid ,
                                    p.usercode ,
                                    p.fullname ,
                                    p.sonnum ,
                                    p.deleted ,
                                    p.entrycode,
                                    p.SortID
                            FROM    Ptype p ,
                                    F_GetManPTypeAll(@OperatorID) W
                            WHERE   p.typeid = W.typeid
                                    AND W.parid = '00000'
                                    AND W.typeid <> '00000' AND p.IsService=0
                                    AND p.iscombinationproduct=0
                ELSE 
                    INSERT  INTO #MainType
                            ( typeid ,
                              usercode ,
                              fullname ,
                              sonnum ,
                              deleted ,
                              entrycode,
                              SortID
                            )
                            SELECT  p.typeid ,
                                    p.usercode ,
                                    p.fullname ,
                                    p.sonnum ,
                                    p.deleted ,
                                    p.entrycode,
                                    p.SortID
                            FROM    Ptype p ,
                                    F_GetManPTypeAll(@OperatorID) W
                            WHERE   p.typeid = W.typeid
                                    AND W.parid = @PtypeID
                                    AND W.typeid <> '00000'AND p.IsService=0
                                    AND p.iscombinationproduct=0
        END
--序列号委托, 受托期初,状态值统计	

	set @stateCountSql ='INSERT  INTO #InitPtypeSerialStateCount
            ( 
          	PtypeID,
          	State7,
          	State9,
          	State10,
          	State11,
          	State13,
          	State14,
          	State16,
          	State32
            )
            select PtypeID,
		SUM(case when [State]=7 then 1 else 0 end ) as State7,
		SUM(case when [State]=9 then 1 else 0 end ) as State9,
		SUM(case when [State]=10 then 1 else 0 end ) as State10,
		SUM(case when [State]=11 then 1 else 0 end ) as State11,
		SUM(case when [State]=13 then 1 else 0 end ) as State13,
		SUM(case when [State]=14 then 1 else 0 end ) as State14,
		SUM(case when [State]=16 then 1 else 0 end ) as State16,
		SUM(case when [State]=32 then 1 else 0 end ) as State32
		From [gp_initPtypeSerial]
		Where 1=1 '
		
		IF @BtypeID<>''
		BEGIN
		IF @Type='144'
			SET @stateCountSql =@stateCountSql +' AND BtypeID2 IN (SELECT typeid FROM #Btype) '
		IF @Type='140'
			SET @stateCountSql =@stateCountSql +' AND BtypeID1 IN (SELECT typeid FROM #Btype) '
		END
		IF @KtypeID<>''
			SET @stateCountSql =@stateCountSql +' AND KtypeID= '+@KtypeID

		IF @EtypeID<>''
			SET @stateCountSql =@stateCountSql +' AND EtypeID= '+@EtypeID

		IF @stypeid<>''
			SET @stateCountSql =@stateCountSql +' AND STypeId IN( SELECT typeid FROM #stype ) '

		set @stateCountSql =@stateCountSql +' GROUP BY PtypeID '

		EXEC(@stateCountSql)
---------------------------------------------------------------
    IF @searchMode = 'TreeSearch' 
        BEGIN
	
            SELECT  @sonNum = CASE WHEN sonnum > 0 THEN 1
                                   ELSE 0
                              END
            FROM    ptype
            WHERE   typeid = @PtypeID
            SELECT  @SQL = 'SELECT 
					(select SUM(ISNULL(sc.State7,0)) FROM #InitPtypeSerialStateCount sc where p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) )AS State7,
(select SUM(ISNULL(sc.State9,0)) FROM #InitPtypeSerialStateCount sc where p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) )AS State9,
(select SUM(ISNULL(sc.State10,0)) FROM #InitPtypeSerialStateCount sc where p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) )AS State10,
(select SUM(ISNULL(sc.State11,0)) FROM #InitPtypeSerialStateCount sc where p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) )AS State11,
(select SUM(ISNULL(sc.State13,0)) FROM #InitPtypeSerialStateCount sc where p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) )AS State13,
(select SUM(ISNULL(sc.State14,0)) FROM #InitPtypeSerialStateCount sc where p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) )AS State14,
(select SUM(ISNULL(sc.State16,0)) FROM #InitPtypeSerialStateCount sc where p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) )AS State16,
(select SUM(ISNULL(sc.State32,0)) FROM #InitPtypeSerialStateCount sc where p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) )AS State32,
					p.typeid,
					p.sonnum,
					p.Entrycode,
					p.usercode,
					p.sortid,
	                p.fullname AS pfullname,
					SUM(ISNULL(b.qty,0))  AS qty,
					SUM(ISNULL(b.CostTotal,0)) AS CostTotal,
					SUM(ISNULL(b.Total,0)) AS Total,
					price =case when SUM(ISNULL(b.qty,0))=0 then 0 else CAST(SUM(ISNULL(b.Total,0)) AS NUMERIC(24,10))/SUM(ISNULL(b.qty,0)) end,
					btypeid=(select top 1 case  when ' + @BtypeAll
                    + '=1 and typeid=''00000''  then ''00000'' else  isnull(typeid,'''') end as btypeid from btype where typeid='''
                    + @btypeid
                    + '''),
					bsonnum=(select top 1 case  when typeid=''00000'' then 1 else  sonnum end as sonnum from btype where typeid='''
                    + @btypeid + ''')
				   FROM #MainType p '
            IF @Zero = 0 
                SET @SQL = @SQL + ' LEFT '
            IF @Zero = 1 
                SET @SQL = @SQL + ' INNER '
            SET @SQL = @SQL + ' JOIN(
								SELECT 	a.Ptypeid,
										a.Type,
										SUM(ISNULL(a.qty,0)) AS qty,
										SUM(ISNULL(a.CostTotal,0)) AS costTotal,
										SUM(ISNULL(a.Total,0)) AS Total
								FROM 	IniCommissionStock a' 			

            IF NOT ( @BtypeID = '00000'
                     AND @MBTypeId = '00001'
                     AND @MBTypeId2 = '00002'
                   ) 
                SET @SQL = @SQL
                    + ' INNER JOIN #Btype B ON a.BtypeID=B.typeid '

            IF NOT ( @PtypeID = '00000'
                     AND @MPtypeid = '00000'
                   ) 
                SET @SQL = @SQL
                    + ' INNER JOIN #Ptype P ON a.PtypeID=P.typeid '
			   
			   	 
            IF NOT ( @stypeid = ''
                     AND @Mstypeid = '00000'
                   ) 
                SET @SQL = @SQL
                    + '    INNER JOIN #stype s  ON a.stypeID=s.typeid '

            SET @SQL = @SQL + ' WHERE  	a.Type=' + @Type
                + '  GROUP BY a.Ptypeid,a.type '	

			--关联条件期初数量与序列数量商品ID相同，或者期初数量有数据，序列号商品无数据的情况，目的为了避免关联出重复数据  施训果 2015-08-04
            SELECT  @SQL = @SQL
                     + ')b ON p.typeid=LEFT(b.Ptypeid,LEN(p.typeid)) '
            IF @Zero = 1 
                SET @SQL = @SQL + ' where  qty <>0 or Total<>0'
            SELECT  @SQL = @SQL + ' GROUP BY
							   p.typeid,
							   p.sonnum,
							   p.usercode,
							   p.fullname,
							   p.Entrycode,
							   p.sortid
							   ORDER BY p.sortid asc'
        END

    IF @searchMode = 'LineSearch' 
        BEGIN
            SET @usercode = '%' + @usercode + '%'
            SET @fullname = '%' + @fullname + '%'
            SET @entryCode = '%' + @entryCode + '%'

            SELECT  @SQL = ' SELECT   
							SUM(ISNULL(sc.State7,0)) AS State7,
							SUM(ISNULL(sc.State9,0)) AS State9,
							SUM(ISNULL(sc.State10,0)) AS State10,
							SUM(ISNULL(sc.State11,0)) AS State11,
							SUM(ISNULL(sc.State13,0)) AS State13,
							SUM(ISNULL(sc.State14,0)) AS State14,
							SUM(ISNULL(sc.State16,0)) AS State16,
							SUM(ISNULL(sc.State32,0)) AS State32,
						    p.typeid,
							p.sonnum,
							p.Entrycode,
							p.usercode,
							p.fullname AS pfullname,
							SUM(ISNULL(i.qty,0))  AS qty,
							SUM(ISNULL(i.CostTotal,0)) AS CostTotal,
							SUM(ISNULL(i.Total,0)) AS Total,
							price =case when SUM((ISNULL(i.qty,0)))=0 then 0 else CAST(SUM(ISNULL(i.Total,0)) AS NUMERIC(24,10))/SUM(ISNULL(i.qty,0)) end,
							btypeid=(select top 1 case  when ' + @BtypeAll
                    + '=1 and typeid=''00000'' then ''00000'' else  isnull(typeid,'''') end as btypeid from btype where typeid='''
                    + @btypeid
                    + '''),
							bsonnum=(select top 1 case  when typeid=''00000'' then 1 else  sonnum end as sonnum from btype where typeid='''
                    + @btypeid + ''')
		               FROM #MainType  p LEFT JOIN #InitPtypeSerialStateCount sc ON p.typeid=LEFT(sc.Ptypeid,LEN(p.typeid)) ' 
            IF @Zero = 0 
                SET @SQL = @SQL + ' LEFT '
            IF @Zero = 1 
                SET @SQL = @SQL + ' INNER '
            SET @SQL = @SQL + '     JOIN(
								SELECT 	C.Ptypeid,
										C.Type,
										SUM(ISNULL(C.qty,0)) AS qty,
										SUM(ISNULL(C.CostTotal,0)) AS costTotal,
										SUM(ISNULL(C.Total,0)) AS Total
								FROM 	IniCommissionStock C '
   		
            SET @SQL = @SQL + 'LEFT JOIN  employee j ON j.typeid=C.etypeid '

            IF NOT ( @BtypeID = '00000'
                     AND @MBTypeId = '00001'
                     AND @MBTypeId2 = '00002'
                   ) 
                SET @SQL = @SQL
                    + '    INNER JOIN #Btype B  ON C.BtypeID=B.typeid '

            IF NOT ( @PTypeID = '00000'
                     AND @MPtypeid = '00000'
                   ) 
                SET @SQL = @SQL
                    + '    INNER JOIN #Ptype P  ON C.PtypeID=P.typeid '
				 
            IF NOT ( @stypeid = ''
                     AND @Mstypeid = '00000'
                   ) 
                SET @SQL = @SQL
                    + '    INNER JOIN #stype s  ON C.stypeID=s.typeid '
				
            SET @SQL = @SQL + '    WHERE  type =' + @type 
            SET @SQL = @SQL
                + ' and ISNULL(c.Qty,0)<>0   GROUP BY C.Ptypeid,C.type) i ON p.typeid=LEFT(i.Ptypeid,LEN(p.typeid))  OR i.Ptypeid=sc.Ptypeid
						WHERE 	ISNULL(p.usercode,'''') LIKE''' + @usercode + ''' 
								AND ISNULL(p.fullname,'''') LIKE ''' + @fullname + ''' 
								AND ISNULL(p.Entrycode,'''') LIKE ''' + @entryCode + '''
	                    GROUP BY 
								p.typeid,
								p.sonnum,
								p.Entrycode,
								p.usercode,
								p.fullname
						 ORDER BY p.usercode'			
	
        END

    PRINT ( @sql )
    EXEC(@SQL)
    DROP TABLE #Ptype,#stype,#Btype,#MainType,#InitPtypeSerialStateCount
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_GetIniDistCommissionStock]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_GetIniDistCommissionStock]
GO








CREATE  PROCEDURE [GP_GetIniDistCommissionStock]
    (
      @OperatorID VARCHAR(50) ,
      @type VARCHAR(10) = '140' ,
      @stypeid VARCHAR(8000) ,
      @usercode VARCHAR(200) ,
      @fullname VARCHAR(200) ,
      @entrycode VARCHAR(200)
    )
--@encode$--
AS 
    SET nocount ON
    SET ANSI_WARNINGS  OFF

--------------------------------------------------------------权限检查-------------------------------------------------------
    IF @OperatorID IS NULL 
        RETURN 1
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT
    IF @Re <> 0 
        RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


    CREATE TABLE #Ptype ( TypeID VARCHAR(50) )
    CREATE TABLE #Btype ( TypeID VARCHAR(50) )
    CREATE TABLE #stype ( TypeID VARCHAR(50) )

--分支机构    
    INSERT  INTO #stype
            ( typeid
            )
            SELECT  typeid
            FROM    F_GetAllManagerBaseTypeId(@stypeid, 11, @OperatorID)

    INSERT  INTO #Ptype
            SELECT  a.typeid
            FROM    F_BaseGetManPType(@OperatorID) a
            WHERE   a.FullName LIKE '%' + @fullname + '%'
                    AND UserCode LIKE '%' + @usercode + '%'
                    AND a.EntryCode LIKE '%' + @entrycode + '%'
                    AND sonnum = 0

    DECLARE @SQL VARCHAR(6000)
    SET @SQL = ' AND I.qty<>0 AND I.Type=' + @type

    IF EXISTS ( SELECT  *
                FROM    userconfig
                WHERE   configname = 'btypeall'
                        AND Value = 1 ) 
        INSERT  INTO #Btype
                SELECT  typeid
                FROM    F_GetManDetailBType(@OperatorID) 
    ELSE 
        BEGIN
            IF @type = '140' 
                INSERT  INTO #Btype
                        SELECT  typeid
                        FROM    F_GetManDetailBType(@OperatorID)
                        WHERE   typeid LIKE '00001%'
            ELSE 
                INSERT  INTO #Btype
                        SELECT  typeid
                        FROM    F_GetManDetailBType(@OperatorID)
                        WHERE   typeid LIKE '00002%'
        END

	
    SET @SQL = 'INSERT INTO #iniCommissionStock
				    SELECT I.PtypeId as ptypeid,
				           b.typeid as btypeid,
				           b.usercode as busercode,
				           b.fullname as bfullname,sum(qty) as qty 
					  from iniCommissionStock I 
				           INNER JOIN btype b ON i.btypeid=b.typeid 
				           INNER JOIN #Ptype P ON I.PtypeID=P.typeid '
	

    IF NOT ( @MBTypeId = '00001'
             AND @MBTypeId2 = '00002'
           ) 
        SET @SQL = @SQL + ' INNER JOIN #Btype B1 ON I.BtypeID=B1.typeid '

/*IF NOT (@MPtypeid = '00000')
	SET @SQL =@SQL+' INNER JOIN #Ptype P ON I.PtypeID=P.typeid '*/
	
    IF NOT ( @stypeid = ''
             AND @MStypeid = '00000'
           ) 
        SET @SQL = @SQL + ' INNER JOIN #stype s ON I.stypeID=s.typeid '
    
    SET @SQL = @SQL + ' WHERE I.qty<>0 AND I.Type=' + @type
    SET @SQL = @SQL + ' GROUP BY I.PtypeId,b.typeid,b.usercode,b.fullname '

    PRINT @sql
    CREATE TABLE #iniCommissionStock
        (
          ptypeid VARCHAR(50) ,
          btypeid VARCHAR(50) ,
          busercode VARCHAR(26) ,
          bfullname VARCHAR(66) ,
          qty  NUMERIC(24, 10) 
        )
    CREATE TABLE #DistStock ( ptypeid VARCHAR(50) )

    EXEC(@SQL)
--print @sql
    INSERT  INTO #DistStock
            ( ptypeid
            )
            SELECT  S.ptypeid
            FROM    ( SELECT DISTINCT
                                ptypeid
                      FROM      #iniCommissionStock
                    ) S
                    INNER JOIN dbo.ptype P ON P.typeId = S.ptypeid
            ORDER BY P.UserCode
            
            
            
		
    DECLARE @btypeid VARCHAR(50)
    DECLARE @bfullname VARCHAR(66)
    DECLARE @ColName VARCHAR(8000)

--Select distinct btypeid,bfullname from #iniCommissionStock

    SET @ColName = 'ptypeid as typeid '

    DECLARE rowcursor CURSOR
    FOR
        SELECT DISTINCT
                btypeid ,
                bfullname
        FROM    #iniCommissionStock
    OPEN rowcursor
    FETCH NEXT FROM rowcursor INTO @btypeid, @bfullname
--PRINT @bfullname
--PRINT  @@FETCH_STATUS 
    WHILE @@FETCH_STATUS = 0 
        BEGIN
            EXEC('ALTER table #DistStock ADD ['+@bfullname+']  NUMERIC(24, 10) ')
            SET @SQL = '
		UPDATE #DistStock SET  [' + @bfullname
                + ']=ISNULL(i.qty,0)
		FROM (select ptypeid,sum(isnull(qty,0)) as qty from #iniCommissionStock where btypeid='''
                + @btypeid + ''' group by ptypeid) i
		INNER JOIN
		#DistStock d
		ON i.ptypeid=d.ptypeid
		'
            EXEC(@SQL)
            SET @ColName = @ColName + ',ISNULL([' + @bfullname + '],0) as ['
                + @bfullname + ']'
            FETCH NEXT FROM rowcursor INTO @btypeid, @bfullname
        END
    CLOSE rowcursor
    DEALLOCATE rowcursor
--PRINT @ColName

    EXEC('select '+@ColName+' from #DistStock')
    DROP TABLE #DistStock
    DROP TABLE #iniCommissionStock

    DROP TABLE #Ptype,#Btype,#stype





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE               PROCEDURE [GP_GetIniDistCommissionStock1] 
(
	@OperatorID 	varchar(50),
	@PtypeID        varchar(50),
    @type           varchar(10) ='140',
    @stypeid		varchar(8000)
)
--@encode$--

as

set nocount on
set ANSI_WARNINGS  off

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #stype (TypeID varchar(50))

--分支机构    
INSERT INTO #stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

INSERT INTO #Ptype select a.typeid from F_GetManDetailPType(@OperatorID) a where a.typeid like @PtypeID+'%'


DECLARE @SQL varchar(6000)

IF EXISTS(SELECT * FROM userconfig WHERE configname='btypeall' AND Value=1)
	INSERT INTO #Btype select typeid from F_GetManDetailBType(@OperatorID) 
ELSE
BEGIN
	IF @type='140'
		INSERT INTO #Btype select typeid from F_GetManDetailBType(@OperatorID) where typeid like '00001%'
	ELSE
		INSERT INTO #Btype select typeid from F_GetManDetailBType(@OperatorID) where typeid like '00002%'
END


SET @SQL='Select I.BtypeID AS typeid,
               isnull(QTY,0) as QTY
               from iniCommissionStock I '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
    SET @SQL=@SQL+' INNER JOIN #Btype B ON I.BtypeID=B.typeid '

IF NOT (@PtypeID ='00000' AND @MPtypeid = '00000')
    SET @SQL=@SQL+' INNER JOIN #Ptype P ON I.PtypeID=P.typeid '
    
IF NOT (@stypeid ='' AND @MStypeid = '00000')
    SET @SQL=@SQL+' INNER JOIN #stype s ON I.stypeID=s.typeid '
    
    SET @SQL=@SQL+' WHERE I.qty<>0 AND I.Type='+@type 

--print @SQL return 1
EXEC(@SQL)

DROP TABLE #Ptype,#Btype,#stype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_GetInoutStock]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_GetInoutStock]
GO





-- 销售汇总分析是否有数据
-- cqhua 2009-12-04

CREATE        PROCEDURE GP_GetInoutStock
(
	 @OperatorId	VARCHAR(50),
	 @startdate		VARCHAR(30),
	 @enddate		VARCHAR(30),
	 @ptypeid		VARCHAR(8000),
	 @stypeid		VARCHAR(8000),
	 @ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #BType (typeid VARCHAR(50))
CREATE TABLE #PType (typeid VARCHAR(50))
CREATE TABLE #ktype (TypeID VARCHAR(50))
CREATE TABLE #etype (TypeID VARCHAR(50))
CREATE TABLE #dtype (TypeID VARCHAR(50))
CREATE TABLE #stype (TypeID VARCHAR(50))

INSERT INTO #BType SELECT a.typeid FROM F_GetMANDetailBType(@OperatorID) a

INSERT INTO #ktype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)
INSERT INTO #etype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)
INSERT INTO #dtype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)
INSERT INTO #ktype(TypeID) values('10000')
--分支机构    
INSERT INTO #stype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
IF @ptypeid=''
	INSERT INTO #Ptype SELECT typeid FROM  F_LinePC(@OperatorID,@ptypecategoryid) 
ELSE
	INSERT INTO #Ptype SELECT a.typeid FROM F_ManPTypeInCategoryID ( @OperatorId,@ptypeid,@ptypecategoryid) a, (SELECT * FROM  dbo.f_split(@ptypeid,',')) b WHERE LEFT(a.typeid,LEN(b.a))=b.a

DECLARE @revlue INT 
SET @revlue =0

DECLARE @SQL NVARCHAR(MAX)
SET @SQL='
if exists(
SELECT  1
FROM inoutstocktable I
'
IF NOT (@stypeid ='' AND @MStypeid = '00000')
    SET @SQL=@SQL+ ' INNER JOIN  #Stype S ON I.STypeID=S.TypeID '
IF NOT (@MEtypeid = '00000')
    SET @SQL=@SQL+ ' INNER JOIN  #Etype E ON I.ETypeID=E.TypeID '
IF NOT (@MKtypeid = '00000')
    SET @SQL=@SQL+ ' INNER JOIN  #Ktype K ON I.KTypeID=K.TypeID '
IF NOT (@MBtypeid = '00000')
    SET @SQL=@SQL+ ' INNER JOIN  #Btype B ON I.BTypeID=B.TypeID ' 
SET @SQL=@SQL+
'
WHERE audited =1 
AND billtype IN (11,45,305,141,160,215,12,46)
AND billdate>='''+@startdate+''' 
AND billdate<='''+@enddate+'''
)
SET @revlue=1
ELSE
SET @revlue=0
'
EXECUTE sp_executesql @SQL,N'@revlue int OUTPUT',@revlue  OUTPUT


--PRINT @SQL
DROP TABLE  #Ptype,#Btype,#ktype,#etype,#dtype,#stype
RETURN @revlue
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


--======================================
--作者:谢吉康
--日期:2003-11-07
--描述:在借欠的经营历程中增加按商品查找

--修改日期：2003-11-25
--修改原因：增加了单据编号的字段
--修改结果：测试通过
--======================================
CREATE                  PROCEDURE [GP_GetLendBorrowFromPtype]
(
	@OperatorId	VARCHAR(50),
	@StartDate	VARCHAR(20),
	@EndDate	VARCHAR(20),
	@PtypeId	VARCHAR(50),
	@BtypeId	VARCHAR(50),
	@EtypeId	VARCHAR(50),
	@KtypeId	VARCHAR(50),
	@LineType	INT,
	@isSon		INT,
	@OrderFild	VARCHAR(50),
	@OrderType 	varchar(20),
	@ShowZero	INT,
	@BillType   VARCHAR(50),
	@BillCode   VARCHAR(200) = '%',   -- #&**&#
	@STypeId	VARCHAR(MAX),
	@IsReporting	INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
DECLARE @SQL VARCHAR(8000)
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--多级权限
SELECT a.* INTO #ptype FROM F_GetManPtypeAll(@OperatorID) a  WHERE a.IsService=0 AND a.iscombinationproduct = 0 --商品权限
SELECT a.* INTO #btype FROM F_GetManBtypeAll(@OperatorID) a --往来单位权限
SELECT a.* INTO #stock FROM F_GetManKtypeAll(@OperatorID) a --仓库权限
SELECT a.* INTO #employee FROM F_GetManDetailEtype(@OperatorID) a --职员权限



--====================================================================树型表
IF @LineType='0'
BEGIN
	SELECT @SQL='
		SELECT 	p.typeId,
				p.sonnum,
				p.UserCode,
				p.FullName,
				SUM(ISNULL(b.qty,0)) AS qty
		FROM #ptype p
			LEFT JOIN 
			(
				SELECT 	a.BillNumberId,
						a.BillDate,
						a.BillCode,
						a.Btypeid,
						a.EtypeId,
						a.KtypeId,
						b.PtypeId,
						b.Qty,
						e.fullname AS efullname,
						k.fullname AS kfullname,
						bt.fullname AS bfullname
				FROM 	LendIndex a,
						LendBill b,
						Employee e,
						Stock K,
						Btype Bt
				WHERE 	a.BillNumberId=B.BillNumberId
						AND a.etypeid=e.typeid
						AND a.ktypeid=k.typeid
						AND a.btypeid=bt.typeid
						AND a.ifcheck=''t''	
						AND a.BillType LIKE '+CHAR(39)+@BillType+CHAR(39)+'
						AND a.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
						AND a.billdate>='+CHAR(39)+@StartDate+CHAR(39)+'
						AND a.billdate<='+CHAR(39)+@EndDate+CHAR(39)
						
				IF @BtypeId<>'' 
					SELECT @SQL=@SQL+' AND a.btypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@BtypeId+CHAR(39)+',2))'					
					
				IF @KtypeId<>''			
					SELECT @SQL=@SQL+' AND a.ktypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@KtypeId+CHAR(39)+',4))'
					
				IF @EtypeId<>''
					SELECT @SQL=@SQL+' AND a.etypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@EtypeId+CHAR(39)+',3))'

				SELECT @SQL = @SQL + ' AND A.STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''+@STypeId+''',11,'''+@OperatorID+''')) '
				SELECT @SQL = @SQL + ' AND A.DTypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''',9,'''+@OperatorID+''')) '

				--权限检查
                SELECT @SQL = @SQL + ' AND a.EtypeID IN (SELECT typeid FROM #employee)'
                SELECT @SQL = @SQL + ' AND a.KtypeID IN (SELECT typeid FROM #stock)'
                SELECT @SQL = @SQL + ' AND a.BtypeID IN (SELECT typeid FROM #btype)'
				SELECT @SQL = @SQL + ' AND b.PtypeID IN (SELECT typeid FROM #ptype)'

		SELECT @SQL=@SQL+')b
			ON p.typeId=LEFT(b.PtypeId,len(p.typeId))'

		IF @PtypeId=''
		BEGIN
			SELECT @SQL=@SQL+' WHERE p.parid=''00000'''
		END
		ELSE
		BEGIN
			IF @isSon=0 
				SELECT @SQL=@SQL+' WHERE p.parid='+CHAR(39)+@PtypeId+CHAR(39)
			ELSE
				SELECT @SQL=@SQL+' WHERE p.typeid='+CHAR(39)+@PtypeId+CHAR(39)
		END

		SELECT @SQL=@SQL+'
			GROUP BY p.typeId,p.sonnum,p.UserCode,p.Fullname
			ORDER BY p.UserCode'
	
END
--====================================================================线性表
IF  @LineType=1
BEGIN
	SELECT @SQL='
		SELECT 	p.typeId,
				p.sonnum,
				p.UserCode,
				p.FullName,
				SUM(ISNULL(b.qty,0)) AS qty
		FROM #Ptype p
			LEFT JOIN 
			(
				SELECT 	b.PtypeId,
						SUM(ISNULL(b.Qty,0)) AS Qty
				FROM 	LendIndex a,
						LendBill b,
						Employee e,
						Stock K,
						Btype Bt
				WHERE 	a.BillNumberId=B.BillNumberId
						AND a.etypeid=e.typeid
						AND a.ktypeid=k.typeid
						AND a.btypeid=bt.typeid
						AND a.ifcheck=''t''											
						AND a.BillType LIKE '+CHAR(39)+@BillType+CHAR(39)+'
						AND a.billdate>='+CHAR(39)+@StartDate+CHAR(39)+'
						AND a.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
						AND a.billdate<='+CHAR(39)+@EndDate+CHAR(39)
						
				IF @BtypeId<>'' 
					SELECT @SQL=@SQL+' AND a.btypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@BtypeId+CHAR(39)+',2))'					
					
				IF @KtypeId<>''			
					SELECT @SQL=@SQL+' AND a.ktypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@KtypeId+CHAR(39)+',4))'
					
				IF @EtypeId<>''
					SELECT @SQL=@SQL+' AND a.etypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@EtypeId+CHAR(39)+',3))'

				SELECT @SQL = @SQL + ' AND A.STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''+@STypeId+''',11,'''+@OperatorID+''')) '
				SELECT @SQL = @SQL + ' AND A.DTypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''',9,'''+@OperatorID+''')) '
				
				--权限检查
                SELECT @SQL = @SQL + ' AND a.EtypeID IN (SELECT typeid FROM #employee)'
                SELECT @SQL = @SQL + ' AND a.KtypeID IN (SELECT typeid FROM #stock)'
                SELECT @SQL = @SQL + ' AND a.BtypeID IN (SELECT typeid FROM #btype)'
				SELECT @SQL = @SQL + ' AND b.PtypeID IN (SELECT typeid FROM #ptype)'

				SELECT @SQL = @SQL + ' GROUP BY b.PTypeID '

		SELECT @SQL=@SQL+')b
			ON p.typeId=LEFT(b.PtypeId,len(p.typeId))'
		IF @PtypeId=''
			SELECT @SQL=@SQL+' WHERE  p.sonnum=0'
		ELSE	
			BEGIN
				DECLARE @CurSon INT			
				
				SELECT @CurSon=sonnum FROM Ptype WHERE typeid=@PtypeId

				IF @CurSon>0 				
					SELECT @SQL=@SQL+' WHERE p.typeid LIKE '+CHAR(39)+@PtypeId+'%'+CHAR(39)+' AND p.sonnum=0 AND p.typeid<>'+CHAR(39)+@Ptypeid+CHAR(39)				
				ELSE
					SELECT @SQL=@SQL+' WHERE p.typeid='+CHAR(39)+@PtypeId+CHAR(39)					
			END
		
		IF @ShowZero=0 
			SELECT @SQL=@SQL+' AND qty<>0'

			
		SELECT @SQL=@SQL+'
			GROUP BY p.typeId,p.sonnum,p.UserCode,p.Fullname
			ORDER BY p.UserCode'
	
END
--=================================================================================明细表
IF @LineType=2 
BEGIN
	SELECT @SQL='
		SELECT 	a.billnumberid,
				a.billdate,
				a.billcode,
				a.stypeid,
				a.comment,
				b.qty,	
				a.billtype,
				e.fullname AS efullname,
				e.typeid AS etypeid,
				k.fullname AS kfullname,
				k.typeid AS ktypeid,
				bt.fullname AS bfullname,
				bt.typeid AS btypeid,
				p.fullname AS pfullname	,
				b.id AS customdetailid,
				a.RedWord			
		FROM 	LendIndex a,
				LendBill b,
				employee e,
				stock k,
				btype bt,
				ptype p
		WHERE 	a.billnumberid=b.billnumberid
				AND a.etypeid=e.typeid
				AND a.ktypeid=k.typeid
				AND a.btypeid=bt.typeid
				AND b.ptypeid=p.typeid	
				AND a.ifcheck=''t''	
				AND a.BillType LIKE '+CHAR(39)+@BillType+CHAR(39)+'
				AND a.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
				AND a.billdate>='+CHAR(39)+@StartDate+CHAR(39)+'
				AND a.billdate<='+CHAR(39)+@EndDate+CHAR(39)+'
				AND b.ptypeid LIKE '+CHAR(39)+@Ptypeid+'%'+CHAR(39)
				
		IF @BtypeId<>'' 
			SELECT @SQL=@SQL+' AND a.btypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@BtypeId+CHAR(39)+',2))'					
		
		IF @KtypeId<>''			
			SELECT @SQL=@SQL+' AND a.ktypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@KtypeId+CHAR(39)+',4))'
		
		IF @EtypeId<>''
			SELECT @SQL=@SQL+' AND a.etypeid IN (SELECT typeid FROM F_GetAllBaseTypeId('+CHAR(39)+@EtypeId+CHAR(39)+',3))'

		SELECT @SQL = @SQL + ' AND A.STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''+@STypeId+''',11,'''+@OperatorID+''')) '
		SELECT @SQL = @SQL + ' AND A.DTypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''',9,'''+@OperatorID+''')) '
		
		--权限检查
        SELECT @SQL = @SQL + ' AND a.EtypeID IN (SELECT typeid FROM #employee)'
        SELECT @SQL = @SQL + ' AND a.KtypeID IN (SELECT typeid FROM #stock)'
        SELECT @SQL = @SQL + ' AND a.BtypeID IN (SELECT typeid FROM #btype)'
        SELECT @SQL = @SQL + ' AND p.TypeID IN (SELECT typeid FROM #ptype)'
		--SELECT @SQL = @SQL + ' ORDER BY A.BillDate,A.BillCode'
END

--==============================================================================执行SQL
--Print(@SQL)
--EXEC(@SQL)

--2014-06-03 杨俊修改,解决超过一页则不能打印、导出自定义字段信息问题
IF(@LineType <> 2)
BEGIN
	EXEC(@SQL)
END
ELSE
BEGIN
	IF(@IsReporting = 0)
	BEGIN
		SELECT @SQL = @SQL + ' ORDER BY A.BillDate,A.BillCode'
		--PRINT @SQL
		EXEC(@SQL)
	END
	ELSE IF(@IsReporting = 1)
	BEGIN
		CREATE TABLE #tmp_result
		(
			Costom1  varchar(max),  
			Costom2  varchar(max),  
			Costom3  varchar(max),  
			Costom4  varchar(max),  
			Costom5  varchar(max),  
			Costom6  varchar(max),  
			Costom7  varchar(max),  
			Costom8  varchar(max),  
			Costom9  varchar(max),  
			Costom10  varchar(max),  
			Costom11  varchar(max),  
			Costom12  varchar(max),  
			Costom13  varchar(max),  
			Costom14  varchar(max),  
			Costom15  varchar(max),  
			Costom16  varchar(max),  
			Costom1detail  varchar(max),  
			Costom2detail  varchar(max),  
			Costom3detail  varchar(max),  
			Costom4detail  varchar(max),  
			Costom5detail  varchar(max),  
			Costom6detail  varchar(max),  
			Costom7detail  varchar(max),  
			Costom8detail  varchar(max),  
			Costom9detail  varchar(max),  
			Costom10detail  varchar(max),  
			Costom11detail  varchar(max),  
			Costom12detail  varchar(max),  
			Costom13detail  varchar(max),  
			Costom14detail  varchar(max),  
			Costom15detail  varchar(max),  
			Costom16detail  varchar(max),  
			row_id    varchar(100)
		)
		--生成rowid
	SET @SQL = 'SELECT DISTINCT row_number() over (order by a.BillnumberID) as rowid,' + SUBSTRING(@SQL,CHARINDEX('SELECT DISTINCT',@SQL) + 13,LEN(@SQL))

		SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ORDER BY A.BillDate,A.BillCode ' + 
				  ' 
				   DECLARE @p1 dbo.Tb_QueryCustom  
			   INSERT INTO @p1 SELECT billnumberid,billtype,CustomdetailID,row_number() over (order by BillnumberID) from #temp1 
			   INSERT INTO #tmp_result EXEC Web_QueryCustomData @p1,2 

				   --显示最终结果
				   SELECT a.*,b.* 
					  FROM #temp1 a 
					  left join #tmp_result b on a.rowid=b.row_id

					DROP TABLE #temp1,#tmp_result
				   '
				   print @SQL
		EXEC (@SQL)
	END
END
--删除零时表
DROP TABLE #ptype
DROP TABLE #btype 
DROP TABLE #stock
DROP TABLE #employee


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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














/****** Object:  Stored Procedure dbo.gp_GetLendList    Script Date: 2002-6-20 10:14:57 ******/

/*
   使用多种条件获得单据明细
*/
CREATE     PROCEDURE gp_GetLendList
(
   @OperatorID		varchar(50),
   @BorrowOrLend	varchar(20)='',
   @BeginDate		varchar(20)='',
   @EndDate			varchar(20)='',
   @BTypeID			varchar(50)='',
   @PTypeID			varchar(50)='',
   @STypeId			varchar(max),
   @IsReporting		INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--SELECT	* 
--FROM	V_LendFace
--WHERE	BillDate >= @BeginDate 
--		AND BillDate <= CASE @EndDate WHEN '' THEN '3000-1-1' ELSE @EndDate END
--		AND bTypeID = CASE @BTypeID  WHEN '' THEN bTypeID ELSE @BTypeID END
--		AND pTypeID = CASE @PTypeID  WHEN '' THEN pTypeID ELSE @PTypeID END
--		AND 
--		(
--		BillType = CASE @BorrowOrLend WHEN 'Lend' THEN  87 WHEN '' THEN  87 ELSE 1 END
--		OR
--		BillType = CASE @BorrowOrLend WHEN 'Lend' THEN  88 WHEN '' THEN  88 ELSE 1 END
--		OR
--		BillType = CASE @BorrowOrLend WHEN 'Borrow' THEN  71 WHEN '' THEN  71 ELSE 1 END
--		OR
--		BillType = CASE @BorrowOrLend WHEN 'Borrow' THEN  72 WHEN '' THEN  72 ELSE 1 END
--		)
--		AND BTypeID IN (SELECT typeid FROM F_GetManDetailBtype(@OperatorID))
--		AND PTypeID IN (SELECT typeid FROM F_GetManDetailPtype(@OperatorID))
--		AND KTypeID IN (SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
--		AND ETypeID IN (SELECT typeid FROM F_GetManDetailEtype(@OperatorID))
--		AND STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID))

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
--	SELECT	* 
--	FROM	V_LendFace
--	WHERE	BillDate >= @BeginDate 
--			AND BillDate <= CASE @EndDate WHEN '' THEN '3000-1-1' ELSE @EndDate END
--			AND bTypeID = CASE @BTypeID  WHEN '' THEN bTypeID ELSE @BTypeID END
--			AND pTypeID = CASE @PTypeID  WHEN '' THEN pTypeID ELSE @PTypeID END
--			AND 
--			(
--			BillType = CASE @BorrowOrLend WHEN 'Lend' THEN  87 WHEN '' THEN  87 ELSE 1 END
--			OR
--			BillType = CASE @BorrowOrLend WHEN 'Lend' THEN  88 WHEN '' THEN  88 ELSE 1 END
--			OR
--			BillType = CASE @BorrowOrLend WHEN 'Borrow' THEN  71 WHEN '' THEN  71 ELSE 1 END
--			OR
--			BillType = CASE @BorrowOrLend WHEN 'Borrow' THEN  72 WHEN '' THEN  72 ELSE 1 END
--			)
--			AND BTypeID IN (SELECT typeid FROM F_GetManDetailBtype(@OperatorID))
--			AND PTypeID IN (SELECT typeid FROM F_GetManDetailPtype(@OperatorID))
--			AND KTypeID IN (SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
--			AND ETypeID IN (SELECT typeid FROM F_GetManDetailEtype(@OperatorID))
--			AND STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID))
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
	SELECT * INTO #Result FROM (
	-------------------------
	SELECT	* 
	FROM	V_LendFace
	WHERE	BillDate >= @BeginDate 
	        AND ifcheck='t'
			AND BillDate <= CASE @EndDate WHEN '' THEN '3000-1-1' ELSE @EndDate END
			AND bTypeID = CASE @BTypeID  WHEN '' THEN bTypeID ELSE @BTypeID END
			AND pTypeID = CASE @PTypeID  WHEN '' THEN pTypeID ELSE @PTypeID END
			AND 
			(
			BillType = CASE @BorrowOrLend WHEN 'Lend' THEN  87 WHEN '' THEN  87 ELSE 1 END
			OR
			BillType = CASE @BorrowOrLend WHEN 'Lend' THEN  88 WHEN '' THEN  88 ELSE 1 END
			OR
			BillType = CASE @BorrowOrLend WHEN 'Lend' THEN  11 WHEN '' THEN  11 ELSE 1 END
			OR
			BillType = CASE @BorrowOrLend WHEN 'Borrow' THEN  71 WHEN '' THEN  71 ELSE 1 END
			OR
			BillType = CASE @BorrowOrLend WHEN 'Borrow' THEN  72 WHEN '' THEN  72 ELSE 1 END
			OR
			BillType = CASE @BorrowOrLend WHEN 'Borrow' THEN  34 WHEN '' THEN  34 ELSE 1 END
			)
			AND BTypeID IN (SELECT typeid FROM F_GetManDetailBtype(@OperatorID))
			AND PTypeID IN (SELECT typeid FROM F_GetManDetailPtype(@OperatorID))
			AND KTypeID IN (SELECT typeid FROM F_GetManDetailKtype(@OperatorID))
			AND ETypeID IN (SELECT typeid FROM F_GetManDetailEtype(@OperatorID))
			AND STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID))
	) AS A
	
			SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
					  FROM #Result a  
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype  --CustomdetailID
					 LEFT JOIN Custom_BillDetails cd	  on a.billnumberid=cd.BillId and a.billtype=cd.billtype  AND a.CustomdetailID=cd.Detailid
				
				DROP TABLE #Result
			  


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





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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












/****** Object:  Stored Procedure dbo.gp_GetLendList    Script Date: 2002-6-20 10:14:57 ******/

/*
   得到各种包含权限的期初值
*/
CREATE    PROCEDURE gp_GetLimitLend00
(
   @OperatorID		varchar(50),
   @BTypeID			varchar(50)='',
   @PTypeID			varchar(50)='',
   @Type            varchar(10),		--期初种类
   @STypeId			varchar(max)		--分支机构
)
--@encode$--

AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

IF @Type='LendBorrow'          --借进借出
Begin
	SELECT	isnull(sum(qty),0) AS Qty,
			isnull(sum(Lend),0) AS Lend,
			isnull(sum(Borrow),0) AS Borrow 
	FROM	V_LendFace00 
	WHERE	1=1
			AND bTypeID = CASE @BTypeID  WHEN '' THEN bTypeID ELSE @BTypeID END
			AND pTypeID = CASE @PTypeID  WHEN '' THEN pTypeID ELSE @PTypeID END
			AND BTypeID IN (SELECT typeid FROM F_GetManDetailBtype(@OperatorID))
			AND PTypeID IN (SELECT typeid FROM F_GetManDetailPtype(@OperatorID))
			AND STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID))
End











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

















/****** Object:  Stored Procedure dbo.Gp_GetLoginUserList    Script Date: 2002-6-20 10:14:48 ******/

-- 返回 -1 往来单位名称不正确
CREATE    PROCEDURE Gp_GetLoginUserList 
(
  @BTypeName [varchar](66)='00000',
  @BTypeID [varchar](50)=''
)
--@encode$--
AS
set nocount on
DECLARE @SQLText [varchar] (2000)
DECLARE @BTYPEID_U [varchar](50)
IF @BTypeID = ''
IF @BTypeName <> '00000'
BEGIN
 SELECT  employee.FullName as 'fullname', employee.UserCode as 'usercode', 
         cast(loginuser.password as varchar(10)) as 'password', 
         loginuser.etypeid, loginuser.lim,loginuser.BtypeId as 'btypeid'
 FROM employee RIGHT OUTER JOIN
       loginuser ON (employee.typeId = loginuser.etypeid)
            INNER JOIN (SELECT typeid
   FROM btype
   WHERE fullname=@BTypeName and deleted=0)AS c
  ON (employee.btypeid = c.typeid)
 ORDER BY loginuser.etypeid
 RETURN 0
END
IF @BTypeID = ''
IF @BTypeName = '00000' 
 SELECT @BTYPEID_U='00000'
IF @BTypeID <> ''
 SELECT @BTYPEID_U=@BTypeID
--  建立临时表
DECLARE @TableName [varchar] (500)
 Select @TableName='Web2'+convert(varchar(2),datepart(dd,GetDate()))+convert(varchar(2),datepart(hh,GetDate()))+convert(varchar(2),datepart(m,GetDate()))+convert(varchar(2),datepart(s,GetDate()))+convert(varchar(4),datepart(ms,GetDate()))
 Select @SQLText='Create Table '+N'##'+@TableName+'([FullName] [varchar] (66) NULL ,[UserCode] [varchar] (26) NULL ,[password] [varchar] (20) NULL ,[etypeid] [varchar] (50) NULL ,[lim] [binary] (2000) NULL ,[BTypeID] [varchar] (50) NULL ,[btypename] [varchar] (200) NULL , )'
 Exec(@SQLText)
 if @@error<>0
 begin
  --RAISERROR('创建临时表发生错误！',16,1)
  return -1
 end
 
-- 临时表插入数据
Select @SQLText = 'Insert into '+N'##'+@TableName +'([FullName],[UserCode],[password],[etypeid],[lim],[BTypeID],[btypename])'
        +' SELECT  employee.FullName as ''fullname'', employee.UserCode as ''usercode'', '
 +'        cast(loginuser.password as varchar(10)) as ''password'','
 +'        loginuser.etypeid, loginuser.lim,loginuser.BtypeId as ''btypeid'','
 +'  loginuser.mangerbtypeid as ''btypename'''
 +' FROM employee RIGHT OUTER JOIN'
  +'     loginuser ON employee.typeId = loginuser.etypeid'
 +' WHERE loginuser.BtypeId='''+@BTYPEID_U+''''
 +' ORDER BY loginuser.etypeid'
Exec(@SQLText)
--print @SQLText
if @@error<>0
   begin
    --RAISERROR('插入临时表记录出错！',16,1)
    return -3
   end
-- 建立游标
SELECT @SQLText = 'Declare My_Cursor CURSOR For Select btypename from '+N'##'+@TableName+' For UPDATE OF btypename'
Exec(@SQLText)
Open My_Cursor
DECLARE @EID [varchar] (50)
DECLARE @BNAME [varchar] (200)
Fetch Next From My_Cursor Into @EID
While @@Fetch_status=0
Begin
 exec Web_GetParentPath1 @EID,2,@BNAME output
 SELECT @SQLText = 'update '+N'##'+@TableName+' set btypename='''+@BNAME+''' WHERE CURRENT OF My_Cursor'
 Exec(@SQLText)
 Fetch Next From My_Cursor Into @EID
end 
Close My_Cursor
Deallocate My_Cursor
-- 返回结果
SELECT @SQLText = 'Select * from '+N'##'+@TableName
Exec(@SQLText)
-- 删除临时表
SELECT @SQLText = 'drop table '+N'##'+@TableName
Exec(@SQLText)


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：黄清	
	日期：2013-05-23	
	描述：取权限范围内分支机构财务期间信息--状态栏显示
*/
CREATE PROCEDURE Gp_GetManStypeFPeriod
(
	@OperatorId VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON
EXEC('EXEC Web_QueryTabTr')

DECLARE @FPeriod		 INT,			--财务结账
		@FMonth			 INT
		

CREATE TABLE #STYPE (TypeId VARCHAR(50),FullName VARCHAR(200),VerifyID VARCHAR(50),Vfullname VARCHAR(200))
INSERT INTO #STYPE(TypeId,FullName,VerifyID,Vfullname)
SELECT F.TypeId,S.FullName,f.TypeId,s.FullName FROM F_GetManDetailSType(@OperatorId) F
INNER JOIN SType S ON S.TypeId=F.TypeId
WHERE IsSelfVerify=1

IF NOT EXISTS (SELECT *FROM #STYPE WHERE TypeId IN (SELECT S.VerifyID FROM employee E INNER JOIN SType S ON S.TypeId=E.STypeID WHERE E.TypeId=@OperatorId))
	INSERT INTO #STYPE(TypeId,FullName,VerifyID,Vfullname)
	SELECT S.TypeId,S.FullName,V.TypeId,V.FullName FROM SType S
	INNER JOIN SType V ON S.VerifyID=V.TypeId
	 WHERE S.TypeId IN  (SELECT STypeID FROM employee WHERE TypeId=@OperatorId)

IF EXISTS (SELECT *FROM employee E INNER JOIN SType S ON S.TypeId=E.STypeID WHERE S.IsSelfVerify='0')
BEGIN
	UPDATE #STYPE
	SET FullName=S.FullName
	FROM SType S
	INNER JOIN employee E ON S.TypeId=E.STypeID
	 WHERE S.VerifyID=#STYPE.TypeId
	AND E.typeId=@OperatorId
END
	
--获取开账期间
SELECT	TOP 1
		@FMonth = SubValue 
FROM	sysdata 
WHERE	SubName = 'FMonth'		


SELECT @FPeriod = SubValue FROM sysdata WHERE SubName = 'FPeriod'		

--获取指定分支机构当前财务期间		
SELECT	CASE WHEN FPeriod IS NULL THEN @FMonth
			 ELSE FPeriod END
				  AS fPeriod,
		S.FullName AS sfullname,
		S.Vfullname	as vfullname
FROM dbo.Ac_AccountsPeroid_Stype A 
RIGHT JOIN #SType S ON S.TypeId=A.Stypeid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_GetMsg_LackBatchQty]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_GetMsg_LackBatchQty]
GO




/*

功能说明：		库存不足(手工指定法)

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_GetMsg_LackBatchQty]
(
	@intRe					INT,					--过账返回的出错代号
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
)
--@encode$--        
AS

IF @intBillType NOT IN (11,305,17,21,187,140)
	RETURN

DECLARE
	@AllowNegativeStock	INT,
	@Costing			INT

EXEC GP_GetSubValue 'AllowNegativeStock', '',@AllowNegativeStock OUTPUT

EXEC GP_GetSubValue 'Costing', '',@Costing OUTPUT

--生成一个临时表
CREATE TABLE #table(
	PTypeID				VARCHAR(50),
	KTypeID				VARCHAR(50),
	Qty					 NUMERIC(24, 10) ,
	GoodsNumber			VARCHAR(100),
	ProduceDate			VARCHAR(50),
	ValidDate			VARCHAR(50),
	GoodsBTypeID		VARCHAR(50),
	GoodsCostPrice		 NUMERIC(24, 10) 
)



IF @intBillType=11
BEGIN
	INSERT #table
	SELECT PTypeID,KTypeID,SUM(Qty),GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,ROUND(GoodsCostPrice,4)
	FROM SaleBill a
	INNER JOIN PTYPE b
	ON a.PtypeId=b.typeId
	WHERE BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,ROUND(GoodsCostPrice,4)
END
ELSE IF @intBillType=305
BEGIN
	INSERT #table
	SELECT a.PTypeID,b.KTypeID,SUM(a.Qty),a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
	FROM retailBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PTypeID,b.KTypeID,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
END
ELSE IF @intBillType=17
BEGIN
	INSERT #table
	SELECT a.PTypeID,b.KTypeID,SUM(Qty),a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
	FROM MoveBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PTypeID,b.KTypeID,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
END
ELSE IF @intBillType=21
BEGIN
	INSERT #table
	SELECT a.PTypeID,b.KTypeID,SUM(Qty),a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
	FROM MoveBjBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PTypeID,b.KTypeID,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
END
ELSE IF @intBillType=108
BEGIN
	INSERT #table
	SELECT a.PTypeID,a.KTypeID,SUM(Qty),a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
	FROM CommissionBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PTypeID,a.KTypeID,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
END
ELSE IF @intBillType=187
BEGIN
	INSERT #table
	SELECT a.PTypeID,a.KTypeID,SUM(Qty),a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
	FROM STypeMoveBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PTypeID,a.KTypeID,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.GoodsBTypeID,ROUND(a.GoodsCostPrice,4)
END
ELSE IF @intBillType=140
BEGIN
	INSERT #table
	SELECT PTypeID,KTypeID,SUM(Qty),GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,ROUND(GoodsCostPrice,4)
	FROM CommissionBill a
	INNER JOIN PTYPE b
	ON a.PtypeId=b.typeId
	WHERE BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,ROUND(GoodsCostPrice,4)
END

/*
INSERT #AuditGetResult
SELECT c.FullName AS PFullName,d.FullName AS KFullName,a.PTypeID,a.KTypeID,a.Qty AS BillQty,b.Qty
FROM #table a
LEFT JOIN
(
	SELECT a.PtypeId,a.KtypeId,b.Qty,b.GoodsNumber,b.ProduceDate,b.ValidDate,b.GoodsBTypeID,b.Price
	FROM #table a
	INNER JOIN GoodsStocks b
	ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
	GROUP BY a.PtypeId,a.KtypeId,b.GoodsNumber,b.ProduceDate,b.ValidDate,b.GoodsBTypeID,b.Price,b.Qty
) b
ON a.PTypeID=b.PtypeId 
AND a.KTypeID=b.KtypeId
AND a.GoodsNumber=b.GoodsNumber
AND a.ProduceDate=b.ProduceDate
AND a.ValidDate=b.ValidDate
AND a.GoodsBTypeID=b.GoodsBTypeID
AND a.GoodsCostPrice=b.Price
INNER JOIN PType c
ON a.PTypeID=c.typeId
INNER JOIN Stock d
ON a.KTypeID=d.typeId
WHERE a.Qty>ISNULL(b.Qty,0)
*/

INSERT #AuditGetResult
SELECT a.PTypeID,a.KTypeID,a.Qty AS BillQty,b.Qty
FROM #table a
LEFT JOIN
(
	SELECT a.PtypeId,a.KtypeId,b.Qty,b.GoodsNumber,b.ProduceDate,b.ValidDate,b.GoodsBTypeID,b.Price
	FROM #table a
	INNER JOIN GoodsStocks b
	ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
	GROUP BY a.PtypeId,a.KtypeId,b.GoodsNumber,b.ProduceDate,b.ValidDate,b.GoodsBTypeID,b.Price,b.Qty
) b
ON a.PTypeID=b.PtypeId 
AND a.KTypeID=b.KtypeId
AND a.GoodsNumber=b.GoodsNumber
AND a.ProduceDate=b.ProduceDate
AND a.ValidDate=b.ValidDate
AND a.GoodsBTypeID=b.GoodsBTypeID
AND a.GoodsCostPrice=b.Price
WHERE a.Qty>ISNULL(b.Qty,0)




DROP TABLE #table

GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_GetMsg_LackQty]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_GetMsg_LackQty]
GO




/*

功能说明：		库存不足(非手工指定法)

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_GetMsg_LackQty]
(
	@intRe					INT,					--过账返回的出错代号
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
)
--@encode$--        
AS

IF @intBillType NOT IN (11,305,17,21,187,140)
	RETURN

DECLARE
	@AllowNegativeStock	INT,
	@Costing			INT

EXEC GP_GetSubValue 'AllowNegativeStock', '',@AllowNegativeStock OUTPUT

EXEC GP_GetSubValue 'Costing', '',@Costing OUTPUT


--生成一个临时表
CREATE TABLE #table(
	PTypeID		VARCHAR(100),
	KTypeID		VARCHAR(100),
	Qty			 NUMERIC(24, 10) 
)

IF @intBillType=11
BEGIN
	INSERT #table
	SELECT PTypeID,KTypeID,SUM(Qty)
	FROM SaleBill a
	INNER JOIN PTYPE b
	ON a.PtypeId=b.typeId
	WHERE BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY PtypeId,KTypeID
END
ELSE IF @intBillType=305
BEGIN
	INSERT #table
	SELECT a.PTypeID,b.KTypeID,SUM(Qty)
	FROM retailBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	
	GROUP BY a.PtypeId,b.KTypeID
END
ELSE IF @intBillType=17
BEGIN
	INSERT #table
	SELECT a.PTypeID,b.KTypeID,SUM(Qty)
	FROM MoveBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PtypeId,b.KTypeID
END
ELSE IF @intBillType=21
BEGIN
	INSERT #table
	SELECT a.PTypeID,b.KTypeID,SUM(Qty)
	FROM MoveBjBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PtypeId,b.KTypeID
END
ELSE IF @intBillType=187
BEGIN
	INSERT #table
	SELECT a.PTypeID,a.KTypeID,SUM(Qty)
	FROM STypeMoveBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PtypeId,a.KTypeID
END
ELSE IF @intBillType=140
BEGIN
	INSERT #table
	SELECT a.PTypeID,a.KTypeID,SUM(Qty)
	FROM CommissionBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	INNER JOIN PTYPE c
	ON a.PtypeId=c.typeId
	WHERE a.BillNumberId=@intBillNumberID AND IsService=0
	GROUP BY a.PtypeId,a.KTypeID
END


/*
IF @AllowNegativeStock=0 OR @Costing IN (1,2)
BEGIN
	--#table是按PTypeID,KTypeID进行了汇总的
	

	INSERT #AuditGetResult
	SELECT c.FullName AS PFullName,d.FullName AS KFullName,
	a.PTypeID,a.KTypeID,a.Qty AS BillQty,b.Qty
	FROM #table a
	LEFT JOIN
	(
		SELECT a.PtypeId,a.KtypeId,ISNULL(SUM(b.Qty),0) AS Qty
		FROM #table a
		LEFT JOIN GoodsStocks b
		ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
		GROUP BY a.PtypeId,a.KtypeId
	) b
	ON a.PTypeID=b.PtypeId AND a.KTypeID=b.KtypeId
	INNER JOIN PType c
	ON a.PTypeID=c.typeId
	INNER JOIN Stock d
	ON a.KTypeID=d.typeId
	WHERE a.Qty>ISNULL(b.Qty,0)
END
*/

IF @AllowNegativeStock=0 OR @Costing IN (1,2)
BEGIN
	--#table是按PTypeID,KTypeID进行了汇总的
	
	INSERT #AuditGetResult
	SELECT a.PTypeID,a.KTypeID,a.Qty AS BillQty,b.Qty
	FROM #table a
	LEFT JOIN
	(
		SELECT a.PtypeId,a.KtypeId,ISNULL(SUM(b.Qty),0) AS Qty
		FROM #table a
		LEFT JOIN GoodsStocks b
		ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
		GROUP BY a.PtypeId,a.KtypeId
	) b
	ON a.PTypeID=b.PtypeId AND a.KTypeID=b.KtypeId
	WHERE a.Qty>ISNULL(b.Qty,0)
END


DROP TABLE #table

GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_GetMsg_StockLack]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_GetMsg_StockLack]
GO




/*

功能说明：		先生成库存不足的信息

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_GetMsg_StockLack]
(
	@intRe					INT,					--过账返回的出错代号(-1表示库存不足;序列号部分还在做)
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
)
--@encode$--        
AS


IF @intBillType NOT IN (11,305,17,21,187,108,140)
	RETURN

DECLARE
	@AllowNegativeStock	INT,
	@Costing			INT

EXEC GP_GetSubValue 'AllowNegativeStock', '',@AllowNegativeStock OUTPUT

EXEC GP_GetSubValue 'Costing', '',@Costing OUTPUT

IF @Costing=3
BEGIN
	--手工指定法的处理
	EXEC GP_GetMsg_LackBatchQty
		@intRe,
		@intBillType,
		@intBillNumberID
END
ELSE IF @AllowNegativeStock=0 OR @Costing IN (1,2)
BEGIN
	EXEC GP_GetMsg_LackQty
		@intRe,
		@intBillType,
		@intBillNumberID
END


GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	入库为单据提供成本价（非手工指定法）
	作    者：	冯波
	修改时间：	
	
	需要确认的：
*/
CREATE             PROCEDURE Gp_GetNowCostPrice_In
(
	@chvPTypeID				varchar(50),
	@chvKTypeID				varchar(50)
	
)
--@encode$--
AS
BEGIN
	DECLARE
		@nCostingMethod		INT
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod OUT
	
	--价格小数位
	DECLARE @priceDigit INT
	
	SELECT @priceDigit = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName = 'price'
	
	DECLARE	
		@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint
	

	SET @AVERAGE	= 0		-- 移动加权平均算法
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	SET @HAND		= 3		-- 手工指定
		
	DECLARE
		@decTempPrice		 NUMERIC(24, 10) ,
		@chvSTypeID			VARCHAR(50)
		
	SELECT
		@decTempPrice=0
			

	CREATE TABLE #NowCost(
		Price	 NUMERIC(24, 10) 
	)
	
	DECLARE
		@intGetCurPrice		INT
		
	SELECT
		@intGetCurPrice=0
		
	IF @nCostingMethod=@AVERAGE
	BEGIN
		IF NOT EXISTS(
			SELECT Price
			FROM GoodsStocks
			WHERE PtypeId=@chvPTypeID AND KtypeId=@chvKTypeID
		)
		BEGIN--移动平均，没有仓库相关成本，就读物价信息
			SELECT
				@intGetCurPrice=1
		END
	END
	ELSE
	BEGIN--非移动平均，读物价信息
		SELECT
			@intGetCurPrice=1
	END
	
			--取最近
		SELECT @chvSTypeID=STypeID
		FROM Stock
		WHERE typeId=@chvKTypeID
	
	--分支机构适用物价信息,1为分支机构物价信息
	DECLARE @ifStype INT
	SELECT @ifStype = PriceType FROM dbo.SType WHERE TypeId = @chvSTypeID

	IF @intGetCurPrice=1
	BEGIN
		IF @ifStype = 1
		BEGIN
			INSERT #NowCost(Price)
			SELECT ROUND(PS.RecPrice,@priceDigit)
			FROM dbo.PType_STypePrice PS
			INNER JOIN ptype P ON PS.PTypeID=P.TypeID AND PS.UnitID=P.BaseUnitID
			WHERE PS.STypeID=@chvSTypeID
			AND PS.PTypeID=@chvPTypeID
			
			IF NOT EXISTS(SELECT TOP 1 1 FROM #NowCost)
				INSERT #NowCost(Price)
				SELECT ROUND(RecPrice,@priceDigit)
				FROM dbo.ptype
				WHERE TypeID=@chvPTypeID
		END
		ELSE
			INSERT #NowCost(Price)
			SELECT ROUND(PS.RecPrice,@priceDigit)
			FROM dbo.PType_STypePrice PS
			INNER JOIN ptype P ON PS.PTypeID=P.TypeID AND PS.UnitID=P.BaseUnitID
			WHERE PS.STypeID=@chvSTypeID
			AND PS.PTypeID=@chvPTypeID
	END
	ELSE
	BEGIN
		INSERT #NowCost(Price)
		SELECT CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(Total) AS  NUMERIC(24, 10) )/CAST(SUM(Qty) AS  NUMERIC(24, 10) ),@priceDigit) END AS Price
		FROM GoodsStocks
		WHERE PtypeId=@chvPTypeID AND KtypeId=@chvKTypeID
		GROUP BY PtypeId,KTypeID
	END

	
	SELECT *
	FROM #NowCost
	
	DROP TABLE #NowCost
END
	

	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	出库为单据提供成本价（非手工指定法）
	作    者：	冯波
	修改时间：	
	
*/
CREATE             PROCEDURE Gp_GetNowCostPrice_Out
(
	@chvPTypeID				varchar(50),
	@chvKTypeID				varchar(50),
	@decQty					 NUMERIC(24, 10) 
	
)
--@encode$--
AS
BEGIN
	DECLARE
		@nCostingMethod		INT
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod OUT
	
	
	DECLARE	
		@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		SMALLINT
	
	--读取配置小数位
	DECLARE
		@PriceDigit INT,
		@TotalDigit INT
	
	SELECT @PriceDigit = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName = 'price'
	SELECT @TotalDigit = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName = 'total'
	

	SET @AVERAGE	= 0		-- 移动加权平均算法
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	
	DECLARE
		@decTempPrice		 NUMERIC(24, 10) ,
		@decTempQty			 NUMERIC(24, 10) ,
		@decTemMoney		 NUMERIC(24, 10) ,
		@decOldQty			 NUMERIC(24, 10) ,
		@decCurQty			 NUMERIC(24, 10) ,
		@decCurPrice		 NUMERIC(24, 10) ,
		@decCurMoney		 NUMERIC(24, 10) ,
		@intCurGoodsOrder	INT,
		@i					INT,
		@decAllQty			 NUMERIC(24, 10) ,
		@decInputQty		 NUMERIC(24, 10) 
		
		
	SELECT
		@decInputQty=@decQty,
		@decTempPrice=0,
		@decTempQty=0,
		@decTemMoney=0,
		@i=0,
		@decOldQty=@decQty
		
	CREATE TABLE #GoodsStocks(
		Qty				 NUMERIC(24, 10) ,
		Price			 NUMERIC(24, 10) ,
		Total			 NUMERIC(24, 10) ,
		GoodsOrder		INT
	)
		
	CREATE TABLE #NowCost(
		Price	 NUMERIC(24, 10) ,
		Total	 NUMERIC(24, 10) 
	)
	
	IF @decQty=0
	BEGIN
		SELECT * FROM #NowCost
		RETURN
	END
	
		
	IF NOT EXISTS(
		SELECT Price
		FROM GoodsStocks
		WHERE PtypeId=@chvPTypeID AND KtypeId=@chvKTypeID
	)
	BEGIN
		SELECT * FROM #NowCost
		DROP TABLE #NowCost
		DROP TABLE #GoodsStocks
		RETURN
	END
	
	INSERT #GoodsStocks(Qty,Price,Total,GoodsOrder)
	SELECT Qty,Price,Total,GoodsOrder
	FROM GoodsStocks
	WHERE PtypeId=@chvPTypeID AND KtypeId=@chvKTypeID
	
	SELECT @decAllQty=ISNULL(SUM(Qty),0)
	FROM #GoodsStocks
	
	SELECT @decAllQty=ISNULL(@decAllQty,0)
	
	IF @nCostingMethod=@AVERAGE
	BEGIN
		
		SELECT @decCurQty=Qty,@decCurPrice=Price,@decCurMoney=Total
		FROM #GoodsStocks
		
		
		IF @decQty=@decCurQty
		BEGIN
			INSERT #NowCost(Price,Total)
			SELECT ROUND(@decCurPrice,@PriceDigit),ROUND(@decCurMoney,@TotalDigit)
		END
		ELSE
		BEGIN
			INSERT #NowCost(Price,Total)
			SELECT ROUND(@decCurPrice,@PriceDigit),ROUND(@decCurPrice*@decQty,@TotalDigit)
		END
		
		SELECT @decTempPrice=@decCurPrice
	END
	ELSE IF @nCostingMethod=@FIFO
	BEGIN
		WHILE @decQty>0
		BEGIN
			IF NOT EXISTS(
				SELECT GoodsOrder
				FROM #GoodsStocks
				WHERE Qty<>0
			)
			BEGIN		
				SELECT 
					@decCurQty=0,
					@decQty=0,
					@decCurMoney=0
				
			END
			ELSE
			BEGIN
				SELECT @decCurQty=Qty,@decCurPrice=Price,@decCurMoney=Total,@intCurGoodsOrder=GoodsOrder
				FROM #GoodsStocks
				WHERE  Qty<>0
				AND GoodsOrder
				IN
				(
					SELECT MIN(GoodsOrder) AS GoodsOrder
					FROM #GoodsStocks
					WHERE Qty<>0
				)
			END
			SELECT @i=@i+1
			
			IF @decCurQty>@decQty
			BEGIN
				SELECT 
					@decTemMoney=@decTemMoney+@decQty*@decCurPrice,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decQty,
					@decQty=0
			END
			ELSE IF @decCurQty=@decQty
			BEGIN
				SELECT
					@decTemMoney=@decTemMoney+@decCurMoney,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decQty,
					@decQty=0
			END
			ELSE
			BEGIN
				SELECT 
					@decTemMoney=@decTemMoney+@decCurQty*@decCurPrice,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decCurQty,
					@decQty=@decQty-@decCurQty
					
				UPDATE #GoodsStocks
				SET Qty=0
				WHERE GoodsOrder=@intCurGoodsOrder
			END	
		END
		
		IF @i<>1
		BEGIN
			SELECT @decTempPrice=ROUND(@decTemMoney/@decTempQty,@PriceDigit)
		END
		
	END
	ELSE IF @nCostingMethod=@LIFO
	BEGIN
	
		WHILE @decQty>0
		BEGIN
			IF NOT EXISTS(
				SELECT GoodsOrder
				FROM #GoodsStocks
				WHERE Qty<>0
			)
			BEGIN		
				SELECT 
					@decCurQty=0,
					@decQty=0,
					@decCurMoney=0
				
			END
			ELSE
			BEGIN
				SELECT @decCurQty=Qty,@decCurPrice=Price,@decCurMoney=Total,@intCurGoodsOrder=GoodsOrder
				FROM #GoodsStocks
				WHERE Qty<>0
				AND GoodsOrder
				IN
				(
					SELECT MAX(GoodsOrder) AS GoodsOrder
					FROM #GoodsStocks
					WHERE Qty<>0
				)
			END
			
			SELECT @i=@i+1
			
			IF @decCurQty>@decQty
			BEGIN
				SELECT 
					@decTemMoney=@decTemMoney+@decQty*@decCurPrice,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decQty,
					@decQty=0
			END
			ELSE IF @decCurQty=@decQty
			BEGIN
				SELECT
					@decTemMoney=@decTemMoney+@decCurMoney,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decQty,
					@decQty=0
			END
			ELSE
			BEGIN
				SELECT 
					@decTemMoney=@decTemMoney+@decCurQty*@decCurPrice,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decCurQty,
					@decQty=@decQty-@decCurQty
					
				UPDATE #GoodsStocks
				SET Qty=0
				WHERE GoodsOrder=@intCurGoodsOrder
			END	
		END

		IF @i<>1
		BEGIN
			SELECT @decTempPrice=ROUND(@decTemMoney/@decTempQty,@PriceDigit)
		END
	END
	
	IF @nCostingMethod IN (@LIFO,@FIFO)
	BEGIN
		IF @decQty=0
		BEGIN
			INSERT #NowCost(Price,Total)
			SELECT ROUND(@decTempPrice,@PriceDigit),ROUND(@decTemMoney,@TotalDigit)
		END
		ELSE
		BEGIN
			INSERT #NowCost(Price,Total)
			SELECT ROUND(@decTempPrice,@PriceDigit),ROUND(@decTempPrice*@decOldQty,@TotalDigit)
		END
	END
	
	
	IF @decAllQty<@decInputQty
	BEGIN
		--如果超出，则用价格来算金额
		UPDATE #NowCost
		SET Total=ISNULL(@decTempPrice*@decInputQty,@TotalDigit)
	END
	
	SELECT *
	FROM #NowCost
	
	DROP TABLE #NowCost
END
	

	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


CREATE             PROCEDURE Gp_GetNowCostPrice_OutByPtypes
(
	@chvPTypeID				varchar(50),
	@chvPTypeName			varchar(500),
	@chvKTypeID				varchar(50),
	@decQty					 NUMERIC(24, 10) ,
	@totaldata               NUMERIC(24, 10)     OUTPUT
	
)
--@encode$--
AS
BEGIN
	DECLARE
		@nCostingMethod		INT
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod OUT
	
	
	DECLARE	
		@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint
	

	SET @AVERAGE	= 0		-- 移动加权平均算法
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	
	DECLARE
		@decTempPrice		 NUMERIC(24, 10) ,
		@decTempQty			 NUMERIC(24, 10) ,
		@decTemMoney		 NUMERIC(24, 10) ,
		@decOldQty			 NUMERIC(24, 10) ,
		@decCurQty			 NUMERIC(24, 10) ,
		@decCurPrice		 NUMERIC(24, 10) ,
		@decCurMoney		 NUMERIC(24, 10) ,
		@intCurGoodsOrder	INT,
		@i					INT,
		@decAllQty			 NUMERIC(24, 10) ,
		@decInputQty		 NUMERIC(24, 10) 
		
		
	SELECT
		@decInputQty=@decQty,
		@decTempPrice=0,
		@decTempQty=0,
		@decTemMoney=0,
		@i=0,
		@decOldQty=@decQty
		
	CREATE TABLE #GoodsStocks(
		Qty				 NUMERIC(24, 10) ,
		Price			 NUMERIC(24, 10) ,
		Total			 NUMERIC(24, 10) ,
		GoodsOrder		INT
	)
		
	CREATE TABLE #NowCost(
		Price	 NUMERIC(24, 10) ,
		Total	 NUMERIC(24, 10) 
	)
	
	IF @decQty=0
	BEGIN
		SELECT * FROM #NowCost
		RETURN
	END
	
		DECLARE
		@str		varchar(500)
	
	
		
	IF NOT EXISTS(
		SELECT Price
		FROM GoodsStocks
		WHERE PtypeId=@chvPTypeID AND KtypeId=@chvKTypeID
	)
	BEGIN
	  
	  SELECT * FROM #NowCost
	  DROP TABLE #NowCost
	  DROP TABLE #GoodsStocks
	  SET @str='商品：'+@chvPTypeName+'没有库存不能进行本单毛利的操作'
	  RAISERROR(@str,16,1)
      RETURN -1
	END
	
	INSERT #GoodsStocks(Qty,Price,Total,GoodsOrder)
	SELECT Qty,Price,Total,GoodsOrder
	FROM GoodsStocks
	WHERE PtypeId=@chvPTypeID AND KtypeId=@chvKTypeID
	
	SELECT @decAllQty=ISNULL(SUM(Qty),0)
	FROM #GoodsStocks
	
	SELECT @decAllQty=ISNULL(@decAllQty,0)
	
	IF @nCostingMethod=@AVERAGE
	BEGIN
		
		SELECT @decCurQty=Qty,@decCurPrice=Price,@decCurMoney=Total
		FROM #GoodsStocks
		
		
		IF @decQty=@decCurQty
		BEGIN
			INSERT #NowCost(Price,Total)
			SELECT ROUND(@decCurPrice,4),ROUND(@decCurMoney,2)
		END
		ELSE
		BEGIN
			INSERT #NowCost(Price,Total)
			SELECT ROUND(@decCurPrice,4),ROUND(@decCurPrice*@decQty,2)
		END
		
		SELECT @decTempPrice=@decCurPrice
	END
	ELSE IF @nCostingMethod=@FIFO
	BEGIN
		WHILE @decQty>0
		BEGIN
			IF NOT EXISTS(
				SELECT GoodsOrder
				FROM #GoodsStocks
				WHERE Qty<>0
			)
			BEGIN		
				SELECT 
					@decCurQty=0,
					@decQty=0,
					@decCurMoney=0
				
			END
			ELSE
			BEGIN
				SELECT @decCurQty=Qty,@decCurPrice=Price,@decCurMoney=Total,@intCurGoodsOrder=GoodsOrder
				FROM #GoodsStocks
				WHERE  Qty<>0
				AND GoodsOrder
				IN
				(
					SELECT MIN(GoodsOrder) AS GoodsOrder
					FROM #GoodsStocks
					WHERE Qty<>0
				)
			END
			SELECT @i=@i+1
			
			IF @decCurQty>@decQty
			BEGIN
				SELECT 
					@decTemMoney=@decTemMoney+@decQty*@decCurPrice,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decQty,
					@decQty=0
			END
			ELSE IF @decCurQty=@decQty
			BEGIN
				SELECT
					@decTemMoney=@decTemMoney+@decCurMoney,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decQty,
					@decQty=0
			END
			ELSE
			BEGIN
				SELECT 
					@decTemMoney=@decTemMoney+@decCurQty*@decCurPrice,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decCurQty,
					@decQty=@decQty-@decCurQty
					
				UPDATE #GoodsStocks
				SET Qty=0
				WHERE GoodsOrder=@intCurGoodsOrder
			END	
		END
		
		IF @i<>1
		BEGIN
			SELECT @decTempPrice=ROUND(@decTemMoney/@decTempQty,4)
		END
		
	END
	ELSE IF @nCostingMethod=@LIFO
	BEGIN
	
		WHILE @decQty>0
		BEGIN
			IF NOT EXISTS(
				SELECT GoodsOrder
				FROM #GoodsStocks
				WHERE Qty<>0
			)
			BEGIN		
				SELECT 
					@decCurQty=0,
					@decQty=0,
					@decCurMoney=0
				
			END
			ELSE
			BEGIN
				SELECT @decCurQty=Qty,@decCurPrice=Price,@decCurMoney=Total,@intCurGoodsOrder=GoodsOrder
				FROM #GoodsStocks
				WHERE Qty<>0
				AND GoodsOrder
				IN
				(
					SELECT MAX(GoodsOrder) AS GoodsOrder
					FROM #GoodsStocks
					WHERE Qty<>0
				)
			END
			
			SELECT @i=@i+1
			
			IF @decCurQty>@decQty
			BEGIN
				SELECT 
					@decTemMoney=@decTemMoney+@decQty*@decCurPrice,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decQty,
					@decQty=0
			END
			ELSE IF @decCurQty=@decQty
			BEGIN
				SELECT
					@decTemMoney=@decTemMoney+@decCurMoney,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decQty,
					@decQty=0
			END
			ELSE
			BEGIN
				SELECT 
					@decTemMoney=@decTemMoney+@decCurQty*@decCurPrice,
					@decTempPrice=@decCurPrice,
					@decTempQty=@decTempQty+@decCurQty,
					@decQty=@decQty-@decCurQty
					
				UPDATE #GoodsStocks
				SET Qty=0
				WHERE GoodsOrder=@intCurGoodsOrder
			END	
		END

		IF @i<>1
		BEGIN
			SELECT @decTempPrice=ROUND(@decTemMoney/@decTempQty,4)
		END
	END
	
	IF @nCostingMethod IN (@LIFO,@FIFO)
	BEGIN
		IF @decQty=0
		BEGIN
			INSERT #NowCost(Price,Total)
			SELECT ROUND(@decTempPrice,4),ROUND(@decTemMoney,2)
		END
		ELSE
		BEGIN
			INSERT #NowCost(Price,Total)
			SELECT ROUND(@decTempPrice,4),ROUND(@decTempPrice*@decOldQty,2)
		END
	END
	
	
	IF @decAllQty<@decInputQty
	BEGIN
		--如果超出，则用价格来算金额
		UPDATE #NowCost
		SET Total=ISNULL(@decTempPrice*@decInputQty,2)
	END
	
	SELECT @totaldata=Total
	FROM #NowCost
	

	
	
	
	DROP TABLE #NowCost
	

END
	

	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


CREATE             PROCEDURE Gp_GetNowCostPrice_OutByPtypesTotal
(
	@PTypeIDs				varchar(500),
	@PTypeNames				varchar(500),
	@KTypeIDs				varchar(500),
	@Qtys					varchar(500)
	
)
--@encode$--
AS
BEGIN

--得到需要处理的数据
CREATE TABLE #PTypeIDs
(
    nID int identity(1,1),
	ptypeid	varchar(100)
)

CREATE TABLE #PTypeNames
(
    nID int identity(1,1),
	ptypename	varchar(500)
)

CREATE TABLE #Qtys
(
    nID int identity(1,1),
	qty	varchar(100)
)

CREATE TABLE #KTypeIDs
(
    nID int identity(1,1),
	ktypeid	varchar(100)
)

INSERT INTO #PTypeIDs
SELECT	*
FROM 	F_Split(@PTypeIDs,'|')
INSERT INTO #PTypeNames
SELECT	*
FROM 	F_Split(@PTypeNames,'|')
INSERT INTO #Qtys
SELECT	*
FROM 	F_Split(@Qtys,'|')
INSERT INTO #KTypeIDs
SELECT	*
FROM 	F_Split(@KTypeIDs,',')

--程序部分(游标)

DECLARE 
		@TCptypeid		        varchar(100),
		@TCqty		            varchar(100),
		@TCptypename		    varchar(100),
		@TCktypeid		        varchar(100),
        @nCostprice	             NUMERIC(24, 10) ,
        @nCostpriceTotal         NUMERIC(24, 10) 
        
SET @nCostpriceTotal=0
DECLARE TC CURSOR FOR
	SELECT p.ptypeid,q.qty,n.ptypename,k.ktypeid
	FROM #PTypeIDs p
	LEFT JOIN #Qtys q ON q.nid=p.nID
	LEFT JOIN #PTypeNames n on n.nid=p.nID
	LEFT JOIN #KTypeIDs k on k.nid=p.nID
    ORDER BY p.nID ASC

OPEN TC
FETCH NEXT FROM TC INTO @TCptypeid,@TCqty,@TCptypename,@TCktypeid

WHILE @@FETCH_STATUS = 0
	BEGIN
	--获取每一个商品的成本单价的和
	exec Gp_GetNowCostPrice_OutByPtypes @TCptypeid,@TCptypename ,@TCktypeid,@TCqty,@nCostprice out
	SET @nCostpriceTotal=@nCostpriceTotal+ CAST( ISNULL(@nCostprice,0) AS  NUMERIC(24, 10) ) 
	FETCH NEXT FROM TC INTO @TCptypeid,@TCqty,@TCptypename,@TCktypeid
	END
END

CLOSE TC
DEALLOCATE TC
DROP TABLE #PTypeIDs,#Qtys

select @nCostpriceTotal as CostpriceTotal

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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














CREATE   PROCEDURE [Gp_GetOtherBillCode]     --得到正规单据编外的单据编号   肖伟  2002-7-14
(
    @BillType int,                                 --单据类型  306是盘点单
    @GetType int,                                --是生成编号"1",还是单据编号雷同时修正编号"2"
    @reBillCode varchar(200) output,     --返回单据编号  -- #&**&#
    @reBillDate varchar(20) output           --返回单据日期  
)
--@encode$--
AS
    SET NOCOUNT ON
    Declare @BCFirstChar char(3),@BCSecondChar char(4),@AutoBillCode bit,@NewCode char(4)
    Declare @Year varchar(4),@Month varchar(2),@Day varchar(2)

    --得到系统时间        
    Select @Year=year(getdate()), @Month=month(getdate()) , @Day=day(getdate()) 
    Set @reBillDate=@Year + '-' + @Month + '-' + @Day        
    IF @BillType=306 Set @BCFirstChar='PM-'          --根据单据编号类型得到编号首字母
    
    Set @reBillCode=@BCFirstChar
    Select @BCSecondChar=value From UserConfig where ConfigName='Billcodeindex'            --得到用户录入的编号第三到第六位号码
          
    if @BCSecondChar<>''  
        Set @reBillCode=@reBillCode + LTrim(RTrim(@BCSecondChar)) + '-'
    else    
        Set @reBillCode=@reBillCode + '-'
    Select @AutoBillCode=value from Userconfig where ConfigName='IfBillCode'                      --得到是否编号自动生成 
    
    IF @AutoBillCode=1 or @GetType=2
    Begin                       
          
          if len(@Month)=1 
               Set @reBillCode=@reBillCode + '0' + @Month
          else 
               Set @reBillCode=@reBillCode + @Month
          if len(@Day)=1 
               Set @reBillCode=@reBillCode + '0' + @Day + '-'
          else 
               Set @reBillCode=@reBillCode + @Day + '-'
          
--          Select BillCode From StockCheckIndex Where BillCode like 'PM-' 
          Select  @NewCode=(isnull(max(right(BillCode,4)),0)+1)  from StockCheckIndex where BillDate=@reBillDate                  
          if len(@NewCode)=1 Set @NewCode='000' + @NewCode
          if len(@NewCode)=2 Set @NewCode='00' + @NewCode
          if len(@NewCode)=3 Set @NewCode='0' + @NewCode
          Set @reBillCode= @reBillCode + @NewCode
    End               
    Else
         Set @reBillCode=''










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetPayConfigInfoByID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_GetPayConfigInfoByID]
GO
--==========================================================
--BY:zy
--DATE:2017-06-28
--DESCRIPTION:获取具体支付账户配置
--==========================================================
CREATE PROC Gp_GetPayConfigInfoByID
(
	@paytype   INT,	   -- 账户类型：1---支付宝，2---微信
	@ID   INT	   -- 账户ID
)
--@encode$--

AS
SET NOCOUNT ON

CREATE TABLE #temp
(
	PayConfigID		INT				NOT NULL,
	stypeids		VARCHAR(8000)	,
	stypenames		VARCHAR(8000)	
)

INSERT INTO #temp 
SELECT A.ID,
	   'stypeid' = stuff
                          ((SELECT     ',' + B.TypeId
                              FROM         PayConfigInfo AS t
                              LEFT JOIN StypePayConfigInfo D ON t.ID=D.PayConfigID
							  LEFT JOIN SType B ON D.StypeID = B.TypeId
                              WHERE t.ID=A.ID FOR xml path('')), 1, 1, ''),
       'sfullname' = stuff
                          ((SELECT     ',' + B.FullName
                              FROM         PayConfigInfo AS t
                              LEFT JOIN StypePayConfigInfo D ON t.ID=D.PayConfigID
							  LEFT JOIN SType B ON D.StypeID = B.TypeId
                              WHERE t.ID=A.ID FOR xml path('')), 1, 1, '')
FROM PayConfigInfo A
WHERE A.PayType=@paytype AND A.ID=@ID
GROUP BY A.ID

SELECT 
    A.ID,
    A.UserCode,
    A.FullName,
    A.PID,
    A.AppID,
    ISNULL(A.KeyWord,'') AS 'privatekey',
    ISNULL(A.KeyWordPublic,'') AS 'publickey',
    C.nId AS 'nid',
	C.FullName AS 'afullname',
	B.stypeids AS 'stypeid',
	B.stypenames AS 'sfullname',
    A.Comment,
    A.IsDefault
FROM PayConfigInfo A
LEFT JOIN #temp B ON A.ID=B.PayConfigID
LEFT JOIN Ac_Items C ON A.BankCardID=C.nId
WHERE A.PayType=@paytype AND A.ID=@ID

DROP TABLE #temp

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	颜熙
	Date	:	2017/10/26
	Description	: Pos管辖信息精确匹配
*/
CREATE PROCEDURE Gp_GetPosAdminitorInfo
(
	@usercode VARCHAR(50) ,
	@tablename  VARCHAR(50),
	@OperatorId VARCHAR(50) 
)
--@encode$--
AS
SET NOCOUNT ON 

IF(@tablename ='POSEmployee')
BEGIN
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeID = '00001')
	BEGIN 
		SELECT UserCode,FullName,Eid,Comment AS remark,typeId,sonnum FROM dbo.employee WHERE (UserCode = @usercode OR FullName = @usercode)  AND typeId<>'00000' AND typeId<>'00001'
	END 
ELSE 
	BEGIN
        SELECT  UserCode ,
                FullName ,
                Eid ,
                Comment AS remark ,
                A.typeId ,
                sonnum
        FROM    dbo.employee A
                INNER JOIN dbo.etype_l L ON A.typeId LIKE L.typeid + '%'
        WHERE   (UserCode = @usercode
                OR FullName = @usercode)
                AND A.typeId <> '00000'
                AND A.typeId <> '00001'
                AND L.etypeid = @OperatorId
				AND L.flag = 1
	END 
END 
ELSE IF(@tablename = 'POSOperator')
BEGIN  
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeID = '00001')
	BEGIN
		SELECT e.UserCode,e.FullName,e.Eid AS OperatorId,d.FullName AS dfullname,job AS positionname,e.sonnum,e.typeId FROM dbo.employee e INNER JOIN dbo.Department d ON e.DtypeID = d.typeid INNER JOIN dbo.loginuser L ON l.etypeid = e.typeId WHERE (e.UserCode = @usercode  OR e.FullName = @usercode) AND E.typeId<>'00000' AND E.typeId<>'00001'
	END 
	ELSE
	BEGIN
        SELECT  e.UserCode ,
                e.FullName ,
                e.Eid AS OperatorId ,
                d.FullName AS dfullname ,
                Job AS positionname ,
                e.sonnum ,
                e.typeId
        FROM    dbo.employee e
                INNER JOIN dbo.Department d ON e.DtypeID = d.typeid
                INNER JOIN dbo.loginuser L ON L.etypeid = e.typeId
                INNER JOIN dbo.etype_l EL ON e.typeId LIKE EL.typeid + '%'
        WHERE   ( e.UserCode = @usercode
                  OR e.FullName = @usercode
                )
                AND e.typeId <> '00000'
                AND e.typeId <> '00001'
                AND E.deleted = 0
                AND EL.flag = 1
                AND EL.etypeid = @OperatorId;
	END 
END 
ELSE IF(@tablename = 'PosAccount')
BEGIN 
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '0000')
	BEGIN
			SELECT	FullName,UserCode,nId,Comment AS remark,nId AS  TypeId,SonNum
			FROM	Ac_Items A
			WHERE	TypeName='B'
					AND (UserCode = @usercode OR Fullname = @usercode) AND  nTypeId <> '00000'
					AND UserCode NOT IN('2181','2131','1151') AND ( A.nTypeID LIKE '0000100004%'  )
	END
	ELSE
	BEGIN
			SELECT	FullName,UserCode,nId,Comment AS remark,nId AS  TypeId,SonNum
			FROM	Atype_L L
					INNER JOIN dbo.Ac_Items A  ON ( (L.flag=0 AND a.nTypeId=L.typeid) OR (L.Flag=1 AND a.nTypeId LIKE L.TypeId + '%'))
			WHERE	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerATypeID = '-99999')
					AND l.etypeid=@OperatorId
					AND L.Type = '0'
					AND (a.nTypeId LIKE '0000100004%' )
					AND (UserCode = @usercode OR Fullname = @usercode ) AND Deleted = 0 
					AND nTypeId <> '00000' 			
	END	
END 
ELSE IF(@tablename = 'Ptype')
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID = '00000')
	BEGIN  
		SELECT FullName,UserCode,Pid,Comment AS remark,Standard,Type,MultEntryCode AS entrycode,typeId,sonnum FROM dbo.ptype WHERE (UserCode = @usercode OR FullName = @usercode) AND typeId<>'00000'
	END 
	ELSE
	BEGIN
		SELECT	FullName,UserCode,Pid,Comment AS remark,Standard,Type, 
		CASE WHEN A.sonnum >0 THEN  '' 
        ELSE A.MultEntryCode END AS entrycode
        ,A.typeId,sonnum
		FROM	PType_L L
				INNER JOIN PType  A ON A.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @OperatorId
				AND L.flag = 1 
				AND (A.UserCode = @usercode OR A.Fullname = @usercode ) 
				--AND A.Deleted = 0 
				AND A.TypeID <> '00000'
	END			
END 
ELSE IF(@tablename = 'btype')
BEGIN 
	IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerBTypeID = '00001' )
	BEGIN 
		SELECT FullName,UserCode,Bid,Comment AS remark,TelAndAddress AS address,typeId,sonnum FROM dbo.btype WHERE (UserCode = @usercode OR FullName = @usercode) AND typeId<>'00000' AND typeId<>'00001' AND typeId LIKE '00001%'
	END 
	ELSE
	BEGIN
		SELECT	FullName,UserCode,Bid,Comment AS remark,TelAndAddress AS address,A.typeId,sonnum
		FROM	BType_L L
				INNER JOIN BType  A ON A.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = ''+@OperatorId+''
				AND L.flag = 1 
				AND (A.UserCode = @usercode OR A.Fullname = @usercode ) 
				AND A.TypeID <> '00000'
				AND A.typeId LIKE '00001%'
	END 
END 


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：王珏
	日期：2013-02-25
	描述：获取POS档案信息
*/
CREATE	PROCEDURE	Gp_GetPosInfo
(
	@ifDeleted	INT=0,		--显示停用信息
	@usercode   VARCHAR(200)='',
	@fullname   VARCHAR(200)='',
	@kusercode   VARCHAR(200)='',
	@kfullname   VARCHAR(200)='',
	@querytype  INT,         --0为非查询模式 1为查询模式
	@passtype   VARCHAR(200)='-1'
)
--@encode$--
AS
SET NOCOUNT ON


DECLARE @SQL NVARCHAR(4000)
					   
SET @SQL = ' SELECT	a.posid,
				    a.UserCode,
					a.FullName, 
					a.ktypeid,
					a.btypeid,
					a.stypeid,
					a.bankcardid,
					ac.fullname AS bcfullname,
					a.cashid,
					ac1.fullname AS cashfullname,
					a.alipayid,
					ac2.fullname AS alipayfullname,
					a.wxpayid,
					ac3.fullname AS wxpayfullname,
					a.allinpayid,
					allin.fullname AS allinpayfullname,
					a.JFPayId,					
					ac4.fullname AS JFPayFullName,
					a.dealbtypeid,
					a.vipmoneyid,
					a.macaddress,
					a.STATE,
					CASE WHEN a.STATE = 0 THEN ''新建''
					     WHEN a.STATE = 1 THEN ''启用''
						 WHEN a.STATE = 2 THEN ''停用''
					EnD AS statename,
					CASE WHEN ISNULL(a.MacAddress,'''') = '''' THEN ''未绑定''
					ELSE ''已绑定'' END AS posbindtype,
					a.Comment,
					a.passtype,
					CASE WHEN ISNULL(a.passtype,0) = 0 THEN ''日结后上传''
					ELSE ''即时上传'' END AS ptfullname,
					CASE WHEN Isnull(a.permitsaleemployee,0)=0 Then ''否'' else ''是'' end permitsaleemployee
			 FROM PosInfo a
			 LEFT JOIN AC_ITEMS ac ON a.bankcardid=ac.nid
			 LEFT JOIN AC_ITEMS ac1 ON a.cashid=ac1.nid
			  LEFT JOIN AC_ITEMS ac2 ON a.alipayid=ac2.nid
			 LEFT JOIN AC_ITEMS ac3 ON a.wxpayid=ac3.nid
			 LEFT JOIN AC_ITEMS ac4 ON a.JFPayId=ac4.nid
			 LEFT JOIN AC_ITEMS allin ON a.allinpayid=allin.nid
			 LEFT JOIN STOCK k ON k.typeid=a.ktypeid
			 '
IF @querytype = 0
	BEGIN
		IF @ifDeleted = 0
			SET @SQL = @SQL + ' WHERE a.STATE <>2 '					
	END
ELSE
	BEGIN
		SET @SQL = @SQL+' WHERE 1=1 '
		IF  @usercode<>''
			SET @SQL = @SQL+' AND a.usercode LIKE ''%'+@usercode+'%'''
		IF 	@fullname<>''
			SET @SQL = @SQL+' AND a.fullname LIKE ''%'+@fullname+'%'''
		IF 	@kusercode<>''
			SET @SQL = @SQL+' AND k.usercode LIKE ''%'+@kusercode+'%'''
		IF 	@kfullname<>''
			SET @SQL = @SQL+' AND k.fullname LIKE ''%'+@kfullname+'%'''
		IF @passtype<>-1
			SET @SQL = @SQL+' AND a.passtype LIKE ''%'+@passtype+'%'''			
		IF @ifDeleted = 0
			SET @SQL = @SQL +' AND a.STATE <>2 '
	END	 
SET @SQL = @SQL +' ORDER BY usercode'

--PRINT @SQL
EXEC (@SQL)

GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetPOSPayConfigInfoByID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_GetPOSPayConfigInfoByID]
GO
--==========================================================
--BY:zy
--DATE:2017-06-28
--DESCRIPTION:获取具体POS与支付账户关联配置
--==========================================================
CREATE PROC Gp_GetPOSPayConfigInfoByID
(
	@paytype   INT,	   -- 账户类型：1---支付宝，2---微信，3---通联收银宝
	@ID   INT	   -- 账户ID
)
--@encode$--

AS
SET NOCOUNT ON

SELECT 
    B.ID,
    C.PosID,
    C.UserCode,
    C.FullName,
    C.ktypeid,
    D.UserCode AS 'kusercode',
    D.FullName AS 'kfullname'
FROM POSPayConfigInfo A
INNER JOIN PayConfigInfo B ON A.PayConfigID=B.ID
INNER JOIN PosInfo C ON A.PosID=C.PosID
INNER JOIN STOCK D ON C.ktypeid=D.typeId
WHERE B.PayType=@paytype AND B.ID=@ID

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetPreBrandArTotal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_GetPreBrandArTotal]
GO

/*
	作者:李德强
	日期:2018-01-12
	描述:往来单位品牌应收此前余额
*/
CREATE  PROCEDURE Gp_GetPreBrandArTotal
(
	@OperatorID 	VARCHAR(100),  	            --操作员ID号 
	@startdate 		VARCHAR(20),	            --时间点
	@enddate 		VARCHAR(20),	            --时间点
	@stypeid		VARCHAR(MAX),
	@btypeid 		VARCHAR(MAX),               --客户typeid
	@brandarTypeid	VARCHAR(MAX),				--品牌名称
	@dtypeid		VARCHAR(MAX),				--部门编号
	@includepre		VARCHAR(10),						--包含预收
	@cid			VARCHAR(10),				--币别
	@pretotal 		 NUMERIC(24, 10)  OUTPUT,     	--返回余额(本币)
	@npretotal 		 NUMERIC(24, 10)  OUTPUT     	--返回余额(原币)
	)
AS
BEGIN

---[Begin]所有明细数据
CREATE TABLE #tempBill  (
	BillNumberId	INT,
	StypeId			VARCHAR(50),
	BillDate		DATETIME,
	BillCode		VARCHAR(200),
	BillType		INT, 
	BrandarTypeId	VARCHAR(50),
	BrandUserCode	VARCHAR(50),
	BrandFullName	VARCHAR(50),
	BTypeID			VARCHAR(50),--结算单位
	DTypeID			VARCHAR(50),--部门ID
	ARAddTotal		NUMERIC(24,10) NOT NULL DEFAULT(0), 
	nARAddTotal		NUMERIC(24,10) NOT NULL DEFAULT(0), 
	ARDecTotal		NUMERIC(24,10) NOT NULL DEFAULT(0), 
	nARDecTotal		NUMERIC(24,10) NOT NULL DEFAULT(0), 
	
	Comment			VARCHAR(MAX),
	CId				INT, 
	Rate			NUMERIC(24,10),
	IsIni			INT, 
	ifcheck 		VARCHAR(5),
	RedWord 		INT, 
)

CREATE TABLE #detail  (
	Btypeid VARCHAR(50),
	PreTotal		DECIMAL(24,10),   
	nPreTotal		DECIMAL(24,10)
)

INSERT INTO #tempBill
EXEC Gp_GetBrandArAndYsDetail @OperatorID,@stypeid,@btypeid,@dtypeid,@brandartypeid,@startdate,@enddate,@includepre,@cid 


CREATE TABLE #BrandarTypeId(BrandarTypeId VARCHAR(50))
INSERT INTO #BrandarTypeId(BrandarTypeId)
SELECT B.TypeId FROM brandar_Commodity B 
INNER JOIN dbo.f_split(@brandarTypeid,',') F ON  B.TypeId LIKE F.a+'%'

DECLARE @SQL NVARCHAR(MAX)
 
SET @SQL = ' INSERT INTO #detail (Btypeid,PreTotal,nPreTotal) 
			 SELECT '''+@btypeid+''',  SUM(ARAddTotal - ARDecTotal) AS PreTotal ,SUM(nARAddTotal - nARDecTotal) AS nPreTotal FROM #tempBill 
			 WHERE RedWord = 0 AND  ((BillDate < ' + CHAR(39) + @startdate + CHAR(39) + 
			 'AND isIni = 0) OR (Billtype = 189 and isIni = 1)) AND BTypeId = ' + CHAR(39) + @btypeid + CHAR(39)

IF @dtypeid <> ''
	SET @SQL += ' AND DTypeId = ' + CHAR(39) + @dtypeid + CHAR(39)
	
IF @brandarTypeid <> ''
	SET @SQL += ' AND BrandarTypeId IN (SELECT BrandarTypeId FROM #BrandarTypeId)'



EXEC(@SQL)


CREATE TABLE #cid(cid int)
IF @cid = 0
INSERT INTO #cid
        ( cid )
SELECT CId FROM dbo.Ac_Currency
ELSE
INSERT INTO #cid
        ( cid )
SELECT @cid



--IF @brandarTypeid <> ''
--UPDATE #detail SET PreTotal =ISNULL(D.PreTotal,0)+ISNULL(B.ARTotal00,0),nPreTotal = ISNULL(D.nPreTotal,0)+ ISNULL(B.NARTotal00,0)  
--FROM #detail D 
--FULL JOIN 
--(SELECT SUM(a.ARTotal00),SUM(a.NARTotal00) FROM 
--Brandar_ArApTotal a INNER JOIN #cid c ON c.cid = a.Cid 
--INNER JOIN #BrandarTypeId bt ON bt.BrandarTypeId = a.BrandarTypeID
--WHERE a.BrandarTypeID = @brandarTypeid) B ON D.BrandarTypeid = B.BrandarTypeID AND B.BtypeID = D.Btypeid
--ELSE
--UPDATE #detail SET PreTotal = ISNULL(D.PreTotal,0)+ISNULL(B.ARTotal00,0),nPreTotal = ISNULL(D.nPreTotal,0)+ ISNULL(B.NARTotal00,0)
--FROM #detail D FULL JOIN (SELECT C.BtypeID, SUM(C.ARTotal00) AS ARTotal00,SUM(C.NARTotal00) NARTotal00 FROM 
--                          (SELECT a.* FROM Brandar_ArApTotal a INNER JOIN #cid c ON c.cid = a.Cid WHERE a.BtypeID = @btypeid) C WHERE C.BtypeID = @btypeid GROUP BY C.BtypeID) B ON B.BtypeID = D.Btypeid


IF @brandarTypeid<>''
BEGIN
	SELECT @pretotal = SUM(a.ARTotal00),@npretotal = SUM(a.NARTotal00) FROM Brandar_ArApTotal a 
	INNER JOIN #cid c ON c.cid = a.Cid 
	INNER JOIN #BrandarTypeId bt ON bt.BrandarTypeId = a.BrandarTypeID
	WHERE a.BtypeID = @btypeid
END 
ELSE
BEGIN
	SELECT @pretotal = SUM(a.ARTotal00),@npretotal = SUM(a.NARTotal00) FROM Brandar_ArApTotal a 
	INNER JOIN #cid c ON c.cid = a.Cid 
	WHERE a.BtypeID = @btypeid
	--SELECT @pretotal,@npretotal
END 

SELECT @pretotal = ISNULL(PreTotal,0)+ ISNULL(@pretotal,0),@npretotal = ISNULL(nPreTotal,0)+ ISNULL(@npretotal,0) FROM #detail

DROP TABLE #tempBill

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



/*
	作者：谢吉康
	日期：2016-08-19
	描述：计算此前的实物库存数量
*/
CREATE PROCEDURE Gp_GetPreDateFactStocksQty
(
	@OperatorID	varchar(200),
	@StartDate	varchar(20),
	@PTypeId	varchar(200),
	@KTypeId	varchar(8000),
	@etypeid	VARCHAR(8000)='',--注意：如果etypeid=''表示没有受职员权限范围控制，如果全部请为00001
	@stypeid	VARCHAR(8000)=''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid <> '-99999'
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE TypeId IN (SELECT * FROM F_GetAllBaseTypeId(@KTypeId,4))
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailKType(@OperatorID)) AND TypeId IN (SELECT * FROM F_GetAllBaseTypeId(@KTypeId,4))

IF @etypeid IS NULL  SELECT @etypeid=''

IF @PTypeId = '00000'
	SET @PTypeId = '%'

DECLARE @TypeId 	varchar(100)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @etypeid<>'' 
	INSERT INTO #GetManETypeId(TypeId) SELECT e.typeid FROM F_GetManDetailEType(@OperatorID) e  INNER JOIN F_GetAllBaseTypeId(@etypeid,3) fe ON e.TypeId = fe.TypeId

--分支机构
CREATE TABLE #GetManSTypeid(TYpeid VARCHAR(100))
INSERT INTO #GetManSTypeid(TYpeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DELETE FROM #GetManKTypeId WHERE TypeId NOT IN( SELECT TypeId FROM stock WHERE STypeID IN(SELECT TypeId FROM #GetManSTypeid)) --删除分支机构以外的仓库

CREATE TABLE #PType
(
	TypeId		VARCHAR(50)
)
INSERT INTO #PType SELECT TypeId FROM F_GetManDetailPType(@OperatorID)

DECLARE  @SQL VARCHAR(8000)

--计算数据
SET @SQL='
			SELECT 	ISNULL(SUM(B.Qty),0) AS Qty
			FROM	( 
						SELECT 	ISNULL(SUM(a.qty),0) AS Qty
						FROM 	Fact_InOutstocktable a,
						        FactIndex bil  , 
								#PType p,
								#GetManKTypeId K
						WHERE 	a.PtypeId = p.TypeId
						        and a.billnumberid=bil.billnumberid						       
								AND a.KTypeId = K.TypeId
								AND a.BillDate<'+CHAR(39)+@StartDate+CHAR(39)+'
								AND a.KTypeID<>''10000'' 
								AND a.PTypeID LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)
if @etypeid<>''
	SET @SQL=@SQL+' AND a.EtypeId IN(SELECT typeid FROM #GetManETypeId) '

SET @SQL=@SQL+'
						UNION ALL 
						SELECT 	ISNULL(SUM(a.Qty),0) AS Qty
						FROM 	IniFactStocks a,
								#PType p,
								#GetManKTypeId K
						WHERE 	a.KTypeId = K.TypeId
								AND a.PTypeId = P.TypeId
								AND PTypeID LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)+'  
								AND a.KTypeID<>''10000''
								AND a.KTypeID LIKE ''%'''
if @etypeid<>''
	SET @SQL=@SQL+' 			AND a.EtypeId IN(SELECT typeid FROM #GetManETypeId) '

SET @SQL=@SQL+'	) B '
--print(@SQL)
EXEC(@SQL)


DROP TABLE #GetManKTypeId,#PType,#GetManETypeId,#GetManSTypeid









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2009-04-13
	描述：计算此前的库存数量和金额
--------------------------------------
	修改:Wang Wei 
	日期:2010-08-31
    描述:添加职员控制
*/
CREATE PROCEDURE Gp_GetPreDateQtyOrTotal
(
	@OperatorID	varchar(200),
	@StartDate	varchar(20),
	@PTypeId	varchar(200),
	@KTypeId	varchar(8000),
	@etypeid	VARCHAR(8000)='',--注意：如果etypeid=''表示没有受职员权限范围控制，如果全部请为00001
	@stypeid	VARCHAR(8000)=''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid <> '-99999'
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE TypeId IN (SELECT * FROM F_GetAllBaseTypeId(@KTypeId,4))
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailKType(@OperatorID)) AND TypeId IN (SELECT * FROM F_GetAllBaseTypeId(@KTypeId,4))

IF @etypeid IS NULL  SELECT @etypeid=''

IF @PTypeId = '00000'
	SET @PTypeId = '%'

DECLARE @TypeId 	varchar(100)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @etypeid<>'' 
	INSERT INTO #GetManETypeId(TypeId) SELECT e.typeid FROM F_GetManDetailEType(@OperatorID) e  INNER JOIN F_GetAllBaseTypeId(@etypeid,3) fe ON e.TypeId = fe.TypeId

--分支机构
CREATE TABLE #GetManSTypeid(TYpeid VARCHAR(100))
INSERT INTO #GetManSTypeid(TYpeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DELETE FROM #GetManKTypeId WHERE TypeId NOT IN( SELECT TypeId FROM stock WHERE STypeID IN(SELECT TypeId FROM #GetManSTypeid)) --删除分支机构以外的仓库

CREATE TABLE #PType
(
	TypeId		VARCHAR(50)
)
INSERT INTO #PType SELECT TypeId FROM F_GetManDetailPType(@OperatorID)

DECLARE  @SQL VARCHAR(8000)

--计算数据
SET @SQL='
			SELECT 	ISNULL(SUM(B.Qty),0) AS Qty, 
					ISNULL(SUM(B.Total),0) AS Total 
			FROM	( 
						SELECT 	ISNULL(SUM(case when AdPriceType<>0 then 0 else  a.Qty end),0) AS Qty,
								ISNULL(SUM(a.CostTotal),0) AS Total 
						FROM 	InOutStockTable a,
						        billindex bil  , 
								#PType p,
								#GetManKTypeId K
						WHERE 	a.PtypeId = p.TypeId
						        and a.billnumberid=bil.billnumberid
						        and a.BillType = bil.BillType
						       
								AND a.KTypeId = K.TypeId
								AND a.BillDate<'+CHAR(39)+@StartDate+CHAR(39)+'
								AND a.KTypeID<>''10000'' 
								AND a.PTypeID LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39) + '
						UNION ALL
						SELECT 	ISNULL(SUM(a.Qty),0) AS Qty,
								ISNULL(SUM(a.CostTotal),0) AS Total 
						FROM 	InOutStockTable a,
						        PosAllotApplyBillIndex bil  , 
								#PType p,
								#GetManKTypeId K
						WHERE 	a.PtypeId = p.TypeId
						        and a.billnumberid=bil.billnumberid		
						        and a.BillType = bil.BillType				       
								AND a.KTypeId = K.TypeId
								AND a.BillDate<'+CHAR(39)+@StartDate+CHAR(39)+'
								AND a.KTypeID<>''10000'' 
								AND a.PTypeID LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)
								
if @etypeid<>''
	SET @SQL=@SQL+' AND a.EtypeId IN(SELECT typeid FROM #GetManETypeId) '

SET @SQL=@SQL+'
						UNION ALL 
						SELECT 	ISNULL(SUM(a.Qty),0) AS Qty,
								ISNULL(SUM(a.Total),0) AS Total 
						FROM 	IniGoodsStocks a,
								#PType p,
								#GetManKTypeId K
						WHERE 	a.KTypeId = K.TypeId
								AND a.PTypeId = P.TypeId
								AND PTypeID LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)+'  
								AND a.KTypeID<>''10000''
								AND a.KTypeID LIKE ''%'' 
						UNION ALL 
						SELECT 	ISNULL(SUM(a.Qty),0) AS Qty,
								ISNULL(SUM(a.CostTotal),0) AS Total 
						FROM 	IniCommissionStock a,
								#PType p,
								#GetManKTypeId K
						WHERE 	a.KTypeId = K.TypeId
								AND a.PTypeId = P.TypeId 
								AND PTypeID LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)+' 
								AND a.KTypeID<>''10000''
								AND a.Type = 144'
if @etypeid<>''
	SET @SQL=@SQL+' 			AND a.EtypeId IN(SELECT typeid FROM #GetManETypeId) '

SET @SQL=@SQL+'	) B '
--print(@SQL)
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#PType,#GetManETypeId,#GetManSTypeid









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetPreTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_GetPreTotal]
GO


/*
	作者:毛欣蓉
	日期:2011-03-1
	描述:应收应付查询此前余额
*/
CREATE  PROCEDURE Gp_GetPreTotal
(
	@OperatorID 	VARCHAR(100),  	            --操作员ID号
	@StartDate 		VARCHAR(20),	            --时间点
	@BtypeID 		VARCHAR(MAX),               --客户typeid
	@stypeid		VARCHAR(MAX),
	@includePre		INT,
	@cid            VARCHAR(10)='0',                        --币种信息，0表示选择所有币种
	@pretotal 		 NUMERIC(24, 10)  OUTPUT,     	--返回余额
	@npretotal 		 NUMERIC(24, 10)  OUTPUT,     	--返回余额
	@artotal		 NUMERIC(24, 10)  OUTPUT,		--返回应收余额
	@nartotal		 NUMERIC(24, 10)  OUTPUT,		--返回应收余额
	@aptotal		 NUMERIC(24, 10)  OUTPUT,		--返回应付余额
	@naptotal		 NUMERIC(24, 10)  OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MDTypeId VARCHAR(50),@MSTypeId VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
	
create table #stype
(
	typeid		VARCHAR(100)
)
create table #listtable
(
	billnumberid	INT,
	billtype	INT,
	atypeid		VARCHAR(100),
	redword		INT,
	total		 NUMERIC(24, 10) ,
	ntotal		 NUMERIC(24, 10) 
)

DECLARE 
		@TmpAr	 NUMERIC(24, 10) ,
		@NTmpAr	 NUMERIC(24, 10) ,
		@TmpAP	 NUMERIC(24, 10) ,
		@NTmpAP	 NUMERIC(24, 10) 


--分支机构
INSERT INTO #stype(typeid) 
SELECT  A.typeid
FROM	F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

IF @cid='0'
  BEGIN
       SET @cid='%%'
  END

IF @includePre=1
BEGIN
	--应收发生额
	SELECT  @TmpAr=SUM(aradd),@NTmpAr=SUM(naradd) FROM 
	(
	SELECT  SUM(Total) AS aradd,SUM(NTotal) AS naradd 
	FROM ListTable l
	INNER JOIN #stype s ON l.stypeid=s.typeid
--	INNER JOIN BillIndex bi ON l.BillNumberId=bi.BillNumberId
	INNER JOIN AC_Items AC ON l.AtypeId=AC.nid
	WHERE l.BTypeID=@BtypeID 
	  AND AC.UserCode='987' 
	  AND l.BillDate>=@StartDate 
	  AND l.Audited = 1
	--  AND bi.redword=0 
	  AND l.CID LIKE @cid 
	  GROUP by l.AtypeId
	UNION ALL
	SELECT -SUM(total) AS aradd,-SUM(ntotal) AS naradd 
	FROM ListTable l
	INNER JOIN #stype s ON l.stypeid=s.typeid
	--INNER JOIN BillIndex bi ON l.BillNumberId=bi.BillNumberId
	INNER JOIN AC_Items AC ON l.AtypeId=AC.nid  
	WHERE l.BTypeID=@BtypeID 
	  AND AC.UserCode='2131' 
	  AND l.BillDate>=@StartDate 
	  AND l.Audited = 1
	--  AND bi.redword=0
	  AND l.CID LIKE @cid  
	  GROUP by l.AtypeId
	)a
	--应付发生额
	SELECT @TmpAP=SUM(aradd),@NTmpAP=SUM(naradd) FROM 
	(
	SELECT  SUM(Total) AS aradd,SUM(NTotal) AS naradd 
	FROM ListTable l
	INNER JOIN #stype s ON l.stypeid=s.typeid
	--INNER JOIN BillIndex bi ON l.BillNumberId=bi.BillNumberId
	INNER JOIN AC_Items AC ON l.AtypeId=AC.nid  
	WHERE l.BTypeID=@BtypeID 
	AND AC.UserCode='2121' 
	AND l.BillDate>=@StartDate 
	AND l.Audited = 1
	--AND bi.redword=0
	AND l.CID LIKE @cid 
	GROUP by l.AtypeId
	UNION ALL
	SELECT -SUM(total) AS aradd,-SUM(ntotal) AS naradd 
	FROM ListTable l
	INNER JOIN #stype s ON l.stypeid=s.typeid
	--INNER JOIN BillIndex bi ON l.BillNumberId=bi.BillNumberId
	INNER JOIN AC_Items AC ON l.AtypeId=AC.nid   
	WHERE l.BTypeID=@BtypeID 
	AND AC.UserCode='1151' 
	AND l.BillDate>=@StartDate 
	AND  l.Audited = 1
	--AND bi.redword=0
	AND l.CID LIKE @cid 
	GROUP BY l.AtypeId
	)a
	
	SET @artotal=(
	SELECT SUM(ARTotal)-SUM(YSTotal) 
	FROM BType_ARAPTotal B
	INNER JOIN #stype S ON B.StypeId=S.typeid
	WHERE BTypeID=@BtypeID
	  AND B.CID LIKE @cid
	)
    SET @nartotal=(
    SELECT SUM(NARTotal)-SUM(NYSTotal) 
    FROM BType_ARAPTotal B
    INNER JOIN #stype S ON B.STypeID=S.typeid  
    WHERE BTypeID=@BtypeID
      AND B.CID LIKE @cid  
    )	
    
	SET @artotal=ISNULL(@artotal,0)-ISNULL(@TmpAr,0)
	SET @nartotal=ISNULL(@nartotal,0)-ISNULL(@NTmpAr,0)
	
	SET @aptotal=(
	SELECT SUM(APTotal)-SUM(YFTotal) 
	FROM BType_ARAPTotal B
	INNER JOIN #stype S ON B.STypeID=S.typeid  
	WHERE BTypeID=@BtypeID
	  AND B.CID LIKE @cid 
	)
	
    SET @naptotal=(
    SELECT SUM(NAPTotal)-SUM(NYFTotal) 
    FROM BType_ARAPTotal B
    INNER JOIN #stype S ON B.STypeID=S.typeid
    WHERE BTypeID=@BtypeID
      AND B.CID LIKE @cid 
    )	
    
	SET @aptotal=ISNULL(@aptotal,0)-ISNULL(@TmpAP,0)
	SET @naptotal=ISNULL(@naptotal,0)-ISNULL(@NTmpAP,0)
END
ELSE
BEGIN
--应收发生额
	SELECT @TmpAr=SUM(aradd),@NTmpAr=SUM(naradd) FROM 
	(
	SELECT  SUM(Total) AS aradd,SUM(NTotal) AS naradd 
	FROM ListTable l
	INNER JOIN #stype s ON l.stypeid=s.typeid
	--INNER JOIN BillIndex bi ON l.BillNumberId=bi.BillNumberId 
	INNER JOIN AC_Items AC ON l.AtypeId=AC.nid
	WHERE l.BTypeID=@BtypeID 
	AND AC.UserCode='987'  
	AND l.BillDate>=@StartDate 
	AND l.Audited = 1
	--AND bi.redword=0 
	AND l.CID LIKE @cid
	GROUP by l.AtypeId
	)a
	
	--应付发生额
	SELECT @TmpAP=SUM(aradd),@NTmpAP=SUM(naradd) FROM 
	(
	SELECT  SUM(Total) AS aradd,SUM(NTotal) AS naradd 
	FROM ListTable l
	INNER JOIN AC_Items AC ON l.AtypeId=AC.nid
	INNER JOIN #stype s ON l.stypeid=s.typeid
	--INNER JOIN BillIndex bi ON l.BillNumberId=bi.BillNumberId  
	WHERE l.BTypeID=@BtypeID 
	AND AC.UserCode='2121' 
	AND l.BillDate>=@StartDate 
	AND  l.Audited = 1
	--And bi.redword=0  
	AND l.stypeid=s.typeid
	AND l.CID LIKE @cid 
	GROUP by l.AtypeId
	)a
	
	SET @artotal=(
	SELECT SUM(ARTotal) 
	FROM BType_ARAPTotal B
	INNER JOIN #stype S ON B.STypeID=S.typeid 
	WHERE BTypeID=@BtypeID
	  AND B.CID LIKE @cid
	)
	
	SET @nartotal=(
	SELECT SUM(NARTotal) 
	FROM BType_ARAPTotal B
	INNER JOIN #stype S ON B.STypeID=S.typeid 
	WHERE BTypeID=@BtypeID
	  AND B.CID LIKE @cid
	)
	
	SET @artotal=ISNULL(@artotal,0)-ISNULL(@TmpAr,0)
	SET @nartotal=ISNULL(@nartotal,0)-ISNULL(@NTmpAr,0)
	
	SET @aptotal=(
	SELECT SUM(APTotal) 
	FROM BType_ARAPTotal B
	INNER JOIN #stype S ON B.STypeID=S.typeid
	WHERE BTypeID=@BtypeID
	  AND B.CID LIKE @cid 
	)
	
	SET @naptotal=(
	SELECT SUM(NAPTotal) 
	FROM BType_ARAPTotal B
	INNER JOIN #stype S ON B.STypeID=S.typeid
	WHERE BTypeID=@BtypeID 
	  AND B.CID LIKE @cid
	)
	
	SET @aptotal=ISNULL(@aptotal,0)-ISNULL(@TmpAP,0)
	SET @naptotal=ISNULL(@naptotal,0)-ISNULL(@NTmpAP,0)
END
--总余额
SET @pretotal=@artotal-@aptotal
SET @npretotal=@nartotal-@naptotal
DROP TABLE #stype,#listtable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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















/****** Object:  Stored Procedure dbo.Gp_GetProduceModel23    Script Date: 2002-6-20 10:14:48 ******/

CREATE  PROCEDURE Gp_GetProduceModel23   --------从ProduceModelIndex表得到ProduceModel的所有内容(应用在库存盘点)
(
   @OperatorID varchar(100),       ------------操作员id
   @ModelID int,
   @type int,                                ---操作类型,1是根据ProduceModelIndex的ProduceModelID读ProduceModel
   @ModelName varchar(66) output,
   @CreatePtypeid varchar(100) output,
   @Comment varchar(256) output,
   @RowIndex int output,                              --ProduceModelIndex表符合条件的行数
   @ModelPtypeID varchar(100) output,
   @Qty  NUMERIC(24, 10)  output,
   @Pname varchar(66) output,                    ---商品全名
   @KID varchar(100) output,
   @kname varchar(66) output,                    ---仓库全名
   @Row int output                                       --ProduceModel表符合条件的行数
)
--@encode$--
AS
SET NOCOUNT ON
-------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re

-----------------------只返回ProduceModelIndex表的信息
select @ModelName=ProduceModelName,@CreatePtypeID=PTypeID,@comment=comment
        from ProduceModelIndex where PTypeID like @MPtypeid+'%' 
select @RowIndex=@@RowCount

select top 1 @KID=typeid,@Kname=fullname from Stock where sonnum=0 and deleted=0 


if @type=1 and @ModelID<>0              ---------根据ProduceModelID读出ProduceModel中关连ID的信息
begin
    select @ModelPtypeID=PTypeID,@Qty=Qty from ProduceModel where ProduceModelID=@ModelID and PTypeID like @MPtypeid+'%'      
    select @Pname=fullname from Ptype where typeid=@ModelPTypeID
    select @Row=@@RowCount
end

if @type=1 and @ModelID=0
   return -1















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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






















/*
	作者：谢吉康
	日期：2003-05-13
	描述：代销查询中查询产品或者客户的分布状况
*/
/*
	修改：舒珊
	日期：2016-5-27
	描述：添加类别筛选
*/
CREATE          PROCEDURE [GP_GetProductDiscFromCommission] 
(
	@OperatorID		varchar(50),
	@Type			varchar(20),	--查询的类型  1.WB,SB    以客户查商品的分布   2.WK,WJ,SK,SJ   以商品查客户的分布
	@CurId			varchar(50),	--当前的ID
	@JType			int,		--结算的类型  1.全部发（收）货    2.已结算   3和0.库存中
	@Stypeid		varchar(1550)='00001', --分支机构
	@ptypecategoryid    VARCHAR(MAX )     --商品类别ID	
)
--@encode$--
AS	
set nocount on

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #Ptype (TypeID varchar(50),usercode varchar(200),fullname varchar(200))
CREATE TABLE #Btype (TypeID varchar(50),usercode varchar(200),fullname varchar(200))
CREATE TABLE #Stype (TypeID varchar(50))

IF @Type='WB' Or @Type='SB'
BEGIN
	INSERT INTO #Ptype(typeid,usercode,fullname) select typeid,usercode,fullname from ptype where typeid in ( select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a)
	INSERT INTO #Btype(typeid,usercode,fullname) select typeid,usercode,fullname from btype where typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@CurId,',')) b where left(a.typeid,len(b.a))=b.a)
END
ELSE
BEGIN
	INSERT INTO #Ptype(typeid,usercode,fullname) select typeid,usercode,fullname from ptype where typeid in (SELECT typeId FROM   F_ManPTypeInCategoryID ( @OperatorID,@CurId,@ptypecategoryid) )
	INSERT INTO #Btype(typeid,usercode,fullname) select typeid,usercode,fullname from btype where typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
END

IF NOT (@Stypeid='' AND @MStypeid='00000')
    INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)
    
	DECLARE @SQL      varchar(8000)
	SELECT @SQL=''
	DECLARE @SQL1      varchar(8000) -- 加上期初分布数据
	SELECT @SQL1=''

	IF @Type='WB' Or @Type='SB'   --=======================相关的客户分布
	BEGIN
	
		SELECT @SQL='SELECT 	p.TypeID,
					p.UserCode,
					p.FullName,
					sum(isnull(c.qty,0)) AS qty,
					sum(isnull(c.CostTotal,0)) AS CostTotal,
					sum(isnull(c.Total,0)) AS Total	
				FROM 	#Ptype p 
	            INNER JOIN CommissionStock c ON p.TypeId=c.PtypeId '
		
		IF NOT (@Stypeid='' AND @MStypeid='00000')
			SELECT @SQL=@SQL+'  INNER JOIN #Stype s ON s.TypeID=c.stypeId '
		
		SELECT @SQL=@SQL+'	WHERE  c.qty>0
					AND c.BtypeId IN (select typeid from #Btype) '
	
		IF @Type='WB' 
			SELECT @SQL=@SQL+' AND c.Type In (140,141,142,143) GROUP BY	p.TypeID,p.UserCode,p.FullName'
		ELSE
			SELECT @SQL=@SQL+' AND c.Type In (144,145,146,147) GROUP BY	p.TypeID,p.UserCode,p.FullName'
		
	END 	
	ELSE			--==============================相关的产品分布
	BEGIN
		IF @JType in (0,3)	--==============库存查询和未结算查询
		BEGIN
				SELECT @SQL='SELECT 	b.TypeID,
							b.UserCode,
							b.FullName,
							sum(isnull(c.qty,0)) AS qty,
							sum(isnull(c.CostTotal,0)) AS CostTotal,
							sum(isnull(c.Total,0)) AS Total	
						FROM 	#Btype b 
					    INNER JOIN CommissionStock c ON b.TypeId=c.BtypeId '
					    
		    IF NOT (@Stypeid='' AND @MStypeid='00000')
				SELECT @SQL=@SQL+'  INNER JOIN #Stype s ON s.TypeID=c.stypeId '	
		    IF @Type='WK'  
		    BEGIN 
		    SELECT @SQL=@SQL+' WHERE c.PtypeId IN (select typeid from #ptype)'
		    END 
		    ELSE 
			SELECT @SQL=@SQL+' WHERE c.qty>0
							AND c.PtypeId IN (select typeid from #ptype)'
			IF @Type='WK' OR @Type='WJ'
				SELECT @SQL=@SQL+' AND c.Type In (140,141,142,143) GROUP BY	b.TypeID,b.UserCode,b.FullName'
			ELSE
				SELECT @SQL=@SQL+' AND c.Type In (144,145,146,147) GROUP BY	b.TypeID,b.UserCode,b.FullName'
		END
		ELSE			--==============@JType=1:全部发（收）货、@JType=2结算分布查询	@JType=1  
			BEGIN	
				SELECT @SQL='
					SELECT	B.TypeID,
						B.UserCode,
						B.FullName,
						ISNULL(SUM(-A.Qty),0) as Qty,
                    			 	ISNULL(SUM(-A.CostTotal),0) as CostTotal,
						ISNULL(SUM(-A.Total),0) as Total
					FROM   InOutStockTable A 
					INNER JOIN Billindex C ON A.BillnumberID =C.BillnumberID
					INNER JOIN #Btype	B ON c.BtypeID=B.TypeID '
				
				IF NOT (@CurId = '' AND @MPtypeid='00000' AND @ptypecategoryid='')	
					SELECT @SQL=@SQL+' INNER JOIN #Ptype	P ON A.PtypeID=P.TypeID '
				
				IF NOT (@Stypeid='' AND @MStypeid='00000')
					SELECT @SQL=@SQL+' INNER JOIN #Stype s ON s.TypeID=C.stypeId '	
				
				SELECT @SQL=@SQL+' WHERE C.redword =0 '
						
				IF @Type='WJ'	--===============委托
				BEGIN
					IF @JType=1
						SELECT @SQL=@SQL+' AND A.BillType in (140,142)'
					ELSE
						SELECT @SQL=@SQL+' AND A.BillType=141'
				END
				ELSE		--===============受托
				BEGIN
					IF @JType=1
						SELECT @SQL=@SQL+' AND A.BillType in (144,146)'
					ELSE
						SELECT @SQL=@SQL+' AND A.BillType=145'							
				END

				SELECT @SQL=@SQL+'
								GROUP 	BY 	B.TypeID,
										B.UserCode,
										B.FullName'
				IF @JType =1
				BEGIN
					SET @SQL1='
						SELECT	B.TypeID,
							B.UserCode,
							B.FullName,
							ISNULL(SUM(A.Qty),0) as Qty,
	                    			 	ISNULL(SUM(A.CostTotal),0) as CostTotal,
							ISNULL(SUM(A.Total),0) as Total
						FROM 	iniCommissionStock A 
						INNER JOIN	#Btype	B ON A.BtypeID=B.TypeID '
					
				    IF NOT(@MPtypeid='00000')			
				    SELECT @SQL1=@SQL1+' INNER JOIN	#Ptype	P ON A.PtypeID=P.TypeID  '
						
					IF NOT(@Stypeid='' AND @MStypeid='00000')
		            SELECT @SQL1=@SQL1+' INNER JOIN #Stype s ON s.TypeID=A.stypeId '		
							
					IF @Type='WJ'	--===============委托
						BEGIN
							SELECT @SQL1=@SQL1+' WHERE A.Type in (140)'
						END
					ELSE		--===============受托
						BEGIN
							SELECT @SQL1=@SQL1+' WHERE A.Type in (144)'
						END
					SELECT @SQL1=@SQL1+'
							GROUP 	BY 	B.TypeID,
									B.UserCode,
									B.FullName'
					SELECT @SQL='SELECT 
									X.TypeID,
									X.UserCode,
									X.FullName,
									ISNULL(SUM(X.Qty),0) as Qty,
	                    			ISNULL(SUM(X.CostTotal),0) as CostTotal,
									ISNULL(SUM(X.Total),0) as Total 
								FROM ('+@SQL+' UNION ALL '+@SQL1+') X
								GROUP 	BY 	X.TypeID,
										X.UserCode,
										X.FullName '
				END
	

			END
	END

SET @SQL ='SELECT Y.*,price=case when y.qty=0 then 0 else cast (y.total as NUMERIC(24, 10)) / cast(y.qty as NUMERIC(24, 10)) end,costprice =case when y.qty=0 then 0 else cast( y.costtotal as NUMERIC(24, 10))/cast(y.qty as NUMERIC(24, 10)) end FROM ('+@SQL+') Y '
IF @Type='WB' Or @Type='SB'
	SELECT @SQL=@SQL+' ORDER BY Y.UserCode'	
ELSE
	IF @JType=1
		SELECT @SQL=@SQL+' ORDER BY Y.UserCode'	
	ELSE
		SELECT @SQL=@SQL+' ORDER BY Y.UserCode'	

--Print(@SQL)
Exec(@SQL)

DROP TABLE #Ptype
DROP TABLE #Btype













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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









/*
	作者：谢吉康
	日期：2003-05-22
	描述：查询赠送获赠的分布基本情况
*/
CREATE  PROCEDURE [GP_GetProductFromGiveOrGiveMe] 
(
	@Qtype		char(10),	--G:赠送	M:获赠
	@QtypeMx	char(10),	--GP:客户赠送
	@PtypeId	varchar(50),	--商品的ＩＤ
	@BtypeId	varchar(50),	--客户的ＩＤ
	@EtypeId	varchar(50)	--职员的ＩＤ
)
	--@encode$--
AS
	SET NOCOUNT ON
	DECLARE	@SQL			VARCHAR(8000)	
	DECLARE 	@CurSon		Int			--当前的SonNum 
	DECLARE 	@WhereCondition 	VARCHAR(8000)	--查询条件
BEGIN
	IF @QtypeMx='GB' Or @QtypeMx='MB'
		BEGIN
			SELECT @CurSon=sonnum FROM Btype	WHERE TypeId=@BtypeId
			IF @CurSon>0 
				SET @CurSon=1
			ELSE
				SET @CurSon=0
			IF @CurSon=1
				SELECT @WhereCondition=' AND B.typeId Like '''+@BtypeId+'%'''
			ELSE
				SELECT @WhereCondition=' AND B.typeId = '''+@BtypeId+''''
		END
	IF @QtypeMx='GP' Or @QtypeMx='MP'
		BEGIN
			SELECT @CurSon=sonnum FROM Ptype	WHERE TypeId=@PtypeId
			IF @CurSon>0
				SET @CurSon=1
			ELSE
				SET @CurSon=0	
			IF @CurSon=1
				SELECT @WhereCondition=' AND P.typeId Like '''+@PtypeId+'%'''
			ELSE
				SELECT @WhereCondition=' AND P.typeId = '''+@PtypeId+''''
		END 
	IF @QtypeMx='GE'
		BEGIN
			SELECT @CurSon=sonnum FROM Employee WHERE TypeId=@EtypeId
			IF @CurSon>0 
				SET @CurSon=1
			ELSE
				SET @CurSon=0
			IF @CurSon=1
				SELECT @WhereCondition=' AND E.typeId Like '''+@EtypeId+'%'''
			ELSE
				SELECT @WhereCondition=' AND E.typeId = '''+@EtypeId+''''

		END
	IF @Qtype='G'
		SELECT @WhereCondition=@WhereCondition+' AND Bil.BillType=139'
	ELSE
		SELECT @WhereCondition=@WhereCondition+' AND Bil.BillType=126'

	SELECT @SQL='
			SELECT 	bil.BillDate,
					bil.BillCode,
					bil.BillType,
					b.usercode as busercode,
					b.fullname as bfullname,
					e.usercode as eusercode,
					e.fullname as efullname,
					k.usercode as kusercode,
					k.fullname as kfullname,
					p.usercode as pusercode,
					p.fullname as pfullname,
					sum(isnull(I.qty,0)) as qty,
					sum(isnull(CostTotal,0)) as CostTotal
			FROM 		InOutStockTable I,
					BillIndex bil,
					employee e,
					btype b,
					stock k,
					ptype p
			WHERE 	bil.BillNumberId=I.BillNumberId
					AND bil.etypeid=e.typeid
					AND bil.btypeid=b.typeid
					AND bil.ktypeid=k.typeid
					AND I.PtypeId=p.typeid
					AND bil.RedWord=0
					AND bil.Draft=0'
	SELECT @SQL=@SQL+@WhereCondition
	SELECT @SQL=@SQL+' GROUP BY bil.BillDate,bil.BillCode,bil.BillType,b.fullname,e.fullname,k.fullname,p.fullname,b.usercode,e.usercode,k.usercode,p.usercode'
	
	--PRINT(@SQL)
	EXEC(@SQL)
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_GetSABuyStat]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].GP_GetSABuyStat
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2014-06-19
-- Description: 获取远程服务器的数据-跨账套查询采购统计（先筛选数据插入当前帐套临时表中）
-- =============================================
CREATE PROCEDURE GP_GetSABuyStat
(
	@accconstr  VARCHAR(1000),  --连接字符串
	/*@stypeid	VARCHAR(max)='',
	@ptypeid	VARCHAR(MAX)='',
	@btypeid    VARCHAR(max)='',
	@dealbtypeid VARCHAR(max)='',
	@ktypeid	VARCHAR(max)='',*/
	@startdate  VARCHAR(30),
	@enddate	VARCHAR(30),
	@reportname VARCHAR(50), --报表类型，SA_PtypeBuyStat商品，SA_BtypeBuyStat供应商
	@tbName		VARCHAR(100), --临时表名
	@ruletype		INT,			--规则类型: 0=系统规则,1=自定义规则的编码, 2=自定义规则的名称 , 3=自定义规则的编码和名称
	@pid		VARCHAR(max)='',
	@pusercode	VARCHAR(max)='',
	@pfullname	VARCHAR(max)='',
	@bid		VARCHAR(max)='',
	@busercode	VARCHAR(max)='',
	@bfullname	VARCHAR(max)='',
	@sid		VARCHAR(max)='',
	@susercode	VARCHAR(max)='',
	@sfullname	VARCHAR(max)='',
	@kid		VARCHAR(max)='',
	@kusercode	VARCHAR(max)='',
	@kfullname	VARCHAR(max)='',
	@dealid		VARCHAR(max)='',
	@dealusercode	VARCHAR(max)='',
	@dealfullname	VARCHAR(max)='',
	@showmode		INT =0 -- 统计方式 0默认全部，1 按月 2 按季度 3 按年度
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON;
	
	--IF @ptypeid='00000' SET @ptypeid=''
	
	CREATE TABLE #Ptype (TypeID varchar(50),pID INT,usercode VARCHAR(200),fullname VARCHAR(200) )
	CREATE TABLE #Btype (TypeID varchar(50))
	CREATE TABLE #DealBtype (TypeID varchar(50))
	CREATE TABLE #Ktype (TypeID varchar(50))
	CREATE TABLE #Stype (TypeID varchar(50))
	
	DECLARE @BaseInfoSql VARCHAR(max)
	IF @ruletype=0
	BEGIN
	SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid,Pid,UserCode,FullName FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pid+''','','') WHERE ISNULL(A,'''')<>'''' AND pid=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@bid+''','','') WHERE ISNULL(A,'''')<>'''' AND bid=a
		INSERT INTO #DealBtype  SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealid+''','','') WHERE ISNULL(A,'''')<>'''' AND bid=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kid+''','','') WHERE ISNULL(A,'''')<>'''' AND kid=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@sid+''','','') WHERE ISNULL(A,'''')<>'''' AND sid=a  '
	END
	IF @ruletype=1
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid,Pid,UserCode,FullName FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@busercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #DealBtype  SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@susercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a  '
	END
	IF @ruletype=2
	BEGIN
	SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid,Pid,UserCode,FullName FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@bfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #DealBtype  SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@sfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a  '
	END
	IF @ruletype=3
	BEGIN
	SET @BaseInfoSql='
		INSERT INTO #Ptype 
		SELECT   typeid,Pid,UserCode,FullName 
		FROM '+@accconstr+'.dbo.ptype p, f_split('''+@pusercode+''','','') u,f_split('''+@pfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND p.UserCode=u.a AND p.FullName=f.a
		
		INSERT INTO #Btype SELECT  typeid 
		FROM '+@accconstr+'.dbo.btype b, f_split('''+@busercode+''','','') u,f_split('''+@bfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND b.UserCode=u.a AND b.FullName=f.a
		
		INSERT INTO #DealBtype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.btype b, f_split('''+@dealusercode+''','','') u,f_split('''+@dealfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND b.UserCode=u.a AND b.FullName=f.a
		
		INSERT INTO #Ktype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.Stock k, f_split('''+@kusercode+''','','') u,f_split('''+@kfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND k.UserCode=u.a AND k.FullName=f.a
		
		INSERT INTO #Stype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.SType s, f_split('''+@susercode+''','','') u,f_split('''+@sfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND s.UserCode=u.a AND s.FullName=f.a	'
	END
	   PRINT @BaseInfoSql
EXEC (@BaseInfoSql)

  IF NOT EXISTS(SELECT TOP 1 1 FROM #ptype)
    BEGIN
    SET @BaseInfoSql='
		INSERT INTO #ptype 
		SELECT  typeid,pid,usercode,FullName 
		FROM  '+@accconstr+'.dbo.ptype 
		WHERE sonnum=0   '
    END
	 EXEC(@BaseInfoSql)
	DECLARE @sql VARCHAR(max),
			@type VARCHAR(50)='timeType,',
			@tmpSql VARCHAR(200)
			

		 PRINT @BaseInfoSql
	IF @showmode = 0
	BEGIN
		SET @type = ''
		SET @tmpSql=''
	END
	IF @showmode = 2
	BEGIN
		SET @tmpSql = 'CAST(YEAR(bi.BillDate) AS VARCHAR(10))+ CAST(DATEPART(qq,bi.BillDate) AS VARCHAR(10)),'
	END
	IF @showmode = 3
	BEGIN
		SET @tmpSql = 'YEAR(bi.BillDate),'
	END 
	IF @reportname='SA_PtypeBuyStat'
		SELECT @tmpSql=@tmpSql+'a.ptypeid'
	ELSE 
		SELECT @tmpSql=@tmpSql+'bi.dealbtypeid'

	SELECT @sql=' insert into  ['+@tbName+']('+@type+'typeid,qty,total,taxtotal,ProtectTotal,Advantagetotal,xid,usercode,fullname) 
		SELECT  '+@tmpSql+',
				Qty= SUM(CASE a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-1*a.Qty) Else Convert( NUMERIC(24, 10) ,a.Qty) END),
				Total=SUM(CASE a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-1*a.Total) Else Convert( NUMERIC(24, 10) ,a.Total) END),
				TaxTotal=SUM(CASE 	a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-a.taxtotal)ELSE Convert( NUMERIC(24, 10) ,a.taxtotal) END),
				--zeroPriceqty = SUM(CASE WHEN a.Price=0 AND a.BillType = 145 THEN ABS(a.Qty)WHEN a.Price=0 THEN a.Qty ELSE 0 END),
				ProtectTotal=0,
				Advantagetotal = 0,
				p.pid,
				p.usercode,
				p.fullname
				FROM '+@accconstr+'.dbo.InoutStockTable a 
				INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Ptype)
			SELECT @sql=@sql+'	INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Btype)
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype)-- AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Ktype)
			SELECT @sql=@sql+'	INNER JOIN #Ktype k ON a.kTypeID like k.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE a.BillDate >= '''+@startdate+''' AND a.BillDate<='''+@enddate+''' 
				AND a.IsGift = 0  AND BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND a.billtype in(34,6,161,145)
				GROUP BY 
						'+@tmpSql+',
						p.pid,
						p.usercode,
						p.fullname
						'
	PRINT(@sql)
	EXEC(@sql)

	--获得价保
	SELECT @sql=' insert into  ['+@tbName+']('+@type+'typeid,qty,total,taxtotal,ProtectTotal,Advantagetotal,xid,usercode,fullname)  
		SELECT '+@tmpSql+',
				Qty= 0,
				Total=0,
				TaxTotal=0,
				ProtectTotal=sum(a.total),
				Advantagetotal = 0,
				p.pid,
				p.usercode,
				p.fullname
				FROM '+@accconstr+'.dbo.PriceProtectBill a 
				INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Ptype)
			SELECT @sql=@sql+'	INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Btype)
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype) --AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE bi.BillDate >= '''+@startdate+''' AND bi.BillDate<='''+@enddate+''' 
				AND  BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND bi.billtype=151
				GROUP BY 
						'+@tmpSql+',
						p.pid,
						p.usercode,
						p.fullname
						'
		--PRINT(@sql)
	EXEC(@sql)

	--获利
	SELECT @sql=' insert into  ['+@tbName+']('+@type+'typeid,qty,total,taxtotal,ProtectTotal,Advantagetotal,xid,usercode,fullname) 
		SELECT  '+@tmpSql+',
				Qty= 0,
				Total=0,
				TaxTotal=0,
				ProtectTotal=0,
				Advantagetotal=sum(a.total),
				p.pid,
				p.usercode,
				p.fullname
				FROM '+@accconstr+'.dbo.Advantage a 
				INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Ptype)
			SELECT @sql=@sql+'	INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Btype) 
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype)-- AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE bi.BillDate >= '''+@startdate+''' AND bi.BillDate<='''+@enddate+''' 
				AND  BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND bi.billtype=150
				GROUP BY 
						'+@tmpSql+',
						p.pid,
						p.usercode,
						p.fullname
						'
	--PRINT(@sql)
	EXEC(@sql)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_GetSABuyStatbtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].GP_GetSABuyStatbtype
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2014-11-12
-- Description: 获取远程服务器的数据-跨账套查询采购统计往来单位（先筛选数据插入当前帐套临时表中）
-- =============================================
CREATE PROCEDURE GP_GetSABuyStatbtype
(
	@accconstr  VARCHAR(1000),  --连接字符串
	/*@stypeid	VARCHAR(max)='',
	@ptypeid	VARCHAR(MAX)='',
	@btypeid    VARCHAR(max)='',
	@dealbtypeid VARCHAR(max)='',
	@ktypeid	VARCHAR(max)='',*/
	@startdate  VARCHAR(30),
	@enddate	VARCHAR(30),
	@reportname VARCHAR(50), --报表类型，SA_PtypeBuyStat商品，SA_BtypeBuyStat供应商
	@tbName		VARCHAR(100), --临时表名
	@ruletype		INT,			--规则类型: 0=系统规则,1=自定义规则的编码, 2=自定义规则的名称 , 3=自定义规则的编码和名称
	@pid		VARCHAR(max)='',
	@pusercode	VARCHAR(max)='',
	@pfullname	VARCHAR(max)='',
	@bid		VARCHAR(max)='',
	@busercode	VARCHAR(max)='',
	@bfullname	VARCHAR(max)='',
	@sid		VARCHAR(max)='',
	@susercode	VARCHAR(max)='',
	@sfullname	VARCHAR(max)='',
	@kid		VARCHAR(max)='',
	@kusercode	VARCHAR(max)='',
	@kfullname	VARCHAR(max)='',
	@dealid		VARCHAR(max)='',
	@dealusercode	VARCHAR(max)='',
	@dealfullname	VARCHAR(max)='',
	@showmode		INT =0 -- 统计方式 0默认全部，1 按月 2 按季度 3 按年度
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON;
	
	--IF @ptypeid='00000' SET @ptypeid=''
	
	CREATE TABLE #Ptype (TypeID varchar(50) )
	CREATE TABLE #Btype (TypeID varchar(50))
	CREATE TABLE #DealBtype (TypeID varchar(50),bID INT,usercode VARCHAR(200),fullname VARCHAR(200))
	CREATE TABLE #Ktype (TypeID varchar(50))
	CREATE TABLE #Stype (TypeID varchar(50))
	 DECLARE @BaseInfoSql VARCHAR(max)
	IF @ruletype=0
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pid+''','','') WHERE ISNULL(A,'''')<>'''' AND pid=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@bid+''','','') WHERE ISNULL(A,'''')<>'''' AND bid=a
		INSERT INTO #DealBtype  SELECT  typeid,bid,usercode,FullName FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealid+''','','') WHERE ISNULL(A,'''')<>'''' AND bid=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kid+''','','') WHERE ISNULL(A,'''')<>'''' AND kid=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@sid+''','','') WHERE ISNULL(A,'''')<>'''' AND sid=a  '
	END
	IF @ruletype=1
	BEGIN
	SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@busercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #DealBtype  SELECT   typeid,bid,usercode,FullName FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@susercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a  '
	END
	IF @ruletype=2
	BEGIN
	SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@bfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #DealBtype  SELECT  typeid,bid,usercode,FullName FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@sfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a  '
	END
	IF @ruletype=3
	BEGIN
	SET @BaseInfoSql='
		INSERT INTO #Ptype 
		SELECT   typeid
		FROM '+@accconstr+'.dbo.ptype p, f_split('''+@pusercode+''','','') u,f_split('''+@pfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND p.UserCode=u.a AND p.FullName=f.a
		
		INSERT INTO #Btype SELECT  typeid 
		FROM '+@accconstr+'.dbo.btype b, f_split('''+@busercode+''','','') u,f_split('''+@bfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND b.UserCode=u.a AND b.FullName=f.a
		
		INSERT INTO #DealBtype 
		SELECT  typeid,bid,usercode,FullName  
		FROM '+@accconstr+'.dbo.btype b, f_split('''+@dealusercode+''','','') u,f_split('''+@dealfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND b.UserCode=u.a AND b.FullName=f.a
		
		INSERT INTO #Ktype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.Stock k, f_split('''+@kusercode+''','','') u,f_split('''+@kfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND k.UserCode=u.a AND k.FullName=f.a
		
		INSERT INTO #Stype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.SType s, f_split('''+@susercode+''','','') u,f_split('''+@sfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND s.UserCode=u.a AND s.FullName=f.a	'
	END
	  EXEC(@BaseInfoSql)
    IF NOT EXISTS(SELECT TOP 1 1 FROM #DealBtype)
    BEGIN
      SET @BaseInfoSql='
		INSERT INTO #DealBtype 
		SELECT  typeid,bid,usercode,FullName 
		FROM  '+@accconstr+'.dbo.btype 
		WHERE sonnum=0   '
    END
	  EXEC(@BaseInfoSql)
	
	DECLARE @sql VARCHAR(max),
			@type VARCHAR(50)='timeType,',
			@tmpSql VARCHAR(200)
	--SELECT * FROM #DealBtype
	IF @showmode = 0
	BEGIN
		SET @type = ''
		SET @tmpSql=''
	END
	IF @showmode = 2
	BEGIN
		SET @tmpSql = 'CAST(YEAR(bi.BillDate) AS VARCHAR(10))+ CAST(DATEPART(qq,bi.BillDate) AS VARCHAR(10)),'
	END
	IF @showmode = 3
	BEGIN
		SET @tmpSql = 'YEAR(bi.BillDate),'
	END 
	IF @reportname='SA_PtypeBuyStat'
		SELECT @tmpSql=@tmpSql+'a.ptypeid'
	ELSE 
		SELECT @tmpSql=@tmpSql+'bi.dealbtypeid'

	SELECT @sql=' insert into  ['+@tbName+']('+@type+'typeid,qty,total,taxtotal,ProtectTotal,Advantagetotal,xid,usercode,fullname) 
		SELECT  '+@tmpSql+',
				Qty= SUM(CASE a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-1*a.Qty) Else Convert( NUMERIC(24, 10) ,a.Qty) END),
				Total=SUM(CASE a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-1*a.Total) Else Convert( NUMERIC(24, 10) ,a.Total) END),
				TaxTotal=SUM(CASE 	a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-a.taxtotal)ELSE Convert( NUMERIC(24, 10) ,a.taxtotal) END),
				--zeroPriceqty = SUM(CASE WHEN a.Price=0 AND a.BillType = 145 THEN ABS(a.Qty)WHEN a.Price=0 THEN a.Qty ELSE 0 END),
				ProtectTotal=0,
				Advantagetotal = 0,
				d.bid,
				d.usercode,
				d.fullname
				FROM '+@accconstr+'.dbo.InoutStockTable a 
				INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Ptype)
			SELECT @sql=@sql+'	INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Btype)
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype)-- AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Ktype)
			SELECT @sql=@sql+'	INNER JOIN #Ktype k ON a.kTypeID like k.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE a.BillDate >= '''+@startdate+''' AND a.BillDate<='''+@enddate+''' 
				AND a.IsGift = 0  AND BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND a.billtype in(34,6,161,145)
				GROUP BY 
						'+@tmpSql+',
						d.bid,
						d.usercode,
						d.fullname
						'
	--PRINT(@sql)
	EXEC(@sql)

	--获得价保
	SELECT @sql=' insert into  ['+@tbName+']('+@type+'typeid,qty,total,taxtotal,ProtectTotal,Advantagetotal,xid,usercode,fullname)  
		SELECT '+@tmpSql+',
				Qty= 0,
				Total=0,
				TaxTotal=0,
				ProtectTotal=sum(a.total),
				Advantagetotal = 0,
				d.bid,
				d.usercode,
				d.fullname
				FROM '+@accconstr+'.dbo.PriceProtectBill a 
				INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Ptype)
			SELECT @sql=@sql+'	INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Btype)
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype)-- AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE bi.BillDate >= '''+@startdate+''' AND bi.BillDate<='''+@enddate+''' 
				AND  BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND bi.billtype=151
				GROUP BY 
						'+@tmpSql+',
						d.bid,
						d.usercode,
						d.fullname
						'
		--PRINT(@sql)
	EXEC(@sql)

	--获利
	SELECT @sql=' insert into  ['+@tbName+']('+@type+'typeid,qty,total,taxtotal,ProtectTotal,Advantagetotal,xid,usercode,fullname) 
		SELECT  '+@tmpSql+',
				Qty= 0,
				Total=0,
				TaxTotal=0,
				ProtectTotal=0,
				Advantagetotal=sum(a.total),
				d.bid,
				d.usercode,
				d.fullname
				FROM '+@accconstr+'.dbo.Advantage a 
				INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Ptype)
			SELECT @sql=@sql+'	INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Btype) 
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype)-- AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE bi.BillDate >= '''+@startdate+''' AND bi.BillDate<='''+@enddate+''' 
				AND  BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND bi.billtype=150
				GROUP BY 
						'+@tmpSql+',
						d.bid,
						d.usercode,
						d.fullname
						'
	PRINT(@sql)
	EXEC(@sql)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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









-- ========================================================================
-- 功能说明：得到单据的自定义字符
-- 作者：陈启华  2004-12-15


-- ========================================================================



CREATE      PROCEDURE [GP_GETSETCODE] 
(
	@chvOperatorID		varchar(50),	-- 11、操作员 ID（作权限范围检查用）
	@chvBilltype        numeric(5,0)
)
--@encode$--
AS 
SET NOCOUNT ON

IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe


DECLARE @SQL Varchar(2000)
SET @SQL='SELECT * FROM CodeConfig WHERE Billtype ='+Convert(varchar(100),@chvBilltype)
EXEC (@SQL)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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






/*
	作者：谢吉康
	日期：2004-11-14
	描述：盘点单存储草稿后调出，商品的排序变化
	原因：没有按照商品的UserCode排序
	结果：本地修改后测试结果正确
	
	修改：舒珊
	日期：2016年2月25日
	描述：增添表头自定义显示字段
*/
CREATE        PROCEDURE Gp_GetStockCheck23   --------从StockCheckIndex表得到StockCheck的所有内容(应用在库存盘点)
(
	@OperatorID varchar(100),       		------------操作员id
	@StartDate 	datetime='',            ------------盘点开始日期
	@EndDate 	datetime='',            ------------盘点查询最后日期
	@ScID 		int='',
	@ptypeid 	varchar(100)='',         --可选的商品ID
	@type 		int,                    ---操作类型,1是只读StockCheckIndex表的内容,2是根据StockCheckIndex的StockCheckID读StockCheck
	@UserCode 	varchar(66)='',
	@FullName 	varchar(66)='',
	@stypeid	VARCHAR(MAX)='',
	@ktypeid	VARCHAR(MAX)='',
	@ifwx		INT=1,						--是否维修库(0=正常,1=维修)	
	@ifserialcheck INT=0
)
--@encode$--
AS
SET NOCOUNT ON
-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM  F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID) --F_GetManDetailKType(@OperatorID)
CREATE CLUSTERED INDEX #GetManKTypeId_t ON #GetManKTypeId(TypeId);

DECLARE @costing int  --当前系统的成本算法

SELECT @costing=subvalue FROM sysdata WHERE subname='costing'

-------------------------------------------------------------读表的内容-----------------------------------------------------
--IF @UserCode='' SELECT @UserCode='%' ELSE SELECT @UserCode='%'+@UserCode+'%'--换为拼接语句，为空时，不进行单个%比对
--IF @FullName='' SELECT @FullName='%' ELSE SELECT @FullName='%'+@FullName+'%'

DECLARE @sql varchar(MAX)
DECLARE @sql_StockCheckID VARCHAR(MAX)
IF @type=1               ---------根据StockCheckID读出StockCheck中关连ID的信息
	BEGIN
	-----------------------只返回StockCheckIndex表的信息
	   IF @ScID<>0 
		   BEGIN
		       SELECT  	a.BillDate ,
						a.Pass, 
						a.BillCode , 
						a.KTypeID , 
						a.ETypeID , 
						a.Comment , 
						b.fullname AS Kname, 
						c.fullname AS Ename,
						b.stypeid,
						CASE WHEN a.SerialCheck=1 THEN '序列号盘点' WHEN a.IfWx = 1 THEN '维修商品盘点' ELSE '正常商品盘点' END AS IfWx,
						a.serialcheck,
						SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,
						SysDiy7_head,SysDiy8_head,SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,
						SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head 
		       FROM 	StockCheckIndex a 
						LEFT JOIN Custom_BillIndex csindex on a.stockcheckid=csindex.BillId and csindex.billtype=(select billtype from billname where BillName='盘点单'  )
						INNER JOIN Stock b ON (a.KTypeid=b.typeid) 
						INNER JOIN employee c ON (a.ETypeid=c.typeid) 
						INNER JOIN #GetManKTypeId k ON k.TypeId=a.KTypeID
				WHERE	a.StockCheckID=@ScID AND a.SerialCheck=@ifserialcheck
						AND a.ifWX=@ifwx
		   END
	   ELSE
		   BEGIN
				CREATE TABLE #tmpStock(StockCheckID VARCHAR(50))
				CREATE CLUSTERED INDEX #tmpStock_t ON #tmpStock(StockCheckID);
							
				SET @sql_StockCheckID = 'INSERT INTO #tmpStock 
							 SELECT	
									s.StockCheckID 
							 FROM	StockCheck s
							 INNER JOIN ptype p ON (p.typeid=s.ptypeid) 
							 WHERE p.sonnum=0'
				IF @UserCode <> '' 
					SET @sql_StockCheckID = @sql_StockCheckID + ' AND usercode LIKE ''%' + @UserCode + '%'''
				IF @FullName <> ''
					SET @sql_StockCheckID = @sql_StockCheckID + ' AND Fullname LIKE ''%' + @FullName + '%'''
				SET @sql_StockCheckID = @sql_StockCheckID + ' GROUP BY s.StockCheckID'
				   
				SET @sql = '
					   SELECT DISTINCT a.StockCheckID,
								a.Pass , 
								a.BillDate , 
								a.BillCode , 
								a.KTypeID , 
								a.ETypeID , 
								a.Comment , 
								b.fullname AS Kname, 
								d.fullname AS Ename,
								b.stypeid,
								CASE WHEN a.SerialCheck=1 THEN ''序列号盘点''  WHEN a.IfWx = 1 THEN ''维修商品盘点'' ELSE ''正常商品盘点'' END AS IfWx,
								a.serialcheck,
								SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,
								SysDiy7_head,SysDiy8_head,SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,
								SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head 
					   FROM		StockCheckIndex a 
								LEFT JOIN Custom_BillIndex csindex on a.stockcheckid=csindex.BillId and csindex.billtype=(select billtype from billname where BillName=''盘点单''  )
								INNER JOIN F_GetManKTypeAll(''' +@OperatorID+''') b		ON (a.KTypeid=b.typeid) 
								INNER JOIN  (select * from F_GetManDetailEType('''+@OperatorID+''') union select '''')c	ON (a.ETypeid=c.typeid) 
								LEFT JOIN Employee d ON a.ETypeID=d.TypeID
								INNER JOIN #GetManKTypeId k ON k.TypeId=a.KTypeID
								INNER JOIN #tmpStock
											as s ON (a.StockCheckID=s.StockCheckID)	
					   WHERE	a.ifWX='+CAST(@ifwx as varchar(1))+'
								AND	 a.SerialCheck='+CAST(@ifserialcheck as varchar(1))+'
								AND  a.BillDate>='''+CONVERT(varchar(12),@StartDate,23)+ '''
								AND  a.BillDate<='''+CONVERT(varchar(12),@EndDate,23)+''''
								--PRINT(@sql_StockCheckID)
								--PRINT(@sql)
				EXEC(@sql_StockCheckID)
				EXEC(@sql)
				DROP TABLE #tmpStock
		   END
	END
ELSE IF @type=2 AND @ScID<>0      --读StockCheck的内容
	BEGIN
	    SELECT 	a.PTypeID ,
				a.produceDate,
				a.validDate,
				a.GoodsNumber,
				a.GoodsCostPrice,
				b.EntryCode,
				b.Standard,
				b.Type,
				b.Area, 
				a.Id,
				SUM(a.Qty) AS CheckQty, 
				b.fullname,
				b.usercode,
				b.unit1
		FROM 	StockCheck a 
				INNER JOIN ptype b ON (a.Ptypeid=b.typeid) 
		WHERE 	a.StockCheckID=@ScID 
		GROUP BY usercode,
				 fullname,
				 PTypeID,
				 unit1,
				 a.Id,
				b.EntryCode,
				b.Standard,
				b.Type,
				b.Area,
				a.produceDate,
				a.validDate,
				a.GoodsNumber,
				a.GoodsCostPrice
		ORDER BY
				a.Id
	END
ELSE IF @type=3 AND @scID<>0       ----读库存
	BEGIN
	    SELECT	ISNULL(SUM(qty),0) AS qty 
	    FROM	GoodsStocks gs 
				INNER JOIN	StockCheckIndex si ON gs.KtypeId=si.KTypeID AND  si.StockCheckID=@ScID
	    WHERE	ptypeid=@ptypeid 
	END
ELSE IF @type=4     --读盘点汇总的商品列表,借用@ptypeid传入仓库ID
	BEGIN 	
	      IF @ptypeid='' OR @ptypeid='00000' SELECT @ptypeid='%'
	
	      IF @costing=0   --移动加权平均
		      BEGIN
		       SELECT a.typeid,a.usercode,a.fullname,a.unit1,ISNULL(b.CheckQty,0) AS CheckQty,
		              ISNULL(c.Qty,0) AS Qty,ISNULL((ISNULL(b.CheckQty,0)-CASE c.Qty WHEN NULL THEN 0 ELSE c.Qty END),0) AS CountQty,ISNULL(c.Total,0) AS QtyMoney,
		              b.StockCheckID,(SELECT BillCode FROM StockCheckIndex WHERE StockCheckID=b.StockCheckID AND pass=0) AS BillCode
		       FROM ptype a LEFT JOIN
		        (
		             SELECT MAX(b.StockCheckID) AS StockCheckID, SUM(b.Qty) AS CheckQty,b.PtypeID FROM StockCheck b JOIN StockCheckIndex d ON (b.StockCheckID=d.StockCheckID) WHERE d.pass<>1 AND d.Ktypeid LIKE @ptypeid
		                   AND b.PtypeID IN (SELECT * FROM F_GetManDetailPType(@OperatorID)) GROUP BY PtypeID
		        )b ON (a.typeid=b.PtypeID) LEFT JOIN 
		        (
		             SELECT c.PtypeID,ISNULL(c.Total,0) AS Total,ISNULL(c.Qty,0) AS Qty FROM GoodsStocks c WHERE c.Ktypeid LIKE @ptypeid 
		        )c ON (a.typeID=c.PtypeID) WHERE  a.sonnum=0 AND a.typeid IN (SELECT * FROM F_GetManDetailPType(@OperatorID))
		      END
	      ELSE   --先进先出,后进先出
		      BEGIN
		            SELECT a.typeid,a.usercode,a.fullname,a.unit1,ISNULL(b.CheckQty,0) AS CheckQty,
		              ISNULL(c.Qty,0) AS Qty,ISNULL((ISNULL(b.CheckQty,0)-CASE c.Qty WHEN NULL THEN 0 ELSE c.Qty END),0) AS CountQty,ISNULL(c.Total,0) AS QtyMoney,
		              b.StockCheckID,(SELECT BillCode FROM StockCheckIndex WHERE StockCheckID=b.StockCheckID AND pass=0) AS BillCode
		       FROM ptype a LEFT JOIN
		        (
		             SELECT MAX(b.StockCheckID) AS StockCheckID, SUM(b.Qty) AS CheckQty,b.PtypeID FROM StockCheck b JOIN StockCheckIndex d ON (b.StockCheckID=d.StockCheckID) WHERE d.pass<>1 AND d.Ktypeid LIKE @ptypeid
		                   AND b.PtypeID IN (SELECT * FROM F_GetManDetailPType(@OperatorID)) GROUP BY PtypeID
		        )b ON (a.typeid=b.PtypeID) LEFT JOIN 
		        (
		             SELECT PtypeID,ISNULL(SUM(Total),0) AS Total,ISNULL(SUM(Qty),0) AS Qty FROM GoodsStocks WHERE Ktypeid LIKE @ptypeid GROUP BY ptypeid
		        )c ON (a.typeID=c.PtypeID) WHERE  a.sonnum=0 AND a.typeid IN (SELECT * FROM F_GetManDetailPType(@OperatorID))
		      END      
	END
IF @type=2 AND @ScID=0 
   RETURN -1






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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




/*
	作者：谢吉康
	日期：2006-05-15
	描述：盘点历史库存
*/
CREATE    PROCEDURE Gp_GetStockCheck23_Xjkang   --------从StockCheckIndex表得到StockCheck的所有内容(应用在库存盘点)
(
	@OperatorID 	varchar(100),       		-- 操作员id
	@StartDate 		datetime='',            -- 盘点开始日期
	@EndDate 		datetime='',            -- 盘点查询最后日期
	@ScID 			int='',
	@ptypeid 		varchar(100)='',         -- 可选的商品ID
	@type 			int,                    -- 操作类型,1是只读StockCheckIndex表的内容,2是根据StockCheckIndex的StockCheckID读StockCheck
	@EndDatePoint	datetime='',			-- 盘点日期		
	@UserCode 		varchar(100)='',			-- 商品编号
	@FullName 		varchar(100)=''			-- 商品名称
)
--@encode$--
AS
SET NOCOUNT ON
-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------

DECLARE @costing int  --当前系统的成本算法

SELECT @costing=subvalue FROM sysdata WHERE subname='costing'

-------------------------------------------------------------读表的内容-----------------------------------------------------

IF @UserCode='' SELECT @UserCode='%' ELSE SELECT @UserCode='%'+@UserCode+'%'
IF @FullName='' SELECT @FullName='%' ELSE SELECT @FullName='%'+@FullName+'%'

IF @type=1               ---------根据StockCheckID读出StockCheck中关连ID的信息
	BEGIN
	-----------------------只返回StockCheckIndex表的信息
	   IF @ScID<>0 
		   BEGIN
		       	SELECT	a.BillDate ,
						a.Pass, 
						a.BillCode , 
						a.KTypeID , 
						a.ETypeID , 
						a.Comment , 
						b.fullname AS Kname, 
						c.fullname AS Ename 
				FROM 	StockCheckIndex a JOIN Stock b ON (a.KTypeid=b.typeid) JOIN employee c ON (a.ETypeid=c.typeid) 
				WHERE 	a.StockCheckID=@ScID
		   END
	   ELSE
			BEGIN
			   	SELECT 	DISTINCT 
						a.StockCheckID,
						a.Pass , 
						a.BillDate , 
						a.BillCode , 
						a.KTypeID , 
						a.ETypeID , 
						a.Comment , 
						b.fullname AS Kname, 
						c.fullname AS Ename 
				FROM 	StockCheckIndex a JOIN Stock b ON (a.KTypeid=b.typeid) JOIN employee c ON (a.ETypeid=c.typeid) LEFT JOIN (SELECT p.usercode,p.fullname,p.typeid,s.StockCheckID FROM StockCheck s JOIN ptype p ON (p.typeid=s.ptypeid) WHERE p.deleted=0 AND p.sonnum=0)
			      s ON (a.StockCheckID=s.StockCheckID)
				WHERE 	a.KTypeID LIKE @MKtypeid+'%' 
						AND a.ETypeID LIKE @MEtypeid+'%' 
						AND a.BillDate>=@StartDate 
						AND a.BillDate<=@EndDate 
						AND s.usercode LIKE @UserCode 
						AND s.Fullname LIKE @FullName
			END
	END
ELSE IF @type=2 AND @ScID<>0      --读StockCheck的内容
	BEGIN
		SELECT 	a.PTypeID , 
				a.Id,
				SUM(a.Qty) AS CheckQty, 
				b.fullname,
				b.usercode,
				b.unit1 
		FROM 	StockCheck a JOIN ptype b ON (a.Ptypeid=b.typeid) 
		WHERE 	a.StockCheckID=@ScID 
		GROUP BY usercode,
				 fullname,
				 PTypeID,
				 unit1,
				 a.Id
		ORDER BY
				a.Id
	END
ELSE IF @type=3 AND @scID<>0       ----读库存
	BEGIN
		SELECT 	ISNULL(SUM(qty),0) AS qty 
		FROM 	GoodsStocks 
		WHERE 	ptypeid=@ptypeid 
				AND ktypeid=(SELECT Ktypeid FROM StockCheckIndex WHERE StockCheckID=@ScID)
	END
ELSE IF @type=4     --读盘点汇总的商品列表,借用@ptypeid传入仓库ID
	BEGIN 
		IF @PTypeId='' OR @PTypeId='00000' SELECT @PTypeId='%'

		--先将盘点表的数据处理在一起，避免同一商品出现在两张盘点单中的时候库存数量翻倍的情况 谢吉康 2006-5-18
		SELECT	B.PTypeId,
				MAX(B.StockCheckID) AS StockCheckID,
				ISNULL(SUM(B.Qty),0) AS CheckQty
		INTO	#CheckStock
		FROM	StockCheckIndex D,
				StockCheck B
		WHERE	B.StockCheckID=D.StockCheckID
				AND D.Pass <> 1
				AND D.KTypeId LIKE @PTypeId
				AND B.PtypeID LIKE @MPTypeID+'%'
				AND D.KTypeId LIKE @MKTypeId + '%'
		GROUP BY B.PTypeId
		
		--去当前库存的数量，期初+出入库记录
		SELECT	G.PTypeId,
				ISNULL(SUM(G.Qty),0) AS Qty,
				ISNULL(SUM(G.CostTotal),0) AS CostTotal
		INTO	#GoodsStocks
		FROM (
			SELECT	PTypeId,
					ISNULL(SUM(Qty),0) AS Qty,
					ISNULL(SUM(CostTotal),0) AS CostTotal
			FROM	InOutStockTable
			WHERE	Audited = 1
					AND KTypeId <> '10000'
					AND BillDate<=@EndDatePoint
					AND PTypeId LIKE @MPTypeId + '%'
					AND KTypeId LIKE @PTypeId + '%'
					AND KTypeId LIKE @MKTypeId + '%'
			GROUP BY PTypeId
			UNION ALL
			SELECT	PTypeId,
					ISNULL(SUM(Qty),0) AS Qty,
					ISNULL(SUM(Total),0) AS CostTotal
			FROM	iniGoodsStocks
			WHERE	PTypeId LIKE @MPTypeId + '%'
					AND KTypeId LIKE @PTypeId + '%'
					AND KTypeId LIKE @MKTypeId + '%'
			GROUP BY PTypeId
			UNION ALL
			SELECT	TypeId,
					0 AS Qty,
					0 AS CostTotal
			FROM	PType
			WHERE	SonNum = 0
					AND Deleted = 0
		)G GROUP BY G.PTypeId

		--正式查询数据
		SELECT 	A.TypeId,
				A.usercode,
				A.fullname,
				A.unit1,
		      	B.StockCheckId,
				(SELECT BillCode FROM StockCheckIndex WHERE StockCheckId=b.StockCheckId AND pass=0) AS BillCode,
				ISNULL(B.Qty,0) AS Qty,
				ISNULL(B.Total,0) AS QtyMoney,
				ISNULL(B.CheckQty,0) AS CheckQty,
				ISNULL((ISNULL(b.CheckQty,0)-
					CASE B.Qty 
						WHEN NULL THEN 0 
						ELSE B.Qty END),0
					) AS CountQty
		FROM 	PType A 
		LEFT JOIN (
					SELECT	B.PTypeId,
							I.StockCheckId,
							ISNULL(SUM(B.Qty),0) AS Qty,
							ISNULL(SUM(B.CostTotal),0) AS Total,
							ISNULL(SUM(I.CheckQty),0) AS CheckQty
					FROM	#GoodsStocks B
					LEFT JOIN (
						SELECT	PTypeId,
								StockCheckId,
								ISNULL(SUM(CheckQty),0) AS CheckQty
						FROM	#CheckStock
						GROUP BY PTypeId,StockCheckId
					)I ON B.PTypeId = I.PTypeId
					GROUP BY B.PTypeId,I.StockCheckId
		)B ON A.TypeId = B.PTypeId
		WHERE  	A.SonNum=0 
				AND A.Deleted=0 
				AND A.TypeId LIKE @MPTypeID +'%'
		ORDER BY A.UserCode

		--删除临时表
		DROP TABLE #CheckStock,#GoodsStocks
	END

IF @type=2 AND @ScID=0 
   RETURN -1




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_GetStypeMonthProc]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].GP_GetStypeMonthProc
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*
	作者：	毛欣蓉
	时间：	2016-7-11
	描述：获取分支机构月经相同的记录(所选分支必须期间、年度一样一样，开始时间和结束时间都一致)
*/

CREATE PROCEDURE [dbo].GP_GetStypeMonthProc
(
	@OperatorID   VARCHAR(50),
	@StypeId	varchar(max)		--分支机构id
)
--@encode$--
AS
set nocount on

SELECT 
	CAST(P.period AS VARCHAR(2))+','+CAST(P.Year AS VARCHAR(4)) Period,
	CONVERT(VARCHAR(10),P.StartDate,120)+' 到 '+CONVERT(VARCHAR(10),P.EndDate,120) DataTexts
FROM MonthProc P
INNER JOIN dbo.F_BaseGetAllManagerBaseTypeId(@StypeId,11,@OperatorID) F ON F.TypeId=P.STypeID AND P.MonthNo<>'本期'
GROUP BY P.Year,P.period,P.StartDate,P.EndDate
ORDER BY P.Year,P.period

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE   PROCEDURE Gp_GetSubValue
(
 @szName	varchar(30),
 @stypeid	varchar(max),
 @szReturn	varchar (50) output
)
--@encode$--
AS
SET NOCOUNT ON

IF UPPER(@szName)=UPPER('stypeinicanmodify')
BEGIN
	SELECT	TOP 1 
			@szReturn=U.Value 
	FROM	SType_Config C,
			SType_UserConfig U 
	WHERE	C.ConfigNo = U.ConfigNo 
			AND C.ConfigName = 'stypeinicanmodify' 
			AND ISNULL(U.STypeID,'') = @stypeid
END
ELSE
BEGIN
	SELECT TOP 1 @szReturn=SubValue FROM sysdata WHERE subname=@szName
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_GETTe_InitData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_GETTe_InitData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*	作者：黄清	
	日期：2014-05-16
	描述：获取出纳系统初始化数据

*/
CREATE PROCEDURE [dbo].[GP_GETTe_InitData]
(
	@stypeid	varchar(100),	--分支机构ID
	@buid		VARCHAR(5),		--业务类型ID 1.现金 2.银行存款 3.银行对账单
	@cid		VARCHAR(5),		--币种ID
	@OperatorID	VARCHAR(50)		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200),UserCode VARCHAR(200),CID INT,IsCash INT)
	INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName,UserCode,CID,IsCash) 
	SELECT L.Typeid,L.Stypeid,A.FullName,A.UserCode,A.Cid,A.IsCash FROM F_LineAccount(@OperatorID,'') L
	INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
	WHERE L.Stypeid=@stypeid AND A.Deleted<>'1' 
	
	--写入空数据
	INSERT INTO #Ac_Account_L(TypeId,StypeId,FullName,UserCode)VALUES
	('',@stypeid,'','')
END;



IF @buid='1'
BEGIN 
	IF @cid='0' --综合本位币单独处理
	BEGIN
			SELECT	TI.STypeId,
					AtypeId,
					A.FullName AS afullname,
					A.UserCode AS ausercode,
					'' AS AccountId,
					SUM(FCreditOri) AS FCredit,
					SUM(FDebitOri) AS FDebit,
					SUM(InitBalanceOri) AS  InitBalance
			FROM Te_InitDataDetail TD 
			INNER JOIN Te_InitDataIndex TI ON TI.Id=TD.IndexId AND TI.BUId=@buid
			RIGHT JOIN #Ac_Account_L A ON A.TypeId=TD.AtypeId AND A.StypeId=TI.STypeId
			WHERE A.StypeId=@stypeid AND IsCash='1' --AND A.Deleted<>'1' AND a.SonNum=0
			GROUP BY TD.AtypeId,TI.STypeId,A.FullName,A.UserCode
			ORDER BY A.UserCode
			RETURN
	END
	
	--单一币种
	SELECT	ISNULL(te.tid,'-1') AS indexid,
			A.TypeId AS atypeid,
			A.FullName AS afullname,
			A.UserCode AS ausercode,
			ISNULL(Te.FCredit,0) as fcredit,
			ISNULL(Te.FDebit,0) as fdebit,
			ISNULL(Te.InitBalance,0) as initbalance
	FROM #Ac_Account_L A
	INNER JOIN F_GetStandard_Ac_Account(@OperatorID) L ON A.TypeId=L.TypeId AND L.STypeId=@stypeid
	LEFT JOIN ( SELECT	ti.id as tid, 
						TI.BUId,
						TI.Cid,
						TI.STypeId,
						AtypeId,
						AccountId,
						FCredit,
						FDebit,
						InitBalance
				FROM Te_InitDataDetail TD 
				INNER JOIN Te_InitDataIndex TI ON TI.Id=TD.IndexId WHERE TI.STypeId=@stypeid
				) Te ON Te.STypeId=@stypeid AND te.AtypeId=a.TypeId  AND Te.BUId=@buid AND (te.Cid=@cid OR te.Cid='0')
	WHERE A.IsCash=1 
			--AND A.SonNum=0 
			AND A.StypeId=@stypeid AND (A.Cid=@cid OR A.Cid='0') 
			--AND A.Deleted<>'1'
	ORDER BY A.UserCode
	RETURN
END 

IF @buid='2' OR @buid='3'
BEGIN
	DECLARE @transtype INT=0
	IF @buid='2'
		SET @transtype='1'
	IF @buid='3'
		SET @transtype='0'
	
	IF @cid=0
	BEGIN		
		SELECT	'-1' AS indexid,
				tb.id AS accountid,
				TB.UserCode AS acusercode,
				TB.FullName AS acfullname,
				AccountNumber AS acnumber,
				TB.ATypeId AS atypeid,
				ISNULL(A.FullName,'****') AS acatypefullname,
				ISNULL(A.UserCode,'****') AS ausercode,
				ISNULL(TE.FCreditOri,0) AS FCredit,
				ISNULL(FDebitOri,0) AS FDebit,
				ISNULL(InitBalanceOri,0) AS  InitBalance,
				ISNULL(Trani.FCreditTotalOri,0) AS tfdebit,
				ISNULL(Trani.FDebitTotalOri,0) AS tfcredit,
				--银行存款调整后期初余额=期初余额 +借方调整（企业未达账贷） - 贷方调整（企业未达账借）
				--银行对账单调整后期初余额=期初余额 + 贷方调整（银行未达账借） - 借方调整（银行未达账贷）
				CASE WHEN @buid='3' THEN ISNULL(InitBalanceOri,0)+ISNULL(Trani.FDebitTotalOri,0)-ISNULL(Trani.FCreditTotalOri,0) 
					ELSE ISNULL(InitBalanceOri,0)+ISNULL(Trani.FCreditTotalOri,0)-ISNULL(Trani.FDebitTotalOri,0)  END AS tinitbalance
		FROM Te_BankAccount TB
		INNER JOIN F_LineBank(@OperatorID) LB ON LB.TypeId=TB.Id
		LEFT JOIN #Ac_Account_L A ON TB.ATypeId=A.TypeId AND A.StypeId=@stypeid
		LEFT JOIN ( SELECT	AtypeId,
							AccountId,
							SUM(ISNULL(FCreditOri,0)) AS FCreditOri,
							SUM(ISNULL(FDebitOri,0)) AS FDebitOri,
							SUM(ISNULL(InitBalanceOri,0)) AS InitBalanceOri
					FROM Te_InitDataDetail TD 
					INNER JOIN Te_InitDataIndex TI ON TI.Id=TD.IndexId AND AccountId IS NOT NULL
					WHERE TI.STypeId=@stypeid  AND BUId=@buid 
					GROUP BY AtypeId,AccountId
					) Te ON TB.AtypeId=TE.AtypeId  AND TB.Id=TE.AccountId
		LEFT JOIN (	SELECT	AccountId,
							SUM(FDebitTotalOri) AS FDebitTotalori,
							SUM(FCreditTotalOri) AS  FCreditTotalori 
					FROM Te_AccountInTransit_Index 
					WHERE Type=@transtype
					GROUP BY AccountId) Trani ON Trani.AccountId=Tb.id  
		WHERE TB.STypeId=@stypeid  AND TB.IsDestroy=0 --AND a.SonNum=0
		ORDER BY TB.AccountNumber 
		RETURN
	END


	SELECT	TE.tid AS indexid,
			tb.id AS accountid,
			TB.UserCode AS acusercode,
			TB.FullName AS acfullname,
			AccountNumber AS acnumber,
			TB.ATypeId AS atypeid,
			ISNULL(A.FullName,'****') AS acatypefullname,
			ISNULL(A.UserCode,'****') AS ausercode,
			ISNULL(Te.FCredit,0) as fcredit,
			ISNULL(Te.FDebit,0) as fdebit,
			ISNULL(Te.InitBalance,0) as initbalance,
			ISNULL(Ti.FCreditTotal,0) AS tfdebit,
			ISNULL(Ti.FDebitTotal,0) AS tfcredit,
			--银行存款 调整后=期初余额 +借方调整（企业未达账贷） - 贷方调整（企业未达账借）
			--银行对账单 调整后=期初余额 + 贷方调整（银行未达账借） - 借方调整（银行未达账贷）
			CASE WHEN @buid='3' THEN ISNULL(Te.InitBalance,0)+ISNULL(Ti.FDebitTotal,0)-ISNULL(Ti.FCreditTotal,0) 
				ELSE ISNULL(Te.InitBalance,0)+ISNULL(Ti.FCreditTotal,0)-ISNULL(Ti.FDebitTotal,0) END AS tinitbalance
	FROM Te_BankAccount TB
	INNER JOIN F_LineBank(@OperatorID) LB ON LB.TypeId=TB.Id
	LEFT JOIN #Ac_Account_L A ON TB.ATypeId=A.TypeId AND A.StypeId=@stypeid
	LEFT JOIN ( SELECT	ti.id as tid, 
						TI.BUId,
						TI.Cid,
						TI.STypeId,
						AtypeId,
						AccountId,
						FCredit,
						FDebit,
						InitBalance
				FROM Te_InitDataDetail TD 
				INNER JOIN Te_InitDataIndex TI ON TI.Id=TD.IndexId 
				WHERE TI.STypeId=@stypeid AND Ti.BUId=@buid AND (ti.Cid=@cid or ti.Cid=0)
				) Te ON te.AtypeId=tb.aTypeId   AND TB.Id=TE.AccountId
	LEFT JOIN (	SELECT	AccountId,
						SUM(FDebitTotal) AS FDebitTotal,
						SUM(FCreditTotal) AS  FCreditTotal 
				FROM Te_AccountInTransit_Index 
				WHERE [Type]=@transtype AND Cid=@cid
				GROUP BY AccountId) TI ON TI.AccountId=Tb.id  
	WHERE TB.STypeId=@stypeid AND (TB.Cid=@cid OR tb.Cid=0) AND TB.IsDestroy=0
	ORDER BY TB.AccountNumber 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetTe_SetAcPeriod]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_GetTe_SetAcPeriod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--==========================================
--created by glj
--date 2015-01-19
--function description 保存时判断跟出纳相关数据 
--==========================================
CREATE PROCEDURE Gp_GetTe_SetAcPeriod
(
	@Fyear		INT,
	@FPeriod	INT
)
--1:当分支机构设置了启用期间，均未结束初始化，且均未有未达账数据 返回True
--2:9.5 1597 判断修改后的年度跟出纳年度是否一致
--3:9.5 1613 判断是否存在固定资产累计折旧计划表数据，
--@encode$--
AS
SET NOCOUNT ON
IF EXISTS (SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE IsUse = 1 ) AND EXISTS (SELECT TOP 1 1 FROM dbo.Te_AccountInTransit_Index )
	BEGIN
		RETURN 1
	END
IF EXISTS(SELECT TOP 1  1 FROM Te_StartPeriod WHERE (SFYear<>@Fyear OR (SFYear=@Fyear AND SFPeriod<>@FPeriod )) AND SFYear<>0 AND SFPeriod<>0 )  AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue='1')
	BEGIN
		RETURN 2
	END
IF EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FYear<>@Fyear OR FMonth<>@FPeriod) AND EXISTS(SELECT TOP 1 1 FROM Ac_DepreciationPlan)
	BEGIN
		RETURN 3
	END
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
 if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetUnitsTrack]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_GetUnitsTrack]
GO
/*
	作者: 魏伟
	时间: 2015-05-26
	描述: 获取计量单位与往来单位跟踪表数据 
*/
CREATE PROCEDURE [Gp_GetUnitsTrack]
(
	    @operatorid			VARCHAR(100),	---操作员ID
		@BillType           INT,            ---单据类型 
		@BTypeId            VARCHAR(max),   ---往来单位ID
		@PTypeId			VARCHAR(max),   ---商品ID
		@UnitId				VARCHAR(max)    ---计量单位ID
)
 	 
 --@encode$--
AS
set nocount on 
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

CREATE TABLE #Ptype (TypeID VARCHAR(200), FullName varchar(200))
CREATE TABLE #Btype (TypeID VARCHAR(200), FullName varchar(200))
CREATE TABLE #Utype (TypeID VARCHAR(200), FullName varchar(200))
 

--商品
INSERT INTO #Ptype SELECT p.typeid,p.FullName FROM dbo.ptype p INNER JOIN   dbo.F_GetAllManagerBaseTypeId(@PTypeId,1,@operatorid) f ON p.typeId = f.TypeId 

--往来单位
INSERT INTO #Btype SELECT b.typeid,b.FullName FROM dbo.btype b INNER JOIN  F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) f ON b.typeId = f.TypeId

--计量单位
	IF @UnitId = '0' OR @UnitId = '' OR @UnitId = '%'
				INSERT INTO #Utype SELECT UnitsId,FullName FROM dbo.PType_Units
			ELSE
				BEGIN					
					INSERT INTO #Utype SELECT pu.UnitsId,pu.FullName FROM dbo.PType_Units pu INNER JOIN (
					SELECT 	DISTINCT A.TypeId 
					FROM 	F_GetManDetailPType(@OperatorId) A, 
							(SELECT A FROM dbo.F_Split(@UnitId,',')) B 
					WHERE	A.TypeId LIKE B.A + '%') f ON f.TypeId=pu.UnitsId
			END  
 
  IF(@BillType<>'0')
  BEGIN 
   SELECT BillType  =CASE ut.BillType WHEN 1 THEN '采购类' ELSE '销售类' end,
		 ut.BillType AS BillTypeID,
		 ut.BillDate,
		 ut.id AS id,
		 p.FullName AS PFullName,
		 p.TypeID AS PTypeID,
		 b.FullName AS BFullName,
		 b.TypeID AS BTypeId,
		 u.FullName AS UFullName,
		 u.TypeID AS UTypeId 
  FROM dbo.UnitsTrack UT 
  INNER JOIN #Ptype p ON p.TypeID=UT.PtypeId 
  INNER JOIN #Btype b ON b.TypeID=UT.BtypeId 
  INNER JOIN #Utype u ON u.TypeID=UT.UnitId  
   WHERE UT.BillType=@BillType
  END
  ELSE 
  BEGIN
  SELECT BillType  =CASE ut.BillType WHEN 1 THEN '采购类' ELSE '销售类' end,
	     ut.BillType AS BillTypeID,
		 ut.BillDate,
		 ut.id AS id,
		 p.FullName AS PFullName,
		 p.TypeID AS PTypeID,
		 b.FullName AS BFullName,
		 b.TypeID AS BTypeId,
		 u.FullName AS UFullName,
		 u.TypeID AS UTypeId 
  FROM dbo.UnitsTrack UT 
  INNER JOIN #Ptype p ON p.TypeID=UT.PtypeId 
  INNER JOIN #Btype b ON b.TypeID=UT.BtypeId 
  INNER JOIN #Utype u ON u.TypeID=UT.UnitId  
 
  END
   
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE       PROCEDURE Gp_GetUserGroupLim 
(
 @UGId varchar(10)
)
--@encode$--
AS
set nocount on
	SELECT TOP 1 ugid,ugname,comment,Lim
	FROM UserGroup
	WHERE ugid=@UGId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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





CREATE     PROCEDURE gp_GetVerInfo_Pro
(
	@chvVer				varchar(50) output,
	@chvValidateNum		varchar(50) output
)
--@encode$--
AS
	SET NOCOUNT ON

	IF NOT EXISTS(SELECT SubValue FROM SysData1 WHERE SubNo = 1)
		RETURN 1

	SELECT @chvVer = SubValue FROM SysData1 WHERE SubNo = 1
	IF @@ERROR <> 0 RETURN 2

	IF NOT EXISTS(SELECT SubValue FROM SysData1 WHERE SubNo = 2)
	RETURN 1

	SELECT @chvValidateNum = 'NewDogVersion'





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

-- =============================================
--获取会员卡信息
-- =============================================
CREATE PROCEDURE Gp_GetVipCardInfo
(
	@vipcardcode	VARCHAR(400),
	@vipcardid		INT,
	@billstypeid	VARCHAR(50)=''
)
--@encode$--	
AS

SET NOCOUNT ON;

DECLARE @VipOverage INT = 0
DECLARE @VipLowerNumber  NUMERIC(24, 10)  = 0
DECLARE @beginCountNum INT
DECLARE @endCountNum INT,
		@vipBillStoredByStypeId INT 
		
--会卡余额低于XX提醒标示
SELECT TOP 1 @VipOverage = ISNULL(Value,0) from Userconfig where ConfigName = 'VipOverage';
SELECT TOP 1 @VipLowerNumber = ISNULL(Value,0) from Userconfig where ConfigName = 'VipLowerNumber';
SELECT TOP 1 @vipBillStoredByStypeId = ISNULL(value,0) FROM dbo.Userconfig WHERE ConfigName = 'vipBillStoredByStypeId'

SELECT  @VipOverage as VipOverage,
		@VipLowerNumber as VipLowerNumber,
		a.*,
		case a.deleted when 0 then '启用' when 2 then '停用' when 3 then '挂失' else '' end as state,
		a.czyemoney as vipczmoney,
		(a.BeginCent+a.totalCent) as endCent,
		a.czyemoney as vipczhmoney,
		CASE WHEN @vipBillStoredByStypeId = 0 THEN a.cZyeMoney ELSE ISNULL(nvs.cZyeMoney,0) END AS stypeczyemoney,
		c.PlateNumber,
		b.DisCountType,
		b.TypeName,
		b.CardTypeDiscount,	--卡类型折扣
		d.FullName AS bfullname,
		d.salezekou as salezekou,
        d.buyzekou as buyzekou,
        d.price as price,
        d.arlimittime as arlimittime,
        d.paymentltime as paymentltime,
		1 AS RepairItemsDiscount,
		c.ChargingStandardsID,
		q.FullName AS chargingstandardsname,
		E.FullName AS efullname,
		E.dtypeid AS DtypeID,
        E.Department AS dfullname,
        E.StypeID AS StypeID,
        S.FullName AS sfullname,
        aa.TypeId AS atypeid1,
        aa.FullName AS atypeid1name,
        (select denominatedid from btype where typeid=a.BTypeID) as denid,
        (select fullname from btype where typeid=(select denominatedid from btype where typeid=a.BTypeID)) as dename
FROM    nVipCardSign a
LEFT JOIN dbo.nVipCardSignStype nvs ON nvs.VipCardID = a.VipCardID AND nvs.StypeId = @billstypeid 
		LEFT JOIN NVipCardSet b ON a.vipCardTypeId = b.vipCardTypeId
		LEFT JOIN dbo.QP_RepairAutoInfo c ON a.RATypeID=c.TypeID
		LEFT JOIN dbo.btype d ON a.BTypeID=d.typeId
		LEFT JOIN QP_ChargingStandards q ON c.ChargingStandardsID=q.ID
		LEFT JOIN Employee E ON D.etypeid=E.TypeID
		LEFT JOIN Stype S ON E.StypeID=S.TypeID
		LEFT JOIN BillAtype ba ON ba.StypeId = S.TypeId AND ba.BillTypeId = '181'
		LEFT JOIN Ac_Account aa ON aa.TypeId = ba.AtypeId AND aa.StypeId = S.TypeId
WHERE 
		a.vipcardcode = @vipcardcode OR	a.VipCardID = @vipcardid
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetVipSMSMessageData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Gp_GetVipSMSMessageData
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	得到会员短信发送内容
-- 时间：	2017-10-27
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_GetVipSMSMessageData
(
	@BillNumberId	NUMERIC(10,0),--单据ID
	@BillType		INT=0,			--单据类型	
	@Sign			VARCHAR(50)		--签名
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Result
(
	Name		VARCHAR(200),--发送姓名
	Tel			VARCHAR(50),--电话号码
	tempContent VARCHAR(500)--短信内容
)

--如果不存在自动发送信息的模板，则直接返回
--判断单据是否存在  发送短信的单据类型 1：会员储值充值单181、会员批量储值充值单312 零售单305、零售退货单215、销售出库单11、销售退货单45、组合品销售出库单12、组合品销售退货单46、维修取件单167、上门维修单172、委托代销结算单141、整机更换单168、积分调整单-1、收款单4、消费调整单-2

IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE isPostSend=1) 
OR (NOT EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId=@BillNumberId AND BillType IN(181,312,305,215,11,45,12,46,167,172,141,168,4,427)) AND @BillType NOT IN(-1,-2)) 
OR (@BillType IN(-1,-2) AND NOT EXISTS(SELECT * FROM nVipAdjust WHERE BillNumberId=@BillNumberId))
	BEGIN
		SELECT * FROM #Result
		RETURN 
	END
	

--获取自动发送会员短信的模板
DECLARE 
	@iniT_Count		INT=1,
	@sumT_Count		INT=0,--需要发送短信的集中模板
	@smsId			INT,--短信ID
	@tempTypeId		INT,--短信模板ID
	@tempContent	VARCHAR(MAX),--模板短信内容
	@vipCardTypeID	VARCHAR(MAX)--模板对应的发送对象
	
--@tempTypeId=1)--会员储值充值单
--@tempTypeId=2)--会员消费（积分）
--@tempTypeId=3)--会员消费（储值）
--@tempTypeId=4)--会员消费（储值+积分）
--@tempTypeId=5)--会员积分转储值
CREATE TABLE #SMSInfoTemplate
(
	TId				INT IDENTITY(1,1),
	smsId			INT,
	tempTypeId		INT,
	tempContent		VARCHAR(500),
	vipCardTypeID	VARCHAR(MAX)
)
INSERT INTO #SMSInfoTemplate(smsId,tempTypeId,tempContent,vipCardTypeID)
SELECT 
	T.smsId,
	T.tempTypeId,
	tempContent,
	dbo.F_GetVipTemplateCardTypeName(smsId,1)
FROM SMSInfo_Template T
WHERE 
	T.isPostSend=1
SELECT @sumT_Count=@@ROWCOUNT

--=================================返回内容=================================================
CREATE TABLE #BillDetails(
	DId				INT IDENTITY(1,1),
	持卡人			VARCHAR(200) NOT NULL DEFAULT(''),
	系统时间		VARCHAR(100) NOT NULL DEFAULT(''),
	尾号			VARCHAR(8) NOT NULL DEFAULT(''),
	电话号码		VARCHAR(50) NOT NULL DEFAULT(''),
	本次储值金额	NUMERIC(24,2) NOT NULL DEFAULT(0.00),
	储值余额		NUMERIC(24,2) NOT NULL DEFAULT(0.00),
	本次消费金额	NUMERIC(24,2) NOT NULL DEFAULT(0.00),
	本次积分		INT NOT NULL DEFAULT(0),
	积分余额		INT NOT NULL DEFAULT(0),
	本次储值结算金额  NUMERIC(24,2)  NOT NULL DEFAULT(0.00),
	原积分余额		NUMERIC(24,2) NOT NULL DEFAULT(0),
	原储值余额		NUMERIC(24,2) NOT NULL DEFAULT(0.00),
	分支机构		VARCHAR(200) NOT NULL DEFAULT(''),
	仓库			VARCHAR(200) NOT NULL DEFAULT(''),
	门店			VARCHAR(200) NOT NULL DEFAULT(''),
	兑换积分		INT NOT NULL DEFAULT(0),
	转储值金额		NUMERIC(24,2) NOT NULL DEFAULT(0.00),
	签名			VARCHAR(50) NOT NULL DEFAULT('')
)

DECLARE 
	@dId		INT=1,
	@dCount		INT=0,
	@持卡人		VARCHAR(200)='',
	@系统时间	VARCHAR(100)=CONVERT(VARCHAR(100),GETDATE(),20),
	@尾号		VARCHAR(8)='',
	@电话号码	VARCHAR(50)='',
	@本次储值金额 NUMERIC(22,2)=0.00,
	@储值余额	NUMERIC(22,2)=0.00,
	@本次消费金额 NUMERIC(22,2)=0.00,
	@本次积分	INT=0,
	@积分余额	INT=0,
	@本次储值结算金额 NUMERIC(22,2)=0.00,
	@原积分余额	INT=0,
	@原储值余额 NUMERIC(22,2)=0.00,
	@分支机构	VARCHAR(200)='',
	@仓库		VARCHAR(200)='',
	@门店		VARCHAR(200)='',
	@兑换积分	INT=0,
	@转储值金额	NUMERIC(24,2)=0.00,
	@isExists	INT=0,
	@tempStr	VARCHAR(MAX)=''
WHILE(@iniT_Count<=@sumT_Count)
	BEGIN
		SELECT @smsId=smsId,@tempTypeId=tempTypeId,@tempContent=tempContent,@vipCardTypeID=vipCardTypeID FROM #SMSInfoTemplate WHERE TId=@iniT_Count
		
		IF(@tempTypeId=1 AND @BillType IN(181,312))--会员储值充值单
		BEGIN
			IF(@BillType=181)--会员储值充值单
			BEGIN
				INSERT INTO #BillDetails(持卡人,系统时间,尾号,电话号码,本次储值金额,储值余额,原储值余额,积分余额,原积分余额,签名,分支机构)
				SELECT 
					C.Bname,
					CONVERT(VARCHAR(100),GETDATE(),20),
					RIGHT(C.VipCardCode,4),
					C.Btel,
					ISNULL(B.totalmoney,0),
					ISNULL(C.cZyeMoney,0),
					ISNULL(C.cZyeMoney,0)-ISNULL(B.totalmoney,0),
					ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0),--积分余额
					ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0),--原积分余额
					@Sign,
					S.FullName--分支机构
				FROM BillIndex B
				INNER JOIN nVipCardSign C ON C.VipCardID=B.VipCardID AND c.Btel<>''
				INNER JOIN SType S ON S.TypeId=B.Stypeid
				WHERE 
					B.BillNumberId=@BillNumberId
					AND B.NewPosBill=0
					AND (@vipCardTypeID='0' OR (@vipCardTypeID<>'0' AND EXISTS(SELECT * FROM SMSInfo_Template_CardType WHERE smsId=@smsId AND VipCardTypeID=C.VipCardTypeID)))
				SELECT @dCount=@@ROWCOUNT				
				SET @isExists=1
			END
			IF(@BillType=312)--会员批量储值充值单
			BEGIN
				INSERT INTO #BillDetails(持卡人,系统时间,尾号,电话号码,本次储值金额,储值余额,原储值余额,积分余额,原积分余额,签名,分支机构)
				SELECT 
					C.Bname,
					CONVERT(VARCHAR(100),GETDATE(),20),
					RIGHT(C.VipCardCode,4),
					C.Btel,
					ChargeMoney,
					AfterChargeMoney,
					BeforeChargeMoney,
					ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0),--积分余额
					ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0),--原积分余额
					@Sign,
					s.FullName
				FROM BillIndex B
				INNER JOIN VipAddMoneyBatchBill BB ON BB.BillNumberId=B.BillNumberId
				INNER JOIN nVipCardSign C ON C.VipCardID=BB.VipCardID AND c.Btel<>''
				INNER JOIN SType S ON S.TypeId=B.Stypeid
				WHERE 
					B.BillNumberId=@BillNumberId
					AND B.NewPosBill=0
					AND (@vipCardTypeID='0' OR (@vipCardTypeID<>'0' AND EXISTS(SELECT * FROM SMSInfo_Template_CardType WHERE smsId=@smsId AND VipCardTypeID=C.VipCardTypeID)))
				SELECT @dCount=@@ROWCOUNT		
				SET @isExists=1
			END	
		END
		ELSE IF(@tempTypeId=5 AND @BillType=427)--积分转储值单
		BEGIN
			INSERT INTO #BillDetails(持卡人,系统时间,尾号,电话号码,储值余额,原储值余额,积分余额,原积分余额,签名,分支机构,兑换积分,转储值金额,门店,仓库)
			SELECT 
				C.Bname,
				CONVERT(VARCHAR(100),GETDATE(),20),
				RIGHT(C.VipCardCode,4),
				C.Btel,
				ISNULL(C.cZyeMoney,0),
				ISNULL(C.cZyeMoney,0)-ISNULL(CB.ChangeMoney,0),
				ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0),--积分余额
				ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0)+ISNULL(CB.ChangeCent,0),--原积分余额
				@Sign,
				S.FullName,
				CB.ChangeCent,
				CB.ChangeMoney,
				CASE WHEN B.NewPosBill=1 THEN (SELECT FullName FROM posinfo WHERE PosID=B.posid) ELSE '' END,
				CASE WHEN B.NewPosBill=1 THEN (select S.FullName from posinfo P INNER JOIN stock S ON PosID=B.posid AND S.typeId=P.ktypeid) ELSE '' END
			FROM BillIndex B
			INNER JOIN VipCentToMoneyBill CB ON CB.BillNumberId=B.BillNumberId
			INNER JOIN nVipCardSign C ON C.VipCardID=CB.VipCardID AND c.Btel<>''
			INNER JOIN SType S ON S.TypeId=B.Stypeid
			WHERE 
				B.BillNumberId=@BillNumberId
				AND (@vipCardTypeID='0' OR (@vipCardTypeID<>'0' AND EXISTS(SELECT * FROM SMSInfo_Template_CardType WHERE smsId=@smsId AND VipCardTypeID=C.VipCardTypeID)))
			SELECT @dCount=@@ROWCOUNT		
			SET @isExists=1
		END
		ELSE IF((@BillType=-2 AND @tempTypeId=4) OR(@BillType=-1 AND @tempTypeId=2))-- @BillType=-2消费调整单 @BillType=-1积分调整单
		BEGIN
			INSERT INTO #BillDetails(持卡人,系统时间,尾号,电话号码,本次储值金额,储值余额,本次消费金额,本次积分,积分余额,本次储值结算金额,原积分余额,原储值余额,签名)
			SELECT 
				C.Bname,
				CONVERT(VARCHAR(100),GETDATE(),20),
				RIGHT(C.VipCardCode,4),
				C.Btel,
				0,--本次储值金额
				ISNULL(C.cZyeMoney,0),--储值余额
				CASE WHEN @BillType=-2 THEN ISNULL(B.SumCost,0) ELSE 0 END,--本次消费金额
				CASE WHEN @BillType=-1 THEN ISNULL(B.SumCost,0) ELSE 0 END,--本次积分
				ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0),--积分余额
				0,--本次储值结算金额
				CASE WHEN @BillType=-2 THEN ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0)
					ELSE CASE WHEN (ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0))-ISNULL(B.SumCost,0)>0 THEN (ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0))-ISNULL(B.SumCost,0) ELSE 0 END 
				END,--原积分余额
				ISNULL(C.cZyeMoney,0),--原储值余额
				@Sign
			FROM nVipAdjust B
			INNER JOIN nVipCardSign C ON C.VipCardID=B.VipNo AND c.Btel<>''
			WHERE  
				B.BillNumberId=@BillNumberId
				AND (@vipCardTypeID='0' OR (@vipCardTypeID<>'0' AND EXISTS(SELECT * FROM SMSInfo_Template_CardType WHERE smsId=@smsId AND VipCardTypeID=C.VipCardTypeID)))
			SELECT @dCount=@@ROWCOUNT	
			SET @isExists=1
		END
		ELSE IF(@tempTypeId IN(3,4) AND @BillType=4)--收款单
		BEGIN
			INSERT INTO #BillDetails(持卡人,系统时间,尾号,电话号码,本次储值金额,储值余额,本次消费金额,本次积分,积分余额,本次储值结算金额,原积分余额,原储值余额,签名,分支机构)
			SELECT 
				C.Bname,
				CONVERT(VARCHAR(100),GETDATE(),20),
				RIGHT(C.VipCardCode,4),
				C.Btel,
				0,--本次储值金额
				ISNULL(C.cZyeMoney,0),--储值余额
				ISNULL(B.totalmoney,0),--本次消费金额   
				B.JF,--本次积分
				ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0),--积分余额
				ISNULL(M.Total,0),--本次储值结算金额
				ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0)-ISNULL(B.JF,0),--原积分余额
				B.vipCZMoney,--原储值余额
				@Sign,
				S.FullName
			FROM BillIndex B
			INNER JOIN gatheringBill M ON M.BillNumberId=B.BillNumberId AND ((B.VipCardID<>-1 AND M.VipCardID=B.VipCardID) OR (B.VipCardID=-1 AND M.VipCardID<>-1))
			INNER JOIN nVipCardSign C ON (C.VipCardID=M.VipCardID OR C.VipCardID=B.VipCardID) AND c.Btel<>''
			INNER JOIN SType S ON S.TypeId=B.Stypeid
			WHERE
				B.BillNumberId=@BillNumberId
				AND B.NewPosBill=0
				AND (@vipCardTypeID='0' 
						OR (@vipCardTypeID<>'0' AND EXISTS(SELECT * FROM SMSInfo_Template_CardType WHERE smsId=@smsId AND VipCardTypeID=C.VipCardTypeID)))
			SELECT @dCount=@@ROWCOUNT	
			SET @isExists=1
		END
		ELSE IF(@BillType IN(305,215,11,45,12,46,167,172,141,168) AND @tempTypeId IN(2,3,4))--正常单据
		BEGIN
			INSERT INTO #BillDetails(持卡人,系统时间,尾号,电话号码,本次储值金额,储值余额,本次消费金额,本次积分,积分余额,本次储值结算金额,原积分余额,原储值余额,签名,分支机构,仓库)
			SELECT 
				C.Bname,
				CONVERT(VARCHAR(100),GETDATE(),20),
				RIGHT(C.VipCardCode,4),
				C.Btel,
				0,--本次储值金额
				ISNULL(C.cZyeMoney,0),--储值余额
				CASE WHEN B.BillType IN(215,45,46) THEN -ISNULL(B.totalmoney,0) ELSE ISNULL(B.totalmoney,0) END,--本次消费金额   
				B.JF,--本次积分
				ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0),--积分余额
				CASE WHEN B.BillType IN(215,45,46) THEN -ISNULL(M.Total,0) ELSE ISNULL(M.Total,0) END,--本次储值结算金额
				ISNULL(C.BeginCent,0)+ISNULL(C.totalCent,0)-ISNULL(B.JF,0),--原积分余额
				B.vipCZMoney,--原储值余额
				@Sign,
				s.FullName,
				K.FullName
			FROM BillIndex B
			LEFT JOIN BillMulAccount M ON M.BillNumberId=B.BillNumberId AND ((B.VipCardID<>-1 AND M.VipCardID=B.VipCardID) OR (B.VipCardID=-1 AND M.VipCardID<>-1))
			INNER JOIN nVipCardSign C ON (C.VipCardID=M.VipCardID OR C.VipCardID=B.VipCardID) AND c.Btel<>''
			INNER JOIN SType S ON S.TypeId=B.Stypeid
			INNER JOIN stock K ON K.typeId=B.ktypeid
			WHERE
				B.BillNumberId=@BillNumberId
				AND B.NewPosBill=0
				AND (@vipCardTypeID='0' 
						OR (@vipCardTypeID<>'0' AND EXISTS(SELECT * FROM SMSInfo_Template_CardType WHERE smsId=@smsId AND VipCardTypeID=C.VipCardTypeID)))
			SELECT @dCount=@@ROWCOUNT	
			SET @isExists=1
		END
		
		--存在发送消息
		IF(@isExists=1)
		BEGIN
			SET @dId=1
			WHILE(@dId<=@dCount)
			BEGIN
				SET @tempStr=@tempContent
				SELECT @持卡人=持卡人,@系统时间=系统时间,@尾号=尾号,@电话号码=电话号码,@本次储值金额=本次储值金额,@储值余额=储值余额,@本次消费金额=本次消费金额,@本次积分=本次积分,@积分余额=积分余额,@本次储值结算金额=本次储值结算金额,@原积分余额=原积分余额,@原储值余额=原储值余额,@分支机构=分支机构,@仓库=仓库,@门店=门店,@兑换积分=兑换积分,@转储值金额=转储值金额 FROM #BillDetails WHERE DId=@dId
				
				SET @tempStr=REPLACE(@tempStr,'@持卡人',@持卡人)
				SET @tempStr=REPLACE(@tempStr,'@系统时间',@系统时间)
				SET @tempStr=REPLACE(@tempStr,'@尾号',@尾号)
				SET @tempStr=REPLACE(@tempStr,'@本次储值金额',@本次储值金额)
				SET @tempStr=REPLACE(@tempStr,'@储值余额',@储值余额)
				SET @tempStr=REPLACE(@tempStr,'@本次消费金额',@本次消费金额)
				SET @tempStr=REPLACE(@tempStr,'@本次积分',@本次积分)
				SET @tempStr=REPLACE(@tempStr,'@积分余额',@积分余额)
				SET @tempStr=REPLACE(@tempStr,'@本次储值结算金额',@本次储值结算金额)
				SET @tempStr=REPLACE(@tempStr,'@原积分余额',@原积分余额)
				SET @tempStr=REPLACE(@tempStr,'@原储值余额',@原储值余额)
				SET @tempStr=REPLACE(@tempStr,'@签名',@Sign)
				SET @tempStr=REPLACE(@tempStr,'@分支机构',@分支机构)
				SET @tempStr=REPLACE(@tempStr,'@仓库',@仓库)
				SET @tempStr=REPLACE(@tempStr,'@门店',@门店)
				SET @tempStr=REPLACE(@tempStr,'@兑换积分',@兑换积分)
				SET @tempStr=REPLACE(@tempStr,'@转储值金额',@转储值金额)
				
				INSERT INTO #Result(Name,Tel,tempContent) VALUES(@持卡人,@电话号码,@tempStr)
				SET @dId=@dId+1
			END
		END
		SET @isExists=0
		SET @iniT_Count+=1
	END

SELECT * FROM #Result 

--===================================删除临时表【BEGIN】===================================

DROP TABLE #Result

--===================================删除临时表【END】  ===================================
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/************************************************************
 * 创 建 人：罗淮文
 * 创建时间: 2014-04-08 11:40:50
 * 修改日期：2014-06-03
 * 内容描述：获取指定商品的虚拟库存
 * 修改日期：2014-09-03
 * 修改内容：受批次号，自由项控制
 ************************************************************/
IF EXISTS (SELECT * FROM sysobjects s WHERE s.id=OBJECT_ID('[dbo].[Gp_GetVirtualStock]') and OBJECTPROPERTY(id, N'IsProcedure')= 1)
BEGIN
	DROP PROC Gp_GetVirtualStock
END
GO
CREATE PROC Gp_GetVirtualStock(
	@TypeId			VARCHAR(MAX),					--商品ID
	@OperatorId		VARCHAR(100),					--操作员ID
	@szKtypeId		VARCHAR(100),					--仓库ID
	@StypeId		VARCHAR(100),					--分支机构
	@costing		varchar(10)='',					--账套类型，手工指定账套
	@costprice		 NUMERIC(24, 10) =NULL,				--批次成本价
	@goodsnumber	varchar(200)='',				--批号
	@producedate	varchar(30)='',					--生产日期
	@validdate		varchar(30)='',					--效期至
	@itemid			varchar(10)='',					--自由项
	@isSelectedGoodsNo varchar(3) = '0'
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	DECLARE @ParId VARCHAR(100) = '00000'	--商品父ID
	DECLARE @VirtualQtySql VARCHAR(MAX)		--虚拟库存计算公式SQL

	IF @TypeId IS NOT NULL
	BEGIN
		SELECT @ParId = ParId FROM ptype WHERE typeid=@TypeId
	END
	--获取虚拟库存计算公式
	SELECT @VirtualQtySql = u.[Value]
		FROM   Userconfig u
		WHERE  u.ConfigName = 'VirtualQtySQL'
	IF @VirtualQtySql IS NULL OR @VirtualQtySql = ''
	BEGIN
		--默认公式：
		--	虚拟库存=账面库存+已采购订货数量-已销售订货数量+草稿入库-草稿出库
		SET @VirtualQtySql = 'isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)'
	END

	--------多单位计算[按基本单位计算]Start--------
	DECLARE @Qty    NVARCHAR(2000),
			@Lendqty NVARCHAR(2000),
			@Borrowqty NVARCHAR(2000),
			@RQty NVARCHAR(2000),
			@CQty NVARCHAR(2000),
			@BuyOrderQty NVARCHAR(2000),
			@BuyReachQty NVARCHAR(2000),
			@SaleOrderQty NVARCHAR(2000),
			@SaleReachQty NVARCHAR(2000),
			@temptable  NVARCHAR(2000)

	SELECT  @Qty='o.Qty',
			@Lendqty='SUM(o.Lend-o.LendBack)',
			@Borrowqty='SUM(o.Borrow-o.BorrowBack)',   
			@BuyReachQty='o.BuyReachQty', 
			@RQty='o.RQty',        
			@CQty='o.CQty',        
			@BuyOrderQty='o.BuyOrderQty', 
			@BuyReachQty='o.BuyReachQty', 
			@SaleOrderQty='o.SaleOrderQty',
			@SaleReachQty='o.SaleReachQty',
			@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1','1')
	--------多单位计算End---------

	IF OBJECT_ID('tempdb.dbo.#GetManPTypeAll') IS NOT NULL
	BEGIN
		DROP TABLE #GetManPTypeAll
	END
	--商品基本信息
	CREATE TABLE #GetManPTypeAll
	(
		TypeId			varchar(100),
		FullName        varchar(200),
		UserCode        varchar(100),
		Sonnum			 NUMERIC(24, 10) ,
		Parid           varchar(200),
		unit1           varchar(100),
		unit2           varchar(100),
		unitrate1       varchar(100),
		unitname       NVARCHAR(2000),
		baseunitname    NVARCHAR(2000),
		unitrate        NVARCHAR(2000)
	)
	CREATE UNIQUE CLUSTERED INDEX [PtypeAllidx] ON [dbo].[#GetManPTypeAll] 
	(
		[typeId]
	)

	SET @SQL='INSERT INTO #GetManPTypeAll SELECT P.TypeId,P.FullName,P.UserCode,P.Sonnum,P.Parid,P.unit1,P.unit2,P.unitrate1,'
	SET @SQL+='u1.fullname,u1.fullname,1'
	SET @SQL+='  FROM F_GetManPTypeAll('''+@OperatorID+''') P inner join ptype p1 on p.typeid=p1.typeid '+@temptable
	SET @SQL+=' WHERE P.Parid='''+@Parid+''' AND p1.TypeId='''+@TypeId+''''
	EXEC(@SQL)
	--处理商品父编码
	DECLARE @MMPtypeid VARCHAR(100)
	SET @MMPtypeid=''
	IF LEFT(@parid,len(@MMPtypeid))<>@MMPtypeid 
	BEGIN
		SET @parid=LEFT(@MMPtypeid,len(@MMPtypeid)-5)
	END
	IF @Parid='' 
	BEGIN
		SET @Parid='00000'
	END

	-- 全部仓库
	IF @szKtypeId='' OR @szKtypeId='00000'
	BEGIN
		SELECT @szKtypeId='%'	
	END
	
--被引用的订单数量
IF OBJECT_ID('tempdb.dbo.#RefrenceQty') IS NOT NULL
BEGIN
	DROP TABLE #RefrenceQty
END
CREATE TABLE #RefrenceQty
(
	ptypeid varchar(100),
	ktypeid varchar(100),
	billnumberid varchar(100),
	refQty  NUMERIC(24, 10) ,
	saleOrBuy varchar(10)
)
--被引用的采购订单
SET @SQL = 'INSERT INTO #RefrenceQty 
select b.ptypeid,b.ktypeid,b.billnumberid,
CASE WHEN SUM(b.qty) > SUM(o.orderQty) 
THEN SUM(o.orderQty) 
ELSE  sum(b.qty) end AS saleQty,''B''  
from buybill b 
INNER join 
(
	SELECT o.orderid,o.ptypeid,o.ktypeid,sum(o.qty)-isnull(sum(t.buyQty),0) as orderQty,o.goodscostprice,o.goodsnumber,o.produceDate,o.ValidDate,o.ItemID
	FROM orderbill o
	inner join
	(
		SELECT orderid,ptypeid,ktypeid,sum(buyQty) as buyQty,goodscostprice,goodsnumber,produceDate,ValidDate,ItemID
		FROM
		(
			SELECT s.orderid,s.ptypeid,s.ktypeid,case when b.ifcheck = ''f'' then 0 else sum(s.qty) end as buyQty,
			s.goodscostprice,s.goodsnumber,s.produceDate,s.ValidDate,s.ItemID
			FROM buybill s inner join billindex b on s.billnumberid=b.billnumberid
			group by s.orderid,s.ptypeid,s.ktypeid,b.ifcheck,s.goodscostprice,s.goodsnumber,s.produceDate,s.ValidDate,s.ItemID
		) t group by orderid,ptypeid,ktypeid,goodscostprice,goodsnumber,produceDate,ValidDate,ItemID
	) t on o.orderid=t.orderid AND o.goodscostprice=t.goodscostprice AND o.goodsnumber=t.goodsnumber AND o.produceDate=t.produceDate
	AND o.validdate=t.validdate AND o.itemid=t.itemid
	GROUP BY o.orderid,o.ptypeid,o.ktypeid,o.goodscostprice,o.goodsnumber,o.produceDate,o.ValidDate,o.ItemID
) o on b.orderid=o.orderid
INNER JOIN billindex i on b.billnumberid=i.billnumberid and i.draft=1
AND i.ifwx=0 AND i.IsIni=0
WHERE b.ptypeid='''+@TypeId+''' AND b.ktypeid='''+@szKtypeId+''''
IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL
	BEGIN
		SET @SQL = @SQL + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END
	IF @isSelectedGoodsNo='1'
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	ELSE
	BEGIN
		IF @producedate IS NOT NULL AND @producedate <> ''
		BEGIN
			SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		END
		IF @validdate IS NOT NULL AND @validdate <> ''
		BEGIN
			SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
		END
	END
END
IF(@goodsnumber <> '')
BEGIN
	SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
END
if @itemid <> '' AND @itemid <> 0
BEGIN
	SET @SQL = @SQL +' AND o.itemid='''+@itemid+''''
END
SET @SQL = @SQL + ' group by b.ptypeid,b.ktypeid,b.billnumberid,b.orderid'
/**
注释，不再执行计算被引用的采购订单数量
修改日期：2014-11-10
修改原因：当虚拟库存公式为："草稿入库"时虚拟库存数量与报表中的虚拟库存数量不一致
EXEC(@SQL)
**/
--被引用的销售出库订单
SET @SQL='INSERT INTO #RefrenceQty
SELECT b.ptypeid,b.ktypeid,b.billnumberid,
CASE WHEN SUM(b.qty) > SUM(o.orderQty) 
THEN SUM(o.orderQty) 
WHEN SUM(b.qty) <= SUM(o.orderQty) 
then sum(b.qty) end AS saleQty,''s'' 
FROM salebill b 
INNER join 
(
	SELECT o.orderid,o.ptypeid,o.ktypeid,sum(o.qty)-isnull(sum(t.saleQty),0) as orderQty,o.goodscostprice,o.goodsnumber,o.producedate,o.validdate,o.itemid
	FROM orderbill o
	inner join
	(
		SELECT orderid,ptypeid,ktypeid,sum(saleQty) as saleQty,t.goodscostprice,t.goodsnumber,t.producedate,t.validdate,t.itemid
		FROM
		(
			SELECT s.orderid,s.ptypeid,s.ktypeid,case when b.ifcheck = ''f'' then 0 else sum(s.qty) end as saleQty,
			s.goodscostprice,s.goodsnumber,s.producedate,s.validdate,s.itemid 
			FROM salebill s
			inner join billindex b on s.billnumberid=b.billnumberid
			group by s.orderid,s.ptypeid,s.ktypeid,b.ifcheck,s.goodscostprice,s.goodsnumber,s.producedate,s.validdate,s.itemid
		) t group by orderid,ptypeid,ktypeid,goodscostprice,goodsnumber,producedate,validdate,itemid
	) t on o.orderid=t.orderid
	group by o.orderid,o.ptypeid,o.ktypeid,o.goodscostprice,o.goodsnumber,o.producedate,o.validdate,o.itemid
) o on b.orderid=o.orderid
inner join billindex i on b.billnumberid=i.billnumberid and i.draft=1
AND i.ifwx=0 AND i.IsIni=0
where b.ptypeid='''+@TypeId+''' and b.ktypeid='''+@szKtypeId+''''

IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL
	BEGIN
		SET @SQL = @SQL + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END
	IF @isSelectedGoodsNo='1'
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	ELSE
	BEGIN
		IF @producedate IS NOT NULL AND @producedate <> ''
		BEGIN
			SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		END
		IF @validdate IS NOT NULL AND @validdate <> ''
		BEGIN
			SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
		END
	END
END
IF(@goodsnumber <> '')
BEGIN
	SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
END
if @itemid <> '' AND @itemid <> 0
BEGIN
	SET @SQL = @SQL +' AND o.itemid='''+@itemid+''''
END
SET @SQL = @SQL + ' group by b.ptypeid,b.ktypeid,b.billnumberid,b.orderid'
/**
注释，不再执行计算被引用的销售订单数量
修改日期：2014-11-10
修改原因：当虚拟库存公式为："草稿出库"时虚拟库存数量与报表中的虚拟库存数量不一致
EXEC(@SQL)
**/

SET @SQL = ''
-------------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb.dbo.#DGS') IS NOT NULL
BEGIN
	DROP TABLE #DGS
END
CREATE TABLE #DGS
(
	PTypeId		varchar(100),
	RQty		 NUMERIC(24, 10) ,
	CQty		 NUMERIC(24, 10) 
)
IF OBJECT_ID('tempdb.dbo.#InOutStockDraft') IS NOT NULL
BEGIN
	DROP TABLE #InOutStockDraft
END
CREATE TABLE #InOutStockDraft
(
	PTypeId varchar(100),
	RQty	 NUMERIC(24, 10) ,
	CQty	 NUMERIC(24, 10) 
)
DECLARE @SQL_WHERE VARCHAR(MAX)=''
IF(@costing = '3')
BEGIN
	IF @isSelectedGoodsNo='1'
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND produceDate='''+@producedate+''''
		SET @SQL_WHERE = @SQL_WHERE + '  AND validdate='''+@validdate+''''
	END
	ELSE
	BEGIN
		IF @producedate IS NOT NULL AND @producedate <> ''
		BEGIN
			SET @SQL_WHERE = @SQL_WHERE + ' AND produceDate='''+@producedate+''''
		END
		IF @validdate IS NOT NULL AND @validdate <> ''
		BEGIN
			SET @SQL_WHERE = @SQL_WHERE + '  AND validdate='''+@validdate+''''
		END
	END
END
IF(@goodsnumber <> '')
BEGIN
	SET @SQL_WHERE = @SQL_WHERE + ' AND goodsnumber='''+@goodsnumber+''''
END
if @itemid <> '' AND @itemid <> 0
BEGIN
	SET @SQL_WHERE = @SQL_WHERE +' AND itemid='''+@itemid+''''
END

--插入商品入库库存和出库库存(草稿)
	SET @SQL = 'INSERT INTO #DGS(PTypeId,RQty,CQty)
	SELECT PTypeId,ISNULL(SUM(RQty),0) AS RQty,ISNULL(SUM(CQty),0) AS CQty
	FROM GoodsStocks_Draft B WHERE KTypeID='''+@szKtypeId+''' AND PTypeId='''+@TypeId+''''+@SQL_WHERE+' GROUP BY PTypeId'
EXEC(@SQL)

---------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb.dbo.#ResultLeftTable') IS NOT NULL
	BEGIN
		DROP TABLE #ResultLeftTable
	END
	CREATE TABLE #ResultLeftTable
	(
		pTypeId			 VARCHAR(50),
		saleQty			  NUMERIC(24, 10) 
	)

	SELECT  @SQL='INSERT INTO #ResultLeftTable (pTypeId,saleqty)
		SELECT g.typeId,0 FROM inoutstocktable S  
		--inner join dbo.F_GetManPTypeDetailALL('''+@OperatorID+''') pp on S.ptypeid=pp.typeid
		INNER join #GetManPTypeAll  g on  S.ptypeid like g.typeid +''%''  
		WHERE S.KTypeId = '''+@szKtypeId+''''+@SQL_WHERE+''
	EXEC (@SQL)
-----------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb.dbo.#LeftJoinTable') IS NOT NULL
	BEGIN
		DROP TABLE #LeftJoinTable
	END
	CREATE TABLE #LeftJoinTable
	(
		TypeId			 VARCHAR(50),
		RQty			 NUMERIC(24, 10) ,
		CQty			 NUMERIC(24, 10) ,
		Qty				 NUMERIC(24, 10) ,
		Lendqty			 NUMERIC(24, 10) ,
		Borrowqty		 NUMERIC(24, 10) ,
		SaleOrderQty	 NUMERIC(24, 10) ,
		BuyOrderQty		 NUMERIC(24, 10) ,
		SaleReachQty	 NUMERIC(24, 10) ,
		BuyReachQty		 NUMERIC(24, 10) 
	)
--草稿库存
SELECT @SQL='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)
	SELECT o.PTypeId AS TypeId,'+@RQty+','+@CQty+',0 AS Qty,0 AS Lendqty,0 AS Borrowqty,0 AS SaleOrderQty,0 AS BuyOrderQty,0 AS SaleReachQty,0 AS BuyReachQty
	FROM #DGS o INNER JOIN ptype p1 on o.ptypeid=p1.typeid '+ @temptable	
EXEC (@SQL) 
--账面库存
SELECT @SQL ='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)		
SELECT 	p1.typeid,0 AS RQty,0 AS CQty,SUM('+@qty+') AS qty,0 AS Lendqty,0 AS Borrowqty,0 AS SaleOrderQty,0 AS BuyOrderQty,0 AS SaleReachQty,0 AS BuyReachQty
FROM GOODSSTOCKS_QTY o INNER JOIN ptype p1 on o.ptypeid=p1.typeid '+ @temptable+' WHERE o.KTypeId='''+@szKtypeId+''''
SELECT @SQL = @SQL +' AND o.ptypeid='''+@TypeId+''''

IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL
	BEGIN
		SET @SQL = @SQL + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END
	IF @isSelectedGoodsNo='1'
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	ELSE
	BEGIN
		IF @producedate IS NOT NULL AND @producedate <> ''
		BEGIN
			SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		END
		IF @validdate IS NOT NULL AND @validdate <> ''
		BEGIN
			SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
		END
	END
END
IF(@goodsnumber <> '')
BEGIN
	SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
END
IF @itemid <> '' AND @itemid <> '0'
BEGIN
	SET @SQL = @SQL + ' AND o.itemid='''+@itemid+''''
END
SET @SQL = @SQL + ' GROUP BY p1.typeid '
EXEC (@SQL)	
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT @SQL ='		
	INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)					
	SELECT 	'''+@TypeId+''' AS typeid,0 AS RQty,0 AS CQty,0 AS qty,'+@Lendqty+' AS Lendqty,'+@Borrowqty+' AS  Borrowqty,
			0 AS SaleOrderQty,0 AS BuyOrderQty,0 AS SaleReachQty,0 AS BuyReachQty FROM 	V_LendStatus o 
		   INNER JOIN ptype p1  on o.ptypeid=p1.typeid ' + @temptable+'
		   WHERE o.ktypeid='''+@szKtypeId+'''  AND o.ptypeid = '''+@TypeId+''''
IF(@costing = '3')
BEGIN
	IF @isSelectedGoodsNo='1'
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	ELSE
	BEGIN
		IF @producedate IS NOT NULL AND @producedate <> ''
		BEGIN
			SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		END
		IF @validdate IS NOT NULL AND @validdate <> ''
		BEGIN
			SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
		END
	END
END
IF(@goodsnumber <> '')
BEGIN
	SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
END
IF @itemid <> '' AND @itemid <> '0'
BEGIN
	SET @SQL = @SQL + ' AND o.itemid='''+@itemid+''''
END
EXEC (@SQL)	
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
--采购订单
SELECT @SQL ='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)	
			SELECT '''+@TypeId+''' AS typeid,0 AS RQty,0 AS CQty,0 AS qty,0 AS LendQty,0 AS BorrowQty,0 AS SaleOrderQty,
			CASE WHEN ISNULL(SUM(O.QTY),0) - ISNULL(SUM(O.ReachQty),0) >=0 THEN ISNULL(SUM(O.QTY),0) ELSE 0 END AS BuyOrderQty,
			0 AS SaleReachQty,
			CASE WHEN ISNULL(SUM(O.QTY),0) - ISNULL(SUM(O.ReachQty),0) >=0 THEN ISNULL(SUM(O.ReachQty),0) ELSE 0 END AS BuyReachQty
			FROM orderbill O INNER JOIN orderindex I ON O.billnumberid=i.billnumberid 
			INNer join ptype p1  on o.ptypeid=p1.typeid '+ @temptable+' 
			WHERE O.ktypeid='''+@szKtypeId+''' AND O.Ptypeid='''+@TypeId+''' AND I.BillType=301
			AND I.BillOver=0 AND I.ORDERSTATE<>1 and O.BillOver=0 AND I.ifaudit=1'
			
IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL --AND @costprice <> ''
	BEGIN
		SET @SQL = @SQL + ' AND o.price='+CAST(@costprice AS VARCHAR)+''
	END
	IF @isSelectedGoodsNo='1'
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	ELSE
	BEGIN
		IF @producedate IS NOT NULL AND @producedate <> ''
		BEGIN
			SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		END
		IF @validdate IS NOT NULL AND @validdate <> ''
		BEGIN
			SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
		END
	END
END
IF(@goodsnumber <> '')
BEGIN
	SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
END
IF @itemid <> '' AND @itemid <> '0'
BEGIN
	SET @SQL = @SQL + ' AND o.itemid='''+@itemid+''''
END
EXEC (@SQL)

--销售订单
SELECT @SQL ='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)	
			SELECT '''+@TypeId+''' AS typeid,0 AS RQty,0 AS CQty,0 AS qty,0 AS LendQty,0 AS BorrowQty,
			CASE WHEN ISNULL(SUM(O.QTY),0) - ISNULL(SUM(O.ReachQty),0) >=0 THEN ISNULL(SUM(O.QTY),0) ELSE 0 END AS SaleOrderQty,
			0 AS BuyOrderQty,
			CASE WHEN ISNULL(SUM(O.QTY),0) - ISNULL(SUM(O.ReachQty),0) >=0 THEN ISNULL(SUM(O.ReachQty),0) ELSE 0 END AS SaleReachQty,
			0 AS BuyReachQty
			FROM orderbill O INNER JOIN orderindex I ON O.billnumberid=i.billnumberid 
			INNER JOIN ptype p1  on o.ptypeid=p1.typeid '+ @temptable+' 
			WHERE O.ktypeid='''+@szKtypeId+''' AND O.Ptypeid='''+@TypeId+''' AND I.BillType=300
			AND I.BillOver=0 AND I.ORDERSTATE<>1 and O.BillOver=0 AND I.ifaudit=1'
			
IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL --AND @costprice <> ''
	BEGIN
		SET @SQL = @SQL + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END
	IF @isSelectedGoodsNo='1'
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	ELSE
	BEGIN
		IF @producedate IS NOT NULL AND @producedate <> ''
		BEGIN
			SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		END
		IF @validdate IS NOT NULL AND @validdate <> ''
		BEGIN
			SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
		END
	END
END
IF(@goodsnumber <> '')
BEGIN
	SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
END
IF @itemid <> '' AND @itemid <> '0'
BEGIN
	SET @SQL = @SQL + ' AND o.itemid='''+@itemid+''''
END
EXEC (@SQL)

--组合品销售订单
SELECT @SQL ='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)	
			SELECT '''+@TypeId+''' AS typeid,0 AS RQty,0 AS CQty,0 AS qty,0 AS LendQty,0 AS BorrowQty,
			CASE WHEN ISNULL(SUM(O.QTY),0) - ISNULL(SUM(O.ReachQty),0) >=0 THEN ISNULL(SUM(O.QTY),0) ELSE 0 END AS SaleOrderQty,
			0 AS BuyOrderQty,
			CASE WHEN ISNULL(SUM(O.QTY),0) - ISNULL(SUM(O.ReachQty),0) >=0 THEN ISNULL(SUM(O.ReachQty),0) ELSE 0 END AS SaleReachQty,
			0 AS BuyReachQty
			FROM PT_Combin_OrderBillDetail O INNER JOIN orderindex I ON O.billnumberid=i.billnumberid 
			INNER JOIN ptype p1  on o.ptypeid=p1.typeid '+ @temptable+' 
			WHERE O.ktypeid='''+@szKtypeId+''' AND O.Ptypeid='''+@TypeId+''' AND I.BillType=313
			AND I.BillOver=0 AND I.ORDERSTATE<>1 and O.BillOver=0 AND I.ifaudit=1'
			
IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL --AND @costprice <> ''
	BEGIN
		SET @SQL = @SQL + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END
	IF @isSelectedGoodsNo='1'
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	ELSE
	BEGIN
		IF @producedate IS NOT NULL AND @producedate <> ''
		BEGIN
			SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
		END
		IF @validdate IS NOT NULL AND @validdate <> ''
		BEGIN
			SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
		END
	END
END
IF(@goodsnumber <> '')
BEGIN
	SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
END
IF @itemid <> '' AND @itemid <> '0'
BEGIN
	SET @SQL = @SQL + ' AND o.itemid='''+@itemid+''''
END
EXEC (@SQL)
-----------------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb.dbo.#resultTable') IS NOT NULL
	BEGIN
		DROP TABLE #resultTable
	END
	CREATE TABLE #resultTable
	(
		typeid varchar(200),
		fullname varchar(2000),
		usercode varchar(200),
		Sonnum  NUMERIC(24, 10) ,
		parid varchar(200),
		qty  NUMERIC(24, 10) ,
		Lendqty  NUMERIC(24, 10) ,
		Borrowqty  NUMERIC(24, 10) ,
		FactQty  NUMERIC(24, 10) ,
		RQty  NUMERIC(24, 10) ,
		CQty  NUMERIC(24, 10) ,
		KFHQty  NUMERIC(24, 10) ,
		BuyOrderQty  NUMERIC(24, 10) ,
		SaleOrderQty  NUMERIC(24, 10) ,
		SaleCanQty  NUMERIC(24, 10) ,
		unitname varchar(100),
		baseunitname varchar(100),
		unitrate numeric(18,0),
		BuyReachQty  NUMERIC(24, 10) ,
		SaleReachQty  NUMERIC(24, 10) 
	)

SELECT @SQL='INSERT INTO #resultTable
				SELECT	a.typeid,
				a.fullname,
				a.usercode,
				a.Sonnum,
				a.parid,
				ISNULL(SUM(o.qty),0) AS qty,
				ISNULL(SUM(o.Lendqty),0) AS Lendqty,
				ISNULL(SUM(o.borrowqty),0) AS Borrowqty,
				ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.borrowqty),0)-ISNULL(SUM(o.lendqty),0) AS FactQty,
				ISNULL(SUM(o.rqty),0) AS RQty,
				ISNULL(SUM(o.cqty),0) AS CQty,
				ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.rqty),0)-ISNULL(SUM(o.cqty),0) AS KFHQty,
				ISNULL(SUM(o.BuyOrderQty),0) -ISNULL(SUM(o.BuyReachQty),0)  BuyOrderQty,
				ISNULL(SUM(o.SaleOrderQty),0) - ISNULL(SUM(o.SaleReachQty),0) SaleOrderQty,
				CASE 
					WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0) 
					THEN  ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
					WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  
					THEN ISNULL(SUM(o.qty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
					WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0)  
					THEN ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
					WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  
					THEN ISNULL(SUM(o.qty),0)
				END AS SaleCanQty,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.unitname END AS unitname,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.baseunitname END AS baseunitname,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.unitrate END AS unitrate,
				ISNULL(SUM(o.BuyReachQty),0) AS BuyReachQty,
				ISNULL(SUM(o.SaleReachQty),0) AS SaleReachQty
		FROM #GetManPTypeAll a 
		LEFT JOIN #LeftJoinTable o ON LEFT(o.typeid,LEN(a.typeid))=a.typeid 
		GROUP BY	a.typeid,
					a.fullname,
					a.usercode,
					a.Sonnum,
					a.parid,
					a.unit1,
					a.unitrate1,
					a.unit2,	
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.unitname END,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE	 a.baseunitname END,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.unitrate END '
	EXEC(@SQL)
	SELECT @SQL = 'SELECT ISNULL('+@virtualqtysql+',0) AS VirtualQty FROM #resultTable a
				   LEFT JOIN 
				   (
						SELECT ptypeId, abs(sum(saleqty)) AS saleqty 
						FROM #resultlefttable GROUP BY ptypeid
					) o 
					ON LEFT(o.ptypeid,LEN(a.typeid))=a.typeid
				   INNER JOIN Ptype p ON p.typeid=a.typeid WHERE p.isservice=0'
	EXEC (@SQL)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/************************************************************
 * 创 建 人：ZY
 * 创建时间: 2017-07-19
 * 内容描述：根据维度获取明细行商品的虚拟库存
 ************************************************************/
IF EXISTS (SELECT * FROM sysobjects s WHERE s.id=OBJECT_ID('[dbo].[Gp_GetVirtualStockByConfig]') and OBJECTPROPERTY(id, N'IsProcedure')= 1)
BEGIN
	DROP PROC Gp_GetVirtualStockByConfig
END
GO
CREATE PROC Gp_GetVirtualStockByConfig(
	@TypeId			VARCHAR(MAX),					--商品ID
	@OperatorId		VARCHAR(100),					--操作员ID
	@szKtypeId		VARCHAR(100),					--仓库ID
	@StypeId		VARCHAR(100),					--分支机构
	@costing		varchar(10)='',					--账套类型，手工指定账套
	@costprice		 NUMERIC(24, 10) =NULL,				--批次成本价
	@goodsnumber	varchar(200)='',				--批号
	@producedate	varchar(30)='',					--生产日期
	@validdate		varchar(30)='',					--效期至
	@itemid			INT=-1,							--自由项
	@cargoid		INT=0,							--货位
	@isSelectedGoodsNo varchar(3) = '0',			--是否选择批次
	@orderid        INT=-1							--订单号
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	DECLARE @ParId VARCHAR(100) = '00000'	--商品父ID
	DECLARE @VirtualQtySql VARCHAR(MAX)		--虚拟库存计算公式SQL

	IF @TypeId IS NOT NULL
	BEGIN
		SELECT @ParId = ParId FROM ptype WHERE typeid=@TypeId
	END
	--获取虚拟库存计算公式
	SELECT @VirtualQtySql = u.[Value]
		FROM   Userconfig u
		WHERE  u.ConfigName = 'VirtualQtySQL'
	IF @VirtualQtySql IS NULL OR @VirtualQtySql = ''
	BEGIN
		--默认公式：
		--	虚拟库存=账面库存+已采购订货数量-已销售订货数量+草稿入库-草稿出库
		SET @VirtualQtySql = 'isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)'
	END
	
	--虚拟库存维度配置
	DECLARE @VirtualInventoryJudgment VARCHAR(1)='1'
	SELECT @VirtualInventoryJudgment=[Value] FROM Userconfig where ConfigName='VirtualInventoryJudgment'
	
	--特殊处理未选批次的商品
	--IF @costprice IS NULL AND @isSelectedGoodsNo <> '1'
	--BEGIN
	--	SET @producedate = NULL;
	--	SET @validdate = NULL;
	--END
	--ELSE
	--BEGIN
	--	SET @isSelectedGoodsNo='1';
	--END
	IF @producedate IS NOT NULL AND @producedate <> ''
	BEGIN
		SET @producedate=CONVERT(varchar(10),@producedate,23)
	END
	IF @validdate IS NOT NULL AND @validdate <> ''
	BEGIN
		SET @validdate=CONVERT(varchar(10),@validdate,23)
	END
print @validdate
	--------多单位计算[按基本单位计算]Start--------
	DECLARE @Qty    NVARCHAR(2000),
			@Lendqty NVARCHAR(2000),
			@Borrowqty NVARCHAR(2000),
			@RQty NVARCHAR(2000),
			@CQty NVARCHAR(2000),
			@BuyOrderQty NVARCHAR(2000),
			@BuyReachQty NVARCHAR(2000),
			@SaleOrderQty NVARCHAR(2000),
			@SaleReachQty NVARCHAR(2000),
			@temptable  NVARCHAR(2000)

	SELECT  @Qty='o.Qty',
			@Lendqty='SUM(o.Lend-o.LendBack-o.saleqty)',
			@Borrowqty='SUM(o.Borrow-o.BorrowBack-o.buyqty)',   
			@BuyReachQty='o.BuyReachQty', 
			@RQty='o.RQty',        
			@CQty='o.CQty',        
			@BuyOrderQty='o.BuyOrderQty', 
			@BuyReachQty='o.BuyReachQty', 
			@SaleOrderQty='o.SaleOrderQty',
			@SaleReachQty='o.SaleReachQty',
			@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1','1')
	--------多单位计算End---------

	IF OBJECT_ID('tempdb.dbo.#GetManPTypeAll') IS NOT NULL
	BEGIN
		DROP TABLE #GetManPTypeAll
	END
	--商品基本信息
	CREATE TABLE #GetManPTypeAll
	(
		TypeId			varchar(100),
		FullName        varchar(200),
		UserCode        varchar(100),
		Sonnum			 NUMERIC(24, 10) ,
		Parid           varchar(200),
		unit1           varchar(100),
		unit2           varchar(100),
		unitrate1       varchar(100),
		unitname       NVARCHAR(2000),
		baseunitname    NVARCHAR(2000),
		unitrate        NVARCHAR(2000)
	)
	CREATE UNIQUE CLUSTERED INDEX [PtypeAllidx] ON [dbo].[#GetManPTypeAll] 
	(
		[typeId]
	)

	SET @SQL='INSERT INTO #GetManPTypeAll SELECT P.TypeId,P.FullName,P.UserCode,P.Sonnum,P.Parid,P.unit1,P.unit2,P.unitrate1,'
	SET @SQL+='u1.fullname,u1.fullname,1'
	SET @SQL+='  FROM F_GetManPTypeAll('''+@OperatorID+''') P inner join ptype p1 on p.typeid=p1.typeid '+@temptable
	SET @SQL+=' WHERE P.Parid='''+@Parid+''' AND p1.TypeId='''+@TypeId+''''
	EXEC(@SQL)
	--处理商品父编码
	DECLARE @MMPtypeid VARCHAR(100)
	SET @MMPtypeid=''
	IF LEFT(@parid,len(@MMPtypeid))<>@MMPtypeid 
	BEGIN
		SET @parid=LEFT(@MMPtypeid,len(@MMPtypeid)-5)
	END
	IF @Parid='' 
	BEGIN
		SET @Parid='00000'
	END

	-- 全部仓库
	IF @szKtypeId='' OR @szKtypeId='00000'
	BEGIN
		SELECT @szKtypeId='%'	
	END
	

SET @SQL = ''
-------------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb.dbo.#DGS') IS NOT NULL
BEGIN
	DROP TABLE #DGS
END
CREATE TABLE #DGS
(
	PTypeId		varchar(100),
	RQty		 NUMERIC(24, 10) ,
	CQty		 NUMERIC(24, 10) 
)
IF OBJECT_ID('tempdb.dbo.#InOutStockDraft') IS NOT NULL
BEGIN
	DROP TABLE #InOutStockDraft
END
CREATE TABLE #InOutStockDraft
(
	PTypeId varchar(100),
	RQty	 NUMERIC(24, 10) ,
	CQty	 NUMERIC(24, 10) 
)
DECLARE @SQL_WHERE VARCHAR(MAX)=''

IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END	
END
IF @VirtualInventoryJudgment='2'
BEGIN
	IF @producedate IS NOT NULL 
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND produceDate='''+@producedate+''''
	END
	IF @validdate IS NOT NULL 
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + '  AND validdate='''+@validdate+''''
	END
	IF @goodsnumber IS NOT NULL AND @goodsnumber<>''
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND goodsnumber='''+@goodsnumber+''''
	END
	if @itemid IS NOT NULL AND @itemid<>-1
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE +' AND itemid='+cast(@itemid AS varchar(10))+''
	END
	IF @cargoid IS NOT NULL AND @cargoid<>0
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE +' AND CargoID='+cast(@cargoid AS varchar(10))+''
	END
END

--插入商品入库库存和出库库存(草稿)
	SET @SQL = 'INSERT INTO #DGS(PTypeId,RQty,CQty)
	SELECT PTypeId,ISNULL(SUM(RQty),0) AS RQty,ISNULL(SUM(CQty),0) AS CQty
	FROM GoodsStocks_Draft B WHERE KTypeID='''+@szKtypeId+''' AND PTypeId='''+@TypeId+''''+@SQL_WHERE+' GROUP BY PTypeId'
EXEC(@SQL)

-------------------------------------------------------------------------------------------------------------------------------------------------
--需要加上本草稿的库存和订单
IF OBJECT_ID('tempdb.dbo.#DRAFT') IS NOT NULL
BEGIN
	DROP TABLE #DRAFT
END
CREATE TABLE #DRAFT
(
	PTypeId		varchar(100),
	DraftQty		 NUMERIC(24, 10)
)
--IF (@orderid <> -1)
--BEGIN
--	DECLARE @billnumberid VARCHAR(100),@billtype int;
--	SELECT @billnumberid=C.BillNumberId,@billtype=C.BillType FROM OrderBill A
--	LEFT JOIN SaleBill B ON A.OrderID=B.OrderID
--	LEFT JOIN BillIndex C ON B.BillNumberId=C.BillNumberId
--	WHERE C.draft=1 AND C.ifcheck='f' AND A.OrderID=@orderid
	
--	DECLARE @TEMPSQL VARCHAR(8000),@TableName VARCHAR(50)
--	IF (@billnumberid IS NOT NULL AND @billtype IS NOT NULL AND @billtype NOT IN (300,87,313,160))
--	BEGIN
--		SELECT @TableName=DBO.F_BillTableName(@billtype)
		
--		SET @TEMPSQL='
--		INSERT INTO #DRAFT
--		SELECT	b.ptypeid,
--				SUM(ISNULL(b.Qty,0)) AS DraftQty
--		FROM 	BillIndex a 
--		INNER JOIN '+@TableName+' b ON a.BillNumberId = b.BillNumberId
--		WHERE a.BillNumberId = '+@billnumberid+' AND a.draft = 1 AND b.DraftFlag = 1 '+@SQL_WHERE+'
--		GROUP BY b.ptypeid'	

--		EXEC (@TEMPSQL)	
--	END
--	IF (@billtype = 313)
--	BEGIN
--		SET @tableName='PT_Combin_OrderBillDetail'
--	END
--	ELSE
--	BEGIN
--		SET @tableName='OrderBill'
--	END
--	SET @TEMPSQL='
--	insert into #DRAFT(ptypeid,DraftQty)
--	select ptypeid,SUM(isnull(qty,0))
--	from '+@tableName+' where OrderID='+convert(varchar,@orderid)+''+@SQL_WHERE+' GROUP BY ptypeid'
--	EXEC(@TEMPSQL)
--END

---------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb.dbo.#ResultLeftTable') IS NOT NULL
	BEGIN
		DROP TABLE #ResultLeftTable
	END
	CREATE TABLE #ResultLeftTable
	(
		pTypeId			 VARCHAR(50),
		saleQty			  NUMERIC(24, 10) 
	)

	SELECT  @SQL='INSERT INTO #ResultLeftTable (pTypeId,saleqty)
		SELECT g.typeId,0 FROM inoutstocktable S  
		INNER join #GetManPTypeAll  g on  S.ptypeid like g.typeid +''%''  
		WHERE S.KTypeId = '''+@szKtypeId+''''+@SQL_WHERE+''
	EXEC (@SQL)
-----------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb.dbo.#LeftJoinTable') IS NOT NULL
	BEGIN
		DROP TABLE #LeftJoinTable
	END
	CREATE TABLE #LeftJoinTable
	(
		TypeId			 VARCHAR(50),
		RQty			 NUMERIC(24, 10) ,
		CQty			 NUMERIC(24, 10) ,
		Qty				 NUMERIC(24, 10) ,
		Lendqty			 NUMERIC(24, 10) ,
		Borrowqty		 NUMERIC(24, 10) ,
		SaleOrderQty	 NUMERIC(24, 10) ,
		BuyOrderQty		 NUMERIC(24, 10) ,
		SaleReachQty	 NUMERIC(24, 10) ,
		BuyReachQty		 NUMERIC(24, 10) 
	)
--草稿库存
SELECT @SQL='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)
	SELECT o.PTypeId AS TypeId,'+@RQty+','+@CQty+',0 AS Qty,0 AS Lendqty,0 AS Borrowqty,0 AS SaleOrderQty,0 AS BuyOrderQty,0 AS SaleReachQty,0 AS BuyReachQty
	FROM #DGS o INNER JOIN ptype p1 on o.ptypeid=p1.typeid '+ @temptable	
EXEC (@SQL) 

SET @SQL_WHERE=''
IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END	
END
IF @VirtualInventoryJudgment='2'
BEGIN
	IF @producedate IS NOT NULL 
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND o.produceDate='''+@producedate+''''
	END
	IF @validdate IS NOT NULL 
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + '  AND o.validdate='''+@validdate+''''
	END
	IF @goodsnumber IS NOT NULL AND @goodsnumber<>''
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND o.goodsnumber='''+@goodsnumber+''''
	END
	IF @itemid IS NOT NULL AND @itemid<>-1
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND o.itemid='+cast(@itemid AS varchar(10))+''
	END
	IF @cargoid IS NOT NULL  AND @cargoid<>0
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE +' AND o.CargoID='+cast(@cargoid AS varchar(10))+''
	END
END
SET @SQL_WHERE = @SQL_WHERE + ' GROUP BY p1.typeid '
--账面库存
SELECT @SQL ='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)		
SELECT 	p1.typeid,0 AS RQty,0 AS CQty,SUM('+@qty+') AS qty,0 AS Lendqty,0 AS Borrowqty,0 AS SaleOrderQty,0 AS BuyOrderQty,0 AS SaleReachQty,0 AS BuyReachQty
FROM GOODSSTOCKS_QTY o INNER JOIN ptype p1 on o.ptypeid=p1.typeid '+ @temptable+' WHERE o.KTypeId='''+@szKtypeId+''''
SELECT @SQL = @SQL +' AND o.ptypeid='''+@TypeId+''''+@SQL_WHERE+''
EXEC (@SQL)	

-------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT @SQL ='		
	INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)					
	SELECT 	'''+@TypeId+''' AS typeid,0 AS RQty,0 AS CQty,0 AS qty,'+@Lendqty+' AS Lendqty,'+@Borrowqty+' AS  Borrowqty,
			0 AS SaleOrderQty,0 AS BuyOrderQty,0 AS SaleReachQty,0 AS BuyReachQty FROM 	V_LendStatus o 
		   INNER JOIN ptype p1  on o.ptypeid=p1.typeid ' + @temptable+'
		   WHERE o.ktypeid='''+@szKtypeId+'''  AND o.ptypeid = '''+@TypeId+''''
IF @VirtualInventoryJudgment='2'
BEGIN		   
	IF @producedate IS NOT NULL 
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
	END
	IF @validdate IS NOT NULL 
	BEGIN
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	IF @goodsnumber IS NOT NULL AND @goodsnumber<>''
	BEGIN
		SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
	END
	IF @itemid IS NOT NULL AND @itemid<>-1
	BEGIN
		SET @SQL = @SQL + ' AND o.itemid='+cast(@itemid AS varchar(10))+''
	END
END
EXEC (@SQL)	
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
--采购订单
SELECT @SQL ='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)	
			SELECT '''+@TypeId+''' AS typeid,0 AS RQty,0 AS CQty,0 AS qty,0 AS LendQty,0 AS BorrowQty,0 AS SaleOrderQty,
			CASE WHEN SUM(ISNULL(O.BuyOrderQty,0)-ISNULL(O.LimitBuyQty,0))>=0 
			THEN SUM(ISNULL(O.BuyOrderQty,0)-ISNULL(O.LimitBuyQty,0)) ELSE 0 END AS BuyOrderQty,
			0 AS SaleReachQty,
			CASE WHEN SUM(ISNULL(O.BuyReachQty,0)) >=0 THEN SUM(ISNULL(O.BuyReachQty,0)) ELSE 0 END AS BuyReachQty
			FROM GoodsStocks_order O 
			INNer join ptype p1  on o.ptypeid=p1.typeid '+ @temptable+' 
			WHERE O.ktypeid='''+@szKtypeId+''' AND O.Ptypeid='''+@TypeId+''''
			
IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL
	BEGIN
		SET @SQL = @SQL + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END	
END
IF @VirtualInventoryJudgment='2'
BEGIN
	IF @producedate IS NOT NULL 
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
	END
	IF @validdate IS NOT NULL 
	BEGIN
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	IF @goodsnumber IS NOT NULL AND @goodsnumber<>''
	BEGIN
		SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
	END
	IF @itemid IS NOT NULL  AND @itemid<>-1
	BEGIN
		SET @SQL = @SQL + ' AND o.itemid='+cast(@itemid AS varchar(10))+''
	END
	IF @cargoid IS NOT NULL AND @cargoid<>0
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE +' AND o.CargoID='+cast(@cargoid AS varchar(10))+''
	END
END
EXEC (@SQL)

--销售/组合品订单
SELECT @SQL ='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)	
			SELECT '''+@TypeId+''' AS typeid,0 AS RQty,0 AS CQty,0 AS qty,0 AS LendQty,0 AS BorrowQty,
			CASE WHEN SUM(ISNULL(O.SaleOrderQty,0)-ISNULL(O.LimitSaleQty,0)) >=0 
			THEN SUM(ISNULL(O.SaleOrderQty,0)-ISNULL(O.LimitSaleQty,0)) ELSE 0 END AS SaleOrderQty,
			0 AS BuyOrderQty,
			CASE WHEN SUM(ISNULL(O.SaleReachQty,0)) >=0 THEN SUM(ISNULL(O.SaleReachQty,0)) ELSE 0 END AS SaleReachQty,
			0 AS BuyReachQty
			FROM GoodsStocks_order O 
			INNER JOIN ptype p1  on o.ptypeid=p1.typeid '+ @temptable+' 
			WHERE O.ktypeid='''+@szKtypeId+''' AND O.Ptypeid='''+@TypeId+''''
			
IF(@costing = '3')
BEGIN
	IF @costprice IS NOT NULL 
	BEGIN
		SET @SQL = @SQL + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
	END
END
IF @VirtualInventoryJudgment='2'
BEGIN
	IF @producedate IS NOT NULL 
	BEGIN
		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
	END
	IF @validdate IS NOT NULL 
	BEGIN
		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
	END
	IF @goodsnumber IS NOT NULL AND @goodsnumber<>''
	BEGIN
		SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
	END
	IF @itemid IS NOT NULL  AND @itemid<>-1
	BEGIN
		SET @SQL = @SQL + ' AND o.itemid='+cast(@itemid AS varchar(10))+''
	END
	IF @cargoid IS NOT NULL AND @cargoid<>0
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE +' AND o.CargoID='+cast(@cargoid AS varchar(10))+''
	END
END
EXEC (@SQL)

--组合品销售订单
--SELECT @SQL ='INSERT INTO #LeftJoinTable (TypeId,RQty,CQty,Qty,Lendqty,Borrowqty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty)	
--			SELECT '''+@TypeId+''' AS typeid,0 AS RQty,0 AS CQty,0 AS qty,0 AS LendQty,0 AS BorrowQty,
--			CASE WHEN ISNULL(SUM(O.QTY),0) - ISNULL(SUM(O.ReachQty),0) >=0 THEN ISNULL(SUM(O.QTY),0) ELSE 0 END AS SaleOrderQty,
--			0 AS BuyOrderQty,
--			CASE WHEN ISNULL(SUM(O.QTY),0) - ISNULL(SUM(O.ReachQty),0) >=0 THEN ISNULL(SUM(O.ReachQty),0) ELSE 0 END AS SaleReachQty,
--			0 AS BuyReachQty
--			FROM PT_Combin_OrderBillDetail O INNER JOIN orderindex I ON O.billnumberid=i.billnumberid 
--			INNER JOIN ptype p1  on o.ptypeid=p1.typeid '+ @temptable+' 
--			WHERE O.ktypeid='''+@szKtypeId+''' AND O.Ptypeid='''+@TypeId+''' AND I.BillType=313
--			AND I.BillOver=0 AND I.ORDERSTATE<>1 and O.BillOver=0 AND I.ifaudit=1'
			
--IF(@costing = '3')
--BEGIN
--	IF @costprice IS NOT NULL 
--	BEGIN
--		SET @SQL = @SQL + ' AND o.goodscostprice='+CAST(@costprice AS VARCHAR)+''
--	END
--END
--IF @VirtualInventoryJudgment='2'
--BEGIN
--	IF @producedate IS NOT NULL
--	BEGIN
--		SET @SQL = @SQL + ' AND o.produceDate='''+@producedate+''''
--	END
--	IF @validdate IS NOT NULL 
--	BEGIN
--		SET @SQL = @SQL + '  AND o.validdate='''+@validdate+''''
--	END
--	IF @goodsnumber IS NOT NULL 
--	BEGIN
--		SET @SQL = @SQL + ' AND o.goodsnumber='''+@goodsnumber+''''
--	END
--	IF @itemid IS NOT NULL 
--	BEGIN
--		SET @SQL = @SQL + ' AND o.itemid='+cast(@itemid AS varchar(10))+''
--	END
--	IF @cargoid IS NOT NULL 
--	BEGIN
--		SET @SQL_WHERE = @SQL_WHERE +' AND o.CargoID='+cast(@cargoid AS varchar(10))+''
--	END
--END
--EXEC (@SQL)
-----------------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb.dbo.#resultTable') IS NOT NULL
	BEGIN
		DROP TABLE #resultTable
	END
	CREATE TABLE #resultTable
	(
		typeid varchar(200),
		fullname varchar(2000),
		usercode varchar(200),
		Sonnum  NUMERIC(24, 10) ,
		parid varchar(200),
		qty  NUMERIC(24, 10) ,
		Lendqty  NUMERIC(24, 10) ,
		Borrowqty  NUMERIC(24, 10) ,
		FactQty  NUMERIC(24, 10) ,
		RQty  NUMERIC(24, 10) ,
		CQty  NUMERIC(24, 10) ,
		KFHQty  NUMERIC(24, 10) ,
		BuyOrderQty  NUMERIC(24, 10) ,
		SaleOrderQty  NUMERIC(24, 10) ,
		SaleCanQty  NUMERIC(24, 10) ,
		unitname varchar(100),
		baseunitname varchar(100),
		unitrate numeric(18,0),
		BuyReachQty  NUMERIC(24, 10) ,
		SaleReachQty  NUMERIC(24, 10) 
	)

SELECT @SQL='INSERT INTO #resultTable
				SELECT	a.typeid,
				a.fullname,
				a.usercode,
				a.Sonnum,
				a.parid,
				ISNULL(SUM(o.qty),0) AS qty,
				ISNULL(SUM(o.Lendqty),0) AS Lendqty,
				ISNULL(SUM(o.borrowqty),0) AS Borrowqty,
				ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.borrowqty),0)-ISNULL(SUM(o.lendqty),0) AS FactQty,
				ISNULL(SUM(o.rqty),0) AS RQty,
				ISNULL(SUM(o.cqty),0) AS CQty,
				ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.rqty),0)-ISNULL(SUM(o.cqty),0) AS KFHQty,
				ISNULL(SUM(o.BuyOrderQty),0) BuyOrderQty,
				ISNULL(SUM(o.SaleOrderQty),0) SaleOrderQty,
				ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.SaleOrderQty),0) AS SaleCanQty,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.unitname END AS unitname,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.baseunitname END AS baseunitname,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.unitrate END AS unitrate,
				ISNULL(SUM(o.BuyReachQty),0) AS BuyReachQty,
				ISNULL(SUM(o.SaleReachQty),0) AS SaleReachQty
		FROM #GetManPTypeAll a 
		LEFT JOIN #LeftJoinTable o ON LEFT(o.typeid,LEN(a.typeid))=a.typeid 
		GROUP BY	a.typeid,
					a.fullname,
					a.usercode,
					a.Sonnum,
					a.parid,
					a.unit1,
					a.unitrate1,
					a.unit2,	
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.unitname END,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE	 a.baseunitname END,
				CASE WHEN a.Sonnum>0 THEN NULL ELSE a.unitrate END '
	EXEC(@SQL)
	--+ISNULL(DraftQty,0)
	SELECT @SQL = 'SELECT ISNULL('+@virtualqtysql+',0) AS VirtualQty FROM #resultTable a
				   LEFT JOIN 
				   (
						SELECT ptypeId, abs(sum(saleqty)) AS saleqty 
						FROM #resultlefttable GROUP BY ptypeid
					) o 
					ON LEFT(o.ptypeid,LEN(a.typeid))=a.typeid
					--LEFT JOIN
					--(
					--	SELECT ptypeid,sum(isnull(DraftQty,0)) as DraftQty
					--	FROM #Draft GROUP BY PTYPEID
					--)D 
					--ON D.ptypeid=a.typeid
				   INNER JOIN Ptype p ON p.typeid=a.typeid WHERE p.isservice=0'
	EXEC (@SQL)

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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








-- 回访单据编号 
-- cqhua 2009-11-13
-- HF-T-20091113-0001
---------------------------------------------------------------
CREATE                            PROCEDURE Gp_GetVisitBillCode
(
	@YEAR varchar(50),
	@MONTH VARCHAR(50), 	--自动产生编号时为月份，自定义编号时是经手人名字
	@DAY VARCHAR(50),		--自动产生编号时为日期，自定义编号时为仓库名
	@BillFlag VARCHAR(3)='HF',
	@BCode VARCHAR(200) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

     -- chen_qihua 单据编号自定义改为 200 长度 -- #&**&#	
	 -- DECLARE @BCFirstChar VARCHAR(50),@bMon bit,@bDay bit,@billcode VARCHAR(25),@temp VARCHAR(4),@t INT,@AutoBillCode VARCHAR(50)
	 DECLARE @BCFirstChar VARCHAR(50),@bMon bit,@bDay bit,@billcode VARCHAR(200),@temp VARCHAR(4),@t INT,@AutoBillCode VARCHAR(200)
	 SELECT @BCFirstChar=Value FROM Userconfig WHERE ConfigName='Billcodeindex'


	 DECLARE @tYear VarChar(4), @tMonth VARCHAR(2),@tday VARCHAR(2)
	 Set @tYear = @YEAR--Year(GetDate())
	 IF len(@tYear) <> 4 
		Set @tYear = '20' + @tYear
	
	 SELECT @tmonth=RIGHT(CAST(@MONTH+100 AS VARCHAR(10)),2)
	 SELECT @tday=RIGHT(CAST(@DAY+100 AS VARCHAR(10)),2)
	
	 SELECT @BCode=''
      SELECT @billcode=Max(Reverse(Left((Reverse(rtrim(BillCode))),(CharIndex('-',Reverse(rtrim(BillCode)))-1))))
      FROM Visit 
      WHERE  LEFT(RIGHT(BillCode,13),4)=@tYear And LEFT(RIGHT(BillCode,9),2)=@tMonth AND LEFT(RIGHT(BillCode,7),2)=@tDay  And (CharIndex('-',BillCode)>0)
      AND ISNUMERIC(Reverse(Left((Reverse(rtrim(BillCode))),(CharIndex('-',Reverse(rtrim(BillCode)))-1)))) = 1 AND LEN(BillCode) >= 17

	
	declare @oldlen int
	
	IF @billcode IS NULL OR ISNUMERIC(@billcode) = 0
	Begin
	   Select @billcode='0001'
	End
	Else
	Begin
	   --有局限，每日单据不能上万
	   Select @billcode=Right(Cast((Cast(@billcode as numeric(18,0))+10001) As varchar(50)),4)
	End

	--#01以上---------------------------------------------------------------------
	 SELECT @billcode=@tYear + @tmonth + @tday+'-'+@billcode

	 SELECT @BCode=@BillFlag+'-'+ISNULL(@BCFirstChar,'')+'-'+@billcode











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_GetVoucherIsEdit]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_GetVoucherIsEdit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--==========================================
--created by glj
--date 2015-01-26
--function description 修改凭证时判断是否满足条件 
--==========================================
CREATE PROCEDURE Gp_GetVoucherIsEdit
(
	@BillNumberID	INT,			--凭证ID
	@StypeId		VARCHAR(50),	--分支机构
	@Operatorid		VARCHAR(50)		--操作员
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @IsEdit	INT
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill B WHERE B.BillNumberId=@BillNumberID AND ISNULL(B.ATypeId,'')<>'' AND B.STypeId=@StypeId AND B.ATypeId NOT IN(SELECT Typeid FROM F_LineAccount(@Operatorid,@StypeId)) )
	SET  @IsEdit=1
ELSE 
	SET @IsEdit=0

SELECT TOP 1 
    ISNULL(fchecked,'') fchecked,
    ISNULL(recheckid,'') recheckid,
    ISNULL(ifcheck,'') ifcheck,
    ISNULL(etypeid,'') etypeid,
    ISNULL(vouchertype,'') vouchertype,
    ISNULL((SELECT SubValue FROM sysdata WHERE SubName='aceditsysvoucher'),'') aceditsysvoucher,
    ISNULL((SELECT SubValue FROM sysdata WHERE SubName='aceditothervoucher'),'') aceditothervoucher,
    ISNULL(fperiod,'') fperiod,
    @IsEdit	'IsEdit'
FROM Ac_Voucher 
WHERE BillNumberID=@BillNumberID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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











/*
作者：cqhua
日期：2009-11-16
描述：维修品库存期初
*/
CREATE        PROCEDURE Gp_GetWxDbf 
(	
@szPtypeId varchar(50),		--商品的ID
@szKtypeId varchar(50),		--仓库的ID
@dqty    NUMERIC(24, 10)  output
)
--@encode$--
AS
set nocount on
DECLARE @szSql varchar(500)

IF @szktypeid<>'0'	--具体的仓库
BEGIN
	SELECT 	@dqty = SUM(qty)
	FROM 	wx_inigoodsstocks 
	WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid
			AND KTypeId=@szKTypeId
	
	IF 	@dqty IS null SELECT @dqty=0
	RETURN
END 
ELSE			--全部仓库
BEGIN
	SELECT 	@dqty = SUM(qty)
	FROM 	wx_inigoodsstocks 
	WHERE 	LEFT(ptypeid,LEN(@szptypeid))=@szptypeid										

	IF 	@dqty IS null SELECT @dqty=0
	RETURN
END














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2009-04-13
	描述：计算此前的库存数量和金额
*/
CREATE PROCEDURE Gp_GetWxPreDateQtyOrTotal
(
	@OperatorID	varchar(200),
	@StartDate	varchar(20),
	@PTypeId	varchar(200),
	@KTypeId	varchar(8000),
	@etypeid	VARCHAR(8000)='',
	@stypeid	VARCHAR(8000)=''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------


CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailKType(@OperatorID)) AND TypeId IN (SELECT * FROM F_GetAllBaseTypeId(@KTypeId,4))

--分支机构
CREATE TABLE #GetManSTypeid(TYpeid VARCHAR(100))
INSERT INTO #GetManSTypeid(TYpeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)



IF @PTypeId = '00000'
	SET @PTypeId = '%'

DECLARE @TypeId 	varchar(100)

CREATE TABLE #Result
(
	TypeId		varchar(100)
)

IF @KTypeID = ''
	INSERT INTO #Result(TypeId) SELECT TypeId FROM Stock WHERE SonNum = 0 AND TypeId IN (SELECT TypeId FROM #GetManKTypeId)
ELSE
	INSERT INTO #Result(TypeId) SELECT TypeId FROM #GetManKTypeId

--计算数据
SELECT 	ISNULL(SUM(B.Qty),0) AS Qty, 
		ISNULL(SUM(B.Total),0) AS Total 
FROM	( 
			SELECT 	ISNULL(SUM(a.Qty),0) AS Qty,
					ISNULL(SUM(a.CostTotal),0) AS Total 
			FROM 	Wx_InOutStockTable a Inner Join BillIndex b On a.BillNumberId=b.BillNumberId And b.RedWord=0 
					INNER JOIN #GetManSTypeid ss ON b.Stypeid=ss.TYpeid
			WHERE 	a.BillDate<@StartDate
					AND a.KTypeID<>'10000' 
					AND (a.KTypeID IN (SELECT TypeId FROM #Result)) 
					AND a.PTypeID LIKE @PTypeId+'%'
			UNION ALL 
			SELECT 	ISNULL(SUM(a.Qty),0) AS Qty,
					ISNULL(SUM(a.Total),0) AS Total 
			FROM 	Wx_IniGoodsStocks a 
					INNER JOIN #Result k ON a.KTypeId=k.TypeId
					INNER JOIN (SELECT typeid FROM stock WHERE STypeID IN(SELECT typeId FROM  #GetManSTypeid)) ss ON ss.TYpeid=k.TypeId
			WHERE 	PTypeID LIKE @PTypeId+'%' 
					AND a.KTypeID<>'10000' 
					AND a.KTypeID LIKE '%' 
) B

DROP TABLE #Result,#GetManKTypeId,#GetManSTypeid









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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














/****** Object:  Stored Procedure dbo.Gp_GetZt    Script Date: 2002-6-20 10:14:48 ******/

CREATE  PROCEDURE Gp_GetZt
--@encode$--
AS
set nocount on
select * from ztdb















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE   PROCEDURE Gp_GoodsInItTemp
(
	@pusercode	varchar(200),
	@pfullname 	varchar(200),
    @kusercode	varchar(200),
	@kfullname 	varchar(200),
	@Qty		 NUMERIC(24, 10) ,
	@Price		 NUMERIC(24, 10) ,
	@Total		 NUMERIC(24, 10) ,
    @OperatorID varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON

     DECLARE @ptypeid varchar(100),@ktypeid varchar(100)
     SELECT @ptypeid=typeid FROM ptype where usercode=@pusercode AND sonnum=0 AND deleted=0
     SELECT @ktypeid=typeid FROM stock where usercode=@kusercode AND sonnum=0 AND deleted=0
     
     IF NOT EXISTS (SELECT * FROM iniGoodsStocks WHERE ptypeid=ISNULL(@ptypeid,'') AND ktypeid=ISNULL(@ktypeid,''))
     BEGIN
          INSERT INTO iniGoodsStocks(ptypeid,ktypeid,Qty,Price,Total,goodsOrder) VALUES (isnull(@ptypeid,''),isnull(@ktypeid,''),@Qty,@Price,@Total,0)
     END
     else
     begin
          SELECT @Qty=ISNULL(Qty,0)+ ISNULL(@Qty,0),@Total=ISNULL(Total,0)+ ISNULL(@Total,0) FROM iniGoodsStocks 
          WHERE ptypeid=ISNULL(@ptypeid,'') AND ktypeid=ISNULL(@ktypeid,'')

          update iniGoodsStocks set Qty=@Qty,Price=CASE WHEN ISNULl(@Qty,0)=0 THEN 0 ELSE ISNULL(@Total,0)/ISNULL(@Qty,1) END,Total=@Total 
          WHERE ptypeid=ISNULL(@ptypeid,'') AND ktypeid=ISNULL(@ktypeid,'')
     end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



/*
	作者：王刚
	日期：2012-05-4
	描述：移动加权下写批号  GOODSSTOCKS_BATCHNO		IniGoodsStocks
*/
CREATE   PROCEDURE Gp_GoodsNumIniData
(
	@Type			VARCHAR(10),		-- A.新增   M.修改  D.删除
	@PTypeId		VARCHAR(100),
	@KTypeId		VARCHAR(100),
	@Qty			 NUMERIC(24, 10) ,
	@Price			 NUMERIC(24, 10) ,
	@Total			 NUMERIC(24, 10) ,
	@GoodsNumber	VARCHAR(1000)
)
--@encode$--
AS
SET NOCOUNT ON

IF @Type = 'A'
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM GOODSSTOCKS_BATCHNO WHERE GoodsNumber = @GoodsNumber)
	BEGIN
		RAISERROR('此批号已经存在！',16,1)
		RETURN
	END

	INSERT GOODSSTOCKS_BATCHNO(PTypeID,KTypeID,GoodsNumber,Qty) VALUES(@PTypeId,@KTypeId,@GoodsNumber,@Qty)
	
	IF EXISTS(SELECT TOP 1 1 FROM IniGoodsStocks WHERE PtypeId = @PTypeId AND KtypeId = @KTypeId)
	BEGIN
		UPDATE IniGoodsStocks
		SET Qty = Qty + @Qty,
			Total = Total + @Total
		WHERE PtypeId = @PTypeId AND KtypeId = @KTypeId	
	END
	ELSE
	BEGIN
		INSERT IniGoodsStocks
		(	PtypeId,
			KtypeId,
			OutFactoryDate,
			Qty,
			Price,
			Total,
			GoodsOrder,
			GoodsNumber
		)
		VALUES
		(	
			@PTypeId,
			@KTypeId,
			GETDATE(),
			@Qty,
			@Price,
			@Total,
			0,
			''
		)
	END
END

IF @Type = 'M'
BEGIN
	DECLARE @T_Qty  NUMERIC(24, 10) 
	
	SELECT @T_Qty = Qty FROM GOODSSTOCKS_BATCHNO WHERE PTypeID = @PTypeId AND KTypeID = @KTypeId AND GoodsNumber = @GoodsNumber
	
	UPDATE GOODSSTOCKS_BATCHNO
	SET Qty = @Qty
	WHERE PTypeID = @PTypeId AND KTypeID = @KTypeId AND GoodsNumber = @GoodsNumber
	
	IF EXISTS(SELECT TOP 1 1 FROM IniGoodsStocks WHERE PtypeId = @PTypeId AND KtypeId = @KTypeId)
	BEGIN
		UPDATE IniGoodsStocks
		SET Qty = Qty - @T_Qty + @Qty,
			Total = (Qty - @T_Qty + @Qty) * Price
		WHERE PtypeId = @PTypeId AND KtypeId = @KTypeId	
	END
END

IF @Type = 'D'
BEGIN
	DELETE GOODSSTOCKS_BATCHNO WHERE PTypeID = @PTypeId AND KTypeID = @KTypeId AND GoodsNumber = @GoodsNumber
	
	IF EXISTS(SELECT TOP 1 1 FROM IniGoodsStocks WHERE PtypeId = @PTypeId AND KtypeId = @KTypeId)
	BEGIN
		UPDATE IniGoodsStocks
		SET Qty = Qty - @Qty,
			Total = Total - @Total
		WHERE PtypeId = @PTypeId AND KtypeId = @KTypeId	
	END
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GP_GoodsSellStat]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].GP_GoodsSellStat
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*------------------------------------------
 作者：	蒋奎
 日期：	2014-6-17
 描述：	跨帐套查询-商品销售统计-数据源获取				
 思路:	C#多线程会遍历这个存储过程,遍历一次出一个帐套的商品销售明细数据到@tbName临时表
-------------------------------------------*/
CREATE PROCEDURE GP_GoodsSellStat
(
	@accconstr  VARCHAR(1000),		--一个帐套的连接字符串
	/*@stypeid	VARCHAR(max)='',	--分支机构
	@ptypeid	VARCHAR(MAX)='',	--商品id
	@btypeid	varchar(1550)='',	--结算单位
	@dealbtypeid VARCHAR(1550)='',	--往来单位
	@ktypeid	varchar(1550)='',*/	--仓库名称
	@startdate  VARCHAR(30),		--查询起始时间
	@enddate	VARCHAR(30),		--查询结束时间
	@reportname VARCHAR(50),		--报表类型，SA_GoodsSellStat商品销售
	@tbName		VARCHAR(100),		--临时表名
	@ruletype		INT,			--规则类型: 0=系统规则,1=自定义规则的编码, 2=自定义规则的名称 , 3=自定义规则的编码和名称
	@pid		VARCHAR(max)='',
	@pusercode	VARCHAR(max)='',
	@pfullname	VARCHAR(max)='',
	@bid		VARCHAR(max)='',
	@busercode	VARCHAR(max)='',
	@bfullname	VARCHAR(max)='',
	@sid		VARCHAR(max)='',
	@susercode	VARCHAR(max)='',
	@sfullname	VARCHAR(max)='',
	@kid		VARCHAR(max)='',
	@kusercode	VARCHAR(max)='',
	@kfullname	VARCHAR(max)='',
	@dealid		VARCHAR(max)='',
	@dealusercode	VARCHAR(max)='',
	@dealfullname	VARCHAR(max)='',
	@showway			VARCHAR(30)	--统计方式 full全部，season 按季度 year 按年度

)
--@encode$--

AS
BEGIN
SET NOCOUNT ON 
	
	--将Selector选择的基本信息,根据合并规则从查询帐套出数据到临时表-----开始------------------------------
	CREATE TABLE #Ptype (TypeID varchar(50),pID INT,usercode VARCHAR(200),fullname VARCHAR(200) )
	CREATE TABLE #Btype (TypeID varchar(50))
	CREATE TABLE #DealBtype (TypeID varchar(50))
	CREATE TABLE #Ktype (TypeID varchar(50))
	CREATE TABLE #Stype (TypeID varchar(50))
	
	DECLARE @BaseInfoSql VARCHAR(max)

	IF @ruletype=0 --系统规则
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid,Pid,UserCode,FullName FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pid+''','','') WHERE ISNULL(A,'''')<>'''' AND pid=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@bid+''','','') WHERE ISNULL(A,'''')<>'''' AND bid=a
		INSERT INTO #DealBtype  SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealid+''','','') WHERE ISNULL(A,'''')<>'''' AND bid=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kid+''','','') WHERE ISNULL(A,'''')<>'''' AND kid=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@sid+''','','') WHERE ISNULL(A,'''')<>'''' AND sid=a  '
	END
	IF @ruletype=1 --自定义规则的编码
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid,Pid,UserCode,FullName FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@busercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #DealBtype  SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kusercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@susercode+''','','') WHERE ISNULL(A,'''')<>'''' AND usercode=a  '
	END
	IF @ruletype=2 --自定义规则的名称
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype SELECT  typeid,Pid,UserCode,FullName FROM  '+@accconstr+'.dbo.ptype , f_split('''+@pfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Btype SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@bfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #DealBtype  SELECT  typeid FROM  '+@accconstr+'.dbo.btype, f_split('''+@dealfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Ktype SELECT  typeid FROM  '+@accconstr+'.dbo.Stock, f_split('''+@kfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a
		INSERT INTO #Stype SELECT  typeid FROM  '+@accconstr+'.dbo.SType, f_split('''+@sfullname+''','','') WHERE ISNULL(A,'''')<>'''' AND FullName=a  '
	END
	IF @ruletype=3 --自定义规则的编码和名称
	BEGIN
		SET @BaseInfoSql='
		INSERT INTO #Ptype 
		SELECT   typeid,Pid,UserCode,FullName 
		FROM '+@accconstr+'.dbo.ptype p, f_split('''+@pusercode+''','','') u,f_split('''+@pfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND p.UserCode=u.a AND p.FullName=f.a
		
		INSERT INTO #Btype SELECT  typeid 
		FROM '+@accconstr+'.dbo.btype b, f_split('''+@busercode+''','','') u,f_split('''+@bfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND b.UserCode=u.a AND b.FullName=f.a
		
		INSERT INTO #DealBtype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.btype b, f_split('''+@dealusercode+''','','') u,f_split('''+@dealfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND b.UserCode=u.a AND b.FullName=f.a
		
		INSERT INTO #Ktype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.Stock k, f_split('''+@kusercode+''','','') u,f_split('''+@kfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND k.UserCode=u.a AND k.FullName=f.a
		
		INSERT INTO #Stype 
		SELECT  typeid 
		FROM '+@accconstr+'.dbo.SType s, f_split('''+@susercode+''','','') u,f_split('''+@sfullname+''','','') f
		WHERE ISNULL(u.A,'''')<>'''' AND  ISNULL(f.A,'''')<>'''' AND s.UserCode=u.a AND s.FullName=f.a	'
	END
	--PRINT @BaseInfoSql
	EXEC (@BaseInfoSql)

	--如果#ptype里面没有数据(说明没有Selector数据),就直接从帐套出数据到#ptype
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #ptype)
    BEGIN
    SET @BaseInfoSql='
		INSERT INTO #ptype 
		SELECT  typeid,pid,usercode,FullName 
		FROM  '+@accconstr+'.dbo.ptype 
		WHERE sonnum=0   '
    END
	EXEC(@BaseInfoSql)
	
	--将Selector选择的基本信息,根据合并规则从帐套出数据到临时表-----结束------------------------------

	--时间字段处理
	DECLARE @sql VARCHAR(max)='',		--拼接sql
			@insertColumn VARCHAR(50),	--插入列
			@selectColumn VARCHAR(200)	--选择列

	IF @showway = 'full'	--所有
	BEGIN
		SET @insertColumn =''
		SET @selectColumn =''
	END
	IF @showway = 'season'	--季度
	BEGIN
		SET @insertColumn = 'timeType,'
		SET @selectColumn = 'CAST(YEAR(bi.BillDate) AS VARCHAR(10))+ CAST(DATEPART(qq,bi.BillDate) AS VARCHAR(10)),'
	END
	IF @showway = 'year'	--年
	BEGIN
		SET @insertColumn = 'timeType,'
		SET @selectColumn = 'YEAR(bi.BillDate),'
	END 
	
	SET @selectColumn=@selectColumn+'a.ptypeid'			--商品id
	
	
	
	--主数据 --> 从出入库表和单据主索引表里面出商品的销售明细
	
	SELECT @sql+='	INSERT INTO ['+@tbName+'] ('+@insertColumn+'TypeID,usercode,fullname,basicunit,isgift,Qty,Total,SaleTotal,TaxTotal,CostTotal,ProtectTotal,Advantagetotal,ShareFee,xid) 
					SELECT  
						'+@selectColumn+',
						p.usercode,
						p.fullname,
						basicunit='' '',
						a.isgift,
						-a.qty,
						-a.total,
						-a.SaleTotal,
						-a.TaxTotal,
						-a.CostTotal,
						ProtectTotal =0,
						Advantagetotal=0,
						-a.sharefee,
						p.pid	
					FROM '+@accconstr+'.dbo.InoutStockTable a
					INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId  
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Ptype)
			SELECT @sql=@sql+' 	INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%''  '
				
		IF EXISTS(SELECT TOP 1 1 FROM #Btype)
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype) --AND @dealbtypeid NOT IN('00001','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Ktype)
			SELECT @sql=@sql+'	INNER JOIN #Ktype k ON a.KTypeID like k.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE a.BillDate >= '''+@startdate+''' AND a.BillDate<='''+@enddate+''' 
				AND a.IsGift = 0  AND BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND a.billtype in(305,215,11,45,160,141,12,46)
					     '


	--价保 -->只出价保数据其它的不出
	CREATE TABLE #ProtectTotal
	(
		typeid VARCHAR(50),
		ProtectTotal  NUMERIC(24, 10) 
	)
	SELECT @sql+='	INSERT INTO ['+@tbName+'] ('+@insertColumn+'TypeID,usercode,fullname,basicunit,isgift,Qty,Total,SaleTotal,TaxTotal,CostTotal,ProtectTotal,Advantagetotal,ShareFee,xid) 
					SELECT  
						'+@selectColumn+',
						p.usercode,
						p.fullname,
						basicunit='' '',
						isgift=0,
						qty=0,
						total=0,
						SaleTotal=0,
						TaxTotal=0,
						CostTotal=0,
						ProtectTotal=sum(a.total), 
						Advantagetotal=0,
						sharefee=0,	
						p.pid	
					FROM '+@accconstr+'.dbo.PriceProtectBill a 
				INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
				INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
				'
		IF EXISTS(SELECT TOP 1 1 FROM #Btype)
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype) --AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE bi.BillDate >= '''+@startdate+''' AND bi.BillDate<='''+@enddate+''' 
				AND  BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND bi.billtype=149
				GROUP BY 
						'	+@selectColumn+',
							p.pid,
							p.usercode,
							p.fullname
						'
	 

	
	--返利 -->只出返利数据其它的不出
	CREATE TABLE #Advantagetotal
	(
		typeid VARCHAR(50),
		Advantagetotal  NUMERIC(24, 10) 
	)
	SELECT @sql+='	INSERT INTO ['+@tbName+'] ('+@insertColumn+'TypeID,usercode,fullname,basicunit,isgift,Qty,Total,SaleTotal,TaxTotal,CostTotal,ProtectTotal,Advantagetotal,ShareFee,xid) 
					SELECT  
						'+@selectColumn+',
						p.usercode,
						p.fullname,
						basicunit='' '',
						isgift=0,
						qty=0,
						total=0,
						SaleTotal=0,
						TaxTotal=0,
						CostTotal=0,
						ProtectTotal=0,
						Advantagetotal=sum(a.total), 
						sharefee=0,	
						p.pid
					FROM '+@accconstr+'.dbo.Advantage a 
					INNER JOIN '+@accconstr+'.dbo.BillIndex bi ON a.BillNumberId=bi.BillNumberId 
					INNER JOIN #Ptype p ON a.PtypeId  like p.TypeID+''%'' 
				 '
		IF EXISTS(SELECT TOP 1 1 FROM #Btype) 
			SELECT @sql=@sql+'   INNER JOIN #Btype b ON  bi.BtypeId  like b.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #DealBtype) --AND @dealbtypeid NOT IN('00002','00000')
			SELECT @sql=@sql+'	INNER JOIN #DealBtype d ON bi.DealBTypeID like d.TypeID+''%'' 
			'
		IF EXISTS(SELECT TOP 1 1 FROM #Stype)
			SELECT @sql=@sql+'	INNER JOIN #Stype s ON  a.STypeID like s.TypeID+''%'' 
			'
		SELECT @sql=@sql+'		WHERE bi.BillDate >= '''+@startdate+''' AND bi.BillDate<='''+@enddate+''' 
				AND  BI.redword=0 AND bi.draft=0  AND bi.ifYearBill= 0 AND bi.billtype=148
				GROUP BY 
						'	+@selectColumn+',
							p.pid,
							p.usercode,
							p.fullname
						'
	
		
				
	--PRINT (@sql)				
	EXEC(@sql)
				
END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
局部更新
优化 卢春 2010-08-10
*/
/*
	修改：赵斌
	日期：2011-09-02
	描述：名称列支持拼音码
*/
/*
	修改：李灏龙
	日期：2012年2月21日15:40:40
	描述：名称列支持规格的模糊查询
		  具体修改：zs001
*/
/*
	修改：李灏龙
	日期：2012年6月12日10:15:35
	描述：增加货位筛选
		  具体修改：zs002
*/
/*
	修改：李灏龙
	日期：2012年9月17日 14:39:39
	描述：跟踪价格与结算单位关联
		  具体修改：zs003
*/
/*
	修改：田小波
	日期：2016年11月17日 
	描述：启用多单位单价后 需要关联单位ID
*/
/*
	修改：刘飞
	日期：2017年3月22日 
	描述：子查询条件不充分,导致TOP和ORDER BY出来的结果和外面的筛选条件不匹配,从而查不到数据
*/
/*
	修改：刘飞
	日期：2017年4月25日 
	描述：选序列号,销售出库单需根据,是否借出转销售筛选
*/
CREATE           PROCEDURE GP_GridLocalUpdateQueryBaseInfo23
(
	@OperatorID		varchar(50),
	@DBName			varchar(128),
	@UserCode		varchar(500) = '',
	@FullName		varchar(500) = '',
	@GridID			int, 				-- 销售换货单出入库区别标志
	@Condition		varchar(500),
	@BTypeTrack		varchar(500),		-- 往来单位名称
	@IfTrack		int,
	@chvBillType	varchar(50)	= '',	-- 单据类型
	@chvKTypeName	varchar(500) = '',	-- 仓库名称
	@chvCargoID		varchar(500),		--zs002：货位ID
	@useCargo		INT = 1,			--zs010: 是否启用货位 1：是   0：否
	@chvETypeName	varchar(500) = '',	-- 经手人名称
	@chvBillDate	varchar(100) = '',	-- 单据日期
	@chvDTypeName	varchar(500) = '',	-- 部门名称
	@wxproperty		int = 0,			-- 维修属性（erp5.0添加）
	@EntryCode		varchar(500) = '',	-- 配件条码(qp20 Wang Wei Add)
	@stid			VARCHAR(50)='00001',
	@cargoktypeid	VARCHAR(20),				--暂时不用了
	@cid			VARCHAR(50) = '0',
	@chvDenominated VARCHAR(500)='',		--zs003:结算单位id
	@chvDealBtypeID VARCHAR(500)='',		--zs003:往来单位id
	@mcid				VARCHAR(50)='',		--当前单据的币种
	@isservice          INT = 1,             --是否显示服务商品
	@chvitemid			    VARCHAR(100) = '',
	@chvcargoiddata		    VARCHAR(100) = '',
	@chviscombined		    VARCHAR(100) = '',
	@chvproducedate		VARCHAR(100) = '',
	@chvvaliddate		    VARCHAR(100) = '',
	@chvgoodsnumber		VARCHAR(100) = '',
	@chvcostprice       VARCHAR(100) = '',
	@existcombination	int =   0,
	@chvlendtosale      int	=   0     --是否勾选借出转销售：0未勾选，1勾选
)
--@encode$--
AS
SET NOCOUNT ON	-- 返回结果不受影响
--将序列号单独出来处理
IF LEFT(@DBName, 6) = 'Serial'
BEGIN	
	EXEC GP_ExactMatchingSerial @OperatorID,@DBName,@UserCode,@FullName,@GridID,@Condition,@BTypeTrack,@IfTrack,@chvBillType,@chvKTypeName,@chvCargoID,@useCargo,@chvETypeName,@chvBillDate,@chvDTypeName,@wxproperty,@EntryCode,@stid,@cargoktypeid,@cid,@chvDenominated,@chvDealBtypeID,@mcid,@isservice,@chvitemid,@chvcargoiddata,@chviscombined,@chvproducedate,@chvvaliddate,@chvgoodsnumber,@chvcostprice,@existcombination,@chvlendtosale
	RETURN;	
END
IF @DBName IS NULL  RETURN 1
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @OperatorID
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------

DECLARE @cKtypeID varchar(50)

select @cKtypeID=typeid from stock where fullname= @chvKTypeName

IF @cKtypeID is null or @cKtypeID = ''
SET @cKtypeID='00001'


--没有分支机构，强行赋值默认分支机构
IF @stid=NULL OR @stid=''
	SET @stid='00001'

-- 系统配置采用价格跟踪

DECLARE @numSalePrice  NUMERIC(24, 10) , @numCostPrice  NUMERIC(24, 10) 	--#-01
SET @numSalePrice = 0
SET @numCostPrice = 0

--系统配置是否使用多编码
DECLARE @MultiCode varchar(1)
SET @MultiCode = '0'
SELECT TOP 1 @MultiCode = Value FROM UserConfig WHERE ConfigName = 'IfMultiCode'


-- 声明 SQL 语句变量
DECLARE @SQL varchar(MAX) 
SELECT @SQL = ''


--如果没有cid，unitid,则cid默认为本位币,unitid为商品默认单位
IF @cid = ''
	SELECT @mcid = cid FROM Ac_Currency WHERE Sysrow = 1
	
DECLARE @unittype VARCHAR(50) 
SELECT	@unittype = CASE WHEN @chvBillType IN (11,12,300,313,184,305,45,46,160,140,142,141,215,402,403) THEN 'SaleUnitId'		--销售单,销售订单,报价单等销售类单据
					     WHEN @chvBillType IN (34,301,185,6,161,144,145,146,400,401) THEN 'BuyUnitId'		--采购单,采购订单,询价单等采购类单据
						 WHEN @chvBillType IN(17,21,187,188,175,310,420) THEN 'StockUnitId'
					ELSE 'baseunitid' END 

IF not exists(select top 1 1 from CargoType c inner join STOCK s on s.typeId = c.KtypeID where c.CargoID=@chvCargoID and s.FullName=''+@chvKTypeName+'') and @chvCargoID !=''
	SELECT TOP 1 @chvCargoID = c.CargoID from STOCK k inner join CargoType c on k.typeId = c.KtypeID where c.IsDefault = 1 and k.FullName = ''+@chvKTypeName+''


declare @pricetracktype varchar(5)
select @pricetracktype=isnull(Value,1)-1   from Userconfig where ConfigName = 'pricetracktype'

DECLARE @SalePriceTrack varchar(50),@SaleOrderPriceTrack varchar(50),
		@BuyPriceTrack varchar(50),@BuyOrderPriceTrack varchar(50),@QueryPrice VARCHAR(50),@ResponsePrice VARCHAR(50),
		@BuyOrBackOriginalPrice varchar(100),
		@BuyOrBackDiscountRate varchar(100),
		@SaleOrBackOriginalPrice varchar(100),
		@SaleOrBackDiscountRate varchar(100),
		@DiscountTrack varchar(100),	
		@DiscountPriceTrack varchar(100),
		@PriceTrack varchar(100),
		@TaxTrack	varchar(100),
		@TaxPriceTrack	varchar(100),
		@TrackTableSql VARCHAR(MAX)
		
		
		SET @SalePriceTrack = '0 AS SalePriceTrack'
		SET @SaleOrderPriceTrack = '0 AS SaleOrderPriceTrack'
		SET @BuyPriceTrack = '0 AS BuyPriceTrack'
		SET @BuyOrderPriceTrack = '0 AS BuyOrderPriceTrack'
		SET @QueryPrice = '0 AS QueryPrice'
		SET @ResponsePrice = '0 AS ResponsePrice'
		SET @BuyOrBackOriginalPrice = '0 AS BuyOrBackOriginalPrice'
		SET @BuyOrBackDiscountRate ='0 AS BuyOrBackDiscountRate'
		SET @SaleOrBackOriginalPrice ='0 AS SaleOrBackOriginalPrice'
		SET @SaleOrBackDiscountRate ='0 AS SaleOrBackDiscountRate'
		SET @DiscountTrack ='0 AS DiscountTrack'
		SET @DiscountPriceTrack ='0 AS DiscountPriceTrack'
		SET @PriceTrack ='0 AS PriceTrack'
		SET @TaxTrack='0 AS TaxTrack'
		SET @TaxPriceTrack='0 AS TaxPriceTrack'
		SET @TrackTableSql = ''

------------------------------------------价格跟踪  start  -----------------------------------
CREATE TABLE #temp_PriceTrack
(
	PtypeId				varchar(50),
	DiscountTrack   NUMERIC(24, 10) ,			--价格跟踪扣率跟踪
	DiscountPriceTrack	  NUMERIC(24, 10) ,		--价格跟踪扣率跟踪
	PriceTrack	  NUMERIC(24, 10), 			--价格跟踪扣率跟踪
	TaxTrack	NUMERIC(24,10),				--税率跟踪
	TaxPriceTrack	NUMERIC(24,10),			--含税单价跟踪
	DiscountTrackStype   NUMERIC(24, 10) ,			--分支机构间价格跟踪扣率跟踪
	DiscountPriceTrackStype	  NUMERIC(24, 10) ,		--分支机构间价格跟踪扣率跟踪
	PriceTrackStype	  NUMERIC(24, 10), 			--分支机构间价格跟踪扣率跟踪
	TaxTrackStype	NUMERIC(24,10),				--分支机构间税率跟踪
	TaxPriceTrackStype	NUMERIC(24,10),			--分支机构间含税单价跟踪
	[UID]		INT,
	isbtypetrack	INT,
	pricetracksource INT
);
IF @DBName <> 'ptype'
BEGIN
	INSERT INTO #temp_PriceTrack
	EXEC Web_GetPriceTrackInfo @cid,@stid,@chvDenominated,@chvDealBtypeID,@chvBillType
END
------------------------------------------价格跟踪  End    -----------------------------------

DECLARE @PriceType varchar(5)
SELECT @PriceType=PriceType FROM SType WHERE TypeId=@stid
IF @stid = '' OR @stid = null
SET @PriceType='0'
					  
IF @DBName = 'ptype'
BEGIN
	DECLARE @StopBuySql vARCHAR(2000) --采购入库单、采购换货单、采购订单中增加“停止采购”
	set @StopBuySql=''
	IF @chvBillType IN(34,204,301,400)  OR (@chvBillType=161 AND @GridID=2 )
		SET @StopBuySql=' AND ISNULL(p.stopbuy,0)=0 '
		
	--选商品根据配置
	DECLARE @combineSQL NVARCHAR(MAX)='',@combineSQL1 NVARCHAR(MAX),@combineSQLwithMultiCode NVARCHAR(MAX)='',@chvMode varchar(50) = '',-- FullNameOrUserCode列检索的标识
			@tempSQL NVARCHAR(1000)
			
	IF (@UserCode <> '')
	BEGIN
		SET @chvMode='usercode'
	END
	ELSE IF (@FullName <> '')
	BEGIN
		SET @chvMode='fullname'
	END
	SET @combineSQL=dbo.F_CombinePtypeSearchByConfig(@chvMode,@UserCode,'','',@FullName,'','0')
	SET @combineSQL1 = dbo.F_CombinePtypeSearchByConfigNew(@chvMode,@UserCode,'','',@FullName,'','0',1)
	------------------------------------------价格跟踪  start  -----------------------------------
	IF @chvBillType IN (16,187,306,127)
	BEGIN
		INSERT INTO #temp_PriceTrack
		EXEC Web_GetPriceTrackInfo_InTable @cid,@stid,@chvDenominated,@chvDealBtypeID,@chvBillType,@combineSQL
	END
	------------------------------------------价格跟踪  End    -----------------------------------				
	--系统采用多编码
	DECLARE @IfMultiCodeBill int=0
	IF @MultiCode = '1' --AND @chvBillType IN ('305','300','11','6','160','140','141','142','143','144','145','146','147','301','34','45','161','177','178','183','184','185','201','202','215','313','12','46')
		SET @IfMultiCodeBill = 1
	
	declare @bill_ptypeexactmatching int 
	select @bill_ptypeexactmatching=[Value] from Userconfig where ConfigName='bill_ptypeexactmatching' 

	CREATE TABLE #one(typeid VARCHAR(50))
	
	-- 生产拆装单 ( 出库 )
	IF @chvBillType = '16' OR @chvBillType = '187' OR @chvBillType='173'
	BEGIN
	
		SET @tempSQL = 'INSERT INTO #one( typeid )
					SELECT	 p.typeid
					FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
					WHERE	p.SonNum = 0 And p.Deleted = 0 AND p.TypeID <> ''00000''
					' + case when @bill_ptypeexactmatching=1 then @combineSQL1 else @combineSQL end+CASE WHEN @isservice = 0 THEN + ' AND P.isservice = 0 ' ELSE ' ' END + '
					' + CASE WHEN @existcombination=0 
							 THEN '  AND ISNULL(p.iscombinationproduct,0)=0 ' 
							 ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(P.iscombinationproduct,0)=1  AND P.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						END 
		EXEC (@tempSQL)

		IF (SELECT COUNT(*) FROM #one)>1
			TRUNCATE TABLE #one
	
	
		-- 判断系统的成本算法；0：移动加权平均；1：先进先出；2：后进先出 3:手工指定法
		DECLARE @strCosting char(1)
		SELECT TOP 1 @strCosting = SubValue FROM SysData WHERE SubName = 'costing'
		DECLARE @strAssistant VARCHAR(5000)
		SET @strAssistant = ''
		--IF @chvBillType = '16'
			SET @strAssistant = '(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID)) as auxfullname1,
								 (select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID)) as auxfullname2,
								 (select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID)) as auxfullname3,
								 (select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID) as auxrate1,
								 (select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID) as auxrate2,
								 (select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID) as auxrate3,'

		SET @SQL = '
				SELECT	p.*,
						f.unitid,
						f.unit,
						f.unitrate,
						f.nunitid,
						f.nunit,
						f.rate,
						f.buyunitname,
						f.buymunitrate,
						f.saleunitname,
						f.salemunitrate,
						f.stockunitname,
						' + CASE WHEN @UserCode <> '' THEN ''''+@UserCode+'''' 
						WHEN @FullName <> '' THEN ''''+@FullName+''''
						ELSE '''''' END + ' AS multentrycode1,
						f.stockmunitrate,'
						IF @DBName<>'Ac_Items'
						BEGIN 
							SET @SQL = @SQL+'
							dbo.F_GetAllEntrycode(p.typeid,p.SaleUnitId,2) AS salemunitcode,
							dbo.F_GetAllEntrycode(p.typeid,p.BuyUnitId,2) AS buymunitcode,
							dbo.F_GetAllEntrycode(p.typeid,p.StockUnitId,2) AS stockmunitcode,
							dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2) AS basemunitcode,
							'
						END
						SET @SQL = @SQL+'
					'''' AS CustomerCode,
					'''' AS Serial,
					' + CASE WHEN @strCosting = '3' THEN '0' ELSE 'CASE WHEN g.CostPrice IS NULL THEN CAST(p.RecPrice AS  NUMERIC(24, 10) ) ELSE CAST(g.CostPrice AS  NUMERIC(24, 10) ) END' END + ' AS CostPrice
				FROM (
					SELECT DISTINCT * FROM (						
					SELECT	TOP 2 p.*,
						'+@strAssistant
					+'0 AS ShowOrder
					FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END +'
					WHERE	p.SonNum = 0 And p.Deleted = 0 AND p.TypeID <> ''00000''
						' +CASE WHEN EXISTS(SELECT TOP 1 * FROM #one) THEN ' AND p.TypeID = '''+(SELECT typeid FROM #one)+'''' ELSE  @combineSQL END + '
							' + CASE WHEN @EntryCode <> '' THEN 'AND p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @EntryCode + ''',1))' ELSE '' END + '
					' + CASE WHEN @isservice = 0 THEN + ' AND P.isservice = 0 ' ELSE ' ' END + '
					' + CASE WHEN @existcombination=0 
							 THEN '  AND ISNULL(p.iscombinationproduct,0)=0 ' 
							 ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(P.iscombinationproduct,0)=1  AND P.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						END 						
						--既然是精确匹配,那top2排序有什么意义？直接去掉排序
					--+ ' ORDER BY ShowOrder 
					+ '
					UNION ALL 
					SELECT	TOP 1 p.*,
						'+@strAssistant
					+'0 AS ShowOrder
					FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
					WHERE	p.SonNum = 0 And p.Deleted = 0 AND p.TypeID <> ''00000''
					' +CASE WHEN EXISTS(SELECT TOP 1 * FROM #one) THEN ' AND p.TypeID = '''+(SELECT typeid FROM #one)+'''' ELSE  @combineSQL END + '
							' + CASE WHEN @EntryCode <> '' THEN 'AND p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @EntryCode + ''',1))' ELSE '' END 
					+ CASE WHEN @isservice = 0 THEN + ' AND P.isservice = 0 ' ELSE ' ' END + '
					' + CASE WHEN @existcombination=0 
							 THEN '  AND ISNULL(p.iscombinationproduct,0)=0 ' 
							 ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(P.iscombinationproduct,0)=1  AND P.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						END 
					+ ') X 
					
				) p
				LEFT JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = p.typeid
				' + CASE WHEN @strCosting = '3' THEN '' ELSE 'LEFT JOIN (
					SELECT	g.PTypeID,
						CostPrice = CAST(SUM(g.Total) AS NUMERIC(24,10)) / CAST(CASE WHEN SUM(g.QTY) = 0 THEN NULL ELSE SUM(g.QTY) END AS NUMERIC(24,10))
					FROM	GoodsStocks g, Stock s
					WHERE	g.KTypeID = s.TypeID
						AND (s.FullName = ''' + @chvKTypeName + ''' OR s.UserCode = ''' + @chvKTypeName + ''')
					GROUP BY g.PTypeID
				) g ON g.PTypeID = p.TypeID' END			
	END 
	--盘点单
	ELSE IF  @chvBillType = '306'
	BEGIN
		DECLARE @chvKTypeTrackID varchar(50)
		SET @chvKTypeTrackID = ''
		IF @chvKTypeName <> ''
		BEGIN
			SELECT	TOP 1 @chvKTypeTrackID = TypeID
			FROM	Stock
			WHERE	UserCode = @chvKTypeName
				OR FullName = @chvKTypeName
					
			--如果没有传入货位，则改为仓库的默认货位
			IF @chvCargoID = ''
			SELECT @chvCargoID = CargoID FROM CargoType WHERE KtypeID = @chvKTypeTrackID AND IsDefault = 1
		END
		SET @SQL = '
				SELECT	p.*,
						'''' AS CustomerCode,
						'''' AS Serial,
						ISNULL(g.Qty,0) AS qty,
						ISNULL(g.NQTY,0) AS nqty,
						ISNULL(w.Qty,0) AS WxQty,
						ISNULL(W.NQTY,0) AS WxNQTY,
						f.unitid,
						f.unit,
						f.unitrate,
						f.nunitid,
						f.nunit,
						f.rate,
						f.buyunitname,
						f.buymunitrate,
						f.saleunitname,
						f.salemunitrate,
						f.stockunitname,
						f.stockmunitrate,
						' + CASE WHEN @UserCode <> '' THEN ''''+@UserCode+'''' 
						WHEN @FullName <> '' THEN ''''+@FullName+''''
						ELSE '''''' END + ' AS multentrycode1,
						ISNULL(aux1.fullname,'''') AS auxfullname1, 
						ISNULL(aux2.fullname,'''') AS auxfullname2, 
						ISNULL(aux3.fullname,'''') AS auxfullname3,
						ISNULL(aux.SaleUnitRate1,0) AS auxrate1,
						ISNULL(aux.SaleUnitRate2,0) AS auxrate2,
						ISNULL(aux.SaleUnitRate3,0) AS auxrate3,
						dbo.F_GetAllEntrycode(p.typeid,f.StockUnitId,2) AS stockmunitcode
					   
				FROM (
					SELECT DISTINCT * FROM (
					SELECT	TOP 2 p.* 
					' 
						--既然是精确匹配,那top2排序有什么意义？直接去掉排序					
				--	+ CASE WHEN @UserCode <> '' THEN 'CASE WHEN (p.UserCode = ''' + @UserCode + ''' 
				--											OR (SELECT count(*) FROM dbo.f_split(p.multentrycode,'';'') WHERE a=''' + @UserCode + '''   )>0 
				--											OR p.Standard = ''' + @UserCode + '''
				--											OR p.PyCode = ''' + @UserCode + '''
				--											OR p.FullName = ''' + @UserCode + ''' 
				--											OR p.Type = ''' + @UserCode + ''')' ELSE '' END + '
				--' +CASE WHEN @FullName <> '' THEN 'CASE WHEN (p.UserCode = ''' + @FullName + ''' 
				--													OR (SELECT count(*) FROM dbo.f_split(p.multentrycode,'';'') WHERE a=''' + @FullName + '''   )>0
				--													OR p.Standard = ''' + @FullName + '''
				--													OR p.PyCode = ''' + @FullName + '''
				--													OR p.FullName = ''' + @FullName + '''
				--													OR p.Type = ''' + @FullName + ''')' ELSE '' END +'
				--	THEN 0 ELSE 1 END AS ShowOrder	
					+'
					FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
					WHERE	p.SonNum = 0 And p.Deleted = 0 AND p.TypeID <> ''00000''
						' + @combineSQL + '
						' + CASE WHEN @isservice = 0 THEN + ' AND P.isservice = 0 ' ELSE ' ' END + '
						'+ CASE WHEN @existcombination=0 
								THEN ' AND ISNULL(p.iscombinationproduct,0)=0 ' 
								ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(P.iscombinationproduct,0)=1  AND P.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						   END 
						--既然是精确匹配,那top2排序有什么意义？直接去掉排序	
						 --+' ORDER BY ShowOrder 
						 + '
					UNION ALL 
					SELECT	TOP 1 p.*
					FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
					WHERE	p.SonNum = 0 And p.Deleted = 0 AND p.TypeID <> ''00000''
					' + @combineSQL1 + CASE WHEN @isservice = 0 THEN + ' AND P.isservice = 0 ' ELSE ' ' END + '
					' + CASE WHEN @existcombination=0 
							 THEN '  AND ISNULL(p.iscombinationproduct,0)=0 ' 
							 ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(P.iscombinationproduct,0)=1  AND P.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						END 
					+ ') X 
				) p
				LEFT JOIN dbo.PType_AuxiliaryUnits_Ext aux ON aux.ptypeid = p.typeid
				LEFT JOIN dbo.PType_Units aux1 ON aux1.UnitsId = aux.SaleUnitID1
				LEFT JOIN dbo.PType_Units aux2 ON aux2.UnitsId = aux.SaleUnitID2
				LEFT JOIN dbo.PType_Units aux3 ON aux3.UnitsId = aux.SaleUnitID3
				LEFT JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = p.typeid
				LEFT JOIN (SELECT PTypeID,SUM(ISNULL(Qty,0)) AS Qty,SUM(ISNULL(NQTY,0)) AS NQTY FROM GOODSSTOCKS_QTY WHERE KTypeID = ''' + @chvKTypeTrackID + ''''+ CASE WHEN @useCargo = 1 THEN ' AND CargoID = '''+ @chvCargoID +'''' ELSE '' END + ' GROUP BY PTypeID) g ON g.PTypeID = p.TypeID  --zs002:修改为货位筛选
				LEFT JOIN (SELECT PTypeID,SUM(ISNULL(Qty,0)) AS Qty,SUM(ISNULL(NQTY,0)) AS NQTY FROM Wx_GoodsStocks WHERE KTypeID = ''' + @chvKTypeTrackID + ''''+ CASE WHEN @useCargo = 1 THEN ' AND CargoID = '''+ @chvCargoID +'''' ELSE '' END + ' GROUP BY PTypeID) w ON w.PTypeID = p.TypeID'   
	END
	--生产模板
	ELSE IF @chvBillType = '127'
	BEGIN
		DECLARE @chvProKTypeId VARCHAR(100)
		SET @chvProKTypeId = ''
		IF @chvKTypeName <> ''
			SELECT TOP 1 @chvProKTypeId = TypeID FROM Stock WHERE UserCode = @chvKTypeName OR FullName = @chvKTypeName
		SELECT @SQL = '
			SELECT	p.*,
					CustomerCode = '''',
					Serial = '''',
					ISNULL(g.Qty,0) AS Qty,
					f.unitid,
					f.unit,
					f.unitrate,
					f.nunitid,
					f.nunit,
					f.rate,
					f.buyunitname,
					f.buymunitrate,
					f.saleunitname,
					f.salemunitrate,
					f.stockunitname,
					f.stockmunitrate,
					' + CASE WHEN @UserCode <> '' THEN ''''+@UserCode+'''' 
						WHEN @FullName <> '' THEN ''''+@FullName+''''
						ELSE '''''' END + ' AS multentrycode1
			FROM	(
					SELECT DISTINCT * FROM (
						SELECT	TOP 2 p.*
				'
				--既然是精确匹配,那top2排序有什么意义？直接去掉排序	
				-- + CASE WHEN @UserCode <> '' THEN 'CASE WHEN (p.UserCode = ''' + @UserCode + ''' 
				--											OR (SELECT count(*) FROM dbo.f_split(p.multentrycode,'';'') WHERE a=''' + @UserCode + '''   )>0   
				--											OR p.Standard = ''' + @UserCode + '''
				--											OR p.PyCode = ''' + @UserCode + '''
				--											OR p.FullName = ''' + @UserCode + ''' 
				--											OR p.Type = ''' + @UserCode + ''')' ELSE '' END + '
				--' +CASE WHEN @FullName <> '' THEN 'CASE WHEN (p.UserCode = ''' + @FullName + ''' 
				--													OR (SELECT count(*) FROM dbo.f_split(p.multentrycode,'';'') WHERE a=''' + @FullName + '''   )>0
				--													OR p.Standard = ''' + @FullName + '''
				--													OR p.PyCode = ''' + @FullName + '''
				--													OR p.FullName = ''' + @FullName + '''
				--													OR p.Type = ''' + @FullName + ''')' ELSE '' END +'
				--THEN 0 ELSE 1 END AS ShowOrder 
				+'
				FROM Ptype p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
				WHERE	p.SonNum = 0 And p.Deleted = 0 And p.TypeID <> ''00000'' '+ @combineSQL + '
						' + CASE WHEN @isservice = 0 THEN + ' AND P.isservice = 0 ' ELSE ' ' END + '
						 '+ CASE WHEN @existcombination=0 
								THEN ' AND ISNULL(p.iscombinationproduct,0)=0 ' 
								ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(P.iscombinationproduct,0)=1  AND P.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						    END 
						    
				--既然是精确匹配,那top2排序有什么意义？直接去掉排序	
						 --+' ORDER BY ShowOrder 
						 + '
					UNION ALL 
					SELECT	TOP 1 p.*
					FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
					WHERE	p.SonNum = 0 And p.Deleted = 0 AND p.TypeID <> ''00000''
					' + @combineSQL1 + CASE WHEN @isservice = 0 THEN + ' AND P.isservice = 0 ' ELSE ' ' END + '
					' + CASE WHEN @existcombination=0 
							 THEN '  AND ISNULL(p.iscombinationproduct,0)=0 ' 
							 ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(P.iscombinationproduct,0)=1  AND P.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						END 
					+ ') X
			) p
			LEFT JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = p.typeid
			LEFT JOIN (SELECT PTypeID,SUM(ISNULL(Qty,0)) AS Qty FROM GoodsStocks WHERE KTypeID LIKE ''' + @chvProKTypeId + '%'' AND KTypeId IN (SELECT TypeId FROM F_GetManDetailKType('+CHAR(39)+@chvOperatorID+CHAR(39)+')) GROUP BY PTypeID) g ON g.PTypeID = p.TypeID'
	END
	ELSE
 	BEGIN
		-----------------------------------------往来单位适用价----------------------------------------------
		DECLARE @BtypePrice VARCHAR(50)
		SELECT	TOP 1 @BtypePrice = ISNULL(Price,'')
		FROM	BType 
		WHERE	FullName = @BTypeTrack
		
		IF @BtypePrice IS NULL SET @BtypePrice = ''
		----------------------------------------------------------------------------------------------------

		-- 获取往来单位 ID 值,仓库ID值(没用了),价格跟踪使用
		DECLARE @chvBTypeTrackID varchar(50)
		SET @chvBTypeTrackID = ''
		IF @BTypeTrack <> ''
		BEGIN
			SELECT	TOP 1 @chvBTypeTrackID = TypeID
			FROM	BType
			WHERE	UserCode = @BTypeTrack
				OR FullName = @BTypeTrack
		END

		-- 获取销售出库单、采购入库单价格跟踪配置
		DECLARE @chvPriceTrack varchar(1)
		SELECT	TOP 1 @chvPriceTrack = Value
		FROM	UserConfig
		WHERE	ConfigName = 'PriceTrack'
		

		--选商品根据配置
		SET @combineSQLwithMultiCode=dbo.F_CombinePtypeSearchByConfig(@chvMode,@UserCode,'','',@FullName,'',@IfMultiCodeBill)	
		SET @combineSQL1 = dbo.F_CombinePtypeSearchByConfigNew(@chvMode,@UserCode,'','',@FullName,'',@IfMultiCodeBill,1)
		------------------------------------------价格跟踪  start  -----------------------------------
		IF @chvBillType NOT IN (16,187,306,127)
		BEGIN
			TRUNCATE TABLE #temp_PriceTrack
			INSERT INTO #temp_PriceTrack
			EXEC Web_GetPriceTrackInfo_InTable @cid,@stid,@chvDenominated,@chvDealBtypeID,@chvBillType,@combineSQLwithMultiCode
		END
		------------------------------------------价格跟踪  End    -----------------------------------		
		
		SET @tempSQL = 'INSERT INTO #one( typeid )
					SELECT	 p.typeid
					FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
					' + CASE WHEN @IfMultiCodeBill = 1 THEN 'LEFT JOIN PUserCode u ON u.BTypeID = '''+ @chvDealBtypeID + ''' AND p.TypeID = u.PTypeID' ELSE '' END + '
					WHERE	p.SonNum = 0 And p.Deleted = 0 AND p.TypeID <> ''00000''
					' + case when @bill_ptypeexactmatching=1 then @combineSQL1 else @combineSQL end+CASE WHEN @isservice = 0 THEN + ' AND P.isservice = 0 ' ELSE ' ' END + '
					' + CASE WHEN @existcombination=0 
							 THEN '  AND ISNULL(p.iscombinationproduct,0)=0 ' 
							 ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(P.iscombinationproduct,0)=1  AND P.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						END 
		EXEC (@tempSQL)
		
		IF (SELECT COUNT(*) FROM #one)>1
			TRUNCATE TABLE #one

		-- 系统配置是否采用价格跟踪
		DECLARE @ifUsePriceTrack int
		SET @ifUsePriceTrack = 0
		IF @chvPriceTrack = '1' OR @chvPriceTrack = '2'
		BEGIN
			IF @chvBillType IN ('11','12','34','300','301','313','6','45','46','305','140','141','142','160','161','144','145','146','187','188','184','185','215')
			BEGIN
				SET @ifUsePriceTrack = 1 
				IF @chvBillType IN ('11','12','305','313','45','46','140','141','142','160','187','215')
					SET @SalePriceTrack = 'ISNULL(b.SalePrice,0) AS SalePriceTrack'
				IF @chvBillType = '300'
					SET @SaleOrderPriceTrack = 'ISNULL(b.SaleOrderPrice,0) AS SaleOrderPriceTrack'
				IF @chvBillType = '301'
					SET @BuyOrderPriceTrack = 'ISNULL(b.BuyOrderPrice,0) AS BuyOrderPriceTrack'
				IF @chvBillType IN ('34','6','161','144','145','146','188')
					SET @BuyPriceTrack = 'ISNULL(b.CostPrice,0) AS BuyPriceTrack'
				IF @chvBillType = '185'
					SET @QueryPrice = 'ISNULL(b.QueryPrice,0) AS QueryPrice'
				IF @chvBillType = '184'
					SET @ResponsePrice = 'ISNULL(b.ResponsePrice,0) AS ResponsePrice'
					
				SET @BuyOrBackOriginalPrice = 'ISNULL(b.ResponsePrice,0) AS ResponsePrice'
				SET @BuyOrBackDiscountRate = 'ISNULL(b.ResponsePrice,0) AS ResponsePrice'
				SET @SaleOrBackOriginalPrice = 'ISNULL(b.ResponsePrice,0) AS ResponsePrice'
				SET @SaleOrBackDiscountRate = 'ISNULL(b.ResponsePrice,0) AS ResponsePrice'
				
				
			
			END
		END
		
		SET @SQL = 'SELECT	a.*,
						''' + @BtypePrice+''' AS BtypePrice,
						' + @SalePriceTrack + ',
						' + @SaleOrderPriceTrack + ',
						' + @BuyPriceTrack + ',
						' + @BuyOrderPriceTrack + ',
						' + @QueryPrice + ',
						' + @ResponsePrice + ',
						PromotePrice = 0,
						Serial = '''',
						f.unitid,
						f.unit,
						f.unitrate,
						f.nunitid,
						f.nunit,
						f.rate,
						f.buyunitname,
						f.buymunitrate,
						f.saleunitname,
						f.salemunitrate,
						f.stockunitname,
						' + CASE WHEN @UserCode <> '' THEN ''''+@UserCode+'''' 
						WHEN @FullName <> '' THEN ''''+@FullName+''''
						ELSE '''''' END + ' AS multentrycode1,
						dbo.F_GetAllEntrycode(a.typeid,a.SaleUnitId,2) AS salemunitcode,
						dbo.F_GetAllEntrycode(a.typeid,a.BuyUnitId,2) AS buymunitcode,
						dbo.F_GetAllEntrycode(a.typeid,a.StockUnitId,2) AS stockmunitcode,
						dbo.F_GetAllEntrycode(a.typeid,a.BaseUnitId,2) AS basemunitcode,
						f.stockmunitrate
					FROM ( 
						SELECT	TOP 2 p.*,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID)) as auxfullname1,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID)) as auxfullname2,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID)) as auxfullname3,
						(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID) as auxrate1,
						(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID) as auxrate2,
						(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=p.TypeID) as auxrate3,
						' + CASE WHEN @IfMultiCodeBill = 1 THEN 'u.UserCode' ELSE '''''' END + ' AS CustomerCode						
						FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
						' + CASE WHEN @IfMultiCodeBill = 1 THEN 'LEFT JOIN PUserCode u ON u.BTypeID = '''+ @chvDealBtypeID + ''' AND p.TypeID = u.PTypeID' ELSE '' END + '
						WHERE	p.SonNum = 0 AND p.Deleted = 0 AND p.TypeID <> ''00000'' '+@StopBuySql+' 
							' +CASE WHEN EXISTS(SELECT TOP 1 * FROM #one) THEN ' AND p.TypeID = '''+(SELECT typeid FROM #one)+'''' ELSE  @combineSQLwithMultiCode END + '
							' + CASE WHEN @EntryCode <> '' THEN 'AND p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @EntryCode + ''',1))' ELSE '' END + '
							' + CASE WHEN @isservice = 0 THEN + ' AND p.isservice = 0 ' ELSE ' ' END + '
							' + CASE WHEN @existcombination=0 
								THEN ' AND ISNULL(p.iscombinationproduct,0)=0 ' 
								ELSE '  AND (ISNULL(p.iscombinationproduct,0)=0 OR (ISNULL(p.iscombinationproduct,0)=1  AND p.typeid IN (SELECT combinationproductptypeid FROM CombinationProductIndex WHERE isstop=0 AND ischeck=1 ))) ' 
						   END 
					 + '
					) a 	
					LEFT JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = a.typeid
					' + CASE WHEN @ifUsePriceTrack = 1 THEN 'LEFT JOIN PriceTrack b ON b.BTypeID = ''' + @chvDenominated + 
																				''' AND b.stypeid='+CHAR(39)+@stid+CHAR(39)+
																				' AND  a.TypeID = b.PTypeID'+ 
																				' AND b.cid='+CHAR(39)+@mcid+CHAR(39) +
																	' AND b.btypeflag='+CHAR(39)+@pricetracktype+CHAR(39)+  
						CASE WHEN @unittype != '' THEN ' AND b.uid= a.'+@unittype ELSE '' END  ELSE '' END
					
								
	END	
	DROP TABLE #one
END
ELSE IF LEFT(@DBName, 6) = 'Serial'
BEGIN	
	--2008-02-19 序列号关联货位
	DECLARE @serialrelation  INT		--序列号借欠出入库校验模式
	SELECT TOP 1 @serialrelation = VALUE FROM UserConfig WHERE ConfigName = 'serialrelation'

	--2008-02-19 徐辉添加序列号可以查询%
	SET @UserCode=REPLACE(@UserCode,'%','[%]')

	--2008-02-19 徐辉添加序列号可以查询%
	DECLARE @mngLendSerial  INT		--序列号借欠出入库校验模式
	SELECT TOP 1 @mngLendSerial = VALUE FROM UserConfig WHERE ConfigName = 'mngLendSerial'

	-- 确认仓库 ID 值 ( 参数通过 @FullName 来传递 )
	-- 若先选择了商品，则确认商品 ID 值 ( 参数通过 @DBName 传递，而 @DBName 最前面是 Serial )
	DECLARE @chvKTypeID varchar(50), @chvPTypeID varchar(50)
	DECLARE @szPtypeid varchar(50) --价格跟踪序列号所对应的商品ID 徐辉 2004-10-14
	SET @szPtypeid  = ''
	SET @chvKTypeID = ''
	SET @chvPTypeID = ''

	-- 非委托、受托代销结算
	IF @FullName <> 'CommissionWTJS' AND @FullName <> 'CommissionSTJS' AND  @FullName <> 'CommissionSTTH'
	BEGIN
		SELECT	TOP 1 @chvKTypeID = TypeID
		FROM	Stock
		WHERE	UserCode = @FullName
			OR FullName = @FullName
	END

	IF @FullName = 'CommissionSTTH'
	BEGIN
		SELECT	TOP 1 @chvKTypeID = TypeID
		FROM	Stock
		WHERE	UserCode = @chvKTypeName
			OR FullName = @chvKTypeName
	END

	IF RIGHT(@DBName, LEN(@DBName) - 6) <> ''
	BEGIN
		SELECT	TOP 1 @chvPTypeID = TypeID
		FROM	PType
		WHERE	UserCode = RIGHT(@DBName, LEN(@DBName) - 6)
	END

	IF @chvBillType='16'	-- 拆装出库
	BEGIN
		-- 判断系统的成本算法；0：移动加权平均；1：先进先出；2：后进先出；3：手工指定法
		SELECT TOP 1 @strCosting = SubValue FROM SysData WHERE SubName = 'costing'

		SET @SQL = '
	SELECT a.*,
       (select fullname from stock where typeid=a.Ktypeid ) as kfullname,
		b.*,
		
		'''' AS CustomerCode,
	    f.unitid,
		f.unit,
		f.unitrate,
		f.nunitid,
		f.nunit,
		f.rate,
		f.buyunitname,
		f.buymunitrate,
		f.saleunitname,
		f.salemunitrate,
		f.stockunitname,
		f.stockmunitrate,
		(dbo.F_GetAllEntrycode(b.TypeID,b.SaleUnitId,2)) AS salemunitcode,
		(dbo.F_GetAllEntrycode(b.TypeID,b.BuyUnitId,2)) AS buymunitcode,
		(dbo.F_GetAllEntrycode(b.TypeID,b.StockUnitId,2)) AS stockmunitcode,
		dbo.F_GetAllEntrycode(b.typeid,b.BaseUnitId,2) AS basemunitcode,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname1,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname2,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname3,
		(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate1,
		(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate2,
		(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate3
	FROM (
		SELECT TOP 2 a.Serial,
			a.PTypeID,
		    a.Ktypeid,
			CASE WHEN a.Serial = ''' + @UserCode + ''' THEN 0 ELSE 1 END AS ShowOrder,
			itemid=a.ItemId,
			itemname= CASE WHEN a.IsCombined = 0  THEN
			(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
			iscombined=a.IsCombined,
			CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
			CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
			a.ProduceDate,
			a.ValidDate,
			a.goodsnumber as goodsnumber ,
			a.costprice
		FROM	GP_CruPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.State IN (1,7)
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.Serial LIKE ''%' + @UserCode + '%'''
			
	-- 子查询增加商品筛选，避免TOP时，取出不相干的数据，导致后面INNER JOIN不到
	IF RIGHT(@DBName, LEN(@DBName) - 6) <> ''
	BEGIN
		SET @SQL = @SQL + '
		AND a.PTypeID = ''' + @chvPTypeID + ''''
	END	
	SET @SQL = @SQL + '
		ORDER BY ShowOrder
	) a INNER JOIN PType b ON a.PTypeID = b.TypeID  and b.deleted=0
	LEFT JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = a.Ptypeid
	' + CASE WHEN @strCosting = '3' THEN '' ELSE 'LEFT JOIN (
		SELECT	g.PTypeID,
			CostPrice = SUM(g.Total) / CASE WHEN SUM(g.QTY) = 0 THEN NULL ELSE SUM(g.QTY) END
		FROM	GoodsStocks g, Stock s
		WHERE	g.KTypeID = s.TypeID
			AND (s.FullName = ''' + @chvKTypeName + ''' OR s.UserCode = ''' + @chvKTypeName + ''')
		GROUP BY g.PTypeID
	) g ON g.PTypeID = a.PTypeID
    '
	END
	
	SET @SQL=@SQL+' where 1=1 '
	--9.6新加 参数判断
	IF @chvitemid <> ''
	SET @SQL = @SQL + '
		AND a.ItemID = ''' + @chvitemid + ''''

	IF @chvcargoid <> ''
	SET @SQL = @SQL + '
		AND a.CargoID = ''' + @chvcargoid + ''''
		
	IF @chviscombined <> ''
	SET @SQL = @SQL + '
		AND a.IsCombined = ''' + @chviscombined + ''''
		
	IF @chvproducedate <> ''
	SET @SQL = @SQL + '
		AND a.ProduceDate = ''' + @chvproducedate + ''''
		
	IF @chvvaliddate <> ''
	SET @SQL = @SQL + '
		AND a.ValidDate  = ''' + @chvvaliddate + ''''

	IF @chvgoodsnumber <> ''
	SET @SQL = @SQL + '
		AND a.goodsnumber  = ''' + @chvgoodsnumber + ''''
		
	IF @chvcostprice <> ''
    SET @SQL = @SQL + '
	AND a.costprice  = ''' + @chvcostprice + ''''
	
	END
	ELSE
	BEGIN
		SET @chvBTypeTrackID = ''
		IF @BTypeTrack <> ''
		BEGIN
			SELECT	TOP 1 @chvBTypeTrackID = TypeID
			FROM	BType
			WHERE	UserCode = @BTypeTrack
				OR FullName = @BTypeTrack
		END

		SELECT	TOP 1 @BtypePrice = ISNULL(Price,'')
		FROM	BType 
		WHERE	FullName = @BTypeTrack
		IF @BtypePrice IS NULL SET @BtypePrice = ''

		SELECT	TOP 1 @chvPriceTrack = Value
		FROM	UserConfig
		WHERE	ConfigName = 'PriceTrack'

		--系统采用多编码
		SET @IfMultiCodeBill = 0
		IF @MultiCode = '1' AND @chvBillType IN ('305','11','6','160','140','141','142','143','144','145','146','147','34','45','161','201','202','215')
			SET @IfMultiCodeBill = 1
		
		-- 系统配置是否采用价格跟踪
		SET @ifUsePriceTrack = 0
		IF @chvPriceTrack = '1' OR @chvPriceTrack = '2'
		BEGIN
			IF @chvBillType IN ('11','34','6','45','305','140','141','142','160','161','145','146')
			BEGIN
				SET @ifUsePriceTrack = 1
				IF @chvBillType IN ('11','305','45','140','141','142','160')
					SET @SalePriceTrack = 'ISNULL(b.SalePrice,0) AS SalePriceTrack'
				IF @chvBillType IN ('34','6','161','145','146')
					SET @BuyPriceTrack = 'ISNULL(b.CostPrice,0) AS BuyPriceTrack'
			END
		END
		
		SET @SQL = '
	SELECT TOP 2 a.*,
	    
		(select fullname from stock where typeid=a.Ktypeid ) as kfullname,
		p.*,
		''' + @BtypePrice+''' AS BtypePrice,
		' + ISNULL(@SalePriceTrack,'0') + ',
		' + ISNULL(@BuyPriceTrack,'0') + ',
		PromotePrice = 0,
		f.unitid,
		f.unit,
		f.unitrate,
		f.nunitid,
		f.nunit,
		f.rate,
		f.buyunitname,
		f.buymunitrate,
		f.saleunitname,
		f.salemunitrate,
		f.stockunitname,
		f.stockmunitrate,
		(dbo.F_GetAllEntrycode(p.TypeID,p.SaleUnitId,2)) AS salemunitcode,
		(dbo.F_GetAllEntrycode(p.TypeID,p.BuyUnitId,2)) AS buymunitcode,
		dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2) AS basemunitcode,
		(' + CASE WHEN @IfMultiCodeBill = 1 THEN 'SELECT TOP 1 UserCode FROM PUserCode WHERE PTypeID=a.PTypeID AND BTypeID='''+ @chvBTypeTrackID + '''' ELSE '''''' END + ') AS CustomerCode
	FROM (
		SELECT	TOP 100 PERCENT  a.Serial,
			a.PTypeID,
			a.Ktypeid,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname1,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname2,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID)) as auxfullname3,
			(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate1,
			(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate2,
			(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.PTypeID) as auxrate3,
			CASE WHEN a.Serial = ''' + @UserCode + ''' THEN 0 ELSE 1 END AS ShowOrder'
			
			IF @chvBillType = '87'
			SET @SQL = @SQL + '
			,a.ItemId
			,a.itemname
			,a.iscombined
			,a.CargoID
			,a.cargofullname
			,a.ProduceDate
			,a.ValidDate
			,a.costprice
			,a.goodsnumber
			'
        
		IF @chvBillType = '72'	-- 借进还出 Roamer Wu 2004-03-02 加入借欠返回的控制
			SET @SQL = @SQL + '
		    ,itemid=a.ItemId,
			itemname= CASE WHEN a.IsCombined = 0  THEN
			(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
			iscombined=a.IsCombined,
			
			CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
			CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
			a.ProduceDate,
			a.ValidDate,
			a.goodsnumber ,
			null as costprice
		FROM	GP_LendPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.Serial LIKE ''%' + @UserCode + '%''
			AND a.BTypeID2 = ''' + CASE WHEN @chvDealBtypeID IS NOT NULL AND LEN(@chvDealBtypeID)>0 THEN @chvDealBtypeID ELSE @chvBTypeTrackID END + '''
			AND a.State IN (17,20)
			AND a.Flag = 1
			AND a.BFlag = 1'
		ELSE IF @chvBillType = '88'	-- 借出还回
			SET @SQL = @SQL + '
		    ,itemid=a.ItemId,
			itemname= CASE WHEN a.IsCombined = 0  THEN
			(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
			iscombined=a.IsCombined,
			
			a.CargoID,
			a.ProduceDate,
			a.ValidDate,
			ct.fullname AS cargofullname,
			 a.goodsnumber,
			 null as costprice
		FROM	GP_LendPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.Serial LIKE ''%' + @UserCode + '%''
			AND a.State = 18
			AND a.BTypeID1 = ''' + CASE WHEN @chvDealBtypeID IS NOT NULL AND LEN(@chvDealBtypeID)>0 THEN @chvDealBtypeID ELSE @chvBTypeTrackID END + '''
			AND a.Flag = 0'
		ELSE IF @chvBillType = '87'	-- 借出开单
		BEGIN
			SET @SQL = @SQL + '
		FROM (
			SELECT	a.Serial,
				a.PTypeID,
				a.KTypeID,
				itemid=a.ItemId,
				itemname= CASE WHEN a.IsCombined = 0  THEN
				(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
				iscombined=a.IsCombined,
				CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
			    CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
				a.ProduceDate,
				a.ValidDate,
				a.goodsnumber as goodsnumber,
				a.costprice
			FROM	GP_CruPTypeSerial a
			LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
			WHERE	a.Serial LIKE ''%' + @UserCode + '%''
				AND a.State IN (1,7)
				AND a.KTypeID = ''' + @chvKTypeID + '''
				--v5.0  徐辉，借出的不能再借了
				AND a.Serial NOT IN (SELECT Serial FROM GP_LendPTypeSerial WHERE Flag = 0 AND State = 18)
		) a
		WHERE	a.Serial LIKE ''%' + @UserCode + '%'''
		END
		ELSE IF @chvBillType IN ('419','420')	-- 实物库存
			BEGIN
			  SET  @SQL = @SQL + ' 
			    ,XFullName,GFullName,
				itemid,itemname,
				iscombined,
				a.cargoid,
				producedate,
				validdate,cargofullname,goodsnumber,costprice  from (select 
			a.Serial,
				a.PTypeID,
				a.KTypeID,
				(SELECT FullName FROM stock WHERE SonNum=0 AND TypeID = A.Ktypeid) as Kfullname,
				(select BuyDefaultRate from ptype where typeid=a.PTypeID) as BuyDefaultRate,
				(select SaleDefaultRate from ptype where typeid=a.PTypeID) as SaleDefaultRate,
				a.InKtypeTime,
				a.OutKtypeTime,
				null as Note,
				a.State,
				null as BTypeID1,
				null as  BTypeID2,
				null as XFullName,
				null as GFullName,
				itemid,
				itemname =  CASE WHEN a.IsCombined = 0  THEN
					(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId )  END,
				iscombined,
				a.cargoid,
				producedate,
				validdate,
				ct.fullname AS cargofullname,
				goodsnumber,
				null as costprice,a.Flag
				 from dbo.gp_FactPtypeSerial a
				 LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
			     WHERE a.Serial LIKE ''%' + @UserCode + '%'' 
			) a'
			END
		ELSE
		BEGIN
			SET @SQL = @SQL + '
			   ,itemid=a.ItemId,
				itemname= CASE WHEN a.IsCombined = 0  THEN
				(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
				iscombined=a.IsCombined,
				CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
			    CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
				a.ProduceDate,
				a.ValidDate,
				a.goodsnumber as goodsnumber,
				a.costprice
		FROM	GP_CruPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.Serial LIKE ''%' + @UserCode + '%'''
			
			IF @chvBillType = '413' 
			BEGIN
				SET @SQL = @SQL+'AND a.State IN (2,3,9,11,13,14,15,30,21,31)'
			END
			ELSE IF @chvBillType = '412' 
			BEGIN
				SET @SQL = @SQL+'AND a.State IN (1,7,40)'
			END
			ELSE IF @chvBillType = '45' OR @chvBillType = '215' OR @chvBillType = '403' OR (@chvBillType = '160' AND @GridID = 2)	-- 销售退货单
			BEGIN
					SET @SQL = @SQL + '
				AND a.State IN (2,9,14,21)'	-- 销售退货单只查询已销售序列号,受托代销已销售 徐辉2005-01-15
				
				IF @chvBillType = '215'
				SET @SQL = @SQL + '
				AND a.Serial IN (SELECT Serial FROM gp_inoutPtypeSerial WHERE (BillType=11 OR BillType=402 OR BillType=305) and ptypeid=a.PTypeID and ifcheck=''t'' 
				and BTypeID1=a.BTypeID1)'
				
				--销售退货单也要看到销售换货单出库的序列号
				IF @chvBillType = '160' OR @chvBillType = '45'
				SET @SQL = @SQL + '
				AND a.Serial IN (SELECT Serial FROM gp_inoutPtypeSerial WHERE (BillType=160 OR BillType=305 OR BillType=402 OR BillType=11) and ptypeid=a.PTypeID and ifcheck=''t'' 
				and BTypeID1=a.BTypeID1)'
			
			END
			ElSE IF @chvBillType = '6' OR  @chvBillType = 401		-- 采购退货不能选受托代销入库的商品
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 1 AND a.Flag = 1'
			ELSE IF @chvBillType = '166' OR @chvBillType = '168' OR @chvBillType = '172'	-- 维修单、整机更换单、上门维修单
			BEGIN
				IF @wxproperty = 0	-- 正常商品
					SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 1 AND a.Flag = 1'
				ELSE	-- 维修品
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 25 AND a.Flag = 1'
			END
			ELSE IF @chvBillType = '167' OR @chvBillType = '169'	-- 维修取件单、送修单
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 25
			AND a.Flag = 1'
			ELSE IF @chvBillType = '170'	-- 送修返回单
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 29 AND a.Flag = 0'
			ELSE if  @chvBillType = '202'  --其他出库单
			SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State =1  AND a.Flag = 1'
			ELSE IF @chvBillType = '175' OR @chvBillType = '174'	-- 维修品调拨单、维修品调出单
			BEGIN
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 25 AND a.Flag = 1'
			END
			ELSE IF @chvBillType = '173'	-- 维修品调入单
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 1 AND a.Flag = 1'
			ELSE IF @chvBillType='187' --OR @chvBillType='140' --分支机构调拨出库单
			BEGIN
				SET @SQL = @SQL + '
					AND a.KTypeID = ''' + @chvKTypeID + '''
					AND	a.State = 1
					AND a.Flag = 1'
			END
			ELSE IF @chvBillType = '9'	-- 报损单（报损维维修品）
			BEGIN
				IF @wxproperty = 0	-- 正常商品
					SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State IN (1,7)
			AND a.Flag = 1'
				ELSE	-- 维修品
					SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State = 25 AND a.Flag = 1'
			END						
			ElSE IF @chvBillType <> '45' AND @chvBillType <> '6' AND @chvBillType <> '142' AND @FullName <> 'CommissionWTJS' AND @FullName <> 'CommissionSTJS' AND @FullName <> 'CommissionSTTH' AND @FullName <> 'CommissionWTTH'
				SET @SQL = @SQL + '
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State IN (1,7,40) AND a.Flag = 1'
			ELSE IF @FullName = 'CommissionWTJS' OR @FullName = 'CommissionWTTH' OR @chvBillType = '142'
				SET @SQL = @SQL + '
			AND a.BTypeID1 = ''' + @chvBTypeTrackID + '''
			AND (a.Ktypeid IN (SELECT TypeId FROM Stock WHERE stypeid=''' + @stid + ''') OR (a.ktypeid=''10000'' AND  stypeid='''+@stid +'''))
			AND a.State IN (13,32)'
			ELSE IF @FullName = 'CommissionSTJS'
				SET @SQL = @SQL + '
			AND a.BTypeID2 = ''' + @chvBTypeTrackID + '''
			AND a.State IN (7,9,10,11,13,14,16,22,23,31,32)
			AND (a.Ktypeid IN (SELECT TypeId FROM Stock WHERE stypeid=''' + @stid + ''') OR (a.ktypeid=''10000'' AND  stypeid='''+@stid+''') )
			AND a.CommissionState = 0'
			ELSE IF @FullName = 'CommissionSTTH'
				SET @SQL = @SQL + '
			AND a.BTypeID2 = ''' + @chvBTypeTrackID + '''
			AND a.KTypeID = ''' + @chvKTypeID + '''
			AND a.State IN (7) '
		END
		
		SET @SQL = @SQL + '
		ORDER BY ShowOrder
	) a INNER JOIN PType p ON a.PTypeID = p.TypeID  and p.deleted=0
	LEFT JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = a.Ptypeid
	' + CASE WHEN @ifUsePriceTrack = 1 THEN 
	'LEFT JOIN PriceTrack b ON b.BTypeID = ''' + @chvDenominated + ''' AND a.PTypeID = b.PTypeID 
	AND b.stypeid='''+@stid+''''+ ' AND b.cid='+CHAR(39)+@mcid+CHAR(39)+ ' 
	AND b.btypeflag='+CHAR(39)+@pricetracktype+CHAR(39)+ CASE WHEN @unittype != '' THEN ' 
	AND b.uid= p.'+@unittype ELSE '' END ELSE '' END+'
	LEFT JOIN gp_LendPtypeSerial LPS ON a.Serial=LPS.Serial 
	WHERE	1=1 '
	END

	-- 商品编号不为空
	IF RIGHT(@DBName, LEN(@DBName) - 6) <> ''
		SET @SQL = @SQL + '
		AND a.PTypeID = ''' + @chvPTypeID + ''''
	
    IF LEFT(@DBName, 6) = 'Serial'
    BEGIN
		--9.6新加 参数判断
		IF @chvitemid <> ''
		SET @SQL = @SQL + '
			AND a.ItemID = ''' + @chvitemid + ''''

		IF @chvcargoid <> ''
		SET @SQL = @SQL + '
			AND a.CargoID = ''' + @chvcargoid + ''''
			
		IF @chviscombined <> ''
		SET @SQL = @SQL + '
			AND a.IsCombined = ''' + @chviscombined + ''''
			
		IF @chvproducedate <> ''
		SET @SQL = @SQL + '
			AND a.ProduceDate = ''' + @chvproducedate + ''''
			
		IF @chvvaliddate <> ''
		SET @SQL = @SQL + '
			AND a.ValidDate  = ''' + @chvvaliddate + ''''

		IF @chvgoodsnumber <> ''
		SET @SQL = @SQL + '
			AND a.goodsnumber  = ''' + @chvgoodsnumber + ''''
		
		IF @chvcostprice <> ''
        SET @SQL = @SQL + '
	        AND a.costprice  = ''' + @chvcostprice + ''''
		
        --是否勾选借出转销售
        IF @chvBillType = 11
        BEGIN
		    IF @chvlendtosale = 1
            BEGIN
                SET @SQL = @SQL + '
	                AND LPS.State = 18
	                AND LPS.BTypeID1 = ''' + CASE WHEN @chvDealBtypeID IS NOT NULL AND LEN(@chvDealBtypeID)>0 THEN @chvDealBtypeID ELSE @chvBTypeTrackID END + ''''
            END
            ELSE
            BEGIN
                SET @SQL = @SQL + '
	                AND ISNULL(LPS.State,-1) <> ''18'''
            END
        END
	END

    --盘点单306,可选借出库存中序列号
	IF @mngLendSerial = 1 AND @chvBillType NOT IN (71,72,87,88,203,306) AND @chvlendtosale = 0	-- 序列号借欠出入库校验模式
		SET @SQL = @SQL + '
		AND a.Serial NOT IN (SELECT Serial FROM GP_LendPTypeSerial WHERE Flag = 0 AND State = 18)'
END
ELSE


BEGIN
	IF @chvBillType='159'									--业务凭证
	BEGIN
		DECLARE @proinfo INT --A8=2  V3=1
		SELECT @proinfo = SubValue FROM sysdata WHERE SubName = 'proinfo'
		
		SET @SQL = '
			SELECT a.* FROM (
				SELECT	TOP 100 PERCENT
					'''' AS typeATypeID,
					CASE i.TypeName
						WHEN ''C'' THEN ''【资产】''
						WHEN ''F'' THEN ''【固定资产】''
						WHEN ''L'' THEN ''【负债合计】''
						WHEN ''G'' THEN ''【收入类】''
						WHEN ''B'' THEN ''【银行账户】''
						WHEN ''E'' THEN ''【费用类型】''
						WHEN ''A'' THEN ''【 所有者权益】''
					END AS typeFullName,
					null as typeusercode,
					i.nId, '''' as TypeId, '''' as ParId,i.Leveal,i.SonNum,i.SonCount,i.UserCode,i.FullName,i.Name,i.CreateBank,i.BankType,i.IsBank,i.Comment,i.PyCode,i.Deleted,i.TypeName,i.XiWaMaxNumber,i.Sysrow,i.IsModify
					,i.ntypeid
				FROM Ac_Items i
				INNER JOIN F_GetCredenceATypeAll('''+ @chvOperatorID+''') f ON f.nid = i.nId
				WHERE	i.Deleted = 0 AND i.SonNum = 0
					AND i.nId NOT IN (''30'',''31'',''37'',''34'')
					' + CASE WHEN @UserCode <> '' THEN 'AND (i.UserCode LIKE ''%' + @UserCode + '%'' OR i.PYCode LIKE ''%' + @UserCode + '%'')' ELSE '' END + '
					' + CASE WHEN @FullName <> '' THEN 'AND (i.FullName LIKE ''%' + @FullName + '%''
						OR i.PyCode LIKE ''%' + @FullName + '%'')' ELSE '' END + '
					AND ( (i.nTypeID LIKE ''0000100003%''  and i.nid in (select nid from F_AllTreeA ('''+ @chvOperatorID+''')  )) or i.nTypeID NOT LIKE ''0000100003%'') 
					AND i.UserCode NOT IN (''1251'',''2122'') '
		IF @proinfo = 1
			SET @SQL += ' AND i.nid <> ''28'' '
		
		IF EXISTS(select top 1 1 from sysdata where SubName = 'assets' and SubValue = 1) --是否启用资产卡片
			SET @SQL += ' AND i.TypeName <> ''F'' '
		
		SET @SQL += ' ) a '	
				
	END
	ELSE IF @chvBillType = '16'
	BEGIN
		SET @SQL = '
	SELECT	p.*,
		
		CostPrice = CASE WHEN g.Price IS NULL THEN CAST(p.RecPrice AS  NUMERIC(24, 10) ) ELSE CAST(g.Price AS  NUMERIC(24, 10) ) END
	FROM (
		SELECT	TOP 2 p.FullName,
			p.UserCode,
			
			CostPrice = CASE WHEN g.Price IS NULL THEN CAST(p.RecPrice AS  NUMERIC(24, 10) ) ELSE CAST(g.Price AS  NUMERIC(24, 10) ) END,
			' + CASE WHEN @UserCode <> '' THEN 'CASE WHEN (p.UserCode = ''' + @UserCode + ''' OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(''' + @UserCode + ''',1)) OR p.PyCode = ''' + @UserCode + ''')' ELSE '' END + '
			' + CASE WHEN @FullName <> '' THEN 'CASE WHEN (p.FullName = ''' + @FullName + ''' OR p.Pycode = ''' + @FullName + ''' OR p.Standard = ''' + @FullName + ''')' ELSE '' END + '
			THEN 0 ELSE 1 END AS ShowOrder
		FROM	PType p' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') c ON p.TypeID = c.TypeID' ELSE '' END + '
		WHERE	p.SonNum = 0 And p.Deleted = 0 AND p.TypeID <> ''00000''
		' + @combineSQL +'
		ORDER BY ShowOrder
	) p
	LEFT JOIN (
		SELECT	g.PTypeID,
			g.Price
		FROM	GoodsStocks g, Stock s
		WHERE	g.KTypeID = s.TypeID AND (s.FullName = ''%' + @chvKTypeName + ''' OR s.UserCode = ''' + @chvKTypeName + ''')
	) g ON p.TypeID = g.PTypeID'
	END
	ELSE IF @DBName = 'Ac_Items'
	BEGIN
		DECLARE @manFunc varchar(1000), @whereSQL varchar(1000), @ifAllAType int
		SET @ifAllAType = 0
		IF @chvBillType = '93'
		BEGIN
			IF @chvMIncome = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN F_GetManDetailAtypeSr(''' + @OperatorID + ''') b ON a.nid = b.nid'
			SET @whereSQL = ' AND a.nTypeID LIKE ''0000300003%'' AND A.SonNum = 0 '
		END
		ELSE IF @chvBillType IN ('10','36','158')
		BEGIN
			IF @chvMExpense = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN F_GetManDetailAtypeFy(''' + @OperatorID + ''') b ON a.nid = b.nid'
			SET @whereSQL = ' AND a.nTypeID LIKE ''0000400003%'' AND A.SonNum = 0'
		END
		ELSE IF @chvBillType IN ('4')
		BEGIN
			DECLARE @AddCID	INT = 0
			IF EXISTS (SELECT * FROM ac_currency where Sysrow=1 AND CId = @cid)
			SET @AddCID = 1
			IF @chvMATypeID = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN (SELECT nid FROM F_LineA(''' + @OperatorID + ''') 
							 Union SELECT nid FROM Ac_Items WHERE nid IN(''27'',''39'',''34''))  b ON a.nid = b.nid'
			SET @whereSQL = ' AND (a.nTypeID LIKE ''0000100003%'' OR a.isBank = ''1'' OR a.nid = ''39'' OR a.nid=''34'' AND '+@cid+' = 1 ) AND A.SonNum = 0'
		END
			ELSE IF @chvBillType IN ('189')
		BEGIN
			IF @chvMATypeID = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN (SELECT nid FROM F_LineA(''' + @OperatorID + '''))  b ON a.nid = b.nid'
			SET @whereSQL = ' AND (a.nTypeID LIKE ''0000100003%'' OR a.isBank = 1 ) AND A.SonNum = 0'
		END
		ELSE IF @chvBillType IN ('66')
		BEGIN
			IF @chvMATypeID = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN (SELECT nid FROM F_LineA(''' + @OperatorID + ''') 
							 Union SELECT nid FROM Ac_Items WHERE nid IN(''27'',''39''))  b ON a.nid = b.nid'
			SET @whereSQL = ' AND (a.nTypeID LIKE ''0000100003%'' OR a.isBank = 1 OR a.nid = ''27'' ) AND A.SonNum = 0'
		END
		ELSE IF @chvBillType IN ('5')
		BEGIN
			IF @chvMATypeID = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN F_LineA(''' + @OperatorID + ''')  b ON a.nid = b.nid'
			SET @whereSQL = ' AND (a.nTypeID LIKE ''0000100003%'' OR a.isBank = 1) AND A.SonNum = 0'
		END
		ELSE IF @chvBillType IN ( '77')	--转款单
		BEGIN
			SET @ifAllAType = 1
			--IF @chvMATypeID = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN F_LineA(''' + @OperatorID + ''') b ON a.nid = b.nid'
			--SET @whereSQL = ''
			SET @whereSQL = ' AND (a.nTypeID LIKE ''0000100003%'' OR a.isBank = 1) AND A.SonNum = 0'
			DECLARE @chvChgMoneyALimit int --系统配置“转款单中，银行账户权限有效”
			SET @chvChgMoneyALimit = 0
			SELECT TOP 1 @chvChgMoneyALimit = Value FROM UserConfig WHERE ConfigName = 'ChgMoneyALimit' 
			IF @chvChgMoneyALimit = 1 and  @chvMATypeID <> '0000'
			BEGIN
				SET @ifAllAType = 0
			END
		END
		ELSE IF @chvBillType IN ('189','190')--预收付款单
		BEGIN
			IF @chvMATypeID = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN F_LineA(''' + @OperatorID + ''') b ON a.nid = b.nid'
			SET @whereSQL = ' AND (a.nTypeID LIKE ''0000100003%'' OR a.isBank = 1) AND A.SonNum = 0'
		END
		ELSE IF @chvBillType IN ('78','84','85','212')
		BEGIN
			IF @chvMCapital = '0000' SET @ifAllAType = 1
			SET @manFunc = ' INNER JOIN F_GetManDetailAtypeZc(''' + @OperatorID + ''') b ON a.nid = b.nid'
			SET @whereSQL = ' AND a.nTypeID LIKE ''0000100002%'' '
		END
		--select @ifAllAType
		SET @SQL = '
	SELECT	TOP 2 a.*,
		' + CASE WHEN @UserCode <> '' THEN 'CASE WHEN a.UserCode = ''' + @UserCode + '''' ELSE '' END + '
		' + CASE WHEN @FullName <> '' THEN 'CASE WHEN a.FullName = ''' + @FullName + '''' ELSE '' END + '
		THEN 0 ELSE 1 END AS ShowOrder
	FROM	Ac_Items a' + CASE WHEN @ifAllAType = 0 THEN @manFunc ELSE '' END + '
	WHERE	a.Deleted = 0 AND a.SonNum = 0 ' + @whereSQL + '
		' + CASE WHEN @UserCode <> '' THEN 'AND (a.UserCode LIKE ''%' + @UserCode + '%''
						OR a.PyCode LIKE ''%' + @UserCode + '%'')' ELSE '' END + '
		' + CASE WHEN @FullName <> '' THEN 'AND (a.FullName LIKE ''%' + @FullName + '%''
						OR a.PyCode LIKE ''%' + @FullName + '%'')' ELSE '' END + '
		ORDER BY ShowOrder'
	END
	ELSE IF @DBName = 'btype'
	BEGIN
		DECLARE @BTypeAll int
		SELECT TOP 1 @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BtypeAll'

		SET @SQL = '
	SELECT	TOP 2 a.*,
		' + CASE WHEN @UserCode <> '' THEN 'CASE WHEN( a.UserCode = ''' + @UserCode + ''' OR a.PyCode = ''' + @UserCode + ''')' ELSE '' END + '
		' + CASE WHEN @FullName <> '' THEN 'CASE WHEN( a.FullName = ''' + @FullName + ''' OR a.PyCode = ''' + @FullName + ''')' ELSE '' END + '
		THEN 0 ELSE 1 END AS ShowOrder
	FROM	BType a' + CASE WHEN @BTypeAll <> '1' THEN ' INNER JOIN F_GetManDetailBtype(''' + @OperatorID + ''') c ON a.TypeID = c.TypeID' ELSE '' END + '
	WHERE	a.SonNum = 0 AND a.Deleted = 0 AND a.TypeID <> ''00001''
		' + CASE WHEN @UserCode <> '' THEN 'AND (a.UserCode LIKE ''%' + @UserCode + '%''
						OR a.PyCode LIKE ''%' + @UserCode + '%'')' ELSE '' END + '
		' + CASE WHEN @FullName <> '' THEN 'AND (a.FullName LIKE ''%' + @FullName + '%''
						OR a.PyCode LIKE ''%' + @FullName + '%''
						OR a.UserCode LIKE ''%' + @FullName + '%'')' ELSE '' END + '
		' + CASE WHEN @BTypeAll <> '1' AND @chvBillType IN ('115','116') THEN 'AND a.TypeID LIKE ''00001%'''
			WHEN @BTypeAll <> '1' AND @chvBillType IN ('128','129','204') THEN 'AND a.TypeID LIKE ''00002%''' ELSE '' END  + '
		ORDER BY ShowOrder'
	END
END
IF @chvBillType = '203'	 AND @DBName='serial'	-- 序列号调整单
			SET @SQL =
			 '
			   SELECT	a.*,
		p.*,
		''' + @BtypePrice+''' AS BtypePrice,
		' + @SalePriceTrack + ',
		' + @BuyPriceTrack + ',
		PromotePrice = 0,
		(' + CASE WHEN @IfMultiCodeBill = 1 THEN 'SELECT TOP 1 UserCode FROM PUserCode WHERE PTypeID=a.PTypeID AND BTypeID='''+ @chvBTypeTrackID + '''' ELSE '''''' END + ') AS CustomerCode
	FROM (
		SELECT	TOP 2 a.Serial,
				a.PTypeID,
				(SELECT FullName FROM BType WHERE SonNum=0 AND TypeID = a.BTypeID1) as XFullName, 
				a.BTypeID1,
				a.BTypeID2,
				(SELECT FullName FROM BType WHERE SonNum=0 AND TypeID = a.BTypeID2) as GFullName,
				a.InKtypeTime,
				a.OutKtypeTime,
				a.State,
				a.State AS nstate,
				a.KtypeID,
				a.CargoID,
				ct.fullname as cargofullname
				,(SELECT fullname FROM Stock WHERE typeid = a.KtypeID) AS kfullname,
				CASE WHEN a.Serial = ''' + @UserCode + ''' THEN 0 ELSE 1 END AS ShowOrder
		FROM	GP_CruPTypeSerial a' + CASE WHEN @chvMPTypeID <> '00000' THEN ' INNER JOIN F_GetManDetailPtype(''' + @OperatorID + ''') b ON a.PTypeID = b.TypeID' ELSE '' END + '
				LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.Serial LIKE ''%' + @UserCode + '%''
		ORDER BY ShowOrder
		) a INNER JOIN PType p ON a.PTypeID = p.TypeID  and p.deleted=0
		' + CASE WHEN @ifUsePriceTrack = 1 THEN 'LEFT JOIN PriceTrack b ON b.BTypeID = ''' + @chvDenominated + ''' AND a.PTypeID = b.PTypeID AND b.stypeid='''+@stid+''' AND b.btypeflag='+CHAR(39)+@pricetracktype+CHAR(39)  ELSE '' END + '  --zs003：关联结算单位
		WHERE	1=1 
			 '
	 
DECLARE @cargoid1		NUMERIC(18,0)
DECLARE @cargoid1name	VARCHAR(100)
/* wg去掉 未启用多仓库时，调单进来，明细仓库可能和表头仓库不一直，所以货位的值要根据表头仓库重新取一次
IF @chvCargoID = '' OR @chvCargoID = '0' OR @chvCargoID = '-1'
	SELECT TOP 1 @cargoid1 = c.CargoID,@cargoid1name = c.FullName from STOCK k inner join CargoType c on k.typeId = c.KtypeID where c.IsDefault = 1 and k.FullName = ''+@chvKTypeName+''
ELSE
	SET @cargoid1 = @chvCargoID
*/	
if @serialrelation<>1
BEGIN
	SELECT TOP 1 @cargoid1 = c.CargoID,@cargoid1name = c.FullName from STOCK k inner join CargoType c on k.typeId = c.KtypeID where c.IsDefault = 1 and k.FullName = ''+@chvKTypeName+''
	IF (@DBName='serial' OR LEFT(@DBName, 6) = 'Serial') AND @UserCode <>'' 
	BEGIN
		SELECT TOP 1 @cargoid1 = c.CargoID,@cargoid1name = c.FullName 
		from STOCK k 
		inner join CargoType c  on k.typeId = c.KtypeID 
		INNER JOIN dbo.gp_CruPtypeSerial g ON g.CargoID = c.CargoID
		where k.FullName = ''+@chvKTypeName+'' AND g.Serial=@UserCode
		IF @cargoid1 IS NULL
				SELECT TOP 1 @cargoid1 = c.CargoID,@cargoid1name = c.FullName 
				from STOCK k 
				inner join CargoType c  on k.typeId = c.KtypeID 
				INNER JOIN dbo.gp_LendPtypeSerial g ON g.CargoID = c.CargoID
				where  k.FullName = ''+@chvKTypeName+'' AND g.Serial=@UserCode
	END
END

--PRINT @SQL
IF @cargoid1 IS NULL
SET @cargoid1 = 0
IF @cargoid1name IS NULL
SET @cargoid1name = ''
DECLARE @exSql Nvarchar(max)

IF @DBName='Ac_Items' OR @chvBillType='159'--业务凭证选项目不需要价格信息
BEGIN
	SELECT @exSQL='SELECT *'
END
--基本单位反算大单位预设价格，因为原来是*，所以覆盖
ELSE
BEGIN
    IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName='CalcMunitPrePriceByBaseWhenNone' AND Value=1)
    BEGIN
	    SELECT @exSql = 'SELECT CASE WHEN ISNULL(PP.PreSalePrice1,0)=0 THEN ISNULL(BasePrice.PreSalePrice1,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice1 END AS PreSalePrice1,
						    CASE WHEN ISNULL(PP.PreSalePrice2,0)=0 THEN ISNULL(BasePrice.PreSalePrice2,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice2 END AS PreSalePrice2,
						    CASE WHEN ISNULL(PP.PreSalePrice3,0)=0 THEN ISNULL(BasePrice.PreSalePrice3,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice3 END AS PreSalePrice3,
						    CASE WHEN ISNULL(PP.PreSalePrice4,0)=0 THEN ISNULL(BasePrice.PreSalePrice4,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice4 END AS PreSalePrice4,
						    CASE WHEN ISNULL(PP.PreSalePrice5,0)=0 THEN ISNULL(BasePrice.PreSalePrice5,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice5 END AS PreSalePrice5,
						    CASE WHEN ISNULL(PP.PreSalePrice6,0)=0 THEN ISNULL(BasePrice.PreSalePrice6,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice6 END AS PreSalePrice6,
						    CASE WHEN ISNULL(PP.PreSalePrice7,0)=0 THEN ISNULL(BasePrice.PreSalePrice7,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice7 END AS PreSalePrice7,
						    CASE WHEN ISNULL(PP.PreSalePrice8,0)=0 THEN ISNULL(BasePrice.PreSalePrice8,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice8 END AS PreSalePrice8,
						    CASE WHEN ISNULL(PP.PreSalePrice9,0)=0 THEN ISNULL(BasePrice.PreSalePrice9,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice9 END AS PreSalePrice9,
						    CASE WHEN ISNULL(PP.PreSalePrice10,0)=0 THEN ISNULL(BasePrice.PreSalePrice10,0)*ISNULL(ext.Rate,1) ELSE PP.PreSalePrice10 END AS PreSalePrice10,
						    CASE WHEN ISNULL(PP.PreBuyPrice1,0)=0 THEN ISNULL(BasePrice.PreBuyPrice1,0)*ISNULL(ext.Rate,1) ELSE PP.PreBuyPrice1 END AS PreBuyPrice1,
						    CASE WHEN ISNULL(PP.PreBuyPrice2,0)=0 THEN ISNULL(BasePrice.PreBuyPrice2,0)*ISNULL(ext.Rate,1) ELSE PP.PreBuyPrice2 END AS PreBuyPrice2,
						    CASE WHEN ISNULL(PP.PreBuyPrice3,0)=0 THEN ISNULL(BasePrice.PreBuyPrice3,0)*ISNULL(ext.Rate,1) ELSE PP.PreBuyPrice3 END AS PreBuyPrice3,
						    CASE WHEN ISNULL(PP.PreBuyPrice4,0)=0 THEN ISNULL(BasePrice.PreBuyPrice4,0)*ISNULL(ext.Rate,1) ELSE PP.PreBuyPrice4 END AS PreBuyPrice4,
						    CASE WHEN ISNULL(PP.PreBuyPrice5,0)=0 THEN ISNULL(BasePrice.PreBuyPrice5,0)*ISNULL(ext.Rate,1) ELSE PP.PreBuyPrice5 END AS PreBuyPrice5,
						    CASE WHEN ISNULL(PP.RetailPrice,0)=0 THEN ISNULL(BasePrice.RetailPrice,0)*ISNULL(ext.Rate,1) ELSE PP.RetailPrice END AS PreSalePrice11,
						    CASE WHEN ISNULL(PP.TopSalePrice,0)=0 THEN ISNULL(BasePrice.TopSalePrice,0)*ISNULL(ext.Rate,1) ELSE PP.TopSalePrice END AS PreSalePrice12,
						    CASE WHEN ISNULL(PP.LowSalePrice,0)=0 THEN ISNULL(BasePrice.LowSalePrice,0)*ISNULL(ext.Rate,1) ELSE PP.LowSalePrice END AS PreSalePrice13,
						    CASE WHEN ISNULL(PP.TopBuyPrice,0)=0 THEN ISNULL(BasePrice.TopBuyPrice,0)*ISNULL(ext.Rate,1) ELSE PP.TopBuyPrice END AS PreBuyPrice6,
						    CASE WHEN ISNULL(PP.RetailPrice,0)=0 THEN ISNULL(BasePrice.RetailPrice,0)*ISNULL(ext.Rate,1) ELSE PP.RetailPrice END AS PreBuyPrice7,
						 	T.*,Ext.*,
						 	brandarfullname = (SELECT TOP 1 FullName FROM dbo.brandar_Commodity WHERE typeid = t.brandartypeid),
						 	CPI.*
						    '
    END
    ELSE
    BEGIN
	    SELECT @exSql = 'SELECT 
								PP.PreSalePrice1  AS PreSalePrice1,
								PP.PreSalePrice2  AS PreSalePrice2,
								PP.PreSalePrice3  AS PreSalePrice3,
								PP.PreSalePrice4  AS PreSalePrice4,
								PP.PreSalePrice5  AS PreSalePrice5,
								PP.PreSalePrice6  AS PreSalePrice6,
								PP.PreSalePrice7  AS PreSalePrice7,
								PP.PreSalePrice8  AS PreSalePrice8,
								PP.PreSalePrice9  AS PreSalePrice9,
								PP.PreSalePrice10  AS PreSalePrice10,
								PP.RetailPrice  AS PreSalePrice11,
								PP.TopSalePrice  AS PreSalePrice12,
								PP.LowSalePrice  AS PreSalePrice13,
								PP.PreBuyPrice1  AS PreBuyPrice1,
								PP.PreBuyPrice2  AS PreBuyPrice2,
								PP.PreBuyPrice3  AS PreBuyPrice3,
								PP.PreBuyPrice4  AS PreBuyPrice4,
								PP.PreBuyPrice5  AS PreBuyPrice5,
								PP.TopBuyPrice  AS PreBuyPrice6,
								PP.RetailPrice  AS PreBuyPrice7,
								T.*,Ext.*,
								brandarfullname = (SELECT TOP 1 FullName FROM dbo.brandar_Commodity WHERE typeid = t.brandartypeid),
								CPI.*'
    END
END

if @serialrelation<>1 
BEGIN
SET @exSql += '
            	    ,'''+CONVERT(VARCHAR(10),@cargoid1)+''' as cargoid
					,'''+@cargoid1name+''' as cargoidname
					,'''+@cargoid1name+''' as cargofullname '
END

IF @DBName<>'Ac_Items' AND @chvBillType<>'159'--业务凭证选项目不需要价格信息
BEGIN 
	SET @exSql += '	,'''+ISNULL(CONVERT(VARCHAR(10),@PriceType),'')+''' as PriceType,'
	SET @exSql = @exSql+'
	ISNULL((SELECT TOP 1 ISNULL(RecPrice, 0) FROM ptype_stypeprice  WHERE PTypeID = T.TypeID AND stypeid='''+@stid+''' AND UnitID = T.'+CASE WHEN @unittype <> '' THEN @unittype ELSE 'baseUnitId' END+' ),0) as StypeRecPrice,
	ISNULL((SELECT TOP 1 ISNULL(RecSalePrice, 0) FROM ptype_stypeprice  WHERE PTypeID = T.TypeID AND stypeid='''+@stid+''' AND UnitID = T.'+CASE WHEN @unittype <> '' THEN @unittype ELSE 'baseUnitId' END+'),0) as StypeRecSalePrice,
	ISNULL((SELECT TOP 1 ISNULL(recamgstypebuyprice, 0) FROM ptype_price  WHERE PTypeID = T.TypeID  AND UnitID = T.'+CASE WHEN @unittype <> '' THEN @unittype ELSE 'baseUnitId' END+'),0) as amgrecstypebuyprice,
	ISNULL((SELECT TOP 1 ISNULL(recamgstypesaleprice, 0) FROM ptype_price  WHERE PTypeID = T.TypeID  AND UnitID = T.'+CASE WHEN @unittype <> '' THEN @unittype ELSE 'baseUnitId' END+'),0) as amgrecstypesaleprice,
	ISNULL((SELECT ISNULL(RecAppraisalPrice, 0) FROM PType_StypePrice WHERE PTypeID = T.TypeID AND stypeid='''+ISNULL(CONVERT(VARCHAR(10),@stid),'')+''' AND UnitID = T.'+CASE WHEN @unittype <> '' THEN @unittype ELSE 'baseUnitId' END+'),0) as RecAppraisalPrice,
	ISNULL((SELECT ISNULL(RecSendPrice, 0) FROM PType_StypePrice WHERE PTypeID = T.TypeID AND stypeid='''+ISNULL(CONVERT(VARCHAR(10),@stid),'')+''' AND UnitID = T.'+CASE WHEN @unittype <> '' THEN @unittype ELSE 'baseUnitId' END+'),0) as RecSendPrice,
	(select ReferPrice from PType_Price where PTypeID=t.typeid  AND UnitID = T.baseUnitId) as ReferPrice,
	(select ReferPrice from PType_Price where PTypeID=t.typeid  AND UnitID = T.baseUnitId) as PReferPrice,
	(select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=t.typeid  and STYPEID=''' + ISNULL(CONVERT(VARCHAR(10),@stid),'') + ''' AND UnitID =T.baseUnitId) as SReferPrice,
	'
		SET @exSql = @exSql+'pt.isbtypetrack,
	pt.DiscountTrack ,			--价格跟踪扣率跟踪
	pt.DiscountPriceTrack,		--价格跟踪扣率跟踪
	pt.PriceTrack,				--价格跟踪扣率跟踪
	pt.TaxTrack,				--税率跟踪
	pt.TaxPriceTrack,			--含税单价跟踪
	pt.DiscountTrackStype,			--分支机构间价格跟踪扣率跟踪
	pt.DiscountPriceTrackStype,		--分支机构间价格跟踪扣率跟踪
	pt.PriceTrackStype, 			--分支机构间价格跟踪扣率跟踪
	pt.TaxTrackStype,				--分支机构间税率跟踪
	pt.TaxPriceTrackStype,			--分支机构间含税单价跟踪
	pt.pricetracksource,
	cpi.price as combinationprice ,
	BasePrice.retailprice AS baseretailprice,
		(select isnull(SUM(ISNULL(fa.QTY,0)),0) from FactStocks fa  where fa.PtypeId  = T.typeid  AND  fa.KTypeID LIKE ''' + @cKtypeID + '%'' AND  fa.KTypeId IN (SELECT TypeId FROM F_GetMANDetailKType('''+@OperatorID+'''))) + ( select  isnull(SUM(ISNULL(v.QTY,0)),0) from GoodsLend v where v.PTypeID like T.typeid+''%'' 
							AND v.KTypeID = ''' + @cKtypeID + ''' ) AS FactQty,	-- 实际数量= 库存量+借出/借进
	'+CASE WHEN @chvKTypeName IN('CommissionWTJS','CommissionWTTH') THEN '(SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.CostTotal,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.CommissionStock g WHERE g.PtypeId = t.TypeID AND g.Btypeid = ''' + @chvDealBtypeID + ''' AND g.Stypeid = ''' + @stid + ''' AND g.[Type] =140 ) ' ELSE ' (SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks g WHERE g.PtypeId = t.TypeID AND g.KtypeId = ''' + @cKtypeID + '''  ) ' END + ' AS showcostprice
	FROM ('+@SQL+') T '
END		
ELSE
BEGIN
	SET @exSql = @exSql+' FROM ('+@SQL+') T '
END
					
IF @DBName<>'Ac_Items' AND @chvBillType<>'159'--业务凭证选项目不需要价格信息
BEGIN 
	SELECT @exSql = @exSql+'LEFT JOIN '
	+CASE WHEN @PriceType=1 THEN ' PType_StypePrice 'ELSE ' PType_Price ' END+' pp on T.TypeID = pp.PTypeID '
	+CASE WHEN @PriceType=1 THEN ' AND pp.StypeID='''+@STID+''' 'ELSE '  ' END+
	+CASE WHEN @unittype <> ' ' THEN ' AND pp.unitid=t.'+@unittype ELSE '' END+'  '

	--基本单位预设价格信息
	SELECT @exSQL=@exSQL+' 
	LEFT JOIN  '+CASE WHEN @PriceType=1 THEN 'PType_StypePrice'ELSE 'PType_Price' END
				+' BasePrice ON t.TypeID=BasePrice.PTypeID AND BasePrice.IsDefaultUnit=1 '
				+CASE WHEN @PriceType=1 THEN ' AND BasePrice.StypeID='''+@STID+''' 'ELSE ' ' END+' 

	LEFT JOIN PType_Units_EXT EXT ON t.TypeID=EXT.PTypeID ' +CASE WHEN @unittype<>'' THEN 'AND EXT.unitsid=t.'+@unittype+' ' ELSE ' ' END
	SET @exSql = @exSql+'left join #temp_PriceTrack pt on T.typeid = pt.ptypeid '+CASE WHEN @unittype != '' THEN ' AND pt.uid= T.'+@unittype ELSE '' END+' 
	LEFT JOIN CombinationProductIndex cpi ON cpi.combinationproductptypeid=t.typeid AND cpi.isstop=0 AND cpi.ischeck=1 '
END
SET @exSQL=@exSQL+' ORDER BY T.UserCode  '

--select @exSql for xml path('')
--print @exSql
EXEC(@exSql)

DROP TABLE #temp_PriceTrack 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-03-31
	描述：手动生成会计凭证
	EXEC GP_HandCreate_Voucher 6,'00001',2
*/
CREATE PROCEDURE GP_HandCreate_Voucher
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@AtId			INT = 0,				-- 凭证模版ID
	@specifyDate	DATE = '',				-- 手工指定凭证日期
	@verifyStypeid 	VARCHAR(50)='' OUTPUT,	--返回单据上分支机构对应的独立分支机构
	@VoucherId		INT	= 0 OUTPUT,			--生成凭证后的凭证ID
	@Type			INT = 0,				-- 结果类型 0.返回错误提示 1.返回错误凭证修改 2.凭证标错，并返回提示
	@JustRep		INT = 0,				--0.中断式生成，可以抛出异常 1.非中断式生成，不抛出异常
	@szPID			VARCHAR(MAX) OUTPUT,	-- 返回出错信息
	@CreateType		INT = 1,				-- 生成来源：0.即时生成凭证 1.经营历程生成凭证
	@InOutStypeId	VARCHAR(50)='',			-- 调拨单分支机构区别（调入/调出）
	@IfCommission	INT = 0,				-- 单据类别：0：一般单据；1：提成单；2：暂估发票 3：优惠券
	@checkdeficit	INT	= 0	,				--是否检查赤字 0不检查，1检查提示，2检查不能保存
	@deficitvoucher	INT OUTPUT				--包含资金类科目的凭证，用于赤字检查；0不包含，1包含
)
--@encode$--
AS
SET NOCOUNT ON
--重置output参数
SET @verifyStypeid = ''
SET @VoucherId = 0
SET @szPID = ''
SET @deficitvoucher = 0

CREATE TABLE #Billnumberids
(
	Billnumberid	NUMERIC(18,0)
)
INSERT INTO #Billnumberids(Billnumberid)
SELECT	a FROM dbo.f_split(@BillNumberId,',')

--判断是否有凭证模版存在
DECLARE @BillType			INT,			-- 单据类型
		@billdate			DATETIME,
		@STypeid			VARCHAR(50),	-- 分支机构
		@STypeid2			VARCHAR(50),	-- 调入分支机构
		@cid				INT,			-- 单据币种
		@rate				NUMERIC(24, 10) ,	-- 单据币种汇率
		@ratetype			INT,			-- 汇率计算方式
		@btypeid			VARCHAR(50),	-- 往来，用于区分客户与供货商
		@Sql				VARCHAR(MAX)	-- 动态SQL

IF @IfCommission = 0	
	SELECT TOP 1 @BillType	= BillType,
			@stypeid	= a.Stypeid,
			@billdate   = A.BillDate,
			@STypeid2 = StypeID2
	FROM	BillIndex a
	INNER JOIN #Billnumberids B ON B.Billnumberid = A.BillNumberId
	ORDER BY A.BillDate ASC
ELSE IF @IfCommission = 1   --提成单
	SELECT TOP 1 @BillType	= 311,
			@stypeid	= a.Stypeid,
			@billdate   = A.BillDate
	FROM	dbo.CommissionBillNew a
	INNER JOIN #Billnumberids B ON B.Billnumberid = A.BillNumberId
	ORDER BY A.BillDate ASC
ELSE IF @IfCommission = 2   --暂估发票
	SELECT TOP 1 @BillType	= BillType,
			@stypeid	= a.Stypeid,
			@billdate   = A.BillDate
	FROM	dbo.ReceiptBillIndex a
	INNER JOIN #Billnumberids B ON B.Billnumberid = A.BillNumberId
	ORDER BY A.BillDate ASC	
	
ELSE IF @IfCommission = 3 	--优惠券、
	BEGIN	
		SELECT	@BillType	= BillType,
				@stypeid	= a.Stypeid,
				@billdate   = A.BillDate
		FROM	dbo.Coupon_BillIndex a
		INNER JOIN #Billnumberids B ON B.Billnumberid = A.BillNumberId
		ORDER BY BillDate ASC
	END
ELSE IF @IfCommission = 4 	--门店配送
	BEGIN	
		SELECT	@BillType	= BillType,
				@stypeid	= a.Stypeid,
				@billdate   = A.BillDate
		FROM	dbo.PosAllotApplyBillIndex a
		INNER JOIN #Billnumberids B ON B.Billnumberid = A.BillNumberId
		ORDER BY BillDate ASC
	END	
--单据不生成
IF @BillType NOT IN (11,45,160,305,139,140,142,141,34,6,161,126,144,146,145,21,187,188,201,202,9,14,16,116,115,128,129,4,189,66,190,148,
					150,149,151,36,84,85,78,158,77,93,5,10,57,205,181,183,166,167,168,170,172,159,173,174,212,213,214,215,147,310,311,312,
					400,401,402,403,404,405,450,12,46,414,423,424,426,427,428,429,327,328,329)
	RETURN 0
	
--获取此分支对应的核算分支机构
SELECT @verifyStypeid = VerifyID FROM dbo.SType WHERE TypeId = @STypeid

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE StypeId = @verifyStypeid AND IsUse = 1)
BEGIN
	SET @szPID = '当前核算分支机构还未开账，不能生成凭证';
	
	IF @CreateType = 0
		RETURN -227
	ELSE IF @JustRep = 0
		RAISERROR(@szPID,16,1)
	
	RETURN -13
END

--特殊处理：调拨单，调出调入类型
DECLARE @InOutType INT
SET @InOutType = 0

IF @BillType = 310
BEGIN
	IF ISNULL(@InOutStypeId,'') <> ''
	BEGIN		
		IF EXISTS(	SELECT TOP 1 1 
					FROM dbo.BillIndex T1
					INNER JOIN #Billnumberids T2 ON T1.BillNumberId = T2.Billnumberid
					WHERE T1.Stypeid = @InOutStypeId
						AND NOT EXISTS (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE ISNULL(InOutType,0) = -1 AND GoodsBillId = T1.BillNumberId)	
				)
		BEGIN
			SET @InOutType = -1
		END
		ELSE IF EXISTS(	SELECT TOP 1 1 
						FROM dbo.BillIndex T1
						INNER JOIN #Billnumberids T2 ON T1.BillNumberId = T2.Billnumberid
						WHERE T1.Stypeid2 = @InOutStypeId
							AND NOT EXISTS (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE ISNULL(InOutType,0) = 1 AND GoodsBillId = T1.BillNumberId)	
					)
		BEGIN
			SET @InOutType = 1
		END
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN  Ac_GoodsBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid WHERE G.InOutType = -1)
		BEGIN
			SET @InOutType = -1
			SET @InOutStypeId = @STypeid
		END 
		ELSE IF NOT EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN  Ac_GoodsBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid WHERE G.InOutType = 1)
		BEGIN
			IF EXISTS(	SELECT TOP 1 1 
						FROM dbo.BillIndex T1
						INNER JOIN #Billnumberids T2 ON T1.BillNumberId = T2.Billnumberid
						WHERE IfConfirm = 0
					)
			BEGIN			
				SET @szPID = '单据未确认入账，无法生成调入方凭证！'
				
				IF @JustRep = 0
					RAISERROR(@szPID,16,1)
				
				RETURN -15
			END
			
			SET @InOutType = 1
			SET @InOutStypeId = @STypeid2
		END
		ELSE
		BEGIN
			SET @szPID = '单据已经生成过凭证，无法再次生成！'
			
			IF @JustRep = 0
				RAISERROR(@szPID,16,1)
			
			RETURN -13
		END
	END
	
	SELECT @verifyStypeid = VerifyID FROM dbo.SType WHERE TypeId = @InOutStypeId
	
	--出纳与总账联用时，控制资金调拨单生成的凭证时，期间与总账一致
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @verifyStypeid AND IsConnect = 1)
		AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period T1 
						INNER JOIN dbo.Ac_AccountsPeroid_Stype T2 ON T1.STypeId = T2.Stypeid AND T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod)
	BEGIN
		SET @szPID = '出纳当前期间与总账期间不一致，不能生成凭证';
		
		IF @CreateType = 0
			RETURN -230
		ELSE IF @JustRep = 0
			RAISERROR(@szPID,16,1)
		
		RETURN -14
	END
END

--默认模板判断
DECLARE @billName VARCHAR(500),@stypename VARCHAR(500)
		,@AuditType	INT
SELECT @stypename = FullName FROM dbo.SType WHERE TypeId = @verifyStypeid
SELECT @billName = BillName FROM dbo.BillName WHERE Billtype = @billtype

--生成凭证
IF @AtId = 0
BEGIN
	IF @BillType IN (212,213)
	BEGIN	
		SELECT TOP 1 @AuditType = t.AuditType 
		FROM Ac_AssetBusinessType t 
		INNER JOIN dbo.BillIndex t1 ON t1.AssetBusinessTypeId = t.Id
		INNER JOIN #Billnumberids t2 ON t2.Billnumberid = t1.BillNumberId
		WHERE t.STypeId = @verifyStypeid
		
		SELECT	@AtId = t.AtId
		FROM	Ac_Auditing_Template T
		WHERE	t.BillType = @BillType
			AND t.STypeId = @verifyStypeid
			AND IsDefault = 1
			AND T.AuditType = @AuditType
	END
	ELSE IF @BillType IN (310)
	BEGIN
		SELECT	@AtId = t.AtId
		FROM	Ac_Auditing_Template T
		WHERE	t.BillType = @BillType
			AND t.STypeId = @verifyStypeid
			AND IsDefault = 1
			AND InOutType = @InOutType
	END
	ELSE IF @BillType IN (57)
	BEGIN
		SELECT TOP 1 @InOutType = B.AdPriceType
		FROM	BillIndex B
		INNER JOIN #Billnumberids T ON T.Billnumberid = B.BillNumberId
				
		SELECT	@AtId = t.AtId
		FROM	Ac_Auditing_Template T
		WHERE	t.BillType = @BillType
			AND t.STypeId = @verifyStypeid
			AND IsDefault = 1
			AND ISNULL(InOutType,0) = @InOutType
	END
	ELSE IF @BillType IN (450)
	BEGIN
		SELECT TOP 1 @InOutType = B.ChargeOffType
		FROM	BillIndex B
		INNER JOIN #Billnumberids T ON T.Billnumberid = B.BillNumberId
	
		SELECT	@AtId = t.AtId
		FROM	Ac_Auditing_Template T
		WHERE	t.BillType = @BillType
			AND t.STypeId = @verifyStypeid
			AND IsDefault = 1
			AND ChargeOffType = @InOutType
	END
	ELSE
	BEGIN		
		SELECT	@AtId = t.AtId
		FROM	Ac_Auditing_Template T
		WHERE	t.BillType = @BillType
			AND t.STypeId = @verifyStypeid
			AND IsDefault = 1
	END
END

--判断模板是否存在
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE AtId = @AtId AND STypeId = @verifyStypeid)
BEGIN		
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		SET @szPID = '分支机构['+@stypename+']'
		
	SET @szPID += ' ['+@billname+']无此凭证模板！'
	
	IF @CreateType = 0
		RETURN -220
	ELSE IF @JustRep = 0
		RAISERROR(@szPID,16,1)
		
	RETURN -13
END


IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='acsummary' AND SubValue = 1)--配置要求每行分录必有摘要时，检查模板是否符合
BEGIN
	DECLARE @countAudit INT,@countSummary INT
	SELECT @countAudit = COUNT(*) FROM dbo.Ac_Auditing_Template_Detail WHERE atid = @atid
	SELECT @countSummary = COUNT(*) FROM dbo.Ac_Auditing_Template_Detail WHERE atid = @atid AND Summary <> ''
	
	IF @countAudit > @countSummary
	BEGIN
		SET @szPID = '配置要求每条凭证分录必有摘要，模板不符规则，无法生成凭证！';
		
		IF @CreateType = 0
			RETURN -219
		ELSE IF @JustRep = 0
			RAISERROR(@szPID,16,1)
		
		RETURN -13
	END
END

--获取凭证字
DECLARE @vgid INT
SELECT @vgid = AT.VgId 
FROM dbo.Ac_Auditing_Template at
INNER JOIN Ac_Voucher_Group VG ON VG.VgId = AT.VgId
WHERE AtId = @AtId

--判断是否有凭证字
IF ISNULL(@vgid,'') = ''
BEGIN
	SET @szPID = '系统没有生成凭证所需的凭证字，无法生成凭证！';
	
	IF @CreateType = 0
		RETURN -218
	ELSE IF @JustRep = 0
		RAISERROR(@szPID,16,1)
		
	RETURN -13
END

--调整按配置来决定凭证日期
--1.按单据日期生成
--2.按系统日期生成
--3.生成时手工指定
DECLARE @datetype INT
SELECT @datetype = subvalue FROM dbo.sysdata WHERE SubName = 'voucherdatetype'

--212，213，214，始终按1来
IF @BillType IN (212,213,214)
	SET @datetype = 1

IF @datetype = 2
BEGIN
	SET @billdate = CAST( GETDATE() AS DATE)
END
ELSE IF @datetype = 3
BEGIN
	SET @billdate = @specifyDate
END
			
--取会计期间
DECLARE @fyear		INT,
		@fperiod	INT,
		@beginDate	DATETIME,
		@endYearDate	DATETIME,
		@SFbegin	DATETIME
		
--调整为获取分支机构各自的当前会计期间
SELECT @fperiod = ap.FPeriod,@fyear = ap.FYear,@beginDate = p.FBegin,@SFbegin = PS.FBegin
FROM dbo.Ac_AccountsPeroid_Stype ap
INNER JOIN Ac_Period p ON p.FYear = ap.FYear AND p.FPeriod = ap.FPeriod
INNER JOIN Ac_Period PS ON AP.SFYear = PS.FYear AND AP.SFPeriod = PS.FPeriod 
WHERE ap.Stypeid = @verifyStypeid

SELECT TOP 1 @endYearDate = FEnd FROM dbo.Ac_Period WHERE FYear = @fyear ORDER BY FPeriod DESC

--对总账启用期间以前的业务单据做过滤
IF @billdate < @SFBEGIN
BEGIN
	SET @szPID = '当前单据的日期早于总账启用日期，无需生成凭证。';
	
	IF @CreateType = 0
		RETURN -226
	ELSE IF @JustRep = 0
		RAISERROR(@szPID,16,1)
		
	RETURN -13
END
ELSE IF @billdate > @endYearDate
BEGIN
	SET @szPID = '当前单据生成的会计凭证无对应会计期间，请先结账到下一年度再生成。';
	
	IF @CreateType = 0
		RETURN -226
	ELSE IF @JustRep = 0
		RAISERROR(@szPID,16,1)
		
	RETURN -13
END 

--若单据日期小于当前会计期间起始日期，则取当前系统日期，若当前系统日期也小于当前会计期间起始日期，则取当前会计期间起始日期。
IF @billdate < @beginDate
	SET @billdate = GETDATE()
IF @billdate < @beginDate
	SET @billdate = @beginDate
	
--如果时间超出了本年末期结束，按本年末期为准
--9.2调整为无此期间，提示没有对应年度
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FBegin <= CONVERT(varchar(100), @billdate, 23) AND FEnd >= CONVERT(varchar(100), @billdate, 23))
BEGIN
	SET @szPID = '当前单据生成的会计凭证无对应会计期间，请先结账到下一年度再生成';
	
	IF @CreateType = 0
		RETURN 0
	ELSE IF @JustRep = 0
		RAISERROR(@szPID,16,1)
		
	RETURN -13
END

--根据最后确定的日期获取相应的期间年及期间
SELECT @fyear = FYear,@fperiod = FPeriod FROM dbo.Ac_Period WHERE @billdate >= FBegin AND @billdate <= FEnd

--以前生成主表信息的逻辑在各个分支里面，现在统一提出来做处理，更便于维护
DECLARE @VoucherType INT
SET @VoucherType = 3	--一般业务单据生成

IF @BillType IN (212,213,214)		--固定资产卡片系统中的单据
	SET @VoucherType = 4
ELSE IF @BillType = 310  --出纳系统中的资金调拨单
	SET @VoucherType = 7 

--插入凭证主表
EXEC @VoucherId =   dbo.GP_SaveAc_VoucherIndex 
					@stypeid = @verifyStypeid, -- varchar(50)
					@vgid = @vgid, -- int
					@billdate = @BillDate, -- datetime
					@etypeid = @szCheckMan, -- varchar(50)
					@type = @VoucherType,
					@IsCommission = @IfCommission
DECLARE @countRow INT
SET @countRow = @@ROWCOUNT

IF  @countRow = 0
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	SET @szpid = '写入主表信息错误！'
	
	IF @CreateType = 0
		RETURN -211
		
	RAISERROR(@szpid,16,1)
	RETURN -2
END

IF @VoucherId = -1
BEGIN
	SET @szpid = '您使用的是试用版，凭证数量不能大于200！'
	
	IF @CreateType = 0
		RETURN -223
	ELSE IF @JustRep = 0
		RAISERROR(@szpid,16,1)
		
	RETURN -2
END
ELSE IF @VoucherId = -3
BEGIN
	SET @szpid = '检查程序版本错误！'
	RAISERROR(@szpid,16,1)
	RETURN -2
END

--新思路：在生成凭证主表信息成功后，里面写入对照表，最大程度避免在后续生成明细的过程中，又有其他生成凭证的请求并发，导致数据异常
--独立结转成本配置
DECLARE @independentoutprice INT
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1)
	SET @independentoutprice = 1
ELSE
	SET @independentoutprice = 0
	
--判断单据是否已生成凭证
IF  (	
		@BillType = 310 
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_GoodsBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid WHERE G.InOutType = -1)
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_GoodsBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid WHERE G.InOutType = 1)
	)
	OR
	(
		@IfCommission =0 --一般单据
		AND @BillType <> 310 
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_GoodsBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid
					WHERE VourchBillId <> -1 AND ((@independentoutprice = 1 AND IsCost IN(0,2)) OR @independentoutprice = 0))
	)
	OR(
		@IfCommission IN(1)--提成单
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_CommissionBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid AND g.billtype = @BillType
					WHERE VourchBillId <> -1)
	)
	OR(
		@IfCommission = 2--暂估发票
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_ReceiptBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid
					WHERE VourchBillId <> -1 AND ((@independentoutprice = 1 AND IsCost IN(0,2)) OR @independentoutprice = 0))
	)
	OR(
		@IfCommission=3--优惠券
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_CouponBill_VoucherBill G ON G.CouponBillId = B.Billnumberid AND G.BillType = @BillType AND G.VourchBillId <> -1)
	)
	OR(
		@IfCommission=4--门店配送
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_DeliveryBill_VoucherBill G ON G.DeliveryBillId = B.Billnumberid AND G.BillType = @BillType AND G.VourchBillId <> -1)
	)
BEGIN
	SET @szPID = '单据已经生成过凭证，无法再次生成！'
END
ELSE --写入业务单据和会计凭证的对照表
BEGIN
	DECLARE @iscost INT
	IF @independentoutprice = 1
		SET @iscost = 0
	ELSE
		SET @iscost = 2
		
	IF @IfCommission =0
	BEGIN
		--先清除对照表中VourchBillId = -1的业务单据记录
		DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId IN (SELECT Billnumberid FROM #Billnumberids) AND VourchBillId = -1 AND IsCost IN(0,2) AND ISNULL(InOutType,0) = @InOutType
		INSERT INTO dbo.Ac_GoodsBill_VoucherBill(GoodsBillId,VourchBillId,IsCost,InOutType)SELECT Billnumberid,@VoucherId,@iscost,@InOutType FROM #Billnumberids		
	END
	ELSE IF @IfCommission=1
	BEGIN
		DELETE FROM dbo.Ac_CommissionBill_VoucherBill WHERE GoodsBillId IN (SELECT Billnumberid FROM #Billnumberids) AND billtype = @BillType AND VourchBillId = -1                                                                    
		INSERT INTO dbo.Ac_CommissionBill_VoucherBill(GoodsBillId,VourchBillId,billtype)SELECT Billnumberid,@VoucherId,@BillType FROM #Billnumberids			
	END
	ELSE IF @IfCommission = 2
	BEGIN
		DELETE FROM dbo.Ac_ReceiptBill_VoucherBill WHERE GoodsBillId IN (SELECT Billnumberid FROM #Billnumberids) AND VourchBillId = -1 AND IsCost IN(0,2)
		INSERT INTO dbo.Ac_ReceiptBill_VoucherBill(GoodsBillId,VourchBillId,IsCost)SELECT Billnumberid,@VoucherId,@iscost FROM #Billnumberids
	END
	ELSE IF @IfCommission=3--优惠券
	BEGIN
		DELETE FROM dbo.Ac_CouponBill_VoucherBill WHERE CouponBillId IN (SELECT Billnumberid FROM #Billnumberids) AND BillType=@BillType AND VourchBillId = -1 
		INSERT INTO dbo.Ac_CouponBill_VoucherBill(CouponBillId,VourchBillId,BillType)SELECT Billnumberid,@VoucherId,@BillType FROM #Billnumberids
	END
	ELSE IF @IfCommission=4--门店配送
	BEGIN
		DELETE FROM dbo.Ac_DeliveryBill_VoucherBill WHERE DeliveryBillId IN (SELECT Billnumberid FROM #Billnumberids) AND BillType=@BillType AND VourchBillId = -1 
		INSERT INTO dbo.Ac_DeliveryBill_VoucherBill(DeliveryBillId,VourchBillId,BillType)SELECT Billnumberid,@VoucherId,@BillType FROM #Billnumberids
	END
END
--再次判断单据是否已生成凭证
IF  (	
		@BillType = 310 
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_GoodsBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid WHERE G.InOutType = -1 AND g.VourchBillId <> @VoucherId)
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_GoodsBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid WHERE G.InOutType = 1 AND g.VourchBillId <> @VoucherId)
	)
	OR
	(
		@IfCommission =0
		AND @BillType <> 310 
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_GoodsBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid
					WHERE VourchBillId <> -1 AND VourchBillId <> @VoucherId AND ((@independentoutprice = 1 AND IsCost IN(0,2)) OR @independentoutprice = 0))
	)
	OR(
		@IfCommission=1
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_CommissionBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid AND g.billtype = @BillType
					WHERE VourchBillId <> -1 AND VourchBillId <> @VoucherId)
	)
	OR(
		@IfCommission = 2
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_ReceiptBill_VoucherBill G ON G.GoodsBillId = B.Billnumberid
					WHERE VourchBillId <> -1  AND VourchBillId <> @VoucherId AND ((@independentoutprice = 1 AND IsCost IN(0,2)) OR @independentoutprice = 0))
	)
	OR(
		@IfCommission=3--优惠券
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_CouponBill_VoucherBill G ON G.CouponBillId = B.Billnumberid AND g.billtype = @BillType
					WHERE VourchBillId <> -1 AND VourchBillId <> @VoucherId)
	)
	OR(
		@IfCommission=4--门店配送
		AND EXISTS(SELECT TOP 1 1 FROM #Billnumberids B INNER JOIN dbo.Ac_DeliveryBill_VoucherBill G ON G.DeliveryBillId = B.Billnumberid AND g.billtype = @BillType
					WHERE VourchBillId <> -1 AND VourchBillId <> @VoucherId)
	)
BEGIN
	SET @szPID = '单据已经生成过凭证，无法再次生成！'
END

IF @szPID <> ''--如果过程出错，确保数据正确性，删除关联表凭证记录
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId
	
	DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_CommissionBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_ReceiptBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_CouponBill_VoucherBill WHERE VourchBillId = @VoucherId--优惠券关联表
	DELETE FROM dbo.Ac_DeliveryBill_VoucherBill WHERE VourchBillId = @VoucherId
	
	IF @JustRep = 0
		RAISERROR(@szPID,16,1)
		
	RETURN -13
END

IF  (
		@IfCommission = 0 
		AND EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex B INNER JOIN #Billnumberids T ON T.Billnumberid = B.BillNumberId WHERE B.RedWord<>0)
	)
	OR(
		@IfCommission = 1
		AND EXISTS(SELECT TOP 1 1 FROM dbo.CommissionBillNew B INNER JOIN #Billnumberids T ON T.Billnumberid = B.BillNumberId WHERE B.RedWord<>0)
	)
	OR(
		@IfCommission = 2
		AND EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex B INNER JOIN #Billnumberids T ON T.Billnumberid = B.BillNumberId WHERE B.RedWord<>0)
	)
	OR(
		@IfCommission = 3
		AND EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_BillIndex B INNER JOIN #Billnumberids T ON T.Billnumberid = B.BillNumberId WHERE B.RedWord<>0)
	)
	OR(
		@IfCommission = 4
		AND EXISTS(SELECT TOP 1 1 FROM dbo.PosAllotApplyBillIndex B INNER JOIN #Billnumberids T ON T.Billnumberid = B.BillNumberId WHERE B.RedWord<>0)
	)
BEGIN
	SET @szPID = '单据已经被红冲，无法生成凭证！'
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	
	DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_CommissionBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_ReceiptBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_CouponBill_VoucherBill WHERE VourchBillId = @VoucherId--优惠券关联表
	DELETE FROM dbo.Ac_DeliveryBill_VoucherBill WHERE VourchBillId = @VoucherId
	RETURN -15
END

DECLARE @return	NUMERIC(18,0)			--分录生成结果值，没问题的时候返回值等同@VoucherId
		,@GoodsBillIds	VARCHAR(MAX)	--接收生成凭证时金额不为0的业务单据id

--生成凭证明细
IF @BillType IN(423,424,426,428,429) --优惠券入库单、优惠券出库单
BEGIN
	EXEC @return = dbo.GP_BatchCreateVoucher_CouponBill @BillNumberId,
	    @szCheckMan,
	    @BillType,
	    @BillDate, 
	    @FYear,
	    @FPeriod,
	    @AtId, 
	    @VoucherId ,
	    @Type,
	    @szPID		OUTPUT,
	    @CreateType,
	    @JustRep,
	    @IfCommission, --优惠券固定为3
	    @GoodsBillIds OUTPUT
END
ELSE IF @BillType IN(327,328,329) --门店配送
BEGIN
	EXEC @return = dbo.GP_BatchCreateVoucher_DeliveryBill @BillNumberId,
	    @szCheckMan,
	    @BillType,
	    @BillDate, 
	    @FYear,
	    @FPeriod,
	    @AtId, 
	    @VoucherId ,
	    @Type,
	    @szPID		OUTPUT,
	    @CreateType,
	    @JustRep,
	    @IfCommission, --优惠券固定为3
	    @GoodsBillIds OUTPUT
END
ELSE IF @BillType IN (450)
BEGIN
	EXEC @return = dbo.GP_BatchCreateVoucher_ChargeOffBill @BillNumberId,
	    @szCheckMan,
	    @BillType,
	    @BillDate, 
	    @FYear,
	    @FPeriod,
	    @AtId, 
	    @VoucherId ,
	    @Type,
	    @szPID		OUTPUT,
	    @CreateType,
	    @JustRep,
	    @IfCommission,
	    @GoodsBillIds	OUTPUT
END
ELSE IF @BillType IN (404,405) --采购暂估开票、销售暂估开票  @IfCommission：2
BEGIN
	EXEC @return = dbo.GP_BatchCreateVoucher_ZanGuFaPiao 
		@BillNumberId,
		@szCheckMan,
		@BillType,
		@BillDate,
		@FYear,
		@Fperiod,
		@AtId,
		@VoucherId	,
		@Type,
		@szPID		OUTPUT,
		@CreateType,
		@JustRep,
	    @GoodsBillIds	OUTPUT
END
ELSE IF @BillType IN (4,66,189,190)--收款单、付款单、--预收、预付
BEGIN
	EXEC @return = dbo.GP_BatchCreateVoucher_PayGatherBill 
		@BillNumberId,
		@szCheckMan,
		@BillType,
		@BillDate,
		@FYear,
		@Fperiod,
		@AtId,
		@Type,
		@VoucherId	,
		@szPID		OUTPUT,
		@CreateType,
		@JustRep,
	    @GoodsBillIds	OUTPUT
END

ELSE IF @BillType IN (214)  --type:4
BEGIN
	EXEC  @return = dbo.Gp_CreateVoucher_AssetsBill @BillNumberId, 
	    @BillType, -- int
	    @AtId, -- int
	    @BillDate, -- date
	    @Fyear, -- int
	    @Fperiod, -- int
	    @szCheckMan, -- varchar(50)
	    @CreateType,
	    @szPID		OUTPUT,
	    @VoucherID,
	    @Type,
	    @JustRep,
	    @GoodsBillIds	OUTPUT
	
END

ELSE IF @BillType IN (212,213)  --type:4 213	固定资产减少单 212	固定资产增加单
BEGIN
	EXEC  @return = dbo.Gp_CreateVoucher_AssetIncDecBill @BillNumberId, 
	    @BillType, -- int
	    @AtId, -- int
	    @BillDate, -- date
	    @Fyear, -- int
	    @Fperiod, -- int
	    @szCheckMan, -- varchar(50)
	    @CreateType,
	    @szPID		OUTPUT,
	    @VoucherID,
	    @Type,
	    @JustRep,
	    @GoodsBillIds	OUTPUT
	
END

ELSE IF @BillType IN (5,10,36,77,78,84,85,93,158)
BEGIN
	EXEC @return = dbo.GP_BatchCreateVoucher_MoneyBill @BillNumberId,
	    @szCheckMan,
	    @BillType,
	    @BillDate,
	    @FYear,
	    @FPeriod,
	    @AtId,
	    @VoucherId,
	    @Type,
	    @szPID		OUTPUT,
	    @CreateType,
	    @JustRep,
	    @GoodsBillIds	OUTPUT
END
ELSE IF @BillType IN (57,205) --成本调价单、采购费用分摊单
BEGIN
	EXEC @return =dbo.GP_BatchCreateVoucher_OtherBill @BillNumberId,
	    @szCheckMan,
	    @BillType,
	    @BillDate,
	    @FYear,
	    @FPeriod,
	    @AtId,
	    @VoucherId ,
	    @Type,
	    @szPID		OUTPUT,
	    @CreateType,
	    @JustRep,
	    @GoodsBillIds	OUTPUT
END
ELSE IF @BillType IN (159)
BEGIN
	EXEC @return =dbo.GP_BatchCreateVoucher_AccountCredence @BillNumberId,
	    @szCheckMan,
	    @BillType,
	    @BillDate,
	    @FYear,
	    @FPeriod,
	    @AtId,
	    @VoucherId ,
	    @Type,
	    @szPID		OUTPUT,
	    @CreateType,
	    @GoodsBillIds	OUTPUT
END
ELSE IF @BillType IN (310) --type:7
BEGIN
	EXEC @return =dbo.GP_BatchCreateVoucher_CapitalTransfer @BillNumberId,
	    @szCheckMan,
	    @BillType,
	    @BillDate,
	    @FYear,
	    @FPeriod,
	    @AtId,
	    @VoucherId,
	    @Type,
	    @szPID		OUTPUT,
	    @CreateType,
	    @JustRep,
	    @GoodsBillIds	OUTPUT
END
ELSE
BEGIN
	EXEC @return = dbo.GP_BatchCreateVoucher_CommonBill @BillNumberId,
	    @szCheckMan,
	    @BillType,
	    @BillDate, 
	    @FYear,
	    @FPeriod,
	    @AtId, 
	    @VoucherId,
	    @Type,
	    @szPID		OUTPUT,
	    @CreateType,
	    @JustRep,
	    @IfCommission,
	    @GoodsBillIds	OUTPUT
END


--调整并插入辅助核算明细表
EXEC dbo.Gp_InsertAscidsAsDetails @VoucherID

--调整信息
DECLARE @LendTotal  NUMERIC(24, 10) ,@LoanTotal  NUMERIC(24, 10) ,@CountRowTotal INT
SELECT @LendTotal = SUM(FCreditTotal),@LoanTotal = SUM(FDebitTotal)
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @VoucherId

SELECT @CountRowTotal = COUNT(rowno) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId

--调整表头信息记录
UPDATE dbo.Ac_Voucher SET FDebitTotal = @LendTotal,FCreditTotal = @LoanTotal,FEntryCount=@CountRowTotal
WHERE BillNumberId = @VoucherId

--调整摘要信息，对于配置了每行都要有摘要的情况，自动以前第一行分录的摘要信息对没有摘要的分录进行填充
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='acsummary' AND SubValue = 1)--配置要求每行分录必有摘要
BEGIN
	DECLARE @Summary VARCHAR(300)
	SELECT  @Summary = Summary FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND ROWNO=1
	
	UPDATE Ac_Voucher_Bill SET Summary = @Summary
	WHERE	BillNumberId = @VoucherId AND Summary = ''
END

----------------------生成完成后的凭证检查---------------------------------------
DECLARE	@flag INT --是否需要用户补足
		,@autoflag INT --即时生成凭证异常
		,@CannotCreat	INT  --不能生成凭证
SET @flag = 0
SET @autoflag = 0
SET @CannotCreat = 0

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId) 
BEGIN
	SET @AutoFlag = -214
	SET @szPID += '【单据生成凭证所有金额为0，无法生成或不需生成会计凭证】'
	SET @flag = -12
END

IF @flag <>-12 AND EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill T1 INNER JOIN dbo.Ac_Account T2 ON T1.atypeid = T2.TypeId AND T2.StypeId = t1.StypeId AND Deleted = 1 WHERE BillNumberId = @VoucherId)
BEGIN
	SET @AutoFlag = -228
	SET @szPID = '【生成凭证中有会计科目被停用】 '
	SET @flag = -10
	--RETURN -10
END

IF @flag <>-12 AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND ATypeId = '') 
BEGIN
	SET @AutoFlag = -222
	SET @szPID += '【存在凭证分录科目获取失败】'
	SET @flag = -1
END

IF @flag <>-12 AND EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE BillNumberId = @VoucherId AND FDebitTotal <> FCreditTotal)
BEGIN
	SET @AutoFlag = -217
	SET @szPID += '【生成的凭证借贷不平衡】'
	SET @flag = -2 
END

IF @flag <>-12 AND 
	--EXISTS
	--(
	--	SELECT TOP 1 1 
	--	FROM (
	--		SELECT	A.ATypeId,COUNT(A.Ascids) AS AscidCount_Account
	--		FROM	Ac_Account_Assist_CheckItems A
	--		INNER JOIN Ac_Voucher_Bill B ON B.STypeId = A.STypeId AND B.ATypeId = A.ATypeId
	--		WHERE	B.BillNumberId = @VoucherId
	--		GROUP BY A.ATypeId
	--	) T
	--	INNER JOIN (
	--		SELECT	B.ATypeId,COUNT(A.typeName) AS AscidCount_Bill
	--		FROM	Ac_Voucher_Bill_Assist_CheckItems A
	--		INNER JOIN	Ac_Voucher_Bill B ON B.ID = A.vBId
	--		INNER JOIN	Ac_Assist_CheckItems C ON C.UserCode = A.typeName
	--		INNER JOIN	Ac_Account_Assist_CheckItems D ON D.STypeId = B.STypeId AND D.Ascids = C.AscIds AND D.ATypeId = B.ATypeId
	--		WHERE	B.BillNumberId = @VoucherId
	--		GROUP BY B.ATypeId
	--	) T1 ON T1.ATypeId = T.ATypeId AND T1.AscidCount_Bill <> T.AscidCount_Account
	--)
	--AND
	EXISTS
	(
		SELECT TOP 1 B.ATypeId,C.Ascids,AC.TypeId 
		FROM Ac_Voucher_Bill B
		INNER JOIN (SELECT ATypeId,STypeId,Ascids FROM Ac_Account_Assist_CheckItems GROUP BY STypeId,ATypeId,Ascids) C ON C.STypeId = B.STypeId AND C.ATypeId = B.ATypeId 
		LEFT JOIN (SELECT vBId,X.TypeId,AAC.AscIds FROM Ac_Voucher_Bill_Assist_CheckItems X INNER JOIN Ac_Assist_CheckItems AAC ON AAC.UserCode = X.typeName) AC ON AC.vBId = B.ID AND AC.AscIds = C.Ascids
		WHERE B.BillNumberId = @VoucherId AND ISNULL(ac.TypeId,'') = ''
	)
BEGIN	
	SET @AutoFlag = -216
	SET @szPID +='【科目的辅助核算项获取异常】'
	SET @flag = -4	
END

IF @flag <>-12 AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId AND FDebitTotalFor = 0 AND FCreditTotalFor = 0)
BEGIN
	SET @AutoFlag = -213
	SET @szPID += '【存在科目外币核算与单据币种不符】'
	SET @flag = -5	
END

IF @flag <>-12 AND EXISTS(SELECT * FROM sysdata WHERE SubName = 'acpitdataflow' AND SubValue = 1)--必填现金流量
BEGIN
	DECLARE @countJie  NUMERIC(24, 10) ,@countDai  NUMERIC(24, 10) 

	SELECT @countJie = SUM(FDebitTotal),@countDai = SUM(FCreditTotal)
	FROM dbo.Ac_Voucher_Bill a
	INNER JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND a.STypeId = b.StypeId
	WHERE BillNumberId = @VoucherId AND (b.IsBank = 1 OR b.IsCash = 1 OR b.IsOther = 1)
	
	IF @countJie <> @countDai 
	BEGIN
		SET @AutoFlag = -221
		SET @szPID += '【配置要求填写现金流量】'
		SET @flag = -9	
	END
END

SET @deficitvoucher = 0
--赤字检查  (IsCash=1 OR IsBank=1 AND IsOther=1)
--赤字处理方式：检查凭证是否存在赤字情况并标记，然后将结果返回给客户端，存在标记则提示客户，由客户确认是否保留凭证
IF @flag =0 AND @checkdeficit > 0 --AND EXISTS (select TOP 1 1 from sysdata where subname in ( 'fundaccountisredsave','fundaccountisrednosave') and subvalue = '1')
BEGIN
	DECLARE @maxFyear INT
			,@maxFperiod INT
	
	SELECT @maxFyear=MAX(FYear) FROM dbo.Ac_Balance WHERE STypeId = @STypeid
	SELECT @maxFperiod=MAX(FPeriod) FROM dbo.Ac_Balance WHERE STypeId = @STypeid AND FYear = @maxFyear
	
	SELECT t.ATypeId,t.BILLTOTAL+ISNULL(ab.FEndBalance,0) AS balance 
	INTO #TMPcheckdeficit
	FROM 
	(
		SELECT  ISNULL(SUM(CASE WHEN b.Fdc = 1 THEN B.FDebitTotal - B.FCreditTotal ELSE B.FCreditTotal - B.FDebitTotal END ),0) AS BILLTOTAL
				,B.ATypeId 
		FROM Ac_Voucher_Bill B 
		INNER JOIN Ac_Voucher V ON V.BillNumberId = B.BillNumberId
		INNER JOIN (SELECT ATypeId FROM Ac_Voucher_Bill WHERE BillNumberId = @VoucherId) B1 ON B1.ATypeId = B.ATypeId
		INNER JOIN Ac_Account A ON A.TypeId = B.ATypeId AND A.StypeId = V.STypeId
		WHERE V.IfCheck = 'f'
			AND	V.MarkError = ''
			AND V.STypeId = @stypeid
			AND (A.IsCash=1 OR A.IsBank=1 OR A.IsOther=1)
		GROUP BY B.ATypeId
	) T
	LEFT JOIN Ac_Balance AB ON AB.ATypeId = T.ATypeId AND AB.Cid = 0 AND AB.STypeId = @STypeid AND AB.FYear = @maxFyear AND AB.FPeriod = @maxFperiod
	
	IF EXISTS (SELECT TOP 1 1 FROM #TMPcheckdeficit)
	BEGIN	
		SET @deficitvoucher = 1
	END
	
	IF EXISTS (SELECT TOP 1 1 FROM #TMPcheckdeficit WHERE balance < 0)
	BEGIN	
		DECLARE @str VARCHAR(500)
		SET @str = ''
		SELECT @str += A.FullName + ','
		FROM	Ac_Account A 
		INNER JOIN #TMPcheckdeficit T ON T.ATypeId = A.TypeId
		WHERE A.StypeId = @STypeid
			AND	T.balance < 0 
			
		SET @autoflag = -14
		SET @flag = -14
		SET @szPID = '当前凭证会造成【'+SUBSTRING(@str,0,len(@str))+'】科目余额出现赤字。'
	END
	DROP TABLE #TMPcheckdeficit
END

IF (@CreateType = 0 AND @autoflag <> 0) OR @CannotCreat <>0
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId	
	
	DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_CommissionBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_ReceiptBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_CouponBill_VoucherBill WHERE VourchBillId = @VoucherId
	DELETE FROM dbo.Ac_DeliveryBill_VoucherBill WHERE VourchBillId = @VoucherId
	RETURN @AutoFlag	
END
ELSE IF @flag = -12
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
	DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId	
	
	UPDATE dbo.Ac_GoodsBill_VoucherBill SET VourchBillId = -1 WHERE VourchBillId = @VoucherId
	UPDATE dbo.Ac_CommissionBill_VoucherBill SET VourchBillId = -1 WHERE VourchBillId = @VoucherId
	UPDATE dbo.Ac_ReceiptBill_VoucherBill SET VourchBillId = -1 WHERE VourchBillId = @VoucherId
	UPDATE dbo.Ac_CouponBill_VoucherBill SET VourchBillId = -1  WHERE VourchBillId = @VoucherId
	UPDATE dbo.Ac_DeliveryBill_VoucherBill SET VourchBillId = -1  WHERE VourchBillId = @VoucherId
	
	RETURN @flag
END
ELSE IF @Type = 0 AND @flag <> 0 --报告模式下，有错误的凭证都不能保留，放在这里处理是为了便于处理对照表
BEGIN
	IF @flag <> -14
	BEGIN
		DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
		DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherId
		DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherId	
		
		DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE VourchBillId = @VoucherId
		DELETE FROM dbo.Ac_CommissionBill_VoucherBill WHERE VourchBillId = @VoucherId
		DELETE FROM dbo.Ac_ReceiptBill_VoucherBill WHERE VourchBillId = @VoucherId
		DELETE FROM dbo.Ac_CouponBill_VoucherBill WHERE VourchBillId = @VoucherId
		DELETE FROM dbo.Ac_DeliveryBill_VoucherBill WHERE VourchBillId = @VoucherId
	END
	
	RETURN @flag
END

--完成所有验证后，对凭证进行标错处理
UPDATE Ac_Voucher SET MarkError = @szPID WHERE BillNumberId = @VoucherId
----------------------生成完成后的凭证检查end---------------------------------------

-----------------------调整对应关系-----------------------------------------------
--生成凭证时金额不为0的业务单据id
CREATE TABLE #TmpBillNumberId
(
	billindexid	NUMERIC(18,0)
)
INSERT INTO #TmpBillNumberId(billindexid)
SELECT  a
FROM	f_split(@GoodsBillIds,',')
WHERE	a <> ''

IF @IfCommission =0 
BEGIN
	--将生成凭证时金额全部为0的业务单据的对应凭证id置为-1
	UPDATE Ac_GoodsBill_VoucherBill SET VourchBillId = -1
	WHERE GoodsBillId NOT IN (SELECT billindexid FROM #TmpBillNumberId)
		AND InOutType = @InOutType
		AND VourchBillId = @VoucherId
	
	--写BillIndex记账人
	UPDATE dbo.BillIndex SET TallyId = @szCheckMan WHERE BillNumberId IN (SELECT * FROM #TmpBillNumberId)
END
ELSE IF @IfCommission=1
BEGIN
	UPDATE Ac_CommissionBill_VoucherBill SET VourchBillId = -1
	WHERE GoodsBillId NOT IN (SELECT billindexid FROM #TmpBillNumberId)	
		AND VourchBillId = @VoucherId
END
ELSE IF @IfCommission = 2
BEGIN	
	UPDATE Ac_ReceiptBill_VoucherBill SET VourchBillId = -1
	WHERE GoodsBillId NOT IN (SELECT billindexid FROM #TmpBillNumberId)	
		AND VourchBillId = @VoucherId
	
	UPDATE dbo.ReceiptBillIndex SET TallyId = @szCheckMan WHERE BillNumberId IN (SELECT billindexid FROM #TmpBillNumberId)
END
ELSE IF @IfCommission=3--优惠券
BEGIN	
	UPDATE Ac_CouponBill_VoucherBill SET VourchBillId = -1
	WHERE CouponBillId NOT IN (SELECT billindexid FROM #TmpBillNumberId)	
		AND VourchBillId = @VoucherId
	
	UPDATE dbo.Coupon_BillIndex SET TallyId = @szCheckMan WHERE BillNumberId IN (SELECT billindexid FROM #TmpBillNumberId)
END
ELSE IF @IfCommission=4--门店配送
BEGIN	
	UPDATE Ac_DeliveryBill_VoucherBill SET VourchBillId = -1
	WHERE DeliveryBillId NOT IN (SELECT billindexid FROM #TmpBillNumberId)	
		AND VourchBillId = @VoucherId
	
	--UPDATE dbo.Coupon_BillIndex SET TallyId = @szCheckMan WHERE BillNumberId IN (SELECT billindexid FROM #TmpBillNumberId)
END
-----------------------调整对应关系end-----------------------------------------------
IF @CreateType = 0
	RETURN 0

RETURN @flag


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：
*/
CREATE PROCEDURE GP_HandIndexChartData
(
	@ifsj INT=0
)
--@encode$--
AS
SET NOCOUNT ON

	--判断该账套是否应该汇总数据了
	 --不需要同步
	 IF @ifsj<>1 --升级ifsj=1 不验证
	 BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='indexpagestyle'  AND SubValue='1' )
			RETURN
		
		DECLARE @indexpagelastreftime   DATETIME,
				@countDuration INT
		
		SELECT @indexpagelastreftime=SubValue   FROM dbo.sysdata WHERE SubName='indexpagelastreftime' 
		 
		--固定时间更新	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='frequencytype'  AND SubValue='0')
		BEGIN
			SELECT @countDuration=SubValue   FROM dbo.sysdata WHERE SubName='day_indexpagereftime' 
			DECLARE  @h  INT
			SET  @h =  datename(hh,GETDATE())
			IF (@h=0)
				SET @h=24
			IF (@h <> @countDuration)
					RETURN 	
		END
		
		--每隔好多时间更新	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='frequencytype'  AND SubValue='1')
		BEGIN
			SELECT @countDuration=SubValue  FROM dbo.sysdata WHERE SubName='time_indexpagereftime' 
			IF (DATEDIFF (HOUR,@indexpagelastreftime,GETDATE())<@countDuration)
				RETURN 
		END
	END

	DECLARE @startdate DATETIME
	SELECT @startdate=StartDate FROM  MonthProc	 WHERE MonthNo='本期'
	TRUNCATE TABLE IndexChartData
    ------销售数据汇总-----------	
        CREATE TABLE #result
        (
			  PtypeId VARCHAR(50),
			  total NUMERIC(24,2),
			  costtotal NUMERIC(24,2)  
        )
        INSERT  INTO #result
        SELECT PtypeId,  CAST(SUM(saletotal) AS NUMERIC(24,2)) AS total,CAST(SUM(costtotal) AS NUMERIC(24,2)) AS costtotal
        FROM (
         SELECT
			    a.PtypeId,
				sum(-Total) saletotal ,
				sum(-CostTotal) costtotal
			FROM InOutstocktable a
			WHERE a.BillType IN (11 ,45 ,160 ,305 ,141,215)
			AND  a.BillDate>@startdate
			AND  a.Audited=1
			GROUP BY  a.PtypeId
			UNION  ALL
			SELECT	
				a.PtypeId,
				SUM(a.DiscountPrice*(a.Qty-a.InvoiceQty)) AS saletotal,
				SUM(a.CostTotal-a.InvoiceCostTotal) AS costtotal
			FROM dbo.SendBill a,
			dbo.BillIndex b
			WHERE a.BillNumberId=b.BillNumberId
			AND b.BillDate >@startdate   AND b.draft=0 AND b.RedWord=0  AND b.IsIni=0
			GROUP BY a.PtypeId
			UNION  ALL
			SELECT	
				a.PtypeId,
				-SUM(a.DiscountPrice*(a.Qty-a.InvoiceQty)) AS saletotal,
				-SUM(a.CostTotal-a.InvoiceCostTotal)  AS costtotal
			FROM dbo.SendBackBill a,
			dbo.BillIndex b
			WHERE a.BillNumberId=b.BillNumberId
			AND b.BillDate >@startdate   AND b.draft=0 AND b.RedWord=0    AND b.IsIni=0
			GROUP BY a.PtypeId
			UNION  ALL
			SELECT	
				a.PtypeId,
				SUM(a.NTotal) AS saletotal,
				SUM(a.InvoiceCostTotal) AS costtotal
			FROM dbo.ReceiptBill a,
			dbo.ReceiptBillIndex b
			WHERE a.BillNumberId=b.BillNumberId
			AND b.BillDate >@startdate   AND b.draft=0 AND b.RedWord=0   AND b.IsIni=0
			AND b.BillType=405
			GROUP BY a.PtypeId
		)a 
		GROUP BY a.PtypeId
		
		INSERT INTO IndexChartData(TypeId,fullname,total,total1,total2,flag)
		SELECT TOP 5
			a.PtypeId,
			b.FullName,
			a.total AS total,
			a.total-a.costtotal AS maoli,
		    CAST( CASE WHEN a.total=0 THEN 0 ELSE (a.total-a.costtotal)/ a.total END AS NUMERIC(24,2)) AS maolilv ,
		    1
		FROM #result a,
		ptype b
		WHERE a.PtypeId=b.typeId
		ORDER BY a.total DESC
		
		DECLARE @orTotal NUMERIC(24,10)
		DECLARE @orCosttotal   NUMERIC(24,10)
		DECLARE @allTotal NUMERIC(24,10)
		DECLARE @allCosttotal   NUMERIC(24,10)
		
		SELECT @orTotal=SUM(total),@orCosttotal=SUM(total1)
		FROM IndexChartData	 WHERE flag=1
		
		SELECT @allTotal=SUM(total),@allCosttotal=SUM(total-costtotal)
		FROM #result
		
 		INSERT INTO IndexChartData(TypeId,fullname,total,total1,total2,flag)
		SELECT 	'99999' AS ptypeid   ,
				'其他商品'   AS FullName,
				@allTotal-@orTotal,
				(@allTotal-@orTotal)-(@allCosttotal-@orCosttotal) AS maoli,
				CAST(CASE WHEN (@allTotal-@orTotal)=0 THEN 0 ELSE ((@allTotal-@orTotal)-(@allCosttotal-@orCosttotal)) /(@allTotal-@orTotal) END AS NUMERIC(24,2)) AS maolilv  ,
				1
	    --处理金额有大于10w的时候，数据以w元为单位
	    
	    IF EXISTS( SELECT TOP 1 1 FROM IndexChartData WHERE total>100000 AND flag=1 AND TypeId<>'99999')
	    BEGIN
			UPDATE dbo.IndexChartData SET total=CAST(total/10000 AS NUMERIC(22,2)), total1=CAST(total2/10000 AS NUMERIC(22,2)),CountType=1
			WHERE flag=1
	    END
		DROP TABLE #result 
	----------------------销售数据汇总 end---------------------
	-------------费用汇总start------------	
		CREATE TABLE #tmp
		(
			atypeid VARCHAR(50),
			fullname VARCHAR(200),
			total	NUMERIC(22,2)
		)
		INSERT INTO #tmp
		SELECT a.nTypeID,a.fullname,SUM(ISNULL(b.Total,0)) AS total
		FROM dbo.Ac_Items a
		INNER JOIN 
		(
			SELECT  a.nTypeID,SUM(ISNULL(b.Total,0)) AS total
			FROM 
			dbo.Ac_Items a
			INNER JOIN dbo.AType_Total b  ON  a.nId=b.ATypeID
			WHERE   a.nTypeId LIKE '0000400003%'
			GROUP BY a.nTypeID
		)b  ON  b.nTypeID LIKE a.nTypeID+'%' 
		WHERE   a.nTypeId LIKE '0000400003%'
			   AND a.Leveal=3
		GROUP BY a.nTypeID,a.fullname
		
		CREATE TABLE #t1(typeid VARCHAR(50))
	
		 INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		 SELECT atypeid,fullname,total,2  
		 FROM #tmp 
		 WHERE fullname='财务费用' OR fullname='销售费用'    --财务费用，销售费用
		 
		 INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		 SELECT TOP 2 atypeid,fullname,total,2 
		 FROM #tmp 
		 WHERE	  fullname<>'财务费用' AND  fullname<>'销售费用'
		 ORDER BY total DESC   --财务费用销售费用以外top2
		
		 INSERT INTO #t1
		 SELECT typeid FROM	 IndexChartData	 WHERE flag=2
		 
		 INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		 SELECT '99999' AS atypeid,'other' AS fullname, ISNULL(SUM(t.total),0),2	    --上面两种情况以外的全部合计
		 FROM #tmp  t
		 WHERE  NOT EXISTS(SELECT  1 FROM #t1 a WHERE a.typeid=t.atypeid)
		  AND t.total<>0

		IF EXISTS( SELECT TOP 1 1 FROM IndexChartData WHERE total>100000 AND flag=2 AND TypeId<>'99999')
	    BEGIN
			UPDATE dbo.IndexChartData SET total=CAST(total/10000 AS NUMERIC(22,2)),CountType=1
			WHERE flag=2
	     END
		 DROP TABLE #tmp,#t1
	  -----------费用汇总end-----------------------
	  -------库存汇总 start----------------
		INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		SELECT	TOP 5 a.PtypeId,p.FullName,a.Total,3
		FROM(
			SELECT PtypeId,SUM(Total)	AS Total
			FROM dbo.GoodsStocks 
			GROUP BY PtypeId
			)a,
		dbo.ptype p
		WHERE a.PtypeId=p.typeId
		ORDER BY a.Total DESC
		
		IF EXISTS( SELECT TOP 1 1 FROM IndexChartData WHERE total>100000 AND flag=3 AND TypeId<>'99999')
	    BEGIN
			UPDATE dbo.IndexChartData SET total=CAST(total/10000 AS NUMERIC(22,2)),CountType=1
			WHERE flag=3
	     END
	------------库存汇总end------------
	------------资金汇总star ------------
		CREATE TABLE #tmp1
		(
			atypeid VARCHAR(50),
			fullname VARCHAR(200),
			total	NUMERIC(22,2)
		)
		
		
		--   货币资金
		DECLARE @hbzj NUMERIC(22,10)
		
		SELECT  @hbzj=SUM(ISNULL(b.Total,0)) 
		FROM dbo.Ac_Items a
		INNER JOIN dbo.AType_Total b	 ON b.ATypeID = a.nId
		WHERE   a.nTypeId LIKE '0000100004%'  OR a.nTypeId LIKE '0000100003%'
	
		INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		SELECT '0000100003','货币资金',ISNULL(@hbzj,0),4
		
		INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		SELECT '0000100005','应收合计',SUM(ISNULL(Total,0)),4
		FROM Ac_Items a
		LEFT JOIN	AType_Total b ON a.nId=b.ATypeID
		WHERE a.UserCode='987'
		
		INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		SELECT '0000100009','预付资金',SUM(ISNULL(Total,0)),4
		FROM Ac_Items a
		LEFT JOIN	AType_Total b ON a.nId=b.ATypeID
		WHERE a.UserCode='1151'
		
		INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		SELECT '0000100001','库存商品总值',SUM(ISNULL(Total,0)),4
		FROM Ac_Items a
		LEFT JOIN	AType_Total b ON a.nId=b.ATypeID
		WHERE a.UserCode='1241'
		
		DECLARE @ohertotal NUMERIC(22,10)
		SELECT  @ohertotal=SUM(ISNULL(b.Total,0)) 
		FROM dbo.Ac_Items a
		INNER JOIN dbo.AType_Total b	 ON b.ATypeID = a.nId 
		WHERE   a.nTypeId NOT LIKE '0000100004%'  AND a.nTypeId NOT LIKE '0000100003%'
		AND a.UserCode NOT IN('987', '1151','1241')
		AND a.nTypeId LIKE '00001%'
		
		INSERT INTO IndexChartData(TypeId,fullname,total,flag)
		SELECT '99999','other',ISNULL(@ohertotal,0),4
		
		IF EXISTS( SELECT TOP 1 1 FROM IndexChartData WHERE total>100000 AND flag=4 AND TypeId<>'99999')
	    BEGIN
			UPDATE dbo.IndexChartData SET total=CAST(total/10000 AS NUMERIC(22,2)),CountType=1
			WHERE flag=4
	    END
		DROP TABLE #tmp1
	------------资金汇总end ------------
	
	---------往来start-----------
	
		--应收
		DECLARE @total NUMERIC(22,10)
		SELECT @total=SUM(artotal)
		FROM dbo.BType_ArApTotal 
		
		INSERT INTO IndexChartData(TypeId,fullname,total,total1,total2,flag)
		SELECT TOP 5  a.BTypeID,b.fullname,a.total, CAST((a.total/@total)*100 AS NUMERIC(22,2)) AS percenttotal,@total AS zjtotal,5  
		FROM
		(
			SELECT SUM(ARTotal)	AS total,BTypeID
			FROM dbo.BType_ArApTotal
			WHERE ARTotal<>0
			GROUP  BY BTypeID 
		)a,
		dbo.btype b 
		WHERE a.BTypeID=b.typeId
		ORDER BY a.total DESC
		
		IF EXISTS( SELECT TOP 1 1 FROM IndexChartData WHERE total>100000 AND flag=5 AND TypeId<>'99999')
	    BEGIN
			UPDATE dbo.IndexChartData SET total=CAST(total/10000 AS NUMERIC(22,2)),CountType=1   ,total2=CAST(total2/10000 AS NUMERIC(22,2))
			WHERE flag=5
	     END
       --超期应收
	
		CREATE TABLE #artmp
		(
			btypeid VARCHAR(50),
			total NUMERIC(24,10)
		)
		
		INSERT INTO #artmp(total,  btypeid)
		SELECT SUM(total) AS total,
				btypeid
		 FROM (
			SELECT	 
					SUM(Bil.TotalMoney-ISNULL(Bil.TotalinMoney,0)-ISNULL(Bil.CompleteTotal,0)-ISNULL(Bil.preferenceMoney,0)-ISNULL(Bil.ChargeOffTotal,0)) AS total,
					Bil.btypeid
				
					FROM 	BillIndex Bil  	
			WHERE	Bil.BillType = 11  	
					AND Bil.AlertDay<>'9999' 
					AND DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate), GETDATE())>=0 
					AND ((Bil.IfCheck = 't' AND Bil.RedWord = 0 AND Bil.IfYearBill = 0)  OR Bil.isini=1 )
					AND (Bil.TotalMoney - ISNULL(Bil.TotalinMoney,0) - ISNULL(Bil.CompleteTotal,0)-ISNULL(Bil.preferenceMoney,0)-ISNULL(Bil.ChargeOffTotal,0)) > 0
					AND (Bil.ifStopMoney='0' or Bil.IfStopMoney IS NULL) 
			GROUP BY Bil.btypeid
					UNION ALL 
			SELECT	
					SUM(Bil.taxTotalMoney-ISNULL(Bil.CompleteTotal,0)-ISNULL(Bil.ChargeOffTotal,0)) AS total,
					Bil.btypeid
					
					FROM 	ReceiptBillIndex Bil
					 
			WHERE	Bil.BillType = 405  	
					AND Bil.AlertDay<>'9999' 
					AND DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate),  GETDATE())>=0 
					AND ((Bil.IfCheck = 't' AND Bil.RedWord = 0 AND Bil.IfYearBill = 0)  OR Bil.isini=1 )
					AND (Bil.TotalMoney - ISNULL(Bil.CompleteTotal,0)-ISNULL(Bil.ChargeOffTotal,0)) > 0
					AND (Bil.ifStopMoney='0' or Bil.IfStopMoney IS NULL) 
			GROUP BY Bil.btypeid
			)a
			GROUP BY btypeid
		
		DECLARE @cqtotal NUMERIC(22,10)
		SELECT @cqtotal=SUM(total)
		FROM #artmp
		
		INSERT INTO IndexChartData(TypeId,fullname,total,total1,total2,flag)
		SELECT TOP 5 a.btypeid,b.fullname,a.total,CAST((a.total/@cqtotal)*100 AS NUMERIC(22,2))  AS percenttotal ,@cqtotal AS zjtotal,6
		FROM #artmp a,
		dbo.btype b
		WHERE a.btypeid=b.typeId 
		ORDER BY total DESC
		
		IF EXISTS( SELECT TOP 1 1 FROM IndexChartData WHERE total>100000 AND flag=6 AND TypeId<>'99999')
	    BEGIN
			UPDATE dbo.IndexChartData SET total=CAST(total/10000 AS NUMERIC(22,2)),total2=CAST(total2/10000 AS NUMERIC(22,2)),CountType=1
			WHERE flag=6
	     END
		DROP TABLE #artmp
		
		
	UPDATE sysdata SET SubValue=GETDATE() WHERE SubName='indexpagelastreftime'
	-----end-------------------------------  
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Hr_AddImg]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Hr_AddImg]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王刚	
	日期：2011-04-2
	描述：添加照片
*/
CREATE PROCEDURE GP_Hr_AddImg
( 	
	@person_id int,			--人员ID		
	@pic image,				--文件路径		
	@length int,			--文件大小
	@filename varchar(max)	-- 文件名称
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS (SELECT Person_ID  FROM HR_Img WHERE Person_ID = @person_id)
	BEGIN
		UPDATE	 HR_Img
		SET	     pic		= @pic,
				 length		= @length,
				 filename	= @filename
		WHERE	 Person_ID	= @person_id
	 RETURN
	END 

	
INSERT INTO HR_Img
(
	Person_ID,
	pic,
	length,
	filename
)
VALUES
(
	@person_id,
	@pic,
	@length,
	@filename
)


IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('照片添加添加失败！',16,1)
		RETURN
	END 	

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_Hr_AddPerLimit]    Script Date: 03/16/2011 08:45:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Hr_AddPerLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Hr_AddPerLimit]
GO
-- =============================================
-- Author:		王刚
-- Create date: 03/26/2011 
-- Description:	添加人员权限
-- =============================================
CREATE PROCEDURE [dbo].Gp_Hr_AddPerLimit
(	
	@Limit VARCHAR(MAX),		 --权限字符串
	@Person_ID int				 --人员ID
)
--@encode$--
AS
UPDATE HR_PersonLimit
SET
		Limit		=	@Limit
WHERE	Person_ID	=	@Person_ID						 --人员ID

RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-26
	描述：保存试用期员工任务的自我评价
-------------------------------------------*/
CREATE PROCEDURE GP_HR_AddProTaskEs
(
	@taskID		varchar(MAX),	---任务ID
	@personId	varchar(MAX),	---执行任务的试用期员工
	@datetime	DATETIME,
	@content	varchar(MAX)	---评价内容
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO HR_TaskEstimate
(
	Task_ID,
	Person_ID,
	HR_ID,
	Content,
	DateTime
)
VALUES
(
	@taskID,
	@personId,	
	@personId,	--自我评价，故评价人的ID和执行任务的人的ID相同
	@content,
	@datetime
)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-6
	描述：修改密码
-------------------------------------------*/
CREATE PROCEDURE GP_HR_ChangePwd
(
	@personId	VARCHAR(MAX),	---人员ID
	@oldPwd		VARCHAR(MAX),	---旧密码
	@newPwd		VARCHAR(MAX),	---新密码	
	@returnMsg	VARCHAR(MAX) OUT,
	@returnCode	int OUT				---0修改成功，1修改失败
)
--@encode$--
AS
SET NOCOUNT ON

---判断旧密码是否正确
SELECT	*
FROM	HR_Person
WHERE	ID=@personId AND password=@oldPwd
IF @@ROWCOUNT!=1
BEGIN
	SET	@returnMsg='密码错误'
	SET @returnCode=1
	RETURN
END

---修改密码
UPDATE HR_Person SET password=@newPwd WHERE ID=@personId
SET	@returnMsg='修改成功'
SET	@returnCode=0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-26
	描述：保存试用期员工任务的自我评价
-------------------------------------------*/
CREATE PROCEDURE GP_HR_DelInDirection
(
	@name		varchar(MAX)	---面试评估项目名称
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM HR_InterviewerEstimate a INNER JOIN HR_InterviewDirection b ON a.Title=b.Name
		 WHERE b.Name=@name)
	BEGIN
		RAISERROR('该评估项目已在使用，不能删除!',16,1)
		RETURN
	END				
DELETE HR_InterviewDirection
WHERE Name=@name			
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_Hr_DelPerson]    Script Date: 03/16/2011 08:45:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Hr_DelPerson]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Hr_DelPerson]
GO
-- =============================================
-- Author:		王刚
-- Create date: 03/28/2011 
-- Description:	修改人员信息
-- =============================================

CREATE PROCEDURE [dbo].Gp_Hr_DelPerson
(
	@id int			--人员id
)
--@encode$--
AS

BEGIN TRANSACTION TRAN_DEL
DELETE FROM HR_Person WHERE id = @id									--删除人员

IF EXISTS (SELECT *FROM HR_PersonLimit WHERE Person_ID=@id)		--删除人员相对应的权限
	DELETE FROM HR_PersonLimit
	WHERE Person_ID=@id
	
IF EXISTS (SELECT * FROM HR_Img WHERE Person_ID = @id)			-- 删除人员照片
	DELETE FROM HR_Img	
	WHERE Person_ID = @id
	
IF EXISTS (SELECT * FROM HR_TaskDistribution WHERE Person_ID = @id) --删除任务分配记录
	DELETE FROM HR_TaskDistribution
	WHERE Person_ID = @id
	
IF (@@ERROR <> 0)
	ROLLBACK TRANSACTION TRAN_DEL
ELSE
	COMMIT TRANSACTION TRAN_DEL
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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


/****** Object:  StoredProcedure [dbo].[GP_HR_HrLogin]    Script Date: 03/21/2011 09:56:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*-----------------------------------
	作者：黄清
	日期：2011-3-16
	描述：HR系统HR登陆判断
-----------------------------------*/
CREATE PROCEDURE [dbo].[GP_HR_HrLogin] 
(
	@Name			VARCHAR(MAX),
	@pwd			VARCHAR(MAX),
	@reValue		VARCHAR(MAX) OUT,
	@personlimit	VARCHAR(MAX) OUT,   ---权限
	@personid		INT OUT,
	@identify		INT OUT				---用户状态
)
--@encode$--
AS
SET NOCOUNT ON

IF @pwd = '1'
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Hr_Person WHERE Name = '00001' AND ISNULL(password,'') = '')
	BEGIN
		UPDATE Hr_Person SET password = @Name WHERE Name = '00001'
	END	
END
ELSE IF @pwd = '2'
BEGIN
	SELECT TOP 1 * FROM dbo.HR_Person WHERE Name = '00001'
END
ELSE IF @pwd = '3'
BEGIN
	IF @Name = ''
	BEGIN
		UPDATE Hr_Person SET password = '0'   WHERE Name = '00003'
		UPDATE Hr_Person SET password = 'bhWCruESCG0=' WHERE Name = '00004'		
	END
	ELSE	
	BEGIN
		UPDATE Hr_Person SET password = '1'   WHERE Name = '00003'
		UPDATE Hr_Person SET password = @Name WHERE Name = '00004'		
	END
END
ELSE IF @pwd = '4'
BEGIN
	UPDATE Hr_Person SET password = @Name WHERE Name = '00005'	
	UPDATE Hr_Person SET password = CONVERT(VARCHAR(10),GETDATE(),120) WHERE Name = '00006'
END
ELSE IF @pwd = '5'
BEGIN
	SELECT TOP 1 * FROM dbo.HR_Person WHERE Name = '00006'
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-24
	描述：面试评价方向的新增和修改
-------------------------------------------*/
CREATE PROCEDURE GP_HR_InDirectionAddandUpdate
(
	@id			int,				---id
	@Name		VARCHAR(MAX),		---评价方向名称
	@Remark		VARCHAR(MAX),		---备注
	@optype		VARCHAR(MAX),		---操作类型
	@returnMsg	VARCHAR(MAX) out,	---返回信息
	@returnCode	VARCHAR(MAX) out	---返回码，1：操作执行成功，0：操作执行失败
)
--@encode$--
AS
SET NOCOUNT ON

IF @optype='doAdd' ---新增操作
BEGIN
	SELECT *FROM HR_InterviewDirection WHERE Name=@Name
	IF @@ROWCOUNT=1
	BEGIN
		SET @returnMsg='该类型已存在！'
		SET	@returnCode='0'
		RETURN
	END		
	INSERT INTO HR_InterviewDirection	---类型不存在，新增
	(
		Name,
		Remark
	) 
	VALUES
	(	
		@Name,
		@Remark
	)
	IF @@ROWCOUNT=1	
	BEGIN
		SET @returnMsg='新增成功！'
		SET	@returnCode='1'
	END
END

IF @optype='doModify'	---修改操作
BEGIN
	SELECT *FROM HR_InterviewDirection WHERE Name=@Name  AND ID <> @id
	IF @@ROWCOUNT=1
	BEGIN
		SET @returnMsg='该类型已存在！'
		SET	@returnCode='0'
		RETURN
	END	
	UPDATE	HR_InterviewDirection 
	SET		Name=@Name,
			Remark=@Remark 
	WHERE	ID = @id
	IF	@@ROWCOUNT=1
	BEGIN
		SET	@returnMsg='修改成功！'
		SET	@returnCode='2'
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-26
	描述：判断该任务是否已分配（废弃）
-------------------------------------------*/
CREATE PROCEDURE Gp_Hr_IsDistribute
(
	@Flag			INT,
	@SysValue		VARCHAR(MAX) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

--DECLARE @sql		NVARCHAR(2000),
--		@durDate	VARCHAR(MAX),
--		@curDate	VARCHAR(MAX),
--		@curValue	VARCHAR(MAX)
		
--SET @curDate = CONVERT(VARCHAR(10),GETDATE(),120)		

--IF @Flag = 1
--BEGIN
--	SET @sql='SELECT @subvalue=password FROM HR_Person WHERE Name = ''00003''' 
--	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @curValue OUT
	
--	SET @sql='SELECT @subvalue=password FROM HR_Person WHERE Name = ''00006''' 
--	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @durDate OUT
	
--	IF @durDate = @curDate
--		SET @SysValue = @curValue
--	ELSE IF @durDate <> @curDate
--		SET @SysValue = '0'
--END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_Hr_ModInterview]    Script Date: 03/16/2011 08:45:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Hr_ModInterview]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Hr_ModInterview]
GO
-- =============================================
-- Author:		王刚
-- Create date: 03/18/2011 
-- Description:	修改面试者信息
-- =============================================
CREATE PROCEDURE [dbo].[Gp_Hr_ModInterview]
(
	@Name VARCHAR(max),
	@Sex bit,
	@Age int,
	@IDCard VARCHAR(MAX),
	@University VARCHAR(MAX),
	@Speciality VARCHAR(MAX),
	@Email VARCHAR(MAX),
	@Phone VARCHAR(MAX),
	@BirthDay DATETIME,
	@Intro VARCHAR(MAX),
	@PersonStatus_ID int,
	@Postion_ID int,
	@Remark VARCHAR(MAX)
)
--@encode$--
AS	
	UPDATE  HR_Person
	SET		Name      		 = @Name,
			Sex	      		 = @Sex,
			Age		  		 = @Age,
			IDCard	  		 = @IDCard,
			University		 = @University,
			Speciality		 = @Speciality,
			Email	  		 = @Email,
			Phone     		 = @Phone,
			BirthDay         = @BirthDay,
			Intro            = @Intro,
			PersonStatus_ID  = @PersonStatus_ID,
			Postion_ID       = @Postion_ID
	WHERE	[IDCard]= @IDCard
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_Hr_ModPerson]    Script Date: 03/16/2011 08:45:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Hr_ModPerson]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_Hr_ModPerson
GO
-- =============================================
-- Author:		王刚
-- Create date: 03/24/2011 
-- Description:	修改人员信息
-- =============================================
CREATE PROCEDURE [dbo].Gp_Hr_ModPerson
(
	@LoginName VARCHAR(MAX),
	@OldName VARCHAR(MAX),
	@Phone VARCHAR(MAX),		--电话
	@Sex bit,					--性别
	@Postion_ID	 int,			--职位
	@Remark VARCHAR(MAX)		--备注
)
--@encode$--
AS	
IF EXISTS(SELECT * FROM HR_Person WHERE LoginName=@LoginName AND @LoginName<>@OldName)
BEGIN
		RAISERROR('姓名重复,请在名字前加区分的标志!',16,1)
		RETURN
	END		
UPDATE  HR_Person
SET		Name	   = @LoginName,
		LoginName  = @LoginName,
		Phone	   = @Phone,
		Sex		   = @Sex,
		Postion_ID = @Postion_ID,
		Remark	   = @Remark
WHERE	LoginName  = @OldName
RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-31
	描述：试用期员工分配任务时人员列表
-------------------------------------------*/
CREATE PROCEDURE GP_HR_ProInfoDistribute
(
	@taskId		VARCHAR(MAX),	---任务ID
	@positionId	VARCHAR(MAX)	---职位ID
)
--@encode$--
AS
SET NOCOUNT ON


SELECT	a.typeId	personID,
		a.FullName	Name,
		b.Name	positionName,
		CASE a.Sex WHEN 1 THEN '男' ELSE '女' END AS Sex
FROM	employee a
INNER JOIN HR_Postion b ON b.ID=a.HrpostionId
WHERE a.typeId NOT in
(	----过滤已领取或已分配啦该任务的人员
	SELECT	Person_ID
	FROM	HR_TaskDistribution
	WHERE	Task_ID=@taskId
)	
AND A.HrpostionId=@positionId AND A.HrPersonStatu=3	---过滤职位不符合要求的人员
RETURN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-26
	描述：查看试用期员工任务的评价
-------------------------------------------*/
CREATE PROCEDURE GP_HR_QueryProTaskEs
(
	@taskID		varchar(MAX),	---任务ID
	@personId	varchar(MAX)	---执行任务的试用期员工
)
--@encode$--
AS
SET NOCOUNT ON

SELECT	a.Content content,
		b.Name hrname,
		a.DateTime Estime
FROM	HR_TaskEstimate a
INNER	JOIN HR_Person b ON a.HR_ID=b.ID
WHERE	a.Person_ID=@personId AND Task_ID=@taskID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_Hr_SaveInterview]    Script Date: 03/16/2011 08:45:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Hr_SaveInterview]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Hr_SaveInterview]
GO
-- =============================================
-- Author:		王刚
-- Create date: 03/17/2011 
-- Description:	添加HR信息
-- =============================================
CREATE PROCEDURE [dbo].[Gp_Hr_SaveInterview]
(
	@Name VARCHAR(MAX),
	@IDCard VARCHAR(MAX),
	@Sex bit,
	@Age int,
	@Speciality VARCHAR(MAX),
	@University VARCHAR(MAX),
	@Email VARCHAR(MAX),
	@Phone VARCHAR(MAX),
	@BirthDay datetime,
	@Intro VARCHAR(MAX),
	@PersonStatus_ID int,
	@Postion_ID int,
	@Remark VARCHAR(MAX)
)
--@encode$--
AS
	IF EXISTS(SELECT IDCard FROM HR_Person WHERE IDCard=@IDCard)
		RETURN -1
		
	INSERT INTO HR_Person
	(
		Name,
		Age,
		IDCard,
		Sex,
		University,
		Speciality,
		Email,
		Phone,
		BirthDay,
		Intro,
		PersonStatus_ID,
		Postion_ID,
		Remark
	)
	VALUES
	(
		@Name,
		@Age,
		@IDCard,
		@Sex,
		@University,
		@Speciality,
		@Email,
		@Phone,
		@BirthDay,
		@Intro,
		@PersonStatus_ID,
		@Postion_ID,
		@Remark
	)
RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_Hr_SavePerson]    Script Date: 03/16/2011 08:45:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Hr_SavePerson]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Hr_SavePerson]
GO
-- =============================================
-- Author:		王刚
-- Create date: 03/24/2011 
-- Description:	添加人员信息
-- =============================================
CREATE PROCEDURE [dbo].Gp_Hr_SavePerson
(
	@LoginName VARCHAR(MAX),	--登陆名
	@Phone VARCHAR(MAX),		--电话
	@Sex bit,					--性别
	@Postion_ID	 int,			--职位
	@Remark VARCHAR(MAX)		--备注
)
--@encode$--
AS
DECLARE @BirthDay AS varchar(max)=''
IF EXISTS(SELECT LoginName FROM HR_Person WHERE LoginName=@LoginName)
	BEGIN
		RAISERROR('姓名重复，请在名字前添加区别的标志',16,1)
		RETURN
	END	
	
BEGIN TRANSACTION TRAN_SAVE	
INSERT INTO HR_Person
(
	Name,
	LoginName,
	Phone,
	Sex,
	BirthDay,
	PersonStatus_ID,
	Postion_ID,
	Remark
)
VALUES
(
	@LoginName,
	@LoginName,
	@Phone,
	@Sex,
	@BirthDay,
	'1',				--人员状态 表示普通操作员
	@Postion_ID,
	@Remark
)

DECLARE 
	@Person_ID INT
	
SELECT	@Person_ID = ID							--得到人员ID存入权限表中
FROM	HR_Person
WHERE	LoginName = @LoginName

INSERT INTO HR_PersonLimit
(
	Person_ID,
	Limit,
	Identifier
)
VALUES
(
	@Person_ID,
	'0000000000000000000000000000000000000000',
	'1'
)

IF (@@ERROR <> 0)
	ROLLBACK TRANSACTION TRAN_SAVE
ELSE
	COMMIT TRANSACTION TRAN_SAVE
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-2
	描述：查看正在执行该任务的员工
-------------------------------------------*/
/*------------------------------------------
	作者：何家福
	日期：2011-6-2
	描述：增加开始时间、结束时间、备注
-------------------------------------------*/
CREATE PROCEDURE GP_HR_ShowProList
(
	@taskID		varchar(MAX)	---任务ID
)
--@encode$--
AS
SET NOCOUNT ON

SELECT a.FullName AS proname,
		c.Name AS positionname,
		b.BeginTime AS startdate,
		b.DeadTime AS enddate,
		b.Remark AS remark
FROM	employee AS a
INNER JOIN HR_TaskDistribution AS b ON b.Person_ID=a.typeId
INNER JOIN	HR_Postion AS c ON a.HrpostionId=c.ID
WHERE	b.Task_ID=@taskID AND B.TaskStatus_ID = '1'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-26
	描述：保存试用期员工任务分配
-------------------------------------------*/
CREATE PROCEDURE GP_HR_TaskDistribute
(
	@taskID		varchar(MAX),	---任务ID
	@personId	varchar(MAX),	---执行任务的试用期员工
	@beginTime	datetime,		---任务开始时间
	@endingTime	datetime,		---任务结束时间
	@remark		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO		HR_TaskDistribution
(
	Task_ID,
	Person_ID,
	TaskStatus_ID,
	BeginTime,
	DeadTime,
	Remark
)
VALUES
(
	@taskID,
	@personId,
	'1',
	@beginTime,
	@endingTime,
	@remark
)
IF @@ROWCOUNT=1
	RETURN 1		----任务分配成功

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'Gp_Hr_TaskToEnd') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure Gp_Hr_TaskToEnd
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-19
	描述：通过任务分配ID修改任务状态
*/
CREATE PROC Gp_Hr_TaskToEnd
(
	  @personname		varchar(max),
      @taskid           int,
      @TaskStatus_ID    int,
      @EndTime          DATETIME
)
--@encode$--      
AS
  UPDATE HR_TaskDistribution
  SET  TaskStatus_ID=@TaskStatus_ID,
       EndTime=@EndTime
  WHERE Task_ID = @taskid AND Person_ID = (SELECT ID 
										   FROM HR_Person 
										   WHERE Name = @personname)
SET NOCOUNT ON


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-03-31
	描述：修改、添加部门信息
*/
CREATE PROCEDURE Gp_HrAddModDept
(
	@id					int,
	@usercode			varchar(MAX),
	@deptname			varchar(MAX),
	@deptremark			varchar(MAX),
	@opType				varchar(MAX)

)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @OldUserCode varchar(max),
		@OldName varchar(max)
SELECT  @OldUserCode=UserCode FROM HR_Department WHERE ID=@id
SELECT  @OldName=Name FROM HR_Department WHERE ID=@id
IF @opType = 'add' 		--新增
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM HR_Department WHERE userCode = @usercode)
			BEGIN
				RAISERROR('部门编号重复，添加失败！',16,1)
				RETURN
			END
		IF EXISTS(SELECT TOP 1 1 FROM HR_Department WHERE Name = @deptname)
			BEGIN
				RAISERROR('部门名称重复，添加失败！',16,1)
				RETURN
			END
		
			INSERT INTO HR_Department
			(
				userCode,
				Name,
				Remark
			)VALUES(
				@usercode,
				@deptname,
				@deptremark
			)		
	END
ELSE IF @opType = 'mod' 	--修改	
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM HR_Department WHERE userCode = @usercode AND Name <> @deptname AND @usercode<>@OldUserCode)
			BEGIN
				RAISERROR('部门编号重复，修改失败！',16,1)
				RETURN
			END
		IF EXISTS(SELECT TOP 1 1 FROM HR_Department WHERE Name = @deptname AND userCode <> @usercode AND @deptname<>@OldName)
			BEGIN
				RAISERROR('部门名称重复，修改失败！',16,1)
				RETURN
			END
				
		UPDATE	HR_Department
		SET		userCode	= @usercode,
				Remark		= @deptremark,
				Name		= @deptname
		WHERE	ID	 		= @id
	END
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** Object:  StoredProcedure [dbo].[Gp_HrAdminMgr]    Script Date: 03/16/2011 14:48:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

/*
	添加HR系统管理员
	时间：2011.3.15
	作者：赵斌
*/

/*
	修改时间：2011.3.16
	修改者：赵斌
	描述：增加修改管理员信息
*/

/*
	修改时间：2011.3.18
	修改者：赵斌
	描述：增加权限控制
*/

CREATE PROCEDURE [dbo].[Gp_HrAdminMgr]
(
	@Name		varchar(MAX),
	@LoginName	varchar(MAX),
	@Password	varchar(MAX),
	@Phone		varchar(MAX),
	@Email		varchar(MAX),
	@Rights		varchar(MAX),
	@Remark		varchar(MAX),	
	@opType		varchar(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

--当页面操作类型为a的时候，新增管理员
IF @opType = 'a'         
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM HR_Administrator WHERE LoginName = @LoginName)
			RETURN -1                       --包含相同登陆名的管理员
						
		INSERT INTO HR_Administrator
		(
			Name,
			LoginName,
			Password,
			Phone,
			Email,
			Rights,
			Remark
		)VALUES(
			@Name,
			@LoginName,
			@Password,
			@Phone,
			@Email,
			@Rights,
			@Remark
		)
		
		IF @@ROWCOUNT = 0
			RETURN -2
	END
ELSE IF @opType = 'm'       --修改管理员信息
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM HR_Administrator WHERE Name = @Name AND [LoginName]<>@LoginName)
			RETURN -1
			
		UPDATE	HR_Administrator
		SET		Name			= @Name,
				Password		= @Password,
				Phone			= @Phone,
				Email			= @Email,
				Remark			= @Remark,
				Rights			= @Rights
		WHERE	LoginName		=@LoginName
		
		IF	@@ROWCOUNT = 0
			RETURN	-2			
	END

RETURN 0

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





/****** Object:  StoredProcedure [dbo].[Gp_HrTaskAddAndEdit]    Script Date: 03/16/2011 15:18:51 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_HrDelDept]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_HrDelDept]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：赵斌
	日期：2011.4.1
	描述：删除部门
*/


CREATE PROCEDURE [dbo].[Gp_HrDelDept]
(
	@id int								--部门id号
)
--@encode$--
AS
	--如果部门存在职位，则不能被删除
IF EXISTS(SELECT TOP 1 1 FROM HR_Postion P INNER JOIN HR_Department D ON P.Department_ID=D.ID
		 WHERE D.ID=@id)
	BEGIN
		RAISERROR('该部门存在职位，不能被删除！',16,1)
		RETURN
	END				
DELETE FROM HR_Department where ID = @id				
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2011-03-17
	描述：职位删除
*/
/*
	修改：赵斌
	日期：2011.4.1
	描述：增加条件判断
*/
/*
	修改：王刚
	日期：2011.12.27
	描述：
*/
CREATE PROCEDURE Gp_HrDelJob
(
	@jobid	int
)
--@encode$--
AS
SET NOCOUNT ON
	IF EXISTS(SELECT TOP 1 1 
			  FROM HR_Person P 
			  WHERE P.postion_ID= @jobid)
		BEGIN
			RAISERROR('该职位存在关联的人员，不能被删除!',16,1)
			RETURN
		END	 
	DELETE FROM Hr_Postion 
	WHERE	ID = @jobid			
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_HrTaskAddAndEdit]    Script Date: 03/16/2011 15:18:51 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_HrDelTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_HrDelTask]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：赵斌
	日期：2011.4.1
	描述：删除任务
*/


CREATE PROCEDURE [dbo].[Gp_HrDelTask]
(
	@Name varchar(MAX)			--任务名称
)
--@encode$--
AS
	--如果有员工没有完成该任务，则不能被删除
IF EXISTS(SELECT TOP 1 1 FROM HR_TaskDistribution TD INNER JOIN HR_Task T ON T.ID = TD.Task_ID
		 WHERE T.Name=@Name AND TD.TaskStatus_ID = 1)
	BEGIN
		RAISERROR('有员工没有完成该任务，不能被删除！',16,1)
		RETURN
	END					
DELETE FROM HR_Task 
WHERE Name = @Name
DELETE FROM HR_TaskDistribution 
WHERE HR_TaskDistribution.Task_ID = (
	SELECT ID 
	FROM HR_Task 
	WHERE Name = @Name)	
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：韩林
	日期：2011-03-16
	描述：添加部门
*/

CREATE PROCEDURE [dbo].[Gp_HrDptAdd]
(
	@name varchar(MAX),
	@remark varchar(MAX)
)
--@encode$--
AS
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Hr_Department WHERE Name=@name)
		RETURN -1
		
	INSERT INTO HR_Department
	(
		Name,
		Remark
	)
	VALUES
	(
		@name,
		@remark
	)
	
	IF @@ROWCOUNT=0
		RETURN -2
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：韩林
	日期：2011-3-31
	描述：保存面试人员的面试次数
-------------------------------------------*/
CREATE PROCEDURE GP_HrEstimateTimes
(
	@person_id int	---人员Id
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM HR_NextEstimateTimes WHERE person_id=@person_id)
	RETURN

INSERT INTO HR_NextEstimateTimes
(
	Person_ID
)
VALUES
(
	@person_Id
)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2011-03-25
	描述：新用户家庭信息添加
*/
CREATE PROCEDURE Gp_HrFamilyAdd
( 
	@person_id int,		
	@id int,		
	@appellation varchar(MAX),	--称谓
	@name varchar(MAX),			
	@company varchar(MAX),		
	@phone varchar(MAX),			
	@remark varchar(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	IF @id!=0
		BEGIN
			UPDATE HR_PersonFamily
			SET	   Appellation=@appellation,
				   Name	      =@name,
				   Company	  =@company,
				   Phone	  =@phone,
				   Remark	  =@remark
			WHERE  ID=@id
			RETURN 
		END
	INSERT INTO HR_PersonFamily
	(
		Person_ID,
		Appellation,
		Name,
		Company,
		Phone,
		Remark
	)
	VALUES
	(
		@person_id,
		@appellation,
		@name,
		@company,
		@phone,
		@remark
	)

	IF @@ROWCOUNT = 0
		BEGIN
			RAISERROR('家庭信息添加失败！',16,1)
			RETURN
		END 	
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2011-03-28
	描述：新用户添加
*/
/*
	修改：何家福	
	日期：2011-03-28
	描述：增加拼音(pycode)字段
*/
CREATE PROCEDURE Gp_HrInterviewersAdd
(	
	@otype	varchar(MAX),
	@person_id int,
	@oldname varchar(MAX),		--原来的名字
	@name varchar(MAX),
	@pycode varchar(MAX),       --姓名拼音
    @sex bit,
    @idcard varchar(MAX),
    @university varchar(MAX),
    @specialty varchar(MAX),	--专业
    @email varchar(MAX),
    @phone varchar(MAX),
    @birthday varchar(MAX),
    @tall int,					--身高
    @postion varchar(MAX),
    @hukou varchar(MAX),			--户口
    @polity varchar(MAX),
    @marriage varchar(MAX),		--婚姻状况
    @degree varchar(MAX),
    @graduatedate varchar(MAX),
    @address varchar(MAX),
    @accessiondate varchar(MAX),
    @oldmonthlypay varchar(MAX),
    @wantpay varchar(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@ID INT,
		@personstaus_id int      --人员状态
IF(@otype='m')	
BEGIN
	IF EXISTS(SELECT * FROM HR_Person WHERE Name=@name AND @name<>@oldname)
		BEGIN
			RAISERROR('姓名重复,请在名字前加区分的标志!',16,1)
			RETURN
		END	
	SELECT @ID=ID FROM HR_Person WHERE Name=@oldname 
	UPDATE HR_Person
	SET	   Postion_ID	=@postion,
		   Name			=@name,
		   PyCode       =@pycode,
		   LoginName	=@name,
		   Sex			=@sex,
		   BirthDay		=CONVERT(char(10),@birthday,120),
		   Tall			=@tall,
		   Hukou		=@hukou,
		   IDCard		=@idcard,
		   Polity		=@polity,
		   Marriage		=@marriage,
		   Degree		=@degree,
		   University	=@university,
		   Speciality	=@specialty,
		   GraduateDate	=@graduatedate,
		   Phone		=@phone,
		   Email		=@email,
		   Address		=@address,
		   AccessionDate=@accessiondate,
		   OldMonthlyPay=@oldmonthlypay,
		   WantPay		=@wantpay
	WHERE  ID			=@ID
	RETURN 
END	

IF(@otype='a')	
BEGIN	
	IF EXISTS(SELECT * FROM HR_Person WHERE Name=@name)
	BEGIN
		RAISERROR('姓名重复,请在名字前加区分的标志!',16,1)
		RETURN
	END	
	BEGIN TRANSACTION TRAN_SAVE		
    SET @personstaus_id=1
	INSERT INTO HR_Person
	(
		Name,
		LoginName,
		PyCode,
		PersonStatus_ID,
		Postion_ID,
		Sex,
		BirthDay,
		Tall,
		Hukou,
		IDCard,
		Polity,
		Marriage,
		Degree,
		University,
		Speciality,
		GraduateDate,
		Phone,
		Email,
		Address,
		AccessionDate,
		OldMonthlyPay,
		WantPay
	)
	VALUES
	(
		@name,
		@name,
		@pycode,
		@personstaus_id,
		@postion,
		@sex,
		CONVERT(char(10),@birthday,120),
		@tall,
		@hukou,
		@idcard,
		@polity,
		@marriage,
		@degree,
		@university,
		@specialty,
		@graduatedate,
		@phone,
		@email,
		@address,
		@accessiondate,
		@oldmonthlypay,
		@wantpay
	)
	
	IF @@ROWCOUNT = 0
		BEGIN
			RAISERROR('基本信息添加失败！',16,1)
			RETURN
		END 


	IF (@person_id = 0)
		BEGIN
			DECLARE	@personid INT
			IF EXISTS (SELECT id FROM HR_Person WHERE Name = @name)
			BEGIN 
				SELECT  @personid= id FROM HR_Person WHERE Name = @name
				UPDATE	HR_Img
				SET		Person_ID  = @personid
				WHERE	Person_ID  = 0
			END			
		END
END

IF (@@ERROR <> 0)
	ROLLBACK TRANSACTION TRAN_SAVE
ELSE
	COMMIT TRANSACTION TRAN_SAVE
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：韩林
	日期：2011-3-31
	描述：保存面试评价信息
-------------------------------------------*/
/*------------------------------------------
	修改：何家福
	日期：2011-6-3
	描述：保存面试所有评价信息
-------------------------------------------*/
CREATE PROCEDURE Gp_HrInterviewEstimateAdd
(
	@count int,			  --评价条数总数
	@icount int,		  --当前评价条数
	@person_id int,	      --人员Id
	@title varchar(MAX),   --评价项目
	@score int,			  --得分
	@content varchar(max),--评价内容
	@hr_id varchar(max)	  --面试官id		
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @times int,		  --当前轮数
		@returnvalue int =1 --返回值
BEGIN
	SELECT  @times=NextTimes+1 FROM HR_NextEstimateTimes
	WHERE	Person_ID=@person_id	
	--IF EXISTS(SELECT TOP 1 1 FROM HR_InterviewerEstimate WHERE Times= @times) AND @icount =1
	--	DELETE FROM HR_InterviewerEstimate WHERE Times=@times	
	INSERT INTO HR_InterviewerEstimate
	(
		Times,
		Title,
		Score,
		Content,
		Person_ID,
		HR_ID
	)
	VALUES
	(
		@times,
		@title,
		@score,
		@content,
		@person_Id,
		@hr_id
	)
	IF @icount=@count
	BEGIN
		UPDATE HR_NextEstimateTimes
		SET	   NextTimes=NextTimes+1
		WHERE  Person_ID=@person_id
		SET	   @returnvalue=0
	END
END
RETURN @returnValue
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：韩林
	日期：2011-4-01
	描述：保存面试评价信息
-------------------------------------------*/
CREATE PROCEDURE Gp_HrInterviewTimes
(
	@person_id int      --面试者Id		
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN
	
	UPDATE HR_NextEstimateTimes
	SET	   NextTimes=NextTimes+1
	WHERE  Person_ID=@person_id
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林 / 王刚
	日期：2011-03-17 / 2011-12-27
	描述：职位添加
*/
CREATE PROCEDURE Gp_HrJobAdd
(
	@dtypeid varchar(50),
	@jobname varchar(MAX),
	@intro varchar(MAX),
	@remark varchar(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM HR_Postion WHERE Name=@jobname AND Department_ID=@dtypeid)
		BEGIN
			RAISERROR('该部门已经存在相同职位，请勿重复添加！',16,1)
			RETURN
		END
	INSERT INTO HR_Postion
	(
		Name,
		Department_ID,
		Intro,
		Remark
	)
	VALUES
	(
		@jobname,
		@dtypeid,
		@intro,
		@remark
	)
	
	IF @@ROWCOUNT=2
		BEGIN
			RAISERROR('职位添加失败，请重试',16,1)
			RETURN
		END
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：韩林
	日期：2011-4-12
	描述：修改人员状态到试用期
*/
CREATE PROC [dbo].Gp_HrModPersonStatus
(
 @ID          int,
 @PersonStatus_ID   INT
)
--@encode$-- 
as

BEGIN TRANSACTION TRAN_SAVE	
UPDATE HR_Person
SET PersonStatus_ID=@PersonStatus_ID
WHERE ID=@ID

INSERT INTO HR_PersonLimit
(
	Person_ID,
	Limit,
	Identifier
)
VALUES
(
	@ID,
	'0000000000000000000000000000000000000000',
	'2'
)

IF (@@ERROR <> 0)
	ROLLBACK TRANSACTION TRAN_SAVE
ELSE
	COMMIT TRANSACTION TRAN_SAVE
GO
  
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2011-03-28
	描述：新用户教育经历添加
*/
CREATE PROCEDURE [dbo].[Gp_HrPersonEduAdd]
( 
	@person_id int,
	@id int,
	@date varchar(MAX),
	@school varchar(MAX),
	@specialty varchar(MAX),
	@degree varchar(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN
	IF @id!=0
		BEGIN
			UPDATE HR_PersonEdu
			SET	   Date		=@date,
				   School	=@school,
				   Specialty=@specialty,
				   Degree   =@degree
			WHERE  ID=@ID
			RETURN 
		END	
	INSERT INTO HR_PersonEdu
	(
		Person_ID,
		Date,
		School,
		Specialty,
		Degree
	)
	VALUES
	(
		@person_id,
		@date,
		@school,
		@specialty,
		@degree
	)

	IF @@ROWCOUNT = 0
		BEGIN
			RAISERROR('教育经历添加失败！',16,1)
			RETURN
		END 
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Web_HrAdminSearch]    Script Date: 03/16/2011 15:13:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_HrPostionEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_HrPostionEdit]
GO

/*
	作者：赵斌 / 王刚
	日期：2011.4.2/ 2011-12-27
	描述：编辑职位
*/
CREATE PROCEDURE [dbo].[Gp_HrPostionEdit]
(
	@jobid			int,						--职位id
	@jobname		varchar(max),				--参数为职位名称
	@dtypeid		varchar(100),				--部门id
	@intro			varchar(max),				--职位说明
	@remark			varchar(max),				--职位备注
	@olddtypeid		varchar(100)				--原来的部门
)
--@encode$--
AS
DECLARE @OldJobName varchar(max)
BEGIN
	IF @dtypeid = @olddtypeid
		BEGIN
			IF EXISTS(SELECT * FROM HR_Postion P WHERE P.Name=@jobname AND P.ID <> @jobid)
				BEGIN
					RAISERROR('本部门已经存在相同名称的职位！',16,1)
					RETURN
				END
			
			UPDATE	HR_Postion
			SET		Name			=	@jobname,
					Department_ID	=	@dtypeid,
					Intro			=	@intro,
					Remark			=	@remark
			WHERE   ID				=	@jobid
			RETURN 0
		END 
	ELSE
		BEGIN
			IF EXISTS(SELECT * FROM HR_Postion P WHERE P.Name=@jobname AND Department_ID = @dtypeid)
				BEGIN
					RAISERROR('该部门已经存在相同名称的职位！',16,1)
					RETURN
				END
				
			DELETE HR_Postion WHERE ID = @jobid
			INSERT INTO HR_Postion
			(
				Name,
				Department_ID,
				Intro,
				Remark
			)
			VALUES
			(
				@jobname,
				@dtypeid,
				@intro,
				@remark
			)
			
			IF @@ROWCOUNT=2
				BEGIN
					RAISERROR('职位添加失败，请重试',16,1)
					RETURN
				END
		END
END

GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER OFF 
GO




/****** Object:  StoredProcedure [dbo].[Gp_HrTaskAddAndEdit]    Script Date: 03/16/2011 15:18:51 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_HrTaskAddAndEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_HrTaskAddAndEdit]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：韩林
	日期：2011.3.16
	描述：任务增加与编辑
*/

/*
	修改：赵斌
	日期：2011.3.25
	描述：修改raiserror处理方式
*/

/*
	修改：赵斌
	日期：2011.3.31
	描述：加入职位
*/

/*
	修改：何家福
	日期：2011.6.1
	描述：加入任务状态
*/

CREATE PROCEDURE [dbo].[Gp_HrTaskAddAndEdit]
(
	@taskid	int,				--任务id
	@Name varchar(MAX),			--任务名称
	@IntendingDays int,			--持续时间
	@Content varchar(MAX),		--内容
	@Remark varchar(MAX),		--备注
	@Postion_ID int,			--所属职位id
	@opType varchar(max)
)
--@encode$--
AS
IF @opType='add'
	BEGIN
	--如果查询到已经存在相同任务名的任务，提示
		IF EXISTS(SELECT TOP 1 1 FROM HR_Task WHERE Name=@Name AND Postion_ID = @Postion_ID)
			BEGIN
				RAISERROR('该职位已经存在相同任务，请重新输入！',16,1)
				RETURN
			END				
		INSERT INTO HR_Task
		(
			Name,
			IntendingDays,
			Content,
			Remark,
			Postion_ID
		)
		VALUES
		(
			@Name,
			@IntendingDays,
			@Content,
			@Remark,
			@Postion_ID
		)
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息添加失败！',16,1)
				RETURN
			END 						
	END
ELSE IF @opType ='mod' 	--修改
	BEGIN	
		IF EXISTS(SELECT TOP 1 1 FROM HR_Task WHERE Name=@Name AND Postion_ID = @Postion_ID AND ID <> @taskid)
			BEGIN
				RAISERROR('该职位已经存在相同任务，请重新输入！',16,1)
				RETURN
			END	
		--更新表	
		UPDATE	HR_Task
		SET	    Name		  = @Name,
				IntendingDays = @IntendingDays,
				Content       = @Content,
				Remark        = @Remark,
				Postion_ID	  = @Postion_ID
		WHERE	ID		  	  = @taskid
		
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息修改失败！',16,1)
				RETURN 
			END
	END
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

/*
	作者：赵斌
	日期：2011.3.24
	描述：查询某个任务由哪些员工在执行
*/
	
CREATE PROCEDURE [dbo].[Gp_HrTaskDistributeStatis]
(
	@Name		varchar(MAX)				--参数为任务名称
)
--@encode$--
AS

--连接三张表进行查询，找出满足条件的任务
--SELECT	P.Name
--FROM	Hr_Person P
--INNER JOIN HR_TaskDistribution T ON P.ID = T.Person_ID
--INNER JOIN HR_Task HT ON (T.Task_ID = HT.Id AND HT.Name = @Name)

SELECT		HP.Name personName,
			D.Name departmentName,
			P.Name postionName,
			HP.Phone personPhone,
			T.Remark remark
FROM		HR_Department D
INNER JOIN	HR_Postion P ON D.ID = P.Department_ID
INNER JOIN	HR_Person HP ON P.ID = HP.Postion_ID
INNER JOIN	HR_TaskDistribution T ON HP.ID = T.Person_ID
INNER JOIN	HR_Task HT ON (T.Task_ID = HT.ID AND HT.Name = @Name)

GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER OFF 
GO




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

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		韩林
-- Create date: 03/23/2011 
-- Description:	为面试者分配用户名
-- =============================================
CREATE PROCEDURE [dbo].[Gp_HrUserNameAdd]
(
	@person_id int,
	@loginname varchar(max),
	@pwd varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @personstatus_id int
BEGIN
	IF EXISTS (SELECT TOP 1 1 FROM HR_Person WHERE LoginName=@loginname)
		BEGIN
			RAISERROR('用户名重复！',16,1)
			RETURN
		END 
	SET	    @personstatus_id=2
	UPDATE  HR_Person
	SET	    LoginName	  =@loginname,
		    password		  =@pwd,
		    PersonStatus_ID=@personstatus_id	  
	WHERE   ID=@person_id
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2011-03-28
	描述：新用户工作经历添加
*/
CREATE PROCEDURE Gp_HrWorkExpAdd
( 
	@person_id int,
	@id int,
	@date varchar(max),
	@company varchar(max),
	@department varchar(max),
	@job varchar(max),
	@dimission varchar(max),  --离职原因
	@proveperson varchar(max), --证明人
	@companyphone varchar(max) 
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN
	IF @id!=0
		BEGIN
			UPDATE HR_PersonWorkExp
			SET	   Date			  =@date,
				   Company		  =@company,
				   Department	  =@department,
				   Job			  =@job,
				   DimissionReason=@dimission,
				   ProvePerson	  =@proveperson,
				   CompanyPhone	  =@companyphone
			WHERE  ID=@id
			RETURN
		END
	INSERT INTO HR_PersonWorkExp
	(
		Person_ID,
		Date,
		Company,
		Department,
		Job,
		DimissionReason,
		ProvePerson,
		CompanyPhone
	)
	VALUES
	(
		@person_id,
		@date,
		@company,
		@department,
		@job,
		@dimission,
		@proveperson,
		@companyphone
	)

	IF @@ROWCOUNT = 0
		BEGIN
			RAISERROR('工作经历添加失败！',16,1)
			RETURN
		END 
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_IfCreateAddBill]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[Gp_IfCreateAddBill]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

----========================
----修改者：黄清
----日期：2013-05-20
----描述：是否可以生成增加单 
----========================
CREATE    PROCEDURE [dbo].[Gp_IfCreateAddBill]
(
	@cardid			[VARCHAR](50),
	@stypeid		[VARCHAR](50),
	@msg			[VARCHAR](200) OUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @AssetsState INT
	
--获取开账期间
DECLARE @FPeriod		 INT,			--分支机构当前财务期间		
		@fyear			 INT
SELECT	TOP 1
		@FPeriod = SubValue 
FROM	sysdata 
WHERE	SubName = 'FPeriod'	


SELECT	TOP 1
		@fyear = SubValue 
FROM	sysdata 
WHERE	SubName = 'fyear'	

--获取指定分支机构当前财务期间		
IF EXISTS (SELECT 1 FROM  dbo.Ac_AccountsPeroid_Stype WHERE Stypeid=@stypeid)
BEGIN
	SELECT	@FPeriod=FPeriod,
			@fyear=FYear
	FROM dbo.Ac_AccountsPeroid_Stype 
	WHERE Stypeid=@stypeid
END

DECLARE @inaccountdate DATETIME
SELECT @inaccountdate=InAccountDate FROM Ac_AssetsCards WHERE Id =@cardid

IF EXISTS(SELECT *FROM Ac_AssetsCards WHERE Id =@cardid AND AssetsState<>2 )
BEGIN
	SET @msg=@msg+'卡片状态不符合要求,不能生成增加单' return -1
	--RAISERROR('%s卡片状态不符合要求,不能生成增加单',16,1,@msg)return -1--return -31
END
IF EXISTS(SELECT 1 FROM Ac_Period WHERE FPeriod=@FPeriod AND FYear=@fyear  AND IsCurrent=1 AND FBegin>@inaccountdate)
BEGIN
	SET @msg=@msg+'入账时间小于当前会计期间开始日期,不能生成增加单' return -1
	--RAISERROR('%s入账时间小于当前会计期间开始日期,不能生成增加单',16,1,@msg)return -1--return -31
END

IF EXISTS(SELECT 1 FROM Ac_Period WHERE FPeriod=@FPeriod AND FYear=@fyear  AND IsCurrent=1 AND FEnd<@inaccountdate)
BEGIN
	SET @msg=@msg+'入账时间大于当前会计期间结束日期,不能生成增加单' return -1
	--RAISERROR('%s入账时间大于当前会计期间结束日期,不能生成增加单',16,1,@msg)return -1--return -31
END

RETURN 0
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_ifDiyBillModify]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_ifDiyBillModify]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-08-02
--	描述：装机配置单修改前判断
---------------------------------------------
CREATE PROCEDURE GP_ifDiyBillModify
( 
	@id		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS (SELECT *FROM DiyIndex WHERE BillNumberId=@id)
BEGIN
	RAISERROR('该装机配置单已不存在，不能修改！',16,1)RETURN -1
END

IF EXISTS(SELECT TOP 1 1 FROM DiyBillTypePSaleTypeID 
          INNER JOIN dbo.BillIndex  b ON b.BillNumberId =  DiyBillTypePSaleTypeID.SalebillNumberId
          WHERE DiyBillTypeId = @id
          AND b.RedWord=0)
BEGIN
	RAISERROR('该装机配置单已被调用，不能修改！',16,1)RETURN -2
END    

     

SELECT	IndexOrderId AS billcode,
		E1.typeId AS etypeid,
		E1.FullName AS efullname,
		D.Comment AS comment,
		e2.FullName AS checkfullname 
FROM DiyIndex D 
INNER JOIN employee E1 ON E1.typeId=D.EtypeId 
INNER JOIN employee E2 ON E2.typeId=D.Checke
WHERE D.BillNumberId=@id
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2011.10.24
	描述：bug 4612
*/
CREATE PROCEDURE Gp_IfUseInpos
(
  @ktypeid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON
--pos模块
if exists(select stockid from CommonPosInfo  where stockid=@ktypeid)
	BEGIN
	  RETURN 1
	END
ELSE 
 RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_IM_Readed_Msg_ToBakTable]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_IM_Readed_Msg_ToBakTable];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2017-02-23
	描述：备份消息记录表
*/
CREATE PROCEDURE Gp_IM_Readed_Msg_ToBakTable
--@encode$--
AS
SET NOCOUNT ON

DECLARE @moveimmesagedays INT

SET @moveimmesagedays = 0

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'moveimmesagedays')
BEGIN
	SELECT TOP 1 @moveimmesagedays = SubValue FROM dbo.sysdata WHERE SubName = 'moveimmesagedays'
END

IF @moveimmesagedays = 0
BEGIN
	INSERT INTO dbo.IM_Message_NoSocket_Bak
	( 
		Title ,
		Content ,
		TypeID ,
		BillCode ,
		BillType ,
		SenderID ,
		SenderName ,
		ReceiverID ,
		ReceiverName ,
		MessageType ,
		CreateDate ,
		IsRead ,
		SenderIP ,
		ReceiverIP ,
		BillNumberId
	)
	SELECT	Title, 
			Content, 
			TypeID, 
			BillCode, 
			BillType, 
			SenderID, 
			SenderName, 
			ReceiverID, 
			ReceiverName, 
			MessageType, 
			CreateDate, 
			IsRead, 
			SenderIP, 
			ReceiverIP, 
			BillNumberId
	FROM	dbo.IM_Message_NoSocket
	WHERE	IsRead = 1	

	--备份成功后删除已读记录
	IF @@ROWCOUNT <> 0
	BEGIN
		DELETE FROM IM_Message_NoSocket WHERE IsRead = 1
	END
END
ELSE
BEGIN
	INSERT INTO dbo.IM_Message_NoSocket_Bak
	( 
		Title ,
		Content ,
		TypeID ,
		BillCode ,
		BillType ,
		SenderID ,
		SenderName ,
		ReceiverID ,
		ReceiverName ,
		MessageType ,
		CreateDate ,
		IsRead ,
		SenderIP ,
		ReceiverIP ,
		BillNumberId
	)
	SELECT	Title, 
			Content, 
			TypeID, 
			BillCode, 
			BillType, 
			SenderID, 
			SenderName, 
			ReceiverID, 
			ReceiverName, 
			MessageType, 
			CreateDate, 
			IsRead, 
			SenderIP, 
			ReceiverIP, 
			BillNumberId
	FROM	dbo.IM_Message_NoSocket
	WHERE	DATEDIFF(DAY,CONVERT(VARCHAR(10),CreateDate,120),GETDATE()) >= @moveimmesagedays	

	--备份成功后删除已读记录
	IF @@ROWCOUNT <> 0
	BEGIN
		DELETE FROM IM_Message_NoSocket WHERE DATEDIFF(DAY,CONVERT(VARCHAR(10),CreateDate,120),GETDATE()) >= @moveimmesagedays
	END
END	
    
GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO    



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_Import_brandCredit]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_Import_brandCredit]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	创建：武智均
	时间：2019-07-02 15:58:23.633
	描述：品牌信用额度导入
*/
CREATE   PROCEDURE [dbo].[Gp_Import_brandCredit]
    (
      @sUserCode VARCHAR(200)='' ,
      @sFullName VARCHAR(200)='' ,
      @brandUserCode VARCHAR(200)='' ,
      @brandFullName VARCHAR(200)='' ,
      @bUserCode VARCHAR(200)='' ,
      @bFullName VARCHAR(200)='' ,
      @credit VARCHAR(18)='',
      @ErrMsg VARCHAR(200) OUTPUT 
    )
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

	SET @sUserCode = LTRIM(RTRIM(@sUserCode))
	SET @sFullName = LTRIM(RTRIM(@sFullName))
	SET @brandUserCode = LTRIM(RTRIM(@brandUserCode))
	SET @brandFullName = LTRIM(RTRIM(@brandFullName))
	SET @bUserCode = LTRIM(RTRIM(@bUserCode))
	SET @bFullName = LTRIM(RTRIM(@bFullName))
	SET @credit = LTRIM(RTRIM(@credit))

	DECLARE @StypeID	VARCHAR (50),
			@BrandtypeID VARCHAR (50), --品牌typeid
			@BtypeID	VARCHAR (50),
			@CreditNum  NUMERIC(24, 10) ,
			@MaxCredit  NUMERIC(24, 10) =999999999999.99,
			@BTypeAll   INT	,	--统一客户供货商
			@proinfo INT -- 判断当前版本  v3:1， a8:2， v1:4 
	SELECT @BTypeAll=Value FROM dbo.Userconfig  WHERE ConfigName='btypeall'
	
	--- v3:1， a8:2， v1:4 
	SELECT @proinfo=subvalue FROM sysdata where subname='proinfo'
	IF(@proinfo <> 2)
	SET @StypeID = '00001'
	
	--分支机构
IF(@proinfo = 2) --v3、v1没有分支机构，所以不用判断参数
BEGIN
	IF(@sUserCode = '' )
	BEGIN
		SET @ErrMsg = '分支机构编号不能为空'
		RETURN -1
	END
	ELSE IF(@sUserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.SType WHERE UserCode = @sUserCode) OR @sUserCode='0')
	BEGIN
		SET @ErrMsg = '分支机构编号不存在'
		RETURN -1
	END
	ELSE IF (@sFullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.SType WHERE FullName = @sFullName) OR @sFullName='总部')
	BEGIN
		SET @ErrMsg = '分支机构名称不存在'
		RETURN -1
	END
	ELSE IF(@sFullName NOT IN (SELECT TOP 1 fullname FROM dbo.SType WHERE UserCode = @sUserCode) AND @sFullName <> '' AND @sUserCode <> '')
	BEGIN
		SET @ErrMsg = '分支机构编号与分支机构名称不匹配'
		RETURN -1
	END
	SELECT @StypeID = typeId  FROM dbo.SType WHERE UserCode = @sUserCode AND  (@sFullName = '' OR (@sFullName <> '' AND				FullName = @sFullName) )
	IF @StypeID IS NULL
	BEGIN
		SET @ErrMsg = '未找到分支机构'
		RETURN -1
	END
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE typeId = @StypeID AND sonnum > 0)
	BEGIN
		SET @ErrMsg = '该分支机构为父类'
		RETURN -1
	END
END
ELSE
 SET @StypeID = '00001'
	--分支机构
	
	--品牌参数验证Begin
	IF(@brandUserCode = '')
	BEGIN
		SET @ErrMsg = '品牌编号不能为空'
		RETURN -1
	END
	ELSE IF(@brandFullName <> '' AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE FullName = @brandFullName))
	BEGIN
		SET @ErrMsg = '品牌名称不存在'
		RETURN -1
	END
	ELSE IF(@brandUserCode <> '' AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE UserCode = @brandUserCode))
	BEGIN
		SET @ErrMsg = '品牌编号不存在'
		RETURN -1
	END
	ELSE IF(@brandFullName <> '' AND @brandUserCode <> '' AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE		UserCode = @brandUserCode AND FullName = @brandFullName))
	BEGIN
		SET @ErrMsg = '品牌编号和品牌名称不匹配'
		RETURN -1
	END
	SELECT @BrandtypeID = TypeId FROM dbo.brandar_Commodity WHERE UserCode = @brandUserCode AND (@brandFullName = '' OR (@brandFullName <> '' AND FullName = @brandFullName))
	IF @BrandtypeID IS NULL
	BEGIN
		SET @ErrMsg = '未找到该品牌'
		RETURN -1
	END
	IF EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE TypeId = @BrandtypeID AND sonnum > 0)
	BEGIN
		SET @ErrMsg = '该品牌为父类'
		RETURN -1
	END
	--品牌参数验证End

	--结算单位
	IF(@bUserCode = '')
	BEGIN
		SET @ErrMsg = '结算单位编号不能为空'
		RETURN -1
	END
	ELSE IF(@bUserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.Btype WHERE UserCode = @bUserCode  AND (LEFT(parid,5)='00001' OR @BTypeAll=1) ) OR @bUserCode='0')
	BEGIN
		SET @ErrMsg = '结算单位编号不存在'
		RETURN -1
	END
	ELSE IF (@bFullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.Btype WHERE FullName = @bFullName  AND (LEFT(parid,5)='00001' OR @BTypeAll=1)))
	BEGIN
		SET @ErrMsg = '结算单位名称不存在'
		RETURN -1
	END
	ELSE IF(@bFullName NOT IN (SELECT TOP 1 fullname FROM dbo.Btype WHERE UserCode = @bUserCode AND (LEFT(parid,5)='00001' OR @BTypeAll=1) AND @bUserCode <> '') AND @bFullName <> '')
	BEGIN
		SET @ErrMsg = '结算单位编号与结算单位名称不匹配'
		RETURN -1
	END
	SELECT @BtypeID = typeId  FROM dbo.Btype WHERE UserCode = @bUserCode AND  (@bFullName = '' OR (@bFullName <> '' AND FullName = @bFullName))
	IF @BtypeID IS NULL
	BEGIN
		SET @ErrMsg = '未找到结算单位'
		RETURN -1
	END
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Btype WHERE typeId = @BtypeID AND sonnum > 0)
	BEGIN
		SET @ErrMsg = '该结算单位为父类'
		RETURN -1
	END
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Btype WHERE typeId = @BtypeID AND IsUseBrandarType <> 1)
	BEGIN
		SET @ErrMsg = '该结算单位没有启用品牌应收强制管理'
		RETURN -1
	END
	--结算单位
	
	--信用额度
	
	IF @credit IS NULL OR @credit = '' 
        SET @CreditNum = NULL
    ELSE IF ( ISNUMERIC(@credit) <> 1 ) 
    BEGIN
        SET @ErrMsg = '信用额度请输入数字'
        RETURN -1
    END
    ELSE IF ( CHARINDEX('-', @credit) <> 0 ) 
    BEGIN
        SET @ErrMsg = '信用额度不能为负数'
        RETURN -1
    END
    ELSE 
    BEGIN
		IF( 2 <( len(@credit)-charindex('.',@credit))AND charindex('.',@credit) > 0)
		BEGIN
			SET @ErrMsg = '信用额度小数位数大于2位'
			RETURN -1
		END
		
		SET @CreditNum = CONVERT( NUMERIC(24, 10) , @credit)
		
		IF(@CreditNum > @MaxCredit)
		BEGIN
			SET @ErrMsg = '信用额度不能大于999999999999.99'
			RETURN -1
		END
    END
    
    IF EXISTS(SELECT 1 FROM dbo.BrandBtype_Credit WHERE StypeId=@StypeID AND BtypeId=@BtypeID AND BrandarTypeId = @BrandtypeID 
				AND Credit = @CreditNum)
	BEGIN
        SET @ErrMsg = '导入数据重复'
        RETURN -1
    END

	DELETE dbo.BrandBtype_Credit WHERE StypeId=@StypeID AND BtypeId=@BtypeID AND BrandarTypeId = @BrandtypeID
	
	IF @CreditNum IS NOT NULL
	BEGIN
		INSERT INTO dbo.BrandBtype_Credit
				( BtypeId, StypeId,BrandarTypeId, Credit )
		VALUES  ( @BtypeID, -- BtypeId - varchar(50)
				  @StypeID, -- StypeId - varchar(50)
				  @BrandtypeID,
				  @CreditNum  -- Credit - numeric 18 ,2
				  )
		IF @@rowcount = 0 
		BEGIN
			SET @ErrMsg = '导入失败'
			RETURN -1
		END
	    ELSE
	    BEGIN
			--修改BType的ARLimit值
	    	UPDATE BType
			SET ARLimit = bb.Credit
			FROM BType b
			INNER JOIN (SELECT BtypeId,StypeId,ISNULL(SUM(Credit),0) Credit FROM BrandBtype_Credit GROUP BY BtypeId,StypeId) bb
			ON bb.BtypeId = @BtypeId and bb.StypeId = @StypeId and bb.Credit > b.ARLimit
			WHERE typeid = @BtypeID AND typeid NOT IN ('00001','00002')
	    
			--修改btype_credit的信用额度
			DECLARE @CreditOld int
			DECLARE @brandCreditOld int
			SELECT  @brandCreditOld = sum(Credit) FROM dbo.BrandBtype_Credit WHERE BtypeId=@BtypeID	AND StypeId=@StypeID
			--存在btype_credit，修改信用额度
			IF EXISTS (SELECT TOP 1 1 FROM dbo.btype_credit WHERE StypeId=@StypeID AND BtypeId=@BtypeID)
			BEGIN
				SELECT  @CreditOld = sum(Credit) FROM dbo.btype_credit WHERE StypeId=@StypeID AND BtypeId=@BtypeID
				IF ISNULL(@CreditOld,0) < @brandCreditOld
				BEGIN
					UPDATE btype_credit 
					SET Credit = @brandCreditOld  
					WHERE StypeId=@StypeID AND BtypeId=@BtypeID
				END
			END
			--没有btype_credit，新增一个
			ELSE
			BEGIN
				INSERT INTO btype_credit( BtypeId, StypeId, Credit )
				VALUES(@BtypeID,@StypeID,@brandCreditOld)
			END
	    END
	END
    
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_Import_Credit]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_Import_Credit]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	修改：唐韬
	时间：2015-04-10 15:10:23.633
	描述：信用额度导入
*/
CREATE   PROCEDURE [dbo].[Gp_Import_Credit]
    (
      @sUserCode VARCHAR(200)='' ,
      @sFullName VARCHAR(200)='' ,
      @bUserCode VARCHAR(200)='' ,
      @bFullName VARCHAR(200)='' ,
      @credit VARCHAR(18)='',
      @ErrMsg VARCHAR(200) OUTPUT 
    )
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

	SET @sUserCode = LTRIM(RTRIM(@sUserCode))
	SET @sFullName = LTRIM(RTRIM(@sFullName))
	SET @bUserCode = LTRIM(RTRIM(@bUserCode))
	SET @bFullName = LTRIM(RTRIM(@bFullName))
	SET @credit = LTRIM(RTRIM(@credit))

	DECLARE @StypeID	VARCHAR (50),
			@BtypeID	VARCHAR (50),
			@CreditNum  NUMERIC(24, 10) ,
			@MaxCredit  NUMERIC(24, 10) =999999999999.99,
			@proinfo    INT,    --版本
			@BTypeAll   INT		--统一客户供货商
	SELECT @BTypeAll=Value FROM dbo.Userconfig  WHERE ConfigName='btypeall'
	
	--- v3:1， a8:2， v1:4 
	SELECT @proinfo=subvalue FROM sysdata where subname='proinfo'
	IF(@proinfo <> 2)
	SET @StypeID = '00001'
	
	IF(@proinfo = 2)
		BEGIN
		--分支机构
		IF(@sUserCode = '' )
		BEGIN
			SET @ErrMsg = '分支机构编号不能为空'
			RETURN -1
		END
		ELSE IF(@sUserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.SType WHERE UserCode = @sUserCode) OR @sUserCode='0')
		BEGIN
			SET @ErrMsg = '分支机构编号不存在'
			RETURN -1
		END
		ELSE IF (@sFullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.SType WHERE FullName = @sFullName) OR @sFullName='总部')
		BEGIN
			SET @ErrMsg = '分支机构名称不存在'
			RETURN -1
		END
		ELSE IF(@sFullName NOT IN (SELECT TOP 1 fullname FROM dbo.SType WHERE UserCode = @sUserCode) AND @sFullName <> '' AND @sUserCode <> '')
		BEGIN
			SET @ErrMsg = '分支机构编号与分支机构名称不匹配'
			RETURN -1
		END
		SELECT @StypeID = typeId  FROM dbo.SType WHERE UserCode = @sUserCode AND (@sFullName = '' OR (@sFullName <> '' AND				FullName = @sFullName) )
		IF @StypeID IS NULL
		BEGIN
			SET @ErrMsg = '未找到分支机构'
			RETURN -1
		END
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE typeId = @StypeID AND sonnum > 0)
		BEGIN
			SET @ErrMsg = '该分支机构为父类'
			RETURN -1
		END
	END
	--分支机构

	--结算单位
	IF(@bUserCode = '')
	BEGIN
		SET @ErrMsg = '结算单位编号不能为空'
		RETURN -1
	END
	ELSE IF(@bUserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.Btype WHERE UserCode = @bUserCode  AND (LEFT(parid,5)='00001' OR @BTypeAll=1) ) OR @bUserCode='0')
	BEGIN
		SET @ErrMsg = '结算单位编号不存在'
		RETURN -1
	END
	ELSE IF (@bFullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.Btype WHERE FullName = @bFullName  AND (LEFT(parid,5)='00001' OR @BTypeAll=1)))
	BEGIN
		SET @ErrMsg = '结算单位名称不存在'
		RETURN -1
	END
	ELSE IF(@bFullName NOT IN (SELECT TOP 1 fullname FROM dbo.Btype WHERE UserCode = @bUserCode AND (LEFT(parid,5)='00001' OR @BTypeAll=1) AND @bUserCode <> '') AND @bFullName <> '')
	BEGIN
		SET @ErrMsg = '结算单位编号与结算单位名称不匹配'
		RETURN -1
	END
	SELECT @BtypeID = typeId  FROM dbo.Btype WHERE UserCode = @bUserCode AND (@bFullName = '' OR (@bFullName <> '' AND FullName = @bFullName))
	IF @BtypeID IS NULL
	BEGIN
		SET @ErrMsg = '未找到结算单位'
		RETURN -1
	END
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Btype WHERE typeId = @BtypeID AND sonnum > 0)
	BEGIN
		SET @ErrMsg = '该结算单位为父类'
		RETURN -1
	END
	--结算单位
	
	--信用额度
	
	IF @credit IS NULL OR @credit = '' 
        SET @CreditNum = NULL
    ELSE IF ( ISNUMERIC(@credit) <> 1 ) 
    BEGIN
        SET @ErrMsg = '信用额度请输入数字'
        RETURN -1
    END
    ELSE IF ( CHARINDEX('-', @credit) <> 0 ) 
    BEGIN
        SET @ErrMsg = '信用额度不能为负数'
        RETURN -1
    END
    ELSE 
    BEGIN
		IF( 2 <( len(@credit)-charindex('.',@credit))AND charindex('.',@credit) > 0)
		BEGIN
			SET @ErrMsg = '信用额度小数位数大于2位'
			RETURN -1
		END
		
		SET @CreditNum = CONVERT( NUMERIC(24, 10) , @credit)
		
		IF(@CreditNum > @MaxCredit)
		BEGIN
			SET @ErrMsg = '信用额度不能大于999999999999.99'
			RETURN -1
		END
    END

	--信用额度
	
	--IF 0 < (SELECT COUNT(1) FROM dbo.btype_credit WHERE StypeId=@StypeID AND BtypeId=@BtypeID)
	--BEGIN
	--	UPDATE btype_credit 
	--	SET Credit = ISNULL(Credit,0) + @CreditNum  
	--	WHERE StypeId=@StypeID AND BtypeId=@BtypeID
	--END
	--ELSE
	--BEGIN
	
	IF EXISTS(SELECT 1 FROM dbo.btype_credit WHERE StypeId=@StypeID AND BtypeId=@BtypeID AND Credit = @CreditNum)
	BEGIN
        SET @ErrMsg = '导入数据重复'
        RETURN -1
    END
	--IF EXISTS(SELECT 1 FROM btype_credit BC
	--			INNER JOIN ( SELECT BtypeId,StypeId,SUM(Credit) Credit FROM BrandBtype_Credit GROUP BY BtypeId,StypeId) A 
	--			ON A.StypeId = BC.StypeID and A.BtypeId = BC.BtypeID
	--			WHERE A.Credit > @CreditNum and BC.BtypeId not in ('00001','00002') AND @Stypeid = BC.StypeId AND BC.BtypeId =					@BtypeID ) 
	--BEGIN
	--	SET @ErrMsg = '信用额度不能低于品牌信用额度!'
	--	RETURN -1
	--END
	
	DELETE dbo.btype_credit WHERE StypeId=@StypeID AND BtypeId=@BtypeID
	
	IF @CreditNum IS NOT NULL
	BEGIN
		INSERT INTO dbo.btype_credit
				( BtypeId, StypeId, Credit )
		VALUES  ( @BtypeID, -- BtypeId - varchar(50)
				  @StypeID, -- StypeId - varchar(50)
				  @CreditNum  -- Credit - numeric 18 ,2
				  )
		IF @@rowcount = 0 
		BEGIN
			SET @ErrMsg = '导入失败'
			RETURN -1
		END
	END
	--END

    
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	固定资产导入
	作    者：	
	修改时间：	2014-12-01
*/
CREATE             PROCEDURE Gp_Import_PPE
(
	@UserCode					VARCHAR(200),--资产编号
	@FullName					VARCHAR(200),--资产名称
	@BarCode					VARCHAR(200),--固定资产条码 
	@STypeUserCode				VARCHAR(200),--分支机构 
	@AssertATypeUserCode		VARCHAR(200),--固定资产科目编号
	@DepATypeUserCode			VARCHAR(200),--累计折旧科目编号
	@DisATypeUserCode			VARCHAR(200),--折旧分配科目编号
	@DevalueATypeUserCode		VARCHAR(200),--减值准备科目编号
	@CategoryUserCode			VARCHAR(200),--资产类别编号
	@Location					VARCHAR(200),--存放地点
	@Size						VARCHAR(200),--规格型号 
	@Units						VARCHAR(200),--计量单位 
	@Condition					VARCHAR(200),--使用状况 
	@DTypeUserCode				VARCHAR(200),--所属部门编号 
	@InAccountDate				DATETIME,--入账日期  
	@BusinessType				VARCHAR(200),--增加方式
	@InAccoutTotal				VARCHAR(50),--入账原值
	@Cid						VARCHAR(200),--币种
	@CurInAccountTotal			VARCHAR(50),--外币原值
	@Rate						VARCHAR(50),--汇率  
	@DepTotal					VARCHAR(50),--累计折旧
	@DevalueReady				VARCHAR(50),--已计提减值准备  
	@NetValue					VARCHAR(50),--净值
	@NetSalvageRate				VARCHAR(50),--预计净残值率%  
	@NetSalvage					VARCHAR(50),--预计净残值  
	@DepreciationMean			VARCHAR(200),--折旧方法 
--	@DurYear					VARCHAR(50),--预计使用年限  
	@DepreciationMonth			VARCHAR(50),--已计提月份数  
	@PreMonth					VARCHAR(50),--预计使用月份数
	@ExpectWork					VARCHAR(50),--预计工作总量  
	@WorkTime					VARCHAR(50),--已提工作量  
	@WorkUnit					VARCHAR(50),--工作量单位
	@Comment					VARCHAR(500),--备注
	@Qty						VARCHAR(50), --资产数量
	--@ETypeID					VARCHAR(50),--操作员
	@ErrMsg						VARCHAR(200) OUTPUT --出错信息
)
--@encode$--
AS
	SET NOCOUNT ON
	
/*
固定资产相关表
Ac_AssetBusinessType			业务类型	
Ac_AssetsCards					固定资产卡片	
Ac_AssetsCards_History			固定资产卡片历史数据
Ac_AssetsCardsState				固定资产卡片状态	
Ac_AssetsCategory				资产类别	
Ac_Account						会计科目表,Fdc	余额借贷方向：1.借 -1.贷
Ac_AssetStorageLocation			资产存放地点
Ac_FixedAssetsInit_Stype		固定资产初始化

SET @ErrMsg=''
RETURN -1
*/

DECLARE
	@STypeId				VARCHAR(50),--分支机构，如果是非独立的，则查出独立的分支机构
	@IsUseAcSystem			INT,--是否使用总账,1表示使用,
	@Proinfo				INT--1=V3, 2=A8

SELECT @Proinfo=SubValue 
FROM sysdata
WHERE SubName='Proinfo'
	
DECLARE
	@AssertATypeId			VARCHAR(50),
	@DepATypeId				VARCHAR(50),
	@DisATypeId				VARCHAR(50),
	@DevalueATypeId			VARCHAR(50)='',
	@CategoryId				INT,
	@LocationId				INT,
	@ConditionId			INT,
	@DTypeid				VARCHAR(50),
	@BusinessTypeId			INT,
	@AssetsState			INT,
	@intCID					INT	,
	@DurYear				INT,--预计使用年限  
	@durmonth				INT

IF ( ISNUMERIC(@PreMonth) <>1 ) 
BEGIN
    SET @ErrMsg = '预计使用月份请输入数字'
    RETURN -1
END	


SET @durmonth=@PreMonth%12
SET @duryear=@PreMonth/12
/*
数值型,整数型的基本校验

*/	
DECLARE
	@decInAccoutTotal				 NUMERIC(24, 10) ,--入账原值
	@decCurInAccountTotal			 NUMERIC(24, 10) ,--外币原值
	@decRate						 NUMERIC(24, 10) ,--汇率  
	@decDepTotal					 NUMERIC(24, 10) ,--累计折旧
	@decDevalueReady				 NUMERIC(24, 10) ,--已计提减值准备  
	@decNetValue					 NUMERIC(24, 10) ,--净值
	@decNetSalvageRate				 NUMERIC(24, 10) ,--预计净残值率%  
	@decNetSalvage					 NUMERIC(24, 10) ,--预计净残值  
	@intDurYear						INT,--预计使用年限  
	@intDepreciationMonth			INT,--已计提月份数  
	@intPreMonth					INT,--预计使用月份数
	@intExpectWork					VARCHAR(50),--预计工作总量  
	@intWorkTime					 NUMERIC(24, 10) --已提工作量  

SELECT
	@InAccoutTotal=ISNULL(@InAccoutTotal,'0'),
	@CurInAccountTotal=ISNULL(@CurInAccountTotal,'0'),
	@Rate=ISNULL(@Rate,'0'),
	@DepTotal=ISNULL(@DepTotal,'0'),
	@DevalueReady=ISNULL(@DevalueReady,'0'),
	@NetValue=ISNULL(@NetValue,'0'),
	@NetSalvageRate=ISNULL(@NetSalvageRate,'0'),
	@NetSalvage=ISNULL(@NetSalvage,'0'),
	@DurYear=ISNULL(@DurYear,'0'),
	@DepreciationMonth=ISNULL(@DepreciationMonth,'0'),
	@PreMonth=ISNULL(@PreMonth,'0'),
	@ExpectWork=ISNULL(@ExpectWork,'0'),
	@WorkTime=ISNULL(@WorkTime,'0')


IF ( @duryear <1 ) 
BEGIN
    SET @ErrMsg = '预计使用月份必须大于等于12!'
    RETURN -1
END



IF ( ISNUMERIC(@InAccoutTotal) <> 1  ) OR @InAccoutTotal = '0' 
BEGIN
    SET @ErrMsg = '入账原值请输入数字!'
    RETURN -1
END


IF ( ISNUMERIC(@CurInAccountTotal) <> 1 OR @CurInAccountTotal = '0') 
BEGIN
    SET @ErrMsg = '外币原值请输入数字!'
    RETURN -1
END


IF ( ISNUMERIC(@Rate) <> 1 ) 
BEGIN
    SET @ErrMsg = '汇率请输入数字!'
    RETURN -1
END


IF ( ISNUMERIC(@DepTotal) <> 1 ) 
BEGIN
    SET @ErrMsg = '累计折旧请输入数字!'
    RETURN -1
END


IF ( ISNUMERIC(@DevalueReady) <> 1 ) 
BEGIN
    SET @ErrMsg = '已计提减值准备请输入数字!'
    RETURN -1
END

IF ( ISNUMERIC(@NetValue) <> 1 ) 
BEGIN
    SET @ErrMsg = '净值请输入数字!'
    RETURN -1
END

IF ( ISNUMERIC(@NetSalvageRate) <> 1 ) 
BEGIN
    SET @ErrMsg = '预计净残值率%请输入数字!'
    RETURN -1
END

IF ( ISNUMERIC(@NetSalvage) <> 1 ) 
BEGIN
    SET @ErrMsg = '预计净残值请输入数字!'
    RETURN -1
END

IF ( ISNUMERIC(@DurYear) <> 1 ) 
BEGIN
    SET @ErrMsg = '预计使用年限请输入数字!'
    RETURN -1
END

IF ( ISNUMERIC(@DepreciationMonth) <> 1 ) 
BEGIN
    SET @ErrMsg = '已计提月份数请输入数字!'
    RETURN -1
END

IF ( ISNUMERIC(@PreMonth) <> 1 ) 
BEGIN
    SET @ErrMsg = '预计使用月份数请输入数字!'
    RETURN -1
END


--折旧方法	必填	检测折旧方法是否存在
IF LTRIM(RTRIM(@DepreciationMean))=''
BEGIN
	SET @ErrMsg='折旧方法必填！'
	RETURN -1
END

DECLARE
	@intDepreciationMean	INT --折旧方法对应的ID
	
SELECT 	@intDepreciationMean=0

IF NOT EXISTS(
	SELECT ID
	FROM Ac_DepreciationMean
	WHERE Comment=@DepreciationMean
)
BEGIN
	SET @ErrMsg='该折旧方法不存在！'
	RETURN -1
END
ELSE
BEGIN
	SELECT @intDepreciationMean=ID
	FROM Ac_DepreciationMean
	WHERE Comment=@DepreciationMean
END

IF @intDepreciationMean = 5 
BEGIN
	IF ( ISNUMERIC(@ExpectWork) <> 1 ) 
	BEGIN
		SET @ErrMsg = '预计工作总量请输入数字!'
		RETURN -1
	END

	IF ( ISNUMERIC(@WorkTime) <> 1 ) 
	BEGIN
		SET @ErrMsg = '已提工作量请输入数字!'
		RETURN -1
	END
	
	IF CHARINDEX('.', @WorkTime)> 0 
	BEGIN
		IF (LEN(@WorkTime)-CHARINDEX('.',@WorkTime)>2)
		BEGIN
			SET @ErrMsg = '已提工作量且必须是大于0的数值，不超过2位小数！'
			RETURN -1
		END
	END
END
ELSE
BEGIN
	IF(LTRIM(RTRIM(@WorkTime))<>'')
	BEGIN
		SET @ErrMsg = '折旧方式为“工作量法”时已提工作量为必填，否则不能填'
		RETURN -1
	END
END

--判断整数

IF CHARINDEX('.', @DurYear)<> 0 
BEGIN
    SET @ErrMsg = '预计使用年限请输入整数!'
    RETURN -1
END

IF CHARINDEX('.', @DepreciationMonth)<> 0 
BEGIN
    SET @ErrMsg = '已计提月份数请输入整数!'
    RETURN -1
END

IF CHARINDEX('.',@PreMonth )<> 0 
BEGIN
    SET @ErrMsg = '预计使用月份数请输入整数!'
    RETURN -1
END

--IF CHARINDEX('.', @ExpectWork)<> 0 
--BEGIN
--    SET @ErrMsg = '预计工作总量请输入整数!'
--    RETURN -1
--END

--IF @intDepreciationMean=5 
--BEGIN
--IF CHARINDEX('.', @ExpectWork)> 0 
--	BEGIN
--		IF (LEN(@ExpectWork)-CHARINDEX('.',@ExpectWork)>2)
--		BEGIN
--			SET @ErrMsg = '预计工作总量小数位数不超过2位小数！'
--			RETURN -1
--		END
--	END
--END 

--'双倍余额递减法'
IF @intDepreciationMean = 3 AND @PreMonth<36
BEGIN
	SET @ErrMsg = '若折旧方法为双倍余额递减法时,预计使用月份数不能小于36个月!'
	RETURN -1
END 

--分支机构编号	必填，V3不需要检查此字段	检测分支机构基础资料是否存在
IF @Proinfo=2
BEGIN
	IF NOT EXISTS(
		SELECT TypeId
		FROM SType
		WHERE UserCode=@STypeUserCode AND sonnum=0
	)
	BEGIN
		SET @ErrMsg='系统中不存在该分支机构！'
		RETURN -1
	END
END
ELSE
BEGIN
	SET @STypeId='00001'
END

DECLARE
	@InputSTypeID	VARCHAR(50)	

IF @Proinfo=2
BEGIN
	SELECT
		@STypeId=TypeID,@InputSTypeID=TypeId
	FROM SType
	WHERE UserCode=@STypeUserCode
	
	IF EXISTS(
		SELECT TypeID
		FROM SType
		WHERE TypeId=@STypeId AND IsSelfVerify=0
	)
	BEGIN
		SELECT @STypeId=VerifyID
		FROM SType
		WHERE TypeId=@STypeId
	END		
END
ELSE
BEGIN
	SET @InputSTypeID='00001'
END

--未初始化的分支机构导入卡片后，状态为初始
--已初始化的分支机构导入卡片后，状态为未入账
--对应表：Ac_AssetsCardsState
IF EXISTS(
	SELECT ID
	FROM Ac_FixedAssetsInit_Stype a
	WHERE a.StypeId=@STypeId
)
BEGIN
	--已初始化 2未入账
	SET @AssetsState=2
END
ELSE
BEGIN
	--未初始化 1 初始
	SET @AssetsState=1
END	


IF @BusinessType IN ('购入（原值含税）','购入（原值不含税）','自建工程') AND  @DepTotal <> '0' AND @AssetsState=2
BEGIN
	SET @ErrMsg = '若增加方式为【购入（原值含税）】，【购入（原值不含税）】，【自建工程】，累计折旧值应该为0!'
	RETURN -1
END 


IF LTRIM(RTRIM(@WorkTime))=''
BEGIN
	SET @WorkTime = '0'
END
SELECT
	@decInAccoutTotal=CAST(@InAccoutTotal AS  NUMERIC(24, 10) ),
	@decCurInAccountTotal=CAST(@CurInAccountTotal AS  NUMERIC(24, 10) ),
	@decRate=CAST(@Rate AS  NUMERIC(24, 10) ),
	@decDepTotal=CAST(@DepTotal AS  NUMERIC(24, 10) ),
	@decDevalueReady=CAST(@DevalueReady AS  NUMERIC(24, 10) ),
	@decNetValue=CAST(@NetValue AS  NUMERIC(24, 10) ),
	@decNetSalvageRate=CAST(@NetSalvageRate AS  NUMERIC(24, 10) ),
	@decNetSalvage=CAST(@NetSalvage AS  NUMERIC(24, 10) ) ,
	@intDurYear=CAST(@DurYear AS INT),
	@intDepreciationMonth=CAST(@DepreciationMonth AS INT),
	@intPreMonth=CAST(@PreMonth AS INT),
	--@intExpectWork=CAST(@ExpectWork AS INT),
	@intWorkTime=CAST(@WorkTime AS  NUMERIC(24, 10) )

--资产编号	必填	检测是否已存在重名的编号
IF LTRIM(RTRIM(@UserCode))=''
BEGIN
	SET @ErrMsg='资产编号必填！'
	RETURN -1
END

IF EXISTS(
	SELECT ID
	FROM Ac_AssetsCards
	WHERE UserCode=@UserCode
)
BEGIN
	SET @ErrMsg='已存在该资产编号！'
	RETURN -1
END


--资产名称	必填	文本
IF LTRIM(RTRIM(@FullName))=''
BEGIN
	SET @ErrMsg='资产名称必填！'
	RETURN -1
END

SELECT @BarCode=ISNULL(@Barcode,'')

--固定资产条码	非必填	检测是否已存在重复的条码
IF EXISTS(
	SELECT ID
	FROM Ac_AssetsCards
	WHERE BarCode=@BarCode AND ISNULL(@BarCode,'')<>''
)
BEGIN
	SET @ErrMsg='已存在该条码！'
	RETURN -1
END

SELECT @IsUseAcSystem=CAST(SubValue AS Int)
FROM dbo.sysdata 
WHERE SubName = 'IsUseAcSystem'






--固定资产科目编号①	必填	检测科目编号在对应分支机构是否存在，科目类别必须为“资产”，余额方向为“借”
IF @IsUseAcSystem=1
BEGIN
	IF LTRIM(RTRIM(@AssertATypeUserCode))=''
	BEGIN
		SET @ErrMsg='固定资产科目编号必填！'
		RETURN -1
	END

	IF NOT EXISTS(
		SELECT a.TypeId
		FROM Ac_Account a
		WHERE a.UserCode=@AssertATypeUserCode
		AND a.StypeId=@STypeId
		AND a.Fdc=1
		AND LEFT(a.TypeId,5)='00001'
	)
	BEGIN
		SET @ErrMsg='该固定资产科目编号不满足条件：科目编号必须在对应分支机构存在，科目类别必须为资产，余额方向为借，请检查！'
		RETURN -1
	END
END

--累计折旧科目编号	必填	检测科目编号在对应分支机构是否存在，科目类别必须为“资产”，余额方向为“贷”
IF @IsUseAcSystem=1
BEGIN
	IF LTRIM(RTRIM(@DepATypeUserCode))=''
	BEGIN
		SET @ErrMsg='累计折旧科目编号必填！'
		RETURN -1
	END

	IF NOT EXISTS(
		SELECT a.TypeId
		FROM Ac_Account a
		WHERE a.UserCode=@DepATypeUserCode
		AND a.StypeId=@STypeId
		AND a.Fdc=-1
		AND LEFT(a.TypeId,5)='00001'
	)
	BEGIN
		SET @ErrMsg='该累计折旧科目编号不满足条件：科目编号必须在对应分支机构存在，科目类别必须为资产，余额方向为贷，请检查！'
		RETURN -1
	END
END

--折旧分配科目编号	必填	检测科目编号在对应分支机构是否存在，折旧分配科目，科目类别必须为非“资产类”
IF @IsUseAcSystem=1
BEGIN
	IF LTRIM(RTRIM(@DisATypeUserCode))=''
	BEGIN
		SET @ErrMsg='折旧分配科目编号必填！'
		RETURN -1
	END

	IF NOT EXISTS(
		SELECT a.TypeId
		FROM Ac_Account a
		WHERE a.UserCode=@DisATypeUserCode
		AND a.StypeId=@STypeId
		AND LEFT(a.TypeId,5)<>'00001'
	)
	BEGIN
		SET @ErrMsg='该折旧分配科目编号不满足条件：科目编号必须在对应分支机构存在，科目类别必须为非资产，请检查！'
		RETURN -1
	END
END

--减值准备科目编号	非必填	检测科目编号在对应分支机构是否存在，科目类别必须为“资产”，余额方向为“贷”
IF @IsUseAcSystem=1
BEGIN
	IF LTRIM(RTRIM(@DevalueATypeUserCode))<>'' AND NOT EXISTS(
		SELECT a.TypeId
		FROM Ac_Account a
		WHERE a.UserCode=@DevalueATypeUserCode
		AND a.StypeId=@STypeId
		AND a.Fdc=-1
		AND LEFT(a.TypeId,5)='00001'
	)
	BEGIN
		SET @ErrMsg='该减值准备科目编号不满足条件：科目编号必须在对应分支机构存在，科目类别必须为资产，余额方向为贷，请检查！'
		RETURN -1
	END
END

--资产类别编号	必填	检测是否存在且与所填分支机构匹配
/*
注意资产类别上的分支机构为“独立核算分支机构”，固定资产卡片上的分支机构是“实体分支机构”，要按照其从属关系，对可选资产类别进行判定，具体方法如下：
从当前所填的分支机构查到其记账分支机构（若是独立核算的分支机构，记账分支机构就是其本身），然后再查是否是在记账分支机构对应的资产类别中
*/

IF LTRIM(RTRIM(@CategoryUserCode))=''
BEGIN
	SET @ErrMsg='资产类别编号必填！'
	RETURN -1
END


IF NOT EXISTS(
	SELECT a.Id 
	FROM Ac_AssetsCategory a
	WHERE a.UserCode=@CategoryUserCode
	AND a.StypeId=@STypeId
)
BEGIN
	SET @ErrMsg='资产类别编号不存在，或与分支机构不匹配！'
	RETURN -1
END

--存放地点	非必填	要与已存在的基础资料相匹配
IF LTRIM(RTRIM(@Location))<>''
AND NOT EXISTS(
	SELECT ID
	FROM Ac_AssetStorageLocation
	WHERE Location=@Location
)
BEGIN
	SET @ErrMsg='存放地点不存在！'
	RETURN -1
END



--规格型号	非必填	文本
--计量单位	非必填	文本


--使用状况	非必填	要与已建的基础资料相匹配
IF LTRIM(RTRIM(@Condition))<>''
AND NOT EXISTS(
	SELECT ID
	FROM Ac_AssetWorkingCondition
	WHERE Comment=@Condition
)
BEGIN
	SET @ErrMsg='使用状况不存在！'
	RETURN -1
END



--所属部门编号	必填	检测部门编号是否存在，是否属于所填分支机构？？

IF LTRIM(RTRIM(@DTypeUserCode))=''
BEGIN
	SET @ErrMsg='所属部门编号必填！'
	RETURN -1
END

IF NOT EXISTS(
	SELECT typeid
	FROM Department
	WHERE usercode=@DTypeUserCode
)
BEGIN
	SET @ErrMsg='所属部门编号不存在！'
	RETURN -1
END




--入账日期	必填	分支机构未初始：入账日期只能是起始会计期间之前的日期；分支机构已初始：入账日期只能是起始会计期之后的日期
DECLARE
	@datIniDate	DATETIME,
	@FPERIOD	INT,
	@FYear		INT
	
	
--SELECT @FPERIOD=CAST(SUBVALUE AS Int) 
--FROM dbo.sysdata 
--WHERE SubName = 'fperiod'	

--SELECT @FYear=CAST(SUBVALUE AS Int) 
--FROM dbo.sysdata 
--WHERE SubName = 'fyear'	

SELECT	@FYear=SFYear,
		@FPERIOD=SFPeriod
FROM	Ac_AccountsPeroid_Stype 
WHERE	Stypeid = @STypeId


IF EXISTS(
	SELECT ID
	FROM Ac_FixedAssetsInit_Stype a
	WHERE a.StypeId=@STypeId
)
BEGIN
	SELECT	@datIniDate=FBegin
	FROM	Ac_Period
	WHERE	FPeriod=@FPERIOD
			AND FYear=@FYear
	
	IF @InAccountDate < @datIniDate
	BEGIN
		SET @ErrMsg='分支机构已初始：入账日期只能是起始会计期之后的日期!'
		RETURN -1
	END
END
ELSE
BEGIN
	--未初始化
	 IF EXISTS(SELECT stypeid FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId)
	 BEGIN
		SELECT  @datIniDate = a.FBegin 
		FROM Ac_Period a JOIN dbo.Ac_AccountsPeroid_Stype b
		ON( a.FYear = b.SFYear AND a.FPeriod = b.SFPeriod)
		AND b.Stypeid = @STypeId
	 END
	 ELSE
	 BEGIN
		SELECT	@datIniDate=FBegin
		FROM	Ac_Period
		WHERE	FPeriod=@FPERIOD
				AND FYear=@FYear
	 END
	
	IF @InAccountDate >= @datIniDate
	BEGIN
		SET @ErrMsg='分支机构未初始：入账日期只能是起始会计期间之前的日期!'
		RETURN -1
	END
END

--增加方式	必填	判断是否存在，是否启用
IF LTRIM(RTRIM(@BusinessType))=''
BEGIN
	SET @ErrMsg='增加方式必填！'
	RETURN -1
END

IF NOT EXISTS(
	SELECT ID
	FROM Ac_AssetBusinessType
	WHERE FullName=@BusinessType AND Deleted=1
)
BEGIN
	SET @ErrMsg='增加方式不存在或未启用！'
	RETURN -1
END

--入账原值	必填	检测是否为正数值类型
IF @decCurInAccountTotal<0
BEGIN
	SET @ErrMsg='入账原值必须是正数！'
	RETURN -1
END

--币种	必填	检测币种是否存在
IF LTRIM(RTRIM(@Cid))=''
BEGIN
	SET @ErrMsg='币种必填！'
	RETURN -1
END

IF NOT EXISTS(
	SELECT CId
	FROM Ac_Currency
	WHERE UserCode=@Cid
)
BEGIN
	SET @ErrMsg='币种不存在！'
	RETURN -1
END
ELSE
BEGIN
	SELECT @intCId=CId
	FROM Ac_Currency
	WHERE UserCode=@Cid
END





--汇率	必填	检测是否为正数值，若币种是本位币汇率必须为1
IF @decRate<=0 OR @decRate<>ROUND(@decRate,4)
BEGIN
	SET @ErrMsg='汇率必须是正数，且不超过4位小数！'
	RETURN -1
END

IF EXISTS(
	SELECT CId
	FROM Ac_Currency
	WHERE UserCode=@Cid
	AND Sysrow=1
	AND @decRate<>1
)
BEGIN
	SET @ErrMsg='本位币汇率必须为1！'
	RETURN -1
END

--外币原值	必填	根据系统的外币折算方式，判断是否满足：外币原值=入账原值/汇率  或者 外币原值=入账原值*汇率
IF  EXISTS(
	SELECT CId
	FROM Ac_Currency
	WHERE UserCode=@Cid
	AND BasisType=0
)
BEGIN
	--乘以汇率
	IF @decCurInAccountTotal<>ROUND(@decInAccoutTotal/@decRate,4)
	BEGIN
		SET @ErrMsg='不满足：外币原值=入账原值/汇率的公式！'
		RETURN -1
	END
END

IF  EXISTS(
	SELECT CId
	FROM Ac_Currency
	WHERE UserCode=@Cid
	AND BasisType=1
)
BEGIN
	--除以汇率
	IF @decCurInAccountTotal<>ROUND(@decInAccoutTotal*(@decRate*1.0),2)
	BEGIN
		SET @ErrMsg='不满足：外币原值=入账原值*汇率的公式！'
		RETURN -1
	END
END

--累计折旧	必填	检测是否为数值且大于等于0
IF @decDepTotal<0
BEGIN
	SET @ErrMsg='累计折旧必须大于等于0！'
	RETURN -1
END

--已计提减值准备	必填	分支机构未初始：检测是否为数值且大于等于0，分支机构已初始：只能为0
IF EXISTS(
	SELECT ID
	FROM Ac_FixedAssetsInit_Stype a
	WHERE a.StypeId=@STypeId
)
BEGIN
	IF @decDevalueReady<>0
	BEGIN
		SET @ErrMsg='分支机构已初始化，已计提减值准备只能为0！'
		RETURN -1
	END
END
ELSE
BEGIN
	IF @decDevalueReady<0
	BEGIN
		SET @ErrMsg='分支机构未初始化，已计提减值准备必须大于等于0！'
		RETURN -1
	END
END



--净值	必填	检测是否为数值且大于等于0
IF @decNetValue<0
BEGIN
	SET @ErrMsg='净值必须大于等于0！'
	RETURN -1
END


--检测是否满足 净值=入账原值-累计折旧-减值准备
IF @decNetValue<>@decInAccoutTotal-@decDepTotal-@decDevalueReady
BEGIN
	SET @ErrMsg='不满足净值=入账原值-累计折旧-减值准备的公式！'
	RETURN -1
END


--预计净残值率%	必填	有效值在0到50

IF @decNetSalvageRate<0 OR @decNetSalvageRate>50 OR @decNetSalvageRate<>ROUND(@decNetSalvageRate,4)
BEGIN
	SET @ErrMsg='预计净残值率必须在[0,50]，且不超过4位小数！'
	RETURN -1
END

--预计净残值	必填	检测是否为数值且大于等于0
IF @decNetSalvage<0
BEGIN
	SET @ErrMsg='预计净残值必须大于等于0！'
	RETURN -1
END
IF @decNetSalvage<>ROUND(@decNetSalvage,2)
BEGIN
	SET @ErrMsg='预计净残值必须大于等于0，且不超过2位小数！'
	RETURN -1
END


--检测是否满足 预计净残值=入账原值*预计净残值率
IF @decNetSalvage<>ROUND(@decInAccoutTotal*@decNetSalvageRate*0.01,2)
BEGIN
	SET @ErrMsg='不满足预计净残值=入账原值*预计净残值率这个公式！'
	RETURN -1
END


--预计使用年限	必填	录入，只能填大于0，小于30的整数
IF @intDurYear<0 OR @intDurYear>30
BEGIN
	SET @ErrMsg='预计使用年限必须在[0,30]！'
	RETURN -1
END

----若折旧方法选取双倍余额递减法时，预计使用年限必须是大于2的正数
--IF @intDepreciationMean=3  AND @intDurYear%2<>0  --双倍余额递减法
--BEGIN
--	SET @ErrMsg='若折旧方法选取双倍余额递减法时，预计使用年限必须是大于2的正数！'
--	RETURN -1
--END

----预计使用月份数 必填  按照预计使用年限*12 校验
--IF @intPreMonth <> @intDurYear * 12
--BEGIN
--	SET @ErrMsg='不满足预计使用月份数=预计使用年限*12的公式！'
--	RETURN -1
--END

--已计提月份数	必填	已计提月份数要小于预计使用月份数,只能填大于0的整数

IF @intDepreciationMonth<0 OR @intDepreciationMonth>@intPreMonth OR @intDepreciationMonth<>ROUND(@intDepreciationMonth,0)
BEGIN
	SET @ErrMsg='已计提月份数只能是小于预计使用月份数，且大于等于0的整数！'
	RETURN -1
END
 
--工作量法，@intDepreciationMean=5 

--预计工作总量		折旧方式为“工作量法”为必填，否则不能填,大于0的数值类型，不超过2位小数
IF @intDepreciationMean=5 
BEGIN
	IF @intExpectWork<0 OR @intExpectWork<>ROUND(@intExpectWork,2)
	BEGIN
		SET @ErrMsg='当折旧方式为工作量法时，预计工作量必填，且必须是大于0的数值，不超过2位小数！'
		RETURN -1
	END
END

--已提工作量		折旧方式为“工作量法”为必填，否则不能填,大于等于0的数值类型，不超过2位小数，不能大于预计工作量
IF @intDepreciationMean=5 
BEGIN
	IF @intWorkTime<0 OR @intWorkTime<ROUND(@intWorkTime,2) OR @WorkTime>@ExpectWork
	BEGIN
		SET @ErrMsg='当折旧方式为工作量法时，已提工作量必填，不能大于预计工作量，且必须是大于0的数值，不超过2位小数！'
		RETURN -1
	END
END
--工作量单位		折旧方式为“工作量法”为可填，否则不能填,文本
IF @intDepreciationMean<>5 
BEGIN
	SET @WorkUnit=NULL
END

--备注	非必填	非必填
IF LTRIM(RTRIM(@Comment)) <> ''	
BEGIN
	SET @Comment = LTRIM(RTRIM(@Comment))
	DECLARE @CommentLength INT
    SELECT @CommentLength = DATALENGTH(@Comment)
	IF(@CommentLength > 250)
	BEGIN
		SET @ErrMsg='备注内容的长度（'+CONVERT(VARCHAR(4),@CommentLength)+'）超过了250个字符（一个汉字算两个字符）！'
		RETURN -1
	END
END
--固定资产科目编号的判断


	


	
	
	

SELECT @AssertATypeId=a.TypeId
FROM Ac_Account a
WHERE a.UserCode=@AssertATypeUserCode
AND a.StypeId=@STypeId	

SELECT @DepATypeId=a.TypeId
FROM Ac_Account a
WHERE a.UserCode=@DepATypeUserCode
AND a.StypeId=@STypeId	

SELECT @DisATypeId=a.TypeId
FROM Ac_Account a
WHERE a.UserCode=@DisATypeUserCode
AND a.StypeId=@STypeId	

IF LTRIM(RTRIM(@DevalueATypeUserCode))<>''
BEGIN
	SELECT @DevalueATypeId=a.TypeId
	FROM Ac_Account a
	WHERE a.UserCode=@DevalueATypeUserCode
	AND a.StypeId=@STypeId	
	
	SET @DevalueATypeId = ISNULL(@DevalueATypeId,'')
END

SELECT @CategoryId=ID
FROM Ac_AssetsCategory
WHERE StypeId=@STypeId AND UserCode=@CategoryUserCode

SELECT @LocationId=ID
FROM Ac_AssetStorageLocation
WHERE Location=@Location

SELECT @ConditionID=ID
FROM Ac_AssetWorkingCondition
WHERE Comment=@Condition

SELECT @BusinessTypeID=ID
FROM Ac_AssetBusinessType
WHERE FullName=@BusinessType AND STypeId=@STypeId

SELECT @DTypeid=typeid
FROM Department
WHERE usercode=@DTypeUserCode



IF EXISTS (SELECT * FROM dbo.Ac_Account WHERE StypeId=@STypeId AND TypeId=@AssertATypeId AND sonnum > 0)
BEGIN
	SET @ErrMsg='固定资产科目为父节点，不能导入！'
		RETURN -1
END

IF EXISTS (SELECT * FROM dbo.Ac_Account WHERE StypeId=@STypeId AND TypeId=@DepATypeId AND sonnum > 0)
BEGIN
	SET @ErrMsg='累计折旧科目为父节点，不能导入！'
		RETURN -1
END

IF EXISTS (SELECT * FROM dbo.Ac_Account WHERE StypeId=@STypeId AND TypeId=@DisATypeId AND sonnum > 0)
BEGIN
	SET @ErrMsg='折旧分配科目为父节点，不能导入！'
		RETURN -1
END

IF EXISTS (SELECT * FROM dbo.Ac_Account WHERE StypeId=@STypeId AND TypeId=@DevalueATypeId AND sonnum > 0)
BEGIN
	SET @ErrMsg='减值准备科为父节点，不能导入！'
		RETURN -1
END
 
IF EXISTS (SELECT * FROM dbo.Department WHERE typeid=@DTypeid AND sonnum > 0)
BEGIN
	SET @ErrMsg='部门为父节点，不能导入！'
		RETURN -1
END

--处理资产数量
IF ISNUMERIC(@Qty) <> 1
	SET @Qty = 0
ELSE
	SET @Qty = CAST(@Qty AS NUMERIC(24,0))

IF LTRIM(RTRIM(@ExpectWork)) =''
SET @ExpectWork='0'

INSERT Ac_AssetsCards(UserCode,FullName,STypeId,AssertATypeId,DepATypeId,DisATypeId,DevalueATypeId,CategoryId,LocationId,
ConditionId,Size,DTypeid,InAccountDate,BusinessTypeId,Total,Cid,F_Total,Rate,DepTotal,DevalueReady,NetValue,NetSalvage,
NetSalvageRate,DepreciationMean,DurYear,durmonth,DepreciationMonth,Units,Comment,AssetsState,OperationDate,ETypeId,
XiWaMaxNumber,BarCode,ExpectWork,FinishWork,WorkUnit,Qty)
SELECT @UserCode,@FullName,@InputSTypeId,@AssertATypeId,@DepATypeId,@DisATypeId,@DevalueATypeId,@CategoryId,@LocationId,
@ConditionId,@Size,@DTypeid,@InAccountDate,@BusinessTypeId,@decInAccoutTotal,@intCID,@decCurInAccountTotal,@decRate,@decDepTotal,@decDevalueReady,@decNetValue,@decNetSalvage,
@decNetSalvageRate,@intDepreciationMean,@duryear,@durmonth,@intDepreciationMonth,@Units,@Comment,@AssetsState,GETDATE(),'00001',
1,@BarCode,CAST(ISNULL(@ExpectWork,'0') AS NUMERIC),@intWorkTime,@WorkUnit,@Qty

DECLARE @CARDIDS	INT
SET @CARDIDS=SCOPE_IDENTITY();

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AC_AssetsCards
UPDATE AC_AssetsCards SET XiWaMaxNumber = @XiWaMaxNumber WHERE id = @CARDIDS
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*






*/




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	修改：武智均
	时间：2019-09-04
	描述：生产模板导入
*/
CREATE PROCEDURE Gp_Import_Produce
(
	  @ProduceModelName VARCHAR(66)='' , -- 模板名称
      @pUserCode VARCHAR(200)='' , -- 生产商品编号
      @pFullName VARCHAR(200)='' , -- 生产商品名称
      @UserCode VARCHAR(200)='' , -- 商品编号
      @FullName VARCHAR(200)='' , -- 商品名称
      @BaseUnitName VARCHAR(200)='', -- 商品基本计量单位
	  @Qty VARCHAR(10)='' , -- 配套数量
      @Commet VARCHAR(256)='', -- 摘要
      @CreateTime DATETIME = '', --创建时间
      @ErrMsg VARCHAR(200) OUTPUT 
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
	IF(@Qty = '' )
	BEGIN
		SET @ErrMsg = '配套数量错误'
		RETURN -1
	END
	
	SET @ProduceModelName = LTRIM(RTRIM(@ProduceModelName))
	SET @pUserCode = LTRIM(RTRIM(@pUserCode))
	SET @pFullName = LTRIM(RTRIM(@pFullName))
	SET @UserCode = LTRIM(RTRIM(@UserCode))
	SET @FullName = LTRIM(RTRIM(@FullName))
	SET @BaseUnitName = LTRIM(RTRIM(@BaseUnitName))
	SET @Commet = LTRIM(RTRIM(@Commet))
	DECLARE @Qtys NUMERIC(24,10)
	SET @Qtys = dbo.F_RoundQty(@Qty)
	
	IF(@Qtys <= 0 )
	BEGIN
		SET @ErrMsg = '配套数量错误'
		RETURN -1
	END
	
	--模板名称不能存在相同
	IF EXISTS(SELECT top 1 1 FROM ProduceModelIndex WHERE ProduceModelName = @ProduceModelName AND CreateTime != @CreateTime )
	BEGIN
		SET @ErrMsg = '模板名称已存在'
		RETURN -1
	END
	
	--生成商品编号和名称
	IF(@pUserCode = '' )
	BEGIN
		SET @ErrMsg = '生成商品编号不能为空'
		RETURN -1
	END
	ELSE IF(NOT EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @pUserCode))
	BEGIN
		SET @ErrMsg = '生成商品编号不存在'
		RETURN -1
	END
	ELSE IF(NOT EXISTS(SELECT top 1 1 FROM Ptype WHERE @pFullName = '' OR (UserCode = @pUserCode AND FullName = @pFullName) ))
	BEGIN
		SET @ErrMsg = '生成商品编号和名称不匹配'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @pUserCode AND Sonnum > 0 ))
	BEGIN
		SET @ErrMsg = '生成商品不能为父节点'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @pUserCode AND Iscombinationproduct = 1 ))
	BEGIN
		SET @ErrMsg = '生成商品不能为组合品'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @pUserCode AND isservice = 1 ))
	BEGIN
		SET @ErrMsg = '生成商品不能为服务商品'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @pUserCode AND Deleted = 1 ))
	BEGIN
		SET @ErrMsg = '生成商品已停用'
		RETURN -1
	END
	
	--商品编号和名称
	IF(@UserCode = '' )
	BEGIN
		SET @ErrMsg = '商品编号不能为空'
		RETURN -1
	END
	ELSE IF(NOT EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @UserCode))
	BEGIN
		SET @ErrMsg = '商品编号不存在'
		RETURN -1
	END
	ELSE IF(NOT EXISTS(SELECT top 1 1 FROM Ptype WHERE @FullName = '' OR (UserCode = @UserCode AND FullName = @FullName) ))
	BEGIN
		SET @ErrMsg = '商品编号和名称不匹配'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @UserCode AND Sonnum > 0 ))
	BEGIN
		SET @ErrMsg = '商品不能为父节点'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @UserCode AND Iscombinationproduct = 1 ))
	BEGIN
		SET @ErrMsg = '商品不能为组合品'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @UserCode AND isservice = 1 ))
	BEGIN
		SET @ErrMsg = '商品不能为服务商品'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @UserCode AND Deleted = 1 ))
	BEGIN
		SET @ErrMsg = '商品已停用'
		RETURN -1
	END
	
	--基本计量单位
	IF(@BaseUnitName = '' )
	BEGIN
		SET @ErrMsg = '基本计量单位不能为空'
		RETURN -1
	END
	ELSE IF(NOT EXISTS(SELECT top 1 1 FROM Ptype_Units WHERE FullName = @BaseUnitName))
	BEGIN
		SET @ErrMsg = '基本计量单位不存在'
		RETURN -1
	END
	ELSE IF(NOT EXISTS(SELECT top 1 1 FROM Ptype A INNER JOIN Ptype_Units B ON A.baseUnitId = B.UnitsId WHERE A.UserCode = @UserCode AND B.FullName = @BaseUnitName ))
	BEGIN
		SET @ErrMsg = '基本计量单位与商品不匹配'
		RETURN -1
	END
	
	--配套数量
	IF(@Qtys <= 0 )
	BEGIN
		SET @ErrMsg = '配套数量必须大于0'
		RETURN -1
	END
	
	DECLARE @pPtypeId	VARCHAR (50), -- 生产商品typeid
			@PtypeId	VARCHAR (50), -- 商品typeid
			@ProduceModelId INT, -- 模板Id
			@IsInsertModel BIT = 0, -- 是否新增模板
			@ShowOrder INT -- 模板明细排序
	SELECT @pPtypeId = typeId FROM Ptype WHERE UserCode = @pUserCode
	SELECT @PtypeId = typeId FROM Ptype WHERE UserCode = @UserCode
	SELECT @ProduceModelId = (ISNULL((MAX(ProduceModelId)),0)+1) FROM ProduceModelIndex

	
	--模板名称
	IF(@ProduceModelName = '' )
	BEGIN
		SET @ErrMsg = '模板名称不能为空'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM ProduceModelIndex WHERE ProduceModelName = @ProduceModelName AND PtypeId = @pPtypeId))
	BEGIN
		SET @IsInsertModel = 1
		SELECT @ProduceModelId = ProduceModelID FROM ProduceModelIndex  WHERE ProduceModelName = @ProduceModelName
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM ProduceModelIndex WHERE ProduceModelName = @ProduceModelName AND PtypeId <> @pPtypeId AND Comment = @Commet))
	BEGIN
		SET @ErrMsg = '模板名称不能重复'
		RETURN -1
	END

	SELECT @ShowOrder = (ISNULL(COUNT(*),0)+1) FROM ProduceModel WHERE ProduceModelId = @ProduceModelId
	--新增模板
	IF(@IsInsertModel = 0)
	BEGIN
		INSERT INTO ProduceModelIndex VALUES(@ProduceModelId,@ProduceModelName,@pPtypeId,@Commet,@CreateTime)
	END
	
	--新增模板明细
	IF EXISTS (SELECT TOP 1 1 FROM ProduceModel WHERE ProduceModelId = @ProduceModelId AND PtypeId = @PtypeId)
	BEGIN
		SET @ErrMsg = '组合模板的商品已存在'
		RETURN -1
	END
	ELSE
	BEGIN
		INSERT INTO ProduceModel(ProduceModelID,PTypeID,Qty,ShowOrder) VALUES(@ProduceModelId,@PtypeId,@Qtys,@ShowOrder)
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'Gp_Import_Stype_PmPriceInfo')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE Gp_Import_Stype_PmPriceInfo
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	时间：2015-04-02
	作者：唐韬
	描述：导入分支机构物价信息导入
	
	时间：2016-11-08
	修改：舒珊
	描述：增加“计量单位编号”、“计量单位名称”两列
	
	时间：2017-01-11
	修改：舒珊
	描述：这个地方 不管系统配置 更改基本单位预设价格自动更改其他，不换算非基本单位的数据
*/
CREATE    PROCEDURE Gp_Import_Stype_PmPriceInfo
    (
      @sUserCode [varchar](200)='' , --分支机构
      @sFullName [varchar](200)='' ,
      @UserCode [varchar](200) ='',--商品
      @FullName [varchar](200)='' ,
      @UUserCode [varchar](200) ='',--多单位
      @UFullName [varchar](200)='' ,
      @StrPreBuyPrice1 [VARCHAR](25) ,
      @StrPreBuyPrice2 [VARCHAR](25) ,
      @StrPreBuyPrice3 [VARCHAR](25) ,
      @StrPreBuyPrice4 [VARCHAR](25) ,
      @StrPreBuyPrice5 [VARCHAR](25) ,
      @StrTopBuyPrice [VARCHAR](25) ,
      @StrPreSalePrice1 [VARCHAR](25) ,
      @StrPreSalePrice2 [VARCHAR](25) ,
      @StrPreSalePrice3 [VARCHAR](25) ,
      @StrPreSalePrice4 [VARCHAR](25) ,
      @StrPreSalePrice5 [VARCHAR](25) ,
      @StrPreSalePrice6 [VARCHAR](25) ,
      @StrPreSalePrice7 [VARCHAR](25) ,
      @StrPreSalePrice8 [VARCHAR](25) ,
      @StrPreSalePrice9 [VARCHAR](25) ,
      @StrPreSalePrice10 [VARCHAR](25) ,
      @StrReferprice [VARCHAR](25) ,
      @StrRetailPrice [VARCHAR](25) ,
      @StrTopSalePrice [VARCHAR](25) ,
      @StrLowSalePrice [VARCHAR](25) ,
      @ErrMsg VARCHAR(200) OUTPUT 
    )
--@encode$--    
AS 
    SET NOCOUNT ON

----------------------------------------------------------------------------------
 DECLARE @STypeID VARCHAR(50) 
 
 SET  @sUserCode = LTRIM(RTRIM(@sUserCode))
 SET  @sFullName = LTRIM(RTRIM(@sFullName))
 SET  @UserCode = LTRIM(RTRIM(@UserCode))
 SET  @FullName = LTRIM(RTRIM(@FullName))

--分支机构

IF(@sUserCode = '')
BEGIN
	SET @ErrMsg = '分支机构编号不能为空'
	RETURN -1
END
ELSE IF(@sUserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.SType WHERE UserCode = @sUserCode) OR @sUserCode='0')
BEGIN
	SET @ErrMsg = '分支机构编号不存在'
	RETURN -1
END
ELSE IF (@sFullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.SType WHERE FullName = @sFullName) OR @sFullName='总部')
BEGIN
	SET @ErrMsg = '分支机构名称不存在'
	RETURN -1
END
ELSE IF(@sFullName NOT IN (SELECT TOP 1 fullname FROM dbo.SType WHERE UserCode = @sUserCode) AND @sFullName <> '' AND @sUserCode <> '')
BEGIN
	SET @ErrMsg = '分支机构编号与分支机构名称不匹配'
	RETURN -1
END
SELECT   @STypeID = typeId  FROM dbo.SType WHERE UserCode = @sUserCode 
IF EXISTS (SELECT TOP 1 1  FROM dbo.SType WHERE TypeId = @STypeID AND sonnum > 0)
BEGIN
	SET @ErrMsg = '该分支机构为父节点，不能导入'
	RETURN -1	
END
--分支机构 

--商品
IF(@UserCode = '' )
BEGIN
	SET @ErrMsg = '商品编号不能为空'
	RETURN -1
END
ELSE IF(@UserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @UserCode) OR @UserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
ELSE IF (@FullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @FullName) OR @FullName='全部商品')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
ELSE IF(@FullName NOT IN (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @UserCode) AND @FullName <> '' AND @UserCode <> '')
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END

--“计量单位编号” (必填)、“计量单位名称”
IF(@UUserCode = '')
BEGIN
	SET @ErrMsg = '计量单位编号不能为空'
	RETURN -1
END
ELSE IF(@UUserCode <> '' AND NOT EXISTS(SELECT UnitsID FROM dbo.PType_units WHERE UserCode = @UUserCode) OR @UUserCode='0')
BEGIN
	SET @ErrMsg = '计量单位编号不存在'
	RETURN -1
END
ELSE IF (@UFullName <> '' AND NOT EXISTS(SELECT UnitsID FROM dbo.PType_units WHERE FullName = @UFullName))
BEGIN
	SET @ErrMsg = '计量单位名称不存在'
	RETURN -1
END
ELSE IF(@UFullName NOT IN (SELECT TOP 1 fullname FROM dbo.PType_units WHERE UserCode = @UUserCode) AND @UFullName <> '' AND @UUserCode <> '')
BEGIN
	SET @ErrMsg = '计量单位编号与计量单位名称不匹配'
	RETURN -1
END
--判断商品有没有这个计量单位
IF NOT EXISTS (SELECT 1 FROM PType_units_EXT WHERE PtypeID = (SELECT TOP 1 typeId FROM dbo.ptype WHERE UserCode = @UserCode)
AND UnitsId = (SELECT TOP 1 UnitsId FROM dbo.PType_Units WHERE UserCode =@UUserCode))
BEGIN
    SET @ErrMsg = '该商品没有此计量单位';
    RETURN -1; 
END

    DECLARE @PTypeID VARCHAR(50),@maxPrice NUMERIC =  9999999999.9999999999
    SELECT TOP 1  @PTypeID = typeId   FROM dbo.ptype WHERE UserCode = @UserCode 
    --AND FullName = @FullName
    
    DECLARE @UNITSID		INT=-1,
			@IsDefaultUnit	INT=-1,
			@RateType		int=-1;
	
	SELECT @UNITSID=E.UNITSID,
		   @IsDefaultUnit=E.IsDefaultUnit,
		   @RateType=E.RateType
	FROM PType_units_EXT E
	INNER JOIN PType_units U ON E.UNITSID=U.UNITSID
	WHERE E.PTYPEID=@PTypeID AND U.USERCODE=@UUserCode
   IF(@RateType<>0)
	BEGIN
		SET @ErrMsg = '计量单位不能为浮动单位'
		RETURN -1
	END
    
    IF EXISTS (SELECT TOP 1 1  FROM dbo.ptype WHERE TypeId = @PTypeID AND sonnum > 0)
	BEGIN
		SET @ErrMsg = '该商品为父节点，不能导入'
		RETURN -1	
	END
	DECLARE @d_price   VARCHAR(5),  --  单价小数位数  2    
			@d_price1  INT  ;      
    SELECT @d_price            = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 2
    SET @d_price1              = CONVERT(INT,@d_price)
    
    DECLARE @PreBuyPrice1  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice1 = '' ) 
        SET @PreBuyPrice1 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice1) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价1请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice1) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价1不能为负数'
                    RETURN -1
                END
            ELSE 
				BEGIN 
					IF( @d_price1 <( len(@StrPreBuyPrice1)-charindex('.',@StrPreBuyPrice1))AND charindex('.',@StrPreBuyPrice1) > 0)
					BEGIN
						SET @ErrMsg = '预设进价1小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SELECT  @PreBuyPrice1 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice1)
					IF(@PreBuyPrice1 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价1最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreBuyPrice2  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice2 = '' ) 
        SET @PreBuyPrice2 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice2) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价2请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice2) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价2不能为负数'
                    RETURN -1
                END
            ELSE 
				BEGIN
					IF( @d_price1 <( len(@StrPreBuyPrice2)-charindex('.',@StrPreBuyPrice2))AND charindex('.',@StrPreBuyPrice2) > 0)
					BEGIN
						SET @ErrMsg = '预设进价2小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreBuyPrice2 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice2)
					IF(@PreBuyPrice2 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价2最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END
                

    DECLARE @PreBuyPrice3  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice3 = '' ) 
        SET @PreBuyPrice3 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice3) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价3请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice3) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价3不能为负数'
                    RETURN -1
                END
            ELSE               
                BEGIN
					IF( @d_price1 <( len(@StrPreBuyPrice3)-charindex('.',@StrPreBuyPrice3))AND charindex('.',@StrPreBuyPrice3) > 0)
					BEGIN
						SET @ErrMsg = '预设进价3小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreBuyPrice3 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice3)
					IF(@PreBuyPrice3 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价3最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreBuyPrice4  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice4 = '' ) 
        SET @PreBuyPrice4 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice4) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价4请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice4) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价4不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreBuyPrice4)-charindex('.',@StrPreBuyPrice4))AND charindex('.',@StrPreBuyPrice4) > 0)
					BEGIN
						SET @ErrMsg = '预设进价4小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreBuyPrice4 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice4)
					IF(@PreBuyPrice4 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价4最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreBuyPrice5  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice5 = '' ) 
        SET @PreBuyPrice5 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice5) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价5请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice5) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价5不能为负数'
                    RETURN -1
                END
            ELSE     
                BEGIN
					IF( @d_price1 <( len(@StrPreBuyPrice5)-charindex('.',@StrPreBuyPrice5))AND charindex('.',@StrPreBuyPrice5) > 0)
					BEGIN
						SET @ErrMsg = '预设进价5小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreBuyPrice5 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice5)
					IF(@PreBuyPrice5 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价5最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @TopBuyPrice  NUMERIC(24, 10) 
    IF ( @StrTopBuyPrice = '' ) 
        SET @TopBuyPrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrTopBuyPrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最高进价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrTopBuyPrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最高进价不能为负数'
                    RETURN -1
                END
            ELSE            
                BEGIN
					IF( @d_price1 <( len(@StrTopBuyPrice)-charindex('.',@StrTopBuyPrice))AND charindex('.',@StrTopBuyPrice) > 0)
					BEGIN
						SET @ErrMsg = '最高进价小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @TopBuyPrice = CONVERT( NUMERIC(24, 10) , @StrTopBuyPrice)
					IF(@TopBuyPrice > @maxPrice)
					BEGIN
						SET @ErrMsg = '最高进价最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice1  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice1 = '' ) 
        SET @PreSalePrice1 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice1) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价1请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice1) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价1不能为负数'
                    RETURN -1
                END
            ELSE  
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice1)-charindex('.',@StrPreSalePrice1))AND charindex('.',@StrPreSalePrice1) > 0)
					BEGIN
						SET @ErrMsg = '预设售价1小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice1 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice1)
					IF(@PreSalePrice1 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价1最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice2  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice2 = '' ) 
        SET @PreSalePrice2 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice2) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价2请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice2) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价2不能为负数'
                    RETURN -1
                END
            ELSE 
                
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice2)-charindex('.',@StrPreSalePrice2))AND charindex('.',@StrPreSalePrice2) > 0)
					BEGIN
						SET @ErrMsg = '预设售价2小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice2 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice2)
					IF(@PreSalePrice2 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价2最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice3  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice3 = '' ) 
        SET @PreSalePrice3 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice3) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价3请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice3) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价3不能为负数'
                    RETURN -1
                END
            ELSE 
                
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice3)-charindex('.',@StrPreSalePrice3))AND charindex('.',@StrPreSalePrice3) > 0)
					BEGIN
						SET @ErrMsg = '预设售价3小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice3 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice3)
					IF(@PreSalePrice3 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价3最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice4  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice4 = '' ) 
        SET @PreSalePrice4 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice4) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价4请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice4) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价4不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice4)-charindex('.',@StrPreSalePrice4))AND charindex('.',@StrPreSalePrice4) > 0)
					BEGIN
						SET @ErrMsg = '预设售价4小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice4 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice4)
					IF(@PreSalePrice4 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价4最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice5  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice5 = '' ) 
        SET @PreSalePrice5 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice5) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价5请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice5) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价5不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice5)-charindex('.',@StrPreSalePrice5))AND charindex('.',@StrPreSalePrice5) > 0)
					BEGIN
						SET @ErrMsg = '预设售价5小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice5 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice5)
					IF(@PreSalePrice5 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价5最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice6  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice6 = '' ) 
        SET @PreSalePrice6 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice6) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价6请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice6) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价6不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice6)-charindex('.',@StrPreSalePrice6))AND charindex('.',@StrPreSalePrice6) > 0)
					BEGIN
						SET @ErrMsg = '预设售价6小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice6 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice6)
					IF(@PreSalePrice6 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价6最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice7  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice7 = '' ) 
        SET @PreSalePrice7 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice7) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价7请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice7) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价7不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice7)-charindex('.',@StrPreSalePrice7))AND charindex('.',@StrPreSalePrice7) > 0)
					BEGIN
						SET @ErrMsg = '预设售价7小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice7 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice7)
					IF(@PreSalePrice7 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价7最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice8  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice8 = '' ) 
        SET @PreSalePrice8 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice8) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价8请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( ( SELECT   CHARINDEX('-', @StrPreSalePrice8)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价8不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice8)-charindex('.',@StrPreSalePrice8))AND charindex('.',@StrPreSalePrice8) > 0)
					BEGIN
						SET @ErrMsg = '预设售价8小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice8 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice8)
					IF(@PreSalePrice8 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价8最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice9  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice9 = '' ) 
        SET @PreSalePrice9 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice9) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价9请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice9) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价9不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice9)-charindex('.',@StrPreSalePrice9))AND charindex('.',@StrPreSalePrice9) > 0)
					BEGIN
						SET @ErrMsg = '预设售价9小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice9 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice9)
					IF(@PreSalePrice9 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价9最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice10  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice10 = '' ) 
        SET @PreSalePrice10 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice10) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价10请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice10) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价10不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice10)-charindex('.',@StrPreSalePrice10))AND charindex('.',@StrPreSalePrice10) > 0)
					BEGIN
						SET @ErrMsg = '预设售价10小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice10 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice10)
					IF(@PreSalePrice10 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价10最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END
    
    DECLARE @Referprice  NUMERIC(24, 10) 
    IF ( @StrReferprice = '' ) 
        SET @Referprice = 0
    ELSE 
        IF ( ISNUMERIC(@StrReferprice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '参考成本请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrReferprice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '参考成本不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrReferprice)-charindex('.',@StrReferprice))AND charindex('.',@StrReferprice) > 0)
					BEGIN
						SET @ErrMsg = '参考成本小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @Referprice = CONVERT( NUMERIC(24, 10) , @StrReferprice)
					IF(@Referprice > @maxPrice)
					BEGIN
						SET @ErrMsg = '参考成本最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @RetailPrice  NUMERIC(24, 10) 
    IF ( @StrRetailPrice = '' ) 
        SET @RetailPrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrRetailPrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '零售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrRetailPrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '零售价不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrRetailPrice)-charindex('.',@StrRetailPrice))AND charindex('.',@StrRetailPrice) > 0)
					BEGIN
						SET @ErrMsg = '零售价小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @RetailPrice = CONVERT( NUMERIC(24, 10) , @StrRetailPrice)
					IF(@RetailPrice > @maxPrice)
					BEGIN
						SET @ErrMsg = '零售价最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @TopSalePrice  NUMERIC(24, 10) 
    IF ( @StrTopSalePrice = '' ) 
        SET @TopSalePrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrTopSalePrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最高售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrTopSalePrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最高售价不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrTopSalePrice)-charindex('.',@StrTopSalePrice))AND charindex('.',@StrTopSalePrice) > 0)
					BEGIN
						SET @ErrMsg = '最高售价小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @TopSalePrice = CONVERT( NUMERIC(24, 10) , @StrTopSalePrice)
					IF(@TopSalePrice > @maxPrice)
					BEGIN
						SET @ErrMsg = '最高售价最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @LowSalePrice  NUMERIC(24, 10) 
    IF ( @StrLowSalePrice = '' ) 
        SET @LowSalePrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrLowSalePrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最低售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrLowSalePrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最低售价不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrLowSalePrice)-charindex('.',@StrLowSalePrice))AND charindex('.',@StrLowSalePrice) > 0)
					BEGIN
						SET @ErrMsg = '最低售价小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @LowSalePrice = CONVERT( NUMERIC(24, 10) , @StrLowSalePrice)
					IF(@LowSalePrice > @maxPrice)
					BEGIN
						SET @ErrMsg = '最低售价最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

  
----------------------------------------------------------------------------------------------
    IF NOT EXISTS (SELECT STypeID FROM dbo.PType_STypePrice WHERE STypeID = @STypeID AND PTypeID = @PTypeID and unitID=@UNITSID )
    BEGIN
		DECLARE @XiWaMaxNumber  NUMERIC(24, 10) 
		SELECT @XiWaMaxNumber = ISNULL(MAX(XiWaMaxNumber),0)+1 FROM dbo.PType_STypePrice
		INSERT INTO dbo.PType_STypePrice
		        ( STypeID ,
		          PTypeID ,
		          unitID,
		          IsDefaultUnit,
		          PreBuyPrice1 ,
		          PreBuyPrice2 ,
		          PreBuyPrice3 ,
		          PreBuyPrice4 ,
		          PreBuyPrice5 ,
		          PreSalePrice1 ,
		          PreSalePrice2 ,
		          PreSalePrice3 ,
		          PreSalePrice4 ,
		          PreSalePrice5 ,
		          PreSalePrice6 ,
		          PreSalePrice7 ,
		          PreSalePrice8 ,
		          PreSalePrice9 ,
		          PreSalePrice10 ,
		          RetailPrice ,
		          TopSalePrice ,
		          LowSalePrice ,
		          referprice,
		          TopBuyPrice ,
		          XiWaMaxNumber 
		        )
		VALUES  ( @STypeID , -- STypeID - varchar(50)
		          @PTypeID , -- PTypeID - varchar(50)
		          @UNITSID,
		          @IsDefaultUnit,
		          @PreBuyPrice1 , -- PreBuyPrice1 - numeric
		          @PreBuyPrice2 , -- PreBuyPrice2 - numeric
		          @PreBuyPrice3 , -- PreBuyPrice3 - numeric
		          @PreBuyPrice4 , -- PreBuyPrice4 numeric
		          @PreBuyPrice5 , -- PreBuyPrice5 numeric
		          @PreSalePrice1 , -- PreSalePrice1 numeric
		          @PreSalePrice2 , -- PreSalePrice2 numeric
		          @PreSalePrice3 , -- PreSalePrice3 - numeric
		          @PreSalePrice4 , -- PreSalePrice4 - numeric
		          @PreSalePrice5 , -- PreSalePrice5 - numeric
		          @PreSalePrice6 , -- PreSalePrice6 - numeric
		          @PreSalePrice7 , -- PreSalePrice7 - numeric
		          @PreSalePrice8 , -- PreSalePrice8 - numeric
		          @PreSalePrice9 , -- PreSalePrice9 - numeric
		          @PreSalePrice10 , -- PreSalePrice10 - numeric
		          @RetailPrice , -- RetailPrice - numeric
		          @TopSalePrice , -- TopSalePrice - numeric
		          @LowSalePrice , -- LowSalePrice - numeric
		          @ReferPrice,  -- referprice - numeric  
		          @TopBuyPrice, -- 
		          @XiWaMaxNumber  -- XiWaMaxNumber - numeric
		        )
	            IF @@rowcount = 0 
				BEGIN
					SET @ErrMsg = '导入失败'
					RETURN -1
				END
	/*         

SELECT TopBuyPrice AS'最高进价',RetailPrice AS'零售价', TopSalePrice AS '最高售价',
LowSalePrice AS '最低售价', referprice AS '参考成本'  FROM dbo.PType_STypePrice
*/	
    END
    ELSE
    BEGIN
		UPDATE  dbo.PType_STypePrice
		SET     PreBuyPrice1 = @PreBuyPrice1 ,
				PreBuyPrice2 = @PreBuyPrice2 ,
				PreBuyPrice3 = @PreBuyPrice3 ,
				PreBuyPrice4 = @PreBuyPrice4 ,
				PreBuyPrice5 = @PreBuyPrice5 ,
				TopBuyPrice =  @TopBuyPrice ,
				PreSalePrice1 = @PreSalePrice1 ,
				PreSalePrice2 = @PreSalePrice2 ,
				PreSalePrice3 = @PreSalePrice3 ,
				PreSalePrice4 = @PreSalePrice4 ,
				PreSalePrice5 = @PreSalePrice5 ,
				PreSalePrice6 = @PreSalePrice6 ,
				PreSalePrice7 = @PreSalePrice7 ,
				PreSalePrice8 = @PreSalePrice8 ,
				PreSalePrice9 = @PreSalePrice9 ,
				PreSalePrice10 = @PreSalePrice10 ,
				RetailPrice = @RetailPrice ,
				LowSalePrice = @LowSalePrice ,
				TopSalePrice = @TopSalePrice ,
				ReferPrice = @ReferPrice,
				UNITID=@UNITSID,
				IsDefaultUnit=@IsDefaultUnit
		WHERE   PTypeID = @PTypeID AND STypeID = @STypeID and UNITID=@UNITSID
	    IF @@rowcount = 0 
		BEGIN
			SET @ErrMsg = '导入失败'
			RETURN -1
		END
    END 
       
DELETE  FROM  PType_STypePrice 
WHERE STYPEID=@STypeID
AND  PTypeID = @PTypeID 
AND IsDefaultUnit=0
AND ISNULL(PreBuyPrice1,0)=0 
AND	ISNULL(PreBuyPrice2,0)=0
AND ISNULL(PreBuyPrice3,0)=0
AND	ISNULL(PreBuyPrice4,0)=0 
AND	ISNULL(PreBuyPrice5,0)=0
AND	ISNULL(PreSalePrice1,0)=0
AND	ISNULL(PreSalePrice2,0)=0 
AND	ISNULL(PreSalePrice3,0)=0 
AND	ISNULL(PreSalePrice4,0)=0 
AND	ISNULL(PreSalePrice5,0)=0 
AND	ISNULL(PreSalePrice6,0)=0 
AND	ISNULL(PreSalePrice7,0)=0 
AND	ISNULL(PreSalePrice8,0)=0 
AND	ISNULL(PreSalePrice9,0)=0 
AND	ISNULL(PreSalePrice10, 0)=0
AND	ISNULL(RetailPrice,0)=0 
AND	ISNULL(TopSalePrice,0)=0 
AND	ISNULL(LowSalePrice,0)=0
AND	ISNULL(RecPrice,0)=0
AND	ISNULL(TopBuyPrice,0)=0
AND	ISNULL(referprice,0)=0
AND ISNULL(RECSALEPRICE,0)=0
AND ISNULL(RECAPPRAISALPRICE,0)=0
AND ISNULL(RECSENDPRICE,0)=0


GO





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


/****** Object:  StoredProcedure [dbo].[gp_ImportA]    Script Date: 05/20/2011 17:29:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	修 改 者：廖晨羽
	日    期：2011-08-23
	修改原因：导入地区信息
	修改位置：转换输入参数
*/



CREATE               PROCEDURE [dbo].[gp_ImportA]
(
 @AFullName   [varchar](66),
 @UserCode  [varchar](256),
 @FullName  [varchar](256),
 @Name [varchar](256),
 @PyCode  [varchar](257),
 @LinkMan [varchar](257),
 @Tel [varchar](257),
 @Comment  [varchar](257),
 @ReturnID  VARCHAR(100) output,
 @ErrMsg VARCHAR(200) output
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

IF ((SELECT DATALENGTH(@PyCode)) > 256)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@LinkMan)) > 256)
BEGIN
	SET @ErrMsg = '负责人的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Tel)) > 256)
BEGIN
	SET @ErrMsg = '电话的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 256)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度256'
	RETURN -1
END

DECLARE @Parid [varchar](50)
IF (@AfullName = '')
BEGIN
	SET @Parid = '00000'
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.AreaType WHERE fullname = @AfullName) OR @AfullName = '所有地区'
		BEGIN
			SET @ErrMsg = '父类名称不存在'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Parid = (SELECT TOP 1 typeid FROM dbo.AreaType WHERE fullname = @AfullName)
		END
END

DECLARE @DbName [varchar](30) = 'AreaType'

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '地区编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '地区全名不能为空'
	RETURN -1
END

IF(@Pycode = '')
BEGIN
	SELECT @Pycode = dbo.fun_getPY(@FullName)
END
----------------------------------------------------------------------------------------------

declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from areatype where typeid=@parid)


--判断停用不能分类
declare @deleted INT
select @deleted=deleted from areatype where typeId=@Parid
	if(@deleted=1)
		BEGIN
			SET @ErrMsg = '该地区档案【' + @parFullName + '】已经被停用，不能分类'
			RETURN -1
			--RAISERROR('该地区档案【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
		end
-- 判断库存量（每种商品）是否为零

IF EXISTS(select AreaTypeID from Btype WHERE AreaTypeID=@Parid)
BEGIN
	SET @ErrMsg = '该地区档案【' + @parFullName + '】已经在客户或供货商档案中使用，不能分类'
	RETURN -1
	--RAISERROR('该地区档案【%s】已经在客户或供货商档案中使用，不能分类',16,1,@parFullName)return---RETURN -801
end

IF EXISTS(select AreaTypeID from Crm_Btype WHERE AreaTypeID=@Parid)
BEGIN
	SET @ErrMsg = '该地区档案【' + @parFullName + '】客户管理中使用，不能分类'
	RETURN -1
	--RAISERROR('该地区档案【%s】已在CRM客户管理中使用，不能分类',16,1,@parFullName)return
end

-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1
BEGIN
	SET @ErrMsg = '地区档案的分类不能超过10层'
	RETURN -1
	--RAISERROR('地区档案的分类不能超过10层',16,1)return--return -1
end
if @nReturntype=-2 
BEGIN
	SET @ErrMsg = '无法添加基本信息'
	RETURN -1
	--RAISERROR('无法添加基本信息',16,1)return--return -2
end
 
-- 判断重复的ID,UserCode

if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) OR (fullname=@fullname and deleted<>1) )
begin
	
	--print '['+@usercode+']地区档案已存在'
	--print  @EtypeId_1
	SET @ErrMsg = '【' + @FullName + '】已经存在，地区档案的名称或编号不能相同'
	RETURN -1
	--RAISERROR('【%s】已经存在，地区档案的名称或编号不能相同',16,1,@FullName)return--return -3
end
-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
begin
	--print '['+@usercode+']地区档案已存在'
	SET @ErrMsg = '【' + @FullName + '】名称或编号不能与已有的名称或编号重复'
	RETURN -1
	--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复',16,1,@FullName)return--return -10
end

-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) OR (fullname=@fullname and deleted=1))
begin
	--print '['+@usercode+']地区档案已存在'
	SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被已停用的地区档案使用，请更换或删除该停用的编号或名称'
	RETURN -1
	--RAISERROR('该【%s】的编号或名称已被已停用的地区档案使用，请更换或删除该停用的编号或名称',16,1,@FullName)return---return -31
end
-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
begin
	--print '['+@usercode+']地区档案已存在'
	SET @ErrMsg = '该地区档案【' + @FullName + '】名称或编号不能与已停用的名称或编号重复'
	RETURN -1
	--RAISERROR('该地区档案【%s】名称或编号不能与已停用的名称或编号重复',16,1,@FullName)return--return -101
end

/*
-- 判断地区档案的最大使用数量
declare @nCount int
select @nCount=Count(*) from AreaType 
where sonnum = 0 
 and deleted=0
if @nCount > 10
begin
-- print '地区档案数量大于10'
 return -99
end
*/

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode


begin tran insertproc
select @leveal=leveal from AreaType where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO [AreaType] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [UserCode],
  [FullName], 
  [Name],
  [SysFlag],
  [deleted],
  [Comment],
  [PyCode],
  [Tel],
  [LinkMan]	
 )  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @UserCode,
  @FullName,
  @name,
  0,
  0,
  @Comment,
  @returnPym,
  @Tel,
  @LinkMan
 )
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [AreaType]
 set sonnum=@nSonnum+1,soncount=@nSoncount+1
 where typeid=@Parid
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AreaType
UPDATE AreaType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
commit tran insertproc




SET  @ReturnID = @@ROWCOUNT
















GO





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


/****** Object:  StoredProcedure [dbo].[Gp_ImportAc_IniAccount]    Script Date: 05/20/2011 17:29:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	创 建 者：唐韬
	日    期：2014-06-18 10:55:59.583
	创建原因：导入财务期初
*/

CREATE               PROCEDURE [dbo].[Gp_ImportAc_IniAccount]
(
	@SUserCode		[varchar](300)='',		--分支机构
	@CUserCode		[varchar](300)='',		--币种编号
	@AUserCode       [varchar](300)='',		--科目编号
	@AFullName      [varchar](200)='',		--科目名称
	@AscFullName1	[varchar](200)='',		--辅助核算项目名称1
	@AscFullName2	[varchar](200)='',		--辅助核算项目名称2
	@AscFullName3	[varchar](200)='',		--辅助核算项目名称3
	@AscFullName4	[varchar](200)='',		--辅助核算项目名称4
	@AscFullName5	[varchar](200)='',		--辅助核算项目名称5
	@AscFullName6	[varchar](200)='',		--辅助核算项目名称6
	@HSUserCode1	[varchar](200)='',		--核算项目编号1
	@HSFullName1	[varchar](200)='',		--核算项目名称1
	@HSUserCode2	[varchar](200)='',		--核算项目编号2
	@HSFullName2	[varchar](200)='',		--核算项目名称2
	@HSUserCode3	[varchar](200)='',		--核算项目编号3
	@HSFullName3	[varchar](200)='',		--核算项目名称3
	@HSUserCode4	[varchar](200)='',		--核算项目编号4
	@HSFullName4	[varchar](200)='',		--核算项目名称4
	@HSUserCode5	[varchar](200)='',		--核算项目编号5
	@HSFullName5	[varchar](200)='',		--核算项目名称5
	@HSUserCode6	[varchar](200)='',		--核算项目编号6
	@HSFullName6	[varchar](200)='',		--核算项目名称6
	
	@strFDebitFor1		[VARCHAR](25)='' ,		--本年累计借方
	@strFCreditFor1	   [VARCHAR](25)='',		--本年累计贷方
	@strIniTotalFor1	[VARCHAR](25)='',		--期初余额
	@strFYTotalFor		[VARCHAR](25)='',		--本年累计损益实际发生额

	@Fzhs           INT	,					--0 非辅助核算 1 辅助核算
	@ReturnID		VARCHAR(100) OUTPUT,
	@ErrMsg			VARCHAR(500) OUTPUT

)
--@encode$--
AS
SET NOCOUNT ON

DECLARE 
	@StypeId	VARCHAR(50),--分支机构ID
	@AtypeId	VARCHAR(50),--科目ID
	@Cid		INT ,		--币种 cid 外币核算 1不核算（本位币）  0	所有币种  其他币种id
	@FYear		INT,		--总账分支机构启用年度
	@FPeriod	INT,		--总账分支机构启用期间
	@Year		INT,		--业务分支机构启用本期年度
	@Period		INT,		--业务分支机构启用本期期间
	@Fdc		INT,		--Fdc 借贷方向：1.借 -1.贷
	@Acid		INT,		--会计科目所选币种
	@SysRow		INT,		--币种是否预制数据
	@BasisType	INT,		--币种换算计算方式
	@Rate		NUMERIC(24, 10), --币种汇率
	@SyType		BIT=0,		--是否损益类科目
	@AscIds1	INT,--辅助核算一
	@AscIds2	INT,--辅助核算二
	@AscIds3	INT,--辅助核算三
	@AscIds4	INT,--辅助核算四
	@AscIds5	INT,--辅助核算五
	@AscIds6	INT,--辅助核算六
	@value1		VARCHAR(50),--辅助核算TypeID一
	@value2		VARCHAR(50),--辅助核算TypeID二
	@value3		VARCHAR(50),--辅助核算TypeID三
	@value4		VARCHAR(50),--辅助核算TypeID四
	@value5		VARCHAR(50),--辅助核算TypeID五
	@value6		VARCHAR(50),--辅助核算TypeID六
	@count		INT,		--科目对应辅助核算实际个数
	@ItemCount  INT =0,		--导入辅助核算科目数量
	@groupid int

/**/
DECLARE   @IniYTotal  NUMERIC(24, 10)  ,
          @IniYTotalFor  NUMERIC(24, 10)  ,
          @FDebit  NUMERIC(24, 10)  ,
          @FDebitFor  NUMERIC(24, 10)  ,
          @FCredit  NUMERIC(24, 10)  ,
          @FCreditFor  NUMERIC(24, 10)  ,
          @IniTotal  NUMERIC(24, 10)  ,
          @IniTotalFor  NUMERIC(24, 10),  
          @FYTotal  NUMERIC(24, 10)=0 ,--本币本年累计损益实际发生额
          @FYTotalFor  NUMERIC(24, 10)=0 --原币本年累计损益实际发生额

-------------------------------------转换输入参数---------------------------------------------
--分支机构
IF(@SUserCode = '')
	BEGIN
		SET @ErrMsg = '分支机构编号不能为空'
		RETURN -1
	END
ELSE IF(NOT EXISTS(SELECT typeId FROM dbo.SType WHERE UserCode = @SUserCode AND Deleted=0))
	BEGIN
		SET @ErrMsg = '分支机构不存在'
		RETURN -1
	END
ELSE
BEGIN
	IF(EXISTS(SELECT typeId FROM dbo.SType WHERE UserCode = @SUserCode AND  sonnum>0))
	BEGIN
		SET @ErrMsg = '该分支机构为父节点，不能导入'
		RETURN -1
	END
	ELSE
	BEGIN
		SELECT @StypeId =typeId FROM dbo.SType WHERE UserCode = @SUserCode 
		SELECT @FYear=SFYear,@FPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeId
		SELECT @Period=period,@Year=[YEAR] FROM MonthProc WHERE Stypeid=@StypeId AND MonthNo='本期'
	END
END
--分支机构

--IF EXISTS (
--		SELECT	TOP 1 1
--		FROM	SType_UserConfig
--		WHERE	ConfigNo = 1
--				AND Value = 1
--				AND STypeID=@StypeId
--	) AND EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=1)
--BEGIN
--		SET @ErrMsg = '该分支机构已开账，不能导入'
--		RETURN -1
--END

IF  EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=1)
BEGIN
		SET @ErrMsg = '该分支机构已开账，不能导入'
		RETURN -1
END
--币种
SET @CUserCode = LTRIM(RTRIM(@CUserCode));
IF(@CUserCode = '')
BEGIN
	SET @ErrMsg = '币种不能为空'
	RETURN -1
END
ELSE IF(NOT EXISTS(SELECT CId FROM dbo.Ac_Currency WHERE UserCode = @CUserCode AND Deleted=0))
BEGIN
	SET @ErrMsg = '币种不存在'
	RETURN -1
END
ELSE 
BEGIN
	SELECT  @Cid = cid, @Rate = rate ,@SysRow= Sysrow ,@BasisType = BasisType FROM dbo.Ac_Currency WHERE UserCode = @CUserCode
	IF(@SysRow <> 1)
	BEGIN
		IF(NOT EXISTS(SELECT SubValue FROM dbo.sysdata WHERE SubName='isforeigncurrency' AND SubValue='1'))
		BEGIN
			SET @ErrMsg = '系统没有启用外币核算'
			RETURN -1
		END
	END	
END


--币种


--科目
IF(@AUserCode = '')
BEGIN 
	SET @ErrMsg = '科目编号不能为空'
	RETURN -1
END
IF(@AFullName = '')
BEGIN 
	SET @ErrMsg = '科目名称不能为空'
	RETURN -1
END
ELSE
BEGIN
-- cid 0是所有，-1是不核算
	DECLARE @sonnum int
	SELECT @sonnum = sonnum,@AtypeId = typeid ,@Fdc= Fdc, @Acid = cid FROM dbo.Ac_Account 
	WHERE StypeId= @StypeId and UserCode=RTRIM( LTRIM(@AUserCode)) and fullname =RTRIM( LTRIM(@AFullName)) and deleted=0

	IF(@AtypeId IS NULL)
	BEGIN
		SET @ErrMsg = '科目不存在'
		RETURN -1
	END
	
	IF(@sonnum>0)
	BEGIN
		SET @ErrMsg = '科目为父节点，不能导入'
		RETURN -1
	END	
	--是否是损益类科目
	IF(LEFT(@AtypeId,5)='00003')
	BEGIN
		SET @SyType = 1
	END
	--当启用期间不是第1期时，只能导入本年累计数，不能导入期初数据；

	IF @SyType = 1
	BEGIN
		IF @Period = 1 AND @FYear=@Year 
		BEGIN
			SET @ErrMsg = '启用期间为第1期时损益类科目时不能导入数据'
			RETURN -1
		END
		ELSE
		BEGIN
			IF ( @strIniTotalFor1 <> '' ) 
			BEGIN
				SET @ErrMsg = '损益类科目只能录入本年累计,不能录入期初余额'
				RETURN -1
			END
		END
	END
	--IF(@SysRow<>1)
	--BEGIN
		IF(@Acid <> 0 )
		BEGIN
			IF @Acid = -1
			BEGIN
				SET @ErrMsg = '科目没有配置'+@CUserCode+'外币核算'
				RETURN -1
			END
			IF @Cid <> @Acid
			BEGIN
				SET @ErrMsg = '科目没有配置'+@CUserCode+'外币核算'
				RETURN -1
			END
		END
	--END
END

IF(@Period = 1  AND @FYear=@Year)
BEGIN
	IF ( @strFDebitFor1 <> '' OR @strFCreditFor1 <> '') 
	BEGIN
		SET @ErrMsg = '启用期间为第1期间时不能录入本年累计数据'
		RETURN -1
	END
	SET @strFDebitFor1='0'
	SET @strFCreditFor1='0'
END

SELECT a.Ascids,b.FullName INTO #A 
FROM Ac_Account_Assist_CheckItems a 
JOIN Ac_Assist_CheckItems b ON a.Ascids = b.AscIds
AND a.STypeId = @StypeId
AND a.ATypeId = @AtypeId
AND a.Cid = @Cid

SELECT @count = COUNT(1) FROM #A

--科目

IF(@Fzhs = 0)
BEGIN
	IF( @count > 0)
	BEGIN
		SET @ErrMsg = '科目不能是辅助核算科目'
		RETURN -1
	END
END

--启用辅助核算
IF(@Fzhs = 1)
BEGIN
  -- DECLARE @temp VARCHAR(max)
  -- SET @temp = @AscFullName1+','+@AscFullName2+','+@AscFullName3+','+@AscFullName4+','+@AscFullName5
  -- IF ( EXISTS (SELECT COUNT(1) FROM f_split(@temp,',')  WHERE a<>'' GROUP BY a  HAVING COUNT(a)>1))
  -- BEGIN
		--SET @ErrMsg = '辅助核算项目出现重复'
		--RETURN -1
  -- END
   
--科目辅助核算来源 

IF NOT EXISTS(SELECT TOP 1 1 FROM  Ac_Account_Assist_CheckItems  WHERE cid = @Cid AND STypeId=@StypeId AND ATypeId=@AtypeId)
BEGIN
	SET @ErrMsg = '科目对应的辅助核算项目和币种【'+@CUserCode+'】不匹配'
	RETURN -1 
END


IF( @count = 0)
BEGIN
	SET @ErrMsg = '科目与币种对应不正确或科目未配置辅助核算项目'
	RETURN -1
END
ELSE
BEGIN
	IF(@AscFullName1 <> '')
	BEGIN
		SET @ItemCount = @ItemCount +1
	END
	IF(@AscFullName2 <> '')
	BEGIN
		SET @ItemCount = @ItemCount +1
	END
	IF(@AscFullName3 <> '')
	BEGIN
		SET @ItemCount = @ItemCount +1
	END
	IF(@AscFullName4 <> '')
	BEGIN
		SET @ItemCount = @ItemCount +1
	END
	
	IF(@AscFullName5 <> '')
	BEGIN
		SET @ItemCount = @ItemCount +1
	END
	
	IF(@AscFullName6 <> '')
	BEGIN
		SET @ItemCount = @ItemCount +1
	END
	
	IF (@ItemCount > @count)
	BEGIN
		SET @ErrMsg = '辅助核算项目名称填写过多'
		RETURN -1
	END
	
	IF (@ItemCount < @count)
	BEGIN
		SET @ErrMsg = '辅助核算项目名称未填写完'
		RETURN -1
	END
END

--科目辅助核算来源

--辅助核算项目名称1
IF(@AscFullName1 ='')
BEGIN
	SET @ErrMsg = '辅助核算项目名称1不能为空'
	RETURN -1
END
IF(NOT EXISTS(SELECT Ascids FROM  #A WHERE FullName =@AscFullName1 ))
BEGIN
	SET @ErrMsg = '辅助核算项目名称1('+@AscFullName1+')不存在'
	RETURN -1
END
ELSE
BEGIN
	SELECT @AscIds1 = Ascids FROM  #A WHERE FullName =@AscFullName1 
	IF(@AscIds1 <= 0)
	BEGIN
		SET @ErrMsg = '辅助核算项目名称1('+@AscFullName1+')不合法'
		RETURN -1
	END
END
--辅助核算项目名称1

--辅助核算项目名称2
IF(@AscFullName2 <>'')
BEGIN
    IF( NOT EXISTS(SELECT Ascids FROM  #A WHERE FullName =@AscFullName2 ) )
	BEGIN
		SET @ErrMsg = '辅助核算项目名称2('+@AscFullName2+')不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SELECT @AscIds2 = Ascids FROM  #A WHERE FullName =@AscFullName2
	END
END
ELSE
BEGIN
	IF(@HSUserCode2<> '' OR @HSFullName2 <> '')
	BEGIN
		SET @ErrMsg = '辅助核算项目名称2未填写，不能填写填写核算项目2'
		RETURN -1
	END
END
--辅助核算项目名称2

--辅助核算项目名称3
IF(@AscFullName3 <>'' )
BEGIN
    IF( NOT EXISTS(SELECT Ascids FROM  #A WHERE FullName =@AscFullName3 ) )
	BEGIN
		SET @ErrMsg = '辅助核算项目名称3('+@AscFullName3+')不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SELECT @AscIds3 = Ascids FROM  #A WHERE FullName =@AscFullName3 
	END
END
ELSE
BEGIN
	IF(@HSUserCode3<> '' OR @HSFullName3 <> '')
	BEGIN
		SET @ErrMsg = '辅助核算项目名称3未填写，不能填写填写核算项目3'
		RETURN -1
	END
END
--辅助核算项目名称3

--辅助核算项目名称4
IF(@AscFullName4 <>'' )
BEGIN
    IF( NOT EXISTS(SELECT Ascids FROM  #A WHERE FullName =@AscFullName4 ) )
	BEGIN
		SET @ErrMsg = '辅助核算项目名称4('+@AscFullName4+')不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SELECT @AscIds4 = Ascids FROM  #A WHERE FullName =@AscFullName4 
	END
END
ELSE
BEGIN
	IF(@HSUserCode4<> '' OR @HSFullName4<> '')
	BEGIN
		SET @ErrMsg = '辅助核算项目名称4未填写，不能填写填写核算项目4'
		RETURN -1
	END
END
--辅助核算项目名称4


--辅助核算项目名称5
IF(@AscFullName5 <>'' )
BEGIN
    IF( NOT EXISTS(SELECT Ascids FROM  #A WHERE FullName =@AscFullName5 ) )
	BEGIN
		SET @ErrMsg = '辅助核算项目名称5('+@AscFullName5+')不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SELECT @AscIds5 = Ascids FROM  #A WHERE FullName =@AscFullName5 
	END
END
ELSE
BEGIN
	IF(@HSUserCode5<> '' OR @HSFullName5 <> '')
	BEGIN
		SET @ErrMsg = '辅助核算项目名称5未填写，不能填写填写核算项目5'
		RETURN -1
	END
END
--辅助核算项目名称5

--辅助核算项目名称6
IF(@AscFullName6 <>'' )
BEGIN
    IF( NOT EXISTS(SELECT Ascids FROM  #A WHERE FullName =@AscFullName6 ) )
	BEGIN
		SET @ErrMsg = '辅助核算项目名称6('+@AscFullName6+')不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SELECT @AscIds6 = Ascids FROM  #A WHERE FullName =@AscFullName6 
	END
END
ELSE
BEGIN
	IF(@HSUserCode6<> '' OR @HSFullName6 <> '')
	BEGIN
		SET @ErrMsg = '辅助核算项目名称6未填写，不能填写填写核算项目6'
		RETURN -1
	END
END
--辅助核算项目名称6


--验证辅助核算项
	CREATE  TABLE #Temp(AscIds INT, VALUE VARCHAR(100))
	DECLARE @Column     VARCHAR(50) , @ErrMsgTemp		VARCHAR(200) 
	DECLARE @sql NVARCHAR(max),@str NVARCHAR(1000),@str1 NVARCHAR(1000),
	@sqlWhere NVARCHAR(200)=' AND STypeId= '''+@StypeId +''' AND ATypeId='''+ @AtypeId+ ''' AND cid ='+CONVERT(VARCHAR(10),@Cid)  

	DECLARE @Number INT
	SET @Number = 4
	
	IF(@AscIds1 >0)
	BEGIN
		IF @AscIds1 > 4
			SET @Number += 1
		EXEC Query_Ac_Assist @StypeId,@AscIds1,@HSUserCode1,@HSFullName1,1,@Column OUTPUT,@value1 OUTPUT,@ErrMsgTemp OUTPUT
		IF( @ErrMsgTemp IS NOT NULL)
		BEGIN
			SET @ErrMsg = @ErrMsgTemp
			RETURN -1
		END
		INSERT INTO #Temp ( AscIds, VALUE )VALUES (@AscIds1, @value1 )
		SET @sql = 'SELECT @groupid = t.GroupId FROM (
					SELECT STypeId,ATypeId,GroupId,cid,
						  MAX(CASE Ascids WHEN '+CAST(@AscIds1 AS VARCHAR)+' THEN FieldValue ELSE NULL END) AS fzhs1,
						  MAX(CASE Ascids WHEN '+CAST(@AscIds2 AS VARCHAR)+' THEN FieldValue ELSE NULL END) AS fzhs2,
						  MAX(CASE Ascids WHEN '+CAST(@AscIds3 AS VARCHAR)+' THEN FieldValue ELSE NULL END) AS fzhs3,
						  MAX(CASE Ascids WHEN '+CAST(@AscIds4 AS VARCHAR)+' THEN FieldValue ELSE NULL END) AS fzhs4,
						  MAX(CASE Ascids WHEN '+CAST(@AscIds5 AS VARCHAR)+' THEN FieldValue ELSE NULL END) AS fzhs5,
						  MAX(CASE Ascids WHEN '+CAST(@AscIds6 AS VARCHAR)+' THEN FieldValue ELSE NULL END) AS fzhs6
					FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail
					WHERE  STypeId='''+@StypeId+' ''
					and ATypeId='''+@AtypeId+'''
					and cid = '+CONVERT(VARCHAR(10),@Cid)+'
					GROUP BY ATypeId,GroupId ,STypeId ,cid )
				as t
				where 1=1 '
				SET @sql+=' and t.'+@Column+'='''+@value1 +''''
		
		
	END
	IF (@AscIds2 >0)
	BEGIN
		IF @AscIds2 > 4
			SET @Number += 1
		EXEC Query_Ac_Assist @StypeId,@AscIds2,@HSUserCode2,@HSFullName2,2,@Column OUTPUT,@value2 OUTPUT,@ErrMsgTemp OUTPUT
		IF( @ErrMsgTemp IS NOT NULL)
		BEGIN
			SET @ErrMsg = @ErrMsgTemp
			RETURN -1
		END
		INSERT INTO #Temp ( AscIds, VALUE )VALUES (@AscIds2, @value2 )
		SET @sql+=' and t.'+@Column+'='''+@value2 +''''
	END
	IF (@AscIds3 >0)
	BEGIN
		IF @AscIds3 > 4
			SET @Number += 1
		EXEC Query_Ac_Assist @StypeId,@AscIds3,@HSUserCode3,@HSFullName3,3,@Column OUTPUT,@value3 OUTPUT,@ErrMsgTemp OUTPUT
		IF( @ErrMsgTemp IS NOT NULL)
		BEGIN
			SET @ErrMsg = @ErrMsgTemp
			RETURN -1
		END
		INSERT INTO #Temp ( AscIds, VALUE )VALUES (@AscIds3, @value3 )
		SET @sql+=' and t.'+@Column+'='''+@value3 +''''
	END
	IF (@AscIds4 >0)
	BEGIN
		IF @AscIds4 > 4
			SET @Number += 1
		EXEC Query_Ac_Assist @StypeId,@AscIds4,@HSUserCode4,@HSFullName4,4,@Column OUTPUT,@value4 OUTPUT,@ErrMsgTemp OUTPUT
		IF( @ErrMsgTemp IS NOT NULL)
		BEGIN
			SET @ErrMsg = @ErrMsgTemp
			RETURN -1
		END
		INSERT INTO #Temp ( AscIds, VALUE )VALUES (@AscIds4, @value4 )
		SET @sql+=' and t.'+@Column+'='''+@value4 +''''
	END
	
    IF (@AscIds5 >0)
	BEGIN
		IF @AscIds5 > 4
			SET @Number += 1
		EXEC Query_Ac_Assist @StypeId,@AscIds5,@HSUserCode5,@HSFullName5,5,@Column OUTPUT,@value5 OUTPUT,@ErrMsgTemp OUTPUT
		IF( @ErrMsgTemp IS NOT NULL)
		BEGIN
			SET @ErrMsg = @ErrMsgTemp
			RETURN -1
		END
		INSERT INTO #Temp ( AscIds, VALUE )VALUES (@AscIds5, @value5 )
		SET @sql+=' and t.'+@Column+'='''+@value5 +''''
	END
	
    IF (@AscIds6 >0)
	BEGIN
		IF @AscIds6 > 4
			SET @Number += 1
		EXEC Query_Ac_Assist @StypeId,@AscIds6,@HSUserCode6,@HSFullName6,6,@Column OUTPUT,@value6 OUTPUT,@ErrMsgTemp OUTPUT
		IF( @ErrMsgTemp IS NOT NULL)
		BEGIN
			SET @ErrMsg = @ErrMsgTemp
			RETURN -1
		END
		INSERT INTO #Temp ( AscIds, VALUE )VALUES (@AscIds6, @value6 )
		SET @sql+=' and t.'+@Column+'='''+@value6 +''''
	END
	

--验证辅助核算项end

	exec sp_executesql @sql,N'@groupid int output',@groupid OUTPUT

END
--启用辅助核算

--本年累计借方	本年累计贷方	期初余额
DECLARE @FDebitFor1  NUMERIC(24, 10)  ,@FCreditFor1  NUMERIC(24, 10)  ,@IniTotalFor1  NUMERIC(24, 10)
DECLARE @MaxValue  NUMERIC(24, 10)  = 999999999999.99, @MinValue  NUMERIC(24, 10) = -999999999999.99

DECLARE @RoundTotal INT
SELECT @RoundTotal =DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName='total'
IF ( @strFDebitFor1 = '' ) 
BEGIN
	SET @FDebitFor1 = 0
	--SET @ErrMsg = '本年累计借方请输入数字'
    --RETURN -1
END
ELSE  IF ( ISNUMERIC(@strFDebitFor1) <> 1 ) 
BEGIN
    SET @ErrMsg = '本年累计借方请输入数字'
    RETURN -1
END
ELSE 
	BEGIN
		IF( @RoundTotal <( len(@strFDebitFor1)-charindex('.',@strFDebitFor1))AND charindex('.',@strFDebitFor1) > 0)
		BEGIN
			SET @ErrMsg = '本年累计借方小数位数大于'+CAST(@RoundTotal AS VARCHAR(4))+'位，不允许导入'
			RETURN -1
		END
		
		SELECT  @FDebitFor1 = CONVERT( NUMERIC(24, 10) , @strFDebitFor1)
		
		IF(@FDebitFor1 > @MaxValue)
		BEGIN
			SET @ErrMsg = '本年累计借方最大值不能大于999999999999.9999999999'
			RETURN -1
		END
		IF(@FDebitFor1 < @MinValue)
		BEGIN
			SET @ErrMsg = '本年累计借方最小值不能小于-999999999999.9999999999'
			RETURN -1
		END
	END
        
IF ( @strFCreditFor1 = '' ) 
BEGIN
	SET @FCreditFor1 = 0
	--SET @ErrMsg = '本年累计贷方请输入数字'
    --RETURN -1
END
ELSE  IF ( ISNUMERIC(@strFCreditFor1) <> 1 ) 
BEGIN
    SET @ErrMsg = '本年累计贷方请输入数字'
    RETURN -1
END
ELSE 
	BEGIN
		IF( @RoundTotal <( len(@strFCreditFor1)-charindex('.',@strFCreditFor1))AND charindex('.',@strFCreditFor1) > 0)
		BEGIN
			SET @ErrMsg = '本年累计贷方小数位数大于'+CAST(@RoundTotal AS VARCHAR(4))+'位，不允许导入'
			RETURN -1
		END
		
		SELECT  @FCreditFor1 = CONVERT( NUMERIC(24, 10) , @strFCreditFor1)
		
		IF(@FCreditFor1 > @MaxValue)
		BEGIN
			SET @ErrMsg = '本年累计贷方最大值不能大于999999999999.9999999999'
			RETURN -1
		END
		IF(@FCreditFor1 < @MinValue)
		BEGIN
			SET @ErrMsg = '本年累计贷方最小值不能小于-999999999999.9999999999'
			RETURN -1
		END
	END
	
IF ( @strIniTotalFor1 = '' ) 
BEGIN
	SET @IniTotalFor1 = 0
	--SET @ErrMsg = '期初余额请输入数字'
    --RETURN -1
END
ELSE  IF ( ISNUMERIC(@strIniTotalFor1) <> 1 ) 
BEGIN
    SET @ErrMsg = '期初余额请输入数字'
    RETURN -1
END
ELSE 
	BEGIN
		IF( @RoundTotal <( len(@strIniTotalFor1)-charindex('.',@strIniTotalFor1))AND charindex('.',@strIniTotalFor1) > 0)
		BEGIN
			SET @ErrMsg = '期初余额小数位数大于'+CAST(@RoundTotal AS VARCHAR(4))+'位，不允许导入'
			RETURN -1
		END
		
		SELECT  @IniTotalFor1 = CONVERT( NUMERIC(24, 10) , @strIniTotalFor1)
		
		IF(@IniTotalFor1 > @MaxValue)
		BEGIN
			SET @ErrMsg = '期初余额最大值不能大于999999999999.9999999999'
			RETURN -1
		END
		IF(@IniTotalFor1 < @MinValue)
		BEGIN
			SET @ErrMsg = '期初余额最小值不能小于-999999999999.9999999999'
			RETURN -1
		END
	END
	
IF(@IniTotalFor1 = 0 AND @FDebitFor1 = 0 AND @FCreditFor1 = 0)
BEGIN
	SET @ErrMsg = '本年累计借方、本年累计贷方和期初余额不能全为空或0'
	RETURN -1
END
IF(@SyType=1)
	BEGIN
		--本年累计损益实际发生额判断
		IF(@FDebitFor1<>@FCreditFor1 AND @FDebitFor1<>0 AND ISNULL(@strFYTotalFor,'')='')
			BEGIN	
				SET @ErrMsg = '当 本年累计借方 不等于 本年累计贷方 且都不等于0时，本年累计损益实际发生额不能为空'
				RETURN -1
			END
		ELSE IF(@FDebitFor1=@FCreditFor1 AND @FDebitFor1=0 AND ISNULL(@strFYTotalFor,'0')<>'0')
			BEGIN	
				SET @ErrMsg = '当 本年累计借方 等于 本年累计贷方 且都等于0时，本年累计损益实际发生额只能为0或空'
				RETURN -1
			END
		ELSE IF(@FDebitFor1=@FCreditFor1 AND @FDebitFor1<>0 AND @IniTotalFor1>0 AND CAST(ISNULL(@strFYTotalFor,'0') AS NUMERIC(24,10))<0)
			BEGIN	
				SET @ErrMsg = '当 本年累计借方 不等于 本年累计贷方 且都不等于0且期初余额大于0时本年累计损益实际发生额大于0'
				RETURN -1
			END
		ELSE IF(@FDebitFor1=@FCreditFor1 AND @FDebitFor1<>0 AND @IniTotalFor1<0 AND CAST(ISNULL(@strFYTotalFor,'0') AS NUMERIC(24,10))>0)
			BEGIN	
				SET @ErrMsg = '当 本年累计借方 不等于 本年累计贷方 且都不等于0且期初余额大于0时本年累计损益实际发生额小于0'
				RETURN -1
			END

		SET @FYTotalFor=CAST(ISNULL(@strFYTotalFor,'0') AS NUMERIC(24,10))
	END
--IF(@FDebitFor1 = 0 AND @FCreditFor1= 0 AND  @IniTotalFor1 =0)
--BEGIN

--RETURN 1
--END

--借  年初余额= (期初余额 + 贷方 - 借方)/汇率
	--贷  年初余额= (期初余额 - 贷方 + 借方)/汇率
	--IF @BasisType = 1
	--BEGIN
	--	SET @FDebit = @FDebitFor1/@Rate
	--	SET @FCredit = @FCreditFor1/@Rate
	--	SET @IniTotal = @IniTotalFor1/@Rate
	--END
	--ELSE
	--BEGIN
	--	SET @FDebit = @FDebitFor1*@Rate
	--	SET @FCredit = @FCreditFor1*@Rate
	--	SET @IniTotal = @IniTotalFor1*@Rate
	--END
	
	SET @FDebit = @FDebitFor1
	SET @FCredit = @FCreditFor1
	SET @IniTotal = @IniTotalFor1
	--@Fdc INT ,--Fdc 借贷方向：1.借 -1.贷
	IF(@Fdc = 1)
	BEGIN
		SET @IniYTotalFor = @IniTotalFor1 + @FCreditFor1 -@FDebitFor1
		SET @IniYTotal = @IniTotal + @FCredit - @FDebit
	END
	ELSE
	BEGIN
		SET @IniYTotalFor = @IniTotalFor1 - @FCreditFor1 + @FDebitFor1
		SET @IniYTotal = @IniTotal - @FCredit + @FDebit
	END
	IF (@SyType = 1)
	BEGIN
		IF(@Fdc = 1)
		BEGIN
			SET @IniYTotalFor = @IniTotalFor1 - @FCreditFor1 + @FDebitFor1
			SET @IniYTotal = @IniTotal - @FCredit + @FDebit
		END
		ELSE
		BEGIN
			SET @IniYTotalFor = @IniTotalFor1 + @FCreditFor1 - @FDebitFor1
			SELECT @IniYTotalFor
			SET @IniYTotal = @IniTotal + @FCredit - @FDebit
		END

	END
	IF @BasisType = 1
	BEGIN
		SET @IniYTotal = @IniYTotal / @rate
		SET @FDebit = @FDebitFor1/@Rate
		SET @FCredit = @FCreditFor1/@Rate
		SET @IniTotal = @IniTotalFor1/@Rate
		SET @FYTotal=@FYTotalFor/@Rate
	END
	ELSE
	BEGIN
		SET @IniYTotal = @IniYTotal * @rate
		SET @FDebit = @FDebitFor1*@Rate
		SET @FCredit = @FCreditFor1*@Rate
		SET @IniTotal = @IniTotalFor1*@Rate
		SET @FYTotal=@FyTotalFor*@Rate
	END
	IF (@SyType = 1)
	BEGIN
		SET @IniYTotal = 0
		SET @IniYTotalFor = 0
	END
	ELSE --如果不是损益类科目，即使输入了本年累计损益实际发生额 也等于0
	BEGIN
		SET @FyTotal = 0
		SET @FyTotalFor = 0
	END


-- 辅助核算操作s
IF(@Fzhs = 1)
BEGIN
		IF (@SyType = 1)
		BEGIN
			SET @IniTotal = @FyTotal
			SET @IniTotalFor = @IniYTotalFor
			SET @IniTotalFor1 = @FyTotalFor
		END
	
	DECLARE   @IniYTotalbf numeric,
 
          @FDebitbf numeric,
 
          @FCreditbf numeric,
    
          @IniTotalbf numeric
	
	DECLARE @MaxGroupId INT		
	BEGIN TRAN operation
	DECLARE @tran_error int
	SET @tran_error = 0
    BEGIN TRY  
	
	--有数据先删除
	DELETE Ac_IniAccount WHERE STypeId = @StypeId AND ATypeId= @AtypeId AND Cid = @Cid AND FYear = @FYear AND FPeriod = @FPeriod 
	DELETE Ac_IniAccount_Assist_CheckItems  WHERE STypeId = @StypeId AND ATypeId= @AtypeId AND Cid = @Cid AND FYear = @FYear AND FPeriod = @FPeriod 
	DELETE Ac_IniAccount_Assist_CheckItems_Detail  WHERE STypeId = @StypeId AND ATypeId= @AtypeId AND Cid = @Cid AND FYear = @FYear AND FPeriod = @FPeriod AND GroupId = ISNULL(@groupid,0)
		
		--最大分组id
	SELECT @MaxGroupId= ISNULL(MAX(GroupId),0)
	FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail 
		WHERE  STypeId = @StypeId
			AND ATypeId= @AtypeId
			AND Cid = @Cid
			AND FYear = @FYear 
			AND FPeriod = @FPeriod 
	IF( @MaxGroupId<=0)
	BEGIN
		SET @MaxGroupId = 1
	END 
	ELSE
	begin
		SET @MaxGroupId = @MaxGroupId+1
	end
	DECLARE  @aid varchar(20),@avlue VARCHAR(50)
	DECLARE My_Cursor CURSOR SCROLL FOR SELECT AscIds,VALUE FROM #Temp

	OPEN My_Cursor
	FETCH NEXT FROM My_Cursor INTO @aid ,@avlue 	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO dbo.Ac_IniAccount_Assist_CheckItems_Detail
				( STypeId ,
				  ATypeId ,
				  Cid ,
				  Ascids ,
				  FieldValue ,
				  IniYTotal ,
				  IniYTotalFor ,
				  FDebit ,
				  FDebitFor ,
				  FCredit ,
				  FCreditFor ,
				  IniTotal ,
				  IniTotalFor ,
				  GroupId ,
				  FYear ,
				  FPeriod ,
				  FYTotal ,
				  FYTotalFor
				)
		VALUES  ( @STypeId , -- STypeId - varchar(50)
				  @ATypeId , -- ATypeId - varchar(50)
				  @Cid, -- Cid - int
				  @aid , -- Ascids - int
				  @avlue , -- FieldValue - varchar(50)
				  dbo.F_RoundTotal(@IniYTotal), -- IniYTotal - numeric
				  dbo.F_RoundTotal(@IniYTotalFor) , -- IniYTotalFor - numeric
				  dbo.F_RoundTotal(@FDebit) , -- FDebit - numeric
				  dbo.F_RoundTotal(@FDebitFor1) , -- FDebitFor - numeric
				  dbo.F_RoundTotal(@FCredit) , -- FCredit - numeric
				  dbo.F_RoundTotal(@FCreditFor1) , -- FCreditFor - numeric
				  dbo.F_RoundTotal(@IniTotal) , -- IniTotal - numeric
				  dbo.F_RoundTotal(@IniTotalFor1) , -- IniTotalFor - numeric
				  @MaxGroupId , -- GroupId - int
				  @FYear , -- FYear - varchar(10)
				  @FPeriod , -- FPeriod - int
				  dbo.F_RoundTotal(@FyTotal) , -- FYTotal - numeric
				  dbo.F_RoundTotal(@FyTotalFor) -- FYTotalFor - numeric
				)
		
	FETCH NEXT FROM My_Cursor INTO @aid ,@avlue 
	END

	CLOSE My_Cursor 
	DEALLOCATE My_Cursor

	--插入账务期初辅助核算总表数据
	INSERT INTO Ac_IniAccount_Assist_CheckItems(STypeId,ATypeId,Cid,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,FYear,FPeriod,FYTotal,FYTotalFor)
	SELECT D.STypeId,D.ATypeId,D.Cid,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,D.FYear,D.FPeriod,FYTotal,FYTotalFor 
	FROM Ac_IniAccount_Assist_CheckItems_Detail D 
	INNER JOIN (
		SELECT STypeId,ATypeId,FYear,FPeriod,Cid,GroupId,MIN(Ascids) Ascids 
		FROM Ac_IniAccount_Assist_CheckItems_Detail 
		WHERE STypeId = @StypeId AND ATypeId= @AtypeId AND Cid = @Cid AND FYear = @FYear AND FPeriod = @FPeriod 
		GROUP BY STypeId,ATypeId,FYear,FPeriod,Cid,GroupId
	) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.FYear=D.FYear AND F.FPeriod=D.FPeriod AND F.GroupId=D.GroupId AND F.Cid=D.Cid AND F.Ascids=D.Ascids WHERE D.STypeId = @StypeId AND D.ATypeId= @AtypeId AND D.Cid = @Cid AND D.FYear = @FYear AND D.FPeriod = @FPeriod 
	--插入账务期初科目表数据
	INSERT INTO Ac_IniAccount(STypeId,ATypeId,Cid,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,FYear,FPeriod,FYTotal,FYTotalFor,FYTotalDebit,FYTotalDebitFor,FYTotalCredit,FYTotalCreditFor)
	SELECT STypeId,ATypeId,Cid,SUM(IniYTotal) IniYTotal,SUM(IniYTotalFor) IniYTotalFor,SUM(FDebit) FDebit,SUM(FDebitFor) FDebitFor,SUM(FCredit) FCredit,SUM(FCreditFor) FCreditFor,SUM(IniTotal) IniTotal,SUM(IniTotalFor) IniTotalFor,FYear,FPeriod,SUM(FYTotal) FYTotal,SUM(FYTotalFor) FYTotalFor,0 FYTotalDebit,0 FYTotalDebitFor,0 FYTotalCredit,0 FYTotalCreditFor FROM Ac_IniAccount_Assist_CheckItems WHERE STypeId = @StypeId AND ATypeId= @AtypeId AND Cid = @Cid AND FYear = @FYear AND FPeriod = @FPeriod 
	GROUP BY STypeId,ATypeId,Cid,FYear,FPeriod
		
	--END
	 END TRY

	BEGIN CATCH
   -- PRINT '出现异常，错误编号：' + convert(varchar,error_number()) + ',错误消息：' + error_message()
    SET @tran_error = @tran_error + 1
END CATCH

IF(@tran_error > 0)
    BEGIN
        --执行出错，回滚事务
        ROLLBACK TRAN;
        PRINT '错误消息:'+error_message();
    END
ELSE
    BEGIN
        --没有异常，提交事务
        COMMIT TRAN;
		SET  @ReturnID = @@ROWCOUNT
		RETURN @ReturnID
    END
	
	
	

END
-- 非辅助核算操作e
IF(@Fzhs = 0)
BEGIN

	IF(EXISTS(SELECT 1 FROM Ac_IniAccount WHERE STypeId = @StypeId AND ATypeId= @AtypeId AND Cid = @Cid AND FYear = @FYear AND FPeriod = @FPeriod ))	
	BEGIN
		DELETE Ac_IniAccount WHERE STypeId = @StypeId AND ATypeId= @AtypeId AND Cid = @Cid AND FYear = @FYear AND FPeriod = @FPeriod 
	END

IF(@SyType =1 AND @Period <>1 AND @FYear=@Year )
BEGIN
	SET @IniTotal = @FyTotal
	SET @IniTotalFor = @FyTotalFor
	SET @IniTotalFor1 = @FyTotalFor
END

	INSERT INTO dbo.Ac_IniAccount
        ( STypeId ,
          ATypeId ,
          iniYTotal ,
          iniYTotalFor ,
          FDebit ,
          FDebitFor ,
          FCredit ,
          FCreditFor ,
          iniTotal ,
          iniTotalFor ,
          Cid ,
          FYear ,
          FPeriod ,
          FYTotal ,
          FYTotalFor ,
          FYTotalDebit ,
          FYTotalDebitFor ,
          FYTotalCredit ,
          FYTotalCreditFor
        )
VALUES  (  @STypeId , -- STypeId - varchar(50)
				  @ATypeId , -- ATypeId - varchar(50)
         dbo.F_RoundTotal(@IniYTotal), -- IniYTotal - numeric
				  dbo.F_RoundTotal(@IniYTotalFor) , -- IniYTotalFor - numeric
				  dbo.F_RoundTotal(@FDebit) , -- FDebit - numeric
				  dbo.F_RoundTotal(@FDebitFor1) , -- FDebitFor - numeric
				  dbo.F_RoundTotal(@FCredit) , -- FCredit - numeric
				  dbo.F_RoundTotal(@FCreditFor1) , -- FCreditFor - numeric
				  dbo.F_RoundTotal(@IniTotal) , -- IniTotal - numeric
				  dbo.F_RoundTotal(@IniTotalFor1) , -- IniTotalFor - numeric
         @Cid , -- Cid - int
          @FYear , -- FYear - varchar(10)
          @FPeriod , -- FPeriod - int
          dbo.F_RoundTotal(@FyTotal) , -- FYTotal - numeric
          dbo.F_RoundTotal(@FyTotalFor) , -- FYTotalFor - numeric
          0 , -- FYTotalDebit - numeric
          0 , -- FYTotalDebitFor - numeric
          0 , -- FYTotalCredit - numeric
          0  -- FYTotalCreditFor - numeric
        )


END





 

GO





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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	创 建 者：李灏龙
	日    期：2017-07-26
	创建原因：导入会员卡期初储值
*/

CREATE               PROCEDURE [dbo].[Gp_ImportAc_VipIniCz]
(
	@VipCardCode	VARCHAR(50),		--会员卡号
	@sUserCode		VARCHAR(50),		--分支机构usercode
	@qCcZMoney      VARCHAR(100),		--期初储值金额
	@ReturnID		VARCHAR(100) OUTPUT,
	@ErrMsg			VARCHAR(500) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@StypeId	VARCHAR(50)	--分支机构ID
		,@VipCardId	INT		--会员卡id
		
SET @ErrMsg = '导入成功'

-------------------------------------转换输入参数---------------------------------------------
--分支机构
SELECT @StypeId =typeId FROM dbo.SType WHERE UserCode = @sUserCode 

IF(ISNULL(@StypeId,'') = '')
BEGIN
	SET @ErrMsg = '分支机构编号错误'
	RETURN -1
END

IF(EXISTS(SELECT typeId FROM dbo.SType WHERE typeid = @StypeId AND  sonnum>0))
BEGIN
	SET @ErrMsg = '该分支机构为父节点，不能导入'
	RETURN -1
END

IF EXISTS(SELECT * FROM dbo.SType_UserConfig WHERE StypeId = @stypeid AND Value = 1)
BEGIN
	SET @ErrMsg = '该分支机构已开帐，不能导入'
	RETURN -1
END 

--会员卡
SELECT @VipCardId = VipCardID FROM dbo.nVipCardSign WHERE VipCardCode = @VipCardCode

IF(ISNULL(@VipCardId,'') = '')
BEGIN
	SET @ErrMsg = '会员卡号错误'
	RETURN -1
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSign WHERE VipCardID = @VipCardid AND IsCz = 0)
BEGIN
	SET @ErrMsg = '该会员卡不是储值卡'
	RETURN -1
END 

IF EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSign WHERE VipCardID = @VipCardid AND deleted = 1)
BEGIN
	SET @ErrMsg = '该会员卡已经停用'
	RETURN -1
END 
--985 新增判断适用机构
IF EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSign V WHERE V.VipCardCode=@VipCardCode AND V.isApplyAllStype=0 AND NOT EXISTS(SELECT * FROM VipCard_ApplyStype ApS INNER JOIN SType S ON S.UserCode=@sUserCode AND S.TypeId=ApS.StypeId AND VipCardID=V.VipCardID))
BEGIN
	SELECT	@ErrMsg='会员卡【'+(SELECT VipCardCode FROM nVipCardSign WHERE VipCardID=@VipCardid)+'】不适用于当前机构！'
	RETURN -1
END 

--期初储值金额
IF ISNULL(@qCcZMoney,'')=''
BEGIN
	SET @ErrMsg = '请输入期初储值金额！'
	RETURN -1
END

IF CAST(@qCcZMoney AS numeric(24,10))  < 0
BEGIN
	SET @ErrMsg = '期初储值金额小于0'
	RETURN -1
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSignStype WHERE VipCardID = @VipCardid AND StypeId = @stypeid)
BEGIN
	INSERT INTO dbo.nVipCardSignStype
	        ( VipCardID ,
	          StypeId ,
	          qCczMoney ,
	          lJczMoney ,
	          lJxFczMoney ,
	          bNczMoney ,
	          bNxFczMoney ,
	          cZyeMoney ,
	          lJxFMoney ,
	          bNxFMoney
	        )
	SELECT	c.VipCardID ,
			@stypeid,
			0 ,
			0,
			0,
			0 ,
			0,
			0,
			0,
			0 
	FROM dbo.nVipCardSign c
	WHERE c.VipCardID = @VipCardid
END 

DECLARE	@oldqcczmoney	NUMERIC(24,10)
		,@ljczmoney		NUMERIC(24,10)
		,@xfczmoney		NUMERIC(24,10)
		
SELECT @oldqcczmoney = qCczMoney FROM dbo.nVipCardSignStype WHERE VipCardID = @VipCardid AND StypeId = @StypeId
SELECT @ljczmoney=SUM(lJczMoney),@xfczmoney=SUM(lJxFczMoney) FROM dbo.nVipCardSignStype WHERE VipCardID = @VipCardid

IF @ljczmoney+@qCcZMoney-@oldqcczmoney < @xfczmoney
BEGIN
	SET @ErrMsg = '修改期初储值余额后，会造成储值余额为负数'
	RETURN -1
END 

UPDATE nVipCardSignStype 
SET	qCczMoney = @qcczmoney
	,cZyeMoney=@qcczmoney
	,lJczMoney = @qcczmoney+lJxFczMoney
WHERE	VipCardID = @VipCardid AND StypeId = @stypeid

IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'inicanmodify' AND SubValue = 'T')
BEGIN
	--更新其他业务期初中【会员储值】的期初值
	DECLARE @numQcTotal  NUMERIC(24, 10) 
			,@sys_cid	INT
	SELECT	@sys_cid = CId FROM dbo.Ac_Currency WHERE Sysrow = 1
	SELECT  @numQcTotal = ISNULL(SUM(qCczMoney),0) FROM nVipCardSignStype WHERE StypeId = @stypeid
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.AType_Total WHERE ATypeID = '34' AND STypeID = @stypeid AND CID = @sys_cid )
		UPDATE  dbo.AType_Total SET Total00 = ISNULL(@numQcTotal,0),Ntotal00=ISNULL(@numQcTotal,0) WHERE ATypeID = '34' AND STypeID = @stypeid AND CID = @sys_cid
	ELSE
		INSERT dbo.AType_Total
		        ( ATypeID ,
		          STypeID ,
		          Total00 ,
		          Total ,
		          CID ,
		          Ntotal00 ,
		          Ntotal
		        )
		VALUES  ( '34' , -- ATypeID - varchar(50)
		          @stypeid , -- STypeID - varchar(50)
		          ISNULL(@numQcTotal,0) , -- Total00 - numeric
		          0 , -- Total - numeric
		          @sys_cid , -- CID - int
		          ISNULL(@numQcTotal,0) , -- Ntotal00 - numeric
		          0  -- Ntotal - numeric
		        )
END

SET  @ReturnID = @@ROWCOUNT
RETURN 0
 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ImportAcAccount]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ImportAcAccount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/31
	Description	:	从系统预置模版导入到科目表
*/

CREATE PROCEDURE GP_ImportAcAccount
(
	@SubId		INT,			--科目表引入的是哪套会计制度
	@EtypeId	VARCHAR(100),	--操作员ID
	@StypeId	VARCHAR(100),	--分支机构
	@DtId		VARCHAR(MAX),	--当设置了DtId,表明只引入行业部分数据
	@AcId		INT				--科目表 TREEID
)
--@encode$--
AS 
SET NOCOUNT ON

-----检查

IF NOT EXISTS ( SELECT  1 FROM Ac_Account_Set_List WHERE SubId = @SubId) 
	BEGIN
		RAISERROR (N'科目表[%d]不存在.', 15, 1, @SubId) ;
		RETURN -1 ; 
	END

IF NOT EXISTS ( SELECT  1 FROM SType WHERE TypeId = @StypeId ) 
    BEGIN
        RAISERROR (N'分支机构[%s]不存在.', 15, 1, @StypeId) ;
        RETURN -1 ; 
    END

--当设置了DtId,表明只引入行业部分数据
DECLARE @useTemp INT=0 

IF ISNULL(@DtId,'')<>''
    BEGIN
        SET @useTemp = 1 ;
        
        SELECT a AS DtId INTO #temp_DtID FROM [dbo].[f_split](@dtid, ',') ;
    END

DECLARE @DateNow DATETIME ;
DECLARE @SelectRowCount INT ;
DECLARE @InsertRowCount INT ;

SET @DateNow = GETDATE() ;

IF @useTemp = 1
    BEGIN
        SELECT  @SelectRowCount = COUNT(1)
        FROM    Ac_account_Set_Detail d
                JOIN #temp_DtID t ON t.DtId = d.DtId
        WHERE   d.SubId = @SubId ;
        
       IF NOT EXISTS(SELECT TOP 1 1 FROM #temp_DtID)
        BEGIN
            RAISERROR (N'科目表%d中没有符合要求的数据.', 15, 1, @SubId) ;
            RETURN -1 ; 
        END
        
    END		
  
DECLARE @syscid INT
SELECT TOP 1 @syscid = cid FROM Ac_Currency WHERE Sysrow = 1
IF @syscid IS NULL
	BEGIN
		RAISERROR (N'由于系统中本位币未设置，引入科目失败.', 15, 1, @SubId) ;
		RETURN -1 ; 
	END



DECLARE @ThisXiWaNo INT ;
SELECT @ThisXiWaNo = ISNULL(MAX(XiWaMaxNumber),0)+1 FROM Ac_Account 

BEGIN TRANSACTION

--先清除掉Ac_Account/Ac_Account_Assist_CheckItems表中原来的数据
DELETE  Ac_Account WHERE StypeId = @StypeId AND AcId=@AcId
DELETE Ac_Account_Assist_CheckItems WHERE STypeId = @STypeId AND AcId=@AcId

IF @useTemp = 0 
    BEGIN
		-- 先引入分类
		INSERT  INTO Ac_Account
		(
			StypeId,
			TypeId,
			ParId,
			Leveal,
			SonNum,
			SonCount,
			[group],
			UserCode,
			FullName,
			Name,
			Fdc,
			IsCash,
			IsBank,
			IsOther,
			--IsDiary,
			Comment,
			PyCode,
			ETypeId,
			CreateDateTime,
			FContact,
			CheckType,
			XiWaMaxNumber,
			AcId
			--MainItems,
			--AdditionItems,
			--ExchId,
			--FAcctint,
			--FAcnt,
			--AscIds,
			--FAdjustRate,
			--FContact,
			--FInterest,
			--FintRate
		)   
		SELECT  
			@STypeId,				--StypeId,
			TypeId,				--TypeId,
			ParId,				--ParId,
			Leveal,				--Leveal,
			SonNum,				--SonNum,
			SonCount,			--SonCount,
			[group],            --group
			UserCode,			--UserCode,
			FullName,			--FullName,
			ISNULL(Name,''),	--Name,
			Fdc,				--Fdc,
			IsCash,				--IsCash,
			IsBank,				--IsBank,
			IsOther,			--IsOther,
			--null,				--IsDiary,
			ISNULL(Comment,''),	--Comment,
			PyCode,				--PyCode,
			@ETypeId,			--ETypeId,
			@DateNow,			--CreateDateTime,
			FContact,           --FContact,
			CheckType,          --CheckType
			@ThisXiWaNo,      --XiWaMaxNumber
			@AcId
			--NULL,				--MainItems, 
			--NULL,				--AdditionItems, 
			--NULL,				--ExchId, 
			--NULL,				--FAcctint, 
			--NULL,				--FAcnt, 
			--NULL,				--AscIds, 
			--NULL,				--FAdjustRate, 
			--NULL,				--FContact, 
			--NULL,				--FInterest, 
			--NULL				--FintRate 		
		FROM Ac_account_Set_Detail
		WHERE
			SubId = @SubId 
			AND Leveal = 1
      
        -- 引入非分类
        INSERT  INTO Ac_Account
		(
			StypeId,
			TypeId,
			ParId,
			Leveal,
			SonNum,
			SonCount,
			[group],
			UserCode,
			FullName,
			Name,
			Fdc,
			IsCash,
			IsBank,
			IsOther,
			--IsDiary,
			Comment,
			PyCode,
			ETypeId,
			CreateDateTime,
			FContact,
			CheckType,
			XiWaMaxNumber,
			AcId
			--MainItems,
			--AdditionItems,
			--ExchId,
			--FAcctint,
			--FAcnt,
			--AscIds,
			--FAdjustRate,
			--FContact,
			--FInterest,
			--FintRate
		)   
		SELECT  
			@STypeId,				--StypeId,
			TypeId,				--TypeId,
			ParId,				--ParId,
			D.Leveal,				--Leveal,
			SonNum,				--SonNum,
			SonCount,			--SonCount,
			[group],            --group
			ISNULL(CASE WHEN D.Leveal<3 THEN D.UserCode ELSE dbo.F_GetNewUserCode(D.UserCode,D.Leveal) END,''),--UserCode,
			FullName,			--FullName,
			Name,	            --Name,
			Fdc,				--Fdc,
			IsCash,				--IsCash,
			IsBank,				--IsBank,
			IsOther,			--IsOther,
			--null,				--IsDiary,
			Comment,            --Comment,
			PyCode,           	--PyCode,
			@ETypeId,			--ETypeId,
			@DateNow,           --CreateDateTime
			FContact,           --FContact
			CheckType,			--CheckType,
			@ThisXiWaNo,		--XiWaMaxNumber
			@AcId
			--NULL,				--MainItems, 
			--NULL,				--AdditionItems, 
			--NULL,				--ExchId, 
			--NULL,				--FAcctint, 
			--NULL,				--FAcnt, 
			--NULL,				--AscIds, 
			--NULL,				--FAdjustRate, 
			--NULL,				--FContact, 
			--NULL,				--FInterest, 
			--NULL				--FintRate 		
		FROM Ac_account_Set_Detail D
		WHERE 
			SubId = @SubId 
			AND D.Leveal > 1;
    END
ELSE 
    BEGIN
		-- 先引入分类
		INSERT  INTO Ac_Account
		(
			StypeId,
			TypeId,
			ParId,
			Leveal,
			SonNum,
			SonCount,
			[group],
			UserCode,
			FullName,
			Name,
			Fdc,
			IsCash,
			IsBank,
			IsOther,
			--IsDiary,
			Comment,
			PyCode,
			ETypeId,
			CreateDateTime,
			FContact,
			CheckType,
			XiWaMaxNumber,
			AcId
			--MainItems,
			--AdditionItems,
			--ExchId,
			--FAcctint,
			--FAcnt,
			--AscIds,
			--FAdjustRate,
			--FContact,
			--FInterest,
			--FintRate
		)   
		SELECT  
			@STypeId,				--StypeId,
			TypeId,				--TypeId,
			ParId,				--ParId,
			Leveal,				--Leveal,
			SonNum,				--SonNum,
			SonCount,			--SonCount,
			[group],            --group
			UserCode,			--UserCode,
			FullName,			--FullName,
			ISNULL(Name,''),	--Name,
			Fdc,				--Fdc,
			IsCash,				--IsCash,
			IsBank,				--IsBank,
			IsOther,			--IsOther,
			--null,				--IsDiary,
			ISNULL(Comment,''),	--Comment,
			PyCode,				--PyCode,
			@ETypeId,			--ETypeId,
			@DateNow,			--CreateDateTime,
			FContact,           --FContact,
			CheckType,          --CheckType
			@ThisXiWaNo,        --XiWaMaxNumber
			@AcId
			--NULL,				--MainItems, 
			--NULL,				--AdditionItems, 
			--NULL,				--ExchId, 
			--NULL,				--FAcctint, 
			--NULL,				--FAcnt, 
			--NULL,				--AscIds, 
			--NULL,				--FAdjustRate, 
			--NULL,				--FContact, 
			--NULL,				--FInterest, 
			--NULL				--FintRate 		
		FROM Ac_account_Set_Detail
		WHERE 
			SubId = @SubId 
			AND Leveal = 1

		INSERT  INTO Ac_Account
		(
			StypeId,
			TypeId,
			ParId,
			Leveal,
			SonNum,
			SonCount,
			[group],
			UserCode,
			FullName,
			Name,
			Fdc,
			IsCash,
			IsBank,
			IsOther,
			--IsDiary,
			Comment,
			PyCode,
			ETypeId,
			CreateDateTime,
			FContact,
			CheckType,
			XiWaMaxNumber,
			AcId
			--MainItems,
			--AdditionItems,
			--ExchId,
			--FAcctint,
			--FAcnt,
			--AscIds,
			--FAdjustRate,
			--FContact,
			--FInterest,
			--FintRate
		)   
		SELECT  
			@STypeId,				--StypeId,
			d.TypeId,			--TypeId,
			d.ParId,			--ParId,
			d.Leveal,			--Leveal,
			d.SonNum,			--SonNum,
			d.SonCount,			--SonCount,
			d.[group],          --group
			ISNULL(CASE WHEN D.Leveal<3 THEN D.UserCode ELSE dbo.F_GetNewUserCode(D.UserCode,D.Leveal) END,''),			--UserCode,
			d.FullName,			--FullName,
			d.Name,         	--Name,
			d.Fdc,				--Fdc,
			d.IsCash,			--IsCash,
			d.IsBank,			--IsBank,
			d.IsOther,			--IsOther,
			--null,				--IsDiary,
			d.Comment,          --Comment,
			d.PyCode,			--PyCode,
			@ETypeId,			--ETypeId,
			@DateNow,           --CreateDateTime
			FContact,           --fcontact
			CheckType,         --CheckType			
			@ThisXiWaNo,
			@AcId
			--NULL,				--MainItems, 
			--NULL,				--AdditionItems, 
			--NULL,				--ExchId, 
			--NULL,				--FAcctint, 
			--NULL,				--FAcnt, 
			--NULL,				--AscIds, 
			--NULL,				--FAdjustRate, 
			--NULL,				--FContact, 
			--NULL,				--FInterest, 
			--NULL				--FintRate 		
		FROM Ac_account_Set_Detail d
		INNER JOIN #temp_DtID t ON t.DtId = d.DtId
		WHERE   
			d.SubId = @SubId 
			AND D.Leveal > 1;
    END


--修改科目表-对应会计模板信息
DECLARE @SetFullName VARCHAR(200)=''
SELECT @SetFullName=FullName FROM Ac_Account_Set_List WHERE SubId=@SubId
UPDATE Ac_Table SET SetFullName=@SetFullName,SetId=@SubId WHERE AcId=@AcId

--========================================================修正数据=======================================
--一级科目父节点
UPDATE  Ac_Account SET ParId = '00000'
WHERE   
	TypeId IN ('00001', '00002', '00003', '00004', '00005', '00006')
	AND StypeId = @StypeId 
	AND AcId=@AcId;
--科目拼音         
UPDATE Ac_Account
SET PyCode = dbo.fun_getPY(FullName)
WHERE PyCode IS NULL
	OR LTRIM(RTRIM(PyCode)) = '' AND stypeid = @stypeid  AND AcId=@AcId
	
-- update FLEVEAL
-- 因为 资产 负债 现在变成分类了
-- 现在leveal=2 才是真正的1级，视觉上的1级
-- 依次上移一级
-- update sonnum soncount
UPDATE Ac_Account
SET
	SonNum = (SELECT COUNT(1)
				FROM Ac_Account a 
				WHERE 
					a.ParId = ac.TypeId 
					AND a.Leveal = ac.Leveal + 1 
					AND a.StypeId = ac.StypeId  
					AND AcId=@AcId
				),
	SonCount = ISNULL(CAST((SELECT MAX(Right(TypeID,5)) 
							FROM Ac_Account a 
							WHERE 
								a.ParId = ac.TypeId 
								AND a.Leveal = ac.Leveal + 1 
								AND a.StypeId = ac.StypeId 
								AND AcId=@AcId)
					AS INT),0),
	IsDiary = 0,
	MainItems = '',
	AdditionItems = '',
	ExchId = -1,
	FAcctint = 0,
	FAcnt = ASD.fcontact,
	Ascids = '',
	FAdjustRate = 0,
	FInterest = 0,
	fintrate = 0,
	FLEVEAL = ac.Leveal - 1,
	Deleted = 0,
	XiWaMaxNumber = 1,
	cid = @syscid,
	IsDist = 0,
	IsPreGather = 0,
	IsPrePay = 0,
	IsGather = 0,
	IsPay = 0,
	IsVip = 0               
From Ac_Account ac
INNER JOIN Ac_Account_Set_Detail ASD ON ASD.SubId=@SubId  AND  ASD.TypeId=ac.TypeId  --更新辅助FAcnt
WHERE 
	stypeid = @stypeid  
	AND AcId=@AcId
	
-- 核算往来必须拥有一个辅助核算单位（默认为往来单位4）
;WITH A AS (
	SELECT 
		StypeId,
		TypeId 
	FROM Ac_Account
	WHERE 
		stypeid = @StypeId 
		and fcontact = 1
		AND AcId=@AcId
)
INSERT INTO Ac_Account_Assist_CheckItems
(
	STypeId,
	ATypeId,
	Cid, 
	Ascids,
	AcId
)
SELECT 
	Stypeid,
	typeId,
	1,
	4,
	@AcId
FROM A
 
COMMIT TRANSACTION

RETURN 0 ;

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_ImportAccountData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[GP_ImportAccountData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	科目表导入
-- 时间：	2019-05-22
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [GP_ImportAccountData]
(
	@ParUserCode		VARCHAR(200)='',--父级编号
	@ParFullName		VARCHAR(200)='',--父级描名称
	@UserCode			VARCHAR(200)='',--编号
	@FullName			VARCHAR(200)='',--描名称
	@Name				VARCHAR(200),--科目简名
	@dde_Category		VARCHAR(200),--科目类别
	@Pycode				VARCHAR(200),--拼音码
	@Fdc				VARCHAR(200),--余额方向
	@Cid				VARCHAR(200),--外币核算
	@FadjustRate		VARCHAR(200),--期末调汇	
	@AdjustAccounts		VARCHAR(200),--数量核算
	@UnitId				VARCHAR(200),--计量单位
	@IsCash				VARCHAR(200),--现金科目
	@IsBank				VARCHAR(200),--银行科目
	@IsOther			VARCHAR(200),--其他货币资金
	@dde_group			VARCHAR(200),--损益类型
	@Fcontact			VARCHAR(200),--核算往来
	@CheckType			VARCHAR(200),--核算性质
	@ItemCode1			VARCHAR(200),--辅助核算项目代码1
	@ItemName1			VARCHAR(200),--辅助核算项目名称1
	@ItemCode2			VARCHAR(200),--辅助核算项目代码2
	@ItemName2			VARCHAR(200),--辅助核算项目名称2
	@ItemCode3			VARCHAR(200),--辅助核算项目代码3
	@ItemName3			VARCHAR(200),--辅助核算项目名称3
	@ItemCode4			VARCHAR(200),--辅助核算项目代码4
	@ItemName4			VARCHAR(200),--辅助核算项目名称4
	@ItemCode5			VARCHAR(200),--辅助核算项目代码5
	@ItemName5			VARCHAR(200),--辅助核算项目名称5
	@ItemCode6			VARCHAR(200),--辅助核算项目代码6
	@ItemName6			VARCHAR(200),--辅助核算项目名称6
	@MainUserCode		VARCHAR(200),--预设现金流量项目主表项目编号
	@MainName			VARCHAR(200),--预设现金流量项目主表项目名称
	@AdditionUserCode	VARCHAR(200),--预设现金流量项目附表项目编号
	@AdditionName		VARCHAR(200),--预设现金流量项目附表项目名称
	
	@OperatorId			VARCHAR(50),
	@ErrMsg				VARCHAR(1000) OUTPUT
)
AS
SET NOCOUNT ON

DECLARE
	@STypeId		VARCHAR(50)='00000',--分支机构ID
	@ParTypeId		VARCHAR(50)='',--父级会计科目ID
	@ParSonNum		INT=0,--父级会计科目子级个数
	@ParLevel		INT=0,--父级级别
	@ParCategory	VARCHAR(50)='',--父级会计科目ID
	@ParIsUse		INT=0,--父节点是否被使用
	@TypeId			VARCHAR(50)='',--会计科目ID
	@MainItems		VARCHAR(50)='',--主表项目
	@AdditionItems	VARCHAR(50)='',--附表项目
	@ParIsCash		INT=0,--父类现金科目
	@ParIsBank		INT=0,--父类银行科目
	@ParIsOther		INT=0,--父类其他货币资金
	@AcId			INT=0,
	@ErrorCount		INT=0

SET @ParUserCode=ltrim(rtrim(@ParUserCode))--父级编号
SET @ParFullName=ltrim(rtrim(@ParFullName))--父级描名称
SET @UserCode=ltrim(rtrim(@UserCode))--编号
SET @FullName=ltrim(rtrim(@FullName))--描名称
SET @Name=ltrim(rtrim(@Name))--科目简名名
SET @dde_Category=ltrim(rtrim(@dde_Category))--科目类别
SET @Pycode=ltrim(rtrim(@Pycode))--拼音码
SET @Fdc=ltrim(rtrim(@Fdc))--余额方向
SET @Cid=ltrim(rtrim(@Cid))--外币核算
SET @FadjustRate=ltrim(rtrim(@FadjustRate))--期末调汇	
SET @AdjustAccounts=ltrim(rtrim(@AdjustAccounts))--数量核算
SET @UnitId=ltrim(rtrim(@UnitId))--计量单位
SET @IsCash=ltrim(rtrim(@IsCash))--现金科目
SET @IsBank=ltrim(rtrim(@IsBank))--银行科目
SET @IsOther=ltrim(rtrim(@IsOther))--其他货币资金
SET @dde_group=ltrim(rtrim(@dde_group))--损益类型
SET @Fcontact=ltrim(rtrim(@Fcontact))--核算往来
SET @CheckType=ltrim(rtrim(@CheckType))--核算性质
SET @ItemCode1=ltrim(rtrim(@ItemCode1))--辅助核算项目代码1
SET @ItemName1=ltrim(rtrim(@ItemName1))--辅助核算项目名称1
SET @ItemCode2=ltrim(rtrim(@ItemCode2))--辅助核算项目代码2
SET @ItemName2=ltrim(rtrim(@ItemName2))--辅助核算项目名称2
SET @ItemCode3=ltrim(rtrim(@ItemCode3))--辅助核算项目代码3
SET @ItemName3=ltrim(rtrim(@ItemName3))--辅助核算项目名称3
SET @ItemCode4=ltrim(rtrim(@ItemCode4))--辅助核算项目代码4
SET @ItemName4=ltrim(rtrim(@ItemName4))--辅助核算项目名称4
SET @ItemCode5=ltrim(rtrim(@ItemCode5))--辅助核算项目代码5
SET @ItemName5=ltrim(rtrim(@ItemName5))--辅助核算项目名称5
SET @ItemCode6=ltrim(rtrim(@ItemCode6))--辅助核算项目代码6
SET @ItemName6=ltrim(rtrim(@ItemName6))--辅助核算项目名称6
SET @MainUserCode=ltrim(rtrim(@MainUserCode))--预设现金流量项目主表项目编号
SET @MainName=ltrim(rtrim(@MainName))--预设现金流量项目主表项目名称
SET @AdditionUserCode=ltrim(rtrim(@AdditionUserCode))--预设现金流量项目附表项目编号
SET @AdditionName=ltrim(rtrim(@AdditionName))--预设现金流量项目附表项目名称

--=============================================基本信息验证【BEGIN】==================================
--父类科目节点
IF(ISNULL(@ParUserCode,'')<>'' OR ISNULL(@ParFullName,'')<>'')--如果父节点不为空
	BEGIN
		IF ISNULL(@ParUserCode,'')=''
			BEGIN
				SET @ErrMsg='父类科目编号不能为空'
				RETURN -1
			END
			
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE UserCode=@ParUserCode AND StypeId=@STypeId)
			BEGIN
				SET @ErrMsg='父类科目不存在'
				RETURN -1
			END
		
		IF ISNULL(@ParFullName,'')<>'' AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE UserCode=@ParUserCode AND StypeId=@STypeId AND FullName=@ParFullName)
			BEGIN
				SET @ErrMsg='父类科目编号和名称不匹配'
				RETURN -1
			END
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE UserCode=@ParUserCode AND StypeId=@STypeId AND Deleted=0)
			BEGIN
				SET @ErrMsg='父类科目已被停用'
				RETURN -1
			END
			
		SELECT 
			@ParTypeId=TypeId,
			@ParLevel=Leveal,
			@ParIsCash=IsCash,
			@ParIsBank=IsBank,
			@ParIsOther=IsOther,
			@AcId=AcId 
		FROM Ac_Account 
		WHERE 
			UserCode=@ParUserCode 
			AND StypeId=@STypeId--父级科目ID

	    --判断子节点是否被使用
	    DECLARE @ISv3 INT SET @ISv3=(SELECT  SubValue FROM sysdata WHERE SubName='ProInfo')
	    DECLARE @STypeId2 VARCHAR(100) = case when @ISv3 = 1 then '00001' else @STypeId end 
	    EXEC @ParIsUse = GP_CheckAccountUsage @STypeId=@STypeId2,@ATypeId = @ParTypeId

		IF @ParIsUse=1
			BEGIN
				SET @ErrMsg='父类科目已有业务发生，不能直接建立子科目，请手动进行分类。'
				RETURN -1
			END
	END
ELSE
	BEGIN			
		--00001=资产,00002=负债,00003=损益,00004=成本,00005=权益,00006=共同
		IF(@dde_Category NOT IN('资产','负债','损益','成本','权益','共同'))
			BEGIN
				SET @ErrMsg='不存在该科目类别'
				RETURN -1
			END
		--通过科目类别确定父类
		SELECT 
			@ParTypeId=TypeId,
			@ParLevel=Leveal,
			@ParIsCash=IsCash,
			@ParIsBank=IsBank,
			@ParIsOther=IsOther,
			@AcId=AcId 
		FROM Ac_Account 
		WHERE 
			(UserCode=@dde_Category OR FullName=@dde_Category) 
			AND StypeId=@STypeId
	END

--科目验证   
IF ISNULL(@UserCode,'')=''
	BEGIN
		SET @ErrMsg='科目编号不能为空'
		RETURN -1
	END
	
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE UserCode=@UserCode AND StypeId=@STypeId)
	BEGIN
		SET @ErrMsg='科目编号已存在'
		RETURN -1
	END

IF ISNULL(@FullName,'')=''
	BEGIN
		SET @ErrMsg='科目名称不能为空'
		RETURN -1
	END
		
DECLARE @Leveal INT=0
DECLARE @SQL NVARCHAR(MAX)='
DECLARE 
	@len1 INT,
	@len2 INT,
	@len3 INT,
	@len4 INT,
	@len5 INT,
	@len6 INT,
	@len7 INT,
	@len8 INT,
	@len9 INT,
	@len10 INT
    
SELECT  
	@len1=Len1,
    @len2=Len2+@len1,
    @len3=Len3+@len2,
    @len4=Len4+@len3,
    @len5=Len5+@len4,
    @len6=Len6+@len5,
    @len7=Len7+@len6,
    @len8=Len8+@len7,
    @len9=Len9+@len8,
    @len10=Len10+@len9
FROM Ac_Table;

SELECT TOP 1 @Leveal=@len'+ CAST(@ParLevel AS VARCHAR(10))

EXEC SP_EXECUTESQL @sql,N'@Leveal INT output',@Leveal OUTPUT ;

--为null的原因是添加的层次超出了预定
IF @Leveal IS NULL 
    BEGIN
		SET @ErrMsg='添加的科目超出科目表中设置，请检查'
		RETURN -1
    END

IF @Leveal<> LEN(@UserCode) 
    BEGIN
		SET @ErrMsg='编码长度不正确，应该为'+CAST(@Leveal AS VARCHAR)+'位'
		RETURN -1
    END
    
IF ISNUMERIC(@UserCode)=0
    BEGIN
		SET @ErrMsg='科目编号必须为纯数字'
		RETURN -1
    END
     
 IF LEFT(@UserCode,LEN(@ParUserCode))<>@ParUserCode
    BEGIN
		SET @ErrMsg='科目编号必须以父类编号开头'
		RETURN -1
    END    

 --余额方向
 IF(@Fdc NOT IN('借方','贷方'))
    BEGIN
		SET @ErrMsg='余额方向只能填写【借方/贷方】'
		RETURN -1
    END    
	
SET @Fdc=CASE WHEN @Fdc='借方' THEN 1 ELSE -1 END
    
--填写不核算、所有币种、自定义币种	期末调汇

IF NOT (@Cid IN('不核算','所有币种') OR EXISTS(SELECT TOP 1 1 FROM Ac_Currency WHERE FullName=@Cid OR UserCode=@Cid))
    BEGIN
		SET @ErrMsg='不存在该外币核算方式'
		RETURN -1
    END  
    
IF(@Cid='不核算')--期末调汇=0
	SET @FadjustRate=0
ELSE
	SET @FadjustRate=CASE WHEN @FadjustRate='是' THEN 1 ELSE 0 END

SET @Cid=CASE WHEN @Cid='不核算' THEN (SELECT TOP 1 CId FROM Ac_Currency WHERE Sysrow=1)
		 WHEN @Cid='所有币种' THEN 0
		 ELSE ISNULL((SELECT CId FROM Ac_Currency WHERE FullName=@Cid OR UserCode=@Cid),1) END
    
--只有资产类科目才有 数量核算-计量单位
IF(LEFT(@ParTypeId,5)='00001')
	BEGIN
		--数量核算：可填是、否、空，否和空同义；
		SET @AdjustAccounts=CASE WHEN @AdjustAccounts='是' THEN 1 ELSE 0 END

		--计量单位：只有“数量核算”填“是”，“计量单位”填写以后才生效，否则不生效；启用了数量核算，计量单位就必须填写，不能为空，且必须是系统中计量单位表存在的单位。
		IF(@AdjustAccounts=1)
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM PType_Units WHERE UserCode=@UnitId OR FullName=@UnitId)
					BEGIN
						SET @ErrMsg='计量单位不存在或为空'
						RETURN -1		
					END
					
				SELECT @UnitId=UnitsId FROM PType_Units WHERE UserCode=@UnitId OR FullName=@UnitId
			END
		ELSE 
			SET @UnitId=0
	END
ELSE 
	BEGIN
		SET @AdjustAccounts=0
		SET @UnitId=0
	END
	
--现金科目、银行科目、其他货币资金：与父类保持一致，必填；
IF(LEN(@ParTypeId)=5)
	BEGIN
		SET @IsCash=CASE WHEN @IsCash='是' THEN 1 ELSE 0 END
		SET @IsBank=CASE WHEN @IsBank='是' THEN 1 ELSE 0 END
		SET @IsOther=CASE WHEN @IsOther='是' THEN 1 ELSE 0 END
		
		IF(CAST(@IsCash AS INT)+CAST(@IsBank AS INT)+CAST(@IsOther AS INT))>1					
			BEGIN
				SET @ErrMsg='【现金科目、银行科目、其他资金】三选一，只能其中一个为是'
				RETURN -1		
			END
	END
ELSE 
	BEGIN
		SET @IsCash=@ParIsCash--父类现金科目
		SET @IsBank=@ParIsBank--父类银行科目
		SET @IsOther=@ParIsOther--父类其他货币资金
	END

--核算往来：可填写是、否、空，否和空同义；
SET @Fcontact=CASE WHEN @Fcontact='是' THEN 1 ELSE 0 END

--核算性质：可填写应收、应付，“核算往来”填“是”，“核算性质”就必须填写，且要正确填写；
IF(@Fcontact=1)
	BEGIN
	
		IF(ISNULL(@CheckType,'')='')
			BEGIN
				SET @ErrMsg='选择了核算往来，核算性质就不能为空'
				RETURN -1
			END
			
		IF(@CheckType NOT IN('应收','应付'))
			BEGIN
				SET @ErrMsg='核算性质只能为【应收/应付】'
				RETURN -1
			END
			
		--核算性质
		SET @CheckType=CASE WHEN @CheckType='应收' THEN 1 ELSE 2 END
	END
ELSE 
	SET @CheckType=0
	
--辅助核算项目
DECLARE @Items VARCHAR(100)=''

IF(@ItemCode1<>'' OR @ItemName1<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode1)
			BEGIN
				SET @ErrMsg='辅助核算项目代码1不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName1)
			BEGIN
				SET @ErrMsg='辅助核算项目名称1不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode1 AND FullName=@ItemName1)
			BEGIN
				SET @ErrMsg='辅助核算项目1编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode1
	END
	
IF(@ItemCode2<>'' OR @ItemName2<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode2)
			BEGIN
				SET @ErrMsg='辅助核算项目代码2不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName2)
			BEGIN
				SET @ErrMsg='辅助核算项目名称2不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode2 AND FullName=@ItemName2)
			BEGIN
				SET @ErrMsg='辅助核算项目2编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode2
	END	
IF(@ItemCode3<>'' OR @ItemName3<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode3)
			BEGIN
				SET @ErrMsg='辅助核算项目代码3不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName3)
			BEGIN
				SET @ErrMsg='辅助核算项目名称3不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode3 AND FullName=@ItemName3)
			BEGIN
				SET @ErrMsg='辅助核算项目3编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode3
	END	
IF(@ItemCode4<>'' OR @ItemName4<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode4)
			BEGIN
				SET @ErrMsg='辅助核算项目代码4不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName4)
			BEGIN
				SET @ErrMsg='辅助核算项目名称4不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode4 AND FullName=@ItemName4)
			BEGIN
				SET @ErrMsg='辅助核算项目4编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode4
	END	
IF(@ItemCode5<>'' OR @ItemName5<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode5)
			BEGIN
				SET @ErrMsg='辅助核算项目代码5不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName5)
			BEGIN
				SET @ErrMsg='辅助核算项目名称5不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode5 AND FullName=@ItemName5)
			BEGIN
				SET @ErrMsg='辅助核算项目5编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode5
	END	

IF(@ItemCode6<>'' OR @ItemName6<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode6)
			BEGIN
				SET @ErrMsg='辅助核算项目代码6不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName6)
			BEGIN
				SET @ErrMsg='辅助核算项目名称6不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode6 AND FullName=@ItemName6)
			BEGIN
				SET @ErrMsg='辅助核算项目6编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode6
	END	
	
--启用“核算往来”，至少需填写一项系统中存在的辅助核算项目
IF(@Fcontact=1 AND LEN(@Items)<1)
	BEGIN
		SET @ErrMsg='选择核算往来则必须选择至少一项辅助核算'
		RETURN -1
	END
	
--===========现金流量【BEGIN】=========
--@MainItems	VARCHAR(50),--主表项目
--@AdditionItems	VARCHAR(50)--附表项目
--主表项目
IF(LEFT(@ParTypeId,5) NOT IN('00001','00003')) OR (LEFT(@ParTypeId,5)='00001' AND (@IsCash=0 AND @IsBank=0 AND @IsOther=0))--// 资产类 现金 银行 其他货币资金)
	BEGIN
		SET @MainItems=''
		SET @AdditionItems=''
	END
ELSE 
	BEGIN
		IF(LEFT(@ParTypeId,5)='00001' AND (@IsCash=1 OR @IsBank=1 OR @IsOther=1))--// 资产类 现金 银行 其他货币资金
			BEGIN
				IF(@MainUserCode<>'' OR @MainName<>'')
					BEGIN
					
						IF NOT EXISTS(SELECT * FROM Ac_CashMoneyItems WHERE UserCode=@MainUserCode AND TypeId<'00005' AND SonNum=0)
							BEGIN
								SET @ErrMsg='预设现金流量项目主表项目编号不存在或为父类'
								RETURN -1
							END
							
						IF ISNULL(@MainName,'')<>'' AND NOT EXISTS(SELECT * FROM Ac_CashMoneyItems WHERE UserCode=@MainUserCode AND FullName=@MainName AND TypeId<'00005' AND SonNum=0)
							BEGIN
								SET @ErrMsg='预设现金流量项目主表项目编号与名称不匹配'
								RETURN -1
							END
							
						SELECT @MainItems=TypeId FROM Ac_CashMoneyItems WHERE UserCode=@MainUserCode AND TypeId<'00005' AND SonNum=0
					END
			END
		ELSE 
			SET @MainItems=''
		
		--附表项目
		IF(@AdditionUserCode<>'' OR @AdditionName<>'')
			BEGIN
				IF NOT EXISTS(SELECT * FROM Ac_CashMoneyItems WHERE UserCode=@AdditionUserCode AND TypeId>='00005' AND SonNum=0)
					BEGIN
						SET @ErrMsg='预设现金流量项目附表项目编号不存在或为父类'
						RETURN -1
					END
				IF ISNULL(@AdditionName,'')<>'' AND NOT EXISTS(SELECT * FROM Ac_CashMoneyItems WHERE UserCode=@AdditionUserCode AND FullName=@AdditionName AND TypeId>='00005' AND SonNum=0)
					BEGIN
						SET @ErrMsg='预设现金流量项目附表项目编号与名称不匹配'
						RETURN -1
					END
					
				SELECT @AdditionItems=TypeId FROM Ac_CashMoneyItems WHERE UserCode=@AdditionUserCode AND TypeId>='00005' AND SonNum=0
			END
	END
--==========现金流量【END】=============
		
--损益类型-1=非损益类科目, 501=营业收入,502=营业收入及税金,503=期间费用,504=其他收益,505=其他损失,506=以前年度损益调整,507=所得税
DECLARE @GroupId INT
IF LEFT(@ParTypeId,5)='00003'--损益类科目才允许选择
	BEGIN
		IF(@dde_group NOT IN('营业收入','营业收入及税金','期间费用','其他收益','其他损失','以前年度损益调整','所得税'))
			BEGIN
				SET @ErrMsg='该损益类型不存在'
				RETURN -1
			END
		IF(@dde_group='营业收入')
			SET @dde_group=501
			
		IF(@dde_group='营业收入及税金')
			SET @dde_group=502
			
		IF(@dde_group='期间费用')
			SET @dde_group=503
			
		IF(@dde_group='其他收益')
			SET @dde_group=504
			
		IF(@dde_group='其他损失')
			SET @dde_group=505
			
		IF(@dde_group='以前年度损益调整')
			SET @dde_group=506
			
		IF(@dde_group='所得税')
			SET @dde_group=507
			
	END
ELSE
	BEGIN 
		SELECT @dde_group=[Group] FROM Ac_Account WHERE StypeId=@STypeId AND TypeId=@ParTypeId
	END

--=============================================基本信息验证【END】==================================
DECLARE 
	@nRet			INT=0,
	@XiWaMaxNumber	INT=0,--最大缓存值
	@Facnt			INT,--辅助核算
	@ExchId			INT=0 

-- 获得新的ID号
EXEC @nRet= Gp_Create_Ac_Account_Id @StypeId, @ParTypeId,'Ac_Account',@TypeId OUT,0,0

--最大缓存值
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Account

--辅助核算
SET @Facnt=CASE WHEN LEN(@Items)>0 THEN 1 ELSE 0 END

SET @ExchId=CASE WHEN @Cid=(SELECT TOP 1 CId FROM Ac_Currency WHERE Sysrow=1) THEN 1 ELSE 0 END

BEGIN TRAN InsertPro
INSERT INTO Ac_Account 
(
	StypeId, 
	TypeId,
	Parid,
	Leveal, 
	SonNum,
	SonCount,
	UserCode,
	FullName,
	Name,
	Fdc,
	IsCash,
	IsBank,
	IsDiary,
	Comment,
	PyCode,
	ETypeId,
	CreateDateTime,
	MainItems,
	AdditionItems,
	ExchId,
	FAcnt,
	FContact,
	FAdjustRate,
	FLeveal,
	XiWaMaxNumber,
	IsOther, 
	Cid,
	[Group],
	CheckType,
	AdjustAccounts,
	UnitID,
	AcId,
	FAcctint,
	AscIds,
	FintRate
)
VALUES
(
	@StypeId, 
	@TypeId,
	@ParTypeId,
	@ParLevel+1, 
	0,--SonNum,
	0,--SonCount,
	@UserCode,
	@FullName,
	@Name,
	@Fdc,
	@IsCash,
	@IsBank,
	0,--IsDiary,
	'',--Comment,
	@PyCode,
	@OperatorId,--ETypeId,
	GETDATE(),--CreateDateTime,
	@MainItems,
	@AdditionItems,
	@ExchId,
	@FAcnt,
	@FContact,
	@FAdjustRate,
	@ParLevel,
	@XiWaMaxNumber,
	@IsOther, 
	@Cid,
	@dde_group,--@dde_group,--[Group],
	@CheckType,
	@AdjustAccounts,
	@UnitID,
	@AcId,
	0,--FAcctint,
	'',--AscIds,
	0--FintRate
)
SET @ErrorCount=@@ERROR

-- 重新填写辅助核算项目
DECLARE @Currency TABLE(Cid INT)

IF @Cid = 0 
	INSERT INTO @Currency SELECT CId FROM Ac_Currency
ELSE 
	INSERT INTO @Currency SELECT @Cid  

INSERT  INTO Ac_Account_Assist_CheckItems 
(
	STypeId,
	ATypeId,
	Cid,
	Ascids,
	AcId
)
SELECT DISTINCT 
	@STypeId, 
	@TypeId, 
	Cid, 
	a,
	@AcID
FROM @Currency,dbo.f_split(@Items,',')
SET @ErrorCount=@@ERROR

--更改父类
IF(@ParSonNum=0)
	BEGIN
		UPDATE Ac_Account 
		SET 
			SonNum+=1,
			SonCount+=1,
			FAcctint = 0,
			AscIds = '',
			FInterest = 0,
			FintRate = 0,
			IsPreGather = 0,
			IsPrePay = 0,
			IsGather = 0,
			IsPay = 0,
			IsVip = 0
		WHERE 
			TypeId=@ParTypeId 
			AND StypeId=@STypeId
			
		SET @ErrorCount=@@ERROR
	END

IF EXISTS(SELECT * FROM SysData WHERE SubName='proinfo' AND SubValue=1)
	BEGIN
		SET @STypeId='00001'
		
		--最大缓存值
		SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Account

		INSERT INTO Ac_Account 
		(
			StypeId, 
			TypeId,
			Parid,
			Leveal, 
			SonNum,
			SonCount,
			UserCode,
			FullName,
			Name,
			Fdc,
			IsCash,
			IsBank,
			IsDiary,
			Comment,
			PyCode,
			ETypeId,
			CreateDateTime,
			MainItems,
			AdditionItems,
			ExchId,
			FAcnt,
			FContact,
			FAdjustRate,
			FLeveal,
			XiWaMaxNumber,
			IsOther, 
			Cid,
			[Group],
			CheckType,
			AdjustAccounts,
			UnitID,
			AcId,
			FAcctint,
			AscIds,
			FintRate
		)
		VALUES
		(
			@StypeId, 
			@TypeId,
			@ParTypeId,
			@ParLevel+1, 
			0,--SonNum,
			0,--SonCount,
			@UserCode,
			@FullName,
			@Name,
			@Fdc,
			@IsCash,
			@IsBank,
			0,--IsDiary,
			'',--Comment,
			@PyCode,
			@OperatorId,--ETypeId,
			GETDATE(),--CreateDateTime,
			@MainItems,
			@AdditionItems,
			@ExchId,
			@FAcnt,
			@FContact,
			@FAdjustRate,
			@ParLevel,
			@XiWaMaxNumber,
			@IsOther, 
			@Cid,
			@dde_group,--[Group],
			@CheckType,
			@AdjustAccounts,
			@UnitID,
			@AcId,
			0,--FAcctint,
			'',--AscIds,
			0--FintRate
		)
		SET @ErrorCount=@@ERROR
		
		--更改父类
		IF(@ParSonNum=0)
			BEGIN
				UPDATE Ac_Account 
				SET 
					SonNum+=1,
					SonCount+=1,
					FAcctint = 0,
					AscIds = '',
					FInterest = 0,
					FintRate = 0,
					IsPreGather = 0,
					IsPrePay = 0,
					IsGather = 0,
					IsPay = 0,
					IsVip = 0
				WHERE 
					TypeId=@ParTypeId 
					AND StypeId=@STypeId
					
				SET @ErrorCount=@@ERROR
			END
			
		INSERT  INTO Ac_Account_Assist_CheckItems 
		(
			STypeId,
			ATypeId,
			Cid,
			Ascids,
			AcId
		)
		SELECT DISTINCT 
			@STypeId, 
			@TypeId, 
			Cid, 
			a,
			@AcID
		FROM @Currency,dbo.f_split(@Items,',')
		SET @ErrorCount=@@ERROR
	END
	


IF(@ErrorCount<>0)
	BEGIN
		ROLLBACK TRAN InsertPro
		SET @ErrMsg='导入失败'
		RETURN -1	
	END
ELSE 
	BEGIN
		COMMIT TRAN InsertPro
	END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_ImportAccountingInitialData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_ImportAccountingInitialData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--==========================================================
--BY:GLJ
--DATE:2016-08-02
--DESCRIPTION:导入账务期初   期初数据 1：引入往来余额:2：引入库存余额:3：引入固定资产余额
--==========================================================
CREATE PROCEDURE Gp_ImportAccountingInitialData
(
	@STypeId		VARCHAR(50),	--分支机构id
	@ATypeId		VARCHAR(50),	--分支机构id
	@CId			INT,			--币种
	@Flag			INT,			--1：引入往来余额:2：引入库存余额:3：引入固定资产余额
	@OperatorID		VARCHAR(50)		--操作员id
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE 
	@SQL		VARCHAR(MAX)='',--执行语句
	@SFYear		INT,			--分支机构启用年度
	@SFPeriod	INT,			--分支机构启用期间
	@Error		INT=0
	
IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=1)
	BEGIN
		RAISERROR('当前分支机构已经开账，不允许继续操作！',16,1)
		RETURN
	END
	
DECLARE @stypeindependentopen INT 
SELECT @stypeindependentopen =  SubValue FROM dbo.sysdata WHERE SubName = 'stypeindependentopen'

SELECT @SFyear=SFYear,@SFPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId--当前分支机构启用年度/期间
IF EXISTS(SELECT TOP 1 1 FROM SType S 
	INNER JOIN SType_UserConfig SU ON SU.StypeId=S.TypeId AND S.VerifyID=@STypeId AND S.deleted=0 AND (SU.SFYear<>@SFyear OR SU.SFPeriod<>@SFPeriod)) AND @stypeindependentopen=1 AND (@Flag = 1 OR @Flag = 2)
	BEGIN
		RAISERROR('因业务系统与总账系统【启用期间】不一致无法引入，请手工录入科目数据！',16,1)
		RETURN
	END

--=================================业务取值【BEGIN】===================================
--查询包含非独立分支机构
CREATE TABLE #SType(STypeId VARCHAR(50),VerifyID VARCHAR(50))
INSERT INTO #SType(STypeId,VerifyID) SELECT TypeId,VerifyID FROM SType WHERE VerifyID=@STypeId AND deleted=0	
		   
--业务数据临时表	   
CREATE TABLE #TempData
(
	ATypeId			VARCHAR(50),
	STypeId			VARCHAR(50),
	ETypeID			VARCHAR(50),
	DTypeID			VARCHAR(50),
	BTypeID			VARCHAR(50),
	BillTotal		NUMERIC(22,10) NOT NULL DEFAULT 0.0000000000,
	BillTotalFor	NUMERIC(22,10) NOT NULL DEFAULT 0.0000000000,
	GroupId			INT IDENTITY(1,1)
)
IF(@Flag=1)--1：引入往来余额
	BEGIN
		--------提取费用单配置
		DECLARE @Expensetoar INT
		SELECT @Expensetoar=SUBVALUE FROM dbo.sysdata WHERE SubName='expensetoar'

		INSERT INTO #TempData(ATypeId,STypeId,ETypeID,DTypeID,BTypeID,BillTotal,BillTotalFor)
		SELECT
			@ATypeId ATypeId,
			Stypeid,
			etypeid,
			DTypeId,
			btypeid,
			ISNULL(SUM(BillTotal),0) BillTotal,
			ISNULL(SUM(BillTotalFor),0) BillTotalFor
		FROM (
			SELECT
				A.Stypeid,
				A.etypeid,
				A.DTypeId,
				A.btypeid,
				CASE WHEN a.BillType IN(45,6,148,149,150,151,46,4,66) THEN -(ISNULL(A.totalmoney,0)-ISNULL(A.preferencemoney,0)-ISNULL(A.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))   
					ELSE ISNULL(a.totalmoney,0)-ISNULL(A.preferencemoney,0)-ISNULL(A.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
				END BillTotal,
				CASE WHEN a.BillType IN(45,6,148,149,150,151,46,4,66) THEN -(ISNULL(A.NTotalMoney,0)-ISNULL(A.NPreferenceMoney,0)-ISNULL(A.NCompleteTotal,0)-ISNULL(A.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))         
					ELSE (ISNULL(A.NTotalMoney,0)-ISNULL(A.NPreferenceMoney,0)-ISNULL(A.NCompleteTotal,0)-ISNULL(A.NTotalInMoney,0))-ISNULL(A.NChargeOffTotal,0)                             
				END BillTotalFor
			FROM #SType S 
			INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.ISINI=1 AND A.CID=@CId AND A.BillType NOT IN(116,115,128,129,36,400,401,404,405) AND A.ATypeID1=@ATypeId
			
			UNION ALL--暂估入库单
			
			SELECT
				A.Stypeid,
				A.etypeid,
				A.DTypeId,
				A.btypeid,
				(AB.Qty-InvoiceQty)*AB.DiscountPrice AS  BillTotal,
				(AB.Qty-InvoiceQty)*AB.NDiscountPrice AS  BillTotalFor 
			FROM #SType S 
			INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid AND A.BillType=400 AND A.ATypeID1=@ATypeId
			INNER JOIN AppraisalBill AB ON AB.BillNumberId=A.BillNumberId
			
			UNION ALL --暂估退货单
			
			SELECT
				A.Stypeid,
				A.etypeid,
				A.DTypeId,
				A.btypeid,
				-(AB.total-AB.DiscountPrice*InvoiceQty) BillTotal,
				-(AB.NTotal-AB.NDiscountPrice*InvoiceQty) BillTotalFor 
			FROM #SType S 
			INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid AND A.BillType=401 AND A.ATypeID1=@ATypeId
			INNER JOIN AppraisalBackBill AB ON AB.BillNumberId=A.BillNumberId
			
			UNION ALL --(404采购暂估开票 405销售发货开票)
			
			SELECT 
				A.Stypeid,
				A.etypeid,
				A.DTypeId,
				A.btypeid,
				A.TaxTotalMoney-A.CompleteTotal-A.ChargeOffTotal BillTotal,
				A.NTaxTotalMoney-A.NCompleteTotal-A.NChargeOffTotal BillTotalFor 
			FROM #SType S 
			INNER JOIN ReceiptBillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid AND ((A.BillType=405 AND A.ATypeID1=@ATypeId) OR (A.BillType=404 AND A.ATypeID2=@ATypeId))
			--INNER JOIN ReceiptBill AB ON AB.BillNumberId=A.BillNumberId

			UNION ALL--提取应收应付的增加，减少单

			SELECT
				A.Stypeid,
				A.etypeid,
				A.DTypeId,
				C.BtypeId,
				CASE WHEN A.BillType IN(129,115) THEN -(ISNULL(C.total,0)-ISNULL(A.preferencemoney,0)-ISNULL(C.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))
					ELSE ISNULL(c.total,0)-ISNULL(a.preferencemoney,0)-ISNULL(c.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
				END AS BillTotal,
				CASE WHEN A.BillType IN(129,115) THEN -(ISNULL(c.NTotal,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(c.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))
					ELSE ISNULL(c.NTotal,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(c.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0)
				END AS BillTotalFor	
			FROM #SType S 
			INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.ISINI=1 AND A.CID=@CId AND A.BillType IN (116,115,128,129) AND A.ATypeID1=@ATypeId
			LEFT JOIN AdDebtBill C  ON C.BillNumberId=A.BillNumberId

			UNION ALL --提取费用单

			SELECT 
				A.Stypeid,
				A.etypeid,
				A.DTypeId,
				A.btypeid,
				CASE WHEN @Expensetoar=1 AND SUBSTRING(A.btypeid,1,5)='00001' THEN -(ISNULL(a.totalmoney,0)-ISNULL(a.preferencemoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))   
					ELSE ISNULL(a.totalmoney,0)-ISNULL(a.preferencemoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
				END AS BILLTOTAL,
				CASE WHEN @Expensetoar=1 AND SUBSTRING(A.btypeid,1,5)='00001' THEN -(ISNULL(a.NTotalMoney,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(a.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))         
					ELSE (ISNULL(a.NTotalMoney,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(a.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))                             
				END AS BILLTOTALFOR
			FROM #SType S 
			INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.ISINI=1 AND A.CID=@CId AND A.BillType=36  AND A.ATypeID1=@ATypeId
		) F	
		GROUP BY Stypeid,etypeid,DTypeId,btypeid	
	END
ELSE IF(@Flag=2 AND @CId=1)--2：引入库存余额
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='useatypefrom' AND SubValue='1')
			BEGIN
				INSERT INTO #TempData(ATypeId,STypeId,BillTotal,BillTotalFor)
				SELECT
					@ATypeId ATypeId,
					S.STypeId,
					ISNULL(SUM(G.Total),0) BillTotal,
					ISNULL(SUM(G.Total),0) BillTotalFor
				FROM #SType S 
				INNER JOIN Stock ST ON ST.STypeID=S.STypeId
				INNER JOIN IniGoodsStocks G ON G.KtypeId=ST.typeId
				INNER JOIN ptype P ON P.typeId=G.PtypeId 
				INNER JOIN Base_InventoryTypeDetails D ON D.TID=P.InventoryTypeID AND D.STypeID=S.STypeId AND D.StockATypeID=@ATypeId
				GROUP BY S.STypeId
			END
		ELSE 
			BEGIN
				INSERT INTO #TempData(ATypeId,STypeId,BillTotal,BillTotalFor)
				SELECT
					@ATypeId ATypeId,
					S.STypeId,
					ISNULL(SUM(G.Total),0) BillTotal,
					ISNULL(SUM(G.Total),0) BillTotalFor
				FROM #SType S 
				INNER JOIN Stock ST ON ST.STypeID=S.STypeId
				INNER JOIN IniGoodsStocks G ON G.KtypeId=ST.typeId
				INNER JOIN SType S1 ON S1.TypeId=S.VerifyID AND S1.ATypeID4=@ATypeId
				GROUP BY S.STypeId
	END	
	END
ELSE IF(@Flag=3 AND EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='assets' AND SubValue='1')) AND @CId=1--3：引入固定资产余额
	BEGIN
		INSERT INTO #TempData(ATypeId,STypeId,DTypeID,BillTotal,BillTotalFor)
		SELECT 
			@ATypeId ATypeId,
			STypeId,
			DTypeid,
			ISNULL(SUM(BillTotal),0),
			ISNULL(SUM(BillTotalFor),0)
		FROM (
			--固定资产科目
			SELECT
				s.STypeId,
				ac.DTypeid,
				ISNULL(AC.Total,0) BillTotal,
				ISNULL(AC.Total,0) BillTotalFor                                                             
			FROM #SType S 
			INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5) AND AC.AssertATypeId=@ATypeId
			
			UNION ALL
			--累计折旧科目
			SELECT
				S.STypeId,
				AC.DTypeid,
				ISNULL(AC.DepTotal,0) BillTotal,
				ISNULL(AC.DepTotal,0) BillTotalFor                            
			FROM #SType S 
			INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5) AND AC.DepATypeId=@ATypeId
			
			UNION ALL
			--减值准备科目
			SELECT
				S.STypeId,
				AC.DTypeid,
				ISNULL(AC.DevalueReady,0) BillTotal,
				ISNULL(AC.DevalueReady,0) BillTotalFor                     
			FROM #SType S 
			INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5) AND AC.DevalueATypeId=@ATypeId
		) F 
		GROUP BY STypeId,DTypeid
	END
--删除相同分支机构  部门  职员 往来单位   合计为0 的数据
DECLARE @GroupbyStr VARCHAR(MAX)=''--分组字段
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND Ascids=1)
	SET @GroupbyStr+=',STypeId'
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND Ascids=2)
	SET @GroupbyStr+=',DTypeid'
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND Ascids=3)
	SET @GroupbyStr+=',ETypeid'
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND Ascids=4)
	SET @GroupbyStr+=',BTypeid'
--重新获取总值
SET @SQL='
SELECT
	ATypeId
	'+@GroupbyStr+',
	SUM(ISNULL(BillTotal,0)) BillTotal,
	SUM(ISNULL(BillTotalFor,0)) BillTotalFor
INTO #TempData1
FROM #TempData
GROUP BY ATypeId'+@GroupbyStr
+'
DELETE FROM #TempData

INSERT INTO #TempData(ATypeId'+@GroupbyStr+',BillTotal,BillTotalFor)
SELECT ATypeId'+@GroupbyStr+',BillTotal,BillTotalFor FROM #TempData1

DROP TABLE #TempData1
'
EXEC(@SQL)

DELETE FROM #TempData WHERE BillTotal=0 AND BillTotalFor=0
--=================================业务取值  【END】===================================

--=================================更改期初表数据【BEGIN】===================================	
BEGIN TRAN	
------------------ 删除原数据 重新导入数据	
--删除期初表相应数据
DELETE Ac_IniAccount WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND FYear=@SFYear AND FPeriod=@SFPeriod
SELECT @Error+=@@ERROR

--期初辅助核算主表数据
DELETE Ac_IniAccount_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND FYear=@SFYear AND FPeriod=@SFPeriod
SELECT @Error+=@@ERROR

--期初辅助核算明细表数据
DELETE Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND Cid=@CId AND FYear=@SFYear AND FPeriod=@SFPeriod
SELECT @Error+=@@ERROR

--=============================重新插入期初数据
--辅助核算明细表
INSERT INTO Ac_IniAccount_Assist_CheckItems_Detail
(
	STypeId,
	ATypeId,
	Cid,
	Ascids,
	FieldValue,
	IniYTotal,
	IniYTotalFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	IniTotal,
	IniTotalFor,
	GroupId,
	IniYqty,
	FDebitqty,
	FCreditqty,
	iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor
)
SELECT
	@STypeId STypeId,
	@ATypeId ATypeId,
	@CId Cid,
	C.Ascids,
	CASE WHEN C.Ascids=1 THEN ISNULL(T.STypeId,'')
			WHEN C.Ascids=2 THEN ISNULL(T.DTypeID,'')
			WHEN C.Ascids=3 THEN ISNULL(T.ETypeID,'')
			WHEN C.Ascids=4 THEN ISNULL(T.BTypeID,'')
			ELSE ''
	END FieldValue,
	ISNULL(dbo.F_RoundTotal(T.BillTotal),0) IniYTotal,
	ISNULL(dbo.F_RoundTotal(T.BillTotalFor),0) IniYTotalFor,
	0 FDebit,
	0 FDebitFor,
	0 FCredit,
	0 FCreditFor,
	dbo.F_RoundTotal(T.BillTotal) IniTotal,
	dbo.F_RoundTotal(T.BillTotalFor) IniTotalFor,
	t.GroupId,
	0 IniYqty,
	0 FDebitqty,
	0 FCreditqty,
	0 iniqty,
	@SFYear FYear,
	@SFPeriod FPeriod,
	0 FYTotal,
	0 FYTotalFor
FROM #TempData T
INNER JOIN Ac_Account_Assist_CheckItems C  ON C.ATypeId=T.ATypeId AND C.STypeId=@STypeId AND C.ATypeId=@ATypeId AND c.Cid=@CId
SET @Error+=@@ERROR	
	
--辅助核算主表
INSERT INTO Ac_IniAccount_Assist_CheckItems
(
	STypeId,
	ATypeId,
	Cid,
	IniYTotal,
	IniYTotalFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	IniTotal,
	IniTotalFor,
	IniYqty,
	FDebitqty,
	FCreditqty,
	iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor
)
SELECT
	@STypeId STypeId,
	@ATypeId ATypeId,
	@CId Cid,
	ISNULL(dbo.F_RoundTotal(T.BillTotal),0) IniYTotal,
	ISNULL(dbo.F_RoundTotal(T.BillTotalFor),0) IniYTotalFor,
	0 FDebit,
	0 FDebitFor,
	0 FCredit,
	0 FCreditFor,
	dbo.F_RoundTotal(T.BillTotal) IniTotal,
	dbo.F_RoundTotal(T.BillTotalFor) IniTotalFor,
	0 IniYqty,
	0 FDebitqty,
	0 FCreditqty,
	0 iniqty,
	@SFYear FYear,
	@SFPeriod FPeriod,
	0 FYTotal,
	0 FYTotalFor
FROM #TempData T
WHERE EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems C  WHERE C.ATypeId=T.ATypeId AND C.STypeId=@STypeId AND C.ATypeId=@ATypeId AND c.Cid=@CId)
SET @Error+=@@ERROR	
--账务期初表
INSERT INTO Ac_IniAccount                           
(
	STypeId,
	ATypeId,
	iniYTotal,
	iniYTotalFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	iniTotal,
	iniTotalFor,
	Cid,IniYqty,
	FDebitqty,
	FCreditqty,
	iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor,
	FYTotalDebit,
	FYTotalDebitFor,
	FYTotalCredit,
	FYTotalCreditFor
)
SELECT  
	@STypeId STypeId,
	@ATypeId ATypeId,
	ISNULL(dbo.F_RoundTotal(SUM(BillTotal)),0) iniYTotal,
	ISNULL(dbo.F_RoundTotal(SUM(BillTotalFor)),0) iniYTotalFor,
	0 FDebit,
	0 FDebitFor,
	0 FCredit,
	0 FCreditFor,
	ISNULL(dbo.F_RoundTotal(SUM(BillTotal)),0) iniTotal,
	ISNULL(dbo.F_RoundTotal(SUM(BillTotalFor)),0) iniTotalFor,
	@CId Cid,
	0 IniYqty,
	0 FDebitqty,
	0 FCreditqty,
	0 iniqty,
	@SFYear FYear,
	@SFPeriod FPeriod,
	0 FYTotal,
	0 FYTotalFor,
	0 FYTotalDebit,
	0 FYTotalDebitFor,
	0 FYTotalCredit,
	0 FYTotalCreditFor
FROM #TempData
SET @Error+=@@ERROR

--事务处理
IF(@Error=0)
	BEGIN
		COMMIT TRAN 
		RETURN 1
	END
ELSE 
	BEGIN
		ROLLBACK TRAN
		RETURN 0
	END
	
DROP TABLE #SType,#TempData

--=================================更改期初表数据【BEGIN】===================================	


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ImportApIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_ImportApIni
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		廖晨羽
-- Create date: 2011-09-09
-- Description: 应付期初导入
-- =============================================
CREATE PROCEDURE Gp_ImportApIni
(
	@SFullName VARCHAR(66),
	@BFullName VARCHAR(66),
	@Strtotal		VARCHAR(18),
	@Strpretotal	VARCHAR(18),
	@comment	varchar(1000),
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON;
	
-------------------------------------转换输入参数---------------------------------------------

DECLARE @stypeid	VARCHAR(1000)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF (@SFullName = '' OR @SFullName = '总部' OR NOT EXISTS(SELECT typeid FROM dbo.SType WHERE fullname = @SFullName))
	BEGIN
		SET @ErrMsg = '该分支机构不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PStypeId VARCHAR(50)
		DECLARE @SChildCount NUMERIC(18,0)
		SET @PStypeId = (SELECT TOP 1 typeid FROM dbo.SType WHERE fullname = @SFullName)
		SELECT @SChildCount = COUNT(*) FROM dbo.SType WHERE typeId LIKE @PStypeId + '%' AND typeId <> @PStypeId
		IF (@SChildCount = 0)
			BEGIN
				SET @stypeid = @PStypeId		
				IF (@stypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@typeid)))
				BEGIN
					SET @ErrMsg = '操作员不具备该分支机构权限'
					RETURN -1
				END				
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该分支机构是父类'
				RETURN -1
			END
	END

	--判断分支机构是否已开账
	IF ((SELECT U.Value FROM SType_UserConfig U,SType_Config C WHERE U.ConfigNo = C.ConfigNo AND U.Value = '1' AND U.STypeID = @stypeid) = 1)
	BEGIN
		SET @ErrMsg = '该分支机构已开账'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

DECLARE	@btypeid			varchar(1000)
IF(@BFullName = '全部供货商' OR @BFullName = '所有客户')
BEGIN
	SET @ErrMsg = '该往来单位是父类'
	RETURN -1
END
IF (@BFullName = '' OR @BFullName = 'ABC' OR NOT EXISTS(SELECT typeid FROM dbo.btype WHERE fullname = @BFullName))
BEGIN
	SET @ErrMsg = '该往来单位不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PBtypeId VARCHAR(50)
	DECLARE @BChildCount NUMERIC(18,0)
	SET @PBtypeId = (SELECT TOP 1 typeid FROM dbo.btype WHERE fullname = @BFullName)
	SELECT @BChildCount = COUNT(*) FROM dbo.btype WHERE typeId LIKE @PBtypeId + '%' AND typeId <> @PBtypeId
	IF (@BChildCount = 0)
		BEGIN
			SET @btypeid	 = @PBtypeId			
			IF (@btypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@typeid)))
			BEGIN
				SET @ErrMsg = '操作员不具备该往来单位权限'
				RETURN -1
			END			
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该往来单位是父类'
			RETURN -1
		END
END

DECLARE @total		 NUMERIC(24, 10) 
IF (@Strtotal = '')
BEGIN
	SET @total = 0
END
ELSE
BEGIN
	IF(ISNUMERIC(@Strtotal) <> 1)
		BEGIN
			SET @ErrMsg = '应付期初请输入数字'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @total = CONVERT( NUMERIC(24, 10) , @Strtotal)
		END
END

DECLARE @pretotal	 NUMERIC(24, 10) 
IF (@Strpretotal = '')
BEGIN
	SET @pretotal = 0
END
ELSE
BEGIN
	IF(ISNUMERIC(@Strpretotal) <> 1)
		BEGIN
			SET @ErrMsg = '预付期初请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @Strpretotal)) <> 0)
		BEGIN
			SET @ErrMsg = '预付期初不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @pretotal = CONVERT( NUMERIC(24, 10) , @Strpretotal)
		END
END	
----------------------------------------------------------------------------------------------

		IF NOT EXISTS(
					SELECT BTypeID
					FROM BType_ARAPTotal
					WHERE BTypeID=@btypeid	 AND STypeID=@stypeid
				)
				BEGIN
					INSERT BType_ARAPTotal(BTypeID,STypeID,APTotal00,YFTotal00)
					SELECT @btypeid	,@stypeid,@Total,@pretotal
					
						update btype set initcomment=@comment where typeId=@btypeid	
				END
				ELSE
				BEGIN
					UPDATE BType_ARAPTotal SET APTotal00 = @Total,YFTotal00=@pretotal
					WHERE BTypeID = @btypeid	 AND STypeID=@stypeid
					
						update btype set initcomment=@comment where typeId=@btypeid	
				END
		if not exists(select 1 from AType_Total where ATypeID='0000100009' and STypeID=@stypeid)
			insert into AType_Total(STypeID,ATypeID,Total,Total00) values(@stypeid,'0000100009',0,0)
		update AType_Total set Total00=(select SUM(YFTotal00) from BType_ARAPTotal where STypeID=@stypeid)  where ATypeID='0000100009' and STypeID=@stypeid

SET @ReturnID = @@ROWCOUNT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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


/****** Object:  StoredProcedure [dbo].[gp_ImportA]    Script Date: 05/20/2011 17:29:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	修 改 者：周华
	日    期：2012-07-31
	描    述：9.0新工具导入地域信息，去掉了长度类型等验证。以前版本gp_ImportA
*/
CREATE               PROCEDURE [dbo].[gp_ImportAreaType]
(
 @AFullName   [varchar](66),
 @UserCode  [varchar](256),
 @FullName  [varchar](66),
 @Name [varchar](30),
 @PyCode  [varchar](500),
 @LinkMan [varchar](256),
 @Tel [varchar](256),
 @Comment  [varchar](256),
 @ErrMsg VARCHAR(200) output
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
DECLARE @Parid [varchar](50)
DECLARE @nReturntype int
	,@EtypeId_1 [varchar](50)
	,@nSoncount int
	,@nSonnum int
	,@leveal smallint
DECLARE @parFullName varchar(200)
DECLARE @deleted INT
DECLARE @returnPym varchar(1000)
DECLARE @DbName [varchar](30) = 'AreaType'

/* --去掉长度验证
IF ((SELECT DATALENGTH(@PyCode)) > 256)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@LinkMan)) > 256)
BEGIN
	SET @ErrMsg = '负责人的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Tel)) > 256)
BEGIN
	SET @ErrMsg = '电话的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 256)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度256'
	RETURN -1
END
*/

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '地区编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '地区全名不能为空'
	RETURN -1
END

IF (@AfullName = '')
	SET @Parid = '00000'
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.AreaType WHERE fullname = @AfullName) OR @AfullName = '所有地区'
	BEGIN
		SET @ErrMsg = '父类名称不存在'
		RETURN -1
	END
	ELSE
		SELECT TOP 1 @Parid =typeid FROM dbo.AreaType WHERE fullname = @AfullName
END

SELECT @Pycode = dbo.fun_getPY(@FullName) WHERE @Pycode='';

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

select top 1 @parFullName=fullname from areatype where typeid=@parid

--判断停用不能分类
select @deleted=deleted from areatype where typeId=@Parid
if(@deleted=1)
BEGIN
	SET @ErrMsg = '该地区档案【' + @parFullName + '】已经被停用，不能分类'
	RETURN -1
END
-- 判断库存量（每种商品）是否为零
IF EXISTS(select AreaTypeID from Btype WHERE AreaTypeID=@Parid)
BEGIN
	SET @ErrMsg = '该地区档案【' + @parFullName + '】已经在客户或供货商档案中使用，不能分类'
	RETURN -1
END

IF EXISTS(select AreaTypeID from Crm_Btype WHERE AreaTypeID=@Parid)
BEGIN
	SET @ErrMsg = '该地区档案【' + @parFullName + '】客户管理中使用，不能分类'
	RETURN -1
END

-- 获得新的ID号
EXEC @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1
BEGIN
	SET @ErrMsg = '地区档案的分类不能超过10层'
	RETURN -1
END
if @nReturntype=-2 
BEGIN
	SET @ErrMsg = '无法添加基本信息'
	RETURN -1
END
 
-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) OR (fullname=@fullname and deleted<>1) )
begin
	SET @ErrMsg = '【' + @FullName + '】已经存在，地区档案的名称或编号不能相同'
	RETURN -1
end
-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
begin
	SET @ErrMsg = '【' + @FullName + '】名称或编号不能与已有的名称或编号重复'
	RETURN -1
end

-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) OR (fullname=@fullname and deleted=1))
begin
	SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被已停用的地区档案使用，请更换或删除该停用的编号或名称'
	RETURN -1
end
-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
BEGIN
	SET @ErrMsg = '该地区档案【' + @FullName + '】名称或编号不能与已停用的名称或编号重复'
	RETURN -1
END

EXEC @returnPym = fun_getPy @FullName
IF @PyCode <>'' SET @returnPym=@PyCode

BEGIN TRAN insertproc

SELECT @leveal=leveal+1 FROM AreaType WHERE typeid=@Parid

INSERT INTO [AreaType] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [UserCode],
  [FullName], 
  [Name],
  [SysFlag],
  [deleted],
  [Comment],
  [PyCode],
  [Tel],
  [LinkMan]	
 )  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @UserCode,
  @FullName,
  @name,
  0,
  0,
  @Comment,
  @returnPym,
  @Tel,
  @LinkMan
 )
IF @@ROWCOUNT=0 
BEGIN
	ROLLBACK TRAN insertproc 
	RETURN -1
END
ELSE 
	update [AreaType] set sonnum=@nSonnum+1,soncount=@nSoncount+1 where typeid=@Parid

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber NUMERIC(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AreaType
UPDATE AreaType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

COMMIT TRAN insertproc

GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ImportArIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_ImportArIni
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		廖晨羽
-- Create date: 2011-09-09
-- Description: 应收期初导入
-- =============================================
CREATE PROCEDURE Gp_ImportArIni
(
	@SFullName VARCHAR(66),
	@BFullName VARCHAR(66),
	@Strtotal		VARCHAR(18),
	@Strpretotal	VARCHAR(18),
	@comment	varchar(1000),
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON;
	
-------------------------------------转换输入参数---------------------------------------------

DECLARE @stypeid	VARCHAR(1000)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF (@SFullName = '' OR @SFullName = '总部' OR NOT EXISTS(SELECT typeid FROM dbo.SType WHERE fullname = @SFullName))
	BEGIN
		SET @ErrMsg = '该分支机构不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PStypeId VARCHAR(50)
		DECLARE @SChildCount NUMERIC(18,0)
		SET @PStypeId = (SELECT TOP 1 typeid FROM dbo.SType WHERE fullname = @SFullName)
		SELECT @SChildCount = COUNT(*) FROM dbo.SType WHERE typeId LIKE @PStypeId + '%' AND typeId <> @PStypeId
		IF (@SChildCount = 0)
			BEGIN
				SET @stypeid = @PStypeId		
				IF (@stypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@typeid)))
				BEGIN
					SET @ErrMsg = '操作员不具备该分支机构权限'
					RETURN -1
				END				
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该分支机构是父类'
				RETURN -1
			END
	END

	--判断分支机构是否已开账
	IF ((SELECT U.Value FROM SType_UserConfig U,SType_Config C WHERE U.ConfigNo = C.ConfigNo AND U.Value = '1' AND U.STypeID = @stypeid) = 1)
	BEGIN
		SET @ErrMsg = '该分支机构已开账'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

DECLARE	@btypeid			varchar(1000)
IF(@BFullName = '全部供货商' OR @BFullName = '所有客户')
BEGIN
	SET @ErrMsg = '该往来单位是父类'
	RETURN -1
END
IF (@BFullName = '' OR @BFullName = 'ABC' OR NOT EXISTS(SELECT typeid FROM dbo.btype WHERE fullname = @BFullName))
BEGIN
	SET @ErrMsg = '该往来单位不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PBtypeId VARCHAR(50)
	DECLARE @BChildCount NUMERIC(18,0)
	SET @PBtypeId = (SELECT TOP 1 typeid FROM dbo.btype WHERE fullname = @BFullName)
	SELECT @BChildCount = COUNT(*) FROM dbo.btype WHERE typeId LIKE @PBtypeId + '%' AND typeId <> @PBtypeId
	IF (@BChildCount = 0)
		BEGIN
			SET @btypeid = @PBtypeId		
			IF (@btypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@typeid)))
			BEGIN
				SET @ErrMsg = '操作员不具备该往来单位权限'
				RETURN -1
			END			
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该往来单位是父类'
			RETURN -1
		END
END

DECLARE @total		 NUMERIC(24, 10) 
IF (@Strtotal = '')
BEGIN
	SET @total = 0
END
ELSE
BEGIN
	IF(ISNUMERIC(@Strtotal) <> 1)
		BEGIN
			SET @ErrMsg = '应收期初请输入数字'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @total = CONVERT( NUMERIC(24, 10) , @Strtotal)
		END
END

DECLARE @pretotal	 NUMERIC(24, 10) 
IF (@Strpretotal = '')
BEGIN
	SET @pretotal = 0
END
ELSE
BEGIN
	IF(ISNUMERIC(@Strpretotal) <> 1)
		BEGIN
			SET @ErrMsg = '预收期初请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @Strpretotal)) <> 0)
		BEGIN
			SET @ErrMsg = '预收期初不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @pretotal = CONVERT( NUMERIC(24, 10) , @Strpretotal)
		END
END	

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

		IF NOT EXISTS(
					SELECT BTypeID
					FROM BType_ARAPTotal
					WHERE BTypeID=@btypeid	 AND STypeID=@stypeid
				)
				BEGIN
					INSERT BType_ARAPTotal(BTypeID,STypeID,ARTotal00,YSTotal00)
					SELECT @btypeid	,@stypeid,@Total,@pretotal
					
					update btype set initcomment=@comment where typeId=@btypeid	
				END
				ELSE
				BEGIN
					UPDATE BType_ARAPTotal SET ARTotal00 = @Total,YSTotal00=@pretotal
					WHERE BTypeID = @btypeid	 AND STypeID=@stypeid
					
					update btype set initcomment=@comment where typeId=@btypeid	
				END
		if not exists(select 1 from AType_Total where ATypeID='0000200006' and STypeID=@stypeid)
			insert into AType_Total(STypeID,ATypeID,Total,Total00) values(@stypeid,'0000200006',0,0)
		update AType_Total set Total00=(select SUM(ystotal00) from BType_ARAPTotal where STypeID=@stypeid)  where ATypeID='0000200006' and STypeID=@stypeid

SET @ReturnID = @@ROWCOUNT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_ImportATypeData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[GP_ImportATypeData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	会计科目
-- 时间：	2019-05-22
-- 作者：	GLJ

-- 修改：	武智均
-- 时间：	2019-07-18
-- 描述：	取消几个必填字段
-- ========================================================================
CREATE PROC [GP_ImportATypeData]
(
	@STypeUserCode		VARCHAR(200)='',--分支机构 编号
	@STypeFullName		VARCHAR(200)='',--分支机构 名称
	@ParUserCode		VARCHAR(200)='',--父级编号
	@ParFullName		VARCHAR(200)='',--父级描名称
	@UserCode			VARCHAR(200)='',--编号
	@FullName			VARCHAR(200)='',--描名称
	@Name				VARCHAR(200),--科目简名
	@Pycode				VARCHAR(200),--拼音码
	@Fdc				VARCHAR(200),--余额方向
	@Cid				VARCHAR(200),--外币核算
	@FadjustRate		VARCHAR(200),--期末调汇	
	@AdjustAccounts		VARCHAR(200),--数量核算
	@UnitId				VARCHAR(200),--计量单位
	@Fcontact			VARCHAR(200),--核算往来
	@CheckType			VARCHAR(200),--核算性质
	@ItemCode1			VARCHAR(200),--辅助核算项目代码1
	@ItemName1			VARCHAR(200),--辅助核算项目名称1
	@ItemCode2			VARCHAR(200),--辅助核算项目代码2
	@ItemName2			VARCHAR(200),--辅助核算项目名称2
	@ItemCode3			VARCHAR(200),--辅助核算项目代码3
	@ItemName3			VARCHAR(200),--辅助核算项目名称3
	@ItemCode4			VARCHAR(200),--辅助核算项目代码4
	@ItemName4			VARCHAR(200),--辅助核算项目名称4
	@ItemCode5			VARCHAR(200),--辅助核算项目代码5
	@ItemName5			VARCHAR(200),--辅助核算项目名称5
	@ItemCode6			VARCHAR(200),--辅助核算项目代码6
	@ItemName6			VARCHAR(200),--辅助核算项目名称6
	@MainUserCode		VARCHAR(200),--预设现金流量项目主表项目编号
	@MainName			VARCHAR(200),--预设现金流量项目主表项目名称
	@AdditionUserCode	VARCHAR(200),--预设现金流量项目附表项目编号
	@AdditionName		VARCHAR(200),--预设现金流量项目附表项目名称
	
	@OperatorId			VARCHAR(50),
	@ErrMsg				VARCHAR(1000) OUTPUT
)
AS
SET NOCOUNT ON

DECLARE
	@STypeId		VARCHAR(50)='',--分支机构ID
	@ParTypeId		VARCHAR(50)='',--父级会计科目ID
	@ParSonNum		INT=0,--父级会计科目子级个数
	@ParLevel		INT=0,--父级级别
	@ParGroup		INT,--父级损益类型
	@ParIsUse		INT=0,--父节点是否被使用
	@TypeId			VARCHAR(50)='',--会计科目ID
	@MainItems		VARCHAR(50)='',--主表项目
	@AdditionItems	VARCHAR(50)='',--附表项目
	@ParIsCash		INT=0,--父类现金科目
	@ParIsBank		INT=0,--父类银行科目
	@ParIsOther		INT=0,--父类其他货币资金
	@AcId			INT=0,
	@ErrorCount		INT=0


SET @STypeUserCode=ltrim(rtrim(@STypeUserCode))--分支机构编号
SET @STypeFullName=ltrim(rtrim(@STypeFullName))--分支机构名称
SET @ParUserCode=ltrim(rtrim(@ParUserCode))--父级编号
SET @ParFullName=ltrim(rtrim(@ParFullName))--父级描名称
SET @UserCode=ltrim(rtrim(@UserCode))--编号
SET @FullName=ltrim(rtrim(@FullName))--描名称
SET @Name=ltrim(rtrim(@Name))--科目简名名
SET @Pycode=ltrim(rtrim(@Pycode))--拼音码
SET @Fdc=ltrim(rtrim(@Fdc))--余额方向
SET @Cid=ltrim(rtrim(@Cid))--外币核算
SET @FadjustRate=ltrim(rtrim(@FadjustRate))--期末调汇	
SET @AdjustAccounts=ltrim(rtrim(@AdjustAccounts))--数量核算
SET @UnitId=ltrim(rtrim(@UnitId))--计量单位
SET @Fcontact=ltrim(rtrim(@Fcontact))--核算往来
SET @CheckType=ltrim(rtrim(@CheckType))--核算性质
SET @ItemCode1=ltrim(rtrim(@ItemCode1))--辅助核算项目代码1
SET @ItemName1=ltrim(rtrim(@ItemName1))--辅助核算项目名称1
SET @ItemCode2=ltrim(rtrim(@ItemCode2))--辅助核算项目代码2
SET @ItemName2=ltrim(rtrim(@ItemName2))--辅助核算项目名称2
SET @ItemCode3=ltrim(rtrim(@ItemCode3))--辅助核算项目代码3
SET @ItemName3=ltrim(rtrim(@ItemName3))--辅助核算项目名称3
SET @ItemCode4=ltrim(rtrim(@ItemCode4))--辅助核算项目代码4
SET @ItemName4=ltrim(rtrim(@ItemName4))--辅助核算项目名称4
SET @ItemCode5=ltrim(rtrim(@ItemCode5))--辅助核算项目代码5
SET @ItemName5=ltrim(rtrim(@ItemName5))--辅助核算项目名称5
SET @ItemCode6=ltrim(rtrim(@ItemCode6))--辅助核算项目代码6
SET @ItemName6=ltrim(rtrim(@ItemName6))--辅助核算项目名称6
SET @MainUserCode=ltrim(rtrim(@MainUserCode))--预设现金流量项目主表项目编号
SET @MainName=ltrim(rtrim(@MainName))--预设现金流量项目主表项目名称
SET @AdditionUserCode=ltrim(rtrim(@AdditionUserCode))--预设现金流量项目附表项目编号
SET @AdditionName=ltrim(rtrim(@AdditionName))--预设现金流量项目附表项目名称

--=============================================基本信息验证【BEGIN】==================================
IF @StypeFullName is null
SET @StypeFullName = ''
IF @ParFullName is null
SET @ParFullName = ''

--分支机构验证
IF ISNULL(@StypeUserCode,'')=''
	BEGIN
		SET @ErrMsg='分支机构编号不能为空'
		RETURN -1
	END

IF NOT EXISTS(SELECT TOP 1 1 FROM SType WHERE UserCode=@StypeUserCode)
	BEGIN
		SET @ErrMsg='分支机构编号不存在'
		RETURN -1
	END
	
IF NOT EXISTS(SELECT TOP 1 1 FROM SType WHERE UserCode=@STypeUserCode AND (@StypeFullName = '' or FullName=@StypeFullName))
	BEGIN
		SET @ErrMsg='分支机构编号和名称不匹配'
		RETURN -1
	END
	
IF NOT EXISTS(SELECT TOP 1 1 FROM SType WHERE UserCode=@StypeUserCode AND deleted=0)
	BEGIN
		SET @ErrMsg='分支机构已停用'
		RETURN -1
	END	

SELECT @STypeId=TypeId FROM SType WHERE UserCode=@StypeUserCode--分支机构ID

--父类科目节点
IF ISNULL(@ParUserCode,'')=''
	BEGIN
		SET @ErrMsg='父类科目编号不能为空'
		RETURN -1
	END
	
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE UserCode=@ParUserCode AND StypeId=@STypeId)
	BEGIN
		SET @ErrMsg='父类科目不存在'
		RETURN -1
	END

IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE UserCode=@ParUserCode AND StypeId=@STypeId AND (@ParFullName = '' or FullName=@ParFullName))
	BEGIN
		SET @ErrMsg='父类科目编号和名称不匹配'
		RETURN -1
	END

IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE UserCode=@ParUserCode AND StypeId=@STypeId AND Deleted=0)
	BEGIN
		SET @ErrMsg='父类科目已被停用'
		RETURN -1
	END
	
SELECT 
	@ParTypeId=TypeId,
	@ParLevel=Leveal,
	@ParIsCash=IsCash,
	@ParIsBank=IsBank,
	@ParIsOther=IsOther,
	@AcId=AcId,
	@ParGroup=[group]
FROM Ac_Account 
WHERE 
	UserCode=@ParUserCode 
	AND StypeId=@STypeId--父级科目ID

--判断子节点是否被使用
EXEC @ParIsUse = GP_CheckAccountUsage @STypeId=@STypeId,@ATypeId = @ParTypeId

IF @ParIsUse=1
	BEGIN
		SET @ErrMsg='父类科目已有业务发生，不能直接建立子科目，请手动进行分类。'
		RETURN -1
	END

--科目验证   
IF ISNULL(@UserCode,'')=''
	BEGIN
		SET @ErrMsg='科目编号不能为空'
		RETURN -1
	END
	
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE UserCode=@UserCode AND StypeId=@STypeId)
	BEGIN
		SET @ErrMsg='科目编号已存在'
		RETURN -1
	END

IF ISNULL(@FullName,'')=''
	BEGIN
		SET @ErrMsg='科目名称不能为空'
		RETURN -1
	END
		
DECLARE @Leveal INT=0
DECLARE @SQL NVARCHAR(MAX)='
DECLARE 
	@len1 INT,
	@len2 INT,
	@len3 INT,
	@len4 INT,
	@len5 INT,
	@len6 INT,
	@len7 INT,
	@len8 INT,
	@len9 INT,
	@len10 INT
    
SELECT  
	@len1=Len1,
    @len2=Len2+@len1,
    @len3=Len3+@len2,
    @len4=Len4+@len3,
    @len5=Len5+@len4,
    @len6=Len6+@len5,
    @len7=Len7+@len6,
    @len8=Len8+@len7,
    @len9=Len9+@len8,
    @len10=Len10+@len9
FROM Ac_Table;

SELECT TOP 1 @Leveal=@len'+ CAST(@ParLevel AS VARCHAR(10))

EXEC SP_EXECUTESQL @sql,N'@Leveal INT output',@Leveal OUTPUT ;

--为null的原因是添加的层次超出了预定
IF @Leveal IS NULL 
    BEGIN
		SET @ErrMsg='添加的科目超出科目表中设置，请检查'
		RETURN -1
    END

IF @Leveal<> LEN(@UserCode) 
    BEGIN
		SET @ErrMsg='编码长度不正确，应该为'+CAST(@Leveal AS VARCHAR)+'位'
		RETURN -1
    END
    
IF ISNUMERIC(@UserCode)=0
    BEGIN
		SET @ErrMsg='科目编号必须为纯数字'
		RETURN -1
    END
     
 IF LEFT(@UserCode,LEN(@ParUserCode))<>@ParUserCode
    BEGIN
		SET @ErrMsg='科目编号必须以父类编号开头'
		RETURN -1
    END   
     
 --余额方向  
 IF ISNULL(@Fdc,'') = ''
 BEGIN
	SELECT @Fdc = case when ISNULL(@Fdc,'') = '' then Fdc else @Fdc end FROM Ac_Account 
	WHERE UserCode=@ParUserCode AND StypeId=@STypeId
 END 
 ELSE IF(@Fdc NOT IN('借方','贷方'))
    BEGIN
		SET @ErrMsg='余额方向只能填写【借方/贷方】'
		RETURN -1
    END    
 ELSE 
 SET @Fdc=CASE WHEN @Fdc='借方' THEN 1 ELSE -1 END
  
 SET @FadjustRate=CASE WHEN @FadjustRate='是' THEN 1 ELSE 0 END   
--填写不核算、所有币种、自定义币种	期末调汇
IF ISNULL(@Cid,'') = ''
BEGIN
	SELECT @Cid = case when ISNULL(@Cid,'') = '' then Cid else @Cid end FROM Ac_Account 
	WHERE UserCode=@ParUserCode AND StypeId=@STypeId
	
END 
ELSE IF NOT (@Cid IN('不核算','所有币种') OR EXISTS(SELECT TOP 1 1 FROM Ac_Currency WHERE FullName=@Cid OR UserCode=@Cid))
    BEGIN
		SET @ErrMsg='不存在该外币核算方式'
		RETURN -1
    END  
    
ELSE 
BEGIN
	IF(@Cid='不核算')--期末调汇=0
		SET @FadjustRate=0
	SET @Cid=CASE WHEN @Cid='不核算' THEN (SELECT TOP 1 CId FROM Ac_Currency WHERE Sysrow=1)
			 WHEN @Cid='所有币种' THEN 0
			 ELSE ISNULL((SELECT CId FROM Ac_Currency WHERE FullName=@Cid OR UserCode=@Cid),1) END
END
    
--只有资产类科目才有 数量核算-计量单位
IF(LEFT(@ParTypeId,5)='00001')
	BEGIN
		--数量核算：可填是、否、空，否和空同义；
		SET @AdjustAccounts=CASE WHEN @AdjustAccounts='是' THEN 1 ELSE 0 END

		--计量单位：只有“数量核算”填“是”，“计量单位”填写以后才生效，否则不生效；启用了数量核算，计量单位就必须填写，不能为空，且必须是系统中计量单位表存在的单位。
		IF(@AdjustAccounts=1)
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM PType_Units WHERE UserCode=@UnitId OR FullName=@UnitId)
					BEGIN
						SET @ErrMsg='计量单位不存在或为空'
						RETURN -1		
					END
					
				SELECT @UnitId=UnitsId FROM PType_Units WHERE UserCode=@UnitId OR FullName=@UnitId
			END
		ELSE 
			SET @UnitId=0
	END
ELSE 
	BEGIN
		SET @AdjustAccounts=0
		SET @UnitId=0
	END
	
--核算往来：可填写是、否、空，否和空同义；
SET @Fcontact=CASE WHEN @Fcontact='是' THEN 1 ELSE 0 END

--核算性质：可填写应收、应付，“核算往来”填“是”，“核算性质”就必须填写，且要正确填写；
IF(@Fcontact=1)
	BEGIN
		IF(ISNULL(@CheckType,'')='')
			BEGIN
				SET @ErrMsg='选择了核算往来，核算性质就不能为空'
				RETURN -1
			END
			
		IF(@CheckType NOT IN('应收','应付'))
			BEGIN
				SET @ErrMsg='核算性质只能为【应收/应付】'
				RETURN -1
			END
			
		--核算性质
		SET @CheckType=CASE WHEN @CheckType='应收' THEN 1 ELSE 2 END
	END
ELSE 
	SET @CheckType=0
	
--辅助核算项目
DECLARE @Items VARCHAR(100)=''

IF(@ItemCode1<>'' OR @ItemName1<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode1)
			BEGIN
				SET @ErrMsg='辅助核算项目代码1不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName1)
			BEGIN
				SET @ErrMsg='辅助核算项目名称1不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode1 AND FullName=@ItemName1)
			BEGIN
				SET @ErrMsg='辅助核算项目1编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode1
	END
IF(@ItemCode2<>'' OR @ItemName2<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode2)
			BEGIN
				SET @ErrMsg='辅助核算项目代码2不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName2)
			BEGIN
				SET @ErrMsg='辅助核算项目名称2不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode2 AND FullName=@ItemName2)
			BEGIN
				SET @ErrMsg='辅助核算项目2编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode2
	END	
IF(@ItemCode3<>'' OR @ItemName3<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode3)
			BEGIN
				SET @ErrMsg='辅助核算项目代码3不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName3)
			BEGIN
				SET @ErrMsg='辅助核算项目名称3不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode3 AND FullName=@ItemName3)
			BEGIN
				SET @ErrMsg='辅助核算项目3编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode3
	END	
IF(@ItemCode4<>'' OR @ItemName4<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode4)
			BEGIN
				SET @ErrMsg='辅助核算项目代码4不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName4)
			BEGIN
				SET @ErrMsg='辅助核算项目名称4不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode4 AND FullName=@ItemName4)
			BEGIN
				SET @ErrMsg='辅助核算项目4编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode4
	END	
IF(@ItemCode5<>'' OR @ItemName5<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode5)
			BEGIN
				SET @ErrMsg='辅助核算项目代码5不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName5)
			BEGIN
				SET @ErrMsg='辅助核算项目名称5不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode5 AND FullName=@ItemName5)
			BEGIN
				SET @ErrMsg='辅助核算项目5编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode5
	END	
IF(@ItemCode6<>'' OR @ItemName6<>'')
	BEGIN
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode6)
			BEGIN
				SET @ErrMsg='辅助核算项目代码6不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE FullName=@ItemName6)
			BEGIN
				SET @ErrMsg='辅助核算项目名称6不存在'
				RETURN -1
			END
		IF NOT EXISTS(SELECT * FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode6 AND FullName=@ItemName6)
			BEGIN
				SET @ErrMsg='辅助核算项目6编号与名称不匹配'
				RETURN -1
			END
			
		SELECT @Items+=CAST(AscIds AS VARCHAR)+',' FROM Ac_Assist_CheckItems WHERE UserCode=@ItemCode6
	END	
	
--启用“核算往来”，至少需填写一项系统中存在的辅助核算项目
IF(@Fcontact=1 AND LEN(@Items)<=0)
	BEGIN
		SET @ErrMsg='选择核算往来则必须选择至少一项辅助核算'
		RETURN -1
	END
	
--===========现金流量【BEGIN】=========
--@MainItems	VARCHAR(50),--主表项目
--@AdditionItems	VARCHAR(50)--附表项目
--主表项目
IF(LEFT(@ParTypeId,5) NOT IN('00001','00003')) OR (LEFT(@ParTypeId,5)='00001' AND (@ParIsCash=0 AND @ParIsBank=0 AND @ParIsOther=0))--// 资产类 现金 银行 其他货币资金)
	BEGIN
		SET @MainItems=''
		SET @AdditionItems=''
	END
ELSE 
	BEGIN
		IF(LEFT(@ParTypeId,5)='00001' AND (@ParIsCash=1 OR @ParIsBank=1 OR @ParIsOther=1))--// 资产类 现金 银行 其他货币资金
			BEGIN
				IF(@MainUserCode<>'' OR @MainName<>'')
					BEGIN
					
						IF NOT EXISTS(SELECT * FROM Ac_CashMoneyItems WHERE UserCode=@MainUserCode AND TypeId<'00005' AND SonNum=0)
							BEGIN
								SET @ErrMsg='预设现金流量项目主表项目编号不存在或为父类'
								RETURN -1
							END
							
						IF ISNULL(@MainName,'')<>'' AND NOT EXISTS(SELECT * FROM Ac_CashMoneyItems WHERE UserCode=@MainUserCode AND FullName=@MainName AND TypeId<'00005' AND SonNum=0)
							BEGIN
								SET @ErrMsg='预设现金流量项目主表项目编号与名称不匹配'
								RETURN -1
							END
							
						SELECT @MainItems=TypeId FROM Ac_CashMoneyItems WHERE UserCode=@MainUserCode AND TypeId<'00005' AND SonNum=0
					END
			END
		ELSE 
			SET @MainItems=''
		
		--附表项目
		IF(@AdditionUserCode<>'' OR @AdditionName<>'')
			BEGIN
				IF NOT EXISTS(SELECT * FROM Ac_CashMoneyItems WHERE UserCode=@AdditionUserCode AND TypeId>='00005' AND SonNum=0)
					BEGIN
						SET @ErrMsg='预设现金流量项目附表项目编号不存在或为父类'
						RETURN -1
					END
				IF ISNULL(@AdditionName,'')<>'' AND NOT EXISTS(SELECT * FROM Ac_CashMoneyItems WHERE UserCode=@AdditionUserCode AND FullName=@AdditionName AND TypeId>='00005' AND SonNum=0)
					BEGIN
						SET @ErrMsg='预设现金流量项目附表项目编号与名称不匹配'
						RETURN -1
					END
					
				SELECT @AdditionItems=TypeId FROM Ac_CashMoneyItems WHERE UserCode=@AdditionUserCode AND TypeId>='00005' AND SonNum=0
			END
	END
--==========现金流量【END】=============
		
--=============================================基本信息验证【END】==================================
DECLARE 
	@nRet			INT=0,
	@XiWaMaxNumber	INT=0,--最大缓存值
	@Facnt			INT,--辅助核算
	@ExchId			INT=0 
	
-- 获得新的ID号
EXEC @nRet= Gp_Create_Ac_Account_Id @Stypeid, @ParTypeId,'Ac_Account',@TypeId OUT,0,0

--最大缓存值
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Account

--辅助核算
SET @Facnt=CASE WHEN LEN(@Items)>0 THEN 1 ELSE 0 END

SET @ExchId=CASE WHEN @Cid=(SELECT TOP 1 CId FROM Ac_Currency WHERE Sysrow=1) THEN 1 ELSE 0 END

BEGIN TRAN InsertPro
INSERT INTO Ac_Account 
(
	StypeId, 
	TypeId,
	Parid,
	Leveal, 
	SonNum,
	SonCount,
	UserCode,
	FullName,
	Name,
	Fdc,
	IsCash,
	IsBank,
	IsDiary,
	Comment,
	PyCode,
	ETypeId,
	CreateDateTime,
	MainItems,
	AdditionItems,
	ExchId,
	FAcnt,
	FContact,
	FAdjustRate,
	FLeveal,
	XiWaMaxNumber,
	IsOther, 
	Cid,
	[Group],
	CheckType,
	AdjustAccounts,
	UnitID,
	AcId,
	FAcctint,
	AscIds,
	FintRate
)
VALUES
(
	@StypeId, 
	@TypeId,
	@ParTypeId,
	@ParLevel+1, 
	0,--SonNum,
	0,--SonCount,
	@UserCode,
	@FullName,
	@Name,
	@Fdc,
	@ParIsCash,
	@ParIsBank,
	0,--IsDiary,
	'',--Comment,
	@PyCode,
	@OperatorId,--ETypeId,
	GETDATE(),--CreateDateTime,
	@MainItems,
	@AdditionItems,
	@ExchId,
	@FAcnt,
	@FContact,
	@FAdjustRate,
	@ParLevel,
	@XiWaMaxNumber,
	@ParIsOther, 
	@Cid,
	100,--@dde_group,--[Group],
	@CheckType,
	@AdjustAccounts,
	@UnitID,
	@AcId,
	0,--FAcctint,
	'',--AscIds,
	0--FintRate
)
SET @ErrorCount=@@ERROR


--更改父类
IF(@ParSonNum=0)
	BEGIN
		UPDATE Ac_Account 
		SET 
			SonNum+=1,
			SonCount+=1,
			FAcctint = 0,
			AscIds = '',
			FInterest = 0,
			FintRate = 0,
			IsPreGather = 0,
			IsPrePay = 0,
			IsGather = 0,
			IsPay = 0,
			IsVip = 0
		WHERE 
			TypeId=@ParTypeId 
			AND StypeId=@STypeId
		SET @ErrorCount=@@ERROR
	END
	
-- 重新填写辅助核算项目
DECLARE @Currency TABLE(Cid INT)

IF @Cid = 0 
	INSERT  INTO @Currency SELECT CId FROM Ac_Currency
ELSE 
	INSERT  INTO @Currency SELECT @Cid  
	
INSERT  INTO Ac_Account_Assist_CheckItems 
(
	STypeId,
	ATypeId,
	Cid,
	Ascids,
	AcId
)
SELECT DISTINCT 
	@stypeid, 
	@typeid, 
	Cid, 
	a,
	@AcID
FROM @Currency,dbo.f_split(@Items,',')
SET @ErrorCount=@@ERROR
                
IF(@ErrorCount<>0)
	BEGIN
		ROLLBACK TRAN InsertPro
		SET @ErrMsg='导入失败'
		RETURN -1	
	END
ELSE 
	BEGIN
		COMMIT TRAN InsertPro
	END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.02.01
	描述：处理atype数据到ac_items，并将ac_items中数据与atype层次相关联
		 后面增加其他项目的处理
*/
CREATE PROCEDURE Gp_ImportAtypeToItemtype

--@encode$--
AS
SET NOCOUNT ON


--调整叶子结点的可分类属性
UPDATE Ac_Items SET IsModify=0 WHERE Sysrow=1 AND nId < 39

UPDATE Ac_Items SET Sysrow=a.sysrow
FROM Ac_Items i
INNER JOIN ATYPE a ON A.typeId=I.TypeId 
WHERE I.Sysrow<>A.sysrow AND I.nId>39

IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE TypeId='000030000200007' )
	UPDATE Ac_Items SET IsModify=0 WHERE TypeId='000030000200007'

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE SonNum <> 0 AND UserCode IN (SELECT UserCode FROM dbo.atype WHERE sonnum <> 0))
--插入atype所有父结点到Ac_Items
INSERT INTO dbo.Ac_Items
        ( 
		  nTypeId ,
          nParId ,
          Leveal ,
          SonNum ,
          SonCount ,
          UserCode ,
          FullName ,
          Name ,
          CreateBank ,
          BankType ,
          IsBank ,
          Comment ,
          PyCode ,
          Deleted ,
          TypeName ,
          XiWaMaxNumber ,
          Sysrow ,
          IsModify
        )
SELECT typeId,parid,leveal,sonnum,soncount,UserCode,FullName,Name,'','',0,Comment,PyCode,Deleted,
		CASE LEFT(typeId,10)
			WHEN '00000' THEN ''
			WHEN '0000100004' THEN 'B'
			WHEN '0000100002' THEN 'F'
			ELSE CASE LEFT(typeId,5)
					WHEN '00001' THEN 'C'
					WHEN '00002' THEN 'L'
					WHEN '00003' THEN 'G'
					WHEN '00004' THEN 'E'
				 END
		END ,XiWaMaxNumber,sysrow,ifCanClass
FROM dbo.atype 
WHERE sonnum  <> 0 AND typeId <> '00005'

--atype数据与ac_items数据匹配的，直接按atype父子结点关系更新
UPDATE dbo.Ac_Items 
SET nTypeId = T1.typeId,nParId = T1.parid
FROM dbo.atype T1
	INNER JOIN dbo.Ac_Items T2 ON T1.UserCode = T2.UserCode
WHERE T1.sonnum = 0 AND (( LEFT(T1.typeId,10)='0000100004' AND T2.TypeName='B')
						OR (T1.typeid = '0000100003' AND T2.TypeName = 'B')
						OR (LEFT(T1.typeId,10)='0000100002' AND T2.TypeName='F')
						OR (LEFT(T1.typeId,5) = '00001' AND T2.TypeName='C')
						OR (LEFT(T1.typeId,5) = '00002' AND T2.TypeName='L')
						OR (LEFT(T1.typeId,5) = '00003' AND T2.TypeName='G')
						OR (LEFT(T1.typeId,5) = '00004' AND T2.TypeName='E')
						)
--处理用户在ac_items中新增的项，直接关联指定父结点
DECLARE @nId INT ,@TypeName VARCHAR(2),@AUserCode VARCHAR(100),@Sysrow INT

DECLARE specialCur CURSOR READ_ONLY FOR
	SELECT nid,TypeName,UserCode,Sysrow 
	FROM dbo.Ac_Items 
	WHERE nid NOT in
		(SELECT nId FROM dbo.atype T1
			INNER JOIN dbo.Ac_Items T2 ON T1.UserCode = T2.UserCode
			WHERE T1.sonnum = 0 AND (( LEFT(T1.typeId,10)='0000100004' AND T2.TypeName='B')
						OR (T1.typeid = '0000100003' AND T2.TypeName = 'B')
						OR (LEFT(T1.typeId,10)='0000100002' AND T2.TypeName='F')
						OR (LEFT(T1.typeId,5) = '00001' AND T2.TypeName='C')
						OR (LEFT(T1.typeId,5) = '00002' AND T2.TypeName='L')
						OR (LEFT(T1.typeId,5) = '00003' AND T2.TypeName='G')
						OR (LEFT(T1.typeId,5) = '00004' AND T2.TypeName='E')
						)
		)
		AND SonNum = 0

OPEN specialCur
FETCH NEXT FROM specialCur INTO @nId,@TypeName,@AUserCode,@Sysrow

DECLARE @parid VARCHAR(50),@dbname VARCHAR(50),@newTypeid VARCHAR(50),
		@nSonnum INT,@nSoncount INT,@nReturntype INT
SET @dbname = 'Ac_Items'

UPDATE dbo.Ac_Items SET SonCount = (SELECT COUNT(nTypeId) FROM dbo.Ac_Items WHERE LEN(nTypeId)= 5 AND nTypeId <> '00000') WHERE nTypeId = '00000'


WHILE @@FETCH_STATUS = 0
BEGIN
	IF @TypeName = 'B'	--B 银行
		SELECT @parid = typeId FROM dbo.atype WHERE UserCode = '87'
	ELSE IF @TypeName = 'G'--G 其他收入
		SELECT @parid = typeId FROM dbo.atype WHERE UserCode = '5102'
	ELSE IF @TypeName = 'E' --E 费用合计
		SELECT @parid = typeId FROM dbo.atype WHERE UserCode = '043'
	ELSE IF @TypeName = 'F'--F 固定资产
		SELECT @parid = typeId FROM dbo.atype WHERE UserCode = '1501'
	ELSE IF @TypeName = 'C'--C 资产
		SELECT @parid = typeId FROM dbo.atype WHERE UserCode = '90'
	ELSE IF @TypeName = 'L'--L 负债类
		SELECT @parid = typeId FROM dbo.atype WHERE UserCode = '02'
	ELSE IF @TypeName = 'A' AND @Sysrow = 1--A 新增所有者权益 特殊处理
		BEGIN
			IF @AUserCode = '05' 
				SELECT @parid = '00000'
			ELSE 
				SELECT @parid = nTypeId FROM dbo.Ac_Items WHERE UserCode = '05'
		END
	
	
	--计算typeid
	DECLARE @szTypeId	VARCHAR(50),
			@sonnum		INT,
			@par		VARCHAR(50),
			@soncount	INT,
			@createdid	VARCHAR(50)

		
	SELECT 	@szTypeId = ntypeid,
			@sonnum =sonnum,
			@par = parid,
			@soncount = soncount 
	FROM 	ac_items 
	WHERE 	ntypeid= @parid

	
	DECLARE @tempId 	VARCHAR(5),
			@nReturn 	INT
	SELECT @soncount=@soncount+1
	EXEC @nReturn=inttostr @soncount,@tempId out
	IF @nReturn=-1  
	BEGIN
		RAISERROR('分类不能超过10层',16,1)
	END 
	ELSE
	BEGIN
		IF @sztypeid='00000' 
			SELECT @createdid=@tempId			
		ELSE 
			SELECT @createdid=RTRIM(@szTypeid)+@tempId
	END

	UPDATE dbo.Ac_Items SET nTypeId = @createdid,nParId = @parid
	WHERE nId = @nId
	
	
	--调整父结点sonnum,soncount
	UPDATE dbo.Ac_Items SET SonNum = SonNum + 1,SonCount = SonCount + 1
	WHERE nTypeId = @parid

	
	FETCH NEXT FROM specialCur INTO @nId,@TypeName,@AUserCode,@Sysrow
END

CLOSE specialCur
DEALLOCATE specialCur


--处理sonnum
UPDATE dbo.Ac_Items SET SonNum = (SELECT COUNT(nTypeId) FROM dbo.Ac_Items T1 WHERE T1.nParId = T2.ntypeid)
FROM dbo.Ac_Items T2
WHERE T2.SonNum <> 0
--处理soncount（00001的子结点中缺失0000100006，会导致新增结点ntypeid重复）
DECLARE @soncountTypeid VARCHAR(50)
SELECT TOP 1  @soncountTypeid = nTypeId
FROM dbo.Ac_Items WHERE nparid = '00001'
ORDER BY ntypeId DESC 

UPDATE dbo.Ac_Items SET SonCount = CAST(SUBSTRING(@soncountTypeid,6,10) AS INT)
WHERE nTypeId = '00001'

--处理银行的isbank
UPDATE dbo.Ac_Items SET IsBank = 1 WHERE nTypeId LIKE '0000100004%'



-----------------新增预置数据处理--------------------------------

DECLARE @cTypeId VARCHAR(50),@cParid VARCHAR(50),@MaxXiwa INT
--调整"现金"到“全部现金合计”下
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = 'SYS-1001')
BEGIN
	
	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@cParid = nParId FROM dbo.Ac_Items WHERE UserCode = '1001'

	UPDATE dbo.Ac_Items SET nTypeId = @cTypeId,nParId = @cParid,Leveal = 2,SonCount = 1,SonNum = 1,XiWaMaxNumber = @MaxXiwa + 1,IsBank=0 WHERE UserCode = 'SYS-1001'
	UPDATE dbo.Ac_Items SET nTypeId = @cTypeId + '00001',nParId = @cTypeId,Leveal = 3,SonCount = 0,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '1001'
END

--再次处理现金名称为“默认现金”，防止未处理到
UPDATE dbo.Ac_Items SET FullName = '默认现金' WHERE nId = 1

--调整“待摊费用”到“待摊费用合计”下
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = 'SYS-1301')
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@cParid = nParId FROM dbo.Ac_Items WHERE UserCode = '1301'

	UPDATE dbo.Ac_Items SET nTypeId = @cTypeId,nParId = @cParid,Leveal = 2,SonCount = 1,SonNum = 1,XiWaMaxNumber = @MaxXiwa + 1,IsBank=0 WHERE UserCode = 'SYS-1301'
	UPDATE dbo.Ac_Items SET nTypeId = @cTypeId + '00001',nParId = @cTypeId,Leveal = 3,SonCount = 0,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '1301'
END

-----------调整“0435-财务费用”到“支出类-费用合计”下，“043599-汇兑损益”到“支出类-费用合计-财务费用”下，同时调整父节点相关信息------------------------
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '0435'  AND Sysrow=1 )
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '043' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '043' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '0435'  AND Sysrow=1
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '043599'  AND Sysrow=1 )
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '0435' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '0435' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '043599'  AND Sysrow=1
END
----------------------------------------------------------------------------------------------------------------------------------------------------

-----------在【基础资料-项目管理-支出类-费用合计】下预设【0445-销售费用】项目，并预设下级项目【044599-业务提成】项目；------------------------
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '0445'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '043' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '043' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '0445'  AND Sysrow=1
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '044599'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '0445' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '0445' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '044599'  AND Sysrow=1
END
--044598  运杂费
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '044598'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '0445' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '0445' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '044598'  AND Sysrow=1
END
--044597  在【基础资料-项目管理-支出类-费用合计-销售费用】下预设项目【044597-市场活动费用】项目
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '044597'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '0445' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '0445' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '044597'  AND Sysrow=1
END
-------在【基础资料-项目管理-支出类-费用合计-销售费用】下预设【044596-积分转储值】项目------------------------
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '044596'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '0445' AND Sysrow=1

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE nTypeId=@cTypeId
	UPDATE dbo.Ac_Items SET nTypeId =@cTypeId+ REPLICATE('0',5-LEN(@soncount))+CAST(@soncount AS VARCHAR(5)),nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '044596' AND Sysrow=1 		
END

--在【基础资料-项目管理-收入类-其他收入】下预设项目【0334-优惠券收入】项目；
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '0334'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '5102' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '5102' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '0334'  AND Sysrow=1
END
--在【基础资料-项目管理-负债合计】下预设【2191-优惠券】项目；
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '2191'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '02' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '02' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '2191'  AND Sysrow=1
END

-----------在【基础资料-项目管理-负债合计】下预设【2211-应付职工薪酬、221199-员工提成】项目；------------------------
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '2211'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '02' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '02' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '2211'  AND Sysrow=1
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '221199'  AND Sysrow=1)
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '2211' AND Sysrow=1
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '2211' AND Sysrow=1
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '221199'  AND Sysrow=1
END
-------------------------------------------------新增预置数据end---------------------------------------------------------------------------------------------------
-----------在【基础资料-项目管理-】下预设【资产类 1251-发出商品、负债类 2211-应付暂估】项目；------------------------
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '1251'  AND Sysrow=1 AND ISNULL(nTypeId,'')='')
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '90'
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '90'
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '1251' AND Sysrow=1 
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = '2122'  AND Sysrow=1 AND ISNULL(nTypeId,'')='')
BEGIN	
	SELECT @MaxXiwa = MAX(XiWaMaxNumber) FROM dbo.Ac_Items

	SELECT @cTypeId = nTypeId,@soncount = SonCount+1 FROM dbo.Ac_Items WHERE UserCode = '2122'
	
	EXEC inttostr @soncount,@tempId out

	UPDATE dbo.Ac_Items SET SonCount = SonCount+1,SonNum = SonNum+1,XiWaMaxNumber = @MaxXiwa + 1 WHERE UserCode = '02'
	UPDATE dbo.Ac_Items SET nTypeId = RTRIM(@cTypeId)+@tempId,nParId = @cTypeId,XiWaMaxNumber = @MaxXiwa + 2 WHERE UserCode = '2122' AND Sysrow=1 
END
----------------------------------------------------------------------------------------------------------------------------------------------------




--处理分支机构
DECLARE @stypeCount INT
SELECT @stypeCount = COUNT(TypeId)
FROM dbo.SType
WHERE TypeId <> '00000'

CREATE TABLE #SType
(
	rowindex	INT IDENTITY(1,1),
	typeid		VARCHAR(50)
)
INSERT INTO #SType(typeid)
SELECT TypeId
FROM dbo.SType WHERE TypeId <> '00000'

DECLARE @snid INT,@index INT,@stypeid VARCHAR(50)
DECLARE nidCur CURSOR READ_ONLY FOR
	SELECT nId
	FROM dbo.Ac_Items
	WHERE nTypeId <> '00000'
OPEN nidCur
FETCH NEXT FROM nidCur INTO @snid

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @index = 1
	WHILE @index<=@stypeCount
	BEGIN
		SELECT @stypeid = typeid FROM #SType WHERE rowindex = @index
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items_Detail WHERE nId = @snid AND STypeId = @stypeid)
			INSERT INTO dbo.Ac_Items_Detail
			        ( nId ,
			          STypeId ,
			          ATypeId ,
			          DepATypeId ,
			          DisATypeId ,
			          XiWaMaxNumber
			        )
			VALUES  ( @snid , -- nId - int
			          @stypeid , -- STypeId - varchar(50)
			          '' , -- ATypeId - varchar(50)
			          '' , -- DepATypeId - varchar(50)
			          '' , -- DisATypeId - varchar(50)
			          1  -- XiWaMaxNumber - int
			        )
		SET @index += 1
	END
	
	FETCH NEXT FROM nidCur INTO @snid	
END
CLOSE nidCur
DEALLOCATE nidCur



DECLARE @CodeIndex INT,@CodeCount INT,@userCode VARCHAR(50),@fullname VARCHAR(200)
--调整usercode重复
CREATE TABLE #TmpUsercode
(
	Usercode	VARCHAR(50),
	RowIndex	INT IDENTITY(1,1)
)

INSERT INTO #TmpUsercode( Usercode)
SELECT UserCode
FROM
(
SELECT COUNT(*) AS num,UserCode
FROM dbo.Ac_Items
WHERE nTypeId <> '00000'
GROUP BY UserCode
)T
WHERE num <> 1

SET @CodeIndex = 1

SELECT @CodeCount = COUNT(*)
FROM #TmpUsercode

WHILE @CodeIndex <= @CodeCount
BEGIN
	SELECT @userCode = usercode FROM #TmpUsercode WHERE RowIndex = @CodeIndex
	
	UPDATE dbo.Ac_Items SET UserCode = UserCode + '@' + CAST(nId AS VARCHAR(10))
	WHERE UserCode = @userCode AND SonNum <> 0 AND Sysrow = 0
		
	SET @CodeIndex += 1
END
--调整fullname重复
CREATE TABLE #TmpFullName
(
	FulllName	VARCHAR(200),
	RowIndex	INT IDENTITY(1,1)
)

INSERT INTO #TmpFullName(FulllName)
SELECT FullName
FROM
(
SELECT COUNT(*) AS num,FullName
FROM dbo.Ac_Items
WHERE nTypeId <> '00000'
GROUP BY FullName
)T
WHERE num <> 1


SET @CodeIndex = 1

SELECT @CodeCount = COUNT(*)
FROM #TmpFullName

WHILE @CodeIndex <= @CodeCount
BEGIN
	SELECT @fullname = FulllName FROM #TmpFullName WHERE RowIndex = @CodeIndex
	
	UPDATE dbo.Ac_Items SET FullName = FullName + '@' + CAST(nId AS VARCHAR(10))
	WHERE FullName = @fullname AND Sysrow = 0
	
	SET @CodeIndex += 1
END

DROP TABLE #TmpUsercode,#TmpFullName


UPDATE a SET SonCount = (SELECT TOP 1 CAST(RIGHT(b.nTypeId,5) AS INT)  FROM Ac_Items b WHERE b.nParId = a.nTypeId ORDER BY b.nTypeId DESC)
FROM Ac_Items a
WHERE a.SonNum > 0




--调整项目表中sonnum,防止异常导致ntypeid重复
DECLARE @nTypeId VARCHAR(50),@SumSon INT

DECLARE updateCur CURSOR READ_ONLY FOR
	SELECT nTypeId
	FROM dbo.Ac_Items

OPEN updateCur

FETCH NEXT FROM updateCur INTO @nTypeId

WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT @SumSon = COUNT(nTypeId) FROM dbo.Ac_Items WHERE nParId = @nTypeId
	UPDATE dbo.Ac_Items SET SonNum = @SumSon WHERE nTypeId = @nTypeId

	FETCH NEXT FROM updateCur INTO @nTypeId
END
--bug 535
UPDATE dbo.Ac_Items SET FullName = '『会员储值』' WHERE nId = 34

CLOSE updateCur
DEALLOCATE updateCur


--处理leveal
UPDATE dbo.Ac_Items SET Leveal = LEN(nTypeId)/5
WHERE nTypeId <> '00000'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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


/****** Object:  StoredProcedure [dbo].[Gp_ImportB]    Script Date: 05/20/2011 17:29:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*
	作者：廖晨羽
	日期：2011-08-17
	描述：修改@TelAndAddress参数的长度为256,添加etypeid字段
	
	修 改 者：廖晨羽
	日    期：2011-08-22
	修改原因：导入供货商信息
	修改位置：转换输入参数
*/





CREATE                  PROCEDURE [dbo].[Gp_ImportB]
(
	@BFullName   [varchar](66),
	@UserCode  [varchar](26),
	@FullName  [varchar](66),
	@PyCode   varchar(201),
	@StrCreateDate varchar(200),
	@AFullName VARCHAR(66),
	@consignee	VARCHAR(100),	--收货人
	@consigneetel VARCHAR(100),	--收货人电话
	@consigneeaddress VARCHAR(500),	--到货地址
	@EFullName VARCHAR(66), --职员
	@StrARLimitTime [varchar](18),
	@StrPaymentLTime[varchar] (18), 
	@Strbuyprice varchar(200),
	@StrSaleZeKou VARCHAR(18),
	@StrBuyZeKou VARCHAR(18),
	@StrPrice    varchar(200),
	@Tel1	varchar(50),
	@Tel2	varchar(50),
	@Tel3	varchar(50),
	@Fax	varchar(50),
	@Email	varchar(50),
	@WWW	varchar(50),
	@PostCode  [varchar](201),
	@TelAndAddress  [varchar](257),
	@bankandacount  [varchar](66),
	@Bank	varchar(50),
	@BankName varchar(50),
	@TaxNumber  [varchar](20),
	@Comment  [varchar](257),
	@LinkMan1 varchar(50),
	@StrLinkSex1 VARCHAR(10),
	@StrLinkBirthDay1 varchar(200),
	@LinkJob1 varchar(50),
	@LinkCall1 Varchar(50),
	@LinkEMail1 varchar(50),
	@LinkTel1 varchar(50),
	@LinkMobile1 varchar(50),
	@LinkPost1 varchar(50),
	@LinkAddress1 varchar(50),
	@LinkComment1 varchar(257),
	@LinkMan2 varchar(50),
	@StrLinkSex2 VARCHAR(10),
	@StrLinkBirthDay2 varchar(200),
	@LinkJob2 varchar(50),
	@LinkCall2 Varchar(50),
	@LinkEMail2 varchar(50),
	@LinkTel2 varchar(50),
	@LinkMobile2 varchar(50),
	@LinkPost2 varchar(50),
	@LinkAddress2 varchar(50),
	@LinkComment2 varchar(257),
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
IF ((SELECT DATALENGTH(@PyCode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@PostCode)) > 200)
BEGIN
	SET @ErrMsg = '邮编的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@TelAndAddress)) > 256)
BEGIN
	SET @ErrMsg = '地址的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 256)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@LinkComment1)) > 256)
BEGIN
	SET @ErrMsg = '联系人1备注的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@LinkComment2)) > 256)
BEGIN
	SET @ErrMsg = '联系人2备注的长度大于最大允许长度256'
	RETURN -1
END

DECLARE @Parid VARCHAR(50)
IF (@BFullName = '')
BEGIN
	SET @Parid = '00002'
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.btype WHERE fullname = @BFullName) OR @BFullName = 'ABC'
	BEGIN
		SET @ErrMsg = '父类名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PBtypeId VARCHAR(50)
		SET @PBtypeId = (SELECT TOP 1 typeid FROM BType WHERE fullname = @BFullName)
		IF (SUBSTRING(@PBtypeId, 1, 5) = '00001')
			BEGIN
				SET @ErrMsg = '父类名称不存在'
				RETURN -1
			END
		ELSE
			BEGIN
				SET @Parid = @PBtypeId
			END
	END	
END

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '供货商编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '供货商名称不能为空'
	RETURN -1
END

IF(@Pycode = '')
BEGIN
	SELECT @Pycode = dbo.fun_getPY(@FullName)
END

DECLARE	@CreateDate DATETIME
IF (@StrCreateDate = '')
BEGIN
	SELECT @CreateDate = CONVERT(VARCHAR, GETDATE(), 23)
END
ELSE IF (ISDATE(@StrCreateDate) <> 1)
	 BEGIN
	 		SET @ErrMsg = '建档日期请输入日期,请使用YYYY-MM-DD的格式'
			RETURN -1
	 END
ELSE
BEGIN
	SET @CreateDate = @StrCreateDate
END

DECLARE @AreaTypeID varchar(50)
IF (@AFullName = '')
BEGIN
	SET @AreaTypeID = ''
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.AreaType WHERE fullname = @AFullName) OR @AFullName = '所有地区'
	BEGIN
		SET @ErrMsg = '地区名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PAtypeId VARCHAR(50)
		DECLARE @AChildCount NUMERIC(18,0)
		SET @PAtypeId = (SELECT TOP 1 typeid FROM dbo.AreaType WHERE fullname = @AfullName)
		SELECT @AChildCount = COUNT(*) FROM dbo.AreaType WHERE typeId LIKE @PAtypeId + '%' AND typeId <> @PAtypeId
		IF (@AChildCount = 0)
			BEGIN
				SET @AreaTypeID = @PAtypeId
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该地区是父节点'
				RETURN -1
			END
	END	
END

DECLARE @etypeid varchar(50)
IF (@EFullName = '')
BEGIN
	SET @etypeid = ''
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.employee WHERE fullname = @EFullName) OR @EFullName = 'root' OR @EFullName = '超级用户'
	BEGIN
		SET @ErrMsg = '关联职员不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PEtypeId VARCHAR(50)
		DECLARE @EChildCount NUMERIC(18,0)
		SET @PEtypeId = (SELECT TOP 1 typeid FROM dbo.employee WHERE fullname = @EFullName)
		SELECT @EChildCount = COUNT(*) FROM dbo.employee WHERE typeId LIKE @PEtypeId + '%' AND typeId <> @PEtypeId
		IF (@EChildCount = 0)
			BEGIN
				SET @etypeid = @PEtypeId
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该职员是父节点'
				RETURN -1
			END
	END	
END

DECLARE @ARLimitTime  NUMERIC(24, 10) 
IF (@StrARLimitTime = '')
BEGIN
	SET @ARLimitTime = 9999
END
ELSE IF(ISNUMERIC(@StrARLimitTime) <> 1)
BEGIN
	SET @ErrMsg = '收款期限请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('.', @StrARLimitTime)) <> 0)
BEGIN
	SET @ErrMsg = '收款期限请输入整数'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrARLimitTime)) <> 0)
BEGIN
	SET @ErrMsg = '收款期限不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @ARLimitTime = CONVERT( NUMERIC(24, 10) , @StrARLimitTime)
	IF(@ARLimitTime <=0)
	BEGIN
		SET @ErrMsg = '收款期限不能为0'
		RETURN -1
	END
	IF(@ARLimitTime > 9999)
	BEGIN
		SET @ErrMsg = '收款期限应小于9999'
		RETURN -1
	END
END

DECLARE @PaymentLTime  NUMERIC(24, 10) 
IF (@StrPaymentLTime = '')
BEGIN
	SET @PaymentLTime = 9999
END
ELSE IF(ISNUMERIC(@StrPaymentLTime) <> 1)
BEGIN
	SET @ErrMsg = '付款期限请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('.', @StrPaymentLTime)) <> 0)
BEGIN
	SET @ErrMsg = '付款期限请输入整数'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPaymentLTime)) <> 0)
BEGIN
	SET @ErrMsg = '付款期限不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PaymentLTime = CONVERT( NUMERIC(24, 10) , @StrPaymentLTime)
	IF(@PaymentLTime <=0)
	BEGIN
		SET @ErrMsg = '付款期限不能为0'
		RETURN -1
	END
	IF(@PaymentLTime > 9999)
	BEGIN
		SET @ErrMsg = '付款期限应小于9999'
		RETURN -1
	END
END

DECLARE	@buyprice varchar(50)
SELECT @buyprice = CASE @Strbuyprice 
						   WHEN '无' THEN '0'
						   WHEN '' THEN '0'
						   WHEN '预设进价1' THEN '1'
						   WHEN '预设进价2' THEN '2'
						   WHEN '预设进价3' THEN '3'
						   WHEN '预设进价4' THEN '4'
						   WHEN '预设进价5' THEN '5'
						   WHEN '最高进价' THEN '6'
						   ELSE 'ERROR' 
				END
IF(@buyprice = 'ERROR')
BEGIN
	SET @ErrMsg = '适用进价不匹配'
	RETURN -1
END


DECLARE @SaleZeKou  NUMERIC(24, 10) 
IF (@StrSaleZeKou = '')
BEGIN
	SET @SaleZeKou = NULL
END
ELSE IF(ISNUMERIC(@StrSaleZeKou) <> 1)
BEGIN
	SET @ErrMsg = '销售折扣请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrSaleZeKou)) <> 0)
BEGIN
	SET @ErrMsg = '销售折扣不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @SaleZeKou = CONVERT( NUMERIC(24, 10) , @StrSaleZeKou)
	IF (@SaleZeKou<=0 OR @SaleZeKou >1)
	BEGIN
		SET @ErrMsg = '销售折扣输入错误'
		RETURN -1
	END
END

DECLARE @BuyZeKou  NUMERIC(24, 10) 
IF (@StrBuyZeKou = '')
BEGIN
	SET @BuyZeKou = NULL
END
ELSE IF(ISNUMERIC(@StrBuyZeKou) <> 1)
BEGIN
	SET @ErrMsg = '采购折扣请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrBuyZeKou)) <> 0)
BEGIN
	SET @ErrMsg = '采购折扣不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @BuyZeKou = CONVERT( NUMERIC(24, 10) , @StrBuyZeKou)
	IF (@BuyZeKou<=0 OR @BuyZeKou >1)
	BEGIN
		SET @ErrMsg = '采购折扣输入错误'
		RETURN -1
	END
END

DECLARE	@Price varchar(50)
SELECT @Price = CASE @StrPrice  
						   WHEN '无' THEN '0'
						   WHEN '' THEN '0'
						   WHEN '预设售价1' THEN '1'
						   WHEN '预设售价2' THEN '2'
						   WHEN '预设售价3' THEN '3'
						   WHEN '预设售价4' THEN '4'
						   WHEN '预设售价5' THEN '5'
						   WHEN '预设售价6' THEN '6'
						   WHEN '预设售价7' THEN '7'
						   WHEN '预设售价8' THEN '8'
						   WHEN '预设售价9' THEN '9'
						   WHEN '预设售价10' THEN '10'
						   WHEN '零售价' THEN '11'
						   WHEN '最高售价' THEN '12'
						   WHEN '最低售价' THEN '13'
						   ELSE 'ERROR' 
				END
IF(@Price = 'ERROR')
BEGIN
	SET @ErrMsg = '适用售价不匹配'
	RETURN -1
END

DECLARE @PostCodeLen INT
SELECT @PostCodeLen = LEN(@PostCode)
IF(@PostCodeLen>200)
BEGIN
	SET @ErrMsg = '邮编不能超过200字符'
	RETURN -1
END


DECLARE @LinkSex1 BIT
SELECT @StrLinkSex1 = CASE @StrLinkSex1 
							WHEN '' THEN '1'
							WHEN '男' THEN '1' 
							WHEN '女' THEN '0'
							ELSE '无'			
					END
IF(@StrLinkSex1 = '无')
BEGIN
	SET @ErrMsg = '性别请输入男或女'
	RETURN -1
END
ELSE
BEGIN
	SET @LinkSex1 = CONVERT(BIT, @StrLinkSex1)
END

DECLARE	@LinkBirthDay1 DATETIME
IF (@StrLinkBirthDay1 = '')
BEGIN
	SELECT @LinkBirthDay1 = '1980-01-01 00:00:00'
END
ELSE IF (ISDATE(@StrLinkBirthDay1) <> 1 )
	 BEGIN
 		SET @ErrMsg = '联系人1生日请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	 END
ELSE
BEGIN
	SET @LinkBirthDay1 = @StrLinkBirthDay1
END

DECLARE @LinkSex2 BIT
SELECT @StrLinkSex2 = CASE @StrLinkSex2 
							WHEN '' THEN '1'
							WHEN '男' THEN '1' 
							WHEN '女' THEN '0'
							ELSE '无'			
					END
IF(@StrLinkSex2 = '无')
BEGIN
	SET @ErrMsg = '性别请输入男或女'
	RETURN -1
END
ELSE
BEGIN
	SET @LinkSex2 = CONVERT(BIT, @StrLinkSex2)
END

DECLARE	@LinkBirthDay2 DATETIME
IF (@StrLinkBirthDay2 = '')
BEGIN
	SELECT @LinkBirthDay2 = '1980-01-01 00:00:00'
END
ELSE IF (ISDATE(@StrLinkBirthDay2) <> 1 )
	 BEGIN
 		SET @ErrMsg = '联系人2生日请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	 END
ELSE
BEGIN
	SET @LinkBirthDay2 = @StrLinkBirthDay2
END

DECLARE @DbName VARCHAR(30) = 'btype'

DECLARE @Name  [Varchar](30) = ''

DECLARE @Area  [Varchar](30) = ''

DECLARE @Person  [varchar](20) = ''

DECLARE @Artotal00  NUMERIC(24, 10)  = 0

DECLARE @Aptotal00  NUMERIC(24, 10)  = 0

DECLARE @Client BIT = 1

DECLARE @ARLimit  NUMERIC(24, 10) 

DECLARE @ifStype INT = 1

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

declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(select subvalue from sysdata where subname='ifqp')

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from btype where typeid=@parid)
declare @typeName varchar(20)
if substring(@parid,1,5)='00001'
	set @typeName='客户'
if substring(@parid,1,5)='00002'
	set @typeName='供货商'

-- 判断单位的往来
if @Parid='00000'
return -11

--判断停用不能分类
declare @deleted INT
select @deleted=deleted from btype where typeId=@Parid
if(@deleted=1)
BEGIN
   SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已经被停用，不能分类'
   RETURN -1	
   --RAISERROR('该%s【%s】已经被停用，不能分类',16,1,@typeName,@parFullName)return ---15  
end
--判断序列号
if exists(select BTypeID1 from gp_CruPtypeSerial where BTypeID1=@Parid)
	begin
		--print '住来有序列号，不能分类'
		 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有序列号关联情况，不能分类'
		 RETURN -1
		 --RAISERROR('该%s【%s】已有序列号关联情况，不能分类',16,1,@typeName,@parFullName)return ---15
	end
if exists(select BTypeID1 from gp_initPtypeSerial where BTypeID1=@Parid)
	begin
		--print '往来有期初序列号，不能分类'
		 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有期初序列号关联情况，不能分类'
		 RETURN -1
		 --RAISERROR('该【%s】已有期初序列号关联情况，不能分类',16,1,@typeName,@parFullName)return --16
	end
	
--判断是否被分支机构使用，若被使用则禁止分类
IF EXISTS(SELECT * FROM SType WHERE BTypeID1=@Parid OR BTypeID2=@Parid)
	BEGIN
		SET @ErrMsg = '该往来单位已经被分支机构关联，禁止分类'
		RETURN -1					
		--RAISERROR('该往来单位已经被分支机构关联，禁止分类',16,1)
		--RETURN		
	END
--判断序列号
if exists(select BTypeID2 from gp_CruPtypeSerial where BTypeID2=@Parid)
	begin
		--print '住来有序列号，不能分类'
		 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有序列号关联情况，不能分类'
		 RETURN -1	
		 --RAISERROR('该%s【%s】已有序列号关联情况，不能分类',16,1,@typeName,@parFullName)return--return -15
	end
if exists(select BTypeID2 from gp_initPtypeSerial where BTypeID2=@Parid)
	begin
		--print '往来有期初序列号，不能分类'
		 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有期初序列号关联情况，不能分类'
		 RETURN -1	
		 --RAISERROR('该%s【%s】已有期初序列号关联情况，不能分类',16,1,@typeName,@parFullName)return--return -16
	end

if exists(select typeid from [btype] where typeid=@parid and ARTotal-ApTotal<>0)
	begin
		--print '['+@FullName+']单位往来帐不为零，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】往来帐不为零，不能分类'
		RETURN -1	
		--RAISERROR('该%s【%s】往来帐不为零，不能分类',16,1,@typeName,@parFullName)return
	end 
if exists(select typeid from [btype] where typeid=@parid and ARTotal00-ApTotal00<>0)
	begin
		--print '['+@FullName+']单位往来帐不为零，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】往来帐不为零，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】往来帐不为零，不能分类',16,1,@typeName,@parFullName)return--return -7
	end 

--判断应收应付预收预付期初
if exists(select BTypeID from BType_ArApTotal where BTypeID=@parid and (ARTotal00<>0 or APTotal00<>0 or YSTotal00<>0 or YFTotal00<>0))
	begin
		--print '['+@FullName+']单位往来帐不为零，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】应收或应付期初中不为零，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】应收或应付期初中不为零，不能分类',16,1,@typeName,@parFullName)return--return -7
	end 

-- 判断借欠余额
if exists(select bTypeID from V_LendStatus where bTypeID=@parid and Qty<>0)
	begin
		--print '['+@FullName+']单位有借进借出，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有借进借出，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有借进借出，不能分类',16,1,@typeName,@parFullName)return--return -5
	end 
-- 判断经营
if exists(select bTypeID from listtable where bTypeID=@parid )
   or exists(select bTypeID from LendIndex where bTypeID=@parid and totalQty<>0) 
   or exists(select bTypeID from BillIndex where bTypeID=@parid )
	begin
		--print '['+@FullName+']单位已经经营过，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已经经营过，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已经经营过，不能分类',16,1,@typeName,@parFullName)return--return -6
	end 
IF  exists(select bTypeID from OrderIndex where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 订单
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在订单中使用过，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已在订单中使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -501
	END
IF  exists(select bTypeID from LendIndex where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 借欠
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在借欠单种使用过，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已在借欠单种使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -502
	END
IF  exists(select bTypeID from AdDebtBill where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 借欠
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在应收应付中使用过，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已在应收应付中使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -502
	END

-- 判断代销情况
if exists(select bTypeID from iniCommissionStock where bTypeID=@parid and Qty<>0)
   or exists(select bTypeID from CommissionStock where bTypeID=@parid and Qty<>0)
	begin
		--print '['+@FullName+']单位有代销情况，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有代销情况，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有代销情况，不能分类',16,1,@typeName,@parFullName)return--return -13
	end 

-- 判断代销情况
if exists(select bTypeID from iniCommissionStock where bTypeID=@parid and (total<>0 or costtotal<>0))
   or exists(select bTypeID from CommissionStock where bTypeID=@parid and (total<>0 or costtotal<>0))
	begin
		--print '['+@FullName+']单位有代销情况，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有代销情况，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有代销情况，不能分类',16,1,@typeName,@parFullName)return--return -13
	end 


IF  exists(select bTypeID from PriceProtect where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位有经营历程，不能分类
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有价保通知，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有价保通知，不能分类',16,1,@typeName,@parFullName)return--RETURN -508
	END

IF  exists(select bTypeID from FapiaoBillIndex where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位有发票，不能分类
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有发票，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有发票，不能分类',16,1,@typeName,@parFullName)return--RETURN -510
	END

--判断价格跟踪
IF EXISTS(select btypeid from PriceTrack where BtypeID=@Parid)
	BEGIN
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联价格跟踪，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已关联价格跟踪，不能分类',16,1,@typeName,@parFullName)RETURN
	END
--判断信用额度
IF EXISTS(select btypeid from BType_Credit where BtypeID=@Parid)
	BEGIN
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有信用额度，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已有信用额度，不能分类',16,1,@typeName,@parFullName)RETURN
	END
--判断在会计凭证中是否关联
IF EXISTS(select ATypeID from AccountCredence where ATypeID=@Parid and TypeATypeID in('0000100009', '0000100005',  '0000200001',  '0000200006'))
	BEGIN
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联会计凭证，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已关联会计凭证，不能分类',16,1,@typeName,@parFullName)RETURN
	END
--商品信息关联分支机构，则该分支机构不能被分类
IF EXISTS(select BTypeID from QP_PType_Ext where BTypeID=@Parid)	
	BEGIN 
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联商品，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已关联商品，不能分类',16,1,@typeName,@parFullName)RETURN
	END
--关联维修业务中的保险公司
IF EXISTS(select BTypeID from Qp_ReceptionBill_Insurance where BTypeID=@Parid)	
	BEGIN 
	    --print '25555'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联维修业务，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已关联维修业务，不能分类',16,1,@typeName,@parFullName)RETURN
	END
-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
	BEGIN
		SET @ErrMsg = '客户和供货商的分类不能超过9层'
		RETURN -1
		--RAISERROR('客户和供货商的分类不能超过9层',16,1)return-- return -1
	end
if @nReturntype=-2 
	BEGIN
		SET @ErrMsg = '无法添加基本信息'
		RETURN -1
		--RAISERROR('无法添加基本信息',16,1)return--return -2
	end
-- 判断重复的ID,UserCode
if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
	begin
		--print '['+@usercode+']往来已存在'
		SET @ErrMsg = '该【' + @FullName + '】已经存在，' + @typeName + '编号或名称不能相同'
		RETURN -1
		--RAISERROR('该【%s】已经存在，%s编号或名称不能相同',16,1,@FullName,@typeName)return--return -3
	end

if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
	begin
		--print '['+@usercode+']往来已存在'
		SET @ErrMsg = @typeName + '名称或编号不能与已有的名称或编号重复'
		RETURN -1
		--RAISERROR('%s名称或编号不能与已有的名称或编号重复',16,1,@typeName)return--return -10
	end

-- 判断重复的ID,UserCode
if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		--print '['+@usercode+']往来已存在'
		SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被已停用的' + @typeName + '使用，请更换或删除该停用的编号或名称'
		RETURN -1
		--RAISERROR('该【%s】的编号或名称已被已停用的%s使用，请更换或删除该停用的编号或名称',16,1,@FullName,@typeName)--return -31
	end

if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
	begin
		--print '['+@usercode+']往来已存在'
		SET @ErrMsg = @typeName + '名称或编号不能与已停用的名称或编号重复'
		RETURN -1
		--RAISERROR('%s名称或编号不能与已停用的名称或编号重复',16,1,@typeName)--return -101
	END
	
--已关请购单
if exists(select btypeid from RequestBill  where bTypeID=@parid)
	BEGIN
		   -- PRINT '2555555555'
		SET @ErrMsg = '该'+ @typeName +'【'+ @parFullName +'】已关联请购单，不能分类'
		RETURN -1   
		--RAISERROR('该%s【%s】已关联请购单，不能分类',16,1,@typeName,@parFullName)return--return -518
	end
--已关pos
if exists(select btypeid from CommonPosInfo  where bTypeID=@parid)
   OR exists(select btypeid from CommonPosSaleIndex  where bTypeID=@parid)
	BEGIN	
	   -- PRINT '2555555555'
	    SET @ErrMsg = '该'+ @typeName +'【'+ @parFullName +'】已关联pos，不能分类'
		RETURN -1   
		--RAISERROR('该%s【%s】已关联pos，不能分类',16,1,@typeName,@parFullName)return--return -518
	END
--已关联会员卡
		if exists(select btypeid from nvipcardsign where bTypeID=@parid)
		BEGIN
			SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联会员卡，不能分类'
			RETURN -1
			--RAISERROR('该%s【%s】已关联会员卡，不能分类',16,1,@typeName,@parFullName)return--return -516
		end	

if @ifqp='1'
	begin
		--已关联维修车辆
		if exists(select btypeid from qp_repairautoinfo where bTypeID=@parid)
		BEGIN
			SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联维修车辆，不能分类'
			RETURN -1
			--RAISERROR('该%s【%s】已关联维修车辆，不能分类',16,1,@typeName,@parFullName)return--return -517
		end
		--已关配件档案
		if exists(select btypeid from QP_PType_Ext  where bTypeID=@parid)
		BEGIN
			SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联配件档案，不能分类'
			RETURN -1
			--RAISERROR('该%s【%s】已关联配件档案，不能分类',16,1,@typeName,@parFullName)return--return -518
		end
	end
DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

DECLARE @Ar00Temp  NUMERIC(24, 10) 
DECLARE @Ap00Temp  NUMERIC(24, 10) 
SET @Ar00Temp =0
SET @Ap00Temp =0

IF @Artotal00<>0 AND @Aptotal00<>0  -- 期初不应者都有
	RETURN 201
--IF EXISTS(select Value from userconfig where configName='Btypeall' AND Value='1')  -- 客户，供货商统一
	BEGIN
		IF LEFT(@EtypeId_1,5) ='00001' -- 客户
			BEGIN
				IF @Artotal00 >0 
					BEGIN
						SET @Ar00Temp = @Artotal00
						SET @Ap00Temp = 0
					END
				IF @Artotal00 <0 
					BEGIN
						SET @Ar00Temp = 0
						SET @Ap00Temp = abs(@Artotal00)
					END		
			END 
		ELSE  -- 供货商
			BEGIN
				IF @Aptotal00 >0 
					BEGIN
						SET @Ar00Temp = 0
						SET @Ap00Temp = @Aptotal00
					END
				IF @Aptotal00 <0 
					BEGIN
						SET @Ar00Temp = abs(@Aptotal00)
						SET @Ap00Temp = 0
					END	
			END
	END


begin tran insertproc
select @leveal=leveal from btype where typeid=@Parid
select @leveal=@leveal+1

IF EXISTS (select * from sysdata where subName='inicanmodify' AND subValue='T') AND @Artotal00<>-9123456789 AND @Aptotal00<>-9123456789-- 未开帐

INSERT INTO [btype] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [USERCODE],
  [Area],
  [TelAndAddress],
  [PostCode],
  [Name],
  [Person],
  [TaxNumber],
  [BankAndAcount],
  [ARTotal00],
  [APTotal00],
  [Comment],
  [Client],
  [ARLimit],
  [ARLimitTime],
  [PaymentLTime],
  [Tel1],
  [Tel2],
  [Tel3],
  [WWW],
  [Email],
  [Fax],
  [Bank],
  [BankName],
[LinkMan1],
[LinkSex1],
[LinkBirthDay1],
[LinkJob1],
[LinkCall1],
[LinkTel1],
[LinkMobile1],
[LinkEMail1],
[LinkPost1],
[LinkAddress1],
[LinkComment1],
[LinkMan2],
[LinkSex2],
[LinkBirthDay2],
[LinkJob2],
[LinkCall2],
[LinkTel2],
[LinkMobile2],
[LinkEMail2],
[LinkPost2],
[LinkAddress2],
[LinkComment2],
[CreateDate],
[SaleZeKou],
[BuyZeKou],
[PyCode],
[Price],
[buyprice],
[AreaTypeID],
[etypeid],
[consignee],
[consigneetel],
[consigneeaddress]

) 
 
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Area,
  @TelAndAddress,
  @PostCode,
  @Name,
  @Person,
  @TaxNumber,
  @bankandacount,
  @Ar00Temp,
  @Ap00Temp,
  @Comment,
  @Client,
  @ARLimit,
  @ARLimitTime,
  @PaymentLTime,
 @Tel1,
 @Tel2,
 @Tel3,
 @WWW,
 @Email,
 @Fax,
 @Bank,
 @BankName,
@LinkMan1,
@LinkSex1,
@LinkBirthDay1,
@LinkJob1,
@LinkCall1,
@LinkTel1,
@LinkMobile1,
@LinkEMail1,
@LinkPost1,
@LinkAddress1,
@LinkComment1,
@LinkMan2,
@LinkSex2,
@LinkBirthDay2,
@LinkJob2,
@LinkCall2,
@LinkTel2,
@LinkMobile2,
@LinkEMail2,
@LinkPost2,
@LinkAddress2,
@LinkComment2,
@CreateDate,
@SaleZeKou,
@BuyZeKou,
@returnPym,
@Price,
@buyprice,
@AreaTypeID,
@etypeid,
@consignee,
@consigneetel,
@consigneeaddress
)
ELSE -- 已开帐
INSERT INTO [btype] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [USERCODE],
  [Area],
  [TelAndAddress],
  [PostCode],
  [Name],
  [Person],
  [TaxNumber],
  [BankAndAcount],
--  [ARTotal00],
--- [APTotal00],
  [Comment],
  [Client],
  [ARLimit],
  [ARLimitTime],
  [PaymentLTime],
  [Tel1],
  [Tel2],
  [Tel3],
  [WWW],
  [Email],
  [Fax],
  [Bank],
  [BankName],
[LinkMan1],
[LinkSex1],
[LinkBirthDay1],
[LinkJob1],
[LinkCall1],
[LinkTel1],
[LinkMobile1],
[LinkEMail1],
[LinkPost1],
[LinkAddress1],
[LinkComment1],
[LinkMan2],
[LinkSex2],
[LinkBirthDay2],
[LinkJob2],
[LinkCall2],
[LinkTel2],
[LinkMobile2],
[LinkEMail2],
[LinkPost2],
[LinkAddress2],
[LinkComment2],
[CreateDate],
[SaleZeKou],

[BuyZeKou],
[PyCode],
[Price],
buyprice,
[AreaTypeID],
[etypeid],
[consignee],
[consigneetel],
[consigneeaddress]

) 
 
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Area,
  @TelAndAddress,
  @PostCode,
  @Name,
  @Person,
  @TaxNumber,
  @bankandacount,
--  @Ar00Temp,
--  @Ap00Temp,
  @Comment,
  @Client,
  @ARLimit,
  @ARLimitTime,
  @PaymentLTime,
 @Tel1,
 @Tel2,
 @Tel3,
 @WWW,
 @Email,
 @Fax,
 @Bank,
 @BankName,
@LinkMan1,
@LinkSex1,
@LinkBirthDay1,
@LinkJob1,
@LinkCall1,
@LinkTel1,
@LinkMobile1,
@LinkEMail1,
@LinkPost1,
@LinkAddress1,
@LinkComment1,
@LinkMan2,
@LinkSex2,
@LinkBirthDay2,
@LinkJob2,
@LinkCall2,
@LinkTel2,
@LinkMobile2,
@LinkEMail2,
@LinkPost2,
@LinkAddress2,
@LinkComment2,
@CreateDate,
@SaleZeKou,
@BuyZeKou,
@returnPym,
@Price,
@buyprice,
@AreaTypeID,
@etypeid,
@consignee,
@consigneetel,
@consigneeaddress

)

if @@rowcount=0 
	begin
	 rollback tran insertproc 
	 SET @ErrMsg = '客户和供货商档案不能超过9层'
	 RETURN -1
	 --return RAISERROR('客户和供货商档案不能超过9层',16,1)--return-1
	end 
else 
	begin
	--客户关联了信用额度管理，则该客户可以被分类和删除，同时信用额度中该客户的信用额度记录删除了
	IF EXISTS(select btypeid from btype_credit where BtypeId=@Parid) 	
		BEGIN 
			Delete from btype_credit where BtypeId=@Parid 
		END
	 update [btype]
	 set sonnum=@nSonnum+1,soncount=@nSoncount+1
	 where typeid=@Parid
	end

----客户关联了信用额度管理，则该客户可以被分类和删除，同时信用额度中该客户的信用额度记录删除了
--IF EXISTS(select btypeid from btype_credit where BtypeId=@Parid) 	
--	BEGIN 
--		--RAISERROR('该%s【%s】已关联信用额度，不能分类',16,1,@typeName,@parFullName)RETURN
--		Delete from btype_credit where BtypeId=@Parid 
--	END
-- 建立Employee数据 .超级用户的节点 --
--select @UserCode=@UserCode+'_超级用户'
--exec @nReturnType=Gp_InsertE '00000','employee',@UserCode,'超级用户','','','','',@EtypeId_1
if @ifStype=0
begin
--插入信用额度表
	IF(@ARLimit IS NOT NULL)
	BEGIN
		if exists(select 1 from btype_credit where StypeId='00001' and BtypeId=@EtypeId_1)
			update btype_credit set Credit=@ARLimit where StypeId='00001' and BtypeId=@EtypeId_1
		else 
			insert into btype_credit(BtypeId,StypeId,Credit) values(@EtypeId_1,'00001',@ARLimit)
	END
end

if (@nReturnType <> 0)
begin 
 rollback tran insertproc 
 return @nReturnType 
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM BType
UPDATE BType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

commit tran insertproc




SET  @ReturnID = @@ROWCOUNT
































GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE         PROCEDURE GP_ImportBill
(
	@UserCode		varchar(500) = '',
	@FullName		varchar(500) = '',
    @qty             NUMERIC(24, 10) =0,
    @OperatorID		varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON	-- 返回结果不受影响
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------	权限检查 - End		--------

-----------------------定义全局表结构-------------------
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[tempPtype]') AND type in (N'U'))
BEGIN
    CREATE TABLE tempPtype(
        typeid nvarchar(50) not null,
        qty  NUMERIC(24, 10)  not null,
        OperatorID varchar(50)
    )
END
------写入数据并检测权限-----
INSERT INTO tempPtype(typeid,qty,OperatorID)
SELECT w.typeid,@qty,@OperatorID FROM F_GetManDetailPtype(@OperatorID) W INNER JOIN ptype  P ON W.typeid=P.typeid 
Where (p.UserCode = @UserCode OR p.FullName =@FullName)  and  deleted=0 and sonnum=0


----------------------取出需要的数据--------------------------
IF(ISNULL(@UserCode,'')='' AND ISNULL(@FullName,'')='' AND @qty=0 AND @OperatorID!='')
BEGIN
    SELECT p.*,w.qty,'' as ktypeid FROM tempPtype W INNER JOIN ptype P  ON W.typeid=P.typeid  Where OperatorID=@OperatorID
    delete tempPtype  Where OperatorID=@OperatorID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012-09-21
	描述：导入分支机构单据往来科目
*/
CREATE PROCEDURE GP_ImportBillAtype
(
	@OperatorId		VARCHAR(50),		-- 当前操作员ID
	@Data	TbType_BillAtype READONLY,
	@Template VARCHAR(100),
	@errmsg		VARCHAR(1000)	OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

--判断会计科目模板是否使用
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account_Set_List WHERE IsUse = 1)
BEGIN
	SET @errmsg = '未启用任何科目表！'
	RETURN -1
END

DECLARE @templatename VARCHAR(100)
IF @Template = 'GP_ImportBillAtype1'
	SET @templatename = '企业会计制度科目'
ELSE IF @Template = 'GP_ImportBillAtype2'
	SET @templatename = '小企业会计准则科目'
ELSE IF @Template = 'GP_ImportBillAtype3'
	SET @templatename = '新会计准则科目'
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account_Set_List WHERE IsUse = 1 AND FullName = @templatename)
BEGIN
	SET @errmsg = '模板与系统会计科目不匹配！'
	RETURN -1
END

DECLARE @SfullName	VARCHAR(200),	--分支机构名称
		@BillName	VARCHAR(100),	--结转科目项、存货科目项或单据名称
		@UserCode	VARCHAR(100),	--科目编号
		@FullName	VARCHAR(200),	--科目名称
		
		@stypeid	VARCHAR(50),
		@atypeid	VARCHAR(50),
		@billtype	VARCHAR(50),
		@item		VARCHAR(50)
		
BEGIN TRAN Import_Tran--开始事务

DECLARE @Index INT,@Version INT
SET @Index = 1

SELECT @Version = SubValue FROM dbo.sysdata WHERE SubName = 'ProInfo'

DECLARE BillCur CURSOR READ_ONLY FOR 
		SELECT	SfullName,
				BillName,
				UserCode,
				FullName
		FROM @Data

OPEN BillCur

FETCH NEXT FROM BillCur INTO @SfullName,
							@BillName	,	
							@UserCode	,	
							@FullName	
										
WHILE (@@FETCH_STATUS = 0)
BEGIN
	SET @item = ''
	SET @billtype = ''
	
	IF @Index = 1 AND ISNULL(@SfullName,'')=''
	BEGIN
		ROLLBACK TRAN Import_Tran
		SET @errmsg = '未填写分支机构，无法导入！';
		RETURN -1
	END
	IF @Index = 1 AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE FullName = @SfullName)
	BEGIN
		ROLLBACK TRAN Import_Tran
		SET @errmsg = '第一行分支机构名称错误，无法导入！';
		RETURN -1
	END
	IF @Index = 1 AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE FullName = @SfullName AND IsSelfVerify = 1)
	BEGIN
		ROLLBACK TRAN Import_Tran
		SET @errmsg = '分支机构【'+@SfullName+'】非独立核算，无法导入！'
		RETURN -1
	END
	
	IF @Index = 1
		SELECT @stypeid = TypeId FROM dbo.SType WHERE FullName = @SfullName

	IF NOT EXISTS(SELECT * FROM dbo.BillName WHERE BillName LIKE N'' + @BillName + N'%') 
		AND @BillName NOT IN ('本年利润科目','利润分配科目','汇兑损益科目','存货科目','费用单（供货商）','费用单（客户）')
	BEGIN
		ROLLBACK TRAN Import_Tran
		SET @errmsg = '第【'+CAST(@index AS VARCHAR(10))+'】行,【'+@BillName+'】不存在，无法导入！'
		RETURN -1
	END
	
	SELECT @atypeid = TypeId FROM dbo.Ac_Account WHERE StypeId = @stypeid AND UserCode = @UserCode
	IF ISNULL(@atypeid,'') = ''
	BEGIN
		ROLLBACK TRAN Import_Tran
		SET @errmsg = '第【'+CAST(@index AS VARCHAR(10))+'】行,不存在编号【'+@UserCode+'】的会计科目，导入失败！';
		RETURN -1
	END
	IF @UserCode = ''
	BEGIN
		ROLLBACK TRAN Import_Tran
		SET @errmsg = '第【'+CAST(@index AS VARCHAR(10))+'】行,会计科目编号为空，导入失败！';
		RETURN -1
	END
	
	IF @BillName = '本年利润科目'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE ATypeID <> '' AND TypeId = @stypeid)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@index AS VARCHAR(10))+'】行,已设置“本年利润科目”，无法导入！'
			RETURN -1
		END
		ELSE
			SET @item = 'atypeid'
	END
	ELSE IF @BillName = '利润分配科目'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE ATypeID2 <> '' AND TypeId = @stypeid)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@index AS VARCHAR(10))+'】行,已设置“利润分配科目”，无法导入！'
			RETURN -1
		END
		SET @item = 'atypeid2'
	END
	ELSE IF @BillName = '汇兑损益科目'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE ATypeID3 <> '' AND TypeId = @stypeid)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@index AS VARCHAR(10))+'】行,已设置“汇总损益科目”，无法导入！'
			RETURN -1
		END
		SET @item = 'atypeid3'
	END
	ELSE IF @BillName = '存货科目'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE ATypeID4 <> '' AND TypeId = @stypeid)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@index AS VARCHAR(10))+'】行,已设置“存货科目”，无法导入！'
			RETURN -1
		END
		SET @item = 'atypeid4'
	END
	ELSE IF @BillName = '费用单（供货商）'
		SET @billtype = '36_server'
	ELSE IF @BillName = '费用单（客户）'
		SET @billtype = '36_client'
	ELSE
		SELECT @billtype = Billtype FROM dbo.BillName WHERE BillName LIKE N'' + @BillName + N'%'
	
	IF @item <> ''
	BEGIN
		DECLARE @sql VARCHAR(MAX)
		SET @sql = 'UPDATE dbo.SType SET '+@item +'= '''+@atypeid+''' WHERE TypeId = '''+@stypeid + ''''
		EXEC (@sql)
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillAtype WHERE BillTypeId = @billtype AND StypeId = @stypeid  AND ISNULL(AtypeId,'') <> '')
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@index AS VARCHAR(10))+'】行,已设置“'+@BillName+'”对应科目，无法导入！'
			RETURN -1
		END
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.BillAtype WHERE BillTypeId = @billtype AND StypeId = @stypeid)
		BEGIN
			INSERT INTO dbo.BillAtype( BillTypeId, AtypeId, StypeId )
			VALUES  (@BillType,@atypeid,@stypeid)
		END
		ELSE
		BEGIN
			UPDATE dbo.BillAtype SET AtypeId = @atypeid WHERE BillTypeId = @billtype AND StypeId = @stypeid
		END
		
	END
	
	SET @Index += 1
	SET @UserCode = ''
	
	FETCH NEXT FROM BillCur INTO @SfullName,
							@BillName	,	
							@UserCode	,	
							@FullName		
END

COMMIT TRAN Import_Tran

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013-05-16
	描述：导入分支机构单据往来科目
*/
CREATE PROCEDURE GP_ImportBillAtypeInner
(
	@OperatorId		VARCHAR(50),		-- 当前操作员ID
	@StypeId		VARCHAR(50),
	@SubId			INT
)
--@encode$--
AS
SET NOCOUNT ON


IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId = @StypeId AND IsSelfVerify = 1)
BEGIN
	RAISERROR('分支机构非独立核算，无法导入往来科目设置！',16,1)
	RETURN -1
END

DECLARE @BillName	VARCHAR(100),	--结转科目项、存货科目项或单据名称
		@UserCode	VARCHAR(100),	--科目编号
		@FullName	VARCHAR(200),	--科目名称
		
		@atypeid	VARCHAR(50),
		@billtype	VARCHAR(50),
		@item		VARCHAR(50)
		

--异常信息
CREATE TABLE #ErrorMsg
(
	msg VARCHAR(MAX)
)

DECLARE @Index INT,@Version INT
SET @Index = 1

SELECT @Version = SubValue FROM dbo.sysdata WHERE SubName = 'ProInfo'

DECLARE BillCur CURSOR READ_ONLY FOR 
		SELECT	BTypeName,
				 CASE WHEN UserCode<>'' 
				 THEN  dbo.F_GetNewUserCode(UserCode,dbo.F_GetDefaultLeveal(UserCode)) 
				 ELSE UserCode 
				 END UserCode,
				FullName
		FROM BATypeIdPreset WHERE SubId = @SubId

OPEN BillCur

FETCH NEXT FROM BillCur INTO 
							@BillName	,	
							@UserCode	,	
							@FullName	
										
WHILE (@@FETCH_STATUS = 0)
BEGIN
	SET @item = ''
	SET @billtype = ''
	
	IF @BillName IN('组合品销售出库单','组合品销售退货单') AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SUBNAME ='combinationproduct' AND SUBVALUE = 0)
	BEGIN
		GOTO Again
	END
	
	IF @BillName IN('运输配送单') AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SUBNAME ='usetransport' AND SUBVALUE = 0)
	BEGIN
		GOTO Again
	END

	IF NOT EXISTS(SELECT * FROM dbo.BillName WHERE BillName LIKE N'' + @BillName + N'%') 
		AND @BillName NOT IN ('本年利润科目','利润分配科目','汇兑损益科目','存货科目','费用单（供货商）','费用单（客户）','采购暂估开票（借）','采购暂估开票（贷）','发出商品开票','成本调价单（入库）')
	BEGIN
		INSERT INTO #ErrorMsg
		SELECT '【'+@BillName+'】不存在'
		GOTO Again
	END
	
	SET @atypeid = ''
	SELECT @atypeid = TypeId FROM dbo.Ac_Account WHERE StypeId = @stypeid AND UserCode = @UserCode
	IF ISNULL(@atypeid,'') = ''
	BEGIN
		INSERT INTO #ErrorMsg
		SELECT '【'+@BillName+'】导入失败,不存在编号【'+@UserCode+'】的会计科目，导入失败！';
		GOTO Again
	END
	IF @UserCode = ''
	BEGIN
		INSERT INTO #ErrorMsg
		SELECT '【'+@BillName+'】导入失败,会计科目编号为空，导入失败！';
		GOTO Again
	END
	IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @stypeid AND TypeId = @atypeid AND SonNum > 0)
	BEGIN
		INSERT INTO #ErrorMsg
		SELECT '科目【'+ @FullName + '】不是子科目，无法使用'
		GOTO Again
	END
	
	IF @BillName = '本年利润科目'
	BEGIN
		SET @item = 'atypeid'
	END
	ELSE IF @BillName = '利润分配科目'
	BEGIN
		SET @item = 'atypeid2'
	END
	ELSE IF @BillName = '汇兑损益科目'
	BEGIN
		SET @item = 'atypeid3'
	END
	ELSE IF @BillName = '存货科目'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE ATypeID4 <> '' AND TypeId = @stypeid)
		BEGIN
			UPDATE dbo.SType SET AtypeId4=@atypeid WHERE TypeId = @StypeId
		END
		SET @item = 'atypeid4'
	END
	ELSE IF @BillName = '费用单（供货商）'
		SET @billtype = '36_server'
	ELSE IF @BillName = '费用单（客户）'
		SET @billtype = '36_client'
	ELSE IF @BillName='采购暂估开票（借）'
		SET @billtype='404_jie'
	ELSE IF @BillName='采购暂估开票（贷）'
		SET @billtype='404_dai'
	ELSE IF @BillName='发出商品开票'
		SET @billtype='405'
	ELSE IF @BillName='成本调价单（入库）'
		SET @billtype='57'
	SELECT @billtype = Billtype FROM dbo.BillName WHERE BillName LIKE N'' + @BillName + N'%'
	
	IF @item <> ''
	BEGIN
		DECLARE @sql VARCHAR(MAX)
		SET @sql = 'UPDATE dbo.SType SET '+@item +'= '''+@atypeid+''' WHERE TypeId = '''+@stypeid + ''''
		EXEC (@sql)
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.BillAtype WHERE BillTypeId = @billtype AND StypeId = @stypeid)
		BEGIN
			INSERT INTO dbo.BillAtype( BillTypeId, AtypeId, StypeId )
			VALUES  (@BillType,@atypeid,@stypeid)
		END
		ELSE
		BEGIN
			UPDATE dbo.BillAtype SET AtypeId = @atypeid WHERE BillTypeId = @billtype AND StypeId = @stypeid
		END
		
	END
	
	SET @Index += 1
	SET @UserCode = ''
	
	Again:
	FETCH NEXT FROM BillCur INTO
							@BillName	,	
							@UserCode	,	
							@FullName		
END

CLOSE  BillCur
DEALLOCATE BillCur

SELECT * FROM #ErrorMsg
DROP TABLE #ErrorMsg

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportBtype]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_ImportBtype]
GO


/****** Object:  StoredProcedure [dbo].[Gp_ImportB]    Script Date: 05/20/2011 17:29:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
/*
	Create by ：	Haiyang Li
	Date：				2012-07-31
	Description:  往来单位基本信息导入基本信息导入, 原有基础上增加结算单位
	2013-12-18 周华 添加父类验证是为结算单位
*/
CREATE PROCEDURE [dbo].[Gp_ImportBtype]
    (
	  @BUserCode varchar(66) ,
      @BFullName VARCHAR(66) ,
      @UserCode VARCHAR(200) ,
      @FullName VARCHAR(200) ,
      @IsCarrier VARCHAR(10) ,
      @PyCode VARCHAR(201) ,
      @StrCreateDate VARCHAR(200) ,
      @AFullName VARCHAR(66) ,
      --@consignee VARCHAR(100) ,	--收货人
     -- @consigneetel VARCHAR(100) ,	--收货人电话
    --  @consigneeaddress VARCHAR(500) ,	--到货地址
      @EFullName VARCHAR(66) , --职员
      @StopDate VARCHAR(200) ,
      @StrARLimitTime VARCHAR(25) ,
      @StrPaymentLTime VARCHAR(25) ,
      @ltsaleoutsday VARCHAR(200) ,
      @ltbuyinsday VARCHAR(200) ,
      @ltsaleorderday VARCHAR(200) ,
      @ltbuyorderday VARCHAR(200) ,
      @Isusebrandar varchar(50), --是否启用品牌应收
      @ltsalertday VARCHAR(200) ,
      @ltbuyrtday VARCHAR(200) ,
      @Strbuyprice VARCHAR(200) ,
      @StrSaleZeKou VARCHAR(25) ,
      @StrBuyZeKou VARCHAR(25) ,
      @StrPrice VARCHAR(200) ,
      @Tel1 VARCHAR(50) ,
      @Tel2 VARCHAR(50) ,
      @Tel3 VARCHAR(50) ,
      @Fax VARCHAR(50) ,
      @Email VARCHAR(50) ,
      @WWW VARCHAR(50) ,
      @PostCode VARCHAR(201) ,
      @TelAndAddress VARCHAR(257) ,
      @bankandacount VARCHAR(66) ,
      @Bank VARCHAR(50) ,
      @BankName VARCHAR(50) ,
      @TaxNumber VARCHAR(20) ,
      @Comment VARCHAR(257) ,
      @LinkMan1 VARCHAR(50) ,
      @StrLinkSex1 VARCHAR(10) ,
      @StrLinkBirthDay1 VARCHAR(200) ,
      @LinkJob1 VARCHAR(50) ,
      @LinkCall1 VARCHAR(50) ,
      @LinkEMail1 VARCHAR(50) ,
      @LinkTel1 VARCHAR(50) ,
      @LinkMobile1 VARCHAR(50) ,
      @LinkPost1 VARCHAR(50) ,
      @LinkAddress1 VARCHAR(50) ,
      @LinkComment1 VARCHAR(257) ,
      @LinkMan2 VARCHAR(50) ,
      @StrLinkSex2 VARCHAR(10) ,
      @StrLinkBirthDay2 VARCHAR(200) ,
      @LinkJob2 VARCHAR(50) ,
      @LinkCall2 VARCHAR(50) ,
      @LinkEMail2 VARCHAR(50) ,
      @LinkTel2 VARCHAR(50) ,
      @LinkMobile2 VARCHAR(50) ,
      @LinkPost2 VARCHAR(50) ,
      @LinkAddress2 VARCHAR(50) ,
      @LinkComment2 VARCHAR(257) ,
      @DenominatedFullName VARCHAR(66) ,  --结算单位名称
      @DenominatedUserCode VARCHAR(66) ,  --结算单位编号
      @ErrMsg VARCHAR(200) OUTPUT,
      @sheng		VARCHAR(100) = '',		--省
      @shi			VARCHAR(100) = '',		--市
      @xian			VARCHAR(100) = ''		--县
    )
--@encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
 /*
    IF ( ( SELECT   DATALENGTH(@PyCode)
         ) > 200 ) 
        BEGIN
            SET @ErrMsg = '拼音码的长度大于最大允许长度200'
            RETURN -1
        END

    IF ( ( SELECT   DATALENGTH(@PostCode)
         ) > 200 ) 
        BEGIN
            SET @ErrMsg = '邮编的长度大于最大允许长度200'
            RETURN -1
        END

    IF ( ( SELECT   DATALENGTH(@TelAndAddress)
         ) > 256 ) 
        BEGIN
            SET @ErrMsg = '地址的长度大于最大允许长度256'
            RETURN -1
        END

    IF ( ( SELECT   DATALENGTH(@Comment)
         ) > 256 ) 
        BEGIN
            SET @ErrMsg = '备注的长度大于最大允许长度256'
            RETURN -1
        END

    IF ( ( SELECT   DATALENGTH(@LinkComment1)
         ) > 256 ) 
        BEGIN
            SET @ErrMsg = '联系人1备注的长度大于最大允许长度256'
            RETURN -1
        END

    IF ( ( SELECT   DATALENGTH(@LinkComment2)
         ) > 256 ) 
        BEGIN
            SET @ErrMsg = '联系人2备注的长度大于最大允许长度256'
            RETURN -1
        END
*/


DECLARE @Parid VARCHAR(50)
IF (@BFullName = '' AND @BUserCode='')
    SET @Parid = '00002'
ELSE
BEGIN
	IF ISNULL(@BUserCode,'')<>''
		BEGIN
		IF NOT EXISTS ( SELECT TOP 1
								typeid
						FROM    dbo.btype
						WHERE  UserCode=@BUserCode )
			OR (@BFullName = 'ABC' AND @BUserCode='abc')
			BEGIN
				SET @ErrMsg = '不存在此名称与编号对应的父类'
				RETURN -1
			END
		ELSE 
			BEGIN
				DECLARE @PBtypeId VARCHAR(50)
				SET @PBtypeId = ( SELECT TOP 1
											typeid
								  FROM      BType
								  WHERE     UserCode=@BUserCode
								)
				IF ( SUBSTRING(@PBtypeId, 1, 5) = '00001' ) 
					BEGIN
						SET @ErrMsg = '不存在此名称与编号对应的父类'
						RETURN -1
					END
				ELSE 
				BEGIN
					IF EXISTS(SELECT 1 FROM (
						SELECT b.denominatedid,b.usercode AS dusercode,b.FullName AS dfullname FROM btype a JOIN btype b ON a.denominatedid=b.typeId AND a.typeid<>a.denominatedid AND a.typeid LIKE '00002%'
					) w  WHERE w.dusercode=@BUserCode AND w.dfullname=@BFullName)
					BEGIN
						SET @ErrMsg='此父类已在结算单位当中使用,不能做为父类';
						RETURN -1
					END
					ELSE
						SET @Parid = @PBtypeId
				END
			END	
	END
END

    IF ( @UserCode = '' ) 
        BEGIN
            SET @ErrMsg = '供货商编号不能为空'
            RETURN -1
        END

    IF ( @FullName = '' ) 
        BEGIN
            SET @ErrMsg = '供货商名称不能为空'
            RETURN -1
        END
        
    DECLARE @IsCarrierInput BIT    
    IF ( @IsCarrier = '')
        BEGIN
            SET @ErrMsg = '必须指定供货商是否为承运商'
            RETURN -1
        END
    ELSE
        BEGIN
          DECLARE @pariscarrier BIT
          SET @pariscarrier = (SELECT TOP 1 iscarrier FROM dbo.btype WHERE typeId = @Parid)
          IF ( @pariscarrier = 1)
			  BEGIN 
				  SET @IsCarrierInput = 1
				  --(991版本，测试说去掉这里的提示)
				  --SET @ErrMsg = '父类为承运商的供货商已指定为承运商'
			  END
	      ELSE
	          BEGIN
	              IF (@IsCarrier<>'是' AND @IsCarrier<>'否')
	                  BEGIN
	                      SET @ErrMsg = '是否承运商只能输入是或否'
	                      RETURN -1
	                  END
	              ELSE IF(@IsCarrier='是')
	                  SET @IsCarrierInput=1
	              ELSE IF(@IsCarrier='否')
	                  SET @IsCarrierInput=0
				-- IF (@pariscarrier = 0 AND @IsCarrierInput = 1 AND @Parid<>'00002')
					--BEGIN
					-- SET @ErrMsg = '父类不是承运商,此供货商不能指定为承运商'
					-- RETURN -1
				--END 
	          END
	    END
        

    IF ( @Pycode = '' ) 
        BEGIN
            SELECT  @Pycode = dbo.fun_getPY(@FullName)
        END

    DECLARE @CreateDate DATETIME
    IF ( @StrCreateDate = '' ) 
        BEGIN
            SELECT  @CreateDate = CONVERT(VARCHAR, GETDATE(), 23)
        END
    ELSE 
        IF ( ISDATE(@StrCreateDate) <> 1 ) 
            BEGIN
                SET @ErrMsg = '建档日期请输入日期,请使用YYYY-MM-DD的格式'
                RETURN -1
            END
        ELSE 
            BEGIN
                SET @CreateDate = @StrCreateDate
            END

    DECLARE @AreaTypeID VARCHAR(50)
    IF ( @AFullName = '' ) 
        BEGIN
            SET @AreaTypeID = ''
        END
    ELSE 
        BEGIN
            IF NOT EXISTS ( SELECT TOP 1
                                    typeid
                            FROM    dbo.AreaType
                            WHERE   fullname = @AFullName )
                OR @AFullName = '所有地区' 
                BEGIN
                    SET @ErrMsg = '地区名称不存在'
                    RETURN -1
                END
            ELSE 
                BEGIN
                    DECLARE @PAtypeId VARCHAR(50)
                    DECLARE @AChildCount NUMERIC(18, 0)
                    SET @PAtypeId = ( SELECT TOP 1
                                                typeid
                                      FROM      dbo.AreaType
                                      WHERE     fullname = @AfullName
                                    )
                    SELECT  @AChildCount = COUNT(*)
                    FROM    dbo.AreaType
                    WHERE   typeId LIKE @PAtypeId + '%'
                            AND typeId <> @PAtypeId
                    IF ( @AChildCount = 0 ) 
                        BEGIN
                            SET @AreaTypeID = @PAtypeId
                        END
                    ELSE 
                        BEGIN
                            SET @ErrMsg = '该地区是父节点'
                            RETURN -1
                        END
                END	
        END

    DECLARE @etypeid VARCHAR(50)
    IF ( @EFullName = '' ) 
        BEGIN
            SET @etypeid = ''
        END
    ELSE 
        BEGIN
            IF NOT EXISTS ( SELECT TOP 1
                                    typeid
                            FROM    dbo.employee
                            WHERE   fullname = @EFullName )
                OR @EFullName = 'root'
                OR @EFullName = '超级用户' 
                BEGIN
                    SET @ErrMsg = '关联职员不存在'
                    RETURN -1
                END
            ELSE 
                BEGIN
                    DECLARE @PEtypeId VARCHAR(50)
                    DECLARE @EChildCount NUMERIC(18, 0)
                    SET @PEtypeId = ( SELECT TOP 1
                                                typeid
                                      FROM      dbo.employee
                                      WHERE     fullname = @EFullName
                                    )
                    SELECT  @EChildCount = COUNT(*)
                    FROM    dbo.employee
                    WHERE   typeId LIKE @PEtypeId + '%'
                            AND typeId <> @PEtypeId
                    IF ( @EChildCount = 0 ) 
                        BEGIN
                            SET @etypeid = @PEtypeId
                        END
                    ELSE 
                        BEGIN
                            SET @ErrMsg = '该职员是父节点'
                            RETURN -1
                        END
                END	
        END
        
    DECLARE @StopDateInput DATETIME    
    IF (@StopDate = '')
		SET @StopDateInput = NULL
	ELSE IF (ISDATE(@StopDate) <> 1)
	BEGIN
		SET @ErrMsg = '停用日期请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	END
	ELSE
		SET @StopDateInput = @StopDate

    DECLARE @ARLimitTime  NUMERIC(24, 10) 
    IF ( @StrARLimitTime = '' ) 
        BEGIN
            SET @ARLimitTime = 9999
        END
    ELSE 
        IF ( ISNUMERIC(@StrARLimitTime) <> 1 ) 
            BEGIN
                SET @ErrMsg = '收款期限请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( ( SELECT   CHARINDEX('.', @StrARLimitTime)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '收款期限请输入整数'
                    RETURN -1
                END
            ELSE 
                IF ( ( SELECT   CHARINDEX('-', @StrARLimitTime)
                     ) <> 0 ) 
                    BEGIN
                        SET @ErrMsg = '收款期限不能为负数'
                        RETURN -1
                    END
                ELSE 
                    BEGIN
                        SELECT  @ARLimitTime = CONVERT( NUMERIC(24, 10) , @StrARLimitTime)
                        IF ( @ARLimitTime <= 0 ) 
                            BEGIN
                                SET @ErrMsg = '收款期限不能为0'
                                RETURN -1
                            END
                        IF ( @ARLimitTime > 9999 ) 
                            BEGIN
                                SET @ErrMsg = '收款期限应小于9999'
                                RETURN -1
                            END
                    END

    DECLARE @PaymentLTime  NUMERIC(24, 10) 
    IF ( @StrPaymentLTime = '' ) 
        BEGIN
            SET @PaymentLTime = 9999
        END
    ELSE 
        IF ( ISNUMERIC(@StrPaymentLTime) <> 1 ) 
            BEGIN
                SET @ErrMsg = '付款期限请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( ( SELECT   CHARINDEX('.', @StrPaymentLTime)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '付款期限请输入整数'
                    RETURN -1
                END
            ELSE 
                IF ( ( SELECT   CHARINDEX('-', @StrPaymentLTime)
                     ) <> 0 ) 
                    BEGIN
                        SET @ErrMsg = '付款期限不能为负数'
                        RETURN -1
                    END
                ELSE 
                    BEGIN
                        SELECT  @PaymentLTime = CONVERT( NUMERIC(24, 10) , @StrPaymentLTime)
                        IF ( @PaymentLTime <= 0 ) 
                            BEGIN
                                SET @ErrMsg = '付款期限不能为0'
                                RETURN -1
                            END
                        IF ( @PaymentLTime > 9999 ) 
                            BEGIN
                                SET @ErrMsg = '付款期限应小于9999'
                                RETURN -1
                            END
                    END
                    
    
    DECLARE @ltsaleoutsdate DATETIME
	DECLARE @ltbuyinsdate DATETIME
	DECLARE @ltsaleorderdate DATETIME
	DECLARE @ltbuyorderdate DATETIME
	DECLARE @ltsalertdate DATETIME
	DECLARE @ltbuyrtdate DATETIME
                  
	IF (@ltsaleoutsday = '')
		SET @ltsaleoutsdate = NULL
	ELSE IF (ISDATE(@ltsaleoutsday) <> 1)
	BEGIN
		SET @ErrMsg = '最近销售出库日期请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	END
	ELSE
		SET @ltsaleoutsdate = @ltsaleoutsday
		
	IF (@ltbuyinsday = '')
		SET @ltbuyinsdate = NULL
	ELSE IF (ISDATE(@ltbuyinsday) <> 1)
	BEGIN
		SET @ErrMsg = '最近采购入库日期请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	END
	ELSE
		SET @ltbuyinsdate = @ltbuyinsday
		
	IF (@ltsaleorderday = '')
		SET @ltsaleorderdate = NULL
	ELSE IF (ISDATE(@ltsaleorderday) <> 1)
	BEGIN
		SET @ErrMsg = '最近销售订货日期请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	END
	ELSE
		SET @ltsaleorderdate = @ltsaleorderday
		
	IF (@ltbuyorderday = '')
		SET @ltbuyorderdate = NULL
	ELSE IF (ISDATE(@ltbuyorderday) <> 1)
	BEGIN
		SET @ErrMsg = '最近采购订货日期请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	END
	ELSE
		SET @ltbuyorderdate = @ltbuyorderday
		
	IF (@ltsalertday = '')
		SET @ltsalertdate = NULL
	ELSE IF (ISDATE(@ltsalertday) <> 1)
	BEGIN
		SET @ErrMsg = '最近销售退货日期请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	END
	ELSE
		SET @ltsalertdate = @ltsalertday
		
	IF (@ltbuyrtday = '')
		SET @ltbuyrtdate = NULL
	ELSE IF (ISDATE(@ltbuyrtday) <> 1)
	BEGIN
		SET @ErrMsg = '最近采购退货日期请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	END
	ELSE
		SET @ltbuyrtdate = @ltbuyrtday
		-- 结算单位存在性验证
	DECLARE @DenominatedId VARCHAR(50)
    IF NOT EXISTS ( SELECT  1
                    FROM    BTYPE
                    WHERE   FullName = @DenominatedFullName AND UserCode=@DenominatedUserCode AND sonnum = 0
                            AND ( typeid LIKE '00002%'
                                  AND EXISTS ( SELECT   1
                                               FROM     dbo.Userconfig
                                               WHERE    ConfigName = 'btypeall'
                                                        AND value = '0' )
                                  OR NOT EXISTS ( SELECT    1
                                                  FROM      dbo.Userconfig
                                                  WHERE     ConfigName = 'btypeall'
                                                            AND value = '0' )
                                ) ) 
        BEGIN
			IF (@DenominatedFullName = '' AND @DenominatedUserCode = '' )
				SET @DenominatedId = '-99999';
            else IF ( @FullName = @DenominatedFullName AND @UserCode=@DenominatedUserCode) 
                SET @DenominatedId = '-99999';
            ELSE 
                BEGIN
                    SET @ErrMsg = '该结算单位是父节点或者结算单位不存在或者不是一个有效的结算单位或者结算单位编号与名称不对应';
                    RETURN -1;
                END
        END
    ELSE 
        SELECT  @DenominatedId = typeid
        FROM    BType
        WHERE   UserCode=@DenominatedUserCode;/*FullName = @DenominatedFullName;*/

		
		
		-- 预设进价
    DECLARE @buyprice VARCHAR(50)
    SELECT  @buyprice = CASE @Strbuyprice
                          WHEN '无' THEN '0'
                          WHEN '' THEN '0'
                          WHEN '预设进价1' THEN '1'
                          WHEN '预设进价2' THEN '2'
                          WHEN '预设进价3' THEN '3'
                          WHEN '预设进价4' THEN '4'
                          WHEN '预设进价5' THEN '5'
                          WHEN '最高进价' THEN '6'
                          WHEN '零售价' THEN '7'
                          ELSE 'ERROR'
                        END
    IF ( @buyprice = 'ERROR' ) 
        BEGIN
            SET @ErrMsg = '适用进价不匹配'
            RETURN -1
        END


	DECLARE 
	@d_discount                VARCHAR(5),   --  扣率小数位数               4
	@d_discount1               INT ;         --  扣率小数位数               4
	                          
	SELECT @d_discount         = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 4
	SET @d_discount1           = CONVERT(INT,@d_discount)

    DECLARE @SaleZeKou  NUMERIC(24, 10) 
    IF ( @StrSaleZeKou = '' ) 
        BEGIN
            SET @SaleZeKou = NULL
        END
    ELSE 
        IF ( ISNUMERIC(@StrSaleZeKou) <> 1 ) 
            BEGIN
                SET @ErrMsg = '销售折扣请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( ( SELECT   CHARINDEX('-', @StrSaleZeKou)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '销售折扣不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
                    SELECT  @SaleZeKou = CONVERT( NUMERIC(24, 10) , @StrSaleZeKou)
                    IF ( @SaleZeKou <= 0
                         OR @SaleZeKou > 1
                       ) 
                        BEGIN
                            SET @ErrMsg = '销售折扣输入错误'
                            RETURN -1
                        END
                    IF dbo.F_CheckDecimal(@StrSaleZeKou,4,@d_discount1) < 0
					BEGIN
						SET @ErrMsg='销售折扣值多于'+@d_discount+'位小数'
						RETURN -1;
					END
                END

    DECLARE @BuyZeKou  NUMERIC(24, 10) 
    IF ( @StrBuyZeKou = '' ) 
        BEGIN
            SET @BuyZeKou = NULL
        END
    ELSE 
        IF ( ISNUMERIC(@StrBuyZeKou) <> 1 ) 
            BEGIN
                SET @ErrMsg = '采购折扣请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( ( SELECT   CHARINDEX('-', @StrBuyZeKou)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '采购折扣不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
                    SELECT  @BuyZeKou = CONVERT( NUMERIC(24, 10) , @StrBuyZeKou)
                    IF ( @BuyZeKou <= 0
                         OR @BuyZeKou > 1
                       ) 
                        BEGIN
                            SET @ErrMsg = '采购折扣输入错误'
                            RETURN -1
                        END
                    IF dbo.F_CheckDecimal(@StrBuyZeKou,4,@d_discount1) < 0
					BEGIN
						SET @ErrMsg='采购折扣值多于'+@d_discount+'位小数'
						RETURN -1;
					END
                END

    DECLARE @Price VARCHAR(50)
    SELECT  @Price = CASE @StrPrice
                       WHEN '无' THEN '0'
                       WHEN '' THEN '0'
                       WHEN '预设售价1' THEN '1'
                       WHEN '预设售价2' THEN '2'
                       WHEN '预设售价3' THEN '3'
                       WHEN '预设售价4' THEN '4'
                       WHEN '预设售价5' THEN '5'
                       WHEN '预设售价6' THEN '6'
                       WHEN '预设售价7' THEN '7'
                       WHEN '预设售价8' THEN '8'
                       WHEN '预设售价9' THEN '9'
                       WHEN '预设售价10' THEN '10'
                       WHEN '零售价' THEN '11'
                       WHEN '最高售价' THEN '12'
                       WHEN '最低售价' THEN '13'
                       ELSE 'ERROR'
                     END
    IF ( @Price = 'ERROR' ) 
        BEGIN
            SET @ErrMsg = '适用售价不匹配'
            RETURN -1
        END

    DECLARE @PostCodeLen INT
    SELECT  @PostCodeLen = LEN(@PostCode)
    IF ( @PostCodeLen > 200 ) 
        BEGIN
            SET @ErrMsg = '邮编不能超过200字符'
            RETURN -1
        END


    DECLARE @LinkSex1 BIT
    SELECT  @StrLinkSex1 = CASE @StrLinkSex1
                             WHEN '' THEN '1'
                             WHEN '男' THEN '1'
                             WHEN '女' THEN '0'
                             ELSE '无'
                           END
    IF ( @StrLinkSex1 = '无' ) 
        BEGIN
            SET @ErrMsg = '性别请输入男或女'
            RETURN -1
        END
    ELSE 
        BEGIN
            SET @LinkSex1 = CONVERT(BIT, @StrLinkSex1)
        END

    DECLARE @LinkBirthDay1 DATETIME
    IF ( @StrLinkBirthDay1 = '' ) 
        BEGIN
            SELECT  @LinkBirthDay1 = '1980-01-01 00:00:00'
        END
    ELSE 
        IF ( ISDATE(@StrLinkBirthDay1) <> 1 ) 
            BEGIN
                SET @ErrMsg = '联系人1生日请输入日期,请使用YYYY-MM-DD的格式'
                RETURN -1
            END
        ELSE 
            BEGIN
                SET @LinkBirthDay1 = @StrLinkBirthDay1
            END

    DECLARE @LinkSex2 BIT
    SELECT  @StrLinkSex2 = CASE @StrLinkSex2
                             WHEN '' THEN '1'
                             WHEN '男' THEN '1'
                             WHEN '女' THEN '0'
                             ELSE '无'
                           END
    IF ( @StrLinkSex2 = '无' ) 
        BEGIN
            SET @ErrMsg = '性别请输入男或女'
            RETURN -1
        END
    ELSE 
        BEGIN
            SET @LinkSex2 = CONVERT(BIT, @StrLinkSex2)
        END

    DECLARE @LinkBirthDay2 DATETIME
    IF ( @StrLinkBirthDay2 = '' ) 
        BEGIN
            SELECT  @LinkBirthDay2 = '1980-01-01 00:00:00'
        END
    ELSE 
        IF ( ISDATE(@StrLinkBirthDay2) <> 1 ) 
            BEGIN
                SET @ErrMsg = '联系人2生日请输入日期,请使用YYYY-MM-DD的格式'
                RETURN -1
            END
        ELSE 
            BEGIN
                SET @LinkBirthDay2 = @StrLinkBirthDay2
            END



    DECLARE @Name [Varchar](30) = ''

    DECLARE @Area [Varchar](30) = ''

    DECLARE @Person [varchar](20) = ''

    DECLARE @Artotal00  NUMERIC(24, 10)  = 0

    DECLARE @Aptotal00  NUMERIC(24, 10)  = 0

    DECLARE @Client BIT = 1

    DECLARE @ARLimit  NUMERIC(24, 10) 

    DECLARE @ifStype INT = 1

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

    DECLARE @nReturntype INT ,
        @EtypeId_1 [varchar](50) ,
        @nSoncount INT ,
        @nSonnum INT ,
        @leveal SMALLINT

--判断是否为汽配
    DECLARE @ifqp VARCHAR(1)
    SET @ifqp = ( SELECT    subvalue
                  FROM      sysdata
                  WHERE     subname = 'ifqp'
                )

    DECLARE @parFullName VARCHAR(200)
    SET @parFullName = ( SELECT TOP 1
                                fullname
                         FROM   btype
                         WHERE  typeid = @parid
                       )
                       
    DECLARE @typeName VARCHAR(20)
    DECLARE @typename1 VARCHAR(20)
	DECLARE @id1 VARCHAR(20)

    IF SUBSTRING(@parid, 1, 5) = '00001'
    begin 
        SET @typeName = '客户'
        SET @typeName1='供货商'
		SET @id1='00002'
    END
    IF SUBSTRING(@parid, 1, 5) = '00002' 
    begin
		set @typeName='供货商'
		SET @typeName1='客户'
		SET @id1='00001'
    end

-- 判断单位的往来
    IF @Parid = '00000' 
        RETURN -11

--判断停用不能分类
    DECLARE @deleted INT
    SELECT  @deleted = deleted
    FROM    btype
    WHERE   typeId = @Parid
    IF ( @deleted = 1 ) 
        BEGIN
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已经被停用，不能分类'
            RETURN -1	
   --RAISERROR('该%s【%s】已经被停用，不能分类',16,1,@typeName,@parFullName)return ---15  
        END
--判断序列号
    IF EXISTS ( SELECT  BTypeID1
                FROM    gp_CruPtypeSerial
                WHERE   BTypeID1 = @Parid ) 
        BEGIN
		--print '住来有序列号，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已有序列号关联情况，不能分类'
            RETURN -1
		 --RAISERROR('该%s【%s】已有序列号关联情况，不能分类',16,1,@typeName,@parFullName)return ---15
        END
    IF EXISTS ( SELECT  BTypeID1
                FROM    gp_initPtypeSerial
                WHERE   BTypeID1 = @Parid ) 
        BEGIN
		--print '往来有期初序列号，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已有期初序列号关联情况，不能分类'
            RETURN -1
		 --RAISERROR('该【%s】已有期初序列号关联情况，不能分类',16,1,@typeName,@parFullName)return --16
        END
	
--判断是否被分支机构使用，若被使用则禁止分类
    IF EXISTS ( SELECT  *
                FROM    SType
                WHERE   BTypeID1 = @Parid
                        OR BTypeID2 = @Parid ) 
        BEGIN
            SET @ErrMsg = '该往来单位已经被分支机构关联，禁止分类'
            RETURN -1					
		--RAISERROR('该往来单位已经被分支机构关联，禁止分类',16,1)
		--RETURN		
        END
--判断序列号
    IF EXISTS ( SELECT  BTypeID2
                FROM    gp_CruPtypeSerial
                WHERE   BTypeID2 = @Parid ) 
        BEGIN
		--print '住来有序列号，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已有序列号关联情况，不能分类'
            RETURN -1	
		 --RAISERROR('该%s【%s】已有序列号关联情况，不能分类',16,1,@typeName,@parFullName)return--return -15
        END
    IF EXISTS ( SELECT  BTypeID2
                FROM    gp_initPtypeSerial
                WHERE   BTypeID2 = @Parid ) 
        BEGIN
		--print '往来有期初序列号，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已有期初序列号关联情况，不能分类'
            RETURN -1	
		 --RAISERROR('该%s【%s】已有期初序列号关联情况，不能分类',16,1,@typeName,@parFullName)return--return -16
        END

    IF EXISTS ( SELECT  typeid
                FROM    [btype]
                WHERE   typeid = @parid
                        AND ARTotal - ApTotal <> 0 ) 
        BEGIN
		--print '['+@FullName+']单位往来帐不为零，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】往来帐不为零，不能分类'
            RETURN -1	
		--RAISERROR('该%s【%s】往来帐不为零，不能分类',16,1,@typeName,@parFullName)return
        END 
    IF EXISTS ( SELECT  typeid
                FROM    [btype]
                WHERE   typeid = @parid
                        AND ARTotal00 - ApTotal00 <> 0 ) 
        BEGIN
		--print '['+@FullName+']单位往来帐不为零，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】往来帐不为零，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】往来帐不为零，不能分类',16,1,@typeName,@parFullName)return--return -7
        END 

--判断应收应付预收预付期初
    IF EXISTS ( SELECT  BTypeID
                FROM    BType_ArApTotal
                WHERE   BTypeID = @parid
                        AND ( ARTotal00 <> 0
                              OR APTotal00 <> 0
                              OR YSTotal00 <> 0
                              OR YFTotal00 <> 0
                            ) ) 
        BEGIN
		--print '['+@FullName+']单位往来帐不为零，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】应收或应付期初中不为零，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】应收或应付期初中不为零，不能分类',16,1,@typeName,@parFullName)return--return -7
        END 

-- 判断借欠余额
    IF EXISTS ( SELECT  bTypeID
                FROM    V_LendStatus
                WHERE   bTypeID = @parid
                        AND Qty <> 0 ) 
        BEGIN
		--print '['+@FullName+']单位有借进借出，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有借进借出，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】有借进借出，不能分类',16,1,@typeName,@parFullName)return--return -5
        END 
-- 判断经营
    IF EXISTS ( SELECT  bTypeID
                FROM    listtable
                WHERE   bTypeID = @parid )
        OR EXISTS ( SELECT  bTypeID
                    FROM    LendIndex
                    WHERE   bTypeID = @parid
                            AND totalQty <> 0 )
        OR EXISTS ( SELECT  bTypeID
                    FROM    BillIndex
                    WHERE   bTypeID = @parid ) 
        BEGIN
		--print '['+@FullName+']单位已经经营过，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已经经营过，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已经经营过，不能分类',16,1,@typeName,@parFullName)return--return -6
        END 
    IF EXISTS ( SELECT  bTypeID
                FROM    OrderIndex
                WHERE   bTypeID = @parid ) 
        BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 订单
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已在订单中使用过，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已在订单中使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -501
        END
    IF EXISTS ( SELECT  bTypeID
                FROM    LendIndex
                WHERE   bTypeID = @parid ) 
        BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 借欠
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已在借欠单种使用过，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已在借欠单种使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -502
        END
    IF EXISTS ( SELECT  bTypeID
                FROM    AdDebtBill
                WHERE   bTypeID = @parid ) 
        BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 借欠
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已在应收应付中使用过，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已在应收应付中使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -502
        END

-- 判断代销情况
    IF EXISTS ( SELECT  bTypeID
                FROM    iniCommissionStock
                WHERE   bTypeID = @parid
                        AND Qty <> 0 )
        OR EXISTS ( SELECT  bTypeID
                    FROM    CommissionStock
                    WHERE   bTypeID = @parid
                            AND Qty <> 0 ) 
        BEGIN
		--print '['+@FullName+']单位有代销情况，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有代销情况，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】有代销情况，不能分类',16,1,@typeName,@parFullName)return--return -13
        END 

-- 判断代销情况
    IF EXISTS ( SELECT  bTypeID
                FROM    iniCommissionStock
                WHERE   bTypeID = @parid
                        AND ( total <> 0
                              OR costtotal <> 0
                            ) )
        OR EXISTS ( SELECT  bTypeID
                    FROM    CommissionStock
                    WHERE   bTypeID = @parid
                            AND ( total <> 0
                                  OR costtotal <> 0
                                ) ) 
        BEGIN
		--print '['+@FullName+']单位有代销情况，不能分类'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有代销情况，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】有代销情况，不能分类',16,1,@typeName,@parFullName)return--return -13
        END 


    IF EXISTS ( SELECT  bTypeID
                FROM    PriceProtect
                WHERE   bTypeID = @parid ) 
        BEGIN
	--print '['+@FullName+']单位有经营历程，不能分类
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有价保通知，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】有价保通知，不能分类',16,1,@typeName,@parFullName)return--RETURN -508
        END

    IF EXISTS ( SELECT  bTypeID
                FROM    FapiaoBillIndex
                WHERE   bTypeID = @parid ) 
        BEGIN
	--print '['+@FullName+']单位有发票，不能分类
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有发票，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】有发票，不能分类',16,1,@typeName,@parFullName)return--RETURN -510
        END

--判断价格跟踪
    IF EXISTS ( SELECT  btypeid
                FROM    PriceTrack
                WHERE   BtypeID = @Parid ) 
        BEGIN
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已关联价格跟踪，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已关联价格跟踪，不能分类',16,1,@typeName,@parFullName)RETURN
        END
--判断信用额度
    IF EXISTS ( SELECT  btypeid
                FROM    BType_Credit
                WHERE   BtypeID = @Parid ) 
        BEGIN
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已有信用额度，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已有信用额度，不能分类',16,1,@typeName,@parFullName)RETURN
        END
--判断在会计凭证中是否关联
    IF EXISTS ( SELECT  ATypeID
                FROM    AccountCredence
                WHERE   ATypeID = @Parid
                        AND TypeATypeID IN ( '0000100009', '0000100005',
                                             '0000200001', '0000200006' ) ) 
        BEGIN
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已关联会计凭证，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已关联会计凭证，不能分类',16,1,@typeName,@parFullName)RETURN
        END
--商品信息关联分支机构，则该分支机构不能被分类
    IF EXISTS ( SELECT  BTypeID
                FROM    QP_PType_Ext
                WHERE   BTypeID = @Parid ) 
        BEGIN 
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联商品，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已关联商品，不能分类',16,1,@typeName,@parFullName)RETURN
        END
--关联维修业务中的保险公司
    IF EXISTS ( SELECT  BTypeID
                FROM    Qp_ReceptionBill_Insurance
                WHERE   BTypeID = @Parid ) 
        BEGIN 
	    --print '25555'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已关联维修业务，不能分类'
            RETURN -1
		--RAISERROR('该%s【%s】已关联维修业务，不能分类',16,1,@typeName,@parFullName)RETURN
        END
-- 获得新的ID号
    DECLARE @DbName VARCHAR(30) = 'btype'
    EXEC @nReturntype= Gp_createId @ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
    IF @nReturntype = -1 
        BEGIN
            SET @ErrMsg = '客户和供货商的分类不能超过9层'
            RETURN -1
		--RAISERROR('客户和供货商的分类不能超过9层',16,1)return-- return -1
        END
    IF @nReturntype = -2 
        BEGIN
            SET @ErrMsg = '无法添加基本信息'
            RETURN -1
		--RAISERROR('无法添加基本信息',16,1)return--return -2
        END
-- 判断重复的ID,UserCode
DECLARE @BameFlag varchar(50)
select @BameFlag=value from Userconfig where ConfigName='equalbidname'

IF @BameFlag<>1
BEGIN
	 IF EXISTS (SELECT TypeID FROM [btype] WHERE typeId =@EtypeId_1 OR (usercode = @usercode AND deleted<>1) OR (fullname=@fullname AND deleted <> 1))
	 BEGIN
		SET @ErrMsg = '该【' + @FullName + '】已经存在，' + @typeName+ '编号或名称不能相同'
            RETURN -1
	 END
END
ELSE
BEGIN
	 IF EXISTS (SELECT TypeID FROM [btype] WHERE typeId = @EtypeId_1 OR (usercode = @usercode AND deleted <> 1) ) 
	 BEGIN
		 SET @ErrMsg = @typeName + '编号不能与已有的编号重复'
            RETURN -1
	 END
END


    IF EXISTS ( SELECT  TypeID
                FROM    [btype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @fullname
                             AND deleted <> 1
                           )
                        /*OR ( fullname = @usercode
                             AND deleted <> 1
                           )*/ ) 
        BEGIN
		--print '['+@usercode+']往来已存在'
            SET @ErrMsg = @typeName + '名称不能与已有的编号重复'
            RETURN -1
		--RAISERROR('%s名称或编号不能与已有的名称或编号重复',16,1,@typeName)return--return -10
        END
        
--名称不能与另一部分(客户名称不能与供货商)名称相同
IF EXISTS(select TypeID from [btype] where typeId=@EtypeId_1 OR (fullname=@fullname AND typeid LIKE @id1+'%' AND deleted<>1))
BEGIN
	SET @ErrMsg=@typename+'名称不能与已有'+@typename1+'名称重复';
	RETURN -1
END


IF @BameFlag<>1
BEGIN
	IF EXISTS (SELECT TypeID FROM [btype] WHERE typeId = @EtypeId_1 OR (usercode = @usercode AND deleted = 1) OR (fullname = @fullname AND deleted = 1)) 
	BEGIN
		 SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @typeName
                + '使用，请更换或删除该停用的编号'
         RETURN -1
	END
END
ELSE
BEGIN
	 IF EXISTS (SELECT TypeID FROM [btype] WHERE   typeId = @EtypeId_1 OR ( usercode = @usercode AND deleted = 1)) 
	 BEGIN
		 SET @ErrMsg = @typeName + '编号不能与已停用的编号重复'
            RETURN -1
	 END
END


---- 判断重复的ID,UserCode
--    IF EXISTS ( SELECT  TypeID
--                FROM    [btype]
--                WHERE   typeId = @EtypeId_1
--                        OR ( usercode = @usercode
--                             AND deleted = 1
--                           )
--                        /*OR ( fullname = @fullname
--                             AND deleted = 1
--                           )*/ ) 
--        BEGIN
--		--print '['+@usercode+']往来已存在'
--            SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @typeName
--                + '使用，请更换或删除该停用的编号'
--            RETURN -1
--		--RAISERROR('该【%s】的编号或名称已被已停用的%s使用，请更换或删除该停用的编号或名称',16,1,@FullName,@typeName)--return -31
--        END

--    IF EXISTS ( SELECT  TypeID
--                FROM    [btype]
--                WHERE   typeId = @EtypeId_1
--                        OR ( usercode = @fullname
--                             AND deleted = 1
--                           )
--                        /*OR ( fullname = @usercode
--                             AND deleted = 1
--                           )*/ ) 
--        BEGIN
--		--print '['+@usercode+']往来已存在'
--            SET @ErrMsg = @typeName + '名称不能与已停用的编号重复'
--            RETURN -1
--		--RAISERROR('%s名称或编号不能与已停用的名称或编号重复',16,1,@typeName)--return -101
--        END
	
--已关请购单
    IF EXISTS ( SELECT  btypeid
                FROM    RequestBill
                WHERE   bTypeID = @parid ) 
        BEGIN
		   -- PRINT '2555555555'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已关联请购单，不能分类'
            RETURN -1   
		--RAISERROR('该%s【%s】已关联请购单，不能分类',16,1,@typeName,@parFullName)return--return -518
        END
--已关pos
    IF EXISTS ( SELECT  btypeid
                FROM    CommonPosInfo
                WHERE   bTypeID = @parid )
        OR EXISTS ( SELECT  btypeid
                    FROM    CommonPosSaleIndex
                    WHERE   bTypeID = @parid ) 
        BEGIN	
	   -- PRINT '2555555555'
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已关联pos，不能分类'
            RETURN -1   
		--RAISERROR('该%s【%s】已关联pos，不能分类',16,1,@typeName,@parFullName)return--return -518
        END
--已关联会员卡
    IF EXISTS ( SELECT  btypeid
                FROM    nvipcardsign
                WHERE   bTypeID = @parid ) 
        BEGIN
            SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                + '】已关联会员卡，不能分类'
            RETURN -1
			--RAISERROR('该%s【%s】已关联会员卡，不能分类',16,1,@typeName,@parFullName)return--return -516
        END	

    IF @ifqp = '1' 
        BEGIN
		--已关联维修车辆
            IF EXISTS ( SELECT  btypeid
                        FROM    qp_repairautoinfo
                        WHERE   bTypeID = @parid ) 
                BEGIN
                    SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                        + '】已关联维修车辆，不能分类'
                    RETURN -1
			--RAISERROR('该%s【%s】已关联维修车辆，不能分类',16,1,@typeName,@parFullName)return--return -517
                END
		--已关配件档案
            IF EXISTS ( SELECT  btypeid
                        FROM    QP_PType_Ext
                        WHERE   bTypeID = @parid ) 
                BEGIN
                    SET @ErrMsg = '该' + @typeName + '【' + @parFullName
                        + '】已关联配件档案，不能分类'
                    RETURN -1
			--RAISERROR('该%s【%s】已关联配件档案，不能分类',16,1,@typeName,@parFullName)return--return -518
                END
        END
    DECLARE @returnPym VARCHAR(1000)
    EXEC @returnPym = fun_getPy @FullName

    IF @PyCode <> '' 
        SET @returnPym = @PyCode

    DECLARE @Ar00Temp  NUMERIC(24, 10) 
    DECLARE @Ap00Temp  NUMERIC(24, 10) 
    SET @Ar00Temp = 0
    SET @Ap00Temp = 0

    IF @Artotal00 <> 0
        AND @Aptotal00 <> 0  -- 期初不应者都有
        RETURN 201
--IF EXISTS(select Value from userconfig where configName='Btypeall' AND Value='1')  -- 客户，供货商统一
    BEGIN
        IF LEFT(@EtypeId_1, 5) = '00001' -- 客户
            BEGIN
                IF @Artotal00 > 0 
                    BEGIN
                        SET @Ar00Temp = @Artotal00
                        SET @Ap00Temp = 0
                    END
                IF @Artotal00 < 0 
                    BEGIN
                        SET @Ar00Temp = 0
                        SET @Ap00Temp = ABS(@Artotal00)
                    END		
            END 
        ELSE  -- 供货商
            BEGIN
                IF @Aptotal00 > 0 
                    BEGIN
                        SET @Ar00Temp = 0
                        SET @Ap00Temp = @Aptotal00
                    END
                IF @Aptotal00 < 0 
                    BEGIN
                        SET @Ar00Temp = ABS(@Aptotal00)
                        SET @Ap00Temp = 0
                    END	
            END
    END
    
DECLARE @IsUseBrandarType INT

--是否启用品牌应收
IF (@Isusebrandar = '启用')
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName ='usebrandartype' and SubValue = 1)
		SET @IsUseBrandarType = 1;
	ELSE 
		SET @IsUseBrandarType = 0;
ELSE IF(@Isusebrandar = '不启用' OR @Isusebrandar = '')
	SET @IsUseBrandarType = 0;
ELSE 
	BEGIN
		SET @ErrMsg = '请选择启用品牌应收值：启用/不启用';
		RETURN -1;
	END



    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    btype
    WHERE   typeid = @Parid
    SELECT  @leveal = @leveal + 1

    IF EXISTS ( SELECT  *
                FROM    sysdata
                WHERE   subName = 'inicanmodify'
                        AND subValue = 'T' )
        AND @Artotal00 <> -9123456789
        AND @Aptotal00 <> -9123456789-- 未开帐
        INSERT  INTO [btype]
		( 
			[typeId] ,
			[Parid] ,
			[leveal] ,
			[soncount] ,
			[sonnum] ,
			[FullName] ,
			[USERCODE] ,
			[Area] ,
			[TelAndAddress] ,
			[PostCode] ,
			[Name] ,
			[Person] ,
			[TaxNumber] ,
			[BankAndAcount] ,
			[ARTotal00] ,
			[APTotal00] ,
			[Comment] ,
			[Client] ,
			[ARLimit] ,
			[ARLimitTime] ,
			[PaymentLTime] ,
			[Tel1] ,
			[Tel2] ,
			[Tel3] ,
			[WWW] ,
			[Email] ,
			[Fax] ,
			[Bank] ,
			[BankName] ,
			[LinkMan1] ,
			[LinkSex1] ,
			[LinkBirthDay1] ,
			[LinkJob1] ,
			[LinkCall1] ,
			[LinkTel1] ,
			[LinkMobile1] ,
			[LinkEMail1] ,
			[LinkPost1] ,
			[LinkAddress1] ,
			[LinkComment1] ,
			[LinkMan2] ,
			[LinkSex2] ,
			[LinkBirthDay2] ,
			[LinkJob2] ,
			[LinkCall2] ,
			[LinkTel2] ,
			[LinkMobile2] ,
			[LinkEMail2] ,
			[LinkPost2] ,
			[LinkAddress2] ,
			[LinkComment2] ,
			[CreateDate] ,
			[SaleZeKou] ,
			[BuyZeKou] ,
			[PyCode] ,
			[Price] ,
			[buyprice] ,
			[AreaTypeID] ,
			[etypeid] ,
			--[consignee] ,
			-- [consigneetel] ,
			--[consigneeaddress], 
			[DenominatedId],
			iscarrier,
			sheng,
			shi,
			xian,
			IsUseBrandarType
			)VALUES( 
			@EtypeId_1 ,
			@Parid ,
			@leveal ,
			0 ,
			0 ,
			@FullName ,
			@UserCode ,
			@Area ,
			@TelAndAddress ,
			@PostCode ,
			@Name ,
			@Person ,
			@TaxNumber ,
			@bankandacount ,
			@Ar00Temp ,
			@Ap00Temp ,
			@Comment ,
			@Client ,
			@ARLimit ,
			@ARLimitTime ,
			@PaymentLTime ,
			@Tel1 ,
			@Tel2 ,
			@Tel3 ,
			@WWW ,
			@Email ,
			@Fax ,
			@Bank ,
			@BankName ,
			@LinkMan1 ,
			@LinkSex1 ,
			@LinkBirthDay1 ,
			@LinkJob1 ,
			@LinkCall1 ,
			@LinkTel1 ,
			@LinkMobile1 ,
			@LinkEMail1 ,
			@LinkPost1 ,
			@LinkAddress1 ,
			@LinkComment1 ,
			@LinkMan2 ,
			@LinkSex2 ,
			@LinkBirthDay2 ,
			@LinkJob2 ,
			@LinkCall2 ,
			@LinkTel2 ,
			@LinkMobile2 ,
			@LinkEMail2 ,
			@LinkPost2 ,
			@LinkAddress2 ,
			@LinkComment2 ,
			@CreateDate ,
			@SaleZeKou ,
			@BuyZeKou ,
			@returnPym ,
			@Price ,
			@buyprice ,
			@AreaTypeID ,
			@etypeid ,
			--@consignee ,
			-- @consigneetel ,
			--@consigneeaddress ,
			CASE WHEN @DenominatedId = '-99999' THEN @EtypeId_1 ELSE @DenominatedId END,
			@IsCarrierInput,
			@sheng,
			@shi,
			@xian,
			@IsUseBrandarType
                )
    ELSE -- 已开帐
        INSERT  INTO [btype]
                ( [typeId] ,
                  [Parid] ,
                  [leveal] ,
                  [soncount] ,
                  [sonnum] ,
                  [FullName] ,
                  [USERCODE] ,
                  [Area] ,
                  [TelAndAddress] ,
                  [PostCode] ,
                  [Name] ,
                  [Person] ,
                  [TaxNumber] ,
                  [BankAndAcount] ,
--  [ARTotal00],
--- [APTotal00],
                  [Comment] ,
                  [Client] ,
                  [ARLimit] ,
                  [ARLimitTime] ,
                  [PaymentLTime] ,
                  [Tel1] ,
                  [Tel2] ,
                  [Tel3] ,
                  [WWW] ,
                  [Email] ,
                  [Fax] ,
                  [Bank] ,
                  [BankName] ,
                  [LinkMan1] ,
                  [LinkSex1] ,
                  [LinkBirthDay1] ,
                  [LinkJob1] ,
                  [LinkCall1] ,
                  [LinkTel1] ,
                  [LinkMobile1] ,
                  [LinkEMail1] ,
                  [LinkPost1] ,
                  [LinkAddress1] ,
                  [LinkComment1] ,
                  [LinkMan2] ,
                  [LinkSex2] ,
                  [LinkBirthDay2] ,
                  [LinkJob2] ,
                  [LinkCall2] ,
                  [LinkTel2] ,
                  [LinkMobile2] ,
                  [LinkEMail2] ,
                  [LinkPost2] ,
                  [LinkAddress2] ,
                  [LinkComment2] ,
                  [CreateDate] ,
                  [SaleZeKou] ,
                  [BuyZeKou] ,
                  [PyCode] ,
                  [Price] ,
                  buyprice ,
                  [AreaTypeID] ,
                  [etypeid] ,
                  --[consignee] ,
                  --[consigneetel] ,
                  --[consigneeaddress] ,
                  DenominatedId ,
                  stopdate,
                  ltsaleoutsday,
                  ltbuyinsday,
                  ltsaleorderday,
                  ltbuyorderday,
                  ltsalertday,
                  ltbuyrtday,
                  iscarrier,
				  sheng,
				  shi,
				  xian,
				  IsUseBrandarType
                )
        VALUES  ( @EtypeId_1 ,
                  @Parid ,
                  @leveal ,
                  0 ,
                  0 ,
                  @FullName ,
                  @UserCode ,
                  @Area ,
                  @TelAndAddress ,
                  @PostCode ,
                  @Name ,
                  @Person ,
                  @TaxNumber ,
                  @bankandacount ,
--  @Ar00Temp,
--  @Ap00Temp,
                  @Comment ,
                  @Client ,
                  @ARLimit ,
                  @ARLimitTime ,
                  @PaymentLTime ,
                  @Tel1 ,
                  @Tel2 ,
                  @Tel3 ,
                  @WWW ,
                  @Email ,
                  @Fax ,
                  @Bank ,
                  @BankName ,
                  @LinkMan1 ,
                  @LinkSex1 ,
                  @LinkBirthDay1 ,
                  @LinkJob1 ,
                  @LinkCall1 ,
                  @LinkTel1 ,
                  @LinkMobile1 ,
                  @LinkEMail1 ,
                  @LinkPost1 ,
                  @LinkAddress1 ,
                  @LinkComment1 ,
                  @LinkMan2 ,
                  @LinkSex2 ,
                  @LinkBirthDay2 ,
                  @LinkJob2 ,
                  @LinkCall2 ,
                  @LinkTel2 ,
                  @LinkMobile2 ,
                  @LinkEMail2 ,
                  @LinkPost2 ,
                  @LinkAddress2 ,
                  @LinkComment2 ,
                  @CreateDate ,
                  @SaleZeKou ,
                  @BuyZeKou ,
                  @returnPym ,
                  @Price ,
                  @buyprice ,
                  @AreaTypeID ,
                  @etypeid ,
                  --@consignee ,
                 -- @consigneetel ,
                 -- @consigneeaddress ,
                  CASE WHEN @DenominatedId = '-99999' THEN @EtypeId_1 ELSE @DenominatedId END ,
                  @StopDateInput,
                  @ltsaleoutsdate,
			      @ltbuyinsdate,
				  @ltsaleorderdate,
				  @ltbuyorderdate,
				  @ltsalertdate,
				  @ltbuyrtdate,
				  @IsCarrierInput,
				  @sheng,
				  @shi,
				  @xian,
				  @IsUseBrandarType
                )

    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            SET @ErrMsg = '添加失败'
            RETURN -1
	 --return RAISERROR('客户和供货商档案不能超过9层',16,1)--return-1
        END 
    ELSE 
    BEGIN
--客户关联了信用额度管理，则该客户可以被分类和删除，同时信用额度中该客户的信用额度记录删除了
        IF EXISTS ( SELECT  btypeid
                    FROM    btype_credit
                    WHERE   BtypeId = @Parid ) 
            BEGIN 
                DELETE  FROM btype_credit
                WHERE   BtypeId = @Parid 
            END
        UPDATE  [btype]
        SET     sonnum = @nSonnum + 1 ,
                soncount = @nSoncount + 1
        WHERE   typeid = @Parid
        
    END
    
    -- 插入后验证，结算单位是否被分类
    IF EXISTS(SELECT 1 FROM btype WHERE FullName = @DenominatedFullName AND UserCode=@DenominatedUserCode AND sonnum <> 0)
	BEGIN
		ROLLBACK TRAN insertproc 
		SET @ErrMsg = '结算单位不能为父节点';
		RETURN -1;
	END
	
-- 修改品牌是否启用(客户供货商没有统一 and @EtypeId_1 为供应商)
IF (NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value=1) AND  LEFT(@EtypeId_1,5) ='00002' )
BEGIN
	UPDATE [btype] SET IsUseBrandarType = 0 WHERE typeId = @EtypeId_1
END

----客户关联了信用额度管理，则该客户可以被分类和删除，同时信用额度中该客户的信用额度记录删除了
--IF EXISTS(select btypeid from btype_credit where BtypeId=@Parid) 	
--	BEGIN 
--		--RAISERROR('该%s【%s】已关联信用额度，不能分类',16,1,@typeName,@parFullName)RETURN
--		Delete from btype_credit where BtypeId=@Parid 
--	END
-- 建立Employee数据 .超级用户的节点 --
--select @UserCode=@UserCode+'_超级用户'
--exec @nReturnType=Gp_InsertE '00000','employee',@UserCode,'超级用户','','','','',@EtypeId_1

--修改期限
UPDATE	dbo.btype
SET		ckarlimittime  = CASE
								WHEN skmonthday IS NOT NULL THEN 0
								ELSE 1
						 END,
		ckpaymentltime = CASE
								WHEN fkmonthday IS NOT NULL THEN 0
								ELSE 1
						 END
WHERE	typeid = @EtypeId_1

--插入信用额度表
IF @ifStype = 0 
BEGIN
    IF ( @ARLimit IS NOT NULL ) 
        BEGIN
            IF EXISTS ( SELECT  1
                        FROM    btype_credit
                        WHERE   StypeId = '00001'
                                AND BtypeId = @EtypeId_1 ) 
                UPDATE  btype_credit
                SET     Credit = @ARLimit
                WHERE   StypeId = '00001'
                        AND BtypeId = @EtypeId_1
            ELSE 
                INSERT  INTO btype_credit
                        ( BtypeId, StypeId, Credit )
                VALUES  ( @EtypeId_1, '00001', @ARLimit )
        END
END

IF ( @nReturnType <> 0 ) 
    BEGIN 
        ROLLBACK TRAN insertproc 
        RETURN @nReturnType 
    END

--修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    BType
    UPDATE  BType
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @EtypeId_1

    COMMIT TRAN insertproc
GO





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


/****** Object:  StoredProcedure [dbo].[Gp_ImportC]    Script Date: 05/20/2011 17:29:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*
	作者：廖晨羽
	日期：2011-08-17
	描述：修改@TelAndAddress参数的长度为256,添加etypeid字段
	
	修 改 者：廖晨羽
	日    期：2011-08-22
	修改原因：导入客户信息
	修改位置：转换输入参数
*/





CREATE                  PROCEDURE [dbo].[Gp_ImportC]
(
	@BFullName   [varchar](66),
	@UserCode  [varchar](26),
	@FullName  [varchar](66),
	@PyCode   varchar(201),
	@StrCreateDate varchar(200),
	@AFullName VARCHAR(66),
	@EFullName VARCHAR(66), --职员
	@StrARLimitTime [varchar](18),
	@StrPaymentLTime[varchar] (18), 
	@Strbuyprice varchar(200),
	@StrSaleZeKou VARCHAR(18),
	@StrBuyZeKou VARCHAR(18),
	@StrPrice    varchar(200),
	@Tel1	varchar(50),
	@Tel2	varchar(50),
	@Tel3	varchar(50),
	@Fax	varchar(50),
	@Email	varchar(50),
	@WWW	varchar(50),
	@PostCode  [varchar](201),
	@TelAndAddress  [varchar](257),
	@bankandacount  [varchar](66),
	@Bank	varchar(50),
	@BankName varchar(50),
	@TaxNumber  [varchar](20),
	@Comment  [varchar](257),
	@LinkMan1 varchar(50),
	@StrLinkSex1 VARCHAR(10),
	@StrLinkBirthDay1 varchar(200),
	@LinkJob1 varchar(50),
	@LinkCall1 Varchar(50),
	@LinkEMail1 varchar(50),
	@LinkTel1 varchar(50),
	@LinkMobile1 varchar(50),
	@LinkPost1 varchar(50),
	@LinkAddress1 varchar(50),
	@LinkComment1 varchar(257),
	@LinkMan2 varchar(50),
	@StrLinkSex2 VARCHAR(10),
	@StrLinkBirthDay2 varchar(200),
	@LinkJob2 varchar(50),
	@LinkCall2 Varchar(50),
	@LinkEMail2 varchar(50),
	@LinkTel2 varchar(50),
	@LinkMobile2 varchar(50),
	@LinkPost2 varchar(50),
	@LinkAddress2 varchar(50),
	@LinkComment2 varchar(257),
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

IF ((SELECT DATALENGTH(@PyCode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@PostCode)) > 200)
BEGIN
	SET @ErrMsg = '邮编的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@TelAndAddress)) > 256)
BEGIN
	SET @ErrMsg = '地址的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 256)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@LinkComment1)) > 256)
BEGIN
	SET @ErrMsg = '联系人1备注的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@LinkComment2)) > 256)
BEGIN
	SET @ErrMsg = '联系人2备注的长度大于最大允许长度256'
	RETURN -1
END

DECLARE @Parid VARCHAR(50)
IF (@BFullName = '')
BEGIN
	SET @Parid = '00001'
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.btype WHERE fullname = @BFullName) OR @BFullName = 'ABC'
	BEGIN
		SET @ErrMsg = '父类名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PBtypeId VARCHAR(50)
		SET @PBtypeId = (SELECT TOP 1 typeid FROM BType WHERE fullname = @BFullName)
		IF (SUBSTRING(@PBtypeId, 1, 5) = '00002')
			BEGIN
				SET @ErrMsg = '父类名称不存在'
				RETURN -1
			END
		ELSE
			BEGIN
				SET @Parid = @PBtypeId
			END
	END	
END

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '客户编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '客户名称不能为空'
	RETURN -1
END

IF(@Pycode = '')
BEGIN
	SELECT @Pycode = dbo.fun_getPY(@FullName)
END

DECLARE	@CreateDate DATETIME
IF (@StrCreateDate = '')
BEGIN
	SELECT @CreateDate = CONVERT(VARCHAR, GETDATE(), 23)
END
ELSE IF (ISDATE(@StrCreateDate) <> 1)
	 BEGIN
	 		SET @ErrMsg = '建档日期请输入日期,请使用YYYY-MM-DD的格式'
			RETURN -1
	 END
ELSE
BEGIN
	SET @CreateDate = @StrCreateDate
END

DECLARE @AreaTypeID varchar(50)
IF (@AFullName = '')
BEGIN
	SET @AreaTypeID = ''
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.AreaType WHERE fullname = @AFullName) OR @AFullName = '所有地区'
	BEGIN
		SET @ErrMsg = '地区名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PAtypeId VARCHAR(50)
		DECLARE @AChildCount NUMERIC(18,0)
		SET @PAtypeId = (SELECT TOP 1 typeid FROM dbo.AreaType WHERE fullname = @AfullName)
		SELECT @AChildCount = COUNT(*) FROM dbo.AreaType WHERE typeId LIKE @PAtypeId + '%' AND typeId <> @PAtypeId
		IF (@AChildCount = 0)
			BEGIN
				SET @AreaTypeID = @PAtypeId
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该地区是父节点'
				RETURN -1
			END
	END	
END

DECLARE @etypeid varchar(50)
IF (@EFullName = '')
BEGIN
	SET @etypeid = ''
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.employee WHERE fullname = @EFullName) OR @EFullName = 'root' OR @EFullName = '超级用户'
	BEGIN
		SET @ErrMsg = '关联职员不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PEtypeId VARCHAR(50)
		DECLARE @EChildCount NUMERIC(18,0)
		SET @PEtypeId = (SELECT TOP 1 typeid FROM dbo.employee WHERE fullname = @EFullName)
		SELECT @EChildCount = COUNT(*) FROM dbo.employee WHERE typeId LIKE @PEtypeId + '%' AND typeId <> @PEtypeId
		IF (@EChildCount = 0)
			BEGIN
				SET @etypeid = @PEtypeId
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该职员是父节点'
				RETURN -1
			END
	END	
END

DECLARE @ARLimitTime  NUMERIC(24, 10) 
IF (@StrARLimitTime = '')
BEGIN
	SET @ARLimitTime = 9999
END
ELSE IF(ISNUMERIC(@StrARLimitTime) <> 1)
BEGIN
	SET @ErrMsg = '收款期限请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('.', @StrARLimitTime)) <> 0)
BEGIN
	SET @ErrMsg = '收款期限请输入整数'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrARLimitTime)) <> 0)
BEGIN
	SET @ErrMsg = '收款期限不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @ARLimitTime = CONVERT( NUMERIC(24, 10) , @StrARLimitTime)
	IF(@ARLimitTime <=0)
	BEGIN
		SET @ErrMsg = '收款期限不能为0'
		RETURN -1
	END
	IF(@ARLimitTime > 9999)
	BEGIN
		SET @ErrMsg = '收款期限应小于9999'
		RETURN -1
	END
END

DECLARE @PaymentLTime  NUMERIC(24, 10) 
IF (@StrPaymentLTime = '')
BEGIN
	SET @PaymentLTime = 9999
END
ELSE IF(ISNUMERIC(@StrPaymentLTime) <> 1)
BEGIN
	SET @ErrMsg = '付款期限请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('.', @StrPaymentLTime)) <> 0)
BEGIN
	SET @ErrMsg = '付款期限请输入整数'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPaymentLTime)) <> 0)
BEGIN
	SET @ErrMsg = '付款期限不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PaymentLTime = CONVERT( NUMERIC(24, 10) , @StrPaymentLTime)
	IF(@PaymentLTime <=0)
	BEGIN
		SET @ErrMsg = '付款期限不能为0'
		RETURN -1
	END
	IF(@PaymentLTime > 9999)
	BEGIN
		SET @ErrMsg = '付款期限应小于9999'
		RETURN -1
	END
END

DECLARE	@buyprice varchar(50)
SELECT @buyprice = CASE @Strbuyprice 
						   WHEN '无' THEN '0'
						   WHEN '' THEN '0'
						   WHEN '预设进价1' THEN '1'
						   WHEN '预设进价2' THEN '2'
						   WHEN '预设进价3' THEN '3'
						   WHEN '预设进价4' THEN '4'
						   WHEN '预设进价5' THEN '5'
						   WHEN '最高进价' THEN '6'
						   ELSE 'ERROR' 
				END
IF(@buyprice = 'ERROR')
BEGIN
	SET @ErrMsg = '适用进价不匹配'
	RETURN -1
END

DECLARE @SaleZeKou  NUMERIC(24, 10) 
IF (@StrSaleZeKou = '')
BEGIN
	SET @SaleZeKou = NULL
END
ELSE IF(ISNUMERIC(@StrSaleZeKou) <> 1)
BEGIN
	SET @ErrMsg = '销售折扣请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrSaleZeKou)) <> 0)
BEGIN
	SET @ErrMsg = '销售折扣不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @SaleZeKou = CONVERT( NUMERIC(24, 10) , @StrSaleZeKou)
	IF (@SaleZeKou<=0 OR @SaleZeKou >1)
	BEGIN
		SET @ErrMsg = '销售折扣输入错误'
		RETURN -1
	END
END

DECLARE @BuyZeKou  NUMERIC(24, 10) 
IF (@StrBuyZeKou = '')
BEGIN
	SET @BuyZeKou = NULL
END
ELSE IF(ISNUMERIC(@StrBuyZeKou) <> 1)
BEGIN
	SET @ErrMsg = '采购折扣请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrBuyZeKou)) <> 0)
BEGIN
	SET @ErrMsg = '采购折扣不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @BuyZeKou = CONVERT( NUMERIC(24, 10) , @StrBuyZeKou)
	IF (@BuyZeKou<=0 OR @BuyZeKou >1)
	BEGIN
		SET @ErrMsg = '采购折扣输入错误'
		RETURN -1
	END
END

DECLARE	@Price varchar(50)
SELECT @Price = CASE @StrPrice  
						   WHEN '无' THEN '0'
						   WHEN '' THEN '0'
						   WHEN '预设售价1' THEN '1'
						   WHEN '预设售价2' THEN '2'
						   WHEN '预设售价3' THEN '3'
						   WHEN '预设售价4' THEN '4'
						   WHEN '预设售价5' THEN '5'
						   WHEN '预设售价6' THEN '6'
						   WHEN '预设售价7' THEN '7'
						   WHEN '预设售价8' THEN '8'
						   WHEN '预设售价9' THEN '9'
						   WHEN '预设售价10' THEN '10'
						   WHEN '零售价' THEN '11'
						   WHEN '最高售价' THEN '12'
						   WHEN '最低售价' THEN '13'
						   ELSE 'ERROR' 
				END
IF(@Price = 'ERROR')
BEGIN
	SET @ErrMsg = '适用售价不匹配'
	RETURN -1
END

DECLARE @PostCodeLen INT
SELECT @PostCodeLen = LEN(@PostCode)
IF(@PostCodeLen>200)
BEGIN
	SET @ErrMsg = '邮编不能超过200字符'
	RETURN -1
END

DECLARE @LinkSex1 BIT
SELECT @StrLinkSex1 = CASE @StrLinkSex1 
							WHEN '' THEN '1'
							WHEN '男' THEN '1' 
							WHEN '女' THEN '0'
							ELSE '无'			
					END
IF(@StrLinkSex1 = '无')
BEGIN
	SET @ErrMsg = '性别请输入男或女'
	RETURN -1
END
ELSE
BEGIN
	SET @LinkSex1 = CONVERT(BIT, @StrLinkSex1)
END

DECLARE	@LinkBirthDay1 DATETIME
IF (@StrLinkBirthDay1 = '')
BEGIN
	SELECT @LinkBirthDay1 = '1980-01-01 00:00:00'
END
ELSE IF (ISDATE(@StrLinkBirthDay1) <> 1 )
	 BEGIN
 		SET @ErrMsg = '联系人1生日请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	 END
ELSE
BEGIN
	SET @LinkBirthDay1 = @StrLinkBirthDay1
END

DECLARE @LinkSex2 BIT
SELECT @StrLinkSex2 = CASE @StrLinkSex2 
							WHEN '' THEN '1'
							WHEN '男' THEN '1' 
							WHEN '女' THEN '0'
							ELSE '无'			
					END
IF(@StrLinkSex2 = '无')
BEGIN
	SET @ErrMsg = '性别请输入男或女'
	RETURN -1
END
ELSE
BEGIN
	SET @LinkSex2 = CONVERT(BIT, @StrLinkSex2)
END


DECLARE	@LinkBirthDay2 DATETIME
IF (@StrLinkBirthDay2 = '')
BEGIN
	SELECT @LinkBirthDay2 = '1980-01-01 00:00:00'
END
ELSE IF (ISDATE(@StrLinkBirthDay2) <> 1 )
	 BEGIN
 		SET @ErrMsg = '联系人2生日请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	 END
ELSE
BEGIN
	SET @LinkBirthDay2 = @StrLinkBirthDay2
END

DECLARE @DbName VARCHAR(30) = 'btype'

DECLARE @Name  [Varchar](30) = ''

DECLARE @Area  [Varchar](30) = ''

DECLARE @Person  [varchar](20) = ''

DECLARE @Artotal00  NUMERIC(24, 10)  = 0

DECLARE @Aptotal00  NUMERIC(24, 10)  = 0

DECLARE @Client BIT = 1

DECLARE @ARLimit  NUMERIC(24, 10) 

DECLARE @ifStype INT = 1

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

declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(select subvalue from sysdata where subname='ifqp')

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from btype where typeid=@parid)
declare @typeName varchar(20)
if substring(@parid,1,5)='00001'
	set @typeName='客户'
if substring(@parid,1,5)='00002'
	set @typeName='供货商'

-- 判断单位的往来
if @Parid='00000'
return -11

--判断停用不能分类
declare @deleted INT
select @deleted=deleted from btype where typeId=@Parid
if(@deleted=1)
BEGIN
   SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已经被停用，不能分类'
   RETURN -1	
   --RAISERROR('该%s【%s】已经被停用，不能分类',16,1,@typeName,@parFullName)return ---15  
end
--判断序列号
if exists(select BTypeID1 from gp_CruPtypeSerial where BTypeID1=@Parid)
	begin
		--print '住来有序列号，不能分类'
		 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有序列号关联情况，不能分类'
		 RETURN -1
		 --RAISERROR('该%s【%s】已有序列号关联情况，不能分类',16,1,@typeName,@parFullName)return ---15
	end
if exists(select BTypeID1 from gp_initPtypeSerial where BTypeID1=@Parid)
	begin
		--print '往来有期初序列号，不能分类'
		 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有期初序列号关联情况，不能分类'
		 RETURN -1
		 --RAISERROR('该【%s】已有期初序列号关联情况，不能分类',16,1,@typeName,@parFullName)return --16
	end
	
--判断是否被分支机构使用，若被使用则禁止分类
IF EXISTS(SELECT * FROM SType WHERE BTypeID1=@Parid OR BTypeID2=@Parid)
	BEGIN
		SET @ErrMsg = '该往来单位已经被分支机构关联，禁止分类'
		RETURN -1					
		--RAISERROR('该往来单位已经被分支机构关联，禁止分类',16,1)
		--RETURN		
	END
--判断序列号
if exists(select BTypeID2 from gp_CruPtypeSerial where BTypeID2=@Parid)
	begin
		--print '住来有序列号，不能分类'
		 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有序列号关联情况，不能分类'
		 RETURN -1	
		 --RAISERROR('该%s【%s】已有序列号关联情况，不能分类',16,1,@typeName,@parFullName)return--return -15
	end
if exists(select BTypeID2 from gp_initPtypeSerial where BTypeID2=@Parid)
	begin
		--print '往来有期初序列号，不能分类'
		 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有期初序列号关联情况，不能分类'
		 RETURN -1	
		 --RAISERROR('该%s【%s】已有期初序列号关联情况，不能分类',16,1,@typeName,@parFullName)return--return -16
	end

if exists(select typeid from [btype] where typeid=@parid and ARTotal-ApTotal<>0)
	begin
		--print '['+@FullName+']单位往来帐不为零，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】往来帐不为零，不能分类'
		RETURN -1	
		--RAISERROR('该%s【%s】往来帐不为零，不能分类',16,1,@typeName,@parFullName)return
	end 
if exists(select typeid from [btype] where typeid=@parid and ARTotal00-ApTotal00<>0)
	begin
		--print '['+@FullName+']单位往来帐不为零，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】往来帐不为零，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】往来帐不为零，不能分类',16,1,@typeName,@parFullName)return--return -7
	end 

--判断应收应付预收预付期初
if exists(select BTypeID from BType_ArApTotal where BTypeID=@parid and (ARTotal00<>0 or APTotal00<>0 or YSTotal00<>0 or YFTotal00<>0))
	begin
		--print '['+@FullName+']单位往来帐不为零，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】应收或应付期初中不为零，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】应收或应付期初中不为零，不能分类',16,1,@typeName,@parFullName)return--return -7
	end 

-- 判断借欠余额
if exists(select bTypeID from V_LendStatus where bTypeID=@parid and Qty<>0)
	begin
		--print '['+@FullName+']单位有借进借出，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有借进借出，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有借进借出，不能分类',16,1,@typeName,@parFullName)return--return -5
	end 
-- 判断经营
if exists(select bTypeID from listtable where bTypeID=@parid )
   or exists(select bTypeID from LendIndex where bTypeID=@parid and totalQty<>0) 
   or exists(select bTypeID from BillIndex where bTypeID=@parid )
	begin
		--print '['+@FullName+']单位已经经营过，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已经经营过，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已经经营过，不能分类',16,1,@typeName,@parFullName)return--return -6
	end 
IF  exists(select bTypeID from OrderIndex where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 订单
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在订单中使用过，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已在订单中使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -501
	END
IF  exists(select bTypeID from LendIndex where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 借欠
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在借欠单种使用过，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已在借欠单种使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -502
	END
IF  exists(select bTypeID from AdDebtBill where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位已经经营过，不能分类' 借欠
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在应收应付中使用过，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已在应收应付中使用过，不能分类',16,1,@typeName,@parFullName)return--RETURN -502
	END

-- 判断代销情况
if exists(select bTypeID from iniCommissionStock where bTypeID=@parid and Qty<>0)
   or exists(select bTypeID from CommissionStock where bTypeID=@parid and Qty<>0)
	begin
		--print '['+@FullName+']单位有代销情况，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有代销情况，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有代销情况，不能分类',16,1,@typeName,@parFullName)return--return -13
	end 

-- 判断代销情况
if exists(select bTypeID from iniCommissionStock where bTypeID=@parid and (total<>0 or costtotal<>0))
   or exists(select bTypeID from CommissionStock where bTypeID=@parid and (total<>0 or costtotal<>0))
	begin
		--print '['+@FullName+']单位有代销情况，不能分类'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有代销情况，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有代销情况，不能分类',16,1,@typeName,@parFullName)return--return -13
	end 


IF  exists(select bTypeID from PriceProtect where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位有经营历程，不能分类
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有价保通知，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有价保通知，不能分类',16,1,@typeName,@parFullName)return--RETURN -508
	END

IF  exists(select bTypeID from FapiaoBillIndex where bTypeID=@parid )
	BEGIN
	--print '['+@FullName+']单位有发票，不能分类
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有发票，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】有发票，不能分类',16,1,@typeName,@parFullName)return--RETURN -510
	END

--判断价格跟踪
IF EXISTS(select btypeid from PriceTrack where BtypeID=@Parid)
	BEGIN
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联价格跟踪，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已关联价格跟踪，不能分类',16,1,@typeName,@parFullName)RETURN
	END
--判断信用额度
IF EXISTS(select btypeid from BType_Credit where BtypeID=@Parid)
	BEGIN
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有信用额度，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已有信用额度，不能分类',16,1,@typeName,@parFullName)RETURN
	END
--判断在会计凭证中是否关联
IF EXISTS(select ATypeID from AccountCredence where ATypeID=@Parid and TypeATypeID in('0000100009', '0000100005',  '0000200001',  '0000200006'))
	BEGIN
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联会计凭证，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已关联会计凭证，不能分类',16,1,@typeName,@parFullName)RETURN
	END
--商品信息关联分支机构，则该分支机构不能被分类
IF EXISTS(select BTypeID from QP_PType_Ext where BTypeID=@Parid)	
	BEGIN 
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联商品，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已关联商品，不能分类',16,1,@typeName,@parFullName)RETURN
	END
--关联维修业务中的保险公司
IF EXISTS(select BTypeID from Qp_ReceptionBill_Insurance where BTypeID=@Parid)	
	BEGIN 
	    --print '25555'
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联维修业务，不能分类'
		RETURN -1
		--RAISERROR('该%s【%s】已关联维修业务，不能分类',16,1,@typeName,@parFullName)RETURN
	END
-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
	BEGIN
		SET @ErrMsg = '客户和供货商的分类不能超过9层'
		RETURN -1
		--RAISERROR('客户和供货商的分类不能超过9层',16,1)return-- return -1
	end
if @nReturntype=-2 
	BEGIN
		SET @ErrMsg = '无法添加基本信息'
		RETURN -1
		--RAISERROR('无法添加基本信息',16,1)return--return -2
	end
-- 判断重复的ID,UserCode
if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
	begin
		--print '['+@usercode+']往来已存在'
		SET @ErrMsg = '该【' + @FullName + '】已经存在，' + @typeName + '编号或名称不能相同'
		RETURN -1
		--RAISERROR('该【%s】已经存在，%s编号或名称不能相同',16,1,@FullName,@typeName)return--return -3
	end

if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
	begin
		--print '['+@usercode+']往来已存在'
		SET @ErrMsg = @typeName + '名称或编号不能与已有的名称或编号重复'
		RETURN -1
		--RAISERROR('%s名称或编号不能与已有的名称或编号重复',16,1,@typeName)return--return -10
	end

-- 判断重复的ID,UserCode
if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		--print '['+@usercode+']往来已存在'
		SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被已停用的' + @typeName + '使用，请更换或删除该停用的编号或名称'
		RETURN -1
		--RAISERROR('该【%s】的编号或名称已被已停用的%s使用，请更换或删除该停用的编号或名称',16,1,@FullName,@typeName)--return -31
	end

if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
	begin
		--print '['+@usercode+']往来已存在'
		SET @ErrMsg = @typeName + '名称或编号不能与已停用的名称或编号重复'
		RETURN -1
		--RAISERROR('%s名称或编号不能与已停用的名称或编号重复',16,1,@typeName)--return -101
	END
	
--已关请购单
if exists(select btypeid from RequestBill  where bTypeID=@parid)
	BEGIN
		   -- PRINT '2555555555'
		SET @ErrMsg = '该'+ @typeName +'【'+ @parFullName +'】已关联请购单，不能分类'
		RETURN -1   
		--RAISERROR('该%s【%s】已关联请购单，不能分类',16,1,@typeName,@parFullName)return--return -518
	end
--已关pos
if exists(select btypeid from CommonPosInfo  where bTypeID=@parid)
   OR exists(select btypeid from CommonPosSaleIndex  where bTypeID=@parid)
	BEGIN	
	   -- PRINT '2555555555'
	    SET @ErrMsg = '该'+ @typeName +'【'+ @parFullName +'】已关联pos，不能分类'
		RETURN -1   
		--RAISERROR('该%s【%s】已关联pos，不能分类',16,1,@typeName,@parFullName)return--return -518
	END
--已关联会员卡
		if exists(select btypeid from nvipcardsign where bTypeID=@parid)
		BEGIN
			SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联会员卡，不能分类'
			RETURN -1
			--RAISERROR('该%s【%s】已关联会员卡，不能分类',16,1,@typeName,@parFullName)return--return -516
		end		

if @ifqp='1'
	begin
		--已关联维修车辆
		if exists(select btypeid from qp_repairautoinfo where bTypeID=@parid)
		BEGIN
			SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联维修车辆，不能分类'
			RETURN -1
			--RAISERROR('该%s【%s】已关联维修车辆，不能分类',16,1,@typeName,@parFullName)return--return -517
		end
		--已关配件档案
		if exists(select btypeid from QP_PType_Ext  where bTypeID=@parid)
		BEGIN
			SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联配件档案，不能分类'
			RETURN -1
			--RAISERROR('该%s【%s】已关联配件档案，不能分类',16,1,@typeName,@parFullName)return--return -518
		end
	end
DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

DECLARE @Ar00Temp  NUMERIC(24, 10) 
DECLARE @Ap00Temp  NUMERIC(24, 10) 
SET @Ar00Temp =0
SET @Ap00Temp =0

IF @Artotal00<>0 AND @Aptotal00<>0  -- 期初不应者都有
	RETURN 201
--IF EXISTS(select Value from userconfig where configName='Btypeall' AND Value='1')  -- 客户，供货商统一
	BEGIN
		IF LEFT(@EtypeId_1,5) ='00001' -- 客户
			BEGIN
				IF @Artotal00 >0 
					BEGIN
						SET @Ar00Temp = @Artotal00
						SET @Ap00Temp = 0
					END
				IF @Artotal00 <0 
					BEGIN
						SET @Ar00Temp = 0
						SET @Ap00Temp = abs(@Artotal00)
					END		
			END 
		ELSE  -- 供货商
			BEGIN
				IF @Aptotal00 >0 
					BEGIN
						SET @Ar00Temp = 0
						SET @Ap00Temp = @Aptotal00
					END
				IF @Aptotal00 <0 
					BEGIN
						SET @Ar00Temp = abs(@Aptotal00)
						SET @Ap00Temp = 0
					END	
			END
	END


begin tran insertproc
select @leveal=leveal from btype where typeid=@Parid
select @leveal=@leveal+1

IF EXISTS (select * from sysdata where subName='inicanmodify' AND subValue='T') AND @Artotal00<>-9123456789 AND @Aptotal00<>-9123456789-- 未开帐

INSERT INTO [btype] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [USERCODE],
  [Area],
  [TelAndAddress],
  [PostCode],
  [Name],
  [Person],
  [TaxNumber],
  [BankAndAcount],
  [ARTotal00],
  [APTotal00],
  [Comment],
  [Client],
  [ARLimit],
  [ARLimitTime],
  [PaymentLTime],
  [Tel1],
  [Tel2],
  [Tel3],
  [WWW],
  [Email],
  [Fax],
  [Bank],
  [BankName],
[LinkMan1],
[LinkSex1],
[LinkBirthDay1],
[LinkJob1],
[LinkCall1],
[LinkTel1],
[LinkMobile1],
[LinkEMail1],
[LinkPost1],
[LinkAddress1],
[LinkComment1],
[LinkMan2],
[LinkSex2],
[LinkBirthDay2],
[LinkJob2],
[LinkCall2],
[LinkTel2],
[LinkMobile2],
[LinkEMail2],
[LinkPost2],
[LinkAddress2],
[LinkComment2],
[CreateDate],
[SaleZeKou],
[BuyZeKou],
[PyCode],
[Price],
[AreaTypeID],
[etypeid],
[buyprice]
) 
 
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Area,
  @TelAndAddress,
  @PostCode,
  @Name,
  @Person,
  @TaxNumber,
  @bankandacount,
  @Ar00Temp,
  @Ap00Temp,
  @Comment,
  @Client,
  @ARLimit,
  @ARLimitTime,
  @PaymentLTime,
 @Tel1,
 @Tel2,
 @Tel3,
 @WWW,
 @Email,
 @Fax,
 @Bank,
 @BankName,
@LinkMan1,
@LinkSex1,
@LinkBirthDay1,
@LinkJob1,
@LinkCall1,
@LinkTel1,
@LinkMobile1,
@LinkEMail1,
@LinkPost1,
@LinkAddress1,
@LinkComment1,
@LinkMan2,
@LinkSex2,
@LinkBirthDay2,
@LinkJob2,
@LinkCall2,
@LinkTel2,
@LinkMobile2,
@LinkEMail2,
@LinkPost2,
@LinkAddress2,
@LinkComment2,
@CreateDate,
@SaleZeKou,
@BuyZeKou,
@returnPym,
@Price,
@AreaTypeID,
@etypeid,
@buyprice
)
ELSE -- 已开帐
INSERT INTO [btype] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [USERCODE],
  [Area],
  [TelAndAddress],
  [PostCode],
  [Name],
  [Person],
  [TaxNumber],
  [BankAndAcount],
--  [ARTotal00],
--- [APTotal00],
  [Comment],
  [Client],
  [ARLimit],
  [ARLimitTime],
  [PaymentLTime],
  [Tel1],
  [Tel2],
  [Tel3],
  [WWW],
  [Email],
  [Fax],
  [Bank],
  [BankName],
[LinkMan1],
[LinkSex1],
[LinkBirthDay1],
[LinkJob1],
[LinkCall1],
[LinkTel1],
[LinkMobile1],
[LinkEMail1],
[LinkPost1],
[LinkAddress1],
[LinkComment1],
[LinkMan2],
[LinkSex2],
[LinkBirthDay2],
[LinkJob2],
[LinkCall2],
[LinkTel2],
[LinkMobile2],
[LinkEMail2],
[LinkPost2],
[LinkAddress2],
[LinkComment2],
[CreateDate],
[SaleZeKou],
[BuyZeKou],
[PyCode],
[Price],
[AreaTypeID],
[etypeid],
[buyprice]
) 
 
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Area,
  @TelAndAddress,
  @PostCode,
  @Name,
  @Person,
  @TaxNumber,
  @bankandacount,
--  @Ar00Temp,
--  @Ap00Temp,
  @Comment,
  @Client,
  @ARLimit,
  @ARLimitTime,
  @PaymentLTime,
 @Tel1,
 @Tel2,
 @Tel3,
 @WWW,
 @Email,
 @Fax,
 @Bank,
 @BankName,
@LinkMan1,
@LinkSex1,
@LinkBirthDay1,
@LinkJob1,
@LinkCall1,
@LinkTel1,
@LinkMobile1,
@LinkEMail1,
@LinkPost1,
@LinkAddress1,
@LinkComment1,
@LinkMan2,
@LinkSex2,
@LinkBirthDay2,
@LinkJob2,
@LinkCall2,
@LinkTel2,
@LinkMobile2,
@LinkEMail2,
@LinkPost2,
@LinkAddress2,
@LinkComment2,
@CreateDate,
@SaleZeKou,
@BuyZeKou,
@returnPym,
@Price,
@AreaTypeID,
@etypeid,
@buyprice
)

if @@rowcount=0 
	begin
	 rollback tran insertproc 
	 SET @ErrMsg = '客户和供货商档案不能超过9层'
	 RETURN -1
	 --return RAISERROR('客户和供货商档案不能超过9层',16,1)--return-1
	end 
else 
	begin
	--客户关联了信用额度管理，则该客户可以被分类和删除，同时信用额度中该客户的信用额度记录删除了
	IF EXISTS(select btypeid from btype_credit where BtypeId=@Parid) 	
		BEGIN 
			Delete from btype_credit where BtypeId=@Parid 
		END
	 update [btype]
	 set sonnum=@nSonnum+1,soncount=@nSoncount+1
	 where typeid=@Parid
	end

----客户关联了信用额度管理，则该客户可以被分类和删除，同时信用额度中该客户的信用额度记录删除了
--IF EXISTS(select btypeid from btype_credit where BtypeId=@Parid) 	
--	BEGIN 
--		--RAISERROR('该%s【%s】已关联信用额度，不能分类',16,1,@typeName,@parFullName)RETURN
--		Delete from btype_credit where BtypeId=@Parid 
--	END
-- 建立Employee数据 .超级用户的节点 --
--select @UserCode=@UserCode+'_超级用户'
--exec @nReturnType=Gp_InsertE '00000','employee',@UserCode,'超级用户','','','','',@EtypeId_1
if @ifStype=0
begin
--插入信用额度表
	IF(@ARLimit IS NOT NULL)
	BEGIN
		if exists(select 1 from btype_credit where StypeId='00001' and BtypeId=@EtypeId_1)
			update btype_credit set Credit=@ARLimit where StypeId='00001' and BtypeId=@EtypeId_1
		else 
			insert into btype_credit(BtypeId,StypeId,Credit) values(@EtypeId_1,'00001',@ARLimit)
	END
end

if (@nReturnType <> 0)
begin 
 rollback tran insertproc 
 return @nReturnType 
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM BType
UPDATE BType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

commit tran insertproc




SET  @ReturnID = @@ROWCOUNT
































GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/****** Object:  StoredProcedure [dbo].[gp_Importcashbank]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	作	  者：廖晨羽
	日    期：2011-09-13
	描	  述：导入现金银行期初
*/


CREATE         PROCEDURE [dbo].[gp_Importcashbank]
(
	@SFullName   [varchar](200),		--分支机构名称
	@AFullName   [varchar](200),		--科目名称
	@Strtotal00  [varchar](18),			--科目余额
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
DECLARE @stypeid	VARCHAR(1000)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF (@SFullName = '' OR @SFullName = '总部' OR NOT EXISTS(SELECT typeid FROM dbo.SType WHERE fullname = @SFullName))
	BEGIN
		SET @ErrMsg = '该分支机构不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PStypeId VARCHAR(50)
		DECLARE @SChildCount NUMERIC(18,0)
		SET @PStypeId = (SELECT TOP 1 typeid FROM dbo.SType WHERE fullname = @SFullName)
		SELECT @SChildCount = COUNT(*) FROM dbo.SType WHERE typeId LIKE @PStypeId + '%' AND typeId <> @PStypeId
		IF (@SChildCount = 0)
			BEGIN
				SET @stypeid = @PStypeId		
				IF (@stypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@typeid)))
				BEGIN
					SET @ErrMsg = '操作员不具备该分支机构权限'
					RETURN -1
				END				
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该分支机构是父类'
				RETURN -1
			END
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

	--判断分支机构是否已开账
IF ((SELECT U.Value FROM SType_UserConfig U,SType_Config C WHERE U.ConfigNo = C.ConfigNo AND U.Value = '1' AND U.STypeID = @stypeid) = 1)
BEGIN
	SET @ErrMsg = '已开账'
	RETURN -1
END

DECLARE @atypeid	VARCHAR(1000)
IF(@AFullName = '现金')
SET @AFullName = '现    金'
IF (@AFullName = '' OR @AFullName = 'root' OR NOT EXISTS(SELECT typeid FROM dbo.atype WHERE fullname = @AFullName))
BEGIN
	SET @ErrMsg = '该科目名称不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PAtypeId VARCHAR(50)
	DECLARE @AChildCount NUMERIC(18,0)
	SET @PAtypeId = (SELECT TOP 1 typeid FROM dbo.atype WHERE fullname = @AFullName)
	IF (SUBSTRING(@PAtypeId, 1, 10) <> '0000100004' AND @PAtypeId <> '0000100003')
	BEGIN
		SET @ErrMsg = '该科目名称不存在'
		RETURN -1
	END
	SELECT @AChildCount = COUNT(*) FROM dbo.atype WHERE typeId LIKE @PAtypeId + '%' AND typeId <> @PAtypeId
	IF (@AChildCount = 0)
		BEGIN
			SET @atypeid = @PAtypeId			
			IF (@atypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',5,@typeid)))
			BEGIN
				SET @ErrMsg = '操作员不具备该银行账户权限'
				RETURN -1
			END			
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该科目名称是父类'
			RETURN -1
		END
END

DECLARE @total00  NUMERIC(24, 10) 
IF (@Strtotal00 = '')
BEGIN
	SET @ErrMsg = '请输入科目余额'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@Strtotal00) <> 1)
		BEGIN
			SET @ErrMsg = '科目余额请输入数字'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @total00 = CONVERT( NUMERIC(24, 10) , @Strtotal00)
		END
END
----------------------------------------------------------------------------------------------

IF EXISTS (SELECT 1 FROM atype_total WHERE atypeid=@atypeid AND stypeid=@stypeid)   
 UPDATE atype_total SET total00=@total00 WHERE atypeid=@atypeid AND stypeid=@stypeid ---存在
 ELSE 
 INSERT INTO atype_total(atypeid,stypeid,total,total00)  --不存在
 VALUES(@atypeid,@stypeid,0,@total00)
 
 SET @ReturnID = @@ROWCOUNT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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


/****** Object:  StoredProcedure [dbo].[Gp_ImportC]    Script Date: 05/20/2011 17:29:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
	修 改 者：周华
	日    期：2012-07-31
	描    述:导入客户档案 以前版本Gp_ImportC
	
	2013-12-18 周华 添加父类验证是为结算单位
*/
CREATE                  PROCEDURE [dbo].[Gp_ImportCustomers]
(
	@BUserCode varchar(66),
	@BFullName   [varchar](66),
	@UserCode  [varchar](200),
	@FullName  [varchar](200),
	@PyCode   varchar(500),
	@StrCreateDate varchar(200),
	@AFullName VARCHAR(66),
	@EFullName VARCHAR(66), --职员
	@StopDate VARCHAR(200) ,
	@StrARLimitTime [varchar](25),
	@StrPaymentLTime[varchar] (25), 
	@ltsaleoutsday VARCHAR(200) ,
    @ltbuyinsday VARCHAR(200) ,
    @ltsaleorderday VARCHAR(200) ,
    @ltbuyorderday VARCHAR(200) ,
    @ltsalertday VARCHAR(200) ,
    @ltbuyrtday VARCHAR(200) ,
    @Isusebrandar varchar(50), --是否启用品牌应收
	@Strbuyprice varchar(50),
	@StrSaleZeKou VARCHAR(25),
	@StrBuyZeKou VARCHAR(25),
	@StrPrice    varchar(200),
	@Tel1	varchar(50),
	@Tel2	varchar(50),
	@Tel3	varchar(50),
	@Fax	varchar(50),
	@Email	varchar(50),
	@WWW	varchar(50),
	@PostCode  [varchar](200),
	@TelAndAddress  [varchar](256),
	@bankandacount  [varchar](66),
	@Bank	varchar(50),
	@BankName varchar(50),
	@TaxNumber  [varchar](20),
	@Comment  [varchar](256),
	@LinkMan1 varchar(50),
	@StrLinkSex1 VARCHAR(10),
	@StrLinkBirthDay1 varchar(200),
	@LinkJob1 varchar(50),
	@LinkCall1 Varchar(50),
	@LinkEMail1 varchar(50),
	@LinkTel1 varchar(50),
	@LinkMobile1 varchar(50),
	@LinkPost1 varchar(50),
	@LinkAddress1 varchar(50),
	@LinkComment1 varchar(256),
	@LinkMan2 varchar(50),
	@StrLinkSex2 VARCHAR(10),
	@StrLinkBirthDay2 varchar(200),
	@LinkJob2 varchar(50),
	@LinkCall2 Varchar(50),
	@LinkEMail2 varchar(50),
	@LinkTel2 varchar(50),
	@LinkMobile2 varchar(50),
	@LinkPost2 varchar(50),
	@LinkAddress2 varchar(50),
	@LinkComment2 varchar(256),
	@ErrMsg VARCHAR(200) output,
	@denominatedName VARCHAR(200),
	@denominatedUserCode VARCHAR(200),
	@tb TbType_BaseInfoCustom  READONLY ,--自定义属性
	@costom1            VARCHAR(600)=''         ,
	@costom2            VARCHAR(600)=''          ,
	@costom3            VARCHAR(600)=''          ,
	@costom4            VARCHAR(600)=''          ,
	@costom5            VARCHAR(600)=''          ,
	@costom6            VARCHAR(600)=''          ,
	@costom7            VARCHAR(600)=''          ,
	@costom8            VARCHAR(600)=''          ,
	@costom9            VARCHAR(600)=''          ,
	@costom10           VARCHAR(600)=''          ,
	@costom11           VARCHAR(600)=''          ,
	@costom12           VARCHAR(600)=''          ,
	@costom13           VARCHAR(600)=''          ,
	@costom14           VARCHAR(600)=''          ,
	@costom15           VARCHAR(600)=''          ,
	@costom16           VARCHAR(600)=''          ,
	@sheng				VARCHAR(100) = '',		--省
	@shi				VARCHAR(100) = '',		--市
	@xian				VARCHAR(100) = ''		--县 
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
/* --去掉长度验证
IF ((SELECT DATALENGTH(@PyCode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@PostCode)) > 200)
BEGIN
	SET @ErrMsg = '邮编的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@TelAndAddress)) > 256)
BEGIN
	SET @ErrMsg = '地址的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 256)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@LinkComment1)) > 256)
BEGIN
	SET @ErrMsg = '联系人1备注的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@LinkComment2)) > 256)
BEGIN
	SET @ErrMsg = '联系人2备注的长度大于最大允许长度256'
	RETURN -1
END
*/
DECLARE @Parid VARCHAR(50)
DECLARE @PBtypeId VARCHAR(50)
DECLARE	@CreateDate DATETIME
DECLARE @AreaTypeID varchar(50)
DECLARE @PAtypeId VARCHAR(50)
DECLARE @AChildCount NUMERIC(18,0)
DECLARE @PEtypeId VARCHAR(50)
DECLARE @EChildCount NUMERIC(18,0)
DECLARE @etypeid varchar(50)
DECLARE @ARLimitTime  NUMERIC(24, 10) 
DECLARE @SaleZeKou  NUMERIC(24, 10) 
DECLARE @BuyZeKou  NUMERIC(24, 10) 
DECLARE	@Price varchar(50)
DECLARE @PostCodeLen INT
DECLARE @LinkSex1 BIT
DECLARE @PaymentLTime  NUMERIC(24, 10) 
DECLARE	@buyprice varchar(50)
DECLARE	@LinkBirthDay1 DATETIME
DECLARE @LinkSex2 BIT
DECLARE	@LinkBirthDay2 DATETIME
DECLARE @StopDateInput DATETIME
DECLARE @ltsaleoutsdate DATETIME
DECLARE @ltbuyinsdate DATETIME
DECLARE @ltsaleorderdate DATETIME
DECLARE @ltbuyorderdate DATETIME
DECLARE @ltsalertdate DATETIME
DECLARE @ltbuyrtdate DATETIME
DECLARE @IsUseBrandarType INT
DECLARE @denominatedid VARCHAR(200)='';

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '客户编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '客户名称不能为空'
	RETURN -1
END


IF (@BFullName = '' AND @BUserCode='')
	SET @Parid = '00001'
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM btype WHERE usercode=@BUserCode) OR (@BFullName='ABC' AND @BUserCode='abc')
	BEGIN
		SET @ErrMsg='不存在此名称与编号对应的父类';
		RETURN -1;
	END
	--IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.btype WHERE fullname = @BFullName AND UserCode=@BUserCode) OR @BFullName = 'ABC'
	--BEGIN
	--	SET @ErrMsg = '父类名称不存在'
	--	RETURN -1
	--END
	ELSE
	BEGIN

		SELECT TOP 1 @PBtypeId =typeid FROM BType WHERE UserCode=@BUserCode
		IF (SUBSTRING(@PBtypeId, 1, 5) = '00002')
		BEGIN
			SET @ErrMsg = '不存在此名称与编号对应的父类'
			RETURN -1
		END
		ELSE
		BEGIN
				IF EXISTS(SELECT 1 FROM (
					SELECT b.denominatedid,b.usercode AS dusercode,b.FullName AS dfullname FROM btype a JOIN btype b ON a.denominatedid=b.typeId AND a.typeid<>a.denominatedid AND  a.typeid LIKE '00001%'
				) w  WHERE w.dusercode=@BUserCode AND w.dfullname=@BFullName)
				BEGIN
					SET @ErrMsg='此父类已在结算单位当中使用,不能做为父类';
					RETURN -1
				END
				ELSE
					SET @Parid = @PBtypeId
		END
	END	
END



SELECT @Pycode = dbo.fun_getPY(@FullName) WHERE @Pycode = ''

IF (@StrCreateDate = '')
	SET @CreateDate = CONVERT(VARCHAR, GETDATE(), 23)
ELSE IF (ISDATE(@StrCreateDate) <> 1)
BEGIN
	SET @ErrMsg = '建档日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @CreateDate = @StrCreateDate

IF (@AFullName = '')
BEGIN
	SET @AreaTypeID = ''
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.AreaType WHERE fullname = @AFullName) OR @AFullName = '所有地区'
	BEGIN
		SET @ErrMsg = '地区名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SELECT TOP 1 @PAtypeId =typeid FROM dbo.AreaType WHERE fullname = @AfullName
		SELECT @AChildCount = COUNT(*) FROM dbo.AreaType WHERE typeId LIKE @PAtypeId + '%' AND typeId <> @PAtypeId
		IF (@AChildCount = 0)
			SET @AreaTypeID = @PAtypeId
		ELSE
		BEGIN
			SET @ErrMsg = '该地区是父节点'
			RETURN -1
		END
	END	
END

IF (@EFullName = '')
BEGIN
	SET @etypeid = ''
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.employee WHERE fullname = @EFullName) OR @EFullName = 'root' OR @EFullName = '超级用户'
	BEGIN
		SET @ErrMsg = '关联职员不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SELECT TOP 1 @PEtypeId = typeid FROM dbo.employee WHERE fullname = @EFullName
		SELECT @EChildCount = COUNT(*) FROM dbo.employee WHERE typeId LIKE @PEtypeId + '%' AND typeId <> @PEtypeId
		IF (@EChildCount = 0)
			SET @etypeid = @PEtypeId
		ELSE
		BEGIN
			SET @ErrMsg = '该职员是父节点'
			RETURN -1
		END
	END	
END

IF (@StopDate = '')
	SET @StopDateInput = NULL
ELSE IF (ISDATE(@StopDate) <> 1)
BEGIN
	SET @ErrMsg = '停用日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @StopDateInput = @StopDate

IF (@StrARLimitTime = '') SET @ARLimitTime = 9999

ELSE IF(ISNUMERIC(@StrARLimitTime) <> 1)
BEGIN
	SET @ErrMsg = '收款期限请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('.', @StrARLimitTime)) <> 0)
BEGIN
	SET @ErrMsg = '收款期限请输入整数'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrARLimitTime)) <> 0)
BEGIN
	SET @ErrMsg = '收款期限不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @ARLimitTime = CONVERT( NUMERIC(24, 10) , @StrARLimitTime)
	IF(@ARLimitTime <=0)
	BEGIN
		SET @ErrMsg = '收款期限不能为0'
		RETURN -1
	END
	IF(@ARLimitTime > 9999)
	BEGIN
		SET @ErrMsg = '收款期限应小于9999'
		RETURN -1
	END
END

IF (@StrPaymentLTime = '') 
	SET @PaymentLTime = 9999
ELSE IF(ISNUMERIC(@StrPaymentLTime) <> 1)
BEGIN
	SET @ErrMsg = '付款期限请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('.', @StrPaymentLTime)) <> 0)
BEGIN
	SET @ErrMsg = '付款期限请输入整数'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPaymentLTime)) <> 0)
BEGIN
	SET @ErrMsg = '付款期限不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SET @PaymentLTime = CONVERT( NUMERIC(24, 10) , @StrPaymentLTime)
	IF(@PaymentLTime <=0)
	BEGIN
		SET @ErrMsg = '付款期限不能为0'
		RETURN -1
	END
	IF(@PaymentLTime > 9999)
	BEGIN
		SET @ErrMsg = '付款期限应小于9999'
		RETURN -1
	END
END

IF (@ltsaleoutsday = '')
	SET @ltsaleoutsdate = NULL
ELSE IF (ISDATE(@ltsaleoutsday) <> 1)
BEGIN
	SET @ErrMsg = '最近销售出库日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @ltsaleoutsdate = @ltsaleoutsday
	
IF (@ltbuyinsday = '')
	SET @ltbuyinsdate = NULL
ELSE IF (ISDATE(@ltbuyinsday) <> 1)
BEGIN
	SET @ErrMsg = '最近采购入库日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @ltbuyinsdate = @ltbuyinsday
	
IF (@ltsaleorderday = '')
	SET @ltsaleorderdate = NULL
ELSE IF (ISDATE(@ltsaleorderday) <> 1)
BEGIN
	SET @ErrMsg = '最近销售订货日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @ltsaleorderdate = @ltsaleorderday
	
IF (@ltbuyorderday = '')
	SET @ltbuyorderdate = NULL
ELSE IF (ISDATE(@ltbuyorderday) <> 1)
BEGIN
	SET @ErrMsg = '最近采购订货日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @ltbuyorderdate = @ltbuyorderday
	
IF (@ltsalertday = '')
	SET @ltsalertdate = NULL
ELSE IF (ISDATE(@ltsalertday) <> 1)
BEGIN
	SET @ErrMsg = '最近销售退货日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @ltsalertdate = @ltsalertday
	
IF (@ltbuyrtday = '')
	SET @ltbuyrtdate = NULL
ELSE IF (ISDATE(@ltbuyrtday) <> 1)
BEGIN
	SET @ErrMsg = '最近采购退货日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @ltbuyrtdate = @ltbuyrtday

SET @buyprice = CASE @Strbuyprice 
						   WHEN '无' THEN '0'
						   WHEN '' THEN '0'
						   WHEN '预设进价1' THEN '1'
						   WHEN '预设进价2' THEN '2'
						   WHEN '预设进价3' THEN '3'
						   WHEN '预设进价4' THEN '4'
						   WHEN '预设进价5' THEN '5'
						   WHEN '最高进价' THEN '6'
						   WHEN '零售价' THEN '7'
						   ELSE 'ERROR' 
				END
IF(@buyprice = 'ERROR')
BEGIN
	SET @ErrMsg = '适用进价不匹配'
	RETURN -1
END


DECLARE 
@d_discount                VARCHAR(5),   --  扣率小数位数               4
@d_discount1               INT ;         --  扣率小数位数               4
                          
SELECT @d_discount         = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 4
SET @d_discount1           = CONVERT(INT,@d_discount)

IF (@StrSaleZeKou = '') 
	SET @SaleZeKou = NULL
ELSE IF(ISNUMERIC(@StrSaleZeKou) <> 1)
BEGIN
	SET @ErrMsg = '销售折扣请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrSaleZeKou)) <> 0)
BEGIN
	SET @ErrMsg = '销售折扣不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SET @SaleZeKou = CONVERT( NUMERIC(24, 10) , @StrSaleZeKou)
	IF (@SaleZeKou<=0 OR @SaleZeKou >1)
	BEGIN
		SET @ErrMsg = '销售折扣输入错误'
		RETURN -1
	END
	IF dbo.F_CheckDecimal(@StrSaleZeKou,4,@d_discount1) < 0
	BEGIN
		SET @ErrMsg='销售折扣值多于'+@d_discount+'位小数'
		RETURN -1;
	END
END



IF (@StrBuyZeKou = '') 
	SET @BuyZeKou = NULL
ELSE IF(ISNUMERIC(@StrBuyZeKou) <> 1)
BEGIN
	SET @ErrMsg = '采购折扣请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrBuyZeKou)) <> 0)
BEGIN
	SET @ErrMsg = '采购折扣不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SET @BuyZeKou = CONVERT( NUMERIC(24, 10) , @StrBuyZeKou)
	IF (@BuyZeKou<=0 OR @BuyZeKou >1)
	BEGIN
		SET @ErrMsg = '采购折扣输入错误'
		RETURN -1
	END
	IF dbo.F_CheckDecimal(@StrBuyZeKou,4,@d_discount1) < 0
	BEGIN
		SET @ErrMsg='采购折扣值多于'+@d_discount+'位小数'
		RETURN -1;
	END
END

SELECT @Price = CASE @StrPrice  
						   WHEN '无' THEN '0'
						   WHEN '' THEN '0'
						   WHEN '预设售价1' THEN '1'
						   WHEN '预设售价2' THEN '2'
						   WHEN '预设售价3' THEN '3'
						   WHEN '预设售价4' THEN '4'
						   WHEN '预设售价5' THEN '5'
						   WHEN '预设售价6' THEN '6'
						   WHEN '预设售价7' THEN '7'
						   WHEN '预设售价8' THEN '8'
						   WHEN '预设售价9' THEN '9'
						   WHEN '预设售价10' THEN '10'
						   WHEN '零售价' THEN '11'
						   WHEN '最高售价' THEN '12'
						   WHEN '最低售价' THEN '13'
						   ELSE 'ERROR' 
				END
IF(@Price = 'ERROR')
BEGIN
	SET @ErrMsg = '适用售价不匹配'
	RETURN -1
END

SET @PostCodeLen = LEN(@PostCode)
IF(@PostCodeLen>200)
BEGIN
	SET @ErrMsg = '邮编不能超过200字符'
	RETURN -1
END

SET @StrLinkSex1 = CASE @StrLinkSex1 
							WHEN '' THEN '1'
							WHEN '男' THEN '1' 
							WHEN '女' THEN '0'
							ELSE '无'			
					END
IF(@StrLinkSex1 = '无')
BEGIN
	SET @ErrMsg = '性别请输入男或女'
	RETURN -1
END
ELSE
	SET @LinkSex1 = CONVERT(BIT, @StrLinkSex1)


IF (@StrLinkBirthDay1 = '')
	SET @LinkBirthDay1 = '1980-01-01 00:00:00'
ELSE IF (ISDATE(@StrLinkBirthDay1) <> 1 )
BEGIN
	SET @ErrMsg = '联系人1生日请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @LinkBirthDay1 = @StrLinkBirthDay1

SET @StrLinkSex2 = CASE @StrLinkSex2 
							WHEN '' THEN '1'
							WHEN '男' THEN '1' 
							WHEN '女' THEN '0'
							ELSE '无'			
					END
IF(@StrLinkSex2 = '无')
BEGIN
	SET @ErrMsg = '性别请输入男或女'
	RETURN -1
END
ELSE
	SET @LinkSex2 = CONVERT(BIT, @StrLinkSex2)

IF (@StrLinkBirthDay2 = '')
	SET @LinkBirthDay2 = '1980-01-01 00:00:00'
ELSE IF (ISDATE(@StrLinkBirthDay2) <> 1 )
BEGIN
	SET @ErrMsg = '联系人2生日请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
END
ELSE
	SET @LinkBirthDay2 = @StrLinkBirthDay2
	


-- 结算单位是否存在
IF NOT EXISTS(SELECT 1 FROM BTYPE WHERE FullName=@denominatedName AND UserCode=@denominatedUserCode AND sonnum=0
		AND (typeid LIKE '00001%' 
				AND EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='btypeall' AND value='0')
				OR NOT EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='btypeall' AND value='0')
			)
	)
BEGIN
	IF (@denominatedUserCode='' AND @denominatedName='')
		SET @denominatedid='-99999';
	ELSE IF (@FullName=@denominatedName AND @denominatedUserCode=@UserCode)	
		SET @denominatedid='-99999';
	ELSE
	BEGIN
		SET @ErrMsg='该结算单位是父节点或者结算单位不存在或者不是一个有效的结算单位或者结算单位编号与名称不对应';
		RETURN -1;
	END
END
ELSE
	SELECT @denominatedid=typeid FROM BType WHERE UserCode=@denominatedUserCode;/*FullName=@denominatedName;*/

--是否启用品牌应收
IF (@Isusebrandar = '启用')
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName ='usebrandartype' and SubValue = 1)
		SET @IsUseBrandarType = 1;
	ELSE 
		SET @IsUseBrandarType = 0;
ELSE IF(@Isusebrandar = '不启用' OR @Isusebrandar = '')
	SET @IsUseBrandarType = 0;
ELSE 
	BEGIN
		SET @ErrMsg = '请选择启用品牌应收值：启用/不启用';
		RETURN -1;
	END


----------------------------------------------------------------------------------------------
DECLARE @DbName VARCHAR(30) = 'btype'
DECLARE @Name  [Varchar](30) = ''
DECLARE @Area  [Varchar](30) = ''
DECLARE @Person  [varchar](20) = ''
DECLARE @Artotal00  NUMERIC(24, 10)  = 0
DECLARE @Aptotal00  NUMERIC(24, 10)  = 0
DECLARE @Client BIT = 1
DECLARE @ARLimit  NUMERIC(24, 10) 

DECLARE @ifStype INT = 1
declare @nReturntype int
	,@EtypeId_1 [varchar](50)
	,@nSoncount int
	,@nSonnum int
	,@leveal smallint

--判断是否为汽配
declare @ifqp varchar(1)
declare @parFullName varchar(200)
declare @typeName varchar(20)
DECLARE @typename1 VARCHAR(20)
DECLARE @id1 VARCHAR(20)
declare @deleted INT

select @ifqp=subvalue from sysdata where subname='ifqp'

set @parFullName=(select top 1 fullname from btype where typeid=@parid)

if substring(@parid,1,5)='00001'
begin
	set @typeName='客户'
	SET @typeName1='供货商'
	SET @id1='00002'
END
if substring(@parid,1,5)='00002'
BEGIN
	set @typeName='供货商'
	SET @typeName1='客户'
	SET @id1='00001'
END
-- 判断单位的往来
if @Parid='00000'
return -11
--判断停用不能分类
select @deleted=deleted from btype where typeId=@Parid
if(@deleted=1)
BEGIN
   SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已经被停用，不能分类'
   RETURN -1	
END
--判断序列号
if exists(select BTypeID1 from gp_CruPtypeSerial where BTypeID1=@Parid)
begin
	 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有序列号关联情况，不能分类'
	 RETURN -1
end
if exists(select BTypeID1 from gp_initPtypeSerial where BTypeID1=@Parid)
begin
	 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有期初序列号关联情况，不能分类'
	 RETURN -1
end
	
--判断是否被分支机构使用，若被使用则禁止分类
IF EXISTS(SELECT * FROM SType WHERE BTypeID1=@Parid OR BTypeID2=@Parid)
BEGIN
	SET @ErrMsg = '该往来单位已经被分支机构关联，禁止分类'
	RETURN -1					
END
--判断序列号
if exists(select BTypeID2 from gp_CruPtypeSerial where BTypeID2=@Parid)
begin
	 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有序列号关联情况，不能分类'
	 RETURN -1	
end
if exists(select BTypeID2 from gp_initPtypeSerial where BTypeID2=@Parid)
begin
	 SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有期初序列号关联情况，不能分类'
	 RETURN -1	
end

if exists(select typeid from [btype] where typeid=@parid and ARTotal-ApTotal<>0)
begin
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】往来帐不为零，不能分类'
	RETURN -1	
end 
if exists(select typeid from [btype] where typeid=@parid and ARTotal00-ApTotal00<>0)
begin
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】往来帐不为零，不能分类'
	RETURN -1
end 

--判断应收应付预收预付期初
if exists(select BTypeID from BType_ArApTotal where BTypeID=@parid and (ARTotal00<>0 or APTotal00<>0 or YSTotal00<>0 or YFTotal00<>0))
begin
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】应收或应付期初中不为零，不能分类'
	RETURN -1
end 

-- 判断借欠余额
if exists(select bTypeID from V_LendStatus where bTypeID=@parid and Qty<>0)
begin
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有借进借出，不能分类'
	RETURN -1
end 
-- 判断经营
if exists(select bTypeID from listtable where bTypeID=@parid )
   or exists(select bTypeID from LendIndex where bTypeID=@parid and totalQty<>0) 
   or exists(select bTypeID from BillIndex where bTypeID=@parid )
begin
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已经经营过，不能分类'
	RETURN -1
end 
IF  exists(select bTypeID from OrderIndex where bTypeID=@parid )
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在订单中使用过，不能分类'
	RETURN -1
END
IF  exists(select bTypeID from LendIndex where bTypeID=@parid )
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在借欠单种使用过，不能分类'
	RETURN -1
END
IF  exists(select bTypeID from AdDebtBill where bTypeID=@parid )
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已在应收应付中使用过，不能分类'
	RETURN -1
END

-- 判断代销情况
if exists(select bTypeID from iniCommissionStock where bTypeID=@parid and Qty<>0)
   or exists(select bTypeID from CommissionStock where bTypeID=@parid and Qty<>0)
begin
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有代销情况，不能分类'
	RETURN -1
end 

-- 判断代销情况
if exists(select bTypeID from iniCommissionStock where bTypeID=@parid and (total<>0 or costtotal<>0))
   or exists(select bTypeID from CommissionStock where bTypeID=@parid and (total<>0 or costtotal<>0))
begin
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有代销情况，不能分类'
	RETURN -1
end 

IF  exists(select bTypeID from PriceProtect where bTypeID=@parid )
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有价保通知，不能分类'
	RETURN -1
END

IF  exists(select bTypeID from FapiaoBillIndex where bTypeID=@parid )
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】有发票，不能分类'
	RETURN -1
END

--判断价格跟踪
IF EXISTS(select btypeid from PriceTrack where BtypeID=@Parid)
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联价格跟踪，不能分类'
	RETURN -1
END
--判断信用额度
IF EXISTS(select btypeid from BType_Credit where BtypeID=@Parid)
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已有信用额度，不能分类'
	RETURN -1
END
--判断在会计凭证中是否关联
IF EXISTS(select ATypeID from AccountCredence where ATypeID=@Parid and TypeATypeID in('0000100009', '0000100005',  '0000200001',  '0000200006'))
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联会计凭证，不能分类'
	RETURN -1
END
--商品信息关联分支机构，则该分支机构不能被分类
IF EXISTS(select BTypeID from QP_PType_Ext where BTypeID=@Parid)	
BEGIN 
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联商品，不能分类'
	RETURN -1
END
--关联维修业务中的保险公司
IF EXISTS(select BTypeID from Qp_ReceptionBill_Insurance where BTypeID=@Parid)	
BEGIN 
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联维修业务，不能分类'
	RETURN -1
END
-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
BEGIN
	SET @ErrMsg = '客户和供货商的分类不能超过9层'
	RETURN -1
END
if @nReturntype=-2 
BEGIN
	SET @ErrMsg = '无法添加基本信息'
	RETURN -1
END
-- 判断重复的ID,UserCode
DECLARE @BnameFlag varchar(50)
select @BnameFlag=value from Userconfig where ConfigName='equalbidname'

IF @BnameFlag<>1
begin
	if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】已经存在，名称或编号不能相同'
		RETURN -1
	end
end
else
begin
	if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1))
	begin
		SET @ErrMsg = '该【' + @usercode + '】已经存在，名称或编号不能相同'
		RETURN -1
	end
end

if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) /*or (fullname=@usercode and deleted<>1)*/)
begin
	SET @ErrMsg = @typeName + '名称不能与已有的编号重复'
	RETURN -1
END
--名称不能与另一部分(客户名称不能与供货商)名称相同
IF EXISTS(select TypeID from [btype] where typeId=@EtypeId_1 OR (fullname=@fullname AND typeid LIKE @id1+'%' AND deleted<>1))
BEGIN
	SET @ErrMsg=@typename+'名称不能与已有'+@typename1+'名称重复';
	RETURN -1
END

-- 判断重复的ID,UserCode
if  @BnameFlag<>1
begin
	if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @typeName + '使用，请更换或删除该停用的编号'
		RETURN -1
	end
end
else
begin
	if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @typeName + '使用，请更换或删除该停用的编号'
		RETURN -1
	end
end

if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) /*or (fullname=@usercode and deleted=1)*/)
BEGIN
	SET @ErrMsg = @typeName + '名称不能与已停用的编号重复'
	RETURN -1
END
	
--已关请购单
if exists(select btypeid from RequestBill  where bTypeID=@parid)
BEGIN
	SET @ErrMsg = '该'+ @typeName +'【'+ @parFullName +'】已关联请购单，不能分类'
	RETURN -1   
END
--已关pos
if exists(select btypeid from CommonPosInfo  where bTypeID=@parid)
   OR exists(select btypeid from CommonPosSaleIndex  where bTypeID=@parid)
   OR EXISTS(SELECT btypeId FROM dbo.PosInfo WHERE btypeId=@parid)
BEGIN	
   -- PRINT '2555555555'
    SET @ErrMsg = '该'+ @typeName +'【'+ @parFullName +'】已关联pos，不能分类'
	RETURN -1   
END
IF EXISTS (SELECT BtypeID FROM PriceRule_Detail_BConfig WHERE BtypeID=@parid)
BEGIN
	SET @ErrMsg = '该'+ @typeName +'【'+ @parFullName +'】已关联促销，不能分类'
	RETURN -1;
END


--已关联会员卡
if exists(select btypeid from nvipcardsign where bTypeID=@parid)
BEGIN
	SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联会员卡，不能分类'
	RETURN -1
END		



if @ifqp='1'
begin
	--已关联维修车辆
	if exists(select btypeid from qp_repairautoinfo where bTypeID=@parid)
	BEGIN
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联维修车辆，不能分类'
		RETURN -1
	END
	--已关配件档案
	if exists(select btypeid from QP_PType_Ext  where bTypeID=@parid)
	BEGIN
		SET @ErrMsg = '该' + @typeName + '【' + @parFullName + '】已关联配件档案，不能分类'
		RETURN -1
	END
end
DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' SET @returnPym=@PyCode

DECLARE @Ar00Temp  NUMERIC(24, 10) 
DECLARE @Ap00Temp  NUMERIC(24, 10) 
SET @Ar00Temp =0
SET @Ap00Temp =0
-- 期初不应者都有
IF @Artotal00<>0 AND @Aptotal00<>0  RETURN 201
BEGIN
	IF LEFT(@EtypeId_1,5) ='00001' -- 客户
	BEGIN
		SELECT @Ar00Temp = @Artotal00,@Ap00Temp = 0 WHERE @Artotal00 >0;
		SELECT @Ar00Temp = 0,@Ap00Temp = abs(@Artotal00) WHERE @Artotal00 <0;
	END 
	ELSE  -- 供货商
	BEGIN
		SELECT @Ar00Temp = 0,@Ap00Temp = @Aptotal00 WHERE @Aptotal00 >0;
		SELECT @Ar00Temp = abs(@Aptotal00),@Ap00Temp = 0 WHERE @Aptotal00 <0;
	END
END

--验证客户自定义开始
	CREATE TABLE #Custom(
		EditKind			VARCHAR(50) ,				--数据类型
		label				VARCHAR(50),				--属性名称
		datafield			VARCHAR(50),				-- 数据库对应字段
		maxbytelength		int     --长度
	)

	IF ( 0 < (SELECT COUNT(1) FROM @tb))
	BEGIN
		INSERT INTO #Custom (EditKind,label,datafield,maxbytelength) SELECT EditKind,label,datafield,maxbytelength FROM @tb
	END
	IF( 0 < (SELECT COUNT(1) FROM CustomBaseInforColumnsDefines WHERE BaseType='btype'))
	BEGIN
		IF  @costom1 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列1'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='自定义列1类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom1) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='自定义列1超出最大值'
				RETURN -1 
			END
		END

		IF  @costom2 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列2'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='自定义列2类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom2) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='自定义列2超出最大值'
				RETURN -1 
			END
		END

		IF  @costom3 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列3'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='自定义列3类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom3) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='自定义列3超出最大值'
				RETURN -1 
			END
		END

		IF  @costom4 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列4'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='自定义列4类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom4) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='自定义列4超出最大值'
				RETURN -1 
			END
		END

		IF  @costom5 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列5'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='自定义列5类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom5) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='自定义列5超出最大值'
				RETURN -1 
			END
		END

		IF  @costom6 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列6'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='自定义列6类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom6) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='自定义列6超出最大值'
				RETURN -1 
			END
		END

		IF  @costom7 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列7'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='自定义列7类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom7) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='自定义列7超出最大值'
				RETURN -1 
			END
		END

		IF  @costom8 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列8'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='自定义列8类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom8) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='自定义列8超出最大值'
				RETURN -1 
			END
		END

		IF  @costom9 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列9'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='自定义列9类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom9) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='自定义列9超出最大值'
				RETURN -1 
			END
		END

		IF  @costom10 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列10'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='自定义列10类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom10) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='自定义列10超出最大值'
				RETURN -1 
			END
		END

		IF  @costom11 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列11'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='自定义列11类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom11) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='自定义列11超出最大值'
				RETURN -1 
			END
		END

		IF  @costom12 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列12'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='自定义列12类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom12) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='自定义列12超出最大值'
				RETURN -1 
			END
		END

		IF  @costom13 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列13'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='自定义列13类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom13) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='自定义列13超出最大值'
				RETURN -1 
			END
		END

		IF  @costom14 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列14'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='自定义列14类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom14) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='自定义列14超出最大值'
				RETURN -1 
			END
		END

		IF  @costom15 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列15'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='自定义列15类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom15) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='自定义列15超出最大值'
				RETURN -1 
			END
		END

		IF  @costom16 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列16'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='自定义列16类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom16) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='自定义列16超出最大值'
				RETURN -1 
			END
		END
	END
	ELSE
	BEGIN
		IF (@costom1 <> ''   OR @costom2 <> ''   OR @costom3 <> ''   OR @costom4 <> ''   OR @costom5 <> ''   OR @costom6 <> ''   OR @costom7 <> ''   OR @costom8 <> ''   OR @costom9 <> ''   OR @costom10 <> ''   OR @costom11 <> ''   OR @costom12 <> ''   OR @costom13 <> ''   OR @costom14 <> ''   OR @costom15 <> ''   OR @costom16 <> ''  )
		BEGIN
			SET @ErrMsg ='系统未启用客户自定义列'
			RETURN -1
		END
	END
	DROP TABLE #Custom
--验证客户自定义结束

BEGIN TRAN insertproc
select @leveal=leveal+1 from btype where typeid=@Parid

IF EXISTS (select * from sysdata where subName='inicanmodify' AND subValue='T') AND @Artotal00<>-9123456789 AND @Aptotal00<>-9123456789-- 未开帐
BEGIN

INSERT INTO [btype] 
( 
	[typeId],
	[Parid],
	[leveal],
	[soncount],
	[sonnum],
	[FullName],
	[USERCODE],
	[Area],
	[TelAndAddress],
	[PostCode],
	[Name],
	[Person],
	[TaxNumber],
	[BankAndAcount],
	[ARTotal00],
	[APTotal00],
	[Comment],
	[Client],
	[ARLimit],
	[ARLimitTime],
	[PaymentLTime],
	[Tel1],
	[Tel2],
	[Tel3],
	[WWW],
	[Email],
	[Fax],
	[Bank],
	[BankName],
	[LinkMan1],
	[LinkSex1],
	[LinkBirthDay1],
	[LinkJob1],
	[LinkCall1],
	[LinkTel1],
	[LinkMobile1],
	[LinkEMail1],
	[LinkPost1],
	[LinkAddress1],
	[LinkComment1],
	[LinkMan2],
	[LinkSex2],
	[LinkBirthDay2],
	[LinkJob2],
	[LinkCall2],
	[LinkTel2],
	[LinkMobile2],
	[LinkEMail2],
	[LinkPost2],
	[LinkAddress2],
	[LinkComment2],
	[CreateDate],
	[SaleZeKou],
	[BuyZeKou],
	[PyCode],
	[Price],
	[AreaTypeID],
	[etypeid],
	[buyprice],
	denominatedid,
	sheng,
	shi,
	xian,
	IsUseBrandarType
)VALUES( 
	@EtypeId_1,
	@Parid,
	@leveal,
	0,
	0,
	@FullName,
	@UserCode,
	@Area,
	@TelAndAddress,
	@PostCode,
	@Name,
	@Person,
	@TaxNumber,
	@bankandacount,
	@Ar00Temp,
	@Ap00Temp,
	@Comment,
	@Client,
	@ARLimit,
	@ARLimitTime,
	@PaymentLTime,
	@Tel1,
	@Tel2,
	@Tel3,
	@WWW,
	@Email,
	@Fax,
	@Bank,
	@BankName,
	@LinkMan1,
	@LinkSex1,
	@LinkBirthDay1,
	@LinkJob1,
	@LinkCall1,
	@LinkTel1,
	@LinkMobile1,
	@LinkEMail1,
	@LinkPost1,
	@LinkAddress1,
	@LinkComment1,
	@LinkMan2,
	@LinkSex2,
	@LinkBirthDay2,
	@LinkJob2,
	@LinkCall2,
	@LinkTel2,
	@LinkMobile2,
	@LinkEMail2,
	@LinkPost2,
	@LinkAddress2,
	@LinkComment2,
	@CreateDate,
	@SaleZeKou,
	@BuyZeKou,
	@returnPym,
	@Price,
	@AreaTypeID,
	@etypeid,
	@buyprice,
	CASE WHEN @denominatedid='-99999' THEN @EtypeId_1 ELSE @denominatedid END,
	@sheng,
	@shi,
	@xian,
	@IsUseBrandarType
)
end
ELSE -- 已开帐
INSERT INTO [btype] 
( 
	[typeId],
	[Parid],
	[leveal],
	[soncount],
	[sonnum],
	[FullName],
	[USERCODE],
	[Area],
	[TelAndAddress],
	[PostCode],
	[Name],
	[Person],
	[TaxNumber],
	[BankAndAcount],
	--  [ARTotal00],
	--- [APTotal00],
	[Comment],
	[Client],
	[ARLimit],
	[ARLimitTime],
	[PaymentLTime],
	[Tel1],
	[Tel2],
	[Tel3],
	[WWW],
	[Email],
	[Fax],
	[Bank],
	[BankName],
	[LinkMan1],
	[LinkSex1],
	[LinkBirthDay1],
	[LinkJob1],
	[LinkCall1],
	[LinkTel1],
	[LinkMobile1],
	[LinkEMail1],
	[LinkPost1],
	[LinkAddress1],
	[LinkComment1],
	[LinkMan2],
	[LinkSex2],
	[LinkBirthDay2],
	[LinkJob2],
	[LinkCall2],
	[LinkTel2],
	[LinkMobile2],
	[LinkEMail2],
	[LinkPost2],
	[LinkAddress2],
	[LinkComment2],
	[CreateDate],
	[SaleZeKou],
	[BuyZeKou],
	[PyCode],
	[Price],
	[AreaTypeID],
	[etypeid],
	[buyprice],
	denominatedid,
	stopdate,
	ltsaleoutsday,
	ltbuyinsday,
	ltsaleorderday,
	ltbuyorderday,
	ltsalertday,
	ltbuyrtday,
	sheng,
	shi,
	xian,
	IsUseBrandarType 
)VALUES( 
	@EtypeId_1,
	@Parid,
	@leveal,
	0,
	0,
	@FullName,
	@UserCode,
	@Area,
	@TelAndAddress,
	@PostCode,
	@Name,
	@Person,
	@TaxNumber,
	@bankandacount,
	--  @Ar00Temp,
	--  @Ap00Temp,
	@Comment,
	@Client,
	@ARLimit,
	@ARLimitTime,
	@PaymentLTime,
	@Tel1,
	@Tel2,
	@Tel3,
	@WWW,
	@Email,
	@Fax,
	@Bank,
	@BankName,
	@LinkMan1,
	@LinkSex1,
	@LinkBirthDay1,
	@LinkJob1,
	@LinkCall1,
	@LinkTel1,
	@LinkMobile1,
	@LinkEMail1,
	@LinkPost1,
	@LinkAddress1,
	@LinkComment1,
	@LinkMan2,
	@LinkSex2,
	@LinkBirthDay2,
	@LinkJob2,
	@LinkCall2,
	@LinkTel2,
	@LinkMobile2,
	@LinkEMail2,
	@LinkPost2,
	@LinkAddress2,
	@LinkComment2,
	@CreateDate,
	@SaleZeKou,
	@BuyZeKou,
	@returnPym,
	@Price,
	@AreaTypeID,
	@etypeid,
	@buyprice,
	CASE WHEN @denominatedid='-99999' THEN @EtypeId_1 ELSE @denominatedid END,
	@StopDateInput,
	@ltsaleoutsdate,
	@ltbuyinsdate,
	@ltsaleorderdate,
	@ltbuyorderdate,
	@ltsalertdate,
	@ltbuyrtdate,
	@sheng,
	@shi,
	@xian,
	@IsUseBrandarType
)

if @@rowcount=0 
begin
	rollback tran insertproc 
	SET @ErrMsg = '添加失败'
	RETURN -1
end 
else 
begin
	--客户关联了信用额度管理，则该客户可以被分类和删除，同时信用额度中该客户的信用额度记录删除了
	IF EXISTS(select btypeid from btype_credit where BtypeId=@Parid) 	
	BEGIN 
		Delete from btype_credit where BtypeId=@Parid 
	END
	update [btype]
	set sonnum=@nSonnum+1,soncount=@nSoncount+1
	where typeid=@Parid
end

-- 插入后验证，结算单位是否被分类
IF EXISTS(SELECT 1 FROM btype WHERE FullName = @denominatedName AND UserCode=@denominatedUserCode AND sonnum <> 0)
BEGIN
	ROLLBACK TRAN insertproc 
	SET @ErrMsg = '结算单位不能为父节点';
	RETURN -1;
END

if @ifStype=0
begin
--插入信用额度表
	IF(@ARLimit IS NOT NULL)
	BEGIN
		if exists(select 1 from btype_credit where StypeId='00001' and BtypeId=@EtypeId_1)
			update btype_credit set Credit=@ARLimit where StypeId='00001' and BtypeId=@EtypeId_1
		else 
			insert into btype_credit(BtypeId,StypeId,Credit) values(@EtypeId_1,'00001',@ARLimit)
	END
end

if (@nReturnType <> 0)
begin 
	ROLLBACK TRAN insertproc 
	return @nReturnType 
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM BType
UPDATE BType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

--修改期限
UPDATE	dbo.btype
SET		ckarlimittime  = CASE
								WHEN skmonthday IS NOT NULL THEN 0
								ELSE 1
						 END,
		ckpaymentltime = CASE
								WHEN fkmonthday IS NOT NULL THEN 0
								ELSE 1
						 END
WHERE	typeid = @EtypeId_1


IF( 0 < (SELECT COUNT(1) FROM CustomBaseInforColumnsDefines WHERE BaseType='btype'))
	BEGIN
	--	IF (@costom1 <> ''   OR @costom2 <> ''   OR @costom3 <> ''   OR @costom4 <> ''   OR @costom5 <> ''   OR @costom6 <> ''   OR @costom7 <> ''   OR @costom8 <> ''   OR @costom9 <> ''   OR @costom10 <> ''   OR @costom11 <> ''   OR @costom12 <> ''   OR @costom13 <> ''   OR @costom14 <> ''   OR @costom15 <> ''   OR @costom16 <> ''  )
	--	BEGIN
				INSERT INTO dbo.Btype_CustomColumns
        ( typeid ,
          Costom1 ,
          Costom2 ,
          Costom3 ,
          Costom4 ,
          Costom5 ,
          Costom6 ,
          Costom7 ,
          Costom8 ,
          Costom9 ,
          Costom10 ,
          Costom11 ,
          Costom12 ,
          Costom13 ,
          Costom14 ,
          Costom15 ,
          Costom16 
        )
		VALUES  ( 
		@EtypeId_1,
		@costom1,
		@costom2,
		@costom3,
		@costom4,
		@costom5,
		@costom6,
		@costom7,
		@costom8,
		@costom9,
		@costom10,
		@costom11,
		@costom12,
		@costom13,
		@costom14,
		@costom15,
		@costom16
				)
	--	END
	END

COMMIT TRAN insertproc

GO





GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.GP_ImportCxmgkbdr',N'P'))
BEGIN
	DROP PROC dbo.GP_ImportCxmgkbdr;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	作者：谢吉康
	日期：2017-07-05
	描述：促销买够商品捆绑导入模板
*/	

CREATE PROC GP_ImportCxmgkbdr
(	
	@operatorid			VARCHAR(50),			--操作员ID
	@qty				VARCHAR(50),			--数量
	@usercode			VARCHAR(200),			--商品编号
	@fullname			VARCHAR(200),			--商品名称	
	@kbusercode			VARCHAR(200),			--捆绑商品编号
	@kbfullname			VARCHAR(200),			--捆绑商品名称	
	@jjtotal			VARCHAR(50),			--加价金额
	@kbqty				VARCHAR(50),			--捆绑数量
	@ReturnID			VARCHAR(100) OUTPUT,	--返回ID
	@ErrMsg				VARCHAR(200) OUTPUT		--返回消息
)
--@encode$--
AS
SET NOCOUNT ON

/*
SetGridColumnIsVisible(new string[] { "buyqty", "usercode", "fullname", "bindusercode", "bindfullname", "othertotal", "qty" }, true);
SetGridColumnName("usercode", "商品编号");
SetGridColumnName("fullname", "商品名称");
SetGridColumnName("othertotal", "加价金额");
SetGridColumnName("qty", "捆绑数量");
*/

IF @usercode = ''
BEGIN
	SET @ErrMsg = '商品编号为空！'
	RETURN -1
END	

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.F_GetManPTypeAll(@operatorid) WHERE UserCode = @usercode AND deleted = 0 AND sonnum = 0)
BEGIN
	SET @ErrMsg = '商品信息不在权限范围内或者不正确！'
	RETURN -1
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.F_GetManPTypeAll(@operatorid) WHERE UserCode = @kbusercode AND deleted = 0 AND sonnum = 0)
BEGIN
	SET @ErrMsg = '捆绑商品信息不在权限范围内或者不正确！'
	RETURN -1
END

IF ISNUMERIC(@qty) = 0 OR ISNUMERIC(@jjtotal)= 0 OR ISNUMERIC(@kbqty) = 0
BEGIN
	SET @ErrMsg = '金额或者数量必须为数字！'
	RETURN -1
END

DECLARE @_jjtotal NUMERIC(24,10)
		,@_qty	NUMERIC(24,10)
		,@_kbqty	NUMERIC(24,10)

SET @_jjtotal = CAST(@jjtotal AS NUMERIC(24,10))
SET @_qty = CAST(@qty AS NUMERIC(24,10))
SET @_kbqty = CAST(@kbqty AS NUMERIC(24,10))

IF @_jjtotal < 0 OR @_kbqty < 0 OR @_qty < 0
BEGIN
	SET @ErrMsg = '金额或者数量不能为负数！'
	RETURN -1
END

DECLARE @typeid		VARCHAR(50),
		@bptypeid	VARCHAR(50)

SELECT @typeid = typeid FROM ptype WHERE UserCode = @usercode
SELECT @bptypeid = typeid FROM ptype WHERE UserCode = @kbusercode

INSERT INTO importptypetemp
(
	etypeid,
	billtype,
	PtypeId,
	StrEntryCode,
	qty,	
	strprice,
	StrTax
)VALUES(
	@operatorid,
	3337,
	@typeid,
	@bptypeid,
	@_qty,	
	@_jjtotal,
	@_kbqty
)

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.GP_ImportCxmgspzpdr',N'P'))
BEGIN
	DROP PROC dbo.GP_ImportCxmgspzpdr;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	作者：谢吉康
	日期：2017-07-05
	描述：促销买够商品赠品导入模板
*/	

CREATE PROC GP_ImportCxmgspzpdr
(	
	@operatorid			VARCHAR(50),			--操作员ID
	@usercode			VARCHAR(200),			--商品编号
	@fullname			VARCHAR(200),			--商品名称
	@zsqty				VARCHAR(50),			--赠送数量
	@tjtotal			VARCHAR(50),			--特价金额
	@qty				VARCHAR(50),			--赠送数量
	@ReturnID			VARCHAR(100) OUTPUT,	--返回ID
	@ErrMsg				VARCHAR(200) OUTPUT		--返回消息
)
--@encode$--
AS
SET NOCOUNT ON

/*
SetGridColumnIsVisible(new string[] { "buyqty", "usercode", "fullname", "othertotal", "qty" }, true);
SetGridColumnName("othertotal", "特价金额");
SetGridColumnName("usercode", "赠品编号");
SetGridColumnName("fullname", "赠品名称");
SetGridColumnName("qty", "赠送数量");
*/

IF @usercode = ''
BEGIN
	SET @ErrMsg = '商品编号为空！'
	RETURN -1
END	

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.F_GetManPTypeAll(@operatorid) WHERE UserCode = @usercode AND deleted = 0 AND sonnum = 0)
BEGIN
	SET @ErrMsg = '商品信息不在权限范围内或者不正确！'
	RETURN -1
END

IF ISNUMERIC(@tjtotal)= 0 OR ISNUMERIC(@qty) = 0 OR ISNUMERIC(@zsqty) = 0
BEGIN
	SET @ErrMsg = '金额或者数量必须为数字！'
	RETURN -1
END

DECLARE @_tjtotal NUMERIC(24,10)
		,@_qty	NUMERIC(24,10)
		,@_zsqty	NUMERIC(24,10)

SET @_tjtotal = CAST(@tjtotal AS NUMERIC(24,10))
SET @_qty = CAST(@qty AS NUMERIC(24,10))
SET @_zsqty = CAST(@zsqty AS NUMERIC(24,10))

IF @_tjtotal < 0 OR @_qty < 0 OR @_zsqty < 0
BEGIN
	SET @ErrMsg = '金额或者数量不能为负数！'
	RETURN -1
END

DECLARE @typeid VARCHAR(50)

SELECT @typeid = typeid FROM ptype WHERE UserCode = @usercode

INSERT INTO importptypetemp
(
	etypeid,
	billtype,
	PtypeId,
	qty,
	strprice,
	strtax
)VALUES(
	@operatorid,
	3335,
	@typeid,
	@_qty,
	@_zsqty,
	@_tjtotal
)

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.GP_ImportCxmgtjdr',N'P'))
BEGIN
	DROP PROC dbo.GP_ImportCxmgtjdr;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	作者：谢吉康
	日期：2017-07-05
	描述：促销买够商品特价导入模板
*/	

CREATE PROC GP_ImportCxmgtjdr
(	
	@operatorid			VARCHAR(50),			--操作员ID
	@usercode			VARCHAR(200),			--商品编号
	@fullname			VARCHAR(200),			--商品名称	
	@tjtotal			VARCHAR(50),			--特价金额
	@qty				VARCHAR(50),			--买够数量
	@ReturnID			VARCHAR(100) OUTPUT,	--返回ID
	@ErrMsg				VARCHAR(200) OUTPUT		--返回消息
)
--@encode$--
AS
SET NOCOUNT ON

/*
SetGridColumnIsVisible(new string[] { "indatesnum", "usercode", "fullname", "othertotal" }, true);
SetGridColumnName("usercode", "商品编号");
SetGridColumnName("fullname", "商品名称");
SetGridColumnName("othertotal", "价格");
*/

IF @usercode = ''
BEGIN
	SET @ErrMsg = '商品编号为空！'
	RETURN -1
END	

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.F_GetManPTypeAll(@operatorid) WHERE UserCode = @usercode AND deleted = 0 AND sonnum = 0)
BEGIN
	SET @ErrMsg = '商品信息不在权限范围内或者不正确！'
	RETURN -1
END

IF ISNUMERIC(@tjtotal)= 0 OR ISNUMERIC(@qty) = 0
BEGIN
	SET @ErrMsg = '金额或者数量必须为数字！'
	RETURN -1
END

DECLARE @_tjtotal NUMERIC(24,10)
		,@_qty	NUMERIC(24,10)

SET @_tjtotal = CAST(@tjtotal AS NUMERIC(24,10))
SET @_qty = CAST(@qty AS NUMERIC(24,10))

IF @_tjtotal < 0 OR @_qty < 0
BEGIN
	SET @ErrMsg = '金额或者数量不能为负数！'
	RETURN -1
END

DECLARE @typeid VARCHAR(50)

SELECT @typeid = typeid FROM ptype WHERE UserCode = @usercode

INSERT INTO importptypetemp
(
	etypeid,
	billtype,
	PtypeId,
	qty,
	strprice
)VALUES(
	@operatorid,
	3336,
	@typeid,
	@_qty,	
	@_tjtotal
)

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.GP_ImportCxmmjezpdr',N'P'))
BEGIN
	DROP PROC dbo.GP_ImportCxmmjezpdr;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	作者：谢吉康
	日期：2017-07-05
	描述：促销买满金额赠品导入模板
*/	

CREATE PROC GP_ImportCxmmjezpdr
(	
	@operatorid			VARCHAR(50),			--操作员ID
	@usercode			VARCHAR(200),			--商品编号
	@fullname			VARCHAR(200),			--商品名称
	@total				VARCHAR(50),			--买满金额
	@tjtotal			VARCHAR(50),			--特价金额
	@qty				VARCHAR(50),			--赠送数量
	@ReturnID			VARCHAR(100) OUTPUT,	--返回ID
	@ErrMsg				VARCHAR(200) OUTPUT		--返回消息
)
--@encode$--
AS
SET NOCOUNT ON

/*
SetGridColumnName("othertotal", "特价金额");
SetGridColumnName("usercode", "赠品编号");
SetGridColumnName("fullname", "赠品名称");
SetGridColumnName("qty", "赠送数量");
*/

IF @usercode = ''
BEGIN
	SET @ErrMsg = '商品编号为空！'
	RETURN -1
END	

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.F_GetManPTypeAll(@operatorid) WHERE UserCode = @usercode AND deleted = 0 AND sonnum = 0)
BEGIN
	SET @ErrMsg = '商品信息不在权限范围内或者不正确！'
	RETURN -1
END

IF ISNUMERIC(@total)= 0 OR ISNUMERIC(@tjtotal) = 0 OR ISNUMERIC(@qty) = 0
BEGIN
	SET @ErrMsg = '金额或者数量必须为数字！'
	RETURN -1
END

DECLARE @_tjtotal NUMERIC(24,10)
		,@_qty	NUMERIC(24,10)
		,@_total	NUMERIC(24,10)

SET @_tjtotal = CAST(@tjtotal AS NUMERIC(24,10))
SET @_qty = CAST(@qty AS NUMERIC(24,10))
SET @_total = CAST(@total AS NUMERIC(24,10))

IF @_total < 0 OR @_tjtotal < 0 OR @_qty < 0
BEGIN
	SET @ErrMsg = '金额或者数量不能为负数！'
	RETURN -1
END

DECLARE @typeid VARCHAR(50)

SELECT @typeid = typeid FROM ptype WHERE UserCode = @usercode

INSERT INTO importptypetemp
(
	etypeid,
	billtype,
	PtypeId,
	qty,
	strprice,
	strtax
)VALUES(
	@operatorid,
	3334,
	@typeid,
	@_qty,
	@_total,
	@_tjtotal
)

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.GP_ImportCxzcyspdr',N'P'))
BEGIN
	DROP PROC dbo.GP_ImportCxzcyspdr;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	作者：谢吉康
	日期：2017-07-05
	描述：促销商品导入
*/	

CREATE PROC GP_ImportCxzcyspdr
(	
	@operatorid			VARCHAR(50),			--操作员ID
	@usercode			VARCHAR(200),			--商品编号
	@fullname			VARCHAR(200),			--商品名称
	@ReturnID			VARCHAR(100) OUTPUT,	--返回ID
	@ErrMsg				VARCHAR(200) OUTPUT		--返回消息
)
--@encode$--
AS
SET NOCOUNT ON

IF @usercode = ''
BEGIN
	SET @ErrMsg = '商品编号为空！'
	RETURN -1
END	

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.F_GetManPTypeAll(@operatorid) WHERE UserCode = @usercode AND deleted = 0 AND sonnum = 0)
BEGIN
	SET @ErrMsg = '商品信息不在权限范围内或者不正确！'
	RETURN -1
END

DECLARE @typeid VARCHAR(50)

SELECT @typeid = typeid FROM ptype WHERE UserCode = @usercode

INSERT INTO importptypetemp
(
	etypeid,
	billtype,
	PtypeId
)VALUES(
	@operatorid,
	3333,
	--'cysp',
	@typeid
)

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



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

/****** Object:  StoredProcedure [dbo].[Gp_ImportD]    Script Date: 05/25/2011 09:05:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*
	修 改 者：廖晨羽
	日	  期：2011-08-18
	修改原因：导入部门信息
	修改位置：转换输入参数
*/


CREATE            PROCEDURE [dbo].[Gp_ImportD]
(
	@DFullName   [varchar](100),
	@UserCode  [varchar](100),
	@FullName  [varchar](100),
	@Name [varchar](100),
	@PyCode varchar(201),
	@Tel varchar(50),
	@Fax varchar(50),
	@LinkMan varchar(50),
    @Comment  [varchar](100),
    @ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

IF ((SELECT DATALENGTH(@PyCode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

DECLARE @DbName		[varchar](30) = 'DepartMent'

--IF ((SELECT DATALENGTH(@PyCode)) > 500)
--BEGIN
--	SET @ErrMsg = '拼音码的长度大于最大允许长度500'
--	RETURN -1
--END

DECLARE @Parid VARCHAR(50)
IF (@DFullName = '')
BEGIN
	SET @Parid = '00000'
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.Department WHERE fullname = @DFullName)
	BEGIN
		SET @ErrMsg = '父类名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		BEGIN
			SET @Parid = (SELECT TOP 1 typeid FROM Department WHERE fullname = @DFullName)
		END
	END	
END

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '部门编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '部门全名不能为空'
	RETURN -1
END

IF(@Pycode = '')
BEGIN
	SELECT @Pycode = dbo.fun_getPY(@FullName)
END
----------------------------------------------------------------------------------------------

declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint
 
declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from department where typeid=@parid)


--判断停用不能分类
declare @deleted INT
select @deleted=deleted from department where typeId=@Parid
if(@deleted=1)
BEGIN
   SET @ErrMsg = '该部门【' + @parFullName + '】已经被停用，不能分类'
   RETURN -1	
   --RAISERROR('该部门【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
end

-- 判断经营
if exists (select DTypeID from Billindex where DTypeID=@parid ) 
begin
	--print '['+@FullName+']分支机构已经经营过，不能分类'
	SET @ErrMsg = '该部门【' + @parFullName + '】存在经营历程或已经在职员信息中使用，不能分类'
	RETURN -1
	--RAISERROR('该部门【%s】存在经营历程或已经在职员信息中使用，不能分类',16,1,@parFullName)return--return -301
end 

--判断部门信息是否被职员信息使用过：若有使用，禁止分类
if exists(select DtypeID from employee where DtypeID=@Parid)
	BEGIN
		SET @ErrMsg = '该部门【' + @parFullName + '】已经在职员信息中使用，不能分类'
		RETURN -1
		--RAISERROR('该部门【%s】已经在职员信息中使用，不能分类',16,1,@parFullName)RETURN
	end
	
if exists(SELECT * FROM nVipConfiscateConfig WHERE DTypeID=@Parid) or exists (SELECT * FROM nVipWashCarTimesConfig WHERE DTypeID=@Parid)
    begin
        --print '2555'
		SET @ErrMsg = '该部门【' + @parFullName + '】已经在充值单中使用，不能分类'
		RETURN -1
		--RAISERROR('该部门【%s】已经在充值单中使用，不能分类',16,1,@parFullName)RETURN
	end

--关联销售计划
if exists(SELECT * FROM DtypeSaleplan WHERE DTypeID=@Parid)
begin
        --print '2555'
		SET @ErrMsg ='该部门【'+@parFullName+'】已经在销售计划中使用，不能分类'
		RETURN -1
end
--使用登记单
if exists(SELECT * FROM CM_CarUseIndex WHERE DTypeID=@Parid)
begin
        --print '2555'
        SET @ErrMsg ='该部门【'+@parFullName+'】已经在使用登记单中使用，不能分类'
		RETURN -1
END
--车辆费用单
if exists(SELECT * FROM CM_FeeIndex WHERE DTypeID=@Parid)
begin
        --print '2555'
        SET @ErrMsg ='该部门【'+@parFullName+'】已经在车辆费用单中使用，不能分类'
		RETURN -1
END
	
if exists (select DTypeID from OrderIndex where DTypeID=@parid )
begin
	-- print '订单用过'
	SET @ErrMsg = '该部门【' + @parFullName + '】已在订单中使用，不能分类'
	RETURN -1
	--RAISERROR('该部门【%s】已在订单中使用，不能分类',16,1,@parFullName)return--return -501
end
if exists (select DTypeID from LendIndex where DTypeID=@parid )
begin
	-- print '借欠用过'
	SET @ErrMsg = '该部门【' + @parFullName + '】已在借欠单种使用，不能分类'
	RETURN -1
	--RAISERROR('该部门【%s】已在借欠单种使用，不能分类',16,1,@parFullName)return--return -502
end
if exists (select DTypeID from FapiaoBillIndex where DTypeID=@parid )
begin
	-- print '借欠用过'
	SET @ErrMsg = '该部门【' + @parFullName + '】作为发票开单的部门，不能分类'
	RETURN -1
	--RAISERROR('该部门【%s】作为发票开单的部门，不能分类',16,1,@parFullName)return--return -511
end

-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1
BEGIN
	SET @ErrMsg = '部门的分类不能超过10层'
	RETURN -1
	--RAISERROR('部门的分类不能超过10层',16,1)return--return -1
end
if @nReturntype=-2
BEGIN
	SET @ErrMsg = '无法添加基本信息'
	RETURN -1
	--RAISERROR('无法添加基本信息',16,1)return--return -2
end
-- 判断重复的ID,UserCode

if exists(select * from [DepartMent] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
begin
	--print '['+@usercode+']分支机构已存在'
		SET @ErrMsg = '【'+ @FullName + '】名称或编号不能与已有的名称或编号重复，不能分类'
		RETURN -1
		--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复，不能分类',16,1,@FullName)return--return -303
end
-- 判断重复的ID,UserCode
if exists(select * from [DepartMent] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
begin
	--print '['+@usercode+']分支机构已存在'
	SET @ErrMsg = '【'+ @FullName + '】名称或编号不能与已有的名称或编号重复，不能分类'
	RETURN -1
	--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复，不能分类',16,1,@FullName)return--return -303
end

-- 判断重复的ID,UserCode
if exists(select * from [DepartMent] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
begin
	--print '['+@usercode+']分支机构已存在'
	SET @ErrMsg = '【'+ @FullName + '】名称或编号不能与已有的名称或编号重复，不能分类'
	RETURN -1
	--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复，不能分类',16,1,@FullName)return--return -303
end
-- 判断重复的ID,UserCode
if exists(select * from [DepartMent] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
begin
	--print '['+@usercode+']分支机构已存在'
	SET @ErrMsg = '【'+ @FullName + '】名称或编号不能与已有的名称或编号重复，不能分类'
	RETURN -1
	--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复，不能分类',16,1,@FullName)return--return -303
end




/*
-- 判断分支机构的最大使用数量
declare @nCount int
select @nCount=Count(*) from DepartMent 
where sonnum = 0 
 and deleted=0
if @nCount > 10
begin
-- print '分支机构数量大于10'
 return -99
end
*/

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

begin tran insertproc
select @leveal=leveal from DepartMent where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO [DepartMent] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [Name], 
  [UserCode],
  [Comment],
  [LinkMan],
  [Tel],
  [Fax],
  [PyCode]
 )  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @name,
  @UserCode,
  @Comment,
  @LinkMan ,
  @Tel ,
  @Fax,
  @returnPym
 )
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [DepartMent]
 set sonnum=@nSonnum+1,soncount=@nSoncount+1
 where typeid=@Parid
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Department
UPDATE Department SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
commit tran insertproc



SET @ReturnID = @@ROWCOUNT






















GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[gp_ImportDefaultStock]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[gp_ImportDefaultStock]
GO

/************       Script Date: 05/07/2019 15:28:40 ************/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	修 改 者：赵燕琴
	日    期：2019-05-07
	描    述：商品默认仓库货拉导入
*/
CREATE   PROCEDURE [dbo].[gp_ImportDefaultStock]
(
 @PUserCode  [varchar](66),
 @PFullName   [varchar](200),
 @SUserCode  [varchar](66),
 @SFullName  [varchar](200),
 @KUserCode [varchar](66),
 @KFullName  [varchar](256),
 @CUserCode [varchar](200),
 @CFullName [varchar](200),
 @ErrMsg VARCHAR(200) output
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

DECLARE @dbname	[varchar](30) = 'DefaultStock '

DECLARE @ptypeid [varchar](50)='0'
DECLARE @stypeid [varchar](50)='0'
DECLARE @ktypeid [varchar](50)='0' 
DECLARE @cargoid [varchar](50)='0' 
DECLARE @proinfo INT
DECLARE @value INT

--- v3=1 a8=2 v1=4 
SELECT @proinfo=subvalue FROM sysdata where subname='proinfo'

--1启用货位
SELECT @value=Value FROM Userconfig WHERE ConfigName='mngcargospace' 

   --分支机构
IF (@proinfo=2)
   BEGIN
   SELECT @stypeid=typeid from SType where usercode=@SUserCode
   END
ELSE
   BEGIN--v1v3不填写分支机构，即使填写了也不处理，保存在默认分支机构
   SELECT @stypeid=typeid from SType where typeid=00001
   END
--商品编号
select @ptypeid=typeid from PType where usercode=@PUserCode
--仓库
select @ktypeid=typeid from Stock where usercode=@KUserCode
--货位
select @cargoid=cargoid from CargoType where usercode=@CUserCode

-----导入的相关验证--------------

------------------------------------------------------------------------商品------------------------
IF(@PUserCode = '')
BEGIN
	SET @ErrMsg = '商品编号不能为空'
	RETURN -1
END
ELSE IF @PUserCode <> '' AND NOT EXISTS(SELECT TOP 1 UserCode FROM dbo.ptype WHERE UserCode = @PUserCode) 
	BEGIN
		SET @ErrMsg = '商品编号填写不正确！'
		RETURN -1
	END
ELSE IF @PFullName <> '' AND NOT EXISTS(SELECT TOP 1 UserCode FROM dbo.ptype WHERE FullName = @PFullName) 
	BEGIN
		SET @ErrMsg = '商品名称填写不正确！'
		RETURN -1
	END	
ELSE IF(@PFullName NOT IN (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @PUserCode) AND @PFullName <> '' AND @PUserCode <> '')
		BEGIN
			SET @ErrMsg = '商品编号与商品名称不匹配'
			RETURN -1
		END


---------------------------------------------------------------------------分支机构---------------------------------------------------------------	
---A8分支机构必填

IF(@proinfo=2)
BEGIN
IF(@Stypeid = '')
    BEGIN
	   SET @ErrMsg = '分支机构编号不能为空'
	   RETURN -1
    END
ELSE IF(@Stypeid <> '')AND  NOT EXISTS(SELECT TOP 1 UserCode FROM dbo.SType WHERE UserCode = @SUserCode OR @SUserCode='0') 
   BEGIN
		SET @ErrMsg = '分支机构编号填写不正确'
		RETURN -1
	END
ELSE IF (@SFullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.SType WHERE FullName = @SFullName) OR @SFullName='总部')
		BEGIN
			SET @ErrMsg = '分支机构名称填写不正确'
			RETURN -1
		END
ELSE IF(@SFullName NOT IN (SELECT TOP 1 fullname FROM dbo.SType WHERE UserCode = @SUserCode) AND @SFullName <> '' AND @SUserCode <> '')
		BEGIN
			SET @ErrMsg = '分支机构编号与分支机构名称不匹配'
			RETURN -1
		END
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE UserCode = @SUserCode AND sonnum > 0)
		BEGIN
			SET @ErrMsg = '该分支机构为父类'
			RETURN -1
		END
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE UserCode = @SUserCode AND deleted = 1)
		BEGIN
			SET @ErrMsg = '该分支机构已停用'
			RETURN -1
		END
END

--------------------------------------------------------------------------仓库---------------------------------------------------------

IF(@Ktypeid = '')
BEGIN
	SET @ErrMsg = '默认仓库编号不能为空'
	RETURN -1
END	
ELSE IF (@Ktypeid <> '') AND NOT EXISTS(SELECT TOP 1 UserCode FROM dbo.Stock WHERE UserCode = @KUserCode) 
	BEGIN
		SET @ErrMsg = '仓库编号填写不正确！'
		RETURN -1
	END
ELSE IF (@KFullName <> '') AND NOT EXISTS(SELECT TOP 1 UserCode FROM dbo.Stock WHERE FullName = @KFullName) 
	BEGIN
		SET @ErrMsg = '仓库名称填写不正确！'
		RETURN -1
	END
ELSE IF(@KFullName NOT IN (SELECT TOP 1 fullname FROM dbo.Stock WHERE UserCode = @KUserCode) AND @KFullName <> '' AND @KUserCode <> '')
		BEGIN
			SET @ErrMsg = '仓库编号与仓库名称不匹配'
			RETURN -1
		END
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Stock WHERE UserCode = @KUserCode AND sonnum > 0)
		BEGIN
			SET @ErrMsg = '该仓库为父类'
			RETURN -1
		END
IF EXISTS(SELECT TOP 1 1 FROM dbo.Stock WHERE UserCode = @KUserCode  AND deleted = 1)
		BEGIN
			SET @ErrMsg = '该仓库已停用'
			RETURN -1
		END
------------------------------------------------------------------------------------------------------------------------------------------
	
IF(@proinfo=2)---A8才判断
BEGIN	
       DECLARE @stypeid1 [varchar](50)='0'        
          select @stypeid1=stypeid from dbo.Stock where usercode=@KUserCode  --仓库对应的分支机构     
          if(@stypeid1<>@stypeid)
          BEGIN
          SET @ErrMsg = '默认仓库信息与填入的分支机构不匹配！'
          RETURN -1
          END
END
-------1:启用货位,货位不为空---------
IF(@value = 1 and @CUserCode <> '')
 BEGIN
 
         IF EXISTS(SELECT TOP 1 1 FROM dbo.CargoType WHERE UserCode = @CUserCode  AND deleted = 1)
		 BEGIN
			SET @ErrMsg = '该货位已停用'
			RETURN -1
		 END
		 
		 IF  NOT EXISTS(SELECT TOP 1 UserCode FROM dbo.CargoType WHERE UserCode = @CUserCode) 
		BEGIN
		SET @ErrMsg = '货位编号填写不正确！'
		RETURN -1
		END
		
		 IF @CFullName <> '' AND  NOT EXISTS(SELECT TOP 1 UserCode FROM dbo.CargoType WHERE FullName = @CFullName) 
		BEGIN
		SET @ErrMsg = '货位名称填写不正确！'
		RETURN -1
		END
		
		IF(@CFullName NOT IN (SELECT TOP 1 fullname FROM dbo.CargoType WHERE UserCode = @CUserCode) AND @CFullName <> '' AND @CUserCode <> '')
		BEGIN
			SET @ErrMsg = '货位编号与货位名称不匹配'
			RETURN -1
		END
		
          DECLARE @ktypeid1 [varchar](50)='0'        
          select @ktypeid1=ktypeid from CargoType where usercode=@CUserCode  --货位对应的默认仓库     
          if(@ktypeid1<>@ktypeid)
          BEGIN
          SET @ErrMsg = '默认货位信息与填入的默认仓库不匹配！'
          RETURN -1
          END
           -----如果存在同样的数据----
 
         IF EXISTS(SELECT TOP 1 CargoId FROM DefaultStock WHERE StypeId= @stypeid AND Ktypeid=@ktypeid AND Ptypeid=@ptypeid AND cargoid=@cargoid)
         BEGIN
         SET @ErrMsg = '导入的该条信息已存在！'
		 RETURN -1
         END
          
 END
    --启用货位，货位为空时，
  --IF(@value = 1 and @CUserCode = '')
  --    BEGIN
  --         SET @ErrMsg = '默认货位信息为空则不导入！'
		--   RETURN -1     
  --    END

 
--启用货位，货位为空时，导入该分支机构的默认仓库的默认货位
--IF(@value = 1 and @CUserCode = '')
-- BEGIN
--      select @cargoid=cargoid  from cargotype c left join Stock s on s.typeid=c.ktypeid 
--      where  s.usercode=@KUserCode and c.isdefault=1 
--      and s.stypeid=(select typeid from stype where usercode=@SUserCode)   
-- END
----------不启用货位,提示不填入默认货位-------------------------------------------------------------
 IF(@value <> 1)
 BEGIN
    IF(@CUserCode<>'' OR @CFullName<>'' )
    BEGIN
       SET @ErrMsg = '未启用货位，不能填写默认货位！'
		   RETURN -1     
    END

 --------2:不启用货位，此时的货位信息应该为对应的分支机构下该默认仓库的默认货位--------------    
    IF(@CUserCode = '')
    BEGIN
      select @cargoid=cargoid  from cargotype c left join Stock s on s.typeid=c.ktypeid 
      where  s.usercode=@KUserCode and c.isdefault=1 
      and s.stypeid=@stypeid  
     END
     
    IF EXISTS(SELECT TOP 1 CargoId FROM DefaultStock WHERE StypeId= @stypeid AND Ktypeid=@ktypeid AND Ptypeid=@ptypeid AND cargoid=@cargoid)
         BEGIN
         SET @ErrMsg = '导入的该条信息已存在！'
		 RETURN -1
         END
 END    
---------------------------------------写入默认仓库表---------------------------

BEGIN TRAN insertproc


IF NOT EXISTS(SELECT TOP 1 CargoId FROM DefaultStock WHERE StypeId= @stypeid AND Ptypeid=@ptypeid)
BEGIN
INSERT INTO [DefaultStock] 
  ( 
  [StypeId],
  [Ktypeid],
  [Ptypeid],
  [CargoId]
 
 )  
VALUES 
 ( 
 @stypeid,
 @ktypeid,
 @ptypeid,
 @cargoid
 )

 IF @@ROWCOUNT=0 
    BEGIN
	ROLLBACK TRAN insertproc 
	 SET @ErrMsg = '新增数据失败！'
	RETURN -1
    END
END
ELSE 

    update DefaultStock SET CargoId=@cargoid ,Ktypeid=@ktypeid
    where StypeId= @stypeid  AND Ptypeid=@ptypeid


 COMMIT TRAN insertproc

GO



	IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ImportDepartment]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ImportDepartment]
GO

/****** Object:  StoredProcedure [dbo].[Gp_ImportD]    Script Date: 05/25/2011 09:05:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	Create by ：	Haiyang Li
	Date：				2012-07-31
	Description:  部门基本信息导入
*/
CREATE PROCEDURE [dbo].[GP_ImportDepartment]
    (
      @DFullName VARCHAR(100) ,
      @UserCode VARCHAR(100) ,
      @FullName VARCHAR(100) ,
      @Name VARCHAR(100) ,
      @PinyinCode VARCHAR(201) ,
      @Tel VARCHAR(50) ,
      @Fax VARCHAR(50) ,
      @LinkMan VARCHAR(50) ,
      @Comment VARCHAR(100) ,
      @ErrMsg VARCHAR(200) OUTPUT
    )
--@encode$--    
AS 
    SET NOCOUNT ON
-------------------------------------转换输入参数---------------------------------------------
		-- 拼音码长度
    /*IF ( ( SELECT   DATALENGTH(@PinyinCode)
         ) > 200 ) 
        BEGIN
            SET @ErrMsg = '拼音码的长度大于最大允许长度200'
            RETURN -1
        END
*/

		--父类存在性验证
    DECLARE @Parid VARCHAR(50)
    IF ( @DFullName = '' ) 
        BEGIN
            SET @Parid = '00000'
        END
    ELSE 
        BEGIN
            IF NOT EXISTS ( SELECT TOP 1
                                    typeid
                            FROM    dbo.Department
                            WHERE   fullname = @DFullName ) 
                BEGIN
                    SET @ErrMsg = '父类名称不存在'
                    RETURN -1
                END
            ELSE 
                BEGIN
                    BEGIN
                        SET @Parid = ( SELECT TOP 1
                                                typeid
                                       FROM     Department
                                       WHERE    fullname = @DFullName
                                     )
                    END
                END	
        END

    IF ( @UserCode = '' ) 
        BEGIN
            SET @ErrMsg = '部门编号不能为空'
            RETURN -1
        END

    IF ( @FullName = '' ) 
        BEGIN
            SET @ErrMsg = '部门全名不能为空'
            RETURN -1
        END

-- 获取拼音码
    IF ( @PinyinCode = '' ) 
        BEGIN
            SELECT  @PinyinCode = dbo.fun_getPY(@FullName)
        END
----------------------------------------------------------------------------------------------

    DECLARE @nReturntype INT ,
        @EtypeId_1 VARCHAR(50) ,
        @nSoncount INT ,
        @nSonnum INT ,
        @leveal SMALLINT
		-- 根据id 获取父类名称
    DECLARE @parFullName VARCHAR(200)
    SET @parFullName = ( SELECT TOP 1
                                fullname
                         FROM   department
                         WHERE  typeid = @parid
                       )

-- 判断停用不能分类
    DECLARE @deleted INT
    SELECT  @deleted = deleted
    FROM    department
    WHERE   typeId = @Parid
    IF ( @deleted = 1 ) 
        BEGIN
            SET @ErrMsg = '该部门【' + @parFullName + '】已经被停用，不能分类'
            RETURN -1	
   --RAISERROR('该部门【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
        END

-- 经营历程
    IF EXISTS ( SELECT  TOP 1 1
                FROM    Billindex
                WHERE   DTypeID = @parid ) 
        BEGIN
		--print '['+@FullName+']分支机构已经经营过，不能分类'
            SET @ErrMsg = '该部门【' + @parFullName + '】存在经营历程或已经在职员信息中使用，不能分类'
            RETURN -1
		-- RAISERROR('该部门【%s】存在经营历程或已经在职员信息中使用，不能分类',16,1,@parFullName)return--return -301
        END 

		-- 判断部门信息是否被职员信息使用过：若有使用，禁止分类
    IF EXISTS ( SELECT  TOP 1 1
                FROM    employee
                WHERE   DtypeID = @Parid ) 
        BEGIN
            SET @ErrMsg = '该部门【' + @parFullName + '】已经在职员信息中使用，不能分类'
            RETURN -1
		-- RAISERROR('该部门【%s】已经在职员信息中使用，不能分类',16,1,@parFullName)RETURN
        END
		
		-- 已经在充值单中使用
    IF EXISTS ( SELECT  TOP 1 1
                FROM    nVipConfiscateConfig
                WHERE   DTypeID = @Parid )
        OR EXISTS ( SELECT  *
                    FROM    nVipWashCarTimesConfig
                    WHERE   DTypeID = @Parid ) 
        BEGIN
        --print '2555'
            SET @ErrMsg = '该部门【' + @parFullName + '】已经在充值单中使用，不能分类'
            RETURN -1
		-- RAISERROR('该部门【%s】已经在充值单中使用，不能分类',16,1,@parFullName)RETURN
        END

		-- 关联销售计划
    IF EXISTS ( SELECT  TOP 1 1
                FROM    DtypeSaleplan
                WHERE   DTypeID = @Parid ) 
        BEGIN
        --print '2555'
            SET @ErrMsg = '该部门【' + @parFullName + '】已经在销售计划中使用，不能分类'
            RETURN -1
        END
		-- 使用登记单
    IF EXISTS ( SELECT  TOP 1 1
                FROM    CM_CarUseIndex
                WHERE   DTypeID = @Parid ) 
        BEGIN
        --print '2555'
            SET @ErrMsg = '该部门【' + @parFullName + '】已经在使用登记单中使用，不能分类'
            RETURN -1
        END
		-- 车辆费用单
    IF EXISTS ( SELECT  TOP 1 1
                FROM    CM_FeeIndex
                WHERE   DTypeID = @Parid ) 
        BEGIN
        --print '2555'
            SET @ErrMsg = '该部门【' + @parFullName + '】已经在车辆费用单中使用，不能分类'
            RETURN -1
        END
		-- 订单中使用
    IF EXISTS ( SELECT  TOP 1 1
                FROM    OrderIndex
                WHERE   DTypeID = @parid ) 
        BEGIN
		-- print '订单用过'
            SET @ErrMsg = '该部门【' + @parFullName + '】已在订单中使用，不能分类'
            RETURN -1
		-- RAISERROR('该部门【%s】已在订单中使用，不能分类',16,1,@parFullName)return--return -501
        END
        
    -- 借欠单据使用
    IF EXISTS ( SELECT  TOP 1 1
                FROM    LendIndex
                WHERE   DTypeID = @parid ) 
        BEGIN
		-- print '借欠用过'
            SET @ErrMsg = '该部门【' + @parFullName + '】已在借欠单种使用，不能分类'
            RETURN -1
		--RAISERROR('该部门【%s】已在借欠单种使用，不能分类',16,1,@parFullName)return--return -502
        END
        
    -- 发票开单使用过
    IF EXISTS ( SELECT  TOP 1 1
                FROM    FapiaoBillIndex
                WHERE   DTypeID = @parid ) 
        BEGIN
		-- print '发票开单'
            SET @ErrMsg = '该部门【' + @parFullName + '】作为发票开单的部门，不能分类'
            RETURN -1
		--RAISERROR('该部门【%s】作为发票开单的部门，不能分类',16,1,@parFullName)return--return -511
        END



-- 获得新的ID号
DECLARE @DbName [varchar](30) = 'DepartMent'
    EXEC @nReturntype = Gp_createId @ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
    IF @nReturntype = -1 
        BEGIN
            SET @ErrMsg = '部门的分类不能超过10层'
            RETURN -1
		--RAISERROR('部门的分类不能超过10层',16,1)return--return -1
        END
    IF @nReturntype = -2 
        BEGIN
            SET @ErrMsg = '无法添加基本信息'
            RETURN -1
		--RAISERROR('无法添加基本信息',16,1)return--return -2
        END
    
		-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TOP 1 1
                FROM    [DepartMent]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @usercode
                             AND deleted <> 1
                           )
                        OR ( fullname = @fullname
                             AND deleted <> 1
                           ) ) 
        BEGIN
		--print '['+@usercode+']部门已经存在'
            SET @ErrMsg = '【' + @FullName + '】名称或编号不能与已有的名称或编号重复，不能分类'
            RETURN -1
		--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复，不能分类',16,1,@FullName)return--return -303
        END
    
		-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TOP 1 1
                FROM    [DepartMent]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @fullname
                             AND deleted <> 1
                           )
                        OR ( fullname = @usercode
                             AND deleted <> 1
                           ) ) 
        BEGIN
	--print '['+@usercode+']分支机构已存在'
            SET @ErrMsg = '【' + @FullName + '】名称或编号不能与已有的名称或编号重复，不能分类'
            RETURN -1
	--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复，不能分类',16,1,@FullName)return--return -303
        END

-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TOP 1 1
                FROM    [DepartMent]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @usercode
                             AND deleted = 1
                           )
                        OR ( fullname = @fullname
                             AND deleted = 1
                           ) ) 
        BEGIN
	--print '['+@usercode+']分支机构已存在'
            SET @ErrMsg = '【' + @FullName + '】名称或编号不能与已有的名称或编号重复，不能分类'
            RETURN -1
	--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复，不能分类',16,1,@FullName)return--return -303
        END
-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TOP 1 1
                FROM    [DepartMent]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @fullname
                             AND deleted = 1
                           )
                        OR ( fullname = @usercode
                             AND deleted = 1
                           ) ) 
        BEGIN
	--print '['+@usercode+']分支机构已存在'
            SET @ErrMsg = '【' + @FullName + '】名称或编号不能与已有的名称或编号重复，不能分类'
            RETURN -1
	--RAISERROR('【%s】名称或编号不能与已有的名称或编号重复，不能分类',16,1,@FullName)return--return -303
        END




/*
-- 判断分支机构的最大使用数量
declare @nCount int
select @nCount=Count(*) from DepartMent 
where sonnum = 0 
 and deleted=0
if @nCount > 10
begin
-- print '分支机构数量大于10'
 return -99
end
*/

    DECLARE @returnPym VARCHAR(1000)
    EXEC @returnPym = fun_getPy @FullName

    IF @PinyinCode <> '' 
        SET @returnPym = @PinyinCode

    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    DepartMent
    WHERE   typeid = @Parid
    SELECT  @leveal = @leveal + 1
    INSERT  INTO [DepartMent]
            ( [typeId] ,
              [Parid] ,
              [leveal] ,
              [soncount] ,
              [sonnum] ,
              [FullName] ,
              [Name] ,
              [UserCode] ,
              [Comment] ,
              [LinkMan] ,
              [Tel] ,
              [Fax] ,
              [PyCode]
            )
    VALUES  ( @EtypeId_1 ,
              @Parid ,
              @leveal ,
              0 ,
              0 ,
              @FullName ,
              @name ,
              @UserCode ,
              @Comment ,
              @LinkMan ,
              @Tel ,
              @Fax ,
              @returnPym
            )
    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
    ELSE 
        BEGIN
            UPDATE  [DepartMent]
            SET     sonnum = @nSonnum + 1 ,
                    soncount = @nSoncount + 1
            WHERE   typeid = @Parid
        END
--添加默认货位
DECLARE @CargoFullName VARCHAR(200)
SET @CargoFullName = @FullName + N'默认货位'
EXEC dbo.Gp_CargoTypeEdit @CargoID = 0, -- int
    @UserCode = @CargoFullName, -- nvarchar(200)
    @FullName = @CargoFullName, -- nvarchar(200)
    @KtypeID = @EtypeId_1, -- nvarchar(50)
    @Comment = '', -- varchar(500)
    @isDefault = 0, -- int
    @ControlType = '' -- varchar(20)



--修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    Department
    UPDATE  Department
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @EtypeId_1
 
    COMMIT TRAN insertproc
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ImportE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_ImportE]
GO
/****** Object:  StoredProcedure [dbo].[Gp_ImportE]    Script Date: 05/25/2011 09:10:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO





/*
	作者：廖晨羽
	日期：2011-08-18
	描述：用于导入职员信息
*/



CREATE   PROCEDURE [dbo].[Gp_ImportE]
(
 @EFullName   [varchar](66),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @PyCode   varchar(201),
 @Department  [varchar](100),
 @SFullName varchar(66),
 @StrMaxPre   VARCHAR(18),
 @Comment  [varchar](257),
 @Mob varchar (50),
 @Tel   [varchar](20),
 @Tel2 varchar (50),
 @Mail varchar (50),
 @Informer varchar (20),
 @PostCode varchar (10),
 @Address  [varchar](66),
 @QQ varchar(50),
 @MSN varchar(50),
 @mBlog varchar(200),
 @Blog varchar(200),
 @StrSex VARCHAR(10),
 @Nation varchar(20),
 @StrBirthDay VARCHAR (200),
 @StrJobtime VARCHAR(200),
 @StrStature VARCHAR(16),
 @StrWeight VARCHAR(16),
 @Blood varchar(20),
 @Health varchar(257),
 @Job varchar (50),
 @Job2 varchar (50),
 @College varchar (50),
 @Knowledge varchar(20),
 @Speciality varchar (50),
 @Com_level varchar (20),
 @For_language varchar (20),
 @For_lan_level varchar (20),
 @Nat_place varchar (20),
 @Political varchar (20),
 @StrMarriage VARCHAR(4),
 @Fam_status varchar (50),
 @IDCard varchar(50),
 @Reg_place varchar (50),
 @ReturnID  VARCHAR(100) output,
 @ErrMsg VARCHAR(200) output
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

IF ((SELECT DATALENGTH(@PyCode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@comment)) > 256)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Health)) > 256)
BEGIN
	SET @ErrMsg = '健康状况的长度大于最大允许长度256'
	RETURN -1
END

DECLARE @DbName		[varchar](30) = 'employee'
DECLARE	@BtypeID [varchar](50) = '00000'
DECLARE @Team varchar(200) = NULL 
DECLARE @tichengRate  NUMERIC(24, 10)   = 0

DECLARE @Parid VARCHAR(50)
IF (@EFullName = '' OR @EFullName = '超级用户')
BEGIN
	SET @Parid = '00001'
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.employee WHERE fullname = @EFullName) OR @EFullName = 'root'
	BEGIN
		SET @ErrMsg = '父类名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SET @Parid = (SELECT TOP 1 typeid FROM dbo.employee WHERE fullname = @EFullName)
	END	
END
IF((select COUNT(typeId)  from btype where etypeId = @Parid) > 0)
BEGIN
	SET @ErrMsg = '该父类职员已关联往来单位，不能进行分类操作'
	RETURN -1
END


IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '职员编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '职员姓名不能为空'
	RETURN -1
END

IF(@Pycode = '')
BEGIN
	SELECT @Pycode = dbo.fun_getPY(@FullName)
END

DECLARE @DtypeID VARCHAR(50)
IF (@Department = '')
BEGIN
	SET @ErrMsg = '部门名称不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.Department WHERE FullName = @Department) OR @Department = '所有部门'
	BEGIN
		SET @ErrMsg = '部门名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PDtypeId VARCHAR(50)
		DECLARE @DChildCount NUMERIC(18,0)
		SET @PDtypeId = (SELECT TOP 1 typeid FROM dbo.Department WHERE fullname = @Department)
		SELECT @DChildCount = COUNT(*) FROM dbo.Department WHERE typeId LIKE @PDtypeId + '%' AND typeId <> @PDtypeId
		IF (@DChildCount = 0)
			BEGIN
				SET @DtypeID = @PDtypeId
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该部门是父节点'
				RETURN -1
			END
	END	
END

DECLARE @STypeID varchar(50)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF (@SFullName = '')
	BEGIN
		SET @ErrMsg = '分支机构名称不能为空'
		RETURN -1
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.SType WHERE FullName=@SFullName) OR @SFullName = '总部'
		BEGIN
			SET @ErrMsg = '该分支机构不存在'
			RETURN -1
		END
		ELSE
		BEGIN
			DECLARE @PStypeId VARCHAR(50)
			DECLARE @SChildCount NUMERIC(18,0)
			SET @PStypeId = (SELECT TOP 1 typeid FROM dbo.SType WHERE fullname = @SFullName)
			SELECT @SChildCount = COUNT(*) FROM dbo.SType WHERE typeId LIKE @PStypeId + '%' AND typeId <> @PStypeId
			IF (@SChildCount = 0)
				BEGIN
					SET @STypeID = @PStypeId
				END
			ELSE
				BEGIN
					SET @ErrMsg = '该分支机构是父类'
					RETURN -1
				END
		END	
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

IF EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

DECLARE @MaxPre  NUMERIC(24, 10) 
IF (@StrMaxPre = '')
BEGIN
	SET @MaxPre = -999999999918.99
END
ELSE IF(ISNUMERIC(@StrMaxPre) <> 1)
BEGIN
	SET @ErrMsg = '每单优惠限额请输入数字'
	RETURN -1
END
ELSE
BEGIN
	SELECT @MaxPre = CONVERT( NUMERIC(24, 10) , @StrMaxPre)
END
IF (@MaxPre > 1000)
BEGIN
	SET @ErrMsg = '每单优惠限额最大1000'
	RETURN -1
END

DECLARE @Sex BIT
SELECT @StrSex = CASE @StrSex 
							WHEN '' THEN '1'
							WHEN '男' THEN '1' 
							WHEN '女' THEN '0'
							ELSE '无'			
					END
IF(@StrSex = '无')
BEGIN
	SET @ErrMsg = '性别请输入男或女'
	RETURN -1
END
ELSE
BEGIN
	SET @Sex = CONVERT(BIT, @StrSex)
END

DECLARE	@BirthDay DATETIME
IF (@StrBirthDay = '')
BEGIN
	SELECT @BirthDay = '2050-1-1'
END
ELSE IF (ISDATE(@StrBirthDay) <> 1 )
	 BEGIN
 		SET @ErrMsg = '出生日期请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	 END
ELSE
BEGIN
	SET @BirthDay = @StrBirthDay
END

DECLARE	@Jobtime DATETIME
IF (@StrJobtime = '')
BEGIN
	SELECT @Jobtime = '2050-1-1'
END
ELSE IF (ISDATE(@StrJobtime) <> 1 )
	 BEGIN
 		SET @ErrMsg = '到岗时间请输入日期,请使用YYYY-MM-DD的格式'
		RETURN -1
	 END
ELSE
BEGIN
	SET @Jobtime = @StrJobtime
END


DECLARE @Stature  NUMERIC(24, 10) 
IF (@StrStature = '')
BEGIN
	SET @Stature = NULL
END
ELSE IF(ISNUMERIC(@StrStature) <> 1)
BEGIN
	SET @ErrMsg = '身高请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrStature)) <> 0)
BEGIN
	SET @ErrMsg = '身高不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @Stature = CONVERT( NUMERIC(24, 10) , @StrStature)
END

DECLARE @Weight  NUMERIC(24, 10) 
IF (@StrWeight = '')
BEGIN
	SET @Weight = NULL
END
ELSE IF(ISNUMERIC(@StrWeight) <> 1)
BEGIN
	SET @ErrMsg = '体重请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrWeight)) <> 0)
BEGIN
	SET @ErrMsg = '体重不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @Weight = CONVERT( NUMERIC(24, 10) , @StrWeight)
END


DECLARE @Marriage BIT
SELECT @Marriage = CASE @StrMarriage 
							WHEN '已婚' THEN 1 
							WHEN '离异' THEN 2
							ELSE 0			
					END

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

declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from employee where typeid=@parid)
--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(select subvalue from sysdata where subname='ifqp')

--部门不存在
if not exists(select typeid from department where typeid=@dtypeid)
BEGIN
	SET @ErrMsg = '所选部门不存在，请另选一个部门'
	RETURN -1	
	--RAISERROR('所选部门不存在，请另选一个部门',16,1)return
end

--判断停用不能分类
declare @deleted INT
select @deleted=deleted from employee where typeId=@Parid
if(@deleted=1)
BEGIN
   SET @ErrMsg = '该职员【' + @parFullName + '】已经被停用，不能分类'
   RETURN -1	
   --RAISERROR('该职员【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
end

-- 职员已经使用
if exists(select etypeid from billindex where etypeId=@parid   and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 

--车辆信息使用
if exists(select Driver from CM_CarInfo where Driver=@parid)
begin
   -- print'25555'
	SET @ErrMsg = '该职员【'+@parFullName+'】已经使用过，不能分类'
	RETURN -1	
end 

if exists(select ETypeID from PerformanceDistribution where ETypeID=@parid)
begin
   -- print'25555'
   SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
   RETURN -1
   --RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 

if exists(select ReceptionId from Billindex_CarRepair where ReceptionId=@parid)
begin
   -- print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
--关联pos
if exists(select etypeid from CommonPosInfo where etypeid1=@parid)
begin
   -- print'25555'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
--关联维修业务调度中的负责人
if exists(select ItemPrincipal from Billindex_CarRepair where ItemPrincipal=@parid)
begin
    --print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
if exists(select MonitorPrincipal from Billindex_CarRepair where MonitorPrincipal=@parid)
begin
    --print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
--维修工
if exists(select ETypeId from Qp_AttemperBill_RepairItemsPerson where ETypeId=@parid)
begin
    --print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 

--关联销售计划
if exists(select ETypeId from EtypeSaleplan where ETypeId=@parid)
begin
    --print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联销售计划，不能分类'
    RETURN -1
	--RAISERROR('该职员【%s】已经关联销售计划，不能分类',16,1,@parFullName)return--return -9
end 

--使用登记单
if exists(select ETypeId from CM_CarUseIndex where ETypeId=@parid)
 OR EXISTS(select Driver from CM_CarUseBill where Driver=@parid)
 OR EXISTS(select ETypeId from CM_CarUseBill where ETypeId=@parid)
begin
    --print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联使用登记单，不能分类'
    RETURN -1
end 
--车辆费用单
if exists(select ETypeId from CM_FeeIndex where ETypeId=@parid)
begin
    --print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联车辆费用单，不能分类'
    RETURN -1
end 

if exists(select ETypeId from RequestIndex where ETypeId=@parid)
begin
    --print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联请购单，不能分类'
    RETURN -1
	--RAISERROR('该职员【%s】已经关联请购单，不能分类',16,1,@parFullName)return--return -9
end 

if exists(select ETypeId from RequestBill where ETypeId=@parid)
begin
    --print'25555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联请购单，不能分类'
    RETURN -1
	--RAISERROR('该职员【%s】已经关联请购单，不能分类',16,1,@parFullName)return--return -9
END

if exists(select UnitSatrap from Billindex_CarRepair where UnitSatrap=@parid)
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
if exists(select etypeid from billindex where checke =@parid  and checke<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select checke from dbo.DiyIndex where checke =@parid  and checke<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select etypeid from wx_bill_jiejian where Etypeid =@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 


if exists(select etypeid from wx_bill_call where etypeid =@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select checke from nVipAdjust where checke=@parid and checke<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
END
if exists(select wxmanID from billindex where wxmanID =@parid  and wxmanID<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select ETypeID from Qp_SuccorBill_RepairItems where ETypeID =@parid)
begin
   -- print '2555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
--工具入出库台帐
if exists(select ETypeID from ToolIndex where ETypeID =@parid)
begin
   -- print '2555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
--储值快速充值单

if exists(select ETypeID from nVipConfiscateConfig where ETypeID =@parid)
begin
    --print '2555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
 if exists(select ETypeID from nVipWashCarTimesConfig where ETypeID =@parid)
begin
    --print '3555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

--电脑配置
 if EXISTS (select ETypeID from dbo.DiyIndex where ETypeID =@parid)
begin
    --print '3555'
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
  
if exists(select Etypeid from wx_bill_jiejian where Etypeid =@parid  and Etypeid<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select etypeid from OrderIndex where etypeId=@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已被订单使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已在订单中使用，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已在订单中使用，不能分类',16,1,@parFullName)return---return -501
end 
if exists(select etypeid from OrderIndex where checke=@parid  and checke<>'00001')
begin
	--print '['+@FullName+']职员已被订单使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已在订单中使用，不能分类'
    RETURN -1	
	--RAISERROR('该职员【%s】已在订单中使用，不能分类',16,1,@parFullName)return---return -501
end 

if exists(select etypeid from LendIndex where etypeId=@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已被借欠使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已在借欠单中使用，不能分类'
    RETURN -1
	--RAISERROR('该职员【%s】已在借欠单中使用，不能分类',16,1,@parFullName)return--return -502
end 

IF EXISTS(select etypeid from nVipAdjust WHERE etypeid=@parid)
BEGIN
		SET @ErrMsg = '该职员【' + @parFullName + '】已在会员卡消费调整或者积分中进行处理，不能分类'
		RETURN -1
		--RAISERROR('该职员【%s】已在会员卡消费调整或者积分中进行处理，不能分类',16,1,@parFullName)return--return -502		
END

if exists(select etypeid from LendIndex where checke=@parid  and checke<>'00001')
begin
	--print '['+@FullName+']职员已被借欠使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已在借欠单中使用，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已在借欠单中使用，不能分类',16,1,@parFullName)return--return -502
end 
if exists(select etypeid from RepairEngage where (etypeId=@parid  and etypeid<>'00001') OR (etypeId1=@parid  and etypeid1<>'00001') or (checke=@parid  and checke<>'00001'))
begin
	--print '['+@FullName+']职员已被维修使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已在维修单中使用，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已在维修单中使用，不能分类',16,1,@parFullName)return--return -503
end

IF EXISTS(select CreatorTypeID from crm_Schedule WHERE CreatorTypeID=@parid  AND CreatorTypeID<>'00001')
BEGIN
	--print '职员有日程，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已在日程中使用，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已在日程中使用，不能分类',16,1,@parFullName)return--RETURN -504
END
IF EXISTS(select SenderTypeID,ReceiverTypeID,CreatorTypeID from crm_Message WHERE (SenderTypeID=@parid AND SenderTypeID<>'00001') OR (ReceiverTypeID=@parid and ReceiverTypeID<>'00001')  or (CreatorTypeID=@parid AND CreatorTypeID<>'00001'))
BEGIN
	--print '职员有日程给抄送，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已在日程中使用，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已在日程中使用，不能分类',16,1,@parFullName)return--RETURN -504
END
IF EXISTS(select SenderTypeID,ReceiverTypeID,CreatorTypeID from crm_MessageNoread WHERE (SenderTypeID=@parid AND SenderTypeID<>'00001') OR (ReceiverTypeID=@parid and ReceiverTypeID<>'00001')  or (CreatorTypeID=@parid AND CreatorTypeID<>'00001'))
BEGIN
	--print '职员有日程给抄送，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已在日程中使用，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已在日程中使用，不能分类',16,1,@parFullName)return--RETURN -504
END

IF EXISTS(select createor from crm_Btype WHERE createor=@parid AND createor<>'00001')
BEGIN
	--print '职员有创建了CRM客户，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已创建了CRM客户，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已创建了CRM客户，不能分类',16,1,@parFullName)return--RETURN -505
END
IF EXISTS(select createor from crm_linkMan WHERE createor=@parid  AND createor<>'00001')
BEGIN
	--print '职员有创建了CRM联系人，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已创建了CRM联系人，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已创建了CRM联系人，不能分类',16,1,@parFullName)return--RETURN -506
END
--IF EXISTS(select EtypeId from InvoiceBill WHERE EtypeId=@parid)
--BEGIN
	--print '职员有发票经手人，不能分类'
	--RETURN -507
--END

IF EXISTS(select WriteId from PriceProtect WHERE WriteId=@parid  AND WriteId<>'00001')
BEGIN
	--print '职员有作为价保通知登记人，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】有价保通知，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】有价保通知，不能分类',16,1,@parFullName)return--RETURN -509
END

if exists(select etypeid from Advantage_standard where etypeId=@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已在返利标准中使用，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】作为返利标准的制作人，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】作为返利标准的制作人，不能分类',16,1,@parFullName)return--return -515
end 



IF EXISTS(select EtypeId from FapiaoBillIndex WHERE EtypeId=@parid AND EtypeId<>'00001')
BEGIN
	--print '职员有发票经手人，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】作为发票经手人，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】作为发票经手人，不能分类',16,1,@parFullName)return--RETURN -507
END
IF EXISTS(select Assessor from FapiaoBillIndex WHERE Assessor=@parid AND Assessor<>'00001')
BEGIN
	--print '职员有发票审核人，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】作为发票审核人或制单人，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】作为发票审核人或制单人，不能分类',16,1,@parFullName)return--RETURN -512
END
IF EXISTS(select checke from FapiaoBillIndex WHERE checke=@parid AND checke<>'00001')
BEGIN
	--print '职员有发票制单人，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】作为发票审核人或制单人，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】作为发票审核人或制单人，不能分类',16,1,@parFullName) RETURN ---512
END
IF EXISTS(select EtypeId from TcBillIndex WHERE EtypeId=@parid AND EtypeId<>'00001')
BEGIN
	--print '职员有提成规则单审核人，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】作为提成规则单制单人或审核人，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】作为提成规则单制单人或审核人，不能分类',16,1,@parFullName) RETURN--RETURN -513
END
IF EXISTS(select checke from TcBillIndex WHERE checke=@parid AND checke<>'00001')
BEGIN
	--print '职员有提成规则单制单人，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】作为提成规则单制单人或审核人，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】作为提成规则单制单人或审核人，不能分类',16,1,@parFullName) RETURN--RETURN -513
END
--提成可以选父节点
--if EXISTS(select EtypeID from tcbill WHERE EtypeID=@parid)
--BEGIN
	--print '职员有提成规则单制单人，不能分类'
	--RAISERROR('该职员【%s】作为提成规则业务员，不能分类',16,1,@parFullName) RETURN--RETURN -513		
--END
IF EXISTS(select * from nVipCardSign where Etypeid=@parid AND etypeid<>'00001')
BEGIN
	--print '职员有提成规则单制单人，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】作为会员卡的发卡人，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】作为会员卡的发卡人，不能分类',16,1,@parFullName) RETURN--RETURN -514
END

--已经是操作员的不能分类
if exists(select etypeid from loginuser where etypeId=@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员是操作员，不能分类'
	SET @ErrMsg = '该职员【' + @parFullName + '】已经是操作员，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已经是操作员，不能分类',16,1,@parFullName) RETURN--return -12
end 

if @ifqp='1'
begin
--在快修单中为维修工
	if exists (select RepairManTypeID from QP_QuickRepairBill_RepairItems where  RepairManTypeID=@parid and RepairManTypeID<>'00001')
	BEGIN
		   SET @ErrMsg = '该职员【' + @parFullName + '】作为快修单的修理工，不能分类'
		   RETURN -1
	       --RAISERROR('该职员【%s】作为快修单的修理工，不能分类',16,1,@parFullName) RETURN--  return  -371
	end
	if exists (select RepairManTypeID from QP_QuickRepairBill_PType where  RepairManTypeID=@parid and RepairManTypeID<>'00001')
	BEGIN
			SET @ErrMsg = '该职员【' + @parFullName + '】作为快修单的修理工，不能分类'
		    RETURN -1
	        --RAISERROR('该职员【%s】作为快修单的修理工，不能分类',16,1,@parFullName) RETURN-- return  -371
	end
	--维修人员工作组
	if exists (select etypeid from QP_WorkGroup_Person where  etypeid=@parid and etypeid<>'00001')
	BEGIN
		SET @ErrMsg = '该职员【' + @parFullName + '】已在人员工作组中使用过，不能分类'
		RETURN -1
		--RAISERROR('该职员【%s】已在人员工作组中使用过，不能分类',16,1,@parFullName) RETURN--return  -372
	end
	--洗车结算单洗车工
	if exists(select etypeid from QP_WashCarBill where etypeid=@parid and etypeid<>'00001')
	BEGIN
		SET @ErrMsg = '该职员【' + @parFullName + '】已在洗车结算单中使用过，不能分类'
		RETURN -1
		--RAISERROR('该职员【%s】已在洗车结算单中使用过，不能分类',16,1,@parFullName) RETURN--return -373
	end
end
--盘点单
if exists(select top 1 etypeid  from  StockCheckIndex where etypeid=@parid and etypeid<>'00001' )
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已在盘点单中使用过，不能分类'
	RETURN -1
	--RAISERROR('该职员【%s】已在盘点单中使用过，不能分类',16,1,@parFullName) RETURN--return -370
end
-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
BEGIN
	SET @ErrMsg = '职员的分类不能超过9层'
	RETURN -1
	--RAISERROR('职员的分类不能超过9层',16,1)return--return -1
end
if @nReturntype=-2 
BEGIN
	SET @ErrMsg = '无法添加基本信息'
	RETURN -1
	--RAISERROR('无法添加基本信息',16,1)return--return -2
end

-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted<>1) or (fullname=@fullname and fullname<>'超级用户' and deleted<>1))
begin
	--print '['+@usercode+']职员已存在'
	SET @ErrMsg = '该【' + @FullName + '】已经存在，职员编号或名称不能相同'
	RETURN -1
	--RAISERROR('该【%s】已经存在，职员编号或名称不能相同',16,1,@FullName)return--return -3
end


-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted<>1) or (fullname=@usercode and fullname<>'超级用户' and deleted<>1))
begin
	--print '['+@usercode+']职员已存在'
	SET @ErrMsg = '职员名称或编号不能与已有的名称或编号重复'
	RETURN -1
	--RAISERROR('职员名称或编号不能与已有的名称或编号重复',16,1)return--return -10
end

-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted=1) or (fullname=@fullname and fullname<>'超级用户' and deleted=1))
begin
	--print '['+@usercode+']职员已存在'
	SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称'
	RETURN -1
	--RAISERROR('该【%s】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称',16,1,@FullName) return--return -31
end

-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted=1) or (fullname=@usercode and fullname<>'超级用户' and deleted=1))
begin
	--print '['+@usercode+']职员已存在'
	SET @ErrMsg = '职员名称或编号不能与已停用的名称或编号重复'
	RETURN -1
	--RAISERROR('职员名称或编号不能与已停用的名称或编号重复',16,1) return--return -101
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

begin tran insertproc
select @leveal=leveal from employee where typeid=@Parid 
select @leveal=@leveal+1
INSERT INTO [employee] 
  ( 
	[typeId],
	  [Parid],
	  [leveal],
	  [soncount],
	  [sonnum],
	  [FullName],
	  [UserCode],
	  [Department],
	  [Tel],
	  [Address],
	  [Comment],
	  [BtypeID],
	[Sex],
	[Nation],
	[Knowledge],
	[Blood],
	[Health],
	[IDCard],
	[BirthDay],
	[Marriage],
	[Job],
	[Job2],
	[Jobtime],
	[Mob],
	[Mail],
	[Political],
	[Nat_place],
	[Tel2],
	[College],
	[For_language],
	[Reg_place],
	[Com_level],
	[Weight],
	[Stature],
	[Fam_status],
	[Informer],
	[Speciality],
	[For_lan_level],
	[PostCode],
	[PyCode],
	[DtypeID],
	[MaxPre],
	[tichengRate],
	[STypeID],
    [QQ],
	[MSN],
	[Blog],
	[mBlog],
	[Team]
)  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Department,
  @Tel,
  @Address,
  @Comment,
  @BtypeID,
@Sex,
@Nation,
@Knowledge,
@Blood,
@Health,
@IDCard,
@BirthDay,
@Marriage,
@Job,
@Job2,
@Jobtime,
@Mob,
@Mail,
@Political,
@Nat_place,
@Tel2,
@College,
@For_language,
@Reg_place,
@Com_level,
@Weight,
@Stature,
@Fam_status,
@Informer,
@Speciality,
@For_lan_level,
@PostCode,
@returnPym,
@DtypeID,
@MaxPre,
@tichengRate,
@STypeID,
@QQ,
@MSN,
@Blog,
@mBlog,
@Team
)
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [employee]
  set sonnum=@nSonnum+1,soncount=@nSoncount+1
  where typeid=@Parid
end
-- 建立超级用户的登录帐号
if @Parid='00000'
begin
 exec @nReturntype=Gp_AddNewLogin @EtypeId_1,1
 if @nReturntype=-1 return -1
 if @nReturntype=-2 return -2
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Employee
UPDATE Employee SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
commit tran insertproc


SET @ReturnID = @@ROWCOUNT


GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ImportEmployee]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_ImportEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Gp_ImportEmployee]    Script Date: 05/25/2011 09:10:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*
	修改者：周华
	日  期：2012-08-06
	描  述：导入职员信息 以前版本Gp_ImportE
*/
CREATE   PROCEDURE [dbo].[Gp_ImportEmployee]
(
 @Pusercode   [varchar](66),
 @Dusercode   [varchar](66),
 @EFullName   [varchar](66),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @PyCode   varchar(201),
 @Department  [varchar](100),
 @SFullName varchar(66),
 @StrMaxPre   VARCHAR(25),
 @tichengRate varchar(25),	--新增提成比例
 @buyerminvalue varchar(25),    --采购最低下限折扣值
 @saleminvalue varchar(25),	--销售最低下限折扣值
 @Comment  [varchar](257),
 @Mob varchar (50),
 @Tel   [varchar](20),
 @Tel2 varchar (50),
 @Mail varchar (50),
 @Informer varchar (20),
 @PostCode varchar (10),
 @Address  [varchar](66),
 @QQ varchar(50),
 @MSN varchar(50),
 @mBlog varchar(200),
 @Blog varchar(200),
 @StrSex VARCHAR(10),
 @Nation varchar(20),
 @StrBirthDay VARCHAR (200),
 @StrJobtime VARCHAR(200),
 @StrStature VARCHAR(16),
 @StrWeight VARCHAR(16),
 @Blood varchar(20),
 @Health varchar(257),
 @Job varchar (50),
 @Job2 varchar (50),
 @College varchar (50),
 @Knowledge varchar(20),
 @Speciality varchar (50),
 @Com_level varchar (20),
 @For_language varchar (20),
 @For_lan_level varchar (20),
 @Nat_place varchar (20),
 @Political varchar (20),
 @StrMarriage VARCHAR(4),
 @Fam_status varchar (50),
 @IDCard varchar(50),
 @Reg_place varchar (50),
 @ErrMsg VARCHAR(200) output,
 @DefaultSFullName VARCHAR(200),
      @tb TbType_BaseInfoCustom  READONLY ,--自定义属性
		@costom1              VARCHAR(600)=''         ,
		@costom2              VARCHAR(600)=''          ,
		@costom3              VARCHAR(600)=''          ,
		@costom4              VARCHAR(600)=''          ,
		@costom5              VARCHAR(600)=''          ,
		@costom6              VARCHAR(600)=''          ,
		@costom7              VARCHAR(600)=''          ,
		@costom8              VARCHAR(600)=''          ,
		@costom9              VARCHAR(600)=''          ,
		@costom10             VARCHAR(600)=''          ,
		@costom11             VARCHAR(600)=''          ,
		@costom12             VARCHAR(600)=''          ,
		@costom13             VARCHAR(600)=''          ,
		@costom14             VARCHAR(600)=''          ,
		@costom15             VARCHAR(600)=''          ,
		@costom16             VARCHAR(600)=''          
)
--@encode$--
AS
BEGIN
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
/*
IF ((SELECT DATALENGTH(@PyCode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@comment)) > 256)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度256'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Health)) > 256)
BEGIN
	SET @ErrMsg = '健康状况的长度大于最大允许长度256'
	RETURN -1
END
*/

DECLARE @DbName		[varchar](30) = 'employee'
DECLARE	@BtypeID [varchar](50) = '00000'
DECLARE @Team varchar(200) = NULL 
--DECLARE @tichengRate  NUMERIC(24, 10)   = 0
IF LTRIM(RTRIM(@tichengRate))=''
	SET @tichengRate='0';
ELSE
BEGIN
	IF CAST(@tichengRate AS  NUMERIC(24, 10) )>999.9999
	BEGIN
		SET @ErrMsg='提成比例应该小于等于999.9999';
		RETURN -1;
	END
	
	IF CAST(@tichengRate AS  NUMERIC(24, 10) )<0
	BEGIN
		SET @ErrMsg='提成比例不能小于0！';
		RETURN -1;
	END
	
	DECLARE 
	@percentage                VARCHAR(5),   --  百分比小数位数               7
	@percentage1               INT ;         --  百分比小数位数               7
	                          
	SELECT @percentage         = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 7
	SET @percentage1           = CONVERT(INT,@percentage)
	IF(dbo.F_CheckDecimal(@tichengRate,7,@percentage1) < 0)
	BEGIN
		SET @ErrMsg='提成比例值多于'+@percentage+'位小数'
		RETURN -1;
	END
	
END


DECLARE 
@d_discount                VARCHAR(5),   --  扣率小数位数               4
@d_discount1               INT ;         --  扣率小数位数               4
                          
SELECT @d_discount         = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 4
SET @d_discount1           = CONVERT(INT,@d_discount)
declare @buyerminvalue_temp NUMERIC(24, 10) ,
		@saleminvalue_temp NUMERIC(24, 10) 

SET @buyerminvalue =ISNULL(@buyerminvalue,0)
SET @saleminvalue = ISNULL(@saleminvalue,0)

--采购最低下限折扣值
IF (@buyerminvalue = '') 
	SET @buyerminvalue = NULL
ELSE IF(ISNUMERIC(@buyerminvalue) <> 1)
BEGIN
	SET @ErrMsg = '采购最低下限折扣请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @buyerminvalue)) <> 0)
BEGIN
	SET @ErrMsg = '采购最低下限折扣不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SET @buyerminvalue_temp = CONVERT( NUMERIC(24, 10) , @buyerminvalue)
	IF (@buyerminvalue_temp<0 OR @buyerminvalue_temp >1)
	BEGIN
		SET @ErrMsg = '采购最低下限折扣只能输入0-1的正数'
		RETURN -1
	END
	IF dbo.F_CheckDecimal(@buyerminvalue,4,@d_discount1) < 0
	BEGIN
		SET @ErrMsg='采购最低下限折扣值多于'+@d_discount+'位小数'
		RETURN -1;
	END	
END


IF (@saleminvalue = '') 
	SET @saleminvalue = NULL
ELSE IF(ISNUMERIC(@saleminvalue) <> 1)
BEGIN
	SET @ErrMsg = '销售最低下限折扣请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @saleminvalue)) <> 0)
BEGIN
	SET @ErrMsg = '销售最低下限折扣不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SET @saleminvalue_temp = CONVERT( NUMERIC(24, 10) , @saleminvalue)
	IF (@saleminvalue_temp<0 OR @saleminvalue_temp >1)
	BEGIN
		SET @ErrMsg = '销售最低下限折扣只能输入0-1的正数'
		RETURN -1
	END
	IF dbo.F_CheckDecimal(@saleminvalue,4,@d_discount1) < 0
	BEGIN
		SET @ErrMsg='销售最低下限折扣值多于'+@d_discount+'位小数'
		RETURN -1;
	END	
END



DECLARE @Parid VARCHAR(50)

IF ISNULL(@Pusercode,'')<>''
BEGIN
	IF EXISTS(SELECT TOP 1 typeid FROM dbo.employee WHERE USERCODE = @Pusercode and (usercode<>'admin' OR usercode<>'00000'))
	BEGIN
		SELECT TOP 1 @Parid =typeid FROM dbo.employee WHERE Usercode = @Pusercode
	END
	ELSE
	BEGIN
		SET @ErrMsg = '父类不存在,请检查父类编号是否有误！'
		RETURN -1
	END
END
ELSE
BEGIN
	IF (@EFullName = '' OR @EFullName = '超级用户')
		SET @Parid = '00001'
END


IF((select COUNT(typeId)  from btype where etypeId = @Parid) > 0)
BEGIN
	SET @ErrMsg = '该父类职员已关联往来单位，不能进行分类操作'
	RETURN -1
END


IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '职员编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '职员姓名不能为空'
	RETURN -1
END

SELECT @Pycode = dbo.fun_getPY(@FullName) WHERE @Pycode = ''

---9.91新增 父类名称编号、部门编号
IF ISNULL(@Dusercode,'')=''
BEGIN
	SET @ErrMsg = '部门编号不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF EXISTS(select 1 from Department WHERE usercode=@Dusercode and deleted=1)
	BEGIN
		SET @ErrMsg = '导入失败，该部门已被停用。'
		RETURN -1
	END
END

---END

DECLARE @DtypeID VARCHAR(50)
IF (@Department = '')
BEGIN
	SET @ErrMsg = '部门名称不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.Department WHERE FullName = @Department) OR @Department = '所有部门'
	BEGIN
		SET @ErrMsg = '部门名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PDtypeId VARCHAR(50)
		DECLARE @DChildCount NUMERIC(18,0)
		SELECT TOP 1 @PDtypeId = typeid FROM dbo.Department WHERE fullname = @Department
		SELECT @DChildCount = COUNT(*) FROM dbo.Department WHERE typeId LIKE @PDtypeId + '%' AND typeId <> @PDtypeId
		IF (@DChildCount = 0)
			SET @DtypeID = @PDtypeId
		ELSE
		BEGIN
			SET @ErrMsg = '该部门是父节点'
			RETURN -1
		END
	END	
END

DECLARE @STypeID varchar(50)
IF (@SFullName = '')
	BEGIN
		--SET @ErrMsg = '分支机构名称不能为空'
		--RETURN -1
		SET @SFullName=@DefaultSFullName
	END
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.SType WHERE FullName=@SFullName) OR @SFullName = '总部'
	BEGIN
		SET @ErrMsg = '该分支机构不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PStypeId VARCHAR(50)
		DECLARE @SChildCount NUMERIC(18,0)
		SET @PStypeId = (SELECT TOP 1 typeid FROM dbo.SType WHERE fullname = @SFullName)
		SELECT @SChildCount = COUNT(*) FROM dbo.SType WHERE typeId LIKE @PStypeId + '%' AND typeId <> @PStypeId
		IF (@SChildCount = 0)
			SET @STypeID = @PStypeId
		ELSE
		BEGIN
			SET @ErrMsg = '该分支机构是父类'
			RETURN -1
		END                            
	END	
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') OR id = OBJECT_ID(N'[dbo].[V1ZTInfo]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
		SET @stypeid = '00001'
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

IF EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
		SET @stypeid = '00001'
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

IF EXISTS (SELECT TypeId FROM dbo.SType WHERE typeid = @STypeID AND deleted = 1 )
BEGIN
	SET @ErrMsg = '该该分支机构已经被停用'
	RETURN -1 
END

DECLARE @MaxPre  NUMERIC(24, 10) 
IF (@StrMaxPre = '')
	SET @MaxPre = -999999999918.99
ELSE IF(ISNUMERIC(@StrMaxPre) <> 1)
BEGIN
	SET @ErrMsg = '每单优惠限额请输入数字'
	RETURN -1
END
ELSE
	SELECT @MaxPre = CONVERT( NUMERIC(24, 10) , @StrMaxPre)
IF (@MaxPre > 1000)
BEGIN
	SET @ErrMsg = '每单优惠限额最大1000'
	RETURN -1
END

DECLARE @Sex BIT
SELECT @StrSex = CASE @StrSex 
							WHEN '' THEN '1'
							WHEN '男' THEN '1' 
							WHEN '女' THEN '0'
							ELSE '无'			
					END
IF(@StrSex = '无')
BEGIN
	SET @ErrMsg = '性别请输入男或女'
	RETURN -1
END
ELSE
	SET @Sex = CONVERT(BIT, @StrSex)

DECLARE	@BirthDay DATETIME
IF (@StrBirthDay = '')
	SET @BirthDay = '2050-1-1'
ELSE IF (ISDATE(@StrBirthDay) <> 1 )
 BEGIN
	SET @ErrMsg = '出生日期请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
 END
ELSE
	SET @BirthDay = @StrBirthDay

DECLARE	@Jobtime DATETIME
IF (@StrJobtime = '')
	SELECT @Jobtime = '2050-1-1'
ELSE IF (ISDATE(@StrJobtime) <> 1 )
 BEGIN
	SET @ErrMsg = '到岗时间请输入日期,请使用YYYY-MM-DD的格式'
	RETURN -1
 END
ELSE
	SET @Jobtime = @StrJobtime

DECLARE @Stature  NUMERIC(24, 10) 
IF (@StrStature = '')
	SET @Stature = NULL
ELSE IF(ISNUMERIC(@StrStature) <> 1)
BEGIN
	SET @ErrMsg = '身高请输入数字'
	RETURN -1
END
ELSE IF(CHARINDEX('-', @StrStature)<> 0)
BEGIN
	SET @ErrMsg = '身高不能为负数'
	RETURN -1
END
ELSE
	SET @Stature = CONVERT( NUMERIC(24, 10) , @StrStature)

DECLARE @Weight  NUMERIC(24, 10) 
IF (@StrWeight = '')
	SET @Weight = NULL
ELSE IF(ISNUMERIC(@StrWeight) <> 1)
BEGIN
	SET @ErrMsg = '体重请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrWeight)) <> 0)
BEGIN
	SET @ErrMsg = '体重不能为负数'
	RETURN -1
END
ELSE
	SET @Weight = CONVERT( NUMERIC(24, 10) , @StrWeight)

DECLARE @Marriage INT
SELECT @Marriage = CASE @StrMarriage 
							WHEN '已婚' THEN 1 
							WHEN '离异' THEN 2
							WHEN '未婚' THEN 0
							WHEN  '' THEN 0
							ELSE -1		
					END
IF @Marriage=-1
BEGIN
	SET @ErrMsg='婚姻状况列只能填写【已婚】【离异】【未婚】或不填';
	RETURN -1;
END

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

declare @nReturntype int
	,@EtypeId_1 [varchar](50)
	,@nSoncount int
	,@nSonnum int
	,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from employee where typeid=@parid)
--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(select subvalue from sysdata where subname='ifqp')

--部门不存在
if not exists(select typeid from department where typeid=@dtypeid)
BEGIN
	SET @ErrMsg = '所选部门不存在，请另选一个部门'
	RETURN -1	
end

--判断停用不能分类
declare @deleted INT
select @deleted=deleted from employee where typeId=@Parid
if(@deleted=1)
BEGIN
   SET @ErrMsg = '该职员【' + @parFullName + '】已经被停用，不能分类'
   RETURN -1	
end

-- 职员已经使用
if exists(select etypeid from billindex where etypeId=@parid   and etypeid<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 

--车辆信息使用
if exists(select Driver from CM_CarInfo where Driver=@parid)
begin
	SET @ErrMsg = '该职员【'+@parFullName+'】已经使用过，不能分类'
	RETURN -1	
end 

if exists(select ETypeID from PerformanceDistribution where ETypeID=@parid)
begin
   SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
   RETURN -1
end 

if exists(select ReceptionId from Billindex_CarRepair where ReceptionId=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 
--关联pos
if exists(select etypeid from CommonPosInfo where etypeid1=@parid)
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 
--关联维修业务调度中的负责人
if exists(select ItemPrincipal from Billindex_CarRepair where ItemPrincipal=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 
if exists(select MonitorPrincipal from Billindex_CarRepair where MonitorPrincipal=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 
--维修工
if exists(select ETypeId from Qp_AttemperBill_RepairItemsPerson where ETypeId=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 

--关联销售计划
if exists(select ETypeId from EtypeSaleplan where ETypeId=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联销售计划，不能分类'
    RETURN -1
end 

--使用登记单
if exists(select ETypeId from CM_CarUseIndex where ETypeId=@parid)
 OR EXISTS(select Driver from CM_CarUseBill where Driver=@parid)
 OR EXISTS(select ETypeId from CM_CarUseBill where ETypeId=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联使用登记单，不能分类'
    RETURN -1
end 
--车辆费用单
if exists(select ETypeId from CM_FeeIndex where ETypeId=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联车辆费用单，不能分类'
    RETURN -1
end 

if exists(select ETypeId from RequestIndex where ETypeId=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联请购单，不能分类'
    RETURN -1
end 

if exists(select ETypeId from RequestBill where ETypeId=@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经关联请购单，不能分类'
    RETURN -1
END

if exists(select UnitSatrap from Billindex_CarRepair where UnitSatrap=@parid)
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 
if exists(select etypeid from billindex where checke =@parid  and checke<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 

if exists(select checke from dbo.DiyIndex where checke =@parid  and checke<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 

if exists(select etypeid from wx_bill_jiejian where Etypeid =@parid  and etypeid<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 


if exists(select etypeid from wx_bill_call where etypeid =@parid  and etypeid<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 

if exists(select checke from nVipAdjust where checke=@parid and checke<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
END
if exists(select wxmanID from billindex where wxmanID =@parid  and wxmanID<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 

if exists(select ETypeID from Qp_SuccorBill_RepairItems where ETypeID =@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 
--工具入出库台帐
if exists(select ETypeID from ToolIndex where ETypeID =@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 
--储值快速充值单

if exists(select ETypeID from nVipConfiscateConfig where ETypeID =@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 
 if exists(select ETypeID from nVipWashCarTimesConfig where ETypeID =@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 

--电脑配置
 if EXISTS (select ETypeID from dbo.DiyIndex where ETypeID =@parid)
begin
    SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1
end 
  
if exists(select Etypeid from wx_bill_jiejian where Etypeid =@parid  and Etypeid<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经使用过，不能分类'
    RETURN -1	
end 

if exists(select etypeid from OrderIndex where etypeId=@parid  and etypeid<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已在订单中使用，不能分类'
    RETURN -1	
end 
if exists(select etypeid from OrderIndex where checke=@parid  and checke<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已在订单中使用，不能分类'
    RETURN -1	
end 

if exists(select etypeid from LendIndex where etypeId=@parid  and etypeid<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已在借欠单中使用，不能分类'
    RETURN -1
end 

IF EXISTS(select etypeid from nVipAdjust WHERE etypeid=@parid)
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已在会员卡消费调整或者积分中进行处理，不能分类'
	RETURN -1
END

if exists(select etypeid from LendIndex where checke=@parid  and checke<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已在借欠单中使用，不能分类'
	RETURN -1
end 
if exists(select etypeid from RepairEngage where (etypeId=@parid  and etypeid<>'00001') OR (etypeId1=@parid  and etypeid1<>'00001') or (checke=@parid  and checke<>'00001'))
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已在维修单中使用，不能分类'
	RETURN -1
end

IF EXISTS(select CreatorTypeID from crm_Schedule WHERE CreatorTypeID=@parid  AND CreatorTypeID<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已在日程中使用，不能分类'
	RETURN -1
END
IF EXISTS(select SenderTypeID,ReceiverTypeID,CreatorTypeID from crm_Message WHERE (SenderTypeID=@parid AND SenderTypeID<>'00001') OR (ReceiverTypeID=@parid and ReceiverTypeID<>'00001')  or (CreatorTypeID=@parid AND CreatorTypeID<>'00001'))
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已在日程中使用，不能分类'
	RETURN -1
END
IF EXISTS(select SenderTypeID,ReceiverTypeID,CreatorTypeID from crm_MessageNoread WHERE (SenderTypeID=@parid AND SenderTypeID<>'00001') OR (ReceiverTypeID=@parid and ReceiverTypeID<>'00001')  or (CreatorTypeID=@parid AND CreatorTypeID<>'00001'))
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已在日程中使用，不能分类'
	RETURN -1
END

IF EXISTS(select createor from crm_Btype WHERE createor=@parid AND createor<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已创建了CRM客户，不能分类'
	RETURN -1
END
IF EXISTS(select createor from crm_linkMan WHERE createor=@parid  AND createor<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已创建了CRM联系人，不能分类'
	RETURN -1
END

IF EXISTS(select WriteId from PriceProtect WHERE WriteId=@parid  AND WriteId<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】有价保通知，不能分类'
	RETURN -1
END

if exists(select etypeid from Advantage_standard where etypeId=@parid  and etypeid<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】作为返利标准的制作人，不能分类'
	RETURN -1
end 

IF EXISTS(select EtypeId from FapiaoBillIndex WHERE EtypeId=@parid AND EtypeId<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】作为发票经手人，不能分类'
	RETURN -1
END
IF EXISTS(select Assessor from FapiaoBillIndex WHERE Assessor=@parid AND Assessor<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】作为发票审核人或制单人，不能分类'
	RETURN -1
END
IF EXISTS(select checke from FapiaoBillIndex WHERE checke=@parid AND checke<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】作为发票审核人或制单人，不能分类'
	RETURN -1
END
IF EXISTS(select EtypeId from TcBillIndex WHERE EtypeId=@parid AND EtypeId<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】作为提成规则单制单人或审核人，不能分类'
	RETURN -1
END
IF EXISTS(select checke from TcBillIndex WHERE checke=@parid AND checke<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】作为提成规则单制单人或审核人，不能分类'
	RETURN -1
END

IF EXISTS(select * from nVipCardSign where Etypeid=@parid AND etypeid<>'00001')
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】作为会员卡的发卡人，不能分类'
	RETURN -1
END

--已经是操作员的不能分类
if exists(select etypeid from loginuser where etypeId=@parid  and etypeid<>'00001')
begin
	SET @ErrMsg = '该职员【' + @parFullName + '】已经是操作员，不能分类'
	RETURN -1
end 

if @ifqp='1'
begin
--在快修单中为维修工
	if exists (select RepairManTypeID from QP_QuickRepairBill_RepairItems where  RepairManTypeID=@parid and RepairManTypeID<>'00001')
	BEGIN
		   SET @ErrMsg = '该职员【' + @parFullName + '】作为快修单的修理工，不能分类'
		   RETURN -1
	end
	if exists (select RepairManTypeID from QP_QuickRepairBill_PType where  RepairManTypeID=@parid and RepairManTypeID<>'00001')
	BEGIN
			SET @ErrMsg = '该职员【' + @parFullName + '】作为快修单的修理工，不能分类'
		    RETURN -1
	end
	--维修人员工作组
	if exists (select etypeid from QP_WorkGroup_Person where  etypeid=@parid and etypeid<>'00001')
	BEGIN
		SET @ErrMsg = '该职员【' + @parFullName + '】已在人员工作组中使用过，不能分类'
		RETURN -1
	end
	--洗车结算单洗车工
	if exists(select etypeid from QP_WashCarBill where etypeid=@parid and etypeid<>'00001')
	BEGIN
		SET @ErrMsg = '该职员【' + @parFullName + '】已在洗车结算单中使用过，不能分类'
		RETURN -1
	end
end
--盘点单
if exists(select top 1 etypeid  from  StockCheckIndex where etypeid=@parid and etypeid<>'00001' )
BEGIN
	SET @ErrMsg = '该职员【' + @parFullName + '】已在盘点单中使用过，不能分类'
	RETURN -1
end
-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
BEGIN
	SET @ErrMsg = '职员的分类不能超过9层'
	RETURN -1
end
if @nReturntype=-2 
BEGIN
	SET @ErrMsg = '无法添加基本信息'
	RETURN -1
end

-- 判断重复的ID,UserCode
DECLARE @EnameFlag varchar(50)
select @EnameFlag=value from Userconfig where ConfigName='equaleroname'
IF @EnameFlag<>1
	begin
	if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted<>1) or (fullname=@fullname and fullname<>'超级用户' and deleted<>1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】已经存在，职员编号或名称不能相同'
		RETURN -1
	end
end
else
begin
	if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted<>1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】已经存在，职员编号不能相同'
		RETURN -1
	end
end


-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted<>1) or (fullname=@usercode and fullname<>'超级用户' and deleted<>1))
begin
	SET @ErrMsg = '职员名称或编号不能与已有的名称或编号重复'
	RETURN -1
end


-- 判断重复的ID,UserCode
IF @EnameFlag<>1
begin
	if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted=1) or (fullname=@fullname and fullname<>'超级用户' and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称'
		RETURN -1
	end
end
else
begin
	if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的职员使用，请更换或删除该停用的编号'
		RETURN -1
	end
end


-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted=1) or (fullname=@usercode and fullname<>'超级用户' and deleted=1))
begin
	SET @ErrMsg = '职员名称或编号不能与已停用的名称或编号重复'
	RETURN -1
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode


    --验证职员自定义开始 
	CREATE TABLE #Custom(
		EditKind			VARCHAR(50) ,				--数据类型
		label				VARCHAR(50),				--属性名称
		datafield			VARCHAR(50),				-- 数据库对应字段
		maxbytelength		int     --长度
	)

	IF ( 0 < (SELECT COUNT(1) FROM @tb))
	BEGIN
		INSERT INTO #Custom (EditKind,label,datafield,maxbytelength) SELECT EditKind,label,datafield,maxbytelength FROM @tb
	END
	IF( 0 < (SELECT COUNT(1) FROM CustomBaseInforColumnsDefines WHERE BaseType='etype'))
	BEGIN
		IF  @costom1 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列1'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='自定义列1类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom1) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='自定义列1超出最大值'
				RETURN -1 
			END
		END

		IF  @costom2 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列2'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='自定义列2类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom2) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='自定义列2超出最大值'
				RETURN -1 
			END
		END

		IF  @costom3 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列3'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='自定义列3类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom3) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='自定义列3超出最大值'
				RETURN -1 
			END
		END

		IF  @costom4 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列4'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='自定义列4类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom4) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='自定义列4超出最大值'
				RETURN -1 
			END
		END

		IF  @costom5 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列5'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='自定义列5类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom5) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='自定义列5超出最大值'
				RETURN -1 
			END
		END

		IF  @costom6 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列6'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='自定义列6类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom6) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='自定义列6超出最大值'
				RETURN -1 
			END
		END

		IF  @costom7 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列7'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='自定义列7类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom7) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='自定义列7超出最大值'
				RETURN -1 
			END
		END

		IF  @costom8 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列8'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='自定义列8类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom8) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='自定义列8超出最大值'
				RETURN -1 
			END
		END

		IF  @costom9 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列9'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='自定义列9类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom9) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='自定义列9超出最大值'
				RETURN -1 
			END
		END

		IF  @costom10 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列10'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='自定义列10类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom10) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='自定义列10超出最大值'
				RETURN -1 
			END
		END

		IF  @costom11 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列11'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='自定义列11类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom11) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='自定义列11超出最大值'
				RETURN -1 
			END
		END

		IF  @costom12 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列12'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='自定义列12类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom12) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='自定义列12超出最大值'
				RETURN -1 
			END
		END

		IF  @costom13 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列13'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='自定义列13类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom13) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='自定义列13超出最大值'
				RETURN -1 
			END
		END

		IF  @costom14 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列14'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='自定义列14类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom14) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='自定义列14超出最大值'
				RETURN -1 
			END
		END

		IF  @costom15 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列15'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='自定义列15类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom15) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='自定义列15超出最大值'
				RETURN -1 
			END
		END

		IF  @costom16 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列16'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='自定义列16类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom16) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='自定义列16超出最大值'
				RETURN -1 
			END
		END
	END
	ELSE
	BEGIN
		IF (@costom1 <> ''   OR @costom2 <> ''   OR @costom3 <> ''   OR @costom4 <> ''   OR @costom5 <> ''   OR @costom6 <> ''   OR @costom7 <> ''   OR @costom8 <> ''   OR @costom9 <> ''   OR @costom10 <> ''   OR @costom11 <> ''   OR @costom12 <> ''   OR @costom13 <> ''   OR @costom14 <> ''   OR @costom15 <> ''   OR @costom16 <> ''  )
		BEGIN
			SET @ErrMsg ='系统未启用职员自定义列'
			RETURN -1
		END
	END
	DROP TABLE #Custom
	--验证职员自定义结束
	


BEGIN TRAN insertproc
select @leveal=leveal+1 from employee where typeid=@Parid 
INSERT INTO [employee] 
  ( 
	[typeId],
	  [Parid],
	  [leveal],
	  [soncount],
	  [sonnum],
	  [FullName],
	  [UserCode],
	  [Department],
	  [Tel],
	  [Address],
	  [Comment],
	  [BtypeID],
	[Sex],
	[Nation],
	[Knowledge],
	[Blood],
	[Health],
	[IDCard],
	[BirthDay],
	[Marriage],
	[Job],
	[Job2],
	[Jobtime],
	[Mob],
	[Mail],
	[Political],
	[Nat_place],
	[Tel2],
	[College],
	[For_language],
	[Reg_place],
	[Com_level],
	[Weight],
	[Stature],
	[Fam_status],
	[Informer],
	[Speciality],
	[For_lan_level],
	[PostCode],
	[PyCode],
	[DtypeID],
	[MaxPre],
	[tichengRate],
	[STypeID],
    [QQ],
	[MSN],
	[Blog],
	[mBlog],
	[Team],
    [Buyerminvalue],
    [Saleminvalue]
)  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Department,
  @Tel,
  @Address,
  @Comment,
  @BtypeID,
@Sex,
@Nation,
@Knowledge,
@Blood,
@Health,
@IDCard,
@BirthDay,
@Marriage,
@Job,
@Job2,
@Jobtime,
@Mob,
@Mail,
@Political,
@Nat_place,
@Tel2,
@College,
@For_language,
@Reg_place,
@Com_level,
@Weight,
@Stature,
@Fam_status,
@Informer,
@Speciality,
@For_lan_level,
@PostCode,
@returnPym,
@DtypeID,
@MaxPre,
CAST(@tichengRate AS  NUMERIC(24, 10) ),
@STypeID,
@QQ,
@MSN,
@Blog,
@mBlog,
@Team,
CAST(ISNULL(@Buyerminvalue,0) AS  NUMERIC(24, 10) ),
CAST(ISNULL(@Saleminvalue,0) AS  NUMERIC(24, 10) )
)
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [employee]
  set sonnum=@nSonnum+1,soncount=@nSoncount+1
  where typeid=@Parid
end
-- 建立超级用户的登录帐号
if @Parid='00000'
begin
 exec @nReturntype=Gp_AddNewLogin @EtypeId_1,1
 if @nReturntype=-1 return -1
 if @nReturntype=-2 return -2
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Employee
UPDATE Employee SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
 

	IF( 0 < (SELECT COUNT(1) FROM CustomBaseInforColumnsDefines WHERE BaseType='etype'))
	BEGIN
	--	IF (@costom1 <> ''   OR @costom2 <> ''   OR @costom3 <> ''   OR @costom4 <> ''   OR @costom5 <> ''   OR @costom6 <> ''   OR @costom7 <> ''   OR @costom8 <> ''   OR @costom9 <> ''   OR @costom10 <> ''   OR @costom11 <> ''   OR @costom12 <> ''   OR @costom13 <> ''   OR @costom14 <> ''   OR @costom15 <> ''   OR @costom16 <> ''  )
	--	BEGIN
				INSERT INTO dbo.Etype_CustomColumns
        ( typeid ,
          Costom1 ,
          Costom2 ,
          Costom3 ,
          Costom4 ,
          Costom5 ,
          Costom6 ,
          Costom7 ,
          Costom8 ,
          Costom9 ,
          Costom10 ,
          Costom11 ,
          Costom12 ,
          Costom13 ,
          Costom14 ,
          Costom15 ,
          Costom16 
        )
		VALUES  ( 
		@EtypeId_1,
		@costom1,
		@costom2,
		@costom3,
		@costom4,
		@costom5,
		@costom6,
		@costom7,
		@costom8,
		@costom9,
		@costom10,
		@costom11,
		@costom12,
		@costom13,
		@costom14,
		@costom15,
		@costom16
				)
	END
	
 
commit tran insertproc

END

GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ImportExpense]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[GP_ImportExpense];
GO


/****** Object:  StoredProcedure [dbo].[GP_ImportExpense]    Script Date: 05/20/2011 17:29:17 ******/
SET ANSI_NULLS ON;
GO

SET QUOTED_IDENTIFIER OFF;
GO

/*	
	创 建 者：yx
	日    期：2017-10-16
	创建原因：导入费用单、现金费用单等单据表体
*/


CREATE  PROCEDURE [dbo].[GP_ImportExpense]
    (
      @EUserCode VARCHAR(50) = '' ,
      @DUserCode VARCHAR(50) = '' ,
      @AtypeUserCode VARCHAR(50) ,
      @NTotal VARCHAR(50) ='' ,
      @DetailComment VARCHAR(255) = '' ,
      @ReturnID VARCHAR(100) OUTPUT ,
      @ErrMsg VARCHAR(200) OUTPUT ,
      @typeid [VARCHAR](MAX) = '',
      @btypeid VARCHAR(50),
      @brandreceiva VARCHAR(500)
    )
--@encode$--
AS
    SET NOCOUNT ON;

    DECLARE @PtypeId VARCHAR(50);
    DECLARE @flagint INT;
    DECLARE @ChildCount NUMERIC(18, 0);
    DECLARE @NTotalN FLOAT
-------------------------------------转换输入参数---------------------------------------------
--IF(@UserCode = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @UserCode) OR @UserCode='0')
--BEGIN
--	SET @ErrMsg = '商品编号不存在'
--	RETURN -1
--END
	

    DECLARE @temp		VARCHAR(500);
    DECLARE @userid		VARCHAR(MAX) ,
        @billtype		VARCHAR(4) ,
        @formStype		VARCHAR(50) ,
        @formstock		VARCHAR(50) ,
        @temp1			VARCHAR(50) ,
        @mergeqty		VARCHAR(50);---分解操作员ID和单据类型编号
         
    DECLARE @dtypeid	VARCHAR(50)='',@etypeid VARCHAR(50)=''
    DECLARE @count		INT --小数位数
   
    SELECT @count = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName = 'total'
    
    IF(@NTotal ='')
	BEGIN
		  SET @ErrMsg = '原币金额不能为空！';
          RETURN -1;
	END
	ELSE
	BEGIN
		IF(ISNUMERIC(@Ntotal)<>1)
		BEGIN
			SET @ErrMsg = '原币金额请输入数字！';
			RETURN -1;
		END 
		ELSE 
			SET @NTotalN = cast(@NTotal as FLOAT)

		IF (CHARINDEX('.',@NTotal)>0 AND LEN(@NTotal)-CHARINDEX('.',@NTotal)>@count)
		BEGIN
			SET @ErrMsg = '原币金额小数位数不超过'+CAST(@count AS VARCHAR)+'位小数！'
			RETURN -1
		END
	END  
	
    SET @userid = ( SELECT TOP 1
                            a
                    FROM    f_split(@typeid, 'я')
                  );
    SET @temp = ( SELECT    a
                  FROM      f_split(@typeid, 'я')
                  WHERE     a <> @userid
                );

    SET @billtype = ( SELECT TOP 1
                                a
                      FROM      f_split(@temp, '#')
                    );

    SET @formStype = ( SELECT   a
                       FROM     f_split(@temp, '#')
                       WHERE    a <> @billtype
                     );

    IF ( @AtypeUserCode = ''
         OR CAST(@NTotal AS VARCHAR) = ''
       )
        BEGIN
            SET @ErrMsg = '费用项目编号不能为空！';
            RETURN -1;
        END;

    IF ( @NTotalN = 0 )
        BEGIN
            SET @ErrMsg = '原币金额不能为0！';
            RETURN -1;
        END; 

    IF ( @AtypeUserCode <> '' )
        BEGIN
            IF NOT EXISTS ( SELECT  nId
                            FROM    dbo.Ac_Items
                            WHERE   UserCode = @AtypeUserCode )
                BEGIN
                    SET @ErrMsg = '该项目编号不存在！';
                    RETURN -1;
                END;
            IF EXISTS ( SELECT  nId
                        FROM    dbo.Ac_Items
                        WHERE   UserCode = @AtypeUserCode
                                AND deleted = 1 )
                BEGIN
                    SET @ErrMsg = '该项目已停用！';
                    RETURN -1;
                END;
			 IF EXISTS ( SELECT  nId
                        FROM    dbo.Ac_Items
                        WHERE   UserCode = @AtypeUserCode
                                AND SonNum>0 )
                BEGIN
                
                    SET @ErrMsg = '该项目为父节点，不能导入！';
                    RETURN -1;
                END;
             
             DECLARE @Atypeid VARCHAR(50)
             
             SELECT @Atypeid = nTypeId FROM dbo.Ac_Items WHERE UserCode = @AtypeUserCode
             
             IF (@Atypeid IS NOT NULL AND @Atypeid <>'' AND  @Atypeid NOT LIKE '0000400003%')
				BEGIN
					SET @ErrMsg = '模板中的项目不是费用项目'
					RETURN -1
				END
				
            IF (@AtypeUserCode NOT IN (SELECT UserCode FROM dbo.Ac_Items WHERE nId IN (SELECT typeId FROM F_GetAllManagerBaseTypeId('',6,@userid))))
				BEGIN
					SET @ErrMsg = '操作员没有该项目权限'
					RETURN -1
				END
        END;
        
    DECLARE @BrandarTypeId	VARCHAR(50);	--商品品牌ID
    DECLARE @SonNum			INT;			--商品品牌是否子类，0：子类
    IF EXISTS(SELECT * FROM dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue='1')
     AND EXISTS( select top 1 1 from btype where IsUseBrandarType=1 and typeId=@btypeid)
     AND  @billtype =36
    BEGIN
		IF ISNULL(@brandreceiva,'')='' 
		BEGIN
			SET @ErrMsg = '启用品牌应收管理时，商品品牌编码不能为空!'
			RETURN -1
		END
    END 
    ELSE IF @billtype <> 158
    BEGIN
		SET @brandreceiva = ''
    END 
    
    IF(ISNULL(@brandreceiva,'')<>'')
    BEGIN
		SELECT @BrandarTypeId=TypeId,@SonNum=SonNum FROM dbo.brandar_Commodity WHERE UserCode = @brandreceiva
		IF (ISNULL(@BrandarTypeId,'')='')
		BEGIN
			SET @ErrMsg ='录入的商品品牌编码不存在!'
			RETURN -1
		END 
		
		IF (@SonNum<>0)
		BEGIN
			SET @ErrMsg = '录入的商品品牌编码必须为子类编码!'
			RETURN -1
		END 
    END
	
    DECLARE @nid INT; 
    SELECT  @nid = nId
    FROM    dbo.Ac_Items
    WHERE   UserCode = @AtypeUserCode;


	IF(@billtype=158 OR @billtype =36)
	BEGIN
		IF ( @EUserCode <> '' )
        BEGIN
            IF NOT EXISTS ( SELECT  *
                            FROM    dbo.employee
                            WHERE   UserCode = @EUserCode )
                BEGIN
                    SET @ErrMsg = '明细行经手人为【'+ISNULL(@EUserCode,'')+'】的编号在系统中不存在，不允许导入！';
                    RETURN -1;
                END;
            IF EXISTS (  SELECT  * FROM    dbo.employee WHERE UserCode = @EUserCode AND deleted = 1 )
                BEGIN
                    SET @ErrMsg = '明细行经手人为【'+ISNULL(@EUserCode,'')+'】的编号在系统中已停用，不允许导入！';
                    RETURN -1;
                END;
                
            IF EXISTS (  SELECT  * FROM    dbo.employee WHERE UserCode = @EUserCode AND sonnum>0 )
                BEGIN
                    SET @ErrMsg = '明细行经手人为【'+ISNULL(@EUserCode,'')+'】的编号在系统中为父节点，不允许导入！';
                    RETURN -1;
                END;
            IF (@EUserCode NOT IN (SELECT UserCode FROM dbo.employee WHERE typeId IN (SELECT typeId FROM F_GetAllManagerBaseTypeId('',3,@userid))))
				BEGIN
					SET @ErrMsg = '操作员没有该经手人权限'
					RETURN -1
				END
        END;
        ELSE
        BEGIN
			SET @ErrMsg = '【明细行经手人编号】字段为必填项，不能为空！！';
			RETURN -1
        END 
        
        IF ( @DUserCode <> '' )
        BEGIN
            IF NOT EXISTS ( SELECT  *
                            FROM    dbo.Department
                            WHERE   UserCode = @DUserCode )
                BEGIN
                    SET @ErrMsg = '明细行部门为【'+ISNULL(@DUserCode,'')+'】的编号在系统中不存在，不允许导入！';
                    RETURN -1;
                END;
            IF EXISTS (  SELECT  * FROM    dbo.Department WHERE UserCode = @DUserCode AND deleted = 1 )
                BEGIN
                    SET @ErrMsg = '明细行部门为【'+ISNULL(@DUserCode,'')+'】的编号在系统中已停用，不允许导入！';
                    RETURN -1;
                END;
            IF EXISTS (SELECT  * FROM  dbo.Department WHERE UserCode = @DUserCode AND sonnum>0 )
                BEGIN
                    SET @ErrMsg = '明细行部门为【'+ISNULL(@DUserCode,'')+'】的编号在系统中为父节点，不允许导入！';
                    RETURN -1;
                END;
            IF (@DUserCode NOT IN (SELECT UserCode FROM dbo.Department WHERE typeId IN (SELECT typeId FROM F_GetAllManagerBaseTypeId('',9,@userid)
            )))
				BEGIN
					SET @ErrMsg = '操作员没有该部门权限'
					RETURN -1
				END
        END;
        ELSE
        BEGIN
			SET @ErrMsg = '【明细行部门编号】字段为必填项，不能为空！';
			RETURN -1
        END 
        
        SELECT @dtypeid =  typeid FROM dbo.Department WHERE UserCode = @DUserCode
        SELECT @etypeid = typeId FROM  dbo.employee WHERE   UserCode = @EUserCode
	END 
	
    INSERT  INTO ImportMoneyBillTemp
            ( billtype ,
              atypeid ,
              total ,
              comment ,
              [delete] ,
              userid,
              ntotal,
              DTypeId,
              ETypeId,
              BrandarTypeId
            )
    VALUES  ( @billtype ,
              @nid ,
              @NTotalN ,
              @DetailComment ,
              0 ,
              @userid,
              @NTotalN,
              @dtypeid,
              @etypeid,
              @BrandarTypeId
            );

    SET @ReturnID = @@ROWCOUNT;

GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/****** Object:  StoredProcedure [dbo].[gp_ImportFixed]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	作	  者：廖晨羽
	日    期：2011-09-13
	描	  述：导入固定资产期初
*/


CREATE         PROCEDURE [dbo].[gp_ImportFixed]
(
	@SFullName   [varchar](200),		--分支机构名称
	@AFullName   [varchar](200),		--科目名称
	@Strtotal00  [varchar](18),			--科目余额
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
DECLARE @stypeid	VARCHAR(1000)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF (@SFullName = '' OR @SFullName = '总部' OR NOT EXISTS(SELECT typeid FROM dbo.SType WHERE fullname = @SFullName))
	BEGIN
		SET @ErrMsg = '该分支机构不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PStypeId VARCHAR(50)
		DECLARE @SChildCount NUMERIC(18,0)
		SET @PStypeId = (SELECT TOP 1 typeid FROM dbo.SType WHERE fullname = @SFullName)
		SELECT @SChildCount = COUNT(*) FROM dbo.SType WHERE typeId LIKE @PStypeId + '%' AND typeId <> @PStypeId
		IF (@SChildCount = 0)
			BEGIN
				SET @stypeid = @PStypeId		
				IF (@stypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@typeid)))
				BEGIN
					SET @ErrMsg = '操作员不具备该分支机构权限'
					RETURN -1
				END				
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该分支机构是父类'
				RETURN -1
			END
	END

	--判断分支机构是否已开账
	IF ((SELECT U.Value FROM SType_UserConfig U,SType_Config C WHERE U.ConfigNo = C.ConfigNo AND U.Value = '1' AND U.STypeID = @stypeid) = 1)
	BEGIN
		SET @ErrMsg = '该分支机构已开账'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

DECLARE @atypeid	VARCHAR(1000)
IF (@AFullName = '' OR @AFullName = 'root' OR NOT EXISTS(SELECT typeid FROM dbo.atype WHERE fullname = @AFullName))
BEGIN
	SET @ErrMsg = '该科目名称不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PAtypeId VARCHAR(50)
	DECLARE @AChildCount NUMERIC(18,0)
	SET @PAtypeId = (SELECT TOP 1 typeid FROM dbo.atype WHERE fullname = @AFullName)
	IF (SUBSTRING(@PAtypeId, 1, 10) <> '0000100002')
	BEGIN
		SET @ErrMsg = '该科目名称不存在'
		RETURN -1
	END
	SELECT @AChildCount = COUNT(*) FROM dbo.atype WHERE typeId LIKE @PAtypeId + '%' AND typeId <> @PAtypeId
	IF (@AChildCount = 0)
		BEGIN
			SET @atypeid = @PAtypeId	
			IF (@atypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',8,@typeid)))
			BEGIN
				SET @ErrMsg = '操作员不具备该固定资产权限'
				RETURN -1
			END				
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该科目名称是父类'
			RETURN -1
		END
END

DECLARE @total00  NUMERIC(24, 10) 
IF (@Strtotal00 = '')
BEGIN
	SET @ErrMsg = '请输入科目余额'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@Strtotal00) <> 1)
		BEGIN
			SET @ErrMsg = '科目余额请输入数字'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @total00 = CONVERT( NUMERIC(24, 10) , @Strtotal00)
		END
END
----------------------------------------------------------------------------------------------
 IF EXISTS (SELECT 1 FROM atype_total WHERE atypeid=@atypeid AND stypeid=@stypeid)   
 UPDATE atype_total SET total00=@total00 WHERE atypeid=@atypeid AND stypeid=@stypeid ---存在
 ELSE 
 INSERT INTO atype_total(atypeid,stypeid,total,total00)  --不存在
 VALUES(@atypeid,@stypeid,0,@total00)
 
 SET @ReturnID = @@ROWCOUNT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/****** Object:  StoredProcedure [dbo].[gp_ImportIniGoodsLend]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：廖晨羽
	日    期：2011-09-13
	描	  述：导入借欠期初
*/


CREATE         PROCEDURE [dbo].[gp_ImportIniGoodsLend]
(
	@BFullName   [varchar](200),		--往来单位名称
	@KFullName   [varchar](200),		--仓库名称
	@PUserCode	 [varchar](200),		--借欠商品编号
	@PFullName   [varchar](200),		--借欠商品名称
	@StrLendQty  [varchar](18),			--借出数量
	@StrBorrowQty  [varchar](18),		--借进数量
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
DECLARE	@btypeid		varchar(1000)
IF (@BFullName = '' OR @BFullName = 'ABC' OR NOT EXISTS(SELECT typeid FROM dbo.btype WHERE fullname = @BFullName))
BEGIN
	SET @ErrMsg = '该往来单位不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PBtypeId VARCHAR(50)
	DECLARE @BChildCount NUMERIC(18,0)
	SET @PBtypeId = (SELECT TOP 1 typeid FROM dbo.btype WHERE fullname = @BFullName)
	SELECT @BChildCount = COUNT(*) FROM dbo.btype WHERE typeId LIKE @PBtypeId + '%' AND typeId <> @PBtypeId
	IF (@BChildCount = 0)
		BEGIN
			SET @btypeid = @PBtypeId	
			IF (@btypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@typeid)))
			BEGIN
				SET @ErrMsg = '操作员不具备该往来单位权限'
				RETURN -1
			END				
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该往来单位是父类'
			RETURN -1
		END
END

DECLARE	@ktypeid		varchar(1000)
IF (@KFullName = '' OR @KFullName = '全部仓库' OR NOT EXISTS(SELECT typeid FROM dbo.Stock WHERE fullname = @KFullName))
BEGIN
	SET @ErrMsg = '该仓库不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PktypeId VARCHAR(50)
	DECLARE @KChildCount NUMERIC(18,0)
	SET @PktypeId = (SELECT TOP 1 typeid FROM dbo.Stock WHERE fullname = @KFullName)
	SELECT @KChildCount = COUNT(*) FROM dbo.Stock WHERE typeId LIKE @PktypeId + '%' AND typeId <> @PktypeId
	IF (@KChildCount = 0)
		BEGIN
			SET @ktypeid = @PktypeId	
			IF (@ktypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@typeid)))
			BEGIN
				SET @ErrMsg = '操作员不具备该仓库权限'
				RETURN -1
			END					
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该仓库是父类'
			RETURN -1
		END
END

--判断仓库关联的分支机构是否已开账
IF EXISTS (SELECT U.Value as valueinfo FROM SType_Config C,SType_UserConfig U,Stock K WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND U.STypeID = K.STypeID AND K.TypeId = @KtypeId) 
AND ((SELECT U.Value as valueinfo FROM SType_Config C,SType_UserConfig U,Stock K WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND U.STypeID = K.STypeID AND K.TypeId = @KtypeId) <> 0)
BEGIN
	SET @ErrMsg = '该仓库关联的分支机构已开账'
	RETURN -1
END

IF(@PUserCode = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @PUserCode) OR @PUserCode='0')
BEGIN
	SET @ErrMsg = '借欠商品编号不存在'
	RETURN -1
END
ELSE IF (@PFullName = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @PFullName) OR @PFullName='库存配件')
BEGIN
	SET @ErrMsg = '借欠商品名称不存在'
	RETURN -1
END
ELSE IF(@PFullName <> (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @PUserCode))
BEGIN
	SET @ErrMsg = '借欠商品编号与借欠商品名称不匹配'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PtypeId  VARCHAR(50)
	DECLARE @ChildCount NUMERIC(18,0)
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @PUserCode)
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0 OR (@PFullName = '库存配件' AND @PUserCode = '0'))
	BEGIN
		SET @ErrMsg = '该商品为父节点'
		RETURN -1	
	END
	IF (@PtypeId NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@typeId)))
		BEGIN
			SET @ErrMsg = '操作员不具备该商品权限'
			RETURN -1
		END	
END

DECLARE @LendQty  NUMERIC(24, 10) 
IF (@StrLendQty = '')
BEGIN
	SET @ErrMsg = '请输入借出数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrLendQty) <> 1)
		BEGIN
			SET @ErrMsg = '借出数量请输入数字'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @LendQty = CONVERT( NUMERIC(24, 10) , @StrLendQty)
		END
END

DECLARE @BorrowQty  NUMERIC(24, 10) 
IF (@StrBorrowQty = '')
BEGIN
	SET @ErrMsg = '请输入借进数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrBorrowQty) <> 1)
		BEGIN
			SET @ErrMsg = '借进数量请输入数字'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @BorrowQty = CONVERT( NUMERIC(24, 10) , @StrBorrowQty)
		END
END

DECLARE @qty  NUMERIC(24, 10) 
SET @qty = @BorrowQty - @LendQty
----------------------------------------------------------------------------------------------

IF NOT EXISTS(SELECT Qty FROM dbo.IniGoodsLend WHERE btypeid = @btypeid AND ptypeid = @ptypeid AND ktypeid = @ktypeid)	--判断是否已经存在一样的期初信息
BEGIN							  --不存在
	IF (@qty <> 0)
	BEGIN                           
		INSERT INTO
			IniGoodsLend(btypeid,ptypeid,ktypeid,qty) 
		VALUES(@btypeid,@ptypeid,@ktypeid,@qty)
	END
END
ELSE
BEGIN                             --存在
	DELETE FROM dbo.IniGoodsLend 
	WHERE btypeid = @btypeid AND ptypeid = @ptypeid AND ktypeid = @ktypeid
	IF (@qty <> 0)
	BEGIN
		INSERT INTO
		dbo.IniGoodsLend(btypeid,ptypeid,ktypeid,qty) 
		VALUES(@btypeid,@ptypeid,@ktypeid,@qty)
	END
END

SET @ReturnID = @@ROWCOUNT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/****** Object:  StoredProcedure [dbo].[gp_ImportIniGoodsstocks]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：廖晨羽
	日    期：2011-08-29
	描	  述：导入库存期初
*/



CREATE         PROCEDURE [dbo].[gp_ImportIniGoodsstocks]
(
	@KFullName   [varchar](66),		--仓库名称
	@PFullName   [varchar](200),		--商品名称
	@PUserCode	 [varchar](200),		--商品编号
	@StrQty  [varchar](18),			--商品数量
	@StrPrice  [varchar](18),		--商品单价
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

DECLARE @Allow VARCHAR(50),@operId VARCHAR(max),@IsManual VARCHAR(20)  ---分解是否允许负库存,操作员id,是否使用手工指定法
SET @Allow = (SELECT TOP 1 A FROM f_split(@typeid,'я'))
DECLARE @tempChar VARCHAR(max)
SET @tempChar = (SELECT SUBSTRING(@typeid,(SELECT LEN(@allow) + 2),(SELECT LEN(@typeid))))
SET @operId = (SELECT TOP 1 A FROM f_split(@tempChar,'я') )
SET @IsManual = (SELECT A FROM f_split(@tempChar,'я') WHERE A <> @operId)

DECLARE @KtypeId VARCHAR(50)
IF (@KFullName = '' OR @KFullName = '全部仓库' OR NOT EXISTS(SELECT typeid FROM dbo.stock WHERE fullname = @KfullName))
BEGIN
	SET @ErrMsg = '仓库名称不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PKtypeId VARCHAR(50)
	DECLARE @KChildCount NUMERIC(18,0)
	SET @PKtypeId = (SELECT TOP 1 typeid FROM dbo.stock WHERE fullname = @KfullName)
	SELECT @KChildCount = COUNT(*) FROM dbo.stock WHERE typeId LIKE @PKtypeId + '%' AND typeId <> @PKtypeId
	IF (@KChildCount = 0)
		BEGIN
			SET @KtypeId = @PKtypeId
			IF (@KtypeId NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@operId)))
			BEGIN
				SET @ErrMsg = '操作员不具备该仓库权限'
				RETURN -1
			END			
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该仓库是父类'
			RETURN -1
		END
END

--判断仓库关联的分支机构是否已开账
IF EXISTS (SELECT U.Value as valueinfo FROM SType_Config C,SType_UserConfig U,Stock K WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND U.STypeID = K.STypeID AND K.TypeId = @KtypeId) 
AND ((SELECT U.Value as valueinfo FROM SType_Config C,SType_UserConfig U,Stock K WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND U.STypeID = K.STypeID AND K.TypeId = @KtypeId) <> 0)
BEGIN
	SET @ErrMsg = '已开账'
	RETURN -1
END

IF(@PUserCode = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @PUserCode) OR @PUserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
ELSE IF (@PFullName = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @PFullName) OR @PFullName='全部商品')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
ELSE IF(@PFullName <> (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @PUserCode))
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PtypeId  VARCHAR(50)
	DECLARE @ChildCount NUMERIC(18,0)
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @PUserCode)	
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0)
	BEGIN
		SET @ErrMsg = '该商品为父节点，不能导入期初'
		RETURN -1	
	END
	IF (@PtypeId NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@operId)))
		BEGIN
			SET @ErrMsg = '操作员不具备该商品权限'
			RETURN -1
		END	
END

DECLARE @Qty  NUMERIC(24, 10) 
IF (@StrQty = '')
BEGIN
	SET @ErrMsg = '请输入商品数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
			SET @ErrMsg = '商品数量请输入数字'
			RETURN -1
		END
	SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
END

IF (@Allow <> 'isAllow')
	BEGIN
		IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
		BEGIN
			SET @ErrMsg = '商品数量不能为负数'
			RETURN -1
		END
	END

IF (@Qty = 0)
BEGIN
	SET @ErrMsg = '商品数量不能为0'
	RETURN -1
END

DECLARE @Price  NUMERIC(24, 10) 
IF (@StrPrice = '')
BEGIN
	SET @ErrMsg = '请输入商品单价'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrPrice) <> 1)
		BEGIN
			SET @ErrMsg = '商品单价请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrPrice)) <> 0)
		BEGIN
			SET @ErrMsg = '商品单价不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Price = CONVERT( NUMERIC(24, 10) , @StrPrice)
		END
END

DECLARE @Total  NUMERIC(24, 10) 
SET @Total = (SELECT ROUND((@Qty * @Price),2))
SET @Price = (SELECT ROUND((@Total/@Qty),4))
----------------------------------------------------------------------------------------------
IF(@IsManual = 'IsManual') --使用手工指定法
BEGIN
	exec Gp_DealHandCostIniData @nType='A',@PTypeId=@PtypeId,@KTypeId=@KtypeId,@Qty=@Qty,@Price=@Price,@Total=@Total,@gNumber='',@pDate='',@vDate='',@GoodsOrder='-1'
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT Qty FROM dbo.IniGoodsStocks WHERE PtypeId = @PtypeId AND KtypeId = @KtypeId)	--判断是否已经存在一样的期初信息
	BEGIN                             --不存在
		INSERT INTO
			iniGoodsStocks(PtypeId,KtypeId,Qty,Price,Total) 
		VALUES(@PtypeId,@KtypeId,@Qty,@Price,@Total)
	END
	ELSE
	BEGIN                             --存在
		DELETE FROM iniGoodsStocks WHERE ptypeId = @PtypeId AND KtypeId = @KtypeId
		INSERT INTO
			iniGoodsStocks(PtypeId,KtypeId,Qty,Price,Total) 
		VALUES(@PtypeId,@KtypeId,@Qty,@Price,@Total)
	END
END


SET @ReturnID = @@ROWCOUNT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[gp_ImportIniLend]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].gp_ImportIniLend
GO

/*
	作者：周华
	时间：2012-08-02
	描述：借欠期初导入
*/
CREATE PROC gp_ImportIniLend
(
	@bTypeCode VARCHAR(50) --编号
	,@bTypeName VARCHAR(100) --往来单位名称
	,@stockCode VARCHAR(50) --编号
	,@stockName VARCHAR(100) --仓库名称
	,@pTypeCode VARCHAR(50) --商品编号
	,@pTypeName VARCHAR(100) --商品名称
	,@itemValueName VARCHAR(100) --自由项值字称
	,@LendQty VARCHAR(23) --DECIMAL(22,10) --借出数量
	,@LendNQty VARCHAR(23) --DECIMAL(22,10) --借出浮动
	,@BorrowQty VARCHAR(23) --DECIMAL(22,10) --借进数量
	,@BorrowNQty VARCHAR(23) --DECIMAL(22,10) --借进浮动
	,@ErrMsg NVARCHAR(200)
)
--@encode$--  	
AS
BEGIN
	DECLARE @btypeId VARCHAR(50)
			,@stockId VARCHAR(50)
			,@ptypeId VARCHAR(50);
			
	DECLARE @itemFrom VARCHAR(20)
			,@itemId VARCHAR(20)
			,@itemValueId VARCHAR(20);
		
	
	IF NOT EXISTS(SELECT 1 FROM dbo.btype WHERE UserCode=@bTypeCode AND FullName=@bTypeName)
	BEGIN
		SET @ErrMsg='不存在此编号与名称对应的往来单位';
		RETURN -1;
	END
	IF NOT EXISTS(SELECT 1 FROM dbo.Stock WHERE UserCode=@stockCode AND FullName=@stockName)
	BEGIN
		SET @ErrMsg='不存在此编号与名称对应的仓库';
		RETURN -1;
	END
	IF NOT EXISTS(SELECT 1 FROM dbo.ptype WHERE UserCode=@pTypeCode AND FullName=@pTypeName)
	BEGIN
		SET @ErrMsg='不存在此编号与名称对应的商品';
		RETURN -1;
	END

	-- 选id
	SELECT @btypeId=typeId FROM dbo.btype WHERE UserCode=@bTypeCode;
	SELECT @stockId=typeId FROM dbo.Stock WHERE UserCode=@stockCode;
	SELECT @ptypeId=typeid FROM dbo.ptype WHERE UserCode=@pTypeCode;
	
	-- 验证系统是否启用自由项，和商品是否启用
	IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='isfreeitem' AND SubValue='1')
	AND EXISTS(SELECT 1 FROM dbo.ptype WHERE customitemid IS NOT NULL AND customitemid>0)
	BEGIN
		SELECT @itemId=customitemid,@itemFrom=customitemfrom FROM dbo.ptype WHERE typeId=@ptypeId;
		-- 自由项验证
		IF @itemId IS NOT NULL AND @itemFrom IS NOT NULL
		BEGIN
			SET @itemValueId=[dbo].[F_Get_FreeItem_ValueID](@itemId,@itemValueName,@itemFrom);
			IF @itemValueId =-99999 
			BEGIN
				SET @ErrMsg='自由项数据错误';
				RETURN -1;
			END
		END	
	END
	
	--插入
	INSERT INTO dbo.IniGoodsLend
	        ( BtypeId ,
	          PtypeId ,
	          KtypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          Qty ,
	          Price ,
	          Total ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ItemID ,
	          Iscombined ,
	          Nqty ,
	          ProduceDate ,
	          ValidDate ,
	          LendQty ,
	          NLendQty ,
	          BorrowQty ,
	          NBorrowQty
	        )
	VALUES  ( @btypeId , -- BtypeId - varchar(50)
	          @ptypeId , -- PtypeId - varchar(50)
	          @stockId , -- KtypeId - varchar(50)
	          '' , -- JobNumber - varchar(20)
	          GETDATE() , -- OutFactoryDate - datetime
	          ISNULL(CAST(@BorrowQty AS DECIMAL(22,10)),0)-ISNULL(CAST(@LendQty AS DECIMAL(22,10)),0) , -- Qty - numeric
	          0.0000 , -- Price - numeric
	          0.0000 , -- Total - numeric
	          0 , -- GoodsOrder - int
	          '' , -- GoodsNumber - varchar(100)
	          CASE WHEN @itemValueId=-99999 OR @itemValueId IS NULL THEN 0 ELSE CAST(@itemValueId AS INT) END, -- ItemID - int
	          ISNULL(@itemFrom,0) , -- Iscombined - bit
	          ISNULL(CAST(@BorrowNQty AS DECIMAL(22,10)),0)-ISNULL(CAST(@LendNQty AS DECIMAL(22,10)),0) , -- Nqty - numeric
	          '' , -- ProduceDate - varchar(50)
	          '' , -- ValidDate - varchar(50)
	          ISNULL(CAST(@LendQty AS DECIMAL(22,10)),0) , -- LendQty - numeric
	          ISNULL(CAST(@LendNQty AS DECIMAL(22,10)),0) , -- NLendQty - numeric
	          ISNULL(CAST(@BorrowQty AS DECIMAL(22,10)),0) , -- BorrowQty - numeric
	          ISNULL(CAST(@BorrowNQty AS DECIMAL(22,10)),0)  -- NBorrowQty - numeric
	        )
	
END

GO



GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ImportIniLendDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].GP_ImportIniLendDT
GO
/*
	作者：周华
	时间：2012-08-17
	描述：借欠期初导入
*/
CREATE PROC GP_ImportIniLendDT
(
	@dt TbType_IniLend READONLY
)
--@encode$--  	
AS
BEGIN
	BEGIN TRAN 
	BEGIN TRY
		DELETE a FROM dbo.IniGoodsLend a JOIN (SELECT DISTINCT BtypeId,PtypeId,KtypeId FROM @dt ) b ON a.BtypeId=b.BtypeId AND a.PtypeId=b.PtypeId AND a.KtypeId=b.KtypeId
		INSERT INTO dbo.IniGoodsLend
	        ( BtypeId ,
	          PtypeId ,
	          KtypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          Qty ,
	          --Price ,
	          --Total ,
	          --GoodsOrder ,
	          GoodsNumber ,
	          ItemID ,
	          Iscombined ,
	          Nqty ,
	          ProduceDate ,
	          ValidDate ,
	          LendQty ,
	          NLendQty ,
	          BorrowQty ,
	          NBorrowQty
	        )
		SELECT   BtypeId , -- BtypeId - varchar(50)
	          PtypeId , -- PtypeId - varchar(50)
	          KtypeId , -- KtypeId - varchar(50)
	          '' , -- JobNumber - varchar(20)
	          GETDATE() , -- OutFactoryDate - datetime
	          SUM(BorrowQty)-SUM(LendQty) , -- Qty - numeric
	          --NULL , -- Price - numeric
	          --NULL , -- Total - numeric
	          --0 , -- GoodsOrder - int
	          GoodsNumber , -- GoodsNumber - varchar(100)
	          ItemId , -- ItemID - int
	          Iscombined , -- Iscombined - bit
	          SUM(NBorrowQty)-SUM(NLendQty), -- Nqty - numeric
	          '' , -- ProduceDate - varchar(50)
	          '' , -- ValidDate - varchar(50)
	          SUM(LendQty) , -- LendQty - numeric
	          SUM(NLendQty) , -- NLendQty - numeric
	          SUM(BorrowQty) , -- BorrowQty - numeric
	          SUM(NBorrowQty)  -- NBorrowQty - numeric
		FROM @dt GROUP BY BtypeId,PtypeId,KtypeId,ItemID,Iscombined,GoodsNumber
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		ROLLBACK TRAN
	END CATCH
END
GO




GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[gp_ImportIniPhStockDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].gp_ImportIniPhStockDT
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：ZT
	时间：2016-07-04
	描述：实物库存期初导入
*/
CREATE PROC gp_ImportIniPhStockDT
(
	@dt TbType_IniStock READONLY
)
--@encode$--  	
AS
BEGIN
	DECLARE @costing VARCHAR(50)='';
	SELECT @costing=SubValue FROM dbo.sysdata WHERE SubName='costing';
	DECLARE @serialRelation VARCHAR(10)= ''
	SELECT @serialRelation = Value FROM dbo.Userconfig WHERE ConfigName='serialRelation'
	
		
	SELECT * INTO #dt1 FROM @dt
	UPDATE #dt1 SET ProduceDate = CONVERT(VARCHAR(10), CONVERT(datetime, ProduceDate),20) WHERE ProduceDate<>''
	UPDATE #dt1 SET ValidDate =   CONVERT(VARCHAR(10), CONVERT(datetime, ValidDate),20)   WHERE ValidDate<>'' 

	DECLARE 
	 @PtypeId VARCHAR(50)
	,@KTypeID VARCHAR(50)
	,@CargoId INT
	,@ItemId INT
	,@Iscombined BIT
	,@ProduceDate VARCHAR(50)
	,@Validdate VARCHAR(50)
	,@GoodsNumber VARCHAR(100)
	,@Serial VARCHAR(MAX)
	,@index INT = 1
	,@STypeID VARCHAR(50)
	,@Id INT 
	,@Qty  NUMERIC(24, 10) 
	,@GoodsOrder INT
			
			

--BEGIN TRAN
--BEGIN TRY
DELETE a FROM dbo.IniFactStocks a 
JOIN (SELECT DISTINCT PtypeId,KtypeId FROM #dt1) b ON a.PtypeId=b.PtypeId AND a.KtypeId=b.KtypeId;

DELETE a FROM dbo.IniFactStocks_Qty a 
JOIN (SELECT DISTINCT PtypeId,KtypeId FROM #dt1) b ON a.PtypeId=b.PtypeId AND a.KtypeId=b.KtypeId;

IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngSerial' AND Value='1')
BEGIN
	DELETE a FROM gp_iniFactPtypeSerial a JOIN (SELECT DISTINCT PtypeId,KtypeId FROM #dt1) b 
	ON a.PtypeId=b.PtypeId AND a.KtypeId=b.KtypeId AND a.State = 1;
END
			
--IF @costing=0
BEGIN 
	INSERT INTO IniFactStocks (PtypeId,KtypeId,Qty)
	SELECT PtypeId,KtypeId, dbo.F_RoundQty( SUM(Qty) ) FROM #dt1
	GROUP BY PtypeId,KtypeId  

	
	INSERT INTO IniFactStocks_Qty(PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,qty,NQty)
	SELECT PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,
		CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END ,
		CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END ,
		dbo.F_RoundQty(SUM(qty)),dbo.F_RoundQty(SUM(NQty))
	FROM #dt1
	GROUP BY PtypeId,KtypeId,CargoID,ItemID,Iscombined,GoodsNumber,
	CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END ,
	CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END ;	
	
	

	DECLARE CURSORT0 CURSOR FOR
	SELECT   PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,
				CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END AS 'ProduceDate',
				CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END AS 'Validdate'
	FROM #dt1
	GROUP BY PtypeId,KtypeId,CargoID,ItemID,Iscombined,GoodsNumber,
		CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END ,
		CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END 
	
	OPEN CURSORT0
	FETCH NEXT FROM CURSORT0 INTO @PtypeId,@KTypeID,@CargoId,@ItemId,@Iscombined,@GoodsNumber,@ProduceDate,@ValidDate
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF  EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngSerial' AND Value='1')
		BEGIN
			IF EXISTS(select TOP 1 1 from ptype WHERE ifSerial='1' AND Typeid=@PtypeId) 
			BEGIN
				SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @KTypeID	
				DECLARE CURSORT00 CURSOR FOR
				SELECT Serial FROM #dt1
				WHERE  PtypeId = @PtypeId AND  KTypeID = @KTypeID AND  CargoID= @CargoId AND  Itemid = @ItemId AND  Iscombined = @Iscombined 
				AND  GoodsNumber = @GoodsNumber AND ProduceDate = ISNULL( @ProduceDate ,'') AND ValidDate = ISNULL( @ValidDate ,'') 	AND Serial != ''
				OPEN CURSORT00
				FETCH NEXT FROM CURSORT00 INTO @Serial 
				WHILE @@FETCH_STATUS = 0
				BEGIN 
					 INSERT INTO dbo.gp_iniFactPtypeSerial 
								 (Serial , KtypeID , PtypeID , InKtypeTime , State , Flag ,  GoodsNumber , 
								 STypeId , ItemID , IsCombined , CargoID , ProduceDate , ValidDate) 
					 SELECT a AS 'Serial',@KTypeID,@PtypeId, GETDATE(),1,1, ISNULL(@GoodsNumber,''),
							@STypeID,ISNULL(@ItemId,0),ISNULL(@Iscombined,0),@CargoId,ISNULL(@ProduceDate,''),ISNULL(@ValidDate,'') FROM dbo.f_split(@Serial,',')
					 FETCH NEXT FROM CURSORT00 INTO @Serial
				END
				CLOSE CURSORT00
				DEALLOCATE CURSORT00
			END
			ELSE
			BEGIN
				--商品没有启用强制序列号
				GOTO ERROR1
			END
		END
		ELSE
		BEGIN
			--系统没有启用序列号严密管理,随便搞
			SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @KTypeID	
			DECLARE CURSORT00 CURSOR FOR
			SELECT Serial FROM #dt1
			WHERE  PtypeId = @PtypeId AND  KTypeID = @KTypeID AND  CargoID= @CargoId AND  Itemid = @ItemId AND  Iscombined = @Iscombined 
			AND  GoodsNumber = @GoodsNumber AND ProduceDate = ISNULL( @ProduceDate ,'') AND ValidDate = ISNULL( @ValidDate ,'') 	AND Serial != ''
			OPEN CURSORT00
			FETCH NEXT FROM CURSORT00 INTO @Serial 
			WHILE @@FETCH_STATUS = 0
			BEGIN 
				 INSERT INTO dbo.gp_iniFactPtypeSerial 
							 (Serial , KtypeID , PtypeID , InKtypeTime , State , Flag ,  GoodsNumber , 
							 STypeId , ItemID , IsCombined , CargoID , ProduceDate , ValidDate) 
				 SELECT a AS 'Serial',@KTypeID,@PtypeId, GETDATE(),1,1, ISNULL(@GoodsNumber,''),
						@STypeID,ISNULL(@ItemId,0),ISNULL(@Iscombined,0),@CargoId,ISNULL(@ProduceDate,''),ISNULL(@ValidDate,'') FROM dbo.f_split(@Serial,',')
				 FETCH NEXT FROM CURSORT00 INTO @Serial
			END
			CLOSE CURSORT00
			DEALLOCATE CURSORT00
		END
	
		FETCH NEXT FROM CURSORT0 INTO @PtypeId,@KTypeID,@CargoId,@ItemId,@Iscombined,@GoodsNumber ,@ProduceDate,@ValidDate
	END
	CLOSE CURSORT0
	DEALLOCATE CURSORT0
END
			
DROP TABLE #dt1	
return 0		

ERROR1:
	CLOSE CURSORT0
	DEALLOCATE CURSORT0
RETURN -1
			
END
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[gp_ImportIniStockDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].gp_ImportIniStockDT
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-08-17
	描述：库存期初导入
*/
CREATE PROC gp_ImportIniStockDT
(
	@dt TbType_IniStock READONLY
)
--@encode$--  	
AS
BEGIN

DECLARE @costing VARCHAR(50)='';
SELECT @costing=SubValue FROM dbo.sysdata WHERE SubName='costing';
DECLARE @serialRelation VARCHAR(10)= ''
SELECT @serialRelation = Value FROM dbo.Userconfig WHERE ConfigName='serialRelation'
	
SELECT * INTO #dt1 FROM @dt
UPDATE #dt1 SET ProduceDate = CONVERT(VARCHAR(10), CONVERT(datetime, ProduceDate),20) WHERE ProduceDate<>''
UPDATE #dt1 SET ValidDate =   CONVERT(VARCHAR(10), CONVERT(datetime, ValidDate),20)   WHERE ValidDate<>'' 
	
DECLARE 
 @PtypeId VARCHAR(50)
,@KTypeID VARCHAR(50)
,@CargoId INT
,@ItemId INT
,@Iscombined BIT
,@ProduceDate VARCHAR(50)
,@Validdate VARCHAR(50)
,@GoodsNumber VARCHAR(100)
,@Serial VARCHAR(MAX)
,@index INT = 1
,@STypeID VARCHAR(50)
,@Id INT 
,@Qty  NUMERIC(24, 10) 
,@CostPrice  NUMERIC(24, 10) 
,@GoodsOrder INT
			

DELETE a FROM dbo.IniGoodsStocks a JOIN (SELECT DISTINCT PtypeId,KtypeId FROM #dt1) b ON a.PtypeId=b.PtypeId AND a.KtypeId=b.KtypeId;
DELETE a FROM ini_goodsstocks_qty a JOIN (SELECT DISTINCT PtypeId,KtypeId FROM #dt1) b ON a.PtypeId=b.PtypeId AND a.KtypeId=b.KtypeId;

--IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngSerial' AND Value='1')
--BEGIN
	DELETE a FROM gp_initPtypeSerial a JOIN (SELECT DISTINCT PtypeId,KtypeId FROM #dt1) b ON a.PtypeId=b.PtypeId AND a.KtypeId=b.KtypeId AND a.State = 1;
--END
IF @costing=0
BEGIN
	INSERT INTO IniGoodsStocks (PtypeId,KtypeId,JobNumber,OutFactoryDate,Qty,Price,Total,GoodsOrder,GoodsNumber)
	SELECT PtypeId,KtypeId,'',GETDATE(), 
	dbo.F_RoundQty( SUM(Qty) ),
	dbo.F_RoundPrice( dbo.F_RoundTotal( SUM(qty*price)) *1.0/SUM(qty) ),
	dbo.F_RoundTotal( SUM(qty*price) ),0,
	'' FROM #dt1 GROUP BY PtypeId,KtypeId  
 
				
	INSERT INTO Ini_GOODSSTOCKS_QTY(PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,qty,NQty)
	SELECT PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,
		CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END ,
		CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END ,
		dbo.F_RoundQty(SUM(qty)),dbo.F_RoundQty(SUM(NQty))
	FROM #dt1
	GROUP BY PtypeId,KtypeId,CargoID,ItemID,Iscombined,GoodsNumber,
	CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END ,
	CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END ;	
				

	DECLARE CURSORT0 CURSOR FOR
	SELECT   PtypeId,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,
				CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END AS 'ProduceDate',
				CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END AS 'Validdate'
	FROM #dt1
	GROUP BY PtypeId,KtypeId,CargoID,ItemID,Iscombined,GoodsNumber,
	CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END ,
	CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END 
						
	OPEN CURSORT0
	FETCH NEXT FROM CURSORT0 INTO @PtypeId,@KTypeID,@CargoId,@ItemId,@Iscombined,@GoodsNumber,@ProduceDate,@ValidDate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF  EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngSerial' AND Value='1')
		BEGIN
			IF EXISTS(select TOP 1 1 from ptype WHERE ifSerial='1' AND Typeid=@PtypeId) 
			BEGIN
				SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @KTypeID	
				SELECT @Id = id FROM dbo.Ini_GOODSSTOCKS_QTY WHERE PtypeId = @PtypeId AND 
				KTypeID = @KTypeID AND CargoID= @CargoId AND Itemid = @ItemId AND Iscombined = @Iscombined AND GoodsNumber = @GoodsNumber 
				AND ProduceDate = ISNULL( @ProduceDate ,'')AND ValidDate = ISNULL( @ValidDate,'')
				
				DECLARE CURSORT00 CURSOR FOR
				SELECT Serial FROM #dt1
				WHERE  PtypeId = @PtypeId AND  KTypeID = @KTypeID AND  CargoID= @CargoId AND  Itemid = @ItemId AND  Iscombined = @Iscombined 
				AND  GoodsNumber = @GoodsNumber AND ProduceDate = ISNULL( @ProduceDate ,'') AND ValidDate = ISNULL( @ValidDate ,'') 	AND Serial != ''
				OPEN CURSORT00
				FETCH NEXT FROM CURSORT00 INTO @Serial 
				WHILE @@FETCH_STATUS = 0
				BEGIN
					 INSERT INTO dbo.gp_initPtypeSerial 
								 (ID ,Serial , KtypeID , PtypeID , InKtypeTime , State , Flag , iniFlag , CostPrice  , GoodsNumber , 
								 STypeId , ItemID , IsCombined , CargoID , ProduceDate , ValidDate) 
					 SELECT @Id,a AS 'Serial',@KTypeID,@PtypeId, GETDATE(),1,1,1,0, ISNULL(@GoodsNumber,''),
							@STypeID,ISNULL(@ItemId,0),ISNULL(@Iscombined,0),@CargoId,ISNULL(@ProduceDate,''),ISNULL(@ValidDate,'') FROM dbo.f_split(@Serial,',')
					 FETCH NEXT FROM CURSORT00 INTO @Serial
				END
				CLOSE CURSORT00
				DEALLOCATE CURSORT00
			END
		END
		ELSE
		BEGIN
			SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @KTypeID	
				SELECT @Id = id FROM dbo.Ini_GOODSSTOCKS_QTY WHERE PtypeId = @PtypeId AND 
				KTypeID = @KTypeID AND CargoID= @CargoId AND Itemid = @ItemId AND Iscombined = @Iscombined AND GoodsNumber = @GoodsNumber 
				AND ProduceDate = ISNULL( @ProduceDate ,'')AND ValidDate = ISNULL( @ValidDate,'')
				
				DECLARE CURSORT01 CURSOR FOR
				SELECT Serial FROM #dt1
				WHERE  PtypeId = @PtypeId AND  KTypeID = @KTypeID AND  CargoID= @CargoId AND  Itemid = @ItemId AND  Iscombined = @Iscombined 
				AND  GoodsNumber = @GoodsNumber AND ProduceDate = ISNULL( @ProduceDate ,'') AND ValidDate = ISNULL( @ValidDate ,'') 	AND Serial != ''
				OPEN CURSORT01
				FETCH NEXT FROM CURSORT01 INTO @Serial 
				WHILE @@FETCH_STATUS = 0
				BEGIN
					 INSERT INTO dbo.gp_initPtypeSerial 
								 (ID ,Serial , KtypeID , PtypeID , InKtypeTime , State , Flag , iniFlag , CostPrice  , GoodsNumber , 
								 STypeId , ItemID , IsCombined , CargoID , ProduceDate , ValidDate) 
					 SELECT @Id,a AS 'Serial',@KTypeID,@PtypeId, GETDATE(),1,1,1,0, ISNULL(@GoodsNumber,''),
							@STypeID,ISNULL(@ItemId,0),ISNULL(@Iscombined,0),@CargoId,ISNULL(@ProduceDate,''),ISNULL(@ValidDate,'') FROM dbo.f_split(@Serial,',')
					 FETCH NEXT FROM CURSORT01 INTO @Serial
				END
				CLOSE CURSORT01
				DEALLOCATE CURSORT01
		END
		
		FETCH NEXT FROM CURSORT0 INTO @PtypeId,@KTypeID,@CargoId,@ItemId,@Iscombined,@GoodsNumber ,@ProduceDate,@ValidDate
	END
	CLOSE CURSORT0
	DEALLOCATE CURSORT0
END
ELSE IF @costing IN (1,2)
BEGIN
	INSERT INTO IniGoodsStocks(PtypeId,KTypeId,Qty,Price,Total,ProduceDate,ValidDate,GoodsOrder) 
	SELECT PtypeId,KTypeId,Qty,Price,Total,ProduceDate,ValidDate,
		ROW_NUMBER() OVER(PARTITION BY PtypeID,KtypeID ORDER BY PtypeID desc ) GoodsOrder 
		FROM (
		SELECT PtypeId,KtypeId, dbo.F_RoundQty(SUM(Qty))AS qty,Price ,dbo.F_RoundTotal(SUM(qty*price)) AS Total,
		0 AS GoodsOrder,--ROW_NUMBER() OVER(ORDER BY GETDATE()),--先进先出 后进先出 没有批次
		'' AS ProduceDate,''  AS ValidDate
		FROM #dt1 
		GROUP BY PtypeId,KtypeId,Price
	) AS t

	INSERT INTO Ini_goodsstocks_qty(PTypeId,KTypeId,CargoId,ItemId,Iscombined,GoodsNumber,Qty,NQty,ProduceDate,ValidDate)
	SELECT PtypeId,KtypeId,CargoID,ItemID,Iscombined,GoodsNumber,dbo.F_RoundQty(SUM(qty)),dbo.F_RoundQty(SUM(nqty)),'',''
	FROM #dt1 GROUP BY  PtypeID,KtypeID,CargoId,ItemID,Iscombined,GoodsNumber

	DECLARE @mngcargospace INT, @ifitem INT
	SELECT @mngcargospace = Value FROM dbo.Userconfig WHERE ConfigName='mngcargospace'


	DECLARE CURSORT1 CURSOR FOR
	SELECT PtypeId,KtypeId,CargoID,ItemID,Iscombined
	FROM #dt1 
	GROUP BY  PtypeID,KtypeID,CargoId,ItemID,Iscombined

	OPEN CURSORT1
	FETCH NEXT FROM CURSORT1 INTO @PtypeId,@KTypeID,@CargoId,@ItemId,@Iscombined
	WHILE @@FETCH_STATUS = 0
	BEGIN			
		IF  EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngSerial' AND Value='1')
		BEGIN
			IF EXISTS(select TOP 1 1 from ptype WHERE ifSerial='1' AND Typeid=@PtypeId) 
			BEGIN
				SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @KTypeID	
				SELECT @Id = id FROM dbo.Ini_GOODSSTOCKS_QTY 
				WHERE PtypeId = @PtypeId AND  KTypeID = @KTypeID AND  CargoID= @CargoId AND  Itemid = @ItemId AND  Iscombined = @Iscombined 
				
				SELECT @ifitem = customitemid  FROM ptype WHERE typeid=@PtypeId 
				
				DECLARE CURSORT11 CURSOR FOR
				SELECT Serial,price FROM #dt1
				WHERE  PtypeId = @PtypeId AND  KTypeID = @KTypeID AND  CargoID= @CargoId AND  Itemid = @ItemId AND  Iscombined = @Iscombined AND Serial != ''
				OPEN CURSORT11
				FETCH NEXT FROM CURSORT11 INTO @Serial,@CostPrice
				WHILE @@FETCH_STATUS = 0
				BEGIN
					 SET @GoodsOrder = 0
					 IF @mngcargospace <> 1 AND (@ifitem IS NULL OR @ifitem = '' OR @ifitem = 0)
					 BEGIN 
						SELECT @GoodsOrder = GoodsOrder FROM dbo.IniGoodsStocks WHERE PtypeId = @PtypeId AND  KTypeID = @KTypeID AND Price = @CostPrice
					 END 
					 INSERT INTO dbo.gp_initPtypeSerial 
								 (ID ,Serial , KtypeID , PtypeID , InKtypeTime , State , Flag , iniFlag , CostPrice  , GoodsNumber , STypeId , ItemID , IsCombined , CargoID , ProduceDate , ValidDate,GoodsOrder) 
					 SELECT @Id,a AS 'Serial',@KTypeID,@PtypeId, GETDATE(),1,1,1,0,'',@STypeID,@ItemId,@Iscombined,@CargoId,'','',@GoodsOrder FROM dbo.f_split(@Serial,',')
					 FETCH NEXT FROM CURSORT11 INTO @Serial,@CostPrice
				END
					CLOSE CURSORT11
					DEALLOCATE CURSORT11
			END
		END
		ELSE
		BEGIN
				SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @KTypeID	
				SELECT @Id = id FROM dbo.Ini_GOODSSTOCKS_QTY 
				WHERE PtypeId = @PtypeId AND  KTypeID = @KTypeID AND  CargoID= @CargoId AND  Itemid = @ItemId AND  Iscombined = @Iscombined 
				
				SELECT @ifitem = customitemid  FROM ptype WHERE typeid=@PtypeId 
				
				DECLARE CURSORT12 CURSOR FOR
				SELECT Serial,price FROM #dt1
				WHERE  PtypeId = @PtypeId AND  KTypeID = @KTypeID AND  CargoID= @CargoId AND  Itemid = @ItemId AND  Iscombined = @Iscombined AND Serial != ''
				OPEN CURSORT12
				FETCH NEXT FROM CURSORT12 INTO @Serial,@CostPrice
				WHILE @@FETCH_STATUS = 0
				BEGIN
					 SET @GoodsOrder = 0
					 IF @mngcargospace <> 1 AND (@ifitem IS NULL OR @ifitem = '' OR @ifitem = 0)
					 BEGIN 
						SELECT @GoodsOrder = GoodsOrder FROM dbo.IniGoodsStocks WHERE PtypeId = @PtypeId AND  KTypeID = @KTypeID AND Price = @CostPrice
					 END 
					 INSERT INTO dbo.gp_initPtypeSerial 
								 (ID ,Serial , KtypeID , PtypeID , InKtypeTime , State , Flag , iniFlag , CostPrice  , GoodsNumber , STypeId , ItemID , IsCombined , CargoID , ProduceDate , ValidDate,GoodsOrder) 
					 SELECT @Id,a AS 'Serial',@KTypeID,@PtypeId, GETDATE(),1,1,1,0,'',@STypeID,@ItemId,@Iscombined,@CargoId,'','',@GoodsOrder FROM dbo.f_split(@Serial,',')
					 FETCH NEXT FROM CURSORT12 INTO @Serial,@CostPrice
				END
					CLOSE CURSORT12
					DEALLOCATE CURSORT12
		END

			FETCH NEXT FROM CURSORT1 INTO @PtypeId,@KTypeID,@CargoId,@ItemId,@Iscombined
		END
		CLOSE CURSORT1
		DEALLOCATE CURSORT1
END
ELSE
BEGIN

	INSERT INTO IniGoodsStocks(PtypeId,KTypeId,Qty,Price,Total,ProduceDate,Validdate,GoodsNumber,GoodsOrder) 
	SELECT PtypeId,KtypeId, dbo.F_RoundQty(SUM(Qty)),Price,dbo.F_RoundTotal(SUM(qty*price))
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
	,GoodsNumber,ROW_NUMBER() OVER(ORDER BY GETDATE()) FROM #dt1
	GROUP BY  PtypeId,KtypeId,Price
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
	,GoodsNumber

	INSERT INTO Ini_goodsstocks_qty(PTypeId,KTypeId,Qty,CargoId,ItemId,NQty,Iscombined,ProduceDate,Validdate,GoodsNumber,GoodsCostPrice)
	SELECT PtypeId,KtypeId,dbo.F_RoundQty(SUM(qty)),CargoID,ItemID,dbo.F_RoundQty(SUM(Nqty)),Iscombined
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
	,GoodsNumber,price FROM #dt1 
	GROUP BY  PtypeId,KtypeId,Price
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
	,GoodsNumber,CargoID,ItemID,Iscombined


	DECLARE CURSORT3 CURSOR FOR
	SELECT PtypeId,KtypeId,CargoID,ItemID,Iscombined
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END AS 'ProduceDate'
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END AS 'Validdate'
	,GoodsNumber,price
	FROM #dt1 
	GROUP BY  PtypeId,KtypeId,Price
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
	,GoodsNumber,CargoID,ItemID,Iscombined

	OPEN CURSORT3
	FETCH NEXT FROM CURSORT3 INTO @PtypeId,@KTypeID,@CargoId,@ItemId,@Iscombined,@ProduceDate,@ValidDate,@GoodsNumber,@CostPrice
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF  EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngSerial' AND Value='1')
		BEGIN
			IF EXISTS(select TOP 1 1 from ptype WHERE ifSerial='1' AND Typeid=@PtypeId) 
			BEGIN
				SELECT @GoodsOrder = GoodsOrder FROM IniGoodsStocks WHERE PtypeId = @PtypeId AND 
				KTypeID = @KTypeID AND GoodsNumber = ISNULL( @GoodsNumber,'') AND Price = @CostPrice 
				AND ProduceDate = ISNULL( @ProduceDate ,'')AND ValidDate = ISNULL( @ValidDate,'')

				SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @KTypeID	

				SELECT @Id = id FROM dbo.Ini_GOODSSTOCKS_QTY WHERE 
				PtypeId = @PtypeId AND 	KTypeID = @KTypeID AND CargoID= @CargoId AND Itemid = @ItemId AND 
				Iscombined = @Iscombined AND GoodsNumber =ISNULL(  @GoodsNumber,'')	AND ProduceDate = ISNULL( @ProduceDate ,'') 
				AND ValidDate = ISNULL( @ValidDate,'')
				AND GoodsCostPrice = @CostPrice

				DECLARE CURSORT33 CURSOR FOR
				SELECT Serial FROM #dt1
				WHERE PtypeId = @PtypeId AND 	KTypeID = @KTypeID AND CargoID= @CargoId AND Itemid = @ItemId AND 
				Iscombined = @Iscombined AND GoodsNumber =ISNULL(  @GoodsNumber,'')	AND ProduceDate = ISNULL( @ProduceDate ,'')
				AND ValidDate = ISNULL( @ValidDate ,'') AND price = @CostPrice AND Serial != ''
				OPEN CURSORT33
				FETCH NEXT FROM CURSORT33 INTO @Serial 
				WHILE @@FETCH_STATUS = 0
				BEGIN
					 INSERT INTO dbo.gp_initPtypeSerial 
								 (ID ,Serial , KtypeID , PtypeID , InKtypeTime , State , Flag , iniFlag , CostPrice  , GoodsOrder,GoodsNumber , STypeId , ItemID									, IsCombined , CargoID , ProduceDate , ValidDate) 
					 SELECT @Id,a AS 'Serial',@KTypeID,@PtypeId, GETDATE(),1,1,1,@CostPrice,@GoodsOrder ,@GoodsNumber,@STypeID,@ItemId,@Iscombined,@CargoId,
					 @ProduceDate,@ValidDate FROM dbo.f_split(@Serial,',')
					 FETCH NEXT FROM CURSORT33 INTO @Serial
				END
				CLOSE CURSORT33
				DEALLOCATE CURSORT33
			END
		END
		ELSE
		BEGIN
			SELECT @GoodsOrder = GoodsOrder FROM IniGoodsStocks WHERE PtypeId = @PtypeId AND 
			KTypeID = @KTypeID AND GoodsNumber = ISNULL( @GoodsNumber,'') AND Price = @CostPrice AND ProduceDate = ISNULL( @ProduceDate ,'')
			AND ValidDate = ISNULL( @ValidDate,'')
			
			SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @KTypeID	
			
			SELECT @Id = id FROM dbo.Ini_GOODSSTOCKS_QTY WHERE 
			PtypeId = @PtypeId AND 	KTypeID = @KTypeID AND CargoID= @CargoId AND Itemid = @ItemId AND 
			Iscombined = @Iscombined AND GoodsNumber =ISNULL(  @GoodsNumber,'')	AND ProduceDate = ISNULL( @ProduceDate ,'')
			AND ValidDate = ISNULL( @ValidDate,'') AND GoodsCostPrice = @CostPrice
			
			DECLARE CURSORT34 CURSOR FOR
			SELECT Serial FROM #dt1
			WHERE PtypeId = @PtypeId AND 	KTypeID = @KTypeID AND CargoID= @CargoId AND Itemid = @ItemId AND 
			Iscombined = @Iscombined AND GoodsNumber =ISNULL(  @GoodsNumber,'')	AND ProduceDate = ISNULL( @ProduceDate ,'')
			AND ValidDate = ISNULL( @ValidDate ,'') AND price = @CostPrice AND Serial != ''
			OPEN CURSORT34
			FETCH NEXT FROM CURSORT34 INTO @Serial 
			WHILE @@FETCH_STATUS = 0
			BEGIN
				 INSERT INTO dbo.gp_initPtypeSerial 
							 (ID ,Serial , KtypeID , PtypeID , InKtypeTime , State , Flag , iniFlag , CostPrice  , GoodsOrder,GoodsNumber , 
							 STypeId , ItemID , IsCombined , CargoID , ProduceDate , ValidDate) 
				 SELECT @Id,a AS 'Serial',@KTypeID,@PtypeId, GETDATE(),1,1,1,@CostPrice,@GoodsOrder ,@GoodsNumber,@STypeID,@ItemId,@Iscombined,
				 @CargoId,@ProduceDate,@ValidDate FROM dbo.f_split(@Serial,',')
				 FETCH NEXT FROM CURSORT34 INTO @Serial
			END
			CLOSE CURSORT34
			DEALLOCATE CURSORT34
		END
		
		FETCH NEXT FROM CURSORT3 INTO @PtypeId,@KTypeID,@CargoId,@ItemId,@Iscombined,@ProduceDate,@ValidDate,@GoodsNumber,@CostPrice	
	END
	
	CLOSE CURSORT3
	DEALLOCATE CURSORT3
END
	
DROP TABLE #dt1
return 0	

END
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[gp_ImportIniStocks]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].gp_ImportIniStocks
GO

/*
	作者：周华
	时间：2012-08-07
	描述：库存期初导入 配置信息在存储过程中去读取。
*/
CREATE PROC gp_ImportIniStocks
(
	@StypeCode VARCHAR(26)
	,@StypeName VARCHAR(256)
	,@StockCode VARCHAR(26)
	,@StockName VARCHAR(256)
	,@ProductCode VARCHAR(200)
	,@ProductName VARCHAR(200)
	,@GoodsNum VARCHAR(100)
	,@CargoCode VARCHAR(200)
	,@CargoName VARCHAR(200)
	,@ItemValueName VARCHAR(500)
	,@ProduceDate VARCHAR(50)
	,@ValidDate VARCHAR(50)
	,@Price VARCHAR(23) --  NUMERIC(24, 10) 
	,@Qty VARCHAR(23)
	,@NQty VARCHAR(23)
	,@ErrMsg NVARCHAR(200)
)
--@encode$--  	
AS
BEGIN
	DECLARE @stypeid VARCHAR(50);
	DECLARE @costing VARCHAR(10);
	
	DECLARE @itemFrom VARCHAR(20)
			,@itemId VARCHAR(20)
			,@itemValueId VARCHAR(20);
	DECLARE @cargoEnable INT=0
			,@goodsNumEnable INT=0
			,@freeItemEnable INT=0;

	-- 验证
	IF NOT EXISTS(SELECT 1 FROM dbo.SType WHERE FullName=@StypeName AND UserCode=@StypeCode)
	BEGIN
		SET @ErrMsg='不存在编号与名称对应的分支机构';
		RETURN -1;
	END
	
	IF NOT EXISTS(SELECT 1 FROM stock WHERE FullName=@StockName AND UserCode=@StockCode)
	BEGIN
		SET @ErrMsg='不存在编号与名称对应的仓库';
		RETURN -1;
	END
	
	IF NOT EXISTS(SELECT 1 FROM dbo.ptype WHERE FullName=@ProductName AND UserCode=@ProductCode)
	BEGIN
		SET @ErrMsg='不存在编号与名称对应的商品';
		RETURN -1;
	END
	
	SELECT @stypeid=TypeId FROM dbo.SType WHERE UserCode=@StypeCode;
	
	IF NOT EXISTS(SELECT 1 FROM stock WHERE UserCode=@StockCode AND STypeID=@stypeid)
	BEGIN
		SET @ErrMsg='仓库不属于分支机构';
		RETURN -1;
	END
	
	-- 读取配置 验证
	-- 0 移动加权法   {启用 批号货位自由项 验证}
	-- 1,2 先进先出	{启用 货位自由项 验证}
	-- 3 手工指定 ｛启用 生产日期 有效至期 ｝ ｛启用 批号货位自由项 验证｝
	SELECT @costing=SubValue FROM dbo.sysdata WHERE SubName='costing';

	--启用货位,批号，自由项
	SELECT @cargoEnable=1 WHERE EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='mngcargospace' AND Value='1');
	SELECT @goodsNumEnable=1 WHERE EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='ifusegoodsnumber' AND Value='1')
		AND EXISTS(SELECT 1 FROM dbo.ptype WHERE IfUseGoodsNum='1')
	SELECT @freeItemEnable=1 WHERE EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='ifusegoodsnumber' AND Value='1')
	AND EXISTS(SELECT 1 FROM dbo.ptype WHERE customitemid IS NOT NULL AND customitemid>0)
	
	--货位
	IF @cargoEnable=1 AND NOT EXISTS(SELECT 1 FROM dbo.CargoType WHERE FullName=@CargoName AND UserCode=@CargoCode)
	BEGIN
		SET @ErrMsg='不存在编号和名称对应的货位';
		RETURN -1;
	END
	-- 批号
	IF @goodsNumEnable=1 AND (@GoodsNum='' OR @GoodsNum IS NULL)
	BEGIN
		SET @ErrMsg='批号为空';
		RETURN -1;
	END
	--自由项
	IF @freeItemEnable=1
	BEGIN
		SELECT @itemId=customitemid,@itemFrom=customitemfrom FROM dbo.ptype WHERE UserCode=@ProductCode;
		-- 自由项验证
		IF @itemId IS NOT NULL AND @itemFrom IS NOT NULL
		BEGIN
			SET @itemValueId=[dbo].[F_Get_FreeItem_ValueID](@itemId,@itemValueName,@itemFrom);
			IF @itemValueId =-99999 
			BEGIN
				SET @ErrMsg='自由项数据错误';
				RETURN -1;
			END
		END	
	END

	
	IF @costing='0'
	BEGIN
		SELECT 1;
	END
	ELSE IF @costing IN ('1','2')
	BEGIN
		SELECT 1;
	END
	ELSE
	BEGIN
		SELECT 1;
	END
END

GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ImportInitCommission]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ImportInitCommission]
GO

/****** Object:  StoredProcedure [dbo].[GP_ImportInitCommission]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：Haiyang, Li
	日    期：2012-08-17
	描	  述：导入委托代销期初
*/


CREATE PROCEDURE [dbo].[GP_ImportInitCommission]
(
      @Details TBType_ImportInitCommission READONLY
)
--@encode$--
AS 
    SET NOCOUNT ON
    SELECT  btypeid ,
            stypeid ,
            type ,
            ptypeid ,
            dbo.F_RoundTotal(SUM(costprice * qty))  AS costtotal ,
            dbo.F_RoundTotal(SUM(price * qty))AS total ,
            dbo.F_RoundQty(SUM(qty)) AS qty ,
            MAX(explain) AS explain
    INTO    #ImportCommissionInitTotal
    FROM    @Details
    GROUP BY btypeid ,
            stypeid ,
            type ,
            ptypeid
		
		
		
		
    DELETE  T
    FROM    IniCommissionStock T
            INNER JOIN #ImportCommissionInitTotal S ON T.Type = S.type
                                                       AND T.Ptypeid = S.ptypeid
                                                       AND T.btypeid = S.btypeid
                                                       AND T.stypeid = S.stypeid
		
    INSERT  INTO IniCommissionStock
            ( btypeid ,
              ptypeid ,
              ktypeid ,
              etypeid ,
              stypeid ,
              type ,
              qty ,
              CostTotal ,
              Total ,
              explain 
            )
            SELECT  btypeid ,
                    ptypeid ,
                    '' ,
                    '' ,
                    stypeid ,
                    type ,
                    qty ,
                    CostTotal ,
                    Total ,
                    explain
            FROM    #ImportCommissionInitTotal
		
		
    SELECT  btypeid ,
            stypeid ,
            type ,
            ptypeid ,
            ItemID ,
            Iscombined ,
            GoodsNumber ,
            dbo.F_RoundQty(SUM(qty)) AS qty ,
            dbo.F_RoundQty(SUM(nqty)) AS nqty ,
            MAX(explain) AS explain,
            Producedate,
            Validdate
    INTO    #ImportCommissionInitDetails
    FROM    @Details
    GROUP BY btypeid ,
            stypeid ,
            type ,
            ptypeid ,
            ItemID ,
            Iscombined ,
            GoodsNumber ,
            Producedate,
            Validdate
            
		DELETE  D
    FROM    IniCommissionStock_Qty D
            INNER JOIN #ImportCommissionInitDetails S ON D.Type = S.type
                                                       AND D.Ptypeid = S.ptypeid
                                                       AND D.btypeid = S.btypeid
                                                       AND D.stypeid = S.stypeid
		
		 INSERT  INTO IniCommissionStock_Qty
            ( PTypeId ,
              Btypeid ,
              Stypeid ,
              Type ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              Qty ,
              NQty,
              Producedate,
              Validdate
            )
            SELECT  PTypeId ,
                    BTypeId ,
                    Stypeid ,
                    Type ,
                    itemId ,
                    isCombined ,
                    goodsNumber ,
                    qty ,
                    nQty,
                    Producedate,
					Validdate
            FROM    #ImportCommissionInitDetails;
		
		
DROP TABLE #ImportCommissionInitDetails
DROP TABLE #ImportCommissionInitTotal
		

    SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportInitSerial]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_ImportInitSerial]
GO

/****** Object:  StoredProcedure [dbo].[Gp_ImportInitSerial]    Script Date: 05/25/2015 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：施训果
	日    期：2015-05-25
	描	  述：导入委托代销期初【序列号不关联自由项、批号、货位】
*/


CREATE PROCEDURE [dbo].[Gp_ImportInitSerial]
(
	  @Type INT,
	  @IsEnterCostPrice INT,
	  @serialRelation INT,
      @AddToDetails TBType_ImportInitCommission READONLY,
      @UpdateDetails TBType_ImportInitCommission READONLY,
      @SerialDetails TBType_ImportInitSerial READONLY
)
--@encode$--
AS 
    SET NOCOUNT ON
------------------------------------------处理数量需要叠加数据开始-----------------------------------------------
CREATE TABLE #ImportCommissionInitTotalAdd
(
	btypeid		varchar(50),
	stypeid		varchar(50),
	type		INT,
	ptypeid		varchar(50),
	SerialType		TINYINT,
	costtotal		 NUMERIC(24, 10) ,
	total		 NUMERIC(24, 10) ,
	qty			 NUMERIC(24, 10) ,
	explain		varchar(256),
	DealType		TINYINT
)

CREATE TABLE #ImportCommissionInitTotal
(
	btypeid		varchar(50),
	stypeid		varchar(50),
	type		INT,
	ptypeid		varchar(50),
	SerialType		TINYINT,
	costtotal		 NUMERIC(24, 10) ,
	total		 NUMERIC(24, 10) ,
	qty			 NUMERIC(24, 10) ,
	explain		varchar(256),
	DealType		TINYINT
)

CREATE TABLE #ImportCommissionInitDetailsAdd
(
	btypeid		varchar(50),
	stypeid		varchar(50),
	type		INT,
	ptypeid		varchar(50),
	ItemID		INT,
	Iscombined		BIT,
	GoodsNumber		varchar(100),
	SerialType		TINYINT,
	costprice		 NUMERIC(24, 10) ,
	qty				 NUMERIC(24, 10) ,
	nqty			 NUMERIC(24, 10) ,
	Producedate		varchar(50),
	Validdate		varchar(50),
	KTypeID			varchar(50),
	CargoID			INT,
	DealType		tinyint
)

CREATE TABLE #ImportCommissionInitDetails
(
	btypeid		varchar(50),
	stypeid		varchar(50),
	type		INT,
	ptypeid		varchar(50),
	ItemID		INT,
	Iscombined		BIT,
	GoodsNumber		varchar(100),
	SerialType		TINYINT,
	costprice		 NUMERIC(24, 10) ,
	qty				 NUMERIC(24, 10) ,
	nqty			 NUMERIC(24, 10) ,
	Producedate		varchar(50),
	Validdate		varchar(50),
	KTypeID			varchar(50),
	CargoID			INT,
	DealType		tinyint
)

CREATE TABLE #AddToDetails
(	
		 btypeid 				VARCHAR (50)					DEFAULT ('')
		,stypeid 				VARCHAR (50)					DEFAULT ('')
		,ptypeid				VARCHAR (50)					DEFAULT ('')
		,ktypeid				VARCHAR (50)					DEFAULT ('')
		,cargoid				VARCHAR (50)					DEFAULT ('')
		,type						INT NOT NULL
		,goodsNumber		VARCHAR(100)				 	DEFAULT ('')
		,itemId					INT										DEFAULT (0)
		,isCombined			BIT										DEFAULT (0)
		,qty 						 NUMERIC(24, 10)  				DEFAULT (0)
		,nQty 					 NUMERIC(24, 10)  				DEFAULT (0)
		,costprice			 NUMERIC(24, 10) 				DEFAULT (0)
		,price					 NUMERIC(24, 10) 			  DEFAULT (0)
		,explain				VARCHAR(256)				  DEFAULT ('')
		,Producedate             VARCHAR(50)               DEFAULT ('')
		,Validdate				VARCHAR(50)				  DEFAULT ('')
		,SerialType					INT
		,DealType					INT
);

CREATE TABLE #UpdateDetails
(	
		 btypeid 				VARCHAR (50)					DEFAULT ('')
		,stypeid 				VARCHAR (50)					DEFAULT ('')
		,ptypeid				VARCHAR (50)					DEFAULT ('')
		,ktypeid				VARCHAR (50)					DEFAULT ('')
		,cargoid				VARCHAR (50)					DEFAULT ('')
		,type						INT NOT NULL
		,goodsNumber		VARCHAR(100)				 	DEFAULT ('')
		,itemId					INT										DEFAULT (0)
		,isCombined			BIT										DEFAULT (0)
		,qty 						 NUMERIC(24, 10)  				DEFAULT (0)
		,nQty 					 NUMERIC(24, 10)  				DEFAULT (0)
		,costprice			 NUMERIC(24, 10) 				DEFAULT (0)
		,price					 NUMERIC(24, 10) 			  DEFAULT (0)
		,explain				VARCHAR(256)				  DEFAULT ('')
		,Producedate             VARCHAR(50)               DEFAULT ('')
		,Validdate				VARCHAR(50)				  DEFAULT ('')
		,SerialType					INT
		,DealType					INT
);

INSERT INTO #AddToDetails
        ( btypeid ,
          stypeid ,
          ptypeid ,
          ktypeid ,
          cargoid ,
          type ,
          goodsNumber ,
          itemId ,
          isCombined ,
          qty ,
          nQty ,
          costprice ,
          price ,
          explain ,
          Producedate ,
          Validdate ,
          SerialType ,
          DealType
        )
SELECT btypeid
		,stypeid 
		,ptypeid
		,ktypeid
		,cargoid
		,type
		,goodsNumber
		,itemId		
		,isCombined	
		,qty 
		,nQty
		,costprice
		,price
		,explain
		,Producedate
		,Validdate
		,SerialType
		,DealType
FROM @AddToDetails

INSERT INTO #UpdateDetails
        ( btypeid ,
          stypeid ,
          ptypeid ,
          ktypeid ,
          cargoid ,
          type ,
          goodsNumber ,
          itemId ,
          isCombined ,
          qty ,
          nQty ,
          costprice ,
          price ,
          explain ,
          Producedate ,
          Validdate ,
          SerialType ,
          DealType
        )
SELECT btypeid
		,stypeid 
		,ptypeid
		,ktypeid
		,cargoid
		,type
		,goodsNumber
		,itemId		
		,isCombined	
		,qty 
		,nQty
		,costprice
		,price
		,explain
		,Producedate
		,Validdate
		,SerialType
		,DealType
FROM @UpdateDetails

DECLARE @SQL VARCHAR(5000)
SET @SQL='INSERT INTO #ImportCommissionInitTotalAdd(btypeid,stypeid,type,ptypeid,costtotal,total,qty,explain,SerialType,DealType)
			SELECT  btypeid ,
            stypeid ,
            type ,
            ptypeid , 
            dbo.F_roundTotal(SUM(costprice * qty ))AS costtotal ,
            dbo.F_roundTotal(SUM(price * qty))AS total ,
            dbo.F_roundQty(SUM(qty)) AS qty ,
            MAX(explain) AS explain,'
IF @serialRelation=1
	SET @SQL=@SQL+'SerialType,DealType '
ELSE 
	SET @SQL=@SQL+'0 AS SerialType,0 AS DealType '
	
	SET @SQL=@SQL+' FROM #AddToDetails
			GROUP BY btypeid ,
					stypeid ,
					type ,
					ptypeid '
IF @serialRelation=1
	SET @SQL=@SQL+',SerialType,DealType '
EXEC (@SQL)
	SET @SQL=' MERGE #ImportCommissionInitTotalAdd ICIT 
			  USING IniCommissionStock IC 
			  ON IC.Type = ICIT.type
			  AND IC.Ptypeid = ICIT.ptypeid
			  AND IC.btypeid = ICIT.btypeid
			  AND IC.stypeid = ICIT.stypeid '
IF @serialRelation=1
	SET @SQL = @SQL+' AND IC.SerialType = ICIT.SerialType '
	
	SET @SQL=@SQL+' WHEN MATCHED THEN UPDATE SET ICIT.total=ICIT.total+IC.Total,ICIT.costtotal=ICIT.costtotal+IC.CostTotal,ICIT.qty=ICIT.qty+IC.qty; '
EXEC (@SQL)	

	SET @SQL=' DELETE  T 
			  FROM IniCommissionStock T 
              INNER JOIN #ImportCommissionInitTotalAdd S ON T.Type = S.type
              AND T.Ptypeid = S.ptypeid
              AND T.btypeid = S.btypeid
              AND T.stypeid = S.stypeid '
IF @serialRelation=1
	SET @SQL=@SQL+' AND T.SerialType=S.SerialType '
EXEC (@SQL)	

    INSERT  INTO IniCommissionStock
            ( btypeid ,
              ptypeid ,
              ktypeid ,
              etypeid ,
              stypeid ,
              type ,
              qty ,
              CostTotal ,
              Total ,
              SerialType,
              explain ,
              DealType
            )
            SELECT  btypeid ,
                    ptypeid ,
                    '10000' ,
                    '' ,
                    stypeid ,
                    type ,
                    qty ,
                    CostTotal ,
                    Total ,
                    SerialType,
                    explain,
                    DealType
            FROM    #ImportCommissionInitTotalAdd

SET @SQL='INSERT  INTO #ImportCommissionInitDetails(btypeid,stypeid,type,ptypeid,ItemID,Iscombined,
	GoodsNumber,qty,nqty,Producedate,Validdate,costprice,SerialType,KTypeID,CargoID,DealType)
	SELECT  btypeid ,
            stypeid ,
            type ,
            ptypeid ,
            ItemID ,
            Iscombined ,
            GoodsNumber ,
            dbo.F_roundQty(SUM(qty) )AS qty ,
            dbo.F_roundQty(SUM(nqty) )AS nqty ,
            Producedate,
            Validdate,
			'
	--不录入成本单价，将成本单价置为0
	IF @IsEnterCostPrice=1
	SET @SQL=@SQL+' costprice, '
	ELSE 
	SET @SQL=@SQL+' 0 AS costprice, '
	
	IF @serialRelation=1
	SET @SQL=@SQL+' SerialType,KTypeID,CargoID,DealType '
	ELSE 
	SET @SQL=@SQL+' 0 AS SerialType,10000 AS KTypeID,0 AS CargoID,0 AS DealType '
	SET @SQL = @SQL+' FROM #AddToDetails
					GROUP BY '
	IF	@IsEnterCostPrice=1
	SET @SQL = @SQL+' costprice, '
	
	IF @serialRelation=1
	SET @SQL = @SQL+' KTypeID ,SerialType,CargoID,DealType, '
	
	SET @SQL=@SQL+'	btypeid ,
					stypeid ,
					type ,
					ptypeid ,
					ItemID ,
					Iscombined ,
					GoodsNumber ,
					Producedate,
					Validdate '
    EXEC (@SQL)	  
    SET  @SQL='MERGE #ImportCommissionInitDetailsAdd ICID
	USING IniCommissionStock_Qty ICS 
	ON ICS.Type = ICID.type
		AND ICS.Ptypeid = ICID.ptypeid
		AND ICS.btypeid = ICID.btypeid
        AND ICS.stypeid = ICID.stypeid
        AND ICS.ItemID = ICID.ItemID
        AND ICS.Iscombined = ICID.Iscombined
        AND ICS.GoodsNumber = ICID.GoodsNumber
		AND ICS.Producedate=ICID.Producedate
        AND ICS.Validdate = ICID.Validdate '
        
	IF	@IsEnterCostPrice=1
	SET @SQL = @SQL+' AND ICS.GoodsCostPrice = ICID.costprice '
	
	IF @serialRelation=1
	SET @SQL = @SQL+' AND ICS.SerialType = ICID.SerialType
        AND ICS.KTypeID = ICID.KTypeID
        AND ICS.CargoID=ICID.CargoID '
        
	SET @SQL=@SQL+' WHEN MATCHED THEN UPDATE SET ICID.nqty=ICID.nqty+ICS.NQty,ICID.qty=ICID.qty+ICS.qty; '
    EXEC (@SQL)
    
    SET @SQL='DELETE  D
			FROM IniCommissionStock_Qty D
            INNER JOIN #ImportCommissionInitDetailsAdd S ON D.Type = S.type
                                                       AND D.Ptypeid = S.ptypeid
                                                       AND D.btypeid = S.btypeid
                                                       AND D.stypeid = S.stypeid
                                                       AND D.ItemID = S.ItemID
                                                       AND D.Iscombined = S.Iscombined
                                                       AND D.GoodsNumber = S.GoodsNumber
                                                       AND D.Producedate=S.Producedate
                                                       AND D.Validdate = S.Validdate '
	IF	@IsEnterCostPrice=1
	SET @SQL=@SQL+' AND D.GoodsCostPrice = S.costprice '
	IF @serialRelation=1
	SET @SQL=@SQL+' AND D.KTypeID = S.KTypeID
                    AND D.CargoID=S.CargoID 
                    AND D.SerialType=S.SerialType '
	EXEC (@SQL)
	
		 INSERT  INTO IniCommissionStock_Qty
            ( PTypeId ,
              Btypeid ,
              Stypeid ,
              Type ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              Qty ,
              NQty,
              Producedate,
              Validdate,
              SerialType,
              GoodsCostPrice,
			  KTypeID,
			  CargoID,
              DealType
            )
            SELECT  PTypeId ,
                    BTypeId ,
                    Stypeid ,
                    Type ,
                    itemId ,
                    isCombined ,
                    goodsNumber ,
                    qty ,
                    nQty,
                    Producedate,
					Validdate,
					SerialType,
					costprice,
					KTypeID,
					CargoID,
					DealType
            FROM    #ImportCommissionInitDetailsAdd;
            
------------------------------------------处理数量需要叠加数据结束-----------------------------------------------

------------------------------------------处理数量需要覆盖数据开始-----------------------------------------------
	SET @SQL='INSERT INTO #ImportCommissionInitTotal(btypeid,stypeid,type,ptypeid,costtotal,total,qty,explain,SerialType,DealType)
			SELECT  btypeid ,
            stypeid ,
            type ,
            ptypeid ,
            dbo.F_roundTotal(SUM(costprice * qty)) AS costtotal ,
            dbo.F_roundTotal(SUM(price * qty))AS total ,
            dbo.F_roundQty(SUM(qty)) AS qty,
            MAX(explain) AS explain, '
    IF @serialRelation=1
    SET @SQL=@SQL+' SerialType,DealType '
    ELSE 
    SET @SQL=@SQL+' 0 AS SerialType,0 AS DealType '
    
    SET @SQL=@SQL+' FROM #UpdateDetails
				GROUP BY btypeid ,
				stypeid ,
				type ,
				ptypeid '
    
    IF @serialRelation=1
    SET @SQL=@SQL+' ,SerialType,DealType '
	EXEC (@SQL)
	
	SET @SQL=' DELETE  T 
			FROM IniCommissionStock T 
            INNER JOIN #ImportCommissionInitTotal S ON T.Type = S.type
                                                       AND T.Ptypeid = S.ptypeid
                                                       AND T.btypeid = S.btypeid
                                                       AND T.stypeid = S.stypeid '
    
    IF @serialRelation=1
    SET @SQL=@SQL+' AND T.SerialType=S.SerialType '
	EXEC (@SQL)
		
    INSERT  INTO IniCommissionStock
            ( btypeid ,
              ptypeid ,
              ktypeid ,
              etypeid ,
              stypeid ,
              type ,
              qty ,
              CostTotal ,
              Total ,
              SerialType,
              explain ,
              DealType
            )
            SELECT  btypeid ,
                    ptypeid ,
                    '10000' ,
                    '' ,
                    stypeid ,
                    type ,
                    qty ,
                    CostTotal ,
                    Total ,
                    SerialType,
                    explain,
                    DealType
            FROM    #ImportCommissionInitTotal
		
	SET @SQL='INSERT  INTO #ImportCommissionInitDetails(btypeid,stypeid,type,ptypeid,ItemID,Iscombined,
	GoodsNumber,qty,nqty,Producedate,Validdate,costprice,SerialType,KTypeID,CargoID,DealType)
    SELECT  btypeid ,
            stypeid ,
            type ,
            ptypeid ,
            ItemID ,
            Iscombined ,
            GoodsNumber ,
            dbo.F_roundQty(SUM(qty)) AS qty ,
            dbo.F_roundQty(SUM(nqty)) AS nqty ,
            Producedate,
            Validdate,'
    IF	@IsEnterCostPrice=1
	SET @SQL=@SQL+' costprice, '
	ELSE 
	SET @SQL=@SQL+' 0 AS costprice,'
	
    IF @serialRelation=1
    SET @SQL=@SQL+' SerialType,KTypeID,CargoID,DealType '
    ELSE 
    SET @SQL=@SQL+' 0 AS SerialType,10000 AS KTypeID, 0 AS CargoID,0 AS DealType '
    
    SET @SQL=@SQL+' FROM #UpdateDetails GROUP BY '
	IF	@IsEnterCostPrice=1
	SET @SQL=@SQL+' costprice, '
	
    IF @serialRelation=1
    SET @SQL=@SQL+' SerialType,KTypeID,CargoID,DealType, '
    
    SET @SQL=@SQL+' btypeid ,
            stypeid ,
            type ,
            ptypeid ,
            ItemID ,
            Iscombined ,
            GoodsNumber ,
            Producedate,
            Validdate '
	EXEC (@SQL)
    
    SET @SQL='DELETE  D
    FROM    IniCommissionStock_Qty D
            INNER JOIN #ImportCommissionInitDetails S ON D.Type = S.type
                                                       AND D.Ptypeid = S.ptypeid
                                                       AND D.btypeid = S.btypeid
                                                       AND D.stypeid = S.stypeid
                                                       AND D.ItemID = S.ItemID
                                                       AND D.Iscombined = S.Iscombined
                                                       AND D.GoodsNumber = S.GoodsNumber
                                                       AND D.Producedate=S.Producedate
                                                       AND D.Validdate = S.Validdate '
	IF	@IsEnterCostPrice=1
	SET @SQL=@SQL+' AND D.GoodsCostPrice = S.costprice '
	
    IF @serialRelation=1
    SET @SQL=@SQL+' AND D.KTypeID = S.KTypeID
                    AND D.CargoID = S.CargoID
                    AND D.SerialType=S.SerialType 
                    '
	EXEC (@SQL)
	
		 INSERT  INTO IniCommissionStock_Qty
            ( PTypeId ,
              Btypeid ,
              Stypeid ,
              Type ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              Qty ,
              NQty,
              Producedate,
              Validdate,
              SerialType,
              GoodsCostPrice,
			  KTypeID,
			  CargoID,
              DealType
            )
            SELECT  PTypeId ,
                    BTypeId ,
                    Stypeid ,
                    Type ,
                    itemId ,
                    isCombined ,
                    goodsNumber ,
                    qty ,
                    nQty,
                    Producedate,
					Validdate,
					SerialType,
					costprice,
					KTypeID,
					CargoID,
					DealType
            FROM    #ImportCommissionInitDetails;
------------------------------------------处理数量需要覆盖数据结束-----------------------------------------------

------------------------------------------处理序列号数据开始-----------------------------------------------
            
			SELECT 
				Serial,
				btypeid ,
				stypeid ,
				ptypeid ,
				ktypeid ,
				cargoid ,
				itemId ,
				costprice,
				Iscombined ,
				goodsNumber ,
				SerialType,
				Producedate,
				Validdate,
				SerialType	AS State
			INTO #ImportInitSerialDetails
			FROM @SerialDetails 
            
            IF @Type=140
            BEGIN
				DECLARE
					@Serial VARCHAR(50) ,
					@ItemID VARCHAR(50) ,
					@ProduceDate VARCHAR(50) ,
					@ValidDate VARCHAR(50) ,
					@CostPrice  NUMERIC(24, 10) ,
					@GoodsNumber VARCHAR(100) ,
					@PtypeID VARCHAR(50) ,
					@BTypeId VARCHAR(50) , 	
					@STypeId VARCHAR(50) ,
					@State INT
			
				WHILE EXISTS(SELECT Serial FROM #ImportInitSerialDetails WHERE State=32)
				BEGIN

					SELECT TOP 1 @Serial=Serial,@ItemID=itemId,@ProduceDate=Producedate,@ValidDate=Validdate,@CostPrice=costprice,
					@GoodsNumber=goodsNumber,@PtypeID=ptypeid,@BTypeId=btypeid,@STypeId=stypeid,@State=[State]
					FROM #ImportInitSerialDetails
					WHERE State=32
					
					UPDATE gp_initPtypeSerial
					SET BTypeID1=@BTypeId 
					WHERE PtypeID=@PtypeID AND STypeId=@STypeId AND [State]=32 AND (BTypeID1='' OR BTypeID1 IS NULL) AND [ItemID]=@ItemID 
					AND ProduceDate=@ProduceDate AND ValidDate=@ValidDate  AND GoodsNumber=@GoodsNumber AND Serial=@Serial
					DELETE FROM #ImportInitSerialDetails WHERE serial=@Serial
				END

				INSERT  INTO gp_initPtypeSerial
				( 
					Serial ,
					KtypeID ,
					PtypeID ,
					BtypeID1 ,
					State ,
					CostPrice ,
					GoodsNumber ,
					STypeId ,
					ItemID,
					isCombined,
					CargoID,
					ProduceDate,
					ValidDate,
					Flag
				)
				SELECT  
					Serial ,
					ktypeid ,
					ptypeid ,
					btypeid ,
					State ,
					costprice ,
					goodsNumber ,
					stypeid ,
					itemId,
					isCombined,
					cargoid,
					Producedate,
					Validdate,
					0
				FROM #ImportInitSerialDetails
			END
			ELSE
				INSERT  INTO gp_initPtypeSerial
				( 
					Serial ,
					KtypeID ,
					PtypeID ,
					BtypeID2 ,
					State ,
					CostPrice ,
					GoodsNumber ,
					STypeId ,
					ItemID,
					isCombined,
					CargoID,
					ProduceDate,
					ValidDate,
					Flag
				)
				SELECT  
					Serial ,
					ktypeid ,
					ptypeid ,
					btypeid ,
					State ,
					costprice ,
					goodsNumber ,
					stypeid ,
					itemId,
					isCombined,
					cargoid,
					Producedate,
					Validdate,
					CASE WHEN State IN(1,7,25) THEN 1
					ELSE 0 END
				FROM #ImportInitSerialDetails
				
------------------------------------------处理序列号数据结束-----------------------------------------------
DROP TABLE #ImportCommissionInitDetailsAdd
DROP TABLE #ImportCommissionInitTotalAdd
DROP TABLE #ImportCommissionInitDetails
DROP TABLE #ImportCommissionInitTotal
DROP TABLE #ImportInitSerialDetails
DROP TABLE #AddToDetails
DROP TABLE #UpdateDetails
		

    SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ImportInitWxStock]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ImportInitWxStock]
GO

/****** Object:  StoredProcedure [dbo].[GP_ImportInitWxStock]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：Haiyang, Li
	日    期：2012-08-17
	描	  述：导入维修品期初
	
	2015-04-27 SiHuaShan 新增维修品序列号导入     
*/


CREATE PROCEDURE [dbo].[GP_ImportInitWxStock]
    (
      @Details TBType_ImportInitWxStock READONLY,
      @ETypeId  VARCHAR(50)=''
    )
--@encode$--
AS 
    SET NOCOUNT ON

    SELECT  ptypeid ,
            ktypeid ,
            SUM(qty) AS qty ,
            SUM(nqty) AS nqty ,
            goodsNumber ,
            itemId ,
            isCombined,
            producedate,
		    validdate,
		    Serial,
		    ROW_NUMBER() OVER(ORDER BY KTypeId) AS RowIndex
    INTO    #ImportWxStockDetails
    FROM    @Details
    GROUP BY ktypeid ,
            ptypeid ,
            goodsNumber ,
            itemId ,
            isCombined ,
            producedate,
            validdate,
            Serial
    DELETE  T
    FROM    wx_IniGoodsStocks T
            INNER JOIN #ImportWxStockDetails S ON T.ptypeid = S.ptypeid
                                                  AND T.ktypeid = S.ktypeid
		
    INSERT  INTO wx_IniGoodsStocks
            ( PTypeId ,
              KTypeId ,
              JobNumber ,
              OutFactoryDate ,
              GoodsOrder ,
              Qty ,
              Nqty ,
              GoodsNumber ,
              ItemID ,
              Iscombined,
              ProduceDate,
              ValidDate
            )
            SELECT  ptypeid ,
                    ktypeid ,
                    '' ,
                    GETDATE() ,
                    0 ,
                    SUM(qty) ,
                    SUM(nQty) ,
                    goodsNumber ,
                    itemId ,
                    isCombined,
                    '',
					''
            FROM    #ImportWxStockDetails
		    GROUP BY PTYpeID,KTypeId,GoodsNumber,ItemID,Iscombined,ProduceDate,ValidDate
	
----------------序列号开始----------------
			
    --删除原序列号
    DELETE A  FROM gp_initPtypeSerial A INNER JOIN @Details B ON  A.PTypeID=B.PTypeID 
														      AND A.KTypeID=B.KTypeID 
    WHERE A.[State]=25

	DECLARE @RowCount INT,
			@RowIndex INT,
			@PTypeId VARCHAR(50),
			@KTypeId VARCHAR(50),
			@StypeId VARCHAR(50),
			@Serial	 VARCHAR(MAX),
			@GoodsNumber VARCHAR(100),
			@ItemId  VARCHAR(100),
			@Iscombined INT
	
	SELECT @RowCount=COUNT(1) FROM #ImportWxStockDetails;
	IF @RowCount=0  
	BEGIN
		DROP TABLE #ImportWxStockDetails;
		RETURN;
	END
	SET @RowIndex=1;

	WHILE(@RowIndex<=@RowCount)
	BEGIN
		SELECT  @Serial=A.serial,
				@PTypeId=A.PTypeID,
				@KTypeId=A.KTypeID,
				@StypeId=B.STypeID,
				@GoodsNumber=A.GoodsNumber,
				@ItemId=A.ItemId,
				@Iscombined=A.Iscombined
		FROM #ImportWxStockDetails A INNER JOIN Stock B ON A.ktypeid=B.typeId AND A.RowIndex=@RowIndex;
        
		--插入新序列号
		INSERT INTO  gp_initPtypeSerial
						([Serial],
						 [KtypeID],
						 [PtypeID],
						 [state],
						 [Flag],
						 [CommissionState],
						 [ETypeID],
						 iniFlag,
						 STypeId,
						 GoodsNumber,
						 ItemID,
						 Iscombined
						)
		SELECT Serial,
			   @KTypeId,
			   @PTypeId,
			   25,
			   1,
			   '',
			   @ETypeId,
			   1,
			   @StypeId,
			   @GoodsNumber,
			   @ItemId,
			   @Iscombined FROM F_SplitSerial(REPLACE(@Serial,'，',','),',') WHERE Serial<>'';
			   
		SET @RowIndex+=1;
	END
	
    DROP TABLE #ImportWxStockDetails
    SET NOCOUNT OFF
    
    ----------------序列号结束----------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_ImportItemATypeData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[GP_ImportItemATypeData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	项目对应科目导入模板
-- 时间：	2019-05-20
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [GP_ImportItemATypeData]
(
	@UserCode			VARCHAR(200)='',--编号
	@FullName			VARCHAR(200)='',--描名称
	
	@StypeUserCode		VARCHAR(200)='',--分支机构 编号
	@StypeFullName		VARCHAR(200)='',--分支机构 名称
	
	@AtypeUserCode		VARCHAR(200)='',--会计科目 编号
	@AtypeFullName		VARCHAR(200)='',--会计科目 名称

	@ErrMsg				VARCHAR(1000) OUTPUT
)
AS
SET NOCOUNT ON

DECLARE
	@NId		INT=0,
	@STypeId	VARCHAR(50)='',--分支机构ID
	@ATypeId	VARCHAR(50)='',--会计科目ID
	@ErrorCount INT=0,--错误标志
	@XiWaMaxNumber INT=0--缓存最大值

SET @UserCode=ltrim(rtrim(@UserCode))
SET @FullName=ltrim(rtrim(@FullName))
SET @StypeUserCode=ltrim(rtrim(@StypeUserCode))
SET @StypeFullName=ltrim(rtrim(@StypeFullName))
SET @AtypeUserCode=ltrim(rtrim(@AtypeUserCode))
SET @AtypeFullName=ltrim(rtrim(@AtypeFullName))

--=============================================基本信息验证【BEGIN】==================================
--项目验证
IF ISNULL(@UserCode,'')=''
	BEGIN
		SET @ErrMsg='项目编号不能为空'
		RETURN -1
	END
	
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode=@UserCode)
	BEGIN
		SET @ErrMsg='项目编号不存在'
		RETURN -1
	END

IF ISNULL(@FullName,'')<>'' AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode=@UserCode AND FullName=@FullName)
	BEGIN
		SET @ErrMsg='项目编号和名称不匹配'
		RETURN -1
	END
	
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode=@UserCode AND SonNum=0)
	BEGIN
		SET @ErrMsg='不能导入为父级的项目'
		RETURN -1
	END
		
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode=@UserCode AND Deleted=0)
	BEGIN
		SET @ErrMsg='项目信息已经停用'
		RETURN -1
	END
	
SELECT @NId=nId FROM Ac_Items WHERE UserCode=@UserCode--项目

IF EXISTS(SELECT TOP 1 * FROM SysData WHERE SubName='ProInfo' AND SubValue=2)
	BEGIN
		--分支机构验证
		IF ISNULL(@StypeUserCode,'')=''
			BEGIN
				SET @ErrMsg='分支机构编号不能为空'
				RETURN -1
			END
		IF NOT EXISTS(SELECT TOP 1 1 FROM stype WHERE UserCode=@StypeUserCode)
			BEGIN
				SET @ErrMsg='分支机构编号不存在'
				RETURN -1
			END

		IF ISNULL(@StypeFullName,'')<>'' AND NOT EXISTS(SELECT TOP 1 1 FROM stype WHERE UserCode=@StypeUserCode AND FullName=@StypeFullName)
			BEGIN
				SET @ErrMsg='分支机构编号和名称不匹配'
				RETURN -1
			END
			
		IF NOT EXISTS(SELECT TOP 1 1 FROM stype WHERE UserCode=@StypeUserCode AND SonNum=0)
			BEGIN
				SET @ErrMsg='不能导入为父级的分支机构'
				RETURN -1
			END
			
		IF NOT EXISTS(SELECT TOP 1 1 FROM stype WHERE UserCode=@StypeUserCode AND deleted=0)
			BEGIN
				SET @ErrMsg='分支机构信息已经停用'
				RETURN -1
			END
			
		SELECT @STypeId=TypeId FROM SType WHERE UserCode=@StypeUserCode
	END
ELSE 
	SET @STypeId='00001'
	
--科目验证
IF ISNULL(@AtypeUserCode,'')=''
	BEGIN
		SET @ErrMsg='科目编号不能为空'
		RETURN -1
	END
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND UserCode=@AtypeUserCode)
	BEGIN
		SET @ErrMsg='科目编号不存在'
		RETURN -1
	END

IF ISNULL(@AtypeFullName,'')<>'' AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND UserCode=@AtypeUserCode AND FullName=@AtypeFullName)
	BEGIN
		SET @ErrMsg='科目编号和名称不匹配'
		RETURN -1
	END
			
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND UserCode=@AtypeUserCode AND SonNum=0)
	BEGIN
		SET @ErrMsg='不能导入为父级的科目'
		RETURN -1
	END	
	
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND UserCode=@AtypeUserCode AND Deleted=0)
	BEGIN
		SET @ErrMsg='科目信息已经停用'
		RETURN -1
	END
	
SELECT @ATypeId=TypeId FROM Ac_Account WHERE StypeId=@STypeId AND UserCode=@AtypeUserCode--会计科目

--=============================================基本信息验证【END】==================================


SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items_Detail

BEGIN TRAN InsertItemsDetail

--删除原数据
DELETE FROM Ac_Items_Detail WHERE nId=@NId AND STypeId=@STypeId
SELECT @ErrorCount+=@@ERROR

--重新插入数据
INSERT INTO Ac_Items_Detail
(
	nId,
	STypeId,
	ATypeId,
	DepATypeId,
	DisATypeId,
	XiWaMaxNumber
)
VALUES
(
	@NId,
	@STypeId,
	@ATypeId,
	'',
	'',
	@XiWaMaxNumber
)
SELECT @ErrorCount+=@@ERROR

--修改主表最大缓存值ID
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items

UPDATE Ac_Items SET XiWaMaxNumber=@XiWaMaxNumber WHERE nId=@NId
SELECT @ErrorCount+=@@ERROR


IF(@ErrorCount<>0)
	BEGIN
		ROLLBACK TRAN InsertItemsDetail
		SET @ErrMsg='导入失败'
		RETURN -1	
	END
ELSE 
	BEGIN
		COMMIT TRAN InsertItemsDetail
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_ImportItemData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[GP_ImportItemData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	项目导入
-- 时间：	2019-05-17
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [GP_ImportItemData]
(
	@ParUserCode		VARCHAR(200)='',--父级 编号
	@ParFullName		VARCHAR(200)='',--父级 名称
	@UserCode			VARCHAR(200)='',--编号
	@FullName			VARCHAR(200)='',--描名称
	@Name				VARCHAR(200)='',--简名
	@PyCode				VARCHAR(200)='',--拼音码
	@CreateBank         varchar(400)='',--开户行
	@BankType           varchar(400)='',--银行类型
	@Comment			VARCHAR(1000)='',--备注		
	@ErrMsg				VARCHAR(1000) OUTPUT
)
AS
SET NOCOUNT ON


DECLARE
	@PNId			INT=0,
	@ParId			VARCHAR(50)='',--父级ID
	@PFullName		VARCHAR(200)='',--父级名称
	@ParLevel		INT=0,--父级级别
	@ParSysRow		INT=0,--是否为系统项目
	@ParIsModify	INT=0,--是否允许分类
	@ParTypeName	VARCHAR(50)='',--父级类别
	@ParIsUse		INT=0,--父级是否被使用
	@ParDeleted		INT=0,--父级是否停用
	
	@newTypeid	VARCHAR(50),--新增节点表中TypeID
	@nTypeid	VARCHAR(50),--已经存在的项目ID 
	@nReturntype INT,
	@IsBank		INT=0,--是否是银行
	@XiWaMaxNumber INT=0,--缓存最大值
	@nSonNum	INT,		
	@nSonCount	INT,
	@NIDS		INT=0,--项目ID
	@ErrorCount INT=0--错误标志
	

SET @ParUserCode=ltrim(rtrim(@ParUserCode))
SET @ParFullName=ltrim(rtrim(@ParFullName))
SET @UserCode=ltrim(rtrim(@UserCode))
SET @FullName=ltrim(rtrim(@FullName))
--=============================================基本信息验证【BEGIN】==================================
--父级项目验证
IF ISNULL(@ParUserCode,'')=''
	BEGIN
		SET @ErrMsg='父类项目编号不能为空'
		RETURN -1
	END
	
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode=@ParUserCode)
	BEGIN
		SET @ErrMsg='父类项目编号不存在'
		RETURN -1
	END

IF ISNULL(@ParFullName,'')<>'' AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode=@ParUserCode AND FullName=@ParFullName)
	BEGIN
		SET @ErrMsg='父类项目编号和名称不匹配'
		RETURN -1
	END


--项目编号
IF ISNULL(@UserCode,'')=''
	BEGIN
		SET @ErrMsg='项目编号不能为空'
		RETURN -1
	END

IF ISNULL(@FullName,'')=''
	BEGIN
		SET @ErrMsg='项目名称不能为空'
		RETURN -1
	END

IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode=@UserCode)--编号不允许重复
	BEGIN
		SET @ErrMsg='已存在该编号'
		RETURN -1
	END		
IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE FullName=@FullName)--名称不允许重复
	BEGIN
		SET @ErrMsg='已存在该名称'
		RETURN -1
	END
	
--父级信息
SELECT 
	@PNId=NID,
	@ParId=nTypeId,
	@ParSysRow=Sysrow,
	@ParIsModify=IsModify,
	@ParLevel=Leveal,
	@ParTypeName=TypeName ,
	@ParDeleted=Deleted
FROM Ac_Items WHERE UserCode=@ParUserCode

--得到当前新增数据TypeID
EXEC @nReturntype= Gp_CreateId_AcItem @ParID, 'Ac_Items', @newTypeid OUT,@nSonNum OUT, @nSonCount OUT
IF @nReturntype = -1
	BEGIN
		SET @ErrMsg='父级项目子级不能超过10层'
		RETURN -1
	END
ELSE IF @nReturntype = -2
	BEGIN
		SET @ErrMsg='无法添加'
		RETURN -1	
	END

--是否为系统项目
IF (@ParSysRow=1 AND @ParIsModify=0)
	BEGIN
		SET @ErrMsg='该父类项目为系统项目，不允许添加子级'
		RETURN -1
	END
	
--该父类项目已经正常使用
IF @ParDeleted=1
	BEGIN
		SET @ErrMsg='该父类项目已经停用，不允许添加子级'
		RETURN -1
	END
		
--判断父级是否使用
IF (SELECT dbo.Fn_GetIsUse_Items(@PNId,2))>0
	BEGIN
		SET @ErrMsg='该父级信息已经使用，不允许添加子级'
		RETURN -1
	END	
	
IF EXISTS(SELECT TOP 1 1 FROM PosInfo WHERE (BankCardID =@PNId OR CashID=@PNId OR alipayid=@PNId OR wxpayid=@PNId OR allinpayid=@PNId  OR JFPayId=@PNId))
	BEGIN
		SET @ErrMsg='该信息已关联POS，不允许添加子级'
		RETURN -1
	END	
--=============================================基本信息验证【END】==================================

IF(@ParTypeName='B' AND @ParID NOT LIKE '0000100003%') 
	SET @IsBank=1
		
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items

BEGIN TRAN InsertItems

--新增
UPDATE Ac_Items SET SonNum+=1,SonCount+=1,XiWaMaxNumber=@XiWaMaxNumber WHERE nTypeId=@ParId
SET @ErrorCount+=@@ERROR

INSERT INTO Ac_Items
(
	[nTypeId],
	[nParId],
	[UserCode],
	[FullName],
	[Comment],
	[PyCode],
	[CreateBank],
	[BankType],
	[IsBank],
	[Deleted],
	[TypeName],
	[Sysrow],
	IsModify,
	[TypeId],
	[ParId],
	[Leveal],
	[SonNum],
	[SonCount],
	[Name],
	[XiWaMaxNumber]
)
VALUES
(
	@newTypeid,
	@ParID,
	@UserCode,
	@FullName,
	@Comment,
	@PyCode,
	@CreateBank,
	@BankType,
	@IsBank,
	0,
	@ParTypeName,
	0,
	1,
	'',
	'',
	@ParLevel+1,
	0,
	0,
	@Name,
	@XiWaMaxNumber+1
	)
SET @NIDS=SCOPE_IDENTITY();
SET @ErrorCount+=@@ERROR	

--插入项目对应科目明细
INSERT INTO Ac_Items_Detail(nId,STypeId,ATypeId,DepATypeId,DisATypeId)
SELECT @NIDS,TypeId,'','','' FROM SType WHERE sonnum=0

--修改 项目对应科目明细最大缓存值
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items_Detail
UPDATE Ac_Items_Detail SET XiWaMaxNumber=@XiWaMaxNumber,@XiWaMaxNumber+=1 WHERE nId=@NIDS
SET @ErrorCount+=@@ERROR


IF(@ErrorCount<>0)
	BEGIN
		ROLLBACK TRAN InsertItems
		SET @ErrMsg='导入失败'
		RETURN -1	
	END
ELSE 
	BEGIN
		COMMIT TRAN InsertItems
	END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013-05-16
	描述：导入项目对应科目
*/
CREATE PROCEDURE GP_ImportItemDetails
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@STypeId			VARCHAR(50),
	@SubId				INT
)
--@encode$--
AS
SET NOCOUNT ON


CREATE TABLE #ErrorMsg
(
	msg VARCHAR(MAX)
)


DECLARE @ItemUserCode VARCHAR(200),@ItemFullName VARCHAR(200),@ATypeUserCode VARCHAR(200),@ATypeFullName VARCHAR(200),@VerifyStypeid VARCHAR(50)

DECLARE @NID INT,@ATypeid	VARCHAR(50)

		
		
DECLARE BillCur CURSOR READ_ONLY FOR 
		SELECT	UserCode,FullName,
		CASE WHEN ATypeUserCode<>'' 
		 THEN  dbo.F_GetNewUserCode(ATypeUserCode,dbo.F_GetDefaultLeveal(ATypeUserCode)) 
		 ELSE ATypeUserCode 
		 END ATypeUserCode	,
		ATypeFullName
		FROM dbo.ItemATypeIdPreset
		WHERE SubId = @SubId AND ATypeUserCode <> ''

OPEN BillCur

FETCH NEXT FROM BillCur INTO @ItemUserCode,
							@ItemFullName	,	
							@ATypeUserCode	,	
							@ATypeFullName	
										
WHILE (@@FETCH_STATUS = 0)
BEGIN
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId = @STypeId)
	BEGIN
		INSERT INTO #ErrorMsg
		SELECT '分支机构不存在'
		GOTO Again
	END
	
	SELECT @VerifyStypeid = VerifyID FROM dbo.SType WHERE TypeId = @STypeId--获取核算分支的id
	
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE UserCode = @ItemUserCode AND FullName = @ItemFullName)
	BEGIN
		INSERT INTO #ErrorMsg
		SELECT '【'+@ItemFullName+'】不存在'
		GOTO Again
	END
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account WHERE UserCode = @ATypeUserCode AND FullName = @ATypeFullName AND StypeId = @VerifyStypeid)
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM #ErrorMsg WHERE msg='【' + @ATypeFullName + '】不存在')
		BEGIN		
			INSERT INTO #ErrorMsg
			SELECT '【' + @ATypeFullName + '】不存在'
		END
		GOTO Again
	END
	
	SELECT @NID = nid FROM dbo.Ac_Items WHERE UserCode = @ItemUserCode AND FullName = @ItemFullName
	SET @ATypeid = ''
	SELECT @ATypeid = typeid FROM dbo.Ac_Account WHERE UserCode = @ATypeUserCode AND FullName = @ATypeFullName AND StypeId = @VerifyStypeid
	
	
	IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @VerifyStypeid AND TypeId = @atypeid AND SonNum > 0)
	BEGIN
		INSERT INTO #ErrorMsg
		SELECT '科目【'+ @ATypeFullName + '】不是子科目，无法使用'
		GOTO Again
	END
	
	
	IF ISNULL(@ATypeid,'') <> ''
	UPDATE dbo.Ac_Items_Detail SET ATypeId = @ATypeid WHERE nId = @NID AND STypeId = @STypeId
	
	
	Again:
	FETCH NEXT FROM BillCur INTO @ItemUserCode,
							@ItemFullName	,	
							@ATypeUserCode	,	
							@ATypeFullName	
END

CLOSE BillCur
DEALLOCATE BillCur

SELECT * FROM #ErrorMsg

DROP TABLE #ErrorMsg 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.11.26
	描述：从其他分支机构导入项目
*/
CREATE PROCEDURE GP_ImportItemtype
(
	@desstypeid	VARCHAR(50),	--目标分支机构
	@stypeid	VARCHAR(50),	--来源分支机构
	@item		INT				--1是同时导入项目
)
--@encode$--
AS
SET NOCOUNT ON



--校验项目信息是否存在
IF @item = 1
BEGIN
	DECLARE @ItemCount INT, --选中项目类别下的项目数
		@ItemCountDes	INT --目标分支机构项目数

	SELECT c.nId
	INTO #TempSrcItem
	FROM dbo.ItemType a
		INNER JOIN dbo.ItemType_Item b ON a.nId = b.itemTypeId
		INNER JOIN dbo.Ac_Items c ON b.itemId = c.nId
		INNER JOIN dbo.Ac_Items_Detail d ON c.nId = d.nId AND d.STypeId = @stypeid
	WHERE a.STypeid = @stypeid

	SELECT b.nId
	INTO #TempDesItem
	FROM dbo.Ac_Items a
		INNER JOIN dbo.Ac_Items_Detail b ON a.nId = b.nId AND b.STypeId = @desstypeid

	SELECT @ItemCount = COUNT(*) FROM #TempSrcItem
	SELECT @ItemCountDes = COUNT(*) FROM #TempDesItem  WHERE nid IN (SELECT a.nId FROM #TempSrcItem a INNER JOIN #TempDesItem T ON a.nId = t.nId)

	DROP TABLE #TempSrcItem,#TempDesItem
	
		
	IF @ItemCount <> @ItemCountDes
	BEGIN
		RAISERROR('当前分支机构项目信息不匹配，不能导入！',16,1)
		RETURN -1
	END
END

BEGIN TRAN imoprtTran

--清除目标分支机构原有分类信息
DELETE FROM dbo.ItemType_Item WHERE itemTypeId IN(SELECT nid FROM dbo.ItemType WHERE STypeid = @desstypeid AND Attribute = 2)
DELETE FROM dbo.ItemType WHERE STypeid = @desstypeid

IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN imoprtTran
	RAISERROR('导入失败！',16,1)
	RETURN -1
END



CREATE TABLE #TempID
(
	nid		INT,
	typeid	VARCHAR(50)
)


--导入
INSERT INTO dbo.ItemType
        ( typeId ,
          ParId ,
          leveal ,
          sonnum ,
          soncount ,
          CanModify ,
          UserCode ,
          FullName ,
          Name ,
          Attribute ,
          Comment ,
          STypeid ,
          deleted ,
          PyCode ,
          XiWaMaxNumber
        )
OUTPUT INSERTED.nid,INSERTED.typeId INTO #TempID
SELECT typeId,ParId,leveal,sonnum,soncount,CanModify,UserCode,FullName,Name,Attribute,Comment,@desstypeid,deleted,PyCode,XiWaMaxNumber 
FROM dbo.ItemType
WHERE STypeid = @stypeid

IF @item = 1 --导入项目
BEGIN
	INSERT INTO dbo.ItemType_Item( itemTypeId, itemId )
	SELECT b.nid,c.itemId
	FROM dbo.ItemType a
		INNER JOIN #TempID b ON a.typeId = b.typeid
		INNER JOIN dbo.ItemType_Item c ON a.nId = c.itemTypeId
	WHERE a.STypeid = @stypeid
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN imoprtTran
		RAISERROR('导入失败！',16,1)
		RETURN -1
	END
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemType WHERE STypeid = @desstypeid AND typeId = '00000')
BEGIN
	INSERT INTO dbo.ItemType
        ( typeId ,
          ParId ,
          leveal ,
          sonnum ,
          soncount ,
          CanModify ,
          UserCode ,
          FullName ,
          Name ,
          Attribute ,
          Comment ,
          STypeid ,
          deleted ,
          PyCode ,
          XiWaMaxNumber
        )
	SELECT typeId,ParId,leveal,sonnum,soncount,CanModify,UserCode,FullName,Name,Attribute,Comment,@desstypeid,deleted,PyCode,XiWaMaxNumber 
	FROM dbo.ItemType
	WHERE STypeid = @stypeid AND typeId = '00000'
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN imoprtTran
		RAISERROR('导入失败！',16,1)
		RETURN -1
	END
END


COMMIT TRAN imoprtTran

DROP TABLE #TempID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

GO

/****** Object:  StoredProcedure [dbo].[gp_ImportK]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	修 改 者：廖晨羽
	日    期：2011-08-23
	修改原因：导入仓库信息
	修改位置：转换输入参数
*/



CREATE         PROCEDURE [dbo].[gp_ImportK]
(
	@KFullName   [varchar](66),
	@UserCode  [varchar](26),
	@FullName  [varchar](66),
	@Name [varchar](30),
	@PyCode varchar(201),
	@SFullName VARCHAR(100),
	@LinkMan varchar(20),
	@Tel varchar(50),
	@Address varchar(50),
	@Comment  [varchar](257),
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

IF ((SELECT DATALENGTH(@PyCode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 256)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度256'
	RETURN -1
END

DECLARE @Parid   [varchar](50)
IF (@KFullName = '' OR  @KFullName = '全部仓库')
BEGIN
	SET @Parid = '00000'
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.Stock WHERE fullname = @KfullName)
	BEGIN
		SET @ErrMsg = '父类名称不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		SET @Parid = (SELECT TOP 1 typeid FROM stock WHERE fullname = @KfullName)
	END
END

DECLARE @DbName  [varchar](30) = 'stock'

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '仓库编号不能为空'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '仓库全名不能为空'
	RETURN -1
END

IF(@Pycode = '')
BEGIN
	SELECT @Pycode = dbo.fun_getPY(@FullName)
END

DECLARE @STypeID varchar(50)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF (@SfullName = '')
	BEGIN
		SET @ErrMsg = '分支机构不能为空'
		RETURN -1
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 typeid FROM stype WHERE fullname = @SfullName) OR @SfullName = '总部'
			BEGIN
				SET @ErrMsg = '该分支机构不存在'
				RETURN -1
			END
		ELSE	
			BEGIN
				DECLARE @PStypeId VARCHAR(50)
				DECLARE @SChildCount NUMERIC(18,0)
				SET @PStypeId = (SELECT TOP 1 typeid FROM stype WHERE fullname = @SfullName)
				SELECT @SChildCount = COUNT(*) FROM dbo.stype WHERE typeid LIKE @PStypeId + '%' AND typeid <> @PStypeId
				IF (@SChildCount = 0)
					BEGIN
						SET @STypeID = @PStypeId
					END
				ELSE
					BEGIN
						SET @ErrMsg = '该分支机构为父类'
						RETURN -1
					END
				IF((SELECT TOP 1 STypeID FROM dbo.Stock WHERE fullname = @KfullName) <> @STypeID)
				BEGIN
					SET @ErrMsg = '该分支机构必须与父类分支机构一样'
					RETURN -1
				END	
			END
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

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

declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from stock where typeid=@parid)
--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(select subvalue from sysdata where subname='ifqp')
if(@ParId<>'00000')
begin
--判断停用不能分类
declare @deleted INT
select @deleted=deleted from stock where typeId=@Parid
if(@deleted=1)
BEGIN
   SET @ErrMsg = '该仓库【' + @parFullName + '】已经被停用，不能分类'
   RETURN -1
   --RAISERROR('该仓库【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
end
-- 判断维修库存中期初是否为零
if exists(select ktypeid from Wx_iniGoodsstocks where ktypeid=@parid and Qty<>0)
	BEGIN
		SET @ErrMsg = '该仓库【'+ @parFullName +'】维修品库存期初余量不为零，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】维修品库存期初余量不为零，不能分类',16,1,@parFullName)return--return -4
	end 
-- 判断库存量（每种商品）是否为零
if exists(select ktypeid from goodsstocks where ktypeid=@parid and Qty<>0)
	begin
		--print '['+@FullName+']仓库库存余量不为零，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】库存余量不为零，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】库存余量不为零，不能分类',16,1,@parFullName)return--return -4
	end 
if exists(select ktypeid from inigoodsstocks where ktypeid=@parid and Qty<>0)
	begin
		--print '['+@FullName+']仓库库存余量不为零，不能分类'
		SET @ErrMsg = '该仓库【' + @parFullName + '】库存余量不为零，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】库存余量不为零，不能分类',16,1,@parFullName)return--return -4
	end 

--pos模块
if exists(select KTypeID from CommonPosSaleIndex  where ktypeid=@parid)
OR exists(select KTypeID from CommonPosPtypeCheckNdx  where ktypeid=@parid)
OR exists(select KTypeID from CX_SaleStocksArea  where ktypeid=@parid)
OR exists(select stockid from CommonPosInfo  where stockid=@parid)
	begin
		 --print '2555'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
	end

if exists(select ktypeid from wx_goodsstocks where ktypeid=@parid and Qty<>0)
	begin
		--print '['+@FullName+']仓库库存余量不为零，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】库存余量不为零，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】库存余量不为零，不能分类',16,1,@parFullName)return--return -4
	end 
if exists(select ktypeid from wx_inigoodsstocks where ktypeid=@parid and Qty<>0)
	begin
		--print '['+@FullName+']仓库库存余量不为零，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】库存余量不为零，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】库存余量不为零，不能分类',16,1,@parFullName)return--return -4
	end 
if exists(select ktypeid from inigoodsstocks where ktypeid=@parid and Total<>0)
	begin
		--print '['+@FullName+']仓库库存成本不为零，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】有库存期初，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】有库存期初，不能分类',16,1,@parFullName)return--return -34
	end 
--判断序列号
if exists(select KTypeID from gp_CruPtypeSerial where KTypeID=@Parid)
	begin
		--print '此仓库有序列号，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】有序列号关联情况，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】有序列号关联情况，不能分类',16,1,@parFullName)return--return -15
	end
if exists(select KTypeID from gp_initPtypeSerial where KTypeID=@Parid)
	begin
		--print '此仓库有期初序列号，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】有期初序列号关联情况，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】有期初序列号关联情况，不能分类',16,1,@parFullName)return--return -16
	end

-- 判断借欠余额
if exists(select kTypeID from V_LendStatus where kTypeID=@parid and Qty<>0)
	begin
		--print '['+@FullName+']仓库有借进借出，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】有借进借出，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】有借进借出，不能分类',16,1,@parFullName)return--return -5
	end 
-- 判断经营
if exists(select kTypeID from InOutStockTable where kTypeID=@parid and Qty<>0)      
   or exists(select kTypeID from LendIndex where kTypeID=@parid and totalQty<>0)    
	begin
		--print '['+@FullName+']仓库已经经营过，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
	end 
if exists(select kTypeID from OrderIndex where kTypeID=@parid and kTypeID <> '00000' )
	begin
		-- print '订单使用过'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】已在订单中使用，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】已在订单中使用，不能分类',16,1,@parFullName)return--return -501
	end
if exists(select kTypeID from LendIndex where kTypeID=@parid)
	begin
		-- print '借欠使用过'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】已在借欠单中使用，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】已在借欠单中使用，不能分类',16,1,@parFullName)return--return -502
	end

if exists(select kTypeID from Billindex where (kTypeID=@parid OR  kTypeID2=@parid OR  kTypeID3=@parid) and kTypeID <> '00000')    --modify 2010.05.21  ljun
	begin
		--经营过
		SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
	end

if exists(select kTypeID from iniCommissionStock where kTypeID=@parid and Qty<>0)
   or exists(select kTypeID from CommissionStock where kTypeID=@parid and Qty<>0)
	begin
		--print '['+@FullName+']仓库有代销情况，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】存在代销情况，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】存在代销情况，不能分类',16,1,@parFullName)return--return -13
	end 

if exists(select kTypeID from iniCommissionStock where kTypeID=@parid and total<>0)
   or exists(select kTypeID from CommissionStock where kTypeID=@parid and total<>0)
	begin
		--print '['+@FullName+']仓库有代销情况，不能分类'
		SET @ErrMsg = '该仓库【'+ @parFullName +'】存在代销情况，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】存在代销情况，不能分类',16,1,@parFullName)return--return -13
	end 
	if @ifqp='1'
	begin
		--采购类单
		if exists(select ktypeid from buybill where ktypeid=@parid)
			BEGIN
				SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
			end
		--领料出库单
		if exists(select KTypeID from Qp_PickingBill where ktypeid=@parid)
			begin
			    --print '2555'
			    SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
			end
		--领料退回单
		if exists(select KTypeId from Qp_PickingBackBill where KTypeId=@parid)
			begin
			    --print '2555'
			    SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
			end
		--销售类
		if exists(select ktypeid from salebill where ktypeid=@parid)
			BEGIN
				SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
			end
		--代销类
		if exists(select ktypeid from CommissionBill where ktypeid=@parid)
			BEGIN
				SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@FullName)return--RETURN -6
			end
		--订单类
		if exists(select ktypeid from orderbill where ktypeid=@parid)
			BEGIN
				SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
			end
		if exists(select ktypeid from IntegralExchangeBill where ktypeid=@parid)
			BEGIN
				SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
			end
		--快修单表体
		if exists(select ktypeid from QP_QuickRepairBill_PType where ktypeid=@parid)
			BEGIN
				SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
			end
		--生产拆装单
		if exists(select ktypeid from disassemblebill where ktypeid=@parid)
			BEGIN
				SET @ErrMsg = '该仓库【'+ @parFullName +'】已经经营过，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)return--RETURN -6
			end
		--已设置货位
		if exists(select ktypeid from CargoSpace where ktypeid=@parid)
			BEGIN
				SET @ErrMsg = '该仓库【'+ @parFullName +'】已设置货位，不能分类'
				RETURN -1
				--RAISERROR('该仓库【%s】已设置货位，不能分类',16,1,@parFullName)return--return -35
			end
	end

--盘点单
if exists(select top 1 ktypeid  from  StockCheckIndex where ktypeid=@parid  )
	BEGIN
		SET @ErrMsg = '该仓库【'+ @parFullName +'】已在库存盘点单中使用，不能分类'
		RETURN -1
		--RAISERROR('该仓库【%s】已在库存盘点单中使用，不能分类',16,1,@parFullName)return--return -370
	end
end

--销售类
		IF EXISTS(SELECT * FROM OrderBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				SET @ErrMsg = '该仓库已关联销售订单或采购订单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联销售订单或采购订单，不能分类',16,1)
				--RETURN
			END
		IF EXISTS(SELECT * FROM SaleBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				SET @ErrMsg = '该仓库已关联销售出库单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联销售出库单，不能分类',16,1)
				--RETURN
			END
		IF EXISTS(SELECT * FROM SaleGoodsExchangeBill,Stock WHERE (KTypeID=@parid AND KTypeID=Stock.typeId) OR (KTypeID2=@parid AND KTypeID2=Stock.typeId))
			BEGIN
				SET @ErrMsg = '该仓库已关联销售换货单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联销售换货单，不能分类',16,1)
				--RETURN
			END
		IF EXISTS(SELECT * FROM SaleBackBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				SET @ErrMsg = '该仓库已关联销售退货单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联销售退货单，不能分类',16,1)
				--RETURN
			END
		IF EXISTS(SELECT * FROM CommissionBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				SET @ErrMsg = '该仓库已关联委托代销单据，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联委托代销单据，不能分类',16,1)
				--RETURN
			END
		--采购类
		IF EXISTS(SELECT * FROM BuyBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				SET @ErrMsg = '该仓库已关联采购入库单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联采购入库单，不能分类',16,1)
				--RETURN
			END
		IF EXISTS(SELECT * FROM BuybackBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				SET @ErrMsg = '该仓库已关联采购退货单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联采购退货单，不能分类',16,1)
				--RETURN
			END
		IF EXISTS(SELECT * FROM BuyGoodsExchangeBill,Stock WHERE (KTypeID=@parid AND KTypeID=Stock.typeId) OR ((KTypeID2=@parid AND KTypeID2=Stock.typeId)))
			BEGIN
				SET @ErrMsg = '该仓库已关联采购换货单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联采购换货单，不能分类',16,1)
				--RETURN
			END
		--库存类
		IF EXISTS(SELECT * FROM StypeMoveBill,Stock WHERE (KTypeID=@parid AND KTypeID=Stock.typeId) OR ((KTypeID2=@parid AND KTypeID2=Stock.typeId)))
			BEGIN
				SET @ErrMsg = '该仓库已关联分支机构调拨出库单或分支机构调拨入库单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联分支机构调拨出库单或分支机构调拨入库单，不能分类',16,1)
				--RETURN
			END
		IF EXISTS(SELECT * FROM DisassembleBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				SET @ErrMsg = '该仓库已关联生产拆装单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联生产拆装单，不能分类',16,1)
				--RETURN
			END
		--会员类
		IF EXISTS(SELECT * FROM IntegralExchangeBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				SET @ErrMsg = '该仓库已关联积分兑换单，不能分类'
				RETURN -1
				--RAISERROR('该仓库已关联积分兑换单，不能分类',16,1)
				--RETURN
			END


-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
	BEGIN
		SET @ErrMsg = '仓库的分类不能超过10层'
		RETURN -1
		--RAISERROR('仓库的分类不能超过10层',16,1)return--return -1
	end
if @nReturntype=-2 
	BEGIN
		SET @ErrMsg = '无法添加基本信息'
		RETURN -1
		--RAISERROR('无法添加基本信息',16,1)return--return -2
	end
-- 判断重复的ID,UserCode
if exists(select typeId from Stock where  (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
	begin
		--print '['+@usercode+']仓库已存在'
		SET @ErrMsg = '【' + @FullName + '】已经存在，仓库的名称或编号不能相同'
		RETURN -1
		--RAISERROR('【%s】已经存在，仓库的名称或编号不能相同',16,1,@FullName)return--return -3
	end


-- 判断重复的ID,UserCode
if exists(select * from [stock] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		--print '['+@usercode+']仓库已存在'
		SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被已停用的仓库使用，请更换或删除该停用的编号或名称'
		RETURN -1
		--RAISERROR('该【%s】的编号或名称已被已停用的仓库使用，请更换或删除该停用的编号或名称',16,1,@FullName)return--return -31
	end
-- 判断重复的ID,UserCode
if exists(select * from [stock] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
	begin
		--print '['+@usercode+']仓库已存在'
		SET @ErrMsg = '该仓库【' + @FullName + '】名称或编号不能与已停用的名称或编号重复'
		RETURN -1
		--RAISERROR('该仓库【%s】名称或编号不能与已停用的名称或编号重复',16,1,@FullName)return--return -101
	end

/*
-- 判断仓库的最大使用数量
declare @nCount int
select @nCount=Count(*) from stock 
where sonnum = 0 
 and deleted=0
if @nCount > 10
begin
-- print '仓库数量大于10'
 return -99
end
*/

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

begin tran insertproc
select @leveal=leveal from stock where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO [stock] 
  ( 
	[typeId],
	[Parid],
	[leveal],
	[soncount],
	[sonnum],
	[FullName],
	[Name], 
	[UserCode],
	[Comment],
	[LinkMan],
	[Tel],
	[Add],
	[PyCode],
	[STypeID]
 )  
VALUES 
 ( 
	@EtypeId_1,
	@Parid,
	@leveal,
	0,
	0,
	@FullName,
	@name,
	@UserCode,
	@Comment,
	@LinkMan ,
	@Tel ,
	@Address,
	@returnPym,
	@STypeID
 )
if @@rowcount=0 
begin
	rollback tran insertproc 
	return -1
end else 
begin
	update [stock]
	set sonnum=@nSonnum+1,soncount=@nSoncount+1
	where typeid=@Parid
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Stock
UPDATE Stock SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
commit tran insertproc



SET @ReturnID = @@ROWCOUNT



















GO





IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_ImportKtypeStockAlarm]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].Gp_ImportKtypeStockAlarm
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：zyq
	日    期：2019-09-06
	描	  述：按仓库库存上下限导入 
*/


CREATE PROCEDURE [dbo].[Gp_ImportKtypeStockAlarm]
   (
	@KtypeUserCode   [varchar](200), --仓库编号
	@KtypeUFullName   [varchar](200),---仓库名称
	@ProductUserCode   [varchar](200),--商品编号
	@ProductFullName   [varchar](200),--商品名称
	@UpQty		VARCHAR(10)= '',  --库存上限
	@DownQty	VARCHAR(10)= '', ---库存下限
	@OrderQty   VARCHAR(10)= '',	--订货库存
	@ErrMsg     VARCHAR(200) output
)
AS
SET NOCOUNT ON
-------------------------------------------转换输入参数----------------------------
DECLARE @ktypeid [varchar](200)
DECLARE @ptypeid [varchar](200) 
DECLARE @UpQtys NUMERIC(18,2)
DECLARE @DownQtys NUMERIC(18,2)
DECLARE @OrderQtys NUMERIC(18,2)

IF(@UpQty = '' ) 
BEGIN
     SET  @UpQtys=0
END
ELSE
BEGIN
     SET @UpQtys = CONVERT(NUMERIC(18,2),@UpQty)
END


IF(@DownQty = '' ) 
BEGIN
     SET  @DownQtys=0
END 
ELSE
BEGIN
    SET @DownQtys = CONVERT(NUMERIC(18,2),@DownQty)
END

IF (@OrderQty='')
BEGIN
     SET  @OrderQtys=CONVERT(NUMERIC(18,2),0)
END
ELSE
BEGIN
     SET @OrderQtys = CONVERT(NUMERIC(18,2),@OrderQty)
END

--商品编号
select @ptypeid = typeid from PType where usercode=@ProductUserCode
--仓库
select @ktypeid = typeid from Stock where usercode=@KtypeUserCode



---导入验证仓库----
IF(@KtypeUserCode = '')
BEGIN
	SET @ErrMsg = '仓库编号不能为空'
	RETURN -1
END
ELSE IF(NOT EXISTS(SELECT top 1 1 FROM Stock WHERE UserCode = @KtypeUserCode))
	BEGIN
		SET @ErrMsg = '仓库编号不存在'
		RETURN -1
	END
IF @KtypeUFullName<>'' AND NOT EXISTS(SELECT top 1 1 FROM Stock WHERE UserCode = @KtypeUserCode AND FullName=@KtypeUFullName)
    BEGIN
    SET @ErrMsg = '仓库编号和仓库名称不匹配'
		RETURN -1
    END

IF(EXISTS(SELECT top 1 1 FROM Stock WHERE UserCode = @KtypeUserCode AND Sonnum > 0 ))
	BEGIN
		SET @ErrMsg = '仓库不能为父节点'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Stock WHERE UserCode = @KtypeUserCode AND Deleted = 1 ))
	BEGIN
		SET @ErrMsg = '仓库已停用'
		RETURN -1
	END
	
	
---导入验证商品----	    
IF(@ProductUserCode = '')
BEGIN
	SET @ErrMsg = '商品编号不能为空'
	RETURN -1
END
ELSE IF(NOT EXISTS(SELECT top 1 1 FROM ptype WHERE UserCode = @ProductUserCode))
	BEGIN
		SET @ErrMsg = '商品编号不存在'
		RETURN -1
	END
IF @ProductFullName<>'' AND NOT EXISTS(SELECT top 1 1 FROM ptype WHERE UserCode = @ProductUserCode AND FullName=@ProductFullName)
    BEGIN
    SET @ErrMsg = '商品编号和商品名称不匹配'
		RETURN -1
    END
IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @ProductUserCode AND Sonnum > 0 ))
	BEGIN
		SET @ErrMsg = '商品不能为父节点'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @ProductUserCode AND Iscombinationproduct = 1 ))
	BEGIN
		SET @ErrMsg = '商品不能为组合品'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @ProductUserCode AND isservice = 1 ))
	BEGIN
		SET @ErrMsg = '商品不能为服务商品'
		RETURN -1
	END
	ELSE IF(EXISTS(SELECT top 1 1 FROM Ptype WHERE UserCode = @ProductUserCode AND Deleted = 1 ))
	BEGIN
		SET @ErrMsg = '商品已停用'
		RETURN -1
	END
	
---导入验证数量----	 

--配套数量
	IF(@UpQtys < 0 )
	BEGIN
		SET @ErrMsg = '库存上限必须大于0'
		RETURN -1
	END
	IF(@DownQtys < 0 )
	BEGIN
		SET @ErrMsg = '库存下限必须大于0'
		RETURN -1
	END
	IF(@OrderQtys < 0 )
	BEGIN
		SET @ErrMsg = '订货库存必须大于0'
		RETURN -1
	END
	IF(@UpQtys>0 and @DownQtys>0 and @UpQtys <= @DownQtys )
	BEGIN
		SET @ErrMsg = '库存上限必须大于库存下限'
		RETURN -1
	END


BEGIN TRAN insertproc

IF NOT EXISTS(SELECT TOP 1 1 FROM STOCKALARM where PtypeId=@ptypeid AND KTypeId=@ktypeid)
BEGIN
INSERT INTO [STOCKALARM] 
  ( 
   PTypeId,
   KTypeId,
   UpLimitQty,
   DownLimitQty,
   OrderQty
 
 )  
VALUES 
 ( 
 @ptypeid,
 @ktypeid,
 @UpQtys,
 @DownQtys,
 @OrderQtys
 )

 IF @@ROWCOUNT=0 
    BEGIN
	ROLLBACK TRAN insertproc 
	 SET @ErrMsg = '新增数据失败！'
	RETURN -1
    END
END
ELSE 

    update STOCKALARM
    set UpLimitQty=@UpQtys,DownLimitQty=@DownQtys,OrderQty=@OrderQtys 
   WHERE PtypeId=@ptypeid AND KTypeId=@ktypeid


 COMMIT TRAN insertproc

GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：王珏
	日期：2013-02-21
	描述：导入POS档案信息
*/
CREATE	PROCEDURE	GP_ImportPosInfo
(
	@OperatorID		VARCHAR(100),
	@usercode		VARCHAR(200),
	@fullname		VARCHAR(200),
	@kfullname		VARCHAR(66),
	@bfullname		VARCHAR(66),
	@bankcard		VARCHAR(200),
	@cash			VARCHAR(200),			
	@strpycode		VARCHAR(100),		
	@strcomment		VARCHAR(500),
	@wxpay			VARCHAR(100)='',
	@alipay			VARCHAR(100)='',
	@allinpay		VARCHAR(100)='',
	@jfpay			VARCHAR(100)='',
	@enablebtype	VARCHAR(100)='',
	@dealbtype		VARCHAR(100)='',
	@ErrMsg         VARCHAR(200) OUTPUT	
)
--@encode$--  
AS
SET NOCOUNT ON

DECLARE @ktypeid	VARCHAR(50)
DECLARE @kid		INT
DECLARE @btypeid	VARCHAR(50)
DECLARE @stypeid	VARCHAR(50)
DECLARE @BankCardID	INT
DECLARE @CashID		INT
DECLARE @pycode		VARCHAR(100)
DECLARE @comment	VARCHAR(500)


IF(@usercode = '')
BEGIN
	SET @ErrMsg = 'POS编号不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF EXISTS (SELECT 1 FROM PosInfo WHERE UserCode=@usercode)
		BEGIN
			SET @ErrMsg = 'POS编号已经存在'
			RETURN -1 
		END
END

IF(@fullname = '')
BEGIN
	SET @ErrMsg = 'POS名称不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF EXISTS (SELECT 1 FROM PosInfo WHERE FullName=@fullname)
		BEGIN
			SET @ErrMsg = 'POS名称已经存在'
			RETURN -1 
		END
END

IF(@kfullname = '')
BEGIN
	SET @ErrMsg = '所属仓库不能为空'
	RETURN -1
END	
ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.Stock WHERE FullName=@kfullname) OR @kfullname = '全部仓库'
		BEGIN
			SET @ErrMsg = '该所属仓库不存在'
			RETURN -1
		END
		ELSE
		BEGIN
			DECLARE @SKtypeId VARCHAR(50)
			DECLARE @SKid INT
			DECLARE @KChildCount NUMERIC(18,0)
			SET @SKtypeId = (SELECT TOP 1 typeid FROM dbo.Stock WHERE fullname = @kfullname)
			SET @SKid = (SELECT TOP 1 Kid FROM dbo.Stock WHERE fullname = @kfullname)
			SELECT @KChildCount = COUNT(*) FROM dbo.Stock WHERE typeId LIKE @SKtypeId + '%' AND typeId <> @SKtypeId
			IF (@KChildCount = 0)
				BEGIN
					SET @ktypeid = @SKtypeId
					SET @kid=@SKid
				END	
			ELSE
			BEGIN
				SET @ErrMsg = '该所属仓库是父类'
				RETURN -1
			END
		END	
	END	

IF NOT EXISTS(SELECT TOP 1 typeid FROM F_GetManKTypeAll(@OperatorID) WHERE typeId=@ktypeid)
BEGIN
	SET @ErrMsg='该职员无该仓库权限'
		RETURN -1
END
			
DECLARE @kdeleted INT
DECLARE @kCargoCount INT
SELECT @kdeleted=deleted FROM dbo.Stock WHERE typeId=@ktypeid
IF @kdeleted=1
BEGIN
	SET @ErrMsg = '该仓库已停用'
	RETURN -1
END

SELECT @kCargoCount=count(1) FROM CargoType where ktypeid= @ktypeid
IF(@kCargoCount>1)
BEGIN
	SET @ErrMsg = '该仓库存在多个货位'
	RETURN -1
END


SELECT @stypeid=stypeid FROM dbo.Stock WHERE typeid=@ktypeid

IF(@bfullname = '')
BEGIN
	SET @ErrMsg = '对应客户不能为空'
	RETURN -1
END	
ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.Btype WHERE FullName=@bfullname AND typeid LIKE '00001%') OR @bfullname = '所有客户'
		BEGIN
			SET @ErrMsg = '该对应客户不存在'
			RETURN -1
		END
		ELSE
		BEGIN
			DECLARE @SBtypeId VARCHAR(50)
			DECLARE @BChildCount NUMERIC(18,0)
			SET @SBtypeId = (SELECT TOP 1 typeid FROM dbo.Btype WHERE fullname = @bfullname AND typeid LIKE '00001%')
			SELECT @BChildCount = COUNT(*) FROM dbo.Btype WHERE typeId LIKE @SBtypeId + '%' AND typeId <> @SBtypeId
			IF (@BChildCount = 0)
				SET @btypeid = @SBtypeId
			ELSE
			BEGIN
				SET @ErrMsg = '该对应客户是父类'
				RETURN -1
			END
		END	
	END	

IF NOT EXISTS (SELECT TOP 1 TypeId FROM F_GetManBTypeAll(@OperatorID) WHERE typeId like '00001%' AND typeId=@btypeid)
BEGIN
	SET @ErrMsg = '该职员无该客户权限'
	RETURN -1
END

DECLARE @cdeleted INT
SELECT @cdeleted=deleted FROM dbo.Btype WHERE typeId=@btypeid
IF @cdeleted=1
BEGIN
	SET @ErrMsg = '该客户已停用'
	RETURN -1
END

IF(@bankcard = '')
BEGIN
	SET @ErrMsg = '银行卡对应项目不能为空'
	RETURN -1
END	
ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.Ac_Items WHERE FullName=@bankcard AND IsBank = 1)
		BEGIN
			SET @ErrMsg = '该银行卡对应项目不存在'
			RETURN -1
		END
		ELSE
		BEGIN
			DECLARE @SBankCardID INT
			DECLARE @nTypeId VARCHAR(50)
			DECLARE @BankChildCount NUMERIC(18,0)
			SELECT TOP 1 @SBankCardID = nid,@nTypeId = nTypeId FROM dbo.Ac_Items WHERE fullname = @bankcard AND IsBank = 1
			SELECT @BankChildCount = COUNT(*) FROM dbo.Ac_Items WHERE nTypeid LIKE @nTypeId + '%' AND nTypeId <> @nTypeId
			IF (@BankChildCount = 0)
				SET @BankCardID = @SBankCardID
			ELSE
			BEGIN
				SET @ErrMsg = '该银行卡对应项目是父类'
				RETURN -1
			END
		END	
	END
	
IF NOT EXISTS (SELECT TOP 1 nid FROM F_GetManDetailAllAType(@OperatorID) WHERE nid=@BankCardID)
BEGIN
	SET @ErrMsg = '该职员无该银行卡权限'
	RETURN -1
END
		
DECLARE @bdeleted INT
SELECT @bdeleted=deleted FROM dbo.Ac_Items WHERE nid=@BankCardID
IF @bdeleted=1
BEGIN
	SET @ErrMsg = '该银行卡已停用'
	RETURN -1
END

IF(@cash = '')
BEGIN
	SET @ErrMsg = '现金对应项目不能为空'
	RETURN -1
END	
ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.Ac_Items WHERE FullName=@cash AND nTypeId like '0000100003%')
		BEGIN
			SET @ErrMsg = '该现金对应项目不存在'
			RETURN -1
		END
		ELSE
		BEGIN
			DECLARE @SCashID INT
			DECLARE @nTypeIdCash VARCHAR(50)
			DECLARE @CashChildCount NUMERIC(18,0)
			SELECT TOP 1 @SCashID = nid,@nTypeIdCash = nTypeId FROM dbo.Ac_Items WHERE fullname = @cash AND nTypeId like '0000100003%'
			SELECT @CashChildCount = COUNT(*) FROM dbo.Ac_Items WHERE nTypeid LIKE @nTypeIdCash + '%' AND nTypeId <> @nTypeIdCash
			IF (@CashChildCount = 0)
				SET @CashID = @SCashID
			ELSE
			BEGIN
				SET @ErrMsg = '该现金对应项目是父类'
				RETURN -1
			END
		END	
	END
	
IF NOT EXISTS (SELECT TOP 1 nid FROM F_GetManDetailAllAType(@OperatorID) WHERE nid=@CashID)
BEGIN
	SET @ErrMsg = '该职员无该现金项目权限'
	RETURN -1
END
		
DECLARE @bdeletedcash INT
SELECT @bdeletedcash=deleted FROM dbo.Ac_Items WHERE nid=@CashID
IF @bdeletedcash=1
BEGIN
	SET @ErrMsg = '该现金项目已停用'
	RETURN -1
END

IF @enablebtype NOT IN ('是','否')
BEGIN
	SET @ErrMsg = '启用挂往来只能填写是或否'
		RETURN -1 	
END

DECLARE @WxPayID		   INT,
		@AlipayID		   INT,
		@AllInpayID		   INT,
		@JFPayID		   INT,
		@DealBTypeID	   VARCHAR(50),
		@IsDealBType BIT

IF @enablebtype='是'
BEGIN
	/*
		任泉熹 2018-02-06 10:59:59
		ID:2083，bug修正，系统已启用品牌应收功能的，不允许导入挂往来的pos信息
	*/
	IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='usebrandartype' and SubValue=1)
	BEGIN
		SET @ErrMsg = '已启用品牌应收功能，不能导入挂往来账户'
		RETURN -1
	END
	--IF NOT EXISTS(SELECT 1 FROM dbo.btype WHERE FullName=@dealbtype)
	--BEGIN
	--	SET @ErrMsg = '该往来账户不存在'
	--	RETURN -1
	--END
	--IF EXISTS(SELECT 1 FROM dbo.btype WHERE FullName=@dealBtype AND soncount<>0)
	--BEGIN
	--	SET @ErrMsg = '该往来账户是大类，不能导入'
	--	RETURN -1 	
	--END
	--IF EXISTS(SELECT 1 FROM dbo.btype WHERE FullName=@dealBType AND TypeID LIKE '00002%')
	--BEGIN
	--	SET @ErrMsg = '该往来账户不是有效的客户'
	--	RETURN -1 	
	--END
	--IF EXISTS(SELECT 1 FROM dbo.btype WHERE FullName=@dealbtype AND deleted=1)
	--BEGIN
	--	SET @ErrMsg='该往来账户已停用'
	--	RETURN -1
	--END
	--IF NOT EXISTS(SELECT 1 FROM dbo.F_GetManBTypeAll(@OperatorID) WHERE FullName=@dealbtype)
	--BEGIN
	--	SET @ErrMsg='无该往来账户权限'
	--	RETURN -1
	--END
	SELECT @DealBTypeID='',@IsDealBType=1
END

IF @enablebtype='否'
BEGIN
	SELECT @DealBTypeID='',@IsDealBType=0
END

--IF NOT EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@wxpay)
--BEGIN
--	SET @ErrMsg = '该微信项目不存在'
--	RETURN -1
--END
IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@wxpay AND soncount<>0 AND ISNULL(@wxpay, '') <> '')
BEGIN
	SET @ErrMsg = '该微信项目是大类，不能导入'
	RETURN -1 	
END
IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@wxpay AND deleted=1 AND ISNULL(@wxpay, '') <> '')
BEGIN
	SET @ErrMsg='该微信项目已停用'
	RETURN -1
END

IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@WxPay AND IsBank=0 AND ISNULL(@wxpay, '') <> '')
BEGIN
	SET @ErrMsg='该微信项目不是有效的银行账户'
	RETURN -1
END

IF ISNULL(@WxPay,'')=''
BEGIN
	SET	@WxPayID=0
END
ELSE
BEGIN
	SELECT @WxPayID=nid FROM dbo.Ac_Items WHERE FullName=@WxPay AND ISNULL(@wxpay, '') <> ''
END


IF NOT EXISTS(SELECT 1 FROM dbo.F_GetManDetailAllAType(@OperatorID) WHERE Nid=@WxPayID) AND ISNULL(@wxpay, '') <> ''
BEGIN
	SET @ErrMsg='无该微信项目权限'
	RETURN -1
END
-----------------------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@alipay)
BEGIN
	SET @ErrMsg = '该支付宝项目不存在'
	RETURN -1
END
IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@alipay AND soncount<>0)
BEGIN
	SET @ErrMsg = '该支付宝项目是大类，不能导入'
	RETURN -1 	
END
IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@alipay AND deleted=1)
BEGIN
	SET @ErrMsg='该支付宝项目已停用'
	RETURN -1
END

IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@alipay AND IsBank=0)
BEGIN
	SET @ErrMsg='该支付宝项目不是有效的银行账户'
	RETURN -1
END
SELECT @AliPayID=nid FROM dbo.Ac_Items WHERE FullName=@alipay

IF NOT EXISTS(SELECT 1 FROM dbo.F_GetManDetailAllAType(@OperatorID) WHERE Nid=@AliPayID)
BEGIN
	SET @ErrMsg='无该支付宝项目权限'
	RETURN -1
END
------------------------------------------------------------

-----------------------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@allinpay)
BEGIN
	SET @ErrMsg = '该易支付项目不存在'
	RETURN -1
END
IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@allinpay AND soncount<>0)
BEGIN
	SET @ErrMsg = '该易支付项目是大类，不能导入'
	RETURN -1 	
END
IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@allinpay AND deleted=1)
BEGIN
	SET @ErrMsg='该易支付项目已停用'
	RETURN -1
END

IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@allinpay AND IsBank=0)
BEGIN
	SET @ErrMsg='该易支付项目不是有效的银行账户'
	RETURN -1
END
SELECT @AllInpayID=nid FROM dbo.Ac_Items WHERE FullName=@allinpay

IF NOT EXISTS(SELECT 1 FROM dbo.F_GetManDetailAllAType(@OperatorID) WHERE Nid=@AllInpayID)
BEGIN
	SET @ErrMsg='无该易支付项目权限'
	RETURN -1
END
------------------------------------------------------------

-----------------------------------------------------------------
IF NOT EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@jfpay)
BEGIN
	SET @ErrMsg = '该积分收款项目不存在'
	RETURN -1
END
IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@jfpay AND SonNum<>0)
BEGIN
	SET @ErrMsg = '该积分收款项目是大类，不能导入'
	RETURN -1 	
END
IF EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE FullName=@jfpay AND deleted=1)
BEGIN
	SET @ErrMsg='该积分收款项目已停用'
	RETURN -1
END

SELECT @JFPayID=nid FROM dbo.Ac_Items WHERE FullName=@jfpay
IF NOT EXISTS(SELECT 1 FROM dbo.F_GetManDetailAllAType(@OperatorID) WHERE Nid=@AliPayID)
BEGIN
	SET @ErrMsg='无积分收款项目权限'
	RETURN -1
END
------------------------------------------------------------

IF(@strpycode = '')
BEGIN
	SET @pycode = dbo.fun_getPY(@FullName)
END	
ELSE
BEGIN
	SET @pycode = @strpycode
END

IF(@strcomment = '')
BEGIN
	SET @comment = NULL
END
ELSE
BEGIN
	SET @comment = @strcomment
END	

DECLARE @ItemId INT
SELECT @ItemId=nid FROM dbo.Ac_Items WHERE UserCode='2191'	AND FullName='『优惠券』'

--991bug 1343 POS导入模板中没有这几项，需要默认改1，pos才能使用
BEGIN TRAN insertproc
INSERT INTO PosInfo (UserCode,
					 FullName,
					 ktypeid,
					 stypeid,
					 BtypeID,
					 BankCardID,
					 CashID,
					 VIPMoneyID,					 
					 PyCode,
					 STATE,
					 Comment,
					 KID,
					 enablebtype,
					 dealbtypeid,
					 wxpayid,
					 alipayid,
					 allinpayid,
					 JFPayId,
					 PassType,
					 permitsavenonnumber,
					 codesearchway,
					 rememberemployee,
					 permitsaleemployee,
					 enablemultipleaccounts,
					 couponmoneyid)
			 VALUES (@usercode,
					 @fullname,
					 @ktypeid,
					 @stypeid,
					 @btypeid,
					 @BankCardID,
					 @CashID,
					 34,						
					 @pycode,
					 1,							
					 @comment,
					 @kid,
					 @IsDealBType,
					 @DealBTypeID,
					 @WxPayID,
					 @AliPayID,
					 @AllInPayID,
					 @JFPayID,
					 1,
					 1,
					 1,
					 1,
					 1,
					 1,
					 @ItemId)
							
IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
        
COMMIT TRAN insertproc  
GO




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'GP_ImportPriceTempDT ') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_ImportPriceTempDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：把单据明细保存存储过程dt版
*/
CREATE PROCEDURE GP_ImportPriceTempDT
(
	@tb TbType_PriceTemp READONLY
)	
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	-- 写入数据表
	INSERT INTO ImportPriceTemp(
		 etypeid , 
		 typeid  ,
		 usercode  ,
		 fullname  ,
		 itemid  ,
		 itemname  ,
		 iscombined  ,
		 munit  ,
		 munitid  ,
		 munitrate 	,
		 baojiamode  ,
		 price ,
		 discount  ,
		 curmdiscountprice  ,
		 tax ,
		 curmtaxprice ,
		 xianjiamode  ,
		 comment  
	) SELECT 
		 etypeid , 
		 typeid  ,
		 usercode  ,
		 fullname  ,
		 itemid  ,
		 itemname  ,
		 iscombined  ,
		 munit  ,
		 munitid  ,
		 munitrate 	,
		 baojiamode  ,
		 price ,
		 discount  ,
		 curmdiscountprice  ,
		 tax ,
		 curmtaxprice ,
		 xianjiamode  ,
		 comment  
	FROM @tb
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'GP_ImportPriceTrackDetail') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_ImportPriceTrackDetail;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：把单据明细保存存储过程dt版
*/
CREATE PROCEDURE GP_ImportPriceTrackDetail
(
	@PriceTrackType VARCHAR(6), --价格类型  0.销售订单  1.销售出库单  2.采购订单  3.采购入库单 4.报价单  5.询价单 6.发出商品出库单 7.暂估入库单
	@tb TbType_PriceTrackDetail READONLY
)	
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @TrackTime DATETIME 
	
	SELECT @TrackTime= GETDATE()
	
	IF @PriceTrackType='0'	
	BEGIN
		--有重复数据的时候先删除重复数据再插入新数据
		DELETE PriceTrack_SaleOrder FROM PriceTrack_SaleOrder p, @tb t
		WHERE p.BtypeId=T.BtypeId AND p.BtypeFlag=T.BtypeFlag AND p.PtypeId=T.PtypeId AND p.StypeId=T.StypeId AND p.UId=T.UId AND p.CId=T.CId
		INSERT INTO dbo.PriceTrack_SaleOrder
	        ( BtypeId ,
	          BtypeFlag ,
	          PtypeId ,
	          StypeId ,
	          [UId] ,
	          CId ,
	          Price ,
	          DiscountRate ,
	          DiscountPrice ,
	          Tax ,
	          TaxPrice,
	          TrackTime
	        )
	         SELECT 
				BtypeId , 
				BtypeFlag  ,
				PtypeId  ,
				StypeId  ,
				[UId]  ,
				CId  ,
				Price  ,
				DiscountRate  ,
				DiscountPrice  ,
				Tax 	,
				TaxPrice  ,
				@TrackTime
			FROM @tb
	END
	ELSE IF @PriceTrackType='1'
	BEGIN
	--有重复数据的时候先删除重复数据再插入新数据
		DELETE PriceTrack_Sale FROM PriceTrack_Sale p, @tb t
		WHERE p.BtypeId=T.BtypeId AND p.BtypeFlag=T.BtypeFlag AND p.PtypeId=T.PtypeId AND p.StypeId=T.StypeId AND p.UId=T.UId AND p.CId=T.CId
		INSERT INTO dbo.PriceTrack_Sale
	        ( BtypeId ,
	          BtypeFlag ,
	          PtypeId ,
	          StypeId ,
	          [UId] ,
	          CId ,
	          Price ,
	          DiscountRate ,
	          DiscountPrice ,
	          Tax ,
	          TaxPrice,
	          TrackTime
	        )
	         SELECT 
				BtypeId , 
				BtypeFlag  ,
				PtypeId  ,
				StypeId  ,
				[UId]  ,
				CId  ,
				Price  ,
				DiscountRate  ,
				DiscountPrice  ,
				Tax 	,
				TaxPrice ,
				@TrackTime 
			FROM @tb
	END
	ELSE IF @PriceTrackType='2'
	BEGIN
	--有重复数据的时候先删除重复数据再插入新数据
		DELETE PriceTrack_BuyOrder FROM PriceTrack_BuyOrder p, @tb t
		WHERE p.BtypeId=T.BtypeId AND p.BtypeFlag=T.BtypeFlag AND p.PtypeId=T.PtypeId AND p.StypeId=T.StypeId AND p.UId=T.UId AND p.CId=T.CId
		INSERT INTO dbo.PriceTrack_BuyOrder
	        ( BtypeId ,
	          BtypeFlag ,
	          PtypeId ,
	          StypeId ,
	          [UId] ,
	          CId ,
	          Price ,
	          DiscountRate ,
	          DiscountPrice ,
	          Tax ,
	          TaxPrice,
	          TrackTime
	        )
	         SELECT 
				BtypeId , 
				BtypeFlag  ,
				PtypeId  ,
				StypeId  ,
				[UId]  ,
				CId  ,
				Price  ,
				DiscountRate  ,
				DiscountPrice  ,
				Tax 	,
				TaxPrice  ,
				@TrackTime
			FROM @tb
	END 
	ELSE IF @PriceTrackType='3'
	BEGIN
	--有重复数据的时候先删除重复数据再插入新数据
		DELETE PriceTrack_Buy FROM PriceTrack_Buy p, @tb t
		WHERE p.BtypeId=T.BtypeId AND p.BtypeFlag=T.BtypeFlag AND p.PtypeId=T.PtypeId AND p.StypeId=T.StypeId AND p.UId=T.UId AND p.CId=T.CId
		INSERT INTO dbo.PriceTrack_Buy
	        ( BtypeId ,
	          BtypeFlag ,
	          PtypeId ,
	          StypeId ,
	          [UId] ,
	          CId ,
	          Price ,
	          DiscountRate ,
	          DiscountPrice ,
	          Tax ,
	          TaxPrice,
	          TrackTime
	        )
	         SELECT 
				BtypeId , 
				BtypeFlag  ,
				PtypeId  ,
				StypeId  ,
				[UId]  ,
				CId  ,
				Price  ,
				DiscountRate  ,
				DiscountPrice  ,
				Tax 	,
				TaxPrice  ,
				@TrackTime
			FROM @tb
	END
	ELSE IF @PriceTrackType='4'
	BEGIN
	--有重复数据的时候先删除重复数据再插入新数据
		DELETE PriceTrack_Quote FROM PriceTrack_Quote p, @tb t
		WHERE p.BtypeId=T.BtypeId AND p.BtypeFlag=T.BtypeFlag AND p.PtypeId=T.PtypeId AND p.StypeId=T.StypeId AND p.UId=T.UId AND p.CId=T.CId
		INSERT INTO dbo.PriceTrack_Quote
	        ( BtypeId ,
	          BtypeFlag ,
	          PtypeId ,
	          StypeId ,
	          [UId] ,
	          CId ,
	          Price ,
	          DiscountRate ,
	          DiscountPrice ,
	          Tax ,
	          TaxPrice,
	          TrackTime
	        )
	         SELECT 
				BtypeId , 
				BtypeFlag  ,
				PtypeId  ,
				StypeId  ,
				[UId]  ,
				CId  ,
				Price  ,
				DiscountRate  ,
				DiscountPrice  ,
				Tax 	,
				TaxPrice  ,
				@TrackTime
			FROM @tb
	END
	ELSE IF @PriceTrackType='5'
	BEGIN
	--有重复数据的时候先删除重复数据再插入新数据
		DELETE PriceTrack_AskPrice FROM PriceTrack_AskPrice p, @tb t
		WHERE p.BtypeId=T.BtypeId AND p.BtypeFlag=T.BtypeFlag AND p.PtypeId=T.PtypeId AND p.StypeId=T.StypeId AND p.UId=T.UId AND p.CId=T.CId
		INSERT INTO dbo.PriceTrack_AskPrice
	        ( BtypeId ,
	          BtypeFlag ,
	          PtypeId ,
	          StypeId ,
	          [UId] ,
	          CId ,
	          Price ,
	          DiscountRate ,
	          DiscountPrice ,
	          Tax ,
	          TaxPrice,
	          TrackTime
	        )
	         SELECT 
				BtypeId , 
				BtypeFlag  ,
				PtypeId  ,
				StypeId  ,
				[UId]  ,
				CId  ,
				Price  ,
				DiscountRate  ,
				DiscountPrice  ,
				Tax 	,
				TaxPrice  ,
				@TrackTime
			FROM @tb 
	END 
	ELSE IF @PriceTrackType='6'
	BEGIN
	--有重复数据的时候先删除重复数据再插入新数据
		DELETE PriceTrack_Send FROM PriceTrack_Send p, @tb t
		WHERE p.BtypeId=T.BtypeId AND p.BtypeFlag=T.BtypeFlag AND p.PtypeId=T.PtypeId AND p.StypeId=T.StypeId AND p.UId=T.UId AND p.CId=T.CId
		INSERT INTO dbo.PriceTrack_Send
	        ( BtypeId ,
	          BtypeFlag ,
	          PtypeId ,
	          StypeId ,
	          [UId] ,
	          CId ,
	          Price ,
	          DiscountRate ,
	          DiscountPrice ,
	          Tax ,
	          TaxPrice,
	          TrackTime
	        )
	         SELECT 
				BtypeId , 
				BtypeFlag  ,
				PtypeId  ,
				StypeId  ,
				[UId]  ,
				CId  ,
				Price  ,
				DiscountRate  ,
				DiscountPrice  ,
				Tax 	,
				TaxPrice  ,
				@TrackTime
			FROM @tb
	END 
	ELSE IF @PriceTrackType='7'
	BEGIN
	--有重复数据的时候先删除重复数据再插入新数据
		DELETE PriceTrack_Appraisal FROM PriceTrack_Appraisal p, @tb t
		WHERE p.BtypeId=T.BtypeId AND p.BtypeFlag=T.BtypeFlag AND p.PtypeId=T.PtypeId AND p.StypeId=T.StypeId AND p.UId=T.UId AND p.CId=T.CId
		INSERT INTO dbo.PriceTrack_Appraisal
	        ( BtypeId ,
	          BtypeFlag ,
	          PtypeId ,
	          StypeId ,
	          [UId] ,
	          CId ,
	          Price ,
	          DiscountRate ,
	          DiscountPrice ,
	          Tax ,
	          TaxPrice,
	          TrackTime
	        )
	         SELECT 
				BtypeId , 
				BtypeFlag  ,
				PtypeId  ,
				StypeId  ,
				[UId]  ,
				CId  ,
				Price  ,
				DiscountRate  ,
				DiscountPrice  ,
				Tax 	,
				TaxPrice  ,
				@TrackTime
			FROM @tb
	END
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportProduct]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_ImportProduct]
GO

/****** Object:  StoredProcedure [dbo].[QP_Gp_ImportP]    Script Date: 05/30/2011 15:28:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	修改：周华 李海洋
	时间：2012-08-01
	描述：导入工具用商品导入，因为gp_importptype这个存储过程有了，所以用product,参考以前版本：QP_Gp_ImportP 
	2013-05-07 周华 把9.1的敏捷搬过来 添加基本单位的设置
*/
CREATE          PROCEDURE [dbo].Gp_ImportProduct
    (
		@PUserCode [VARCHAR](200) ,
		@PFullName [varchar](200) ,
		@UserCode [varchar](200) ,
		@FullName [varchar](200) ,
		@Name [varchar](200) ,
		@Pycode [VARCHAR](200) ,
		@EntryCode [varchar](200) ,
		@Standard [varchar](200) ,
		@Type [varchar](200) ,
		@Area [varchar](200) ,
		@BuyDefaultRate [varchar](15), --采购/销售默认税率值】：可为空、可为零
		@SaleDefaultRate [varchar](15), 
		@UsefulLifeDay [varchar](200) ,
		@BFullName [varchar](200) ,
		@integral [VARCHAR](30) ,
		--@Unit1 [varchar](200),
		--@Unit2 [varchar](200),
		--@UnitRate1 [varchar](200),
		@IFullName VARCHAR(500), --存货类型
		@PCategory VARCHAR(500), --商品类别
		@Comment [varchar](251) ,
		@StrPreBuyPrice1 [VARCHAR](25) ,
		@StrPreBuyPrice2 [VARCHAR](25) ,
		@StrPreBuyPrice3 [VARCHAR](25) ,
		@StrPreBuyPrice4 [VARCHAR](25) ,
		@StrPreBuyPrice5 [VARCHAR](25) ,
		@StrTopBuyPrice [VARCHAR](25) ,
		@StrPreSalePrice1 [VARCHAR](25) ,
		@StrPreSalePrice2 [VARCHAR](25) ,
		@StrPreSalePrice3 [VARCHAR](25) ,
		@StrPreSalePrice4 [VARCHAR](25) ,
		@StrPreSalePrice5 [VARCHAR](25) ,
		@StrPreSalePrice6 [VARCHAR](25) ,
		@StrPreSalePrice7 [VARCHAR](25) ,
		@StrPreSalePrice8 [VARCHAR](25) ,
		@StrPreSalePrice9 [VARCHAR](25) ,
		@StrPreSalePrice10 [VARCHAR](25) ,
		@StrRetailPrice [VARCHAR](25) ,
		@StrTopSalePrice [VARCHAR](25) ,
		@StrLowSalePrice [VARCHAR](25) ,
		@ErrMsg VARCHAR(200) OUTPUT ,
		--@typeid [varchar](500) ,
		@IfUseEntryCode VARCHAR(10) ,   --是否启用条码
		@IfUseGoodsNum VARCHAR(10),   --是批号管理
		@IsCombinationProduct VARCHAR(10),    --组合品
		@customitemname VARCHAR(8000) ,  --自由项
		@ValidDays VARCHAR(100) ,		--近效天数  小于有效天数
		@IfSerial VARCHAR(10) ,		--是否严密序列号管理
		@SerialCount VARCHAR(100),		--序列号位数  小于50	
		@BaseUniteCode varchar(200), -- 基本单位 
		@SaleUniteCode VARCHAR(200),
		@SaleUniteRate VARCHAR(25),    
		@BuyUniteCode VARCHAR(200),
		@BuyUniteRate VARCHAR(25),    
		@StockUniteCode VARCHAR(200),
		@StockUniteRate VARCHAR(25),
		@AssistantUniteCode VARCHAR(200),
		@AssistantUniteRate VARCHAR(18),
		@ExtUniteCode1 VARCHAR(200),
		@ExtUniteRate1 VARCHAR(25),
		@EntryCode1 varchar(200)='' , --计量单位一条码、计量单位二条码、计量单位三条码
		@ExtUniteCode2 VARCHAR(200),
		@ExtUniteRate2 VARCHAR(25),
		@EntryCode2 varchar(200)='' ,
		@ExtUniteCode3 VARCHAR(200),
		@ExtUniteRate3 VARCHAR(25),
		@EntryCode3 varchar(200)='' ,
		@AssistantUniteCode1 VARCHAR(200),
		@AssistantUniteCode2 VARCHAR(200),
		@AssistantUniteCode3 VARCHAR(200),
		@IsService VARCHAR(10) ='',  --是否启用服务商品
		@OperatorID VARCHAR(200),  --操作员ID
		@STypeID VARCHAR(200), --分支机构
		@tb TbType_PtypeCustom  READONLY ,--自定义属性
		@costom1				VARCHAR(600)=''         ,
		@costom2				VARCHAR(600)=''          ,
		@costom3				VARCHAR(600)=''          ,
		@costom4				VARCHAR(600)=''          ,
		@costom5				VARCHAR(600)=''          ,
		@costom6				VARCHAR(600)=''          ,
		@costom7				VARCHAR(600)=''          ,
		@costom8				VARCHAR(600)=''          ,
		@costom9				VARCHAR(600)=''          ,
		@costom10				VARCHAR(600)=''          ,
		@costom11				VARCHAR(600)=''          ,
		@costom12				VARCHAR(600)=''          ,
		@costom13				VARCHAR(600)=''          ,
		@costom14				VARCHAR(600)=''          ,
		@costom15				VARCHAR(600)=''          ,
		@costom16				VARCHAR(600)=''          ,
		@brandarUserCode		VARCHAR(200)=''			 ,		--商品品牌编码
		@othercomment1	VARCHAR(250)='',		--其他备注
		@othercomment2	VARCHAR(250)='',		--其他备注
		@othercomment3	VARCHAR(250)='',		--其他备注
		@othercomment4	VARCHAR(250)='',		--其他备注
		@othercomment5	VARCHAR(250)=''			--其他备注 		
    )
--@encode$--
AS 
    SET NOCOUNT ON
    
    --商品品牌
	DECLARE @brandartypeid	VARCHAR(50)
	IF @brandarUserCode = ''
	BEGIN
		SELECT	@brandartypeid = TypeId FROM dbo.brandar_Commodity WHERE SonNum = 0 AND IsSys = 1
	END
	ELSE 
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE UserCode = @brandarUserCode AND sonnum = 0)
		BEGIN			
			SELECT	@brandartypeid = TypeId FROM dbo.brandar_Commodity WHERE SonNum = 0 AND  UserCode = @brandarUserCode
		END
		ELSE
		BEGIN
			SET @ErrMsg='商品品牌编码不正确' 
			RETURN -1
		END
	END

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @dbname [varchar](30) = 'Ptype'
--DECLARE @IfSerial [varchar](200) = '0'
--DECLARE @SerialCount [varchar](200) = '0' 
    DECLARE @ColorGroupID [varchar](50) = '0'
    DECLARE @SizeGroupID [varchar](50) = '0'
    DECLARE @DwgNo [varchar](200) = ''
    DECLARE @Brand [varchar](200) = ''
    DECLARE @Import [varchar](200) = ''
    DECLARE @GeneralType [varchar](200) = ''
    DECLARE @GeneralDwgNo [varchar](250) = ''
    DECLARE @Property [varchar](200) = ''
    DECLARE @PackageQty [varchar](200) = ''
    DECLARE @Weight [varchar](200) = '0'
    DECLARE @TaxNumber [varchar](200) = ''
    DECLARE @Taxrate [varchar](200) = '0'
    DECLARE @FcUnit [varchar](200) = ''
    DECLARE @FcPrice [varchar](200) = '0'
    DECLARE @autotypepycode [VARCHAR](MAX) = ''
    DECLARE @UsefulLifeMonth [varchar](200) = 0
	DECLARE @baseUniteId INT; --默认pcs
	DECLARE @SaleUniteId INT; --默认pcs
	DECLARE @BuyUniteId INT; --默认pcs
	DECLARE @StockUniteId INT; --默认pcs
	DECLARE @AssistantUniteId INT; 
	DECLARE @ExtUniteId1 INT; 
	DECLARE @ExtUniteId2 INT; 
	DECLARE @ExtUniteId3 INT; 
	DECLARE @AssistantUniteId1 INT; 
	DECLARE @AssistantUniteRate1 DECIMAL(24,10);
	DECLARE @AssistantUniteId2 INT; 
	DECLARE @AssistantUniteRate2 DECIMAL(24,10);
	DECLARE @AssistantUniteId3 INT; 
	DECLARE @AssistantUniteRate3 DECIMAL(24,10);
	DECLARE @ParIsService INT=0;
	DECLARE @BuyDefaultRate1 DECIMAL(24,10) ;
	DECLARE @SaleDefaultRate1 DECIMAL(24,10) ;
	DECLARE @EqualEntrycode VARCHAR(10);--允许条码重复 
	
	SET @EntryCode1 = LTRIM(RTRIM(@EntryCode1))
	SET @EntryCode2 = LTRIM(RTRIM(@EntryCode2))
	SET @EntryCode3 = LTRIM(RTRIM(@EntryCode3))
	SET @BuyDefaultRate = LTRIM(RTRIM(@BuyDefaultRate))
	SET @SaleDefaultRate = LTRIM(RTRIM(@SaleDefaultRate))
	
	DECLARE 
	@d_qty                     VARCHAR(5),  --数量小数位数   1
	@d_price                   VARCHAR(5),  --单价小数位数   2
	@d_total                   VARCHAR(5),  --金额小数位数   3
	@d_discount                VARCHAR(5),  --扣率小数位数   4
	@d_tax                     VARCHAR(5),  --税率小数位数   5
	@d_exchangeRate            VARCHAR(5),  --汇率小数位数   6
	@d_percentage              VARCHAR(5),  --百分比小数位数 7
	@d_translateRate           VARCHAR(5)  --换算率小数位数 8
                          
	SELECT @d_qty              = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 1
	SELECT @d_price            = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 2
	SELECT @d_total            = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 3
	SELECT @d_discount         = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 4
	SELECT @d_tax              = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 5
	SELECT @d_exchangeRate     = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 6
	SELECT @d_percentage       = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 7
	SELECT @d_translateRate    = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 8
	
--DECLARE @ValidDays [varchar](200)= 0
/*
IF ((SELECT DATALENGTH(@PUserCode)) > 200)
BEGIN
	SET @ErrMsg = '父类编号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@PFullName)) > 200)
BEGIN
	SET @ErrMsg = '父类名称的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@UserCode)) > 200)
BEGIN
	SET @ErrMsg = '商品编号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@FullName)) > 200)
BEGIN
	SET @ErrMsg = '商品全名的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Name)) > 200)
BEGIN
	SET @ErrMsg = '商品简称的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Pycode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@EntryCode)) > 200)
BEGIN
	SET @ErrMsg = '条码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Standard)) > 200)
BEGIN
	SET @ErrMsg = '规格的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Type)) > 200)
BEGIN
	SET @ErrMsg = '型号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Area)) > 200)
BEGIN
	SET @ErrMsg = '产地的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 250)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度250'
	RETURN -1
END
*/
--临时只支持基本单位
DECLARE @isdoubleunit INT =0
SELECT @isdoubleunit=Value FROM dbo.Userconfig WHERE ConfigName = 'doubleunit'
IF @isdoubleunit<>1 OR @IsCombinationProduct='启用'
BEGIN 
IF (@SaleUniteCode<>@BaseUniteCode OR
    @BuyUniteCode<>@BaseUniteCode 
    )
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
IF (@StockUniteCode<>'' AND @StockUniteCode<>@BaseUniteCode)
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
IF (@AssistantUniteCode<>'' AND @AssistantUniteCode<>@BaseUniteCode)
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
IF (@ExtUniteCode1<>'' AND @ExtUniteCode1<>@BaseUniteCode)
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
IF (@ExtUniteCode2<>'' AND @ExtUniteCode2<>@BaseUniteCode)
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
IF (@ExtUniteCode3<>'' AND @ExtUniteCode3<>@BaseUniteCode)
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
IF (@AssistantUniteCode1<>'' AND @AssistantUniteCode1<>@BaseUniteCode)
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
IF (@AssistantUniteCode2<>'' AND @AssistantUniteCode2<>@BaseUniteCode)
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
IF (@AssistantUniteCode3<>'' AND @AssistantUniteCode3<>@BaseUniteCode)
    BEGIN 
        SET @ErrMsg='所有单位均要与基本单位一致' 
        RETURN -1
    END 
END



--辅助单位不能相同
IF (@AssistantUniteCode1 <> '' AND @AssistantUniteCode2 <> '' AND  @AssistantUniteCode1 = @AssistantUniteCode2 )
	OR (@AssistantUniteCode1 <> '' AND @AssistantUniteCode3 <> '' AND  @AssistantUniteCode1 = @AssistantUniteCode3)
	OR (@AssistantUniteCode2 <> '' AND @AssistantUniteCode3 <> '' AND @AssistantUniteCode2 = @AssistantUniteCode3)
BEGIN
	SET @ErrMsg='辅助单位不能相同' 
    RETURN -1
END



DECLARE @Parid VARCHAR(50)
IF ((@PFullName = '' AND @PUserCode = '' )
     OR (@PFullName = '全部商品' AND @PUserCode = '0') ) 
    BEGIN
        SET @Parid = '00000'
        SET @ParIsService = 1
    END
ELSE
BEGIN
IF NOT EXISTS (SELECT  typeId FROM  dbo.ptype WHERE  UserCode = @PUserCode ) 
BEGIN
    SET @ErrMsg = '父类编号不存在'
    RETURN -1
END
ELSE 
BEGIN
	IF ISNULL(@PFullName,'')<>''
	BEGIN
		IF NOT EXISTS ( SELECT  typeId FROM    dbo.ptype WHERE   FullName = @PFullName ) 
			BEGIN
				--SET @ErrMsg = '父类名称不存在'
				--RETURN -1
				SET @ErrMsg ='' --991版本 屏蔽此判断
			END
		ELSE
		BEGIN
			IF (@PFullName <> (SELECT TOP 1 fullname FROM   dbo.ptype WHERE  UserCode = @PUserCode) ) 
			BEGIN
				--SET @ErrMsg = '父类编号与父类名称不匹配'
				--RETURN -1
				SET @ErrMsg ='' --991版本 屏蔽此判断
				SELECT TOP 1
				@Parid = typeid,
				@ParIsService = IsService
				FROM     dbo.ptype
				WHERE    UserCode = @PUserCode
			END
			ELSE IF EXISTS(SELECT 1 FROM PType WHERE UserCode=@PUserCode AND iscombinationproduct=1)
			BEGIN
				--SET @ErrMsg='父类不能选择组合品'
				--RETURN -1
				 SET @ErrMsg ='' --991版本 屏蔽此判断
				 
				 SELECT TOP 1
					@Parid = typeid,
					@ParIsService = IsService
					FROM     dbo.ptype
					WHERE    UserCode = @PUserCode
			END
			ELSE 
			BEGIN
				SELECT TOP 1
				@Parid = typeid,
				@ParIsService = IsService
				FROM     dbo.ptype
				WHERE    UserCode = @PUserCode
			END
		END
    END
    ELSE
    BEGIN
		IF ISNULL(@PUserCode,'')<>''
		BEGIN
			IF NOT EXISTS ( SELECT  typeId FROM   dbo.ptype WHERE  usercode = @PUserCode ) 
			BEGIN
				 SET @ErrMsg = '父类编号不存在'
				 RETURN -1
			END
			ELSE
				SELECT TOP 1
				@Parid = typeid,
				@ParIsService = IsService
				FROM     dbo.ptype
				WHERE    UserCode = @PUserCode
		END
    
    END
END
END

    DECLARE @tempdeleted BIT
    DECLARE @parStopBuy INT
    SELECT TOP 1
            @tempdeleted = deleted ,
            @parStopBuy = stopbuy
    FROM    dbo.ptype
    WHERE   UserCode = @PUserCode
    IF ( @tempdeleted = 1 ) 
        BEGIN
            SET @ErrMsg = '父类商品已停用'
            RETURN -1
        END
    IF ( @parStopBuy = 1 ) 
        BEGIN
            SET @ErrMsg = '父类商品已停止采购'
            RETURN -1
        END
/*
    DECLARE @isBtypeAll VARCHAR(50) ,
        @isEqualProName VARCHAR(20)  ---分解统一客户供货商和商品同名
    SET @isBtypeAll = ( SELECT TOP 1
                                A
                        FROM    f_split(@typeid, 'я')
                      )
    SET @isEqualProName = ( SELECT  A
                            FROM    f_split(@typeid, 'я')
                            WHERE   A <> @isBtypeAll
                          )
    IF ( @isEqualProName = 'Enabled' ) 
        BEGIN
            IF EXISTS ( SELECT TOP 1
                                typeid
                        FROM    dbo.ptype
                        WHERE   fullname = @FullName ) 
                BEGIN
                    SET @ErrMsg = '商品名称重复'
                    RETURN -1
                END
        END
*/
IF (CHARINDEX(';',@EntryCode)>0)
BEGIN 
	SET @ErrMsg='请勿在条码中输入特殊字符【;】！';
	RETURN -1;	
END 

-- 如果启用商品同名，则可以同名，否则验证不能同名
IF NOT EXISTS(SELECT * FROM dbo.userconfig WHERE configname='equalproname' AND value='1')
	AND EXISTS(SELECT * FROM dbo.ptype WHERE FullName=@FullName)
BEGIN
	SET @ErrMsg='商品名称重复';
	RETURN -1;
END


    IF ( @UserCode = '' ) 
        BEGIN
            SET @ErrMsg = '商品编号不能为空'
            RETURN -1
        END
    ELSE 
        IF ( ( SELECT   COUNT(*)
               FROM     dbo.ptype
               WHERE    usercode = @UserCode
             ) > 0 ) 
            BEGIN
                SET @ErrMsg = '商品编号已存在'
                RETURN -1
            END

    IF ( @FullName = '' ) 
        BEGIN
            SET @ErrMsg = '商品名称不能为空'
            RETURN -1
        END

    IF ( @Pycode = '' ) 
        BEGIN
            SELECT  @Pycode = dbo.fun_getPY(@FullName)
        END

    IF ( @UsefulLifeDay = '' ) 
        BEGIN
            SET @UsefulLifeDay = 0
        END
    ELSE 
        IF ( ISNUMERIC(@UsefulLifeDay) <> 1 ) 
            BEGIN
                SET @ErrMsg = '有效期请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( ( SELECT   CHARINDEX('.', @UsefulLifeDay)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '有效期请输入整数'
                    RETURN -1
                END
            ELSE 
                IF ( ( SELECT   CHARINDEX('-', @UsefulLifeDay)
                     ) <> 0 ) 
                    BEGIN
                        SET @ErrMsg = '有效期不能为负数'
                        RETURN -1
                    END

    IF ( ( SELECT   CONVERT(INT, @UsefulLifeDay)
         ) > 9999 ) 
        BEGIN
            SET @ErrMsg = '有效期最大值为9999'
            RETURN -1
        END

    DECLARE @BTypeID [varchar](200)
    IF ( @BFullName = '' ) 
        BEGIN
            SET @BTypeID = ''
        END
    ELSE 
        BEGIN
            IF NOT EXISTS ( SELECT TOP 1
                                    typeid
                            FROM    dbo.BType
                            WHERE   fullname = @BFullName )
                OR @BFullName = 'ABC'
                OR @BFullName = '所有客户'
                OR @BFullName = '全部供货商' 
                BEGIN
                    SET @ErrMsg = '供货商不存在'
                    RETURN -1
                END
            ELSE 
                BEGIN
				--验证供应商是否与客户统一情况下
                IF NOT EXISTS(SELECT 1 FROM BTYPE WHERE FullName=@BFullName AND sonnum=0
					AND (typeid LIKE '00002%' 
							AND EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='btypeall' AND value='0') --未统一时只能是供应商
							OR NOT EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='btypeall' AND value='0')
						)
					)
				BEGIN
					SET @ErrMsg='供货商不存在';
					RETURN -1;
				END
                
                
                    DECLARE @PBtypeId VARCHAR(50)
                    DECLARE @BChildCount NUMERIC(18, 0)
                    SET @PBtypeId = ( SELECT TOP 1
                                                typeid
                                      FROM      BType
                                      WHERE     fullname = @BFullName
                                    )
                    SELECT  @BChildCount = COUNT(*)
                    FROM    dbo.BType
                    WHERE   typeid LIKE @PBtypeId + '%'
                            AND typeid <> @PBtypeId
                    IF ( @BChildCount = 0 ) 
                        SET @BTypeID = @PBtypeId
                    ELSE 
                        BEGIN
                            SET @ErrMsg = '该供货商为父类'
                            RETURN -1
                        END	
                END
        END
        
    --IF ( @isBtypeAll = 'False' ) 
    --    BEGIN
    --        DECLARE @tempBtypeid VARCHAR(200)
    --        SET @tempBtypeid = SUBSTRING(@BTypeID, 1, 5)
    --        IF ( @tempBtypeid = '00001' ) 
    --            BEGIN
    --                SET @ErrMsg = '供货商不能为客户'
    --                RETURN -1
    --            END
    --    END
    
    --验证存货类型
    DECLARE @InventoryTypeID INT
    IF (@IFullName='')
    BEGIN
        SET @IFullName='库存商品'
        SET @InventoryTypeID=(SELECT TOP 1 NID FROM dbo.Base_InventoryType WHERE FullName=@IFullName)
    END
    ELSE IF NOT EXISTS(SELECT 1 FROM dbo.Base_InventoryType WHERE FullName=@IFullName)
    BEGIN
        SET @ErrMsg='指定的存货类型不存在'
        RETURN -1
    END
    ELSE
    BEGIN
        SET @InventoryTypeID=(SELECT TOP 1 NID FROM dbo.Base_InventoryType WHERE FullName=@IFullName)
    END
    
    DECLARE @PCategoryID VARCHAR(500)
    IF (@PCategory<>'')
    BEGIN
        IF NOT EXISTS(SELECT 1 FROM dbo.PTypeCategory WHERE UserCode=@PCategory)
        BEGIN
            SET @ErrMsg='指定的商品类别不存在'
            RETURN -1
        END
        ELSE
        BEGIN
        SET @PCategoryID=(SELECT TOP 1 typeid FROM dbo.PTypeCategory WHERE UserCode=@PCategory)
        END
    END
    ELSE
    BEGIN
        SET @PCategoryID=''
    END

--验证新加
-- 1.自由项

    DECLARE @customitemid VARCHAR(20)
    DECLARE @customitemfrom VARCHAR(20)
    DECLARE @customitemrefid VARCHAR(MAX)
	DECLARE @customitemname1 VARCHAR(8000) = @customitemname
    IF @customitemname = '' OR NOT EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='isfreeitem' AND SubValue='1')
        SET @customitemname = NULL;
    ELSE 
    BEGIN
		SELECT TOP 1
				@customitemid = id ,
				@customitemfrom = isCombined ,
				@customitemrefid = referenceidlist
		FROM    ( SELECT    id ,
							fullname ,
							referenceidlist ,
							1 AS isCombined
				  FROM      customPtypeItems
				  UNION ALL
				  SELECT    _Id ,
							Name ,
							'' ,
							0
				  FROM      xw_SelfDataType
				  WHERE     deleted = 0
				) a
		WHERE   fullname = @customitemname1

		IF @customitemid IS NULL 
		BEGIN
			SET @ErrMsg = '自由项【' + @customitemname + '】不存在或已停用';
			RETURN -1;
		END
    END

-- 2.近效期必须小于有效期
    IF @ValidDays=''
        SET @ValidDays = '0';
    IF @UsefulLifeDay =''
        SET @UsefulLifeDay = '0';

    IF ( @ValidDays <> '0'
         OR @UsefulLifeDay <> '0'
       )
        AND CAST(@ValidDays AS INT) >= CAST(@UsefulLifeDay AS INT)
        BEGIN
            SET @ErrMsg = '近效期必须小于有效期';
            RETURN -1;
        END

--9.91版本新增
--判断条件是否互斥
	IF @IsCombinationProduct='启用' AND @IsService='启用'
	BEGIN
		SET @ErrMsg = '不能同时启用组合品与服务商品!';
        RETURN -1;
	END
	
	IF @IfSerial = '启用' AND @IsService='启用'
	BEGIN
		SET @ErrMsg = '不能同时启用序列号与服务商品!';
        RETURN -1;
	END

	IF @IfSerial = '启用' AND @IsCombinationProduct='启用'
	BEGIN
		SET @ErrMsg = '不能同时启用序列号与组合品!';
        RETURN -1;
	END

-- 3 序列号
	IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='mngSerial' AND value='1') --系统配置启用
	BEGIN
		IF @IfSerial IN ('','不启用')
			SET @IfSerial='0'
		ELSE IF @IfSerial = '启用' 
		BEGIN
			IF @SerialCount=''
				SET @SerialCount='0'

			IF CAST(@SerialCount AS INT) > 50 
			BEGIN
				SET @ErrMsg = '序列号长度不能大于50';
				RETURN -1;
			END

			SET @IfSerial='1'
		END
		ELSE 
			BEGIN
				SET @ErrMsg='启用序列号列应该填写【启用】，【不启用】或不填';
				RETURN -1;
			END
	END
	ELSE
		SET @IfSerial='0';
	-- 验证条码
	IF @IfUseEntryCode IN ('','不启用')
	BEGIN
		SET @IfUseEntryCode='0';
		IF @EntryCode <> ''
		BEGIN
			SET @ErrMsg='未启用条码不能填写条码'
			RETURN -1;
		END
	END
	ELSE IF @IfUseEntryCode='启用'
	BEGIN
		SET @IfUseEntryCode='1';
		-- 启用了条码，条码不为空时验证不能重复
		IF @EntryCode='' AND EXISTS(SELECT 1 FROM sysdata WHERE SubName='ifuseentrycodeext' AND SubValue='0') --没有启用条码组合，启用就填；
		BEGIN
			SET @ErrMsg='启用了条码请填写条码列';
			RETURN -1;
		END
		ELSE
			BEGIN 
				IF NOT EXISTS(SELECT * FROM UserConfig WHERE ConfigName = 'equalentrycode' AND value ='1')
				BEGIN
					IF EXISTS (SELECT Ptypeid FROM dbo.PType_EntryCode_Ext WHERE EntryCode=@EntryCode AND @EntryCode<>''
							   UNION ALL
							   SELECT Ptypeid FROM dbo.PType_Units_EntryCode_Ext WHERE EntryCode=@EntryCode AND @EntryCode<>'')
					BEGIN
						SET @ErrMsg='条码重复';
						RETURN -1;
					END
				END
			END 
	END
	ELSE 
	BEGIN
		SET @ErrMsg='启用条码列应该填写【启用】，【不启用】或不填'
		RETURN -1;
	END
	
	IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='ifusegoodsnumber' AND Value='1') --系统配置启用批号才验证
	BEGIN
		IF @IfUseGoodsNum IN ('','不启用')
			SET @IfUseGoodsNum='0';
		ELSE IF @IfUseGoodsNum='启用' 
			SET @IfUseGoodsNum='1';
		ELSE 
		BEGIN
			SET @ErrMsg='启用批号管理列只能填【启用】，【不启用】或不填'
			RETURN -1;
		END
	END
	ELSE
		SET @IfUseGoodsNum='0';
		
	--启用组合品
	IF @IsCombinationProduct='启用' AND NOT EXISTS (SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='combinationproduct' AND SubValue='1')
	BEGIN
		SET @ErrMsg='系统没有启用组合品，不能导入组合品'
		RETURN -1;
	END
	IF @IsCombinationProduct IN ('','不启用')
		SET @IsCombinationProduct='0';
	ELSE IF @IsCombinationProduct='启用' 
		SET @IsCombinationProduct='1';
	ELSE 
	BEGIN
		SET @ErrMsg='启用组合品管理列只能填【启用】，【不启用】或不填'
		RETURN -1;
	END


	--启用服务商品验证
	IF @IsService='启用' AND NOT EXISTS (SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='useserviceproduct' AND SubValue='1')
	BEGIN
		SET @ErrMsg='系统没有启用服务商品，不能导入服务商品'
		RETURN -1;
	END
	IF @IsService IN ('','不启用')
		BEGIN
			IF( @ParIsService = 1 AND @Parid <> '00000')
			BEGIN
				SET @ErrMsg='要导入的商品属性与父类不一致'
				RETURN -1;
			END
			SET @IsService='0';
		END
	ELSE IF @IsService='启用' 
	BEGIN

		IF @IfUseGoodsNum='1'
		BEGIN
			SET @ErrMsg='服务商品，不能启用批号'
			RETURN -1;
		END
		IF @IfSerial = '1'
		BEGIN
			SET @ErrMsg='服务商品，不能启用强制序列号管理'
			RETURN -1;
		END
		IF @customitemname <>''
		BEGIN
			SET @ErrMsg='服务商品，不能启用自由项'
			RETURN -1;
		END
		
		IF @ParIsService = 0
		BEGIN
			SET @ErrMsg='要导入的商品属性与父类不一致'
			RETURN -1;
		END
		
		SET @IsService='1';
	END
	ELSE 
	BEGIN
		SET @ErrMsg='启用服务商品列只能填【启用】，【不启用】或不填'
		RETURN -1;
	END

	-- 采购/销售默认税率值验证：可为空、可为零
	IF( @BuyDefaultRate <> '' AND ISNUMERIC(@BuyDefaultRate) = 1)
	BEGIN
		SET @BuyDefaultRate1 = CONVERT(DECIMAL(24,10),@BuyDefaultRate)
		IF (@BuyDefaultRate1 IS NOT NULL AND(@BuyDefaultRate1 < 0 OR @BuyDefaultRate1 >99))
		BEGIN
			SET @ErrMsg='采购默认税率值只能是大于等于零的数字，可为空，最大值99'
			RETURN -1;
		END
		IF dbo.F_CheckDecimal(@BuyDefaultRate,5,@d_tax) < 0
		BEGIN
			SET @ErrMsg='采购默认税率值多于'+@d_tax+'位小数'
			RETURN -1;
		END
	END
	
	IF( @SaleDefaultRate <> '' AND ISNUMERIC(@SaleDefaultRate) = 1)
	BEGIN
		SET @SaleDefaultRate1 = CONVERT(DECIMAL(24,10),@SaleDefaultRate)
		IF (@SaleDefaultRate1 IS NOT NULL AND(@SaleDefaultRate1 < 0 OR @SaleDefaultRate1 >99))
		BEGIN
			SET @ErrMsg='销售默认税率值只能是大于等于零的数字，可为空，最大值99'
			RETURN -1;
		END
		IF dbo.F_CheckDecimal(@SaleDefaultRate,5,@d_tax) < 0
		BEGIN
			SET @ErrMsg='销售默认税率值多于'+@d_tax+'位小数'
			RETURN -1;
		END
	END
	

	
	--导入单位验证
	SET @BaseUniteCode=LTRIM(RTRIM(@BaseUniteCode));
	IF @BaseUniteCode=''  OR  @BaseUniteCode IS NULL
	BEGIN
		SET @ErrMsg='没有填写基本单位编号';
		RETURN -1;
	END
	IF NOT EXISTS(SELECT 1 FROM ptype_units WHERE UserCode=@BaseUniteCode)
	BEGIN
		SET @ErrMsg='不存在导入的基本单位编号';
		RETURN -1;
	END
	
	DECLARE @doubleunit INT =0
	SELECT @doubleunit=Value FROM dbo.Userconfig WHERE ConfigName = 'doubleunit'
	IF @doubleunit=1
		BEGIN
		SET @SaleUniteCode=LTRIM(RTRIM(@SaleUniteCode));
		IF @SaleUniteCode='' 
		BEGIN
			SET @ErrMsg='没有填写销售默认单位编号';
			RETURN -1;
		END
		IF NOT EXISTS(SELECT 1 FROM ptype_units WHERE UserCode=@SaleUniteCode)
		BEGIN
			SET @ErrMsg='不存在导入的销售默认单位编号';
			RETURN -1;
		END
		ELSE
			SELECT @SaleUniteid=UnitsId FROM dbo.PType_Units WHERE UserCode=@SaleUniteCode
		IF @SaleUniteRate=''
		BEGIN
			SET @ErrMsg='没有填写销售默认单位换算率';
			RETURN -1;
		END
		IF dbo.F_CheckDecimal(@SaleUniteRate,8,@d_translateRate) < 0
		BEGIN
			SET @ErrMsg='销售默认单位换算率值多于'+@d_translateRate+'位小数'
			RETURN -1;
		END
		IF CAST(@SaleUniteRate AS  NUMERIC(24, 10) )<=0
		BEGIN
			SET @ErrMsg='销售默认单位换算率不能小于等于0';
			RETURN -1;
		END
		IF CAST(@SaleUniteRate AS  NUMERIC(24, 10) )<>1 AND @SaleUniteCode=@BaseUniteCode
		BEGIN
			SET @ErrMsg='销售默认单位为基本单位时换算率只能为1';
			RETURN -1;
		END
		
		SET @BuyUniteCode=LTRIM(RTRIM(@BuyUniteCode));
		IF @BuyUniteCode='' 
		BEGIN
			SET @ErrMsg='没有填写采购默认单位编号';
			RETURN -1;
		END
		IF NOT EXISTS(SELECT 1 FROM ptype_units WHERE UserCode=@BuyUniteCode)
		BEGIN
			SET @ErrMsg='不存在导入的采购默认单位编号';
			RETURN -1;
		END
		ELSE
			SELECT @BuyUniteid=UnitsId FROM dbo.PType_Units WHERE UserCode=@BuyUniteCode
		IF @BuyUniteRate=''
		BEGIN
			SET @ErrMsg='没有填写采购默认单位换算率';
			RETURN -1;
		END
		IF dbo.F_CheckDecimal(@BuyUniteRate,8,@d_translateRate) < 0
		BEGIN
			SET @ErrMsg='采购默认单位换算率值多于'+@d_translateRate+'位小数'
			RETURN -1;
		END
		IF CAST(@BuyUniteRate AS  NUMERIC(24, 10) )<=0
		BEGIN
			SET @ErrMsg='采购默认单位换算率不能小于等于0';
			RETURN -1;
		END
		IF CAST(@BuyUniteRate AS  NUMERIC(24, 10) )<>1 AND @BuyUniteCode=@BaseUniteCode
		BEGIN
			SET @ErrMsg='采购默认单位为基本单位时换算率只能为1';
			RETURN -1;
		END
		
		IF CAST(@BuyUniteRate AS  NUMERIC(24, 10) )<>CAST(@SaleUniteRate AS  NUMERIC(24, 10) ) AND @BuyUniteCode=@SaleUniteCode
		BEGIN
			SET @ErrMsg='采购、销售、存货单位一致时换算率必须一致';
			RETURN -1;
		END
			
		SET @StockUniteCode=LTRIM(RTRIM(@StockUniteCode));
		IF @StockUniteCode='' 
		BEGIN
			SET @ErrMsg='没有填写存货默认单位编号';
			RETURN -1;
		END
		IF NOT EXISTS(SELECT 1 FROM ptype_units WHERE UserCode=@StockUniteCode)
		BEGIN
			SET @ErrMsg='不存在导入的存货默认单位编号';
			RETURN -1;
		END
		ELSE
			SELECT @StockUniteid=UnitsId FROM dbo.PType_Units WHERE UserCode=@StockUniteCode
		IF @StockUniteRate=''
		BEGIN
			SET @ErrMsg='没有填写存货默认单位换算率';
			RETURN -1;
		END
		IF dbo.F_CheckDecimal(@StockUniteRate,8,@d_translateRate) < 0
		BEGIN
			SET @ErrMsg='存货默认单位换算率值多于'+@d_translateRate+'位小数'
			RETURN -1;
		END
		IF CAST(@StockUniteRate AS  NUMERIC(24, 10) )<=0
		BEGIN
			SET @ErrMsg='存货默认单位换算率不能小于等于0';
			RETURN -1;
		END
		IF CAST(@StockUniteRate AS  NUMERIC(24, 10) )<>1 AND @StockUniteCode=@BaseUniteCode
		BEGIN
			SET @ErrMsg='存货默认单位为基本单位时换算率只能为1';
			RETURN -1;
		END	
		IF CAST(@StockUniteRate AS  NUMERIC(24, 10) )<>CAST(@SaleUniteRate AS  NUMERIC(24, 10) ) AND @StockUniteCode=@SaleUniteCode
			OR CAST(@StockUniteRate AS  NUMERIC(24, 10) )<>CAST(@BuyUniteRate AS  NUMERIC(24, 10) ) AND @StockUniteCode=@BuyUniteCode
		BEGIN
			SET @ErrMsg='采购、销售、存货单位一致时换算率必须一致';
			RETURN -1;
		END
		
		SET @AssistantUniteCode=LTRIM(RTRIM(@AssistantUniteCode));
		IF @AssistantUniteCode<>'' 
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM ptype_units WHERE UserCode=@AssistantUniteCode)
			BEGIN
				SET @ErrMsg='不存在导入的浮动计量单位编号';
				RETURN -1;
			END
			ELSE
				SELECT @AssistantUniteid=UnitsId FROM dbo.PType_Units WHERE UserCode=@AssistantUniteCode
			IF @AssistantUniteRate=''
			BEGIN
				SET @ErrMsg='没有填写浮动单位换算率';
				RETURN -1;
			END
			IF dbo.F_CheckDecimal(@AssistantUniteRate,8,@d_translateRate) < 0
			BEGIN
				SET @ErrMsg='浮动单位换算率多于'+@d_translateRate+'位小数'
				RETURN -1;
			END
			IF CAST(@AssistantUniteRate AS  NUMERIC(24, 10) )<=0
			BEGIN
				SET @ErrMsg='浮动单位换算率不能小于等于0';
				RETURN -1;
			END
			IF  @AssistantUniteCode=@BaseUniteCode OR @AssistantUniteCode=@SaleUniteCode OR  @AssistantUniteCode=@BuyUniteCode OR @AssistantUniteCode=@StockUniteCode
			BEGIN
				SET @ErrMsg='浮动单位编号不能与其他任何一个单位编号相同';
				RETURN -1;
			END
		END
		
		IF @ExtUniteCode1<>''
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM ptype_units WHERE UserCode=@ExtUniteCode1)
			BEGIN
				SET @ErrMsg='不存在导入的计量单位一编号';
				RETURN -1;
			END
			ELSE
				SELECT @ExtUniteid1=UnitsId FROM dbo.PType_Units WHERE UserCode=@ExtUniteCode1
			IF @ExtUniteRate1=''
			BEGIN
				SET @ErrMsg='没有填写计量单位一换算率';
				RETURN -1;
			END
			IF dbo.F_CheckDecimal(@ExtUniteRate1,8,@d_translateRate) < 0
			BEGIN
				SET @ErrMsg='计量单位一换算率多于'+@d_translateRate+'位小数'
				RETURN -1;
			END
			IF CAST(@ExtUniteRate1 AS  NUMERIC(24, 10) )<=0
			BEGIN
				SET @ErrMsg='计量单位一换算率不能小于等于0';
				RETURN -1;
			END
			/*
			IF  @ExtUniteCode1 IN (@BaseUniteCode,@SaleUniteCode,@BuyUniteCode,@StockUniteCode,@AssistantUniteCode)
			BEGIN
				SET @ErrMsg='单位一、二、三编号不能相同，且不能与基本、销售、采购、存货、浮动中任意一个编号相同';
				RETURN -1;
			END
			*/
		END
		
		IF @ExtUniteCode2<>''
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM ptype_units WHERE UserCode=@ExtUniteCode2)
			BEGIN
				SET @ErrMsg='不存在导入的计量单位二编号';
				RETURN -1;
			END
			ELSE
				SELECT @ExtUniteid2=UnitsId FROM dbo.PType_Units WHERE UserCode=@ExtUniteCode2
			IF @ExtUniteRate2=''
			BEGIN
				SET @ErrMsg='没有填写计量单位二换算率';
				RETURN -1;
			END
			IF dbo.F_CheckDecimal(@ExtUniteRate2,8,@d_translateRate) < 0
			BEGIN
				SET @ErrMsg='计量单位二换算率多于'+@d_translateRate+'位小数'
				RETURN -1;
			END
			IF CAST(@ExtUniteRate2 AS  NUMERIC(24, 10) )<=0
			BEGIN
				SET @ErrMsg='计量单位二换算率不能小于等于0';
				RETURN -1;
			END
			/*
			IF  @ExtUniteCode2 IN (@BaseUniteCode,@SaleUniteCode,@BuyUniteCode,@StockUniteCode,@AssistantUniteCode,@ExtUniteCode1)
			BEGIN
				SET @ErrMsg='单位一、二、三编号不能相同，且不能与基本、销售、采购、存货、浮动中任意一个编号相同';
				RETURN -1;
			END
			*/
		END
		
		IF @ExtUniteCode3<>''
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM ptype_units WHERE UserCode=@ExtUniteCode3)
			BEGIN
				SET @ErrMsg='不存在导入的计量单位三编号';
				RETURN -1;
			END
			ELSE
				SELECT @ExtUniteid3=UnitsId FROM dbo.PType_Units WHERE UserCode=@ExtUniteCode3
			IF @ExtUniteRate3=''
			BEGIN
				SET @ErrMsg='没有填写计量单位三换算率';
				RETURN -1;
			END
			IF dbo.F_CheckDecimal(@ExtUniteRate3,8,@d_translateRate) < 0
			BEGIN
				SET @ErrMsg='计量单位三换算率多于'+@d_translateRate+'位小数'
				RETURN -1;
			END
			IF CAST(@ExtUniteRate3 AS  NUMERIC(24, 10) )<=0
			BEGIN
				SET @ErrMsg='计量单位三换算率不能小于等于0';
				RETURN -1;
			END
			/*
			IF  @ExtUniteCode3 IN (@BaseUniteCode,@SaleUniteCode,@BuyUniteCode,@StockUniteCode,@AssistantUniteCode,@ExtUniteCode1,@ExtUniteCode2)
			BEGIN
				SET @ErrMsg='单位一、二、三编号不能相同，且不能与基本、销售、采购、存货、浮动中任意一个编号相同';
				RETURN -1;
			END
			*/
		END
		
		IF EXISTS ( 
			SELECT t.c  FROM (
			          SELECT LTRIM(RTRIM(@ExtUniteCode1)) AS 'c'
			UNION ALL SELECT LTRIM(RTRIM(@ExtUniteCode2)) AS 'c'
			UNION ALL SELECT LTRIM(RTRIM(@ExtUniteCode3)) AS 'c' ) AS t
			WHERE t.c <> ''
			GROUP BY t.c
			having COUNT(1) > 1 )
		BEGIN
			SET @ErrMsg='计量单位一、二、三编号不能相同';
			RETURN -1;
		END

		IF @BaseUniteCode = @ExtUniteCode1 AND CAST(@ExtUniteRate1 AS  NUMERIC(24, 10) )  <> 1
		BEGIN
			
			SET @ErrMsg='计量单位一为基本单位时换算率只能为1';
			RETURN -1;
		END
		IF @BaseUniteCode = @ExtUniteCode2 AND CAST(@ExtUniteRate2 AS  NUMERIC(24, 10) )  <> 1
		BEGIN
			
			SET @ErrMsg='计量单位二为基本单位时换算率只能为1';
			RETURN -1;
		END
		IF @BaseUniteCode = @ExtUniteCode3 AND CAST(@ExtUniteRate3 AS  NUMERIC(24, 10) )  <> 1
		BEGIN
			
			SET @ErrMsg='计量单位三为基本单位时换算率只能为1';
			RETURN -1;
		END
		
		--验证计量单位一条码、计量单位二条码、计量单位三条码
		IF @IfUseEntryCode = 1 
		BEGIN
			IF @EntryCode <> '' AND @EntryCode IN (@EntryCode1,@EntryCode2,@EntryCode3)
			BEGIN
				SET @ErrMsg='商品条码不能计量单位一、二、三条码相同';
				RETURN -1;
			END
			
			IF EXISTS ( SELECT t.c  FROM (
						          SELECT @EntryCode1 AS 'c'
						UNION ALL SELECT @EntryCode2 AS 'c'
						UNION ALL SELECT @EntryCode3 AS 'c' ) AS t
						WHERE t.c<>''
						GROUP BY t.c
						having COUNT(1) > 1 )
			BEGIN
				SET @ErrMsg='计量单位一、二、三条码不能相同';
				RETURN -1;
			END
			/*
			IF @EntryCode1 <> '' AND (@EntryCode1 = @EntryCode2 OR @EntryCode1 = @EntryCode3)
			BEGIN
				SET @ErrMsg='计量单位一、二、三条码不能相同';
				RETURN -1;
			END
			IF @EntryCode2 <> '' AND @EntryCode2 = @EntryCode3
			BEGIN
				SET @ErrMsg='计量单位一、二、三条码不能相同';
				RETURN -1;
			END
			*/
			SELECT @EqualEntrycode = Value FROM dbo.Userconfig WHERE ConfigName='equalentrycode';
			IF @EqualEntrycode = '0'
			BEGIN
				IF 0 < ( SELECT COUNT(1) FROM dbo.PType_EntryCode_Ext WHERE EntryCode <> '' AND EntryCode IN (@EntryCode1 , @EntryCode2 ,@EntryCode3))
				OR 0 < ( SELECT COUNT(1) FROM dbo.PType_Units_EntryCode_Ext           WHERE EntryCode <> '' AND EntryCode IN (@EntryCode1 , @EntryCode2 ,@EntryCode3))
				BEGIN
					SET @ErrMsg='计量单位一、二、三条码不能相同，且不能与系统任意一个条码相同';
					RETURN -1;
				END
			END
		END
		ELSE
		BEGIN
			IF(@EntryCode1 <> '' OR @EntryCode2  <> '' OR @EntryCode3  <> '' )
			BEGIN
				SET @ErrMsg='因模板中【条码、计量单位一/二/三条码】列有值，而未启用条码';
				RETURN -1;
			END
			
			SET @EntryCode1 = ''
			SET @EntryCode2 = ''
			SET @EntryCode3 = ''
		END
		--验证计量单位一条码、计量单位二条码、计量单位三条码
		
	END
	
	IF @AssistantUniteCode1<>'' AND @AssistantUniteCode1 NOT IN (@BaseUniteCode,@SaleUniteCode,@BuyUniteCode,@StockUniteCode,@ExtUniteCode1,@ExtUniteCode2,@ExtUniteCode3)
		OR @AssistantUniteCode2<>'' AND @AssistantUniteCode3 NOT IN (@BaseUniteCode,@SaleUniteCode,@BuyUniteCode,@StockUniteCode,@ExtUniteCode1,@ExtUniteCode2,@ExtUniteCode3)
		OR @AssistantUniteCode3<>'' AND @AssistantUniteCode2 NOT IN (@BaseUniteCode,@SaleUniteCode,@BuyUniteCode,@StockUniteCode,@ExtUniteCode1,@ExtUniteCode2,@ExtUniteCode3)
	BEGIN
		SET @ErrMsg='辅助单位一、二、三编号必须是除浮动以外所有计量单位中的计量单位编号'
		RETURN -1
	END
-------------------------单位验证完成--------------------------------	

    IF ( @integral = '' ) 
        SET @integral = 0
    ELSE 
        IF ( ISNUMERIC(@integral) <> 1 ) 
            BEGIN
                SET @ErrMsg = '兑换积分请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @integral) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '兑换积分不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @integral = ( SELECT    ROUND(@integral, 2)
                                )


    DECLARE @PreBuyPrice1  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice1 = '' ) 
        SET @PreBuyPrice1 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice1) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价1请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice1) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价1不能为负数'
                    RETURN -1
                END
            ELSE 
                SELECT  @PreBuyPrice1 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice1)
	
	IF @PreBuyPrice1 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreBuyPrice1,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设进价1值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END

    DECLARE @PreBuyPrice2  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice2 = '' ) 
        SET @PreBuyPrice2 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice2) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价2请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice2) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价2不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreBuyPrice2 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice2)

	IF @PreBuyPrice2 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreBuyPrice2,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设进价2值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreBuyPrice3  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice3 = '' ) 
        SET @PreBuyPrice3 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice3) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价3请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice3) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价3不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreBuyPrice3 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice3)

	IF @PreBuyPrice3 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreBuyPrice3,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设进价3值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreBuyPrice4  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice4 = '' ) 
        SET @PreBuyPrice4 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice4) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价4请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice4) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价4不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreBuyPrice4 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice4)
	
	IF @PreBuyPrice4 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreBuyPrice4,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设进价4值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreBuyPrice5  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice5 = '' ) 
        SET @PreBuyPrice5 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice5) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价5请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice5) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价5不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreBuyPrice5 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice5)

	IF @PreBuyPrice5 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreBuyPrice5,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设进价5值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @TopBuyPrice  NUMERIC(24, 10) 
    IF ( @StrTopBuyPrice = '' ) 
        SET @TopBuyPrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrTopBuyPrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最高进价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrTopBuyPrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最高进价不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @TopBuyPrice = CONVERT( NUMERIC(24, 10) , @StrTopBuyPrice)

	IF @TopBuyPrice <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrTopBuyPrice,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='最高进价值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice1  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice1 = '' ) 
        SET @PreSalePrice1 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice1) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价1请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice1) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价1不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice1 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice1)
	
	IF @PreSalePrice1 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice1,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价1值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice2  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice2 = '' ) 
        SET @PreSalePrice2 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice2) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价2请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice2) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价2不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice2 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice2)

	IF @PreSalePrice2 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice2,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价2值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice3  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice3 = '' ) 
        SET @PreSalePrice3 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice3) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价3请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice3) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价3不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice3 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice3)

	IF @PreSalePrice3 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice3,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价3值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice4  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice4 = '' ) 
        SET @PreSalePrice4 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice4) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价4请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice4) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价4不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice4 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice4)

	IF @PreSalePrice4 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice4,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价4值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice5  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice5 = '' ) 
        SET @PreSalePrice5 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice5) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价5请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice5) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价5不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice5 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice5)

	IF @PreSalePrice5 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice5,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价5值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice6  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice6 = '' ) 
        SET @PreSalePrice6 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice6) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价6请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice6) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价6不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice6 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice6)

	IF @PreSalePrice6 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice6,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价6值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice7  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice7 = '' ) 
        SET @PreSalePrice7 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice7) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价7请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice7) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价7不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice7 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice7)

	IF @PreSalePrice7 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice7,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价7值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice8  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice8 = '' ) 
        SET @PreSalePrice8 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice8) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价8请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( ( SELECT   CHARINDEX('-', @StrPreSalePrice8)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价8不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice8 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice8)

	IF @PreSalePrice8 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice8,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价8值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice9  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice9 = '' ) 
        SET @PreSalePrice9 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice9) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价9请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice9) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价9不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice9 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice9)

	IF @PreSalePrice9 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice9,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价9值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @PreSalePrice10  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice10 = '' ) 
        SET @PreSalePrice10 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice10) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价10请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice10) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价10不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @PreSalePrice10 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice10)

	IF @PreSalePrice10 <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrPreSalePrice10,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='预设售价10值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @RetailPrice  NUMERIC(24, 10) 
    IF ( @StrRetailPrice = '' ) 
        SET @RetailPrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrRetailPrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '零售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrRetailPrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '零售价不能为负数'
                    RETURN -1
                END
            ELSE 
                SET @RetailPrice = CONVERT( NUMERIC(24, 10) , @StrRetailPrice)

	IF @RetailPrice <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrRetailPrice,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='零售价值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @TopSalePrice  NUMERIC(24, 10) 
    IF ( @StrTopSalePrice = '' ) 
        SET @TopSalePrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrTopSalePrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最高售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrTopSalePrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最高售价不能为负数'
                    RETURN -1
                END
            ELSE 
                SELECT  @TopSalePrice = CONVERT( NUMERIC(24, 10) , @StrTopSalePrice)

	IF @TopSalePrice <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrTopSalePrice,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='最高售价值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    DECLARE @LowSalePrice  NUMERIC(24, 10) 
    IF ( @StrLowSalePrice = '' ) 
        SET @LowSalePrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrLowSalePrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最低售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrLowSalePrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最低售价不能为负数'
                    RETURN -1
                END
            ELSE 
                SELECT  @LowSalePrice = CONVERT( NUMERIC(24, 10) , @StrLowSalePrice)
	
	IF @LowSalePrice <> 0
	BEGIN
		IF dbo.F_CheckDecimal(@StrLowSalePrice,2,@d_price) < 0
		BEGIN
			SET @ErrMsg='最低售价值多于'+@d_price+'位小数'
			RETURN -1;
		END
	END
	
    IF ( @FcPrice = '' ) 
        BEGIN
            SET @FcPrice = 0
        END
    ELSE 
        IF ( ISNUMERIC(@FcPrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrLowSalePrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '不能为负数'
                    RETURN -1
                END
----------------------------------------------------------------------------------------------
    	
    DECLARE @nReturntype INT ,
        @EtypeId_1 [varchar](50) ,
        @nSoncount INT ,
        @nSonnum INT ,
        @leveal SMALLINT
    DECLARE @parFullName VARCHAR(200)
    SET @parFullName = ( SELECT TOP 1
                                fullname
                         FROM   Ptype
                         WHERE  typeid = @parid
                       )
    IF ( @ParId <> '00000' ) 
        BEGIN
--判断停用不能分类
            IF EXISTS ( SELECT  1
                        FROM    ptype
                        WHERE   typeId = @Parid
                                AND deleted = 1 ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已经被停用，不能分类'
                    RETURN -1	
                END
-- 判断库存量（每个仓库）是否为零
            IF EXISTS ( SELECT  ptypeid
                        FROM    goodsstocks
                        WHERE   ptypeid = @ParId
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
                    RETURN -1	
                END 
            IF EXISTS ( SELECT  ptypeid
                        FROM    inigoodsstocks
                        WHERE   ptypeid = @ParId
                                AND ( Qty <> 0
                                      OR Total <> 0
                                    ) ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
                    RETURN -1	
                END 

            IF EXISTS ( SELECT  ptypeid
                        FROM    wx_goodsstocks
                        WHERE   ptypeid = @ParId
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
                    RETURN -1	
                END 
            IF EXISTS ( SELECT  ptypeid
                        FROM    wx_inigoodsstocks
                        WHERE   ptypeid = @ParId
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
                    RETURN -1	
                END 

-- 判断借欠余额
            IF EXISTS ( SELECT  pTypeID
                        FROM    V_LendStatus
                        WHERE   pTypeID = @ParId
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有借进借出，不能分类'
                    RETURN -1	
                END 
-- 判断经营
            IF EXISTS ( SELECT  pTypeID
                        FROM    InOutStockTable
                        WHERE   pTypeID = @ParId
                                AND Qty <> 0 )
                OR EXISTS ( SELECT  pTypeID
                            FROM    LendBill
                            WHERE   pTypeID = @ParId
                                    AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
                    RETURN -1	
                END 

            IF EXISTS ( SELECT  pTypeID
                        FROM    QP_InsuranceBill_PType
                        WHERE   pTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
                    RETURN -1	
                END
	
            IF EXISTS ( SELECT  pTypeID
                        FROM    Billindex
                        WHERE   pTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
                    RETURN -1	
                END
            IF EXISTS ( SELECT  pTypeID
                        FROM    OrderBill
                        WHERE   pTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已在订单中使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PtypeId
                        FROM    PromotePrice
                        WHERE   PtypeId = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已在促销中使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PtypeId
                        FROM    PriceTrack
                        WHERE   PtypeId = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已在价格跟踪中使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  pTypeID
                        FROM    RepairEngage
                        WHERE   pTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已在维修中使用，不能分类'
                    RETURN -1
                END
-- 判断代销
            IF EXISTS ( SELECT  pTypeID
                        FROM    iniCommissionStock
                        WHERE   pTypeID = @ParId
                                AND Qty <> 0 )
                OR EXISTS ( SELECT  pTypeID
                            FROM    CommissionStock
                            WHERE   pTypeID = @ParId
                                    AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有代销情况，不能分类'
                    RETURN -1
                END 
            IF EXISTS ( SELECT  pTypeID
                        FROM    iniCommissionStock
                        WHERE   pTypeID = @ParId
                                AND total <> 0 )
                OR EXISTS ( SELECT  pTypeID
                            FROM    CommissionStock
                            WHERE   pTypeID = @ParId
                                    AND total <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有代销情况，不能分类'
                    RETURN -1
                END 
            IF NOT EXISTS ( SELECT  typeid
                            FROM    dbo.btype
                            WHERE   typeid = @BTypeID
                                    AND deleted = 0 )
                AND @BTypeID <> '' 
                BEGIN
                    SET @ErrMsg = '供应商已被删除或停用'
                    RETURN -1
                END

-- 判断序列号
            IF EXISTS ( SELECT  PTypeID
                        FROM    gp_CruPtypeSerial
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有序列号关联情况，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    gp_initPtypeSerial
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有期初序列号关联情况，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    PuserCode
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】设置了多编码，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    gp_LendPtypeserial
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有借欠序列号，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    produceModel
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有生产模板，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    produceModelIndex
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有生产模板，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    stockcheck
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】有盘点单，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    dbo.QP_RecycleBill
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    QP_QuickRepairBill_PType
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    QP_EvaluationBill_PType
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    dbo.[QP_EvaluationBill_PType]
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    QP_QuickRepairBill_PType
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    IntegralExchangeBill
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    QuotePriceBill
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  PTypeID
                        FROM    AskPriceBill
                        WHERE   PTypeID = @ParId ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
                    RETURN -1
                END

	--判断在分支机构物价信息中使用
            IF EXISTS ( SELECT  *
                        FROM    PType_STypePrice
                        WHERE   PTypeID = @ParId
                                AND ( PreBuyPrice1 <> 0
                                      OR PreBuyPrice2 <> 0
                                      OR PreBuyPrice3 <> 0
                                      OR PreBuyPrice4 <> 0
                                      OR PreBuyPrice5 <> 0
                                      OR PreSalePrice1 <> 0
                                      OR PreSalePrice2 <> 0
                                      OR PreSalePrice3 <> 0
                                      OR PreSalePrice4 <> 0
                                      OR PreSalePrice5 <> 0
                                      OR PreSalePrice6 <> 0
                                      OR PreSalePrice7 <> 0
                                      OR PreSalePrice8 <> 0
                                      OR PreSalePrice9 <> 0
                                      OR PreSalePrice10 <> 0
                                      OR RetailPrice <> 0
                                      OR TopSalePrice <> 0
                                      OR LowSalePrice <> 0
                                      OR RecPrice <> 0
                                    ) ) 
                BEGIN
                    SET @ErrMsg = '该商品【' + @parFullName + '】在分支机构物价信息中使用，不能分类'
                    RETURN -1
                END
	--商品信息被单据关联禁止分类
            DECLARE @TableName VARCHAR(128)
            DECLARE @sql NVARCHAR(1500)
            DECLARE @break INT=0;
            DECLARE Ptype_cursor CURSOR
            FOR
                SELECT  o.[name] AS tablename
                FROM    syscolumns c
                        INNER JOIN sysobjects o ON ( c.[id] = o.[id] )
                WHERE   c.[name] = 'ptypeid'
                        AND o.type = 'u'
                        AND o.[name] NOT IN ( 'PType_STypePrice',
                                              'PType_Picture',
                                              'ptype_PicStream',
                                              'DefaultStock') FOR READ ONLY
            OPEN Ptype_cursor
            FETCH NEXT FROM Ptype_cursor INTO @TableName
            WHILE @@fetch_status = 0 
                BEGIN
                    DECLARE @intBeUsed INT
                    SET @sql = 'IF EXISTS(SELECT * from  ' + @TableName
                        + ' where ptypeid=''' + @Parid
                        + ''') SELECT @intBeUsed = 1 ELSE SELECT @intBeUsed = 0 '
                    EXECUTE sp_executesql @sql, N'@intBeUsed INT OUTPUT',
                        @intBeUsed OUTPUT

                    IF ( @intBeUsed > 0
                         AND @TableName NOT IN ( 'PType_Price', 'QP_PType_Ext','PType_Units_Ext', --添加新表，这个表也要排除
                                                 'TCBill','PType_AuxiliaryUnits_Ext','PType_InventoryType','PType_Units_EntryCode_Ext','PType_EntryCode_Ext' )
                       )
                    BEGIN
                        SET @break=1;
                        BREAK;
                    END
                    FETCH NEXT FROM Ptype_cursor INTO @TableName
                END
             
            CLOSE Ptype_cursor
            DEALLOCATE Ptype_cursor
            IF @break=1
			BEGIN
				 SET @ErrMsg = '该商品已经使用过不允许分类'
				 RETURN -1;
			END
        END

    IF EXISTS ( SELECT  PTypeID
                FROM    QP_RepairSetMeal_Fittings
                WHERE   PTypeID = @ParId ) 
        BEGIN
            RETURN -36
        END
-- 获得新的ID号
    EXEC @nReturntype= Gp_createId @ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
    IF @nReturntype = -1 
        BEGIN
            SET @ErrMsg = '商品的分类不能超过10层'
            RETURN -1
        END
    IF @nReturntype = -2 
        BEGIN
            SET @ErrMsg = '无法添加基本信息,请检查填写是否有误!'
            RETURN -1
        END
-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted <> 1
                           ) ) 
        BEGIN
            SET @ErrMsg = '该【' + @FullName + '】已经存在，职员编号或名称不能相同'
            RETURN -1
        END
-- 判断已停用的重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted = 1
                           ) ) 
        BEGIN
            SET @ErrMsg = '该【' + @FullName
                + '】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称'
            RETURN -1
        END
        

  
    	--验证商品自定义开始 
	CREATE TABLE #Custom(
		EditKind			VARCHAR(50) ,				--数据类型
		label				VARCHAR(50),				--属性名称
		datafield			VARCHAR(50),				-- 数据库对应字段
		maxbytelength		int     --长度
	)

	IF ( 0 < (SELECT COUNT(1) FROM @tb))
	BEGIN
		INSERT INTO #Custom (EditKind,label,datafield,maxbytelength) SELECT EditKind,label,datafield,maxbytelength FROM @tb
	END
	IF( 0 < (SELECT COUNT(1) FROM CustomBaseInforColumnsDefines WHERE BaseType='ptype'))
	BEGIN
		IF  @costom1 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列1'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='自定义列1类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom1) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom1'))
			BEGIN
				SET @ErrMsg ='自定义列1超出最大值'
				RETURN -1 
			END
		END

		IF  @costom2 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列2'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='自定义列2类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom2) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom2'))
			BEGIN
				SET @ErrMsg ='自定义列2超出最大值'
				RETURN -1 
			END
		END

		IF  @costom3 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列3'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='自定义列3类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom3) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom3'))
			BEGIN
				SET @ErrMsg ='自定义列3超出最大值'
				RETURN -1 
			END
		END

		IF  @costom4 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列4'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='自定义列4类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom4) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom4'))
			BEGIN
				SET @ErrMsg ='自定义列4超出最大值'
				RETURN -1 
			END
		END

		IF  @costom5 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列5'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='自定义列5类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom5) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom5'))
			BEGIN
				SET @ErrMsg ='自定义列5超出最大值'
				RETURN -1 
			END
		END

		IF  @costom6 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列6'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='自定义列6类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom6) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom6'))
			BEGIN
				SET @ErrMsg ='自定义列6超出最大值'
				RETURN -1 
			END
		END

		IF  @costom7 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列7'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='自定义列7类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom7) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom7'))
			BEGIN
				SET @ErrMsg ='自定义列7超出最大值'
				RETURN -1 
			END
		END

		IF  @costom8 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列8'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='自定义列8类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom8) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom8'))
			BEGIN
				SET @ErrMsg ='自定义列8超出最大值'
				RETURN -1 
			END
		END

		IF  @costom9 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列9'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='自定义列9类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom9) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom9'))
			BEGIN
				SET @ErrMsg ='自定义列9超出最大值'
				RETURN -1 
			END
		END

		IF  @costom10 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列10'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='自定义列10类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom10) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom10'))
			BEGIN
				SET @ErrMsg ='自定义列10超出最大值'
				RETURN -1 
			END
		END

		IF  @costom11 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列11'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='自定义列11类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom11) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom11'))
			BEGIN
				SET @ErrMsg ='自定义列11超出最大值'
				RETURN -1 
			END
		END

		IF  @costom12 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列12'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='自定义列12类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom12) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom12'))
			BEGIN
				SET @ErrMsg ='自定义列12超出最大值'
				RETURN -1 
			END
		END

		IF  @costom13 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列13'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='自定义列13类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom13) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom13'))
			BEGIN
				SET @ErrMsg ='自定义列13超出最大值'
				RETURN -1 
			END
		END

		IF  @costom14 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列14'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='自定义列14类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom14) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom14'))
			BEGIN
				SET @ErrMsg ='自定义列14超出最大值'
				RETURN -1 
			END
		END

		IF  @costom15 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列15'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='自定义列15类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom15) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom15'))
			BEGIN
				SET @ErrMsg ='自定义列15超出最大值'
				RETURN -1 
			END
		END

		IF  @costom16 <> '' 
			BEGIN 
			IF(NOT EXISTS (SELECT datafield FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='找不到对应的自定义列16'
				RETURN -1
			END
			IF( '0' <> (SELECT EditKind FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='自定义列16类型不符，请修改为文本类型'
				RETURN -1 
			END
			IF( DATALENGTH(@costom16) > (SELECT maxbytelength FROM #Custom WHERE datafield='costom16'))
			BEGIN
				SET @ErrMsg ='自定义列16超出最大值'
				RETURN -1 
			END
		END
	END
	ELSE
	BEGIN
		IF (@costom1 <> ''   OR @costom2 <> ''   OR @costom3 <> ''   OR @costom4 <> ''   OR @costom5 <> ''   OR @costom6 <> ''   OR @costom7 <> ''   OR @costom8 <> ''   OR @costom9 <> ''   OR @costom10 <> ''   OR @costom11 <> ''   OR @costom12 <> ''   OR @costom13 <> ''   OR @costom14 <> ''   OR @costom15 <> ''   OR @costom16 <> ''  )
		BEGIN
			SET @ErrMsg ='系统未启用商品自定义列'
			RETURN -1
		END
	END
	DROP TABLE #Custom
	--验证商品自定义结束
	

--SortID处理
DECLARE @SortID INT=0
SELECT @SortID = ISNULL( MAX(p.SortID),0)+1
FROM dbo.ptype p
WHERE p.ParId = @Parid
--SortID处理

    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    ptype
    WHERE   typeid = @ParId
    SELECT  @leveal = @leveal + 1


    IF NOT EXISTS ( SELECT  *
                    FROM    AutoType
                    WHERE   fullname = @Type )
        AND LTRIM(RTRIM(@Type)) <> '' 
        BEGIN
            INSERT  dbo.AutoType
                    ( fullname, comment, PYCode )
            VALUES  ( @Type, '', @autotypepycode ) 
        END
	
	--读取多单位配置
    DECLARE @UnitsType INT 
    SELECT  @UnitsType = value
    FROM    userconfig
    WHERE   configname = 'doubleunit'
	
	--定制修改 导入基本单位
	SET @baseUniteId=(SELECT UnitsId FROM ptype_units WHERE UserCode=@BaseUniteCode AND @BaseUniteCode<>'')

	
    INSERT  INTO [ptype]
            ( [typeId] ,
              [Parid] ,
              [leveal] ,
              [soncount] ,
              [sonnum] ,
              [FullName] ,
              [pycode] ,
              [Name] ,
              [UserCode] ,
              [Standard] ,
              [Type] ,
              [Area] ,
              [Unit1] ,
              [Unit2] ,
              [Unitrate1] ,
              [Unitrate2] ,
              [UsefulLifeMonth] ,
              [UsefulLifeDay] ,
              [Comment] ,
              [ColorGroupID] ,     -----肖伟2002-6-5 Add For 服装版
              [SizeGroupID] ,
              [EntryCode] ,
              [DwgNo] ,
              [integral] ,
              IfUseEntryCode ,
              IfUseGoodsNum ,
              customitemid ,
              customitemfrom ,
              customitemname ,
              customitemrefid ,
              ValidDays ,
              IfSerial ,
              SerialCount ,
              deleted ,
              stopbuy ,
              UnitsType ,
              AssistantUnitId ,
              SaleUnitId ,
              BuyUnitId ,
              ProduceUnitId ,
              StockUnitId ,
              JobUnitId ,
              baseUnitId,
              [createdate],
              IsService,
              SortID,
              BuyDefaultRate,
              SaleDefaultRate,
              CanModify,
              PtypeCategoryID,
              iscombinationproduct,
              InventoryTypeID,
              brandartypeid,
              othercomment1,
			  othercomment2,
			  othercomment3,
			  othercomment4,
			  othercomment5
            )      -----肖伟2002-6-5 Add For 服装版
    VALUES  ( @EtypeId_1 ,
              @ParId ,
              @leveal ,
              0 ,
              0 ,
              @fullname ,
              @Pycode ,
              @Name ,
              @UserCode ,
              @Standard ,
              @Type ,
              @Area ,
              '' , --大单位(废除)
              '' , --小单位(废除)
              0 , --单位换算率(废除)
              0 , --单位换算率(废除)
              @UsefulLifeMonth ,
              @UsefulLifeDay ,
              @Comment ,
              @ColorGroupID ,   -----肖伟2002-6-5 Add For 服装版
              @SizeGroupID ,
              CASE WHEN @IfUseEntryCode='1' THEN @EntryCode ELSE '' END ,
              @dwgno ,
              @integral ,
              CAST(@IfUseEntryCode AS BIT) ,
              CAST(@IfUseGoodsNum AS BIT) ,
              @customitemid ,
              @customitemfrom ,
              @customitemname ,
              @customitemrefid ,
              @ValidDays ,
              @IfSerial ,
              CASE WHEN @IfSerial='1' THEN  CAST(@SerialCount AS INT) ELSE '0' END,
              0 ,
              0 ,
              @UnitsType ,
			  CASE @doubleunit WHEN 1 THEN @AssistantUniteId ELSE 0 END,
              CASE @doubleunit WHEN 1 THEN @SaleUniteId ELSE @baseUniteId END,--1 ,
              CASE @doubleunit WHEN 1 THEN @buyUniteId ELSE @baseUniteId END,--1 ,
              1 ,
              CASE @doubleunit WHEN 1 THEN @StockUniteId ELSE @baseUniteId END,--1 ,
              0 ,
              @baseUniteId,
               GETDATE(),--1
               CAST(@IsService AS INT) ,
               @SortID,
               @BuyDefaultRate1,
               @SaleDefaultRate1,
               0,
               @PCategoryID,
               CAST(@IsCombinationProduct AS INT),
               @InventoryTypeID,
               @brandartypeid,
               @othercomment1,
			   @othercomment2,
			   @othercomment3,
			   @othercomment4,
			   @othercomment5
            )    -----肖伟2002-6-5 Add For 服装版
            
	CREATE TABLE #PType_Units_Ext
	(
		UniteCode		VARCHAR(200),
		UnitsId			INT  NULL,
		RateType		INT  NULL, --0代码固定，1浮动
		Rate			VARCHAR(18),
		IsDefaultUnit	INT NOT NULL DEFAULT(0),  --代表默认单位
		EntryCode VARCHAR(200)
	) 
	CREATE TABLE #PType_Units_Ext1
	(
		PtypeID			VARCHAR(50) NOT NULL DEFAULT(''),
		UnitsId			INT NOT NULL,
		RateType		INT NOT NULL, --0代码固定，1浮动
		Rate			 NUMERIC(24, 10) ,
		EntryCode		VARCHAR(200),
		IsDefaultUnit	INT NOT NULL DEFAULT(0),  --代表默认单位
		IsUse			INT NULL DEFAULT(1),	  --是否启用(0否1是)
	) 

	INSERT INTO #PType_Units_Ext
	VALUES	(@BaseUniteCode,@baseUniteid,0,'1.00',1,'')
			
	IF @doubleunit=1
    	INSERT INTO #PType_Units_Ext
		VALUES	(@AssistantUniteCode,@AssistantUniteid,1,@AssistantUniteRate,0,''),
				(@SaleUniteCode,@SaleUniteid,0,@SaleUniteRate,0,''),
				(@BuyUniteCode,@BuyUniteid,0,@BuyUniteRate,0,''),
				(@StockUniteCode,@StockUniteid,0,@StockUniteRate,0,''),
				(@ExtUniteCode1,@ExtUniteid1,0,@ExtUniteRate1,0,@EntryCode1),
				(@ExtUniteCode2,@ExtUniteid2,0,@ExtUniteRate2,0,@EntryCode2),
				(@ExtUniteCode3,@ExtUniteid3,0,@ExtUniteRate3,0,@EntryCode3)
				
    DELETE  FROM PType_Units_Ext
    WHERE   ptypeid = @EtypeId_1
    
    INSERT  INTO #PType_Units_Ext1
    ( 
			  UnitsId ,
			  PtypeID,
			  RateType ,
			  Rate ,
			  EntryCode ,
			  IsDefaultUnit
    )
    SELECT	  UnitsId ,
			  @EtypeId_1,
			  RateType ,
			  MAX(Rate) ,
			  EntryCode,
			  MAX(IsDefaultUnit)
	FROM	#PType_Units_Ext
	WHERE	UnitsId IS NOT NULL
	GROUP BY UnitsId,RateType,EntryCode
 
	--删除重复的记录
    DELETE #PType_Units_Ext1 WHERE UnitsId in ( 
		SELECT UnitsId FROM #PType_Units_Ext1 GROUP BY UnitsId HAVING COUNT(UnitsId) > 1
    ) AND EntryCode = ''

    IF (@BaseUniteCode = @ExtUniteCode1 AND @EntryCode1 <> '' )
	OR (@BaseUniteCode = @ExtUniteCode2 AND @EntryCode2 <> '' )
	OR (@BaseUniteCode = @ExtUniteCode3 AND @EntryCode3 <> '' )
	BEGIN		
		DELETE #PType_Units_Ext1 WHERE PtypeID= @EtypeId_1 AND UnitsId = @baseUniteid AND EntryCode=''
		UPDATE #PType_Units_Ext1 SET IsDefaultUnit = 1 WHERE PtypeID= @EtypeId_1 AND UnitsId = @baseUniteid 
	END 
    
    /*
    INSERT  INTO dbo.PType_Units_Ext
    ( 
			  UnitsId ,
			  PtypeID,
			  RateType ,
			  Rate ,
			  EntryCode ,
			  IsDefaultUnit
    )
    SELECT	  ISNULL(UnitsId,0),
			  PtypeID,
			  RateType ,
			  Rate ,
			  EntryCode ,
			  IsDefaultUnit
	FROM #PType_Units_Ext1
	*/
	
	--上面的代码有问题，顺序不对，重新写 谢吉康 2019-04-30
	DELETE FROM dbo.PType_Units_Ext WHERE ptypeid = @EtypeId_1
			
	IF LTRIM(RTRIM(@BaseUniteCode))<>''
		AND EXISTS(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @BaseUniteCode)
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM PType_Units_Ext WHERE PtypeID = @EtypeId_1 AND UnitsId IN (SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @BaseUniteCode))
		BEGIN
			INSERT INTO dbo.PType_Units_Ext(ptypeid,UnitsId,RateType,rate,EntryCode,IsDefaultUnit,IsUse)
			VALUES
			(@EtypeId_1,(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @BaseUniteCode),0,1,'',1,1)
		END
	END
	
	IF LTRIM(RTRIM(@ExtUniteCode1))<>''
		AND EXISTS(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode1)
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM PType_Units_Ext WHERE PtypeID = @EtypeId_1 AND UnitsId IN (SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode1))
		BEGIN
			INSERT INTO dbo.PType_Units_Ext(ptypeid,UnitsId,RateType,rate,EntryCode,IsDefaultUnit,IsUse)
			VALUES
			(@EtypeId_1,(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode1),0,@ExtUniteRate1,@EntryCode1,0,1)
		END
		ELSE
		BEGIN
			UPDATE dbo.PType_Units_Ext	SET EntryCode=@EntryCode1
			WHERE ptypeid=@EtypeId_1 AND
			UnitsId=(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode1) AND
			RateType=0	AND
			rate=1	AND
			EntryCode=''	AND
			IsDefaultUnit=1	AND
			IsUse=1
		END
	END
	
	IF LTRIM(RTRIM(@ExtUniteCode2))<>''
		AND EXISTS(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode2)
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM PType_Units_Ext WHERE PtypeID = @EtypeId_1 AND UnitsId IN (SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode2))
		BEGIN
			INSERT INTO dbo.PType_Units_Ext(ptypeid,UnitsId,RateType,rate,EntryCode,IsDefaultUnit,IsUse)
			VALUES
			(@EtypeId_1,(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode2),0,@ExtUniteRate2,@EntryCode2,0,1)
		END	
		ELSE
		BEGIN
			UPDATE dbo.PType_Units_Ext	SET EntryCode=@EntryCode2
			WHERE ptypeid=@EtypeId_1 AND
			UnitsId=(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode2) AND
			RateType=0	AND
			rate=1	AND
			EntryCode=''	AND
			IsDefaultUnit=1	AND
			IsUse=1
		END		
	END
	
	IF LTRIM(RTRIM(@ExtUniteCode3))<>''
		AND EXISTS(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode3)		
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM PType_Units_Ext WHERE PtypeID = @EtypeId_1 AND UnitsId IN (SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode3))
		BEGIN
			INSERT INTO dbo.PType_Units_Ext(ptypeid,UnitsId,RateType,rate,EntryCode,IsDefaultUnit,IsUse)
			VALUES
			(@EtypeId_1,(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode3),0,@ExtUniteRate3,@EntryCode3,0,1)
		END
		ELSE
		BEGIN
			UPDATE dbo.PType_Units_Ext	SET EntryCode=@EntryCode3
			WHERE ptypeid=@EtypeId_1 AND
			UnitsId=(SELECT UnitsId FROM dbo.PType_Units WHERE UserCode = @ExtUniteCode3) AND
			RateType=0	AND
			rate=1	AND
			EntryCode=''	AND
			IsDefaultUnit=1	AND
			IsUse=1
		END
	END	
	
	--插入其他单位信息
	DECLARE @curUnitId	INT
	
	DECLARE UnitCursor CURSOR FOR
		SELECT ISNULL(UnitsId,0) AS UnitsId FROM #PType_Units_Ext1 ORDER BY Rate ASC
	
	OPEN UnitCursor
	
	FETCH NEXT FROM UnitCursor INTO @curUnitId
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM PType_Units_Ext WHERE PtypeID = @EtypeId_1 AND UnitsId = @curUnitId)
		BEGIN
			INSERT  INTO dbo.PType_Units_Ext
			( 
					  UnitsId ,
					  PtypeID,
					  RateType ,
					  Rate ,
					  EntryCode ,
					  IsDefaultUnit
			)
			SELECT	  ISNULL(UnitsId,0),
					  PtypeID,
					  RateType ,
					  Rate ,
					  EntryCode ,
					  IsDefaultUnit
			FROM      #PType_Units_Ext1
			WHERE	  UnitsId = @curUnitId
			ORDER BY  Rate ASC			
		END
		
		FETCH NEXT FROM UnitCursor INTO @curUnitId
	END
	
	CLOSE UnitCursor
	DEALLOCATE UnitCursor	
	
	IF(	@IfUseEntryCode='1')
	BEGIN 
		IF(@EntryCode<>'')
		BEGIN 
			INSERT INTO dbo.PType_EntryCode_Ext
					( Ptypeid ,
					  EntryCode ,
					  IsDefaultEntryCode
					)
			SELECT @EtypeId_1,@EntryCode,1
		END 
		IF(@EntryCode1<>'' AND @isdoubleunit = 1)
		BEGIN
		    INSERT  INTO dbo.PType_Units_EntryCode_Ext
				( PtypeID ,
				  UnitsId ,
				  EntryCode ,
				  IsDefaultEntryCode
				)
			SELECT	  @EtypeId_1,
					  ISNULL(@ExtUniteid1,0),
					  @EntryCode1 ,
					  1
		END
		IF(@EntryCode2<>'' AND @isdoubleunit = 1)
		BEGIN
		    INSERT  INTO dbo.PType_Units_EntryCode_Ext
				( PtypeID ,
				  UnitsId ,
				  EntryCode ,
				  IsDefaultEntryCode
				)
			SELECT	  @EtypeId_1,
					  ISNULL(@ExtUniteid2,0),
					  @EntryCode2,
					  1
		END
		IF(@EntryCode3<>'' AND @isdoubleunit = 1)
		BEGIN
		    INSERT  INTO dbo.PType_Units_EntryCode_Ext
				( PtypeID ,
				  UnitsId ,
				  EntryCode ,
				  IsDefaultEntryCode
				)
			SELECT	  @EtypeId_1,
					  ISNULL(@ExtUniteid3,0),
					  @EntryCode3,
					  1
		END
	END 

	--填充商品多条码		
	EXEC FillPtypeMultibarcode @EtypeId_1
	
    DECLARE @temprate DECIMAL(24,10),@tempunitid INT
    IF @AssistantUniteCode1<>''
		SELECT TOP 1 @assistantuniteid1 = UnitsId,@assistantuniterate1 =Rate FROM #PType_Units_Ext WHERE UniteCode=@AssistantUniteCode1
    
    IF @AssistantUniteCode2<>''
		SELECT TOP 1 @assistantuniteid2 = UnitsId,@assistantuniterate2 =Rate FROM #PType_Units_Ext WHERE UniteCode=@AssistantUniteCode2
		
	IF @AssistantUniteCode3<>''
		SELECT TOP 1 @assistantuniteid3 = UnitsId,@assistantuniterate3 =Rate FROM #PType_Units_Ext WHERE UniteCode=@AssistantUniteCode3
    
    IF ISNULL(@assistantuniterate2,0)>ISNULL(@assistantuniterate1,0)
    BEGIN
		SET @temprate=@assistantuniterate1
		SET @tempunitid=@assistantuniteid1
		
		SET @assistantuniterate1=@assistantuniterate2
		SET @assistantuniteid1=@assistantuniteid2
		
		SET @assistantuniterate2=@temprate
		SET @assistantuniteid2=@tempunitid
    END
    
    IF ISNULL(@assistantuniterate3,0)>ISNULL(@assistantuniterate1,0)
    BEGIN
		SET @temprate=@assistantuniterate1
		SET @tempunitid=@assistantuniteid1
		
		SET @assistantuniterate1=@assistantuniterate3
		SET @assistantuniteid1=@assistantuniteid3
		
		SET @assistantuniterate3=@temprate
		SET @assistantuniteid3=@tempunitid
    END
	
	IF ISNULL(@assistantuniterate3,0)>ISNULL(@assistantuniterate2,0)
    BEGIN
		SET @temprate=@assistantuniterate2
		SET @tempunitid=@assistantuniteid2
		
		SET @assistantuniterate2=@assistantuniterate3
		SET @assistantuniteid2=@assistantuniteid3
		
		SET @assistantuniterate3=@temprate
		SET @assistantuniteid3=@tempunitid
    END
    
    
	INSERT INTO dbo.PType_AuxiliaryUnits_Ext
	        ( PtypeID ,
	          SaleUnitID1 ,
	          SaleUnitRate1 ,
	          SaleUnitID2 ,
	          SaleUnitRate2 ,
	          SaleUnitID3 ,
	          SaleUnitRate3
	        )
	VALUES  ( @EtypeId_1 , -- PtypeID - varchar(50)
	          @AssistantUniteId1 , -- SaleUnitID1 - int
	          @AssistantUniteRate1 , -- SaleUnitRate1 - decimal
	          @AssistantUniteId2 , -- SaleUnitID2 - int
	          @AssistantUniteRate2 , -- SaleUnitRate2 - decimal
	          @AssistantUniteId3 , -- SaleUnitID3 - int
	          @AssistantUniterate3  -- SaleUnitRate3 - decimal
	        )
	
	DROP TABLE #PType_Units_Ext
	DROP TABLE #PType_Units_Ext1
	
	--只导入基本单位
    INSERT  ptype_price
            ( PTypeID ,
              PreBuyPrice1 ,
              PreBuyPrice2 ,
              PreBuyPrice3 ,
              PreBuyPrice4 ,
              PreBuyPrice5 ,
              TopBuyPrice ,
              PreSalePrice1 ,
              PreSalePrice2 ,
              PreSalePrice3 ,
              PreSalePrice4 ,
              PreSalePrice5 ,
              PreSalePrice6 ,
              PreSalePrice7 ,
              PreSalePrice8 ,
              PreSalePrice9 ,
              PreSalePrice10 ,
              RetailPrice ,
              TopSalePrice ,
              LowSalePrice ,
              UnitID,
              IsDefaultUnit
            )
    VALUES  ( @EtypeId_1 ,
              @PreBuyPrice1 ,
              @PreBuyPrice2 ,
              @PreBuyPrice3 ,
              @PreBuyPrice4 ,
              @PreBuyPrice5 ,
              @TopBuyPrice ,
              @PreSalePrice1 ,
              @PreSalePrice2 ,
              @PreSalePrice3 ,
              @PreSalePrice4 ,
              @PreSalePrice5 ,
              @PreSalePrice6 ,
              @PreSalePrice7 ,
              @PreSalePrice8 ,
              @PreSalePrice9 ,
              @PreSalePrice10 ,
              @RetailPrice ,
              @TopSalePrice ,
              @LowSalePrice ,
              @baseUniteId,
              1
            )
       
      
            
    INSERT  dbo.QP_PType_Ext
            ( PTypeID ,
              Brand ,
              Import ,
              GeneralType ,
              GeneralDwgNo ,
              Property ,
              PackageQty ,
              Weight ,
              TaxNumber ,
              Taxrate ,
              BTypeID ,
              FcUnit ,
              FcPrice
            )
    VALUES  ( @EtypeId_1 ,
              @Brand ,
              @Import ,
              @GeneralType ,
              @GeneralDwgNo ,
              @Property ,
              @PackageQty ,
              @Weight ,
              @TaxNumber ,
              @Taxrate ,
              @BTypeID ,
              @FcUnit ,
              @FcPrice
            ) 
 
    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
    ELSE 
        BEGIN
            UPDATE  [ptype]
            SET     sonnum = @nSonnum + 1 ,
                    soncount = @nSoncount + 1
            WHERE   typeid = @ParId
            UPDATE  Ptype
            SET     preprice1 = 0 ,
                    preprice2 = 0 ,
                    preprice3 = 0 ,
                    preprice4 = 0 ,
                    preprice5 = 0 ,
                    SerialCount = 0 ,
                    recprice = 0
            WHERE   Typeid = @ParId
	
        END

--修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    PType
    UPDATE  PType
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @EtypeId_1
	
	DELETE dbo.PosReDataGlobal WHERE stypeid='-99999'
	INSERT INTO dbo.PosReDataGlobal
	        ( IfReData, stypeid )
	VALUES  ( 1, -- IfReData - int
	          '-99999'  -- stypeid - varchar(50)
	          )
	          
	--更新数据
	CREATE TABLE #TempUnitsExt
	(
		nid		INT IDENTITY(1,1),
		ptypeid	VARCHAR(50),
		sortid	INT
	)
	INSERT INTO #TempUnitsExt(ptypeid,sortid)SELECT ptypeid,SortId FROM PType_Units_Ext WHERE PtypeID = @EtypeId_1 ORDER BY SortId ASC

	UPDATE	PType_Units_Ext
	SET		UnitsSortId = t.nid
	FROM	PType_Units_Ext pue
	INNER JOIN #TempUnitsExt t ON pue.PtypeID= t.ptypeid AND pue.SortId = t.sortid	
	
	DROP TABLE #TempUnitsExt          
	          
	
	IF( 0 < (SELECT COUNT(1) FROM CustomBaseInforColumnsDefines WHERE BaseType='ptype'))
	BEGIN
		INSERT INTO dbo.Ptype_CustomColumns
        ( typeid ,
          Costom1 ,
          Costom2 ,
          Costom3 ,
          Costom4 ,
          Costom5 ,
          Costom6 ,
          Costom7 ,
          Costom8 ,
          Costom9 ,
          Costom10 ,
          Costom11 ,
          Costom12 ,
          Costom13 ,
          Costom14 ,
          Costom15 ,
          Costom16 
        )
		VALUES  ( 
		@EtypeId_1,
		@costom1,
		@costom2,
		@costom3,
		@costom4,
		@costom5,
		@costom6,
		@costom7,
		@costom8,
		@costom9,
		@costom10,
		@costom11,
		@costom12,
		@costom13,
		@costom14,
		@costom15,
		@costom16
				)

	--	END
	END
	
	
    COMMIT TRAN insertproc


GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE   PROCEDURE Gp_ImportPtype
(
	@pusercode	varchar(200),
	@pfullname 	varchar(200),
    @usercode	varchar(200),
	@fullname 	varchar(200),
    @OperatorID varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON
   
    DECLARE @nReturntype INT,
        @p_ParId [varchar](50),
        @EtypeId_1 [varchar](50),
        @dbname [varchar](50),
        @nSoncount INT,
        @nSonnum INT,
        @leveal SMALLINT

    SELECT @p_ParId=typeId FROM ptype WHERE usercode=ISNULL(@pusercode,'00000')
    SELECT @dbname='Ptype'

-- 判断库存量（每个仓库）是否为零
    IF EXISTS ( SELECT  ptypeid
                FROM    goodsstocks
                WHERE   ptypeid = @p_ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
            RETURN -4
        END 
    IF EXISTS ( SELECT  ptypeid
                FROM    inigoodsstocks
                WHERE   ptypeid = @p_ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
            RETURN -4
        END 

    IF EXISTS ( SELECT  ptypeid
                FROM    wx_goodsstocks
                WHERE   ptypeid = @p_ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
            RETURN -4
        END 
    IF EXISTS ( SELECT  ptypeid
                FROM    wx_inigoodsstocks
                WHERE   ptypeid = @p_ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
            RETURN -4
        END 

-- 判断借欠余额
    IF EXISTS ( SELECT  pTypeID
                FROM    V_LendStatus
                WHERE   pTypeID = @p_ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品有借进借出，不能分类'
            RETURN -5
        END 
-- 判断经营
    IF EXISTS ( SELECT  pTypeID
                FROM    InOutStockTable
                WHERE   pTypeID = @p_ParId
                        AND Qty <> 0 )
        OR EXISTS ( SELECT  pTypeID
                    FROM    LendBill
                    WHERE   pTypeID = @p_ParId
                            AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
            RETURN -6
        END 

    IF EXISTS ( SELECT  pTypeID
                FROM    Billindex
                WHERE   pTypeID = @p_ParId ) 
        BEGIN
            RETURN -6
	--print '经营过'
        END
    IF EXISTS ( SELECT  pTypeID
                FROM    OrderBill
                WHERE   pTypeID = @p_ParId ) 
        BEGIN
            RETURN -501
	--print '订单使用'
        END
    IF EXISTS ( SELECT  pTypeID
                FROM    RepairEngage
                WHERE   pTypeID = @p_ParId ) 
        BEGIN
            RETURN -503
	--print '维修使用'
        END
-- 判断代销
    IF EXISTS ( SELECT  pTypeID
                FROM    iniCommissionStock
                WHERE   pTypeID = @p_ParId
                        AND Qty <> 0 )
        OR EXISTS ( SELECT  pTypeID
                    FROM    CommissionStock
                    WHERE   pTypeID = @p_ParId
                            AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
            RETURN -13
        END 
--判断序列号
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_CruPtypeSerial
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
	--print '住来有序列号，不能分类'
            RETURN -15
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_initPtypeSerial
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
	--print '往来有期初序列号，不能分类'
            RETURN -16
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    PuserCode
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
	--print '设置了多编码，不能分类'
            RETURN -17
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_LendPtypeserial
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
	--print '商品有借欠序列号，不能分类'
            RETURN -18
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    produceModel
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
	--print '商品有生产模板明细，不能分类'
            RETURN -19
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    produceModelIndex
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
	--print '商品有生产模板索引，不能分类'
            RETURN -19
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    stockcheck
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
	--print '商品有盘点单，不能分类'
            RETURN -20
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    dbo.QP_RecycleBill
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
            RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_QuickRepairBill_PType
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
            RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_EvaluationBill_PType
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
            RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    dbo.[QP_EvaluationBill_PType]
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
            RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_QuickRepairBill_PType
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
            RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    IntegralExchangeBill
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
            RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QuotePriceBill
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
            RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    AskPriceBill
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
            RETURN -21
        END
    IF EXISTS (SELECT TOP 1 * FROM CargoSpace WHERE PTypeID=@p_ParId)    
    BEGIN
		RETURN -22--存在货位
	END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_RepairSetMeal_Fittings
                WHERE   PTypeID = @p_ParId ) 
        BEGIN
	--print '设置了维修套餐，不能分类'
            RETURN -36
        END
-- 获得新的ID号
    EXEC @nReturntype= Gp_createId @p_ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
    IF @nReturntype = -1 
        RETURN -1
    IF @nReturntype = -2 
        RETURN -2
-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted <> 1
                           ) ) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
            RETURN -3
        END
-- 判断已停用的重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted = 1
                           ) ) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
            RETURN -31
        END
    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    ptype
    WHERE   typeid = @p_ParId
    SELECT  @leveal = @leveal + 1

 INSERT  INTO [ptype]
            (
              [typeId],
              [Parid],
              [leveal],
              [soncount],
              [sonnum],
              [FullName],
              [UserCode],
              [Type]
            )   
    VALUES  (
              @EtypeId_1,
              @p_ParId,
              @leveal,
              0,
              0,
              @fullname,
              @UserCode,
              ''
            )    ----
     
    UPDATE ptype SET soncount=ISNULL(soncount,0)+1 ,sonnum=ISNULL(sonnum,0)+ 1 WHERE typeid = @p_ParId

    INSERT  ptype_price
            (
              PTypeID/*,
              PreBuyPrice1,
              PreBuyPrice2,
              PreBuyPrice3,
              PreBuyPrice4,
              PreBuyPrice5,
              PreSalePrice1,
              PreSalePrice2,
              PreSalePrice3,
              PreSalePrice4,
              PreSalePrice5,
              PreSalePrice6,
              PreSalePrice7,
              PreSalePrice8,
              PreSalePrice9,
              PreSalePrice10,
              RetailPrice,
              TopSalePrice,
              LowSalePrice*/
            )
    VALUES  (
              @EtypeId_1/*,
              @r_PreBuyPrice1,
              @r_PreBuyPrice2,
              @r_PreBuyPrice3,
              @r_PreBuyPrice4,
              @r_PreBuyPrice5,
              @r_PreSalePrice1,
              @r_PreSalePrice2,
              @r_PreSalePrice3,
              @r_PreSalePrice4,
              @r_PreSalePrice5,
              @r_PreSalePrice6,
              @r_PreSalePrice7,
              @r_PreSalePrice8,
              @r_PreSalePrice9,
              @r_PreSalePrice10,
              @r_RetailPrice,
              @r_TopSalePrice,
              @r_LowSalePrice*/
            )

INSERT  dbo.QP_PType_Ext
            (
              PTypeID/*,
              Brand,
              Import,
              GeneralType,
              GeneralDwgNo,
              Property,
              PackageQty,
              Weight,
              TaxNumber,
              Taxrate,
              BTypeID,
              FcUnit,
              FcPrice*/
            )
    VALUES  (
              @EtypeId_1/*,
              @e_Brand,
              @e_Import,
              @e_GeneralType,
              @e_GeneralDwgNo,
              @e_Property,
              @e_PackageQty,
              @e_Weight,
              @e_TaxNumber,
              @e_Taxrate,
              @e_BTypeID,
              @e_FcUnit,
              @e_FcPrice*/
            ) 
 

    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END

    
    --修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    PType
    UPDATE  PType
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @EtypeId_1
    COMMIT TRAN insertproc
  /* DECLARE @ptypeid varchar(100)
     SELECT @ptypeid=typeid FROM ptype where usercode=@pusercode AND sonnum=0 AND deleted=0
     
     IF NOT EXISTS (SELECT * FROM ptype where usercode=@usercode AND sonnum=0 AND deleted=0)
     BEGIN
          
          INSERT INTO ptype(typeid,ParId,usercode,fullname) VALUES ('',@ptypeid,ISNULL(@usercode,''),ISNULL(@fullname,''))
     END*/
   
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportPtypeBrandar]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_ImportPtypeBrandar]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
	作者：谢吉康
	时间：2017-11-17
	描述：导入商品品牌
*/
CREATE PROCEDURE [dbo].[Gp_ImportPtypeBrandar]
(
    @PCUserCode			VARCHAR(200),			--品牌编码
    @PCFullName			VARCHAR(200),			--品牌名称
    @ParUserCode		VARCHAR(200),			--所属品牌编码
    @Comment			VARCHAR(500),			--品牌备注
    @ErrMsg				VARCHAR(200) OUTPUT
)
--@encode$--
AS 

SET NOCOUNT ON

DECLARE @dbname VARCHAR(50)='brandar_Commodity'
DECLARE @PCTypeID VARCHAR(500)
DECLARE @sonnum INT
DECLARE @soncount INT
DECLARE @Parid VARCHAR(500)

DECLARE @PBrandarID VARCHAR(500)

IF (@PCUserCode='')
BEGIN
    SET @ErrMsg='商品品牌编号不能为空'
    RETURN -1
END
ELSE IF (@PCFullName='')
BEGIN
    SET @ErrMsg='商品品牌名称不能为空'
    RETURN -1
END
ELSE IF EXISTS(SELECT 1 FROM dbo.brandar_Commodity WHERE UserCode=@PCUserCode)
BEGIN
    SET @ErrMsg='商品品牌编号已存在'
    RETURN -1
END
ELSE IF EXISTS(SELECT 1 FROM dbo.brandar_Commodity WHERE FullName=@PCFullName)
BEGIN
    SET @ErrMsg='商品品牌名称已存在'
    RETURN -1
END

IF (@ParUserCode<>'')
BEGIN
	DECLARE @typeId VARCHAR(50)
	SELECT TOP 1 @typeId = typeid FROM dbo.brandar_Commodity WHERE usercode = @ParUserCode
	
	--处理默认品牌
	IF EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE typeid = @typeId AND Issys = 1)
	BEGIN
		--默认品牌不允许分类
		IF @Parid <> '00000'
		BEGIN
			RAISERROR('系统默认品牌不允许分类，请修改后再保存。',16,1) 
			RETURN	
		END
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE TypeId = @typeId AND Issys = 1) 
			AND @Parid <> '00000'
		BEGIN
			RAISERROR('系统默认品牌不允许重新归类，请修改后再保存。',16,1) 
			RETURN	
		END
		ELSE
		BEGIN
			--父类被使用则不能分类了
			IF @typeId <> ''
			BEGIN
				DECLARE @Re				INT,
						@errMsgX		VARCHAR(500)
				EXEC @Re = Web_BrandarCommondityCanDel @typeId,@errMsgX OUTPUT
				IF @Re <> 0
				BEGIN
					RAISERROR('所属品牌已经被使用，不能分类，请修改后再保存。',16,1) 
					RETURN
				END
			END	
		END
	END	

	IF EXISTS(SELECT TOP 1 1 FROM dbo.brandar_Commodity WHERE UserCode = @ParUserCode AND IsSys = 1)
	BEGIN
		SET @ErrMsg='系统默认的品牌不允许分类'
        RETURN -1
	END
	
    IF NOT EXISTS(SELECT 1 FROM dbo.brandar_Commodity WHERE UserCode=@ParUserCode)
    BEGIN
        SET @ErrMsg='所属品牌编码不存在'
        RETURN -1
    END
    ELSE
	BEGIN 
		SET @Parid=(SELECT TOP 1 typeid FROM dbo.brandar_Commodity WHERE UserCode=@ParUserCode)
	END
END
ELSE
BEGIN
    SET @Parid='00000'
END

DECLARE @nReturntype INT
EXEC @nReturntype=dbo.Gp_CreateId @Parid,@dbName,@PCTypeID OUT,@sonnum OUT,@soncount OUT
IF @nReturntype = -1 
BEGIN
    SET @ErrMsg = '商品品牌分类分类不能超过10层'
    RETURN -1
END
IF @nReturntype = -2 
BEGIN
    SET @ErrMsg = '无法添加商品品牌信息'
    RETURN -1
END

DECLARE @leveal INT
BEGIN TRAN insertproc


SELECT  @leveal = leveal
FROM    dbo.brandar_Commodity
WHERE   typeid = @ParId
SELECT  @leveal = @leveal + 1

INSERT INTO dbo.brandar_Commodity
        ( typeid ,
          parid ,
          leveal ,
          sonnum ,
          soncount ,
          UserCode ,
          FullName ,
          Comment,
          XiWaMaxNumber
        )
VALUES  ( @PCTypeID , -- typeid - varchar(50)
          @Parid , -- parid - varchar(50)
          @leveal , -- leveal - int
          0 , -- sonnum - int
          0 , -- soncount - int
          @PCUserCode , -- UserCode - varchar(200)
          @PCFullName , -- FullName - varchar(200)
          @Comment,  -- Comment - varchar(500)
          1
        )

IF @@rowcount = 0 
    BEGIN
        ROLLBACK TRAN insertproc 
        RETURN -1
    END
ELSE 
    BEGIN
        UPDATE  dbo.brandar_Commodity
        SET     sonnum = @sonnum + 1 ,
                soncount = @soncount + 1
        WHERE   typeid = @ParId
    END


COMMIT TRAN insertproc
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportPtypeCategory]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_ImportPtypeCategory]
GO

/****** Object:  StoredProcedure [dbo].[Gp_ImportPtypeCategory]    Script Date: 05/30/2011 15:28:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：寇晨
	时间：2016-08-02
	描述：导入商品类别
*/
CREATE PROCEDURE [dbo].[Gp_ImportPtypeCategory]
(
    @PCUserCode VARCHAR(500),  --类别编码
    @PCFullName VARCHAR(500),  --类别名称
    @ParUserCode VARCHAR(500), --所属类别编码
    @Comment VARCHAR(500),     --类别备注
    @ErrMsg VARCHAR(200) OUTPUT
)
--@encode$--
AS 
    SET NOCOUNT ON
    
    DECLARE @dbname VARCHAR(50)='PTypeCategory'
    DECLARE @PCTypeID VARCHAR(500)
    DECLARE @sonnum INT
    DECLARE @soncount INT
    DECLARE @Parid VARCHAR(500)
    
    DECLARE @PCategoryID VARCHAR(500)
    IF (@PCUserCode='')
    BEGIN
        SET @ErrMsg='商品类别编号不能为空'
        RETURN -1
    END
    ELSE IF (@PCFullName='')
    BEGIN
        SET @ErrMsg='商品类别名称不能为空'
        RETURN -1
    END
    ELSE IF EXISTS(SELECT 1 FROM dbo.PTypeCategory WHERE UserCode=@PCUserCode)
    BEGIN
        SET @ErrMsg='商品类别编号已存在'
        RETURN -1
    END
    ELSE IF EXISTS(SELECT 1 FROM dbo.PTypeCategory WHERE FullName=@PCFullName)
    BEGIN
        SET @ErrMsg='商品类别名称已存在'
        RETURN -1
    END
    
    IF (@ParUserCode<>'')
    BEGIN
        IF NOT EXISTS(SELECT 1 FROM dbo.PTypeCategory WHERE UserCode=@ParUserCode)
        BEGIN
            SET @ErrMsg='所属类别编码不存在'
            RETURN -1
        END
        ELSE
		BEGIN 
			SET @Parid=(SELECT TOP 1 typeid FROM dbo.PTypeCategory WHERE UserCode=@ParUserCode)
		END
    END
    ELSE
    BEGIN
        SET @Parid='00000'
    END
    
    DECLARE @nReturntype INT
    EXEC @nReturntype=dbo.Gp_CreateId @Parid,@dbName,@PCTypeID OUT,@sonnum OUT,@soncount OUT
    IF @nReturntype = -1 
    BEGIN
        SET @ErrMsg = '商品类别分类分类不能超过10层'
        RETURN -1
    END
    IF @nReturntype = -2 
    BEGIN
        SET @ErrMsg = '无法添加商品类别信息'
        RETURN -1
    END
    
    DECLARE @leveal INT
    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    dbo.PTypeCategory
    WHERE   typeid = @ParId
    SELECT  @leveal = @leveal + 1
    
    INSERT INTO dbo.PTypeCategory
            ( typeid ,
              parid ,
              leveal ,
              sonnum ,
              soncount ,
              UserCode ,
              FullName ,
              Comment
            )
    VALUES  ( @PCTypeID , -- typeid - varchar(50)
              @Parid , -- parid - varchar(50)
              @leveal , -- leveal - int
              0 , -- sonnum - int
              0 , -- soncount - int
              @PCUserCode , -- UserCode - varchar(200)
              @PCFullName , -- FullName - varchar(200)
              @Comment  -- Comment - varchar(500)
            )
    
    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
    ELSE 
        BEGIN
            UPDATE  dbo.PTypeCategory
            SET     sonnum = @sonnum + 1 ,
                    soncount = @soncount + 1
            WHERE   typeid = @ParId
        END
	
	
    COMMIT TRAN insertproc
GO



IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_ImportPtypeMultiCode]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_ImportPtypeMultiCode]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	创建：glj
	时间：2018-12-13
	描述：商品多编码模板
*/
CREATE PROCEDURE [dbo].Gp_ImportPtypeMultiCode
    (
      @BUserCode VARCHAR(200),--往来单位编号
      @BFullName VARCHAR(200) ,--往来单位名称
      @PUserCode VARCHAR(200),--商品编号
      @PFullName VARCHAR(200),--商品名称
      @UserDefinedCode VARCHAR(200),--自定义编号
      @ErrMsg VARCHAR(200) OUTPUT 
    )
AS 
SET NOCOUNT ON

--条件判断
--=====往来单位/商品/自定义编号不能为空判断=======
IF(ISNULL(@BUserCode,'')='')--往来单位
	BEGIN
			SET @ErrMsg = '往来单位编号不能为空'
			RETURN -1
	END

IF(ISNULL(@PUserCode,'')='')--商品
	BEGIN
			SET @ErrMsg = '商品编号不能为空'
			RETURN -1
	END
IF(ISNULL(@UserDefinedCode,'')='')--自定义编号
	BEGIN
			SET @ErrMsg = '自定义编号不能为空'
			RETURN -1
	END

--=====往来单位/商品/自定义编号 是否存在判断=======
IF NOT EXISTS(SELECT * FROM btype WHERE UserCode=@BUserCode AND deleted=0 AND sonnum=0)
	BEGIN
			SET @ErrMsg = '往来单位不存在或为父类'
			RETURN -1
	END


--商品判断
IF NOT EXISTS(SELECT * FROM ptype WHERE UserCode=@PUserCode AND deleted=0 AND sonnum=0)
	BEGIN
			SET @ErrMsg = '商品编号不存在'
			RETURN -1
	END

DECLARE 
	@PtypeId VARCHAR(50)='',
	@BtypeId VARCHAR(50)=''
	
SELECT @PtypeId=typeId FROM ptype WHERE UserCode=@PUserCode
SELECT @BtypeId=typeId FROM btype WHERE UserCode=@BUserCode

IF EXISTS(SELECT TOP 1 1 FROM dbo.Pusercode WHERE btypeid = @BtypeId AND usercode = @UserDefinedCode)
BEGIN
	SET @ErrMsg = '自定义编号重复，不能导入！'
	RETURN -1
END

DELETE FROM Pusercode WHERE ptypeid=@PtypeId and btypeid=@BtypeId

INSERT INTO PUserCode(btypeid,ptypeid,usercode) VALUES(@BtypeId,@PtypeId,@UserDefinedCode)

 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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


/****** Object:  StoredProcedure [dbo].[Gp_ImportPtypeTemp]    Script Date: 05/20/2011 17:29:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	创 建 者：廖晨羽
	日    期：2011-09-16
	创建原因：导入单据信息
*/



CREATE               PROCEDURE [dbo].[Gp_ImportPtypeTemp]
(
 @CargoUserCode	[varchar](500)='',
 @CargoFullName	[varchar](500)='',
 @UserCode      [varchar](256),
 @FullName      [varchar](200),
 @StrStock      [varchar](66)='',
 @StrQty	    [varchar] (18),
 @StrEntryCode  [varchar](500),
 @PUserCode		[varchar](256)='',
 @StrPrice      [varchar](66)='',
 @StrTax        [varchar](66)='',
 @StrDiscount   [varchar](66)='',
 @ProduceDate	varchar(100)='',
 @ValidDate		varchar(100)='',
 @GoodsNumber	varchar(100)='',
 @Comment		varchar(255)='',
 @btypeid		varchar(100)='',
 @ReturnID		VARCHAR(100) OUTPUT,
 @ErrMsg		VARCHAR(200) OUTPUT,
 @typeid		[varchar](max)='',
 @StrSerials	[varchar](max)='',
 @State			VARCHAR(50) ='',
 @StrStockIn    [varchar](66)='',
 @CargoUserCodeIn	[varchar](500)='',
 @isUseCarGo    [varchar] (18)='',
 @billindexStock [varchar](500)='', --表头仓库信息
 @billindexStockin [varchar](500)=''
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PtypeId  VARCHAR(50)
DECLARE @flagint  INT
DECLARE @ChildCount NUMERIC(18,0)
-------------------------------------转换输入参数---------------------------------------------
--IF(@UserCode = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @UserCode) OR @UserCode='0')
--BEGIN
--	SET @ErrMsg = '商品编号不存在'
--	RETURN -1
--END

DECLARE @maxQty  NUMERIC(24, 10) =9999999999.999999999
DECLARE @maxQty1 VARCHAR(25) ='9999999999.999999999'
DECLARE @weicount VARCHAR(50)
DECLARE @temp VARCHAR(500)
DECLARE @userid VARCHAR(max),@billtype VARCHAR(4),@formStype VARCHAR(50),@formstock VARCHAR(50),@temp1 VARCHAR(50) ,@mergeqty VARCHAR(50) ---分解操作员ID和单据类型编号
SET @userid = (SELECT TOP 1 A FROM f_split(@typeid,'я'))
SET @temp = (SELECT A FROM f_split(@typeid,'я') WHERE A <> @userid )
if(@billtype <> '306')
BEGIN

SET @billtype = (SELECT top 1 A FROM f_split(@temp,'#'))
SET @formStype = (SELECT  A FROM f_split(@temp,'#') WHERE A <> @billtype  )
END
ELSE
BEGIN
SET @billtype = (SELECT top 1 A FROM f_split(@temp,'#'))
SET @temp1 = (SELECT  A FROM f_split(@temp,'#') where A <> @billtype)
--SET @formStype = (SELECT top 1  A FROM f_splitBy829(@temp1,'*') order by s asc)
--SET @formstock = (SELECT  top 1 A FROM f_splitBy829(@temp1,'*') order by s desc )
SELECT @formStype = A FROM f_splitBy829(@temp1,'*') WHERE s=1 
SELECT @formstock = A FROM f_splitBy829(@temp1,'*') WHERE s=2
--是否勾选盘点数量合并
SELECT @mergeqty  = A FROM f_splitBy829(@temp1,'*') WHERE s=3  
--IF NOT EXISTS(select * from goodsstocks_qty where ptypeid=@PtypeId and ktypeid=@formstock)
--BEGIN

--		SET @ErrMsg = '商品没有在表头仓库中'
--		RETURN -1	
--END

END

IF( @billtype='34' or @billtype='300' or  @billtype='11' or  @billtype='301' or @billtype='400' or @billtype='402')
BEGIN
	IF( @PUserCode = '')
	BEGIN
	
		IF(@UserCode = '' AND @StrEntryCode ='')
		BEGIN
			SET @ErrMsg = '商品编号和条码不能同时为空'
			RETURN -1
		END
		
	END
	ELSE
	BEGIN
	
		IF(@UserCode = '' AND @StrEntryCode = '' AND @btypeid = '')
		BEGIN
			SET @ErrMsg ='现在是以商品自定义编号导入，请在单据上选择对应的往来单位'
			RETURN -1
		END
		
	END

END
ELSE
BEGIN

	IF(@UserCode = '' AND @StrEntryCode ='')
	BEGIN
		SET @ErrMsg = '商品编号和条码不能同时为空'
		RETURN -1
	END

END



--IF @UserCode = ''
--BEGIN
--	SET @ErrMsg = '商品编号不能为空'
--	RETURN -1
--END
--商品编号不为空
IF(@UserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @UserCode) OR @UserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
IF(@UserCode <> '' AND 1 = (SELECT TOP 1 deleted FROM dbo.ptype WHERE UserCode = @UserCode))
BEGIN
	SET @ErrMsg = '该商品已停用'
	RETURN -1
END
IF (@FullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @FullName) OR @FullName='全部商品')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
IF(@FullName NOT IN (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @UserCode) AND @FullName <> '' AND @UserCode <> '')
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END
--商品编号不为空

--商品条码不为空
IF @StrEntryCode <> ''
BEGIN
	IF( NOT EXISTS (SELECT EntryCode FROM dbo.PType_EntryCode_Ext WHERE entrycode = @StrEntryCode))
	BEGIN
		SET @ErrMsg = '商品条码不存在'
		RETURN -1
	END
	IF(@UserCode='' AND @FullName='')
		BEGIN
		IF(  1<= (SELECT COUNT(1) FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1)) AND deleted = 1))
		BEGIN
			SET @ErrMsg = '该商品已停用'
			RETURN -1
		END
	END
	IF(@UserCode='' AND @FullName<>'')
		BEGIN
		IF( 1<= (SELECT COUNT(1) FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1)) AND FullName= @FullName AND deleted = 1))
		BEGIN
			SET @ErrMsg = '该商品已停用'
			RETURN -1
		END
	END
	IF( @UserCode <> '' AND (@UserCode NOT IN (SELECT TOP 1 UserCode FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1)) AND @UserCode = UserCode)) )
	BEGIN
		SET @ErrMsg = '商品条码与商品编号不匹配'
		RETURN -1
	END
	IF( @FullName <> '' AND @FullName NOT IN (SELECT TOP 1 fullname FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1))) )
	BEGIN
		SET @ErrMsg = '商品条码与商品名称不匹配'
		RETURN -1
	END

	--与开发沟通，调整为同一条码对应多个商品编码时，提示：条码对应的商品编码重复！不带入商品到表体。	
	IF (1 < (SELECT COUNT(1) FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1)) ))
	BEGIN
		SET @ErrMsg = '条码对应的商品编码重复，不能导入'
		RETURN -1	
	END
END 

--商品条码不为空  
IF(@UserCode <> '')
BEGIN
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @UserCode)
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0)
	BEGIN
		SET @ErrMsg = '该商品为父节点，不能导入'
		RETURN -1	
	END
	SET @StrEntryCode=(SELECT TOP 1 entrycode FROM dbo.ptype WHERE UserCode = @UserCode)
END
ELSE IF(@UserCode = '' AND @StrEntryCode <> '')
BEGIN
	SELECT @UserCode=UserCode FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1))
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @UserCode)
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0)
	BEGIN
		SET @ErrMsg = '该商品为父节点，不能导入'
		RETURN -1	
	END
END
--商品自定义编号验证
IF( @billtype='34' or @billtype='300' or  @billtype='11' or  @billtype='301' or @billtype='400' or @billtype='402')
BEGIN
	IF( @UserCode = '' AND @StrEntryCode ='' AND @btypeid <> '' AND @PUserCode <> '')
	BEGIN
		IF(NOT EXISTS(SELECT ptypeid FROM PUserCode WHERE btypeid=@btypeid AND usercode=@PUserCode))
		BEGIN
			SET @ErrMsg = '没有匹配的商品自定义编号'
			RETURN -1	
		END
		ELSE
		BEGIN
			SELECT @PtypeId = ptypeid FROM PUserCode WHERE btypeid=@btypeid AND usercode=@PUserCode
			SELECT @UserCode = usercode FROM dbo.ptype WHERE typeId = @PtypeId
			
			IF NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE typeId=@PtypeId)
			BEGIN
				SET @ErrMsg = '自定义编号所对应的商品不存在'
				RETURN -1
			END
			IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ptype WHERE typeId=@PtypeId AND deleted=0)
			BEGIN
				SET @ErrMsg = '自定义编号所对应的商品已停用'
				RETURN -1
			END
		END
			
	END
END


IF (@ptypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@userid)))
BEGIN
	SET @ErrMsg = '操作员没有该商品权限'
	RETURN -1
END
/*
IF @StrEntryCode<> '' AND @UserCode =''
BEGIN
	IF @FullName = ''
	BEGIN
		IF (0 < (SELECT SUM(sonnum) FROM dbo.ptype WHERE EntryCode = @StrEntryCode AND deleted = 0))
		BEGIN
			SET @ErrMsg = '该商品为父节点，不能导入'
			RETURN -1	
		END
		IF (1 < (SELECT COUNT(1) FROM dbo.ptype WHERE EntryCode = @StrEntryCode AND deleted = 0))
		BEGIN
			SET @ErrMsg = '系统中有相同的条码，不能导入'
			RETURN -1	
		END
	END
	ELSE
	BEGIN
		IF (0 < (SELECT SUM(sonnum) FROM dbo.ptype WHERE EntryCode = @StrEntryCode AND FullName= @FullName AND deleted = 0))
		BEGIN
			SET @ErrMsg = '该商品为父节点，不能导入'
			RETURN -1	
		END	
		IF (1 < (SELECT COUNT(1) FROM dbo.ptype WHERE EntryCode = @StrEntryCode AND FullName= @FullName AND deleted = 0))
		BEGIN
			SET @ErrMsg = '条码对应的商品编码重复，不能导入'
			RETURN -1	
		END
	END
END
*/




--print(@typeid+'typeid')
--print(@formStype+'stype')
--print(@StrStock+'stock')
--print(@formstock+'fromstock')
/*
1、	可以使用服务商品的单据：
SELECT * FROM dbo.BillName WHERE BillName IN ('销售订单','采购订单','报价单','询价单','请购单','零售单','零售退货单','销售出库单','销售退货单',
'销售换货单','采购入库单','采购退货单','采购换货单','积分兑换单')

*/

IF 0 = (SELECT CHARINDEX(','+@billtype+',',',184,305,215,300,11,45,160,204,185,301,34,6,161,183,'))
BEGIN

	IF(1=(SELECT count(*) FROM dbo.ptype WHERE UserCode = @UserCode and isservice=1) AND @UserCode<>'')
		BEGIN
		
		SET @ErrMsg = '该商品属于服务商品不能导入'
		RETURN -1
	END
	IF( @StrEntryCode<>'' AND 1=(SELECT count(*) FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1)) and isservice=1))
		BEGIN
		SET @ErrMsg = '该商品属于服务商品不能导入'
		RETURN -1
	END
END


--验证是否为组合品商品 添加库存盘点单，添加赠送单、获赠单
IF 0 <> (SELECT CHARINDEX(','+@billtype+',',',184,305,215,300,11,45,160,204,185,301,34,6,161,183,140,141,144,145,17,21,306,400,401,402,403,405,404,401,139,126,'))
BEGIN
	IF(1=(SELECT count(*) FROM dbo.ptype WHERE UserCode = @UserCode and iscombinationproduct=1) AND @UserCode<>'')
		BEGIN
		SET @ErrMsg = '该商品属于组合品商品不能导入'
		RETURN -1
	END
	IF( @StrEntryCode<>'' AND 1=(SELECT count(*) FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1)) and iscombinationproduct=1) )
		BEGIN
		SET @ErrMsg = '该商品属于组合品商品不能导入'
		RETURN -1
	END
END

if(len(@ErrMsg)>0 and (@billtype='144' or  @billtype='145'  or  @billtype='140'  or  @billtype='141') )
BEGIN
 RETURN -1
END
ELSE 
BEGIN
 SET @ErrMsg = ''
END

/*
--非手工指定算法下：盘点单上录入商品如果系统配置中【货位，自由项、物流单据采用批号】
--三个配置均没有启用 商品需要去重
--3 手工指定
IF(@billtype='306')
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='Costing' AND SubValue <>'3' )
	BEGIN
		IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='IsFreeItem' AND SubValue='0' ) AND
		EXISTS (SELECT 1 FROM dbo.Userconfig WHERE ConfigName='mngcargospace' AND Value='0' ) AND
		EXISTS (SELECT 1 FROM dbo.Userconfig WHERE ConfigName='IfUseGoodsNumber' AND Value='0' ) AND @mergeqty = '0'
		BEGIN
			IF EXISTS (SELECT 1 FROM dbo.ImportPtypeTemp1 WHERE etypeid=@userid AND BillType=@billtype AND PtypeId=@PtypeId)
			BEGIN
				SET @ErrMsg = '存在相同的商品编码，不能导入'
				RETURN -1
			END
		END
	END
END
*/

DECLARE @stockid VARCHAR(500),@stockname VARCHAR(100),@cargoid VARCHAR(500),@cargoName VARCHAR(100),@stockidin VARCHAR(500),@stocknamein VARCHAR(500),@cargoidin VARCHAR(500),@cargoNamein VARCHAR(100)
set @stockid=null set @stockname=null set @cargoid=null set @cargoName=NULL SET @stockidin=NULL SET @cargoidin=NULL SET @cargoNamein=NULL SET @stocknamein=NULL

/*
--获取用户的列控制权限
IF EXISTS( select * from LoginUserCol where ETypeID=@userid AND BillType=@billtype AND ColDataField='mqty')--数量
BEGIN
IF(@StrQty <> '')
BEGIN
        IF(@billtype='140' or @billtype='141' or @billtype='144' or @billtype='145')
		SET @ErrMsg = '当前操作员没有修改数量的权限'
		RETURN -1	 
END
END
*/
--单价
IF(@StrPrice <> '')
BEGIN
	--导入单价类型
	DECLARE @importpricetype VARCHAR(1)
	DECLARE @pricetype VARCHAR(10)
	SET @importpricetype='0'
	SET @pricetype='单价'
	--销售
	IF(@billtype='11' or @billtype='300' or @billtype='45' or @billtype='402 'or @billtype='403')
	BEGIN
		SELECT @importpricetype=Value FROM dbo.Userconfig WHERE ConfigName='setsalebilltempletpricetype'
		SET @pricetype='销售单价'
	END
	--采购
	ELSE IF(@billtype='6' OR @billtype='34' or @billtype='301' or @billtype='400')
	BEGIN
		SELECT @importpricetype=Value FROM dbo.Userconfig WHERE ConfigName='setbuybilltempletpricetype'
		SET @pricetype='采购单价'
	END
	--获取用户的列控制权限
	IF EXISTS(	select * from LoginUserCol 
				where ETypeID=@userid AND BillType=@billtype 
						AND ColDataField=
						CASE @importpricetype 
						WHEN '0' THEN 'curmsaleprice' 
						WHEN '1' THEN 'curmdiscountprice' 
						WHEN '2' THEN 'curmtaxprice' END)
	BEGIN
		SET @ErrMsg = '当前操作员没有修改'+CASE @importpricetype 
						WHEN '0' THEN @pricetype 
						WHEN '1' THEN '折后单价' 
						WHEN '2' THEN '含税单价' END
						+'的权限'
		RETURN -1	 
	END
END

IF(@StrDiscount <> '')
BEGIN
IF EXISTS( select * from LoginUserCol where ETypeID=@userid AND BillType=@billtype AND ColDataField='discount')--扣率
BEGIN
		SET @ErrMsg = '当前操作员没有修改扣率的权限'
		RETURN -1	
END
END

IF(@StrTax <> '')
BEGIN
IF EXISTS( select * from LoginUserCol where ETypeID=@userid AND BillType=@billtype AND ColDataField='tax')--税率
BEGIN

		SET @ErrMsg = '当前操作员没有修改税率的权限'
		RETURN -1	
END
END

IF @billtype = '17' OR @billtype = '21' OR @billtype = '327'
BEGIN
IF NOT EXISTS (select * from Qp_MulStockConfig where BillType=@billtype and IsChecked=1 )AND (@StrStock <> '' OR @StrStockIn <> '')
BEGIN
        SET @ErrMsg = '该单据未启用多仓库，明细仓库请不要填写'
		RETURN -1	
END
ELSE IF EXISTS (select * from Qp_MulStockConfig where BillType=@billtype and IsChecked=1 )
BEGIN

IF @StrStock='' AND @CargoUserCode <> ''
BEGIN
		SET @ErrMsg = '启用了多仓库，填写了出库货位编号，则必须填写出库仓库'
		RETURN -1
END
IF @StrStockin='' AND @CargoUserCodein <> ''
BEGIN
		SET @ErrMsg = '启用了多仓库，填写了入库货位编号，则必须填写入库仓库'
		RETURN -1
END

IF (@StrStock <> '' or @StrStockIn <> '')
BEGIN
--1，判断出/入仓库编号是否存在
IF @StrStock <> '' and NOT EXISTS(select typeId from STOCK where UserCode=@StrStock AND typeId <> '00000')
BEGIN
        SET @ErrMsg = '出库仓库编号不存在'
		RETURN -1
END
ELSE IF @StrStockIn <> '' AND NOT EXISTS(select typeId from STOCK where UserCode=@StrStockIn AND typeId <> '00000')
BEGIN
		SET @ErrMsg = '入库仓库编号不存在'
		RETURN -1
END
--2，是否为父节点
IF @StrStock <> '' and EXISTS (SELECT TOP 1 typeid FROM dbo.Stock WHERE UserCode=@StrStock AND sonnum > 0)
BEGIN
		SET @ErrMsg = '该出仓库为父节点，不能导入'
		RETURN -1
END
ELSE IF @StrStockIn <> '' AND  EXISTS (SELECT TOP 1 typeid FROM dbo.Stock WHERE UserCode=@StrStockIn AND sonnum > 0)
BEGIN
		SET @ErrMsg = '该入仓库为父节点，不能导入'
		RETURN -1
END
--获取出入库ID
select @stockid=typeid,@stockname=fullname from STOCK where UserCode=@StrStock

select @stockidin=typeid,@stocknamein=fullname from STOCK where UserCode=@StrStockIn

--3，判断操作员多级权限
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @userid AND MangerKTypeID = '00000')
OR EXISTS(SELECT TOP 1 1 FROM KType_L WHERE ETypeId=@userid AND  @stockid LIKE typeid+'%' OR @stockidin LIKE typeid+'%')
		SET @ErrMsg = ''
ELSE
BEGIN
        SET @ErrMsg = '操作员没有该仓库权限'
		RETURN -1
END
--4，判断是否是父节点仓库
IF @StrStock <> '' AND  EXISTS (select * from stock where UserCode=@StrStock and leveal=0)
BEGIN
        SET @ErrMsg = '该出仓库为父节点仓库不能导入'
		RETURN -1
END 
ELSE if @StrStockIn <> '' AND EXISTS (select * from stock where UserCode=@StrStockIn and leveal=0)
BEGIN
		SET @ErrMsg = '该入仓库为父节点仓库不能导入'
		RETURN -1
END
--5，判断是否是停用仓库
IF @StrStock<>'' and EXISTS (select * from stock where UserCode=@StrStock and deleted=1)
BEGIN
        SET @ErrMsg = '该出仓库已经停用不能导入'
		RETURN -1
END 
ELSE IF @StrStockIn <> '' AND   EXISTS (select * from stock where UserCode=@StrStockIn and deleted=1)
BEGIN
		SET @ErrMsg = '该入仓库已经停用不能导入'
		RETURN -1
END

IF @StrStock <> '' AND NOT EXISTS(select * from stock where UserCode=@StrStock and STypeID=@formStype)
BEGIN
        SET @ErrMsg = '该出库仓库不属于表头分支机构'
		RETURN -1
END
IF @StrStockIn <> '' AND  NOT EXISTS(select * from stock where UserCode=@StrStockIn and STypeID=@formStype)
BEGIN
        SET @ErrMsg = '该入库仓库不属于表头分支机构'
		RETURN -1
END

--货位调整
IF @isUseCarGo='启用'
BEGIN
    IF @StrStock <> @StrStockIn
    BEGIN
        SET @ErrMsg = '启用货位调整，出库仓库必须和入库仓库一样'
		RETURN -1
    END
END
ELSE IF @isUseCarGo = '未启用'
BEGIN
    IF @StrStock = @StrStockIn
    BEGIN
        SET @ErrMsg = '未启用货位调整，出库仓库必须和入库仓库不一样'
		RETURN -1
    END
END

--通过所有验证
--select @cargoid=CargoID,@cargoName=FullName from CargoType where KtypeID=@stockid and IsDefault=1
--select @cargoidin=CargoID,@cargoNamein=FullName from CargoType where KtypeID=@stockidin and IsDefault=1

END
END
END

--货位验证
IF (@billtype = '17' OR @billtype = '21' or @billtype = '327')
BEGIN
IF EXISTS(select ConfigNo from Userconfig where ConfigName='mngcargospace' and Value=1)
BEGIN
--启用了货位管理，
IF (@CargoUserCode <> '' OR @CargoUserCodeIn <> '')
BEGIN
--用户没有填写明细仓库，如果用户填写了货位，货位必须与表头仓库对应
IF @CargoUserCode <> '' AND @StrStock = '' AND (SELECT KtypeID FROM dbo.CargoType WHERE UserCode=@CargoUserCode)<>@billindexStock
BEGIN
    SET @ErrMsg = '没有启用多仓库，出库货位必须与表头出库仓库对应!'
	RETURN -1
END
IF @CargoUserCodein <> '' AND @StrStockIn = '' AND (SELECT KtypeID FROM dbo.CargoType WHERE UserCode=@CargoUserCodeIn)<>@billindexStockin
BEGIN
    SET @ErrMsg = '没有启用多仓库，入库货位必须与表头入库仓库对应!'
	RETURN -1
END



IF @CargoUserCode <> '' and NOT EXISTS(SELECT KtypeID,CargoID FROM dbo.CargoType WHERE UserCode = @CargoUserCode)
BEGIN
		SET @ErrMsg = '出库货位不存在或者出库货位名称与编号不匹配!'
		RETURN -1
END
IF @CargoUserCodein <> '' and NOT EXISTS(SELECT KtypeID,CargoID FROM dbo.CargoType WHERE UserCode = @CargoUserCodeIn)
BEGIN
		SET @ErrMsg = '入库货位不存在或者入库货位名称与编号不匹配!'
		RETURN -1
END

IF @CargoUserCode <> '' AND @StrStock <> '' AND (SELECT UserCode FROM dbo.Stock WHERE typeId IN (SELECT KtypeID FROM dbo.CargoType WHERE UserCode=@CargoUserCode))<>@StrStock
BEGIN
		SET @ErrMsg = '填写出库货位不属于填写出库仓库!'
		RETURN -1
END
IF @CargoUserCodeIn <> '' AND @StrStockIn <> '' AND (SELECT UserCode FROM dbo.Stock WHERE typeId IN ( SELECT KtypeID FROM dbo.CargoType WHERE UserCode=@CargoUserCodeIn))<>@StrStockIn
BEGIN
		SET @ErrMsg = '填写入库货位不属于填写入库仓库!'
		RETURN -1
END

IF @CargoUserCode <> '' AND NOT EXISTS (SELECT CargoID FROM dbo.CargoType WHERE UserCode=@CargoUserCode)
BEGIN
		SET @ErrMsg = '出库货位信息有误!'
		RETURN -1
END
IF @CargoUserCodeIn <> '' AND NOT EXISTS (SELECT CargoID FROM dbo.CargoType WHERE UserCode=@CargoUserCodeIn)
BEGIN
		SET @ErrMsg = '入库货位信息有误!'
		RETURN -1
END

IF @isUseCarGo = '启用'
BEGIN
		IF @CargoUserCode =@CargoUserCodeIn
		BEGIN
		    SET @ErrMsg = '出库货位编号和入库货位编号不能一样'
			RETURN -1
		END
END


    set @cargoid=(SELECT CargoID FROM dbo.CargoType WHERE UserCode=@CargoUserCode)
	SET @cargoName=(SELECT FullName FROM dbo.CargoType WHERE UserCode=@CargoUserCode)
    SET @cargoidin=(SELECT CargoID FROM dbo.CargoType WHERE UserCode=@CargoUserCodeIn)
	SET @cargoNamein=(SELECT FullName FROM dbo.CargoType WHERE UserCode=@CargoUserCodeIn)
END

END
ELSE
BEGIN
--没有启用货位，取默认货位，（如果填写了货位，则非法）
IF @CargoUserCode<>'' OR @CargoUserCodeIn<>''
BEGIN
    SET @ErrMsg='系统没有启用货位, 不能填写货位!'
    RETURN -1;
END
	 select @cargoid=CargoID,@cargoName=FullName from CargoType where KtypeID=@stockid and IsDefault=1
	 SELECT @cargoidin=CargoID,@cargoNamein=FullName from CargoType where KtypeID=@stockidin and IsDefault=1
	
END
END



IF( (@billtype='34' or @billtype='300' or  @billtype='11' or  @billtype='301' or  @billtype='6' or  @billtype='45' or  @billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141' or @billtype='45' or @billtype='400' or @billtype='402' or @billtype='401' or @billtype='403'  OR @billtype = '126' OR @billtype='139') and @StrStock <> '')--采购入库单(验证仓库的合法性)
BEGIN

--(1)判断是否启用仓库
IF NOT EXISTS (select * from Qp_MulStockConfig where BillType=@billtype and IsChecked=1 ) 
BEGIN
        SET @ErrMsg = '该单据未启用多仓库'
		RETURN -1	
END
ELSE
BEGIN
--(1)判断仓库的编号是否存在
IF NOT EXISTS(select typeId from STOCK where UserCode=@StrStock AND typeId <> '00000')
BEGIN
        SET @ErrMsg = '仓库编号不存在'
		RETURN -1
END

 IF EXISTS (SELECT TOP 1 typeid FROM dbo.Stock WHERE UserCode=@StrStock AND sonnum > 0)
 BEGIN
	SET @ErrMsg = '该仓库为父节点，不能导入'
	RETURN -1
 END

select @stockid=typeid,@stockname=fullname from STOCK where UserCode=@StrStock
--(2)判断操作员多级权限
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @userid AND MangerKTypeID = '00000')
OR EXISTS(SELECT TOP 1 1 FROM KType_L WHERE ETypeId=@userid AND  @stockid LIKE typeid+'%')
--有权限
 --SET @ErrMsg = '存在权限'
 SET @ErrMsg = ''
ELSE
BEGIN
        SET @ErrMsg = '操作员没有该仓库权限'
		RETURN -1
END


--判断是否是该分支机构下的仓库
--print(@formStype)
IF NOT EXISTS(select * from stock where UserCode=@StrStock and STypeID=@formStype)
BEGIN
        SET @ErrMsg = '该仓库不属于表头分支机构'
		RETURN -1
END
--判断是否是父节点仓库
IF EXISTS (select * from stock where UserCode=@StrStock and leveal=0)
BEGIN
        SET @ErrMsg = '该仓库为父节点仓库不能导入'
		RETURN -1
END
--判断是否是停用仓库
IF EXISTS (select * from stock where UserCode=@StrStock and deleted=1)
BEGIN
        SET @ErrMsg = '该仓库已经停用不能导入'
		RETURN -1
END



--(3)通过了所有的验证
IF EXISTS(select ConfigNo from Userconfig where ConfigName='mngcargospace' and Value=1)
BEGIN
set @cargoid=null
set @cargoName=null
END
ELSE
BEGIN
select @cargoid=CargoID,@cargoName=usercode from CargoType where KtypeID=@stockid and IsDefault=1
END

END

END


IF EXISTS(select ConfigNo from Userconfig where ConfigName='mngcargospace' and Value=0)
BEGIN
   
   IF(@billtype='306')
   select @cargoid=CargoID,@cargoName=usercode from CargoType where KtypeID=@formstock and IsDefault=1
	
END

--报损单
IF @billtype='9' or @billtype ='14'
BEGIN
IF EXISTS(select ConfigNo from Userconfig where ConfigName='mngcargospace' and Value=1)
BEGIN
		IF @CargoUserCode <> ''
		BEGIN
			IF NOT EXISTS(SELECT KtypeID,CargoID FROM dbo.CargoType WHERE UserCode = @CargoUserCode)
			BEGIN
					SET @ErrMsg = '货位不存在或者货位名称与编号不匹配!'
					RETURN -1
			END

			IF (SELECT KtypeID FROM dbo.CargoType WHERE UserCode=@CargoUserCode)<>@billindexStock
			BEGIN
					SET @ErrMsg = '填写货位不属于表头仓库!'
					RETURN -1
			END
		END
		
		set @cargoid=(SELECT CargoID FROM dbo.CargoType WHERE UserCode=@CargoUserCode)
		set @cargoName=(SELECT FullName FROM dbo.CargoType WHERE UserCode=@CargoUserCode)
END
ELSE
BEGIN
    IF @CargoUserCode <> ''
		BEGIN
		    SET @ErrMsg = '系统没有启用货位, 不能填写货位!'
			RETURN -1
		END
	select @cargoid=CargoID,@cargoName=usercode from CargoType where KtypeID=@billindexStock and IsDefault=1
END
END
/*********************全面修改表体通用导入小数位数检测*****************/
DECLARE 
                                                              
------------------------- ----------------- -------------------- -----
@d_qty                     VARCHAR(5),  --  数量小数位数               1
@d_price                   VARCHAR(5),  --  单价小数位数               2
@d_discount                VARCHAR(5),  --  扣率小数位数               4
@d_tax                     VARCHAR(5),  --  税率小数位数               5
--@d_total                   VARCHAR(5),  --  金额小数位数               3
--@d_exchangeRate            VARCHAR(5),  --  汇率小数位数               6
--@d_percentage              VARCHAR(5),  --  百分比小数位数             7
--@d_translateRate           VARCHAR(5),  --  换算率小数位数             8
                                                              
------------------------- ----------------- -------------------- -----
@d_qty1                    INT,         --  数量小数位数               1
@d_price1                  INT,         --  单价小数位数               2
@d_discount1               INT,         --  扣率小数位数               4
@d_tax1                    INT;         --  税率小数位数               5
--@d_total1                  INT,         --  金额小数位数               3
--@d_exchangeRate1           INT,         --  汇率小数位数               6
--@d_percentage1             INT,         --  百分比小数位数             7
--@d_translateRate1          INT;         --  换算率小数位数             8

                          
SELECT @d_qty              = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 1
SELECT @d_price            = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 2
SELECT @d_discount         = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 4
SELECT @d_tax              = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 5
--SELECT @d_total            = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 3
--SELECT @d_exchangeRate     = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 6
--SELECT @d_percentage       = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 7
--SELECT @d_translateRate    = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 8

SET @d_qty1                = CONVERT(INT,@d_qty)
SET @d_price1              = CONVERT(INT,@d_price)
SET @d_discount1           = CONVERT(INT,@d_discount)
SET @d_tax1                = CONVERT(INT,@d_tax)
--SET @d_total1              = CONVERT(INT,@d_total)
--SET @d_exchangeRate1       = CONVERT(INT,@d_exchangeRate)
--SET @d_percentage1         = CONVERT(INT,@d_percentage)
--SET @d_translateRate1      = CONVERT(INT,@d_translateRate)
/*********************全面修改表体通用导入小数位数检测*****************/

DECLARE @Qty  NUMERIC(24, 10) 
IF(@billtype='34' or @billtype='301' or @billtype='6' or  @billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141' or @billtype='400' or @billtype='401')--采购入库单
BEGIN
--验证数量
IF (@StrQty = '')
BEGIN
    IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
    BEGIN
    SET @ErrMsg = '请输入采购数量'
	RETURN -1
    END
    ELSE
    BEGIN
	SET @ErrMsg = '请输入采购数量'
	RETURN -1
	END
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
		     IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
		     BEGIN
				SET @ErrMsg = '采购数量请输入数字'
				RETURN -1
		     END
		     ELSE IF (@billtype='126')
		     BEGIN
				SET @ErrMsg = '数量请输入数字'
				RETURN -1
		     END 
		     ELSE
		     BEGIN
				 SET @ErrMsg = '采购数量请输入数字'
				 RETURN -1
			 END
		END
	ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
		BEGIN
		IF(@billtype='144' or  @billtype='145')
	     BEGIN
			 SET @ErrMsg = '采购数量不能为负数'
			 RETURN -1
	     END
        ELSE IF (@billtype='126')
	     BEGIN
			SET @ErrMsg = '数量不能为负数'
			RETURN -1
	     END 
		ELSE
		 BEGIN
			SET @ErrMsg = '采购数量不能为负数'
			RETURN -1
		 END
		END
	ELSE
		BEGIN
			--IF(LEN(@StrQty)>14)
			--BEGIN
			--	IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
			--	 BEGIN
			--	  SET @ErrMsg = '数量总长度不能大于14位数'
			--	 RETURN -1
			--	 END
			--	 ELSE
			--	 BEGIN
			--		SET @ErrMsg = '采购数量总长度不能大于14位数'
			--		RETURN -1
			--	 END
			--END
			IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
			BEGIN
				IF(LEN(substring(@StrQty,0,charindex('.',@StrQty)))>10)
				BEGIN
				
					SET @ErrMsg = '采购数量不能超出10位数'
					RETURN -1
				END
			END
			IF(charindex('.',@StrQty)>0)
			BEGIN
				select @weicount=len(@StrQty)-charindex('.',@StrQty)
				--SELECT @d_qty1
				IF(CONVERT(INT,@weicount) > @d_qty1  )
				BEGIN
					IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
					BEGIN
						SET @ErrMsg = '采购数量小数位数不能超出'+@d_qty+'位'
						RETURN -1
					END
					ELSE
					BEGIN
						SET @ErrMsg = '采购数量小数位数不能超出'+@d_qty+'位'
						RETURN -1
					END
				END
			END
			

			IF(len(@StrQty)-charindex('.',@StrQty)>14)
			BEGIN
				SET @ErrMsg = '采购数量位数超长，整数位数不能超过14位，小数位数不能超过10位'
				RETURN -1
			END 
	
			SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
			IF(@Qty <=0)
			BEGIN
			IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
		     BEGIN
		      SET @ErrMsg = '采购数量不能小于等于0'
			 RETURN -1
		     END
		     ELSE
		     BEGIN
				SET @ErrMsg = '采购数量不能为0'
				RETURN -1
		     END
			END
		END

END
--验证数量
END


--变价调拨单 验证调拨价格
IF(@billtype='21')
BEGIN
	--IF(@StrPrice = '')
	--BEGIN
	--	SET @ErrMsg = '请输入调拨价格'
	--	RETURN -1
	--END
	IF(ISNUMERIC(@StrPrice) = 1 )
	BEGIN
		DECLARE @StrPrice1  NUMERIC(24, 10) 
		SET @StrPrice1 = CONVERT( NUMERIC(24, 10) ,@StrPrice)
		IF(@StrPrice1 <=0)
			BEGIN
				SET @ErrMsg = '调拨价格不能小于等于0'
				RETURN -1
			END
		
		IF(charindex('.',@StrPrice)>0)
		BEGIN
			select @weicount=len(@StrPrice)-charindex('.',@StrPrice)
			IF(CONVERT(INT,@weicount) > @d_price1  )
				BEGIN
					SET @ErrMsg = '调拨价格小数位数不能超出'+@d_price+'位'
					RETURN -1
				END
		END
	END
END

--门店配送单 验证配送价格
IF(@billtype='21')
BEGIN
	--IF(@StrPrice = '')
	--BEGIN
	--	SET @ErrMsg = '请输入调拨价格'
	--	RETURN -1
	--END
	IF(ISNUMERIC(@StrPrice) = 1 )
	BEGIN
		DECLARE @StrPrice2  NUMERIC(24, 10) 
		SET @StrPrice2 = CONVERT( NUMERIC(24, 10) ,@StrPrice)
		IF(@StrPrice2 <=0)
			BEGIN
				SET @ErrMsg = '配送价格不能小于等于0'
				RETURN -1
			END
		
		IF(charindex('.',@StrPrice)>0)
		BEGIN
			select @weicount=len(@StrPrice)-charindex('.',@StrPrice)
			IF(CONVERT(INT,@weicount) > @d_price1  )
				BEGIN
					SET @ErrMsg = '配送价格小数位数不能超出'+@d_price+'位'
					RETURN -1
				END
		END
	END
END

IF(@billtype='34' or @billtype='301' or @billtype='6'  or @billtype='144' or  @billtype='145' or @billtype='140'  or  @billtype='141' or @billtype='400' or @billtype='401')--采购入库单
BEGIN

--IF(@billtype='144' or  @billtype='145')
--BEGIN
--IF(@StrPrice = '')
--BEGIN
--	SET @ErrMsg = '请输入单价'
--	RETURN -1
--END
--END

IF (@StrPrice <> '')
BEGIN
	IF(ISNUMERIC(@StrPrice) <> 1)
		BEGIN
		    IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
		     BEGIN
		      SET @ErrMsg = '采购单价请输入数字'
			 RETURN -1
		     END
		     ELSE
		     BEGIN
			SET @ErrMsg = '采购单价请输入数字'
			RETURN -1
			END
		END
	ELSE IF((SELECT CHARINDEX('-', @StrPrice)) <> 0)
		BEGIN
		     IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
		     BEGIN
		      SET @ErrMsg = '采购单价不能为负数'
			 RETURN -1
		     END
		     ELSE
		     BEGIN
			SET @ErrMsg = '采购单价不能为负数'
			RETURN -1
			END
		END
		
		IF(charindex('.',@StrPrice) <> 0)
		BEGIN
		select @weicount=len(@StrPrice)-charindex('.',@StrPrice)
		IF(CONVERT(INT,@weicount) > @d_price1 )
		BEGIN
		    IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
		     BEGIN
		      SET @ErrMsg = '采购单价小数位数不能超出'+@d_price+'位'
			 RETURN -1
		     END
		     ELSE
		     BEGIN
			SET @ErrMsg = '采购单价小数位数不能超出'+@d_price+'位'
			RETURN -1
			END
		END
		
		IF(LEN(substring(@StrPrice,0,charindex('.',@StrPrice)))>10)
		BEGIN
		    IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141')
		     BEGIN
		      SET @ErrMsg = '采购单价不能超出10位数'
			 RETURN -1
		     END
		     ELSE
		     BEGIN
			SET @ErrMsg = '采购单价不能超出10位数'
			RETURN -1
			END
		END
		END

		
		
		
END
END

IF(@billtype='11' OR @billtype = '34' )
BEGIN
	IF(@State<>'' AND @State<>'赠品')
	BEGIN
		SET @ErrMsg = '状态列为空和赠品之外其他内容时不支持导入'
		RETURN -1
	END 
	ELSE
	BEGIN
		IF(@State = '赠品')
			SET @State = '1'
		ELSE
			SET @State = '0'
	END 
	IF(@State = '1' AND @StrPrice = '')
		SET @StrPrice = '0'

	IF(@State = '1' AND @StrPrice<>'' AND @StrPrice<>'0')
	BEGIN
		SET @ErrMsg = '商品为赠品时单价必须为0'
		RETURN -1
	END 
END 
else
begin 
	set @State = 0
end




IF(@billtype='11' or @billtype='300' or  @billtype='45' or @billtype='402' or @billtype='403')--销售出库单
BEGIN
--验证数量
IF (@StrQty = '')
BEGIN
	SET @ErrMsg = '请输入销售数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
			SET @ErrMsg = '销售数量请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
		BEGIN
			SET @ErrMsg = '销售数量不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
			IF(@Qty <=0)
			BEGIN
				SET @ErrMsg = '销售数量不能小于等于0'
				RETURN -1
			END
		END
		IF(charindex('.',@StrQty)>0)
		BEGIN
		select @weicount=len(@StrQty)-charindex('.',@StrQty)
		IF(CONVERT(INT,@weicount) > @d_qty1 )
		BEGIN
			SET @ErrMsg = '销售数量小数位数不能超出'+@d_qty+'位'
			RETURN -1
		END
		END
		
	
		
		
		
END
--验证数量
END


IF(@billtype='11' or @billtype='300' or  @billtype='45' or @billtype='402' or @billtype='403')--销售出库单
BEGIN
IF (@StrPrice <> '')
BEGIN
	IF(ISNUMERIC(@StrPrice) <> 1)
		BEGIN
			SET @ErrMsg = '销售单价请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrPrice)) <> 0)
		BEGIN
			SET @ErrMsg = '销售单价不能为负数'
			RETURN -1
		END
		
		IF(charindex('.',@StrPrice) <> 0)
		BEGIN
		select @weicount=len(@StrPrice)-charindex('.',@StrPrice)
		IF(CONVERT(INT,@weicount) > @d_price1 )
		BEGIN
			SET @ErrMsg = '销售单价小数位数不能超出'+@d_price+'位'
			RETURN -1
		END
		END
			
		IF(LEN(substring(@StrPrice,0,charindex('.',@StrPrice)))>10)
		BEGIN
			SET @ErrMsg = '销售单价不能超出10位数'
			RETURN -1
		END

		
		
		
		
END
END




IF(@billtype='17' OR @billtype='21' OR @billtype='9' OR @billtype='14')--同价/变价调拨单
BEGIN
	--验证数量
	IF (@StrQty = '')
	BEGIN
		SET @ErrMsg = '请输入库存数量'
		RETURN -1
	END
	ELSE
	BEGIN
		IF(ISNUMERIC(@StrQty) <> 1)
			BEGIN
				SET @ErrMsg = '库存数量请输入数字'
				RETURN -1
			END
		ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
			BEGIN
				SET @ErrMsg = '库存数量不能为负数'
				RETURN -1
			END
		ELSE
			BEGIN
				SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
				IF(@Qty <=0)
				BEGIN
					SET @ErrMsg = '库存数量不能小于等于0'
					RETURN -1
				END
			END
			IF(charindex('.',@StrQty)>0)
			BEGIN
			select @weicount=len(@StrQty)-charindex('.',@StrQty)
			IF(CONVERT(INT,@weicount) > @d_qty1 )
			BEGIN
				SET @ErrMsg = '库存数量小数位数不能超出'+@d_qty+'位'
				RETURN -1
			END
			END
	END
	--验证数量
END

IF(@billtype='327')--门店配送单
BEGIN
	--验证数量
	IF (@StrQty = '')
	BEGIN
		SET @ErrMsg = '请输入配送数量'
		RETURN -1
	END
	ELSE
	BEGIN
		IF(ISNUMERIC(@StrQty) <> 1)
			BEGIN
				SET @ErrMsg = '配送数量请输入数字'
				RETURN -1
			END
		ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
			BEGIN
				SET @ErrMsg = '配送数量不能为负数'
				RETURN -1
			END
		ELSE
			BEGIN
				SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
				IF(@Qty <=0)
				BEGIN
					SET @ErrMsg = '配送数量不能小于等于0'
					RETURN -1
				END
			END
			IF(charindex('.',@StrQty)>0)
			BEGIN
			select @weicount=len(@StrQty)-charindex('.',@StrQty)
			IF(CONVERT(INT,@weicount) > @d_qty1 )
			BEGIN
				SET @ErrMsg = '配送数量小数位数不能超出'+@d_qty+'位'
				RETURN -1
			END
			END
	END
	--验证数量
END


IF ( @billtype = '126' OR @billtype = '139')--赠送单/获赠单
    BEGIN
--验证数量
        IF ( @StrQty = '' )
            BEGIN
                SET @ErrMsg = '请输入数量';
                RETURN -1;
            END;
        ELSE
            BEGIN
                IF ( ISNUMERIC(@StrQty) <> 1 )
                    BEGIN
                        SET @ErrMsg = '数量请输入数字';
                        RETURN -1;
                    END;
                ELSE
                    IF ( ( SELECT   CHARINDEX('-', @StrQty)
                         ) <> 0 )
                        BEGIN
                            SET @ErrMsg = '数量不能为负数';
                            RETURN -1;
                        END;
                    ELSE
                        BEGIN
                            SET @Qty = CONVERT(NUMERIC(24, 10), @StrQty);
                            IF ( @Qty <= 0 )
                                BEGIN
                                    SET @ErrMsg = '数量不能小于等于0';
                                    RETURN -1;
                                END;
                        END;
                IF ( CHARINDEX('.', @StrQty) > 0 )
                    BEGIN
                        SELECT  @weicount = LEN(@StrQty) - CHARINDEX('.',
                                                              @StrQty);
                        IF ( CONVERT(INT, @weicount) > @d_qty1 )
                            BEGIN
                                SET @ErrMsg = '数量小数位数不能超出' + @d_qty + '位';
                                RETURN -1;
                            END;
                    END;
            END;
--验证数量
    END;





IF(@billtype='306')--
BEGIN
--验证数量
IF (@StrQty = '')
BEGIN
	SET @ErrMsg = '请输入库存盘点数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
			SET @ErrMsg = '库存盘点数量请输入数字'
			RETURN -1
		END
	ELSE
		BEGIN
			IF(charindex('.',@StrQty)>0)
			BEGIN
				select @weicount=len(@StrQty)-charindex('.',@StrQty)
				IF(CONVERT(INT,@weicount) > @d_qty1 )
				BEGIN
					SET @ErrMsg = '库存盘点数量小数位数不能超出'+@d_qty+'位'
					RETURN -1
				END
			END
		END
	SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)

END
--验证数量
END

IF( @Qty > @maxQty)
BEGIN
	IF(@billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141' OR @billtype='301' OR @billtype='6'  OR @billtype='401')
	BEGIN
		SET @ErrMsg = '采购数量不能大于'+@maxQty1
		RETURN -1
	END
	IF(@billtype='11' or @billtype='300' or  @billtype='45' or @billtype='402' or @billtype='403')
	BEGIN
		SET @ErrMsg = '销售数量不能大于'+@maxQty1
		RETURN -1
	END
	IF (@billtype ='306')
	BEGIN
		SET @ErrMsg = '库存盘点数量不能大于'+@maxQty1
		RETURN -1
	END
	
	IF(@billtype='17' OR @billtype='21')
	BEGIN
		SET @ErrMsg = '库存盘点数量不能大于'+@maxQty1
		RETURN -1
	END
	
	IF(@billtype='327')
	BEGIN
		SET @ErrMsg = '配送数量不能大于'+@maxQty1
		RETURN -1
	END
	
	SET @ErrMsg = '数量不能大于'+@maxQty1
	RETURN -1
END

--IF(@ProduceDate <> '' and @billtype='306')
--BEGIN
--  select @flagint=isdate(@ProduceDate)
--  IF(@flagint=0)
--  BEGIN
--    SET @ErrMsg = '生产日期必须为yyyy-mm-dd日期格式'
--    RETURN -1
--  END
--  select @flagint=len(@ProduceDate)
--  IF(@flagint <>  10)
--  BEGIN
--    SET @ErrMsg = '生产日期必须为yyyy-mm-dd日期格式'
--    RETURN -1
--  END
  
--  BEGIN TRY
--  select dbo.getDateFormat1(@ProduceDate)
--  END TRY
--  BEGIN CATCH
--    SET @ErrMsg = '生产日期必须为yyyy-mm-dd日期格式'
--    RETURN -1
--  END CATCH
--END


IF(@billtype='306')
BEGIN
	DECLARE @Costing  INT
	SELECT @Costing = SubValue FROM dbo.sysdata WHERE SubName='Costing'

  IF(@ProduceDate <> '')
  BEGIN
	  IF @Costing <> 3 AND @Costing <> 0
	  BEGIN
		 SET @ErrMsg = '非手工指定成本算法下不能填写生产日期'
		 RETURN -1
	  END
	  IF NOT EXISTS( SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName ='IfUseProduceDate' AND Value='1')
	  BEGIN
		SET @ErrMsg = '系统未启用物流单据商品采用生产日期，不能填写生产日期'
		RETURN -1
	  END
	  select @flagint=isdate(@ProduceDate)
	 
	  IF(@flagint=0)
	  BEGIN
		SET @ErrMsg = '生产日期必须为yyyy-mm-dd日期格式'
		RETURN -1
	  END
	  select @flagint=len(@ProduceDate)
	  IF(@flagint <>  10)
	  BEGIN
		SET @ErrMsg = '生产日期必须为yyyy-mm-dd日期格式'
		RETURN -1
	  END
	  
	   select @flagint=charindex('-',@ProduceDate)
	  IF( @flagint = 0 )
	  BEGIN
		SET @ErrMsg = '生产日期必须为yyyy-mm-dd日期格式'
		RETURN -1
	  END
  
	  
  END
  
  
  if(@ValidDate <> '')
  BEGIN
	  IF @Costing <> 3 AND @Costing <> 0
	  BEGIN
		 SET @ErrMsg = '非手工指定成本算法下不能填写效期至'
		 RETURN -1
	  END
	  IF NOT EXISTS( SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName ='IfUseValidDate' AND Value='1')
	  BEGIN
		SET @ErrMsg = '系统未启用物流单据商品采用效期至，不能填写效期至'
		RETURN -1
	  END
	  select @flagint=isdate(@ValidDate)
	  
	  IF(@flagint=0)
	  BEGIN
		SET @ErrMsg = '效期至必须为yyyy-mm-dd日期格式'
		RETURN -1
	  END
  
  select @flagint=len(@ValidDate)
  
  IF(@flagint <> 10)
  BEGIN
    SET @ErrMsg = '效期至必须为yyyy-mm-dd日期格式'
    RETURN -1
  END
  
   select @flagint=charindex('-',@ValidDate)
  
    IF(@flagint = 0)
	BEGIN
		SET @ErrMsg = '效期至必须为yyyy-mm-dd日期格式'
		RETURN -1
	END
 
  END
  
  
END


IF @billtype = '306'
BEGIN
	IF ( '1' =(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='ifusegoodsnumber' AND Value='0') AND @GoodsNumber <>'' )
	BEGIN
		SET @ErrMsg = '系统没有启用批号，不能填写批号'
		RETURN -1
	END

	IF('1' =(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='ifusegoodsnumber' AND Value='1') AND @GoodsNumber <>'')
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM dbo.ptype WHERE typeId= @ptypeid AND IfUseGoodsNum = 1) 
		BEGIN
			SET @ErrMsg = '商品没有启用批号，不能填写批号'
			RETURN -1
		END
	END
END


IF(len(@StrTax)-charindex('.',@StrTax)>14)
BEGIN
	SET @ErrMsg = '税率位数超长，整数位数不能超过14位，小数位数不能超过10位'
	RETURN -1
END 

--根据不同的格式来验证不同字段
IF(@billtype='11' OR @billtype='34' OR @billtype='300' or  @billtype='301' OR @billtype='6' or  @billtype='45'  or  @billtype='144' or  @billtype='145' or  @billtype='140'  or  @billtype='141' or @billtype='400' or @billtype='402' OR @billtype='401' or @billtype='403')
BEGIN
DECLARE @val VARCHAR(50)
DECLARE @temQty int
SELECT @val=Value FROM Userconfig WHERE ConfigName='gridtype'
IF(@val='1')--税率格式
BEGIN
IF(@StrDiscount <> '')
BEGIN
SET @ErrMsg = '税率格式下折扣未启用'
RETURN -1
END
--IF(@StrTax = '')
--SELECT @StrTax=Value FROM Userconfig WHERE ConfigName='alltaxrate'
IF(@StrTax <> '')
BEGIN
	IF(ISNUMERIC(@StrTax) <> 1)
		BEGIN
			SET @ErrMsg = '税率请输入数字'
			RETURN -1
		END
		
	--IF(len(@StrTax) <> len(replace(@StrTax,'.','')))
	--BEGIN
	-- SET @ErrMsg = '税率不能为小数'
	--		RETURN -1
	--END	
IF((SELECT CHARINDEX('-', @StrTax)) <> 0)
		BEGIN
			SET @ErrMsg = '税率不能为负数'
			RETURN -1
		END
		
		SET @temQty = CONVERT( NUMERIC(24, 10) , @StrTax)
			IF(@temQty < 0  OR @temQty >99)
			BEGIN
				SET @ErrMsg = '税率必须在0到99之间'
				RETURN -1
			END
			IF( dbo.F_CheckDecimal(@StrTax,5,@d_tax1) < 0)
			BEGIN
				SET @ErrMsg = '税率不能超出'+@d_tax+'位数'
				RETURN -1
			END
END
END
IF(@val='2')--折扣格式
BEGIN
IF(@StrTax <> '')
BEGIN
SET @ErrMsg = '折扣格式下税率未启用'
RETURN -1
END
--IF(@StrDiscount = '')
--SELECT @StrDiscount=Value FROM Userconfig WHERE ConfigName='zekouvalue'
IF(@StrDiscount <> '')
BEGIN
IF(ISNUMERIC(@StrDiscount) <> 1)
		BEGIN
			SET @ErrMsg = '折扣请输入数字'
			RETURN -1
		END
		IF((SELECT CHARINDEX('-', @StrDiscount)) <> 0)
		BEGIN
			SET @ErrMsg = '折扣不能为负数'
			RETURN -1
		END
		
		select @weicount=len(@StrDiscount)-charindex('.',@StrDiscount)
		IF(CONVERT(INT,@weicount) > @d_discount1 )
		BEGIN
			SET @ErrMsg = '折扣小数位数不能超出'+@d_discount+'位'
			RETURN -1
		END
		
			SET @temQty = CONVERT( NUMERIC(24, 10) , @StrDiscount)
			IF(@temQty < 0  OR @temQty >9)
			BEGIN
				SET @ErrMsg = '折扣必须在0到10之间'
				RETURN -1
			END
			IF( dbo.F_CheckDecimal(@StrDiscount,4,@d_discount1) < 0)
			BEGIN
				SET @ErrMsg = '折扣不能超出'+@d_discount+'位数'
				RETURN -1
			END

END
END
IF(@val='3')--普通格式(不允许录入税率、扣率，提示未启用)
BEGIN
IF(@StrTax <> '' OR @StrDiscount <> '')
BEGIN
SET @ErrMsg = '普通格式下税率、扣率，未启用'
RETURN -1
END
END
IF(@val='4')--全格式
BEGIN
IF(@StrTax <> '')
BEGIN
IF(ISNUMERIC(@StrTax) <> 1)
		BEGIN
			SET @ErrMsg = '税率请输入数字'
			RETURN -1
		END
 --  IF(len(@StrTax) <> len(replace(@StrTax,'.','')))
	--BEGIN
	-- SET @ErrMsg = '税率不能为小数'
	--		RETURN -1
	--END	
IF((SELECT CHARINDEX('-', @StrTax)) <> 0)
		BEGIN
			SET @ErrMsg = '税率不能为负数'
			RETURN -1
		END
		
		SET @temQty = CONVERT( NUMERIC(24, 10) , @StrTax)
			IF(@temQty < 0  OR @temQty >99 )
			BEGIN
				SET @ErrMsg = '税率必须在0到99之间'
				RETURN -1
			END
			IF( dbo.F_CheckDecimal(@StrTax,5,@d_tax1) < 0)
			BEGIN
				SET @ErrMsg = '税率不能超出'+@d_tax+'位数'
				RETURN -1
			END
END	
	
IF(@StrDiscount <> '')
BEGIN
	IF(ISNUMERIC(@StrDiscount) <> 1)
		BEGIN
			SET @ErrMsg = '折扣请输入数字'
			RETURN -1
		END
		IF((SELECT CHARINDEX('-', @StrDiscount)) <> 0)
		BEGIN
			SET @ErrMsg = '折扣不能为负数'
			RETURN -1
		END
	
		select @weicount=len(@StrDiscount)-charindex('.',@StrDiscount)
		IF(CONVERT(INT,@weicount) > @d_discount1  )
		BEGIN
			SET @ErrMsg = '折扣小数位数不能超出'+@d_discount+'位'
			RETURN -1
		END
		SET @temQty = CONVERT( NUMERIC(24, 10) , @StrDiscount)
			IF(@temQty < 0  OR @temQty >9)
			BEGIN
				SET @ErrMsg = '折扣必须在0到10之间'
				RETURN -1
			END
END
END

END

IF(@billtype = '34' or @billtype='301' or @billtype='400')
BEGIN
	IF(1 = (SELECT TOP 1 StopBuy FROM dbo.ptype WHERE UserCode = @UserCode))
	BEGIN
		SET @ErrMsg = '该商品已停止采购'
		RETURN -1
	END
END

DECLARE @IsService INT = 0

SELECT @IsService = IsService from dbo.ptype WHERE typeId = @ptypeid

IF(@FullName = '' AND @UserCode <> '')--商品名称为空时(为名车赋值)
BEGIN
SELECT @FullName=fullname FROM PType WHERE UserCode = @UserCode
END
IF(@FullName = '' AND @UserCode = '')
BEGIN
	SELECT TOP 1 @FullName=fullname,@UserCode=UserCode FROM dbo.ptype WHERE TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@StrEntryCode,1)) AND IfUseEntryCode = 1 AND deleted = 0
END

DECLARE @unitstype VARCHAR(66)
SELECT @unitstype=unitstype FROM PType WHERE UserCode = @UserCode


DECLARE @munitid VARCHAR(50)
DECLARE @munit VARCHAR(50)

DECLARE @baseunitid VARCHAR(50)
DECLARE @baseunit VARCHAR(50)

DECLARE @nunitid VARCHAR(50)
DECLARE @nunit VARCHAR(50)

DECLARE @munitrate VARCHAR(50)
DECLARE @unitrate VARCHAR(50)

--获取商品的采购或是销售的默认单位和基本单位以及浮动单位
IF(@billtype = '34' or @billtype='301' or @billtype='6'  or  @billtype='144' or  @billtype='145' or @billtype='400' or @billtype='401' OR @billtype = '126')--采购
BEGIN
SELECT @munitid=BuyUnitId FROM PType WHERE UserCode=@UserCode
SELECT @munit=fullname FROM PType_Units WHERE UnitsId=@munitid
END

IF(@billtype = '11' Or @billtype = '300' or  @billtype='45' or  @billtype='140'  or  @billtype='141' or @billtype='402' or @billtype='403'  OR @billtype = '139')--销售
BEGIN
SELECT @munitid=SaleUnitId FROM PType WHERE UserCode=@UserCode
SELECT @munit=fullname FROM PType_Units WHERE UnitsId=@munitid
END

IF(@billtype = '17' OR @billtype='21' or @billtype='306' OR @billtype='9' OR @billtype='14' or @billtype='327')--同价/变价
BEGIN
SELECT @munitid=StockUnitId FROM PType WHERE UserCode=@UserCode
SELECT @munit=fullname FROM PType_Units WHERE UnitsId=@munitid
END

SELECT @baseunitid=baseUnitId FROM PType WHERE UserCode=@UserCode
SELECT @baseunit=fullname FROM PType_Units WHERE UnitsId=@baseunitid

SELECT @nunitid=AssistantUnitId FROM PType WHERE UserCode=@UserCode
SELECT @nunit=fullname FROM PType_Units WHERE UnitsId=@nunitid

SELECT @munitrate=rate from PType_Units_Ext where PtypeID=@ptypeid and UnitsId=@munitid
SELECT @unitrate=rate from PType_Units_Ext where PtypeID=@ptypeid and RateType=1

DECLARE @ImportTime DATETIME
SELECT @ImportTime = CONVERT(VARCHAR(23), GETDATE(), 121)

DECLARE @ReferPrice  NUMERIC(24, 10) =0
SELECT @ReferPrice = ReferPrice  FROM dbo.PType_Price WHERE PTypeID =@ptypeid

DECLARE @UnitsEntryCode VARCHAR(200)='',@dUnitsId INT 

--销售、采购条形码，单位
IF( @billtype = '11' OR  @billtype = '34' OR @billtype = '300' OR @billtype = '301' OR @billtype='403' OR @billtype = '126' OR @billtype = '139' OR @billtype = '45' OR @billtype = '6')
BEGIN
	IF (@billtype = '11' OR @billtype = '300' OR @billtype='403' OR @billtype = '139' OR @billtype = '45')
	BEGIN
		SELECT @dUnitsId = SaleUnitId FROM dbo.ptype WHERE typeId= @ptypeid
	END
	ELSE
	BEGIN
		SELECT @dUnitsId = BuyUnitId  FROM dbo.ptype WHERE typeId= @ptypeid
	END
	SELECT @UnitsEntryCode = dbo.F_GetAllEntrycode(@ptypeid,@dUnitsId,2)
END
ELSE IF( @billtype = '306')
BEGIN
	SELECT @dUnitsId = StockUnitId  FROM dbo.ptype WHERE typeId= @ptypeid
	SELECT @UnitsEntryCode = dbo.F_GetAllEntrycode(@ptypeid,@dUnitsId,2)
END
ELSE
BEGIN
	SELECT @dUnitsId = baseUnitId FROM dbo.ptype WHERE typeId= @ptypeid
	SELECT @UnitsEntryCode = dbo.F_GetAllEntrycode(@ptypeid,@dUnitsId,2)
END
SET @StrTax = LTRIM(RTRIM(@StrTax))
IF ( (@val='1' OR @val = '4' ) AND @StrTax = '' )
BEGIN
	IF @billtype IN ('45','300','11','141','140','403')
	BEGIN
		SELECT @StrTax = SaleDefaultRate FROM dbo.ptype WHERE typeId = @PtypeId
	END
	ELSE IF @billtype IN ('6','34','301','144','145','401')
	BEGIN
		SELECT @StrTax = BuyDefaultRate FROM dbo.ptype WHERE typeId = @PtypeId
	END
END
----------------------------------------------------------------------------------------------
IF(@billtype='306')
BEGIN

/*********************************************************************************************
	修改功能：	A9.8.1新增需求 1.3.2、库存盘点单导入增加货位支持
	修改者：	Liu Fei
	修改日期：	2016.10.27
	*********************************************************************************************/
	IF EXISTS (SELECT 1 FROM Userconfig WHERE ConfigName='mngcargospace' AND Value='1' )
	BEGIN
		IF (@CargoUserCode='' AND @CargoFullName='')
		BEGIN
			SET @ErrMsg = '货位编号和货位名称不能同时为空';
			RETURN -1;
		END
		ELSE
		BEGIN
			IF(@CargoUserCode <> '')
			BEGIN
				IF NOT EXISTS(SELECT CargoID FROM CargoType WHERE UserCode=@CargoUserCode)
				BEGIN
					SET @ErrMsg = '货位编号不存在';
					RETURN -1;
				END
				IF EXISTS (SELECT 1 FROM CargoType WHERE UserCode=@CargoUserCode AND deleted=1)
				BEGIN
					SET @ErrMsg = '该货位已停用';
					RETURN -1;
				END
			END
			IF (@CargoFullName <> '')
			BEGIN
				IF NOT EXISTS(SELECT CargoID FROM CargoType WHERE FullName=@CargoFullName)
				BEGIN
					SET @ErrMsg = '货位名称不存在';
					RETURN -1;
				END
				IF EXISTS (SELECT 1 FROM CargoType WHERE FullName=@CargoFullName AND deleted=1)
				BEGIN
					SET @ErrMsg = '该货位已停用';
					RETURN -1;
				END
			END
			IF(@CargoFullName NOT IN (SELECT FullName FROM CargoType WHERE UserCode=@CargoUserCode) AND @CargoFullName <> '' AND @CargoUserCode <> '')
			BEGIN
				SET @ErrMsg = '货位编号与货位名称不匹配';
				RETURN -1;
			END
			SELECT @cargoid = CargoID,@cargoName=FullName FROM CargoType WHERE UserCode=@CargoUserCode OR FullName=@CargoFullName;
		END
	END


	INSERT INTO dbo.ImportPtypeTemp1
			( etypeid, BillType, PtypeId )
	VALUES  ( @userid, -- etypeid - varchar(50)
			  @billtype, -- BillType - varchar(4)
			  @ptypeid  -- PtypeId - varchar(50)
			  )
END

INSERT INTO importptypetemp(etypeid,BillType,PtypeId,Qty,deleted,ImportTime,StrEntryCode,StrPrice,StrTax,StrDiscount,munitid,munit,baseunitid,baseunit,nunitid,nunit,munitrate,unitrate,unitstype,stockid,stockidin,stockname,stocknamein,cargoid,cargoidin,cargoName,cargoNamein,ProduceDate,ValidDate,GoodsNumber,Comment,IsService,ReferPrice,unitsentrycode,Serial,isGift)  VALUES
(@userid, @billtype, @ptypeid, @Qty, 0, @ImportTime,@StrEntryCode,@StrPrice,@StrTax,@StrDiscount,@munitid,@munit,@baseunitid,@baseunit,@nunitid,@nunit,@munitrate,@unitrate,@unitstype,@stockid,@stockidin,@stockname,@stocknamein,@cargoid,@cargoidin,@cargoName,@cargoNamein,@ProduceDate,@ValidDate,@GoodsNumber,@Comment,@IsService,@ReferPrice,@UnitsEntryCode,@StrSerials,@State)
SET  @ReturnID = @@ROWCOUNT

GO






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


/****** Object:  StoredProcedure [dbo].[Gp_ImportPtypeTemp]    Script Date: 05/20/2011 17:29:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	创 建 者：廖晨羽
	日    期：2011-09-16
	创建原因：导入单据信息
*/
/*	
	修 改 者：廖晨羽
	日    期：2012年4月19日19:28:05
	修改原因：维修接件单无数量列
*/


CREATE               PROCEDURE [dbo].[Gp_ImportPtypeTemp_wxjj]
(
 @UserCode  [varchar](256),
 @FullName   [varchar](66),
 @ReturnID  VARCHAR(100) OUTPUT,
 @ErrMsg VARCHAR(200) OUTPUT,
 @typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
IF(@UserCode = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @UserCode) OR @UserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
ELSE IF (@FullName = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @FullName) OR @FullName='全部商品')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
ELSE IF(@FullName <> (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @UserCode))
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END
ELSE IF(1 = (SELECT TOP 1 deleted FROM dbo.ptype WHERE UserCode = @UserCode))
BEGIN
	SET @ErrMsg = '该商品已停用'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PtypeId  VARCHAR(50)
	DECLARE @ChildCount NUMERIC(18,0)
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @UserCode)
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0)
	BEGIN
		SET @ErrMsg = '该商品为父节点，不能导入'
		RETURN -1	
	END
END

DECLARE @Qty  NUMERIC(24, 10) ,
		@StrQty	VARCHAR(10)
SET @StrQty = '1'

IF (@StrQty = '')
BEGIN
	SET @ErrMsg = '请输入商品数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
			SET @ErrMsg = '商品数量请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
		BEGIN
			SET @ErrMsg = '商品数量不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
			IF(@Qty <=0)
			BEGIN
				SET @ErrMsg = '商品数量不能为0'
				RETURN -1
			END
		END
END

DECLARE @userid VARCHAR(max),@billtype VARCHAR(4)  ---分解操作员ID和单据类型编号
SET @userid = (SELECT TOP 1 A FROM f_split(@typeid,'я'))
SET @billtype = (SELECT A FROM f_split(@typeid,'я') WHERE A <> @userid)

IF (@ptypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@userid)))
BEGIN
	SET @ErrMsg = '操作员没有该商品权限'
	RETURN -1
END

IF(@billtype = '34')
BEGIN
	IF(1 = (SELECT TOP 1 StopBuy FROM dbo.ptype WHERE UserCode = @UserCode))
	BEGIN
		SET @ErrMsg = '该商品已停止采购'
		RETURN -1
	END
END

DECLARE @ImportTime DATETIME
SELECT @ImportTime = CONVERT(VARCHAR(23), GETDATE(), 121)
----------------------------------------------------------------------------------------------
INSERT INTO importptypetemp(etypeid,BillType,PtypeId,Qty,deleted,ImportTime) VALUES
(@userid, @billtype, @ptypeid, @Qty, 0, @ImportTime)

SET  @ReturnID = @@ROWCOUNT

GO



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


/****** Object:  StoredProcedure [dbo].[Gp_ImportPtypeTemp]    Script Date: 05/20/2011 17:29:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	创 建 者：廖晨羽
	日    期：2011-09-16
	创建原因：导入单据信息
*/



CREATE               PROCEDURE [dbo].[Gp_ImportPtypeTempBy647]
(
 @UserCode      [varchar](256),
 @FullName      [varchar](66),
 @StrQty	    [varchar] (18),
 @StrPrice      [varchar](66)='',
 @ReturnID  VARCHAR(100) OUTPUT,
 @ErrMsg VARCHAR(200) OUTPUT,
 @typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PtypeId  VARCHAR(50)
DECLARE @ChildCount NUMERIC(18,0)
-------------------------------------转换输入参数---------------------------------------------

IF(@UserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @UserCode) OR @UserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
ELSE IF (@FullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @FullName) OR @FullName='全部商品')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
ELSE IF(@FullName NOT IN (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @UserCode) AND @FullName <> '' AND @UserCode <> '')
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END

ELSE IF(1 = (SELECT TOP 1 deleted FROM dbo.ptype WHERE UserCode = @UserCode))
BEGIN
	SET @ErrMsg = '该商品已停用'
	RETURN -1
END

ELSE
BEGIN
   
    IF(@UserCode <> '')
    BEGIN
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @UserCode)
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0)
	BEGIN
		SET @ErrMsg = '该商品为父节点，不能导入'
		RETURN -1	
	END

	END
	
END

DECLARE @weicount VARCHAR(50)
DECLARE @temp VARCHAR(200)
DECLARE @userid VARCHAR(max),@billtype VARCHAR(4),@formStype VARCHAR(50)  ---分解操作员ID和单据类型编号
SET @userid = (SELECT TOP 1 A FROM f_split(@typeid,'я'))
SET @temp = (SELECT A FROM f_split(@typeid,'я') WHERE A <> @userid )
SET @billtype = (SELECT top 1 A FROM f_split(@temp,'#'))
SET @formStype = (SELECT  A FROM f_split(@temp,'#') WHERE A <> @billtype  )

print(@typeid+'typeid')
print(@formStype+'stype')




DECLARE @stockid VARCHAR(500),@stockname VARCHAR(100),@cargoid VARCHAR(500),@cargoName VARCHAR(100)
set @stockid=null set @stockname=null set @cargoid=null set @cargoName=null












DECLARE @Qty  NUMERIC(24, 10) 
IF(@billtype='144' or @billtype='145')--
BEGIN
--验证数量
IF (@StrQty = '')
BEGIN
	SET @ErrMsg = '请输入数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
			SET @ErrMsg = '数量请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
		BEGIN
			SET @ErrMsg = '数量不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
			IF(@Qty <=0)
			BEGIN
				SET @ErrMsg = '数量不能为0'
				RETURN -1
			END
		END
		IF(charindex('.',@StrQty)>0)
		BEGIN
		select @weicount=len(@StrQty)-charindex('.',@StrQty)
		IF(CONVERT(INT,@weicount) > 4 )
		BEGIN
			SET @ErrMsg = '数量小数位数不能超出4位'
			RETURN -1
		END
		END
END
--验证数量
END



IF(@billtype='144' or @billtype='145')--
BEGIN
IF (@StrPrice <> '')
BEGIN
	IF(ISNUMERIC(@StrPrice) <> 1)
		BEGIN
			SET @ErrMsg = '单价请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrPrice)) <> 0)
		BEGIN
			SET @ErrMsg = '单价不能为负数'
			RETURN -1
		END
		
		IF(charindex('.',@StrPrice) <> 0)
		BEGIN
		select @weicount=len(@StrPrice)-charindex('.',@StrPrice)
		IF(CONVERT(INT,@weicount) > 4 )
		BEGIN
			SET @ErrMsg = '单价小数位数不能超出4位'
			RETURN -1
		END
		
		IF(LEN(substring(@StrPrice,0,charindex('.',@StrPrice)))>10)
		BEGIN
			SET @ErrMsg = '单价不能超出10位数'
			RETURN -1
		END
		END
		ELSE
		BEGIN
		IF(len(@StrPrice)>10)
		BEGIN
			SET @ErrMsg = '单价不能超出10位数'
			RETURN -1
		END
		END
		
		
		
END
END







IF (@ptypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@userid)))
BEGIN
	SET @ErrMsg = '操作员没有该商品权限'
	RETURN -1
END





IF(@FullName = '')--商品名称为空时(为名车赋值)
BEGIN
SELECT @FullName=fullname FROM PType WHERE UserCode = @UserCode
END


DECLARE @unitstype VARCHAR(66)
SELECT @unitstype=unitstype FROM PType WHERE UserCode = @UserCode


DECLARE @munitid VARCHAR(50)
DECLARE @munit VARCHAR(50)

DECLARE @baseunitid VARCHAR(50)
DECLARE @baseunit VARCHAR(50)

DECLARE @nunitid VARCHAR(50)
DECLARE @nunit VARCHAR(50)

DECLARE @munitrate VARCHAR(50)
DECLARE @unitrate VARCHAR(50)

--获取商品的采购或是销售的默认单位和基本单位以及浮动单位
IF(@billtype = '144' or @billtype = '145' )--
BEGIN
SELECT @munitid=BuyUnitId FROM PType WHERE UserCode=@UserCode
SELECT @munit=fullname FROM PType_Units WHERE UnitsId=@munitid
END


SELECT @baseunitid=baseUnitId FROM PType WHERE UserCode=@UserCode
SELECT @baseunit=fullname FROM PType_Units WHERE UnitsId=@baseunitid

SELECT @nunitid=AssistantUnitId FROM PType WHERE UserCode=@UserCode
SELECT @nunit=fullname FROM PType_Units WHERE UnitsId=@nunitid

SELECT @munitrate=rate from PType_Units_Ext where PtypeID=@ptypeid and UnitsId=@munitid
SELECT @unitrate=rate from PType_Units_Ext where PtypeID=@ptypeid and RateType=1

DECLARE @ImportTime DATETIME
SELECT @ImportTime = CONVERT(VARCHAR(23), GETDATE(), 121)
----------------------------------------------------------------------------------------------
INSERT INTO importptypetemp(etypeid,BillType,PtypeId,Qty,deleted,ImportTime,StrPrice,munitid,munit,baseunitid,baseunit,nunitid,nunit,munitrate,unitrate,unitstype,stockid,stockname,cargoid,cargoName)  VALUES
(@userid, @billtype, @ptypeid, @Qty, 0, @ImportTime,@StrPrice,@munitid,@munit,@baseunitid,@baseunit,@nunitid,@nunit,@munitrate,@unitrate,@unitstype,@stockid,@stockname,@cargoid,@cargoName)
SET  @ReturnID = @@ROWCOUNT



GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/****** Object:  StoredProcedure [dbo].[gp_ImportShouTuo]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：廖晨羽
	日    期：2011-08-29
	描	  述：导入受托代销期初
*/


CREATE         PROCEDURE [dbo].[gp_ImportShouTuo]
(
	@SFullName   [varchar](200),		--分支机构名称
	@BFullName   [varchar](200),		--往来单位名称
	@PUserCode	 [varchar](200),		--商品编号
	@PFullName   [varchar](200),		--商品名称
	@StrQty  [varchar](18),			--受托代销数量
	@StrPrice	[varchar](18),		--单价
	@explain VARCHAR(256),			--说明
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

DECLARE @Allow VARCHAR(50),@operId VARCHAR(max)  ---分解是否允许供货商和操作员id
SET @Allow = (SELECT TOP 1 A FROM f_split(@typeid,'я'))
SET @operId = (SELECT A FROM f_split(@typeid,'я') WHERE A <> @Allow)

DECLARE @stypeid	VARCHAR(1000)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF (@SFullName = '' OR @SFullName = '总部' OR NOT EXISTS(SELECT typeid FROM dbo.SType WHERE fullname = @SFullName))
	BEGIN
		SET @ErrMsg = '该分支机构不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PStypeId VARCHAR(50)
		DECLARE @SChildCount NUMERIC(18,0)
		SET @PStypeId = (SELECT TOP 1 typeid FROM dbo.SType WHERE fullname = @SFullName)
		SELECT @SChildCount = COUNT(*) FROM dbo.SType WHERE typeId LIKE @PStypeId + '%' AND typeId <> @PStypeId
		IF (@SChildCount = 0)
			BEGIN
				SET @stypeid = @PStypeId	
				IF (@stypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@operId)))
				BEGIN
					SET @ErrMsg = '操作员不具备该分支机构权限'
					RETURN -1
				END					
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该分支机构是父类'
				RETURN -1
			END
	END

	--判断分支机构是否已开账
	IF ((SELECT U.Value FROM SType_UserConfig U,SType_Config C WHERE U.ConfigNo = C.ConfigNo AND U.Value = '1' AND U.STypeID = @stypeid) = 1)
	BEGIN
		SET @ErrMsg = '该分支机构已开账'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

DECLARE	@btypeid		varchar(1000)
IF(@BFullName = '全部供货商' OR @BFullName = '所有客户')
BEGIN
	SET @ErrMsg = '该往来单位是父类'
	RETURN -1
END
IF (@BFullName = '' OR @BFullName = 'ABC' OR NOT EXISTS(SELECT typeid FROM dbo.btype WHERE fullname = @BFullName))
BEGIN
	SET @ErrMsg = '该往来单位不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PBtypeId VARCHAR(50)
	DECLARE @BChildCount NUMERIC(18,0)
	SET @PBtypeId = (SELECT TOP 1 typeid FROM dbo.btype WHERE fullname = @BFullName)
	SELECT @BChildCount = COUNT(*) FROM dbo.btype WHERE typeId LIKE @PBtypeId + '%' AND typeId <> @PBtypeId
	IF (@BChildCount = 0)
		BEGIN
			SET @btypeid = @PBtypeId		
			IF (@btypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@operId)))
			BEGIN
				SET @ErrMsg = '操作员不具备该往来单位权限'
				RETURN -1
			END			
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该往来单位是父类'
			RETURN -1
		END
END

IF(@Allow = 'False')
BEGIN
	DECLARE @tempBtypeid VARCHAR(max)
	SET @tempBtypeid = SUBSTRING(@btypeid,1,5)
	IF(@tempBtypeid = '00001')
	BEGIN
			SET @ErrMsg = '该往来单位不能是客户'
			RETURN -1
	END
END

IF(@PUserCode = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @PUserCode) OR @PUserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
ELSE IF (@PFullName = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @PFullName) OR @PFullName='库存配件')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
ELSE IF(@PFullName <> (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @PUserCode))
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PtypeId  VARCHAR(50)
	DECLARE @ChildCount NUMERIC(18,0)
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @PUserCode)
	IF (@PtypeId NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@operId)))
			BEGIN
				SET @ErrMsg = '操作员不具备该商品权限'
				RETURN -1
			END		
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0 OR (@PFullName = '库存配件' AND @PUserCode = '0'))
	BEGIN
		SET @ErrMsg = '该商品为父节点，不能导入期初'
		RETURN -1	
	END
END

DECLARE @Qty  NUMERIC(24, 10) 
IF (@StrQty = '')
BEGIN
	SET @ErrMsg = '请输入受托代销数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
			SET @ErrMsg = '受托代销数量请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
		BEGIN
			SET @ErrMsg = '受托代销数量不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
		END
END

DECLARE @CostTotal  NUMERIC(24, 10)  = 0

DECLARE @Price  NUMERIC(24, 10) 
IF (@StrPrice = '')
BEGIN
	SET @ErrMsg = '请输入单价'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrPrice) <> 1)
		BEGIN
			SET @ErrMsg = '单价请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrPrice)) <> 0)
		BEGIN
			SET @ErrMsg = '单价不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Price = CONVERT( NUMERIC(24, 10) , @StrPrice)
		END
END

DECLARE @Total  NUMERIC(24, 10) 
IF (@Qty = 0 OR @Price = 0)
BEGIN
	SET @Price = 0
	SET @Total = 0
END
ELSE
	SELECT @Total = ROUND(@Qty*@Price, 2)
----------------------------------------------------------------------------------------------

IF NOT EXISTS(SELECT Qty FROM dbo.IniCommissionStock WHERE btypeid = @btypeid AND ptypeid = @ptypeid AND type = 144 AND stypeid = @stypeid)	--判断是否已经存在一样的期初信息
BEGIN                             --不存在
	INSERT INTO
		IniCommissionStock(btypeid,ptypeid,ktypeid,etypeid,type,qty,CostTotal,Total,explain,stypeid) 
	VALUES(@btypeid,@ptypeid,'','',144,@qty,@CostTotal,@Total,@explain,@stypeid)
END
ELSE
BEGIN                             --存在
	DELETE FROM IniCommissionStock 
	WHERE btypeid = @btypeid AND ptypeid = @ptypeid AND type = 144 AND stypeid = @stypeid
	
	INSERT INTO
		IniCommissionStock(btypeid,ptypeid,ktypeid,etypeid,type,qty,CostTotal,Total,explain,stypeid) 
	VALUES(@btypeid,@ptypeid,'','',144,@qty,@CostTotal,@Total,@explain,@stypeid)
END

SET @ReturnID = @@ROWCOUNT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ImportStock]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ImportStock]

GO

/****** Object:  StoredProcedure [dbo].[gp_ImportK]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO



/*
	Create by ：	Haiyang Li
	Date：				2012-07-31
	Description:  仓库档案基本信息导入
*/



CREATE PROCEDURE [dbo].[GP_ImportStock]
    (
      @KFullName VARCHAR(66) ,
      @UserCode VARCHAR(26) ,
      @FullName VARCHAR(66) ,
      @Name VARCHAR(30) ,
      @PyCode VARCHAR(201) ,
      @SFullName VARCHAR(100) ,
      @LinkMan VARCHAR(20) ,
      @Job		VARCHAR(100) = '',			--职位
      @Tel VARCHAR(50) ,
      @Address VARCHAR(50) ,
      @Comment VARCHAR(257) ,
      @ErrMsg VARCHAR(200) OUTPUT,
      @DefaultSFullName VARCHAR(200),
      @mobile		VARCHAR(100) = '',		--手机
      @sheng		VARCHAR(100) = '',		--省
      @shi			VARCHAR(100) = '',		--市
      @xian			VARCHAR(100) = '',		--县
      @postcode		VARCHAR(100) = ''		--邮编
    )
--@encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    /*IF ( ( SELECT   DATALENGTH(@PyCode)
         ) > 200 ) 
        BEGIN
            SET @ErrMsg = '拼音码的长度大于最大允许长度200'
            RETURN -1
        END

    IF ( ( SELECT   DATALENGTH(@Comment)
         ) > 256 ) 
        BEGIN
            SET @ErrMsg = '备注的长度大于最大允许长度256'
            RETURN -1
        END*/

    DECLARE @Parid VARCHAR(50)
    IF ( @KFullName = ''
         OR @KFullName = '全部仓库'
       ) 
        BEGIN
            SET @Parid = '00000'
        END
    ELSE 
        BEGIN
            IF NOT EXISTS ( SELECT TOP 1
                                    1
                            FROM    dbo.Stock
                            WHERE   fullname = @KfullName ) 
                BEGIN
                    SET @ErrMsg = '父类名称不存在'
                    RETURN -1
                END
            ELSE 
                BEGIN
                    SET @Parid = ( SELECT TOP 1
                                            typeid
                                   FROM     dbo.Stock
                                   WHERE    fullname = @KfullName
                                 )
					IF EXISTS ( SELECT ktypeid FROM  DefaultStock WHERE ktypeid=@Parid)
					BEGIN
						SET @ErrMsg = '该仓库已在商品默认仓库中使用,不能分类'
						RETURN -1
					END
                END
        END



    IF ( @UserCode = '' ) 
        BEGIN
            SET @ErrMsg = '仓库编号不能为空'
            RETURN -1
        END

    IF ( @FullName = '' ) 
        BEGIN
            SET @ErrMsg = '仓库全名不能为空'
            RETURN -1
        END

    IF ( @Pycode = '' ) 
        BEGIN
            SELECT  @Pycode = dbo.fun_getPY(@FullName)
        END

    DECLARE @STypeID VARCHAR(50)
    IF ( @SfullName = '' ) 
        BEGIN
            SET @SFullName=@DefaultSFullName
        END
    IF EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[A8ZTInfo]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
        BEGIN
            IF NOT EXISTS ( SELECT TOP 1
                                    typeid
                            FROM    stype
                            WHERE   fullname = @SfullName )
                OR @SfullName = '总部' 
                BEGIN
                    SET @ErrMsg = '该分支机构不存在'
                    RETURN -1
                END
            ELSE 
                BEGIN
                    DECLARE @PStypeId VARCHAR(50)
                    DECLARE @SChildCount NUMERIC(18, 0)
                    SET @PStypeId = ( SELECT TOP 1
                                                typeid
                                      FROM      stype
                                      WHERE     fullname = @SfullName
                                    )
                    SELECT  @SChildCount = COUNT(*)
                    FROM    dbo.stype
                    WHERE   typeid LIKE @PStypeId + '%'
                            AND typeid <> @PStypeId
                    IF ( @SChildCount = 0 ) 
                        BEGIN
                            SET @STypeID = @PStypeId
                        END
                    ELSE 
                        BEGIN
                            SET @ErrMsg = '该分支机构为父类'
                            RETURN -1
                        END
                    IF ( ( SELECT TOP 1
                                    STypeID
                           FROM     dbo.Stock
                           WHERE    fullname = @KfullName
                         ) <> @STypeID ) 
                        BEGIN
                            SET @ErrMsg = '该分支机构必须与父类分支机构一样'
                            RETURN -1
                        END			             
                END
        END

    IF EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[V3ZTInfo]') OR id = OBJECT_ID(N'[dbo].[V1ZTInfo]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
        BEGIN
            IF ( @SFullName = ''
                 OR @SFullName = '默认分支机构'
               ) 
                BEGIN
                    SET @stypeid = '00001'
                END
            ELSE 
                BEGIN
                    SET @ErrMsg = '分支机构只能填默认分支机构或为空'
                    RETURN -1
                END
        END

    IF EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[QPZTInfo]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
        BEGIN
            IF ( @SFullName = ''
                 OR @SFullName = '默认分支机构'
               ) 
                BEGIN
                    SET @stypeid = '00001'
                END
            ELSE 
                BEGIN
                    SET @ErrMsg = '分支机构只能填默认分支机构或为空'
                    RETURN -1
                END
        END

    IF EXISTS (SELECT TypeId FROM dbo.SType WHERE typeid = @STypeID AND deleted = 1 )
    BEGIN
		SET @ErrMsg = '该分支机构已经被停用'
		RETURN -1 
	END

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

    DECLARE @nReturntype INT ,
        @StockID [varchar](50) ,
        @nSoncount INT ,
        @nSonnum INT ,
        @leveal SMALLINT

    DECLARE @parFullName VARCHAR(200)
    SET @parFullName = ( SELECT TOP 1
                                fullname
                         FROM   stock
                         WHERE  typeid = @parid
                       )
--判断是否为汽配
    DECLARE @ifqp VARCHAR(1)
    SET @ifqp = ( SELECT    subvalue
                  FROM      sysdata
                  WHERE     subname = 'ifqp'
                )
    IF ( @ParId <> '00000' ) 
        BEGIN
--判断停用不能分类
            DECLARE @deleted INT
            SELECT  @deleted = deleted
            FROM    stock
            WHERE   typeId = @Parid
            IF ( @deleted = 1 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】已经被停用，不能分类'
                    RETURN -1 
                END
-- 判断维修库存中期初是否为零
            IF EXISTS ( SELECT  ktypeid
                        FROM    Wx_iniGoodsstocks
                        WHERE   ktypeid = @parid
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】维修品库存期初余量不为零，不能分类'
                    RETURN -1
                END 
-- 判断库存量（每种商品）是否为零
            IF EXISTS ( SELECT  ktypeid
                        FROM    goodsstocks
                        WHERE   ktypeid = @parid
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】库存余量不为零，不能分类'
                    RETURN -1
                END 
            IF EXISTS ( SELECT  ktypeid
                        FROM    inigoodsstocks
                        WHERE   ktypeid = @parid
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】库存余量不为零，不能分类'
                    RETURN -1
                END 

--pos模块
            IF EXISTS ( SELECT  KTypeID
                        FROM    CommonPosSaleIndex
                        WHERE   ktypeid = @parid )
                OR EXISTS ( SELECT  KTypeID
                            FROM    CommonPosPtypeCheckNdx
                            WHERE   ktypeid = @parid )
                OR EXISTS ( SELECT  KTypeID
                            FROM    CX_SaleStocksArea
                            WHERE   ktypeid = @parid )
                OR EXISTS ( SELECT  stockid
                            FROM    CommonPosInfo
                            WHERE   stockid = @parid ) 
                BEGIN
		 --print '2555'
                    SET @ErrMsg = '该仓库【' + @parFullName + '】已经经营过，不能分类'
                    RETURN -1
                END

            IF EXISTS ( SELECT  ktypeid
                        FROM    wx_goodsstocks
                        WHERE   ktypeid = @parid
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】库存余量不为零，不能分类'
                    RETURN -1
                END 
            IF EXISTS ( SELECT  ktypeid
                        FROM    wx_inigoodsstocks
                        WHERE   ktypeid = @parid
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】库存余量不为零，不能分类'
                    RETURN -1
                END 
            IF EXISTS ( SELECT  ktypeid
                        FROM    inigoodsstocks
                        WHERE   ktypeid = @parid
                                AND Total <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】有库存期初，不能分类'
                    RETURN -1
                END 
--判断序列号
            IF EXISTS ( SELECT  KTypeID
                        FROM    gp_CruPtypeSerial
                        WHERE   KTypeID = @Parid ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】有序列号关联情况，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  KTypeID
                        FROM    gp_initPtypeSerial
                        WHERE   KTypeID = @Parid ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】有期初序列号关联情况，不能分类'
                    RETURN -1
                END

-- 判断借欠余额
            IF EXISTS ( SELECT  kTypeID
                        FROM    V_LendStatus
                        WHERE   kTypeID = @parid
                                AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】有借进借出，不能分类'
                    RETURN -1
                END 
-- 判断经营
            IF EXISTS ( SELECT  kTypeID
                        FROM    InOutStockTable
                        WHERE   kTypeID = @parid
                                AND Qty <> 0 )
                OR EXISTS ( SELECT  kTypeID
                            FROM    LendIndex
                            WHERE   kTypeID = @parid
                                    AND totalQty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】已经经营过，不能分类'
                    RETURN -1
                END 
            IF EXISTS ( SELECT  kTypeID
                        FROM    OrderIndex
                        WHERE   kTypeID = @parid
                                AND kTypeID <> '00000' ) 
                BEGIN
		-- print '订单使用过'
                    SET @ErrMsg = '该仓库【' + @parFullName + '】已在订单中使用，不能分类'
                    RETURN -1
                END
            IF EXISTS ( SELECT  kTypeID
                        FROM    LendIndex
                        WHERE   kTypeID = @parid ) 
                BEGIN
		-- print '借欠使用过'
                    SET @ErrMsg = '该仓库【' + @parFullName + '】已在借欠单中使用，不能分类'
                    RETURN -1
                END

            IF EXISTS ( SELECT  kTypeID
                        FROM    Billindex
                        WHERE   ( kTypeID = @parid
                                  OR kTypeID2 = @parid
                                  OR kTypeID3 = @parid
                                )
                                AND kTypeID <> '00000' )    --modify 2010.05.21  ljun
                BEGIN
		--经营过
                    SET @ErrMsg = '该仓库【' + @parFullName + '】已经经营过，不能分类'
                    RETURN -1
                END

            IF EXISTS ( SELECT  kTypeID
                        FROM    iniCommissionStock
                        WHERE   kTypeID = @parid
                                AND Qty <> 0 )
                OR EXISTS ( SELECT  kTypeID
                            FROM    CommissionStock
                            WHERE   kTypeID = @parid
                                    AND Qty <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】存在代销情况，不能分类'
                    RETURN -1
                END 

            IF EXISTS ( SELECT  kTypeID
                        FROM    iniCommissionStock
                        WHERE   kTypeID = @parid
                                AND total <> 0 )
                OR EXISTS ( SELECT  kTypeID
                            FROM    CommissionStock
                            WHERE   kTypeID = @parid
                                    AND total <> 0 ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】存在代销情况，不能分类'
                    RETURN -1
                END 
            IF @ifqp = '1' 
                BEGIN
		--采购类单
                    IF EXISTS ( SELECT  ktypeid
                                FROM    buybill
                                WHERE   ktypeid = @parid ) 
                        BEGIN
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
		--领料出库单
                    IF EXISTS ( SELECT  KTypeID
                                FROM    Qp_PickingBill
                                WHERE   ktypeid = @parid ) 
                        BEGIN
			    --print '2555'
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
		--领料退回单
                    IF EXISTS ( SELECT  KTypeId
                                FROM    Qp_PickingBackBill
                                WHERE   KTypeId = @parid ) 
                        BEGIN
			    --print '2555'
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
		--销售类
                    IF EXISTS ( SELECT  ktypeid
                                FROM    salebill
                                WHERE   ktypeid = @parid ) 
                        BEGIN
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
		--代销类
                    IF EXISTS ( SELECT  ktypeid
                                FROM    CommissionBill
                                WHERE   ktypeid = @parid ) 
                        BEGIN
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
		--订单类
                    IF EXISTS ( SELECT  ktypeid
                                FROM    orderbill
                                WHERE   ktypeid = @parid ) 
                        BEGIN
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
                    IF EXISTS ( SELECT  ktypeid
                                FROM    IntegralExchangeBill
                                WHERE   ktypeid = @parid ) 
                        BEGIN
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
		--快修单表体
                    IF EXISTS ( SELECT  ktypeid
                                FROM    QP_QuickRepairBill_PType
                                WHERE   ktypeid = @parid ) 
                        BEGIN
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
		--生产拆装单
                    IF EXISTS ( SELECT  ktypeid
                                FROM    disassemblebill
                                WHERE   ktypeid = @parid ) 
                        BEGIN
                            SET @ErrMsg = '该仓库【' + @parFullName
                                + '】已经经营过，不能分类'
                            RETURN -1
                        END
                END

--盘点单
            IF EXISTS ( SELECT TOP 1
                                ktypeid
                        FROM    StockCheckIndex
                        WHERE   ktypeid = @parid ) 
                BEGIN
                    SET @ErrMsg = '该仓库【' + @parFullName + '】已在库存盘点单中使用，不能分类'
                    RETURN -1
                END
        END

--销售类
    IF EXISTS ( SELECT  *
                FROM    OrderBill ,
                        Stock
                WHERE   KTypeID = @parid
                        AND KTypeID = Stock.typeId ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联销售订单或采购订单，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  *
                FROM    SaleBill ,
                        Stock
                WHERE   KTypeID = @parid
                        AND KTypeID = Stock.typeId ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联销售出库单，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  *
                FROM    SaleGoodsExchangeBill ,
                        Stock
                WHERE   ( KTypeID = @parid
                          AND KTypeID = Stock.typeId
                        )
                        OR ( KTypeID2 = @parid
                             AND KTypeID2 = Stock.typeId
                           ) ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联销售换货单，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  *
                FROM    SaleBackBill ,
                        Stock
                WHERE   KTypeID = @parid
                        AND KTypeID = Stock.typeId ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联销售退货单，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  *
                FROM    CommissionBill ,
                        Stock
                WHERE   KTypeID = @parid
                        AND KTypeID = Stock.typeId ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联委托代销单据，不能分类'
            RETURN -1
        END
		--采购类
    IF EXISTS ( SELECT  *
                FROM    BuyBill ,
                        Stock
                WHERE   KTypeID = @parid
                        AND KTypeID = Stock.typeId ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联采购入库单，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  *
                FROM    BuybackBill ,
                        Stock
                WHERE   KTypeID = @parid
                        AND KTypeID = Stock.typeId ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联采购退货单，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  *
                FROM    BuyGoodsExchangeBill ,
                        Stock
                WHERE   ( KTypeID = @parid
                          AND KTypeID = Stock.typeId
                        )
                        OR ( (KTypeID2 = @parid
                             AND KTypeID2 = Stock.typeId)
                           ) ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联采购换货单，不能分类'
            RETURN -1
        END
		--库存类
    IF EXISTS ( SELECT  *
                FROM    StypeMoveBill ,
                        Stock
                WHERE   ( KTypeID = @parid
                          AND KTypeID = Stock.typeId
                        )
                        OR ( (KTypeID2 = @parid
                             AND KTypeID2 = Stock.typeId)
                           ) ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联分支机构调拨出库单或分支机构调拨入库单，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  *
                FROM    DisassembleBill ,
                        Stock
                WHERE   KTypeID = @parid
                        AND KTypeID = Stock.typeId ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联生产拆装单，不能分类'
            RETURN -1
        END
		--会员类
    IF EXISTS ( SELECT  *
                FROM    IntegralExchangeBill ,
                        Stock
                WHERE   KTypeID = @parid
                        AND KTypeID = Stock.typeId ) 
        BEGIN
            SET @ErrMsg = '该仓库已关联积分兑换单，不能分类'
            RETURN -1
        END
	-- 9.2 pos
	IF EXISTS(SELECT TOP 1 * FROM PriceRule_Detail_KConfig WHERE   KTypeID=@Parid)
		BEGIN
			RAISERROR('该仓库已关联价格策略，不能分类',16,1);RETURN -1;
		END
	IF EXISTS(SELECT TOP 1 * FROM PromoRule_Detail_KConfig WHERE   KTypeID=@Parid)
		BEGIN
			RAISERROR('该仓库已关联促销规则，不能分类',16,1);RETURN -1;
		END
	IF EXISTS(SELECT TOP 1 * FROM PosInfo WHERE KTypeID=@Parid)
		BEGIN
			RAISERROR('该仓库已关联POS，不能分类',16,1);RETURN -1;
		END

-- 获得新的ID号
    DECLARE @DbName VARCHAR(30) = 'stock'
    EXEC @nReturntype= Gp_createId @ParId, @dbname, @StockID OUT, @nSonnum OUT,
        @nSoncount OUT
    IF @nReturntype = -1 
        BEGIN
            SET @ErrMsg = '仓库的分类不能超过10层'
            RETURN -1
        END
    IF @nReturntype = -2 
        BEGIN
            SET @ErrMsg = '无法添加基本信息'
            RETURN -1
        END
-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  typeId
                FROM    Stock
                WHERE   ( usercode = @usercode
                          AND deleted <> 1
                        )
                        OR ( fullname = @fullname
                             AND deleted <> 1
                           ) ) 
        BEGIN
            SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被使用，仓库的名称或编号不能相同!'
            RETURN -1
        END


-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  *
                FROM    [stock]
                WHERE   typeId = @StockID
                        OR ( usercode = @usercode
                             AND deleted = 1
                           )
                        OR ( fullname = @fullname
                             AND deleted = 1
                           ) ) 
        BEGIN
            SET @ErrMsg = '该【' + @FullName
                + '】的编号或名称已被已停用的仓库使用，请更换或删除该停用的编号或名称'
            RETURN -1
        END
-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  *
                FROM    [stock]
                WHERE   typeId = @StockID
                        OR ( usercode = @fullname
                             AND deleted = 1
                           )
                        OR ( fullname = @usercode
                             AND deleted = 1
                           ) ) 
        BEGIN
            SET @ErrMsg = '该仓库【' + @FullName + '】名称或编号不能与已停用的名称或编号重复'
            RETURN -1
        END

/*
-- 判断仓库的最大使用数量
declare @nCount int
select @nCount=Count(*) from stock 
where sonnum = 0 
 and deleted=0
if @nCount > 10
begin
-- print '仓库数量大于10'
 return -99
end
*/

    DECLARE @returnPym VARCHAR(1000)
    EXEC @returnPym = fun_getPy @FullName

    IF @PyCode <> '' 
        SET @returnPym = @PyCode

    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    stock
    WHERE   typeid = @Parid
    SELECT  @leveal = @leveal + 1
    INSERT  INTO [stock]
            ( [typeId] ,
              [Parid] ,
              [leveal] ,
              [soncount] ,
              [sonnum] ,
              [FullName] ,
              [Name] ,
              [UserCode] ,
              [Comment] ,
              [LinkMan] ,
              [Tel] ,
              [Add] ,
              [PyCode] ,
              [STypeID],
              [Mobile],
              [sheng],
              [shi],
              [xian],
              [postcode],
              [job]
            )
    VALUES  ( @StockID ,
              @Parid ,
              @leveal ,
              0 ,
              0 ,
              @FullName ,
              @name ,
              @UserCode ,
              @Comment ,
              @LinkMan ,
              @Tel ,
              @Address ,
              @returnPym ,
              @STypeID,
              @mobile,
              @sheng,
              @shi,
              @xian,
              @postcode,
              @Job
            )
    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
    ELSE 
        BEGIN
            UPDATE  [stock]
            SET     sonnum = @nSonnum + 1 ,
                    soncount = @nSoncount + 1
            WHERE   typeid = @Parid
        END

--修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    Stock
    UPDATE  Stock
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @StockID
 
		-- 添加默认货位
    DECLARE @DefaultCargoName VARCHAR(200)
    SET @DefaultCargoName = @FullName + N'默认货位'
    EXEC Gp_CargoTypeEdit '', @DefaultCargoName, @DefaultCargoName, @StockID,
        @DefaultCargoName, 1 , 0, 'ADD'
 
    COMMIT TRAN insertproc

GO





IF EXISTS ( SELECT
                *
            FROM
                dbo.sysobjects
            WHERE
                id = OBJECT_ID(N'[dbo].[Gp_ImportStockAlarmDT]')
                AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_ImportStockAlarmDT]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：tangtao
	日    期：2015-08-27
	描	  述：库存上下限批量导入 
*/


CREATE PROCEDURE Gp_ImportStockAlarmDT 
    (
      @Details TBType_ImportStockAlarm READONLY
    )
AS
    BEGIN
    
		DELETE dbo.STOCKALARM WHERE PTypeId IN (SELECT PTypeId FROM @Details) AND KTypeId='00000'
		
		CREATE TABLE #STOCKALARMTEMP
		(	
			ID					INT					NOT NULL			,
			PTypeId				VARCHAR (50) 		NOT NULL			   ,
			UpLimitQty			 NUMERIC(24, 10) 		NULL		DEFAULT (0),
			DownLimitQty		 NUMERIC(24, 10) 		NULL		DEFAULT (0)
		)
		
		INSERT INTO #STOCKALARMTEMP ( ID , PTypeId , UpLimitQty , DownLimitQty ) 
		SELECT ID , PTypeId , UpLimitQty , DownLimitQty FROM @Details
		
		--BUG 32 仅导入最后一行记录的数据 
		DELETE FROM #STOCKALARMTEMP 
		WHERE PTypeId IN ( 
			SELECT PTypeId FROM #STOCKALARMTEMP GROUP BY PTypeId HAVING COUNT(PTypeId) > 1 
			) 
		AND ID NOT IN ( 
			SELECT MAX(ID) FROM #STOCKALARMTEMP GROUP BY PTypeId HAVING COUNT(PTypeId) > 1 
			) 
		
		INSERT  INTO dbo.STOCKALARM 
        ( PTypeId , UpLimitQty , DownLimitQty , KTypeId , OrderQty  )
        SELECT  
          PTypeId , UpLimitQty , DownLimitQty , '00000' ,  0
        FROM   #STOCKALARMTEMP
        
		/* 合并导入
        INSERT  INTO dbo.STOCKALARM 
        ( PTypeId , UpLimitQty , DownLimitQty , KTypeId , OrderQty  )
        SELECT  
          PTypeId , SUM( ISNULL(UpLimitQty,0)) , SUM(ISNULL(DownLimitQty,0)) , '00000' ,  0
        FROM   @Details
        GROUP BY PTypeId
		*/
		DELETE STOCKALARM WHERE KTypeId='00000' AND UpLimitQty = 0 AND DownLimitQty = 0
		
		DROP TABLE #STOCKALARMTEMP
		
    END
  
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.GP_ImportSyBtype',N'P'))
BEGIN
	DROP PROC dbo.GP_ImportSyBtype;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	作者：L
	日期：2019-05-27 
	描述：适用往来导入模板
*/	

CREATE PROC GP_ImportSyBtype
(	
	@operatorid			VARCHAR(50),			--操作员ID
	@usercode			VARCHAR(200),			--商品编号
	@fullname			VARCHAR(200),			--商品名称	
	@billtype			INT,					--类型
	@ReturnID			VARCHAR(100) OUTPUT,	--返回ID
	@ErrMsg				VARCHAR(200) OUTPUT		--返回消息
)
--@encode$--
AS
SET NOCOUNT ON

IF @usercode = ''
BEGIN
	SET @ErrMsg = '编号为空！'
	RETURN -1
END	

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.F_GetManBTypeAll(@operatorid) WHERE UserCode = @usercode AND deleted = 0 AND sonnum = 0)
BEGIN
	SET @ErrMsg = '单位信息不在权限范围内或者不正确！'
	RETURN -1
END

DECLARE @typeid		VARCHAR(50),
		@bptypeid	VARCHAR(50)

SELECT @typeid = typeid FROM btype WHERE UserCode = @usercode

INSERT INTO importptypetemp1
(
	etypeid,
	billtype,
	PtypeId
)VALUES(
	@operatorid,
	@billtype,
	@typeid
)

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：王珏
	日期：2013-03-05
	描述：导入税务资料信息
*/
CREATE	PROCEDURE	GP_ImportTaxInfo
(
	@usercode		VARCHAR(200),
	@fullname		VARCHAR(200),
	@strtaxtype		VARCHAR(200),
	@strtax			VARCHAR(5),
	@strpycode		VARCHAR(100),
	@strcomment		VARCHAR(500),
	@ErrMsg         VARCHAR(200) OUTPUT	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @taxtype INT
DECLARE @tax	  NUMERIC(24, 10) 
DECLARE @pycode	 VARCHAR(100)
DECLARE @comment VARCHAR(500)

IF(@usercode = '')
BEGIN
	SET @ErrMsg = '税种编码不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF EXISTS (SELECT 1 FROM TaxInfo WHERE UserCode=@usercode)
		BEGIN
			SET @ErrMsg = '税种编码已经存在'
			RETURN -1 
		END
END

IF(@fullname = '')
BEGIN
	SET @ErrMsg = '税种名称不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF EXISTS (SELECT 1 FROM TaxInfo WHERE FullName=@fullname)
		BEGIN
			SET @ErrMsg = '税种名称已经存在'
			RETURN -1 
		END
END

IF(@strtaxtype = '')
BEGIN
	SET @ErrMsg = '税种类型不能为空'
	RETURN -1
END
ELSE
BEGIN
	IF(@strtaxtype <> '价内税' AND @strtaxtype <> '价外税')
	BEGIN
		SET @ErrMsg = '税种类型不正确'
		RETURN -1
	END
	ELSE
	BEGIN
		IF @strtaxtype = '价内税'
			SET @taxtype = 0
		IF @strtaxtype = '价外税'
			SET @taxtype = 1	
	END
END

IF(@strtax = '')
BEGIN
	SET @tax = 0	
END
ELSE
	IF (ISNUMERIC(@strtax) <> 1)
	BEGIN
		SET @ErrMsg = '税率请输入数字'
		RETURN -1
    END
    ELSE
		IF (CHARINDEX('-', @strtax) <> 0 ) 
		BEGIN
			SET @ErrMsg = '税率不能为负数'
			RETURN -1
		END
		IF(CHARINDEX('.',@strtax) <> 0 )
		BEGIN
			SET @ErrMsg = '税率不能为小数'
			RETURN -1
		END
		ELSE
		BEGIN
			SELECT  @tax = CONVERT( NUMERIC(24, 10) , @strtax)
			IF(@tax > 99)
			BEGIN
				SET @ErrMsg = '税率最大值为99'
				RETURN -1
			END
		END	
			
IF(@strpycode = '')
BEGIN
	SET @pycode = NULL
END	
ELSE
BEGIN
	SET @pycode = @strpycode
END

IF(@strcomment = '')
BEGIN
	SET @comment = NULL
END
ELSE
BEGIN
	SET @comment = @strcomment
END	

BEGIN TRAN insertproc
INSERT INTO TaxInfo (UserCode,
					 FullName,
					 TaxType,
					 Tax,
					 PyCode,
					 Comment)
			VALUES	(@usercode,
					 @fullname,
					 @taxtype,
					 @tax,
					 @pycode,
					 @comment)
IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
        
COMMIT TRAN insertproc  
GO 					 




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ImportVipCard]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_ImportVipCard]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






/*
	Added		:	喻堂
	Date		:	2012/03/08
	Description	:	从EXCEL导入会员卡资料，供打印管理器调用
*/


/*
	参数信息
	NOT NULL	表明该字段必须存在
	UNIQUE		表明该字段不能与EXCEL、数据库中其他数据记录重复
	EXISTS		表明该字段必须在数据库中存在，[]中的是表名
	IN			表明该字段的值的范围必须在[]中
	
	会员卡号		NOT NULL
	卡类型			NOT NULL
	单位名称		NOT NULL	EXISTS[BType]
	持卡人			NOT NULL
	持卡人拼音码	NULL
	生日			NULL
	手机			NULL
	通讯地址		NULL
	邮政编码		NULL
	从事行业		NULL
	证件号码		NULL
	性别			NULL		IN[男/女/NULL]
	状态			NOT NULL	[启用/删除/停用/挂失]
	发卡人			NOT NULL	EXISTS[Employee]
	发卡日期		NULL
	到期日期		NULL
	初始金额		NULL
	初始积分		NULL
	储值余额		NULL
	会员储值		NOT NULL	[是/否]
	备注			NULL

*/


CREATE PROC [dbo].[Gp_ImportVipCard]
(
	@OperatorID				VARCHAR(50),			--操作员ID
	@strVipCardCode			VARCHAR(100),			--Vip卡卡号
	@strCardType			VARCHAR(100),			--卡类型
	@strBTypeID             VARCHAR(100),            --结算单位ID
	--@strDiscountType		char(1),				--优惠方式
	@strBType				VARCHAR(100),			--客户名称
	@strBname				VARCHAR(66),			--客户姓名/持卡人
	@strPYcode				VARCHAR(300),			--客户拼音码
	@strBbirthday			VARCHAR(100),		    --客户生日
	@strBTel				VARCHAR(100),			--客户电话/手机
	@strBAddr				VARCHAR(100),			--联系地址
	@strBPostcode			VARCHAR(200),			--邮政编码
	@strBTrade				VARCHAR(100),			--从事行业
	@strBIDcard				VARCHAR(100),			--证件号码
	@strBSex				VARCHAR(100),			--客户性别
	@strVipStatus			VARCHAR(100),			--会员卡状态
	@strEType				VARCHAR(600),			--发卡人
	@strCreateDate			VARCHAR(100),			--发卡日期
	@strEndDate				VARCHAR(100),			--失效期
	@strBeginMoney			VARCHAR(100),			--初始金额
	@strBeginCent			VARCHAR(100),			--初始积分
	@strIsCz				VARCHAR(100) = '否',	--储值会员
	@strQcCzMoney			VARCHAR(100),			--期初储值金额
	@strComment				VARCHAR(256),			--备注	
	@jkStypeCode			VARCHAR(200),			--建卡分支机构编号
	@srcpassword			VARCHAR(100),			--初始密码
	@ErrMsg                 VARCHAR(800) output
)
--@encode$--
AS 
SET NOCOUNT ON

-----------------参数检查------------------------------------------------------------------------------
DECLARE @VipCardCode	VARCHAR(50),
		@VipCardTypeID	INT,
		@BTypeID		VARCHAR(50),
		@BName			VARCHAR(66),
		@PYcode			VARCHAR(300),
		@Bbirthday		DATETIME,
		@BTel			VARCHAR(50),
		@BAddr			VARCHAR(50),
		@BPostCode		VARCHAR(200),
		@BTrade			VARCHAR(12),
		@BIDcard		VARCHAR(26),
		@BSex			VARCHAR(1),
		@VipStatus		VARCHAR(1),
		@EtypeID		VARCHAR(50),
		@CreateDate		DATETIME,
		@EndDate		DATETIME,
		@BeginMoney		 NUMERIC(24, 10) ,
		@BeginCent		 NUMERIC(24, 10) ,
		@CzyeMoney		 NUMERIC(24, 10) ,
		@qCcZMoney		 NUMERIC(24, 10) ,
		@IsCZ			VARCHAR(2),
		@Comment		VARCHAR(256),
		@ifJF			CHAR(1)='1',
		@GiveCent		NUMERIC= 0

--会员卡重复判断
IF EXISTS ( SELECT  *
            FROM    nVipCardSign
            WHERE   VipCardCode = @strVipCardCode
			) 
    BEGIN
        SET @ErrMsg = '会员卡[' + @strVipCardCode + ']已存在,请检查!' ;
        RETURN -1 ;
    END	
    
--VipCardCode
IF EXISTS ( SELECT  *
            FROM    nVipCardSign
            WHERE   VipCardCode = @strVipCardCode
                    AND deleted <> '1' 
                    AND EndDate > GETDATE() ) 
    BEGIN
        SET @ErrMsg = '会员卡[' + @strVipCardCode + ']已存在且正在使用中,请检查!' ;
        RETURN -1 ;
    END	
	
IF LTRIM(RTRIM(@strVipCardCode)) = '' 
    BEGIN
        SET @ErrMsg = '会员卡号不能为空,请检查!' ;
        RETURN -1 ;
    END	
   


IF LEN(@strVipCardCode) > 50 
    BEGIN
        SET @ErrMsg = '会员卡号[' + @strVipCardCode + ']长度不能超过50位,请检查!' ;
        RETURN -1 ;
    END	
SET @VipCardCode = @strVipCardCode ;
	

--VipCardTypeID
IF LTRIM(RTRIM(@strCardType)) = '' 
    BEGIN
        SET @ErrMsg = '卡类型不能为空,请检查!' ;
        RETURN -1 ;
    END	

--判断是否是纯数字
SET @srcpassword = LTRIM(RTRIM(@srcpassword))

IF @srcpassword<>''
BEGIN
	IF PATINDEX('%[^0-9]%', @srcpassword)>0
	BEGIN
		SET @ErrMsg = '初始密码必须为数字!' ;
		RETURN -1 ;
	END
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'newcardneedpassword' AND SubValue = '1')
BEGIN
	IF @srcpassword = ''
	BEGIN
		SET @ErrMsg = '初始密码不能为空!' ;
		RETURN -1 ;
	END
END	

SELECT  @VipCardTypeID = VipCardTypeID ,@ifJF=ifJF,@GiveCent = GiveCent
FROM    [nVipCardSet]
WHERE   [TypeName] = @strCardType ;
IF @VipCardTypeID IS NULL 
BEGIN
	--set @VipCardTypeID = 0
    INSERT  INTO [nVipCardSet]
    (
         [TypeName],
         [DiscountType],
         [ifJF],
         [deleted],
         [Comment],
         [VipCardnum]
    )VALUES(
         @strCardType,
         1,
         1,
         0,
         '',
         0
     )

    SET @VipCardTypeID = SCOPE_IDENTITY() ;

    IF @VipCardTypeID IS NULL 
        BEGIN
            SET @ErrMsg = '卡类型' + @strCardType + '不存在并且添加默认失败,请检查!' ;
            RETURN -1 ;
        END
END


--结算单位判断
IF ISNULL(@strBTypeID,'')<>'' OR ISNULL(@strBType,'')<>''
BEGIN
	--编号为空和名称不为空
	IF ISNULL(@strBTypeID,'')='' AND ISNULL(@strBType,'')<>''
	BEGIN
		SET @ErrMsg = '结算单位编号不能为空，请检查！' ;
		RETURN -1
	END
	--编号不为空和名称为空
	IF ISNULL(@strBTypeID,'')<>'' AND ISNULL(@strBType,'')=''
	BEGIN
		SET @ErrMsg = '结算单位单位名称不能为空，请检查！' ;
		RETURN -1
	END
	
	IF EXISTS(SELECT TOP 1 * FROM Userconfig WHERE ConfigName = 'BTypeAll' AND Value = 0)
		SELECT  @BTypeID = TypeID FROM btype WHERE FullName=@strBType AND TypeId LIKE '00001%'
	ELSE
		SELECT @BTypeID=TypeID FROM btype WHERE FullName=@strBType	
				
	SET @BTypeID=ISNULL(@BTypeID,'')
	
	
	--名称不存在
	IF ISNULL(@BTypeID,'')=''
	BEGIN
		SET @ErrMsg = '结算单位[' + @strBType + ']不存在，不能导入！' ;
		RETURN -1
	END

	--编号存在 名称不匹配
	IF NOT EXISTS(SELECT * FROM btype WHERE UserCode=@strBTypeID AND typeId=@BTypeID)
	BEGIN
		SET @ErrMsg = '结算单位编号[' + @strBTypeID + ']与结算单位名称[' + @strBType + ']不匹配,不能导入!' ;
		RETURN -1
	END

	IF NOT EXISTS(SELECT TOP 1 1 FROM btype WHERE FullName= @strBType AND deleted=0 )
		BEGIN
			SET @ErrMsg = '结算单位[' + @strBType + ']已经停用,不能导入!' ;
			RETURN -1 ;
		END 

	--客户为父类时不能导入
	IF NOT EXISTS(SELECT 1 FROM btype WHERE FullName = @strBType AND deleted = 0 AND soncount = 0 )
		BEGIN
			SET @ErrMsg = '结算单位[' + @strBType + ']为父类,不能导入!' ;
			RETURN -1 ;
		END
END

  
--BName
IF LTRIM(RTRIM(@strBname)) = '' 
    BEGIN
        SET @ErrMsg = '持卡人不能为空,请检查!' ;
        RETURN -1 ;
    END

IF LEN(@strBname) > 66 
    BEGIN
        SET @ErrMsg = '持卡人[' + @strBname + ']长度不能超过66位,请检查!' ;
        RETURN -1 ;
    END
SET @Bname = @strBname ;


--PYCode
IF LEN(@strPYcode) > 300 
    BEGIN
        SET @ErrMsg = '持卡人拼音码[' + @strPYcode + ']长度不能超过 300位,请检查!' ;
        RETURN -1 ;
    END
ELSE 
    IF LTRIM(RTRIM(@strPYcode)) <>'' 
        BEGIN
            SET @PYcode = @strPYcode ;
        END

IF (@strPYcode = '')         
 set @Pycode = dbo.fun_getPY(@strBname)

--Birthday

IF @strBbirthday <> '' 
BEGIN
	IF (ISDATE(@strBbirthday) = 0 OR LEN(@strBbirthday) <> 10)
	BEGIN
		SET @ErrMsg = '生日必须为yyyy-mm-dd日期格式!' ;
		RETURN -1 ;
	END
END
 
SET @Bbirthday = CASE WHEN ISDATE(@strBbirthday) = 1
                      THEN CAST(@strBbirthday AS DATETIME)
                      WHEN ISNUMERIC(@strBbirthday) = 1
                      THEN CAST(CAST(@strBbirthday AS INT) - 2 AS DATETIME)	---excel 日期中存储的实际上是个int 和 sql中的日期转换的结果差值2
                      ELSE DATEADD(YEAR, -20, GETDATE())														---处理失败，默认持卡人20岁
                 END ;
               
IF @Bbirthday > GETDATE() 
    BEGIN
        SET @ErrMsg = '生日[' + @strBbirthday + ']不能超过今天,请检查!' ;
        RETURN -1 ;
    END

SET @Bbirthday=CONVERT(VARCHAR(10),@Bbirthday,120)
--BTel
IF LEN(@strBTel) > 50 
    BEGIN
        SET @ErrMsg = '手机[' + @strBTel + ']长度不能超过50,请检查!' ;
        RETURN -1 ;
    END
ELSE 
    IF LTRIM(RTRIM(@strBTel)) <> '' 
        BEGIN
            SET @BTel = @strBTel ;
        END
SET @BTel = @strBTel

--BAddr
IF LEN(@strBAddr) > 50 
    BEGIN
        SET @ErrMsg = '通讯地址[' + @strBAddr + ']长度不能超过50位,请检查!' ;
        RETURN -1 ;
    END
ELSE 
    IF LTRIM(RTRIM(@strBAddr)) <> '' 
        BEGIN
            SET @BAddr = @strBAddr ;
        END
SET @BAddr = @strBAddr

--BPostCode
IF LEN(@strBPostcode) > 200 
    BEGIN
        SET @ErrMsg = '邮政编码[' + @strBPostcode + ']长度不能超过200位,请检查!' ;
        RETURN -1 ;
    END
ELSE 
    IF LTRIM(RTRIM(@strBPostcode)) <> '' 
        BEGIN
            SET @BPostCode = @strBPostcode ;
        END
SET @BPostCode = @strBPostcode ;

--BTrade
IF LEN(@strBTrade) > 12 
    BEGIN
        SET @ErrMsg = '从事行业[' + @strBTrade + ']长度不能超过12位,请检查!' ;
        RETURN -1 ;
    END
ELSE 
    IF LTRIM(RTRIM(@strBTrade)) <> '' 
        BEGIN
            SET @BTrade = @strBTrade ;
        END
SET @BTrade = @strBTrade ;

--BIDCard
IF LEN(@strBIDcard) > 26 
    BEGIN
        SET @ErrMsg = '证件号码[' + @strBIDcard + ']长度不能超过26位,请检查!' ;
        RETURN -1 ;
    END
ELSE 
    IF LTRIM(RTRIM(@strBTrade)) <> '' 
        BEGIN
            SET @BIDcard = @strBIDcard ;
        END
SET @BIDcard = @strBIDcard ;

--BSex
SET @BSex = CASE WHEN @strBSex = '男' THEN '1'
                 WHEN @strBSex = '女' THEN '0'
                 ELSE '1'						--转换不成功默认为男
            END ;


-- VipStatus
/*
-- 映射的是deleted字段
-- 0 启用
-- 1 删除
-- 2 停用
-- 3 挂失
*/
SET @VipStatus = CASE WHEN @strVipStatus = '启用' THEN '0'
                      WHEN @strVipStatus = '删除' THEN '1'
                      WHEN @strVipStatus = '停用' THEN '2'
                      WHEN @strVipStatus = '挂失' THEN '3'
                      ELSE NULL
                 END ;
IF @VipStatus IS NULL 
    BEGIN
        SET @ErrMsg = '会员卡状态[' + @strVipStatus + ']不正确,请检查!' ;
        RETURN -1 ;
    END


--ETypeID
SELECT  @ETypeID = TypeID
FROM    [Employee]
WHERE   [FullName] = @strEType ;
IF @EtypeID IS NULL 
    BEGIN
        SET @ErrMsg = '发卡人[' + @strEType + ']不正确,请检查!' ;
        RETURN -1 ;
    END

--发卡人停用时不能导入
IF NOT EXISTS ( SELECT  1
                FROM    [Employee]
                WHERE   [FullName] = @strEType
                        AND deleted = 0 ) 
    BEGIN
        SET @ErrMsg = '发卡人[' + @strEType + ']已经被停用,不能导入!' ;
        RETURN -1 ;
    END

--发卡人为父类时不能导入
IF NOT EXISTS ( SELECT  1
                FROM    [Employee]
                WHERE   [FullName] = @strEType
                        AND deleted = 0
                        AND soncount = 0 ) 
    BEGIN
        SET @ErrMsg = '发卡人[' + @strEType + ']为父类,不能导入!' ;
        RETURN -1 ;
    END

--CreateDate

IF @strCreateDate <> '' 
BEGIN
	IF (ISDATE(@strCreateDate) = 0 OR LEN(@strCreateDate) <> 10)
	BEGIN
		SET @ErrMsg = '发卡日期必须为yyyy-mm-dd日期格式!' ;
		RETURN -1 ;
	END
END
SET @CreateDate = CASE WHEN ISDATE(@strCreateDate) = 1
                       THEN CAST(@strCreateDate AS DATETIME)
                       WHEN ISNUMERIC(@strCreateDate) = 1
                       THEN CAST(CAST(@strCreateDate AS INT) - 2 AS DATETIME)	---excel 日期中存储的实际上是个int 和 sql中的日期转换的结果差值2
                       ELSE GETDATE()
                  END ;
					
SET @CreateDate=CONVERT(VARCHAR(10),@CreateDate,120)
--EndDate
if(@strEndDate = '')
begin
	declare @ValidDate int,@ValidType int
	select @ValidDate = ValidDate,
	@ValidType = ValidType
	from nVipCardSet where VipCardTypeID = @VipCardTypeID
	if(@ValidType = 0)
	 set @EndDate = DATEADD(YY, @ValidDate, @CreateDate)
	 else if(@ValidType = 1)
	 set @EndDate = DATEADD(MM, @ValidDate, @CreateDate)
	 else if(@ValidType = 2)
	 set @EndDate = DATEADD(DAY, @ValidDate, @CreateDate)
	 set @EndDate = @EndDate - 1
end
else
begin
SET @EndDate = CASE WHEN ISDATE(@strEndDate) = 1
                    THEN CAST(@strEndDate AS DATETIME)
                    WHEN ISNUMERIC(@strEndDate) = 1
                    THEN CAST(CAST(@strEndDate AS INT) - 2 AS DATETIME)	---excel 日期中存储的实际上是个int 和 sql中的日期转换的结果差值2
                    ELSE GETDATE()
               END ;
SET @EndDate=CONVERT(VARCHAR(10),@EndDate,120)
end


if(@CreateDate > @EndDate)
BEGIN
            SET @ErrMsg = '有效期小于发卡日期' ;
            RETURN -1 ;
        END

--BeginMoney
IF @strBeginMoney IS NULL
    OR @strBeginMoney = '' 
    BEGIN
        SET @BeginMoney = 0 ;
    END
ELSE 
    IF ISNUMERIC(@strBeginMoney) = 1 
        BEGIN
            SET @BeginMoney = CAST(@strBeginMoney AS  NUMERIC(24, 10) ) ;
        END
    ELSE 
        BEGIN
            SET @ErrMsg = '初始消费金额[' + @strBeginMoney + ']请输入数字!' ;
            RETURN -1 ;
        END
IF ( ( SELECT   CHARINDEX('-', @strBeginMoney)
     ) <> 0 ) 
    BEGIN
        SET @ErrMsg = '初始消费金额不能为负数'
        RETURN -1
    END       
DECLARE @d_total INT
SELECT @d_total         = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 3
IF( dbo.F_CheckDecimal(@strBeginMoney,3,@d_total) < 0)
BEGIN
	SET @ErrMsg = '初始消费金额不能超出'+CONVERT(VARCHAR(5),@d_total)+'位数'
	RETURN -1
END

--BeginCent
IF @strBeginCent IS NULL
    OR @strBeginCent = '' 
    BEGIN
		set @BeginCent = 0
        --select @BeginCent = GiveCent from nVipCardSet where VipCardTypeID=@VipCardTypeID ;
    END
ELSE 
    IF ISNUMERIC(@strBeginCent) = 1 
        BEGIN
            SET @BeginCent = CAST(@strBeginCent AS  NUMERIC(24, 10) ) ;
        END
    ELSE 
        BEGIN 
            SET @ErrMsg = '初始积分[' + @strBeginMoney + ']请输入数字!' ;
            RETURN -1 ;
        END
IF ( ( SELECT   CHARINDEX('.', @strBeginCent)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '初始积分请输入整数'
                    RETURN -1
                END
            ELSE
IF ( ( SELECT   CHARINDEX('-', @strBeginCent)
     ) <> 0 ) 
    BEGIN
        SET @ErrMsg = '初始积分不能为负数'
        RETURN -1
    END                         
IF @ifJF = '1'
BEGIN
	SET @BeginCent = @BeginCent + @GiveCent  
END

--IsCz
SET @IsCz = CASE WHEN @strIsCz = '是' THEN '1'
                 WHEN @strIsCz = '否' THEN '0'
                 ELSE NULL
            END ;
IF @IsCz IS NULL 
    BEGIN
        SET @ErrMsg = '会员储值信息[' + @strIsCz + ']不正确,请检查!' ;
        RETURN -1 ;
    END

IF LEN(@strComment) > 256 
    BEGIN
        SET @ErrMsg = '备注长度不能超过256位,请检查!' ;
        RETURN -1 ;
    END
IF LTRIM(RTRIM(@strComment)) <> '' 
    BEGIN
        SET @Comment = @strComment ;
    END
ELSE 
    SET @Comment = ''
 
 --========================985 【BEGIN】===============================
 --建卡机构
 
DECLARE @jkStypeId VARCHAR(50)='00001'--默认值-【默认分支机构】
IF EXISTS(SELECT * FROM SysData WHERE SubName='ProInfo' AND SubValue=2)
	BEGIN
		IF ISNULL(LTRIM(RTRIM(@jkStypeCode)),'') = ''
			BEGIN
				SET @ErrMsg = '建卡机构编号不能为空,请检查!' ;
				RETURN -1 ;
			END	
		
		IF NOT EXISTS(SELECT * FROM SType WHERE UserCode=LTRIM(RTRIM(@jkStypeCode)))
			BEGIN
				SET @ErrMsg = '建卡机构编号不存在,请检查!' ;
				RETURN -1 ;
			END
		IF NOT EXISTS(SELECT * FROM SType WHERE UserCode=LTRIM(RTRIM(@jkStypeCode)) AND soncount=0)
			BEGIN
				SET @ErrMsg = '建卡机构编号不允许选择父级,请检查!' ;
				RETURN -1 ;
			END
			
		IF NOT EXISTS(SELECT * FROM SType WHERE UserCode=LTRIM(RTRIM(@jkStypeCode)) AND soncount=0 AND deleted = 0)
			BEGIN
				SET @ErrMsg = '建卡机构编号不允许选择停用机构,请检查!' ;
				RETURN -1 ;
			END	
			
		SELECT @jkStypeId=TypeId FROM SType WHERE UserCode=LTRIM(RTRIM(@jkStypeCode))
		
		IF NOT EXISTS(SELECT * FROM F_GetAllManagerBaseTypeId(@jkStypeId,11,@OperatorID))			
			BEGIN
				SET @ErrMsg = '建卡机构不在您分支机构权限范围内,请检查!' ;
				RETURN -1 ;
			END	
		
	END
 --========================985 【END】===============================
    
--QcCzMoney
DECLARE @isV1V3	INT
SELECT @isV1V3=CASE SubValue WHEN '2' THEN 0 ELSE 1 END FROM sysdata WHERE SubName='proinfo'
SET @qCcZMoney = 0 

IF @isV1V3 = 1 AND @IsCZ = 1
BEGIN 
	IF @strQcCzMoney IS NULL OR @strQcCzMoney = '' 
	BEGIN
		SET @qCcZMoney = 0 ;
	END
	ELSE 
		IF ISNUMERIC(@strQcCzMoney) = 1 
		BEGIN
			SET @qCcZMoney = CAST(@strQcCzMoney AS  NUMERIC(24, 10) ) ;
		END
		ELSE 
		BEGIN
			SET @ErrMsg = '期初储值金额[' + @strQcCzMoney + ']请输入数字!' ;
			RETURN -1 ;
		END
	    
	IF ( ( SELECT   CHARINDEX('-', @strQcCzMoney)) <> 0 ) 
	BEGIN
		SET @ErrMsg = '期初储值金额不能为负数'
		RETURN -1
	END       
	    
	IF( dbo.F_CheckDecimal(@strQcCzMoney,3,@d_total) < 0)
	BEGIN
		SET @ErrMsg = '期初储值金额不能超出'+CONVERT(VARCHAR(5),@d_total)+'位数'
		RETURN -1
	END
	
	IF EXISTS(SELECT * FROM dbo.SType_UserConfig WHERE stypeid = '00001' AND Value = 1) AND @qCcZMoney > 0
	BEGIN
		SET @ErrMsg = '账套已开账，不能进行期初储值余额的导入'
		RETURN -1	
	END 
END 
    
-----------------插入数据------------------------------------------------------------------------------

BEGIN TRAN

INSERT  INTO nVipCardSign
(
     VipCardCode,--vip卡号
     VipCardTypeID,--该卡所属vip卡的类型，与nVipCardSet相关联
     Bname,--持卡人姓名
     pycode,--持卡人拼音码
     Bsex,--性别0表示女，1表示男
     Bbirthday,--客户生日
     Btel,--联系电话
     Baddr,--联系地址
     Bpostcode,--邮编
     Btrade,--行业
     BIDcard,--证件号码
     ETypeID,--办理人id，和系统employee表关联
     CreateDate,--发卡日期
     EndDate,
     deleted,
     BeginMoney,--初始消费金额
     BeginCent,--初始积分
     totalMoney,--消费总金额
     totalCent,--总积分
     Comment,
     IsCz,
     qCczMoney,
     lJczMoney,
     RATypeID,
     BTypeID,
     CarType,
     CarWashPrice,
     IsWashTimes,
     CanWashTimes00,
     CanWashTimes,
     jkStypeId,
     isApplyAllStype,
     isApplyAllPOS,
     pWord
)VALUES(
     @VipCardCode,
     @VipCardTypeID,
     @Bname,
     @pycode,
     @Bsex,
     @Bbirthday,
     @Btel,
     @Baddr,
     @Bpostcode,
     @Btrade,
     @BIDcard,
     @ETypeID,
     @CreateDate,
     @EndDate,
     @VipStatus,
     @BeginMoney,
     @BeginCent,
     0,
     0,
     @Comment,
     @IsCz,
     @qCcZMoney,
     0,
     '',
     @BTypeID,
     0,
     0.0000,
     0,
     0,
     0,
     @jkStypeId,
     1,
     1,
     @srcpassword
) ;

IF @@ROWCOUNT = 0 
    BEGIN
        SET @ErrMsg = '客户添加失败,请重试或联系系统管理员!' ;
        RETURN -2
    END	

	
COMMIT TRAN

--================统计各个类型vip卡发放的数量=========
DECLARE @CardTypeid INT
DECLARE @num INT


UPDATE  nVipCardSet
SET     VipCardnum = (SELECT    COUNT(1)
                      FROM      [nVipCardSign]
                      WHERE     deleted <> '1'
                                AND VipCardTypeid = @VipCardTypeID
                     )
WHERE   VipCardTypeID = @VipCardTypeID

--==============期初刷新金额===========================
IF EXISTS ( SELECT TOP 1
                    1
            FROM    SysData
            WHERE   SubName = 'inicanmodify'
                    AND SubValue = 'T' ) 
BEGIN
	--刷新储值余额
    UPDATE  nVipCardSign
    SET     cZyeMoney = qCczMoney + lJczMoney
    WHERE   VipCardCode = @VipCardCode
	
	IF @isV1V3 = 1
	BEGIN
		--刷新会计科目
		DECLARE @numQcTotal  NUMERIC(24, 10)
				,@cid		INT
		SELECT  @numQcTotal = ISNULL(SUM(qCczMoney), 0)
		FROM    nVipCardSign
		
		SELECT @cid = CId FROM dbo.Ac_Currency WHERE Sysrow = 1
		
		IF EXISTS ( SELECT TOP 1 1 FROM AType_Total AT WHERE AT.ATypeID = '34' AND AT.CID = @cid ) 
		BEGIN
			UPDATE  AType_Total
			SET     Total00 = ISNULL(@numQcTotal, 0)
					,Ntotal00 = ISNULL(@numQcTotal, 0)
			WHERE   ATypeID = '34' AND CID = @cid
		END
		ELSE 
		BEGIN
			INSERT  INTO AType_Total
				(
				 ATypeID,
				 STypeID,
				 Total00,
				 Ntotal00,
				 CID
				)
			VALUES  (
					 '34',
					 '00001',
					 @numQcTotal,					 
					 @numQcTotal,
					 @cid
					 )
		END
    END 
END

--更新分支机构会员卡信息表
IF @isV1V3 = 1 AND @IsCZ = 1
BEGIN
	INSERT INTO dbo.nVipCardSignStype
	        ( VipCardID ,
	          StypeId ,
	          qCczMoney ,
	          lJczMoney ,
	          lJxFczMoney ,
	          bNczMoney ,
	          bNxFczMoney ,
	          cZyeMoney ,
	          lJxFMoney ,
	          bNxFMoney
	        )
	SELECT	c.VipCardID ,
			'00001',
			@qCcZMoney ,
			@qCcZMoney ,
			0,
			0 ,
			0 ,
			@qCcZMoney ,
			c.BeginMoney,
			0 
	FROM dbo.nVipCardSign c
	WHERE c.VipCardCode = @VipCardCode
	
	IF @@ROWCOUNT = 0 
    BEGIN
        SET @ErrMsg = '客户添加失败,请重试或联系系统管理员!' ;
        RETURN -2
    END	
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012-08-28
	描述：导入凭证模板
*/
CREATE PROCEDURE GP_ImportVoucherTemplate
(
	@OperatorId		VARCHAR(50),		-- 当前操作员ID
	@Data	TbType_VoucherTemplate	READONLY,
	@errmsg		VARCHAR(1000)	OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

--判断会计科目模板是否使用
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account_Set_List WHERE IsUse = 1)
BEGIN
	SET @errmsg = '未启用任何科目表！'
	RETURN -1
END


DECLARE @sfullname		VARCHAR(100),
		@billname		VARCHAR(100),
		@usercode		VARCHAR(200), --模板编号
		@fullname		VARCHAR(200), --模板名称
		@groupfullname	VARCHAR(50),
		@isdefault		VARCHAR(10),
		@summary		VARCHAR(200),	-- 摘要
		@atypefromname	VARCHAR(200),   
		@atypeusercode	VARCHAR(50),
		@atypefullname	VARCHAR(50),
		@dcname			VARCHAR(50),
		@totalfrom		VARCHAR(200),
		@assitems		VARCHAR(1000),
		@isCost			VARCHAR(50),
		
		@BillType		INT,			--单据类型
		@Default		INT,			--是否默认
		@PyCode			VARCHAR(200),	--拼音码
		@Group			INT,			--凭证字
		@stypeid		VARCHAR(50),	--分支机构ID
		
		@atid			INT,			--模板id
		
		@atypefrom		INT,				--科目来源
		@atypeid		VARCHAR(50),		-- 会计科目
		@dc				INT,				-- 借贷方向
		@BillMoneyId	INT,				--金额来源ID
		@express		VARCHAR(1000),		-- 金额来源_公式
		
		@atdid			INT,				--明细id
		@audittype		INT					

DECLARE @templateCount INT,@excelrowCount INT,@V3StypeBill INT,@hasAssetsTemp INT,@Currentfullname VARCHAR(200)

SET @templateCount = 0
SET @excelrowCount = 0

SET @HasAssetsTemp = 0

--存储分割的辅助核算
CREATE TABLE #tmpAssit
(
	typeWithDetail	VARCHAR(200),
	rowno			INT IDENTITY(1,1)
)

CREATE TABLE #tmpTypeWithDetail
(
	name	VARCHAR(100),
	rowno	INT IDENTITY(1,1)
)

DECLARE @typeWithDetail VARCHAR(200),@rowIndex INT,@rowCount INT,@typeName VARCHAR(100),@detailName VARCHAR(100),@type INT,@detail INT

--处理缺失金额字段
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE Express='(outcosttotal - incosttotal)' AND BillType = 160)
BEGIN
	INSERT INTO dbo.Ac_BillMoney_List
	        ( BillType ,
	          FullName ,
	          Express ,
	          Content ,
	          Sysrow
	        )
	VALUES  ( 160 ,
	          '出库成本金额 减 入库成本金额' , 
	          '(outcosttotal - incosttotal)' , 
	          '出库成本金额-入库成本金额' , 
	          1
	        )
END
--处理预制错字
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_BillMoney_List WHERE BillType = 161 AND FullName = '抹零后金额 减 实收金额')
BEGIN
	UPDATE dbo.Ac_BillMoney_List SET FullName = '抹零后金额 减 实付金额',Content = '抹零后金额-实付金额' 
	WHERE FullName = '抹零后金额 减 实收金额' AND BillType = 161
END

--是否固定资产初始化
DECLARE @InitAssetsFlag INT

DECLARE @CurrentBillType INT
SET @CurrentBillType = 0

BEGIN TRAN Import_Tran--开始事务

DECLARE BillCur CURSOR READ_ONLY FOR 
	SELECT 	sfullname ,
			billname		,
			usercode		,
			fullname		,
			groupfullname	,
			isdefault		,
			summary			,
			atypefrom		,
			CASE WHEN atypeusercode<>'' 
			THEN  dbo.F_GetNewUserCode(atypeusercode,dbo.F_GetDefaultLeveal(atypeusercode)) 
			ELSE atypeusercode 
			END atypeusercode	,
			atypefullname	,
			dc				,
			totalfrom		,
			assitems        ,
			isCost		 
	FROM @Data

OPEN BillCur

FETCH NEXT FROM BillCur INTO @sfullname	,
							@billname		,
							@usercode		,
							@fullname		,
							@groupfullname	,
							@isdefault		,
							@summary		,
							@atypefromname	,
							@atypeusercode	,
							@atypefullname	,
							@dcname			,
							@totalfrom		,
							@assitems		,
							@isCost
WHILE (@@FETCH_STATUS = 0)
BEGIN
	SET @excelrowCount += 1
	IF ISNULL(@fullname,'')<>''
		SET @Currentfullname = @fullname
	IF (ISNULL(@sfullname,'') <> '') --分支机构有值,新的模板
	BEGIN
		--1.取分支机构id，单据编号，凭证字编号,插表头，生成atid
		--2.判断科目来源，判断科目是否叶子结点，得到科目id
		--3.判断金额来源，得到金额来源id
		--4.写明细
		--5.科目来源手工的，判断辅助核算是否合适，写辅助核算
		
		SET @BillType = -1--置空
		SET @group = -1
		SET @stypeid = ''
		SET @V3StypeBill = 1
		
		SET @HasAssetsTemp = 0
		
		--判断前一模板是否有借有贷
		IF @templateCount <> 0
			AND (
				NOT  EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND Fdc = 1)
				OR NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND Fdc = -1)
				)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+ CAST(@excelrowCount -1 AS VARCHAR(10)) +'】行所属模板借贷缺少一方！'
			RETURN -1
		END
		
		
		--取各种ID
		SELECT @billtype = Billtype FROM dbo.BillName WHERE BillName LIKE N'' + @billname + N'%'
		
		IF ISNULL(@billname,'') = '部门转移'
			SET @BillType = -1
		ELSE IF ISNULL(@billname,'') = '计提资产减值准备'
			SET @BillType = -2
		ELSE IF ISNULL(@billtype,-1) = -1
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+ CAST(@excelrowCount AS VARCHAR(10))+'】行 单据类型【'+@billname+'】不可用！'
			RETURN -1
		END
		
		
		SELECT @stypeid = typeid FROM dbo.SType WHERE FullName = @sfullname
		
		--判断是否为固定资产卡片
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'assets' AND SubValue = 1)
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId = @STypeId AND IfAssetsIni = 1)
				SET @InitAssetsFlag = 1
			ELSE
				SET @InitAssetsFlag = 0	
		END
		ELSE
			SET @InitAssetsFlag = -1
		
		--固定资产未初始化
		IF @InitAssetsFlag = 0 AND @billtype IN (212,213,214,-1,-2)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+ CAST(@excelrowCount AS VARCHAR(10))+'】行 固定资产未初始化，【'+@Currentfullname +'】 无法导入！'
			SET @CurrentBillType = @billtype
			RETURN -1
		END		
		
		--V3，不导分支机构单据
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
			AND @BillType IN (187,188)
		BEGIN
			FETCH NEXT FROM BillCur INTO @sfullname	,
							@billname		,
							@usercode		,
							@fullname		,
							@groupfullname	,
							@isdefault		,
							@summary		,
							@atypefromname	,
							@atypeusercode	,
							@atypefullname	,
							@dcname			,
							@totalfrom		,
							@assitems	    ,
							@isCost
			SET @V3StypeBill = 0
			CONTINUE
		END
		
		IF (@isdefault = '是')
			SET @Default = 1
		ELSE
			SET @Default = 0
		
		
		SET @PyCode = dbo.Fun_GetPy(@FullName)

		SELECT @group = VgId FROM dbo.Ac_Voucher_Group WHERE FullName = @groupfullname
		
		IF ISNULL(@Group,-1) = -1
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+ CAST(@excelrowCount AS VARCHAR(10))+'】行 凭证字【'+@groupfullname+'】不可用！'
			RETURN -1
		END
		IF ISNULL(@stypeid,'') = ''
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 分支机构【'+@sfullname+'】不可用！'
			RETURN -1
		END
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId=@stypeid AND IsSelfVerify <> 1)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 分支机构【'+@sfullname+'】非独立核算，不能设置凭证模板！'
			RETURN -1
		END

		--判断是否重名
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE BillType = @BillType AND ( UserCode = @usercode OR FullName = @fullname) AND STypeId = @stypeid)
		BEGIN
			IF @billtype NOT IN (212,213,214)
			BEGIN
				ROLLBACK TRAN Import_Tran
				SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行：存在同名模板，无法导入！'
				RETURN -1
			END
		END
		
		--是否已有默认
		IF @Default = 1 AND
			 EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE BillType = @BillType AND IsDefault = 1 AND STypeId = @stypeid)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+ CAST(@excelrowCount AS VARCHAR(10))+'】行，已有默认模板， 无法再导入默认模板！'
			RETURN -1
		END
		
		--是否没有默认
		IF @Default = 0 AND
			 NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE BillType = @BillType AND IsDefault = 1 AND STypeId = @stypeid)
			AND @billtype NOT IN (212,213,214,-1,-2)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+ CAST(@excelrowCount AS VARCHAR(10))+'】行，没有默认模板， 不能直接导入非默认模板！'
			RETURN -1
		END

		INSERT INTO Ac_Auditing_Template
		(
			UserCode,
			FullName,
			BillType,
			ETypeId,
			IsDefault,
			CreateDateTime,
			PyCode,
			Comment,
			VgId,
			STypeId,
			Sysrow
		)VALUES(
			@UserCode,
			@FullName,
			@BillType,
			@OperatorId,
			@Default,
			GETDATE(),
			@PyCode,
			'',
			@Group,
			@stypeid,
			0
		)
		
		SET @atid = SCOPE_IDENTITY();
		
		SET @templateCount += 1
		
		
		--首条明细
		SELECT @atypefrom = CASE  WHEN @atypefromname = '手工选择' THEN 1
								  WHEN @atypefromname = '单据上收付款项目对应科目' THEN 2
								  WHEN @atypefromname = '单据上往来科目' THEN 3
								  WHEN @atypefromname = '单据上项目对应科目' THEN 4
								  WHEN (@atypefromname = '单据上项目对应固定资产科目' OR @atypefromname = '固定资产科目') THEN 5
								  WHEN @atypefromname = '单据上借方项目对应科目' THEN 6
								  WHEN @atypefromname = '单据上贷方项目对应科目' THEN 7
								  WHEN @atypefromname = '单据上业务类型对应科目' THEN 8
								  WHEN (@atypefromname = '单据上项目对应累计折旧科目' OR @atypefromname='固定资产累计折旧科目') THEN 9
								  WHEN (@atypefromname = '单据上项目对应折旧分配科目' OR @atypefromname = '固定资产折旧分配科目') THEN 10
								  WHEN @atypefromname = '固定资产减值准备科目' THEN 11
							END
		
		IF ISNULL(@atypefrom,-1) = -1
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 科目来源【'+@atypefromname+'】不可用！'
			RETURN -1
		END
		
		IF @atypefrom = 1
			SELECT @atypeid = TypeId FROM dbo.Ac_Account WHERE StypeId = @Stypeid AND UserCode = @atypeusercode
		
		IF @atypefrom = 1 AND ISNULL(@atypeid,'') = ''
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 科目【'+ @atypefullname + '】不存在，请检查科目编号和名称是否正确！'
			RETURN -1
		END		
		
		IF @atypefrom = 1 AND EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @stypeid AND TypeId = @atypeid AND SonNum > 0)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 科目【'+ @atypefullname + '】不是子科目，无法使用！'
			RETURN -1
		END
		
		SELECT @dc = CASE	WHEN @dcname = '借' THEN 1
							WHEN @dcname = '贷' THEN -1
					 END
		IF ISNULL(@dc,0) = 0
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 无此借贷方向:【'+@dcname+ '】！'
			RETURN -1
		END
		
		SELECT @BillMoneyId=BillMoneyId,@express = Express 
		FROM dbo.Ac_BillMoney_List 
		WHERE BillType = @billtype AND REPLACE(FullName,' ','') = REPLACE(@totalfrom,' ','')
		
		IF REPLACE(@totalfrom,' ','') = '平衡数'
			SELECT @BillMoneyId=BillMoneyId,@express = Express 
			FROM dbo.Ac_BillMoney_List 
			WHERE BillType = 0 AND REPLACE(FullName,' ','') = REPLACE(@totalfrom,' ','')
		
		IF ISNULL(@BillMoneyId,0) = 0 OR ISNULL(@express,'') = ''
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 金额来源【'+@totalfrom+'】不可用！'
			RETURN -1
		END
		
		INSERT INTO Ac_Auditing_Template_Detail
					(
						AtId,
						Summary,
						AcFrom,
						ATypeId,
						Fdc,
						BillMoneyId,
						Express,
						AssistCheckItmes,
						AssistCheckItmesIds,
						isCost
					)VALUES(
						@atid,
						@summary,
						@atypefrom,
						@atypeid,
						@dc,
						@BillMoneyId,
						@express,
						'',
						'',
						CASE WHEN ISNULL(@isCost,'')='成本' THEN 1 ELSE 0 END
					)
		
		SET @atdid = SCOPE_IDENTITY();
		--辅助核算
		INSERT INTO #tmpAssit
		        ( typeWithDetail)
		SELECT a
		FROM dbo.f_split(@assitems,',')
		
		
		SET @rowIndex = 1
		SELECT @rowCount = COUNT(*) FROM #tmpAssit
		
		WHILE(@rowIndex <= @rowCount)
		BEGIN
			SET @type = -1 --置空
			SET @detail = -1
		
			SELECT @typeWithDetail = typeWithDetail FROM #tmpAssit WHERE rowno = @rowIndex
			
			INSERT INTO #tmpTypeWithDetail(name)
			SELECT a
			FROM dbo.f_split(@typeWithDetail,':')
			
			SELECT @typeName = name FROM #tmpTypeWithDetail WHERE rowno = 1
			SELECT @detailName = name FROM #tmpTypeWithDetail WHERE rowno = 2
			
			SELECT @type = AscIds FROM dbo.Ac_Assist_CheckItems WHERE FullName = @typeName
			SELECT @detail = nId FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = @BillType AND AscIds = @type AND FullName = @detailName
			

			IF ISNULL(@type,-1) = -1
			BEGIN
				ROLLBACK TRAN Import_Tran
				SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 辅助核算类别【'+@typename+'】不可用！'
				RETURN -1
			END
			IF ISNULL(@detail,-1) = -1
			BEGIN
				ROLLBACK TRAN Import_Tran
				SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 辅助核算对应单据项目【'+@detailName+'】不可用！'
				RETURN -1
			END
			
			--V3辅助核算不带分支机构
			IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
				AND @type = 1
			BEGIN
				SET @rowIndex += 1
				TRUNCATE TABLE #tmpTypeWithDetail
				CONTINUE
			END
			
			INSERT INTO dbo.Ac_Auditing_Template_Detail_Assist_CheckItems
			        ( AtdId ,
			          Atid ,
			          AssistCheckItmes ,
			          AssistCheckItmesIds ,
			          Express ,
			          AscIds ,
			          AscIdsDetailId
			        )
			VALUES  ( @atdid ,@atid ,'' ,'' , '' , @type , @detail)
			
			SET @rowIndex += 1
			TRUNCATE TABLE #tmpTypeWithDetail
		END
		
		TRUNCATE TABLE #tmpAssit
		
		SET @atypefrom = -1
		SET @atypeid = ''
		SET @dc  = 0
		SET @BillMoneyId = 0
		SET @express = ''
		SET @type = -1
		SET @detail = -1
	END
	ELSE --没有值，当前模板明细
		--1.判断科目来源，判断科目是否叶子结点，得到科目id
		--2.判断金额来源，得到金额来源id
		--3.写明细
		--4.科目来源手工的，判断辅助核算是否合适，写辅助核算
	BEGIN
		IF @V3StypeBill = 0
		BEGIN
			FETCH NEXT FROM BillCur INTO @sfullname	,
							@billname		,
							@usercode		,
							@fullname		,
							@groupfullname	,
							@isdefault		,
							@summary		,
							@atypefromname	,
							@atypeusercode	,
							@atypefullname	,
							@dcname			,
							@totalfrom		,
							@assitems       ,
							@iscost
			CONTINUE
		END
		
		SELECT @atypefrom = CASE  WHEN @atypefromname = '手工选择' THEN 1
								  WHEN @atypefromname = '单据上收付款项目对应科目' THEN 2
								  WHEN @atypefromname = '单据上往来科目' THEN 3
								  WHEN @atypefromname = '单据上项目对应科目' THEN 4
								  WHEN (@atypefromname = '单据上项目对应固定资产科目' OR @atypefromname = '固定资产科目') THEN 5
								  WHEN @atypefromname = '单据上借方项目对应科目' THEN 6
								  WHEN @atypefromname = '单据上贷方项目对应科目' THEN 7
								  WHEN @atypefromname = '单据上业务类型对应科目' THEN 8
								  WHEN (@atypefromname = '单据上项目对应累计折旧科目' OR @atypefromname='固定资产累计折旧科目') THEN 9
								  WHEN (@atypefromname = '单据上项目对应折旧分配科目' OR @atypefromname = '固定资产折旧分配科目') THEN 10
								  WHEN @atypefromname = '固定资产减值准备科目' THEN 11
							END
		
		IF ISNULL(@atypefrom,-1) = -1
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 科目来源【'+@atypefromname+'】不可用！'
			RETURN -1
		END
		
		IF @atypefrom = 1
			SELECT @atypeid = TypeId FROM dbo.Ac_Account WHERE StypeId = @Stypeid AND UserCode = @atypeusercode
		
		IF @atypefrom = 1 AND ISNULL(@atypeid,'') = ''
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 科目【'+ @atypefullname + '】不存在，，请检查科目编号和名称是否正确！！'
			RETURN -1
		END		
		
		IF @atypefrom = 1 AND EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @stypeid AND TypeId = @atypeid AND SonNum > 0)
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 科目【'+ @atypefullname + '】不是子科目，无法使用！'
			RETURN -1
		END
		
		SELECT @dc = CASE	WHEN @dcname = '借' THEN 1
							WHEN @dcname = '贷' THEN -1
					 END
		IF ISNULL(@dc,0) = 0
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 无此借贷方向:【'+@dcname+ '】！'
			RETURN -1
		END
		
		SELECT @BillMoneyId=BillMoneyId,@express = Express 
		FROM dbo.Ac_BillMoney_List 
		WHERE BillType = @billtype AND REPLACE(FullName,' ','') = REPLACE(@totalfrom,' ','')
		
		IF REPLACE(@totalfrom,' ','') = '平衡数'
			SELECT @BillMoneyId=BillMoneyId,@express = Express 
			FROM dbo.Ac_BillMoney_List 
			WHERE BillType = 0 AND REPLACE(FullName,' ','') = REPLACE(@totalfrom,' ','')
		
		IF ISNULL(@BillMoneyId,0) = 0 OR ISNULL(@express,'') = ''
		BEGIN
			ROLLBACK TRAN Import_Tran
			SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 金额来源【'+@totalfrom+'】不可用！'
			RETURN -1
		END
		
		INSERT INTO Ac_Auditing_Template_Detail
					(
						AtId,
						Summary,
						AcFrom,
						ATypeId,
						Fdc,
						BillMoneyId,
						Express,
						AssistCheckItmes,
						AssistCheckItmesIds,
						isCost
					)VALUES(
						@atid,
						@summary,
						@atypefrom,
						@atypeid,
						@dc,
						@BillMoneyId,
						@express,
						'',
						'',
						CASE WHEN ISNULL(@isCost,'')='成本' THEN 1 ELSE 0 END
					)
		
		SET @atdid = SCOPE_IDENTITY();
		--辅助核算
		INSERT INTO #tmpAssit
		        ( typeWithDetail)
		SELECT a
		FROM dbo.f_split(@assitems,',')
		
		
		SET @rowIndex = 1
		SELECT @rowCount = COUNT(*) FROM #tmpAssit
		
		WHILE(@rowIndex <= @rowCount)
		BEGIN
			SET @type = -1 --置空
			SET @detail = -1
		
			SELECT @typeWithDetail = typeWithDetail FROM #tmpAssit WHERE rowno = @rowIndex
			
			INSERT INTO #tmpTypeWithDetail(name)
			SELECT a
			FROM dbo.f_split(@typeWithDetail,':')
			
			SELECT @typeName = name FROM #tmpTypeWithDetail WHERE rowno = 1
			SELECT @detailName = name FROM #tmpTypeWithDetail WHERE rowno = 2
			
			SELECT @type = AscIds FROM dbo.Ac_Assist_CheckItems WHERE FullName = @typeName
			SELECT @detail = nId FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = @BillType AND AscIds = @type AND FullName = @detailName
			
			
			IF ISNULL(@type,-1) = -1
			BEGIN
				ROLLBACK TRAN Import_Tran
				SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 辅助核算类别【'+@typename+'】不可用！'
				RETURN -1
			END
			IF ISNULL(@detail,-1) = -1
			BEGIN
				ROLLBACK TRAN Import_Tran
				SET @errmsg = '第【'+CAST(@excelrowCount AS VARCHAR(10))+'】行 辅助核算对应单据项目【'+@detailName+'】不可用！'
				RETURN -1
			END
			
			--V3辅助核算不带分支机构
			IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
				AND @type = 1
			BEGIN
				SET @rowIndex += 1
				TRUNCATE TABLE #tmpTypeWithDetail
				CONTINUE
			END
			
			INSERT INTO dbo.Ac_Auditing_Template_Detail_Assist_CheckItems
			        ( AtdId ,
			          Atid ,
			          AssistCheckItmes ,
			          AssistCheckItmesIds ,
			          Express ,
			          AscIds ,
			          AscIdsDetailId
			        )
			VALUES  ( @atdid ,@atid ,'' ,'' , '' , @type , @detail)
			
			SET @rowIndex += 1
			TRUNCATE TABLE #tmpTypeWithDetail
		END
		
		TRUNCATE TABLE #tmpAssit
		
		SET @atypefrom = -1
		SET @atypeid = ''
		SET @dc  = 0
		SET @BillMoneyId = 0
		SET @express = ''
		SET @type = -1
		SET @detail = -1
		
	END	
	
	
	
	FETCH NEXT FROM BillCur INTO @sfullname	,
							@billname		,
							@usercode		,
							@fullname		,
							@groupfullname	,
							@isdefault		,
							@summary		,
							@atypefromname	,
							@atypeusercode	,
							@atypefullname	,
							@dcname			,
							@totalfrom		,
							@assitems       ,
							@iscost
END

--判断最后一模板是否有借有贷
IF @templateCount <> 0
	AND (
		NOT  EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND Fdc = 1)
		OR NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid AND Fdc = -1)
		)
BEGIN
	ROLLBACK TRAN Import_Tran
	SET @errmsg = '第【'+CAST(@excelrowCount -1 AS VARCHAR(50)) +'】行所属模板借贷缺少一方！'
	RETURN -1
END

COMMIT TRAN Import_Tran--提交事务

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013-05-16
	描述：内部导入凭证模板
*/
CREATE PROCEDURE GP_ImportVoucherTemplate_Inner
(
	@OperatorId		VARCHAR(50),
	@STypeId		VARCHAR(50),
	@SubId			INT,
	@JustAssets		INT = 0,		--0.所有 1.仅固定资产管理相关的5种模板
	@OutValue		INT = 0	OUTPUT	-- 返回值
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId=@stypeid AND IsSelfVerify <> 1)
BEGIN
	RAISERROR('该分支机构非独立核算，不能设置凭证模板！',16,1)
	RETURN -1
END


DECLARE @billtype		INT,
		@usercode		VARCHAR(200), --模板编号
		@fullname		VARCHAR(200), --模板名称
		@groupfullname	VARCHAR(50),
		@summary		VARCHAR(200),	-- 摘要
		@atypefromname	VARCHAR(200),   
		@atypeusercode	VARCHAR(50),
		@atypefullname	VARCHAR(50),
		@dcname			VARCHAR(50),
		@totalfrom		VARCHAR(200),
		@assitems		VARCHAR(1000),
		@PyCode			VARCHAR(200),	--拼音码
		@Group			INT,			--凭证字
		@atid			INT,			--模板id
		@atypefrom		INT,				--科目来源
		@atypeid		VARCHAR(50),		-- 会计科目
		@dc				INT,				-- 借贷方向
		@BillMoneyId	INT,				--金额来源ID
		@express		VARCHAR(1000),		-- 金额来源_公式
		@atdid			INT,				--明细id
		@audittype		INT,		
		@ChargeOffType	INT,				--往来核销类别
		@inouttype		INT,			--310调出 调入 区分
		@isCost			INT,			--是否是成本类明细
		@orderID		INT				--排序ID

DECLARE @templateCount INT,@V3StypeBill INT,@errmsg VARCHAR(MAX),@Currentfullname VARCHAR(200),@HasAssetsTemp INT

SET @templateCount = 0

SET @HasAssetsTemp = 0

DECLARE @InitAssetsFlag INT
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'assets' AND SubValue = 1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId = @STypeId AND IfAssetsIni = 1)
		SET @InitAssetsFlag = 1
	ELSE
		SET @InitAssetsFlag = 0	
END
ELSE
	SET @InitAssetsFlag = -1

	
--存储分割的辅助核算
CREATE TABLE #tmpAssit
(
	typeWithDetail	VARCHAR(200),
	rowno			INT IDENTITY(1,1)
)

CREATE TABLE #tmpTypeWithDetail
(
	name	VARCHAR(100),
	rowno	INT IDENTITY(1,1)
)

--异常信息存储
CREATE TABLE #ErrorMsg
(
	msg	VARCHAR(MAX),
	msgtype	INT
)

--删除原有系统模板	
DELETE FROM dbo.Ac_Auditing_Template WHERE Sysrow = 1 AND STypeId = @STypeId AND @JustAssets = 0
DELETE  dbo.Ac_Auditing_Template_Detail FROM dbo.Ac_Auditing_Template_Detail ad INNER JOIN dbo.Ac_Auditing_Template a ON a.AtId = ad.Atid WHERE a.Sysrow = 1 AND a.STypeId = @STypeId AND @JustAssets = 0

DECLARE @typeWithDetail VARCHAR(200),@rowIndex INT,@rowCount INT,@typeName VARCHAR(100),@detailName VARCHAR(100),@type INT,@detail INT

DECLARE @CurrentBillType INT
SET @CurrentBillType = 0

DECLARE @index INT
SET @index = 0

DECLARE BillCur CURSOR READ_ONLY FOR 
	SELECT 	Billtype		,
			usercode,
			fullname		,
			groupfullname	,
			summary			,
			atypefrom		,
			CASE WHEN atypeusercode<>'' 
			 THEN  dbo.F_GetNewUserCode(atypeusercode,dbo.F_GetDefaultLeveal(atypeusercode)) 
			 ELSE atypeusercode 
			 END atypeusercode	,
			atypefullname	,
			dc				,
			totalfrom		,
			assitems		,
			audittype		,
			ChargeOffType  ,
			InOutType,
			isCost,
			orderID
	FROM VoucherTemplatePreset
	WHERE SubId = @SubId
	ORDER BY Billtype ASC ,InOutType,summary,AuditType,ChargeOffType,mainrow DESC

OPEN BillCur

FETCH NEXT FROM BillCur INTO @BillType	,
							@usercode		,
							@fullname		,
							@groupfullname	,
							@summary		,
							@atypefromname	,
							@atypeusercode	,
							@atypefullname	,
							@dcname			,
							@totalfrom		,
							@assitems		,
							@audittype		,
							@ChargeOffType	,
							@inouttype,
							@isCost,
							@orderID
WHILE (@@FETCH_STATUS = 0)
BEGIN
	IF ISNULL(@fullname,'')<>''
		SET @Currentfullname = @fullname
	IF (ISNULL(@usercode,'') <> '') --编号有值,新的模板
	BEGIN
		--1.取分支机构id，单据编号，凭证字编号,插表头，生成atid
		--2.判断科目来源，判断科目是否叶子结点，得到科目id
		--3.判断金额来源，得到金额来源id
		--4.写明细
		--5.科目来源手工的，判断辅助核算是否合适，写辅助核算
		
		SET @group = -1
		SET @V3StypeBill = 1
		
		SET @HasAssetsTemp = 0
		
		--IF @billtype = @CurrentBillType
		--	GOTO Again;
		
		IF @JustAssets = 1 AND @billtype NOT IN (212,213,214,-1,-2,410,411)--仅导入新增的固定资产相关模板
			GOTO Again;
		--固定资产卡片未启用
		ELSE IF @InitAssetsFlag = -1 AND @billtype IN (212,213,214,-1,-2,410,411)
		BEGIN
			GOTO Again
		END
		--固定资产未初始化
		--ELSE IF @InitAssetsFlag = 0 AND @billtype IN (212,213,214,-1,-2,410)
		--BEGIN
		--	INSERT INTO #ErrorMsg(msg,msgtype)
		--	SELECT '固定资产未初始化，【'+@Currentfullname +'】 无法导入！',0
		--	SET @CurrentBillType = @billtype
		--	GOTO Again
		--END

		--固定资产相关的已存在，不再导入
		IF @JustAssets = 0 AND @billtype IN (212,213,214,-1,-2,410,411) 
			AND EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE BillType = @billtype AND AuditType = @audittype AND STypeId = @STypeId) 
		BEGIN
			SET @HasAssetsTemp = 1
			GOTO Again
		END
		
		
		SET @atid = 0
		
		IF ISNULL(@billtype,-1) = -1 AND ISNULL(@audittype,0) = 0
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 单据类型不可用！',0
			SET @CurrentBillType = @billtype
			GOTO Again
		END
		
		--V3，不导分支机构单据
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
			AND @BillType IN (187,188)
		BEGIN
			FETCH NEXT FROM BillCur INTO
							@billtype		,
							@usercode		,
							@fullname		,
							@groupfullname	,
							@summary		,
							@atypefromname	,
							@atypeusercode	,
							@atypefullname	,
							@dcname			,
							@totalfrom		,
							@assitems		,
							@audittype		,
							@ChargeOffType
			SET @V3StypeBill = 0
		END
		
		
		
		SET @PyCode = dbo.Fun_GetPy(@FullName)

		SELECT @group = VgId FROM dbo.Ac_Voucher_Group WHERE FullName = @groupfullname
		
		IF ISNULL(@Group,-1) = -1
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 凭证字【'+@groupfullname+'】不可用',0
			SET @CurrentBillType = @billtype
			GOTO Again
		END


		--判断是否重名
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE BillType = @BillType AND ( UserCode = @usercode OR FullName = @fullname) AND STypeId = @stypeid)
		BEGIN
			IF (SELECT COUNT(*) FROM dbo.Ac_Auditing_Template WHERE BillType = @billtype AND STypeId = @STypeId AND BillType NOT IN (212,213,214)) = 1
				UPDATE dbo.Ac_Auditing_Template SET IsDefault = 1 WHERE BillType = @billtype
		
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】已有同名或同编号的模版，请修改已有模版编号或名称后执行导入',1
			SET @CurrentBillType = @billtype
			GOTO Again
		END
		


		INSERT INTO Ac_Auditing_Template
		(
			UserCode,
			FullName,
			BillType,
			ETypeId,
			IsDefault,
			CreateDateTime,
			PyCode,
			Comment,
			VgId,
			STypeId,
			Sysrow,
			AuditType,
			ChargeOffType,
			InOutType
		)VALUES(
			@UserCode,
			@FullName,
			@BillType,
			@OperatorId,
			CASE WHEN @billtype IN (212,213,214,410) THEN 1 ELSE 1 END,--9.8.1 bug1486 固定资产模板增加是否字段
			GETDATE(),
			@PyCode,
			'',
			@Group,
			@stypeid,
			1,
			@audittype,
			@ChargeOffType,
			@inouttype
		)
		
		SET @atid = SCOPE_IDENTITY();
		
		
		SET @templateCount += 1
		
		
		--首条明细
		SELECT @atypefrom = CASE  WHEN @atypefromname = '手工选择' THEN 1
								  WHEN @atypefromname = '单据上收付款项目对应科目' THEN 2
								  WHEN @atypefromname = '单据上往来科目' THEN 3
								  WHEN @atypefromname = '单据上项目对应科目' THEN 4
								  WHEN (@atypefromname = '固定资产科目' OR @atypefromname = '固定资产科目') THEN 5
								  WHEN @atypefromname = '单据上借方项目对应科目' THEN 6
								  WHEN @atypefromname = '单据上贷方项目对应科目' THEN 7
								  WHEN @atypefromname = '单据上业务类型对应科目' THEN 8
								  WHEN (@atypefromname = '单据上项目对应累计折旧科目' OR @atypefromname='固定资产累计折旧科目') THEN 9
								  WHEN (@atypefromname = '单据上项目对应折旧分配科目' OR @atypefromname = '固定资产折旧分配科目') THEN 10
								  WHEN @atypefromname = '固定资产减值准备科目' THEN 11
								  WHEN @atypefromname = '单据上账户对应科目' THEN 12
								  WHEN @atypefromname = '单据上往来科目（借）' THEN 13
								  WHEN @atypefromname = '单据上往来科目（贷）' THEN 14
								  WHEN @atypefromname = '存货类型的存货科目' THEN 15
								  WHEN @atypefromname = '存货类型的收入科目' THEN 16
								  WHEN @atypefromname = '存货类型的成本科目' THEN 17
								  WHEN @atypefromname = '入账原值差异科目' THEN 18
								  WHEN @atypefromname = '汇率影响原值科目' THEN 19
								  WHEN @atypefromname = '固定资产折旧分配科目' THEN 20
								  WHEN @atypefromname = '固定资产累计折旧科目' THEN 21
							END
		
		IF ISNULL(@atypefrom,-1) = -1
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 科目来源【'+@atypefromname+'】不可用',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END
		
		SET @atypeid=''
		IF @atypefrom = 1
			SELECT @atypeid = TypeId FROM dbo.Ac_Account WHERE StypeId = @Stypeid AND UserCode = @atypeusercode
		
		IF @atypefrom = 1 AND ISNULL(@atypeid,'') = ''
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 科目【'+ @atypefullname + '】不存在',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END		
		
		IF @atypefrom = 1 AND EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @stypeid AND TypeId = @atypeid AND SonNum > 0)
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 科目【'+ @atypefullname + '】不是子科目，无法使用',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END
		
		--对预置模板中银行科目的辅助核算进行检测，如果辅助核算没有挂银行账户，不导入此辅助
		IF @atypeid = '0000100002'
			AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account T1
					LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.TypeId = T2.ATypeId AND T1.StypeId = T2.STypeId
					WHERE T1.TypeId = @atypeid AND T1.StypeId = @stypeid AND T2.Ascids = 5)
		BEGIN
			SET @assitems = ''
		END
		
		SELECT @dc = CASE	WHEN @dcname = '借' THEN 1
							WHEN @dcname = '贷' THEN -1
					 END
		IF ISNULL(@dc,0) = 0
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 无此借贷方向:【'+@dcname+ '】',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END
		
		IF @totalfrom = '平衡数'
			SELECT @BillMoneyId=BillMoneyId,@express = Express 
			FROM dbo.Ac_BillMoney_List 
			WHERE BillType = 0 AND REPLACE(FullName,' ','') = REPLACE(@totalfrom,' ','')
		ELSE
			SELECT @BillMoneyId=BillMoneyId,@express = Express 
			FROM dbo.Ac_BillMoney_List 
			WHERE BillType = @billtype AND REPLACE(FullName,' ','') = REPLACE(@totalfrom,' ','')
		
		IF ISNULL(@BillMoneyId,0) = 0 OR ISNULL(@express,'') = ''
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 金额来源【'+@totalfrom+'】不可用',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END
		
		INSERT INTO Ac_Auditing_Template_Detail
					(
						AtId,
						Summary,
						AcFrom,
						ATypeId,
						Fdc,
						BillMoneyId,
						Express,
						AssistCheckItmes,
						AssistCheckItmesIds,
						isCost,
						OrderID
					)VALUES(
						@atid,
						@summary,
						@atypefrom,
						@atypeid,
						@dc,
						@BillMoneyId,
						@express,
						'',
						'',
						@isCost,
						@OrderID
					)
		
		SET @atdid = SCOPE_IDENTITY();
		--辅助核算
		TRUNCATE TABLE #tmpAssit
		INSERT INTO #tmpAssit
		        ( typeWithDetail)
		SELECT a
		FROM dbo.f_split(@assitems,',')
		
		
		SET @rowIndex = 1
		SELECT @rowCount = COUNT(*) FROM #tmpAssit
		
		WHILE(@rowIndex <= @rowCount)
		BEGIN
			SET @type = -1 --置空
			SET @detail = -1
		
			SELECT @typeWithDetail = typeWithDetail FROM #tmpAssit WHERE rowno = @rowIndex
			
			INSERT INTO #tmpTypeWithDetail(name)
			SELECT a
			FROM dbo.f_split(@typeWithDetail,':')
			
			SELECT @typeName = name FROM #tmpTypeWithDetail WHERE rowno = 1
			SELECT @detailName = name FROM #tmpTypeWithDetail WHERE rowno = 2
			
			SELECT @type = AscIds FROM dbo.Ac_Assist_CheckItems WHERE FullName = @typeName
			SELECT @detail = nId FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = @BillType AND AscIds = @type AND FullName = @detailName
			

			IF ISNULL(@type,-1) = -1
			BEGIN
				INSERT INTO #ErrorMsg(msg,msgtype)
				SELECT '【'+@Currentfullname +'】 辅助核算类别【'+@typename+'】不可用',0
				SET @CurrentBillType = @billtype
				DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
				DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
				DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
				GOTO Again
			END
			IF ISNULL(@detail,-1) = -1
			BEGIN
				INSERT INTO #ErrorMsg(msg,msgtype)
				SELECT '【'+@Currentfullname +'】 辅助核算对应单据项目【'+@detailName+'】不可用',0
				SET @CurrentBillType = @billtype
				DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
				DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
				DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
				GOTO Again
			END
			
			--V3辅助核算不带分支机构
			IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
				AND @type = 1
			BEGIN
				SET @rowIndex += 1
				TRUNCATE TABLE #tmpTypeWithDetail
				CONTINUE
			END
			
			INSERT INTO dbo.Ac_Auditing_Template_Detail_Assist_CheckItems
			        ( AtdId ,
			          Atid ,
			          AssistCheckItmes ,
			          AssistCheckItmesIds ,
			          Express ,
			          AscIds ,
			          AscIdsDetailId
			        )
			VALUES  ( @atdid ,@atid ,'' ,'' , '' , @type , @detail)
			
			SET @rowIndex += 1
			TRUNCATE TABLE #tmpTypeWithDetail
		END
		
		TRUNCATE TABLE #tmpAssit
		
		SET @atypefrom = -1
		SET @atypeid = ''
		SET @dc  = 0
		SET @BillMoneyId = 0
		SET @express = ''
		SET @type = -1
		SET @detail = -1
	END
	ELSE --没有值，当前模板明细
		--1.判断科目来源，判断科目是否叶子结点，得到科目id
		--2.判断金额来源，得到金额来源id
		--3.写明细
		--4.科目来源手工的，判断辅助核算是否合适，写辅助核算
	BEGIN
		IF @V3StypeBill = 0 OR ISNULL(@atid,0) = 0
		BEGIN
			GOTO Again
		END
		
		IF @JustAssets = 1 AND @billtype NOT IN (212,213,214,-1,-2,410)--仅导入新增的固定资产相关模板
			GOTO Again;
		--固定资产卡片未启用
		ELSE IF @InitAssetsFlag = -1 AND @billtype IN (212,213,214,-1,-2,410)
		BEGIN
			GOTO Again
		END
		--固定资产未初始化
		--ELSE IF @InitAssetsFlag = 0 AND @billtype IN (212,213,214,-1,-2,410)
		--BEGIN
		--	GOTO Again
		--END
		--固定资产相关的已存在，不再导入
		IF @HasAssetsTemp = 1
		BEGIN
			GOTO Again;
		END
		
		SELECT @atypefrom = CASE  WHEN @atypefromname = '手工选择' THEN 1
								  WHEN @atypefromname = '单据上收付款项目对应科目' THEN 2
								  WHEN @atypefromname = '单据上往来科目' THEN 3
								  WHEN @atypefromname = '单据上项目对应科目' THEN 4
								  WHEN (@atypefromname = '固定资产科目' OR @atypefromname = '固定资产科目') THEN 5
								  WHEN @atypefromname = '单据上借方项目对应科目' THEN 6
								  WHEN @atypefromname = '单据上贷方项目对应科目' THEN 7
								  WHEN @atypefromname = '单据上业务类型对应科目' THEN 8
								  WHEN (@atypefromname = '单据上项目对应累计折旧科目' OR @atypefromname='固定资产累计折旧科目') THEN 9
								  WHEN (@atypefromname = '单据上项目对应折旧分配科目' OR @atypefromname = '固定资产折旧分配科目') THEN 10
								  WHEN @atypefromname = '固定资产减值准备科目' THEN 11
								  WHEN @atypefromname = '单据上账户对应科目' THEN 12
								  WHEN @atypefromname = '单据上往来科目（借）' THEN 13
								  WHEN @atypefromname = '单据上往来科目（贷）' THEN 14
								  WHEN @atypefromname = '存货类型的存货科目' THEN 15
								  WHEN @atypefromname = '存货类型的收入科目' THEN 16
								  WHEN @atypefromname = '存货类型的成本科目' THEN 17
								  WHEN @atypefromname = '入账原值差异科目' THEN 18
								  WHEN @atypefromname = '汇率影响原值科目' THEN 19
								  WHEN @atypefromname = '固定资产折旧分配科目' THEN 20
								  WHEN @atypefromname = '固定资产累计折旧科目' THEN 21
							END
		
		IF ISNULL(@atypefrom,-1) = -1
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 科目来源【'+@atypefromname+'】不可用',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END
		
		SET @atypeid=''
		IF @atypefrom = 1
			SELECT @atypeid = TypeId FROM dbo.Ac_Account WHERE StypeId = @Stypeid AND UserCode = @atypeusercode
		
		IF @atypefrom = 1 AND ISNULL(@atypeid,'') = ''
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 科目【'+ @atypefullname + '】不存在',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END		
		
		IF @atypefrom = 1 AND EXISTS (SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @stypeid AND TypeId = @atypeid AND SonNum > 0)
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 科目【'+ @atypefullname + '】不是子科目，无法使用',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END
		
		--对预置模板中银行科目的辅助核算进行检测，如果辅助核算没有挂银行账户，不导入此辅助
		IF @atypeid = '0000100002'
			AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account T1
					LEFT JOIN dbo.Ac_Account_Assist_CheckItems T2 ON T1.TypeId = T2.ATypeId AND T1.StypeId = T2.STypeId
					WHERE T1.TypeId = @atypeid AND T1.StypeId = @stypeid AND T2.Ascids = 5)
		BEGIN
			SET @assitems = ''
		END
		
		SELECT @dc = CASE	WHEN @dcname = '借' THEN 1
							WHEN @dcname = '贷' THEN -1
					 END
		IF ISNULL(@dc,0) = 0
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 无此借贷方向:【'+@dcname+ '】',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END
		
		IF @totalfrom = '平衡数'
			SELECT @BillMoneyId=BillMoneyId,@express = Express 
			FROM dbo.Ac_BillMoney_List 
			WHERE BillType = 0 AND REPLACE(FullName,' ','') = REPLACE(@totalfrom,' ','')
		ELSE
			SELECT @BillMoneyId=BillMoneyId,@express = Express 
			FROM dbo.Ac_BillMoney_List 
			WHERE BillType = @billtype AND REPLACE(FullName,' ','') = REPLACE(@totalfrom,' ','')
		
		IF ISNULL(@BillMoneyId,0) = 0 OR ISNULL(@express,'') = ''
		BEGIN
			INSERT INTO #ErrorMsg(msg,msgtype)
			SELECT '【'+@Currentfullname +'】 金额来源【'+@totalfrom+'】不可用',0
			SET @CurrentBillType = @billtype
			DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
			DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
			GOTO Again
		END
		
		INSERT INTO Ac_Auditing_Template_Detail
					(
						AtId,
						Summary,
						AcFrom,
						ATypeId,
						Fdc,
						BillMoneyId,
						Express,
						AssistCheckItmes,
						AssistCheckItmesIds,
						isCost,
						OrderID
					)VALUES(
						@atid,
						@summary,
						@atypefrom,
						@atypeid,
						@dc,
						@BillMoneyId,
						@express,
						'',
						'',
						@isCost,
						@orderID
					)
		
		SET @atdid = SCOPE_IDENTITY();
		--辅助核算
		TRUNCATE TABLE #tmpAssit
		INSERT INTO #tmpAssit
		        ( typeWithDetail)
		SELECT a
		FROM dbo.f_split(@assitems,',')
		
		
		SET @rowIndex = 1
		SELECT @rowCount = COUNT(*) FROM #tmpAssit
		
		WHILE(@rowIndex <= @rowCount)
		BEGIN
			SET @type = -1 --置空
			SET @detail = -1
		
			SELECT @typeWithDetail = typeWithDetail FROM #tmpAssit WHERE rowno = @rowIndex
			
			INSERT INTO #tmpTypeWithDetail(name)
			SELECT a
			FROM dbo.f_split(@typeWithDetail,':')
			
			SELECT @typeName = name FROM #tmpTypeWithDetail WHERE rowno = 1
			SELECT @detailName = name FROM #tmpTypeWithDetail WHERE rowno = 2
			
			SELECT @type = AscIds FROM dbo.Ac_Assist_CheckItems WHERE FullName = @typeName
			SELECT @detail = nId FROM dbo.Ac_Assist_CheckItems_BillType WHERE BillType = @BillType AND AscIds = @type AND FullName = @detailName
			
			
			IF ISNULL(@type,-1) = -1
			BEGIN
				INSERT INTO #ErrorMsg(msg,msgtype)
				SELECT '【'+@Currentfullname +'】 辅助核算类别【'+@typename+'】不可用',0
				SET @CurrentBillType = @billtype
				DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
				DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
				DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
				GOTO Again
			END
			IF ISNULL(@detail,-1) = -1
			BEGIN
				INSERT INTO #ErrorMsg(msg,msgtype)
				SELECT '【'+@Currentfullname +'】 辅助核算对应单据项目【'+@detailName+'】不可用',0
				SET @CurrentBillType = @billtype
				DELETE FROM dbo.Ac_Auditing_Template WHERE AtId = @Atid
				DELETE FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @Atid
				DELETE FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems WHERE Atid = @Atid
				GOTO Again
			END
			
			--V3辅助核算不带分支机构
			IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
				AND @type = 1
			BEGIN
				SET @rowIndex += 1
				TRUNCATE TABLE #tmpTypeWithDetail
				CONTINUE
			END
			
			INSERT INTO dbo.Ac_Auditing_Template_Detail_Assist_CheckItems
			        ( AtdId ,
			          Atid ,
			          AssistCheckItmes ,
			          AssistCheckItmesIds ,
			          Express ,
			          AscIds ,
			          AscIdsDetailId
			        )
			VALUES  ( @atdid ,@atid ,'' ,'' , '' , @type , @detail)
			
			SET @rowIndex += 1
			TRUNCATE TABLE #tmpTypeWithDetail
		END
		
		TRUNCATE TABLE #tmpAssit
		
		SET @atypefrom = -1
		SET @atypeid = ''
		SET @dc  = 0
		SET @BillMoneyId = 0
		SET @express = ''
		SET @type = -1
		SET @detail = -1
		
		SET @CurrentBillType = 0
	END	
	

	Again:
	FETCH NEXT FROM BillCur INTO @BillType	,
							@usercode		,
							@fullname		,
							@groupfullname	,
							@summary		,
							@atypefromname	,
							@atypeusercode	,
							@atypefullname	,
							@dcname			,
							@totalfrom		,
							@assitems		,
							@audittype		,
							@ChargeOffType  ,
							@inouttype,
							@isCost,
							@orderID
							
END

CLOSE BillCur
DEALLOCATE BillCur		

SELECT * FROM #ErrorMsg


IF EXISTS(SELECT TOP 1 1 FROM #ErrorMsg WHERE msgtype = 0)
	SET @OutValue = -1
ELSE
	SET @OutValue = 0

DROP TABLE #ErrorMsg

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/****** Object:  StoredProcedure [dbo].[gp_ImportWeiTuo]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：廖晨羽
	日    期：2011-08-29
	描	  述：导入委托代销期初
*/


CREATE         PROCEDURE [dbo].[gp_ImportWeiTuo]
(
	@SFullName   [varchar](200),		--分支机构名称
	@BFullName   [varchar](200),		--往来单位名称
	@PUserCode	 [varchar](200),		--商品编号
	@PFullName   [varchar](200),		--商品名称
	@StrQty  [varchar](18),			--委托代销数量
	@StrCostPrice  [varchar](18),		--成本单价
	@StrPrice	[varchar](18),		--结算单价
	@explain VARCHAR(256),			--说明
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) OUTPUT,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------
DECLARE @Allow VARCHAR(50),@operId VARCHAR(max)  ---分解是否允许供货商和操作员id
SET @Allow = (SELECT TOP 1 A FROM f_split(@typeid,'я'))
SET @operId = (SELECT A FROM f_split(@typeid,'я') WHERE A <> @Allow)

DECLARE @stypeid	VARCHAR(1000)
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[A8ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF (@SFullName = '' OR @SFullName = '总部' OR NOT EXISTS(SELECT typeid FROM dbo.SType WHERE fullname = @SFullName))
	BEGIN
		SET @ErrMsg = '该分支机构不存在'
		RETURN -1
	END
	ELSE
	BEGIN
		DECLARE @PStypeId VARCHAR(50)
		DECLARE @SChildCount NUMERIC(18,0)
		SET @PStypeId = (SELECT TOP 1 typeid FROM dbo.SType WHERE fullname = @SFullName)
		SELECT @SChildCount = COUNT(*) FROM dbo.SType WHERE typeId LIKE @PStypeId + '%' AND typeId <> @PStypeId
		IF (@SChildCount = 0)
			BEGIN
				SET @stypeid = @PStypeId		
				IF (@stypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@operId)))
				BEGIN
					SET @ErrMsg = '操作员不具备该分支机构权限'
					RETURN -1
				END				
			END
		ELSE
			BEGIN
				SET @ErrMsg = '该分支机构是父类'
				RETURN -1
			END
	END

	--判断分支机构是否已开账
	IF ((SELECT U.Value FROM SType_UserConfig U,SType_Config C WHERE U.ConfigNo = C.ConfigNo AND U.Value = '1' AND U.STypeID = @stypeid) = 1)
BEGIN
	SET @ErrMsg = '该分支机构已开账'
	RETURN -1
END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V3ZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QPZTInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	IF(@SFullName = '' OR @SFullName='默认分支机构')
	BEGIN
		SET @stypeid = '00001'
	END
	ELSE
	BEGIN
		SET @ErrMsg = '分支机构只能填默认分支机构或为空'
		RETURN -1
	END
END

DECLARE	@btypeid		varchar(1000)
IF(@BFullName = '全部供货商' OR @BFullName = '所有客户')
BEGIN
	SET @ErrMsg = '该往来单位是父类'
	RETURN -1
END
IF (@BFullName = '' OR @BFullName = 'ABC' OR NOT EXISTS(SELECT typeid FROM dbo.btype WHERE fullname = @BFullName))
BEGIN
	SET @ErrMsg = '该往来单位不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PBtypeId VARCHAR(50)
	DECLARE @BChildCount NUMERIC(18,0)
	SET @PBtypeId = (SELECT TOP 1 typeid FROM dbo.btype WHERE fullname = @BFullName)
	SELECT @BChildCount = COUNT(*) FROM dbo.btype WHERE typeId LIKE @PBtypeId + '%' AND typeId <> @PBtypeId
	IF (@BChildCount = 0)
		BEGIN
			SET @btypeid = @PBtypeId	
			IF (@btypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@operId)))
			BEGIN
				SET @ErrMsg = '操作员不具备该往来单位权限'
				RETURN -1
			END					
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该往来单位是父类'
			RETURN -1
		END
END

IF(@Allow = 'False')
BEGIN
	DECLARE @tempBtypeid VARCHAR(max)
	SET @tempBtypeid = SUBSTRING(@btypeid,1,5)
	IF(@tempBtypeid = '00002')
	BEGIN
			SET @ErrMsg = '该往来单位不能是供货商'
			RETURN -1
	END
END

IF(@PUserCode = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @PUserCode) OR @PUserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
ELSE IF (@PFullName = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @PFullName) OR @PFullName='库存配件')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
ELSE IF(@PFullName <> (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @PUserCode))
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PtypeId  VARCHAR(50)
	DECLARE @ChildCount NUMERIC(18,0)
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @PUserCode)
	IF (@PtypeId NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@operId)))
			BEGIN
				SET @ErrMsg = '操作员不具备该商品权限'
				RETURN -1
			END		
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0 OR (@PFullName = '库存配件' AND @PUserCode = '0'))
	BEGIN
		SET @ErrMsg = '该商品为父节点，不能导入期初'
		RETURN -1	
	END
END

DECLARE @Qty  NUMERIC(24, 10) 
IF (@StrQty = '')
BEGIN
	SET @ErrMsg = '请输入委托代销数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
			SET @ErrMsg = '委托代销数量请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
		BEGIN
			SET @ErrMsg = '委托代销数量不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
		END
END

DECLARE @CostPrice  NUMERIC(24, 10) 
IF (@StrCostPrice = '')
BEGIN
	SET @ErrMsg = '请输入成本单价'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrCostPrice) <> 1)
		BEGIN
			SET @ErrMsg = '成本单价请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrCostPrice)) <> 0)
		BEGIN
			SET @ErrMsg = '成本单价不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @CostPrice = CONVERT( NUMERIC(24, 10) , @StrCostPrice)
		END
END

DECLARE @CostTotal  NUMERIC(24, 10) 
IF (@Qty = 0)
BEGIN
	SET @Qty = 0
	SET @CostPrice = 0
	SET @CostTotal = 0
END
ELSE
	SELECT @CostTotal = ROUND(@Qty*@CostPrice, 2)

DECLARE @Price  NUMERIC(24, 10) 
IF (@StrPrice = '')
BEGIN
	SET @ErrMsg = '请输入结算单价'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrPrice) <> 1)
		BEGIN
			SET @ErrMsg = '结算单价请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrPrice)) <> 0)
		BEGIN
			SET @ErrMsg = '结算单价不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Price = CONVERT( NUMERIC(24, 10) , @StrPrice)
		END
END

DECLARE @Total  NUMERIC(24, 10) 
IF (@Qty = 0)
BEGIN
	SET @Price = 0
	SET @Total = 0
END
ELSE
	SELECT @Total = ROUND(@Qty*@Price, 2)
----------------------------------------------------------------------------------------------

IF NOT EXISTS(SELECT Qty FROM dbo.IniCommissionStock WHERE btypeid = @btypeid AND ptypeid = @ptypeid AND type = 140 AND stypeid = @stypeid)	--判断是否已经存在一样的期初信息
BEGIN                             --不存在
	INSERT INTO
		IniCommissionStock(btypeid,ptypeid,ktypeid,etypeid,type,qty,CostTotal,Total,explain,stypeid) 
	VALUES(@btypeid,@ptypeid,'','',140,@qty,@CostTotal,@Total,@explain,@stypeid)
END
ELSE
BEGIN                             --存在
	DELETE FROM IniCommissionStock 
	WHERE btypeid = @btypeid AND ptypeid = @ptypeid AND type = 140 AND stypeid = @stypeid
	
	INSERT INTO
		IniCommissionStock(btypeid,ptypeid,ktypeid,etypeid,type,qty,CostTotal,Total,explain,stypeid) 
	VALUES(@btypeid,@ptypeid,'','',140,@qty,@CostTotal,@Total,@explain,@stypeid)
END

SET @ReturnID = @@ROWCOUNT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

/****** Object:  StoredProcedure [dbo].[gp_ImportWx_iniGoodsStocks]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	作	  者：廖晨羽
	日    期：2011-09-13
	描	  述：导入维修品库存期初
*/


CREATE         PROCEDURE [dbo].[gp_ImportWx_iniGoodsStocks]
(
	@KFullName   [varchar](200),		--仓库名称
	@PUserCode	 [varchar](200),		--商品编号
	@PFullName   [varchar](200),		--商品名称
	@StrQty  [varchar](18),			--期初数量
	@ReturnID  VARCHAR(100) output,
	@ErrMsg VARCHAR(200) output,
	@typeid  [varchar](max)
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

DECLARE	@ktypeid		varchar(1000)
IF (@KFullName = '' OR @KFullName = '全部仓库' OR NOT EXISTS(SELECT typeid FROM dbo.Stock WHERE fullname = @KFullName))
BEGIN
	SET @ErrMsg = '该仓库不存在'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PktypeId VARCHAR(50)
	DECLARE @KChildCount NUMERIC(18,0)
	SET @PktypeId = (SELECT TOP 1 typeid FROM dbo.Stock WHERE fullname = @KFullName)
	SELECT @KChildCount = COUNT(*) FROM dbo.Stock WHERE typeId LIKE @PktypeId + '%' AND typeId <> @PktypeId
	IF (@KChildCount = 0)
		BEGIN
			SET @ktypeid = @PktypeId		
			IF (@ktypeid NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@typeid)))
			BEGIN
				SET @ErrMsg = '操作员不具备该仓库权限'
				RETURN -1
			END				
		END
	ELSE
		BEGIN
			SET @ErrMsg = '该仓库是父类'
			RETURN -1
		END
END

--判断仓库关联的分支机构是否已开账
IF EXISTS (SELECT U.Value as valueinfo FROM SType_Config C,SType_UserConfig U,Stock K WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND U.STypeID = K.STypeID AND K.TypeId = @KtypeId) 
AND ((SELECT U.Value as valueinfo FROM SType_Config C,SType_UserConfig U,Stock K WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND U.STypeID = K.STypeID AND K.TypeId = @KtypeId) <> 0)
BEGIN
	SET @ErrMsg = '已开账'
	RETURN -1
END

IF(@PUserCode = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @PUserCode) OR @PUserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
ELSE IF (@PFullName = '' OR NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @PFullName) OR @PFullName='库存配件')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
ELSE IF(@PFullName <> (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @PUserCode))
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END
ELSE
BEGIN
	DECLARE @PtypeId  VARCHAR(50)
	DECLARE @ChildCount NUMERIC(18,0)
	SET @PtypeId = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @PUserCode)
	SELECT @ChildCount = COUNT(*) FROM dbo.ptype WHERE typeId LIKE @PtypeId + '%' AND typeId <> @PtypeId
	IF (@ChildCount > 0 OR (@PFullName = '库存配件' AND @PUserCode = '0'))
	BEGIN
		SET @ErrMsg = '该商品为父节点'
		RETURN -1	
	END
	IF (@PtypeId NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@typeId)))
		BEGIN
			SET @ErrMsg = '操作员不具备该商品权限'
			RETURN -1
		END	
END

DECLARE @Qty  NUMERIC(24, 10) 
IF (@StrQty = '')
BEGIN
	SET @ErrMsg = '请输入期初数量'
	RETURN -1
END
ELSE
BEGIN
	IF(ISNUMERIC(@StrQty) <> 1)
		BEGIN
			SET @ErrMsg = '期初数量请输入数字'
			RETURN -1
		END
	ELSE IF((SELECT CHARINDEX('-', @StrQty)) <> 0)
		BEGIN
			SET @ErrMsg = '期初数量不能为负数'
			RETURN -1
		END
	ELSE
		BEGIN
			SET @Qty = CONVERT( NUMERIC(24, 10) , @StrQty)
		END
END
----------------------------------------------------------------------------------------------

IF NOT EXISTS(SELECT Qty FROM dbo.Wx_iniGoodsStocks WHERE PtypeId = @PtypeId AND ktypeid = @ktypeid)	--判断是否已经存在一样的期初信息
BEGIN							  --不存在                    
	INSERT INTO
		Wx_iniGoodsStocks(PtypeId,KtypeId,Qty)
	VALUES(@ptypeid,@ktypeid,@qty)
END
ELSE
BEGIN                             --存在
	UPDATE  dbo.Wx_iniGoodsStocks 
	SET Qty = @qty
	WHERE PtypeId = @PtypeId AND ktypeid = @ktypeid
END

IF (@Qty = 0)
BEGIN
	DELETE FROM dbo.Wx_iniGoodsStocks 
	WHERE PtypeId = @PtypeId AND ktypeid = @ktypeid
END

SET @ReturnID = @@ROWCOUNT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理期初
	返回结果：
	作    者：冯波
	创建时间：2012-09-04
	修改历史：
	
	
*/
CREATE          PROCEDURE GP_Ini_UpGrade
--@encode$--
AS
BEGIN

	--期初的处理，待测试OK后再放到专门的存储过程中

	--库存期初
	DECLARE
			@AVERAGE					VARCHAR(50),
			@FIFO						VARCHAR(50),
			@LIFO						VARCHAR(50),
			@HAND						VARCHAR(50),
			@nCostingMethod				VARCHAR(50)
			
	SELECT
			@AVERAGE	= '0',		-- 移动加权平均算法
			@FIFO		= '1',		-- 先进先出
			@LIFO		= '2',		-- 后进先出
			@HAND		= '3'		-- 手工指定法
		
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output
	
	DECLARE
			@intIfUseGoodsNumber VARCHAR(100)
			
	SELECT @intIfUseGoodsNumber=0
			
	SELECT 	@intIfUseGoodsNumber=Value		
	FROM Userconfig
	WHERE ConfigName='ifusegoodsnumber'


	IF EXISTS(SELECT PTypeID FROM IniGoodsStocks)
	BEGIN
		IF @nCostingMethod=@HAND AND @intIfUseGoodsNumber=1
		BEGIN
			UPDATE IniGoodsStocks
			SET GoodsNumber=CASE ISNULL(GoodsNumber,'') WHEN '' THEN '默认批号' ELSE GoodsNumber END
		END
		ELSE
		BEGIN
			UPDATE IniGoodsStocks
			SET GoodsNumber=ISNULL(GoodsNumber,'')
		END
	
		IF NOT EXISTS(SELECT PTypeID FROM Ini_GOODSSTOCKS_QTY)
		BEGIN
			INSERT Ini_GOODSSTOCKS_QTY(PTypeID,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
			SELECT a.PtypeId,a.KtypeId,b.CargoID,0,0,a.GoodsNumber,a.ProduceDate,a.ValidDate,a.Qty,CASE ISNULL(c.Rate,0) WHEN 0 THEN 0 ELSE a.Qty*c.Rate END,CASE @nCostingMethod WHEN @HAND THEN a.Price ELSE 0 END
			FROM IniGoodsStocks a
			INNER JOIN 
			(
				SELECT KtypeID,MIN(CargoID) AS CargoID
				FROM CargoType 
				GROUP BY KtypeID
			) b
			ON a.KtypeId=b.KtypeID
			LEFT JOIN PType_Units_Ext c
			ON a.PtypeId=c.PtypeID AND c.RateType=1
		END
	END


	--代销期初
	IF EXISTS(SELECT PTypeID FROM IniCommissionStock)
	BEGIN
		IF NOT EXISTS(SELECT PTypeID FROM IniCommissionStock_Qty)
		BEGIN	
			INSERT IniCommissionStock_Qty(PTypeID,Type,Btypeid,Stypeid,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty)
			SELECT a.PtypeId,a.Type,a.Btypeid,a.Stypeid,0,0,'','','',a.Qty,CASE ISNULL(c.Rate,0) WHEN 0 THEN 0 ELSE a.Qty*c.Rate END
			FROM IniCommissionStock a
			LEFT JOIN PType_Units_Ext c
			ON a.PtypeId=c.PtypeID AND c.RateType=1
			
			UPDATE IniCommissionStock_Qty
			SET GoodsNumber='默认批号'
			WHERE ISNULL(GoodsNumber,'')='' AND @nCostingMethod=@HAND AND @intIfUseGoodsNumber=1
		END
	END



	--借欠期初
	IF EXISTS(SELECT PTypeID FROM IniGoodsLend)
	BEGIN
		UPDATE IniGoodsLend
		SET GoodsNumber=ISNULL(GoodsNumber,''),
		ItemID=ISNULL(ItemID,0),
		Iscombined=ISNULL(Iscombined,0),
		ProduceDate=ISNULL(ProduceDate,''),
		ValidDate=ISNULL(ValidDate,''),
		LendQty=CASE WHEN Qty<0 THEN -Qty ELSE 0 END,
		BorrowQty=CASE WHEN Qty>
		0 THEN Qty ELSE 0 END,
		NLendQty=ISNULL(NLendQty,0),
		NBorrowQty=ISNULL(NBorrowQty,0),
		Nqty=ISNULL(NQty,0)
		
		UPDATE IniGoodsLend
		SET GoodsNumber='默认批号'
		WHERE ISNULL(GoodsNumber,'')='' AND @nCostingMethod=@HAND AND @intIfUseGoodsNumber=1
	
		UPDATE IniGoodsLend
		SET ItemID=0,Iscombined=0,Nqty=CASE ISNULL(b.Rate,0) WHEN 0 THEN 0 ELSE IniGoodsLend.Qty*b.Rate END,
		NLendQty=CASE ISNULL(b.Rate,0) WHEN 0 THEN 0 ELSE IniGoodsLend.LendQty*b.Rate END,
		NBorrowQty=CASE ISNULL(b.Rate,0) WHEN 0 THEN 0 ELSE IniGoodsLend.BorrowQty*b.Rate END
		FROM 
		(
			SELECT a.PTypeID,ISNULL(b.Rate,0) AS Rate
			FROM IniGoodsLend a
			LEFT JOIN PType_Units_Ext b
			ON a.PtypeId=b.PtypeID
			WHERE a.PtypeId=b.PtypeID AND b.RateType=1
		) b
		WHERE IniGoodsLend.PtypeId=b.PtypeId
		
	END


	IF EXISTS(SELECT PTypeID FROM wx_IniGoodsStocks)
	BEGIN
		UPDATE wx_IniGoodsStocks
		SET GoodsNumber=ISNULL(GoodsNumber,''),
		ItemID=ISNULL(ItemID,0),
		Iscombined=ISNULL(Iscombined,0),
		ProduceDate=ISNULL(ProduceDate,''),
		ValidDate=ISNULL(ValidDate,'')
		
		UPDATE wx_IniGoodsStocks
		SET GoodsNumber='默认批号'
		WHERE ISNULL(GoodsNumber,'')='' AND @nCostingMethod=@HAND AND @intIfUseGoodsNumber=1
	
	
		UPDATE wx_IniGoodsStocks
		SET ItemID=0,Iscombined=0,Nqty=CASE ISNULL(b.Rate,0) WHEN 0 THEN 0 ELSE wx_IniGoodsStocks.Qty*b.Rate END
		FROM 
		(
			SELECT a.PTypeID,ISNULL(b.Rate,0) AS Rate
			FROM wx_IniGoodsStocks a
			LEFT JOIN PType_Units_Ext b
			ON a.PtypeId=b.PtypeID
			WHERE a.PtypeId=b.PtypeID AND b.RateType=1
		) b
		WHERE wx_IniGoodsStocks.PtypeId=b.PtypeId
	END		
	
	--处理数据错误的
	
	--处理代销库的货位
	UPDATE InOutstocktable
	SET CargoID=0
	WHERE KtypeId='10000' AND CargoID<>0
	
	--处理销售出库单成本价销售时的NTAXMONEY
	IF EXISTS(
		SELECT a.BillNumberId
		FROM BillIndex a
		INNER JOIN Ac_Currency b
		ON a.CID=b.CId
		WHERE a.BillType=11 AND b.BasisType='0'
	)
	BEGIN
		UPDATE SaleBill
		SET 
			NTaxMoney=CASE b.Rate WHEN 1 THEN TaxMoney ELSE ROUND(SaleBill.TaxTotal/b.Rate,2)-ROUND(SaleBill.SaleTotal/b.Rate,2) END		
		FROM BillIndex b
		WHERE b.CostSale=1 AND SaleBill.BillNumberID=b.BillNumberID
	END
	
	
	IF EXISTS(
		SELECT a.BillNumberId
		FROM BillIndex a
		INNER JOIN Ac_Currency b
		ON a.CID=b.CId
		WHERE a.BillType=11 AND b.BasisType='1'
	)
	BEGIN
		UPDATE SaleBill
		SET 
			NTaxMoney=CASE b.Rate WHEN 1 THEN TaxMoney ELSE ROUND(SaleBill.TaxTotal*b.Rate,2)-ROUND(SaleBill.SaleTotal*b.Rate,2) END
		FROM BillIndex b
		WHERE b.CostSale=1 AND SaleBill.BillNumberID=b.BillNumberID
	END
	
	

	--往来期初
	EXEC UpdateBtypeArApData
END
GO




IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_IniToArApTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_IniToArApTotal
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2012-05-29
-- Description: 将期初单据数据转到应收应付期初
-- 备注：2013-9-29 增加当@stypeid传入"%",处理全部分支机构数据。
-- =============================================
CREATE PROCEDURE Gp_IniToArApTotal
(
	@stypeid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

--如果分支机构已经开账，则直接返回
IF EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeID = @STypeId AND Value = '1' AND ConfigNo = '1')
	RETURN 0

DECLARE @ExpenseToAr INT=0
		
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'	
		
CREATE TABLE #billindexARAPTotal
(
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		APTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		YFTotal00  NUMERIC(24, 10) ,
		FCTotal00  NUMERIC(24, 10) ,
		GRIRTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10) ,
		nAPTotal00  NUMERIC(24, 10) ,
		nYSTotal00  NUMERIC(24, 10) ,
		nYFTotal00  NUMERIC(24, 10) ,
		NFCTotal00  NUMERIC(24, 10) ,
		NGRIRTotal00  NUMERIC(24, 10) 
)
CREATE NONCLUSTERED INDEX CIX_billindexARAPTotal_X ON #billindexARAPTotal(stypeid,btypeid,cid)

INSERT INTO #billindexARAPTotal
	( 
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			APTotal00 ,
			YSTotal00 ,
			YFTotal00 ,
			FCTotal00,
			GRIRTotal00,
			nARTotal00 ,
			nAPTotal00 ,
			nYSTotal00 ,
			nYFTotal00,
			NFCTotal00,
			NGRIRTotal00
	)
	SELECT	stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(APTotal00),
			SUM(YSTotal00),
			SUM(YFTotal00),
			SUM(FCTotal00),
			SUM(GRIRTotal00),
			SUM(nARTotal00),
			SUM(nAPTotal00),
			SUM(nYSTotal00),
			SUM(nYFTotal00),
			SUM(NFCTotal00),
			SUM(NGRIRTotal00)
	FROM
	(
		SELECT	stypeid ,
				btypeid ,
				cid ,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					ELSE 0 
				END AS artotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney -ISNULL(ChargeOffTotal,0)
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)) 
					ELSE 0 
				END AS aptotal00,
				CASE WHEN billtype =189 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS ystotal00,
				CASE WHEN billtype =190 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS yftotal00,
				0 AS FCTotal00,
				0 AS  GRIRTotal00,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS nartotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0) 
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS naptotal00,
				CASE WHEN billtype =189 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nystotal00,
				CASE WHEN billtype =190 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nyftotal00,
				0 AS NFCTotal00,
				0 AS  NGRIRTotal00
		FROM dbo.BillIndex
		WHERE	BillType IN(4,66,11,12,45,46,85,93,141,148,149,160,167,168,172,181,6,34,36,84,145,150,151,161,170,189,190,213,212,312)
				AND IsIni=1
				AND (Stypeid=@stypeid OR @stypeid='%')
		UNION ALL
		SELECT  b.stypeid ,
				a.btypeid ,
				b.cid ,
				CASE WHEN b.billtype = 116
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					ELSE 0
				END AS artotal00,
				CASE WHEN b.billtype = 128
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					 ELSE 0
				END AS aptotal00,
				0 AS ystotal00,
				0 AS yftotal00,
				0 AS FCTotal00,
				0 AS GRIRTotal00,
				CASE WHEN b.billtype = 116
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					ELSE 0
				END AS nartotal00,
				CASE WHEN b.billtype = 128
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					 ELSE 0
				END AS naptotal00,
				0 AS nystotal00,
				0 AS nyftotal00,
				0 AS NFcTotal00,
				0 AS NGRIRTotal00
		FROM	AdDebtBill a 
		INNER JOIN billindex b ON a.BillNumberId =b.BillNumberId
		WHERE	BillType IN(115,116,128,129)
				AND IsIni=1
				AND (B.Stypeid=@stypeid OR @stypeid='%')
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=402
				   THEN dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYFTotal00,
			   0 AS NYSTotal00,
			   CASE WHEN B.BillType=402
					THEN dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
				
		FROM SendBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=403
				   THEN -dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   CASE WHEN B.BillType=403
					THEN -dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
		FROM SendBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.Total
					ELSE dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.DiscountPrice)
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.NTotal
				    ELSE dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.NDiscountPrice )
				    END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.Total
					ELSE dbo.F_RoundTotal(-(A.Qty-A.InvoiceQty)*A.DiscountPrice )
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.NTotal
					ELSE dbo.F_RoundTotal(-(A.Qty-A.InvoiceQty)*A.NDiscountPrice )
					END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
		
		UNION ALL
		SELECT 
			  B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.BillType=405
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.BillType=405
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM ReceiptBillIndex B 
		WHERE  B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
		UNION ALL
		SELECT 
		B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.totalmoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS ARTotal00,
			  CASE 
				   WHEN B.ChargeOffType IN (3,4)
				   THEN B.totalmoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.NTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NARTotal00,
			  CASE 
				   WHEN B.ChargeOffType IN (3,4)
				   THEN B.NTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM dbo.BillIndex B 
		 WHERE B.BillType= 450 AND B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
	) total
	GROUP BY stypeid,btypeid,cid

DELETE FROM #billindexARAPTotal WHERE ISNULL(YSTotal00,0)=0 AND ISNULL(YFTotal00,0)=0 AND ISNULL(ARTotal00,0)=0 AND ISNULL(APTotal00,0)=0 
			AND ISNULL(nYSTotal00,0)=0 AND ISNULL(nYFTotal00,0)=0 AND ISNULL(nARTotal00,0)=0 AND ISNULL(nAPTotal00,0)=0 
			AND ISNULL(NGRIRTotal00,0)=0 AND ISNULL(GRIRTotal00,0)=0 AND ISNULL(FCTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0

DELETE FROM dbo.BType_ArApTotal WHERE (stypeid =@stypeid OR @stypeid='%')
INSERT INTO dbo.BType_ArApTotal
        ( BTypeID ,
          STypeID ,
          ARTotal ,
          APTotal ,
          YSTotal ,
          YFTotal ,
          ARTotal00 ,
          APTotal00 ,
          YSTotal00 ,
          YFTotal00 ,
          nARTotal ,
          nAPTotal ,
          nYSTotal ,
          nYFTotal ,
          nARTotal00 ,
          nAPTotal00 ,
          nYSTotal00 ,
          nYFTotal00 ,
          CID,
          GRIRTotal,
          FCTotal,
          GRIRTotal00,
          FCTotal00,
          NGRIRTotal,
          NFCTotal,
          NGRIRTotal00,
          NFCTotal00
        )
SELECT    BTypeID ,
          STypeID ,
          0 ,
          0 ,
          0 ,
          0 ,
          ARTotal00 ,
          APTotal00 ,
          YSTotal00 ,
          YFTotal00 ,
          0 ,
          0 ,
          0 ,
          0 ,
          nARTotal00 ,
          nAPTotal00 ,
          nYSTotal00 ,
          nYFTotal00 ,
          CID,
          0,
          0,
          GRIRTotal00,
          FCTotal00,
          0,
          0,
          NGRIRTotal00,
          NFCTotal00
FROM #billindexARAPTotal
IF @@ERROR<>0
	RAISERROR('录入应收应付期初失败！',16,1)

--写入atype_toatl
DECLARE	@AR_ID VARCHAR(50),		
		@AP_ID VARCHAR(50),
		@YS_ID VARCHAR(50),		
		@YF_ID VARCHAR(50),
		@APP_ID VARCHAR(50),
		@SEND_ID VARCHAR(50);
--将FullName换成UserCode,有些版本的FullName不一致会导致程序报错
SELECT @AR_ID=nid FROM dbo.Ac_Items WHERE UserCode='987'		
SELECT @AP_ID=nid FROM dbo.Ac_Items WHERE UserCode='2121'		
SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE UserCode='2131'		
SELECT @YF_ID=nid FROM dbo.Ac_Items WHERE UserCode='1151'
SELECT @APP_ID=NID FROM dbo.Ac_Items WHERE UserCode='2122'
SELECT @SEND_ID=NID FROM dbo.Ac_Items WHERE UserCode='1251'

DELETE FROM  AType_Total WHERE ATypeID IN (@AR_ID,@AP_ID,@YS_ID,@YF_ID,@APP_ID,@SEND_ID) AND	(stypeid =@stypeid OR @stypeid='%')
IF EXISTS(SELECT TOP 1 1 FROM BType_ARAPTotal WHERE	(stypeid =@stypeid OR @stypeid='%'))
BEGIN
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)	
	SELECT	@AR_ID,	
			STypeID,
			SUM(artotal00),
			SUM(nartotal00),
			CID
	FROM	BType_ARAPTotal
	WHERE		(stypeid =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING	SUM(artotal00)<>0
	
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)	
	SELECT	@AP_ID,	
			STypeID,
			SUM(aptotal00),
			SUM(naptotal00),
			CID
	FROM	BType_ARAPTotal
	WHERE		(stypeid =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING SUM(aptotal00)<>0
	
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)	
	SELECT	@YS_ID,	
			STypeID,
			SUM(YSTotal00),
			SUM(nYSTotal00),
			CID
	FROM	BType_ARAPTotal
	WHERE		(stypeid =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING	SUM(YSTotal00)<>0
	
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)	
	SELECT	@YF_ID,	
			STypeID,
			SUM(YFTotal00),
			SUM(nYFTotal00),
			CID
	FROM	BType_ARAPTotal
	WHERE		(stypeid =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING SUM(YFTotal00)<>0
	
	--暂估
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)
	SELECT @APP_ID,
			STypeID,
			SUM(GRIRTotal00),
			SUM(NGRIRTotal00),
			CID
	FROM BType_ArApTotal
	WHERE (STypeID =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING SUM(GRIRTotal00)<>0
	
	--发出
	INSERT INTO AType_Total
	(	
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)
	SELECT @SEND_ID,
			STypeID,
			SUM(FCTotal00),
			SUM(NFCTotal00),
			CID
	FROM BType_ArApTotal
	WHERE (STypeID=@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING SUM(FCTotal00)<>0
END 	


DROP TABLE #billindexARAPTotal
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_InnerARTotal_AddEdit]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_InnerARTotal_AddEdit]
GO



/*

功能说明：      新增或修改分支机构的内部应收

作    者：       冯波

创建日期：       2011-1-25

返回结果：       

*/  

CREATE PROCEDURE [GP_InnerARTotal_AddEdit]
(
	@nBillID					NUMERIC(10,0),			--单据ID
	@decTotal					 NUMERIC(24, 10) ,	
	@nID						 NUMERIC(24, 10) =0,		--明细ID 		
	@strErrMsg					VARCHAR(4000) OUT		--返回的出错信息
)
--@encode$--        
AS

SELECT @strErrMsg=''

DECLARE 
		@strKTypeID				VARCHAR(50),
		@strSTypeID				VARCHAR(50),			--公司ID
		@strSTypeID2			VARCHAR(50),
		@intBillType			INT

SELECT @strSTypeID=Stypeid,@intBillType=BillType
FROM BillIndex
WHERE BillNumberId=@nBillID

IF @intBillType=188
BEGIN
	SELECT @strKTypeID=a.Ktypeid
	FROM
	(
		SELECT TOP 1 KTypeID
		FROM STypeMoveBill
		WHERE BillNumberId=@nBillID
	) a
END
ELSE IF @intBillType=187
BEGIN
	SELECT @strKTypeID=a.Ktypeid
	FROM
	(
		SELECT TOP 1 Ktypeid2 AS KTypeID
		FROM STypeMoveBill
		WHERE BillNumberId=@nBillID
	) a
END
ELSE IF @intBillType=159
BEGIN
	SELECT @strSTypeID=STypeID 
	FROM AccountCredence
	WHERE BillNumberID=@nBillID
END

IF @intBillType IN (187,188)
BEGIN
	SELECT @strSTypeID2=STypeID
	FROM Stock
	WHERE typeId=@strKTypeID
END
ELSE IF @intBillType=159
BEGIN
	SELECT @strSTypeID2=ATypeID
	FROM AccountCredence
	WHERE BillNumberID=@nBillID AND ID=@nID
END

IF NOT EXISTS(SELECT STypeID FROM SType_InnerARTotal WHERE STypeID=@strSTypeID AND STypeID2=@strSTypeID2)
BEGIN
	INSERT INTO SType_InnerARTotal(STypeID,STypeID2,InnerARTotal)
	VALUES(@strSTypeID,@strSTypeID2,@decTotal)		
END
ELSE
BEGIN
	UPDATE SType_InnerARTotal
	SET InnerARTotal=ISNULL(InnerARTotal,0)+@decTotal
	WHERE STypeID=@strSTypeID AND STypeID2=@strSTypeID2
END




GO



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

/****** Object:  StoredProcedure [dbo].[Gp_InsertA]    Script Date: 05/23/2011 15:58:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

--费用合计-新增或复制新增
--修改者：黄飞佳  日期：2012-4-16


CREATE      PROCEDURE [dbo].[Gp_InsertA]
(
 @Parid   [varchar](50),
 @DbName         [varchar](30),
 @szFlag  [char](2),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @Name  [varchar](30),
 @Total00    NUMERIC(24, 10) ,
 @Comment  [varchar](256),
 @PyCode   varchar(200),
 @MagEType varchar(200)
 )
--@encode$--
AS
SET NOCOUNT ON
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from atype where typeid=@parid)

--判断停用不能分类
declare @deleted INT
select @deleted=deleted from atype where typeId=@Parid
if(@deleted=1)
begin
   RAISERROR('该会计科目【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
end
--系统会计科目不能分类
if exists(select * from atype where typeId=@Parid and sonnum=0 and sysrow=1)
begin
	--print '['+@FullName+']帐户金额不为零，不能分类'
	RAISERROR('该会计科目【%s】为系统会计科目，不能分类',16,1,@parFullName)return--return -8
end 
-- 判断当前金额
if exists(select *,typeid from [atype] where typeid=@parid and Total<>0)
begin
	--print '['+@FullName+']帐户金额不为零，不能分类'
	RAISERROR('该会计科目【%s】账户金额不为零，不能分类',16,1,@parFullName)return--return -8
end 
if exists(select *,typeid from [atype] where typeid=@parid and Total00<>0)
begin
	--print '['+@FullName+']帐户金额不为零，不能分类'
	RAISERROR('该会计科目【%s】账户金额不为零，不能分类',16,1,@parFullName)return--return -8
end 

-- 判断固定资产期初是否有数据
if exists(select *,ATypeID   from AType_Total where ATypeID=@parid and Total00<>0)
begin
	--print '['+@FullName+']帐户已经经营过，不能分类'
	RAISERROR('该会计科目【%s】已有期初数据，不能分类',16,1,@parFullName)return--return -6
end 
-- 判断单据中是否录入数据
IF EXISTS(SELECT * FROM PreBill WHERE AtypeId=@parid)
BEGIN
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
END
if exists(select * from billindex where AtypeID=@parid)
BEGIN
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6		
END
if exists(select * from listtable where AtypeID=@parid)
BEGIN
    RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6		
END
if exists(select atypeid from MoneyBill where AtypeID=@parid)
BEGIN
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6				
END
if exists(select atypeid from MoveMoneyBill where AtypeID=@parid)
BEGIN
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6					
END
--在多账户中使用
if exists(select atypeid from BillMulAccount where AtypeID=@parid)
BEGIN
    --print '25555'
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6					
END
--在其他出入库业务类别中使用

if exists(select atypeid from OtherInOutType where AtypeID=@parid)
BEGIN
    --print '25555'
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6					
END
--pos管理中使用
if exists(select bankatypeid from PosRetailCash where bankatypeid=@parid)
BEGIN
    --print '25555'
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6					
END
if exists(select atypeid from AccountCredence where AtypeID=@parid AND TypeATypeID NOT IN('0000200001','0000100005','0000200006','0000100009','0000100010'))
BEGIN
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6				
END
if exists(select atypeid from paybill where AtypeID=@parid)
BEGIN
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6					
END
if exists(select atypeid from gatheringbill where AtypeID=@parid)
BEGIN		
    RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6		
END

if exists(select *,typeid from [atype] where typeid=@parid AND ifCanClass=0)
begin 
 --   if((select isnull(Total,0) from AType_Total  where ATypeID=@parid)>0)
 --       begin
 --           RAISERROR('该会计科目【%s】金额不为零，不能分类',16,1,@parFullName)return
 --       end
 --   if((select isnull(Total00,0) from AType_Total  where ATypeID=@parid)>0)
 --       begin
 --           RAISERROR('该会计科目【%s】金额不为零，不能分类',16,1,@parFullName)return
 --       end 
	----print '['+@FullName+']帐户金额为系统科目，不能分类'
	RAISERROR('该会计科目【%s】为系统科目，不能分类',16,1,@parFullName)return--return -88
end 

-- 判断经营
if exists(select aTypeID from listtable where aTypeID=@parid and Total<>0)
begin
	--print '['+@FullName+']帐户已经经营过，不能分类'
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
end 

-- 判断会计凭证
if exists(select aTypeID from AccountCredence where aTypeID=@parid AND TypeATypeID NOT IN('0000200001','0000100005','0000200006','0000100009','0000100010'))
begin
	RAISERROR('该会计科目【%s】已关联会计凭证，不能分类',16,1,@parFullName)return--return -6
end 

-- 判断经营
if exists(select aTypeID from listtable where aTypeID=@parid and Total<>0)
begin
	--print '['+@FullName+']帐户已经经营过，不能分类'
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
end 

--判断科目是否被会计凭证使用
--IF EXISTS(SELECT * FROM AccountCredence WHERE ATypeID=@Parid)
--	BEGIN 
--		RAISERROR('该会计科目【%s】已经被会计凭证单据使用过，禁止分类',16,1)
--		RETURN
--	END
--判断银行账户是否被现金银行期初添加期初金额，若有则禁止银行账户分类
IF LEFT(@Parid,10)='0000100004'
	BEGIN
		IF EXISTS(SELECT * FROM AType_Total WHERE ATypeID=@Parid and Total00<>0)
		BEGIN
			RAISERROR('该会计科目【%s】已经有期初数据，禁止分类',16,1,@parFullName)
			RETURN
		END	
	END
	
-- 判断经营
if exists(select aTypeID from billindex where aTypeID=@parid)
begin
	--print '['+@FullName+']帐户已经经营过，不能分类'
	RAISERROR('该会计科目【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
end 

-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
begin
	RAISERROR('该会计科目的分类不能超过10层',16,1)return
end--return -1
if @nReturntype=-2 
begin 
 RAISERROR('无法添加基本信息',16,1)return--return -2
end
-- 判断重复的ID,UserCode科目
if exists(select * from [atype] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted<>1) or (fullname=@fullname and deleted<>1))
begin
	--print '['+@usercode+']科目已存在'
	RAISERROR('该【%s】已经存在，会计科目编号或名称不能相同',16,1,@FullName)return--return -3
end

if exists(select * from [atype] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted<>1) or (fullname=@usercode and deleted<>1))
begin
	--print '['+@usercode+']科目已存在'
	RAISERROR('会计科目名称或编号不能与已有的名称或编号重复',16,1)return--return -10
end

-- 判断重复的ID,UserCode科目
if exists(select * from [atype] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted=1) or (fullname=@fullname and deleted=1))
begin
	--print '['+@usercode+']科目已存在'
	RAISERROR('该【%s】的编号或名称已被已停用的会计科目使用，请更换或删除该停用的编号或名称',16,1,@FullName) return--return -31
end

if exists(select * from [atype] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted=1) or (fullname=@usercode and deleted=1))
begin
	--print '['+@usercode+']科目已存在'
	RAISERROR('会计科目名称或编号不能与已停用的名称或编号重复',16,1) return--return -101
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode


-- 加入权限限制

DECLARE @MATYPE  varchar(50)
DECLARE @mftypeid  varchar(50)
DECLARE @mitypeid  varchar(50)
DECLARE @mctypeid  varchar(50)


SELECT @MATYPE 	 = MangerATypeID
	 , @mftypeid =MangerExpense
	 , @mitypeid = MangerIncome
     , @mctypeid = MangerCpaital
FROM loginuser
WHERE [EtypeID] = @MagEType

-- **********************************************************************
-- =================== 看看操作员是否有添加该子结点的权限===================

-- 特殊处理权限为全部的情况 == begin

IF @MATYPE ='00000' OR @MATYPE='0000' --银行帐户
	SET @MATYPE ='0000100004'
IF @mftypeid='0000'  -- 费用权限
	SET @mftypeid='0000400003'
IF @mitypeid='0000'  -- 收入权限
	SET @mitypeid='0000300003'
IF @mctypeid ='0000' -- 『固定资产合计』
	SET @mctypeid='0000100002'

IF LEFT(@EtypeId_1,10)='0000100004' -- 银行下面添加子科目
BEGIN
	IF @MATYPE <>'0000100004' 
	BEGIN
		IF LEN(@MATYPE)>=lEN(@EtypeId_1)
				RAISERROR('您的权限不能够在会计科目【%s】下添加节点',16,1,@parFullName)--RETURN -961
	END
END
IF LEFT(@EtypeId_1,10)='0000400003' -- 费用权限下面添加子科目
BEGIN
	IF @MATYPE <>'0000400003' 
	BEGIN
		IF LEN(@mftypeid)>=lEN(@EtypeId_1)
			RAISERROR('您的权限不能够在会计科目【%s】下添加节点',16,1,@parFullName)--RETURN -961
	END
END

IF LEFT(@EtypeId_1,10)='0000300003' -- 收入权限下面添加子科目
BEGIN
	IF @MATYPE <>'0000300003' 
	BEGIN
		IF LEN(@mitypeid)>=lEN(@EtypeId_1)
			RAISERROR('您的权限不能够在会计科目【%s】下添加节点',16,1,@parFullName)--RETURN -961
	END
END

IF LEFT(@EtypeId_1,10)='0000100002' -- 『固定资产合计』权限下面添加子科目
BEGIN
	IF @MATYPE <>'0000100002' 
	BEGIN
		IF LEN(@mctypeid)>=lEN(@EtypeId_1)
			RAISERROR('您的权限不能够在会计科目【%s】下添加节点',16,1,@parFullName)--RETURN -961
	END
END
-- ***********************************************************************************
begin tran insertproc
select @leveal=leveal from atype where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO [atype] 
--INSERT INTO [Ac_Expenses]
  ( --[typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [Name],
  [UserCode],
  [total00], 
  [sysflag],
  [Comment],
  [PyCode]
) 
 
VALUES 
 ( --@EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @Name,
  @UserCode,
  dbo.F_RoundTotal(@Total00),
  @szFlag,
  @Comment,
  @returnPym
)
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
END ELSE
begin
 update [atype]
 set sonnum=@nSonnum+1,soncount=@nSoncount+1
 where typeid=@Parid
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AType
UPDATE AType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

commit tran insertproc




GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertAc_AssetsCards]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[Gp_InsertAc_AssetsCards]
GO


/****** Object:  StoredPROCEDURE [dbo].[Gp_InsertAc_AssetsCards]    Script Date: 05/17/2011 20:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

----========================
----修改者：黄清
----日期：2013-05-20
----描述：固定资产卡片新增
----========================
CREATE    PROCEDURE [dbo].[Gp_InsertAc_AssetsCards]
(
	@cardid			[VARCHAR](50),
	@UserCode		[VARCHAR](200),
	@FullName		[VARCHAR](200),
	@stypeid		[VARCHAR](50),
	@dtypeid		[VARCHAR](50),
	@size			[VARCHAR](50),
	@categoryid		[VARCHAR](50),
	@locationid		[VARCHAR](50),
	@conditionid	[VARCHAR](50),
	@inaccountdate	DATETIME,
	@businesstypeid	[VARCHAR](50),
	@total			 NUMERIC(24, 10) ,
	@cid			[VARCHAR](50),
	@rate			 NUMERIC(24, 10) ,
	@ftotal			 NUMERIC(24, 10) ,
	@deptotal		 NUMERIC(24, 10) ,
	@devalueready	 NUMERIC(24, 10) ,
	@netvalue		 NUMERIC(24, 10) ,
	@netsalvage		 NUMERIC(24, 10) ,
	@netsalvagerate	 NUMERIC(24, 10) ,
	@depreciationmean	[VARCHAR](50),
	@duryear			INT,
	@durmonth			INT,
	@depreciationmonth	INT,
	@assertatypeid	[VARCHAR](50),
	@depatypeid		[VARCHAR](50),
	@disatypeid		[VARCHAR](50),
	@devalueatypeid	[VARCHAR](50),
	@etypeid		[VARCHAR](50),
	@Comment  [VARCHAR](256),
	@units		[VARCHAR](200),
	@ini		VARCHAR(5),
	@barcode	VARCHAR(256),
	@Qty         NUMERIC(24, 10),
	@expectwork	 NUMERIC(24, 10) ,
	@finishwork  NUMERIC(24, 10) ,
	@workunit	VARCHAR(256)
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@stypeid AND (ISNULL(SFYear,0)=0 OR ISNULL(SFPeriod,0)=0))
	BEGIN
		RAISERROR('请先设置当前分支机构的启用期间，再执行当前操作！',16,1) RETURN
	END
IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND deleted=1)
	BEGIN
		RAISERROR('该分支机构已被停用，不能进行操作！',16,1) RETURN
	END	
IF EXISTS(SELECT 1 FROM AC_AssetsCards WHERE usercode=@usercode)
BEGIN
	RAISERROR('该【%s】的编号已经使用，请更换编号',16,1,@usercode)return--return -31
END
IF @ini='0' AND EXISTS (SELECT 1 FROM Ac_AssetBusinessType WHERE id=@businesstypeid AND (AuditType=1 OR AuditType=2 OR AuditType=3) AND @deptotal<>0)
BEGIN
	RAISERROR('正常卡片，增加方式为【购入(原值含税)】、【购入(原值不含税)】、【自建工程】的资产卡片累计折旧值应该为0',16,1)return--return -31
END

--IF EXISTS(SELECT 1 FROM AC_AssetsCards WHERE fullname=@fullname)
--BEGIN
--	RAISERROR('该【%s】的名称已经使用，请更换名称',16,1,@FullName)return--return -31
--END

DECLARE @AssetsState INT
DECLARE @IsA8 INT	
IF EXISTS(SELECT *FROM sysdata WHERE SubName='ProInfo' AND SubValue=2)
	SET @IsA8=1
ELSE
	SET @IsA8=0
	
--获取开账期间

--获取开账期间
DECLARE 
	@SFyear			 INT,	--分支机构启用年度
	@SFPeriod		 INT,	--分支机构启用期间
	@Fyear			 INT,	--分支机构当前年度
	@FPeriod		 INT,	--分支机构当前期间		
	@VerifyID VARCHAR(50)	--分支机构独立分支ID
		
SELECT @VerifyID=VerifyID FROM SType WHERE TypeId =@stypeid

SELECT	
	@SFyear=SFYear,
	@SFPeriod=SFPeriod,
	@Fyear=FYear,
	@FPeriod=FPeriod
FROM dbo.Ac_AccountsPeroid_Stype 
WHERE Stypeid=@VerifyID

IF @barcode IS NOT NULL AND @barcode<>'' AND EXISTS (SELECT *FROM AC_AssetsCards WHERE BarCode=@barcode)
BEGIN
	RAISERROR('固定资产条码【%s】已存在，请更换条码',16,1,@barcode)RETURN
END


---初始数据录入
IF @ini='1'
BEGIN
	SET @AssetsState=1
	
	IF EXISTS (SELECT 1 FROM Stype WHERE TypeId=@VerifyID AND IfAssetsIni=1) AND @IsA8=1
	BEGIN
		RAISERROR('所选分支机构已初始化，请重新选择',16,1,@usercode)return--return -31
	END
	IF EXISTS (SELECT 1 FROM Stype WHERE TypeId=@VerifyID AND IfAssetsIni=1) AND @IsA8=0
	BEGIN
		RAISERROR('初始化已完成，不能录入初始数据，请确认',16,1,@usercode)return--return -31
	END
	
	--初始数据录入，未开账，入账时间<起始会计期间开始日期
	IF EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@VerifyID AND IsUse=0) AND EXISTS(SELECT 1 FROM Ac_Period WHERE FPeriod=@SFPeriod AND FYear=@SFyear AND IsCurrent=1 AND FBegin<=@inaccountdate)
	BEGIN
		RAISERROR('初始数据录入，未开账时,入账日期必须小于系统起始会计期间日期,请确认',16,1,@usercode)return--return w-31
	END
	
	--初始数据录入，已开账，入账时间<当前会计期间开始日期
	IF EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@VerifyID AND IsUse=1) AND EXISTS(SELECT 1 FROM Ac_Period WHERE FPeriod=@FPeriod AND FYear=@Fyear AND IsCurrent=1 AND FBegin<=@inaccountdate)
	BEGIN
		RAISERROR('初始数据录入，已开账，入账时间必须小于当前会计期间开始日期,请确认',16,1,@usercode)return--return -31
	END
END

--正常卡片录入
IF @ini='0'
BEGIN
	SET @AssetsState=2
	
	IF EXISTS(SELECT 1 FROM Stype WHERE TypeId=@VerifyID AND IfAssetsIni=0) AND @IsA8=1
	BEGIN
		RAISERROR('所选分支机构未初始化，请重新选择',16,1,@usercode)return--return -31
	END
	
	IF NOT EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@VerifyID AND IsUse=1) AND @IsA8=1
	BEGIN
		RAISERROR('所选分支机构已初始化但未开账，请重新选择',16,1,@usercode)return--return -31
	END
	
	IF( NOT EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@VerifyID AND IsUse=1) OR EXISTS(SELECT 1 FROM Stype WHERE TypeId=@VerifyID AND IfAssetsIni=0))  AND @IsA8=1
	BEGIN
		RAISERROR('未完成初始化或未开账，不能录入卡片数据，请确认',16,1,@usercode)return--return -31
	END
	
	IF EXISTS(SELECT 1 FROM Ac_Period WHERE FPeriod=@FPeriod AND IsCurrent=1 AND FYear=@Fyear AND  FBegin>@inaccountdate)
	BEGIN
		RAISERROR('正常卡片录入，入账时间必须大于当前会计期间开始日期,请确认',16,1,@usercode)return--return -31
	END
END

--DECLARE @AudtiType VARCHAR(50)
--SELECT @AudtiType=AuditType FROM Ac_AssetBusinessType WHERE Id=@businesstypeid
--IF (@AudtiType=1 OR @AudtiType=1 OR @AudtiType=2) AND @deptotal<>0
--BEGIN
--	RAISERROR('增加方式为【购入(原值含税)】、【购入(原值不含税)】、【自建工程】的资产卡片累计折旧值应该为0',16,1)return--return -31
--END


--非工作量法，工作量相关字段统一处理为null
IF @depreciationmean<>'5'
BEGIN
	SET @expectwork=NULL
	SET @finishwork=NULL
	SET @workunit=NULL
END


INSERT INTO AC_AssetsCards
(
	UserCode,
	FullName,
	stypeid,
	dtypeid,
	size,
	categoryid,
	locationid,
	conditionid,
	inaccountdate,
	businesstypeid,
	total,
	cid,
	rate,
	F_Total,
	deptotal,
	devalueready,
	netvalue,
	netsalvage,
	netsalvagerate,
	depreciationmean,
	duryear,
	durmonth,
	depreciationmonth,
	assertatypeid,
	depatypeid,
	disatypeid,
	devalueatypeid,
	Comment,
	AssetsState,
	OperationDate,
	ETypeId,
	Units,
	barcode,
	Qty,
	ExpectWork,
	FinishWork,
	WorkUnit
)
VALUES
(
	@UserCode,
	@FullName,
	@stypeid,
	@dtypeid,
	@size,
	@categoryid,
	@locationid,
	@conditionid,
	@inaccountdate,
	@businesstypeid,
	dbo.F_RoundTotal(@total),
	@cid,
	dbo.F_RoundExchangeRate(@rate),
	dbo.F_RoundTotal(@ftotal),
	dbo.F_RoundTotal(@deptotal),
	@devalueready,
	dbo.F_RoundTotal(@netvalue),
	dbo.F_RoundTotal(@netsalvage),
	dbo.F_RoundPercentage(@netsalvagerate),
	@depreciationmean,
	@duryear,
	@durmonth,
	@depreciationmonth,
	@assertatypeid,
	@depatypeid,
	@disatypeid,
	@devalueatypeid,
	@Comment,
	@AssetsState,
	GETDATE(),
	@etypeid,
	@units,
	@barcode,
	@Qty,
	@expectwork,
	@finishwork,
	@workunit
)

DECLARE @CARDIDS	INT
SET @CARDIDS=SCOPE_IDENTITY();

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AC_AssetsCards
UPDATE AC_AssetsCards SET XiWaMaxNumber = @XiWaMaxNumber WHERE id = @CARDIDS

IF @CARDID IS NULL 
BEGIN
 RETURN -1
END
ELSE
BEGIN
	RETURN @CARDIDS
END


GO




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertAc_Auditing_Template_DetailDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertAc_Auditing_Template_DetailDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：唐韬
	时间：2014-06-16 11:43:02.953
	描述：凭证明细之辅助核算明细保存存存储过程dt版
*/
CREATE PROCEDURE GP_InsertAc_Auditing_Template_DetailDT
(
	@tb TbType_Ac_Auditing_Template_Detail_Assist_CheckItems READONLY
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON


 INSERT INTO dbo.Ac_Auditing_Template_Detail_Assist_CheckItems
        ( AtdId ,
          Atid ,
          AscIds ,
          AscIdsDetailId                    
        )
        SELECT  AtdId ,--模版明细ID
                ATID ,--模版主表ID
                AscIds ,--辅助核算主表ID,
                AscIdsDetailId   --辅助核算明细表ID	
        FROM    @tb
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertAc_CashMoney]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_InsertAc_CashMoney]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROC [dbo].[Gp_InsertAc_CashMoney]
(
	@Parid			[varchar](50),
	@DbName         [varchar](30),
	@UserCode		[varchar](100),
	@FullName		[varchar](100)
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS (SELECT *FROM Ac_Account WHERE MainItems=@Parid OR AdditionItems=@Parid)
	BEGIN
		RAISERROR('现金流量项目已被科目使用，不允许分类',16,1)return--return -1
	END

IF EXISTS (SELECT *FROM Ac_Voucher_Bill_CashMoneyItems WHERE MATypeId=@Parid OR DATypeId=@Parid)
	BEGIN
		RAISERROR('现金流量项目已被会计凭证使用，不允许分类',16,1)return--return -1
	END
	
declare @nReturntype int,@Ac_CashMoneyId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

-- 获得新的ID号
EXEC @nReturntype=Gp_createId @ParId,@dbname,@Ac_CashMoneyId_1 out,@nSonnum out,@nSoncount OUT
IF @nReturntype=-1
	BEGIN
		RAISERROR('现金流量项目的分类不能超过10层',16,1)return--return -1
	END
IF @nReturntype=-2
	BEGIN
		RAISERROR('无法添加基本信息',16,1)return--return -2
	END
-- 判断重复的ID,UserCode
DECLARE @Name VARCHAR(200)=''
SELECT @Name=FullName FROM [Ac_CashMoneyItems] WHERE typeId=@Ac_CashMoneyId_1 or usercode=@usercode
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1)
		RETURN
	END
	
BEGIN TRAN insertproc
SELECT @leveal=leveal FROM Ac_CashMoneyItems WHERE typeid=@Parid
SELECT @leveal=@leveal+1
INSERT INTO [Ac_CashMoneyItems] 
( 
	[typeId],
	[Parid],
	[leveal],
	[sonnum],
	[soncount],
	[UserCode],
	[FullName],
	[PyCode],
	[sysrow]
)  
VALUES 
( 
	@Ac_CashMoneyId_1,
	@Parid,
	@leveal,
	0,
	0,
	@UserCode,
	@FullName,
	'',
	0	
)
IF @@rowcount=0 
	BEGIN
		 ROLLBACK TRAN insertproc 
		 return -1
	END
ELSE 
	BEGIN
		UPDATE [Ac_CashMoneyItems]
		SET 
			sonnum=@nSonnum+1,
			soncount=@nSoncount+1
		WHERE typeid=@Parid
	END

COMMIT TRAN insertproc


























GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertAc_SubsidiaryEquipment]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[Gp_InsertAc_SubsidiaryEquipment]
GO


/****** Object:  StoredPROCEDURE [dbo].[Gp_InsertAc_AssetsCards]    Script Date: 05/17/2011 20:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

----========================
----修改者：黄清
----日期：2013-05-20
----描述：固定资产卡片新增-附属设备
----========================
CREATE    PROCEDURE [dbo].[Gp_InsertAc_SubsidiaryEquipment]
(
	@cardid			VARCHAR(50),
	@FullName		VARCHAR(200),
	@size			VARCHAR(50),
	@locationid		VARCHAR(50),
	@qty			INT,
	@unitsid		VARCHAR(50),
	@value			 NUMERIC(24, 10) ,
	@usedate		VARCHAR(50),
	@Comment		VARCHAR(200)
)
--@encode$--
AS
SET NOCOUNT ON

--IF EXISTS(SELECT 1 FROM AC_AssetsCards WHERE usercode=@usercode)
--BEGIN
--	RAISERROR('该【%s】的编号已经使用，请更换编号',16,1,@usercode)return--return -31
--END


--IF EXISTS(SELECT 1 FROM AC_AssetsCards WHERE fullname=@fullname)
--BEGIN
--	RAISERROR('该【%s】的名称已经使用，请更换名称',16,1,@FullName)return--return -31
--END



INSERT INTO Ac_SubsidiaryEquipment
(
	CardId,
	FullName,
	locationid,
	size,
	Qty,
	Units,
	Value,
	UseDate,
	Comment  

)
VALUES
(
	@cardid,
	@FullName,
	@locationid,
	@size,
	dbo.F_RoundQty(@qty),
	@unitsid,
	@value,
	@usedate,
	@Comment  
)
IF @@rowcount=0 
BEGIN
 RETURN -1
END
ELSE
BEGIN
	RETURN SCOPE_IDENTITY();
END
----修改XiWa的XiWaMaxNumber
--DECLARE @XiWaMaxNumber numeric(18,0)
--SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM PType
--UPDATE PType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE     PROCEDURE GP_InsertAccountCredence (
	@BillNumberID		int,
	@TypeAtypeID		varchar(50),
	@ATypeID			varchar(50),
	@J_Total			 NUMERIC(24, 10) ,
	@D_Total			 NUMERIC(24, 10) ,
	@Comment			varchar(255),
	@STypeID			varchar(50)='',
    @ETypeID			varchar(50)='',
    @DTypeID			varchar(50)='',
	@BrandarTypeId		VARCHAR(50)='' --品牌应收
)
--@encode$--
AS
SET NOCOUNT ON
insert into [AccountCredence]
           ([billnumberid],
            [TypeATypeID],
			[ATypeID],
            [J_Total],
			[D_Total],
            [comment],
            STypeID,
            ETypeID,
            DTypeID,
            BrandarTypeId)
values  (	@billnumberid,
			@TypeAtypeID,
			@ATypeID,
			dbo.F_RoundTotal(@J_Total),
			dbo.F_RoundTotal(@D_Total),
			@comment,
			@STypeID,
			@ETypeID,
			@DTypeID,
			@BrandarTypeId)
			
if @@rowcount=0 return 0 else return 1




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[GP_InsertAccountCredenceDT]') AND OBJECTPROPERTY(ID, N'ISPROCEDURE') = 1)
DROP PROCEDURE [DBO].GP_InsertAccountCredenceDT
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-06-13 10:00:00
	描述：会计凭证表数据插入dt版
*/
CREATE PROC GP_InsertAccountCredenceDT
(
	@billNumberId INT
	,@stypeId VARCHAR(50)	
	,@tb TbType_AccountCredence READONLY
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO [AccountCredence]([billnumberid],[TypeATypeID],[ATypeID],[J_Total],[D_Total],[comment],STypeID,NJ_Total,ND_Total,Cid,Rate,BrandarTypeId, ETypeID,
		   DTypeID)
	SELECT @billNumberId,
		   [TypeATypeID],
		   [ATypeID],
		   dbo.F_RoundTotal([J_Total]),
		   dbo.F_RoundTotal([D_Total]),
		   [comment],
		   @stypeId,
		   dbo.F_RoundTotal(NJ_Total),
		   dbo.F_RoundTotal(ND_Total),
		   Cid,
		   dbo.F_RoundExchangeRate(Rate),
		   BrandarTypeId, 
		   ETypeID,
		   DTypeID
	FROM @tb;
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE   PROCEDURE [Gp_InsertAdDebtBill]
(
 @BillNumberId  [numeric](10,0),
 @BtypeId  [varchar](50),
 @Total    NUMERIC(24, 10) ,
 @Comment  [varchar](256),
 @STypeID  [varchar](50)=''
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[AdDebtBill] 
  ( [BillNumberId],
  [Comment],
  [BtypeId],
  [total],
  [STypeID]) 
 
VALUES 
 ( @BillNumberId,
  @Comment,
  @BtypeId,
  dbo.F_RoundTotal(@total),
  @STypeID)
if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：廖晨羽
描述：写入明细表(表值)
*/
CREATE              PROCEDURE [Gp_InsertAdDebtBillDT]
(
	@details TBType_AdDebt READONLY
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO [dbo].[AdDebtBill] 
  ( 
		[BillNumberId],
		[Comment],
		[BtypeId],
		[total],
		[STypeID],
		--9.0新字段
		ntotal,
		NCompleteTotal,
		CompleteTotal,
		ShowOrder,
		AlertDay,
		[BrandarTypeId]
)  
SELECT	[BillNumberId],
		[Comment],
		[BtypeId],
		dbo.F_RoundTotal([total]),
		[STypeID],
		--9.0新字段
		dbo.F_RoundTotal(ntotal), 
		dbo.F_RoundTotal(NCompleteTotal),
		dbo.F_RoundTotal(CompleteTotal),
		ShowOrder,
		AlertDay,
		ISNULL(brandartypeid,'')
FROM	@details


if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	修改作者:谢吉康
	修改日期:2004-5-10
	修改描述:修改了表结构,增加了字段ChangeAllStock
*/
CREATE        PROCEDURE [Gp_InsertAdPriceBill]
(
	@BillNumberId  	[numeric](10,0),
	@PtypeId  		[varchar](50),
	@Qty   			 NUMERIC(24, 10) ,
	@Price   		 NUMERIC(24, 10) ,
	@Total   		 NUMERIC(24, 10) ,
	@Comment  		[varchar](256),
	@intisUnit2 	[int],
	@ChangeAllStock [int],    			--是否修改所有商品的成本
	@InputCostPrice	 NUMERIC(24, 10)  = 0,	--成本单价
	@GoodsNumber	varchar(100) = '',	-- 批号
	@ProduceDate	varchar(50) = '',	-- 生产日期
	@ValidDate		varchar(50) = '',	-- 效期至
	@GoodsBTypeID	varchar(50) = '',	-- 供货商ID值
	@GoodsCostPrice	 NUMERIC(24, 10)  = 0,	-- 出库批次成本单价
	@HandZeroCost	int = 0,				-- 手工指定成本单价
	@STypeID		varchar(50)='',
	@BeforePrice	VARCHAR(MAX),		--调价前单价
	@BeforeTotal	VARCHAR(MAX),		--调价前金额
	@AdRate			VARCHAR(MAX)		--调价比率
)
--@encode$--
AS 
SET NOCOUNT ON
IF @BeforePrice = ''
	SET @BeforePrice = NULL
	
IF @BeforeTotal = ''
	SET @BeforeTotal = NULL
	
INSERT INTO [dbo].[AdPriceBill] 
	(
		[BillNumberId],
		[Comment],
		[PtypeId],
		[Qty],
		[Price],
		[total],
		[isunit2],
		[ChangeAllStock],
		[InputCostPrice],
		[GoodsNumber],
		[ProduceDate],
		[ValidDate],
		[GoodsBTypeID],
		[GoodsCostPrice],
		[HandZeroCost],
		STypeID,
		[BeforePrice],
		[BeforeTotal],
		[Rate]
	)  
VALUES 
	(
		@BillNumberId,
		@Comment,
		@PtypeId,
		dbo.F_RoundQty(@Qty),
		dbo.F_RoundPrice(@Price),
		dbo.F_RoundTotal(@total),
		@intisUnit2,
		@ChangeAllStock,
		@InputCostPrice,
		@GoodsNumber,
		@ProduceDate,
		@ValidDate,
		@GoodsBTypeID,
		dbo.F_RoundPrice(@GoodsCostPrice),
		@HandZeroCost,
		@STypeID,
		dbo.F_RoundPrice(@BeforePrice),
		dbo.F_RoundTotal(@BeforeTotal),
		@AdRate
	)
if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[GP_InsertAdPriceBillDT]') AND OBJECTPROPERTY(ID, N'IsProcedure') = 1)
	DROP PROCEDURE [DBO].GP_InsertAdPriceBillDT
GO
/*
	作者：周华
	时间：2012-05-24
	描述：成本调价单 明细写入的dt版
*/
CREATE PROCEDURE GP_InsertAdPriceBillDT
(
	@BillNumberId INT
	,@STypeId VARCHAR(50)
	,@tb TbType_AdPrice READONLY
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON
	INSERT INTO [AdPriceBill](
		[BillNumberId],
		[Comment],
		[PtypeId],
		[Qty],
		[Price],
		[total],
		[isunit2],
		[ChangeAllStock],
		[InputCostPrice],
		[GoodsNumber],
		[ProduceDate],
		[ValidDate],
		[GoodsBTypeID],
		[GoodsCostPrice],
		[HandZeroCost],
		STypeID,
		[BeforePrice],
		[BeforeTotal],
		[Rate]
		
		,NQty
		,UnitRate
		,ItemID
		,IsCombined
		,CargoId
		,ktypeid
		,Serial
		,NTotal
		,NPrice
		,frombillid
		,ShowOrder
		,ChangeTotal
		,[Type]
	) SELECT 
		@BillNumberId,
		A.Comment,
		A.PtypeId,
		dbo.F_RoundQty(A.Qty),
		dbo.F_RoundPrice(A.Price),
		dbo.F_RoundTotal(A.total),
		A.intisUnit2,
		A.ChangeAllStock,
		A.InputCostPrice,
		A.GoodsNumber,
		A.ProduceDate,
		A.ValidDate,
		A.GoodsBTypeID,
		dbo.F_RoundPrice(A.GoodsCostPrice),
		A.HandZeroCost,
		@STypeID,
		CASE WHEN A.BeforePrice='' THEN NULL ELSE A.BeforePrice END,
		CASE WHEN A.BeforeTotal='' THEN NULL ELSE A.BeforeTotal END,
		dbo.F_RoundPercentage(A.AdRate)
		,dbo.F_RoundQty(A.NQty)
		,dbo.F_RoundTranslateRate(A.UnitRate)
		,A.ItemID
		,A.IsCombined
		,CASE WHEN A.KTypeID<>'00000'
			  THEN  CASE WHEN A.CargoID=0
					THEN B.CargoID
			  ELSE  A.CargoID
			  END
		ELSE A.CargoID
		END
		,A.ktypeid
		,A.Serial
		,dbo.F_RoundTotal(A.NTotal)
		,dbo.F_RoundPrice(A.NPrice)
		,A.frombillid
		,ShowOrder
		,dbo.F_RoundTotal(A.ChangeTotal)
		,1
	FROM @tb A LEFT JOIN CargoType B ON A.KTypeID=B.KTypeID AND B.IsDefault=1 ;
	SELECT * FROM @tb 
END
GO



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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
作者：廖晨羽
描述：写入明细表(表值)
*/
CREATE PROCEDURE [GP_InsertAdvantageBillDT]
(
	@details TBType_Advantage READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

-- 写入数据表
	INSERT INTO Advantage
	(
		BillNumberID,
		Serial,
		PTypeID,
		StartDate,
		EndDate,
		StandardCode,
		Type,
		Qty,
		Total,
		Comment,
		BillType,
		STypeID,
		--9.0新加字段
		ITEMID,
		IsCombined,
		GoodsNumber     
	)
	SELECT 
		BillNumberID,
		Serial,
		PTypeID,
		StartDate,
		EndDate,
		StandardCode,
		Type,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundTotal(Total),
		Comment,
		BillType,
		STypeID,  
		--9.0新加字段
		ITEMID, 
		IsCombined,
		GoodsNumber           
	FROM 
		@details

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Gp_InsertAPIApplication]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_InsertAPIApplication]
GO

/****** Object:  StoredProcedure [dbo].[Gp_InsertK]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [dbo].[Gp_InsertAPIApplication]
(
	@CompanyName		[varchar](200),
	@BizLinecenseCode	[varchar](200),
	@ContactName		[varchar](50),
	@ContactNum			[varchar](50),
	@ContactEmail		[varchar](50),
	@ContactAddr		[varchar](200),
	@AppCode			VARCHAR(50) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

--判断是否提交过
DECLARE @State INT
SELECT @State=BillState FROM APIApplicationBill where BizLinecenseCode=@BizLinecenseCode AND CompanyName=@CompanyName 
IF @State=0
BEGIN
	RAISERROR('您已提交过审核单且处于未审核状态，请勿重复提交',16,1) 
	RETURN
END

ELSE IF @State=1
BEGIN
	RAISERROR('您已提交过审核单且已经审核通过，请勿重复提交',16,1) 
	RETURN
END

ELSE
BEGIN
	DECLARE @OrderID VARCHAR(10),@BillCode VARCHAR(50)
	SELECT @OrderID='1'+ISNULL(MAX(OrderID),'00000') FROM APIApplicationBill WHERE CAST(SubmitDate AS DATE)=CAST(GETDATE() AS DATE)
	SET @OrderID=RIGHT(CAST(@OrderID AS INT)+1,5)
	SET @BillCode='API_'+CONVERT(varchar(100), GETDATE(), 112)+'_'+@OrderID
	INSERT INTO APIApplicationBill
	(
		BillCode, 
		OrderID, 
		CompanyName, 
		BizLinecenseCode, 
		ContactName, 
		ContactNum, 
		ContactEmail, 
		ContactAddr, 
		SubmitDate, 
		BillState, 
		Auditor, 
		AuditDate,
		APPSecret
	)
	VALUES
	(
		@BillCode,
		@OrderID,
		@CompanyName,
		@BizLinecenseCode,
		@ContactName,
		@ContactNum,
		@ContactEmail,
		@ContactAddr,
		GETDATE(),
		0,
		'',
		'',
		''
	)
	SET @AppCode=@BillCode
	RETURN
END

GO





GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'dbo.Gp_InsertAppraisalBackBillDT',N'P'))
BEGIN
	DROP PROC dbo.Gp_InsertAppraisalBackBillDT;
END
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
		作者：司华山
		时间：2015-05-14
		描述：新增暂估退货明细
*/

CREATE PROC dbo.Gp_InsertAppraisalBackBillDT
(
	@Details TbType_AppraisalBackBill READONLY
)
--@encode$--
AS 
BEGIN
	SET NOCOUNT ON
	
	DECLARE @BillNumberID VARCHAR(50)
		
	SELECT TOP 1 @BillNumberID = BillNumberID FROM @details
	
	--期初单据不处理草稿库存
	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
	BEGIN
		-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
		EXEC GP_Deal_DraftQTY @BillNumberID,401,'-'
	END
	
	DELETE A FROM dbo.AppraisalBackBill A,@Details B WHERE A.BillNumberId=B.BillNumberID
		AND NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID
												 AND A.BillNumberId=B.BillNumberID
												 AND A.OldBillNumberID=B.OldBillNumberID
												 AND A.OldID=B.OldID
												 AND B.ID<>0)
	
	INSERT INTO AppraisalBackBill([BillNumberId],
								  [PtypeId],
								  [Qty],
								  [SalePrice],
								  [discount],
								  [DiscountPrice],
								  [costprice],
								  [total],
								  [TaxPrice],
								  [TaxTotal],
								  [comment],
								  [TeamNo],
								  [TeamNo1],
								  [Serial],
								  [OldID],
								  [OldBillNumberID],
								  [InputCostPrice],
								  [GoodsOrder],
								  [GoodsNumber],
								  [ProduceDate],
								  [ValidDate],
								  [GoodsCostPrice],
								  [HandZeroCost],
								  [SaleTotal],
								  [Tax],
								  [KTypeID],
								  [Stypeid],
								  [TaxMoney],
								  [NSalePrice],
								  [NSaleTotal],
								  [NDiscountPrice],
								  [NTotal],
								  [NTaxPrice],
								  [NTaxTotal],
								  [NTaxMoney],
								  [UnitID],
								  [NUnitID],
								  [NQty],
								  [UnitRate],
								  [NUnitMsg],
								  [MUnitID],
								  [MQty],
								  [MUnitRate],
								  [MUnitMsg],
								  [MSalePrice],
								  [MDiscountPrice],
							 	  [MTaxPrice],
								  [CurMSalePrice],
								  [CurMDiscountPrice],
								  [CurMTaxPrice],
								  [CargoID],
								  [ItemID],
								  [IsCombined],
								  [InvoiceQty],
								  [InvoiceMoney],
								  [NInvoiceMoney],
								  [IsGift],
								  [PriceStyle],
								  [InvoiceCostTotal],
								  [InvoiceMoneyEX],
								  [NInvoiceMoneyEX],
								  [InvoiceNQty],
								  [CostTotal],
								  [InvoiceSaleMoney],
								  [NInvoiceSaleMoney],
								  [ShareFee],
								  [ShowOrder],
						    	  PriceSource
								 )
	SELECT						  BillNumberId,
								  PtypeId,
								  dbo.F_RoundQty(Qty),
								  dbo.F_RoundPrice(SalePrice),
								  dbo.F_RoundDiscount(discount),
								  dbo.F_RoundPrice(DiscountPrice),
								  dbo.F_RoundPrice(costprice),
								  dbo.F_RoundTotal(total),
								  dbo.F_RoundPrice(TaxPrice),
								  dbo.F_RoundTotal(TaxTotal),
								  comment,
								  TeamNo,
								  TeamNo1,
								  Serial,
								  OldID,
								  OldBillNumberID,
								  dbo.F_RoundPrice(InputCostPrice),
								  GoodsOrder,
								  GoodsNumber,
								  ProduceDate,
								  ValidDate,
								  dbo.F_RoundPrice(GoodsCostPrice),
								  HandZeroCost,
								  dbo.F_RoundTotal(SaleTotal),
								  dbo.F_RoundTax(Tax),
								  KTypeID,
								  Stypeid,
								  dbo.F_RoundTotal(TaxMoney),
								  dbo.F_RoundPrice(NSalePrice),
								  dbo.F_RoundTotal(NSaleTotal),
								  dbo.F_RoundPrice(NDiscountPrice),
								  dbo.F_RoundTotal(NTotal),
								  dbo.F_RoundPrice(NTaxPrice),
								  dbo.F_RoundTotal(NTaxTotal),
								  dbo.F_RoundTotal(NTaxMoney),
								  UnitID,
								  NUnitID,
								  dbo.F_RoundQty(NQty),
								  dbo.F_RoundTranslateRate(UnitRate),
								  NUnitMsg,
								  MUnitID,
								  dbo.F_RoundQty(MQty),
								  dbo.F_RoundTranslateRate(MUnitRate),
								  MUnitMsg,
								  dbo.F_RoundPrice(MSalePrice),
								  dbo.F_RoundPrice(MDiscountPrice),
							 	  dbo.F_RoundPrice(MTaxPrice),
								  dbo.F_RoundPrice(CurMSalePrice),
								  dbo.F_RoundPrice(CurMDiscountPrice),
								  dbo.F_RoundPrice(CurMTaxPrice),
								  CargoID,
								  ItemID,
								  IsCombined,
								  dbo.F_RoundQty(InvoiceQty),
								  dbo.F_RoundTotal(InvoiceMoney),
								  dbo.F_RoundTotal(NInvoiceMoney),
								  IsGift,
								  PriceStyle,
								  dbo.F_RoundTotal(InvoiceCostTotal),
								  dbo.F_RoundTotal(InvoiceMoneyEX),
								  dbo.F_RoundTotal(NInvoiceMoneyEX),
								  dbo.F_RoundQty(InvoiceNQty),
								  dbo.F_RoundTotal(CostTotal),
								  dbo.F_RoundTotal(InvoiceSaleMoney),
								  dbo.F_RoundTotal(NInvoiceSaleMoney),
								  dbo.F_RoundTotal(ShareFee),
								  ShowOrder,
							      PriceSource
		FROM @Details A WHERE ID=0 OR NOT EXISTS(SELECT ID FROM dbo.AppraisalBackBill B WHERE A.ID=B.ID
												 AND A.BillNumberId=B.BillNumberID
												 AND A.OldBillNumberID=B.OldBillNumberID
												 AND A.OldID=B.OldID)
		
		UPDATE A	SET		A.[PtypeId]				= B.[PtypeId],
							A.[Qty]					= B.[Qty],
							A.[SalePrice]			= B.[SalePrice],
							A.[discount]			= B.[discount],
							A.[DiscountPrice]		= B.[DiscountPrice],
							A.[costprice]			= B.[costprice],
							A.[total]				= B.[total],
							A.[TaxPrice]			= B.[TaxPrice],
							A.[TaxTotal]			= B.[TaxTotal],
							A.[comment]				= B.[comment],
							A.[TeamNo]				= B.[TeamNo],
							A.[TeamNo1]				= B.[TeamNo1],
							A.[Serial]				= B.[Serial],
							A.[OldID]				= B.[OldID],
							A.[OldBillNumberID]		= B.[OldBillNumberID],
							A.[InputCostPrice]		= B.[InputCostPrice],
							A.[GoodsOrder]			= B.[GoodsOrder],
							A.[GoodsNumber]			= B.[GoodsNumber],
							A.[ProduceDate]			= B.[ProduceDate],
							A.[ValidDate]			= B.[ValidDate],
							A.[GoodsCostPrice]		= B.[GoodsCostPrice],
							A.[HandZeroCost]		= B.[HandZeroCost],
							A.[SaleTotal]			= B.[SaleTotal],
							A.[Tax]					= B.[Tax],
							A.[KTypeID]				= B.[KTypeID],
							A.[Stypeid]				= B.[Stypeid],
							A.[TaxMoney]			= B.[TaxMoney],
							A.[NSalePrice]			= B.[NSalePrice],
							A.[NSaleTotal]			= B.[NSaleTotal],
							A.[NDiscountPrice]		= B.[NDiscountPrice],
							A.[NTotal]				= B.[NTotal],
							A.[NTaxPrice]			= B.[NTaxPrice],
							A.[NTaxTotal]			= B.[NTaxTotal],
							A.[NTaxMoney]			= B.[NTaxMoney],
							A.[UnitID]				= B.[UnitID],
							A.[NUnitID]				= B.[NUnitID],
							A.[NQty]				= B.[NQty],
							A.[UnitRate]			= B.[UnitRate],
							A.[NUnitMsg]			= B.[NUnitMsg],
							A.[MUnitID]				= B.[MUnitID],
							A.[MQty]				= B.[MQty],
							A.[MUnitRate]			= B.[MUnitRate],
							A.[MUnitMsg]			= B.[MUnitMsg],
							A.[MSalePrice]			= B.[MSalePrice],
							A.[MDiscountPrice]		= B.[MDiscountPrice],
							A.[MTaxPrice]			= B.[MTaxPrice],
							A.[CurMSalePrice]		= B.[CurMSalePrice],
							A.[CurMDiscountPrice]	= B.[CurMDiscountPrice],
							A.[CurMTaxPrice]		= B.[CurMTaxPrice],
							A.[CargoID]				= B.[CargoID],
							A.[ItemID]				= B.[ItemID],
							A.[IsCombined]			= B.[IsCombined],
							A.[InvoiceQty]			= B.[InvoiceQty],
							A.[InvoiceMoney]		= B.[InvoiceMoney],
							A.[NInvoiceMoney]		= B.[NInvoiceMoney],
							A.[IsGift]				= B.[IsGift],
							A.[PriceStyle]			= B.[PriceStyle],
							A.[InvoiceCostTotal]	= B.[InvoiceCostTotal],
							A.[InvoiceMoneyEX]		= B.[InvoiceMoneyEX],
							A.[NInvoiceMoneyEX]		= B.[NInvoiceMoneyEX],
							A.[InvoiceNQty]			= B.[InvoiceNQty],
							A.[CostTotal]			= B.[CostTotal],
							A.[InvoiceSaleMoney]	= B.[InvoiceSaleMoney],
							A.[NInvoiceSaleMoney]	= B.[NInvoiceSaleMoney],
							A.[ShareFee]			= B.[ShareFee],
							A.[ShowOrder]			= B.[ShowOrder]	  ,
							A.[PriceSource] 	= B.[PriceSource]
		FROM AppraisalBackBill A,@Details B WHERE A.ID=B.ID
											  AND A.BillNumberId=B.BillNumberID
											  AND A.OldBillNumberID=B.OldBillNumberID
											  AND A.OldID=B.OldID
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO
IF EXISTS(SELECT Name FROM SysObjects WHERE ID=OBJECT_ID('dbo.GP_InsertAppraisalBackBillDTCheck'))
BEGIN
	DROP PROC dbo.GP_InsertAppraisalBackBillDTCheck;
END
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON;
GO
/*
		作者：司华山
		日期：2015-05-19
		描述：暂估退货单保存前检查退货商品数量与原单商品数量
*/
CREATE PROC dbo.GP_InsertAppraisalBackBillDTCheck
(
	@Details TbType_AppraisalBackBill READONLY
)
--@encode$--
AS
BEGIN
	SELECT 1 AS Ret FROM AppraisalBill a JOIN @Details b on a.BillNumberId=b.OldBillNumberId AND a.Id=b.OldId
	WHERE b.OldBillNumberId<>0 AND ISNULL(a.Qty,0)-ISNULL(a.Backqty,0)<b.Qty 
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'dbo.Gp_InsertAppraisalBillDT',N'P'))
BEGIN
	DROP PROC dbo.Gp_InsertAppraisalBillDT
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*
		作者：司华山
		日期：2015-05-14
		描述：新增暂估入库明细
*/
CREATE PROC dbo.Gp_InsertAppraisalBillDT
(
	@Details TbType_AppraisalBill READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @BillNumberID VARCHAR(50)

	SELECT TOP 1 @BillNumberID = BillNumberID FROM @Details
	

	--期初单据不处理草稿库存
	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
	BEGIN
		-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
		EXEC GP_Deal_DraftQTY @BillNumberID,400,'-'
		
		IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f' AND draft=1)
		BEGIN
			-- 处理订单库存,先减去引用未过账数量
			EXEC GP_Deal_OrderReferQty @BillnumberID,400,'-'
		END
		ELSE
		BEGIN
			-- 处理订单库存,先减去过账数量
			EXEC GP_Deal_OrderReachQTY @BillnumberID,400,'-'
		END
	END
	
	UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
	FROM OrderBill a 
	JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM @Details b WHERE b.OrderId<>-1 GROUP BY orderid)b ON b.orderid=a.OrderID
	
	DELETE A FROM dbo.AppraisalBill A,@Details B WHERE A.BillNumberId=B.BillNumberID
		AND NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID
												 AND A.BillNumberId=B.BillNumberID
												 AND A.orderid=B.OrderID
												 AND B.ID<>0)
	
	INSERT INTO AppraisalBill([BillNumberId],
							  [PtypeId],
							  [Qty],
							  [SalePrice],
							  [discount],
							  [DiscountPrice],
							  [total],
							  [TaxPrice],
							  [TaxTotal] ,
							  [comment],
							  [TeamNo1],
							  [TeamNo] ,
							  [orderid],
							  [Serial] ,
							  [InputCostPrice],
							  [GoodsOrder] ,
							  [BackQty] ,
							  [GoodsNumber],
							  [ProduceDate],
							  [ValidDate] ,
							  [GoodsCostPrice],
							  [HandZeroCost],
							  [SaleTotal],
							  [Tax],
							  [KTypeID] ,
							  [Stypeid],
							  [TaxMoney] ,
							  [NSalePrice],
							  [NSaleTotal],
							  [NDiscountPrice] ,
							  [NTotal] ,
							  [NTaxPrice],
							  [NTaxTotal],
							  [NTaxMoney],
							  [UnitID] ,
							  [NUnitID] ,
							  [NQty],
							  [UnitRate],
							  [NUnitMsg] ,
							  [MUnitID],
							  [MQty],
							  [MUnitRate] ,
							  [MUnitMsg],
							  [MSalePrice],
							  [MDiscountPrice] ,
							  [MTaxPrice] ,
							  [CurMSalePrice],
							  [CurMDiscountPrice],
							  [CurMTaxPrice],
							  [CargoID] ,
							  [ItemID],
							  [IsCombined] ,
							  [entryCode] ,
							  [InvoiceQty],
							  [InvoiceMoney],
							  [NInvoiceMoney],
							  [IsGift],
							  [InvoiceMoneyEX],
							  [NInvoiceMoneyEX] ,
							  [InvoiceCostTotal],
							  [InvoiceNQty],
							  [InvoiceSaleMoney],
							  [NInvoiceSaleMoney],
							  [ShareFee],
							  [OldBillNumberID],
							  [OldID],
							  [ShowOrder],
							 [PriceSource] 
							  )
	SELECT					  BillNumberId,
							  PtypeId,
							  dbo.F_RoundQty(Qty),
							  dbo.F_RoundPrice(SalePrice),
							  dbo.F_RoundDiscount(discount),
							  dbo.F_RoundPrice(DiscountPrice),
							  dbo.F_RoundTotal(total),
							  dbo.F_RoundPrice(TaxPrice),
							  dbo.F_RoundTotal(TaxTotal) ,
							  comment,
							  TeamNo1,
							  TeamNo ,
							  orderid,
							  Serial ,
							  dbo.F_RoundPrice(InputCostPrice),
							  GoodsOrder ,
							  dbo.F_RoundQty(BackQty) ,
							  GoodsNumber,
							  ProduceDate,
							  ValidDate ,
							  dbo.F_RoundPrice(GoodsCostPrice),
							  HandZeroCost,
							  dbo.F_RoundTotal(SaleTotal),
							  dbo.F_RoundTax(Tax),
							  KTypeID ,
							  Stypeid,
							  dbo.F_RoundTotal(TaxMoney) ,
							  dbo.F_RoundPrice(NSalePrice),
							  dbo.F_RoundTotal(NSaleTotal),
							  dbo.F_RoundPrice(NDiscountPrice) ,
							  dbo.F_RoundTotal(NTotal) ,
							  dbo.F_RoundPrice(NTaxPrice),
							  dbo.F_RoundTotal(NTaxTotal),
							  dbo.F_RoundTotal(NTaxMoney),
							  UnitID ,
							  NUnitID ,
							  dbo.F_RoundQty(NQty),
							  dbo.F_RoundTranslateRate(UnitRate),
							  NUnitMsg ,
							  MUnitID,
							  dbo.F_RoundQty(MQty),
							  dbo.F_RoundTranslateRate(MUnitRate) ,
							  MUnitMsg,
							  dbo.F_RoundPrice(MSalePrice),
							  dbo.F_RoundPrice(MDiscountPrice) ,
							  dbo.F_RoundPrice(MTaxPrice) ,
							  dbo.F_RoundPrice(CurMSalePrice),
							  dbo.F_RoundPrice(CurMDiscountPrice),
							  dbo.F_RoundPrice(CurMTaxPrice),
							  CargoID ,
							  ItemID,
							  IsCombined ,
							  entryCode ,
							  dbo.F_RoundQty(InvoiceQty),
							  dbo.F_RoundTotal(InvoiceMoney),
							  dbo.F_RoundTotal(NInvoiceMoney),
							  IsGift,
							  dbo.F_RoundTotal(InvoiceMoneyEX),
							  dbo.F_RoundTotal(NInvoiceMoneyEX) ,
							  dbo.F_RoundTotal(InvoiceCostTotal),
							  dbo.F_RoundQty(InvoiceNQty),
							  dbo.F_RoundTotal(InvoiceSaleMoney),
							  dbo.F_RoundTotal(NInvoiceSaleMoney),
							  ShareFee,
							  dbo.F_RoundTotal(OldBillNumberID),
							  OldID,
							  ShowOrder,
							  PriceSource
		FROM @Details A WHERE A.ID=0 OR NOT EXISTS(SELECT ID FROM dbo.AppraisalBill B WHERE A.ID=B.ID
																						AND A.BillNumberId=B.BillNumberID
																						AND A.orderid=B.OrderID)
		
		UPDATE A SET		  A.[BillNumberId]		=	B.[BillNumberId],
							  A.[PtypeId]			=	B.[PTypeID],
							  A.[Qty]				=	B.[Qty],
							  A.[SalePrice]			=	B.[SalePrice],
							  A.[discount]			=	B.[discount],
							  A.[DiscountPrice]		=	B.[DiscountPrice],
							  A.[total]				=	B.[total],
							  A.[TaxPrice]			=	B.[TaxPrice],
							  A.[TaxTotal]			=	B.[TaxTotal] ,
							  A.[comment]			=	B.[Comment],
							  A.[TeamNo1]			=	B.[TeamNo1],
							  A.[TeamNo]			=	B.[TeamNo] ,
							  A.[orderid]			=	B.[OrderID],
							  A.[Serial]			=	B.[Serial],
							  A.[InputCostPrice]	=	B.[InputCostPrice],
							  A.[GoodsOrder]		=	B.[GoodsOrder],
							  A.[BackQty]			=	B.[BackQty],
							  A.[GoodsNumber]		=	B.[GoodsNumber],
							  A.[ProduceDate]		=	B.[ProduceDate],
							  A.[ValidDate]			=	B.[ValidDate],
							  A.[GoodsCostPrice]	=	B.[GoodsCostPrice],
							  A.[HandZeroCost]		=	B.[HandZeroCost],
							  A.[SaleTotal]			=	B.[SaleTotal],
							  A.[Tax]				=	B.[Tax],
							  A.[KTypeID]			=	B.[KTypeID],
							  A.[Stypeid]			=	B.[Stypeid],
							  A.[TaxMoney]			=	B.[TaxMoney],
							  A.[NSalePrice]		=	B.[NSalePrice],
							  A.[NSaleTotal]		=	B.[NSaleTotal],
							  A.[NDiscountPrice]	=	B.[NDiscountPrice] ,
							  A.[NTotal]			=	B.[NTotal],
							  A.[NTaxPrice]			=	B.[NTaxPrice],
							  A.[NTaxTotal]			=	B.[NTaxTotal],
							  A.[NTaxMoney]			=	B.[NTaxMoney],
							  A.[UnitID]			=	B.[UnitID],
							  A.[NUnitID]			=	B.[NUnitID],
							  A.[NQty]				=	B.[NQty],
							  A.[UnitRate]			=	B.[UnitRate],
							  A.[NUnitMsg]			=	B.[NUnitMsg],
							  A.[MUnitID]			=	B.[MUnitID],
							  A.[MQty]				=	B.[MQty],
							  A.[MUnitRate] 		=	B.[MUnitRate],
							  A.[MUnitMsg]			=	B.[MUnitMsg],
							  A.[MSalePrice]		=	B.[MSalePrice],
							  A.[MDiscountPrice]	=	B.[MDiscountPrice],
							  A.[MTaxPrice]			=	B.[MTaxPrice],
							  A.[CurMSalePrice]		=	B.[CurMSalePrice],
							  A.[CurMDiscountPrice] =	B.[CurMDiscountPrice],
							  A.[CurMTaxPrice]		=	B.[CurMTaxPrice],
							  A.[CargoID]			=	B.[CargoID],
							  A.[ItemID]			=	B.[ItemID],
							  A.[IsCombined]		=	B.[IsCombined],
							  A.[entryCode]			=	B.[entryCode],
							  A.[InvoiceQty]		=	B.[InvoiceQty],
							  A.[InvoiceMoney]		=	B.[InvoiceMoney],
							  A.[NInvoiceMoney]		=	B.[NInvoiceMoney],
							  A.[IsGift]			=	B.[IsGift],
							  A.[InvoiceMoneyEX]	=	B.[InvoiceMoneyEX],
							  A.[NInvoiceMoneyEX]	=	B.[NInvoiceMoneyEX],
							  A.[InvoiceCostTotal]	=	B.[InvoiceCostTotal],
							  A.[InvoiceNQty]		=	B.[InvoiceNQty],
							  A.[InvoiceSaleMoney]	=	B.[InvoiceSaleMoney],
							  A.[NInvoiceSaleMoney]	=	B.[NInvoiceSaleMoney],
							  A.[ShareFee]			=	B.[ShareFee],
							  A.[OldBillNumberID]	=	B.[OldBillNumberID],
							  A.[OldID]			=	B.[OldID],
							  A.[ShowOrder]			=	B.[ShowOrder],
							  A.[PriceSource] 	= B.[PriceSource]
		FROM dbo.AppraisalBill A ,@Details B WHERE A.ID=B.ID
											   AND A.BillNumberId=B.BillNumberID
											   AND A.orderid=B.OrderID
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



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


/****** Object:  StoredProcedure [dbo].[Gp_InsertArea]    Script Date: 05/20/2011 17:29:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO






CREATE               PROCEDURE [dbo].[Gp_InsertArea]
(
 @Parid   [varchar](50),
 @DbName         [varchar](30),
 @UserCode  [varchar](256),
 @FullName  [varchar](256),
 @Name [varchar](256),
 @Tel [varchar](256),
 @LinkMan [varchar](256),
 @PyCode  [varchar](256),
 @Comment  [varchar](256)

)
--@encode$--
AS
SET NOCOUNT ON
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from areatype where typeid=@parid)


--判断停用不能分类
declare @deleted INT
select @deleted=deleted from areatype where typeId=@Parid
	if(@deleted=1)
		begin
			RAISERROR('该地区档案【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
		end
-- 判断库存量（每种商品）是否为零


-----------------------------判断是否在自定义中有关联信息--------------------------------------
DECLARE 
	@result			INT=0,		--自定义接收返回值
	@temptypename	VARCHAR(20)
SET @temptypename='AreaType'

--能否分类判断
EXEC Gp_BaseInfoCheck 'AreaType',@ParId,'0'

-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1
begin
	RAISERROR('地区档案的分类不能超过10层',16,1)return--return -1
end
if @nReturntype=-2 
begin
	RAISERROR('无法添加基本信息',16,1)return--return -2
end
 
-- 判断重复的ID,UserCode

if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) OR (fullname=@fullname and deleted<>1) )
begin
	
	--print '['+@usercode+']地区档案已存在'
	--print  @EtypeId_1
	RAISERROR('【%s】已经存在，地区档案的名称或编号不能相同',16,1,@FullName)return--return -3
end
-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
begin
	--print '['+@usercode+']地区档案已存在'
	RAISERROR('【%s】名称或编号不能与已有的名称或编号重复',16,1,@FullName)return--return -10
end

-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) OR (fullname=@fullname and deleted=1))
begin
	--print '['+@usercode+']地区档案已存在'
	RAISERROR('该【%s】的编号或名称已被已停用的地区档案使用，请更换或删除该停用的编号或名称',16,1,@FullName)return---return -31
end
-- 判断重复的ID,UserCode
if exists(select * from [AreaType] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
begin
	--print '['+@usercode+']地区档案已存在'
	RAISERROR('该地区档案【%s】名称或编号不能与已停用的名称或编号重复',16,1,@FullName)return--return -101
end

/*
-- 判断地区档案的最大使用数量
declare @nCount int
select @nCount=Count(*) from AreaType 
where sonnum = 0 
 and deleted=0
if @nCount > 10
begin
-- print '地区档案数量大于10'
 return -99
end
*/

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode


begin tran insertproc
select @leveal=leveal from AreaType where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO [AreaType] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [UserCode],
  [FullName], 
  [Name],
  [SysFlag],
  [deleted],
  [Comment],
  [PyCode],
  [Tel],
  [LinkMan]	
 )  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @UserCode,
  @FullName,
  @name,
  0,
  0,
  @Comment,
  @returnPym,
  @Tel,
  @LinkMan
 )
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [AreaType]
 set sonnum=@nSonnum+1,soncount=@nSoncount+1
 where typeid=@Parid
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AreaType
UPDATE AreaType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
commit tran insertproc





















GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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















/****** Object:  Stored Procedure dbo.Gp_InsertAreaDept    Script Date: 2002-6-20 10:14:48 ******/

CREATE  PROCEDURE [Gp_InsertAreaDept]
(
 @Dbname  [varchar](30),
 @usercode  [varchar](10),
 @Fullname  [varchar](50),
 @Comment  [varchar](50)
)
--@encode$--
AS 
SET NOCOUNT ON
declare @sql varchar(2000)
select @sql='INSERT INTO '+@Dbname+' ( usercode,Fullname,Comment) VALUES ( '+char(39)+@usercode+char(39)+','
  +char(39)+@Fullname+char(39)+','+char(39)+ @Comment+char(39)+')'
exec(@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.08.29
	描述：将明细中的辅助核算字填入生成的凭证明细辅助核算中
			并排出不存在的辅助核算以重写明细中的辅助核算 
*/
CREATE PROCEDURE Gp_InsertAscidsAsDetails
(
	@VoucherID	INT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @ascids VARCHAR(MAX),@Id INT
	
CREATE TABLE #TmpItem
(
	id		INT IDENTITY(1,1),
	item	VARCHAR(500)
)

CREATE TABLE #TmpAscid
(
	id	INT	IDENTITY(1,1),
	value	VARCHAR(50)
)

DECLARE AscidCur CURSOR READ_ONLY FOR
	SELECT id,AscIds 
	FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID
OPEN AscidCur
FETCH NEXT FROM AscidCur INTO @Id,@ascids
WHILE (@@FETCH_STATUS = 0)
BEGIN
	SELECT @ascids = SUBSTRING(@ascids,0,LEN(@ascids))
	
	INSERT INTO #TmpItem(item )
	SELECT * FROM dbo.f_split(@ascids,',')
	
	
	DECLARE @Count INT,@Item VARCHAR(500),@Index INT,@ItemId INT
	SET @Index = 1
	SELECT @Count = COUNT(*) FROM #TmpItem
	
	WHILE @Index <= @Count
	BEGIN
		SELECT @Item = item FROM #TmpItem WHERE id = @Index
		
		INSERT INTO #TmpAscid(value )
		SELECT * FROM dbo.f_split(@item,':')
		SET @Index += 1
	END
	
	
	INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
		        ( BillNumberId ,
		          vBId ,
		          typeName ,
		          TypeId
		        )
		SELECT DISTINCT @VoucherID,@id,T3.UserCode,T2.value
		FROM #TmpAscid T1
			INNER JOIN #TmpAscid t2 ON T1.id = (T2.id - 1)
			INNER JOIN dbo.Ac_Assist_CheckItems T3 ON T1.value = T3.AscIds
			INNER JOIN dbo.Ac_Account_Assist_CheckItems T4 ON T3.AscIds = T4.Ascids
			INNER JOIN dbo.Ac_Account T5 ON T4.STypeId = T5.StypeId AND T4.ATypeId = T5.TypeId
			INNER JOIN dbo.Ac_Voucher_Bill T6 ON T5.TypeId = T6.ATypeId AND T5.StypeId = T6.STypeId AND T6.ID = @id AND t6.BillNumberId = @VoucherID
		WHERE T1.id % 2 <> 0
	
	
	TRUNCATE TABLE #TmpAscid
	TRUNCATE TABLE #TmpItem
	
	SET @ascids = ''
	FETCH NEXT FROM AscidCur INTO @Id,@ascids
END

CLOSE AscidCur
DEALLOCATE AscidCur


--调整明细辅助核算
UPDATE dbo.Ac_Voucher_Bill SET AscIds= dbo.F_Get_VoucherAscids(id,1) WHERE BillNumberId = @VoucherID

DROP TABLE #TmpItem,#TmpAscid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.06.25
	描述：用于将期初数据的辅助核算字填入生成的凭证明细辅助核算中
*/
CREATE PROCEDURE Gp_InsertAscidsForInitAccount
(
	@BillnumberId	INT,
	@id		INT,--明细id
	@ascids	VARCHAR(2000)--辅助核算信息
)
--@encode$--
AS
SET NOCOUNT ON
	
	CREATE TABLE #TmpItem
	(
		id		INT IDENTITY(1,1),
		item	VARCHAR(500)
	)
	
	CREATE TABLE #TmpAscid
	(
		id	INT	IDENTITY(1,1),
		value	VARCHAR(50)
	)
	

	SELECT @ascids = SUBSTRING(@ascids,0,LEN(@ascids))

	
	INSERT INTO #TmpItem(item )
	SELECT * FROM dbo.f_split(@ascids,',')
	
	
	DECLARE @Count INT,@Item VARCHAR(500),@Index INT,@ItemId INT
	SET @Index = 1
	SELECT @Count = COUNT(*) FROM #TmpItem
	
	WHILE @Index <= @Count
	BEGIN
		SELECT @Item = item FROM #TmpItem WHERE id = @Index
		
		INSERT INTO #TmpAscid(value )
		SELECT * FROM dbo.f_split(@item,':')
		
		SET @Index += 1
	END
	

	
	INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
		        ( BillNumberId ,
		          vBId ,
		          typeName ,
		          TypeId
		        )
		SELECT @billnumberid,@id,T3.UserCode,T2.value
		FROM #TmpAscid T1
			INNER JOIN #TmpAscid t2 ON T1.id = (T2.id - 1)
			INNER JOIN dbo.Ac_Assist_CheckItems T3 ON T1.value = T3.AscIds
		WHERE T1.id % 2 <> 0
		
	DROP TABLE #TmpItem,#TmpAscid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertAskPriceBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertAskPriceBillDT;
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-04 09:42:48.077
	描述：询价单明细查入DT 版
*/
CREATE PROCEDURE Gp_InsertAskPriceBillDT
(
	@tb TbType_AskPrice READONLY
)	
--@encode$--
AS
BEGIN
	INSERT INTO AskPriceBill(
		BillNumberID,
		PTypeID,
		Qty,
		Price,
		SaleTotal,
		Discount,
		DiscountPrice,
		total,
		Tax,
		TaxPrice,
		TaxTotal,
		Comment,
		isUnit2,
		STypeID
		
		-- 新字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty--15
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		,IfBargainOn
		,ShowOrder
		,PriceSource
	) SELECT
		BillNumberID,
		PTypeID,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(Price),
		dbo.F_RoundTotal(SaleTotal),
		dbo.F_RoundDiscount(Discount),
		dbo.F_RoundPrice(DiscountPrice),
		dbo.F_RoundTotal(Total),
		dbo.F_RoundTax(Tax),
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		Comment,
		IsUnit2,
		STypeID
		
		-- 新字段
		,dbo.F_RoundTotal(TaxMoney) --1
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty) --15
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined --25
		,IfBargainOn
		,ShowOrder
		,PriceSource
	FROM @tb;
		
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_InsertAssetDepDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].GP_InsertAssetDepDT
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2013-05-20 14:15:43.577
	描述：固定折旧单
*/
CREATE  PROCEDURE GP_InsertAssetDepDT
(
	@tb TbType_AssetDep READONLY
)
--@encode$--
AS 
    SET NOCOUNT ON
    INSERT INTO dbo.DepBill
            ( BillNumberId ,
              AssetCardId ,
              Depreciation ,
              Comment,
              WorkTime,
              WorkUnit,
              DTypeId
            )
            SELECT 
            BillNumberId
            ,AssetCardId
            ,dbo.F_RoundTotal(Depreciation)
            ,Comment
            ,WorkTime
            ,WorkUnit
            ,DTypeId
            FROM @tb;
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-01
	描述：写入过账模版
*/
CREATE PROCEDURE Gp_InsertAuditing_Template
(
	@UserCode	VARCHAR(200),	-- 模版编号
	@FullName	VARCHAR(200),	-- 模版名称
	@BillType	INT,			-- 单据类型
	@Group		INT,			-- 凭证字
	@Default    INT,			-- 是否默认 0.否 1.是
	@ETypeId	VARCHAR(50),	-- 创建人
	@oldatid	INT=0,			-- 原模板ID
	@stypeid	VARCHAR(50),	--分支机构ID
	@explaintext	VARCHAR(200),	--说明文字
	@explainaudittype	VARCHAR(200), --说明选择的id
	@iscombinerow	INT,			--是否合并行分录
	@inouttype		VARCHAR(5),		--资金调拨单调出调入标志 1.调入 -1.调出
	@ChargeOffType	INT	,	--往来核销单 0=应收冲应付,1=预收冲预付,2=应收转应收,3=应付转应付,4=预收转应付,5=预付转应收
	@AuditType    INT =0 --业务类型
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PyCode VARCHAR(200),
		@nId	NUMERIC(18,0),
		@isSys	INT
		
SET @PyCode = dbo.Fun_GetPy(@FullName)--拼音码



--判断编号或者名称是否相同
IF EXISTS(SELECT TOP 1 1 FROM Ac_Auditing_Template WHERE BillType = @BillType AND (UserCode = @UserCode OR FullName = @FullName) AND AtId <> @oldatid AND STypeId = @stypeid)
BEGIN
	RAISERROR('模板编号或者名称重复，请确认！',16,1)
	RETURN -1
END

--不存在模板，本模板又不是默认模板
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE BillType = @BillType AND STypeId = @stypeid ) AND @BillType NOT IN (212,213,214,-1,-2,410)
	AND @Default <> 1
BEGIN
	RETURN -3
END


--不存在默认模板,且此模板不是设置为默认
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE BillType = @BillType AND IsDefault = 1 AND STypeId = @stypeid AND AtId <> @oldatid)	
	AND @Default <> 1 AND @BillType<>212 AND @BillType<>213 --卡片增加单减少单,折旧单，不检查默认
BEGIN
	RETURN -4
END

--固定资产增加单折旧单有业务类型单独处理
IF @BillType IN (212,213) 
BEGIN 
	SELECT @AuditType=AuditType FROM Ac_Auditing_Template WHERE AtId = @nId AND BillType = @BillType AND STypeId = @stypeid
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE BillType = @BillType AND STypeId = @stypeid AND AuditType = @AuditType) 
	AND @Default <> 1
	BEGIN
		RETURN -3
	END
	
	IF NOT  EXISTS(SELECT * FROM dbo.Ac_Auditing_Template WHERE BillType = @BillType AND IsDefault = 1 AND STypeId = @stypeid AND AuditType = @AuditType AND AtId <> @oldatid) AND @Default<>1
	BEGIN
		RETURN -4
	END 
END 

--往来核销单 同一个模板类型6个不同模板默认方案设置
IF @BillType=450 AND NOT EXISTS(SELECT * FROM Ac_Auditing_Template WHERE BillType=@BillType AND STypeId=@stypeid AND AtId<>@oldatid AND ChargeOffType=@ChargeOffType AND IsDefault=1)  AND @Default<>1
	RETURN -4


IF @oldatid = 0
BEGIN
	INSERT INTO Ac_Auditing_Template
	(
		UserCode,
		FullName,
		BillType,
		ETypeId,
		IsDefault,
		CreateDateTime,
		PyCode,
		Comment,
		VgId,
		STypeId,
		explaintext,
		ExplainAuditType,
		IsCombineRow,
		InOutType,
		AuditType,
		ChargeOffType
	)VALUES(
		@UserCode,
		@FullName,
		@BillType,
		@ETypeId,
		@Default,
		GETDATE(),
		@PyCode,
		'',
		@Group,
		@stypeid,
		@explaintext,
		@explainaudittype,
		@iscombinerow,
		@inouttype,
		CASE WHEN  @AuditType = 0 THEN NULL
		WHEN @BillType = -1 THEN 12
		WHEN @BillType = -2 THEN 13
		ELSE @AuditType END ,
		CASE WHEN @BillType=450 THEN @ChargeOffType ELSE NULL END
	)

	IF @@ROWCOUNT = 0
	BEGIN
		RETURN -2
	END

	SET @nId = SCOPE_IDENTITY();
END
ELSE
BEGIN
	UPDATE dbo.Ac_Auditing_Template
	SET UserCode = @UserCode,
		FullName = @FullName,
		BillType = @BillType,
		ETypeId = @ETypeId,
		IsDefault = @Default,
		CreateDateTime = GETDATE(),
		PyCode = @PyCode,
		VgId = @Group,
		STypeId = @stypeid,
		explaintext=@explaintext,
		ExplainAuditType=@explainaudittype,
		IsCombineRow=@iscombinerow,
		ChargeOffType=CASE WHEN @BillType=450 THEN @ChargeOffType ELSE NULL END,
		AuditType=@AuditType
	WHERE AtId = @oldatid
	
	SET @nId = @oldatid
END



--修改模版为默认
--9.7.1 BUG 1198
IF(@Default=1)
	BEGIN
		IF (@BillType IN(310,57))
			BEGIN
				UPDATE Ac_Auditing_Template SET IsDefault = 0 WHERE AtId <> @nId AND BillType = @BillType AND STypeId = @stypeid AND InOutType=@inouttype
			END
		--往来核销单增加核销类型后  根据核销类型设置默认模板
		ELSE IF (@BillType=450)
			BEGIN
				UPDATE Ac_Auditing_Template SET IsDefault = 0 WHERE AtId <> @nId AND BillType = @BillType AND STypeId = @stypeid AND ChargeOffType=@ChargeOffType
			END
		ELSE IF (@BillType IN(212,213))-- ,214,-1,-2,410木有业务类型
			BEGIN
				--DECLARE @AuditType INT
				SELECT @AuditType=AuditType FROM Ac_Auditing_Template WHERE AtId = @nId AND BillType = @BillType AND STypeId = @stypeid
				UPDATE dbo.Ac_Auditing_Template SET IsDefault = 0 WHERE AtId <> @nId AND BillType = @BillType AND STypeId = @stypeid AND AuditType = @AuditType 
			END 
		ELSE
			BEGIN
				UPDATE Ac_Auditing_Template SET IsDefault = 0 WHERE AtId <> @nId AND BillType = @BillType AND STypeId = @stypeid 
				--SELECT @nId
			END
	END

RETURN @nId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-01
	描述：写入过账模版明细
	exec Gp_InsertAuditing_Template_Detail @atid=3,@summary='a',@atypefrom=1,@atypeid='',@dc=1,@totalfrom='税额',@express='taxtotal - total',@assitems='职员(职员)',@billtype = 11
*/
CREATE PROCEDURE Gp_InsertAuditing_Template_Detail
(
	@atid			INT,				-- 模版ID
	@summary		VARCHAR(200),		-- 摘要
	@atypefrom		VARCHAR(200),		-- 科目来源
	@atypeid		VARCHAR(50),		-- 会计科目
	@dc				INT,				-- 借贷方向
	@totalfrom		VARCHAR(200),		-- 金额来源
	@express		VARCHAR(1000),		-- 金额来源_公式
	@assitems		VARCHAR(1000)='',	-- 辅助核算名称
	@assitemsids	VARCHAR(1000)='',	-- 辅助核算IDS
	@BillType		INT,				-- 单据类型
	@summarytype	VARCHAR(100),		--摘要选择的id
	@isCost			BIT,				--是否属于成本类明细
	@OrderID		INT					--明细排序ＩＤ
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @BillMoneyId INT

SELECT @BillMoneyId = BillMoneyId FROM Ac_BillMoney_List WHERE FullName = @totalfrom AND Express = @express AND BillType = @BillType

IF @express='balancemoney'
	SELECT @BillMoneyId=BillMoneyId FROM Ac_BillMoney_List WHERE Express='balancemoney'

IF @summarytype IS NULL --OR @summarytype='7'
	SET @summarytype=''

INSERT INTO Ac_Auditing_Template_Detail
(
	AtId,
	Summary,
	AcFrom,
	ATypeId,
	Fdc,
	BillMoneyId,
	Express,
	AssistCheckItmes,
	AssistCheckItmesIds,
	SummaryType,
	isCost,
	OrderID
)VALUES(
	@atid,
	@summary,
	@atypefrom,
	@atypeid,
	@dc,
	@BillMoneyId,
	@express,
	@assitems,
	@assitemsids,
	@summarytype,
	@isCost,
	@OrderID
)

IF @@ROWCOUNT = 0
	RETURN -1
	
RETURN SCOPE_IDENTITY();	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertB]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_InsertB]
GO


/****** Object:  StoredProcedure [dbo].[Gp_InsertB]    Script Date: 05/20/2011 17:29:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
/*最后修改版  作者：董湛   日期：2012-4-17  描述：添加相关字段及参数BackPercent BackLimitDay*/
/*最后修改版  作者：黄飞佳 日期：2012-3-28  描述：是否准许修改单据中价格，添加相关字段及参数*/

/*
	作者：廖晨羽
	日期：2011-08-17
	描述：修改@TelAndAddress参数的长度为256,添加etypeid字段
*/


/*
	作者：吕文祺
	日期：2012-04-18
	描述：新增字段@denominatedid支持结算单位
*/




CREATE PROCEDURE [dbo].[Gp_InsertB]
(
	@Parid   [VARCHAR](50),
	@DbName         [VARCHAR](30),
	@UserCode  [VARCHAR](200),
	@FullName  [VARCHAR](200),
	@Name  [VARCHAR](30), 
	@Area  [VARCHAR](30),
	@TelAndAddress  [VARCHAR](256),
	@PostCode  [VARCHAR](200),
	@Person  [VARCHAR](20),
	@TaxNumber  [VARCHAR](20),
	@bankandacount  [VARCHAR](66),
	@Artotal00  NUMERIC(24, 10) ,
	@Aptotal00    NUMERIC(24, 10) ,
	@Comment  [VARCHAR](256),
	@Client [Bit]=1,
	@ARLimit  NUMERIC(24, 10) =0,
	@ARLimitTime  NUMERIC(24, 10) =99999,
	@PaymentLTime NUMERIC(24, 10) =99999, 
	@Tel1 VARCHAR(50),
	@Tel2 VARCHAR(50),
	@Tel3 VARCHAR(50),
	@WWW VARCHAR(50),
	@Email VARCHAR(50),
	@Fax VARCHAR(50),
	@Bank VARCHAR(50),
	@BankName VARCHAR(50),
	@LinkMan1 VARCHAR(50),
	@LinkSex1 bit,
	@LinkBirthDay1 datetime,
	@LinkJob1 VARCHAR(50),
	@LinkCall1 VARCHAR(50),
	@LinkTel1 VARCHAR(50),
	@LinkMobile1 VARCHAR(50),
	@LinkEMail1 VARCHAR(50),
	@LinkPost1 VARCHAR(50),
	@LinkAddress1 VARCHAR(256),
	@LinkComment1 VARCHAR(256),
	@LinkMan2 VARCHAR(50),
	@LinkSex2 bit,
	@LinkBirthDay2 datetime,
	@LinkJob2 VARCHAR(50),
	@LinkCall2 VARCHAR(50),
	@LinkTel2 VARCHAR(50),
	@LinkMobile2 VARCHAR(50),
	@LinkEMail2 VARCHAR(50),
	@LinkPost2 VARCHAR(50),
	@LinkAddress2 VARCHAR(256),
	@LinkComment2 VARCHAR(256),
	@CreateDate datetime,
	@SaleZeKou  NUMERIC(24, 10) ,
	@BuyZeKou  NUMERIC(24, 10) ,
	@PyCode   VARCHAR(200),
	@Price    VARCHAR(50),
	@AreaTypeID VARCHAR(50),
	@ifStype INT=0,
	@etypeid			VARCHAR(50)='',		--职员
	@buyprice			VARCHAR(50)='',		--适用进价
	@consignee			VARCHAR(100)='',	--收货人
	@consigneetel		VARCHAR(100)='',    --收货人电话
	@consigneeaddress	VARCHAR(1000)='',	--收货人地址	
	@valeditprice BIT,
    @denominatedid VARCHAR(100),
	@backlimitday	INT,				--退换货期限(天)
	@backpercent	INT,				--换货比例(%)
	@cid			INT,				--关联货币
	@pricetrackenable INT=1,				--1.启用价格跟踪 0.不启用
	@cqdays INT=NULL, --超期提前预警
	@chkskmonthday INT=0 , --启用收款月结日 checkbox
	@skmonthday INT=NULL, --启用收款月结日  
	@chkfkmonthday INT=0, --启用付款月结日 checkbox
	@fkmonthday INT=NULL, --启用付款月结日  
	@dzdays INT=NULL, --每月对账日期  
	@dzwarningdays INT=NULL, --对账日提前预警天数  
	
	@ckarlimittime int=NULL, --收款期限
	@ckpaymentltime INT= NULL, --付款期限
	@fkcqdays        INT =NULL, --付款超期提前预警
	@fkdzdays  INT=NULL,--付款每月对账日期
	@fkdzwarningdays int=NULL,  --付款对账日提前预警
	@iscarrier BIT=0,
	@sheng				VARCHAR(100) = '',		--省
	@shi				VARCHAR(100) = '',		--市
	@xian				VARCHAR(100) = '',		--县
	@blevel				VARCHAR(100) = '',		--单位等级
	@isusebrandartype	BIT=0,					--是否启用品牌应收
	@skmonth			VARCHAR(10) = NULL,		--收款第几月
	@skday				VARCHAR(10) = NULL,		--收款第几日 
	@skdzdayflag		VARCHAR(10) = '0',		--按对账日期计算收款期限
	@fkmonth			VARCHAR(10) = NULL,		--付款第几月
	@fkday				VARCHAR(10) = NULL,		--付款第几日
	@fkdzdayflag		VARCHAR(10) = '0',		--按对账日期计算付款期限	
	@skcyjartime		VARCHAR(10) = '0',		--收款次月结
	@fkcyjaptime		VARCHAR(10) = '0'		--付款次月结	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @nReturntype INT,@EtypeId_1 [VARCHAR](50),@nSoncount INT,@nSonnum INT,@leveal smallINT

--判断是否为汽配
DECLARE @ifqp VARCHAR(1)
SET @ifqp=(SELECT subvalue FROM sysdata WHERE subname='ifqp')

DECLARE @parFullName VARCHAR(200)
SET @parFullName=(SELECT top 1 fullname FROM btype WHERE typeid=@parid)
DECLARE @typeName VARCHAR(20)
DECLARE @typeName2 VARCHAR(20)
IF substring(@parid,1,5)='00001'
BEGIN
	SET @typeName='客户'
	SET @typeName2='供货商'
END
IF substring(@parid,1,5)='00002'
BEGIN
	SET @typeName='供货商'
	SET @typeName2='客户'
END

-- 判断单位的往来
IF @Parid='00000'
RETURN -11

--能否分类判断
EXEC Gp_BaseInfoCheck 'btype',@parid,'0'

-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount OUT
IF @nReturntype=-1 
	BEGIN
		RAISERROR('客户和供货商的分类不能超过9层',16,1)RETURN-- RETURN -1
	END
IF @nReturntype=-2 
	BEGIN
		RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'curflag' AND SubValue = '1')
BEGIN
	RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
END	
-- 判断重复的ID,UserCode

IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (usercode=@usercode AND deleted<>1) )
	BEGIN
		RAISERROR('往来单位编号不能与已有的编号重复',16,1)RETURN--RETURN -3
	END
IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (fullname=@usercode AND deleted<>1) )
	BEGIN
		RAISERROR('往来单位编号不能与已有的名称重复',16,1)RETURN--RETURN -3
	END
	
DECLARE @eroFlag varchar(50)
select @eroFlag=value from Userconfig where ConfigName='equalItemname'
IF (@eroFlag=0)
begin
	IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (usercode=@FullName AND deleted<>1) )
	BEGIN
		RAISERROR('往来单位名称不能与已有的编号重复',16,1)RETURN--RETURN -3
	END
end	
else
begin
	IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (usercode=@usercode AND deleted<>1) )
	BEGIN
		RAISERROR('往来单位编号不能与已有的编号重复',16,1)RETURN--RETURN -3
	END
end
	
-----判断供货商和客户名称不能相同
DECLARE @otypename VARCHAR(50)
IF LEFT(@Parid,5)='00001'
	SET @otypename='供货商'
ELSE
	SET @otypename='客户'
IF EXISTS(SELECT TypeID FROM [btype] WHERE FullName=@FullName AND deleted<>1 AND LEFT(typeId,5)<>LEFT(@EtypeId_1,5) )
	BEGIN
		RAISERROR('%s的名称不能与已有%s的名称重复',16,1,@typeName,@otypename)RETURN--RETURN -3
	END


-- 判断重复的ID,UserCode
IF @eroFlag=0
BEGIN
	IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (usercode=@usercode AND deleted=1) OR (fullname=@fullname AND deleted=1))
	BEGIN
		RAISERROR('该【%s】的编号已被已停用的[%s]使用，请更换或删除该停用的编号',16,1,@FullName,@typeName)RETURN -31
	END
END
ELSE
BEGIN
	IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (usercode=@usercode AND deleted=1) )
	BEGIN
		RAISERROR('该【%s】的编号已被已停用的[%s]使用，请更换或删除该停用的编号',16,1,@FullName,@typeName)RETURN -31
	END
END

--IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (usercode=@usercode AND deleted=1) ) --OR (fullname=@fullname AND deleted=1)
--	BEGIN
--		RAISERROR('该【%s】的编号已被已停用的[%s]使用，请更换或删除该停用的编号',16,1,@FullName,@typeName)RETURN -31
--	END
IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (FullName=@usercode AND deleted=1) )
	BEGIN
		RAISERROR('%s编号不能与已停用的名称重复',16,1,@typeName)RETURN -101
	END
IF EXISTS(SELECT TypeID FROM [btype] WHERE typeId=@EtypeId_1 OR (UserCode=@FullName AND deleted=1) )
	BEGIN
		RAISERROR('%s名称不能与已停用的编号重复',16,1,@typeName)RETURN -101
	END
--IF EXISTS(SELECT TypeID FROM [btype] WHERE FullName=@FullName AND deleted=1 AND LEFT(typeId,5)<>LEFT(@EtypeId_1,5) )
--	BEGIN
--		RAISERROR('%s的名称不能与已停用的%s名称重复',16,1,@typeName,@otypename)RETURN--RETURN -3
--	END
	
			
DECLARE @returnPym VARCHAR(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

DECLARE @Ar00Temp  NUMERIC(24, 10) 
DECLARE @Ap00Temp  NUMERIC(24, 10) 
SET @Ar00Temp =0
SET @Ap00Temp =0

IF @Artotal00<>0 AND @Aptotal00<>0  -- 期初不应者都有
	RETURN 201
--IF EXISTS(SELECT Value FROM userconfig WHERE configName='Btypeall' AND Value='1')  -- 客户，供货商统一
	BEGIN
		IF LEFT(@EtypeId_1,5) ='00001' -- 客户
			BEGIN
				IF @Artotal00 >0 
					BEGIN
						SET @Ar00Temp = @Artotal00
						SET @Ap00Temp = 0
					END
				IF @Artotal00 <0 
					BEGIN
						SET @Ar00Temp = 0
						SET @Ap00Temp = abs(@Artotal00)
					END		
			END 
		ELSE  -- 供货商
			BEGIN
				IF @Aptotal00 >0 
					BEGIN
						SET @Ar00Temp = 0
						SET @Ap00Temp = @Aptotal00
					END
				IF @Aptotal00 <0 
					BEGIN
						SET @Ar00Temp = abs(@Aptotal00)
						SET @Ap00Temp = 0
					END	
			END
	END


BEGIN tran insertproc
SELECT @leveal=leveal FROM btype WHERE typeid=@Parid
SELECT @leveal=@leveal+1

--并发控制 ,判断typeid是否重复
IF EXISTS(SELECT TOP 1 1 FROM btype WHERE typeId=@EtypeId_1)
BEGIN
	RAISERROR('该【%s】已经存在，请重新保存',16,1,@FullName)
	RETURN
END
--961 需求 结算单位 清空
IF	@denominatedid=''
	SET @denominatedid=@EtypeId_1

IF EXISTS (SELECT * FROM sysdata WHERE subName='inicanmodify' AND subValue='T') AND @Artotal00<>-9123456789 AND @Aptotal00<>-9123456789-- 未开帐
INSERT INTO [btype] 
( 
	[typeId],
	[Parid],
	[leveal],
	[soncount],
	[sonnum],
	[FullName],
	[USERCODE],
	[Area],
	[TelAndAddress],
	[PostCode],
	[Name],
	[Person],
	[TaxNumber],
	[BankAndAcount],
	[ARTotal00],
	[APTotal00],
	[Comment],
	[Client],
	[ARLimitTime],
	[PaymentLTime],
	[Tel1],
	[Tel2],
	[Tel3],
	[WWW],
	[Email],
	[Fax],
	[Bank],
	[BankName],
	[LinkMan1],
	[LinkSex1],
	[LinkBirthDay1],
	[LinkJob1],
	[LinkCall1],
	[LinkTel1],
	[LinkMobile1],
	[LinkEMail1],
	[LinkPost1],
	[LinkAddress1],
	[LinkComment1],
	[LinkMan2],
	[LinkSex2],
	[LinkBirthDay2],
	[LinkJob2],
	[LinkCall2],
	[LinkTel2],
	[LinkMobile2],
	[LinkEMail2],
	[LinkPost2],
	[LinkAddress2],
	[LinkComment2],
	[CreateDate],
	[SaleZeKou],
	[BuyZeKou],
	[PyCode],
	[Price],
	[AreaTypeID],
	[etypeid],
	[buyprice],
	[consignee],
	[consigneetel], 
	[consigneeaddress],
	[cannotmodifyprice], 
	[denominatedid],
	[backlimitday],
    [backpercent],
    [Cid],
    [PriceTrackEnable],
    cqdays,
	chkskmonthday ,
	skmonthday ,
	chkfkmonthday ,
	fkmonthday ,
	dzdays ,
	dzwarningdays, 
	ckarlimittime ,
	ckpaymentltime ,
	fkcqdays ,     
	fkdzdays , 
	fkdzwarningdays,
	iscarrier,
	sheng,
	shi,
	xian,
	[blevel],
	isusebrandartype,
	skmonth,
	skday,
	skdzdayflag,
	fkmonth,
	fkday,
	fkdzdayflag,
	skcyjartime,
	fkcyjaptime
)VALUES( 
	@EtypeId_1,
	@Parid,
	@leveal,
	0,
	0,
	@FullName,
	@UserCode,
	@Area,
	@TelAndAddress,
	@PostCode,
	@Name,
	@Person,
	@TaxNumber,
	@bankandacount,
	@Ar00Temp,
	@Ap00Temp,
	@Comment,
	@Client,
	@ARLimitTime,
	@PaymentLTime,
	@Tel1,
	@Tel2,
	@Tel3,
	@WWW,
	@Email,
	@Fax,
	@Bank,
	@BankName,
	@LinkMan1,
	@LinkSex1,
	@LinkBirthDay1,
	@LinkJob1,
	@LinkCall1,
	@LinkTel1,
	@LinkMobile1,
	@LinkEMail1,
	@LinkPost1,
	@LinkAddress1,
	@LinkComment1,
	@LinkMan2,
	@LinkSex2,
	@LinkBirthDay2,
	@LinkJob2,
	@LinkCall2,
	@LinkTel2,
	@LinkMobile2,
	@LinkEMail2,
	@LinkPost2,
	@LinkAddress2,
	@LinkComment2,
	@CreateDate,
	dbo.F_RoundDiscount(@SaleZeKou),
	dbo.F_RoundDiscount(@BuyZeKou),
	@returnPym,
	@Price,
	@AreaTypeID,
	ISNULL(@etypeid,''),
	@buyprice,
	ISNULL(@consignee,''),
	ISNULL(@consigneetel,''),
	ISNULL(@consigneeaddress,''),
	dbo.F_RoundPrice(@valeditprice),
    @denominatedid,
    @backlimitday,
    @backpercent,
    @cid,
    @pricetrackenable,
    @cqdays,
	@chkskmonthday ,
	@skmonthday ,
	@chkfkmonthday ,
	@fkmonthday ,
	@dzdays ,
	@dzwarningdays ,
	@ckarlimittime ,
	@ckpaymentltime,
	@fkcqdays ,
	@fkdzdays ,
	@fkdzwarningdays ,
	@iscarrier,
	@sheng,
	@shi,
	@xian,
	@blevel,
	@isusebrandartype,
	@skmonth,
	@skday,
	@skdzdayflag,
	@fkmonth,
	@fkday,
	@fkdzdayflag,
	@skcyjartime,
	@fkcyjaptime
)
ELSE -- 已开帐
INSERT INTO [btype] 
( 
	[typeId],
	[Parid],
	[leveal],
	[soncount],
	[sonnum],
	[FullName],
	[USERCODE],
	[Area],
	[TelAndAddress],
	[PostCode],
	[Name],
	[Person],
	[TaxNumber],
	[BankAndAcount],
	[Comment],
	[Client],
	[ARLimitTime],
	[PaymentLTime],
	[Tel1],
	[Tel2],
	[Tel3],
	[WWW],
	[Email],
	[Fax],
	[Bank],
	[BankName],
	[LinkMan1],
	[LinkSex1],
	[LinkBirthDay1],
	[LinkJob1],
	[LinkCall1],
	[LinkTel1],
	[LinkMobile1],
	[LinkEMail1],
	[LinkPost1],
	[LinkAddress1],
	[LinkComment1],
	[LinkMan2],
	[LinkSex2],
	[LinkBirthDay2],
	[LinkJob2],
	[LinkCall2],
	[LinkTel2],
	[LinkMobile2],
	[LinkEMail2],
	[LinkPost2],
	[LinkAddress2],
	[LinkComment2],
	[CreateDate],
	[SaleZeKou],
	[BuyZeKou],
	[PyCode],
	[Price],
	[AreaTypeID],
	[etypeid],
	[buyprice],
	[consignee],
	[consigneetel], 
	[consigneeaddress],
	[cannotmodifyprice], 
    [denominatedid],
    [backlimitday],
    [backpercent],
    [Cid],
    [PriceTrackEnable],
    cqdays,
	chkskmonthday ,
	skmonthday ,
	chkfkmonthday ,
	fkmonthday ,
	dzdays ,
	dzwarningdays ,
	ckarlimittime ,
	ckpaymentltime ,
	fkcqdays  ,
	fkdzdays , 
	fkdzwarningdays, 
	iscarrier,
	sheng,
	shi,
	xian,
	blevel,
	isusebrandartype,
	skmonth,
	skday,
	skdzdayflag,
	fkmonth,
	fkday,
	fkdzdayflag,
	skcyjartime,
	fkcyjaptime
)VALUES( 
	@EtypeId_1,
	@Parid,
	@leveal,
	0,
	0,
	@FullName,
	@UserCode,
	@Area,
	@TelAndAddress,
	@PostCode,
	@Name,
	@Person,
	@TaxNumber,
	@bankandacount,
	@Comment,
	@Client,
	@ARLimitTime,
	@PaymentLTime,
	@Tel1,
	@Tel2,
	@Tel3,
	@WWW,
	@Email,
	@Fax,
	@Bank,
	@BankName,
	@LinkMan1,
	@LinkSex1,
	@LinkBirthDay1,
	@LinkJob1,
	@LinkCall1,
	@LinkTel1,
	@LinkMobile1,
	@LinkEMail1,
	@LinkPost1,
	@LinkAddress1,
	@LinkComment1,
	@LinkMan2,
	@LinkSex2,
	@LinkBirthDay2,
	@LinkJob2,
	@LinkCall2,
	@LinkTel2,
	@LinkMobile2,
	@LinkEMail2,
	@LinkPost2,
	@LinkAddress2,
	@LinkComment2,
	@CreateDate,
	dbo.F_RoundDiscount(@SaleZeKou),
	dbo.F_RoundDiscount(@BuyZeKou),
	@returnPym,
	@Price,
	@AreaTypeID,
	ISNULL(@etypeid,''),
	@buyprice,
	ISNULL(@consignee,''),
	ISNULL(@consigneetel,''),
	ISNULL(@consigneeaddress,''),
	dbo.F_RoundPrice(@valeditprice), 
    @denominatedid,
    @backlimitday,
    @backpercent,
    @cid,
    @pricetrackenable,
    @cqdays,
	@chkskmonthday ,
	@skmonthday ,
	@chkfkmonthday ,
	@fkmonthday ,
	@dzdays ,
	@dzwarningdays ,
	@ckarlimittime,
	@ckpaymentltime,
	@fkcqdays ,
	@fkdzdays ,
	@fkdzwarningdays,
	@iscarrier,
	@sheng,
	@shi,
	@xian,
	@blevel,
	@isusebrandartype,
	@skmonth,
	@skday,
	@skdzdayflag,
	@fkmonth,
	@fkday,
	@fkdzdayflag,
	@skcyjartime,
	@fkcyjaptime
)

IF @@rowcount=0 
	BEGIN
	 rollback tran insertproc 
	 RETURN RAISERROR('客户和供货商档案不能超过9层',16,1)--RETURN-1
	END 
else 
	BEGIN
	--客户关联了信用额度管理，则该客户可以被分类和删除，同时信用额度中该客户的信用额度记录删除了
	IF EXISTS(SELECT btypeid FROM btype_credit WHERE BtypeId=@Parid) 	
		BEGIN 
			Delete FROM btype_credit WHERE BtypeId=@Parid 
		END
	 update [btype]
	 SET sonnum=@nSonnum+1,soncount=@nSoncount+1
	 WHERE typeid=@Parid
	END

IF (@nReturnType <> 0)
BEGIN 
 rollback tran insertproc 
 RETURN @nReturnType 
END

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM BType
UPDATE BType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

commit tran insertproc


GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

















/****** Object:  Stored Procedure dbo.Gp_InsertB    Script Date: 2002-6-20 10:14:48 ******/




CREATE   PROCEDURE Gp_InsertB_CORP
(
 @Parid   [varchar](50),
 @DbName         [varchar](30),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @Name  [Varchar](30), 
 @Area  [Varchar](30),
 @TelAndAddress  [varchar](66),
 @PostCode  [varchar](10),
 @Person  [varchar](20),
 @TaxNumber  [varchar](20),
 @Bank [varchar](50),
 @Account  [varchar](66),
 @Artotal00  NUMERIC(24, 10) ,
 @Aptotal00    NUMERIC(24, 10) ,
 @Comment  [varchar](256),
 @Client [Bit]=1,
 @ARLimit  NUMERIC(24, 10) =0
)
--@encode$--
AS
SET NOCOUNT ON
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint
-- 判断单位的往来
if exists(select typeid from [btype] where typeid=@parid and ARTotal-ApTotal<>0)
begin
	--print '['+@FullName+']单位往来帐不为零，不能分类'
	return -7
end 
if exists(select typeid from [btype] where typeid=@parid and ARTotal00-ApTotal00<>0)
begin
	--print '['+@FullName+']单位往来帐不为零，不能分类'
	return -7
end 


-- 判断借欠余额
if exists(select bTypeID from V_LendStatus where bTypeID=@parid and Qty<>0)
begin
	--print '['+@FullName+']单位有借进借出，不能分类'
	return -5
end 
-- 判断经营
if exists(select bTypeID from listtable where bTypeID=@parid )
   or exists(select bTypeID from LendIndex where bTypeID=@parid and totalQty<>0)
begin
	--print '['+@FullName+']单位已经经营过，不能分类'
	return -6
end 
-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 return -1
if @nReturntype=-2 return -2
-- 判断重复的ID,UserCode
if exists(select TypeID from [btype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
begin
	--print '['+@usercode+']往来已存在'
	return -3
end

begin tran insertproc
select @leveal=leveal from btype where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO [btype] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [USERCODE],
  [Area],
  [TelAndAddress],
  [PostCode],
  [Name],
  [Person],
  [TaxNumber],
  [Bank],
  [BankAndAcount],
  [ARTotal00],
  [APTotal00],
  [Comment],
  [Client],
  [ARLimit]
) 
 
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Area,
  @TelAndAddress,
  @PostCode,
  @Name,
  @Person,
  @TaxNumber,
  @Bank,
  @Account,
  @Artotal00,
  @ApTotal00,
  @Comment,
  @Client,
  @ARLimit
)
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [btype]
 set sonnum=@nSonnum+1,soncount=@nSoncount+1
 where typeid=@Parid
end
-- 建立Employee数据 .超级用户的节点 --
--select @UserCode=@UserCode+'_超级用户'
--exec @nReturnType=Gp_InsertE '00000','employee',@UserCode,'超级用户','','','','',@EtypeId_1
if (@nReturnType <> 0)
begin 
 rollback tran insertproc 
 return @nReturnType 
end
commit tran insertproc










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*

*/
CREATE       PROCEDURE Gp_InsertBackingbill
(
	@BillNumberID			[numeric](10,0),
	@backingoutreason		varchar(2000),
	@backingoutcheck		varchar(2000),
	@backingoutresult		varchar(2000),
	@backingoutstate		int,
	@stypeid				varchar(100)		
)
--@encode$--
AS 
SET NOCOUNT ON

IF @backingoutstate=1
begin
		IF NOT EXISTS (SELECT	TOP 1 1 FROM	SType_UserConfig  WHERE	ConfigNo = 1 AND Value = 1	AND STypeID=@stypeid  )
		begin
			RETURN 3	-- 没有开帐不允许过帐
		end
end

	insert into Qp_BackingOut_Bill(backingoutreason,backingoutcheck,backingoutresult,billnumberid,backingoutstate) 
							values(@backingoutreason,@backingoutcheck,@backingoutresult,@billnumberid,@backingoutstate)

	if @@rowcount=0 return -1 else return 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
维修结算单_-配件明细表（写的是Qp_ReceptionBill_FactUsePType）
*/
CREATE       PROCEDURE GP_InsertBalanceBill_PType
(
	@BillNumberID					numeric(18,0),
	@PTypeID						varchar(50),
	@ID								numeric(18,0),
	@Qty							 NUMERIC(24, 10) ,
	@Price							 NUMERIC(24, 10) ,
	@Total							 NUMERIC(24, 10) ,
	@Discount						 NUMERIC(24, 10) ,
	@DiscountPrice					 NUMERIC(24, 10) ,
	@DiscountTotal					 NUMERIC(24, 10) ,
	@Comment						varchar(500),
	@Insurance						INT,
	@Virtual						INT
)
--@encode$--
AS 
SET NOCOUNT ON



--对于非虚增的配件，要保存

IF @Virtual=1
BEGIN
	INSERT Qp_ReceptionBill_PType(BillNumberId,PTypeID,Qty,Price,Total,Discount,DiscountPrice,DiscountTotal,Insurance,Comment,Virtual)
	VALUES(@BillNumberId
		  ,@PTypeID
		  ,dbo.F_RoundQty(@Qty)
		  ,dbo.F_RoundPrice(@Price)
		  ,dbo.F_RoundTotal(@Total)
		  ,dbo.F_RoundDiscount(@Discount)
		  ,dbo.F_RoundPrice(@DiscountPrice)
		  ,dbo.F_RoundTotal(@DiscountTotal)
		  ,@Insurance
		  ,@Comment
		  ,@Virtual)
	
	SET @ID=SCOPE_IDENTITY();
	
	DECLARE 
		@ETypeID		VARCHAR(50)
		
	SELECT @ETypeID=ETypeID
	FROM BillIndex
	WHERE BillNumberId=@BillNumberID
	
	INSERT Qp_ReceptionBill_FactUsePType(BillNumberId,PickingID,ReceptionBillnumberId,ReceptionBillPTypeId,PTypeID,Qty,Price,Total,Insurance,CostTotal,ETypeID,Discount,DiscountPrice,DiscountTotal,Comment,Virtual)
	VALUES(0,
		   0,
		   @BillNumberId,
		   @ID,
		   @PTypeID,
		   dbo.F_RoundQty(@Qty),
		   dbo.F_RoundPrice(@Price),
		   dbo.F_RoundTotal(@Total),
		   @Insurance,
		   0,
		   @ETypeID,
		   dbo.F_RoundDiscount(@Discount),
		   dbo.F_RoundPrice(@DiscountPrice),
		   dbo.F_RoundTotal(@DiscountTotal),
		   @Comment,
		   1)
END
ELSE
BEGIN
	UPDATE Qp_ReceptionBill_FactUsePType
	SET 
		Qty=dbo.F_RoundQty(@Qty),
		Price=dbo.F_RoundPrice(@Price),
		Total=dbo.F_RoundTotal(@Total),
		Discount=dbo.F_RoundDiscount(@Discount),
		DiscountPrice=dbo.F_RoundPrice(@DiscountPrice),
		DiscountTotal=dbo.F_RoundTotal(@DiscountTotal),
		Comment=@Comment,
		Insurance=@Insurance,
		Virtual=@Virtual
	WHERE ID=@ID
	
	
END

if @@rowcount=0 return -1 else return 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_INSERTBaseSyncInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Gp_INSERTBaseSyncInfo]
GO

/*
	作者：谢吉康
	日期：2018-10-15
	描述：写入同步信息
*/
CREATE PROCEDURE Gp_InsertBaseSyncInfo
(
	@usercode		VARCHAR(500),			--编号
	@flag			VARCHAR(10),			--修改标识
	@wmsid			VARCHAR(100),			--WMS标识
	@wmsfullname	VARCHAR(500),			--WMS名称
	@wmsusercode	VARCHAR(500),			--WMS编号
	@skuid			VARCHAR(100) = '',		--商品SKUID
	@wmsunit1		VARCHAR(10) = '1',		--单位
	@wmsprop1name	VARCHAR(200) = '',		--属性1
	@wmsprop2name	VARCHAR(200) = '',		--属性1
	@tablename		VARCHAR(100)			--基本信息类型
)
AS
SET NOCOUNT ON

IF @tablename = 'ptype'
BEGIN
	UPDATE ptype SET iswmssync = @flag WHERE usercode = @usercode

	--没有自由项的商品
	IF @wmsprop1name = ''
	BEGIN
		INSERT INTO WmsErpPtypeContrastSetting
		(
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			WMS_SKUID,
			WMS_Unit1,
			WMS_Prop1Name,
			WMS_Prop2Name,
			erp_customitemfrom,
			erp_customitemid,
			ERP_TypeId,
			ERP_SKUId,
			nType
		)
		SELECT  @wmsid,
				@wmsusercode,
				@wmsfullname,
				@skuid,
				@wmsunit1,  
				@wmsprop1name,
				@wmsprop2name,      
				CustomItemFrom,
				customitemid,                            
				typeid,
				0,
				1
		FROM    ptype
		WHERE   usercode = @usercode
	END
	ELSE
	BEGIN
		DECLARE @id INT
		
		CREATE TABLE #GetCustomInfo
		(
			customitemid	INT,
			customitemfom	INT,
			entrycode		VARCHAR(200),
			itemid			VARCHAR(100),
			iscombined		INT,
			fullname		VARCHAR(500),
			id				INT,
			datatypeid		INT
		)
		INSERT INTO #GetCustomInfo
		(
			customitemid,
			customitemfom,
			entrycode,
			itemid,
			iscombined,
			fullname,
			id,
			datatypeid
		)
		EXEC Web_QueryCustomInfoFromPtypeUserCode @usercode

		SELECT @id = id FROM #GetCustomInfo WHERE fullname = @wmsprop1name
		
		INSERT INTO WmsErpPtypeContrastSetting
		(
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			WMS_SKUID,
			WMS_Unit1,
			WMS_Prop1Name,
			WMS_Prop2Name,
			erp_customitemfrom,
			erp_customitemid,
			ERP_SKUId,
			ERP_TypeId,
			nType
		)
		SELECT  @wmsid,
				@wmsusercode,
				@wmsfullname,
				@skuid,
				@wmsunit1,  
				@wmsprop1name,
				@wmsprop2name,      
				CustomItemFrom,
				customitemid,  
				@id,                          
				typeid,
				1
		FROM    ptype
		WHERE   usercode = @usercode

		DROP TABLE #GetCustomInfo
	END
END
ELSE IF @tablename = 'btype'
BEGIN
	UPDATE btype SET iswmssync = @flag WHERE usercode = @usercode
	
    INSERT INTO WmsErpBTypeContrastSetting
    (
        WMS_TypeId,
        WMS_UserCode,
        WMS_FullName,
        ERP_TypeId
    )
    SELECT  @wmsid,            
            @wmsusercode,
            @wmsfullname,
            typeid
    FROM    btype
    WHERE   usercode = @usercode
END
ELSE IF @tablename = 'employee'
BEGIN
	UPDATE employee SET iswmssync = @flag WHERE usercode = @usercode
	
	INSERT INTO WmsErpEmployeeContrastSetting
	(
		WMS_TypeId,
		WMS_UserCode,
		WMS_FullName,
		ERP_TypeId
	)
	SELECT  @wmsid,			
			@wmsusercode,
			@wmsfullname,
			typeid
	FROM    employee
	WHERE   usercode = @usercode
END
ELSE IF @tablename = 'stock'
BEGIN
	UPDATE stock SET iswmssync = @flag WHERE usercode = @usercode
    INSERT INTO WmsErpStockContrastSetting
    (
        WMS_TypeId,
        WMS_UserCode,
        WMS_FullName,
        ERP_TypeId
    )
    SELECT  @wmsid,            
            @wmsusercode,
            @wmsfullname,
            typeid
    FROM    stock
    WHERE   usercode = @usercode
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertBillIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--**********************************************
--存储过程修改记录
--1.修改原因:a.增加过帐时根据配置判断是否允许过帐日期与当前日期不一致的问题 b.增加ID字段用于物理顺序
--2.修改方法:增加
--3.结果:成功
--4.修改人:肖伟
--5.LAST修改时间:2002-10-28
--**********************************************
CREATE  PROCEDURE [Gp_InsertBillIndex]
    (
      @BillDate [datetime] ,
      @BillCode [varchar](200) ,  -- #&**&#
      @BillType [numeric](4, 0) ,
      @Comment [varchar](2000) ,
      @AtypeId [varchar](50) ,
      @PtypeId [varchar](50) ,
      @BtypeId [varchar](50) ,
      @EtypeId [varchar](50) ,
      @KtypeId [varchar](50) ,
      @KtypeId2 [varchar](50) ,
      @IfCheck [char](1) ,
      @CheckE [varchar](50) ,
      @TotalMoney  NUMERIC(24, 10)  ,
      @TotalQty  NUMERIC(24, 10)  ,
      @TotalInMoney  NUMERIC(24, 10)  ,
      @Tax  NUMERIC(24, 10)  ,
      @szPeriod [SMALLINT] ,
      @Explain [varchar](2000) ,
      @Draft [bit] ,
      @RedWord [bit] ,
      @OrderId [numeric] = 0 ,
	--添加新的参数
      @WayBillCode VARCHAR(50) = NULL ,
      @Goodsnumber VARCHAR(20) = NULL ,
      @PackWay VARCHAR(20) = NULL ,
      @Tel VARCHAR(100) = NULL , --100个字符 【司华山 2015-04-03】
      @preferencemoney  NUMERIC(24, 10)  = 0 ,		--优惠金额【谢吉康 2004-07-16】
      @AlertDay INT = 9999 ,				--收款期限 
      @Assessor VARCHAR(50) = NULL ,
      @IfAudit CHAR(1) = '3' ,
      @Audit_explain VARCHAR(256) = NULL ,
      @DtypeId VARCHAR(50) = '' ,		--分支机构ID
      @VipCardID INT = -1 ,				-- VIP卡的唯一ID值
      @KTypeID3 VARCHAR(50) = '' ,	-- 表头第三个仓库，目前用于新维修的自行维修单
      @LinkMan VARCHAR(256) = '' ,	-- 新维修(接件单) - 联系人
      @LinkTel VARCHAR(256) = '' ,	-- 新维修(接件单) - 联系电话
      @LinkAddr VARCHAR(256) = '' ,	-- 新维修(接件单) - 联系地址
      @wxManID VARCHAR(50) = '' ,	-- 新维修(维修单、上门维修单) - 维修人ID
      @JieJianBillNumberID VARCHAR(200) = '' ,	-- 新维修 - 接件单的BillNumberID
      @JieJianID VARCHAR(200) = '' ,	-- 新维修 - 接件单对应商品明细行的物理顺序ID
      @BaoXiuBillNumberID VARCHAR(200) = '' ,	-- 新维修 - 报修单的BillNumberID
      @BaoXiuID VARCHAR(200) = '' ,	-- 新维修 - 报修单对应商品明细行的物理顺序ID
      @BuyDate VARCHAR(50) = '' ,	-- 新维修(接件单) - 购买日期
      @Serial VARCHAR(200) = '' ,	-- 新维修 - 序列号
      @wxTotal  NUMERIC(24, 10)  = 0 ,	-- 新维修(表尾) - 维修费用、换机费用
      @ErrDes VARCHAR(3000) = '' ,	-- 新维修 - 故障描述
      @ifHideJieJian INT = 0 ,			-- 新维修 - 是否隐藏接件详情，0：不隐藏；1：隐藏
      @ifWX INT = 0 ,			-- 是否针对维修库存进行盘点、报损、报溢；0：正常库，1：维修库
      @IfBargainOn INT = 0 ,				--询价单、报价单成交标志 0：未成交  1：成交
      @STypeID VARCHAR(50) = '' ,
      @FromBillNumberID NUMERIC(10, 0) = 0 ,
      @CostSale BIT = 0 ,
      @completedate DATETIME ,			--预计完成
      @billstate INT ,				--单据状态
      @ifmulaccount INT ,				--是否多账户收款
      @vipczmoney  NUMERIC(24, 10)  ,		--会员卡充值前金额
      @otherinouttype INT ,					--其他出入库单业务类别
      @czbeforetimes  NUMERIC(24, 10)  ,		  --会员卡充值前次数
      @PosBillType INT ,
      @TransportId VARCHAR(10) ,
      @IsFreightMoney INT ,
      @FreightAddr VARCHAR(300) ,
      @FreightPerson VARCHAR(100) ,
      @FreightTel VARCHAR(100) ,
      @ShareMode TINYINT ,			--摊销方式
      @uf1 VARCHAR(200) = '' ,		--自定义表头字段
      @uf2 VARCHAR(200) = '' ,
      @uf3 VARCHAR(200) = '' ,
      @uf4 VARCHAR(200) = '' ,
      @uf5 VARCHAR(200) = '' ,
	--9.0新字段
      @DEALBTYPEID VARCHAR(50) ,		--结算单位
      @cid INT ,				--外币币种ID
      @rate  NUMERIC(24, 10)  ,		--汇率
      @ntotalmoney MONEY ,				--原币总金额
      @ntotalinmoney MONEY ,				--原币收现金额
      @npreferencemoney MONEY ,				--原币优惠金额
      @nvipczmoney MONEY ,				--原币会员卡充值金额
      @atypeid1 VARCHAR(50) ,		--往来科目
      @billproperty INT ,					--单据属性
      @ncompletetotal  NUMERIC(24, 10)  ,		--原币结算金额
      @isini BIT ,
      @ATID INT ,
      @completetotal  NUMERIC(24, 10)  ,
      @IfCargo BIT ,
      @IfInvoice INT ,
      @invoicemoney  NUMERIC(24, 10)  = 0 ,
      @ninvoicemoney  NUMERIC(24, 10)  = 0,
      @importtype TINYINT=0,
      @AssetBusinessTypeId  int=0,
      @promoruleid	int,
	  @beforepromobillnumberid int,
	  @promotionmsg NVARCHAR(500)='',
	  @STypeID2 VARCHAR(50)='',
	  @ifconfirm int=0,
	  @FeeDeductType int=0,
	  @TransferType int=1,
	  @isyapi INT=0,
	  @yapiorderid VARCHAR(20)='0',
	  @DeliveryAddress VARCHAR(256)= '' ,
	  @Discount  NUMERIC(24, 10) =1,
	  @AdpriceType INT=0,
	  @checkSave varchar(128)='',
	  @chargeoffbtypeid VARCHAR(50)='',
	  @chargeofftype INT=0,
	  @chargeofftotal NUMERIC(24, 10)=0 ,
	  @nchargeofftotal NUMERIC(24, 10)=0,
	  @IsLend int = 0,
	  @WarehouseOutDay INT = 9999,--出库期限 
	  @StockInDeadline INT = 9999,--入库期限 
	  @IsNeedTransport BIT=0,--是否需要运输配送
	  @iscombinationstyle INT = 0,
	  @transporterid VARCHAR(50)='0',
	  @transporterfullname varchar(200)	='',
	  @shipperfullname varchar(100)	='',
	  @shipperperson varchar(100)='',
	  @shippertel varchar(100)='',
	  @transportno VARCHAR(200)='',
	  @totalfreight NUMERIC(24,10)=0,
	  @ntotalfreight NUMERIC(24,10)=0,
	  @PromonIds	VARCHAR(1000)='',  --促销方案id
	  @isByBrandarType INT=0,
	  @NewPosBill INT=0, --pos上传单据标志
	  @PayOnTheSpot	INT = 0, --当面付
	  @posid INT = 0,
	  @YjkBillCode VARCHAR(200)=''	--易居客 订单编号
	  )
--@encode$--
AS 
SET NOCOUNT ON


/*
	--********软件安全相关处理**********	
	DECLARE @ProInfoname VARCHAR(6)
	SELECT @ProInfoname = CASE SubValue WHEN  '1' THEN 'V3' WHEN '2' THEN 'A8' WHEN '4' THEN 'V1' ELSE '' END FROM dbo.sysdata WHERE SubName = 'ProInfo'
	IF EXISTS(SELECT TOP 1 1 FROM  sysdatadb..rwxsysadmin WHERE [Version] = @ProInfoname AND rgday <> 99999)
	BEGIN			
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ControlFlag' AND SubValue = 'ssct')
		BEGIN
			RETURN -99
		END
			
		DECLARE @roundN INT
				,@NetLevel INT
				,@DiffDay INT
		SELECT @DiffDay = DATEDIFF(DAY,SubValue,GETDATE()) FROM sysdata WHERE SubName = 'PassVchCheck'
		
		IF @importtype = 0 AND @BillType IN (11,34) AND @DiffDay > 90 AND EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @STypeID)
			RETURN -98
		
		SELECT @roundN = CAST(RAND()*100 as INT)
		SELECT @NetLevel = CAST( SubValue AS INT) FROM sysdata WHERE SubName = 'NetLevel'
		IF @roundN > @NetLevel AND EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @STypeID)
			RETURN -97
			
		UPDATE sysdata SET SubComment = @roundN WHERE SubName = 'NetLevel' 
	END
*/	
	--********软件安全相关处理end**********	
	

-- ********	判断是否试用版 - Start	********
    DECLARE @N INT ,
			@intVersion INT

-- 判断版本号，是否试用版
    SELECT  @N = CAST(SubValue AS INT)
    FROM    SysData1
    WHERE   SubNo = 2	-- 版本号

	IF @N IS NULL RETURN -1
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 6 AND SubValue = '1')
		AND (EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 10 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 9 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 11 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 13 AND ISNULL(SubValue,'') = ''))		 
	RETURN -3	

    DECLARE @intBit INT ,
        @intMask INT
    SELECT  @intBit = @N & 15
    SELECT  @intMask = POWER(2, @intBit) ^ POWER(2, @intBit + 1) ^ POWER(2,
                                                              @intBit + 2)
            ^ POWER(2, @intBit + 3) ^ POWER(2, @intBit + 4) ^ POWER(2,
                                                              @intBit + 5)
    SELECT  @intVersion = ( @intMask & @N ) / POWER(2, @intBit)
-- ********	判断是否试用版 - END	********

    DECLARE @Re INT ,
        @Flag INT
    EXEC @Re= Gp_Validate 2, @Flag OUTPUT
    IF @Re <> 0 
        RETURN -3 --检查程序版本错误

    IF @intVersion NOT IN ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                            15 ) 
        BEGIN
	--RAISERROR('校验错误 ！',16,1) 
            RETURN -3 --检查程序版本错误
        END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @billnumberid >= 200
	BEGIN
		--RAISERROR('试用版最多录200条单据 ！',16,1) 
		RETURN -1
	END
END  

    DECLARE @BeginDate DATETIME ,
        @szItem VARCHAR(30) ,
        @szVchCode VARCHAR(30)
        
    --EXEC Gp_GetSubValue 'period', @STypeID, @szPeriod OUT
    SELECT TOP 1
            @BeginDate = startdate
    FROM    monthproc
    WHERE   MonthNo='本期' AND STypeID=@STypeID
    
    --EXEC @re = Gp_Fz_Base '',2
    --IF @re <> 0 RETURN -2

/*
IF EXISTS(SELECT TOP 1 1 FROM  sysdatadb..rwxsysadmin WHERE [Version] = @ProInfoname AND rgday <> 99999)
BEGIN			
	--验证数据是否已经被控制
	--此处不做数据清理，放在C++中进行数据清理
	DECLARE @isControl varchar(10)
	SET @isControl=''
	SELECT @isControl=subvalue FROM SYSDATA WHERE subname='ControlFlag'
	IF @isControl = 'ssct'
	BEGIN
		RETURN -100
	END
	--验证数据是否允许执行保存   
	IF @checkSave='check_account_num_err'
	BEGIN
		RETURN -102
	END
	IF @checkSave<>'bill_allow_save' AND @BillType IN (4,11)
	BEGIN
		RETURN -101
	END
	ELSE
	BEGIN
		--bill_unsave
		UPDATE sysdata1 SET subvalue=N'`ljk_vlvgqe' WHERE subname='BillSaveCheck'
	END
END	
*/
--DECLARE
	--@intNeed TINYINT


--去掉195号汽配单据@billstate判断
--IF @BillType=195 AND @billstate=3
--BEGIN
--	SELECT @intNeed=1
--END
--ELSE
--BEGIN
	--SELECT @intNeed=0
--END
	


--询价, 报价单
    IF @BillType NOT IN ( 184, 185 ) --AND @intNeed=0
        BEGIN
            IF @isini = 1 
            BEGIN
				--增加独立开账期初时间判断
				DECLARE @iniBegindate DATETIME  --取会计期间开始时间
				IF NOT EXISTS(SELECT TOP 1 1  FROM dbo.sysdata WHERE SubName='stypeindependentopen' AND SubValue=1)
				BEGIN
					SELECT @iniBegindate=fBegin FROM dbo.Ac_Period 
					WHERE FYear IN (SELECT subvalue FROM dbo.sysdata WHERE subname ='fyear' ) AND FPeriod IN (SELECT subvalue FROM dbo.sysdata WHERE SubName='fmonth')
				END
				ELSE
				BEGIN
					SELECT @iniBeginDate=fbegin FROM dbo.Ac_Period A,dbo.SType_UserConfig B
					WHERE A.FPeriod=b.SFPeriod AND A.FYear=B.SFYear AND B.StypeId= @STypeID
				END
				IF @billdate >= @iniBegindate 
					RETURN -8
			END
            IF @BillDate < @BeginDate
                AND @isini = 0 AND @BillType<>310 --资金调拨单不验证录单日期小于本期开始日期
                BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
                    RETURN -2
                END
                
	---根据配置检查过帐日期是否当前日期  开始 如果单据没有审核流程才判断,如果有审核流程,则在审核流程中判断 谢吉康 2004-06-14
            IF ( @isini = 0 AND @importtype=0) 
                BEGIN	
                    IF NOT EXISTS ( SELECT TOP 1
                                            1
                                    FROM    AuditingFlowSet
                                    WHERE   BillType = @BillType
                                            AND IfUse = 1
                                            AND LEFT(AuditingReason, 1) <> 1 )	--检查单据是否有审核流程
                        BEGIN
                            DECLARE @CurDate DATETIME
                            DECLARE @IsOrNotPassOneDay BIT
                            SELECT  @CurDate = GETDATE()
                            SELECT TOP 1
                                    @IsOrNotPassOneDay = value
                            FROM    UserConfig
                            WHERE   ConfigName = 'PassOneDay'
                            IF ( CONVERT(DATETIME, @BillDate) <> CONVERT(DATETIME, CONVERT(VARCHAR, YEAR(@CurDate))
                                 + '-' + CONVERT(VARCHAR, MONTH(@CurDate))
                                 + '-' + CONVERT(VARCHAR, DAY(@CurDate))) )
                                AND ( @IsOrNotPassOneDay = 1 ) 
                                BEGIN 
				--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
                                    RETURN -4
                                END
                        END
		--有审核流程单据，第一次录单时需要和当前日期一致
                    ELSE 
                        BEGIN
                            SELECT  @CurDate = GETDATE()
                            SELECT TOP 1
                                    @IsOrNotPassOneDay = value
                            FROM    UserConfig
                            WHERE   ConfigName = 'PassOneDay'
                            IF ( CONVERT(DATETIME, @BillDate) <> CONVERT(DATETIME, CONVERT(VARCHAR, YEAR(@CurDate))
                                 + '-' + CONVERT(VARCHAR, MONTH(@CurDate))
                                 + '-' + CONVERT(VARCHAR, DAY(@CurDate))) )
                                AND ( @IsOrNotPassOneDay = 1 ) 
                                BEGIN 
				--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
                                    RETURN -4
                                END
                        END
                END	
	---根据配置检查过帐日期是否当前日期  完毕
        END
        
	--收款单业务草稿导入的时候用
	--IF(@BillType = 4 AND EXISTS(SELECT * FROM dbo.sysdata WHERE SubName =  'usebrandartype' AND SubValue = 1))
	--BEGIN
	--	SET @isbybrandartype = 1
	--END 
    INSERT  INTO [dbo].[BillIndex]
            ( [vipczmoney] ,
              [BillDate] ,
              [BillCode] ,
              [BillType] ,
              [Comment] ,
              [atypeid] ,
              [ptypeid] ,
              [btypeid] ,
              [etypeid] ,
              [ktypeid] ,
              [ktypeid2] ,
              [ifcheck] ,
              [checke] ,
              [totalqty] ,
              [totalmoney] ,
              [totalinmoney] ,
              [tax] ,
              [period] ,
              [explain] ,
              [draft] ,
              [RedWord] ,
              [orderid] ,
              [waybillcode] ,
              [goodsnumber] ,
              [packway] ,
              [Tel] ,
              [preferencemoney] ,
              [AlertDay] ,
              [ID] ,
              [Assessor] ,
              [IfAudit] ,
              [Audit_explain] ,
              [DtypeId] ,
              [VipCardID] ,
              [KTypeID3] ,
              [LinkMan] ,
              [LinkTel] ,
              [LinkAddr] ,
              [wxManID] ,
              [JieJianBillNumberID] ,
              [JieJianID] ,
              [BaoXiuBillNumberID] ,
              [BaoXiuID] ,
              [BuyDate] ,
              [Serial] ,
              [wxTotal] ,
              [ErrDes] ,
              [ifHideJieJian] ,
              [ifWX] ,
              [IfBargainOn] ,
              [Stypeid] ,
              [FromBillNumberID] ,
              [CostSale] ,
              [ifmulaccount] ,
              otherinouttype ,
              PosBillType ,
              checkTime ,
              LastUpdateTime ,
              ShareMode ,
              TransportId ,
              IsFreightMoney ,
              FreightAddr ,
              FreightPerson ,
              FreightTel ,
              uf1 ,
              uf2 ,
              uf3 ,
              uf4 ,
              uf5 ,
              DEALBTYPEID ,
              cid ,
              rate ,
              ntotalmoney ,
              ntotalinmoney ,
              npreferencemoney ,
              nvipczmoney ,
              atypeid1 ,
              billproperty ,
              ncompletetotal ,
              isini ,
              ATID ,
              CompleteTotal ,
              IfCargo ,
              IfInvoice ,
              invoicemoney ,
              ninvoicemoney,
              importtype,
              AssetBusinessTypeId,
              PromoRuleId,
              BeforePromoBillNumberId,
              promotionmsg,
              StypeID2,
              IfConfirm,
              FeeDeductType,
              TransferType,
              isyapi,
              yapiorderid,
              DeliveryAddress,
              BillTime,
              Discount,
              AdPriceType,
              chargeoffbtypeid,
              chargeofftype,
              ChargeOffTotal,
              NChargeOffTotal,
              islend,
              transportno,
              WarehouseOutDay,
              StockInDeadline,
              IsNeedTransport,
              iscombinationstyle,
              Transporterid,
              Transporterfullname,
              shipperfullname,
              shipperperson,
              shippertel,
			  totalfreight,
			  ntotalfreight,
			  PromonIds,
			  isByBrandarType,
			  NewPosBill,
			  PayOnTheSpot,
			  posid,
			  YjkBillCode
            )
    VALUES  ( @vipczmoney ,
              @BillDate ,
              @BillCode ,
              @BillType ,
              @Comment ,
              @atypeid ,
              @ptypeid ,
              @btypeid ,
              @etypeid ,
              @ktypeid ,
              @ktypeid2 ,
              @ifcheck ,
              @checke ,
              dbo.F_RoundQty(@totalqty) ,
              dbo.F_RoundTotal(@totalmoney) ,
              dbo.F_RoundTotal(@totalinmoney) ,
              dbo.F_RoundTax(@tax) ,
              @szPeriod ,
              @explain ,
              @draft ,
              @redword ,
              @orderID ,
              @waybillcode ,
              @goodsnumber ,
              @packway ,
              @Tel ,
              dbo.F_RoundTotal(@preferencemoney) ,
              @AlertDay ,
              0 ,
              @Assessor ,
              @IfAudit ,
              @Audit_explain ,
              @DtypeId ,
              @VipCardID ,
              @KTypeID3 ,
              @LinkMan ,
              @LinkTel ,
              @LinkAddr ,
              @wxManID ,
              @JieJianBillNumberID ,
              @JieJianID ,
              @BaoXiuBillNumberID ,
              @BaoXiuID ,
              @BuyDate ,
              @Serial ,
              dbo.F_RoundTotal(@wxTotal) ,
              @ErrDes ,
              @ifHideJieJian ,
              @ifWX ,
              @IfBargainOn ,
              @Stypeid ,
              @FromBillNumberID ,
              @CostSale ,
              @ifmulaccount ,
              @otherinouttype ,
              @PosBillType ,
              GETDATE() ,
              NULL ,
              @ShareMode ,
              @TransportId ,
              @IsFreightMoney,
              @FreightAddr ,
              @FreightPerson ,
              @FreightTel ,
              @uf1 ,
              @uf2 ,
              @uf3 ,
              @uf4 ,
              @uf5 ,
              @DEALBTYPEID ,
              @cid ,
              dbo.F_RoundExchangeRate(@rate) ,
              dbo.F_RoundTotal(@ntotalmoney) ,
              dbo.F_RoundTotal(@ntotalinmoney) ,
              dbo.F_RoundTotal(@npreferencemoney) ,
              dbo.F_RoundTotal(@nvipczmoney) ,
              @atypeid1 ,
              @billproperty ,
              dbo.F_RoundTotal(@ncompletetotal) ,
              @isini ,
              @ATID ,
              dbo.F_RoundTotal(@CompleteTotal) ,
              @IfCargo ,
              @IfInvoice ,
              dbo.F_RoundTotal(@invoicemoney) ,
              dbo.F_RoundTotal(@ninvoicemoney),
              @importtype,
              @AssetBusinessTypeId ,
              @promoruleid,
			  @beforepromobillnumberid,
			  @promotionmsg,
			  @STypeID2,
			  @ifconfirm,
			  @FeeDeductType,
			  @TransferType,
			  @isyapi,
			  @yapiorderid,
			  @DeliveryAddress,
			   CONVERT(VARCHAR(20), GETDATE(), 24),
			   dbo.F_RoundDiscount(@Discount),
			   @AdpriceType,
			   @chargeoffbtypeid,
			   @chargeofftype,
			   @chargeofftotal,
			   @nchargeofftotal,
			   @IsLend,
			   @transportno,
			   @WarehouseOutDay,
			   @StockInDeadline,
			   @IsNeedTransport,
			   @iscombinationstyle,
			   @transporterid ,
			   @transporterfullname,
			   @shipperfullname,
			   @shipperperson,
			   @shippertel,
			   @totalfreight,
			   @ntotalfreight,
			   ISNULL(@PromonIds,''),
			   @isByBrandarType,
			   ISNULL(@NewPosBill,0),
			   @PayOnTheSpot,
			   @posid,
			   @YjkBillCode
            )

    DECLARE @intReturn BIGINT

    SELECT  @intReturn = SCOPE_IDENTITY();

    IF ( @isini = 1 )  --期初单据计算completetotal,chargeoffTotal
        BEGIN
            DECLARE @currate  NUMERIC(24, 10)  ,
                @curbasistype INT ,
                @curCompleteTotal  NUMERIC(24, 10) ,
                @curChargeOffTotal NUMERIC(24, 10) 
            SELECT  @currate = rate ,
                    @curbasistype = basistype
            FROM    Ac_Currency
            WHERE   CId = @cid
            IF ( @curbasistype = 1 ) 
            BEGIN
                SET @curCompleteTotal = dbo.F_RoundTotal(@ncompletetotal / @currate)
                SET @curChargeOffTotal= dbo.F_RoundTotal(@nchargeofftotal/ @currate)
            END
            ELSE 
            BEGIN
                SET @curCompleteTotal = dbo.F_RoundTotal(@ncompletetotal * @currate)
                SET @curChargeOffTotal= dbo.F_RoundTotal(@nchargeofftotal* @currate)
            END
	
            UPDATE  BillIndex
            SET     CompleteTotal = dbo.F_RoundTotal(@curCompleteTotal),ChargeOffTotal=dbo.F_RoundTotal(@curChargeOffTotal)
            WHERE   BillNumberId = @intReturn	
        END



    IF @BillType = 181--IN (177,178,186,191,192,195,196,197,199,200,198,181,182,179)
        BEGIN
            INSERT  INTO Billindex_CarRepair
                    ( [BillNumberId] ,
                      [BillDate] ,
                      [BillType] ,
                      [RATypeID] ,
                      [OperationSort] ,
                      [RepairMode] ,
                      [Oil] ,
                      [Mileage] ,
                      [EpibolyItem] ,
                      [OtherItem] ,
                      [Status] ,
                      [ManHourTotal] ,
                      [ManHourTax] ,
                      [ManHourTaxTotal] ,
                      [PTypeTotal] ,
                      [PTypeTax] ,
                      [PTypeTaxTotal] ,
                      [EpibolyTotal] ,
                      [OtherTotal] ,
                      [InPriceType] ,
                      BTypeID1 ,
                      QuickRepairBillID ,
                      ManHourInsuranceTotal ,
                      PTypeInsuranceTotal ,
                      InvoiceMode ,
                      InvoiceCode ,
                      InsuranceStatus ,
                      repairtype ,
                      bespokedate ,
                      receptiondate ,
                      completedate ,
                      infactorydate ,
                      factcompletedate ,
                      receptionid ,
                      unitsatrap ,
                      sendperson ,
                      ErrDescription ,
                      epibolycosttotal ,
                      preferencereason ,
                      balancedate ,
                      itemprincipal ,
                      monitorprincipal ,
                      billstate ,
                      intendingkickback ,
                      settlementkickback ,
                      BackTypeId ,
                      intendingtalkbackdate ,
                      istalkbackover ,
                      czbeforetimes ,
                      RepairAutoTypeId
	                  )
            VALUES  ( @intReturn ,
                      @BillDate ,
                      @BillType ,
                      '' ,
                      '' ,
                      '' ,
                      '' ,
                      '' ,
                      '' ,
                      '' ,
                      0 ,
                      0 ,
                      0 ,
                      0 ,
                      0 ,
                      0 ,
                      0 ,
                      0 ,
                      0 ,
                      '' ,
                      '' ,
                      0 ,
                      0 ,
                      0 ,
                      0 ,
                      '' ,
                      0 ,
                      0 ,
                      '9999-12-31 23:59:59' ,
                      '9999-12-31 23:59:59' ,
                      @completedate ,
                      '9999-12-31 23:59:59' ,
                      '9999-12-31 23:59:59' ,
                      '' ,
                      '' ,
                      '' ,
                      '' ,
                      0 ,
                      '' ,
                      '9999-12-31 23:59:59' ,
                      '' ,
                      '' ,
                      @billstate ,
                      0 ,
                      0 ,
                      0 ,
                      '9999-12-31 23:59:59' ,
                      0 ,
                      @czbeforetimes ,
                      NULL
			              )	

            IF @@rowcount = 0
                OR @@error <> 0
		--RAISERROR('更新单据发生错误！',16,1)
                RETURN -5
        END

    RETURN @intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertBillIndexAutoDraft]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertBillIndexAutoDraft]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2019-12-23
	描述：自动保存草稿
*/
CREATE  PROCEDURE Gp_InsertBillIndexAutoDraft
(
	@billguid		VARCHAR(100),
	@BillDate		[datetime] ,
	@BillCode		[varchar](200) ,  -- #&**&#
	@BillType		[numeric](4, 0) ,
	@Comment		[varchar](2000) ,
	@AtypeId		[varchar](50) ,
	@PtypeId		[varchar](50) ,
	@BtypeId		[varchar](50) ,
	@EtypeId		[varchar](50) ,
	@KtypeId		[varchar](50) ,
	@KtypeId2		[varchar](50) ,
	@IfCheck		[char](1) ,
	@CheckE			[varchar](50) ,
	@TotalMoney		NUMERIC(24, 10)  ,
	@TotalQty		NUMERIC(24, 10)  ,
	@TotalInMoney	NUMERIC(24, 10)  ,
	@Tax			NUMERIC(24, 10)  ,
	@szPeriod		[SMALLINT] ,
	@Explain		[varchar](2000) ,
	@Draft			[bit] ,
	@RedWord		[bit] ,
	@OrderId		[numeric] = 0 ,
	--添加新的参数
	@WayBillCode	VARCHAR(50) = NULL ,
	@Goodsnumber	VARCHAR(20) = NULL ,
	@PackWay		VARCHAR(20) = NULL ,
	@Tel			VARCHAR(100) = NULL , --100个字符 【司华山 2015-04-03】
	@preferencemoney  NUMERIC(24, 10)  = 0 ,		--优惠金额【谢吉康 2004-07-16】
	@AlertDay		INT = 9999 ,				--收款期限 
	@Assessor		VARCHAR(50) = NULL ,
	@IfAudit		CHAR(1) = '3' ,
	@Audit_explain VARCHAR(256) = NULL ,
	@DtypeId VARCHAR(50) = '' ,		--分支机构ID
	@VipCardID INT = -1 ,				-- VIP卡的唯一ID值
	@KTypeID3 VARCHAR(50) = '' ,	-- 表头第三个仓库，目前用于新维修的自行维修单
	@LinkMan VARCHAR(256) = '' ,	-- 新维修(接件单) - 联系人
	@LinkTel VARCHAR(256) = '' ,	-- 新维修(接件单) - 联系电话
	@LinkAddr VARCHAR(256) = '' ,	-- 新维修(接件单) - 联系地址
	@wxManID VARCHAR(50) = '' ,	-- 新维修(维修单、上门维修单) - 维修人ID
	@JieJianBillNumberID VARCHAR(200) = '' ,	-- 新维修 - 接件单的BillNumberID
	@JieJianID VARCHAR(200) = '' ,	-- 新维修 - 接件单对应商品明细行的物理顺序ID
	@BaoXiuBillNumberID VARCHAR(200) = '' ,	-- 新维修 - 报修单的BillNumberID
	@BaoXiuID VARCHAR(200) = '' ,	-- 新维修 - 报修单对应商品明细行的物理顺序ID
	@BuyDate VARCHAR(50) = '' ,	-- 新维修(接件单) - 购买日期
	@Serial VARCHAR(200) = '' ,	-- 新维修 - 序列号
	@wxTotal  NUMERIC(24, 10)  = 0 ,	-- 新维修(表尾) - 维修费用、换机费用
	@ErrDes VARCHAR(3000) = '' ,	-- 新维修 - 故障描述
	@ifHideJieJian INT = 0 ,			-- 新维修 - 是否隐藏接件详情，0：不隐藏；1：隐藏
	@ifWX INT = 0 ,			-- 是否针对维修库存进行盘点、报损、报溢；0：正常库，1：维修库
	@IfBargainOn INT = 0 ,				--询价单、报价单成交标志 0：未成交  1：成交
	@STypeID VARCHAR(50) = '' ,
	@FromBillNumberID NUMERIC(10, 0) = 0 ,
	@CostSale BIT = 0 ,
	@completedate DATETIME ,			--预计完成
	@billstate INT ,				--单据状态
	@ifmulaccount INT ,				--是否多账户收款
	@vipczmoney  NUMERIC(24, 10)  ,		--会员卡充值前金额
	@otherinouttype INT ,					--其他出入库单业务类别
	@czbeforetimes  NUMERIC(24, 10)  ,		  --会员卡充值前次数
	@PosBillType INT ,
	@TransportId VARCHAR(10) ,
	@IsFreightMoney INT ,
	@FreightAddr VARCHAR(300) ,
	@FreightPerson VARCHAR(100) ,
	@FreightTel VARCHAR(100) ,
	@ShareMode TINYINT ,			--摊销方式
	@uf1 VARCHAR(200) = '' ,		--自定义表头字段
	@uf2 VARCHAR(200) = '' ,
	@uf3 VARCHAR(200) = '' ,
	@uf4 VARCHAR(200) = '' ,
	@uf5 VARCHAR(200) = '' ,
	--9.0新字段
	@DEALBTYPEID VARCHAR(50) ,		--结算单位
	@cid INT ,				--外币币种ID
	@rate  NUMERIC(24, 10)  ,		--汇率
	@ntotalmoney MONEY ,				--原币总金额
	@ntotalinmoney MONEY ,				--原币收现金额
	@npreferencemoney MONEY ,				--原币优惠金额
	@nvipczmoney MONEY ,				--原币会员卡充值金额
	@atypeid1 VARCHAR(50) ,		--往来科目
	@billproperty INT ,					--单据属性
	@ncompletetotal  NUMERIC(24, 10)  ,		--原币结算金额
	@isini BIT ,
	@ATID INT ,
	@completetotal  NUMERIC(24, 10)  ,
	@IfCargo BIT ,
	@IfInvoice INT ,
	@invoicemoney  NUMERIC(24, 10)  = 0 ,
	@ninvoicemoney  NUMERIC(24, 10)  = 0,
	@importtype TINYINT=0,
	@AssetBusinessTypeId  int=0,
	@promoruleid	int,
	@beforepromobillnumberid int,
	@promotionmsg NVARCHAR(500)='',
	@STypeID2 VARCHAR(50)='',
	@ifconfirm int=0,
	@FeeDeductType int=0,
	@TransferType int=1,
	@isyapi INT=0,
	@yapiorderid VARCHAR(20)='0',
	@DeliveryAddress VARCHAR(256)= '' ,
	@Discount  NUMERIC(24, 10) =1,
	@AdpriceType INT=0,
	@checkSave varchar(128)='',
	@chargeoffbtypeid VARCHAR(50)='',
	@chargeofftype INT=0,
	@chargeofftotal NUMERIC(24, 10)=0 ,
	@nchargeofftotal NUMERIC(24, 10)=0,
	@IsLend int = 0,
	@WarehouseOutDay INT = 9999,--出库期限 
	@StockInDeadline INT = 9999,--入库期限 
	@IsNeedTransport BIT=0,--是否需要运输配送
	@iscombinationstyle INT = 0,
	@transporterid VARCHAR(50)='0',
	@transporterfullname varchar(200)	='',
	@shipperfullname varchar(100)	='',
	@shipperperson varchar(100)='',
	@shippertel varchar(100)='',
	@transportno VARCHAR(200)='',
	@totalfreight NUMERIC(24,10)=0,
	@ntotalfreight NUMERIC(24,10)=0,
	@PromonIds	VARCHAR(1000)='',  --促销方案id
	@isByBrandarType INT=0,
	@NewPosBill INT=0, --pos上传单据标志
	@PayOnTheSpot	INT = 0, --当面付
	@posid INT = 0
)
--@encode$--
AS 
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 1 FROM BillIndexAutoDraft WHERE billguid = @billguid)
BEGIN
	INSERT  INTO [dbo].BillIndexAutoDraft
	( 
		[billguid],
		[vipczmoney] ,
		[BillDate] ,
		[BillCode] ,
		[BillType] ,
		[Comment] ,
		[atypeid] ,
		[ptypeid] ,
		[btypeid] ,
		[etypeid] ,
		[ktypeid] ,
		[ktypeid2] ,
		[ifcheck] ,
		[checke] ,
		[totalqty] ,
		[totalmoney] ,
		[totalinmoney] ,
		[tax] ,
		[period] ,
		[explain] ,
		[draft] ,
		[RedWord] ,
		[orderid] ,
		[waybillcode] ,
		[goodsnumber] ,
		[packway] ,
		[Tel] ,
		[preferencemoney] ,
		[AlertDay] ,
		[ID] ,
		[Assessor] ,
		[IfAudit] ,
		[Audit_explain] ,
		[DtypeId] ,
		[VipCardID] ,
		[KTypeID3] ,
		[LinkMan] ,
		[LinkTel] ,
		[LinkAddr] ,
		[wxManID] ,
		[JieJianBillNumberID] ,
		[JieJianID] ,
		[BaoXiuBillNumberID] ,
		[BaoXiuID] ,
		[BuyDate] ,
		[Serial] ,
		[wxTotal] ,
		[ErrDes] ,
		[ifHideJieJian] ,
		[ifWX] ,
		[IfBargainOn] ,
		[Stypeid] ,
		[FromBillNumberID] ,
		[CostSale] ,
		[ifmulaccount] ,
		otherinouttype ,
		PosBillType ,
		checkTime ,
		LastUpdateTime ,
		ShareMode ,
		TransportId ,
		IsFreightMoney ,
		FreightAddr ,
		FreightPerson ,
		FreightTel ,
		uf1 ,
		uf2 ,
		uf3 ,
		uf4 ,
		uf5 ,
		DEALBTYPEID ,
		cid ,
		rate ,
		ntotalmoney ,
		ntotalinmoney ,
		npreferencemoney ,
		nvipczmoney ,
		atypeid1 ,
		billproperty ,
		ncompletetotal ,
		isini ,
		ATID ,
		CompleteTotal ,
		IfCargo ,
		IfInvoice ,
		invoicemoney ,
		ninvoicemoney,
		importtype,
		AssetBusinessTypeId,
		PromoRuleId,
		BeforePromoBillNumberId,
		promotionmsg,
		StypeID2,
		IfConfirm,
		FeeDeductType,
		TransferType,
		isyapi,
		yapiorderid,
		DeliveryAddress,
		BillTime,
		Discount,
		AdPriceType,
		chargeoffbtypeid,
		chargeofftype,
		ChargeOffTotal,
		NChargeOffTotal,
		islend,
		transportno,
		WarehouseOutDay,
		StockInDeadline,
		IsNeedTransport,
		iscombinationstyle,
		Transporterid,
		Transporterfullname,
		shipperfullname,
		shipperperson,
		shippertel,
		totalfreight,
		ntotalfreight,
		PromonIds,
		isByBrandarType,
		NewPosBill,
		PayOnTheSpot,
		posid
	)
	VALUES  
	( 
		@billguid,
		@vipczmoney ,
		@BillDate ,
		@BillCode ,
		@BillType ,
		@Comment ,
		@atypeid ,
		@ptypeid ,
		@btypeid ,
		@etypeid ,
		@ktypeid ,
		@ktypeid2 ,
		@ifcheck ,
		@checke ,
		dbo.F_RoundQty(@totalqty) ,
		dbo.F_RoundTotal(@totalmoney) ,
		dbo.F_RoundTotal(@totalinmoney) ,
		dbo.F_RoundTax(@tax) ,
		@szPeriod ,
		@explain ,
		@draft ,
		@redword ,
		@orderID ,
		@waybillcode ,
		@goodsnumber ,
		@packway ,
		@Tel ,
		dbo.F_RoundTotal(@preferencemoney) ,
		@AlertDay ,
		0 ,
		@Assessor ,
		@IfAudit ,
		@Audit_explain ,
		@DtypeId ,
		@VipCardID ,
		@KTypeID3 ,
		@LinkMan ,
		@LinkTel ,
		@LinkAddr ,
		@wxManID ,
		@JieJianBillNumberID ,
		@JieJianID ,
		@BaoXiuBillNumberID ,
		@BaoXiuID ,
		@BuyDate ,
		@Serial ,
		dbo.F_RoundTotal(@wxTotal) ,
		@ErrDes ,
		@ifHideJieJian ,
		@ifWX ,
		@IfBargainOn ,
		@Stypeid ,
		@FromBillNumberID ,
		@CostSale ,
		@ifmulaccount ,
		@otherinouttype ,
		@PosBillType ,
		GETDATE() ,
		NULL ,
		@ShareMode ,
		@TransportId ,
		@IsFreightMoney,
		@FreightAddr ,
		@FreightPerson ,
		@FreightTel ,
		@uf1 ,
		@uf2 ,
		@uf3 ,
		@uf4 ,
		@uf5 ,
		@DEALBTYPEID ,
		@cid ,
		dbo.F_RoundExchangeRate(@rate) ,
		dbo.F_RoundTotal(@ntotalmoney) ,
		dbo.F_RoundTotal(@ntotalinmoney) ,
		dbo.F_RoundTotal(@npreferencemoney) ,
		dbo.F_RoundTotal(@nvipczmoney) ,
		@atypeid1 ,
		@billproperty ,
		dbo.F_RoundTotal(@ncompletetotal) ,
		@isini ,
		@ATID ,
		dbo.F_RoundTotal(@CompleteTotal) ,
		@IfCargo ,
		@IfInvoice ,
		dbo.F_RoundTotal(@invoicemoney) ,
		dbo.F_RoundTotal(@ninvoicemoney),
		@importtype,
		@AssetBusinessTypeId ,
		@promoruleid,
		@beforepromobillnumberid,
		@promotionmsg,
		@STypeID2,
		@ifconfirm,
		@FeeDeductType,
		@TransferType,
		@isyapi,
		@yapiorderid,
		@DeliveryAddress,
		CONVERT(VARCHAR(20), GETDATE(), 24),
		dbo.F_RoundDiscount(@Discount),
		@AdpriceType,
		@chargeoffbtypeid,
		@chargeofftype,
		@chargeofftotal,
		@nchargeofftotal,
		@IsLend,
		@transportno,
		@WarehouseOutDay,
		@StockInDeadline,
		@IsNeedTransport,
		@iscombinationstyle,
		@transporterid ,
		@transporterfullname,
		@shipperfullname,
		@shipperperson,
		@shippertel,
		@totalfreight,
		@ntotalfreight,
		ISNULL(@PromonIds,''),
		@isByBrandarType,
		ISNULL(@NewPosBill,0),
		@PayOnTheSpot,
		@posid
	)
END
ELSE
BEGIN
	UPDATE	dbo.BillIndexAutoDraft			
	SET		[vipczmoney]=@vipczmoney ,
			[BillDate]= @BillDate ,
			[BillCode]= @BillCode ,
			[BillType]= @BillType ,
			[Comment]= @Comment ,
			[atypeid]= @atypeid ,
			[ptypeid]= @ptypeid ,
			[btypeid]= @btypeid ,
			[etypeid]= @etypeid ,
			[ktypeid]= @ktypeid ,
			[ktypeid2]= @ktypeid2 ,
			[ifcheck] =@ifcheck ,
			[checke] =@checke ,
			[totalqty] =dbo.F_RoundQty(@totalqty) ,
			[totalmoney] =dbo.F_RoundTotal(@totalmoney) ,
			[totalinmoney] =dbo.F_RoundTotal(@totalinmoney) ,
			[tax] =dbo.F_RoundTax(@tax) ,
			[period] =@szPeriod ,
			[explain] =@explain ,
			[draft] =@draft ,
			[RedWord] =@redword ,
			[orderid] =@orderID ,
			[waybillcode]= @waybillcode ,
			[goodsnumber]= @goodsnumber ,
			[packway]= @packway ,
			[Tel]= @Tel ,
			[preferencemoney]= dbo.F_RoundTotal(@preferencemoney) ,
			[AlertDay]= @AlertDay ,			
			[Assessor]= @Assessor ,
			[IfAudit]= @IfAudit ,
			[Audit_explain]= @Audit_explain ,
			[DtypeId]= @DtypeId ,
			[VipCardID]= @VipCardID ,
			[KTypeID3]= @KTypeID3 ,
			[LinkMan] =@LinkMan ,
			[LinkTel]= @LinkTel ,
			[LinkAddr]= @LinkAddr ,
			[wxManID]= @wxManID ,
			[JieJianBillNumberID]= @JieJianBillNumberID ,
			[JieJianID]= @JieJianID ,
			[BaoXiuBillNumberID]= @BaoXiuBillNumberID ,
			[BaoXiuID]= @BaoXiuID ,
			[BuyDate] =@BuyDate ,
			[Serial] =@Serial ,
			[wxTotal]= dbo.F_RoundTotal(@wxTotal) ,
			[ErrDes]= @ErrDes ,
			[ifHideJieJian]= @ifHideJieJian ,
			[ifWX]= @ifWX ,
			[IfBargainOn] =@IfBargainOn ,
			[Stypeid]= @Stypeid ,
			[FromBillNumberID] =@FromBillNumberID ,
			[CostSale]= @CostSale ,
			[ifmulaccount]= @ifmulaccount ,
			otherinouttype= @otherinouttype ,
			PosBillType= @PosBillType ,
			checkTime= GETDATE() ,
			LastUpdateTime= NULL ,
			ShareMode= @ShareMode ,
			TransportId= @TransportId ,
			IsFreightMoney =@IsFreightMoney,
			FreightAddr= @FreightAddr ,
			FreightPerson =@FreightPerson ,
			FreightTel= @FreightTel ,
			uf1= @uf1 ,
			uf2= @uf2 ,
			uf3 =@uf3 ,
			uf4= @uf4 ,
			uf5= @uf5 ,
			DEALBTYPEID= @DEALBTYPEID ,
			cid= @cid ,
			rate= dbo.F_RoundExchangeRate(@rate) ,
			ntotalmoney= dbo.F_RoundTotal(@ntotalmoney) ,
			ntotalinmoney= dbo.F_RoundTotal(@ntotalinmoney) ,
			npreferencemoney= dbo.F_RoundTotal(@npreferencemoney) ,
			nvipczmoney= dbo.F_RoundTotal(@nvipczmoney) ,
			atypeid1= @atypeid1 ,
			billproperty =@billproperty ,
			ncompletetotal= dbo.F_RoundTotal(@ncompletetotal) ,
			isini= @isini ,
			ATID =@ATID ,
			CompleteTotal= dbo.F_RoundTotal(@CompleteTotal) ,
			IfCargo= @IfCargo ,
			IfInvoice =@IfInvoice ,
			invoicemoney =dbo.F_RoundTotal(@invoicemoney) ,
			ninvoicemoney=dbo.F_RoundTotal(@ninvoicemoney),
			importtype=@importtype,
			AssetBusinessTypeId=@AssetBusinessTypeId ,
			PromoRuleId=@promoruleid,
			BeforePromoBillNumberId=@beforepromobillnumberid,
			promotionmsg=@promotionmsg,
			StypeID2=@STypeID2,
			IfConfirm=@ifconfirm,
			FeeDeductType=@FeeDeductType,
			TransferType=@TransferType,
			isyapi=@isyapi,
			yapiorderid=@yapiorderid,
			DeliveryAddress=@DeliveryAddress,
			BillTime=CONVERT(VARCHAR(20), GETDATE(), 24),
			Discount=dbo.F_RoundDiscount(@Discount),
			AdPriceType=@AdpriceType,
			chargeoffbtypeid=@chargeoffbtypeid,
			chargeofftype=@chargeofftype,
			ChargeOffTotal=@chargeofftotal,
			NChargeOffTotal=@nchargeofftotal,
			islend=@IsLend,
			transportno=@transportno,
			WarehouseOutDay=@WarehouseOutDay,
			StockInDeadline=@StockInDeadline,
			IsNeedTransport=@IsNeedTransport,
			iscombinationstyle=@iscombinationstyle,
			Transporterid=@transporterid ,
			Transporterfullname=@transporterfullname,
			shipperfullname=@shipperfullname,
			shipperperson=@shipperperson,
			shippertel=@shippertel,
			totalfreight=@totalfreight,
			ntotalfreight=@ntotalfreight,
			PromonIds=ISNULL(@PromonIds,''),
			isByBrandarType=@isByBrandarType,
			NewPosBill=ISNULL(@NewPosBill,0),
			PayOnTheSpot=@PayOnTheSpot,
			posid=@posid,
			CreateDate = GETDATE()
	WHERE	billguid = @billguid
END

--删除多账户信息
DELETE FROM BillMulAccountAutoDraft WHERE BillGuid = @BillGuid

--删除品牌多账户
DELETE FROM BillMulBrandAutoDraft WHERE BillGuid = @BillGuid


RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[GP_InsertBillSaveTimeLog]')
                    AND TYPE IN ( N'P', N'PC' ) ) 
    DROP PROC GP_InsertBillSaveTimeLog;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	By: Haiyang, Li
	Date: 2012-10-30
	Description: 单据分时记录函数
*/
--插入保存单据时间日志
CREATE PROCEDURE GP_InsertBillSaveTimeLog
    @SaveDate DATETIME ,
    @tb TbType_BillSaveTimeLog READONLY
--@encode$--
AS 
    BEGIN
        SET NOCOUNT ON
        INSERT  INTO BillSaveTimeLog
                ( SaveDate ,
                  BillTypeID ,
                  BillCode ,
                  FunctionOrder ,
                  FunctionName ,
                  Elapsed
                )
                SELECT  @SaveDate ,
                        BillTypeID ,
                        BillCode ,
                        FunctionOrder ,
                        FunctionName ,
                        Elapsed
                FROM    @tb
    END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



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




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertBuyBackBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertBuyBackBillDT;

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-03 15:15:58.937
	描述：采购退货单明细插入dt版
*/
CREATE PROCEDURE GP_InsertBuyBackBillDT
	@tb TbType_BuyBack READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @BillNumberID VARCHAR(50)
	
	SELECT TOP 1 @BillNumberID = BillNumberID FROM @tb

	--期初单据不处理草稿库存
	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
	BEGIN
		-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
		EXEC GP_Deal_DraftQTY @BillNumberID,6,'-'
	END
	
	DELETE A FROM BuyBackBill A,@tb B WHERE A.BillNumberId=B.BillNumberID AND  NOT EXISTS(
			   SELECT ID FROM @tb B WHERE A.BillNumberID=B.BillNumberID
									  AND A.ID=B.ID
								      AND A.OldId=B.OldID
								      AND A.OldBillNumberID=B.OldBillNumberID
								      AND B.ID<>0)
	
	INSERT INTO [BuyBackBill](BillNumberId,
							  PtypeId,
							  Qty,
							  SalePrice,
							  discount,
							  DiscountPrice,
							  jobnumber,
							  total,
							  OutFactoryDate,
							  TaxPrice,
							  TaxTotal,
							  Comment,
						      isUnit2,
							  Serial,
							  OldID,
							  OldBillNumberID,
							  InputCostPrice,
							  GoodsNumber,
							  ProduceDate,
							  ValidDate,
							  GoodsBTypeID,
							  GoodsCostPrice,
							  HandZeroCost,
							  Tax,
							  SaleTotal,
							  KTypeID,
							  STypeID,	
							  TaxMoney,
							  NSalePrice,
							  NSaleTotal,
							  NDiscountPrice,
							  NTotal,
							  NTaxPrice,
							  NTaxTotal,
							  NTaxMoney,
							  CargoId,
							  UnitId,
							  NUnitId,
							  NQty,
							  UnitRate,
							  NUnitMsg,
							  MUnitId,
							  MQty,
							  MUnitRate,
							  MUnitMsg,
							  MSalePrice,
							  MDiscountPrice,
							  MTaxPrice,
							  CurMSalePrice,
							  CurMDiscountPrice,
							  CurMTaxPrice,
							  ItemId,
							  IsCombined,
							  CompleteQty,
							  InvoiceQty,
							  InvoiceMoney,
							  NInvoiceMoney,
							  IsGift,
							  PriceStyle,
							  CompleteTotal,
							  NCompleteTotal,
							  ShowOrder,
							  PriceSource 
							  ) 
	
	SELECT					 BillNumberId,
							 PtypeId,
							 dbo.F_RoundQty(Qty),
							 dbo.F_RoundPrice(SalePrice),
							 dbo.F_RoundDiscount(discount),
							 dbo.F_RoundPrice(DiscountPrice),
							 jobno,
							 dbo.F_RoundTotal(total),
							 makedate,
							 dbo.F_RoundPrice(TaxPrice),
							 dbo.F_RoundTotal(TaxTotal),
							 comment,
							 intIsUnit2,
							 Serial,
							 OldID,
							 OldBillNumberID,
							 dbo.F_RoundPrice(InputCostPrice),
							 GoodsNumber,
							 ProduceDate,
							 ValidDate,
							 GoodsBTypeID,
							 dbo.F_RoundPrice(GoodsCostPrice),
							 HandZeroCost,
							 dbo.F_RoundTax(Tax),
							 dbo.F_RoundTotal(SaleTotal),
							 KTypeID,
							 STypeID,
							 dbo.F_RoundTotal(TaxMoney),
							 dbo.F_RoundPrice(NSalePrice),
							 dbo.F_RoundTotal(NSaleTotal),
							 dbo.F_RoundPrice(NDiscountPrice),
							 dbo.F_RoundTotal(NTotal),
							 dbo.F_RoundPrice(NTaxPrice),
							 dbo.F_RoundTotal(NTaxTotal),
							 dbo.F_RoundTotal(NTaxMoney),
							 CargoId,
							 UnitId,
							 NUnitId,
							 dbo.F_RoundQty(NQty),
							 dbo.F_RoundTranslateRate(UnitRate),
							 NUnitMsg,
							 MUnitId,
							 dbo.F_RoundQty(MQty),
							 dbo.F_RoundTranslateRate(MUnitRate),
							 MUnitMsg,
							 dbo.F_RoundPrice(MSalePrice),
							 dbo.F_RoundPrice(MDiscountPrice),
							 dbo.F_RoundPrice(MTaxPrice),
							 dbo.F_RoundPrice(CurMSalePrice),
							 dbo.F_RoundPrice(CurMDiscountPrice),
							 dbo.F_RoundPrice(CurMTaxPrice),
							 ItemId,
							 IsCombined,
							 dbo.F_RoundQty(CompleteQty),
							 dbo.F_RoundQty(InvoiceQty),
							 dbo.F_RoundTotal(InvoiceMoney),
							 dbo.F_RoundTotal(NInvoiceMoney),
							 IsGift,
							 PriceStyle,
							 dbo.F_RoundTotal(CompleteTotal),
							 dbo.F_RoundTotal(NCompleteTotal),
							 ShowOrder,
							 PriceSource
	--尽量减少碰撞吧，ID不可行
	FROM @tb A WHERE ID=0 OR NOT EXISTS (
		SELECT ID FROM dbo.BuyBackBill B WHERE A.BillNumberID=B.BillNumberID
										   AND A.ID=B.ID
										   AND A.OldId=B.OldID
										   AND A.OldBillNumberID=B.OldBillNumberID)
	
	UPDATE A SET	A.PtypeId=B.PTypeID,
					A.Qty=B.Qty,
					A.SalePrice=B.SalePrice,
					A.discount=B.Discount,
					A.DiscountPrice=B.DiscountPrice,
					A.jobnumber=B.JobNo,
					A.total=B.Total,
					A.OutFactoryDate=B.MakeDate,
					A.TaxPrice=B.TaxPrice,
					A.TaxTotal=B.TaxTotal,
					A.Comment=B.Comment,
					A.isUnit2=B.intIsUnit2,
					A.Serial=B.Serial,
					A.OldID=B.OldId,
					A.OldBillNumberID=B.OldBillNumberID,
					A.InputCostPrice=B.InputCostPrice,
					A.GoodsNumber=B.GoodsNumber,
					A.ProduceDate=B.ProduceDate,
					A.ValidDate=B.ValidDate,
					A.GoodsBTypeID=B.GoodsBTypeID,
					A.GoodsCostPrice=B.GoodsCostPrice,
					A.HandZeroCost=B.HandZeroCost,
					A.Tax=B.Tax,
					A.SaleTotal=B.SaleTotal,
					A.KTypeID=B.KTypeID,
					A.STypeID=B.STypeID,	
					A.TaxMoney=B.TaxMoney,
					A.NSalePrice=B.NSalePrice,
					A.NSaleTotal=B.NSaleTotal,
					A.NDiscountPrice=B.NDiscountPrice,
					A.NTotal=B.NTotal,
					A.NTaxPrice=B.NTaxPrice,
					A.NTaxTotal=B.NTaxTotal,
					A.NTaxMoney=B.NTaxMoney,
					A.CargoId=B.CargoID,
					A.UnitId=B.UnitID,
					A.NUnitId=B.NUnitID,
					A.NQty=B.NQty,
					A.UnitRate=B.UnitRate,
					A.NUnitMsg=B.NUnitMsg,
					A.MUnitId=B.MUnitID,
					A.MQty=B.MQty,
					A.MUnitRate=B.MunitRate,
					A.MUnitMsg=B.MUnitMsg,
					A.MSalePrice=B.MSalePrice,
					A.MDiscountPrice=B.MDiscountPrice,
					A.MTaxPrice=B.MTaxPrice,
					A.CurMSalePrice=B.CurMSalePrice,
					A.CurMDiscountPrice=B.CurMDiscountPrice,
					A.CurMTaxPrice=B.CurMTaxPrice,
					A.ItemId=B.ItemId,
					A.IsCombined=B.IsCombined,
					A.CompleteQty=B.CompleteQty,
					A.InvoiceQty=B.InvoiceQty,
					A.InvoiceMoney=B.InvoiceMoney,
					A.NInvoiceMoney=B.NInvoiceMoney,
					A.IsGift=B.IsGift,
					A.PriceStyle=B.PriceStyle,
					A.CompleteTotal=B.CompleteTotal,
					A.NCompleteTotal=B.NCompleteTotal,
					A.ShowOrder=B.ShowOrder,
					A.PriceSource = B.PriceSource
	FROM dbo.BuyBackBill A ,@tb B WHERE A.BillNumberID=B.BillNumberID
									AND A.ID=B.ID
								    AND A.OldId=B.OldID
								    AND A.OldBillNumberID=B.OldBillNumberID
								    
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertBuyBackBillDTCheck]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertBuyBackBillDTCheck;

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-03 15:53:34.363
	描述：采购退货插入明细前的验证
*/

CREATE PROCEDURE GP_InsertBuyBackBillDTCheck
	@tb TbType_BuyBackCheck READONLY
--@encode$--
AS
BEGIN

	SELECT 1 AS ret FROM BuyBill a JOIN @tb b on a.BillNumberId=b.OldBillNumberId AND a.Id=b.OldId
	WHERE b.OldBillNumberId<>0 AND ISNULL(a.Qty,0)-ISNULL(a.Backqty,0)<b.Qty 
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



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





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertBuyBillAutoDraftDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertBuyBillAutoDraftDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	时间：2019-12-23
	描述：把单据明细保存存储过程dt版
*/
CREATE PROCEDURE GP_InsertBuyBillAutoDraftDT
(
	@tb TbType_BuyAutoDraft READONLY
)
--@encode$--
AS
BEGIN

SET NOCOUNT ON

DECLARE @billguid VARCHAR(100)

SELECT TOP 1 @billguid = billguid FROM @tb

DELETE FROM BuyBillAutoDraft WHERE BillGuid = @BillGuid
		
-- 写入数据表
INSERT INTO BuyBillAutoDraft
(
	BillGuid,
	BillNumberID,
	PTypeID,
	Qty,
	SalePrice,
	Discount,
	DiscountPrice,
	JobNumber,
	total,
	OutFactoryDate,
	TaxPrice,
	TaxTotal,
	Comment,
	OrderID,
	isUnit2,
	Serial,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	Tax,
	SaleTotal,
	KTypeID,
	Stypeid,
	FromBillNumberID,
	FromBillID,
	ShareFee

	-- 新增字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined

	,CompleteQty
	,entryCode
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,IsGift
	,CompleteTotal
	,NCompleteTotal
	,LendBillID
	,LendBillNumberID
	,ShowOrder
	,AskBillID
	,AskBillNumberID
	,PriceSource
) 
SELECT	BillGuid,
		BillNumberID,
		PTypeID,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(Discount),
		dbo.F_RoundPrice(DiscountPrice),
		Jobno,
		dbo.F_RoundTotal(Total),
		MakeDate,
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		Comment,
		OrderID,
		intIsUnit2,
		Serial,
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		dbo.F_RoundPrice(DiscountPrice),
		1,
		dbo.F_RoundTax(Tax),
		dbo.F_RoundTotal(SaleTotal),
		KTypeID,
		STypeID,
		FromBillNumberID,
		FromBillID,
		0
		-- 新字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,dbo.F_RoundQty(CompleteQty)
		,entryCode
		,dbo.F_RoundQty(InvoiceQty)
		,dbo.F_RoundTotal(InvoiceMoney)
		,dbo.F_RoundTotal(NInvoiceMoney)
		,IsGift
		,dbo.F_RoundTotal(CompleteTotal)
		,dbo.F_RoundTotal(NCompleteTotal)
		,LendBillID
		,LendBillNumberID	
		,ShowOrder
		,AskBillID
		,AskBillNumberID
		,PriceSource
FROM	@tb A 
WHERE	billguid = @billguid
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertBuyBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertBuyBillDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-03 09:18:19.193
	描述：把单据明细保存存储过程dt版
*/
CREATE PROCEDURE GP_InsertBuyBillDT
(
	@tb TbType_Buy READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	-- 更新待收货数量
	UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
	FROM OrderBill a 
	JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM @tb b WHERE b.OrderId<>-1 GROUP BY orderid)b ON b.orderid=a.OrderID
	
	DECLARE @BillNumberID VARCHAR(50)
	
	SELECT TOP 1 @BillNumberID = BillNumberID FROM @tb
	
	--期初单据不处理草稿库存
	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
	BEGIN
		-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
		EXEC GP_Deal_DraftQTY @BillNumberID,34,'-'
		
		IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f' AND draft=1)
		BEGIN
			-- 处理订单库存,先减去引用未过账数量
			EXEC GP_Deal_OrderReferQty @BillnumberID,34,'-'
		END
		ELSE
		BEGIN
			-- 处理订单库存,先减去过账数量
			EXEC GP_Deal_OrderReachQTY @BillnumberID,34,'-'
		END
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM BuyBill WHERE BillNumberId=@BillNumberID)
	BEGIN	
		DELETE A FROM dbo.BuyBill A,@tb B WHERE A.BillNumberId=B.BillNumberID AND NOT EXISTS(
					SELECT ID FROM @tb B WHERE A.BillNumberID=B.BillNumberID
										   AND A.ID=B.ID
										   AND A.OrderID=B.OrderID
										   AND A.LendBillID=B.LendBillID
										   AND A.LendBillNumberID=B.LendBillNumberID
										   AND A.AskBillID=B.AskBillID
										   AND A.AskBillNumberID=B.AskBillNumberID
										   AND B.ID<>0)
		
		-- 写入数据表
		INSERT INTO BuyBill(
			BillNumberID,
			PTypeID,
			Qty,
			SalePrice,
			Discount,
			DiscountPrice,
			JobNumber,
			total,
			OutFactoryDate,
			TaxPrice,
			TaxTotal,
			Comment,
			OrderID,
			isUnit2,
			Serial,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			Tax,
			SaleTotal,
			KTypeID,
			Stypeid,
			FromBillNumberID,
			FromBillID,
			ShareFee
			
			-- 新增字段
			,TaxMoney
			,NSalePrice
			,NSaleTotal
			,NDiscountPrice
			,NTotal
			,NTaxPrice
			,NTaxTotal
			,NTaxMoney
			,CargoId
			,UnitId
			,NUnitId
			,NQty
			,UnitRate
			,NUnitMsg
			,MUnitId
			,MQty
			,MUnitRate
			,MUnitMsg
			,MSalePrice
			,MDiscountPrice
			,MTaxPrice
			,CurMSalePrice
			,CurMDiscountPrice
			,CurMTaxPrice
			,ItemId
			,IsCombined
			
			,CompleteQty
			,entryCode
			,InvoiceQty
			,InvoiceMoney
			,NInvoiceMoney
			,IsGift
			,CompleteTotal
			,NCompleteTotal
			,LendBillID
			,LendBillNumberID
			,ShowOrder
			,AskBillID
			,AskBillNumberID
			,PriceSource
		) SELECT 
			BillNumberID,
			PTypeID,
			dbo.F_RoundQty(Qty),
			dbo.F_RoundPrice(SalePrice),
			dbo.F_RoundDiscount(Discount),
			dbo.F_RoundPrice(DiscountPrice),
			Jobno,
			dbo.F_RoundTotal(Total),
			MakeDate,
			dbo.F_RoundPrice(TaxPrice),
			dbo.F_RoundTotal(TaxTotal),
			Comment,
			OrderID,
			intIsUnit2,
			Serial,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			dbo.F_RoundPrice(DiscountPrice),
			1,
			dbo.F_RoundTax(Tax),
			dbo.F_RoundTotal(SaleTotal),
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID,
			0
			-- 新字段
			,dbo.F_RoundTotal(TaxMoney)
			,dbo.F_RoundPrice(NSalePrice)
			,dbo.F_RoundTotal(NSaleTotal)
			,dbo.F_RoundPrice(NDiscountPrice)
			,dbo.F_RoundTotal(NTotal)
			,dbo.F_RoundPrice(NTaxPrice)
			,dbo.F_RoundTotal(NTaxTotal)
			,dbo.F_RoundTotal(NTaxMoney)
			,CargoId
			,UnitId
			,NUnitId
			,dbo.F_RoundQty(NQty)
			,dbo.F_RoundTranslateRate(UnitRate)
			,NUnitMsg
			,MUnitId
			,dbo.F_RoundQty(MQty)
			,dbo.F_RoundTranslateRate(MUnitRate)
			,MUnitMsg
			,dbo.F_RoundPrice(MSalePrice)
			,dbo.F_RoundPrice(MDiscountPrice)
			,dbo.F_RoundPrice(MTaxPrice)
			,dbo.F_RoundPrice(CurMSalePrice)
			,dbo.F_RoundPrice(CurMDiscountPrice)
			,dbo.F_RoundPrice(CurMTaxPrice)
			,ItemId
			,IsCombined
			
			,dbo.F_RoundQty(CompleteQty)
			,entryCode
			,dbo.F_RoundQty(InvoiceQty)
			,dbo.F_RoundTotal(InvoiceMoney)
			,dbo.F_RoundTotal(NInvoiceMoney)
			,IsGift
			,dbo.F_RoundTotal(CompleteTotal)
			,dbo.F_RoundTotal(NCompleteTotal)
			,LendBillID
			,LendBillNumberID	
			,ShowOrder
			,AskBillID
			,AskBillNumberID
			,PriceSource
		--尽量减少碰撞吧，ID不可行
		FROM @tb A WHERE ID=0 OR NOT EXISTS(
			SELECT ID FROM dbo.BuyBill B WHERE A.BillNumberID=B.BillNumberID
										   AND A.ID=B.ID
										   AND A.OrderID=B.OrderID
										   AND A.LendBillID=B.LendBillID
										   AND A.LendBillNumberID=B.LendBillNumberID
										   AND A.AskBillID=B.AskBillID
										   AND A.AskBillNumberID=B.AskBillNumberID
										   )

		UPDATE A SET  PTypeID=B.PTypeID,
					  Qty=B.Qty,
					  SalePrice=B.SalePrice,
					  Discount=B.Discount,
					  DiscountPrice=B.DiscountPrice,
					  JobNumber=B.JobNo,
					  total=B.Total,
					  OutFactoryDate=B.MakeDate,
					  TaxPrice=B.TaxPrice,
					  TaxTotal=B.TaxTotal,
					  Comment=B.Comment,
					  OrderID=B.OrderID,
					  isUnit2=B.intIsUnit2,
					  Serial=B.Serial,
					  GoodsNumber=B.GoodsNumber,
					  ProduceDate=B.ProduceDate,
					  ValidDate=B.ValidDate,
					  GoodsBTypeID=B.GoodsBTypeID,
					  GoodsCostPrice=B.DiscountPrice,
					  HandZeroCost=1,
					  Tax=B.Tax,
					  SaleTotal=B.SaleTotal,
					  KTypeID=B.KTypeID,
					  Stypeid=B.STypeID,
					  FromBillNumberID=B.FromBillNumberID,
					  FromBillID=B.FromBillID,
					  ShareFee=0,
					  TaxMoney=B.TaxMoney,
					  NSalePrice=B.NSalePrice,
					  NSaleTotal=B.NSaleTotal,
					  NDiscountPrice=B.NDiscountPrice,
					  NTotal=B.NTotal,
					  NTaxPrice=B.NTaxPrice,
					  NTaxTotal=B.NTaxTotal,
					  NTaxMoney=B.NTaxMoney,
					  CargoId=B.CargoId,
					  UnitId=B.UnitId,
					  NUnitId=B.NUnitId,
					  NQty=B.NQty,
					  UnitRate=B.UnitRate,
					  NUnitMsg=B.NUnitMsg,
					  MUnitId=B.MUnitId,
					  MQty=B.MQty,
					  MUnitRate=B.MUnitRate,
					  MUnitMsg=B.MunitMsg,
					  MSalePrice=B.MSalePrice,
					  MDiscountPrice=B.MDiscountPrice,
					  MTaxPrice=B.MTaxPrice,
					  CurMSalePrice=B.CurMSalePrice,
					  CurMDiscountPrice=B.CurMDiscountPrice,
					  CurMTaxPrice=B.CurMTaxPrice,
					  ItemId=B.ItemId,
					  IsCombined=B.IsCombined,
					  CompleteQty=B.CompleteQty,
					  entryCode=B.EntryCode,
					  InvoiceQty=B.InvoiceQty,
					  InvoiceMoney=B.InvoiceMoney,
					  NInvoiceMoney=B.NInvoiceMoney,
					  IsGift=B.IsGift,
					  CompleteTotal=B.CompleteTotal,
					  NCompleteTotal=B.NCompleteTotal,
					  LendBillID=B.LendBillID,
					  LendBillNumberID=B.LendBillNumberID,
					  ShowOrder=B.ShowOrder,
					  AskBillID=B.AskBillID,
					  AskBillNumberID=B.AskBillNumberID,
					 PriceSource = b.PriceSource 
					FROM dbo.BuyBill A,@tb B WHERE A.BillNumberID=B.BillNumberID
								   AND A.ID=B.ID
								   AND A.OrderID=B.OrderID
								   AND A.LendBillID=B.LendBillID
								   AND A.LendBillNumberID=B.LendBillNumberID
								   AND A.AskBillID=B.AskBillID
								   AND A.AskBillNumberID=B.AskBillNumberID
		END
		ELSE
		BEGIN
			INSERT INTO BuyBill(
			BillNumberID,
			PTypeID,
			Qty,
			SalePrice,
			Discount,
			DiscountPrice,
			JobNumber,
			total,
			OutFactoryDate,
			TaxPrice,
			TaxTotal,
			Comment,
			OrderID,
			isUnit2,
			Serial,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			HandZeroCost,
			Tax,
			SaleTotal,
			KTypeID,
			Stypeid,
			FromBillNumberID,
			FromBillID,
			ShareFee
			
			-- 新增字段
			,TaxMoney
			,NSalePrice
			,NSaleTotal
			,NDiscountPrice
			,NTotal
			,NTaxPrice
			,NTaxTotal
			,NTaxMoney
			,CargoId
			,UnitId
			,NUnitId
			,NQty
			,UnitRate
			,NUnitMsg
			,MUnitId
			,MQty
			,MUnitRate
			,MUnitMsg
			,MSalePrice
			,MDiscountPrice
			,MTaxPrice
			,CurMSalePrice
			,CurMDiscountPrice
			,CurMTaxPrice
			,ItemId
			,IsCombined
			
			,CompleteQty
			,entryCode
			,InvoiceQty
			,InvoiceMoney
			,NInvoiceMoney
			,IsGift
			,CompleteTotal
			,NCompleteTotal
			,LendBillID
			,LendBillNumberID
			,ShowOrder
			,AskBillID
			,AskBillNumberID
			,PriceSource
		) SELECT 
			BillNumberID,
			PTypeID,
			dbo.F_RoundQty(Qty),
			dbo.F_RoundPrice(SalePrice),
			dbo.F_RoundDiscount(Discount),
			dbo.F_RoundPrice(DiscountPrice),
			Jobno,
			dbo.F_RoundTotal(Total),
			MakeDate,
			dbo.F_RoundPrice(TaxPrice),
			dbo.F_RoundTotal(TaxTotal),
			Comment,
			OrderID,
			intIsUnit2,
			Serial,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			dbo.F_RoundPrice(DiscountPrice),
			1,
			dbo.F_RoundTax(Tax),
			dbo.F_RoundTotal(SaleTotal),
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID,
			0
			-- 新字段
			,dbo.F_RoundTotal(TaxMoney)
			,dbo.F_RoundPrice(NSalePrice)
			,dbo.F_RoundTotal(NSaleTotal)
			,dbo.F_RoundPrice(NDiscountPrice)
			,dbo.F_RoundTotal(NTotal)
			,dbo.F_RoundPrice(NTaxPrice)
			,dbo.F_RoundTotal(NTaxTotal)
			,dbo.F_RoundTotal(NTaxMoney)
			,CargoId
			,UnitId
			,NUnitId
			,dbo.F_RoundQty(NQty)
			,dbo.F_RoundTranslateRate(UnitRate)
			,NUnitMsg
			,MUnitId
			,dbo.F_RoundQty(MQty)
			,dbo.F_RoundTranslateRate(MUnitRate)
			,MUnitMsg
			,dbo.F_RoundPrice(MSalePrice)
			,dbo.F_RoundPrice(MDiscountPrice)
			,dbo.F_RoundPrice(MTaxPrice)
			,dbo.F_RoundPrice(CurMSalePrice)
			,dbo.F_RoundPrice(CurMDiscountPrice)
			,dbo.F_RoundPrice(CurMTaxPrice)
			,ItemId
			,IsCombined
			
			,dbo.F_RoundQty(CompleteQty)
			,entryCode
			,dbo.F_RoundQty(InvoiceQty)
			,dbo.F_RoundTotal(InvoiceMoney)
			,dbo.F_RoundTotal(NInvoiceMoney)
			,IsGift
			,dbo.F_RoundTotal(CompleteTotal)
			,dbo.F_RoundTotal(NCompleteTotal)
			,LendBillID
			,LendBillNumberID	
			,ShowOrder
			,AskBillID
			,AskBillNumberID
			,PriceSource
			FROM @tb A 
		END
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



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





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertBuyGoodsExchangeBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertBuyGoodsExchangeBillDT;
	
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-03 16:58:13.333
	描述：采购换货单明细插入dt版
*/
CREATE PROCEDURE Gp_InsertBuyGoodsExchangeBillDT
	@tb TbType_BuyGoodsExchange READONLY
--@encode$--
AS
BEGIN
	INSERT INTO [dbo].[BuyGoodsExchangeBill]( 
		[BillNumberId],
		[InOrOut],
		[PtypeId],
		[Qty],
		[SalePrice],
		[discount],
		[DiscountPrice],
		[jobnumber],
		[total],
		[OutFactoryDate],
		[TaxPrice],
		[TaxTotal],
		[comment],
		[isUnit2],
		[Serial],
		[InputCostPrice],
		[GoodsNumber],
		[ProduceDate],
		[ValidDate],
		[GoodsBTypeID],
		[GoodsCostPrice],
		[HandZeroCost],
		Tax,
		SaleTotal,
		KTypeID,
		STypeID
		
		-- 新增字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,CargoId
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		
		,CompleteQty
		,InvoiceQty
		,InvoiceMoney
		,NInvoiceMoney
		,IsGift
		,OldID
		,OldBillNumberID
		,CompleteTotal
		,NCompleteTotal
		,ShowOrder
		,PriceSource
	) SELECT
		BillNumberId,
		InOrOut,
		PtypeId,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(discount),
		dbo.F_RoundPrice(DiscountPrice),
		jobnumber,
		dbo.F_RoundTotal(total),
		OutFactoryDate,
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		Comment,
		intisUnitTow,
		Serial,
		dbo.F_RoundPrice(InputCostPrice),
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		dbo.F_RoundPrice(GoodsCostPrice),
		HandZeroCost,
		dbo.F_RoundTax(Tax),
		dbo.F_RoundTotal(SaleTotal),
		KTypeID,
		STypeID

		-- 新增字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		
		,dbo.F_RoundQty(CompleteQty)
		,dbo.F_RoundQty(InvoiceQty)
		,dbo.F_RoundTotal(InvoiceMoney)
		,dbo.F_RoundTotal(NInvoiceMoney)
		,IsGift
		,OldID
		,OldBillNumberID
		,dbo.F_RoundTotal(CompleteTotal)
		,dbo.F_RoundTotal(NCompleteTotal)
		,ShowOrder
		,PriceSource
	FROM @tb;
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_InsertCapitalTransferAddDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].GP_InsertCapitalTransferAddDT
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2014-05-23 11:12:34.437
	描述：资金调拨单保存
*/
CREATE  PROCEDURE GP_InsertCapitalTransferAddDT
	@tb TbType_CapitalTransfer READONLY
--@encode$--
AS 
    SET NOCOUNT ON
    INSERT INTO dbo.CapitalTransfer_Bill
            ( BillNumberId ,
              BankAccountOut ,
              BankAccountIn ,
              TransferPrice,
              NTransferPrice ,
              DeductPrice,
              NDeductPrice,
              Comment
            )
	SELECT BillNumberId,BankAccountOut,BankAccountIn,dbo.F_RoundTotal(TransferPrice),dbo.F_RoundTotal(NTransferPrice),dbo.F_RoundTotal(DeductPrice),dbo.F_RoundTotal(NDeductPrice),Comment FROM @tb;
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-18
	描述：保存车辆使用登记明细
*/
CREATE PROCEDURE [dbo].[GP_InsertCarFeeBill]
	@BillNumberID  numeric(11,0), -- 单据ID
	@comment       varchar(256),  -- 备注
	@FeeTypeid	   int,			  -- 费用ID
	@Total         money          -- 金额

	--@encode$--
AS
	-- 写入数据
	SET NOCOUNT ON;
	
	INSERT INTO CM_FeeBill
	(
		BillNumberId,
		Comment,
		FeeTypeid,
		Total
	)
	VALUES
	(
		@BillNumberID,
		@comment,
		@FeeTypeid,
		dbo.F_RoundTotal(@Total)

	)
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：陈守川
	日期：2011-11-18
	描述：保存车辆费用单索引
*/
CREATE PROCEDURE [dbo].[GP_InsertCarFeeBillIndex]
	@BillNumberID numeric(11,0),
	@BillDate varchar(50),    -- 车牌号码
	@BillCode varchar(200),   -- 单据编号
    @BillType numeric(10,0),  -- 单据类型
    @CarId    int,			  -- 车辆id
    @Comment  varchar(256),   -- 备注
    @Stypeid  varchar(50),    -- 经手人
    @Etypeid  varchar(50),    -- 分支机构
    @Dtypeid  varchar(50),	  -- 部门
    @period	  SMALLINT,
    @Totalmoney numeric(19,0),--单据金额
    @checke   varchar(50),	  --制单人
    @Explain  varchar(256)    -- 说明
	--@encode$--
AS
	-- 写入数据
SET NOCOUNT ON

--*******************************************检查start*******************************************
	DECLARE @N int, @intVersion int

	-- 判断版本号，是否试用版
	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 2	-- 版本号

	IF @N IS NULL RETURN -1

	DECLARE @intBit int, @intMask int
	SELECT @intBit = @N & 15
	SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
	SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)
	-- ********	判断是否试用版 - END	********

	DECLARE @Re int,@Flag int
	EXEC @Re=Gp_Validate 2, @Flag OUTPUT
	IF @Re <>0 RETURN -3 --检查程序版本错误

	IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
	BEGIN
		--RAISERROR('校验错误 ！',16,1) 
		RETURN -3 --检查程序版本错误
	END

	IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
	BEGIN
		DECLARE @billnumberidtmp int
		SELECT @billnumberidtmp=ISNULL(COUNT(billnumberid),0) FROM billindex
		
		IF @billnumberidtmp > 200
		BEGIN
			--RAISERROR('试用版 ！',16,1) 
			RETURN -1
		END
	END  

--*******************************************检查end*******************************************	

--*****************************************单据日期检查start***********************************
	DECLARE @szPeriod [SMALLINT]
	DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
	EXEC Gp_GetSubValue 'period',@STypeID,@szPeriod out
	SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
	IF @BillDate<@BeginDate 
		BEGIN 
			--RAISERROR('录单日期小于本期开始日期 ！',16,1)
			RETURN -2
		END
	---根据配置检查过帐日期是否当前日期
	DECLARE @CurDate datetime
	DECLARE @IsOrNotPassOneDay bit
	SELECT @CurDate=GETDATE()
	SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
	IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
		BEGIN 
			--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
			RETURN -4
		END
--*****************************************单据日期检查end************************************

IF @BillNumberID=0
BEGIN
	INSERT INTO CM_FeeIndex
	(
		BillDate,
		BillCode,
		BillType,
		Comment,
		CarId,
		Stypeid,
		Etypeid,
		Dtypeid,
		Totalmoney,
		checke,
		Explain
	)
	VALUES
	(
		@BillDate,
		@BillCode,
		@BillType,
		@Comment,
		@CarId,
		@Stypeid,
		@Etypeid,
		@dtypeid,
		@Totalmoney,
		@checke,
		@explain
	)
	
	select @BillNumberId=SCOPE_IDENTITY();
	RETURN @BillNumberId
END
ELSE
BEGIN
	UPDATE	CM_FeeIndex
	SET		BillDate=@BillDate,
			BillCode=@BillCode,
			BillType=@BillType,
			Comment=@Comment,
			CarId=@CarId,
			Stypeid=@Stypeid,
			Etypeid=@Etypeid,
			Dtypeid=@dtypeid,
			Totalmoney=@Totalmoney,
			checke=@checke,
			Explain=@explain
			WHERE	BillNumberId= @BillNumberId
	DELETE FROM CM_FeeBill WHERE BillNumberID=@BillNumberId
	RETURN @BillNumberId
	IF @@rowcount =0  or @@error<>0
		RAISERROR('更新单据发生错误！',16,1)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：廖晨羽
描述：写入明细表(表值)
*/
CREATE              PROCEDURE [Gp_InsertCargo]
(
	@details TbType_Cargo READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO dbo.CargoType
        ( UserCode ,
          FullName ,
          KtypeID ,
          Comment ,
          PyCode ,
          deleted ,
          IsDefault ,
          XiWaMaxNumber,
          PathNo
        )
SELECT 
	 UserCode,
	 FullName,
	 KtypeID,
	 Comment,
	 PyCode,
	 0, 
	 IsDefault,
	 XiWaMaxNumber,
	 PathNo
	FROM @details


if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-16
	描述：车辆信息更新
*/
CREATE PROCEDURE [dbo].[Gp_InsertCarInfo]
	@platenumber varchar(50), -- 车牌号码
	@cartype varchar(50),     -- 车型
	@receptiondate datetime,  -- 登记日期
	@etypeid varchar(50)	  -- 驾驶员
	--@encode$--
AS
	-- 写入数据
	SET NOCOUNT ON;
	
	if exists (select platenumber from CM_CarInfo where platenumber=@platenumber )
	begin
		RAISERROR('已存在相同的车牌号码，请重新输入车牌号!',16,1)return--return -511
	end
	
	if exists (select fullname from employee where typeId=@etypeid and deleted=1)
	begin
		RAISERROR('选择的驾驶员已停用，请重新选择驾驶员!',16,1)return--return -511
	end
	
	INSERT INTO CM_CarInfo
	(
		Platenumber,
		Cartype,
		Receptiondate,
		Driver
	)
	VALUES
	(
		@Platenumber,
		@Cartype,
		@Receptiondate,
		@etypeid
	)
	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-18
	描述：保存车辆使用登记明细
*/
CREATE PROCEDURE GP_InsertCarUseBill
	@BillNumberID  numeric(11,0), -- 单据ID
	@comment       varchar(256),  -- 备注
	@CarId		   int,			  -- 车辆ID
	@Driver        varchar(50),   -- 驾驶员
	@Etypeid	   varchar(50),   -- 用车人
	@Destination   varchar(200),  -- 目的地
	@Use		   varchar(500),  -- 用途
	@Usestartdate  datetime,      -- 使用开始日期
	@Useenddate    datetime       -- 使用结束日期

	--@encode$--
AS
	-- 写入数据
	SET NOCOUNT ON;
	IF @Driver IS NULL OR @Driver=''
		BEGIN
			SET @Driver=''
		END
	INSERT INTO CM_CarUseBill
		(
			BillNumberId,
			Comment,
			CarId,
			Driver,
			Etypeid,
			Destination,
			[Use],
			Usestartdate,
			Useenddate
			
		)
		VALUES
		(
			@BillNumberID,
			@comment,
			@CarId,
			@Driver,
			@Etypeid,
			@Destination,
			@Use,
			@Usestartdate,
			@Useenddate
		)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：陈守川
	日期：2011-11-18
	描述：保存车辆使用登记索引
*/
CREATE PROCEDURE [dbo].[GP_InsertCarUseIndex]
	@BillNumberID numeric(11,0),
	@BillDate varchar(50),    -- 单据日期
	@BillCode varchar(200),   -- 单据编号
    @BillType numeric(10,0),  -- 单据类型
    @Comment  varchar(256),   -- 备注
    @Stypeid  varchar(50),    -- 经手人
    @Etypeid  varchar(50),    -- 分支机构
    @Dtypeid  varchar(50),	  -- 部门
    @period	  SMALLINT,
    @checke   varchar(50),	  --制单人
    @Explain  varchar(256)    -- 说明
	--@encode$--
AS
	-- 写入数据
SET NOCOUNT ON;

--*******************************************检查start*******************************************
	DECLARE @N int, @intVersion int

	-- 判断版本号，是否试用版
	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 2	-- 版本号

	IF @N IS NULL RETURN -1

	DECLARE @intBit int, @intMask int
	SELECT @intBit = @N & 15
	SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
	SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)
	-- ********	判断是否试用版 - END	********

	DECLARE @Re int,@Flag int
	EXEC @Re=Gp_Validate 2, @Flag OUTPUT
	IF @Re <>0 RETURN -3 --检查程序版本错误

	IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
	BEGIN
		--RAISERROR('校验错误 ！',16,1) 
		RETURN -3 --检查程序版本错误
	END

	IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
	BEGIN
		DECLARE @billnumberidtmp int
		SELECT @billnumberidtmp=ISNULL(COUNT(billnumberid),0) FROM billindex
		
		IF @billnumberidtmp > 200
		BEGIN
			--RAISERROR('试用版 ！',16,1) 
			RETURN -1
		END
	END  
--*******************************************检查end*******************************************	

--*****************************************单据日期检查start***********************************
	DECLARE @szPeriod [SMALLINT]
	DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
	EXEC Gp_GetSubValue 'period',@STypeID,@szPeriod out
	SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
	IF @BillDate<@BeginDate 
		BEGIN 
			--RAISERROR('录单日期小于本期开始日期 ！',16,1)
			RETURN -2
		END
	---根据配置检查过帐日期是否当前日期
	DECLARE @CurDate datetime
	DECLARE @IsOrNotPassOneDay bit
	SELECT @CurDate=GETDATE()
	SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
	IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
		BEGIN 
			--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
			RETURN -4
		END
--*****************************************单据日期检查end************************************

IF @BillNumberID=0
BEGIN
	INSERT INTO CM_CarUseIndex
	(
		BillDate,
		BillCode,
		BillType,
		Comment,
		Stypeid,
		Etypeid,
		Dtypeid,
		checke,
		Explain
	)
	VALUES
	(
		@BillDate,
		@BillCode,
		@BillType,
		@Comment,
		@Stypeid,
		@Etypeid,
		@dtypeid,
		@checke,
		@explain  
	)
	select @BillNumberId=SCOPE_IDENTITY();
	RETURN @BillNumberId
END
ELSE
BEGIN
	UPDATE CM_CarUseIndex
	SET	BillDate=@BillDate,
		BillCode=@BillCode,
		BillType=@BillType,
		Comment=@Comment,
		Stypeid=@Stypeid,
		Etypeid=@Etypeid,
		Dtypeid=@dtypeid,
		checke=@checke,
		Explain=@explain
	WHERE	BillNumberId= @BillNumberId
	DELETE FROM CM_CarUseBill WHERE BillNumberID=@BillNumberId
	RETURN @BillNumberId
	IF @@rowcount =0  or @@error<>0
		RAISERROR('更新单据发生错误！',16,1)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE     PROCEDURE GP_InsertCashMoneyBill
(@billnumberid  int,
 @atypeid       varchar(50),
 @total          NUMERIC(24, 10) ,
 @comment       varchar(255)
)
--@encode$--
as
SET NOCOUNT ON
insert into [Moneybill]
           ([billnumberid],
            [atypeid],
            [total],
            [comment])
values  (@billnumberid,
         @atypeid,
         dbo.F_RoundTotal(@total),
         @comment)
if @@rowcount=0 return 0 else return 1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertChargeOffBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertChargeOffBillDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：施训果
	时间：
	描述：添加往来核销单详细
*/
CREATE PROCEDURE GP_InsertChargeOffBillDT
	@tb TbType_ChargeOff READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	--数据检测
	DECLARE @Re INT
	EXEC @Re = Gp_Fz_Base '',2
	IF @Re <> 0
	BEGIN
		RAISERROR('发生未知错误！',16,1)
	END
	
	DELETE A FROM dbo.ChargeOffBill A,@tb B WHERE A.BillNumberID=B.BillNumberID 
	
	INSERT INTO dbo.ChargeOffBill
	        ( 
	          BillNumberId ,
	          FromBillNumberid ,
	          ChargeOffType ,
	          IsCharged ,
	          BTypeID ,
	          ChargeOffValue ,
	          NChargeOffValue,
	          FromBillType,
	          FromBillID,
	          TeamNo,
	          Comment,
	          ShowOrder
	        )
	         SELECT 
	          BillNumberId ,
	          FromBillNumberid ,
	          ChargeOffType ,
	          IsCharged ,
	          BTypeID ,
	          ChargeOffValue ,
	          NChargeOffValue,
	          FromBillType,
	          FromBillID,
	          TeamNo,
	          Comment,
	          ShowOrder
	FROM @tb
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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














/****** Object:  Stored Procedure dbo.Gp_InsertCheckStock    Script Date: 2002-6-20 10:14:48 ******/

CREATE  PROCEDURE [Gp_InsertCheckStock]
(@ptypeid varchar(30),
 @ktypeid varchar(30),
 @qty   NUMERIC(24, 10) ,
 @lossqty  NUMERIC(24, 10) ,
 @comment varchar(256))
--@encode$--
AS
SET NOCOUNT ON
if exists(select * from CheckStock a where a.ptypeid=@ptypeid and a.ktypeid=@ktypeid)
 update CheckStock 
  set Qty=dbo.F_RoundQty(@qty),
      lossqty=dbo.F_RoundQty(@lossQty), 
      comment=@comment 
  where ptypeid=@ptypeid and ktypeid=@ktypeid
else
 insert into CheckStock
  (ptypeid,ktypeid,qty,lossqty,comment)  values (@ptypeid,@ktypeid,@qty,@lossqty,@comment)
if @@ROWCOUNT=0 return -1 else return 0















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO
--组合品模版表头保存
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertCombinationBillDetail',N'P'))
BEGIN
	DROP PROC  GP_InsertCombinationBillDetail
END
GO
CREATE PROC GP_InsertCombinationBillDetail
(	
	@CombinationProductID INT, 
	@Ptypeid  VARCHAR(50),
	@Unit	  INT,  
	@Qty	  NUMERIC(24,10),   
	@Price	  NUMERIC(24,10),  
	@Remark	  VARCHAR(500), 
	@ItemId   INT,  
	@Standard VARCHAR(50), 
	@Barcode  VARCHAR(50),
	@Total	  NUMERIC(24,10)
)
AS
BEGIN
	INSERT INTO  CombinationProductDetail
	(
		CombinationProductID, 
		Ptypeid,
		Unit,  
		Qty,   
		Price,  
		Remark, 
		ItemId,  
		[Standard], 
		Barcode,
		Total
	)	
	VALUES
	(
		@CombinationProductID, 
		@Ptypeid,
		@Unit,  
		@Qty,   
		@Price,  
		@Remark, 
		@ItemId,  
		@Standard, 
		@Barcode,
		@Total
	)
END




GO
--组合品模版表头保存
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertCombinationIndex',N'P'))
BEGIN
	DROP PROC  GP_InsertCombinationIndex
END
GO
CREATE PROC GP_InsertCombinationIndex
(
	@CombinationProductID		INT,
	@CombinationProductPTypeID	VARCHAR(100),
	@ETypeID					VARCHAR(50),
	@DTypeID					VARCHAR(50),
	@Summary					VARCHAR(500),
	@BarCode					VARCHAR(50),
	@Price						NUMERIC(24,10),
	@CombinationProductUnit		INT,
	@IsStop	 INT,
	@IsCheck INT
)
AS
BEGIN
	   DECLARE @CombinationProductUserCode VARCHAR(100),
			   @CombinationProductFullName VARCHAR(100)
	   SELECT @CombinationProductUserCode=UserCode,@CombinationProductFullName=Fullname FROM dbo.ptype WHERE typeId=@CombinationProductPTypeID
	   IF @CombinationProductID>0
	   BEGIN
			UPDATE CombinationProductIndex 
			SET 
			CombinationProductPTypeID=@CombinationProductPTypeID,
			CombinationProductUserCode=@CombinationProductUserCode,
			CombinationProductFullName=@CombinationProductFullName,
			ETypeID=@ETypeID,
			DTypeID=@DTypeID,
			BarCode=@BarCode,
			Summary=@Summary,
			Price=@Price,
			CombinationProductUnit=@CombinationProductUnit,
			IsStop=@IsStop,
			IsCheck=@IsCheck		
			FROM CombinationProductIndex
			WHERE CombinationProductID=@CombinationProductID	
			DELETE FROM CombinationProductDetail WHERE CombinationProductID=@CombinationProductID
	   END
	   ELSE
	   BEGIN
			INSERT INTO  CombinationProductIndex
			(
				CombinationProductPTypeID,
				CombinationProductUserCode,
				CombinationProductFullName,
				ETypeID,
				DTypeID,
				BarCode,
				Summary,
				Price,
				CombinationProductUnit,
				IsStop,
				IsCheck		
			)	
			VALUES
			(
				@CombinationProductPTypeID,
				@CombinationProductUserCode,
				@CombinationProductFullName,
				@ETypeID,
				@DTypeID,
				@BarCode,
				@Summary,
				@Price,
				@CombinationProductUnit,
				@IsStop,
				@IsCheck
			)
	  SET @CombinationProductID=@@IDENTITY
	  END
	  
      DECLARE @XiWaMaxNumber NUMERIC(18, 0)
	  SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
	  FROM    PType
	  UPDATE  PType
	  SET     XiWaMaxNumber = @XiWaMaxNumber
	  WHERE   TypeId = @CombinationProductPTypeID
	  RETURN  @CombinationProductID
END




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：罗淮文
时间：2016-07-19
描述：写入组合品销售退货单明细表(表值)
*/
CREATE              PROCEDURE [Gp_InsertCombinationSaleBackBillDetailDT]
(
	@details TBType_CombinationSaleBack READONLY
)
--@encode$--
AS 
SET NOCOUNT ON
	
DECLARE @BillNumberID VARCHAR(50)

SELECT TOP 1 @BillNumberID = BillNumberID FROM @Details
--期初单据不处理草稿库存
IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
BEGIN
	-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
	EXEC GP_Deal_DraftQTY @BillNumberID,46,'-'
END		
DELETE A FROM dbo.PT_Combin_SaleBackBillDetail A,@Details B WHERE A.BillNumberId=B.BillNumberId AND 
	   NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID
											 AND A.BillNumberiD=B.BillNumberiD
											 AND A.OldBillNumberID=B.OldBillNumberID
											 AND A.OldID=B.OldID
											 AND B.ID<>0)

INSERT INTO [dbo].[PT_Combin_SaleBackBillDetail] 
  ( 
	[BillNumberId],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[OutFactoryDate],
	[TaxPrice],
	[TaxTotal],
	[comment],
	[isUnit2],
	[Serial],
	[OldID],
	[OldBillNumberID],
	--[CostPrice],
	[InputCostPrice],
	[GoodsNumber],
	[ProduceDate],
	[ValidDate],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost],
	Tax,
	SaleTotal,
	KTypeID,
	STypeID,
	FromBillNumberID,
	FromBillID
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,CompleteQTY
	
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,IsGift
	,ReferPrice
	,PriceStyle
	,PromoType
	,CompleteTotal
	,NCompleteTotal
	,pindexid
	,combinationptypeid
	,ShowOrder
	,PriceSource
) 
SELECT 
	BillNumberId,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	JobNo,
	dbo.F_RoundTotal(total),
	MakeDate,
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	intisUnit2,
	Serial,
	OldID,
	OldBillNumberID,
	--CostPrice,
	dbo.F_RoundPrice(InputCostPrice),
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	KTypeID,
	STypeID,
	FromBillNumberID,
	FromBillID
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoId
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined
	,dbo.F_RoundQty(CompleteQTY)
	,dbo.F_RoundQty(InvoiceQty)
	,dbo.F_RoundTotal(InvoiceMoney)
	,dbo.F_RoundTotal(NInvoiceMoney)
	,IsGift
	,dbo.F_RoundPrice(ReferPrice)
	,PriceStyle
	,PromoType
	,dbo.F_RoundTotal(CompleteTotal)
	,dbo.F_RoundTotal(NCompleteTotal)	
	,pindexid
	,combinationptypeid
	,ShowOrder	
	,PriceSource		
	--尽量减少碰撞吧，ID不可行
	FROM @details A WHERE ID=0 OR NOT EXISTS(SELECT ID FROM dbo.PT_Combin_SaleBackBillDetail B WHERE A.ID=B.ID
																				 AND A.BillNumberiD=B.BillNumberiD
																				 AND A.OldBillNumberID=B.OldBillNumberID
																				 AND A.OldID=B.OldID)

UPDATE A SET	PtypeId=B.PTypeID,
				Qty=B.Qty,
				SalePrice=B.SalePrice,
				discount=B.Discount,
				DiscountPrice=B.DiscountPrice,
				jobnumber=B.JobNo,
				total=B.Total,
				OutFactoryDate=B.MakeDate,
				TaxPrice=B.TaxPrice,
				TaxTotal=B.TaxTotal,
				comment=B.Comment,
				isUnit2=B.IntIsUnit2,
				Serial=B.Serial,
				OldID=B.OldID,
				OldBillNumberID=B.OldBillNumberID,
				InputCostPrice=B.InputCostPrice,
				GoodsNumber=B.GoodsNumber,
				ProduceDate=B.ProduceDate,
				ValidDate=B.ValidDate,
				GoodsBTypeID=B.GoodsBTypeID,
				GoodsCostPrice=B.GoodsCostPrice,
				HandZeroCost=B.HandZeroCost,
				Tax=B.Tax,
				SaleTotal=B.SaleTotal,
				KTypeID=B.KTypeID,
				STypeID=B.STypeID,
				FromBillNumberID=B.FromBillNumberID,
				FromBillID=B.FromBillID,
				TaxMoney=B.TaxMoney,
				NSalePrice=B.NSalePrice,
				NSaleTotal=B.NSaleTotal,
				NDiscountPrice=B.NDiscountPrice,
				NTotal=B.NTotal,
				NTaxPrice=B.NTaxPrice,
				NTaxTotal=B.NTaxTotal,
				NTaxMoney=B.NTaxMoney,
				CargoId=B.CargoID,
				UnitId=B.UnitID,
				NUnitId=B.NUnitID,
				NQty=B.NQty,
				UnitRate=B.UnitRate,
				NUnitMsg=B.NUnitMsg,
				MUnitId=B.MUnitID,
				MQty=B.MQty,
				MUnitRate=B.MUnitRate,
				MUnitMsg=B.MUnitMsg,
				MSalePrice=B.MSalePrice,
				MDiscountPrice=B.MDiscountPrice,
				MTaxPrice=B.MTaxPrice,
				CurMSalePrice=B.CurMSalePrice,
				CurMDiscountPrice=B.CurMDiscountPrice,
				CurMTaxPrice=B.CurMTaxPrice,
				ItemId=B.ItemID,
				IsCombined=B.IsCombined,
				CompleteQTY=B.CompleteQty,
				InvoiceQty=B.InvoiceQty,
				InvoiceMoney=B.InvoiceMoney,
				NInvoiceMoney=B.NInvoiceMoney,
				IsGift=B.IsGift,
				ReferPrice=B.ReferPrice,
				PriceStyle=B.PriceStyle,
				PromoType=B.PromoType,
				CompleteTotal=B.CompleteTotal,
				NCompleteTotal=B.NCompleteTotal,
				pindexid=B.pindexid,
				combinationptypeid = B.combinationptypeid,
				ShowOrder=B.ShowOrder,
				PriceSource = b.PriceSource
FROM dbo.PT_Combin_SaleBackBillDetail A,@details B WHERE A.ID=B.ID
									 AND A.BillNumberiD=B.BillNumberiD
								 	 AND A.OldBillNumberID=B.OldBillNumberID
									 AND A.OldID=B.OldID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：罗淮文
时间：2016-07-19
描述：写入组合品销售退货单明细表(表值)
*/
CREATE              PROCEDURE [Gp_InsertCombinationSaleBackBillDT]
(
	@details TBType_CombinationSaleBack READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

DELETE A FROM dbo.PT_Combin_SaleBackBill A,@Details B WHERE A.BillNumberId=B.BillNumberId AND 
	   NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID
											 AND A.BillNumberiD=B.BillNumberiD
											 AND A.OldBillNumberID=B.OldBillNumberID
											 AND A.OldID=B.OldID
											 AND B.ID<>0)

INSERT INTO [dbo].[PT_Combin_SaleBackBill] 
  ( 
	[BillNumberId],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[OutFactoryDate],
	[TaxPrice],
	[TaxTotal],
	[comment],
	[isUnit2],
	[OldID],
	[OldBillNumberID],
	--[CostPrice],
	[InputCostPrice],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost],
	Tax,
	SaleTotal,
	KTypeID,
	STypeID,
	FromBillNumberID,
	FromBillID
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,CompleteQTY
	
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,IsGift
	,ReferPrice
	,PriceStyle
	,PromoType
	,CompleteTotal
	,NCompleteTotal
	,pindexid
	,ShowOrder
	,PriceSource
	,Couponcode
) 
SELECT 
	BillNumberId,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	JobNo,
	dbo.F_RoundTotal(total),
	MakeDate,
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	intisUnit2,
	OldID,
	OldBillNumberID,
	--CostPrice,
	dbo.F_RoundPrice(InputCostPrice),
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	KTypeID,
	STypeID,
	FromBillNumberID,
	FromBillID
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoId
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined
	,dbo.F_RoundQty(CompleteQTY)
	,dbo.F_RoundQty(InvoiceQty)
	,dbo.F_RoundTotal(InvoiceMoney)
	,dbo.F_RoundTotal(NInvoiceMoney)
	,IsGift
	,dbo.F_RoundPrice(ReferPrice)
	,PriceStyle
	,PromoType
	,dbo.F_RoundTotal(CompleteTotal)
	,dbo.F_RoundTotal(NCompleteTotal)	
	,pindexid
	,ShowOrder			
	,PriceSource
	,ISNULL(Couponcode,'')
	--尽量减少碰撞吧，ID不可行
	FROM @details A WHERE ID=0 OR NOT EXISTS(SELECT ID FROM dbo.PT_Combin_SaleBackBill B WHERE A.ID=B.ID
																				 AND A.BillNumberiD=B.BillNumberiD
																				 AND A.OldBillNumberID=B.OldBillNumberID
																				 AND A.OldID=B.OldID)

UPDATE A SET	PtypeId=B.PTypeID,
				Qty=B.Qty,
				SalePrice=B.SalePrice,
				discount=B.Discount,
				DiscountPrice=B.DiscountPrice,
				jobnumber=B.JobNo,
				total=B.Total,
				OutFactoryDate=B.MakeDate,
				TaxPrice=B.TaxPrice,
				TaxTotal=B.TaxTotal,
				comment=B.Comment,
				isUnit2=B.IntIsUnit2,
				OldID=B.OldID,
				OldBillNumberID=B.OldBillNumberID,
				InputCostPrice=B.InputCostPrice,
				GoodsBTypeID=B.GoodsBTypeID,
				GoodsCostPrice=B.GoodsCostPrice,
				HandZeroCost=B.HandZeroCost,
				Tax=B.Tax,
				SaleTotal=B.SaleTotal,
				KTypeID=B.KTypeID,
				STypeID=B.STypeID,
				FromBillNumberID=B.FromBillNumberID,
				FromBillID=B.FromBillID,
				TaxMoney=B.TaxMoney,
				NSalePrice=B.NSalePrice,
				NSaleTotal=B.NSaleTotal,
				NDiscountPrice=B.NDiscountPrice,
				NTotal=B.NTotal,
				NTaxPrice=B.NTaxPrice,
				NTaxTotal=B.NTaxTotal,
				NTaxMoney=B.NTaxMoney,
				CargoId=B.CargoID,
				UnitId=B.UnitID,
				NUnitId=B.NUnitID,
				NQty=B.NQty,
				UnitRate=B.UnitRate,
				NUnitMsg=B.NUnitMsg,
				MUnitId=B.MUnitID,
				MQty=B.MQty,
				MUnitRate=B.MUnitRate,
				MUnitMsg=B.MUnitMsg,
				MSalePrice=B.MSalePrice,
				MDiscountPrice=B.MDiscountPrice,
				MTaxPrice=B.MTaxPrice,
				CurMSalePrice=B.CurMSalePrice,
				CurMDiscountPrice=B.CurMDiscountPrice,
				CurMTaxPrice=B.CurMTaxPrice,
				ItemId=B.ItemID,
				IsCombined=B.IsCombined,
				CompleteQTY=B.CompleteQty,
				InvoiceQty=B.InvoiceQty,
				InvoiceMoney=B.InvoiceMoney,
				NInvoiceMoney=B.NInvoiceMoney,
				IsGift=B.IsGift,
				ReferPrice=B.ReferPrice,
				PriceStyle=B.PriceStyle,
				PromoType=B.PromoType,
				CompleteTotal=B.CompleteTotal,
				NCompleteTotal=B.NCompleteTotal,
				pindexid=B.pindexid,
				ShowOrder=B.ShowOrder,
				PriceSource = b.PriceSource,
				Couponcode=ISNULL(b.Couponcode,'')
FROM dbo.PT_Combin_SaleBackBill A,@details B WHERE A.ID=B.ID
									 AND A.BillNumberiD=B.BillNumberiD
								 	 AND A.OldBillNumberID=B.OldBillNumberID
									 AND A.OldID=B.OldID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCombinationSaleBillDetailsDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCombinationSaleBillDetailsDT
GO

/*
作者：罗淮文
描述：写入组合品销售出库单明细表(表值)
日期：2016-07-14
*/
CREATE PROCEDURE Gp_InsertCombinationSaleBillDetailsDT
(
	@details TBType_CombinationSale READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
DECLARE @Re INT
EXEC @Re = Gp_Fz_Base '',2
IF @Re <> 0
BEGIN
	RAISERROR('发生未知错误！',16,1)
END

DECLARE @BillNumberID VARCHAR(50)
		
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

-- 更新待收货数量
	UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
	FROM PT_Combin_OrderBillDetail a 
	JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM @details b WHERE b.OrderId<>-1 GROUP BY orderid)b ON b.orderid=a.OrderID
	
	UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
	FROM PT_Combin_OrderBill a 
	JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM @details b WHERE b.OrderId<>-1 GROUP BY orderid)b ON b.orderid=a.OrderID

--期初单据不处理草稿库存
IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
BEGIN
	-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
	EXEC GP_Deal_DraftQTY @BillNumberID,12,'-'

	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f' AND draft=1)
	BEGIN
		-- 处理订单库存,先减去引用未过账数量
		EXEC GP_Deal_OrderReferQty @BillnumberID,12,'-'
	END
	ELSE
	BEGIN
		-- 处理订单库存,先减去过账数量
		EXEC GP_Deal_OrderReachQTY @BillnumberID,12,'-'
	END
END
	
DELETE A FROM dbo.PT_Combin_SaleBillDetail A,@details B WHERE A.BillNumberId=B.BillNumberID AND NOT EXISTS(
			   SELECT ID FROM @details B WHERE A.BillNumberID=B.BillNumberID 
										   AND A.OrderID=B.OrderID 
										   AND A.ID=B.ID
										   AND A.BillNumberID=B.BillNumberId
										   AND B.ID<>0)

INSERT INTO PT_Combin_SaleBillDetail
(
	BillNumberId,
	PtypeId,
	Qty,
	SalePrice,
	discount,
	DiscountPrice,
	jobnumber,
	total,
	OutFactoryDate,
	TaxPrice,
	TaxTotal,
	comment,
	OrderID,
	isUnit2,
	Serial,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	Tax,
	SaleTotal,
	KTypeID,
	STypeID,
	ShareFee
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,completeqty
	,CompleteTotal
	,NCompleteTotal
	,entryCode
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,PriceSource
	,IsGift
	,BeforePromoID
	,ReferPrice
	,PriceStyle
	,PromoType
	,LendBillID
	,LendBillNumberID
	,ShowOrder
	,diyid
	,pindexid
	,combinationptypeid
	,PriceDetailId
	,PriceRuleId
)
SELECT 
	BillNumberId,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	jobnumber,
	dbo.F_RoundTotal(total),
	OutFactoryDate,
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	OrderID,
	intisUnitTow,
	Serial,
	dbo.F_RoundPrice(InputCostPrice),
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	KTypeID,
	STypeID,
	0
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoId
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined
	,dbo.F_RoundQty(completeqty)
	,dbo.F_RoundTotal(CompleteTotal)
	,dbo.F_RoundTotal(NCompleteTotal)
	,entryCode
	,dbo.F_RoundQty(InvoiceQty)
	,dbo.F_RoundTotal(InvoiceMoney)
	,dbo.F_RoundTotal(NInvoiceMoney)
	,PriceSource
	,IsGift
	,BeforePromoID
	,dbo.F_RoundPrice(ReferPrice)
	,PriceStyle
	,PromoType
	,LendBillID
	,LendBillNumberID
	,ShowOrder	
	,diyid
	,pindexid
	,combinationptypeid
	,PriceDetailId
	,PriceRuleId
	--尽量减少碰撞吧，ID不可行
	FROM @details A WHERE ID=0 OR NOT EXISTS (
		SELECT ID FROM dbo.PT_Combin_SaleBillDetail B WHERE A.BillNumberID=B.BillNumberID 
										AND A.OrderID=B.OrderID 
										AND A.ID=B.ID
										AND A.BillNumberID=B.BillNumberId)

UPDATE A SET	PtypeId=B.PTypeID,
				Qty=B.Qty,
				SalePrice=dbo.F_RoundPrice(B.SalePrice),
				discount=dbo.F_RoundDiscount(B.Discount),
				DiscountPrice=dbo.F_RoundPrice(B.DiscountPrice),
				jobnumber=B.jobnumber,
				total=dbo.F_RoundTotal(B.Total),
				OutFactoryDate=B.OutFactoryDate,
				TaxPrice=dbo.F_RoundPrice(B.TaxPrice),
				TaxTotal=dbo.F_RoundTotal(B.TaxTotal),
				comment=B.comment,
				OrderID=B.OrderID,
				isUnit2=B.intisUnitTow,
				Serial=B.Serial,
				InputCostPrice=dbo.F_RoundPrice(B.InputCostPrice),
				GoodsNumber=B.GoodsNumber,
				ProduceDate=B.ProduceDate,
				ValidDate=B.ValidDate,
				GoodsBTypeID=B.GoodsBTypeID,
				GoodsCostPrice=dbo.F_RoundPrice(B.GoodsCostPrice),
				HandZeroCost=B.HandZeroCost,
				Tax=dbo.F_RoundTax(B.Tax),
				SaleTotal=dbo.F_RoundTotal(B.SaleTotal),
				KTypeID=B.KTypeID,
				STypeID=B.STypeID,
				ShareFee=0,
				TaxMoney=dbo.F_RoundTotal(B.TaxMoney)
				,NSalePrice=dbo.F_RoundPrice(B.NSalePrice)
				,NSaleTotal=dbo.F_RoundTotal(B.NSaleTotal)
				,NDiscountPrice=dbo.F_RoundPrice(B.NDiscountPrice)
				,NTotal=dbo.F_RoundTotal(B.NTotal)
				,NTaxPrice=dbo.F_RoundPrice(B.NTaxPrice)
				,NTaxTotal=dbo.F_RoundTotal(B.NTaxTotal)
				,NTaxMoney=dbo.F_RoundTotal(B.NTaxMoney)
				,CargoId=B.CargoID
				,UnitId=B.UnitID
				,NUnitId=B.NUnitID
				,NQty=dbo.F_RoundQty(B.NQty)
				,UnitRate=B.UnitRate
				,NUnitMsg=B.NUnitMsg
				,MUnitId=B.MunitID
				,MQty=dbo.F_RoundQty(B.MQty)
				,MUnitRate=B.MUnitRate
				,MUnitMsg=B.MUnitMsg
				,MSalePrice=dbo.F_RoundPrice(B.MSalePrice)
				,MDiscountPrice=dbo.F_RoundPrice(B.MDiscountPrice)
				,MTaxPrice=dbo.F_RoundPrice(B.MTaxPrice)
				,CurMSalePrice=dbo.F_RoundPrice(B.CurMSalePrice)
				,CurMDiscountPrice=dbo.F_RoundPrice(B.CurMDiscountPrice)
				,CurMTaxPrice=dbo.F_RoundPrice(B.CurMTaxPrice)
				,ItemId=B.ItemID
				,IsCombined=B.IsCombined
				,completeqty=dbo.F_RoundQty(B.CompleteQty)
				,CompleteTotal=dbo.F_RoundTotal(B.CompleteTotal)
				,NCompleteTotal=dbo.F_RoundTotal(B.NCompleteTotal)
				,entryCode=B.EntryCode
				,InvoiceQty=dbo.F_RoundQty(B.InvoiceQty)
				,InvoiceMoney=dbo.F_RoundTotal(B.InvoiceMoney)
				,NInvoiceMoney=dbo.F_RoundTotal(B.NInvoiceMoney)
				,PriceSource=B.PriceSource
				,IsGift=B.IsGift
				,BeforePromoID=B.BeforePromoID
				,ReferPrice=B.ReferPrice
				,PriceStyle=B.PriceStyle
				,PromoType=B.PromoType
				,LendBillID=B.LendBillID
				,LendBillNumberID=B.LendBillNumberID
				,ShowOrder=B.ShowOrder
				,diyid=B.diyid
				,pindexid=B.pindexid
				,combinationptypeid=B.combinationptypeid
				,a.PriceDetailId =  b.PriceDetailId
				,a.PriceRuleId = b.PriceRuleId
 FROM dbo.PT_Combin_SaleBillDetail A,@details B WHERE A.BillNumberID=B.BillNumberID 
								  AND A.OrderID=B.OrderID 
								  AND A.ID=B.ID
								  AND A.BillNumberID=B.BillNumberId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCombinationSaleBillDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCombinationSaleBillDT
GO

/*
作者：罗淮文
描述：写入组合品销售出库单明细表(表值)
日期：2016-07-14
*/
CREATE PROCEDURE Gp_InsertCombinationSaleBillDT
(
	@details TBType_CombinationSale READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
DECLARE @Re INT
EXEC @Re = Gp_Fz_Base '',2
IF @Re <> 0
BEGIN
	RAISERROR('发生未知错误！',16,1)
END

DECLARE @BillNumberID VARCHAR(50)	
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details
IF EXISTS(SELECT TOP 1 1 FROM PT_Combin_SaleBill WHERE BillNumberId=@BillNumberID)
BEGIN
	DELETE A FROM dbo.PT_Combin_SaleBill A,@details B WHERE A.BillNumberId=B.BillNumberID AND NOT EXISTS(
				   SELECT ID FROM @details B WHERE A.BillNumberID=B.BillNumberID 
											   AND A.OrderID=B.OrderID 
											   AND A.ID=B.ID
											   AND B.ID<>0)

	INSERT INTO PT_Combin_SaleBill
	(
		BillNumberId,
		PtypeId,
		Qty,
		SalePrice,
		discount,
		DiscountPrice,
		jobnumber,
		total,
		OutFactoryDate,
		TaxPrice,
		TaxTotal,
		comment,
		OrderID,
		isUnit2,
		InputCostPrice,
		GoodsBTypeID,
		GoodsCostPrice,
		HandZeroCost,
		Tax,
		SaleTotal,
		KTypeID,
		STypeID,
		ShareFee
		--9.0新字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,CargoId
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		,completeqty
		,CompleteTotal
		,NCompleteTotal
		,entryCode
		,InvoiceQty
		,InvoiceMoney
		,NInvoiceMoney
		,PriceSource
		,IsGift
		,BeforePromoID
		,ReferPrice
		,PriceStyle
		,PromoType
		,LendBillID
		,LendBillNumberID
		,ShowOrder
		,diyid
		,pindexid
		,PromonIds
		,CouponCode
		,IsVipPoint
		,IsPromotion
	)
	SELECT 
		BillNumberId,
		PtypeId,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(discount),
		dbo.F_RoundPrice(DiscountPrice),
		jobnumber,
		dbo.F_RoundTotal(total),
		OutFactoryDate,
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		comment,
		OrderID,
		intisUnitTow,
		dbo.F_RoundPrice(InputCostPrice),
		GoodsBTypeID,
		dbo.F_RoundPrice(GoodsCostPrice),
		HandZeroCost,
		dbo.F_RoundTax(Tax),
		dbo.F_RoundTotal(SaleTotal),
		KTypeID,
		STypeID,
		0
		--9.0新字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,dbo.F_RoundQty(completeqty)
		,dbo.F_RoundTotal(CompleteTotal)
		,dbo.F_RoundTotal(NCompleteTotal)
		,entryCode
		,dbo.F_RoundQty(InvoiceQty)
		,dbo.F_RoundTotal(InvoiceMoney)
		,dbo.F_RoundTotal(NInvoiceMoney)
		,PriceSource
		,IsGift
		,BeforePromoID
		,dbo.F_RoundPrice(ReferPrice)
		,PriceStyle
		,PromoType
		,LendBillID
		,LendBillNumberID
		,ShowOrder	
		,diyid
		,pindexid
		,ISNULL(PromonIds,'')
		,ISNULL(CouponCode,'')
		,IsVipPoint
		,IsPromotion
		--尽量减少碰撞吧，ID不可行
		FROM @details A WHERE ID=0 OR NOT EXISTS (
			SELECT ID FROM dbo.PT_Combin_SaleBill B WHERE A.BillNumberID=B.BillNumberID 
											AND A.OrderID=B.OrderID 
											AND A.ID=B.ID)

	UPDATE A SET	PtypeId=B.PTypeID,
					Qty=B.Qty,
					SalePrice=dbo.F_RoundPrice(B.SalePrice),
					discount=dbo.F_RoundDiscount(B.Discount),
					DiscountPrice=dbo.F_RoundPrice(B.DiscountPrice),
					jobnumber=B.jobnumber,
					total=dbo.F_RoundTotal(B.Total),
					OutFactoryDate=B.OutFactoryDate,
					TaxPrice=dbo.F_RoundPrice(B.TaxPrice),
					TaxTotal=dbo.F_RoundTotal(B.TaxTotal),
					comment=B.comment,
					OrderID=B.OrderID,
					isUnit2=B.intisUnitTow,
					InputCostPrice=dbo.F_RoundPrice(B.InputCostPrice),
					GoodsBTypeID=B.GoodsBTypeID,
					GoodsCostPrice=dbo.F_RoundPrice(B.GoodsCostPrice),
					HandZeroCost=B.HandZeroCost,
					Tax=dbo.F_RoundTax(B.Tax),
					SaleTotal=dbo.F_RoundTotal(B.SaleTotal),
					KTypeID=B.KTypeID,
					STypeID=B.STypeID,
					ShareFee=0,
					TaxMoney=dbo.F_RoundTotal(B.TaxMoney)
					,NSalePrice=dbo.F_RoundPrice(B.NSalePrice)
					,NSaleTotal=dbo.F_RoundTotal(B.NSaleTotal)
					,NDiscountPrice=dbo.F_RoundPrice(B.NDiscountPrice)
					,NTotal=dbo.F_RoundTotal(B.NTotal)
					,NTaxPrice=dbo.F_RoundPrice(B.NTaxPrice)
					,NTaxTotal=dbo.F_RoundTotal(B.NTaxTotal)
					,NTaxMoney=dbo.F_RoundTotal(B.NTaxMoney)
					,CargoId=B.CargoID
					,UnitId=B.UnitID
					,NUnitId=B.NUnitID
					,NQty=dbo.F_RoundQty(B.NQty)
					,UnitRate=B.UnitRate
					,NUnitMsg=B.NUnitMsg
					,MUnitId=B.MunitID
					,MQty=dbo.F_RoundQty(B.MQty)
					,MUnitRate=B.MUnitRate
					,MUnitMsg=B.MUnitMsg
					,MSalePrice=dbo.F_RoundPrice(B.MSalePrice)
					,MDiscountPrice=dbo.F_RoundPrice(B.MDiscountPrice)
					,MTaxPrice=dbo.F_RoundPrice(B.MTaxPrice)
					,CurMSalePrice=dbo.F_RoundPrice(B.CurMSalePrice)
					,CurMDiscountPrice=dbo.F_RoundPrice(B.CurMDiscountPrice)
					,CurMTaxPrice=dbo.F_RoundPrice(B.CurMTaxPrice)
					,ItemId=B.ItemID
					,IsCombined=B.IsCombined
					,completeqty=dbo.F_RoundQty(B.CompleteQty)
					,CompleteTotal=dbo.F_RoundTotal(B.CompleteTotal)
					,NCompleteTotal=dbo.F_RoundTotal(B.NCompleteTotal)
					,entryCode=B.EntryCode
					,InvoiceQty=dbo.F_RoundQty(B.InvoiceQty)
					,InvoiceMoney=dbo.F_RoundTotal(B.InvoiceMoney)
					,NInvoiceMoney=dbo.F_RoundTotal(B.NInvoiceMoney)
					,PriceSource=B.PriceSource
					,IsGift=B.IsGift
					,BeforePromoID=B.BeforePromoID
					,ReferPrice=B.ReferPrice
					,PriceStyle=B.PriceStyle
					,PromoType=B.PromoType
					,LendBillID=B.LendBillID
					,LendBillNumberID=B.LendBillNumberID
					,ShowOrder=B.ShowOrder
					,diyid=B.diyid
					,pindexid=B.pindexid
					,PromonIds=ISNULL(b.PromonIds,'')
					,CouponCode=ISNULL(b.CouponCode,'')
					,IsVipPoint=b.IsVipPoint
					,IsPromotion=b.IsPromotion
					FROM dbo.PT_Combin_SaleBill A,@details B WHERE A.BillNumberID=B.BillNumberID 
									  AND A.OrderID=B.OrderID 
									  AND A.ID=B.ID
END
ELSE
BEGIN
	INSERT INTO PT_Combin_SaleBill
	(
		BillNumberId,
		PtypeId,
		Qty,
		SalePrice,
		discount,
		DiscountPrice,
		jobnumber,
		total,
		OutFactoryDate,
		TaxPrice,
		TaxTotal,
		comment,
		OrderID,
		isUnit2,
		InputCostPrice,
		GoodsBTypeID,
		GoodsCostPrice,
		HandZeroCost,
		Tax,
		SaleTotal,
		KTypeID,
		STypeID,
		ShareFee
		--9.0新字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,CargoId
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		,completeqty
		,CompleteTotal
		,NCompleteTotal
		,entryCode
		,InvoiceQty
		,InvoiceMoney
		,NInvoiceMoney
		,PriceSource
		,IsGift
		,BeforePromoID
		,ReferPrice
		,PriceStyle
		,PromoType
		,LendBillID
		,LendBillNumberID
		,ShowOrder
		,diyid
		,pindexid
		,PromonIds
		,CouponCode
		,IsVipPoint
		,IsPromotion
	)
	SELECT 
		BillNumberId,
		PtypeId,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(discount),
		dbo.F_RoundPrice(DiscountPrice),
		jobnumber,
		dbo.F_RoundTotal(total),
		OutFactoryDate,
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		comment,
		OrderID,
		intisUnitTow,
		dbo.F_RoundPrice(InputCostPrice),
		GoodsBTypeID,
		dbo.F_RoundPrice(GoodsCostPrice),
		HandZeroCost,
		dbo.F_RoundTax(Tax),
		dbo.F_RoundTotal(SaleTotal),
		KTypeID,
		STypeID,
		0
		--9.0新字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,dbo.F_RoundQty(completeqty)
		,dbo.F_RoundTotal(CompleteTotal)
		,dbo.F_RoundTotal(NCompleteTotal)
		,entryCode
		,dbo.F_RoundQty(InvoiceQty)
		,dbo.F_RoundTotal(InvoiceMoney)
		,dbo.F_RoundTotal(NInvoiceMoney)
		,PriceSource
		,IsGift
		,BeforePromoID
		,dbo.F_RoundPrice(ReferPrice)
		,PriceStyle
		,PromoType
		,LendBillID
		,LendBillNumberID
		,ShowOrder	
		,diyid
		,pindexid
		,ISNULL(PromonIds,'')
		,CouponCode
		,IsVipPoint
		,IsPromotion
		FROM @details A 
END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertCommission]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertCommission]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE  PROCEDURE [Gp_InsertCommission]
    (
	@BillCode				VARCHAR(200),   --单据编号
	@FullName				VARCHAR(200)='',   --单据名称
	@BillDate				DATETIME  ,		 --单据日期 
	@PlanStart				DATETIME  ,
	@PlanEnd					DATETIME  ,
	@CommissionStandard		INT  ,			 --提成基准  1=销售额 2=价税合计
	@Checke					VARCHAR(50)  ,				--制单人
	@Comment					VARCHAR(256) ='',	--摘要
	@BillState				INT ,						--单据状态  1=未审核  2=审核  3=禁用
	@UseState				INT =0,			--使用状态  1=未引用  2=引用  3=部分完成 4=全部完成
	@IsStop					INT =0	,			--是否禁用  0=正常  1/2当禁用时写入单据状态 启用时写到单据状态列 起保存禁用时的状态
	@Checker				VARCHAR(50),   --审核人
	@CheckerTime			DATETIME ,		 --审核时间
	@SalePlanId				NUMERIC(18,0),   --关联计划ID
	@SalesFlag	INT ,			 --是否使用促销商品销售额不参与提成 1=勾选
	@BelowCostFlag 	INT		 --是否使用低于成本销售额不参与提成 1=勾选
	  )
--@encode$--
AS 
    SET NOCOUNT ON
    
IF @CheckerTime = ''
BEGIN
	SET @CheckerTime = NULL
END


    INSERT  INTO [dbo].ReferencePlanCommission
            ( 
BillCode	,		
FullName	,		
BillDate	,		
PlanStart	,		
PlanEnd		,	
CommissionStandard	,
Checke				,
CheckeTime			,
Comment			,
BillState		,	
UseState		,	
IsStop			,
Checker			,
CheckerTime		,
SalePlanId ,
SalesFlag,
BelowCostFlag
            )
    VALUES  ( 
@BillCode			,
@FullName			,
@BillDate			,
@PlanStart			,
@PlanEnd			,
@CommissionStandard	,
@Checke				,
GETDATE()			,
ISNULL(@Comment,'')			,
@BillState			,
@UseState			,
@IsStop				,
@Checker			,
@CheckerTime		,
@SalePlanId,
@SalesFlag,
@BelowCostFlag 
            )

    DECLARE @intReturn BIGINT

    SELECT  @intReturn = SCOPE_IDENTITY();

    RETURN @intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertCommissionBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertCommissionBillDT;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-05-04 13:44:17.917
	描述：受托单明细查入 Dt版
*/
CREATE PROCEDURE Gp_InsertCommissionBillDT
	@tb TbType_Commission READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @bt INT=0;
	SELECT TOP 1 @bt=BillType FROM @tb;
	
	-- 更新待收货数量
	UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
	FROM OrderBill a 
	JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM @tb b WHERE b.OrderId<>-1 GROUP BY orderid)b ON b.orderid=a.OrderID
	
	DECLARE @BillNumberID VARCHAR(50)	
	SELECT TOP 1 @BillNumberID = BillNumberID FROM @tb
	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
	BEGIN		
		IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f' AND draft=1)
		BEGIN
			-- 处理订单库存,先减去引用未过账数量
			EXEC GP_Deal_OrderReferQty @BillnumberID,@bt,'-'
		END
		ELSE
		BEGIN
			-- 处理订单库存,先减去过账数量
			EXEC GP_Deal_OrderReachQTY @BillnumberID,@bt,'-'
		END
	END

	INSERT INTO [CommissionBill](
		[BillNumberId],--0
		[Type],
		[PtypeId],
		[Qty],
		[SalePrice],
		[discount], --5
		[DiscountPrice],
		[jobnumber],
		[total],
		[OutFactoryDate],
		[TaxPrice],--10
		[TaxTotal],
		[comment],
		[orderid],
		[IsUnit2],
		[Serial],--15
		[OldID],
		[OldBillnumberID],
		[InputCostPrice],
		[GoodsNumber],
		[ProduceDate], --20
		[ValidDate],
		[GoodsBTypeID],
		[GoodsCostPrice],
		[HandZeroCost],
		[OldBillid], --25
		Tax,
		SaleTotal,
		KTypeID,
		STypeID
		
		-- 新增字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,CargoId
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		,completeqty
		,InvoiceQty
		,InvoiceMoney
		,NInvoiceMoney
		,ReferPrice
		,PriceStyle
		,CompleteTotal
		,NCompleteTotal
		,ShowOrder
		,PriceSource
	) SELECT 
		BillNumberId, --0
		BillType,
		PtypeId,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(discount),--5
		dbo.F_RoundPrice(DiscountPrice),
		jobno,
		dbo.F_RoundTotal(total),
		OutFactoryDate,
		dbo.F_RoundPrice(TaxPrice), --10
		dbo.F_RoundTotal(TaxTotal),
		comment,
		orderid,
		IsUnit2,
		Serial, --15
		OldID,
		CASE WHEN @bt in (142,146) THEN 0 ELSE OldBillNumberID END,
		dbo.F_RoundPrice(InputCostPrice),
		GoodsNumber,
		ProduceDate,--20
		ValidDate,
		GoodsBTypeID,
		dbo.F_RoundPrice(CASE WHEN @bt=144 THEN DiscountPrice ELSE GoodsCostPrice END),
		CASE WHEN BillType=144 AND KTypeID='10000' THEN 1 ELSE HandZeroCost END HandZeroCost,
		CASE WHEN @bt in(142,146) THEN OldBillNumberId ELSE 0 END ,--OldBillid
		dbo.F_RoundTax(Tax),--26
		dbo.F_RoundTotal(SaleTotal),
		CASE WHEN @bt=141 THEN '10000' ELSE KTypeID END,
		STypeID 
		
		-- 新字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,dbo.F_RoundQty(completeqty)
		,dbo.F_RoundQty(InvoiceQty)
		,dbo.F_RoundTotal(InvoiceMoney)
		,dbo.F_RoundTotal(NInvoiceMoney)
		,dbo.F_RoundPrice(ReferPrice)
		,PriceStyle
		,dbo.F_RoundTotal(CompleteTotal)
		,dbo.F_RoundTotal(NCompleteTotal)
		,ShowOrder
		,PriceSource
	FROM @tb;
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO




IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertCompleteBrandarBalance]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Gp_InsertCompleteBrandarBalance
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：shushan
	日期：2017-12-19
	描述：保存 按商品品牌结算
-------------------------------------------*/
CREATE PROCEDURE Gp_InsertCompleteBrandarBalance
(
	@MoneyBillNumberID 	NUMERIC(10,0),--单据ID
	@GoodBillNumberID	NUMERIC(10,0),
	@GoodsBillType		INT ,
	@isini			INT,
	@brandartypeid	VARCHAR(50),
	@CId			INT,--币种
	@NTaxTotal		NUMERIC(24,10) ,--原币价税合计金额（销售金额）
	@TaxTotal		NUMERIC(24,10),--价税合计金额（销售金额）
	@NCompleteTotal	NUMERIC(24,10) ,--原币结算金额
	@CompleteTotal	NUMERIC(24,10) ,--结算金额
	@Comment			VARCHAR(200),--备注
	@OperatorID		VARCHAR(50),
	@isAudit		INT ,
	@detailid		INT --应收增加 减少单
)
AS 
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @ERROR INT
IF(@GoodsBillType IN(405))
BEGIN
	IF NOT EXISTS(SELECT * FROM ReceiptBillIndex WHERE BillNumberId=@GoodBillNumberID)
		RETURN 1
END		
ELSE 
BEGIN
	IF NOT EXISTS(SELECT * FROM BillIndex WHERE BillNumberId=@GoodBillNumberID)
		RETURN 1
END		
	
--存在按单、按商品结算的
IF EXISTS(SELECT TOP 1 1 FROM BILLINDEX WHERE BillNumberId=@GoodBillNumberID AND jsStyle =1 AND @GoodsBillType  NOT IN(405,115,116,128,129))
OR EXISTS(SELECT TOP 1 1 FROM dbo.AdDebtBill WHERE BillNumberId=@GoodBillNumberID AND JsStyle=1 AND ID=@detailid)
OR EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberId=@GoodBillNumberID AND jsStyle=1 AND @GoodsBillType IN(405))
RETURN 3

--存在按单、按商品结算的
IF EXISTS(SELECT TOP 1 1 FROM BILLINDEX WHERE BillNumberId=@GoodBillNumberID AND jsStyle =2 AND @GoodsBillType NOT IN(405,115,116,128,129))
OR EXISTS(SELECT TOP 1 1 FROM dbo.AdDebtBill WHERE BillNumberId=@GoodBillNumberID AND JsStyle=2 AND ID=@detailid)
OR EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberId=@GoodBillNumberID AND jsStyle =2 AND @GoodsBillType IN(405))
RETURN 4

--存在核销
IF EXISTS(SELECT TOP 1 1 FROM BILLINDEX WHERE BillNumberId=@GoodBillNumberID AND  @GoodsBillType  NOT IN(405) AND ChargeOffTotal>0)
OR EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberId=@GoodBillNumberID AND @GoodsBillType IN(405) AND ChargeOffTotal>0)
RETURN 7


DECLARE @intBillType int,
		@TotalMoney_y  NUMERIC(24, 10) ,
		@TotalInMoney_y  NUMERIC(24, 10),
		@preferencemoney_y  NUMERIC(24, 10) ,
		@CompleteTotal_y  NUMERIC(24, 10) ,
		@NTotalMoney_y  NUMERIC(24, 10) ,
		@NTotalInMoney_y  NUMERIC(24, 10),
		@Npreferencemoney_y  NUMERIC(24, 10) ,
		@NCompleteTotal_y  NUMERIC(24, 10) ,
		@NChargeOffTotal_y	NUMERIC(24,10)

		
--存在 结算金额>未结算金额
IF @GoodsBillType IN (404,405)
	BEGIN
		SELECT @intBillType=BillType,@TotalMoney_y=TaxTotalMoney,@TotalInMoney_y=0,
		@preferencemoney_y=0,@CompleteTotal_y=CompleteTotal,
		@NTotalMoney_y=NTaxTotalMoney,
		@NTotalInMoney_y=0,
		@Npreferencemoney_y=0,
		@NCompleteTotal_y=NCompleteTotal,
		@NChargeOffTotal_y=NChargeOffTotal
		FROM ReceiptBillIndex WHERE BillnumberID=@GoodBillNumberID
	END
ELSE IF @GoodsBillType IN (115,116,128,129)
	BEGIN 
		SELECT @intBillType=bil.BillType,@TotalMoney_y=adb.total,@TotalInMoney_y=0,
		@preferencemoney_y=0,@CompleteTotal_y=adb.CompleteTotal,
		@NTotalMoney_y=adb.NTotal,
		@NTotalInMoney_y=0,
		@Npreferencemoney_y=0,
		@NCompleteTotal_y=adb.NCompleteTotal,
		@NChargeOffTotal_y=adb.NChargeOffTotal
		FROM dbo.AdDebtBill adb
		INNER JOIN billindex bil ON bil.BillNumberId = adb.BillNumberId
		 WHERE  adb.BillnumberID=@GoodBillNumberID AND adb.ID=@detailid
	END 
	ELSE
		SELECT @intBillType=BillType,@TotalMoney_y=TotalMoney,@TotalInMoney_y=TotalInMoney,
		@preferencemoney_y=preferencemoney,@CompleteTotal_y=CompleteTotal,
		@NTotalMoney_y=NTotalMoney,
		@NTotalInMoney_y=NTotalInMoney,
		@Npreferencemoney_y=Npreferencemoney,
		@NCompleteTotal_y=NCompleteTotal,
		@NChargeOffTotal_y=NChargeOffTotal
		FROM BillIndex WHERE BillnumberID=@GoodBillNumberID
IF (@NTotalMoney_y>=0 AND (@NTotalMoney_y-@Npreferencemoney_y) < @NCompleteTotal_y+@NTotalInMoney_y)
	OR (@NTotalMoney_y<0 AND (@NTotalMoney_y-@Npreferencemoney_y) > @NCompleteTotal_y+@NTotalInMoney_y)
				
RETURN 6 

--IF @isAudit=0 --草稿 
--	DELETE FROM CompleteBrandarTotal WHERE MoneyBillId=@MoneyBillNumberId AND GoodsBillID NOT IN (select GoodsBillID from Completetotal WHERE MoneyBillID=@MoneyBillNumberId) 
--IF @isAudit=1
--	DELETE FROM CompleteBrandarTotal WHERE MoneyBillid=@MoneyBillNumberID AND Goodsbillid=@GoodBillNumberID AND BillType=@GoodsBillType
	
DECLARE @Billdate datetime 

select @Billdate=getDate()
IF EXISTS (SELECT etypeid FROM Billindex WHERE BillnumberID =@MoneyBillNumberId)
		SELECT @Billdate =billdate FROM Billindex WHERE BillnumberID =@MoneyBillNumberId
				
INSERT INTO CompleteBrandarTotal
(
	GoodsBillID,	
	MoneyBillId,
	STypeId,
	BTypeId,
	BrandarTypeID,
	BillType,--单据类型
	BillDate,--当前保存时间
	BillCode,--单据编号
	CId,--币种
	--TaxTotal,--价税合计金额（销售金额）
	--NTaxTotal,--原币价税合计金额（销售金额）
	CompleteTotal,--结算金额
	NCompleteTotal,--原币结算金额
	Comment,--备注
	EtypeID,--经手人ID
	IsDraft,--是否草稿
	IsIni,--是否期初
	detailid
)
SELECT b.BillNumberId,
		@MoneyBillNumberID,
		b.Stypeid,
		b.btypeid,
		@BrandarTypeID,
		b.BillType,
		@Billdate,
		b.BillCode,
		b.cid,
		--CASE WHEN C.BasisType=0 THEN dbo.F_RoundTotal(@NTaxTotal*C.Rate) ELSE dbo.F_RoundTotal(@NTaxTotal/C.Rate) END AS  TaxTotal, 
		--@NTaxTotal,
		--CASE WHEN C.BasisType=0 THEN dbo.F_RoundTotal(@NCompleteTotal*C.Rate) ELSE dbo.F_RoundTotal(@NCompleteTotal/C.Rate) END AS CompleteTotal   ,
		dbo.F_RoundTotal(@CompleteTotal),
		dbo.F_RoundTotal(@NCompleteTotal),
		@Comment,
		b.etypeid,
		CASE WHEN @isini=1 THEN 0 
			 ELSE CASE WHEN @isAudit=1 THEN 0 
						ELSE 1 END 
			END ,
		@isini	,
		@detailid	 
FROM Billindex b
WHERE @intBillType not in (404,405)
and b.BillNumberId=@GoodBillNumberID
UNION ALL
SELECT  r.BillNumberId,
		@MoneyBillNumberID,
		r.Stypeid,
		r.btypeid,
		@BrandarTypeID,
		r.BillType,
		GETDATE(),
		r.BillCode,
		r.cid,
		--CASE WHEN C.BasisType=0 THEN dbo.F_RoundTotal(@NTaxTotal*C.Rate) ELSE dbo.F_RoundTotal(@NTaxTotal/C.Rate) END AS  TaxTotal, 
		--@NTaxTotal,
		dbo.F_RoundTotal(@CompleteTotal),
		dbo.F_RoundTotal(@NCompleteTotal),
		@Comment,
		r.etypeid,
		CASE WHEN @isini=1 THEN 0 
			 ELSE CASE WHEN @isAudit=1 THEN 0 
						ELSE 1 END 
			END ,
		@isini	,
		@detailid	 
FROM ReceiptBillIndex r
INNER JOIN Ac_Currency C ON C.CId=r.CId
WHERE @intBillType in (404,405)
and BillNumberId=@GoodBillNumberID

SET @Error+=@@ERROR

IF @Error<>0 
	RETURN 2 ------------发生错误
	
IF @isAudit=0 --草稿 到此返回了
	RETURN 0
ELSE 
BEGIN 
	-- *** 处理九种单据的结算状态 - Start ***
	IF (@NTotalMoney_y>=0 AND (@NTotalMoney_y-@NPreferencemoney_y) <= @NCompleteTotal_y+@NTotalInMoney_y)
		OR (@NTotalMoney_y<0 AND (@NTotalMoney_y-@NPreferencemoney_y) >= @NCompleteTotal_y+@NTotalInMoney_y)
	BEGIN
		IF @intBillType IN (404,405)
		BEGIN
			UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@GoodBillNumberId
		END
		ELSE IF @intBillType IN (115,116,128,129) 
		BEGIN
			UPDATE dbo.AdDebtBill 
			SET  
				JsStyle='3',
				jsState=CASE WHEN @intBillType IN(115,116) THEN CASE WHEN NTotal>NCompleteTotal+NChargeOffTotal THEN '1' ELSE '2' END
							ELSE '2' END				
			WHERE BillNumberID=@GoodBillNumberId AND id=@detailid
				
			UPDATE BillIndex 
			SET jsStyle = '3',jsState = '2' 
			WHERE BillNumberID=@GoodBillNumberId AND
			NOT EXISTS (
				SELECT 1 
				FROM  AdDebtBill 
				WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
				AND	jsState<>2
			 )
			 
			UPDATE BillIndex 
			SET jsStyle = '4',jsState = '1' 
			WHERE BillNumberID=@GoodBillNumberId AND
			 EXISTS (
				SELECT 1 
				FROM  AdDebtBill 
				WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
				AND	JsStyle=1 AND jsState=1
			 )
			 
			 IF NOT  EXISTS (SELECT  1 FROM (SELECT CASE WHEN (JsStyle=0 or jsState=0) THEN 0
									WHEN JsStyle=1 AND jsState=1 THEN 0
									WHEN JsStyle=1 AND jsState=2 THEN 1
									WHEN JsStyle=3 AND jsState=1 THEN 0
									WHEN JsStyle=3 AND jsState=2 THEN 0
									END as flag FROM  AdDebtBill WHERE BillNumberId=@GoodBillNumberId AND Id <> @detailid ) a WHERE a.flag=0)
			BEGIN 	 
				UPDATE BillIndex 
				SET jsStyle = '4',jsState = '2' 
				WHERE  BillNumberId=@GoodBillNumberId
			END 
					 
		END
		ELSE
		BEGIN
			UPDATE BillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@GoodBillNumberId
		END
	END
	ELSE
	BEGIN
		IF @intBillType IN (404,405)
		BEGIN
			UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@GoodBillNumberId
		END
		ELSE IF @intBillType IN (115,116,128,129) 
		BEGIN
			UPDATE dbo.AdDebtBill 
			SET  
				JsStyle='3',
				jsState=CASE WHEN @intBillType IN(115,116) THEN CASE WHEN NTotal>NCompleteTotal+NChargeOffTotal THEN '1' ELSE '2' END
							ELSE '1' END				
			WHERE BillNumberID=@GoodBillNumberId AND id=@detailid
			
			UPDATE BillIndex 
			SET jsStyle = '3',jsState = '1' 
			WHERE NOT EXISTS (
				SELECT 1 
				FROM  AdDebtBill 
				WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
				AND	JsStyle<>3 
			 )AND BillNumberID=@GoodBillNumberId 
			 
			UPDATE BillIndex 
			SET jsStyle = '4',jsState = '1' 
			WHERE  EXISTS (
				SELECT 1 
				FROM  AdDebtBill 
				WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
				AND	JsStyle=1 
			 )AND BillNumberID=@GoodBillNumberId 
			
		END 
		ELSE
		BEGIN
			UPDATE BillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@GoodBillNumberId
		END
	END
END 


RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertCompleteBrandarTotal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Gp_InsertCompleteBrandarTotal
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：GLJ
	日期：2017-12-08
	描述：保存 按商品品牌结算
-------------------------------------------*/
CREATE PROCEDURE Gp_InsertCompleteBrandarTotal
(
	@BillNumberID 	NUMERIC(10,0),--单据ID
	@BillType		INT,--单据类型
	@BillCode		VARCHAR(200),--单据编号
	@CId			INT,--币种
	@STypeId 		VARCHAR(50),--分支机构ID
	@BTypeId		VARCHAR(50),--往来单位ID
	@isIni			INT,		--是否期初
	@ETypeID		VARCHAR(50),--经手人
	@CompleteTotal	Type_CompleteBrandarTotal READONLY,
	@OperatorID		VARCHAR(50)
)
AS 
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--期初未结算销售出库单、期初未结算销售退货单、期初未结算销售换货单、期初未结算委托代销结算单、期初未结算组合品销售出库单、期初未结算组合品销售退货单
IF(@BillType IN(11,45,160,141,12,46,4,189,93,66))
	BEGIN
		IF NOT EXISTS(SELECT * FROM BillIndex WHERE BillNumberId=@BillNumberID)
			BEGIN
				RETURN 1
			END
	END
--期初未结算销售发货开票
IF(@BillType IN(405))
	BEGIN
		IF NOT EXISTS(SELECT * FROM ReceiptBillIndex WHERE BillNumberId=@BillNumberID)
			BEGIN
				RETURN 1
			END
	END
	
--该往来单位有没有启用品牌，没有启用品牌不能按品牌结算
IF NOT EXISTS (SELECT TOP 1 1 FROM btype WHERE typeid=@BTypeId AND IsUseBrandarType=1)
BEGIN 
	RETURN 7

END 

--存在按单、按商品结算的
IF EXISTS(SELECT TOP 1 1 FROM BILLINDEX WHERE BillNumberId=@BillNumberID AND jsStyle =1 AND @BillType IN(11,45,160,141,12,46))
	OR EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberId=@BillNumberID AND jsStyle=1 AND @BillType IN(405))
RETURN 3

--存在按单、按商品结算的
IF EXISTS(SELECT TOP 1 1 FROM BILLINDEX WHERE BillNumberId=@BillNumberID AND jsStyle =2 AND @BillType IN(11,45,160,141,12,46))
	OR EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberId=@BillNumberID AND jsStyle =2 AND @BillType IN(405))
RETURN 4

--存在核销得


--存在结算完成
IF EXISTS(SELECT TOP 1 1 FROM BILLINDEX WHERE BillNumberId=@BillNumberID AND jsState=2 AND @BillType IN(11,45,160,141,12,46))
OR EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberId=@BillNumberID AND jsState=2 AND @BillType IN(405))
RETURN 5

DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';
--存在 结算金额>未结算金额
CREATE TABLE #BrandarARAPTotal
	(
		BrandarTypeID VARCHAR(50),
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10),
		nYSTotal00  NUMERIC(24, 10) ,
		Total00		NUMERIC(24, 10) ,
		NTotal00	NUMERIC(24, 10)
	)
	
INSERT INTO #BrandarARAPTotal
	(		
			BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			YSTotal00 ,
			nARTotal00 ,
			nYSTotal00,
			Total00,
			NTotal00
	)
	SELECT	BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(YSTotal00),
			SUM(nARTotal00),
			SUM(nYSTotal00),
			SUM(ARTotal00)-SUM(YSTotal00),
			SUM(nARTotal00)-SUM(nYSTotal00)
			
	FROM
	(	--销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.CompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=11
		UNION ALL      
		--组合品销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.PT_Combin_SaleBillDetail s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=12
		UNION ALL
		--销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal00,
				0 AS YSTotal00 ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.salebackbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=45
		UNION ALL 
		--组合品销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal00,
				0 AS YSTotal00 ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.PT_Combin_SaleBackBillDetail s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=46 
		UNION ALL 
		--销售换货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.salegoodsexchangebill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=160 
		UNION ALL 
		--委托代销结算单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.commissionbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE b.IsIni=1
				  AND  b.Stypeid=@stypeid
				  AND b.BillNumberId=@billNumberId AND @billType=141 
		UNION ALL 
		--销售发货开票
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.ReceiptBill s
			INNER JOIN  ReceiptBillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=405 
		UNION ALL 
		--其他收入单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.total AS  ARTotal,
				0 AS YSTotal ,
				s.NTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND b.BillNumberId=@billNumberId AND @billType=93 
		UNION ALL 
		--费用单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.total
					  ELSE 0
					  END  AS  ARTotal,
				0 AS YSTotal ,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.NTotal
					  ELSE 0
					  END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1	
			WHERE b.IsIni=1
			      AND b.BillNumberId=@billNumberId AND @billType=36		
		UNION ALL 
		--多账户
		SELECT	s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					 THEN -(s.PreferenceMoney+S.TotalInMoney-s.YSTotalInMoney  )
					 WHEN b.billtype =36 AND b.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
					 THEN (s.PreferenceMoney+s.TotalInMoney+s.YSTotalInMoney )
					 ELSE s.PreferenceMoney+S.TotalInMoney-s.YSTotalInMoney 
					END  AS  ARTotal00,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(-s.YSTotalInMoney  )
					ELSE -s.YSTotalInMoney 
					END AS YSTotal00 ,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.NPreferenceMoney+S.NTotalInMoney-s.NYSTotalInMoney )
					 WHEN b.billtype =36 AND b.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
					 THEN (s.nPreferenceMoney+s.nTotalInMoney+s.NYSTotalInMoney )
					ELSE s.PreferenceMoney+S.TotalInMoney-s.NYSTotalInMoney
					END  AS nARTotal00 ,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(-s.NYSTotalInMoney  )
					ELSE -s.NYSTotalInMoney 
					END AS nYSTotal00 
			FROM BillMulBrand s
			INNER JOIN BILLINDEX B ON s.billnumberid=b.billnumberid
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE s.BillNumberId=@billNumberId 
				   AND s.billtype=@billType
				   AND b.Stypeid=@stypeid
				   AND b.isini=1
				   AND  b.BillType  NOT IN (305,215)
		UNION ALL 
				--多账户
		SELECT	s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0  AS  ARTotal00,
				CASE WHEN @billtype IN (305) 
					THEN -(-s.YSTotalInMoney  )
					ELSE -s.YSTotalInMoney 
					END AS YSTotal00 ,
				0  AS nARTotal00 ,
				CASE WHEN @billtype IN (305) 
					THEN -(-s.NYSTotalInMoney  )
					ELSE -s.NYSTotalInMoney 
					END AS nYSTotal00 
			FROM BillMulBrand s
			INNER JOIN BILLINDEX B ON s.billnumberid=b.billnumberid
			INNER JOIN dbo.btype bt ON bt.typeId=b.btypeid AND bt.IsUseBrandarType=1
			WHERE s.BillNumberId=@billNumberId 
				   AND s.billtype=@billType
				   AND b.Stypeid=@stypeid
				   AND b.isini=1
				   AND  b.BillType   IN (305,215)
		UNION ALL 
		--品牌结算
		SELECT	s.BrandarTypeID,
				s.stypeid,
				s.btypeid,
				s.cid,
				CASE 
					WHEN @billtype IN (11,12,160,141,93,405) THEN -s.CompleteTotal
					ELSE s.CompleteTotal 
				END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE 
					WHEN @billtype IN (11,12,160,141,93,405) THEN -s.NCompleteTotal
					ELSE s.NCompleteTotal
				END  AS nARTotal00 ,
				0 AS nYSTotal00  
			FROM CompleteBrandarTotal s
			WHERE s.GoodsBillID=@billNumberId 
				   AND s.billtype=@billType
				   AND s.Stypeid=@stypeid
				   AND S.isDraft=0  --不是草稿的
				   AND s.isini=1		
	)total
	GROUP BY BrandarTypeID,stypeid,btypeid,cid
		
DELETE FROM #BrandarARAPTotal WHERE YSTotal00=0  AND ARTotal00=0  AND nYSTotal00=0 AND nARTotal00=0 

IF EXISTS (SELECT TOP 1 1 
			FROM #BrandarARAPTotal b
			INNER JOIN @CompleteTotal c ON b.BrandarTypeID=c.BrandarTypeID
			WHERE ABS(B.NTotal00)<ABS(c.NCompleteTotal)
			)
			
RETURN 6 	
			


DECLARE @Error INT=0
--物流	
IF(@BillType IN(11,45,160,141,12,46,405,93,66,36))
	BEGIN
		--回写completetotal
		DELETE FROM completeTotal WHERE GoodsBillID=@BillNumberID AND MoneyBillId=-1 AND BillType=@BillType
		DELETE FROM CompleteBrandarTotal WHERE GoodsBillID=@BillNumberID AND MoneyBillId=-1 AND BillType=@BillType
		SET @Error+=@@ERROR
	END
--钱流
IF(@BillType IN(4,189))
	BEGIN
		DELETE FROM completeTotal WHERE MoneyBillId=@BillNumberID AND GoodsBillID=-1 AND BillType=@BillType
		DELETE FROM CompleteBrandarTotal WHERE MoneyBillId=@BillNumberID AND GoodsBillID=-1  AND BillType=@BillType
		SET @Error+=@@ERROR
	END
	
DECLARE  @op INT=1;

IF @Billtype IN (45,46)
	SELECT  @op=-1;

INSERT INTO CompleteBrandarTotal
(
	GoodsBillID,	
	MoneyBillId,
	STypeId,
	BTypeId,
	BrandarTypeID,
	BillType,--单据类型
	BillDate,--当前保存时间
	BillCode,--单据编号
	CId,--币种
	CompleteTotal,--结算金额
	NCompleteTotal,--原币结算金额
	Comment,--备注
	EtypeID,--经手人ID
	IsDraft,--是否草稿
	IsIni--是否期初
)
SELECT 
	CASE WHEN @BillType IN(11,45,160,141,12,46,405,93,66,36) THEN @BillNumberID ELSE -1 END GoodsBillID,
	CASE WHEN @BillType IN(4,189) THEN @BillNumberID ELSE -1 END MoneyBillId,
	@STypeId STypeId,
	@BTypeId BTypeId,
	T.BrandarTypeID,
	@BillType BillType,
	GETDATE() BillDate,
	@BillCode BillCode,
	T.CId,
	dbo.F_RoundTotal(T.CompleteTotal*@op),
	dbo.F_RoundTotal(T.NCompleteTotal*@op),
	ISNULL(T.Comment,''),	
	@ETypeID EtypeID,
	CASE WHEN @isIni=1 THEN  0 ELSE 1 END as  IsDraft,
	@isIni IsIni
FROM @CompleteTotal T
INNER JOIN Ac_Currency C ON C.CId=T.CId
SET @Error+=@@ERROR





IF @Error<>0 
	RETURN 2 ------------发生错误


DECLARE @decCompleteTotal  NUMERIC(24, 10) ,
		@decNCompleteTotal  NUMERIC(24, 10) 
			
SELECT @decNCompleteTotal=ISNULL(SUM(t.NCompleteTotal),0),
	   @decCompleteTotal=ISNULL(SUM(t.CompleteTotal),0)
FROM @CompleteTotal t
INNER JOIN Ac_Currency C ON C.CId=T.CId

--回写completetotal	
INSERT completeTotal
(
	GoodsBillID,
	GoodsBillDetailID,
	MoneyBillID,
	CompleteTotal,
	Billdate,
	etypeid,
	NCompleteTotal,
	BillType
)
VALUES
( 
	CASE WHEN @BillType IN(11,45,160,141,12,46,405,93,66,36) THEN @BillNumberID ELSE -1 END ,
	NULL,
	CASE WHEN @BillType IN(4,189) THEN @BillNumberID ELSE -1 END ,
	 dbo.F_RoundTotal( @decNCompleteTotal*@op),
	GETDATE(),
	@ETypeID ,
	 dbo.F_RoundTotal( @decCompleteTotal*@op),
	@BillType
)

SET @Error+=@@ERROR

--回写结算状态，重新按照 原币 重算外币的completetotal

DECLARE @BasisType INT 

SELECT  @BasisType=BasisType
FROM dbo.Ac_Currency a
INNER JOIN (
	SELECT  CId
	FROM ReceiptBillIndex 
	WHERE BillnumberID=@BillNumberID 
		AND @BillType=405
	UNION 
	SELECT  CId
	FROM billindex 
	WHERE BillnumberID=@BillNumberID 
		AND @BillType<>405
) c ON c.CId = a.CId
	
UPDATE  ReceiptBillIndex 
SET		JSStyle=CASE 
					WHEN EXISTS(SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsBillID = @BillNumberID) THEN 3
					WHEN EXISTS(SELECT TOP 1 1 FROM completeTotal WHERE GoodsBillID = @BillNumberID) THEN 2
					ELSE 0
				END,
		JSState=CASE WHEN ABS(NTaxTotalMoney)=ABS(NCompleteTotal+NChargeOffTotal) THEN 2 ELSE 1 END,
		CompleteTotal=CASE WHEN @BasisType=0 THEN dbo.F_RoundTotal(NCompleteTotal*Rate) ELSE dbo.F_RoundTotal(NCompleteTotal/Rate) END 
	
WHERE	BillnumberID=@BillNumberID 
		AND @BillType=405
 
UPDATE  Billindex 
SET		JSStyle=CASE 
					WHEN EXISTS(SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsBillID = @BillNumberID) THEN 3
					WHEN EXISTS(SELECT TOP 1 1 FROM completeTotal WHERE GoodsBillID = @BillNumberID) THEN 2
					ELSE 0
				END, 
		JSState=CASE WHEN ABS(NTotalMoney-NPreferenceMoney)=ABS(NTotalInMoney+NCompleteTotal+NChargeOffTotal) THEN 2 ELSE 1 END,
		CompleteTotal=CASE WHEN @BasisType=0 THEN dbo.F_RoundTotal(NCompleteTotal*Rate) ELSE dbo.F_RoundTotal(NCompleteTotal/Rate) END 
WHERE	BillnumberID=@BillNumberID 
		AND @BillType<>405


RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		按商品结算
-- 最后修改作者：	haiquan
-- 最后修改时间：	2007-04-11
-- ========================================================================
CREATE                                            PROCEDURE [GP_InsertCompleteGoodTotal]
(
	@MoneyBillNumberID int,--收/付款单据id
	@GoodBillNumberID int,--被结算的单据id
	@CompleteGoodQTY  NUMERIC(24, 10) ,--被结算的数量
	@Ptypeid varchar(50), --被结算商品id
	@Billid int, --表单记录的id号
	@InOrOut char(1), --出入库
	@reDo char(1),
	@completegoodtotal  NUMERIC(24, 10) ,
	@Price  NUMERIC(24, 10) ,
	@ncompletegoodtotal  NUMERIC(24, 10) ,
	@IsSelect bit,
	@GoodsBillType INT=-1
)
--@encode$--
AS
SET NOCOUNT ON
--发票单据
IF @GoodsBillType IN(404,405)
BEGIN
	IF NOT EXISTS (SELECT 1 FROM ReceiptBillIndex WHERE BillnumberID=@GoodBillNumberId)
		RETURN 1
	IF EXISTS(SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillnumberID=@GoodBillNumberId AND ChargeOffTotal>0 )
		RETURN 3 -----------指定的单据已被核销
END
ELSE
BEGIN 
	IF(not exists(select 1 FROM Billindex WHERE BillnumberID=@GoodBillNumberId))
		RETURN 1 -------------指定的单据不存在
		
	IF EXISTS(SELECT 1 FROM dbo.Billindex WHERE BillnumberID=@GoodBillNumberId AND ChargeOffTotal>0 )
		RETURN 3 -----------指定的单据已被核销
END
IF NOT EXISTS(SELECT BillnumberID FROM Billindex WHERE BillnumberID=@MoneyBillNumberId)
	RETURN 1

DELETE FROM CompleteGoodTotal WHERE MoneyBillid=@MoneyBillNumberID AND Goodsbillid=@GoodBillNumberID AND Billid=@Billid
	AND BillType=@GoodsBillType
	
    if @CompleteGoodQTY=0 --如果结算数量为0，不保存
	  return 0

--IF @reDo<>''   --如果存在修改，则删除原来的记录
--	DELETE FROM CompleteGoodTotal WHERE MoneyBillID=@MoneyBillNumberId And GoodsBillId=@GoodBillNumberID
--print(@sql)

DECLARE @Billdate datetime 

select @Billdate=getDate()

IF EXISTS (SELECT etypeid FROM Billindex WHERE BillnumberID =@MoneyBillNumberId)
		SELECT @Billdate =billdate FROM Billindex WHERE BillnumberID =@MoneyBillNumberId
Insert into CompleteGoodTotal(GoodsBillID,MoneyBillID,CompleteGoodQTY,Draft,Ptypeid,BillID,BillDate,InOrOut,completegoodtotal,Price,ncompletegoodtotal,IsSelect,BillType)
 	 Values(@GoodBillNumberID,@MoneyBillNumberID,dbo.F_RoundQty(@CompleteGoodQTY),0,@Ptypeid,@Billid,@Billdate,@InOrOut,dbo.F_RoundTotal(@completegoodtotal),dbo.F_RoundPrice(@Price),
 	 dbo.F_RoundTotal(@ncompletegoodtotal),@IsSelect,@GoodsBillType) 

IF @@error<>0 
RETURN 2 ------------发生错误

UPDATE CompleteGoodTotal SET draft=0,BillDate=@Billdate WHERE MoneyBillID=@MoneyBillNumberId AND Draft=1
IF @@error<>0 
RETURN 2 ------------发生错误
ELSE
BEGIN
	-- *** 处理九种单据的结算状态 - Start ***
	DECLARE @intBillType int,@TotalMoney  NUMERIC(24, 10) ,@TotalInMoney  NUMERIC(24, 10) 
	DECLARE @preferencemoney  NUMERIC(24, 10) ,@CompleteTotal  NUMERIC(24, 10) 
	IF @GoodsBillType IN(404,405)
		SELECT @intBillType=BillType,@TotalMoney=TaxTotalMoney,@TotalInMoney=0,
		@preferencemoney=0,@CompleteTotal=CompleteTotal
		FROM ReceiptBillIndex WHERE BillnumberID=@GoodBillNumberID
	ELSE 
		SELECT @intBillType=BillType,@TotalMoney=TotalMoney,@TotalInMoney=TotalInMoney,
		@preferencemoney=preferencemoney,@CompleteTotal=CompleteTotal
		FROM BillIndex WHERE BillnumberID=@GoodBillNumberID
	
	IF @intBillType NOT IN (160,161)
	BEGIN
		IF(@TotalMoney-@Preferencemoney)=(@CompleteTotal+@TotalInMoney)
			IF @intBillType IN (404,405)
				UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@GoodBillNumberID
			ELSE
				UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@GoodBillNumberID
		ELSE
			IF @intBillType IN (404,405)
				UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@GoodBillNumberID
			ELSE 
				UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@GoodBillNumberID
	END
	ELSE
	BEGIN
		DECLARE @sumComGoodQtyOut  NUMERIC(24, 10) ,@sumBillGoodQtyOut  NUMERIC(24, 10) 
		DECLARE @sumComGoodQtyIn  NUMERIC(24, 10) ,@sumBillGoodQtyIn  NUMERIC(24, 10) 
		SELECT @sumComGoodQtyOut=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
		WHERE GoodsBillID=@GoodBillNumberID AND InOrOut = 'O' AND Draft = 0
		SELECT @sumComGoodQtyIn=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
		WHERE GoodsBillID=@GoodBillNumberID AND InOrOut = 'I' AND Draft = 0
		IF @intBillType = 160
		BEGIN
			SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
			WHERE BillNumberID=@GoodBillNumberID AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
			SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
			WHERE BillNumberID=@GoodBillNumberID AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
		END
		IF @intBillType = 161
		BEGIN
			SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
			WHERE BillNumberID=@GoodBillNumberID AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
			SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
			WHERE BillNumberID=@GoodBillNumberID AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
		END
		IF (@TotalMoney-@Preferencemoney)=(@CompleteTotal+@TotalInMoney) AND
			(@sumComGoodQtyOut+@sumComGoodQtyIn)=(@sumBillGoodQtyOut+@sumBillGoodQtyIn)
			UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@GoodBillNumberID
		ELSE
			UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@GoodBillNumberID
	END
	IF @@error<>0 RETURN 2 ------------发生错误
	RETURN 0
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


-- ========================================================================
-- 功能说明：		保存草稿的按商品 结算过程
-- 最后修改作者：	haiquan 
-- 最后修改时间：	2007-04-13
-- ========================================================================
CREATE                    PROCEDURE [GP_InsertCompleteGoodTotal_Draft]
(
	@MoneyBillNumberID int,--收/付款单据id
	@GoodBillNumberID int,--被结算的单据id
	@CompleteGoodQTY  NUMERIC(24, 10) ,--被结算的数量
	@Ptypeid varchar(50), --被结算商品id
	@Billid int, --表单记录的id号
	@InOrOut char(1), --出入库
	@reDo char(1),
	@CompleteGoodTotal  NUMERIC(24, 10) ,--被结算的金额
	@Price  NUMERIC(24, 10) ,
	@nCompleteGoodTotal  NUMERIC(24, 10) ,
	@IsSelect bit,
	@GoodsBillType    INT=-1
)
--@encode$--
AS
    --保存为草稿时将按单结算过程记录下来，此时并不改变BillIndex中的CompleteTotal.
    SET NOCOUNT ON
	IF @GoodsBillType IN (404,405)
	BEGIN
		IF NOT EXISTS (SELECT 1 FROM ReceiptBillIndex WHERE BillNumberID=@GoodBillNumberID)
			RETURN 1
		IF EXISTS(SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillnumberID=@GoodBillNumberId AND ChargeOffTotal>0 )
			RETURN 3 -----------指定的单据已被核销
	END
	ELSE 
	BEGIN
		If(Not Exists(Select 1 From billindex Where billnumberid=@GoodBillNumberID))
			Return 1 -------------指定的单据不存在
		IF EXISTS(SELECT 1 FROM dbo.Billindex WHERE BillnumberID=@GoodBillNumberId AND ChargeOffTotal>0 )
			RETURN 3 -----------指定的单据已被核销
    --先删除CompleteTotal中可能有的草稿的按单结算记录（因为可能重复保存草稿）
	END
	DELETE FROM CompleteGoodTotal WHERE MoneyBillId=@MoneyBillNumberId AND GoodsBillID NOT IN (select GoodsBillID from Completetotal WHERE MoneyBillID=@MoneyBillNumberId) 
	--删除按品牌结算的草稿
  	Delete From dbo.CompleteBrandarTotal 
		   Where MoneyBillID=@MoneyBillNumberID 
			 And isDraft=1
			 AND BillType=@GoodsBillType
			 And GoodsBillid IN (SELECT * FROM F_Split(@GoodBillNumberID,'~'))
			 
IF @CompleteGoodQTY=0
     DELETE FROM CompleteGoodTotal WHERE MoneyBillId=@MoneyBillNumberId AND GoodsBillID=@GoodBillNumberID AND Billid=@Billid
ELSE
	 BEGIN
		 Insert CompleteGoodTotal(GoodsBillID,MoneyBillID,CompleteGoodQTY,Draft,Ptypeid,BillID,InOrOut,completegoodtotal,Price,nCompleteGoodTotal,IsSelect,BillType)
		 Values(@GoodBillNumberID,@MoneyBillNumberID,dbo.F_RoundQty(@CompleteGoodQTY),1,@Ptypeid,@Billid,@InOrOut,dbo.F_RoundTotal(@completegoodtotal),dbo.F_RoundPrice(@Price),
		 dbo.F_RoundTotal(@nCompleteGoodTotal),@IsSelect,@GoodsBillType) 
     END 

    If @@error<>0 Return 2 ------------发生错误
    Else
    Return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		按单结算
-- 最后修改作者：	冯 波
-- 最后修改时间：	2004-04-08
-- 添加对草稿所对应的按单结算物流单据进行删除
-- ========================================================================
CREATE                                PROCEDURE [GP_InsertCompleteTotal] (
@intGoodsNumberId int,
@intGoodsDetailId int,
@intMoneyNumberId int,
@decCompleteTotal  NUMERIC(24, 10) ,
@decNCompleteTotal  NUMERIC(24, 10) ,
@IsGood int = 0, --0 按单 1 按商品 2 按品牌
@GoodsBillType   INT=-1         --------被结算单据的BillType    
)--@encode$--
AS
SET NOCOUNT ON
--发票单据
IF @GoodsBillType IN (404,405)
BEGIN
	IF NOT EXISTS (SELECT 1 FROM ReceiptBillIndex WHERE BillNumberID=@intGoodsNumberId)
	RETURN 1
END
ELSE IF @GoodsBillType IN (423,424,425,426)
BEGIN
	IF NOT EXISTS (SELECT 1 FROM dbo.Coupon_BillIndex WHERE BillNumberID=@intGoodsNumberId)
	RETURN 1
END 
--物流单据
ELSE
BEGIN
	IF(not exists(select 1 FROM Billindex WHERE BillnumberID=@intGoodsNumberId))
		RETURN 1 -------------指定的单据不存在
END
--收付款单
IF NOT EXISTS(SELECT BillnumberID FROM Billindex WHERE BillnumberID=@intMoneyNumberId)
	RETURN 1
	
IF @IsGood IN (0,1) --判断是否按品牌结算过了
BEGIN
	IF @GoodsBillType IN (404,405)
	BEGIN
		IF EXISTS (SELECT  1 FROM ReceiptBillIndex WHERE BillNumberID=@intGoodsNumberId AND JSStyle=3)
			RETURN 14 
	END
	ELSE IF @GoodsBillType IN (115,116,128,129)
	BEGIN 
		IF EXISTS(SELECT  1 FROM  addebtbill WHERE BillNumberID=@intGoodsNumberId AND id=@intGoodsDetailId AND JSStyle =3 )
		BEGIN 
			--应收增加 减少单 明细表体按品牌结算过了
			RETURN 14 
		END 
		
	END  
	ELSE 
	BEGIN
		IF EXISTS (SELECT  1 FROM dbo.BillIndex WHERE BillNumberID=@intGoodsNumberId AND @GoodsBillType NOT IN (423,424,425,426)AND JSStyle=3)
			RETURN 14 
	END 
	 
END 
IF @IsGood=2 --判断是否按单、商品结算过了
BEGIN
	IF @GoodsBillType IN (404,405)
	BEGIN
		IF EXISTS(SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@intGoodsNumberId AND ChargeOffTotal>0)
			RETURN 10 --按品牌结算的单据已经被核销,不允许再按品牌结算 
		IF EXISTS (SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@intGoodsNumberId AND JSStyle IN (1))
			RETURN 11 --该单据存在按单、按商品结算过程
		IF EXISTS (SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@intGoodsNumberId AND JSStyle IN (2))
			RETURN 12 --该单据存在按单、按商品结算过程
		IF EXISTS (SELECT 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@intGoodsNumberId AND JSState=2)
			RETURN 13 --该单据已经结算完成
			
	END
	ELSE IF @GoodsBillType IN (115,116,128,129)
	BEGIN 
		IF EXISTS(SELECT 1 FROM dbo.addebtbill WHERE BillNumberID=@intGoodsNumberId AND id=@intGoodsDetailId  AND ChargeOffTotal>0)
			RETURN 10 --按品牌结算的单据已经被核销,不允许再按品牌结算	
		IF EXISTS(SELECT  1 FROM  addebtbill WHERE BillNumberID=@intGoodsNumberId AND id=@intGoodsDetailId AND JSStyle =1 )
		BEGIN 
			--应收增加 减少单 明细表体按单结算过了
			RETURN 14 
		END 
		IF EXISTS (SELECT  1 FROM  addebtbill WHERE BillNumberID=@intGoodsNumberId AND id=@intGoodsDetailId AND JSState=2)
			RETURN 13 --该单据已经结算完成 
		
	END 
	ELSE 
	BEGIN
		IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillNumberID=@intGoodsNumberId AND ChargeOffTotal>0)
			RETURN 10 --按品牌结算的单据已经被核销,不允许再按品牌结算
		IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberID=@intGoodsNumberId AND JSStyle IN (1))
			RETURN 11 --该单据存在按单、按商品结算过程
		IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberID=@intGoodsNumberId AND JSStyle IN (2))
			RETURN 12 --该单据存在按单、按商品结算过程
		IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberID=@intGoodsNumberId AND JSState=2)
			RETURN 13 --该单据已经结算完成 

	END 
END 

DECLARE @IFStopMoney char(1)
SET @IFStopMoney='0'
SELECT @IFStopMoney =ifStopMoney FROM Billindex where BillnumberID=@intGoodsNumberId
IF @IFStopMoney ='1' RETURN 8

DECLARE @Billtype  int -- 收、付款单据类型
DECLARE @szBtypeid VARCHAR(50) --结算单位
DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

SELECT @Billtype =Billtype,@szBtypeid=btypeid FROM Billindex WHERE  BillnumberID=@intMoneyNumberId
--SELECT @GoodsBillType=Billtype FROM Billindex WHERE  BillnumberID=@intGoodsNumberId

declare @Jstatus  NUMERIC(24, 10) 
DECLARE @GoodBillCompleteTotal  NUMERIC(24, 10) ,
		@GoodBillTotalMoney  NUMERIC(24, 10) ,
		@GoodBillPreferencemoney  NUMERIC(24, 10) ,
		@GoodBillTotalInMoney  NUMERIC(24, 10) ,
		@GoodBillChargeoffValue NUMERIC(24,10),
		@NGoodBillCompleteTotal  NUMERIC(24, 10) ,
		@NGoodBillTotalMoney  NUMERIC(24, 10) ,
		@NGoodBillPreferencemoney  NUMERIC(24, 10) ,
		@NGoodBillTotalInMoney  NUMERIC(24, 10) ,
		@NGoodBillChargeoffValue NUMERIC(24,10)

--发票单据
IF @GoodsBillType IN (404,405)
BEGIN
	SELECT  @GoodsBillType=Billtype,
		@GoodBillCompleteTotal=ISNULL(CompleteTotal,0),
		@GoodBillTotalMoney = ISNULL(TaxTotalMoney,0),
		@GoodBillPreferencemoney = 0,
		@GoodBillTotalInMoney =0,
		@GoodBillChargeoffValue=ChargeOffTotal,
		@NGoodBillCompleteTotal=ISNULL(NCompleteTotal,0),
		@NGoodBillTotalMoney = ISNULL(NTaxTotalMoney,0),
		@NGoodBillPreferencemoney = 0,
		@NGoodBillTotalInMoney =0,
		@NGoodBillChargeoffValue=NChargeOffTotal,
		@Jstatus=ISNULL(NTaxTotalMoney,0)-(ISNULL(NCompleteTotal,0)+ISNULL(NChargeOffTotal,0))
	FROM ReceiptBillIndex WHERE BillnumberID=@intGoodsNumberId

END
ELSE IF  @GoodsBillType IN  (423,424,425,426)
BEGIN
SELECT	@GoodsBillType=Billtype,
		@GoodBillCompleteTotal=ISNULL(CompleteTotal,0),
		@GoodBillTotalMoney = ISNULL(TotalMoney,0),
		@GoodBillPreferencemoney = ISNULL(0,0),
		@GoodBillTotalInMoney = ISNULL(TotalInMoney,0),
		@GoodBillChargeoffValue=ChargeOffTotal,
		@NGoodBillCompleteTotal=ISNULL(NCompleteTotal,0),
		@NGoodBillTotalMoney = ISNULL(NTotalMoney,0),
		@NGoodBillPreferencemoney = ISNULL(NPreferencemoney,0),
		@NGoodBillTotalInMoney = ISNULL(NTotalInMoney,0),
		@NGoodBillChargeoffValue=NChargeOffTotal,
		@Jstatus=ISNULL(Ntotalmoney,0)-(ISNULL(Ntotalinmoney,0)+ISNULL(NCompleteTotal,0)+ISNULL(Npreferencemoney, 0)+ISNULL(NChargeOffTotal,0))
FROM dbo.Coupon_BillIndex WHERE BillnumberID=@intGoodsNumberId	
END
ELSE IF  @GoodsBillType IN  (115,116,128,129)
BEGIN 
	--应收 应付 增加 减少单 处理表体
	SELECT	@GoodsBillType=bil.Billtype,
			@GoodBillCompleteTotal=ISNULL(adb.CompleteTotal,0),
			@GoodBillTotalMoney = ISNULL(adb.total,0),
			@GoodBillPreferencemoney =0,
			@GoodBillTotalInMoney = 0,
			@GoodBillChargeoffValue=ISNULL(adb.ChargeOffTotal,0),
			@NGoodBillCompleteTotal=ISNULL(adb.NCompleteTotal,0),
			@NGoodBillTotalMoney = ISNULL(adb.NTotal,0),
			@NGoodBillPreferencemoney = 0,
			@NGoodBillTotalInMoney =0,
			@NGoodBillChargeoffValue=ISNULL(adb.NChargeOffTotal,0),
			@Jstatus=ISNULL(adb.total,0)+ISNULL(adb.NCompleteTotal,0)+ISNULL(adb.NChargeOffTotal,0)
	FROM AdDebtBill  adb
	INNER JOIN  billindex bil ON adb.billnumberid=bil.BillNumberId
	WHERE bil.BillnumberID=@intGoodsNumberId AND  adb.id=@intGoodsDetailId
END   
ELSE
--物流单据
SELECT	@GoodsBillType=Billtype,
		@GoodBillCompleteTotal=ISNULL(CompleteTotal,0),
		@GoodBillTotalMoney = ISNULL(TotalMoney,0),
		@GoodBillPreferencemoney = ISNULL(Preferencemoney,0),
		@GoodBillTotalInMoney = ISNULL(TotalInMoney,0),
		@GoodBillChargeoffValue=ChargeOffTotal,
		@NGoodBillCompleteTotal=ISNULL(NCompleteTotal,0),
		@NGoodBillTotalMoney = ISNULL(NTotalMoney,0),
		@NGoodBillPreferencemoney = ISNULL(NPreferencemoney,0),
		@NGoodBillTotalInMoney = ISNULL(NTotalInMoney,0),
		@NGoodBillChargeoffValue=NChargeOffTotal,
		@Jstatus=ISNULL(Ntotalmoney,0)-(ISNULL(Ntotalinmoney,0)+ISNULL(NCompleteTotal,0)+ISNULL(Npreferencemoney, 0)+ISNULL(NChargeOffTotal,0))
FROM billindex WHERE BillnumberID=@intGoodsNumberId

IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal
	WHERE GoodsBillID = @intGoodsNumberId AND MoneyBillID = @intMoneyNumberId) 
AND NOT EXISTS (SELECT TOP 1 1 FROM dbo.CompleteBrandarTotal
	WHERE GoodsBillID = @intGoodsNumberId AND MoneyBillID = @intMoneyNumberId) 
AND @IsGood = 0
BEGIN
	IF ( @NGoodBillTotalMoney>=0 AND (@NGoodBillTotalMoney-@NGoodBillPreferencemoney) < (@NGoodBillCompleteTotal+@decNCompleteTotal+@NGoodBillTotalInMoney+@NGoodBillChargeoffValue) )
	OR ( @NGoodBillTotalMoney<0 AND (@NGoodBillTotalMoney-@NGoodBillPreferencemoney) > (@NGoodBillCompleteTotal+@decNCompleteTotal+@NGoodBillTotalInMoney+@NGoodBillChargeoffValue) )
		RETURN 9
END

--确定未结算金额符号的正负
-- 收款单
IF @Billtype=4
BEGIN
	--销售发票
	IF @GoodsBillType =405
	BEGIN
		UPDATE ReceiptBillIndex SET CompleteTotal=dbo.F_RoundTotal(ISNULL(CompleteTotal,0)+@decCompleteTotal),NCompleteTotal=dbo.F_RoundTotal(ISNULL(NCompleteTotal,0) +(@decNCompleteTotal))
		WHERE BillNumberID=@intGoodsNumberId
	END
	ELSE IF @GoodsBillType=426
	BEGIN
		UPDATE dbo.Coupon_BillIndex SET CompleteTotal = dbo.F_RoundTotal(isnull(CompleteTotal,0)+(-@decCompleteTotal)),NCompleteTotal = dbo.F_RoundTotal(isnull(NCompleteTotal,0)+(-@decNCompleteTotal))
		WHERE BillnumberID=@intGoodsNumberId 
	END 
	ELSE IF @GoodsBillType=424
	BEGIN
		UPDATE Coupon_BillIndex SET CompleteTotal = dbo.F_RoundTotal(isnull(CompleteTotal,0)+@decCompleteTotal),NCompleteTotal = dbo.F_RoundTotal(isnull(NCompleteTotal,0)+@decNCompleteTotal)
		WHERE BillnumberID=@intGoodsNumberId
	END
	ELSE IF @GoodsBillType =45 OR @GoodsBillType =46  OR @GoodsBillType=403 OR @GoodsBillType=148 OR @GoodsBillType=149 OR @GoodsBillType=115 OR (@GoodsBillType=36 AND @ExpenseToAr=1 AND LEFT(@szBtypeid,5)='00001')-- 销售退货单45 返利执行单148  价保执行单149  启用了配置后的费用单
	BEGIN
		UPDATE Billindex SET CompleteTotal = dbo.F_RoundTotal(isnull(CompleteTotal,0)+(-@decCompleteTotal)),NCompleteTotal = dbo.F_RoundTotal(isnull(NCompleteTotal,0)+(-@decNCompleteTotal))
		WHERE BillnumberID=@intGoodsNumberId
	END		
	ELSE  -- 销售出库单11  委托代销结算141 其他收入单93 固定资产变卖85 卡片模式下的固定资产减少单213
	BEGIN
		UPDATE Billindex SET CompleteTotal = dbo.F_RoundTotal(isnull(CompleteTotal,0)+@decCompleteTotal),NCompleteTotal = dbo.F_RoundTotal(isnull(NCompleteTotal,0)+@decNCompleteTotal)
		WHERE BillnumberID=@intGoodsNumberId
	END
END

-- 付款单
IF @Billtype=66
BEGIN
	--采购发票
	IF @GoodsBillType=404
	BEGIN
		UPDATE ReceiptBillIndex SET CompleteTotal = dbo.F_RoundTotal(isnull(CompleteTotal,0)+@decCompleteTotal),NCompleteTotal = dbo.F_RoundTotal(isnull(NCompleteTotal,0)+(@decNCompleteTotal)) 
		WHERE BillnumberID=@intGoodsNumberId
	END
	ELSE IF @GoodsBillType=423
	BEGIN
		UPDATE Coupon_BillIndex SET CompleteTotal = dbo.F_RoundTotal(isnull(CompleteTotal,0)+@decCompleteTotal),NCompleteTotal = dbo.F_RoundTotal(isnull(NCompleteTotal,0)+@decNCompleteTotal)			
		WHERE BillnumberID=@intGoodsNumberId
	END 
	ELSE IF @GoodsBillType =6 OR @GoodsBillType=401 OR @GoodsBillType=150 OR @GoodsBillType=151 OR @GoodsBillType=129 -- 采购退货单6 获利核算执行单150 获得价保执行单151  
	BEGIN
		UPDATE Billindex SET CompleteTotal = dbo.F_RoundTotal(isnull(CompleteTotal,0)+(-@decCompleteTotal)),NCompleteTotal = dbo.F_RoundTotal(isnull(NCompleteTotal,0)+(-@decNCompleteTotal)) 
		WHERE BillnumberID=@intGoodsNumberId
	END
	ELSE  -- 采购入库单34  受托代销结算145 费用单36 固定资产购买84  卡片模式下的固定资产增加单212
	BEGIN
		UPDATE Billindex SET CompleteTotal = dbo.F_RoundTotal(isnull(CompleteTotal,0)+@decCompleteTotal),NCompleteTotal = dbo.F_RoundTotal(isnull(NCompleteTotal,0)+@decNCompleteTotal)			
		WHERE BillnumberID=@intGoodsNumberId
	END
END

--结算应收应付增加减少单的时候要回写结算金额到明细
IF @GoodsBillType=115 OR @GoodsBillType=116 OR @GoodsBillType=128 OR @GoodsBillType=129
BEGIN
	DECLARE @AdCompleteTotal DECIMAL(18,2),
			@AdNCompleteTotal DECIMAL(18,2),
			@Total   DECIMAL(18,2),
			@NTotal  DECIMAL(18,2);
			
	SELECT  @NTotal=NTotal,@Total=total,@AdCompleteTotal=CompleteTotal,@AdNCompleteTotal=NCompleteTotal  FROM dbo.AdDebtBill
	WHERE ID=@intGoodsDetailId
	IF (@AdNCompleteTotal+ABS(@decNCompleteTotal))>@NTotal
	RETURN 9
	
	UPDATE	dbo.AdDebtBill 
	SET		CompleteTotal=dbo.F_RoundTotal(CompleteTotal+ABS(@decCompleteTotal)),
			NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal+ABS(@decNCompleteTotal))
	WHERE   ID=@intGoodsDetailId
END

declare @isok  NUMERIC(24, 10) 
declare @isok2  NUMERIC(24, 10) 
declare @A  NUMERIC(24, 10) 
declare @B  NUMERIC(24, 10) 

-- haiquan添加草稿批量过帐，对按单结算的控制，真不容易
IF @GoodsBillType  IN (404,405)
	SELECT @isok=ISNULL(nTaxTotalMoney,0)-(ISNULL(nCompleteTotal,0)+ISNULL(NChargeOffTotal,0)) FROM ReceiptBillIndex WHERE BillNumberID=@intGoodsNumberId
ELSE IF @GoodsBillType  IN (423,424,426)
	SELECT @isok=ISNULL(ntotalmoney, 0)-(ISNULL(ntotalinmoney, 0)+ISNULL(nCompleteTotal, 0)+ISNULL(npreferencemoney, 0)+ISNULL(nChargeOffTotal,0))  FROM dbo.Coupon_BillIndex WHERE BillNumberid=@intGoodsNumberId
ELSE IF @GoodsBillType IN (115,116,128,129) 
BEGIN 
	SELECT @isok=ISNULL(NTotal, 0)+ISNULL(nCompleteTotal, 0)+ISNULL(nChargeOffTotal,0) FROM dbo.AdDebtBill WHERE BillNumberid=@intGoodsNumberId AND id=@intGoodsDetailId
END 
ELSE
	SELECT @isok=ISNULL(ntotalmoney, 0)-(ISNULL(ntotalinmoney, 0)+ISNULL(nCompleteTotal, 0)+ISNULL(npreferencemoney, 0)+ISNULL(nChargeOffTotal,0))  FROM BillIndex WHERE BillNumberid=@intGoodsNumberId

	IF (@GoodsBillType<>160 and @GoodsBillType<>161) 
		BEGIN
				

			IF (@Jstatus<=0)  --结算前未结算金额状态
				  BEGIN
					IF(@isok>0) 
					RETURN 3
				  END
			IF (@Jstatus>=0)
				  BEGIN
					IF(@isok<0) 
					RETURN 3
				  END
		END
	ELSE
	   BEGIN
   --       IF (@Jstatus*@isok>=0)  --结算前未结算金额状态
	--	     BEGIN

	--			IF(ABS(@isok)-ABS(@Jstatus)>0) 
	--			RETURN 3

	--		 END

 	--	  ELSE
	 --   	BEGIN			
		        --SELECT @isok2=isnull(CompleteTotal,0) FROM BillIndex WHERE BillnumberID=@intGoodsNumberId
					SELECT @isok2=isnull(NCompleteTotal,0)+ISNULL(NTotalInMoney,0)+ISNULL(NPreferencemoney,0) FROM BillIndex WHERE BillnumberID=@intGoodsNumberId
					IF (@GoodsBillType=160)--检测的是按商品结算的情形
						BEGIN
							SELECT @A=SUM(nTaxTotal) FROM SaleGoodsExchangeBill WHERE BillNumberId=@intGoodsNumberId AND InOrOut='O'
							SELECT @B=-1*SUM(nTaxTotal) FROM SaleGoodsExchangeBill WHERE BillNumberId=@intGoodsNumberId AND InOrOut='I'
							
							IF (@isok2>@A OR @isok2 < @B)
	
								RETURN 3
						END
					IF (@GoodsBillType=161)
						BEGIN
							SELECT @A=-1*SUM(nTaxTotal) FROM BuyGoodsExchangeBill WHERE BillNumberId=@intGoodsNumberId AND InOrOut='O'
							SELECT @B=SUM(nTaxTotal) FROM BuyGoodsExchangeBill WHERE BillNumberId=@intGoodsNumberId AND InOrOut='I'
							
							IF (@isok2<@A OR @isok2 > @B)
	
								RETURN 3
						END  
			--END  
	 END 

DECLARE @Billdate datetime
DECLARE @EtypeID varchar(50)
SET @EtypeID =''
--select @EtypeID=ETypeID from ReceiptBillIndex

IF EXISTS (SELECT etypeid FROM Billindex WHERE BillnumberID =@intMoneyNumberId)
	SELECT @Billdate =billdate,@EtypeID=etypeid FROM Billindex WHERE BillnumberID =@intMoneyNumberId

IF @@error<>0 RETURN 2 ------------发生错误
 --先删除CompleteTotal中可能有的草稿的按单结算记录
 BEGIN
	DELETE FROM CompleteTotal WHERE MoneyBillID=@intMoneyNumberId And Draft=1
 END
IF @@error<>0 RETURN 2 ------------发生错误
 INSERT completeTotal(GoodsBillID,GoodsBillDetailID,MoneyBillID,CompleteTotal,Billdate,etypeid,NCompleteTotal,BillType)
 VALUES(@intGoodsNumberId,@intGoodsDetailId,@intMoneyNumberId,dbo.F_RoundTotal(@decCompleteTotal),@Billdate,@EtypeID,dbo.F_RoundTotal(@decNCompleteTotal),@GoodsBillType)
IF @@error<>0 RETURN 2 ------------发生错误
ELSE
BEGIN
	-- *** 处理九种单据的结算状态 - Start ***
	DECLARE @intBillType int,
			@TotalMoney  NUMERIC(24, 10) ,
			@TotalInMoney  NUMERIC(24, 10) ,
			@preferencemoney  NUMERIC(24, 10) ,
			@CompleteTotal  NUMERIC(24, 10) ,
			@NTotalMoney  NUMERIC(24, 10) ,
			@NTotalInMoney  NUMERIC(24, 10) ,
			@Npreferencemoney  NUMERIC(24, 10) ,
			@NCompleteTotal  NUMERIC(24, 10),
			@NChargeOffTotal	NUMERIC(24,10)
			
	IF @GoodsBillType IN (404,405)
		SELECT @intBillType=BillType,
			   @TotalMoney=TaxTotalMoney,
			   @TotalInMoney=0,
			   @preferencemoney=0,
			   @CompleteTotal=CompleteTotal,
			   @NTotalMoney=NTaxTotalMoney,
			   @NTotalInMoney=0,
			   @Npreferencemoney=0,
			   @NCompleteTotal=NCompleteTotal,
			   @NChargeOffTotal=NChargeOffTotal
		FROM ReceiptBillIndex WHERE BillnumberID=@intGoodsNumberId
	ELSE IF @GoodsBillType IN (423,424,425,426)
		SELECT @intBillType=BillType,
			   @TotalMoney=TotalMoney,
			   @TotalInMoney=TotalInMoney,
			   @preferencemoney=preferencemoney,
			   @CompleteTotal=CompleteTotal,
			   @NTotalMoney=NTotalMoney,
			   @NTotalInMoney=NTotalInMoney,
			   @Npreferencemoney=Npreferencemoney,
			   @NCompleteTotal=NCompleteTotal,
			   @NChargeOffTotal=NChargeOffTotal
		FROM dbo.Coupon_BillIndex WHERE BillnumberID=@intGoodsNumberId
	ELSE IF  @GoodsBillType IN  (115,116,128,129)
	BEGIN 
		--应收 应付 增加 减少单 处理表体
		SELECT	@intBillType=bil.Billtype,
				@TotalMoney=ISNULL(adb.CompleteTotal,0),
				@GoodBillTotalMoney = ISNULL(adb.total,0),
				@preferencemoney =0,
				@TotalInMoney = 0,
				@NCompleteTotal=ISNULL(adb.NCompleteTotal,0),
				@NTotalMoney = ISNULL(adb.NTotal,0),
				@Npreferencemoney = 0,
				@NTotalInMoney =0,
				@NChargeOffTotal=ISNULL(adb.NChargeOffTotal,0)
		FROM AdDebtBill  adb
		INNER JOIN  billindex bil ON adb.billnumberid=bil.BillNumberId
		WHERE bil.BillnumberID=@intGoodsNumberId AND  adb.id=@intGoodsDetailId
	END   
	ELSE 
		SELECT @intBillType=BillType,
			   @TotalMoney=TotalMoney,
			   @TotalInMoney=TotalInMoney,
			   @preferencemoney=preferencemoney,
			   @CompleteTotal=CompleteTotal,
			   @NTotalMoney=NTotalMoney,
			   @NTotalInMoney=NTotalInMoney,
			   @Npreferencemoney=Npreferencemoney,
			   @NCompleteTotal=NCompleteTotal,
			   @NChargeOffTotal=NChargeOffTotal
		FROM BillIndex WHERE BillnumberID=@intGoodsNumberId
		
	-- jsStyle：0 - 无，1 - 按单结算，2 - 按商品结算
	-- jsState：0 - 未结算，1 - 未完成结算，2 - 结算完成
	IF NOT EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=@intGoodsNumberId AND Draft = 0 AND BillType=@GoodsBillType)
	AND NOT EXISTS (SELECT TOP 1 1 FROM dbo.CompleteBrandarTotal WHERE GoodsBillID=@intGoodsNumberId AND isDraft = 0 AND BillType=@GoodsBillType AND ((@GoodsBillType IN(115,116) AND DetailId= @intGoodsDetailId) OR @GoodsBillType NOT IN(115,116)))
	AND @IsGood=0
	BEGIN	-- 之前没有按商品结算记录
		IF (@NTotalMoney>=0 AND (@NTotalMoney-@NPreferencemoney) <= @NCompleteTotal+@NTotalInMoney+@NChargeOffTotal)
		OR (@NTotalMoney<0 AND (@NTotalMoney-@NPreferencemoney) >= @NCompleteTotal+@NTotalInMoney+@NChargeOffTotal) 
			IF @intBillType IN (404,405)
				UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			ELSE IF @intBillType IN (423,424,426)
				UPDATE dbo.Coupon_BillIndex SET jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			ELSE IF @intBillType IN (115,116,128,129) 
			BEGIN
				UPDATE dbo.AdDebtBill 
				SET  
					JsStyle='1',
					jsState=CASE WHEN @intBillType IN(115,116) THEN CASE WHEN NTotal>NCompleteTotal+NChargeOffTotal THEN '1' ELSE '2' END
								ELSE '2' END				
				WHERE BillNumberID=@intGoodsNumberId AND id=@intGoodsDetailId
				
				UPDATE BillIndex 
				SET jsStyle = '1',jsState = '2' 
				WHERE NOT EXISTS (
					SELECT 1 
					FROM  AdDebtBill 
					WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
				    AND jsState<>2
				 )
				  AND BillNumberID=@intGoodsNumberId
				
			END 
			ELSE
				UPDATE BillIndex SET jsStyle = '1',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
		ELSE
			IF @intBillType IN (404,405)
				UPDATE ReceiptBillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
			ELSE IF @intBillType IN (423,424,426)
				UPDATE Coupon_BillIndex SET jsState = '1' WHERE BillNumberID=@intGoodsNumberId	
			ELSE IF @intBillType IN (115,116,128,129) 
			BEGIN
				UPDATE dbo.AdDebtBill 
				SET  
					JsStyle='1',
					jsState=CASE WHEN @intBillType IN(115,116) THEN CASE WHEN NTotal>NCompleteTotal+NChargeOffTotal THEN '1' ELSE '2' END
								ELSE '1' END				
				WHERE BillNumberID=@intGoodsNumberId AND id=@intGoodsDetailId
				
				UPDATE BillIndex 
				SET jsStyle = '1',jsState = '1' 
				WHERE  EXISTS (
					SELECT 1 
					FROM  AdDebtBill 
					WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
				 )
				 AND BillNumberID=@intGoodsNumberId
				
			END 
			ELSE 
				UPDATE BillIndex SET jsStyle = '1',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
	END
	ELSE IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=@intGoodsNumberId AND BillType=@GoodsBillType AND Draft = 0 AND CompleteGoodQTY<>0)
	OR @IsGood=1
	BEGIN
		IF @intBillType NOT IN (160,161)
		BEGIN
			IF (@NTotalMoney-@NPreferencemoney)=(@NCompleteTotal+@NTotalInMoney+@NChargeOffTotal)
				IF @intBillType IN (404,405)
					UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			ELSE
				IF @intBillType IN (404,405)
					UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
				ELSE
					UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
		END
		ELSE
		BEGIN
			DECLARE @sumComGoodQtyOut  NUMERIC(24, 10) ,@sumBillGoodQtyOut  NUMERIC(24, 10) 
			DECLARE @sumComGoodQtyIn  NUMERIC(24, 10) ,@sumBillGoodQtyIn  NUMERIC(24, 10) 
			SELECT @sumComGoodQtyOut=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
			WHERE GoodsBillID=@intGoodsNumberId AND InOrOut = 'O' AND Draft = 0
			SELECT @sumComGoodQtyIn=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
			WHERE GoodsBillID=@intGoodsNumberId AND InOrOut = 'I' AND Draft = 0
			IF @intBillType = 160
			BEGIN
				SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
				WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0

				SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
				WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
			END
			IF @intBillType = 161
			BEGIN
				SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
				WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
				SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
				WHERE BillNumberID=@intGoodsNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
			END
			IF (@NTotalMoney-@NPreferencemoney)=(@NCompleteTotal+@NTotalInMoney+@NChargeOffTotal) AND
				(@sumComGoodQtyOut+@sumComGoodQtyIn)=(@sumBillGoodQtyOut+@sumBillGoodQtyIn)
				UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			ELSE
				UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
		END
	END
	ELSE IF  EXISTS (SELECT TOP 1 1 FROM dbo.CompleteBrandarTotal WHERE GoodsBillID=@intGoodsNumberId AND BillType=@GoodsBillType AND isDraft = 0 AND CompleteTotal<>0)
	OR @IsGood=2
	BEGIN 
		IF (@NTotalMoney>=0 AND (@NTotalMoney-@NPreferencemoney) <= @NCompleteTotal+@NTotalInMoney)
		OR (@NTotalMoney<0 AND (@NTotalMoney-@NPreferencemoney) >= @NCompleteTotal+@NTotalInMoney)
		BEGIN
			IF @intBillType IN (404,405)
			BEGIN
				UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			END
			ELSE IF @intBillType IN (115,116,128,129) 
			BEGIN
				UPDATE dbo.AdDebtBill 
				SET  
					JsStyle='3',
					jsState=CASE WHEN @intBillType IN(115,116) THEN CASE WHEN NTotal>NCompleteTotal+NChargeOffTotal THEN '1' ELSE '2' END
								ELSE '2' END				
				WHERE BillNumberID=@intGoodsNumberId AND id=@intGoodsDetailId
			
				UPDATE BillIndex 
				SET jsStyle = '3',jsState = '2' 
				WHERE BillNumberID=@intGoodsNumberId AND
				NOT EXISTS (
					SELECT 1 
					FROM  AdDebtBill 
					WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
					AND	 jsState<>2
				 )
				 
				UPDATE BillIndex 
				SET jsStyle = '4',jsState = '1' 
				WHERE BillNumberID=@intGoodsNumberId AND
				 EXISTS (
					SELECT 1 
					FROM  AdDebtBill 
					WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
					AND	JsStyle=1 AND jsState=1
				 )AND BillType in(115,116)
				 
				 IF NOT  EXISTS (SELECT  1 FROM (SELECT CASE WHEN (JsStyle=0 or jsState=0) THEN 0
										WHEN JsStyle=1 AND jsState=1 THEN 0
										WHEN JsStyle=1 AND jsState=2 THEN 1
										WHEN JsStyle=3 AND jsState=1 THEN 0
										WHEN JsStyle=3 AND jsState=2 THEN 0
										END as flag FROM  AdDebtBill WHERE BillNumberId=@intGoodsNumberId) a WHERE a.flag=0)
				BEGIN 	 
					UPDATE BillIndex 
					SET jsStyle = '4',jsState = '2' 
					WHERE  BillNumberId=@intGoodsNumberId AND BillType in(115,116)
				END 
					 
			END 

			ELSE
			BEGIN
				UPDATE BillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@intGoodsNumberId
			END
		END
		ELSE
		BEGIN
			IF @intBillType IN (404,405)
			BEGIN
				UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
			END
			ELSE IF @intBillType IN (115,116,128,129) 
			BEGIN
				UPDATE dbo.AdDebtBill 
				SET  
					JsStyle='3',
					jsState=CASE WHEN @intBillType IN(115,116) THEN CASE WHEN NTotal>NCompleteTotal+NChargeOffTotal THEN '1' ELSE '2' END
								ELSE '1' END				
				WHERE BillNumberID=@intGoodsNumberId AND id=@intGoodsDetailId
					
				UPDATE BillIndex 
				SET jsStyle = '3',jsState = '1' 
				WHERE BillNumberID=@intGoodsNumberId AND
				NOT EXISTS (
					SELECT 1 
					FROM  AdDebtBill 
					WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
					AND	JsStyle<>3 
				 )
				 
				UPDATE BillIndex 
				SET jsStyle = '4',jsState = '1' 
				WHERE BillNumberID=@intGoodsNumberId AND
				 EXISTS (
					SELECT 1 
					FROM  AdDebtBill 
					WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
					AND	JsStyle=1 
				 )
				
			END 
			ELSE
			BEGIN
				UPDATE BillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@intGoodsNumberId
			END
		END
	END 
	
	-- *** 处理九种单据的结算状态 - End ***
	
	IF @@error<>0 RETURN 2 ------------发生错误
	RETURN 0
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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
















-- ========================================================================
-- 功能说明：		删除以前保存的草稿的按单结算过程
-- 最后修改作者：	冯 波
-- 最后修改时间：	2004-04-08
-- ========================================================================
CREATE        PROCEDURE [GP_InsertCompleteTotal_DelDraft]
(
 @intMoneyNumberId int          --收款单/付款单ID
)
--@encode$--
AS
    
    SET NOCOUNT ON

    Delete From CompleteTotal Where MoneyBillID=@intMoneyNumberId And Draft=1
   -- Delete From CompleteGoodTotal Where MoneyBillID=@intMoneyNumberId And Draft=1--haiquan添加按商品结算记录的删除

	
    If @@error<>0 Return 2 ------------发生错误
    Else
    Return 0













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

















-- ========================================================================
-- 功能说明：		保存草稿的按单结算过程
-- 最后修改作者：	冯 波
-- 最后修改时间：	2004-04-08
-- ========================================================================
CREATE       PROCEDURE [GP_InsertCompleteTotal_Draft]
(
 @intGoodsNumberId int,          --物流单据ID
 @intMoneyNumberId int,          --收款单/付款单ID
 @intGoodsDetailId int,
 @decCompleteTotal  NUMERIC(24, 10) , --本次结算金额
 @decNCompleteTotal  NUMERIC(24, 10) ,
 @IsSelect         bit,
 @GoodsBillType		   INT=-1
)
--@encode$--
AS
    --保存为草稿时将按单结算过程记录下来，此时并不改变BillIndex中的CompleteTotal.
    SET NOCOUNT ON
    -------------指定的单据不存在
    IF @GoodsBillType IN (404,405)
    BEGIN
		IF NOT EXISTS (SELECT 1 FROM ReceiptBillIndex WHERE BillNumberID =@intGoodsNumberId)
			RETURN 1
    END
    ELSE IF @GoodsBillType IN (423,424,425,426)
    BEGIN
		IF NOT EXISTS (SELECT 1 FROM dbo.Coupon_BillIndex WHERE BillNumberID =@intGoodsNumberId)
			RETURN 1
    END
    ELSE 
		If(NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=@intGoodsNumberId))
			Return 1 
			
    Insert CompleteTotal(GoodsBillID,GoodsBillDetailID,MoneyBillID,CompleteTotal,Draft,NCompleteTotal,IsSelect,Billtype)
           Values(@intGoodsNumberId,@intGoodsDetailId,@intMoneyNumberId,dbo.F_RoundTotal(@decCompleteTotal),1,dbo.F_RoundTotal(@decNCompleteTotal),@IsSelect,@GoodsBillType)  --表示是草稿

	
    If @@error<>0 Return 2 ------------发生错误
    Else
    Return 0

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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



-- ========================================================================
-- 功能说明：		删除以前保存的草稿的按品牌结算过程
-- ========================================================================
CREATE            PROCEDURE [GP_InsertCompleteTotalBrandar_DelDraft]
(
 @intMoneyNumberId int,          --收款单/付款单ID
 @GoodBillNumbers varchar(1000),
 @GoodsBillType INT=-1
)
--@encode$--
AS
SET NOCOUNT ON

	--删除按商品结算的草稿
	Delete From dbo.CompleteGoodTotal 
		   Where MoneyBillID=@intMoneyNumberId 
			 And Draft=1
			 AND BillType=@GoodsBillType
			 And GoodsBillid IN (SELECT * FROM F_Split(@GoodBillNumbers,'~'))
			 
  	Delete From dbo.CompleteBrandarTotal 
		   Where MoneyBillID=@intMoneyNumberId 
			 And isDraft=1
			 AND BillType=@GoodsBillType
			 And GoodsBillid IN (SELECT * FROM F_Split(@GoodBillNumbers,'~'))
		 
    If @@error<>0 Return 2 ------------发生错误
    Else
    Return 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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



-- ========================================================================
-- 功能说明：		删除以前保存的草稿的按商品结算过程
-- 最后修改作者：	haiquan 
-- 最后修改时间：	2007-04-08
-- ========================================================================
CREATE            PROCEDURE [GP_InsertCompleteTotalGood_DelDraft]
(
 @intMoneyNumberId int,          --收款单/付款单ID
 @GoodBillNumbers varchar(1000),
 @GoodsBillType INT=-1
)
--@encode$--
AS
SET NOCOUNT ON

  	Delete From CompleteGoodTotal 
		   Where MoneyBillID=@intMoneyNumberId 
			 And Draft=1
			 AND BillType=@GoodsBillType
			 And GoodsBillid IN (SELECT * FROM F_Split(@GoodBillNumbers,'~'))
			--haiquan添加按商品结算记录的删除
			 

    If @@error<>0 Return 2 ------------发生错误
    Else
    Return 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCouponAllotBillDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCouponAllotBillDT
GO

/*
作者：舒珊
描述：写入优惠券调拨单
*/
CREATE              PROCEDURE Gp_InsertCouponAllotBillDT
(
	@details TBType_CouponAllot READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
DECLARE @Re INT
EXEC @Re = Gp_Fz_Base '',2
IF @Re <> 0
BEGIN
	RAISERROR('发生未知错误！',16,1)
END

DECLARE @BillNumberID VARCHAR(50)
	
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

DELETE FROM dbo.Coupon_AllotBill WHERE BillNumberID=@BillNumberID

INSERT INTO dbo.Coupon_AllotBill
(
	billnumberid
	,Couponcode
	,couponid
	,InCargoId
	,OutCargoId
	,Comment
	,QTY
)
SELECT	billnumberid
		,Couponcode
		,couponid
		,ISNULL(InCargoId,'0')
		,ISNULL(OutCargoId,'0')
		,ISNULL(Comment,'')
		,QTY
FROM	@details A 

--更新默认货位
DECLARE @curBillNumberId NUMERIC(18,0)

SELECT TOP 1 @curBillNumberId = BillNumberId FROM @details

UPDATE	Coupon_AllotBill
SET		OutCargoId = ct.CargoID	
FROM	Coupon_AllotBill Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.OutKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId
		AND ct.IsDefault = 1
		
UPDATE	Coupon_AllotBill
SET		InCargoId = ct.CargoID	
FROM	Coupon_AllotBill Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.InKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId		
		AND ct.IsDefault = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCouponBackBillDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCouponBackBillDT
GO

/*
作者：舒珊
描述：写入优惠券退货单明细表上表体(表值)
*/
CREATE              PROCEDURE Gp_InsertCouponBackBillDT
(
	@details TBType_CouponBack READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
DECLARE @Re INT
EXEC @Re = Gp_Fz_Base '',2
IF @Re <> 0
BEGIN
	RAISERROR('发生未知错误！',16,1)
END

DECLARE @BillNumberID VARCHAR(50)
	
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

DELETE FROM dbo.coupon_BackBill WHERE BillNumberID=@BillNumberID

INSERT INTO dbo.coupon_BackBill
(
	billnumberid
	,Couponcode
	,CouponId
	,qty
	,price
	,nprice
	,total
	,ntotal
	,comment
	,CargoId
	,OutBillId


)
SELECT 
	BillNumberID
	,Couponcode
	,CouponId
	,dbo.F_RoundQty(Qty)
	,dbo.F_RoundPrice(Price)
	,dbo.F_RoundPrice(Price)
	,dbo.F_RoundTotal(Total)
	,dbo.F_RoundTotal(Total)
	,Comment
	,CargoId
	,OutBillId
	FROM @details A 
	

--更新默认货位
DECLARE @curBillNumberId NUMERIC(18,0)

SELECT TOP 1 @curBillNumberId = BillNumberId FROM @details

UPDATE	coupon_BackBill
SET		CargoId = ct.CargoID	
FROM	coupon_BackBill Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.InKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId	
		AND ct.IsDefault = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertCouponBillIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertCouponBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/***********************************************

**********************************************/
CREATE	PROCEDURE [Gp_InsertCouponBillIndex]
(
	@BillDate			DATETIME,
	@BillCode			VARCHAR(200) ,  
	@BillType			INT, 
	@FromType			INT,
	@STypeId			VARCHAR(50),
	@BTypeId			VARCHAR(50),
	@DealBTypeId		VARCHAR(50),
	@DTypeId			VARCHAR(50),
	@ETypeId			VARCHAR(50),
	@OutKTypeId			VARCHAR(50),
	@InKTypeId			VARCHAR(50),
	@Cid				INT,
	@Rate				NUMERIC(24,10),
	@ATypeId1			VARCHAR(50),
	@IfMulAccount		INT,
	@ATypeId			VARCHAR(50),
	@Comment			VARCHAR(255),
	@Explain			VARCHAR(255),
	@Maker				VARCHAR(200),
	@IsIni				INT,
	@TotalQty			NUMERIC(24,10),
	@TotalMoney			NUMERIC(24,10),
	@NTotalMoney		NUMERIC(24,10),
	@CompleteTotal		NUMERIC(24,10),
	@NCompleteTotal		NUMERIC(24,10),
	@TotalInMoney		NUMERIC(24,10),
	@NTotalInMoney		NUMERIC(24,10),
	@PosID	INT,
	@Checke				VARCHAR(50) = '',		--制单人
	@PosBillCode		VARCHAR(200)	,		--pos生单对应的pos端单据编号
	@PreferenceMoney	NUMERIC(24, 10),  --抹零金额
	@NPreferenceMoney	NUMERIC(24, 10)  --抹零金额
)
--@encode$--
AS 
    SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********
DECLARE @N INT ,
		@intVersion INT

-- 判断版本号，是否试用版
SELECT  @N = CAST(SubValue AS INT)
FROM    SysData1
WHERE   SubNo = 2	-- 版本号

IF @N IS NULL RETURN -1

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 6 AND SubValue = '1')
	AND (EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 10 AND ISNULL(SubValue,'') = '')
		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 9 AND ISNULL(SubValue,'') = '')
		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 11 AND ISNULL(SubValue,'') = '')
		 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 13 AND ISNULL(SubValue,'') = ''))		 
RETURN -3	

DECLARE @intBit INT ,
    @intMask INT
SELECT  @intBit = @N & 15
SELECT  @intMask = POWER(2, @intBit) ^ POWER(2, @intBit + 1) ^ POWER(2,
                                                          @intBit + 2)
        ^ POWER(2, @intBit + 3) ^ POWER(2, @intBit + 4) ^ POWER(2,
                                                          @intBit + 5)
SELECT  @intVersion = ( @intMask & @N ) / POWER(2, @intBit)
-- ********	判断是否试用版 - END	********

DECLARE @Re INT ,
    @Flag INT
EXEC @Re= Gp_Validate 2, @Flag OUTPUT
IF @Re <> 0 
    RETURN -3 --检查程序版本错误

IF @intVersion NOT IN ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15 ) 
BEGIN
	--RAISERROR('校验错误 ！',16,1) 
    RETURN -3 --检查程序版本错误
END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM Coupon_BillIndex
	
	IF @billnumberid >= 200
	BEGIN
		--RAISERROR('试用版最多录200条单据 ！',16,1) 
		RETURN -1
	END
END  

DECLARE @BeginDate DATETIME ,
    @szItem VARCHAR(30) ,
    @szVchCode VARCHAR(30)
    
SELECT TOP 1
        @BeginDate = startdate
FROM    monthproc
WHERE   MonthNo='本期' AND STypeID=@STypeID

IF @isini = 1 
BEGIN
	--增加独立开账期初时间判断
	DECLARE @iniBegindate DATETIME  --取会计期间开始时间
	IF NOT EXISTS(SELECT TOP 1 1  FROM dbo.sysdata WHERE SubName='stypeindependentopen' AND SubValue=1)
	BEGIN
		SELECT @iniBegindate=fBegin FROM dbo.Ac_Period 
		WHERE FYear IN (SELECT subvalue FROM dbo.sysdata WHERE subname ='fyear' ) AND FPeriod IN (SELECT subvalue FROM dbo.sysdata WHERE SubName='fmonth')
	END
	ELSE
	BEGIN
		SELECT @iniBeginDate=fbegin FROM dbo.Ac_Period A,dbo.SType_UserConfig B
		WHERE A.FPeriod=b.SFPeriod AND A.FYear=B.SFYear AND B.StypeId= @STypeID
	END
	IF @billdate >= @iniBegindate 
		RETURN -8
END

--验证录单日期小于本期开始日期
IF @BillDate < @BeginDate AND @isini = 0
BEGIN 
	--RAISERROR('录单日期小于本期开始日期 ！',16,1)
    RETURN -2
END

DECLARE @CurDate DATETIME
DECLARE @IsOrNotPassOneDay BIT
SELECT  @CurDate = GETDATE()
SELECT TOP 1
        @IsOrNotPassOneDay = value
FROM    UserConfig
WHERE   ConfigName = 'PassOneDay'
IF ( CONVERT(DATETIME, @BillDate) <> CONVERT(DATETIME, CONVERT(VARCHAR, YEAR(@CurDate))
     + '-' + CONVERT(VARCHAR, MONTH(@CurDate))
     + '-' + CONVERT(VARCHAR, DAY(@CurDate))) )
    AND ( @IsOrNotPassOneDay = 1 ) 
BEGIN 
--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
    RETURN -4
END

INSERT INTO dbo.Coupon_BillIndex
        ( 
          BillDate ,
          BillCode ,
          BillType ,
          FromType ,
          STypeId ,
          DTypeId ,
          ETypeId ,
          OutKTypeId ,
          InKTypeId ,
          Cid ,
          Rate ,
          TotalQty ,
          TotalMoney ,
          NTotalMoney ,
          CompleteTotal ,
          NCompleteTotal ,
          TotalInMoney ,
          NTotalInMoney ,
          ChargeOffTotal,
          NChargeOffTotal,
          IfMulAccount ,
          ATypeId ,
          BTypeId ,
          DealBTypeId ,
          Comment ,
          Explain,
          Poster ,
          PostTime ,
          MakeTime ,
          Maker ,
          Checker ,
          CheckeTime ,
          IfAudit ,--2=原始草稿,0=待审核草稿,-1=审核不通过草稿,1=审核通过草稿。
          Draft ,
          IfCheck ,
          RedWord ,
          IsIni ,
          IfYearBill ,
          RedReason ,
          ATypeId1 ,
          Atid ,
          TallyId,
          JsState,
          PosId,
          Checke,
          LastUpdateTime,
          PosBillCode,
          PreferenceMoney,
          NPreferenceMoney
          
        )
VALUES  ( 
          @BillDate ,
          @BillCode ,
          @BillType ,
          CASE WHEN @BillType IN (425,426) THEN  -1 ELSE  @FromType END ,
          @STypeId ,
          @DTypeId ,
          @ETypeId ,
          @OutKTypeId ,
          @InKTypeId ,
          @Cid ,
          @Rate ,
          dbo.F_RoundQty(ISNULL(@TotalQty,0)) ,
          dbo.F_RoundTotal(ISNULL(@TotalMoney,0)) ,
          dbo.F_RoundTotal(ISNULL(@NTotalMoney,0)) ,
          dbo.F_RoundTotal(ISNULL(@CompleteTotal,0)) ,
          dbo.F_RoundTotal(ISNULL(@NCompleteTotal,0)) ,
          dbo.F_RoundTotal(ISNULL(@TotalInMoney,0)) ,
          dbo.F_RoundTotal( ISNULL(@NTotalInMoney,0)) ,
          dbo.F_RoundTotal(0) ,
          dbo.F_RoundTotal( 0) ,
          @IfMulAccount ,
          @ATypeId ,
          @BTypeId ,
          @DealBTypeId ,
          @Comment ,
          @Explain ,
          '' ,
          NULL ,
          GETDATE() ,
          @Maker ,
          '' ,
          GETDATE() ,
          2 , 
          1 ,
          'f' ,
          0 ,
          @IsIni ,
          0 ,
          '' ,
          @ATypeId1 ,
          '' ,
          '',
          0,
          CASE WHEN @PosID IS NULL THEN 0 ELSE @PosID END,
          @Checke,
          NULL,
          @PosBillCode,
           dbo.F_RoundTotal( ISNULL(@NPreferenceMoney,0)),
          dbo.F_RoundTotal( ISNULL( @NPreferenceMoney,0))
        )

DECLARE @intReturn BIGINT

SELECT  @intReturn = SCOPE_IDENTITY();

RETURN @intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCouponCodeInfo') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCouponCodeInfo
GO

/*
作者：LF
描述：期初优惠券券编码写入
*/
CREATE PROCEDURE Gp_InsertCouponCodeInfo
(
	@couponCodeList TBType_CouponCodeInfo READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
DECLARE @Re INT
EXEC @Re = Gp_Fz_Base '',2
IF @Re <> 0
BEGIN
	RAISERROR('发生未知错误！',16,1)
END

INSERT INTO dbo.Coupon_CodeInfo
(
	CouponCode,
	CouponId,
	[State],
	IsIni,
	KtypeId,
	CargoId,
	IniState,
	InvalidDate,
	IsYear,
	InDate,
	OutDate,
	OutPrice,
	iniKtypeId,
	iniCargoId
)
SELECT	CouponCode,
		CouponId,
		[State],
		IsIni,
		KtypeId,		
		CargoId,
		IniState,
		InvalidDate,
		IsYear,
		InDate,
		OutDate,
		OutPrice,
		KtypeId,
		CargoId
FROM	@couponCodeList	

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCouponInBillDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCouponInBillDT
GO

/*
作者：舒珊
描述：写入优惠券入库单明细表(表值)
*/
CREATE              PROCEDURE Gp_InsertCouponInBillDT
(
	@details TBType_CouponIn READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
--DECLARE @Re INT
--EXEC @Re = Gp_Fz_Base '',2
--IF @Re <> 0
--BEGIN
--	RAISERROR('发生未知错误！',16,1)
--END

DECLARE @BillNumberID VARCHAR(50),@isini INT,@InKtypeId	varchar(50)
	
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

---期初 操作 couponcode
--SELECT @isini=IsIni ,@InKtypeId=InKtypeId  FROM dbo.Coupon_BillIndex WHERE BillNumberID=@BillNumberID
--CREATE TABLE #iniCoupon_Bill 
--(	ID int,
--	CouponCode varchar(200)
--)
--IF @isini=1
--BEGIN
--	INSERT INTO #iniCoupon_Bill 
--	(	ID,
--		CouponCode
			
--	)
--	SELECT  A.ID ,  B.StrColumn AS couponcode
--	FROM    (SELECT StrXml = CONVERT(XML, '<root><v>'+REPLACE( Couponcode, 'я', '</v><v>')+'</v></root>') , ID    FROM   
--			   dbo.coupon_InBill WHERE BillNumberID=@BillNumberID    ) A OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(200)')  FROM   A.StrXml.nodes('/root/v') N (v)   ) B 
--	--清除原表的couponcode
--	DELETE dbo.Coupon_CodeInfo where Couponcode IN (SELECT CouponCode FROM  #iniCoupon_Bill)
	
--END 

----期初 操作 couponcode

DELETE FROM dbo.Coupon_InBill WHERE BillNumberID=@BillNumberID

INSERT INTO dbo.Coupon_InBill
(
	BillNumberID
	,Couponcode
	,Comment
	,CouponId
	,Qty
	,CostPrice
	,NCostPrice
	,CostTotal
	,NCostTotal
	,CargoId
	,InDate
	,InvalidDate
	

)
SELECT 
	BillNumberID
	,Couponcode
	,Comment
	,CouponId
	,dbo.F_RoundQty(Qty)
	,dbo.F_RoundPrice(CostPrice)
	,dbo.F_RoundPrice(NCostPrice)
	,dbo.F_RoundTotal(CostTotal)
	,dbo.F_RoundTotal(NCostTotal)
	,CargoId
	,InDate
	,InvalidDate
	FROM @details A 
	
--更新默认货位
DECLARE @curBillNumberId NUMERIC(18,0)

SELECT TOP 1 @curBillNumberId = BillNumberId FROM @details

UPDATE	Coupon_InBill
SET		CargoId = ct.CargoID	
FROM	Coupon_InBill Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.InKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId
		AND ct.IsDefault = 1
	
--IF @isini=1
--BEGIN	
--	--重新加入
--	TRUNCATE TABLE #iniCoupon_Bill 
--	INSERT INTO #iniCoupon_Bill 
--	(	ID,
--		CouponCode
			
--	)
--	SELECT  A.ID ,  B.StrColumn AS couponcode
--	FROM    (SELECT StrXml = CONVERT(XML, '<root><v>'+REPLACE( Couponcode, 'я', '</v><v>')+'</v></root>') , ID    FROM   
--			   Coupon_InBill WHERE BillNumberID=@BillNumberID    ) A OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(200)')  FROM   A.StrXml.nodes('/root/v') N (v)   ) B 
			   
--	INSERT INTO dbo.Coupon_CodeInfo
--		        ( CouponCode ,
--		          CouponId ,
--		          [State] ,
--		          --Dbguid ,
--		          IsIni ,
--		          KtypeId ,
--		          CargoId ,
--		          IniState ,
--		          InvalidDate ,
--		          IsYear,
--		          outprice
		          
--		        )
--		SELECT  c.CouponCode,
--				ct.CouponId,
--				1,--在库
--				1,
--				@InKtypeId,
--				ci.cargoid,
--				1,
--				InvalidDate= CASE  WHEN ct.InvalidType=1 THEN  '9999-12-31' 
--								   WHEN ct.InvalidType=3 THEN ct.InvalidDate 
--								   WHEN ct.InvalidType=2 THEN  CASE WHEN ct.InvalidStartDateType =1 THEN dbo.F_GetInvalidDate(ci.CouponId,ci.InDate,423)
--																	WHEN ct.InvalidStartDateType =2 THEN '9999-12-31' --入库的时候 判断不到出库日期 不写
--																    ELSE '9999-12-31' END 
--									ELSE '9999-12-31'   
									
--								END ,
--				0,
--				dbo.F_RoundPrice(0)
--			FROM #iniCoupon_Bill c
--			left JOIN Coupon_InBill  ci ON c.id=ci.Id
--			INNER JOIN coupon_TypeInfo ct ON ct.CouponId=cI.CouponId
--END 
--DROP TABLE #iniCoupon_Bill	

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCouponOutBillDetailsDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCouponOutBillDetailsDT
GO

/*
作者：舒珊
描述：写入优惠券出库单明细表下表体(表值)
*/
CREATE              PROCEDURE Gp_InsertCouponOutBillDetailsDT
(
	@details TBType_CouponOutPtype READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
DECLARE @Re INT
EXEC @Re = Gp_Fz_Base '',2
IF @Re <> 0
BEGIN
	RAISERROR('发生未知错误！',16,1)
END

DECLARE @BillNumberID VARCHAR(50)
	
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

DELETE FROM dbo.Coupon_OutBill_Ptype WHERE BillNumberID=@BillNumberID

--CREATE TABLE #CurCoupon_OutBill 
--(	ID int,
--	CouponCode varchar(200)
--)

--INSERT INTO #CurCoupon_OutBill 
--(	ID,
--	CouponCode
--)
--SELECT  A.ID ,  B.StrColumn AS couponcode
--FROM    (SELECT StrXml = CONVERT(XML, '<root><v>'+REPLACE( Couponcode, 'я', '</v><v>')+'</v></root>') , ID    FROM   
--           dbo.Coupon_OutBill WHERE BillNumberID=@BillNumberID    ) A OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(200)')  FROM   A.StrXml.nodes('/root/v') N (v)   ) B 


INSERT INTO dbo.Coupon_OutBill_Ptype
(
	Bid
	,BillnumberId
	,Couponcode
	,ptypeid
	,CouponId
	,qty
	,price
	,nprice
	,total
	,ntotal



)
SELECT 
	C.ID
	,A.BillNumberID
	,A.Couponcode
	,A.ptypeid
	,A.CouponId
	,dbo.F_RoundQty(A.Qty)
	,dbo.F_RoundPrice(A.Price)
	,dbo.F_RoundPrice(A.NPrice)
	,dbo.F_RoundTotal(A.Total)
	,dbo.F_RoundTotal(A.NTotal)
	FROM @details A
	 LEFT JOIN dbo.coupon_OutBill C ON  A.Couponcode=C.Couponcode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCouponOutBillDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCouponOutBillDT
GO

/*
作者：舒珊
描述：写入优惠券出库单明细表上表体(表值)
*/
CREATE              PROCEDURE Gp_InsertCouponOutBillDT
(
	@details TBType_CouponOut READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
DECLARE @Re INT
EXEC @Re = Gp_Fz_Base '',2
IF @Re <> 0
BEGIN
	RAISERROR('发生未知错误！',16,1)
END

DECLARE @BillNumberID VARCHAR(50),@isini INT,@OutKtypeId	varchar(50)

SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

---期初 操作 couponcode
--SELECT @isini=IsIni ,@OutKtypeId=OutKtypeId  FROM dbo.Coupon_BillIndex WHERE BillNumberID=@BillNumberID
--CREATE TABLE #iniCoupon_Bill 
--(	ID int,
--	CouponCode varchar(200)
--)
--IF @isini=1
--BEGIN
--	INSERT INTO #iniCoupon_Bill 
--	(	ID,
--		CouponCode
			
--	)
--	SELECT  A.ID ,  B.StrColumn AS couponcode
--	FROM    (SELECT StrXml = CONVERT(XML, '<root><v>'+REPLACE( Couponcode, 'я', '</v><v>')+'</v></root>') , ID    FROM   
--			   dbo.coupon_OutBill WHERE BillNumberID=@BillNumberID    ) A OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(200)')  FROM   A.StrXml.nodes('/root/v') N (v)   ) B 
--	--清除原表的couponcode
--	DELETE dbo.coupon_OutBill where Couponcode IN (SELECT CouponCode FROM  #iniCoupon_Bill)
	
--END 

----期初 操作 couponcode


IF EXISTS(SELECT TOP 1 1 FROM coupon_OutBill WHERE BillNumberId=@BillNumberID)
BEGIN
	DELETE A FROM dbo.coupon_OutBill A,@details B WHERE A.BillNumberId=B.BillNumberID AND NOT EXISTS(
				   SELECT ID FROM @details B WHERE A.BillNumberID=B.BillNumberID 
											   AND A.ID=B.ID
											   AND B.ID<>0)


	INSERT INTO coupon_OutBill
	(
		BillNumberID
		,Couponcode
		,Comment
		,CouponId
		,Qty
		,Price
		,NPrice
		,Total
		,NTotal
		,OutDate
		,InvalidDate
		,CargoId
		,BackQty
		
	)
	SELECT 
		BillNumberID
		,Couponcode
		,Comment
		,CouponId
		,dbo.F_RoundQty(Qty)
		,dbo.F_RoundPrice(Price)
		,dbo.F_RoundPrice(NPrice)
		,dbo.F_RoundTotal(Total)
		,dbo.F_RoundTotal(NTotal)
		,OutDate
		,InvalidDate
		,CargoId
		,BackQty
		FROM @details A
		WHERE ID=0 OR NOT EXISTS (
			SELECT ID FROM dbo.coupon_OutBill B WHERE A.BillNumberID=B.BillNumberID 
													AND A.ID=B.ID
												)

UPDATE A SET	Couponcode=B.Couponcode
				,Comment=B.Comment
				,CouponId=B.CouponId
				,Qty=dbo.F_RoundQty(B.Qty)
				,Price=dbo.F_RoundPrice(B.Price)
				,NPrice=dbo.F_RoundPrice(B.NPrice)
				,Total=dbo.F_RoundTotal(B.Total)
				,NTotal=dbo.F_RoundTotal(B.NTotal)
				,OutDate=B.OUTDATE
				,InvalidDate=B.InvalidDate
				,CargoId=B.CargoId
				,BackQty=dbo.F_RoundQty(B.BackQty)

 FROM dbo.coupon_OutBill A,@details B WHERE A.BillNumberID=B.BillNumberID 
									  AND A.ID=B.ID
									
END 	 
ELSE 
BEGIN 
	
	INSERT INTO coupon_OutBill
	(
		BillNumberID
		,Couponcode
		,Comment
		,CouponId
		,Qty
		,Price
		,NPrice
		,Total
		,NTotal
		,OutDate
		,InvalidDate
		,CargoId
		,BackQty
	)
	SELECT 
		BillNumberID
		,Couponcode
		,Comment
		,CouponId
		,dbo.F_RoundQty(Qty)
		,dbo.F_RoundPrice(Price)
		,dbo.F_RoundPrice(NPrice)
		,dbo.F_RoundTotal(Total)
		,dbo.F_RoundTotal(NTotal)
		,OutDate
		,InvalidDate
		,CargoId
		,BackQty
		FROM @details A
END 

--IF @isini=1
--BEGIN	
--	--重新加入
--	TRUNCATE TABLE #iniCoupon_Bill 
--	INSERT INTO #iniCoupon_Bill 
--	(	ID,
--		CouponCode
			
--	)
--	SELECT  A.ID ,  B.StrColumn AS couponcode
--	FROM    (SELECT StrXml = CONVERT(XML, '<root><v>'+REPLACE( Couponcode, 'я', '</v><v>')+'</v></root>') , ID    FROM   
--			   coupon_OutBill WHERE BillNumberID=@BillNumberID    ) A OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(200)')  FROM   A.StrXml.nodes('/root/v') N (v)   ) B 
			   
--	INSERT INTO dbo.Coupon_CodeInfo
--		        ( CouponCode ,
--		          CouponId ,
--		          [State] ,
--		          --Dbguid ,
--		          IsIni ,
--		          KtypeId ,
--		          CargoId ,
--		          IniState ,
--		          InvalidDate ,
--		          IsYear,
--		          outprice
		          
--		        )
--		SELECT  c.CouponCode,
--				ct.CouponId,
--				2,--出库
--				1,
--				@OutKtypeId,
--				ci.cargoid,
--				1,
--				InvalidDate= CASE  WHEN ct.InvalidType=1 THEN  '9999-12-31' 
--								   WHEN ct.InvalidType=3 THEN ct.InvalidDate 
--								   WHEN ct.InvalidType=2 THEN  CASE WHEN ct.InvalidStartDateType =1 THEN dbo.F_GetInvalidDate(ci.CouponId,ci.OutDate,423)
--																	WHEN ct.InvalidStartDateType =2 THEN '9999-12-31' --入库的时候 判断不到出库日期 不写
--																    ELSE '9999-12-31' END 
--									ELSE '9999-12-31'   
									
--								END ,
--				0,
--				ci.NPrice
--			FROM #iniCoupon_Bill c
--			left JOIN coupon_OutBill  ci ON c.id=ci.Id
--			INNER JOIN coupon_TypeInfo ct ON ct.CouponId=cI.CouponId
--END 
--DROP TABLE #iniCoupon_Bill	

--更新默认货位
DECLARE @curBillNumberId NUMERIC(18,0)

SELECT TOP 1 @curBillNumberId = BillNumberId FROM @details

UPDATE	Coupon_OutBill
SET		CargoId = ct.CargoID	
FROM	Coupon_OutBill Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.OutKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId
		AND ct.IsDefault = 1

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCouponStypeInBillDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCouponStypeInBillDT
GO

/*
作者：谢吉康
日期：2019-11-08
描述：写入优惠券分支机构调拨入库单明细表(表值)
*/
CREATE PROCEDURE Gp_InsertCouponStypeInBillDT
(
	@details TBType_CouponAllotStype READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @BillNumberID VARCHAR(50),@isini INT,@InKtypeId	varchar(50)
	
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

DELETE FROM dbo.Coupon_AllotBillStype WHERE BillNumberID=@BillNumberID

INSERT INTO dbo.Coupon_AllotBillStype
(
	BillNumberID
	,Couponcode
	,Comment
	,CouponId
	,Qty
	,Price
	,Total
	--,CostPrice
	--,NCostPrice
	--,CostTotal
	--,NCostTotal
	--,CargoId
	--,InDate
	,InvalidDate
	,InStockDate
)
SELECT	BillNumberID
		,Couponcode
		,Comment
		,CouponId
		,dbo.F_RoundQty(Qty)
		,dbo.F_RoundPrice(Price)
		,dbo.F_RoundTotal(Total)
		--,dbo.F_RoundPrice(CostPrice)
		--,dbo.F_RoundPrice(NCostPrice)
		--,dbo.F_RoundTotal(CostTotal)
		--,dbo.F_RoundTotal(NCostTotal)
		--,CargoId
		--,InDate
		,InvalidDate
		,InStockDate
	FROM @details A 
	
--更新默认货位
DECLARE @curBillNumberId NUMERIC(18,0)

SELECT TOP 1 @curBillNumberId = BillNumberId FROM @details

--修改货位
UPDATE	Coupon_AllotBillStype
SET		InCargoId = ct.CargoID	
FROM	Coupon_AllotBillStype Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.InKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId
		AND ct.IsDefault = 1
		
UPDATE	Coupon_AllotBillStype
SET		OutCargoId = ct.CargoID	
FROM	Coupon_AllotBillStype Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.OutKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId
		AND ct.IsDefault = 1		


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertCouponStypeOutBillDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertCouponStypeOutBillDT
GO

/*
作者：谢吉康
日期：2019-11-08
描述：写入优惠券分支机构调拨出库单明细表(表值)
*/
CREATE  PROCEDURE Gp_InsertCouponStypeOutBillDT
(
	@details TBType_CouponAllotStype READONLY
)
--@encode$--
AS 
SET NOCOUNT ON


DECLARE @BillNumberID VARCHAR(50),@isini INT,@OutKtypeId	varchar(50)

SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

DELETE FROM dbo.Coupon_AllotBillStype WHERE BillNumberID=@BillNumberID
	
INSERT INTO Coupon_AllotBillStype
(
	BillNumberID
	,Couponcode
	,Comment
	,CouponId
	,Qty
	,Price
	--,NPrice
	,Total
	--,NTotal
	--,OutDate
	--,InvalidDate
	--,CargoId
	--,BackQty
	,InStockDate
)
SELECT	BillNumberID
		,Couponcode
		,Comment
		,CouponId
		,dbo.F_RoundQty(Qty)
		,dbo.F_RoundPrice(Price)
		--,dbo.F_RoundPrice(NPrice)
		,dbo.F_RoundTotal(Total)
		--,dbo.F_RoundTotal(NTotal)
		--,OutDate
		--,InvalidDate
		--,CargoId
		--,BackQty
		,InStockDate
FROM	@details A

--更新默认货位
DECLARE @curBillNumberId NUMERIC(18,0)

SELECT TOP 1 @curBillNumberId = BillNumberId FROM @details

UPDATE	Coupon_AllotBillStype
SET		InCargoId = ct.CargoID	
FROM	Coupon_AllotBillStype Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.InKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId
		AND ct.IsDefault = 1
		
UPDATE	Coupon_AllotBillStype
SET		OutCargoId = ct.CargoID	
FROM	Coupon_AllotBillStype Inb,		
		Coupon_BillIndex Bi,		
		CargoType ct
WHERE	Inb.BillNumberId = bi.BillNumberId
		AND Bi.OutKTypeId = ct.KtypeID
		AND Inb.BillNumberId = @curBillNumberId
		AND ct.IsDefault = 1

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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










CREATE                     PROCEDURE Gp_InsertCRMB
(
 @Parid   [varchar](50),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @Name  [Varchar](30), 
 @Area  [Varchar](30),
 @TelAndAddress  [varchar](66),
 @PostCode  [varchar](10),
 @Person  [varchar](20),
 @TaxNumber  [varchar](20),
 @Account  [varchar](66),
 @Artotal00  NUMERIC(24, 10) ,
 @Aptotal00    NUMERIC(24, 10) ,
 @Comment  [varchar](256),
 @Client [Bit]=1,
 @ARLimit VARCHAR(50),
 @ARLimitTime  NUMERIC(24, 10) =99999,
 @PaymentLTime NUMERIC(24, 10) =99999, 
 @Tel1 varchar(50),
 @Tel2 varchar(50),
 @Tel3 varchar(50),
 @WWW varchar(50),
 @Email varchar(50),
 @Fax varchar(50),
 @Bank varchar(50),
 @BankName varchar(50),
@LinkManId1 varchar(50),
@LinkMan1 varchar(50),
@LinkSex1 bit,
@LinkBirthDay1 datetime,
@LinkJob1 varchar(50),
@LinkCall1 Varchar(50),
@LinkTel1 varchar(50),
@LinkMobile1 varchar(50),
@LinkEMail1 varchar(50),
@LinkPost1 varchar(50),
@LinkAddress1 varchar(50),
@LinkComment1 varchar(50),
@LinkManId2 varchar(50),
@LinkMan2 varchar(50),
@LinkSex2 bit,
@LinkBirthDay2 datetime,
@LinkJob2 varchar(50),
@LinkCall2 Varchar(50),
@LinkTel2 varchar(50),
@LinkMobile2 varchar(50),
@LinkEMail2 varchar(50),
@LinkPost2 varchar(50),
@LinkAddress2 varchar(50),
@LinkComment2 varchar(50),
@CreateDate varchar(10),
@SaleZeKou  NUMERIC(24, 10) ,
@BuyZeKou  NUMERIC(24, 10) ,
@PyCode   varchar(200),
@Price    varchar(50),
@AreaTypeID varchar(50),
@OperateId varchar(100),
@OperateName varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @returnPym varchar(1000)
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

SET @EtypeId_1 = '00001'
SET @ParId = '00000'
SET @nSonnum = 0
SET @nSoncount = 0


EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

DECLARE @Ar00Temp  NUMERIC(24, 10) 
DECLARE @Ap00Temp  NUMERIC(24, 10) 
SET @Ar00Temp =0
SET @Ap00Temp =0


SET @Parid = '00001'

begin tran insertproc
select @leveal=leveal from btype where typeid=@Parid
select @leveal=@leveal+1

INSERT INTO [CRM_btype] 
  ([Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [USERCODE],
  [Area],
  [TelAndAddress],
  [PostCode],
  [Name],
  [Person],
  [TaxNumber],
  [BankAndAcount],
  [ARTotal],
  [APTotal],
  [ARTotal00],
  [APTotal00],
  [deleted],
  [Comment],
  [Client],
  [ARLimit],
  [ARLimitTime],
  [PaymentLTime],
  [Tel1],
  [Tel2],
  [Tel3],
  [WWW],
  [Email],
  [Fax],
  [Bank],
  [BankName],
[LinkManId1],
[LinkMan1],
[LinkSex1],
[LinkBirthDay1],
[LinkJob1],
[LinkCall1],
[LinkTel1],
[LinkMobile1],
[LinkEMail1],
[LinkPost1],
[LinkAddress1],
[LinkComment1],
[LinkManId2],
[LinkMan2],
[LinkSex2],
[LinkBirthDay2],
[LinkJob2 ],
[LinkCall2],
[LinkTel2],
[LinkMobile2],
[LinkEMail2],
[LinkPost2],
[LinkAddress2],
[LinkComment2],
[CreateDate],
[SaleZeKou],
[BuyZeKou],
[PyCode],
[Price],
[AreaTypeID],
[Createor],
[CreateorName]
) 
 
VALUES 
 (@Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Area,
  @TelAndAddress,
  @PostCode,
  @Name,
  @Person,
  @TaxNumber,
  @Account,
  0,
  0,
  0,
  0,
  0,
  @Comment,
  @Client,
  dbo.F_RoundTotal(CAST(@ARLimit AS  NUMERIC(24, 10) )),
  @ARLimitTime,
  @PaymentLTime,
 @Tel1,
 @Tel2,
 @Tel3,
 @WWW,
 @Email,
 @Fax,
 @Bank,
 @BankName,
@LinkManId1,
@LinkMan1,
@LinkSex1,
@LinkBirthDay1,
@LinkJob1,
@LinkCall1,
@LinkTel1,
@LinkMobile1,
@LinkEMail1,
@LinkPost1,
@LinkAddress1,
@LinkComment1,
@LinkManId2,
@LinkMan2,
@LinkSex2,
@LinkBirthDay2,
@LinkJob2,
@LinkCall2,
@LinkTel2,
@LinkMobile2,
@LinkEMail2,
@LinkPost2,
@LinkAddress2,
@LinkComment2,
@CreateDate,
dbo.F_RoundDiscount(@SaleZeKou),
dbo.F_RoundDiscount(@BuyZeKou),
@returnPym,
dbo.F_RoundPrice(@Price),
@AreaTypeID,
@OperateId,
@OperateName
)

if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end 

-- 建立Employee数据 .超级用户的节点 --
--select @UserCode=@UserCode+'_超级用户'
--exec @nReturnType=Gp_InsertE '00000','employee',@UserCode,'超级用户','','','','',@EtypeId_1
if (@nReturnType <> 0)
begin 
 rollback tran insertproc 
 return @nReturnType 
end
commit tran insertproc

UPDATE CRM_LinkMan SET Crm_BtypeId =SCOPE_IDENTITY() WHERE [id]=@LinkManId1
UPDATE CRM_LinkMan SET Crm_BtypeId =SCOPE_IDENTITY() WHERE [id]=@LinkManId2


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--SELECT * FROM dbo.sqlLog ORDER BY id DESC 
--exec Gp_InsertCRMB @Parid='',@UserCode='klk',@FullName='lll',@Name='',@Area='',@TelAndAddress='ilkjkl',@PostCode='33333',@Person='',@TaxNumber='5245',@Account='542424',@Artotal00=0,@Aptotal00=0,@Comment='2lhfgghf',@Client=1,@ARLimit='0.0',@ARLimitTime=252,@PaymentLTime=55,@Tel1='111',@Tel2='111',@Tel3='111',@WWW='kolpo',@Email='pp@sina.com',@Fax='uiioi2212',@Bank='uiolo',@BankName='kopop',@LinkManId1='',@LinkMan1='',@LinkSex1=0,@LinkBirthDay1=NULL,@LinkJob1='',@LinkCall1='',@LinkTel1='',@LinkMobile1='',@LinkEMail1='',@LinkPost1='',@LinkAddress1='',@LinkComment1='',@LinkManId2='',@LinkMan2='',@LinkSex2=0,@LinkBirthDay2=NULL,@LinkJob2='',@LinkCall2='',@LinkTel2='',@LinkMobile2='',@LinkEMail2='',@LinkPost2='',@LinkAddress2='',@LinkComment2='',@CreateDate='2012-06-20 00:00:00',@SaleZeKou=1,@BuyZeKou=1,@PyCode='ll',@Price=0,@AreaTypeID='00001',@OperateId='00001',@OperateName='超级用户'



/*
*			9.7表体自定义
*			2015-10-15
*/
GO
	IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertCustom_BillDetails',N'P'))
	BEGIN
		DROP PROC GP_InsertCustom_BillDetails
	END
GO
	CREATE PROC GP_InsertCustom_BillDetails
	(
		@BillId			INT,
		@Detailid		INT,
		@BillType		INT,
		@SysDiy1		VARCHAR(500)='',
		@SysDiy2		VARCHAR(500)='',
		@SysDiy3		VARCHAR(500)='',
		@SysDiy4		VARCHAR(500)='',
		@SysDiy5		VARCHAR(500)='',
		@SysDiy6		NUMERIC(22,10)=0,
		@SysDiy7		NUMERIC(22,10)=0,
		@SysDiy8		NUMERIC(22,10)=0,
		@SysDiy9		NUMERIC(22,10)=0,
		@SysDiy10		NUMERIC(22,10)=0,
		@SysDiy11		VARCHAR(500)='',
		@SysDiy12		VARCHAR(500)='',
		@SysDiy13		VARCHAR(500)='',
		@SysDiy14		VARCHAR(500)='',
		@SysDiy15		VARCHAR(500)='',
		@SysDiy16		VARCHAR(500)='',
		@SysDiy17	VARCHAR(500),
		@SysDiy18	VARCHAR(500),
		@SysDiy19	VARCHAR(500),
		@SysDiy20	VARCHAR(500),
		@SysDiy21	VARCHAR(500),
		@SysDiy22	VARCHAR(500),
		@SysDiy23	VARCHAR(500),
		@SysDiy24	VARCHAR(500),
		@SysDiy25	VARCHAR(500),
		@SysDiy26	VARCHAR(500),
		@SysDiy27	NUMERIC(24,10)=0,
		@SysDiy28	NUMERIC(24,10)=0,
		@SysDiy29	NUMERIC(24,10)=0,
		@SysDiy30	NUMERIC(24,10)=0,
		@SysDiy31	NUMERIC(24,10)=0,
		@SysDiy32	VARCHAR(20)='',		
		@SysDiy33	VARCHAR(500)='',
		@SysDiy34	VARCHAR(500)='',
		@SysDiy35	VARCHAR(500)='',
		@SysDiy36	VARCHAR(500)='',
		@SysDiy37	VARCHAR(500)='',
		@SysDiy38	VARCHAR(500)='',
		@SysDiy39	VARCHAR(500)='',
		@SysDiy40	VARCHAR(500)='',
		@InOrOut	CHAR(1)=''
	)
	AS
	BEGIN
		INSERT INTO dbo.Custom_BillDetails
		( 
			BillId ,
			Detailid ,
			BillType ,
			SysDiy1 ,
			SysDiy2 ,
			SysDiy3 ,
			SysDiy4 ,
			SysDiy5 ,
			SysDiy6 ,
			SysDiy7 ,
			SysDiy8 ,
			SysDiy9 ,
			SysDiy10 ,
			SysDiy11 ,
			SysDiy12 ,
			SysDiy13 ,
			SysDiy14 ,
			SysDiy15 ,
			SysDiy16,
			SysDiy17,
			SysDiy18,
			SysDiy19,
			SysDiy20,
			SysDiy21,
			SysDiy22,
			SysDiy23,
			SysDiy24,
			SysDiy25,
			SysDiy26,
			SysDiy27,
			SysDiy28,
			SysDiy29,
			SysDiy30,
			SysDiy31,
			SysDiy32,
			SysDiy33,
			SysDiy34,
			SysDiy35,
			SysDiy36,
			SysDiy37,
			SysDiy38,
			SysDiy39,
			SysDiy40,					
			InOrOut
		)VALUES( 
			@BillId ,
			@Detailid ,
			@BillType ,
			@SysDiy1 ,
			@SysDiy2 ,
			@SysDiy3 ,
			@SysDiy4 ,
			@SysDiy5 ,
			@SysDiy6 ,
			@SysDiy7 ,
			@SysDiy8 ,
			@SysDiy9 ,
			@SysDiy10 ,
			@SysDiy11 ,
			@SysDiy12 ,
			@SysDiy13 ,
			@SysDiy14 ,
			@SysDiy15 ,
			@SysDiy16,
			@SysDiy17,
			@SysDiy18 ,
			@SysDiy19 ,
			@SysDiy20 ,
			@SysDiy21 ,
			@SysDiy22 ,
			@SysDiy23 ,
			@SysDiy24 ,
			@SysDiy25 ,
			@SysDiy26 ,
			@SysDiy27 ,
			@SysDiy28 ,
			@SysDiy29 ,
			@SysDiy30 ,
			@SysDiy31 ,
			CASE @SysDiy32 WHEN '' THEN NULL ELSE CONVERT(VARCHAR(10),@SysDiy32,120) END,
			@SysDiy33,
			@SysDiy34,
			@SysDiy35,
			@SysDiy36,
			@SysDiy37,
			@SysDiy38,
			@SysDiy39,
			@SysDiy40,
			@InOrOut	
		)
		IF @@ROWCOUNT =0 OR @@ERROR<>0
		RETURN -5
	END
GO



/*
*			9.7表体自定义
*			2015-10-15
*/
GO
	IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertCustom_BillDetailsAutoDraft',N'P'))
	BEGIN
		DROP PROC GP_InsertCustom_BillDetailsAutoDraft
	END
GO
	CREATE PROC GP_InsertCustom_BillDetailsAutoDraft
	(
		@BillGuid		VARCHAR(100),
		@BillId			INT,
		@Detailid		INT,
		@BillType		INT,
		@SysDiy1		VARCHAR(500)='',
		@SysDiy2		VARCHAR(500)='',
		@SysDiy3		VARCHAR(500)='',
		@SysDiy4		VARCHAR(500)='',
		@SysDiy5		VARCHAR(500)='',
		@SysDiy6		NUMERIC(22,10)=0,
		@SysDiy7		NUMERIC(22,10)=0,
		@SysDiy8		NUMERIC(22,10)=0,
		@SysDiy9		NUMERIC(22,10)=0,
		@SysDiy10		NUMERIC(22,10)=0,
		@SysDiy11		VARCHAR(500)='',
		@SysDiy12		VARCHAR(500)='',
		@SysDiy13		VARCHAR(500)='',
		@SysDiy14		VARCHAR(500)='',
		@SysDiy15		VARCHAR(500)='',
		@SysDiy16		VARCHAR(500)='',
		@SysDiy17	VARCHAR(500),
		@SysDiy18	VARCHAR(500),
		@SysDiy19	VARCHAR(500),
		@SysDiy20	VARCHAR(500),
		@SysDiy21	VARCHAR(500),
		@SysDiy22	VARCHAR(500),
		@SysDiy23	VARCHAR(500),
		@SysDiy24	VARCHAR(500),
		@SysDiy25	VARCHAR(500),
		@SysDiy26	VARCHAR(500),
		@SysDiy27	NUMERIC(24,10)=0,
		@SysDiy28	NUMERIC(24,10)=0,
		@SysDiy29	NUMERIC(24,10)=0,
		@SysDiy30	NUMERIC(24,10)=0,
		@SysDiy31	NUMERIC(24,10)=0,
		@SysDiy32	VARCHAR(20)='',		
		@SysDiy33	VARCHAR(500)='',
		@SysDiy34	VARCHAR(500)='',
		@SysDiy35	VARCHAR(500)='',
		@SysDiy36	VARCHAR(500)='',
		@SysDiy37	VARCHAR(500)='',
		@SysDiy38	VARCHAR(500)='',
		@SysDiy39	VARCHAR(500)='',
		@SysDiy40	VARCHAR(500)='',
		@InOrOut	CHAR(1)=''
	)
	AS
	BEGIN
		INSERT INTO dbo.Custom_BillDetailsAutoDraft
		( 
			BillGuid,
			BillId ,
			Detailid ,
			BillType ,
			SysDiy1 ,
			SysDiy2 ,
			SysDiy3 ,
			SysDiy4 ,
			SysDiy5 ,
			SysDiy6 ,
			SysDiy7 ,
			SysDiy8 ,
			SysDiy9 ,
			SysDiy10 ,
			SysDiy11 ,
			SysDiy12 ,
			SysDiy13 ,
			SysDiy14 ,
			SysDiy15 ,
			SysDiy16,
			SysDiy17,
			SysDiy18,
			SysDiy19,
			SysDiy20,
			SysDiy21,
			SysDiy22,
			SysDiy23,
			SysDiy24,
			SysDiy25,
			SysDiy26,
			SysDiy27,
			SysDiy28,
			SysDiy29,
			SysDiy30,
			SysDiy31,
			SysDiy32,
			SysDiy33,
			SysDiy34,
			SysDiy35,
			SysDiy36,
			SysDiy37,
			SysDiy38,
			SysDiy39,
			SysDiy40,					
			InOrOut
		)VALUES( 
			@BillGuid,
			@BillId ,
			@Detailid ,
			@BillType ,
			@SysDiy1 ,
			@SysDiy2 ,
			@SysDiy3 ,
			@SysDiy4 ,
			@SysDiy5 ,
			@SysDiy6 ,
			@SysDiy7 ,
			@SysDiy8 ,
			@SysDiy9 ,
			@SysDiy10 ,
			@SysDiy11 ,
			@SysDiy12 ,
			@SysDiy13 ,
			@SysDiy14 ,
			@SysDiy15 ,
			@SysDiy16,
			@SysDiy17,
			@SysDiy18 ,
			@SysDiy19 ,
			@SysDiy20 ,
			@SysDiy21 ,
			@SysDiy22 ,
			@SysDiy23 ,
			@SysDiy24 ,
			@SysDiy25 ,
			@SysDiy26 ,
			@SysDiy27 ,
			@SysDiy28 ,
			@SysDiy29 ,
			@SysDiy30 ,
			@SysDiy31 ,
			CASE @SysDiy32 WHEN '' THEN NULL ELSE CONVERT(VARCHAR(10),@SysDiy32,120) END,
			@SysDiy33,
			@SysDiy34,
			@SysDiy35,
			@SysDiy36,
			@SysDiy37,
			@SysDiy38,
			@SysDiy39,
			@SysDiy40,
			@InOrOut	
		)
		IF @@ROWCOUNT =0 OR @@ERROR<>0
		RETURN -5
	END
GO



GO
/*
*			9.7自定义表头保存
*			2015-10-15
*/

IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertCustom_BillIndex',N'P'))
BEGIN
	DROP PROC GP_InsertCustom_BillIndex
END
Go

CREATE PROC GP_InsertCustom_BillIndex
(
	@BillId			INT,
	@BillType		INT,
	@SysDiy1	VARCHAR(500)='',
	@SysDiy2	VARCHAR(500)='',
	@SysDiy3	VARCHAR(500)='',
	@SysDiy4	VARCHAR(500)='',
	@SysDiy5	VARCHAR(500)='',
	@SysDiy6	NUMERIC(24,10)=0,
	@SysDiy7	NUMERIC(24,10)=0,
	@SysDiy8	NUMERIC(24,10)=0,
	@SysDiy9	NUMERIC(24,10)=0,
	@SysDiy10	NUMERIC(24,10)=0,
	@SysDiy11	VARCHAR(500)='',
	@SysDiy12	VARCHAR(500)='',
	@SysDiy13	VARCHAR(500)='',
	@SysDiy14	VARCHAR(500)='',
	@SysDiy15	VARCHAR(500)='',
	@SysDiy16	VARCHAR(500)='',
	@SysDiy17	VARCHAR(500)='',
	@SysDiy18	VARCHAR(500)='',
	@SysDiy19	VARCHAR(500)='',
	@SysDiy20	VARCHAR(500)='',
	@SysDiy21	VARCHAR(500)='',
	@SysDiy22	VARCHAR(500)='',
	@SysDiy23	VARCHAR(500)='',
	@SysDiy24	VARCHAR(500)='',
	@SysDiy25	VARCHAR(500)='',
	@SysDiy26	VARCHAR(500)='',
	@SysDiy27	NUMERIC(24,10)=0,
	@SysDiy28	NUMERIC(24,10)=0,
	@SysDiy29	NUMERIC(24,10)=0,
	@SysDiy30	NUMERIC(24,10)=0,
	@SysDiy31	NUMERIC(24,10)=0,
	@SysDiy32	VARCHAR(20)='',
	@SysDiy33	VARCHAR(500)='',
	@SysDiy34	VARCHAR(500)='',
	@SysDiy35	VARCHAR(500)='',
	@SysDiy36	VARCHAR(500)='',
	@SysDiy37	VARCHAR(500)='',
	@SysDiy38	VARCHAR(500)='',
	@SysDiy39	VARCHAR(500)='',
	@SysDiy40	VARCHAR(500)=''
)
AS
BEGIN
	DELETE FROM dbo.Custom_BillIndex WHERE BillId = @BillId AND BillType = @BillType

	INSERT INTO dbo.Custom_BillIndex
	( 
		BillId ,
		BillType ,
		SysDiy1_head ,
		SysDiy2_head ,
		SysDiy3_head ,
		SysDiy4_head ,
		SysDiy5_head ,
		SysDiy6_head ,
		SysDiy7_head ,
		SysDiy8_head ,
		SysDiy9_head ,
		SysDiy10_head ,
		SysDiy11_head ,
		SysDiy12_head ,
		SysDiy13_head ,
		SysDiy14_head ,
		SysDiy15_head ,
		SysDiy16_head ,
		SysDiy17_head,
		SysDiy18_head,
		SysDiy19_head,
		SysDiy20_head,
		SysDiy21_head,
		SysDiy22_head,
		SysDiy23_head,
		SysDiy24_head,
		SysDiy25_head,
		SysDiy26_head,
		SysDiy27_head,
		SysDiy28_head,
		SysDiy29_head,
		SysDiy30_head,
		SysDiy31_head,
		SysDiy32_head,
		SysDiy33_head,
		SysDiy34_head,
		SysDiy35_head,
		SysDiy36_head,
		SysDiy37_head,
		SysDiy38_head,
		SysDiy39_head,
		SysDiy40_head
	)VALUES( 
		@BillId,
		@BillType ,
		@SysDiy1 ,
		@SysDiy2 ,
		@SysDiy3 ,
		@SysDiy4 ,
		@SysDiy5 ,
		@SysDiy6 ,
		@SysDiy7 ,
		@SysDiy8 ,
		@SysDiy9 ,
		@SysDiy10 ,
		@SysDiy11 ,
		@SysDiy12 ,
		@SysDiy13 ,
		@SysDiy14 ,
		@SysDiy15 ,
		@SysDiy16 ,
		@SysDiy17 ,
		@SysDiy18 ,
		@SysDiy19 ,
		@SysDiy20 ,
		@SysDiy21 ,
		@SysDiy22 ,
		@SysDiy23 ,
		@SysDiy24 ,
		@SysDiy25 ,
		@SysDiy26 ,
		@SysDiy27 ,
		@SysDiy28 ,
		@SysDiy29 ,
		@SysDiy30 ,
		@SysDiy31 ,
		CASE @SysDiy32 WHEN '' THEN NULL ELSE CONVERT(VARCHAR(10),@SysDiy32,120) END,
		@SysDiy33,
		@SysDiy34,
		@SysDiy35,
		@SysDiy36,
		@SysDiy37,
		@SysDiy38,
		@SysDiy39,
		@SysDiy40
	)
	
	IF @@ROWCOUNT =0 OR @@ERROR<>0
	RETURN -5
END
GO




GO
/*
*			9.7自定义表头保存
*			2015-10-15
*/

IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertCustom_BillIndexAutoDraft',N'P'))
BEGIN
	DROP PROC GP_InsertCustom_BillIndexAutoDraft
END
Go

CREATE PROC GP_InsertCustom_BillIndexAutoDraft
(
	@BillGuid		VARCHAR(100),
	@BillId			INT,
	@BillType		INT,
	@SysDiy1	VARCHAR(500)='',
	@SysDiy2	VARCHAR(500)='',
	@SysDiy3	VARCHAR(500)='',
	@SysDiy4	VARCHAR(500)='',
	@SysDiy5	VARCHAR(500)='',
	@SysDiy6	NUMERIC(24,10)=0,
	@SysDiy7	NUMERIC(24,10)=0,
	@SysDiy8	NUMERIC(24,10)=0,
	@SysDiy9	NUMERIC(24,10)=0,
	@SysDiy10	NUMERIC(24,10)=0,
	@SysDiy11	VARCHAR(500)='',
	@SysDiy12	VARCHAR(500)='',
	@SysDiy13	VARCHAR(500)='',
	@SysDiy14	VARCHAR(500)='',
	@SysDiy15	VARCHAR(500)='',
	@SysDiy16	VARCHAR(500)='',
	@SysDiy17	VARCHAR(500)='',
	@SysDiy18	VARCHAR(500)='',
	@SysDiy19	VARCHAR(500)='',
	@SysDiy20	VARCHAR(500)='',
	@SysDiy21	VARCHAR(500)='',
	@SysDiy22	VARCHAR(500)='',
	@SysDiy23	VARCHAR(500)='',
	@SysDiy24	VARCHAR(500)='',
	@SysDiy25	VARCHAR(500)='',
	@SysDiy26	VARCHAR(500)='',
	@SysDiy27	NUMERIC(24,10)=0,
	@SysDiy28	NUMERIC(24,10)=0,
	@SysDiy29	NUMERIC(24,10)=0,
	@SysDiy30	NUMERIC(24,10)=0,
	@SysDiy31	NUMERIC(24,10)=0,
	@SysDiy32	VARCHAR(20)='',
	@SysDiy33	VARCHAR(500)='',
	@SysDiy34	VARCHAR(500)='',
	@SysDiy35	VARCHAR(500)='',
	@SysDiy36	VARCHAR(500)='',
	@SysDiy37	VARCHAR(500)='',
	@SysDiy38	VARCHAR(500)='',
	@SysDiy39	VARCHAR(500)='',
	@SysDiy40	VARCHAR(500)=''
)
AS
BEGIN
	DELETE FROM dbo.Custom_BillIndexAutoDraft WHERE BillGuid = @BillGuid AND BillType = @BillType

	INSERT INTO dbo.Custom_BillIndexAutoDraft
	( 
		BillGuid,
		BillId ,
		BillType ,
		SysDiy1_head ,
		SysDiy2_head ,
		SysDiy3_head ,
		SysDiy4_head ,
		SysDiy5_head ,
		SysDiy6_head ,
		SysDiy7_head ,
		SysDiy8_head ,
		SysDiy9_head ,
		SysDiy10_head ,
		SysDiy11_head ,
		SysDiy12_head ,
		SysDiy13_head ,
		SysDiy14_head ,
		SysDiy15_head ,
		SysDiy16_head ,
		SysDiy17_head,
		SysDiy18_head,
		SysDiy19_head,
		SysDiy20_head,
		SysDiy21_head,
		SysDiy22_head,
		SysDiy23_head,
		SysDiy24_head,
		SysDiy25_head,
		SysDiy26_head,
		SysDiy27_head,
		SysDiy28_head,
		SysDiy29_head,
		SysDiy30_head,
		SysDiy31_head,
		SysDiy32_head,
		SysDiy33_head,
		SysDiy34_head,
		SysDiy35_head,
		SysDiy36_head,
		SysDiy37_head,
		SysDiy38_head,
		SysDiy39_head,
		SysDiy40_head
	)VALUES( 
		@BillGuid,
		@BillId,
		@BillType ,
		@SysDiy1 ,
		@SysDiy2 ,
		@SysDiy3 ,
		@SysDiy4 ,
		@SysDiy5 ,
		@SysDiy6 ,
		@SysDiy7 ,
		@SysDiy8 ,
		@SysDiy9 ,
		@SysDiy10 ,
		@SysDiy11 ,
		@SysDiy12 ,
		@SysDiy13 ,
		@SysDiy14 ,
		@SysDiy15 ,
		@SysDiy16 ,
		@SysDiy17 ,
		@SysDiy18 ,
		@SysDiy19 ,
		@SysDiy20 ,
		@SysDiy21 ,
		@SysDiy22 ,
		@SysDiy23 ,
		@SysDiy24 ,
		@SysDiy25 ,
		@SysDiy26 ,
		@SysDiy27 ,
		@SysDiy28 ,
		@SysDiy29 ,
		@SysDiy30 ,
		@SysDiy31 ,
		CASE @SysDiy32 WHEN '' THEN NULL ELSE CONVERT(VARCHAR(10),@SysDiy32,120) END,
		@SysDiy33,
		@SysDiy34,
		@SysDiy35,
		@SysDiy36,
		@SysDiy37,
		@SysDiy38,
		@SysDiy39,
		@SysDiy40
	)
	
	IF @@ROWCOUNT =0 OR @@ERROR<>0
	RETURN -5
END
GO




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE                                            PROCEDURE [Gp_InsertCustomBillColumns]
(
	@billnumberid         numeric(18,0),
	@billtype             varchar(100),
	@Costom1              VARCHAR(600)='',
	@Costom2              VARCHAR(600)='',
	@Costom3              VARCHAR(600)='',
	@Costom4              VARCHAR(600)='',
	@Costom5              VARCHAR(600)='',
	@Costom6              VARCHAR(600)='',
	@Costom7              VARCHAR(600)='',
	@Costom8              VARCHAR(600)='',
	@Costom9              VARCHAR(600)='',
	@Costom10             VARCHAR(600)='',
	@Costom11             VARCHAR(600)='',
	@Costom12             VARCHAR(600)='',
	@Costom13             VARCHAR(600)='',
	@Costom14             VARCHAR(600)='',
	@Costom15             VARCHAR(600)='',
	@Costom16             VARCHAR(600)=''
	)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN

IF EXISTS(SELECT 1 FROM CustomBillColumnsDefines WHERE billtype=@billtype)
begin
	INSERT INTO [dbo].[CustomBillColumns] 
(
	billnumberid,
	billtype,
	Costom1,     
	Costom2,     
	Costom3,     
	Costom4,     
	Costom5,     
	Costom6,     
	Costom7,     
	Costom8,     
	Costom9,     
	Costom10,    
	Costom11,    
	Costom12,    
	Costom13,    
	Costom14,    
	Costom15,    
	Costom16	
)VALUES(
	@billnumberid,
	@billtype,    
	@Costom1,     
	@Costom2,     
	@Costom3,     
	@Costom4,     
	@Costom5,     
	@Costom6,     
	@Costom7,     
	@Costom8,     
	@Costom9,     
	@Costom10,    
	@Costom11,    
	@Costom12,    
	@Costom13,    
	@Costom14,    
	@Costom15,    
	@Costom16 
)
	IF @@rowcount =0 OR @@error<>0
		--RAISERROR('更新单据发生错误！',16,1)
		RETURN -5
end
END


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE                                            PROCEDURE [Gp_InsertCustomBillDetailColumns]
(
	@billnumberid         numeric(18,0),
	@billtype             varchar(100),
	@detailId			  bigint,
	@InOrOut              CHAR(1),
	@Costom1              VARCHAR(600)='',
	@Costom2              VARCHAR(600)='',
	@Costom3              VARCHAR(600)='',
	@Costom4              VARCHAR(600)='',
	@Costom5              VARCHAR(600)='',
	@Costom6              VARCHAR(600)='',
	@Costom7              VARCHAR(600)='',
	@Costom8              VARCHAR(600)='',
	@Costom9              VARCHAR(600)='',
	@Costom10             VARCHAR(600)='',
	@Costom11             VARCHAR(600)='',
	@Costom12             VARCHAR(600)='',
	@Costom13             VARCHAR(600)='',
	@Costom14             VARCHAR(600)='',
	@Costom15             VARCHAR(600)='',
	@Costom16             VARCHAR(600)=''
	)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 1 FROM CustomBilldetailColumnsDefines WHERE billtype=@billtype)
	begin
		INSERT INTO [dbo].[CustomBillDetailColumns] 
		(
			billnumberid,
			billtype,
			detailId,
			InOrOut,
			Costom1,     
			Costom2,     
			Costom3,     
			Costom4,     
			Costom5,     
			Costom6,     
			Costom7,     
			Costom8,     
			Costom9,     
			Costom10,    
			Costom11,    
			Costom12,    
			Costom13,    
			Costom14,    
			Costom15,    
			Costom16	
		)VALUES(
			@billnumberid,
			@billtype,  
			@detailId,  
			@InOrOut,
			@Costom1,     
			@Costom2,     
			@Costom3,     
			@Costom4,     
			@Costom5,     
			@Costom6,     
			@Costom7,     
			@Costom8,     
			@Costom9,     
			@Costom10,    
			@Costom11,    
			@Costom12,    
			@Costom13,    
			@Costom14,    
			@Costom15,    
			@Costom16 
		)

		IF @@rowcount =0  OR @@error<>0
			--RAISERROR('更新单据发生错误！',16,1)
			RETURN -5
	END
END

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertCustomReferenceValue]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_InsertCustomReferenceValue]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===================================
--李灏龙
--组合自由项插入
--======================================
CREATE PROCEDURE Gp_InsertCustomReferenceValue
(
	@OperatorId	VARCHAR(50),	--操作员ID	
	@itemsid	BIGINT,			--组合项id
	@ReferenId	VARCHAR(MAX),	--id组合
	@Fullname	VARCHAR(MAX)	--名称组合
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @FullnameTable TABLE
(
	id	INT	IDENTITY(0,1),
	fullnames	VARCHAR(MAX)
)
INSERT INTO @FullnameTable( fullnames )
SELECT a FROM dbo.f_split(@Fullname,'я')

DECLARE @combineCount	INT
		,@loop			INT
		,@loopfullnames	VARCHAR(MAX)
		,@looptable		VARCHAR(10)
		,@tables		VARCHAR(2000)
		,@droptables	VARCHAR(2000)
		,@columns		VARCHAR(2000)
		,@sql			VARCHAR(MAX)
SELECT @combineCount=MAX(id) FROM @FullnameTable
SET @loop = 0
SET @tables = ''
SET @droptables=''
SET @columns = ''
SET @sql = ''

WHILE @loop <= @combineCount
BEGIN
	SELECT @loopfullnames  = fullnames  FROM @FullnameTable WHERE id = @loop
	SET @looptable = '#t'+CAST(@loop AS VARCHAR)
	SET @tables += @looptable + ' t'+CAST(@loop AS VARCHAR)+','
	SET @droptables += @looptable + ','
	SET @columns += 't' +CAST(@loop AS VARCHAR) + '.a+''я''+'
	SET @sql += '
	SELECT * 
	INTO '+@looptable+'
	FROM dbo.f_split('''+@loopfullnames+''',''；'') 
	
	'	
	SET @loop +=1
END

SET @tables = LEFT(@tables,LEN(@tables)-1)
SET @droptables = LEFT(@droptables,LEN(@droptables)-1)
SET @columns = LEFT(@columns,LEN(@columns)-5)

CREATE TABLE #fullname(fullname VARCHAR(1000))

SET @sql += '
INSERT INTO #fullname(fullname)
SELECT '+@columns+'
FROM '+@tables+'

DROP TABLE '+@droptables+'
'

EXEC(@sql)

INSERT INTO CustomReferenceValue(ReferenId,itemsid,Fullname)
SELECT @ReferenId,@itemsid,t.fullname 
FROM (SELECT fullname FROM #fullname GROUP BY fullname) t
WHERE NOT EXISTS(SELECT * FROM CustomReferenceValue WHERE itemsid = @itemsid AND ReferenId=@ReferenId AND fullname = t.fullname)

DROP TABLE #fullname

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_InsertD]
GO

/****** Object:  StoredProcedure [dbo].[Gp_InsertD]    Script Date: 05/25/2011 09:05:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*
	修 改 者：李小虎
	日	  期：2011.3.26
	修改原因：部门被职员使用后禁止分类
	修改地方：判断职员信息语句
*/


CREATE            PROCEDURE [dbo].[Gp_InsertD]
(
	@Parid   [varchar](50),
	@DbName         [varchar](30),
	@UserCode  [varchar](100),
	@FullName  [varchar](100),
	@Name [varchar](100),
	@Comment  [varchar](100),
	@LinkMan varchar(50),
	@Tel varchar(50),
	@Fax varchar(50),
    @PyCode varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint
 
declare @parFullName varchar(200)
set @parFullName=(SELECT top 1 fullname FROM department WHERE typeid=@parid)

--能否分类判断
IF @ParId<>'00000'
BEGIN
	DECLARE @erromsg VARCHAR(MAX)
	--分类判断
	BEGIN TRY
		EXEC Gp_BaseInfoCheck 'department',@parid,'0'
	END TRY
	BEGIN CATCH
		SELECT @erromsg=ERROR_MESSAGE()
		RAISERROR('%s',16,1,@erromsg)RETURN
	END CATCH
END



-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount OUT
IF @nReturntype=-1
BEGIN
	RAISERROR('部门的分类不能超过10层',16,1)RETURN--RETURN -1
END
IF @nReturntype=-2
BEGIN
	RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
END
-- 判断重复的ID,UserCode

IF EXISTS(SELECT * FROM [DepartMent] WHERE typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
BEGIN
	--print '['+@usercode+']分支机构已存在'

		RAISERROR('【%s】名称或编号不能与已有的名称或编号重复',16,1,@FullName)RETURN--RETURN -303
END
-- 判断重复的ID,UserCode
IF EXISTS(SELECT * FROM [DepartMent] WHERE typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
BEGIN
	--print '['+@usercode+']分支机构已存在'
	RAISERROR('【%s】名称或编号不能与已有的名称或编号重复',16,1,@FullName)RETURN--RETURN -303
END

-- 判断重复的ID,UserCode
IF EXISTS(SELECT * FROM [DepartMent] WHERE typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
BEGIN
	--print '['+@usercode+']分支机构已存在'
	RAISERROR('【%s】名称或编号不能与已有的名称或编号重复',16,1,@FullName)RETURN--RETURN -303
END
-- 判断重复的ID,UserCode
IF EXISTS(SELECT * FROM [DepartMent] WHERE typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
BEGIN
	--print '['+@usercode+']分支机构已存在'
	RAISERROR('【%s】名称或编号不能与已有的名称或编号重复',16,1,@FullName)RETURN--RETURN -303
END




/*
-- 判断分支机构的最大使用数量
declare @nCount int
SELECT @nCount=Count(*) FROM DepartMent 
WHERE sonnum = 0 
 and deleted=0
IF @nCount > 10
BEGIN
-- print '分支机构数量大于10'
 RETURN -99
END
*/

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

BEGIN tran insertproc
SELECT @leveal=leveal FROM DepartMent WHERE typeid=@Parid
SELECT @leveal=@leveal+1
INSERT INTO [DepartMent] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [Name], 
  [UserCode],
  [Comment],
  [LinkMan],
  [Tel],
  [Fax],
  [PyCode]
 )  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @name,
  @UserCode,
  @Comment,
  @LinkMan ,
  @Tel ,
  @Fax,
  @returnPym
 )
IF @@rowcount=0 
BEGIN
 rollback tran insertproc 
 RETURN -1
END else 
BEGIN
 update [DepartMent]
 set sonnum=@nSonnum+1,soncount=@nSoncount+1
 WHERE typeid=@Parid
END

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Department
UPDATE Department SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
commit tran insertproc


























GO





GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'dbo.GP_InsertDeliveryApplyBillDT',N'P'))
BEGIN
	DROP PROC dbo.GP_InsertDeliveryApplyBillDT
END
GO

/*
	作者：陈强
	日期：2019-11-14
	描述：要货申请单明细

*/

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

                
CREATE PROC dbo.GP_InsertDeliveryApplyBillDT
(
	@details Tb_DeliveryApplyBill READONLY
)

AS
BEGIN
	SET NOCOUNT ON
	
	DELETE A FROM dbo.PosAllotApplyBill A,@Details B WHERE A.BillNumberId=B.BillNumberId 
	AND  NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID AND A.BillNumberiD=B.BillNumberiD AND B.ID<>0)
	
	DELETE D FROM DeliveryApplyBill D,@Details B WHERE D.BillNumberId=B.BillNumberId 
												 
	
	INSERT INTO [dbo].[DeliveryApplyBill]
	([ShowOrder],[BillNumberId],[PtypeId],[Qty],[Price],[Total],[UnitID],[MUnitID],[MQty]
    ,[MUnitRate],[MUnitMsg],[MPrice],[ItemID],[IsCombined],[Comment],[CargoID],[DeliveryQty])
    SELECT ShowOrder,BillNumberId,PtypeId,Qty,Price,Total,UnitID,MUnitID,MQty,
           MUnitRate,MUnitMsg,MPrice,ItemID,IsCombined,Comment,CargoID,DeliveryQty
           FROM @details
          
           
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO
IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.Gp_InsertDeliveryBackBillDT',N'P'))
BEGIN
	DROP PROC dbo.Gp_InsertDeliveryBackBillDT;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	作者：陈强
	日期：2019-12-02
	描述：门店调货退货单保存明细
*/	

CREATE PROC Gp_InsertDeliveryBackBillDT
(
	@Details TbType_DeliveryBackBill READONLY
)
AS
BEGIN
SET NOCOUNT ON

DECLARE @BillNumberID VARCHAR(50)
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details
	
--期初单据不处理草稿库存
IF EXISTS (SELECT 1 FROM dbo.posallotapplybillindex WHERE BillNumberId=@BillNumberID AND IsIni=0)
BEGIN
	-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
	EXEC GP_Deal_DraftQTY @BillNumberID,328,'-'
END
		
DELETE D FROM DeliveryBackBill D,@Details B WHERE D.BillNumberId=B.BillNumberId 											 
	
INSERT INTO [dbo].[DeliveryBackBill](
	[ShowOrder]
   ,[BillNumberId]
   ,[Serial]
   ,[outktypeid]
   ,[outCargoID]
   ,[inktypeid]
   ,[inCargoID]
   ,[PtypeId]
   ,[ItemID]
   ,[IsCombined]
   ,[GoodsNumber]
   ,[ProduceDate]
   ,[ValidDate]
   ,[Qty]
   ,[Price]
   ,[Total]
   ,[UnitID]
   ,[MUnitID]
   ,[MQty]
   ,[MUnitRate]
   ,[MUnitMsg]
   ,[MPrice]
   ,[NUnitID]
   ,[NUnitRate]
   ,[NQty]
   ,[NUnitMsg]
   ,[Comment]
   ,[InflowQty]
   ,[DeliveryID]
   ,[GoodsCostPrice]
   ,[GoodsCostTotal]
   ,[HandZeroCost])
SELECT	ShowOrder
   ,BillNumberId
   ,Serial
   ,outktypeid
   ,outCargoID
   ,inktypeid
   ,inCargoID
   ,PtypeId
   ,ItemID
   ,IsCombined
   ,GoodsNumber
   ,ProduceDate
   ,ValidDate
   ,Qty
   ,Price
   ,Total
   ,UnitID
   ,MUnitID
   ,MQty
   ,MUnitRate
   ,MUnitMsg
   ,MPrice
   ,NUnitID
   ,NUnitRate
   ,NQty
   ,NUnitMsg
   ,Comment
   ,InflowQty
   ,DeliveryID
   ,GoodsCostPrice
   ,GoodsCostTotal
   ,HandZeroCost
FROM @Details A 
		
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
Author:			赵燕琴
Create date: 2019-12-02
Description 门店调拨单(表值)
*/
CREATE PROCEDURE [GP_InsertDeliVeryBillDT]
(
	@details  TBType_DeliVeryBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @BillNumberID VARCHAR(50)
	
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details


--期初单据不处理草稿库存
IF EXISTS (SELECT 1 FROM dbo.posallotapplybillindex WHERE BillNumberId=@BillNumberID AND IsIni=0)
BEGIN
	-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
	EXEC GP_Deal_DraftQTY @BillNumberID,327,'-'
END


IF EXISTS(SELECT TOP 1 1 FROM DeliVeryBill WHERE BillNumberId=@BillNumberID)
BEGIN
	--存在先删除
	DELETE A FROM dbo.DeliVeryBill A,@details B WHERE A.BillNumberId=B.BillNumberID

	 --AND NOT EXISTS(
		--			   SELECT ID FROM @details B WHERE A.BillNumberID=B.BillNumberID 
		--										   AND A.DeliveryApplyBillId=B.DeliveryApplyBillId 
		--										   AND A.ID=B.ID											  
		--										   AND B.ID<>0)

	INSERT INTO [dbo].[DeliVeryBill] 
	( 
			BillNumberId
			,Serial
			,ktypeidout
			,CargoIDout
			,ktypeidin
			,CargoIDin
			,PtypeId
			,ItemID
			,IsCombined
			,GoodsNumber
			,ProduceDate
			,ValidDate
			,Qty
			,Price
			,Total
			,UnitID
			,MUnitID
			,MQty
			,MUnitRate
			,MUnitMsg
			,MPrice
			,NUnitID
			,NUnitRate
			,NQty
			,NUnitMsg
			,Comment
			,PickedQty
			,CheckQty
			,UnfinishedQty
			,DeliveryApplyBillId
			,GoodsCostPrice
			,GoodsCostTotal
			,HandZeroCost
			,InputCostPrice
			,ShowOrder
	)  
	SELECT
			BillNumberId
			,Serial
			,ktypeidout
			,CargoIDout
			,ktypeidin
			,CargoIDin
			,PtypeId
			,ItemID
			,IsCombined
			,GoodsNumber
			,ProduceDate
			,ValidDate
			,dbo.F_RoundQty(Qty)  
			,dbo.F_RoundPrice(Price)   						
			,dbo.F_RoundTotal(Total)
			,UnitID
			,dbo.F_RoundTranslateRate(MUnitID)	
			,dbo.F_RoundQty(MQty)	
			,dbo.F_RoundTranslateRate(MUnitRate)
			,MUnitMsg
			,dbo.F_RoundPrice(MPrice)	
			,NUnitID
			,NUnitRate
			,dbo.F_RoundQty(NQty)
			,NUnitMsg
			,Comment
			,dbo.F_RoundQty(PickedQty)
			,dbo.F_RoundQty(CheckQty)
			,dbo.F_RoundQty(UnfinishedQty)
			,DeliveryApplyBillId
			,dbo.F_RoundPrice(GoodsCostPrice)			
			,dbo.F_RoundTotal(GoodsCostTotal) 		
			,HandZeroCost
			,InputCostPrice
			,ShowOrder
			FROM @details	A WHERE ID=0 OR NOT EXISTS (
			SELECT ID FROM dbo.DeliVeryBill  B WHERE A.BillNumberID=B.BillNumberID 
			AND A.DeliveryApplyBillId=B.DeliveryApplyBillId 
			AND A.ID=B.ID	
	)	
											
											
	UPDATE A SET	BillNumberId=B.BillNumberId
					,Serial=B.Serial
					,ktypeidout=B.ktypeidout
					,CargoIDout =B.CargoIDout
					,ktypeidin=B.ktypeidin
					,CargoIDin =B.CargoIDin
					,PtypeId= B.PtypeId
					,ItemID=B.ItemID
					,IsCombined=B.IsCombined
					,GoodsNumber=B.GoodsNumber
					,ProduceDate=B.ProduceDate
					,ValidDate=B.ValidDate
					,Qty=dbo.F_RoundQty(B.Qty)  
					,Price=dbo.F_RoundPrice(B.Price)   						
					,Total=dbo.F_RoundTotal(B.Total)
					,UnitID=B.UnitID
					,MUnitId=dbo.F_RoundTranslateRate(B.MUnitId)	
					,MQty=dbo.F_RoundQty(B.MQty)	
					,MUnitRate=dbo.F_RoundTranslateRate(B.MUnitRate)	
					,MUnitMsg=B.MUnitMsg
					,MPrice=dbo.F_RoundPrice(B.MPrice)	
					,NUnitID=B.NUnitID
					,NUnitRate=B.NUnitRate
					,NQty=dbo.F_RoundQty(B.NQty)
					,NUnitMsg=B.NUnitMsg
					,Comment=B.Comment
					,PickedQty=dbo.F_RoundQty(B.PickedQty)
					,CheckQty=dbo.F_RoundQty(B.CheckQty)
					,UnfinishedQty=dbo.F_RoundQty(B.UnfinishedQty)
					,DeliveryApplyBillId=B.DeliveryApplyBillId
					,GoodsCostPrice=dbo.F_RoundPrice(B.GoodsCostPrice)			
					,GoodsCostTotal=dbo.F_RoundTotal(B.GoodsCostTotal) 		
					,HandZeroCost=B.HandZeroCost
					,InputCostPrice=B.InputCostPrice
					,ShowOrder=B.ShowOrder

	FROM dbo.DeliveryBill A,@details B WHERE A.BillNumberID=B.BillNumberID 
		AND A.DeliveryApplyBillId=B.DeliveryApplyBillId 
		AND A.ID=B.ID
																				 								  											   
END
ELSE
BEGIN
	INSERT INTO [dbo].[DeliVeryBill] 
	( 
			BillNumberId
			,Serial
			,ktypeidout
			,CargoIDout
			,ktypeidin
			,CargoIDin
			,PtypeId
			,ItemID
			,IsCombined
			,GoodsNumber
			,ProduceDate
			,ValidDate
			,Qty
			,Price
			,Total
			,UnitID
			,MUnitID
			,MQty
			,MUnitRate
			,MUnitMsg
			,MPrice
			,NUnitID
			,NUnitRate
			,NQty
			,NUnitMsg
			,Comment
			,PickedQty
			,CheckQty
			,UnfinishedQty
			,DeliveryApplyBillId
			,GoodsCostPrice
			,GoodsCostTotal
			,HandZeroCost
			,InputCostPrice
			,ShowOrder
	)  
	SELECT	BillNumberId
			,Serial
			,ktypeidout
			,CargoIDout
			,ktypeidin
			,CargoIDin
			,PtypeId
			,ItemID
			,IsCombined
			,GoodsNumber
			,ProduceDate
			,ValidDate
			,dbo.F_RoundQty(Qty)  
			,dbo.F_RoundPrice(Price)   						
			,dbo.F_RoundTotal(Total)
			,UnitID
			,dbo.F_RoundTranslateRate(MUnitID)	
			,dbo.F_RoundQty(MQty)	
			,dbo.F_RoundTranslateRate(MUnitRate)	
			,MUnitMsg
			,dbo.F_RoundPrice(MPrice)	
			,NUnitID
			,NUnitRate
			,dbo.F_RoundQty(NQty)
			,NUnitMsg
			,Comment
			,dbo.F_RoundQty(PickedQty)
			,dbo.F_RoundQty(CheckQty)
			,dbo.F_RoundQty(UnfinishedQty)
			,DeliveryApplyBillId
			,dbo.F_RoundPrice(GoodsCostPrice)			
			,dbo.F_RoundTotal(GoodsCostTotal) 		
			,HandZeroCost
			,InputCostPrice
			,ShowOrder

		FROM @details A
END	
	
IF @@ROWCOUNT = 0 
	RETURN -1 
ELSE 
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
Author:			赵燕琴
Create date: 2019-12-02
Description 门店配送验收单(表值)
*/
CREATE PROCEDURE [GP_InsertDeliveryCheckBillDT]
(
	@details  TBType_DeliveryCheckBill  READONLY
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[DeliveryCheckBill] 
( 
				 BillNumberId
                 ,Serial
                 ,outktypeid
                 ,outCargoID
                 ,inktypeid
                 ,inCargoID

                  ,PtypeId
                  ,ItemID
                  ,IsCombined
                  ,GoodsNumber
                  ,ProduceDate
                  ,ValidDate

                  ,Qty
                  ,Price
                  ,Total
                  ,UnitID
                  ,MUnitID
                  ,MQty
                  ,MUnitRate

                  ,MUnitMsg
                  ,MPrice
                  ,NUnitID
                  ,NUnitRate
                  ,NQty
                  ,NUnitMsg

                  ,Comment
                  ,InflowQty
                  ,DeliveryID
                   ,GoodsCostPrice
	              ,GoodsCostTotal		
	              ,HandZeroCost
                  ,ShowOrder
)  
SELECT


					 BillNumberId,
					 Serial,
					 outktypeid,
					 outCargoID,
					 inktypeid,
					 inCargoID,

					 PtypeId,
					 ItemID
					 ,IsCombined
					 ,GoodsNumber
					 ,ProduceDate
                    ,ValidDate

  					,dbo.F_RoundQty(Qty)  
					,dbo.F_RoundPrice(Price)   						
					,dbo.F_RoundTotal(Total)
                    ,UnitID
                 	,dbo.F_RoundTranslateRate(MUnitID)	
                	,dbo.F_RoundQty(MQty)	
                    ,dbo.F_RoundTranslateRate(MUnitRate)	
                    
                   ,MUnitMsg
                   ,dbo.F_RoundPrice(MPrice)	
                   ,NUnitID
                   ,NUnitRate
                   ,dbo.F_RoundQty(NQty)
                   ,NUnitMsg                                      
                  ,Comment
                  ,dbo.F_RoundQty(InflowQty)                  
                  ,DeliveryID
                  ,dbo.F_RoundPrice(GoodsCostPrice)			
	              ,dbo.F_RoundTotal(GoodsCostTotal) 		
                  ,HandZeroCost
                  ,ShowOrder
                    
   
	FROM @details
	
	--UPDATE DeliveryBill SET CheckQty=dbo.F_RoundQty(t.Qty) FROM @details t where DeliveryBill.ID=t.DeliveryID
	
IF @@ROWCOUNT = 0 
	RETURN -1 
ELSE 
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：HanLin
	日期：2012-8-23
	描述：对应收\应付增加\减少单收付款时,completetotal要回写到明细里面
	
*/

CREATE PROCEDURE [dbo].Gp_InsertDetailCompleteTotal
(
	@completetotal  NUMERIC(24, 10) ,
	@ncompletetotal  NUMERIC(24, 10) ,
	@billid		INT
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE	dbo.AdDebtBill 
SET		CompleteTotal=dbo.F_RoundTotal(CompleteTotal+@completetotal),
		NCompleteTotal=dbo.F_RoundTotal(NCompleteTotal+@ncompletetotal)
WHERE   ID=@billid

IF @@ERROR<>0
	RETURN -1
ELSE
	RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-15
--	描述：部门销售计划明细插入
---------------------------------------------
CREATE PROCEDURE GP_InsertDetailDtypeSaleplan
(
	@saleplanid		VARCHAR(MAX), 
	@indexvalue		VARCHAR(MAX),
	@planvalue		VARCHAR(MAX),
	@indexcount		INT,
	@timetotalid	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE	@timeid VARCHAR(MAX)
SET @timeid='0'
SELECT TOP (@indexcount) @timeid=ID FROM SaleTime WHERE TotalID=@timetotalid ORDER BY ID

INSERT INTO DetailDtypeSaleplan (	
	DtypeSaleplanID,
	RatingValue,
	PlanValue,
	DetailTimeID
)
VALUES(
	@saleplanid,
	@indexvalue,
	@planvalue,
	@timeid
)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-15
--	描述：部门销售计划明细插入
---------------------------------------------
CREATE PROCEDURE GP_InsertDetailEtypeSaleplan
(
	@saleplanid		VARCHAR(MAX), 
	@indexvalue		VARCHAR(MAX),
	@planvalue		VARCHAR(MAX),
	@indexcount		INT,
	@timetotalid	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE	@timeid VARCHAR(MAX)
SET @timeid='0'
SELECT TOP (@indexcount) @timeid=ID FROM SaleTime WHERE TotalID=@timetotalid ORDER BY ID

INSERT INTO DetailEtypeSaleplan (	
	EtypeSaleplanID,
	RatingValue,
	PlanValue,
	DetailTimeID
)
VALUES(
	@saleplanid,
	@indexvalue,
	@planvalue,
	@timeid
)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-13
--	描述：分支机构销售计划数据插入
---------------------------------------------
CREATE PROCEDURE GP_InsertDetailStypeSaleplan
(
	@saleplanid		VARCHAR(MAX), 
	@indexvalue		VARCHAR(MAX),
	@planvalue		VARCHAR(MAX),
	@indexcount		INT,
	@timetotalid	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE	@timeid VARCHAR(MAX)
SET @timeid='0'
SELECT TOP (@indexcount) @timeid=ID FROM SaleTime WHERE TotalID=@timetotalid ORDER BY ID

INSERT INTO DetailStypeSaleplan (	
	StypeSaleplanID,
	RatingValue,
	PlanValue,
	DetailTimeID
)
VALUES(
	@saleplanid,
	@indexvalue,
	@planvalue,
	@timeid
)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	Author:			 李海洋
	Create date: 2012-05-16 
	Description: 拆装单明细(表值)

*/
CREATE PROCEDURE Gp_InsertDissBillDT
(
	@details TBType_DissBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[DisassembleBill] 
( 
	 BillNumberId		
	,PtypeId  			
	,Qty   					
	,CostPrice			
	,JobNumber   				
	,Total   				
	,InOrOut  			
	,OutFactoryDate  			
	,Comment  			
	,IsUnit2 	
	,Serial					
	,InputCostPrice	
	,GoodsNumber		
	,ProduceDate		
	,ValidDate			
	,GoodsBTypeID		
	,GoodsCostPrice	
	,HandZeroCost		
	,KTypeID				
	,STypeID				
	--9.0新字段
	,CargoId				
	,ItemId					
	,IsCombined
	,nqty
	,UnitRate
	
	,MUnitId
	,MUnitRate
	,MQty
	,CurMSalePrice
	,ShowOrder
)
	SELECT 
		BillNumberId		
		,PtypeId  			
		,dbo.F_RoundQty(Qty)   					
		,dbo.F_RoundPrice(CostPrice)			
		,JobNo   				
		,dbo.F_RoundTotal(Total)   				
		,InOrOut  			
		,MakeDate  			
		,Comment  			
		,intisUnitTow 	
		,Serial					
		,dbo.F_RoundPrice(InputCostPrice)	
		,GoodsNumber		
		,ProduceDate		
		,ValidDate			
		,GoodsBTypeID		
		,dbo.F_RoundPrice(GoodsCostPrice)	
		,HandZeroCost		
		,KTypeID				
		,STypeID				
		--9.0新字段
		,CargoId				
		,ISNULL(ItemId,0)					
		,ISNULL(IsCombined,0)
		,dbo.F_RoundQty(nQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		
		,MUnitId
		,dbo.F_RoundTranslateRate(MUnitRate)
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundPrice(CurMSalePrice)
		,ShowOrder
	FROM @details

IF @@ROWCOUNT = 0 
	RETURN -1 
ELSE 
	RETURN 0	




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-15
--	描述：部门销售计划总表数据插入
---------------------------------------------
CREATE PROCEDURE GP_InsertDtypeSaleAllPlan
(	
	@fullname		VARCHAR(MAX),
	@moneyunit		varchar(max),
	@planid			VARCHAR(MAX),
	@stypeid		VARCHAR(MAX),
	@timetotalid	VARCHAR(MAX),
	@alltotalindex	VARCHAR(MAX),
	@alltotalplan	VARCHAR(MAX),
	@comment		VARCHAR(MAX),
	@ifstype		VARCHAR(MAX)='1',
	@intReturn		int out
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @splanid VARCHAR(MAX)
SET @splanid=''
SELECT @splanid=ID  FROM StypeSaleplan WHERE SplanID=@planid AND StypeID=@stypeid

IF EXISTS (SELECT *FROM DtypeSaleAllPlan WHERE FullName=@fullname) AND @ifstype='0' 
BEGIN
	RAISERROR('该销售计划名称【%s】已经在部门销售计划中使用！',16,1,@fullname)RETURN -1
END

INSERT INTO DtypeSaleAllPlan (
	FullName,
	MoneyUnit,
	STypePlanID,
	AllRatingValue,
	AllPlanValue,
	TotalID,
	IfAudit,
	IfUse,
	comment
)
VALUES(
	@fullname,
	@moneyunit,
	@splanid,
	@alltotalindex,
	@alltotalplan,
	@timetotalid,
	'1',
	'2',
	@comment
)

SELECT @intReturn=SCOPE_IDENTITY();
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-15
--	描述：部门销售计划数据插入
---------------------------------------------
CREATE PROCEDURE GP_InsertDtypeSalePlan
(
	@timetotalid VARCHAR(MAX),
	@planid		VARCHAR(MAX), 
	@stypeid	VARCHAR(MAX),
	@dtypeid	VARCHAR(MAX),
	@percent	VARCHAR(MAX),
	@totalindex	VARCHAR(MAX),
	@totalplan	VARCHAR(MAX),
	@intReturn	int out
)
--@encode$--
AS
SET NOCOUNT ON
INSERT INTO DtypeSaleplan (	
	DplanID,
	StypeID,
	DtypeID,
	TimeID,
	ApportionScale,
	RatingValue,
	PlanValue
)
VALUES(
	@planid,
	@stypeid,
	@dtypeid,
	@timetotalid,
	@percent,
	@totalindex,
	@totalplan
)

SELECT @intReturn=SCOPE_IDENTITY();
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_InsertE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_InsertE]
GO
/****** Object:  StoredProcedure [dbo].[Gp_InsertE]    Script Date: 05/25/2011 09:10:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO





CREATE   PROCEDURE [dbo].[Gp_InsertE]
(
 @Parid   [varchar](50),
 @DbName         [varchar](30),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @Department  [varchar](100),
 @Tel   [varchar](20),
 @Address  [varchar](66),
 @Comment  [varchar](256),
 @BtypeID [varchar](50),
@Sex bit,
@Nation varchar(20),
@Knowledge varchar(20),
@Blood varchar(20),
@Health varchar(256),
@IDCard varchar(50),
@BirthDay datetime,
@Marriage int,
@Job varchar (50),
@Job2 varchar (50),
@Jobtime datetime,
@Mob varchar (50),
@Mail varchar (50),
@Political varchar (20),
@Nat_place varchar (20),
@Tel2 varchar (50),
@College varchar (50),
@For_language varchar (20),
@Reg_place varchar (50),
@Com_level varchar (20),
@Weight  NUMERIC(24, 10) ,
@Stature  NUMERIC(24, 10) ,
@Fam_status varchar (50),
@Informer varchar (20),
@Speciality varchar (50),
@For_lan_level varchar (20),
@PostCode varchar (10),
@DtypeID  varchar(50),
@PyCode   varchar(200),
@MaxPre    NUMERIC(24, 10) ,
@tichengRate    NUMERIC(24, 10) ,
@STypeID varchar(50),
@QQ varchar(50),
@MSN varchar(50),
@Blog varchar(200),
@mBlog varchar(200),
@Team varchar(200),
@Buyerminvalue NUMERIC(24, 10),
@Saleminvalue NUMERIC(24, 10)
)
--@encode$--
AS
SET NOCOUNT ON
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from employee where typeid=@parid)
--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(select subvalue from sysdata where subname='ifqp')

--部门不存在
if not exists(select typeid from department where typeid=@dtypeid)
begin
	RAISERROR('所选部门不存在，请另选一个部门',16,1)return
end

--能否分类判断
IF @ParId<>'00000'
BEGIN
	DECLARE @erromsg VARCHAR(MAX)
	--分类判断
	BEGIN TRY
		EXEC Gp_BaseInfoCheck 'employee',@parid,'0'
	END TRY
	BEGIN CATCH
		SELECT @erromsg=ERROR_MESSAGE()
		RAISERROR('%s',16,1,@erromsg)RETURN
	END CATCH
END


-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
begin
	RAISERROR('职员的分类不能超过9层',16,1)return--return -1
end
if @nReturntype=-2 
begin
	RAISERROR('无法添加基本信息',16,1)return--return -2
end

-- 判断重复的ID,UserCode
DECLARE @eroFlag varchar(50)
select @eroFlag=value from Userconfig where ConfigName='equaleroname'
if (@eroFlag=0)
begin 
	if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted<>1) or (fullname=@fullname and fullname<>'超级用户' and deleted<>1))
	begin
		--print '['+@usercode+']职员已存在'
		RAISERROR('该【%s】已经存在，职员编号或名称不能相同',16,1,@FullName)return--return -3
	end
end
else
begin
	if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted<>1))
	begin
		RAISERROR('该【%s】已经存在，职员编号不能相同',16,1,@FullName)return--return -3
	end
end

-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted<>1) or (fullname=@usercode and fullname<>'超级用户' and deleted<>1))
begin
	--print '['+@usercode+']职员已存在'
	RAISERROR('职员名称或编号不能与已有的名称或编号重复',16,1)return--return -10
end

-- 判断重复的ID,UserCode
if @eroFlag=0
BEGIN
	if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted=1) or (fullname=@fullname and fullname<>'超级用户' and deleted=1))
	begin
		RAISERROR('该【%s】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称',16,1,@FullName) return--return -31
	end
END
ELSE
BEGIN
	if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted=1) )
	begin
		RAISERROR('该【%s】的编号已被已停用的职员使用，请更换或删除该停用的编号',16,1,@FullName) return--return -31
	end
END


-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted=1) or (fullname=@usercode and fullname<>'超级用户' and deleted=1))
begin
	--print '['+@usercode+']职员已存在'
	RAISERROR('职员名称或编号不能与已停用的名称或编号重复',16,1) return--return -101
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

begin tran insertproc
select @leveal=leveal from employee where typeid=@Parid 
select @leveal=@leveal+1
INSERT INTO [employee] 
  ( 
	[typeId],
	  [Parid],
	  [leveal],
	  [soncount],
	  [sonnum],
	  [FullName],
	  [UserCode],
	  [Department],
	  [Tel],
	  [Address],
	  [Comment],
	  [BtypeID],
	[Sex],
	[Nation],
	[Knowledge],
	[Blood],
	[Health],
	[IDCard],
	[BirthDay],
	[Marriage],
	[Job],
	[Job2],
	[Jobtime],
	[Mob],
	[Mail],
	[Political],
	[Nat_place],
	[Tel2],
	[College],
	[For_language],
	[Reg_place],
	[Com_level],
	[Weight],
	[Stature],
	[Fam_status],
	[Informer],
	[Speciality],
	[For_lan_level],
	[PostCode],
	[PyCode],
	[DtypeID],
	[MaxPre],
	[tichengRate],
	[STypeID],
    	[QQ],
	[MSN],
	[Blog],
	[mBlog],
	[Team],
    	[Buyerminvalue],
    	[Saleminvalue]
)  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Department,
  @Tel,
  @Address,
  @Comment,
  @BtypeID,
@Sex,
@Nation,
@Knowledge,
@Blood,
@Health,
@IDCard,
@BirthDay,
@Marriage,
@Job,
@Job2,
@Jobtime,
@Mob,
@Mail,
@Political,
@Nat_place,
@Tel2,
@College,
@For_language,
@Reg_place,
@Com_level,
@Weight,
@Stature,
@Fam_status,
@Informer,
@Speciality,
@For_lan_level,
@PostCode,
@returnPym,
@DtypeID,
dbo.F_RoundTotal(@MaxPre),
dbo.F_RoundPercentage(@tichengRate),
@STypeID,
@QQ,
@MSN,
@Blog,
@mBlog,
@Team,
@Buyerminvalue,
@Saleminvalue
)
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [employee]
  set sonnum=@nSonnum+1,soncount=@nSoncount+1
  where typeid=@Parid
end
-- 建立超级用户的登录帐号
if @Parid='00000'
begin
 exec @nReturntype=Gp_AddNewLogin @EtypeId_1,1
 if @nReturntype=-1 return -1
 if @nReturntype=-2 return -2
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Employee
UPDATE Employee SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
 
--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','Employee','0'

commit tran insertproc





GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_InsertEHr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_InsertEHr
GO
/****** Object:  StoredProcedure [dbo].[Gp_InsertE]    Script Date: 05/01/2012 09:10:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

--------------------------------------------
--	作者：韩林
--	日期：2012-01-05
--	描述：HR人员转为试用期的时候存进employee表中的时候新加了两个字段，有别于Gp_InsertE
---------------------------------------------



CREATE   PROCEDURE [dbo].Gp_InsertEHr
(
 @Parid   [varchar](50),
 @DbName         [varchar](30),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @Department  [varchar](100),
 @Tel   [varchar](20),
 @Address  [varchar](66),
 @Comment  [varchar](256),
 @BtypeID [varchar](50),
@Sex bit,
@Nation varchar(20),
@Knowledge varchar(20),
@Blood varchar(20),
@Health varchar(256),
@IDCard varchar(50),
@BirthDay datetime,
@Marriage int,
@Job varchar (50),
@Job2 varchar (50),
@Jobtime datetime,
@Mob varchar (50),
@Mail varchar (50),
@Political varchar (20),
@Nat_place varchar (20),
@Tel2 varchar (50),
@College varchar (50),
@For_language varchar (20),
@Reg_place varchar (50),
@Com_level varchar (20),
@Weight  NUMERIC(24, 10) ,
@Stature  NUMERIC(24, 10) ,
@Fam_status varchar (50),
@Informer varchar (20),
@Speciality varchar (50),
@For_lan_level varchar (20),
@PostCode varchar (10),
@DtypeID  varchar(50),
@PyCode   varchar(200),
@MaxPre    NUMERIC(24, 10) ,
@tichengRate    NUMERIC(24, 10) ,
@STypeID varchar(50),
@QQ varchar(50),
@MSN varchar(50),
@Blog varchar(200),
@mBlog varchar(200),
@Team varchar(200),
@postion_id	int =0,		--hr转过来的试用期员工使用的职位
@personstatus_id int=4	--人员状态，从HR过来的为3，其他的时候为4
)
--@encode$--
AS
SET NOCOUNT ON
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from employee where typeid=@parid)
--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(select subvalue from sysdata where subname='ifqp')

--部门不存在
if not exists(select typeid from department where typeid=@dtypeid)
begin
	RAISERROR('所选部门不存在，请另选一个部门',16,1)return
end

--判断停用不能分类
declare @deleted INT
select @deleted=deleted from employee where typeId=@Parid
if(@deleted=1)
begin
   RAISERROR('该职员【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
end


-----------------------------判断是否在自定义中有关联信息--------------------------------------
DECLARE 
	@result			INT=0,		--自定义接收返回值
	@temptypename	VARCHAR(20)
SET @temptypename='etype'

	exec @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@parid,@result=0
		IF @result=1
		BEGIN
			RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) return
		END
---------------------------------------- END ------------------------------------------------------	

-- 职员已经使用
if exists(select etypeid from billindex where etypeId=@parid   and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
--车辆信息使用
if exists(select Driver from CM_CarInfo where Driver=@parid)
begin
   -- print'25555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 

if exists(select ETypeID from PerformanceDistribution where ETypeID=@parid)
begin
   -- print'25555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 

if exists(select ReceptionId from Billindex_CarRepair where ReceptionId=@parid)
begin
   -- print'25555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
--关联pos
if exists(select etypeid from CommonPosInfo where etypeid1=@parid)
begin
   -- print'25555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
--关联维修业务调度中的负责人
if exists(select ItemPrincipal from Billindex_CarRepair where ItemPrincipal=@parid)
begin
    --print'25555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
if exists(select MonitorPrincipal from Billindex_CarRepair where MonitorPrincipal=@parid)
begin
    --print'25555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
--维修工
if exists(select ETypeId from Qp_AttemperBill_RepairItemsPerson where ETypeId=@parid)
begin
    --print'25555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
--关联销售计划
if exists(select ETypeId from EtypeSaleplan where ETypeId=@parid)
begin
    --print'25555'
	RAISERROR('该职员【%s】已经关联销售计划，不能分类',16,1,@parFullName)return--return -9
end 
--使用登记单
if exists(select ETypeId from CM_CarUseIndex where ETypeId=@parid)
 OR EXISTS(select Driver from CM_CarUseBill where Driver=@parid)
 OR EXISTS(select ETypeId from CM_CarUseBill where ETypeId=@parid)
begin
    --print'25555'
	RAISERROR('该职员【%s】已经关联使用登记单，不能分类',16,1,@parFullName)return--return -9
end 
--车辆费用单
if exists(select ETypeId from CM_FeeIndex where ETypeId=@parid)
begin
    --print'25555'
	RAISERROR('该职员【%s】已经关联车辆费用单，不能分类',16,1,@parFullName)return--return -9
end 

if exists(select ETypeId from RequestIndex where ETypeId=@parid)
begin
    --print'25555'
	RAISERROR('该职员【%s】已经关联请购单，不能分类',16,1,@parFullName)return--return -9
end 

if exists(select ETypeId from RequestBill where ETypeId=@parid)
begin
    --print'25555'
	RAISERROR('该职员【%s】已经关联请购单，不能分类',16,1,@parFullName)return--return -9
END
 
if exists(select UnitSatrap from Billindex_CarRepair where UnitSatrap=@parid)
begin
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return--return -9
end 
if exists(select etypeid from billindex where checke =@parid  and checke<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select checke from dbo.DiyIndex where checke =@parid  and checke<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
if exists(select etypeid from wx_bill_jiejian where Etypeid =@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 


if exists(select etypeid from wx_bill_call where etypeid =@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select checke from nVipAdjust where checke=@parid and checke<>'00001')
BEGIN
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
END
if exists(select wxmanID from billindex where wxmanID =@parid  and wxmanID<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select ETypeID from Qp_SuccorBill_RepairItems where ETypeID =@parid)
begin
   -- print '2555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
--工具入出库台帐
if exists(select ETypeID from ToolIndex where ETypeID =@parid)
begin
   -- print '2555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
--储值快速充值单

if exists(select ETypeID from nVipConfiscateConfig where ETypeID =@parid)
begin
    --print '2555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
 if exists(select ETypeID from nVipWashCarTimesConfig where ETypeID =@parid)
begin
    --print '3555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
  
--电脑配置
 if EXISTS (select ETypeID from dbo.DiyIndex where ETypeID =@parid)
begin
    --print '3555'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 
  
if exists(select Etypeid from wx_bill_jiejian where Etypeid =@parid  and Etypeid<>'00001')
begin
	--print '['+@FullName+']职员已经使用，不能分类'
	RAISERROR('该职员【%s】已经使用过，不能分类',16,1,@parFullName)return---return -9
end 

if exists(select etypeid from OrderIndex where etypeId=@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已被订单使用，不能分类'
	RAISERROR('该职员【%s】已在订单中使用，不能分类',16,1,@parFullName)return---return -501
end 
if exists(select etypeid from OrderIndex where checke=@parid  and checke<>'00001')
begin
	--print '['+@FullName+']职员已被订单使用，不能分类'
	RAISERROR('该职员【%s】已在订单中使用，不能分类',16,1,@parFullName)return---return -501
end 

if exists(select etypeid from LendIndex where etypeId=@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已被借欠使用，不能分类'
	RAISERROR('该职员【%s】已在借欠单中使用，不能分类',16,1,@parFullName)return--return -502
end 

IF EXISTS(select etypeid from nVipAdjust WHERE etypeid=@parid)
BEGIN
		RAISERROR('该职员【%s】已在会员卡消费调整或者积分中进行处理，不能分类',16,1,@parFullName)return--return -502		
END

if exists(select etypeid from LendIndex where checke=@parid  and checke<>'00001')
begin
	--print '['+@FullName+']职员已被借欠使用，不能分类'
	RAISERROR('该职员【%s】已在借欠单中使用，不能分类',16,1,@parFullName)return--return -502
end 
if exists(select etypeid from RepairEngage where (etypeId=@parid  and etypeid<>'00001') OR (etypeId1=@parid  and etypeid1<>'00001') or (checke=@parid  and checke<>'00001'))
begin
	--print '['+@FullName+']职员已被维修使用，不能分类'
	RAISERROR('该职员【%s】已在维修单中使用，不能分类',16,1,@parFullName)return--return -503
end

IF EXISTS(select CreatorTypeID from crm_Schedule WHERE CreatorTypeID=@parid  AND CreatorTypeID<>'00001')
BEGIN
	--print '职员有日程，不能分类'
	RAISERROR('该职员【%s】已在日程中使用，不能分类',16,1,@parFullName)return--RETURN -504
END
IF EXISTS(select SenderTypeID,ReceiverTypeID,CreatorTypeID from crm_Message WHERE (SenderTypeID=@parid AND SenderTypeID<>'00001') OR (ReceiverTypeID=@parid and ReceiverTypeID<>'00001')  or (CreatorTypeID=@parid AND CreatorTypeID<>'00001'))
BEGIN
	--print '职员有日程给抄送，不能分类'
	RAISERROR('该职员【%s】已在日程中使用，不能分类',16,1,@parFullName)return--RETURN -504
END
IF EXISTS(select SenderTypeID,ReceiverTypeID,CreatorTypeID from crm_MessageNoread WHERE (SenderTypeID=@parid AND SenderTypeID<>'00001') OR (ReceiverTypeID=@parid and ReceiverTypeID<>'00001')  or (CreatorTypeID=@parid AND CreatorTypeID<>'00001'))
BEGIN
	--print '职员有日程给抄送，不能分类'
	RAISERROR('该职员【%s】已在日程中使用，不能分类',16,1,@parFullName)return--RETURN -504
END

IF EXISTS(select createor from crm_Btype WHERE createor=@parid AND createor<>'00001')
BEGIN
	--print '职员有创建了CRM客户，不能分类'
	RAISERROR('该职员【%s】已创建了CRM客户，不能分类',16,1,@parFullName)return--RETURN -505
END
IF EXISTS(select createor from crm_linkMan WHERE createor=@parid  AND createor<>'00001')
BEGIN
	--print '职员有创建了CRM联系人，不能分类'
	RAISERROR('该职员【%s】已创建了CRM联系人，不能分类',16,1,@parFullName)return--RETURN -506
END
--IF EXISTS(select EtypeId from InvoiceBill WHERE EtypeId=@parid)
--BEGIN
	--print '职员有发票经手人，不能分类'
	--RETURN -507
--END

IF EXISTS(select WriteId from PriceProtect WHERE WriteId=@parid  AND WriteId<>'00001')
BEGIN
	--print '职员有作为价保通知登记人，不能分类'
	RAISERROR('该职员【%s】有价保通知，不能分类',16,1,@parFullName)return--RETURN -509
END

if exists(select etypeid from Advantage_standard where etypeId=@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员已在返利标准中使用，不能分类'
	RAISERROR('该职员【%s】作为返利标准的制作人，不能分类',16,1,@parFullName)return--return -515
end 



IF EXISTS(select EtypeId from FapiaoBillIndex WHERE EtypeId=@parid AND EtypeId<>'00001')
BEGIN
	--print '职员有发票经手人，不能分类'
	RAISERROR('该职员【%s】作为发票经手人，不能分类',16,1,@parFullName)return--RETURN -507
END
IF EXISTS(select Assessor from FapiaoBillIndex WHERE Assessor=@parid AND Assessor<>'00001')
BEGIN
	--print '职员有发票审核人，不能分类'
	RAISERROR('该职员【%s】作为发票审核人或制单人，不能分类',16,1,@parFullName)return--RETURN -512
END
IF EXISTS(select checke from FapiaoBillIndex WHERE checke=@parid AND checke<>'00001')
BEGIN
	--print '职员有发票制单人，不能分类'
	RAISERROR('该职员【%s】作为发票审核人或制单人，不能分类',16,1,@parFullName) RETURN ---512
END
IF EXISTS(select EtypeId from TcBillIndex WHERE EtypeId=@parid AND EtypeId<>'00001')
BEGIN
	--print '职员有提成规则单审核人，不能分类'
	RAISERROR('该职员【%s】作为提成规则单制单人或审核人，不能分类',16,1,@parFullName) RETURN--RETURN -513
END
IF EXISTS(select checke from TcBillIndex WHERE checke=@parid AND checke<>'00001')
BEGIN
	--print '职员有提成规则单制单人，不能分类'
	RAISERROR('该职员【%s】作为提成规则单制单人或审核人，不能分类',16,1,@parFullName) RETURN--RETURN -513
END
--提成可以选父节点
--if EXISTS(select EtypeID from tcbill WHERE EtypeID=@parid)
--BEGIN
	--print '职员有提成规则单制单人，不能分类'
	--RAISERROR('该职员【%s】作为提成规则业务员，不能分类',16,1,@parFullName) RETURN--RETURN -513		
--END
IF EXISTS(select * from nVipCardSign where Etypeid=@parid AND etypeid<>'00001')
BEGIN
	--print '职员有提成规则单制单人，不能分类'
	RAISERROR('该职员【%s】作为会员卡的发卡人，不能分类',16,1,@parFullName) RETURN--RETURN -514
END

--已经是操作员的不能分类
if exists(select etypeid from loginuser where etypeId=@parid  and etypeid<>'00001')
begin
	--print '['+@FullName+']职员是操作员，不能分类'
	RAISERROR('该职员【%s】已经是操作员，不能分类',16,1,@parFullName) RETURN--return -12
end 

if @ifqp='1'
begin
--在快修单中为维修工
	if exists (select RepairManTypeID from QP_QuickRepairBill_RepairItems where  RepairManTypeID=@parid and RepairManTypeID<>'00001')
	begin
	       RAISERROR('该职员【%s】作为快修单的修理工，不能分类',16,1,@parFullName) RETURN--  return  -371
	end
	if exists (select RepairManTypeID from QP_QuickRepairBill_PType where  RepairManTypeID=@parid and RepairManTypeID<>'00001')
	begin
	        RAISERROR('该职员【%s】作为快修单的修理工，不能分类',16,1,@parFullName) RETURN-- return  -371
	end
	--维修人员工作组
	if exists (select etypeid from QP_WorkGroup_Person where  etypeid=@parid and etypeid<>'00001')
	begin
		RAISERROR('该职员【%s】已在人员工作组中使用过，不能分类',16,1,@parFullName) RETURN--return  -372
	end
	--洗车结算单洗车工
	if exists(select etypeid from QP_WashCarBill where etypeid=@parid and etypeid<>'00001')
	begin
		RAISERROR('该职员【%s】已在洗车结算单中使用过，不能分类',16,1,@parFullName) RETURN--return -373
	end
end
--盘点单
if exists(select top 1 etypeid  from  StockCheckIndex where etypeid=@parid and etypeid<>'00001' )
begin
	RAISERROR('该职员【%s】已在盘点单中使用过，不能分类',16,1,@parFullName) RETURN--return -370
end
-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 
begin
	RAISERROR('职员的分类不能超过9层',16,1)return--return -1
end
if @nReturntype=-2 
begin
	RAISERROR('无法添加基本信息',16,1)return--return -2
end

-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted<>1) or (fullname=@fullname and fullname<>'超级用户' and deleted<>1))
begin
	--print '['+@usercode+']职员已存在'
	RAISERROR('该【%s】已经存在，职员编号或名称不能相同',16,1,@FullName)return--return -3
end


-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted<>1) or (fullname=@usercode and fullname<>'超级用户' and deleted<>1))
begin
	--print '['+@usercode+']职员已存在'
	RAISERROR('职员名称或编号不能与已有的名称或编号重复',16,1)return--return -10
end

-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@usercode  and deleted=1) or (fullname=@fullname and fullname<>'超级用户' and deleted=1))
begin
	--print '['+@usercode+']职员已存在'
	RAISERROR('该【%s】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称',16,1,@FullName) return--return -31
end

-- 判断重复的ID,UserCode
if exists(select TypeID from [employee] where typeId=@EtypeId_1 or (usercode=@fullname  and deleted=1) or (fullname=@usercode and fullname<>'超级用户' and deleted=1))
begin
	--print '['+@usercode+']职员已存在'
	RAISERROR('职员名称或编号不能与已停用的名称或编号重复',16,1) return--return -101
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

begin tran insertproc
select @leveal=leveal from employee where typeid=@Parid 
select @leveal=@leveal+1
INSERT INTO [employee] 
  ( 
	[typeId],
	  [Parid],
	  [leveal],
	  [soncount],
	  [sonnum],
	  [FullName],
	  [UserCode],
	  [Department],
	  [Tel],
	  [Address],
	  [Comment],
	  [BtypeID],
	[Sex],
	[Nation],
	[Knowledge],
	[Blood],
	[Health],
	[IDCard],
	[BirthDay],
	[Marriage],
	[Job],
	[Job2],
	[Jobtime],
	[Mob],
	[Mail],
	[Political],
	[Nat_place],
	[Tel2],
	[College],
	[For_language],
	[Reg_place],
	[Com_level],
	[Weight],
	[Stature],
	[Fam_status],
	[Informer],
	[Speciality],
	[For_lan_level],
	[PostCode],
	[PyCode],
	[DtypeID],
	[MaxPre],
	[tichengRate],
	[STypeID],
    [QQ],
	[MSN],
	[Blog],
	[mBlog],
	[Team],
	[HrPersonStatu],
	[HrpostionId]
)  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @UserCode,
  @Department,
  @Tel,
  @Address,
  @Comment,
  @BtypeID,
@Sex,
@Nation,
@Knowledge,
@Blood,
@Health,
@IDCard,
@BirthDay,
@Marriage,
@Job,
@Job2,
@Jobtime,
@Mob,
@Mail,
@Political,
@Nat_place,
@Tel2,
@College,
@For_language,
@Reg_place,
@Com_level,
@Weight,
@Stature,
@Fam_status,
@Informer,
@Speciality,
@For_lan_level,
@PostCode,
@returnPym,
@DtypeID,
dbo.F_RoundTotal(@MaxPre),
dbo.F_RoundPercentage(@tichengRate),
@STypeID,
@QQ,
@MSN,
@Blog,
@mBlog,
@Team,
@personstatus_id,
@postion_id
)
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [employee]
  set sonnum=@nSonnum+1,soncount=@nSoncount+1
  where typeid=@Parid
end
-- 建立超级用户的登录帐号
if @Parid='00000'
begin
 exec @nReturntype=Gp_AddNewLogin @EtypeId_1,1
 if @nReturntype=-1 return -1
 if @nReturntype=-2 return -2
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Employee
UPDATE Employee SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
commit tran insertproc





GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertElectronicScaleConfig]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_InsertElectronicScaleConfig]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*************************************************************
创 建 人：罗淮文
创建日期：2016-08-04
描    述：电子秤直连配置保存
*************************************************************/
CREATE	PROCEDURE	[dbo].[Gp_InsertElectronicScaleConfig]
(
	@InterfaceCode			VARCHAR(25),
	@InterfaceName			VARCHAR(50),
	@ElectronicScaleTypeId	INT,
	@EntryCodeFormatId		INT,
	@SendPrice				VARCHAR(25),
	@QtyDigitLenth			INT,
	@MoneyDigitLenth		INT,
	@SendCode				INT,
	@SendName				INT,
	@Comment				VARCHAR(256),
	@EtypeId				VARCHAR(50),
	@UpdateE				VARCHAR(50),
	@ID						INT=-1
)

--@encode$--
AS 
SET NOCOUNT ON
IF @ID=-1
BEGIN
	INSERT INTO ElectronicScaleInterfaceConfig
	(
		InterfaceCode,
		InterfaceName,
		ElectronicScaleTypeId,
		EntryCodeFormatId,
		SendPrice,
		QtyDigitLenth,
		MoneyDigitLenth,
		SendCode,
		SendName,
		Comment,
		CreateDate,
		EtypeId
	)
	VALUES
	(
		@InterfaceCode,
		@InterfaceName,
		@ElectronicScaleTypeId,
		@EntryCodeFormatId,
		@SendPrice,
		@QtyDigitLenth,
		@MoneyDigitLenth,
		@SendCode,
		@SendName,
		@Comment,
		GETDATE(),
		@EtypeId
	)
	IF @@ROWCOUNT = 0
	BEGIN
		RETURN -1
	END
	ELSE
	BEGIN
		RETURN @@IDENTITY
	END
END
ELSE
BEGIN
	UPDATE ElectronicScaleInterfaceConfig SET 
	InterfaceCode = @InterfaceCode,
	InterfaceName = @InterfaceName,
	ElectronicScaleTypeId = @ElectronicScaleTypeId,
	EntryCodeFormatId = @EntryCodeFormatId,
	SendPrice = @SendPrice,
	QtyDigitLenth = @QtyDigitLenth,
	MoneyDigitLenth = @MoneyDigitLenth,
	SendCode = @SendCode,
	SendName = @SendName,
	Comment = @Comment,
	UpdateTime = GETDATE(),
	UpdateE = @UpdateE
	WHERE id=@ID
	IF @@ROWCOUNT = 0
	BEGIN
		RETURN -1
	END
END

GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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










-- ========================================================================
-- 功能说明：	维修故障查询
-- 作    者：	cqhua
-- 2009-11-09
-- ========================================================================
CREATE    PROCEDURE GP_InsertErrDes
(
	@ErrCode        varchar(100)='',	
	@ErrName        varchar(100)='',
	@ErrPycode      varchar(100)='',
	@ErrDes         varchar(100)='',
	@ErrDeal        varchar(256)='',
	@ErrComment     varchar(256)='',
	@Total           NUMERIC(24, 10) 
	
)	

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

IF EXISTS(select * from  wx_ErrDescription where errcode =@errcode or errcode=@errname or errname=@errcode or errname=@errname)
	RETURN -2
ELSE	
	INSERT INTO wx_ErrDescription(ErrCode,ErrName,ErrPyCode,ErrDes,ErrDeal,ErrComment,Total) 
	VALUES (@ErrCode,@ErrName,@ErrPyCode,@ErrDes,@ErrDeal,@ErrComment,dbo.F_RoundTotal(@Total))

IF @@rowcount =0
	RETURN -1
ELSE
	RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-15
--	描述：职员销售计划时间总表数据插入
---------------------------------------------
CREATE PROCEDURE GP_InsertEtypeSaleAllPlan
(	
	@moneyunit		varchar(max),
	@planid			VARCHAR(MAX),
	@fullname		VARCHAR(MAX),
	@dtypeid		VARCHAR(MAX),
	@timetotalid	VARCHAR(MAX),
	@alltotalindex	VARCHAR(MAX),
	@alltotalplan	VARCHAR(MAX),
	@comment		VARCHAR(MAX),
	@intReturn		int out
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @dplanid VARCHAR(MAX)
SELECT @dplanid=ID  FROM DtypeSaleplan WHERE DplanID=@planid AND DtypeID=@dtypeid

INSERT INTO EtypeSaleAllPlan (
	FullName,
	MoneyUnit,
	DTypePlanID,
	AllRatingValue,
	AllPlanValue,
	TotalID,
	IfAudit,
	IfUse,
	comment
)
VALUES(
	@fullname,
	@moneyunit,
	@dplanid,
	@alltotalindex,
	@alltotalplan,
	@timetotalid,
	'1',
	'2',
	@comment
)

SELECT @intReturn=SCOPE_IDENTITY();
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-15
--	描述：部门销售计划数据插入
---------------------------------------------
CREATE PROCEDURE GP_InsertEtypeSalePlan
(
	@planid		VARCHAR(MAX), 
	@stypeid	VARCHAR(MAX),
	@dtypeid	VARCHAR(MAX),
	@timetotalid VARCHAR(MAX),
	@etypeid	VARCHAR(MAX),
	@percent	VARCHAR(MAX),
	@totalindex	VARCHAR(MAX),
	@totalplan	VARCHAR(MAX),
	@intReturn	int out
)
--@encode$--
AS
SET NOCOUNT ON
INSERT INTO EtypeSaleplan (	
	EplanID,
	StypeID,
	DtypeID,
	TimeID,
	EtypeID,
	ApportionScale,
	RatingValue,
	PlanValue
)
VALUES(
	@planid,
	@stypeid,
	@dtypeid,
	@timetotalid,
	@etypeid,
	@percent,
	@totalindex,
	@totalplan
)

SELECT @intReturn=SCOPE_IDENTITY();
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
备料估价单_-配件明细表
*/
CREATE       PROCEDURE Gp_InsertEvaluationBill_PType
(
	@BillNumberID			[numeric](10,0),
	@PTypeID				varchar(50),
	@Qty					 NUMERIC(24, 10) ,
	@Price					 NUMERIC(24, 10) ,
	@Total					 NUMERIC(24, 10) ,
	@IsUnit2				int,
	@STypeID				varchar(50)=''
)
--@encode$--
AS 
SET NOCOUNT ON



INSERT INTO QP_EvaluationBill_PType
(
	[BillNumberID],
	[PTypeID],
	[Qty],
	[Price],
	[Total],
	[IsUnit2],
	STypeID
)
VALUES
(
	@BillNumberID,
	@PTypeID,
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@Price),
	dbo.F_RoundTotal(@Total),
	@IsUnit2,
	@STypeID
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
备料估价单_-维修项目明细表
*/
CREATE       PROCEDURE Gp_InsertEvaluationBill_RepairItems
(
	@BillNumberID			[numeric](10,0),
	@RepairItemsTypeID		varchar(50),
	@StandardManHour		 NUMERIC(24, 10) ,
	@CheckHour				 NUMERIC(24, 10) ,
	@Total					 NUMERIC(24, 10) ,
	@STypeID				varchar(50)=''
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO QP_EvaluationBill_RepairItems
(
	[BillNumberID],
	[RepairItemsTypeID],
	[StandardManHour],
	[CheckHour],
	[Total],
	STypeID
)
VALUES
(
	@BillNumberID,
	ISNULL(@RepairItemsTypeID,''),
	@StandardManHour,
	@CheckHour,
	dbo.F_RoundTotal(@Total),
	@STypeID
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
作者：廖晨羽
描述：写入发票明细表(表值)
*/
CREATE PROCEDURE [Gp_InsertFaPiaoBillDT]
(
	@details TBType_FaPiao READONLY
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[FaPiaoBill] 
  ( 
	[BillNumberId],
	[BillType],
	[MainBillNumberID],
	[KtypeId],
	[PtypeId],
	[Qty],
	[Price],
	[total],
	[Tax],
	[TaxPrice],
	[TaxTotal],
	[comment],
	STypeID,
	discount,
	BeforePrice,
	BeforeTotal,
	RecordedItemId,
	--9.0新加字段
	nprice,	
	ntotal,	
	ntaxprice,	
	ntaxtotal,	
	ntaxmoney,	
	cargoid,	
	unitid,	
	nunitid,	
	nqty,	
	unitrate,	
	nunitmsg,	
	munitid,	
	mqty,	
	munitrate,	
	munitmsg,	
	mprice,	
	mtaxprice,	
	curmprice,	
	curmtaxprice,	
	itemid,	
	iscombined,	
	nbeforeprice,	
	nberoretotal,
	goodsnumber,
	curmsaleprice ,
	nsaletotal,
	saleprice, 
	taxmoney,
	nsaleprice,
	ProduceDate,
	ValidDate,
	ShowOrder
) 
SELECT 
	[BillNumberId],
	[BillType],
	[MainBillNumberID],
	[KtypeId],
	[PtypeId],
	dbo.F_RoundQty([Qty]),
	dbo.F_RoundPrice([Price]),
	dbo.F_RoundTotal([total]),
	dbo.F_RoundTax([Tax]),
	dbo.F_RoundPrice([TaxPrice]),
	dbo.F_RoundTotal([TaxTotal]),
	[comment],
	STypeID,
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(BeforePrice),
	dbo.F_RoundTotal(BeforeTotal),
	RecordedItemId,
	--9.0新加字段
	dbo.F_RoundPrice(nprice),	
	dbo.F_RoundTotal(ntotal),	
	dbo.F_RoundPrice(ntaxprice),	
	dbo.F_RoundTotal(ntaxtotal),	
	dbo.F_RoundTotal(ntaxmoney),	
	cargoid,	
	unitid,	
	nunitid,	
	dbo.F_RoundQty(nqty),	
	dbo.F_RoundTranslateRate(unitrate),	
	nunitmsg,	
	munitid,	
	dbo.F_RoundQty(mqty),	
	dbo.F_RoundTranslateRate(munitrate),	
	munitmsg,	
	dbo.F_RoundPrice(mprice),	
	dbo.F_RoundPrice(mtaxprice),	
	dbo.F_RoundPrice(curmprice),	
	dbo.F_RoundPrice(curmtaxprice),	
	itemid,	
	iscombined,	
	dbo.F_RoundPrice(nbeforeprice),	
	dbo.F_RoundTotal(nberoretotal),
	goodsnumber,
	dbo.F_RoundPrice(curmsaleprice) ,
	dbo.F_RoundTotal(nsaletotal),
	dbo.F_RoundPrice(saleprice), 
	dbo.F_RoundTotal(taxmoney),
	dbo.F_RoundPrice(nsaleprice),
	ProduceDate,
	ValidDate,
	ShowOrder
	FROM 
		@details
if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
功能：新增发票索引
作者：卢春  2009-01
*/
CREATE    PROCEDURE [Gp_InsertFaPiaoBillIndex] (
	@BillDate  			[datetime],
	@BillCode  			[varchar](200),
	@BillType  			[numeric](4,0),
	@FaPiaoType			[char](1),
	@FaPiaoCode			[varchar](256),
	@Comment  			[varchar](256),
	@Explain 			[varchar](256),
	@BtypeId  			[varchar](100),
	@dealBtypeId  		[varchar](100),
	@EtypeId  			[varchar](100),
	@DtypeId 			[varchar](100) = '',		--分支机构ID
	@CheckE  			[varchar](100) = '',
	@Assessor			[varchar](100) = '',
	@Tax   				 NUMERIC(24, 10) ,
	@TotalQty 			 NUMERIC(24, 10) ,
	@TotalMoney  		 NUMERIC(24, 10) ,
	@TaxTotalMoney 		 NUMERIC(24, 10) ,
	@STypeID			varchar(50)='',
	@OtherTotal 		 NUMERIC(24, 10) ,
	@CID				INT,
	@RATE				 NUMERIC(24, 10) ,
	@NTOTALMONEY		DECIMAL(22,10),
	@NTAXTOTALMONEY		DECIMAL(22,10)
)
--@encode$--
AS 
SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********
DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -1

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)
-- ********	判断是否试用版 - END	********

DECLARE @Re int,@Flag int
EXEC @Re=Gp_Validate 2, @Flag OUTPUT
IF @Re <>0 RETURN -3 --检查程序版本错误

IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
BEGIN
	--RAISERROR('校验错误 ！',16,1) 
	RETURN -3 --检查程序版本错误
END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM FaPiaobillindex
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -1
	END
END  

IF NOT EXISTS (
	SELECT	TOP 1 1
	FROM	SType_UserConfig
	WHERE	ConfigNo = 1
			AND Value = '1'
			AND STypeID=@STypeID
)
	RETURN -33	-- 没有开帐不允许过帐


DECLARE @szPeriod [SMALLINT]
DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
EXEC Gp_GetSubValue 'period',@STypeID,@szPeriod out
SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
IF @BillDate<@BeginDate AND @BillType NOT IN(162,163)
BEGIN 
	--RAISERROR('录单日期小于本期开始日期 ！',16,1)
	RETURN -2
END
---根据配置检查过帐日期是否当前日期
DECLARE @CurDate datetime
DECLARE @IsOrNotPassOneDay bit
SELECT @CurDate=GETDATE()
SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
BEGIN 
	--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
	RETURN -4
END

INSERT INTO [dbo].[FaPiaoBillIndex] 
(
	[BillDate],
	[BillCode],
	[BillType],
	[FaPiaoType],
	[FaPiaoCode],
	[Comment],
	[explain],
	[btypeid],
	dealBtypeId,
	[etypeid],
	[DtypeId],
	[checke],
	[Assessor],
	[Tax],
	[totalqty],
	[totalmoney],
	[taxtotalmoney],
	STypeID,
	othertotal,
	CID,
	RATE,
	NTOTALMONEY,
	NTAXTOTALMONEY
)VALUES(
	@BillDate,
	@BillCode,
	@BillType,
	@FaPiaoType,
	@FaPiaoCode,
	@Comment,
	@explain,
	@btypeid,
	@dealBtypeId,
	@etypeid,
	@DtypeId,
	@checke,
	@Assessor,
	dbo.F_RoundTax(@tax),
	dbo.F_RoundQty(@totalqty),
	dbo.F_RoundTotal(@totalmoney),
	dbo.F_RoundTotal(@taxtotalmoney),
	@STypeID,
	dbo.F_RoundTotal(@OtherTotal),
	@CID,
	@RATE,
	dbo.F_RoundTotal(@NTOTALMONEY),
	dbo.F_RoundTotal(@NTAXTOTALMONEY)
)

IF @@rowcount =0  OR @@error<>0
	--RAISERROR('更新单据发生错误！',16,1)
	RETURN -5
ELSE BEGIN
	-- 修改 FaPiaoBillIndex 的 ID 字段，写入真实的物理录单顺序
	DECLARE @NewID numeric(10,0)
	SELECT 	@NewID = ISNULL(MAX(ID),0) + 1
	FROM	FaPiaoBillIndex

	UPDATE	FaPiaoBillIndex
	SET		ID = @NewID
	WHERE	BillNumberID =SCOPE_IDENTITY();
 	RETURN SCOPE_IDENTITY();
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-16
	描述：费用信息新增
*/
CREATE PROCEDURE Gp_InsertFeeType
(
	@usercode varchar(50),  -- 费用编号
	@fullname varchar(100), -- 费用名称
	@comment  varchar(256)  -- 备注
)	
--@encode$--
AS
	-- 写入数据
	SET NOCOUNT ON;
	
	if exists (select usercode from CM_FeeType where usercode=@usercode )
	begin
		RAISERROR('已存在相同的费用编号，请重新进行编号！',16,1)return--return -511
	end
	
	if exists (select fullname from CM_FeeType where fullname=@fullname )
	begin
		RAISERROR('已存在相同的费用名称，请另取一个名称！',16,1)return--return -511
	end
	
	INSERT INTO CM_FeeType
	(
		Usercode,
		Fullname,
		Comment
	)
	VALUES
	(
		@usercode,
		@fullname,
		@comment
	)
	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功
		
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO		



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_InsertFixedAddDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].GP_InsertFixedAddDT
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2013-05-20 14:15:43.577
	描述：固定资产增加单保存
*/
CREATE  PROCEDURE GP_InsertFixedAddDT
(
	@tb TbType_AssetInc READONLY
)
--@encode$--
AS 
    SET NOCOUNT ON
    
    INSERT INTO dbo.AssetIncDecBill
            ( BillNumberId ,
              AssetCardId ,
              BillType ,
              NTotal ,
              Total ,
              Tax ,
              NTaxMoney ,
              TaxMoney ,
              NTaxTotal ,
              TaxTotal ,
              NDepTotal ,
              DepTotal ,
              NNetValue ,
              NetValue ,
              Comment
            )
		SELECT    
			  BillNumberId , -- BillNumberId - int
              AssetCardId , -- AssetCardId - int
              BillType , -- BillType - int
              dbo.F_RoundTotal(NTotal) , -- NTotal - numeric
              dbo.F_RoundTotal(Total) , -- Total - numeric
              dbo.F_RoundTax(Tax) , -- Tax - numeric
              dbo.F_RoundTotal(NTaxMoney) , -- NTaxMoney - numeric
              dbo.F_RoundTotal(TaxMoney) , -- TaxMoney - numeric
              dbo.F_RoundTotal(NTaxTotal) , -- NTaxTotal - numeric
              dbo.F_RoundTotal(TaxTotal) , -- TaxTotal - numeric
              dbo.F_RoundTotal(NDepTotal) , -- NDepTotal - numeric
              dbo.F_RoundTotal(DepTotal) , -- DepTotal - numeric
              0 , -- NNetValue - numeric
              0 , -- NetValue - numeric
              Comment  -- Comment - varchar(255)
            FROM @tb;
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertFixedAssetsIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertFixedAssetsIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROC Gp_InsertFixedAssetsIndex
	@createdate DATE,
	@billcode varchar(100),
	@stypeid VARCHAR(50),
	@dtypeid VARCHAR(50),
	@etypeid VARchar(50),
	@state INT,
	@memo VARCHAR(200),
	@comment VARCHAR(200)
--@encode$--
AS 
BEGIN
	DECLARE @ret INT=0
	
	INSERT INTO FixedAssetsIndex (createdate,billcode,stypeid,dtypeid,etypeid,[state],memo,comment)
	VALUES (@createdate,@billcode,@stypeid,@dtypeid,@etypeid,@state,@memo,@comment)
	SET @ret=SCOPE_IDENTITY();
	
	RETURN @ret;
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_InsertFixedAssetsStockCheckDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].GP_InsertFixedAssetsStockCheckDT
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2014-04-21 
	描述：固定资产盘点单保存
*/
CREATE PROCEDURE GP_InsertFixedAssetsStockCheckDT
(
	@tb TbType_FixedAssetsStockCheck READONLY
)
--@encode$--	
AS
BEGIN
	INSERT INTO dbo.FixedAssetsDetails
	        ( BillNumberID ,
	          AssertsCardId ,
	          UserCode ,
	          FullName ,
	          barcode ,
	          acstate ,
	          panbarcode ,
	          panstate ,
	          comment
	        )
	SELECT  BillNumberID,
		AssetsCardId,
		UserCode,
		FullName,
		barcode,
		acstate,
		panbarcode,
		panstate,
		comment
		FROM @tb;
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_InsertFixedReduceDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].GP_InsertFixedReduceDT
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2013-05-20 14:15:43.577
	描述：固定资产减少单保存
*/
CREATE  PROCEDURE GP_InsertFixedReduceDT
	@tb TbType_AssetDec READONLY
--@encode$--
AS 
    SET NOCOUNT ON
    
    INSERT INTO dbo.AssetIncDecBill
            ( BillNumberId ,
              AssetCardId ,
              BillType ,
              NTotal ,
              Total ,
              Tax ,
              NTaxMoney ,
              TaxMoney ,
              NTaxTotal ,
              TaxTotal ,
              NDepTotal ,
              DepTotal ,
              NNetValue ,
              NetValue ,
              Comment
            )
		SELECT    
			  BillNumberId , -- BillNumberId - int
              AssetCardId , -- AssetCardId - int
              BillType , -- BillType - int
              dbo.F_RoundTotal(NTotal) , -- NTotal - numeric
              dbo.F_RoundTotal(Total) , -- Total - numeric
              dbo.F_RoundTax(Tax) , -- Tax - numeric
              dbo.F_RoundTotal(NTaxMoney) , -- NTaxMoney - numeric
              dbo.F_RoundTotal(TaxMoney) , -- TaxMoney - numeric
              dbo.F_RoundTotal(NTaxTotal) , -- NTaxTotal - numeric
              dbo.F_RoundTotal(TaxTotal) , -- TaxTotal - numeric
              0 , -- NDepTotal - numeric
              0 , -- DepTotal - numeric
              dbo.F_RoundTotal(NNetValue) , -- NNetValue - numeric
              dbo.F_RoundTotal(NetValue) , -- NetValue - numeric
              Comment  -- Comment - varchar(255)
            FROM @tb;
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
作者：廖晨羽
描述：写入明细表(表值)
*/
CREATE PROCEDURE [Gp_InsertGatheringBillDT]
(
	@details TBType_Gathering READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO [dbo].[gatheringBill] 
  ( [BillNumberId],
  [AtypeId],
  [total],
  [Comment],
  [STypeID],
  [VipCardID]
  --9.0新加字段
  ,NTotal
  ,RelevanceBillId
  ,ShowOrder
  ,brandartypeid
  ,PreferenceMoney
  ,NPreferenceMoney
  )
SELECT 
	[BillNumberId],
  [AtypeId],
  dbo.F_RoundTotal([total]),
  [Comment],
  [STypeID],
  [VipCardID]
  --9.0新加字段
  ,dbo.F_RoundTotal(NTotal)
  ,RelevanceBillId
  ,ShowOrder
  ,ISNULL(brandartypeid,'')
  ,dbo.F_RoundTotal(preferencemoney)
  ,dbo.F_RoundTotal(npreferencemoney)
	FROM 
		@details

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：廖晨羽
描述：写入赠送单明细表(表值)
2013-05-09 周华 添加 ktypeid 多仓库
*/
CREATE              PROCEDURE [GP_InsertGiveBillDT]
(
	@details TBType_Give READONLY
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO [dbo].[GiveBill] 
  ( 
	BillNumberID,
	PTypeID,
	Qty,
	Comment,
	isUnit2,
	Serial,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	--9.0新字段
	,CargoId 
	,UnitId 
	,NUnitId 
	,NQty 
	,UnitRate 
	,NUnitMsg 
	,MUnitId 
	,MQty 
	,MUnitRate 
	,MUnitMsg 
	,ItemId 
	,IsCombined 
	,KTypeId
	,ShowOrder
)  
SELECT 
	BillNumberID,
	PTypeID,
	dbo.F_RoundQty(Qty),
	Comment,
	intIsUnit2,
	Serial,
	dbo.F_RoundPrice(InputCostPrice),
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	STypeID
	--9.0新字段
	,CargoId 
	,UnitId 
	,NUnitId 
	,dbo.F_RoundQty(NQty) 
	,dbo.F_RoundTranslateRate(UnitRate) 
	,NUnitMsg 
	,MUnitId 
	,dbo.F_RoundQty(MQty) 
	,dbo.F_RoundTranslateRate(MUnitRate) 
	,MUnitMsg 
	,ItemId 
	,IsCombined 
	,KTypeId
	,ShowOrder
	FROM @details



if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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













/*
	作者：谢吉康
	日期：2003-12-9
	描述：将采购、销售中发生的赠送、获赠的关联关系记入下面的表中
*/
CREATE     PROCEDURE Gp_InsertGiveFromSaleOrBuy
(
	@SourceBillNumberId		INT,
	@DestBillNumberId		INT,
	@IfCheck 				CHAR(1),
	@ETypeID				VARCHAR(50),
	@BTypeID				VARCHAR(50),
	@KTypeID				VARCHAR(50),
	@Explain				VARCHAR(256),
	@Comment				VARCHAR(256),
	@OutPutID				INT		OUTPUT
)
--@encode$--
AS	
BEGIN
DECLARE @DestBId INT
	SELECT TOP 1 @DestBId=DestBillNumberId FROM GiveFromSaleOrBuy WHERE SourceBillNumberId = @SourceBillNumberId
	IF @@ROWCOUNT = 0 
		BEGIN
			INSERT INTO GiveFromSaleOrBuy
			(
				SourceBillNumberId,
				DestBillNumberId,
				IfCheck,
				ETypeID,
				BTypeID,
				KTypeID,
				Explain,
				Comment
			)
			VALUES
			(
				@SourceBillNumberId,
				@DestBillNumberId,
				@IfCheck,
				@ETypeID,
				@BTypeID,
				@KTypeID,
				@Explain,
				@Comment
			)
	
			SELECT @OutPutID = [ID] FROM GiveFromSaleOrBuy WHERE SourceBillNumberId = @SourceBillNumberId AND DestBillNumberId = @DestBillNumberId
		
			IF @@ROWCOUNT=0
				RETURN -1
			ELSE
				RETURN 0
		END
	ELSE
		BEGIN
		   IF(@DestBId=@DestBillNumberId)
		     BEGIN
			UPDATE	GiveFromSaleOrBuy
			SET		IfCheck = @IfCheck,
					ETypeID = @ETypeID,
					BTypeID = @BTypeID,
					KTypeID = @KTypeID,
					Explain = @Explain,
					Comment = @Comment
			WHERE	SourceBillNumberId = @SourceBillNumberId

			IF @@ROWCOUNT = 0
				RETURN -1
			ELSE
				RETURN 0
		    END
		END
	
END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2003-12-9
	描述：将采购、销售中发生的赠送、获赠的关联关系明细记入下面的表中
*/
CREATE PROCEDURE Gp_InsertGiveFromSaleOrBuyBill
(
	@ID						INT,
	@PTypeID				VARCHAR(50),
	@Qty					 NUMERIC(24, 10) 
)
--@encode$--
AS
BEGIN
	INSERT INTO GiveFromSaleOrBuyBill
		(
			[ID],
			PTypeID,
			Qty
		)
		VALUES
		(
			@ID,
			@PTypeID,
			dbo.F_RoundQty(@Qty)
		)

	IF @@ROWCOUNT=0
		RETURN -1
	ELSE
		RETURN 0
END
	








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGivemeBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertGivemeBillDT;
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-05-03 17:21:09.263
	描述：获赠单明细查入DT版
	2013-05-09 周华 添加KTypeId字段 多仓库
*/
CREATE PROCEDURE Gp_InsertGivemeBillDT
	@tb TbType_GiveMe READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	INSERT INTO GiveMeBill(
		BillNumberID,
		PTypeID,
		Qty,
		Comment,
		isUnit2,
		Serial,
		InputCostPrice,
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		GoodsCostPrice,
		HandZeroCost,
		STypeID
		
		-- 新字段
		,CargoId
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,ItemId
		,IsCombined
		
		,KTypeId
		,ShowOrder
	) SELECT
		BillNumberID,
		PTypeID,
		dbo.F_RoundQty(Qty),
		Comment,
		intIsUnit2,
		Serial,
		dbo.F_RoundPrice(InputCostPrice),
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		dbo.F_RoundPrice(GoodsCostPrice),
		HandZeroCost,
		STypeID
		
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,ItemId
		,IsCombined
		
		,KTypeId
		,ShowOrder
	FROM @tb;
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE       PROCEDURE Gp_InsertGoodsExchangeBill
(
	@BillNumberId  	[numeric](10,0),
	@InOrOut  		[char](1),
	@PtypeId  		[varchar](50),
	@Qty   			 NUMERIC(24, 10) ,
	@SalePrice  	 NUMERIC(24, 10) ,
	@Discount  		 NUMERIC(24, 10) ,
	@DiscountPrice   NUMERIC(24, 10) ,
	@Jobnumber  	[varchar](20),
	@Total   		 NUMERIC(24, 10) ,
	@OutFactoryDate [datetime]=Null,
	@TaxPrice  		 NUMERIC(24, 10) ,
	@TaxTotal  		 NUMERIC(24, 10) ,
	@Comment  		[varchar](255),
	@intisUnitTow 	[int],
	--	@Serial		varchar(50)
	@Serial			varchar(MAX),				-- 序列号值
	@InputCostPrice  NUMERIC(24, 10) =0	-- 成本单价
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[GoodsExchangeBill] 
  ( 
	[BillNumberId],
	[InOrOut],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[OutFactoryDate],
	[TaxPrice],
	[TaxTotal],
	[comment],
	[isUnit2],
	[Serial],
	[InputCostPrice]
) 
 
VALUES 
 ( 
	@BillNumberId,
	@InOrOut,
	@PtypeId,
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@SalePrice),
	dbo.F_RoundDiscount(@discount),
	dbo.F_RoundPrice(@DiscountPrice),
	@jobnumber,
	dbo.F_RoundTotal(@total),
	@OutFactoryDate,
	dbo.F_RoundPrice(@TaxPrice),
	dbo.F_RoundTotal(@TaxTotal),
	@Comment,
	@intisUnitTow,
	@Serial,
	dbo.F_RoundPrice(@InputCostPrice)
)
if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitFIFO]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertGoodsInitFIFO;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-06-11
	描述：先进先出 保存库存期初
	2012-07-03 添加默认货位处理
*/
CREATE PROCEDURE Gp_InsertGoodsInitFIFO
	@ptypeid VARCHAR(50)
	,@ktypeid VARCHAR(50)
	,@tb1 TbType_GoodsInitFIFO_h READONLY
	,@tb2 TbType_GoodsInitFIFO_b READONLY
	,@tb3 TbType_StockAge READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @c INT=0;
	DELETE IniGoodsStocks WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId;
	DELETE ini_goodsstocks_qty WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId;
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='serialRelation' AND Value='1')
	BEGIN
		DELETE gp_initPtypeSerial WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId AND State=1;
	END

	DECLARE @Maxid INT =0
	SELECT @Maxid = ISNULL(MAX(id),0) FROM Ini_GOODSSTOCKS_QTY 
	
	INSERT INTO IniGoodsStocks(PtypeId,KTypeId,Qty,Price,Total,GoodsOrder,ProduceDate,ValidDate) 
	SELECT @ptypeid,@ktypeid,dbo.F_RoundQty(Qty),dbo.F_RoundPrice(Price),dbo.F_RoundTotal(Total),
	ROW_NUMBER() OVER(ORDER BY GETDATE()),-- 先进先出 后进先出 没有批次
	'','' FROM @tb1;
	
	SELECT @c=cargoId FROM cargotype WHERE isDefault=1 AND ktypeid=@ktypeid;
	INSERT INTO Ini_goodsstocks_qty(PTypeId,KTypeId,CargoId,ItemId,Iscombined,GoodsNumber,Qty,NQty,ProduceDate,ValidDate,LockNumber)
	SELECT @ptypeid,@ktypeid,ISNULL(CargoId,ISNULL(@c,0)),ISNULL(ItemId,0),ISNULL(Iscombined,0),ISNULL(GoodsNumber,''),
	dbo.F_RoundQty(Qty),dbo.F_RoundQty(ISNULL(NQty,0)),'','',dbo.F_RoundQty(ISNULL(LockNumber,0)) FROM @tb2;

	--insert serial
		DECLARE 
			 @CargoId INT
			,@ItemId INT
			,@Iscombined BIT
			,@GoodsNumber VARCHAR(100)
			,@Serial VARCHAR(8000)
			,@index INT = 1
			,@STypeID VARCHAR(50)
			,@Id INT 
			--,@Qty  NUMERIC(24, 10) 
			,@NQty  NUMERIC(24, 10) 
			--,@SerialCount INT
			
		CREATE TABLE #temp (
			id  INT IDENTITY(1,1),
			id1 INT --qty 明细id
			)

		INSERT INTO #temp (id1)SELECT id FROM Ini_GOODSSTOCKS_QTY  WHERE ID > @Maxid ORDER  BY ID ASC
		SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @ktypeid	
		
		DECLARE CURSORT CURSOR FOR
		SELECT CargoId ,GoodsNumber ,ItemId ,NQty ,Iscombined,Serial FROM @tb2

		OPEN CURSORT
		FETCH NEXT FROM CURSORT INTO @CargoId,@GoodsNumber,@ItemId,@NQty,@Iscombined,@Serial
		WHILE @@FETCH_STATUS = 0
		
		BEGIN
		IF @Serial <> ''
		BEGIN
			/*
			SELECT @Id = ID FROM dbo.Ini_GOODSSTOCKS_QTY  WHERE PTypeID=@ptypeid AND KTypeID = @ktypeid AND CargoID = @CargoId 
			AND ItemID = @ItemId AND Iscombined = @Iscombined AND ProduceDate=@ProduceDate AND Validdate = @Validdate AND GoodsNumber = @GoodsNumber
			AND Qty = @Qty AND GoodsCostPrice = @Price
			*/
			SELECT @Id = id1 FROM #temp WHERE id = @index
			IF(CHARINDEX('я',@Serial)=1)
			BEGIN
				SET @Serial = SUBSTRING(@Serial,2,LEN(@Serial)-1)
			END
			INSERT INTO dbo.gp_initPtypeSerial ( Serial, State,Flag,iniFlag,ETypeID,STypeID,ID,GoodsOrder,InKtypeTime) 
			SELECT a AS 'Serial',1,1,1,'',@STypeID,@Id ,0,GETDATE() FROM dbo.f_split(@Serial,'я')
			
			UPDATE dbo.gp_initPtypeSerial  SET KtypeID=@ktypeid,PtypeID=@ptypeid ,
			GoodsNumber = ISNULL( @GoodsNumber,''),ItemID = ISNULL( @ItemId ,0), IsCombined = ISNULL( @Iscombined,0) ,CargoID= CASE WHEN ISNULL(@CargoId,0) = 0 THEN ISNULL(@c,0) ELSE @CargoId END
			WHERE Serial IN (SELECT * FROM dbo.f_split(@Serial,'я'))
			
			SELECT @index = @index+1
		END
		ELSE
		BEGIN
			SELECT @index = @index+1
		END
		
		FETCH NEXT FROM CURSORT INTO @CargoId,@GoodsNumber,@ItemId,@NQty,@Iscombined,@Serial
		
		END
		CLOSE CURSORT
		DEALLOCATE CURSORT
		DROP TABLE #temp
		--insert serial
		
		--库龄
		DECLARE @CurrentDate VARCHAR(10)
		SELECT @CurrentDate = CONVERT(VARCHAR(10),GETDATE(),23)
		
		UPDATE a SET 
		a.StockAge = 1+ DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStock a JOIN @tb3 b ON a.ID = b.ID WHERE b.TYPE = 1
				
		UPDATE a SET 
		a.StockAge =  1+DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStype a JOIN @tb3 b ON a.ID = b.ID WHERE b.TYPE = 2
		
		UPDATE a SET 
		a.StockAge =  1+DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeGroup a JOIN @tb3 b ON a.ID = b.ID WHERE b.TYPE = 3

END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitMan]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertGoodsInitMan;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-06-11
	描述：手工指定 保存库存期初
	2012-07-03 添加默认货位处理
	2012-07-25 添加goodscostprice
*/
CREATE PROCEDURE Gp_InsertGoodsInitMan
	@ptypeid VARCHAR(50)
	,@ktypeid VARCHAR(50)
	,@tb1 TbType_GoodsInitMan_h READONLY
	,@tb2 TbType_GoodsInitMan_b READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON ;
	DECLARE @c INT=0;
	DELETE IniGoodsStocks WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId;
	DELETE ini_goodsstocks_qty WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId;
	
	INSERT INTO IniGoodsStocks(PtypeId,KTypeId,Qty,Price,Total,ProduceDate,Validdate,GoodsNumber,GoodsOrder) 
	SELECT @ptypeid,@ktypeid,Qty,Price,Total
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
	,ISNULL(GoodsNumber,''),ROW_NUMBER() OVER(ORDER BY GETDATE()) FROM @tb1;
	
	SELECT @c=cargoId FROM cargotype WHERE isDefault=1 AND ktypeid=@ktypeid;
	INSERT INTO Ini_goodsstocks_qty(PTypeId,KTypeId,Qty,CargoId,ItemId,NQty,Iscombined,ProduceDate,Validdate,GoodsNumber,GoodsCostPrice)
	SELECT @ptypeid,@ktypeid,Qty,ISNULL(CargoId,ISNULL(@c,0)),ISNULL(ItemId,0),ISNULL(NQty,0),ISNULL(Iscombined,0)
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
	,ISNULL(GoodsNumber,'') 
	,GoodsCostPrice FROM @tb2;
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitManSimple]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertGoodsInitManSimple;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-06-11
	描述：手工指定 保存库存期初
*/
CREATE PROCEDURE Gp_InsertGoodsInitManSimple
	@ptypeid VARCHAR(50)
	,@ktypeid VARCHAR(50)
	,@tb TbType_GoodsInitMan READONLY
	,@tb1 TbType_StockAge READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON ;
	DECLARE @c INT=0;
	DELETE IniGoodsStocks WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId;
	DELETE Ini_GoodsStocks_qty WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId;
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='serialRelation' AND Value='1')
	BEGIN
		DELETE gp_initPtypeSerial WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId AND State = 1;
	END
	
	DECLARE @Maxid INT =0
	SELECT @Maxid = ISNULL(MAX(id),0) FROM Ini_GOODSSTOCKS_QTY 
	
	IF EXISTS(SELECT 1 FROM @tb)
	BEGIN
		INSERT INTO IniGoodsStocks(PtypeId,KTypeId,Qty,Price,Total,ProduceDate,Validdate,GoodsNumber,GoodsOrder) 
		SELECT @ptypeid,@ktypeid,dbo.F_RoundQty(ISNULL(SUM(Qty),0)),dbo.F_RoundPrice(Price),dbo.F_RoundTotal( SUM(Total))
		,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
		,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
		,ISNULL(GoodsNumber,''),ROW_NUMBER() OVER(ORDER BY GETDATE())
		 FROM @tb
		GROUP BY Price
		,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END --ProduceDate
		,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END --Validdate
		,ISNULL(GoodsNumber,'')
		
		SELECT @c=cargoId FROM cargotype WHERE isDefault=1 AND ktypeid=@ktypeid;
		INSERT INTO Ini_GoodsStocks_qty(PTypeId,KTypeId,CargoId,ItemID,Iscombined,GoodsNumber,Qty,NQty,GoodsCostPrice,ProduceDate,ValidDate,LockNumber) 
		SELECT @ptypeid,@ktypeid,CASE WHEN ISNULL(CargoID,0)=0 THEN ISNULL(@c,0) ELSE CargoID END,ISNULL(ItemId,0),ISNULL(Iscombined,0),ISNULL(GoodsNumber,''),
		dbo.F_RoundQty(ISNULL(Qty,0)),dbo.F_RoundQty(ISNULL(NQty,0)),dbo.F_RoundPrice(price)
		,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
		,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
		,dbo.F_RoundQty(ISNULL(LockNumber,0))
		FROM @tb
		--GROUP BY Price,CargoId,ISNULL(ItemId,0),ISNULL(Iscombined,0)
		--,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END --ProduceDate
		--,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END --Validdate
		--,ISNULL(GoodsNumber,'')
		
		--insert serial
		DECLARE 
			 @CargoId INT
			,@ItemId INT
			,@Iscombined BIT
			,@ProduceDate VARCHAR(50)
			,@Validdate VARCHAR(50)
			,@GoodsNumber VARCHAR(100)
			,@Serial VARCHAR(max)
			,@index INT = 1
			,@STypeID VARCHAR(50)
			,@Id INT 
			,@Qty  NUMERIC(24, 10) 
			,@Price  NUMERIC(24, 10) 
			,@SerialCount INT
			,@GoodsOrder INT
			
		CREATE TABLE #temp (
			id  INT IDENTITY(1,1),
			id1 INT --qty 明细id
			)
		CREATE TABLE #temp1 (
			goodsorder  NUMERIC(24, 10) ,
			price   NUMERIC(24, 10)  ,
			GoodsNumber  varchar(100),
			ProduceDate  varchar(50),
			ValidDate  varchar(50)
			)
		
		INSERT INTO #temp (id1)SELECT id FROM Ini_GOODSSTOCKS_QTY  WHERE ID > @Maxid ORDER  BY ID ASC
		INSERT INTO #temp1 (goodsorder,price,ProduceDate ,Validdate ,GoodsNumber)
		SELECT goodsorder,price,ProduceDate ,Validdate ,GoodsNumber 
		FROM IniGoodsStocks WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId
		SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @ktypeid	
		
		DECLARE CURSORT CURSOR FOR
		SELECT CargoId,ItemId ,Iscombined ,ProduceDate ,Validdate ,GoodsNumber ,Serial ,Qty,Price  FROM @tb

		OPEN CURSORT
		FETCH NEXT FROM CURSORT INTO @CargoId,@ItemId ,@Iscombined ,@ProduceDate ,@Validdate ,@GoodsNumber ,@Serial,@SerialCount ,@Price
		WHILE @@FETCH_STATUS = 0
		
		BEGIN
		IF @Serial <> '' AND @SerialCount IS NOT NULL
		BEGIN
			SELECT @Id = id1 FROM #temp WHERE id = @index
			IF(CHARINDEX('я',@Serial)=1)
			BEGIN
				SET @Serial = SUBSTRING(@Serial,2,LEN(@Serial)-1)
			END
			
			IF  EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='serialRelation' AND Value='1')
			BEGIN
			
					INSERT INTO dbo.gp_initPtypeSerial ( Serial, State,Flag,iniFlag,ETypeID,STypeID,ID,CostPrice,InKtypeTime) 
			        SELECT a AS 'Serial',1,1,1,'',@STypeID,@Id,dbo.F_RoundPrice(@Price),GETDATE() FROM dbo.f_split(@Serial,'я')
			
			END		
			
			SELECT @GoodsOrder = GoodsOrder FROM #temp1 WHERE price = @Price AND GoodsNumber = ISNULL(@GoodsNumber ,'')AND ProduceDate = ISNULL(@ProduceDate,'') AND ValidDate = ISNULL(@Validdate,'')
			
			UPDATE dbo.gp_initPtypeSerial  SET KtypeID=@ktypeid,PtypeID=@ptypeid ,GoodsOrder = ISNULL( @GoodsOrder,0),
			GoodsNumber =ISNULL(@GoodsNumber,''),ItemID = ISNULL( @ItemId,0) , IsCombined = ISNULL( @Iscombined,0) ,
			--ProduceDate =@ProduceDate, ValidDate=@Validdate , 
			ProduceDate = CASE WHEN ISNULL(@ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,@ProduceDate) AS VARCHAR(10)),'') END,
			ValidDate = CASE WHEN ISNULL(@Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,@Validdate) AS VARCHAR(10)),'') END,
			CargoId = CASE WHEN EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='serialRelation' AND Value='0')  THEN 0
			 WHEN ISNULL(@CargoId,0) = 0  THEN ISNULL(@c,0) ELSE @CargoId END
			WHERE Serial IN (SELECT * FROM dbo.f_split(@Serial,'я'))
	
			SELECT @index = @index+1
		END
		ELSE
		BEGIN
			SELECT @index = @index+1
		END
		
		FETCH NEXT FROM CURSORT INTO @CargoId,@ItemId ,@Iscombined ,@ProduceDate ,@Validdate ,@GoodsNumber ,@Serial ,@SerialCount ,@Price
		
		END
		CLOSE CURSORT
		DEALLOCATE CURSORT
		DROP TABLE #temp
		--insert serial
		
	END
		--库龄
		DECLARE @CurrentDate VARCHAR(10)
		SELECT @CurrentDate = CONVERT(VARCHAR(10),GETDATE(),23)
		
		UPDATE a SET 
		a.StockAge =  1+DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStock a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 1
				
		UPDATE a SET 
		a.StockAge =  1+DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStype a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 2
		
		UPDATE a SET 
		a.StockAge =  1+DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeGroup a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 3
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertGoodsInitMV]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertGoodsInitMV;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-06-11
	描述：移动加权法 保存库存期初
		2012-07-03 添加默认货位处理
*/
CREATE PROCEDURE Gp_InsertGoodsInitMV
	@ptypeid VARCHAR(50)
	,@ktypeid VARCHAR(50)
	,@qty  NUMERIC(24, 10) 
	,@price  NUMERIC(24, 10) 
	,@total  NUMERIC(24, 10) 
	,@tb TbType_GoodsInitMV READONLY
	,@tb1 TbType_StockAge READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @c INT=0;
	DELETE IniGoodsStocks WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId;
	DELETE ini_goodsstocks_qty WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId;

	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='serialrelation' AND Value='1')
	BEGIN
		DELETE gp_initPtypeSerial WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId AND State=1;
	END
	
	DECLARE @Maxid INT =0
	SELECT @Maxid = ISNULL(MAX(id),0) FROM Ini_GOODSSTOCKS_QTY 
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='AllowNegativeStock' AND SubValue='1')
	BEGIN
		INSERT INTO IniGoodsStocks(PtypeId,KTypeId,Qty,Price,Total,ProduceDate,Validdate,GoodsNumber) 
		SELECT @ptypeid,@ktypeid,dbo.F_RoundQty(@qty),dbo.F_RoundPrice(@price),dbo.F_RoundTotal(@total),'','','' 
	END
	ELSE
	BEGIN
		INSERT INTO IniGoodsStocks(PtypeId,KTypeId,Qty,Price,Total,ProduceDate,Validdate,GoodsNumber) 
		SELECT @ptypeid,@ktypeid,dbo.F_RoundQty(@qty),dbo.F_RoundPrice(@price),dbo.F_RoundTotal(@total),'','','' WHERE @qty<>0;
	END
	
	SELECT @c=cargoId FROM cargotype WHERE isDefault=1 AND ktypeid=@ktypeid;
	INSERT INTO Ini_goodsstocks_qty(PTypeId,KTypeId,CargoId,ItemId,Iscombined,GoodsNumber,Qty,NQty,ProduceDate,Validdate,LockNumber)
	SELECT @ptypeid,@ktypeid,ISNULL(CargoId,ISNULL(@c,0)),ISNULL(ItemId,0),ISNULL(Iscombined,0),ISNULL(GoodsNumber,''),dbo.F_RoundQty(Qty),dbo.F_RoundQty(ISNULL(NQty,0))
	,CASE WHEN ISNULL(ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,ProduceDate) AS VARCHAR(10)),'') END
	,CASE WHEN ISNULL(Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,Validdate) AS VARCHAR(10)),'') END
	,LockNumber
	FROM @tb;

	--insert serial
		DECLARE 
			 @CargoId INT
			,@ItemId INT
			,@Iscombined BIT
			,@GoodsNumber VARCHAR(100)
			,@Serial VARCHAR(max)
			,@index INT = 1
			,@STypeID VARCHAR(50)
			,@Id INT 
			--,@Qty  NUMERIC(24, 10) 
			,@NQty  NUMERIC(24, 10) 
			--,@SerialCount INT
			,@ProduceDate VARCHAR(50)
			,@Validdate VARCHAR(50)
			
		CREATE TABLE #temp (
			id  INT IDENTITY(1,1),
			id1 INT --qty 明细id
			)

		INSERT INTO #temp (id1)SELECT id FROM Ini_GOODSSTOCKS_QTY  WHERE ID > @Maxid ORDER  BY ID ASC
		SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @ktypeid	
		
		DECLARE CURSORT CURSOR FOR
		SELECT CargoId ,GoodsNumber ,ItemId ,NQty ,Iscombined,Serial,ProduceDate ,Validdate FROM @tb

		OPEN CURSORT
		FETCH NEXT FROM CURSORT INTO @CargoId,@GoodsNumber,@ItemId,@NQty,@Iscombined,@Serial,@ProduceDate ,@Validdate
		WHILE @@FETCH_STATUS = 0
		
		BEGIN
		IF @Serial <> '' 
		BEGIN
			/*
			SELECT @Id = ID FROM dbo.Ini_GOODSSTOCKS_QTY  WHERE PTypeID=@ptypeid AND KTypeID = @ktypeid AND CargoID = @CargoId 
			AND ItemID = @ItemId AND Iscombined = @Iscombined AND ProduceDate=@ProduceDate AND Validdate = @Validdate AND GoodsNumber = @GoodsNumber
			AND Qty = @Qty AND GoodsCostPrice = @Price
			*/
			SELECT @Id = id1 FROM #temp WHERE id = @index
			IF(CHARINDEX('я',@Serial)=1)
			BEGIN
				SET @Serial = SUBSTRING(@Serial,2,LEN(@Serial)-1)
			END
			INSERT INTO dbo.gp_initPtypeSerial ( Serial, State,Flag,iniFlag,ETypeID,STypeID,ID,GoodsOrder,CostPrice,InKtypeTime) 
			SELECT a AS 'Serial',1,1,1,'',@STypeID,@Id,0,0,NULL FROM dbo.f_split(@Serial,'я')
			
			UPDATE dbo.gp_initPtypeSerial  SET KtypeID=@ktypeid,PtypeID=@ptypeid ,
			GoodsNumber = ISNULL( @GoodsNumber,''),ItemID = ISNULL( @ItemId ,0), IsCombined = ISNULL( @Iscombined,0) ,
			CargoID=CASE WHEN ISNULL(@CargoId,0) = 0 THEN ISNULL(@c,0) ELSE @CargoId END,
			ProduceDate = CASE WHEN ISNULL(@ProduceDate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,@ProduceDate) AS VARCHAR(10)),'') END,
			ValidDate = CASE WHEN ISNULL(@Validdate,'')='' THEN '' ELSE ISNULL(CAST(CONVERT(DATE,@Validdate) AS VARCHAR(10)),'') END 
			WHERE Serial IN (SELECT * FROM dbo.f_split(@Serial,'я'))
			
			SELECT @index = @index+1
		END
		ELSE
		BEGIN
			SELECT @index = @index+1
		END
		
		FETCH NEXT FROM CURSORT INTO @CargoId,@GoodsNumber,@ItemId,@NQty,@Iscombined,@Serial,@ProduceDate ,@Validdate
		
		END
		CLOSE CURSORT
		DEALLOCATE CURSORT
		DROP TABLE #temp
		--insert serial
		--库龄
		DECLARE @CurrentDate VARCHAR(10)
		SELECT @CurrentDate = CONVERT(VARCHAR(10),GETDATE(),23)
		
		UPDATE a SET 
		a.StockAge = 1 + DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStock a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 1
				
		UPDATE a SET 
		a.StockAge =  1 +DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStype a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 2
		
		UPDATE a SET 
		a.StockAge = 1 + DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeGroup a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 3
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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















/****** Object:  Stored Procedure dbo.Gp_InsertGuestBack    Script Date: 2002-6-20 10:14:49 ******/

CREATE   PROCEDURE [Gp_InsertGuestBack]
(
 @BillNumberId  [numeric](10,0),
 @PtypeId  [varchar](50),
 @Qty    NUMERIC(24, 10) ,
 @SalePrice   NUMERIC(24, 10) ,
 @Discount   NUMERIC(24, 10) ,
 @DiscountPrice   NUMERIC(24, 10) ,
 @JobNo   [varchar](20),
 @Total    NUMERIC(24, 10) ,
 @MakeDate  [datetime],
 @TaxPrice   NUMERIC(24, 10) ,
 @TaxTotal   NUMERIC(24, 10) ,
 @Comment  [varchar](255)
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[GuestBack] 
  ( [BillNumberId],
  [PtypeId],
  [Qty],
  [SalePrice],
  [discount],
  [DiscountPrice],
  [jobnumber],
  [total],
  [OutFactoryDate],
  [TaxPrice],
  [TaxTotal],
  [comment])  
VALUES 
 ( @BillNumberId,
  @PtypeId,
  dbo.F_RoundQty(@Qty),
  dbo.F_RoundPrice(@SalePrice),
  dbo.F_RoundDiscount(@discount),
  dbo.F_RoundPrice(@DiscountPrice),
  @jobno,
  dbo.F_RoundTotal(@total),
  @MakeDate,
  dbo.F_RoundPrice(@TaxPrice),
  dbo.F_RoundTotal(@TaxTotal),
  @Comment 
 )
--if @@rowcount=0 return -1 else return 0
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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
















/****** Object:  Stored Procedure dbo.Gp_InsertGuestBackIndex    Script Date: 2002-6-20 10:14:49 ******/

CREATE    PROCEDURE [Gp_InsertGuestBackIndex]
(
  @BillDate  [datetime],
  @BillCode  [varchar](200), -- #&**&#
  @BillType  [numeric](4,0),
  @Comment  [varchar](256),
  @AtypeId  [varchar](50),
  @PtypeId  [varchar](50),
  @BtypeId  [varchar](50),
  @EtypeId  [varchar](50),
  @KtypeId  [varchar](50),
  @KtypeId2 [varchar](50),
  @IfCheck  [char](1),
  @CheckE  [varchar](50),
  @TotalMoney   NUMERIC(24, 10) ,
  @TotalQty  NUMERIC(24, 10) ,
  @TotalInMoney   NUMERIC(24, 10) ,
  @Tax   [numeric],
  @szPeriod [smallint],
  @Explain [varchar](256),
  @Draft  [bit],
  @RedWord [bit],
  @OrderId [numeric]=0 ,
  @WayBillCode [varchar](50)='',
  @GoodsNumber NUMERIC(2,0)=0,
  @PackWay[varchar](20)='',
  @TEL[varchar](20)=''
)
--@encode$--
AS 
SET NOCOUNT ON
declare @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
--exec Gp_GetSubValue 'period',@szPeriod out
select @BeginDate=startdate from monthproc where period=@szPeriod
if @BillDate<@BeginDate 
begin 
 --RAISERROR('录单日期小于本期开始日期 ！',16,1) 
 return -2
end
BEGIN TRAN InsertBillIndex
/* if @BillType=11 or @BillType=203
    select @szItem='SaleCode'
 if @BillType=45  select @szItem='StockBackCode'
 if @BillType=4  select @szItem= 'ReceiverCode'
 if @BillType=34  select @szItem= 'StockCode'
 if @BillType=6   select @szItem= 'StockBackCode'
 if @BillType=66  select @szItem= 'PayCode'
 if @BillType=9   select @szItem= 'LoseCode'
 if @BillType=14  select @szItem= 'OverFlowCode'
 if @BillType=16  select @szItem= 'RemoveCode'
 if @BillType=77  select @szItem= 'MoveMoneyCode'
 if @BillType=115 or @BillType=116 or @BillType=128 or @BillType=129 
    select @szItem= 'ChangeAccountCode'
 if @BillType=57  select @szItem= 'ChangePriceCode'
 if @BillType=17  select @szItem= 'AllotCode'
 if @BillType=21  select @szItem='MoveBjCode'
 if @BillType=201  select @szItem='CommissionCode'
 if @BillType=202  select @szItem='CommissionBackCode'
 if @BillType=300  select @szItem='SaleOrderCode'
 if @BillType=301  select @szItem='BuyOrderCode'
exec gp_GetSubValue @szItem,@szVchCode out
*/
INSERT INTO [dbo].[GuestBackIndex] 
  ([BillDate],
  [BillCode],
  [BillType],
  [Comment],
  [atypeid],
  [ptypeid],
  [btypeid],
  [etypeid],
  [ktypeid],
  [ktypeid2],
  [ifcheck],
  [checke],
  [totalqty],
  [totalmoney],
  [totalinmoney],
  [tax],
  [period],
  [explain], 
  [draft],
  [RedWord],
  [orderid],
  [WayBillCode],
  [GoodsNumber],
  [PackWay],
  [TEL])  
VALUES 
 (@BillDate,
  @BillCode,
  @BillType,
  @Comment,
  @atypeid,
  @ptypeid,
  @btypeid,
  @etypeid,
  @ktypeid,
  @ktypeid2,
  @ifcheck,
  @checke,
  dbo.F_RoundQty(@totalqty),
  dbo.F_RoundTotal(@totalmoney),
  dbo.F_RoundTotal(@totalinmoney),
  dbo.F_RoundTax(@tax),
  @szPeriod,
  @explain,
  @draft,
  @redword,
  @orderID,
  @WayBillCode,
  @GoodsNumber,
  @PackWay,
  @TEL)
if @@rowcount =0  
begin
 if @@trancount<>0 rollback tran InsertBillIndex
 return -1
end else
begin
-- select @szVchCode=right(10000000000+@szVchCode,10)
-- exec Gp_SetSubValue @szItem,@szVchCode
 if @@trancount<>0 COMMIT TRAN InsertBillIndex
 return SCOPE_IDENTITY();
end

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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















/****** Object:  Stored Procedure dbo.Gp_InsertGuestGet    Script Date: 2002-6-20 10:14:49 ******/

CREATE   PROCEDURE [Gp_InsertGuestGet]
(
 @BillNumberId  [numeric](10,0),
 @PtypeId  [varchar](50),
 @Qty    NUMERIC(24, 10) ,
 @SalePrice   NUMERIC(24, 10) ,
 @Discount   NUMERIC(24, 10) ,
 @DiscountPrice   NUMERIC(24, 10) ,
 @Jobnumber  [varchar](20),
 @Total    NUMERIC(24, 10) ,
 @OutFactoryDate [datetime]=Null,
 @TaxPrice   NUMERIC(24, 10) ,
 @TaxTotal   NUMERIC(24, 10) ,
 @Comment  [varchar](255),
 @OrderID [int]
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[GuestGet] 
  ( [BillNumberId],
  [PtypeId],
  [Qty],
  [SalePrice],
  [discount],
  [DiscountPrice],
  [jobnumber],
  [total],
  [OutFactoryDate],
  [TaxPrice],
  [TaxTotal],
  [comment],
  OrderID)  
VALUES 
 ( @BillNumberId,
  @PtypeId,
  dbo.F_RoundQty(@Qty),
  dbo.F_RoundPrice(@SalePrice),
  dbo.F_RoundDiscount(@discount),
  dbo.F_RoundPrice(@DiscountPrice),
  @jobnumber,
  dbo.F_RoundTotal(@total),
  @OutFactoryDate,
  dbo.F_RoundPrice(@TaxPrice),
  dbo.F_RoundTotal(@TaxTotal),
  @Comment,
  @OrderID)
if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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
















/****** Object:  Stored Procedure dbo.Gp_InsertGuestGetIndex    Script Date: 2002-6-20 10:14:49 ******/

CREATE    PROCEDURE [Gp_InsertGuestGetIndex]
(
  @BillDate  [datetime],
  @BillCode  [varchar](200),  -- #&**&#
  @BillType  [numeric](4,0),
  @Comment  [varchar](256),
  @AtypeId  [varchar](50),
  @PtypeId  [varchar](50),
  @BtypeId  [varchar](50),
  @EtypeId  [varchar](50),
  @KtypeId  [varchar](50),
  @KtypeId2 [varchar](50),
  @IfCheck  [char](1),
  @CheckE  [varchar](50),
  @TotalMoney   NUMERIC(24, 10) ,
  @TotalQty  NUMERIC(24, 10) ,
  @TotalInMoney   NUMERIC(24, 10) ,
  @Tax   [numeric],
  @szPeriod [smallint],
  @Explain [varchar](256),
  @Draft  [bit],
  @RedWord [bit],
  @OrderId [numeric]=0 
)
--@encode$--
AS 
SET NOCOUNT ON
declare @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
--exec Gp_GetSubValue 'period',@szPeriod out
select @BeginDate=startdate from monthproc where period=@szPeriod
if @BillDate<@BeginDate 
begin 
 --RAISERROR('录单日期小于本期开始日期 ！',16,1) 
 return -2
end
/*BEGIN TRAN InsertBillIndex
 if @BillType=11 or @BillType=203
    select @szItem='SaleCode'
 if @BillType=45  select @szItem='StockBackCode'
 if @BillType=4  select @szItem= 'ReceiverCode'
 if @BillType=34  select @szItem= 'StockCode'
 if @BillType=6   select @szItem= 'StockBackCode'
 if @BillType=66  select @szItem= 'PayCode'
 if @BillType=9   select @szItem= 'LoseCode'
 if @BillType=14  select @szItem= 'OverFlowCode'
 if @BillType=16  select @szItem= 'RemoveCode'
 if @BillType=77  select @szItem= 'MoveMoneyCode'
 if @BillType=115 or @BillType=116 or @BillType=128 or @BillType=129 
    select @szItem= 'ChangeAccountCode'
 if @BillType=57  select @szItem= 'ChangePriceCode'
 if @BillType=17  select @szItem= 'AllotCode'
 if @BillType=21  select @szItem='MoveBjCode'
 if @BillType=201  select @szItem='CommissionCode'
 if @BillType=202  select @szItem='CommissionBackCode'
 if @BillType=300  select @szItem='SaleOrderCode'
 if @BillType=301  select @szItem='BuyOrderCode'
exec gp_GetSubValue @szItem,@szVchCode out
*/
INSERT INTO [dbo].[GuestGetIndex] 
  ([BillDate],
  [BillCode],
  [BillType],
  [Comment],
  [atypeid],
  [ptypeid],
  [btypeid],
  [etypeid],
  [ktypeid],
  [ktypeid2],
  [ifcheck],
  [checke],
  [totalqty],
  [totalmoney],
  [totalinmoney],
  [tax],
  [period],
  [explain], 
  [draft],
  [RedWord],
  [orderid]
)  
VALUES 
 (@BillDate,
  @BillCode,
  @BillType,
  @Comment,
  @atypeid,
  @ptypeid,
  @btypeid,
  @etypeid,
  @ktypeid,
  @ktypeid2,
  @ifcheck,
  @checke,
  dbo.F_RoundQty(@totalqty),
  dbo.F_RoundTotal(@totalmoney),
  dbo.F_RoundTotal(@totalinmoney),
  dbo.F_RoundTax(@tax),
  @szPeriod,
  @explain,
  @draft,
  @redword,
  @orderID)
if @@rowcount =0  or @@error<>0
  RAISERROR('更新单据发生错误！',16,1)
else
 return SCOPE_IDENTITY();

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE   PROCEDURE [Gp_InsertGuestPay]
(
 @BillNumberId  [numeric](10,0),
 @AtypeId  [varchar](50),
 @Total    NUMERIC(24, 10) ,
 @Comment  [varchar](256)
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[GuestPay] 
  ( [BillNumberId],
  [AtypeId],
  [total],
  [Comment])  
VALUES 
 ( @BillNumberId,
  @AtypeId,
  dbo.F_RoundTotal(@total),
  @Comment)
if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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
















/****** Object:  Stored Procedure dbo.Gp_InsertGuestPayIndex    Script Date: 2002-6-20 10:14:49 ******/

CREATE    PROCEDURE [Gp_InsertGuestPayIndex]
(
  @BillDate  [datetime],
  @BillCode  [varchar](200),  -- #&**&#
  @BillType  [numeric](4,0),
  @Comment  [varchar](256),
  @AtypeId  [varchar](50),
  @PtypeId  [varchar](50),
  @BtypeId  [varchar](50),
  @EtypeId  [varchar](50),
  @KtypeId  [varchar](50),
  @KtypeId2 [varchar](50),
  @IfCheck  [char](1),
  @CheckE  [varchar](50),
  @TotalMoney   NUMERIC(24, 10) ,
  @TotalQty  NUMERIC(24, 10) ,
  @TotalInMoney   NUMERIC(24, 10) ,
  @Tax   [numeric],
  @szPeriod [smallint],
  @Explain [varchar](256),
  @Draft  [bit],
  @RedWord [bit],
  @OrderId [numeric]=0 
)
--@encode$--
AS 
SET NOCOUNT ON
declare @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
--exec Gp_GetSubValue 'period',@szPeriod out
select @BeginDate=startdate from monthproc where period=@szPeriod
if @BillDate<@BeginDate 
begin 
 --RAISERROR('录单日期小于本期开始日期 ！',16,1) 
 return -2
end
/*BEGIN TRAN InsertBillIndex
 if @BillType=11 or @BillType=203
    select @szItem='SaleCode'
 if @BillType=45  select @szItem='StockBackCode'
 if @BillType=4  select @szItem= 'ReceiverCode'
 if @BillType=34  select @szItem= 'StockCode'
 if @BillType=6   select @szItem= 'StockBackCode'
 if @BillType=66  select @szItem= 'PayCode'
 if @BillType=9   select @szItem= 'LoseCode'
 if @BillType=14  select @szItem= 'OverFlowCode'
 if @BillType=16  select @szItem= 'RemoveCode'
 if @BillType=77  select @szItem= 'MoveMoneyCode'
 if @BillType=115 or @BillType=116 or @BillType=128 or @BillType=129 
    select @szItem= 'ChangeAccountCode'
 if @BillType=57  select @szItem= 'ChangePriceCode'
 if @BillType=17  select @szItem= 'AllotCode'
 if @BillType=21  select @szItem='MoveBjCode'
 if @BillType=201  select @szItem='CommissionCode'
 if @BillType=202  select @szItem='CommissionBackCode'
 if @BillType=300  select @szItem='SaleOrderCode'
 if @BillType=301  select @szItem='BuyOrderCode'
exec gp_GetSubValue @szItem,@szVchCode out
*/
INSERT INTO [dbo].[GuestPayIndex] 
  ([BillDate],
  [BillCode],
  [BillType],
  [Comment],
  [atypeid],
  [ptypeid],
  [btypeid],
  [etypeid],
  [ktypeid],
  [ktypeid2],
  [ifcheck],
  [checke],
  [totalqty],
  [totalmoney],
  [totalinmoney],
  [tax],
  [period],
  [explain], 
  [draft],
  [RedWord],
  [orderid]
)  
VALUES 
 (@BillDate,
  @BillCode,
  @BillType,
  @Comment,
  @atypeid,
  @ptypeid,
  @btypeid,
  @etypeid,
  @ktypeid,
  @ktypeid2,
  @ifcheck,
  @checke,
  dbo.F_RoundQty(@totalqty),
  dbo.F_RoundTotal(@totalmoney),
  dbo.F_RoundTotal(@totalinmoney),
  dbo.F_RoundTax(@tax),
  @szPeriod,
  @explain,
  @draft,
  @redword,
  @orderID)
if @@rowcount =0  or @@error<>0
  RAISERROR('更新单据发生错误！',16,1)
else
 return SCOPE_IDENTITY();

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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













--////////////////////////////////////
--作者：谢吉康
--日期：2003-03-12
--描述：写入数据到代销库存期初表中
CREATE    PROCEDURE [gp_InsertIniCommissionStock] 
(
  @Ptypeid varchar(50),
  @Btypeid varchar(50),
  @Type int,
  @Qty   numeric(9),
  @CostTotal varchar(20),
  @Total varchar(20),
  @Tax varchar(20),
  @TaxTotal varchar(20),
  @explain varchar(256)
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
  INSERT INTO IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,explain)
  VALUES(@Ptypeid,@Btypeid,@Type,@Qty,@CostTotal,@Total,@Tax,@TaxTotal,@explain)
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertIniGoodsStockStockAge]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertIniGoodsStockStockAge;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：周华
	时间：2012-06-11
	描述：移动加权法 简单版
*/
CREATE PROCEDURE Gp_InsertIniGoodsStockStockAge
	@tb1 TbType_StockAge READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON;
	
		--库龄
		DECLARE @CurrentDate VARCHAR(10)
		SELECT @CurrentDate = CONVERT(VARCHAR(10),GETDATE(),23)
		
		UPDATE a SET 
		a.StockAge = 1+ DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStock a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 1
				
		UPDATE a SET 
		a.StockAge = 1+ DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStype a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 2
		
		UPDATE a SET 
		a.StockAge = 1+ DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeGroup a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 3
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



/*
	作者：谢吉康
	日期：2004-03-10
	描述：写入借欠的期初序列号
*/
Create       PROCEDURE GP_InsertIniLendPTypeSerial
(
		@Serial			VARCHAR(1000),
		@KTypeID		VARCHAR(50),
		@PTypeID		VARCHAR(50),
		@BTypeID1		VARCHAR(50),		
		@InKTypeTime	VARCHAR(50),
		@State			VARCHAR(50),
		@Flag			VARCHAR(50),
		@ItemId			VARCHAR(100),--自由项
		@GoodsNumber	VARCHAR(100) --批号
)
--@encode$--
AS
	DECLARE @SerialCount   INT,
			@mngLendSerial  INT		--序列号借欠出入库校验模式
	SELECT  @mngLendSerial = VALUE FROM UserConfig WHERE ConfigName = 'mngLendSerial'

IF @mngLendSerial = 1 
	BEGIN
		IF @Flag = 1							--借进
			BEGIN
				SELECT * FROM GP_initPTypeSerial WHERE Serial = @Serial				--判断真实库中是否有此序列号
		
				IF @@ROWCOUNT<>0
					BEGIN
						--RAISERROR('序列号已存在，请确认后重试！',16,1)
						RETURN 1
					END		
			END
		ELSE
			BEGIN
				SELECT * FROM GP_initPTypeSerial WHERE Serial = @Serial	AND Flag = 1 	AND State not in (25,26,27,28,29)	--判断真实库中是否有此序列号
		
				IF @@ROWCOUNT=0
					BEGIN
						--RAISERROR('因为采用了借欠的效验模式，序列号在真实库中不存在，请确认后重试！',16,1)
						RETURN -2
					END

				SELECT * FROM GP_initPTypeSerial WHERE Serial = @Serial AND Flag = 1 AND PTypeID = @PTypeID AND KTypeID = @KTypeID 	AND State not in (25,26,27,28,29)
				IF @@ROWCOUNT = 0
				BEGIN
					--RAISERROR('因为采用了借欠的效验模式，录入借出序列号的商品与仓库属性必须与真实库的一致，请确认后重试！',16,1)
					RETURN -3
				END
			END

		SELECT * FROM GP_initLendPTypeSerial WHERE Serial = @Serial	--判断借欠库中是否有此序列号
	
		IF @@ROWCOUNT<>0
			BEGIN
				--RAISERROR('序列号已存在，请确认后重试！',16,1)
				RETURN 1
			END		


		------------------------------------------
		IF @Flag = 1							--借进
			INSERT INTO GP_initLendPTypeSerial
			(
				Serial,
				KTypeID,
				PTypeID,
				BTypeID2,
				InKTypeTime,
				State,
				Flag,
				BFlag,
				GoodsNumber, 
				ItemID
			)
			VALUES 
			( 
				@Serial,
				@KTypeID,
				@PTypeID,
				@BTypeID1,
				@InKTypeTime,
				@State,
				@Flag,
				'1',
				@GoodsNumber,
				@ItemId
			)
		ELSE									--借出
			INSERT INTO GP_initLendPTypeSerial
			(
				Serial,
				KTypeID,
				PTypeID,
				BTypeID1,
				InKTypeTime,
				State,
				Flag,
				GoodsNumber,
				ItemID
			)
			VALUES 
			( 
				@Serial,
				@KTypeID,
				@PTypeID,
				@BTypeID1,
				@InKTypeTime,
				@State,
				@Flag,
				@ItemId,
				@GoodsNumber
			)

		IF @@ROWCOUNT <> 0
			BEGIN
				--修改出库日期
				UPDATE	GP_initLendPTypeSerial
				SET		OutKTypeTime = InKtypeTime
				WHERE	OutKTypeTime IS NULL
						AND [state] = 18
								
				IF @Flag = 1 
					SELECT @SerialCount = Count(Serial) FROM GP_initLendPTypeSerial WHERE PTypeID = @PTypeID AND KTypeID = @KTypeID AND BTypeID2 = @BTypeID1 AND Serial=@Serial
				ELSE
					SELECT @SerialCount = Count(Serial) FROM GP_initLendPTypeSerial WHERE PTypeID = @PTypeID AND KTypeID = @KTypeID AND BTypeID1 = @BTypeID1 AND Serial=@Serial

				--RAISERROR('录入序列号成功！',16,1)

				IF @SerialCount = 1					
					RETURN 0
				ELSE
					RETURN @SerialCount
			END
		ELSE
			BEGIN
				--RAISERROR('录入序列号失败，请确认后重试！',16,1)
				RETURN -1
			END
		-----------------------------------------------------------

	END
ELSE
	BEGIN
		SELECT * FROM GP_initLendPTypeSerial WHERE Serial = @Serial
	
		IF @@ROWCOUNT<>0
			BEGIN
				--RAISERROR('序列号已存在，请确认后重试！',16,1)
				RETURN 1
			END
		ELSE
			BEGIN
				IF @Flag = 1							--借进
					INSERT INTO GP_initLendPTypeSerial
					(
						Serial,
						KTypeID,
						PTypeID,
						BTypeID2,
						InKTypeTime,
						State,
						Flag,
						BFlag 
					)
					VALUES 
					( 
						@Serial,
						@KTypeID,
						@PTypeID,
						@BTypeID1,
						@InKTypeTime,
						@State,
						@Flag,
						'1'
					)
				ELSE									--借出
					INSERT INTO GP_initLendPTypeSerial
					(
						Serial,
						KTypeID,
						PTypeID,
						BTypeID1,
						InKTypeTime,
						State,
						Flag 
					)
					VALUES 
					( 
						@Serial,
						@KTypeID,
						@PTypeID,
						@BTypeID1,
						@InKTypeTime,
						@State,
						@Flag 
					)
	
				IF @@ROWCOUNT <> 0
					BEGIN
						--修改出库日期
						UPDATE	GP_initLendPTypeSerial
						SET		OutKTypeTime = InKtypeTime
						WHERE	OutKTypeTime IS NULL
								AND [state] = 18
							
						IF @Flag = 1 
							SELECT @SerialCount = Count(Serial) FROM GP_initLendPTypeSerial WHERE PTypeID = @PTypeID AND KTypeID = @KTypeID AND BTypeID2 = @BTypeID1 AND Serial=@Serial
						ELSE
							SELECT @SerialCount = Count(Serial) FROM GP_initLendPTypeSerial WHERE PTypeID = @PTypeID AND KTypeID = @KTypeID AND BTypeID1 = @BTypeID1 AND Serial=@Serial
	
						--RAISERROR('录入序列号成功！',16,1)
	
						IF @SerialCount = 1					
							RETURN 0
						ELSE
							RETURN @SerialCount
					END
				ELSE
					BEGIN
						--RAISERROR('录入序列号失败，请确认后重试！',16,1)
						RETURN -1
					END
			END
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	描述：库存期初序列号插入
*/
CREATE PROC GP_InsertInitPTypeSerialDT
(
  @InitPTypeSerial TBType_Gp_InitPTypeSerial READONLY
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM @InitPTypeSerial a where EXISTS(
		SELECT 1 FROM Gp_InitPTypeSerial s where s.Serial=a.Serial and s.ktypeid=a.KtypeID AND s.PtypeId=a.Ptypeid
		and s.stypeid=a.stypeid and s.etypeid=a.etypeid))
BEGIN
 RAISERROR('插入的序列号已经存在！',16,1)
 return
END

INSERT INTO Gp_InitPTypeSerial
(
    Serial ,
   KtypeID ,
   PtypeID ,
   STypeId ,
   ETypeID
)
SELECT Serial,KtypeID ,PtypeID,STypeId,ETypeID FROM @InitPTypeSerial

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入序列号发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
保险理赔_-配件明细表
*/
CREATE       PROCEDURE Gp_InsertInsurance_PType
(
	@BillNumberID			[numeric](10,0),
	@PTypeID				varchar(50),
	@Qty					 NUMERIC(24, 10) ,
	@TaxPrice				 NUMERIC(24, 10) ,
	@TaxTotal				 NUMERIC(24, 10) ,
 	@InsuranceTotal			 NUMERIC(24, 10) ,
	@Virtual				INT,
	@Comment				VARCHAR(250),
	@IsUnit2				INT,
	@GoodsCostTotal			 NUMERIC(24, 10) ,
	@STypeID				VARCHAR(50)='',
	@QuickOrReceptionBillId INT
)
--@encode$--
AS 
SET NOCOUNT ON



INSERT INTO QP_InsuranceBill_PType
(
	BillNumberID,
	PTypeID,
	Qty,
	TaxPrice,
	TaxTotal,
	InsuranceTotal,
	Virtual,
	Comment,
	IsUnit2,
	GoodsCostTotal,
	STypeID,
	QuickOrReceptionBillId
)
VALUES
(
	@BillNumberID,
	ISNULL(@PTypeID,''),
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@TaxPrice),
	dbo.F_RoundTotal(@TaxTotal),
	dbo.F_RoundTotal(@InsuranceTotal),
	@Virtual,
	ISNULL(@Comment,''),
	@IsUnit2,
	dbo.F_RoundTotal(@GoodsCostTotal),
	@STypeID,
	ISNULL(@QuickOrReceptionBillId,0)
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
保险理赔_-维修项目明细表
*/
CREATE       PROCEDURE Gp_InsertInsurance_RepairItems
(
	@BillNumberID			[numeric](10,0),
	@RepairItemsTypeID		varchar(50),
	@ManHour				 NUMERIC(24, 10) ,
	@Total					 NUMERIC(24, 10) ,
	@InsuranceTotal			 NUMERIC(24, 10) ,
	@CostTotal				 NUMERIC(24, 10) ,
	@Virtual				INT,
	@Comment				VARCHAR(250),
	@QuickOrReceptionBillId INT
	
)
--@encode$--
AS 
SET NOCOUNT ON



INSERT INTO QP_InsuranceBill_RepairItems
(
	BillNumberID,
	RepairItemsTypeID,
	ManHour,
	Total,
	InsuranceTotal,
	CostTotal,
	Virtual,
	Comment,
	QuickOrReceptionBillId
)
VALUES
(
	@BillNumberID,
	ISNULL(@RepairItemsTypeID,''),
	@ManHour,
	dbo.F_RoundTotal(@Total),
	dbo.F_RoundTotal(@InsuranceTotal),
	dbo.F_RoundTotal(@CostTotal),
	@Virtual,
	ISNULL(@Comment,''),
	ISNULL(@QuickOrReceptionBillId,0)
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*

*/
CREATE       PROCEDURE Gp_InsertIntegralExchangeBill
(
	@BillNumberID			[numeric](10,0),
	@KTypeID				varchar(50),
	@CargoSpace				varchar(200) = '',
	@PTypeID				varchar(50),
	@Qty					 NUMERIC(24, 10) ,
	@Price					 NUMERIC(24, 10) ,
	@Total					 NUMERIC(24, 10) ,
	@Comment				varchar(255),	-- 备注
	@IsUnit2				int,
	@InputCostPrice			 NUMERIC(24, 10) ,
	@HandZeroCost			int,
	@STypeID				varchar(50)='',
	@Serial					varchar(MAX),	-- 序列号值
	@GoodsNumber			varchar(100) = '',	-- 批号
	@ProduceDate			varchar(50) = '',	-- 生产日期
	@ValidDate				varchar(50) = '',	-- 效期
	@GoodsCostPrice			 NUMERIC(24, 10)  = 0	-- 出库批次成本单价
	
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO IntegralExchangeBill
(
	[BillNumberID],
	[KTypeID],
	[PTypeID],
	[Qty],
	[Price],
	[Total],
	[Comment],
	[IsUnit2],
	[InputCostPrice],
	[HandZeroCost],
	STypeID,
	Serial,
	ProduceDate,
	ValidDate,
	GoodsCostPrice,
	GoodsNumber
)
VALUES
(
	@BillNumberID,
	@KTypeID,
	@PTypeID,
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(ISNULL(@Price,0)),
	dbo.F_RoundTotal(ISNULL(@Total,0)),
	@Comment,
	@IsUnit2,
	dbo.F_RoundPrice(@InputCostPrice),
	@HandZeroCost,
	@STypeID,
	@Serial,
	@ProduceDate,
	@ValidDate,
	dbo.F_RoundPrice(@GoodsCostPrice),
	@GoodsNumber
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO








IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertIntegralExchangeBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertIntegralExchangeBillDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
*/
CREATE PROCEDURE Gp_InsertIntegralExchangeBillDT
	@BillNumberId NUMERIC(10,0)
	,@InputCostPriceFlag BIT
	,@STypeId VARCHAR(50)
	,@tb TbType_IntegralExchange READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO IntegralExchangeBill(
		[BillNumberID],
		[KTypeID],
		[PTypeID],
		[Qty],
		[Price],
		[Total],
		[Comment],
		[IsUnit2],
		[InputCostPrice],
		[HandZeroCost],
		STypeID,
		Serial,
		ProduceDate,
		ValidDate,
		GoodsCostPrice,
		GoodsNumber
	
		,CargoId
		,ItemId
		,IsCombined
		,NQty
		,UnitRate
		,ShowOrder
	) SELECT 
		@BillNumberID,
		KTypeID,
		PTypeID,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(ISNULL(Price,0)),
		dbo.F_RoundTotal(ISNULL(Total,0)),
		Comment,
		IsUnit2,
		dbo.F_RoundPrice(CASE WHEN @InputCostPriceFlag=1 THEN InputCostPrice ELSE 0 END),
		HandZeroCost,
		@STypeID,
		Serial,
		ProduceDate,
		ValidDate,
		dbo.F_RoundPrice(GoodsCostPrice),
		GoodsNumber
		
		,CargoId
		,ItemId
		,IsCombined
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,ShowOrder
	FROM @tb

	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_InsertIntoRequestBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].GP_InsertIntoRequestBill
GO



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertIntoRequestBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertIntoRequestBillDT;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-04 09:26:48.117
	描述：请购单明细查入dt版
*/
CREATE PROCEDURE GP_InsertIntoRequestBillDT
	@tb TbType_BuyRequest READONLY
--@encode$--
AS
BEGIN
	INSERT INTO RequestBill(
		BillNumberId,
		PtypeId,
		Qty, 
		SalePrice,	
		discount,	
		DiscountPrice,	
		total,	
		TaxPrice,	 
		TaxTotaL,
		comment,
		SaleTotal,
		Tax,
		Stypeid,
		RequestDate,
		OrderDate,
		Btypeid,
		ComparePrice,
		[State],
		Etypeid

		-- 新增字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,NCompleteTotal
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		,RequestQty
		,ShowOrder
		,PriceSource
	) SELECT
		BillNumberId,
		PtypeId,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(discount),
		dbo.F_RoundPrice(DiscountPrice),
		dbo.F_RoundTotal(total),
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		comment,
		dbo.F_RoundTotal(SaleTotal),
		dbo.F_RoundTax(Tax),
		Stypeid,
		RequestDate,
		OrderDate,
		Btypeid,
		dbo.F_RoundPrice(compareprice),
		State,
		Etypeid

		-- 新增字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,dbo.F_RoundTotal(NCompleteTotal)
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,0
		,ShowOrder
		,PriceSource
	FROM @tb;
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_InsertIntoRequestIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].GP_InsertIntoRequestIndex
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-08-16
-- Description: 请购单表头插入和修改
-- =============================================
CREATE PROCEDURE GP_InsertIntoRequestIndex
(
		@BillNumberId			NUMERIC(10, 0),	 --单据编号
		@BillDate				DATETIME,		 --做单时间
		@BillCode				VARCHAR(200),	 --单据编号
		@BillType				NUMERIC(4, 0),   --单据类型
		@comment				VARCHAR(500),	 --备注
		@Stypeid				VARCHAR(50) ,	 --分支机构
		@tax					 NUMERIC(24, 10) ,	 --税率
		@Etypeid				VARCHAR(50),	 --职员
		@dtypeid				VARCHAR(50),	 --部门
		@checke					VARCHAR(50),	 --制单人
		@totalqty				 NUMERIC(24, 10) ,	 --总数量
		@totalmoney				 NUMERIC(24, 10) ,	 --总金额
		@period					SMALLINT,
		@isfeeback				VARCHAR(2),      --修复标志
		@explain				VARCHAR(500),	 --说明
		
		@Cid INT,
		@Rate DECIMAL(22,10),
		@NTotalMoney DECIMAL(22,10),
		@IfYearBill INT,
		@Discount	 NUMERIC(24, 10) ,
		@RequestDate			DATETIME
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
		DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
		EXEC Gp_GetSubValue 'period',@STypeID,@period out
		SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@period
		DECLARE @CurDate datetime
		DECLARE @IsOrNotPassOneDay bit
	
	IF @BillNumberId = -1	--新增单据
	BEGIN
	
			-- ********	判断是否试用版 - Start	********
		DECLARE @N int, @intVersion int

		-- 判断版本号，是否试用版
		SELECT	@N = CAST(SubValue AS int)
		FROM	SysData1
		WHERE	SubNo = 2	-- 版本号

		IF @N IS NULL RETURN -1

		DECLARE @intBit int, @intMask int
		SELECT @intBit = @N & 15
		SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
		SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)
		-- ********	判断是否试用版 - END	********

		DECLARE @Re int,@Flag int
		EXEC @Re=Gp_Validate 2, @Flag OUTPUT
		IF @Re <>0 RETURN -3 --检查程序版本错误

		IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
		BEGIN
			--RAISERROR('校验错误 ！',16,1) 
			RETURN -3 --检查程序版本错误
		END

		IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
		BEGIN
			DECLARE @billnumberidtmp int
			SELECT @billnumberidtmp=ISNULL(COUNT(billnumberid),0) FROM billindex
			
			IF @billnumberidtmp > 200
			BEGIN
				--RAISERROR('试用版 ！',16,1) 
				RETURN -1
			END
		END  


		IF @BillType NOT IN (184,185) 
		BEGIN
			IF @BillDate<@BeginDate AND @BillType <>204
			BEGIN 
				--RAISERROR('录单日期小于本期开始日期 ！',16,1)
				RETURN -2
			END
			---根据配置检查过帐日期是否当前日期  开始 如果单据没有审核流程才判断,如果有审核流程,则在审核流程中判断 谢吉康 2004-06-14
			IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType=@BillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)	--检查单据是否有审核流程
			BEGIN
				SELECT @CurDate=GETDATE()
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1) AND @isfeeback='0'
				BEGIN 
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -4
				END
			END
			--有审核流程单据，第一次录单时需要和当前日期一致
			ELSE
			BEGIN
				SELECT @CurDate=GETDATE()
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1) AND @isfeeback='0'
				BEGIN 
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -4
				END
			END
			---根据配置检查过帐日期是否当前日期  完毕
		END
	
		INSERT INTO RequestIndex
		(
			BillDate,
			BillCode,
			BillType,
			comment,
			Stypeid,
			Etypeid,
			dtypeid,
			checke,
			totalqty,
			totalmoney,
			tax,
			period,
			explain,
			
			Cid,
			Rate,
			NTotalMoney,
			IfYearBill,
			IfAudit,
			Discount,
			RequestDate
		)
		VALUES
		(
			@BillDate,
			@BillCode,
			@BillType,
			@comment,
			@Stypeid,
			@Etypeid,
			@dtypeid,
			@checke,
			dbo.F_RoundQty(@totalqty),
			dbo.F_RoundTotal(@totalmoney),
			dbo.F_RoundTax(@tax),
			@period,
			@explain,
			
			@Cid,
			@Rate,
			dbo.F_RoundTotal(@NTotalMoney),
			@IfYearBill,
			'',
			dbo.F_RoundDiscount(@Discount),
			@RequestDate
		)
		DECLARE   @intReturn	BIGINT

		SELECT @intReturn=SCOPE_IDENTITY();
		--保存单据编号的种子数
		EXEC GP_SaveBillCode_Seed @intReturn,@BillDate,@BillType,@billcode
	END
	ELSE   --修改单据
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM RequestIndex WHERE BillNumberID = @BillNumberID AND BillType = @BillType)
			RETURN -7
			
		IF @BillType NOT IN (184,185)
		BEGIN
			IF @BillDate<@BeginDate AND @BillType <>204
			BEGIN 
				--RAISERROR('录单日期小于本期开始日期 ！',16,1) 
				RETURN -2
			END
			
			---根据配置检查过帐日期是否当前日期  开始 如果单据没有审核流程才判断,如果有审核流程,则在审核流程中判断 谢吉康 2004-06-14
			DECLARE @chvIfAudit varchar(10)
			IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType=@BillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)	--检查单据是否有审核流程
			BEGIN
				SELECT @CurDate=GETDATE()
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1) AND @isfeeback='0'
				BEGIN 
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -4
				END
			END
			ELSE
			BEGIN
				SET @chvIfAudit = ''
				SELECT @CurDate=BillDate,@chvIfAudit=ISNULL(IfAudit,'') FROM AuditingBill Where BillNumberId = @BillNumberId AND BillIndexType<>0
				IF @chvIfAudit = '' OR @chvIfAudit = '-1'
				BEGIN
					SELECT @CurDate=GETDATE()
				END
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1) AND @isfeeback='0'
				BEGIN
			
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -4
				END
			
			END
		END
		
		 UPDATE RequestIndex 
		 SET
			BillDate=@BillDate,
			BillCode=@BillCode,
			BillType=@BillType,
			Comment=@comment,
			Stypeid=@Stypeid,
			etypeid=@Etypeid,
			dtypeid=@dtypeid,
			checke=@checke,
			totalqty=dbo.F_RoundQty(@totalqty),
			totalmoney=dbo.F_RoundTotal(@totalmoney),
			tax=dbo.F_RoundTax(@tax),
			period=@period,
			explain=@explain,
			Discount=dbo.F_RoundDiscount(@Discount),
			RequestDate = @RequestDate
		 WHERE BillNumberId=@BillNumberId
		 
		 SELECT @intReturn=@BillNumberId
		 
		 DELETE  FROM RequestBill WHERE BillNumberId=@BillNumberId
		 
		 -- 清除表头，明细自定义
		DELETE FROM CustomBillColumns	WHERE billnumberid=@BillNumberId AND BillType=@BillType
		DELETE FROM [CustomBillDetailColumns]WHERE billnumberid=@BillNumberId AND BillType=@BillType
		DELETE FROM dbo.Custom_BillDetails WHERE BillId=@BillNumberId AND BillType=@BillType
		DELETE FROM dbo.Custom_BillIndex WHERE BillId=@BillNumberId AND BillType=@BillType
	END	

END

RETURN	@intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Gp_InsertK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_InsertK]
GO

/****** Object:  StoredProcedure [dbo].[Gp_InsertK]    Script Date: 05/20/2011 17:30:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


CREATE         PROCEDURE [dbo].[Gp_InsertK]
(
	@Parid			[varchar](50),
	@DbName         [varchar](30),
	@UserCode		[varchar](26),
	@FullName		[varchar](66),
	@Name			[varchar](30),
	@Comment		[varchar](256),
	@LinkMan		varchar(20),
	@Tel			varchar(50),		--电话
	@Address		varchar(50),		--地址
	@PyCode			varchar(200),
	@STypeID		varchar(50),
	@job			VARCHAR(100) = '',	--职位
	@mobile			VARCHAR(100) = '',	--手机
	@sheng			VARCHAR(100) = '',	--省
	@shi			VARCHAR(100) = '',	--市
	@xian			VARCHAR(100) = '',	--县
	@postcode		VARCHAR(100) = ''	--邮编
)
--@encode$--
AS
SET NOCOUNT ON
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

declare @parFullName varchar(200)
set @parFullName=(SELECT top 1 fullname FROM stock where typeid=@parid)
--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(SELECT subvalue FROM sysdata where subname='ifqp')
IF(@ParId<>'00000')
BEGIN
--判断停用不能分类
declare @deleted INT
SELECT @deleted=deleted FROM stock where typeId=@Parid
IF(@deleted=1)
BEGIN
   RAISERROR('该仓库【%s】已经被停用，不能分类',16,1,@parFullName)RETURN ---15  
END

-----------------------------判断是否在自定义中有关联信息--------------------------------------
DECLARE 
	@result			INT=0,		--自定义接收返回值
	@temptypename	VARCHAR(20)
SET @temptypename='ktype'

	exec @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@temptypename,@ctypeid=@parid,@result=0
		IF @result=1
		BEGIN
			RAISERROR('当前信息已在自定义中关联,不可以再''分类''',16,1) RETURN
		END
---------------------------------------- END ------------------------------------------------------	

---------------------------------已关联辅助核算，不能分类----------------------------------------
--IF EXISTS(SELECT stypeid FROM AC_ACCOUNT_ASSIST_CHECKITEMS WHERE stypeid=@Parid)
--	OR EXISTS(SELECT stypeid FROM AC_BALANCE_ASSIST_CHECKITEMS  WHERE stypeid=@Parid)
--	OR EXISTS(SELECT stypeid FROM AC_BALANCE_ASSIST_CHECKITEMS_DETAIL  WHERE stypeid=@Parid)
--	OR EXISTS(SELECT stypeid FROM AC_INIACCOUNT_ASSIST_CHECKITEMS  WHERE stypeid=@Parid)
--	OR EXISTS(SELECT stypeid FROM AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL  WHERE stypeid=@Parid)
--	OR EXISTS(SELECT typeid FROM AC_VOUCHER_BILL_ASSIST_CHECKITEMS  WHERE typeid=@Parid)
--	BEGIN
--		RAISERROR('该基本信息已关联辅助核算,不能分类',16,1)RETURN--RETURN -355
--	END
	
---------------------------------已关联凭证录入，不能分类----------------------------------------
--IF EXISTS(SELECT stypeid FROM AC_VOUCHER WHERE stypeid=@Parid)
--	OR EXISTS(SELECT stypeid FROM AC_VOUCHER_BILL  WHERE stypeid=@Parid)
--	OR EXISTS(SELECT typeid FROM AC_VOUCHER_BILL_ASSIST_CHECKITEMS  WHERE typeid=@Parid)
--	OR EXISTS(SELECT stypeid FROM AC_VOUCHER_BILL_CASHMONEYITEMS  WHERE stypeid=@Parid)
--	BEGIN
--		RAISERROR('该基本信息已关联凭证录入,不能分类',16,1)RETURN--RETURN -355
--	END
	
-- 判断维修库存中期初是否为零
IF EXISTS(SELECT ktypeid FROM Wx_iniGoodsstocks where ktypeid=@parid and Qty<>0)
	BEGIN
		RAISERROR('该仓库【%s】维修品库存期初余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
	END 
-- 判断库存量（每种商品）是否为零
IF EXISTS(SELECT ktypeid FROM goodsstocks where ktypeid=@parid and Qty<>0)
	BEGIN
		--print '['+@FullName+']仓库库存余量不为零，不能分类'
		RAISERROR('该仓库【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
	END 
IF EXISTS(SELECT ktypeid FROM inigoodsstocks where ktypeid=@parid and Qty<>0)
	BEGIN
		--print '['+@FullName+']仓库库存余量不为零，不能分类'
		RAISERROR('该仓库【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
	END 
	
--判断库存期初数量状况	
IF EXISTS(SELECT ktypeid FROM Ini_GOODSSTOCKS_QTY where ktypeid=@parid and Qty<>0)
	BEGIN
		RAISERROR('该仓库【%s】期初库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
	END 
	
--pos模块
IF EXISTS(SELECT KTypeID FROM CommonPosSaleIndex  where ktypeid=@parid)
OR EXISTS(SELECT KTypeID FROM CommonPosPtypeCheckNdx  where ktypeid=@parid)
OR EXISTS(SELECT KTypeID FROM CX_SaleStocksArea  where ktypeid=@parid)
OR EXISTS(SELECT stockid FROM CommonPosInfo  where stockid=@parid)
	BEGIN
		 --print '2555'
		RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
	END
IF EXISTS(SELECT ktypeid FROM wx_goodsstocks where ktypeid=@parid and Qty<>0)
	BEGIN
		--print '['+@FullName+']仓库库存余量不为零，不能分类'
		RAISERROR('该仓库【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
	END 
IF EXISTS(SELECT ktypeid FROM wx_inigoodsstocks where ktypeid=@parid and Qty<>0)
	BEGIN
		--print '['+@FullName+']仓库库存余量不为零，不能分类'
		RAISERROR('该仓库【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
	END 
IF EXISTS(SELECT ktypeid FROM inigoodsstocks where ktypeid=@parid and Total<>0)
	BEGIN
		--print '['+@FullName+']仓库库存成本不为零，不能分类'
		RAISERROR('该仓库【%s】有库存期初，不能分类',16,1,@parFullName)RETURN--RETURN -34
	END 
--判断序列号
IF EXISTS(SELECT KTypeID FROM gp_CruPtypeSerial where KTypeID=@Parid)
	BEGIN
		--print '此仓库有序列号，不能分类'
		 RAISERROR('该仓库【%s】有序列号关联情况，不能分类',16,1,@parFullName)RETURN--RETURN -15
	END
IF EXISTS(SELECT KTypeID FROM gp_initPtypeSerial where KTypeID=@Parid)
	BEGIN
		--print '此仓库有期初序列号，不能分类'
		 RAISERROR('该仓库【%s】有期初序列号关联情况，不能分类',16,1,@parFullName)RETURN--RETURN -16
	END

--发票中关联了仓库，则不允许分类
IF EXISTS(SELECT KTypeID FROM FaPiaoBill where KTypeID=@Parid)
	BEGIN
		 RAISERROR('该仓库【%s】已在发票中关联，不能分类',16,1,@parFullName)RETURN--RETURN -16
	END

-- 判断借欠余额
IF EXISTS(SELECT kTypeID FROM V_LendStatus where kTypeID=@parid and Qty<>0)
	BEGIN
		--print '['+@FullName+']仓库有借进借出，不能分类'
		RAISERROR('该仓库【%s】有借进借出，不能分类',16,1,@parFullName)RETURN--RETURN -5
	END 
-- 判断经营
IF EXISTS(SELECT kTypeID FROM InOutStockTable where kTypeID=@parid and Qty<>0)      
   or EXISTS(SELECT kTypeID FROM LendIndex where kTypeID=@parid and totalQty<>0)    
	BEGIN
		--print '['+@FullName+']仓库已经经营过，不能分类'
		RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
	END 
IF EXISTS(SELECT kTypeID FROM OrderIndex where kTypeID=@parid and kTypeID <> '00000' )
	BEGIN
		-- print '订单使用过'
		RAISERROR('该仓库【%s】已在订单中使用，不能分类',16,1,@parFullName)RETURN--RETURN -501
	END
IF EXISTS(SELECT kTypeID FROM LendIndex where kTypeID=@parid)
	BEGIN
		-- print '借欠使用过'
		RAISERROR('该仓库【%s】已在借欠单中使用，不能分类',16,1,@parFullName)RETURN--RETURN -502
	END

IF EXISTS(SELECT kTypeID FROM Billindex where (kTypeID=@parid OR  kTypeID2=@parid OR  kTypeID3=@parid) and kTypeID <> '00000')    --modify 2010.05.21  ljun
	BEGIN
		--经营过
		RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
	END

IF EXISTS(SELECT kTypeID FROM iniCommissionStock where kTypeID=@parid and Qty<>0)
   or EXISTS(SELECT kTypeID FROM CommissionStock where kTypeID=@parid and Qty<>0)
	BEGIN
		--print '['+@FullName+']仓库有代销情况，不能分类'
		RAISERROR('该仓库【%s】存在代销情况，不能分类',16,1,@parFullName)RETURN--RETURN -13
	END 

IF EXISTS(SELECT kTypeID FROM iniCommissionStock where kTypeID=@parid and total<>0)
   or EXISTS(SELECT kTypeID FROM CommissionStock where kTypeID=@parid and total<>0)
	BEGIN
		--print '['+@FullName+']仓库有代销情况，不能分类'
		RAISERROR('该仓库【%s】存在代销情况，不能分类',16,1,@parFullName)RETURN--RETURN -13
	END 
	IF @ifqp='1'
	BEGIN
		--采购类单
		IF EXISTS(SELECT ktypeid FROM buybill where ktypeid=@parid)
			BEGIN
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
			END
		--领料出库单
		IF EXISTS(SELECT KTypeID FROM Qp_PickingBill where ktypeid=@parid)
			BEGIN
			    --print '2555'
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
			END
		--领料退回单
		IF EXISTS(SELECT KTypeId FROM Qp_PickingBackBill where KTypeId=@parid)
			BEGIN
			    --print '2555'
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
			END
		--销售类
		IF EXISTS(SELECT ktypeid FROM salebill where ktypeid=@parid)
			BEGIN
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
			END
		--代销类
		IF EXISTS(SELECT ktypeid FROM CommissionBill where ktypeid=@parid)
			BEGIN
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@FullName)RETURN--RETURN -6
			END
		--订单类
		IF EXISTS(SELECT ktypeid FROM orderbill where ktypeid=@parid)
			BEGIN
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
			END
		IF EXISTS(SELECT ktypeid FROM IntegralExchangeBill where ktypeid=@parid)
			BEGIN
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
			END
		--快修单表体
		IF EXISTS(SELECT ktypeid FROM QP_QuickRepairBill_PType where ktypeid=@parid)
			BEGIN
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
			END
		--生产拆装单
		IF EXISTS(SELECT ktypeid FROM disassemblebill where ktypeid=@parid)
			BEGIN
				RAISERROR('该仓库【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
			END
		--已设置货位
		IF EXISTS(SELECT ktypeid FROM CargoSpace where ktypeid=@parid)
			BEGIN
				RAISERROR('该仓库【%s】已设置货位，不能分类',16,1,@parFullName)RETURN--RETURN -35
			END
	END

--盘点单
IF EXISTS(SELECT top 1 ktypeid  FROM  StockCheckIndex where ktypeid=@parid  )
	BEGIN
		RAISERROR('该仓库【%s】已在库存盘点单中使用，不能分类',16,1,@parFullName)RETURN--RETURN -370
	END
END

--销售类
		IF EXISTS(SELECT * FROM OrderBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				RAISERROR('该仓库已关联销售订单或采购订单，不能分类',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM SaleBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				RAISERROR('该仓库已关联销售出库单，不能分类',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM SaleGoodsExchangeBill,Stock WHERE (KTypeID=@parid AND KTypeID=Stock.typeId) OR (KTypeID2=@parid AND KTypeID2=Stock.typeId))
			BEGIN
				RAISERROR('该仓库已关联销售换货单，不能分类',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM SaleBackBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				RAISERROR('该仓库已关联销售退货单，不能分类',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM CommissionBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				RAISERROR('该仓库已关联委托代销单据，不能分类',16,1)
				RETURN
			END
		--采购类
		IF EXISTS(SELECT * FROM BuyBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				RAISERROR('该仓库已关联采购入库单，不能分类',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM BuybackBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				RAISERROR('该仓库已关联采购退货单，不能分类',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM BuyGoodsExchangeBill,Stock WHERE (KTypeID=@parid AND KTypeID=Stock.typeId) OR ((KTypeID2=@parid AND KTypeID2=Stock.typeId)))
			BEGIN
				RAISERROR('该仓库已关联采购换货单，不能分类',16,1)
				RETURN
			END
		--库存类
		IF EXISTS(SELECT * FROM StypeMoveBill,Stock WHERE (KTypeID=@parid AND KTypeID=Stock.typeId) OR ((KTypeID2=@parid AND KTypeID2=Stock.typeId)))
			BEGIN
				RAISERROR('该仓库已关联分支机构调拨出库单或分支机构调拨入库单，不能分类',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM DisassembleBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				RAISERROR('该仓库已关联生产拆装单，不能分类',16,1)
				RETURN
			END
		--会员类
		IF EXISTS(SELECT * FROM IntegralExchangeBill,Stock WHERE KTypeID=@parid AND KTypeID=Stock.typeId)
			BEGIN
				RAISERROR('该仓库已关联积分兑换单，不能分类',16,1)
				RETURN
			END
		---------------------------------------------- 9.2新增判断BEGIN ------------------------------------------------
		BEGIN
						
		IF EXISTS(SELECT TOP 1 * FROM PriceRule_Detail_KConfig WHERE   KTypeID=@Parid)
			BEGIN
				RAISERROR('该仓库已关联价格策略，不能分类',16,1)RETURN
			END
		IF EXISTS(SELECT TOP 1 * FROM PromoRule_Detail_KConfig WHERE   KTypeID=@Parid)
			BEGIN
				RAISERROR('该仓库已关联促销规则，不能分类',16,1)RETURN
			END
		IF EXISTS(SELECT TOP 1 * FROM PosInfo WHERE KTypeID=@Parid)
			BEGIN
				RAISERROR('该仓库已关联POS，不能分类',16,1)RETURN
			END
		END	
		
		---------------------------------------------- 9.2新增判断END --------------------------------------------------

-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
IF @nReturntype=-1 
	BEGIN
		RAISERROR('仓库的分类不能超过10层',16,1)RETURN--RETURN -1
	END
IF @nReturntype=-2 
	BEGIN
		RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
-- 判断重复的ID,UserCode
IF EXISTS(SELECT typeId FROM Stock where  (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
	BEGIN
		--print '['+@usercode+']仓库已存在'
		RAISERROR('【%s】已经存在，仓库的名称或编号不能相同',16,1,@FullName)RETURN--RETURN -3
	END


-- 判断重复的ID,UserCode
IF EXISTS(SELECT * FROM [stock] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	BEGIN
		--print '['+@usercode+']仓库已存在'
		RAISERROR('该【%s】的编号或名称已被已停用的仓库使用，请更换或删除该停用的编号或名称',16,1,@FullName)RETURN--RETURN -31
	END
-- 判断重复的ID,UserCode
IF EXISTS(SELECT * FROM [stock] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
	BEGIN
		--print '['+@usercode+']仓库已存在'
		RAISERROR('该仓库【%s】名称或编号不能与已停用的名称或编号重复',16,1,@FullName)RETURN--RETURN -101
	END

/*
-- 判断仓库的最大使用数量
declare @nCount int
SELECT @nCount=Count(*) FROM stock 
where sonnum = 0 
 and deleted=0
IF @nCount > 10
BEGIN
-- print '仓库数量大于10'
 RETURN -99
END
*/

/*插入前判断默认货位是否重复-------------开始*/
DECLARE @msg VARCHAR(max)=''
IF EXISTS(SELECT TOP 1 1 FROM CargoType WHERE UserCode=@FullName+'默认货位')
BEGIN
	SET @msg='【'+@FullName+'】仓库对应的默认货位“'+@FullName+'默认货位”编码已在货位档案里存在，请修改货位档案后再新增该仓库！'
	RAISERROR(@msg,16,1)
	RETURN 
END
IF EXISTS(SELECT TOP 1 1 FROM CargoType WHERE FullName=@FullName+'默认货位')
BEGIN
	SET @msg='【'+@FullName+'】仓库对应的默认货位“'+@FullName+'默认货位”名称已在货位档案里存在，请修改货位档案后再新增该仓库！'
	RAISERROR(@msg,16,1)
	RETURN 
END
/*插入前判断默认货位是否重复-------------结束*/


DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

BEGIN tran insertproc
SELECT @leveal=leveal FROM stock where typeid=@Parid
SELECT @leveal=@leveal+1
INSERT INTO [stock] 
  ( 
	[typeId],
	[Parid],
	[leveal],
	[soncount],
	[sonnum],
	[FullName],
	[Name], 
	[UserCode],
	[Comment],
	[LinkMan],
	[Tel],
	[Add],
	[PyCode],
	[STypeID],
	[Job],
	[mobile],
	[sheng],
	[shi],
	[xian],
	[postcode]
 )  
VALUES 
 ( 
	@EtypeId_1,
	@Parid,
	@leveal,
	0,
	0,
	@FullName,
	@name,
	@UserCode,
	@Comment,
	@LinkMan ,
	@Tel ,
	@Address,
	@returnPym,
	@STypeID,
	@job,
	@mobile,
	@sheng,
	@shi,
	@xian,
	@postcode
 )
IF @@rowcount=0 
BEGIN
	rollback tran insertproc 
	RETURN -1
END else 
BEGIN
	update [stock]
	set sonnum=@nSonnum+1,soncount=@nSoncount+1
	where typeid=@Parid
END

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Stock
UPDATE Stock SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
 
commit tran insertproc
























GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




CREATE           PROCEDURE Gp_InsertL
(
 @Parid   [varchar](50),
 @DbName         [varchar](30),
 @szKtypeID      [varchar](30),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @SimpleName [varchar](30),
 @Comment  [varchar](256),
 @PyCode varchar(200)

)
--@encode$--
AS
SET NOCOUNT ON
declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint
-- 判断库存量（每种商品）是否为零

if exists(select Ltypeid from GoodsLocal where Ltypeid=@parid and Qty<>0)
begin
	--print '['+@FullName+']货位库存余量不为零，不能分类'
	return -4
end 


--判断序列号
if exists(select LTypeID from gp_CruPtypeSerial where LTypeID=@Parid)
begin
	--print '此货位有序列号，不能分类'
	 return -15
end


-- 判断经营
if exists(select LTypeID from LocalDetail where (LTypeID=@parid or LTypeID2=@parid) and Qty<>0)
   --or exists(select LTypeID from LocalIndex where (LTypeID=@parid or LTypeID2=@parid) and totalQty<>0)
begin
	--print '['+@FullName+']货位已经经营过，不能分类'
	return -6
end 


-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 return -1
if @nReturntype=-2 return -2
 
-- 判断重复的ID,UserCode

if exists(select * from [Ltype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) )
begin
	
	--print '['+@usercode+']货位已存在'
	--print  @EtypeId_1
	return -3
end
-- 判断重复的ID,UserCode
if exists(select * from [Ltype] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
begin
	--print '['+@usercode+']货位已存在'
	return -10
end

-- 判断重复的ID,UserCode
if exists(select * from [Ltype] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) )
begin
	--print '['+@usercode+']货位已存在'
	return -31
end
-- 判断重复的ID,UserCode
if exists(select * from [Ltype] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
begin
	--print '['+@usercode+']货位已存在'
	return -101
end

/*
-- 判断货位的最大使用数量
declare @nCount int
select @nCount=Count(*) from Ltype 
where sonnum = 0 
 and deleted=0
if @nCount > 10
begin
-- print '货位数量大于10'
 return -99
end
*/

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode


begin tran insertproc
select @leveal=leveal from Ltype where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO [Ltype] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [Ktypeid],
  [UserCode],
  [FullName], 
  [Name],
  [SysFlag],
  [deleted],
  [Comment],
  [PyCode]	
 )  
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @szKtypeID,
  @UserCode,
  @FullName,
  @simplename,
  0,
  0,
  @Comment,
  @returnPym
 )
if @@rowcount=0 
begin
 rollback tran insertproc 
 return -1
end else 
begin
 update [Ltype]
 set sonnum=@nSonnum+1,soncount=@nSoncount+1
 where typeid=@Parid
end
 
commit tran insertproc













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertLendBill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertLendBill]
GO




IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[Gp_InsertLendBillDT]')
                    AND TYPE IN ( N'P', N'PC' ) ) 
    DROP PROC Gp_InsertLendBillDT;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-08 16:11:03.190
	描述：借欠四种单据的明细插入dt版
*/
CREATE PROCEDURE Gp_InsertLendBillDT
    @BillNumberID INT ,
    @BillType INT ,
    @StypeId VARCHAR(50) ,
    @tb TbType_LendBorrow READONLY
--@encode$--
AS 
    BEGIN
        SET NOCOUNT ON
        /*
        DECLARE @QTY DECIMAL(22, 4)
        DECLARE @NQTY DECIMAL(22, 4)
        DECLARE @RN INT 
		
        SET @RN = -999
        -- 验证此表数据中是否存在不符合条件的数据，如果有选出 行号
        IF @BillType IN ( 72, 88 ) --还回 基本单位数量
            BEGIN
                SELECT  CASE WHEN @BillType = 88 THEN A.qty + T.Qty 
												WHEN @BillType = 72 THEN - A.qty - T.Qty 
												END AS qty ,
												
                        CASE WHEN @BillType = 88 THEN A.nQty + T.nQty 
                        WHEN @BillType = 72 THEN - A.nQty - T.nQty 
                        END AS nQty ,
                        T.Rn
                INTO    #Temp
                FROM    ( SELECT    AVG(L.qty) + ISNULL(SUM(L1.qty), 0) AS qty ,
                                    AVG(L.nQty) + ISNULL(SUM(L1.nQty), 0) AS nQty ,
                                    L.Id ,
                                    L.BillNumberId
                          FROM      dbo.LendBill L
                                    LEFT JOIN ( SELECT  Lx.*
                                                FROM    dbo.LendBill Lx
                                                WHERE   Lx.BillNumberId <> @BillNumberID
                                              ) L1 ON L.id = L1.BackItemId
                          GROUP BY  L.Id ,
                                    L.BillNumberId
                        ) A
                        INNER JOIN ( SELECT RN = ROW_NUMBER() OVER ( ORDER BY GETDATE() ) ,
                                            BackItemId ,
                                            Qty ,
                                            nQty
                                     FROM   @tb
                                   ) T ON A.id = T.backitemid
                          
                -- 先出第一条不符合条件的就行了
                SELECT TOP 1
                        @QTY = qty ,
                        @RN = rn
                FROM    #Temp
                ORDER BY qty DESC
        
            
                SELECT TOP 1
                        @NQTY = nQty ,
                        @RN = rn
                FROM    #Temp
                ORDER BY nQty DESC
       
                IF ( @QTY > 0 ) 
                    BEGIN
                        DROP TABLE #Temp
                        RETURN @RN + 1000	-- 基本单位数量超过调原单数量
                    END
                IF ( @NQTY > 0 ) 
                    BEGIN
                        DROP TABLE #Temp
                        RETURN @RN + 2000 -- 浮动单位数量超过调原单数量
                    END
                DROP TABLE #Temp
            END
            */
        DELETE  LendBill
        WHERE   BillNumberId = @BillNumberID
        INSERT  INTO LendBill
                ( BillNumberId ,
                  Comment ,
                  PtypeId ,
                  Qty ,
                  Serial ,
                  STypeID ,
                  BackItemId ,
                  CargoId ,
                  ItemId ,
                  IsCombined ,
                  NQty ,
                  GoodsNumber ,
                  UnitRate,
                  ProduceDate,
                  ValidDate,
                  ShowOrder,
                  FromBillid
                )
                SELECT  @BillNumberID ,
                        Comment ,
                        PtypeId ,
                        ISNULL(dbo.F_RoundQty(Qty) ,0),
                        Serial ,
                        @StypeId ,
                        BackItemId ,
                        CargoId ,
                        ItemId ,
                        IsCombined ,
                        ISNULL(dbo.F_RoundQty(NQty) ,0),
                        GoodsNumber ,
						ISNULL(dbo.F_RoundTranslateRate(UnitRate),0),
						ProduceDate,
						ValidDate,
						ShowOrder,
						FromBillid
                FROM    @tb;
                
		UPDATE dbo.LendIndex SET totalqty = 
			( SELECT ISNULL( SUM(Qty),0) FROM dbo.LendBill WHERE BillNumberId = @BillNumberID  )
		WHERE BillNumberId = @BillNumberID

       
	
    END           
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[Gp_InsertLendBillDTAfterCheck]')
                    AND TYPE IN ( N'P', N'PC' ) ) 
    DROP PROC Gp_InsertLendBillDTAfterCheck;
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-10 16:11:03.190
	描述：借欠四种单据的明细 dt版 事后验证
*/
CREATE PROCEDURE Gp_InsertLendBillDTAfterCheck
    @BTypeId VARCHAR(50) ,
    @KTypeId VARCHAR(50) ,
    @Type VARCHAR(50) -- 72 借进换回
												--88 借出换回
    ,
    @tb TbType_LendBorrowAfterCheck READONLY
--@encode$--
AS 
    BEGIN     
	-- 选出 没有借出（进）或 者借出（进）数量 小于 还进（出）的数据  也就是多还了的记录
	
        SELECT * FROM (SELECT  CASE WHEN @Type = 72
                     THEN ISNULL(SUM(BorrowBack), 0) - ISNULL(SUM(Borrow), 0)
                     WHEN @Type = 88
                     THEN ISNULL(SUM(LendBack), 0) - ISNULL(SUM(Lend), 0)
                END AS re ,
                CASE WHEN @Type = 72
                     THEN ISNULL(SUM(NBorrowBack), 0) - ISNULL(SUM(NBorrow), 0)
                     WHEN @Type = 88
                     THEN ISNULL(SUM(NLendBack), 0) - ISNULL(SUM(NLend), 0)
                END AS nre ,
                ISNULL(SUM(Lend), 0) AS lend ,
                ISNULL(SUM(Borrow), 0) AS borrow ,
                ISNULL(SUM(NLend), 0) AS nlend ,
                ISNULL(SUM(NBorrow), 0) AS nborrow ,
                V.pfullname ,
                V.pTypeid ,
                V.IsCombined ,
                V.ItemID ,
                V.GoodsNumber 
        FROM    (
        
        SELECT		
			lb.PtypeId AS pTypeID, 
			li.kTypeID, 	
			li.bTypeID,
			lb.Qty AS Qty,
			lb.ItemID,
			lb.IsCombined,
			lb.NQty,
			lb.GoodsNumber,
			p.FullName AS 'pfullname' ,
			CASE li.BillType WHEN 71 THEN Qty ELSE 0 END AS Borrow,
			CASE li.BillType WHEN 72 THEN -Qty ELSE 0 END AS BorrowBack,
			CASE li.BillType WHEN 87 THEN -Qty ELSE 0 END AS Lend,
			CASE li.BillType WHEN 88 THEN Qty ELSE 0 END AS LendBack,
			CASE li.BillType WHEN 71 THEN NQty ELSE 0 END AS NBorrow,
			CASE li.BillType WHEN 72 THEN -NQty ELSE 0 END AS NBorrowBack,
			CASE li.BillType WHEN 87 THEN -NQty ELSE 0 END AS NLend,
			CASE li.BillType WHEN 88 THEN NQty ELSE 0 END AS NLendBack
		FROM dbo.LendBill lb 
			  INNER JOIN dbo.LendIndex li ON li.BillNumberId = lb.BillNumberId 
			  INNER JOIN dbo.ptype p ON lb.PtypeId = p.typeId 
			  WHERE li.ifcheck='t' AND li.RedWord=0 AND li.draft = 0
        
        ) V
                INNER JOIN @tb T ON V.pTypeID = T.PTypeID
									AND V.IsCombined = T.IsCombined 
									AND V.ItemID = T.ItemID 
									AND V.GoodsNumber = T.GoodsNumber 
        WHERE   V.BTypeID = @btypeid
                AND V.KTypeID = @ktypeid
                
                
        GROUP BY V.pTypeID ,
                V.pFullName ,
                V.IsCombined ,
                V.ItemID ,
                V.GoodsNumber ) R ORDER BY R.re DESC
    END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertLendInit]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertLendInit;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-06-07
	描述：保存借欠期初
	2012-08-10 修改自由项写入null的情况
	2015-0-28 SiHuaShan  增加序列号插入
	
	
	--梁晰 2017-03-30 借出借入序列号只受各自数量影响
*/

CREATE PROCEDURE [dbo].[Gp_InsertLendInit]
	@btypeid VARCHAR(100) --往来单位id
	,@ptypeId VARCHAR(100) -- 商品id
	,@ktypeId VARCHAR(100) -- 仓库id
	,@tb TbType_LendInit READONLY 
--@encode$--
AS
BEGIN
	DELETE IniGoodsLend WHERE btypeid=@btypeid AND ptypeid=@ptypeid AND ktypeid=@ktypeid
	
	
	IF EXISTS(SELECT 1 FROM @tb)
		INSERT INTO IniGoodsLend(
			BtypeId
			,PtypeId
			,KtypeId
			,Qty
			,GoodsNumber
			,ItemID
			,Nqty
			,Iscombined
			,LendQty
			,NLendQty
			,BorrowQty
			,NBorrowQty
		) SELECT @btypeid,
				 @ptypeId,
				 @ktypeId,
				 dbo.F_RoundQty(SUM(Qty)),
				 ISNULL(GoodsNumber,''),
				 ISNULL(ItemId,0),
				 dbo.F_RoundQty(ISNULL(SUM(Nqty),0)),
				 ISNULL(Iscombined,0),
				 dbo.F_RoundQty(ISNULL(SUM(Lend),0)),
				 dbo.F_RoundQty(ISNULL(SUM(LendNqty),0)),
				 dbo.F_RoundQty(ISNULL(SUM(Borrow),0)),
				 dbo.F_RoundQty(ISNULL(SUM(BorrowNqty),0)) 
				 FROM @tb GROUP BY ItemId,Iscombined,GoodsNumber; 
	
	DECLARE @LendQty INT,@BorrowQty INT;
	
	SELECT @LendQty = ISNULL(SUM(Lend),0),@BorrowQty = ISNULL(SUM(Borrow),0)
	FROM @tb;
	
	IF @LendQty = 0
	BEGIN
	    
	    DELETE FROM gp_initLendPtypeSerial WHERE PtypeID=@ptypeId AND  KtypeID=@ktypeId AND (BtypeID2=@btypeid OR BTypeID1=@btypeid) AND State = 18
	END
	
	IF @BorrowQty = 0
	BEGIN
	    DELETE FROM gp_initLendPtypeSerial WHERE PtypeID=@ptypeId AND  KtypeID=@ktypeId AND (BtypeID2=@btypeid OR BTypeID1=@btypeid) AND State = 17
	END
	
-------------序列号开始------------------
	DECLARE @RowCount INT,
			@RowIndex INT,
			@Flag	  INT,
			@State	  INT,
			@IfBorrow INT,
			@GoodsNumber VARCHAR(50),
			@ItemId		VARCHAR(50),
			@Iscombined	BIT,
			@Serial		VARCHAR(MAX);
			
	SELECT GoodsNumber,
		   Serial,
		   ItemId,
		   IfBorrow,
		   Iscombined,
		   ROW_NUMBER() OVER(ORDER BY ItemId,Iscombined,GoodsNumber) AS RowIndex 
	INTO #TMP 
	FROM @tb WHERE Serial IS NOT NULL AND Serial <>'' GROUP BY  GoodsNumber,Serial,ItemId,IfBorrow,Iscombined;	
	
	SELECT @RowCount=COUNT(1) FROM #TMP ;
	IF @RowCount=0
	BEGIN
		DROP TABLE #TMP;
		RETURN;
	END
	

	SET @RowIndex=0;
	
	WHILE(@RowIndex<=@RowCount)
	BEGIN
	
		SELECT @IfBorrow=IfBorrow,
			   @GoodsNumber=GoodsNumber,
			   @ItemId=ItemId,
			   @Iscombined=Iscombined,
			   @Serial=Serial
		FROM #TMP 
		WHERE RowIndex=@RowIndex;
		
		SET @Flag=@IfBorrow;
		IF @GoodsNumber IS NULL
			SET @GoodsNumber='';
		IF @ItemId IS NULL
			SET @ItemId=0;
		--借进序列号
		IF @IfBorrow=1					
		BEGIN
			INSERT INTO gp_initLendPtypeSerial(
												Serial,
												KtypeID,
												PtypeID,
												BTypeID2,
												InKtypeTime,
												State,
												Flag,
												IsCombined,
												ItemID,
												GoodsNumber,
												BFlag
											  )
								      SELECT Serial,
											 @ktypeId,
											 @ptypeId,
											 @btypeid,
											 CONVERT(VARCHAR(20),GETDATE(),20),
											 17,
											 1,
											 @Iscombined,
											 @ItemId,
											 @GoodsNumber,
											 '1'
									 FROM F_SplitSerial(@Serial,'я') WHERE Serial <>'';
		END
		--借出序列号
		ELSE    
		BEGIN
			INSERT INTO gp_initLendPtypeSerial(
												Serial,
												KtypeID,
												PtypeID,
												BtypeID1,
												InKtypeTime,
												State,
												Flag,
												IsCombined,
												ItemID,
												GoodsNumber
											  )
								      SELECT Serial,
											 @ktypeId,
											 @ptypeId,
											 @btypeid,
											 CONVERT(VARCHAR(20),GETDATE(),20),
											 18,
											 0,
											 @Iscombined,
											 @ItemId,
											 @GoodsNumber
									 FROM F_SplitSerial(@Serial,'я') WHERE Serial <>'';
		END
		
		SET @RowIndex+=1;
	END
	
	DROp TABLE #TMP
	DELETE dbo.IniGoodsLend WHERE LendQty=0 AND BorrowQty = 0
	
END
---------------序列号结束--------------------
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


/*
	--编程：Roamer Wu
	--时间：2003-12-29
	--功能：插入货位单据的明细
*/
CREATE       PROCEDURE GP_InsertLocalDetail
(
	@BillNumberID	 numeric(18, 0),
	@BillType	 numeric(4, 0),
	@PTypeID	 varchar (50),
	@LTypeID	 varchar (50) = '',		--入库货位
	@LTypeID2	 varchar (50) = '',		--出库货位
	@QTY		  NUMERIC(24, 10) ,
	@Price		  NUMERIC(24, 10) ,
	@Total		  NUMERIC(24, 10) ,
	@IsUnit2	 int,
	@Comment	 Varchar(255),
	@Serial		 VARCHAR(max)
)
--@encode$--
AS

SET NOCOUNT ON

SET @Price = NULLIF(@Price,0)
SET @Total = NULLIF(@Total,0)

Insert Into LocalDetail(
	[BillNumberID],
	[BillType],
	[PTypeID],
	[LTypeID],
	[LTypeID2],
	[QTY],
	[Price],
	[Total],
	[IsUnit2],
	[Comment],
	[Serial]
	)
Values (
	@BillNumberID,
	@BillType,
	@PTypeID,
	@LTypeID,
	@LTypeID2,
	dbo.F_RoundQty(@QTY),
	dbo.F_RoundPrice(@Price),
	dbo.F_RoundTotal(@Total),
	@IsUnit2,
	@Comment,
	@Serial
)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


/*
	--编程：Roamer Wu
	--时间：2003-12-29
	--功能：添加货单据的索引
*/
CREATE        PROCEDURE GP_InsertLocalIndex
(
	@BillType		 numeric(4, 0),
	@BillCode		 varchar (200),  -- #&**&#
	@BillDate		 datetime,
	@ETypeID		 varchar (50),
	@KTypeID		 varchar (50),
	@IfCheck		 varchar (50),
	@TotalQty		  NUMERIC(24, 10) ,
	@BID			  NUMERIC(24, 10) ,
	@BCode			 varchar (50),
	@Period			 smallint,
	@Comment		 varchar (256),
	@Explain		 varchar (256),
	@RedWord		 int,
	@Draft			 bit,
	@ETypeID1		 varchar (50),
	@EtypeID2		 varchar (50)	  
)
--@encode$--
AS
SET NOCOUNT ON

Insert Into LocalIndex (
	BillType,
	BillCode,
	BillDate,
	ETypeID,
	KTypeID,
	IfCheck,
	TotalQty,
	BID,
	BCode,
	Period,
	Comment,
	Explain,
	RedWord,
	Draft,
	ETypeID1,
	ETypeID2
			)
Values			(
	@BillType,
	@BillCode,
	@BillDate,
	@ETypeID,
	@KTypeID,
	@IfCheck,
	@TotalQty,
	@BID,
	@BCode,
	@Period,
	@Comment,
	@Explain,
	@RedWord,
	@Draft,
	@ETypeID1,
	@ETypeID2	 
			)
if @@rowcount =0  or @@error<>0
  RAISERROR('更新单据发生错误！',16,1)
else
 return SCOPE_IDENTITY();


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	Author:			 李海洋
	Create date: 2012-05-16 
	Description: 报损单明细插入(表值)
*/
CREATE PROCEDURE [GP_InsertLoseBillDT]
(
	@details TBType_LoseOverFlowBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO LoseBill (
	 BillNumberId		
	,PtypeId  			
	,Qty   					
	,Price   				
	,Total  				
	,Comment  			
	,IsUnit2 				
	--@Serial				
	,Serial					
	,InputCostPrice	
	,GoodsNumber		
	,ProduceDate		
	,ValidDate			
	,GoodsBTypeID		
	,GoodsCostPrice	
	,HandZeroCost		
	,STypeID				
	-- 9.0 新字段
	,UnitId							
	,NUnitId				
	,NQty						
	,UnitRate				
	,NUnitMsg				
	,MUnitId				
	,MQty						
	,MUnitRate			
	,MUnitMsg				
	,MPrice					
	,CargoId				
	,ItemId					
	,IsCombined		
	,ShowOrder	
	,KTypeID
	,ifWX
)
	SELECT 
		 BillNumberId		
	,PtypeId  			
	,dbo.F_RoundQty(Qty)   					
	,dbo.F_RoundPrice(Price)   				
	,dbo.F_RoundTotal(Total)  				
	,Comment  			
	,IsUnit2 				
	--@Serial				
	,Serial					
	,dbo.F_RoundPrice(InputCostPrice)	
	,GoodsNumber		
	,ProduceDate		
	,ValidDate			
	,GoodsBTypeID		
	,dbo.F_RoundPrice(GoodsCostPrice)	
	,HandZeroCost		
	,STypeID				
	-- 9.0 新字段
	,UnitId							
	,NUnitId				
	,dbo.F_RoundQty(NQty)						
	,dbo.F_RoundTranslateRate(UnitRate)				
	,NUnitMsg				
	,MUnitId				
	,dbo.F_RoundQty(MQty)						
	,dbo.F_RoundTranslateRate(MUnitRate)			
	,MUnitMsg				
	,dbo.F_RoundPrice(MPrice)					
	,CargoId				
	,ItemId					
	,IsCombined		
	,ShowOrder	
	,KTypeID
	,ifWX
	FROM @details

IF @@ROWCOUNT = 0
	RETURN -1
ELSE
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE    PROCEDURE GP_InsertMoneyBill
(@billnumberid  int,
 @atypeid       varchar(50),
 @total          NUMERIC(24, 10) ,
 @comment       varchar(255),
 @STypeID		varchar(50)
)
--@encode$--
as
SET NOCOUNT ON
insert into [moneybill]
           ([billnumberid],
            [atypeid],
            [total],
            [comment],
            STypeID)
values  (@billnumberid,
         @atypeid,
         dbo.F_RoundTotal(@total),
         @comment,
         @STypeID)
if @@rowcount=0 return 0 else return 1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[DBO].[GP_InsertMoneyBillDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[GP_InsertMoneyBillDT];
GO
/*
	作者：周华
	时间：2012-05-15 16:27:45.593
	描述：财务单据过据  多数单据通用明细写入的dt版表
	
	6-11 添加ntotal字段
*/

CREATE PROCEDURE GP_InsertMoneyBillDT
    (
      @BillNumberId			INT ,
      @STypeId				VARCHAR(50) ,
      @tb TbType_Money		READONLY
    )
--@encode$--	
AS
BEGIN
    INSERT  INTO [MoneyBill]
    ( BillNumberId ,
      AtypeId ,
      total ,
      Comment ,
      Stypeid ,
      NTotal ,
      DTypeId ,
      ETypeId ,
      ShowOrder,
      BrandarTypeId
    )
    SELECT  @BillNumberId ,
            ATypeId ,
            dbo.F_RoundTotal(Total) ,
            Comment ,
            @STypeId ,
            dbo.F_RoundTotal(NTotal) ,
            DTypeId ,
            ETypeId ,
            ShowOrder,
            ISNULL(BrandarTypeId,'')
    FROM    @tb;
END;
GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO




SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[DBO].[GP_InsertMoneyBillMulBrand]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[GP_InsertMoneyBillMulBrand];
GO
/*
	作者：颜熙
	时间：2018-01-30 
	描述：费用单导入品牌应收
*/

CREATE PROCEDURE GP_InsertMoneyBillMulBrand
    (
      @BillNumberId			INT 
    )
--@encode$--	
AS
BEGIN
	DECLARE @BTYPEID VARCHAR(50)=''
	SELECT  @BTYPEID=btypeid FROM BillIndex WHERE BillNumberId= @BillNumberId
    IF EXISTS ( SELECT  * FROM  dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue = 1 ) 
    AND EXISTS (SELECT TOP 1 1 FROM  BTYPE WHERE typeid=@BTYPEID AND IsUseBrandarType=1  )
    AND EXISTS(SELECT * FROM dbo.sysdata WHERE SubName = 'expensetoar' AND SubValue = 1)
    AND EXISTS(SELECT * FROM dbo.BillMulAccount WHERE BillNumberId = @BillNumberId)
	BEGIN
			INSERT INTO dbo.BillMulBrand
					( STypeID ,
					  BTypeID ,
					  BrandarTypeID ,
					  BillNumberId ,
					  BillType ,
					  Cid ,
					  Rate ,
					  TaxTotal ,
					  NTaxTotal ,
					  PreferenceMoney ,
					  NPreferenceMoney ,
					  TotalInMoney ,
					  NTotalInMoney ,
					  YSTotalInMoney ,
					  NYSTotalInMoney ,
					  TheOrderARTotal ,
					  NTheOrderARTotal ,
					  isIni
					)
			SELECT BI.Stypeid,BI.btypeid,S.BrandarTypeID,
			BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.total),SUM(S.NTotal),0,0,BI.totalinmoney,BI.NTotalInMoney,
			0,0,SUM(S.total)-BI.totalinmoney,SUM(S.NTotal) - BI.NTotalInMoney,0
			FROM dbo.MoneyBill S 
			INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
			WHERE BI.BillNumberId = @BillNumberId
			GROUP BY S.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,BI.totalinmoney,BI.NTotalInMoney  
	END 
END;
GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/*
-- 功能说明：	月结存
-- 作    者：	卢  春
-- 最后修改：	2003-007-27
-- last modify chen_qihua 2004-2-18 增加月结后更新损益临时表（tmpGain）
*/
CREATE PROCEDURE Gp_InsertMonthProc
(
	@chvMonthNo			varchar(50),	-- 本月名称
	@datStartDate		datetime,		-- 本月开始日期
	@datEndDate			datetime,		-- 本月截止日期
	@intPeriod			int,			-- 期号
	@chvComment			varchar(50),	-- 备注
	@STypeID			VARCHAR(MAX)=''	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @datUpStartDate			DATETIME,
		@chvSubValue			VARCHAR(50),
		@returnvalue			INT =0,
		@isuseacsystem			INT=0,
		@StypeIndependentOpen	INT,						--独立开账
		@BeginPeriod			INT,
		@BeginYear			    INT,
		@CurrPeriod				INT,
		@CurrYear				INT,
		@monthYear				INT		--当前年度

SELECT TOP 1 @monthYear = Year FROM dbo.MonthProc WHERE MonthNo = '本期' AND stypeid = @stypeid

SELECT @StypeIndependentOpen=SubValue FROM Sysdata WHERE SubName='StypeIndependentOpen'

DELETE FROM dbo.MonthProc WHERE STypeID IN(SELECT TypeID FROM SType WHERE sonnum>0)
--独立开账
IF @StypeIndependentOpen=1
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.SType_UserConfig WHERE StypeId=@STypeID AND Value=0)
		RETURN 2
	--启用期间
	SELECT @BeginPeriod=SFPeriod,@BeginYear=SFYear FROM dbo.SType_UserConfig WHERE StypeId=@STypeID
	SELECT TOP 1 @CurrPeriod=Period,@CurrYear=Year FROM dbo.MonthProc WHERE STypeID=@STypeID AND Year = @monthYear ORDER BY period DESC
	--没有月结记录,取启用期间
	IF @@ROWCOUNT=0
	BEGIN
		SET @chvMonthNo='本期'
		SELECT @datStartDate=FBegin,@datEndDate=FEnd FROM dbo.Ac_Period WHERE FPeriod=@BeginPeriod AND FYear=@BeginYear
	END
	ELSE
	BEGIN
		--年度、期间小于启用期间
		IF @CurrYear<@BeginYear OR(@CurrYear=@BeginYear AND @CurrPeriod<@BeginPeriod)
		BEGIN
			SET @CurrYear=@BeginYear
			SET @CurrPeriod=@BeginPeriod
			SELECT @datStartDate=FBegin,@datEndDate=FEnd FROM dbo.Ac_Period WHERE FPeriod=@BeginPeriod AND FYear=@BeginYear
		END
		ELSE
		BEGIN
			SELECT @datStartDate=FBegin,@datEndDate=FEnd FROM dbo.Ac_Period WHERE FPeriod=@CurrPeriod AND FYear=@CurrYear
		END
	END
	SET @intPeriod=@CurrPeriod
END
ELSE
BEGIN
	SELECT @intPeriod=CAST(Period AS INT) FROM dbo.MonthProc WHERE STypeID=@STypeID AND MonthNo='本期'
	SET @CurrYear=Year(@datStartDate)
END

-- 若存在相同月结名称不允许月结
IF EXISTS(SELECT * FROM MonthProc WHERE MonthNo = @chvMonthNo AND STypeID=@STypeID) 
	RETURN -2

IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE Stypeid=@STypeID AND draft=1 AND BillType IN (212,213,214) AND BillDate<=@datEndDate AND BillDate>=@datStartDate)
BEGIN 
	RAISERROR('当前业务期间内尚有固定资产业务单据未过账',16,1)
	RETURN
END

IF EXISTS(SELECT 1 FROM dbo.Ac_AssetsCards WHERE STypeId=@STypeID AND inaccountdate>=@datStartDate AND inaccountdate<=@datEndDate AND AssetsState IN (1,2))
BEGIN
	RAISERROR('有入账日期在当前业务期内的卡片未入账,不能月结',16,1)
	RETURN
END

SELECT @isuseacsystem=subvalue FROM sysdata WHERE SubName='isuseacsystem'

--新增分支机构月结
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.MonthProc WHERE STypeID=@STypeID)
BEGIN
	DECLARE @MinSTypeID VARCHAR(100);
	SELECT TOP 1 @MinSTypeID=STypeID FROM MonthProc ORDER BY STypeID DESC
	INSERT INTO dbo.MonthProc
	        ( STypeID ,
	          MonthNo ,
	          StartDate ,
	          EndDate ,
	          period ,
	          Year ,
	          comment
	        )
	SELECT	  @STypeID,
	          MonthNo ,
	          CONVERT(VARCHAR(10),StartDate,120) ,
	          CONVERT(VARCHAR(10),EndDate,120) ,
	          period ,
	          Year ,
	          comment
	FROM MonthProc WHERE STypeID=@MinSTypeID
END

IF @chvMonthNo = '本期'
BEGIN
 	INSERT INTO MonthProc (
		MonthNo,
		StartDate,
		EndDate,
		Period,
		Comment,
		STypeID,
		Year
	)
	VALUES (
		@chvMonthNo,
		CONVERT(VARCHAR(10),@datStartDate,120),
		CONVERT(VARCHAR(10),@datEndDate,120),
		@intPeriod,
		@chvComment,
		@STypeID,
		@CurrYear
	)
END
ELSE
BEGIN
	--非独立开账
	IF @StypeIndependentOpen=0
	BEGIN
		-- 获取本期的开始日期
		SELECT	@datUpStartDate = StartDate
		FROM	MonthProc
		WHERE	Monthno = '本期' AND STypeID=@STypeID
		
		IF @datUpStartDate IS NULL
		BEGIN
			SELECT @datUpStartDate=MIN(StartDate) FROM dbo.MonthProc WHERE	Monthno = '本期'
		END
		
		SET @datStartDate = @datUpStartDate
	END
	
	-- 插入本次月结的新记录
	INSERT INTO MonthProc (
		MonthNo,
		StartDate,
		EndDate,
		Period,
		Comment,
		STypeID,
		Year
	)
	VALUES (
		@chvMonthNo,
		CONVERT(VARCHAR(10),@datStartDate,120),
		CONVERT(VARCHAR(10),@datEndDate,120),
		@intPeriod,
		@chvComment,
		@STypeID,
		@CurrYear
	)

	-- 操作成功
	IF @@ROWCOUNT <> 0
	BEGIN
		/* 更新历史记录 - Start */		
		DECLARE @AR_ID VARCHAR(50),		
				@AP_ID VARCHAR(50)
			
		SELECT @AR_ID=nid FROM dbo.Ac_Items WHERE UserCode='987'				--『应收款合计』
		SELECT @AP_ID=nid FROM dbo.Ac_Items WHERE UserCode='2121'				--『应付账款合计』
							
		INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,nTotal,BqTotal,nBqTotal,CID,Year)	
		SELECT	@intPeriod,
				b.AtypeId,
				B.STypeId,
				ISNULL(SUM(b.Total),0),
				ISNULL(SUM(b.Ntotal),0),
				0,
				0,
				b.CID,
				@CurrYear					
		FROM	ListTable b
		INNER JOIN dbo.Ac_Items ai ON ai.nid=b.AtypeId
		WHERE	b.BillDate <= @datEndDate							
				AND b.Audited = 1
				AND STypeID=@STypeID
		GROUP BY B.STypeID,b.AtypeId,b.CID
				
		INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,nTotal,BqTotal,nBqTotal,CID,Year)
		SELECT	@intPeriod,
				c.ATypeID,
				C.STypeID,
				ISNULL(SUM(c.Total00),0),
				ISNULL(SUM(c.Ntotal00),0),
				0,
				0,
				c.CID,
				@CurrYear
		FROM	AType_Total c	
		INNER JOIN dbo.Ac_Items ai ON ai.nid=c.AtypeId		
		WHERE C.STypeID=@STypeID
		GROUP BY C.STypeID,c.ATypeID,c.CID
				
		--本期数据
		INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,nTotal,BqTotal,nBqTotal,CID,Year)
		SELECT	@intPeriod,
				b.ATypeID,
				b.STypeID,
				0,
				0,
				ISNULL(SUM(b.Total),0),
				ISNULL(SUM(b.Ntotal),0),
				b.CID,
				@CurrYear
		FROM	ListTable b
		INNER JOIN dbo.Ac_Items ai ON ai.nid=b.AtypeId
		WHERE	b.BillDate >= @datStartDate
				AND b.BillDate <= @datEndDate						
				AND b.Audited = 1
				AND STypeID=@StypeID
		GROUP BY B.STypeID,b.AtypeId,b.CID									
		
		-- 删除都为0的数据
		DELETE FROM MonthATypeHistory WHERE Total = 0 AND BqTotal = 0 AND period = @intPeriod

		--保存固定资产卡片余额		
		INSERT INTO Ac_AssetsCards_History
		(		AssertsCardId,TypeId,Parid,UserCode,FullName,STypeId,AssertATypeId,DepATypeId,DisATypeId,DevalueATypeId,CategoryId,LocationId,
				ConditionId,Size,DTypeid,InAccountDate,BusinessTypeId,Total,Cid,F_Total,Rate,DepTotal,DevalueReady,NetValue,NetSalvage,NetSalvageRate,
				DepreciationMean,DurYear,durmonth,DepreciationMonth,Comment,AssetsState,BusinessDate,OperationDate,ETypeId,BillId,AuditType
		)
		SELECT AssertsCardId,TypeId,Parid,UserCode,FullName,STypeId,AssertATypeId,DepATypeId,DisATypeId,DevalueATypeId,CategoryId,LocationId,
			   ConditionId,Size,DTypeid,InAccountDate,BusinessTypeId,Total,Cid,F_Total,Rate,DepTotal,DevalueReady,NetValue,NetSalvage,NetSalvageRate,
			   DepreciationMean,DurYear,durmonth,DepreciationMonth,Comment,ah.AssetsState,@datEndDate,GETDATE(),'00001',0,-4
		FROM  Ac_AssetsCards_History ah INNER JOIN 
		(
			SELECT RANK() OVER 
			(PARTITION BY AssertsCardId ORDER BY BusinessDate DESC,id DESC)sorid,
			Id
			FROM Ac_AssetsCards_History
			WHERE BusinessDate<=@datEndDate  AND AuditType NOT IN(-3,-4)
			AND STypeId=@STypeID
		) a ON a.id=ah.Id
		WHERE a.sorid=1 AND ISNULL(ah.BillType,0)<>213  
		
		--13 期间
		DECLARE @IsThirtyPeriod INT=0
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE IsNature=0 AND IsDynamic=0 AND NatureCount=13)
		BEGIN
			SET @IsThirtyPeriod=1
		END
		
		SET @intPeriod = @intPeriod + 1
		IF @StypeIndependentOpen=1 AND @intPeriod>CASE WHEN @IsThirtyPeriod=1 THEN 13 ELSE 12 END
		BEGIN
			SET @intPeriod=1
			--创建下一年度期间表
			IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FYear=@CurrYear+1)
			BEGIN
				INSERT INTO dbo.Ac_Period
				        ( FYear ,
				          FMonth ,
				          IsNature ,
				          NatureCount ,
				          FPeriod ,
				          FBegin ,
				          FEnd ,
				          Deleted ,
				          IsCurrent ,
				          IsDynamic
				        )
				SELECT	  FYear+1 ,
				          FMonth ,
				          IsNature ,
				          NatureCount ,
				          FPeriod ,
				          DATEADD(Year,1,FBegin) ,
				          DATEADD(Year,1,FEnd) ,
				          Deleted ,
				          IsCurrent ,
				          IsDynamic
				FROM dbo.Ac_Period WHERE FYear=@CurrYear
			END
		END
		
		UPDATE	MonthProc
		SET		StartDate = CONVERT(VARCHAR(10),DATEADD(DAY,1,@datEndDate),120),
			    Year = CASE WHEN @CurrPeriod = 12 THEN @CurrYear + 1 ELSE @CurrYear END,
			    EndDate=NULL,
				Period = @intPeriod
		WHERE	Monthno = '本期' 
				AND STypeID=@STypeID
		
		-- 在数据表 SysData 中，更新最新期号
		UPDATE sysdata set subValue =(SELECT MAX(Period)FROM dbo.MonthProc WHERE MonthNo='本期') where subName='period'
	END
END

-- 返回处理值
IF @@ROWCOUNT = 0
	RETURN -1	-- 操作不成功
ELSE
	RETURN 0




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	Author:			 李海洋
	Create date: 2012-05-12 
	Description: 同价调拨单明细表(表值参数)GP_InsertMoveBillDT
*/
CREATE PROCEDURE [Gp_InsertMoveBillDT]
(
	@details TBType_MoveBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO [dbo].[MoveBill] 
(
	 BillNumberId
	,PtypeId
	,Qty
	,Price
	,Total
	,Comment	
	,isUnit2
	--	@Serial
	,Serial
	,InputCostPrice
	,GoodsNumber
	,ProduceDate
	,ValidDate
	,GoodsBTypeID
	,GoodsCostPrice
	,HandZeroCost
	,STypeID
	,KTypeId
	,KTypeId2
	-- 9.0新字段
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MPrice
	,Incargoid
	,Outcargoid
	,ItemId
	,IsCombined
	,ShowOrder
	,AllotID
 )
	SELECT
		 BillNumberId
		,PtypeId
		,dbo.F_RoundQty(Qty)
		,dbo.F_RoundPrice(Price)
		,dbo.F_RoundTotal(Total)
		,Comment
		,IsUnit2
		--	@Serial
		,Serial
		,dbo.F_RoundPrice(InputCostPrice)
		,GoodsNumber
		,ProduceDate
		,ValidDate
		,GoodsBTypeID
		,dbo.F_RoundPrice(GoodsCostPrice)
		,HandZeroCost
		,STypeID
		,KTypeId
		,KTypeId2
		-- 9.0新字段
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MPrice)
		,Incargoid
		,Outcargoid
		,ItemId
		,IsCombined
		,ShowOrder
		,AllotID
	FROM @details

IF @@ROWCOUNT = 0 
	RETURN -1 
ELSE
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertMoveBjBillDT]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertMoveBjBillDT]
GO

/*
	Author:			 李海洋
	Create date: 2012-05-15 
	Description: 添加变价调拨单明细(表值参数)
*/
CREATE PROCEDURE [Gp_InsertMoveBjBillDT]
    (
      @details TBType_MoveBjBill READONLY
    )
--@encode$--
AS 
    SET NOCOUNT ON
    INSERT  INTO [dbo].[MoveBjBill]
            ( BillNumberId ,
              PtypeId ,
              Qty ,
              Price ,
              Total ,
              Comment ,
              IsUnit2 ,
              Serial ,
              InputCostPrice ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              GoodsBTypeID ,
              GoodsCostPrice ,
              HandZeroCost ,
              STypeID ,
              KTypeId ,
              KTypeId2	
	-- 9.0 新字段
              ,
              UnitId ,
              NUnitId ,
              NQty ,
              UnitRate ,
              NUnitMsg ,
              MUnitId ,
              MQty ,
              MUnitRate ,
              MUnitMsg ,
              MPrice ,
              Incargoid ,
              Outcargoid ,
              ItemId ,
              IsCombined,
              ShowOrder,
              AllotID 		
            )
            SELECT  BillNumberId ,
                    PtypeId ,
                    dbo.F_RoundQty(Qty) ,
                    dbo.F_RoundPrice(Price) ,
                    dbo.F_RoundTotal(Total) ,
                    Comment ,
                    IsUnit2 ,
                    Serial ,
                    dbo.F_RoundPrice(InputCostPrice) ,
                    GoodsNumber ,
                    ProduceDate ,
                    ValidDate ,
                    GoodsBTypeID ,
                    dbo.F_RoundPrice(GoodsCostPrice) ,
                    HandZeroCost ,
                    STypeID ,
                    KTypeId ,
                    KTypeId2		
	-- 9.0 新字段
                    ,
                    UnitId ,
                    NUnitId ,
                    dbo.F_RoundQty(NQty) ,
                    dbo.F_RoundTranslateRate(UnitRate) ,
                    NUnitMsg ,
                    MUnitId ,
                    dbo.F_RoundQty(MQty) ,
                    dbo.F_RoundTranslateRate(MUnitRate) ,
                    MUnitMsg ,
                    dbo.F_RoundPrice(MPrice) ,
                    Incargoid ,
                    Outcargoid ,
                    ItemId ,
                    IsCombined,
                    ShowOrder,
                    AllotID 
            FROM    @details

    IF @@ROWCOUNT = 0 
        RETURN -1 
    ELSE 
        RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE   PROCEDURE [Gp_InsertMoveMoneyBill]
(
 @BillNumberId  [numeric](10,0),
 @Comment  [varchar](256),
 @AtypeId  [varchar](50),
 @Total    NUMERIC(24, 10) ,
 @STypeID [VARCHAR](50)
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[MoveMoneyBill] 
  ( [BillNumberId],
  [Comment],
  [AtypeId],
  [total],
  [STypeID]) 
 
VALUES 
 ( @BillNumberId,
  @Comment,
  @AtypeId,
  dbo.F_RoundTotal(@total),
  @STypeID)
if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[Gp_InsertMoveMoneyBillDT]') AND OBJECTPROPERTY(ID, N'IsProcedure') = 1)
	DROP PROCEDURE [DBO].[Gp_InsertMoveMoneyBillDT]
GO
/*
	作者：周华
	时间：2012-05-15 16:27:45.593
	描述：财务单据过据  多数单据通用明细写入的dt版表
*/

CREATE PROCEDURE Gp_InsertMoveMoneyBillDT
(
	@BillNumberId INT
	,@STypeId VARCHAR(50)
	,@tb TbType_MoveMoney READONLY
)
--@encode$--	
AS
BEGIN
	INSERT INTO [MoveMoneyBill](
		BillNumberId
		,ATypeId
		,Total
		,NTotal
		,Comment
		,STypeId
		,ShowOrder
	) SELECT @BillNumberId,ATypeId,dbo.F_RoundTotal(Total),dbo.F_RoundTotal(NTotal),Comment,@STypeId,ShowOrder FROM @tb;
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		多账户保存
-- 最后修改：		毛欣蓉
-- 修改时间：		2011-05-30
-- ========================================================================
CREATE    PROCEDURE Gp_InsertMultAtype
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 
	@atypeid			varchar(50),
	@comment			varchar(500),
	@Total				 NUMERIC(24, 10) ,
	@vipcardid			INT,
	@NTotalMoney				 NUMERIC(24, 10) ,
	@tradeno VARCHAR(200),--交易号
	@paytype int,--支付方式 0-无 1-微信 2-支付宝
	@billtype INT,--单据类型
	@yhType   INT =-1,
	@CouponCode VARCHAR(5000)='',
	@viptotal NUMERIC(24, 10) =0
)
--@encode$--
AS

	SET NOCOUNT ON
	-- 写入数据表
	INSERT INTO BillMulAccount
	(
		BillNumberID,
		atypeid,
		total,
		comment,
		vipcardid,
		NTotalMoney,
		TradeNo,
		paytype,
		billtype,
		yhType,
		CouponCode,
		viptotal
	)
	VALUES
	(
		@BillNumberID,
		@atypeid,
		dbo.F_RoundTotal(@total),
		ISNULL(@comment,''),
		isnull(@vipcardid,-1),
		dbo.F_RoundTotal(@NTotalMoney),
		@tradeno,
		@paytype,
		@billtype,
		@yhType,
		ISNULL(@CouponCode,''),
		dbo.F_RoundTotal(@viptotal)
	)

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：多账面保存
-- 最后修改：谢吉康
-- 修改时间：2019-12-25
-- ========================================================================
CREATE    PROCEDURE Gp_InsertMultAtypeAutoDraft
(
	@BillGuid			VARCHAR(100),
	@BillNumberID		numeric(10,0),	-- 单据 ID 
	@atypeid			varchar(50),
	@comment			varchar(500),
	@Total				 NUMERIC(24, 10) ,
	@vipcardid			INT,
	@NTotalMoney				 NUMERIC(24, 10) ,
	@tradeno VARCHAR(200),--交易号
	@paytype int,--支付方式 0-无 1-微信 2-支付宝
	@billtype INT,--单据类型
	@yhType   INT =-1,
	@CouponCode VARCHAR(5000)='',
	@viptotal NUMERIC(24, 10) =0
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO BillMulAccountAutoDraft
(
	BillGuid,
	BillNumberID,
	atypeid,
	total,
	comment,
	vipcardid,
	NTotalMoney,
	TradeNo,
	paytype,
	billtype,
	yhType,
	CouponCode,
	viptotal
)
VALUES
(
	@BillGuid,
	@BillNumberID,
	@atypeid,
	dbo.F_RoundTotal(@total),
	ISNULL(@comment,''),
	isnull(@vipcardid,-1),
	dbo.F_RoundTotal(@NTotalMoney),
	@tradeno,
	@paytype,
	@billtype,
	@yhType,
	ISNULL(@CouponCode,''),
	dbo.F_RoundTotal(@viptotal)
)

-- 操作返回值
IF @@ROWCOUNT = 0
	RETURN -1	-- 失败
ELSE
	RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		品牌多账户保存
-- 最后修改：		
-- 修改时间：		2011-05-30
-- ========================================================================
CREATE    PROCEDURE Gp_InsertMultBrandar
(
	@STypeID			VARCHAR(50),
	@BTypeID			VARCHAR(50),
	@BrandarTypeID		VARCHAR(50),
	@BillNumberId		NUMERIC(24,10),
	@BillType			INT, 
	@CID				NUMERIC(24,10),
	@Rate				NUMERIC(24,10),
	@TaxTotal			NUMERIC(24,10),
	@NTaxTotal			NUMERIC(24,10),
	@PreferenceMoney	NUMERIC(24,10),
	@NPreferenceMoney	NUMERIC(24,10),
	@TotalInMoney		NUMERIC(24,10),
	@NTotalInMoney		NUMERIC(24,10),
	@TheOrderARTotal	NUMERIC(24,10),
	@NTheOrderARTotal	NUMERIC(24,10),
	@YSTotalInMoney		NUMERIC(24,10),
	@NYSTotalInMoney	NUMERIC(24,10),
	@isIni				INT 

)
--@encode$--
AS

	SET NOCOUNT ON
	-- 写入数据表
	INSERT INTO dbo.BillMulBrand
	        (	STypeID,
				BTypeID,
				BrandarTypeID,
				BillNumberId,
				BillType,	
				CID,
				Rate,
				TaxTotal,
				NTaxTotal,
				PreferenceMoney,
				NPreferenceMoney,
				TotalInMoney,
				NTotalInMoney,
				TheOrderARTotal,
				NTheOrderARTotal,
				YSTotalInMoney,
				NYSTotalInMoney,
				isIni

	        )
	VALUES  (	@STypeID			,
				@BTypeID			,
				@BrandarTypeID		,
				@BillNumberId		,
				@BillType			, 
				@CID				,
				@Rate				,
				dbo.F_RoundTotal(@TaxTotal)			,
				dbo.F_RoundTotal(@NTaxTotal	)		,
				dbo.F_RoundTotal(@PreferenceMoney)	,
				dbo.F_RoundTotal(@NPreferenceMoney)	,
				dbo.F_RoundTotal(@TotalInMoney	)	,
				dbo.F_RoundTotal(@NTotalInMoney	)	,
				dbo.F_RoundTotal(@TheOrderARTotal)	,
				dbo.F_RoundTotal(@NTheOrderARTotal)	,
				dbo.F_RoundTotal(@YSTotalInMoney)	,
				dbo.F_RoundTotal(@NYSTotalInMoney)	,
				@isIni				 
	        )
	
	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：调入品牌收款数据
-- 作    者：谢吉康
-- 修改时间：2019-12-25
-- ========================================================================
CREATE    PROCEDURE Gp_InsertMultBrandarAutoDraft
(
	@BillGuid			VARCHAR(100),
	@STypeID			VARCHAR(50),
	@BTypeID			VARCHAR(50),
	@BrandarTypeID		VARCHAR(50),
	@BillNumberId		NUMERIC(24,10),
	@BillType			INT, 
	@CID				NUMERIC(24,10),
	@Rate				NUMERIC(24,10),
	@TaxTotal			NUMERIC(24,10),
	@NTaxTotal			NUMERIC(24,10),
	@PreferenceMoney	NUMERIC(24,10),
	@NPreferenceMoney	NUMERIC(24,10),
	@TotalInMoney		NUMERIC(24,10),
	@NTotalInMoney		NUMERIC(24,10),
	@TheOrderARTotal	NUMERIC(24,10),
	@NTheOrderARTotal	NUMERIC(24,10),
	@YSTotalInMoney		NUMERIC(24,10),
	@NYSTotalInMoney	NUMERIC(24,10),
	@isIni				INT 

)
--@encode$--
AS

SET NOCOUNT ON
-- 写入数据表
INSERT INTO dbo.BillMulBrandAutoDraft
(	
	BillGuid,
	STypeID,
	BTypeID,
	BrandarTypeID,
	BillNumberId,
	BillType,	
	CID,
	Rate,
	TaxTotal,
	NTaxTotal,
	PreferenceMoney,
	NPreferenceMoney,
	TotalInMoney,
	NTotalInMoney,
	TheOrderARTotal,
	NTheOrderARTotal,
	YSTotalInMoney,
	NYSTotalInMoney,
	isIni
)VALUES(
	@BillGuid,	
	@STypeID			,
	@BTypeID			,
	@BrandarTypeID		,
	@BillNumberId		,
	@BillType			, 
	@CID				,
	@Rate				,
	dbo.F_RoundTotal(@TaxTotal)			,
	dbo.F_RoundTotal(@NTaxTotal	)		,
	dbo.F_RoundTotal(@PreferenceMoney)	,
	dbo.F_RoundTotal(@NPreferenceMoney)	,
	dbo.F_RoundTotal(@TotalInMoney	)	,
	dbo.F_RoundTotal(@NTotalInMoney	)	,
	dbo.F_RoundTotal(@TheOrderARTotal)	,
	dbo.F_RoundTotal(@NTheOrderARTotal)	,
	dbo.F_RoundTotal(@YSTotalInMoney)	,
	dbo.F_RoundTotal(@NYSTotalInMoney)	,
	@isIni				 
)

-- 操作返回值
IF @@ROWCOUNT = 0
	RETURN -1	-- 失败
ELSE
	RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertNewTCDataIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertNewTCDataIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE  PROCEDURE [Gp_InsertNewTCDataIndex]
    (
	  @BillCode [varchar](200) ,  
      @BillDate [datetime] ,
      @CommissionStart	DATETIME =NULL,			 --提成开始
	  @CommissionEnd	DATETIME =NULL,			 --提成结束
	  @CommissionSchemeID	NUMERIC(18,0),
      @Checke VARCHAR(50) ,				--制单人
	  --@Checker					VARCHAR(50) = '',	--审核人
	  --@CheckerTime				DATETIME ,		    --审核时间
	  @Explain					VARCHAR(256)='' ,	--说明
	  @Comment					VARCHAR(256)='' ,	--摘要
	  @IsAuto					INT	 ,						--自动生成  0=手动 1=自动
	  @BillState				INT ,						--单据状态  1=未审核  2=审核
	  @stypeid					VARCHAR(50),	
	  @ifcheck					CHAR(1),
	  @commissiontotal	 NUMERIC(24, 10) ,
	  @total  NUMERIC(24, 10) ,
	  @qty  NUMERIC(24, 10) 
	  )
--@encode$--
AS 
    SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********
    DECLARE @N INT ,
        @intVersion INT

-- 判断版本号，是否试用版
    SELECT  @N = CAST(SubValue AS INT)
    FROM    SysData1
    WHERE   SubNo = 2	-- 版本号

IF @N IS NULL RETURN -1

    DECLARE @intBit INT ,
        @intMask INT
    SELECT  @intBit = @N & 15
    SELECT  @intMask = POWER(2, @intBit) ^ POWER(2, @intBit + 1) ^ POWER(2,
                                                              @intBit + 2)
            ^ POWER(2, @intBit + 3) ^ POWER(2, @intBit + 4) ^ POWER(2,
                                                              @intBit + 5)
    SELECT  @intVersion = ( @intMask & @N ) / POWER(2, @intBit)
-- ********	判断是否试用版 - END	********

    DECLARE @Re INT ,
        @Flag INT
    EXEC @Re= Gp_Validate 2, @Flag OUTPUT
    IF @Re <> 0 
        RETURN -3 --检查程序版本错误

    IF @intVersion NOT IN ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                            15 ) 
        BEGIN
	--RAISERROR('校验错误 ！',16,1) 
            RETURN -3 --检查程序版本错误
        END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM BillIndex
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版最多录200条单据 ！',16,1) 
		RETURN -1
	END
END  

DECLARE @BeginDate DATETIME ,
        @szItem VARCHAR(30) ,
        @szVchCode VARCHAR(30),
        @szPeriod SMALLINT
    EXEC Gp_GetSubValue 'period', @STypeID, @szPeriod OUT
    SELECT TOP 1
            @BeginDate = startdate
    FROM    monthproc
    WHERE   period = @szPeriod

IF @BillDate < @BeginDate
                BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
                    RETURN -2
                END

IF NOT EXISTS ( SELECT TOP 1
                                            1
                                    FROM    AuditingFlowSet
                                    WHERE   BillType = 311
                                            AND IfUse = 1
                                            AND LEFT(AuditingReason, 1) <> 1 )	--检查单据是否有审核流程
                        BEGIN
                            DECLARE @CurDate DATETIME
                            DECLARE @IsOrNotPassOneDay BIT
                            SELECT  @CurDate = GETDATE()
                            SELECT TOP 1
                                    @IsOrNotPassOneDay = value
                            FROM    UserConfig
                            WHERE   ConfigName = 'PassOneDay'
                            IF ( CONVERT(DATETIME, @BillDate) <> CONVERT(DATETIME, CONVERT(VARCHAR, YEAR(@CurDate))
                                 + '-' + CONVERT(VARCHAR, MONTH(@CurDate))
                                 + '-' + CONVERT(VARCHAR, DAY(@CurDate))) )
                                AND ( @IsOrNotPassOneDay = 1 ) 
                                BEGIN 
				--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
                                    RETURN -4
                                END
                        END
		--有审核流程单据，第一次录单时需要和当前日期一致
                    ELSE 
                        BEGIN
                            SELECT  @CurDate = GETDATE()
                            SELECT TOP 1
                                    @IsOrNotPassOneDay = value
                            FROM    UserConfig
                            WHERE   ConfigName = 'PassOneDay'
                            IF ( CONVERT(DATETIME, @BillDate) <> CONVERT(DATETIME, CONVERT(VARCHAR, YEAR(@CurDate))
                                 + '-' + CONVERT(VARCHAR, MONTH(@CurDate))
                                 + '-' + CONVERT(VARCHAR, DAY(@CurDate))) )
                                AND ( @IsOrNotPassOneDay = 1 ) 
                                BEGIN 
				--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
                                    RETURN -4
                                END
                        END



    INSERT  INTO [dbo].CommissionBillNew
            ( 
      BillCode ,  
      BillDate ,
      CommissionStart	,	
	  CommissionEnd	,			
	  CommissionSchemeID	,
      Checke  ,
	  --Checker	,
	  CheckeTime,
	  --CheckerTime ,
	  Explain ,	
	  Comment ,	
	  IsAuto ,		
	  BillState,
	  stypeid,
      ifcheck,
      CommissionTotal,
      total,
      qty,
      draft,
      billtype
      )
    VALUES  ( 
      @BillCode ,  
      @BillDate ,
      @CommissionStart	,			
	  @CommissionEnd	,			 
	  @CommissionSchemeID	,
      @Checke  ,			
	  --@Checker	,	
	  GETDATE(),		
	  --@CheckerTime ,		   
	  @Explain ,	
	  @Comment ,	
	  @IsAuto ,						
	  @BillState,
	  @stypeid,
	  @ifcheck,
	  dbo.F_RoundTotal(@commissiontotal),
	  dbo.F_RoundTotal(@total),
	  dbo.F_RoundQty(@qty),
	  1,
	  311
            )

    DECLARE @intReturn BIGINT

    SELECT  @intReturn = SCOPE_IDENTITY();

    RETURN @intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertNewTCDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertNewTCDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE GP_InsertNewTCDT
	@tb TbType_NewTC READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	INSERT INTO CommissionBillNewDetail(
		BillNumberId,			
		EtypeID,	
		DtypeID,				
		Qty,						
		Total,					
		CommissionTotal,			
		Comment,
		ShowOrder
	) SELECT 
		BillNumberId,			
		EtypeID,
		DtypeID,					
		dbo.F_RoundQty(Qty),						
		dbo.F_RoundTotal(Total),					
		dbo.F_RoundTotal(CommissionTotal),			
		Comment,
		ShowOrder
	FROM @tb
	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertNewTCIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertNewTCIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE  PROCEDURE [Gp_InsertNewTCIndex]
    (
@BillCode				VARCHAR(200) ,   --单据编号
@FullName				VARCHAR(200) ,   --单据名称
@BillDate				DATETIME=null ,		 --单据日期 
@RuleStart				DATETIME=null ,		 --规则开始
@RuleEnd					DATETIME=null ,		 --规则结束
@CommissionStandard		INT ,			 --提成基准  0=折后金额 1=价税合计 2=销售数量 3=销售
@IsUseEtypeCommission	INT ,			 --是否使用职员提成比例 1=勾选
@SalesFlag	INT ,			 --是否使用促销商品销售额不参与提成 1=勾选
@BelowCostFlag 	INT ,			 --是否使用低于成本销售额不参与提成 1=勾选
@ECommissionType			INT ,			 --提成人类型  0=业务员   1=上级参与提成
@CommissionStyle			INT ,			 --提成方式    0=单一提成 1=区间提成
@Checke					VARCHAR(50) ,				--制单人
@Comment					VARCHAR(256),	--摘要
@BillState				INT ,						--单据状态  1=未审核  2=审核  3=禁用
@UseState				INT ,			--使用状态  1=未引用  2=引用  3=部分完成
@IsStop					INT ,			--是否禁用  0=正常  1/2当禁用时写入单据
@Checker				VARCHAR(50) ,	--审核人
@CheckerTime			DATETIME 		 --审核时间
	  )
--@encode$--
AS 
    SET NOCOUNT ON

	
IF @CheckerTime = ''
BEGIN
	SET @CheckerTime = NULL
END

    INSERT  INTO [dbo].CommissionRule
            ( 
BillCode,				
FullName,				
BillDate,				
RuleStart,				
RuleEnd	,				
CommissionStandard	,	
IsUseEtypeCommission,	
SalesFlag,
BelowCostFlag,
ECommissionType		,	
CommissionStyle		,	
Checke				,	
CheckeTime			,	
Comment				,	
BillState			,	
UseState			,	
IsStop				,
Checker,
CheckerTime

            )
    VALUES  ( 
@BillCode,				
@FullName,				
@BillDate,				
@RuleStart,				
@RuleEnd,				
@CommissionStandard		,
@IsUseEtypeCommission	,
@SalesFlag,
@BelowCostFlag,
@ECommissionType		,
@CommissionStyle		,
@Checke					,
GETDATE()				,
@Comment				,
@BillState				,
@UseState				,
@IsStop					,
@Checker				,
@CheckerTime
      
            )

    DECLARE @intReturn BIGINT

    SELECT  @intReturn = SCOPE_IDENTITY();

    RETURN @intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertOM_LoginUsers]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_InsertOM_LoginUsers]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：鲁大林	
	日期：2012-4-16
	描述：OM系统操作员插入
*/
CREATE PROCEDURE Gp_InsertOM_LoginUsers
(
	@btypeid VARCHAR(50)=NULL,			--往来单位
	@usercode VARCHAR(50)=NULL,			--操作员账号
	@username VARCHAR(50)=NULL,			--姓名
	@date VARCHAR(50)=NULL,				--注册时间
	@level INT,						--等级
	@telephone VARCHAR(50)=NULL,		--联系座机
	@qq VARCHAR(50)=NULL,				--QQ
	@email VARCHAR(50)=NULL,			--电子邮件
	@mobilephone VARCHAR(50)=NULL,		--联系手机
	@lim VARCHAR(5000)=NULL,			--权限
	@password VARCHAR(10)=NULL			--密码
)
--@encode$--
AS
-----------------------------------判断是否存在当前的用户(如果存在，返回-1)------------------
IF EXISTS(SELECT * FROM OM_LoginUsers WHERE UserName=@username)
BEGIN
	RETURN -1			
END
-----------------------------------判断账号是否重复(如果存在，返回-2)--------------------------------------------
IF EXISTS(SELECT * FROM OM_LoginUsers WHERE UserCode=@usercode)
BEGIN	
	RETURN -2
END
SET NOCOUNT ON
--执行的插入操作
BEGIN
	INSERT INTO OM_LoginUsers
	(
		[BtypeID],
		[UserCode],
		[UserName],
		[Date],
		[Level],
		[TelePhone],
		[QQ],
		[Email],
		[MobilePhone],
		[Lim],
		[Password]
	)
	VALUES
	(
		@btypeid,
		@usercode,
		@username,
		@date,
		@level,
		@telephone,
		@qq,
		@email,
		@mobilephone,
		@lim,
		@password
	)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇			
	日期：2012-04-17
	描述：Om商品类型的增删改
*/
CREATE  PROCEDURE [dbo].[GP_InsertOm_PytpeClass]
(
    @Parid   [varchar](50),
    @DbName         [varchar](30),
    @UserCode  [varchar](256),
    @FullName  [varchar](256),
    @Remark VARCHAR(500),
    @controltype VARCHAR(50),
    @typeid VARCHAR(100)
)
AS
SET NOCOUNT ON
declare @nReturntype int,
        @EtypeId_1 [varchar](50),
        @nSoncount int,
        @nSonnum int,
        @leveal smallint

declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from OM_PtypeClass where typeid=@parid)
DECLARE @count INT
set @count=(SELECT Sonnum FROM OM_PtypeClass WHERE typeid=@typeid)
-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1
begin
	RAISERROR('商品类型的分类不能超过10层',16,1)return--return -1
end
if @nReturntype=-2 
begin
	RAISERROR('无法添加基本信息',16,1)return--return -2
end
IF(@controltype='add')--添加类型
BEGIN
if exists(select * from OM_PtypeClass where typeId=@EtypeId_1 or usercode=@usercode  OR fullname=@fullname )
begin
	RAISERROR('【%s】已经存在，商品类型的名称或编号不能相同',16,1,@FullName)return--return -3
end
IF EXISTS(SELECT TOP 1 1 from Om_ptype WHERE PTYPECLASS_ID=@typeid)
begin
	RAISERROR('该商品类型下已有商品,不能分类',16,1)return
END
begin tran insertproc
select @leveal=leveal from OM_PtypeClass where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO OM_PtypeClass
        (TypeID,
         UserCode,
         FullName,
         ParID,
         Leveal,
         Sonnum,
         Soncount,
         Remark)
VALUES
        (@EtypeId_1,
         @UserCode,
         @FullName,
         @Parid,
         @leveal,
         0, 
         0, 
         @Remark 
         )
IF @@rowcount=0 
BEGIN
   ROLLBACK TRAN insertproc 
   RETURN -1
   END
   ELSE 
BEGIN
UPDATE  dbo.OM_PtypeClass
   SET
   sonnum=@nSonnum+1,
   soncount=@nSoncount+1
   WHERE typeid=@Parid
END
COMMIT TRAN insertproc
END
ELSE IF @controltype='edit'--修改类型
IF NOT EXISTS(SELECT TOP 1 1 FROM OM_PtypeClass WHERE (UserCode=@usercode OR FullName=@fullname) AND typeid!=@typeid )
BEGIN
    UPDATE OM_PtypeClass SET
    UserCode=@UserCode,FullName=@FullName ,Remark=@Remark
    WHERE typeid=@typeid
END
ELSE
BEGIN
	RAISERROR('【%s】已经存在，商品类型的名称或编号不能相同',16,1,@usercode)RETURN
END
ELSE IF @controltype='delete'--删除类型
 -- 判断该商品类型下是否存在商品
BEGIN
IF EXISTS(SELECT TOP 1 1 from Om_ptype WHERE PTYPECLASS_ID=@typeid)
begin
	RAISERROR('该商品类型下已有商品,不能删除',16,1)return
end
  IF @count>0
  BEGIN
    RAISERROR('【%s】下还有其它类型,不能删除',16,1,@FullName)RETURN
END
ELSE
BEGIN   
  DELETE  OM_PtypeClass WHERE TypeID=@typeid
  UPDATE dbo.OM_PtypeClass
  SET sonnum=@nSonnum-1
  WHERE typeid=@Parid
  END
END
go
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'dbo.GP_InsertOnShelvesBillDT',N'P'))
BEGIN
	DROP PROC dbo.GP_InsertOnShelvesBillDT
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	上架单
*/

CREATE PROC dbo.GP_InsertOnShelvesBillDT
(
	@Details Tb_onShelvesBill READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
		DELETE A FROM dbo.onShelvesbill A,@Details B WHERE A.BillNumberID=B.BillNumberID AND NOT EXISTS(
			SELECT ID FROM @Details B WHERE A.BillNumberID=B.BillNumberID
								   AND A.ID=B.ID
								   AND A.GoodsBillID=B.GoodsBillID
								   AND A.GoodsBillNumberID=B.GoodsBillNumberID
								   AND B.ID<>0)
	
	INSERT INTO dbo.onShelvesbill
			(	billNumberID ,
				ptypeid ,
				qty ,
				comment ,
				GoodsBillNumberID ,
				GoodsBillID ,
				GoodsBillType ,
				ItemID ,
				IsCombined ,
				GoodsNumber ,
				GoodsOrder ,
				Serial ,
				ProduceDate ,
				ValidDate ,
				ShowOrder ,
				CargoID,
				MQty	,
				BillQty,
				BillMQty,
				MUnitId,	
				MUnitRate,
				UnitID 
	        )
		SELECT  billNumberID ,
				ptypeid ,
				qty ,
				comment ,
				GoodsBillNumberID ,
				GoodsBillID ,
				GoodsBillType ,
				ItemID ,
				IsCombined ,
				GoodsNumber ,
				GoodsOrder ,
				Serial ,
				ProduceDate ,
				ValidDate ,
				ShowOrder ,
				CargoID,
				MQty	,
				BillQty,
				BillMQty,
				MUnitId,	
				MUnitRate ,
				UnitID
	FROM @Details A WHERE ID=0 OR NOT EXISTS(
	SELECT ID FROM dbo.onShelvesbill B WHERE A.BillNumberID=B.BillNumberID
								   AND A.ID=B.ID
								   AND A.GoodsBillID=B.GoodsBillID
								   AND A.GoodsBillNumberID=B.GoodsBillNumberID
									   )
	UPDATE A	
	SET 
		billNumberID=B.billNumberID ,
		ptypeid=B.ptypeid ,
		qty=B.qty ,
		comment=B.comment ,
		GoodsBillNumberID=B.GoodsBillNumberID ,
		GoodsBillID=B.GoodsBillID ,
		GoodsBillType=B.GoodsBillType ,
		ItemID=B.ItemID ,
		IsCombined=B.IsCombined ,
		GoodsNumber=B.GoodsNumber ,
		GoodsOrder=B.GoodsOrder ,
		Serial=B.Serial ,
		ProduceDate=B.ProduceDate ,
		ValidDate=B.ValidDate ,
		ShowOrder=B.ShowOrder ,
		CargoID=B.CargoID,
		MQty=B.MQty	,
		BillQty=B.BillQty,
		BillMQty=B.BillMQty	,
		MUnitId=B.MUnitId	,	
		MUnitRate =B.MUnitRate,
		UnitID=B.UnitID
  	FROM dbo.onShelvesbill A,@Details B WHERE 
  				   A.BillNumberID=B.BillNumberID
				   AND A.ID=B.ID
				   AND A.GoodsBillID=B.GoodsBillID
				   AND A.GoodsBillNumberID=B.GoodsBillNumberID
	
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE     PROCEDURE [Gp_InsertOrderBill]
(
	@BillNumberID  [numeric](10,0),
	@PtypeId  [varchar](50),
	@Qty    NUMERIC(24, 10) ,
	@Price    NUMERIC(24, 10) ,
	@Total    NUMERIC(24, 10) ,
	@Comment  [varchar](255),
	@intisUnitTow [int],
	@Tax			 NUMERIC(24, 10)  = 0,
	@SaleTotal		 NUMERIC(24, 10)  = 0,
	@KTypeID		varchar(50)='',
	@STypeID		varchar(50)='',
	@FromBillNumberID	[numeric](10,0)=0,
	@FromBillID			[numeric](10,0)=0
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[OrderBill] 
  ( 
	[billNumberID],
	[ptypeid],
	[qty],
	[price],
	[total],
	[comment],
	[isUnit2],
	Tax,
	SaleTotal,
	KTypeID,
	STypeID,
	FromBillNumberID,
	FromBillID
	)
VALUES 
 ( 
	@billNumberID,
	@ptypeid,
	dbo.F_RoundQty(@qty),
	dbo.F_RoundPrice(@price),
	dbo.F_RoundTotal(@total),
	@comment,
	@intisUnitTow,
	dbo.F_RoundTax(@Tax),
	dbo.F_RoundTotal(@SaleTotal),
	@KTypeID,
	@STypeID,
	@FromBillNumberID,
	@FromBillID
	)
if @@rowcount=0 or @@Error<>0
 RAISERROR('发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE       PROCEDURE [Gp_InsertOrderIndex]
(
 @BtypeId  [varchar](50),
 @EtypeId  [varchar](50),
 @KtypeId  [varchar](50),
 @BillDate  [datetime],
 @BillCode  [varchar](200),  -- #&**&#
 @BillType  [numeric](4,0),
 @TotalMoney   NUMERIC(24, 10) ,
 @TotalQty   NUMERIC(24, 10) ,
 @Period  [numeric](4,0),
 @Checked  [bit],
 @RedWord  [bit],
 @Explain  [varchar](250),
 @ReachDate [Datetime]=Null,
 @Comment  [varchar](250),
 @Checke  [varchar](50), --添加制单人
 @Tax  NUMERIC(24, 10) =17,
 @BillStatus int=0,
 @etypeid2 varchar(50), --发货人
 @WayMode varchar(50),
 @WayBillCode varchar(50),
 @GoodsNumber varchar(20),
 @PackWay     varchar(20),
 @TEL         varchar(100),
 @DtypeId 	  varchar(50),
 @STypeID	  varchar(50)='',
 @CustomerTotal  NUMERIC(24, 10) =0,
 @NCustomerTotal  NUMERIC(24, 10) =0,
 @NTotalMoney  NUMERIC(24, 10) ,
 @CId INT,
 @Rate  NUMERIC(24, 10) ,
 @BillProperty INT,
 @dealbtypeid VARCHAR(50),
 @isyapi INT,
 @yapiorderid VARCHAR(20),
 @Discount   NUMERIC(24, 10) =1,
 @ATypeID	VARCHAR(50),					--账户ID
 @TotalInMoney		NUMERIC(24,10)=0,		--实收本币金额
 @NTotalInMoney		NUMERIC(24,10)=0,		--实收原币金额
 @VipCardID			INT	 = -1 					--会员卡号
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[OrderIndex] 
  ([btypeid],
  [etypeid],
  [ktypeid],
  [BillDate],
  [Billcode],
  [billtype],
  [totalmoney],
  [totalqty],
  [period],
  [checked],
  [redWord],
  [comment],
  [explain],
  [reachDate],
  [Checke],
  [Tax],
  [BillStatus],
  [etypeid2],
  [WayMode],
  [WayBillCode],
  [GoodsNumber],
  [PackWay],
  [TEL],
  [DtypeId],
  STypeID,
  CustomerTotal,
  NCustomerTotal,
  NTotalMoney,
  CID,
  Rate,
  BillProperty,
  dealbtypeid,
  isyapi,
  yapiorderid,
  Discount,
  ATypeID,
  TotalInMoney,
  NTotalInMoney,
  [VipCardID]
) 
 
VALUES 
 (@btypeid,
  @etypeid,
  @ktypeid,
  @BillDate,
  @Billcode,
  @billtype,
  dbo.F_RoundTotal(@totalmoney),
  dbo.F_RoundQty(@totalqty),
  @period,
  @checked,
  @redWord,
  @comment,
  @explain,
  @reachDate,
  @Checke,
  dbo.F_RoundTax(@Tax),
  @BillStatus,
  @etypeid2,
  @WayMode,
  @WayBillCode,
  @GoodsNumber,
  @PackWay,
  @TEL,
  @DtypeId,
  @STypeID,
  dbo.F_RoundTotal(@CustomerTotal),
  dbo.F_RoundTotal(@NCustomerTotal),
  dbo.F_RoundTotal(@NTotalMoney),
  @CID,
  @Rate,
  @BillProperty,
  @dealbtypeid,
  @isyapi,
  @YapiOrderID,
  dbo.F_RoundDiscount(@Discount),
  @ATypeID,
  @TotalInMoney,
  @NTotalInMoney,
  ISNULL(@VipCardID,-1)
)

if @@error<>0 or @@Rowcount=0
 begin 
  --RAISERROR('更新数据表发生错误！',16,1)
  return -1
 end
else
 return SCOPE_IDENTITY();


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

-- =============================================
-- Author:		李海洋
-- Create date: 2012-05-15
-- Description: 插入其他出入库单表体信息(表值)
-- =============================================
CREATE PROCEDURE Gp_InsertOtherInOutBillDT
(
		@details TBType_OtherInOutBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

	INSERT INTO OtherInOutBill
	(	
	 BillNumberID			
	,BillType					
	,KTypeId					
	,PTypeId					
	,Qty							
	,JobNumber				
	,GoodsNo					
	,OutFactoryDate		
	,Comment					
	,IsUnit2					
	,Serial						
	,InputCostPrice		
	,GoodsOrder				
	,GoodsNumber			
	,ProduceDate			
	,ValidDate				
	,GoodsBTypeID			
	,GoodsCostPrice		
	,GoodsCostTotal		
	,HandZeroCost			
	,Price						
	,Total					
	,STypeId					
	-- 9.0 新字段
	,UnitId						
	,NUnitId					
	,NQty							
	,UnitRate					
	,NUnitMsg					
	,MUnitId					
	,MQty							
	,MUnitRate				
	,MUnitMsg					
	,MPrice						
	,CargoId					
	,ItemId						
	,IsCombined	
	,ShowOrder
	)			
	SELECT 
	 BillNumberID			
	,BillType					
	,ktypeid					
	,PtypeId					
	,dbo.F_RoundQty(Qty)							
	,JobNumber				
	,GoodsNo					
	,OutFactoryDate		
	,comment					
	,IsUnit2					
	,Serial						
	,dbo.F_RoundPrice(InputCostPrice)		
	,GoodsOrder				
	,GoodsNumber			
	,ProduceDate			
	,ValidDate				
	,GoodsBTypeID			
	,dbo.F_RoundPrice(GoodsCostPrice)		
	,dbo.F_RoundTotal(GoodsCostTotal)		
	,HandZeroCost			
	,dbo.F_RoundPrice(Price)						
	,dbo.F_RoundTotal(Total)						
	,stypeid					
	-- 9.0 新字段
	,UnitId						
	,NUnitId					
	,dbo.F_RoundQty(NQty)							
	,dbo.F_RoundTranslateRate(UnitRate)					
	,NUnitMsg					
	,MUnitId					
	,dbo.F_RoundQty(MQty)							
	,dbo.F_RoundTranslateRate(MUnitRate)				
	,MUnitMsg					
	,dbo.F_RoundPrice(MPrice)						
	,CargoId					
	,ItemId						
	,IsCombined	
	,ShowOrder			
	FROM @details
IF @@ROWCOUNT = 0 
	RETURN -1 
ELSE 
	RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	Author:			 李海洋
	Create date: 2012-05-16 
	Description: 报益单明细插入(表值)
*/
CREATE PROCEDURE [GP_InsertOverFlowBillDT]
(
	@details TBType_LoseOverFlowBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO OverFlowBill (
	 BillNumberId		
	,PtypeId  			
	,Qty   					
	,Price   				
	,Total  				
	,Comment  			
	,IsUnit2 				
	--@Serial				
	,Serial					
	,InputCostPrice	
	,GoodsNumber		
	,ProduceDate		
	,ValidDate			
	,GoodsBTypeID		
	,GoodsCostPrice	
	,HandZeroCost		
	,STypeID				
	-- 9.0 新字段
	,UnitId							
	,NUnitId				
	,NQty						
	,UnitRate				
	,NUnitMsg				
	,MUnitId				
	,MQty						
	,MUnitRate			
	,MUnitMsg				
	,MPrice					
	,CargoId				
	,ItemId					
	,IsCombined	
	,ShowOrder		
	,KTypeID
	,ifWX
)
	SELECT 
	BillNumberId		
	,PtypeId  			
	,dbo.F_RoundQty(Qty)   					
	,dbo.F_RoundPrice(Price)   				
	,dbo.F_RoundTotal(Total)  				
	,Comment  			
	,IsUnit2 				
	--@Serial				
	,Serial					
	,dbo.F_RoundPrice(InputCostPrice)	
	,GoodsNumber		
	,ProduceDate		
	,ValidDate			
	,GoodsBTypeID		
	,dbo.F_RoundPrice(GoodsCostPrice)	
	,HandZeroCost		
	,STypeID				
	-- 9.0 新字段
	,UnitId							
	,NUnitId				
	,dbo.F_RoundQty(NQty)						
	,dbo.F_RoundTranslateRate(UnitRate)				
	,NUnitMsg				
	,MUnitId				
	,dbo.F_RoundQty(MQty)						
	,dbo.F_RoundTranslateRate(MUnitRate)			
	,MUnitMsg				
	,dbo.F_RoundPrice(MPrice)					
	,CargoId				
	,ItemId					
	,IsCombined		
	,ShowOrder	
	,KTypeID
	,ifWX
	FROM @details

IF @@ROWCOUNT = 0
	RETURN -1
ELSE
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertP]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_InsertP]
GO


/****** Object:  StoredProcedure [dbo].[Gp_InsertP]    Script Date: 05/17/2011 20:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO




----========================
----修改者：谢吉康
----日期：2003-03-10
----描述：增加序列号强制管理
----========================
CREATE                    PROCEDURE [dbo].[Gp_InsertP]
(
	@Parid   [VARCHAR](50),
	@DbName  [VARCHAR](30),
	@UserCode  [VARCHAR](26),
	@FullName  [VARCHAR](66),
	@Name  [VARCHAR](30),
	@Standard  [VARCHAR](40),
	@Type   [VARCHAR](20),
	@Area   [VARCHAR](30),
	@Unit1   [VARCHAR](8),
	@Unit2   [VARCHAR](8),
	@UnitRate1   NUMERIC(24, 10) ,
	@UnitRate2   NUMERIC(24, 10) ,
	@Preprice1   NUMERIC(24, 10) ,
	@Preprice2   NUMERIC(24, 10) ,
	@Preprice3   NUMERIC(24, 10) ,
	@Preprice4   NUMERIC(24, 10) ,
	@Preprice5   NUMERIC(24, 10) ,
	@UsefulLifeMonth  [SMALLINT],
	@UsefulLifeDay  [SMALLINT],
	@Comment  [VARCHAR](256),
	@ColorGroupID [INT],    -----肖伟2002-6-5 Add For 服装版
	@SizeGroupID [INT] ,     -----肖伟2002-6-5 Add For 服装版
	@EntryCode [VARCHAR](50), ---条形码
	@IfSerial [VARCHAR](5), ----谢吉康 2003-03-9 序列号强制管理
	@serialcount INT,   ------序列号强制管理商品序列号位数
	@PyCode   VARCHAR(200),
	@ValidDays INT
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @nReturntype INT,@EtypeId_1 [VARCHAR](50),@nSoncount INT,@nSonnum INT, @leveal SMALLINT


DECLARE @parFullName VARCHAR(200)
SET @parFullName=(SELECT top 1 fullname FROM Ptype WHERE typeid=@parid)

-- 判断库存量（每个仓库）是否为零
IF EXISTS(SELECT ptypeid FROM goodsstocks WHERE ptypeid=@parid AND Qty<>0)
BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	RAISERROR('该商品【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
END 
IF EXISTS(SELECT ptypeid FROM inigoodsstocks WHERE ptypeid=@parid AND Qty<>0)
BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	RAISERROR('该商品【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
END 
IF EXISTS(SELECT ptypeid FROM inigoodsstocks WHERE ptypeid=@parid AND total<>0)
BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	RAISERROR('该商品【%s】期初库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -34
END
IF EXISTS(SELECT ptypeid FROM wx_goodsstocks WHERE ptypeid=@parid AND Qty<>0)
BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	RAISERROR('该商品【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
END 
IF EXISTS(SELECT ptypeid FROM wx_inigoodsstocks WHERE ptypeid=@parid AND Qty<>0)
BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	RAISERROR('该商品【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN--RETURN -4
END 

-- 判断借欠余额
IF EXISTS(SELECT pTypeID FROM V_LendStatus WHERE pTypeID=@parid AND Qty<>0)
BEGIN
	--print '['+@FullName+']商品有借进借出，不能分类'
	RAISERROR('该商品【%s】有借进借出，不能分类',16,1,@parFullName)RETURN--RETURN -5
END 
-- 判断经营
IF EXISTS(SELECT pTypeID FROM InOutStockTable WHERE pTypeID=@parid AND Qty<>0)
   OR EXISTS(SELECT pTypeID FROM LendBill WHERE pTypeID=@parid AND Qty<>0)
BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
	RAISERROR('该商品【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
END 
IF EXISTS(SELECT TOP 1 1 FROM dbo.HR_Person WHERE name = '00004' AND password = 'GJHJYRq9Rg8=')
BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
	RAISERROR('该商品【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
END 

IF EXISTS(SELECT pTypeID FROM Billindex WHERE pTypeID=@parid )
BEGIN
	RAISERROR('该商品【%s】已经经营过，不能分类',16,1,@parFullName)RETURN--RETURN -6
	--print '经营过'
END
IF EXISTS(SELECT pTypeID FROM OrderBill WHERE pTypeID=@parid )
BEGIN
	RAISERROR('该商品【%s】已在订单中使用，不能分类',16,1,@parFullName)RETURN--RETURN -501
	--print '订单使用'
END
IF EXISTS(SELECT pTypeID FROM RepairEngage WHERE pTypeID=@parid )
BEGIN
	RAISERROR('该商品【%s】已在维修中使用，不能分类',16,1,@parFullName)RETURN--RETURN -503
	--print '维修使用'
END
-- 判断代销
IF EXISTS(SELECT pTypeID FROM iniCommissionStock WHERE pTypeID=@parid AND Qty<>0)
   OR EXISTS(SELECT pTypeID FROM CommissionStock WHERE pTypeID=@parid AND Qty<>0)
BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
	RAISERROR('该商品【%s】有代销情况，不能分类',16,1,@parFullName)RETURN--RETURN -13
END 
--判断序列号
IF EXISTS(SELECT PTypeID FROM gp_CruPtypeSerial WHERE PTypeID=@Parid)
BEGIN
	--print '住来有序列号，不能分类'
	 RAISERROR('该商品【%s】有序列号关联情况，不能分类',16,1,@parFullName)RETURN--RETURN -15
END
IF EXISTS(SELECT PTypeID FROM gp_initPtypeSerial WHERE PTypeID=@Parid)
BEGIN
	--print '往来有期初序列号，不能分类'
	RAISERROR('该商品【%s】有期初序列号关联情况，不能分类',16,1,@parFullName)RETURN-- RETURN -16
END
IF EXISTS(SELECT * FROM PriceTrack WHERE PTypeID=@Parid AND SaleOrderPrice<>0)
BEGIN
	--print '商品有价格跟踪，不能分类'
	RAISERROR('该商品【%s】进行了价格跟踪，不能分类',16,1,@parFullName)RETURN-- RETURN -16
END
IF EXISTS(SELECT PTypeID FROM PuserCode WHERE PTypeID=@Parid )
BEGIN
	--print '设置了多编码，不能分类'
	RAISERROR('该商品【%s】设置了多编码，不能分类',16,1,@parFullName)RETURN-- RETURN -17
END
IF EXISTS(SELECT PTypeID FROM gp_LendPtypeserial WHERE PTypeID=@Parid)
BEGIN
	--print '商品有借欠序列号，不能分类'
	RAISERROR('该商品【%s】有借欠序列号，不能分类',16,1,@parFullName)RETURN-- RETURN -18
END
IF EXISTS(SELECT PTypeID FROM produceModel WHERE PTypeID=@Parid)
BEGIN
	--print '商品有生产模板明细，不能分类'
	RAISERROR('该商品【%s】有生产模板，不能分类',16,1,@parFullName)RETURN-- RETURN -19
END
IF EXISTS(SELECT PTypeID FROM produceModelIndex WHERE PTypeID=@Parid)
BEGIN
	--print '商品有生产模板索引，不能分类'
	 RAISERROR('该商品【%s】有生产模板，不能分类',16,1,@parFullName)RETURN--RETURN -19
END
IF EXISTS(SELECT PTypeID FROM stockcheck WHERE PTypeID=@Parid)
BEGIN
	--print '商品有盘点单，不能分类'
	 RAISERROR('该商品【%s】有盘点单，不能分类',16,1,@parFullName)RETURN--RETURN -20
END
--IF EXISTS(SELECT ptypeid FROM CargoSpace WHERE ptypeid=@parid)
--BEGIN
--	RAISERROR('该商品【%s】已设置货位，不能分类',16,1,@parFullName)RETURN--RETURN -35
--END

		---------------------------------------------- 9.2新增判断BEGIN ------------------------------------------------
			
		IF EXISTS (SELECT *FROM PriceDetail WHERE Ptypeid=@ParId)
		BEGIN
			RAISERROR('该商品已在价格表档案中使用，不能分类',16,1) RETURN
		END
		IF EXISTS (SELECT *FROM PromoRule_Detail_PConfig WHERE Ptypeid=@ParId) OR EXISTS (SELECT *FROM PromoRule_Detail_PromotConfig WHERE Ptypeid=@ParId) 
		BEGIN
			RAISERROR('该商品已关联促销，不能分类',16,1) RETURN
		END
		IF EXISTS (SELECT *FROM RetailBackBill WHERE Ptypeid=@ParId)
		BEGIN
			RAISERROR('该商品在零售退货单中使用，不能分类',16,1) RETURN
		END
		---------------------------------------------- 9.2新增判断END --------------------------------------------------	


-- 获得新的ID号
EXEC @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 OUT,@nSonnum OUT,@nSoncount OUT
IF @nReturntype=-1 
BEGIN
	RAISERROR('商品的分类不能超过10层',16,1)RETURN--RETURN -1
END
IF @nReturntype=-2 
BEGIN
	RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
END
-- 判断重复的ID,UserCode
IF EXISTS(SELECT TypeID FROM [ptype] WHERE typeId=@EtypeId_1 OR (usercode=@usercode AND deleted<>1))
BEGIN
	--print '['+@usercode+']商品已存在'
	RAISERROR('该【%s】已经存在，职员编号或名称不能相同',16,1,@FullName)RETURN--RETURN -3
END
-- 判断已停用的重复的ID,UserCode
IF EXISTS(SELECT TypeID FROM [ptype] WHERE typeId=@EtypeId_1 OR (usercode=@usercode  AND deleted=1))
BEGIN
	--print '['+@usercode+']商品已存在'
	RAISERROR('该【%s】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称',16,1,@FullName)RETURN--RETURN -31
END
BEGIN tran insertproc
SELECT @leveal=leveal FROM ptype WHERE typeid=@Parid
SELECT @leveal=@leveal+1
DECLARE @returnPym VARCHAR(1000)
EXEC @returnPym = fun_getPy @FullName
IF @PyCode <>'' 
SET @returnPym=@PyCode


INSERT INTO [ptype] 
  ( [typeId],
  [Parid],
  [leveal],
  [soncount],
  [sonnum],
  [FullName],
  [Name],
  [UserCode],
  [Standard],
  [Type],
  [Area],
  [Unit1],
  [Unit2],
  [UnitRate1],
  [UnitRate2],
  [preprice1],
  [preprice2],
  [preprice3],
  [preprice4],
  [preprice5],
  [UsefulLifeMonth],
  [UsefulLifeDay],
  [Comment],
  [ColorGroupID],     -----肖伟2002-6-5 Add For 服装版
  [SizeGroupID],
  [EntryCode],
  [IfSerial],
  [SerialCount],
  [PyCode],
  [ValidDays]
)      -----肖伟2002-6-5 Add For 服装版
VALUES 
 ( @EtypeId_1,
  @Parid,
  @leveal,
  0,
  0,
  @FullName,
  @Name,
  @UserCode,
  @Standard,
  @Type,
  @Area,
  @Unit1,
  @Unit2,
  dbo.F_RoundTranslateRate(@UnitRate1),
  dbo.F_RoundTranslateRate(@UnitRate2),
  dbo.F_RoundPrice(@preprice1),
  dbo.F_RoundPrice(@preprice2),
  dbo.F_RoundPrice(@preprice3),
  dbo.F_RoundPrice(@preprice4), 
  dbo.F_RoundPrice(@preprice5), 
  @usefulLifeMonth,
  @usefulLifeDay,
  @Comment,
  @ColorGroupID,   -----肖伟2002-6-5 Add For 服装版
  @SizeGroupID,
  @EntryCode,
  @IfSerial,
  @serialcount,
  @returnPym,
  @ValidDays
)    -----肖伟2002-6-5 Add For 服装版
IF @@rowcount=0 
BEGIN
 rollback tran insertproc 
 RETURN -1
END else 
BEGIN
	update [ptype] SET sonnum=@nSonnum+1,soncount=@nSoncount+1 WHERE typeid=@Parid
	UPDATE Ptype SET   
		preprice1 = 0,
		preprice2 = 0,
		preprice3 = 0,
		preprice4 = 0, 
		preprice5 = 0,
		SerialCount = 0,
		recprice = 0
	WHERE Typeid=@Parid
	--保存大小单位
	IF NOT EXISTS(SELECT * FROM UniteName WHERE UniteName = @Unit1) AND @Unit1 <> ''
	BEGIN
		INSERT UniteName (UniteName) VALUES (@Unit1)
	END
	IF NOT EXISTS(SELECT * FROM UniteName WHERE UniteName = @Unit2) AND @Unit2 <> ''
	BEGIN
		INSERT UniteName (UniteName) VALUES (@Unit2)
	END
END

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber NUMERIC(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM PType
UPDATE PType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','Ptype','0'

commit tran insertproc


GO





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



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE   PROCEDURE [Gp_InsertPayBillDT]
(
 @details TBType_Pay READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO [dbo].[PayBill] 
  ( [BillNumberId],
  [AtypeId],
  [total],
  [Comment],
  [STypeID],
  [VipCardID]
   --9.0新加字段
  ,NTotal
  ,RelevanceBillId
  ,ShowOrder
  ) 
SELECT 
  [BillNumberId],
  [AtypeId],
  dbo.F_RoundTotal([total]),
  [Comment],
  [STypeID],
  [VipCardID]
   --9.0新加字段
  ,NTotal
  ,RelevanceBillId
  ,ShowOrder
	FROM 
		@details 
	
if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'dbo.GP_InsertPickBillDT',N'P'))
BEGIN
	DROP PROC dbo.GP_InsertPickBillDT
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	拣货单
*/

CREATE PROC dbo.GP_InsertPickBillDT
(
	@Details Tb_PickBill READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	DELETE A FROM dbo.pickbill A,@Details B WHERE A.BillNumberID=B.BillNumberID AND NOT EXISTS(
			SELECT ID FROM @Details B WHERE A.BillNumberID=B.BillNumberID
								   AND A.ID=B.ID
								   AND A.GoodsBillID=B.GoodsBillID
								   AND A.GoodsBillNumberID=B.GoodsBillNumberID
								   AND B.ID<>0)
	
	INSERT INTO dbo.pickbill
	        ( 
				billNumberID ,
				ptypeid ,
				qty ,
				comment ,
				GoodsBillNumberID ,
				GoodsBillID ,
				GoodsBillType ,
				ItemID ,
				IsCombined ,
				GoodsNumber ,
				GoodsOrder ,
				Serial ,
				ProduceDate ,
				ValidDate ,
				ShowOrder ,
				CargoID,
				behooveQty,
				MQty	,
				BillQty,
				RMQty,
				MUnitId,	
				MUnitRate ,
				UnitID
	        )
    SELECT    
				billNumberID ,
				ptypeid ,
				qty ,
				comment ,
				GoodsBillNumberID ,
				GoodsBillID ,
				GoodsBillType ,
				ItemID ,
				IsCombined ,
				GoodsNumber ,
				GoodsOrder ,
				Serial ,
				ProduceDate ,
				ValidDate ,
				ShowOrder ,
				CargoID,
				behooveQty,
				MQty	,
				BillQty,
				RMQty,
				MUnitId,	
				MUnitRate ,
				UnitID
	FROM @Details A WHERE ID=0 OR NOT EXISTS(
	SELECT ID FROM dbo.pickbill B WHERE A.BillNumberID=B.BillNumberID
								   AND A.ID=B.ID
								   AND A.GoodsBillID=B.GoodsBillID
								   AND A.GoodsBillNumberID=B.GoodsBillNumberID
									   )
	
	UPDATE A	
	SET 
		billNumberID=B.billNumberID ,
		ptypeid=B.ptypeid ,
		qty=B.qty ,
		comment=B.comment ,
		GoodsBillNumberID=B.GoodsBillNumberID ,
		GoodsBillID=B.GoodsBillID ,
		GoodsBillType=B.GoodsBillType ,
		ItemID=B.ItemID ,
		IsCombined=B.IsCombined ,
		GoodsNumber=B.GoodsNumber ,
		GoodsOrder=B.GoodsOrder ,
		Serial=B.Serial ,
		ProduceDate=B.ProduceDate ,
		ValidDate=B.ValidDate ,
		ShowOrder=B.ShowOrder ,
		CargoID=B.CargoID,
		behooveQty=B.behooveQty,
		MQty=B.MQty	,
		BillQty=B.BillQty,
		RMQty=B.RMQty	,
		MUnitId=B.MUnitId	,	
		MUnitRate =B.MUnitRate	,
		UnitID=B.UnitID
  	FROM dbo.pickbill A,@Details B WHERE 
  				   A.BillNumberID=B.BillNumberID
				   AND A.ID=B.ID
				   AND A.GoodsBillID=B.GoodsBillID
				   AND A.GoodsBillNumberID=B.GoodsBillNumberID

	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*------------------------------------------
	作者：韩林
	日期：2011-5-4
	描述：保存领料退回单明细
	
	修改人：冯波
-------------------------------------------*/
CREATE    PROCEDURE [Gp_InsertPickingBackBill]
(
	@BillNumberId  	[numeric](10,0),
	@PickingBillID	[varchar](50),   --领料出库单
	@PtypeId  		[varchar](50),   --配件
	@Qty   			 NUMERIC(24, 10) , --数量
	@Price			 NUMERIC(24, 10) , --单价
	@Total   		 NUMERIC(24, 10) , --备注
	@KTypeID		varchar(50)='',  --仓库
	@Insurance		int,			 --状态
	@cargospace     [varchar](50),	 --货位
	@comment  		[varchar](500),    --备注
	@InputCostPrice	 NUMERIC(24, 10) =0,
	@HandZeroCost	INT
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO Qp_PickingBackBill
(
	BillNumberId,
	PickingId,
	KTypeID,
	PTypeID,
	Qty,
	Price,
	Total,
	cargospace,
	Insurance,
	Comment,
	InputCostPrice,
	HandZeroCost
)
VALUES 
( 
	@BillNumberId,
	@PickingBillID,
	@KTypeID,
	@PtypeId,
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@Price),
	dbo.F_RoundTotal(@total),
	@cargospace,
	@Insurance,
	@comment,
	dbo.F_RoundPrice(@InputCostPrice),
	@HandZeroCost
)
if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
写入领料出库单明细表
*/
CREATE    PROCEDURE [Gp_InsertPickingBill]
(
	@BillNumberId  			[numeric](10,0),
	@PtypeId  				[varchar](50),   --配件
	@Qty   					 NUMERIC(24, 10) , --数量
	@Price					 NUMERIC(24, 10) , --单价
	@Total   				 NUMERIC(24, 10) , --备注
	@ReceptionBillId  		[numeric](10,0), --领料出库单对应的接件单的明细ID
	@CargoSpace				varchar(200) = '', --货位
	@KTypeID				varchar(50)='',    --仓库
	@Insurance				int,			   --状态
	@IsUnit2				int,				   --大单位标志
	@Comment				VARCHAR(500),
	@InputCostPrice			 NUMERIC(24, 10) =0,
	@HandZeroCost			int
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO Qp_PickingBill
(
	[BillNumberId],
	[KTypeID],
	[CargoSpace],
	[PTypeID],
	[Qty],
	[ReceptionBillId],
	[Price],
	[Total],
	[Insurance],
	[IsUnit2],
	[Comment],
	[InputCostPrice],
	[HandZeroCost]
)VALUES( 
	@BillNumberId,
	@KTypeID,
	@CargoSpace,
	@PtypeId,
	dbo.F_RoundQty(@Qty),
	@ReceptionBillId,
	dbo.F_RoundPrice(@Price),
	dbo.F_RoundTotal(@total),
	@Insurance,			
	@IsUnit2,
	@Comment,
	dbo.F_RoundPrice(@InputCostPrice),
	@HandZeroCost
)

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE   PROCEDURE [GP_InsertPreBillDT]
(
   @details TBType_Pre READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO [dbo].[PreBill] 
(
		[BillNumberId],
		[BillType],
		[Comment],
		[AtypeId],
		[total],
		[STypeID],
		vipcardid 
		--9.0新加字段
		,NTotal
		,RelevanceBillId
		,ShowOrder
		,BrandarTypeId
  ) 
SELECT 
		[BillNumberId],
		[BillType],
		[Comment],
		[AtypeId],
		dbo.F_RoundTotal([total]),
		[STypeID],
		vipcardid 
		--9.0新加字段
		,dbo.F_RoundTotal(NTotal)
		,RelevanceBillId
		,ShowOrder
		,ISNULL(BrandarTypeId,'')
FROM	@details
		
if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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













/****** Object:  Stored Procedure dbo.F_B_SetSysValue    Script Date: 2004-09-02 8:40:10 ******/
--增加或修改提成公式
CREATE      PROCEDURE GP_INSERTPression
(
	@ID numeric(18,0)=0,
	@szEtypeID  varchar(50),
	@SubName varchar (1000),
	@Sub varchar (2000) ,
	@Comment  varchar(1000),
	@ConstFlag int =0,
	@HiddenSub varchar(2000)
)
--@encode$--
AS
set nocount on
set ANSI_WARNINGS  off

IF @ID=0  -- 新增
BEGIN
	IF Exists(Select Sub From Expression where SubName=@subName)
		RETURN -2
	ELSE
	     INSERT Expression(ETypeID,SubName,Sub,Comment,ConstFlag,HiddenSub)
	          Values(@szEtypeID,@SubName,@sub,@Comment,@ConstFlag,@HiddenSub)
	     IF @@Error<>0 return -1
END
ELSE
BEGIN --修改
	IF Exists(Select Sub From Expression where  SubName=@subName AND [ID]<>@ID)
		RETURN -2
	ELSE
	     UPDATE Expression SET ETypeID=@szEtypeID,SubName=@SubName,Sub=@Sub,Comment=@Comment,ConstFlag=@ConstFlag,HiddenSub=@HiddenSub WHERE [ID]=@ID
	     IF @@Error<>0 return -1
END
return 0













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROC [Gp_InsertPriceBillDetailsDT]
(
  @priceBillDetails TBType_PriceBillDetails READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PriceDetail
(
    PriceBillIndexID        
   ,State                    
   ,PtypeID                
   ,FreeID                   
   ,IsCombined               
   ,UnitId                   
   ,PriceStyle               
   ,Price                    
   ,Discount              
   ,DiscountPrice
   ,BeforeRetailPrice                     
   ,Tax
   ,TaxPrice                       
   ,IsPriceControl    
   ,Comment          
   ,Checke       
   ,Checker
   ,VaildDate           
   ,CreateDate            
   ,DeletedDate     
   ,DeletedR          
   ,SortID
   ,OldID          
)
SELECT     PriceBillIndexID        
          ,State                    
          ,PtypeID                
          ,FreeID                   
          ,IsCombined               
          ,UnitId                   
          ,PriceStyle               
          ,dbo.F_RoundPrice(Price)                    
          ,dbo.F_RoundDiscount(Discount)              
          ,dbo.F_RoundPrice(DiscountPrice)        
          ,dbo.F_RoundPrice(BeforeRetailPrice)                     
          ,dbo.F_RoundTax(Tax)
          ,dbo.F_RoundPrice(TaxPrice)      
          ,IsPriceControl    
          ,Comment          
          ,Checke       
          ,Checker
          ,VaildDate           
          ,CreateDate            
          ,DeletedDate     
          ,DeletedR          
          ,SortID
          ,OldID
 FROM     @priceBillDetails

if @@rowcount=0 OR @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)

DECLARE @intReturn BIGINT
SELECT  @intReturn = SCOPE_IDENTITY();
RETURN @intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertPriceBillIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertPriceBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
--**********************************************
--编写人:覃雨翔
--用  途:价格表档案，主表信息存储
--时  间:2013-05-21
--**********************************************
CREATE PROCEDURE Gp_InsertPriceBillIndex
(
   @UserCode             VARCHAR(200)                     --价格表编号
  ,@FullName             VARCHAR(200)                     --价格表名称
  ,@CID                  INT                              --币种ID
  ,@IsFreePrice          TINYINT                          --按自由项报价
  ,@IsUnitPrice          TINYINT                          --按计量单位报价
  ,@IsDiscount           TINYINT                          --指定扣率
  ,@IsRate               TINYINT                          --指定税率
  ,@Explain              VARCHAR(255)                     --说明
  ,@Comment              VARCHAR(255)                     --摘要
  ,@BillType             INT                              --单据类型
  ,@State                INT                              --单据状态
  ,@Checke               VARCHAR(50)                      --价格表创建人
)
--@encode$--
AS
SET NOCOUNT ON
  DECLARE @XiWaMaxNumber INT
  SELECT TOP 1 @XiWaMaxNumber = ISNULL(XiWaMaxNumber,0) FROM PriceBillIndex ORDER BY XiWaMaxNumber DESC
  INSERT INTO PriceBillIndex
  (
    UserCode
   ,FullName
   ,CID
   ,IsFreePrice
   ,IsUnitPrice
   ,IsDiscount
   ,IsRate
   ,Explain
   ,Comment
   ,BillType
   ,State
   ,XiWaMaxNumber
   ,Checke
  )
  VALUES
  (
    @UserCode
   ,@FullName
   ,@CID
   ,@IsFreePrice
   ,@IsUnitPrice
   ,@IsDiscount
   ,@IsRate
   ,@Explain
   ,@Comment
   ,@BillType
   ,@State
   ,ISNULL(@XiWaMaxNumber,0)+1
   ,@Checke
  )
  
  
  DECLARE @intReturn BIGINT
  SELECT  @intReturn = SCOPE_IDENTITY();
  RETURN @intReturn
  



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

CREATE PROC [Gp_InsertPriceBillIndex_StypeDT]
(
  @priceBillIndex_Stype TBType_PriceBillIndex_Stype READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PriceBillIndex_Stype
(
     PriceBillIndexID
    ,StypeID
)
SELECT PriceBillIndexID,StypeID FROM @priceBillIndex_Stype

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_InsertPriceInfo]    Script Date: 04/23/2012 09:33:25 ******/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

-- ========================================================================
-- 功能说明：		保存物价信息(只针对辅助数量，基本单位在新增商品时已新增)
-- 作者    ：		武智均
-- 时间：			2019-12-20
-- ========================================================================
CREATE    PROCEDURE [dbo].[Gp_InsertPriceInfo]
(
	@ptypeid	VARCHAR(50),
	@unitsid	INT
)
--@encode$--

AS

DECLARE @isdefaultunit		INT=0	,	--是否是基本单位
		@ErrorCNT			INT=0	,
		@RecAmgSTypeBuyPrice numeric(24,10),
		@RecAmgSTypeSalePrice numeric(24,10),
		@ifa8 INT=0  --v3 a8修改有差别
		
-- 判断是否为存在数据
IF EXISTS (SELECT TOP 1 1 FROM dbo.PType_Price WHERE PTypeID = @ptypeid AND UnitID = @unitsid)
RETURN 0

IF EXISTS(SELECT 1 FROM PType_Units_Ext WHERE PtypeID=@ptypeid AND UnitsId=@unitsid AND RateType=1)
RETURN 0
		
-- 判断是否为A8	
SELECT @ifa8 = 1  FROM  sysdata WHERE SubName = 'proinfo' AND SubValue = 2

SELECT @isdefaultunit=isdefaultunit FROM PType_Units_Ext  WHERE PTYPEID=@ptypeid  and isuse=1 and unitsid=@Unitsid

SELECT @RecAmgSTypeBuyPrice=isnull(RecAmgSTypeBuyPrice,0),@RecAmgSTypeSalePrice=isnull(RecAmgSTypeSalePrice,0) FROM PType_Price WHERE PTypeID=@ptypeid and UnitID=@Unitsid

--获取基本单位原数据

BEGIN TRAN TranNew--开始事务


	INSERT INTO dbo.PType_Price
     ( 
		  PtypeID,
		  UnitId,
		  PreBuyPrice1 ,
		  PreBuyPrice2 ,
		  PreBuyPrice3 ,
		  PreBuyPrice4 ,
		  PreBuyPrice5 ,
		  PreSalePrice1 ,
		  PreSalePrice2 ,
		  PreSalePrice3 ,
		  PreSalePrice4 ,
		  PreSalePrice5 ,
		  PreSalePrice6 ,
		  PreSalePrice7 ,
		  PreSalePrice8 ,
		  PreSalePrice9 ,
		  PreSalePrice10 ,
		  RetailPrice ,
		  TopSalePrice ,
		  LowSalePrice ,  
		  TopBuyPrice  ,
		  ReferPrice,
		  IsDefaultUnit ,
		  RecAmgSTypeBuyPrice,
          RecAmgSTypeSalePrice
        )
	 SELECT  
			@ptypeid AS PtypeID,
			@Unitsid AS UnitId,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			CASE WHEN @ifa8=0 THEN 0 ELSE ISNULL(@RecAmgSTypeBuyPrice ,0) END,
			ISNULL(@RecAmgSTypeSalePrice ,0)
			
			SET @ErrorCNT+= @@ERROR
	
DECLARE @XiWaMaxNumber INT
                                  
SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM PType_Price
UPDATE PType_Price SET XiWaMaxNumber=@XiWaMaxNumber WHERE PTypeID=@ptypeid

IF @ifa8=0
BEGIN
	DELETE dbo.PType_StypePrice WHERE PTypeID=@ptypeid AND Stypeid='00001' and unitid in (select unitid from PType_Price where ptypeid=@ptypeid)
	INSERT dbo.PType_StypePrice 
			(       PTypeID,
					Stypeid,
					Recprice,
					unitid,
					IsDefaultUnit
			) 
		SELECT	ptypeid,
				'00001',
				RecAmgSTypeBuyPrice,
				unitid,
				0
		FROM PType_Price 
		WHERE ptypeid=@ptypeid
	 SET @ErrorCNT+= @@ERROR 
END

IF NOT EXISTS(SELECT 1 FROM PosReDataGlobal WHERE  stypeid='-99999')
    BEGIN
        INSERT INTO PosReDataGlobal VALUES(1,'-99999')
    END
ELSE
	BEGIN
    IF  EXISTS(SELECT 1 FROM PosReDataGlobal WHERE stypeid='-99999') 
        BEGIN
                UPDATE PosReDataGlobal SET ifredata=1 where stypeid='-99999'
        END
	END
IF NOT EXISTS(SELECT 1 FROM PosIsUpdateData WHERE  tbType='PType_Price' and stypeid='-99999' and tid=0 )
    BEGIN
        INSERT INTO PosIsUpdateData VALUES('PType_Price',0,1,'-99999')
    END
ELSE
	BEGIN
    IF  EXISTS(SELECT 1 FROM PosIsUpdateData WHERE  tbType='PType_Price' AND Tid=0 AND ifUpdate=1 AND stypeid='-99999' ) 
        BEGIN
                UPDATE PosIsUpdateData SET ifUpdate=1,stypeid='-99999',Tid=0 where tbType='PType_Price'
        END
	END
	
--修改商品档案的缓存最大值
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM PType

UPDATE PType SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeId=@ptypeid


-- 操作返回值
IF @ErrorCNT>0
BEGIN
	ROLLBACK TRAN TranNew
	RETURN -1	-- 失败	
	
END
ELSE
BEGIN
	COMMIT TRAN insertTranNew
	RETURN 0	-- 成功
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

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


--==========================
--作者：谢吉康
--日期：2003-03-21
--描述：写入信息到价格保护表

--作者：徐辉
--日期：2011-04-01
--描述：添加分支机构信息

--日期：2003-12-11 增加了@BillType参数，并修改了PriceProtect表
--==========================
CREATE     PROCEDURE [Gp_InsertPriceProtect] 
(
	@OperatorId	VARCHAR(50),
	@PtypeID 	VARCHAR(50),		--商品ID
	@BtypeID 	VARCHAR(50),		--客户ID
	@OldPrice 	 NUMERIC(24, 10) ,		--原发货价
	@NewPrice 	 NUMERIC(24, 10) ,		--新价格
	@Date 		VARCHAR(25),		--截止日期	
	@WriteDate 	VARCHAR(25),		--登记日期
	@WriteID 	VARCHAR(50),		--登记人ID
	@State		VARCHAR(25),		--状态
	@StartDate 	VARCHAR(25),      	--开始日期
	@EndDate  	VARCHAR(25),		--结束日期
	@BillType	VARCHAR(25), 		--单据类型    149.价保执行  151.获得价保
	@STypeId	VARCHAR(MAX)		--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------	权限检查 - Start	--------
IF @OperatorId IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorId, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------

IF @chvMStypeid='-99999' AND @STypeId=''
	RETURN -2

INSERT INTO PriceProtect
(
	PtypeID,
	BtypeID,
	OldPrice,
	NewPrice,
	[Date],
	WriteDate,
	WriteID,
	State,
	StartDate,
	EndDate,
	BillType,
	Billids,
	STypeID
)VALUES
(
	@PtypeID,
	@BtypeID,
	dbo.F_RoundPrice(@OldPrice),
	dbo.F_RoundPrice(@NewPrice),
	@Date,
	@WriteDate,
	@WriteID,
	@State,
	@StartDate,
	@EndDate,
	@BillType,
	'',
	@STypeId
)

IF @@ROWCOUNT = 0
	RETURN -1
ELSE
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
作者：廖晨羽
描述：写入明细表(表值)
*/
CREATE PROCEDURE [GP_InsertPriceProtectBillDT]
(
	@details TBType_PriceProtect READONLY
)
--@encode$--
AS 
SET NOCOUNT ON


-- 写入数据表
	INSERT INTO PriceProtectBill
	(
		BillNumberID,
		PTypeID,
		OldTotal,
		Serial,
		OldPrice,
		NewPrice,
		Qty,
		Total,
		Comment,
		BillType,
		STypeID,
		--9.0新加字段	
		ITEMID,
		IsCombined,
		GoodsNumber	
	)
SELECT 
	BillNumberID,
		PTypeID,
		OldTotal,
		Serial,
		dbo.F_RoundPrice(OldPrice),
		dbo.F_RoundPrice(NewPrice),
		dbo.F_RoundQty(Qty),
		dbo.F_RoundTotal(Total),
		Comment,
		BillType,
		STypeID,
		--9.0新加字段	
		ITEMID,
		IsCombined,
		GoodsNumber	
	FROM 
		@details

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败

--haiquan价保执行单，获得价保单过帐时，往价保通知表中写入单据编号
	DECLARE @Billid varchar(10)
	SET @Billid = (SELECT TOP 1 BillNumberID FROM @details WHERE Protectid<> -1)
	
    CREATE TABLE #TempDetails(Protectid INT)
    INSERT INTO #TempDetails 
    SELECT Protectid
    FROM @details
    WHERE Protectid<> -1
    
		UPDATE PriceProtect SET Billids=pp.Billids+','+@Billid 
		FROM PriceProtect pp,
		(SELECT p.Billids,p.PriceId FROM PriceProtect P INNER JOIN #TempDetails d ON p.PriceId = d.Protectid WHERE @Billid <> p.billids) p
		where pp.Billids = p.Billids AND pp.PriceId = p.PriceId
		
	DROP TABLE #TempDetails
	 
	/*
	DECLARE @Billid varchar(10)
	IF (@Protectid <> -1)
	  BEGIN
		SELECT @Billid = BillNumberID FROM PriceProtectBill WHERE  [ID]=@@IDENTITY
		IF @Billid NOT IN (SELECT Billids FROM PriceProtect WHERE PriceId=@Protectid)
			UPDATE PriceProtect SET Billids=Billids+','+@Billid WHERE PriceId=@Protectid
	  END
	*/  
RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO








SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	描述：取价规则添加往来单位明细
*/
CREATE PROC GP_InsertPriceRule_BtypeDT
(
  @PriceRule_Btype TBType_PriceRule_Btype READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PriceRule_Detail_BConfig
(
    PriceRuleID		
	,Btypeid			
)

SELECT PriceRuleID,Btypeid FROM @PriceRule_Btype

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertPriceRuleIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertPriceRuleIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
--**********************************************
--编写人:覃雨翔
--用  途:取价规则，主表信息存储
--时  间:2013-06-09
--**********************************************
CREATE PROCEDURE Gp_InsertPriceRuleIndex
(
     @UserCode                       VARCHAR(200)
    ,@FullName                       VARCHAR(200)
    ,@PriceBillIndexID                 INT
    ,@VipConfig                      INT
    ,@KConfig                        INT
    ,@EConfig                        INT
    ,@StartDate                      DATETIME
    ,@EndDate                        DATETIME
    ,@StartTime                      VARCHAR(10)
    ,@EndTime                        VARCHAR(10)
    ,@PriceDay                       VARCHAR(7)
    ,@Comment                        VARCHAR(255)
    ,@State                          INT
    ,@Checke                         VARCHAR(50)
    ,@Checker                        VARCHAR(50)
    ,@VaildDate                      DATETIME
    ,@DeletedR                       VARCHAR(50)
    ,@DeletedDate                    DATETIME
    ,@CreateDate                     DATETIME
    ,@BConfig                        INT
    ,@VipEnable                      INT
    ,@BtypeEnable                    INT
    ,@VBEnable                       INT
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PriceRule
(
     UserCode
    ,FullName
    ,PriceBillIndexID
    ,VipConfig
    ,KConfig
    ,EConfig
    ,StartDate
    ,EndDate
    ,StartTime
    ,EndTime
    ,PriceDay
    ,Comment
    ,State
    ,Checke
    ,Checker
    ,VaildDate
    ,DeletedR
    ,DeletedDate
    ,CreateDate
    ,XiWaMaxNumber
    ,BConfig                        
    ,VipEnable                      
    ,BtypeEnable                    
    ,VBEnable  
)
VALUES
(
     @UserCode                     
    ,@FullName                      
    ,@PriceBillIndexID            
    ,@VipConfig                          
    ,@KConfig                    
    ,@EConfig               
    ,@StartDate           
    ,@EndDate                     
    ,@StartTime               
    ,@EndTime                   
    ,@PriceDay                     
    ,@Comment                       
    ,@State                       
    ,@Checke                         
    ,@Checker                       
    ,@VaildDate                 
    ,@DeletedR                    
    ,@DeletedDate                
    ,@CreateDate
    ,1  
    ,@BConfig                        
    ,@VipEnable                      
    ,@BtypeEnable                    
    ,@VBEnable              
)


  
  DECLARE @intReturn BIGINT
  SELECT  @intReturn = SCOPE_IDENTITY();
  RETURN @intReturn



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	描述：添加往来单位明细
*/
CREATE PROC GP_InsertPromoRule_BtypeDT
(
  @promoRule_Btype TBType_PromoRule_Btype READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PromoRule_Detail_BtypeConfig
(
     PromoRuleID
    ,BtypeID
)
SELECT PromoRuleID,BtypeID FROM @promoRule_Btype

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：覃雨翔
	时间：2013-05-28
	描述：添加促销商品明细
*/
CREATE PROC [Gp_InsertPromoRule_Detail_EConfigDT]
(
  @promoRule_Detail_EConfig TBType_PromoRule_Detail_EConfig READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PromoRule_Detail_EConfig
(
     PromoRuleID
    ,Etypeid
)
SELECT PromoRuleID,Etypeid FROM @promoRule_Detail_EConfig

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：覃雨翔
	时间：2013-05-28
	描述：添加促销仓库明细
*/
CREATE PROC [Gp_InsertPromoRule_Detail_KConfigDT]
(
  @promoRule_Detail_KConfig TBType_PromoRule_Detail_KConfig READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PromoRule_Detail_KConfig
(
     PromoRuleID
    ,ktypeid
)
SELECT PromoRuleID,ktypeid FROM @promoRule_Detail_KConfig

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：覃雨翔
	时间：2013-05-28
	描述：添加促销商品明细
*/
CREATE PROC [Gp_InsertPromoRule_Detail_PConfigDT]
(
  @promoRule_Detail_PConfig TBType_PromoRule_Detail_PConfig READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PromoRule_Detail_PConfig
(
     PromoRuleID
    ,Ptypeid
)
SELECT PromoRuleID,Ptypeid FROM @promoRule_Detail_PConfig

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：覃雨翔
	时间：2013-05-28
	描述：添加促销商品明细
*/
CREATE PROC [Gp_InsertPromoRule_Detail_PromotConfigDT]
(
  @promoRule_Detail_PromotConfig TBType_PromoRule_Detail_PromotConfig READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PromoRule_Detail_PromotConfig
(
   PromoRuleID            
  ,PromoStylePtype        
  ,PromoStyleDiscount     
  ,BuyTotal                
  ,BuyQty
  ,InDatesNum                 
  ,DisCount             
  ,Ptypeid            
  ,Qty                  
  ,OtherTotal              
  ,GiftTypeID       
  ,CardTypeID 
  ,BindPtypeId
)
SELECT    PromoRuleID            
         ,PromoStylePtype        
         ,dbo.F_RoundDiscount(PromoStyleDiscount)     
         ,dbo.F_RoundTotal(BuyTotal)                
         ,dbo.F_RoundQty(BuyQty) 
         ,InDatesNum               
         ,dbo.F_RoundDiscount(DisCount)             
         ,Ptypeid            
         ,dbo.F_RoundQty(Qty)                  
         ,dbo.F_RoundPrice(OtherTotal )           
         ,GiftTypeID       
         ,CardTypeID  
         ,BindPtypeId  
FROM @promoRule_Detail_PromotConfig

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：覃雨翔
	时间：2013-05-28
	描述：添加促销会员卡类型明细
*/
CREATE PROC [Gp_InsertPromoRule_Detail_VIPConfigDT]
(
  @promoRule_Detail_VIPConfig TBType_PromoRule_Detail_VIPConfig READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PromoRule_Detail_VIPConfig
(
     PromoRuleID
    ,VipTypeID
)
SELECT PromoRuleID,VipTypeID FROM @promoRule_Detail_VIPConfig

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：覃雨翔
	时间：2013-05-28
	描述：添加促销分支机构明细
*/
CREATE PROC [GP_InsertPromoRule_StypeDT]
(
  @promoRule_Stype TBType_PromoRule_Stype READONLY
)
--@encode$--
AS
SET NOCOUNT ON

INSERT INTO PromoRule_Stype
(
     PromoRuleID
    ,StypeID
)
SELECT PromoRuleID,StypeID FROM @promoRule_Stype

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InsertPromoRuleBillIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_InsertPromoRuleBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
--**********************************************
--编写人:覃雨翔
--用  途:促销规则档案，主表信息存储
--时  间:2013-05-28
--**********************************************
CREATE PROCEDURE Gp_InsertPromoRuleBillIndex
(
     @BillCode                  VARCHAR(200) --单据编号
    ,@FullName                  VARCHAR(200) --活动名称
    ,@PromoStylePtype           INT          --促销模式值商品0=买满金额，1=买够商品
    ,@PromoStyleDiscount        INT          --促销模式之折扣0=减免金额  1=送点券 2=送赠品 3=打折 4=特价
    ,@VIPConfig                 INT          --会员卡设定
    ,@KConfig                   INT          --仓库设定
    ,@EConfig                   INT          --业务员设定
    ,@PConfig                   INT          --商品设定
    ,@CalculateStyle            INT          --计算方式
    ,@BindType                  INT          --捆绑方式
    ,@ReachCondition            INT          --达到条件
    ,@AccumulatedProfits        INT          --累计让利
    ,@DoubleDiscount            INT          --折上有效
    ,@BillState                 INT          --单据状态
    ,@Checke                    VARCHAR(50)  --制单人
    ,@Checker                   VARCHAR(50)  --审核人
    ,@VaildDate                 DATETIME     --审核时间
    ,@CreateDate                DATETIME     --创建时间
    ,@DeletedR                  VARCHAR(50)  --作废人
    ,@DeletedDate               DATETIME     --作废时间
    ,@StartDate                 DATETIME     --生效日期
    ,@EndDate                   DATETIME     --失效时期
    ,@StartTime                 VARCHAR(10)  --起始阶段
    ,@EndTime                   VARCHAR(10)  --结束阶段
    ,@PriceDay                  VARCHAR(7)   --取价日设定
    ,@Comment                   VARCHAR(255) --备注
    ,@GiftsType                 INT          --赠品类别
    ,@BtypeConfig               INT		     --往来单位类别 0=适用全部往来单位,1=适用部分往来单位,2=适用部分结算单位
    ,@promotype					INT			 --0表示每天，1表示每周，2表示每月第几天选项，3表示每月第几周周几选项；当PromoType为2或者3时，前台每月这个选项才生效。
	,@pricemonthday				INT			 --此时PromoType=2，表示每月的第几天，取整值1-31<每月不同>
	,@pricemonthweek			VARCHAR(10)	 --此时PromoType=3，表示每月的第几周的周几，第一个字符表示第几周，第二个字符表示周几，比如“11”，表示当月的第一个周一，第一个字符取值范围1-6，第二个字符取值范围1-7
	,@pricemonthweektype		INT			 --1.第一个选项   2.第二个选项
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @XiWaMaxNumber INT
SELECT TOP 1 @XiWaMaxNumber = ISNULL(XiWaMaxNumber,0) FROM PromoRule ORDER BY XiWaMaxNumber DESC

INSERT INTO PromoRule
(
   BillCode
  ,FullName
  ,PromoStylePtype
  ,PromoStyleDiscount
  ,VIPConfig
  ,KConfig
  ,EConfig
  ,PConfig
  ,CalculateStyle
  ,BindType
  ,ReachCondition
  ,AccumulatedProfits
  ,DoubleDiscount
  ,BillState
  ,Checke
  ,Checker
  ,VaildDate
  ,CreateDate
  ,DeletedR
  ,DeletedDate
  ,StartDate
  ,EndDate
  ,StartTime
  ,EndTime
  ,PriceDay
  ,Comment
  ,GiftsType
  ,XiWaMaxNumber
  ,BtypeConfig
  ,promotype
  ,pricemonthday
  ,pricemonthweek
  ,pricemonthweektype
)
VALUES
(
   @BillCode                
  ,@FullName                 
  ,@PromoStylePtype          
  ,@PromoStyleDiscount       
  ,@VIPConfig               
  ,@KConfig                  
  ,@EConfig                  
  ,@PConfig                  
  ,@CalculateStyle          
  ,@BindType                
  ,@ReachCondition          
  ,@AccumulatedProfits      
  ,@DoubleDiscount           
  ,@BillState                
  ,@Checke                    
  ,@Checker                   
  ,@VaildDate                 
  ,@CreateDate                
  ,@DeletedR                  
  ,@DeletedDate              
  ,@StartDate              
  ,@EndDate            
  ,@StartTime            
  ,@EndTime               
  ,@PriceDay             
  ,@Comment              
  ,@GiftsType
  ,ISNULL(@XiWaMaxNumber,0)+1 
  ,@BtypeConfig     
  ,@promotype
  ,@pricemonthday
  ,@pricemonthweek
  ,@pricemonthweektype
) 

DECLARE @intReturn BIGINT
SELECT  @intReturn = SCOPE_IDENTITY();
RETURN @intReturn




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
韩林：保存零售促销前数据明细
*/
CREATE              PROCEDURE Gp_InsertPromoteRetailBillDT
(
	@details TBType_Retail READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

CREATE TABLE #temp(ID int NULL,BillNumberId INT NULL)
INSERT INTO [dbo].[BeforePromoteRetailBill] 
  ( 
	[BillNumberId],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[TaxPrice],
	[TaxTotal],
	[comment],
	OrderID,
	isUnit2,
	Serial,
	[GoodsNumber],
	[ProduceDate],
	[ValidDate],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost],
	[InputCostPrice],
	Tax,
	SaleTotal,
	STypeID
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,PriceDetailId
	,PriceRuleId
	,PriceSource
	,IsGift
	,etypeid
	,ShowOrder
	,iscombination
	,combinationptypeid
	,pindexid
	,CouponCode
	,IsPromotion
	,IsVipPoint
) 
OUTPUT INSERTED.ID,INSERTED.BillNumberId INTO #temp(id,BillNumberId)
SELECT 
	BillNumberId,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	jobnumber,
	dbo.F_RoundTotal(total),
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	OrderID,
	intIsUnit2,
	Serial,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundPrice(InputCostPrice),
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	STypeID
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoId
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined	
	,dbo.F_RoundQty(InvoiceQty)
	,dbo.F_RoundTotal(InvoiceMoney)
	,dbo.F_RoundTotal(NInvoiceMoney)
	,PriceDetailId
	,PriceRuleId
	,PriceSource
	,IsGift
	,etypeid
	,ShowOrder
	,iscombination
	,combinationptypeid
	,pindexid
	,ISNULL(CouponCode,'')
	,IsPromotion
	,IsVipPoint
	FROM @details

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)

SELECT * FROM #temp
DROP TABLE #temp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
王珏：保存销售单促销前数据明细
*/
CREATE              PROCEDURE Gp_InsertPromoteSaleBillDT
(
	@details TBType_Sale READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

CREATE TABLE #temp(ID int NULL,BillNumberId INT NULL)
INSERT INTO BeforePromoteSaleBill
(
	[BillNumberId],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[OutFactoryDate],
	[TaxPrice],
	[TaxTotal],
	[comment],
	OrderID,
	[isUnit2],
	[Serial],
	[InputCostPrice],
	[GoodsNumber],
	[ProduceDate],
	[ValidDate],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost],
	Tax,
	SaleTotal,
	KTypeID,
	STypeID,
	ShareFee
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,completeqty
	,entryCode
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,PriceSource
	,IsGift
	,ShowOrder
	,iscombination
	,combinationptypeid
	,pindexid
	,etypeid
	,couponcode
	,IsPromotion
	,IsVipPoint
	,PriceDetailId
	,PriceRuleId
)
OUTPUT INSERTED.ID,INSERTED.BillNumberId INTO #temp(id,BillNumberId)
SELECT 
	BillNumberId,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	jobnumber,
	dbo.F_RoundTotal(total),
	OutFactoryDate,
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	OrderID,
	intisUnitTow,
	Serial,
	dbo.F_RoundPrice(InputCostPrice),
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	KTypeID,
	STypeID,
	0
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoId
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined
	,dbo.F_RoundQty(completeqty)
	,entryCode
	,dbo.F_RoundQty(InvoiceQty)
	,dbo.F_RoundTotal(InvoiceMoney)
	,dbo.F_RoundTotal(NInvoiceMoney)
	,PriceSource
	,IsGift
	,ShowOrder
	,iscombination
	,combinationptypeid
	,pindexid
	,ETypeID
	,ISNULL(couponcode,'')
	,IsPromotion
	,IsVipPoint
	,PriceDetailId
	,PriceRuleId
	FROM @details

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)

SELECT * FROM #temp
DROP TABLE #temp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








/*
	作者：谢吉康
	日期：2004-09-02
	描述：判断和修改代理商的信息
*/
CREATE	PROCEDURE GP_InsertProxyInfo(
	@compName	varchar(500),
	@linkaddr	varchar(500),
	@linkphone	varchar(500),
	@email		varchar(500),
	@linkman	varchar(500),
	@note		varchar(8000)
)
--@encode$--
AS
BEGIN
	DELETE FROM ProxyInfo

	INSERT INTO ProxyInfo
	(
		compName,
		linkaddr,
		linkphone,
		email,
		linkman,
		note
	)
	VALUES
	(
		@compName,
		@linkaddr,
		@linkphone,
		@email,
		@linkman,
		@note
	)

	IF @@ROWCOUNT = 0
		--RAISERROR('录入数据失败，请确认后重试！',16,1)
		RETURN -1
	ELSE
		RETURN 0
END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_InsertPtypeInit]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_InsertPtypeInit;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-06-08
	描述：保存库存（先进先出）期初
	2012-07-03 添加默认货位处理
*/
CREATE PROCEDURE Gp_InsertPtypeInit
	@ptypeid VARCHAR(50)
	,@ktypeid VARCHAR(50)
	,@nqty  NUMERIC(24, 10) 
	,@locknumber NUMERIC(24, 10) 
	,@tb TbType_PtypeInit READONLY 
	,@tb1 TbType_StockAge READONLY 
--@encode$--
AS
BEGIN
	DECLARE @c INT=0
	DELETE IniGoodsStocks WHERE Ptypeid=@ptypeid AND Ktypeid=@ktypeid;
	DELETE Ini_GoodsStocks_qty WHERE Ptypeid=@ptypeid AND Ktypeid=@ktypeid;
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='serialRelation' AND Value='1')
	BEGIN
		DELETE gp_initPtypeSerial WHERE PTypeid=@ptypeid AND KTypeId=@ktypeId AND State=1;
	END
	
	IF EXISTS(SELECT 1 FROM @tb)
	BEGIN
		INSERT INTO IniGoodsStocks(
			PtypeId
			,KtypeId
			,JobNumber
			,OutFactoryDate
			,Qty
			,Price
			,Total
			,GoodsOrder
		) SELECT @ptypeid,@ktypeid,'',getdate(),dbo.F_RoundQty(qty),dbo.F_RoundPrice(price),dbo.F_RoundTotal(total),ROW_NUMBER() OVER(ORDER BY GETDATE()) FROM @tb;
		
		SELECT @c=cargoId FROM cargotype WHERE isDefault=1 AND ktypeid=@ktypeid;
		INSERT INTO Ini_GoodsStocks_qty(PTypeId,KTypeId,CargoId,GoodsNumber,Qty,NQty,LockNumber) 
		SELECT @ptypeid,@ktypeid,ISNULL(@c,0),'',dbo.F_RoundQty(SUM(Qty)),dbo.F_RoundQty(@nqty),dbo.F_RoundQty(@locknumber) FROM @tb;
		
		--insert serial
		DECLARE 
		@Serial VARCHAR(8000),
		@STypeID VARCHAR(50),
		@index INT = 1,
		@Id INT 
		
		CREATE TABLE #temp (
			id  INT IDENTITY(1,1),
			id1 INT --qty 明细id
			)

		INSERT INTO #temp (id1)SELECT GoodsOrder FROM IniGoodsStocks  WHERE PtypeId = @ptypeid AND KtypeId = @ktypeid
		SELECT @STypeID = STypeID FROM dbo.Stock  WHERE typeId = @ktypeid	
		
		DECLARE CURSORT CURSOR FOR
		SELECT Serial FROM @tb

		OPEN CURSORT
		FETCH NEXT FROM CURSORT INTO @Serial
		WHILE @@FETCH_STATUS = 0
		BEGIN
		IF @Serial IS NOT NULL AND LTRIM( RTRIM( @Serial)) <> ''
		BEGIN
			SELECT @Id = id1 FROM #temp WHERE id = @index
			IF(CHARINDEX('я',@Serial)=1)
			BEGIN
				SET @Serial = SUBSTRING(@Serial,2,LEN(@Serial)-1)
			END
			INSERT INTO dbo.gp_initPtypeSerial ( Serial, State,Flag,iniFlag,ETypeID,STypeID,KtypeID,PtypeID,GoodsOrder,InKtypeTime,CargoID) 
			SELECT a AS 'Serial',1,1,1,'',@STypeID ,@ktypeid,@ptypeid,@Id,GETDATE() ,@c FROM dbo.f_split(@Serial,'я')
			
			SELECT @index = @index+1
		END
		ELSE
		BEGIN
			SELECT @index = @index+1
		END	
		
		FETCH NEXT FROM CURSORT INTO @Serial 
		
		END
		CLOSE CURSORT
		DEALLOCATE CURSORT

		--insert serial
	END
		--库龄
		DECLARE @CurrentDate VARCHAR(10)
		SELECT @CurrentDate = CONVERT(VARCHAR(10),GETDATE(),23)
		
		UPDATE a SET 
		a.StockAge =  1 + DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStock a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 1
				
		UPDATE a SET 
		a.StockAge =  1 + DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeStype a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 2
		
		UPDATE a SET 
		a.StockAge = 1 +  DATEDIFF(DAY, CONVERT(VARCHAR(10),b.instockdate,23), @CurrentDate ) ,
		a.InStockDate = REPLACE(CONVERT(VARCHAR(10),b.instockdate,23),'/','-')  
		FROM dbo.IniStockAgeGroup a JOIN @tb1 b ON a.ID = b.ID WHERE b.TYPE = 3
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		维修调度的派工明细
-- 最后修改：		毛欣蓉
-- 修改时间：		2011-05-12
-- ========================================================================
CREATE    PROCEDURE Gp_InsertQp_AttemperBill_RepairItemsPerson
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 值
	@RepairItemsID	varchar(50),
	@EtypeId			varchar(50),
	@AllocateDate		DateTime,
	@AllocateHour		 NUMERIC(24, 10) ,
	@CheckHour			 NUMERIC(24, 10) ,
	@Total				 NUMERIC(24, 10) ,
	@CostTotal			 NUMERIC(24, 10) 
)
--@encode$--
AS

	SET NOCOUNT ON
	-- 写入数据表
	INSERT INTO Qp_AttemperBill_RepairItemsPerson
	(
		BillNumberID,
		RepairItemsID,
		Etypeid,
		AllocateDate,
		AllocateHour,
		CheckHour,
		Total,
		CostTotal
	)
	VALUES
	(
		@BillNumberID,	
		@RepairItemsID,
		@EtypeId,
		@AllocateDate,
		@AllocateHour,
		@CheckHour,
		dbo.F_RoundTotal(@Total),
		dbo.F_RoundTotal(@CostTotal)		
	)

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		维修结算单维修项目明细表
-- 最后修改：		冯波
-- 修改时间：		2011-05-05
-- ========================================================================

CREATE             PROCEDURE Gp_InsertQp_BalanceBill_RepairItems
(
	@BillNumberID		numeric(18,0),	-- 单据 ID 值
	@RepairItemsTypeID	varchar(50)='',
	@StandardManHour	 NUMERIC(24, 10) ,
	@CheckHour			 NUMERIC(24, 10) ,
	@Total				 NUMERIC(24, 10) ,
	@CostTotal			 NUMERIC(24, 10) ,
	@RepairProcess		INT,
	@StopReason			VARCHAR(250),
	@RepairMan			VARCHAR(100),
	@StopTime			DATETIME,
	@Discount			 NUMERIC(24, 10) ,
	@DiscountTotal		 NUMERIC(24, 10) ,
	@Insurance			INT,
	@Comment			VARCHAR(500),
	@Virtual			INT,
	@AppointTime		DATETIME,
	@ID					numeric(18,0)=0
)
--@encode$--
AS

	SET NOCOUNT ON
	-- 写入数据表
	
	DECLARE	@intReturn	BIGINT
	
	IF @Virtual=1
	BEGIN
		INSERT INTO Qp_ReceptionBill_RepairItems
		(
			BillNumberID,
			RepairItemsTypeID,
			StandardManHour,
			CheckHour,
			Total,
			CostTotal,
			RepairProcess,
			StopReason,
			RepairMan,
			StopTime,
			Discount,
			DiscountTotal,
			Insurance,
			Comment,
			Virtual,
			AppointTime
		)
		VALUES
		(
			@BillNumberID,
			@RepairItemsTypeID,
			@StandardManHour,
			@CheckHour,
			dbo.F_RoundTotal(@Total),
			dbo.F_RoundTotal(@CostTotal),
			@RepairProcess,
			@StopReason,
			@RepairMan,
			@StopTime,
			dbo.F_RoundDiscount(@Discount),
			dbo.F_RoundTotal(@DiscountTotal),
			@Insurance,
			@Comment,
			@Virtual,
			@AppointTime
		)
		
		SELECT @intReturn=SCOPE_IDENTITY();
	END
	ELSE
	BEGIN
		SELECT @intReturn=@ID
		UPDATE
			Qp_ReceptionBill_RepairItems
		SET	
			RepairItemsTypeID=@RepairItemsTypeID,
			StandardManHour=@StandardManHour,
			CheckHour=@CheckHour,
			Total=dbo.F_RoundTotal(@Total),
			CostTotal=dbo.F_RoundTotal(@CostTotal),
			RepairProcess=@RepairProcess,
			StopReason=@StopReason,
			RepairMan=@RepairMan,
			StopTime=@StopTime,
			Discount=dbo.F_RoundDiscount(@Discount),
			DiscountTotal=dbo.F_RoundTotal(@DiscountTotal),
			Insurance=@Insurance,
			Comment=@Comment,
			Virtual=@Virtual,
			AppointTime=@AppointTime
		WHERE ID=@ID
	
	END
	
	



	
	return @intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



/*
写入发票明细表
*/
CREATE PROCEDURE [Gp_InsertQP_InvoiceOtherTotalDetails]
(
	@BillNumberId  		[numeric](10,0),
	@BillType			[int],
	@MainBillNumberID	[numeric](10,0),
	@Total   			 NUMERIC(24, 10) ,
	@STypeID			[varchar](50)=''
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[QP_InvoiceOtherTotalDetails] 
  ( 
	[BillNumberId],
	[BillType],
	[MainBillNumberID],
	[total],
	STypeID
) 
 
VALUES 
 ( 
	@BillNumberId,
	@BillType,
	@MainBillNumberID,
	dbo.F_RoundTotal(@total),
	@STypeID
)
if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



/*
写入发票明细表
*/
CREATE PROCEDURE [Gp_InsertQP_InvoiceRepairItems]
(
	@BillNumberId  		[numeric](10,0),
	@BillType			[int],
	@MainBillNumberID	[numeric](10,0),
	@RepairItemsTypeID  [varchar](100),
	@Total   			 NUMERIC(24, 10) ,
	@Tax   				 NUMERIC(24, 10) ,
	@TaxTotal  			 NUMERIC(24, 10) ,
	@Comment  			[varchar](255),
	@STypeID			[varchar](50)=''
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[QP_InvoiceRepairItems] 
  ( 
	[BillNumberId],
	[BillType],
	[MainBillNumberID],
	RepairItemsTypeID,
	[total],
	[Tax],
	[TaxTotal],
	[comment],
	STypeID
) 
 
VALUES 
 ( 
	@BillNumberId,
	@BillType,
	@MainBillNumberID,
	@RepairItemsTypeID,
	dbo.F_RoundTotal(@total),
	dbo.F_RoundTax(@Tax),
	dbo.F_RoundTotal(@TaxTotal),
	@Comment,
	@STypeID
)
if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		接待登记单随车附件明细表
-- 最后修改：		冯波
-- 修改时间：		2011-05-06
-- ========================================================================
------2002-4-16日加orderid
CREATE             PROCEDURE Gp_InsertQp_ReceptionBill_Accessory
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 值
	@Items				VARCHAR(100),
	@OtherAccessory		VARCHAR(1000)

)
--@encode$--
AS

	SET NOCOUNT ON
	-- 写入数据表
	INSERT INTO Qp_ReceptionBill_Accessory
	(
		BillNumberID,
		Items,
		OtherAccessory
	)
	VALUES
	(
		@BillNumberID,
		@Items,
		@OtherAccessory
	)

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		接待登记单保险明细表
-- 最后修改：		冯波
-- 修改时间：		2011-05-06
-- ========================================================================
------2002-4-16日加orderid
CREATE             PROCEDURE Gp_InsertQp_ReceptionBill_Insurance
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 值
	@BTypeId			Varchar(50),
	@AccidentDate		DateTime,	
	@AccidentAddr		Varchar(1000),
	@AccidentReason		Varchar(2000)

)
--@encode$--
AS

	SET NOCOUNT ON
	-- 写入数据表
	INSERT INTO Qp_ReceptionBill_Insurance
	(
		BillNumberID,
		BTypeID,
		AccidentAddr,
		AccidentDate,
		AccidentReason
	)
	VALUES
	(
		@BillNumberID,
		@BTypeID,
		@AccidentAddr,
		@AccidentDate,
		@AccidentReason
		
	)

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		接待登记单维修配件明细表
-- 最后修改：		冯波
-- 修改时间：		2011-05-06
-- ========================================================================
------2002-4-16日加orderid
CREATE             PROCEDURE Gp_InsertQp_ReceptionBill_PType
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 值
	@PTypeID			VARCHAR(50),
	@Qty				 NUMERIC(24, 10) ,
	@Price				 NUMERIC(24, 10) ,
	@Total				 NUMERIC(24, 10) ,
	@Insurance			INT,
	@Comment			VARCHAR(500)=''
)
--@encode$--
AS

	SET NOCOUNT ON
	-- 写入数据表
	INSERT INTO Qp_ReceptionBill_PType
	(
		BillNumberID,
		PTypeID,
		Qty,
		Price,
		Total,
		Insurance,
		Comment,
		Discount,
		DiscountPrice,
		DiscountTotal
	)
	VALUES
	(
		@BillNumberID,
		@PTypeID,
		dbo.F_RoundQty(@Qty),
		dbo.F_RoundPrice(@Price),
		dbo.F_RoundTotal(@Total),
		@Insurance,
		@Comment,
		1,
		dbo.F_RoundPrice(@Price),
		dbo.F_RoundTotal(@Total)
		
	)

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		接待登记单维修项目明细表
-- 最后修改：		冯波
-- 修改时间：		2011-05-05
-- ========================================================================
------2002-4-16日加orderid
CREATE             PROCEDURE Gp_InsertQp_ReceptionBill_RepairItems
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 值
	@RepairItemsTypeID	varchar(50)='',
	@StandardManHour	 NUMERIC(24, 10) ,
	@CheckHour			 NUMERIC(24, 10) ,
	@Total				 NUMERIC(24, 10) ,
	@CostTotal			 NUMERIC(24, 10) ,
	@RepairProcess		INT,
	@StopReason			VARCHAR(250),
	@RepairMan			VARCHAR(100),
	@StopTime			DATETIME,
	@Discount			 NUMERIC(24, 10) ,
	@DiscountTotal		 NUMERIC(24, 10) ,
	@Insurance			INT,
	@Comment			VARCHAR(500)='',
	@Virtual			INT,
	@AppointTime		DATETIME
)
--@encode$--
AS


	SET NOCOUNT ON
	-- 写入数据表
	INSERT INTO Qp_ReceptionBill_RepairItems
	(
		BillNumberID,
		RepairItemsTypeID,
		StandardManHour,
		CheckHour,
		Total,
		CostTotal,
		RepairProcess,
		StopReason,
		RepairMan,
		StopTime,
		Discount,
		DiscountTotal,
		Insurance,
		Comment,
		Virtual,
		AppointTime
	)
	VALUES
	(
		@BillNumberID,
		@RepairItemsTypeID,
		@StandardManHour,
		@CheckHour,
		dbo.F_RoundTotal(@Total),
		dbo.F_RoundTotal(@CostTotal),
		@RepairProcess,
		@StopReason,
		@RepairMan,
		@StopTime,
		dbo.F_RoundDiscount(@Discount),
		dbo.F_RoundTotal(@DiscountTotal),
		@Insurance,
		@Comment,
		@Virtual,
		@AppointTime
	)
	
	DECLARE
	@intReturn	BIGINT

	SELECT @intReturn=SCOPE_IDENTITY();
	
	return @intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
快修单_-配件明细表
*/
CREATE       PROCEDURE Gp_InsertQuickRepair_PType
(
	@BillNumberID			[numeric](10,0),
	@PTypeID				varchar(50),
	@KTypeID				varchar(50),
	@CargoSpace				varchar(200),
	@Qty					 NUMERIC(24, 10) ,
	@Price					 NUMERIC(24, 10) ,
	@Total					 NUMERIC(24, 10) ,
	@Discount				 NUMERIC(24, 10) ,
	@DiscountPrice			 NUMERIC(24, 10) ,
	@DiscountTotal			 NUMERIC(24, 10) ,
	@RepairManTypeID		varchar(50),
	@Comment				varchar(250),
	@IsUnit2				int,
	@InputCostPrice			 NUMERIC(24, 10) ,
	@HandZeroCost			int,
	@Insurance				int,
	@STypeID				varchar(50)=''
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO QP_QuickRepairBill_PType
(
	[BillNumberID],
	[PTypeID],
	[KTypeID],
	[CargoSpace],
	[Qty],
	[Price],
	[Total],
	[Discount],
	[DiscountPrice],
	[DiscountTotal],
	[RepairManTypeID],
	[Comment],
	[IsUnit2],
	[InputCostPrice],
	[HandZeroCost],
	[Insurance],
	[STypeID]
)
VALUES
(
	@BillNumberID,
	@PTypeID,
	@KTypeID,
	@CargoSpace,
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@Price),
	dbo.F_RoundTotal(@Total),
	dbo.F_RoundDiscount(@Discount),
	dbo.F_RoundPrice(@DiscountPrice),
	dbo.F_RoundTotal(@DiscountTotal),
	ISNULL(@RepairManTypeID,''),
	ISNULL(@Comment,''),
	@IsUnit2,
	dbo.F_RoundPrice(@InputCostPrice),
	@HandZeroCost,
	@Insurance,
	@STypeID
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
备料估价单_-维修项目明细表
*/
CREATE       PROCEDURE Gp_InsertQuickRepair_RepairItems
(
	@BillNumberID			[numeric](10,0),
	@RepairItemsTypeID		varchar(50),
	@StandardManHour		 NUMERIC(24, 10) ,
	@CheckHour				 NUMERIC(24, 10) ,
	@Total					 NUMERIC(24, 10) ,
	@Discount				 NUMERIC(24, 10) ,
	@DiscountTotal			 NUMERIC(24, 10) ,
	@RepairManTypeID		varchar(50),
	@Comment				varchar(250),
	@Insurance				INT,
	@CostTotal				 NUMERIC(24, 10) ,
	@STypeID				varchar(50)=''
)
--@encode$--
AS 
SET NOCOUNT ON



INSERT INTO QP_QuickRepairBill_RepairItems
(
	[BillNumberID],
	[RepairItemsTypeID],
	[StandardManHour],
	[CheckHour],
	[Total],
	[Discount],
	[DiscountTotal],
	[RepairManTypeID],
	[Comment],
	Insurance,
	CostTotal,
	STypeID
)
VALUES
(
	@BillNumberID,
	ISNULL(@RepairItemsTypeID,''),
	@StandardManHour,
	@CheckHour,
	dbo.F_RoundTotal(@Total),
	dbo.F_RoundDiscount(@Discount),
	dbo.F_RoundTotal(@DiscountTotal),
	ISNULL(@RepairManTypeID,''),
	@Comment,
	@Insurance,
	dbo.F_RoundTotal(@CostTotal),
	@STypeID
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		采购入库单明细数据写入
-- 最后修改：		卢春
-- 修改时间：		2003-03-17
-- ========================================================================
------2002-4-16日加orderid
CREATE             PROCEDURE Gp_InsertQuotePriceBill
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 值
	@PtypeID			varchar(50),	-- 商品 ID 值
	@Qty				 NUMERIC(24, 10) ,	-- 商品数量
	@Price				 NUMERIC(24, 10) ,	-- 商品单价
	@SaleTotal			 NUMERIC(24, 10) ,
	@Discount			 NUMERIC(24, 10) ,	-- 
	@DiscountPrice		 NUMERIC(24, 10) ,	-- 折后单价
	@Total				 NUMERIC(24, 10) ,	-- 商品金额
	@Tax				 NUMERIC(24, 10) ,
	@TaxPrice			 NUMERIC(24, 10) ,	-- 税后单价
	@TaxTotal			 NUMERIC(24, 10) ,	-- 价税合计
	@Comment			varchar(255),	-- 备注
	@intIsUnit2			int,			-- 是否采用双单位。0：否；1：是
	@STypeID			varchar(50)=''
)
--@encode$--
AS
	SET NOCOUNT ON
	-- 写入数据表
	INSERT INTO QuotePriceBill
	(
		BillNumberID,
		PTypeID,
		Qty,
		Price,
		SaleTotal,
		Discount,
		DiscountPrice,
		total,
		Tax,
		TaxPrice,
		TaxTotal,
		Comment,
		isUnit2,
		STypeID
	)
	VALUES
	(
		@BillNumberID,
		@PTypeID,
		dbo.F_RoundQty(@Qty),
		dbo.F_RoundPrice(@Price),
		dbo.F_RoundTotal(@SaleTotal),
		dbo.F_RoundDiscount(@Discount),
		dbo.F_RoundPrice(@DiscountPrice),
		dbo.F_RoundTotal(@Total),
		dbo.F_RoundTax(@Tax),
		dbo.F_RoundPrice(@TaxPrice),
		dbo.F_RoundTotal(@TaxTotal),
		@Comment,
		@intIsUnit2,
		@STypeID
	)

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：廖晨羽
描述：写入报价单单明细表(表值)
*/
CREATE              PROCEDURE [Gp_InsertQuotePriceBillDT]
(
	@details TBType_QuotePrice READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

-- 写入数据表
	INSERT INTO QuotePriceBill
	(
		BillNumberID,
		PTypeID,
		Qty,
		Price,
		SaleTotal,
		Discount,
		DiscountPrice,
		total,
		Tax,
		TaxPrice,
		TaxTotal,
		Comment,
		isUnit2,
		STypeID
		-- 9.0新字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		
		,ExpectedInterest
		,ExpectedInterestRate
		,IfBargainOn
		,ShowOrder
		,UseQty
	) SELECT
		BillNumberID,
		PTypeID,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(Price),
		dbo.F_RoundTotal(SaleTotal),
		dbo.F_RoundDiscount(Discount),
		dbo.F_RoundPrice(DiscountPrice),
		dbo.F_RoundTotal(Total),
		dbo.F_RoundTax(Tax),
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		Comment,
		intIsUnit2,
		STypeID		
		-- 9.0新字段
		,dbo.F_RoundTotal(TaxMoney) 
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,ExpectedInterest
		,dbo.F_RoundPercentage(ExpectedInterestRate)
		,IfBargainOn
		,ShowOrder
		,0
	FROM @details;

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'Gp_InsertReceiptBillDT',N'P'))
BEGIN
	DROP PROC dbo.Gp_InsertReceiptBillDT;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
		作者：司华山
		日期：2015-05-14
		描述：新增发票明细
*/
CREATE PROC dbo.Gp_InsertReceiptBillDT
(
	@Details TbType_ReceiptBill READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
    DELETE  A
    FROM  dbo.ReceiptBill A ,@Details B WHERE A.BillNumberID=B.BillNumberID
		AND NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID
												 AND A.BillNumberID=B.BillNumberID
												 AND A.MainBillNumberID=B.MainBillNumberID
												 AND A.MainBillType=B.MainBillType
												 AND A.RecordedItemId=B.RecordedItemId
												 AND B.ID<>0)

	INSERT INTO dbo.ReceiptBill([BillNumberID],
							[BillType],
							[MainBillNumberID],
							[KTypeID],
							[PTypeID],
							[Qty],
							[Price],
							[Total],
							[Tax],
							[TaxPrice],
							[TaxTotal],
							[Comment],
							[Stypeid],
							[discount],
							[BeforePrice],
							[BeforeTotal],
							[RecordedItemId],
							[Nprice],
							[NTotal],
							[NTaxPrice],
							[NTaxTotal],
							[NTaxMoney],
							[CargoID],
							[UnitID],
							[NUnitID],
							[NQty],
							[UnitRate],
							[NUnitMsg],
							[MUnitID],
							[MQty],
							[MUnitRate],
							[MUnitMsg],
							[MPrice],
							[MTaxPrice],
							[CurMPrice],
							[CurMTaxPrice],
							[ItemID],
							[IsCombined],
							[Nbeforeprice],
							[Nbeforetotal],
							[goodsnumber],
							[saleprice],
							[saletotal],
							[nsaleprice],
							[nsaletotal],
							[curmsaleprice],
							[curmsaletotal],
							[taxmoney],
							[CompleteQty],
							[CompleteTotal],
							[NCompleteTotal],
							[IsGift],
							[TeamNo],
							[TeamNO1],
							[InvoiceCostTotal],
							[MainBillType],
							[InvoiceCostPrice],
							[ProduceDate],
							[ValidDate],
							[Serial],
							[ShowOrder]
							)
	SELECT					BillNumberID,
							BillType,
							MainBillNumberID,
							KTypeID,
							PTypeID,
							dbo.F_RoundQty(Qty),
							dbo.F_RoundPrice(Price),
							dbo.F_RoundTotal(Total),
							dbo.F_RoundTax(Tax),
							dbo.F_RoundPrice(TaxPrice),
							dbo.F_RoundTotal(TaxTotal),
							Comment,
							Stypeid,
							dbo.F_RoundDiscount(discount),
							dbo.F_RoundPrice(BeforePrice),
							dbo.F_RoundTotal(BeforeTotal),
							RecordedItemId,
							dbo.F_RoundPrice(Nprice),
							dbo.F_RoundTotal(NTotal),
							dbo.F_RoundPrice(NTaxPrice),
							dbo.F_RoundTotal(NTaxTotal),
							dbo.F_RoundTotal(NTaxMoney),
							CargoID,
							UnitID,
							NUnitID,
							dbo.F_RoundQty(NQty),
							dbo.F_RoundTranslateRate(UnitRate),
							NUnitMsg,
							MUnitID,
							dbo.F_RoundQty(MQty),
							dbo.F_RoundTranslateRate(MUnitRate),
							MUnitMsg,
							dbo.F_RoundPrice(MPrice),
							dbo.F_RoundPrice(MTaxPrice),
							dbo.F_RoundPrice(CurMPrice),
							dbo.F_RoundPrice(CurMTaxPrice),
							ItemID,
							IsCombined,
							dbo.F_RoundPrice(Nbeforeprice),
							dbo.F_RoundTotal(Nbeforetotal),
							goodsnumber,
							dbo.F_RoundPrice(saleprice),
							dbo.F_RoundTotal(saletotal),
							dbo.F_RoundPrice(nsaleprice),
							dbo.F_RoundTotal(nsaletotal),
							dbo.F_RoundPrice(curmsaleprice),
							dbo.F_RoundTotal(curmsaletotal),
							dbo.F_RoundTotal(taxmoney),
							dbo.F_RoundQty(CompleteQty),
							dbo.F_RoundTotal(CompleteTotal),
							dbo.F_RoundTotal(NCompleteTotal),
							IsGift,
							TeamNo,
							TeamNO1,
							dbo.F_RoundTotal(InvoiceCostTotal),
							MainBillType,
							dbo.F_RoundPrice(InvoiceCostPrice),
							ProduceDate,
							ValidDate,
							Serial,
							ShowOrder
	FROM @Details A WHERE A.ID=0 OR NOT EXISTS(
			  SELECT ID FROM dbo.ReceiptBill B WHERE A.ID=B.ID
												 AND A.BillNumberID=B.BillNumberID
												 AND A.MainBillNumberID=B.MainBillNumberID
												 AND A.MainBillType=B.MainBillType
												 AND A.RecordedItemId=B.RecordedItemId
												 AND A.BillType=B.BillType)
	
	UPDATE A	SET		A.[BillType]			= B.[BillType],
						A.[MainBillNumberID]	= B.[MainBillNumberID],
						A.[KTypeID]				= B.[KTypeID],
						A.[PTypeID]				= B.[PTypeID],
						A.[Qty]					= B.[Qty],
						A.[Price]				= B.[Price],
						A.[Total]				= B.[Total],
						A.[Tax]					= B.[Tax],
						A.[TaxPrice]			= B.[TaxPrice],
						A.[TaxTotal]			= B.[TaxTotal],
						A.[Comment]				= B.[Comment],
						A.[Stypeid]				= B.[Stypeid],
						A.[discount]			= B.[discount],
						A.[BeforePrice]			= B.[BeforePrice],
						A.[BeforeTotal]			= B.[BeforeTotal],
						A.[RecordedItemId]		= B.[RecordedItemId],
						A.[Nprice]				= B.[Nprice],
						A.[NTotal]				= B.[NTotal],
						A.[NTaxPrice]			= B.[NTaxPrice],
						A.[NTaxTotal]			= B.[NTaxTotal],
						A.[NTaxMoney]			= B.[NTaxMoney],
						A.[CargoID]				= B.[CargoID],
						A.[UnitID]				= B.[UnitID],
						A.[NUnitID]				= B.[NUnitID],
						A.[NQty]				= B.[NQty],
						A.[UnitRate]			= B.[UnitRate],
						A.[NUnitMsg]			= B.[NUnitMsg],
						A.[MUnitID]				= B.[MUnitID],
						A.[MQty]				= B.[MQty],
						A.[MUnitRate]			= B.[MUnitRate],
						A.[MUnitMsg]			= B.[MUnitMsg],
						A.[MPrice]				= B.[MPrice],
						A.[MTaxPrice]			= B.[MTaxPrice],
						A.[CurMPrice]			= B.[CurMPrice],
						A.[CurMTaxPrice]		= B.[CurMTaxPrice],
						A.[ItemID]				= B.[ItemID],
						A.[IsCombined]			= B.[IsCombined],
						A.[Nbeforeprice]		= B.[Nbeforeprice],
						A.[NBeforeTotal]		= B.[NBeforeTotal],
						A.[goodsnumber]			= B.[goodsnumber],
						A.[saleprice]			= B.[saleprice],
						A.[saletotal]			= B.[saletotal],
						A.[nsaleprice]			= B.[nsaleprice],
						A.[nsaletotal]			= B.[nsaletotal],
						A.[curmsaleprice]		= B.[curmsaleprice],
						A.[curmsaletotal]		= B.[curmsaletotal],
						A.[taxmoney]			= B.[taxmoney],
						A.[CompleteQty]			= B.[CompleteQty],
						A.[CompleteTotal]		= B.[CompleteTotal],
						A.[NCompleteTotal]		= B.[NCompleteTotal],
						A.[IsGift]				= B.[IsGift],
						A.[TeamNo]				= B.[TeamNo],
						A.[TeamNO1]				= B.[TeamNO1],
						A.[InvoiceCostTotal]	= B.[InvoiceCostTotal],
						A.[MainBillType]		= B.[MainBillType],
						A.[InvoiceCostPrice]	= B.[InvoiceCostPrice],
						A.[ProduceDate]			= B.[ProduceDate],
						A.[ValidDate]			= B.[ValidDate],
						A.[Serial]				= B.[Serial],
						A.[ShowOrder]			= B.[ShowOrder]
	FROM dbo.ReceiptBill A ,@Details B WHERE A.ID=B.ID
										 AND A.BillNumberID=B.BillNumberID
									     AND A.MainBillNumberID=B.MainBillNumberID
										 AND A.MainBillType=B.MainBillType
										 AND A.RecordedItemId=B.RecordedItemId
										 AND A.BillType=B.BillType
	
	SET NOCOUNT OFF
END
Go

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.Gp_InsertReceiptBillIndex',N'P'))
BEGIN
	DROP PROC dbo.Gp_InsertReceiptBillIndex;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*
			作者：司华山
			日期：2015-05-14
			描述：新增发票主表记录
*/

CREATE PROC dbo.Gp_InsertReceiptBillIndex
(
	@BillDate				DATETIME,
	@BillCode				VARCHAR(200),
	@BillType				NUMERIC(4,0),
	@FaPiaoType				CHAR(1),
	@FaPiaoCode				VARCHAR(256),
	@Comment				VARCHAR(256),
	@Explain				VARCHAR(256),
	@BTypeID				VARCHAR(100),
	@ETypeID			    VARCHAR(100),
	@DTypeID				VARCHAR(100),
	@checke					VARCHAR(100),
	@Tax					 NUMERIC(24, 10) ,
	@TotalQty				 NUMERIC(24, 10) ,
	@TotalMoney				 NUMERIC(24, 10) ,
	@TaxTotalMoney			 NUMERIC(24, 10) ,
	@Stypeid				VARCHAR(50),
	@OtherTotal				 NUMERIC(24, 10) ,
	@ifYearBill				INT,
	@IsIni					BIT,
	@CID					INT,
	@Rate					 NUMERIC(24, 10) ,
	@NTotalMoney			 NUMERIC(24, 10) ,
	@NTaxTotalMoney			 NUMERIC(24, 10) ,
	@DealBTypeID			VARCHAR(50),
	@TaskType				TINYINT,
	@AlertDay				INT,
	@RedWord				INT,
	@ifcheck				CHAR(1), 
	@IfStopMoney			INT, 
	@CompleteTotal			 NUMERIC(24, 10)  ,
	@NCompleteTotal			 NUMERIC(24, 10)  ,
	@Draft					BIT,
	@JSState				CHAR(1),
	@JSStyle				CHAR(1),
	@Poster					VARCHAR(100)  ,
	@UpdateE				VARCHAR(100),
	@IfAudit				CHAR(1),
	@ATypeID1				VARCHAR(50),
	@ATypeID2				VARCHAR(50),
	@ATID					INT,
	@Reconciliation			CHAR(1),
	@ChargeOffTotal			NUMERIC(24, 10) ,
	@NChargeOffTotal		NUMERIC(24, 10) 
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	INSERT INTO ReceiptBillIndex(BillDate				
								 ,BillCode				
								 ,BillType				
								 ,FaPiaoType				
								 ,FaPiaoCode				
								 ,Comment				
								 ,Explain				
								 ,BTypeID				
								 ,ETypeID			  
								 ,DTypeID				
								 ,checke					
								 ,Assessor				
								 ,Tax					
								 ,TotalQty				
								 ,TotalMoney				
								 ,TaxTotalMoney			
								 ,Stypeid				
								 ,OtherTotal			
								 ,ifYearBill				
								 ,IsIni					
								 ,CID					
								 ,Rate					
								 ,NTotalMoney			
								 ,NTaxTotalMoney			
								 ,DealBTypeID			
								 ,TaskType				
								 ,AlertDay				
								 ,RedWord				
								 ,ifcheck				
								 ,IfStopMoney			
								 ,CompleteTotal			
								 ,NCompleteTotal			
								 ,Draft					
								 ,JSState				
								 ,JSStyle				
								 ,Poster					
								 ,LastUpdateTime			
								 ,checkTime				
								 ,UpdateE				
								 ,IfAudit				
								 ,ATypeID1				
								 ,ATypeID2
								 ,ATID
								 ,Reconciliation
								 ,ChargeOffTotal	
								 ,NChargeOffTotal
								)
						  VALUES(@BillDate				
								 ,@BillCode				
								 ,@BillType				
								 ,@FaPiaoType				
								 ,@FaPiaoCode				
								 ,@Comment				
								 ,@Explain				
								 ,@BTypeID				
								 ,@ETypeID			  
								 ,@DTypeID				
								 ,@checke					
								 ,''				
								 ,dbo.F_RoundTax(@Tax)					
								 ,dbo.F_RoundQty(@TotalQty)				
								 ,dbo.F_RoundTotal(@TotalMoney)				
								 ,dbo.F_RoundTotal(@TaxTotalMoney)			
								 ,@Stypeid				
								 ,dbo.F_RoundTotal(@OtherTotal)			
								 ,@ifYearBill				
								 ,@IsIni					
								 ,@CID					
								 ,dbo.F_RoundExchangeRate(@Rate)				
								 ,dbo.F_RoundTotal(@NTotalMoney)			
								 ,dbo.F_RoundTotal(@NTaxTotalMoney)			
								 ,@DealBTypeID			
								 ,@TaskType				
								 ,@AlertDay				
								 ,@RedWord				
								 ,@ifcheck				
								 ,@IfStopMoney			
								 ,dbo.F_RoundTotal(@CompleteTotal)			
								 ,dbo.F_RoundTotal(@NCompleteTotal)			
								 ,@Draft					
								 ,@JSState				
								 ,@JSStyle				
								 ,@Poster					
								 ,NULL			
								 ,GETDATE()					
								 ,@UpdateE				
								 ,@IfAudit				
								 ,@ATypeID1				
								 ,@ATypeID2
								 ,@ATID
								 ,@Reconciliation
								 ,@ChargeOffTotal
								 ,@NChargeOffTotal
								)
	IF @@ERROR<>0 or @@ROWCOUNT=0
		RETURN -1
	ELSE
		RETURN SCOPE_IDENTITY();
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

















--**********************************************
--存储过程修改记录
--1.修改原因:a.增加过帐时根据配置判断是否允许过帐日期与当前日期不一致的问题 b.增加ID字段用于物理顺序
--2.修改方法:增加
--3.结果:成功
--4.修改人:肖伟
--5.Last修改时间:2002-10-28
--**********************************************
CREATE             PROCEDURE [Gp_InsertRepairDeal]
(
@billnumberid	numeric(10,0),
@EngageBillID	numeric(10,0),
@BillDate		datetime,
@BillCode		varchar(200), -- #&**&#
@Stat			int	= 1,	-- 处理状态,1-已受理 2-已取件
@Fault			varchar(500)	= '',	-- 受理时故障描述
@Comment		varchar(500)	= '',	-- 受理时检测备注
@Method			int	= 0, -- 维修方法 0-本地直接维修1-更换备件2-报价维修3-返厂维修4-换货
@MoneyRepair	 NUMERIC(24, 10) 	= '', -- 维修费用小计
@NotFree		int	= 1,	-- 是否收费 0-免费1-收费
@FreeMemo		varchar(200)	= '', -- 如果免费，填写免费理由。
@ETypeID		varchar(50)	= '',
@ETypeID1		varchar(50)	 = '',	-- 维修工程师
@ETypeID2		varchar(50)	 = '',	-- 检测划价人
@PayDate		datetime	= '',	-- 取件时间
@IfPay			int	= '',	-- 是否已经取件 0-未取件 1-已取件
@IDCard			varchar(30)	= '',	-- 取件人身份证号码
@KTypeID1		varchar(50) = '',
@KTypeID2		varchar(50) = '',
@IfCheck		varchar(2),
@Draft			bit,
@RedWord		int
)
--@encode$--
AS 
SET NOCOUNT ON

--delete from RepairDeal where billnumberid = @billnumberid


INSERT INTO [dbo].[RepairDeal] 
  (
billnumberid,
EngageBillID,
BillDate,
BillCode,
Stat,	-- 处理状态,1-已受理 2-已取件
Fault,	-- 受理时故障描述
Comment,	-- 受理时检测备注
Method, -- 维修方法 0-本地直接维修1-更换备件2-报价维修3-返厂维修4-换货
MoneyRepair, -- 维修费用小计
NotFree,	-- 是否收费 0-免费1-收费
FreeMemo, -- 如果免费，填写免费理由。
ETypeID,
ETypeID1,	-- 维修工程师
ETypeID2,	-- 检测划价人
PayDate,
IfPay,	-- 是否已经取件 0-未取件 1-已取件
IDCard,	-- 取件人身份证号码
KTypeID1,
KTypeID2,
IfCheck,
Draft,
RedWord
) 
 
VALUES 
 (
@billnumberid,
@EngageBillID,
@BillDate,
@BillCode,
@Stat,	-- 处理状态,1-已受理 2-已取件
@Fault,	-- 受理时故障描述
@Comment,	-- 受理时检测备注
@Method, -- 维修方法 0-本地直接维修1-更换备件2-报价维修3-返厂维修4-换货
dbo.F_RoundTotal(@MoneyRepair), -- 维修费用小计
@NotFree,	-- 是否收费 0-免费1-收费
@FreeMemo, -- 如果免费，填写免费理由。
@ETypeID,
@ETypeID1,	-- 维修工程师
@ETypeID2,	-- 检测划价人
@PayDate,
@IfPay,	-- 是否已经取件 0-未取件 1-已取件
@IDCard,	-- 取件人身份证号码
@KTypeID1,
@KTypeID2,
@IfCheck,
@Draft,
@RedWord
)
/*
if @@rowcount =0  or @@error<>0
  --RAISERROR('更新单据发生错误！',16,1)
else
 return 0
*/













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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




/*
维修受理单明细
*/
CREATE          PROCEDURE Gp_InsertRepairDealDetail
(
	@BillNumberId  	[numeric](10,0),
	@InOrOut  		[char](1),
	@PtypeId 		[varchar](50),
	@Qty   			 NUMERIC(24, 10) ,
	@SalePrice  	 NUMERIC(24, 10) ,
	@Discount  		 NUMERIC(24, 10) ,
	@DiscountPrice   NUMERIC(24, 10) ,
	@Jobnumber  	[varchar](20),
	@Total   		 NUMERIC(24, 10) ,
	@OutFactoryDate [datetime]=Null,
	@TaxPrice  		 NUMERIC(24, 10) ,
	@TaxTotal  		 NUMERIC(24, 10) ,
	@Comment  		[varchar](255),
	@intisUnitTow 	[int],
	--@Serial		varchar(50)
	@Serial			varchar(MAX),				--序列号值
	@InputCostPrice	 NUMERIC(24, 10) =0,	--成本单价
	@GoodsNumber	varchar(100) = '',	-- 批号
	@ProduceDate	varchar(50) = '',	-- 生产日期
	@ValidDate		varchar(50) = '',	-- 效期至
	@GoodsBTypeID	varchar(50) = '',	-- 供货商ID值
	@GoodsCostPrice	 NUMERIC(24, 10)  = 0,	-- 出库批次成本单价
	@HandZeroCost	int = 0				-- 手工指定成本单价
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[RepairDealDetail] 
  ( 
	[BillNumberId],
	[InOrOut],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[OutFactoryDate],
	[TaxPrice],
	[TaxTotal],
	[comment],
	[isUnit2],
	[Serial],
	[InputCostPrice],
	[GoodsNumber],
	[ProduceDate],
	[ValidDate],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost]
) 
 
VALUES 
 ( 
	@BillNumberId,
	@InOrOut,
	@PtypeId,
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@SalePrice),
	dbo.F_RoundDiscount(@discount),
	dbo.F_RoundPrice(@DiscountPrice),
	@jobnumber,
	dbo.F_RoundTotal(@total),
	@OutFactoryDate,
	dbo.F_RoundPrice(@TaxPrice),
	dbo.F_RoundTotal(@TaxTotal),
	@Comment,
	@intisUnitTow,
	@Serial,
	dbo.F_RoundPrice(@InputCostPrice),
	@GoodsNumber,
	@ProduceDate,
	@ValidDate,
	@GoodsBTypeID,
	dbo.F_RoundPrice(@GoodsCostPrice),
	@HandZeroCost
)
if @@rowcount=0 return -1 else return 0




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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











/*
	作者：谢吉康
	日期：2003-12-30
	描述：写入数据到维修表中
*/
CREATE   PROCEDURE GP_InsertRepairEngage
(
	@OperatorID		VARCHAR(50),	
	@BillDate		VARCHAR(20),
	@BillCode		VARCHAR(200),  -- #&**&#
	@BillType		VARCHAR(10),
	@PTypeID		VARCHAR(50),
	@Serial			VARCHAR(256),
	@ETypeID		VARCHAR(50),
	@IfCheck		VARCHAR(10),
	@Checke			VARCHAR(50),
	@RedWord		VARCHAR(10),
	@Draft			INT,
	@Stat			INT,
	@ETypeID1		VARCHAR(50),
	@RepairDate		VARCHAR(20),
	@ETypeName1		VARCHAR(50),
	@Tel			VARCHAR(100),
	@BuyDate		VARCHAR(20),
	@SaleBTypeName	VARCHAR(200),
	@Buyer			VARCHAR(100),
	@Address		VARCHAR(8000),
	@Brief			VARCHAR(256),	
	@Config			VARCHAR(800),
	@RepairType		INT,
	@Attach			VARCHAR(800),
	@Fault			VARCHAR(8000),
	@Comment		VARCHAR(8000),
	@SaleBillID		VARCHAR(66)
)
--@encode$--
AS
BEGIN
	--判断序列号
	SELECT TOP 1 * FROM GP_CruPTypeSerial WHERE Serial = @Serial AND State IN (1,7) AND Flag = 1
	
	IF @@ROWCOUNT <> 0 
		BEGIN
			--RAISERROR('序列号在当前库中，没有出库记录，不允许维修！',16,1)
			RETURN -1
		END
	
	INSERT INTO RepairEngage
	(
		BillDate,
		BillCode,
		BillType,
		PTypeID,
		Serial,
		ETypeID,
		IfCheck,
		Checke,
		RedWord,
		Draft,
		Stat,
		ETypeID1,
		RepairDate,
		ETypeName1,
		Tel,
		BuyDate,		
		SaleBTypeName,
		SaleBillID,
		Buyer,
		Address,
		Brief,
		Config,
		RepairType,
		Attach,
		Fault,
		Comment
	)
	VALUES
	(
		@BillDate,
		@BillCode,
		@BillType,
		@PTypeID,
		@Serial,
		@ETypeID,
		@IfCheck,
		@Checke,
		@RedWord,
		@Draft,
		@Stat,
		@ETypeID1,
		@RepairDate,
		@ETypeName1,
		@Tel,
		@BuyDate,		
		@SaleBTypeName,
		@SaleBillID,
		@Buyer,
		@Address,
		@Brief,	
		@Config,
		@RepairType,
		@Attach,
		@Fault,
		@Comment
	)

	IF @@ROWCOUNT = 0 
		BEGIN
			--RAISERROR('写入数据到维修库中失败，请确认后重试！',16,1)
			RETURN -2
		END
END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：韩林
描述：写入零售退货单明细表(表值)
*/
CREATE  PROCEDURE Gp_InsertRetailBackBillDT
(
	@details TBType_RetailBack READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO [dbo].[RetailBackBill] 
  ( 
	[BillNumberId],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[OutFactoryDate],
	[TaxPrice],
	[TaxTotal],
	[comment],
	[isUnit2],
	[Serial],
	[InputCostPrice],
	[GoodsNumber],
	[ProduceDate],
	[ValidDate],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost],
	Tax,
	SaleTotal,
	STypeID
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoID
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,IsGift
	,OldID
	,OldBillNumberID
	,CompleteQTY
	,PosId
	,ReferPrice
	,PriceStyle
	,PromoType
	,ETypeID
	,ShowOrder
	,KTypeID
	,PriceSource
	,Couponcode
) 
SELECT 
	BillNumberId,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	jobnumber,
	dbo.F_RoundTotal(total),
	MakeDate,
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	intisUnit2,
	Serial,
	dbo.F_RoundPrice(InputCostPrice),
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	STypeID
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoID
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined
	,IsGift
	,OldID
	,OldBillNumberID
	,dbo.F_RoundQty(CompleteQTY)
	,PosId
	,dbo.F_RoundPrice(ReferPrice)
	,PriceStyle
	,PromoType
	,ETypeId
	,ShowOrder
	,KTypeID
	,PriceSource
	,ISNULL(Couponcode,'')
	FROM @details

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：廖晨羽
描述：写入销售出库单明细表(表值)
*/
CREATE              PROCEDURE [Gp_InsertRetailBillDT]
(
	@details TBType_Retail READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO [dbo].[RetailBill] 
  ( 
	[BillNumberId],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[TaxPrice],
	[TaxTotal],
	[comment],
	OrderID,
	isUnit2,
	Serial,
	[GoodsNumber],
	[ProduceDate],
	[ValidDate],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost],
	[InputCostPrice],
	Tax,
	SaleTotal,
	STypeID
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,IsGift
	,BeforePromoID
	,PriceDetailID
	,PriceRuleID
	,PriceSource
	,PosId
	,ReferPrice
	,PriceStyle
	,PromoType
	,ETypeID
	,ShowOrder
	,iscombination
	,combinationptypeid
	,pindexid
	,KTypeID
	,PromonIds
	,CouponCode
	,IsVipPoint
	,IsPromotion
) 
 
SELECT 
	BillNumberId,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	jobnumber,
	dbo.F_RoundTotal(total),
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	OrderID,
	intIsUnit2,
	Serial,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundPrice(InputCostPrice),
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	STypeID
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoId
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined	
	,dbo.F_RoundQty(InvoiceQty)
	,dbo.F_RoundTotal(InvoiceMoney)
	,dbo.F_RoundTotal(NInvoiceMoney)
	,IsGift
	,BeforePromoID
	,PriceDetailID
	,PriceRuleID
	,PriceSource
	,PosId
	,dbo.F_RoundPrice(ReferPrice)
	,PriceStyle
	,PromoType
	,ETypeid
	,ShowOrder
	,iscombination
	,combinationptypeid
	,pindexid
	,KTypeID
	,ISNULL(PromonIds,'')
	,ISNULL(CouponCode,'')
	,IsVipPoint
	,IsPromotion
	FROM @details

if @@rowcount=0 or @@Error<>0
	RAISERROR('插入单据发生错误！',16,1)

UPDATE dbo.BeforePromoteRetailBill SET Serial=dbo.f_getserial(id,@details)
if @@Error<>0
	RAISERROR('插入单据发生错误！',16,1)
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_InsertRetailCombinationDT',N'P'))
BEGIN
	DROP PROC   GP_InsertRetailCombinationDT
END
GO

CREATE PROC GP_InsertRetailCombinationDT
(
	@Tb TbType_RetailCombination READONLY
)
AS
BEGIN
	INSERT INTO RetailCombinationBill
	(
		BillNumberId,
		PtypeId,
		Qty,
		SalePrice,
		discount,
		DiscountPrice,
		total,
		OutFactoryDate,
		TaxPrice,
		TaxTotal,
		IsUnit2,
		BackQTY,
		SaleTotal,
		Tax,
		Stypeid,
		TaxMoney,
		NSalePrice,
		NSaleTotal,
		NDiscountPrice,
		NTotal,
		NTaxPrice,
		NTaxTotal,
		NTaxMoney,
		UnitID,
		NUnitID,
		NQty,
		UnitRate,
		NUnitMsg,
		MUnitID,
		MQty,
		MUnitRate,
		MUnitMsg,
		MSalePrice,
		MDiscountPrice,
		MTaxPrice,
		CurMSalePrice,
		CurMDiscountPrice,
		CurMTaxPrice,
		CargoID,
		InvoiceQty,
		InvoiceMoney,
		NInvoiceMoney,
		IsGift,
		PosId,
		BeforePromoID,
		PriceDetailId,
		PriceRuleId,
		PriceSource,
		PriceStyle,
		PromoType,
		pindexid,
		comment,
		ETypeID,
		itemid,
		Iscombined
		,PromonIds
		,CouponCode
		,IsVipPoint
		,IsPromotion
	)
	SELECT 
			BillNumberId,
			PtypeId,
			Qty,
			SalePrice,
			discount,
			DiscountPrice,
			total,
			OutFactoryDate,
			TaxPrice,
			TaxTotal,
			IsUnit2,
			BackQTY,
			SaleTotal,
			Tax,
			Stypeid,
			TaxMoney,
			NSalePrice,
			NSaleTotal,
			NDiscountPrice,
			NTotal,
			NTaxPrice,
			NTaxTotal,
			NTaxMoney,
			UnitID,
			NUnitID,
			NQty,
			UnitRate,
			NUnitMsg,
			MUnitID,
			MQty,
			MUnitRate,
			MUnitMsg,
			MSalePrice,
			MDiscountPrice,
			MTaxPrice,
			CurMSalePrice,
			CurMDiscountPrice,
			CurMTaxPrice,
			CargoID,
			InvoiceQty,
			InvoiceMoney,
			NInvoiceMoney,
			IsGift,
			PosId,
			BeforePromoID,
			PriceDetailId,
			PriceRuleId,
			PriceSource,
			PriceStyle,
			PromoType,
			pindexid,
			comment,
			etypeid,
			itemid,
			Iscombined
			,ISNULL(PromonIds,'')
			,ISNULL(CouponCode,'')
			,IsVipPoint
			,IsPromotion
		FROM @tb
END
GO



IF exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_InsertS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_InsertS]
GO
/****** Object:  StoredProcedure [dbo].[Gp_InsertS]    Script Date: 05/20/2011 17:31:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO




 
--作    用：插入机构信息


CREATE         PROCEDURE [dbo].[Gp_InsertS]
(
	@Parid      varchar(50),
	@DbName     varchar(30),
	@UserCode   varchar(26),
	@FullName   varchar(66),
	@SimpleName varchar(30) ='',
	@Comment    varchar(256) ='',
	@LinkMan    varchar(20),
	@Tel		varchar(50),
	@Address	varchar(50),
	@PyCode		varchar(200),
	@PostCode	varchar(100),
	@TaxNo		varchar(100),
	@Bank		varchar(100),
	@Account	varchar(100),
	@BTypeID1   varchar(50)=null,
	@BTypeID2   varchar(50)=null,
	@PriceType	varchar(10)='0',
	@atypeid	varchar(50),
	@atypeid2	varchar(50),
	@atypeid3   VARCHAR(50),
	@atypeid4   VARCHAR(50),
	@isselfverify   INT,
	@verifyid   VARCHAR(50),
	@calcFullName   VARCHAR(100),
	@EtypeId VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON

-----对应客户和对应供货商
IF(isnull(@BTypeID1,'')<>'')
	BEGIN
		IF  exists(select * from [SType] where BTypeID1=@BTypeID1)
			BEGIN
				--print '['+@usercode+']机构已存在'
				RAISERROR('该对应客户已经被其它分支机构使用',16,1)RETURN--RETURN -101
			END
	END

IF(isnull(@BTypeID2,'')<>'')
	BEGIN
		IF  exists(select * from [SType] where BTypeID2=@BTypeID2)
			BEGIN
				--print '['+@usercode+']机构已存在'
				RAISERROR('该对应供货商已经被其它分支机构使用',16,1)RETURN--RETURN -101
			END
	END

IF @isselfverify<>1 AND @verifyid=@Parid
BEGIN
	RAISERROR('该分支机构【%s】正在被分类，不能用作其子类的记账单位',16,1,@FullName)RETURN 
END
--能否分类判断
EXEC Gp_BaseInfoCheck 'stype',@Parid,'0'

declare @nReturntype int,@EtypeId_1 [varchar](50),@nSoncount int,@nSonnum int,@leveal smallint

-- 判断机构是否可以分类
---站位


-- 获得新的ID号
exec @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 out,@nSonnum out,@nSoncount out
IF @nReturntype=-1 
	BEGIN
		RAISERROR('分支机构的分类不能超过10层',16,1)RETURN--RETURN -1
	END
IF @nReturntype=-2 
	BEGIN
		RAISERROR('无法添加基本信息',16,1)RETURN--RETURN -2
	END
 
-- 判断重复的ID,UserCode
IF exists(select * from [SType] where typeId=@EtypeId_1 or (usercode=@usercode and deleted<>1) or (fullname=@fullname and deleted<>1))
	BEGIN
		--print '['+@usercode+']机构已存在'
		RAISERROR('【%s】已经存在，分支机构的名称或编号不能相同',16,1,@FullName)RETURN--RETURN -3
	END
-- 判断重复的ID,UserCode
IF exists(select * from [SType] where typeId=@EtypeId_1 or (usercode=@fullname and deleted<>1) or (fullname=@usercode and deleted<>1))
	BEGIN
		--print '['+@usercode+']机构已存在'
		RAISERROR('【%s】名称或编号不能与已有的名称或编号重复',16,1,@FullName)RETURN--RETURN -10
	END

-- 判断重复的ID,UserCode
IF exists(select * from [SType] where typeId=@EtypeId_1 or (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	BEGIN
		--print '['+@usercode+']机构已存在'
		RAISERROR('该【%s】的编号或名称已被已停用的分支机构使用，请更换或删除该停用的编号或名称',16,1,@FullName)RETURN--RETURN -31
	END
-- 判断重复的ID,UserCode
IF exists(select * from [SType] where typeId=@EtypeId_1 or (usercode=@fullname and deleted=1) or (fullname=@usercode and deleted=1))
	BEGIN
		--print '['+@usercode+']机构已存在'
		RAISERROR('该分支机构【%s】名称或编号不能与已停用的名称或编号重复',16,1,@FullName)RETURN--RETURN -101
	END
IF @BTypeID1<>''
	BEGIN
		IF NOT EXISTS(select * from btype where typeId=@BTypeID1)
			BEGIN
				RAISERROR('不存在客户【%s】',16,1,@BTypeID1)
				RETURN
			END
		IF EXISTS(select * from btype where typeId=@BTypeID1 and sonnum<>0)
			BEGIN
				RAISERROR('对应的客户不是子结点，请检查！',16,1)
				RETURN
			END
	END
IF @BTypeID2<>''
	BEGIN
		IF NOT EXISTS(select * from btype where typeId=@BTypeID2)
			BEGIN
				RAISERROR('不存在供货商【%s】',16,1,@BTypeID2)
				RETURN
			END
		IF EXISTS(select * from btype where typeId=@BTypeID2 and sonnum<>0)
			BEGIN
				RAISERROR('对应的客户或供货商不是子结点，请检查！',16,1)
				RETURN
			END
	END
	
	
	
IF @verifyid <> ''
AND NOT @verifyid is NULL
AND  NOT EXISTS (SELECT 1 FROM SType WHERE TypeId = @verifyid)
BEGIN
    RAISERROR('选择的记账单位不存在。',16,1)
    RETURN
END


--独立核算时 修改为自己
IF @isselfverify = 1 
BEGIN
    SET @verifyid = @EtypeId_1
END

-- 核算单位为自己的时候，修改为独立核算
--IF @isselfverify = 0 AND
--BEGIN
--	SET @isselfverify = 1;
--	RETURN
--END

/*

IF @atypeid IS NOT NULL AND NOT EXISTS (SELECT 1 FROM Ac_Account WHERE StypeId = @verifyid AND TypeId = @atypeid)
BEGIN
	RAISERROR('选择的利润科目不存在.',16,1)
	RETURN
END

IF @atypeid2 IS NOT NULL AND NOT EXISTS (SELECT 1 FROM Ac_Account WHERE StypeId = @verifyid AND TypeId = @atypeid2)
BEGIN
	RAISERROR('利润分配科目不存在.',16,1)
	RETURN
END

IF @atypeid3 IS NOT NULL AND NOT EXISTS (SELECT 1 FROM Ac_Account WHERE StypeId = @verifyid AND TypeId = @atypeid3)
BEGIN
	RAISERROR('汇兑损益科目不存在.',16,1)
	RETURN
END

IF @atypeid4 IS NOT NULL AND NOT EXISTS (SELECT 1 FROM Ac_Account WHERE StypeId = @verifyid AND TypeId = @atypeid4)
BEGIN
	RAISERROR('存货科目不存在.',16,1)
	RETURN
END
	
	
	*/
DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

BEGIN TRAN insertproc
select @leveal=leveal from SType where typeid=@Parid
select @leveal=@leveal+1
INSERT INTO [SType] 
  ( 
	TypeId,
	parid,
	leveal,
	soncount,
	sonnum,
	FullName,
	[Name], 
	UserCode,
	Comment,
	[LinkMan],
	[Tel],
	[Address],
	[PyCode],
	[PostCode],
	[TaxNo],
	[Bank],
	[Account],
	[BTypeID1], 
	[BTypeID2],
	[PriceType],
	[atypeid],
	[atypeid2],
	[atypeid3],
	[atypeid4],
	[isselfverify],
	[verifyid],
	[calcFullName]
	)  
VALUES 
 (
	@EtypeId_1,
	@Parid,
	@leveal,
	0,
	0,
	@FullName,
	@simplename,
	@UserCode,
	@Comment,
	@LinkMan ,
	@Tel ,
	@Address,
	@returnPym,
	@PostCode,
	@TaxNo ,
	@Bank,
	@Account, 
	@BTypeID1, 
	@BTypeID2,
	@PriceType,
	@atypeid,
	@atypeid2,
	@atypeid3,
	@atypeid4,
	@isselfverify,
	@verifyid,
	@calcFullName
	)

IF @@rowcount=0 
BEGIN
	ROLLBACK TRAN insertproc 
	RETURN -1
END
ELSE 
BEGIN
	INSERT INTO Ac_AssetBusinessType(BusinessType,FullName,Atid,AuditType,STypeid,Deleted) 
	SELECT 0,'购入（原值含税）',NULL,1,@EtypeId_1,1 UNION 
	SELECT 0,'购入（原值不含税）',NULL,2,@EtypeId_1,1 UNION 
	SELECT 0,'自建工程',NULL,3,@EtypeId_1,1 UNION 
	--SELECT 4,0,'接受投资',NULL,4,1 UNION 
	SELECT 0,'接受捐赠',NULL,5,@EtypeId_1,1 UNION 
	SELECT 0,'盘盈',NULL,6,@EtypeId_1,1 UNION 
	SELECT 1,'变卖',NULL,7,@EtypeId_1,1 UNION 
	SELECT 1,'报废',NULL,8,@EtypeId_1,1 UNION 
	SELECT 1,'投资转出',NULL,9,@EtypeId_1,1 UNION 
	SELECT 1,'捐赠转出',NULL,10,@EtypeId_1,1 UNION 
	SELECT 1,'盘亏',NULL,11,@EtypeId_1,1 UNION 
	SELECT 2,'部门转移',NULL,12,@EtypeId_1,1 UNION 
	SELECT 3,'计提减值准备',NULL,13,@EtypeId_1,1 UNION 
	SELECT 4,'折旧',NULL,14,@EtypeId_1,1  
	
		
	IF EXISTS(SELECT *FROM SType WHERE TypeId=@Parid AND IfAssetsIni=1)
	BEGIN
		UPDATE SType SET IfAssetsIni=1 WHERE TypeId=@EtypeId_1
	END
	--记账单位已初始化
	IF EXISTS(SELECT *FROM SType WHERE TypeId=@verifyid AND IfAssetsIni=1)
	BEGIN
		UPDATE SType SET IfAssetsIni=1 WHERE TypeId=@EtypeId_1
	END
	
	--删除父节点的业务类型信息
	DELETE FROM Ac_AssetBusinessType WHERE STypeId=@Parid
	
	--新增项目分支关联
	INSERT INTO Ac_Items_Detail(NID,STypeId,ATypeId,DepATypeId,DisATypeId)
	SELECT nId,@EtypeId_1,'','','' FROM Ac_Items WHERE nTypeId<>'00000'
	
	--新增存货类型分支关联
	INSERT INTO Base_InventoryTypeDetails(TID,STypeId,StockATypeID,IncomeATypeID,CostATypeID)
	SELECT nId,@EtypeId_1,'','','' FROM Base_InventoryType
	
	--新增商品存货类型关联 取消掉
	  --INSERT INTO dbo.PType_InventoryType
   --       ( Ptypeid, Stypeid, InventoryTypeid)
   --        SELECT p.typeId,@EtypeId_1,c.NID from dbo.ptype p 			
   --        ,(SELECT b.NID from dbo.Base_InventoryType b WHERE b.FullName='库存商品') c 
   --        WHERE p.typeId<>'00000' 
	
	
	--新增变更原因分支关联
	INSERT INTO Base_FixedReasonForChangeDetails(TID,STypeId,EnterATypeID,ForeignATypeID,RateATypeID)
	SELECT nId,@EtypeId_1,'','','' FROM Base_FixedReasonForChange
	
	update [SType]
	set sonnum=@nSonnum+1,soncount=@nSoncount+1
	where typeid=@Parid
	
	--IF(EXISTS( SELECT * FROM dbo.SType_UserConfig WHERE StypeId=@verifyid AND Value=1))
	--BEGIN
	--	IF  NOT EXISTS(SELECT * FROM SType_UserConfig WHERE StypeId=@EtypeId_1)
	--	BEGIN
	--		INSERT INTO SType_UserConfig( ConfigNo, StypeId, Value, EtypeId )VALUES  ( 1,@EtypeId_1,'1',@EtypeId)
	--	END
	--	ELSE
	--	BEGIN
	--		UPDATE SType_UserConfig SET Value=1 WHERE StypeId=@EtypeId_1
	--	END
	--END
	--ELSE
	--BEGIN
	--	INSERT INTO SType_UserConfig(ConfigNo,StypeId,Value,EtypeId) VALUES(1,@EtypeId_1,'0',@EtypeId)
	--END
	
	--9.4分支机构新增时写出纳启用期间表
	INSERT INTO Te_StartPeriod
	(
		STypeId,
		SFYear,
		SFPeriod,
		IsConnect,
		CFYear,
		CFPeriod,
		IsUse
	)VALUES
	(
		@EtypeId_1,
		'0',
		'0',
		'0',
		'0',
		'0',
		'0'		
	)
	--删除父类出纳启用期间表信息
	DELETE FROM Te_StartPeriod WHERE STypeId=@Parid
	
	--9.8独立分支机构开账，分支机构表数据添加
	DECLARE 
		@SFyear		INT,--启用年度
		@SFPeriod	INT,--启用期间
		@StartDate	DATETIME	--启用期间开始时间
	
		SELECT @SFyear=SubValue FROM SysData WHERE SubName='fyear'
		SELECT @SFPeriod=SubValue FROM SysData WHERE SubName='fmonth'
		SELECT @StartDate=FBegin FROM Ac_Period WHERE FYear=@SFyear AND FPeriod=@SFPeriod
	--只保存独立分支机构
	IF(@isselfverify=1)
		BEGIN
			--总账
			INSERT INTO Ac_AccountsPeroid_Stype
			(
				
				STypeId,
				SFYear,
				SFPeriod,
				FYear,
				FPeriod,
				IsUse
			)VALUES
			(
				
				@EtypeId_1,
				@SFyear,
				@SFPeriod,
				@SFyear,
				@SFPeriod,
				0
			)
		END
	--业务
	INSERT INTO SType_UserConfig
	(   ConfigNo,
		STypeId,
		Value,
		EtypeId,
		SFYear,
		SFPeriod
	)
	VALUES
	(
		1,
		@EtypeId_1,
		0,
		@EtypeId,
		@SFyear,
		@SFPeriod
	)
	--区分有没启用独立开账配置
	DECLARE @IFSOPEN INT
	SELECT @IFSOPEN=CAST(subvalue as int) from sysdata where subname='stypeindependentopen' 
	IF @IFSOPEN=1 --启用 
	BEGIN
		INSERT INTO MonthProc
		(
			STypeID,
			MonthNo,
			StartDate,
			period,
			[Year]
		)
		VALUES
		(
			@EtypeId_1,
			'本期',
			@StartDate,
			@SFPeriod,
			@SFyear
		)
	END
	ELSE--没启用 取'00001'数据复制
	BEGIN
		INSERT INTO MonthProc (STypeID,MonthNo,StartDate,enddate,period,[Year])
		SELECT  @EtypeId_1,
				MonthNo,
				StartDate,
				enddate,
				period,
				[Year]
			FROM MonthProc
			WHERE STypeID='00001'
	END
		--具体分支机构 项目
		INSERT INTO ThreeFinancialItem_SType(
			ReportType,
			STypeID,
			ItemID,
			ItemFullName,
			Formula1IsPar, 
			Formula2IsPar
		)
		SELECT 
			F.ReportType,
			@EtypeId_1 STypeID,
			F.ItemID,
			F.ItemFullName,
			F.Formula1IsPar, 
			F.Formula2IsPar
		FROM ThreeFinancialItem F
		WHERE 
			F.AccountSubId=(SELECT SetId FROM Ac_Table WHERE IsUsed=1)
		GROUP BY 
			F.ReportType,
			F.ItemID,
			F.ItemFullName,
			F.Formula1IsPar, 
			F.Formula2IsPar 
		
		--项目子级公式表
		INSERT INTO ThreeFinancialFormula_Stype(
			ReportType,
			STypeID,
			ItemID,
			[SIGN],
			Formula,
			RowId,
			FormulaType,
			IsEditAll
		)
		SELECT 
			ReportType,
			@EtypeId_1 STypeID,
			ItemID,
			[SIGN],
			Formula,
			RowId,
			FormulaType,
			0 IsEditAll
		FROM ThreeFinancialFormula F
		WHERE 
			F.AccountSubId=(SELECT SetId FROM Ac_Table WHERE IsUsed=1)
		GROUP BY 
			ReportType,
			ItemID,
			[SIGN],
			Formula,
			RowId,
			FormulaType
			
		--项目父级公式表
		INSERT INTO ThreeFinancialItemParent_Stype(
			ReportType,				--1:利润表 2：现金流量表 3：资产负债表
			STypeID,		--分支机构ID 
			ParItemID,--父类项目ID
			[Sign],--公式符号 1：正 -1负
			SonItemID,--自己项目ID
			FormulaType--公式类型比如利润表1：本期金额 2本年累计金额
		)
		SELECT 
			ReportType,
			@EtypeId_1 STypeID,
			F.ParItemID,
			F.[Sign],
			F.SonItemID,
			F.FormulaType
		FROM ThreeFinancialItemParent F
		WHERE 
			F.AccountSubId=(SELECT SetId FROM Ac_Table WHERE IsUsed=1)
		GROUP BY 
			ReportType,
			F.ParItemID,
			F.[Sign],
			F.SonItemID,
			F.FormulaType
END

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM SType
UPDATE SType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1
--修改Ac_Items_DetailXiWa的XiWaMaxNumber
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Ac_Items_Detail
UPDATE Ac_Items_Detail SET XiWaMaxNumber = @XiWaMaxNumber,@XiWaMaxNumber+=1 WHERE XiWaMaxNumber=1

COMMIT TRAN insertproc

SET QUOTED_IDENTIFIER ON 

GO





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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：廖晨羽
描述：写入销售退货单明细表(表值)
*/
CREATE              PROCEDURE [Gp_InsertSaleBackBillDT]
(
	@details TBType_SaleBack READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @BillNumberID VARCHAR(50)

SELECT TOP 1 @BillNumberID = BillNumberID FROM @Details
--期初单据不处理草稿库存
IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
BEGIN
	-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
	EXEC GP_Deal_DraftQTY @BillNumberID,45,'-'
END
DELETE A FROM dbo.saleBackBill A,@Details B WHERE A.BillNumberId=B.BillNumberId AND 
	   NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID
											 AND A.BillNumberiD=B.BillNumberiD
											 AND A.OldBillNumberID=B.OldBillNumberID
											 AND A.OldID=B.OldID
											 AND B.ID<>0)

INSERT INTO [dbo].[SaleBackBill] 
  ( 
	[BillNumberId],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[OutFactoryDate],
	[TaxPrice],
	[TaxTotal],
	[comment],
	[isUnit2],
	[Serial],
	[OldID],
	[OldBillNumberID],
	--[CostPrice],
	[InputCostPrice],
	[GoodsNumber],
	[ProduceDate],
	[ValidDate],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost],
	Tax,
	SaleTotal,
	KTypeID,
	STypeID,
	FromBillNumberID,
	FromBillID
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,CompleteQTY
	
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,IsGift
	,ReferPrice
	,PriceStyle
	,PromoType
	,OMBillID
	,CompleteTotal
	,NCompleteTotal
	,ShowOrder
	,EtypeID
	,PriceSource
	,CouponCode
	 
) 
SELECT 
	BillNumberId,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	JobNo,
	dbo.F_RoundTotal(total),
	MakeDate,
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	intisUnit2,
	Serial,
	OldID,
	OldBillNumberID,
	--CostPrice,
	dbo.F_RoundPrice(InputCostPrice),
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	KTypeID,
	STypeID,
	FromBillNumberID,
	FromBillID
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoId
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined
	,dbo.F_RoundQty(CompleteQTY)
	,dbo.F_RoundQty(InvoiceQty)
	,dbo.F_RoundTotal(InvoiceMoney)
	,dbo.F_RoundTotal(NInvoiceMoney)
	,IsGift
	,dbo.F_RoundPrice(ReferPrice)
	,PriceStyle
	,PromoType
	,OMBillID
	,dbo.F_RoundTotal(CompleteTotal)
	,dbo.F_RoundTotal(NCompleteTotal)	
	,ShowOrder	
	,EtypeID
	,PriceSource	
	,ISNULL(Couponcode,'')	
	--尽量减少碰撞吧，ID不可行
	FROM @details A WHERE ID=0 OR NOT EXISTS(SELECT ID FROM dbo.saleBackBill B WHERE A.ID=B.ID
																				 AND A.BillNumberiD=B.BillNumberiD
																				 AND A.OldBillNumberID=B.OldBillNumberID
																				 AND A.OldID=B.OldID)

UPDATE A SET	PtypeId=B.PTypeID,
				Qty=B.Qty,
				SalePrice=B.SalePrice,
				discount=B.Discount,
				DiscountPrice=B.DiscountPrice,
				jobnumber=B.JobNo,
				total=B.Total,
				OutFactoryDate=B.MakeDate,
				TaxPrice=B.TaxPrice,
				TaxTotal=B.TaxTotal,
				comment=B.Comment,
				isUnit2=B.IntIsUnit2,
				Serial=B.Serial,
				OldID=B.OldID,
				OldBillNumberID=B.OldBillNumberID,
				InputCostPrice=B.InputCostPrice,
				GoodsNumber=B.GoodsNumber,
				ProduceDate=B.ProduceDate,
				ValidDate=B.ValidDate,
				GoodsBTypeID=B.GoodsBTypeID,
				GoodsCostPrice=B.GoodsCostPrice,
				HandZeroCost=B.HandZeroCost,
				Tax=B.Tax,
				SaleTotal=B.SaleTotal,
				KTypeID=B.KTypeID,
				STypeID=B.STypeID,
				FromBillNumberID=B.FromBillNumberID,
				FromBillID=B.FromBillID,
				TaxMoney=B.TaxMoney,
				NSalePrice=B.NSalePrice,
				NSaleTotal=B.NSaleTotal,
				NDiscountPrice=B.NDiscountPrice,
				NTotal=B.NTotal,
				NTaxPrice=B.NTaxPrice,
				NTaxTotal=B.NTaxTotal,
				NTaxMoney=B.NTaxMoney,
				CargoId=B.CargoID,
				UnitId=B.UnitID,
				NUnitId=B.NUnitID,
				NQty=B.NQty,
				UnitRate=B.UnitRate,
				NUnitMsg=B.NUnitMsg,
				MUnitId=B.MUnitID,
				MQty=B.MQty,
				MUnitRate=B.MUnitRate,
				MUnitMsg=B.MUnitMsg,
				MSalePrice=B.MSalePrice,
				MDiscountPrice=B.MDiscountPrice,
				MTaxPrice=B.MTaxPrice,
				CurMSalePrice=B.CurMSalePrice,
				CurMDiscountPrice=B.CurMDiscountPrice,
				CurMTaxPrice=B.CurMTaxPrice,
				ItemId=B.ItemID,
				IsCombined=B.IsCombined,
				CompleteQTY=B.CompleteQty,
				InvoiceQty=B.InvoiceQty,
				InvoiceMoney=B.InvoiceMoney,
				NInvoiceMoney=B.NInvoiceMoney,
				IsGift=B.IsGift,
				ReferPrice=B.ReferPrice,
				PriceStyle=B.PriceStyle,
				PromoType=B.PromoType,
				OMBillID=B.OMBillID,
				CompleteTotal=B.CompleteTotal,
				NCompleteTotal=B.NCompleteTotal,
				ShowOrder=B.ShowOrder,
				etypeid=B.ETypeID,
				PriceSource = b.PriceSource,
				Couponcode=ISNULL(b.Couponcode,'')
FROM dbo.saleBackBill A,@details B WHERE A.ID=B.ID
									 AND A.BillNumberiD=B.BillNumberiD
								 	 AND A.OldBillNumberID=B.OldBillNumberID
									 AND A.OldID=B.OldID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertSaleBillAutoDraftDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertSaleBillAutoDraftDT
GO

/*
作者：廖晨羽
描述：写入销售出库单明细表(表值)
*/
CREATE              PROCEDURE Gp_InsertSaleBillAutoDraftDT
(
	@details TBType_SaleAutoDraft READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @billguid VARCHAR(100)
	
SELECT TOP 1 @billguid = billguid FROM @details

DELETE FROM SaleBillAutoDraft WHERE BillGuid = @BillGuid
	
INSERT INTO SaleBillAutoDraft
(
	billguid,
	BillNumberId,
	PtypeId,
	Qty,
	SalePrice,
	discount,
	DiscountPrice,
	jobnumber,
	total,
	OutFactoryDate,
	TaxPrice,
	TaxTotal,
	comment,
	OrderID,
	isUnit2,
	Serial,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	Tax,
	SaleTotal,
	KTypeID,
	STypeID,
	ShareFee
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,completeqty
	,CompleteTotal
	,NCompleteTotal
	,entryCode
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,PriceSource
	,IsGift
	,BeforePromoID
	,ReferPrice
	,PriceStyle
	,PromoType
	,OMBillID
	,LendBillID
	,LendBillNumberID
	,ShowOrder
	,diyid
	,EtypeID
	,PromonIds
	,CouponCode
	,IsVipPoint
	,IsPromotion
	,PriceDetailId
	,PriceRuleId
)
SELECT	billguid,
		BillNumberId,
		PtypeId,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(discount),
		dbo.F_RoundPrice(DiscountPrice),
		jobnumber,
		dbo.F_RoundTotal(total),
		OutFactoryDate,
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		comment,
		OrderID,
		intisUnitTow,
		Serial,
		dbo.F_RoundPrice(InputCostPrice),
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		dbo.F_RoundPrice(GoodsCostPrice),
		HandZeroCost,
		dbo.F_RoundTax(Tax),
		dbo.F_RoundTotal(SaleTotal),
		KTypeID,
		STypeID,
		0
		--9.0新字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,dbo.F_RoundQty(completeqty)
		,dbo.F_RoundTotal(CompleteTotal)
		,dbo.F_RoundTotal(NCompleteTotal)
		,entryCode
		,dbo.F_RoundQty(InvoiceQty)
		,dbo.F_RoundTotal(InvoiceMoney)
		,dbo.F_RoundTotal(NInvoiceMoney)
		,PriceSource
		,IsGift
		,BeforePromoID
		,dbo.F_RoundPrice(ReferPrice)
		,PriceStyle
		,PromoType
		,OMBillID
		,LendBillID
		,LendBillNumberID
		,ShowOrder	
		,diyid
		,EtypeID
		,ISNULL(PromonIds,'')
		,ISNULL(CouponCode,'')
		,ISNULL(IsVipPoint,0)
		,ISNULL(IsPromotion,0)
		,PriceDetailId
		,PriceRuleId
FROM	@details A 
WHERE	billguid = @billguid
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.Gp_InsertSaleBillDT') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.Gp_InsertSaleBillDT
GO

/*
作者：廖晨羽
描述：写入销售出库单明细表(表值)
*/
CREATE              PROCEDURE Gp_InsertSaleBillDT
(
	@details TBType_Sale READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

--数据检测
--DECLARE @Re INT
--EXEC @Re = Gp_Fz_Base '',2
--IF @Re <> 0
--BEGIN
--	RAISERROR('发生未知错误！',16,1)
--END

DECLARE @BillNumberID VARCHAR(50)
	
SELECT TOP 1 @BillNumberID = BillNumberID FROM @details

-- 更新待收货数量
	UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
	FROM OrderBill a 
	JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM @details b WHERE b.OrderId<>-1 GROUP BY orderid)b ON b.orderid=a.OrderID

--期初单据不处理草稿库存
IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
BEGIN
	-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
	EXEC GP_Deal_DraftQTY @BillNumberID,11,'-'
	
	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f' AND draft=1)
	BEGIN
		-- 处理订单库存,先减去引用未过账数量
		EXEC GP_Deal_OrderReferQty @BillnumberID,11,'-'
	END
	ELSE
	BEGIN
		-- 处理订单库存,先减去过账数量
		EXEC GP_Deal_OrderReachQTY @BillnumberID,11,'-'
	END
END

IF EXISTS(SELECT TOP 1 1 FROM SaleBill WHERE BillNumberId=@BillNumberID)
BEGIN
	DELETE A FROM dbo.SaleBill A,@details B WHERE A.BillNumberId=B.BillNumberID AND NOT EXISTS(
				   SELECT ID FROM @details B WHERE A.BillNumberID=B.BillNumberID 
											   AND A.OrderID=B.OrderID 
											   AND A.ID=B.ID
											   AND A.LendBillID=B.LendBillID
											   AND B.ID<>0)

	INSERT INTO SaleBill
	(
		BillNumberId,
		PtypeId,
		Qty,
		SalePrice,
		discount,
		DiscountPrice,
		jobnumber,
		total,
		OutFactoryDate,
		TaxPrice,
		TaxTotal,
		comment,
		OrderID,
		isUnit2,
		Serial,
		InputCostPrice,
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		GoodsCostPrice,
		HandZeroCost,
		Tax,
		SaleTotal,
		KTypeID,
		STypeID,
		ShareFee
		--9.0新字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,CargoId
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		,completeqty
		,CompleteTotal
		,NCompleteTotal
		,entryCode
		,InvoiceQty
		,InvoiceMoney
		,NInvoiceMoney
		,PriceSource
		,IsGift
		,BeforePromoID
		,ReferPrice
		,PriceStyle
		,PromoType
		,OMBillID
		,LendBillID
		,LendBillNumberID
		,ShowOrder
		,diyid
		,EtypeID
		,PromonIds
		,CouponCode
		,IsPromotion
		,IsVipPoint
		,PriceDetailId
		,PriceRuleId
	)
	SELECT 
		BillNumberId,
		PtypeId,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(discount),
		dbo.F_RoundPrice(DiscountPrice),
		jobnumber,
		dbo.F_RoundTotal(total),
		OutFactoryDate,
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		comment,
		OrderID,
		intisUnitTow,
		Serial,
		dbo.F_RoundPrice(InputCostPrice),
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		dbo.F_RoundPrice(GoodsCostPrice),
		HandZeroCost,
		dbo.F_RoundTax(Tax),
		dbo.F_RoundTotal(SaleTotal),
		KTypeID,
		STypeID,
		0
		--9.0新字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,dbo.F_RoundQty(completeqty)
		,dbo.F_RoundTotal(CompleteTotal)
		,dbo.F_RoundTotal(NCompleteTotal)
		,entryCode
		,dbo.F_RoundQty(InvoiceQty)
		,dbo.F_RoundTotal(InvoiceMoney)
		,dbo.F_RoundTotal(NInvoiceMoney)
		,PriceSource
		,IsGift
		,BeforePromoID
		,dbo.F_RoundPrice(ReferPrice)
		,PriceStyle
		,PromoType
		,OMBillID
		,LendBillID
		,LendBillNumberID
		,ShowOrder	
		,diyid
		,EtypeID
		,ISNULL(PromonIds,'')
		,ISNULL(CouponCode,'')
		,IsPromotion
		,IsVipPoint
		,PriceDetailId
		,PriceRuleId
		--尽量减少碰撞吧，ID不可行
		FROM @details A WHERE ID=0 OR NOT EXISTS (
			SELECT ID FROM dbo.SaleBill B WHERE A.BillNumberID=B.BillNumberID 
											AND A.OrderID=B.OrderID 
											AND A.ID=B.ID
											AND A.LendBillID=B.LendBillID)

	UPDATE A SET	PtypeId=B.PTypeID,
					Qty=B.Qty,
					SalePrice=dbo.F_RoundPrice(B.SalePrice),
					discount=dbo.F_RoundDiscount(B.Discount),
					DiscountPrice=dbo.F_RoundPrice(B.DiscountPrice),
					jobnumber=B.jobnumber,
					total=dbo.F_RoundTotal(B.Total),
					OutFactoryDate=B.OutFactoryDate,
					TaxPrice=dbo.F_RoundPrice(B.TaxPrice),
					TaxTotal=dbo.F_RoundTotal(B.TaxTotal),
					comment=B.comment,
					OrderID=B.OrderID,
					isUnit2=B.intisUnitTow,
					Serial=B.Serial,
					InputCostPrice=dbo.F_RoundPrice(B.InputCostPrice),
					GoodsNumber=B.GoodsNumber,
					ProduceDate=B.ProduceDate,
					ValidDate=B.ValidDate,
					GoodsBTypeID=B.GoodsBTypeID,
					GoodsCostPrice=dbo.F_RoundPrice(B.GoodsCostPrice),
					HandZeroCost=B.HandZeroCost,
					Tax=dbo.F_RoundTax(B.Tax),
					SaleTotal=dbo.F_RoundTotal(B.SaleTotal),
					KTypeID=B.KTypeID,
					STypeID=B.STypeID,
					ShareFee=0,
					TaxMoney=dbo.F_RoundTotal(B.TaxMoney)
					,NSalePrice=dbo.F_RoundPrice(B.NSalePrice)
					,NSaleTotal=dbo.F_RoundTotal(B.NSaleTotal)
					,NDiscountPrice=dbo.F_RoundPrice(B.NDiscountPrice)
					,NTotal=dbo.F_RoundTotal(B.NTotal)
					,NTaxPrice=dbo.F_RoundPrice(B.NTaxPrice)
					,NTaxTotal=dbo.F_RoundTotal(B.NTaxTotal)
					,NTaxMoney=dbo.F_RoundTotal(B.NTaxMoney)
					,CargoId=B.CargoID
					,UnitId=B.UnitID
					,NUnitId=B.NUnitID
					,NQty=dbo.F_RoundQty(B.NQty)
					,UnitRate=B.UnitRate
					,NUnitMsg=B.NUnitMsg
					,MUnitId=B.MunitID
					,MQty=dbo.F_RoundQty(B.MQty)
					,MUnitRate=B.MUnitRate
					,MUnitMsg=B.MUnitMsg
					,MSalePrice=dbo.F_RoundPrice(B.MSalePrice)
					,MDiscountPrice=dbo.F_RoundPrice(B.MDiscountPrice)
					,MTaxPrice=dbo.F_RoundPrice(B.MTaxPrice)
					,CurMSalePrice=dbo.F_RoundPrice(B.CurMSalePrice)
					,CurMDiscountPrice=dbo.F_RoundPrice(B.CurMDiscountPrice)
					,CurMTaxPrice=dbo.F_RoundPrice(B.CurMTaxPrice)
					,ItemId=B.ItemID
					,IsCombined=B.IsCombined
					,completeqty=dbo.F_RoundQty(B.CompleteQty)
					,CompleteTotal=dbo.F_RoundTotal(B.CompleteTotal)
					,NCompleteTotal=dbo.F_RoundTotal(B.NCompleteTotal)
					,entryCode=B.EntryCode
					,InvoiceQty=dbo.F_RoundQty(B.InvoiceQty)
					,InvoiceMoney=dbo.F_RoundTotal(B.InvoiceMoney)
					,NInvoiceMoney=dbo.F_RoundTotal(B.NInvoiceMoney)
					,PriceSource=B.PriceSource
					,IsGift=B.IsGift
					,BeforePromoID=B.BeforePromoID
					,ReferPrice=B.ReferPrice
					,PriceStyle=B.PriceStyle
					,PromoType=B.PromoType
					,OMBillID=B.OMBillID
					,LendBillID=B.LendBillID
					,LendBillNumberID=B.LendBillNumberID
					,ShowOrder=B.ShowOrder
					,diyid=B.diyid
					,etypeid=B.ETypeID
					,PromonIds = ISNULL(b.PromonIds,'')
					,CouponCode=ISNULL(b.CouponCode,'')
					,IsPromotion=b.IsPromotion
					,A.IsVipPoint=b.IsVipPoint
					,A.PriceDetailId = b.PriceDetailId
					,A.PriceRuleId = b.PriceRuleId
	 FROM dbo.SaleBill A,@details B WHERE A.BillNumberID=B.BillNumberID 
									  AND A.OrderID=B.OrderID 
									  AND A.ID=B.ID
									  AND A.LendBillID=B.LendBillID

	DELETE A FROM DiyBillTypePSaleTypeID A WHERE SalebillNumberId=@BillNumberID AND NOT EXISTS(SELECT 1 FROM @details B WHERE B.DiyID=A.DiyBillTypeID)
END
ELSE
BEGIN
	INSERT INTO SaleBill
	(
		BillNumberId,
		PtypeId,
		Qty,
		SalePrice,
		discount,
		DiscountPrice,
		jobnumber,
		total,
		OutFactoryDate,
		TaxPrice,
		TaxTotal,
		comment,
		OrderID,
		isUnit2,
		Serial,
		InputCostPrice,
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		GoodsCostPrice,
		HandZeroCost,
		Tax,
		SaleTotal,
		KTypeID,
		STypeID,
		ShareFee
		--9.0新字段
		,TaxMoney
		,NSalePrice
		,NSaleTotal
		,NDiscountPrice
		,NTotal
		,NTaxPrice
		,NTaxTotal
		,NTaxMoney
		,CargoId
		,UnitId
		,NUnitId
		,NQty
		,UnitRate
		,NUnitMsg
		,MUnitId
		,MQty
		,MUnitRate
		,MUnitMsg
		,MSalePrice
		,MDiscountPrice
		,MTaxPrice
		,CurMSalePrice
		,CurMDiscountPrice
		,CurMTaxPrice
		,ItemId
		,IsCombined
		,completeqty
		,CompleteTotal
		,NCompleteTotal
		,entryCode
		,InvoiceQty
		,InvoiceMoney
		,NInvoiceMoney
		,PriceSource
		,IsGift
		,BeforePromoID
		,ReferPrice
		,PriceStyle
		,PromoType
		,OMBillID
		,LendBillID
		,LendBillNumberID
		,ShowOrder
		,diyid
		,EtypeID
		,PromonIds
		,CouponCode
		,IsVipPoint
		,IsPromotion
		,PriceDetailId
		,PriceRuleId
	)
	SELECT 
		BillNumberId,
		PtypeId,
		dbo.F_RoundQty(Qty),
		dbo.F_RoundPrice(SalePrice),
		dbo.F_RoundDiscount(discount),
		dbo.F_RoundPrice(DiscountPrice),
		jobnumber,
		dbo.F_RoundTotal(total),
		OutFactoryDate,
		dbo.F_RoundPrice(TaxPrice),
		dbo.F_RoundTotal(TaxTotal),
		comment,
		OrderID,
		intisUnitTow,
		Serial,
		dbo.F_RoundPrice(InputCostPrice),
		GoodsNumber,
		ProduceDate,
		ValidDate,
		GoodsBTypeID,
		dbo.F_RoundPrice(GoodsCostPrice),
		HandZeroCost,
		dbo.F_RoundTax(Tax),
		dbo.F_RoundTotal(SaleTotal),
		KTypeID,
		STypeID,
		0
		--9.0新字段
		,dbo.F_RoundTotal(TaxMoney)
		,dbo.F_RoundPrice(NSalePrice)
		,dbo.F_RoundTotal(NSaleTotal)
		,dbo.F_RoundPrice(NDiscountPrice)
		,dbo.F_RoundTotal(NTotal)
		,dbo.F_RoundPrice(NTaxPrice)
		,dbo.F_RoundTotal(NTaxTotal)
		,dbo.F_RoundTotal(NTaxMoney)
		,CargoId
		,UnitId
		,NUnitId
		,dbo.F_RoundQty(NQty)
		,dbo.F_RoundTranslateRate(UnitRate)
		,NUnitMsg
		,MUnitId
		,dbo.F_RoundQty(MQty)
		,dbo.F_RoundTranslateRate(MUnitRate)
		,MUnitMsg
		,dbo.F_RoundPrice(MSalePrice)
		,dbo.F_RoundPrice(MDiscountPrice)
		,dbo.F_RoundPrice(MTaxPrice)
		,dbo.F_RoundPrice(CurMSalePrice)
		,dbo.F_RoundPrice(CurMDiscountPrice)
		,dbo.F_RoundPrice(CurMTaxPrice)
		,ItemId
		,IsCombined
		,dbo.F_RoundQty(completeqty)
		,dbo.F_RoundTotal(CompleteTotal)
		,dbo.F_RoundTotal(NCompleteTotal)
		,entryCode
		,dbo.F_RoundQty(InvoiceQty)
		,dbo.F_RoundTotal(InvoiceMoney)
		,dbo.F_RoundTotal(NInvoiceMoney)
		,PriceSource
		,IsGift
		,BeforePromoID
		,dbo.F_RoundPrice(ReferPrice)
		,PriceStyle
		,PromoType
		,OMBillID
		,LendBillID
		,LendBillNumberID
		,ShowOrder	
		,diyid
		,EtypeID
		,ISNULL(PromonIds,'')
		,ISNULL(CouponCode,'')
		,ISNULL(IsVipPoint,0)
		,ISNULL(IsPromotion,0)
		,PriceDetailId
		,PriceRuleId
		FROM @details A 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：廖晨羽
描述：写入销售换货单明细表(表值)
*/
CREATE              PROCEDURE [Gp_InsertSaleGoodsExchangeBillDT]
(
	@details TBType_SaleGoodsExchange READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO [dbo].[SaleGoodsExchangeBill] 
  ( 
	[BillNumberId],
	[InOrOut],
	[PtypeId],
	[Qty],
	[SalePrice],
	[discount],
	[DiscountPrice],
	[jobnumber],
	[total],
	[OutFactoryDate],
	[TaxPrice],
	[TaxTotal],
	[comment],
	[isUnit2],
	[Serial],
	[InputCostPrice],
	[GoodsNumber],
	[ProduceDate],
	[ValidDate],
	[GoodsBTypeID],
	[GoodsCostPrice],
	[HandZeroCost],
	Tax,
	SaleTotal,
	KTypeID,
	STypeID
	--9.0新字段
	,TaxMoney
	,NSalePrice
	,NSaleTotal
	,NDiscountPrice
	,NTotal
	,NTaxPrice
	,NTaxTotal
	,NTaxMoney
	,CargoId
	,UnitId
	,NUnitId
	,NQty
	,UnitRate
	,NUnitMsg
	,MUnitId
	,MQty
	,MUnitRate
	,MUnitMsg
	,MSalePrice
	,MDiscountPrice
	,MTaxPrice
	,CurMSalePrice
	,CurMDiscountPrice
	,CurMTaxPrice
	,ItemId
	,IsCombined
	,CompleteQTY 
	
	,InvoiceQty
	,InvoiceMoney
	,NInvoiceMoney
	,IsGift
	,ReferPrice
	,PriceStyle
	,OldID
	,OldBillNumberID
	,CompleteTotal
	,NCompleteTotal
	,ShowOrder
	,EtypeID
	,PriceSource
)  
SELECT 
	BillNumberId,
	InOrOut,
	PtypeId,
	dbo.F_RoundQty(Qty),
	dbo.F_RoundPrice(SalePrice),
	dbo.F_RoundDiscount(discount),
	dbo.F_RoundPrice(DiscountPrice),
	jobnumber,
	dbo.F_RoundTotal(total),
	OutFactoryDate,
	dbo.F_RoundPrice(TaxPrice),
	dbo.F_RoundTotal(TaxTotal),
	comment,
	intisUnitTow,
	Serial,
	dbo.F_RoundPrice(InputCostPrice),
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	dbo.F_RoundPrice(GoodsCostPrice),
	HandZeroCost,
	dbo.F_RoundTax(Tax),
	dbo.F_RoundTotal(SaleTotal),
	KTypeID,
	STypeID
	--9.0新字段
	,dbo.F_RoundTotal(TaxMoney)
	,dbo.F_RoundPrice(NSalePrice)
	,dbo.F_RoundTotal(NSaleTotal)
	,dbo.F_RoundPrice(NDiscountPrice)
	,dbo.F_RoundTotal(NTotal)
	,dbo.F_RoundPrice(NTaxPrice)
	,dbo.F_RoundTotal(NTaxTotal)
	,dbo.F_RoundTotal(NTaxMoney)
	,CargoId
	,UnitId
	,NUnitId
	,dbo.F_RoundQty(NQty)
	,dbo.F_RoundTranslateRate(UnitRate)
	,NUnitMsg
	,MUnitId
	,dbo.F_RoundQty(MQty)
	,dbo.F_RoundTranslateRate(MUnitRate)
	,MUnitMsg
	,dbo.F_RoundPrice(MSalePrice)
	,dbo.F_RoundPrice(MDiscountPrice)
	,dbo.F_RoundPrice(MTaxPrice)
	,dbo.F_RoundPrice(CurMSalePrice)
	,dbo.F_RoundPrice(CurMDiscountPrice)
	,dbo.F_RoundPrice(CurMTaxPrice)
	,ItemId
	,IsCombined
	,dbo.F_RoundQty(CompleteQTY)
	
	,dbo.F_RoundQty(InvoiceQty)
	,dbo.F_RoundTotal(InvoiceMoney)
	,dbo.F_RoundTotal(NInvoiceMoney)
	,IsGift
	,dbo.F_RoundPrice(ReferPrice)
	,PriceStyle
	,OldID
	,OldBillNumberID
	,dbo.F_RoundTotal(CompleteTotal)
	,dbo.F_RoundTotal(NCompleteTotal)
	,ShowOrder
	,ETypeID
	,PriceSource
	FROM @details

if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_InsertSaleTimeTotal]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[GP_InsertSaleTimeTotal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-5
--	描述：销售计划时间总表数据插入
---------------------------------------------
CREATE PROCEDURE GP_InsertSaleTimeTotal
( 
	@fullname		VARCHAR(MAX),
	@Years			VARCHAR(MAX),
	@Description	VARCHAR(MAX),
	@IFUse			VARCHAR(MAX),
	@intReturn		int out
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS (SELECT *FROM SaleTimeTotal WHERE FullName=@fullname)
BEGIN
	RAISERROR('该时段组名称【%s】已经使用！',16,1,@fullname)
	SELECT @intReturn=-1
	RETURN 
END


INSERT INTO SaleTimeTotal (	
	FullName,
	Years,
	Comment,
	IFAudit,
	IFUse
)
VALUES(
	@fullname,
	@Years,
	@Description,
	'1',
	@IFUse
)

SELECT @intReturn=SCOPE_IDENTITY();
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.Gp_InsertSendBackBillDT',N'P'))
BEGIN
	DROP PROC dbo.Gp_InsertSendBackBillDT;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
			作者：司华山
			日期：2015-05-14
			描述：新增发出商品退货明细
*/	

CREATE PROC Gp_InsertSendBackBillDT
(
	@Details TbType_SendBackBill READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
		
	DECLARE @BillNumberID VARCHAR(50)

	SELECT TOP 1 @BillNumberID = BillNumberID FROM @Details
	--期初单据不处理草稿库存
	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
	BEGIN
		-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
		EXEC GP_Deal_DraftQTY @BillNumberID,403,'-'
	END
	DELETE A FROM dbo.SendBackBill A ,@Details B WHERE A.BillNumberId=B.BillNumberID
		AND NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID 
												 AND A.BillNumberId=B.BillNumberID
												 AND A.OldBillNumberID=B.OldBillNumberID
												 AND A.OldID=B.OldID
												 AND B.ID<>0)
	
	INSERT INTO dbo.SendBackBill([BillNumberId],
							 [PtypeId],
							 [Qty],
							 [SalePrice],
							 [discount],
							 [DiscountPrice],
							 [total],
							 [TaxPrice],
							 [TaxTotal],
							 [comment],
							 [TeamNo],
							 [TeamNO1],
							 [Serial],
							 [OldID],
							 [CostPrice],
							 [OldBillNumberID],
							 [InputCostPrice],
							 [GoodsOrder],
							 [GoodsNumber],
							 [ProduceDate],
							 [ValidDate],
							 [GoodsCostPrice],
							 [HandZeroCost],
							 [SaleTotal],
							 [Tax],
							 [KTypeID],
							 [Stypeid],
							 [TaxMoney],
							 [NSalePrice],
							 [NSaleTotal],
							 [NDiscountPrice],
							 [NTotal],
							 [NTaxPrice],
							 [NTaxTotal],
							 [NTaxMoney],
							 [UnitID],
							 [NUnitID],
							 [NQty],
							 [UnitRate],
							 [NUnitMsg],
							 [MUnitID],
							 [MQty],
							 [MUnitRate],
							 [MUnitMsg],
							 [MSalePrice],
							 [MDiscountPrice],
							 [MTaxPrice],
							 [CurMSalePrice],
							 [CurMDiscountPrice],
							 [CurMTaxPrice],
							 [CargoID],
							 [ItemID],
							 [IsCombined],
							 [InvoiceQty],
							 [InvoiceMoney],
							 [NInvoiceMoney],
							 [IsGift],
							 [ReferPrice],
							 [PriceStyle],
							 [InvoiceMoneyEX],
							 [NInvoiceMoneyEX],
							 [InvoiceCostTotal],
							 [InvoiceNQty],
							 [CostTotal],
							 [InvoiceSaleMoney],
							 [NInvoiceSaleMoney],
							 [ShareFee],
							 [ShowOrder],
							 [PriceSource]
							)
	 SELECT					 BillNumberId,
							 PtypeId,
							 dbo.F_RoundQty(Qty),
							 dbo.F_RoundPrice(SalePrice),
							 dbo.F_RoundDiscount(discount),
							 dbo.F_RoundPrice(DiscountPrice),
							 dbo.F_RoundTotal(total),
							 dbo.F_RoundPrice(TaxPrice),
							 dbo.F_RoundTotal(TaxTotal),
							 comment,
							 TeamNo,
							 TeamNO1,
							 Serial,
							 OldID,
							 dbo.F_RoundPrice(CostPrice),
							 OldBillNumberID,
							 dbo.F_RoundPrice(InputCostPrice),
							 GoodsOrder,
							 GoodsNumber,
							 ProduceDate,
							 ValidDate,
							 dbo.F_RoundPrice(GoodsCostPrice),
							 HandZeroCost,
							 dbo.F_RoundTotal(SaleTotal),
							 dbo.F_RoundTax(Tax),
							 KTypeID,
							 Stypeid,
							 dbo.F_RoundTotal(TaxMoney),
							 dbo.F_RoundPrice(NSalePrice),
							 dbo.F_RoundTotal(NSaleTotal),
							 dbo.F_RoundPrice(NDiscountPrice),
							 dbo.F_RoundTotal(NTotal),
							 dbo.F_RoundPrice(NTaxPrice),
							 dbo.F_RoundTotal(NTaxTotal),
							 dbo.F_RoundTotal(NTaxMoney),
							 UnitID,
							 NUnitID,
							 dbo.F_RoundQty(NQty),
							 dbo.F_RoundTranslateRate(UnitRate),
							 NUnitMsg,
							 MUnitID,
							 dbo.F_RoundQty(MQty),
							 dbo.F_RoundTranslateRate(MUnitRate),
							 MUnitMsg,
							 dbo.F_RoundPrice(MSalePrice),
							 dbo.F_RoundPrice(MDiscountPrice),
							 dbo.F_RoundPrice(MTaxPrice),
							 dbo.F_RoundPrice(CurMSalePrice),
							 dbo.F_RoundPrice(CurMDiscountPrice),
							 dbo.F_RoundPrice(CurMTaxPrice),
							 CargoID,
							 ItemID,
							 IsCombined,
							 dbo.F_RoundQty(InvoiceQty),
							 dbo.F_RoundTotal(InvoiceMoney),
							 dbo.F_RoundTotal(NInvoiceMoney),
							 IsGift,
							 dbo.F_RoundPrice(ReferPrice),
							 PriceStyle,
							 dbo.F_RoundTotal(InvoiceMoneyEX),
							 dbo.F_RoundTotal(NInvoiceMoneyEX),
							 dbo.F_RoundTotal(InvoiceCostTotal),
							 dbo.F_RoundQty(InvoiceNQty),
							 dbo.F_RoundTotal(CostTotal),
							 dbo.F_RoundTotal(InvoiceSaleMoney),
							 dbo.F_RoundTotal(NInvoiceSaleMoney),
							 dbo.F_RoundQty(ShareFee),
							 [ShowOrder],
							 [PriceSource]
		FROM @Details	A WHERE A.ID=0 OR NOT EXISTS(
			SELECT ID FROM dbo.SendBackBill B WHERE A.ID=B.ID 
												 AND A.BillNumberId=B.BillNumberID
												 AND A.OldBillNumberID=B.OldBillNumberID
												 AND A.OldID=B.OldID
												 )
		
		UPDATE A SET		A.[PtypeId]				= B.[PtypeId],
							A.[Qty]					= B.[Qty],
							A.[SalePrice]			= B.[SalePrice],
							A.[discount]			= B.[discount],
							A.[DiscountPrice]		= B.[DiscountPrice],
							A.[total]				= B.[total],
							A.[TaxPrice]			= B.[TaxPrice],
							A.[TaxTotal]			= B.[TaxTotal],
							A.[comment]				= B.[comment],
							A.[TeamNo]				= B.[TeamNo],
							A.[TeamNO1]				= B.[TeamNO1],
							A.[Serial]				= B.[Serial],
							A.[OldID]				= B.[OldID],
							A.[CostPrice]			= B.[CostPrice],
							A.[OldBillNumberID]		= B.[OldBillNumberID],
							A.[InputCostPrice]		= B.[InputCostPrice],
							A.[GoodsOrder]			= B.[GoodsOrder],
							A.[GoodsNumber]			= B.[GoodsNumber],
							A.[ProduceDate]			= B.[ProduceDate],
							A.[ValidDate]			= B.[ValidDate],
							A.[GoodsCostPrice]		= B.[GoodsCostPrice],
							A.[HandZeroCost]		= B.[HandZeroCost],
							A.[SaleTotal]			= B.[SaleTotal],
							A.[Tax]					= B.[Tax],
							A.[KTypeID]				= B.[KTypeID],
							A.[Stypeid]				= B.[Stypeid],
							A.[TaxMoney]			= B.[TaxMoney],
							A.[NSalePrice]			= B.[NSalePrice],
							A.[NSaleTotal]			= B.[NSaleTotal],
							A.[NDiscountPrice]		= B.[NDiscountPrice],
							A.[NTotal]				= B.[NTotal],
							A.[NTaxPrice]			= B.[NTaxPrice],
							A.[NTaxTotal]			= B.[NTaxTotal],
							A.[NTaxMoney]			= B.[NTaxMoney],
							A.[UnitID]				= B.[UnitID],
							A.[NUnitID]				= B.[NUnitID],
							A.[NQty]				= B.[NQty],
							A.[UnitRate]			= B.[UnitRate],
							A.[NUnitMsg]			= B.[NUnitMsg],
							A.[MUnitID]				= B.[MUnitID],
							A.[MQty]				= B.[MQty],
							A.[MUnitRate]			= B.[MUnitRate],
							A.[MUnitMsg]			= B.[MUnitMsg],
							A.[MSalePrice]			= B.[MSalePrice],
							A.[MDiscountPrice]		= B.[MDiscountPrice],
							A.[MTaxPrice]			= B.[MTaxPrice],
							A.[CurMSalePrice]		= B.[CurMSalePrice],
							A.[CurMDiscountPrice]	= B.[CurMDiscountPrice],
							A.[CurMTaxPrice]		= B.[CurMTaxPrice],
							A.[CargoID]				= B.[CargoID],
							A.[ItemID]				= B.[ItemID],
							A.[IsCombined]			= B.[IsCombined],
							A.[InvoiceQty]			= B.[InvoiceQty],
							A.[InvoiceMoney]		= B.[InvoiceMoney],
							A.[NInvoiceMoney]		= B.[NInvoiceMoney],
							A.[IsGift]				= B.[IsGift],
							A.[ReferPrice]			= B.[ReferPrice],
							A.[PriceStyle]			= B.[PriceStyle],
							A.[InvoiceMoneyEX]		= B.[InvoiceMoneyEX],
							A.[NInvoiceMoneyEX]		= B.[NInvoiceMoneyEX],
							A.[InvoiceCostTotal]	= B.[InvoiceCostTotal],
							A.[InvoiceNQty]			= B.[InvoiceNQty],
							A.[CostTotal]			= B.[CostTotal],
							A.[InvoiceSaleMoney]	= B.[InvoiceSaleMoney],
							A.[NInvoiceSaleMoney]	= B.[NInvoiceSaleMoney],
							A.[ShareFee]			= B.[ShareFee],
							A.[ShowOrder]			= B.[ShowOrder],
							A.[PriceSource]	 = B.[PriceSource]
		FROM SendBackBill A,@Details B WHERE A.ID=B.ID 
										 AND A.BillNumberId=B.BillNumberID
										 AND A.OldBillNumberID=B.OldBillNumberID
										 AND A.OldID=B.OldID
		
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO
IF EXISTS(SELECT Name FROM SysObjects WHERE ID=OBJECT_ID('dbo.GP_InsertSendBackBillDTCheck',N'P'))
BEGIN
	DROP PROC dbo.GP_InsertSendBackBillDTCheck;
END
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON;
GO
/*
		作者：司华山
		日期：2015-05-19
		描述：发出商品退货单保存前检查退货商品数量与原单商品数量
*/
CREATE PROC dbo.GP_InsertSendBackBillDTCheck
(
	@Details TbType_SendBackBill READONLY
)
--@encode$--
AS
BEGIN
	SELECT 1 AS Ret FROM SendBill a JOIN @Details b on a.BillNumberId=b.OldBillNumberId AND a.Id=b.OldId
	WHERE b.OldBillNumberId<>0 AND ISNULL(a.Qty,0)-ISNULL(a.Backqty,0)<b.Qty 
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'dbo.Gp_InsertSendBillDT',N'P'))
BEGIN
	DROP PROC dbo.Gp_InsertSendBillDT
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
			作者：司华山
			日期：2015-05-14
			描述：新增发出商品入库明细
*/

CREATE PROC dbo.Gp_InsertSendBillDT
(
	@Details TbType_SendBill READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @BillNumberID VARCHAR(50)
		
	SELECT TOP 1 @BillNumberID = BillNumberID FROM @details
	
	-- 更新待收货数量
	UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
	FROM OrderBill a 
	JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM @details b WHERE b.OrderId<>-1 GROUP BY orderid)b ON b.orderid=a.OrderID
	
	--期初单据不处理草稿库存
	IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND IsIni=0)
	BEGIN
		-- 保存前先将原单据对草稿库存的影响恢复【负向影响库存】
		EXEC GP_Deal_DraftQTY @BillNumberID,402,'-'
		
		IF EXISTS (SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND ifcheck='f' AND draft=1)
		BEGIN
			-- 处理订单库存,先减去引用未过账数量
			EXEC GP_Deal_OrderReferQty @BillnumberID,402,'-'
		END
		ELSE
		BEGIN
			-- 处理订单库存,先减去过账数量
			EXEC GP_Deal_OrderReachQTY @BillnumberID,402,'-'
		END
	END	
	DELETE A FROM dbo.SendBill A,@Details B WHERE A.BillNumberId=B.BillNumberId
		AND NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID
												 AND A.BillNumberId=B.BillNumberID
												 AND A.OrderID=B.OrderId
												 AND B.ID<>0)
	
	INSERT INTO dbo.SendBill([BillNumberId],
							 [PtypeId],
							 [Qty],
							 [SalePrice],
							 [discount],
							 [DiscountPrice],
							 [costprice],
							 [total],
							 [TaxPrice],
							 [TaxTotal],
							 [comment],
							 [OrderID],
							 [TeamNo],
							 [TeamNO1],
							 [Serial],
							 [InputCostPrice],
							 [GoodsOrder],
							 [BackQty],
							 [GoodsNumber],
							 [ProduceDate],
							 [ValidDate],
							 [GoodsCostPrice],
							 [HandZeroCost],
							 [SaleTotal],
							 [Tax],
							 [KTypeID],
							 [Stypeid],
							 [ShareFee],
		 					 [TaxMoney],
							 [NSalePrice],
							 [NSaleTotal],
							 [NDiscountPrice],
							 [NTotal],
							 [NTaxPrice],
							 [NTaxTotal],
						 	 [NTaxMoney],
							 [UnitID],
							 [NUnitID],
							 [NQty],
							 [UnitRate],
							 [NUnitMsg],
							 [MUnitID],
							 [MQty],
							 [MUnitRate],
							 [MUnitMsg],
							 [MSalePrice],
							 [MDiscountPrice],
							 [MTaxPrice],
							 [CurMSalePrice],
							 [CurMDiscountPrice],
							 [CurMTaxPrice],
							 [CargoID],
							 [ItemID],
							 [IsCombined],
							 [entryCode],
							 [InvoiceQty],
							 [InvoiceMoney],
							 [NInvoiceMoney],
							 [PriceSource],
							 [IsGift],
							 [ReferPrice],
							 [PriceStyle],
							 [InvoiceMoneyEX],
							 [NInvoiceMoneyEX],
							 [InvoiceCostTotal],
							 [OldBillNumberID],
							 [OldID],
							 [InvoiceNQty],
							 [CostTotal],
							 [InvoiceSaleMoney],
							 [NInvoiceSaleMoney],
							 [ShowOrder]
							)
	SELECT 
							 BillNumberId,
							 PtypeId,
							 dbo.F_RoundQty(Qty),
							 dbo.F_RoundPrice(SalePrice),
							 dbo.F_RoundDiscount(discount),
							 dbo.F_RoundPrice(DiscountPrice),
							 dbo.F_RoundPrice(costprice),
							 dbo.F_RoundTotal(total),
							 dbo.F_RoundPrice(TaxPrice),
							 dbo.F_RoundTotal(TaxTotal),
							 comment,
							 OrderID,
							 TeamNo,
							 TeamNO1,
							 Serial,
							 dbo.F_RoundPrice(InputCostPrice),
							 GoodsOrder,
							 dbo.F_RoundQty(BackQty),
							 GoodsNumber,
							 ProduceDate,
							 ValidDate,
							 dbo.F_RoundPrice(GoodsCostPrice),
							 HandZeroCost,
							 dbo.F_RoundTotal(SaleTotal),
							 dbo.F_RoundTax(Tax),
							 KTypeID,
							 Stypeid,
							 ShareFee,
		 					 dbo.F_RoundTotal(TaxMoney),
							 dbo.F_RoundPrice(NSalePrice),
							 dbo.F_RoundTotal(NSaleTotal),
							 dbo.F_RoundPrice(NDiscountPrice),
							 dbo.F_RoundTotal(NTotal),
							 dbo.F_RoundPrice(NTaxPrice),
							 dbo.F_RoundTotal(NTaxTotal),
						 	 dbo.F_RoundTotal(NTaxMoney),
							 UnitID,
							 NUnitID,
							 dbo.F_RoundQty(NQty),
							 dbo.F_RoundTranslateRate(UnitRate),
							 NUnitMsg,
							 MUnitID,
							 dbo.F_RoundQty(MQty),
							 dbo.F_RoundTranslateRate(MUnitRate),
							 MUnitMsg,
							 dbo.F_RoundPrice(MSalePrice),
							 dbo.F_RoundPrice(MDiscountPrice),
							 dbo.F_RoundPrice(MTaxPrice),
							 dbo.F_RoundPrice(CurMSalePrice),
							 dbo.F_RoundPrice(CurMDiscountPrice),
							 dbo.F_RoundPrice(CurMTaxPrice),
							 CargoID,
							 ItemID,
							 IsCombined,
							 entryCode,
							 dbo.F_RoundQty(InvoiceQty),
							 dbo.F_RoundTotal(InvoiceMoney),
							 dbo.F_RoundTotal(NInvoiceMoney),
							 PriceSource,
							 IsGift,
							 dbo.F_RoundPrice(ReferPrice),
							 PriceStyle,
							 dbo.F_RoundTotal(InvoiceMoneyEX),
							 dbo.F_RoundTotal(NInvoiceMoneyEX),
							 dbo.F_RoundTotal(InvoiceCostTotal),
							 OldBillNumberID,
							 OldID,
							 dbo.F_RoundQty(InvoiceNQty),
							 dbo.F_RoundTotal(CostTotal),
							 dbo.F_RoundTotal(InvoiceSaleMoney),
							 dbo.F_RoundTotal(NInvoiceSaleMoney),
							 ShowOrder
	FROM @Details A WHERE ID=0 OR NOT EXISTS(SELECT ID FROM dbo.SendBill B WHERE A.ID=B.ID
																			 AND A.BillNumberId=B.BillNumberID
																			 AND A.OrderID=B.OrderId)
	
	
	UPDATE A SET		A.[PtypeId]				=B.[PtypeId],
						A.[Qty]					=B.[Qty],
						A.[SalePrice]			=B.[SalePrice],
						A.[discount]			=B.[discount],
						A.[DiscountPrice]		=B.[DiscountPrice],
						A.[costprice]			=B.[costprice],
						A.[total]				=B.[total],
						A.[TaxPrice]			=B.[TaxPrice],
						A.[TaxTotal]			=B.[TaxTotal],
						A.[comment]				=B.[comment],
						A.[OrderID]				=B.[OrderID],
						A.[TeamNo]				=B.[TeamNo],
						A.[TeamNO1]				=B.[TeamNO1],
						A.[Serial]				=B.[Serial],
						A.[InputCostPrice]		=B.[InputCostPrice],
						A.[GoodsOrder]			=B.[GoodsOrder],
						A.[BackQty]				=B.[BackQty],
						A.[GoodsNumber]			=B.[GoodsNumber],
						A.[ProduceDate]			=B.[ProduceDate],
						A.[ValidDate]			=B.[ValidDate],
						A.[GoodsCostPrice]		=B.[GoodsCostPrice],
						A.[HandZeroCost]		=B.[HandZeroCost],
						A.[SaleTotal]			=B.[SaleTotal],
						A.[Tax]					=B.[Tax],
						A.[KTypeID]				=B.[KTypeID],
						A.[Stypeid]				=B.[Stypeid],
						A.[ShareFee]			=B.[ShareFee],
						A.[TaxMoney]			=B.[TaxMoney],
						A.[NSalePrice]			=B.[NSalePrice],
						A.[NSaleTotal]			=B.[NSaleTotal],
						A.[NDiscountPrice]		=B.[NDiscountPrice],
						A.[NTotal]				=B.[NTotal],
						A.[NTaxPrice]			=B.[NTaxPrice],
						A.[NTaxTotal]			=B.[NTaxTotal],
						A.[NTaxMoney]			=B.[NTaxMoney],
						A.[UnitID]				=B.[UnitID],
						A.[NUnitID]				=B.[NUnitID],
						A.[NQty]				=B.[NQty],
						A.[UnitRate]			=B.[UnitRate],
						A.[NUnitMsg]			=B.[NUnitMsg],
						A.[MUnitID]				=B.[MUnitID],
						A.[MQty]				=B.[MQty],
						A.[MUnitRate]			=B.[MUnitRate],
						A.[MUnitMsg]			=B.[MUnitMsg],
						A.[MSalePrice]			=B.[MSalePrice],
						A.[MDiscountPrice]		=B.[MDiscountPrice],
						A.[MTaxPrice]			=B.[MTaxPrice],
						A.[CurMSalePrice]		=B.[CurMSalePrice],
						A.[CurMDiscountPrice]	=B.[CurMDiscountPrice],
						A.[CurMTaxPrice]		=B.[CurMTaxPrice],
						A.[CargoID]				=B.[CargoID],
						A.[ItemID]				=B.[ItemID],
						A.[IsCombined]			=B.[IsCombined],
						A.[entryCode]			=B.[entryCode],
						A.[InvoiceQty]			=B.[InvoiceQty],
						A.[InvoiceMoney]		=B.[InvoiceMoney],
						A.[NInvoiceMoney]		=B.[NInvoiceMoney],
						A.[PriceSource]			=B.[PriceSource],
						A.[IsGift]				=B.[IsGift],
						A.[ReferPrice]			=B.[ReferPrice],
						A.[PriceStyle]			=B.[PriceStyle],
						A.[InvoiceMoneyEX]		=B.[InvoiceMoneyEX],
						A.[NInvoiceMoneyEX]		=B.[NInvoiceMoneyEX],
						A.[InvoiceCostTotal]	=B.[InvoiceCostTotal],
						A.[OldID]				=B.[OldID],
						A.[OldBillNumberID]		=B.[OldBillNumberID],
						A.[InvoiceNQty]			=B.[InvoiceNQty],
						A.[CostTotal]			=B.[CostTotal],
						A.[InvoiceSaleMoney]	=B.[InvoiceSaleMoney],
						A.[NInvoiceSaleMoney]	=B.[NInvoiceSaleMoney],
						A.[ShowOrder]			=B.[ShowOrder]		
	FROM SendBill A ,@Details B WHERE A.ID=B.ID
								  AND A.BillNumberId=B.BillNumberID
								  AND A.OrderID=B.OrderId
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_InsertSerialAdjustBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].GP_InsertSerialAdjustBill
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-08-18
-- Description: 序列号调整单明细保存
-- =============================================
CREATE PROCEDURE GP_InsertSerialAdjustBill
(
		@BillNumberId			NUMERIC(10, 0),	 --单据编号
		@Serial					VARCHAR(60),	 --新序列号
		@OldSerial				VARCHAR(60),	 --旧的序列号
		@Ktypeid				VARCHAR(50),	 --仓库
		@Ptypeid				VARCHAR(50),	 --商品
		@Btypeid1				VARCHAR(50),	 --供应商
		@Btypeid2				VARCHAR(50),	 --销售商
		@InKtypeTime			DATETIME,		 --入库时间
		@OutKtypeTime			DATETIME,		 --出库时间
		@State					INT,			 --状态
		@Note					VARCHAR(500)	 --备注
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
	DECLARE @ID INT,@SameSearilID INT,@BillId INT
	
	INSERT INTO SerialAdjustBill
		(
			BillNumberId,
			Serial,
			OldSerial,
			KtypeID,
			PtypeID,
			BTypeID1,
			BTypeID2,
			InKtypeTime,
			OutKtypeTime,
			State,
			Note	
		)
		VALUES
		(
			@BillNumberId,
			@Serial,
			@OldSerial,
			@KtypeID,
			@PtypeID,
			@BTypeID1,
			@BTypeID2,
			@InKtypeTime,
			@OutKtypeTime,
			@State,
			@Note
		)
		
	SET @ID=SCOPE_IDENTITY();
	--做过序列号调整单后在做调整单
	/*IF EXISTS(SELECT Serial FROM SerialAdjustBill WHERE Serial=@OldSerial AND ID<>@ID)
	BEGIN
		SET @SameSearilID=(SELECT top 1 sameSearilID FROM SerialAdjustBill WHERE Serial=@OldSerial order by ID desc)
	END
	ELSE
	BEGIN
		SET @SameSearilID=@ID
	END
	SELECT TOP 1 @BillId=Bil.BillNumberId FROM BillIndex Bil,Gp_InOutPTypeSerial G WHERE G.BillNumberid=Bil.BillNumberId AND Bil.RedWord =0 AND Bil.IfCheck = 't' AND  ('я'+G.Serial+'я') = @OldSerial AND G.BillType NOT IN (71,72,87,88,203) ORDER BY Bil.Id DESC 
	IF @BillId IS NULL AND EXISTS(SELECT Serial FROM SerialAdjustBill WHERE Serial=@OldSerial AND ID<>@ID)
	BEGIN
		SET @BillId=(SELECT top 1 BillId FROM SerialAdjustBill WHERE Serial=@OldSerial order by ID desc)
	END
	UPDATE SerialAdjustBill SET SameSearilID=@SameSearilID,BillId=@BillId WHERE ID=@ID
	*/
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_InsertSerialAdjustBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].GP_InsertSerialAdjustBillDT
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-- Author:			李海洋
-- Create date: 2012-05-14
-- Description: 序列号调整单明细保存(表值参数方式)
*/
CREATE PROCEDURE GP_InsertSerialAdjustBillDT
(
		@details TBType_SerialEdit READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	INSERT INTO SerialAdjustBill
		(
			BillNumberId,
			Serial,
			OldSerial,
			KtypeID,
			PtypeID,
			BTypeID1,
			BTypeID2,
			InKtypeTime,
			OutKtypeTime,
			State,
			Note,
			ShowOrder
		)
		SELECT 
			BillNumberId
			,Serial
			,OldSerial
			,KtypeID
			,PtypeID
			,BTypeID1
			,BTypeID2
			,InKtypeTime
			,OutKtypeTime
			,State
			,Note
			,ShowOrder
		FROM @details

	IF @@ROWCOUNT = 0 
		or @@ERROR <> 0
		RAISERROR('插入单据发生错误！',16 , 1)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_InsertSerialAdjustIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].GP_InsertSerialAdjustIndex
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-08-18
-- Description: 序列号调整单主表插入和修改
-- =============================================
CREATE PROCEDURE GP_InsertSerialAdjustIndex
(
		@BillNumberId			NUMERIC(10, 0),	 --单据编号
		@BillDate				DATETIME,		 --做单时间
		@BillCode				VARCHAR(200),	 --单据编号
		@BillType				NUMERIC(4, 0),   --单据类型
		@comment				VARCHAR(500),	 --备注
		@btypeid				VARCHAR(50) ,	 --分支机构
		@dtypeid				VARCHAR(50) ,	 --分支机构
		@etypeid				VARCHAR(50) ,	 --分支机构
		@ktypeid				VARCHAR(50) ,	 --分支机构
		@ktypeid2				VARCHAR(50) ,	 --分支机构
		@ifcheck				CHAR(1),		 --是否过账
		@checke					VARCHAR(50),	 --制单人
		@totalqty				 NUMERIC(24, 10) ,	 --总数量
		@period					SMALLINT,
		@explain				VARCHAR(500),	 --说明
		@RedWord				INT,			 --红冲
		@Draft					BIT,			  --是否草稿
		--@poster					VARCHAR(50),
		@Stypeid				VARCHAR(50) ,	 --分支机构
		@LastUpdateTime			DATETIME		 --最后更新时间
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
		DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
		EXEC Gp_GetSubValue 'period',@STypeID,@period out
		SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@period
		DECLARE @CurDate datetime
		DECLARE @IsOrNotPassOneDay bit
		
	IF @BillNumberId = -1	--新增单据
	BEGIN
	
			-- ********	判断是否试用版 - Start	********
		DECLARE @N int, @intVersion int

		-- 判断版本号，是否试用版
		SELECT	@N = CAST(SubValue AS int)
		FROM	SysData1
		WHERE	SubNo = 2	-- 版本号

		IF @N IS NULL RETURN -1

		DECLARE @intBit int, @intMask int
		SELECT @intBit = @N & 15
		SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
		SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)
		-- ********	判断是否试用版 - END	********

		DECLARE @Re int,@Flag int
		EXEC @Re=Gp_Validate 2, @Flag OUTPUT
		IF @Re <>0 RETURN -3 --检查程序版本错误

		IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
		BEGIN
			--RAISERROR('校验错误 ！',16,1) 
			RETURN -3 --检查程序版本错误
		END

		IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
		BEGIN
			DECLARE @billnumberidtmp int
			SELECT @billnumberidtmp=ISNULL(COUNT(billnumberid),0) FROM billindex
			
			IF @billnumberidtmp > 200
			BEGIN
				--RAISERROR('试用版 ！',16,1) 
				RETURN -1
			END
		END  
			

		IF @BillType NOT IN (184,185) 
		BEGIN
			IF @BillDate<@BeginDate and @BillType <> 203
			BEGIN 
				--RAISERROR('录单日期小于本期开始日期 ！',16,1)
				RETURN -2
			END
			---根据配置检查过帐日期是否当前日期  开始 如果单据没有审核流程才判断,如果有审核流程,则在审核流程中判断 谢吉康 2004-06-14
			IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType=@BillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)	--检查单据是否有审核流程
			BEGIN
				SELECT @CurDate=GETDATE()
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
				BEGIN 
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -4
				END
			END
			--有审核流程单据，第一次录单时需要和当前日期一致
			ELSE
			BEGIN
				SELECT @CurDate=GETDATE()
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
				BEGIN 
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -4
				END
			END
			---根据配置检查过帐日期是否当前日期  完毕
		END
	
		INSERT INTO SerialAdjustIndex
		(
			BillDate,
			BillCode,
			BillType,
			comment,
			LastUpdateTime,
			RedWord,
			Stypeid,
			btypeid,
			checke,
			draft,
			dtypeid,
			etypeid,
			explain,
			ifcheck,
			ktypeid,
			ktypeid2,
			period,
			totalqty
		)
		VALUES
		(
			@BillDate,
			@BillCode,
			@BillType,
			@comment,
			@LastUpdateTime,
			@RedWord,
			@Stypeid,
			@btypeid,
			@checke,
			@draft,
			@dtypeid,
			@etypeid,
			@explain,
			@ifcheck,
			@ktypeid,
			@ktypeid2,
			@period,
			dbo.F_RoundQty(@totalqty)
		)
		DECLARE   @intReturn	BIGINT

		SELECT @intReturn=SCOPE_IDENTITY();
	END
	ELSE   --修改单据
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM SerialAdjustIndex WHERE  draft=0 AND ifcheck='t' AND [BillNumberId]  = @BillNumberId)
			RETURN -5

		IF NOT EXISTS(SELECT TOP 1 1 FROM SerialAdjustIndex WHERE BillNumberID = @BillNumberID AND BillType = @BillType)
			RETURN -7
			
		IF @BillType NOT IN (184,185)
		BEGIN
			IF @BillDate<@BeginDate and @BillType <> 203
			BEGIN 
				--RAISERROR('录单日期小于本期开始日期 ！',16,1) 
				RETURN -2
			END
			
			---根据配置检查过帐日期是否当前日期  开始 如果单据没有审核流程才判断,如果有审核流程,则在审核流程中判断 谢吉康 2004-06-14
			DECLARE @chvIfAudit varchar(10)
			IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType=@BillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)	--检查单据是否有审核流程
			BEGIN
				SELECT @CurDate=GETDATE()
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
				BEGIN 
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -4
				END
			END
			ELSE
			BEGIN
				SET @chvIfAudit = ''
				SELECT @CurDate=BillDate,@chvIfAudit=ISNULL(IfAudit,'') FROM AuditingBill Where BillNumberId = @BillNumberId AND BillIndexType<>0
				IF @chvIfAudit = '' OR @chvIfAudit = '-1'
				BEGIN
					SELECT @CurDate=GETDATE()
				END
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
				BEGIN
			
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -4
				END
			
			END
		END
	
	
		 UPDATE SerialAdjustIndex 
		 SET
			BillDate=@BillDate,
			BillCode=@BillCode,
			BillType=@BillType,
			Comment=@comment,
			LastUpdateTime=@LastUpdateTime,
			totalqty=dbo.F_RoundQty(@totalqty),
			RedWord=@RedWord,
			Stypeid=@Stypeid,
			btypeid=@btypeid,
			checke=@checke,
			draft=@Draft,
			dtypeid=@dtypeid,
			etypeid=@etypeid,
			explain=@explain,
			ifcheck=@ifcheck,
			ktypeid=@ktypeid,
			ktypeid2=@ktypeid2,
			period=@period
		 WHERE BillNumberId=@BillNumberId
		 
		 SELECT @intReturn=@BillNumberId
		 
		--删除自定义表头列
		DELETE FROM CustomBillColumns	WHERE billnumberid=@BillNumberId AND BillType=@BillType
		--删除自定义明细列
		DELETE FROM CustomBillDetailColumns WHERE billnumberid=@BillNumberId AND BillType=@BillType

		 
		 DELETE  FROM SerialAdjustBill WHERE BillNumberId=@BillNumberId
	END	

END

RETURN	@intReturn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[Gp_InsertShareFeeBillDT]') AND OBJECTPROPERTY(ID, N'IsProcedure') = 1)
	DROP PROCEDURE [DBO].Gp_InsertShareFeeBillDT
GO
/*
	作者：周华
	时间：2012-05-15 16:27:45.593
	描述：采购待摊费用明细写入的dt版
*/
CREATE PROCEDURE Gp_InsertShareFeeBillDT
(
	@BillNumberId INT
	,@BillType INT
	,@tb TbType_ShareFee READONLY
)
--@encode$--	
AS
BEGIN
	INSERT INTO ShareFeeBill(
		BillNumberId
		,BillType
		,FromBillNumberId
		,FromBillId
		,Comment
		,ShowOrder
	) SELECT @BillNumberId,@BillType,FromBillNumberId,FromBillId,Comment,ShowOrder FROM @tb;
	
	
	UPDATE A SET A.ShowOrder=B.RowIndex FROM ShareFeeBill A,(
		SELECT ID,ROW_NUMBER()OVER(ORDER BY ID ASC) AS RowIndex,BillNumberId FROM dbo.ShareFeeBill WHERE BillNumberId=@BillNumberId
	) B
	WHERE A.BillNumberID=B.BillNumberID AND A.ID=B.ID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[Gp_InsertShareSourceBillDT]') AND OBJECTPROPERTY(ID, N'IsProcedure') = 1)
	DROP PROCEDURE [DBO].Gp_InsertShareSourceBillDT
GO
/*
	作者：周华
	时间：2012-05-15 16:27:45.593
	描述：采购待摊费2用明细写入的dt版
*/
CREATE PROCEDURE  Gp_InsertShareSourceBillDT
(
	@BillNumberId INT
	,@BillType INT
	,@tb TbType_ShareSource READONLY
)
--@encode$--	
AS
BEGIN
	INSERT INTO ShareSourceBill(
		BillNumberId
		,BillType
		,FromBillNumberId
		,FromBillId
		,FromBillType
		,ShareFee
		,Comment
		,ShowOrder
		
	) SELECT @BillNumberId,@BillType,FromBillNumberId,FromBillId,FromBillType,dbo.F_RoundTotal(ShareFee),Comment,ShowOrder
	FROM @tb WHERE ShareFee<>0;
	
	UPDATE A SET A.ShowOrder=B.RowIndex FROM ShareSourceBill A,(
		SELECT ID,ROW_NUMBER()OVER(ORDER BY ID ASC) AS RowIndex,BillNumberId FROM dbo.ShareSourceBill WHERE BillNumberId=@BillNumberId
	) B
	WHERE A.BillNumberID=B.BillNumberID AND A.ID=B.ID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_InsertSmsTemplateContent]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Gp_InsertSmsTemplateContent]
GO

/*
	作者：谢吉康
	日期：2018-11-06
	描述：写入模版内容
*/
CREATE PROCEDURE Gp_InsertSmsTemplateContent
(
	@smstemplatecode	VARCHAR(500),			--编号 
	@smstemplatename	VARCHAR(500),			--名称
	@smstemplatecontent	VARCHAR(MAX),			--内容	
	@smsbeizhu			VARCHAR(MAX),			--备注
	@templatetype		VARCHAR(10),			--模版类型
	@smsbilltype		VARCHAR(10),			--单价类型
	@retcontent			VARCHAR(MAX) OUTPUT		--返回数据
)
AS
SET NOCOUNT ON

--翻译模版
DECLARE @returncontent VARCHAR(MAX)

EXEC Web_ConvertBillTypeOldSmsContentToHyyun @smsbilltype,@smstemplatecontent,@returncontent OUTPUT

--写入数据
INSERT INTO SMSTemplate
(
	smstemplatecode,
	smstemplatename,
	smstemplatecontent,
	smsbeizhu,
	templatetype,
	smsbilltype,
	HyyunSmsTemplateContent
)VALUES(
	@smstemplatecode,
	@smstemplatename,
	@smstemplatecontent,
	@smsbeizhu,
	@templatetype,
	@smsbilltype,
	@returncontent
) 

--返回串
SET @retcontent = @returncontent

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'dbo.GP_InsertStockAllotBillDT',N'P'))
BEGIN
	DROP PROC dbo.GP_InsertStockAllotBillDT
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	仓库调拨单
*/
                
CREATE PROC dbo.GP_InsertStockAllotBillDT
(
	@details Tb_StockAllotBill READONLY
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	INSERT INTO dbo.FactDepotAllot      
	(
		 BillNumberID , serial , ktypeid , ktypeid2 , ptypeid , itemid , NUnitID , Qty , unitid ,
		unitrate , NQty , NUnitMsg , MUnitID , MQty , MUnitRate , MUnitMsg , IsCombined , GoodsOrder ,
		goodsnumber , producedate , validdate , Comment ,InCargoID,OutCargoID
	)
	SELECT    BillNumberID , serial , ktypeid , ktypeid2 , ptypeid , itemid , NUnitID , Qty , unitid ,
	unitrate , NQty , NUnitMsg , MUnitID , MQty , MUnitRate , MUnitMsg , IsCombined , GoodsOrder ,
	goodsnumber , producedate , validdate , Comment ,InCargoID,OutCargoID
	FROM @details
	
	SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE Id=OBJECT_ID(N'dbo.GP_InsertStockIoutBillDT',N'P'))
BEGIN
	DROP PROC dbo.GP_InsertStockIoutBillDT
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
	仓库入库单
*/

CREATE PROC dbo.GP_InsertStockIoutBillDT
(
	@details Tb_StockIoutBill READONLY
)
--@encode$--
AS
SET NOCOUNT ON
	
INSERT INTO dbo.FactDepotInOut 
( 
	BillNumberID ,
	BillType ,
	billdate,
	stypeid, 
	ptypeid ,
	ktypeid ,
	qty ,
	UnitID ,
	UnitRate ,
	NQty ,
	NUnitID ,
	NUnitMsg ,
	MUnitID ,
	MQty ,
	MUnitRate ,
	MUnitMsg ,
	ItemID ,
	IsCombined ,
	GoodsOrder ,
	GoodsNumber ,
	ProduceDate ,
	ValidDate ,
	CargoID ,
	FromBillID ,
	FromBillNumberID ,
	FromBillType ,
	Serial ,
	comment ,
	entryCode
)
SELECT  BillNumberID ,
		BillType ,
		billdate,
		stypeid, 
		ptypeid ,
		ktypeid ,
		qty ,
		UnitID ,
		UnitRate ,
		NQty ,
		NUnitID ,
		NUnitMsg ,
		MUnitID ,
		MQty ,
		MUnitRate ,
		MUnitMsg ,
		ItemID ,
		IsCombined ,
		GoodsOrder ,
		GoodsNumber ,
		ProduceDate ,
		ValidDate ,
		CargoID ,
		FromBillID ,
		FromBillNumberID ,
		FromBillType ,
		Serial ,
		comment ,
		entryCode
FROM	@details

GO
SET NOCOUNT OFF
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



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




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
Author:			 李海洋
Create date: 2012-05-16 
Description: 分支机构调拨单明细表(表值)
*/
CREATE PROCEDURE [Gp_InsertSTypeMoveBillDT]
(
	@details TBType_STypeMoveBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [dbo].[STypeMoveBill] 
( 
	 BillNumberId  			
	,PtypeId  					
	,Qty   							
	,Price   						
	,Total   						
	,Comment  					
	,IsUnit2 						
	,Serial							
	,InputCostPrice			
	,GoodsNumber				
	,ProduceDate				
	,ValidDate					
	,GoodsBTypeID				
	,GoodsCostPrice			
	,GoodsCostTotal 		
	,HandZeroCost			
	,STypeID						
	,BillType						
	,KTypeID						
	,KTypeID2						
	,FromBillNumberID		
	,FromBillID					
	-- 9.0 新字段
	,UnitId					
	,NUnitId				
	,NQty						
	,UnitRate				
	,NUnitMsg				
	,MUnitId				
	,MQty						
	,MUnitRate			
	,MUnitMsg				
	,MPrice					
	,Incargoid			
	,Outcargoid			
	,ItemId					
	,IsCombined		
	,ShowOrder	
)  
SELECT
   BillNumberId  			
	,PtypeId  					
	,dbo.F_RoundQty(Qty)   							
	,dbo.F_RoundPrice(Price)   						
	,dbo.F_RoundTotal(Total)   						
	,Comment  					
	,IsUnit2 						
	,Serial							
	,dbo.F_RoundPrice(InputCostPrice)			
	,GoodsNumber				
	,ProduceDate				
	,ValidDate					
	,GoodsBTypeID				
	,dbo.F_RoundPrice(GoodsCostPrice)			
	,dbo.F_RoundTotal(GoodsCostTotal) 		
	,HandZeroCost	= CASE WHEN BillType = 188
									THEN 1
									ELSE HandZeroCost
									END	
	,STypeID						
	,BillType	
	,KTypeID						
	,KTypeID2						
	,FromBillNumberID		
	,FromBillID					
	-- 9.0 新字段
	,UnitId					
	,NUnitId				
	,dbo.F_RoundQty(NQty)						
	,dbo.F_RoundTranslateRate(UnitRate)				
	,NUnitMsg				
	,MUnitId				
	,dbo.F_RoundQty(MQty)						
	,dbo.F_RoundTranslateRate(MUnitRate)			
	,MUnitMsg				
	,dbo.F_RoundPrice(MPrice)					
	,Incargoid			
	,Outcargoid			
	,ItemId					
	,IsCombined			
	,ShowOrder
	FROM @details
	
IF @@ROWCOUNT = 0 
	RETURN -1 
ELSE 
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-5
--	描述：销售计划时间总表数据插入
---------------------------------------------
CREATE PROCEDURE GP_InsertStypeSaleAllPlan
(
	@fullname		VARCHAR(MAX), 
	@moneyunit		varchar(max),
	@timetotalid	VARCHAR(MAX),
	@alltotalindex	VARCHAR(MAX),
	@alltotalplan	VARCHAR(MAX),
	@comment		VARCHAR(MAX),
	@ifuse			VARCHAR(MAX),
	@intReturn		int out
)
--@encode$--
AS
SET NOCOUNT ON


IF EXISTS (SELECT *FROM StypeSaleAllPlan WHERE FullName=@fullname)
BEGIN
	RAISERROR('该销售计划名称【%s】已经在分支机构销售计划中使用！',16,1,@fullname)RETURN -1
END

INSERT INTO StypeSaleAllPlan (
	FullName,	
	AllRatingValue,
	AllPlanValue,
	TotalID,
	IfAudit,
	IfUse,
	Comment,
	MoneyUnit
)
VALUES(
	@fullname,
	@alltotalindex,
	@alltotalplan,
	@timetotalid,
	'1',
	@ifuse,
	@comment,
	@moneyunit
)

SELECT @intReturn=SCOPE_IDENTITY();
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-13
--	描述：分支机构销售计划数据插入
---------------------------------------------
CREATE PROCEDURE GP_InsertStypeSalePlan
(
	@splanid		VARCHAR(MAX), 
	@stypeid		VARCHAR(MAX),
	@percent		VARCHAR(MAX),
	@totalindex		VARCHAR(MAX),
	@totalplan		VARCHAR(MAX),
	@timetotalid	VARCHAR(MAX),
	@intReturn		int out
)
--@encode$--
AS
SET NOCOUNT ON
INSERT INTO StypeSalePlan (	
	SplanID,
	StypeID,
	ApportionScale,
	RatingValue,
	PlanValue,
	TimeID
)
VALUES(
	@splanid,
	@stypeid,
	@percent,
	@totalindex,
	@totalplan,
	@timetotalid
)

SELECT @intReturn=SCOPE_IDENTITY();
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：赵斌
	日期：2011-5-4
	描述：救援单_-保存表头
*/
CREATE       PROCEDURE Gp_InsertSuccorBill_Index
(
	@BillNumberID				[numeric](10,0),
	@SuccorAddr					VARCHAR(MAX),
	@SuccorId					int,
	@StartDate					DATETIME,
	@ReachDate					DATETIME,
	@ReceptionID				VARCHAR(MAX),	--接电人
	@ReturnDate					DATETIME,
	@ErrDescription				VARCHAR(MAX),
	@ServiceCardNo				VARCHAR(MAX),
	@LinkTel					VARCHAR(MAX),
	@LinkPerson					VARCHAR(MAX)
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO Qp_SuccorBill
(
	[BillNumberID],
	[SuccorAddr],
	[SuccorId],
	[StartDate],
	[ReachDate],
	[ReturnDate],
	[ServiceCardNo],
	[LinkPerson],
	[LinkTel]
)
VALUES
(
	@BillNumberID,
	@SuccorAddr,
	@SuccorId,
	@StartDate,
	@ReachDate,
	@ReturnDate,
	@ServiceCardNo,
	@LinkPerson,
	@LinkTel
)

INSERT INTO Qp_SuccorBill_ErrDescription
(
	[BillNumberId],
	[Comment]
)
VALUES
(
	@BillNumberID,
	@ErrDescription
)


if @@rowcount=0 return -1 else return 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：赵斌
	日期：2011-5-3
	描述：救援单_-维修配件明细表
*/
CREATE       PROCEDURE Gp_InsertSuccorBill_PType
(
	@BillNumberID			[numeric](10,0),
	@PTypeID				varchar(50),
	@KTypeID				varchar(50),
	@Qty					 NUMERIC(24, 10) ,
	@Price					 NUMERIC(24, 10) ,
	@Total					 NUMERIC(24, 10) ,
	@RepairManTypeID		varchar(50),
	@Comment				varchar(500),
	@InputCostPrice			 NUMERIC(24, 10) ,
	@HandZeroCost			int,
	@CargoSpace				varchar(max)
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO Qp_SuccorBill_PType
(
	[BillNumberID],
	[PTypeID],
	[KTypeID],
	[Qty],
	[Price],
	[Total],
	[ETypeID],
	[Comment],
	[InputCostPrice],
	[HandZeroCost],
	[CargoSpace]
)
VALUES
(
	@BillNumberID,
	@PTypeID,
	@KTypeID,
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@Price),
	dbo.F_RoundTotal(@Total),
	ISNULL(@RepairManTypeID,''),
	ISNULL(@Comment,''),
	dbo.F_RoundPrice(@InputCostPrice),
	@HandZeroCost,
	@CargoSpace
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：赵斌
	日期：2011-5-3
	描述：救援单_-维修项目明细表
*/
CREATE       PROCEDURE Gp_InsertSuccorBill_RepairItems
(
	@BillNumberID			[numeric](10,0),
	@RepairItemsTypeID		varchar(50),
	@StandardManHour		 NUMERIC(24, 10) ,
	@CheckHour				 NUMERIC(24, 10) ,
	@Total					 NUMERIC(24, 10) ,
	@RepairManTypeID		varchar(50),
	@Comment				varchar(250),
	@CostTotal				 NUMERIC(24, 10) 
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO Qp_SuccorBill_RepairItems
(
	[BillNumberID],
	[RepairItemsTypeID],
	[StandardManHour],
	[CheckHour],
	[Total],
	[ETypeID],
	[Comment],
	CostTotal
)
VALUES
(
	@BillNumberID,
	ISNULL(@RepairItemsTypeID,''),
	@StandardManHour,
	@CheckHour,
	dbo.F_RoundTotal(@Total),
	ISNULL(@RepairManTypeID,''),
	@Comment,
	dbo.F_RoundTotal(@CostTotal)
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：赵斌
	日期：2011-5-3
	描述：救援单_-救援收费项目明细表
*/
CREATE       PROCEDURE Gp_InsertSuccorBill_SuccorType
(
	@BillNumberID			[numeric](10,0),
	@SuccorChargeId			int,
	@Total					 NUMERIC(24, 10) ,
	@Comment				varchar(max)
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO Qp_SuccorBill_SuccorItems
(
	[BillNumberID],
	[SuccorChargeId],
	[Total],
	[Comment]
)
VALUES
(
	@BillNumberID,
	@SuccorChargeId,
	dbo.F_RoundTotal(@Total),
	@Comment
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

CREATE            PROCEDURE [dbo].[Gp_InsertTaxInfo]
(
   @UserCode VARCHAR(50),
   @FullName VARCHAR(50),
   @TaxType INT ,
   @Tax  NUMERIC(24, 10) ,
   @Comment VARCHAR(5000),
   @PyCode VARCHAR(100),
   @actiontype VARCHAR(50),
   @TaxID INT
)
--@encode$--
AS
SET NOCOUNT ON

IF(@actiontype<>'edit')
BEGIN
	-- 判断重复的ID,UserCode

DECLARE @existName VARCHAR(50)
DECLARE @MSG VARCHAR(500)
SELECT @existName = FullName FROM taxinfo WHERE UserCode=@UserCode
IF @existName<>''
BEGIN	
	SET @MSG = '与<%s>的编号相同，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出'
	RAISERROR(@MSG,16,1,@existName) RETURN
END

SELECT @existName = FullName FROM taxinfo WHERE FullName=@FullName
IF @existName<>''
BEGIN
	SET @MSG = '与<%s>的名称相同，请重新进行命名！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出'
	RAISERROR(@MSG,16,1,@existName) RETURN
END
	INSERT INTO dbo.TaxInfo (
	UserCode,
	FullName,
	TaxType,
	Tax,
	Comment,
	PyCode
) VALUES ( 
	@UserCode,
	@FullName,
	@TaxType,
	dbo.F_RoundTax(@Tax),
	@Comment,
	@PyCode)
END
ELSE
BEGIN

-- 判断重复的ID,UserCode

SELECT @existName = FullName FROM taxinfo WHERE UserCode=@UserCode AND TaxID<>@TaxID
IF @existName<>''
BEGIN	
	SET @MSG = '与<%s>的编号相同，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出'
	RAISERROR(@MSG,16,1,@existName) RETURN
END
SELECT @existName = FullName FROM taxinfo WHERE FullName=@FullName AND TaxID<>@TaxID
IF @existName<>''
BEGIN
	SET @MSG = '与<%s>的名称相同，请重新进行命名！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出'
	RAISERROR(@MSG,16,1,@existName) RETURN
END

	UPDATE TaxInfo 
	SET UserCode=@UserCode,
		FullName=@FullName,
		TaxType=@TaxType,
		Tax=@Tax,
		Comment=@Comment,
		PyCode=@PyCode
	WHERE taxId=@TaxID
END












SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


CREATE          PROCEDURE GP_InsertTcBill (
	@StartDate		varchar(10),
	@EndDate		varchar(10),
	@BillNumberID		int,
	@PtypeID		varchar(50),
	@EtypeID		varchar(50),
	@SubName		varchar(1000),
	@Sub			varchar(1000),
	@Row			int,
	@ConstFlag		int,
	@ReturnCode_Row		varchar(500) output
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @existRow int
DECLARE	@billCode varchar(200)
IF EXISTS(SELECT TOP 1 1 FROM TcBill b LEFT JOIN TcBillIndex i ON b.BillNumberId=i.BillNumberId 
		WHERE	b.PtypeID=@PtypeID AND b.EtypeID=@EtypeID AND b.Sub=@Sub 
		AND ((i.StartDate<=@enddate AND i.EndDate>=@enddate) OR (i.StartDate<=@startdate AND i.EndDate>=@startdate) OR (i.StartDate>@startdate AND i.EndDate<@EndDate))
	)
BEGIN
	SELECT @existRow=row, @billCode=BillCode FROM TcBill b LEFT JOIN TcBillIndex i ON b.BillNumberId=i.BillNumberId 
		WHERE	b.PtypeID=@PtypeID AND b.EtypeID=@EtypeID AND b.Sub=@Sub 
		AND ((i.StartDate<=@enddate AND i.EndDate>=@enddate) OR (i.StartDate<=@startdate AND i.EndDate>=@startdate) OR (i.StartDate>@startdate AND i.EndDate<@EndDate))
	SELECT	@ReturnCode_Row=@billCode
	RETURN 0
END
	
insert into [TcBill]
	(
	[billnumberid],
	[PtypeID],
	[EtypeID],
        [SubName],
	[Sub],
	[row],
	[ConstFlag]
	)
values  (
	@billnumberid,
	@PtypeID,
	@EtypeID,
	@SubName,
	@Sub,
	@Row,
	@ConstFlag
	)
if @@rowcount=0 return 0 else return 1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


--**********************************************
--销售提成公式设置
--**********************************************
CREATE                               PROCEDURE [Gp_InsertTCBillIndex]
(
	@BillDate  			[datetime],
	@StarDate			[datetime],
	@EndDate			[datetime],
	@BillCode  			[varchar](200),
	@EtypeId  			[varchar](50),--审核人
	@checke  			[varchar](50), --制单人
	@Comment  			[varchar](256)
	/*
	,
	@STypeID			[varchar](50)
	*/
)
--@encode$--
AS 
SET NOCOUNT ON 

DECLARE @szPeriod [SMALLINT]
DECLARE @check INT = 0
DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
--EXEC Gp_GetSubValue 'period',@STypeID,@szPeriod out
EXEC @check = GP_CheckLimit @EtypeId,5190 --基础提成规则审核、反审核
EXEC Gp_GetSubValue 'period','',@szPeriod out

--IF @check = 1 --没有权限
--BEGIN 
--	SET @EtypeId = ''
--END

SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
IF @BillDate<@BeginDate 
BEGIN 
	RETURN -2
END

---根据配置检查过帐日期是否当前日期
DECLARE @CurDate datetime
DECLARE @IsOrNotPassOneDay bit
SELECT @CurDate=GETDATE()
SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
BEGIN 
	--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
	RETURN -4
END


/*
INSERT [dbo].[TCBillIndex] 
(
	[BillDate],
	[BillCode],
	[Comment],
	[StartDate],
	[EndDate],
	[checke],
	[EtypeID],
	[STypeID]
)
VALUES
(
	@BillDate,
	@BillCode,
	@Comment,
	@StarDate,
	@EndDate,
	@checke,
	@EtypeId,
	@STypeID
)
*/

INSERT [dbo].[TCBillIndex] 
(
	[BillDate],
	[BillCode],
	[Comment],
	[StartDate],
	[EndDate],
	[checke],
	[EtypeID]
)
VALUES
(
	@BillDate,
	@BillCode,
	@Comment,
	@StarDate,
	@EndDate,
	@checke,
	@EtypeId
)

IF @@rowcount =0  OR @@error<>0
	--RAISERROR('更新单据发生错误！',16,1)
	RETURN -5
ELSE
 	RETURN SCOPE_IDENTITY();


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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















/****** Object:  Stored Procedure dbo.Gp_InsertTemplateListTable    Script Date: 2002-6-20 10:14:49 ******/

CREATE   PROCEDURE [Gp_InsertTemplateListTable]
(
 @TemplateID  [int],
 @PtypeId  [varchar](50),
 @Qty    NUMERIC(24, 10) ,
 @Comment  [varchar](50)
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [TemplateListTable] 
  ( [TemplateID],
  [Ptypeid],
  [Qty],
  [comment]) 
 
VALUES 
 ( @TemplateID,
  @Ptypeid,
  dbo.F_RoundQty(@Qty),
  @comment)
if @@rowcount =0  
 return -1
else
 return 0
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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















/****** Object:  Stored Procedure dbo.Gp_InsertTemplateTable    Script Date: 2002-6-20 10:14:49 ******/

CREATE   PROCEDURE [Gp_InsertTemplateTable]
(
 @TemplateName  [varchar](20),
 @PtypeId  [varchar](50),
 @Comment  [varchar](50)
)
--@encode$--
AS 
SET NOCOUNT ON
INSERT INTO [TemplateTable] 
  ([TemplateName],
  [ptypeid],
  [comment]) 
 
VALUES 
 ( @TemplateName,
  @ptypeid,
  @comment)
if @@rowcount =0  
 return -1
else
 return SCOPE_IDENTITY();
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
三包索赔_-配件明细表
*/
CREATE       PROCEDURE Gp_InsertThreePackets_PType
(
	@BillNumberID			[numeric](10,0),
	@PTypeID				varchar(50),
	@Qty					 NUMERIC(24, 10) ,
	@TaxPrice				 NUMERIC(24, 10) ,
	@TaxTotal				 NUMERIC(24, 10) ,
 	@InsuranceTotal			 NUMERIC(24, 10) ,
	@Virtual				INT,
	@Comment				VARCHAR(500),
	@IsUnit2				INT,
	@GoodsCostTotal			 NUMERIC(24, 10) ,
	@QuickOrReceptionBillId	INT
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO Qp_ThreePacketsBill_PType
(
	BillNumberID,
	PTypeID,
	Qty,
	TaxPrice,
	TaxTotal,
	InsuranceTotal,
	Virtual,
	Comment,
	IsUnit2,
	CostTotal,
	QuickOrReceptionBillId
)
VALUES
(
	@BillNumberID,
	ISNULL(@PTypeID,''),
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@TaxPrice),
	dbo.F_RoundTotal(@TaxTotal),
	dbo.F_RoundTotal(@InsuranceTotal),
	@Virtual,
	ISNULL(@Comment,''),
	@IsUnit2,
	dbo.F_RoundTotal(@GoodsCostTotal),
	@QuickOrReceptionBillId
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
三包索赔_-维修项目明细表
*/
CREATE       PROCEDURE Gp_InsertThreePackets_RepairItems
(
	@BillNumberID				[numeric](10,0),
	@RepairItemsTypeID			varchar(50),
	@ManHour					 NUMERIC(24, 10) ,
	@Total						 NUMERIC(24, 10) ,
	@InsuranceTotal				 NUMERIC(24, 10) ,
	@CostTotal					 NUMERIC(24, 10) ,
	@Virtual					INT,
	@Comment					VARCHAR(500),
	@QuickOrReceptionBillId		INT=0
	
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO Qp_ThreePacketsBill_RepairItems
(
	BillNumberID,
	RepairItemsTypeID,
	StandardManHour,
	RepairTotal,
	InsuranceTotal,
	CostTotal,
	Virtual,
	Comment,
	QuickOrReceptionBillId
)
VALUES
(
	@BillNumberID,
	ISNULL(@RepairItemsTypeID,''),
	@ManHour,
	dbo.F_RoundTotal(@Total),
	dbo.F_RoundTotal(@InsuranceTotal),
	dbo.F_RoundTotal(@CostTotal),
	@Virtual,
	ISNULL(@Comment,''),
	@QuickOrReceptionBillId
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


-- ========================================================================
-- 功能说明：		工具出入库台帐明细数据写入
-- 作	 者：		韩林
-- 创建时间：		2011-04-26
-- ========================================================================
------2002-4-16日加orderid
CREATE             PROCEDURE  Gp_InsertToolBill
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 值
	@PtypeID			varchar(50),	-- 工具 ID 值
	@Qty				 NUMERIC(24, 10) ,	-- 工具数量
	@Price				 NUMERIC(24, 10) ,	-- 工具单价
	@ValidDate			varchar(50),	-- 工具保修期
	@Comment			varchar(255),	-- 备注
	@intIsUnit2			int,				-- 是否采用双单位。0：否；1：是
	@STypeID			varchar(50)=''
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO ToolBill
(
	BillNumberID,
	PTypeID,
	Qty,
	Price,
	ValidDate,
	Comment,
	isUnit2
)
VALUES
(
	@BillNumberID,
	@PTypeID,
	dbo.F_RoundQty(@Qty),
	dbo.F_RoundPrice(@Price),
	@ValidDate,
	@Comment,
	@intIsUnit2
)
-- 操作返回值
IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('保存失败！',16,1)
		RETURN
	END
RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertTransportBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertTransportBillDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE GP_InsertTransportBillDT
	@tb TbType_Transportbill READONLY
--@encode$--
AS
BEGIN

DELETE A FROM dbo.Transportbill A,@tb B WHERE A.BillNumberID=B.BillNumberID AND NOT EXISTS(
		SELECT ID FROM @tb B WHERE A.BillNumberID=B.BillNumberID
								AND A.ID=B.ID
							   AND A.GoodsBillID=B.GoodsBillID
							   AND A.GoodsBillNumberID=B.GoodsBillNumberID
							   AND B.ID<>0)
							   
INSERT INTO dbo.Transportbill
        ( billNumberID ,
          ptypeid ,
          qty ,
          behooveQty ,
          comment ,
          GoodsBillNumberID ,
          GoodsBillID ,
          GoodsBillType ,
          ItemID ,
          IsCombined ,
          GoodsNumber ,
          GoodsOrder ,
          Serial ,
          [weight] ,
          Volume,
          ShowOrder
	) 
SELECT billNumberID ,
          ptypeid ,
          qty ,
          behooveQty ,
          comment ,
          GoodsBillNumberID ,
          GoodsBillID ,
          GoodsBillType ,
          ItemID ,
          IsCombined ,
          GoodsNumber ,
          GoodsOrder ,
          Serial ,
          [weight] ,
          Volume,
          ShowOrder
          FROM @tb A WHERE ID=0 OR NOT EXISTS(
	SELECT ID FROM dbo.Transportbill B WHERE A.BillNumberID=B.BillNumberID
								   AND A.GoodsBillID=B.GoodsBillID
								   AND A.GoodsBillNumberID=B.GoodsBillNumberID)
          
          
 INSERT INTO Transportcontrastbill
 (
		[billNumberID],
		[saleBillNumberID],
		[saleBillType],
		ShowOrder
 )
 SELECT [billNumberID],
		[saleBillnumberid],
		[saleBilltype],
		ShowOrder
		FROM @tb a
		WHERE NOT EXISTS( SELECT [billNumberID] FROM dbo.Transportcontrastbill B WHERE
								   A.[billNumberID]=B.[billNumberID]
								   AND A.[saleBillnumberid]=B.[saleBillnumberid])
		GROUP BY billNumberID,saleBillNumberID,saleBillType,ShowOrder
  
 UPDATE A
  SET
    A.[billNumberID] = B.[billNumberID],
	A.[saleBillNumberID]= B.[saleBillNumberID],
	A.[saleBillType]= B.[saleBillType],
	A.ShowOrder= B.ShowOrder
	FROM dbo.Transportcontrastbill A,@tb B WHERE
	               A.[billNumberID]=B.[billNumberID]
				   AND A.[saleBillnumberid]=B.[saleBillnumberid]
				   
				   
 UPDATE A
  SET
	  A.billNumberID =B.billNumberID ,
	  A.ptypeid=B.ptypeid,
	  A.qty=B.qty ,
	  A.behooveQty=B.behooveQty ,
	  A.comment=B.comment ,
	  A.GoodsBillNumberID=B.GoodsBillNumberID ,
	  A.GoodsBillID=B.GoodsBillID ,
	  A.GoodsBillType=B.GoodsBillType ,
	  A.ItemID =B.ItemID,
	  A.IsCombined=B.IsCombined ,
	  A.GoodsNumber =B.GoodsNumber,
	  A.GoodsOrder=B.GoodsOrder ,
	  A.Serial=B.Serial ,
	  A.[weight] =B.[weight],
	  A.Volume=B.Volume,
	  A.ShowOrder=B.ShowOrder
	FROM dbo.Transportbill A,@tb B WHERE
					A.ptypeid=B.ptypeid
	               AND A.BillNumberID=B.BillNumberID
				   AND A.GoodsBillID=B.GoodsBillID
				   AND A.GoodsBillNumberID=B.GoodsBillNumberID
          
SET NOCOUNT OFF	
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



/****** Object:  StoredProcedure [dbo].[Gp_InsertUnitConvertSet]    Script Date: 04/23/2012 09:33:25 ******/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (SELECT * from dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_InsertUnitConvertSet]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_InsertUnitConvertSet]
GO

-- ========================================================================
-- 功能说明：		保存单位换算关系
-- 作者    ：		王刚
-- 时间：			2012-04-17
-- ========================================================================
CREATE    PROCEDURE [dbo].[Gp_InsertUnitConvertSet]
(
	@ptypeid	VARCHAR(50),
	@items		Type_UnitConvertSet  READONLY
)
--@encode$--

AS
--BEGIN TRAN BBB

--建立临时表存储数据
CREATE TABLE #PType_Price
(
	RecAmgSTypeBuyPrice	NUMERIC(24,10),
	UnitID				INT,
	PTypeID				VARCHAR(50)
)
INSERT INTO #PType_Price
( 
	RecAmgSTypeBuyPrice, 
	UnitID, 
	PTypeID 
)
SELECT	RecAmgSTypeBuyPrice, 
		UnitID, 
		PTypeID 
FROM	PType_Price
WHERE	PtypeID = @ptypeid	

DELETE PType_Units_Ext WHERE PtypeID = @ptypeid
DELETE PType_Price WHERE PtypeID = @ptypeid

INSERT INTO PType_Units_Ext(PtypeID,UnitsId,RateType,Rate,IsDefaultUnit,EntryCode,isUse)
SELECT  @ptypeid AS PtypeID,
		UnitsId	,	
		RateType,
		dbo.F_RoundTranslateRate(Rate),		
		IsDefaultUnit,
		EntryCode,
		IsUse
FROM	@items
WHERE	UnitsId IS NOT NULL 
	
UPDATE  ptype_price 
SET		unitid=i.unitsid
FROM	@items i 
WHERE	PTypeID=@PTypeID  
		AND ptype_price.unitid=i.oldunitsid 

----------物价信息----------
--更新已有的
UPDATE	PType_Price
SET		PtypeID=@ptypeid,
		UnitId=it.UnitsId,
		PreBuyPrice1=ISNULL(it.PreBuyPrice1,0),
		PreBuyPrice2=ISNULL(it.PreBuyPrice2,0),
		PreBuyPrice3=ISNULL(it.PreBuyPrice3,0),
		PreBuyPrice4=ISNULL(it.PreBuyPrice4,0),
		PreBuyPrice5=ISNULL(it.PreBuyPrice5,0),
		PreSalePrice1=ISNULL(it.PreSalePrice1,0),
		PreSalePrice2=ISNULL(it.PreSalePrice2,0),
		PreSalePrice3=ISNULL(it.PreSalePrice3,0),
		PreSalePrice4=ISNULL(it.PreSalePrice4,0),
		PreSalePrice5=ISNULL(it.PreSalePrice5,0),
		PreSalePrice6=ISNULL(it.PreSalePrice6,0),
		PreSalePrice7=ISNULL(it.PreSalePrice7,0),
		PreSalePrice8=ISNULL(it.PreSalePrice8,0),
		PreSalePrice9=ISNULL(it.PreSalePrice9,0),
		PreSalePrice10=ISNULL(it.PreSalePrice10,0),
		RetailPrice=ISNULL(it.RetailPrice,0),
		TopSalePrice=ISNULL(it.TopSalePrice,0),
		LowSalePrice=ISNULL(it.LowSalePrice, 0),
		TopBuyPrice=ISNULL(it.TopBuyPrice,0),
		IsDefaultUnit=it.IsDefaultUnit	 
FROM 	@items it 
WHERE	UnitsId is not null 
		AND PType_Price.UnitId=it.UnitsId 
		AND PType_Price.ptypeid=@ptypeid

		
------添加新增的		
INSERT INTO dbo.PType_Price
( 
	UnitId,
	PreBuyPrice1 ,
	PreBuyPrice2 ,
	PreBuyPrice3 ,
	PreBuyPrice4 ,
	PreBuyPrice5 ,
	PreSalePrice1 ,
	PreSalePrice2 ,
	PreSalePrice3 ,
	PreSalePrice4 ,
	PreSalePrice5 ,
	PreSalePrice6 ,
	PreSalePrice7 ,
	PreSalePrice8 ,
	PreSalePrice9 ,
	PreSalePrice10 ,
	RetailPrice ,
	TopSalePrice ,
	LowSalePrice ,  
	TopBuyPrice  ,
	IsDefaultUnit,
	PtypeID
)
SELECT	i.UnitsId,
		ISNULL(i.PreBuyPrice1,0),
		ISNULL(i.PreBuyPrice2,0),
		ISNULL(i.PreBuyPrice3,0),
		ISNULL(i.PreBuyPrice4,0),
		ISNULL(i.PreBuyPrice5,0),
		ISNULL(i.PreSalePrice1,0), 
		ISNULL(i.PreSalePrice2,0),
		ISNULL(i.PreSalePrice3,0),
		ISNULL(i.PreSalePrice4,0),
		ISNULL(i.PreSalePrice5,0),
		ISNULL(i.PreSalePrice6,0),
		ISNULL(i.PreSalePrice7,0),
		ISNULL(i.PreSalePrice8,0),
		ISNULL(i.PreSalePrice9,0),
		ISNULL(i.PreSalePrice10,0),
		ISNULL(i.RetailPrice ,0),
		ISNULL(i.TopSalePrice ,0),
		ISNULL(i.LowSalePrice , 0), 
		ISNULL(i.TopBuyPrice ,0),
		i.IsDefaultUnit ,
		@ptypeid
FROM	@items i
WHERE   NOT EXISTS (SELECT UnitId FROM ptype_price WHERE unitid = i.UnitsId AND ptypeid=@ptypeid)
		AND i.UnitsId is not null 
		
--修改PType_Price的RecAmgSTypeBuyPrice价格
UPDATE	PType_Price
SET		RecAmgSTypeBuyPrice = pp.RecAmgSTypeBuyPrice
FROM	PType_Price P
INNER JOIN #PType_Price pp ON p.PTypeID = pp.PTypeID AND p.UnitID = pp.UnitID		
			
--删除固定单位不在表里的
DELETE	ptype_price
WHERE	ptypeid=@ptypeid
		AND unitid NOT IN (SELECT unitsid from ptype_units_ext WHERE ratetype=0 AND ptypeid=@ptypeid)
	  
--非基本单位 的 其他价格全部为0 则删除不保存到表里面
DELETE  ptype_price 
WHERE	ptypeid=@ptypeid
		AND  IsDefaultUnit=0
		AND ISNULL( [PreBuyPrice1] ,0)=0 
		AND ISNULL( [PreBuyPrice2] ,0)=0 
		AND ISNULL( [PreBuyPrice3] ,0)=0 
		AND ISNULL( [PreBuyPrice4] ,0)=0 
		AND ISNULL( [PreBuyPrice5] ,0)=0 
		AND ISNULL( [PreSalePrice1] ,0)=0 
		AND ISNULL( [PreSalePrice2] ,0)=0 
		AND ISNULL( [PreSalePrice3] ,0)=0 
		AND ISNULL( [PreSalePrice4] ,0)=0 
		AND ISNULL( [PreSalePrice5] ,0)=0 
		AND ISNULL( [PreSalePrice6] ,0)=0 
		AND ISNULL( [PreSalePrice7] ,0)=0 
		AND ISNULL( [PreSalePrice8] ,0)=0 
		AND ISNULL( [PreSalePrice9] ,0)=0 
		AND ISNULL( [PreSalePrice10] ,0)=0 
		AND ISNULL( [RetailPrice] ,0)=0 
		AND ISNULL( [TopSalePrice] ,0)=0 
		AND ISNULL( [LowSalePrice] ,0)=0 
		AND ISNULL( TopBuyPrice,0)=0 
		AND ISNULL( ReferPrice,0)=0 
		AND ISNULL( RecAmgSTypeBuyPrice,0)=0
		AND ISNULL( RecAmgSTypeSalePrice,0)=0
		
--处理分支机构物价信息开始
CREATE TABLE #PType_STypePrice
(
	Nid				  INT	IDENTITY(1,1),
	STypeID           VARCHAR (50) DEFAULT ((0)) NOT NULL,
	PTypeID           VARCHAR (50) DEFAULT ((0)) NOT NULL,
	PreBuyPrice1      NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreBuyPrice2      NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreBuyPrice3      NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreBuyPrice4      NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreBuyPrice5      NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice1     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice2     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice3     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice4     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice5     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice6     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice7     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice8     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice9     NUMERIC (24,10) DEFAULT ((0)) NULL,
	PreSalePrice10    NUMERIC (24,10) DEFAULT ((0)) NULL,
	RetailPrice       NUMERIC (24,10) DEFAULT ((0)) NULL,
	TopSalePrice      NUMERIC (24,10) DEFAULT ((0)) NULL,
	LowSalePrice      NUMERIC (24,10) DEFAULT ((0)) NULL,
	RecPrice          NUMERIC (24,10) DEFAULT ((0)) NULL,
	UnitID            INT DEFAULT ((0)) NOT NULL,
	IsDefaultUnit     INT DEFAULT ((0)) NOT NULL,	
	TopBuyPrice       NUMERIC (24,10) DEFAULT ((0)) NULL,
	referprice        NUMERIC (24,10) DEFAULT ((0)) NULL,
	RecSalePrice      NUMERIC (24,10) DEFAULT ((0)) NULL,
	RecAppraisalPrice NUMERIC (24,10) DEFAULT ((0)) NULL,
	RecSendPrice      NUMERIC (24,10) DEFAULT ((0)) NULL
)

DECLARE 	@Nid					INT,
			@UnitsId				INT,
			@oldunitsid				INT,
			@RateType				INT,			--0代表固定  1代码浮动
			@Rate					NUMERIC(24, 10) ,	--换算率
			@IsDefaultUnit			INT,			--是否默认单位
			@EntryCode				VARCHAR(200),
			@IsUse					INT	,			--是否启用(0否1是)
			@PreBuyPrice1			NUMERIC(24,10) ,       
			@PreBuyPrice2			NUMERIC(24,10) ,
			@PreBuyPrice3			NUMERIC (24,10),
			@PreBuyPrice4			NUMERIC (24,10),
			@PreBuyPrice5			NUMERIC (24,10),
			@PreSalePrice1			NUMERIC(24,10) ,
			@PreSalePrice2			NUMERIC(24,10) ,
			@PreSalePrice3			NUMERIC (24,10),
			@PreSalePrice4			NUMERIC(24,10) ,
			@PreSalePrice5			NUMERIC(24,10)  ,
			@PreSalePrice6			NUMERIC(24,10)  ,
			@PreSalePrice7			NUMERIC(24,10)  ,
			@PreSalePrice8			NUMERIC (24,10) ,
			@PreSalePrice9			NUMERIC (24,10) ,
			@PreSalePrice10			NUMERIC(24,10)  ,
			@RetailPrice			NUMERIC(24,10)  ,
			@TopSalePrice			NUMERIC (24,10) ,
			@LowSalePrice			NUMERIC(24,10)  ,  
			@TopBuyPrice			NUMERIC(24,10)	 ,
			@RecAmgSTypeBuyPrice	NUMERIC(24,10)	 ,
			@RecAmgSTypeSalePrice   NUMERIC(24,10)	 ,
			@ReferPrice				NUMERIC(24,10),
			@recPrice				NUMERIC(24,10),
			@STypeId				VARCHAR(50),
			@UnitID					INT,
			@RecSalePrice			NUMERIC(24,10),	
			@RecAppraisalPrice		NUMERIC(24,10),
			@RecSendPrice			NUMERIC(24,10)

DECLARE PType_StypePrice_Cursor CURSOR FOR
	SELECT	UnitsId,
			OldUnitsId,			
			IsDefaultUnit
	FROM	@items	
	
OPEN PType_StypePrice_Cursor

FETCH NEXT FROM PType_StypePrice_Cursor INTO	@UnitsId,
												@OldUnitsId,											
												@IsDefaultUnit
										
WHILE @@FETCH_STATUS = 0
BEGIN	
	--可能存在多分支机构物价信息，需要循环
	DECLARE MxPType_SType CURSOR FOR
		SELECT	STypeID, 				
				PreBuyPrice1, 
				PreBuyPrice2, 
				PreBuyPrice3, 
				PreBuyPrice4, 
				PreBuyPrice5, 
				PreSalePrice1, 
				PreSalePrice2, 
				PreSalePrice3, 
				PreSalePrice4, 
				PreSalePrice5, 
				PreSalePrice6, 
				PreSalePrice7, 
				PreSalePrice8, 
				PreSalePrice9, 
				PreSalePrice10, 
				RetailPrice, 
				TopSalePrice, 
				LowSalePrice, 
				RecPrice, 			
				IsDefaultUnit, 
				TopBuyPrice, 
				referprice, 
				RecSalePrice, 
				RecAppraisalPrice, 
				RecSendPrice
		FROM	PType_STypePrice
		WHERE	PTypeID = @PTypeId
				AND UnitID = @OldUnitsId
		
	OPEN MxPType_SType
	
	FETCH NEXT FROM MxPType_SType INTO	@STypeID, 
										@PreBuyPrice1, 
										@PreBuyPrice2, 
										@PreBuyPrice3, 
										@PreBuyPrice4, 
										@PreBuyPrice5, 
										@PreSalePrice1, 
										@PreSalePrice2, 
										@PreSalePrice3, 
										@PreSalePrice4, 
										@PreSalePrice5, 
										@PreSalePrice6, 
										@PreSalePrice7, 
										@PreSalePrice8, 
										@PreSalePrice9, 
										@PreSalePrice10, 
										@RetailPrice, 
										@TopSalePrice, 
										@LowSalePrice, 
										@RecPrice, 									
										@IsDefaultUnit, 
										@TopBuyPrice, 
										@referprice, 
										@RecSalePrice, 
										@RecAppraisalPrice, 
										@RecSendPrice
	
	WHILE @@FETCH_STATUS = 0
	BEGIN	
		INSERT INTO #PType_STypePrice
			( 
				STypeID ,
				PTypeID ,
				PreBuyPrice1 ,
				PreBuyPrice2 ,
				PreBuyPrice3 ,
				PreBuyPrice4 ,
				PreBuyPrice5 ,
				PreSalePrice1 ,
				PreSalePrice2 ,
				PreSalePrice3 ,
				PreSalePrice4 ,
				PreSalePrice5 ,
				PreSalePrice6 ,
				PreSalePrice7 ,
				PreSalePrice8 ,
				PreSalePrice9 ,
				PreSalePrice10 ,
				RetailPrice ,
				TopSalePrice ,
				LowSalePrice ,
				RecPrice ,
				UnitID ,
				IsDefaultUnit ,
				TopBuyPrice ,
				referprice ,
				RecSalePrice ,
				RecAppraisalPrice ,
				RecSendPrice
			)VALUES(
				@STypeID , -- STypeID - varchar(50)
				@PTypeID , -- PTypeID - varchar(50)
				@PreBuyPrice1 , -- PreBuyPrice1 - numeric
				@PreBuyPrice2 , -- PreBuyPrice2 - numeric
				@PreBuyPrice3 , -- PreBuyPrice3 - numeric
				@PreBuyPrice4 , -- PreBuyPrice4 - numeric
				@PreBuyPrice5 , -- PreBuyPrice5 - numeric
				@PreSalePrice1 , -- PreSalePrice1 - numeric
				@PreSalePrice2 , -- PreSalePrice2 - numeric
				@PreSalePrice3 , -- PreSalePrice3 - numeric
				@PreSalePrice4 , -- PreSalePrice4 - numeric
				@PreSalePrice5 , -- PreSalePrice5 - numeric
				@PreSalePrice6 , -- PreSalePrice6 - numeric
				@PreSalePrice7 , -- PreSalePrice7 - numeric
				@PreSalePrice8 , -- PreSalePrice8 - numeric
				@PreSalePrice9 , -- PreSalePrice9 - numeric
				@PreSalePrice10 , -- PreSalePrice10 - numeric
				@RetailPrice , -- RetailPrice - numeric
				@TopSalePrice , -- TopSalePrice - numeric
				@LowSalePrice , -- LowSalePrice - numeric
				@RecPrice , -- RecPrice - numeric
				@UnitsId , -- UnitID - int
				@IsDefaultUnit , -- IsDefaultUnit - int
				@TopBuyPrice , -- TopBuyPrice - numeric
				@referprice , -- referprice - numeric
				@RecSalePrice , -- RecSalePrice - numeric
				@RecAppraisalPrice , -- RecAppraisalPrice - numeric
				@RecSendPrice  -- RecSendPrice - numeric
			)
						
			FETCH NEXT FROM MxPType_SType INTO	@STypeID, 
												@PreBuyPrice1, 
												@PreBuyPrice2, 
												@PreBuyPrice3, 
												@PreBuyPrice4, 
												@PreBuyPrice5, 
												@PreSalePrice1, 
												@PreSalePrice2, 
												@PreSalePrice3, 
												@PreSalePrice4, 
												@PreSalePrice5, 
												@PreSalePrice6, 
												@PreSalePrice7, 
												@PreSalePrice8, 
												@PreSalePrice9, 
												@PreSalePrice10, 
												@RetailPrice, 
												@TopSalePrice, 
												@LowSalePrice, 
												@RecPrice, 											
												@IsDefaultUnit, 
												@TopBuyPrice, 
												@referprice, 
												@RecSalePrice, 
												@RecAppraisalPrice, 
												@RecSendPrice
	END
	
	CLOSE MxPType_SType
	DEALLOCATE MxPType_SType	
				
	FETCH NEXT FROM PType_StypePrice_Cursor INTO	@UnitsId,		
													@OldUnitsId,									
													@IsDefaultUnit
END

CLOSE PType_StypePrice_Cursor
DEALLOCATE PType_StypePrice_Cursor	

--写入分支机构物价信息数据
CREATE TABLE #PType_STypePriceTemp
(
	STypeId		VARCHAR(50),
	PTypeId		VARCHAR(50),
	UnitId		INT,
	RecPrice	NUMERIC(24,10)
)
INSERT INTO #PType_STypePriceTemp
( 
	STypeId, 
	PTypeId,
	UnitId, 
	RecPrice 
)
SELECT	STypeId, 
		PTypeId,
		UnitId, 
		RecPrice
FROM	PType_STypePrice
WHERE	PTypeId = @PTypeId

DELETE FROM PType_STypePrice WHERE PTypeId = @PTypeId
INSERT INTO PType_STypePrice
( 
	STypeID ,
	PTypeID ,
	PreBuyPrice1 ,
	PreBuyPrice2 ,
	PreBuyPrice3 ,
	PreBuyPrice4 ,
	PreBuyPrice5 ,
	PreSalePrice1 ,
	PreSalePrice2 ,
	PreSalePrice3 ,
	PreSalePrice4 ,
	PreSalePrice5 ,
	PreSalePrice6 ,
	PreSalePrice7 ,
	PreSalePrice8 ,
	PreSalePrice9 ,
	PreSalePrice10 ,
	RetailPrice ,
	TopSalePrice ,
	LowSalePrice ,
	RecPrice ,
	UnitID ,
	IsDefaultUnit ,
	TopBuyPrice ,
	referprice ,
	RecSalePrice ,
	RecAppraisalPrice ,
	RecSendPrice
)
SELECT	STypeID ,
		PTypeID ,
		PreBuyPrice1 ,
		PreBuyPrice2 ,
		PreBuyPrice3 ,
		PreBuyPrice4 ,
		PreBuyPrice5 ,
		PreSalePrice1 ,
		PreSalePrice2 ,
		PreSalePrice3 ,
		PreSalePrice4 ,
		PreSalePrice5 ,
		PreSalePrice6 ,
		PreSalePrice7 ,
		PreSalePrice8 ,
		PreSalePrice9 ,
		PreSalePrice10 ,
		RetailPrice ,
		TopSalePrice ,
		LowSalePrice ,
		RecPrice ,
		UnitID ,
		IsDefaultUnit ,
		TopBuyPrice ,
		referprice ,
		RecSalePrice ,
		RecAppraisalPrice ,
		RecSendPrice
FROM	#PType_STypePrice	
ORDER BY nid	

--修改PType_STypePrice中的recPrice
UPDATE	dbo.PType_STypePrice
SET		RecPrice = pt.RecPrice
FROM	dbo.PType_STypePrice ps
INNER JOIN #PType_STypePriceTemp pt ON ps.STypeID = pt.STypeId AND ps.PTypeID = pt.PTypeId AND ps.UnitID = pt.UnitId

--修改XiWaMaxNumber的值
DECLARE @XiWaMaxNumber int
SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
UPDATE PType_Price set XiWaMaxNumber=@XiWaMaxNumber WHERE PTypeID=@PTypeID 

--更新数据
CREATE TABLE #TempUnitsExt
(
	nid		INT IDENTITY(1,1),
	ptypeid	VARCHAR(50),
	sortid	INT
)
INSERT INTO #TempUnitsExt(ptypeid,sortid)SELECT ptypeid,SortId FROM PType_Units_Ext WHERE PtypeID = @PTypeId ORDER BY SortId ASC

UPDATE	PType_Units_Ext
SET		UnitsSortId = t.nid
FROM	PType_Units_Ext pue
INNER JOIN #TempUnitsExt t ON pue.PtypeID= t.ptypeid AND pue.SortId = t.sortid


-- 操作返回值
IF @@ERROR <>0
BEGIN
	RAISERROR('保存失败！',16,1) 
	RETURN -1	-- 失败		
END
ELSE
	RETURN 0	-- 成功

DROP TABLE #TempUnitsExt,#PType_STypePrice,#PType_Price,#PType_STypePriceTemp

--ROLLBACK TRAN BBB
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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















/****** Object:  Stored Procedure dbo.Gp_InsertUpperLowLimit    Script Date: 2002-6-20 10:14:49 ******/

CREATE   PROCEDURE Gp_InsertUpperLowLimit 
(
 @PtypeId [varchar](50),
 @KtypeId [varchar](50),
 @UpperLimit  NUMERIC(24, 10) ,
 @LowLimit  NUMERIC(24, 10) 
)
--@encode$--
AS
SET NOCOUNT ON
if @ktypeid=''
select * from upperlowlimit a where a.ptypeid=@ptypeid
else
select * from upperlowlimit a where a.ptypeid=@ptypeid and a.ktypeid=@ktypeid
if @@rowcount=0 
 insert into upperlowlimit
  (ptypeid,ktypeid,upperlimit,lowlimit)  values (@ptypeid,@ktypeid,@upperlimit,@lowlimit)
else
 update upperlowlimit 
  set upperlimit=dbo.F_RoundQty(@upperlimit),
      lowlimit=dbo.F_RoundQty(@lowlimit) 
  where ptypeid=@ptypeid and ktypeid=@ktypeid
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：陈守川
	日期：2012-02-07
	描述：保存用户组
*/
CREATE PROCEDURE [dbo].[GP_InsertUserGroup]
(
    @etypeid	VARCHAR(2000),
	@UGName		VARCHAR(50),   -- 用户组名称
    @comment	VARCHAR(256)   -- 说明
)    
--@encode$--
AS
	-- 写入数据
SET NOCOUNT ON;

IF EXISTS(SELECT UGName FROM UserGroup WHERE UGName=@UGName)
	BEGIN
		RAISERROR('角色名称已存在,请重新输入!',16,1)return
	END

DECLARE @UGId NUMERIC(18,0)

SET @UGId = 0

BEGIN
	INSERT INTO UserGroup
	(	
		UGName,
		comment,
		lim,
		etypeid
	)
	VALUES
	(
		@UGName,
		@comment,
		' ',
		@etypeid
	)
END

SET @UGId = SCOPE_IDENTITY();

  DECLARE @i INT 
  
  SET @i=0
  WHILE @i<16
  
  BEGIN
    exec GP_UserRange_Insert @UGId,@i,'00000',1
    SET @i=@i+1
  END
  
   exec GP_BankRange_Insert @UGId,16,'00000',1

IF @@ROWCOUNT =0 ROLLBACK TRAN
  

  
  
RETURN @UGId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_InsertVipAddMoneyBatchBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_InsertVipAddMoneyBatchBillDT;
		
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2014-11-18 
	描述：保存会员储值充单明细
*/
CREATE PROCEDURE GP_InsertVipAddMoneyBatchBillDT
	@tb TbType_VipAddMoneyBatch READONLY
--@encode$--
AS
BEGIN
	INSERT INTO VipAddMoneyBatchBill(
		BillNumberId,
		VipCardId,
		BeforeChargeMoney,
		AfterChargeMoney,
		ChargeMoney,
		PreferenceMoney,
		TotalInMoney,
		EndDate,
		Comment,
		ShowOrder
	) SELECT 
		BillNumberId,
		VipCardId,
		dbo.F_RoundTotal(BeforeChargeMoney),
		dbo.F_RoundTotal(AfterChargeMoney),
		dbo.F_RoundTotal(ChargeMoney),
		dbo.F_RoundTotal(PreferenceMoney),
		dbo.F_RoundTotal(TotalInMoney),
		EndDate,
		Comment,
		ShowOrder
		FROM @tb;
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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









/*
	描述:写入VIP卡的消费数据
	作者:谢吉康
	日期:2004-06-15
*/
CREATE  PROCEDURE Gp_InsertVipCardConsume(
	@intBillNumberId	int,			--单据编号
	@chvVipCardNo		varchar(200),	--Vip卡卡号
	@BTypeId			varchar(50)		--Vip卡关联的往来单位的Id
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@chvBTypeId		varchar(50),	--往来单据的Id
		@dtmBillDate	datetime		--单据日期

SELECT 	TOP 1	
		@chvBTypeId = BTypeID,
		@dtmBillDate = BillDate 
FROM 	BillIndex 
WHERE 	BillNumberID = @intBillNumberId 
		AND RedWord = 0

IF @@ROWCOUNT = 0
BEGIN
	--RAISERROR('无效的单据!',16,1)
	RETURN -1
END

IF LTRIM(RTRIM(@BTypeId))<>LTRIM(RTRIM(@chvBTypeId))
BEGIN
	--RAISERROR('VIP卡对应的往来单位和单据对应的往来单位不一致,请确定后重试!',16,1)
	RETURN -2	
END

IF EXISTS (SELECT * FROM VipCardConsume WHERE BillNumberID = @intBillNumberId )
BEGIN
	UPDATE VipCardConsume SET VipCardNo = @chvVipCardNo 
		WHERE BillNumberId = @intBillNumberId
END
ELSE
BEGIN
	INSERT INTO VipCardConsume(
		VipCardNo,
		PreConsumeDate,
		BillNumberId
	)
	VALUES(
		@chvVipCardNo,
		@dtmBillDate,
		@intBillNumberId
	)
END


IF @@ROWCOUNT = 0
BEGIN
	--RAISERROR('录入数据失败,请确认后重试!',16,1)
	RETURN -3
END

--RAISERROR('录入数据成功!',16,1)
RETURN 0












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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









/*
	描述：VipCardSet（类型）的设置
	作者：谢吉康
	日期：2004-06-08
*/
CREATE  PROCEDURE GP_InsertVipCardSet(
	@Action			varchar(20),
	@VipCardName 	varchar(200),
	@VipCardKL 		 NUMERIC(24, 10) ,
	@VipCardAutoZK 	bit,
	@VipCardKz		bit,
	@ConsumeMoney 	 NUMERIC(24, 10) ,
	@ConsumeTimes 	int,
	@TimeLimit		int,
	@StartDate 		datetime,
	@EndDate 		datetime,
	@Note 			varchar(255),
	@VipCardId		int
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--===========================================================================================新增Vip卡类型
IF @Action = 'Add'
BEGIN
	IF EXISTS(SELECT TOP 1 * FROM VipCardSet WHERE VipCardName = @VipCardName)
		BEGIN
			--RAISERROR('该类型的VIP卡名称已经存在！',16,1)
			RETURN -1
		END
	ELSE
		BEGIN
			INSERT INTO VipCardSet
			(
				VipCardName,
				VipCardKL,
				VipCardAutoZK,
				VipCardKz,
				ConsumeMoney,
				ConsumeTimes,
				TimeLimit,
				StartDate,
				EndDate,
				Note
			)
			VALUES
			(			
				@VipCardName,
				@VipCardKL,
				@VipCardAutoZK,
				@VipCardKz,
				dbo.F_RoundTotal(@ConsumeMoney),
				@ConsumeTimes,
				@TimeLimit,
				@StartDate,
				@EndDate,
				@Note
			)	
	
			IF @@ROWCOUNT = 0
				BEGIN
					--RAISERROR('录入数据失败，请确认后重试！',16,1)
					RETURN -2
				END
			ELSE
				BEGIN
					--RAISERROR('录入数据成功！',16,1)
					RETURN 0
				END
		END
END
--===========================================================================================修改Vip卡类型
IF @Action = 'Modify'
BEGIN
	IF EXISTS(SELECT TOP 1 * FROM VipCardSet WHERE VipCardName = @VipCardName AND VipCardId <> @VipCardId)
		BEGIN
			--RAISERROR('该类型的VIP卡名称已经存在！',16,1)
			RETURN -1
		END
	ELSE
		BEGIN
			UPDATE	VipCardSet
			SET		VipCardName 	= @VipCardName,
					VipCardKL		= @VipCardKL,
					VipCardAutoZK	= @VipCardAutoZK,
					VipCardKz		= @VipCardKz,
					ConsumeMoney	= dbo.F_RoundTotal(@ConsumeMoney),
					ConsumeTimes	= @ConsumeTimes,
					TimeLimit		= @TimeLimit,
					StartDate		= @StartDate,
					EndDate			= @EndDate,
					Note			= @Note
			WHERE	VipCardId = @VipCardId

	
			IF @@ROWCOUNT = 0
				BEGIN
					--RAISERROR('更新数据失败，请确认后重试！',16,1)
					RETURN -2
				END
			ELSE
				BEGIN
					--RAISERROR('更新数据成功！',16,1)
					RETURN 0
				END
		END
END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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










/*
	描述:处理Vip卡发卡的信息
	作者:谢吉康
	日期:2004-06-10
*/
CREATE   PROCEDURE GP_InsertVipCardSign(
	@Action				varchar(20),	--动作	Add-新增   Modify-修改
	@chvVipCardNo		varchar(100),	--Vip卡卡号
	@intVipCardId		int,			--Vip卡类型
	@dtmSignDate		datetime,		--签发日期
	@dtmEndDate			datetime,		--截止日期
	@chvVipCardOwner	varchar(100),	--Vip卡的持有者
	@intCertificateNo	varchar(100),	--证件号码
	@LinkerPhoneNo		varchar(50),	--电话号码
	@LinkerAddr			varchar(256),	--持卡人住址
	@BTypeId			varchar(500),	--往来单位的ID
	@VipCardState		int,			--Vip卡的状态	0.启用  1.停用   2.挂失
	@Note				varchar(256),	--备注
	@VipCardSignId		int				--签发Vip卡的ID
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE	@intVipCardKl int,			--卡的扣率
		@intAutoZk	  int,			--是否自动折扣	0.否  1.是
		@intBTypeID	  varchar(50)	--往来单位的ID

SELECT @intVipCardKl = VipCardKl,@intAutoZk = VipCardAutoZk FROM VipCardSet WHERE VipCardId = @intVipCardId

SELECT TOP 1 @intBTypeID = TypeID FROM BType WHERE FullName = @BTypeID AND Deleted = 0 AND SonNum = 0

IF @@ROWCOUNT = 0
BEGIN
	--RAISERROR('往来单位无效,请确定后重试!',16,1)
	RETURN -3
END

--=======================================================新增发卡
IF @Action = 'Add'
BEGIN
	IF EXISTS(SELECT TOP 1 * FROM VipCardSign WHERE VipCardNo = @chvVipCardNo)
	BEGIN
		--RAISERROR('该卡号的Vip卡已存在,请确定后重试!',16,1)
		RETURN -1
	END	

	INSERT INTO VipCardSign
	(
		VipCardNo,
		VipCardId,
		SignDate,
		EndDate,
		VipCardOwner,
		CertificateNo,
		LinkerPhoneNo,
		LinkerAddr,
		BTypeID,
		VipCardState,
		VipCardZK,
		AutoZk,
		Note
	)
	VALUES
	(
		@chvVipCardNo,
		@intVipCardId,
		@dtmSignDate,
		@dtmEndDate,
		@chvVipCardOwner,
		@intCertificateNo,
		@LinkerPhoneNo,
		@LinkerAddr,
		@intBTypeID,
		@VipCardState,
		@intVipCardKl,
		@intAutoZk,
		@Note
	)

	IF @@ROWCOUNT=0
	BEGIN
		--RAISERROR('录入数据失败,请确定后重试!',16,1)
		RETURN -2
	END
	ELSE
	BEGIN
		--RAISERROR('录入数据成功!',16,1)
		RETURN 0
	END
END

--=======================================================修改发卡
IF @Action = 'Modify'
BEGIN
	IF EXISTS(SELECT * FROM VipCardSign WHERE VipCardNo = @chvVipCardNo AND VipCardSignId <> @VipCardSignId)
	BEGIN
		--RAISERROR('该卡号的Vip卡已存在,请确定后重试!',16,1)
		RETURN -1
	END

	DECLARE @srcBTypeID varchar(50)	--原卡对应的往来单位
	SELECT  @srcBTypeID = BTypeID FROM VipCardSign WHERE VipCardNo = @chvVipCardNo

	IF EXISTS(SELECT * FROM VipCardConsume WHERE VipCardNo = @chvVipCardNo AND BillNumberID <> 0)
	BEGIN
		IF @srcBTypeID <> @intBTypeID
			--RAISERROR('该卡号的Vip卡已有消费记录,请清除消费数据后重试!',16,1)
			RETURN -3
	END
	
	UPDATE	VipCardSign
	SET		VipCardNo		=	@chvVipCardNo,
			VipCardId		=	@intVipCardId,
			SignDate		=	@dtmSignDate,
			EndDate			=	@dtmEndDate,
			VipCardOwner	=	@chvVipCardOwner,
			CertificateNo	=	@intCertificateNo,
			LinkerPhoneNo	=	@LinkerPhoneNo,
			LinkerAddr		=	@LinkerAddr,
			BTypeID			=	@intBTypeID,
			VipCardState	=	@VipCardState,
			VipCardZK		=	@intVipCardKl,
			AutoZk			=	@intAutoZk,
			Note			=	@Note
	WHERE	VipCardSignId 	= @VipCardSignId

	IF @@ROWCOUNT=0
	BEGIN
		--RAISERROR('录入数据失败,请确定后重试!',16,1)
		RETURN -2
	END
	ELSE
	BEGIN
		--RAISERROR('录入数据成功!',16,1)
		RETURN 0
	END		

END












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

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







/*
-- 维修品库存期初、库存期初的分布 cqhua 2009-11-04
*/


CREATE      PROCEDURE GP_InsertVisit
(
 @billdate      Datetime,
 @billcode      varchar(200),
 @etypeid       varchar(50),--操作员ID
 @jbbillnumberid numeric(18,0),
 @btypeid       varchar(50),
 @fullname      varchar(256),
 @linkman      varchar(256),
 @linktel      varchar(256),
 @linkaddr      varchar(256),
 @manyidu      varchar(256),
 @jianyi      varchar(256),
 @inbilldate  datetime,
 @inbillcode  varchar(200)
)
--@encode$--
 AS
SET NOCOUNT ON

if exists(select * from visit where billcode=@Billcode)
	RETURN -1

INSERT INTO Visit(billdate,billcode,etypeid,jbbillnumberid,btypeid,fullname,linkman,linktel,linkaddr,manyidu,jianyi,inbilldate,inbillcode)
VALUES
(
 @billdate,
 @billcode,
 @etypeid,
 @jbbillnumberid,
 @btypeid,
 @fullname,
 @linkman,
 @linktel,
 @linkaddr,
 @manyidu,
 @jianyi,
 @inbilldate,
 @inbillcode  
)
IF @@rowcount =0  OR @@error<>0
	RETURN -2
ELSE
 	RETURN SCOPE_IDENTITY();







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：鲁大林
	日期：2012-04-01
	描述：凭证字管理信息录入
*/
CREATE	PROCEDURE [dbo].[Gp_InsertVoucherData]
(	
	----------------------------AC_VOUCHER_GROUP(凭证字表)------------------------------------
	@fullname			VARCHAR(50),				--凭证字名称
	@ismulvoulimit		BIT	=1,					--限制多借多贷
	
	----------------------------AC_VOUCHER_GROUP_DETAIL(凭证字明细表)-------------------------
	@isdebit			VARCHAR(MAX)=NULL,			--借方必有
	@iscredit			VARCHAR(MAX)=NULL,			--贷方必有
	@isdebitorcredit	VARCHAR(MAX)=NULL,			--借或贷必有
	@isnodebit			VARCHAR(MAX)=NULL,			--借方必无
	@isnocredit			VARCHAR(MAX)=NULL,			--贷方必无
	@isnodebitandcredit	VARCHAR(MAX)=NULL			--借或贷必无
)
--@encode$--
AS
-------------------------------------判断是否存在当前要插入的凭证字---------------------------
IF EXISTS(SELECT * FROM dbo.Ac_Voucher_Group WHERE FullName=@fullname)
BEGIN
	RETURN -1
END	
DECLARE @isDefault INT						--保存插入默认凭证字的值
IF EXISTS(SELECT * FROM dbo.Ac_Voucher_Group)
	SET @isDefault=0
ELSE
	SET @isDefault=1
BEGIN
	INSERT INTO dbo.Ac_Voucher_Group
	( 
		FullName ,
		IsMulVourchLimit ,
		PyCode,
		IsDefault
	)
	VALUES  
	(
		@fullname,
		CASE @ismulvoulimit WHEN 'TRUE' THEN 1 ELSE 0 END,
		NULL,
		@isDefault
	)
	--DECLARE @vgid INT
	--SET @vgid=SCOPE_IDENTITY();																	--获取凭插入证字所在行id
	
	--DECLARE  @Tem_Table_isDebit				TABLE(Debit_id VARCHAR(MAX))							--用于接收借方必有id
	--DECLARE  @Tem_Table_isCrebit			TABLE(Crebit_id VARCHAR(MAX))							--用于接收贷方必有id
	--DECLARE  @Tem_Table_isDebitorCrebit		TABLE(DebitorCrebit_id VARCHAR(MAX))					--用于接收借或贷必有id	
	--DECLARE  @Tem_Table_isNoDebit			TABLE(NoDebit_id VARCHAR(MAX))							--用于接收借方必无id
	--DECLARE  @Tem_Table_isNOCrebit			TABLE(NoCrebit_id VARCHAR(MAX))						--用于接收贷方必无id
	--DECLARE  @Tem_Table_isNoDebitAndCrebit	TABLE(NoDebitAndCrebit_id VARCHAR(MAX))				--用于接收借或贷必无id
	
	--INSERT INTO @Tem_Table_isDebit				SELECT * FROM	dbo.f_split(@isdebit,',')			
	--INSERT INTO @Tem_Table_isCrebit				SELECT * FROM	dbo.f_split(@iscredit,',')	
	--INSERT INTO @Tem_Table_isDebitorCrebit		SELECT * FROM	dbo.f_split(@isdebitorcredit,',')	
	--INSERT INTO @Tem_Table_isNoDebit			SELECT * FROM	dbo.f_split(@isnodebit,',')	
	--INSERT INTO @Tem_Table_isNOCrebit			SELECT * FROM	dbo.f_split(@isnocredit,',')	
	--INSERT INTO @Tem_Table_isNoDebitAndCrebit	SELECT * FROM	dbo.f_split(@isnodebitandcredit,',')	
						
	--INSERT INTO [Ac_Voucher_Group_Detail]
	--	(
	--		[VgId],
	--		[ATypeId],
	--		[IsDebit],
	--		[IsCredit],
	--		[IsDebitOrCredit],
	--		[IsNoDebit],
	--		[IsNoCredit],
	--		[IsNoDebitAndCredit]
	--	)
	--SELECT @vgid,Debit_id,0,1,0,0,0,0  FROM @Tem_Table_isDebit	
	
	--INSERT INTO [Ac_Voucher_Group_Detail]
	--	(
	--		[VgId],
	--		[ATypeId],
	--		[IsDebit],
	--		[IsCredit],
	--		[IsDebitOrCredit],
	--		[IsNoDebit],
	--		[IsNoCredit],
	--		[IsNoDebitAndCredit]
	--	)
	--SELECT @vgid,Crebit_id,1,0,0,0,0,0  FROM @Tem_Table_isCrebit
	--INSERT INTO [Ac_Voucher_Group_Detail] 
	--	(
	--		[VgId],
	--		[ATypeId],
	--		[IsDebit],
	--		[IsCredit],
	--		[IsDebitOrCredit],
	--		[IsNoDebit],
	--		[IsNoCredit],
	--		[IsNoDebitAndCredit]
	--	)
	--SELECT @vgid,DebitorCrebit_id,0,0,1,0,0,0  FROM @Tem_Table_isDebitorCrebit
	--INSERT INTO [Ac_Voucher_Group_Detail] 
	--	(
	--		[VgId],
	--		[ATypeId],
	--		[IsDebit],
	--		[IsCredit],
	--		[IsDebitOrCredit],
	--		[IsNoDebit],
	--		[IsNoCredit],
	--		[IsNoDebitAndCredit]
	--	)
	--SELECT @vgid,NoDebit_id,0,0,0,1,0,0  FROM @Tem_Table_isNoDebit
	--INSERT INTO [Ac_Voucher_Group_Detail] 
	--	(
	--		[VgId],
	--		[ATypeId],
	--		[IsDebit],
	--		[IsCredit],
	--		[IsDebitOrCredit],
	--		[IsNoDebit],
	--		[IsNoCredit],
	--		[IsNoDebitAndCredit]
	--	)
	--SELECT @vgid,NoCrebit_id,0,0,0,0,1,0  FROM @Tem_Table_isNOCrebit
	--INSERT INTO [Ac_Voucher_Group_Detail] 
	--	(
	--		[VgId],
	--		[ATypeId],
	--		[IsDebit],
	--		[IsCredit],
	--		[IsDebitOrCredit],
	--		[IsNoDebit],
	--		[IsNoCredit],
	--		[IsNoDebitAndCredit]
	--	)
	--SELECT @vgid,NoDebitAndCrebit_id,0,0,0,0,0,1  FROM @Tem_Table_isNoDebitAndCrebit
END

SET QUOTED_IDENTIFIER ON 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*

*/
CREATE       PROCEDURE Gp_InsertWashCarBill
(
	@BillNumberID			[numeric](10,0),
	@CheckE					varchar(50),
	@ETypeID				varchar(50)
)
--@encode$--
AS 
SET NOCOUNT ON

/*
IF NOT EXISTS(
	SELECT TOP 1 1 FROM F_GetManDetailEType(@CheckE) WHERE TypeID<>'00001' AND TypeID=@ETypeID
)
BEGIN
	RETURN -2
END


if not exists(select billnumberid from QP_WashCarBill where billnumberid=@BillNumberID)
begin
	if exists(select comment from billindex where billnumberid=@BillNumberID and isnull(comment,'')='')
	begin
		DECLARE
			@intAuto	INT
		
		SELECT @intAuto=CAST(Value AS INT) 
		FROM UserConfig
		WHERE ConfigName='AutoCreateResume'

		

		if @intAuto=1
		begin
			declare
				@rafullname 	varchar(100),
				@efullname		varchar(200)
	
			select @rafullname=PlateNumber from billindex_carrepair a
			inner join QP_RepairAutoInfo b
			on a.ratypeid=b.typeid and a.billnumberid=@BillNumberID

			select @efullname=fullname from employee where typeid=@ETypeID
	
			if isnull(@rafullname,'')<>''
			begin
				update billindex
				set comment=ISNULL('【'+@efullname+'】等为【'+@rafullname+'】洗车。','')
				where billnumberid=@BillNumberID
			end
			else
			begin
				update billindex
				set comment=ISNULL('【'+@efullname+'】等洗车。','')
				where billnumberid=@BillNumberID

			end
		end
	end
end*/

INSERT INTO QP_WashCarBill
(
	[BillNumberID],
	[ETypeID]
)
VALUES
(
	@BillNumberID,
	@ETypeID
)

if @@rowcount=0 return -1 else return 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO








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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
作者：ludalin
时间：2012-10-24
描述:往来预警设置
*/
CREATE PROCEDURE GP_IntercourseSettingControl
( 
	@dealbtypeid    VARCHAR(max)=NULL,		--往来单位id,新增：id字符串  修改：id
	@stypeid		VARCHAR(100)=NULL,		--分支机构id
	@limitday		INT=NULL,				--时间间隔
	@controltype	VARCHAR(10),			--操作类型：Add,Delete,Edit,Query
	@id				int =null				--对应记录的id
)

--@encode$--
AS
SET NOCOUNT ON 
IF	@controltype='Add'--新增
BEGIN
	CREATE TABLE #Tem_btype(btypeid VARCHAR(max))
	INSERT INTO #Tem_btype( btypeid ) SELECT a FROM dbo.f_split(@dealbtypeid,',')
	-------判断是否存在重复情况-----------------
	IF EXISTS(SELECT 1 FROM dbo.IntercourseSetting WHERE BtypeId IN (SELECT * FROM #Tem_btype) AND StypeId=@stypeid)
	BEGIN
		--RAISERROR('存在重复的设置，请检查后重试',16,1) 
		DROP TABLE #Tem_btype
		RETURN 1
	END
	CREATE TABLE #Tem_B(stypeid VARCHAR(max),limitday INT)
	INSERT INTO #Tem_B( stypeid, limitday ) VALUES  ( @stypeid,@limitday)
	INSERT INTO [INTERCOURSESETTING] SELECT * FROM #Tem_btype a LEFT JOIN #Tem_B b ON 1=1
	DROP TABLE #Tem_btype
	DROP TABLE #Tem_B
	RETURN 2
END
ELSE IF @controltype='Delete'--删除
BEGIN
	DELETE FROM dbo.IntercourseSetting WHERE ID=@id
	RETURN 2
END
ELSE IF @controltype='Edit'--修改
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.IntercourseSetting WHERE BtypeId =@dealbtypeid AND StypeId=@stypeid AND ID<>@id)
	BEGIN
		RETURN 1
	END
	ELSE
	BEGIN
		CREATE TABLE #Tem_btype_e(btypeid VARCHAR(max))
		INSERT INTO #Tem_btype_e( btypeid ) SELECT a FROM dbo.f_split(@dealbtypeid,',')
		-------判断是否存在重复情况-----------------
		IF EXISTS(SELECT 1 FROM dbo.IntercourseSetting WHERE BtypeId IN (SELECT * FROM #Tem_btype_e) AND StypeId=@stypeid AND ID<>@id)
		BEGIN
			--RAISERROR('存在重复的设置，请检查后重试',16,1) 
			DROP TABLE #Tem_btype_e
			RETURN 1
		END
		DELETE FROM dbo.IntercourseSetting WHERE ID=@id
		CREATE TABLE #Tem_B_e(stypeid VARCHAR(max),limitday INT)
		INSERT INTO #Tem_B_e( stypeid, limitday ) VALUES  ( @stypeid,@limitday)
		INSERT INTO [INTERCOURSESETTING] SELECT * FROM #Tem_btype_e a LEFT JOIN #Tem_B_e b ON 1=1
		DROP TABLE #Tem_btype_e
		DROP TABLE #Tem_B_e
		RETURN 2
	END
END
ELSE		--查询
BEGIN
	PRINT('')
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_InventorySync]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_InventorySync];
GO

/*
	作者:颜熙
	日期:2016-12-14
	描述:库存同步
*/
CREATE  PROCEDURE Gp_InventorySync 
( 
	@stypeid VARCHAR(MAX) --商品id
)
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
		   SELECT   * INTO #NOInventory
		   FROM     dbo.InOutstocktable
		   WHERE    PtypeId + '\' + KtypeId + '\'
					+ CAST(CargoID AS VARCHAR(50)) NOT IN (SELECT  ISNULL(
					PtypeId + '\' + KtypeId + '\'
					+ CAST(CargoID AS VARCHAR(50)),'' ) FROM dbo.GOODSSTOCKS_QTY)
            SELECT  CAST(p.Pid AS VARCHAR) AS sku_erpid ,
                    s.Kid AS whs_erpid ,
                    p.Pid AS goods_erpid ,
                    g.CargoID AS position_erpid ,
                    0 AS validqty
            FROM    ptype AS p
                    INNER JOIN #NOInventory AS g ON p.typeId = g.PtypeId
                    INNER JOIN Stock AS s ON g.KtypeId = s.typeId
                    INNER JOIN f_split(@stypeid, ',') AS f ON p.typeId = f.a
            WHERE   s.WdSyncFlag = 1
                    AND p.WdSyncFlag = 1
                    AND (p.customitemfrom IS NULL OR p.customitemfrom = '')
            GROUP BY s.FullName ,
                    g.CargoID ,
                    p.Pid ,
                    s.Kid ,
                    p.baseUnitId
            UNION ALL
            SELECT  CAST(P.Pid AS VARCHAR) + '_1_' + CAST(C.id AS VARCHAR)
                    + '_' + CAST(P.baseUnitId AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    P.Pid AS goods_erpid ,
                    G.CargoID AS position_erpid ,
                    0 AS validqty
            FROM    #NOInventory G
                    INNER JOIN ptype P ON P.typeId = G.PtypeId
                    INNER JOIN Stock S ON G.KtypeId = S.typeId
                    INNER JOIN CustomReferenceValue AS C ON G.ItemID = C.id
                    INNER JOIN f_split(@stypeid, ',') AS f ON p.typeId = f.a
            WHERE   P.customitemfrom = 1
                    AND P.WdSyncFlag = 1
                    AND S.WdSyncFlag = 1
            GROUP BY S.Kid ,
                    P.Pid ,
                    G.CargoID ,
                    C.id ,
                    P.baseUnitId ,
                    C.Fullname ,
                    P.FullName
            UNION ALL
            SELECT  CAST(P.Pid AS VARCHAR) + '_0_' + CAST(_Id AS VARCHAR)
                    + '_' + CAST(P.baseUnitId AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    P.Pid AS goods_erpid ,
                    G.CargoID AS position_erpid ,
                    0 AS validqty
            FROM    #NOInventory G
                    INNER JOIN ptype P ON G.PtypeId = P.typeId
                    INNER JOIN Stock S ON S.typeId = G.KtypeId
                    INNER JOIN xw_SelfData X ON G.ItemID = X._Id
                    INNER JOIN f_split(@stypeid, ',') AS f ON p.typeId = f.a
            WHERE   P.customitemfrom = 0
                    AND P.WdSyncFlag = 1
                    AND S.WdSyncFlag = 1
            GROUP BY S.Kid ,
                    P.Pid ,
                    G.CargoID ,
                    X._Id ,
                    P.baseUnitId ,
                    X.FullName ,
                    P.FullName
            UNION ALL
            SELECT  CAST(p.Pid AS VARCHAR) AS sku_erpid ,
                    s.Kid AS whs_erpid ,
                    p.Pid AS goods_erpid ,
                    g.CargoID AS position_erpid ,
                    SUM(g.Qty) AS validqty
            FROM    ptype AS p
                    INNER JOIN GOODSSTOCKS_QTY AS g ON p.typeId = g.PTypeID
                    INNER JOIN Stock AS s ON g.KTypeID = s.typeId
                    INNER JOIN f_split(@stypeid, ',') AS f ON p.typeId = f.a
            WHERE   s.WdSyncFlag = 1
                    AND p.WdSyncFlag = 1
                    AND (p.customitemfrom IS NULL OR p.customitemfrom = '')
            GROUP BY s.FullName ,
                    g.CargoID ,
                    p.Pid ,
                    s.Kid ,
                    p.baseUnitId
            UNION ALL
            SELECT  CAST(P.Pid AS VARCHAR) + '_1_' + CAST(C.id AS VARCHAR)
                    + '_' + CAST(P.baseUnitId AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    P.Pid AS goods_erpid ,
                    G.CargoID AS position_erpid ,
                    SUM(G.Qty) AS validqty
            FROM    GOODSSTOCKS_QTY G
                    INNER JOIN ptype P ON P.typeId = G.PTypeID
                    INNER JOIN Stock S ON G.KTypeID = S.typeId
                    INNER JOIN CustomReferenceValue AS C ON G.ItemID = C.id
                    INNER JOIN f_split(@stypeid, ',') F ON F.a = P.typeId
            WHERE   P.customitemfrom = 1
                    AND P.WdSyncFlag = 1
                    AND S.WdSyncFlag = 1
            GROUP BY S.Kid ,
                    P.Pid ,
                    G.CargoID ,
                    C.id ,
                    P.baseUnitId ,
                    C.Fullname ,
                    P.FullName
            UNION ALL
            SELECT  CAST(P.Pid AS VARCHAR) + '_0_' + CAST(_Id AS VARCHAR)
                    + '_' + CAST(P.baseUnitId AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    P.Pid AS goods_erpid ,
                    G.CargoID AS position_erpid ,
                    SUM(G.Qty) AS validqty
            FROM    GOODSSTOCKS_QTY G
                    INNER JOIN ptype P ON G.PTypeID = P.typeId
                    INNER JOIN Stock S ON S.typeId = G.KTypeID
                    INNER JOIN xw_SelfData X ON G.ItemID = X._Id
                    INNER JOIN f_split(@stypeid, ',') F ON F.a = P.typeId
            WHERE   P.customitemfrom = 0
                    AND P.WdSyncFlag = 1
                    AND S.WdSyncFlag = 1
            GROUP BY S.Kid ,
                    P.Pid ,
                    G.CargoID ,
                    X._Id ,
                    P.baseUnitId ,
                    X.FullName ,
                    P.FullName;
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_InvoiceQueryOldBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_InvoiceQueryOldBill]
GO
GO
/****** Object:  StoredProcedure [dbo].[Gp_InvoiceQueryOldBill]    Script Date: 04/17/2012 09:15:39 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
	作者：徐辉
	日期：2009-01-06 V4.1
	描述：销售，采购发票调单开票
	
	调整：周华
	日期: 2012-04-17 09:17:19.673
	描述: 调整选出单据的未开票金额（sum(taxtotal)改成sum(total)）
		此调整是从9.0上搬移过来的，如果修改，考虑修改9.0上的
*/
CREATE  PROCEDURE [dbo].[Gp_InvoiceQueryOldBill]
( 
	 @chvBeginDate	VARCHAR(25),
	 @chvEndDate	VARCHAR(25),
	 @chvBtype		VARCHAR(250),
	 @chvEtype		VARCHAR(250),
	 @chvKtype		VARCHAR(250),
	 @chvstype		VARCHAR(250),
	 @chvptypeid	VARCHAR(250),	
	 @chvBillCode	VARCHAR(250),
	 @chvBillType	VARCHAR(100),	--查询的单据类型
	 @chvType       VARCHAR(5),		--销售发票调单，162；采购发票调单，163
	 @state			INT,			--开票状态
	 @chvOperatorId VARCHAR(50),    --操作员ID
	 @BtypeID		VARCHAR(250),	--结算单位
	 @comment		VARCHAR(256),
	 @explain		VARCHAR(256),
	  @cid		    VARCHAR(256)    --币种
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 往来单位
IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
BEGIN
	DECLARE @chvBTypeAll char(1)
	SET @chvBTypeAll = '0'
	SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'
	
	SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)
	DECLARE @SQL_ManB varchar(100)
	SET @SQL_ManB = ' INNER JOIN #F_BaseGetManDetailBType B ON a.btypeid = B.TypeID '
	
	IF @chvBTypeAll = '0'
	BEGIN
		IF @chvBillType = '162' AND @chvMBTypeID = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00001%'' '
	
		IF @chvBillType = '163' AND @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00002%'' '
	END
	ELSE
	BEGIN
		IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB
	END
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END

CREATE TABLE #Stype	(TypeID varchar(50))
--分支机构
INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvstype,11,@chvOperatorID)

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('10000')
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID OR a.KTypeID2 = K.TypeID '
END

--部门
IF  @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END
-- ******** 权限范围单独处理 - End ********
DECLARE @fapiaoTableName VARCHAR(100)
SET @fapiaoTableName = 'FaPiaoBill'
IF @chvType='404' OR @chvType='405'
BEGIN
	SET @fapiaoTableName='ReceiptBill'
END
--明细商品穿透查询
IF @chvptypeid<>''
BEGIN
	CREATE TABLE #billnumberid(billnumberid INT)
	IF @chvType = '162' --销售发票
		INSERT #billnumberid SELECT a.billnumberid FROM
			(
			SELECT DISTINCT billnumberid FROM dbo.SaleBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.saleBackBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.retailBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.SaleGoodsExchangeBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.CommissionBill WHERE PtypeId = @chvptypeid
			UNION 
			SELECT DISTINCT billnumberid FROM dbo.RetailBackBill WHERE PtypeId = @chvptypeid
			UNION 
			SELECT DISTINCT billnumberid FROM dbo.PT_Combin_SaleBackBill WHERE PtypeId = @chvptypeid
			UNION 
			SELECT DISTINCT billnumberid FROM dbo.PT_Combin_SaleBill WHERE PtypeId = @chvptypeid
			) a
	IF @chvType = '163' --采购发票
		INSERT #billnumberid SELECT a.billnumberid FROM
			(
			SELECT DISTINCT billnumberid FROM dbo.BuyBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.BuyBackBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.BuyGoodsExchangeBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.CommissionBill WHERE PtypeId = @chvptypeid
			) a
	IF @chvType = '404'--采购暂估开票
	BEGIN
		INSERT #billnumberid SELECT a.billnumberid FROM
			(
			SELECT DISTINCT billnumberid FROM dbo.AppraisalBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.AppraisalBackBill WHERE PtypeId = @chvptypeid
			) a
	END
	IF @chvType = '405'--销售暂估开票
	BEGIN
		INSERT #billnumberid SELECT a.billnumberid FROM
			(
			SELECT DISTINCT billnumberid FROM dbo.SendBill WHERE PtypeId = @chvptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.SendBackBill WHERE PtypeId = @chvptypeid
			) a
	END
END
DECLARE @SQL varchar(2000)
SET @SQL ='
	SELECT	DISTINCT 
			a.BillNumberID,
			a.BillDate,
			a.BillCode,
			a.BillType,
			CASE WHEN a.isini = 1 THEN ''期初单据''
				 WHEN ifYearBill = 0 THEN ''正常单据''				 
				 ELSE ''年结前单据''
			END AS ifYearBill,
			a.ETypeID,
			CASE WHEN a.BillType=401 OR a.BillType=403 OR a.BillType=46 THEN -a.NTotalMoney ELSE a.NTotalMoney END AS TotalMoney,
			CASE WHEN a.BillType=401 OR a.BillType=403 OR a.BillType=46 THEN -a.TotalMoney ELSE a.TotalMoney END AS TotalMoney1,
			ISNULL(detail.Total,0) AS Total,
			0.0 AS NoInvoiceTotal,
			a.comment,
			a.explain
	FROM	BillIndex a ' + @SQL_Man + ' 
	INNER JOIN #stype s on s.typeid=a.stypeid
	LEFT JOIN (
				SELECT	MainBillNumberID,
						SUM(Total) AS Total
				FROM	'+@fapiaoTableName+' 
				GROUP BY MainBillNumberID
	) detail ON a.BillNumberID = detail.MainBillNumberID
	WHERE	a.BillDate >= ''' + @chvBeginDate + ''' AND a.BillDate <= ''' + @chvEndDate + '''
	        AND a.CID=''' + @cid + ''' 
			AND a.BillType IN (' + @chvBillType + ')
			AND ((a.Draft = 0 
			AND a.RedWord = 0 
			AND a.IfCheck = ''t'') OR a.isini=1) '

--0=未全部开票,1=已全部开票,2=全部 
IF @state = 0  SET @SQL = @SQL + ' AND a.IfInvoice IN(0,1)'
IF @state = 1  SET @SQL = @SQL + ' AND ( a.IfInvoice IN(2))'
--IF @state = 2  SET @SQL = @SQL + ' AND ( a.IfInvoice !=2)'

IF @chvBillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @chvBillCode + '%'''
--9.4需求去掉：发票调单应该只按结算单位选取
--IF @chvBType <> '' SET @SQL = @SQL + ' AND a.dealbtypeid=''' + @chvBType + ''''
IF @chvEType <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @chvEType + ''''
IF @chvstype <> '' SET @SQL = @SQL + ' AND a.sTypeID=''' + @chvstype + ''''
IF @chvKType <> '' SET @SQL = @SQL + ' AND (a.KTypeID=''' + @chvKType + ''' OR a.KTypeID2=''' + @chvKType + ''')'
IF @chvptypeid <> '' SET @SQL = @SQL + ' AND a.billnumberid IN(SELECT billnumberid FROM #billnumberid)'
IF @BtypeID <> '' SET @SQL = @SQL + ' AND a.btypeid=''' + @BtypeID + ''''
IF @comment <> '' SET @SQL += ' AND a.comment LIKE ''%' + @comment + '%'''
IF @explain <> '' SET @SQL += ' AND a.explain LIKE ''%' + @explain + '%'''

SET @SQL = @SQL + ' ORDER BY a.BillDate DESC,a.BillCode DESC'

--PRINT(@SQL)
EXEC (@SQL)

IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999' DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMDtypeid = '-99999' DROP TABLE #F_BaseGetManDetailDType
IF @chvptypeid <> '' DROP TABLE #billnumberid

DROP TABLE #Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：张陈仁
	日期：2012-06-29
	描述：判断自定义字段是否可删除
*/

CREATE PROCEDURE Gp_IsCostomFieldIsDelete
(
	@Type VARCHAR(20),
	@BaseType VARCHAR(30)='',
	@BillType INT 
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE 
		@table VARCHAR(30)='',
		@where VARCHAR(50)='',
		@SelectSQL VARCHAR(max)='DECLARE @i INT =1,@sql VARCHAR(MAX)='' SELECT '''
		
--SELECT * FROM dbo.CustomBaseInforColumnsDefines
IF @Type='baseinfor'
   SET @table='CustomBaseInforColumnsDefines'
IF @Type='bill'
   SET @table='CustomBillColumnsDefines'
SET @SelectSQL+=' WHILE(@i<=20) '
SET @SelectSQL+=' BEGIN '
	 SET @SelectSQL+=' IF EXISTS(SELECT 1 FROM '+@table+' WHERE BillType='+cast(@BillType AS VARCHAR(20))+' AND CustomerOrder=@i) '
	    SET @SelectSQL+=' SET @sql=@sql+CAST(@i AS VARCHAR(10))+'' as costom''+CAST(@i AS VARCHAR(10))+'','' '
     SET @SelectSQL+=' SET @i=@i+1 '
SET @SelectSQL+=' END '
SET @SelectSQL+=' SET @sql=LEFT(@sql,LEN(@sql)-1) '
SET @SelectSQL+=' EXEC(@sql) '
--PRINT @SelectSQL
EXEC(@SelectSQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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













CREATE  proc gp_isDogCheckedForAsp
(
	@intValidate int
)
--@encode$--

as
 SET NOCOUNT ON
 declare @Flag int
 DECLARE @BIT INT,@MASK INT
 
 SELECT @BIT=@intValidate & 15
 SELECT @MASK=POWER(2,@BIT)^POWER(2,@BIT+1) ^ POWER(2,@BIT+2) ^ POWER(2,@BIT+3) ^ POWER(2,@BIT+4) ^ POWER(2,@BIT+5)
 SELECT @Flag=(@MASK & @intValidate)/POWER(2,@BIT)

 declare @intValue int,@re int
 exec @re = Gp_Validate 2,@intValue out

 if @re<>0 return 1


 if @Flag=@intValue
 	return 0
 else
 	return 1












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_IsExsitCustomAllDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_IsExsitCustomAllDelete]
GO
/*
	作者：张陈仁
	日期：2012-06-26
	描述：检查自定义属性是否该删除
*/
CREATE PROCEDURE GP_IsExsitCustomAllDelete
(
	@Type VARCHAR(20),
	@BillType INT,
	@BaseType VARCHAR(30)
)
--@encode$--
AS

DECLARE @Sql VARCHAR(MAX), @i INT=1
CREATE TABLE #T
(
    orindex INT, 
	r INT
)

WHILE(@i<=20)
BEGIN
	IF @Type='bill'
	BEGIN
		SET @Sql='
					IF EXISTS(SELECT 1 FROM CustomBillColumns WHERE billtype='+CAST(@BillType AS VARCHAR(50))+' AND (Costom'+CAST(@i AS VARCHAR(50))+' IS NOT NULL AND Costom'+CAST(@i AS CHAR(2))+'<>''''))
						INSERT INTO #T (orindex,r) VALUES ('+CAST(@i AS VARCHAR(50))+',1)
					ELSE
						INSERT INTO #T (orindex,r) VALUES ('+CAST(@i AS VARCHAR(50))+',0) 
				'
	    --PRINT @Sql
		EXEC (@Sql)
	END
	IF @Type='base'
	BEGIN
		SET @Sql='
				   IF EXISTS(SELECT 1 FROM '+@BaseType+'_CustomColumns WHERE Costom'+CAST(@i AS VARCHAR(50))+' IS NOT NULL AND costom'+CAST(@i AS VARCHAR(50))+'<>'''')
					   INSERT INTO #T (orindex,r) VALUES ('+CAST(@i AS VARCHAR(50))+',1)
				   ELSE
					   INSERT INTO #T (orindex,r) VALUES ('+CAST(@i AS VARCHAR(50))+',0) 
		         '
		--PRINT @Sql
		EXEC(@Sql)
	END
	SET @i=@i+1
END
SELECT * FROM #T
DROP TABLE #T



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_IsOrderCanEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_IsOrderCanEdit
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-03-30
-- Description: 订单是否可以修改（0: 没有做过任何除了，1：有销售 2 有采购 3 待审核 4 生成销售订单 5 被终止 6 已完成）
-- =============================================
CREATE PROCEDURE Gp_IsOrderCanEdit
(
	@billnumberid	int
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
--判断订单是否存在（防止开两个窗口，其中一个窗口把订单已经删了）
IF NOT Exists(select 1 from orderindex where billnumberid=@billnumberid)
begin
	RAISERROR('没有找到单据！',16,1) 
	RETURN
end
	
create table #order
(
	orderid int
)

CREATE TABLE #CombinOrder
(
	orderid INT
)

DECLARE @billover	varchar(2),
		@orderstate	varchar(2),
		@returnvalue int=0

insert into #order (orderid)
select orderid from OrderBill where billNumberID=@billnumberid 

INSERT INTO #CombinOrder( orderid )
SELECT OrderID FROM dbo.PT_Combin_OrderBillDetail  where billNumberID=@billnumberid
	
select @billover = billover,@orderstate = orderstate from orderindex where billnumberid=@billnumberid --是否已完成或被终止
IF @billover=1 --被终止
	set @returnvalue = 5
ELSE IF @orderstate=1--已完成
	set @returnvalue = 6
ELSE IF Exists(select 1 from orderbill where frombillnumberid=@billnumberid) --采购订单已生产销售订单
	set @returnvalue = 4
ELSE IF Exists(SELECT ab.BillNumberID FROM AuditingBill ab WHERE  ab.BillNumberID=@billnumberid and ab.BillIndexType = 0 AND IfAudit<>'-1') --待审核单据
	set @returnvalue = 3
ELSE IF Exists(select 1 from salebill sa,billindex bi where sa.orderid in (select orderid from #order) and bi.redword=0 and sa.billnumberid=bi.billnumberid ) --已有销售出库单
	set @returnvalue = 1
ELSE IF Exists(SELECT 1 FROM dbo.OrderIndex oi,dbo.OrderBill ob WHERE oi.billNumberId=ob.billNumberID AND billtype=301
AND SaleOrderID in (select orderid from #order) and oi.redword=0) --已有采购订单
	set @returnvalue = 1
ELSE IF Exists(select 1 from dbo.PT_Combin_SaleBillDetail sa,dbo.billindex bi where sa.orderid in (select orderid from #CombinOrder) and bi.redword=0 and sa.billnumberid=bi.billnumberid ) --已有组合品销售出库单
	set @returnvalue = 1
--判断销售单是否已完成
ELSE IF EXISTS(SELECT  TOP 1 1FROM dbo.OrderBill A INNER JOIN OrderIndex B ON B.billNumberId=A.billNumberID AND B.billtype=300 WHERE A.billNumberID=@billnumberid AND A.ReachQty<A.qty AND a.ReachQty<>0 AND B.BillStatus=0)
	set @returnvalue = 1
ELSE IF Exists(select 1 from buybill bu,billindex bi where bu.orderid in (select orderid from #order) and bi.redword=0 and bu.billnumberid=bi.billnumberid ) --已有采购入库单
	set @returnvalue = 2
ELSE IF Exists(select 1 from appraisalbill bu,billindex bi where bu.orderid in (select orderid from #order) and bi.redword=0 and bu.billnumberid=bi.billnumberid ) --已有发票单据
	set @returnvalue = 2
ELSE IF Exists(select 1 from dbo.CommissionBill bu,billindex bi where bu.orderid in (select orderid from #order) and bi.redword=0 and bu.billnumberid=bi.billnumberid ) --已有代销单据
	set @returnvalue = 2
ELSE IF Exists(select 1 from dbo.SendBill bu,billindex bi where bu.orderid in (select orderid from #order) and bi.redword=0 and bu.billnumberid=bi.billnumberid ) --已有发票单据
	set @returnvalue = 2
ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.OrderBill A INNER JOIN OrderIndex B ON B.billNumberId=A.billNumberID AND B.billtype=301 WHERE A.billNumberID=@billnumberid AND A.ReachQty<A.qty AND a.ReachQty<>0 AND B.BillStatus=0)
	set @returnvalue = 2

drop table #order

return @returnvalue

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_IsRequestCanEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_IsRequestCanEdit
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2011-10-14
-- Description: 请购单是否可以修改
-- =============================================
CREATE PROCEDURE Gp_IsRequestCanEdit
(
	@billnumberid	int
)
--@encode$--
AS
SET NOCOUNT ON

--判断请购单是否全部为请购状态（防止开多个窗口，其中一个窗口把状态已经修改了）
IF  Exists(SELECT * FROM RequestBill where billnumberid=@billnumberid AND state<>1)
	RETURN 1

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[Gp_IsUsedCombinationProduct]') AND OBJECTPROPERTY(ID, N'ISPROCEDURE') = 1)
	DROP PROCEDURE [DBO].Gp_IsUsedCombinationProduct
GO
/*
	作者：shu shan
	时间：
	描述：组合品排除了很多表 高价、价格跟踪、物价信息、分支机构物价信息
	
*/
CREATE PROCEDURE Gp_IsUsedCombinationProduct
(
	@strPTypeId varchar(50)
	,@intIfUsed INT OUTPUT 
)
--@encode$--	
AS
BEGIN
	IF LTRIM(RTRIM(@strPTypeId))='' 
	BEGIN
		SET @intIfUsed=0;
		RETURN;
	END

	DECLARE @sql NVARCHAR(MAX)='';
	DECLARE @sql1 NVARCHAR(max)='';
	DECLARE @sql2 NVARCHAR(max)='';
	
	-- 前提，系统中存在这种表，这个是肯定存在的
	;WITH cte AS (
		SELECT a.name,x.fldName,rn=ROW_NUMBER()OVER(ORDER BY GETDATE()) FROM SYS.tables a 
			LEFT JOIN (
				SELECT tblName,fldName,basType FROM Sys_BaseInfoUsing_Tables WHERE basType='PTypeId'
			) x ON a.name=x.tblName
			JOIN sys.columns b ON a.object_id=b.object_id
	WHERE (x.basType IS NULL OR x.basType ='PTypeId') --,'ProduceModel','ProduceModelIndex' 排除表去掉生产模板
		AND b.name=CASE WHEN x.fldName IS NULL THEN 'PTypeId' ELSE x.fldName END 
		AND a.name NOT IN ('Ptype','PType_Price','PType_Units','PType_Units_Ext','QP_PType_Ext','PType_STypePrice','Ptype_CustomColumns','PType_Picture','PType_InventoryType',
		'nVipGoodsSign','EcShopPriceTrack','EcShopCXPrice','EcShopSyncProductStockCounts','EcShopSyncUpLoadProducts',
		'PriceTrack','PType_AuxiliaryUnits_Ext','EcShopSyncUpLoadProductsPrice','BeforePromoteRetailBill','DefaultStock','OM_Inventory_Ext',
		'AskPriceBill','PriceDetail','produceModelIndex','produceModel','PromoRule_Detail_PConfig',
		'PromotePrice','PuserCode','QuotePriceBill','goodsstocks','STOCKALARM',
		'PriceTrack_Appraisal',
		'PriceTrack_AskPrice',
		'PriceTrack_Buy',
		'PriceTrack_BuyOrder',
		'PriceTrack_Quote',
		'PriceTrack_Sale',
		'PriceTrack_SaleOrder',
		'PriceTrack_Send',
		'PriceTrack_SType_Appraisal',
		'PriceTrack_SType_AskPrice',
		'PriceTrack_SType_Buy',
		'PriceTrack_SType_BuyOrder',
		'PriceTrack_SType_Quote',
		'PriceTrack_SType_Sale',
		'PriceTrack_SType_SaleOrder',
		'PriceTrack_SType_Send',
		'PriceTrack_STypeMove',
		'PriceTrack_SType_Appraisal',	
		'PriceTrack_SType_AskPrice',	
		'PriceTrack_SType_Buy',	
		'PriceTrack_SType_BuyOrder',	
		'PriceTrack_SType_Quote',
		'PriceTrack_SType_Sale',	
		'PriceTrack_SType_SaleOrder',	
		'PriceTrack_SType_Send',	
		'PriceTrack_STypeMove',
		'PType_EntryCode_Ext',
		'PType_Units_EntryCode_Ext' ) --排除表
	)
	SELECT @sql=STUFF((SELECT 'or exists(select 1 from '+name+' where '+CASE WHEN fldName IS NULL THEN 'PTypeId' ELSE fldName END +'='+QUOTENAME(@strPTypeId,'''')+')' FROM cte WHERE rn BETWEEN 1 AND 100 FOR XML PATH('')),1,2,'') 
	,@sql1=CAST((SELECT ' or exists(select 1 from '+name+' where '+CASE WHEN fldName IS NULL THEN 'PTypeId' ELSE fldName END +'='+QUOTENAME(@strPTypeId,'''')+')' FROM cte WHERE rn BETWEEN 101 AND 200 FOR XML PATH('')) AS varchar(max)) 
	,@sql2=CAST((SELECT ' or exists(select 1 from '+name+' where '+CASE WHEN fldName IS NULL THEN 'PTypeId' ELSE fldName END +'='+QUOTENAME(@strPTypeId,'''')+')' FROM cte WHERE rn BETWEEN 201 AND 500 FOR XML PATH('')) AS varchar(max))
	,@intIfUsed=0;

	SELECT @sql1=ISNULL(@sql1,''),@sql2=ISNULL(@sql2,'');
	--PRINT @sql
	--PRINT  @sql1
	--PRINT @sql2
	DECLARE @t TABLE(n int);
	INSERT INTO @t EXEC('if '+@sql+@sql1+@sql2+' select 1 else select 0');
	SELECT @intIfUsed=n FROM @t;
	
 
	--处理价格跟踪表
	--IF @intIfUsed = 0
	--BEGIN
	--	IF EXISTS(SELECT TOP 1 1 FROM PriceTrack WHERE PtypeID=@strPTypeId)
	--		SET @intIfUsed = 2
	--END
	
	SELECT @intIfUsed
END
GO





IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[GP_ISUSEDITEM]') AND OBJECTPROPERTY(ID, N'ISPROCEDURE') = 1)
	DROP PROCEDURE [DBO].[GP_ISUSEDITEM]
GO

/*
	作者：周华
	时间：2012-6-1
	描述：提供判断指定自由项是否使用的过程
	查看整个数据库中，存在ItemId,IsCombined的表 是否存在记录
	2012-6-13 添加排除表
*/
CREATE PROCEDURE Gp_IsUsedItem
(
	@intItemId INT --自由项ID
	,@intIsCombined TINYINT --0表示单一自由项，1表示组合自由项
	,@intIfUsed INT OUTPUT --0表示未使用，1表示使用
)
--@encode$--	
AS
BEGIN
	IF @intItemId<=0
	BEGIN
		SET @intIfUsed=0;
		RETURN;
	END
	DECLARE @sql NVARCHAR(max)='';
	DECLARE @sql1 NVARCHAR(max)='';
	-- 前提，系统中存在这种表，这个是肯定存在的
	;WITH cte AS (
		SELECT a.NAME,rn=ROW_NUMBER() OVER(ORDER BY GETDATE()) FROM sys.tables a 
			JOIN sys.columns b ON a.object_id=b.object_id
		WHERE b.name IN ('ItemId','IsCombined') AND a.Name NOT IN ('customPtypeItems','CustomReferenceValue','CustomReference','xw_SelfData','xw_SelfDataType')--排除表
		GROUP BY a.name 
		HAVING COUNT(1)>1
	)
	SELECT @sql=STUFF((SELECT 'or exists(select 1 from '+name+' where ItemId='+CAST(@intItemId AS varchar(10))+' AND IsCombined='+CAST(@intIsCombined AS varchar(10))+') ' FROM cte WHERE rn BETWEEN 1 AND 100 FOR XML PATH('')),1,2,'')
	,@sql1=CAST((SELECT ' or exists(select 1 from '+name+' where ItemId='+CAST(@intItemId AS varchar(10))+' AND IsCombined='+CAST(@intIsCombined AS varchar(10))+') ' FROM cte WHERE rn BETWEEN 101 AND 200 FOR XML PATH('')) AS NVARCHAR(max))
	,@intIfUsed=0;
	
	SELECT @sql1=ISNULL(@sql1,'');
	
	DECLARE @t TABLE(n int);
	INSERT INTO @t EXEC('if '+@sql+@sql1+' select 1 else select 0');
	SELECT @intIfUsed=n FROM @t;
END
GO 




IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[Gp_IsUsedItemInBaseInfo]') AND OBJECTPROPERTY(ID, N'ISPROCEDURE') = 1)
	DROP PROCEDURE [DBO].[Gp_IsUsedItemInBaseInfo]
GO

/*
	作者：李灏龙
	时间：2012年9月26日 11:06:24
	描述：提供判断指定基本项的值是否在基本信息里使用过
*/
CREATE PROCEDURE Gp_IsUsedItemInBaseInfo
(
	@intItemId INT --自由项ID
	,@intIfUsed INT OUTPUT --0表示未使用，1表示使用
)
--@encode$--	
AS
BEGIN
	DECLARE @typeid VARCHAR(500),@datatype VARCHAR(50)
	SET @intIfUsed = 0
	SET @typeid=''
	SET @datatype=''
	SELECT  @typeid=TypeId,@datatype=DataTypeId FROM xw_SelfData WHERE _Id=@intItemId
	--print @typeid
	--print @datatype
	--select * from xw_SelfData
	
	IF @datatype = ''
		RETURN @intIfUsed
		
	DECLARE @CursorSQL NVARCHAR(MAX)
	--SELECT @CursorSQL='IF EXISTS(SELECT * FROM CustomBillDetailColumns WHERE costom'+cast(CustomerOrder as varchar)+' = '''+@ctypeid+''') SET @@intIfUsed=1 '   --如果存在id，返回1
	--	FROM CustomBillDetailColumnsDefines
	--	WHERE CustomerType=@ctypename
	--	EXEC SP_EXECUTESQL @CursorSQL,N'@intIfUsed INT OUTPUT',@intIfUsed=@intIfUsed OUTPUT
		
	--	SELECT * FROM CustomBillDetailColumnsDefines
		
	--定义游标
	SET @CursorSQL = '	DECLARE CustomCursor CURSOR FOR
						SELECT	BaseType+''_CustomColumns'' AS basetype
								,CustomerOrder
						FROM	CustomBaseInforColumnsDefines
						WHERE	CustomerType = ''__SelfDataType'+ @datatype +'''
						UNION
						SELECT	''CustomBillDetailColumns'' AS basetype
								,CustomerOrder
						FROM	CustomBillDetailColumnsDefines
						WHERE	CustomerType = ''__SelfDataType'+ @datatype +'''
						UNION
						SELECT	''CustomBillColumns'' AS basetype
								,CustomerOrder
						FROM	CustomBillColumnsDefines
						WHERE	CustomerType = ''__SelfDataType'+ @datatype +''''	
	
	EXEC(@CursorSQL)
	PRINT @CursorSQL
	DECLARE @BaseType VARCHAR(50),@CustomerOrder VARCHAR(50)
	
	OPEN CustomCursor
	FETCH NEXT FROM CustomCursor INTO @BaseType,@CustomerOrder
	--print @@FETCH_STATUS
	--print @intIfUsed
	WHILE ( @@FETCH_STATUS = 0 AND @intIfUsed = 0 )
	BEGIN
	
		SET @CursorSQL = 'IF EXISTS(SELECT * FROM '+@BaseType+' WHERE Costom' +@CustomerOrder +' = '+ @typeid+') SET @intIfUsed = 1 '
		EXEC SP_EXECUTESQL @CursorSQL,N'@intIfUsed INT OUTPUT',@intIfUsed=@intIfUsed OUTPUT
		--print @CursorSQL
		FETCH NEXT FROM CustomCursor INTO @BaseType,@CustomerOrder
	END
	CLOSE CustomCursor		-- 关闭游标
	DEALLOCATE CustomCursor	-- 释放游标所使用的资源
	
	RETURN @intIfUsed
END
GO 



IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[GP_ISUSEDPRODUCT]') AND OBJECTPROPERTY(ID, N'ISPROCEDURE') = 1)
	DROP PROCEDURE [DBO].GP_ISUSEDPRODUCT
GO
/*
	作者：周华
	时间：2012-6-1
	描述：提供判断指定商品是否使用
	查看整个数据库中，存在PTypeId(有些表当中不是PTypeId的 查Sys_BaseInfoUsing_Tables中查)的表 是否存在记录
	2012-6-13 排除几个基本表
	2013-06-07 周华  添加排除表
	2016-07-22 魏伟 增加排除表 PType_InventoryType
*/
CREATE PROCEDURE Gp_IsUsedProduct
(
	@strPTypeId varchar(50)
	,@intIfUsed INT OUTPUT 
)
--@encode$--	
AS
BEGIN
	IF LTRIM(RTRIM(@strPTypeId))='' 
	BEGIN
		SET @intIfUsed=0;
		RETURN;
	END

	DECLARE @sql NVARCHAR(MAX)='';
	DECLARE @sql1 NVARCHAR(max)='';
	DECLARE @sql2 NVARCHAR(max)='';
	
	-- 前提，系统中存在这种表，这个是肯定存在的
	;WITH cte AS (
		SELECT a.name,ISNULL(x.fldName,'PTypeId') AS fldName,rn=ROW_NUMBER()OVER(ORDER BY GETDATE()) 
		FROM SYS.tables a 
		LEFT JOIN (
				SELECT tblName,fldName,basType FROM Sys_BaseInfoUsing_Tables WHERE basType='PTypeId'
			) x ON a.name=x.tblName
		JOIN sys.columns b ON a.object_id=b.object_id
	WHERE (x.basType IS NULL OR x.basType ='PTypeId') --,'ProduceModel','ProduceModelIndex' 排除表去掉生产模板
		AND b.name=CASE WHEN x.fldName IS NULL THEN 'PTypeId' ELSE x.fldName END 
		AND a.name NOT IN ('Ptype','PType_Price','PType_Units','PType_Units_Ext','QP_PType_Ext','PType_Price','PType_STypePrice','PType_TranslateRates','Ptype_CustomColumns','PType_Picture','PType_InventoryType',
		'nVipGoodsSign','EcShopPriceTrack','EcShopCXPrice','EcShopSyncProductStockCounts','EcShopSyncUpLoadProducts',
		'PriceTrack','PType_AuxiliaryUnits_Ext','EcShopSyncUpLoadProductsPrice','BeforePromoteRetailBill','DefaultStock','OM_Inventory_Ext',
		'AskPriceBill','PriceDetail','produceModelIndex','produceModel','PromoRule_Detail_PConfig',
		'PromotePrice','PuserCode','QuotePriceBill','goodsstocks','STOCKALARM','ModifyLog_BuyBill','ModifyLog_SaleBill','ModifyLog_PreBill','ModifyLog_PayBill','PType_EntryCode_Ext','PType_Units_EntryCode_Ext','GoodsStocks_Draft','ModifyLog_OrderBill','pricetrack_stype_BuyOrder','EcShopSyncUpLoadProducts','Cost_NoRelog') --排除表
	)
	SELECT @sql=' exists('+ STUFF((SELECT ' select top 1 1 from '+name+' where '+ fldName  +'='+QUOTENAME(@strPTypeId,'''')+' union all' FROM cte WHERE rn BETWEEN 1 AND 100 FOR XML PATH('')),1,1,'') + ' select top 0 0 from Ac_Currency ) '
	,@sql1='or exists('+ STUFF((SELECT ' select top 1 1 from '+name+' where '+ fldName  +'='+QUOTENAME(@strPTypeId,'''')+' union all' FROM cte WHERE rn BETWEEN 101 AND 200 FOR XML PATH('')),1,1,'') + ' select top 0 0 from Ac_Currency ) '
	,@sql2='or exists('+ STUFF((SELECT ' select top 1 1 from '+name+' where '+ fldName  +'='+QUOTENAME(@strPTypeId,'''')+' union all' FROM cte WHERE rn BETWEEN 201 AND 500 FOR XML PATH('')),1,1,'') + ' select top 0 0 from Ac_Currency union all select 1 from CombinationProductIndex WHERE CombinationProductPtypeId = '''+@strPTypeId+''') '
	,@intIfUsed=0;
	/*
	SELECT @sql=STUFF((SELECT 'or exists(select top 1 1 from '+name+' where '+ fldName  +'='+QUOTENAME(@strPTypeId,'''')+')' FROM cte WHERE rn BETWEEN 1 AND 100 FOR XML PATH('')),1,2,'') 
	,@sql1=CAST((SELECT ' or exists(select top 1 1 from '+name+' where '+ fldName  +'='+QUOTENAME(@strPTypeId,'''')+')' FROM cte WHERE rn BETWEEN 101 AND 200 FOR XML PATH('')) AS varchar(max)) 
	,@sql2=CAST((SELECT ' or exists(select top 1 1 from '+name+' where '+ fldName  +'='+QUOTENAME(@strPTypeId,'''')+')' FROM cte WHERE rn BETWEEN 201 AND 500 FOR XML PATH('')) AS varchar(max))
	,@intIfUsed=0;
	*/
	SELECT @sql1=ISNULL(@sql1,''),@sql2=ISNULL(@sql2,'');
	print @sql
	PRINT  @sql1
	PRINT @sql2

	DECLARE @t TABLE(n int);
	INSERT INTO @t EXEC('if '+@sql+@sql1+@sql2+' select 1 else select 0');
	SELECT @intIfUsed=n FROM @t;
 
	--处理价格跟踪表
	IF @intIfUsed = 0
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM PriceTrack WHERE PtypeID=@strPTypeId)
			SET @intIfUsed = 2
	END
	
	SELECT @intIfUsed
END
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	出入库汇总表
	彭勇
*/
CREATE PROCEDURE Gp_KinOutStockUserConfig
(
	@chvOperatorId		varchar(200), --当前操作员
	@strBillTypes		varchar(200), --所选的单据类型 
	@showinstock		bit,          --是否显示入库数量  
	@showoutstock		bit,		  --是否显示出库数量	
	@showstock			bit,		  --是否显示库存数量	
	@shownqty			BIT			  ---是否显示浮动数量	
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 * FROM kinoutstockconfig WHERE ETypeId = @chvOperatorId)
	INSERT INTO kinoutstockconfig
	(
		ETypeId,
		BillTypes,
		shownqty,
		showinstock,
		showoutstock,
		showstock
	)VALUES(
		@chvOperatorId,
		@strBillTypes,
		@shownqty,
		@showinstock,
		@showoutstock,
		@showstock
	)
ELSE
	UPDATE	kinoutstockconfig
	SET		BillTypes 	= @strBillTypes,
			shownqty=@shownqty,
		    showinstock=@showinstock,
		    showoutstock=@showoutstock,
		    showstock=@showstock
	WHERE	ETypeId		= @chvOperatorId


IF @@ROWCOUNT = 0
	RETURN -1
ELSE
	RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[Gp_LendBillCheck]')
                    AND TYPE IN ( N'P', N'PC' ) ) 
    DROP PROC Gp_LendBillCheck;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	借欠明显检查 tt
*/
CREATE PROCEDURE Gp_LendBillCheck
(
    @BillNumberID		INT ,
    @szPID 				varchar(1000)=''	OUTPUT
)
--@encode$--    
AS 
    BEGIN
       
		DECLARE 
		@KtypeID VARCHAR(50),
		@Billtype INT ,
		@BtypeID VARCHAR(50), 
		@Qty  NUMERIC(24, 10) ,
		@NQty  NUMERIC(24, 10) ,
		@FullName VARCHAR(200), 
		@ItemName VARCHAR(300),
		@GoodsNumber VARCHAR(100),
		@Msg VARCHAR(500)=''
		
		SET @szPID = ISNULL(@szPID,'')
		
		SELECT  @KtypeID = ktypeid ,@Billtype = BillType ,@BtypeID =  btypeid
		FROM dbo.LendIndex WHERE BillNumberId = @BillNumberID

		--验证有没有借进或者借出 start
		SELECT TOP 1 @FullName = FullName ,@ItemName = ItemName ,@GoodsNumber = GoodsNumber
		FROM (
		
			SELECT a.PtypeId,a.GoodsNumber,c.FullName,
			CASE a.IsCombined 
				WHEN 1 THEN REPLACE(e.Fullname,'я','/')
				WHEN 0 THEN ISNULL(d.Fullname,'')
				ELSE '' END  AS ItemName 
			FROM (
				SELECT PtypeId, ItemID, IsCombined, GoodsNumber 
				FROM dbo.LendBill WHERE BillNumberId = @BillNumberID
				GROUP BY PtypeId, ItemID,IsCombined,GoodsNumber
				
			) a LEFT JOIN (
			
				SELECT PtypeId, ItemID,IsCombined,GoodsNumber 
				FROM GoodsLend 
				WHERE BtypeId = @BtypeID AND KtypeId = @KtypeID 
				AND PtypeId IN(SELECT PtypeId FROM dbo.LendBill WHERE BillNumberId = @BillNumberId)
				AND (CASE @billtype WHEN 88 THEN lendQty  ELSE BorrowQty END) > 0
				
			)b ON a.PtypeId = b.PtypeId 
				AND a.ItemID = b.ItemID
				AND a.Iscombined = b.IsCombined
				AND a.GoodsNumber = b.GoodsNumber
				
			 JOIN dbo.ptype c 
			 ON a.PtypeId = c.typeId
			 LEFT JOIN xw_SelfData d
			 ON a.ItemID = d._id
			 LEFT JOIN CustomReferenceValue e
			 ON a.ItemID = e.id
			 WHERE b.PtypeId IS NULL
		 ) f
		 --验证有没有借进或者借出 end
		 
		IF @FullName IS NOT NULL
		BEGIN
			SET @szPID = '商品【'+@FullName+'】';
			IF @ItemName <> ''
				SET @szPID = @szPID + ' 自由项【'+@ItemName+'】';
			IF @GoodsNumber <> ''
				SET @szPID = @szPID + ' 批号【'+@GoodsNumber+'】';	
				
			IF @billtype = 72 
				SET @szPID = @szPID + '没有借进过！';
			ELSE IF @billtype = 88
				SET @szPID = @szPID + '没有借出过！';
			ELSE 
				SET @szPID = '';
			RETURN -712
		END
		
		

		
		--验证借出还回或者借进还出数量 start
		SELECT TOP 1 @FullName = FullName ,@ItemName = ItemName ,@GoodsNumber = GoodsNumber ,@Qty = Qty, @NQty = NQty
		FROM (
			SELECT a.PtypeId,c.Fullname,
				CASE a.IsCombined 
				WHEN 1 THEN REPLACE(e.Fullname,'я','/')
				WHEN 0 THEN ISNULL(d.Fullname,'')
				ELSE '' END  AS ItemName ,
				(a.Qty + b.Qty ) AS Qty, (a.NQty + b.NQty ) AS NQty,
				a.GoodsNumber
				FROM (
				
					SELECT PtypeId, ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
					FROM dbo.LendBill WHERE BillNumberId = @BillNumberID
					GROUP BY PtypeId, ItemID,IsCombined,GoodsNumber
					
				) a LEFT JOIN (
				
					SELECT PtypeId, ItemID,IsCombined,GoodsNumber,
						CASE @billtype WHEN 72 THEN BorrowQty   ELSE -LendQty  END  AS Qty ,
						CASE @billtype WHEN 72 THEN NBorrowQty  ELSE -NLendQty END  AS Nqty 
					FROM GoodsLend 
					WHERE BtypeId = @BtypeID AND KtypeId = @KtypeID 
					AND PtypeId IN(SELECT PtypeId FROM dbo.LendBill WHERE BillNumberId = @BillNumberId)
					AND (CASE @billtype WHEN 72 THEN BorrowQty  ELSE LendQty END) > 0
					
				)b ON a.PtypeId = b.PtypeId 
					AND a.ItemID = b.ItemID
					AND a.Iscombined = b.IsCombined
					AND a.GoodsNumber = b.GoodsNumber
					
				 JOIN dbo.ptype c 
				 ON a.PtypeId = c.typeId
				 LEFT JOIN xw_SelfData d
				 ON a.ItemID = d._id
				 LEFT JOIN CustomReferenceValue e
				 ON a.ItemID = e.id
				 WHERE 1=1 AND ((a.Qty + b.Qty ) <> 0 OR  (a.NQty + b.NQty ) <> 0)
		) f
		WHERE (@Billtype = 72 AND (f.Qty < 0 OR f.NQty < 0)) OR (@Billtype = 88 AND (f.Qty > 0 OR f.NQty > 0))
		
		
		
		IF @FullName IS NOT NULL
		BEGIN
			--72	借进还出单
			IF @Billtype = 72
			BEGIN	
				IF @Qty < 0
					SET @szPID = @szPID + '基本单位还出数量大于借进数量, 请确认后重试！';
				IF @NQty < 0
					SET @szPID = @szPID + '浮动单位还出数量大于借进数量, 请确认后重试！';
			END
			ELSE IF @billtype = 88
			BEGIN
				IF @Qty > 0
					SET @szPID = @szPID + '基本单位还回数量大于借出数量, 请确认后重试！';
				IF @NQty > 0
					SET @szPID = @szPID + '浮动单位还回数量大于借出数量, 请确认后重试！';
			END
			
			IF @szPID <> ''
			BEGIN
				SET @Msg = '商品【'+@FullName+'】';
				IF @ItemName <> ''
					SET @Msg = @Msg + ' 自由项【'+@ItemName+'】';
				IF @GoodsNumber <> ''
					SET @Msg = @Msg + ' 批号【'+@GoodsNumber+'】';
				SET @szPID = @Msg + @szPID
				RETURN -712
			END
			
			RETURN 0
		END
		ELSE
		BEGIN
			RETURN 0
		END

    END                    
                   
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO







SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：谢吉康
	日期：2003-12-23
	描述：借欠序列号查询
*/
CREATE                   PROCEDURE Gp_LendBorrowSerialSearch
(
	@OperatorID		VARCHAR(100),	--操作员ID
	@StartDate		VARCHAR(50),	--开始日期
	@EndDate		VARCHAR(50),	--结束日期
	@PTypeID		VARCHAR(8000),	--商品ID
	@dealBTypeID		VARCHAR(8000),	--客户ID
	@JTypeID		VARCHAR(8000),	--供应商ID
	@KTypeID		VARCHAR(8000),	--仓库ID
	@Serial			VARCHAR(1000),	--序列号
	@UserCode		VARCHAR(256),	--商品编号
	@FullName		VARCHAR(256),	--商品名称
	@State			VARCHAR(256),	--状态
	@USER			VARCHAR(256),	--终端用户
	@Note			VARCHAR(200),	--备注
	@ShowUser		VARCHAR(256),	--是否只显示终端用户
	@ModalSearch	VARCHAR(256)	--是否模糊查找
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetManDetailBType(@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetManDetailEType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)

--商品：
CREATE TABLE #GetSelPTypeId(TypeId varchar(100))
INSERT INTO #GetSelPTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@PTypeId,1)

--单位：
CREATE TABLE #GetSelBTypeId(TypeId varchar(100))
INSERT INTO #GetSelBTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@dealBTypeID,2)

--仓库：
CREATE TABLE #GetSelKTypeId(TypeId varchar(100))
INSERT INTO #GetSelKTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@KTypeId,4)

DECLARE @SQL VARCHAR(8000)
DECLARE @SQLWHERE VARCHAR(8000)

--处理具体的参数
IF @PTypeID = '00000'
	SELECT @PTypeID = '%'

IF @dealBTypeID = '00000'
	SELECT @dealBTypeID = '%'

IF @JTypeID = '00000'
	SELECT @JTypeID = '%'

IF @KTypeID = '00000'
	SELECT @KTypeID = '%'

BEGIN
	SELECT @SQL = '
		SELECT 	A.*,
				P.UserCode,
				e.fullname as itemfullname,
				P.FullName AS PFullName,
				K.FullName AS KFullName,
				GFullName=(SELECT FullName FROM BType WHERE SonNum=0 AND TypeID = A.BTypeID1),
				XFullName=(SELECT FullName FROM BType WHERE SonNum=0 AND TypeID = A.BTypeID2) 
		FROM 	GP_LendPTypeSerial A
			  inner join 	PType  P on A.PTypeID = P.TypeID
			inner join	Stock K on K.TypeID = A.KTypeID
				left join vWeb_ItemIDByIsCombined e  on  a.Iscombined=e.iscombined AND e.id=a.ItemID 
		WHERE 	
			    A.PTypeID  IN (SELECT * FROM #GetSelPTypeId)
				AND A.KTypeID  IN (SELECT * FROM #GetSelKTypeId)
				AND A.KTypeID  IN (SELECT TypeId FROM #GetManKTypeId)
				AND A.PTypeID  IN (SELECT TypeId FROM #GetManPTypeId)
				
				'

		SELECT @SQL = @SQL + 'AND ((A.BTypeID1 IN (SELECT * FROM #GetSelBTypeId) AND (A.BTypeID1 IN (SELECT TypeId FROM #GetManBTypeId) OR A.BTypeID1 IN (SELECT TypeId FROM #GetManBTypeId)))
			OR ((A.BTypeID2 IN (SELECT * FROM #GetSelBTypeId) AND (A.BTypeID2 IN (SELECT TypeId FROM #GetManBTypeId) OR A.BTypeID2 IN (SELECT TypeId FROM #GetManBTypeId))))
		)'



		IF @ModalSearch = 0		--模糊查找
			SELECT @SQL = @SQL + '
				AND A.Serial 	 LIKE '+CHAR(39)+'%'+@Serial  + '%'+CHAR(39)+'
				AND P.UserCode   LIKE '+CHAR(39)+'%'+@UserCode + '%'+CHAR(39)+'
				AND P.FullName   LIKE '+CHAR(39)+'%'+@FullName + '%'+CHAR(39)+'
				AND A.State		 LIKE '+CHAR(39)+'%'+@State+'%'+CHAR(39)+'

				AND (A.[User]	 LIKE '+CHAR(39)+'%'+@User+'%'+CHAR(39)+' OR A.[User] IS NULL)
				AND (A.[Note]	 LIKE '+CHAR(39)+'%'+@Note+'%'+CHAR(39)+' OR A.[Note] IS NULL)'
		ELSE
		  BEGIN	
			IF @Serial<>''
			BEGIN				
				Set @Serial=Replace(@Serial,'[%]','%')--由于序列号特殊处理过，所以当不是模糊查询的时候需要替换回来
				SELECT @SQL = @SQL + 
					'AND A.Serial 	 = '+CHAR(39)+@Serial+CHAR(39)+''
			END
			IF @UserCode<>''
				SELECT @SQL = @SQL +'AND P.UserCode   = '+CHAR(39)+@UserCode + CHAR(39)+''
			IF @FullName<>''
				SELECT @SQL = @SQL + 'AND P.FullName  = '+CHAR(39)+@FullName + CHAR(39)+''
			IF @State<>''
				SELECT @SQL = @SQL + 'AND A.State= '+CHAR(39)+@State+CHAR(39)+''
			SELECT @SQL = @SQL + ' 
				 AND (A.[User]	 LIKE '+CHAR(39)+'%'+@User+'%'+CHAR(39)+' OR A.[User] IS NULL)
				 AND (A.[Note]	 LIKE '+CHAR(39)+'%'+@Note+'%'+CHAR(39)+' OR A.[Note] IS NULL)'
		   END
		IF @ShowUser = 1		--只显示终端用户
			SELECT @SQL = @SQL + ' AND A.[USER]<>'''' '

		SELECT @SQL = @SQL + ' ORDER BY A.Serial'


	--PRINT(@SQL)
	EXEC(@SQL)
			
END

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetSelPTypeId,#GetSelBTypeId,#GetSelKTypeId




































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'Gp_LendBuySaleCheck')
                    AND TYPE IN ( N'P', N'PC' ) ) 
    DROP PROC Gp_LendBuySaleCheck;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	借欠转采购销售检查
*/
CREATE PROCEDURE Gp_LendBuySaleCheck
(
    @BillNumberID		INT ,
    @BillType			INT ,
    @szPID 				VARCHAR(1000)=''	OUTPUT
)  
AS 
    BEGIN
       
		DECLARE 
		@Stypeid		VARCHAR(50),
		@Stypeid1		VARCHAR(50),
		--@KtypeID		VARCHAR(50),
		@KtypeID1		VARCHAR(50),
		@BtypeID		VARCHAR(50), 
		@BtypeID1		VARCHAR(50), 
		@Qty			NUMERIC(24,10),
		@NQty			NUMERIC(24,10),
		@FullName		VARCHAR(200), 
		@ItemName		VARCHAR(300),
		@GoodsNumber	VARCHAR(100),
		@Msg			VARCHAR(500)='',
		@RowIndex		INT
		
		SELECT @szPID = ''
		SELECT @Stypeid = Stypeid,@BtypeID = DealBTypeID FROM dbo.BillIndex WHERE BillNumberId = @BillNumberID
		
		/***********     验证有没有借进或者借出 start ***********/
		
		CREATE TABLE #tempbilldetail_1
		(
			PtypeId				VARCHAR(50),
			KtypeId				VARCHAR(50),
			ItemID				INT,
			IsCombined			INT,
			GoodsNumber			VARCHAR(100)
		)
		
		IF @BillType = 11 
		BEGIN
			INSERT INTO #tempbilldetail_1( PtypeId , KtypeId, ItemID ,IsCombined ,GoodsNumber)
			SELECT PtypeId,KTypeID, ItemID, IsCombined, GoodsNumber 
			FROM dbo.SaleBill WHERE BillNumberId = @BillNumberID --AND LendBillNumberID <> 0
			GROUP BY PtypeId,KTypeID, ItemID,IsCombined,GoodsNumber
		END
		ELSE IF @BillType = 12
		BEGIN
			INSERT INTO #tempbilldetail_1( PtypeId , KtypeId, ItemID ,IsCombined ,GoodsNumber)
			SELECT PtypeId,KTypeID, ItemID, IsCombined, GoodsNumber 
			FROM dbo.PT_Combin_SaleBillDetail WHERE BillNumberId = @BillNumberID --AND LendBillNumberID <> 0
			GROUP BY PtypeId,KTypeID, ItemID,IsCombined,GoodsNumber
		END
		ELSE 
		BEGIN
			INSERT INTO #tempbilldetail_1( PtypeId , KtypeId,ItemID ,IsCombined ,GoodsNumber)
			SELECT PtypeId,KTypeID, ItemID, IsCombined, GoodsNumber 
			FROM dbo.BuyBill WHERE BillNumberId = @BillNumberID --AND LendBillNumberID <> 0
			GROUP BY PtypeId, KTypeID,ItemID,IsCombined,GoodsNumber
		END
		
		SELECT TOP 1 @FullName = FullName ,@ItemName = ItemName ,@GoodsNumber = GoodsNumber
		FROM (
				SELECT a.PtypeId,a.GoodsNumber,c.FullName,b.PtypeId AS bPtypeId,
					CASE a.IsCombined 
					WHEN 1 THEN REPLACE(e.Fullname,'я','/')
					WHEN 0 THEN ISNULL(d.Fullname,'')
					ELSE '' END  AS ItemName 
				FROM #tempbilldetail_1 a  
				LEFT JOIN GoodsLend b
				ON (a.PtypeId = b.PtypeId 
					AND a.KtypeId = b.KtypeId
					AND a.ItemID = b.ItemID
					AND a.Iscombined = b.IsCombined
					AND a.GoodsNumber = b.GoodsNumber
					AND b.BtypeId = @BtypeID
					AND (CASE @BillType WHEN 11 THEN b.LendQty  ELSE b.BorrowQty END) > 0
					)
				JOIN dbo.ptype c 
				ON a.PtypeId = c.typeId
				LEFT JOIN xw_SelfData d
				ON a.ItemID = d._id
				LEFT JOIN CustomReferenceValue e
				ON a.ItemID = e.id
		
		 ) f WHERE bPtypeId IS NULL
		
		 
		IF @FullName IS NOT NULL
		BEGIN
			SET @szPID = '商品【'+@FullName+'】';
			IF @ItemName <> ''
				SET @szPID = @szPID + ' 自由项【'+@ItemName+'】';
			IF @GoodsNumber <> ''
				SET @szPID = @szPID + ' 批号【'+@GoodsNumber+'】';	
				
			IF @billtype = 34 
				SET @szPID = @szPID + '没有借进过！';
			ELSE IF @billtype IN (11,12)
				SET @szPID = @szPID + '没有借出过！';
			RETURN -712
		END
		 /***********     验证有没有借进或者借出 end   ***********/
		

		--SELECT * FROM dbo.GoodsLend
--LendQty	  	 借出数量 11
--NLendQty		 借出浮动数量
--BorrowQty		 借进数量 34
--NBorrowQty	 借进浮动数量

		/***************  验证借出借进数量  start     ***********/
		CREATE TABLE #tempbilldetail_2
		(
			PtypeId				VARCHAR(50),
			KtypeId				VARCHAR(50),
			ItemID				INT,
			IsCombined			INT,
			GoodsNumber			VARCHAR(100),
			Qty					NUMERIC(24,10),
			NQty				NUMERIC(24,10)
		)
		IF @BillType = 11 
		BEGIN
			INSERT INTO #tempbilldetail_2( PtypeId ,KtypeId, ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
			SELECT PtypeId, KTypeID, ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
			FROM dbo.SaleBill WHERE BillNumberId = @BillNumberID --AND LendBillNumberID <> 0
			GROUP BY PtypeId, KTypeID, ItemID,IsCombined,GoodsNumber
		END
		ELSE IF @BillType = 12 
		BEGIN
			INSERT INTO #tempbilldetail_2( PtypeId ,KtypeId, ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
			SELECT PtypeId, KTypeID, ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
			FROM dbo.PT_Combin_SaleBillDetail WHERE BillNumberId = @BillNumberID --AND LendBillNumberID <> 0
			GROUP BY PtypeId, KTypeID, ItemID,IsCombined,GoodsNumber
		END
		ELSE 
		BEGIN
			INSERT INTO #tempbilldetail_2( PtypeId ,KtypeId ,ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
			SELECT PtypeId, KTypeID, ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
			FROM dbo.BuyBill WHERE BillNumberId = @BillNumberID --AND LendBillNumberID <> 0
			GROUP BY PtypeId, KTypeID, ItemID,IsCombined,GoodsNumber
		END

		SELECT TOP 1 @FullName = FullName ,@ItemName = ItemName ,@GoodsNumber = GoodsNumber ,@Qty = Qty, @NQty = NQty
		FROM (
			SELECT a.PtypeId,c.Fullname,
				CASE a.IsCombined 
				WHEN 1 THEN REPLACE(e.Fullname,'я','/')
				WHEN 0 THEN ISNULL(d.Fullname,'')
				ELSE '' END  AS ItemName ,
				(a.Qty - b.Qty ) AS Qty, (a.NQty - b.NQty ) AS NQty,
				a.GoodsNumber
				FROM #tempbilldetail_2  a LEFT JOIN (
				
				SELECT PtypeId, KtypeId,ItemID,IsCombined,GoodsNumber,
					CASE @billtype WHEN 34 THEN BorrowQty   ELSE LendQty  END  AS Qty ,
					CASE @billtype WHEN 34 THEN NBorrowQty  ELSE NLendQty END  AS Nqty 
				FROM GoodsLend 
				WHERE BtypeId = @BtypeID
				AND PtypeId IN(SELECT PtypeId FROM dbo.#tempbilldetail_2)
				AND (CASE @BillType WHEN 34 THEN BorrowQty  ELSE LendQty END) > 0
					
				)b ON a.PtypeId = b.PtypeId 
					AND a.KtypeId = b.KtypeId
					AND a.ItemID = b.ItemID
					AND a.Iscombined = b.IsCombined
					AND a.GoodsNumber = b.GoodsNumber
					
				 JOIN dbo.ptype c 
				 ON a.PtypeId = c.typeId
				 LEFT JOIN xw_SelfData d
				 ON a.ItemID = d._id
				 LEFT JOIN CustomReferenceValue e
				 ON a.ItemID = e.id
				 WHERE (a.Qty - b.Qty ) > 0 OR  (a.NQty - b.NQty ) > 0
		) f		
		
		IF @FullName IS NOT NULL
		BEGIN
			IF @Billtype = 34
			BEGIN	
				IF @Qty > 0
					SET @szPID = @szPID + '基本单位数量超出借进数量，';
				IF @NQty > 0
					SET @szPID = @szPID + '浮动单位数量超出借进浮动数量，';
			END
			ELSE IF @billtype IN (11,12)
			BEGIN
				IF @Qty > 0
					SET @szPID = @szPID + '基本单位数量超出借出数量，';
				IF @NQty > 0
					SET @szPID = @szPID + '浮动单位数量超出借出浮动数量，';
			END
			
			IF @szPID <> ''
			BEGIN
				SET @Msg = '商品【'+@FullName+'】';
				IF @ItemName <> ''
					SET @Msg = @Msg + ' 自由项【'+@ItemName+'】';
				IF @GoodsNumber <> ''
					SET @Msg = @Msg + ' 批号【'+@GoodsNumber+'】';
				SET @szPID = @Msg + @szPID +'不能过账，请确认后重试！'
				RETURN -712
			END

		END
		/***************  验证借出借进数量  end       ***********/
		
		
		
		DECLARE   
		@chrOperateType		int,				-- 序列号状态
		@Serial				VARCHAR(MAX ),		
		@chvSerial			varchar(50),		-- 序列号
		@chvPTypeID			varchar(50)	= '',	-- 商品 ID 值
		@chvKTypeID			varchar(50)	= '',	-- 仓库 ID 值 
		@chvBTypeID			varchar(50)	= '',	-- 往来单位 ID 值
		@chvItemId			int=0,				-- 自由项
		@chvGoodsNumber		varchar(100)=''	,	-- 批号
		@state				INT = 0	,			-- 退出游标标志
		@chvIsCombined		BIT = 0	,			-- 组合，
		@chvismngSerial		INT = 0	,			-- 系统采用序列号严密管理模式
		@chvserialRelation	INT = 0 ,			-- 序列号关联货位、自由项、批次批号
		@chvItemId1			int=0,				-- 自由项
		@chvGoodsNumber1	varchar(100)='',	-- 批号
		@chvIsCombined1		BIT = 0	,			-- 组合
		@chvPFullName		VARCHAR(200)	= ''
		
		/*****************  序列号验证  BEGIN     ***************/
		
		SELECT @chvismngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial' 
		SELECT  @chvserialRelation = Value FROM UserConfig WHERE ConfigName = 'serialRelation' 

		--系统采用序列号严密管理模式
		--17	借进
		--18	借出
		--19	借进还出  不允许转采购
		--20	借出还回  不允许转销售
		--34	已转采购
		--33	已转销售
		
		DECLARE @CURSORT CURSOR 
		IF @BillType = 11
			SET @CURSORT = CURSOR FOR SELECT Serial,PtypeId, ISNULL(ItemID,0),ISNULL(GoodsNumber,''),IsCombined FROM dbo.SaleBill WHERE BillNumberId = @BillNumberID  AND  Serial !=''
		ELSE IF @BillType = 12
			SET @CURSORT = CURSOR FOR SELECT Serial,PtypeId, ISNULL(ItemID,0),ISNULL(GoodsNumber,''),IsCombined FROM dbo.PT_Combin_SaleBillDetail WHERE BillNumberId = @BillNumberID  AND  Serial !=''			
		ELSE
			SET @CURSORT = CURSOR FOR SELECT Serial,PtypeId, ISNULL(ItemID,0),ISNULL(GoodsNumber,''),IsCombined FROM dbo.BuyBill  WHERE BillNumberId = @BillNumberID  AND  Serial !=''
		OPEN @CURSORT
		FETCH NEXT FROM @CURSORT INTO @Serial ,@chvPTypeID ,@chvItemId ,@chvGoodsNumber,@chvIsCombined
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @state <> 0
				BREAK
			
			SELECT @chvPFullName = FullName FROM dbo.ptype WHERE typeId = @chvPTypeID
			
			DECLARE CURSORT00 CURSOR FOR
			SELECT a AS 'Serial' FROM  dbo.f_split(@Serial,'я') WHERE a !='' 
			OPEN CURSORT00
			FETCH NEXT FROM CURSORT00 INTO @chvSerial 
			WHILE @@FETCH_STATUS = 0
			BEGIN
				/*****************  序列号状态检查    ***************/
				--WHEN 17 THEN '借进'
				--WHEN 18 THEN '借出'
				--WHEN 19 THEN '借进还出'
				--WHEN 20 THEN '借出还回'
				IF @BillType = 34 AND NOT EXISTS( SELECT TOP 1 1 FROM dbo.gp_LendPtypeSerial WHERE Serial = @chvSerial AND State IN(17,18,20))
				BEGIN
					SET @szPID = '序列号'+@chvSerial+'在当前借欠序列号库中没有借进记录存在，不允许转采购，请确认后重试！'
				END
				IF @BillType IN (11,12) AND NOT EXISTS( SELECT TOP 1 1 FROM dbo.gp_LendPtypeSerial WHERE Serial = @chvSerial AND State = 18 )
				BEGIN
					SET @szPID = '序列号'+@chvSerial+'在当前借欠序列号库中没有借出记录存在，不允许转销售，请确认后重试！'
				END	
				IF NOT EXISTS (SELECT TOP 1 1 FROM dbo.gp_LendPtypeSerial WHERE Serial = @chvSerial )
				BEGIN
					SET @szPID = '序列号'+@chvSerial+'在当前借欠序列号库中没有借'+CASE @BillType WHEN 34 THEN '进'  ELSE '出' END + '记录存在，不允许转'+CASE @BillType WHEN 34 THEN '采购'  ELSE '销售' END + '，请确认后重试！'
				END
				IF @szPID <> ''
				BEGIN
					SET @state = 1
					BREAK
				END 	
				/*****************  序列号状态检查    ***************/
				
				/*****************  序列号关联维度检查    ***************/
				--严密管理模式
				IF @chvserialRelation = 1
				BEGIN
					--商品XXX和序列号XXX所关联的维度（如自由项、批号）不匹配，请确认后重试！
					SELECT @chvItemId1 = ItemID,@chvGoodsNumber1 = GoodsNumber,@chvIsCombined1 = IsCombined FROM gp_LendPtypeSerial WHERE Serial = @chvSerial
					IF(@chvItemId <> @chvItemId1 OR @chvIsCombined <> @chvIsCombined1)
					BEGIN
						SET @szPID = '商品【'+@chvPFullName+'】和序列号'+@chvSerial+'所关联的维度 自由项 不匹配，请确认后重试！';
					END
					ELSE IF (@chvGoodsNumber <> @chvGoodsNumber1 )
					BEGIN
						SET @szPID = '商品【'+@chvPFullName+'】和序列号'+@chvSerial+'所关联的维度 批号 不匹配，请确认后重试！';
					END 
				END
				IF @szPID <> ''
				BEGIN
					SET @state = 1
					BREAK
				END 
				/*****************  序列号关联维度检查e    ***************/	
		
				 
			FETCH NEXT FROM CURSORT00 INTO @chvSerial
			END
			CLOSE CURSORT00
			DEALLOCATE CURSORT00
			
			FETCH NEXT FROM @CURSORT INTO @Serial ,@chvPTypeID ,@chvItemId ,@chvGoodsNumber,@chvIsCombined
		END
		CLOSE @CURSORT
		DEALLOCATE @CURSORT
		
		IF @szPID <> ''
				RETURN -711
		/*****************  序列号验证  end       ***************/
		
		
		
		
		
    END                    
                   
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*

BEGIN TRAN
--SELECT * FROM dbo.BillIndex
DECLARE 
@szPID 				VARCHAR(1000)='',
@ret				INT = 0,
@BillType			INT = 0,
@BillNumberID		INT = 11  --必填
BEGIN TRAN

SELECT @BillType = BillType FROM dbo.BillIndex WHERE BillNumberId = @BillNumberID

EXEC @ret = dbo.Gp_LendBuySaleCheck
    @BillNumberID  ,
    @BillType,  
    @szPID OUT 

SELECT @ret AS ret, @szPID AS szPID
ROLLBACK TRAN


*/




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


/*	
	作者：张陈仁
	时间：2011-08-18
	描述：虚拟库明细帐本借进借出期初
*/

CREATE          PROCEDURE Gp_LendInit
( 
	@OperatorID 		varchar(100),  	     	--操作员ID号 
	@Parid   			varchar(100)='00000',   --商品的父节点号
	@szKtypeId  		varchar(8000)='',       --仓库id号
	@sortfield 			varchar(20),            --按何种方式排序
	@EntryCode			varchar(200),			--商品条码
	@Standard			varchar(200),			--商品规格
	@Ptypeid		    varchar(200),			--商品型号
	@Area				varchar(200),			--商品产地
	@BillType           varchar(50),            --单据类型
	@stypeid			VARCHAR(8000),		    --分支机构id
	@Order              VARCHAR(200)='ORDER BY P.UserCode,p.FullName',           --排序
	@startdate          VARCHAR(30),            --起始时间
	@enddate            VARCHAR(30)             --结束时间
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
DECLARE @SQL varchar(8000)  

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	

--商品
CREATE TABLE #GetManPTypeId
(
	TypeId			varchar(100),
	EntryCode		varchar(100),
	[Standard]		varchar(100),
	[Type]			varchar(20),
	Area			varchar(30)
)
INSERT INTO #GetManPTypeId
(
	TypeId,
	EntryCode,
	[Standard],
	[Type],
	Area
) 
SELECT p.typeId,
	   p.EntryCode,
	   p.Standard,
	   p.Type,
	   p.Area
FROM ptype p	INNER JOIN F_GetManDetailPType(@OperatorID) mp	ON mp.TypeId=p.typeId

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetManDetailBType(@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetManDetailEType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT mk.Typeid FROM F_GetManDetailKTypeSType(@OperatorID) mk
			INNER JOIN #GetSelectSTypeId s ON mk.STypeId=s.TypeId

--仓库
CREATE TABLE #GetManSelKTypeId(TypeId	varchar(100))
INSERT INTO #GetManSelKTypeId(TypeId)
SELECT sk.TypeId FROM F_GetAllBaseTypeId(@szKTypeId,4) sk
			INNER JOIN (SELECT Typeid FROM stock WHERE STypeID IN(SELECT TYPEID FROM #GetSelectSTypeId)) s ON sk.TypeId=s.TypeId


SELECT * INTO #GetManPTypeAll FROM F_GetManPTypeAll(@OperatorID)
DECLARE @MMPtypeid VARCHAR(100)
SET @MMPtypeid=''

IF LEFT(@parid,len(@MMPtypeid))<>@MMPtypeid SET @parid=LEFT(@MMPtypeid,len(@MMPtypeid)-5)
IF @Parid='' SET @Parid='00000'   ---肖伟 2002-06-27加速库存状况查询,并补漏:
                                                       ---如果某操作员设置了权限,并浏览第一层,那么此时的Parid='',什么商品都看不到

IF @szKtypeId='' OR @szKtypeId='00000'   SELECT @szKtypeId='%'	-- 全部仓库


CREATE TABLE #LendTable
	(
	   BillNumberId VARCHAR(50),   --单据ID
	   BillCode     VARCHAR(100),  --单据编号
	   BillDate     DATETIME,      --单据日期
	   BillType     VARCHAR(50),   --单据类型
	   EtypeId      VARCHAR(50),   --职员ID
	   BtypeId      VARCHAR(50),   --往来单位ID
	   PtypeId      VARCHAR(50),   --商品ID
	   StypeId      VARCHAR(50),   --分支机构ID
	   KtypeId      VARCHAR(50),   --仓库ID
	   Qty           NUMERIC(24, 10) , --数量
	   Comment      VARCHAR(256)   --摘要
	)
	
DECLARE @tempSql VARCHAR(max)

SET @tempSql='
   INSERT INTO #LendTable
		(
		   BillNumberId,
		   BillCode,
		   BillDate,
		   BillType,
		   EtypeId,
		   BtypeId,
		   PtypeId,
		   StypeId,
		   Ktypeid,
		   Qty,
		   Comment
		)
   SELECT  B.BillNumberId,
		   I.BillCode,
		   I.BillDate,
		   I.BillType,
		   I.etypeid,
		   I.btypeid,
		   B.PtypeId,
		   B.StypeId,
		   I.ktypeid,
		   B.Qty,
		   I.Comment 
   FROM  dbo.LendBill B 
   INNER JOIN dbo.LendIndex I ON B.BillNumberId=I.BillNumberId '
   SET @tempSql=@tempSql+' WHERE I.BillType IN ('+@BillType+') AND I.BillDate<'''+@startdate+''' '
  --PRINT @tempSql 
  
EXEC (@tempSql)	

DECLARE @Borrow VARCHAR(20),@Lend VARCHAR(20),@LendCount INT 
SELECT
	 @Borrow=SUM(ISNULL(Borrow,0)),
	 @Lend=SUM(ISNULL(Lend,0)) 
FROM V_LendFace00  A
INNER JOIN #GetManSelKTypeId k ON a.kTypeID=k.TypeId
INNER JOIN #GetSelectSTypeId s  ON  a.STypeID=s.typeid
WHERE pTypeID LIKE ''+@Ptypeid+'%'  --这里是查期初数量

SELECT @LendCount=COUNT(*) FROM #LendTable  --查询当前时间之前的库存记录（也要算到此前余量里面）

IF @LendCount>0
	BEGIN 
		SET @SQL='SELECT
						CONVERT( NUMERIC(24, 10) ,'+ISNULL(@Borrow,0)+')+SUM(ISNULL(a.Qty,0)) as BorrowInit,
						CONVERT( NUMERIC(24, 10) ,'+ISNULL(@Lend,0)+')-SUM(ISNULL(a.Qty,0)) AS LendInit,
						p.UserCode,
						p.FullName 
			   FROM #GetManPTypeAll P  
			   LEFT JOIN #LendTable a ON p.typeId=LEFT(a.pTypeID,LEN(P.typeId))
			   INNER JOIN #GetManSelKTypeId k ON a.kTypeID=k.TypeId  
			   INNER JOIN #GetSelectSTypeId s  ON  a.STypeID=s.typeid
			   '
			   IF @ptypeid<>'' OR @MPTypeID=-99999 
				   SET @SQL=@SQL+' INNER JOIN #GetManPTypeAll PP ON a.pTypeID=PP.typeid '+CHAR(13)
			   SET @SQL=@SQL+' WHERE P.typeId='''+@Ptypeid+''' group by p.UserCode,p.FullName  
									 '+@Order+' ' 
		--PRINT @SQL								 
		EXEC(@SQL)
	END
ELSE
	BEGIN
		SELECT  ISNULL(@Borrow,0) AS BorrowInit,ISNULL(@Lend,0) AS LendInit
	END
DROP TABLE #LendTable
DROP TABLE #GetSelectSTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManSelKTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/****** Object:  Stored Procedure dbo.Gp_LendSearch    Script Date: 2002-6-20 10:14:49 ******/

/*
    借进借出的所有查询功能
    @LendOrBorrow: 是借进还是借出
    @Mode : 1.分组筛选查询(单位)
	   参数： @LendOrBorrow 0 借出 1 借进
		 @Filt    筛选统计字段 商品（与分组相反）
		 @FiltVal 其他筛选条件
	    1.分组筛选查询(商品)
	   参数： @LendOrBorrow 0 借出 1 借进
		 @Filt    筛选统计字段 单位（与分组相反）
		 @FiltVal 其他筛选条件
*/
CREATE      PROCEDURE Gp_LendSearch
( 
    @OperatorID     varchar(100),         -- 操作员
	@LendOrBorrow   varchar(20),
	@Mode		    int,
	@Filt		    varchar(50)='',
	@FiltVal	    varchar(200)='',
	@STypeId		varchar(max)		-- 分支机构
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

SET NOCOUNT ON
DECLARE	@RetVal	int
SET @RetVal = -99

DECLARE	@SQLText	varchar(8000)
DECLARE	@SQLWhere	varchar(8000)
SET	@SQLText = ''
SET	@SQLWhere = ''

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

IF @Mode = 1 
BEGIN
-- 分组筛选查询--根据一定的商品对单位分组统计
	SET @SQLText = '
				SELECT	
				       bTypeID,
				       bUserCode,
					   bFullName,
												
						
						SUM(Borrow) AS Borrow,SUM(BorrowBack) AS BorrowBack,
						SUM(Lend) AS Lend,
						SUM(LendBack) AS LendBack,
						SUM(Qty) AS Qty,
						sum(saleqty) as saleqty,
						sum(buyqty) as buyqty
				FROM(
						SELECT	pUserCode,			
								pFullName,
								pEntryCode,
								pTypeID,
								kUserCode,
								kFullName,
								kTypeID,
								bUserCode,
								bFullName,
							    bTypeID,
								billdate,
								qty,
								Borrow,
								BorrowBack,
								Lend,
								LendBack,
								STypeId,
								ifcheck,
								saleqty,
								buyqty
						FROM	V_LendFace
						WHERE ETypeID IN (SELECT typeid FROM F_GetManDetailEtype('''+@OperatorID+'''))
						UNION ALL
						SELECT	pUserCode,
								pFullName,
								pEntryCode,
								pTypeID,
								kUserCode,
								kFullName,
								kTypeID,
								bUserCode,
								bFullName,
								bTypeID,
								0 as billdate,
								qty,
								Borrow,
								0 AS BorrowBack,
								Lend,
								0 AS LendBack,
								STypeId,
								''t'',
								0 as saleqty,
								0 as buyqty
					    FROM	V_LendFace00
				) AS	 V_LendStatus2  '


	IF @Filt <> ''  SET @SQLWhere = @SQLWhere
			+' AND pTypeID = '''+ @Filt +''' '
	
END

-- 分组筛选查询--根据一定的单位对商品分组统计
IF @Mode = 2
BEGIN
	SET @SQLText = 'SELECT  pTypeID,							
							pUserCode,
							pFullName,
							pEntryCode,
							SUM(Borrow) AS Borrow,SUM(BorrowBack) AS BorrowBack,
							SUM(Lend) AS Lend,
							SUM(LendBack) AS LendBack,
							SUM(Qty) AS Qty,
							sum(saleqty) as saleqty,
						    sum(buyqty) as buyqty
				FROM(
						SELECT	pUserCode,			
								pFullName,
								pEntryCode,
								pTypeID,
								kUserCode,
								kFullName,
								kTypeID,
								bUserCode,
								bFullName,
							    bTypeID,
								billdate,
								qty,
								Borrow,
								BorrowBack,
								Lend,
								LendBack,
								STypeId,
								ifcheck,
								saleqty,
								buyqty
						FROM	V_LendFace
						WHERE 	ETypeID IN (SELECT typeid FROM F_GetManDetailEtype('''+@OperatorID+'''))
						UNION ALL
						SELECT	pUserCode,
								pFullName,
								pEntryCode,
								pTypeID,
								kUserCode,
								kFullName,
								kTypeID,
								bUserCode,
								bFullName,
								bTypeID,
								0 as billdate,
								qty,
								Borrow,
								0 AS BorrowBack,
								Lend,
								0 AS LendBack,
								STypeId,
								''t'',
								0 as saleqty,
								0 as buyqty
						FROM	V_LendFace00
				) AS	 V_LendStatus2 '


	IF @Filt <> ''  SET @SQLWhere = @SQLWhere
			+' AND bTypeID = '''+ @Filt +''' '
END

-- 过滤
IF RTRIM(@FiltVal)<>''
BEGIN
	-- 符号变换
	SET @FiltVal = REPLACE(@FiltVal,'~','''')
	SET @FiltVal = REPLACE(@FiltVal,'$','%')
	SET @FiltVal = REPLACE(@FiltVal,'{','>')
	SET @FiltVal = REPLACE(@FiltVal,'}','<')
	
	IF CHARINDEX('AND',LTRIM(UPPER(@FiltVal))) = 1
		SELECT @SQLWhere = @SQLWhere + ' ' + RTRIM(@FiltVal)
	ELSE
		SELECT @SQLWhere = @SQLWhere + ' AND ' + RTRIM(@FiltVal)
END

--IF @LendOrBorrow='Lend'
--	SELECT @SQLWhere = @SQLWhere + ' AND [Lend]-[LendBack]<>0 '
--IF @LendOrBorrow='Borrow'
--	SELECT @SQLWhere = @SQLWhere + ' AND [Borrow]-[BorrowBack]<>0'

SELECT @SQLWhere= @SQLWhere+' AND V_LendStatus2.ptypeId IN (SELECT typeid FROM F_GetManDetailPtype('''+@OperatorID+'''))'
SELECT @SQLWhere= @SQLWhere+' AND V_LendStatus2.btypeId IN (SELECT typeid FROM F_GetManDetailBtype('''+@OperatorID+'''))'
SELECT @SQLWhere= @SQLWhere+' AND V_LendStatus2.KtypeId IN (SELECT typeid FROM F_GetManDetailKtype('''+@OperatorID+'''))'
SELECT @SQLWhere= @SQLWhere+' AND V_LendStatus2.StypeId IN (SELECT typeid FROM #GetManSTypeId)'
SET @SQLWhere+='	AND V_LendStatus2.ifcheck=''t'''
-- 去掉多余的 AND
IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + Right(@SQLWhere,LEN(@SQLWhere)-4)

SET @SQLText = @SQLText + @SQLWhere

IF @Mode = 1 
	SET @SQLText = @SQLText +' GROUP BY bTypeID,bUserCode,bFullName 
							   ORDER BY bUserCode'

IF @Mode = 2
	SET @SQLText = @SQLText +' GROUP BY pTypeID,pUserCode,pEntryCode,pFullName 
							   ORDER BY pUserCode'

EXEC(@SQLText)

DROP TABLE #GetManSTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE GP_LoadDeliveryBillIndex 
( 
 @BillNumberId VARCHAR(20)
)
--@encode$--
AS
SET NOCOUNT ON 

SELECT cbd.BillId,cbd.BillType,
cbd.SysDiy1_head as 'SysDiy1',cbd.SysDiy2_head as 'SysDiy2',cbd.SysDiy3_head as 'SysDiy3',cbd.SysDiy4_head as 'SysDiy4',
cbd.SysDiy5_head as 'SysDiy5',cbd.SysDiy6_head as 'SysDiy6',cbd.SysDiy7_head as 'SysDiy7',cbd.SysDiy8_head as 'SysDiy8',
cbd.SysDiy9_head as 'SysDiy9',cbd.SysDiy10_head as 'SysDiy10',cbd.SysDiy11_head as 'SysDiy11',cbd.SysDiy12_head as 'SysDiy12',
cbd.SysDiy13_head as 'SysDiy13',cbd.SysDiy14_head as 'SysDiy14',cbd.SysDiy15_head as 'SysDiy15',cbd.SysDiy16_head as 'SysDiy16',
cbd.SysDiy17_head as 'SysDiy17',cbd.SysDiy18_head as 'SysDiy18',cbd.SysDiy19_head as 'SysDiy19',cbd.SysDiy20_head as 'SysDiy20',
cbd.SysDiy21_head as 'SysDiy21',cbd.SysDiy22_head as 'SysDiy22',cbd.SysDiy23_head as 'SysDiy23',cbd.SysDiy24_head as 'SysDiy24',
cbd.SysDiy25_head as 'SysDiy25',cbd.SysDiy26_head as 'SysDiy26',cbd.SysDiy27_head as 'SysDiy27',cbd.SysDiy28_head as 'SysDiy28',
cbd.SysDiy29_head as 'SysDiy29',cbd.SysDiy30_head as 'SysDiy30',cbd.SysDiy31_head as 'SysDiy31',cbd.SysDiy32_head as 'SysDiy32',
cbd.SysDiy33_head as 'SysDiy33',cbd.SysDiy34_head as 'SysDiy34',cbd.SysDiy35_head as 'SysDiy35',cbd.SysDiy36_head as 'SysDiy36',
cbd.SysDiy37_head as 'SysDiy37',cbd.SysDiy38_head as 'SysDiy38',cbd.SysDiy39_head as 'SysDiy39',cbd.SysDiy40_head as 'SysDiy40',
e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_H
FROM Custom_BillIndex cbd
INNER JOIN dbo.PosAllotApplyBillIndex oi ON cbd.BillType = oi.billtype AND cbd.BillId=oi.billNumberId
LEFT JOIN employee e ON cbd.sysdiy11_head=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12_head=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13_head=b.typeid
LEFT JOIN department d ON cbd.sysdiy14_head=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15_head=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16_head=s.typeid
WHERE oi.BillNumberId=@billnumberid
	

SELECT [BillNumberId],i.[BillType],[BillCode],[BillDate],
	i.ApplyEtypeId,i.BillOver,i.BillState,i.CID,i.Checker,i.CheckerTime,
	i.Comment,i.DtypeId,i.Explain,i.InKtypeId,i.IsAutoGenerate,i.IsIni,i.IsNeedTransport,i.Isdone,
	i.KtypeId,i.LinkAddr,i.LinkMan,i.LinkTel,i.Qty,i.RedWord,i.StopReason,i.StypeId,
	i.Total,i.Updater,i.UpdaterTime, case when i.WarehouseOutDay = 9999 then null else i.WarehouseOutDay end as WarehouseOutDay,i.checkE,i.checkTime,i.costsale,i.draft,i.ifYearBill,	i.ifcheck,
	[ApplyEtypeId] as etypeid,
	e.FullName as efullname,
	e.fullname as applyefullname,
	st.fullname as sfullname,
	d.fullname as dfullname,
	s.fullname as kfullname,
	i.KtypeId as ktypeidout,
	s.fullname as kfullnameout,
	i.[InKtypeId] AS ktypeidin,
	s1.fullname as kfullnamein,
	e1.fullname as [checkename],
	e2.FullName as checkername,
	ct.*
FROM [dbo].[PosAllotApplyBillIndex] i
LEFT JOIN stock s ON s.typeid=i.ktypeid
LEFT JOIN stock s1 ON s1.typeid=i.inktypeid
LEFT JOIN employee e ON e.typeid=i.applyetypeid
LEFT JOIN employee e1 ON e1.typeid=i.checkE
LEFT JOIN employee e2 ON e2.typeid=i.Checker
LEFT JOIN department d ON d.typeid=i.dtypeid
LEFT JOIN stype st ON st.typeid=i.stypeid
LEFT JOIN #Custom_H ct ON ct.BillId = i.BillNumberId AND ct.BillType = i.BillType
WHERE i.billnumberid=@billnumberid

--select * from [PosAllotApplyBillIndex]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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










--尹毅


CREATE        PROCEDURE [dbo].[GP_LockBangDing] 
(
	@OperatorID 	VARCHAR(50), 	--操作员ID号
	@ETypeid	VARCHAR(50),	
	@LockNum	VARCHAR(50),	--锁号
	@LockRank	int
)
--@encode$--
AS


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
if not exists (select etypeid from loginuser where LockNum = @LockNum)
begin
	UPDATE loginuser
	SET locknum = @LockNum,LockRank=@LockRank
	WHERE etypeid = @ETypeid
--	return 0
--end 
--else
--begin
	return -1
end
else
	return 0










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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








--尹毅

CREATE     PROCEDURE [dbo].[GP_LockBangDingClear] 
(
	@OperatorID 	VARCHAR(50), 	--操作员ID号
	@ETypeid	VARCHAR(50)
)
--@encode$--
AS


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
UPDATE loginuser
SET locknum = ''
WHERE etypeid = @ETypeid 







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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












--尹毅

CREATE         PROCEDURE [dbo].[GP_LockOpenSave] 
(
	@OperatorID 	VARCHAR(50), 	--操作员ID号
	@EtypeId	VARCHAR(50),
	@LockOpen	bit
)
--@encode$--
AS


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

UPDATE loginuser
SET openlock = @LockOpen
WHERE etypeid = @EtypeId







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*	
	修改 : 喻	堂
	日期 : 2012/02/20
	描述 : 直接在查询语句中调用函数，而不使用临时表和游标        
*/
-- 返回 -1 往来单位名称不正确
CREATE   PROCEDURE [dbo].[Gp_LoginUserList] 
(
	@ETypeID		[varchar](100)='',
	@BTypeCode		[varchar](26)='',
	@BTypeName		[varchar](66)='',
	@UserCode		[varchar](26)='',
	@FullName		[varchar](66)='',
	@FiltVal		[varchar](250)='',
	@OrderBy		[varchar](50)='[UserCode]',
	@optype			[varchar](50)=''
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @SQLText	[varchar](8000)
DECLARE @SQLWhere	[varchar](2000)
DECLARE @BTYPEID_U	[varchar](100)
SELECT @SQLText  = ''
SELECT @SQLWhere = 'e.[TypeID]<>''00000'''

-- 确定职员的范围
IF @ETypeID<>'00000' AND @ETypeID<>'00001'
BEGIN
	SET @SQLWhere += ' AND E.TypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''',3,'''+@ETypeID+''')) AND E.TypeId <> '''+@ETypeID+''' AND E.TypeId <> ''00001'' '
END
IF LTRIM(@BTypeCode) <> ''
	SELECT @SQLWhere += ' AND (b.[UserCode] LIKE ''' + @BTypeCode + '%'' '
			+  ' OR b.[TypeID] = ''' + @BTypeCode + ''') '
IF LTRIM(@BTypeName) <> ''
	SELECT @SQLWhere += ' AND b.[FullName] LIKE ''' + @BTypeName + '%'' '
	
IF LTRIM(@UserCode) <> ''
	SELECT @SQLWhere += ' AND (e.[UserCode] LIKE ''%' + @UserCode + '%'' '
			+  ' OR e.[TypeID] = ''' + @UserCode + ''') '
IF LTRIM(@FullName) <> ''
	SELECT @SQLWhere += ' AND e.[FullName] LIKE ''%' + @FullName + '%'' '
IF @optype='1'
	SET @SQLWhere+='AND l.iserp=1 '
IF @optype='2'
	SET @SQLWhere+='AND l.ispos=1 AND l.iserp<>1 '
-- 过滤
IF RTRIM(@FiltVal)<>''
BEGIN
	-- 符号变换
	SELECT @FiltVal = REPLACE(@FiltVal,'~','''')
	SELECT @FiltVal = REPLACE(@FiltVal,'$','%')
	SELECT @FiltVal = REPLACE(@FiltVal,'{','>')
	SELECT @FiltVal = REPLACE(@FiltVal,'}','<')
	IF CHARINDEX('AND',LTRIM(UPPER(@FiltVal))) = 1
		SELECT @SQLWhere += @SQLWhere + ' ' + @FiltVal
	ELSE
		SELECT @SQLWhere += @SQLWhere + ' AND ' + @FiltVal
END

-- 去掉多余的 AND
--IF @SQLWhere<>''
	SELECT @SQLWhere =' WHERE ' + @SQLWhere;

SET @SQLText = '
SELECT 	e.[UserCode],
		e.[FullName],
		l.*,
		CASE WHEN l.isErp = 1  THEN ''是'' ELSE ''否'' END AS Erp,
		CASE WHEN l.isPos = 1  THEN ''是'' ELSE ''否'' END AS Pos,
		CASE WHEN isMobile = 1 THEN ''是'' ELSE ''否'' END Mobile,
		CASE WHEN l.isErp = 1  THEN ''ERP操作员'' WHEN l.isPos = 1 THEN ''POS操作员'' ELSE '''' END AS optype,
		dbo.F_GetPath(MangerBTypeID,2) AS MBTypePath,
		dbo.F_GetPath(MangerBTypeID2,2) AS MBType2Path,
		dbo.F_GetPath(MangerPTypeID,4) AS MPTypePath,
		dbo.F_GetPath(MangerETypeID,3) AS METypePath,
		dbo.F_GetPath(MangerKTypeID,5) AS MKTypePath,
		dbo.F_GetPath(MangerDTypeID,10) AS MDTypePath,
		dbo.F_GetPath(MangerSTypeID,13) AS MSTypePath,
		case 
			when etypeid=''00001'' 
				then 0
			else 2
		end as Morder,
		e.Department,
		e.job	
FROM [employee] e JOIN [Loginuser] l ON (e.[TypeID]=l.[ETypeID])
'+@SQLWhere+'
ORDER BY Morder, '+@OrderBy;
	
--PRINT(@SQLText)
EXEC(@SQLText)

GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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













/****** Object:  Stored Procedure dbo.Gp_LoginUserList    Script Date: 2002-6-20 10:14:50 ******/

/*
   按照职员的特性筛选登陆用户
   成都任我行软件公司Copy Right --刘畅
   20001-12-25 圣诞节
   参数：
     @ETypeID  操作员ID 及其管辖的职员(用于分级管理暂封)
     @BTypeID(@BTypeCode), @BTypeName 职员所在单位 
     @UserCode 职员的编号
     @FullName 职员的全名
     @FiltVal  其他过滤条件
     @OrderBy  排序字段
*/
-- 返回 -1 往来单位名称不正确
CREATE PROCEDURE Gp_LoginUserListNew
(
  @ETypeID		[varchar](100)='',
  @BTypeCode	[varchar](26)='',
  @BTypeName	[varchar](66)='',
  @UserCode		[varchar](26)='',
  @FullName		[varchar](66)='',
  @FiltVal		[varchar](250)='',
  @OrderBy		[varchar](50)='[UserCode]' 
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @SQLText	[varchar](8000)
DECLARE @SQLFrom	[varchar](4000)
DECLARE @SQLWhere	[varchar](2000)
DECLARE @BTYPEID_U	[varchar](100)
SELECT @SQLText  = ''
SELECT @SQLFrom  = ''
SELECT @SQLWhere = 'AND e.[TypeID]<>''00000''  and e.deleted=0 AND e.TypeId <> ''00001'''	--谢吉康 IP弟子批量设置 不包括超级用户 2005-11-7
-- 确定职员的范围
--SELECT @ETypeID = MangerETypeID 
--FROM loginuser
--WHERE [EtypeID] = @ETypeID
IF (@ETypeID<>'00000') AND (@ETypeID<>'00001')
BEGIN
	SELECT @SQLWhere = ' AND e.[TypeID] LIKE ''' + @ETypeID + '%'' '
END
IF LTRIM(@BTypeCode) <> ''
	SELECT @SQLWhere = ' AND (b.[UserCode] LIKE ''' + @BTypeCode + '%'' '
			+  ' OR b.[TypeID] = ''' + @BTypeCode + ''') '
IF LTRIM(@BTypeName) <> ''
	SELECT @SQLWhere = ' AND b.[FullName] LIKE ''' + @BTypeName + '%'' '
IF LTRIM(@UserCode) <> ''
	SELECT @SQLWhere = ' AND (e.[UserCode] LIKE ''%' + @UserCode + '%'' '
			+  ' OR e.[TypeID] = ''' + @UserCode + ''') '
IF LTRIM(@FullName) <> ''
	SELECT @SQLWhere = ' AND e.[FullName] LIKE ''%' + @FullName + '%'' '
-- 过滤
IF RTRIM(@FiltVal)<>''
BEGIN
	-- 符号变换
	SELECT @FiltVal = REPLACE(@FiltVal,'~','''')
	SELECT @FiltVal = REPLACE(@FiltVal,'$','%')
	SELECT @FiltVal = REPLACE(@FiltVal,'{','>')
	SELECT @FiltVal = REPLACE(@FiltVal,'}','<')
	IF CHARINDEX('AND',LTRIM(UPPER(@FiltVal))) = 1
		SELECT @SQLWhere = @SQLWhere + ' ' + @FiltVal
	ELSE
		SELECT @SQLWhere = @SQLWhere + ' AND ' + @FiltVal
END
-- 去掉多余的 AND
IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + Right(@SQLWhere,LEN(@SQLWhere)-4)
-- 建立结果集From

/*肖伟 2002-11-11日根据ALAN动用BTypeID字段所做的修改开始*/
--IF (@ETypeID<>'00000') AND (@ETypeID<>'00001')
       SELECT @SQLFrom = ' FROM [employee] e JOIN [Loginuser] l ON (e.[TypeID]=l.[ETypeID]) '
--Else
--       SELECT @SQLFrom = ' FROM [employee] e JOIN [btype] b ON (e.[BTypeID]=b.[TypeID]) '
--		+ ' JOIN [Loginuser] l ON (e.[TypeID]=l.[ETypeID]) '
/*肖伟 2002-11-11日根据ALAN动用BTypeID字段所做的修改结束*/

-- 获得临时表
DECLARE @TableName	[varchar](500)
SELECT @TableName = 'Web2' + convert(varchar(2),datepart(dd,GetDate()))
		+ convert(varchar(2),datepart(hh,GetDate()))
		+ convert(varchar(2),datepart(m,GetDate()))
		+ convert(varchar(2),datepart(s,GetDate()))
		+ convert(varchar(4),datepart(ms,GetDate()))
-- 插入记录
SELECT @SQLText = ' SELECT e.[UserCode],e.[FullName],l.*'
		+ ',REPLICATE('' '',200) AS MBTypePath'
		+ ',REPLICATE('' '',200) AS MBType2Path'
		+ ',REPLICATE('' '',200) AS MPTypePath'
		+ ',REPLICATE('' '',200) AS METypePath'
		+ ',REPLICATE('' '',200) AS MKTypePath'
		+ ',REPLICATE('' '',200) AS MDTypePath'
		+ ',2 AS Morder'
		+ ' INTO ' + N'##' + @TableName
		+ @SQLFrom
		+ @SQLWhere

Exec(@SQLText)
IF @@error <> 0
   begin
    --RAISERROR('插入临时表记录出错！',16,1)
    return -3
   end
-- 建立游标
SELECT @SQLText = 'Declare My_Cursor CURSOR For Select '
		+  ' MangerBTypeID,MangerBTypeID2,MangerPTypeID '
		+  ',MangerETypeID,MangerKTypeID,MangerDTypeID from ' + N'##' + @TableName
Exec(@SQLText)
Open My_Cursor
DECLARE @MEID	[varchar] (25)
DECLARE @MBID	[varchar] (25)
DECLARE @MBID2	[varchar] (25)
DECLARE @MPID	[varchar] (25)
DECLARE @MKID	[varchar] (25)
DECLARE @MDID	[varchar] (25)
DECLARE @NAMETEMPE	[varchar] (200)
DECLARE @NAMETEMPB	[varchar] (200)
DECLARE @NAMETEMPB2	[varchar] (200)
DECLARE @NAMETEMPP	[varchar] (200)
DECLARE @NAMETEMPK	[varchar] (200)
DECLARE @NAMETEMDK	[varchar] (200)
Fetch Next From My_Cursor Into @MBID, @MBID2, @MPID, @MEID, @MKID, @MDID

WHILE @@Fetch_status=0
Begin
	EXEC Web_GetParentPath1 @MBID, 2, @NAMETEMPB output
	EXEC Web_GetParentPath1 @MBID2, 2, @NAMETEMPB2 output	
	EXEC Web_GetParentPath1 @MEID, 3, @NAMETEMPE output
	EXEC Web_GetParentPath1 @MPID, 4, @NAMETEMPP output
	EXEC Web_GetParentPath1 @MKID, 5, @NAMETEMPK output
	EXEC Web_GetParentPath1 @MDID, 10, @NAMETEMDK output
	SELECT @SQLText = 'update ' + N'##' + @TableName + ' SET '
		+' MBTypePath='''  + @NAMETEMPB  + ''' ,'
		+' MBType2Path=''' + @NAMETEMPB2 + ''' ,'
		+' METypePath='''  + @NAMETEMPE  + ''' ,'
		+' MPTypePath='''  + @NAMETEMPP  + ''' ,'
		+' MDTypePath='''  + @NAMETEMDK  + ''' ,'
		+' MKTypePath='''  + @NAMETEMPK  + ''' 
		WHERE CURRENT OF My_Cursor'

	Exec(@SQLText)
	Fetch Next From My_Cursor Into @MBID, @MBID2, @MPID, @MEID, @MKID, @MDID
END
Close My_Cursor
Deallocate My_Cursor
-- 将超级用户放在最前
SELECT @SQLText = 'update ' + N'##' + @TableName + ' SET '
		+ 'Morder=0 WHERE [ETypeID]=''00001'''
Exec(@SQLText)
-- 返回结果
SELECT @SQLText = 'SELECT * FROM ' + N'##' + @TableName 
		+ ' ORDER BY Morder,' + @OrderBy + ''
Exec(@SQLText)
-- 删除临时表
SELECT @SQLText = 'drop table '+N'##'+@TableName

Exec(@SQLText)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_Make_WdBill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_Make_WdBill];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2017-01-17
	描述：汇总生成单据
*/
CREATE PROCEDURE Gp_Make_WdBill
    (
      @billnumberids VARCHAR(MAX) ,
      @billcode VARCHAR(200)
    )

--@encode$--
AS
    SET NOCOUNT ON;

    BEGIN
        DECLARE @Value VARCHAR(50)= 'False';
        IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'collectBill' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'collectBill';
            END;
        IF ( @Value = 'True' )
            BEGIN
                BEGIN TRANSACTION;
                DECLARE @errorSum INT;
                SET @errorSum = 0;  
                DECLARE @billdate DATETIME=  CONVERT(varchar(100),GETDATE(),8)   
                DECLARE @BillNumberId NUMERIC(18, 0),@Etypeid VARCHAR(50),@Dtypeid VARCHAR(50),@Btypid VARCHAR(50),@Ktypeid VARCHAR(50),@checke VARCHAR(50),@cid INT,
                @rate NUMERIC(22,10),@RedWord INT=0,@StypeId VARCHAR(50)='00001',@period SMALLINT,@tax NUMERIC(24,10),@ATypeID1 VARCHAR(50);
                SELECT TOP 1 @Etypeid = etypeid,@Dtypeid = DTypeId,@btypid=btypeid,@Ktypeid=ktypeid,
                @checke=checke,@cid=CID,@rate = Rate,@RedWord=RedWord,@StypeId=Stypeid,@period=period,@tax=tax,@ATypeID1=ATypeID1,@billdate =CONVERT(varchar(100),CAST(BillDate AS VARCHAR),8) FROM dbo.WdBillIndexTemp WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@billnumberids,',')) 	
                --SELECT @Dtypeid

                INSERT  INTO BillIndex
                        ( BillDate ,	--录单日期
                          BillCode ,	--单据编号
                          BillType ,	--单据类型
                          Comment ,		--摘要
                          atypeid ,		--收款项目ID 现金（1）
                          ATypeID1 ,		--往来科目
                          ptypeid ,		--商品ID
                          btypeid ,		--结算单位
                          DealBTypeID ,  --往来单位
                          etypeid ,		--职员ID
                          ktypeid ,		--仓库ID
                          ifcheck ,		--是否过账 f：未过账,t：过账
                          checke ,		--制单人
                          CID ,
                          Rate ,
                          totalmoney ,	--总金额
                          totalinmoney ,	--收款金额
                          NTotalMoney ,	--总金额
                          NTotalInMoney ,	--收款金额
                          totalqty ,	--数量
                          RedWord ,		--红冲 0
                          draft ,		--草稿标志 1
                          DTypeId ,		--经手人部门
                          Stypeid ,		--分支机构()
                          checkTime ,	--制单时间
                          explain ,		--说明
                          period ,
                          Audit_explain ,	--用于存储VchCode
                          tax ,
                          Assessor ,
                          waybillcode ,    --运单号
                          TEL ,              --承运单位
                          NPreferenceMoney ,   --优惠金额
                          preferencemoney,
                          BillTime    
	                    )
                        SELECT  CONVERT(varchar(100),BillDate, 23) ,
                                @billcode AS billcode ,
                                11 ,
                                '网店订单汇总生成' ,
                                '' ,
                                @ATypeID1 ,
                                '' ,
                                @btypid ,
                                @btypid ,
                                @Etypeid ,
                                @Ktypeid ,
                                'f' ifcheck ,
                                @checke ,
                                @CID ,
                                @Rate ,
                                dbo.F_RoundTotal(SUM(totalmoney)),
                                dbo.F_RoundTotal(SUM(totalinmoney)),
                                dbo.F_RoundTotal(SUM(NTotalMoney)),
                                dbo.F_RoundTotal(SUM(NTotalInMoney)),
                                dbo.F_RoundQty(SUM(totalqty)),
                                @RedWord ,
                                1 draft ,
                                @Dtypeid ,  
                                @Stypeid ,
								CONVERT(VARCHAR(100), GETDATE(), 25),
                                '汇总生成单据' ,
                                @period ,
                                '' Audit_explain ,
                                @tax ,
                                'wdshop' AS Assessor ,
                                '' waybillcode ,
                                '' TEL ,
                                dbo.F_RoundTotal(SUM(NPreferenceMoney)) ,
                                dbo.F_RoundTotal(SUM(NPreferenceMoney)) ,
                                CONVERT(varchar(100),GETDATE(),8)                          
                        FROM    dbo.WdBillIndexTemp
                        WHERE   BillNumberId IN ( SELECT * FROM dbo.f_split(@billnumberids,',') )
                        GROUP BY BillDate;
                        
                SET @errorSum = @errorSum + @@error;						   
                SELECT  @BillNumberId = SCOPE_IDENTITY();																----获取生成的id
                SET @errorSum = @errorSum + @@error;
                EXEC GP_SaveBillCode_Seed @BillNumberId,@BillDate,11,@BillCode						----更新编号种子数
                SET @errorSum = @errorSum + @@error;	
                EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate, 11,@BillCode;						----更新编号种子数
                SET @errorSum = @errorSum + @@error;
                --COMMIT TRANSACTION;
               
                --UPDATE  dbo.BillMulAccount
                --SET     BillNumberId = @BillNumberId
                --WHERE   BillNumberId IN (SELECT * FROM dbo.f_split(@billnumberids,','));
                --SET @errorSum = @errorSum + @@error;		
                
                INSERT INTO dbo.BillMulAccount
                        ( BillNumberId ,
                          ATypeID ,
                          Total ,
                          Comment ,
                          VipCardID ,
                          NTotalMoney ,
                          paymoney,
                          BillType
                        )
                SELECT @BillNumberId,ATypeID,SUM(Total),'【网店销售出库单】商品收款',-1,SUM(NTotalMoney),SUM(paymoney),11 FROM dbo.WdBillMulAccountTemp WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@billnumberids,',')) 
                GROUP BY ATypeID;
                SET @errorSum = @errorSum + @@error;	
                
                DELETE FROM dbo.WdBillMulAccountTemp WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@billnumberids,',')) 
                SET @errorSum = @errorSum + @@error;	
                
                INSERT  INTO SaleBill
                        ( BillNumberId ,	--从表头获取
                          OutFactoryDate ,	--单据日期  
                          Stypeid ,			--分支机构
                          KTypeID ,			--仓库ID
                          CargoID ,			--货位
					  --序列号Serial
					  --批次GoodsOrder
					  --成本单价costprice
                          PtypeId ,			--商品ID
                          entryCode ,		--条形码
                          Qty ,				--基本数量
                          SalePrice ,		--基本单价
                          UnitID ,		--基本单位
                          MQty ,             --销售数量
                          MSalePrice ,		--销售单价
                          MUnitID ,		--销售单位
                          MUnitRate ,		--销售换算率
                          NQty ,			--浮动数量
                          NUnitID ,		--浮动单位
                          UnitRate ,		--浮动换算率
                          discount ,			--折扣率
                          Tax ,			--税率
                          TaxMoney ,			--税额
                          DiscountPrice ,	--折后单价，按基本单价算折后
                          MDiscountPrice ,	--折后单价，按销售单价算折后
                          TaxPrice ,			--含税价，按基本单价算
                          MTaxPrice ,		--含税价，按销售单价算
                          SaleTotal ,		--总金额
                          total ,			--折后总金额
                          TaxTotal ,			--价税合计
                          NSalePrice ,       --原币基本单价
                          CurMSalePrice ,	--原币销售单价
                          NTaxMoney ,		--原币税额
                          NDiscountPrice ,	--原币折后单价
                          CurMDiscountPrice ,--原币折后单价
                          NTaxPrice ,        --原币含税价
                          CurMTaxPrice ,		--原币含税价
                          NSaleTotal ,
                          NTotal ,
                          NTaxTotal ,
                          comment ,
                          IsCombined ,
                          ItemID ,
                          PriceSource ,
                          ETypeID ,        --业务员ID
                          IsGift ,          --赠品项
                          NUnitMsg ,
                          MUnitMsg ,
                          ClearQty ,
                          GoodsNumber,--批号
                          GoodsCostPrice,--商品成本价
                          ProduceDate,--生产日期
                          ValidDate,--效期至
                          Serial --序列号
					    )
                        SELECT  @BillNumberId AS BillNumberId ,
                                OutFactoryDate ,
                                Stypeid ,
                                KTypeID ,
                                CargoID ,
                                PtypeId ,
                                entryCode ,
                                dbo.F_RoundQty(SUM(Qty)),
                                SalePrice ,
                                UnitID ,
                                dbo.F_RoundQty(SUM(MQty)),
                                MSalePrice,
                                MUnitID ,
                                MUnitRate ,
                                dbo.F_RoundQty(SUM(NQty)),
                                NUnitID ,
                                UnitRate ,
                                discount,
                                Tax,
                                TaxMoney,
                                DiscountPrice,
                                MDiscountPrice,
                                TaxPrice,
                                MTaxPrice,
                                dbo.F_RoundTotal(SUM(SaleTotal)),
                                dbo.F_RoundTotal(SUM(total)),
                                dbo.F_RoundTotal(SUM(TaxTotal)),
                                NSalePrice,
                                CurMSalePrice,
                                dbo.F_RoundTotal(SUM(NTaxMoney)) ,
                                NDiscountPrice ,
                                CurMDiscountPrice ,
                                NTaxPrice,
                                CurMTaxPrice,
                                dbo.F_RoundTotal(SUM(NSaleTotal)) ,
                                dbo.F_RoundTotal(SUM(NTotal)) ,
                                dbo.F_RoundTotal(SUM(NTaxTotal)),
                                '汇总生成单据' AS comment ,
                                isCombined ,
                                ItemID ,
                                PriceSource ,
                                @Etypeid ,
                                IsGift ,
                                '' AS NUnitMsg ,
                                '' AS MUnitMsg ,
                                dbo.F_RoundQty(SUM(ClearQty)),
                                GoodsNumber,--批号
                                GoodsCostPrice,--商品成本价
                                ProduceDate,--生产日期
                                ValidDate,--效期至
                                STUFF((SELECT LEFT(serial,LEN(serial)-1) FROM dbo.WdSaleBillTemp w 
                                WHERE Serial<>'' AND  Serial IS NOT NULL AND w.KTypeID=wt.KTypeID
                                AND W.PtypeId = WT.PtypeId AND W.ItemID=WT.ItemID AND W.SalePrice=WT.SalePrice
                                AND W.CargoID = WT.CargoID AND W.Stypeid=WT.Stypeid AND W.entryCode = WT.entryCode
                                AND W.UnitID=WT.UnitID AND W.MSalePrice=WT.MSalePrice AND W.MUnitID=WT.MUnitID
                                AND W.MUnitRate=WT.MUnitRate AND W.UnitRate = WT.UnitRate AND W.discount = WT.discount
                                AND W.Tax = WT.Tax AND W.TaxMoney=wt.TaxMoney AND W.TaxMoney=WT.TaxMoney AND 
                                WT.DiscountPrice=W.DiscountPrice AND WT.TaxPrice=W.TaxPrice AND WT.MTaxPrice=W.MTaxPrice AND
                                WT.MSalePrice=W.MSalePrice AND WT.CurMSalePrice=W.CurMSalePrice AND WT.NDiscountPrice=W.NDiscountPrice
                                AND WT.CurMDiscountPrice=W.CurMDiscountPrice AND WT.IsGift = W.IsGift AND WT.NUnitID=W.NUnitID AND
                                WT.UnitRate =W.UnitRate AND WT.MDiscountPrice=W.MDiscountPrice AND WT.NSalePrice=W.NSalePrice AND
                                WT.CurMTaxPrice=W.CurMTaxPrice AND WT.NTaxPrice = W.NTaxPrice AND WT.IsCombined=W.IsCombined AND 
                                WT.OutFactoryDate = W.OutFactoryDate AND W.GoodsNumber =WT.GoodsNumber AND WT.GoodsCostPrice=W.GoodsCostPrice
								AND WT.ProduceDate = W.ProduceDate AND WT.ValidDate = w.ValidDate AND  BillNumberId IN ( SELECT * FROM dbo.f_split(@billnumberids,',') ) 
                                FOR XML PATH('')),1,0,'')
                        FROM    dbo.WdSaleBillTemp wt
                        WHERE   BillNumberId IN ( SELECT * FROM dbo.f_split(@billnumberids,',') ) 
                        GROUP BY KTypeID ,
                                PtypeId ,
                                ItemID ,
                                SalePrice ,
                                CargoID ,
                                Stypeid ,
                                entryCode ,
                                UnitID ,
                                MSalePrice ,
                                MUnitID ,
                                MUnitRate ,
                                UnitRate ,
                                discount ,
                                Tax ,
                                TaxMoney ,
                                DiscountPrice ,
                                TaxPrice ,
                                MTaxPrice ,
                                MSalePrice ,
                                CurMSalePrice ,
                                NDiscountPrice ,
                                CurMDiscountPrice ,
                                IsGift ,
                                NUnitID ,
                                UnitRate ,
                                MDiscountPrice,
                                NSalePrice,
                                CurMTaxPrice,
                                NTaxPrice,
                                IsCombined,
                                OutFactoryDate,
                                GoodsNumber,--批号
								GoodsCostPrice,--商品成本价
								ProduceDate,--生产日期
								ValidDate,--效期至
								PriceSource;
                SET @errorSum = @errorSum + @@error;	
					            --SELECT * FROM dbo.WdShopBillRelation
					            
                --UPDATE  dbo.WdShopBillRelation
                --SET     Billnumberid = @BillNumberId
                --WHERE   Billnumberid IN ( SELECT * FROM dbo.f_split(@billnumberids,',') );
                INSERT INTO dbo.WdShopBillRelation
                        ( WdShopBillID ,
                          Billnumberid ,
                          Flag ,
                          WdSyncFlag
                        )
				SELECT WdShopBillID,@BillNumberId,flag,WdSyncFlag FROM dbo.WdShopBillRelationTemp WHERE   Billnumberid IN ( SELECT * FROM dbo.f_split(@billnumberids,',') );
                SET @errorSum = @errorSum + @@error;	
                
                DELETE FROM  dbo.WdShopBillRelationTemp WHERE Billnumberid IN ( SELECT * FROM dbo.f_split(@billnumberids,',') );
                
                --DELETE FROM dbo.BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@billnumberids,','))
                --SET @errorSum = @errorSum + @@ERROR
                
                --DELETE FROM dbo.SaleBill WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@billnumberids,','))
                --SET @errorSum = @errorSum + @@ERROR               
					            
                IF ( @errorSum <> 0 )
                    BEGIN
                    --SELECT 'shibai'
                        ROLLBACK TRANSACTION;
                        RETURN -1 
                    END; 
                ELSE
                    BEGIN
                    --SELECT 'chengg'
                        COMMIT TRANSACTION;
                        RETURN @BillNumberId
                    END; 
            END;


    END;
    SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_MakeSerialDetail]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_MakeSerialDetail];
GO

/*
	作者:颜熙
	日期:2017-08-25
	描述:不满足商品货位的序列号重新生成明细
*/
CREATE  PROCEDURE Gp_MakeSerialDetail
( 
	  @BillDate DATETIME ,			---单据日期
      @BillType NUMERIC(4, 0) ,		---单据类型  
      @BillNumberId NUMERIC(10, 0) ,		---单据ID
      @PtypeId VARCHAR(50) = '' ,		---商品ID     
      @Qty NUMERIC(24, 10) = 0 ,	---数量 
      @KTypeId VARCHAR(50) = '00001' ,---仓库ID 
      @ETypeId VARCHAR(200) = '' ,	---业务员ID   
      @Total NUMERIC(24, 10) = 0 ,	---总价/实付金额
      @Price NUMERIC(24, 10) = 0 ,	---单价
      @FreightFee NUMERIC(24, 10) = 0 ,	---运费
      @Cargo VARCHAR(MAX) ,		---货位
      @ItemID INT ,				---自由项
      @Comment VARCHAR(100) = '' ,	---摘要     
      @EshopId VARCHAR(200) ,		---网店id
      @feeatypeid VARCHAR(100) ,    --费用项
      @Flag INT ,
      @IsGift BIT ,        --赠品项
      @Stypeid VARCHAR(50) = '00001' ,--分支机构
      @CargoID VARCHAR(100) = '' , --货位id
      @Itemqty VARCHAR(100) = '' , --每个货位对应数量字符串  
      @id INT         ,--每条明细对应的id
	  @entrycode VARCHAR(100),		--条形码
	  @UnitID INT,			--基本单位
	  @MQty NUMERIC(24, 10) = 0 ,			--销售数量
	  @MSale NUMERIC(24, 10) ,       --销售单价
	  @MUnitID INT,			--销售单位
	  @Mrate NUMERIC(24, 10) ,			--销售换算率
	  @NUnitID int,			--浮动单位
	  @Nrate NUMERIC(24, 10) ,			--浮动换算率@Nrate
	  @iscombined bit, 
	  @serial VARCHAR(MAX),                               
      @GoodsNumber VARCHAR(100)='',--批号
	  @ProduceDate VARCHAR(50)='',--生产日期
	  @ValidDate VARCHAR(50)='',--效期至
	  @GoodsCostPrice NUMERIC(24,10)=0,--商品成本价
	  @batchNumberDeal INT, --批次处理
	  @batchQty NUMERIC(24,10), --批次里的数量
	  @CollectBill BIT, --是否汇总生成
	  @PriceSource VARCHAR(200)='网店生成' --价格来源

)
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
		SET @serial = ISNULL(@serial,'')
		--启用序列号关联货位时使用的序列号表，记录与商品所在货位不符的序列号
		CREATE TABLE #serialRelation
		(
			serial	VARCHAR(50),
			cargoid VARCHAR(100),
			id		INT IDENTITY(1,1)
		)
		
	    CREATE TABLE #serial
		(
			serial	VARCHAR(50),
			id		INT IDENTITY(1,1)
		)
		DECLARE @rowN INT =1,@rowCount INT	,@itemIDN INT ,@IsCombinedN INT 
		 
    	TRUNCATE TABLE #serialRelation
		INSERT INTO #serialRelation(serial,cargoid)
		SELECT serial,whstpt_erpid FROM dbo.WdSerialsDetail WHERE ordercode = SUBSTRING(@Comment,6,17) AND mid = @id AND serialRelationId = 99999
		SELECT @rowN = 1
		SELECT @rowCount = COUNT(*) FROM #serialRelation 
		WHILE @rowN<=@rowCount
		BEGIN
			SELECT @serial = serial,@CargoID = cargoid FROM #serialRelation WHERE id = @rowN
			SELECT @Qty =COUNT(*) FROM dbo.f_split(left(@serial,len(@serial)-1),'я') WHERE a<>''
			
			INSERT INTO #serial(serial)
			SELECT a FROM dbo.f_split(@serial,'я')
			
			
			SELECT @itemIDN = ItemID ,@IsCombinedN = IsCombined FROM dbo.gp_CruPtypeSerial WHERE Serial = (SELECT serial FROM #serial WHERE id =2)
			IF(@ItemID<>0 OR @iscombined<>0)
			BEGIN
				SELECT @ItemID = @itemIDN,@IsCombined = @IsCombinedN
			END 			
			
			SELECT  @GoodsNumber = ISNULL(GoodsNumber,0),
					@ProduceDate = ISNULL(ProduceDate,''),
					@ValidDate = ISNULL(ValidDate,''),
					@GoodsCostPrice = ISNULL(CostPrice,0)
			FROM    gp_CruPtypeSerial
			WHERE   Serial = (SELECT serial FROM #serial WHERE id =2)
					AND PtypeID = @PtypeId
					AND ItemID = @ItemID;
			
			SELECT  @batchQty = Qty  FROM dbo.GOODSSTOCKS_QTY WHERE GoodsNumber = @GoodsNumber AND PTypeID = @PtypeId AND CargoID=@CargoID AND @ProduceDate = @ProduceDate AND GoodsCostPrice = @GoodsCostPrice
			
			SELECT @Total =dbo.F_RoundTotal(@Qty*@Price)
			SET @MQty = @Qty / @Mrate;SET @MSale = @Price * @Mrate;
			SELECT @KTypeId = KtypeID FROM dbo.CargoType WHERE CargoID = @CargoID
			IF(@CollectBill=1 AND @BillType = 11)
				BEGIN 
					INSERT  INTO WdSaleBillTemp
						( BillNumberId ,	--从表头获取
						  OutFactoryDate ,	--单据日期  
						  Stypeid ,			--分支机构
						  KTypeID ,			--仓库ID
						  CargoID ,			--货位
				  --序列号Serial
				  --GoodsOrder,--批次
				  --成本单价costprice
						  PtypeId ,			--商品ID
						  entryCode ,		--条形码
						  Qty ,				--基本数量
						  SalePrice ,		--基本单价
						  UnitID ,		--基本单位
						  MQty ,             --销售数量
						  MSalePrice ,		--销售单价
						  MUnitID ,		--销售单位
						  MUnitRate ,		--销售换算率
						  NQty ,			--浮动数量
						  NUnitID ,		--浮动单位
						  UnitRate ,		--浮动换算率
						  discount ,			--折扣率
						  Tax ,			--税率
						  TaxMoney ,			--税额
						  DiscountPrice ,	--折后单价，按基本单价算折后
						  MDiscountPrice ,	--折后单价，按销售单价算折后
						  TaxPrice ,			--含税价，按基本单价算
						  MTaxPrice ,		--含税价，按销售单价算
						  SaleTotal ,		--总金额
						  total ,			--折后总金额
						  TaxTotal ,			--价税合计
						  NSalePrice ,       --原币基本单价
						  CurMSalePrice ,	--原币销售单价
						  NTaxMoney ,		--原币税额
						  NDiscountPrice ,	--原币折后单价
						  CurMDiscountPrice ,--原币折后单价
						  NTaxPrice ,        --原币含税价
						  CurMTaxPrice ,		--原币含税价
						  NSaleTotal ,
						  NTotal ,
						  NTaxTotal ,
						  comment ,
						  IsCombined ,
						  ItemID ,
						  PriceSource ,
						  ETypeID ,        --业务员ID
						  IsGift ,          --赠品项
						  NUnitMsg ,
						  MUnitMsg ,
						  ClearQty ,
						  GoodsNumber,--批号
						  GoodsCostPrice,--商品成本价
						  ProduceDate,--生产日期
						  ValidDate,--效期至
						  Serial,
						  mid ,
						  nid 
						)
				VALUES  ( @BillNumberId ,
						  @BillDate ,        --单据日期
						  @Stypeid ,         --分支机构
						  @KTypeId ,			--仓库
						  @CargoID ,			--货位
						  @PtypeId ,			--商品
						  @entrycode ,		--条形码
						  @Qty ,             --基本数量
						  @Price ,           --基本单价
						  @UnitID ,			--基本单位
						  @MQty ,			--销售数量
						  @MSale ,           --销售单价
						  @MUnitID ,			--销售单位
						  @Mrate ,			--销售换算率
						  ISNULL(dbo.F_RoundQty(@Qty/@Nrate),0),--浮动数量
						  ISNULL(@NUnitID,0),			--浮动单位
						  ISNULL(@Nrate,0) ,			--浮动换算率@Nrate
						  1 ,				--折扣率
						  0 ,				--税率
						  0 ,				--税额
						  @Price ,			--折后单价，按基本单价算
						  @MSale ,			--折后单价，按销售单价算
						  @Price ,			--含税价，按基本单价算
						  @MSale ,			--含税价，按销售单价算
						  @Total ,			--总金额
						  @Total ,			--折后总金额
						  @Total ,			--含税总金额
						  @Price ,			--原币基本单价
						  @MSale ,			--原币销售单价
						  0 ,				--原币税额
						  @Price ,			--原币折后单价，按基本单价算折后
						  @MSale ,			--原币折后单价，按销售单价算折后
						  @Price ,			--原币含税价，按基本单价算
						  @MSale ,			--原币含税价，按销售单价算
						  @Total ,			--原币总金额
						  @Total ,			--原币折后总金额
						  @Total ,			--原币含税总金额
						  @Comment ,
						  @iscombined ,
						  @ItemID ,
						  @PriceSource ,
						  @ETypeId ,
						  @IsGift ,
						  '' ,
						  '' ,
						  0 ,
						  @GoodsNumber,
						  @GoodsCostPrice,
						  @ProduceDate,
						  @ValidDate,   
						  @serial,                               
						  @id ,
						  0
						);
				END 
			ELSE IF (@CollectBill = 0 AND @BillType = 11)
			BEGIN
				INSERT  INTO SaleBill
					( BillNumberId ,	--从表头获取
					  OutFactoryDate ,	--单据日期  
					  Stypeid ,			--分支机构
					  KTypeID ,			--仓库ID
					  CargoID ,			--货位
			  --序列号Serial
			  --GoodsOrder,--批次
			  --成本单价costprice
					  PtypeId ,			--商品ID
					  entryCode ,		--条形码
					  Qty ,				--基本数量
					  SalePrice ,		--基本单价
					  UnitID ,		--基本单位
					  MQty ,             --销售数量
					  MSalePrice ,		--销售单价
					  MUnitID ,		--销售单位
					  MUnitRate ,		--销售换算率
					  NQty ,			--浮动数量
					  NUnitID ,		--浮动单位
					  UnitRate ,		--浮动换算率
					  discount ,			--折扣率
					  Tax ,			--税率
					  TaxMoney ,			--税额
					  DiscountPrice ,	--折后单价，按基本单价算折后
					  MDiscountPrice ,	--折后单价，按销售单价算折后
					  TaxPrice ,			--含税价，按基本单价算
					  MTaxPrice ,		--含税价，按销售单价算
					  SaleTotal ,		--总金额
					  total ,			--折后总金额
					  TaxTotal ,			--价税合计
					  NSalePrice ,       --原币基本单价
					  CurMSalePrice ,	--原币销售单价
					  NTaxMoney ,		--原币税额
					  NDiscountPrice ,	--原币折后单价
					  CurMDiscountPrice ,--原币折后单价
					  NTaxPrice ,        --原币含税价
					  CurMTaxPrice ,		--原币含税价
					  NSaleTotal ,
					  NTotal ,
					  NTaxTotal ,
					  comment ,
					  IsCombined ,
					  ItemID ,
					  PriceSource ,
					  ETypeID ,        --业务员ID
					  IsGift ,          --赠品项
					  NUnitMsg ,
					  MUnitMsg ,
					  ClearQty ,
					  GoodsNumber,--批号
					  GoodsCostPrice,--商品成本价
					  ProduceDate,--生产日期
					  ValidDate,--效期至
					  Serial,
					  mid ,
					  nid 
					)
			VALUES  ( @BillNumberId ,
					  @BillDate ,        --单据日期
					  @Stypeid ,         --分支机构
					  @KTypeId ,			--仓库
					  @CargoID ,			--货位
					  @PtypeId ,			--商品
					  @entrycode ,		--条形码
					  @Qty ,             --基本数量
					  @Price ,           --基本单价
					  @UnitID ,			--基本单位
					  @MQty ,			--销售数量
					  @MSale ,           --销售单价
					  @MUnitID ,			--销售单位
					  @Mrate ,			--销售换算率
					  ISNULL(dbo.F_RoundQty(@Qty/@Nrate),0),--浮动数量
					  ISNULL(@NUnitID,0) ,			--浮动单位
					  ISNULL(@Nrate,0),			--浮动换算率@Nrate
					  1 ,				--折扣率
					  0 ,				--税率
					  0 ,				--税额
					  @Price ,			--折后单价，按基本单价算
					  @MSale ,			--折后单价，按销售单价算
					  @Price ,			--含税价，按基本单价算
					  @MSale ,			--含税价，按销售单价算
					  @Total ,			--总金额
					  @Total ,			--折后总金额
					  @Total ,			--含税总金额
					  @Price ,			--原币基本单价
					  @MSale ,			--原币销售单价
					  0 ,				--原币税额
					  @Price ,			--原币折后单价，按基本单价算折后
					  @MSale ,			--原币折后单价，按销售单价算折后
					  @Price ,			--原币含税价，按基本单价算
					  @MSale ,			--原币含税价，按销售单价算
					  @Total ,			--原币总金额
					  @Total ,			--原币折后总金额
					  @Total ,			--原币含税总金额
					  @Comment ,
					  @iscombined ,
					  @ItemID ,
					  @PriceSource ,
					  @ETypeId ,
					  @IsGift ,
					  '' ,
					  '' ,
					  0 ,
					  @GoodsNumber,
					  @GoodsCostPrice,
					  @ProduceDate,
					  @ValidDate,   
					  @serial,                               
					  @id ,
					  0
					);
			END 
			ELSE
			BEGIN
				 INSERT  INTO saleBackBill
                        ( BillNumberId ,
                          OutFactoryDate ,	--date
                          Stypeid ,			--分支机构
                          KTypeID ,			--仓库ID
                          CargoID ,
                          PtypeId ,
                          Qty ,				--基本数量
                          SalePrice ,		--基本单价
                          UnitID ,		--基本单位
                          MQty ,             --销售数量
                          MSalePrice ,		--销售单价
                          MUnitID ,		--销售单位
                          MUnitRate ,		--销售换算率
                          NQty ,			--浮动数量
                          NUnitID ,		--浮动单位
                          UnitRate ,		--浮动换算率
                          discount ,			--折扣率
                          Tax ,			--税率
                          TaxMoney ,			--税额
                          DiscountPrice ,	--折后单价，按基本单价算折后
                          MDiscountPrice ,	--折后单价，按销售单价算折后
                          TaxPrice ,			--含税价，按基本单价算
                          MTaxPrice ,		--含税价，按销售单价算
                          SaleTotal ,		--总金额
                          total ,			--折后总金额
                          TaxTotal ,			--价税合计
                          NSalePrice ,       --原币基本单价
                          CurMSalePrice ,	--原币销售单价
                          NTaxMoney ,		--原币税额
                          NDiscountPrice ,	--原币折后单价
                          CurMDiscountPrice ,--原币折后单价
                          NTaxPrice ,        --原币含税价
                          CurMTaxPrice ,		--原币含税价
                          NSaleTotal ,
                          NTotal ,
                          NTaxTotal ,
                          IsCombined ,
                          ItemID ,
                          ETypeID ,       --业务员ID
                          GoodsNumber,
                          GoodsCostPrice,
                          ProduceDate,
                          mid,
                          comment ,
                          Serial
		                )
                VALUES  ( @BillNumberId ,
                          @BillDate ,
                          @Stypeid ,         --分支机构
                          @KTypeId ,			--仓库
                          @CargoID ,			--货位
                          @PtypeId ,			--商品
                          @Qty ,             --基本数量
                          @Price ,           --基本单价
                          @UnitID ,			--基本单位
                          @MQty ,			--销售数量
                          @MSale ,           --销售单价
                          @MUnitID ,			--销售单位
                          @Mrate ,			--销售换算率
                          ISNULL(dbo.F_RoundQty(@Qty/@Nrate),0),				--浮动数量
                          ISNULL(@NUnitID,0),			--浮动单位
					      ISNULL(@Nrate,0),			--浮动换算率@Nrate
                          1 ,				--折扣率
                          0 ,				--税率
                          0 ,				--税额
                          @Price ,			--折后单价，按基本单价算
                          @MSale ,			--折后单价，按销售单价算
                          @Price ,			--含税价，按基本单价算
                          @MSale ,			--含税价，按销售单价算
                          @Total ,			--总金额
                          @Total ,			--折后总金额
                          @Total ,			--含税总金额
                          @Price ,			--原币基本单价
                          @MSale ,			--原币销售单价
                          0 ,				--原币税额
                          @Price ,			--原币折后单价，按基本单价算折后
                          @MSale ,			--原币折后单价，按销售单价算折后
                          @Price ,			--原币含税价，按基本单价算
                          @MSale ,			--原币含税价，按销售单价算
                          @Total ,			--原币总金额
                          @Total ,			--原币折后总金额
                          @Total ,			--原币含税总金额
                          @iscombined ,
                          @ItemID ,
                          @ETypeId ,
                          @GoodsNumber,
                          @GoodsCostPrice,
                          '',
                          @id,
                          @Comment,
                          @serial
                        );	
			END 
			SELECT @rowN=@rowN+1
		END 
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_MarkErrorAcVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_MarkErrorAcVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查询标错
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_MarkErrorAcVoucherBill
(
	@BillNumberId	VARCHAR(50)='',			-- 单据ID
	@MarkError		VARCHAR(200)			--标错原因
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE
	@STypeID		VARCHAR(50)='',--当前分支机构 
	@fchecked		VARCHAR(2)='',
	@recheckid		VARCHAR(2)='',
	@ifcheck		VARCHAR(2)='',
	@vouchertype	VARCHAR(2)='',
	@ErrorCount		INT=0--审核 复核 过账 凭证类型
	
SELECT
	@STypeID=STypeId,
	@fchecked=ISNULL(FChecked,''),
	@recheckid=ISNULL(ReCheckId,''),
	@ifcheck=ISNULL(IfCheck,'')
FROM Ac_Voucher
WHERE BillNumberId=@BillNumberId
		 
IF @@ROWCOUNT = 0--判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN
END
CREATE TABLE #TB(nowFPeriod INT)
INSERT INTO #TB(nowFPeriod)
SELECT bill.period
FROM Ac_GoodsBill_VoucherBill ac
INNER JOIN BillIndex bill ON bill.BillNumberId=ac.GoodsBillId
WHERE 
	AC.VourchBillId=@billnumberid AND
	bill.BillDate<(SELECT StartDate FROM MonthProc WHERE STypeID=@STypeID AND MonthNo='本期')
IF((SELECT COUNT(*) FROM #TB)>0 AND @vouchertype=3)
	BEGIN
		RAISERROR('您选择的凭证业务数据在业务系统已经月结!请确认后重试！',16,1)
		RETURN
	END
	
IF(@fchecked='1' OR @fchecked='-1' OR @recheckid <>'' OR @ifcheck='t')
	BEGIN
		RAISERROR('您选择的凭证已审核/作废/复核/记账！请确认后重试！',16,1)
		RETURN
	END
	
UPDATE Ac_Voucher SET MarkError=@MarkError WHERE BillNumberId=@BillNumberID--标错 凭证主表
IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='标错凭证单据错误，请确认！'
		RAISERROR(@MSG2,16,1)
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
--
--				全面修改单据、红冲记录单据类似
--
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_Modify_Bill_Log',N'P'))
BEGIN
	DROP PROC GP_Modify_Bill_Log
END
GO
CREATE PROC GP_Modify_Bill_Log
(
	@BillNumberID	INT,
	@BillType		INT
)
AS
BEGIN
	IF @BillType NOT IN(4,6,11,34,45,66,189,190,400,401,402,403,404,405,12,46)
	RETURN 0 
	
	DECLARE @ModifyCount INT	--修改次数
	--采购暂估开票/销售发货开票
	IF @BillType IN (404,405)
	BEGIN
		--取修改次数
		SELECT @ModifyCount=ISNULL(MAX(ModifyCount),0)+1 FROM ModifyLog_ReceiptBillIndex WHERE billNumberID=@BillNumberID AND BillType=@BillTYpe
		
		INSERT INTO dbo.ModifyLog_ReceiptBillIndex
				( 
				  BillDate ,BillCode ,BillType ,FaPiaoType ,FaPiaoCode ,
		          Comment ,Explain ,BTypeID ,ETypeID ,DTypeID ,checke ,Assessor ,Tax ,TotalQty ,TotalMoney ,
		          TaxTotalMoney ,Stypeid ,OtherTotal ,ifYearBill ,IsIni ,CID ,Rate ,NTotalMoney , NTaxTotalMoney ,
		          DealBTypeID ,TaskType ,AlertDay ,RedWord ,ifcheck ,IfStopMoney ,CompleteTotal ,NCompleteTotal ,
		          Draft ,JSState ,JSStyle , Poster ,LastUpdateTime ,checkTime , Posttime ,UpdateE ,IfAudit ,
		          ATypeID1 ,ATypeID2 , Period , RedReason , ATID ,Reconciliation , TeamNo ,TallyId ,
		          ChargeOffTotal ,NChargeOffTotal,BillNumberID,ModifyCount
		        )
		SELECT	  BillDate ,BillCode ,BillType ,FaPiaoType ,FaPiaoCode ,
		          Comment ,Explain ,BTypeID ,ETypeID ,DTypeID ,checke ,Assessor ,Tax ,TotalQty ,TotalMoney ,
		          TaxTotalMoney ,Stypeid ,OtherTotal ,ifYearBill ,IsIni ,CID ,Rate ,NTotalMoney , NTaxTotalMoney ,
		          DealBTypeID ,TaskType ,AlertDay ,RedWord ,ifcheck ,IfStopMoney ,CompleteTotal ,NCompleteTotal ,
		          Draft ,JSState ,JSStyle , Poster ,LastUpdateTime ,checkTime , Posttime ,UpdateE ,IfAudit ,
		          ATypeID1 ,ATypeID2 , Period , RedReason , ATID ,Reconciliation , TeamNo ,TallyId ,
		          ChargeOffTotal ,NChargeOffTotal,BillNumberID,@ModifyCount
		FROM dbo.ReceiptBillIndex WHERE BillNumberID=@BillNumberID AND BillType=@BillType
		
		INSERT INTO	dbo.ModifyLog_ReceiptBill
		        ( 
				  BillNumberID ,BillType ,MainBillNumberID , KTypeID , PTypeID ,Qty , Price ,
		          Total , Tax ,TaxPrice , TaxTotal ,Comment ,Stypeid ,discount , BeforePrice ,
		          BeforeTotal ,RecordedItemId ,Nprice ,NTotal ,NTaxPrice , NTaxTotal , NTaxMoney ,
		          CargoID ,UnitID , NUnitID ,NQty , UnitRate , NUnitMsg , MUnitID , MQty , MUnitRate ,
		          MUnitMsg , MPrice ,MTaxPrice ,CurMPrice , CurMTaxPrice , ItemID ,IsCombined ,
		          Nbeforeprice , NBeforeTotal , goodsnumber ,saleprice , saletotal , nsaleprice ,
		          nsaletotal ,curmsaleprice ,curmsaletotal , taxmoney , CompleteQty , CompleteTotal ,
		          NCompleteTotal , IsGift , TeamNo , TeamNO1 , InvoiceCostTotal , MainBillType , InvoiceCostPrice ,
		          ProduceDate ,ValidDate ,Serial , ShowOrder,ID,ModifyCount
		        )
		SELECT	  BillNumberID ,BillType ,MainBillNumberID , KTypeID , PTypeID ,Qty , Price ,
		          Total , Tax ,TaxPrice , TaxTotal ,Comment ,Stypeid ,discount , BeforePrice ,
		          BeforeTotal ,RecordedItemId ,Nprice ,NTotal ,NTaxPrice , NTaxTotal , NTaxMoney ,
		          CargoID ,UnitID , NUnitID ,NQty , UnitRate , NUnitMsg , MUnitID , MQty , MUnitRate ,
		          MUnitMsg , MPrice ,MTaxPrice ,CurMPrice , CurMTaxPrice , ItemID ,IsCombined ,
		          Nbeforeprice , NBeforeTotal , goodsnumber ,saleprice , saletotal , nsaleprice ,
		          nsaletotal ,curmsaleprice ,curmsaletotal , taxmoney , CompleteQty , CompleteTotal ,
		          NCompleteTotal , IsGift , TeamNo , TeamNO1 , InvoiceCostTotal , MainBillType , InvoiceCostPrice ,
		          ProduceDate ,ValidDate ,Serial , ShowOrder,ID,@ModifyCount
		FROM dbo.ReceiptBill WHERE BillNumberID=@BillNumberID AND BillType=@BillType
	END
	ELSE
	BEGIN
		--取修改次数
		SELECT @ModifyCount=ISNULL(MAX(ModifyCount),0)+1 FROM ModifyLog_BillIndex WHERE billNumberID=@BillNumberID AND BillType=@BillTYpe
		
		INSERT INTO dbo.ModifyLog_BillIndex
				( 
				  BillDate , BillCode , BillType ,Comment ,atypeid , ptypeid , btypeid ,
				  etypeid ,ktypeid ,ktypeid2 ,ifcheck ,checke ,totalmoney ,totalinmoney ,
				  totalqty ,tax , period ,explain , RedWord ,draft ,OrderId , waybillcode ,
				  goodsnumber , packway , TEL ,Uploaded , OFF_ID ,TeamNo ,AlertDay ,CompleteTotal ,
				  ID , Assessor ,IfAudit , Audit_explain ,IfStopMoney ,preferencemoney , DTypeId ,
				  JF ,VipCardID ,vipCZMoney ,jsStyle ,jsState , KTypeID3 , LinkMan , LinkTel ,
				  LinkAddr ,wxManID ,JieJianBillNumberID , JieJianID ,JieJianState , BaoXiuBillNumberID ,
				  BaoXiuID ,BuyDate , Serial , wxTotal , ErrDes , ifHideJieJian , ifWX ,
				  ifYearBill , Poster , LastUpdateTime , Stypeid ,FromBillNumberID , CostSale ,
				  OtherInOutType ,PosBillType ,checkTime ,posttime ,updateE , ShareMode , TransportId ,
				  IsIni , ATypeID1 , NCompleteTotal , ATID , IfCargo , InvoiceMoney ,  NInvoiceMoney ,
				  RedReason ,PrePriceNum ,
				  AssetBusinessTypeId , PromoRuleId , BeforePromoBillNumberId , ImportType , NewPosBill ,
				  PromotionMsg ,Reconciliation , ARTOTAL ,APTOTAL , YSTOTAL , YFTOTAL ,
				  IsAuto , IsYapi , YapiOrderID , DeliveryAddress ,AddDTypeETypeType ,
				  BillTime , CWCheck ,IfBargainOn , IfMulAccount , IsFreightMoney ,  FreightAddr , 
				  FreightPerson ,  FreightTel ,IfInvoice , UF1 ,UF2 , UF3 , UF4 ,UF5 , DealBTypeID ,
				  CID , Rate ,NTotalMoney ,NTotalInMoney , NPreferenceMoney ,NVIPCZMoney ,billproperty ,
				  TallyId , StypeID2 ,IfConfirm , TransferType , FeeDeductType ,
				  Discount , AdPriceType ,IsLend , ChargeOffBtypeid ,ChargeOffType ,ChargeOffTotal ,NChargeOffTotal,
				  BillNumberId,ModifyCount
				)
		SELECT    BillDate , BillCode , BillType ,Comment ,atypeid , ptypeid , btypeid ,
				  etypeid ,ktypeid ,ktypeid2 ,ifcheck ,checke ,totalmoney ,totalinmoney ,
				  totalqty ,tax , period ,explain , RedWord ,draft ,OrderId , waybillcode ,
				  goodsnumber , packway , TEL ,Uploaded , OFF_ID ,TeamNo ,AlertDay ,CompleteTotal ,
				  ID , Assessor ,IfAudit , Audit_explain ,IfStopMoney ,preferencemoney , DTypeId ,
				  JF ,VipCardID ,vipCZMoney ,jsStyle ,jsState , KTypeID3 , LinkMan , LinkTel ,
				  LinkAddr ,wxManID ,JieJianBillNumberID , JieJianID ,JieJianState , BaoXiuBillNumberID ,
				  BaoXiuID ,BuyDate , Serial , wxTotal , ErrDes , ifHideJieJian , ifWX ,
				  ifYearBill , Poster , LastUpdateTime , Stypeid ,FromBillNumberID , CostSale ,
				  OtherInOutType ,PosBillType ,checkTime ,posttime ,updateE , ShareMode , TransportId ,
				  IsIni , ATypeID1 , NCompleteTotal , ATID , IfCargo , InvoiceMoney ,  NInvoiceMoney ,
				  RedReason ,PrePriceNum ,
				  AssetBusinessTypeId , PromoRuleId , BeforePromoBillNumberId , ImportType , NewPosBill ,
				  PromotionMsg ,Reconciliation , ARTOTAL ,APTOTAL , YSTOTAL , YFTOTAL ,
				  IsAuto , IsYapi , YapiOrderID , DeliveryAddress ,AddDTypeETypeType ,
				  BillTime , CWCheck ,IfBargainOn , IfMulAccount , IsFreightMoney ,  FreightAddr , 
				  FreightPerson ,  FreightTel ,IfInvoice , UF1 ,UF2 , UF3 , UF4 ,UF5 , DealBTypeID ,
				  CID , Rate ,NTotalMoney ,NTotalInMoney , NPreferenceMoney ,NVIPCZMoney ,billproperty ,
				  TallyId , StypeID2 ,IfConfirm , TransferType , FeeDeductType ,
				  Discount , AdPriceType ,IsLend , ChargeOffBtypeid ,ChargeOffType ,ChargeOffTotal ,NChargeOffTotal,
				  BillNumberId,@ModifyCount
		FROM	dbo.BillIndex WHERE BillNumberId=@BillNumberID
		--收/付款单
		IF @BillType IN(4,66)
		BEGIN
			IF @BillType=4
			BEGIN
				INSERT INTO dbo.ModifyLog_GatheringBill
						( 
						  BillNumberId ,AtypeId ,total ,Comment ,
						  TeamNo ,TeamNO1 ,Stypeid ,ntotal ,
						  VipCardID ,ShowOrder ,RelevanceBillId,ID,ModifyCount
						)
				SELECT	  BillNumberId ,AtypeId ,total ,Comment ,
						  TeamNo ,TeamNO1 ,Stypeid ,ntotal ,
						  VipCardID ,ShowOrder ,RelevanceBillId,ID,@ModifyCount
				FROM dbo.gatheringBill WHERE BillNumberID=@BillNumberID
			END
			ELSE
			BEGIN
				INSERT INTO dbo.ModifyLog_PayBill
						( 
						  BillNumberId , AtypeId ,total ,Comment ,TeamNo ,
						  TeamNO1 ,Stypeid ,ntotal ,VipCardID ,
						  ShowOrder , RelevanceBillId,ID,ModifyCount
						)
				SELECT 	  BillNumberId , AtypeId ,total ,Comment ,TeamNo ,
						  TeamNO1 ,Stypeid ,ntotal ,VipCardID ,
						  ShowOrder , RelevanceBillId,ID,@ModifyCount
				FROM dbo.PayBill WHERE BillNumberID=@BillNumberID
			END
			
			INSERT INTO dbo.ModifyLog_CompleteGoodTotal
					( 
					  GoodsBillID ,MoneyBillID ,InOrOut ,CompleteGoodQTY ,
					  Draft ,Billdate ,PtypeID ,Billid ,CompleteGoodTotal ,
					  Price ,NCompleteGoodTotal ,IsSelect ,BillType,ModifyCount,ID
					)
			SELECT 	  GoodsBillID ,MoneyBillID ,InOrOut ,CompleteGoodQTY ,
					  Draft ,Billdate ,PtypeID ,Billid ,CompleteGoodTotal ,
					  Price ,NCompleteGoodTotal ,IsSelect ,BillType,@ModifyCount,ID
			FROM CompleteGoodTotal WHERE MoneyBillID=@BillNumberID
			
			INSERT INTO dbo.ModifyLog_CompleteTotal
					( 
					  GoodsBillID ,MoneyBillID ,CompleteTotal ,Draft ,
					  Billdate ,EtypeID ,NCompleteTotal ,GoodsBillDetailID ,
					  IsSelect ,BillType,ID,ModifyCount
					)
			SELECT    GoodsBillID ,MoneyBillID ,CompleteTotal ,Draft ,
					  Billdate ,EtypeID ,NCompleteTotal ,GoodsBillDetailID ,
					  IsSelect ,BillType,ID,@ModifyCount
			FROM dbo.CompleteTotal WHERE MoneyBillID=@BillNumberID
		END
		--销售出库单
		ELSE IF @BillType=11
		BEGIN
			INSERT INTO dbo.ModifyLog_SaleBill
					( 
					  BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,
					  jobnumber ,goodsno ,total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,
					  OrderID ,TeamNo ,TeamNO1 , IsUnit2 ,Serial ,InputCostPrice ,GoodsOrder ,
					  BackQty ,GoodsNumber ,ProduceDate ,ValidDate ,GoodsBTypeID ,GoodsCostPrice ,
					  GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,Tax ,KTypeID ,Stypeid ,
					  ShareFee ,TaxMoney ,NSalePrice , NSaleTotal ,NDiscountPrice ,NTotal , NTaxPrice ,
					  NTaxTotal ,NTaxMoney ,UnitID ,NUnitID ,NQty , UnitRate ,NUnitMsg ,MUnitID ,MQty ,MUnitRate ,
					  MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,
					  CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,entryCode , InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,
					  IsGift , BeforePromoID , ReferPrice ,PriceStyle ,PromoType ,PriceSource ,CompleteTotal ,
					  NCompleteTotal ,OMBillID ,ShowOrder ,LendBillNumberID ,LendBillID,ID,ModifyCount
					)
			SELECT    BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,
					  jobnumber ,goodsno ,total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,
					  OrderID ,TeamNo ,TeamNO1 , IsUnit2 ,Serial ,InputCostPrice ,GoodsOrder ,
					  BackQty ,GoodsNumber ,ProduceDate ,ValidDate ,GoodsBTypeID ,GoodsCostPrice ,
					  GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,Tax ,KTypeID ,Stypeid ,
					  ShareFee ,TaxMoney ,NSalePrice , NSaleTotal ,NDiscountPrice ,NTotal , NTaxPrice ,
					  NTaxTotal ,NTaxMoney ,UnitID ,NUnitID ,NQty , UnitRate ,NUnitMsg ,MUnitID ,MQty ,MUnitRate ,
					  MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,
					  CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,entryCode , InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,
					  IsGift , BeforePromoID , ReferPrice ,PriceStyle ,PromoType ,PriceSource ,CompleteTotal ,
					  NCompleteTotal ,OMBillID ,ShowOrder ,LendBillNumberID ,LendBillID,ID,@ModifyCount
			FROM dbo.SaleBill WHERE BillNumberId=@BillNumberID
		END
		--采购退货单
		ELSE IF @BillType=6
		BEGIN
			INSERT INTO dbo.ModifyLog_BuyBackBill
					( 
					  BillNumberId ,PtypeId ,Qty ,SalePrice ,discount , DiscountPrice , costprice ,
					  jobnumber , goodsno ,total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,
					  TeamNo ,TeamNo1 ,IsUnit2 ,Serial ,OldID ,OldBillNumberID ,InputCostPrice ,
					  GoodsOrder ,GoodsNumber ,ProduceDate ,ValidDate , GoodsBTypeID ,GoodsCostPrice ,
					  GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,Tax ,KTypeID ,Stypeid ,
					  TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,
					  NTaxMoney ,UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,
					  MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,CurMTaxPrice ,
					  CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,IsGift ,
					  PriceStyle ,CompleteTotal ,NCompleteTotal ,ShowOrder,ID,ModifyCount
					)
			SELECT    BillNumberId ,PtypeId ,Qty ,SalePrice ,discount , DiscountPrice , costprice ,
					  jobnumber , goodsno ,total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,
					  TeamNo ,TeamNo1 ,IsUnit2 ,Serial ,OldID ,OldBillNumberID ,InputCostPrice ,
					  GoodsOrder ,GoodsNumber ,ProduceDate ,ValidDate , GoodsBTypeID ,GoodsCostPrice ,
					  GoodsCostTotal ,HandZeroCost ,CompleteQTY ,SaleTotal ,Tax ,KTypeID ,Stypeid ,
					  TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,
					  NTaxMoney ,UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,
					  MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,CurMTaxPrice ,
					  CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,IsGift ,
					  PriceStyle ,CompleteTotal ,NCompleteTotal ,ShowOrder,ID,@ModifyCount
			FROM dbo.BuyBackBill WHERE BillNumberId=@BillNumberID
		END
		--采购入库单
		ELSE IF @BillType=34
		BEGIN
			INSERT INTO dbo.ModifyLog_BuyBill
					( 
					  BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,
					  jobnumber ,total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo1 ,
					  TeamNo ,orderid ,IsUnit2 ,Serial ,InputCostPrice ,GoodsOrder ,BackQty ,GoodsNumber ,
					  ProduceDate ,ValidDate ,GoodsBTypeID ,CompleteQTY ,GoodsCostPrice ,GoodsCostTotal , HandZeroCost ,
					  SaleTotal , Tax ,KTypeID ,Stypeid ,FromBillNumberID ,FromBillID ,ShareFee ,
					  TaxMoney ,NSalePrice , NSaleTotal , NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,
					  UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg , MUnitID ,MQty ,MUnitRate ,MUnitMsg ,
					  MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,CurMTaxPrice ,CargoID ,
					  ItemID ,IsCombined , entryCode ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,
					  IsGift ,CompleteTotal ,NCompleteTotal ,LendBillNumberID ,LendBillID , ShowOrder,ID,ModifyCount
					)
			SELECT    BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,
					  jobnumber ,total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo1 ,
					  TeamNo ,orderid ,IsUnit2 ,Serial ,InputCostPrice ,GoodsOrder ,BackQty ,GoodsNumber ,
					  ProduceDate ,ValidDate ,GoodsBTypeID ,CompleteQTY ,GoodsCostPrice ,GoodsCostTotal , HandZeroCost ,
					  SaleTotal , Tax ,KTypeID ,Stypeid ,FromBillNumberID ,FromBillID ,ShareFee ,
					  TaxMoney ,NSalePrice , NSaleTotal , NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,
					  UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg , MUnitID ,MQty ,MUnitRate ,MUnitMsg ,
					  MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,CurMTaxPrice ,CargoID ,
					  ItemID ,IsCombined , entryCode ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,
					  IsGift ,CompleteTotal ,NCompleteTotal ,LendBillNumberID ,LendBillID , ShowOrder,ID,@ModifyCount
			FROM dbo.BuyBill WHERE BillNumberId=@BillNumberID
		END
		--销售退货单
		ELSE IF @BillType=45
		BEGIN
			INSERT INTO dbo.ModifyLog_SaleBackBill
					( 
					  BillNumberId ,PtypeId , Qty ,SalePrice ,discount ,DiscountPrice ,jobnumber ,goodsno ,
					  total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo ,TeamNO1 ,IsUnit2 ,Serial ,
					  OldID ,CostPrice ,OldBillNumberID ,InputCostPrice ,GoodsOrder ,GoodsNumber ,ProduceDate ,
					  ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY , SaleTotal ,
					  Tax ,KTypeID ,Stypeid , FromBillNumberID ,FromBillID ,TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,
					  NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney , UnitID ,NUnitID ,NQty ,UnitRate , NUnitMsg ,MUnitID ,
					  MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,
					  CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,IsGift ,
					  ReferPrice ,PriceStyle ,PromoType ,OMBillID ,CompleteTotal ,NCompleteTotal ,ShowOrder,ID,ModifyCount
					)
			SELECT    BillNumberId ,PtypeId , Qty ,SalePrice ,discount ,DiscountPrice ,jobnumber ,goodsno ,
					  total ,OutFactoryDate ,TaxPrice ,TaxTotal ,comment ,TeamNo ,TeamNO1 ,IsUnit2 ,Serial ,
					  OldID ,CostPrice ,OldBillNumberID ,InputCostPrice ,GoodsOrder ,GoodsNumber ,ProduceDate ,
					  ValidDate ,GoodsBTypeID ,GoodsCostPrice ,GoodsCostTotal ,HandZeroCost ,CompleteQTY , SaleTotal ,
					  Tax ,KTypeID ,Stypeid , FromBillNumberID ,FromBillID ,TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,
					  NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney , UnitID ,NUnitID ,NQty ,UnitRate , NUnitMsg ,MUnitID ,
					  MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,
					  CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,IsGift ,
					  ReferPrice ,PriceStyle ,PromoType ,OMBillID ,CompleteTotal ,NCompleteTotal ,ShowOrder,ID,@ModifyCount
			FROM dbo.saleBackBill WHERE BillNumberId=@BillNumberID
		END
		--预收/付款单
		ELSE IF @BillType IN(189,190)
		BEGIN
			INSERT INTO dbo.ModifyLog_PreBill
			        ( 
			          BillNumberId ,BillType ,Comment ,AtypeId ,total ,
			          TeamNo ,TeamNO1 ,Stypeid ,ntotal ,vipcardid ,
			          ShowOrder ,RelevanceBillId,ID,ModifyCount
			        )
			SELECT	  BillNumberId ,BillType ,Comment ,AtypeId ,total ,
			          TeamNo ,TeamNO1 ,Stypeid ,ntotal ,vipcardid ,
			          ShowOrder ,RelevanceBillId,ID,@ModifyCount
			FROM dbo.PreBill WHERE BillNumberId=@BillNumberID
		END
		--暂估入库单
		ELSE IF @BillType=400
		BEGIN
			INSERT INTO dbo.ModifyLog_AppraisalBill
					( 
					  BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,total ,TaxPrice ,TaxTotal ,
					  comment ,TeamNo1 ,TeamNo ,orderid ,Serial ,InputCostPrice , GoodsOrder ,BackQty ,GoodsNumber ,
					  ProduceDate ,ValidDate ,GoodsCostPrice ,HandZeroCost , SaleTotal , Tax ,KTypeID ,Stypeid ,
					  TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,
					  UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,
					  MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,CurMTaxPrice , CargoID ,ItemID ,
					  IsCombined ,entryCode ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney , IsGift ,InvoiceMoneyEX ,
					  NInvoiceMoneyEX ,InvoiceCostTotal ,OldID , OldBillNumberID ,InvoiceNQty ,InvoiceSaleMoney ,
					  NInvoiceSaleMoney ,ShareFee ,ShowOrder,ID,ModifyCount
					)
			SELECT    BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,total ,TaxPrice ,TaxTotal ,
					  comment ,TeamNo1 ,TeamNo ,orderid ,Serial ,InputCostPrice , GoodsOrder ,BackQty ,GoodsNumber ,
					  ProduceDate ,ValidDate ,GoodsCostPrice ,HandZeroCost , SaleTotal , Tax ,KTypeID ,Stypeid ,
					  TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,
					  UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,
					  MDiscountPrice ,MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,CurMTaxPrice , CargoID ,ItemID ,
					  IsCombined ,entryCode ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney , IsGift ,InvoiceMoneyEX ,
					  NInvoiceMoneyEX ,InvoiceCostTotal ,OldID , OldBillNumberID ,InvoiceNQty ,InvoiceSaleMoney ,
					  NInvoiceSaleMoney ,ShareFee ,ShowOrder,ID,@ModifyCount
			 FROM dbo.AppraisalBill WHERE BillNumberId=@BillNumberID
		END
		--暂估退货单
		ELSE IF @BillType=401
		BEGIN
			INSERT INTO dbo.ModifyLog_AppraisalBackBill
					( 
					  BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,total ,TaxPrice ,
					  TaxTotal ,comment ,TeamNo ,TeamNo1 ,Serial ,OldID ,OldBillNumberID ,InputCostPrice ,
					  GoodsOrder ,GoodsNumber ,ProduceDate ,ValidDate ,GoodsCostPrice ,HandZeroCost ,SaleTotal ,Tax ,
					  KTypeID ,Stypeid ,TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,NTaxPrice ,
					  NTaxTotal ,NTaxMoney ,UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,MUnitID ,MQty ,
					  MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice , MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,
					  CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,
					  IsGift ,PriceStyle ,InvoiceCostTotal ,InvoiceMoneyEX ,NInvoiceMoneyEX ,InvoiceNQty ,
					  CostTotal ,InvoiceSaleMoney ,NInvoiceSaleMoney ,ShareFee ,ShowOrder,ID,ModifyCount
					)
			SELECT 	  BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,total ,TaxPrice ,
					  TaxTotal ,comment ,TeamNo ,TeamNo1 ,Serial ,OldID ,OldBillNumberID ,InputCostPrice ,
					  GoodsOrder ,GoodsNumber ,ProduceDate ,ValidDate ,GoodsCostPrice ,HandZeroCost ,SaleTotal ,Tax ,
					  KTypeID ,Stypeid ,TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,NTaxPrice ,
					  NTaxTotal ,NTaxMoney ,UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,MUnitID ,MQty ,
					  MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice , MTaxPrice ,CurMSalePrice ,CurMDiscountPrice ,
					  CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,NInvoiceMoney ,
					  IsGift ,PriceStyle ,InvoiceCostTotal ,InvoiceMoneyEX ,NInvoiceMoneyEX ,InvoiceNQty ,
					  CostTotal ,InvoiceSaleMoney ,NInvoiceSaleMoney ,ShareFee ,ShowOrder,ID,@ModifyCount
			FROM dbo.AppraisalBackBill WHERE BillNumberId=@BillNumberID
		END
		--发出商品出库单
		ELSE IF @BillType=402
		BEGIN
			INSERT INTO dbo.ModifyLog_SendBill
					( 
					  BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,total ,
					  TaxPrice ,TaxTotal ,comment ,OrderID ,TeamNo ,TeamNO1 ,Serial ,InputCostPrice ,GoodsOrder ,
					  BackQty ,GoodsNumber ,ProduceDate ,ValidDate ,GoodsCostPrice , HandZeroCost ,SaleTotal , Tax ,
					  KTypeID ,Stypeid ,ShareFee ,TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,
					  NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID ,NQty ,UnitRate ,
					  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice , MDiscountPrice ,MTaxPrice ,
					  CurMSalePrice ,CurMDiscountPrice , CurMTaxPrice , CargoID ,ItemID ,IsCombined ,
					  entryCode ,InvoiceQty ,InvoiceMoney , NInvoiceMoney ,PriceSource ,IsGift ,
					  ReferPrice ,PriceStyle ,InvoiceMoneyEX ,NInvoiceMoneyEX ,InvoiceCostTotal ,OldID ,
					  OldBillNumberID , InvoiceNQty ,CostTotal ,InvoiceSaleMoney ,NInvoiceSaleMoney ,ShowOrder,
					  ID,ModifyCount
					)
			SELECT    BillNumberId ,PtypeId ,Qty ,SalePrice ,discount ,DiscountPrice ,costprice ,total ,
					  TaxPrice ,TaxTotal ,comment ,OrderID ,TeamNo ,TeamNO1 ,Serial ,InputCostPrice ,GoodsOrder ,
					  BackQty ,GoodsNumber ,ProduceDate ,ValidDate ,GoodsCostPrice , HandZeroCost ,SaleTotal , Tax ,
					  KTypeID ,Stypeid ,ShareFee ,TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,NTotal ,
					  NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID ,NQty ,UnitRate ,
					  NUnitMsg ,MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice , MDiscountPrice ,MTaxPrice ,
					  CurMSalePrice ,CurMDiscountPrice , CurMTaxPrice , CargoID ,ItemID ,IsCombined ,
					  entryCode ,InvoiceQty ,InvoiceMoney , NInvoiceMoney ,PriceSource ,IsGift ,
					  ReferPrice ,PriceStyle ,InvoiceMoneyEX ,NInvoiceMoneyEX ,InvoiceCostTotal ,OldID ,
					  OldBillNumberID , InvoiceNQty ,CostTotal ,InvoiceSaleMoney ,NInvoiceSaleMoney ,ShowOrder,
					  ID,@ModifyCount
			FROM	dbo.SendBill WHERE BillNumberId=@BillNumberID
		END
		--发出商品退货单
		ELSE IF @BillType=403
		BEGIN
			INSERT INTO dbo.ModifyLog_SendBackBill
					( 
					  BillNumberId ,PtypeId ,Qty ,SalePrice , discount ,DiscountPrice ,total ,TaxPrice ,TaxTotal ,
					  comment ,TeamNo ,TeamNO1 ,Serial ,OldID ,CostPrice ,OldBillNumberID ,InputCostPrice ,
					  GoodsOrder ,GoodsNumber ,ProduceDate ,ValidDate ,GoodsCostPrice ,HandZeroCost ,
					  SaleTotal ,Tax ,KTypeID ,Stypeid ,TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,
					  NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,
					  MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
					  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,
					  NInvoiceMoney ,IsGift ,ReferPrice ,PriceStyle ,InvoiceMoneyEX ,NInvoiceMoneyEX ,
					  InvoiceCostTotal ,InvoiceNQty ,CostTotal ,InvoiceSaleMoney , NInvoiceSaleMoney ,
					  ShareFee ,ShowOrder,ID,ModifyCount
					)
			SELECT	  BillNumberId ,PtypeId ,Qty ,SalePrice , discount ,DiscountPrice ,total ,TaxPrice ,TaxTotal ,
					  comment ,TeamNo ,TeamNO1 ,Serial ,OldID ,CostPrice ,OldBillNumberID ,InputCostPrice ,
					  GoodsOrder ,GoodsNumber ,ProduceDate ,ValidDate ,GoodsCostPrice ,HandZeroCost ,
					  SaleTotal ,Tax ,KTypeID ,Stypeid ,TaxMoney ,NSalePrice ,NSaleTotal ,NDiscountPrice ,
					  NTotal ,NTaxPrice ,NTaxTotal ,NTaxMoney ,UnitID ,NUnitID ,NQty ,UnitRate ,NUnitMsg ,
					  MUnitID ,MQty ,MUnitRate ,MUnitMsg ,MSalePrice ,MDiscountPrice ,MTaxPrice ,CurMSalePrice ,
					  CurMDiscountPrice ,CurMTaxPrice ,CargoID ,ItemID ,IsCombined ,InvoiceQty ,InvoiceMoney ,
					  NInvoiceMoney ,IsGift ,ReferPrice ,PriceStyle ,InvoiceMoneyEX ,NInvoiceMoneyEX ,
					  InvoiceCostTotal ,InvoiceNQty ,CostTotal ,InvoiceSaleMoney , NInvoiceSaleMoney ,
					  ShareFee ,ShowOrder,ID,@ModifyCount
			FROM	dbo.SendBackBill WHERE BillNumberId=@BillNumberID
		END
		ELSE IF @BillType=12--组合品出库单
		BEGIN
		INSERT INTO dbo.ModifyLog_PT_Combin_SaleBill
					( 
					 BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,OrderID
                    ,TeamNo,ID,TeamNO1,IsUnit2,InputCostPrice,GoodsOrder,BackQty,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax,KTypeID,Stypeid
					,ShareFee,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg
					,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,
					BeforePromoID,ReferPrice,PriceStyle,PriceSource,PromoType,CompleteTotal,NCompleteTotal,LendBillID,LendBillNumberID,ShowOrder,DiyID,pindexid,PromonIds,CouponCode
				    ,IsPromotion,IsVipPoint,Reconciliation,ModifyCount
					)
			SELECT	   BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,OrderID
                    ,TeamNo,ID,TeamNO1,IsUnit2,InputCostPrice,GoodsOrder,BackQty,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax,KTypeID,Stypeid
					,ShareFee,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg
					,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,
					BeforePromoID,ReferPrice,PriceStyle,PriceSource,PromoType,CompleteTotal,NCompleteTotal,LendBillID,LendBillNumberID,ShowOrder,DiyID,pindexid,PromonIds,CouponCode
				    ,IsPromotion,IsVipPoint,Reconciliation,@ModifyCount
			FROM	dbo.PT_Combin_SaleBill WHERE BillNumberId=@BillNumberID		
				
	    INSERT INTO dbo.ModifyLog_PT_Combin_SaleBillDetail
					( 
					  BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,OrderID,TeamNo
					 ,ID,TeamNO1,IsUnit2,Serial,InputCostPrice,GoodsOrder,BackQty,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal
					 ,Tax,KTypeID,Stypeid,ShareFee,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty
					 ,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,InvoiceQty,InvoiceMoney
					 ,NInvoiceMoney,IsGift,BeforePromoID,ReferPrice,PriceStyle,PriceSource,PromoType,CompleteTotal,NCompleteTotal,LendBillID,LendBillNumberID,ShowOrder,DiyID,pindexid,combinationptypeid
					 ,SendedQty,PickedQty,ClearQty,OutFactQty,DraftFlag,IsIniFlag,ModifyCount
					)
			SELECT	  BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,OrderID,TeamNo
					 ,ID,TeamNO1,IsUnit2,Serial,InputCostPrice,GoodsOrder,BackQty,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal
					 ,Tax,KTypeID,Stypeid,ShareFee,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty
					 ,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,InvoiceQty,InvoiceMoney
					 ,NInvoiceMoney,IsGift,BeforePromoID,ReferPrice,PriceStyle,PriceSource,PromoType,CompleteTotal,NCompleteTotal,LendBillID,LendBillNumberID,ShowOrder,DiyID,pindexid,combinationptypeid
					 ,SendedQty,PickedQty,ClearQty,OutFactQty,DraftFlag,IsIniFlag,@ModifyCount
			FROM	dbo.PT_Combin_SaleBillDetail WHERE BillNumberId=@BillNumberID		
		END
		ELSE IF @BillType=46--组合品退货单
		BEGIN
			INSERT INTO dbo.ModifyLog_PT_Combin_SaleBackBill
					( 
					 BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,TeamNo,ID,TeamNO1,IsUnit2
					,OldID,CostPrice,OldBillNumberID,InputCostPrice,GoodsOrder,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax,KTypeID,Stypeid,FromBillNumberID,FromBillID
					,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice
					,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,ReferPrice,PriceStyle,PromoType,CompleteTotal,NCompleteTotal
					,pindexid,ShowOrder,PriceSource,CouponCode,Reconciliation,ModifyCount
					)
			SELECT	  BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,TeamNo,ID,TeamNO1,IsUnit2
					,OldID,CostPrice,OldBillNumberID,InputCostPrice,GoodsOrder,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax,KTypeID,Stypeid,FromBillNumberID,FromBillID
					,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice
					,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,ReferPrice,PriceStyle,PromoType,CompleteTotal,NCompleteTotal
					,pindexid,ShowOrder,PriceSource,CouponCode,Reconciliation,@ModifyCount
			FROM	dbo.PT_Combin_SaleBackBill WHERE BillNumberId=@BillNumberID
			
			INSERT INTO dbo.ModifyLog_PT_Combin_SaleBackBillDetail
					( 
					BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,TeamNo,ID,TeamNO1,IsUnit2
					,Serial,OldID,CostPrice,OldBillNumberID,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax
					,KTypeID,Stypeid,FromBillNumberID,FromBillID,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg
					,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,InvoiceQty,InvoiceMoney,NInvoiceMoney
					,IsGift,ReferPrice,PriceStyle,PromoType,CompleteTotal,NCompleteTotal,pindexid,combinationptypeid,ShowOrder,InflowQty,DraftFlag,IsIniFlag,PriceSource,InFactQty,ModifyCount
					)
			SELECT	 	BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,TeamNo,ID,TeamNO1,IsUnit2
					,Serial,OldID,CostPrice,OldBillNumberID,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax
					,KTypeID,Stypeid,FromBillNumberID,FromBillID,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg
					,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,InvoiceQty,InvoiceMoney,NInvoiceMoney
					,IsGift,ReferPrice,PriceStyle,PromoType,CompleteTotal,NCompleteTotal,pindexid,combinationptypeid,ShowOrder,InflowQty,DraftFlag,IsIniFlag,PriceSource,InFactQty,@ModifyCount
			FROM	dbo.PT_Combin_SaleBackBillDetail WHERE BillNumberId=@BillNumberID
		END
	END
END
GO






IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_Modify_WdBillValue]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_Modify_WdBillValue];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2017-02-24
	描述：修改网店单据的atypeid和ntotal以及虚拟库存和品牌应收填写品牌账户
*/
CREATE PROCEDURE Gp_Modify_WdBillValue
    (
      @billnumberids VARCHAR(MAX)
    )

--@encode$--
AS
    SET NOCOUNT ON;

    BEGIN
        DECLARE @intBillNumberID INT ,@count INT;
        DECLARE billnumberid_cursor CURSOR
        FOR
            SELECT  a AS tablename
            FROM    dbo.f_split(@billnumberids, ',') FOR READ ONLY;
        OPEN billnumberid_cursor;
        FETCH NEXT FROM billnumberid_cursor INTO @intBillNumberID;
        WHILE @@fetch_status = 0
            BEGIN
				DECLARE @billtype INT,@brandTypeId VARCHAR(200)
				SELECT @billtype = flag FROM dbo.WdShopBillRelation WHERE Billnumberid=@intBillNumberID
		
				IF(@billtype=1)--销售出库单
				BEGIN 
					DECLARE @total NUMERIC(24, 10);
					SELECT  @total = SUM(NSaleTotal)
					FROM    dbo.SaleBill
					WHERE   BillNumberId = @intBillNumberID;
					UPDATE  dbo.BillIndex
					SET     NTotalMoney = dbo.F_RoundTotal(@total) ,
							totalmoney = dbo.F_RoundTotal(@total)
					WHERE   BillNumberId = @intBillNumberID
					
					IF --EXISTS(SELECT * FROM BillMulAccount WHERE BillNumberId = @intBillNumberID) 
					--AND 
					EXISTS ( SELECT  * FROM  dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue = 1 )
					BEGIN
						INSERT INTO dbo.BillMulBrand
								( STypeID ,
								  BTypeID ,
								  BrandarTypeID ,
								  BillNumberId ,
								  BillType ,
								  Cid ,
								  Rate ,
								  TaxTotal ,
								  NTaxTotal ,
								  PreferenceMoney ,
								  NPreferenceMoney ,
								  TotalInMoney ,
								  NTotalInMoney ,
								  YSTotalInMoney ,
								  NYSTotalInMoney ,
								  TheOrderARTotal ,
								  NTheOrderARTotal ,
								  isIni
								)
						SELECT BI.Stypeid,BI.btypeid,P.BrandarTypeID,
						BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.TaxTotal),SUM(S.NTaxTotal),0,0,0,0,
						0,0,0,0,0
						FROM dbo.SaleBill S INNER JOIN PTYPE P ON S.PtypeId = P.typeId
						INNER JOIN dbo.brandar_Commodity B ON B.TypeId = P.BrandarTypeID
						INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
						WHERE BI.BillNumberId = @intBillNumberID
						GROUP BY P.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate  
			
						SELECT TOP 1 @brandTypeId =  BrandarTypeID FROM dbo.BillMulBrand WHERE BillNumberId = @intBillNumberID ORDER BY NTaxTotal DESC 
						SELECT @brandTypeId
						UPDATE dbo.BillMulBrand SET PreferenceMoney = BI.preferencemoney,NPreferenceMoney =BI.NPreferenceMoney,
						TotalInMoney = BB.TotalInMoney-BI.preferencemoney,NTotalInMoney = BB.NTotalInMoney - BI.NPreferenceMoney
						FROM dbo.BillMulBrand BB
						INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = BB.BillNumberId WHERE BB.BillNumberId = @intBillNumberID
						AND BB.BrandarTypeID = @brandTypeId;
						
						--UPDATE dbo.BillIndex SET preferencemoney = 0,NPreferenceMoney = 0 WHERE BillNumberId = @intBillNumberID
						----启用品牌应收将单据抹零金额清零
					END 
                END 
                IF @billtype = 5 --销售退货单
                BEGIN
					IF --EXISTS(SELECT * FROM BillMulAccount WHERE BillNumberId = @intBillNumberID) 
					--AND 
					EXISTS ( SELECT  * FROM  dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue = 1 )
					BEGIN
						INSERT INTO dbo.BillMulBrand
								( STypeID ,
								  BTypeID ,
								  BrandarTypeID ,
								  BillNumberId ,
								  BillType ,
								  Cid ,
								  Rate ,
								  TaxTotal ,
								  NTaxTotal ,
								  PreferenceMoney ,
								  NPreferenceMoney ,
								  TotalInMoney ,
								  NTotalInMoney ,
								  YSTotalInMoney ,
								  NYSTotalInMoney ,
								  TheOrderARTotal ,
								  NTheOrderARTotal ,
								  isIni
								)
						SELECT BI.Stypeid,BI.btypeid,P.BrandarTypeID,
						BI.BillNumberId,BI.BillType,BI.CID,BI.Rate,SUM(S.TaxTotal),SUM(S.NTaxTotal),0,0,SUM(S.TaxTotal),SUM(S.NTaxTotal),
						0,0,0,0,0
						FROM dbo.saleBackBill S INNER JOIN PTYPE P ON S.PtypeId = P.typeId
						INNER JOIN dbo.brandar_Commodity B ON B.TypeId = P.BrandarTypeID
						INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = S.BillNumberId
						WHERE BI.BillNumberId = @intBillNumberID
						GROUP BY P.BrandarTypeID,BI.Stypeid,BI.btypeid,BI.BillNumberId,BI.BillType,BI.CID,BI.Rate  
			
						SELECT TOP 1 @brandTypeId =  BrandarTypeID FROM dbo.BillMulBrand WHERE BillNumberId = @intBillNumberID ORDER BY NTaxTotal DESC 

						UPDATE dbo.BillMulBrand SET PreferenceMoney = BI.preferencemoney,NPreferenceMoney =BI.NPreferenceMoney,
						TotalInMoney = BB.TotalInMoney-BI.preferencemoney,NTotalInMoney = BB.NTotalInMoney - BI.NPreferenceMoney
						FROM dbo.BillMulBrand BB
						INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = BB.BillNumberId WHERE BB.BillNumberId = @intBillNumberID AND BB.BrandarTypeID = @brandTypeId;
                END 
                END 
                SELECT  @count = COUNT(*) FROM dbo.BillMulAccount WHERE   BillNumberId = @intBillNumberID;
                IF @count > 1
                    BEGIN
                        UPDATE  dbo.BillIndex
                        SET     atypeid = -99999,IfMulAccount = 1 WHERE BillNumberId=@intBillNumberID;
                    END; 
                UPDATE dbo.BillIndex SET ktypeid2 ='',KTypeID3 = '' WHERE BillNumberId = @intBillNumberID
                IF @billtype = 1 --销售出库单
                BEGIN
                EXEC GP_CopyOrCreateBill_DraftQTY @intBillNumberID,11
                END 
                ELSE IF @billtype = 5 --销售退货单
                BEGIN
                EXEC GP_CopyOrCreateBill_DraftQTY @intBillNumberID,45
                END 
                ELSE
                BEGIN
                EXEC GP_CopyOrCreateBill_DraftQTY @intBillNumberID,36
                END 
                FETCH NEXT FROM billnumberid_cursor INTO @intBillNumberID;
                SET @count = 0;
            END;
        CLOSE billnumberid_cursor;
        DEALLOCATE billnumberid_cursor;
    END;
    SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	Author:		毛欣蓉
	Create date: 2012-05-08
	Description: 根据条件修改往来余额:先调用Gp_GetDbf得到此前的余额，然后修改当前余额
*/	
CREATE   PROCEDURE GP_ModifyArApTotal
(
	@AID				INT,
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@numBanlanceTotal	 NUMERIC(24, 10) ,
	@NnumBanlanceTotal	 NUMERIC(24, 10) ,
	@CID				INT,
	@strMsg				VARCHAR(200) OUTPUT --返回消息
)
--@encode$--
AS

DECLARE   @preTotal		 NUMERIC(24, 10) ,	--之前余额
		  @NpreTotal	 NUMERIC(24, 10) ,	--之前余额
		  @totalType	VARCHAR(50)	= '',
		  @NtotalType	VARCHAR(50)	= '',
		  @SQL			VARCHAR(2000) = ''	

EXEC GP_GetArApTotal		@AID,
							@chvBTypeID,
							@chvSTypeID,
							@CID,
							@preTotal output,
							@NpreTotal output
							
							
SET @numBanlanceTotal =  ISNULL(@preTotal,0) + @numBanlanceTotal
SET @NnumBanlanceTotal = ISNULL(@NpreTotal,0) + @NnumBanlanceTotal

IF @numBanlanceTotal < 0 OR @NnumBanlanceTotal < 0 --检查过账后余额不能为负
BEGIN
	SET @strMsg = @AID

	RETURN 918
END
		
IF @AID=1 --应收
BEGIN
	SET @totalType = 'ARTotal'
	SET @NtotalType = 'NARTotal'
END
IF @AID=2 --应付
BEGIN
	SET @totalType = 'APTotal'
	SET @NtotalType = 'NAPTotal'
END	
IF @AID=3 --预收
BEGIN
	SET @totalType = 'YSTotal'
	SET @NtotalType = 'NYSTotal'
END	
IF @AID=4 --预付
BEGIN
	SET @totalType = 'YFTotal'
	SET @NtotalType = 'NYFTotal'
END	
	
IF NOT EXISTS(
	SELECT BTypeID
	FROM BType_ARAPTotal
	WHERE BTypeID=@chvBTypeID AND STypeID=@chvSTypeID AND CID = @CID
)
BEGIN
	SET @SQL='
			INSERT BType_ARAPTotal(BTypeID,STypeID,'+@totalType+','+@NtotalType+',CID)
				VALUES('''+@chvBTypeID+''','''+@chvSTypeID+''','+CAST(@numBanlanceTotal AS VARCHAR)+','+CAST(@NnumBanlanceTotal AS VARCHAR)+','+CAST(@CID AS VARCHAR)+')'
END
ELSE
BEGIN
	SET @SQL='
			UPDATE BType_ARAPTotal SET '+@totalType+' = '+ CAST(@numBanlanceTotal AS VARCHAR)+','+@NtotalType+' = ' +CAST(@NnumBanlanceTotal AS VARCHAR)+'
			WHERE BTypeID = '''+@chvBTypeID+''' AND STypeID='''+@chvSTypeID+''' AND CID='+ CAST(@CID AS VARCHAR)
END

--SELECT @SQL
EXEC (@SQL)

IF @@ERROR <> 0  RETURN -10

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	处理Atype_total 余额
*/
CREATE     PROCEDURE GP_ModifyAtype_total 
(
	@chvATypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50),
	@CID				BIGINT,
	@Total				 NUMERIC(24, 10) ,
	@Ntotal				 NUMERIC(24, 10) 
)
--@encode$--
AS

IF NOT EXISTS(
	SELECT 1
	FROM Atype_total
	WHERE ATypeID=@chvATypeID AND STypeID=@chvSTypeID AND CID = @CID
)
BEGIN
	INSERT INTO AType_Total(ATypeID,STypeID,CID,Total,Ntotal) VALUES(@chvATypeID,@chvSTypeID,@CID,@Total,@Ntotal)
END
ELSE
BEGIN
	UPDATE AType_Total SET Total = ISNULL(Total,0) + @Total,Ntotal = ISNULL(Ntotal,0) + @Ntotal
	WHERE ATypeID = @chvATypeID AND STypeID = @chvSTypeID AND CID = @CID 
END
		
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	BEGIN
		RETURN -10
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：谢吉康
	时间：2019-10-24 
	原因：全面修改单据前的序列号检查
	EXEC Gp_ModifyAuditingBillSerialCheck '2',11
*/
CREATE  PROCEDURE Gp_ModifyAuditingBillSerialCheck
(
	@BillNumberId	varchar(50),	-- 单据编号
	@intBillType	int				-- 单据类型
)
--@encode$--
AS
SET NOCOUNT ON	

DECLARE @DelID			int,			--需要删除的单据的过帐ID   BillIndex->ID
		@laterSerial	varchar(100),	--Gp_InOutPTypeSerial中的序列号
		@returnValue 	INT			,
		@mngLendSerial	VARCHAR(10),	--系统采用序列号借欠出入库校验模式
		@preKTypeId		VARCHAR(50),	--上张单据的仓库
		@cruKTypeId		VARCHAR(50),	--当前前单据中序列号仓库
		@cruSTypeId		VARCHAR(50),	--当前单据的分支机构
		@cruState		VARCHAR(10),	--当前单据中序列号状态
		@nowState		VARCHAR(10),	--序列号库存中的状态
		@nowKtypeId		VARCHAR(50),	--序列号库存中的仓库
		@nowSTypeId		VARCHAR(50)		--序列号库存中的分支机构
		
SET @returnValue = 0
SELECT @mngLendSerial = Value FROM dbo.Userconfig WHERE ConfigName= 'mngLendSerial'

--获取需要删除的单据的过帐Id
----SELECT @DelID = [ID] FROM Gp_InOutPTypeSerial WHERE BillNumberID = @BillNumberID AND 

--循环用游标来判断是否存在后续的单据
DECLARE LaterSerial CURSOR FOR
	SELECT	Serial 
	FROM	Gp_InOutPTypeSerial 
	WHERE	BillNumberId = @BillNumberId 
			AND BillType=@intBillType
			AND BillType NOT IN (71,72,88)

OPEN LaterSerial

FETCH NEXT FROM LaterSerial INTO @laterSerial
WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT	TOP 1 
				@DelID = [ID],
				@cruState = [state],
				@cruKTypeId = CASE WHEN [state] IN (1,7) THEN InKtypeID ELSE OutKtyeID END
		FROM	Gp_InOutPTypeSerial 
		WHERE	BillNumberID = @BillNumberID  
				AND BillType =  @intBillType 
				AND Serial = @laterSerial
	
		IF EXISTS(
			SELECT	Bil.BillNumberId
			FROM	BillIndex Bil,
					Gp_InOutPTypeSerial G
			WHERE	Bil.BillNumberId = G.BillNumberId
					AND Bil.IfCheck = 't'
					AND Bil.RedWord = 0
					--AND Bil.BillNumberId <> @BillNumberId
					AND G.Serial = @laterSerial
					AND g.Id>@DelId
					AND G.BillType NOT IN (71,72,88,203)
			--ORDER BY Bil.Id DESC
		)
		BEGIN
			--PRINT @laterSerial
			--RAISERROR('有后续的单据存在，不允许红冲！',16,1)
			CLOSE LaterSerial
			DEALLOCATE LaterSerial
			RETURN -11
		END
		
		IF  @mngLendSerial = '1'
		BEGIN
			IF EXISTS(
				SELECT	Bil.BillNumberId
				FROM    LendIndex Bil,
						Gp_InOutPTypeSerial G
				WHERE	Bil.BillNumberId = G.BillNumberId
						AND Bil.IfCheck = 't'
						AND Bil.RedWord = 0
						--AND Bil.BillNumberId <> @BillNumberId
						AND G.Serial = @laterSerial
						AND g.Id>@DelId
						AND G.BillType = 87
				--ORDER BY Bil.Id DESC
			)
			BEGIN
				--PRINT @laterSerial
				--RAISERROR('有后续的单据存在，不允许红冲！',16,1)
				CLOSE LaterSerial
				DEALLOCATE LaterSerial
				RETURN -11
			END
		END
		
		--判断序列号是否做过序列号调整单
		IF EXISTS(SELECT TOP 1 1 FROM SerialAdjustBill s,SerialAdjustIndex i WHERE  I.BillNumberId=S.BillNumberId AND I.draft=0	 AND s.OldSerial= 'я'+@laterSerial+'я' )
		BEGIN
			--做过序列号调整单，不允许红冲
			CLOSE LaterSerial
			DEALLOCATE LaterSerial
			RETURN -13
		END
		
		--判断序列号是否被其他分支机构使用了		
		IF NOT EXISTS(SELECT TOP 1 1 FROM Gp_InOutPTypeSerial I INNER JOIN BillIndex B ON I.BillNumberid = B.BillNumberId WHERE I.Serial = @laterSerial AND I.ID > @DelID AND B.RedWord = 0 AND B.IfCheck = 't')
		BEGIN
			SELECT @nowSTypeId = STypeId FROM Stock WHERE TypeId = @cruKTypeId
				
			IF EXISTS(SELECT TOP 1 1 FROM dbo.gp_initPtypeSerial WHERE Serial = @laterSerial AND stypeid <> @nowSTypeId)
			BEGIN
				CLOSE LaterSerial
				DEALLOCATE LaterSerial
				RETURN -14
			END	
		END	
		
		FETCH NEXT FROM LaterSerial INTO @laterSerial
	END

CLOSE LaterSerial
DEALLOCATE LaterSerial

RETURN @returnValue



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

--====================================================================================
-----------------功能：红冲单据 修改Btype_araptotal、Atype_Total
-----------------作者：韩林						   
-----------------日期：2012-06-20                
--====================================================================================

CREATE    PROC Gp_ModifyBAndAtype_Total
(
	@nBillID	numeric(10, 0),		-- 1. 单据编号 ID
	@nBillType	numeric(4, 0)		-- 2. 单据类型
)
--@encode$--
AS
SET NOCOUNT ON
	
DECLARE	@AR_ID					varchar(50),
		@AP_ID					varchar(50),
		@YF_ID					varchar(50),
		@YS_ID					varchar(50),
		@GRIR_ID				VARCHAR(50),
		@FC_ID					VARCHAR(50)

SELECT @AR_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '987'				-- 应收
SELECT @AP_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '2121'			-- 应付
SELECT @YF_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '1151'			-- 预付账款
SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '2131'			-- 预收账款

SELECT 	@FC_id=nid FROM dbo.Ac_Items WHERE UserCode =  '1251'			--发出商品
SELECT 	@GRIR_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '2122'			--应付暂估

DECLARE @btypeid VARCHAR(50)='';
		
IF EXISTS(SELECT 1 FROM dbo.ListTable  WHERE BillNumberId=@nBillID AND BillType=@nBillType)
BEGIN
	--处理科目余额
	MERGE INTO dbo.AType_Total a
	USING(	SELECT AtypeId,STypeID,SUM(Total)AS total,SUM(Ntotal) AS ntotal,CID 
			FROM dbo.ListTable 
			WHERE BillNumberId=@nBillID AND BillType=@nBillType
			GROUP BY AtypeId,STypeID,CID
		)s
	ON a.ATypeID=s.AtypeId AND a.STypeID=s.STypeID AND a.CID=s.CID
	WHEN MATCHED THEN UPDATE SET a.Total+=s.Total,ntotal+=s.NTotal
	WHEN NOT MATCHED THEN INSERT(ATypeID,STypeID,Total,Ntotal,CID)VALUES(s.Atypeid,s.Stypeid,s.Total,s.Ntotal,s.cid)  ;
	
	

	--处理应收应付
	IF EXISTS(SELECT 1 FROM dbo.ListTable  WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@AR_ID)
	BEGIN
		MERGE INTO BType_ArApTotal ba
		USING(	SELECT AtypeId,BtypeId,STypeID,SUM(Total) AS total,SUM(Ntotal) AS ntotal,CID 
				FROM dbo.ListTable 
				WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@AR_ID
				GROUP BY AtypeId,BtypeId,STypeID,CID,BillNumberId
			)s
		ON ba.BTypeID=s.BtypeId AND ba.CID=s.CID AND ba.STypeID=s.STypeID
		WHEN MATCHED THEN UPDATE SET ARTotal+=s.Total,NARTotal+=s.NTotal
		WHEN NOT MATCHED THEN  INSERT(BTypeID,STypeID,ARTotal,nARTotal,cid)VALUES(s.btypeid,s.stypeid,s.total,s.ntotal,s.cid) ;
	END		
	
	IF EXISTS(SELECT 1 FROM dbo.ListTable  WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@AP_ID)
	BEGIN
		MERGE INTO BType_ArApTotal ba
		USING(	SELECT AtypeId,BtypeId,STypeID,SUM(Total) AS total,SUM(Ntotal) AS ntotal,CID 
				FROM dbo.ListTable
				WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@AP_ID
				GROUP BY AtypeId,BtypeId,STypeID,CID,BillNumberId
			)s
		ON ba.BTypeID=s.BtypeId AND ba.CID=s.CID AND ba.STypeID=s.STypeID
		WHEN MATCHED THEN UPDATE SET APTotal+=s.Total,NAPTotal+=s.NTotal
		WHEN NOT MATCHED THEN  INSERT(BTypeID,STypeID,APTotal,nAPTotal,cid)VALUES(s.btypeid,s.stypeid,s.total,s.ntotal,s.cid) ;
	END
			
	IF EXISTS(SELECT 1 FROM dbo.ListTable  WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@YS_ID)
	BEGIN
		MERGE INTO BType_ArApTotal ba
		USING(	SELECT AtypeId,BtypeId,STypeID,SUM(Total) AS total,SUM(Ntotal) AS ntotal,CID 
				FROM dbo.ListTable 
				WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@YS_ID
				GROUP BY AtypeId,BtypeId,STypeID,CID,BillNumberId
			)s
		ON ba.BTypeID=s.BtypeId AND ba.CID=s.CID AND ba.STypeID=s.STypeID
		WHEN MATCHED THEN UPDATE SET YSTotal+=s.Total,NYSTotal+=s.NTotal
		WHEN NOT MATCHED THEN  INSERT(BTypeID,STypeID,YSTotal,nYSTotal,cid)VALUES(s.btypeid,s.stypeid,s.total,s.ntotal,s.cid) ;
	END
 
	IF EXISTS(SELECT 1 FROM dbo.ListTable  WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@YF_ID)
	BEGIN
		MERGE INTO BType_ArApTotal ba
		USING(	SELECT AtypeId,BtypeId,STypeID,SUM(Total) AS total,SUM(Ntotal)AS ntotal,CID 
				FROM dbo.ListTable 
				WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@YF_ID
				GROUP BY AtypeId,BtypeId,STypeID,CID,BillNumberId
			)s
		ON ba.BTypeID=s.BtypeId AND ba.CID=s.CID AND ba.STypeID=s.STypeID
		WHEN MATCHED THEN UPDATE SET YFTotal+=s.Total,NYFTotal+=s.NTotal
		WHEN NOT MATCHED THEN  INSERT(BTypeID,STypeID,YFTotal,nYFTotal,cid)VALUES(s.btypeid,s.stypeid,s.total,s.ntotal,s.cid) ;
	END
		
	IF EXISTS(SELECT 1 FROM dbo.ListTable  WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@FC_id)
	BEGIN
		MERGE INTO BType_ArApTotal ba
		USING(	SELECT AtypeId,BtypeId,STypeID,SUM(Total) AS total,SUM(Ntotal)AS ntotal,CID 
				FROM dbo.ListTable 
				WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@FC_id
				GROUP BY AtypeId,BtypeId,STypeID,CID,BillNumberId
			)s
		ON ba.BTypeID=s.BtypeId AND ba.CID=s.CID AND ba.STypeID=s.STypeID
		WHEN MATCHED THEN UPDATE SET FCTotal+=s.Total,NFCTotal+=s.NTotal
		WHEN NOT MATCHED THEN  INSERT(BTypeID,STypeID,FCTotal,nFCTotal,cid)VALUES(s.btypeid,s.stypeid,s.total,s.ntotal,s.cid) ;
	END
		
	IF EXISTS(SELECT 1 FROM dbo.ListTable  WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@GRIR_ID)
	BEGIN
		MERGE INTO BType_ArApTotal ba
		USING(	SELECT AtypeId,BtypeId,STypeID,SUM(Total) AS total,SUM(Ntotal)AS ntotal,CID 
				FROM dbo.ListTable 
				WHERE BillNumberId=@nBillID AND BillType=@nBillType AND AtypeId=@GRIR_ID
				GROUP BY AtypeId,BtypeId,STypeID,CID,BillNumberId
			)s
		ON ba.BTypeID=s.BtypeId AND ba.CID=s.CID AND ba.STypeID=s.STypeID
		WHEN MATCHED THEN UPDATE SET GRIRTotal+=s.Total,NGRIRTotal+=s.NTotal
		WHEN NOT MATCHED THEN  INSERT(BTypeID,STypeID,GRIRTotal,nGRIRTotal,cid)VALUES(s.btypeid,s.stypeid,s.total,s.ntotal,s.cid) ;
	END
		
	--------------------------------------------品牌应收 begin --------------------------------
	IF NOT EXISTS(SELECT TOP 1 1 FROM  sysdata WHERE SubName='usebrandartype' AND SubValue='1')
	RETURN ;
	DECLARE @ExpenseToAr INT=0
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';

	CREATE TABLE #BrandarARAPTotal
	(
		BrandarTypeID VARCHAR(50),
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10),
		nYSTotal00  NUMERIC(24, 10) ,
		Total00		NUMERIC(24, 10) ,
		NTotal00	NUMERIC(24, 10),
		ARTotal NUMERIC(24, 10) ,
		YSTotal  NUMERIC(24, 10) ,
		nARTotal  NUMERIC(24, 10),
		nYSTotal  NUMERIC(24, 10) ,
		Total		NUMERIC(24, 10) ,
		NTotal	NUMERIC(24, 10)
	)

	INSERT INTO #BrandarARAPTotal
	(		
			BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			YSTotal00 ,
			nARTotal00 ,
			nYSTotal00,
			Total00,
			NTotal00,
			ARTotal,
			YSTotal,
			nARTotal ,
			nYSTotal,
			Total,
			NTotal
	)
	SELECT	BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(YSTotal00),
			SUM(nARTotal00),
			SUM(nYSTotal00),
			0,
			0,
			SUM(ARTotal),
			SUM(YSTotal),
			SUM(nARTotal),
			SUM(nYSTotal),
			0,
			0
			
	FROM
	(	--销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN s.taxtotal-s.CompleteTotal ELSE 0 END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN s.ntaxtotal-s.CompleteTotal ELSE 0 END  AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN s.taxtotal-s.CompleteTotal ELSE 0 END  AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN s.ntaxtotal-s.CompleteTotal ELSE 0 END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE  b.BillNumberId=@nBillID AND @nBillType=11
		UNION ALL      
		--组合品销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN s.taxtotal-s.CompleteTotal  ELSE 0 END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN s.ntaxtotal-s.NCompleteTotal ELSE 0 END AS nARTotal00 ,
				0 AS nYSTotal00,
				CASE WHEN b.IsIni=0 THEN s.taxtotal-s.CompleteTotal ELSE 0 END  AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN s.ntaxtotal-s.CompleteTotal ELSE 0 END  AS nARTotal ,
				0 AS nYSTotal  
			FROM dbo.PT_Combin_SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE  b.BillNumberId=@nBillID AND @nBillType=12
		UNION ALL
		--销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN  -(s.taxtotal-s.CompleteTotal) ELSE 0 END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN -(s.ntaxtotal-s.NCompleteTotal) ELSE 0 END  AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN  -(s.taxtotal-s.CompleteTotal) ELSE 0 END  AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN -(s.ntaxtotal-s.NCompleteTotal) ELSE 0 END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.salebackbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE b.BillNumberId=@nBillID AND @nBillType=45
		UNION ALL 
		--组合品销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN -(s.taxtotal-s.CompleteTotal) ELSE 0 END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN -(s.ntaxtotal-s.NCompleteTotal) ELSE 0 END AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN -(s.taxtotal-s.CompleteTotal) ELSE 0 END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN -(s.ntaxtotal-s.NCompleteTotal) ELSE 0 END AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.PT_Combin_SaleBackBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE  b.BillNumberId=@nBillID AND @nBillType=46 
		UNION ALL 
		--销售换货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN CASE WHEN s.InOrOut='O' THEN s.taxtotal-s.CompleteTotal
																 ELSE -(s.taxtotal-s.CompleteTotal) 
																 END	
									ELSE 0 
									END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN CASE WHEN s.InOrOut='O' THEN s.ntaxtotal-s.NCompleteTotal 
																ELSE -(s.ntaxtotal-s.NCompleteTotal) 
																 END	
									ELSE 0 
									END AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN CASE WHEN s.InOrOut='O' THEN s.taxtotal-s.CompleteTotal
																 ELSE -(s.taxtotal-s.CompleteTotal) 
																 END	 
									ELSE 0 
									END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN CASE WHEN s.InOrOut='O' THEN s.ntaxtotal-s.NCompleteTotal 
															 	 ELSE -(s.ntaxtotal-s.NCompleteTotal) 
																 END
									ELSE 0 
									END AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.salegoodsexchangebill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE  b.BillNumberId=@nBillID AND @nBillType=160 
		UNION ALL 
		--委托代销结算单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN  s.taxtotal-s.CompleteTotal ELSE 0 END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN  s.ntaxtotal-s.NCompleteTotal ELSE 0 END AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN  s.taxtotal-s.CompleteTotal ELSE 0 END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN  s.ntaxtotal-s.NCompleteTotal ELSE 0 END AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.commissionbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
		    INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1		
			WHERE b.BillNumberId=@nBillID AND @nBillType=141 
		UNION ALL 
		--销售发货开票
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN s.taxtotal-s.CompleteTotal ELSE 0 END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN s.ntaxtotal-s.NCompleteTotal ELSE 0 END AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN s.taxtotal-s.CompleteTotal ELSE 0 END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN s.ntaxtotal-s.NCompleteTotal ELSE 0 END AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.ReceiptBill s
			INNER JOIN  ReceiptBillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE  b.BillNumberId=@nBillID AND @nBillType=405 	
		UNION ALL 
		--期初预收款
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS  ARTotal00,
				CASE WHEN b.IsIni=1 THEN  s.total ELSE 0 END  AS YSTotal00 ,
				0 AS nARTotal00 ,
				CASE WHEN b.IsIni=1 THEN s.ntotal ELSE 0 END AS nYSTotal00 ,
				0 AS  ARTotal,
				CASE WHEN b.IsIni=0 THEN  s.total ELSE 0 END  AS YSTotal ,
				0 AS nARTotal ,
				CASE WHEN b.IsIni=0 THEN s.ntotal ELSE 0 END AS nYSTotal 
			FROM dbo.prebill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE  b.BillNumberId=@nBillID AND @nBillType=189 
			      AND ISNULL(B.NChargeOffTotal,0)=0 	
		UNION ALL 
		--应收增加单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN s.total-s.CompleteTotal ELSE 0 END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN s.ntotal-s.NCompleteTotal ELSE 0 END AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN s.total-s.CompleteTotal ELSE 0 END  AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN s.ntotal-s.NCompleteTotal ELSE 0 END AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt ON s.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE  b.BillNumberId=@nBillID AND @nBillType=116 				
		UNION ALL 
		--应收减少单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN  -(s.total-s.CompleteTotal) ELSE 0 END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN -(s.ntotal-s.NCompleteTotal) ELSE 0 END AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN  -(s.total-s.CompleteTotal) ELSE 0 END  AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN -(s.ntotal-s.NCompleteTotal) ELSE 0 END AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE b.BillNumberId=@nBillID AND @nBillType=115 
		UNION ALL 
		--其他收入单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN s.total ELSE 0 END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN s.NTotal ELSE 0 END AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN s.total ELSE 0 END  AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN s.NTotal ELSE 0 END AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE  b.BillNumberId=@nBillID AND @nBillType=93 
		UNION ALL 
		--费用单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN	CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
											 THEN -s.total
											 ELSE 0
											 END  
									ELSE 0 END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN b.IsIni=1 THEN	CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
											THEN -s.NTotal
											ELSE 0
											END
									ELSE 0 END   AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN b.IsIni=0 THEN	CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
											 THEN -s.total
											 ELSE 0
											 END  
									ELSE 0 END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN	CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
											THEN -s.NTotal
											ELSE 0
											END
									ELSE 0 END   AS nARTotal ,
				0 AS nYSTotal 
				
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1		
			WHERE  b.BillNumberId=@nBillID AND @nBillType=36	
		UNION ALL 
		--业务凭证
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.atypeid,
				S.CID,
				CASE  WHEN b.IsIni=1 AND s.TypeATypeID=33  THEN s.J_Total-s.D_Total ELSE 0 END ARTotal00,
				CASE  WHEN b.IsIni=1 AND s.TypeATypeID=39  THEN s.D_Total-s.J_Total ELSE 0 END YSTotal00,
				CASE  WHEN b.IsIni=1 AND s.TypeATypeID=33  THEN s.NJ_Total-s.ND_Total ELSE 0 END nARTotal00,
				CASE  WHEN b.IsIni=1 AND s.TypeATypeID=39  THEN s.ND_Total-s.NJ_Total ELSE 0 END nYSTotal00,
				CASE  WHEN s.TypeATypeID=33  THEN s.J_Total-s.D_Total ELSE 0 END ARTotal,
				CASE  WHEN s.TypeATypeID=39  THEN s.D_Total-s.J_Total ELSE 0 END YSTotal,
				CASE  WHEN s.TypeATypeID=33  THEN s.NJ_Total-s.ND_Total ELSE 0 END nARTotal,
				CASE  WHEN s.TypeATypeID=39  THEN s.ND_Total-s.NJ_Total ELSE 0 END nYSTotal
			FROM dbo.AccountCredence s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId	
			INNER JOIN btype bt on s.ATypeID=bt.typeid and bt. IsUseBrandarType=1	
			WHERE  b.BillNumberId=@nBillID AND @nBillType=159	
		UNION ALL
		--收款单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN -(s.total+s.PreferenceMoney) ELSE 0 END  AS  ARTotal00,
				CASE WHEN b.IsIni=1 AND s.AtypeId=@YS_ID THEN -(s.total) ELSE 0 END  AS YSTotal00 ,  --预收 不包含优惠
				CASE WHEN b.IsIni=1 THEN -(s.ntotal+s.NPreferenceMoney) ELSE 0 END AS nARTotal00 ,
				CASE WHEN b.IsIni=1 AND s.AtypeId=@YS_ID  THEN -(s.ntotal) ELSE 0 END AS nYSTotal00,
				CASE WHEN b.IsIni=0 THEN -(s.total+s.PreferenceMoney) ELSE 0 END  AS  ARTotal,
				CASE WHEN b.IsIni=0 AND s.AtypeId=@YS_ID THEN -(s.total) ELSE 0 END  AS YSTotal ,
				CASE WHEN b.IsIni=0 THEN -(s.ntotal+s.NPreferenceMoney) ELSE 0 END AS nARTotal ,
				CASE WHEN b.IsIni=0 AND s.AtypeId=@YS_ID THEN -(s.ntotal) ELSE 0 END AS nYSTotal
			FROM dbo.gatheringbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1		
			WHERE  b.BillNumberId=@nBillID AND @nBillType=4	
		UNION ALL 
		--多账户
		SELECT	s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.IsIni=1 THEN	CASE WHEN @nBillType IN (215,45,142,46)
											     THEN (s.PreferenceMoney+S.TotalInMoney+s.YSTotalInMoney)
												 WHEN @nBillType =36 THEN  CASE WHEN  s.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
																				THEN (s.PreferenceMoney+s.TotalInMoney+s.YSTotalInMoney )
																				ELSE 0
																				END 
												 ELSE -( s.PreferenceMoney+S.TotalInMoney+s.YSTotalInMoney )
											END 
									ELSE 0 END  AS  ARTotal00,
				CASE WHEN b.IsIni=1 THEN	CASE WHEN @nBillType IN (11,12,160,141,93,405) 
											THEN -(s.YSTotalInMoney  )
											ELSE s.YSTotalInMoney 
											END 
									ELSE 0 END  AS  ysTotal00 ,
				CASE WHEN b.IsIni=1 THEN	CASE WHEN @nBillType IN (215,45,142,46)
											     THEN (s.nPreferenceMoney+S.nTotalInMoney+s.nYSTotalInMoney)
												 WHEN @nBillType =36 THEN  CASE WHEN   s.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
																				THEN (s.nPreferenceMoney+s.nTotalInMoney+s.nYSTotalInMoney )
																				ELSE 0
																				END 
												 ELSE -( s.nPreferenceMoney+S.nTotalInMoney+s.nYSTotalInMoney )
											END 
									ELSE 0 END  AS nARTotal00 ,
				CASE WHEN b.IsIni=1 THEN	CASE WHEN @nBillType IN (11,12,160,141,93,405) 
											THEN -(s.NYSTotalInMoney  )
											ELSE s.NYSTotalInMoney 
											END 
									ELSE 0 END  AS  nysTotal00  ,
				CASE WHEN b.IsIni=0 THEN	CASE WHEN @nBillType IN (215,45,142,46)
											     THEN (s.PreferenceMoney+S.TotalInMoney+s.YSTotalInMoney)
												 WHEN @nBillType =36 THEN  CASE WHEN s.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
																				THEN (s.PreferenceMoney+s.TotalInMoney+s.YSTotalInMoney )
																				ELSE 0
																				END 
												 ELSE -( s.PreferenceMoney+S.TotalInMoney+s.YSTotalInMoney )
											END 
									ELSE 0 END  AS  ARTotal,
				CASE WHEN b.IsIni=0 THEN	CASE WHEN @nBillType IN (11,12,160,141,93,405) 
											THEN -(s.YSTotalInMoney  )
											ELSE s.YSTotalInMoney 
											END 
									ELSE 0 END  AS  ysTotal ,
				CASE WHEN b.IsIni=0 THEN	CASE WHEN @nBillType IN (215,45,142,46)
											     THEN (s.nPreferenceMoney+S.nTotalInMoney+s.nYSTotalInMoney)
												 WHEN @nBillType =36  THEN  CASE WHEN s.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
																				 THEN (s.nPreferenceMoney+s.nTotalInMoney+s.nYSTotalInMoney )
																				 ELSE 0
																				 END 
												 ELSE -( s.nPreferenceMoney+S.nTotalInMoney+s.nYSTotalInMoney )
											END  
									ELSE 0 END  AS nARTotal ,
				CASE WHEN b.IsIni=0 THEN	CASE WHEN @nBillType IN (11,12,160,141,93,405) 
											THEN -(s.NYSTotalInMoney  )
											ELSE s.NYSTotalInMoney 
											END 
									ELSE 0 END  AS  nysTotal 
			FROM BillMulBrand s
			INNER JOIN BILLINDEX B ON s.billnumberid=b.billnumberid
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE s.BillNumberId=@nBillID 
				   AND s.billtype=@nBillType
				   AND  s.BillType  NOT IN (305,215)
				UNION ALL 
		--多账户
		SELECT	s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0   AS  ARTotal00,
				CASE WHEN b.IsIni=1 THEN	CASE WHEN @nBillType IN (305) 
											THEN -(s.YSTotalInMoney  )
											ELSE s.YSTotalInMoney 
											END 
									ELSE 0 END  AS  ysTotal00 ,
				0 AS nARTotal00 ,
				CASE WHEN b.IsIni=1 THEN	CASE WHEN @nBillType IN (305) 
											THEN -(s.NYSTotalInMoney  )
											ELSE s.NYSTotalInMoney 
											END 
									ELSE 0 END  AS  nysTotal00  ,
				0 AS  ARTotal,
				CASE WHEN b.IsIni=0 THEN	CASE WHEN @nBillType IN (305) 
											THEN -(s.YSTotalInMoney  )
											ELSE s.YSTotalInMoney 
											END 
									ELSE 0 END  AS  ysTotal ,
				0 AS nARTotal ,
				CASE WHEN b.IsIni=0 THEN	CASE WHEN @nBillType IN (305) 
											THEN -(s.NYSTotalInMoney  )
											ELSE s.NYSTotalInMoney 
											END 
									ELSE 0 END  AS  nysTotal 
			FROM BillMulBrand s
			INNER JOIN BILLINDEX B ON s.billnumberid=b.billnumberid
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE s.BillNumberId=@nBillID 
				   AND s.billtype=@nBillType
				   AND  s.BillType   IN (305,215)
		UNION ALL 
		--品牌结算
		SELECT	s.BrandarTypeID,
				s.stypeid,
				s.btypeid,
				s.cid,
				CASE WHEN s.IsIni=1 THEN	CASE WHEN @nBillType IN (11,12,160,141,93,405) 
											THEN -s.CompleteTotal
											ELSE s.CompleteTotal 
											END  
									ELSE 0 END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN s.IsIni=1 THEN	CASE WHEN @nBillType IN (11,12,160,141,93,405) 
											THEN -s.NCompleteTotal
											ELSE s.NCompleteTotal
											END 
									ELSE 0 END  AS nARTotal00 ,
				0 AS nYSTotal00 ,
				CASE WHEN s.IsIni=0 THEN	CASE WHEN @nBillType IN (11,12,160,141,93,405) 
											THEN -s.CompleteTotal
											ELSE s.CompleteTotal 
											END  
									ELSE 0 END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN s.IsIni=0 THEN	CASE WHEN @nBillType IN (11,12,160,141,93,405) 
											THEN -s.NCompleteTotal
											ELSE s.NCompleteTotal
											END 
									ELSE 0 END  AS nARTotal ,
				0 AS nYSTotal
			FROM CompleteBrandarTotal s
				INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE s.GoodsBillID=@nBillID 
				   AND s.billtype=@nBillType
				   AND S.isdraft=0  --不是草稿的
				   
	)total
	GROUP BY BrandarTypeID,stypeid,btypeid,cid
	
	DELETE FROM #BrandarARAPTotal WHERE YSTotal00=0  AND ARTotal00=0  AND nYSTotal00=0 AND nARTotal=0 AND YSTotal=0  AND ARTotal=0  AND nYSTotal=0 AND nARTotal=0
	
	
	-- 写入 brandar_ArApTotal 期初
	UPDATE a SET 
		a.ARTotal00=ISNULL(a.ARTotal00,0)-ISNULL(b.ARTotal00,0),
		a.YSTotal00=ISNULL(a.YSTotal00,0)-ISNULL(b.YSTotal00,0),
		a.nARTotal00=ISNULL(a.nARTotal00,0)-ISNULL(b.nARTotal00,0),
		a.nYSTotal00=ISNULL(a.nYSTotal00,0)-ISNULL(b.nYSTotal00,0),
		a.ARTotal=ISNULL(a.ARTotal,0)-ISNULL(b.ARTotal,0),
		a.YSTotal=ISNULL(a.YSTotal,0)-ISNULL(b.YSTotal,0),
		a.nARTotal=ISNULL(a.nARTotal,0)-ISNULL(b.nARTotal,0),
		a.nYSTotal=ISNULL(a.nYSTotal,0)-ISNULL(b.nYSTotal,0)
		
	FROM dbo.brandar_ArApTotal a JOIN #BrandarARAPTotal b 
	ON a.stypeid=b.stypeid AND a.btypeid=b.btypeid AND a.CID=b.cid and a.BrandarTypeID=b.BrandarTypeID
	
	INSERT INTO brandar_ArApTotal(
		BTypeID,
		STypeID,
		BrandarTypeID,
		CID,
		ARTotal,
		YSTotal,
		ARTotal00,
		YSTotal00,
		nARTotal,
		nYSTotal,
		nARTotal00,
		nYSTotal00

	) SELECT 
		b.btypeId,
		b.stypeid,
		B.BrandarTypeID,
		b.cid,
		-b.ARTotal,
		-b.YSTotal,
		-b.ARTotal00,
		-b.YSTotal00,
		-b.nARTotal,
		-b.YSTotal,
		-b.nARTotal00,
		-b.nYSTotal00
	FROM #BrandarARAPTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM brandar_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid AND a.BrandarTypeID=b.BrandarTypeID)

	DELETE  FROM brandar_ArApTotal WHERE ISNULL(ARTotal,0)=0 AND ISNULL(YSTotal,0)=0 
	AND ISNULL(ARTotal00,0)=0  AND ISNULL(YSTotal00,0)=0 
	AND ISNULL(nARTotal,0)=0  AND ISNULL(NYSTotal,0)=0 
	AND ISNULL(NARTotal00,0)=0 AND ISNULL(NYSTotal00,0)=0 
	
	DROP TABLE #BrandarARAPTotal;	
END


IF @@error <> 0
	RETURN -1
ELSE
	RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





--
--		过账后修改单据--单据状态
--
GO
	IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_ModifyBill_Common_GetDetailState',N'P'))
	BEGIN
		DROP PROC GP_ModifyBill_Common_GetDetailState
	END
GO

CREATE PROC GP_ModifyBill_Common_GetDetailState
(
	@BillNumberID INT,
	@DetailID     INT,
	@BillType INT	
)
AS
BEGIN
	DECLARE @BillState TABLE([State] INT);
	--采购入库单
	IF @BillType=34
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal A INNER JOIN dbo.BillIndex B ON A.MoneyBillID=B.BillNumberId AND B.RedWord=0
				  WHERE GoodsBillID=@BillNumberID AND A.BillType=@BillType AND Billid=@DetailID)
			INSERT INTO @BillState(State) SELECT 2		--按商品结算
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID AND RecordedItemId=@DetailID)
			INSERT INTO @BillState(State) SELECT 3		--采购发票调用 
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BuyBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE OldBillNumberID=@BillNumberID AND OldID=@DetailID)
			INSERT INTO @BillState(State) SELECT 4		--采购退货单调用
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BuyGoodsExchangeBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE OldBillNumberID=@BillNumberID AND OldID=@DetailID)
			INSERT INTO @BillState(State) SELECT 5		--采购换货
	END
	--采购退货单
	ELSE IF @BillType=6
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BuyBackBill WHERE OldBillNumberID>0 AND OldID=@DetailID AND BillNumberId=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 6		--引用采购入库单
	
		IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal A INNER JOIN dbo.BillIndex B ON A.MoneyBillID=B.BillNumberId AND B.RedWord=0 
				  WHERE GoodsBillID=@BillNumberID AND A.BillType=@BillType AND Billid=@DetailID)
			INSERT INTO @BillState(State) SELECT 2		--按商品结算  
		 
		IF EXISTS(SELECT 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID AND RecordedItemId=@DetailID)
			INSERT INTO @BillState(State) SELECT 3		--采购发票调用
	END
	--销售出库单
	ELSE IF @BillType=11
	BEGIN
			
		IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal A INNER JOIN dbo.BillIndex B ON A.MoneyBillID=B.BillNumberId AND B.RedWord=0
				  WHERE GoodsBillID=@BillNumberID AND A.BillType=@BillType AND Billid=@DetailID)
			INSERT INTO @BillState(State) SELECT 2		--按商品结算  
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID AND RecordedItemId=@DetailID)
			INSERT INTO @BillState(State) SELECT 7		-- 销售发票调用 
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleGoodsExchangeBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE OldID=@DetailID AND OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 9		--销售换货调用
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.OldID=@DetailID)
			INSERT INTO @BillState(State) SELECT 8		--销售退货调用
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleBill WHERE PromoType=1 AND ID=@DetailID)
			INSERT INTO @BillState(State) SELECT 10		--促销
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleBill WHERE PriceStyle=1 AND ID=@DetailID)
			INSERT INTO @BillState(State) SELECT 11		--高价
	END
	--销售退货单
	ELSE IF @BillType=45
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal A INNER JOIN dbo.BillIndex B ON A.MoneyBillID=B.BillNumberId AND B.RedWord=0
				  WHERE GoodsBillID=@BillNumberID AND A.BillType=@BillType AND Billid=@DetailID)
			INSERT INTO @BillState(State) SELECT 2		--按商品结算  
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID AND RecordedItemId=@DetailID)
			INSERT INTO @BillState(State) SELECT 7		-- 销售发票调用 
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.saleBackBill WHERE OldBillNumberID>0 AND BillNumberId=@BillNumberID AND OldID=@DetailID)
			INSERT INTO @BillState(State) SELECT 12		--引用销售出库单

	END
	--收付款单
	ELSE IF @BillType IN(4,66)
		INSERT INTO @BillState(State) SELECT 1
	--暂估入库单
	ELSE IF @BillType=400
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID AND B.RedWord=0
				  WHERE MainBillNumberID=@BillNumberID AND RecordedItemID=@DetailID AND MainBillType=@BillType)
			INSERT INTO @BillState(State) SELECT 13		--暂估开票调用
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.AppraisalBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
			      WHERE OldID=@DetailID AND OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 14		--暂估退货调用
	END
	--暂估退货单
	ELSE IF @BillType=401
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID AND B.RedWord=0
				  WHERE MainBillNumberID=@BillNumberID AND RecordedItemId=@DetailID AND MainBillType=@BillType)
			INSERT INTO @BillState(State) SELECT 13		--暂估开票调用

	END
	--发出商品出库单
	ELSE IF @BillType=402
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SendBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 16		--已被发出商品退货单调用
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID AND B.RedWord=0
				  WHERE MainBillNumberID=@BillNumberID AND MainBillType=@BillType)
			INSERT INTO @BillState(State) SELECT 15		--已被销售发货开票调用
	END
	--发出商品退货单
	ELSE IF @BillType=403
	BEGIN
	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID AND B.RedWord=0
				  WHERE MainBillNumberID=@BillNumberID AND RecordedItemId=@DetailID AND MainBillType=@BillType)
			INSERT INTO @BillState(State) SELECT 15		--销售发货开票调用
	END
	--采购/销售开票
	ELSE IF @BillType=404
	BEGIN
			
		IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal A INNER JOIN dbo.BillIndex B ON A.MoneyBillID=B.BillNumberId AND B.RedWord=0
				  WHERE GoodsBillID=@BillNumberID AND A.BillType=@BillType AND Billid=@DetailID)
			INSERT INTO @BillState(State) SELECT 2		--按商品结算  

	END
	
	ELSE IF @BillType=405
	BEGIN

		IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal A INNER JOIN dbo.BillIndex B ON A.MoneyBillID=B.BillNumberId AND B.RedWord=0
				  WHERE GoodsBillID=@BillNumberID AND A.BillType=@BillType AND Billid=@DetailID)
			INSERT INTO @BillState(State) SELECT 2		--按商品结算 
	END
	--组合品销售出库单
	ELSE IF @BillType=12
	BEGIN
			
		IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal A INNER JOIN dbo.BillIndex B ON A.MoneyBillID=B.BillNumberId AND B.RedWord=0
				  WHERE GoodsBillID=@BillNumberID AND A.BillType=@BillType )
			INSERT INTO @BillState(State) SELECT 2		--按商品结算  
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID AND RecordedItemId=@DetailID)
			INSERT INTO @BillState(State) SELECT 7		-- 销售发票调用 
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBackBillDetail A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.OldID=@DetailID)
			INSERT INTO @BillState(State) SELECT 8		--销售退货调用
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBill WHERE PromoType=1 AND ID=@DetailID)
			INSERT INTO @BillState(State) SELECT 10		--促销
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBill WHERE PriceStyle=1 AND ID=@DetailID)
			INSERT INTO @BillState(State) SELECT 11		--高价
	END
	--组合品销售退货单
	ELSE IF @BillType=46
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM CompleteGoodTotal A INNER JOIN dbo.BillIndex B ON A.MoneyBillID=B.BillNumberId AND B.RedWord=0
				  WHERE GoodsBillID=@BillNumberID AND A.BillType=@BillType AND Billid=@DetailID)
			INSERT INTO @BillState(State) SELECT 2		--按商品结算  
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID AND RecordedItemId=@DetailID)
			INSERT INTO @BillState(State) SELECT 7		-- 销售发票调用 
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBackBill WHERE OldBillNumberID>0 AND BillNumberId=@BillNumberID AND OldID=@DetailID)
			INSERT INTO @BillState(State) SELECT 12		--引用销售出库单

	END
	SELECT State FROM @BillState
END

GO



--
--		过账后修改单据--单据状态
--
GO
	IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_ModifyBill_Common_GetState',N'P'))
	BEGIN
		DROP PROC GP_ModifyBill_Common_GetState
	END
GO


CREATE PROC GP_ModifyBill_Common_GetState
(
	@BillNumberID INT,
	@BillType INT	
)
AS
BEGIN
	DECLARE @BillState TABLE([State] INT);
	
	IF @BillType NOT IN(404,405) AND EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@billNumberID AND NewPosBill=1)
	BEGIN
		RAISERROR('您所需修改的单据是POS小票上传的单据，不允许修改！',16,1)
	END
	
	IF EXISTS(
		SELECT TOP 1 1 FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId
		WHERE RedWord=0 AND a.FromBillNumberID=@BillNumberID AND a.FromBillType=@BillType
	)
		RAISERROR('该单据已被实物出/入库单引用，不能修改！',16,1)
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND ShelveRefState<>0)
		RAISERROR('该单据已被上架单引用，不能修改！',16,1)
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND citestate<>0)
		RAISERROR('该单据已被拣货单引用，不能修改！',16,1)
	
	IF EXISTS(
		SELECT BillNumberID	FROM BillIndex	WHERE BillNumberID=@BillNumberID AND BillType=@BillType AND CWCheck=1	
	)
		RAISERROR('该单据已财务审核，不能修改！',16,1)
	
	IF @BillType=57
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.AdPriceBill WHERE BillNumberId=@BillNumberID AND FromBillType=404)
		BEGIN
			RAISERROR('自动生成的入库类成本调价单不能修改！',16,1)
		END
		ELSE
		BEGIN
			DECLARE @costing VARCHAR(50)
			SELECT @costing=SubValue FROM dbo.sysdata WHERE SubName='costing'
			IF @costing='0' AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND UF1='usechange' )
			BEGIN
				RAISERROR('移动加权成本算法下系统升级前的成本调价单不能修改！',16,1)
			END
		END
	END
	--采购入库单
	ELSE IF @BillType=34
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='1'
				  UNION ALL 
				  SELECT TOP 1 1 FROM dbo.ChargeOffBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId 
				  WHERE A.FromBillNumberid=@BillNumberID AND B.RedWord=0)
			INSERT INTO @BillState(State) SELECT 2		--按单结算/往来核销
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteGoodTotal A WHERE GoodsBillID=@BillNumberID AND BillType=@BillType AND Draft=1)
			RAISERROR('您所需全面修改的采购入库单存在对应的按商品结算的付款单草稿，不允许修改单据，请先删除对应付款单草稿或者清除草稿按商品结算过程后，再进行修改！',16,1)
				
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='2')
			INSERT INTO @BillState(State) SELECT 3			--按商品结算
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 4		--采购发票调用 
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BuyBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberID=B.BillNumberId AND B.RedWord=0
				  WHERE OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 5		--采购退货单调用
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BuyGoodsExchangeBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 6		--采购换货
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ShareSourceBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.FromBillNumberID=@BillNumberID AND FromBillType=@BillType)
		BEGIN
			RAISERROR('您所需修改的采购入库单已做采购费用分摊，不能修改单据，如需修改请先删除或红冲对应的费用分摊单后再修改！',16,1)
			INSERT INTO @BillState(State) SELECT 7		--费用分摊
		END
		IF NOT EXISTS(SELECT 1 FROM @BillState)
			INSERT INTO @BillState(State) SELECT 1
			       
	END
	--采购退货单
	ELSE IF @BillType=6
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BuyBackBill WHERE OldBillNumberID>0 AND BillNumberId=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 2		--引用采购入库单
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='1'
				  UNION ALL 
				  SELECT TOP 1 1 FROM dbo.ChargeOffBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.FromBillNumberid=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 3		--按单结算/往来核销
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteGoodTotal A WHERE GoodsBillID=@BillNumberID AND BillType=@BillType AND Draft=1)
			RAISERROR('您所需全面修改的采购退货单存在对应的按商品结算的付款单草稿，不允许修改单据，请先删除对应付款单草稿或者清除草稿按商品结算过程后，再进行修改！',16,1)
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='2')
			INSERT INTO @BillState(State) SELECT 4		--按商品结算  
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 5		--采购发票调用
			
		IF NOT EXISTS(SELECT 1 FROM @BillState)
			INSERT INTO @BillState(State) SELECT 1
	END
	--销售出库单
	ELSE IF @BillType=11
	BEGIN
	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='1'
				  UNION ALL 
				  SELECT TOP 1 1 FROM dbo.ChargeOffBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0 
				  WHERE A.FromBillNumberid=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 2		--按单结算/往来核销
   	    
   	    IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteGoodTotal A WHERE GoodsBillID=@BillNumberID AND BillType=@BillType AND Draft=1)
			RAISERROR('您所需全面修改的销售出库单存在对应的按商品结算的收款单草稿，不允许修改单据，请先删除对应收款单草稿或者清除草稿按商品结算过程后，再进行修改！',16,1)
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex A LEFT JOIN PerformanceDistribution B ON A.BillNumberId=B.BillNumberId 
			      WHERE A.BillNumberId=@BillNumberID AND A.RedWord=0 AND ISNULL(B.Total,0)<>0)
			RAISERROR('您所需修改的单据，已进行了业绩分配，不能直接修改，如需修改请先清除本单业绩分配后再进行修改！',16,1)

		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='2')
			INSERT INTO @BillState(State) SELECT 3		--按商品结算	
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 4		-- 销售发票调用 
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.saleBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0 WHERE OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 5
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleGoodsExchangeBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 6		--销售换货调用
			
		IF EXISTS(SELECT 1 FROM dbo.ShareSourceBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.FromBillNumberID=@BillNumberID AND FromBillType=@BillType)
		BEGIN
			RAISERROR('您所需修改的销售出库单已做销售费用分摊，不能修改单据，如需修改请先删除或红冲对应的费用分摊单后再修改！',16,1)
			INSERT INTO @BillState(State) SELECT 7		--费用分摊
		END
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleBill WHERE PromoType=1 AND BillNumberId=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 8		--促销
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleBill WHERE PriceStyle=1 AND BillNumberId=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 9		--高价
		
		IF NOT EXISTS(SELECT 1 FROM @BillState)
			INSERT INTO @BillState(State) SELECT 1
	END
	--销售退货单
	ELSE IF @BillType=45
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='1'
				  UNION ALL 
				  SELECT TOP 1 1 FROM dbo.ChargeOffBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.FromBillNumberid=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 1		--按单结算/往来核销
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteGoodTotal A WHERE GoodsBillID=@BillNumberID AND BillType=@BillType AND Draft=1)
			RAISERROR('您所需全面修改的销售退货单存在对应的按商品结算的收款单草稿，不允许修改单据，请先删除对应收款单草稿或者清除草稿按商品结算过程后，再进行修改！',16,1)
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex A LEFT JOIN PerformanceDistribution B ON A.BillNumberId=B.BillNumberId 
			      WHERE A.BillNumberId=@BillNumberID AND A.RedWord=0 AND ISNULL(B.Total,0)<>0)
			RAISERROR('您所需修改的单据，已进行了业绩分配，不能直接修改，如需修改请先清除本单业绩分配后再进行修改！',16,1)

		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='2')
			INSERT INTO @BillState(State) SELECT 2		--按商品结算	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 3		--销售发票调用
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.saleBackBill WHERE OldBillNumberID>0 AND BillNumberId=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 4		--引用销售出库单
	END
	--收付款单
	ELSE IF @BillType =4
	BEGIN
	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteTotal WHERE MoneyBillID=@BillNumberID AND Draft=0)
			RAISERROR('您所需修改的收款单进行了按单/按商品/按品牌 结算，不允许修改，请先清除本收款单的结算过程后，再进行修改！',16,1)
		INSERT INTO @BillState(State) SELECT 1
	END
	ELSE IF @BillType=66
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteTotal WHERE MoneyBillID=@BillNumberID AND Draft=0)
			RAISERROR('您所需修改的付款单进行了按单/按商品结算，不允许修改，请先清除本付款单的结算过程后，再进行修改！',16,1)
		INSERT INTO @BillState(State) SELECT 1
	END
	ELSE IF @BillType=57
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberID=@BillnumberID AND ktypeid='00000' AND RedWord=0 AND ifcheck='t')
		BEGIN
			RAISERROR('您所需修改的成本调价单为“调整全部仓库”，不允许修改！请确认后重试！',16,1)
		END
	END
	--暂估入库单
	ELSE IF @BillType=400
	BEGIN
		--暂估开票调用
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID AND B.RedWord=0
				  WHERE MainBillNumberID=@BillNumberID AND MainBillType=@BillType)
			RAISERROR('您所要修改的暂估入库单已存在有对应的采购暂估发票，不能修改，请删除或红冲采购暂估发票后再试！',16,1)
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.AppraisalBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 3		--暂估退货调用
		
		IF NOT EXISTS(SELECT 1 FROM @BillState)
			INSERT INTO @BillState(State) SELECT 1
	END
	--暂估退货单
	ELSE IF @BillType=401
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID AND B.RedWord=0
				  WHERE MainBillNumberID=@BillNumberID AND MainBillType=@BillType)
			RAISERROR('您所要修改的暂估退货单已存在有对应的采购暂估发票，不能修改，请删除或红冲采购暂估发票后再试！',16,1)
		
		IF NOT EXISTS(SELECT 1 FROM @BillState)
			INSERT INTO @BillState(State) SELECT 1
	END
	--发出商品出库单
	ELSE IF @BillType=402
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.SendBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND b.RedWord=0
				  WHERE OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 2		--已被发出商品退货单调用
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID AND B.RedWord=0
				  WHERE MainBillNumberID=@BillNumberID AND MainBillType=@BillType)
				  BEGIN
				    RAISERROR('您所要修改的发出商品出库单已存在有对应的销售发货发票，不能修改，请删除或红冲销售发货发票后再试！',16,1)
			        INSERT INTO @BillState(State) SELECT 3
			      END
		
		IF NOT EXISTS(SELECT 1 FROM @BillState)
			INSERT INTO @BillState(State) SELECT 1
	END
	--发出商品退货单
	ELSE IF @BillType=403
	BEGIN
	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID AND B.RedWord=0
				  WHERE MainBillNumberID=@BillNumberID AND MainBillType=@BillType)
				  BEGIN
				    RAISERROR('您所要修改的发出商品退货单已存在有对应的销售发货发票，不能修改，请删除或红冲销售发货发票后再试！',16,1)
			        INSERT INTO @BillState(State) SELECT 1
			      END
	END
	--采购/销售开票
	ELSE IF @BillType=404
	BEGIN
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.AdPriceBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.FromBillNumberID=@BillNumberID AND FromBillType=@BillType)
			INSERT INTO @BillState(State) SELECT 1		--已有对应成本调价单
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@BillNumberID AND BillType=@BillType AND JSStyle=1)
			INSERT INTO @BillState(State) SELECT 2		--按单结算
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteGoodTotal A WHERE GoodsBillID=@BillNumberID AND BillType=@BillType AND Draft=1)
			RAISERROR('您所需全面修改的采购暂估开票存在对应的按商品结算的付款单草稿，不允许修改单据，请先删除对应付款单草稿或者清除草稿按商品结算过程后，再进行修改！',16,1)

		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@BillNumberID AND BillType=@BillType AND JSStyle=2)
			INSERT INTO @BillState(State) SELECT 3		--按商品结算
	END
	
	ELSE IF @BillType=405
	BEGIN
	
		--IF EXISTS(SELECT TOP 1 1 FROM dbo.AdPriceBill WHERE FromBillNumberID=@BillNumberID AND FromBillType=@BillType)
		--	RETURN 2		--已有对应成本调价单
			
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@BillNumberID AND BillType=@BillType AND JSStyle=1)
			INSERT INTO @BillState(State) SELECT 1		--按单结算
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteGoodTotal A WHERE GoodsBillID=@BillNumberID AND BillType=@BillType AND Draft=1)
			RAISERROR('您所需全面修改的销售发货开票存在对应的按商品结算的收款单草稿，不允许修改单据，请先删除对应收款单草稿或者清除草稿按商品结算过程后，再进行修改！',16,1)
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex WHERE BillNumberID=@BillNumberID AND BillType=@BillType AND JSStyle=2)
			INSERT INTO @BillState(State) SELECT 2		--按商品结算
	END
	--组合品销售出库单
	ELSE IF @BillType=12
	BEGIN
	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='1'
				  UNION ALL 
				  SELECT TOP 1 1 FROM dbo.ChargeOffBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0 
				  WHERE A.FromBillNumberid=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 2		--按单结算/往来核销
   	    
   	    IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteGoodTotal A WHERE GoodsBillID=@BillNumberID AND BillType=@BillType AND Draft=1)
			RAISERROR('您所需全面修改的组合品销售出库单存在对应的按商品结算的收款单草稿，不允许修改单据，请先删除对应收款单草稿或者清除草稿按商品结算过程后，再进行修改！',16,1)
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex A LEFT JOIN PerformanceDistribution B ON A.BillNumberId=B.BillNumberId 
			      WHERE A.BillNumberId=@BillNumberID AND A.RedWord=0 AND ISNULL(B.Total,0)<>0)
			RAISERROR('您所需修改的单据，已进行了业绩分配，不能直接修改，如需修改请先清除本单业绩分配后再进行修改！',16,1)

		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='2')
			INSERT INTO @BillState(State) SELECT 3		--按商品结算	
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 4		-- 销售发票调用 
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0 WHERE OldBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 5
			
		IF EXISTS(SELECT 1 FROM dbo.ShareSourceBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.FromBillNumberID=@BillNumberID AND FromBillType=@BillType)
		BEGIN
			RAISERROR('您所需修改的组合品销售出库单已做销售费用分摊，不能修改单据，如需修改请先删除或红冲对应的费用分摊单后再修改！',16,1)
			INSERT INTO @BillState(State) SELECT 7		--费用分摊
		END
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBill WHERE PromoType=1 AND BillNumberId=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 8		--促销
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBill WHERE PriceStyle=1 AND BillNumberId=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 9		--高价
		
		IF NOT EXISTS(SELECT 1 FROM @BillState)
			INSERT INTO @BillState(State) SELECT 1
	END
		--组合品销售退货单
	ELSE IF @BillType=46
	BEGIN		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='1'
				  UNION ALL 
				  SELECT TOP 1 1 FROM dbo.ChargeOffBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0
				  WHERE A.FromBillNumberid=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 1		--按单结算/往来核销
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CompleteGoodTotal A WHERE GoodsBillID=@BillNumberID AND BillType=@BillType AND Draft=1)
			RAISERROR('您所需全面修改的组合品销售退货单存在对应的按商品结算的收款单草稿，不允许修改单据，请先删除对应收款单草稿或者清除草稿按商品结算过程后，再进行修改！',16,1)
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex A LEFT JOIN PerformanceDistribution B ON A.BillNumberId=B.BillNumberId 
			      WHERE A.BillNumberId=@BillNumberID AND A.RedWord=0 AND ISNULL(B.Total,0)<>0)
			RAISERROR('您所需修改的单据，已进行了业绩分配，不能直接修改，如需修改请先清除本单业绩分配后再进行修改！',16,1)

		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberID AND BillType=@BillType AND jsStyle='2')
			INSERT INTO @BillState(State) SELECT 2		--按商品结算	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.FaPiaoBill WHERE MainBillNumberID=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 3		--销售发票调用
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBackBill WHERE OldBillNumberID>0 AND BillNumberId=@BillNumberID)
			INSERT INTO @BillState(State) SELECT 4		--引用组合品销售出库单
	END
	SELECT State FROM @BillState
END
GO



/*
**			单据全面修改 总账凭证验证
*/
GO
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_ModifyBill_VoucherCheck',N'P'))
BEGIN
	DROP PROC GP_ModifyBill_VoucherCheck
END
GO

CREATE PROC GP_ModifyBill_VoucherCheck
(
	@BillNumberID INT,
	@BillType	  INT
)
AS
BEGIN

	IF @BillType=311 AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_CommissionBill_VoucherBill WHERE GoodsBillId=@BillNumberID AND VourchBillId<>-1)
		RETURN -1			--已有总账凭证
	
	IF @BillType IN(404,405)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=@BillNumberID AND VourchBillId<>-1)
			RETURN -1
		IF EXISTS(SELECT TOP 1 1 FROM dbo.AdPriceBill A 
				  INNER JOIN dbo.Ac_GoodsBill_VoucherBill B 
				  ON A.BillNumberId=B.GoodsBillId 
				  AND FromBillNumberID=@BillNumberID 
				  AND FromBillType=@BillType
				  )
			RETURN -2
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_GoodsBill_VoucherBill A INNER JOIN dbo.BillIndex B ON A.GoodsBillId=B.BillNumberId
			 WHERE B.BillNumberId=@BillNumberID AND BillType=@BillType  AND VourchBillId<>-1)
		RETURN -1			--已有总账凭证
	RETURN 0
END
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：杨俊
	日期：2014-05-20
	描述：提成方案--审核、反审核、禁用、启用
-------------------------------------------*/
CREATE PROCEDURE Gp_ModifyCommissionSchemeStatus
(
	@BillNumberId  INT,	--单据ID
	@Type		   INT,	--修改类型,1 - 审核、2 - 反审核、3 - 禁用、4 - 启用
	@OperatorID	   VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
-----------------------------------------------------------------------------------------------------------------------------
DECLARE @RowCount int
----当前时间
--DECLARE @DATE VARCHAR(20)
--SET @DATE = CONVERT(VARCHAR(100), GETDATE(), 23)

IF(@Type = 1)
BEGIN
	----【服务器当前系统日期】大于【执行截止时间】时：执行时间不是有效时间，不能审核
	--IF((SELECT SchemeEnd FROM CommissionScheme WHERE BillNumberId = @BillNumberId) < @DATE)
	--	RETURN -2
	--已审核的单据不能重复审核
	IF((SELECT BillState FROM CommissionScheme WHERE BillNumberId = @BillNumberId) = 2)
		RETURN -3
	
	UPDATE CommissionScheme SET BillState = 2,Checker = @OperatorID,CheckerTime = CONVERT(DATE,GETDATE()) 
	WHERE BillNumberId = @BillNumberId
	SET @RowCount = @@rowcount
	IF @RowCount = 0 
		RETURN -1
END
ELSE IF(@Type = 2)
BEGIN
	IF((SELECT TOP 1 1 FROM CommissionScheme WHERE BillNumberId = @BillNumberId AND BillState = 2) = 1)
	BEGIN
		UPDATE CommissionScheme SET BillState = 1,Checker = '',CheckerTime = NULL 
		WHERE BillNumberId = @BillNumberId
		SET @RowCount = @@rowcount
		IF @RowCount = 0 
			RETURN -1
	END
	ELSE
		RETURN -2
END
ELSE IF(@Type = 3)
BEGIN
	IF((SELECT TOP 1 1 FROM CommissionScheme WHERE BillNumberId = @BillNumberId AND BillState = 2) = 1)
	BEGIN
		UPDATE CommissionScheme SET IsStop = BillState,BillState = 3 WHERE BillNumberId = @BillNumberId
		SET @RowCount = @@rowcount
		IF @RowCount = 0 
			RETURN -1
	END
	ELSE
		RETURN -2
END
ELSE IF(@Type = 4)
BEGIN
	IF((SELECT TOP 1 1 FROM CommissionScheme WHERE BillNumberId = @BillNumberId AND BillState = 3) = 1)
	BEGIN
		UPDATE CommissionScheme SET BillState = IsStop,IsStop = 0 WHERE BillNumberId = @BillNumberId
		SET @RowCount = @@rowcount
		IF @RowCount = 0 
			RETURN -1
	END
	ELSE
		RETURN -2
END
-----------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ModifyDbf]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_ModifyDbf]
GO
/****** Object:  StoredProcedure [dbo].[Gp_ModifyDbf]    Script Date: 11/01/2012 15:13:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
	功能说明：	成本核算，三种算法；修改期初；修改BType对应往来余额
	作    者：	卢  春
	最后修改：	2004-06-09
	
	修改人:冯波   2017-03-24  修改先进先出,后进先出在对有成本价的出库的逻辑,能准确取到这个成本,就不去取近似这个成本的批次  对应9.8稳定版本的BUG 60
*/
CREATE     PROCEDURE [dbo].[Gp_ModifyDbf] 
(
	@nVchType			numeric(4, 0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szSTypeID			varchar(50),			--分支机构
	@szPeriod			varchar(2),				-- 8. 期号 (暂时不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
	@dntotal			 NUMERIC(24, 10) ,			-- 23. 原币成本金额
	@cid				INT,					-- 24.币别
	@szJobNo			varchar(20),			-- 11. (暂时不用)
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10) ,			-- 16. 批次成本单价
	@HandZeroCost		int,					-- 17. 是否为手工输入0成本标志
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 18. 成本单价 (输出)
	@ModifyAuditBill	int=0,					-- 0表示正常单据，1表示修改过账后单据
	@MakeDate			datetime = null,		-- 19. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0		-- 20. (暂时不用)
	--@ValidDate		varchar(50),			-- 21. 有效期至(手工指定)
	--@GoodsBTypeID		varchar(50)				-- 22. 供货商ID值(手工指定)
	
)
----@encode$--
AS
SET NOCOUNT ON


-- 声明会计科目相关变量
DECLARE	@GOODS_ID				varchar(50),
		@CASH_ID				varchar(50),
		@CASH_BANK_ID			varchar(50),
		@AR_ID					varchar(50),
		@AP_ID					varchar(50),
		@YF_ID					varchar(50),
		@YS_ID					 varchar(50),
		@GOODS_LOSS_ID			varchar(50),
		@GOODS_GET_ID			varchar(50),
		@ALLOT_PRICE_ID			varchar(50),
		@PRICE_INCOME_ID		varchar(50),
		@BORROW_BUY_PRICE_ID	varchar(50),
		@GOODS_GIVE_ID			varchar(50),
		@GOODS_PRODUCE_ID		varchar(50),
		@SALE_COST_ID			varchar(50),
		@SALE_INCOME_ID			varchar(50),
		@LEND_GOODS_ID			varchar(50),
		@BORROW_GOODS_ID		varchar(50),
		@BALANCE_ID				varchar(50),
		@DEPRECIATION_ID		varchar(50),
		@APPORTION_EXPENSE_ID	varchar(50),
		@INIT_MONEY_ID			varchar(50),
		@ALL_INCOME_ID			varchar(50),
		@ALL_EXPENSE_ID			varchar(50),
		@PROFIT_ID				varchar(50),
		@ASSETS_ID				varchar(50),
		@DEBT_ID				varchar(50),
		@POWER_ID				varchar(50),
		@ADDEBT_INCOME_ID		varchar(50),
		@ADDEBT_LOSE_ID			varchar(50),
		@GOODS_GIVE_RECNO		varchar(50),
		@GOODS_GIVEME_RECNO		varchar(50),
		@GOODS_REPAIR_ID		varchar(50),
		@SALE_JKFL_EXPENSE_ID	varchar(50),
		@PreferenceID			varchar(50),
		@REPAIR_INCOME_ID		varchar(50),
		@REPAIR_OUTCOME_ID		varchar(50),
		@GRIR_ID				VARCHAR(50),
		@FC_ID					VARCHAR(50)

SELECT @SALE_JKFL_EXPENSE_ID	=nid FROM dbo.Ac_Items WHERE UserCode = '0404'			-- 销售折扣返利支出
SELECT	@GOODS_REPAIR_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0423'		-- 商品维修收入
SELECT @GOODS_GIVE_RECNO		=nid FROM dbo.Ac_Items WHERE UserCode =  '0422'		-- 商品赠送支出
SELECT @GOODS_GIVEME_RECNO		=nid FROM dbo.Ac_Items WHERE UserCode =  '0322'		-- 商品获赠收入
SELECT @GOODS_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '1241'			-- 『库存商品总值合计』
SELECT @CASH_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1001'			-- 现    金
SELECT @AR_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '987'			-- 『应收款合计』
SELECT @AP_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2121'			-- 『应付帐款合计』
SELECT @GOODS_LOSS_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0421'		-- 商品报损支出
SELECT @GOODS_GET_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0321'		-- 商品报溢收入
SELECT @ALLOT_PRICE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0325'		-- 变价调拨差价
SELECT @PRICE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0323'		-- 成本调价收入
SELECT @GOODS_PRODUCE_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0326'		-- 商品拆装差价
SELECT @SALE_COST_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5401'			-- 『销售成本』
SELECT @SALE_INCOME_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '5101'			-- 『销售收入』
SELECT @BALANCE_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '0324'		-- 采购退货差价
SELECT @DEPRECIATION_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0432'		-- 固定资产折旧
SELECT @APPORTION_EXPENSE_ID	=nid FROM dbo.Ac_Items WHERE UserCode =  '1301'			-- 『待摊费用』
--SELECT @ALL_INCOME_ID			= '00003'				-- 【收入类】
--SELECT @ALL_EXPENSE_ID			= '00004'				-- 【支出类】
--SELECT @ASSETS_ID				= '00001'				-- 【资产合计】
--SELECT @DEBT_ID					= '00002'				-- 【负债合计】
SELECT @ADDEBT_INCOME_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '03333'		-- 调帐收入
SELECT @ADDEBT_LOSE_ID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0431'		-- 调帐亏损
SELECT @PreferenceID			=nid FROM dbo.Ac_Items WHERE UserCode =  '0456'		-- 『优惠金额』
SELECT @REPAIR_INCOME_ID 		=nid FROM dbo.Ac_Items WHERE UserCode =  '0328' 	-- 商品维修收入
SELECT @REPAIR_OUTCOME_ID		=nid FROM dbo.Ac_Items WHERE UserCode =  '0423' 	--商品维修支出
SELECT @YF_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '1151'			--预付账款
SELECT @YS_ID					=nid FROM dbo.Ac_Items WHERE UserCode =  '2131'			--预收账款

SELECT 	@FC_id					=nid FROM dbo.Ac_Items WHERE UserCode =  '1251'			--发出商品
SELECT 	@GRIR_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '2122'			--应付暂估



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

-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

DECLARE	@szSql					varchar(500),
		@DBName					varchar(20),
		@szJobNumber			varchar(20),
		@nAllowNegativeStock	int,

		@dTotalTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品金额
		@dQtyTemp				 NUMERIC(24, 10) ,	-- 计算的最终库存商品数量
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
		@dPricetemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@nPeriod				int,
		@OutFactoryDate			datetime,
		@datValidDate			datetime,
		@nGoodsOrder			int

SET @dCostPrice		= 0

SET @dTotalTemp		= 0
SET @dQtyTemp		= 0
SET @dCostTotalTemp	= 0

SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0


-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', @szSTypeID,@nAllowNegativeStock output

-- begin tran Modifydbf
-- save tran Modifydbf
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------




*/


DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT

	-- 成本核算，传入的 ATypeID 参数必定为 “库存商品总值”
	IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
	BEGIN
		-- 若商品数量为 0 且 商品成本金额不等于 0，则回滚报错
		IF @dQty = 0 AND (@dTotal <> 0 OR @dntotal <>0)
		BEGIN
			--RAISERROR('数据出错！',16,1)
			RETURN -7	-- 异常
		END

		

		IF @szPeriod = ''
		BEGIN
			/*****************************************************************
				移动加权平均成本核算法
			******************************************************************/
			IF @szCostingMethod = @AVERAGE
			BEGIN
				IF @dQty = 0 GOTO ERROR3

				-- 判断系统是否采用 “各仓库成本均价一致”
				DECLARE @chrAverageCostPrice varchar(1)

				SELECT	TOP 1 @chrAverageCostPrice = Value
				FROM	UserConfig
				WHERE	ConfigName = 'AverageCostPrice'

				-- 针对具体商品在所有仓库的成本均价
				-- 且库存记录必须同时满足数量和金额都大于等于 0
				DECLARE @numAverageCostPrice  NUMERIC(24, 10) 
				IF @chrAverageCostPrice = '1'
				BEGIN
					SELECT	@numAverageCostPrice =
								CASE WHEN ISNULL(SUM(Qty),0) = 0 OR ISNULL(SUM(Total),0) = 0 THEN 0
									 ELSE ROUND(CAST(SUM(Total) AS NUMERIC(24,10))/CAST(SUM(Qty) AS NUMERIC(24,10)),@intPriceDot)
								END
					FROM	GoodsStocks
					WHERE	PTypeID = @szPTypeID
							AND Qty >= 0
							AND Total >= 0
				END
				ELSE
				BEGIN
					SET @numAverageCostPrice = 0
				END

				-- 判断是否是　“调价全部仓库”　的操作
				DECLARE @ChangeAllStock int, @IfRedWord int
				SET @ChangeAllStock = 0
				SET @IfRedWord = 0

				IF @nVchType = 57
				BEGIN
					SELECT	TOP 1 @ChangeAllStock = ChangeAllStock
					FROM	AdPriceBill
					WHERE	BillNumberID = @nGoodsNo

					SELECT	TOP 1 @IfRedWord = RedWord
					FROM	BillIndex
					WHERE	BillNumberID = @nGoodsNo					
				END

				-- （1）读取库存状况表中的对应仓库的商品数量、成本均价、成本金额
				DECLARE ModifyDbf_Cursor CURSOR FOR
					SELECT	a.Qty,
							CASE WHEN a.Qty <> 0 THEN
								ROUND(CAST(a.Total AS NUMERIC(24,10))/CAST(a.Qty AS  NUMERIC(24, 10)),@intPriceDot)
							ELSE 0
							END AS CostPrice,
							a.Total,
							a.JobNumber,
							a.OutFactoryDate,
							a.GoodsOrder
					FROM	GoodsStocks a
					INNER JOIN
					(
						SELECT TypeID
						FROM Stock
						WHERE STypeID=@szSTypeID
					) b
					ON a.KTypeID=b.TypeID
					WHERE	a.PTypeID = @szPTypeID
							AND a.KTypeID = @szKTypeID
							
				FOR UPDATE

				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,		-- 当前库存商品数量
														@dCostPriceTemp,	-- 当前库存商品成本均价
														@dCostTotalTemp,	-- 当前库存商品成本金额
														@szJobNumber,
														@OutFactoryDate,
														@nGoodsOrder

			

				-- 库存状况表 GoodsStocks 中有对应的商品库存记录
				IF @@FETCH_STATUS = 0
				BEGIN
					-- 确定需核算的商品成本均价
					IF @dTotal <> 0
						-- 从传入参数：金额、数量，来确定成本均价
						SELECT @dCostPriceTemp = ROUND(CAST(@dTotal AS NUMERIC(24,10))/ CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)
					ELSE
					BEGIN
						-- 若传入参数：金额 = 0，且当前库存商品成本均价 <= 0，则成本单价取商品最近进价
						IF ( @dCostPricetemp = 0 OR @dCostQtyTemp = 0 OR @dCostTotalTemp = 0 ) AND @HandZeroCost = 0
							IF @dCostTotalTemp = 0 AND @dCostQtyTemp <> 0 --AND @dQty < 0	-- 出入库，数量不为零，成本金额为0，特殊处理
							BEGIN
								SET @HandZeroCost = 1
								SET @dCostPriceTemp = ROUND(CAST(@dCostTotalTemp  AS NUMERIC(24,10))/ CAST(@dCostQtyTemp AS NUMERIC(24,10)),@intPriceDot)
							END
							ELSE
							BEGIN
								SELECT	@dCostPriceTemp = a.RecPrice
								FROM	PType_STypePrice a
								INNER JOIN PType b
								ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
								WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID
							END
						ELSE
						BEGIN
							IF @HandZeroCost = 1
								SET @dCostPriceTemp = 0
							ELSE
								SET @dCostPriceTemp = ROUND(CAST(@dCostTotalTemp  AS NUMERIC(24,10)) / CAST(@dCostQtyTemp AS NUMERIC(24,10)),@intPriceDot)
						END

						-- 成本调价单，且数量 > 0，成本金额 = 0
						IF @nVchType = 57 AND @dCostQtyTemp > 0 AND @dCostTotalTemp = 0
							SET @dCostPriceTemp = 0
					END

					-- 若最终得出的成本均价 = 0，则页面会提示输入成本价
					IF @dCostPriceTemp <= 0 AND @nVchType <> 57 AND @HandZeroCost = 0 AND @nVchType NOT IN (188,144)
						GOTO ERRORINPUTCOSTPRICE

					-- 若成本单价不为零，乘数量后等于零，此种情况不允许过账
					--IF @dCostPriceTemp <> 0 AND CAST(@dCostPriceTemp * @dQty AS  NUMERIC(24, 10) ) = 0
					--	RETURN 818

					IF @dQty < 0 --AND @nVchType <>201-- Qty 为负，代表商品出库
					BEGIN
						-- 出库数量大于当前库存商品数量
						IF @dCostQtyTemp < ABS(@dQty)
						BEGIN
							-- 库存数量不够时，调价单不能修改库存数据
							IF @nVchType = 57 AND @ChangeAllStock <> 1 GOTO ERROR4

							-- 不允许负库存，则进行提示
							IF @nAllowNegativeStock = 0 AND @ChangeAllStock <> 1 AND (@ModifyAuditBill=0 OR (@ModifyAuditBill=1 AND @nVchType NOT IN (34,144,21,188,201,57,174,17,400,403,45,142,14,160,328,329))) 
							BEGIN
								--SELECT '1'
								GOTO ERROR1
							END
							ELSE
							BEGIN
								IF @nVchType = 57 AND @dTotal = 0 AND @ChangeAllStock = 1 AND @IfRedWord = 2
								BEGIN
									SET @dCostPriceTemp = 0
								END
								-- 最终商品库存数量
								SET @dQtyTemp = @dCostQtyTemp + @dQty
								-- 最终商品库存金额
								IF @dTotal <> 0
									SET @dTotalTemp = ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(@dTotal,@intMoneyDot)
								ELSE
									SET @dTotalTemp = ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(CAST((@dQty * @dCostPriceTemp) AS  NUMERIC(24, 10) ),@intMoneyDot)

								-- 更新库存状况表商品具体数据：库存数量、库存金额
								UPDATE	GoodsStocks
								SET		Total = ROUND(@dTotalTemp,@intMoneyDot),
										Qty = ROUND(@dQtyTemp,@intQtyDot),
										Price = ROUND(CAST(@dTotalTemp  AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2

								IF @nVchType = 57
								BEGIN
									IF @dTotal <> 0
										SET @dCostPrice = ROUND(@dTotal,@intMoneyDot)
									ELSE
										SET @dCostPrice = ROUND(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) ),@intMoneyDot)
								END
								ELSE
								BEGIN
									IF @dTotal <> 0
										SET @dCostPrice = ROUND(ABS(@dTotal),@intMoneyDot)
									ELSE
										SET @dCostPrice = ROUND(ABS(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) )),@intMoneyDot)
								END
								GOTO CLEANUP	-- 执行成功并退出
							END
						END

						-- 出库数量等于当前库存商品数量
						IF @dCostQtyTemp = ABS(@dQty)
						BEGIN
							IF @dTotal = 0	-- 出库金额 = 0
							BEGIN
								IF @dCostTotalTemp > 0
								BEGIN
									IF @HandZeroCost = 1	-- 2009.12 发现红冲采购单，单价为0的情况
									BEGIN
										SET @dQtyTemp = 0
										SET @dTotalTemp = @dCostTotalTemp

										UPDATE	GoodsStocks
										SET		Total	= ROUND(@dTotalTemp,@intMoneyDot),
												Qty		= ROUND(@dQtyTemp,@intQtyDot),
												Price	= 0
										WHERE CURRENT OF ModifyDbf_Cursor
										IF @@ROWCOUNT = 0 GOTO ERROR2

										SET @dCostPrice = @dTotal
									END
									ELSE
									BEGIN
										DELETE FROM GoodsStocks
										WHERE CURRENT OF ModifyDbf_Cursor
										IF @@ROWCOUNT = 0 GOTO ERROR2
	
										IF @nVchType = 57
											SET @dCostPrice = -ABS(@dCostTotalTemp)
										ELSE
											SET @dCostPrice = ABS(@dCostTotaltemp)
									END
								END
								ELSE	-- @dCostTotalTemp <= 0
								BEGIN
									IF @nVchType = 57
									BEGIN
										SET @dTotal = -@dCostTotalTemp
									END
									ELSE
									BEGIN
										IF @HandZeroCost = 0
										BEGIN
											SELECT	@dTotal = ROUND(CAST(@dQty * a.RecPrice AS  NUMERIC(24, 10) ),@intMoneyDot)
											FROM	PType_STypePrice a
											INNER JOIN PType b
											ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
											WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID
	
											IF @dTotal >= 0  AND @nVchType NOT IN (188,144,329,328) GOTO ERRORINPUTCOSTPRICE
										END
									END

									SELECT @dTotalTemp = @dCostTotalTemp + @dTotal
									SELECT @dQtyTemp = @dCostQtyTemp + @dQty	-- 0

									IF @dQtyTemp = 0 AND @dTotalTemp = 0
									BEGIN
										DELETE FROM GoodsStocks
										WHERE CURRENT OF ModifyDbf_Cursor
										IF @@ROWCOUNT = 0 GOTO ERROR2
									END
									ELSE
									BEGIN
										UPDATE	GoodsStocks
										SET		Total	= ROUND(@dTotalTemp,@intMoneyDot),
												Qty		= ROUND(@dQtyTemp,@intQtyDot),
												price	= 0
										WHERE CURRENT OF ModifyDbf_Cursor
										IF @@ROWCOUNT = 0 GOTO ERROR2
									END

									IF @nVchType = 57
										SELECT @dCostPrice = @dTotal
									ELSE
										SELECT @dCostPrice = ABS(@dTotal)
								END
							END
							ELSE	-- Total <> 0
							BEGIN
								-- 若传入参数：金额不等于 0，则更新 GoodsStocks 中对应的库存记录：数量、单价、金额
								SET @dTotalTemp = @dCostTotalTemp + @dTotal
								SET @dQtyTemp = @dCostQtyTemp + @dQty
								SET @dCostPrice = ABS(@dTotal)

								-- 若最终计算出来的成本金额 = 0，则删除 GoodsStocks 中的库存记录
								IF @dTotalTemp = 0 AND @dQtyTemp = 0
								BEGIN
									DELETE FROM GoodsStocks
									WHERE CURRENT OF ModifyDbf_Cursor
									IF @@ROWCOUNT = 0 GOTO ERROR2
								END
								ELSE
								BEGIN
									UPDATE	GoodsStocks
									SET		Total = ROUND(@dTotalTemp,@intMoneyDot),
											Qty = ROUND(@dQtyTemp,@intQtyDot),
											Price = 0
									WHERE CURRENT OF ModifyDbf_Cursor
									IF @@ROWCOUNT = 0 GOTO ERROR2
								END
							END

							GOTO CLEANUP
						END
						-- 出库数量小于当前库存商品数量
						ELSE
						BEGIN
							IF @nVchType = 57 AND @dCostPriceTemp < 0 GOTO ERRORINPUTCOSTPRICE

							IF @dTotal <> 0
								SET @dTotalTemp = ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(@dTotal,@intMoneyDot)
							ELSE
								SET @dTotalTemp =CASE WHEN @nVchType=401 THEN ROUND(@dCostTotalTemp,@intMoneyDot) ELSE ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(CAST((@dQty * @dCostPriceTemp) AS  NUMERIC(24, 10) ),@intMoneyDot) END
							SET @dQtyTemp = @dCostQtyTemp + @dQty


							UPDATE	GoodsStocks
							SET		Total = ROUND(@dTotalTemp,@intMoneyDot),
									Qty = ROUND(@dQtyTemp,@intQtyDot),
									Price = ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							IF @nVchType = 57
							BEGIN
								IF @dTotal <> 0
									SET @dCostPrice = ROUND(@dTotal,@intMoneyDot)
								ELSE
									SET @dCostPrice = ROUND(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) ),@intMoneyDot)
							END
							ELSE
							BEGIN
								IF @dTotal <> 0
									SET @dCostPrice = ROUND(ABS(@dTotal),@intMoneyDot)
								ELSE
									SET @dCostPrice = ROUND(ABS(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) )),@intMoneyDot)
							END
							GOTO CLEANUP
						END
					END
					ELSE	-- Qty 为正，代表商品入库
					BEGIN
						-- 若传入成本金额为 0(如：报溢、获赠)，且非成本调价单
						IF @dTotal = 0 AND @nVchType <> 57 AND @HandZeroCost = 0
						BEGIN
							-- 库存中，若数量 或 成本金额为 0，则取最近进价
							IF @dCostQtyTemp = 0 OR @dCostTotalTemp = 0
							BEGIN
								IF @numAverageCostPrice = 0
								BEGIN
									SELECT	TOP 1 @dCostPriceTemp = a.RecPrice
									FROM	PType_STypePrice a
									INNER JOIN PType b
									ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
									WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID
								END
								ELSE
								BEGIN
									SET @dCostPriceTemp = @numAverageCostPrice
								END
							END
							ELSE
							BEGIN
								-- 计算成本单价：库存金额 / 库存数量
								SELECT @dCostPriceTemp = ROUND(CAST(@dCostTotalTemp AS NUMERIC(24,10))/ CAST(@dCostQtyTemp AS NUMERIC(24,10)),@intPriceDot)

								-- 若成本价 <= 0，则取最近进价
								IF @dCostPriceTemp <= 0
								BEGIN
									IF @numAverageCostPrice = 0
									BEGIN
										SELECT	TOP 1 @dCostPriceTemp = a.RecPrice
										FROM	PType_STypePrice a
										INNER JOIN PType b
										ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
										WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID
									END
									ELSE
									BEGIN
										SET @dCostPriceTemp = @numAverageCostPrice
									END
								END
							END

							-- 若此时计算出的成本价仍 <= 0，则说明最近进价为 0 或有问题
							-- 则页面会提示输入成本价，该价格会写入商品最近进价
							IF @dCostPriceTemp <= 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE

							-- 最终计算出的商品成本单价 * 传入商品数量
							SET @dTotal =CASE WHEN @dntotal=0 AND @nVchType IN(34,144,400,14,201) THEN 0 ELSE  ROUND(CAST(@dCostPriceTemp * @dQty AS  NUMERIC(24, 10) ),@intMoneyDot) END
							IF @dTotal < 0 GOTO ERROR2
						END

						SET @dTotalTemp = @dCostTotalTemp + @dTotal
						SET @dQtyTemp = @dCostQtyTemp + @dQty

						-- 若最终计算出的库存商品数量不等于 0，则商品成本单价 = 最终库存金额 / 商品数量
						IF @dQtyTemp <> 0
						BEGIN
							SET @dCostPriceTemp = ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
						END
						ELSE
						BEGIN
							-- ?若计算出的最终库存数量结果 = 0，则成本单价 = 0
							SET @dCostPriceTemp = 0
						END

						IF @dQtyTemp = 0 AND @dTotalTemp = 0
						BEGIN
							DELETE FROM GoodsStocks
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2
						END
						ELSE
						BEGIN
							UPDATE	GoodsStocks
							SET		Total	= ROUND(@dTotalTemp,@intMoneyDot),
									Qty		= ROUND(@dQtyTemp,@intQtyDot),
									Price	= ROUND(@dCostPriceTemp,@intPriceDot)
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2
						END
						SET @dCostPrice = @dTotal
						GOTO CLEANUP
					END
				END
				-- GoodsStocks 数据表中，没有相关库存记录
				ELSE
				BEGIN
					IF @dQty < 0	-- Qty 为负，代表商品出库，此时为负库存设置才允许出库
					BEGIN
						-- 不允许负库存，则进行提示
						IF @nAllowNegativeStock = 0 AND @ChangeAllStock <> 1 AND (@ModifyAuditBill=0 OR (@ModifyAuditBill=1 AND @nVchType NOT IN (34,144,21,188,201,57,174,17,400,403,45,142,14,160,328,329)))
						BEGIN
							--SELECT 2
							GOTO ERROR1
						END
						-- 库存数量不够时，调价单不能修改库存数据
						IF @nVchType = 57 AND @ChangeAllStock <> 1 GOTO ERROR4
						ELSE
						BEGIN
							IF @nVchType = 57 AND @dTotal = 0 AND @ChangeAllStock = 1 AND @IfRedWord = 2
							BEGIN
								SET @dCostPriceTemp = 0
							END
							ELSE
							BEGIN
								IF @dTotal = 0 AND @HandZeroCost = 0
								BEGIN
									-- ?若输入参数：金额 = 0，则金额 = 最近进价 * 数量
									SELECT	@dTotal = ROUND(CAST((a.RecPrice * @dQty) AS  NUMERIC(24, 10) ),@intMoneyDot)
									FROM	PType_STypePrice a
									INNER JOIN PType b
									ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
									WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID
	
									-- 若最终得出的成本金额 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
									IF @dTotal = 0 AND @nVchType NOT IN (188,144,329,328) GOTO ERRORINPUTCOSTPRICE
								END
							END

							SET @dCostPriceTemp = ROUND(CAST(@dTotal AS NUMERIC(24,10))/ CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)
							SET @dTotalTemp = @dTotal

							INSERT	GoodsStocks (
								PTypeID,
								KTypeID,
								Qty,
								Total,
								Price
							)
							VALUES (
								@szPTypeID,
								@szKTypeID,
								ROUND(@dQty,@intQtyDot),
								ROUND(@dTotal,@intMoneyDot),
								ROUND(@dCostPriceTemp,@intPriceDot)
							)
							IF @@ROWCOUNT = 0 GOTO ERROR2


							IF @nVchType = 57
								SET @dCostPrice = @dTotal
							ELSE
								SET @dCostPrice = ABS(@dTotal)
							GOTO CLEANUP
						END
					END

					IF @dTotal = 0 AND @HandZeroCost = 0
					BEGIN
						IF @numAverageCostPrice = 0  AND @nVchType NOT IN (144,329)
						BEGIN
							SELECT	@dTotal = ROUND(CAST((a.RecPrice * @dQty) AS  NUMERIC(24, 10) ),@intMoneyDot)
							FROM	PType_STypePrice a
							INNER JOIN PType b
							ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
							WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID
						END
						ELSE
						BEGIN
							SET @dTotal = ROUND(CAST(@numAverageCostPrice * @dQty AS  NUMERIC(24, 10) ),@intMoneyDot)
						END
						--只有非全面修改的单据才让手动输入，全面修改 如果发现取不到成本价就写0回去
						IF ISNULL(@ModifyAuditBill,0)=0
						BEGIN 
						-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
						IF @dTotal = 0  AND @nVchType NOT IN (188,144,329,328) GOTO ERRORINPUTCOSTPRICE
						END 	
					END

					SET @dCostPriceTemp = ROUND(CAST(@dTotal AS NUMERIC(24,10))/ CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)
					SET @dTotalTemp = @dTotal

					INSERT	GoodsStocks (
						PTypeID,
						KTypeID,
						Qty,
						Total,
						Price
					)
					VALUES (
						@szPTypeID,
						@szKTypeID,
						ROUND(@dQty,@intQtyDot),
						ROUND(@dTotal,@intMoneyDot),
						ROUND(@dCostPriceTemp,@intPriceDot)
					)
					IF @@ROWCOUNT = 0 GOTO ERROR2

					SET @dCostPrice = ABS(@dTotal)
					GOTO CLEANUP
				END
			-- select @dCostPrice=@dTotaltemp*@dQty
			-- goto CleanUp
			END
			/*****************************************************************
				先进先出成本算法
			******************************************************************/
			ELSE IF @szCostingMethod = @FIFO
			BEGIN
				IF @dQty = 0 GOTO ERROR3

				EXEC Gp_GetDbf	@GOODS_ID,
								@szPTypeID,
								'0',
								'0',
								@szKTypeID,
								@szSTypeID,
								'',
								'',
								@dQtyTemp output,
								@dTotalTemp output
	
				IF @dQtyTemp + @dQty < 0 AND @nVchType <> 201
				BEGIN
					--SELECT 'a1'
					RETURN -1
				END
				SET @dQtyTemp = @dQty
				SET @dTotalTemp = 0
			
			
				--SELECT '@dqty=',@dQty,'@dTotal=',@dTotal,'@HandZeroCost=',@HandZeroCost,'@szPtypeID=',@szPTypeID,'@szKTypeID=',@szKTypeID
				IF @dQty < 0
				BEGIN
					IF @dTotal <> 0 OR (@dTotal = 0 AND @HandZeroCost = 1)
					BEGIN
						/*
						SELECT	'test',Qty,
									CASE WHEN Qty <> 0 THEN
										ROUND(CAST(Total AS  NUMERIC(24, 10))/CAST(Qty AS  NUMERIC(24, 10)),@intPriceDot)
									ELSE 0
									END AS CostPrice,
									Total,
									JobNumber,
									OutFactoryDate,
									GoodsOrder
							FROM	GoodsStocks
							WHERE	PTypeID = @szPTypeID
									AND KTypeID = @szKTypeID
									AND ABS( ROUND(CAST(Total  AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) - ROUND(CAST(@dTotal  AS  NUMERIC(24, 10) )/CAST(@dQty AS  NUMERIC(24, 10) ),@intPriceDot) ) <= 0.005
							ORDER BY GoodsOrder ASC
						*/
					
						IF @GoodsCostPrice>0 AND EXISTS(
							SELECT PTypeID
							FROM dbo.GoodsStocks
							WHERE PTypeID = @szPTypeID
							AND KTypeID = @szKTypeID
							AND Price=@GoodsCostPrice
						)
						BEGIN
							DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
							SELECT	Qty,
									CASE WHEN Qty <> 0 THEN
										ROUND(CAST(Total AS  NUMERIC(24, 10))/CAST(Qty AS  NUMERIC(24, 10)),@intPriceDot)
									ELSE 0
									END AS CostPrice,
									Total,
									JobNumber,
									OutFactoryDate,
									GoodsOrder
							FROM	GoodsStocks
							WHERE	PTypeID = @szPTypeID
									AND KTypeID = @szKTypeID
									AND Price=@GoodsCostPrice
							ORDER BY GoodsOrder ASC FOR UPDATE		-- 出库，则升序查询
						END
						ELSE
						BEGIN
							DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
								SELECT	Qty,
										CASE WHEN Qty <> 0 THEN
											ROUND(CAST(Total AS  NUMERIC(24, 10))/CAST(Qty AS  NUMERIC(24, 10)),@intPriceDot)
										ELSE 0
										END AS CostPrice,
										Total,
										JobNumber,
										OutFactoryDate,
										GoodsOrder
								FROM	GoodsStocks
								WHERE	PTypeID = @szPTypeID
										AND KTypeID = @szKTypeID
										AND ABS( ROUND(CAST(Total  AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) - ROUND(CAST(@dTotal  AS  NUMERIC(24, 10) )/CAST(@dQty AS  NUMERIC(24, 10) ),@intPriceDot) ) <= 0.005
								ORDER BY GoodsOrder ASC FOR UPDATE		-- 出库，则升序查询
						END								
					END
					ELSE
					BEGIN
						DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
							SELECT	Qty,
									CASE WHEN Qty <> 0 THEN
										ROUND(CAST(Total  AS  NUMERIC(24, 10))/CAST(Qty AS  NUMERIC(24, 10)),@intPriceDot)
									ELSE 0
									END AS CostPrice,
									Total,
									JobNumber,
									OutFactoryDate,
									GoodsOrder
							FROM	GoodsStocks
							WHERE	PTypeID = @szPTypeID
									AND KTypeID = @szKTypeID
							ORDER BY GoodsOrder ASC FOR UPDATE		-- 出库，则升序查询
					END
				END
				ELSE
				BEGIN
					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								CASE WHEN Qty <> 0 THEN
									ROUND(CAST(Total  AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot)
								ELSE 0
								END AS CostPrice,
								Total,
								JobNumber,
								OutFactoryDate,
								GoodsOrder
						FROM	GoodsStocks 
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
						ORDER BY GoodsOrder DESC FOR UPDATE		-- 入库，则倒序查询
				END
			
				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
														@dCostPriceTemp,
														@dCostTotalTemp,
														@szJobNumber,
														@OutFactoryDate,
														@nGoodsOrder
				WHILE @@FETCH_STATUS = 0
				BEGIN
					-- 若成本单价不为零，乘数量后等于零，此种情况不允许过账
					
					IF @dQty < 0
					BEGIN
						
						SET @dQty = @dCostQtyTemp + @dQty
						
						IF @dQty <= 0
						BEGIN
							SET @dTotalTemp = @dTotalTemp + @dCostTotalTemp
							

							IF @dQty = 0 AND @dTotal <> 0
							BEGIN
								SELECT @dCostTotalTemp, ABS(@dTotal) - ( ABS(@dTotalTemp) - @dCostTotalTemp )
								
								--SELECT '@dCostTotalTemp=',@dCostTotalTemp,'@dTotal=',@dTotal,'@dTotalTemp=',@dTotalTemp,'@dCostTotalTemp=',@dCostTotalTemp
								
								IF @dCostTotalTemp = ABS(@dTotal) - ( ABS(@dTotalTemp) - @dCostTotalTemp )
								BEGIN
									DELETE FROM GoodsStocks
									WHERE CURRENT OF ModifyDbf_Cursor
									IF @@ROWCOUNT = 0 GOTO ERROR2
								END
								ELSE
								BEGIN
									--SELECT 'a2'
									GOTO ERROR1
								END
								
							END
							ELSE
							BEGIN
								DELETE FROM GoodsStocks
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2
							END

							IF @dQty <> 0
							BEGIN
								FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
																		@dCostPriceTemp,
																		@dCostTotalTemp,
																		@szJobNumber,
																		@OutFactoryDate,
																		@nGoodsOrder
								CONTINUE
							END
							ELSE IF @dQty = 0
							BEGIN
								IF @nVchType = 57
									SET @dCostPrice = ROUND(-CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) ),@intMoneyDot)
								ELSE
									SET @dCostPrice = ROUND(CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) ),@intMoneyDot)
									
								--SELECT 'a3'
								GOTO CleanUp
							END
						END
						ELSE
						BEGIN
							IF @dTotal <> 0
								SET @dTotalTemp = ROUND(@dTotalTemp,@intMoneyDot)
							ELSE
								SET @dTotalTemp = ROUND(@dTotalTemp,@intMoneyDot) + ROUND(ROUND(@dCostQtyTemp - @dQty,@intQtyDot) * ROUND(CAST(@dCostTotalTemp  AS  NUMERIC(24, 10) )/CAST(@dCostQtyTemp AS  NUMERIC(24, 10) ),@intPriceDot),@intMoneyDot)
							IF @nVchType = 57
								SET @dCostPrice = ROUND(-CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) ),@intMoneyDot)
							ELSE
							BEGIN
								IF @dTotal <> 0
									SET @dCostPrice = ROUND(CAST(ABS(@dTotal) AS  NUMERIC(24, 10) ),@intMoneyDot)
								ELSE
									SET @dCostPrice = ROUND(CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) ),@intMoneyDot)
							END

							IF @dTotal <> 0
							BEGIN
								UPDATE	GoodsStocks
								SET		Qty		= ROUND(@dQty,@intQtyDot),
										Total	= ROUND(@dCostTotalTemp + @dTotalTemp + @dTotal,@intMoneyDot),
										Price	= ROUND(CAST( @dCostTotalTemp + @dTotalTemp + @dTotal AS NUMERIC(22,10))/CAST(@dQty AS NUMERIC(22,10)),@intPriceDot)
								WHERE	CURRENT OF ModifyDbf_Cursor
							END
							ELSE
							BEGIN
								UPDATE	GoodsStocks
								SET		Qty		= ROUND(@dQty,@intQtyDot),
										Total	= ROUND(@dCostTotalTemp,@intMoneyDot) - ROUND( ROUND(@dCostQtyTemp - @dQty,@intQtyDot) * ROUND(CAST(@dCostTotalTemp AS NUMERIC(22,10))/CAST(@dCostQtyTemp AS  NUMERIC(24, 10) ),@intPriceDot) ,@intMoneyDot),
										Price	= ROUND((@dCostTotalTemp - ROUND(ROUND(@dCostQtyTemp - @dQty,@intQtyDot) * ROUND(CAST(@dCostTotalTemp AS  NUMERIC(24, 10) )/CAST(@dCostQtyTemp AS  NUMERIC(24, 10)),@intPriceDot),@intMoneyDot) )/@dQty,@intPriceDot)
								WHERE	CURRENT OF ModifyDbf_Cursor
							END
							
							--SELECT 'a4'
							IF @@ROWCOUNT = 0 GOTO ERROR2

							--SELECT 'a5'
							GOTO CLEANUP
						END
					END
					ELSE
					BEGIN
						IF @dTotal=0 AND @nVchType NOT IN(34,144,400,14,201,329,328) AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = ROUND(a.RecPrice * @dQty,@intMoneyDot)
							FROM	PType_STypePrice a
							INNER JOIN PType b
							ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
							WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID

							IF @dTotal <= 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE
						END

						SET @dPriceTemp = ROUND(CAST(@dTotal AS NUMERIC(24,10))/ CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)
						
						--SELECT 'a6'
						IF @dPriceTemp < 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE

						IF @nVchType = 57	-- 调价单处理
						BEGIN
							FETCH LAST FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
																	@dCostPriceTemp,
																	@dCostTotalTemp,
																	@szJobNumber,
																	@OutFactoryDate,
																	@nGoodsOrder

							IF @dPriceTemp = CASE WHEN @dCostQtyTemp = 0 THEN 0 ELSE ROUND(CAST(@dCostTotalTemp AS  NUMERIC(24, 10) )/CAST(@dCostQtyTemp AS  NUMERIC(24, 10)),@intPriceDot) END
							BEGIN
								SET @dTotalTemp = @dCostTotalTemp + @dTotal
								SET @dQtyTemp = @dCostQtyTemp + @dQty

								UPDATE	GoodsStocks
								SET		Qty		= ROUND(@dQtyTemp,@intQtyDot),
										Total	= ROUND(@dTotalTemp,@intMoneyDot),
										Price	= ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
								WHERE CURRENT OF ModifyDbf_Cursor
								
								--SELECT 'a7'
								IF @@ROWCOUNT = 0 GOTO ERROR2

								SET @dCostPrice = ABS(@dTotal)
								
								--SELECT 'a8'
								GOTO CLEANUP
							END
							ELSE
							BEGIN
								SET @dCostPrice = ABS(@dTotal)

								INSERT GoodsStocks (
									PTypeID,
									KTypeID,
									Qty,
									Total,
									Price,
									GoodsOrder,
									JobNumber
								)
								VALUES (
									@szPTypeID,
									@szKTypeID,
									ROUND(@dQty,@intQtyDot),
									ROUND(@dTotal,@intMoneyDot),
									ROUND(@dPricetemp,@intPriceDot),
									@nGoodsOrder + 1,
									@szJobNo
								)
								
								--SELECT 'a9'
								IF @@ROWCOUNT = 0 GOTO ERROR2

								--SELECT 'a10'
								GOTO CLEANUP
							END
						END

						IF @dPriceTemp = CASE WHEN @dCostQtyTemp = 0 THEN 0 ELSE ROUND(CAST(@dCostTotalTemp AS  NUMERIC(24, 10) )/CAST(@dCostQtyTemp AS  NUMERIC(24, 10) ),@intPriceDot) END
						BEGIN
							SET @dTotalTemp = @dCostTotalTemp + @dTotal
							SET @dQtyTemp = @dCostQtyTemp + @dQty


							UPDATE	GoodsStocks
							SET		Qty		= ROUND(@dQtyTemp,@intQtyDot),
									Total	= ROUND(@dTotalTemp,@intMoneyDot),
									Price	= ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
							WHERE	CURRENT OF ModifyDbf_Cursor
							
							--SELECT 'a11'
							IF @@ROWCOUNT = 0 GOTO ERROR2

							SET @dCostPrice = ABS(@dTotal)
							
							--SELECT 'a12'
							GOTO CLEANUP
						END
						ELSE
						BEGIN
							SET @dCostPrice = ABS(@dTotal)

							INSERT GoodsStocks (
								PTypeID,
								KTypeID,
								Qty,
								Total,
								Price,
								GoodsOrder,
								JobNumber
							)
							VALUES (
								@szPTypeID,
								@szKTypeID,
								ROUND(@dQty,@intQtyDot),
								ROUND(@dTotal,@intMoneyDot),
								ROUND(@dPriceTemp,@intPriceDot),
								@nGoodsOrder + 1,
								@szJobNo
							)
							
							--SELECT 'a13'
							IF @@ROWCOUNT = 0 GOTO ERROR2

							--SELECT 'a14'
							GOTO CLEANUP
						END
					END
				END

				IF @@FETCH_STATUS <> 0
				BEGIN
				
					IF @dQty < 0 
					BEGIN
						--SELECT 4
						
						--SELECT 'a15'
						GOTO ERROR1	-- 负库存
					END
					ELSE
					BEGIN
						IF @dTotal = 0 AND @nVchType NOT IN(34,144,400,14,201,329,328) AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = ROUND(a.RecPrice * @dQty,@intMoneyDot)
							FROM	PType_STypePrice a
							INNER JOIN PType b
							ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
							WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID

							-- 若最终无法获取成本金额，则提示手工输入
							
							--SELECT 'a16'
							IF @dTotal = 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE
						END
	
						SET @dPriceTemp = ROUND(CAST(@dTotal AS NUMERIC(24,10))/ CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)
						IF @dPriceTemp < 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE

						SET @dCostPrice = ABS(@dTotal)
	
						INSERT GoodsStocks (
							PTypeID,
							KTypeID,
							Qty,
							Total,
							Price,
							GoodsOrder,
							JobNumber
						)
						VALUES (
							@szPTypeID,
							@szKTypeID,
							ROUND(@dQty,@intQtyDot),
							ROUND(@dTotal,@intMoneyDot),
							ROUND(@dPriceTemp,@intPriceDot),
							1,					-- 新生成的批次默认为 1
							@szJobNo
						)
						
						--SELECT 'a17'
						IF @@ROWCOUNT = 0 GOTO ERROR2

						--SELECT 'a18'
						GOTO CLEANUP
					END
				END
			END
			/*****************************************************************
				后进先出成本算法
			******************************************************************/
			ELSE IF @szCostingMethod = @LIFO
			BEGIN
				IF @dQty = 0 GOTO ERROR3

				EXEC Gp_GetDbf	@GOODS_ID,
								@szPTypeID,
								'0',
								'0',
								@szKTypeID,
								@szSTypeID,
								'',
								'',
								@dQtyTemp output,
								@dTotalTemp output
				
				IF ( @dQtyTemp + @dQty ) < 0 AND @nVchType <> 201
				BEGIN
					RETURN -1
				END

				SET @dQtyTemp = @dQty
				SET @dTotalTemp = 0

				IF @dQty < 0 AND (@dTotal <> 0 OR (@dTotal = 0 AND @HandZeroCost = 1))
				BEGIN
					IF @GoodsCostPrice>0 AND EXISTS
					(
						SELECT PTypeID
						FROM dbo.GoodsStocks
						WHERE PTypeID = @szPTypeID
						AND KTypeID = @szKTypeID
						AND Price=@GoodsCostPrice
					)
					BEGIN
						DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								JobNumber,
								OutFactoryDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
								AND Price=@GoodsCostPrice
						ORDER BY GoodsOrder DESC FOR UPDATE
					END
					ELSE
					BEGIN
						DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								JobNumber,
								OutFactoryDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
								--A89.7 BUG2797 注释下面一行
								AND ABS( ROUND(CAST(Total AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) - ROUND(CAST(@dTotal  AS  NUMERIC(24, 10) )/CAST(@dQty AS  NUMERIC(24, 10) ),@intPriceDot) ) <= 0.005
						ORDER BY GoodsOrder DESC FOR UPDATE
					END
					
					
				END
				ELSE
				BEGIN
					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								JobNumber,
								OutFactoryDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
						ORDER BY GoodsOrder DESC FOR UPDATE

				END

				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
														@dCostPriceTemp,
														@dCostTotalTemp,
														@szJobNumber,
														@OutFactoryDate,
														@nGoodsOrder
				WHILE @@FETCH_STATUS = 0
				BEGIN
					-- 若成本单价不为零，乘数量后等于零，此种情况不允许过账
					--IF @dCostPriceTemp <> 0 AND CAST(@dCostPriceTemp * @dQty AS  NUMERIC(24, 10) ) = 0
					--	RETURN 818

					IF @dQty < 0
					BEGIN
						-- if @nVchType=57 select @nGoodsOrdertemp=@nGoodsOrder,@szJobNotemp=@szJobNumber
						SET @dQty = @dCostQtyTemp + @dQty
						-- print @dQty
						IF @dQty <= 0
						BEGIN
							SET @dTotalTemp = @dTotalTemp + @dCostTotalTemp
							-- print @dTotaltemp

							IF @dQty = 0 AND @dTotal <> 0
							BEGIN
								IF @dCostTotalTemp = ABS(@dTotal) - ( ABS(@dTotalTemp) - @dCostTotalTemp )
								BEGIN
									DELETE FROM GoodsStocks
									WHERE CURRENT OF ModifyDbf_Cursor
									IF @@ROWCOUNT = 0 GOTO ERROR2
								END
								ELSE
								BEGIN
									--SELECT 5
									GOTO ERROR1
								END
							END
							ELSE
							BEGIN
								DELETE FROM GoodsStocks
								WHERE CURRENT OF ModifyDbf_Cursor
								IF @@ROWCOUNT = 0 GOTO ERROR2
							END

							IF @dQty <> 0
							BEGIN
								FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
																		@dCostPriceTemp,
																		@dCostTotalTemp,
																		@szJobNumber,
																		@OutFactoryDate,
																		@nGoodsOrder
								CONTINUE
							END
							ELSE IF @dQty = 0
							BEGIN
								IF @nVchType = 57
									SET @dCostPrice = -CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
								ELSE
									SET @dCostPrice = CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) )
								GOTO CLEANUP
							END
						END
						ELSE
						BEGIN
							IF @dTotal <> 0
								SET @dTotalTemp = ROUND(@dTotalTemp,@intMoneyDot)
							ELSE
								SET @dTotalTemp = ROUND(@dTotalTemp,@intMoneyDot) + ROUND( ROUND(@dCostQtyTemp - @dQty,@intQtyDot) * ROUND(CAST(@dCostTotalTemp  AS  NUMERIC(24, 10) )/CAST(@dCostQtyTemp AS  NUMERIC(24, 10) ),@intPriceDot),@intMoneyDot)
							IF @nVchType = 57
								SET @dCostPrice = ROUND(-CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) ),@intMoneyDot)
							ELSE
							BEGIN
								IF @dTotal <> 0
									SET @dCostPrice = ROUND(CAST(ABS(@dTotal) AS  NUMERIC(24, 10) ),@intMoneyDot)
								ELSE
									SET @dCostPrice = ROUND(CAST(ABS(@dTotalTemp) AS  NUMERIC(24, 10) ),@intMoneyDot)
							END

							IF @dTotal <> 0
							BEGIN
								UPDATE	GoodsStocks
								SET		Qty = ROUND(@dQty,@intQtyDot),
										Total	= ROUND(@dCostTotalTemp + @dTotalTemp + @dTotal,@intMoneyDot),
										Price	= ROUND(CAST( @dCostTotalTemp + @dTotalTemp + @dTotal AS NUMERIC(22,10))/CAST(@dQty AS NUMERIC(22,10)),@intPriceDot)
								WHERE CURRENT OF ModifyDbf_Cursor
							END
							ELSE
							BEGIN
								UPDATE	GoodsStocks
								SET		Qty = ROUND(@dQty,@intQtyDot),
										Total	= ROUND(@dCostTotalTemp,@intMoneyDot) - 
										ROUND( (@dCostQtyTemp - @dQty) * ROUND(CAST(@dCostTotalTemp AS  NUMERIC(24, 10) )/CAST(@dCostQtyTemp AS  NUMERIC(24, 10) ),@intPriceDot ),@intMoneyDot),
										Price	= ROUND(( @dCostTotalTemp - ROUND( (@dCostQtyTemp - @dQty) * ROUND(CAST(@dCostTotalTemp AS  NUMERIC(24, 10) ) /CAST(@dCostQtyTemp AS  NUMERIC(24, 10)),@intPriceDot),@intMoneyDot))/CAST(@dQty AS NUMERIC(22,10)),@intPriceDot)
								WHERE CURRENT OF ModifyDbf_Cursor
							END
							IF @@ROWCOUNT = 0 GOTO ERROR2

							GOTO CLEANUP
						END
					END
					ELSE
					BEGIN
						IF @dTotal = 0 AND @nVchType NOT IN(34,144,400,14,201,329,328) AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = ROUND(a.RecPrice * @dQty,@intMoneyDot)
							FROM	PType_STypePrice a
							INNER JOIN PType b
							ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
							WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID

							IF @dTotal = 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE
						END

						SET @dPriceTemp = ROUND(CAST(@dTotal AS NUMERIC(24,10))/ CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)
						IF @dPriceTemp < 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE

						IF @dPriceTemp = CASE WHEN @dCostQtyTemp = 0 THEN 0 ELSE ROUND(CAST(@dCostTotalTemp AS  NUMERIC(24, 10) )/CAST(@dCostQtyTemp AS  NUMERIC(24, 10) ),@intPriceDot) END
						BEGIN
							SET @dTotalTemp	= @dCostTotalTemp + @dTotal
							SET @dQtyTemp	= @dCostQtyTemp + @dQty

							UPDATE	GoodsStocks
							SET		Qty		= ROUND(@dQtyTemp,@intQtyDot),
									Total	= ROUND(@dTotalTemp,@intMoneyDot),
									Price	= ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/ CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							SET @dCostPrice = ABS(@dTotal)
							GOTO CleanUp

						END
						ELSE
						BEGIN
							SET @dCostPrice = ABS(@dTotal)

							INSERT	GoodsStocks (
								PTypeID,
								KTypeID,
								Qty,
								Total,
								Price,
								GoodsOrder,
								JobNumber
							)
							VALUES (
								@szPTypeID,
								@szKTypeID,
								ROUND(@dQty,@intQtyDot),
								ROUND(@dTotal,@intMoneyDot),
								ROUND(@dPriceTemp,@intPriceDot),
								@nGoodsOrder + 1,
								@szJobNo
							)
							IF @@ROWCOUNT = 0 GOTO ERROR2

							GOTO CleanUp
						END
					END
				END

				-- 库存无记录
				IF @@FETCH_STATUS <> 0
				BEGIN
					IF @dQty < 0 AND @nVchType <> 201
					BEGIN
						--SELECT 6
						GOTO ERROR1	-- 负库存回滚
					END
					ELSE
					BEGIN
						IF @dTotal = 0 AND @nVchType NOT IN(34,144,400,14,201,329,328) AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = ROUND( a.RecPrice * @dQty,@intMoneyDot)
							FROM	PType_STypePrice a
							INNER JOIN PType b
							ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
							WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID

							IF @dTotal = 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE
						END

						SET @dPriceTemp	= ROUND(CAST(@dTotal AS NUMERIC(24,10))/ CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)
						IF @dPriceTemp < 0  AND @nVchType NOT IN (188,144) GOTO ERRORINPUTCOSTPRICE

						SET @dCostPrice	= ABS(@dTotal)

						INSERT GoodsStocks (
							PTypeID,
							KTypeID,
							Qty,
							Total,
							Price,
							GoodsOrder,
							JobNumber
						)
						VALUES (
							@szPTypeID,
							@szKTypeID,
							ROUND(@dQty,@intQtyDot),
							ROUND(@dTotal,@intMoneyDot),
							ROUND(@dPriceTemp,@intPriceDot),

							1,					--  新生成的批次默认为 1
							@szJobNo
						)
						IF @@ROWCOUNT = 0 GOTO ERROR2

						GOTO CleanUp
					END
				END

			END
			/*****************************************************************
				手工指定成本算法
			******************************************************************/
			ELSE IF @szCostingMethod = @HAND
			BEGIN
				-- 解决手工指定法单价太小，造成误差太大的问题
				
				/*
				UPDATE	GoodsStocks
				SET		Price = Total/Qty
				WHERE	Qty <> 0
						AND PTypeID = @szPTypeID
						AND KTypeID = @szKTypeID
				*/
				
				
				IF @dQty = 0 GOTO ERROR3

				-- 批次成本价不为零，乘数量后等于零，此种情况不允许过账
				--IF @GoodsCostPrice <> 0 AND CAST(@GoodsCostPrice * @dQty AS  NUMERIC(24, 10) ) = 0
				--	RETURN 818

				IF @dQty < 0
				BEGIN
					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								GoodsNumber,--JobNumber,
								ProduceDate,--OutFactoryDate,
								ValidDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
								AND GoodsNumber = @GoodsNumber
								AND ProduceDate = @ProduceDate
								AND ValidDate = @ValidDate
								AND ABS(Price-@GoodsCostPrice) = 0
						-- 如果有两个以上完全相同的批次，则先出数量大的
						ORDER BY Qty DESC FOR UPDATE
				END
				ELSE
				BEGIN
					-- 入库金额为0，且不能指定入库单价的单据					
					IF @dTotal = 0 AND @nVchType NOT IN(34,144,400,14,201,329) AND @HandZeroCost = 0
					BEGIN
						SELECT	@dTotal = ROUND(a.RecPrice * @dQty,@intMoneyDot),@dPrice=ROUND(a.RecPrice,@intPriceDot)
						FROM	PType_STypePrice a
						INNER JOIN PType b
						ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
						WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID

						IF @dTotal <= 0 
						BEGIN
							--PRINT('1')
							--PRINT(@dTotal)
							RETURN -5--GOTO ERRORINPUTCOSTPRICE基础通讯版有区别
						END
					END
					
					SET @dPricetemp=@dPrice

					DECLARE ModifyDbf_Cursor SCROLL CURSOR FOR
						SELECT	Qty,
								Price,
								Total,
								GoodsNumber,--JobNumber,
								ProduceDate,--OutFactoryDate,
								ValidDate,
								GoodsOrder
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
								AND GoodsNumber = @GoodsNumber
								AND ProduceDate = @ProduceDate
								AND ValidDate = @ValidDate
								AND Price = @dPriceTemp
						ORDER BY GoodsOrder DESC FOR UPDATE
				END

				OPEN ModifyDbf_Cursor
				FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
														@dCostPriceTemp,
														@dCostTotalTemp,
														@szJobNumber,
														@OutFactoryDate,
														@datValidDate,
														@nGoodsOrder
				IF @@FETCH_STATUS = 0
				BEGIN
					IF @dQty < 0	AND @nVchType <>201-- 出库
					BEGIN
						IF @dCostQtyTemp < ABS(@dQty) 
						BEGIN
							--SELECT 7
							GOTO ERROR1	-- 数量不够，返回错误
						END

						IF @dCostQtyTemp = ABS(@dQty)	-- 数量相同
						BEGIN
							DELETE FROM	GoodsStocks
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							IF @nVchType = 57
								SET @dCostPrice = -ABS(@dCostTotalTemp)
							ELSE
								SET @dCostPrice = ABS(@dCostTotalTemp)
																
							GOTO CleanUp
						END
						ELSE
						BEGIN
						 IF(@nVchType = 57)--红冲回去的时候，这里该取调价后的金额，不然会出现goodsstock的total回不到
						    BEGIN
						    SET @dCostTotalTemp = ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(@dTotal,@intMoneyDot)
						    END
						    ELSE
						    BEGIN
							SET @dCostTotalTemp = ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(@dQty * @dCostPriceTemp,@intMoneyDot)
							END
							--SET @dCostTotalTemp = ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(@dQty * @dCostPriceTemp,@intMoneyDot)
							SET @dQtyTemp = @dCostQtyTemp + @dQty

							UPDATE	GoodsStocks
							SET		Total = ROUND(@dCostTotalTemp,@intMoneyDot),
									Qty = ROUND(@dQtyTemp,@intQtyDot)
							WHERE CURRENT OF ModifyDbf_Cursor
							IF @@ROWCOUNT = 0 GOTO ERROR2

							IF @nVchType = 57
								SET @dCostPrice = ROUND(-ABS(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) )),@intMoneyDot)
							ELSE
								SET @dCostPrice = ROUND(ABS(CAST(@dQty * @dCostPriceTemp AS  NUMERIC(24, 10) )),@intMoneyDot)
							GOTO CleanUp
						END
					END
					ELSE	-- 有指定批次入库
					BEGIN
						SET @dTotalTemp	= @dCostTotalTemp + @dTotal
						SET @dQtyTemp	= @dCostQtyTemp + @dQty

						UPDATE	GoodsStocks
						SET		Qty = ROUND(@dQtyTemp,@intQtyDot),
								Total = ROUND(@dTotalTemp,@intMoneyDot)
						WHERE CURRENT OF ModifyDbf_Cursor
						IF @@ROWCOUNT = 0 GOTO ERROR2

						SET @dCostPrice = @dTotal
						GOTO CleanUp
					END
				END
				ELSE	-- 无该批次入库
				BEGIN
					IF @dQty < 0  AND @nVchType<> 201
					BEGIN
						--SELECT 8
						GOTO ERROR1
					END
					ELSE
					BEGIN
						IF @dTotal  IN ( 0,-1) AND @nVchType NOT IN(34,144,400,14,201,329)  AND @HandZeroCost = 0
						BEGIN
							SELECT	@dTotal = ROUND(a.RecPrice * @dQty,@intMoneyDot),@dPrice=a.RecPrice
							FROM	PType_STypePrice a
							INNER JOIN PType b
							ON a.PTypeID=b.TypeID AND a.UnitID=b.baseUnitId
							WHERE	a.PTypeID = @szPTypeID AND a.STypeID=@szSTypeID
	
							IF @dTotal <= 0  AND @nVchType NOT IN (188,144,329) 
							BEGIN
								--PRINT('2')
								--PRINT(@dTotal)
								GOTO ERRORINPUTCOSTPRICE
							END
						END

						SELECT	@nGoodsOrder = ISNULL(MAX(Goodsorder),0)
						FROM	GoodsStocks
						WHERE	PTypeID = @szPTypeID
								AND KTypeID = @szKTypeID
						
						SET @dPricetemp=@dPrice

						IF @dPriceTemp < 0  AND @nVchType NOT IN (188,144) 
						BEGIN
							--PRINT('3')
							--PRINT(@dPriceTemp)
							GOTO ERRORINPUTCOSTPRICE
						END
						
						--没有该批次，不能反算，直接返回结果，同价调拨单有出现成本金额差异的情况，直接用金额，不能计算 谢吉康 2019-09-06
						IF @nVchType IN (17,188)
							SET @dCostPrice=ROUND(@dTotal,@intMoneyDot)
						ELSE
							SET @dCostPrice=ROUND(@dPriceTemp*@dQty,@intMoneyDot)						

						INSERT	GoodsStocks (
							PTypeID,
							KTypeID,
							Qty,
							Total,
							Price,
							GoodsNumber,--JobNumber,
							ProduceDate,
							ValidDate,
							GoodsOrder
						)
						VALUES (
							@szPTypeID,
							@szKTypeID,
							ROUND(@dQty,@intQtyDot),
							ROUND(@dTotal,@intMoneyDot),
							ROUND(@dPriceTemp,@intPriceDot),
							@GoodsNumber,
							@ProduceDate,
							@ValidDate,
							@nGoodsOrder + 1
						)
						IF @@ROWCOUNT = 0 GOTO ERROR2
						GOTO CleanUp
					END
				END
			END
			-- 成本核算法到此结束
		END
		/*---------------------修改期初--------------------*/
	END
	/* 修改往来单位对应的往来余额 */
	ELSE IF @szATypeID = @AR_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,ARTotal,nARTotal,cid)
				SELECT @szBTypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		ArTotal = ISNULL(ARTotal,0) + @dtotal,
						nARTotal = ISNULL(nARTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND CID = @cid
			END
			
			
			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END
	ELSE IF @szATypeID = @YF_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,YFTotal,nYFTotal,CID)
				SELECT @szBTypeID,@szSTypeID,@dtotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		YFTotal = ISNULL(YFTotal,0) + @dtotal,
						nYFTotal = ISNULL(nYFTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND cid =@cid
			END

			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END
	ELSE IF @szATypeID = @AP_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,APTotal,nAPTotal,cid)
				SELECT @szBTypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		APTotal = ISNULL(APTotal,0) + @dtotal,
						nAPTotal = ISNULL(nAPTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND CID = @cid
			END
			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END
	ELSE IF @szATypeID = @YS_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,YSTotal,nYSTotal,cid)
				SELECT @szBTypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		YSTotal =ISNULL(YSTotal,0) + @dtotal,
						nYSTotal = ISNULL(nYSTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND CID = @cid
			END

			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END 
	--处理应付暂估余额
	ELSE IF @szATypeID = @GRIR_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,GRIRTotal,nGRIRTotal,cid)
				SELECT @szBTypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		GRIRTotal = ISNULL(GRIRTotal,0) + @dtotal,
						nGRIRTotal = ISNULL(nGRIRTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND CID = @cid
			END
			
			
			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END
	--处理应收发出商品
	ELSE IF @szATypeID = @FC_ID AND @szBTypeID <> '0'
	BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT BTypeID
				FROM BType_ARAPTotal
				WHERE BTypeID=@szBTypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT BType_ARAPTotal(BTypeID,STypeID,FCTotal,nFCTotal,cid)
				SELECT @szBTypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	BType_ARAPTotal 
				SET		FCTotal = ISNULL(FCTotal,0) + @dtotal,
						nFCTotal = ISNULL(nFCTotal,0) + @dntotal
				WHERE	BTypeID = @szBTypeID 
						AND STypeID=@szSTypeID
						AND CID = @cid
			END
			
			
			IF @@ROWCOUNT = 0 GOTO ERROR4
			ELSE
			BEGIN
				GOTO SUCCESS
			END
		END
	END
	ELSE 
		BEGIN
		IF @szPeriod = ''
		BEGIN
			IF NOT EXISTS(
				SELECT ATypeID
				FROM AType_Total
				WHERE ATypeID=@szATypeID AND STypeID=@szSTypeID AND CID=@cid
			)
			BEGIN
				INSERT AType_Total(ATypeID,STypeID,Total,Ntotal,CID)
				SELECT @szATypeID,@szSTypeID,@dTotal,@dntotal,@cid
			END
			ELSE
			BEGIN
				UPDATE	AType_Total 
				SET		Total = ISNULL(Total,0)+@dTotal,
						Ntotal = ISNULL(Ntotal,0) + @dntotal
				WHERE	ATypeID = @szATypeID 
						AND STypeID=@szSTypeID
						AND CID=@cid
			END
			
			IF @@ROWCOUNT = 0 GOTO ERROR4 ELSE GOTO SUCCESS
		END 
	END

	CLEANUP:
		-- 返回成功值并退出
		-- 释放游标
		DEALLOCATE ModifyDbf_Cursor
		-- commit tran --ModifyDbf

		RETURN 0

	ERROR1:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -1

	ERROR2:
		DEALLOCATE ModifyDbf_Cursor
		-- rollback tran --ModifyDbf
		RETURN -2

	ERROR3:
		-- 当数量为 0 时，回滚 这边没有定义游标 不需要释放
		-- 一般非物流单据过账时会出现这种情况
		-- rollback tran --ModifyDbf
		--DEALLOCATE ModifyDbf_Cursor
		RETURN 0


	ERROR4:
		-- rollback tran --ModifyDbf
		DEALLOCATE ModifyDbf_Cursor
		RETURN -4

	ERRORINPUTCOSTPRICE:
		-- 若最终得出的成本均价 = 0，则页面会提示输入成本价，该价格会写入商品最近进价
		DEALLOCATE ModifyDbf_Cursor
		RETURN -5

	ERRORINIMODIFYDENY:
		-- 系统已正式开账，不能修改期初
		RETURN -6

	SUCCESS:
		-- 执行成功
		-- commit tran --ModifyDbf
		RETURN 0

GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	功能说明： 代销成本核算，及代销库数据处理
	作    者： 卢  春
	最后修改： 2004-08-16
*/
CREATE                       PROCEDURE Gp_ModifyDbf_DX 
(
	@nVchType			numeric(4,0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本核算法 (暂不用)
	@szAtypeID			varchar(50),			-- 3. 会计科目 ID 值
	@szPtypeID			varchar(50),			-- 4. 商品 ID 值
	@szBtypeID			varchar(50),			-- 5. 往来单位 ID 值
	@szEtypeID			varchar(50),			-- 6. 职员 ID 值
	@szKtypeID			varchar(50),			-- 7. 仓库 ID 值
	@szStypeID			varchar(50),			
	@szPeriod			varchar(2),				-- 8. 期号 (暂不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量
	@dCostTotal			 NUMERIC(24, 10) ,			-- 10. 成本金额 (有正负号)
												--	   最新改为两位小数精度
	@DXTaxTotal			 NUMERIC(24, 10) ,			-- 11. 代销含税金额
	@DXTotal			 NUMERIC(24, 10) ,			-- 12. 代销金额
	@szJobNo			varchar(20),			-- 13. (暂时不用)
	@nGoodsNo			int,					-- 14. (暂时不用)
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 15. 影响的成本金额变化值 (输出)
	@MakeDate			datetime = null,		-- 16. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0		-- 17. (暂时不用)
)
--@encode$--
AS
SET NOCOUNT ON
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -6 期初不能修改
 -7 异常
-----------------------------
*/
--------Some vchtype
DECLARE @GOODS_ID varchar(50)

SELECT
	@GOODS_ID=nid
FROM Ac_Items
WHERE UserCode='1241'	


------------------
DECLARE	@szSql					varchar(500),
		@dbName					varchar(20),
		@szJobNumber			varchar(20),
		@nAllowNegativeStock	int,
		@dTotalTemp				 NUMERIC(24, 10) ,
		@dQtyTemp				 NUMERIC(24, 10) ,
		@dCostTotalTemp			 NUMERIC(24, 10) ,
		@dCostQtyTemp			 NUMERIC(24, 10) ,
        @dPriceTemp				 NUMERIC(24, 10) ,
		@dCostPriceTemp			 NUMERIC(24, 10) ,
		@nPeriod				int,
		@OutFactoryDate			datetime,
		@nGoodsOrder			int,
		@dTaxTotalTemp			 NUMERIC(24, 10) 

SET	@dCostPrice		= 0
SET @dTotalTemp		= 0
SET @dQtyTemp		= 0
SET @dCostTotalTemp	= 0
SET @dCostQtyTemp	= 0
SET @dPriceTemp		= 0
SET @dCostPriceTemp	= 0

EXEC GP_GetSubValue 'AllowNegativeStock',@szStypeID, @nAllowNegativeStock output
-- begin tran Modifydbf
-- save tran Modifydbf

DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT

IF @szATypeID = @GOODS_ID AND @szPTypeID <> '0'
BEGIN
	IF @dQty = 0 AND @dCostTotal <> 0
	BEGIN
		--RAISERROR('数据出错！',16,1)
		--RETURN -7
		RETURN -9
	END

	IF @nVchType IN (140,141,142,143) SET @nVchType = 140
	IF @nVchType IN (144,145,146,147) SET @nVchType = 144

	/*----------代销库出入库处理----------*/
	IF @szKTypeID = '10000'
	BEGIN
		DELETE FROM CommissionStock WHERE Qty = 0 AND Total = 0 AND CostTotal = 0

		IF @dQty = 0 GOTO ERROR3

		DECLARE ModifyDbf_Cursor CURSOR FOR
			SELECT	Qty,
					CostTotal,
					Total,
					TaxTotal,
					CASE Qty WHEN 0 THEN 0
					ELSE CONVERT( NUMERIC(24, 10) , CostTotal/Qty)
					END AS CostPrice
			FROM	CommissionStock
			WHERE	PTypeID = @szPTypeID
					AND Type = @nVchType
					AND BTypeID = @szBTypeID
					AND STypeID=@szStypeID
			FOR UPDATE

		OPEN ModifyDbf_Cursor
		FETCH NEXT FROM ModifyDbf_Cursor INTO	@dCostQtyTemp,
												@dCostTotalTemp,
												@dTotalTemp,
												@dTaxTotalTemp,
												@dCostPriceTemp
		-- 代销库中有此商品的相关记录
		IF @@FETCH_STATUS = 0
		BEGIN
			IF @dQty < 0
			BEGIN
				IF @dCostQtyTemp < ABS(@dQty) 
				BEGIN
					DEALLOCATE ModifyDbf_Cursor
					RETURN -7--GOTO ERROR5
				END
			END

			IF @dCostTotal <> 0 SET @dCostPriceTemp =ROUND(CAST(@dCostTotal AS NUMERIC(24,10))/CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)

			

			/*------代销出库------*/
			IF @dQty < 0
			BEGIN
				IF @dCostQtyTemp < ABS(@dQty) 
				BEGIN
					DEALLOCATE ModifyDbf_Cursor
					RETURN -7--GOTO ERROR5
				END

				IF @dCostQtyTemp = ABS(@dQty)
				BEGIN
					IF @dCostTotal = 0 AND @dTotalTemp = @DXTotal
					BEGIN
						DELETE FROM	CommissionStock
						WHERE CURRENT OF ModifyDbf_Cursor

						SET @dCostPrice = ROUND(@dCostTotalTemp,@intPriceDot)
					END
					ELSE
					BEGIN
						SET @dCostTotalTemp	= ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(@dCostTotal,@intMoneyDot)
						SET @dQtyTemp		= @dCostQtyTemp + @dQty
						SET @dTotalTemp		= @dTotalTemp + @DXTotal
						SET @dCostPrice		= ABS(ROUND(@dCostTotal,@intPriceDot))

						UPDATE	CommissionStock
						SET		Total		= ROUND(@dTotalTemp,@intMoneyDot),
								Qty			= @dQtyTemp,
								CostTotal	= ROUND(@dCostTotalTemp,@intMoneyDot)
						WHERE CURRENT OF ModifyDbf_Cursor
					END

					GOTO CleanUp
				END
				ELSE
				BEGIN

					SET @dTotalTemp		= ROUND(@dTotalTemp,@intMoneyDot) + ROUND(@DXTotal,@intMoneyDot)
					SET @dCostTotalTemp	= @dCostTotalTemp + ROUND(@dCostTotal,@intMoneyDot)
					SET @dQtyTemp		= @dCostQtyTemp + @dQty

					UPDATE	CommissionStock
					SET		Total		= ROUND(@dTotalTemp,@intMoneyDot),
							Qty			= @dQtyTemp,
							CostTotal	= ROUND(@dCostTotalTemp,@intMoneyDot)
					WHERE CURRENT OF ModifyDbf_Cursor

					IF @dCostTotal <> 0
						SET @dCostPrice = ABS(@dCostTotal)
					ELSE
						SET @dCostPrice = ROUND(ABS(@dQty * @dCostPriceTemp),@intMoneyDot)
					GOTO CleanUp
				END
			END
			/*------代销入库------*/
			ELSE
			BEGIN
				IF @dCostTotal = 0 AND @nVchType <> 140
				BEGIN
					SET @dCostTotal = ROUND(CAST(@dCostPriceTemp AS NUMERIC(24,10))* CAST(@dQty AS NUMERIC(24,10)),@intMoneyDot)
				END

				SET @dCostTotalTemp	= ROUND(@dCostTotalTemp,@intMoneyDot) + ROUND(@dCostTotal,@intMoneyDot)
				SET @dTotalTemp		= ROUND(@dTotalTemp,@intMoneyDot) + ROUND(@DXTotal,@intMoneyDot)
				SET @dQtyTemp		= @dCostQtyTemp + @dQty

				IF @dQtyTemp <> 0
					SET @dCostPriceTemp = ROUND(CAST(@dTotalTemp AS NUMERIC(24,10))/CAST(@dQtyTemp AS NUMERIC(24,10)),@intPriceDot)
				ELSE
					SET @dCostPriceTemp = 0

				UPDATE	CommissionStock
				SET		Total		= ROUND(@dTotalTemp,@intMoneyDot),
						Qty			= @dQtyTemp,
						CostTotal	= ROUND(@dCostTotalTemp,@intMoneyDot)
				WHERE CURRENT OF ModifyDbf_Cursor

				SET @dCostPrice = ROUND(@dCostTotal,@intPriceDot)
				GOTO CleanUp
			END
		/********
			代销库中无此商品的相关记录
		********/
		END
		ELSE
		BEGIN
			IF @dQty < 0 
			BEGIN
				DEALLOCATE ModifyDbf_Cursor
				RETURN -7--GOTO ERROR5
			END

			IF @dCostTotal = 0
			BEGIN
				SET @dCostTotal = ROUND(@dCostTotalTemp,@intMoneyDot)
			END

			SET @dCostPriceTemp	= ROUND(CAST(@dCostTotal AS NUMERIC(24,10))/CAST(@dQty AS NUMERIC(24,10)),@intPriceDot)
			SET @dTotalTemp		= @dCostTotal

			INSERT	CommissionStock (
				PTypeID,
				BTypeID,
				STypeID,
				Type,
				Qty,
				CostTotal,
				Total
			)
			VALUES (
				@szPTypeID,
				@szBTypeID,
				@szStypeID,
				@nVchType,
				@dQty,
				@dCostTotal,
				@DXTotal
			)

			SET @dCostPrice = ABS(ROUND(@dCostTotal,@intPriceDot))
			GOTO CleanUp
		END
	END
END

CleanUp:
	DEALLOCATE ModifyDbf_Cursor
	-- commit tran --ModifyDbf
	RETURN 0

ERROR1:
	DEALLOCATE ModifyDbf_Cursor
	-- rollback tran --ModifyDbf
	RETURN -1

ERROR2:
	DEALLOCATE ModifyDbf_Cursor
	-- rollback tran --ModifyDbf
	RETURN -2

ERROR3:
	DEALLOCATE ModifyDbf_Cursor
	-- rollback tran --ModifyDbf
	RETURN 0

ERROR4:
	DEALLOCATE ModifyDbf_Cursor
	-- rollback tran --ModifyDbf
	RETURN -4

ERROR5:
	DEALLOCATE ModifyDbf_Cursor
	-- rollback tran --ModifyDbf
	RETURN -2

ERRORINPUTCOSTPRICE:
	DEALLOCATE ModifyDbf_Cursor
	RETURN -5

ERRORINIMODIFYDENY:
	RETURN -6

SUCCESS:
	-- commit tran --ModifyDbf
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
新维修 - 核心过账
*/
CREATE     PROCEDURE Gp_ModifyDbf_WX (
	@nVchType			numeric(4, 0),			-- 1. 单据类型
	@szCostingMethod	varchar(1),				-- 2. 成本算法
	@szATypeID			varchar(50),			-- 3. 会计科目 ID
	@szPTypeID			varchar(50),			-- 4. 商品 ID
	@szBTypeID			varchar(50),			-- 5. 往来单位 ID
	@szETypeID			varchar(50),			-- 6. 经手人 ID
	@szKTypeID			varchar(50),			-- 7. 仓库 ID
	@szPeriod			varchar(2),				-- 8. 期号 (暂时不用)
	@dQty				 NUMERIC(24, 10) ,			-- 9. 商品数量 ( 有正负号 )
	@intItemID			INT,
	@intIsCombined		TINYINT,
	@dNQty				 NUMERIC(24, 10) ,
	@dTotal				 NUMERIC(24, 10) ,			-- 10. 成本金额 ( 有正负号 )
												--     最新改为两位精度
	@szJobNo			varchar(20),			-- 11. (暂时不用)
	@nGoodsNo			int,					-- 12. (暂时不用)
	@GoodsNumber		varchar(100),			-- 13. 批号(手工指定)
	@ProduceDate		varchar(50),			-- 14. 生产日期(手工指定)
	@ValidDate			varchar(50),			-- 15. 效期至(手工指定)
	@GoodsCostPrice		 NUMERIC(24, 10) ,			-- 16. 批次成本单价
	@HandZeroCost		int,					-- 17. 是否为手工输入0成本标志
	@dCostPrice			 NUMERIC(24, 10)  output,	-- 18. 成本单价 (输出)
	@MakeDate			datetime = null,		-- 19. (暂时不用)
	@dPrice				 NUMERIC(24, 10)  = 0		-- 20. (暂时不用)
)
--@encode$--
AS
SET NOCOUNT ON
/*
--------Return values--------
  0 Success
 -1 库存数量不够
 -2 failure
 -3 数量为零
 -5 提示输入成本价
 -6 期初不能修改
 -7 异常
-----------------------------
*/
SET @dCostPrice = 0
DECLARE @dCostQtyTemp  NUMERIC(24, 10) , @dQtyTemp  NUMERIC(24, 10) ,@dCostNQtyTemp  NUMERIC(24, 10) ,@dNQtyTemp  NUMERIC(24, 10) 

DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT

-- （1）读取维修库中对应仓库的商品数量
DECLARE ModifyDbf_Cursor CURSOR FOR
	SELECT Qty,NQty FROM wx_GoodsStocks 
	WHERE 
		PTypeID = @szPTypeID 
		AND KTypeID = @szKTypeID 
		AND ItemID=@intItemID
		AND IsCombined=@intIsCombined
		AND GoodsNumber=@GoodsNumber
FOR UPDATE

OPEN ModifyDbf_Cursor
FETCH NEXT FROM ModifyDbf_Cursor INTO @dCostQtyTemp,@dCostNQtyTemp
IF @@FETCH_STATUS = 0
BEGIN
	SELECT
		@dQtyTemp = ROUND(@dCostQtyTemp,@intQtyDot) + ROUND(@dQty,@intQtyDot),
		@dNQtyTemp = ROUND(@dCostNQtyTemp,@intQtyDot) + ROUND(@dNQty,@intQtyDot)

	IF @dQty < 0
	BEGIN
		IF @dQtyTemp = 0 AND @dNQtyTemp=0
		BEGIN
			DELETE FROM wx_GoodsStocks WHERE CURRENT OF ModifyDbf_Cursor
			IF @@ROWCOUNT = 0 GOTO ERROR2
		END
		ELSE
		BEGIN
			IF @dQtyTemp < 0 OR @dNQtyTemp<0 GOTO ERROR1

			UPDATE wx_GoodsStocks SET Qty = @dQtyTemp,NQty = @dNQtyTemp WHERE CURRENT OF ModifyDbf_Cursor
			IF @@ROWCOUNT = 0 GOTO ERROR2
		END
	END
	ELSE
	BEGIN
		UPDATE wx_GoodsStocks SET Qty = @dQtyTemp,NQty = @dNQtyTemp WHERE CURRENT OF ModifyDbf_Cursor
		IF @@ROWCOUNT = 0 GOTO ERROR2
	END
END
ELSE
BEGIN
	IF @dQty < 0 OR @dNQtyTemp <0 GOTO ERROR1
	ELSE
	BEGIN
		SELECT 
			@dQty=ROUND(@dQty,@intQtyDot),
			@dNQty=ROUND(@dNQty,@intQtyDot)
	
		INSERT INTO wx_GoodsStocks (PTypeID,KTypeID,GoodsNumber,Qty,ItemID,IsCombined,NQty) VALUES (@szPTypeID,@szKTypeID,@GoodsNumber,@dQty,@intItemID,@intIsCombined,@dNQty)
		IF @@ROWCOUNT = 0 GOTO ERROR2
	END
END

CLEANUP:
	-- 返回成功值并退出
	-- 释放游标
	DEALLOCATE ModifyDbf_Cursor
	RETURN 0

ERROR1:
	DEALLOCATE ModifyDbf_Cursor
	RETURN -61

ERROR2:
	DEALLOCATE ModifyDbf_Cursor
	RETURN -2


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-03-09
	描述：修改操作员类型，处理ERP,POS,手机版同步
*/
CREATE         PROCEDURE Gp_ModifyOperatorType
(
	@ETypeID		VARCHAR(100),	-- 职员 ID 值
	@IsErp			INT,			-- 是否ERP操作员
	@IsMobile		INT,			-- 是否手机操作员
	@IsPos			INT = 0			-- 是否POS操作员
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********

-- 获取数据表 LoginUser 中操作员数
DECLARE @intLoginUserCount INT
SELECT	@intLoginUserCount = COUNT(*)
FROM	LoginUser
WHERE	IsErp = 1		

DECLARE @N INT, @intDogUserCount INT, @intVersion INT
-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS INT)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN 1688

DECLARE @intBit INT, @intMask INT
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

-- 判断软件狗用户数
SELECT	@N = CAST(SubValue AS INT)
FROM	SysData1
WHERE	SubNo = 3	-- 检查用户数

IF @N IS NULL RETURN 1688

IF @intVersion IN (2,3,5,7,9,11,13,15)	-- 试用版
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE subname = 'Proinfo' AND SubValue = '4')
			SELECT @intDogUserCount = 3
		ELSE
			SELECT @intDogUserCount = 5
	END
ELSE
	BEGIN
		IF @IsErp=1
		BEGIN
			SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
			IF ( 3 & @N <> 3 ) RETURN 1688
		END 
	END

-- 若实际操作员数 > 软件狗许可用户数，则不允许过账
IF @intLoginUserCount - 1 > @intDogUserCount 
	RETURN 1688
ELSE IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @ETypeID AND isErp = 0)
	BEGIN
		IF @IsErp = 1 AND @intLoginUserCount > @intDogUserCount
			RETURN 1688
	END

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - END	********
UPDATE LoginUser
SET
	IsErp=@IsErp,
	IsMobile=@IsMobile,
	IsPos=@IsPos
WHERE
	etypeid=@ETypeID
--如果是ERP转POS 则多级权限范围为所有权限	
IF(@IsPos=1)
	BEGIN
		UPDATE LoginUser
		SET
			BTypeID='00000',
			MangerBTypeID='00001',
			MangerPTypeID='00000',
			MangerBTypeID2='00002',
			MangerETypeID='00001',
			MangerKTypeID='00000',
			MangerATypeID='00000',
			MangerExpense='0000',
			MangerIncome='0000',
			MangerCpaital='0000',
			MangerSTypeID='00000',
			MangerOtherCpaital='0000',
			MangerLiabilities='0000',
			MangerRevenue='0000',
			MangerPay='0000',
			MangerDTypeID='00000',
			MangerBankID='00000'
		WHERE etypeid=@ETypeID
	END

--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'

RETURN 0		

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_ModifyPriceInfo]    Script Date: 04/23/2012 09:33:25 ******/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

-- ========================================================================
-- 功能说明：		保存物价信息
-- 作者    ：		舒珊
-- 时间：			2017-01-16
-- ========================================================================
CREATE    PROCEDURE [dbo].[Gp_ModifyPriceInfo]
(
	@ptypeid	VARCHAR(50),
	@prebuyprice1  numeric(24,10),
	@prebuyprice2  numeric(24,10),
	@prebuyprice3  numeric(24,10),
	@prebuyprice4  numeric(24,10),
	@prebuyprice5  numeric(24,10),
	@topbuyprice   numeric(24,10),	
	@presaleprice1  numeric(24,10),
	@presaleprice2  numeric(24,10),
	@presaleprice3  numeric(24,10),
	@presaleprice4  numeric(24,10),
	@presaleprice5  numeric(24,10),
	@presaleprice6  numeric(24,10),
	@presaleprice7  numeric(24,10),
	@presaleprice8  numeric(24,10),
	@presaleprice9  numeric(24,10),
	@presaleprice10  numeric(24,10),
	@retailprice    numeric(24,10),
	@LowSalePrice	numeric(24,10),
	@TopSalePrice	numeric(24,10),
	@recprice		numeric(24,10),
	@referprice		numeric(24,10),
	@unitsid			int,
	@ifa8				int   --v3 a8修改有差别
)
--@encode$--

AS

declare @isdefaultunit		int=0	,	--是否是基本单位
		@ErrorCNT		   INT=0	,
		@RecAmgSTypeBuyPrice numeric(24,10),
		@RecAmgSTypeSalePrice numeric(24,10)
		
SELECT @isdefaultunit=isdefaultunit FROM PType_Units_Ext  WHERE PTYPEID=@ptypeid  and isuse=1 and  unitsid=@Unitsid

select @RecAmgSTypeBuyPrice=isnull(RecAmgSTypeBuyPrice,0),@RecAmgSTypeSalePrice=isnull(RecAmgSTypeSalePrice,0) from PType_Price where PTypeID=@ptypeid and UnitID=@Unitsid

--获取基本单位原数据

BEGIN TRAN TranNew--开始事务

	DELETE PType_Price where PTypeID=@ptypeid and UnitID=@Unitsid
	INSERT INTO dbo.PType_Price
     ( 
		  PtypeID,
		  UnitId,
		  PreBuyPrice1 ,
		  PreBuyPrice2 ,
		  PreBuyPrice3 ,
		  PreBuyPrice4 ,
		  PreBuyPrice5 ,
		  PreSalePrice1 ,
		  PreSalePrice2 ,
		  PreSalePrice3 ,
		  PreSalePrice4 ,
		  PreSalePrice5 ,
		  PreSalePrice6 ,
		  PreSalePrice7 ,
		  PreSalePrice8 ,
		  PreSalePrice9 ,
		  PreSalePrice10 ,
		  RetailPrice ,
		  TopSalePrice ,
		  LowSalePrice ,  
		  TopBuyPrice  ,
		  ReferPrice,
		  IsDefaultUnit ,
		  RecAmgSTypeBuyPrice,
          RecAmgSTypeSalePrice
        )
	 SELECT  
			@ptypeid AS PtypeID,
			@Unitsid as UnitId,
			isnull(@prebuyprice1,0),
			isnull(@prebuyprice2,0),
			isnull(@prebuyprice3,0),
			isnull(@prebuyprice4,0),
			isnull(@prebuyprice5,0),
			isnull(@presaleprice1,0),
			isnull(@presaleprice2,0),
			isnull(@presaleprice3,0),
			isnull(@presaleprice4,0),
			isnull(@presaleprice5,0),
			isnull(@presaleprice6,0),
			isnull(@presaleprice7,0),
			isnull(@presaleprice8,0),
			isnull(@presaleprice9,0),
			isnull(@presaleprice10,0),
			isnull(@retailprice,0),
			isnull(@topsaleprice,0),
			isnull(@lowsaleprice,0),
			isnull(@topbuyprice,0),
			case when @isdefaultunit =0 then 0 else isnull(@referprice,0) end,
			@isdefaultunit,
			case when @ifa8=0 then isnull(@recprice,0) else isnull(@RecAmgSTypeBuyPrice ,0) end,
			isnull(@RecAmgSTypeSalePrice,0)
									
		SET @ErrorCNT+= @@ERROR
	
	--非基本单位 的 其他价格全部为0 则删除不保存到表里面
	DELETE ptype_price 
	where	ptypeid=@ptypeid
		and UnitId=@Unitsid
		and IsDefaultUnit=0
	    and isnull([PreBuyPrice1] ,0)=0 
		and isnull([PreBuyPrice2] ,0)=0 
		and isnull([PreBuyPrice3] ,0)=0 
		and isnull([PreBuyPrice4] ,0)=0 
		and isnull([PreBuyPrice5] ,0)=0 
		and isnull([PreSalePrice1] ,0)=0 
		and isnull([PreSalePrice2] ,0)=0 
		and isnull([PreSalePrice3] ,0)=0 
		and isnull([PreSalePrice4] ,0)=0 
		and isnull([PreSalePrice5] ,0)=0 
		and isnull([PreSalePrice6] ,0)=0 
		and isnull([PreSalePrice7] ,0)=0 
		and isnull([PreSalePrice8] ,0)=0 
		and isnull([PreSalePrice10] ,0)=0 
		and isnull([RetailPrice] ,0)=0 
		and isnull([TopSalePrice] ,0)=0 
	    and isnull([LowSalePrice] ,0)=0 
	    and isnull(TopBuyPrice,0)=0 
		and isnull(ReferPrice,0)=0 
		and isnull(RecAmgSTypeBuyPrice,0)=0
		and isnull(RecAmgSTypeSalePrice,0)=0
		
	SET @ErrorCNT+= @@ERROR
		
	
 DECLARE @XiWaMaxNumber INT
                                  
select @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
update PType_Price set XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@ptypeid
IF @ifa8=0
BEGIN
	DELETE dbo.PType_StypePrice WHERE PTypeID=@ptypeid AND Stypeid='00001' and unitid in (select unitid from PType_Price where ptypeid=@ptypeid)
	INSERT dbo.PType_StypePrice 
			(       PTypeID,
					Stypeid,
					Recprice,
					unitid,
					IsDefaultUnit
			) 
		select ptypeid,
			  '00001',
			   RecAmgSTypeBuyPrice,
			   unitid,
				IsDefaultUnit
		from PType_Price 
	   where ptypeid=@ptypeid
	  SET @ErrorCNT+= @@ERROR 

 
END
IF NOT EXISTS(SELECT 1 FROM PosReDataGlobal WHERE  stypeid='-99999')
    BEGIN
        INSERT INTO PosReDataGlobal VALUES(1,'-99999')
    END
ELSE
	BEGIN
    IF  EXISTS(SELECT 1 FROM PosReDataGlobal WHERE stypeid='-99999') 
        BEGIN
                UPDATE PosReDataGlobal SET ifredata=1 where stypeid='-99999'
        END
	END
IF NOT EXISTS(SELECT 1 FROM PosIsUpdateData WHERE  tbType='PType_Price' and stypeid='-99999' and tid=0 )
    BEGIN
        INSERT INTO PosIsUpdateData VALUES('PType_Price',0,1,'-99999')
    END
ELSE
	BEGIN
    IF  EXISTS(SELECT 1 FROM PosIsUpdateData WHERE  tbType='PType_Price' AND Tid=0 AND ifUpdate=1 AND stypeid='-99999' ) 
        BEGIN
                UPDATE PosIsUpdateData SET ifUpdate=1,stypeid='-99999',Tid=0 where tbType='PType_Price'
        END
	END
	
--修改商品档案的缓存最大值
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM PType

UPDATE PType SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeId=@ptypeid


-- 操作返回值
IF @ErrorCNT>0
BEGIN
	ROLLBACK TRAN TranNew
	RAISERROR('保存失败！',16,1) 
	RETURN -1	-- 失败	
	
END
ELSE
begin
	COMMIT TRAN insertTranNew
	RETURN 0	-- 成功
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


--数据搬移.将typeid(节点和叶子)搬移到Newparid下
--author:王跃
--last modified date:2001-10-15
--注意：该过程不能向已被使用的叶子搬移
CREATE   PROCEDURE gp_MoveData
(
 @flag int=1,--@flag =1 : 商品编号 2:银行帐户 3:往来单位 4:职员 5:仓库
 @typeid varchar(50),
 @newparid varchar(50)
)
--@encode$--
 AS
  set nocount on
  if len(@newparid)>=50 return 1
  declare @newlen int,@maxlen int
  declare @newleveal int,@curleveal int  
  declare @newtypeid varchar(50)
  declare @soncount int
  declare @oldparid varchar(50)
  declare @TableName varchar(128)
  declare @TableName1 varchar(300)
  declare @sql varchar(1000)
  
  select @newlen=len(@newparid)
  if @flag=1 --商品
  begin
	   if not exists(select * from ptype where typeid=@typeid) return 4 --记录不存在
	   if not exists(select * from ptype where typeid=@newparid) return 4 --父记录不存在
 
	   select @maxlen=max(len(typeid)) from ptype where left(typeid,len(@typeid))=@typeid 

	   if @maxlen-len(@typeid)+@newlen>=50 return 2 --无法搬移
	   select @newleveal=isnull(leveal,0)+1 from ptype where typeid=@newparid
	   select @curleveal=leveal from ptype where typeid=@typeid
	   select @soncount=isnull(soncount,0)+1 from ptype where typeid=@newparid
	   if len(cast(@soncount as varchar(20)))>5 return 6

   
	   if @newparid='00000' 
	      select @newtypeid=REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
	   else
	      select @newtypeid=@newparid+REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
   
	   select @oldparid=parid from ptype where typeid=@typeid
	   if @oldparid=@newparid return 3 --不需要搬移


	   --开始替换
	   begin tran


	   declare ptype_cursor cursor
	   for
	      select o.[name] as tablename from syscolumns c inner join sysobjects o on(c.[id]=o.[id]) where c.[name]='ptypeid' and o.type='u'
	   for read only
  
	   open ptype_cursor
	   fetch next from ptype_cursor into  @TableName
	   while @@fetch_status=0
	   begin
	  	   if @soncount=1 --叶子检查是否已被使用
		   begin
		   select @sql= 'select * from  '+ @TableName +' where ptypeid='''+@newparid+''''
		   exec(@sql)
		   if @@rowcount>0
		      begin
		       rollback tran
		       close ptype_cursor
		       deallocate ptype_cursor
		       return 5
		     end
                             end

		   select @sql= 'update  '+ @TableName +' set ptypeid='''+@newtypeid+'''+right(ptypeid,len(ptypeid)-len('''+@typeid+''')) where left(ptypeid,len('''+@typeid+'''))='''+@typeid+''''
		   exec(@sql)
		   if @@error<>0
		   begin
	               rollback tran
		       close ptype_cursor
		       deallocate ptype_cursor
		       return -1
		   end
                            --   print @sql
		  fetch next from ptype_cursor into  @TableName
	  end

	  close ptype_cursor
	  deallocate ptype_cursor

	  update ptype set sonnum=sonnum-1 where typeid=@oldparid --将@typeid 的父节点的儿子数减一
	  if @@error<>0
	  begin
	     rollback tran
	     return -1
	  end

               --更新该节点下儿子节点的typeid
	 update ptype set typeid=@newtypeid+right(typeid,len(typeid)-len(@typeid)),leveal=leveal-@curleveal+@newleveal,parid=@newtypeid+right(parid,len(parid)-len(@typeid)) where left(typeid,len(@typeid))=@typeid and typeid<>@typeid --更新儿子的typeid
 	 if @@error<>0
	 begin
	             	rollback tran
	             return -1
             end


            update loginuser  set MangerPTypeID=@newtypeid+right(MangerPTypeID,len(MangerPTypeID)-len(@typeid)) where left(MangerPTypeID,len(@typeid))=@typeid
           if @@error<>0
           begin
	            rollback tran
	            return -1
           end

           --更新节点本身
           update ptype set typeid=@newtypeid,leveal=@newleveal,parid=@newparid where typeid=@typeid
           if @@error<>0
           begin
	           rollback tran
	           return -1
           end
          update ptype set sonnum=sonnum+1,soncount=soncount+1 where typeid=@newparid
          if @@error<>0
          begin

	     rollback tran
	     return -1
         end

    insert  sysmovedata values(@typeid,@newparid,@flag,getdate())
    if @@error<>0
    begin
     rollback tran
     return -1
    end

        commit tran                 
        return 0 
 end
 else
 
  if @flag=2 --银行帐户
	  begin
	   --除『全部银行存款合计』『其他收入』『费用合计』其他不允许搬移
	   if left(@typeid,10)<>'0000100004' and left(@typeid,10)<>'0000300003' and left(@typeid,10)<>'0000400003' return 7
	   if @typeid in('000040000300001','000040000300002','000030000300001','000030000300002') return 7
	   if left(@typeid,10)<>left(@newparid,10) return 7
	   if not exists(select * from atype where typeid=@typeid) return 4 --记录不存在
	   if not exists(select * from atype where typeid=@newparid) return 4 --父记录不存在
	   select @maxlen=max(len(typeid)) from atype where left(typeid,len(@typeid))=@typeid 
	   if @maxlen-len(@typeid)+@newlen>=50 return 2
	   select @newleveal=isnull(leveal,0)+1 from atype where typeid=@newparid
	   select @curleveal=leveal from atype where typeid=@typeid
	   select @soncount=isnull(soncount,0)+1 from atype where typeid=@newparid
	   if len(cast(@soncount as varchar(20)))>5 return 6
   
	   if @newparid='00000' 
	      select @newtypeid=REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
	   else
	      select @newtypeid=@newparid+REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
   
	   select @oldparid=parid from atype where typeid=@typeid
	   if @oldparid=@newparid return 3
	   --开始替换


	   begin tran

	   declare atype_cursor cursor
	   for
	      select o.[name] as tablename from syscolumns c inner join sysobjects o on(c.[id]=o.[id]) where c.[name]='atypeid' and o.type='u'
	   for read only
  
  	   open atype_cursor
	   fetch next from atype_cursor into  @TableName
	   while @@fetch_status=0
	   begin

	   if @soncount=1 --叶子检查是否已被使用
	   begin
		   select @sql= 'select * from  '+ @TableName +' where atypeid='''+@newparid+''''
		   exec(@sql)
		   if @@rowcount>0
		   begin
		       rollback tran
		       close atype_cursor
		       deallocate atype_cursor
		       return 5
      	            end
             end
 
	   select @sql= 'update  '+ @TableName +' set atypeid='''+@newtypeid+'''+right(atypeid,len(atypeid)-len('''+@typeid+''')) where left(atypeid,len('''+@typeid+'''))='''+@typeid+''''
	   exec(@sql)
	   if @@error<>0
	      begin
		       rollback tran
		       close atype_cursor
		       deallocate atype_cursor
		       return -1
	      end
              --   print @sql
	  fetch next from atype_cursor into  @TableName
           end
 
           close atype_cursor
           deallocate atype_cursor


          update loginuser  set MangerATypeID=@newtypeid+right(MangerATypeID,len(MangerATypeID)-len(@typeid)) where left(MangerATypeID,len(@typeid))=@typeid
          if @@error<>0
          begin
	          rollback tran
                       return -1
          end

          update loginuser  set MangerExpense=@newtypeid+right(MangerExpense,len(MangerExpense)-len(@typeid)) where left(MangerExpense,len(@typeid))=@typeid
          if @@error<>0
          begin
	          rollback tran
                       return -1
          end

          update loginuser  set MangerIncome=@newtypeid+right(MangerIncome,len(MangerIncome)-len(@typeid)) where left(MangerIncome,len(@typeid))=@typeid
          if @@error<>0
          begin
	       rollback tran
	       return -1
          end

          update atype set sonnum=sonnum-1 where typeid=@oldparid --将@typeid 的父节点
          if @@error<>0
          begin
	         rollback tran
	         return -1
          end
          --更新该节点下儿子节点的typeid
           update atype set typeid=@newtypeid+right(typeid,len(typeid)-len(@typeid)),leveal=leveal-@curleveal+@newleveal,parid=@newtypeid+right(parid,len(parid)-len(@typeid)) where left(typeid,len(@typeid))=@typeid and typeid<>@typeid --更新儿子的typeid
           if @@error<>0
           begin
	           rollback tran
	           return -1
           end

	--更新节点本身
             update atype set typeid=@newtypeid,leveal=@newleveal,parid=@newparid where typeid=@typeid
	    if @@error<>0
	    begin
		     rollback tran
		     return -1
	    end
	    update atype set sonnum=sonnum+1,soncount=soncount+1 where typeid=@newparid
	    if @@error<>0
	    begin
		     rollback tran
		     return -1
	    end

    insert  sysmovedata values(@typeid,@newparid,@flag,getdate())
    if @@error<>0
    begin
     rollback tran
     return -1
    end

    commit tran                 
    return 0  
  end
  else
 
  if @flag=3 --往来单位
  begin
   if (@typeid='00001' and @newparid='00002') or (@typeid='00002' and @newparid='00001') or @newparid='00000' return 7
   if left(@typeid,5)<>left(@newparid,5) return 7 --客户供应商不允许交叉搬移
   if not exists(select * from btype where typeid=@typeid) return 4 --记录不存在
   if not exists(select * from btype where typeid=@newparid) return 4 --父记录不存在
   select @maxlen=max(len(typeid)) from btype where left(typeid,len(@typeid))=@typeid 
   if @maxlen-len(@typeid)+@newlen>=50 return 2
   select @newleveal=isnull(leveal,0)+1 from btype where typeid=@newparid
   select @curleveal=leveal from btype where typeid=@typeid
   select @soncount=isnull(soncount,0)+1 from btype where typeid=@newparid
   if len(cast(@soncount as varchar(20)))>5 return 6


   if @newparid='00000' 
      select @newtypeid=REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
   else
      select @newtypeid=@newparid+REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
   
   --print @newtypeid
   select @oldparid=parid from btype where typeid=@typeid
   if @oldparid=@newparid return 3
   --开始替换
   begin tran

	   declare btype_cursor cursor
	   for
	      select o.[name] as tablename from syscolumns c inner join sysobjects o on(c.[id]=o.[id]) where c.[name]='btypeid' and o.type='u'
	   for read only
  
  	   open btype_cursor
	   fetch next from btype_cursor into  @TableName
	   while @@fetch_status=0
	   begin

	   if @soncount=1 --叶子检查是否已被使用
	   begin
		   select @sql= 'select * from  '+ @TableName +' where btypeid='''+@newparid+''''
		   exec(@sql)
		   if @@rowcount>0
		   begin
		       rollback tran
		       close btype_cursor
		       deallocate btype_cursor
		       return 5
      	            end
            end

	   select @sql= 'update  '+ @TableName +' set btypeid='''+@newtypeid+'''+right(btypeid,len(btypeid)-len('''+@typeid+''')) where left(btypeid,len('''+@typeid+'''))='''+@typeid+''''
	   exec(@sql)
	   if @@error<>0
	      begin
		       rollback tran
		       close btype_cursor
		       deallocate btype_cursor
		       return -1
	      end
--   print @sql
	  fetch next from btype_cursor into  @TableName
    end
 
    close btype_cursor
    deallocate btype_cursor




    update btype set sonnum=sonnum-1 where typeid=@oldparid --将@typeid 的父节点
    if @@error<>0
    begin
     rollback tran
     return -1
    end
    --更新该节点下儿子节点的typeid
    update btype set typeid=@newtypeid+right(typeid,len(typeid)-len(@typeid)),leveal=leveal-@curleveal+@newleveal,parid=@newtypeid+right(parid,len(parid)-len(@typeid)) where left(typeid,len(@typeid))=@typeid and typeid<>@typeid --更新儿子的typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end
     update loginuser  set MangerBTypeID2=@newtypeid+right(MangerBTypeID2,len(MangerBTypeID2)-len(@typeid)) where left(MangerBTypeID2,len(@typeid))=@typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end
        
     update loginuser  set MangerBTypeID=@newtypeid+right(MangerBTypeID,len(MangerBTypeID)-len(@typeid)) where left(MangerBTypeID,len(@typeid))=@typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end

   --更新节点本身
    update btype set typeid=@newtypeid,leveal=@newleveal,parid=@newparid where typeid=@typeid
    if @@error<>0
    begin
     rollback tran
     return -1
    end
    update btype set sonnum=sonnum+1,soncount=soncount+1 where typeid=@newparid
    if @@error<>0
    begin
     rollback tran
     return -1
    end

    insert  sysmovedata values(@typeid,@newparid,@flag,getdate())
    if @@error<>0
    begin
     rollback tran
     return -1
    end

    commit tran                 
    return 0 
  end
  else
 
  if @flag=4 --职员
  begin
   if exists(select * from employee where typeid=@typeid and parid='00000') return 7 --职员第一级不允许搬移
   if left(@typeid,5)<>left(@newparid,5) return 7 --职员不允许交叉搬移
  
   if not exists(select * from employee where typeid=@typeid) return 4 --记录不存在
   if not exists(select * from employee where typeid=@newparid) return 4--父记录不存在
   select @maxlen=max(len(typeid)) from employee where left(typeid,len(@typeid))=@typeid 
   if @maxlen-len(@typeid)+@newlen>=50 return 2
   select @newleveal=isnull(leveal,0)+1 from employee where typeid=@newparid
   select @curleveal=leveal from employee where typeid=@typeid
   select @soncount=isnull(soncount,0)+1 from employee where typeid=@newparid
   if len(cast(@soncount as varchar(20)))>5 return 6

   if @newparid='00000' 
      select @newtypeid=REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
   else
      select @newtypeid=@newparid+REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
   
   --print @newtypeid
   select @oldparid=parid from employee where typeid=@typeid
   if @oldparid=@newparid return 3
   --开始替换进销存部分
   begin tran
	   declare etype_cursor cursor
	   for
	      select o.[name] as tablename from syscolumns c inner join sysobjects o on(c.[id]=o.[id]) where c.[name]='etypeid' and o.type='u'
	   for read only
  
  	   open etype_cursor
	   fetch next from etype_cursor into  @TableName
	   while @@fetch_status=0
	   begin

	   if @soncount=1 --叶子检查是否已被使用
	   begin
		   select @sql= 'select * from  '+ @TableName +' where etypeid='''+@newparid+''''
		   exec(@sql)
		   if @@rowcount>0
		   begin
		       rollback tran
		       close etype_cursor
		       deallocate etype_cursor
		       return 5
      	            end
            end

	   select @sql= 'update  '+ @TableName +' set etypeid='''+@newtypeid+'''+right(etypeid,len(etypeid)-len('''+@typeid+''')) where left(etypeid,len('''+@typeid+'''))='''+@typeid+''''
	   exec(@sql)
	   if @@error<>0
	      begin
		       rollback tran
		       close etype_cursor
		       deallocate etype_cursor
		       return -1
	      end
--   print @sql
	  fetch next from etype_cursor into  @TableName
    end
 
    close etype_cursor
    deallocate etype_cursor
--==============================================================
--==============================================================
--==============================================================
--肖伟2003年1月21日修改，增加OA部分职员的搬移【全部是以ETypeID_开头】
   declare @EtypeName varchar(300)
   declare etype_cursor1 cursor
   for
      select c.[name] as EtypeName,o.[name] as tablename from syscolumns c inner join sysobjects o on(c.[id]=o.[id]) where c.[name] like 'ETypeID_%' and o.type='u' and c.[name] <> 'etypeid2'
   for read only
 
   open etype_cursor1
   fetch next from etype_cursor1 into  @EtypeName,@TableName1
   while @@fetch_status=0
   begin

        if @soncount=1 --叶子检查是否已被使用
        begin
	   select @sql= 'select * from  '+ @TableName1 +' where '+@EtypeName+'='''+@newparid+''''
	   exec(@sql)
	   if @@rowcount>0
	   begin
	       rollback tran
	       close etype_cursor1
	       deallocate etype_cursor1
	       return 5
                end
        end

        select @sql= 'update  '+ @TableName1 +' set '+@EtypeName+'='''+@newtypeid+'''+right('+@EtypeName+',len('+@EtypeName+')-len('''+@typeid+''')) where left('+@EtypeName+',len('''+@typeid+'''))='''+@typeid+''''
        exec(@sql)
        if @@error<>0
        begin
	       rollback tran
	       close etype_cursor1
	       deallocate etype_cursor1
	       return -1
        end

        fetch next from etype_cursor1 into  @EtypeName,@TableName1
    end
 
    close etype_cursor1
    deallocate etype_cursor1
--==============================================================
--==============================================================
--==============================================================
    update employee set sonnum=sonnum-1 where typeid=@oldparid --将@typeid 的父节点
    if @@error<>0
    begin
     rollback tran
     return -1
    end
    --更新该节点下儿子节点的typeid
    update employee set typeid=@newtypeid+right(typeid,len(typeid)-len(@typeid)),leveal=leveal-@curleveal+@newleveal,parid=@newtypeid+right(parid,len(parid)-len(@typeid)) where left(typeid,len(@typeid))=@typeid and typeid<>@typeid --更新儿子的typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end

     update loginuser  set etypeid=@newtypeid+right(etypeid,len(etypeid)-len(@typeid)) where left(etypeid,len(@typeid))=@typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end

     update loginuser  set MangerETypeID=@newtypeid+right(MangerETypeID,len(MangerETypeID)-len(@typeid)) where left(MangerETypeID,len(@typeid))=@typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end
        
   --更新节点本身
    update employee set typeid=@newtypeid,leveal=@newleveal,parid=@newparid where typeid=@typeid
    if @@error<>0
    begin
     rollback tran
     return -1
    end
    update employee set sonnum=sonnum+1,soncount=soncount+1 where typeid=@newparid
    if @@error<>0
    begin
     rollback tran
     return -1
    end

    insert  sysmovedata values(@typeid,@newparid,@flag,getdate())
    if @@error<>0
    begin
     rollback tran
     return -1
    end

    commit tran                 
    return 0
  end
  else
 
  if @flag=5 --仓库
  begin
   if not exists(select * from stock where typeid=@typeid) return 4--记录不存在
   if not exists(select * from stock where typeid=@newparid) return 4--父记录不存在
   select @maxlen=max(len(typeid)) from stock where left(typeid,len(@typeid))=@typeid 
   if @maxlen-len(@typeid)+@newlen>=50 return 2
   select @newleveal=isnull(leveal,0)+1 from stock where typeid=@newparid
   select @curleveal=leveal from stock where typeid=@typeid
   select @soncount=isnull(soncount,0)+1 from stock where typeid=@newparid
   if len(cast(@soncount as varchar(20)))>5 return 6

   if @newparid='00000' 
      select @newtypeid=REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
   else
      select @newtypeid=@newparid+REPLICATE('0',5-len(cast(@soncount as varchar(5))))+cast(@soncount as varchar(5))    
   
   --print @newtypeid
   select @oldparid=parid from stock where typeid=@typeid
   if @oldparid=@newparid return 3
   --开始替换
   begin tran
	   declare ktype_cursor cursor
	   for
	      select o.[name] as tablename from syscolumns c inner join sysobjects o on(c.[id]=o.[id]) where c.[name]='ktypeid' and o.type='u'
	   for read only
  
  	   open ktype_cursor
	   fetch next from ktype_cursor into  @TableName
	   while @@fetch_status=0
	   begin

	   if @soncount=1 --叶子检查是否已被使用
	   begin
		   select @sql= 'select * from  '+ @TableName +' where ktypeid='''+@newparid+''''
		   exec(@sql)
		   if @@rowcount>0
		   begin
		       rollback tran
		       close ktype_cursor
		       deallocate ktype_cursor
		       return 5
      	            end
            end

	   select @sql= 'update  '+ @TableName +' set ktypeid='''+@newtypeid+'''+right(ktypeid,len(ktypeid)-len('''+@typeid+''')) where left(ktypeid,len('''+@typeid+'''))='''+@typeid+''''
	   exec(@sql)
	   if @@error<>0
	      begin
		       rollback tran
		       close ktype_cursor
		       deallocate ktype_cursor
		       return -1
	      end
--   print @sql
	  fetch next from ktype_cursor into  @TableName
    end
 
    close ktype_cursor
    deallocate ktype_cursor



    update stock set sonnum=sonnum-1 where typeid=@oldparid --将@typeid 的父节点
    if @@error<>0
    begin
     rollback tran
     return -1
    end
    --更新该节点下儿子节点的typeid
    update stock set typeid=@newtypeid+right(typeid,len(typeid)-len(@typeid)),leveal=leveal-@curleveal+@newleveal,parid=@newtypeid+right(parid,len(parid)-len(@typeid)) where left(typeid,len(@typeid))=@typeid and typeid<>@typeid --更新儿子的typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end

      update BillIndex set ktypeid2=@newtypeid+right(ktypeid2,len(ktypeid2)-len(@typeid)) where left(ktypeid2,len(@typeid))=@typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end

     update loginuser  set MangerKTypeID=@newtypeid+right(MangerKTypeID,len(MangerKTypeID)-len(@typeid)) where left(MangerKTypeID,len(@typeid))=@typeid
      if @@error<>0
      begin
       rollback tran
       return -1
      end
        
   --更新节点本身
    update stock set typeid=@newtypeid,leveal=@newleveal,parid=@newparid where typeid=@typeid
    if @@error<>0
    begin
     rollback tran
     return -1
    end
    update stock set sonnum=sonnum+1,soncount=soncount+1 where typeid=@newparid
    if @@error<>0
    begin
     rollback tran
     return -1
    end
    insert  sysmovedata values(@typeid,@newparid,@flag,getdate())
    if @@error<>0
    begin
     rollback tran
     return -1
    end


    commit tran                 
    return 0
  end


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_MoveData_Ac_Data_Save]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_MoveData_Ac_Data_Save]
GO
/*
作者：谢吉康
日期：2012-07-30
描述：数据搬移对总账辅助核算的处理
*/
CREATE PROCEDURE Gp_MoveData_Ac_Data_Save
(
	@Type			VARCHAR(20),		-- 基本信息类型 1.分支机构 2.部门 3.职员 4.往来单位
	@oldTypeId		VARCHAR(50),	-- 替换前基本信息ID
	@newTypeId		VARCHAR(50),		-- 替换后基本信息的ID
	@oldLen			INT
)
--@encode$--
AS
SET NOCOUNT ON

IF @Type = 'STYPE'
BEGIN	
	UPDATE	Ac_Voucher_Bill 
	SET		AscIds = REPLACE(AscIds,'1:'+@oldTypeId,'1:'+@newTypeId)
	
	UPDATE	Ac_Voucher_Bill_Assist_CheckItems 
	SET		TypeId = @newTypeId + SubString(cast(TypeId as varchar(100)), cast((@oldLen + 1) as INT),len(TypeId) - cast(@oldLen as INT)) -- @newTypeId 
	WHERE	typeName = '01' 
			AND TypeId  like  @oldTypeId + '%'  --@oldTypeId
			
	UPDATE	Ac_IniAccount_Assist_CheckItems_Detail
	SET		FieldValue = @newTypeId + SubString(cast(FieldValue as varchar(100)), cast((@oldLen + 1) as INT),len(FieldValue) - cast(@oldLen as INT))--@newTypeId
	WHERE	Ascids = 1
			AND FieldValue like  @oldTypeId + '%' -- @oldTypeId	
			
	UPDATE	Ac_Balance_Assist_CheckItems_Detail
	SET		FieldValue = @newTypeId + SubString(cast(FieldValue as varchar(100)), cast((@oldLen + 1) as INT),len(FieldValue) - cast(@oldLen as INT))-- @newTypeId
	WHERE	Ascids = 1
			AND FieldValue like  @oldTypeId + '%' --= @oldTypeId				
END
ELSE IF @Type = 'DEPARTMENT'
BEGIN
	UPDATE	Ac_Voucher_Bill 
	SET		AscIds = REPLACE(AscIds,'2:'+@oldTypeId,'2:'+@newTypeId)	
	
	UPDATE	Ac_Voucher_Bill_Assist_CheckItems 
	SET		TypeId = @newTypeId + SubString(cast(TypeId as varchar(100)), cast((@oldLen + 1) as INT),len(TypeId) - cast(@oldLen as INT))--@newTypeId 
	WHERE	typeName = '02' 
			AND TypeId like  @oldTypeId + '%'--= @oldTypeId
			
	UPDATE	Ac_IniAccount_Assist_CheckItems_Detail
	SET		FieldValue = @newTypeId + SubString(cast(FieldValue as varchar(100)), cast((@oldLen + 1) as INT),len(FieldValue) - cast(@oldLen as INT))--@newTypeId
	WHERE	Ascids = 2
			AND FieldValue like  @oldTypeId + '%'--= @oldTypeId	
			
	UPDATE	Ac_Balance_Assist_CheckItems_Detail
	SET		FieldValue = @newTypeId + SubString(cast(FieldValue as varchar(100)), cast((@oldLen + 1) as INT),len(FieldValue) - cast(@oldLen as INT))--@newTypeId
	WHERE	Ascids = 2
			AND FieldValue like  @oldTypeId + '%'--= @oldTypeId
END
ELSE IF @Type = 'EMPLOYEE'
BEGIN
	UPDATE	Ac_Voucher_Bill 
	SET		AscIds = REPLACE(AscIds,'3:'+@oldTypeId,'3:'+@newTypeId)	
	
	UPDATE	Ac_Voucher_Bill_Assist_CheckItems 
	SET		TypeId = @newTypeId + SubString(cast(TypeId as varchar(100)), cast((@oldLen + 1) as INT),len(TypeId) - cast(@oldLen as INT))--@newTypeId 
	WHERE	typeName = '03' 
			AND TypeId like  @oldTypeId + '%'--= @oldTypeId
			
	UPDATE	Ac_IniAccount_Assist_CheckItems_Detail
	SET		FieldValue = @newTypeId + SubString(cast(FieldValue as varchar(100)), cast((@oldLen + 1) as INT),len(FieldValue) - cast(@oldLen as INT))--@newTypeId
	WHERE	Ascids = 3
			AND FieldValue like  @oldTypeId + '%'--= @oldTypeId	
			
	UPDATE	Ac_Balance_Assist_CheckItems_Detail
	SET		FieldValue = @newTypeId + SubString(cast(FieldValue as varchar(100)), cast((@oldLen + 1) as INT),len(FieldValue) - cast(@oldLen as INT))--@newTypeId
	WHERE	Ascids = 3
			AND FieldValue like  @oldTypeId + '%'--= @oldTypeId
END
ELSE IF @Type = 'BTYPE'
BEGIN
	UPDATE	Ac_Voucher_Bill 
	SET		AscIds = REPLACE(AscIds,'4:'+@oldTypeId,'4:'+@newTypeId)	
	
	UPDATE	Ac_Voucher_Bill_Assist_CheckItems 
	SET		TypeId = @newTypeId + SubString(cast(TypeId as varchar(100)), cast((@oldLen + 1) as INT),len(TypeId) - cast(@oldLen as INT))--@newTypeId 
	WHERE	typeName = '04' 
			AND TypeId like  @oldTypeId + '%'--= @oldTypeId
			
	UPDATE	Ac_IniAccount_Assist_CheckItems_Detail
	SET		FieldValue = @newTypeId + SubString(cast(FieldValue as varchar(100)), cast((@oldLen + 1) as INT),len(FieldValue) - cast(@oldLen as INT))--@newTypeId
	WHERE	Ascids = 4
			AND FieldValue like  @oldTypeId + '%'--= @oldTypeId	
			
	UPDATE	Ac_Balance_Assist_CheckItems_Detail
	SET		FieldValue = @newTypeId + SubString(cast(FieldValue as varchar(100)), cast((@oldLen + 1) as INT),len(FieldValue) - cast(@oldLen as INT))--@newTypeId
	WHERE	Ascids = 4
			AND FieldValue like  @oldTypeId + '%'--= @oldTypeId
END

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_MoveDataSave]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_MoveDataSave]
GO
/*
程序功能 基本信息 数据搬移
程序编写 Roamer Wu 2003-10-28 11:48
代码位置: 搬移的代码 请搜索 开始搬移

修改：舒珊
日期：2016-03-01
内容：只有目标节点为子节点是才判断是否允许搬移

*/
CREATE                             PROCEDURE GP_MoveDataSave
(
@OperatorID	 VARCHAR(50),
@DBName		 VARCHAR(20),
@ParID		 VARCHAR(50),
@TypeID		 VARCHAR(50),
@TypeIDnew   VARCHAR(50) output
)
--@encode$--
AS
			
SET nocount ON



IF LEN(@ParID) >= 50
BEGIN
	 RAISERROR('超出基本信息限制级数',16,1) RETURN  --RETURN -200 --第五级的基本信息不可再加
END
IF @TypeID = SUBSTRING(@ParID,1,LEN(@TypeID))
BEGIN
	RAISERROR('不能将基本信息向该基本信息或其下级搬移',16,1) RETURN --RETURN -210 --不充许自己向自己搬移
END
IF (LEN(@TypeID) = 5 AND @ParID = '00000') OR (@ParID = SUBSTRING(@TypeID,1,LEN(@TypeID) - 5))
BEGIN
	RAISERROR('此种搬移没有意义，不会有任何变化',16,1) RETURN --RETURN -211 --搬移为自己的同级，没有意义
END

DECLARE @strTempSql	NVARCHAR(1000),@intIfUsed INT


IF CHARINDEX('QP_',@DBName)=0
BEGIN
	SELECT @strTempSql='
	IF EXISTS(
		SELECT TypeID FROM '+@DBName+' WHERE TypeID IN ('+CHAR(39)+@ParID+CHAR(39)+','+CHAR(39)+@TypeID+CHAR(39)+') AND Deleted<>0
	)
	BEGIN
		SET @intIfUsed=1
	END
	ELSE
	BEGIN
		SET @intIfUsed=0
	END
	'

	EXECUTE sp_executesql @strTempSql,N'@intIfUsed INT OUTPUT',@intIfUsed OUTPUT

	IF @intIfUsed=1
	BEGIN
		RAISERROR('源节点/目标节点都不能被停用',16,1) RETURN
	END
END


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID is null RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MDtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output,@MDtypeid output
IF @Re<>0 RETURN @Re

DECLARE @SonNum INT --目标节点字节电数目
SET @SonNum=0
DECLARE @sonnumSQL NVARCHAR(MAX)
SET @sonnumSQL='SELECT @SonNum=sonnum FROM '+@DBName+' WHERE TYPEID='''+@ParID+''''
EXECUTE sp_executesql @sonnumSQL,N'@SonNum INT OUTPUT',@SonNum OUTPUT

--判断是否为汽配
DECLARE @ifqp VARCHAR(1)
SET @ifqp=(SELECT subvalue FROM sysdata WHERE subname='ifqp')

--2007-7-10 徐辉 添加判断被搬移节点的父节点是否有停用子节点，被搬移后是否只剩下停用节点了
DECLARE @DeletedCount INT
DECLARE @TypeIdSonNum INT

SET @DeletedCount = 0
SET @TypeIdSonNum = 0
BEGIN --------------------是否允许搬移判断
	IF @SonNum<=0--如果目标节点为父节点 则不判断。 只有目标节点为子节点是才判断是否允许搬移
	BEGIN
		EXEC GP_BaseInfoCheck @DBName,@ParID,'3'	
	END
	--服务类商品不能和库存商品搬移
	IF @DBName='ptype' AND @ParID<>'00000'
	BEGIN
		IF EXISTS(SELECT *FROM PType WHERE typeId=@ParID AND IsService=1) AND EXISTS (SELECT *FROM PType WHERE typeId=@typeId AND IsService<>1)
		BEGIN
			RAISERROR('库存商品不能搬移到服务商品下，请调整！',16,1) RETURN
		END
		IF EXISTS(SELECT *FROM PType WHERE typeId=@ParID AND IsService<>1) AND EXISTS (SELECT *FROM PType WHERE typeId=@typeId AND IsService=1)
		BEGIN
			RAISERROR('服务商品不能搬移到库存商品下，请调整！',16,1) RETURN
		END
	END
END

DECLARE
	@result  INT=0
EXEC @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename=@DBName,@ctypeid=@ParID,@result=0
IF @result=1
BEGIN
 RAISERROR('目标基本信息已在自定义中关联,不能搬移',16,1) RETURN
END

DECLARE @TName VARCHAR(20)
DECLARE @TName1 VARCHAR(20)
DECLARE @TName2 VARCHAR(20)
DECLARE @issetMeal INT ---是否为维修套餐
SET @issetmeal=0

IF @DBName = 'STOCK'
	BEGIN
		SET @TName = 'KTypeId'
		SET @TName1 = 'KTypeId1'
		SET @TName2 = 'KTypeId2'
	END
ELSE IF SUBSTRING(@DBName,1,4) = 'AREA'
BEGIN
	SET @TName = SUBSTRING(@DBName,1,4) + 'TypeId'
	SET @TName1 = SUBSTRING(@DBName,1,4) + 'TypeId1'
	SET @TName2 = SUBSTRING(@DBName,1,4) + 'TypeId2'
END
ELSE IF @DBName='QP_RepairItems'
BEGIN
	 	SET @TName = 'RepairItemsTypeID'		
END
ELSE IF @DBName='QP_RepairAutoType'
BEGIN
		SET @TName = 'RepairAutoTypeID'		
END
ELSE IF @DBName='QP_RepairAutoInfo'
BEGIN
		SET @TName = 'RatypeID'		
END
ELSE IF @DBName='QP_RepairSetMeal'
BEGIN
		SET @issetmeal=1
END
ELSE IF @DBName='Stype'
BEGIN
      SET @TName = 'Stypeid'
      SET @TName2 = 'Stypeid2'	
END
ELSE 
	BEGIN
		SET @TName = SUBSTRING(@DBName,1,1) + 'TypeId'
		SET @TName1 = SUBSTRING(@DBName,1,1) + 'TypeId1'
		SET @TName2 = SUBSTRING(@DBName,1,1) + 'TypeId2'
	END


DECLARE @TableName VARCHAR(50),@oldParId VARCHAR(50),@newParId VARCHAR(50)
DECLARE @oldLen INT

DECLARE @SQL NVARCHAR(MAX)
DECLARE @sqlt NVARCHAR(MAX),@rowcount INT,@ParmDefinition NVARCHAR(200)--在以下检查中，用于sp_executesql
--安全第一，再作一次检查 徐辉 2007-6-27 v3.7
--遍历所以含有基本信息的表，看父节点是否有记录


IF @SonNum = 0 AND @ParID<>'00000'
BEGIN
	   IF UPPER(@DBName)='BTYPE'
	   BEGIN
			DELETE BType_ArApTotal
			WHERE BTypeID=@ParID AND ARTotal=0 AND APTotal=0 AND YSTotal=0 AND YFTotal=0
			AND ARTotal00=0 AND APTotal00=0 AND YSTotal00=0 AND YFTotal00=0 
	   END
	   
	   IF UPPER(@DBName)='STYPE'
	   BEGIN
			DELETE BType_ArApTotal
			WHERE STypeID=@ParID AND ARTotal=0 AND APTotal=0 AND YSTotal=0 AND YFTotal=0
			AND ARTotal00=0 AND APTotal00=0 AND YSTotal00=0 AND YFTotal00=0 
			
			DELETE AType_Total
			WHERE STypeID=@ParID AND Total00=0 AND Total=0
	   END
	   
	    IF UPPER(@DBName)='ATYPE'
	   BEGIN
			DELETE AType_Total
			WHERE ATypeID=@ParID AND Total00=0 AND Total=0
	   END
		
		IF @DBName = 'PTYPE'
		BEGIN
			DECLARE @pid VARCHAR(50)
			SELECT @pid=PID FROM PTYPE WHERE TYPEID=@ParID
			EXEC Gp_DataSaveForPosDown '-99999',@DBName,@pid
		END

       DECLARE Newtype_cursor CURSOR
		FOR
			SELECT o.[name] AS tablename FROM syscolumns c INNER JOIN sysobjects o ON(c.[id]=o.[id]) WHERE c.[name]= @TName AND o.type='u'
		FOR 
			READ ONLY
  
		OPEN Newtype_cursor
		FETCH NEXT FROM Newtype_cursor INTO  @TableName
		WHILE @@fetch_status=0
		BEGIN
		   --不再检查货位表,GoodsLend ，角色组的不检查 
			IF	UPPER(@TableName)<>'LTYPE' 
				AND UPPER(@TableName)<>'AC_ACCOUNT' 
				AND UPPER(@TableName)<>'GOODSLEND' 
				AND SUBSTRING(@DBName,1,2)<>'qp' 
				AND UPPER(@TableName)<>'BTYPE_CREDIT'				
				AND UPPER(@TableName)<>'UGAType_L'
				AND UPPER(@TableName)<>'UGBANK_L'
				AND UPPER(@TableName)<>'UGBTYPE_L'
				AND UPPER(@TableName)<>'UGDTYPE_L'
				AND UPPER(@TableName)<>'UGETYPE_L'
				AND UPPER(@TableName)<>'UGKTYPE_L'
				AND UPPER(@TableName)<>'UGPTYPE_L'
				AND UPPER(@TableName)<>'UGSTYPE_L'
				AND UPPER(@TableName)<>'USERGROUPLIMIT'
			BEGIN
				--优惠券需要特殊处理，兑换券只能选具体商品
				IF @TableName = 'coupon_ApplyPtype'
				BEGIN
					SELECT @sqlt= 'IF EXISTS(SELECT '+ @TName +'  FROM '+@TableName+' WHERE '+@TName+'='''+@parid+' AND IsExchangePtype = 1'') SET @count = 1 ELSE SET @count = 0'
					SET @ParmDefinition = N'@count INT OUTPUT';
					EXECUTE sp_executesql @sqlt, @ParmDefinition, @count = @rowcount OUTPUT
				END
				ELSE
				BEGIN				
					SELECT @sqlt= 'IF EXISTS(SELECT '+ @TName +'  FROM '+@TableName+' WHERE '+@TName+'='''+@parid+''') SET @count = 1 ELSE SET @count = 0'
					SET @ParmDefinition = N'@count INT OUTPUT';
					EXECUTE sp_executesql @sqlt, @ParmDefinition, @count = @rowcount OUTPUT
				END
				IF @rowcount <> 0
				BEGIN
					IF @TableName = 'EventLog' AND @TName = 'ETypeId' AND @TName = 'STypeId' AND EXISTS(SELECT TOP 1 1 FROM EventLog WHERE ETypeID = @parid AND Deleted = '1')
						FETCH NEXT FROM Newtype_cursor INTO  @TableName
					ELSE IF @TableName = 'TCBill' AND (@TName = 'PTypeId' OR @TName = 'ETypeId')
						FETCH NEXT FROM Newtype_cursor INTO  @TableName  --汽配才新增的时候会在ptype_price和qp_ptype_ext中增加一条相关信息
					ELSE IF (@TableName='QP_PType_Ext' or @TableName='PType_Price' or @TableName = 'PType_Picture' OR @TableName='PType_Units_Ext' or @TableName='PType_AuxiliaryUnits_Ext' or @TableName='ptype_inventorytype' ) AND @TName='Ptypeid'
						FETCH NEXT FROM Newtype_cursor INTO  @TableName
					ELSE IF @TableName = 'EType_Picture' 
						FETCH NEXT FROM Newtype_cursor INTO  @TableName 
					ELSE IF @TableName = 'PType_STypePrice' 
						FETCH NEXT FROM Newtype_cursor INTO  @TableName 
					ELSE IF @TableName = 'SType_UserConfig' 
						FETCH NEXT FROM Newtype_cursor INTO  @TableName
					ELSE IF @TableName = 'cargotype'
						FETCH NEXT FROM Newtype_cursor INTO  @TableName
					ELSE IF @TableName = 'cargotype'
					FETCH NEXT FROM Newtype_cursor INTO  @TableName
					ELSE IF @TableName = 'GoodsStocks_Draft'
					FETCH NEXT FROM Newtype_cursor INTO  @TableName
					ELSE IF @TableName = 'PType_Units_EntryCode_Ext' --商品单位多条码的表不检查
					FETCH NEXT FROM Newtype_cursor INTO  @TableName
					ELSE IF @TableName = 'PType_EntryCode_Ext' --商品多条码的表不检查
					FETCH NEXT FROM Newtype_cursor INTO  @TableName
					ELSE
					BEGIN
						CLOSE Newtype_cursor
						DEALLOCATE Newtype_cursor
						
						RAISERROR('目标节点已经使用过不能向下搬移数据',16,1) RETURN 
					END
				END
			END
			FETCH NEXT FROM Newtype_cursor INTO  @TableName
		END

		CLOSE Newtype_cursor
		DEALLOCATE Newtype_cursor


		--TypeID1
		DECLARE Newtype_cursor1 CURSOR
		FOR
			SELECT o.[name] AS tablename FROM syscolumns c INNER JOIN sysobjects o ON(c.[id]=o.[id]) WHERE c.[name]= @TName1 AND o.type='u'
		FOR
			READ ONLY
  
		OPEN Newtype_cursor1
		FETCH NEXT FROM Newtype_cursor1 INTO  @TableName
		WHILE @@fetch_status=0
		BEGIN
			SELECT @sqlt= 'IF EXISTS(SELECT '+ @TName1 +'  FROM '+@TableName+' WHERE '+@TName1+'='''+@parid+''') SET @count = 1 ELSE SET @count = 0'
			SET @ParmDefinition = N'@count INT OUTPUT';
			EXECUTE sp_executesql @sqlt, @ParmDefinition, @count = @rowcount OUTPUT
			IF @rowcount <> 0
			BEGIN
				CLOSE Newtype_cursor1
				DEALLOCATE Newtype_cursor1
				RAISERROR('目标节点已经使用过不能向下搬移数据',16,1) RETURN --RETURN -1000
			END

          FETCH NEXT FROM Newtype_cursor1 INTO  @TableName
		END

		CLOSE Newtype_cursor1
		DEALLOCATE Newtype_cursor1

		--TypeID2
		DECLARE Newtype_cursor2 CURSOR
		FOR
			SELECT o.[name] AS tablename FROM syscolumns c INNER JOIN sysobjects o ON(c.[id]=o.[id]) WHERE c.[name]= @TName2 AND o.type='u'
        FOR 
			READ ONLY
  
		OPEN Newtype_cursor2
		FETCH NEXT FROM Newtype_cursor2 INTO  @TableName
        WHILE @@fetch_status=0
        BEGIN 
			SELECT @sqlt= 'IF EXISTS(SELECT '+ @TName2 +'  FROM '+@TableName+' WHERE '+@TName2+'='''+@parid+''') SET @count = 1 ELSE SET @count = 0'
			SET @ParmDefinition = N'@count INT OUTPUT';
			EXECUTE sp_executesql @sqlt, @ParmDefinition, @count = @rowcount OUTPUT
			IF @rowcount <> 0
			BEGIN
				CLOSE Newtype_cursor2
				DEALLOCATE Newtype_cursor2
				RAISERROR('目标节点已经使用过不能向下搬移数据',16,1) RETURN --RETURN -1000
			END
			FETCH NEXT FROM Newtype_cursor2 INTO  @TableName
		END

		CLOSE Newtype_cursor2
		DEALLOCATE Newtype_cursor2
END
--安全第一，再作一次检查 徐辉 2007-6-27 v3.7
--遍历所以含有基本信息的表，看父节点是否有记录
--结束

--------
IF @DBName = 'BTYPE'	-- 单独判断会计凭证中的往来单位科目是否有使用
BEGIN
	SELECT TOP 1 1 FROM AccountCredence WHERE TypeATypeID IN (27,33,35,39) AND ATypeID = @parid
	IF @@ROWCOUNT <> 0
	BEGIN
		RAISERROR('目标节点已经使用过不能向下搬移数据',16,1) RETURN  --RETURN -1000
	END
END

IF @DBName = 'stype'	-- 单独判断会计凭证的分支机构科目是否有使用
BEGIN
	SELECT TOP 1 1 FROM AccountCredence WHERE TypeATypeID IN (28) AND ATypeID = @parid
	IF @@ROWCOUNT <> 0
	BEGIN
		RAISERROR('目标节点已经使用过不能向下搬移数据',16,1) RETURN  --RETURN -1000
	END
END

IF @DBName = 'QP_RepairItems'  --判断维修项目是否在保险理赔单,三包索赔单等使用
BEGIN
	IF EXISTS(SELECT RepairItemsTypeID FROM QP_InsuranceBill_RepairItems WHERE RepairItemsTypeID=@ParID)
				BEGIN
					--print '2555'
					RAISERROR('目标使用，不能把子节点搬移到该目标下',16,1) RETURN --RETURN -28				
	END
	IF EXISTS(SELECT RepairItemsTypeID FROM Qp_ThreePacketsBill_RepairItems WHERE RepairItemsTypeID=@ParID)
				BEGIN
					--print '3555'
					RAISERROR('目标使用，不能把子节点搬移到该目标下',16,1) RETURN --RETURN -28				
	END
END

--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @maxLen INT

IF	@DBName = 'ATYPE'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM ATYPE WHERE TypeID LIKE @TypeID + '%'
ELSE IF	@DBName = 'BTYPE'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM BTYPE WHERE TypeID LIKE @TypeID + '%'
ELSE IF	@DBName = 'STYPE'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM STYPE WHERE TypeID LIKE @TypeID + '%'
ELSE IF	@DBName = 'EMPLOYEE'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM EMPLOYEE WHERE TypeID LIKE @TypeID + '%'
ELSE IF	@DBName = 'PTYPE'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM PTYPE WHERE TypeID LIKE @TypeID + '%'
ELSE IF	@DBName = 'STOCK'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM STOCK WHERE TypeID LIKE @TypeID + '%'
ELSE IF	@DBName = 'DEPARTMENT'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM Department WHERE TypeID LIKE @TypeID + '%'
ELSE IF	@DBName = 'AREATYPE'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM AREATYPE WHERE TypeID LIKE @TypeID + '%'
ELSE IF @DBName='QP_RepairItems'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM QP_RepairItems WHERE TypeID LIKE @TypeID + '%'
ELSE IF @DBName='QP_RepairAutoType'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM QP_RepairAutoType WHERE TypeID LIKE @TypeID + '%'
ELSE IF @DBName='QP_RepairAutoInfo'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM QP_RepairAutoInfo WHERE TypeID LIKE @TypeID + '%'
ELSE IF @DBName='QP_RepairSetMeal'
	SELECT @maxLen = MAX(LEN(TypeID)) FROM QP_RepairSetMeal WHERE TypeID LIKE @TypeID + '%'
	
IF LEN(@ParID) + @maxLen - LEN(@TypeID) >= 50
BEGIN
  RAISERROR('被搬移信息级数太多超出系统限制级数',16,1) RETURN  --	RETURN -220  
END	

DECLARE @transfer_newtypeid VARCHAR(50)

IF SUBSTRING(@DBName,1,2)='qp'
BEGIN
  SET @SQL = '
	DECLARE @SonNum INT,@SonCount INT
	DECLARE @isNotDeleted INT
	DECLARE @newTypeID VARCHAR(50)
	
	SELECT @SonNum = sonNum,@SonCount = sonCount + 1
	FROM ' + @DBName + '
	WHERE TypeId = ''' + @ParID + '''
	
	SELECT @isNotDeleted = 1
	
	
	/*生成新的typeid--开始*/
	
	SET @newTypeID = REPLICATE(''0'',(5 - LEN(@SonCount))) + CAST(@SonCount AS VARCHAR(5))
	
	IF ''' + @ParID + ''' <> ''00000''
		SET @newTypeID = ''' + @ParID + ''' + @newTypeID
	
	--检测新TypeId 是否重复了(如果重复了就循环加@SonCount生成一个不重复的)目的是避免重复typeid的产生
	
	WHILE( EXISTS(SELECT TOP 1 1 FROM ' + @DBName + ' WHERE typeId=@newTypeID  ) )
	BEGIN	
		SET @SonCount=@SonCount+1
		
		SET @newTypeID = REPLICATE(''0'',(5 - LEN(@SonCount))) + CAST(@SonCount AS VARCHAR(5))
	
		IF ''' + @ParID + ''' <> ''00000''
			SET @newTypeID = ''' + @ParID + ''' + @newTypeID
		
	END
	
	/*生成新的typeid--结束*/
	
	--更新sonNum,sonCount
	UPDATE ' + @DBName + '
	SET sonNum = sonNum + @isNotDeleted,sonCount =@SonCount
	WHERE TypeID = ''' + @ParID + '''
	
	--商品排序字段SortID统一处理为零
	IF( ''' + @DBName + '''=''ptype'')
	BEGIN
		UPDATE ptype
		SET	 SortID = 0
		WHERE TypeID LIKE ''' + @TypeID + '%''	
	END
	
	
	--改变TYPEID为新TypeId
	UPDATE ' + @DBName + '
	SET	 TypeID = @newTypeID + SUBSTRING(TypeID,LEN(''' + @TypeID + ''') + 1,50)
	WHERE TypeID LIKE ''' + @TypeID + '%''
	
	--保存新的TypeId供后面修改其他表用
	SET @transfer_newtypeid = @newTypeID
	
	--改变新ParID、新的级数
	
	UPDATE ' + @DBName + '
	SET	 ParID = ''00000'',
		 Leveal = 1
	WHERE	 TypeID Like @newTypeID + ''%''
		 AND LEN(TypeID) = 5
	
	UPDATE ' + @DBName + '
	SET	 ParID = SUBSTRING(TYPEID,1,LEN(TYPEID)-5),
		 Leveal = LEN(TypeID) / 5
	WHERE	 TypeID Like @newTypeID + ''%''
		 AND LEN(TypeID) > 5
	
	--原来的父级子节点数减1
	IF LEN(''' + @TypeID + ''') = 5
		BEGIN
			UPDATE ' + @DBName + '
			SET sonNum = sonNum - @isNotDeleted
			WHERE TypeID = ''00000''
		END
	ELSE
		BEGIN
			UPDATE ' + @DBName + '
			SET sonNum = sonNum - @isNotDeleted
			WHERE TypeID = ''' + SUBSTRING(@TypeID,1,LEN(@TypeID) - 5) + '''
		END
	'
END
ELSE
BEGIN
	/*开始搬移*/
	SET @SQL = '
	
	DECLARE @SonNum INT,@SonCount INT
	DECLARE @isNotDeleted INT
	DECLARE @newTypeID VARCHAR(50)
	
	/*取目标层的sonNum和sonCount*/
	SELECT @SonNum = sonNum,@SonCount = sonCount + 1
	FROM ' + @DBName + '
	WHERE TypeId = ''' + @ParID + '''
	
	SELECT @isNotDeleted = 1 - deleted
	FROM ' + @DBName + '
	WHERE TypeId = ''' + @TypeId + '''
	
	IF @@ROWCOUNT=0
	BEGIN
		 RAISERROR(''被搬移的基本信息中部分信息已经不存在！'',16,1) RETURN 
	END
	
	/*生成新的typeid--开始*/
	
	SET @newTypeID = REPLICATE(''0'',(5 - LEN(@SonCount))) + CAST(@SonCount AS VARCHAR(5))
	
	IF ''' + @ParID + ''' <> ''00000''
		SET @newTypeID = ''' + @ParID + ''' + @newTypeID
	
	--检测新TypeId 是否重复了(如果重复了就循环加@SonCount生成一个不重复的)目的是避免重复typeid的产生
	
	WHILE( EXISTS(SELECT TOP 1 1 FROM ' + @DBName + ' WHERE typeId=@newTypeID  ) )
	BEGIN	
		SET @SonCount=@SonCount+1
		
		SET @newTypeID = REPLICATE(''0'',(5 - LEN(@SonCount))) + CAST(@SonCount AS VARCHAR(5))
	
		IF ''' + @ParID + ''' <> ''00000''
			SET @newTypeID = ''' + @ParID + ''' + @newTypeID
		
	END
	
	/*生成新的typeid--结束*/

	--更新sonNum,sonCount
	
	UPDATE ' + @DBName + '
	SET sonNum = sonNum + @isNotDeleted,sonCount = @SonCount,Deleted = 0
	WHERE TypeID = ''' + @ParID + '''
	
	--商品排序字段SortID统一处理为零
	IF( ''' + @DBName + '''=''ptype'')
	BEGIN
		UPDATE ptype
		SET	 SortID = 0
		WHERE TypeID LIKE ''' + @TypeID + '%''	
	END

	--改变TYPEID为新TypeId
	UPDATE ' + @DBName + '
	SET	 TypeID = @newTypeID + SUBSTRING(TypeID,LEN(''' + @TypeID + ''') + 1,50)/*这里的SUBSTRING截取结果似乎始终为空,待查清*/
	WHERE TypeID LIKE ''' + @TypeID + '%''

	--保存新的TypeId供后面修改其他表用
	SET @transfer_newtypeid = @newTypeID
	
	--改变新ParID、新的级数
	
	UPDATE ' + @DBName + '
	SET	 ParID = ''00000'',
		 Leveal = 1
	WHERE	 TypeID Like @newTypeID + ''%''
		 AND LEN(TypeID) = 5
	
	UPDATE ' + @DBName + '
	SET	 ParID = SUBSTRING(TYPEID,1,LEN(TYPEID)-5),
		 Leveal = LEN(TypeID) / 5
	WHERE	 TypeID Like @newTypeID + ''%''
		 AND LEN(TypeID) > 5
	
	--原来的父级子节点数减1
	IF LEN(''' + @TypeID + ''') = 5
		BEGIN
			UPDATE ' + @DBName + '
			SET sonNum = sonNum - @isNotDeleted
			WHERE TypeID = ''00000''
		END
	ELSE
		BEGIN
			UPDATE ' + @DBName + '
			SET sonNum = sonNum - @isNotDeleted
			WHERE TypeID = ''' + SUBSTRING(@TypeID,1,LEN(@TypeID) - 5) + '''
		END
	'
END


--PRINT @SQL
--EXEC(@SQL)
EXECUTE SP_EXECUTESQL 
		@stmt=@SQL,
		@params=N'@transfer_newtypeid VARCHAR(50) OUTPUT',
		@transfer_newtypeid=@transfer_newtypeid OUTPUT

------------------------------------------------------取出新的TypeID--开始----------------------------------------------------
--DECLARE @SonCount INT,@newTypeID VARCHAR(50)

--IF	@DBName = 'ATYPE'
--	SELECT @SonCount = sonCount FROM Atype WHERE TypeID = @ParID
--ELSE IF	@DBName = 'BTYPE'
--	SELECT @SonCount = sonCount FROM Btype WHERE TypeID = @ParID
--ELSE IF	@DBName = 'EMPLOYEE'
--	SELECT @SonCount = sonCount FROM Employee WHERE TypeID = @ParID
--ELSE IF	@DBName = 'PTYPE' 
--	SELECT @SonCount = sonCount FROM Ptype WHERE TypeID = @ParID
--ELSE IF	@DBName = 'STOCK'
--	SELECT @SonCount = sonCount FROM Stock WHERE TypeID = @ParID
--ELSE IF	@DBName = 'DEPARTMENT'
--	SELECT @SonCount = sonCount FROM DEPARTMENT WHERE TypeID = @ParID
--ELSE IF	@DBName = 'AREATYPE'
--	SELECT @SonCount = sonCount FROM AREATYPE WHERE TypeID = @ParID
--ELSE IF @DBName='QP_RepairItems'
--	SELECT @SonCount = sonCount FROM QP_RepairItems WHERE TypeID = @ParID
--ELSE IF @DBName='QP_RepairAutoType'
--	SELECT @SonCount = sonCount FROM QP_RepairAutoType WHERE TypeID = @ParID
--ELSE IF @DBName='QP_RepairAutoInfo'
--	SELECT @SonCount = sonCount FROM QP_RepairAutoInfo WHERE TypeID = @ParID
--ELSE IF @DBName='QP_RepairSetMeal'
--	SELECT @SonCount = sonCount FROM QP_RepairSetMeal WHERE TypeID = @ParID
--ELSE IF @DBName='Stype'
--	SELECT @SonCount = sonCount FROM SType WHERE TypeID = @ParID
----SELECT @SonCount AS soncount

--SET @newTypeID = REPLICATE('0',(5 - LEN(@SonCount))) + CAST(@SonCount AS VARCHAR(5))
--IF @ParID <> '00000'
--	SET @newTypeID = @ParID + @newTypeID

IF (@transfer_newtypeid IS NULL OR  @transfer_newtypeid='')
BEGIN
	RAISERROR('搬移失败',16,1)
	RETURN 
END

DECLARE @newTypeID VARCHAR(50)
SET @newTypeID=@transfer_newtypeid --新的TypeID

------------------------------------------------------取出新的TypeID--结束---------------------------------------------------

-------------------------------------------------将新的TypeID更新到相关表----------------------------------------------------
SET @typeidNew=@newTypeID
SET @oldParId = @TypeID
SET @newParId = @newTypeID
SET @oldLen = LEN(@oldParId)

----------维修套餐档案单独处理-----------
IF @issetmeal=1
BEGIN
	--print(@typeid)
	--print(@newtypeid)
	--UPDATE QP_RepairSetMeal_Items SET typeid=@newTypeID WHERE typeid=@typeid   --(维修套餐档案_维修项目)
	--UPDATE QP_RepairSetMeal_Fittings  SET typeid=@newtypeID WHERE typeid=@typeid  --(维修套餐档案_维修配件)
	UPDATE QP_RepairSetMeal_Items SET typeid=@newParid+SUBSTRING(typeid, CAST((@oldLen + 1) AS INT),LEN(typeid)-CAST(@oldLen AS VARCHAR))
		WHERE typeid like @oldParId+'%'
	UPDATE QP_RepairSetMeal_Fittings SET typeid=@newParid+SUBSTRING(typeid, CAST((@oldLen + 1) AS INT),LEN(typeid)-CAST(@oldLen AS VARCHAR))
		WHERE typeid like @oldParId+'%'
END
-----------单独处理快修单的修理工
IF @DBName='employee'
BEGIN
	UPDATE QP_QuickRepairBill_PType SET RepairManTypeID=@newParid+SUBSTRING(RepairManTypeID, CAST((@oldLen + 1) AS INT),LEN(RepairManTypeID)-CAST(@oldLen AS VARCHAR))
		WHERE RepairManTypeID like @oldParId+'%'
	UPDATE QP_QuickRepairBill_RepairItems SET RepairManTypeID=@newParid+SUBSTRING(RepairManTypeID, CAST((@oldLen + 1) AS INT),LEN(RepairManTypeID)-CAST(@oldLen AS VARCHAR))
		WHERE RepairManTypeID like @oldParId+'%'
END

--修改TypeID
DECLARE type_cursor CURSOR
FOR
  SELECT o.[name] AS tablename FROM syscolumns c INNER JOIN sysobjects o ON(c.[id]=o.[id]) WHERE c.[name]= @TName AND o.type='u' 
  AND o.name not in('QP_EvaluationBill_ RepairItems','UserGroupLimit')   and o.name not like 'Ug%'    
FOR READ only

OPEN type_cursor
FETCH NEXT FROM type_cursor INTO  @TableName
WHILE @@fetch_status=0
BEGIN

	IF @issetmeal<>1
	BEGIN
		  IF (@TableName<>'CX_SaleStocksArea' OR @TName<>'ktypeid')
		  BEGIN
		   SELECT @sql= 'UPDATE '+ @TableName + '
			SET ' + @TName + ' = ''' + @newParId + ''' + SUBSTRING(' + @TName + ',' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(' + @TName + ') - ' + CAST(@oldLen AS VARCHAR) + ') 
			WHERE ' + @TName + ' like ''' + @oldparid + '%'''		   	
		   	BEGIN TRY
				EXEC(@sql)
			END TRY
			BEGIN CATCH				
			END CATCH
		  END
	END

	FETCH NEXT FROM type_cursor INTO  @TableName
END

CLOSE type_cursor
DEALLOCATE type_cursor
		
--修改TypeID1
DECLARE type_cursor1 CURSOR
FOR
  SELECT o.[name] AS tablename FROM syscolumns c INNER JOIN sysobjects o ON(c.[id]=o.[id]) WHERE c.[name]= @TName1 AND o.type='u'
FOR READ only

OPEN type_cursor1
FETCH NEXT FROM type_cursor1 INTO  @TableName
WHILE @@fetch_status=0
BEGIN
IF @issetmeal<>1
BEGIN
	   SELECT @sql= 'UPDATE '+ @TableName + '
		SET ' + @TName1 + ' = ''' + @newParId + ''' + SUBSTRING(' + @TName1 + ',' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(' + @TName1 + ') - ' + CAST(@oldLen AS VARCHAR) + ') 
		WHERE ' + @TName1 + ' like ''' + @oldparid + '%'''
	   EXEC(@sql)
END
	  FETCH NEXT FROM type_cursor1 INTO  @TableName
END

CLOSE type_cursor1
DEALLOCATE type_cursor1

--修改TypeID2
DECLARE type_cursor2 CURSOR
FOR
  SELECT o.[name] AS tablename FROM syscolumns c INNER JOIN sysobjects o ON(c.[id]=o.[id]) WHERE c.[name]= @TName2 AND o.type='u'
FOR READ only

OPEN type_cursor2
FETCH NEXT FROM type_cursor2 INTO  @TableName
WHILE @@fetch_status=0
BEGIN
IF @issetmeal<>1
BEGIN
       SELECT @sql= 'UPDATE '+ @TableName + '
        SET ' + @TName2 + ' = ''' + @newParId + ''' + SUBSTRING(' + @TName2 + ',' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(' + @TName2 + ') - ' + CAST(@oldLen AS VARCHAR) + ') 
        WHERE ' + @TName2 + ' like ''' + @oldparid + '%'''
       EXEC(@sql)
END
  FETCH NEXT FROM type_cursor2 INTO  @TableName
END

CLOSE type_cursor2
DEALLOCATE type_cursor2


--处理特殊字段名的表---------开始
--如非常见的dealbtypeid,AuditId 等字段,常见的上面处理了,只需向SYS_BaseInfoUsing_Tables加记录就行了
DECLARE @FieldName VARCHAR(50)

DECLARE Non_cursor CURSOR
FOR
  SELECT tblName,fldName FROM SYS_BaseInfoUsing_Tables WHERE basType = @TName
FOR READ only

OPEN Non_cursor
FETCH NEXT FROM Non_cursor INTO  @TableName,@FieldName
WHILE @@fetch_status=0

BEGIN
   SELECT @sql= 'UPDATE '+ @TableName + '
    SET ' + @FieldName + ' = ''' + @newParId + ''' + SUBSTRING(' + @FieldName + ',' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(' + @FieldName + ') - ' + CAST(@oldLen AS VARCHAR) + ') 
    WHERE ' + @FieldName + ' like ''' + @oldparid + '%'''

	IF @TableName = 'sms_BaseInfoMobile' AND @FieldName = 'BTypeID'
	BEGIN
		SET @SQL = @SQL + ' AND nType = 1'
	END

	IF @TableName = 'sms_BaseInfoMobile' AND @FieldName = 'ETypeID'
	BEGIN
		SET @SQL = @SQL + ' AND nType = 2'
	END

	IF @TableName = 'AccountCredence'
	BEGIN
		IF @DBName='BTYPE'--会计凭证中对atypeid值进行特列处理，为了防止btype与stype中表的typeid一致造成数据错误
			SET @SQL = @SQL + ' AND TypeATypeID IN (27,33,35,39)'
		IF @DBName='stype'	
			SET @SQL = @SQL + ' AND TypeATypeID IN (28)'
	END
   EXEC(@sql)
  FETCH NEXT FROM Non_cursor INTO  @TableName,@FieldName
END

CLOSE Non_cursor
DEALLOCATE Non_cursor

--处理特殊字段名的表---------结束


-- 处理多级权限范围数据
IF @DBName IN ('PType','Employee','BType','Stock','AType','Stype','Department')
BEGIN
	DECLARE @Type VARCHAR(10)
	SET @TableName = CASE @DBName
		WHEN 'PType' THEN 'PType_L'
		WHEN 'Employee' THEN 'EType_L'
		WHEN 'BType' THEN 'BType_L'
		WHEN 'Stock' THEN 'KType_L'
		WHEN 'AType' THEN 'AType_L'
		WHEN 'Stype' THEN 'stype_l'
		WHEN 'Department' THEN 'dtype_l'
		END

	SET @Type = CASE WHEN @DBName = 'PType' THEN '2'
		WHEN @DBName = 'Employee' THEN '4'
		WHEN @DBName = 'BType' AND LEFT(@TypeID,5) = '00001' THEN '0'
		WHEN @DBName = 'BType' AND LEFT(@TypeID,5) = '00002' THEN '1'
		WHEN @DBName = 'Stock' THEN '3'
		WHEN @DBName = 'AType' AND (LEFT(@TypeID,10) = '0000100003' OR LEFT(@TypeID,10) = '0000100004') THEN '5'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000400003' THEN '6'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000300003' THEN '7'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000100002' THEN '8'
		WHEN @DBName = 'Stype' THEN '10'
		WHEN @DBName = 'Department' THEN '9'
		END
	
	SET @SQL = '
		DECLARE @ETypeID VARCHAR(50), @TypeID VARCHAR(50), @tempTypeID VARCHAR(50), @Flag INT, @nRet INT
		DECLARE Lim_Cursor CURSOR FOR
			SELECT ETypeID,Flag FROM ' + @TableName + ' WHERE TypeID = ''' + @TypeID + '''
		OPEN Lim_Cursor
		FETCH NEXT FROM Lim_Cursor INTO @ETypeID,@Flag
		WHILE @@FETCH_STATUS=0
		BEGIN
			IF @Flag = 1
			BEGIN
				EXEC @nRet = GP_UserRange_Del @ETypeID,' + @Type + ',''' + @TypeID + ''',0
				IF NOT EXISTS(SELECT TOP 1 1 FROM ' + @TableName + ' WHERE ETypeID = @ETypeID AND TypeID = ''' + @ParID + ''' AND Flag = 1)
					EXEC @nRet = GP_UserRange_Insert @ETypeID,' + @Type + ',''' + @newTypeID + ''',0
			END
			ELSE
			BEGIN
				DECLARE Lim_CurSor1 CURSOR FOR
					SELECT TypeID FROM ' + @TableName + ' WHERE ETypeID = @ETypeID AND TypeID LIKE ''' + @TypeID + '%'' AND Flag = 1
				OPEN Lim_CurSor1
				FETCH NEXT FROM Lim_Cursor1 INTO @TypeID
				WHILE @@FETCH_STATUS=0
				BEGIN
					EXEC @nRet = GP_UserRange_Del @ETypeID,' + @Type + ',@TypeID,0
					IF NOT EXISTS(SELECT TOP 1 1 FROM ' + @TableName + ' WHERE ETypeID = @ETypeID AND TypeID = ''' + @ParID + ''' AND Flag = 1)
					BEGIN
						SET @tempTypeID = ''' + @newParId + ''' + SUBSTRING(@TypeID,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(@TypeID) - ' + CAST(@oldLen AS VARCHAR) + ')
						EXEC @nRet = GP_UserRange_Insert @ETypeID,' + @Type + ',@tempTypeID,0
					END
					FETCH NEXT FROM Lim_Cursor1 INTO @TypeID
				END
				CLOSE Lim_Cursor1
				DEALLOCATE Lim_Cursor1
			END
			FETCH NEXT FROM Lim_Cursor INTO @ETypeID,@Flag
		END
		CLOSE Lim_Cursor
		DEALLOCATE Lim_Cursor
	'
	--PRINT(@SQL)
	EXEC(@SQL)
END

-----------------处理总账辅助核算
EXEC Gp_MoveData_Ac_Data_Save @DBName,@oldparid,@newParId,@oldLen

--处理存储方案里面的字段
DECLARE @SchemeType VARCHAR(200)
SET @SchemeType = @DBName
IF @DBName = 'Employee'
	SET @SchemeType ='etype'
	
IF @DBName='stock'
BEGIN
	SET @SchemeType = 'Ktype'
END
SET @SQL = 'EXEC Gp_ReplaceSchemeDetailValue  '''',''AND (BaseType LIKE ''''%'+@SchemeType+''''')'','''+@TypeID+''','''+ @newtypeid+''''

EXEC (@SQL)
--print @SQL
	  
--------------------自定义更新-----------------------------------
DECLARE @CusSql VARCHAR(MAX)=''
SELECT @CusSql=''

IF @DbName='PType' --组合品
BEGIN
	 UPDATE COmbinationProductIndex SET CombinationProductPtypeId=@newParid WHERE CombinationProductPtypeId=@oldparid
END

IF @DBName='Employee' --自定义11
BEGIN
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy11_head=''' + @newParId + '''+SUBSTRING(SysDiy11_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy11_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy11_head like ''' + @oldparid + '%'' '	
	
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy33_head=''' + @newParId + '''+SUBSTRING(SysDiy33_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy33_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy33_head like ''' + @oldparid + '%'' '	
	
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy34_head=''' + @newParId + '''+SUBSTRING(SysDiy34_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy34_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy34_head like ''' + @oldparid + '%'' '	
	
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy35_head=''' + @newParId + '''+SUBSTRING(SysDiy35_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy35_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy35_head like ''' + @oldparid + '%'' '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy36_head=''' + @newParId + '''+SUBSTRING(SysDiy36_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy36_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy36_head like ''' + @oldparid + '%'' '	
			
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY11=''' + @newParId + '''+SUBSTRING(SYSDIY11,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY11) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY11 like ''' + @oldparid + '%''  '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY33=''' + @newParId + '''+SUBSTRING(SYSDIY33,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY33) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY33 like ''' + @oldparid + '%''  '				
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY34=''' + @newParId + '''+SUBSTRING(SYSDIY34,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY34) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY34 like ''' + @oldparid + '%''  '
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY35=''' + @newParId + '''+SUBSTRING(SYSDIY35,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY35) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY35 like ''' + @oldparid + '%''  '
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY36=''' + @newParId + '''+SUBSTRING(SYSDIY36,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY36) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY36 like ''' + @oldparid + '%''  '						
END
IF @DBName='ptype' --自定义12
BEGIN
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy12_head=''' + @newParId + '''+SUBSTRING(SysDiy12_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy12_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy12_head like ''' + @oldparid + '%'' '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY12=''' + @newParId + '''+SUBSTRING(SYSDIY12,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY12) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY12 like ''' + @oldparid + '%''  '	
END
IF @DBName='BType' --自定义13
BEGIN
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy13_head=''' + @newParId + '''+SUBSTRING(SysDiy13_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy13_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy13_head like ''' + @oldparid + '%'' '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY13=''' + @newParId + '''+SUBSTRING(SYSDIY13,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY13) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY13 like ''' + @oldparid + '%''  '	
END
IF @DBName='Department' --自定义14
BEGIN
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy14_head=''' + @newParId + '''+SUBSTRING(SysDiy14_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy14_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy14_head like ''' + @oldparid + '%'' '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy37_head=''' + @newParId + '''+SUBSTRING(SysDiy37_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy37_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy37_head like ''' + @oldparid + '%'' '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy38_head=''' + @newParId + '''+SUBSTRING(SysDiy38_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy38_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy38_head like ''' + @oldparid + '%'' '						

	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy39_head=''' + @newParId + '''+SUBSTRING(SysDiy39_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy39_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy39_head like ''' + @oldparid + '%'' '	

	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy40_head=''' + @newParId + '''+SUBSTRING(SysDiy40_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy40_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy40_head like ''' + @oldparid + '%'' '	
										
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY14=''' + @newParId + '''+SUBSTRING(SYSDIY14,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY14) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY14 like ''' + @oldparid + '%''  '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY37=''' + @newParId + '''+SUBSTRING(SYSDIY37,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY37) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY37 like ''' + @oldparid + '%''  '
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY38=''' + @newParId + '''+SUBSTRING(SYSDIY38,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY38) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY38 like ''' + @oldparid + '%''  '
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY39=''' + @newParId + '''+SUBSTRING(SYSDIY39,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY39) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY39 like ''' + @oldparid + '%''  '
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY40=''' + @newParId + '''+SUBSTRING(SYSDIY40,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY40) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY40 like ''' + @oldparid + '%''  '						
END
IF @DBName='Stock' --自定义15
BEGIN
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy15_head=''' + @newParId + '''+SUBSTRING(SysDiy15_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy15_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy15_head like ''' + @oldparid + '%'' '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY15=''' + @newParId + '''+SUBSTRING(SYSDIY15,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY15) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY15 like ''' + @oldparid + '%''  '	
END
IF @DBName='Stype' --自定义16
BEGIN
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillIndex
							SET SysDiy16_head=''' + @newParId + '''+SUBSTRING(SysDiy16_head,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SysDiy16_head) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SysDiy16_head like ''' + @oldparid + '%'' '	
					
	SELECT @CusSql=@CusSql+' UPDATE Custom_BillDetails
							SET SYSDIY16=''' + @newParId + '''+SUBSTRING(SYSDIY16,' + CAST((@oldLen + 1) AS VARCHAR) + ',LEN(SYSDIY16) - ' + CAST(@oldLen AS VARCHAR) + ') 
					WHERE SYSDIY16 like ''' + @oldparid + '%''  '	
END


EXEC (@CusSql)
--print (@CusSql)
-------------------------------------------------搬移商品时处理pos下载----------------------------------------------------
IF @DBName = 'PTYPE'  AND EXISTS (SELECT *FROM PType WHERE typeId=LEFT(UPPER(@TypeID),LEN(UPPER(@TypeID))-5) AND sonnum=0)
BEGIN
	SELECT @TypeID
	EXEC Gp_DataSaveForPosDown '-99999',@DBName,'0'
END

------搬移时处理优惠券使用商品引用
IF @DBName = 'PTYPE' AND EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_UpdatePtypeIDInCoupon]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
	EXEC GP_UpdatePtypeIDInCoupon @TypeID , @ParID
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_MoveDataSaveForAcItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_MoveDataSaveForAcItems]
GO
/*
程序功能 基本信息 数据搬移
程序编写 Roamer Wu 2003-10-28 11:48
单独处理Ac_Items 2013-02-19
*/
CREATE PROCEDURE GP_MoveDataSaveForAcItems
(
@OperatorID	 varchar(50),
@DBName		 varchar(20),
@ParID		 varchar(50),
@TypeID		 varchar(50),
@TypeIDnew   varchar(50) output
)
--@encode$--
AS
			
set nocount on

IF Len(@ParID) >= 50
begin
	 RAISERROR('超出基本信息限制级数',16,1) RETURN  --RETURN -200 --第五级的基本信息不可再加
end
IF @TypeID = SUBSTRING(@ParID,1,LEN(@TypeID))
begin
	RAISERROR('不能将基本信息向该基本信息或其下级搬移',16,1) RETURN --RETURN -210 --不充许自己向自己搬移
end
IF (Len(@TypeID) = 5 AND @ParID = '00000') OR (@ParID = SUBSTRING(@TypeID,1,LEN(@TypeID) - 5))
begin
	RAISERROR('此种搬移没有意义，不会有任何变化',16,1) RETURN --RETURN -211 --搬移为自己的同级，没有意义
end



--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),@MDtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output,@MDtypeid output
if @Re<>0 return @Re

DECLARE @SonNum int --目标节点字节电数目
SET @SonNum=0


--2007-7-10 徐辉 添加判断被搬移节点的父节点是否有停用子节点，被搬移后是否只剩下停用节点了
DECLARE @DeletedCount int
DECLARE @TypeIdSonNum int

SET @DeletedCount = 0
SET @TypeIdSonNum = 0


IF NOT EXISTS (SELECT 1 FROM ac_items where ntypeid=@parid)
BEGIN
  	RAISERROR('目标节点不存在，不能搬移',16,1) RETURN --RETURN -405 -- 目标节点不存在，无法搬移
END


DECLARE @checkNid INT,@typeValue INT
SELECT @checkNid = nid,
	   @typeValue = CASE TypeName
				WHEN 'B' THEN 2
				WHEN 'C' THEN 7
				WHEN 'E' THEN 5
				WHEN 'F' THEN 4
				WHEN 'G' THEN 3
				WHEN 'L' THEN 8
				END
FROM dbo.Ac_Items WHERE nTypeId = @ParID

IF dbo.Fn_GetIsUse_Items(@checkNid,@typeValue) = 1
BEGIN
	RAISERROR('目标节点已被使用过，不能搬移',16,1) RETURN --目标结点被使用过，不能作为父结点
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE nTypeId = @ParID AND IsModify = 0)
BEGIN
	RAISERROR('目标节点不能分类，不能搬移',16,1) RETURN
END
IF EXISTS(SELECT *FROM PosInfo WHERE BankCardID IN (SELECT nId FROM Ac_Items WHERE nTypeId=@ParID)) 
BEGIN
	RAISERROR('目标节点关联POS，不能搬移',16,1) RETURN
END

IF EXISTS(SELECT *FROM PosInfo WHERE BankCardID IN (SELECT nId FROM Ac_Items WHERE nTypeId=@TypeID)) 
BEGIN
	RAISERROR('该节点关联POS，不能搬移',16,1) RETURN
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE nTypeId = @ParID AND Deleted = 1)
BEGIN
	RAISERROR('目标节点已被停用，不能搬移',16,1) RETURN
END
IF LEFT(@ParID,10) = '0000100004' AND Len(@ParID) <  LEN(@MAtypeid)
begin
	RAISERROR('超出银行管辖权限',16,1) RETURN --Return -100    --超出银行权限范围，不能添加
end	
IF LEFT(@ParID,10) = '0000300003' AND Len(@ParID) <  LEN(@MIncome)
begin
	RAISERROR('超出其他收入管辖权限',16,1) RETURN --Return -101    --超出其他收入权限范围，不能添加
end	
IF LEFT(@ParID,10) = '0000400003' AND Len(@ParID) <  LEN(@MExpense)
begin
	RAISERROR('超出费用管辖权限',16,1) RETURN --Return -102    --超出费用权限范围，不能添加
end
IF LEN(@TypeID)>5
BEGIN
	SELECT @DeletedCount = COUNT(Deleted) FROM ac_items WHERE nParid=SUBSTRING(@TypeID,1,LEN(@TypeID)-5)  AND Deleted=1
	IF @DeletedCount > 0
	BEGIN
		SELECT @TypeIdSonNum = SonNum FROM ac_items WHERE ntypeid=SUBSTRING(@TypeID,1,LEN(@TypeID)-5)
		IF @TypeIdSonNum = 1
		begin
			RAISERROR('被搬移信息同级有停用信息请先删除停用信息才能搬移',16,1) RETURN --RETURN -2000
	    end
	END
END

SELECT @SonNum=SonNum FROM ac_items WHERE ntypeId=@parid



--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @maxLen INT

SELECT @maxLen = MAX(LEN(nTypeID)) FROM ac_items WHERE nTypeID LIKE @TypeID + '%'
	
IF LEN(@ParID) + @maxLen - LEN(@TypeID) >= 50
begin
  RAISERROR('被搬移信息级数太多超出系统限制级数',16,1) RETURN  --	RETURN -220  
end	



	
DECLARE @SonCount int
DECLARE @isNotDeleted int
DECLARE @newTypeID VARCHAR(50)

SELECT @SonNum = sonNum,@SonCount = sonCount + 1
FROM ac_items
WHERE ntypeid = @ParID

SELECT @isNotDeleted = 1 - deleted
FROM ac_items
Where ntypeid = @TypeId
if @@ROWCOUNT=0
BEGIN
	 RAISERROR('被搬移的基本信息中部分信息已经不存在！',16,1) RETURN 
END

SET @newTypeID = REPLICATE('0',(5 - LEN(@SonCount))) + CAST(@SonCount AS VARCHAR(5))

IF @ParID  <> '00000'
	SET @newTypeID = @ParID + @newTypeID
	--SELECT @newTypeID
--检测新TypeId 是否重复了(如果重复了就循环加@SonCount生成一个不重复的)目的是避免重复typeid的产生(bug3795,客户问题)
WHILE( EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Items WHERE nTypeId=@newTypeID ))
BEGIN	
	SET @SonCount=@SonCount+1
	
	SET @newTypeID = REPLICATE('0',(5 - LEN(@SonCount))) + CAST(@SonCount AS VARCHAR(5))

	IF @ParID  <> '00000'
		SET @newTypeID = @ParID + @newTypeID
END
--

UPDATE ac_items
SET sonNum = sonNum + @isNotDeleted,sonCount = sonCount + 1,Deleted = 0
WHERE ntypeid = @ParID

--改变ntypeid为新ntypeid,调整typename、isbank
UPDATE ac_items
SET	 ntypeid = @newTypeID + SUBSTRING(ntypeid,LEN(@TypeID) + 1,50),
	TypeName = CASE LEFT(@ParID,10)
					WHEN '0000100004' THEN 'B'
					WHEN '0000100003' THEN 'B'
					WHEN '0000100002' THEN 'F'
					ELSE CASE LEFT(ntypeId,5)
							WHEN '00001' THEN 'C'
							WHEN '00002' THEN 'L'
							WHEN '00003' THEN 'G'
							WHEN '00004' THEN 'E'
						 END
				END,
	IsBank = CASE LEFT(@ParID,10) WHEN '0000100004' THEN 1 ELSE 0 END
WHERE ntypeid LIKE ''+ @TypeID +'%'

--改变新ParID、新的级数

UPDATE ac_items
SET	 nParID = '00000',
	 Leveal = 1
WHERE	 ntypeid Like ''+@newTypeID + '%'
	 AND LEN(ntypeid) = 5

UPDATE ac_items
SET	 nParID = SUBSTRING(ntypeid,1,LEN(ntypeid)-5),
	 Leveal = LEN(ntypeid) / 5
WHERE	 ntypeid Like '' + @newTypeID + '%'
	 AND LEN(ntypeid) > 5

--原来的父级子节点数减1
IF LEN(@TypeID) = 5
	BEGIN
		UPDATE ac_items
		SET sonNum = sonNum - @isNotDeleted
		WHERE ntypeid = '00000'
	END
ELSE
	BEGIN
		UPDATE ac_items
		SET sonNum = sonNum - @isNotDeleted
		WHERE ntypeid = SubString(@TypeID,1,LEN(@TypeID) - 5)
	END


------------------------------------------------------计算新的TypeID------------------------------------------------------

Select @SonCount = sonCount From ac_items Where nTypeID = @ParID

SET @newTypeID = REPLICATE('0',(5 - LEN(@SonCount))) + CAST(@SonCount AS VARCHAR(5))
IF @ParID <> '00000'
	SET @newTypeID = @ParID + @newTypeID

-------------------------------------------------要改动的TypeID的类型----------------------------------------------------
Set @typeidNew=@newtypeid

DECLARE @newParId VARCHAR(50),@Type VARCHAR(2),@oldLen int

Set @newParId = @newTypeID
Set @oldLen = Len(@TypeID)


-- 处理多级权限范围数据

SET @Type = 
	CASE
		WHEN LEFT(@TypeID,10) = '0000100003' OR LEFT(@TypeID,10) = '0000100004' THEN '5'
		WHEN LEFT(@TypeID,10) = '0000400003' THEN '6'
		WHEN LEFT(@TypeID,10) = '0000300003' THEN '7'
		WHEN LEFT(@TypeID,10) = '0000100002' THEN '8'
	END


DECLARE @ETypeID varchar(50), @tempTypeID varchar(50), @Flag int, @nRet int,@nId INT,@pNid INT

SELECT @nId = nId FROM dbo.Ac_Items WHERE nTypeId = @newTypeID

DECLARE Lim_Cursor CURSOR FOR
SELECT ETypeID,Flag FROM AType_L WHERE TypeID = @TypeID
OPEN Lim_Cursor
FETCH NEXT FROM Lim_Cursor INTO @ETypeID,@Flag
WHILE @@FETCH_STATUS=0
BEGIN
	IF @Flag = 1
	BEGIN
		EXEC @nRet = GP_UserRange_Del @ETypeID,@Type,@TypeID,0
		IF NOT EXISTS(SELECT TOP 1 1 FROM AType_L WHERE ETypeID = @ETypeID AND TypeID = @ParID AND Flag = 1)
			EXEC @nRet = GP_UserRange_Insert @ETypeID,@Type,@nId,0
	END
	ELSE
	BEGIN
		DECLARE Lim_CurSor1 CURSOR FOR
			SELECT TypeID FROM AType_L WHERE ETypeID = @ETypeID AND TypeID LIKE ''+@TypeID + '%' AND Flag = 1
		OPEN Lim_CurSor1
		FETCH NEXT FROM Lim_Cursor1 INTO @TypeID
		WHILE @@FETCH_STATUS=0
		BEGIN
			EXEC @nRet = GP_UserRange_Del @ETypeID,@Type,@TypeID,0
			IF NOT EXISTS(SELECT TOP 1 1 FROM AType_L WHERE ETypeID = @ETypeID AND TypeID = @ParID AND Flag = 1)
			BEGIN
				SET @tempTypeID = @newParId +  SUBSTRING(@TypeID,@oldLen + 1,LEN(@TypeID) - @oldLen)
				SELECT @pNid = nId FROM dbo.Ac_Items WHERE nTypeId = @tempTypeID
				EXEC @nRet = GP_UserRange_Insert @ETypeID,@Type,@pNid,0
			END
			FETCH NEXT FROM Lim_Cursor1 INTO @TypeID
		END
		CLOSE Lim_Cursor1
		DEALLOCATE Lim_Cursor1
	END
	FETCH NEXT FROM Lim_Cursor INTO @ETypeID,@Flag
END
CLOSE Lim_Cursor
DEALLOCATE Lim_Cursor


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


/*
代码编写：Roamer Wu 2003-10-27
代码功能:查询基本信息
*/
CREATE          PROCEDURE GP_MoveDataSource 
(
@OperatorID	 varchar(50),
@DBName		 varchar(20),
@ParID		 varchar(50)
)
--@encode$--
AS
set nocount on
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),@MDtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output,@MDtypeid output
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

IF @DBName = 'ac_items'
	BEGIN
		IF LEFT(@ParID,10) = '0000100004' AND Len(@ParID) <  LEN(@MAtypeid)
			SET @ParID = @MAtypeid
		IF LEFT(@ParID,10) = '0000300003' AND Len(@ParID) <  LEN(@MIncome)
			SET @ParID = @MIncome
		IF LEFT(@ParID,10) = '0000400003' AND Len(@ParID) <  LEN(@MExpense)
			SET @ParID = @MExpense
		IF @ParID='0000100004'
		BEGIN
			SELECT nTypeId AS typeid,nParID AS parid,SonNum,UserCode,FullName,CAST(Deleted AS BIT) AS Deleted
			FROM dbo.Ac_Items
			WHERE nParId = @ParID 
				AND nTypeID Not Like '000030000300001%'
				AND nTypeID Not Like '000040000300001%'
				AND nTypeID Not Like '000040000300002%'
				AND nTypeID Not Like '000040000300004%'
			ORDER BY UserCode
		END
		ELSE
		BEGIN
			SELECT nTypeId AS typeid,nParID AS parid,SonNum,UserCode,FullName,CAST(Deleted AS BIT) AS Deleted
			FROM dbo.Ac_Items
			WHERE nParId = @ParID
				AND nTypeID Not Like '000030000300001%'
				AND nTypeID Not Like '000040000300001%'
				AND nTypeID Not Like '000040000300002%'
				AND nTypeID Not Like '000040000300004%'
			ORDER BY UserCode
		END
	END

ELSE IF @DBName = 'BTYPE'
	BEGIN
		IF LEFT(@ParID,5) = '00001' AND Len(@ParID) <  LEN(@MBtypeid)
			SET @ParID = @MBtypeid
		IF LEFT(@ParID,5) = '00002' AND Len(@ParID) <  LEN(@MBtypeid2)
			SET @ParID = @MBtypeid2

		SELECT TypeId,ParID,SonNum,UserCode,FullName,Deleted,iscarrier
		FROM BTYPE
		WHERE ParId = @ParID
		ORDER BY UserCode
	END

ELSE IF @DBName = 'EMPLOYEE'
	BEGIN 
		IF @ParID = '00000'
			SET @ParID = '00001'
		IF @ParID = '' OR Len(@ParID) <  LEN(@MEtypeid)
			SET @ParID = @MEtypeid

		SELECT TypeId,ParID,SonNum,UserCode,FullName,Deleted
		FROM EMPLOYEE
		WHERE ParId = @ParID	
		ORDER BY UserCode
	END

ELSE IF @DBName = 'PTYPE' 
	BEGIN
		--将搬移后SortID为零的商品排哈序 ---开始-----
		DECLARE @typeid VARCHAR(50),@i INT=1 ,@maxSortID INT
		--这层最大的SortID
		SELECT @maxSortID =MAX(SortID) FROM dbo.ptype WHERE  ParId = @ParID
		--这层SortID为零的商品
		DECLARE CURSOR_IdList CURSOR  FOR 
			SELECT typeId FROM dbo.ptype WHERE SortID=0 AND ParId = @ParID
		--开始遍历操作
		OPEN CURSOR_IdList
			FETCH NEXT FROM CURSOR_IdList INTO @typeid
		WHILE(@@FETCH_STATUS=0)
		BEGIN
			UPDATE dbo.ptype SET SortID=@maxSortID+@i WHERE typeId=@typeid
			SET @i=@i+1
			FETCH NEXT FROM CURSOR_IdList INTO @typeid
		END
		
		--将搬移后SortID为零的商品排哈序 ---结束-----
		
		IF @ParID = '' OR Len(@ParID) <  LEN(@MPtypeid)
			SET @ParID = @MPtypeid

		SELECT TypeId,ParID,SonNum,UserCode,FullName,Deleted,StopBuy,iscombinationproduct
		FROM PTYPE
		WHERE ParId = @ParID
		ORDER BY SortID
	END

ELSE IF @DBName = 'STOCK' 
	BEGIN
		IF @ParID = '' OR Len(@ParID) <  LEN(@MKtypeid)
			SET @ParID = @MKtypeid

		SELECT TypeId,ParID,SonNum,UserCode,FullName,Deleted
		FROM STOCK
		WHERE ParId = @ParID
		ORDER BY UserCode
	END
ELSE IF @DBName = 'DEPARTMENT' 
	BEGIN
		IF @ParID = '' OR Len(@ParID) <  LEN(@MKtypeid)
			SET @ParID = @MDtypeid

		SELECT TypeId,ParID,SonNum,UserCode,FullName,Deleted
		FROM DEPARTMENT
		WHERE ParId = @ParID
		ORDER BY UserCode
	END
ELSE IF @DBName = 'AREATYPE'
	BEGIN
		IF @ParID = '' OR Len(@ParID) <  LEN(@MKtypeid)
			SET @ParID = @MDtypeid

		SELECT TypeId,ParID,SonNum,UserCode,FullName,Deleted
		FROM AreaType
		WHERE ParId = @ParID
		ORDER BY UserCode
	END
ELSE IF @DBName='QP_RepairAutoInfo' --维修车辆信息档案
	BEGIN
		IF @ParID='' OR len(@ParID)<5
			set @ParID='00000'
		SELECT TypeId,ParId,SonNum,platenumber as usercode,fullname=(select fullname from qp_repairautotype where typeid=repairautotypeid)
		FROM QP_RepairAutoInfo
		WHERE ParId=@ParId
		ORDER BY UserCode
	END

ElSE IF @DBName='QP_RepairAutoType' --维修车型信息档案
	BEGIN
		IF @ParID='' OR len(@ParID)<5
			set @ParID='00000'
		SELECT TypeId,ParId,SonNum,usercode,fullname
		FROM QP_RepairAutoType
		WHERE ParId=@ParId
		ORDER BY UserCode
	END

ElSE IF @DBName='QP_RepairItems' --维修项目
	BEGIN
		IF @ParID='' OR len(@ParID)<5
			set @ParID='00000'
		SELECT TypeId,ParId,SonNum,usercode,fullname
		FROM QP_RepairItems
		WHERE ParId=@ParId
		ORDER BY UserCode
	END

ElSE IF @DBName='QP_RepairSetMeal' --维修套餐档案
	BEGIN
		IF @ParID='' OR len(@ParID)<5
			set @ParID='00000'
		SELECT TypeId,ParId,SonNum,usercode,fullname
		FROM QP_RepairSetMeal
		WHERE ParId=@ParId
		ORDER BY UserCode
	END

ElSE IF @DBName='Stype' --维修套餐档案
	BEGIN
		IF @ParID='' OR len(@ParID)<5
			set @ParID='00000'
		SELECT TypeId,ParId,SonNum,usercode,fullname
		FROM SType
		WHERE ParId=@ParId
		ORDER BY UserCode
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-12-19
	描述：文档管理系统文档移动
*/
CREATE PROCEDURE Gp_MoveDocFile
(
	@id					int,				--文档id
	@etypeid			varchar(50),		--上传者id
	@newpathid			varchar(50),		--路径id
	@filename			varchar(200)		--文件名称
)
--@encode$--
AS
SET NOCOUNT ON

IF LEFT(@newpathid,5)='00001'
	BEGIN
		IF EXISTS(SELECT * FROM DocFile WHERE pathId=@newpathid AND FullName=@filename AND id<>@id)
		BEGIN
			
			RAISERROR('该文件夹下已存在相同文件名的文档！',16,1)
			RETURN
		END
	END
ELSE
	BEGIN
		IF EXISTS(SELECT * FROM DocFile WHERE etypeid=@etypeid AND pathId=@newpathid AND FullName=@filename AND id<>@id)
		BEGIN
			
			RAISERROR('该文件夹下已存在相同文件名的文档',16,1)
			RETURN
		END
	END
	
UPDATE DocFile SET pathId=@newpathid WHERE ID=@ID
IF @@ERROR<>0
	RAISERROR('共享文件失败！',16,1)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



CREATE      Procedure Gp_MoveToCRM
(
 @CrmId  int,
 @ErpTypeId  [varchar](50),
 @ifstype	int=0
 )

--@encode$--
AS 
SET NOCOUNT ON 

DECLARE @EtypeId_1 varchar(50),@nSonnum int,@nSoncount int,@nReturntype int,@leveal int
--生成typeid
exec @nReturntype=Gp_createId @ErpTypeId,'btype',@EtypeId_1 out,@nSonnum out,@nSoncount out
if @nReturntype=-1 return -1
if @nReturntype=-2 return -2

--验证是否有现同编号名称的往来单位
DECLARE @szUserCode varchar(100),@szFullName varchar(100),@szLinkManId1 int,@szLinkManId2 int
SET @szUserCode = ''
SET @szFullName = ''
SELECT @szUserCode = UserCode,@szFullName =FullName FROM Crm_Btype WHERE [id] = @CrmId
IF EXISTS( SELECT 1 FROM Btype WHERE   SUBSTRING(typeId,1,5)<>SUBSTRING(@ErpTypeId,1,5) and (FullName = @szfullname or usercode=@szusercode))
 return -4
IF EXISTS( SELECT UserCode FROM Btype WHERE UserCode = @szUserCode OR FullName = @szUserCode)
 RETURN -3

--验证是否有现同编号名称的往来单位结束

select @leveal=leveal from btype where typeid=@ErpTypeId
select @leveal=@leveal+1
begin tran insertproc
INSERT INTO btype
 ([typeId],
 [parid],
 [leveal],
 [soncount],
 [sonnum],
 [UserCode] ,
 [FullName],
 [Name],
 [Area],
 [TelAndAddress],
 [PostCode],
 [Person],
 [TaxNumber],
 [BankAndAcount],
 [Comment],
 [CreateDate],
 [ARTotal],
 [APTotal],
 [ARTotal00],
 [APTotal00],
 [deleted],
 [Client],
 [ARLimit],
 [initcomment],
 [arapexplain],
 [Tel1],
 [Tel2],
 [Tel3],
 [Fax],
 [WWW],
 [Bank],
 [BankName],
 [Email],
 [LinkMan1],
 [LinkSex1],
 [LinkBirthDay1],
 [LinkJob1],
 [LinkCall1],
 [LinkTel1] ,
 [LinkMobile1] ,
 [LinkPost1],
 [LinkAddress1],
 [LinkEmail1],
 [LinkComment1],
 [LinkMan2],
 [LinkSex2],
 [LinkBirthDay2],
 [LinkJob2],
 [LinkCall2],
 [LinkTel2] ,
 [LinkMobile2],
 [LinkPost2],
 [LinkAddress2],
 [LinkEmail2],
 [LinkComment2],
 [ARLimitTime],
 [paymentLTime],
 [SaleZekou] ,
 [BuyZekou] ,
 [PyCode] ,
 [Price],
 [AreaTypeID],
 [denominatedid],
 [buyprice]) 
SELECT 
 @EtypeId_1,
 @ErpTypeId,
 @leveal ,
 [soncount] ,
 [sonnum] ,
 [UserCode] ,
 [FullName],
 [Name],
 [Area],
 [TelAndAddress],
 rtrim(ltrim([PostCode])),
 [Person],
 rtrim(ltrim([TaxNumber])),
 rtrim(ltrim([BankAndAcount])),
 [Comment],
 [CreateDate],
 [ARTotal],
 [APTotal],
 [ARTotal00],
 [APTotal00],
 [deleted],
 [Client],
 [ARLimit],
 [initcomment],
 [arapexplain],
 [Tel1],
 [Tel2],
 [Tel3],
 [Fax],
 [WWW],
 [Bank],
 [BankName],
 [Email],
 [LinkMan1],
 case when [LinkSex1]=0 then 1 when [LinkSex1]=1 then 0 end  LinkSex1,
 ISNULL([LinkBirthDay1],'1980-01-01 00:00:00.000'),
 [LinkJob1],
 [LinkCall1],
 [LinkTel1] ,
 [LinkMobile1] ,
 [LinkPost1],
 [LinkAddress1],
 [LinkEmail1],
 [LinkComment1],
 [LinkMan2],
 --[LinkSex2],
 case when [LinkSex2]=0 then 1 when [LinkSex2]=1 then 0  end  LinkSex2,
 ISNULL([LinkBirthDay2],'1980-01-01 00:00:00.000'),
 [LinkJob2],
 [LinkCall2],
 [LinkTel2] ,
 [LinkMobile2],
 [LinkPost2],
 [LinkAddress2],
 [LinkEmail2],
 [LinkComment2],
 ISNULL([ARLimitTime],'9999.0000'),
 ISNULL([paymentLTime],'9999.0000'),
 [SaleZekou] ,
 [BuyZekou] ,
 [PyCode] ,
 [Price],
 [AreaTypeID],
 @EtypeId_1 AS denominatedid,
 0
FROM CRM_btype WHERE [Id] = @CrmId 

IF @@rowcount=0 
BEGIN
 rollback tran insertproc 
 return -1
END
ELSE 
BEGIN
  UPDATE [btype]
  SET sonnum=@nSonnum+1,soncount=@nSoncount+1
  WHERE typeid=@ErpTypeId  
END

IF (@nReturnType <> 0)
BEGIN 
  rollback tran insertproc 
  return @nReturnType 
END

COMMIT tran insertproc

Declare @arlimit  NUMERIC(24, 10) 
select @arlimit=arlimit  FROM CRM_btype WHERE [Id] = @CrmId 

if @ifStype=0
begin
--插入信用额度表
	IF(@ARLimit IS NOT NULL)
	BEGIN
		if exists(select 1 from btype_credit where StypeId='00001' and BtypeId=@EtypeId_1)
			update btype_credit set Credit=@ARLimit where StypeId='00001' and BtypeId=@EtypeId_1
		else 
			insert into btype_credit(BtypeId,StypeId,Credit) values(@EtypeId_1,'00001',@ARLimit)
	END
end

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Btype
UPDATE Btype SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



/*
	作者：谢吉康
	日期：2003-12-2
	描述：多仓库数据分布
*/


CREATE     PROCEDURE Gp_MultiStockDisByP23
(
	@OperatorID 	VARCHAR(100) ,		--操作员ID
	@ntype 			INT=1,				--库存分布类别1:期初2:其他
	@parid 			VARCHAR(50),		--商品的父节点
	@EndDatePoint 	VARCHAR(10)='',		--时间点
	@KTypeID		VARCHAR(8000),		--多个仓库
	@STypeID		VARCHAR(MAX),	--分支机构
	@isshowstop     INT,
	@showstockstop  INT =0, --是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid VARCHAR(max)=''
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))

IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN (SELECT Typeid FROM F_GetManDetailSType(@OperatorId)) s
	ON A.TypeId=s.Typeid
	
 	--权限范围内的商品线性表
	CREATE TABLE #ptype(TypeId	varchar(100))
	INSERT INTO #ptype(TypeId) SELECT a.TypeId FROM dbo.F_LinePC(@OperatorID,@ptypeCategoryid) a 

--仓库
IF @KTypeID = ''
	SET @KTypeID ='00000'

CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @KTypeID='00000'
BEGIN
IF @showstockstop=0
	INSERT INTO #GetManKTypeId SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN #GetSelectSTypeId s ON k.STypeId=s.TypeId
	ELSE
	INSERT INTO #GetManKTypeId SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN #GetSelectSTypeId s ON k.STypeId=s.TypeId INNER JOIN   dbo.Stock c ON k.TypeId=c.typeId WHERE c.deleted=0
	
	END
ELSE
BEGIN
 IF @showstockstop=0
	INSERT INTO #GetManKTypeId SELECT k.TypeId 
	FROM F_GetManDetailKTypeSType(@OperatorID) k 
	INNER JOIN #GetSelectSTypeId s ON k.STypeId=s.TypeId
	INNER JOIN (SELECT A FROM f_split(@KTypeID,',')) K1 ON K.TypeId LIKE K1.a + '%'
 ELSE
  	INSERT INTO #GetManKTypeId SELECT k.TypeId 
	FROM F_GetManDetailKTypeSType(@OperatorID) k 
	INNER JOIN #GetSelectSTypeId s ON k.STypeId=s.TypeId
	INNER JOIN (SELECT A FROM f_split(@KTypeID,',')) K1 ON K.TypeId LIKE K1.a + '%'
	INNER JOIN dbo.Stock c ON k.TypeId= c.typeId WHERE c.deleted=0
END	

DECLARE @SQL VARCHAR(MAX)

--统一统计方式和库存状况表一致
/*
SELECT  @KTypeIDSQL1 = REPLACE(@KTypeID,'OR','OR KTypeId')
SELECT  @KTypeIDSQL1 = REPLACE(@KTypeIDSQL1,',','')

SELECT  @ngKTypeId = REPLACE(@KTypeID,'OR','OR g.KTypeId')
SELECT  @ngKTypeId = REPLACE(@ngKTypeId,',','')
*/


--===================================================================================查历史库存分布
IF @ntype=2 
	BEGIN
		SELECT @SQL = '
				SELECT 
					S.Fullname AS SFullName, 
					P.FullName AS PFullName, 
					C.PTypeid, C.Ktypeid,
					C.Qty, 
					C.Total, 
					C.Price
				FROM (
						SELECT 
							t.PtypeId, 
							t.KtypeId, 
							SUM(t.Qty) AS Qty, 
							SUM(t.total) AS Total,
							CASE WHEN SUM(t.qty) = 0 THEN NULL ELSE cast(SUM(t.Total) as NUMERIC(24, 10)) / cast(SUM(t.Qty)as NUMERIC(24, 10)) END  AS Price
				        FROM (
								SELECT 	ptypeid,
										ktypeid,
										SUM(qty) AS qty,
										SUM(total) AS total 
								FROM 	iniCommissionStock 
								Inner join #GetManKTypeId k1 on (k1.typeid=ktypeid)
								WHERE	Type = 144
										AND PTypeID LIKE '+CHAR(39)+@parID+'%'+CHAR(39)+'
								GROUP BY
										PTypeId,
										KTypeId
								UNION ALL
								SELECT 	ptypeid,
										ktypeid,
										SUM(qty) AS qty,
										SUM(total) AS total 
								FROM 	inigoodsstocks
								Inner join #GetManKTypeId k1 on (k1.typeid=ktypeid)
								WHERE 	PTypeID LIKE '+CHAR(39)+@parID+'%'+CHAR(39)+'
								GROUP BY
										PTypeID,
										KTypeID
		         				UNION ALL
		 						SELECT 	ptypeid,
										ktypeid,
										SUM(CASE WHEN BillType=57 THEN 0 ELSE qty END) AS qty,
										SUM(CostTotal) AS Total 
								FROM 	inoutstocktable
								Inner join #GetManKTypeId k1 on (k1.typeid=ktypeid) 
								WHERE 	KTypeID<>''10000'' 
										AND billdate <='+CHAR(39)+@EndDatePoint+CHAR(39)+'
										AND PTypeID LIKE '+CHAR(39)+@parID+'%'+CHAR(39)+'
								GROUP BY 	ptypeid,
											ktypeid
							) t 
							Inner Join F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') p1 on (p1.typeid=t.Ptypeid)
							inner join #ptype pc on p1.typeid=pc.typeid
						WHERE 	t.PtypeId like '+CHAR(39)+@parid+'%'+CHAR(39)+''
						IF @isshowstop=1
						  SELECT @SQL +=' and  p1.deleted=0' 
						 SELECT @SQL +=' GROUP BY t.PtypeId, t.KtypeId
					) C INNER JOIN		dbo.PType P ON (C.PTypeid = P.Typeid ) 
						INNER JOIN		dbo.Stock S ON (C.KTypeid = S.typeid)'
		--PRINT(@SQL)
		EXEC(@SQL)
	END
--============================================================================================当前库存状况表
IF @ntype=3
	BEGIN
		SELECT @SQL = '
				SELECT 
					S.Fullname AS SFullName, 
					P.FullName AS PFullName, 
					C.PTypeid, 
					C.Ktypeid, 
					C.Qty, 
					C.Total, 
					C.Price
			     FROM 
			     (
					SELECT 
						q.PtypeId AS PTypeid, 
						q.KtypeId, 
						SUM(q.Qty) AS Qty, 
						(SUM(Q.qty)*g.price) AS Total, 
						g.price AS Price
			        FROM 
			        
			        (SELECT PtypeId,KtypeId, case when sum(qty)=0 then 0 else cast(sum(total) as NUMERIC(24, 10))/cast(sum(qty)as NUMERIC(24, 10)) end as price FROM dbo.GoodsStocks GROUP BY PtypeId,KtypeId)g
	            INNER JOIN dbo.GoodsStocks_Qty Q ON  g.KtypeId=q.KTypeID AND g.PtypeId=q.PTypeID
			        
			         Inner Join F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') p1 on (p1.typeid=g.Ptypeid)
			         inner join #ptype pc on p1.typeid=pc.typeid
					Inner Join #GetManKTypeId on (#GetManKTypeId.typeid=g.ktypeid) ' + CHAR(10)+'	
             		WHERE g.Ptypeid like ''' + @parid+ '%'' ' + CHAR(10)+''
             		
             			IF @isshowstop=1
						  SELECT @SQL +=' and  p1.deleted=0' 
						 SELECT @SQL +=' GROUP BY q.PtypeId, q.KtypeId,g.price
				) C INNER JOIN	dbo.PType P ON (C.PTypeid = P.Typeid ) 
					INNER JOIN	dbo.Stock S ON (C.KTypeid = S.typeid) '
		PRINT(@SQL)
		EXEC(@SQL)		
	END

DROP TABLE #GetManKTypeId,#GetSelectSTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康
	日期：2017-11-08
	描述：优化多仓库库存查询
*/
CREATE PROCEDURE Gp_MultStockLine
( 
	@OperatorID 		varchar(100),  	   		--操作员ID号
	@stypeid			VARCHAR(8000)='00001',	--分支机构
	@szKtypeId  		varchar(8000)='',       --仓库id号
	@showzeroqty 		varchar(10),            --是否显示库存为0的记录   1---显示    0----不显示	
	@Parid   			varchar(MAX)='00000',   --商品的父节点号
	@EndDataPoint  		varchar(20)='',      	--某一日期的库存
	@szPeriod  			char(2)='' ,            --期号,
	@usercode 			varchar(26)='',         --商品编号
	@fullname  			varchar(66)='',         --商品名称
	@sorttype 			varchar(20)='',            --按何种方式排序
	@SortField  		varchar(25)='',            --按具体的字段排序  
	@IfLendBorrow 		char(1)='',                --是否显示借进借出
	@EntryCode			varchar(200)='',			--商品条码
	@Standard			varchar(200)='',			--商品规格
	@type				varchar(200)='',			--商品型号
	@area				varchar(200)='',			--商品产地
	@PriceType			int=0,					--价格方式
	@dwgno				VARCHAR(MAX)='',		--图号
	@generaldwgno		VARCHAR(MAX)='',		--通用车型
	@pycode				VARCHAR(MAX)='',			--拼音码
	@proot				VARCHAR(100)='',			--按仓库、商品层级
	@showstockstop INT =0 --是否显示停用仓库数据 1为不显示 0为显示
)
--@encode$--
AS

SET NOCOUNT ON
SET ANSI_WARNINGS OFF
DECLARE @Sql varchar(8000)   ---肖伟 2002-06-27加速库存状况查询


IF @Parid='00000' SET @Parid=''

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

IF @stypeid='' 
BEGIN
	SET @stypeid='00000'
END

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
CREATE TABLE #TempSType(TypeId	varchar(MAX))

IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
BEGIN
	 INSERT INTO #TempSType SELECT Typeid FROM F_GetManDetailSType(@OperatorID)

	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN #TempSType s
	ON A.TypeId=s.Typeid
END

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT mk.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) mk
			INNER JOIN #GetSelectSTypeId s ON mk.STypeId=s.TypeId

--选择仓库
CREATE TABLE #GetSelectKTypeId(TypeId	varchar(100))

IF  @showstockstop=0
		INSERT INTO #GetSelectKTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@szKtypeId,4) AS A  
		INNER JOIN (SELECT Typeid FROM #GetManKTypeId) K ON A.TypeId=K.TypeId
ELSE
		INSERT INTO #GetSelectKTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@szKtypeId,4) AS A  
		INNER JOIN (SELECT Typeid FROM #GetManKTypeId) K ON A.TypeId=K.TypeId  
		INNER JOIN dbo.Stock ss ON k.typeid=ss.typeId 
		WHERE deleted=0

CREATE TABLE  #GetManPType
(
	typeId				varchar(50),
	UserCode			varchar(500),
	FullName			varchar(500),
	sonnum				int,
	assistantfullname	varchar(500),
	baseunitfullname	varchar(500),
	stockunitfullname	varchar(500),
	stockUnitRate		numeric(24,1)
)
CREATE CLUSTERED INDEX #GetManPType_p_k ON #GetManPType(typeid)

INSERT INTO #GetManPType
( 
	typeId ,
	UserCode ,
	FullName ,
	sonnum ,
	assistantfullname ,
	baseunitfullname ,
	stockunitfullname ,
	stockUnitRate
)
SELECT	P.typeId,
		P.UserCode,
		P.FullName,
		P.sonnum,
		P.assistantfullname,
		P.baseunitfullname,
		P.stockunitfullname,
		P.stockUnitRate				 
FROM	F_GetManPTypeDetailALL(@OperatorID) P
INNER JOIN (SELECT * FROM dbo.F_GetAllBaseTypeId(@parid,1)) AS o ON o.TypeId=p.typeId
WHERE   p.UserCode LIKE '%'+@UserCode+'%'
		AND p.FullName LIKE '%'+@FullName+'%'
		AND ISNULL(p.EntryCode,'''') LIKE '%' + @EntryCode + '%'
		AND ISNULL(p.Area,'''') 	 LIKE '%' + @area + '%'
		AND P.TypeID<>'00000' 
		AND p.Sonnum=0
		and p.IsService=0

 IF @szKtypeId='' OR @szKtypeId='00000'   SELECT @szKtypeId='%'	-- 全部仓库

--最终数据
CREATE TABLE #LastHisResult
(
	PTypeId		VARCHAR(100),
	Qty			 NUMERIC(24, 10) ,
	nqty		 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	ktypeid		VARCHAR(100)
)
CREATE CLUSTERED INDEX CIX_PTypeID ON #LastHisResult(PTypeID)

CREATE TABLE #INOUT(KtypeID VarChar(50),PtypeID Varchar(50),kusercode Varchar(200))
SELECT a.typeId,a.UserCode,a.FullName INTO #stock FROM dbo.Stock a INNER JOIN #GetSelectKTypeId b ON a.typeId = b.TypeId

INSERT INTO #INOUT(KTYPEID,PTYPEID,kusercode) 
SELECT DISTINCT  s.typeid,ptypeid,s.usercode
FROM	#stock S
LEFT JOIN (
			SELECT	B.KtypeId,
					B.PtypeId
			FROM	(
						SELECT	Distinct 
								Ktypeid,
								ptypeid 
						from	inoutstocktable
						WHERE 	Qty<>0			
								AND (KTypeId IN (SELECT Typeid FROM #GetSelectKTypeId) OR KTypeId = '10000') 
						UNION ALL
						SELECT	Distinct 
								Ktypeid,
								ptypeid
						FROM	INIGOODSSTOCKS 				
						WHERE  (KTypeId IN (SELECT Typeid FROM #GetSelectKTypeId) OR KTypeId = '10000') 											
			)B INNER JOIN #GetManPType P ON P.TypeId = B.PTypeId
)A ON A.Ktypeid=s.typeid 	

INSERT INTO #LastHisResult
SELECT 	g.ptypeid,
		SUM(g.qty) AS qty,
		0,
		SUM(g.total) AS total,
		g.ktypeid
FROM Goodsstocks g 				
INNER JOIN #GetManPType b ON g.PTypeID=b.TypeID
INNER JOIN #GetSelectKTypeId c ON g.KTypeID=c.TypeID
GROUP BY g.ptypeid,g.ktypeid
UNION ALL
SELECT 	g.ptypeid,
		0,
		SUM(g.nqty) AS nqty,
		0,
		g.ktypeid
FROM GOODSSTOCKS_QTY g				
INNER JOIN #GetManPType b ON g.PTypeID=b.TypeID
INNER JOIN #GetSelectKTypeId c ON g.KTypeID=c.TypeID
GROUP BY g.ptypeid,g.ktypeid			

IF @proot<>''
BEGIN
	SELECT @proot=@proot+1
	SET @Sql='  SELECT	y.ktypeid,
						y.typeid,
						sum(y.qty) as qty,
						sum(y.kqty) as kqty,
						sum(y.nqty) as nqty,
						sum(y.total) as total,
						Assistqty=dbo.F_GetCustomAssist(y.TYPEID,  sum(y.qty))
				FROM	(
						select  b.ktypeid,
								SUBSTRING(b.typeid,1,5*'+@proot+') AS typeid,
								sum(b.qty) as qty,
								sum(b.kqty) as kqty,
								sum(nqty) as nqty,
								sum(b.total) as total
								from ( '
END
ELSE
BEGIN
	SELECT @SQL ='	SELECT	B.*,
							Assistqty=dbo.F_GetCustomAssist(b.TYPEID,b.qty) 
					FROM ( '
END
					

SET @SQL = @SQL + '						
							SELECT	ISNULL(a.typeid,'''') typeid,
									ISNULL(a.usercode,'''')usercode,
									ISNULL(a.assistantfullname,'''') AS assistantfullname,
									ISNULL(a.baseunitfullname,'''') AS baseunitfullname,
									ISNULL(a.stockunitfullname,'''') AS stockunitfullname,
									ISNULL(SUM(b.qty),0)/ISNULL(a.stockUnitRate,1) AS kqty,
									ISNULL(a.stockUnitRate,1)stockUnitRate, 	
		 							ISNULL(SUM(b.qty),0)  AS qty, 
		 							ISNULL(SUM(b.nqty),0)  AS nqty,		
									CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) AS price,
									ISNULL(SUM(b.total),0) AS total,
									i.ktypeid,
									i.kusercode
							FROM	#inout i
							LEFT  JOIN #GetManPType a  ON i.ptypeid = a.typeid				
							LEFT  JOIN (
											SELECT	PTypeId,
													ISNULL(SUM(Qty),0)Qty,
													ISNULL(SUM(nqty),0)nqty,
													ISNULL(SUM(Total),0)Total,
													ktypeid
											FROM	#LastHisResult group BY ptypeid,ktypeid
						 ) AS b ON (a.typeid=b.ptypeid AND i.ktypeid=b.ktypeid)	 '							

		IF (@showzeroqty='0' AND @IFLENDBorrow <> '1') 
				SELECT @Sql=@Sql + ' WHERE b.Qty<>0 '							
					
		SELECT @Sql=@Sql+' GROUP BY a.typeid,
									a.usercode,
									a.assistantfullname,
									a.baseunitfullname,
									a.stockunitfullname,
									a.stockUnitRate, 										
									i.ktypeid,
									i.kusercode'
	SELECT @SQL = @SQL +'
	)b '
			
--排序
IF @proot<>''
BEGIN
	IF (@showzeroqty = '0' AND @IFLENDBorrow = '1')
		SELECT @SQL = @SQL +' WHERE b.typeid<>''00000'' AND ((ISNULL(b.qty,0)) <> 0  OR ISNULL(B.total,0)<>0)'
	ELSE 
		SELECT @SQL = @SQL +' where b.typeid<>''00000'''
		
	SET @sql=@sql+' GROUP BY b.ktypeid,b.typeid) as y 
		GROUP BY y.ktypeid,y.typeid order by y.ktypeid,y.typeid '
END
ELSE
BEGIN
    IF (@showzeroqty = '0' AND @IFLENDBorrow = '1' )
	  SELECT @SQL = @SQL +' WHERE (ISNULL(b.qty,0)) <> 0  OR ISNULL(B.total,0)<>0 '
	  
	SET @SQL = @SQL + ' ORDER BY b.kusercode,b.usercode '		
END
	
--PRINT(@Sql)
EXEC (@Sql)			

DROP TABLE #GetManKTypeId,#GetSelectKTypeId,#LastHisResult,#GetSelectSTypeId,#INOUT,#TempSType,#stock,#GetManPType--,#Ptype_temp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_NeedFill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_NeedFill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	费用分摊或修改单据后回填成本价等信息
	作    者：	冯波
	修改时间：	2011-10-20
*/
CREATE             PROCEDURE Gp_NeedFill

--@encode$--
AS 
DECLARE @intMoneyDot INT ,
    @intPriceDot INT
	
SELECT  @intMoneyDot = 2 ,
        @intPriceDot = 4
	
DECLARE @intInnerAR INT
	
SELECT  @intInnerAR = NID
FROM    Ac_Items
WHERE   UserCode = '1132'
	

IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType = 16 ) 
    BEGIN

        UPDATE  DisassembleBill
        SET     costprice = b.CostPrice ,
                Total = ROUND(-b.CostTotal, @intMoneyDot) ,
                CurMSalePrice = b.CostPrice * DisassembleBill.MUnitRate
        FROM    InOutstocktable b
        WHERE   DisassembleBill.BillNumberId IN ( SELECT  BillNumberID
                                                  FROM    #AfterModifyBill
                                                  WHERE   BillType = 16 )
                AND DisassembleBill.inorout = 'O'
                AND DisassembleBill.ID = b.ID
                AND b.BillType = 16
	
    END


IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType = 9 ) 
    BEGIN
	--报损单
        UPDATE  LoseBill
        SET     Total = b.CostTotal ,
                Price = b.CostPrice ,
                MPrice = MUnitRate * b.CostPrice
        FROM    ( SELECT    [ID] ,
                            ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                            CASE SUM(Qty)
                              WHEN 0 THEN 0
                              ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                          10))
                                         / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                          10)), 4)
                            END AS CostPrice
                  FROM      InOutStockTable
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 9 )
                  GROUP BY  [ID]
                ) b
        WHERE   LoseBill.BillNumberID IN ( SELECT   BillNumberID
                                           FROM     #AfterModifyBill
                                           WHERE    BillType = 9 )
                AND LoseBill.[ID] = b.ID 
	
	
        UPDATE  Billindex
        SET     totalmoney = b.Total ,
                NTotalMoney = b.Total
        FROM    ( SELECT    BillNumberID ,
                            SUM(Total) AS Total
                  FROM      LoseBill
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 9 )
                  GROUP BY  BillNumberID
                ) b
        WHERE   BillIndex.BillNumberId = b.BillNumberID 
	
    END


IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType = 14 ) 
    BEGIN
	--报溢单
        UPDATE  overflowBill
        SET     Total = b.CostTotal ,
                Price = b.CostPrice ,
                MPrice = MUnitRate * b.CostPrice
        FROM    ( SELECT    [ID] ,
                            ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                            CASE SUM(Qty)
                              WHEN 0 THEN 0
                              ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                          10))
                                         / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                          10)), 4)
                            END AS CostPrice
                  FROM      InOutStockTable
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 14 )
                  GROUP BY  [ID]
                ) b
        WHERE   overflowBill.BillNumberID IN ( SELECT   BillNumberID
                                               FROM     #AfterModifyBill
                                               WHERE    BillType = 14 )
                AND overflowBill.[ID] = b.ID  
	
	
        UPDATE  Billindex
        SET     totalmoney = b.Total ,
                NTotalMoney = b.Total
        FROM    ( SELECT    BillNumberID ,
                            SUM(Total) AS Total
                  FROM      overflowBill
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 9 )
                  GROUP BY  BillNumberID
                ) b
        WHERE   BillIndex.BillNumberId = b.BillNumberID	
	
    END



IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType IN ( 201, 202 ) ) 
    BEGIN
	--其他出入库单
        UPDATE  OtherInOutBill
        SET     Total = CASE b.BillType
                          WHEN 201 THEN b.CostTotal
                          ELSE -b.CostTotal
                        END ,
                Price = b.CostPrice ,
                MPrice = MUnitRate * b.CostPrice
        FROM    ( SELECT    [ID] ,
                            BillType ,
                            ROUND(SUM(CASE BILLTYPE
                                        WHEN 201 THEN Total
                                        ELSE CostTotal
                                      END), 2) AS CostTotal ,
                            CASE SUM(Qty)
                              WHEN 0 THEN 0
                              ELSE ROUND(CAST(SUM(CASE BILLTYPE
                                                    WHEN 201 THEN Total
                                                    ELSE CostTotal
                                                  END) AS NUMERIC(24, 10))
                                         / CAST(SUM(Qty) AS NUMERIC(24, 10)),
                                         4)
                            END AS CostPrice
                  FROM      InOutStockTable
                  WHERE     BillNumberID IN (
                            SELECT  BillNumberID
                            FROM    #AfterModifyBill
                            WHERE   BillType IN ( 201, 202 ) )
                  GROUP BY  [ID] ,
                            BillType
                ) b
        WHERE   OtherInOutBill.BillNumberID IN (
                SELECT  BillNumberID
                FROM    #AfterModifyBill
                WHERE   BillType IN ( 201, 202 ) )
                AND OtherInOutBill.[ID] = b.ID 
	
	
	
        UPDATE  Billindex
        SET     totalmoney = b.Total ,
                ntotalmoney = b.Total
        FROM    ( SELECT    BillNumberID ,
                            SUM(Total) AS Total
                  FROM      OtherInOutBill
                  WHERE     BillNumberId IN (
                            SELECT  BillNumberID
                            FROM    #AfterModifyBill
                            WHERE   BillType IN ( 201, 202 ) )
                  GROUP BY  BillNumberId
                ) b
        WHERE   Billindex.BillNumberId IN (
                SELECT  BillNumberID
                FROM    #AfterModifyBill
                WHERE   BillType IN ( 201, 202 ) )
                AND BillIndex.BillNumberId = b.BillNumberId
    END


IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType = 17 ) 
    BEGIN
        IF NOT EXISTS ( SELECT  ConfigName
                        FROM    Userconfig
                        WHERE   ConfigName = 'ifusepallotcostprice'
                                AND Value = '2' ) 
            BEGIN
		--同价调拨单
                UPDATE  MoveBill
                SET     Total = b.CostTotal ,
                        Price = b.CostPrice ,
                        MPrice = MUnitRate * b.CostPrice
                FROM    ( SELECT    [ID] ,
                                    ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                                    CASE SUM(Qty)
                                      WHEN 0 THEN 0
                                      ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                          10))
                                                 / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                          10)), 4)
                                    END AS CostPrice
                          FROM      InOutStockTable
                          WHERE     BillNumberID IN ( SELECT
                                                          BillNumberID
                                                      FROM
                                                          #AfterModifyBill
                                                      WHERE
                                                          BillType = 17 )
                                    AND Qty > 0
                          GROUP BY  [ID]
                        ) b
                WHERE   MoveBill.BillNumberID IN (
                        SELECT  BillNumberID
                        FROM    #AfterModifyBill
                        WHERE   BillType IN ( 17 ) )
                        AND MoveBill.[ID] = b.ID 
		
		
		--同价调拨单
                UPDATE  BillIndex
                SET     TotalMoney = b.Total ,
                        totalinmoney = b.Total ,
                        nTotalMoney = b.Total ,
                        ntotalinmoney = b.Total
                FROM    ( SELECT    BillNumberId ,
                                    SUM(Total) AS Total
                          FROM      MoveBill
                          WHERE     BillNumberID IN ( SELECT
                                                          BillNumberID
                                                      FROM
                                                          #AfterModifyBill
                                                      WHERE
                                                          BillType = 17 )
                          GROUP BY  BillNumberId
                        ) b
                WHERE   BillIndex.BillNumberId = b.BillNumberId
            END
    END


IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType = 173 ) 
    BEGIN
	--维修品调入
        UPDATE  wx_Bill_In
        SET     Total = b.CostTotal ,
                Price = b.CostPrice
        FROM    ( SELECT    [ID] ,
                            ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                            CASE SUM(Qty)
                              WHEN 0 THEN 0
                              ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                          10))
                                         / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                          10)), 4)
                            END AS CostPrice
                  FROM      InOutStockTable
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 173 )
                  GROUP BY  [ID]
                ) b
        WHERE   wx_Bill_In.BillNumberID IN ( SELECT BillNumberID
                                             FROM   #AfterModifyBill
                                             WHERE  BillType IN ( 173 ) )
                AND wx_Bill_In.[ID] = b.ID 
	
        UPDATE  BillIndex
        SET     TotalMoney = b.Total ,
                nTotalMoney = b.Total
        FROM    ( SELECT    BillNumberId ,
                            SUM(Total) AS Total
                  FROM      wx_Bill_In
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 173 )
                  GROUP BY  BillNumberId
                ) b
        WHERE   BillIndex.BillNumberId = b.BillNumberId
	
    END


IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType = 187 ) 
    BEGIN
	
        UPDATE  STypeMoveBill
        SET     GoodsCostTotal = b.CostTotal ,
                GoodsCostPrice = b.CostPrice
        FROM    ( SELECT    [ID] ,
                            ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                            CASE SUM(Qty)
                              WHEN 0 THEN 0
                              ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                          10))
                                         / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                          10)), 4)
                            END AS CostPrice
                  FROM      InOutStockTable
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 187 )
                  GROUP BY  [ID]
                ) b
        WHERE   STypeMoveBill.BillNumberID IN (
                SELECT  BillNumberID
                FROM    #AfterModifyBill
                WHERE   BillType IN ( 187 ) )
                AND STypeMoveBill.BillNumberID IN ( SELECT
                                                          BillNumberId
                                                    FROM  dbo.BillIndex
                                                    WHERE BillType = 187
                                                          AND CostSale = 0 )
                AND STypeMoveBill.[ID] = b.ID 
	
	
	
        UPDATE  STypeMoveBill
        SET     GoodsCostTotal = b.CostTotal ,
                GoodsCostPrice = b.CostPrice ,
                Price = b.CostPrice ,
                Total = b.CostTotal,
                MPrice = MUnitRate * b.CostPrice
        FROM    ( SELECT    [ID] ,
                            ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                            CASE SUM(Qty)
                              WHEN 0 THEN 0
                              ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                          10))
                                         / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                          10)), 4)
                            END AS CostPrice
                  FROM      InOutStockTable
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 187 )
                  GROUP BY  [ID]
                ) b
        WHERE   STypeMoveBill.BillNumberID IN (
                SELECT  BillNumberID
                FROM    #AfterModifyBill
                WHERE   BillType IN ( 187 ) )
                AND STypeMoveBill.BillNumberID IN ( SELECT
                                                          BillNumberId
                                                    FROM  dbo.BillIndex
                                                    WHERE BillType = 187
                                                          AND CostSale = 1 )
                AND STypeMoveBill.[ID] = b.ID 
	
	
        UPDATE  BillIndex
        SET     totalmoney = b.total ,
                NTotalMoney = b.total
        FROM    ( SELECT    BillNumberId ,
                            total
                  FROM      ListTable
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 187 )
                            AND AtypeId = @intInnerAR
                ) b
        WHERE   BillIndex.BillNumberId = b.BillNumberId
    END
	


----991门店配送单
IF EXISTS ( SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType = 327 ) 
    BEGIN
	
        UPDATE  dbo.DeliveryBill
        SET     GoodsCostTotal = b.CostTotal ,
                GoodsCostPrice = b.CostPrice
        FROM    ( SELECT    [ID] ,
                            ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                            CASE SUM(Qty)
                              WHEN 0 THEN 0
                              ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                          10))
                                         / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                          10)), 4)
                            END AS CostPrice
                  FROM      InOutStockTable
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 327 ) AND BillType=327
                  GROUP BY  [ID]
                ) b
        WHERE   DeliveryBill.BillNumberID IN (
                SELECT  BillNumberID
                FROM    #AfterModifyBill
                WHERE   BillType IN ( 327) )
                AND DeliveryBill.BillNumberID IN ( SELECT
                                                          BillNumberId
                                                    FROM  dbo.PosAllotApplyBillIndex
                                                    WHERE BillType = 327
                                                          AND CostSale = 0 )
                AND DeliveryBill.[ID] = b.ID 
	
	
	
        UPDATE  DeliveryBill
        SET     GoodsCostTotal = b.CostTotal ,
                GoodsCostPrice = b.CostPrice ,
                Price = b.CostPrice ,
                Total = b.CostTotal,
                MPrice = MUnitRate * b.CostPrice
        FROM    ( SELECT    [ID] ,
                            ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                            CASE SUM(Qty)
                              WHEN 0 THEN 0
                              ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                          10))
                                         / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                          10)), 4)
                            END AS CostPrice
                  FROM      InOutStockTable 
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 327 ) AND BillType=327
                  GROUP BY  [ID]
                ) b
        WHERE   DeliveryBill.BillNumberID IN (
                SELECT  BillNumberID
                FROM    #AfterModifyBill
                WHERE   BillType IN ( 327 ) )
                AND DeliveryBill.BillNumberID IN ( SELECT
                                                          BillNumberId
                                                    FROM  dbo.PosAllotApplyBillIndex
                                                    WHERE BillType = 327
                                                          AND CostSale = 1 )
                AND DeliveryBill.[ID] = b.ID 
	
	
        UPDATE  PosAllotApplyBillIndex
        SET     Total = b.total 
             
        FROM    ( SELECT    BillNumberId ,
                            total
                  FROM      ListTable
                  WHERE     BillNumberID IN ( SELECT    BillNumberID
                                              FROM      #AfterModifyBill
                                              WHERE     BillType = 327 )
                            AND AtypeId = @intInnerAR 
                ) b
        WHERE   PosAllotApplyBillIndex.BillNumberId = b.BillNumberId
        
        
 -------特殊处理一下重算了门店配送成本, 调用了门店配送的退货草稿也要更新价格start.--------------
       

        
    UPDATE  DeliveryBackBill
    SET     GoodsCostTotal =  b.GoodsCostPrice*dbo.DeliveryBackBill.Qty ,
            GoodsCostPrice = b.GoodsCostPrice ,
            Price = b.Price ,
            Total =b.Price*DeliveryBackBill.Qty,
            MPrice = MUnitRate * b.Price
    FROM    ( SELECT    [ID] ,Price,Total,GoodsCostPrice,GoodsCostTotal
                        
              FROM      dbo.DeliveryBill 
              WHERE     BillNumberID IN ( SELECT    BillNumberID
                                          FROM      #AfterModifyBill
                                          WHERE     BillType = 327 ) 
           
            ) b
    WHERE   DeliveryBackBill.DeliveryID IN (
            (SELECT DeliveryID FROM dbo.DeliveryBill WHERE BillNumberId IN(SELECT  BillNumberId FROM  #AfterModifyBill WHERE   BillType =327 )))
           
            AND DeliveryBackBill.DeliveryID = b.ID AND DeliveryID<>0
            
            AND dbo.DeliveryBackBill.BillNumberId IN(SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE BillType=328 AND draft=1)

        
        UPDATE  PosAllotApplyBillIndex
        SET     Total = c.total 
             
        FROM    ( SELECT  BillNumberId,  SUM( total) AS total FROM    dbo.DeliveryBackBill GROUP BY BillNumberId                  
                )c
        WHERE   PosAllotApplyBillIndex.BillNumberId = c.BillNumberId  AND dbo.PosAllotApplyBillIndex.BillType=328 AND draft=1
         
        
      -------特殊处理一下重算了门店配送成本, 调用了门店配送的退货草稿也要更新价格end.--------------
   
        
    END
    
--991门店退货
IF EXISTS (SELECT  BillNumberID FROM  #AfterModifyBill WHERE BillType = 328 ) 
BEGIN
    UPDATE  dbo.DeliveryBackBill
    SET     GoodsCostTotal = b.CostTotal ,
            GoodsCostPrice = b.CostPrice
    FROM   ( 
			SELECT    [ID] ,  
					  ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                      CASE SUM(Qty)
                      WHEN 0 THEN 0
                      ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                      10))
                                     / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                      10)), 4)
                      END AS CostPrice
            FROM      InOutStockTable
            WHERE     BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType = 328 ) AND BillType=328
            GROUP BY  [ID]
            ) b
    WHERE   DeliveryBackBill.BillNumberID IN (
            SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType IN (328) )
            AND DeliveryBackBill.BillNumberID IN (SELECT
                                                      BillNumberId
                                                FROM  dbo.PosAllotApplyBillIndex
                                                WHERE BillType = 328
                                                      AND CostSale = 0 )
            AND DeliveryBackBill.[ID] = b.ID 



    UPDATE  DeliveryBackBill
    SET     GoodsCostTotal = b.CostTotal ,
            GoodsCostPrice = b.CostPrice ,
            Price = b.CostPrice ,
            Total = b.CostTotal,
            MPrice = MUnitRate * b.CostPrice
    FROM    ( SELECT    [ID] ,
                        ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                        CASE SUM(Qty)
                          WHEN 0 THEN 0
                          ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                      10))
                                     / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                      10)), 4)
                        END AS CostPrice
              FROM      InOutStockTable 
              WHERE     BillNumberID IN ( SELECT    BillNumberID
                                          FROM      #AfterModifyBill
                                          WHERE     BillType = 328 ) AND BillType=328
              GROUP BY  [ID]
            ) b
    WHERE   DeliveryBackBill.BillNumberID IN (
            SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType IN ( 328 ) )
            AND DeliveryBackBill.BillNumberID IN ( SELECT
                                                      BillNumberId
                                                FROM  dbo.PosAllotApplyBillIndex
                                                WHERE BillType = 328
                                                      AND CostSale = 1 )
            AND DeliveryBackBill.[ID] = b.ID 


    UPDATE  PosAllotApplyBillIndex
    SET     Total = b.total 
         
    FROM    ( SELECT    BillNumberId ,
                        total
              FROM      ListTable
              WHERE     BillNumberID IN ( SELECT    BillNumberID
                                          FROM      #AfterModifyBill
                                          WHERE     BillType = 328 )
                        AND AtypeId = @intInnerAR 
            ) b
    WHERE   PosAllotApplyBillIndex.BillNumberId = b.BillNumberId
END

--991门店验收
IF EXISTS (SELECT BillNumberID FROM  #AfterModifyBill WHERE BillType = 329 ) 
BEGIN
	UPDATE  dbo.InOutstocktable
    SET     CostTotal = b.CostPrice*Qty ,
            CostPrice = b.CostPrice
    FROM    (SELECT	[ID] ,
                    ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                    CASE SUM(Qty)
                    WHEN 0 THEN 0
                    ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                      10))
                    / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                      10)), 4)
                    END AS CostPrice
              FROM      InOutStockTable
              WHERE     BillNumberID IN (SELECT	BillNumberID FROM #AfterModifyBill WHERE BillType = 327 ) AND BillType=327
              GROUP BY  [ID]
            ) b
    WHERE   InOutstocktable.BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType IN ( 329) )
            AND InOutstocktable.BillNumberID IN (SELECT BillNumberId FROM  dbo.PosAllotApplyBillIndex WHERE BillType = 329 AND CostSale = 0 )
            AND InOutstocktable.id in (SELECT id from  dbo.DeliveryCheckBill WHERE DeliveryID= b.ID )

    UPDATE  InOutstocktable
    SET		CostTotal=b.CostPrice* Qty,
			CostPrice=b.CostPrice,
			Price=b.CostPrice,
			Total=b.CostPrice*Qty,
			SalePrice=b.CostPrice,
			SaleTotal=b.Costprice* Qty,
			TaxPrice=b.CostPrice,
			TaxTotal=b.Costprice* Qty,
			NPrice=b.CostPrice,
			NTotal=b.CostPrice*Qty,
			NSalePrice=b.CostPrice,
			NSaleTotal=b.CostPrice*Qty,
			NTaxPrice=b.CostPrice,
			NTaxTotal=b.CostPrice*Qty
    FROM    ( SELECT	[ID] ,
                        ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                        CASE SUM(Qty)
                        WHEN 0 THEN 0
                        ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                      10))
                                     / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                      10)), 4)
                        END AS CostPrice
              FROM      InOutStockTable 
              WHERE     BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType = 327) AND BillType=327
              GROUP BY  [ID]
            ) b
    WHERE   dbo.InOutstocktable.BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType IN (329))
            AND InOutstocktable.BillNumberID IN (SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE BillType = 329 AND CostSale = 1 )
            AND InOutstocktable.id in ( SELECT id from  dbo.DeliveryCheckBill   WHERE DeliveryID= b.ID )
        


    UPDATE  dbo.DeliveryCheckBill
    SET     GoodsCostTotal = b.CostPrice*Qty ,
            GoodsCostPrice = b.CostPrice
    FROM    ( SELECT    [ID] ,
                        ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                        CASE SUM(Qty)
                        WHEN 0 THEN 0
                        ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                      10))
                                     / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                      10)), 4)
                        END AS CostPrice
              FROM      InOutStockTable
              WHERE     BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType = 327 ) AND BillType=327
              GROUP BY  [ID]
            ) b
    WHERE   DeliveryCheckBill.BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType IN (329))
            AND DeliveryCheckBill.BillNumberID IN (SELECT BillNumberId FROM  dbo.PosAllotApplyBillIndex WHERE BillType = 329 AND CostSale = 0 )
            AND DeliveryCheckBill.DeliveryID = b.ID 



    UPDATE  DeliveryCheckBill
    SET     GoodsCostTotal = b.CostPrice*Qty ,
            GoodsCostPrice = b.CostPrice ,
            Price = b.CostPrice ,
            Total =  b.CostPrice*Qty ,
            MPrice = MUnitRate * b.CostPrice
    FROM    ( SELECT    [ID] ,
                        ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                        CASE SUM(Qty)
                        WHEN 0 THEN 0
                        ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                      10))
                                     / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                      10)), 4)
                        END AS CostPrice
              FROM      InOutStockTable 
              WHERE     BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType = 327 )AND BillType=327
              GROUP BY  [ID]
            ) b
    WHERE   dbo.DeliveryCheckBill.BillNumberID IN (
            SELECT  BillNumberID
            FROM    #AfterModifyBill
            WHERE   BillType IN ( 329 ) )
            AND DeliveryCheckBill.BillNumberID IN (SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE BillType = 329 AND CostSale = 1 )
            AND DeliveryCheckBill.DeliveryID = b.ID 


    UPDATE  PosAllotApplyBillIndex
    SET     Total = b.total 
    FROM    ( SELECT	BillNumberId ,
                        total
              FROM      ListTable
              WHERE     BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType = 329 )
                        AND AtypeId = @intInnerAR 
            ) b
    WHERE   PosAllotApplyBillIndex.BillNumberId = b.BillNumberId

    
    UPDATE	dbo.GoodsStocks 
    SET		Price=b.CostPrice
    FROM    (SELECT    [ID] ,
                        ROUND(SUM(ABS(CostTotal)), 2) AS CostTotal ,
                        CASE SUM(Qty)
                        WHEN 0 THEN 0
                        ELSE ROUND(CAST(SUM(ABS(CostTotal)) AS NUMERIC(24,
                                                      10))
                                     / CAST(SUM(ABS(Qty)) AS NUMERIC(24,
                                                      10)), 4)
                        END AS CostPrice,
                        KtypeId,
                        PtypeId
              FROM      InOutStockTable io
              WHERE  BillNumberID IN (SELECT BillNumberID FROM #AfterModifyBill WHERE BillType = 329) AND  BillType=329 GROUP BY  [ID],KtypeId,PtypeId
            ) b
    WHERE  b.PtypeId=GoodsStocks.PtypeId
    AND  b.KtypeId=dbo.GoodsStocks.KtypeId
  
END
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	过账
	作    者：	
	修改时间：	
*/
CREATE             PROCEDURE Gp_NewAuditing
(
	@nBillID				numeric(10,0),				-- 单据 ID 号
	@szCheckMan				varchar(50),				-- 制单人 ID 值
	@szPID					varchar(1000) output,		-- 返回出错商品 ID 值
	@chvOpID				varchar(50) = '',			-- 当前操作员 ID 值
	@KTypeID				varchar(50) = '' output,	-- 返回仓库ID值，针对多仓库应用
	@billtype				INT = 0,						--单据类型
	@voucherMsg				VARCHAR(50) = '' OUTPUT,	--返回凭证生成信息
	@Ret					INT=0 OUTPUT,
	@VipCentInfo			VARCHAR(200) = '' OUTPUT,				--返回会员卡积分调整信息
	@AssetMsg				VARCHAR(MAX)='' OUTPUT,
	@VipCardCode			VARCHAR(200)='' OUTPUT,
	@CommissionConfirm		INT=0,
	@strReturnBillCode		VARCHAR(200)='' OUT
)
--@encode$--
AS

SET NOCOUNT ON

CREATE TABLE #AuditReturnResult(NORETURNTABLE INT)

EXEC	@Ret=Gp_Auditing	@nBillID,
							@szCheckMan,
							@szPID output,
							@chvOpID,
							@KTypeID output,
							@billtype,
							@voucherMsg OUTPUT,
							@VipCentInfo OUTPUT,
							@AssetMsg OUTPUT,
							@VipCardCode OUTPUT,
							@CommissionConfirm,
							@strReturnBillCode OUT

SELECT @Ret=ISNULL(@Ret,0)

SELECT * FROM #AuditReturnResult

DROP TABLE #AuditReturnResult
	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

BEGIN TRAN

DECLARE
	@nBillID				numeric(10,0),				-- 单据 ID 号
	@szCheckMan				varchar(50),				-- 制单人 ID 值
	@szPID					varchar(1000),				-- 返回出错商品 ID 值
	@chvOpID				varchar(50),				-- 当前操作员 ID 值
	@KTypeID				varchar(50),				-- 返回仓库ID值，针对多仓库应用
	@billtype				INT,						--单据类型
	@voucherMsg				VARCHAR(50) = '',	--返回凭证生成信息
	@Ret					INT=0,
	@VipCentInfo			VARCHAR(200) = '',				--返回会员卡积分调整信息
	@AssetMsg				VARCHAR(MAX)=''
	
SELECT
	@nBillID=17,
	@szCheckMan='00001',
	@chvOpID='00001',
	@billtype=160
	

EXEC
	Gp_NewAuditing
	@nBillID,
	@szCheckMan,
	@szPID OUT,
	@chvOpID,
	@KTypeID OUT,
	@billtype,
	@voucherMsg OUT,
	@Ret OUT,
	@VipCentInfo OUT,
	@AssetMsg OUT


SELECT @Ret,@szPID,@KTypeID,@voucherMsg


ROLLBACK TRAN


DELETE LISTTABLE WHERE BILLNUMBERID=6

UPDATE BILLINDEX SET IFCHECK='f',Draft=1 WHERE BILLNUMBERID=6

*/






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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

修改后单据的过账

作者：冯波



*/
CREATE   PROCEDURE Gp_NewBill_Audit 
(
	@nBillID			numeric(10,0),				-- 1. 单据编号 ID 值
	@nBillType			INT,
	@szCheckMan			VARCHAR(50),				-- 制单人 ID 值
	@chvOpID			VARCHAR(50),				-- 当前操作员 ID 值
	@nRet				INT	OUT,					--0表示修改成功，其他都表示出错
	@strMsg				VARCHAR(500)	OUT,		--返回的错误提示信息
	@KTypeID			VARCHAR(50) = '' OUT		-- 返回仓库ID值，针对多仓库应用
)
--@encode$--
AS

--还需要传入操作员
DECLARE
	@szPID				VARCHAR(500)
	
	
SELECT
	@KTypeID=''	
	
--需要确认是否要改过账时间	

SELECT
	@nRet=0,
	@strMsg=''

--BEGIN TRAN NewBillAudit
--SAVE TRAN NewBillAudit

--把老的记录从InOutStockTable中清除，应该在REVERSE中处理的

IF @nBillType=187
BEGIN
	--分支机构调拨出库单
	IF EXISTS(
		SELECT b.STypeID 
		FROM STypeMoveBill a
		INNER JOIN Stock b
		ON a.Ktypeid2=b.typeId
		WHERE a.BillNumberId=@nBillID
		AND b.STypeID NOT IN
		(
			SELECT	STypeID
			FROM	SType_UserConfig
			WHERE	ConfigNo = 1
			AND Value = 1
		)
	)
	BEGIN
		SELECT @nRet=3
		--ROLLBACK TRAN NewBillAudit
		RETURN 3
	END
END
ELSE IF @nBillType=188
BEGIN
	--分支机构调拨入库单
	IF EXISTS(
		SELECT b.STypeID 
		FROM STypeMoveBill a
		INNER JOIN Stock b
		ON a.Ktypeid=b.typeId
		WHERE a.BillNumberId=@nBillID
		AND b.STypeID NOT IN
		(
			SELECT	STypeID
			FROM	SType_UserConfig
			WHERE	ConfigNo = 1
			AND Value = 1
		)
	)
	BEGIN
		SELECT @nRet=3
		--ROLLBACK TRAN NewBillAudit
		RETURN 3
	END
END


DECLARE
		@datBillDate			DATETIME,					-- 单据日期
		@chvSTypeID				VARCHAR(50),
		@chvATypeID				VARCHAR(50),				-- 收付款账户 ID 值
		@chvBTypeID				VARCHAR(50),				--结算单位
		@chvDealBTypeID			VARCHAR(50),				--往来单位
		@chvETypeID				VARCHAR(50),				-- 经手人 ID 值
		@chvKTypeID				VARCHAR(50),				-- 出库仓库 ID 值
		@chvKTypeID2			VARCHAR(50),				-- 入库仓库 ID 值
		@chvDTypeID				VARCHAR(50),				--部门
		@numTotalMoney			 NUMERIC(24, 10) ,				-- 单据金额合计
		@numTotalInMoney		 NUMERIC(24, 10) ,				-- 单据实收、实付金额
		@numPreferenceMoney		 NUMERIC(24, 10) ,
		@numNTotalMoney			 NUMERIC(24, 10) ,
		@numNTotalInMoney		 NUMERIC(24, 10) ,
		@numNPreferenceMoney	 NUMERIC(24, 10) ,
		@wxTotal				 NUMERIC(24, 10) ,	
		@numTax					 NUMERIC(24, 10) ,
		@ifIndexWX				TINYINT,
		@intCostSale			TINYINT,
		@intCID					INT,
		@ifCheck				VARCHAR(10),				-- 是否草稿标识，f - 草稿；t - 已过账
		@IfMulAccount			TINYINT,
		@intVipCardID			INT,
		@BillName				VARCHAR(100),
		@NumRate				 NUMERIC(24, 10) ,
		@AssetBusinessTypeId    INT,
		@intRedWord				TINYINT,
		@intNewPosBill			TINYINT,
		@AuditType				INT,
		@IfLend					INT=0,
		@datPostTime			DATETIME 
		
	
	
	
		EXEC	GP_GetBillIndexInfo
			@nBillID,
			@nBillType,
			@datBillDate	OUT,
			@chvATypeID	OUT,				-- 收付款账户 ID 值
			@chvBTypeID	OUT,				--结算单位
			@chvDealBTypeID	OUT,				--往来单位
			@chvETypeID	OUT,				-- 经手人 ID 值
			@chvKTypeID	OUT,				-- 出库仓库 ID 值
			@chvKTypeID2	OUT,				-- 入库仓库 ID 值
			@chvDTypeID	OUT,				--部门
			@chvSTypeID	OUT,				--分支机构
			@numTotalMoney	OUT,				-- 单据金额合计
			@numTotalInMoney	OUT,				-- 单据实收、实付金额
			@numPreferenceMoney	OUT,
			@numNTotalMoney	OUT,
			@numNTotalInMoney	OUT,
			@numNPreferenceMoney	OUT,
			@wxTotal	OUT,	
			@numTax	OUT,
			@ifIndexWX	OUT,
			@intCostSale	OUT,
			@intCID	OUT,
			@ifCheck	OUT,				-- 是否草稿标识，f - 草稿；t - 已过账
			@IfMulAccount	OUT,
			@intVipCardID	OUT,
			@NumRate		OUT,
			@AssetBusinessTypeId OUT,
			@intRedWord			OUT,
			@intNewPosBill	OUT,
			@IfLend			OUT,
			@datPostTime	OUT
			
		DECLARE
			@VerifyID	VARCHAR(50)
			
		
		
		SELECT 
			@VerifyID=@chvSTypeID
		
		IF EXISTS(
			SELECT TypeID
			FROM SType
			WHERE TypeId=@chvSTypeID AND IsSelfVerify=0
		)
		BEGIN
			SELECT @VerifyID=VerifyID
			FROM SType
			WHERE TypeId=@chvSTypeID
		END
			
		IF ISNULL(@AssetBusinessTypeId,'')<>''
		BEGIN
			SELECT @AuditType=AuditType
			FROM Ac_AssetBusinessType
			WHERE ID=@AssetBusinessTypeId AND STypeId=@VerifyID
		END
		

--去掉判断，直接过账

IF @nBillType IN (11,34,12,46,6,45,4,66,17,21,305,159,144,145,146,147,160,161,139,126,9,14,57,16,157,140,141,142,143,
		165,166,167,168,169,170,171,172,173,174,175,178,183,186,187,188,191,195,196,197,200,181,182,179,201,202,400,401,402,403)
BEGIN
	-- 产生 ListTable 中应收应付，产生 InOuStockTable 中明细
	
	EXEC @nRet = Gp_CreateMx_new @nBillID,
					@nBillType,
					@datBillDate,
					@chvATypeID,
					@chvBTypeID,
					@chvDealBTypeID,
					@chvETypeID,
					@chvKTypeID,
					@chvKTypeID2,
					@chvDTypeID,
					@chvSTypeID,
					@numTotalMoney ,
					@numTotalInMoney ,
					@numPreferenceMoney ,
					@numNPreferenceMoney ,
					@numNTotalMoney ,
					@numTax ,
					@ifIndexWX ,
					@intCostSale ,
					@intCID,
					@datPostTime
					
	
	IF @nRet <> 0
	BEGIN
		--ROLLBACK TRAN NewBillAudit
		RETURN @nRet
	END
END
ELSE IF @nBillType IN (189,190)
BEGIN
	--处理预收款单，预付款单

	
	EXEC @nRet = GP_Auditing_AType @nBillID,@nBillType,@chvOpID,@datBillDate,@chvBTypeID,@chvDTypeID,@chvSTypeID,@intCID
	
	IF @nRet <> 0
	BEGIN
		--ROLLBACK TRAN NewBillAudit
		RETURN @nRet
	END
	
END
ELSE IF @nBillType NOT IN (189,190,212,213,214,310,404,405)
BEGIN
	-- 产生 ListTable 中应收应付，产生 InOuStockTable 中明细
	EXEC @nRet = Gp_CreateMx @nBillID
	IF @nRet <> 0
	BEGIN
		--ROLLBACK TRAN NewBillAudit
		RETURN @nRet
	END
END



IF @nBillType IN (187,188)
BEGIN
	EXEC @nRet = GP_Auditing_AType @nBillID,@nBillType,''

	IF @nRet <> 0
	BEGIN
		--ROLLBACK TRAN NewBillAudit
		RETURN @nRet
	END
END

DECLARE
		@strTemp		VARCHAR(500)




--往来过账
IF @nBillType IN(11,45,12,46,305,160,157,141,167,168,172,181,93,85,148,149,6,34,145,161,170,36,84,150,151,183,4,66,189,190,6,161,145,151,158,77,93,85,212,213,214,215,312,450)
BEGIN
	EXEC @nRet = GP_AuditArAp @nBillID,0,@nBillType,@datBillDate,@chvATypeID,@chvBTypeID,@chvETypeID,@chvKTypeID,@chvKTypeID2,
	@chvDTypeID,@chvSTypeID,@numTotalMoney,@numTotalInMoney,@numPreferenceMoney,@numNTotalMoney,
	@numNTotalInMoney,@numNPreferenceMoney,@numTax,@ifIndexWX,@intCostSale,@IfMulAccount,@wxTotal,@intVipCardID,
	@intCID,@NumRate,@AuditType,@intNewPosBill,@szPID OUTPUT,@strTemp output,@strTemp OUT
	
	IF @nRet <> 0
	BEGIN
		--ROLLBACK TRAN NewBillAudit
		RETURN @nRet
	END
END
--品牌应收修改，红冲历史数据
IF @nBillType IN (11,12,45,46,160,141,405,189,116,115,93,36,4,305,215)
BEGIN
	EXEC dbo.GP_AuditBrandarArAp @nBillID,@nBillType	
END



-- 检查账户余额，是否过账后会 < 0
EXEC @nRet = GP_AuditingATypeBalanceCheck @nBillID,@nBillType, @szPID OUTPUT
IF @nRet <> 0
BEGIN
	--ROLLBACK TRAN NewBillAudit
	
	IF @szPID<>'' SET @strMsg=@szPID
	
	RETURN @nRet
END

IF @nBillType NOT IN (404,405)
BEGIN 
	EXEC GP_Auditing_DealQty_NewBill
	@nBillID,
	@nBillType,
	0,
	@chvDealBTypeID,
	@chvBTypeID,
	@chvSTypeID,
	@szPID	OUT,
	@nRet	OUT

	IF @szPID<>'' SET @strMsg=@szPID
	IF @nRet<>0 
	BEGIN
		--ROLLBACK TRAN NewBillAudit
		RETURN @nRet
	END
END
SELECT @BillName=detailTable
FROM BillName
WHERE Billtype=@nBillType
		
IF @nBillType IN (11,34,12) AND @IfLend = 1
BEGIN
	EXEC @nRet = Gp_LendBuySaleCheck @nBillID, @nBillType,@strMsg OUTPUT
	IF @nRet<>0 
	BEGIN
		--ROLLBACK TRAN NewBillAudit
		RETURN @nRet
	END
	EXEC Gp_Auditing_LendBuySale @nBillID,@nBillType
END

IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'Edition' AND SubValue = 1)
BEGIN


	IF @nBillType IN (11,34,6,45,17,21,305,144,145,146,147,160,161,139,126,9,14,16,157,140,141,142,143,
	165,166,167,168,169,170,171,172,173,174,175,178,183,186,187,188,191,195,196,197,200,182,179,201,202,203,215,57,400,401,402,403,12,46)
	BEGIN
		DECLARE 
			@SQL NVARCHAR(MAX),
			@intDealSerial	TINYINT
			
		SET @SQL='IF EXISTS(SELECT BillNumberID FROM '+@BillName+' WHERE BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND CAST(Serial AS VARCHAR(MAX))<>'''') SET @intDealSerial=1 ELSE SET @intDealSerial=0'
		EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
		
		PRINT(@SQL)
		
		IF @intDealSerial=0 AND @nBillType=166
		BEGIN
			SET @SQL='IF EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND CAST(Serial AS VARCHAR(MAX))<>'''') SET @intDealSerial=1 ELSE SET @intDealSerial=0'
			EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
		END
		
		--PRINT(@SQL)
		
		IF @intDealSerial=0
		BEGIN
			SET @SQL='IF EXISTS(SELECT a.BillNumberID FROM '+@BillName+' a 
			INNER JOIN PType b ON a.PTypeID=b.TypeID
			WHERE a.BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND b.IfSerial=1) SET @intDealSerial=1 ELSE SET @intDealSerial=0'
			EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
		END
		
		--PRINT(@SQL)
		
		IF @intDealSerial=0 AND @nBillType=166
		BEGIN
			SET @SQL='IF EXISTS(SELECT a.BillNumberID FROM BillIndex a 
			INNER JOIN PType b ON a.PTypeID=b.TypeID
			WHERE a.BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND b.IfSerial=1) SET @intDealSerial=1 ELSE SET @intDealSerial=0'
			EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
		END 
		
		--PRINT(@SQL)

		IF @intDealSerial=1
		BEGIN
			EXEC @nRet = Gp_SerialOperate_Manager @nBillID,@szCheckMan,@chvOpID,
			@chvOpID,@ifIndexWX,@chvBTypeID,@chvSTypeID,@strMsg OUTPUT,@nBillType
			
			IF @nRet<>0 
			BEGIN
				--ROLLBACK TRAN NewBillAudit
				RETURN
			END
		END
	END
END


DECLARE
	@intPostTime	INT
	
SELECT @intPostTime=1		--新修改单据确认这个过账时间不需要变化,还是保持之前的

EXEC @nRet = Gp_AuditingCore @nBillID, @szCheckMan, @chvOpID,
		@nBillType,@datBillDate,@chvATypeID,@chvBTypeID,@chvETypeID,@chvKTypeID,@chvKTypeID2,@chvSTypeID,@numTotalMoney,@numTotalInMoney,@ifCheck,
		@szPID OUTPUT, @KTypeID OUTPUT,@intPostTime


IF @szPID<>'' SET @strMsg=@szPID

IF @nRet<>0 
BEGIN
	--ROLLBACK TRAN NewBillAudit
	RETURN @nRet
END

--再判断下预收预付是否会因此为负
--如果不允许现金账户为负，也存在类似问题
--但如何确定需要判断哪些账户

IF @nBillType IN (11,34,12)
BEGIN
	-- 检测销售、采购单关联订单的完成状态
	EXEC @nRet = GP_AuditingCheckOrderState @nBillID,1
	IF @nRet <> 0 
	BEGIN
		--ROLLBACK TRAN NewBillAudit
		RETURN @nRet
	END
END

--对于启用了货位，而且是属于启用了货位的单据，需要进行处理
DECLARE
	@intReturnID				INT,
	@strReturnBillCode			VARCHAR(100),
	@strErrMsg					VARCHAR(500),
	@voucherMsg					VARCHAR(500)
	

IF @nBillType=11 AND @intCostSale=1
BEGIN
	EXEC	GP_Auditing_DealCostSale
			@nBillID,
			@nBillType,
			@intCostSale,
			@intCID,
			@chvOpID,
			@nRet	OUT,
			@szPID OUT,
			@intReturnID OUT,		
			@strReturnBillCode OUT,
			@strErrMsg OUT
END


IF @nBillType IN (400,401,402,403,404,405)
	BEGIN
	
		EXEC @nRet=Gp_CheckLimitBillType @chvOpID,0,@nBillType
		IF @nRet<>1 
		BEGIN
			--ROLLBACK TRAN NewBillAudit
			RETURN 1000 --没有单据过账的权限
		END
		
		SELECT @nRet = 0
		
		IF @nBillType IN (404,405)
		BEGIN
			IF @nBillType=404
			BEGIN
				--生成成本调价单
				EXEC	GP_ReceiptBill_CreateBill
						@chvOpID,
						@nBillID,
						@intReturnID OUT,		--新生成的单据的ID
						@strReturnBillCode OUT,
						@voucherMsg OUT		--出错信息
			END
			--处理发票状态
		
			EXEC GP_Receipt_Deal @nBillID,0
			

			
			UPDATE ReceiptBillIndex
			SET ifcheck='t',draft=0,Poster=@chvOpID
			WHERE BillNumberId=@nBillID
		END
		ELSE IF @nBillType =400
		BEGIN
			IF EXISTS(
				SELECT ConfigName
				FROM Userconfig
				WHERE ConfigName='appraisalbillautogenerationreceiptbill' AND Value='1'
			)
			BEGIN
				EXEC GP_AppraisalBill_CreateReciptBill
					@chvOpID,
					@nBillID,
					@intReturnID,		--新生成的单据的ID
					@strReturnBillCode OUT,
					@strErrMsg 		--出错信息
			END

		END
		ELSE IF @nBillType =401
		BEGIN
			IF EXISTS(
				SELECT ConfigName
				FROM Userconfig
				WHERE ConfigName='appraisalbillautogenerationreceiptbill' AND Value='1'
			)
			BEGIN
				EXEC GP_AppraisalBackBill_CreateReciptBill
					@chvOpID,
					@nBillID,
					@intReturnID,		--新生成的单据的ID
					@strReturnBillCode OUT,
					@strErrMsg 		--出错信息
			END
		END
		ELSE IF @nBillType =402
		BEGIN
			IF EXISTS(
				SELECT ConfigName
				FROM Userconfig
				WHERE ConfigName='sendbillautogenerationreceiptbill' AND Value='1'
			)
			BEGIN
				EXEC GP_SendBill_CreateReciptBill
					@chvOpID,
					@nBillID,
					@intReturnID,		--新生成的单据的ID
					@strReturnBillCode OUT,
					@strErrMsg 		--出错信息
			END
		END
		ELSE IF @nBillType =403
		BEGIN
			IF EXISTS(
				SELECT ConfigName
				FROM Userconfig
				WHERE ConfigName='sendbillautogenerationreceiptbill' AND Value='1'
			)
			BEGIN
				EXEC GP_SendBackBill_CreateReciptBill
					@chvOpID,
					@nBillID,
					@intReturnID,		--新生成的单据的ID
					@strReturnBillCode OUT,
					@strErrMsg 		--出错信息
			END
		END
	END
	
--如果涉及到成本价销售，或生成分支机构单据，那么能否修改，这个需要确认

--处理货位

--根据实际过账，更新成本调价单的数量（以前是在保存时，由页面写入的数量）
EXEC Gp_Auditing_Fill @nBillID,@nBillType

--过账成功后，还需要把新的记录也写入

IF @nBillType NOT IN (404,405)
BEGIN
	EXEC	Gp_NewBill_Clone 
		@nBillID,
		@nBillType
END

--删除凭证关系,下次就可以再判断了  LHL说的
IF @nBillType=311 AND EXISTS(
	SELECT GoodsBillId 
	FROM Ac_CommissionBill_VoucherBill
	WHERE GoodsBillId=@nBillID AND VourchBillId=-1
)
BEGIN
	DELETE Ac_CommissionBill_VoucherBill 
	WHERE GoodsBillId=@nBillID
END
ELSE IF @nBillType IN (404,405) AND EXISTS(
	SELECT GoodsBillId 
	FROM Ac_ReceiptBill_VoucherBill
	WHERE GoodsBillId=@nBillID AND VourchBillId=-1
)
BEGIN
	DELETE Ac_ReceiptBill_VoucherBill 
	WHERE GoodsBillId=@nBillID
END
ELSE	IF EXISTS(
	SELECT GoodsBillId 
	FROM Ac_GoodsBill_VoucherBill
	WHERE GoodsBillId=@nBillID AND VourchBillId=-1
)
BEGIN
	DELETE Ac_GoodsBill_VoucherBill 
	WHERE GoodsBillId=@nBillID
END

--COMMIT TRAN NewBillAudit



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID			numeric(10,0),				-- 1. 单据编号 ID 值
	@nBillType			INT,
	@szCheckMan			VARCHAR(50),				-- 制单人 ID 值
	@chvOpID			VARCHAR(50),				-- 当前操作员 ID 值
	@nRet				INT,						--0表示修改成功，其他都表示出错
	@strMsg				VARCHAR(500),				--返回的错误提示信息
	@KTypeID			VARCHAR(50)					-- 返回仓库ID值，针对多仓库应用
	
SELECT
	@nBillID=6,
	@nBillType=11,
	@szCheckMan='00001',
	@chvOpID='00001'
	
BEGIN TRAN	
EXEC	Gp_NewBill_Audit 
	@nBillID,
	@nBillType,
	@szCheckMan,
	@chvOpID,
	@nRet	OUT,
	@strMsg	OUT,
	@KTypeID OUT


SELECT B.FullName,A.* FROM ListTable A
INNER JOIN Ac_Items B
ON A.AtypeId=B.nId
		
select APTotal,nAPTotal,* from BType_ArApTotal

SELECT * FROM GOODSSTOCKS

SELECT * FROM GOODSSTOCKS_QTY

select b.FullName,a.* from AType_Total a
inner join Ac_Items b
on a.ATypeID=b.nId


SELECT @nRet,@strMsg,@KTypeID

ROLLBACK TRAN

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

把修改后的物流单据明细复制一份，以便成本重算，这个写入CostRe_Bill

*/
CREATE   PROCEDURE Gp_NewBill_Clone 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT
)
--@encode$--
AS

--为测试过程中好排错，新建表来保存要修改的单据主表和明细



--写入老的单据明细表，先不区分出入库
--在OldBill_Reverse中写入了老单据的明细，所以这里不删除，但是需要判断下

DECLARE
	@datPostTime	DATETIME
	
SELECT @datPostTime=PostTime
FROM Billindex
WHERE BillNumberId=@nBillID AND BillType=@nBillType	

IF @nBillType NOT IN (404,405)
BEGIN
	INSERT CostRe_Bill(BillNumberID,BillType,PTypeID,KTypeID,STypeID,PostTime,BillDate)
	SELECT DISTINCT a.BillNumberID,a.BillType,a.PTypeID,a.KTypeID,a.STypeID,@datPostTime,a.BillDate
	FROM InOutstocktable a
	WHERE a.BillNumberId=@nBillID AND a.BillType=@nBillType AND a.IsService=0
	AND NOT EXISTS(
		SELECT BillNumberID
		FROM CostRe_Bill b
		WHERE b.BillNumberID=@nBillID AND b.BillType=@nBillType
		AND a.PtypeId=b.PTypeID
		AND a.KtypeId=b.KTypeID
		AND b.Posttime=@datPostTime
	)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT
	
SELECT
	@nBillID=2,
	@nBillType=34
	
BEGIN TRAN	

EXEC	Gp_NewBill_Clone 
	@nBillID,
	@nBillType


COMMIT TRAN
--ROLLBACK TRAN


*/



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：谢吉康
	日期：2004-11-11
	描述：重写应收、应付查询
          原来的算法有问题
    日期：2010-02-21
    作者：毛欣蓉
    描述：应收应付查询重做
    
    日期：2012-05-11
    作者：黄清
    描述：往来调整，重做应收应付
*/
CREATE  PROCEDURE Gp_NewqrWl30625
( 
	@OperatorID 	VARCHAR(100) ,   --操作员id
	@btypeid 		VARCHAR(100),	--往来单位节点号
	@stypeid		VARCHAR(2000),	--分支机构
	@StartDate		VARCHAR(50),
	@EndDate		VARCHAR(50),
	@option			int=0,	--选项  0全部显示 1不显示金额为0 2只显示金额为0，3无发生额不显示
	@nType			int,			--1,3  应收  2,4应付
	@etypeid        VARCHAR(2000),	--经手人	
	@includepre		VARCHAR(10)='False'
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL NVARCHAR(MAX),
		@lstSQL VARCHAR(1000),
		@SonNum int,
		@SqlWhere	VARCHAR(1000),
		@SqlWhere1	VARCHAR(1000),
		@preSql1	VARCHAR(1000), --应收增加条件
		@preSql2	VARCHAR(1000), --应收减少条件
		@AtypeType	VARCHAR(1000), --要查询的科目
		@QmSql		VARCHAR(1000)

create table #stype
(
	typeid		VARCHAR(50)
)
create table #btype1
(
	typeid		VARCHAR(50)
)
--分支机构
INSERT INTO #stype(typeid) 
	SELECT  A.typeid
		FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A
		
--往来单位		
INSERT INTO #btype1(typeid) 
	SELECT  A.typeid
		FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) A

--经手人 不带权限范围
create table #etype(typeid	VARCHAR(50))
INSERT INTO #Etype(typeid) 
SELECT  A.typeid FROM F_GetAllBaseTypeId(@etypeid,3) A
		
DECLARE @BillType VARCHAR(MAX)
SET @BillType=''

IF @nType='1' or @nType ='3'
BEGIN
	SET @BillType=@BillType+'305,11,160,141,93,85,167,168,172,181,45,149,148,4,'
	IF @includepre='true'
		SET @BillType=@BillType+'189'
END
ELSE
BEGIN
	SET @BillType=@BillType+'34,161,145,36,84,170,6,151,150,66,'
	IF @includepre='true'
		SET @BillType=@BillType+'190'
END

CREATE TABLE #BillIndex
(
	BillNumberId	 NUMERIC(24, 10) ,
	btypeid			VARCHAR(100),
	billtype		VARCHAR(100),
	totalmoney		 NUMERIC(24, 10) ,
	totalinmoney	 NUMERIC(24, 10) ,
	preferencemoney	 NUMERIC(24, 10) 
)
--压缩主表(查询时间内的数据)
INSERT INTO #BillIndex 
(
	BillNumberId,
	btypeid,
	billtype,
	totalmoney,
	totalinmoney,
	preferencemoney 
)
SELECT	bi.BillNumberId,
		bi.btypeid AS TYPEID,
		BI.BillType,
		bi.totalmoney,
		bi.totalinmoney,
		bi.preferencemoney 
FROM BillIndex BI
INNER JOIN #stype S ON S.typeid=BI.Stypeid
INNER JOIN #etype E ON E.typeid=BI.etypeid
INNER JOIN #btype1 b ON b.typeid=BI.btypeid
WHERE 1=1
AND BillDate >=@StartDate
AND BillDate <=@EndDate
AND BillType IN (SELECT *FROM f_split(@BillType,','))
AND ifYearBill=0
AND ifcheck='t'

--应收增加+ 305,11,160,141,93,85,167,168,172,181
--应收增加- 45,149
--应收减少+	148,4,189(预)
--应收减少- 

--应付增加+ 34,161,145,36,84,170
--应付增加- 6,151
--应付减少+	150,66,190(预)
--应付减少-

DECLARE @billindextname VARCHAR(20)
DECLARE @btypename VARCHAR(20)
SET @billindextname='#BillIndex'
SET @btypename='#BType'

DECLARE @IncludeYsSQL VARCHAR(MAX)
IF @includepre='true' AND  @nType='1' or @nType ='3'
	SET @IncludeYsSQL='		
		UNION ALL
		SELECT	BI.btypeid,
				BM.Total  as BqaddTotal
		FROM '+@billindextname+' BI
		INNER JOIN BillMulAccount BM ON BI.BillNumberId=BM.BillNumberId 
		WHERE	BillType IN (305,11,160,141,93,85,167,168,172,181,45,149)
		AND		BM.ATypeID =''0000200006''
		UNION ALL
		SELECT	BI.btypeid,
				G.Total  as BqaddTotal
		FROM '+@billindextname+' BI
		INNER JOIN gatheringBill G ON BI.BillNumberId=G.BillNumberId 
		WHERE	BillType IN (4)
		AND		G.ATypeID =''0000200006''
		'
ELSE 
	SET @IncludeYsSQL=''

DECLARE @IncludeYfSQL VARCHAR(MAX)
IF @includepre='true' AND  @nType='2' or @nType ='4'
	SET @IncludeYfSQL='
		UNION ALL
		SELECT	BI.btypeid,
				BM.Total  as BqaddTotal
		FROM '+@billindextname+' BI
		INNER JOIN BillMulAccount BM ON BI.BillNumberId=BM.BillNumberId 
		WHERE	BillType IN (34,161,145,36,84,170)
		AND		BM.ATypeID =''0000100009''
		UNION ALL
		SELECT	BI.btypeid,
				p.Total  as BqaddTotal
		FROM '+@billindextname+' BI
		INNER JOIN PayBill p ON BI.BillNumberId=p.BillNumberId 
		WHERE	BillType IN (66)
		AND		p.ATypeID =''0000100009''
		'
ELSE 
	SET @IncludeYfSQL=''


CREATE TABLE #BType
(
	TypeId		VARCHAR(100),
	ystotal		 NUMERIC(24, 10) ,
	yftotal		 NUMERIC(24, 10) ,
	aRaddTotal	 NUMERIC(24, 10) ,
	aRrecTotal	 NUMERIC(24, 10) ,
	aPaddTotal	 NUMERIC(24, 10) ,
	aPrecTotal	 NUMERIC(24, 10) ,
	APQmtotal	 NUMERIC(24, 10) ,
	ARQmtotal	 NUMERIC(24, 10) ,
	ArLimit		 NUMERIC(24, 10) 
)

DECLARE @SQLtbname VARCHAR(50)
SET @SQLtbname='INSERT INTO #BType'
--信用额度
SET @SQL=
'
(
	TypeId,
	YSTotal,
	YFTotal,
	araddTotal,	--应收增加
	arrecTotal,	--应收减少
	apaddTotal, --应付增加
	aprecTotal,	--应付减少
	APQmtotal,	--应付期末
	ARQmtotal,	--应收期末
	ArLimit		--信用额度
)
SELECT	a.TypeId,
		0 AS ystotal,
		0 AS yftotal,
		0 AS araddTotal,
		0 AS arrecTotal,
		0 AS apaddTotal,
		0 AS aprecTotal,
		0 AS APQmtotal,	
		0 AS ARQmtotal,	
		SUM(s.credit) AS ArLimit
FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') a
LEFT JOIN (	SELECT	c.credit,
					c.btypeid
			FROM btype_credit c 
			INNER JOIN   #stype s ON c.StypeId=s.typeid 
		)s ON s.BtypeId=a.typeId 
WHERE SonNum = 0 
GROUP BY A.typeId 
UNION ALL
SELECT	BTypeID,
'
IF @includepre='true' AND  @nType='1' or @nType ='3'
	SET @SQL=@SQL+'
		ystotal AS ystotal,'
ELSE
	SET @SQL=@SQL+'
		0 AS ystotal,'
		
IF @includepre='true' AND  @nType='2' or @nType ='4'
	SET @SQL=@SQL+'
		yftotal AS yftotal,'
ELSE
	SET @SQL=@SQL+'
		0 AS yftotal,'
SET @SQL=@SQL+'
		0 AS araddTotal,
		0 AS arrecTotal,
		0 AS apaddTotal,
		0 AS aprecTotal,'
IF @nType='2' or @nType ='4'
	SET @SQL=@SQL+'
		APTotal AS APQmtotal,'
ELSE
	SET @SQL=@SQL+'
		0 AS APQmtotal,'
IF @nType='1' or @nType ='3'
	SET @SQL=@SQL+'
		ARTotal AS ARQmtotal,'
ELSE 
	SET @SQL=@SQL+'	
		0 AS ARQmtotal,'
SET @SQL=@SQL+'
		0 AS ArLimit
FROM BType_ArApTotal
--GROUP BY BTYPEID
'

IF @nType='1' or @nType ='3'
	SET @SQL=@SQL+'
	UNION ALL
	--应收增加
	SELECT btypeid,
			0 AS ystotal,
			0 AS yftotal,
			SUM(BqaddTotal) AS araddTotal,
			0 AS arrecTotal,
			0 AS apaddTotal,
			0 AS aprecTotal,
			0 AS APQmtotal,	
			0 AS ARQmtotal,	
			0 AS ArLimit
	FROM (
			SELECT	btypeid,
					totalmoney-totalinmoney-preferencemoney as BqaddTotal
			FROM #BillIndex 
			WHERE BillType IN (305,11,160,141,93,85,167,168,172,181) 
			UNION ALL
			SELECT	btypeid,
					-(totalmoney-totalinmoney-preferencemoney) as BqaddTotal
			FROM #BillIndex WHERE BillType IN (45,149)
			'+@IncludeYsSQL+'
	) T
	GROUP BY btypeid
	--应收减少
	UNION ALL
	SELECT btypeid,
			0 AS ystotal,
			0 AS yftotal,
			0 AS aqaddTotal,
			SUM(BqrecTotal) AS arrecTotal,
			0 AS apaddTotal,
			0 AS aprecTotal,
			0 AS APQmtotal,	
			0 AS ARQmtotal,	
			0 AS ArLimit
	FROM (
			SELECT	btypeid,
					totalmoney-totalinmoney-preferencemoney as BqrecTotal
			FROM #BillIndex 
			WHERE  BillType IN (148,189) 
			UNION ALL
			SELECT	btypeid,
					totalmoney+preferencemoney as BqrecTotal
			FROM #BillIndex where BillType IN (4)
	) T2
	GROUP BY btypeid
	'
IF @nType='2' or @nType ='4' --应付增加
	SET @SQL=@SQL+'
	UNION ALL
	SELECT	btypeid,
			0 AS ystotal,
			0 AS yftotal,
			0 AS araddTotal,
			0 AS arrecTotal,
			SUM(BqaddTotal) AS apddTotal,
			0 AS aprecTotal,
			0 AS APQmtotal,	
			0 AS ARQmtotal,	
			0 AS ArLimit
	FROM (
			SELECT	btypeid,
					totalmoney-totalinmoney-preferencemoney as BqaddTotal
			FROM #BillIndex 
			WHERE BillType IN (34,161,145,36,84,170)
			UNION ALL
			SELECT	btypeid,
					-(totalmoney-totalinmoney-preferencemoney) as BqaddTotal
			FROM #BillIndex WHERE BillType IN (6,151)
			'+@IncludeYfSQL+'
	) T3
	GROUP BY btypeid 
	UNION ALL
	SELECT	btypeid,
			0 AS ystotal,
			0 AS yftotal,
			0 AS araddTotal,
			0 AS arrecTotal,
			0 AS apaddTotal,
			SUM(BqrecTotal) AS aprecTotal,
			0 AS APQmtotal,	
			0 AS ARQmtotal,	
			0 AS ArLimit
	FROM (
			SELECT	btypeid,
					totalmoney-totalinmoney-preferencemoney as BqrecTotal
			FROM #BillIndex 
			WHERE  BillType IN (150,190)
			UNION ALL
			SELECT	btypeid,
					totalmoney+preferencemoney as BqrecTotal
			FROM #BillIndex where BillType IN (66)
	) T4
	GROUP BY btypeid
'
--PRINT @SQLtbname+@sql
EXEC(@SQLtbname+@sql)

CREATE TABLE #BTypeBefore --月结到查询开始日期的数据
(
	TypeId		VARCHAR(100),
	ystotal	 NUMERIC(24, 10) ,
	yftotal	 NUMERIC(24, 10) ,
	apaddTotal	 NUMERIC(24, 10) ,
	aprecTotal	 NUMERIC(24, 10) ,
	araddTotal	 NUMERIC(24, 10) ,
	arrecTotal	 NUMERIC(24, 10) ,
	APQmtotal	 NUMERIC(24, 10) ,
	ARQmtotal	 NUMERIC(24, 10) ,
	ArLimit		 NUMERIC(24, 10) 
)
SET @SQLtbname='INSERT INTO #BTypeBefore'

DELETE FROM #BillIndex
--压缩主表(月结到查询开始时间)
INSERT INTO #BillIndex
(
	BillNumberId,
	btypeid,
	billtype,
	totalmoney,
	totalinmoney,
	preferencemoney 
)
SELECT	bi.BillNumberId,
		bi.btypeid AS TYPEID,
		BI.BillType,
		bi.totalmoney,
		bi.totalinmoney,
		bi.preferencemoney 
FROM BillIndex BI
INNER JOIN #stype S ON S.typeid=BI.Stypeid
INNER JOIN #etype E ON E.typeid=BI.etypeid
INNER JOIN #btype1 b ON b.typeid=BI.btypeid
WHERE 1=1
AND BillDate >@EndDate
AND BillType IN (SELECT *FROM f_split(@BillType,','))
AND ifYearBill=0
AND ifcheck='t'

--PRINT @SQLtbname+@sql
EXEC(@SQLtbname+@sql)


DECLARE @SQLcoulumName VARCHAR (MAX)
SET @SQLcoulumName=''

IF @nType=1 OR @nType=3
	SET @SQLcoulumName='		
		SUM(M.BqAddTotal) bqaddtotal,
		SUM(M.Bqretotal) bqrectotal,
		SUM(M.ArLimit) AS arlimit,
		SUM(M.limitartotal) limitartotal,
		SUM(M.total00) AS total00,
		SUM(M.QmTotal) qmtotal
		'
ELSE
	SET @SQLcoulumName='		
		-SUM(M.BqAddTotal) bqaddtotal,
		-SUM(M.Bqretotal) bqrectotal,
		0 AS arlimit,
		0 limitartotal,
		-SUM(M.total00) AS total00,
		-SUM(M.QmTotal) qmtotal
		'

SET @SQL='
SELECT  B.TYPEID,
		b.sonnum,
		b.UserCode,
		b.FullName,
		'
SET @SQL=@SQL+@SQLcoulumName+
'
FROM
(
	SELECT	B2.TypeId AS BTYPEID, 
			B1.ArLimit,
			(B2.ARQmtotal-B2.ystotal-B2.APQmtotal+B2.yftotal-B2.araddTotal)-(B1.araddTotal-B1.apaddTotal)+(B1.arrecTotal-B1.aprecTotal) total00,
			B1.araddTotal-B1.apaddTotal AS BqAddTotal,
			B1.arrecTotal-B1.aprecTotal AS Bqretotal,
			B2.ARQmtotal-B2.ystotal-B2.APQmtotal+B2.yftotal-B2.araddTotal AS QmTotal,
			CASE
				WHEN b1.ArLimit<>0 THEN B2.ARQmtotal-B2.ystotal-B2.APQmtotal+B2.yftotal-B2.araddTotal-B1.ArLimit
				END AS limitartotal
	FROM 
	(
		SELECT	TYPEID,
				SUM(ystotal) AS ystotal,
				SUM(yftotal) AS yftotal,
				SUM(apaddTotal) AS apaddTotal,
				SUM(aprecTotal) AS aprecTotal,
				SUM(araddTotal) AS araddTotal,
				SUM(arrecTotal) AS arrecTotal,
				SUM(APQmtotal) AS APQmtotal,	
				SUM(ARQmtotal) AS ARQmtotal,	
				SUM(ArLimit) AS ArLimit
		FROM #BType
		GROUP BY TypeId
	) B1
	INNER JOIN (SELECT	TYPEID,
						SUM(ystotal) AS ystotal,
						SUM(yftotal) AS yftotal,
						SUM(apaddTotal) AS apaddTotal,
						SUM(aprecTotal) AS aprecTotal,
						SUM(araddTotal) AS araddTotal,
						SUM(arrecTotal) AS arrecTotal,
						SUM(APQmtotal) AS APQmtotal,	
						SUM(ARQmtotal) AS ARQmtotal,	
						SUM(ArLimit) AS ArLimit
				FROM #BTypeBefore
				GROUP BY TypeId
					) B2 ON B1.TypeId=B2.TypeId
) M
RIGHT JOIN btype B ON M.BTYPEID LIKE B.TYPEID+''%''
WHERE B.PARID='''+@btypeid+'''
GROUP BY	B.typeId,
			b.sonnum,
			b.FullName,
			b.UserCode
ORDER BY b.UserCode
'
PRINT @SQL
EXEC(@SQL)	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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






/*
	描述:统计各个类型的vip发卡数量
	作者:haiquan
	日期:2007-11-22
*/
CREATE            PROCEDURE GP_nFreshVipCardNum
--@encode$--
AS
--================统计各个类型vip卡发放的数量=========
DECLARE @CardTypeid int
DECLARE @num int

DECLARE Vip_Cursor CURSOR FOR
	SELECT VipCardTypeid FROM nVipCardSet Where deleted<>'1'

OPEN Vip_Cursor
	FETCH NEXT FROM Vip_Cursor INTO @CardTypeid
	WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT @num = Count(VipCardID) FROM nVipCardSign WHERE deleted<>'1' AND VipCardTypeid=@CardTypeid

			 Update nVipCardSet 
			 SET VipCardnum=@num
			 WHERE VipCardTypeID=@CardTypeid
				   
   			FETCH NEXT FROM Vip_Cursor INTO @CardTypeid
		END
CLOSE Vip_Cursor
DEALLOCATE Vip_Cursor
--==============期初刷新金额===========================
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'inicanmodify' AND SubValue = 'T')
	BEGIN
		--刷新会计科目
		DECLARE @numQcTotal  NUMERIC(24, 10) 
		SELECT  @numQcTotal = ISNULL(SUM(qCczMoney),0) FROM nVipCardSign
		UPDATE  AType SET Total00 = ISNULL(@numQcTotal,0) WHERE TypeId = '0000200005'
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

















/*
	描述:处理Vip卡发卡的信息
	作者:haiquan
	日期:2007-11-22
*/
CREATE            PROCEDURE Gp_nInsertVipCardSign
(
	@OperatorID		    varchar(100),	--超作员的ID
	@Action				varchar(100),	--动作	Add-新增   Modify-修改
	@VipCardId			int,
	@VipCardCode		varchar(100),	--Vip卡卡号
	@Bname				varchar(600),
	@CreateDate			datetime,
	@EndDate			datetime,
	@EName				varchar(600),
	@Cardset			int,
	@Bsex				char(1),
	@Bbirthday			datetime,
	@Btel				varchar(100),
	@Baddr				varchar(100),
	@Bpostcode			varchar(100),
	@Btrade				varchar(100),
	@BIDcard			varchar(100),
	@VipStatus			char(1),
	@Comment			varchar(500),
	@BeginMoney			 NUMERIC(24, 10) ,
	@BeginCent			numeric(18,0),
	@IsCz				varchar(10)='0',
	@qccz				 NUMERIC(24, 10) 
)
--@encode$--
AS

SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
----------------------

DECLARE @ETypeID	  varchar(100)	--发卡人id
DECLARE @ETypeIDx	  varchar(100)	--发卡人id

SET @ETypeIDx=@METypeId


IF EXISTS(SELECT TOP 1 * FROM Employee WHERE FullName = @EName AND Deleted = 0 AND SonNum = 0 AND Typeid like +@ETypeIDx+'%')
  BEGIN
	SELECT @ETypeID = TypeID FROM Employee WHERE FullName = @EName AND Deleted = 0 AND SonNum = 0 AND Typeid like +@ETypeIDx+'%'
  END
ELSE
	BEGIN
		IF(@EName='超级用户')
		  SET @ETypeID='00001'
		ELSE
    	  RETURN -3
	END
--=======================================================新增发卡
IF @Action = 'Add'
BEGIN
	IF EXISTS(SELECT TOP 1 * FROM nVipCardSign WHERE VipCardCode = @VipCardCode AND deleted<>'1')
		BEGIN
			--RAISERROR('该卡号的Vip卡已存在,请确定后重试!',16,1)
			RETURN -1
		END	

	INSERT INTO nVipCardSign
	(
		 VipCardCode,--vip卡号
		 VipCardTypeID  ,--该卡所属vip卡的类型，与nVipCardSet相关联
		 Bname ,--持卡人姓名
		 Bsex,--性别0表示女，1表示男
		 Bbirthday ,--客户生日
		 Btel,--联系电话
		 Baddr  ,--联系地址
		 Bpostcode ,--邮编
		 Btrade  ,--行业
		 BIDcard ,--证件号码
		 etypeid ,--办理人id，和系统employee表关联
		 CreateDate ,--发卡日期
		 EndDate ,
		 deleted ,  
		 BeginMoney ,--初始消费金额
		 BeginCent ,--初始积分
		 totalMoney ,--消费总金额
		 totalCent,--总积分
		 Comment,
		 IsCz,
         qCczMoney
	)
	VALUES
	(
		 @VipCardCode,
		 @Cardset,
		 @Bname,
		 @Bsex,
		 @Bbirthday,
		 @Btel,
		 @Baddr,
		 @Bpostcode,
		 @Btrade,
		 @BIDcard,
		 @etypeid,
		 @CreateDate,
		 @EndDate,
		 @VipStatus,  
		 @BeginMoney,
		 @BeginCent,
		 0,
		 0,
		 @Comment,
		 @IsCz,
		 @qccz
	)



	IF @@ROWCOUNT=0
		BEGIN
			--RAISERROR('录入数据失败,请确定后重试!',16,1)
			RETURN -2
		END		
END

--=======================================================修改发卡
IF @Action = 'Modify'
BEGIN
	IF EXISTS(SELECT * FROM nVipCardSign WHERE VipCardCode = @VipCardCode AND VipCardId <> @VipCardId AND deleted<>'1')
	BEGIN
		RETURN -1
	END


	UPDATE	nVipCardSign
	SET		VipCardCode	=	@VipCardCode   ,
			VipCardTypeID  =	@CardSet,
			Bname 			=	@Bname,
			Bsex			=	@Bsex,
			Bbirthday 		=	@Bbirthday,
			Btel			=	@Btel,
			Baddr  		=	@Baddr,
			Bpostcode 		=	@Bpostcode,
			Btrade  		=	@Btrade,
			BIDcard 		=	@BIDcard,
			etypeid 		=	@etypeid,
			CreateDate 	=	@CreateDate,
			EndDate 		=	@EndDate,
			deleted 		=	@VipStatus,  
			BeginMoney 	=	@BeginMoney,
			BeginCent 		=	@BeginCent,
			Comment 		=	@Comment,
			IsCz			=   @IsCz,
			qCczMoney		=   @qccz
	WHERE	VipCardId 	= @VipCardId
	
	IF @@ROWCOUNT=0
		BEGIN
			--RAISERROR('录入数据失败,请确定后重试!',16,1)
			RETURN -2
		END
END

--================统计各个类型vip卡发放的数量=========
DECLARE @CardTypeid int
DECLARE @num int

DECLARE Vip_Cursor CURSOR FOR
	SELECT VipCardTypeid FROM nVipCardSet Where deleted<>'1'

OPEN Vip_Cursor
	FETCH NEXT FROM Vip_Cursor INTO @CardTypeid
	WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT @num = Count(VipCardID) FROM nVipCardSign WHERE deleted<>'1' AND VipCardTypeid=@CardTypeid

			 Update nVipCardSet 
			 SET VipCardnum=@num
			 WHERE VipCardTypeID=@CardTypeid
				   
   			FETCH NEXT FROM Vip_Cursor INTO @CardTypeid
		END
CLOSE Vip_Cursor
DEALLOCATE Vip_Cursor
--==============期初刷新金额===========================
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'inicanmodify' AND SubValue = 'T')
	BEGIN
		--刷新储值余额
		UPDATE nVipCardSign SET cZyeMoney = qCczMoney + lJczMoney WHERE VipCardCode = @VipCardCode
		--刷新会计科目
		DECLARE @numQcTotal  NUMERIC(24, 10) 
		SELECT  @numQcTotal = ISNULL(SUM(qCczMoney),0) FROM nVipCardSign
		UPDATE  AType SET Total00 = ISNULL(@numQcTotal,0) WHERE TypeId = '0000200005'
	END

RETURN 0



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





















/*
	描述：VipCardSet（类型）的设置
	作者：haiquan
	日期：2007-11-20
*/
CREATE     PROCEDURE GP_nInsertVipGoodsSign(

	  @PTypeid	  	varchar(100),
	  @VipDiscount1  NUMERIC(24, 10) ,
	  @VipDiscount2  NUMERIC(24, 10) ,
	  @VipDiscount3  NUMERIC(24, 10) ,
	  @VipDiscount4  NUMERIC(24, 10) ,
	  @VipPrice		 NUMERIC(24, 10) ,
	  @JFid			int

)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--====================预设折扣和会员价为空时，特殊处理========
	if (@VipDiscount1=-1)
		SELECT @VipDiscount1=-1

	if (@VipDiscount2=-1) 
		SELECT @VipDiscount2=-1

	if (@VipDiscount3=-1) 
		SELECT @VipDiscount3=-1

	if (@VipDiscount4=-1) 
		SELECT @VipDiscount4=-1

	if (@VipPrice=-1)
		SELECT @VipPrice=-1


--===========================================================================================新增Vip卡类型


	IF EXISTS(SELECT TOP 1 * FROM nVipGoodsSign WHERE  PTypeid= @PTypeid)
		BEGIN

		    UPDATE nVipGoodsSign
			SET  Ptypeid=@PTypeid,
				 VipDiscount1=@VipDiscount1,
				 VipDiscount2=@VipDiscount2,
				 VipDiscount3=@VipDiscount3,
				 VipDiscount4=@VipDiscount4,
				 VipPrice=@VipPrice,
				 JFid=@JFid
			WHERE PTypeid= @PTypeid


			IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('录入数据失败，请确认后重试！',16,1)
						RETURN -2
					END
				ELSE
					BEGIN
						--RAISERROR('录入数据成功！',16,1)
						RETURN 0
					END

		END
	ELSE
		BEGIN
			INSERT INTO nVipGoodsSign
			(
				 Ptypeid,
				 VipDiscount1,
				 VipDiscount2,
				 VipDiscount3,
				 VipDiscount4,
				 VipPrice,
				 JFid
			)
			VALUES
			(			
				  @PTypeid,
				  @VipDiscount1,
				  @VipDiscount2,
				  @VipDiscount3,
				  @VipDiscount4,
				  @VipPrice,
				  @JFid
			)	
	
			IF @@ROWCOUNT = 0
				BEGIN
					--RAISERROR('录入数据失败，请确认后重试！',16,1)
					RETURN -2
				END
			ELSE
				BEGIN
					--RAISERROR('录入数据成功！',16,1)
					RETURN 0
				END
		END


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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



/**********************************************************
作者:Hanlin
日期:2013-12-24
功能:云分销订单审核失败的时候删除本地订单
**********************************************************/
CREATE      PROCEDURE Gp_NoAuditDelOrderBill 
(
   @OrderBillNumberID numeric(10,0)         --订单BillNumberid号   
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @yapiorderid VARCHAR(20)=''

SELECT @yapiorderid=yapiorderid FROM dbo.OrderIndex WHERE billNumberId=@OrderBillNumberID
DELETE FROM  dbo.OrderIndex WHERE billNumberId=@OrderBillNumberID
DELETE FROM dbo.OrderBill WHERE billNumberID=@orderbillnumberid

DELETE FROM dbo.Yapi_OrderBillIndex WHERE orderid=@yapiorderid
DELETE FROM dbo.Yapi_OrderBill WHERE orderid=@yapiorderid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


-- =============================================
-- Author:		黄飞佳
-- Create date: 2012-04-09
-- Description: 修改该过程  添加：b.CanNotModifyPrice
-- =============================================


-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-01-16
-- Description: 调单据主表
-- =============================================

-- 2013.05.22 周华 添加prepricenum
--2014-06-20 罗淮文 添加FeeDeductType(手续费扣除账户-资金调拨单)
CREATE   PROCEDURE GP_NSelectBillIndex 
( 
 @BillNumberId VARCHAR(20)
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR (8000),@Billtype INT, @intMoneyDot int
EXEC	@intMoneyDot=Gp_GetDigit 3
SELECT @Billtype=BillType FROM BillIndex WHERE BillNumberId=@BillNumberId

--调入订单有多个币种，则 显示本币 单个币种 原币
declare @isrmb int --是否是本币 1是本币，0原币
select @isrmb= CASE WHEN COUNT(a.cid)>1 THEN 1
								ELSE 0
								END 
from 
(
	SELECT o.cid,  sum(o.ncustomertotal)as ncustomertotal,sum(o.customertotal) AS customertotal 
	FROM ORDERINDEX O
	INNER JOIN (
				SELECT DISTINCT BILLNUMBERID FROM ORDERBILL WHERE ORDERID IN (SELECT ORDERID FROM SALEBILL WHERE BILLNUMBERID =@BillNumberId)
				) B on o.BILLNUMBERID=b.BILLNUMBERID
	group by o.cid 		
) A		


SET @SQL='
	SELECT 
			CASE WHEN ISNULL(a.CwCheck,0) = 0 THEN ''否'' ELSE ''是'' 
			END AS CwCheck,
			a.redword,
			a.adpricetype,
			a.draft,
			a.ifcheck,
			a.billtype,
			a.billnumberid,
			ISNULL(a.frombillnumberid,0) as frombillnumberid,
			a.tax,
			a.billdate,
			a.BillCode,
			a.etypeid,
			a.dtypeid,
			a.btypeid,
			b.IsUseBrandarType,
			a.ktypeid,
			a.ktypeid2,
			a.alertday,
			a.explain,
			a.comment,
			a.atypeid as nid,
			a.atypeid,
			a.waybillcode,
			a.goodsnumber,
			a.packway,
			a.tel,
			a.totalmoney,
			a.ntotalmoney,
			a.totalinmoney,
			a.NTotalInMoney,
			a.preferencemoney as preference,
			a.NPreferenceMoney,
			a.ifwx,
			ISNULL(a.ifbargainon,0) as ifbargainon,
			a.stypeid,
			a.costsale,
			a.totalqty,
			a.otherinouttype,
			a.cwcheck,
			a.ifmulaccount,
			a.sharemode,
			a.posbilltype,
			a.btypeid,
			a.checke,
			e2.fullname as tallyer,
			CASE WHEN ISNULL(a.FromBillNumberID,0) = 0 THEN ''0''
			ELSE (select top 1 oi.checke from billindex oi where oi.billNumberId=a.FromBillNumberID) END AS createid,
			(select fullname from btype where typeId=a.btypeid) as bfullanme,
			a.dealbtypeid,
			(select fullname from btype where typeId=a.dealbtypeid) as dealbname,
			a.rate,
			CASE WHEN a.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
			ELSE
				(select fullname from Ac_Currency where cid=a.CID) END as fullname,
			CASE WHEN a.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE a.CID END  as cid,
			b.CanNotModifyPrice,
			ISNULL(B.fullname,'''') as bfullname,
			ISNull(au.BillDetail,'''') AS BillDetail,
			isnull(E.fullname,'''') AS efullname,
			ISNULL(k.fullname,'''') AS kfullname,
			ISNULL(K2.Fullname,'''') AS kfullname2, 
			CASE ISNULL(a.IfMulAccount,0) WHEN 1 THEN ''【多账户】''
				ELSE isnull(Ac_Items.fullname,'''') 
			END AS afullname,
			CASE ISNULL(CAST(b.price AS NUMERIC(24,10)),0.0) WHEN 0.0 THEN 1 ELSE b.price END AS saleprice,
			CASE ISNULL(CAST(b.buyprice AS NUMERIC(24,10)),0.0) WHEN 0.0 THEN 1 ELSE b.buyprice END AS buyprice,
			ISNULL(D.FullName,'''') AS dfullname,
			ISNULL(E1.FullName,'''') AS checkman, 
			a.atypeid1,
			aa.fullname AS atypeid1name,
			a.CompleteTotal,
			a.NCompleteTotal,
			a.IfCargo,
			a.IfInvoice,
			a.ninvoicemoney,
			a.invoicemoney,
			a.promoRuleId,
			a.BeforePromoBillNumberId,
			a.newposbill,
			case when promotionmsg=''0'' then ''''
			else promotionmsg end as promotionmsg,
			isnull(a.artotal,0) as billystotal,
			isnull(a.ystotal,0) as billyustotal,
			isnull(a.aptotal,0) as billyftotal,
			isnull(a.yftotal,0) as billyuftotal,
			CASE WHEN a.BillType = 34 THEN isnull(a.APTotal,0)-isnull(a.ARTotal,0)+isnull(a.YSTotal,0)-isnull(a.yftotal,0) 
                 ELSE isnull(a.artotal,0)-isnull(a.ystotal,0)-(isnull(a.aptotal,0)-isnull(a.yftotal,0)) END as billysyftotal,
			ISNULL(a.isauto,0) as isauto,
			cast(a.isyapi as int) as isyapi ,
			cast(a.yapiorderid as varchar(20)) as yapiorderid ,	
			a.DeliveryAddress,
			a.islend,
			a.paytype,
			a.chargeofftype,
			ISNULL((select sum(paymoney) as paymoney from BillMulAccount where billnumberid=a.billnumberid),0) as paymoney,
			a.chargeoffbtypeid,
			(select fullname from btype where typeId=a.chargeoffbtypeid) as chargeoffbfullanme,a.totalmoney,
			'
	--添加修改人
	SET @SQL += 'a.updateE, '	
	SET @SQL += '(select top 1 fullname from employee where typeid=a.updateE) as updateEName, '	
--IF @Billtype = 11
--BEGIN
--  		--添加修改人
--	SET @SQL += 'a.updateE, '	
--	SET @SQL += '(select top 1 fullname from employee where typeid=a.updateE) as updateEName, '	
--END				
IF @Billtype IN(11,34)
	SET @SQL = @SQL +'
			ISNULL(O.Billcode,'''') AS ordercode, '
IF @Billtype IN(11,140)
	SET @SQL = @SQL +'
			a.IsFreightMoney,
			a.FreightAddr,
			a.FreightPerson,
			a.FreightTel,
			a.TransportId,
			t.fullname as tranfullname,
			t.typeid as btrantypeid,
			t.bfullname as btranfullname, 
			'
IF @Billtype IN(212,213)
	SET @SQL += 
		'
			A.AssetBusinessTypeId,
			(select top 1 fullname from Ac_AssetBusinessType where id = a.AssetBusinessTypeId) AS businesstypename,
		'			
			
IF @Billtype IN(201,202)
	SET @SQL = @SQL +' 
			ISNULL(OT.FullName,'''') AS othertypefullname, '
SET @SQL = @SQL +'
			ISNULL(S.FullName,'''') AS sfullname,
			a.uf1,
			a.uf2,
			a.uf3,
			a.uf4,
			a.uf5,
			a.ifyearbill,
			a.billproperty,
			a.prepricenum,a.stypeid2,s2.fullname as sfullname2,a.ifconfirm,a.transfertype,a.feededucttype,a.discount,'
IF @BillType In (115,116,128,129)
BEGIN
	SET @SQL = @SQL + ' CASE WHEN a.isini=1 THEN a.nchargeofftotal ELSE (SELECT SUM(nchargeofftotal) FROM addebtbill WHERE billnumberid='''+@BillNumberId+''') END AS nchargeofftotal,'
	SET @SQL = @SQL + ' CASE WHEN a.isini=1 THEN a.chargeofftotal ELSE (SELECT SUM(chargeofftotal) FROM addebtbill WHERE billnumberid='''+@BillNumberId+''') END AS chargeofftotal,'
END
ELSE
BEGIN
	SET @SQL = @SQL + 'a.nChargeOffTotal,a.ChargeOffTotal,'
END

IF @BillType In (11,160,139,140,6,161,146,17,21,187,202,16,183,401,402,12,57)
	SET @SQL = @SQL + 'a.WarehouseOutDay,a.LinkMan,a.LinkTel,a.LinkAddr,a.IsNeedTransport,'
	
IF @BillType In (215,45,160,142,34,161,126,144,17,21,188,201,16,400,403)
	SET @SQL = @SQL + 'a.StockInDeadline,'

IF @BillType In (414)
	SET @SQL = @SQL + 'a.IsFreightMoney,a.FreightPerson,a.FreightTel,a.totalfreight,a.Ntotalfreight,a.transportno,a.WarehouseOutDay,a.StockInDeadline,a.Transporterid,a.Transporterfullname,a.shipperfullname,a.shipperperson,a.shippertel,'
	
SET @SQL = @SQL +'
CASE WHEN A.jsstyle=1 THEN (CASE WHEN a.completetotal <> 0 THEN 1 ELSE 0 END) ELSE 0 END AS BalancedForBill,	--是否已经按单结算
CASE WHEN a.nChargeOffTotal>0 THEN 1 ELSE 0 END AS IsVerification,--是否已经被往来核销
CASE WHEN (SELECT COUNT(1) FROM ShareSourceBill ssb WHERE ssb.FromBillNumberID=a.BillNumberId AND ssb.FromBillType=34) > 0 THEN 1 ELSE 0 END AS CalledByBuyFeeShare,--是否被采购费用分摊调用
CASE WHEN (SELECT COUNT(1) FROM ShareSourceBill ssb WHERE ssb.FromBillNumberID=a.BillNumberId AND ssb.FromBillType=11) > 0 THEN 1 ELSE 0 END AS CalledBySaleFeeShare--是否被销售费用分摊调用'

SET @SQL = @SQL + '
,a.iscombinationstyle 
,a.PromonIds
,dbo.F_GetPromoRuleNames(a.PromonIds) AS promos
,ROUND(dbo.F_GetOrderNCustomerTotal(a.billnumberid,a.billtype),'+CAST (@intMoneyDot AS VARCHAR(50))+') as ncustomertotal --订金总额
,isnull ('+cast(@isrmb as varchar(10))+' ,0) as isrmb--订单本、原币
,isnull(isByBrandarType,0) as  isByBrandarType --收款单 按单收款
,a.jsstyle
,a.PayOnTheSpot
FROM billindex a
LEFT JOIN AuditingBill au	ON (au.billnumberid=a.billnumberid AND Au.BillIndexType = 2)
LEFT JOIN Ac_Items ON a.atypeid = Ac_Items.nID
LEFT JOIN btype b ON a.btypeid = b.typeId
LEFT JOIN employee E ON A.etypeid=E.typeId
LEFT JOIN STOCK k ON k.typeId= A.ktypeid
LEFT JOIN STOCK k2 ON k2.typeId=A.ktypeid2 
LEFT JOIN employee e1 ON E1.typeId=A.checke 
LEFT JOIN employee e2 ON A.TallyId=e2.typeId '
IF @Billtype IN(11,34)
	SET @SQL = @SQL +'
			LEFT JOIN OrderIndex O ON a.orderid= o.billNumberId '
IF @Billtype IN(11,140)
	SET @SQL = @SQL +'
			LEFT JOIN (
			SELECT	t.id,
					t.fullname,
					b.typeid,
					b.fullname as bfullname 
			FROM	QP_Transport t LEFT JOIN btype b on b.typeid = t.btypeid
		   )t
		   ON a.TransportId = t.id '
IF @Billtype IN(201,202)
	SET @SQL = @SQL +'
			LEFT JOIN OtherInOutType OT ON OT.ID=A.OtherInOutType '
SET @SQL = @SQL +'
LEFT JOIN Stype S ON S.TypeId= A.Stypeid 
LEFT JOIN Stype S2 ON S2.Typeid=A.StypeId2
LEFT JOIN Ac_Account aa ON (a.atypeid1 = aa.typeid AND aa.StypeId=S.VerifyID)
LEFT JOIN department D ON D.typeid= A.DTypeId
WHERE a.BillNumberId = '+@billnumberid
		
--print @sql
EXEC (@SQL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2009-01-05
	描述：充值VIP卡
	Gp_nVipAddMoney '00001','1',100,'0000100003','aaaa'
*/
CREATE  PROCEDURE Gp_nVipAddMoney
(
	@chvOperator	varchar(100),
	@CardId			varchar(100),
	@JE				 NUMERIC(24, 10) ,
	@ZH				varchar(100),
	@BZ				varchar(500)
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********
DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -1

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

-- ********	判断是否试用版 - END	********

DECLARE @Re int,@Flag int
EXEC @Re=Gp_Validate 2, @Flag OUTPUT
IF @Re <>0 RETURN -3 --检查程序版本错误

IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
BEGIN
	--RAISERROR('校验错误 ！',16,1) 
	RETURN -3 --检查程序版本错误
END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -16
	END
END 
-- ********	判断是否试用版 - End	******** 

IF @JE = 0
	BEGIN
		DELETE FROM nVipAddMoney WHERE aMoney = 0
		RETURN 0
	END

--如果开账日期大于当前日期，则不允许充值
IF EXISTS(SELECT TOP 1 1 FROM MonthProc WHERE StartDate>GetDate() AND MonthNo = '本期')
	RETURN -15

DECLARE @BeginDate 	datetime,
		@szItem 	varchar(30),
		@szVchCode 	varchar(30),
		@szPeriod	varchar(20),
		@cefullname			VARCHAR(500)='',		--制单人
		@cdfullname			VARCHAR(500)=''			--部门

DECLARE @CheckeName varchar(100),
		@CardName   varchar(200)

SELECT @CheckeName = FullName FROM Employee WHERE TypeId = @chvOperator

SELECT @CardName=VipCardCode FROM nVipCardSign WHERE VipCardId = @CardId
IF @@ROWCOUNT = 0
	RETURN -17

--写入储值明细
INSERT INTO nVipAddMoney
(
	CardId,
	BillDate,
	ETypeId,
	aMoney,
	ATypeId,
	Comment,
	Checke
)VALUES(
	@CardId,
	CONVERT(varchar(10),GetDate(),120),
	@chvOperator,
	@JE,
	@ZH,
	@BZ,
	@CheckeName
)

DECLARE
	@datBillDate	DATETIME
	
SELECT
	@datBillDate=Convert(varchar(10),GetDate(),120)

IF @@ROWCOUNT = 0
	BEGIN
		RETURN -11
	END
ELSE				
	BEGIN
		--增加充值数据
		UPDATE nVipCardSign SET lJczMoney = lJczMoney + @JE,cZyeMoney = cZyeMoney + @JE WHERE VipCardId = @CardId
		IF @@ROWCOUNT = 0 
			BEGIN
				RETURN -12
			END
		ELSE
			--自动生成一张会计凭证	会员储值(0000200005)
			DECLARE @Month		varchar(10),
					@Day		varchar(10),
					@bCode		varchar(300),
					@nBillId	numeric(18,0),
					@ETypeId	varchar(100),
					@Period		int,
					@DTypeId	varchar(100),
					@rex		int,
					@szPID		varchar(1000),
					@eUserCode	varchar(100),
					@kUserCode	varchar(100)

			--如果只有超级用户，则报错
			SELECT TypeId FROM Employee WHERE TypeId NOT IN ('00000','00001') AND Deleted =0 AND SonNum = 0
			IF @@ROWCOUNT = 0
				RETURN -99996
			
			--取系统第一个经手人
			IF @chvOperator = '00001'
				SELECT TOP 1 @ETypeId = TypeId,@eUserCode=TypeId FROM Employee WHERE Deleted = 0 AND SonNum = 0 ORDER BY UserCode				
			ELSE
				BEGIN
					SET @ETypeId = @chvOperator
					SELECT TOP 1 @eUserCode=TypeId FROM Employee WHERE TypeId = @ETypeId AND Deleted = 0 AND SonNum = 0 ORDER BY UserCode					
				END

			--部门信息
			SELECT TOP 1 @DTypeId = ISNULL(D.TypeId,'') FROM Department D,Employee E WHERE D.FullName = E.Department AND D.SonNum = 0 AND D.Deleted = 0

			--仓库编号
			SELECT TOP 1 @kUserCode = FullName FROM Stock WHERE Deleted = 0 AND SonNum = 0 ORDER BY UserCode
		
			--本期
			SELECT @Period=Period FROM MonthProc WHERE MonthNo = '本期'

			IF EXISTS(SELECT * FROM UserConfig WHERE ConfigName = 'IfBillCode' AND Value = 0)
				BEGIN
					SET @bCode = 'KP-'+Replace(Convert(varchar(10),GetDate(),120),'-','')+'-'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
				END
			ELSE
				BEGIN
					IF EXISTS(SELECT * FROM UserConfig WHERE ConfigName = 'BillCodeConfig' AND Value = 0)
						BEGIN
							SET @Month = Month(GetDate())
							SET @Day   = Day(GetDate())
						END
					ELSE
						BEGIN
							IF NOT EXISTS(SELECT * FROM CodeConfig WHERE BillType = 159)
								BEGIN
									SET @Month = Month(GetDate())
									SET @Day   = Day(GetDate())
								END
							ELSE
								BEGIN
									SET @Month = @eUserCode
									SET @Day   = @kUserCode
								END
						END
					
					SELECT @cefullname=fullname FROM dbo.employee WHERE typeId=@chvOperator
					SELECT @cdfullname=fullname FROM dbo.Department WHERE typeId=@DTypeId
					
					--获取单据编号
					EXEC Gp_GetBillCode 159,@Month,@Day,'KP',@datBillDate, @bCode OUTPUT,@cdfullname,@cefullname
				END
				
			

			--写入主表
			INSERT INTO BillIndex
			(
				BillDate,
				BillCode,
				BillType,
				ETypeId,
				IfCheck,
				Checke,
				TotalMoney,
				TotalInMoney,
				TotalQty,
				Period,
				RedWord,
				Draft,
				AlertDay,
				IfStopMoney,
				DTypeId,
				CompleteTotal,
				PreferenceMoney,
				JF,
				VipCardID,
				Comment,
				ATypeId,
				PTypeId,
				BTypeId,
				KTypeId,
				KTypeId2
			)VALUES(
				@datBillDate,
				@bCode,
				159,
				@ETypeId,
				'f',
				@chvOperator,
				0,
				0,
				0,
				@Period,
				0,
				1,
				9999,
				0,
				@DTypeId,
				0,
				0,
				0,
				-1,
				@CardName+'VIP 卡充值'+CAST(@JE as varchar(20))+'元',
				'',
				'',
				'',
				'',
				''
			)	
			IF @@ROWCOUNT = 0
				BEGIN
					RETURN -13
				END
			ELSE
				SET @nBillId = SCOPE_IDENTITY();
				
			EXEC GP_SaveBillCode_Seed
						@nBillId,
						@datBillDate,
						159,
						@bCode			

			--写入明细表	
			IF @JE>0 		
				BEGIN		
					INSERT INTO AccountCredence(BillNumberId,TypeATypeId,ATypeId,J_Total,D_Total)VALUES(@nBillId,LEFT(@ZH,5),@ZH,dbo.F_RoundTotal(ABS(@JE)),0)
					INSERT INTO AccountCredence(BillNumberId,TypeATypeId,ATypeId,J_Total,D_Total)VALUES(@nBillId,'00002','0000200005',0,dbo.F_RoundTotal(ABS(@JE)))
				END
			ELSE
				BEGIN
					INSERT INTO AccountCredence(BillNumberId,TypeATypeId,ATypeId,J_Total,D_Total)VALUES(@nBillId,LEFT(@ZH,5),@ZH,0,dbo.F_RoundTotal(ABS(@JE)))
					INSERT INTO AccountCredence(BillNumberId,TypeATypeId,ATypeId,J_Total,D_Total)VALUES(@nBillId,'00002','0000200005',dbo.F_RoundTotal(ABS(@JE)),0)
				END

			IF @@ROWCOUNT = 0
				BEGIN
					RETURN -14
				END
	END


RETURN @nBillId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1  FROM sys.types t JOIN sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_IntegralExchange' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_nVipInsertCardSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].GP_nVipInsertCardSet--删除此存储过程的引用
	DROP type [dbo].Type_IntegralExchange 
END
GO
CREATE TYPE Type_IntegralExchange AS TABLE					 
(
   JFCent	NUMERIC(24,10)	NOT NULL DEFAULT(0),
   JFMoney  NUMERIC(24,10)	NOT NULL DEFAULT(0)
)
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_nVipInsertCardSet]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[GP_nVipInsertCardSet]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	描述：VipCardSet（类型）的设置
	作者：haiquan
	日期：2007-11-20
*/
CREATE PROCEDURE GP_nVipInsertCardSet(
	@ntype					VARCHAR(20),
	@typename 				VARCHAR(200),
	@discounttype			VARCHAR(50),
	@cardtypediscount		NUMERIC(24, 10) =NULL,
	@ifjf					CHAR(1),
	@comment 				VARCHAR(255),
	@validdate				INT,
	@validtype				INT,
	@jfgz					INT,
	@givecent				NUMERIC(10,0),
	@typelevel				INT,
	@standardcent			NUMERIC(10,0),
	@deductcent				NUMERIC(10,0),
	@VipCardTypeId			INT,
	@IfBirthDay				VARCHAR(10) = '0',--是否启用会员生日积分
	@BirthDayMultiple		NUMERIC(24, 2) = 0 ,--会员生日积分倍数
	@IfDate					VARCHAR(10) = 0,--是否启用日期
	@DateMultiple			NUMERIC(24, 2) = 0 ,--日期积分倍数
	@StartDate				VARCHAR(10),
	@EndDate				VARCHAR(10),
	@IfSalesIntegral		INT ,
	@etypeid				VARCHAR(50),
	@CentToMoney			INT = 0,
	@CentToMoneySet			Type_IntegralExchange READONLY
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

DECLARE 
	@UpgradingScheme	INT =0,
	@changeComment		VARCHAR(100),
	@Error				INT=0
	
IF @IfSalesIntegral=1
	SET	 @changeComment='促销不参与积分'
ELSE
	SET	 @changeComment='促销参与积分'

--低于当前操作员的销售折扣
IF @discounttype = 10 AND EXISTS(SELECT TOP 1 1 FROM dbo.employee WHERE typeid = @etypeid AND @cardtypediscount < SaleMinvalue)
	BEGIN	
		RAISERROR('您所设置的折扣低于您权限的最低折扣，请确认！',16,1) RETURN
	END

--积分转储值规则设置
IF EXISTS(SELECT TOP 1 1 FROM @CentToMoneySet) AND EXISTS(SELECT TOP 1 1 FROM @CentToMoneySet GROUP BY JFCent HAVING COUNT(*)>1)
	BEGIN
		RAISERROR('积分转储值金额设置积分额度不能重复，请确认！',16,1) RETURN
	END
	
--名称是否重复
IF EXISTS(SELECT TOP 1 * FROM nVipCardSet WHERE TypeName = @typename  AND deleted='0' AND (@ntype='A' OR (@ntype = 'M' AND VipCardTypeId <> @VipCardTypeId)))
	BEGIN
		RAISERROR('会员卡类型名称已经存在，请确认！',16,1) RETURN
	END
	
--升级规则是否重复
IF EXISTS(SELECT TOP 1 * FROM nVipCardSet WHERE  TypeLevel=@typelevel AND @typelevel<>0 AND deleted='0' AND (@ntype='A' OR (@ntype = 'M' AND VipCardTypeId <> @VipCardTypeId)))
	BEGIN
		RAISERROR('级别一到五的会员卡类型只能存在一个，请确认！',16,1) RETURN
	END
	
BEGIN TRAN
IF @ntype = 'A'--新增Vip卡类型
	BEGIN
		INSERT INTO dbo.nVipCardSet
		(
			TypeName ,
			DiscountType ,
			ifJF ,
			deleted ,
			Comment ,
			ValidDate ,
			ValidType ,
			CardTypeDiscount ,
			jfgz ,
			GiveCent ,
			TypeLevel ,
			StandardCent ,
			DeductCent,
			IfBirthDay,
			BirthDayMultiple,
			IfDate,
			DateMultiple,
			StartDate,
			EndDate	,
			IfSalesIntegral,
			CentToMoney
		)
		VALUES  
		( 
			@typename,
			@discounttype,
			@ifjf,
			'0',
			@comment,
			@validdate,
			@validtype,
			@cardtypediscount,
			@jfgz,
			@givecent,
			@typelevel,
			@standardcent,
			@deductcent,
			@IfBirthDay,
			@BirthDayMultiple,
			@IfDate,
			@DateMultiple,
			@StartDate,
			@EndDate,
			@IfSalesIntegral,
			@CentToMoney	
		)
		SELECT @VipCardTypeId=@@IDENTITY
		SET @Error+=@@ERROR
				
		INSERT INTO NVipCardSetLog( updateTime,etypeid,VipCardTypeID,ChangeType,comment)  
		VALUES(GETDATE(),@etypeid,@VipCardTypeId,@IfSalesIntegral,'新建卡类型:'+@changeComment)
		SET @Error+=@@ERROR

	END
IF @ntype = 'M'--修改Vip卡类型
	BEGIN
		UPDATE nVipCardSet
		SET		
			TypeName=@typename ,
			DiscountType=@discounttype,
			ifJF=@ifjf,
			Comment=@comment,
			ValidDate=@validdate,
			ValidType=@validtype,
			CardTypeDiscount=@cardtypediscount,
			jfgz=@jfgz,
			GiveCent=@givecent,
			TypeLevel=@typelevel,
			StandardCent=@standardcent,
			DeductCent=@deductcent,
			IfBirthDay=@IfBirthDay,
			BirthDayMultiple=@BirthDayMultiple,
			IfDate=@IfDate,
			DateMultiple=@DateMultiple,
			StartDate=@StartDate,
			EndDate=@EndDate,
			IfSalesIntegral=@IfSalesIntegral,
			CentToMoney=@CentToMoney
		WHERE
			VipCardTypeId=@VipCardTypeId
		SET @Error+=@@ERROR
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM nVipCardSet WHERE VipCardTypeID=@VipCardTypeId AND IfSalesIntegral=@IfSalesIntegral)
		BEGIN
			INSERT INTO NVipCardSetLog(updateTime,etypeid,VipCardTypeID,ChangeType,comment)  
			VALUES(GETDATE(),@etypeid,@VipCardTypeId,@IfSalesIntegral,'修改:'+@changeComment)
			SET @Error+=@@ERROR
		END

	END

--nVipCardSet_IntegralExchange 积分类型-积分转储值设置表
DELETE FROM nVipCardSet_IntegralExchange WHERE VipCardTypeID=@VipCardTypeId
SET @Error+=@@ERROR

INSERT INTO nVipCardSet_IntegralExchange(VipCardTypeID,JFCent,JFMoney)
SELECT @VipCardTypeId,JFCent,JFMoney FROM @CentToMoneySet ORDER BY JFCent
SET @Error+=@@ERROR

IF(@Error=0)
	COMMIT TRAN 
ELSE 
	ROLLBACK TRAN

RETURN @Error

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

/*
作者：李海铨haiquan
日期：2006-12-11
功能：批量更新物价
*/
CREATE PROCEDURE Gp_nVipPriceUpdate(

	@OperatorID 	varchar(50),
	@ParId 			varchar(50)='',
	@usercode 		varchar(50)='',
	@fullname 		varchar(66)='',
	@queryMode 		int=1,
	@strRow			varchar(100),	--修改什么价格
	@strGen			varchar(100), 	--运算符号
	@strPriceValue  varchar(100),	--值，保存运算公式中，第二个数据信息
	@jf				int=-1,
	@strOldValue    VARCHAR(100)   --原价格来源
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL varchar(8000),@strSQL varchar(8000)
DECLARE @PTypeid varchar(100)

CREATE TABLE #Result
(
	Ptypeid      varchar(100),
	VipDiscount1  NUMERIC(24, 10) ,
	VipDiscount2  NUMERIC(24, 10) ,
	VipDiscount3  NUMERIC(24, 10) ,
	VipDiscount4  NUMERIC(24, 10) ,
	VipPrice1 	  NUMERIC(24, 10) ,
	VipPrice2 	  NUMERIC(24, 10) ,
	VipPrice3	  NUMERIC(24, 10) ,
	VipPrice4 	  NUMERIC(24, 10) ,
	VipPrice5 	  NUMERIC(24, 10) ,
	VPrice1		  NUMERIC(24, 10) ,
	VPrice2		  NUMERIC(24, 10) ,
	VPrice3		  NUMERIC(24, 10) ,
	VPrice4		  NUMERIC(24, 10) ,
	VPrice5		  NUMERIC(24, 10) ,
	JFid	  int,
	unitid		int,
	isdefaultunit int
)

/*-------------------------------获得ptypeid（摘自gp_priceinfo）-------------------------------*/
IF @parid='00000'
   SET @PTypeid=@MPTypeId
ELSE
   SET @PTypeid=@parid


SET @SQL='
		 INSERT INTO #Result
		 SELECT distinct P.typeid as Ptypeid,
				CASE WHEN VipDiscount1=-1 THEN 0 ELSE isnull(VipDiscount1,0) END as VipDiscount1,
				CASE WHEN VipDiscount2=-1 THEN 0 ELSE isnull(VipDiscount2,0) END as VipDiscount2,
				CASE WHEN VipDiscount3=-1 THEN 0 ELSE isnull(VipDiscount3,0) END as VipDiscount3,
				CASE WHEN VipDiscount4=-1 THEN 0 ELSE isnull(VipDiscount4,0) END as VipDiscount4,
				CASE WHEN VipPrice1=-1 THEN 0 ELSE isnull(VipPrice1,0) END as VipPrice1,
				CASE WHEN VipPrice2=-1 THEN 0 ELSE isnull(VipPrice2,0) END as VipPrice2,
				CASE WHEN VipPrice3=-1 THEN 0 ELSE isnull(VipPrice3,0) END as VipPrice3,
				CASE WHEN VipPrice4=-1 THEN 0 ELSE isnull(VipPrice4,0) END as VipPrice4,
				CASE WHEN VipPrice5=-1 THEN 0 ELSE isnull(VipPrice5,0) END as VipPrice5,				
				isnull(VipPrice1,0) AS VPrice1,
				isnull(VipPrice2,0) AS VPrice2,
				isnull(VipPrice3,0) AS VPrice3,
				isnull(VipPrice4,0) AS VPrice4,
				isnull(VipPrice5,0) AS VPrice5,				
				isnull(JFid,0) as JFid,
				e.unitsid,
				e.isdefaultunit				
				FROM Ptype P 
				left join ptype_units_ext e on p.typeid =e.ptypeid 
				Left Join nVipGoodsSign A On A.PtypeID=p.typeid and a.unitid=e.unitsid
				LEFT JOIN nVipJfset J ON A.JFid=J.id
				LEFT JOIN (SELECT TypeId FROM F_GetManDetailPType('+char(39)+@OperatorID+char(39)+'))	 f ON f.TypeId=p.typeId					
		WHERE 	P.sonnum=0				  	
				AND e.ratetype = 0'
	 			
IF	@PTypeid<>''
	SET @SQL=@SQL+' AND p.typeid LIKE '''+@PTypeid+'%'''
IF  @usercode<>''
	SET @SQL=@SQL+' AND p.usercode LIKE ''%'+@usercode+'%'''
IF  @fullname<>''
	SET @SQL=@SQL+' AND p.fullname LIKE ''%'+@fullname+'%'''
				
	EXEC(@SQL) 

/*----------构建临时表分别存储字符串的值，构件逻辑上的数组-------------*/

CREATE Table #Row
(
[id]    int IDENTITY (1, 1) NOT NULL,
Rvalue  int
)

CREATE Table #Gen
(
[id]    int IDENTITY (1, 1) NOT NULL,
Gvalue  int 
)

CREATE Table #Pvalue
(
[id]     int IDENTITY (1, 1) NOT NULL,
PVvalue   NUMERIC(24, 10)  NULL
)

CREATE Table #Ovalue
(
[id]     int IDENTITY (1, 1) NOT NULL,
OVvalue  VARCHAR(100) NULL
)
/*-----------插值入表--------------*/
INSERT INTO #Row 	SELECT * FROM F_split(@strRow,',')
INSERT INTO #Gen 	SELECT * FROM F_split(@strGen,',')
INSERT INTO #Pvalue SELECT * FROM F_split(@strPriceValue,',')
INSERT INTO #Ovalue SELECT * FROM F_split(@strOldValue,',')

/*------------声明变量-----------------*/
DECLARE @Rvalue [int]
DECLARE @Gvalue [int]
DECLARE @Pvvalue varchar(30)
/*-------------保存sql语句元素-----------*/
DECLARE @strSQL2 varchar(8000)
DECLARE @SQL2 varchar(8000)

DECLARE @C  NUMERIC(24, 10) 
DECLARE @Pid varchar(100)  
DECLARE @OldValueType VARCHAR(100)



DECLARE @i int
SELECT @i=1

DECLARE @tmpSql NVARCHAR(1000)
SET @tmpSql=' FROM PType_Price  WHERE #Result.Ptypeid=PType_Price.ptypeid'

/*--------------读取值，并做处理-------------------------*/
WHILE (@i<=9)
 BEGIN
	SELECT @Rvalue=null
    SELECT @strSQL2=''
	SELECT @Rvalue=Rvalue 	FROM #Row 	 WHERE [id]=@i
	SELECT @Gvalue=Gvalue 	FROM #Gen 	 WHERE [id]=@i
	SELECT @Pvvalue=Pvvalue FROM #Pvalue WHERE [id]=@i
    SELECT  @OldValueType=OVvalue FROM #Ovalue WHERE [id]=@i
		
	if (@Rvalue is null)
	BREAK

-------修改字段--------

	SELECT @strSQL2=
	CASE @Rvalue
		 WHEN 1 THEN
			'VipDiscount1 = VipDiscount1 '
		 WHEN 2 THEN
			'VipDiscount2 = VipDiscount2'
		 WHEN 3 THEN
			'VipDiscount3 = VipDiscount3'
		 WHEN 4 THEN
			'VipDiscount4 = VipDiscount4'
		 WHEN 5 THEN
			'VipPrice1 = '+@OldValueType
		WHEN 6 THEN
			'VipPrice2 = '+@OldValueType
		WHEN 7 THEN
			'VipPrice3 = '+@OldValueType
		WHEN 8 THEN
			'VipPrice4 = '+@OldValueType
		WHEN 9 THEN
			'VipPrice5 = '+@OldValueType
	END

-------运算符--------

	SELECT @strSQL2=@strSQL2+
	CASE @Gvalue
		 WHEN 1 THEN
			'+'
		 WHEN 2 THEN
			'-'
		 WHEN 3 THEN
			'*'
		 WHEN 4 THEN
			'/'
	END
	
	--只更改基本单位的会员价格
	declare @sqlwhere varchar(1000)
		set @sqlwhere='#Result.isdefaultunit=1 AND PType_Price.IsDefaultUnit = 1 '
	
	IF @Rvalue IN (5,6,7,8,9)
		SELECT @SQL2='UPDATE #Result SET '+ @strSQL2 +@Pvvalue + @tmpSql + ' and '+@sqlwhere
    ELSE 
		SELECT @SQL2='UPDATE #Result SET '+ @strSQL2 +@Pvvalue 
		
	--PRINT @SQL2
	EXEC (@SQL2)	
	

	SELECT 	@Pid=null
	SELECT 	@Pid=Ptypeid
	FROM #Result 
	WHERE 	CASE @Rvalue
				 WHEN 1 THEN
					VipDiscount1
				 WHEN 2 THEN
					VipDiscount2
				 WHEN 3 THEN
					VipDiscount3
				 WHEN 4 THEN
					VipDiscount4
			END
			<= 0
			OR
			CASE @Rvalue
				 WHEN 1 THEN
					VipDiscount1
				 WHEN 2 THEN
					VipDiscount2
				 WHEN 3 THEN
					VipDiscount3
				 WHEN 4 THEN
					VipDiscount4
			END
			> 1

	IF (@Pid is not null) --如果预设折扣不在（0，1]范围内返回
		RETURN 4
/*特殊判断会员价格是否为负*/

	IF (@Rvalue=5 OR @Rvalue=6 OR @Rvalue=7 OR @Rvalue=8 OR @Rvalue=9)
	  BEGIN
		SELECT 	@Pid=null

		SELECT 	@Pid=Ptypeid
		FROM #Result 
		WHERE  VipPrice1 < 0 OR VipPrice2 < 0 OR VipPrice3 < 0 OR VipPrice4 < 0 OR VipPrice5 < 0

		IF (@Pid is not null) --如果单价小于0，返回商品id
			RETURN 3
	  END

	SET @i=@i+1
 END

INSERT INTO nVipGoodsSign(Ptypeid,VipDiscount1,VipDiscount2,VipDiscount3,VipDiscount4,VipPrice1,VipPrice2,VipPrice3,VipPrice4,VipPrice5,JFid,UNITID)
SELECT  PTypeid,
		VipDiscount1=0,
		VipDiscount2=0,
		VipDiscount3=0,
		VipDiscount4=0,
		VipPrice1=0,
		VipPrice2=0,
		VipPrice3=0,
		VipPrice4=0,
		VipPrice5=0,
		JFid=0 ,
		UNITID
FROM #Result R
WHERE not exists (SELECT N.Ptypeid,N.unitid FROM nVipGoodsSign N where N.PTYPEID=R.PTYPEID AND N.UNITID =R.UNITID )


 
BEGIN TRANSACTION --设定回滚

	UPDATE nVipGoodsSign SET 
		   VipDiscount1 = CASE R.VipDiscount1 WHEN 0 THEN -1 ELSE R.VipDiscount1 END,
		   VipDiscount2 = CASE R.VipDiscount2 WHEN 0 THEN -1 ELSE R.VipDiscount2 END,
		   VipDiscount3 = CASE R.VipDiscount3 WHEN 0 THEN -1 ELSE R.VipDiscount3 END,
		   VipDiscount4 = CASE R.VipDiscount4 WHEN 0 THEN -1 ELSE R.VipDiscount4 END,
		   
		   VipPrice1 = case R.VipPrice1 when 0 then -1 else r.VipPrice1 end,
		   VipPrice2 = case R.VipPrice2 when 0 then -1 else r.VipPrice2 end,
		   VipPrice3 = case R.VipPrice3 when 0 then -1 else r.VipPrice3 end,
		   VipPrice4 = case R.VipPrice4 when 0 then -1 else r.VipPrice4 end,
		   VipPrice5 = case R.VipPrice5 when 0 then -1 else r.VipPrice5 end,  
		   JFid= CASE @JF WHEN -1 THEN V.JFid ELSE @JF END
	FROM   #Result R ,
		   nVipGoodsSign  V
	WHERE  R.Ptypeid = V.Ptypeid and r.unitid=v.unitid
	


/*---判断是否成功更新----*/

IF @@rowcount < 1
	BEGIN
		ROLLBACK TRANSACTION
		RETURN 2
	END
ELSE
	BEGIN
		COMMIT TRANSACTION
	END

	UPDATE nVipGoodsSign SET VipPrice1=-1
	WHERE  VipPrice1=0 
		   AND  Ptypeid IN (SELECT Ptypeid FROM #Result WHERE VPrice1=-1)

	UPDATE nVipGoodsSign SET VipPrice2=-1
	WHERE  VipPrice2=0 
		   AND  Ptypeid IN (SELECT Ptypeid FROM #Result WHERE VPrice2=-1)
    
    UPDATE nVipGoodsSign SET VipPrice3=-1
	WHERE  VipPrice3=0 
		   AND  Ptypeid IN (SELECT Ptypeid FROM #Result WHERE VPrice3=-1)
	
	UPDATE nVipGoodsSign SET VipPrice4=-1
	WHERE  VipPrice4=0 
		   AND  Ptypeid IN (SELECT Ptypeid FROM #Result WHERE VPrice4=-1)
		  
	UPDATE nVipGoodsSign SET VipPrice5=-1
	WHERE  VipPrice5=0 
		   AND  Ptypeid IN (SELECT Ptypeid FROM #Result WHERE VPrice5=-1)

	
DROP TABLE #Result
DROP TABLE #Row
DROP TABLE #Gen
DROP TABLE #Pvalue

RETURN 0














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



/*
作者：ldl
日期：2013-08-16
功能：修改、批量修改物价
*/
CREATE          PROCEDURE Gp_nVipPriceUpdateMore(

	@OperatorID 	varchar(50),
	@ptypeid 		varchar(50)='',
	@vipdiscount1	numeric (24,10),
	@vipdiscount2	numeric(24,10),
	@vipdiscount3	numeric(24,10),
	@vipdiscount4	numeric(24,10),
	@vipprice1		numeric(24,10),
	@vipprice2		numeric(24,10),
	@vipprice3		numeric(24,10),
	@vipprice4		numeric(24,10),
	@vipprice5		numeric(24,10),
	@jfid			varchar(50),
	@isedit			varchar(2),
	@unitsid		int
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

IF(@isedit=0)--修改
BEGIN
	DELETE FROM nVipGoodsSign WHERE ptypeid in (SELECT * FROM F_GetAllManagerBaseTypeId('',1,@OperatorID))
		and PTYPEID =@ptypeid and UnitID=@unitsid
	INSERT INTO nVipGoodsSign(ptypeid,vipdiscount1,vipdiscount2,vipdiscount3,vipdiscount4,vipprice1,vipprice2,vipprice3,vipprice4,vipprice5,jfid,UnitID)
		SELECT a.typeId,b.y1,b.y2,b.y3,b.y4,b.hy1,b.hy2,b.hy3,b.hy4,b.hy5,b.jf,b.UnitID
		FROM (SELECT typeId FROM dbo.ptype WHERE typeid in (SELECT * FROM F_GetAllManagerBaseTypeId('',1,@OperatorID))
				and  typeid = @ptypeid and sonnum=0) a 
		INNER JOIN (select   @ptypeid as  ptypeid,
							case when isnull(@vipdiscount1,0)=0 then -1  else  @vipdiscount1 end  as y1,
							  case when isnull(@vipdiscount2,0)=0 then -1 else  @vipdiscount2 end as y2,
							  case when isnull(@vipdiscount3,0)=0 then -1 else  @vipdiscount3  end as y3,
							  case when isnull(@vipdiscount4,0)=0 then -1 else  @vipdiscount4   end as y4,
							  case when isnull(@vipprice1,0)=0 then -1 else @vipprice1 end as hy1,
							  case when isnull(@vipprice2,0)=0 then -1 else @vipprice2  end as hy2,
							  case when isnull(@vipprice3,0)=0 then -1 else @vipprice3  end as hy3,
							  case when isnull(@vipprice4,0)=0 then -1 else @vipprice4  end as hy4,
							  case when isnull(@vipprice5,0)=0 then -1 else @vipprice5  end as hy5,
							 @jfid as jf,
							 @unitsid as UnitID ) b ON a.TYPEID =b.ptypeid			 
							 
	update nVipGoodsSign set jfid=@jfid where ptypeid=@ptypeid
							 
	
END
ELSE--批量修改
BEGIN
	--记已存非基本单位的会员价 这部分不能被直接删掉
	create  table #nvipgoodsign
			(	ptypeid  varchar(50),
				UnitID	int,
				vipprice1 decimal(24,10),
				vipprice2 decimal(24,10),
				vipprice3 decimal(24,10),
				vipprice4 decimal(24,10),
				vipprice5 decimal(24,10)
				--,jfid	int
			)

	insert into #nvipgoodsign 
	select	n.ptypeid,
			n.UnitID,
			n.vipprice1,
			n.vipprice2,
			n.vipprice3,
			n.vipprice4,
			n.vipprice5
			--,n.jfid
			
	from nVipGoodsSign n
	inner join ptype_units_ext e on n.ptypeid=e.ptypeid and n.UnitID=e.unitsid and e.isdefaultunit<>1 and e.ratetype=0
	
	delete  FROM nVipGoodsSign WHERE ptypeid in (SELECT * FROM F_GetAllManagerBaseTypeId('',1,@OperatorID))
	and ptypeid like @PTypeid+'%'
	
	INSERT INTO nVipGoodsSign(ptypeid,vipdiscount1,vipdiscount2,vipdiscount3,vipdiscount4,vipprice1,vipprice2,vipprice3,vipprice4,vipprice5,jfid,UnitID)
	SELECT	a.typeId,
			b.y1,
			b.y2,
			b.y3,
			b.y4,
			case when e.isdefaultunit=0 then -1 else b.hy1 end as hy1,
			case when e.isdefaultunit=0 then -1 else b.hy2 end as hy2,
			case when e.isdefaultunit=0 then -1 else b.hy3 end as hy3,
			case when e.isdefaultunit=0 then -1 else b.hy4 end as hy4,
			case when e.isdefaultunit=0 then -1 else b.hy5 end as hy5,
			 b.jf ,
			 e.unitsid
		FROM (SELECT typeId FROM dbo.ptype WHERE typeid in (SELECT * FROM F_GetAllManagerBaseTypeId('',1,@OperatorID))
				and  typeid like @PTypeid+'%' and sonnum=0) a 
		INNER JOIN (select   @ptypeid as  ptypeid,
							 case when isnull(@vipdiscount1,0)=0 then -1  else  @vipdiscount1 end  as y1,
							  case when isnull(@vipdiscount2,0)=0 then -1 else  @vipdiscount2 end as y2,
							  case when isnull(@vipdiscount3,0)=0 then -1 else  @vipdiscount3  end as y3,
							  case when isnull(@vipdiscount4,0)=0 then -1 else  @vipdiscount4   end as y4,
							  case when isnull(@vipprice1,0)=0 then -1 else @vipprice1 end as hy1,
							  case when isnull(@vipprice2,0)=0 then -1 else @vipprice2  end as hy2,
							  case when isnull(@vipprice3,0)=0 then -1 else @vipprice3  end as hy3,
							  case when isnull(@vipprice4,0)=0 then -1 else @vipprice4  end as hy4,
							  case when isnull(@vipprice5,0)=0 then -1 else @vipprice5  end as hy5,
							  @jfid as jf) b ON a.TYPEID like b.ptypeid+'%'
		LEFT JOIN  ptype_units_ext e on e.ptypeid=a.typeid and e.ratetype=0
		
		update nVipGoodsSign
		set vipprice1=n.vipprice1,
			vipprice2=n.vipprice2,
			vipprice3=n.vipprice3,
			vipprice4=n.vipprice4,
			vipprice5=n.vipprice5
		from #nvipgoodsign n ,
			nVipGoodsSign v
		where n.ptypeid=v.ptypeid and n.UnitID=v.UnitID
		
		drop table #nvipgoodsign
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	修改作者：谢吉康
	修改日期：2004-3-2
	修改描述：开账时对序列号基本信息的判断[PTypeID,BTypeID,KTypeID]

*/
CREATE   PROCEDURE Gp_OkIni
(
	@STypeId		VARCHAR(MAX),		--	仓库信息
    @ReturnValue	VARCHAR(3000) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN OkIni
SAVE TRAN OkIniPoint

DECLARE	@IfMustSerial	BIT,			--是否序列号全局强制管理（是则检查匹配；否则不检查）		
		@IfSType		INT,			--是否启用分支机构
		@StypeFullName	VARCHAR(MAX)
		
SELECT @StypeFullName = S.FullName FROM SType S WHERE S.TypeId=@STypeId
CREATE TABLE #Ktype(TypeId VARCHAR(50),Fullname VARCHAR(200))
INSERT INTO #Ktype(TypeId,Fullname) SELECT TypeId,FullName FROM Stock WHERE STypeId = @STypeId AND SonNum = 0
UPDATE dbo.Ini_GOODSSTOCKS_QTY SET LockNumber=0 WHERE LockNumber IS NULL
DECLARE @starPTypeID VARCHAR(50)
DECLARE @starBTypeID VARCHAR(50)
DECLARE @starKTypeID VARCHAR(50)
DECLARE @starPTypeName VARCHAR(200)
DECLARE @starBTypeName VARCHAR(66)
DECLARE @starKTypeName VARCHAR(66)

----------------判断是否启用分支机构----------------
SET @IfSType = 0

--A8有分支机构	
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
BEGIN
	SET @IfSType = 1		
END
		
-----------------判断分支机构是否开账----------------
--如果分支机构已经开账，则直接返回
IF EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeID = @STypeId AND Value = '1' AND ConfigNo = '1')
BEGIN
	ROLLBACK TRAN OkIniPoint
	COMMIT TRAN OkIni
	RETURN 0
END

IF @IfSType = 1
	SET @StypeFullName = '分支机构【'+@StypeFullName+'】中的'
ELSE
	SET @StypeFullName = ''
	
--------------- 判断序列号	--------------------------------
DECLARE @RE INT=0
SELECT @IfMustSerial=Value FROM UserConfig WHERE ConfigName='mngSerial'

SET @ReturnValue=''
IF @IfMustSerial='1'
BEGIN
	EXEC @RE = Gp_OkIniSerial @StypeId,@ReturnValue output
	
	--select @re,@ReturnValue
END
IF  ISNULL(@RE,0)<0
BEGIN
	ROLLBACK TRAN OkIniPoint
	COMMIT TRAN OkIni
	RETURN @RE
END

-------------- 处理库存期初----------------------------------
DELETE FROM iniGoodsStocks 
WHERE	Qty = 0 
		AND Total = 0 
		AND KtypeId IN(SELECT TypeId FROM #Ktype)
DELETE FROM dbo.Ini_GOODSSTOCKS_QTY
WHERE	Qty=0
		AND NQty=0
		AND KtypeId IN(SELECT TypeId FROM #Ktype)
				
DELETE FROM iniCommissionStock
WHERE	(Qty = 0 AND Total = 0 AND CostTotal = 0 AND Type = 140) OR (Qty = 0 AND Total = 0 AND Type = 144)
		AND STypeID = @STypeId
DELETE FROM dbo.IniCommissionStock_Qty
WHERE	Qty=0
		AND NQty=0
		AND STypeID = @STypeId
		
UPDATE	iniGoodsStocks
SET		Total = CAST(Total AS  NUMERIC(24, 10) )
WHERE	KtypeId IN(SELECT TypeId FROM #Ktype)

DECLARE	@AVERAGE	smallint,
				@FIFO		smallint,
				@LIFO		smallint,
				@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法

DECLARE	@nCostingMethod	INT

EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output

UPDATE	iniGoodsStocks
SET		Price = dbo.F_RoundPrice(Total/Qty)
WHERE	Qty <> 0
		AND KtypeId IN(SELECT TypeId FROM #Ktype)
		AND @nCostingMethod<>@HAND

UPDATE	iniCommissionStock
SET		Total = CAST(Total AS  NUMERIC(24, 10) ),
		CostTotal = CAST(CostTotal AS  NUMERIC(24, 10) )
WHERE	STypeID = @STypeId	
	
DELETE FROM GoodsStocks WHERE KtypeId IN(SELECT TypeId FROM #Ktype)
DELETE FROM CommissionStock WHERE STypeID = @STypeId
DELETE FROM Gp_CruPTypeSerial WHERE KtypeId IN(SELECT TypeId FROM #Ktype)

------------------------------判断期初库存-----------------------------------------------------------
------------------------------库龄期初---------------------------------------------------------------
EXEC Gp_OkIniStockAge @STypeId
------------------------------库龄期初---------------------------------------------------------------
----------------- ----借欠期初处理-------------------------------------------------------------
--存在修改
 UPDATE A SET	A.Qty=ISNULL(A.Qty,0)+ISNULL(B.Qty,0),
				A.NQty=ISNULL(A.NQty,0)+ISNULL(B.NQty,0),
				A.LendQty=ISNULL(A.LendQty,0)+ISNULL(B.LendQty,0),
				A.NLendQty=ISNULL(A.NLendQty,0)+ISNULL(B.NLendQty,0),
				A.BorrowQty=ISNULL(A.BorrowQty,0)+ISNULL(B.BorrowQty,0),
				A.NBorrowQty=ISNULL(A.NBorrowQty,0)+ISNULL(B.NBorrowQty,0)
 FROM dbo.GoodsLend A INNER JOIN dbo.IniGoodsLend B ON A.BTypeID=B.BTypeID AND 
													   A.PTypeID=B.PTypeID AND 
													   A.KTypeID=B.KTypeID AND
													   A.GoodsOrder=B.GoodsOrder AND 
													   A.GoodsNumber=B.GoodsNumber AND 
													   A.ItemID=B.ItemID AND 
													   A.Iscombined=B.Iscombined AND
													   A.ProduceDate=B.ProduceDate AND
													   A.ValidDate=B.ValidDate
 WHERE B.KTypeID IN(SELECT typeId FROM dbo.Stock WHERE STypeID=@STypeId AND sonnum = 0)
 --新增
 INSERT INTO dbo.GoodsLend
        ( BtypeId ,
          PtypeId ,
          KtypeId ,
          JobNumber ,
          OutFactoryDate ,
          Qty ,
          Price ,
          Total ,
          GoodsOrder ,
          GoodsNumber ,
          ItemID ,
          Iscombined ,
          NQty ,
          ProduceDate ,
          ValidDate ,
          LendQty ,
          NLendQty ,
          BorrowQty ,
          NBorrowQty
        )
        SELECT  A.BtypeId ,
                A.PtypeId ,
                A.KtypeId ,
                A.JobNumber ,
                A.OutFactoryDate ,
                A.Qty ,
                A.Price ,
                A.Total ,
                A.GoodsOrder ,
                A.GoodsNumber ,
                A.ItemID ,
                A.Iscombined ,
                A.NQty ,
                A.ProduceDate ,
                A.ValidDate ,
                A.LendQty ,
                A.NLendQty ,
                A.BorrowQty ,
                A.NBorrowQty
        FROM    dbo.IniGoodsLend A
        WHERE   A.KTypeID IN ( SELECT   typeId						
                               FROM     dbo.Stock
                               WHERE    STypeID = @STypeId
                                        AND sonnum = 0 )
                AND NOT EXISTS ( SELECT 1								--存在相同记录不插入
                                 FROM   dbo.GoodsLend B
                                 WHERE  A.BTypeID = B.BTypeID
                                        AND A.PTypeID = B.PTypeID
                                        AND A.KTypeID = B.KTypeID
                                        AND A.GoodsOrder = B.GoodsOrder
                                        AND A.GoodsNumber = B.GoodsNumber
                                        AND A.ItemID = B.ItemID
                                        AND A.Iscombined = B.Iscombined
                                        AND A.ProduceDate = B.ProduceDate
                                        AND A.ValidDate = B.ValidDate )
														    
----------------- ----借欠期初处理-------------------------------------------------------------


----------------------实物库存期初-------------------------------------------------------------
DELETE FROM dbo.FactStocks WHERE KtypeId IN (SELECT typeId FROM  dbo.Stock WHERE STypeID = @STypeId AND sonnum = 0 )
DELETE FROM dbo.FactStocks_Qty WHERE KtypeId IN (SELECT typeId FROM  dbo.Stock WHERE STypeID = @STypeId AND sonnum = 0 )
  
INSERT INTO dbo.FactStocks
        ( PtypeId ,
          KtypeId ,
          Qty 
        )
SELECT 
		  PtypeId ,
          KtypeId ,
          Qty 
FROM  dbo.IniFactStocks A
WHERE   A.KTypeID IN ( SELECT  typeId						
                               FROM     dbo.Stock
                               WHERE    STypeID = @STypeId
                                        AND sonnum = 0 )

INSERT INTO dbo.FactStocks_Qty
        ( PTypeID ,
          KTypeID ,
          CargoID ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          Qty ,
          NQty
        )
SELECT
          PTypeID ,
          KTypeID ,
          CargoID ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          Qty ,
          NQty
FROM dbo.IniFactStocks_Qty A
WHERE   A.KTypeID IN ( SELECT  typeId						
                               FROM     dbo.Stock
                               WHERE    STypeID = @STypeId
                                        AND sonnum = 0 )
 
----------------------实物库存期初-------------------------------------------------------------

----------------- ----特殊处理会计科目-------------------------------------------------------------


DECLARE @nTotal  NUMERIC(24, 10) ,
		@nidNBYS INT ,
		@nWTDXTotal  NUMERIC(24, 10) ,
		@nSTDXTotal  NUMERIC(24, 10) ,
		@total00 NUMERIC(24, 10) 

DECLARE	@GOODS_ID VARCHAR(50),			
		@GOODS_WTDX_ID VARCHAR(50),
		@GOODS_STDX_ID VARCHAR(50),
		@Cid int
 
SELECT @GOODS_ID=nid FROM dbo.Ac_Items WHERE UserCode='1241'			--『库存商品总值合计』
SELECT @GOODS_WTDX_ID=nid FROM dbo.Ac_Items WHERE UserCode='1261'		--『委托代销商品』
SELECT @GOODS_STDX_ID=nid FROM dbo.Ac_Items WHERE UserCode='2141'		--『代销商品』
SELECT @cid=cid FROM dbo.Ac_Currency WHERE Sysrow=1
SELECT @nidNBYS=nid FROM dbo.Ac_Items WHERE FullName='内部应收'

SELECT @total00= ISNULL(SUM(InnerARTotal00),0) FROM SType_InnerARTotal WHERE STypeID=@stypeid 

DELETE dbo.AType_Total WHERE ATypeID=@nidNBYS AND STypeID=@stypeid
INSERT INTO dbo.AType_Total( ATypeID , STypeID ,Total00 , CID , Ntotal00) VALUES(@nidNBYS,@stypeid,@total00,@Cid,@total00)

DELETE FROM  AType_Total WHERE ATypeID IN (@GOODS_ID,@GOODS_WTDX_ID,@GOODS_STDX_ID) AND STypeID=@stypeid

SELECT @nTotal=ISNULL(SUM(I.total),0) FROM inigoodsstocks I INNER JOIN #Ktype K ON I.KtypeId=K.TypeId
INSERT INTO AType_Total(ATypeID,STypeID,Total00,Ntotal00,CID)VALUES(@GOODS_ID,@STypeId,@nTotal,@Ntotal,@Cid)

SELECT @nWTDXTotal=ISNULL(SUM(CostTotal),0) FROM inicommissionStock WHERE Type=140 AND STypeID = @STypeId
INSERT INTO AType_Total(ATypeID,STypeID,Total00,Ntotal00,CID)VALUES(@GOODS_WTDX_ID,@STypeId,@nWTDXTotal,@nWTDXTotal,@Cid)

UPDATE iniCommissionStock SET CostTotal = 0 WHERE Type = 144 AND STypeID = @STypeId

SELECT @nSTDXTotal=ISNULL(SUM(Total),0) FROM inicommissionStock WHERE Type=144 AND STypeID = @STypeId
INSERT INTO AType_Total(ATypeID,STypeID,Total00,Ntotal00,CID)VALUES(@GOODS_STDX_ID,@STypeId,@nSTDXTotal,@nSTDXTotal,@Cid)

-------------处理未分配利润-------------------
DECLARE @lr_id INT,@lrtotal00  NUMERIC(24, 10) 
SELECT @lr_id=nid FROM dbo.Ac_Items WHERE USERcode='3141'  --未分配利润

IF NOT EXISTS(SELECT 1 FROM dbo.AType_Total WHERE ATypeID=@lr_id AND Total00<>0 AND STypeID=@stypeid)
BEGIN
SELECT @lrtotal00=ISNULL(sum(total00),0)
FROM dbo.AType_Total WHERE ATypeID IN(SELECT nId FROM dbo.Ac_Items WHERE nTypeId like '00003%' and sonnum=0)
AND STypeID=@stypeid

SELECT @lrtotal00-=ISNULL(sum(total00),0)
FROM dbo.AType_Total 
WHERE ATypeID IN(SELECT nId FROM dbo.Ac_Items WHERE nTypeId like '00004%' and sonnum=0)
AND STypeID=@stypeid

IF @lr_id<>0
	BEGIN	
		DELETE FROM dbo.AType_Total WHERE ATypeID=@lr_id AND STypeID=@stypeid
		INSERT INTO atype_total (atypeid,stypeid,total00,ntotal00,cid)VALUES(@lr_id,@stypeid,@lrtotal00,@lrtotal00,@cid);	
	END
END

--------------------计算其他资本，使资产负载平衡--------------------------------
DECLARE @Other_ID INT,@ZCTotal  NUMERIC(24, 10) =0,@FZTotal  NUMERIC(24, 10) =0,@QYTotal  NUMERIC(24, 10) =0

SELECT @Other_ID=nid FROM ac_items WHERE UserCode='3101'

SELECT @ZCTotal=ISNULL(SUM(Total00),0)
FROM dbo.AType_Total
WHERE ATypeID IN (SELECT nid FROM dbo.Ac_Items WHERE nTypeId LIKE '00001%' AND SonNum=0 AND usercode<>'1132')  --排除内部应收
	AND atypeid NOT IN ( SELECT nid FROM ac_items WHERE UserCode IN ('SYC-1601','SYC-1602'))
	AND STypeID=@stypeid


--加上内部应收	
SET @ZCTotal+=(SELECT ISNULL(SUM(InnerARTotal00),0) FROM dbo.SType_InnerARTotal WHERE STypeID=@stypeid)	

--------------单独计算固定资产看片的值-----------
DECLARE @ifassetsini INT ,@iscard INT=0,@val  NUMERIC(24, 10) =0.0
SELECT @ifassetsini =ifassetsini FROM stype where typeid=@stypeid;

IF  EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
	SET @iscard=1
	
IF @iscard =1  
BEGIN
  IF @ifassetsini=0  --卡片显示,未初始化的情况
	SET @ZCTotal+=(SELECT ISNULL(SUM(w.netvalue),0) AS netvalue FROM Ac_AssetsCards w WHERE w.AssetsState IN(1,4) AND stypeid=@stypeid)
	ELSE
	BEGIN
		SET @ZCTotal+=
		(
			SELECT ISNULL(SUM(netvalue),0) AS netvalue
			 FROM (
					SELECT rn=ROW_NUMBER() OVER(PARTITION BY AssertsCardId ORDER BY Id desc),* FROM Ac_AssetsCards_History WHERE BillType=0 AND stypeid=@stypeid
					)a WHERE rn=1 AND stypeid=@stypeid
		)

	END
	
END
--------------单独计算固定资产看片的值 end-----------

	
SELECT @FZTotal=ISNULL(SUM(Total00),0)
FROM dbo.AType_Total
WHERE ATypeID IN (SELECT nid FROM dbo.Ac_Items WHERE nTypeId LIKE '00002%' AND SonNum=0)
	AND STypeID=@stypeid
	
SELECT @QYTotal=ISNULL(SUM(Total00),0)
FROM dbo.AType_Total
WHERE ATypeID IN (SELECT nid FROM dbo.Ac_Items WHERE nTypeId LIKE '00005%' AND SonNum=0 AND nId<>@Other_ID)
	AND STypeID=@stypeid
	
DELETE FROM dbo.AType_Total WHERE ATypeID=@Other_ID AND STypeID=@stypeid
INSERT INTO dbo.AType_Total( ATypeID , STypeID ,Total00 , CID , Ntotal00) VALUES(@Other_ID,@Stypeid,@ZCtotal-@FZTotal-@QYTotal,@Cid,@ZCtotal-@FZTotal-@QYTotal)
--------------------计算其他资本，使资产负载平衡 end--------------------------------

--修改财务期初汇总值	
UPDATE	AType_Total
SET		Total = Total00,
		ntotal = Ntotal00
WHERE	STypeID = @STypeId	

DELETE FROM dbo.AType_Total WHERE Ntotal=0 AND Ntotal00=0 AND Total=0 AND Total00=0

--修改往来期初汇总值	
UPDATE	BType_ARAPTotal 
SET		ARTotal = ARTotal00,
		APTotal = APTotal00,
		YSTotal = YSTotal00,
		YFTotal = YFTotal00,
		nARTotal = nARTotal00,
		nAPTotal = nAPTotal00,
		nYSTotal = nYSTotal00,
		nYFTotal = nYFTotal00,
		GRIRTotal=GRIRTotal00,
		NGRIRTotal=NGRIRTotal00,
		FCTotal=FCTotal00,
		NFCTotal=NFCTotal00
WHERE	STypeID = @STypeId	
	
--修改品牌往来期初汇总值,期初值不动	
UPDATE	dbo.Brandar_ArApTotal 
SET		ARTotal = ARTotal00,
		YSTotal = YSTotal00,
		nARTotal = nARTotal00,
		nYSTotal = nYSTotal00
		
WHERE	STypeID = @STypeId	

-----------------------------------------将期初库存写入当前库存表-------------------------------------------

DECLARE @chvCosting varchar(5)
SELECT @chvCosting = SubValue FROM SysData WHERE SubName = 'costing'
IF @chvCosting = '0'
BEGIN
	INSERT INTO GoodsStocks (
		PTypeID,
		KTypeID,
		Qty,
		Price,
		Total
	)
	SELECT	a.PTypeID,
			a.KTypeID,
			SUM(a.Qty) AS Qty,
			CASE WHEN SUM(a.Qty) = 0 THEN 0
				ELSE dbo.F_RoundPrice(SUM(a.Total)/SUM(a.Qty))END AS Price,
			SUM(a.Total) AS Total
	FROM	iniGoodsStocks a
	INNER JOIN #Ktype K ON A.KtypeId=K.TypeId
	GROUP BY a.PTypeID, a.KTypeID
END
ELSE
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM iniGoodsStocks I INNER JOIN #Ktype K ON I.KtypeId=K.TypeId WHERE I.Qty <= 0 )
	BEGIN
		SELECT TOP 1 @starPTypeID=I.PtypeId,@starKTypeID=I.KtypeId
		FROM iniGoodsStocks I INNER JOIN #Ktype K ON I.KtypeId=K.TypeId WHERE I.Qty <= 0

		SELECT TOP 1 @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
		SELECT TOP 1 @starKTypeName=FullName FROM Stock WHERE TypeID=@starKTypeID

		SELECT @ReturnValue='在仓库【'+@starKTypeName+'】中的商品【'+@starPTypeName+'】有数量为零或负数的批次记录，当前配置的成本核算法不允许开账，请修改确认后重试！'
		GOTO CostQtyError
	END
	INSERT INTO dbo.GoodsStocks
	        ( PtypeId ,
	          KtypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          Qty ,
	          Price ,
	          Total ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID
	        )
	SELECT  i.PtypeId ,
	        i.KtypeId ,
	        i.JobNumber ,
	        i.OutFactoryDate ,
	        SUM(i.Qty) ,
	        i.Price ,
	        SUM(i.Total) ,
	        i.GoodsOrder ,
	        i.GoodsNumber ,
	        i.ProduceDate ,
	        i.ValidDate ,
	        i.GoodsBTypeID 
	FROM iniGoodsStocks i 
	INNER JOIN #Ktype k on i.KtypeId=k.TypeId
	GROUP BY  PtypeId ,
	          KtypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          Price ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID
END

INSERT INTO dbo.GOODSSTOCKS_QTY
        ( PTypeID ,
          KTypeID ,
          CargoID ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          GOODSCOSTPRICE,
          Qty ,
          NQty,
          LockNumber
        )
SELECT	  PTypeID ,
          KTypeID ,
          CargoID ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          GOODSCOSTPRICE,
          SUM(Qty) ,
          SUM(NQty),
          SUM(ISNULL(LockNumber,0))
FROM dbo.Ini_GOODSSTOCKS_QTY i
INNER JOIN #Ktype k on i.KtypeId=k.TypeId
GROUP BY  PTypeID ,
          KTypeID ,
          CargoID ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate,
          GOODSCOSTPRICE

-- 处理维修品期初的开账
IF EXISTS(SELECT TOP 1 1 FROM wx_iniGoodsStocks)
BEGIN
	INSERT INTO dbo.wx_GoodsStocks
	(		  PTypeId ,
	          KTypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          Qty ,
	          Price ,
	          Total ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          ItemID ,
	          Iscombined ,
	          Nqty
	)
	SELECT	  PTypeId ,
	          KTypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          SUM(Qty) ,
	          0 ,
	          0 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          ItemID ,
	          Iscombined ,
	          SUM(Nqty)
	FROM	wx_iniGoodsStocks a
	INNER JOIN #Ktype K ON A.KTypeId=K.TypeId
	GROUP BY  PTypeId ,
	          KTypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          ItemID ,
	          Iscombined 
END

---代销
INSERT INTO CommissionStock (
	PTypeID,
	BTypeID,
	Type,
	Qty,
	CostTotal,
	Total,
	Explain,
	KTypeID,
	ETypeID,
	STypeID
)
SELECT	a.PTypeID,
		a.BTypeID,
		a.Type,
		SUM(Qty) AS Qty,
		SUM(CostTotal) AS CostTotal,
		SUM(Total) AS Total,
		A = '',
		B = '',
		C = '',
		A.STypeID
FROM	IniCommissionStock a
WHERE	A.STypeId = @STypeId
GROUP BY a.PTypeID, a.BTypeID, a.Type,A.STypeId

INSERT INTO dbo.CommissionStock_Qty
        ( Ptypeid ,
          Btypeid ,
          Stypeid ,
          Type ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          Qty ,
          NQty
        )
SELECT	  Ptypeid ,
          Btypeid ,
          Stypeid ,
          Type ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          SUM(Qty) ,
          SUM(NQty)
FROM	dbo.IniCommissionStock_Qty
WHERE	STypeId = @STypeId
GROUP BY  Ptypeid ,
          Btypeid ,
          Stypeid ,
          Type ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate

-----------------------------序列号开账---------------------------------------------------------
--如果序列号已经开账过去了，则不能再开账了
DECLARE @IniSerialNull	VARCHAR(MAX)
SET @IniSerialNull = ''

SELECT	TOP 1 
		@IniSerialNull = I.Serial
FROM	Gp_InitPTypeSerial I,
		Gp_CruPTypeSerial C,
		#Ktype k
WHERE	I.Serial = C.Serial
		AND (C.[State] IN (1,7,25,32,9,10,11,16,14) OR ISNULL(C.CommissionState,'') = '0')
		AND I.KTypeid = k.TypeId

IF @IniSerialNull <> ''
	BEGIN
		SELECT @ReturnValue='序列号【'+@IniSerialNull+'】在已经开账的序列号库中已经存在，请修改确认后重试！'
		GOTO SerialError		
	END	

--委托序列号仓库是10000，需要单独处理	
SELECT	TOP 1 
		@IniSerialNull = I.Serial
FROM	Gp_InitPTypeSerial I,
		Gp_CruPTypeSerial C
WHERE	I.Serial = C.Serial
		AND I.STypeId = @STypeId
		AND (C.[State] IN (1,7,25,32,9,10,11,16,14) OR ISNULL(C.CommissionState,'') = '0')
		AND I.KTypeid = '10000'		
		

IF @IniSerialNull <> ''
	BEGIN
		SELECT @ReturnValue='序列号【'+@IniSerialNull+'】在已经开账的序列号库中已经存在，请修改确认后重试！'
		GOTO SerialError		
	END	
	
SELECT	TOP 1 
		@IniSerialNull = I.Serial
FROM	dbo.gp_iniFactPtypeSerial I,
		dbo.gp_FactPtypeSerial C,
		#Ktype k
WHERE	I.Serial = C.Serial
		AND I.KTypeid = k.TypeId		

IF @IniSerialNull <> ''
	BEGIN
		SELECT @ReturnValue='实物序列号【'+@IniSerialNull+'】在已经开账的实物序列号库中已经存在，请修改确认后重试！'
		GOTO SerialError		
	END	

DECLARE @PFullName VARCHAR(200)='',
		@SFullName VARCHAR(200)=''

SELECT TOP 1 @PFullName=P.FullName,@SFullName=S.FullName FROM (
	SELECT COUNT(1) AS SerialCount,PTypeID,KtypeID 
	FROM dbo.gp_iniFactPtypeSerial 
	GROUP BY PtypeID,KtypeID
) A,
(
	SELECT ISNULL(SUM(Qty),0) AS Qty,PTypeID,KTypeID 
	FROM dbo.IniFactStocks
	GROUP BY PtypeId,KtypeId
) B,
#Ktype S,
ptype P
WHERE A.ptypeid=B.ptypeid AND ISNULL(A.SerialCount,0)<>ISNULL(B.Qty,0) AND A.KtypeID=B.ktypeid AND A.ptypeid=P.typeId AND A.KtypeID=S.typeId AND p.IfSerial=1

IF ISNULL(@PFullName,'')<>''
BEGIN
	SELECT @ReturnValue='仓库【'+@SFullName+'】商品【'+@PFullName+'】实物序列号数量与实物库存数量不一致，请确认后重试！'
	GOTO SerialError	
END

IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'mnglendserial' AND VALUE = '1')
	BEGIN 
		--以借欠期初为标准
		SET @IniSerialNull = ''
			
		SELECT	TOP 1
				@IniSerialNull = I.Serial
		FROM	gp_initLendPtypeSerial I,
				Gp_CruPTypeSerial C,
				#Ktype k
		WHERE	I.Serial = C.Serial
				AND I.KTypeid = k.TypeId				
				
		IF @IniSerialNull <> ''
			BEGIN
				SELECT @ReturnValue='序列号【'+@IniSerialNull+'】在已经开账的借欠序列号库中已经存在，请修改确认后重试！'
				GOTO SerialError		
			END	
			
		--以库存（代销）期初为标准
		SET @IniSerialNull = ''
			
		SELECT	TOP 1
				@IniSerialNull = I.Serial
		FROM	gp_LendPtypeSerial I,
				gp_initPtypeSerial C,
				#Ktype k
		WHERE	I.Serial = C.Serial
				AND C.KTypeid = k.TypeId			
				
		IF @IniSerialNull <> ''
			BEGIN
				SELECT @ReturnValue='序列号【'+@IniSerialNull+'】在已经开账的借欠序列号库中已经存在，请修改确认后重试！'
				GOTO SerialError		
			END	
	END	

SET @IniSerialNull = ''
	
SELECT	TOP 1
		@IniSerialNull = I.Serial
FROM	gp_initLendPtypeSerial I,
		Gp_LendPTypeSerial C,
		#Ktype k
WHERE	I.Serial = C.Serial
		AND I.KTypeId = k.TypeId		
		
IF @IniSerialNull <> ''
	BEGIN
		SELECT @ReturnValue='序列号【'+@IniSerialNull+'】在已经开账的借欠序列号库中已经存在，请修改确认后重试！'
		GOTO SerialError		
	END	

-- 更新期初序列号表，追加序列号入库时间为：开账时间
INSERT INTO gp_CruPtypeSerial(Serial,KtypeID,PtypeID,BTypeID1,BtypeID2,InKtypeTime,OutKTypeTime,[User],State,Note,Flag,
		CommissionState,ETypeID,LTypeID,iniFlag,CostPrice,GoodsOrder,GoodsNumber,STypeId,Comment1,Comment2,Comment3,
		ItemID,IsCombined,CargoID,ProduceDate,ValidDate )
SELECT	Serial,KtypeID,PtypeID,BTypeID1,BtypeID2,InKtypeTime,OutKTypeTime,[User],State,Note,Flag,
		CommissionState,ETypeID,LTypeID,iniFlag,CostPrice,GoodsOrder,GoodsNumber,STypeId,Comment1,Comment2,Comment3,
		ItemID,IsCombined,CargoID,ProduceDate,ValidDate 
FROM	gp_initptypeserial a
WHERE	Serial NOT IN (SELECT Serial FROM gp_CruPtypeSerial)
		AND a.STypeId=@STypeId 
		AND a.State NOT IN (13)
		

--获取开账日期
DECLARE @okiniStartdate VARCHAR(20),
		@fyear			INT,
		@fperiod		INT

SELECT @fyear = SubValue FROM sysdata WHERE SubName = 'fyear'
SELECT @fperiod = SubValue FROM sysdata WHERE SubName = 'fperiod'

SELECT TOP 1 
		@okiniStartdate = DATEADD(dd,-1,FBegin) 
FROM	dbo.Ac_Period 
where	FYear = @fyear
		and FPeriod = @fperiod

UPDATE	GP_InitPTypeSerial
SET		InKTypeTime =	CASE 
							WHEN ISNULL(InKTypeTime,'') = '' THEN CAST(YEAR(@okiniStartdate) AS VARCHAR) + '-' + CAST(MONTH(@okiniStartdate) AS VARCHAR) + '-' + CAST(DAY(@okiniStartdate) AS VARCHAR)
							ELSE InKtypeTime
						END
WHERE	STypeId=@STypeId

UPDATE	GP_CruPTypeSerial
SET		InKTypeTime =	CASE 
							WHEN ISNULL(InKTypeTime,'') = '' THEN CAST(YEAR(@okiniStartdate) AS VARCHAR) + '-' + CAST(MONTH(@okiniStartdate) AS VARCHAR) + '-' + CAST(DAY(@okiniStartdate) AS VARCHAR)
							ELSE InKtypeTime
						END
WHERE	STypeId=@STypeId

UPDATE	gp_CruPtypeSerial
SET		PTypeId = Ini.ptypeid,
		KTypeId = Ini.ktypeid,
		[State] = Ini.[state],
		BTypeId1 = Ini.BTypeId1,
		BTypeId2 = Ini.BTypeId2,
		STypeId=Ini.STypeID,
		Flag = CASE
					WHEN ini.[state] IN (1,7,25) THEN 1
					ELSE 0
				END,
		CommissionState = CASE
								WHEN ini.[State] IN( 7,9,10,11,14,16,32)  THEN 0
								ELSE NULL
							END,
		ItemID=Ini.ItemID,
		IsCombined=Ini.IsCombined,
		CargoID=Ini.CargoID,
		GoodsNumber=Ini.GoodsNumber,
		ProduceDate=Ini.ProduceDate,
		ValidDate=Ini.ValidDate,
		CostPrice=Ini.CostPrice
FROM	gp_initptypeserial Ini,
		gp_CruPtypeSerial  C
WHERE	INI.Serial = C.serial 
		AND Ini.STypeId=@STypeId

--处理委托期初
SET @IniSerialNull = ''

SELECT	TOP 1 
		@IniSerialNull = I.Serial
FROM	Gp_InitPTypeSerial I,
		Gp_CruPTypeSerial C
WHERE	I.Serial = C.Serial
		AND C.[State] IN (13)
		AND I.STypeId = @STypeId		

IF @IniSerialNull <> ''
	BEGIN
		SELECT @ReturnValue='委托代销序列号【'+@IniSerialNull+'】在已经开账的序列号库中已经存在，请修改确认后重试！'
		GOTO SerialError		
	END	
	
INSERT INTO gp_CruPtypeSerial
(
		Serial ,
		KtypeID ,
		PtypeID ,
		BTypeID1 ,
		BTypeID2 ,
		InKtypeTime ,
		OutKtypeTime ,
		[User] ,
		State ,
		Note ,
		Flag ,
		CommissionState ,
		ETypeID ,
		LTypeID ,
		iniFlag ,
		CostPrice ,
		GoodsOrder ,
		GoodsNumber ,
		STypeId ,
		Comment1 ,
		Comment2 ,
		Comment3,
		ItemID,IsCombined,CargoID,ProduceDate,ValidDate
) 
SELECT	Serial ,
		KtypeID ,
		PtypeID ,
		BTypeID1 ,
		BTypeID2 ,
		InKtypeTime ,
		OutKtypeTime ,
		[User] ,
		State ,
		Note ,
		Flag ,
		CommissionState ,
		ETypeID ,
		LTypeID ,
		iniFlag ,
		CostPrice ,
		GoodsOrder ,
		GoodsNumber ,
		STypeId ,
		Comment1 ,
		Comment2 ,
		Comment3,
		ItemID,IsCombined,CargoID,ProduceDate,ValidDate
FROM	gp_initptypeserial 
WHERE	[State] = 13 
		AND Serial NOT IN (SELECT Serial FROM gp_CruPtypeSerial)
		AND STypeId = @STypeId		
		
UPDATE	gp_CruPtypeSerial
SET		PTypeId = Ini.ptypeid,
		KTypeId = Ini.ktypeid,
		BTypeId1 = Ini.BTypeId1,
		BTypeId2 = Ini.BTypeId2,
		[State] = Ini.[state],
		STypeId = Ini.STypeId,
		Flag = CASE
					WHEN ini.[state] IN (1,7,25) THEN 1
					ELSE 0
				END		
FROM	gp_initptypeserial Ini,
		gp_CruPtypeSerial  C
WHERE	INI.Serial = C.serial 
		AND INI.State = 13
		AND Ini.STypeId = @STypeId		

UPDATE	GP_InitPTypeSerial
SET		InKTypeTime =	CASE
							WHEN ISNULL(InKTypeTime,'') = '' THEN CAST(YEAR(@okiniStartdate) AS VARCHAR) + '-' + CAST(MONTH(@okiniStartdate) AS VARCHAR) + '-' + CAST(DAY(@okiniStartdate) AS VARCHAR)
							ELSE InKtypeTime
						END
WHERE	[State] = 13
		AND STypeId = @STypeId		

UPDATE	GP_CruPTypeSerial
SET		InKTypeTime = CASE
							WHEN ISNULL(InKTypeTime,'') = '' THEN CAST(YEAR(@okiniStartdate) AS VARCHAR) + '-' + CAST(MONTH(@okiniStartdate) AS VARCHAR) + '-' + CAST(DAY(@okiniStartdate) AS VARCHAR)
							ELSE InKtypeTime
					  END
WHERE	[State] = 13
		AND STypeId = @STypeId

--拷贝期初借欠的序列号
INSERT INTO GP_LendPTypeSerial 
SELECT	A.* 
FROM	GP_initLendPTypeSerial  A
	INNER JOIN #Ktype K ON A.KtypeID=K.TypeId

--实物库存序列号
DELETE FROM dbo.gp_FactPtypeSerial WHERE KtypeID IN(SELECT typeid FROM #KType)

--修改入库时间
UPDATE	gp_iniFactPtypeSerial
SET		InKTypeTime =	CASE 
							WHEN ISNULL(InKTypeTime,'') = '' THEN CAST(YEAR(@okiniStartdate) AS VARCHAR) + '-' + CAST(MONTH(@okiniStartdate) AS VARCHAR) + '-' + CAST(DAY(@okiniStartdate) AS VARCHAR)
							ELSE InKtypeTime
						END
WHERE	KtypeID IN(SELECT typeid FROM #KType)

INSERT INTO dbo.gp_FactPtypeSerial
        ( 
		  Serial ,
          KtypeID ,
          PtypeID ,
          InKtypeTime ,
          OutKtypeTime ,
          State ,
          Flag ,
          CommissionState ,
          ETypeID ,
          GoodsOrder ,
          GoodsNumber ,
          STypeId ,
          Comment1 ,
          ItemID ,
          IsCombined ,
          CargoID ,
          ProduceDate ,
          ValidDate ,
          LendState,
          iniFlag
        )
SELECT    Serial ,
          KtypeID ,
          PtypeID ,
          InKtypeTime ,
          OutKtypeTime ,
          State ,
          Flag ,
          CommissionState ,
          ETypeID ,
          GoodsOrder ,
          GoodsNumber ,
          STypeId ,
          Comment1 ,
          ItemID ,
          IsCombined ,
          CargoID ,
          ProduceDate ,
          ValidDate ,
          0,
          1
FROM dbo.gp_iniFactPtypeSerial
WHERE KtypeID IN(SELECT TypeID FROM #KType)	

-- 处理内应收期初 --
	--验证
	--处理
	UPDATE SType_InnerARTotal SET InnerARTotal=InnerARTotal00 WHERE STypeID=@STypeId --当前分支机构的内部应收处理
-- 

/**************************** END *******************************/

UPDATE UserConfig SET Value = '0' WHERE ConfigName = 'AverageCostPrice'	
UPDATE Sysdata SET SubValue = 'F' WHERE SubName = 'inicanmodify'

--系统年结存后，重算草稿库存
exec QP_Recount_DraftQty

--开账时，当系统设置为序列号宽松管理模式时，所有商品的 IfSerial =0 add by chen_qihua 2004-3-18
IF EXISTS(SELECT * FROM userconfig  WHERE ConfigName ='mngSerial' and Value=0)
	BEGIN
		UPDATE ptype SET IfSerial =0
	END

	COMMIT TRAN OkIni
	RETURN 0
	
error: 
	ROLLBACK TRAN OkIniPoint
	COMMIT TRAN OkIni
	RETURN -1
SerialError: 
	ROLLBACK TRAN OkIniPoint
	COMMIT TRAN OkIni
	RETURN -2
DxQtyError: 
	ROLLBACK TRAN OkIniPoint
	COMMIT TRAN OkIni
	RETURN -3
CostQtyError: 
	ROLLBACK TRAN OkIniPoint
	COMMIT TRAN OkIni
	RETURN -8

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-20
	描述：账务期初
	SELECT * FROM Ac_Balance
	DECLARE @rValue VARCHAR(100)
	EXEC Gp_OkIni_Account '00001',@rValue
	PRINT(@rValue)
*/
CREATE PROCEDURE Gp_OkIni_Account
(
	@MxSTypeId	VARCHAR(50),			-- 明细分支机构
	@rValue		VARCHAR(400) OUTPUT		-- 输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--判断分支机构是否开账，如果开账则直接返回
--IF EXISTS(SELECT TOP 1 * FROM SType_UserConfig WHERE StypeId = @MxSTypeId AND Value = 1)
--	RETURN 0

--非独立分支机构直接返回，没有需要处理的数据
IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId = @MxSTypeId AND IsSelfVerify = 0)
	RETURN 0

IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId AND IsUse = 1)
	RETURN 0

--获取会计年度和会计期间
DECLARE @FYear		VARCHAR(10), --财务年度
		@Period	INT,  --业务期间
		@Cid		INT, 
		@FMonth		INT		--财务期间
		
--非独立开帐的情况下，会存在Ac_AccountsPeroid_Stype无该分支机构的信息的情况，所以要处理一下，以便后面使用
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId)
BEGIN	
	SELECT @FYear = SubValue FROM sysdata WHERE SubName = 'FYear'
	SELECT @FMonth = SubValue FROM sysdata WHERE SubName = 'FMonth'
	INSERT Ac_AccountsPeroid_Stype(Stypeid,SFYear,SFPeriod,FYear,FPeriod,IsUse)
	VALUES(@MxSTypeId,@FYear,@FMonth,@FYear,@FMonth,0)
END
	
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId AND SFYear > 0 AND SFPeriod>0 AND FYear>0 AND FPeriod>0)
BEGIN
	SET @rValue = '总账系统未设置启用期间，不能开账，请确认！'
	RETURN -2
END
	
--判断期初数据试算是否平衡
DECLARE @Re INT
EXEC @Re = Web_IsPeriodBalance '00001',@MxSTypeId
IF @Re <> 1
BEGIN
	SET @rValue = '试算不平衡，不能开账，请确认！'
	
	IF @Re <> -1
		SET @rValue = '财务期初数据异常，不能开帐，请检查。'
		
	RETURN -2
END

SELECT @FYear = FYear,@FMonth = FPeriod  FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId
SELECT @Period = MAX(period) FROM MonthProc WHERE STypeID = @MxSTypeId
SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1

IF @Period IS NULL
	SET @Period = 1
	
--判断总账'应收账款','应付账款','预收账款','预付账款' 与 '应收合计','应付合计','预收资金','预付资金'是否相等【总账模式下判断】
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = '1') AND 1 = 0
BEGIN
	DECLARE @Ac_ArTotal00	 NUMERIC(24, 10) ,
			@Ac_ApTotal00	 NUMERIC(24, 10) ,
			@Ac_YsTotal00	 NUMERIC(24, 10) ,
			@Ac_YfTotal00	 NUMERIC(24, 10) ,
			@ArTotal00		 NUMERIC(24, 10) ,
			@ApTotal00		 NUMERIC(24, 10) ,
			@YsTotal00		 NUMERIC(24, 10) ,
			@YfTotal00		 NUMERIC(24, 10) 
			
	SELECT	@Ac_ArTotal00 = ISNULL(SUM(I.iniTotal),0)
	FROM	Ac_IniAccount I
	INNER JOIN Ac_Account A ON I.ATypeId = A.TypeId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '应收账款'	
			AND I.STypeId = @MxSTypeId

	SELECT	@ArTotal00 = ISNULL(SUM(I.Total00),0)
	FROM	AType_Total I
	INNER JOIN Ac_Items A ON I.ATypeId = A.nId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '应收合计'	
			AND I.STypeId = @MxSTypeId

	IF @Ac_ArTotal00 <> @ArTotal00
	BEGIN
		SET @rValue = '应收账款和应收合计金额不平衡，不能开账，请确认！'
		RETURN -2
	END
	
	SELECT	@Ac_ApTotal00 = ISNULL(SUM(I.iniTotal),0)
	FROM	Ac_IniAccount I
	INNER JOIN Ac_Account A ON I.ATypeId = A.TypeId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '应付账款'	
			AND I.STypeId = @MxSTypeId

	SELECT	@ApTotal00 = ISNULL(SUM(I.Total00),0)
	FROM	AType_Total I
	INNER JOIN Ac_Items A ON I.ATypeId = A.nId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '应付合计'	
			AND I.STypeId = @MxSTypeId

	IF @Ac_ApTotal00 <> @ApTotal00
	BEGIN
		SET @rValue = '应付账款和应付合计金额不平衡，不能开账，请确认！'
		RETURN -2
	END	
	
	SELECT	@Ac_YsTotal00 = ISNULL(SUM(I.iniTotal),0)
	FROM	Ac_IniAccount I
	INNER JOIN Ac_Account A ON I.ATypeId = A.TypeId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '预收账款'	
			AND I.STypeId = @MxSTypeId

	SELECT	@YsTotal00 = ISNULL(SUM(I.Total00),0)
	FROM	AType_Total I
	INNER JOIN Ac_Items A ON I.ATypeId = A.nId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '预收资金'	
			AND I.STypeId = @MxSTypeId

	IF @Ac_ApTotal00 <> @ApTotal00
	BEGIN
		SET @rValue = '预收账款和预收资金金额不平衡，不能开账，请确认！'
		RETURN -2
	END	
	
	SELECT	@Ac_YfTotal00 = ISNULL(SUM(I.iniTotal),0)
	FROM	Ac_IniAccount I
	INNER JOIN Ac_Account A ON I.ATypeId = A.TypeId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '预付账款'	
			AND I.STypeId = @MxSTypeId

	SELECT	@YfTotal00 = ISNULL(SUM(I.Total00),0)
	FROM	AType_Total I
	INNER JOIN Ac_Items A ON I.ATypeId = A.nId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '预付资金'	
			AND I.STypeId = @MxSTypeId

	IF @Ac_ApTotal00 <> @ApTotal00
	BEGIN
		SET @rValue = '预付账款和预付资金金额不平衡，不能开账，请确认！'
		RETURN -2
	END		
END

--固定资产的判断
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
BEGIN
	---该分支机构是否已经初始化	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE IfAssetsIni=1 AND TypeId=@MxSTypeId)  --已经初始化 
		BEGIN
			---独立核算机构才会验证数据
			IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE IsSelfVerify=1 AND TypeId=@MxSTypeId)
				BEGIN
					DECLARE @A  NUMERIC(24, 10) --固定资产科目之和
					DECLARE @B  NUMERIC(24, 10) --累计折旧科目之和
					DECLARE @C  NUMERIC(24, 10) --减值准备科目之和
					DECLARE @NetValueTotal  NUMERIC(24, 10)  --净值之和
					
				
					---取出净值之和
					SELECT @NetValueTotal=ISNULL(SUM(ISNULL(NetValue,0)),0)
					FROM dbo.AC_AssetsCards ac
					JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
					WHERE AssetsState=3 AND AssetsState=4
					
					---取出固定资产科目之和
					SELECT @A=ISNULL(SUM(ISNULL(iniTotal,0)),0)
					FROM dbo.Ac_IniAccount ab 
					JOIN (  SELECT DISTINCT ac.AssertATypeId AS typeid    
							FROM AC_AssetsCards ac 
							JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
							WHERE AssetsState=3 AND AssetsState=4
						 ) ac  ON ab.ATypeId=ac.typeid
					 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
					
					---取出累计折旧科目之和
					SELECT @B=ISNULL(SUM(ISNULL(iniTotal,0)),0)
					FROM dbo.Ac_IniAccount ab 
					JOIN (  SELECT DISTINCT ac.DepATypeId AS typeid    
							FROM AC_AssetsCards ac 
							JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
							WHERE AssetsState=3 AND AssetsState=4
						 ) ac  ON ab.ATypeId=ac.typeid
					 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
					
					---取出减值准备科目之和
					SELECT @C=ISNULL(SUM(ISNULL(iniTotal,0)),0)
					FROM dbo.Ac_IniAccount ab 
					JOIN (  SELECT DISTINCT ac.DevalueATypeId AS typeid    
							FROM AC_AssetsCards ac 
							JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId 
							WHERE AssetsState=3 AND AssetsState=4
						 ) ac  ON ab.ATypeId=ac.typeid
					 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
					
					IF @NetValueTotal!=@A-@B-@C 
						BEGIN
							  SET @rValue = @MxSTypeId
							  RETURN -9
						END
				END
			
		END
	ELSE 
		BEGIN
			DECLARE @tempStypeName  NVARCHAR(500) 
			DECLARE @version		INT
			SELECT @version=SubValue FROM dbo.sysdata WHERE SubName='ProInfo' 
			SELECT @tempStypeName = FullName FROM SType WHERE TypeId = @MxSTypeId
			IF EXISTS(SELECT 1 FROM dbo.SType WHERE IsSelfVerify=0 AND TypeId=@MxSTypeId)
			BEGIN
                SELECT  @tempStypeName = A.FullName
                FROM    dbo.SType A
                        INNER JOIN dbo.SType B ON A.TypeId = B.VerifyID
                WHERE   B.TypeId = @MxSTypeId
				SET @rValue = '本机构的记账分支机构【'+@tempStypeName+'】固定资产未初始化，不能开账，请确认！'
				RETURN -2
			END
			
			IF @version=2
				SET @rValue = '分支机构【'+@tempStypeName+'】固定资产未初始化，不能开账，请确认！'
			ELSE 
				SET @rValue = '固定资产未初始化，不能开账，请确认！'
			RETURN -2
		END
	
END
--辅助核算的判断
IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems)
BEGIN
	DECLARE @STypeId	VARCHAR(50),
			@ATypeId	VARCHAR(50),
			@iniTotal	 NUMERIC(24, 10) ,
			@ACid		INT,
			@Ascids		INT,
			@iniMxTotal	 NUMERIC(24, 10) ,
			@ProInfo	INT,
			@SFullName  VARCHAR(1000),
			@AFullName	VARCHAR(1000),
			@CFullName	VARCHAR(1000),
			@Msg		VARCHAR(1000)
			
	SELECT @ProInfo = SubValue FROM sysdata WHERE SubName = 'ProInfo'
			
	DECLARE iniAccount_Assist_Cursor CURSOR FOR		
		SELECT STypeId,ATypeId,Cid,ISNULL(SUM(iniTotal),0) AS iniTotal FROM Ac_IniAccount_Assist_CheckItems WHERE STypeId = @MxSTypeId GROUP BY STypeId,ATypeId,Cid
		
	OPEN iniAccount_Assist_Cursor

	FETCH NEXT FROM iniAccount_Assist_Cursor INTO @STypeId,@ATypeId,@ACid,@iniTotal

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE iniAccount_Assist_Detail_Cursor CURSOR FOR
			SELECT Ascids FROM Ac_Account_Assist_CheckItems WHERE STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = @ACid
			
		OPEN iniAccount_Assist_Detail_Cursor
		
		FETCH NEXT FROM iniAccount_Assist_Detail_Cursor INTO @Ascids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @iniMxTotal = 0
			SELECT @iniMxTotal = ISNULL(SUM(iniTotal),0) FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = @ACid AND Ascids = @Ascids
			IF @iniTotal <> @iniMxTotal
			BEGIN
				SET @Msg = ''
				SELECT @SFullName = FullName FROM SType WHERE TypeId = @STypeId
				SELECT @AFullName = FullName FROM Ac_Account WHERE TypeId = @ATypeId
				SELECT @CFullName = FullName FROM Ac_Currency WHERE CId = @ACid
				IF @ProInfo = 2
				BEGIN
					SET @Msg = '分支机构【'+@SFullName+'】对应的会计科目【'+@AFullName+'】在币别【'+@CFullName+'】下的辅助核算数据不正确，请确认！'
				END
				ELSE
				BEGIN
					SET @Msg = '会计科目【'+@AFullName+'】在币别【'+@CFullName+'】下的辅助核算数据不正确，请确认！'
				END
				SET @rValue = @Msg
				RETURN -2
			END
			FETCH NEXT FROM iniAccount_Assist_Detail_Cursor INTO @Ascids
		END
		
		CLOSE iniAccount_Assist_Detail_Cursor
		DEALLOCATE iniAccount_Assist_Detail_Cursor
		
		FETCH NEXT FROM iniAccount_Assist_Cursor INTO @STypeId,@ATypeId,@ACid,@iniTotal
	END

	CLOSE iniAccount_Assist_Cursor
	DEALLOCATE iniAccount_Assist_Cursor
END


DECLARE @nRe INT
/*,
		@intPeriod INT,
		@intFMonth	INT
		
SET @intPeriod = @Period
SET @intFMonth = @FMonth
*/
EXEC @nRe = Gp_OkIni_Account_Normal @MxSTypeId,@FYear,@FMonth,@rValue OUTPUT
IF @nRe <> 0
BEGIN
	RAISERROR(@rValue,16,1)
	RETURN @nRe
END

/*   --总账开帐与业务无关
--第一个会计期间开账
IF @Period = @FMonth
BEGIN
	EXEC @nRe = Gp_OkIni_Account_Normal @MxSTypeId,@FYear,@FMonth,@rValue OUTPUT
	IF @nRe <> 0
	BEGIN
		RAISERROR(@rValue,16,1)
		RETURN @nRe
	END
END
ELSE IF @intPeriod > @intFMonth	--多分支机构分开开账
BEGIN
	EXEC @nRe = Gp_OkIni_Account_Normal @MxSTypeId,@FYear,@FMonth,@rValue OUTPUT
	IF @nRe <> 0
	BEGIN
		RAISERROR(@rValue,16,1)
		RETURN @nRe
	END
	
	WHILE @intFMonth < @intPeriod
	BEGIN
		EXEC @nRe = Gp_OkIni_Account_Repeat @MxSTypeId,@FYear,@intFMonth,@rValue OUTPUT
		IF @nRe <> 0
		BEGIN
			RAISERROR(@rValue,16,1)
			RETURN @nRe
		END
		
		SET @intFMonth = @intFMonth + 1
	END
END
*/
--写入期间
--IF @FPeriod < @FMonth
--BEGIN
--	UPDATE	sysdata
--	SET		SubValue = @FMonth
--	WHERE	SubName = 'FPeriod'

--	IF @@ERROR <> 0
--	BEGIN
--		SET @rValue = @@ERROR
--		RETURN -2
--	END
--END

----add  by dongzhan,不把非独立核算的机构写入
--IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId=@MxSTypeId AND IsSelfVerify=1)
--	BEGIN
--	update dbo.Ac_AccountsPeroid_Stype set FYear=@FYear, FPeriod=@FMonth,SFYear=@SFYear,SFPeriod=@SFMonth where Stypeid=@MxSTypeId
--	END
--	ELSE
--	BEGIN
--	INSERT INTO dbo.Ac_AccountsPeroid_Stype(Stypeid,FYear,FPeriod,SFYear,SFPeriod)SELECT @MxSTypeId,@FYear,@FMonth,@SFYear,@SFMonth
--	END
--IF @@ERROR <> 0
--	BEGIN
--		SET @rValue = @@ERROR
--		RETURN -2
--	END
	
--清除ac_iniAccount表中科目异常数据
DELETE I 
FROM	Ac_IniAccount I
WHERE	I.STypeId = @STypeId AND I.ATypeId NOT IN (SELECT A.TYPEID FROM Ac_Account A WHERE A.StypeId = @STypeId)

--总账系统检查无误后，更新Ac_AccountsPeroid_Stype表中的开帐标识
UPDATE Ac_AccountsPeroid_Stype SET IsUse = '1' WHERE STypeID = @MxSTypeId

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-11-06
	描述：账务期初的年中开账
*/
CREATE PROCEDURE Gp_OkIni_Account_MYear
(
	@MxSTypeId	VARCHAR(50),			-- 明细分支机构
	@rValue		VARCHAR(400) OUTPUT		-- 输出信息
)
--@encode$--
AS
SET NOCOUNT ON

	
--判断期初数据试算是否平衡
DECLARE @Re INT
EXEC @Re = Web_IsPeriodBalance '00001',@MxSTypeId
IF @Re <> 1
BEGIN
	SET @rValue = '试算不平衡，不能开账，请确认！'
	RETURN -2
END

--获取会计年度和会计期间
DECLARE @FYear		VARCHAR(10),
		@FPeriod	INT,
		@Cid		INT,
		@FMonth		INT
		
SELECT @FYear = SubValue FROM sysdata WHERE SubName = 'FYear'
SELECT @FMonth = SubValue FROM sysdata WHERE SubName = 'FMonth'
SELECT @FPeriod = SubValue FROM sysdata WHERE SubName = 'FPeriod'
SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1

IF @FPeriod IS NULL
	SET @FPeriod = 1
	
--判断总账'应收账款','应付账款','预收账款','预付账款' 与 '应收合计','应付合计','预收资金','预付资金'是否相等【总账模式下判断】
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = '1') AND 1 = 0
BEGIN
	DECLARE @Ac_ArTotal00	 NUMERIC(24, 10) ,
			@Ac_ApTotal00	 NUMERIC(24, 10) ,
			@Ac_YsTotal00	 NUMERIC(24, 10) ,
			@Ac_YfTotal00	 NUMERIC(24, 10) ,
			@ArTotal00		 NUMERIC(24, 10) ,
			@ApTotal00		 NUMERIC(24, 10) ,
			@YsTotal00		 NUMERIC(24, 10) ,
			@YfTotal00		 NUMERIC(24, 10) 
			
	SELECT	@Ac_ArTotal00 = ISNULL(SUM(I.iniTotal),0)
	FROM	Ac_IniAccount I
	INNER JOIN Ac_Account A ON I.ATypeId = A.TypeId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '应收账款'	
			AND I.STypeId = @MxSTypeId

	SELECT	@ArTotal00 = ISNULL(SUM(I.Total00),0)
	FROM	AType_Total I
	INNER JOIN Ac_Items A ON I.ATypeId = A.nId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '应收合计'	
			AND I.STypeId = @MxSTypeId

	IF @Ac_ArTotal00 <> @ArTotal00
	BEGIN
		SET @rValue = '应收账款和应收合计金额不平衡，不能开账，请确认！'
		RETURN -2
	END
	
	SELECT	@Ac_ApTotal00 = ISNULL(SUM(I.iniTotal),0)
	FROM	Ac_IniAccount I
	INNER JOIN Ac_Account A ON I.ATypeId = A.TypeId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '应付账款'	
			AND I.STypeId = @MxSTypeId

	SELECT	@ApTotal00 = ISNULL(SUM(I.Total00),0)
	FROM	AType_Total I
	INNER JOIN Ac_Items A ON I.ATypeId = A.nId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '应付合计'	
			AND I.STypeId = @MxSTypeId

	IF @Ac_ApTotal00 <> @ApTotal00
	BEGIN
		SET @rValue = '应付账款和应付合计金额不平衡，不能开账，请确认！'
		RETURN -2
	END	
	
	SELECT	@Ac_YsTotal00 = ISNULL(SUM(I.iniTotal),0)
	FROM	Ac_IniAccount I
	INNER JOIN Ac_Account A ON I.ATypeId = A.TypeId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '预收账款'	
			AND I.STypeId = @MxSTypeId

	SELECT	@YsTotal00 = ISNULL(SUM(I.Total00),0)
	FROM	AType_Total I
	INNER JOIN Ac_Items A ON I.ATypeId = A.nId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '预收资金'	
			AND I.STypeId = @MxSTypeId

	IF @Ac_ApTotal00 <> @ApTotal00
	BEGIN
		SET @rValue = '预收账款和预收资金金额不平衡，不能开账，请确认！'
		RETURN -2
	END	
	
	SELECT	@Ac_YfTotal00 = ISNULL(SUM(I.iniTotal),0)
	FROM	Ac_IniAccount I
	INNER JOIN Ac_Account A ON I.ATypeId = A.TypeId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '预付账款'	
			AND I.STypeId = @MxSTypeId

	SELECT	@YfTotal00 = ISNULL(SUM(I.Total00),0)
	FROM	AType_Total I
	INNER JOIN Ac_Items A ON I.ATypeId = A.nId AND I.STypeId = I.STypeId	
	WHERE	A.FullName = '预付资金'	
			AND I.STypeId = @MxSTypeId

	IF @Ac_ApTotal00 <> @ApTotal00
	BEGIN
		SET @rValue = '预付账款和预付资金金额不平衡，不能开账，请确认！'
		RETURN -2
	END		
END

--辅助核算的判断
IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems)
BEGIN
	DECLARE @STypeId	VARCHAR(50),
			@ATypeId	VARCHAR(50),
			@iniTotal	 NUMERIC(24, 10) ,
			@ACid		INT,
			@Ascids		INT,
			@iniMxTotal	 NUMERIC(24, 10) ,
			@ProInfo	INT,
			@SFullName  VARCHAR(1000),
			@AFullName	VARCHAR(1000),
			@CFullName	VARCHAR(1000),
			@Msg		VARCHAR(1000)
			
	SELECT @ProInfo = SubValue FROM sysdata WHERE SubName = 'ProInfo'
			
	DECLARE iniAccount_Assist_Cursor CURSOR FOR		
		SELECT STypeId,ATypeId,Cid,ISNULL(SUM(iniTotal),0) AS iniTotal FROM Ac_IniAccount_Assist_CheckItems GROUP BY STypeId,ATypeId,Cid
		
	OPEN iniAccount_Assist_Cursor

	FETCH NEXT FROM iniAccount_Assist_Cursor INTO @STypeId,@ATypeId,@ACid,@iniTotal

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE iniAccount_Assist_Detail_Cursor CURSOR FOR
			SELECT Ascids FROM Ac_Account_Assist_CheckItems WHERE STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = @ACid
			
		OPEN iniAccount_Assist_Detail_Cursor
		
		FETCH NEXT FROM iniAccount_Assist_Detail_Cursor INTO @Ascids
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @iniMxTotal = 0
			SELECT @iniMxTotal = ISNULL(SUM(iniTotal),0) FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = @ACid AND Ascids = @Ascids
			IF @iniTotal <> @iniMxTotal
			BEGIN
				SET @Msg = ''
				SELECT @SFullName = FullName FROM SType WHERE TypeId = @STypeId
				SELECT @AFullName = FullName FROM Ac_Account WHERE TypeId = @ATypeId
				SELECT @CFullName = FullName FROM Ac_Currency WHERE CId = @ACid
				IF @ProInfo = 2
				BEGIN
					SET @Msg = '分支机构【'+@SFullName+'】对应的会计科目【'+@AFullName+'】在币别【'+@CFullName+'】下的辅助核算数据不正确，请确认！'
				END
				ELSE
				BEGIN
					SET @Msg = '会计科目【'+@AFullName+'】在币别【'+@CFullName+'】下的辅助核算数据不正确，请确认！'
				END
				SET @rValue = @Msg
				RETURN -2
			END
			FETCH NEXT FROM iniAccount_Assist_Detail_Cursor INTO @Ascids
		END
		
		CLOSE iniAccount_Assist_Detail_Cursor
		DEALLOCATE iniAccount_Assist_Detail_Cursor
		
		FETCH NEXT FROM iniAccount_Assist_Cursor INTO @STypeId,@ATypeId,@ACid,@iniTotal
	END

	CLOSE iniAccount_Assist_Cursor
	DEALLOCATE iniAccount_Assist_Cursor
END

DECLARE @nRe INT,
		@intFPeriod INT,
		@intFMonth	INT
		
SET @intFPeriod = @FPeriod
SET @intFMonth = @FMonth

--第一个会计期间开账
IF @FPeriod = @FMonth
BEGIN
	EXEC @nRe = Gp_OkIni_Account_Normal @MxSTypeId,@FYear,@FPeriod,@rValue OUTPUT
	IF @nRe <> 0
	BEGIN
		RAISERROR(@rValue,16,1)
		RETURN @nRe
	END
END
ELSE IF @intFPeriod > @intFMonth	--多分支机构分开开账
BEGIN
	EXEC @nRe = Gp_OkIni_Account_Normal @MxSTypeId,@FYear,@FMonth,@rValue OUTPUT
	IF @nRe <> 0
	BEGIN
		RAISERROR(@rValue,16,1)
		RETURN @nRe
	END
	
	WHILE @intFMonth < @intFPeriod
	BEGIN
		EXEC @nRe = Gp_OkIni_Account_Repeat @MxSTypeId,@FYear,@intFMonth,@rValue OUTPUT
		IF @nRe <> 0
		BEGIN
			RAISERROR(@rValue,16,1)
			RETURN @nRe
		END
		
		SET @intFMonth = @intFMonth + 1
	END
END

--写入期间
IF @FPeriod < @FMonth
BEGIN
	UPDATE	sysdata
	SET		SubValue = @FMonth
	WHERE	SubName = 'FPeriod'

	IF @@ERROR <> 0
	BEGIN
		SET @rValue = @@ERROR
		RETURN -2
	END
END

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-12-12
	描述：正常开账
*/
CREATE PROCEDURE Gp_OkIni_Account_Normal
(
	@MxSTypeId	VARCHAR(50),			-- 明细分支机构
	@FYear		VARCHAR(20),			-- 会计年度
	@FPeriod	VARCHAR(10),			-- 会计期间
	@rValue		VARCHAR(400) OUTPUT		-- 输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--先清除科目余额表数据
DELETE FROM Ac_Balance WHERE STypeId = @MxSTypeId

--先清除科目余额表辅助核算数据
DELETE FROM Ac_Balance_Assist_CheckItems WHERE STypeId = @MxSTypeId

--先清除科目余额表辅助核算明细数据
DELETE FROM Ac_Balance_Assist_CheckItems_Detail WHERE STypeId = @MxSTypeId

--写入本币科目余额表
INSERT INTO Ac_Balance 
(
	STypeId, 
	ATypeId, 
	FBeginBalance, 
	FBeginBalanceFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	Cid, 
	FEndBalance, 
	FEndBalanceFor, 
	FYtdDebit, 
	FYtdDebitFor, 
	FYtdCredit, 
	FYtdCreditFor, 
	FYear, 
	FPeriod
	,FBeginqty
	,FDebitqty
	,FCreditqty
	,FEndqty
	,FYtdDebitqty
	,FYtdCreditqty
)
SELECT	STypeId, 
		ATypeId, 
		ISNULL(SUM(iniTotal),0) AS FBeginBalance, 
		ISNULL(SUM(iniTotalFor),0) AS FBeginBalanceFor, 
		0, 
		0, 
		0, 
		0, 
		Cid,		 		
		ISNULL(SUM(iniTotal),0) AS FEndBalance,
		ISNULL(SUM(iniTotalFor),0) AS FEndBalanceFor,
		ISNULL(SUM(FDebit),0) AS FYtdDebit, 
		ISNULL(SUM(FDebitFor),0) AS FYtdDebitFor, 
		ISNULL(SUM(FCredit),0) AS FYtdCredit, 
		ISNULL(SUM(FCreditFor),0) AS FYtdCreditFor, 
		@FYear,
		@FPeriod
		,ISNULL(SUM(iniqty),0)
		,0
		,0
		,ISNULL(SUM(iniqty),0)
		,ISNULL(SUM(FDebitqty),0)
		,ISNULL(SUM(FCreditqty),0)
FROM	Ac_IniAccount
WHERE	STypeId = @MxSTypeId
GROUP BY STypeId,
		 ATypeId,
		 Cid

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END

--写入综合本位币科目余额表
INSERT INTO Ac_Balance 
(
	STypeId, 
	ATypeId, 
	FBeginBalance, 
	FBeginBalanceFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	Cid, 
	FEndBalance, 
	FEndBalanceFor, 
	FYtdDebit, 
	FYtdDebitFor, 
	FYtdCredit, 
	FYtdCreditFor, 
	FYear, 
	FPeriod
	,FBeginqty
	,FDebitqty
	,FCreditqty
	,FEndqty
	,FYtdDebitqty
	,FYtdCreditqty
)
SELECT	STypeId, 
		ATypeId, 
		ISNULL(SUM(iniTotal),0) AS iniTotal, 
		ISNULL(SUM(iniTotal),0) AS iniTotalFor, 
		0, 
		0, 
		0, 
		0, 
		0 AS Cid,		 		
		ISNULL(SUM(iniTotal),0) AS FEndBalance, 
		ISNULL(SUM(iniTotal),0) AS FEndBalanceFor,
		ISNULL(SUM(FDebit),0) AS FYtdDebit, 
		ISNULL(SUM(FDebit),0) AS FYtdDebitFor, 
		ISNULL(SUM(FCredit),0) AS FYtdCredit, 
		ISNULL(SUM(FCredit),0) AS FYtdCreditFor, 
		@FYear,
		@FPeriod
		,ISNULL(SUM(iniqty),0)
		,0
		,0
		,ISNULL(SUM(iniqty),0)
		,ISNULL(SUM(FDebitqty),0)
		,ISNULL(SUM(FCreditqty),0)
FROM	Ac_IniAccount
WHERE	STypeId = @MxSTypeId
GROUP BY STypeId, 
		 ATypeId

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END

--写入本币辅助核算信息
INSERT INTO Ac_Balance_Assist_CheckItems
(
	STypeId, 
	ATypeId, 
	Cid, 	
	IniYTotal, 
	IniYTotalFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	IniTotal, 
	IniTotalFor, 
	FEndBalance,
	FEndBalanceFor,
	FYear,
	FPeriod
	,IniYqty
	,FDebitqty
	,FCreditqty
	,Iniqty
	,FEndqty
)
SELECT	STypeId, 
		ATypeId, 
		Cid,  
		ISNULL(SUM(IniYTotal),0) AS IniYTotal, 
		ISNULL(SUM(IniYTotalFor),0) AS IniYTotalFor, 
		0 AS FDebit, 
		0 AS FDebitFor, 
		0 AS FCredit, 
		0 AS FCreditFor, 
		ISNULL(SUM(IniTotal),0) AS IniTotal, 
		ISNULL(SUM(IniTotalFor),0) AS IniTotalFor, 
		ISNULL(SUM(IniTotal),0) AS FEndBalance, 
		ISNULL(SUM(IniTotalFor),0) AS FEndBalanceFor,
		@FYear,
		@FPeriod
		,ISNULL(SUM(IniYqty),0)
		,0
		,0
		,ISNULL(SUM(Iniqty),0)
		,ISNULL(SUM(Iniqty),0)
FROM	Ac_IniAccount_Assist_CheckItems
WHERE	STypeId = @MxSTypeId
GROUP BY STypeId,
		 ATypeId,
		 Cid

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END

--计算综合本位币数据
INSERT INTO Ac_Balance_Assist_CheckItems
(
	STypeId, 
	ATypeId, 
	Cid, 	
	IniYTotal, 
	IniYTotalFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	IniTotal, 
	IniTotalFor, 
	FEndBalance,
	FEndBalanceFor,
	FYear,
	FPeriod
	,IniYqty
	,FDebitqty
	,FCreditqty
	,Iniqty
	,FEndqty
)
SELECT	STypeId, 
		ATypeId, 
		0 AS Cid,  
		ISNULL(SUM(IniYTotal),0) AS IniYTotal, 
		ISNULL(SUM(IniYTotal),0) AS IniYTotalFor, 
		0 AS FDebit, 
		0 AS FDebitFor, 
		0 AS FCredit, 
		0 AS FCreditFor, 
		ISNULL(SUM(IniTotal),0) AS IniTotal, 
		ISNULL(SUM(IniTotal),0) AS IniTotalFor, 
		ISNULL(SUM(IniTotal),0) AS FEndBalance, 
		ISNULL(SUM(IniTotal),0) AS FEndBalanceFor,
		@FYear,
		@FPeriod
		,ISNULL(SUM(IniYqty),0)
		,0
		,0
		,ISNULL(SUM(Iniqty),0)
		,ISNULL(SUM(Iniqty),0)
FROM	Ac_IniAccount_Assist_CheckItems
WHERE	STypeId = @MxSTypeId
GROUP BY STypeId, 
		 ATypeId

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END

--写辅助核算的具体信息
INSERT INTO Ac_Balance_Assist_CheckItems_Detail
(
	STypeId, 
	ATypeId, 
	Cid, 
	Ascids, 
	FieldValue, 
	FYear, 
	FPeriod,
	IniTotal,
	IniTotalFor,
	FEndBalance,
	FEndBalanceFor
	,Iniqty
	,FEndqty
)
SELECT	STypeId,
		ATypeId,
		Cid,
		Ascids,
		FieldValue,
		@FYear AS FYear,
		@FPeriod AS FPeriod,
		ISNULL(SUM(IniTotal),0) AS IniTotal,
		ISNULL(SUM(IniTotalFor),0) AS IniTotalFor,
		ISNULL(SUM(IniTotal),0) AS FEndBalance,
		ISNULL(SUM(IniTotalFor),0) AS FEndBalanceFor
		,ISNULL(SUM(iniqty),0) 
		,ISNULL(SUM(iniqty),0) 
FROM	Ac_IniAccount_Assist_CheckItems_Detail
WHERE	STypeId = @MxSTypeId
GROUP BY STypeId,
		 ATypeId,
		 Cid,
		 Ascids,
		 FieldValue

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END

--写辅助核算的具体综合本位币信息
INSERT INTO Ac_Balance_Assist_CheckItems_Detail
(
	STypeId, 
	ATypeId, 
	Cid, 
	Ascids, 
	FieldValue, 
	FYear, 
	FPeriod,
	IniTotal,
	IniTotalFor,
	FEndBalance,
	FEndBalanceFor
	,Iniqty
	,FEndqty
)
SELECT	STypeId,
		ATypeId,
		0 AS Cid,
		Ascids,
		FieldValue,
		@FYear AS FYear,
		@FPeriod AS FPeriod,
		ISNULL(SUM(IniTotal),0) AS IniTotal,
		ISNULL(SUM(IniTotal),0) AS IniTotalFor,
		ISNULL(SUM(IniTotal),0) AS FEndBalance,
		ISNULL(SUM(IniTotal),0) AS FEndBalanceFor
		,ISNULL(SUM(iniqty),0) 
		,ISNULL(SUM(iniqty),0) 
FROM	Ac_IniAccount_Assist_CheckItems_Detail
WHERE	STypeId = @MxSTypeId
GROUP BY STypeId,
		 ATypeId,
		 Ascids,
		 FieldValue

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END

/*暂时查出来没有地方在使用该表里的数据，所以屏蔽了看看
--损益类可以写入损益类科目实际发生额表
INSERT INTO Ac_ProfitAndLoss 
(
	STypeId, 
	ATypeId, 
	Cid, 
	FFTotal, 
	FFTotalFor, 
	FYTotal, 
	FYTotalFor, 
	FYear, 
	FPeriod
)
SELECT  C.STypeId,
		C.ATypeId,
		C.Cid,
		0 AS FFTotal,
		0 AS FFTotalFor,
		ISNULL(SUM(C.FYTotal),0) AS FYTotal,
		ISNULL(SUM(C.FYTotalFor),0) AS FYTotalFor,
		@FYear AS FYear,
		@FPeriod AS FPeriod
FROM	Ac_Account A
INNER JOIN Ac_IniAccount_Assist_CheckItems C ON A.TypeId = C.ATypeId AND A.StypeId = C.STypeId
WHERE	A.StypeId = @MxSTypeId
		AND A.[GROUP] > 500 
		AND A.[GROUP] < 600
GROUP BY C.STypeId,
		 C.ATypeId,
		 C.Cid
		 
IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END	

--损益类可以写入损益类科目实际发生额表综合本位币
INSERT INTO Ac_ProfitAndLoss 
(
	STypeId, 
	ATypeId, 
	Cid, 
	FFTotal, 
	FFTotalFor, 
	FYTotal, 
	FYTotalFor, 
	FYear, 
	FPeriod
)
SELECT  C.STypeId,
		C.ATypeId,
		0 AS Cid,
		0 AS FFTotal,
		0 AS FFTotalFor,
		ISNULL(SUM(C.FYTotal),0) AS FYTotal,
		ISNULL(SUM(C.FYTotal),0) AS FYTotalFor,
		@FYear AS FYear,
		@FPeriod AS FPeriod
FROM	Ac_Account A
INNER JOIN Ac_IniAccount_Assist_CheckItems C ON A.TypeId = C.ATypeId AND A.StypeId = C.STypeId
WHERE	A.StypeId = @MxSTypeId
		AND A.[GROUP] > 500 
		AND A.[GROUP] < 600
GROUP BY C.STypeId,
		 C.ATypeId
		 
IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END	 

--损益类可以写入损益类科目实际发生额辅助核算表
INSERT INTO Ac_ProfitAndLoss_Detail 
(
	STypeId, 
	ATypeId, 
	Cid, 
	Ascids, 
	FieldValue, 
	FFTotal, 
	FFTotalFor, 
	FYTotal, 
	FYTotalFor, 
	FYear, 
	FPeriod
)		
SELECT  C.STypeId,
		C.ATypeId,
		C.Cid,
		C.Ascids,
		C.FieldValue,		
		0 AS FFTotal,
		0 AS FFTotalFor,
		ISNULL(SUM(C.FYTotal),0) AS FYTotal,
		ISNULL(SUM(C.FYTotalFor),0) AS FYTotalFor,
		@FYear AS FYear,
		@FPeriod AS FPeriod
FROM	Ac_Account A
INNER JOIN Ac_IniAccount_Assist_CheckItems_Detail C ON A.TypeId = C.ATypeId AND A.StypeId = C.STypeId
WHERE	A.StypeId = @MxSTypeId
		AND A.[GROUP] > 500 
		AND A.[GROUP] < 600
GROUP BY C.STypeId,
		 C.ATypeId,
		 C.Cid,
		 C.Ascids,
		 C.FieldValue
		 
IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END	

--损益类可以写入损益类科目实际发生额辅助核算表综合本位币
INSERT INTO Ac_ProfitAndLoss_Detail 
(
	STypeId, 
	ATypeId, 
	Cid, 
	Ascids, 
	FieldValue, 
	FFTotal, 
	FFTotalFor, 
	FYTotal, 
	FYTotalFor, 
	FYear, 
	FPeriod
)
SELECT  C.STypeId,
		C.ATypeId,
		0 AS Cid,
		C.Ascids,
		C.FieldValue,
		0 AS FFTotal,
		0 AS FFTotalFor,
		ISNULL(SUM(C.FYTotal),0) AS FYTotal,
		ISNULL(SUM(C.FYTotal),0) AS FYTotalFor,
		@FYear AS FYear,
		@FPeriod AS FPeriod
FROM	Ac_Account A
INNER JOIN Ac_IniAccount_Assist_CheckItems_Detail C ON A.TypeId = C.ATypeId AND A.StypeId = C.STypeId
WHERE	A.StypeId = @MxSTypeId
		AND A.[GROUP] > 500 
		AND A.[GROUP] < 600
GROUP BY C.STypeId,
		 C.ATypeId,
		 C.Ascids,
		 C.FieldValue
		 
IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -2
END
*/
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-12-12
	描述：当前期间大于启用期间的开账
*/
CREATE PROCEDURE Gp_OkIni_Account_Repeat
(
	@MxSTypeId	VARCHAR(50),			-- 明细分支机构
	@FYear		VARCHAR(20),			-- 会计年度
	@FPeriod	VARCHAR(10),			-- 会计期间	
	@rValue		VARCHAR(400) OUTPUT		-- 输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--将本期的科目余额写入下期的期初
INSERT INTO Ac_Balance
(
	STypeId,
	ATypeId,
	FBeginBalance,
	FBeginBalanceFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	Cid,	
	FEndBalance,
	FEndBalanceFor,
	FYtdDebit,
	FYtdDebitFor,
	FYtdCredit,
	FYtdCreditFor,
	FYear,
	FPeriod
)
SELECT	STypeId,
		ATypeId,
		FEndBalance AS FBeginBalance,
		FEndBalanceFor AS FBeginBalanceFor,
		0 AS FDebit,
		0 AS FDebitFor,
		0 AS FCredit,
		0 AS FCreditFor,
		Cid,
		FEndBalance,
		FEndBalanceFor,
		FYtdDebit,
		FYtdDebitFor,
		FYtdCredit,
		FYtdCreditFor,
		@FYear AS FYear,
		@FPeriod + 1 AS FPeriod
FROM	Ac_Balance
WHERE	FPeriod = @FPeriod
		AND FYear = @FYear
		AND STypeId = @MxSTypeId

IF @@ERROR <> 0
BEGIN
	RAISERROR('处理科目余额表错误，请确认！',16,1)
	RETURN -1		
END

--写入辅助核算余额表
INSERT INTO Ac_Balance_Assist_CheckItems 
(
	STypeId, 
	ATypeId, 
	Cid, 
	IniYTotal, 
	IniYTotalFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	IniTotal, 
	IniTotalFor, 
	FYear, 
	FPeriod, 
	FEndBalance, 
	FEndBalanceFor
)
SELECT	STypeId, 
		ATypeId, 
		Cid, 
		IniYTotal, 
		IniYTotalFor, 
		0 AS FDebit, 
		0 AS FDebitFor, 
		0 AS FCredit, 
		0 AS FCreditFor, 
		FEndBalance AS IniTotal, 
		FEndBalanceFor AS IniTotalFor, 
		@FYear AS FYear, 
		@FPeriod + 1 AS FPeriod, 
		FEndBalance, 
		FEndBalanceFor
FROM	Ac_Balance_Assist_CheckItems
WHERE	FYear = @FYear
		AND FPeriod = @FPeriod	
		AND STypeId = @MxSTypeId
		
IF @@ERROR <> 0
BEGIN
	RAISERROR('处理科目余额辅助核算表错误，请确认！',16,1)
	RETURN -1		
END				

--写入辅助核算余额表明细
INSERT INTO Ac_Balance_Assist_CheckItems_Detail 
(
	STypeId, 
	ATypeId, 
	Cid, 
	Ascids, 
	FieldValue, 
	FYear, 
	FPeriod,
	IniTotal,
	IniTotalFor,
	FEndBalance,
	FEndBalanceFor
)
SELECT 	STypeId, 
		ATypeId, 
		Cid, 
		Ascids, 
		FieldValue, 
		@FYear AS FYear, 
		@FPeriod + 1 AS FPeriod,
		FEndBalance AS IniTotal,
		FEndBalanceFor AS IniTotalFor,
		FEndBalance,
		FEndBalanceFor
FROM	Ac_Balance_Assist_CheckItems_Detail
WHERE	FYear = @FYear
		AND FPeriod = @FPeriod
		AND STypeId = @MxSTypeId

IF @@ERROR <> 0
BEGIN
	RAISERROR('处理科目余额辅助核算明细表错误，请确认！',16,1)
	RETURN -1		
END	

--处理损益表
--SELECT * FROM Ac_ProfitAndLoss_Detail
/*
INSERT INTO Ac_ProfitAndLoss 
(
	STypeId, 
	ATypeId, 
	Cid, 
	FFTotal, 
	FFTotalFor, 
	FYTotal, 
	FYTotalFor, 
	FYear, 
	FPeriod
)
SELECT	STypeId, 
		ATypeId, 
		Cid, 
		0 AS FFTotal, 
		0 AS FFTotalFor, 
		FYTotal, 
		FYTotalFor, 
		@FYear AS FYear, 
		@FPeriod + 1 AS FPeriod
FROM	Ac_ProfitAndLoss
WHERE	FYear = @FYear
		AND FPeriod = @FPeriod	
		AND STypeId = @MxSTypeId
		
--处理损益明细表
INSERT INTO Ac_ProfitAndLoss_Detail 
(
	STypeId, 
	ATypeId, 
	Cid, 
	Ascids, 
	FieldValue, 
	FFTotal, 
	FFTotalFor, 
	FYTotal, 
	FYTotalFor, 
	FYear, 
	FPeriod
)	
SELECT	STypeId, 
		ATypeId, 
		Cid, 
		Ascids, 
		FieldValue, 
		0 AS FFTotal, 
		0 AS FFTotalFor, 
		FYTotal, 
		FYTotalFor, 
		@FYear AS FYear, 
		@FPeriod + 1 AS FPeriod
FROM	Ac_ProfitAndLoss_Detail
WHERE	FYear = @FYear
		AND FPeriod = @FPeriod
		AND STypeId = @MxSTypeId
*/

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	修改作者：谢吉康
	修改日期：2010-04-11
	修改描述：开账时对于没有仓库的分支机构的处理
*/
CREATE      PROCEDURE Gp_OkIni_ArApTotalNoStock
(
	@STypeId		VARCHAR(MAX),		--	分支机构信息
    @ReturnValue	VARCHAR(3000) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

--判断是否已经开账
IF EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeID = @STypeId AND Value = '1' AND ConfigNo = '1')
	RETURN 0
	
DECLARE	@IfMustSerial	BIT,			--是否序列号全局强制管理（是则检查匹配；否则不检查）	
		@IfSType		INT,			--是否启用分支机构
		@StypeFullName	VARCHAR(MAX)	--分支机构名称
		
SELECT @StypeFullName = FullName FROM SType WHERE TypeId = @STypeId		

/*
SysData表中的IfQP为1，代表为汽配版

SysData表中的QPEdition值，代表意义如下
1 - 管家婆汽配汽修普及版
2 - 管家婆汽配汽修2s
3 - 管家婆美容快修版

在数据库SysData和SysData1中追加ProInfo记录，以示区分各产品的标识
ProInfo
1 - V3
2 - A8
3 - 汽配
*/

SET @IfSType = 0

--汽配3S、4S才会有分支机构
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IfQP' AND SubValue = '1') AND EXISTS (SELECT TOP 1 1 FROM sysdata WHERE SubName = 'QPEdition' AND (SubValue = '4' OR SubValue = '5'))
	SET @IfSType = 1

--A8有分支机构	
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
	SET @IfSType = 1
	
IF @IfSType = 1
	SET @StypeFullName = '分支机构【'+@StypeFullName+'】中的'
ELSE
	SET @StypeFullName = ''	

SELECT @IfMustSerial=Value FROM UserConfig WHERE ConfigName='mngSerial'

--********************检查序列号，如果强制管理，期初数量是否等于序列号总数开始*****************
IF @IfMustSerial=0 GOTO NotMustSerial

DECLARE @starPTypeID		VARCHAR(50),
		@starBTypeID		VARCHAR(50),
		@starKTypeID		VARCHAR(50),
		@starPTypeName		VARCHAR(66),
		@starBTypeName		VARCHAR(66),
		@starKTypeName		VARCHAR(66),
		@starPQty			 NUMERIC(24, 10) ,
		@starPCostTotal		 NUMERIC(24, 10) ,
		@starSerialQty		NUMERIC(18,0),
		@starSTSerialQty	NUMERIC(18,0)	-- 受托序列号数量
	
--委托代销序列号的处理
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT 	a.PTypeID,a.BTypeID,ISNULL(SUM(a.Qty),0) AS Qty	FROM IniCommissionStock a INNER JOIN PType b ON (a.PTypeID=b.TypeID) WHERE b.ifSerial=1 AND STypeId = @STypeId AND a.Type=140 GROUP BY a.PTypeID,a.BTypeID
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
WHILE @@Fetch_Status = 0 
	BEGIN       
		SELECT @starSerialQty=COUNT(*) FROM gp_initptypeserial WHERE PTypeID=@starPTypeID AND BTypeID1=@starBTypeID AND state=13 AND STypeId = @STypeId
		IF @starSerialQty<>@starPQty
		BEGIN              
			IF ((ISNULL(@starPTypeID,'')='') OR (ISNULL(@starBTypeID,'')=''))
			BEGIN
				SELECT @ReturnValue='委托代销商品序列号中的基本信息丢失，请查询委托代销存中序列号的商品属性和往来单位属性！'
				GOTO SerialError
			END
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在代销库中与往来单位【'+@starBTypeName+'】关联的『委托期初』数量与序列号总数不一致，请核查修正后再开账'              
			GOTO SerialError
		END       
		FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
	END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor		

--2、以Gp_initPTypeSerial为主
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT COUNT(Serial) AS COUNT,PTypeID,BTypeID1 FROM gp_initptypeserial WHERE state=13 AND STypeId = @STypeId GROUP BY PTypeID,BTypeID1
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starBTypeID
WHILE @@Fetch_Status = 0
BEGIN
       SELECT @starPQty=ISNULL(SUM(Qty),0) FROM inicommissionStock WHERE PTypeID=@starPTypeID AND BTypeID=@starBTypeID AND Type = 140 AND STypeID = @STypeId
       
       IF @starSerialQty<>@starPQty
       BEGIN
			IF ((ISNULL(@starPTypeID,'')='') OR (ISNULL(@starBTypeID,'')=''))
				BEGIN
					SELECT @ReturnValue='委托代销商品序列号中的基本信息丢失，请查询委托代销存中序列号的商品属性和往来单位属性！'
					GOTO SerialError
				END
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在代销库中与往来单位【'+@starBTypeName+'】关联的『委托期初』数量与序列号总数不一致，请核查修正后再开账'              
			GOTO SerialError
       END       
       FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starBTypeID
END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

-- 受托代销期初序列号检查
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT a.PTypeID,a.BTypeID,ISNULL(SUM(a.Qty),0) AS Qty FROM IniCommissionStock a INNER JOIN PType b ON a.PTypeID=b.TypeID WHERE b.ifSerial=1 AND STypeId =@STypeId AND a.Type=144 AND ISNULL(a.Qty,0)<>0 GROUP BY a.PTypeID,a.BTypeID	
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
WHILE @@Fetch_Status = 0 
BEGIN
       SELECT @starSerialQty=COUNT(*) FROM gp_initptypeserial WHERE PTypeID=@starPTypeID AND BTypeID2=@starBTypeID AND state = 7 AND STypeId = @STypeId
       IF @starSerialQty<>@starPQty
       BEGIN			
			IF ((ISNULL(@starPTypeID,'')='') OR (ISNULL(@starBTypeID,'')=''))
				BEGIN
					SELECT @ReturnValue='受托代销商品序列号中的基本信息丢失，请查询受托代销存中序列号的商品属性,往来单位属性！'
					GOTO SerialError
				END
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在受托代销库中与往来单位【'+@starBTypeName+'】关联的『受托期初』数量与序列号总数不一致，请核查修正后再开账！'
			GOTO SerialError
       END
       FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

--2、以Gp_initPTypeSerial为主
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT COUNT(Serial) AS COUNT,PTypeID,BTypeID2 FROM gp_initptypeserial WHERE state=7 AND STypeid = @STypeId GROUP BY PTypeID,BTypeID2
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starBTypeID
WHILE @@Fetch_Status = 0 
BEGIN
       SELECT @starPQty=ISNULL(SUM(Qty),0) FROM inicommissionStock WHERE PTypeID=@starPTypeID AND BTypeID=@starBTypeID AND Type = 144 AND STypeID = @STypeId
       IF @starSerialQty<>@starPQty
       BEGIN
			IF ((ISNULL(@starPTypeID,'')='') OR (ISNULL(@starBTypeID,'')='') OR (ISNULL(@starKTypeID,'')=''))
				BEGIN
					SELECT @ReturnValue='受托代销商品序列号中的基本信息丢失，请查询受托代销存中序列号的商品属性,往来单位属性！'
					GOTO SerialError
				END
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在受托代销库中与往来单位【'+@starBTypeName+'】关联的『受托期初』数量与序列号总数不一致，请核查修正后再开账！'
			GOTO SerialError
       END       
       FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starBTypeID
END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

--**********************************************************************************************************无需序列号匹配检查的出口***********************************************************************************************
NotMustSerial:
DELETE FROM iniCommissionStock
WHERE	(Qty = 0 AND Total = 0 AND CostTotal = 0 AND Type = 140) OR (Qty = 0 AND Total = 0 AND Type = 144)
		AND STypeID = @STypeId

DELETE FROM dbo.IniCommissionStock_Qty
WHERE	qty=0
		AND NQty=0	
		AND STypeID = @STypeId	
UPDATE	iniCommissionStock
SET		Total = CAST(Total AS  NUMERIC(24, 10) ),
		CostTotal = CAST(CostTotal AS  NUMERIC(24, 10) )
WHERE	STypeID = @STypeId	

-- 特殊处理会计科目
UPDATE dbo.AType_Total SET Total00=0,Ntotal00=0 WHERE ATypeID=(SELECT nid FROM dbo.Ac_Items WHERE FullName='内部应收') AND STypeID=@stypeid
DECLARE @nWTDXTotal  NUMERIC(24, 10) ,
		@nSTDXTotal  NUMERIC(24, 10) 

DECLARE	@GOODS_ID VARCHAR(50),			
		@GOODS_WTDX_ID VARCHAR(50),
		@GOODS_STDX_ID VARCHAR(50),
		@Cid int
 
SELECT @GOODS_ID=nid FROM dbo.Ac_Items WHERE UserCode='1241'			--『库存商品总值合计』
SELECT @GOODS_WTDX_ID=nid FROM dbo.Ac_Items WHERE UserCode='1261'		--『委托代销商品』
SELECT @GOODS_STDX_ID=nid FROM dbo.Ac_Items WHERE UserCode='2141'		--『代销商品』
SELECT @cid=cid FROM dbo.Ac_Currency WHERE Sysrow=1

DELETE FROM  AType_Total WHERE ATypeID IN (@GOODS_ID,@GOODS_WTDX_ID,@GOODS_STDX_ID) AND STypeID=@stypeid
SELECT @nWTDXTotal=ISNULL(SUM(CostTotal),0) FROM inicommissionStock WHERE Type=140 AND STypeID = @STypeId
INSERT INTO AType_Total(ATypeID,STypeID,Total00,Ntotal00,CID)VALUES(@GOODS_WTDX_ID,@STypeId,@nWTDXTotal,@nWTDXTotal,@Cid)

UPDATE iniCommissionStock SET CostTotal = 0 WHERE Type = 144 AND STypeID = @STypeId

SELECT @nSTDXTotal=ISNULL(SUM(Total),0) FROM inicommissionStock WHERE Type=144 AND STypeID = @STypeId
INSERT INTO AType_Total(ATypeID,STypeID,Total00,Ntotal00,CID)VALUES(@GOODS_STDX_ID,@STypeId,@nSTDXTotal,@nSTDXTotal,@Cid)

-------------处理未分配利润-------------------
DECLARE @lr_id INT,@lrtotal00  NUMERIC(24, 10) 
SELECT @lr_id=nid FROM dbo.Ac_Items WHERE USERcode='3141'  --未分配利润

IF NOT EXISTS(SELECT 1 FROM dbo.AType_Total WHERE ATypeID=@lr_id AND Total00<>0 AND STypeID=@stypeid)
BEGIN
SELECT @lrtotal00=ISNULL(sum(total00),0)
FROM dbo.AType_Total WHERE ATypeID IN(SELECT nId FROM dbo.Ac_Items WHERE nTypeId like '00003%' and sonnum=0)
AND STypeID=@stypeid

SELECT @lrtotal00-=ISNULL(sum(total00),0)
FROM dbo.AType_Total 
WHERE ATypeID IN(SELECT nId FROM dbo.Ac_Items WHERE nTypeId like '00004%' and sonnum=0)
AND STypeID=@stypeid

IF @lr_id<>0
	BEGIN	
		DELETE FROM dbo.AType_Total WHERE ATypeID=@lr_id AND stypeid=@stypeid
		INSERT INTO atype_total (atypeid,stypeid,total00,ntotal00,cid)VALUES(@lr_id,@stypeid,@lrtotal00,@lrtotal00,@cid);	
	END
END

--------------------计算其他资本，使资产负载平衡--------------------------------
DECLARE @Other_ID INT,@ZCTotal  NUMERIC(24, 10) =0,@FZTotal  NUMERIC(24, 10) =0,@QYTotal  NUMERIC(24, 10) =0

SELECT @Other_ID=nid FROM ac_items WHERE UserCode='3101'

SELECT @ZCTotal=ISNULL(SUM(Total00),0)
FROM dbo.AType_Total
WHERE ATypeID IN (SELECT nid FROM dbo.Ac_Items WHERE nTypeId LIKE '00001%' AND SonNum=0 AND usercode<>'1132')  --排除内部应收
	AND STypeID=@stypeid
	
--加上内部应收	
SET @ZCTotal+=(SELECT ISNULL(SUM(InnerARTotal00),0) FROM dbo.SType_InnerARTotal WHERE STypeID=@stypeid)	
	
--------------单独计算固定资产看片的值-----------
DECLARE @ifassetsini INT ,@iscard INT=0,@val  NUMERIC(24, 10) =0.0
SELECT @ifassetsini =ifassetsini FROM stype where typeid=@stypeid;

IF  EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
	SET @iscard=1
	
IF @iscard =1  
BEGIN
  IF @ifassetsini=0  --卡片显示,未初始化的情况
	SET @ZCTotal+=(SELECT ISNULL(SUM(w.netvalue),0) AS netvalue FROM Ac_AssetsCards w WHERE w.AssetsState IN(1,4) AND stypeid=@stypeid)
	ELSE
	BEGIN
		SET @ZCTotal+=
		(
			SELECT ISNULL(SUM(netvalue),0) AS netvalue
			 FROM (
					SELECT rn=ROW_NUMBER() OVER(PARTITION BY AssertsCardId ORDER BY Id desc),* FROM Ac_AssetsCards_History WHERE BillType=0 AND stypeid=@stypeid
					)a WHERE rn=1 AND stypeid=@stypeid
		)

	END
	
END
--------------单独计算固定资产看片的值 end-----------	

SELECT @FZTotal=ISNULL(SUM(Total00),0)
FROM dbo.AType_Total
WHERE ATypeID IN (SELECT nid FROM dbo.Ac_Items WHERE nTypeId LIKE '00002%' AND SonNum=0)
	AND STypeID=@stypeid
	
SELECT @QYTotal=ISNULL(SUM(Total00),0)
FROM dbo.AType_Total
WHERE ATypeID IN (SELECT nid FROM dbo.Ac_Items WHERE nTypeId LIKE '00005%' AND SonNum=0 AND nId<>@Other_ID)
	AND STypeID=@stypeid
	

DELETE FROM dbo.AType_Total WHERE ATypeID=@Other_ID AND STypeID=@stypeid
INSERT INTO dbo.AType_Total( ATypeID , STypeID ,Total00 , CID , Ntotal00) VALUES(@Other_ID,@Stypeid,@ZCtotal-@FZTotal-@QYTotal,@Cid,@ZCtotal-@FZTotal-@QYTotal)
--------------------计算其他资本，使资产负载平衡 end--------------------------------
		

--修改财务期初汇总值	
UPDATE	AType_Total
SET		Total = Total00,
		Ntotal = Ntotal00
WHERE	STypeID = @STypeId	

DELETE FROM dbo.AType_Total WHERE Ntotal=0 AND Ntotal00=0 AND Total=0 AND Total00=0

--修改往来期初汇总值	
UPDATE	BType_ARAPTotal 
SET		ARTotal = ARTotal00,
		APTotal = APTotal00,
		YSTotal = YSTotal00,
		YFTotal = YFTotal00,
		nARTotal = nARTotal00,
		nAPTotal = nAPTotal00,
		nYSTotal = nYSTotal00,
		nYFTotal = nYFTotal00,
		FCTotal=FCTotal00,
		NFCTotal=NFCTotal00,
		GRIRTotal=GRIRTotal00,
		NGRIRTotal=NGRIRTotal00
WHERE	STypeID = @STypeId	


--修改品牌往来期初汇总值	
UPDATE	dbo.Brandar_ArApTotal 
SET		ARTotal = ARTotal00,
		YSTotal = YSTotal00,
		nARTotal = nARTotal00,
		nYSTotal = nYSTotal00
		
WHERE	STypeID = @STypeId	

DELETE FROM CommissionStock WHERE STypeID = @STypeId

--9.7对于数量为零金额不为零的数据不再限制
--IF EXISTS(SELECT TOP 1 1 FROM iniCommissionStock WHERE Type = 140 AND Qty = 0 AND Total <> 0 AND STypeId = @STypeId)
--BEGIN
--	SELECT TOP 1 @starPTypeID=PTypeID,@starBTypeID=BTypeID FROM iniCommissionStock WHERE Type = 140 AND Qty = 0 AND Total <> 0 AND STypeId = @STypeId

--	SELECT TOP 1 @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
--	SELECT TOP 1 @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID

--	SET @ReturnValue='委托代销期初中的商品【'+@starPTypeName+'】，其关联往来单位【'+@starBTypeName+'】对应的期初数量为零，但期初金额不为零，请修改确认后重试！'
--	GOTO CostQtyError
--END

--IF EXISTS(SELECT TOP 1 1 FROM iniCommissionStock WHERE Type = 140 AND Qty = 0 AND CostTotal <> 0 AND STypeID = @STypeId)
--BEGIN
--	SELECT TOP 1 @starPTypeID=PTypeID,@starBTypeID=BTypeID FROM iniCommissionStock WHERE Type = 140 AND Qty = 0 AND CostTotal <> 0 AND STypeId = @STypeId

--	SELECT TOP 1 @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
--	SELECT TOP 1 @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID

--	SET @ReturnValue='委托代销期初中的商品【'+@starPTypeName+'】，其关联往来单位【'+@starBTypeName+'】对应的期初数量为零，但期初成本金额不为零，请修改确认后重试！'
--	GOTO CostQtyError
--END

--IF EXISTS(SELECT TOP 1 1 FROM iniCommissionStock WHERE Type = 144 AND Qty = 0 AND Total <> 0 AND STypeId = @STypeId)
--BEGIN
--	SELECT TOP 1 @starPTypeID=PTypeID,@starBTypeID=BTypeID FROM iniCommissionStock WHERE Type = 144 AND Qty = 0 AND Total <> 0 AND STypeId = @STypeId

--	SELECT TOP 1 @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
--	SELECT TOP 1 @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID

--	SET @ReturnValue='受托代销期初中的商品【'+@starPTypeName+'】，其关联往来单位【'+@starBTypeName+'】对应的期初数量为零，但期初金额不为零，请修改确认后重试！'
--	GOTO CostQtyError
--END		


--===========================处理门店配送===============================--
DECLARE @psSerialNull	VARCHAR(MAX)
DECLARE @SerialState	Int

SET @psSerialNull = ''

SELECT	TOP 1 
	   @psSerialNull = I.Serial,
	   @SerialState  = I.State
	   FROM gp_initLendPtypeSerial I,
	   DeliveryBill D
	   INNER JOIN PosAllotApplyBillIndex po ON D.BillNumberId=po.BillNumberId
	   WHERE I.Serial = D.Serial  AND po.IsIni='1' AND 
	   po.Qty<> D.Qty AND (I.State=1 OR I.State=7) 
	   
IF @psSerialNull <> ''
BEGIN
	IF @SerialState=1
		SELECT @ReturnValue='期初未完成门店配送单据里的序列号【'+@psSerialNull+'】 ，不允许存在期初库存中' 
	ELSE
		SELECT @ReturnValue='配送在途的序列号【'+@psSerialNull+'】 ，不允许存在受托代销的期初库存中' 
	GOTO SerialError		
END	



SELECT	TOP 1 
	   @psSerialNull = I.Serial,
	   @SerialState  = I.State
	   FROM gp_initLendPtypeSerial I,
	   DeliveryBill D
	   INNER JOIN PosAllotApplyBillIndex po ON D.BillNumberId=po.BillNumberId
	   WHERE I.Serial = D.Serial  AND po.IsIni='1' AND 
	   po.Qty<> D.Qty AND (I.State=1 OR I.State=7) 
	   
IF @psSerialNull <> ''
BEGIN
	IF @SerialState=1
		SELECT @ReturnValue='期初未完成门店配送单据里的序列号【'+@psSerialNull+'】 ，不允许存在期初库存中' 
	ELSE 
		SELECT @ReturnValue='配送在途的序列号【'+@psSerialNull+'】 ，不允许存在受托代销的期初库存中' 
	GOTO SerialError		
END	
	   
--==============================END=====================================--
	   
--处理委托期初
DECLARE @IniSerialNull	VARCHAR(MAX)

SET @IniSerialNull = ''


SELECT	TOP 1 
		@IniSerialNull = I.Serial
FROM	Gp_InitPTypeSerial I,
		Gp_CruPTypeSerial C
WHERE	I.Serial = C.Serial
		AND I.STypeId = @STypeId
		AND c.[State] IN (13)
		--AND I.InKTypeTime IS NULL

IF @IniSerialNull <> ''
	BEGIN
		SELECT @ReturnValue='序列号【'+@IniSerialNull+'】在已经开账的委托代销序列号中已经存在，请修改确认后重试！'
		GOTO SerialError		
	END	

SELECT	TOP 1 
		@IniSerialNull = I.Serial
FROM	Gp_InitPTypeSerial I,
		Gp_CruPTypeSerial C
WHERE	I.Serial = C.Serial
		AND I.STypeId = @STypeId
		AND I.[State] IN (13)
		--AND I.InKTypeTime IS NULL

IF @IniSerialNull <> ''
	BEGIN
		SELECT @ReturnValue='委托代销序列号【'+@IniSerialNull+'】在已经开账的序列号库中已经存在，请修改确认后重试！'
		GOTO SerialError		
	END	

	
INSERT INTO gp_CruPtypeSerial
(
		Serial ,
		KtypeID ,
		PtypeID ,
		BTypeID1 ,
		BTypeID2 ,
		InKtypeTime ,
		OutKtypeTime ,
		[User] ,
		State ,
		Note ,
		Flag ,
		CommissionState ,
		ETypeID ,
		LTypeID ,
		iniFlag ,
		CostPrice ,
		GoodsOrder ,
		GoodsNumber ,
		STypeId ,
		Comment1 ,
		Comment2 ,
		Comment3,
		CargoID
) 
SELECT	Serial ,
		KtypeID ,
		PtypeID ,
		BTypeID1 ,
		BTypeID2 ,
		InKtypeTime ,
		OutKtypeTime ,
		[User] ,
		State ,
		Note ,
		Flag ,
		CommissionState ,
		ETypeID ,
		LTypeID ,
		iniFlag ,
		CostPrice ,
		GoodsOrder ,
		GoodsNumber ,
		STypeId ,
		Comment1 ,
		Comment2 ,
		Comment3 ,
		CargoID
FROM	gp_initptypeserial 
WHERE	[State] = 13 
		AND Serial NOT IN (SELECT Serial FROM gp_CruPtypeSerial)
		AND STypeId = @STypeId
		--AND InKTypeTime IS NULL
		
UPDATE	gp_CruPtypeSerial
SET		PTypeId = Ini.ptypeid,
		KTypeId = Ini.ktypeid,
		BTypeId1 = Ini.BTypeId1,
		BTypeId2 = Ini.BTypeId2,
		[State] = Ini.[state],
		STypeId = Ini.STypeId,
		Flag = CASE
					WHEN ini.[state] IN (1,7,25) THEN 1
					ELSE 0
				END,
		CommissionState = CASE
								WHEN ini.[State] = 7 THEN 0
								ELSE NULL
							END						
FROM	gp_initptypeserial Ini,
		gp_CruPtypeSerial  C
WHERE	INI.Serial = C.serial 
		AND INI.[State] = 13
		AND Ini.STypeId = @STypeId
		--AND INI.InKTypeTime IS NULL		

UPDATE	GP_InitPTypeSerial
SET		InKTypeTime = CAST(YEAR(GETDATE()) AS VARCHAR) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR) + '-' + CAST(DAY(GETDATE()) AS VARCHAR)
WHERE	[State] = 13
		AND STypeId = @STypeId
		--AND InKTypeTime IS NULL

UPDATE	GP_CruPTypeSerial
SET		InKTypeTime = CAST(YEAR(GETDATE()) AS VARCHAR) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR) + '-' + CAST(DAY(GETDATE()) AS VARCHAR)
WHERE	[State] = 13
		AND STypeId = @STypeId
		
INSERT INTO CommissionStock (
	PTypeID,
	BTypeID,
	Type,
	Qty,
	CostTotal,
	Total,
	Explain,
	KTypeID,
	ETypeID,
	STypeID
)
SELECT	a.PTypeID,
		a.BTypeID,
		a.Type,
		SUM(Qty) AS Qty,
		SUM(CostTotal) AS CostTotal,
		SUM(Total) AS Total,
		A = '',
		B = '',
		C = '',
		A.STypeID
FROM	IniCommissionStock a
WHERE	A.STypeId = @STypeId
GROUP BY a.PTypeID, a.BTypeID, a.Type,A.STypeId		

INSERT INTO dbo.CommissionStock_Qty
        ( Ptypeid ,
          Btypeid ,
          Stypeid ,
          Type ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate, 
          Qty ,
          NQty
        )
SELECT    Ptypeid ,
          Btypeid ,
          Stypeid ,
          Type ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          SUM(Qty) ,
          SUM(NQty)
FROM dbo.IniCommissionStock_Qty
WHERE	STypeId = @STypeId
GROUP BY Ptypeid ,
          Btypeid ,
          Stypeid ,
          Type ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate 

UPDATE UserConfig SET Value = '0' WHERE ConfigName = 'AverageCostPrice'	

UPDATE SType_InnerARTotal SET InnerARTotal=InnerARTotal00 WHERE STypeID=@STypeId --当前分支机构的内部应收处理

UPDATE Sysdata SET SubValue = 'F' WHERE SubName = 'inicanmodify'
--开账时，当系统设置为序列号宽松管理模式时，所有商品的 IfSerial =0
IF EXISTS(SELECT * FROM userconfig  WHERE ConfigName ='mngSerial' and Value=0)
	BEGIN
		UPDATE ptype SET IfSerial =0
	END

	RETURN 0
		
error: 
	RETURN -1
SerialError: 
	RETURN -2
DxQtyError: 
	RETURN -3
CostQtyError: 
	RETURN -8
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
 按分支机构开账
*/
CREATE PROCEDURE Gp_OkIniAll
(
	@STypeId		VARCHAR(MAX),		--	分支机构
	@ckbusiness	    INT,				-- =1 业务开账
	@ckaccount		INT,				-- =1 总账开账
    @ReturnValue	VARCHAR(MAX) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN OkIniAll
SAVE TRAN OkIniAllPoint

	DECLARE @KTypeId		VARCHAR(MAX),
			@szCanModiIni	INT,
			@Re				INT,
			@rValue			VARCHAR(MAX),
			@MxSTypeId		VARCHAR(MAX),
			@MxSFullName	VARCHAR(MAX),
			@StypeIndependentOpen INT,
			@CID			INT,
			@FYear			INT,
			@FMonth			INT
			
	SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
			
	--业务开账
	IF @ckbusiness=1
	BEGIN
		--对全部分支机构进行开账，所有未开账的分支机构一起校验期初	
		IF @STypeId=''
		BEGIN	
			EXEC @Re = Gp_CheckArapIni @STypeId,@rValue OUTPUT	
			IF @Re < 0
			BEGIN		
				--期初往来对账表中数据与期初单据数据不一致
				--尝试重新计算期初往来数据
				--重新计算后仍错误，则提示
				--注意：该操作在数据异常时会导致开账前后期初往来数据不一致并可能掩盖期初往来数据处理的一些未知BUG
				--2015-07-23 司华山
				EXEC @Re=Gp_IniToArApTotal '%' -- varchar(50)
				IF @Re<0				
					GOTO ERROR
			END		
			
			EXEC @Re = Gp_CheckGoodsNumber @STypeId,@rValue OUTPUT
			IF @Re < 0
			BEGIN						
				GOTO ERROR
			END		
		END

		--选具体分支机构开账的时候:独立核算的分支机构必须在所有以其作为记账单位的非独立分支机构开完帐后才能开账
		IF @stypeid<>'' AND EXISTS(SELECT 1 FROM dbo.SType s WHERE sonnum =0 AND verifyid=@stypeid AND TypeId<>@STypeId AND NOT EXISTS(SELECT 1 FROM dbo.SType_UserConfig WHERE StypeId=s.TypeId AND ConfigNo='1' AND Value='1'))
		AND EXISTS(SELECT 1 from Sysdata WHERE SubName='IsUseAcSystem' AND SubValue='1') --总账情况下验证
		AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='stypeindependentopen' AND SubValue=1)
		BEGIN
			SET @rValue='独立核算的分支机构必须在所有以其作为记账单位的非独立分支机构开完账后才能开账'
			SET @Re=-2
			GOTO ERROR
		END

		--是否有未补录完部门和经手人的单据
		IF @STypeId='' AND EXISTS(SELECT 1 FROM billindex WHERE ifYearBill=1 AND (DTypeId='' OR etypeid=''))
		BEGIN
			SET @rValue=N'期初单据存在【部门、经手人】为空的单据，请在【期初单据查询】中予以完善单据信息，再进行开账！';
			SET @Re=-2
			GOTO ERROR
		END

		IF @STypeId<>'' AND EXISTS(SELECT 1 FROM dbo.BillIndex WHERE ifYearBill=1 AND (DTypeId='' OR etypeid='') AND (@STypeId='00000' OR (@STypeId<>'00000' AND Stypeid=@STypeId)))
		BEGIN
			SET @rValue='【'
			+STUFF((
				SELECT DISTINCT '、'+a.FullName FROM dbo.SType a JOIN billindex b ON a.TypeId=b.Stypeid AND ifYearBill=1 AND (DTypeId='' OR etypeid='') FOR XML PATH('')
			),1,1,'')
			+'】'+N'期初单据存在【部门、经手人】为空的单据，请在【期初单据查询】中予以完善单据信息，再进行开账！';
			SET @Re=-2
			GOTO ERROR
		END

		DECLARE SType_B_Cursor CURSOR FOR
			SELECT A.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,'00001') A INNER JOIN dbo.SType B ON A.TypeId=B.TypeId 
			WHERE B.deleted=0
			
		OPEN SType_B_Cursor

		FETCH NEXT FROM SType_B_Cursor INTO @MxSTypeId

		WHILE @@FETCH_STATUS = 0
			BEGIN
				--开账表没有则写入未开账标识
				IF NOT EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeID = @MxSTypeId)
					BEGIN
						INSERT INTO SType_UserConfig(ConfigNo,Value,EtypeId,STypeID)VALUES('1','0','00001',@MxSTypeId)
					END
					
				--选择具体的分支机构的时候才在此校验期初	
				IF @STypeId <> ''
				BEGIN
					EXEC @Re = Gp_CheckArapIni @MxSTypeId,@rValue OUTPUT	
					IF @Re < 0
					BEGIN	
						--期初往来对账表中数据与期初单据数据不一致
						--尝试重新计算期初往来数据
						--重新计算后仍错误，则提示
						--注意：该操作在数据异常时会导致开账前后期初往来数据不一致并可能掩盖期初往来数据处理的一些未知BUG
						--2015-07-23 司华山
						EXEC @Re=GP_IniToArapTotal	@MxSTypeId
						IF @Re<0				
						BEGIN
							GOTO ERROR
							BREAK
						END
					END			
					
					EXEC @Re = Gp_CheckGoodsNumber @MxSTypeId,@rValue OUTPUT	
					IF @Re < 0
					BEGIN						
						GOTO ERROR
						BREAK
					END			
				END		
				
				DECLARE @version		INT
				SELECT @version=SubValue FROM dbo.sysdata WHERE SubName='ProInfo' 
				SELECT @FYear = FYear,@FMonth = FPeriod  FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @MxSTypeId
				
				--固定资产的判断
				IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
				BEGIN
					---该分支机构是否已经初始化	
					IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE IfAssetsIni=1 AND TypeId=@MxSTypeId)  --已经初始化 
						BEGIN
							---独立核算机构才会验证数据
							IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE IsSelfVerify=1 AND TypeId=@MxSTypeId)
								BEGIN
									DECLARE @A  NUMERIC(24, 10) --固定资产科目之和
									DECLARE @B  NUMERIC(24, 10) --累计折旧科目之和
									DECLARE @C  NUMERIC(24, 10) --减值准备科目之和
									DECLARE @NetValueTotal  NUMERIC(24, 10)  --净值之和
									
								
									---取出净值之和
									SELECT @NetValueTotal=ISNULL(SUM(ISNULL(NetValue,0)),0)
									FROM dbo.AC_AssetsCards ac
									JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
									WHERE AssetsState=3 AND AssetsState=4
									
									---取出固定资产科目之和
									SELECT @A=ISNULL(SUM(ISNULL(iniTotal,0)),0)
									FROM dbo.Ac_IniAccount ab 
									JOIN (  SELECT DISTINCT ac.AssertATypeId AS typeid    
											FROM AC_AssetsCards ac 
											JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
											WHERE AssetsState=3 AND AssetsState=4
										 ) ac  ON ab.ATypeId=ac.typeid
									 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
									
									---取出累计折旧科目之和
									SELECT @B=ISNULL(SUM(ISNULL(iniTotal,0)),0)
									FROM dbo.Ac_IniAccount ab 
									JOIN (  SELECT DISTINCT ac.DepATypeId AS typeid    
											FROM AC_AssetsCards ac 
											JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId
											WHERE AssetsState=3 AND AssetsState=4
										 ) ac  ON ab.ATypeId=ac.typeid
									 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
									
									---取出减值准备科目之和
									SELECT @C=ISNULL(SUM(ISNULL(iniTotal,0)),0)
									FROM dbo.Ac_IniAccount ab 
									JOIN (  SELECT DISTINCT ac.DevalueATypeId AS typeid    
											FROM AC_AssetsCards ac 
											JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@MxSTypeId 
											WHERE AssetsState=3 AND AssetsState=4
										 ) ac  ON ab.ATypeId=ac.typeid
									 WHERE ab.STypeId=@MxSTypeId AND ab.Cid=@Cid AND FYear=@FYear
									
									IF @NetValueTotal!=@A-@B-@C 
										BEGIN
											  SET @rValue = @MxSTypeId
											  SET @Re= -9
											  GOTO ERROR
											  BREAK
										END
								END
							
						END
					ELSE 
						BEGIN
							DECLARE @tempStypeName  NVARCHAR(500) 

							SELECT @tempStypeName = FullName FROM SType WHERE TypeId = @MxSTypeId
							IF EXISTS(SELECT 1 FROM dbo.SType WHERE IsSelfVerify=0 AND TypeId=@MxSTypeId)
							BEGIN
								SELECT  @tempStypeName = A.FullName
								FROM    dbo.SType A
										INNER JOIN dbo.SType B ON A.TypeId = B.VerifyID
								WHERE   B.TypeId = @MxSTypeId
								SET @rValue = '本机构的记账分支机构【'+@tempStypeName+'】固定资产未初始化，不能开账，请确认！'
								SET @Re= -2
								GOTO ERROR
								BREAK
							END
							ELSE
							BEGIN
								SELECT  @tempStypeName = A.FullName
								FROM    dbo.SType A
								WHERE   A.TypeId = @MxSTypeId
							END
							
							IF @version=2
								SET @rValue = '分支机构【'+@tempStypeName+'】固定资产未初始化，不能开账，请确认！'
							ELSE 
								SET @rValue = '固定资产未初始化，不能开账，请确认！'
							SET @Re= -2
							GOTO ERROR
							BREAK
						END
					
				END
				
				----------------会员储值-----------------------
				EXEC @Re=GP_OkIniVipCard @MxSTypeId, @rValue OUTPUT	
				IF @Re < 0
				BEGIN						
					GOTO ERROR
					BREAK
				END	
				----------------会员储值-----------------------
									
				--如果分支机构没有仓库，则不进入按仓库开账流程了
				IF NOT EXISTS(SELECT TOP 1 1 FROM Stock WHERE STypeID = @MxSTypeId)
				BEGIN					
					EXEC @Re = Gp_OkIni_ArApTotalNoStock @MxSTypeId, @rValue OUTPUT					
					IF @Re < 0
						BEGIN						
							GOTO ERROR
							BREAK
						END							
				END
				ELSE --按分支机构开账
					BEGIN
						EXEC @Re = Gp_OkIni @MxSTypeId,@rValue OUTPUT
						IF @Re < 0
						BEGIN						
							GOTO ERROR
							BREAK
						END
					END
				
				--未开帐的分支机构生成期初往来明细数据
				IF 	NOT EXISTS (SELECT 1 FROM SType_UserConfig WHERE StypeId=@MxSTypeId AND Value='1')
				BEGIN
					EXEC GP_GenIniBtype_ArAPTotal @MxSTypeId;
				END
				
				--修改开账标识
				UPDATE SType_UserConfig SET Value = '1' WHERE STypeID = @MxSTypeId
				UPDATE dbo.BillIndex SET draft=0 WHERE IsIni=1 AND Stypeid=@MxSTypeId						
				
				IF @@ERROR <> 0
				BEGIN						
					GOTO ERROR
					BREAK
				END		
								
				FETCH NEXT FROM SType_B_Cursor INTO @MxSTypeId
			END
			
		CLOSE SType_B_Cursor
		DEALLOCATE SType_B_Cursor
	END
	
	--总账单独开账只有启用独立开账才OK
	IF @ckaccount=1
	BEGIN
		EXEC @Re=P_MF_OkIni @STypeId,@rValue OUT
		IF @Re < 0
		BEGIN						
			GOTO ERROR
		END		
	END

COMMIT TRAN OkIniAll
RETURN 0
	
ERROR:
	SET @ReturnValue = @rValue
	IF @Re<>0
	BEGIN
		ROLLBACK TRAN OkIniAllPoint
		COMMIT TRAN OkIniAll
	END
	ELSE 
		COMMIT TRAN OkIniAll
	RETURN @Re

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	

/*

DECLARE
	@STypeId		VARCHAR(MAX),		--	分支机构
	@ckbusiness	    INT,				-- =1 业务开账
	@ckaccount		INT,				-- =1 总账开账
    @ReturnValue	VARCHAR(MAX),		--  输出信息
	@nRet			INT

BEGIN TRAN

SELECT 
	@STypeID='',
	@ckbusiness=1,
	@ckaccount=1

EXEC @nRet=Gp_OkIniAll
	@STypeId,
	@ckbusiness,
	@ckaccount,
    @ReturnValue out
    
SELECT @nRet,@ReturnValue    

ROLLBACK TRAN


*/



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-17
-- Description: 开账处理序列号

--修改:冯波
--序列号严密关联,2015
-- =============================================

CREATE PROCEDURE Gp_OkIniSerial
(
	@STypeId		VARCHAR(50),		--	分支机构
    @ReturnValue	VARCHAR(MAX) out	--  输出信息
)

--@encode$--

AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 


DECLARE @starPTypeID	VARCHAR(50)
DECLARE @starBTypeID	VARCHAR(50)
DECLARE @starKTypeID	VARCHAR(50)
DECLARE @starPTypeName	VARCHAR(200)
DECLARE @starBTypeName	VARCHAR(66)
DECLARE @starKTypeName	VARCHAR(66)
DECLARE @StypeFullName	VARCHAR(200)
DECLARE @starPQty		 NUMERIC(24, 10) 
DECLARE @starPCostTotal  NUMERIC(24, 10) 
DECLARE @starSerialQty	NUMERIC(18,0)
DECLARE @starSTSerialQty NUMERIC(18,0)	-- 受托序列号数量
DECLARE @proinfo		CHAR(1)

SELECT @proinfo=SubValue FROM sysdata WHERE SubName='Proinfo'
IF @proinfo='2'
BEGIN
	SELECT @StypeFullName=fullname FROM stype WHERE TypeId=@STypeId
END
ELSE 
BEGIN
	SET @StypeFullName = ''
END

CREATE TABLE #Ktype(TypeId VARCHAR(50),Fullname VARCHAR(200))
INSERT INTO #Ktype(TypeId,Fullname) SELECT TypeId,FullName FROM Stock WHERE STypeId = @STypeId AND SonNum = 0

--普通库检查
--1、以GoodsStocks为主
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT a.PTypeID,ISNULL(SUM(a.Qty),0) AS Qty,a.KTypeID FROM IniGoodsstocks a JOIN PType b ON (a.PTypeID=b.TypeID) INNER JOIN #Ktype K ON A.KtypeId=K.TypeId  WHERE b.ifSerial=1  GROUP BY a.PTypeID, a.KTypeID
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starPQty,@starKTypeID
WHILE @@Fetch_Status = 0 
	BEGIN       
       SELECT @starSerialQty=COUNT(*) FROM gp_initptypeserial WHERE PTypeID=@starPTypeID AND KTypeID=@starKTypeID AND ( State = 1 OR State = 7 )
       IF @starSerialQty<>@starPQty
       BEGIN
			IF (ISNULL(@starPTypeID,'')='')
				BEGIN
					SELECT @ReturnValue='库存商品序列号中的基本信息丢失，请查询库存中的序列号的商品属性！'
  				    GOTO SerialError
				END
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			IF(ISNULL(@starKTypeID,'')='')
				BEGIN
					SELECT @ReturnValue=''+@StypeFullName+'库存商品【 '+@starPTypeName+' 】的仓库信息为空，请查询库存中的序列号的仓库属性属性！'
					GOTO SerialError
				END
				
			SELECT @starKTypeName=FullName FROM #Ktype WHERE TypeID=@starKTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在仓库【 '+@starKTypeName+' 】中的期初数量与序列号总数（包括库存期初序列号与受托代销期初序列号）不一致，请核查修正后再开账！'
			GOTO SerialError
       END       
       FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starPQty,@starKTypeID
	END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

--2、以Gp_initPTypeSerial为主
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT COUNT(a.Serial) AS COUNT,a.PTypeID,a.KTypeID FROM gp_initptypeserial a INNER JOIN #Ktype K ON A.KtypeId=K.TypeId  WHERE (state=1 OR State = 7) GROUP BY PTypeID,KTypeID
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starKTypeID
WHILE @@Fetch_Status = 0 
	BEGIN       
       SELECT @starPQty=ISNULL(SUM(Qty),0) FROM iniGoodsStocks WHERE PTypeID=@starPTypeID AND KTypeID=@starKTypeID        
       IF @starSerialQty<>@starPQty
       BEGIN			  
			  IF (ISNULL(@starPTypeID,'')='')
				BEGIN
					SELECT @ReturnValue='库存商品序列号中的基本信息丢失，请查询库存中的序列号的商品属性！'
  				    GOTO SerialError
				END
			  SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			  IF(ISNULL(@starKTypeID,'')='')
				BEGIN
					SELECT @ReturnValue=''+@StypeFullName+'库存商品【 '+@starPTypeName+' 】的仓库信息为空，请查询库存中的序列号的仓库属性属性！'
					GOTO SerialError
				END
			  SELECT @starKTypeName=FullName FROM #Ktype WHERE TypeID=@starKTypeID
			  SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在仓库【 '+@starKTypeName+' 】中的期初数量与序列号总数（包括库存期初序列号与受托代销期初序列号）不一致，请核查修正后再开账！'
			  GOTO SerialError
       END       
       FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starKTypeID
	END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor


-- Start - 维修库检查 wx_GoodsStocks
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT a.PTypeID,ISNULL(SUM(a.Qty),0) AS Qty,a.KTypeID FROM wx_IniGoodsStocks a JOIN PType b ON (a.PTypeID=b.TypeID) INNER JOIN #Ktype K ON A.KtypeId=K.TypeId  WHERE b.ifSerial=1  GROUP BY a.PTypeID, a.KTypeID
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starPQty,@starKTypeID
WHILE @@Fetch_Status = 0 
	BEGIN       
       SELECT @starSerialQty=COUNT(*) FROM gp_initptypeserial WHERE PTypeID=@starPTypeID AND KTypeID=@starKTypeID AND State = 25 
       IF @starSerialQty<>@starPQty
       BEGIN
			IF (ISNULL(@starPTypeID,'')='')
				BEGIN
					SELECT @ReturnValue='维修库存商品序列号中的基本信息丢失，请查询维修库存中的序列号的商品属性！'
  				    GOTO SerialError
				END
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			IF(ISNULL(@starKTypeID,'')='')
				BEGIN
					SELECT @ReturnValue=''+@StypeFullName+'维修库存商品【 '+@starPTypeName+' 】的仓库信息为空，请查询库存中的序列号的仓库属性属性！'
					GOTO SerialError
				END
			SELECT @starKTypeName=FullName FROM #Ktype WHERE TypeID=@starKTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在仓库【 '+@starKTypeName+' 】中的维修品库存期初数量与序列号总数不一致，请核查修正后再开账！'
				GOTO SerialError
       END       
       FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starPQty,@starKTypeID
	END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

DECLARE SerialStarManage_cursor CURSOR FOR SELECT COUNT(a.Serial) AS COUNT,a.PTypeID,a.KTypeID FROM gp_initptypeserial a INNER JOIN #Ktype K ON A.KtypeId=K.TypeId  WHERE a.state = 25 GROUP BY PTypeID,KTypeID
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starKTypeID
WHILE @@Fetch_Status = 0 
	BEGIN       
       SELECT @starPQty=ISNULL(SUM(Qty),0) FROM wx_IniGoodsStocks WHERE PTypeID=@starPTypeID AND KTypeID=@starKTypeID
       IF @starSerialQty<>@starPQty
       BEGIN			  
			  IF ((ISNULL(@starPTypeID,'')='') OR (ISNULL(@starKTypeID,'')=''))
				BEGIN
					SELECT @ReturnValue='维修库存商品序列号中的基本信息丢失，请查询维修库存中的序列号的商品属性和仓库属性！'
  				    GOTO SerialError
				END
				SELECT @starKTypeName=FullName FROM #Ktype WHERE TypeID=@starKTypeID
				SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
				SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在仓库【 '+@starKTypeName+' 】中的维修品库存期初数量与序列号总数不一致，请核查修正后再开账！'
				GOTO SerialError
       END       
       FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starKTypeID
	END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor
-- End - 维修库检查 wx_GoodsStocks

--      委托代销期初序列号检查

--1、以GoodsStocks为主
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT 	a.PTypeID,a.BTypeID,ISNULL(SUM(a.Qty),0) AS Qty	FROM IniCommissionStock a INNER JOIN PType b ON (a.PTypeID=b.TypeID)  WHERE b.ifSerial=1 AND STypeId = @STypeId AND a.Type=140 GROUP BY a.PTypeID,a.BTypeID
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
WHILE @@Fetch_Status = 0 
	BEGIN       
		SELECT @starSerialQty=COUNT(*) FROM gp_initptypeserial WHERE PTypeID=@starPTypeID AND BTypeID1=@starBTypeID AND state IN (13,32) AND STypeId = @STypeId
		
		--SELECT @starPTypeID,@starBTypeID,@starPQty,@starSerialQty
		IF @starSerialQty<>@starPQty
		BEGIN              
			IF (ISNULL(@starPTypeID,'')='')
			BEGIN
				SELECT @ReturnValue='委托代销商品序列号中的基本信息丢失，请查询委托代销存中序列号的商品属性！'
				GOTO SerialError
			END
			
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			
			IF(ISNULL(@starBTypeID,'')='')
			BEGIN
				SELECT @ReturnValue=''+@StypeFullName+'委托代销商品【 '+@starPTypeName+' 】存在未关联委托结算单位的序列号，请查询委托代销存中序列号的往来单位属性！'
				GOTO SerialError
			END
			
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在代销库中与往来单位【'+@starBTypeName+'】关联的『委托期初』数量与序列号总数不一致，请核查修正后再开账'              
			GOTO SerialError
		END       
		FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
	END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

--2、以Gp_initPTypeSerial为主
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT COUNT(Serial) AS COUNT,PTypeID,BTypeID1 FROM gp_initptypeserial WHERE state in(13,32) AND STypeId = @STypeId GROUP BY PTypeID,BTypeID1
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starBTypeID
WHILE @@Fetch_Status = 0
BEGIN
       SELECT @starPQty=ISNULL(SUM(Qty),0) FROM inicommissionStock WHERE PTypeID=@starPTypeID AND BTypeID=@starBTypeID AND Type = 140 AND STypeID = @STypeId
       
       IF @starSerialQty<>@starPQty
       BEGIN
			IF (ISNULL(@starPTypeID,'')='')
				BEGIN
					SELECT @ReturnValue='委托代销商品序列号中的基本信息丢失，请查询委托代销中序列号的商品属性！'
					GOTO SerialError
				END
				
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			
			IF(ISNULL(@starBTypeID,'')='')
				BEGIN
					SELECT @ReturnValue=''+@StypeFullName+'委托代销商品【 '+@starPTypeName+' 】存在未关联委托结算单位的序列号，请查询委托代销中序列号的往来单位属性！'
					GOTO SerialError
				END
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在代销库中与往来单位【'+@starBTypeName+'】关联的『委托期初』数量与序列号总数不一致，请核查修正后再开账'              
			GOTO SerialError
       END       
       FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starBTypeID
END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

-- 受托代销期初序列号检查
--1、以GoodsStocks为主
DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT a.PTypeID,a.BTypeID,ISNULL(SUM(a.Qty),0) AS Qty FROM IniCommissionStock a INNER JOIN PType b ON a.PTypeID=b.TypeID WHERE b.ifSerial=1 AND STypeId =@STypeId AND a.Type=144 AND ISNULL(a.Qty,0)<>0 GROUP BY a.PTypeID,a.BTypeID	
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
WHILE @@Fetch_Status = 0 
BEGIN
       SELECT @starSerialQty=COUNT(*) FROM gp_initptypeserial WHERE PTypeID=@starPTypeID AND BTypeID2=@starBTypeID AND state IN  (7,32,9,10,11,16,14) AND STypeId = @STypeId
       
       IF @starSerialQty<>@starPQty
       BEGIN
			--SELECT @starPTypeID,@starBTypeID,@starPQty,@stypeid,@starSTSerialQty		
			--SELECT 11	
			IF (ISNULL(@starPTypeID,'')='')
				BEGIN
					SELECT @ReturnValue='受托代销商品序列号中的基本信息丢失，请查询受托代销中序列号的商品属性！'
					GOTO SerialError
				END
				
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			
			IF(ISNULL(@starBTypeID,'')='')
				BEGIN
					SELECT @ReturnValue=''+@StypeFullName+'受托代销商品【 '+@starPTypeName+' 】存在未关联受托结算单位的序列号，请查询受托代销中序列号的往来单位属性！'
					GOTO SerialError
				END
				
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在受托代销库中与往来单位【'+@starBTypeName+'】关联的『受托期初』数量与序列号总数不一致，请核查修正后再开账！'
			GOTO SerialError
       END
       FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT a.PTypeID,a.BTypeID,ISNULL(SUM(a.Qty),0) AS Qty FROM IniCommissionStock_qty a INNER JOIN PType b ON a.PTypeID=b.TypeID WHERE b.ifSerial=1 AND STypeId =@STypeId AND a.Type=144 AND ISNULL(a.Qty,0)<>0 GROUP BY a.PTypeID,a.BTypeID	
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
WHILE @@Fetch_Status = 0 
BEGIN
       SELECT @starSerialQty=COUNT(*) FROM gp_initptypeserial WHERE PTypeID=@starPTypeID AND BTypeID2=@starBTypeID AND state IN (7,32,9,10,11,16,14) AND STypeId = @STypeId
       IF @starSerialQty<>@starPQty
       BEGIN			
			IF (ISNULL(@starPTypeID,'')='')
				BEGIN
					--SELECT 12
					SELECT @ReturnValue='受托代销商品序列号中的基本信息丢失，请查询受托代销存中序列号的商品属性！'
					GOTO SerialError
				END
				
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			
			IF(ISNULL(@starBTypeID,'')='')
				BEGIN
					SELECT @ReturnValue=''+@StypeFullName+'受托代销商品【 '+@starPTypeName+' 】存在未关联受托结算单位的序列号，请查询受托代销存中序列号的往来单位属性！'
					GOTO SerialError
				END
				
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在受托代销库中与往来单位【'+@starBTypeName+'】关联的『受托期初』数量与序列号总数不一致，
由于该商品存在未进行受托代销结算的情况，请重新保存期初后再开账！'
			GOTO SerialError
       END
       FETCH NEXT FROM SerialStarManage_cursor INTO @starPTypeID,@starBTypeID,@starPQty
END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

--2、以Gp_initPTypeSerial为主

DECLARE SerialStarManage_cursor CURSOR FOR 
	SELECT COUNT(Serial) AS COUNT,PTypeID,BTypeID2 FROM gp_initptypeserial WHERE state IN (7,32,9,10,11,16,14) AND STypeid = @STypeId GROUP BY PTypeID,BTypeID2
OPEN SerialStarManage_cursor
FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starBTypeID
WHILE @@Fetch_Status = 0 
BEGIN
       SELECT @starPQty=ISNULL(SUM(Qty),0) FROM inicommissionStock WHERE PTypeID=@starPTypeID AND BTypeID=@starBTypeID AND Type = 144 AND STypeID = @STypeId
       IF @starSerialQty<>@starPQty
       BEGIN
			IF (ISNULL(@starPTypeID,'')='')
				BEGIN
					--SELECT 13
					SELECT @ReturnValue='受托代销商品序列号中的基本信息丢失，请查询受托代销存中序列号的商品属性,往来单位属性！'
					GOTO SerialError
				END
				
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@starPTypeID
			
			IF(ISNULL(@starBTypeID,'')='')
				BEGIN
					SELECT @ReturnValue=''+@StypeFullName+'受托代销商品【 '+@starPTypeName+' 】存在未关联受托结算单位的序列号，请查询受托代销存中序列号的往来单位属性！'
					GOTO SerialError
				END
				
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@starBTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在受托代销库中与往来单位【'+@starBTypeName+'】关联的『受托期初』数量与序列号总数不一致，请核查修正后再开账！'
			GOTO SerialError
       END       
       FETCH NEXT FROM SerialStarManage_cursor INTO @starSerialQty,@starPTypeID,@starBTypeID
END
CLOSE  SerialStarManage_cursor
DEALLOCATE SerialStarManage_cursor

--系统采用序列号借欠出入库校验模式  谢吉康  2003-12-21
DECLARE @mngLendSerial 	INT
DECLARE @LendQty		 NUMERIC(24, 10) 
DECLARE @LendSerial		VARCHAR(100)
DECLARE @LendBTypeID1	VARCHAR(50)
DECLARE @LendBTypeID2	VARCHAR(50)
DECLARE @LendPTypeID	VARCHAR(50)
DECLARE @LendKTypeID	VARCHAR(50)

DECLARE @iniLendQty		 NUMERIC(24, 10) 
DECLARE @iniSerial		VARCHAR(1000)

SET @iniLendQty = 0

DECLARE @PromptLendSerial  INT	--提示借欠的数量是否大于序列号的数量

SET @PromptLendSerial = 0

SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--专门处理有序列号没有商品的情况
IF EXISTS(	SELECT TOP 1 1 
			FROM GP_initLendPTypeSerial ps 
			LEFT JOIN iniGoodsLend A ON ps.PtypeID=a.PtypeId AND ps.KtypeID=a.KtypeId
			INNER JOIN PType P ON p.typeId=ps.PtypeID
			INNER JOIN #ktype k ON k.typeid=ps.KtypeID
			WHERE	P.IfSerial=1 
					AND ps.KTypeId = k.typeid
					AND a.PtypeId IS NULL
		  )
BEGIN
	SELECT	TOP 1 @LendPTypeID=ps.ptypeid,
			@LendBTypeID2=ISNULL(ps.BTypeID1,ps.BtypeID2),
			@LendKTypeID=ps.KtypeID
	FROM GP_initLendPTypeSerial ps 
	LEFT JOIN iniGoodsLend A ON ps.PtypeID=a.PtypeId AND ps.KtypeID=a.KtypeId
	INNER JOIN PType P ON p.typeId=ps.PtypeID
	INNER JOIN #ktype k ON k.typeid=ps.KtypeID
	WHERE	P.IfSerial=1 
			AND ps.KTypeId = k.typeid
			AND a.PtypeId IS NULL
	SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@LendPTypeID
	SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@LendBTypeID2
	SELECT @starKTypeName=FullName FROM #Ktype WHERE TypeID=@LendKTypeID
	SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在借欠期初库中与往来单位【'+@starBTypeName+'】关联并与仓库【'+@starKTypeName+'】的数量与序列号总数不一致，请核查修正后再开账'
	GOTO SerialError
END
--检测借进的序列号期初与借欠期初的数量是否相同   谢吉康  2003-12-21
DECLARE LendPTypeSerial_Cursor CURSOR	FOR	
	SELECT SUM(ISNULL(A.BorrowQty,0)) AS Qty,A.PTypeID,A.BTypeID,A.KTypeID FROM iniGoodsLend A,PType P,#ktype k WHERE A.PTypeID = P.TypeID AND P.IfSerial=1 AND a.KTypeId = k.typeid GROUP BY A.PTypeID,A.BTypeID,A.KTypeID

OPEN LendPTypeSerial_Cursor
FETCH NEXT FROM LendPTypeSerial_Cursor INTO @LendQty,@LendPTypeID,@LendBTypeID2,@LendKTypeID
WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT @iniLendQty=COUNT(Serial) FROM GP_initLendPTypeSerial WHERE State = 17 AND Flag = 1 AND BTypeID2=@LendBTypeID2 AND PTypeID=@LendPTypeID AND KTypeID=@LendKTypeID 

		IF ISNULL(@iniLendQty,0) = 0
			SET @iniLendQty = 0	

		IF @LendQty <> @iniLendQty
		BEGIN
			IF (ISNULL(@LendPTypeID,'')='')
				BEGIN
					SELECT @ReturnValue='借欠商品序列号中的基本信息丢失，请查询借欠商品库中序列号的商品属性,往来单位属性和仓库属性！'
					GOTO SerialError
				END
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@LendPTypeID
			
			IF ((ISNULL(@LendBTypeID2,'')='') OR (ISNULL(@LendKTypeID,'')=''))
				BEGIN
					SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在借进期初库中基本信息丢失，请查询借欠商品库中序列号的往来单位属性和仓库属性！'
					GOTO SerialError
				END
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@LendBTypeID2
			SELECT @starKTypeName=FullName FROM #Ktype WHERE TypeID=@LendKTypeID
			SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在借进期初库中与往来单位【'+@starBTypeName+'】关联并与仓库【'+@starKTypeName+'】的数量与序列号总数不一致，请核查修正后再开账'
			GOTO SerialError
		END
		FETCH NEXT FROM LendPTypeSerial_Cursor INTO @LendQty,@LendPTypeID,@LendBTypeID2,@LendKTypeID
	END
CLOSE LendPTypeSerial_Cursor
DEALLOCATE LendPTypeSerial_Cursor


--检测借出的序列号期初与借欠期初的数量是否相同   谢吉康  2003-12-21
SET @iniLendQty = 0
DECLARE LendPTypeSerial_Cursor CURSOR	FOR
	SELECT SUM(ISNULL(A.LendQty,0)) AS Qty,A.PTypeID,A.BTypeID,A.KTypeID FROM iniGoodsLend A,PType P,#ktype k WHERE A.PTypeID = P.TypeID AND P.IfSerial = 1 AND a.KTypeId = k.typeid GROUP BY A.PTypeID,A.BTypeID,A.KTypeID

OPEN LendPTypeSerial_Cursor
FETCH NEXT FROM LendPTypeSerial_Cursor INTO @LendQty,@LendPTypeID,@LendBTypeID1,@LendKTypeID
WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT @iniLendQty=COUNT(Serial) FROM GP_initLendPTypeSerial WHERE State = 18 AND Flag = 0 AND BTypeID1=@LendBTypeID1 AND PTypeID=@LendPTypeID AND KTypeID=@LendKTypeID

		IF ISNULL(@iniLendQty,0) = 0
			SET @iniLendQty = 0	

		IF @LendQty <> @iniLendQty
			BEGIN
				IF (ISNULL(@LendPTypeID,'')='')
					BEGIN
						SELECT @ReturnValue='借欠商品序列号中的基本信息丢失，请查询借欠商品库中序列号的商品属性！'
						GOTO SerialError
					END
					
				SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@LendPTypeID
				
				IF ((ISNULL(@LendBTypeID1,'')='') OR (ISNULL(@LendKTypeID,'')=''))
					BEGIN
						SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在借出期初库中基本信息丢失，请查询借欠商品库中序列号的往来单位属性和仓库属性！'
						GOTO SerialError
					END
				SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@LendBTypeID1
				SELECT @starKTypeName=FullName FROM Stock WHERE TypeID=@LendKTypeID
				SELECT @ReturnValue=''+@StypeFullName+'商品【 '+@starPTypeName+' 】在借出期初库中与往来单位【'+@starBTypeName+'】关联并与仓库【'+@starKTypeName+'】的数量与序列号总数不一致，请核查修正后再开账'
				GOTO SerialError
			END
			FETCH NEXT FROM LendPTypeSerial_Cursor INTO @LendQty,@LendPTypeID,@LendBTypeID1,@LendKTypeID
	END
CLOSE LendPTypeSerial_Cursor
DEALLOCATE LendPTypeSerial_Cursor

--检测是否具有效验模式
IF @mngLendSerial = 1
BEGIN
	--借进序列号的判断，是否在真实的库中有记录
	DECLARE LendPTypeSerialOrPTypeSerial_Cursor CURSOR	FOR
		SELECT a.Serial,a.PTypeID,a.BTypeID2,a.KTypeID FROM GP_initLendPTypeSerial a inner join #ktype k on a.ktypeid=k.typeid WHERE a.Flag = 1  ORDER BY a.Serial
	
	OPEN LendPTypeSerialOrPTypeSerial_Cursor
	FETCH NEXT FROM LendPTypeSerialOrPTypeSerial_Cursor INTO @LendSerial,@LendPTypeID,@LendBTypeID2,@LendKTypeID
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM GP_initPTypeSerial WHERE Flag = 1 AND Serial = @LendSerial)
		BEGIN
			IF (ISNULL(@LendPTypeID,'')='')
			BEGIN
				SELECT @ReturnValue='借欠商品序列号中的基本信息丢失，请查询借欠商品库中序列号的商品属性！'
				GOTO SerialError
			END
			
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@LendPTypeID
			
			IF((ISNULL(@LendBTypeID2,'')='') OR (ISNULL(@LendKTypeID,'')=''))
			BEGIN
				SELECT @ReturnValue='借欠商品【'+@starPTypeName+'】序列号中的基本信息丢失，请查询借欠商品库中序列号的往来单位属性和仓库属性！'
				GOTO SerialError
			END
			
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@LendBTypeID2
			SELECT @starKTypeName=FullName FROM #ktype WHERE TypeID=@LendKTypeID
			SELECT @ReturnValue='由于系统采用序列号借欠出入库校验模式，序列号【 '+@LendSerial+' 】在借欠期初库中关联往来单位【'+@starBTypeName+'】,商品【'+@starPTypeName+'】,仓库【'+@starKTypeName+'】与当前序列号期初库中的序列号相同，不能开账，请核查修正后再开账'
			GOTO SerialError
		END
		FETCH NEXT FROM LendPTypeSerialOrPTypeSerial_Cursor INTO @LendSerial,@LendPTypeID,@LendBTypeID2,@LendKTypeID
	END
	CLOSE LendPTypeSerialOrPTypeSerial_Cursor
	DEALLOCATE LendPTypeSerialOrPTypeSerial_Cursor

	SET @iniSerial=''
	SET @LendSerial=''

	--借出序列号的判断，是否在真实的库中有记录
	DECLARE LendPTypeSerialOrPTypeSerial_Cursor1 CURSOR	FOR
		SELECT a.Serial,a.PTypeID,a.BTypeID1,a.KTypeID FROM GP_initLendPTypeSerial a  inner join #ktype k on a.ktypeid=k.typeid WHERE a.Flag=0  ORDER BY a.Serial
	
	OPEN LendPTypeSerialOrPTypeSerial_Cursor1
	FETCH NEXT FROM LendPTypeSerialOrPTypeSerial_Cursor1 INTO @LendSerial,@LendPTypeID,@LendBTypeID1,@LendKTypeID
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM GP_initPTypeSerial WHERE Flag = 0 AND Serial = @LendSerial)
		BEGIN
			IF (ISNULL(@LendPTypeID,'')='')
			BEGIN
				SELECT @ReturnValue='借欠商品序列号中的基本信息丢失，请查询借欠商品库中序列号的商品属性！'
				GOTO SerialError
			END
			
			SELECT @starPTypeName=FullName FROM PType WHERE TypeID=@LendPTypeID
			
			IF((ISNULL(@LendBTypeID1,'')='') OR (ISNULL(@LendKTypeID,'')=''))
			BEGIN
				SELECT @ReturnValue='借欠商品【'+@starPTypeName+'】序列号中的基本信息丢失，请查询借欠商品库中序列号的往来单位属性和仓库属性！'
				GOTO SerialError
			END
			
			SELECT @starBTypeName=FullName FROM BType WHERE TypeID=@LendBTypeID1
			SELECT @starKTypeName=FullName FROM #ktype WHERE TypeID=@LendKTypeID
			SELECT @ReturnValue='由于系统采用序列号借欠出入库校验模式，序列号【 '+@LendSerial+' 】在借欠期初库中关联往来单位【'+@starBTypeName+'】,商品【'+@starPTypeName+'】,仓库【'+@starKTypeName+'】与当前序列号期初库中的序列号相同，不能开账，请核查修正后再开账'
			GOTO SerialError
		END

		IF NOT EXISTS(SELECT TOP 1 1 FROM GP_initPTypeSerial WHERE Serial = @LendSerial AND Flag = 1 AND PTypeID = @LendPTypeID AND KTypeID = @LendKTypeID)
		BEGIN
			SELECT @ReturnValue='因为采用了借欠出入库效验模式，借出序列号【 '+@LendSerial+' 】的商品与仓库属性与真实库中的不一致，请确认后重试！'
			GOTO SerialError
		END
		FETCH NEXT FROM LendPTypeSerialOrPTypeSerial_Cursor1 INTO @LendSerial,@LendPTypeID,@LendBTypeID1,@LendKTypeID
	END
	CLOSE LendPTypeSerialOrPTypeSerial_Cursor1
	DEALLOCATE LendPTypeSerialOrPTypeSerial_Cursor1
END

--序列号严密关联
DECLARE
	@intserialrelation	INT,
	@strTempSerial		VARCHAR(1000)
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

IF @intserialrelation=1
BEGIN
	--判断库存期初(需要把受托代销的库存部分加进去判断),注意看下是否要去掉仓库和货位,因为受托那边KTYPEID=10000,CARGOID=0
	IF EXISTS(
		SELECT a.PTypeID,a.KTypeID
		FROM 
		(
			SELECT	PtypeID,KtypeID,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SUM(Qty) AS SerialCount
			FROM
			(
				SELECT PtypeID,KtypeID,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,Qty
				FROM Ini_GOODSSTOCKS_QTY G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			) a
			GROUP BY PtypeID,KtypeID,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,KtypeID,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (1,7)
			GROUP BY PtypeID,KtypeID,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.KtypeID=b.KtypeID AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		INNER JOIN PType c
		ON a.PTypeID=c.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0) AND c.IfSerial=1
	)
	BEGIN
		SELECT TOP 1 @starKTypeName=d.FullName,@starPTypeName=c.FullName
		FROM 
		(
			SELECT	PtypeID,KtypeID,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SUM(Qty) AS SerialCount
			FROM
			(
				SELECT PtypeID,KtypeID,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,Qty
				FROM Ini_GOODSSTOCKS_QTY G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			) a
			GROUP BY PtypeID,KtypeID,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,KtypeID,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (1,7)
			GROUP BY PtypeID,KtypeID,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.KtypeID=b.KtypeID AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		INNER JOIN PTYPE c
		ON a.PTypeID=c.typeId
		INNER JOIN Stock d
		ON a.KTypeID=d.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0)
		AND c.IfSerial=1
		
		
		SELECT @ReturnValue='序列号严密关联模式下，仓库【 '+@starKTypeName+' 】的商品【 '+@starPTypeName+' 】库存数量跟序列号数量不一致，请按批号/生产日期/效期至/自由项/货位等分别确认后重试！'
			GOTO SerialError
	END


	--判断受托期初
	--受托已出库
	
	IF EXISTS(
		SELECT a.PTypeID,a.Btypeid
		FROM 
		(
			SELECT PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType AS State,SUM(Qty) AS SerialCount
			FROM IniCommissionStock_Qty G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE DealType=2 AND Type=144
			GROUP BY PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,BtypeID2 AS BTypeID,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (9,10,11,16,14)
			GROUP BY PtypeID,Btypeid2,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Btypeid=b.Btypeid AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		AND a.State=b.State
		INNER JOIN PType c
		ON a.PTypeID=c.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0) AND c.IfSerial=1 
	)
	BEGIN
		SELECT TOP 1 @starBTypeName=d.FullName,@starPTypeName=c.FullName
		FROM 
		(
			SELECT PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType AS State,SUM(Qty) AS SerialCount
			FROM IniCommissionStock_Qty G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE DealType=2 AND Type=144
			GROUP BY PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,BtypeID2 AS BTypeID,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (9,10,11,14,16)
			GROUP BY PtypeID,Btypeid2,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Btypeid=b.Btypeid AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		AND a.State=b.State
		INNER JOIN PTYPE c
		ON a.PTypeID=c.typeId
		INNER JOIN btype d
		ON a.Btypeid=d.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0)
		AND c.IfSerial=1
		
		SELECT @ReturnValue='序列号严密关联模式下，往来单位【 '+@starBTypeName+' 】的商品【 '+@starPTypeName+' 】受托已出库数量跟序列号数量不一致，请按批号/生产日期/效期至/自由项/货位/序列号状态等分别确认后重试！'
			GOTO SerialError
	END
	
	--受托已委托判断受托部分
	IF EXISTS(
		SELECT a.PTypeID,a.Btypeid
		FROM 
		(
			SELECT PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType AS State,SUM(Qty) AS SerialCount
			FROM IniCommissionStock_Qty G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE DealType=1 AND Type=144
			GROUP BY PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,Btypeid2 AS Btypeid,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (32)
			GROUP BY PtypeID,BTypeID2,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Btypeid=b.Btypeid AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		AND a.State=b.State
		INNER JOIN PType c
		ON a.PTypeID=c.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0) AND C.IfSerial=1
	)
	BEGIN
		SELECT TOP 1 @starBTypeName=d.FullName,@starPTypeName=c.FullName
		FROM 
		(
			SELECT PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType AS State,SUM(Qty) AS SerialCount
			FROM IniCommissionStock_Qty G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE DealType=1 AND Type=144
			GROUP BY PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,Btypeid2 AS Btypeid,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (32)
			GROUP BY PtypeID,BTypeID2,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Btypeid=b.Btypeid AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		AND a.State=b.State
		INNER JOIN PTYPE c
		ON a.PTypeID=c.typeId
		INNER JOIN Btype d
		ON a.Btypeid=d.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0)
		AND c.IfSerial=1
		
		SELECT @ReturnValue='序列号严密关联模式下，往来单位【 '+@starBTypeName+' 】的商品【 '+@starPTypeName+' 】受托委托已发货数量跟序列号数量不一致，请按批号/生产日期/效期至/自由项/货位/序列号状态等分别确认后重试！'
			GOTO SerialError
	END
	
	----受托已委托判断委托部分
	IF EXISTS(
		SELECT a.PTypeID,a.Btypeid
		FROM 
		(
			SELECT PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType AS State,SUM(Qty) AS SerialCount
			FROM IniCommissionStock_Qty G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE DealType=1 AND Type=140
			GROUP BY PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,Btypeid1 AS Btypeid,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (32)
			GROUP BY PtypeID,BTypeID1,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Btypeid=b.Btypeid AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		AND a.State=b.State
		INNER JOIN PType c
		ON a.PTypeID=c.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0) AND C.IfSerial=1
	)
	BEGIN
		SELECT TOP 1 @starBTypeName=d.FullName,@starPTypeName=c.FullName
		FROM 
		(
			SELECT PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType AS State,SUM(Qty) AS SerialCount
			FROM IniCommissionStock_Qty G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE DealType=1 AND Type=140
			GROUP BY PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,Btypeid1 AS Btypeid,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (32)
			GROUP BY PtypeID,BTypeID1,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Btypeid=b.Btypeid AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		AND a.State=b.State
		INNER JOIN PTYPE c
		ON a.PTypeID=c.typeId
		INNER JOIN Btype d
		ON a.Btypeid=d.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0)
		AND c.IfSerial=1
		
		SELECT @ReturnValue='序列号严密关联模式下，往来单位【 '+@starBTypeName+' 】的商品【 '+@starPTypeName+' 】受托委托已发货数量跟序列号数量不一致，请按批号/生产日期/效期至/自由项/货位/序列号状态等分别确认后重试！'
			GOTO SerialError
	END
	
	
	
	--判断委托期初
	
	IF EXISTS(
		SELECT a.PTypeID,a.Btypeid
		FROM 
		(
			SELECT PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType AS State,SUM(Qty) AS SerialCount
			FROM IniCommissionStock_Qty G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE DealType=0 AND Type=140
			GROUP BY PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,Btypeid1 AS Btypeid,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (13)
			GROUP BY PtypeID,BTypeID1,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Btypeid=b.Btypeid AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		AND a.State=b.State
		INNER JOIN PType c
		ON a.PTypeID=c.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0) AND C.IfSerial=1
	)
	BEGIN
		SELECT TOP 1 @starBTypeName=d.FullName,@starPTypeName=c.FullName
		FROM 
		(
			SELECT PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType AS State,SUM(Qty) AS SerialCount
			FROM IniCommissionStock_Qty G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE DealType=0 AND Type=140
			GROUP BY PtypeID,Btypeid,GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,SerialType
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,Btypeid1 AS Btypeid,CostPrice AS GoodsCostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (13)
			GROUP BY PtypeID,BTypeID1,CostPrice,GoodsNumber,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Btypeid=b.Btypeid AND a.GoodsCostPrice=b.GoodsCostPrice
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.CargoID=b.CargoID AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		AND a.State=b.State
		INNER JOIN PTYPE c
		ON a.PTypeID=c.typeId
		INNER JOIN Btype d
		ON a.Btypeid=d.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0)
		AND c.IfSerial=1
		
		SELECT @ReturnValue='序列号严密关联模式下，往来单位【 '+@starBTypeName+' 】的商品【 '+@starPTypeName+' 】库存委托已发货数量跟序列号数量不一致，请按批号/生产日期/效期至/自由项/货位/序列号状态等分别确认后重试！'
			GOTO SerialError
	END
	
	
	
	--判断维修期初
	IF EXISTS(
		SELECT a.PTypeID,a.Ktypeid
		FROM 
		(
			SELECT PtypeID,Ktypeid,GoodsNumber,ItemID,IsCombined,ProduceDate,ValidDate,SUM(Qty) AS SerialCount
			FROM wx_IniGoodsStocks G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			GROUP BY PtypeID,Ktypeid,GoodsNumber,ItemID,IsCombined,ProduceDate,ValidDate
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,Ktypeid,GoodsNumber,ItemID,IsCombined,ProduceDate,ValidDate,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (25)
			GROUP BY PtypeID,Ktypeid,GoodsNumber,ItemID,IsCombined,ProduceDate,ValidDate
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Ktypeid=b.Ktypeid
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		INNER JOIN PType c
		ON a.PTypeID=c.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0) AND C.IfSerial=1
	)
	BEGIN
		SELECT TOP 1 @starKTypeName=d.FullName,@starPTypeName=c.FullName
		FROM 
		(
			SELECT PtypeID,Ktypeid,GoodsNumber,ItemID,IsCombined,ProduceDate,ValidDate,SUM(Qty) AS SerialCount
			FROM wx_IniGoodsStocks G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			GROUP BY PtypeID,Ktypeid,GoodsNumber,ItemID,IsCombined,ProduceDate,ValidDate
			
		) a	
		LEFT JOIN
		(
			SELECT PtypeID,Ktypeid,GoodsNumber,ItemID,IsCombined,ProduceDate,ValidDate,COUNT(*) AS SerialCount
			FROM gp_initPtypeSerial G INNER JOIN #Ktype K ON g.KTypeID=k.TypeId
			WHERE State IN (25)
			GROUP BY PtypeID,Ktypeid,GoodsNumber,ItemID,IsCombined,ProduceDate,ValidDate
		) b
		ON 
		a.PtypeID=b.PtypeID AND a.Ktypeid=b.Ktypeid
		AND a.GoodsNumber=b.GoodsNumber AND a.ItemID=b.ItemID AND a.Iscombined=b.IsCombined
		AND a.ProduceDate=b.ProduceDate AND  a.ValidDate=b.ValidDate
		INNER JOIN PTYPE c
		ON a.PTypeID=c.typeId
		INNER JOIN Stock d
		ON a.Ktypeid=d.typeId
		WHERE a.SerialCount<>ISNULL(b.SerialCount,0)
		AND c.IfSerial=1
		
		SELECT @ReturnValue='序列号严密关联模式下，仓库【 '+@starKTypeName+' 】的商品【 '+@starPTypeName+' 】维修数量跟序列号数量不一致，请按批号/生产日期/效期至/自由项等分别确认后重试！'
			GOTO SerialError
	END
END

UPDATE  gp_initPTypeSerial			--修改代销的仓库属性 	
SET 	KtypeID = '10000',
		InKtypeTime = NULL,
		CargoID=0
WHERE 	State IN (8,9,10,11,13,16,32)

UPDATE  gp_initPTypeSerial			--修改代销的仓库属性 	
SET 	KtypeID = '10000',
		CargoID=0
WHERE 	State IN (14)

return 0

error: 
	RETURN -1
SerialError: 
	RETURN -2
DxQtyError: 
	RETURN -3
CostQtyError: 
	RETURN -8

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@STypeId		VARCHAR(50),		--	分支机构
    @ReturnValue	VARCHAR(MAX)		--  输出信息
    
    
SELECT
	@STypeID='00001'

EXEC	Gp_OkIniSerial
	@STypeId,
    @ReturnValue out	--  输出信息
    
SELECT  @ReturnValue   


*/




if exists (select * from dbo.sysobjects where id = object_id(N'Gp_OkIniStockAge') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure Gp_OkIniStockAge
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*


开账库龄处理，主要计算规则：
1，如果在期初库存不存在的商品,仓库,那么直接删除
2，如果在期初库龄中只有一条的商品仓库对应记录,那么直接取期初库存的数量和金额
3，如果在期初库龄中不存在的商品,在期初库存中存在的,那么直接新增一条记录,时间取服务器当前时间-1
4，如果在期初库龄和期初库存中都存在,且数量不一致的,且期初库龄不止一条的如果期初库存比期初库龄的数量大,那么直接把最后一个库龄的数量改为相差的数量,金额即可
5，如果在期初库龄和期初库存中都存在,且数量不一致的,且期初库龄不止一条的,如果期初库存比期初库龄的数量小,那么需要一个算法,看需要删除几条库龄,让数量匹配

备注：
这个是开账库龄处理的，规整了些不规范的的数据；因为是临时处理的，并没有针对分支机构来处理，是所有分支机构都处理了的

时间：2016-12-22
作者：冯波


尹聪2017-09-18确认，分支机构和集团的库龄，无法通过库存期初表来算，所以屏蔽掉

*/
CREATE   PROCEDURE Gp_OkIniStockAge
(
	@strSTypeID		VARCHAR(1000)
)

--@encode$--
AS
BEGIN
	--处理仓库库龄(之后有配置的,就读配置)
	
	--如果库存期初全是负数,那么就删除所有的库龄数据
	
	--插入的批次日期先都取服务器日期-1,库龄为1
	DECLARE
		@strBeginDate	VARCHAR(50),
		@strYear		VARCHAR(50),
		@strMonth		VARCHAR(50),
		@strDay			VARCHAR(50)
		
	SELECT
		@strYear=CAST(YEAR(GETDATE()-1) AS VARCHAR(4)),
		@strMonth=CAST(MONTH(GETDATE()-1) AS VARCHAR(2)),
		@strDay=CAST(DAY(GETDATE()-1) AS VARCHAR(2))
		
	IF LEN(@strMonth)=1
	BEGIN
		SELECT @strMonth='0'+@strMonth
	END
	
	IF LEN(@strDay)=1
	BEGIN
		SELECT @strDay='0'+@strDay
	END
		
	SELECT @strBeginDate=@strYear+'-'+@strMonth+'-'+@strDay
	
	DECLARE
				@intCal		INT	--判断是否要继续运算，1表示需要计算，0表示不需要计算
	
	CREATE TABLE #SingleInfo
	(
		PTypeID VARCHAR(50),
		KTypeID VARCHAR(50),
		InStockDate VARCHAR(50),
		StockAge INT,
		Qty NUMERIC(24,10),
		Total NUMERIC(24,10)
	)
	
	--先建立一个临时表,记录所有数量,金额不一致的记录
	CREATE TABLE #DiffInfo
	(
		PTypeID				VARCHAR(50),
		KTypeID				VARCHAR(50),
		StockQty			NUMERIC(22,10),		--期初库存数量
		AgeQty				NUMERIC(22,10),		--期初库龄数量
		StockTotal			NUMERIC(22,10),		--期初库存金额
		AgeTotal			NUMERIC(22,10),		--期初库龄金额,
		AgeCount			INT					--库龄条数
	)
	
	
	CREATE NONCLUSTERED INDEX NCIX_DiffoInfo_Union ON #DiffInfo(PTypeID,KTypeID) 
	
	IF NOT EXISTS(
		SELECT PTypeID
		FROM IniGoodsStocks
		WHERE Qty>0
	)
	BEGIN
		TRUNCATE TABLE IniStockAgeStock
		TRUNCATE TABLE IniStockAgeStype
		TRUNCATE TABLE IniStockAgeGroup
		
		--不需要计算库龄
		RETURN
	END
	ELSE
	BEGIN
		--如果没有库龄数据，也不计算
		IF NOT EXISTS(
			SELECT PTypeID	
			FROM IniStockAgeStock
			UNION ALL
			SELECT PTypeID
			FROM IniStockAgeStype
			UNION ALL
			SELECT PTypeID
			FROM IniStockAgeGroup
		)
		BEGIN
			--不需要计算库龄
			RETURN
		END
		
		
		--判断是否存在库龄期初跟库存期初不一致的,从3个表去分别判断,如果不存在不一致的,则不计算,直接退出
		SELECT @intCal=0
		
		IF EXISTS(
			SELECT PTypeID
			FROM dbo.IniStockAgeStock
		)
		BEGIN
			IF EXISTS(
				SELECT PtypeID
				FROM IniStockAgeStock
				WHERE StockAge<0
			)
			BEGIN
				--库龄为负数的，统一改为服务器日期前一天
				UPDATE IniStockAgeStock
				SET StockAge=1,InStockDate=@strBeginDate
				WHERE StockAge<0
			END
		
			TRUNCATE TABLE #DiffInfo
			INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
			SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
			FROM
			(
				SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
				FROM dbo.IniGoodsStocks
				GROUP BY PTypeID,KTypeID
			) a
			FULL JOIN
			(
				SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
				FROM dbo.IniStockAgeStock
				GROUP BY PTypeID,KTypeID
			) b
			ON a.PTypeID=b.PTypeID
			AND a.KTypeID=b.KTypeID  
			WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
			
			IF NOT EXISTS(
				SELECT PTypeID
				FROM #DiffInfo
			)
			BEGIN
				SELECT @intCal=@intCal+1
			END
			
			TRUNCATE TABLE #DiffInfo

		END
		ELSE
		BEGIN
			SELECT @intCal=@intCal+1
		END
		
		IF EXISTS(
			SELECT PTypeID
			FROM dbo.IniStockAgeSType
		)
		BEGIN
			IF EXISTS(
				SELECT PtypeID
				FROM IniStockAgeSType
				WHERE StockAge<0
			)
			BEGIN
				--库龄为负数的，统一改为服务器日期前一天
				UPDATE IniStockAgeSType
				SET StockAge=1,InStockDate=@strBeginDate
				WHERE StockAge<0
			END
		
			TRUNCATE TABLE #DiffInfo
			INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
			SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
			FROM
			(
				SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
				FROM dbo.IniGoodsStocks
				GROUP BY PTypeID,KTypeID
			) a
			FULL JOIN
			(
				SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
				FROM dbo.IniStockAgeSType
				GROUP BY PTypeID,KTypeID
			) b
			ON a.PTypeID=b.PTypeID
			AND a.KTypeID=b.KTypeID  
			WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
			
			IF NOT EXISTS(
				SELECT PTypeID
				FROM #DiffInfo
			)
			BEGIN
				SELECT @intCal=@intCal+1
			END
			
			TRUNCATE	TABLE	#DiffInfo
		
		END
		ELSE
		BEGIN
			SELECT @intCal=@intCal+1
		END
		
		IF EXISTS(
			SELECT PTypeID
			FROM dbo.IniStockAgeGroup
		)
		BEGIN
			IF EXISTS(
				SELECT PtypeID
				FROM IniStockAgeGroup
				WHERE StockAge<0
			)
			BEGIN
				--库龄为负数的，统一改为服务器日期前一天
				UPDATE IniStockAgeGroup
				SET StockAge=1,InStockDate=@strBeginDate
				WHERE StockAge<0
			END
		
			TRUNCATE TABLE #DiffInfo
			INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
			SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
			FROM
			(
				SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
				FROM dbo.IniGoodsStocks
				GROUP BY PTypeID,KTypeID
			) a
			FULL JOIN
			(
				SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
				FROM dbo.IniStockAgeGroup
				GROUP BY PTypeID,KTypeID
			) b
			ON a.PTypeID=b.PTypeID
			AND a.KTypeID=b.KTypeID  
			WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
			
			IF NOT EXISTS(
				SELECT PTypeID
				FROM #DiffInfo
			)
			BEGIN
				SELECT @intCal=@intCal+1
			END
			
			TRUNCATE	TABLE	#DiffInfo
			
		END
		ELSE
		BEGIN
			SELECT @intCal=@intCal+1
		END
		
		IF @intCal=3
		BEGIN
			--都相等，不需要计算
			RETURN
		END
		ELSE
		BEGIN
			--判断库龄中是否有重复记录，有则清理
			IF EXISTS
			(
				SELECT PTypeID
				FROM IniStockAgeStock
				GROUP BY PtypeID,KtypeID,InStockDate
				HAVING COUNT(*)>1
			)
			BEGIN
				TRUNCATE	TABLE #SingleInfo
				
				INSERT #SingleInfo(PTypeID,KTypeID,InStockDate,StockAge,Qty,Total)
				SELECT PTypeID,KTypeID,InStockDate,StockAge,SUM(Qty),SUM(Total)
				FROM IniStockAgeStock
				GROUP BY PTypeID,KTypeID,InStockDate,StockAge
				
				TRUNCATE TABLE IniStockAgeStock
				
				INSERT IniStockAgeStock(PTypeID,KTypeID,InStockDate,StockAge,Qty,Total)
				SELECT PTypeID,KTypeID,InStockDate,StockAge,Qty,Total
				FROM #SingleInfo
				
				TRUNCATE TABLE #SingleInfo
			END
			
			IF EXISTS
			(
				SELECT PTypeID
				FROM IniStockAgeSType
				GROUP BY PtypeID,KtypeID,InStockDate
				HAVING COUNT(*)>1
			)
			BEGIN
				INSERT #SingleInfo(PTypeID,KTypeID,InStockDate,StockAge,Qty,Total)
				SELECT PTypeID,KTypeID,InStockDate,StockAge,SUM(Qty),SUM(Total)
				FROM IniStockAgeSType
				GROUP BY PTypeID,KTypeID,InStockDate,StockAge
				
				TRUNCATE TABLE IniStockAgeSType
				
				INSERT IniStockAgeSType(PTypeID,KTypeID,InStockDate,StockAge,Qty,Total)
				SELECT PTypeID,KTypeID,InStockDate,StockAge,Qty,Total
				FROM #SingleInfo
				
				TRUNCATE TABLE #SingleInfo
			END
			
			
			
			IF EXISTS
			(
				SELECT PTypeID
				FROM IniStockAgeGroup
				GROUP BY PtypeID,KtypeID,InStockDate
				HAVING COUNT(*)>1
			)
			BEGIN
				INSERT #SingleInfo(PTypeID,KTypeID,InStockDate,StockAge,Qty,Total)
				SELECT PTypeID,KTypeID,InStockDate,StockAge,SUM(Qty),SUM(Total)
				FROM IniStockAgeGroup
				GROUP BY PTypeID,KTypeID,InStockDate,StockAge
				
				TRUNCATE TABLE IniStockAgeGroup
				
				INSERT IniStockAgeGroup(PTypeID,KTypeID,InStockDate,StockAge,Qty,Total)
				SELECT PTypeID,KTypeID,InStockDate,StockAge,Qty,Total
				FROM #SingleInfo
				
				TRUNCATE TABLE #SingleInfo
			END
			--处理完同一商品,仓库,库龄有多条记录的数据
			
			
			--判断是否存在商品无库存,但是有库龄的记录,有的话,一律删除
			IF EXISTS
			(
				SELECT a.PtypeID
				FROM dbo.IniStockAgeStock a
				WHERE NOT EXISTS
				(
					SELECT b.PtypeId 
					FROM dbo.IniGoodsStocks b
					WHERE b.PtypeId=a.PtypeID
					AND b.KtypeID=a.KtypeId
				)
			)
			BEGIN
				DELETE IniStockAgeStock
				WHERE NOT EXISTS
				(
					SELECT b.PtypeId 
					FROM dbo.IniGoodsStocks b
					WHERE b.PtypeId=IniStockAgeStock.PtypeID
					AND b.KtypeID=IniStockAgeStock.KtypeId
				)
			END
			
			IF EXISTS
			(
				SELECT a.PtypeID
				FROM dbo.IniStockAgeSType a
				WHERE NOT EXISTS
				(
					SELECT b.PtypeId 
					FROM dbo.IniGoodsStocks b
					WHERE b.PtypeId=a.PtypeID
					AND b.KtypeID=a.KtypeId
				)
			)
			BEGIN
				DELETE IniStockAgeSType
				WHERE NOT EXISTS
				(
					SELECT b.PtypeId 
					FROM dbo.IniGoodsStocks b
					WHERE b.PtypeId=IniStockAgeSType.PtypeID
					AND b.KtypeID=IniStockAgeSType.KtypeId
				)
			END
			
			IF EXISTS
			(
				SELECT a.PtypeID
				FROM dbo.IniStockAgeGroup a
				WHERE NOT EXISTS
				(
					SELECT b.PtypeId 
					FROM dbo.IniGoodsStocks b
					WHERE b.PtypeId=a.PtypeID
					AND b.KtypeID=a.KtypeId
				)
			)
			BEGIN
				DELETE IniStockAgeGroup
				WHERE NOT EXISTS
				(
					SELECT b.PtypeId 
					FROM dbo.IniGoodsStocks b
					WHERE b.PtypeId=IniStockAgeGroup.PtypeID
					AND b.KtypeID=IniStockAgeGroup.KtypeId
				)
			END
			
			--处理完毕有库龄,无库存的废数据
		END
	END
	

	
				
	SELECT @intCal=1
	
	--1，先处理仓库库龄数据
	
	IF NOT EXISTS(
		SELECT PTypeID	
		FROM IniStockAgeStock
	)
	BEGIN
		--无数据，则不计算
		SELECT @intCal=0	
	END
	ELSE
	BEGIN
		TRUNCATE TABLE #DiffInfo
		INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
		SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
		FROM
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
			FROM dbo.IniGoodsStocks
			GROUP BY PTypeID,KTypeID
		) a
		FULL JOIN
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
			FROM dbo.IniStockAgeStock
			GROUP BY PTypeID,KTypeID
		) b
		ON a.PTypeID=b.PTypeID
		AND a.KTypeID=b.KTypeID  
		WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
	END
	
	IF @intCal=1
	BEGIN
		 IF NOT EXISTS
		(
			SELECT PTypeID
			FROM #DiffInfo
		)
		BEGIN
			--如果没有不相等的，则不计算
			SELECT @intCal=0
		END
		
		TRUNCATE	TABLE	#DiffInfo
	END
	
	--先对库龄数据进行规整,库龄的数量应该都是为正的.如果存在为负数的,且对应的商品仓库的库龄记录只有一条,则保留,如果不止一条,则删除最近库龄以外的所有库龄信息.这个执行完后,就可以保证,如果对应的商品,仓库存在库龄为负数的记录,那么该仓库,商品只有一条库龄记录了
	IF @intCal=1	AND	EXISTS
	(
		SELECT PTypeID
		FROM IniStockAgeStock
		WHERE Qty<0
		GROUP BY PtypeID,KtypeID,InStockDate
		HAVING COUNT(*)>0
	)
	BEGIN
		DELETE IniStockAgeStock
		FROM 
		(
			SELECT PTypeID,KtypeID
			FROM IniStockAgeStock
			WHERE Qty<0
			GROUP BY PtypeID,KtypeID,InStockDate
			HAVING COUNT(*)>0
		)	b
		WHERE IniStockAgeStock.PtypeID=b.PTypeID
		AND IniStockAgeStock.KtypeID=b.KTypeID
		AND NOT EXISTS
		(
			SELECT c.PTypeID,c.KtypeID,MAX(c.InStockDate) InStockDate
			FROM IniStockAgeStock c
			WHERE IniStockAgeStock.PtypeID=c.PtypeID
			AND IniStockAgeStock.KtypeID=c.KtypeID
			GROUP BY c.PtypeID,c.KtypeID
			HAVING IniStockAgeStock.InStockDate=MAX(c.InStockDate)
			
		)
	END

	
	IF @intCal=1
	BEGIN
		TRUNCATE TABLE #DiffInfo
		INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
		SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
		FROM
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
			FROM dbo.IniGoodsStocks
			GROUP BY PTypeID,KTypeID
		) a
		FULL JOIN
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
			FROM dbo.IniStockAgeStock
			GROUP BY PTypeID,KTypeID
		) b
		ON a.PTypeID=b.PTypeID
		AND a.KTypeID=b.KTypeID  
		WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
	END 
	
	IF @intCal=1
	BEGIN
		IF NOT EXISTS
		(
			--判断数量金额是否一致
			SELECT PTypeID
			FROM #DiffInfo
		)
		BEGIN
			--不需要重算库龄就退出
			SELECT @intCal=0
		END
		ELSE
		BEGIN
				--如果在期初库存不存在的商品,仓库,那么直接删除
				
				IF EXISTS(
					SELECT b.PtypeID
					FROM IniStockAgeStock b
					WHERE NOT EXISTS(
						SELECT PTypeID 
						FROM dbo.IniGoodsStocks a
						WHERE a.PTypeID=b.PtypeID
						AND a.KtypeId=b.KtypeID
					)
				)
				BEGIN
					DELETE IniStockAgeStock
					WHERE NOT EXISTS(
						SELECT PTypeID 
						FROM dbo.IniGoodsStocks a
						WHERE a.PTypeID=IniStockAgeStock.PtypeID
						AND a.KtypeId=IniStockAgeStock.KtypeID
					)
				END
				
				
				
				--如果在期初库龄中只有一条的商品,那么直接取期初库存的数量和金额
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE StockQty<>AgeQty AND AgeCount=1
				)
				BEGIN
					UPDATE IniStockAgeStock
					SET Qty=b.StockQty,Total=b.StockTotal
					FROM #DiffInfo b
					WHERE IniStockAgeStock.PtypeID=b.PTypeID
					AND IniStockAgeStock.KtypeID=b.KTypeID
					AND b.StockQty<>b.AgeQty
					AND b.AgeCount=1
				END
				
				
				--如果在期初库龄中不存在的商品,在期初库存中存在的,那么直接新增一条记录,时间取服务器当前时间-1
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount=0 AND StockQty<>0
				)
				BEGIN
					INSERT IniStockAgeStock(PtypeID,KTypeID,InStockDate,StockAge,Qty,Total)
					SELECT PtypeID,KTypeID,@strBeginDate,1,StockQty,StockTotal
					FROM #DiffInfo
					WHERE AgeCount=0 AND StockQty<>0
				END
				

				
				
				--重算#DiffInfo
				
				TRUNCATE TABLE #DiffInfo
				
				INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
				SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
				FROM
				(
					SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
					FROM dbo.IniGoodsStocks
					GROUP BY PTypeID,KTypeID
				) a
				FULL JOIN
				(
					SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
					FROM dbo.IniStockAgeStock
					GROUP BY PTypeID,KTypeID
				) b
				ON a.PTypeID=b.PTypeID
				AND a.KTypeID=b.KTypeID  
				WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
				
				
				
				
				--如果在期初库龄和期初库存中都存在,且数量不一致的,且期初库龄不止一条的如果期初库存比期初库龄的数量大,那么直接把最后一个库龄的数量改为相差的数量,金额即可
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount>1 AND (StockQty>AgeQty)
				)
				BEGIN
					UPDATE IniStockAgeStock
					SET Qty=IniStockAgeStock.Qty+b.Qty,Total=IniStockAgeStock.Total+b.Total
					FROM
					(
						SELECT PTypeID,KTypeID,StockQty-AgeQty Qty,StockTotal-AgeTotal Total
						FROM #DiffInfo
						WHERE AgeCount>1 AND (StockQty>AgeQty)
					) b,
					(
						SELECT c.PTypeID,c.KtypeID,MAX(c.InStockDate) InStockDate
						FROM IniStockAgeStock c
						GROUP BY c.PtypeID,c.KtypeID
						HAVING COUNT(*)>1
					) c
					WHERE IniStockAgeStock.PtypeID=b.PTypeID
					AND IniStockAgeStock.KtypeID=b.KTypeID
					AND IniStockAgeStock.PtypeID=c.PTypeID
					AND IniStockAgeStock.KtypeID=c.KTypeID
					AND IniStockAgeStock.InStockDate=c.InStockDate
					
				END
				
		
				
				
				--如果在期初库龄和期初库存中都存在,且数量不一致的,且期初库龄不止一条的,如果期初库存比期初库龄的数量小,那么需要一个算法,看需要删除几条库龄,让数量匹配
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount>1 AND (StockQty<AgeQty)
				)
				BEGIN
					--通过MERGE来处理
					
					SELECT @intCal=1
					
					WHILE (@intCal=1)
					BEGIN
						--判断时间最早的那条库龄记录的数量,如果比差值大,则它的数量改成本身减差值;如果比差值小,则直接删除
						
						--如果库龄只有一条记录,且数量不相等,则直接相等即可
						IF EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE StockQty<>AgeQty AND AgeCount=1
						)
						BEGIN
							UPDATE IniStockAgeStock
							SET Qty=b.StockQty,Total=b.StockTotal
							FROM #DiffInfo b
							WHERE IniStockAgeStock.PtypeID=b.PTypeID
							AND IniStockAgeStock.KtypeID=b.KTypeID
							AND b.StockQty<>b.AgeQty
							AND b.AgeCount=1
						END
						
						
						
						TRUNCATE TABLE #DiffInfo
				
						INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
						SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
						FROM
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
							FROM dbo.IniGoodsStocks
							GROUP BY PTypeID,KTypeID
						) a
						FULL JOIN
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
							FROM dbo.IniStockAgeStock
							GROUP BY PTypeID,KTypeID
						) b
						ON a.PTypeID=b.PTypeID
						AND a.KTypeID=b.KTypeID  
						WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
						
						
						--如果库存数量小于最近一条的库龄数量,那么只保留最近一条的库龄数量,将库龄数量改成库存数量即可,其他的库龄信息删除
						IF EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE StockQty<=AgeQty AND AgeCount>1
						)
						BEGIN
							IF EXISTS(
								SELECT a.PTypeID
								FROM #DiffInfo	a,
								(
									SELECT b.*
									FROM IniStockAgeStock b
									WHERE EXISTS
									(
										SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
										FROM IniStockAgeStock c
										GROUP BY c.PtypeID,c.KtypeID
										HAVING c.PTypeID=b.PtypeID
										AND c.KtypeID=b.KtypeID
									)
								) b
								WHERE a.PTypeID=b.PtypeID
								AND a.KTypeID=b.KtypeID
								AND a.StockQty<=b.Qty
								AND a.StockQty<=a.AgeQty AND a.AgeCount>1
							)
							BEGIN
								UPDATE IniStockAgeStock
								SET Qty=b.StockQty,Total=b.StockTotal
								FROM #DiffInfo b
								WHERE IniStockAgeStock.PTypeID=b.PTypeID
								AND IniStockAgeStock.KTypeID=b.KTypeID
								AND b.StockQty<=b.AgeQty AND b.AgeCount>1
								AND EXISTS
								(
									SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
									FROM IniStockAgeStock c
									GROUP BY c.PtypeID,c.KtypeID
									HAVING c.PTypeID=IniStockAgeStock.PtypeID
									AND c.KtypeID=IniStockAgeStock.KtypeID
									AND IniStockAgeStock.InStockDate=MIN(c.InStockDate)
								)
								
								DELETE IniStockAgeStock
								FROM #DiffInfo b
								WHERE IniStockAgeStock.PTypeID=b.PTypeID
								AND IniStockAgeStock.KTypeID=b.KTypeID
								AND b.StockQty<=b.AgeQty AND b.AgeCount>1
								AND EXISTS
								(
									SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
									FROM IniStockAgeStock c
									GROUP BY c.PtypeID,c.KtypeID
									HAVING c.PTypeID=IniStockAgeStock.PtypeID
									AND c.KtypeID=IniStockAgeStock.KtypeID
									AND IniStockAgeStock.InStockDate<>MIN(c.InStockDate)
								)
								
								
								TRUNCATE TABLE #DiffInfo
				
								INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
								SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
								FROM
								(
									SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
									FROM dbo.IniGoodsStocks
									GROUP BY PTypeID,KTypeID
								) a
								FULL JOIN
								(
									SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
									FROM dbo.IniStockAgeStock
									GROUP BY PTypeID,KTypeID
								) b
								ON a.PTypeID=b.PTypeID
								AND a.KTypeID=b.KTypeID  
								WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
							END
						END
						
						
						DELETE IniStockAgeStock
						FROM 
						(
							SELECT PTypeID,KTypeID,AgeQty-StockQty Qty
							FROM #DiffInfo
							WHERE AgeCount>1 AND (StockQty<AgeQty)
						) b,
						(
							SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
							FROM IniStockAgeStock c
							GROUP BY c.PtypeID,c.KtypeID
						) c
						WHERE IniStockAgeStock.PtypeID=b.PTypeID
						AND IniStockAgeStock.KtypeID=b.KTypeID
						AND IniStockAgeStock.Qty<=b.Qty
						AND IniStockAgeStock.PtypeID=c.PtypeID
						AND IniStockAgeStock.KtypeID=c.KtypeID
						AND IniStockAgeStock.InStockDate=c.InStockDate
						
						
						UPDATE IniStockAgeStock
						SET Qty=IniStockAgeStock.Qty-b.Qty,Total=IniStockAgeStock.Total-b.Total
						FROM 
						(
							SELECT PTypeID,KTypeID,AgeQty-StockQty Qty,AgeTotal-StockTotal Total
							FROM #DiffInfo
							WHERE AgeCount>1 AND (StockQty<AgeQty)
						) b,
						(
							SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
							FROM IniStockAgeStock c
							GROUP BY c.PtypeID,c.KtypeID
						) c
						WHERE IniStockAgeStock.PtypeID=b.PTypeID
						AND IniStockAgeStock.KtypeID=b.KTypeID
						AND IniStockAgeStock.Qty>b.Qty
						AND IniStockAgeStock.PtypeID=c.PtypeID
						AND IniStockAgeStock.KtypeID=c.KtypeID
						AND IniStockAgeStock.InStockDate=c.InStockDate
						
					
						
					
						TRUNCATE TABLE #DiffInfo
						
						INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
						SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
						FROM
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
							FROM dbo.IniGoodsStocks
							GROUP BY PTypeID,KTypeID
						) a
						FULL JOIN
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
							FROM dbo.IniStockAgeStock
							GROUP BY PTypeID,KTypeID
						) b
						ON a.PTypeID=b.PTypeID
						AND a.KTypeID=b.KTypeID  
						WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0)
						
					
					
						
						IF NOT EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE (StockQty<AgeQty)
						)
						BEGIN
							--如果不存在期初库存比期初库龄小了,则退出循环
							SELECT @intCal=0
						END 
					
					END
					
					
				END
		END
		
	END
	
	
	/*
	SELECT @intCal=1
	
	--2，处理分支机构库龄
	
	IF NOT EXISTS(
		SELECT PTypeID	
		FROM IniStockAgeSType
	)
	BEGIN
		--无数据，则不计算
		SELECT @intCal=0	
	END
	ELSE
	BEGIN
		TRUNCATE TABLE #DiffInfo
		INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
		SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
		FROM
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
			FROM dbo.IniGoodsStocks
			GROUP BY PTypeID,KTypeID
		) a
		FULL JOIN
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
			FROM dbo.IniStockAgeSType
			GROUP BY PTypeID,KTypeID
		) b
		ON a.PTypeID=b.PTypeID
		AND a.KTypeID=b.KTypeID  
		WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
	END
	
	IF @intCal=1
	BEGIN
		 IF NOT EXISTS
		(
			SELECT PTypeID
			FROM #DiffInfo
		)
		BEGIN
			--如果没有不相等的，则不计算
			SELECT @intCal=0
		END
		
		TRUNCATE TABLE #DiffInfo
	END
	
	
	--先对库龄数据进行规整,库龄的数量应该都是为正的.如果存在为负数的,且对应的商品仓库的库龄记录只有一条,则保留,如果不止一条,则删除最近库龄以外的所有库龄信息.这个执行完后,就可以保证,如果对应的商品,仓库存在库龄为负数的记录,那么该仓库,商品只有一条库龄记录了
	IF @intCal=1 AND EXISTS
	(
		SELECT PTypeID
		FROM IniStockAgeStype
		WHERE Qty<0
		GROUP BY PtypeID,KtypeID,InStockDate
		HAVING COUNT(*)>0
	)
	BEGIN
		DELETE IniStockAgeStype
		FROM 
		(
			SELECT PTypeID,KtypeID
			FROM IniStockAgeStype
			WHERE Qty<0
			GROUP BY PtypeID,KtypeID,InStockDate
			HAVING COUNT(*)>0
		)	b
		WHERE IniStockAgeStype.PtypeID=b.PTypeID
		AND IniStockAgeStype.KtypeID=b.KTypeID
		AND NOT EXISTS
		(
			SELECT c.PTypeID,c.KtypeID,MAX(c.InStockDate) InStockDate
			FROM IniStockAgeStype c
			WHERE IniStockAgeStype.PtypeID=c.PtypeID
			AND IniStockAgeStype.KtypeID=c.KtypeID
			GROUP BY c.PtypeID,c.KtypeID
			HAVING IniStockAgeStype.InStockDate=MAX(c.InStockDate)
			
		)
	END
	
	
	--先建立一个临时表,记录所有数量,金额不一致的记录
	
	IF @intCal=1
	BEGIN
		TRUNCATE	TABLE	#DiffInfo
		
		INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
		SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
		FROM
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
			FROM dbo.IniGoodsStocks
			GROUP BY PTypeID,KTypeID
		) a
		FULL JOIN
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
			FROM dbo.IniStockAgeStype
			GROUP BY PTypeID,KTypeID
		) b
		ON a.PTypeID=b.PTypeID
		AND a.KTypeID=b.KTypeID  
		WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
	END
	
	IF @intCal=1
	BEGIN
		IF	NOT EXISTS
		(
			--判断数量金额是否一致
			SELECT PTypeID
			FROM #DiffInfo
		)
		BEGIN
			--不需要重算库龄就退出
			SELECT @intCal=0
		END
		ELSE
		BEGIN
				
				--如果在期初库存不存在的商品,仓库,那么直接删除
				
				IF EXISTS(
					SELECT b.PtypeID
					FROM IniStockAgeStype b
					WHERE NOT EXISTS(
						SELECT PTypeID 
						FROM dbo.IniGoodsStocks a
						WHERE a.PTypeID=b.PtypeID
						AND a.KtypeId=b.KtypeID
					)
				)
				BEGIN
					DELETE IniStockAgeStype
					WHERE NOT EXISTS(
						SELECT PTypeID 
						FROM dbo.IniGoodsStocks a
						WHERE a.PTypeID=IniStockAgeStype.PtypeID
						AND a.KtypeId=IniStockAgeStype.KtypeID
					)
				END
				
				
				
				--如果在期初库龄中只有一条的商品,那么直接取期初库存的数量和金额
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE StockQty<>AgeQty AND AgeCount=1
				)
				BEGIN
					UPDATE IniStockAgeStype
					SET Qty=b.StockQty,Total=b.StockTotal
					FROM #DiffInfo b
					WHERE IniStockAgeStype.PtypeID=b.PTypeID
					AND IniStockAgeStype.KtypeID=b.KTypeID
					AND b.StockQty<>b.AgeQty
					AND b.AgeCount=1
				END
				
				
				--如果在期初库龄中不存在的商品,在期初库存中存在的,那么直接新增一条记录,时间取服务器当前时间-1
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount=0 AND StockQty<>0
				)
				BEGIN
					INSERT IniStockAgeStype(PtypeID,KTypeID,InStockDate,StockAge,Qty,Total)
					SELECT PtypeID,KTypeID,@strBeginDate,1,StockQty,StockTotal
					FROM #DiffInfo
					WHERE AgeCount=0 AND StockQty<>0
				END
				
			
				
				--重算#DiffInfo
				
				TRUNCATE TABLE #DiffInfo
				
				INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
				SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
				FROM
				(
					SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
					FROM dbo.IniGoodsStocks
					GROUP BY PTypeID,KTypeID
				) a
				FULL JOIN
				(
					SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
					FROM dbo.IniStockAgeStype
					GROUP BY PTypeID,KTypeID
				) b
				ON a.PTypeID=b.PTypeID
				AND a.KTypeID=b.KTypeID  
				WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
				
				
				
				
				--如果在期初库龄和期初库存中都存在,且数量不一致的,且期初库龄不止一条的如果期初库存比期初库龄的数量大,那么直接把最后一个库龄的数量改为相差的数量,金额即可
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount>1 AND (StockQty>AgeQty)
				)
				BEGIN
					UPDATE IniStockAgeStype
					SET Qty=IniStockAgeStype.Qty+b.Qty,Total=IniStockAgeStype.Total+b.Total
					FROM
					(
						SELECT PTypeID,KTypeID,StockQty-AgeQty Qty,StockTotal-AgeTotal Total
						FROM #DiffInfo
						WHERE AgeCount>1 AND (StockQty>AgeQty)
					) b,
					(
						SELECT c.PTypeID,c.KtypeID,MAX(c.InStockDate) InStockDate
						FROM IniStockAgeStype c
						GROUP BY c.PtypeID,c.KtypeID
						HAVING COUNT(*)>1
					) c
					WHERE IniStockAgeStype.PtypeID=b.PTypeID
					AND IniStockAgeStype.KtypeID=b.KTypeID
					AND IniStockAgeStype.PtypeID=c.PTypeID
					AND IniStockAgeStype.KtypeID=c.KTypeID
					AND IniStockAgeStype.InStockDate=c.InStockDate
					
				END
				
				
				
				
				--如果在期初库龄和期初库存中都存在,且数量不一致的,且期初库龄不止一条的,如果期初库存比期初库龄的数量小,那么需要一个算法,看需要删除几条库龄,让数量匹配
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount>1 AND (StockQty<AgeQty)
				)
				BEGIN
					--通过MERGE来处理
					
					SELECT @intCal=1
					
					WHILE (@intCal=1)
					BEGIN
						--判断时间最早的那条库龄记录的数量,如果比差值大,则它的数量改成本身减差值;如果比差值小,则直接删除
						
						--如果库龄只有一条记录,且数量不相等,则直接相等即可
						IF EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE StockQty<>AgeQty AND AgeCount=1
						)
						BEGIN
							UPDATE IniStockAgeSType
							SET Qty=b.StockQty,Total=b.StockTotal
							FROM #DiffInfo b
							WHERE IniStockAgeSType.PtypeID=b.PTypeID
							AND IniStockAgeSType.KtypeID=b.KTypeID
							AND b.StockQty<>b.AgeQty
							AND b.AgeCount=1
						END
						
						
						
						TRUNCATE TABLE #DiffInfo
				
						INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
						SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
						FROM
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
							FROM dbo.IniGoodsStocks
							GROUP BY PTypeID,KTypeID
						) a
						FULL JOIN
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
							FROM dbo.IniStockAgeSType
							GROUP BY PTypeID,KTypeID
						) b
						ON a.PTypeID=b.PTypeID
						AND a.KTypeID=b.KTypeID  
						WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
						
						
						--如果库存数量小于最近一条的库龄数量,那么只保留最近一条的库龄数量,将库龄数量改成库存数量即可,其他的库龄信息删除
						IF EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE StockQty<=AgeQty AND AgeCount>1
						)
						BEGIN
							IF EXISTS(
								SELECT a.PTypeID
								FROM #DiffInfo	a,
								(
									SELECT b.*
									FROM IniStockAgeSType b
									WHERE EXISTS
									(
										SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
										FROM IniStockAgeSType c
										GROUP BY c.PtypeID,c.KtypeID
										HAVING c.PTypeID=b.PtypeID
										AND c.KtypeID=b.KtypeID
									)
								) b
								WHERE a.PTypeID=b.PtypeID
								AND a.KTypeID=b.KtypeID
								AND a.StockQty<=b.Qty
								AND a.StockQty<=a.AgeQty AND a.AgeCount>1
							)
							BEGIN
								UPDATE IniStockAgeSType
								SET Qty=b.StockQty,Total=b.StockTotal
								FROM #DiffInfo b
								WHERE IniStockAgeSType.PTypeID=b.PTypeID
								AND IniStockAgeSType.KTypeID=b.KTypeID
								AND b.StockQty<=b.AgeQty AND b.AgeCount>1
								AND EXISTS
								(
									SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
									FROM IniStockAgeSType c
									GROUP BY c.PtypeID,c.KtypeID
									HAVING c.PTypeID=IniStockAgeSType.PtypeID
									AND c.KtypeID=IniStockAgeSType.KtypeID
									AND IniStockAgeSType.InStockDate=MIN(c.InStockDate)
								)
								
								DELETE IniStockAgeSType
								FROM #DiffInfo b
								WHERE IniStockAgeSType.PTypeID=b.PTypeID
								AND IniStockAgeSType.KTypeID=b.KTypeID
								AND b.StockQty<=b.AgeQty AND b.AgeCount>1
								AND EXISTS
								(
									SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
									FROM IniStockAgeSType c
									GROUP BY c.PtypeID,c.KtypeID
									HAVING c.PTypeID=IniStockAgeSType.PtypeID
									AND c.KtypeID=IniStockAgeSType.KtypeID
									AND IniStockAgeSType.InStockDate<>MIN(c.InStockDate)
								)
								
								
								TRUNCATE TABLE #DiffInfo
				
								INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
								SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
								FROM
								(
									SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
									FROM dbo.IniGoodsStocks
									GROUP BY PTypeID,KTypeID
								) a
								FULL JOIN
								(
									SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
									FROM dbo.IniStockAgeSType
									GROUP BY PTypeID,KTypeID
								) b
								ON a.PTypeID=b.PTypeID
								AND a.KTypeID=b.KTypeID  
								WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
							END
						END
						
						DELETE IniStockAgeStype
						FROM 
						(
							SELECT PTypeID,KTypeID,AgeQty-StockQty Qty
							FROM #DiffInfo
							WHERE AgeCount>1 AND (StockQty<AgeQty)
						) b,
						(
							SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
							FROM IniStockAgeStype c
							GROUP BY c.PtypeID,c.KtypeID
						) c
						WHERE IniStockAgeStype.PtypeID=b.PTypeID
						AND IniStockAgeStype.KtypeID=b.KTypeID
						AND IniStockAgeStype.Qty<=b.Qty
						AND IniStockAgeStype.PtypeID=c.PtypeID
						AND IniStockAgeStype.KtypeID=c.KtypeID
						AND IniStockAgeStype.InStockDate=c.InStockDate
						
						
						UPDATE IniStockAgeStype
						SET Qty=IniStockAgeStype.Qty-b.Qty,Total=IniStockAgeStype.Total-b.Total
						FROM 
						(
							SELECT PTypeID,KTypeID,AgeQty-StockQty Qty,AgeTotal-StockTotal Total
							FROM #DiffInfo
							WHERE AgeCount>1 AND (StockQty<AgeQty)
						) b,
						(
							SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
							FROM IniStockAgeStype c
							GROUP BY c.PtypeID,c.KtypeID
						) c
						WHERE IniStockAgeStype.PtypeID=b.PTypeID
						AND IniStockAgeStype.KtypeID=b.KTypeID
						AND IniStockAgeStype.Qty>b.Qty
						AND IniStockAgeStype.PtypeID=c.PtypeID
						AND IniStockAgeStype.KtypeID=c.KtypeID
						AND IniStockAgeStype.InStockDate=c.InStockDate
						
					
					
						TRUNCATE TABLE #DiffInfo
						
						INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
						SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
						FROM
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
							FROM dbo.IniGoodsStocks
							GROUP BY PTypeID,KTypeID
						) a
						FULL JOIN
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
							FROM dbo.IniStockAgeStype
							GROUP BY PTypeID,KTypeID
						) b
						ON a.PTypeID=b.PTypeID
						AND a.KTypeID=b.KTypeID  
						WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0)
						
					
					
						
						IF NOT EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE (StockQty<AgeQty)
						)
						BEGIN
							--如果不存在期初库存比期初库龄小了,则退出循环
							SELECT @intCal=0
						END 
					
					END
					
					
				END
		END
	END
	
	SELECT @intCal=1
	
	--3，处理集团库龄
	IF NOT EXISTS(
		SELECT PTypeID	
		FROM IniStockAgeGroup
	)
	BEGIN
		--无数据，则不计算
		SELECT @intCal=0	
		RETURN
	END
	ELSE
	BEGIN
		INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
		SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
		FROM
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
			FROM dbo.IniGoodsStocks
			GROUP BY PTypeID,KTypeID
		) a
		FULL JOIN
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
			FROM dbo.IniStockAgeGroup
			GROUP BY PTypeID,KTypeID
		) b
		ON a.PTypeID=b.PTypeID
		AND a.KTypeID=b.KTypeID  
		WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
	END
	
	IF @intCal=1 
	BEGIN
		IF	NOT EXISTS
		(
			SELECT PTypeID
			FROM #DiffInfo
		)
		BEGIN
			--如果没有不相等的，则不计算
			SELECT @intCal=0
		END
		
		TRUNCATE	TABLE	#DiffInfo
	END
	
	
	--先对库龄数据进行规整,库龄的数量应该都是为正的.如果存在为负数的,且对应的商品仓库的库龄记录只有一条,则保留,如果不止一条,则删除最近库龄以外的所有库龄信息.这个执行完后,就可以保证,如果对应的商品,仓库存在库龄为负数的记录,那么该仓库,商品只有一条库龄记录了
	IF @intCal=1 AND EXISTS
	(
		SELECT PTypeID
		FROM IniStockAgeGroup
		WHERE Qty<0
		GROUP BY PtypeID,KtypeID,InStockDate
		HAVING COUNT(*)>0
	)
	BEGIN
		DELETE IniStockAgeGroup
		FROM 
		(
			SELECT PTypeID,KtypeID
			FROM IniStockAgeGroup
			WHERE Qty<0
			GROUP BY PtypeID,KtypeID,InStockDate
			HAVING COUNT(*)>0
		)	b
		WHERE IniStockAgeGroup.PtypeID=b.PTypeID
		AND IniStockAgeGroup.KtypeID=b.KTypeID
		AND NOT EXISTS
		(
			SELECT c.PTypeID,c.KtypeID,MAX(c.InStockDate) InStockDate
			FROM IniStockAgeGroup c
			WHERE IniStockAgeGroup.PtypeID=c.PtypeID
			AND IniStockAgeGroup.KtypeID=c.KtypeID
			GROUP BY c.PtypeID,c.KtypeID
			HAVING IniStockAgeGroup.InStockDate=MAX(c.InStockDate)
			
		)
	END
	
	
	--先建立一个临时表,记录所有数量,金额不一致的记录
	IF @intCal=1
	BEGIN
		TRUNCATE	TABLE	#DiffInfo
		
		INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
		SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
		FROM
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
			FROM dbo.IniGoodsStocks
			GROUP BY PTypeID,KTypeID
		) a
		FULL JOIN
		(
			SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
			FROM dbo.IniStockAgeGroup
			GROUP BY PTypeID,KTypeID
		) b
		ON a.PTypeID=b.PTypeID
		AND a.KTypeID=b.KTypeID  
		WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
	END 
	
	IF @intCal=1
	BEGIN
		IF NOT EXISTS
		(
			--判断数量金额是否一致
			SELECT PTypeID
			FROM #DiffInfo
		)
		BEGIN
			--不需要重算库龄就退出
			SELECT @intCal=0
			RETURN
		END
		ELSE
		BEGIN
				
				--如果在期初库存不存在的商品,仓库,那么直接删除
				
				IF EXISTS(
					SELECT b.PtypeID
					FROM IniStockAgeGroup b
					WHERE NOT EXISTS(
						SELECT PTypeID 
						FROM dbo.IniGoodsStocks a
						WHERE a.PTypeID=b.PtypeID
						AND a.KtypeId=b.KtypeID
					)
				)
				BEGIN
					DELETE IniStockAgeGroup
					WHERE NOT EXISTS(
						SELECT PTypeID 
						FROM dbo.IniGoodsStocks a
						WHERE a.PTypeID=IniStockAgeGroup.PtypeID
						AND a.KtypeId=IniStockAgeGroup.KtypeID
					)
				END
				
				
				
				--如果在期初库龄中只有一条的商品,那么直接取期初库存的数量和金额
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE StockQty<>AgeQty AND AgeCount=1
				)
				BEGIN
					UPDATE IniStockAgeGroup
					SET Qty=b.StockQty,Total=b.StockTotal
					FROM #DiffInfo b
					WHERE IniStockAgeGroup.PtypeID=b.PTypeID
					AND IniStockAgeGroup.KtypeID=b.KTypeID
					AND b.StockQty<>b.AgeQty
					AND b.AgeCount=1
				END
				
				
				--如果在期初库龄中不存在的商品,在期初库存中存在的,那么直接新增一条记录,时间取服务器当前时间-1
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount=0 AND StockQty<>0
				)
				BEGIN
					INSERT IniStockAgeGroup(PtypeID,KTypeID,InStockDate,StockAge,Qty,Total)
					SELECT PtypeID,KTypeID,@strBeginDate,1,StockQty,StockTotal
					FROM #DiffInfo
					WHERE AgeCount=0 AND StockQty<>0
				END
				
				
				
				--重算#DiffInfo
				
				TRUNCATE TABLE #DiffInfo
				
				INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
				SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
				FROM
				(
					SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
					FROM dbo.IniGoodsStocks
					GROUP BY PTypeID,KTypeID
				) a
				FULL JOIN
				(
					SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
					FROM dbo.IniStockAgeGroup
					GROUP BY PTypeID,KTypeID
				) b
				ON a.PTypeID=b.PTypeID
				AND a.KTypeID=b.KTypeID  
				WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
				
				
				
				
				--如果在期初库龄和期初库存中都存在,且数量不一致的,且期初库龄不止一条的如果期初库存比期初库龄的数量大,那么直接把最后一个库龄的数量改为相差的数量,金额即可
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount>1 AND (StockQty>AgeQty)
				)
				BEGIN
					UPDATE IniStockAgeGroup
					SET Qty=IniStockAgeGroup.Qty+b.Qty,Total=IniStockAgeGroup.Total+b.Total
					FROM
					(
						SELECT PTypeID,KTypeID,StockQty-AgeQty Qty,StockTotal-AgeTotal Total
						FROM #DiffInfo
						WHERE AgeCount>1 AND (StockQty>AgeQty)
					) b,
					(
						SELECT c.PTypeID,c.KtypeID,MAX(c.InStockDate) InStockDate
						FROM IniStockAgeGroup c
						GROUP BY c.PtypeID,c.KtypeID
						HAVING COUNT(*)>1
					) c
					WHERE IniStockAgeGroup.PtypeID=b.PTypeID
					AND IniStockAgeGroup.KtypeID=b.KTypeID
					AND IniStockAgeGroup.PtypeID=c.PTypeID
					AND IniStockAgeGroup.KtypeID=c.KTypeID
					AND IniStockAgeGroup.InStockDate=c.InStockDate
					
				END
				
				
				
				
				--如果在期初库龄和期初库存中都存在,且数量不一致的,且期初库龄不止一条的,如果期初库存比期初库龄的数量小,那么需要一个算法,看需要删除几条库龄,让数量匹配
				IF EXISTS(
					SELECT PTypeID
					FROM #DiffInfo
					WHERE AgeCount>1 AND (StockQty<AgeQty)
				)
				BEGIN
					--通过MERGE来处理
					
					SELECT @intCal=1
					
					WHILE (@intCal=1)
					BEGIN
						--判断时间最早的那条库龄记录的数量,如果比差值大,则它的数量改成本身减差值;如果比差值小,则直接删除
						
						--如果库龄只有一条记录,且数量不相等,则直接相等即可
						IF EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE StockQty<>AgeQty AND AgeCount=1
						)
						BEGIN
							UPDATE IniStockAgeGroup
							SET Qty=b.StockQty,Total=b.StockTotal
							FROM #DiffInfo b
							WHERE IniStockAgeGroup.PtypeID=b.PTypeID
							AND IniStockAgeGroup.KtypeID=b.KTypeID
							AND b.StockQty<>b.AgeQty
							AND b.AgeCount=1
						END
						
						
						
						TRUNCATE TABLE #DiffInfo
				
						INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
						SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
						FROM
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
							FROM dbo.IniGoodsStocks
							GROUP BY PTypeID,KTypeID
						) a
						FULL JOIN
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
							FROM dbo.IniStockAgeGroup
							GROUP BY PTypeID,KTypeID
						) b
						ON a.PTypeID=b.PTypeID
						AND a.KTypeID=b.KTypeID  
						WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
						
						
						--如果库存数量小于最近一条的库龄数量,那么只保留最近一条的库龄数量,将库龄数量改成库存数量即可,其他的库龄信息删除
						IF EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE StockQty<=AgeQty AND AgeCount>1
						)
						BEGIN
							IF EXISTS(
								SELECT a.PTypeID
								FROM #DiffInfo	a,
								(
									SELECT b.*
									FROM IniStockAgeGroup b
									WHERE EXISTS
									(
										SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
										FROM IniStockAgeGroup c
										GROUP BY c.PtypeID,c.KtypeID
										HAVING c.PTypeID=b.PtypeID
										AND c.KtypeID=b.KtypeID
									)
								) b
								WHERE a.PTypeID=b.PtypeID
								AND a.KTypeID=b.KtypeID
								AND a.StockQty<=b.Qty
								AND a.StockQty<=a.AgeQty AND a.AgeCount>1
							)
							BEGIN
								UPDATE IniStockAgeGroup
								SET Qty=b.StockQty,Total=b.StockTotal
								FROM #DiffInfo b
								WHERE IniStockAgeGroup.PTypeID=b.PTypeID
								AND IniStockAgeGroup.KTypeID=b.KTypeID
								AND b.StockQty<=b.AgeQty AND b.AgeCount>1
								AND EXISTS
								(
									SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
									FROM IniStockAgeGroup c
									GROUP BY c.PtypeID,c.KtypeID
									HAVING c.PTypeID=IniStockAgeGroup.PtypeID
									AND c.KtypeID=IniStockAgeGroup.KtypeID
									AND IniStockAgeGroup.InStockDate=MIN(c.InStockDate)
								)
								
								DELETE IniStockAgeGroup
								FROM #DiffInfo b
								WHERE IniStockAgeGroup.PTypeID=b.PTypeID
								AND IniStockAgeGroup.KTypeID=b.KTypeID
								AND b.StockQty<=b.AgeQty AND b.AgeCount>1
								AND EXISTS
								(
									SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
									FROM IniStockAgeGroup c
									GROUP BY c.PtypeID,c.KtypeID
									HAVING c.PTypeID=IniStockAgeGroup.PtypeID
									AND c.KtypeID=IniStockAgeGroup.KtypeID
									AND IniStockAgeGroup.InStockDate<>MIN(c.InStockDate)
								)
								
								
								TRUNCATE TABLE #DiffInfo
				
								INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
								SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
								FROM
								(
									SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
									FROM dbo.IniGoodsStocks
									GROUP BY PTypeID,KTypeID
								) a
								FULL JOIN
								(
									SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
									FROM dbo.IniStockAgeGroup
									GROUP BY PTypeID,KTypeID
								) b
								ON a.PTypeID=b.PTypeID
								AND a.KTypeID=b.KTypeID  
								WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0) OR ISNULL(a.Total,0)<>ISNULL(b.Total,0)
							END
						END
						
						DELETE IniStockAgeGroup
						FROM 
						(
							SELECT PTypeID,KTypeID,AgeQty-StockQty Qty
							FROM #DiffInfo
							WHERE AgeCount>1 AND (StockQty<AgeQty)
						) b,
						(
							SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
							FROM IniStockAgeGroup c
							GROUP BY c.PtypeID,c.KtypeID
						) c
						WHERE IniStockAgeGroup.PtypeID=b.PTypeID
						AND IniStockAgeGroup.KtypeID=b.KTypeID
						AND IniStockAgeGroup.Qty<=b.Qty
						AND IniStockAgeGroup.PtypeID=c.PtypeID
						AND IniStockAgeGroup.KtypeID=c.KtypeID
						AND IniStockAgeGroup.InStockDate=c.InStockDate
						
						
						UPDATE IniStockAgeGroup
						SET Qty=IniStockAgeGroup.Qty-b.Qty,Total=IniStockAgeGroup.Total-b.Total
						FROM 
						(
							SELECT PTypeID,KTypeID,AgeQty-StockQty Qty,AgeTotal-StockTotal Total
							FROM #DiffInfo
							WHERE AgeCount>1 AND (StockQty<AgeQty)
						) b,
						(
							SELECT c.PTypeID,c.KtypeID,MIN(c.InStockDate) InStockDate
							FROM IniStockAgeGroup c
							GROUP BY c.PtypeID,c.KtypeID
						) c
						WHERE IniStockAgeGroup.PtypeID=b.PTypeID
						AND IniStockAgeGroup.KtypeID=b.KTypeID
						AND IniStockAgeGroup.Qty>b.Qty
						AND IniStockAgeGroup.PtypeID=c.PtypeID
						AND IniStockAgeGroup.KtypeID=c.KtypeID
						AND IniStockAgeGroup.InStockDate=c.InStockDate
						
					
					
						TRUNCATE TABLE #DiffInfo
						
						INSERT #DiffInfo(PTypeID,KTypeID,StockQty,AgeQty,StockTotal,AgeTotal,AgeCount)
						SELECT a.PTypeID,a.KTypeID,ISNULL(a.Qty,0) StockQty,ISNULL(b.Qty,0) AgeQty,ISNULL(a.Total,0) StockTotal,ISNULL(b.Total,0) AgeTotal,ISNULL(b.AgeCount,0)
						FROM
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total
							FROM dbo.IniGoodsStocks
							GROUP BY PTypeID,KTypeID
						) a
						FULL JOIN
						(
							SELECT PTypeID,KTypeID,SUM(Qty) Qty,SUM(Total) Total,COUNT(*) AgeCount
							FROM dbo.IniStockAgeGroup
							GROUP BY PTypeID,KTypeID
						) b
						ON a.PTypeID=b.PTypeID
						AND a.KTypeID=b.KTypeID  
						WHERE ISNULL(a.Qty,0)<>ISNULL(b.Qty,0)
						
					
					
						
						IF NOT EXISTS(
							SELECT PTypeID
							FROM #DiffInfo
							WHERE (StockQty<AgeQty)
						)
						BEGIN
							--如果不存在期初库存比期初库龄小了,则退出循环
							SELECT @intCal=0
						END 
					
					END
					
					
				END
		END
	END
	*/
	
	DROP TABLE #DiffInfo
END
GO



GO
IF EXISTS(SELECT TOP 1 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_OkIniVipCard',N'P'))
BEGIN
	DROP PROC GP_OkIniVipCard
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--会员卡期初开账
CREATE PROC GP_OkIniVipCard
(
	@STypeID	 VARCHAR(MAX),		--分支机构ID
	@ReturnValue NVARCHAR(1000) OUT	--输出信息
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SType_UserConfig WHERE StypeId=@STypeID AND Value=1)
	BEGIN
		RETURN
	END
	
	--产品信息,2=A8
	DECLARE @ProInfo		INT,
			@VipId			INT,
			@STypeName		VARCHAR(100)
			
			
	SELECT @VipId=Nid FROM Ac_Items WHERE UserCode='2181'
	SELECT @ProInfo=SubValue FROM SysData WHERE SubName='ProInfo'
	
	-- 开账将VIP期初储值金额转至储值余额
	--IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubValue=2 AND SubName='ProInfo')
	--BEGIN
		UPDATE	A 
		SET		A.cZyeMoney=ISNULL(F.cZyeMoney,0),
				A.QcCzMoney=ISNULL(F.QcCzMoney,0)
				--A.LjCzMoney=A.LjCzMoney+B.LjCzMoney,
				--A.xFczMoney=A.xFczMoney+B.lJxFczMoney,
				--A.TotalMoney=A.TotalMoney+B.LjXFMoney
		FROM	dbo.nVipCardSign A
		INNER JOIN (
					SELECT	B.VipCardID,
							SUM(ISNULL(B.cZyeMoney,0)) AS cZyeMoney,
							SUM(ISNULL(B.QcCzMoney,0)) AS QcCzMoney
					FROM	(
								SELECT
									VipCardID,
									SUM(ISNULL(cZyeMoney,0)) cZyeMoney,
									SUM(ISNULL(qCczMoney,0)) QcCzMoney 
								FROM dbo.nVipCardSignSType b 
								INNER JOIN f_split(@STypeID,'') F ON F.a=B.StypeId
								GROUP BY VipCardID
								UNION ALL
								SELECT
									VipCardID,
									SUM(ISNULL(cZyeMoney,0)) cZyeMoney,
									SUM(ISNULL(qCczMoney,0)) QcCzMoney 
								FROM dbo.nVipCardSignSType b 
								INNER JOIN (SELECT STypeId FROM dbo.SType_UserConfig WHERE [value] = 1) F ON F.STypeid=B.StypeId
								GROUP BY VipCardID
					)B GROUP BY B.VipCardID
		) F ON A.VipCardID=F.VipCardId
	--END
	--ELSE
	--BEGIN
	--	UPDATE	A 
	--	SET		A.cZyeMoney=B.cZyeMoney,
	--			A.QcCzMoney=B.QcCzMoney
	--			--A.LjCzMoney=B.LjCzMoney,
	--			--A.xFczMoney=B.lJxFczMoney,
	--			--A.TotalMoney=B.LjXFMoney
	--	FROM	dbo.nVipCardSign A ,
	--			dbo.nVipCardSignSType b 
	--	WHERE	A.VipCardID=b.VipCardId AND B.STypeID=@STypeID
	--END
	
	RETURN 0
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

对于所影响的老单据，批量修改成本

在修改了单据后执行

*/
CREATE   PROCEDURE Gp_OldBill_BatchCost 
(
	@nBillID			NUMERIC(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nRet				INT OUT,
	@strErrMsg			VARCHAR(500)='' OUT
)
--@encode$--
AS


SELECT
	@nRet=0,
	@strErrMsg=''

CREATE TABLE #StockInfo(
	PTypeID		VARCHAR(50),
	KTypeID		VARCHAR(50)
)



EXEC Gp_OldBill_ReferTo @nBillID,@nBillType


IF NOT EXISTS(
	SELECT BillNumberID
	FROM #AfterModifyBill
)
BEGIN
	RETURN
END

--#AfterBill这个表示需要修改成本的单据（应该包含单据ID，PTypeID,KTypeID）

DECLARE
	@datPostDate		DATETIME
		
	
SELECT
	@datPostDate=posttime
FROM Billindex
WHERE BillNumberId=@nBillID



--确定期初数据（包含采购费用分摊单）
CREATE TABLE #IniData(
	PTypeID			VARCHAR(50),
	KTypeID			VARCHAR(50),
	Qty				 NUMERIC(24, 10) ,
	CostPrice		 NUMERIC(24, 10) ,
	CostTotal		 NUMERIC(24, 10) ,
	BeginSort		INT DEFAULT 0
)

INSERT #IniData(PTypeID,KTypeID,Qty,CostPrice,CostTotal)
SELECT a.PtypeId,a.KtypeId,SUM(a.Qty),
CASE SUM(a.Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(a.CostTotal) AS  NUMERIC(24, 10) )/CAST(SUM(a.Qty) AS  NUMERIC(24, 10) ),4) END,
SUM(a.CostTotal)
FROM
(
	SELECT  DISTINCT a.BillNumberID,a.ID,a.PtypeId,a.KtypeId,a.Qty,a.CostTotal
	FROM InOutstocktable a,
	#StockInfo b
	WHERE a.PtypeId=b.PTypeID
	AND a.KtypeId=b.KTypeID			
	AND a.PostTime<@datPostDate
	UNION ALL
	SELECT 0,0,a.PtypeId,a.KtypeId,a.Qty,a.Total
	FROM IniGoodsStocks a,
	#StockInfo b	
	WHERE a.PtypeId=b.PTypeID	
	AND a.KtypeId=b.KTypeID		
 
) a
GROUP BY a.PtypeId,a.KtypeId

/*
SELECT '#IniData'
SELECT '#IniData',* FROM #IniData
*/

--确定后面的物流单据(减少表扫描)
CREATE TABLE #AllAfterBill(
	BillNumberID	BIGINT,
	BillType		INT,
	PTypeID			VARCHAR(50),
	KTypeID			VARCHAR(50),
	Qty				 NUMERIC(24, 10) ,
	CostPrice		 NUMERIC(24, 10) ,
	CostTotal		 NUMERIC(24, 10) ,
	PostTime		DATETIME,
	SortID			BIGINT,
	NewSortID		BIGINT
)



--考虑给临时表建立索引
INSERT #AllAfterBill(BillNumberID,BillType,PTypeID,KTypeID,Qty,CostPrice,CostTotal,PostTime,SortID,NewSortID)
SELECT a.BillNumberId,a.BillType,a.PtypeId,a.KtypeId,a.Qty,a.CostPrice,a.CostTotal,a.PostTime,a.SortID,
ROW_NUMBER() OVER(ORDER BY a.PostTime,a.SortID,a.Qty)
FROM
(
	SELECT DISTINCT a.BillNumberId,a.BillType,a.PtypeId,a.KtypeId,a.Qty,a.CostPrice,a.CostTotal,a.PostTime,a.SortID
	FROM InOutstocktable a,
	#StockInfo b
	WHERE a.PtypeId=b.PTypeID			
	AND a.KtypeId=b.KTypeID
	AND a.PostTime>=@datPostDate
	UNION
	SELECT a.BillNumberId,a.BillType,a.PtypeId,a.KtypeId,a.Qty,a.CostPrice,a.CostTotal,a.PostTime,a.SortID
	FROM InOutstocktable a
	WHERE a.BillNumberId=@nBillID
	AND (a.Qty<0 OR (a.Qty>0 AND a.BillType NOT IN (34,161,144,21,188,201,16,57,174)))
) a
ORDER BY a.PostTime,a.SortID,a.Qty

/*
SELECT 'aaa','#AllAfterBill',* FROM #AllAfterBill ORDER BY NewSortID

SELECT '#StockInfo',* FROM #StockInfo
*/

--根据历史库存，来计算出库时所取的成本价
--处理InOutStockTable


--循环修改(两重循环)

DECLARE
	@decIniQty			 NUMERIC(24, 10) ,
	@decIniCostTotal	 NUMERIC(24, 10) ,
	@decNewQty			 NUMERIC(24, 10) ,
	@decNewCostTotal	 NUMERIC(24, 10) ,
	@decQty				 NUMERIC(24, 10) ,
	@decTotal			 NUMERIC(24, 10) ,
	@decCostPrice		 NUMERIC(24, 10) ,
	@decCurQty			 NUMERIC(24, 10) ,		--主要用于出库时，计算当前出库数量，金额
	@decCurCostTotal	 NUMERIC(24, 10) 
	

CREATE TABLE #SumTotal(
	Qty					 NUMERIC(24, 10) ,
	Total				 NUMERIC(24, 10) 
)

--假设#StockInfo表示所影响到的库存，#AfterModifyBill表示所影响到的单据
DECLARE
	@chvPTypeID			VARCHAR(50),
	@chvKTypeID			VARCHAR(50),
	@m					BIGINT,
	@n					BIGINT,
	@intSortID			BIGINT,
	@intTempBillType	INT,
	@strTempBillCode	VARCHAR(200),
	@strKFullName		VARCHAR(50),
	@strPFullName		VARCHAR(50),
	@intGoOn			BIT,
	@chvOtherKTypeID	VARCHAR(50),
	@datOtherPostTime	DATETIME
	
SELECT
	@intGoOn=0	

/*	
SELECT '#AfterModifyBill'
SELECT '#AfterModifyBill',* FROM #AfterModifyBill ORDER BY PostTime,SortID
*/

DECLARE AfterBill_CURSOR CURSOR FOR
SELECT SortID,BillType,KTypeID,PTypeID
FROM #AfterModifyBill
ORDER BY PostTime,SortID,Qty

OPEN AfterBill_CURSOR
FETCH NEXT FROM AfterBill_CURSOR 
INTO @intSortID,@intTempBillType,@chvKTypeID,@chvPTypeID

WHILE @@FETCH_STATUS = 0  AND @intGoOn=0
BEGIN
	--先得到期初
	SELECT
	@decIniQty=0,
	@decIniCostTotal=0,
	@decNewQty=0,
	@decNewCostTotal=0,
	@m=0,
	@n=0

	IF EXISTS(
		SELECT
			PTypeID
		FROM #IniData
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
	)
	BEGIN
		SELECT
			@decIniQty=Qty,
			@decIniCostTotal=CostTotal,
			@m=BeginSort
		FROM #IniData
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
		
		SELECT
			@decIniQty=ISNULL(@decIniQty,0),
			@decIniCostTotal=ISNULL(@decIniCostTotal,0),
			@m=ISNULL(@m,0)
	END
	

	/*	
	SELECT '期初前'
	
	SELECT '期初前',*
	FROM #IniData
	WHERE PtypeId=@chvPTypeID
	AND KtypeId=@chvKTypeID
	*/

	--依次修改影响到的出库成本
	
	SELECT @n=NewSortID,@decCurQty=Qty
	FROM #AllAfterBill
	WHERE PtypeId=@chvPTypeID
	AND KtypeId=@chvKTypeID
	AND SortID=@intSortID
	
	SELECT 
		@n=ISNULL(@n,0),@decCurQty=ISNULL(@decCurQty,0)
		
	
	/*
	SELECT '期初',@chvPTypeID,@chvKTypeID,@decIniQty,@decIniCostTotal,'m='+CAST(@m AS VARCHAR(10)),'n='+CAST(@n AS VARCHAR(10)),@decCurQty,@intSortID
	
	SELECT '调整前'
	
	SELECT '调整前',*
	FROM #AllAfterBill
	WHERE PtypeId=@chvPTypeID
	AND KtypeId=@chvKTypeID
	ORDER BY SortID
	*/
	
	
	IF @decCurQty<0 OR (@decCurQty>0 AND @intTempBillType NOT IN (34,161,144,21,188,201,16,57,174,17) )
	BEGIN
		SELECT
			@decNewQty=SUM(Qty),
			@decNewCostTotal=SUM(CostTotal)
		FROM #AllAfterBill
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
		AND NewSortID>@m
		AND NewSortID<@n
	END
	ELSE
	BEGIN
		SELECT
			@decNewQty=SUM(Qty),
			@decNewCostTotal=SUM(CostTotal)
		FROM #AllAfterBill
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
		AND NewSortID>@m
		AND NewSortID<=@n
	END	
	
	SELECT
		@decNewQty=ISNULL(@decNewQty,0),
		@decNewCostTotal=ISNULL(@decNewCostTotal,0)
	
	
	SELECT
		@decQty=@decIniQty+@decNewQty,
		@decTotal=@decIniCostTotal+@decNewCostTotal
	
	
	IF @intGoOn=0 AND @decCurQty<0 OR (@decCurQty>0 AND @intTempBillType NOT IN (34,161,144,21,188,201,16,57,174,17) )
	BEGIN
		--如果数量为零，则单价=金额
		SELECT
			@decCostPrice=CASE @decQty WHEN 0 THEN 0 ELSE ROUND(@decTotal/@decQty,4) END
			
		--SELECT '单据ID','单据数量',@decCurQty,'SortID',@intSortID,'m',@m,'n',@n,'IniQty',@decIniQty,'IniCostTotal',@decIniCostTotal,'NewQty',@decNewQty,'NewCostTotal',@decNewCostTotal,'Total',@decTotal,'Qty',@decQty,'CostPrice',@decCostPrice
		
		
		IF @intTempBillType IN (57,17,21) AND @decCurQty<0 AND (-@decCurQty>@decQty)
		BEGIN
				SELECT @strKFullName=FullName
				FROM Stock
				WHERE typeId=@chvKTypeID
				
				SELECT @strPFullName=FullName
				FROM PType
				WHERE typeId=@chvPTypeID
				
				SELECT @strTempBillCode=b.BillCode 
				FROM #AfterModifyBill a
				INNER JOIN BillIndex b
				ON a.BillNumberID=b.BillNumberId
				WHERE a.SortID=@intSortID
		
				SELECT 
					@nRet=-460,
					@strErrMsg='修改单据计算成本中，单据['+@strTempBillCode+']仓库['+@strKFullName+']'+'商品['+@strPFullName+']成本调价或同价调拨或变价调拨中出现库存不足的情形，不能修改！',
					@intGoOn=1
		END
		
		IF @intGoOn=0 AND (@decCostPrice<=0 AND @intTempBillType<>57) OR (@intTempBillType=57 AND @decCostPrice=0)
		BEGIN
				SELECT @strKFullName=FullName
				FROM Stock
				WHERE typeId=@chvKTypeID
				
				SELECT @strPFullName=FullName
				FROM PType
				WHERE typeId=@chvPTypeID
				
				SELECT @strTempBillCode=b.BillCode 
				FROM #AfterModifyBill a
				INNER JOIN BillIndex b
				ON a.BillNumberID=b.BillNumberId
				WHERE a.SortID=@intSortID
			
				SELECT 
					@nRet=-460,
					@strErrMsg='修改单据计算成本中，单据['+@strTempBillCode+']仓库['+@strKFullName+']'+'商品['+@strPFullName+']出现成本价为负或为零的情形，不能修改！',
					@intGoOn=1
			
		END
		
		IF @intGoOn=0
		BEGIN
			SELECT
				@decCurCostTotal=ROUND(@decCostPrice*@decCurQty,2)
							
				
			UPDATE InOutstocktable
			SET 
				CostTotal=@decCurCostTotal,
				CostPrice=@decCostPrice
			WHERE SortID=@intSortID  
			
			UPDATE #AllAfterBill
			SET 
				CostTotal=@decCurCostTotal,
				CostPrice=@decCostPrice
			WHERE SortID=@intSortID 
			
			--对同价调拨单的入库进行单独处理
			
			
			IF @intTempBillType=17
			BEGIN
				UPDATE InOutstocktable
				SET 
					CostTotal=-@decCurCostTotal,
					CostPrice=@decCostPrice
				WHERE SortID=@intSortID+1 
				
				--#AllAfterBill也要修改
				UPDATE #AllAfterBill
				SET 
					CostTotal=-@decCurCostTotal,
					CostPrice=@decCostPrice
				WHERE SortID=@intSortID+1 	
			END
			
			
			
			
			SELECT
				@decQty=@decQty+@decCurQty,
				@decTotal=@decTotal+@decCurCostTotal
		END
	END	
	
	--修改期初，不处理成本价
	
	IF @intGoOn=0
	BEGIN
		IF NOT EXISTS(
			SELECT PTypeID
			FROM #IniData
			WHERE PTypeID=@chvPTypeID
			AND KTypeID=@chvKTypeID
		)
		BEGIN
			INSERT #IniData(PTypeID,KTypeID,Qty,CostTotal,BeginSort)
			SELECT @chvPTypeID,@chvKTypeID,@decQty,@decTotal,@n
		END
		ELSE
		BEGIN
			UPDATE #IniData
			SET Qty=@decQty,CostTotal=@decTotal,BeginSort=@n
			WHERE PTypeID=@chvPTypeID
			AND KTypeID=@chvKTypeID
		END
	END
	
	/*
	SELECT '调整后',*
	FROM #IniData
	WHERE PTypeID=@chvPTypeID
	AND KTypeID=@chvKTypeID
	
	SELECT '调整后',*
	FROM #AllAfterBill
	WHERE PTypeID=@chvPTypeID
	AND KTypeID=@chvKTypeID
	*/

	FETCH NEXT FROM AfterBill_CURSOR 
	INTO @intSortID,@intTempBillType,@chvKTypeID,@chvPTypeID
END

--修改GoodsStocks的成本(先直接计算，之后再改为通过之前累计的，加上后续的得到总金额，总数量)



--如果先销售2个100，再采购2个100，再报损1个，做费用分摊30，结果库存金额为0了，应该为30
--这个是因为报损单的成本价是取的30，这个不对。对于用户录入成本或取最近进价的，该怎么处理？

--如果等于0了，则直接取费用分摊单的金额 

CLOSE AfterBill_CURSOR
DEALLOCATE AfterBill_CURSOR

IF @intGoOn=1 RETURN

DECLARE Stock_CURSOR CURSOR FOR
SELECT PTypeID,KTypeID
FROM #StockInfo

OPEN Stock_CURSOR
FETCH NEXT FROM Stock_CURSOR INTO @chvPTypeID,@chvKTypeID

WHILE @@FETCH_STATUS = 0
BEGIN
	--最后算库存的成本价

	TRUNCATE TABLE #SumTotal
		
		
	--始终都把分摊单本身算上（需要测试有无问题）

	INSERT #SumTotal(Qty,Total)
	SELECT 
		ISNULL(SUM(Qty),0) AS Qty,
		ISNULL(SUM(CostTotal),0) AS Total
	FROM InOutstocktable
	WHERE  PtypeId=@chvPTypeID	
	AND KtypeId=@chvKTypeID
	UNION ALL
	SELECT 
		ISNULL(SUM(Qty),0) AS Qty,
		ISNULL(SUM(Total),0) AS Total
	FROM IniGoodsStocks
	WHERE  PtypeId=@chvPTypeID	
	AND KtypeId=@chvKTypeID


	IF EXISTS(
		SELECT PTypeID
		FROM GoodsStocks
		WHERE PtypeId=@chvPTypeID
		AND KtypeId=@chvKTypeID
	)
	BEGIN
		UPDATE GoodsStocks
		SET Qty=b.Qty,Total=b.Total,Price=b.Price
		FROM
		(
			SELECT 
				SUM(a.Qty) AS Qty,
				SUM(a.Total) AS Total,
				CASE SUM(a.Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(a.Total) AS  NUMERIC(24, 10) )/CAST(SUM(a.Qty) AS  NUMERIC(24, 10) ),4) END AS Price
			FROM #SumTotal a
		) b	
		WHERE PtypeId=@chvPTypeID	
		AND KtypeId=@chvKTypeID
	END
	ELSE
	BEGIN
		--因为现在QTY=0的，系统会删除记录，所以需要追加
		
		--如果存在同价调拨单，则不用追加，因为可能转移到其他仓库了
		IF NOT EXISTS(
			SELECT BillNumberID
			FROM #AllAfterBill
			WHERE PTypeID=@chvPTypeID
			AND KTypeID=@chvKTypeID
			AND BillType=17
		)
		BEGIN
			IF EXISTS(
				SELECT SUM(Qty)
				FROM #SumTotal
				HAVING SUM(Qty)<>0 OR SUM(Total)<>0
			)
			BEGIN
				INSERT GoodsStocks(PtypeId,KtypeId,Qty,Price,Total)
				SELECT @chvPTypeID,@chvKTypeID,b.Qty,b.Price,b.Total
				FROM
				(
					SELECT 
						SUM(a.Qty) AS Qty,
						SUM(a.Total) AS Total,
						CASE SUM(a.Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(a.Total) AS  NUMERIC(24, 10) )/CAST(SUM(a.Qty) AS  NUMERIC(24, 10) ),4) END AS Price
					FROM #SumTotal a
				) b	
			END
		END
	END
	
	FETCH NEXT FROM Stock_CURSOR INTO @chvPTypeID,@chvKTypeID
END
CLOSE Stock_CURSOR
DEALLOCATE Stock_CURSOR
		




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

判断单据能否修改

*/
CREATE   PROCEDURE Gp_OldBill_CanModify 
(
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nCanModify			INT OUT,			--0表示能修改，1表示不能修改
	@strMsg				VARCHAR(MAX)=''	OUT
)
--@encode$--
AS

SELECT
	@nCanModify=0

--先判断该单据是否是已过账，未红冲的单据
IF NOT EXISTS(
	SELECT BillNumberID FROM BillIndex	WHERE BillNumberID=@nBillID AND BillType=@nBillType
	UNION ALL
	SELECT BillNumberID FROM dbo.ReceiptBillIndex WHERE BillNumberID=@nBillID AND BillType=@nBillType
)
BEGIN
	SET @strMsg='单据不存在！'
	SET @nCanModify=1
	RETURN
END

IF NOT EXISTS(
	SELECT BillNumberID	FROM BillIndex	WHERE BillNumberID=@nBillID AND BillType=@nBillType	AND IfCheck='t'	AND RedWord=0
	UNION ALL
	SELECT BillNumberID FROM dbo.ReceiptBillIndex WHERE BillNumberID=@nBillID AND BillType=@nBillType
)
BEGIN
	SET @strMsg='单据未过账或已红冲！'
	SET @nCanModify=1
	RETURN
END

--总账凭证
DECLARE @re INT;

EXEC @re=GP_ModifyBill_VoucherCheck @nBillID,@nBillType
IF @re=-1
BEGIN
	SET @strMsg='本单据已生成总账凭证，请删除总账凭证后重试！'
	SET @nCanModify=1
END

IF EXISTS(
	SELECT BillNumberID	FROM BillIndex	WHERE BillNumberID=@nBillID AND BillType=@nBillType AND CWCheck=1	
)
BEGIN
	SET @strMsg='该单据已财务审核，不能修改！'
	SET @nCanModify=1
	RETURN
END

IF @nBillType = 159
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM AccountCredence WHERE ATypeId = '0000200005' AND BillNumberId = @nBillID  AND TypeATypeId IN ('00002'))
	BEGIN
		SET @strMsg='会员卡充值生成的会计凭证不允许修改！'
		SET @nCanModify=1
		RETURN
	END
END

IF EXISTS(
	SELECT BillNumberID	FROM BillIndex	WHERE BillNumberID=@nBillID AND BillType=@nBillType AND PosBillType<>0	
)
BEGIN
	SET @strMsg='不能修改POS结存的单据！'
	SET @nCanModify=1
	RETURN
END

IF @nBillType IN (205,206)
BEGIN
	SET @strMsg='不能修改费用分摊单！'
	SET @nCanModify=1
	RETURN
END

IF @nBillType IN (165,166,167,168,169,170,171,172,173,174,175,177,178,198,192,195,191,197,179,182,200,186,196)
BEGIN
	SET @strMsg='不能修改维修类单据！'
	SET @nCanModify=1
	RETURN
END

IF @nBillType IN (9,14)
BEGIN
	IF EXISTS(
		SELECT BillNumberID	FROM BillIndex	WHERE BillNumberId=@nBillID AND BillType=@nBillType AND ifWX=1
	)
	BEGIN
		SET @strMsg='不能修改报损或报溢维修品的单据！'
		SET @nCanModify=1
		RETURN
	END
	
END

IF @nBillType IN (140,142,143,141,144,146,147,145)
BEGIN
	SET @strMsg='不能修改代销类单据！'
	SET @nCanModify=1
	RETURN
END

IF @nBillType=57
BEGIN
	IF EXISTS(
		SELECT ChangeAllStock FROM AdPriceBill WHERE BillNumberId=@nBillID AND ChangeAllStock=1
	)
	BEGIN
		SET @strMsg='不能修改调价全部仓库的成本调价单！'
		SET @nCanModify=1
		RETURN
	END
END


--如果物流类，费用单已经被摊销，则不能被修改（如果是草稿，则删除草稿）
IF EXISTS(
	SELECT BillNumberID
	FROM FaPiaoBill
	WHERE MainBillNumberID=@nBillID AND BillType=@nBillType
)
BEGIN
	SET @strMsg='不能修改已开发票的单据，如果要修改，请先删除发票！'
	SET @nCanModify=1
	RETURN
END

/*
IF @nBillType=34
BEGIN
	IF EXISTS(
		SELECT BillNumberId
		FROM BuyBill
		WHERE BillNumberId=@nBillID
		AND BackQty<>0
	)
	BEGIN
		SET @strMsg='不能修改关联了采购退货的采购入库单！'
		SET @nCanModify=1
		RETURN
	END
END

IF @nBillType=11
BEGIN
	IF EXISTS(
		SELECT BillNumberId
		FROM SaleBill
		WHERE BillNumberId=@nBillID
		AND BackQty<>0
	)
	BEGIN
		SET @strMsg='不能修改关联了销售退货的销售出库单！'
		SET @nCanModify=1
		RETURN
	END
END
*/

IF @nBillType=305
BEGIN
	IF EXISTS(
		SELECT BillNumberId
		FROM retailBill
		WHERE BillNumberId=@nBillID
		AND BackQty<>0
	)
	BEGIN
		SET @strMsg='不能修改关联了销售退货的零售单！'
		SET @nCanModify=1
		RETURN
	END
END

IF EXISTS(
	SELECT a.BillNumberId
	FROM ShareSourceBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId 
	WHERE a.FromBillNumberID=@nBillID
	AND a.FromBillType=@nBillType
	AND b.ifcheck='t'
	AND B.RedWord=0
) AND @nBillType NOT IN(11,34)
BEGIN
	SET @strMsg='您所需修改的单据已做费用分摊，不能修改单据，如需修改请先红冲对应的费用分摊单后再修改！'
	SET @nCanModify=1
	RETURN	
END

IF EXISTS(
	SELECT a.BillNumberId
	FROM ShareSourceBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	WHERE a.FromBillNumberID=@nBillID
	AND b.ifcheck='f'
)
BEGIN
	--通过触发器删除级联明细
	DELETE BillIndex
	WHERE BillNumberId IN
	(
		SELECT  BillNumberId
		FROM ShareSourceBill
		WHERE FromBillNumberID=@nBillID
	)
	AND ifcheck='f'
END


IF @nBillType=36
BEGIN
	IF EXISTS(
		SELECT a.BillNumberId
		FROM ShareFeeBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID
		AND b.ifcheck='t'
	)
	BEGIN
		SET @strMsg='不能修改已被费用分摊了的单据！'
		SET @nCanModify=1
		RETURN	
	END
	
	IF EXISTS(
		SELECT a.BillNumberId
		FROM ShareFeeBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID
		AND b.ifcheck='f'
	)
	BEGIN
		--通过触发器删除级联明细
		DELETE BillIndex
		WHERE BillNumberId IN
		(
			SELECT  BillNumberId
			FROM ShareFeeBill
			WHERE FromBillNumberID=@nBillID
		)
		AND ifcheck='f'
	END
END

/*
IF EXISTS(
	SELECT BillNumberID
	FROM PerformanceDistribution
	WHERE BillNumberId=@nBillID AND Total<>0
)
BEGIN
	SET @strMsg='不能修改已进行业绩分配的单据！'
	SET @nCanModify=1
	RETURN
END
*/

--判断系统是否开账

DECLARE
	@chvSTypeID		VARCHAR(50)
	
SELECT
	@chvSTypeID=STypeID
FROM BillIndex
WHERE BillNumberID=@nBillID

IF @nBillType IN (404,405)
	SELECT
		@chvSTypeID=STypeID
	FROM dbo.ReceiptBillIndex
	WHERE BillNumberID=@nBillID


IF NOT EXISTS(
	SELECT	TOP 1 1
	FROM	SType_UserConfig
	WHERE	ConfigNo = 1
	AND Value = 1
	AND STypeID=@chvSTypeID
)
BEGIN
	SET @strMsg='系统未开账，不能修改过账后单据！'
	SET @nCanModify=1
	RETURN
END

--判断系统是否月结	MonthProc
DECLARE @szPeriod1	datetime

SELECT	@szPeriod1 = StartDate
FROM	MonthProc
WHERE	MonthNo = '本期' AND STypeID=@chvSTypeID

IF EXISTS(
    SELECT  BillNumberId
    FROM    Billindex
    WHERE   BillNumberId = @nBillID
            AND BillType = @nBillType
            AND BillDate < @szPeriod1
    UNION ALL
    SELECT  BillNumberID
    FROM    dbo.ReceiptBillIndex
    WHERE   BillNumberId = @nBillID
            AND BillType = @nBillType
            AND BillDate < @szPeriod1
            AND Stypeid=@chvSTypeID
)
BEGIN
	SET @strMsg='不能修改月结前的过账单据！'
	SET @nCanModify=1
	RETURN
END
--判断成本算法

DECLARE
	@nCostingMethod		TINYINT,
	@AVERAGE			TINYINT,
	@FIFO				TINYINT,
	@LIFO				TINYINT,
	@HAND				TINYINT

	SET @AVERAGE	= 0		-- 移动加权平均
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	SET @HAND		= 3		-- 手工指定

EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output

IF @nCostingMethod<>@AVERAGE
BEGIN
	SET @strMsg='只能在移动加权成本算法下，才能修改过账后单据！'
	SET @nCanModify=1
	RETURN
END

IF @nBillType NOT IN(4,6,11,34,45,66,400,401,402,403,404,405,12,46)
	BEGIN
	/*
	IF EXISTS(
		SELECT BillNumberId
		FROM Billindex
		WHERE BillNumberId=@nBillID AND BillType=@nBillType
		AND CostSale=1
	)
	BEGIN
		SET @strMsg='不能修改成本价销售或调拨的单据！'
		SET @nCanModify=1
		RETURN
	END
	
	--有序列号的也不能修改
	IF EXISTS(
		SELECT BillNumberid
		FROM gp_inoutPtypeSerial
		WHERE BillNumberid=@nBillID AND BillType=@nBillType
	)
	BEGIN
		SET @strMsg='不能修改有序列号的单据！'
		SET @nCanModify=1
		RETURN
	END
	*/

	--已结算等，已引用等不能修改（规则需要跟需求确认）
	IF EXISTS(
		SELECT a.MoneyBillID
		FROM CompleteTotal a
		INNER JOIN BillIndex b
		ON a.MoneyBillID=b.BillNumberId
		WHERE a.GoodsBillID=@nBillID
		AND A.BillType=@nBillType
		AND b.ifcheck='t'
		AND b.RedWord=0
		UNION ALL
		SELECT a.MoneyBillID
		FROM CompleteGoodTotal a
		INNER JOIN BillIndex b
		ON a.MoneyBillID=b.BillNumberId
		WHERE a.GoodsBillID=@nBillID
		AND A.BillType=@nBillType
		AND b.ifcheck='t'
		AND b.RedWord=0
	)
	BEGIN
		SET @strMsg='不能修改按单或按商品结算的单据！'
		SET @nCanModify=1
		RETURN
	END


	IF EXISTS(
		SELECT a.MoneyBillID
		FROM CompleteTotal a
		INNER JOIN BillIndex b
		ON a.MoneyBillID=b.BillNumberId
		WHERE a.MoneyBillID=@nBillID
		AND A.BillType=@nBillType
		AND b.ifcheck='t'
		AND b.RedWord=0
		UNION ALL
		SELECT a.MoneyBillID
		FROM CompleteGoodTotal a
		INNER JOIN BillIndex b
		ON a.MoneyBillID=b.BillNumberId
		WHERE a.MoneyBillID=@nBillID
		AND A.BillType=@nBillType
		AND b.ifcheck='t'
		AND b.RedWord=0
	)
	BEGIN
		SET @strMsg='不能修改按单或按商品结算的单据！'
		SET @nCanModify=1
		RETURN
	END
END

IF @nBillType=169
BEGIN
	--送修单
	IF EXISTS(
		SELECT a.BillNumberID
		FROM wx_Bill_SendBack a
		INNER JOIN BillIndex b
		ON a.BillNumberID=b.BillNumberId
		WHERE a.SendBillNumberID=@nBillID
		AND b.RedWord=0
	)		
	BEGIN
		SET @strMsg='关联了送修返回单的送修单不能被修改！'
		SET @nCanModify=1
		RETURN
	END
END


IF @nBillType=171
BEGIN
	--报修单
	IF EXISTS(
		SELECT BillNumberId
		FROM BillIndex
		WHERE BaoXiuBillNumberID=@nBillID
		AND RedWord=0
	)		
	BEGIN
		SET @strMsg='关联了上门维修单的报修单不能被修改！'
		SET @nCanModify=1
		RETURN
	END
END



/*
--不能跨分支机构修改单据

--还有些判断是在修改过程中判断的

--如果不允许负库存，出现了负库存，也不能修改

--如果超过了信用额度或最高售价，也要控制

*/
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

把要修改的单据复制一份，以便后续好操作

*/
CREATE   PROCEDURE Gp_OldBill_Clone 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT
)
--@encode$--
AS

--为测试过程中好排错，新建表来保存要修改的单据主表和明细

DELETE Old_BillMulAccount
WHERE BillNumberId=@nBillID AND BillType=@nBillType

INSERT Old_BillMulAccount(BillNumberID,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
SELECT BillNumberID,ATypeID,Total,Comment,VipCardID,NTotalMoney,@nBillType
FROM BillMulAccount
WHERE BillNumberId=@nBillID

IF @nBillType=4
BEGIN
	DELETE  Old_GatheringBill WHERE BillNumberId=@nBillID 

	INSERT Old_GatheringBill(BillNumberID,ATypeID,Total,Comment,TeamNo,TeamNo1,STypeID,VipCardID,ID,RelevanceBillId,ntotal,BrandarTypeID,PreferenceMoney,NPreferenceMoney)
	SELECT BillNumberID,ATypeID,Total,Comment,TeamNo,TeamNo1,STypeID,VipCardID,ID,RelevanceBillId,ntotal,BrandarTypeID,PreferenceMoney,NPreferenceMoney
	FROM GatheringBill
	WHERE BillNumberId=@nBillID
END
ELSE IF @nBillType=66
BEGIN
	DELETE  Old_PayBill WHERE BillNumberId=@nBillID
	
	INSERT Old_PayBill(BillNumberID,ATypeID,Total,Comment,TeamNo,TeamNo1,STypeID,VipCardID,ID,RelevanceBillId,ntotal)
	SELECT BillNumberID,ATypeID,Total,Comment,TeamNo,TeamNo1,STypeID,VipCardID,ID,RelevanceBillId,ntotal
	FROM PayBill
	WHERE BillNumberId=@nBillID
END
ELSE IF @nBillType IN(189,190)
BEGIN
	DELETE Old_PreBill WHERE BillNumberId=@nBillID
	
	INSERT Old_PreBill(BillNumberID,BillType,Comment,ATypeID,Total,TeamNo,TeamNo1,STypeID,VipCardID,ID,RelevanceBillId,ntotal)
	SELECT BillNumberID,BillType,Comment,ATypeID,Total,TeamNo,TeamNo1,STypeID,VipCardID,ID,RelevanceBillId,ntotal
	FROM PreBill
	WHERE BillNumberId=@nBillID
END
ELSE IF @nBillType = 305
BEGIN
	DELETE FROM Old_retailBill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_retailBill (BillNumberId, PtypeId, TaxTotal, NTaxTotal)
	SELECT	BillNumberId, PtypeId, TaxTotal, NTaxTotal
	FROM	retailBill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType = 11
BEGIN
	DELETE FROM Old_SaleBill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_SaleBill (BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal)
	SELECT	BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal
	FROM	SaleBill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType = 12
BEGIN
	DELETE FROM Old_PT_Combin_SaleBill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_PT_Combin_SaleBill (BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal)
	SELECT	BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal
	FROM	PT_Combin_SaleBill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType = 45
BEGIN
	DELETE FROM Old_salebackbill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_salebackbill (BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal)
	SELECT	BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal
	FROM	salebackbill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType = 46
BEGIN
	DELETE FROM Old_PT_Combin_SaleBackBill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_PT_Combin_SaleBackBill (BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal)
	SELECT	BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal
	FROM	PT_Combin_SaleBackBill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType = 160
BEGIN
	DELETE FROM Old_salegoodsexchangebill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_salegoodsexchangebill (BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal,InOrOut)
	SELECT	BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal,InOrOut
	FROM	salegoodsexchangebill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType = 141
BEGIN
	DELETE FROM Old_commissionbill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_commissionbill (BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal)
	SELECT	BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal
	FROM	commissionbill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType = 405
BEGIN
	DELETE FROM Old_ReceiptBill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_ReceiptBill (BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal)
	SELECT	BillNumberId, PtypeId, TaxTotal, NTaxTotal, CompleteTotal, NCompleteTotal
	FROM	ReceiptBill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType IN (115,116)
BEGIN
	DELETE FROM Old_addebtbill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_addebtbill (BillNumberId, BrandarTypeID, BTypeID, Total, NTotal, CompleteTotal, NCompleteTotal)
	SELECT	BillNumberId, BrandarTypeID, BTypeID, Total, NTotal, CompleteTotal, NCompleteTotal
	FROM	addebtbill
	WHERE	BillNumberId=@nBillID
END
ELSE IF @nBillType IN (93,36)
BEGIN
	DELETE FROM Old_moneybill WHERE BillNumberId=@nBillID
	
	INSERT INTO Old_moneybill (BillNumberId, BrandarTypeID, Total, NTotal)
	SELECT  BillNumberId, BrandarTypeID, Total, NTotal
	FROM	MoneyBill
	WHERE	BillNumberId=@nBillID
END


DELETE Old_ListTable WHERE BillNumberID=@nBillID AND BillType=@nBillType
INSERT Old_ListTable(BillNumberID,ATypeID,BTypeID,STypeID,BillType)
SELECT BillNumberID,ATypeID,BTypeID,STypeID,BillType
FROM ListTable
WHERE BillNumberId=@nBillID

DELETE  Old_CompleteTotal WHERE MoneyBillID=@nBillID
INSERT Old_CompleteTotal(GoodsBillID,MoneyBillID,CompleteTotal,Draft,BillDate,ETypeID,BillType)
SELECT GoodsBillID,MoneyBillID,CompleteTotal,Draft,BillDate,ETypeID,BillType
FROM CompleteTotal
WHERE MoneyBillID=@nBillID

DELETE  Old_CompleteGoodTotal WHERE MoneyBillID=@nBillID
INSERT Old_CompleteGoodTotal(GoodsBillID,MoneyBillID,InOrOut,CompleteGoodQty,Draft,BillDate,PTypeID,BillID,CompleteGoodTotal,Price,BillType)
SELECT GoodsBillID,MoneyBillID,InOrOut,CompleteGoodQty,Draft,BillDate,PTypeID,BillID,CompleteGoodTotal,Price,BillType
FROM CompleteGoodTotal
WHERE MoneyBillID=@nBillID

DELETE Old_BillMulBrand WHERE BillNumberId = @nBillID
INSERT INTO Old_BillMulBrand (STypeID, BTypeID, BrandarTypeID, BillNumberId, BillType, Cid, Rate, TaxTotal, NTaxTotal, PreferenceMoney, NPreferenceMoney, TotalInMoney, NTotalInMoney, YSTotalInMoney, NYSTotalInMoney, TheOrderARTotal, NTheOrderARTotal, isIni)
SELECT STypeID, BTypeID, BrandarTypeID, BillNumberId, BillType, Cid, Rate, TaxTotal, NTaxTotal, PreferenceMoney, NPreferenceMoney, TotalInMoney, NTotalInMoney, YSTotalInMoney, NYSTotalInMoney, TheOrderARTotal, NTheOrderARTotal, isIni
FROM   BillMulBrand
WHERE	BillNumberId = @nBillID

DELETE Old_CompleteBrandarTotal WHERE GoodsBillID = @nBillID
INSERT INTO Old_CompleteBrandarTotal (GoodsBillID, MoneyBillId, BrandarTypeID, STypeId, BTypeId, BillType, BillDate, BillCode, CId,  CompleteTotal, NCompleteTotal, Comment, EtypeID, IsDraft, IsIni, DetailId)
SELECT  GoodsBillID, MoneyBillId, BrandarTypeID, STypeId, BTypeId, BillType, BillDate, BillCode, CId,  CompleteTotal, NCompleteTotal, Comment, EtypeID, IsDraft, IsIni, DetailId
FROM    CompleteBrandarTotal
WHERE   GoodsBillID = @nBillID

--写入老的单据明细表，先不区分出入库，因为写入的明细可能还没参与成本重算，所以不删除老的记录
DELETE Old_Bill WHERE BillNumberID=@nBillID AND BillType=@nBillType

DECLARE
	@datPostTime	DATETIME
	
SELECT @datPostTime=PostTime
FROM Billindex
WHERE BillNumberId=@nBillID AND BillType=@nBillType	

IF @nBillType NOT IN (404,405)
BEGIN
	--这里写入主要是为了检查负库存等
	INSERT Old_Bill(BillNumberID,BillType,ID,PTypeID,KTypeID,STypeID,PostTime,BillDate)
	SELECT DISTINCT BillNumberID,BillType,ID,PTypeID,KTypeID,STypeID,@datPostTime,BillDate
	FROM InOutstocktable
	WHERE BillNumberId=@nBillID AND BillType=@nBillType AND IsService=0
END


IF @nBillType NOT IN (404,405)
BEGIN
	--这里写入是为了重算成本，因为存在单据被反复修改，但一次都没成本重算的可能性，所以这里不清除以前的记录
	INSERT CostRe_Bill(BillNumberID,BillType,PTypeID,KTypeID,STypeID,PostTime,BillDate)
	SELECT DISTINCT a.BillNumberID,a.BillType,a.PTypeID,a.KTypeID,a.STypeID,@datPostTime,a.BillDate
	FROM InOutstocktable a
	WHERE a.BillNumberId=@nBillID AND a.BillType=@nBillType AND a.IsService=0
	AND NOT EXISTS(
		SELECT BillNumberID
		FROM CostRe_Bill b
		WHERE b.BillNumberID=@nBillID AND b.BillType=@nBillType
		AND a.PtypeId=b.PTypeID
		AND a.KtypeId=b.KTypeID
		AND b.Posttime=@datPostTime
	)
END

--记录单据修改历史
EXEC GP_Modify_Bill_Log @BillNumberID=@nBillID,@BillType=@nBillType
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT
	
SELECT
	@nBillID=2,
	@nBillType=34
	
BEGIN TRAN	

EXEC	Gp_OldBill_Clone 
	@nBillID,
	@nBillType


COMMIT TRAN
--ROLLBACK TRAN


*/



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
	删除老单据相关数据
*/
CREATE       PROCEDURE GP_OldBill_Clone_Del

--@encode$--
AS
SET NOCOUNT ON 

DELETE FROM  Old_BillMulAccount WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
DELETE FROM  Old_GatheringBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
DELETE FROM  Old_PayBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
DELETE FROM  Old_CompleteTotal WHERE GoodsBillID NOT IN (SELECT BillNumberId FROM BillIndex)
DELETE FROM  Old_CompleteGoodTotal WHERE GoodsBillID NOT IN (SELECT BillNumberId FROM BillIndex)
DELETE FROM  Old_Bill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
DELETE FROM  Old_ListTable WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
DELETE FROM  Old_PreBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

新单据保存后，过账，修改后续单据

作者：冯波



*/
CREATE   PROCEDURE Gp_OldBill_DealModify 
(
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@nBillType			INT,
	@szCheckMan			VARCHAR(50),			-- 制单人 ID 值
	@chvOpID			VARCHAR(50),			-- 当前操作员 ID 值
	@datPostTime		DATETIME,
	@nRet				INT	OUT,				--0表示修改成功，其他都表示出错
	@strMsg				VARCHAR(500)	OUT,	--返回的错误提示信息
	@KTypeID			VARCHAR(50) = '' OUT	-- 返回仓库ID值，针对多仓库应用
)
--@encode$--
AS

BEGIN TRAN DealModify
SAVE TRAN DealModifyPoint

SELECT
	@nRet=0,
	@strMsg=''
	

	
DECLARE
	@chvSTypeID			VARCHAR(50)

IF @nBillType IN (404,405)
BEGIN
	SELECT
		@chvSTypeID=STypeID
	FROM ReceiptBillIndex
	WHERE BillNumberId=@nBillID		
END
ELSE
BEGIN 	
	SELECT
		@chvSTypeID=STypeID
	FROM Billindex
	WHERE BillNumberId=@nBillID		
END

	
	
--对新单据重新过账，但不能调用老的过账	
EXEC Gp_NewBill_Audit 
	@nBillID,
	@nBillType,
	@szCheckMan,
	@chvOpID,
	@nRet OUT,
	@strMsg OUT,
	@KTypeID OUT
	
IF @nRet<>0 
BEGIN
	ROLLBACK TRAN DealModifyPoint
	COMMIT TRAN DealModify
	RETURN @nRet
END	

IF @nBillType=66
BEGIN
	DELETE Old_PayBill WHERE BillNumberId=@nBillID
END

IF @nBillType=4
BEGIN	
	DELETE Old_GatheringBill WHERE BillNumberId=@nBillID
END	

IF @nBillType IN (189,190)
BEGIN
	DELETE Old_PreBill WHERE BillNumberId=@nBillID
END


DELETE Old_BillMulAccount WHERE BillNumberId=@nBillID AND BILLTYPE=@nBillType

IF @nBillType IN (4,66)
BEGIN
	DELETE Old_CompleteGoodTotal WHERE MoneyBillID=@nBillID
	DELETE Old_CompleteTotal WHERE MoneyBillID=@nBillID
END
ELSE
BEGIN
	DELETE Old_CompleteTotal WHERE GoodsBillID=@nBillID AND BILLTYPE=@nBillType
	DELETE Old_CompleteTotal WHERE GoodsBillID=@nBillID AND BILLTYPE=@nBillType
END	

DELETE Old_ListTable WHERE BillNumberId=@nBillID AND BillType=@nBillType

COMMIT TRAN DealModify

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*


DECLARE
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@nBillType			INT,
	@szCheckMan			VARCHAR(50),			-- 制单人 ID 值
	@chvOpID			VARCHAR(50),			-- 当前操作员 ID 值
	@datPostTime		DATETIME,
	@nRet				INT,					--0表示修改成功，其他都表示出错
	@strMsg				VARCHAR(500),			--返回的错误提示信息
	@KTypeID			VARCHAR(50)				-- 返回仓库ID值，针对多仓库应用
	
	
SELECT
	@nBillID=1,
	@nBillType=34,
	@szCheckMan='00001',
	@chvOpID='00001',
	@datPostTime=GETDATE()	

BEGIN TRAN

	EXEC	Gp_OldBill_DealModify 
	@nBillID,
	@nBillType,
	@szCheckMan,
	@chvOpID,
	@datPostTime,
	@nRet	OUT,
	@strMsg	OUT,
	@KTypeID OUT	

SELECT 'returnvalue',@nRet,@strMsg,@KTypeID

SELECT * FROM LISTTABLE WHERE BILLNUMBERID=@NBILLID AND BILLTYPE=@NBILLTYPE

SELECT * FROM ATYPE_TOTAL

SELECT * FROM BTYPE_ARAPTOTAL


ROLLBACK TRAN

*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

把老单据清掉，修改相关单据

作者：冯波



*/
CREATE   PROCEDURE Gp_OldBill_DealModifyOld 
(
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nRet				INT OUT,				--0表示修改成功，其他都表示出错
	@strMsg				VARCHAR(500) OUT		--返回的错误提示信息
)
--@encode$--
AS

BEGIN TRAN DealModifyOld
SAVE TRAN DealModifyOldPoint

EXEC dbo.GP_DoRedWordLock @nBillID,@nBillType

SELECT
	@nRet=0,
	@strMsg=''
	
EXEC Gp_OldBill_Clone @nBillID,@nBillType

EXEC @nRet=Gp_OldBill_Reverse	@nBillID,@nBillType,@strMsg OUT

IF @nRet <> 0
BEGIN
	ROLLBACK TRAN DealModifyOldPoint
	COMMIT TRAN DealModifyOld
END
ELSE
BEGIN
	COMMIT TRAN DealModifyOld
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nRet				INT,					--0表示修改成功，其他都表示出错
	@strMsg				VARCHAR(500)
	
SELECT
	@nBillID=1,
	@nBillType=34	

BEGIN TRAN

EXEC	Gp_OldBill_DealModifyOld 
	@nBillID,
	@nBillType,
	@nRet OUT,				--0表示修改成功，其他都表示出错
	@strMsg OUT				--返回的错误提示信息

SELECT @nRet,@strMsg

SELECT * FROM LISTTABLE WHERE BILLNUMBERID=@NBILLID AND BILLTYPE=@NBILLTYPE

SELECT * FROM ATYPE_TOTAL

SELECT * FROM BTYPE_ARAPTOTAL



--ROLLBACK TRAN

COMMIT TRAN





*/



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波


对于入库类单据，先找出他们会影响的后续单据

1，正常单据的正常库存
2，代销类单据的代销库存
3，维修类单据

是否包含红冲单据

2017-02-06 梁晰 同价调拨单回填状态

*/
CREATE   PROCEDURE Gp_OldBill_Del 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@strPTypeIDOutPut	VARCHAR(50)='' OUT
)
--@encode$--
AS

--需要看能否红冲回去（这个要考虑下）
DECLARE
	@nRet				INT

EXEC @nRet=Gp_OldBill_Reverse @nBillID,@nBillType,@strPTypeIDOutPut OUT

IF @nRet=0
BEGIN
	--执行删除单据的过程
	EXEC @nRet=Gp_OldBill_DelBill @nBillID,@nBillType
END

IF @nBillType IN (17,21,187)
BEGIN
     EXEC Gp_BackFillAllotBillState @nBillID,@nBillType
END

RETURN @nRet


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
	作者：冯波
	描述：删除单据的所有信息(依赖已存在的触发器去删除单据明细)
*/
CREATE    PROCEDURE Gp_OldBill_DelBill
(
	@nBillID		BIGINT,
	@nBillType		INT--单据类型
)
--@encode$--
AS
SET NOCOUNT ON


-- 删除维修受理单
UPDATE 	RepairEngage 
SET 	Stat =1 
WHERE 	BillnumberID IN
(
		Select 	EngageBillID 
		From 	RepairDeal 
		WHERE 	BillNumberID=@nBillID
)

DELETE FROM RepairDeal 
WHERE BillnumberID IN 
(
	SELECT BillNumberID 
	FROM BillIndex 
	WHERE BillType = 157 AND BillNumberID=@nBillID
)
--处理按单结算的问题
DELETE FROM CompleteTotal WHERE (GoodsBillID=@nBillID OR MoneyBillID=@nBillID) AND BillType=@nBillType

--处理按商品结算的问题
DELETE FROM CompleteGoodTotal WHERE (GoodsBillID=@nBillID OR MoneyBillID=@nBillID) AND BillType=@nBillType


--处理按品牌结算的问题
DELETE FROM CompleteBrandarTotal WHERE (GoodsBillID=@nBillID OR MoneyBillID=@nBillID) AND BillType=@nBillType

-- 删除发票
DELETE FROM invoiceBill 
WHERE BillNumberID=@nBillID

--删除QP单据信息
DELETE FROM Billindex_CarRepair 
WHERE BillNumberID=@nBillID

--删除附件
DELETE FROM BillAttachFiles 
WHERE BillNumberID=@nBillID AND BillType=@nBillType

--删除附件日志
DELETE FROM dbo.BillAttachFilesLog
WHERE BillNumberId = @nBillID AND BillType=@nBillType

--删除多账户信息
DELETE FROM BillMulAccount WHERE BillNumberID=@nBillID AND BillType=@nBillType

--删除多账户品牌信息
DELETE FROM BillMulBrand WHERE BillNumberID=@nBillID AND BillType=@nBillType

--删除单据操作日志
DELETE FROM BillOperateLog 
WHERE BillNumberID=@nBillID AND BillType=@nBillType

--删除打印日志
--DELETE FROM PrintRecord 
--WHERE BillNumberID=@nBillID
UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId=@nBillID AND BillType=@nBillType


--删除增加打印次数日志
DELETE FROM AddPrintCountRecord 
WHERE BillNumberID=@nBillID  AND BillType=@nBillType

--删除销售出库单时，删除调用电脑配置单的记录
IF EXISTS (
	SELECT BillNumberId
	FROM BillIndex 
	WHERE BillNumberId=@nBillID 
	AND BillType='11'
)
BEGIN
	DELETE DiyBillTypePSaleTypeID 
	WHERE SalebillNumberId=@nBillID	
END	

--最后执行这步
DELETE FROM dbo.BillIndex 
WHERE BillNumberID=@nBillID
		
IF @@ROWCOUNT = 0
	RETURN -2
ELSE
	RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

修改单据中新单据的处理

作者：冯波



*/
CREATE   PROCEDURE Gp_OldBill_Modify 
(
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@nBillType			INT,
	@szCheckMan			VARCHAR(50),			-- 制单人 ID 值
	@chvOpID			VARCHAR(50),			-- 当前操作员 ID 值
	@datPostTime		DATETIME,
	@nRet				INT OUT,				--0表示修改成功，其他都表示出错
	@strMsg				VARCHAR(500) OUT,		--返回的错误提示信息
	@KTypeID			VARCHAR(50) = '' OUT	-- 返回仓库ID值，针对多仓库应用
)
--@encode$--
AS

BEGIN TRAN OldBillModify
SAVE TRAN OldBillModifyPoint

SELECT
	@nRet=0,
	@strMsg=''	
	
CREATE TABLE #NewInfo(
	PTypeID		VARCHAR(50),
	KTypeID		VARCHAR(50)
)

CREATE TABLE #OldInfo(
	PTypeID		VARCHAR(50),
	KTypeID		VARCHAR(50)
)
IF @nBillType IN (11,12,140,402)--销售出库单、委托代销发货单、组合品销售发货单需要解锁商品
BEGIN
	EXEC dbo.GP_DoClear @nBillID, @nBillType 
END

--新单据过账并处理后续单据
EXEC Gp_OldBill_DealModify
	@nBillID,
	@nBillType,
	@szCheckMan,
	@chvOpID,
	@datPostTime,
	@nRet		OUT,
	@strMsg		OUT,
	@KTypeID	OUT



--修改后校验
IF @nRet=0
BEGIN
	EXEC Gp_OldBill_Verify 
		@nBillID,
		@nBillType,
		@nRet		OUT,
		@strMsg		OUT
END

IF @nRet <> 0
BEGIN
	ROLLBACK TRAN OldBillModifyPoint
	COMMIT TRAN OldBillModify
END
ELSE
BEGIN
	IF @nBillType IN (11,12,34,144,140,400,402)
	BEGIN
		--订单过账数量
		EXEC GP_Deal_OrderReachQTY @nBillID,@nBillType,'+'
	END
	
	-- 检测销售、采购单关联订单的完成状态
	IF @nBillType NOT IN (203,310,404,405)
	BEGIN
		EXEC @nRet = GP_AuditingCheckOrderState @nBillID,1
	END
	
	
	--全面修改单据更改明细draftflag
	DECLARE @TableName VARCHAR(100),@IndexName VARCHAR(50),@SQL VARCHAR(1280)
	SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@nBillType
	IF @IndexName='BillIndex'
	BEGIN
		DECLARE @DraftFlag BIT = 1,
				@IsiniFlag BIT = 0
				
		SELECT @DraftFlag=draft,@IsiniFlag=IsIni FROM dbo.BillIndex WHERE BillNumberId=@nBillID AND BillType=@nBillType

		-- 处理单据明细与主表的过账及期初字段
		SET @SQL = 'UPDATE ' + @TableName + ' SET DraftFlag=' + CAST(@DraftFlag as varchar(4)) + ',IsIniFlag=' + CAST(@IsiniFlag as varchar(4)) + '
					WHERE BillNumberId=' + CAST(@nBillID AS varchar) + ' AND (DraftFlag!=' + CAST(@DraftFlag as varchar(4)) + ' OR IsIniFlag!=' + CAST(@IsiniFlag as varchar(4))+')';
		EXEC (@SQL)
	END
	
	
	COMMIT TRAN OldBillModify
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

入库，得到会影响的单据(只会影响有出库的单据)

但注意信用额度会否相互影响

只考虑InOutStockTable


*/
CREATE   PROCEDURE Gp_OldBill_ReferTo 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT
)
--@encode$--
AS




IF @nBillType NOT IN (34,11,45,6,160,161,9,14,57,17,21,187,188,201,202,16,139,126,305)
BEGIN
	RETURN
END


--查询过账时间在其后的单据
DECLARE
	@datPostDate		DATETIME
	
SELECT
	@datPostDate=PostTime
FROM Billindex
WHERE BillNumberId=@nBillID



--这里还需要按单据类型和出入库性质来具体筛选

--先把老的记录中的相关PTYPEID,KTYPEID得到

INSERT #OldInfo(PTypeID,KTypeID)
SELECT PtypeId,KTypeID
FROM Old_Bill
WHERE BillNumberId=@nBillID
--AND BillType IN ()


DECLARE
	@chvBillName		VARCHAR(50),
	@strSql				VARCHAR(1000)
	
EXEC Gp_GetBillName @nBillType,@chvBillName OUT

SELECT @strSql='
INSERT #NewInfo(PTypeID,KTypeID)
SELECT DISTINCT PtypeId,KTypeID
FROM InOutStockTable
WHERE BillNumberId='+CAST(@nBillID AS VARCHAR(50))


EXEC(@strSql)


INSERT #AfterModifyBill(BillNumberID,BillType,BillID,PTypeID,KTypeID,SortID,Qty,PostTime)
--一般来说，出库部分的都需要处理
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
FROM InOutstocktable a
INNER JOIN
(
	SELECT PTypeID,KTypeID
	FROM #OldInfo
	UNION
	SELECT PTypeID,KTypeID
	FROM #NewInfo
) b
ON a.PtypeId=b.PTypeID 
AND a.KtypeId=b.KTypeID
WHERE a.PostTime>@datPostDate
AND a.Audited=1
AND a.Qty<0
AND a.BillType NOT IN (140,142,143,141)
UNION ALL
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
FROM InOutstocktable a
INNER JOIN
(
	SELECT PTypeID,KTypeID
	FROM #OldInfo
	UNION
	SELECT PTypeID,KTypeID
	FROM #NewInfo
) b
ON a.PtypeId=b.PTypeID 
AND a.KtypeId=b.KTypeID
WHERE a.PostTime>@datPostDate
AND a.Audited=1
AND a.Qty>0
AND a.BillType NOT IN (34,161,144,21,188,201,16,57,174,140,142,143,141)

CREATE TABLE #MoveSameBill(
	BillNumberID	BIGINT,
	BillType		INT,
	BillID			BIGINT,
	PTypeID			VARCHAR(50),
	KTypeID			VARCHAR(50),
	PostTime		DATETIME,
	SortID			INT
)

INSERT #MoveSameBill
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.PostTime,a.SortID
FROM InOutstocktable a
INNER JOIN
(
	SELECT a.BillNumberId,a.ID
	FROM InOutstocktable a
	INNER JOIN
	(
		SELECT PTypeID,KTypeID
		FROM #OldInfo
		UNION
		SELECT PTypeID,KTypeID
		FROM #NewInfo
	) b
	ON a.PtypeId=b.PTypeID 
	AND a.KtypeId=b.KTypeID
	WHERE a.PostTime>@datPostDate
	AND a.Audited=1
	AND a.Qty<0
	AND a.BillType=17
) b
ON a.BillNumberId=b.BillNumberId
AND a.ID=b.ID
WHERE a.BillType=17
AND a.Audited=1
AND a.Qty>0


DECLARE
	@intGoOn	BIT
	
SELECT @intGoOn=0

WHILE @intGoOn=0
BEGIN
	INSERT #MoveSameBill
	SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.PostTime,a.SortID
	FROM InOutstocktable a
	INNER JOIN
	(
		--从同价调拨入库后查后续的同价调拨单
		SELECT a.BillNumberId,a.ID,a.PtypeId,a.KtypeId,a.SortID
		FROM InOutstocktable a
		INNER JOIN
		(
			SELECT PTypeID,KTypeID,MIN(SortID) AS SortID
			FROM #MoveSameBill 
			GROUP BY PTypeID,KTypeID
		) b
		ON a.PtypeId=b.PTypeID 
		AND a.KtypeId=b.KTypeID
		AND a.Audited=1
		AND a.Qty<0
		AND a.BillType=17
		WHERE a.SortID>b.SortID
	) b
	ON a.BillNumberId=b.BillNumberId
	AND a.ID=b.ID
	WHERE a.BillType=17
	AND a.Audited=1
	AND a.Qty>0
	AND NOT EXISTS
	(
		SELECT b.BillID
		FROM #MoveSameBill b
		WHERE b.BillID=a.ID
	)
	
	IF @@ROWCOUNT=0
	BEGIN
		SET @intGoOn=1
	END
END



INSERT #AfterModifyBill(BillNumberID,BillType,BillID,PTypeID,KTypeID,SortID,Qty,PostTime)
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
FROM
(
	SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
	FROM InOutstocktable a
	INNER JOIN
	(
		SELECT PTypeID,KTypeID,MIN(SortID) AS SortID
		FROM #MoveSameBill 
		GROUP BY PTypeID,KTypeID
	) b
	ON a.PtypeId=b.PTypeID 
	AND a.KtypeId=b.KTypeID
	WHERE a.SortID>=b.SortID
	AND a.Audited=1
	AND a.Qty<0
	AND a.BillType NOT IN (140,142,143,141)
	--AND a.HandZeroCost=0
	UNION ALL
	SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
	FROM InOutstocktable a
	INNER JOIN
	(
		SELECT PTypeID,KTypeID,MIN(SortID) AS SortID
		FROM #MoveSameBill 
		GROUP BY PTypeID,KTypeID
	) b
	ON a.PtypeId=b.PTypeID 
	AND a.KtypeId=b.KTypeID
	WHERE a.SortID>=b.SortID
	AND a.Audited=1
	AND a.Qty>0
	AND a.BillType NOT IN (34,161,144,21,188,201,16,57,174,140,142,143,141)
	--AND (a.HandZeroCost=0 OR (a.HandZeroCost=1 AND a.BillType=17))
) a
WHERE NOT EXISTS
(
	SELECT b.BillID
	FROM #AfterModifyBill b
	WHERE b.SortID=a.SortID
)


--对于本单的出库或入库类部分，也加入进去，以便重算
INSERT #AfterModifyBill(BillNumberID,BillType,BillID,PTypeID,KTypeID,SortID,Qty,PostTime)
SELECT a.BillNumberId,a.BillType,a.ID,a.PtypeId,a.KtypeId,a.SortID,a.Qty,a.PostTime
FROM InOutstocktable a
WHERE a.BillNumberId=@nBillID AND 
(a.Qty<0 OR (a.Qty>0 AND a.BillType NOT IN (34,161,144,21,188,201,16,57,174)))


INSERT #StockInfo(PTypeID,KTypeID)
SELECT DISTINCT a.PTypeID,a.KTypeID
FROM #AfterModifyBill a


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波




1，正常单据的正常库存
2，代销类单据的代销库存
3，维修类单据

是否包含红冲单据

*/
CREATE   PROCEDURE Gp_OldBill_Reverse 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@strPTypeIDOutPut	VARCHAR(500) OUT
)
--@encode$--
AS

SELECT @strPTypeIDOutPut=''

--需要看能否红冲回去（这个要考虑下）

DECLARE
	@nRet				INT
	
SELECT 	
	@strPTypeIDOutPut=''

--把InOutStockTable,ListTable的值反向

DECLARE		
	@intAdPriceBillNumberID		INT,
	@intAdPriceNewBillNumberID	INT,
	@strSTypeID					VARCHAR(50),
	@strBTypeID					VARCHAR(50),
	@intCID						INT,
	@nAllowNegativeStock		INT,
	@vipBillStoredByStypeId		INT=0--会员储值结算使用单据所选分支机构进行储值余额判断
	SELECT @vipBillStoredByStypeId=Value FROM Userconfig WHERE ConfigName='vipBillStoredByStypeId'
	
-- 查询是否允许负库存 (适用于移动加权平均成本核算)
EXEC GP_GetSubValue 'AllowNegativeStock', '00001',@nAllowNegativeStock output	
	

--处理序列号
IF @nBillType IN (11,34) AND EXISTS( SELECT TOP 1 1  FROM dbo.BillIndex WHERE BillNumberId = @nBillID AND IsLend= 1)
BEGIN
	
	DECLARE		
	@SQL			NVARCHAR(MAX),
	@intDealSerial	TINYINT,
	@BillName		VARCHAR(100)
					
	SELECT @BillName=detailTable
			FROM BillName
			WHERE Billtype=@nBillType
			
	SET @SQL='IF EXISTS(SELECT BillNumberID FROM '+@BillName+' WHERE BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND CAST(Serial AS VARCHAR(MAX))<>'''') SET @intDealSerial=1 ELSE SET @intDealSerial=0'
	EXECUTE sp_executesql @SQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
	SELECT @intDealSerial AS '@intDealSerial'
	--借欠转采购or销售序列号红冲回去
	IF @intDealSerial=1 
	BEGIN
		IF @nBillType = 34
		BEGIN
				UPDATE a SET a.STATE = b.STATE FROM gp_LendPtypeSerial a JOIN (
				SELECT * FROM (
					SELECT ROW_NUMBER() OVER(PARTITION BY Serial ORDER BY id DESC) AS rn,State,Serial FROM gp_inoutPtypeSerial
					WHERE Serial IN (
						SELECT Serial FROM gp_inoutPtypeSerial WHERE BillType = @nBillType AND BillNumberid = @nBillID
					) AND BillType IN(71,87,88,34)
				) AS t WHERE t.rn = 2 ) b ON a.Serial = b.Serial WHERE b.STATE != CASE @nBillType WHEN 34 THEN 18 ELSE 0 END
				--序列号的状态为：借出时，不回写序列号的状态，只将状态为“借进”、“借出还回”的状态更改为“已转采购”。 18 借出
		END
		ELSE IF @nBillType = 11
		BEGIN
			UPDATE a SET a.STATE = b.STATE FROM gp_LendPtypeSerial a JOIN (
			SELECT * FROM (
				SELECT ROW_NUMBER() OVER(PARTITION BY Serial ORDER BY id DESC) AS rn,State,Serial FROM gp_inoutPtypeSerial
				WHERE Serial IN (
					SELECT Serial FROM gp_inoutPtypeSerial WHERE BillType = @nBillType AND BillNumberid = @nBillID
				) 
			) AS t WHERE t.rn = 2 ) b ON a.Serial = b.Serial WHERE b.STATE != CASE @nBillType WHEN 34 THEN 18 ELSE 0 END
			--序列号的状态为：借出时，不回写序列号的状态，只将状态为“借进”、“借出还回”的状态更改为“已转采购”。 18 借出
		END

	END 
END

IF @nBillType IN (305,11,6,140,141,142,34,45,144,145,146,17,21,9,14,16,155,157,139,126,160,161,165,166,167,168,169,170,172,173,174,175,183,187,188,201,202,215,57,400,401,402,403,12,46)
BEGIN
	EXEC @nRet = GP_SerialRedWord @nBillID,@nBillType
	
	--PRINT('serial')
	--PRINT(@nRet)

	IF @nRet <> 0 RETURN @nRet
END


--删除老单据的序列号痕迹

DELETE gp_inoutPtypeSerial
WHERE BillNumberid=@nBillID AND BillType=@nBillType	

--针对暂估发票的特殊处理  start
IF @nBillType IN (404,405)
BEGIN
	--对成本调价单的红冲要在调用后处理
	IF EXISTS(
		SELECT a.ID
		FROM AdPriceBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID
	)
	BEGIN

		SELECT @intAdPriceBillNumberID=a.BillNumberId,@strSTypeID=b.StypeID,@strBTypeID=b.Btypeid,@intCID=CID
		FROM AdPriceBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID

		
		
		
		MERGE GoodsStocks AS t
		USING(
			SELECT PTypeID,KTypeID,SUM(-Total) AS Total
			FROM AdPriceBill
			WHERE BillNumberID=@intAdPriceBillNumberID
			GROUP BY PTypeID,KTypeID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		WHEN MATCHED THEN 
			UPDATE SET t.Total=t.Total+s.Total,t.Price=CASE t.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(t.Total+s.Total AS  NUMERIC(24, 10) )/CAST(t.Qty AS  NUMERIC(24, 10) ),4) END
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,Qty,Price,Total) 
			VALUES(s.PtypeId,s.KTypeID,0,0,s.Total)
		;
		
		
		MERGE GoodsStocks_Qty AS t
		USING(
			SELECT DISTINCT PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID
			FROM AdPriceBill
			WHERE BillNumberID=@intAdPriceBillNumberID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		AND t.GoodsNumber=s.GoodsNumber AND t.ProduceDate=s.ProduceDate AND t.ValidDate=s.ValidDate
		AND t.CargoID=s.CargoID
	WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,CargoID,ItemID,IsCombined) 
			VALUES(s.PtypeId,s.KTypeID,s.GoodsNumber,s.ProduceDate,s.ValidDate,0,0,0,s.CargoID,0,0)
		;

		--GOODSSTOCKS_QTY不变

		

		UPDATE ListTable
		SET Total=-Total,Ntotal=-Ntotal,CostTotal=-CostTotal
		WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57
		
		EXEC @nRet = Gp_ModifyBAndAtype_Total @intAdPriceBillNumberID,57
		

		
		DELETE ListTable WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57
		
		DELETE AdPriceBill WHERE BillNumberId=@intAdPriceBillNumberID
		
		DELETE BillIndex WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57

	END		
		
	
	
	
	--处理发票状态
	EXEC GP_Receipt_Deal @nBillID,1
END



IF EXISTS(
	SELECT BillNumberID
	FROM InOutstocktable
	WHERE BillNumberId=@nBillID AND BillType=@nBillType
)
BEGIN
	UPDATE	InOutstocktable
	SET		
		Qty = -Qty,
		Total = -Total,
		CostTotal = -CostTotal,
		GoodsCostPrice = CostPrice,
		SaleTotal = -SaleTotal,
		TaxTotal = -TaxTotal,
		NQty=-NQty,
		NTotal=-NTotal,
		NSaleTotal=-NSaleTotal,
		NTaxTotal=-NTaxTotal
	WHERE	BillNumberID = @nBillID AND BillType=@nBillType
END

IF EXISTS(
	SELECT BillNumberID
	FROM wx_InOutStockTable
	WHERE BillNumberId=@nBillID AND BillType=@nBillType
)
BEGIN
	UPDATE	wx_InOutStockTable
	SET		
		Qty = -Qty,
		Total = -Total,
		CostTotal = -CostTotal,
		GoodsCostPrice = CostPrice,
		SaleTotal = -SaleTotal,
		TaxTotal = -TaxTotal,
		NQty=-NQty,
		NTotal=-NTotal,
		NSaleTotal=-NSaleTotal,
		NTaxTotal=-NTaxTotal
	WHERE	BillNumberID = @nBillID AND BillType=@nBillType
END


IF EXISTS(
	SELECT BillNumberID
	FROM ListTable
	WHERE BillNumberId=@nBillID AND BillType=@nBillType
)
BEGIN
	UPDATE	ListTable
	SET		
		Total = -Total,
		CostTotal = -CostTotal,
		Ntotal=-Ntotal
	WHERE	BillNumberID = @nBillID AND BillType=@nBillType
END
/******lend to buy sale******/
IF @nBillType = 34  
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.BuyBill WHERE BillNumberId=@nBillID AND LendBillNumberID<>0)
	BEGIN
		UPDATE A SET A.BuyQty = ISNULL( A.BuyQty ,0) - B.Qty
		FROM LendBill A JOIN (
			 SELECT @nBillID AS BillNumberId, LendBillNumberID,SUM(qty) AS Qty 
			 FROM dbo.BuyBill
			 WHERE BillNumberId = @nBillID AND LendBillNumberID <> 0
			 GROUP BY LendBillNumberID
		) B ON A.ID=B.LendBillNumberID
	END
END
IF @nBillType = 11  
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.SaleBill WHERE BillNumberId=@nBillID AND LendBillNumberID<>0)
	BEGIN
		UPDATE A SET A.SaleQty = ISNULL( A.SaleQty ,0) - B.Qty
		FROM LendBill A JOIN (
			SELECT @nBillID AS BillNumberId, LendBillNumberID,SUM(qty) AS Qty 
			FROM dbo.SaleBill
			WHERE BillNumberId = @nBillID AND LendBillNumberID <> 0
			GROUP BY LendBillNumberID
		) B ON A.ID=B.LendBillNumberID
	END 
END
IF @nBillType IN (11,34) AND EXISTS( SELECT TOP 1 1  FROM dbo.BillIndex WHERE BillNumberId = @nBillID AND IsLend= 1)
BEGIN
	DECLARE 
	@BtypeID		VARCHAR(50)
	CREATE TABLE #tempbill
	(
		PtypeId				VARCHAR(50),
		KtypeId				VARCHAR(50),
		ItemID				INT,
		IsCombined			INT,
		GoodsNumber			VARCHAR(100),
		Qty					NUMERIC(24,10),
		NQty				NUMERIC(24,10)
	)
	SELECT @BtypeID = DealBTypeID FROM dbo.BillIndex WHERE BillNumberId = @nBillID
	/****** 更新借欠库存 begin******/
	IF @nBillType = 11 
	BEGIN
		INSERT INTO #tempbill( PtypeId ,KtypeId, ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
		SELECT PtypeId, KtypeId,ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
		FROM dbo.SaleBill WHERE BillNumberId = @nBillID 
		GROUP BY PtypeId, KtypeId,ItemID,IsCombined,GoodsNumber
	END
	ELSE 
	BEGIN
		INSERT INTO #tempbill( PtypeId ,KtypeId, ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
		SELECT PtypeId, KtypeId,ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
		FROM dbo.BuyBill WHERE BillNumberId = @nBillID 
		GROUP BY PtypeId,KtypeId, ItemID,IsCombined,GoodsNumber
	END
	SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber,
	SUM(BorrowQty) BorrowQty,SUM(NBorrowQty) NBorrowQty,SUM(LendQty) LendQty,SUM(NLendQty) NLendQty
	INTO #goodslendtemp 
	FROM (
		SELECT		
			t1.PtypeId, 	
			t1.KtypeId,
			@BtypeID AS bTypeID,
			t1.ItemID,
			t1.IsCombined,
			t1.GoodsNumber,
			CASE @nBillType WHEN 34 THEN  Qty   ELSE 0 END AS BorrowQty, --借进
			CASE @nBillType WHEN 34 THEN  NQty  ELSE 0 END AS NBorrowQty,
			CASE @nBillType WHEN 11 THEN  Qty   ELSE 0 END AS LendQty,
			CASE @nBillType WHEN 11 THEN  NQty  ELSE 0 END AS NLendQty
		FROM #tempbill t1 
		UNION ALL
		SELECT a.PtypeId,a.KtypeId,a.BtypeId,a.ItemID,a.Iscombined,a.GoodsNumber,a.BorrowQty,a.NBorrowQty,a.LendQty,a.NLendQty 
		FROM dbo.GoodsLend a JOIN #tempbill b
		ON (a.PtypeId = b.PtypeId 
			AND a.KtypeId = b.KtypeId
			AND a.ItemID = b.ItemID
			AND a.Iscombined = b.IsCombined
			AND a.GoodsNumber = b.GoodsNumber
			AND a.BtypeId = @BtypeID)
	)AS t2 GROUP BY PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber
	DELETE b FROM #goodslendtemp a JOIN GoodsLend b 
	ON b.PtypeId = a.PtypeId 
	AND b.KtypeId = a.KtypeId
	AND b.BtypeId = a.BtypeId
	AND b.ItemID = a.ItemID
	AND b.Iscombined = a.Iscombined
	AND b.GoodsNumber = a.GoodsNumber
	INSERT INTO dbo.GoodsLend( PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,LendQty,NLendQty,Qty,NQty)
	SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,LendQty,NLendQty, 
	(BorrowQty - LendQty) AS Qty, (NBorrowQty - NLendQty) AS NQty FROM #goodslendtemp
	DROP TABLE #goodslendtemp
	DELETE GoodsLend WHERE Qty = 0 AND NQty = 0

END
/******lend to buy sale******/

DECLARE
	@chvATypeID			VARCHAR(50),
	@intVipCardID		INT,
	@numTotal			 NUMERIC(24, 10)
	
--这里需要注意，有出错的返回值	

DECLARE @typeid  INT,
		@STypeID VARCHAR(100)

SELECT @STypeID=STypeID FROM dbo.BillIndex WHERE BillNumberId=@nBillID AND BillType=@nBillType
SELECT @typeid=nid FROM dbo.Ac_Items WHERE UserCode='2181'

IF EXISTS(
		SELECT BillNumberId 
		FROM Old_BillMulAccount
		WHERE BillNumberId=@nBillID AND BillType=@nBillType
)
BEGIN
	
	IF EXISTS(
			SELECT BillNumberId 
			FROM Old_BillMulAccount
			WHERE BillNumberId=@nBillID AND ATypeID=@typeid AND VipCardID>0 
	)
	BEGIN
		DECLARE CreateAType_CURSOR CURSOR FOR
		SELECT	ATypeID,Total,VipCardID
		FROM	Old_BillMulAccount
		WHERE	BillNumberId = @nBillID AND ATypeID=@typeid AND VipCardID>0

		OPEN CreateAType_CURSOR
		FETCH NEXT FROM CreateAType_CURSOR INTO	@chvATypeID,
												@numTotal,
												@intVipCardID
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- 循环写入 ListTable
			
			IF @nBillType=45
			BEGIN
				--储值金额是否够支付
				IF EXISTS(SELECT VipCardID FROM nVipCardSign WHERE VipCardID=@intVipCardID  AND cZyeMoney<@numTotal)
				BEGIN
					RETURN 704
				END
				--判断分支机构储值金额是否够支付
				IF @vipBillStoredByStypeId=1 AND EXISTS(SELECT * FROM nVipCardSignStype WHERE VipCardID=@intVipCardID AND StypeId=@STypeID AND cZyeMoney<@numTotal)
					RETURN 707						
				
				UPDATE	nVipCardSign
				SET		cZyeMoney = cZyeMoney - @numTotal
				WHERE	VipCardID = @intVipCardID
				
				UPDATE dbo.nVipCardSignStype 
				SET		cZyeMoney=cZyeMoney-@numTotal,
						lJxFczMoney=lJxFczMoney+@numTotal,
						bNxFczMoney=bNxFczMoney+@numTotal
				WHERE VipCardID=@intVipCardID AND StypeId=@STypeID
			END
			ELSE
			BEGIN
				UPDATE	nVipCardSign
				SET		cZyeMoney = cZyeMoney + @numTotal
				WHERE	VipCardID = @intVipCardID
				
				UPDATE dbo.nVipCardSignStype 
				SET		cZyeMoney=cZyeMoney+@numTotal,
						bNxFczMoney=bNxFczMoney-@numTotal,
						lJxFczMoney=lJxFczMoney-@numTotal
				WHERE VipCardID=@intVipCardID AND StypeId=@STypeID
			END

			FETCH NEXT FROM CreateAType_CURSOR INTO	@chvATypeID,
													@numTotal,
													@intVipCardID
		END
		CLOSE CreateAType_CURSOR
		DEALLOCATE CreateAType_CURSOR
	END
END

--其他处理(因为不生成红单，所以红单ID传0)

IF @nBillType IN (4,66,189)
BEGIN
	EXEC Gp_Deal_JS_OldBill @nBillID,@nBillType
	
	--删除
	DELETE CompleteTotal
	WHERE MoneyBillID=@nBillID AND BillType=@nBillType
	
	DELETE CompleteGoodTotal
	WHERE MoneyBillID=@nBillID AND BillType=@nBillType
	
	DELETE CompleteBrandarTotal
	WHERE MoneyBillID=@nBillID AND BillType=@nBillType
END



EXEC Gp_Deal_All @nBillID,@nBillType,0


IF @nBillType IN (11,34,400,402)
BEGIN
	-- 检测销售、采购单关联订单的完成状态
	EXEC @nRet = GP_AuditingCheckOrderState @nBillID,1
END



DECLARE
	@chvDealBTypeID		VARCHAR(50),
	@chvBTypeID			VARCHAR(50),
	@chvSTypeID			VARCHAR(50)
	

	
IF @nBillType IN (404,405)
BEGIN
	SELECT 
		@chvDealBTypeID=DealBTypeID,
		@chvBTypeID=BTypeID,
		@chvSTypeID=Stypeid
	FROM ReceiptBillIndex
	WHERE BillNumberID=@nBillID AND BillType=@nBillType
END
ELSE
BEGIN
	SELECT 
		@chvDealBTypeID=DealBTypeID,
		@chvBTypeID=BTypeID,
		@chvSTypeID=Stypeid
	FROM BillIndex
	WHERE BillNumberID=@nBillID AND BillType=@nBillType
END	



IF @nBillType NOT IN (71,72,87,88,404,405,450)
BEGIN
	--这里不校验负库存了
	EXEC GP_Auditing_DealQty_Reverse
			@nBillID,
			@nBillType,
			2,
			@chvDealBTypeID,
			@chvBTypeID,
			@chvSTypeID,
			@strPTypeIDOutPut	OUT,
			@nRet	OUT
		
	--PRINT('stock'	)
	--PRINT(@nRet)
	IF ISNULL(@nRet,0)<>0
	BEGIN
		RETURN -18
	END
END


IF @nBillType NOT IN (404,405)
BEGIN
	--把老单据的积分清掉JF
	UPDATE BillIndex
	SET JF=0
	WHERE BillNumberId=@nBillID AND JF<>0 
END




--运行回写
DECLARE
	@ModifyAuditBill	INT		--1表示修改过账后单据
	
SELECT
	@nRet=0,
	@ModifyAuditBill=1		
	
	

EXEC @nRet = Gp_Zc_AuditingInOut @nBillID,@nBillType, 0, @strPTypeIDOutPut output,@ModifyAuditBill

--PRINT('Gp_Zc_AuditingInOut')
--PRINT(@nRet)

IF @nRet<>0 
BEGIN
	IF @nAllowNegativeStock=0
	BEGIN
		SELECT @strPTypeIDOutPut='商品：'+FullName+'取不到成本价或成本价为负数或库存不足！'
		FROM Ptype
		WHERE TypeID=@strPTypeIDOutPut
	END
	ELSE
	BEGIN
		SELECT @strPTypeIDOutPut='商品：'+FullName+'取不到成本价或成本价为负数！'
		FROM Ptype
		WHERE TypeID=@strPTypeIDOutPut
	END
	
	RETURN @nRet
END

IF @nBillType NOT IN (205,206)
BEGIN
	EXEC @nRet = Gp_Zc_AuditingMx @nBillID,@nBillType, 0
END

--PRINT('Gp_Zc_AuditingMx')
--PRINT(@nRet)

--对于有异常的捕获，后续考虑

--然后删除过账痕迹
IF EXISTS(
	SELECT BillNumberID
	FROM InOutstocktable
	WHERE BillNumberId=@nBillID AND BillType=@nBillType
)
BEGIN
	DELETE	InOutstocktable
	WHERE	BillNumberID = @nBillID AND BillType=@nBillType
END

IF EXISTS(
	SELECT BillNumberID
	FROM wx_InOutStockTable
	WHERE BillNumberId=@nBillID AND BillType=@nBillType
)
BEGIN
	DELETE	wx_InOutStockTable
	WHERE	BillNumberID = @nBillID AND BillType=@nBillType
END


IF EXISTS(
	SELECT BillNumberID
	FROM ListTable
	WHERE BillNumberId=@nBillID AND BillType=@nBillType
)
BEGIN
	DELETE	ListTable
	WHERE	BillNumberID = @nBillID AND BillType=@nBillType
END

--销售出库单已经委托代销出库单红冲后需要重新锁定关联的订单数量
IF @nBillType IN (11,12,140,402)
BEGIN
	EXEC GP_DoRedWordLock @nBillID,@nBillType
END

--品牌应收修改，红冲历史数据
IF @nBillType IN (11,12,45,46,160,141,405,189,116,115,93,36,4,305,215,159)
BEGIN
	EXEC dbo.GP_AuditBrandarArAp_Reverse @nBillID,@nBillType	
END

RETURN @nRet


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nRet				INT
	
SELECT
	@nBillID=12,
	@nBillType=400
	

	
BEGIN TRAN	

EXEC	@nRet=Gp_OldBill_Reverse 
	@nBillID,
	@nBillType
	
select @nret	
	
select total,ntotal,* from listtable	where billnumberid=@nbillid and billtype=@nbilltype	

select * from btype_araptotal

select * from atype_total
	
ROLLBACK TRAN
	

*/





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

修改单据事后验证

作者：冯波



*/
CREATE   PROCEDURE Gp_OldBill_Verify 
(
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@nBillType			INT,
	@nRet				INT OUT,				--0表示验证成功，其他都表示出错
	@strMsg				VARCHAR(500) OUT		--返回的错误提示信息
)
--@encode$--
AS

SELECT
	@nRet=0,
	@strMsg=''


--需要加很多判断

--判断是否产生负库存
-------Costing method------------
DECLARE	@AVERAGE	smallint,
		@FIFO		smallint,
		@LIFO		smallint,
		@HAND		smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定法
---------------------

-- 查询是否允许负库存 (适用于移动加权平均成本核算)
DECLARE 
	@nAllowNegativeStock		INT,
	@nCostingMethod				INT,
	@strPTypeID					VARCHAR(50),
	@strFullName				VARCHAR(200),
	@strUserCode				VARCHAR(200),
	@chrIfATypeBalanceCheck		INT,
	@strSTypeID					VARCHAR(50),
	@strBTypeID					VARCHAR(50),
	@strATypeID					VARCHAR(50),
	@strVipCardCode				VARCHAR(200)


EXEC GP_GetSubValue 'AllowNegativeStock', '',@nAllowNegativeStock output

EXEC GP_GetSubValue 'costing', '',@nCostingMethod output

IF (@nCostingMethod<>@AVERAGE) OR (@nCostingMethod=@AVERAGE AND @nAllowNegativeStock=0)
BEGIN
	--不允许负库存
	
	IF EXISTS(
		SELECT a.PtypeId
		FROM GoodsStocks a
		INNER JOIN
		(
			SELECT PTypeID,KTypeID
			FROM #OldInfo
			UNION ALL
			SELECT PTypeID,KTypeID
			FROM #NewInfo
		) b
		ON a.PtypeId=b.PTypeID
		AND a.KtypeId=b.KTypeID
		GROUP BY a.PtypeId,a.KTypeID
		HAVING SUM(a.Qty)<0		
	)
	BEGIN		
		SELECT TOP 1 @strPTypeID=a.PtypeId
		FROM GoodsStocks a
		INNER JOIN
		(
			SELECT PTypeID,KTypeID
			FROM #OldInfo
			UNION ALL
			SELECT PTypeID,KTypeID
			FROM #NewInfo
		) b
		ON a.PtypeId=b.PTypeID
		AND a.KtypeId=b.KTypeID
		GROUP BY a.PtypeId,a.KTypeID
		HAVING SUM(a.Qty)<0	
		
		SELECT
			@strFullName=FullName,
			@strUserCode=Usercode
		FROM PType
		WHERE typeId=@strPTypeID
		
		SET @nRet=1
		SET @strMsg='该操作会导致单据中的商品['+@strUserCode+']'+@strFullName+' 产生负库存，不能修改该单据！'
		
		RETURN
	END
END


	
SELECT @strSTypeID=Stypeid,@strBTypeID=BTypeID
FROM BillIndex
WHERE BillNumberId=@nBillID	

--可能需要一张老的表来记录所影响的科目，这个待定

SELECT	TOP 1
		@chrIfATypeBalanceCheck = Value
FROM	UserConfig
WHERE	ConfigName = 'ATypeBalanceCheck'

IF @chrIfATypeBalanceCheck=1
BEGIN
	IF EXISTS(
		SELECT a.ATypeID
		FROM AType_Total a
		WHERE (a.ATypeID LIKE '0000100003%' OR a.ATypeID LIKE '0000100004%')
		AND EXISTS
		(
			SELECT b.ATypeID
			FROM ListTable b
			WHERE b.BillNumberId=@nBillID
			AND b.BillType=@nBillType
			AND b.ATypeID=a.AtypeId
			AND b.STypeID=a.STypeID
			UNION ALL
			SELECT b.ATypeID
			FROM Old_ListTable b
			WHERE b.BillNumberId=@nBillID
			AND b.BillType=@nBillType
			AND b.ATypeID=a.AtypeId
			AND b.STypeID=a.STypeID
		)
		AND a.Total<0	
	)
	BEGIN
		SET @nRet=1
		
		SELECT TOP 1
			@strUserCode=b.UserCode,
			@strFullName=b.FullName
		FROM AType_Total a
		INNER JOIN AType b
		ON a.ATypeID=b.typeId
		WHERE (a.ATypeID LIKE '0000100003%' OR a.ATypeID LIKE '0000100004%')
		AND EXISTS
		(
			SELECT b.ATypeID
			FROM ListTable b
			WHERE b.BillNumberId=@nBillID
			AND b.BillType=@nBillType
			AND b.ATypeID=a.AtypeId
			AND b.STypeID=a.STypeID
			UNION ALL
			SELECT b.ATypeID
			FROM Old_ListTable b
			WHERE b.BillNumberId=@nBillID
			AND b.BillType=@nBillType
			AND b.ATypeID=a.AtypeId
			AND b.STypeID=a.STypeID
		)
		AND a.Total<0
		
	
		SET @strMsg='该操作会导致['+@strUserCode+']['+@strFullName+']为负，不能修改此单据！'
		
		RETURN
	END
END


IF ISNULL(@strBTypeID,'')='' AND @nBillType<>159 RETURN   --无往来单位则不必校验


IF EXISTS(
		SELECT a.BTypeID
		FROM BType_ArApTotal a
		INNER JOIN
		(
			SELECT a.STypeID,a.BtypeId
			FROM
			(
				SELECT STypeID,AtypeId,BTypeID
				FROM ListTable
				WHERE BillNumberId=@nBillID
				AND BillType=@nBillType
				AND (AtypeId LIKE '0000100009%' OR AtypeId LIKE '0000200006%')
				UNION ALL
				SELECT STypeID,AtypeId,BTypeID
				FROM Old_ListTable
				WHERE BillNumberID=@nBillID
				AND BillType=@nBillType
				AND (AtypeId LIKE '0000100009%' OR AtypeId LIKE '0000200006%')
			) a
		) b
		ON a.STypeID=b.STypeID AND a.BtypeId=b.BtypeId
		WHERE a.YSTotal<0 OR a.YFTotal<0
)
BEGIN
	SET @nRet=1
	
	SELECT TOP 1
		@strUserCode=c.UserCode,
		@strFullName=c.FullName
	FROM BType_ArApTotal a
	INNER JOIN
	(
		SELECT a.STypeID,a.BtypeId
		FROM
		(
			SELECT STypeID,AtypeId,BTypeID
			FROM ListTable
			WHERE BillNumberId=@nBillID
			AND BillType=@nBillType
			AND (AtypeId LIKE '0000100009%' OR AtypeId LIKE '0000200006%')
			UNION ALL
			SELECT STypeID,AtypeId,BTypeID
			FROM Old_ListTable
			WHERE BillNumberID=@nBillID
			AND BillType=@nBillType
			AND (AtypeId LIKE '0000100009%' OR AtypeId LIKE '0000200006%')
		) a
	) b
	ON a.STypeID=b.STypeID AND a.BtypeId=b.BtypeId
	INNER JOIN BType c
	ON a.BTypeID=c.typeId
	WHERE a.YSTotal<0 OR a.YFTotal<0
	
	SET @strMsg='该操作会导致['+@strUserCode+']['+@strFullName+']的预收款或预付款为负，不能修改此单据！'
	
	RETURN
END



--如果有会员卡的，还需要判断会员卡余额是否为负数
IF EXISTS(
	SELECT VIPCardID
	FROM BillMulAccount
	WHERE BillNumberId=@nBillID AND VipCardID>0
	UNION ALL
	SELECT VIPCardID
	FROM Old_BillMulAccount
	WHERE BillNumberId=@nBillID AND VipCardID>0
	UNION ALL
	SELECT VIPCardID
	FROM Old_GatheringBill
	WHERE BillNumberId=@nBillID AND VipCardID>0
)
BEGIN
	IF EXISTS(
		SELECT a.VipCardID
		FROM nVipCardSign a
		WHERE a.cZyeMoney<0
		AND EXISTS
		(
			SELECT b.VIPCardID
			FROM BillMulAccount b
			WHERE b.BillNumberId=@nBillID AND b.VipCardID>0 AND b.VipCardID=a.VipCardID
			UNION ALL
			SELECT b.VIPCardID
			FROM Old_BillMulAccount b
			WHERE b.BillNumberId=@nBillID AND b.VipCardID>0 AND b.VipCardID=a.VipCardID
			UNION ALL
			SELECT VIPCardID
			FROM Old_GatheringBill b
			WHERE b.BillNumberId=@nBillID AND b.VipCardID>0 AND b.VipCardID=a.VipCardID
		)
	)
	BEGIN
		SET @nRet=1
		
		SELECT TOP 1
			@strVipCardCode =a.VipCardCode
		FROM nVipCardSign a
		WHERE a.cZyeMoney<0
		AND EXISTS
		(
			SELECT b.VIPCardID
			FROM BillMulAccount b
			WHERE b.BillNumberId=@nBillID AND b.VipCardID>0 AND b.VipCardID=a.VipCardID
			UNION ALL
			SELECT b.VIPCardID
			FROM Old_BillMulAccount b
			WHERE b.BillNumberId=@nBillID AND b.VipCardID>0 AND b.VipCardID=a.VipCardID
			UNION ALL
			SELECT VIPCardID
			FROM Old_GatheringBill b
			WHERE b.BillNumberId=@nBillID AND b.VipCardID>0 AND b.VipCardID=a.VipCardID
		)
	
		SET @strMsg='该操作会导致会员卡['+@strVipCardCode+']的余额为负，不能修改此单据！'
		
		RETURN
	END
END

	
--其他异常情况




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/****** Object:  StoredProcedure [dbo].[Gp_OM_AddToBackCart]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_AddToBackCart]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_AddToBackCart]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***********************************  
 *任我行通用事业部 过账组 
 
 *Title: 添加商品至购物车
 *CreatorName: 杨川
 *CreatedTime: 2014-07-10
 *ModifierName: 
 *ModifiedTime: 
***********************************/

create PROCEDURE [dbo].[Gp_OM_AddToBackCart] 
(	
	  @Id int,
	  @CommodityId varchar(50),
      @CommodityName nvarchar(100),
      @Quantity  NUMERIC(24, 10) ,
      @Price  NUMERIC(24, 10) ,
      @Discount  NUMERIC(24, 10) ,
      @DiscountPrice  NUMERIC(24, 10) ,
      @TotalMoney  NUMERIC(24, 10) ,
      @SaleMoney  NUMERIC(24, 10) ,
      @UnitID int,
      @UnitName nvarchar(50),
      --@InventoryInfoId int,
      @BtypeId varchar(50),
      @BtypeName nvarchar(100),
      @Comment nvarchar(200),
      @CreatorId int,
      @CreatorName nvarchar(200),
      @CreatedTime datetime,
      @ModifierId int,
      @ModifierName nvarchar(200),
      @ModifiedTime datetime,
      @OrderIndexId INT,
      @OrderId INT,
      @pid NUMERIC(10,0)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

IF NOT EXISTS(SELECT 1 FROM dbo.OM_OrderDetail WHERE billNumberID=@OrderIndexId AND id=@OrderId)
BEGIN
		RAISERROR('引用的订单不存在！',16,1);
END
IF(@id=0)
BEGIN
	SELECT @id=ID FROM OM_BackCart WHERE OrderIndexId=@OrderIndexId AND OrderId=@OrderId
				AND CreatorId=@CreatorId
	IF(@Id IS NULL)SET @Id=0
END
--购物车外添加商品至购物车
IF (@id=0)
BEGIN
	    --未购买
		INSERT INTO dbo.OM_BackCart
				VALUES	(
			  @CommodityId ,
			  @CommodityName ,
			  @Quantity ,
			  @Price ,
			  @Discount,
			  @DiscountPrice,
			  @TotalMoney ,
			  @SaleMoney,
			  @UnitID ,
			  @UnitName ,
			  0 ,
			  --@InventoryInfoId
			  @BtypeId ,
			  @BtypeName ,
			  @Comment ,
			  @CreatorId ,
			  @CreatorName ,
			  @CreatedTime ,
			  @ModifierId ,
			  @ModifierName ,
			  @ModifiedTime,
			  @OrderIndexId,
			  @OrderId,
			  @pid	)
		RETURN 0
END
ELSE
--购物车内添加商品至购物车
BEGIN
	IF((SELECT Quantity+@Quantity FROM dbo.OM_BackCart WHERE Id=@id)>(SELECT ReachQty FROM dbo.OM_OrderDetail WHERE ID=@OrderId))
	BEGIN
		--RAISERROR('您好！退货数量只能小于等于已收货数量,请确认后重新输入！',16,1);
		RETURN -1;
	END
	ELSE
	BEGIN
	UPDATE dbo.OM_BackCart
		SET	Quantity+=@Quantity,TotalMoney=@TotalMoney,SaleMoney=@SaleMoney
		WHERE id=@id
	END
	RETURN 0
END
GO





GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_AddToShoppingCart]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_AddToShoppingCart]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_AddToShoppingCart]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***********************************  
 *任我行通用事业部 过账组 
 
 *Title: 添加商品至购物车
 *CreatorName: 杨川
 *CreatedTime: 2014-07-10
 *ModifierName: 
 *ModifiedTime: 
***********************************/

create PROCEDURE [dbo].[Gp_OM_AddToShoppingCart] 
(	
	  @Id int,
	  @CommodityId varchar(50),
      @CommodityName nvarchar(100),
      @Quantity  NUMERIC(24, 10) ,
      @Price  NUMERIC(24, 10) ,
      @Discount  NUMERIC(24, 10) ,
      @DiscountPrice  NUMERIC(24, 10) ,
      @TotalMoney  NUMERIC(24, 10) ,
      @SaleMoney  NUMERIC(24, 10) ,
      @UnitID int,
      @UnitName nvarchar(50),
      --@InventoryInfoId int,
      @BtypeId varchar(50),
      @BtypeName nvarchar(100),
      @Comment nvarchar(200),
      @CreatorId int,
      @CreatorName nvarchar(200),
      @CreatedTime datetime,
      @ModifierId int,
      @ModifierName nvarchar(200),
      @ModifiedTime datetime,
      @IsShopping BIT,
      @isGift BIT,
      @pid NUMERIC(10,0),
      @bid INT 
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--购物车外添加商品至购物车
IF (@id=0)
BEGIN
    --是否已经购买该商品
	IF EXISTS(SELECT id FROM dbo.OM_ShoppingCart WHERE CommodityId=@CommodityId AND CreatorId=@CreatorId)
	BEGIN
	    --已购买
		UPDATE dbo.OM_ShoppingCart SET Quantity +=@Quantity,TotalMoney=@TotalMoney,SaleMoney=@SaleMoney
		WHERE CommodityId=@CommodityId AND CreatorId=@CreatorId 
	END
	ELSE
	   --未购买
	   INSERT INTO  dbo.OM_ShoppingCart
	           ( CommodityId ,
	             CommodityName ,
	             Quantity ,
	             Price ,
	             Discount ,
	             DiscountPrice ,
	             TotalMoney ,
	             SaleMoney ,
	             UnitID ,
	             UnitName ,
	             InventoryInfoId ,
	             BtypeId ,
	             BtypeName ,
	             Comment ,
	             CreatorId ,
	             CreatorName ,
	             CreatedTime ,
	             ModifierId ,
	             ModifierName ,
	             ModifiedTime ,
	             IsShopping ,
	             pid ,
	             bid ,
	             IsGift
	           )
		VALUES	(
			  @CommodityId ,
			  @CommodityName ,
			  @Quantity ,
			  @Price ,
			  @Discount,
			  @DiscountPrice,
			  @TotalMoney ,
			  @SaleMoney,
			  @UnitID ,
			  @UnitName ,
			  0 ,
			  @BtypeId ,
			  @BtypeName ,
			  @Comment ,
			  @CreatorId ,
			  @CreatorName ,
			  @CreatedTime ,
			  @ModifierId ,
			  @ModifierName ,
			  @ModifiedTime,
	  @IsShopping,@pid,@bid,@isGift   )
END
ELSE
--购物车内添加商品至购物车
BEGIN
	UPDATE dbo.OM_ShoppingCart
	SET	Quantity+=@Quantity,TotalMoney=@TotalMoney,SaleMoney=@SaleMoney
	WHERE id=@id
END
GO






GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_BackBillCodeSeedDeal]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_BackBillCodeSeedDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_BackBillCodeSeedDeal]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：韩林
	日期：2013-10-27
	描述：保存OM单据种子
-------------------------------------------*/
CREATE PROCEDURE [dbo].[Gp_OM_BackBillCodeSeedDeal]
(
	@billdate VARCHAR(8)
)
--@encode$--
AS 
SET NOCOUNT ON
	IF NOT EXISTS(SELECT 1 FROM OM_BackBillCodeSeed WHERE Flowdate=@billdate)
	BEGIN
		INSERT INTO OM_BackBillCodeSeed VALUES(@billdate,2)
		RETURN 1
	END
	ELSE
	BEGIN
		DECLARE @seed INT=0
		SELECT @seed=seed FROM  OM_BackBillCodeSeed WHERE flowdate=@billdate
		UPDATE  OM_BackBillCodeSeed 
		SET Seed+=1
		WHERE FlowDate=@billdate
		RETURN @seed
	END
GO





GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_BillCodeSeedDeal]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_BillCodeSeedDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_BillCodeSeedDeal]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：韩林
	日期：2013-10-27
	描述：保存OM单据种子
-------------------------------------------*/
CREATE PROCEDURE [dbo].[Gp_OM_BillCodeSeedDeal]
(
	@billdate VARCHAR(8)
)
--@encode$--
AS 
SET NOCOUNT ON
	IF NOT EXISTS(SELECT 1 FROM OM_BillCodeSeed WHERE Flowdate=@billdate)
	BEGIN
		INSERT INTO OM_BillCodeSeed VALUES(@billdate,2)
		RETURN 1
	END
	ELSE
	BEGIN
		DECLARE @seed INT=0
		SELECT @seed=seed FROM  OM_BillCodeSeed WHERE flowdate=@billdate
		UPDATE  OM_BillCodeSeed 
		SET Seed+=1
		WHERE FlowDate=@billdate
		RETURN @seed
	END
GO





GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_GenerationOrderDetail]    Script Date: 08/08/2014 11:16:11 ******/

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_GenerationOrderDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_GenerationOrderDetail]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：韩林
	日期：2013-10-25
	描述：组装OM明细为出库单明细
	
*/

create PROCEDURE [dbo].[Gp_OM_GenerationOrderDetail] 
(
	@idlist VARCHAR(max)
)

--@encode$--
AS
SET NOCOUNT ON

DECLARE @tax DECIMAL=0,@gridtype INT =0
SELECT @tax=Value FROM dbo.Userconfig WHERE ConfigName ='AllTaxRate'
SELECT @gridtype = VALUE FROM dbo.Userconfig WHERE ConfigName='gridtype'
IF @gridtype IN (2,3)
	SET @tax=0
SELECT	isgift=CAST(a.isgift AS INT ),
		Qty=ROUND((a.Qty-a.ReachQty)*ue.Rate,4),
		BigQty =
				CASE WHEN b.UnitRate1 = 0 THEN
					ROUND((a.Qty-a.ReachQty)*ue.Rate,4)
				ELSE ROUND((a.Qty-a.ReachQty)/b.UnitRate1*ue.Rate ,4) END,
		Price = ROUND(a.discountprice/(ue.Rate*(CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)),4),
		DiscountPrice = ROUND(a.DiscountPrice/(ue.Rate*(1+@tax/100)),4),
		TaxPrice = ROUND(a.taxprice/ue.Rate ,4),
		ROUND((a.Qty-a.ReachQty)*a.taxprice,2) AS taxtotal,
		a.tax AS tax,
		Discount=CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END,
		ROUND(ROUND((a.Qty-a.ReachQty)*a.DiscountPrice,2)/(1+@tax/100) ,2) AS total,
		curmsaleprice = ROUND(a.DiscountPrice/((CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)) ,4),
		mqty =a.Qty-a.ReachQty,
		munitrate=ue.Rate,
		nsaleprice=ROUND(a.discountprice/(ue.Rate*(CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)) ,4),
		CASE WHEN ISNULL(b.AssistantUnitId,0) = 0 THEN NULL
				ELSE ROUND((a.Qty-a.ReachQty)*ue.Rate / we.rate ,4)	END as nqty,
		curmdiscountprice=ROUND(a.DiscountPrice/(1+@tax/100) ,4),
		curmtaxprice = a.taxprice,
		ntaxmoney = ROUND((a.Qty-a.ReachQty)*a.taxprice,2)-ROUND(ROUND((a.Qty-a.ReachQty)*a.DiscountPrice,2)/(1+@tax/100) ,2),
		ntaxtotal =ROUND((a.Qty-a.ReachQty)*a.taxprice,2),
		taxmoney= ROUND((a.Qty-a.ReachQty)*a.DiscountPrice,2)-ROUND(ROUND((a.Qty-a.ReachQty)*a.DiscountPrice,2)/(1+@tax/100) ,2),
		MUnitID =a.UnitID,
		nunitid= b.AssistantUnitId,
		unitid = b.baseUnitId,
		V.fullname AS unit,
		U.FullName AS munit,
		W.FullName AS nunit,
		nsaletotal=ROUND(ROUND((a.Qty-a.ReachQty)*a.DiscountPrice,2)/((CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)),2),
		ntotal =ROUND(ROUND((a.Qty-a.ReachQty)*a.DiscountPrice,2)/(1+@tax/100),2),				
	    CASE WHEN ISNULL(b.AssistantUnitId,0) = 0 THEN NULL
				ELSE we.rate END AS UnitRate,
		CargoID=0,
		cargofullname='',
		ndiscountprice=ROUND(a.DiscountPrice/(ue.Rate*(1+@tax/100)) ,4),
		ntaxprice=ROUND(a.taxprice/ue.Rate ,4),
		msaleprice=ROUND(a.DiscountPrice/((CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)) ,4),
		mdiscountprice=ROUND(a.DiscountPrice/(1+@tax/100) ,4),
		mtaxprice=a.DiscountPrice,
		InputCostPrice =null,
					-1 AS OldID,
					-1 as BillNumberID,
					-1 as OldBillId,
		(select EntryCode from PType_Units_Ext where PtypeID=b.typeid and UnitsId=a.UnitID) AS munitcode,
		completeqty=0,		
		ninvoicemoney=0,
		invoicemoney=0,
		invoiceqty=0,
		OrderID=-1,
		'' as entrycode,
		sharefee=0,
		GoodsCostPrice=0,
		a.Comment AS BillComment,
		--'' AS BillComment,
		IsUnit2 = 0,
		'' AS serial,
		b.typeid,
		b.UserCode,
		b.FullName,
		b.Unit1,
		b.Unit2,
		0 as UnitRate1,				
		b.Standard,
		b.Type,
		b.Area,
		b.SerialCount,
		b.ValidDays,
		b.IfSerial,
		b.usefullifeday,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				    (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			        ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		b.unitstype,
		saletotal=ROUND(ROUND((a.Qty-a.ReachQty)*a.DiscountPrice,2)/((CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)),2),
		CAST(b.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		a.id AS OMbillID,
		'OM定价' AS pricesource,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname1,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname2,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname3,
		(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate1,
		(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate2,
		(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate3
FROM OM_OrderDetail a
INNER JOIN ptype b ON b.Typeid=a.ptypeid
INNER JOIN  dbo.PType_Units U ON U.UnitsId=a.UnitID 
INNER JOIN dbo.PType_Units_Ext ue ON ue.UnitsId=a.UnitID AND ue.PtypeID=b.typeid
LEFT  JOIN  dbo.PType_Units V ON V.UnitsId=b.baseUnitId
LEFT  JOIN  dbo.PType_Units W ON W.UnitsId=b.AssistantUnitId
LEFT JOIN dbo.PType_Units_Ext we ON we.PtypeID=b.typeId AND we.UnitsId=b.AssistantUnitId		
WHERE a.id IN (SELECT * FROM dbo.f_split(@idlist,','))

Go






/****** Object:  StoredProcedure [dbo].[Gp_OM_GenerationOrderDetail]    Script Date: 08/08/2014 11:16:11 ******/

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].Gp_OM_GenerationSaleBackDetail') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].Gp_OM_GenerationSaleBackDetail

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：王涛
	日期：2014年11月11日 09:46:01
	描述：组装OM退货明细为退货出库单明细
	
*/

create PROCEDURE [dbo].Gp_OM_GenerationSaleBackDetail 
(
	@detail TbType_OMBackDetail READONLY
)

--@encode$--
AS
SET NOCOUNT ON

DECLARE @tax DECIMAL=0,@gridtype INT =0
SELECT @tax=Value FROM dbo.Userconfig WHERE ConfigName ='AllTaxRate'
SELECT @gridtype = VALUE FROM dbo.Userconfig WHERE ConfigName='gridtype'
IF @gridtype IN (2,3)
	SET @tax=0
SELECT	Qty=ROUND((d.qty)*ue.Rate,4),
		BigQty =
				CASE WHEN b.UnitRate1 = 0 THEN
					ROUND((d.qty)*ue.Rate,4)
				ELSE ROUND((d.qty)/b.UnitRate1*ue.Rate ,4) END,
		Price = ROUND(a.discountprice/(ue.Rate*(CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)),4),
		DiscountPrice = ROUND(a.DiscountPrice/(ue.Rate*(1+@tax/100)),4),
		TaxPrice = ROUND(a.DiscountPrice/ue.Rate ,4),
		ROUND((d.qty)*a.DiscountPrice,2) AS taxtotal,
		@tax AS tax,
		Discount=CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END,
		ROUND(ROUND((d.qty)*a.DiscountPrice,2)/(1+@tax/100) ,2) AS total,
		curmsaleprice = ROUND(a.DiscountPrice/((CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)) ,4),
		mqty =d.qty,
		munitrate=ue.Rate,
		nsaleprice=ROUND(a.discountprice/(ue.Rate*(CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)) ,4),
		CASE WHEN ISNULL(b.AssistantUnitId,0) = 0 THEN NULL
				ELSE ROUND((d.qty)*ue.Rate / we.rate ,4)	END as nqty,
		curmdiscountprice=ROUND(a.DiscountPrice/(1+@tax/100) ,4),
		curmtaxprice = a.DiscountPrice,
		ntaxmoney = ROUND((d.qty)*a.DiscountPrice,2)-ROUND(ROUND((d.qty)*a.DiscountPrice,2)/(1+@tax/100) ,2),
		ntaxtotal =ROUND((d.qty)*a.DiscountPrice,2),
		taxmoney= ROUND((d.qty)*a.DiscountPrice,2)-ROUND(ROUND((d.qty)*a.DiscountPrice,2)/(1+@tax/100) ,2),
		MUnitID =a.UnitID,
		nunitid= b.AssistantUnitId,
		unitid = b.baseUnitId,
		V.fullname AS unit,
		U.FullName AS munit,
		W.FullName AS nunit,
		nsaletotal=ROUND(ROUND((d.qty)*a.DiscountPrice,2)/((CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)),2),
		ntotal =ROUND(ROUND((d.qty)*a.DiscountPrice,2)/(1+@tax/100),2),				
	    CASE WHEN ISNULL(b.AssistantUnitId,0) = 0 THEN NULL
				ELSE we.rate END AS UnitRate,
		CargoID=0,
		cargofullname='',
		ndiscountprice=ROUND(a.DiscountPrice/(ue.Rate*(1+@tax/100)) ,4),
		ntaxprice=ROUND(a.DiscountPrice/ue.Rate ,4),
		msaleprice=ROUND(a.DiscountPrice/((CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)) ,4),
		mdiscountprice=ROUND(a.DiscountPrice/(1+@tax/100) ,4),
		mtaxprice=a.DiscountPrice,
		InputCostPrice =null,
					-1 AS OldID,
					-1 as BillNumberID,
					-1 as OldBillId,
		(select EntryCode from PType_Units_Ext where PtypeID=b.typeid and UnitsId=a.UnitID) AS munitcode,
		completeqty=0,		
		ninvoicemoney=0,
		invoicemoney=0,
		invoiceqty=0,
		OrderID=-1,
		'' as entrycode,
		sharefee=0,
		GoodsCostPrice=0,
		a.Comment AS BillComment,
		--'' AS BillComment,
		IsUnit2 = 0,
		'' AS serial,
		b.typeid,
		b.UserCode,
		b.FullName,
		b.Unit1,
		b.Unit2,
		0 as UnitRate1,				
		b.Standard,
		b.Type,
		b.Area,
		b.SerialCount,
		b.ValidDays,
		b.IfSerial,
		b.usefullifeday,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				    (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			        ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		b.unitstype,
		saletotal=ROUND(ROUND((d.qty)*a.DiscountPrice,2)/((CASE WHEN @gridtype IN (2,4) THEN a.discount ELSE 1 END)*(1+@tax/100)),2),
		CAST(b.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		a.id AS OMbillID,
		'OM定价' AS pricesource,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname1,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname2,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname3,
		(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate1,
		(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate2,
		(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate3
FROM dbo.OM_BackOrderDetail a
INNER JOIN ptype b ON b.Typeid=a.ptypeid
INNER JOIN  dbo.PType_Units U ON U.UnitsId=a.UnitID 
INNER JOIN dbo.PType_Units_Ext ue ON ue.UnitsId=a.UnitID AND ue.PtypeID=b.typeid
INNER JOIN @detail d ON d.id=a.ID
LEFT  JOIN  dbo.PType_Units V ON V.UnitsId=b.baseUnitId
LEFT  JOIN  dbo.PType_Units W ON W.UnitsId=b.AssistantUnitId
LEFT JOIN dbo.PType_Units_Ext we ON we.PtypeID=b.typeId AND we.UnitsId=b.AssistantUnitId		


GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].Gp_OM_GetBackBill') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].Gp_OM_GetBackBill
GO



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/***********************************  

 *Title: 单据列表查询
 *CreatorName: 王涛
 *CreatedTime: 2014年11月10日 17:26:28
 *ModifierName: 
 *ModifiedTime: 
***********************************/

create PROCEDURE [dbo].Gp_OM_GetBackBill 
(
	@operatorid			VARCHAR(100),	--操作员ID
	@startdate			VARCHAR(MAX),	--开始日期
	@enddate			VARCHAR(MAX),	--截止日期
	@billcode			VARCHAR(MAX),	--单据编号
	@btypeId			VARCHAR(MAX),	--往来单位id
	@ptypeId			VARCHAR(MAX),	--商品id
	@billstatus			INT				--单据状态
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,
        @MAtypeid VARCHAR(50), 
        @MBtypeid VARCHAR(50), 
        @MBtypeid2 VARCHAR(50), 
        @MEtypeid VARCHAR(50),
        @MKtypeid VARCHAR(50), 
        @MPtypeid VARCHAR(50), 
        @MExpense VARCHAR(50), 
        @MIncome VARCHAR(50),
        @MCapital VARCHAR(50),
        @MDtypeid VARCHAR(50),
        @MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)	


--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID)	

DECLARE @SQL VARCHAR(MAX)=''
SET @SQL='
	;with result as 
	(
	SELECT	b.ID,
			i.CreatedTime,
			i.SerialNo,
			b.ptypeid,
			i.btypeid,
			isnull(fu.salemunitrate,0)*qty as qty,			   
			isnull(fu.unit,'''') as  unitname,
			case when isnull(fu.salemunitrate,0)=0 then 0 else  b.DiscountPrice/isnull(fu.salemunitrate,0) end DiscountPrice,
			
			isnull(fu.saleunitname,'''') as saleunitname,
			isnull(fu.saleunitid,0) as saleunitid,

			qty as saleqty,
			b.DiscountPrice as saleprice,
			''1 ''+ISNULL(fu.saleunitname,'''') +'' = ''+CAST(ISNULL(fu.salemunitrate,''0'') AS VARCHAR(20))+'' ''+ISNULL(fu.Unit,'''') AS conversionrelationship,
			
			b.SaleTotal,
			--case when b.qty-isnull(b.reachqty,0) >0 and isnull(b.reachqty,0)>0 then 3 else  b.Status end status,
			b.Status,
			b.ReachQty, --已开单数据量
			b.confirmqty,
			case when b.qty-isnull(b.reachqty,0)<0 then 0 else    b.qty-isnull(b.reachqty,0) end  unbackqty, --未开单数量
			b.stopqty,  --中止数量
			b.comment
	FROM dbo.OM_BackOrderDetail b
	INNER JOIN dbo.OM_BackOrder i ON b.billNumberID=i.id
	INNER JOIN #GetManBTypeId mb ON i.btypeid=mb.TypeId
	INNER JOIN #GetManPTypeId mp ON b.ptypeid=mp.TypeId
	Left Join dbo.F_GetPtypeUnitInfo() fu  on fu.typeid=b.ptypeid
	WHERE   i.CreatedTime>='''+@startdate+'''
			AND CONVERT (DATE,i.CreatedTime,120)<='''+@enddate+'''
			AND i.SerialNo like ''%'+@billcode+'%'''

SET @SQL +=	'
	
	)
	select * 
	from  result	
	'
	IF @billstatus<>9
	SET @sql +='
			where STATUS='+CAST(@billstatus AS VARCHAR)
SET @SQL +=' ORDER BY SerialNo,CreatedTime,id  '			

PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManBTypeId,#GetManPTypeId

GO








/****** Object:  StoredProcedure [dbo].[Gp_OM_GetBackOrderCount]    Script Date: 11/11/2014 14:37:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_GetBackOrderCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_GetBackOrderCount]
GO



/****** Object:  StoredProcedure [dbo].[Gp_OM_GetBackOrderCount]    Script Date: 11/11/2014 14:37:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	
*/
--exec gp_SelectOMOrderList 10,1,1,'','','',0


CREATE  PROCEDURE [dbo].[Gp_OM_GetBackOrderCount]
(
 
 @OperatorID varchar(50),
 @time varchar(50)='0',
 @state varchar(50)='6',
 @typeid varchar(50)=''
 

)




--@encode$--
AS
SET NOCOUNT ON
	
DECLARE @wheretypeid varchar(max)
SET @wheretypeid=''
DECLARE @wheretime varchar(max)
SET @wheretime=''
DECLARE @wherestate varchar(max)
SET @wherestate=''

	if(@time = '0')--全部时间
	Set @wheretime=''
	if(@time = '1')--最近一个月
	Set @wheretime=' and omOrder.CreatedTime between dateadd(mm,-1,getDate()) and getDate()'
	if(@time = '2')--一个月前
	Set @wheretime=' and datediff(month,omOrder.CreatedTime,getdate())=1'
	if(@time = '3')--今天
	Set @wheretime=' and DateDiff(dd,omOrder.CreatedTime,getdate())=0 '
	
	if(@state = '9')--全部状态
	  SET @wherestate=''
	if(@state = '0')
	  SET @wherestate=' and obill.STATUS=0'
    if(@state = '1')
	  SET @wherestate=' and obill.STATUS=1'
	if(@state = '2')
	  SET @wherestate=' and obill.STATUS=2'



			
DECLARE @sql varchar(max)
	set @sql='select * from ( 
		SELECT cast(obill.billNumberID as int) as billNumberID
			  ,obill.ptypeid as ptypeid,
			  p.fullname  as Fullname,
			  ROUND(obill.qty,4) AS qty
			 ,ROUND(obill.price,4) AS price
			  ,obill.total as total
			  ,obill.comment as comment
			  ,cast(obill.ID as int) as ID
			  ,obill.Discount as Discount
			  ,obill.DiscountPrice as DiscountPrice
			  ,obill.SaleTotal as SaleTotal
			  ,obill.UnitID as UnitID
			  ,obill.ItemID as ItemID
			  ,obill.IsCombined as IsCombined
			  ,obill.ReachQty as ReachQty
			  ,obill.ConfirmQty as ConfirmQty
			  ,obill.StopQty as StopQty,
			  (obill.Qty-obill.Reachqty-obill.StopQty) as NoReachQty,
			  (select isnull(sum(ReachQty-ConfirmQty),0) from OM_Shipments where ombillid=obill.ID and [STATUS]=1) as NoConfirmQty ,
			  omOrder.SerialNo as BillCode,
			  Row_Number() OVER (ORDER BY obill.id) as rownumberid 
			  ,cast(obill.[STATUS] as varchar(50)) as [STATUS],
			  cast(omOrder.Status as varchar(50)) as BillStatus,
			  omOrder.TotalMoney as TotalMoney,
			  cast(omOrder.CreatedTime as varchar(50)) as BillDate,
			  pu.fullname as uname
			FROM OM_BackOrderDetail obill
			INNER JOIN OM_BackOrder omOrder ON  omOrder.id=obill.billNumberID
			INNER JOIN ptype p ON p.typeid=obill.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=obill.UnitID
			where omOrder.CreatorId='''+@OperatorID+'''
			'+@wherestate+'
			'+@wheretime+'
			
	) as b 
	
	where 1=1 
	
	
	order by b.id'
	
	print (@sql)
	exec(@sql)


GO







/****** Object:  StoredProcedure [dbo].[Gp_OM_GetBackOrders]    Script Date: 11/11/2014 14:34:45 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_GetBackOrders]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_GetBackOrders]
GO



/****** Object:  StoredProcedure [dbo].[Gp_OM_GetBackOrders]    Script Date: 11/11/2014 14:34:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
	
*/
--exec gp_SelectOMOrderList 10,1,1,'3','','',0


create PROCEDURE [dbo].[Gp_OM_GetBackOrders]
(
 @PageSize int,
 @PageNum  int,
 @CreatorId varchar(50),
 @time varchar(50)='0',
 @state varchar(50)='9',
 @keyword  varchar(50), 
 @TotalPage  int output
)


--@encode$--
AS
SET NOCOUNT ON
	
DECLARE @wheretypeid varchar(max)
SET @wheretypeid=''
DECLARE @wheretime varchar(max)
SET @wheretime=''
DECLARE @wherestate varchar(max)
SET @wherestate=''

	if(@time = '0')--全部时间
	Set @wheretime=''
	if(@time = '1')--最近一个月
	Set @wheretime=' and omOrder.CreatedTime between dateadd(mm,-1,getDate()) and getDate()'
	if(@time = '2')--一个月前
	Set @wheretime=' and datediff(month,omOrder.CreatedTime,getdate())=1'
	if(@time = '3')--今天
	Set @wheretime=' and DateDiff(dd,omOrder.CreatedTime,getdate())=0 '
	
	if(@state = '9')--全部状态
	  SET @wherestate=''
	if(@state = '0')
	  SET @wherestate=' and omOrderDetail.STATUS=0'
    if(@state = '1')
	  SET @wherestate=' and omOrderDetail.STATUS=1'
	if(@state = '2')
	  SET @wherestate=' and omOrderDetail.STATUS=2'
   if(@state = '3')
	  SET @wherestate=' and omOrderDetail.STATUS=3'

CREATE TABLE #MyTempTable (total INT PRIMARY KEY)
  
    
DECLARE @sqltotal varchar(max)='';
			
			set @sqltotal='insert into #MyTempTable select a.total  from ( 
	        select  COUNT(1) as total from OM_BackOrderDetail omOrderDetail 
	        INNER JOIN OM_BackOrder omOrder ON  omOrder.id=omOrderDetail.billNumberID
	        INNER JOIN ptype p ON p.typeid=omOrderDetail.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=omOrderDetail.UnitID
			where omOrder.CreatorId='''+@CreatorId+'''
				'+@wheretime+'
	            '+@wherestate+'
	            ) a
			'
		 
			if(@keyword<>'')
			begin
			set @sqltotal='insert into #MyTempTable select a.total  from ( 
	        select  COUNT(1) as total from OM_BackOrderDetail omOrderDetail 
	        INNER JOIN OM_BackOrder omOrder ON  omOrder.id=omOrderDetail.billNumberID
	        INNER JOIN ptype p ON p.typeid=omOrderDetail.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=omOrderDetail.UnitID
			where omOrder.CreatorId='''+@CreatorId+'''
				'+@wheretime+'
	            '+@wherestate+'
	            
	             and (p.fullname  like ''%'+@keyword+'%'' or p.usercode like ''%'+@keyword+'%''
	             or omOrder.SerialNo like ''%'+@keyword+'%'') ) a
			'
			end
			exec(@sqltotal)
		 	select @TotalPage=sum(total) from #MyTempTable
		 	


	

			
			
DECLARE @sql varchar(max)
	set @sql=
		'SELECT * FROM(
			SELECT cast(omOrderDetail.billNumberID as int) as billNumberID
			  ,omOrderDetail.ptypeid as ptypeid,
			  p.usercode as UserCode,
			  p.fullname  as Fullname,
			  ROUND(omOrderDetail.qty,4) AS qty
			 ,ROUND(omOrderDetail.price,4) AS price
			  ,omOrderDetail.total as total
			  ,omOrderDetail.comment as comment
			  ,cast(omOrderDetail.ID as int) as ID
			  ,omOrderDetail.Discount as Discount
			  ,omOrderDetail.DiscountPrice as DiscountPrice
			  ,omOrderDetail.SaleTotal as SaleTotal
			  ,omOrderDetail.UnitID as UnitID
			  ,omOrderDetail.ItemID as ItemID
			  ,omOrderDetail.IsCombined as IsCombined
			  ,omOrderDetail.ReachQty as ReachQty
			  ,omOrderDetail.ConfirmQty as ConfirmQty
			  ,omOrderDetail.StopQty as StopQty,
			  (omOrderDetail.Qty-omOrderDetail.Reachqty-omOrderDetail.StopQty) as NoReachQty,
			  (select isnull(sum(ReachQty-ConfirmQty),0) from OM_Shipments where OM_Shipments.id=omOrderDetail.ID and [STATUS]=1) as NoConfirmQty ,
			  omOrder.SerialNo as BillCode,
			  Row_Number() OVER (ORDER BY omOrderDetail.id) as rownumberid 
			  ,cast(omOrderDetail.[STATUS] as varchar(50)) as [STATUS],
			  cast(omOrder.Status as varchar(50)) as BillStatus,
			  omOrder.TotalMoney as TotalMoney,
			  cast(omOrder.CreatedTime as varchar(50)) as BillDate,
			  pu.fullname as uname,
			  omOrder.CreatedTime,
			  ROW_NUMBER() OVER(Order by  omOrderDetail.ID) as RowID
			FROM OM_BackOrderDetail omOrderDetail
			INNER JOIN OM_BackOrder omOrder ON  omOrder.id=omOrderDetail.billNumberID
			INNER JOIN ptype p ON p.typeid=omOrderDetail.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=omOrderDetail.UnitID
			where omOrder.CreatorId='''+@CreatorId+'''
			'+@wherestate+'
			'+@wheretime+'
			 )T WHERE RowID>='+CAST((@PageSize*(@PageNum-1)+1) AS varchar)+' AND RowID<='+CAST((@PageSize*@PageNum)AS varchar)+'			 
			 order by ID
			 '

			if(@keyword<>'')
			set @sql=

		'SELECT * FROM(
			SELECT  cast(omOrderDetail.billNumberID as int) as billNumberID
			  ,omOrderDetail.ptypeid as ptypeid,
			  p.usercode as UserCode,
			  p.fullname  as Fullname,
			  ROUND(omOrderDetail.qty,4) AS qty
			 ,ROUND(omOrderDetail.price,4) AS price
			  ,omOrderDetail.total as total
			  ,omOrderDetail.comment as comment
			  ,cast(omOrderDetail.ID as int) as ID
			  ,omOrderDetail.Discount as Discount
			  ,omOrderDetail.DiscountPrice as DiscountPrice
			  ,omOrderDetail.SaleTotal as SaleTotal
			  ,omOrderDetail.UnitID as UnitID
			  ,omOrderDetail.ItemID as ItemID
			  ,omOrderDetail.IsCombined as IsCombined
			  ,omOrderDetail.ReachQty as ReachQty
			  ,omOrderDetail.ConfirmQty as ConfirmQty
			  ,omOrderDetail.StopQty as StopQty,
			  (omOrderDetail.Qty-omOrderDetail.Reachqty-omOrderDetail.StopQty) as NoReachQty,
			  (select isnull(sum(ReachQty-ConfirmQty),0) from OM_Shipments where OM_Shipments.id=omOrderDetail.ID and [STATUS]=1) as NoConfirmQty ,
			  omOrder.SerialNo as BillCode,
			  Row_Number() OVER (ORDER BY omOrderDetail.id) as rownumberid 
			  ,cast(omOrderDetail.[STATUS] as varchar(50)) as [STATUS],
			  cast(omOrder.Status as varchar(50)) as BillStatus,
			  omOrder.TotalMoney as TotalMoney,
			  cast(omOrder.CreatedTime as varchar(50)) as BillDate,
			  pu.fullname as uname,
			  omOrder.CreatedTime,
			  ROW_NUMBER() OVER(Order by  omOrderDetail.ID) as RowID 
			FROM OM_BackOrderDetail omOrderDetail
			INNER JOIN OM_BackOrder omOrder ON  omOrder.id=omOrderDetail.billNumberID
			INNER JOIN ptype p ON p.typeid=omOrderDetail.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=omOrderDetail.UnitID
			where omOrder.CreatorId='''+@CreatorId+'''
			'+@wherestate+'
			'+@wheretime+' and (p.fullname  like ''%'+@keyword+'%'' or p.usercode like ''%'+@keyword+'%''
			or omOrder.SerialNo like ''%'+@keyword+'%''))T WHERE RowID>='+CAST((@PageSize*(@PageNum-1)+1) AS varchar)+' AND RowID<='+CAST((@PageSize*@PageNum)AS varchar)+'		 
			 order by id
			 '
	print(@sql)		

	exec(@sql)


 drop table #MyTempTable;


GO






/****** Object:  StoredProcedure [dbo].[Gp_OM_GetBill]    Script Date: 08/22/2014 15:09:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_GetBill]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_GetBill]
GO


/****** Object:  StoredProcedure [dbo].[Gp_OM_GetBill]    Script Date: 08/22/2014 15:09:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/***********************************  
 *任我行通用事业部 过账组 
 
 *Title: 单据列表查询
 *CreatorName: 杨川
 *CreatedTime: 2014-07-28
 *ModifierName: 
 *ModifiedTime: 
***********************************/

create PROCEDURE [dbo].[Gp_OM_GetBill] 
(
	@operatorid			VARCHAR(100),	--操作员ID
	@startdate			VARCHAR(MAX),	--开始日期
	@enddate			VARCHAR(MAX),	--截止日期
	@billcode			VARCHAR(MAX),	--单据编号
	@btypeId			VARCHAR(MAX),	--往来单位id
	@ptypeId			VARCHAR(MAX),	--商品id
	@billstatus			INT				--单据状态
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,
        @MAtypeid VARCHAR(50), 
        @MBtypeid VARCHAR(50), 
        @MBtypeid2 VARCHAR(50), 
        @MEtypeid VARCHAR(50),
        @MKtypeid VARCHAR(50), 
        @MPtypeid VARCHAR(50), 
        @MExpense VARCHAR(50), 
        @MIncome VARCHAR(50),
        @MCapital VARCHAR(50),
        @MDtypeid VARCHAR(50),
        @MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)	


--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID)	

DECLARE @SQL VARCHAR(MAX)=''
SET @SQL='
	SELECT	b.ID,
			i.CreatedTime,
			i.SerialNo,
			b.ptypeid,
			i.btypeid,
			i.id as billnumberid,
			
			isnull(fu.salemunitrate,0)*qty as qty,			   
			isnull(fu.unit,'''') as  unitname,
			case when isnull(fu.salemunitrate,0)=0 then 0 else  b.DiscountPrice/isnull(fu.salemunitrate,0) end DiscountPrice,
			
			isnull(fu.saleunitname,'''') as saleunitname,
			isnull(fu.saleunitid,0) as saleunitid,

			qty as saleqty,
			b.tax,
			b.discount,
			b.DiscountPrice as saleprice,
			''1 ''+ISNULL(fu.saleunitname,'''') +'' = ''+CAST(ISNULL(fu.salemunitrate,''0'') AS VARCHAR(20))+'' ''+ISNULL(fu.Unit,'''') AS conversionrelationship,
			
			 
			b.SaleTotal,
			b.Status,
			b.ReachQty,
			b.confirmqty,
			(b.Qty-b.Reachqty-b.StopQty) as WaitQty,
			
			isnull(s.noconfirmqty,0) as noconfirmqty,
			b.stopqty,
			(select isnull(sum(ReachQty),0) from om_backorderdetail where orderid=b.id) as backqty,
			b.comment
	FROM dbo.OM_OrderDetail b
	INNER JOIN dbo.OM_Order i ON b.billNumberID=i.id
	INNER JOIN #GetManBTypeId mb ON i.btypeid=mb.TypeId
	INNER JOIN #GetManPTypeId mp ON b.ptypeid=mp.TypeId
	Left Join dbo.F_GetPtypeUnitInfo() fu  on fu.typeid=b.ptypeid
	LEFT  JOIN 
	(
		select sum(reachqty-confirmqty) as noconfirmqty,ombillid from om_shipments where status=1 group by ombillid
	)s on b.id=s.ombillid
	WHERE   i.CreatedTime>='''+@startdate+'''
			AND CONVERT (DATE,i.CreatedTime,120)<='''+@enddate+'''
			AND i.SerialNo like ''%'+@billcode+'%'''
IF @billstatus<>9
	SET @sql +='
			AND b.STATUS='+CAST(@billstatus AS VARCHAR)
SET @SQL +=	'
	ORDER BY i.SerialNo,i.CreatedTime,b.id '

PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManBTypeId,#GetManPTypeId

GO







GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_GetInventoryProduct]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_GetInventoryProduct]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_GetInventoryProduct]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***********************************  
 *任我行通用事业部 过账组 
 
 *Title: 查询存货商品
 *CreatorName: 杨川
 *CreatedTime: 2014-07-28
 *ModifierName: 
 *ModifiedTime: 
***********************************/

create PROCEDURE [dbo].[Gp_OM_GetInventoryProduct]
(
	@InventoryID    INT,
	@Ptypeid		VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	 IF @Ptypeid<>''
		SELECT p.typeId,p.parid,p.FullName,p.UserCode,o.[Status],p.sonnum 
		 FROM ptype p
		 JOIN (SELECT a FROM  dbo.f_split(@Ptypeid,',')) f ON p.typeId LIKE f.a+'%' 
		 LEFT JOIN OM_Inventory_Ext o 
		 ON p.typeId=o.Ptypeid AND o.InventoryID=@InventoryID
		 WHERE sonnum=0  AND Leveal > 0 AND OmUse=1 AND deleted=0
		 ORDER BY p.typeId
     ELSE 
		 SELECT p.typeId,p.parid,p.FullName,p.UserCode,o.[Status],p.sonnum 
		 FROM ptype p
		 LEFT JOIN OM_Inventory_Ext o 
		 on p.typeId=o.Ptypeid AND o.InventoryID=@InventoryID
		 WHERE sonnum=0  AND Leveal > 0 AND OmUse=1 AND deleted=0
		 ORDER BY p.typeId
	 --SELECT p.typeId,p.parid,p.FullName,p.UserCode,o.[Status],p.sonnum
	 --FROM (	SELECT * FROM F_GetStandard_OMPtype('00001')) p 
	 --LEFT JOIN OMInventoryInfo_Ext o 
	 --ON p.typeId=o.Ptypeid AND o.InventoryID=@InventoryID
	 --ORDER BY p.typeId
	 
	
	 
END
SET NOCOUNT OFF
GO




/****** Object:  StoredProcedure [dbo].[Gp_OM_GetOrderCount]    Script Date: 08/22/2014 13:17:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_GetOrderCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_GetOrderCount]
GO




/****** Object:  StoredProcedure [dbo].[Gp_OM_GetOrderCount]    Script Date: 08/22/2014 13:17:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	
*/
--exec gp_SelectOMOrderList 10,1,1,'','','',0


CREATE  PROCEDURE [dbo].[Gp_OM_GetOrderCount]
(
 
 @OperatorID varchar(50),
 @time varchar(50)='0',
 @state varchar(50)='6',
 @typeid varchar(50)=''
 

)




--@Encode$--
AS
SET NOCOUNT ON
	
DECLARE @wheretypeid varchar(max)
SET @wheretypeid=''
DECLARE @wheretime varchar(max)
SET @wheretime=''
DECLARE @wherestate varchar(max)
SET @wherestate=''

	if(@time = '0')--全部时间
	Set @wheretime=''
	if(@time = '1')--最近一个月
	Set @wheretime=' and omOrder.CreatedTime between dateadd(mm,-1,getDate()) and getDate()'
	if(@time = '2')--一个月前
	Set @wheretime=' and datediff(month,omOrder.CreatedTime,getdate())=1'
	if(@time = '3')--今天
	Set @wheretime=' and DateDiff(dd,omOrder.CreatedTime,getdate())=0 '
	
	if(@state = '6')--全部状态
	  SET @wherestate=''
	if(@state = '0')
	  SET @wherestate=' and obill.STATUS=0'
    if(@state = '2')
	  SET @wherestate=' and obill.STATUS=2'
	if(@state = '3')
	  SET @wherestate=' and obill.STATUS=3'
    if(@state = '4')
      SET @wherestate=' and obill.STATUS=4'
    if(@state = '5')
      SET @wherestate=' and obill.STATUS=5'


			
DECLARE @sql varchar(max)
	set @sql='select * from ( 
		SELECT cast(obill.billNumberID as int) as billNumberID
			  ,obill.ptypeid as ptypeid,obill.pid,
			  p.fullname  as Fullname,
			  ROUND(obill.qty,4) AS qty
			 ,ROUND(obill.price,4) AS price
			  ,obill.total as total
			  ,obill.comment as comment
			  ,cast(obill.ID as int) as ID
			  ,obill.Discount as Discount
			  ,obill.DiscountPrice as DiscountPrice
			  ,obill.SaleTotal as SaleTotal
			  ,obill.UnitID as UnitID
			  ,obill.ItemID as ItemID
			  ,obill.IsCombined as IsCombined
			  ,obill.ReachQty as ReachQty
			  ,obill.ConfirmQty as ConfirmQty
			  ,obill.StopQty as StopQty,
			  (obill.Qty-obill.Reachqty-obill.StopQty) as NoReachQty,
			  (select isnull(sum(ReachQty-ConfirmQty),0) from OM_Shipments where ombillid=obill.ID and [STATUS]=1) as NoConfirmQty ,
			  omOrder.SerialNo as BillCode,
			  Row_Number() OVER (ORDER BY obill.id) as rownumberid 
			  ,cast(obill.[STATUS] as varchar(50)) as [STATUS],
			  cast(omOrder.Status as varchar(50)) as BillStatus,
			  omOrder.TotalMoney as TotalMoney,
			  cast(omOrder.CreatedTime as varchar(50)) as BillDate,
			  pu.fullname as uname
			FROM OM_OrderDetail obill
			INNER JOIN OM_Order omOrder ON  omOrder.id=obill.billNumberID
			INNER JOIN ptype p ON p.typeid=obill.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=obill.UnitID
			where omOrder.CreatorId='''+@OperatorID+'''
			'+@wherestate+'
			'+@wheretime+'
			
	) as b 
	
	where 1=1 
	
	
	order by b.id'
	
	print (@sql)
	exec(@sql)

GO






/****** Object:  StoredProcedure [dbo].[Gp_OM_GetOrders]    Script Date: 08/22/2014 12:50:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_GetOrders]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_GetOrders]
GO


/****** Object:  StoredProcedure [dbo].[Gp_OM_GetOrders]    Script Date: 08/22/2014 12:50:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*	
	
*/
--exec gp_SelectOMOrderList 10,1,1,'3','','',0


create PROCEDURE [dbo].[Gp_OM_GetOrders]
(
 @PageSize int,
 @PageNum  int,
 @CreatorId varchar(50),
 @time varchar(50)='0',
 @state varchar(50)='6',
 @keyword  varchar(50),
 
 @TotalPage  int output
)


--@Encode$--
AS
SET NOCOUNT ON
	
DECLARE @wheretypeid varchar(max)
SET @wheretypeid=''
DECLARE @wheretime varchar(max)
SET @wheretime=''
DECLARE @wherestate varchar(max)
SET @wherestate=''

	if(@time = '0')--全部时间
	Set @wheretime=''
	if(@time = '1')--最近一个月
	Set @wheretime=' and omOrder.CreatedTime between dateadd(mm,-1,getDate()) and getDate()'
	if(@time = '2')--一个月前
	Set @wheretime=' and datediff(month,omOrder.CreatedTime,getdate())=1'
	if(@time = '3')--今天
	Set @wheretime=' and DateDiff(dd,omOrder.CreatedTime,getdate())=0 '
	
	if(@state = '6')--全部状态
	  SET @wherestate=''
	if(@state = '0')
	  SET @wherestate=' and omOrderDetail.STATUS=0'
    if(@state = '2')
	  SET @wherestate=' and omOrderDetail.STATUS=2'
	if(@state = '3')
	  SET @wherestate=' and omOrderDetail.STATUS=3'
    if(@state = '4')
      SET @wherestate=' and omOrderDetail.STATUS=4'
    if(@state = '5')
      SET @wherestate=' and omOrderDetail.STATUS=5'
     if(@state = '7')--已提交未完成
      SET @wherestate=' and omOrderDetail.STATUS in(0,2,3)'

CREATE TABLE #MyTempTable (total INT PRIMARY KEY)
  
    
DECLARE @sqltotal varchar(max)='';
			
			set @sqltotal='insert into #MyTempTable select a.total  from ( 
	        select  COUNT(1) as total from OM_OrderDetail omOrderDetail 
	        INNER JOIN OM_Order omOrder ON  omOrder.id=omOrderDetail.billNumberID
	        INNER JOIN ptype p ON p.typeid=omOrderDetail.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=omOrderDetail.UnitID
			where omOrder.CreatorId='''+@CreatorId+'''
				'+@wheretime+'
	            '+@wherestate+'
	            ) a
			'
		 
			if(@keyword<>'')
			begin
			set @sqltotal='insert into #MyTempTable select a.total  from ( 
	        select  COUNT(1) as total from OM_OrderDetail omOrderDetail 
	        INNER JOIN OM_Order omOrder ON  omOrder.id=omOrderDetail.billNumberID
	        INNER JOIN ptype p ON p.typeid=omOrderDetail.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=omOrderDetail.UnitID
			where omOrder.CreatorId='''+@CreatorId+'''
				'+@wheretime+'
	            '+@wherestate+'
	            
	             and (p.fullname  like ''%'+@keyword+'%'' or p.usercode like ''%'+@keyword+'%''
	             or omOrder.SerialNo like ''%'+@keyword+'%''
	             )
	            
	            ) a
			'
			end
			exec(@sqltotal)
		 	select @TotalPage=sum(total) from #MyTempTable
		 	


	

			
			
DECLARE @sql varchar(max)
	set @sql=

		'SELECT * FROM(SELECT  cast(omOrderDetail.billNumberID as int) as billNumberID
			  ,omOrderDetail.ptypeid as ptypeid,omOrderDetail.pid,
			  p.usercode as UserCode,
			  p.fullname  as Fullname,
			  ROUND(omOrderDetail.qty,4) AS qty
			 ,ROUND(omOrderDetail.price,4) AS price
			  ,omOrderDetail.total as total
			  ,omOrderDetail.comment as comment
			  ,cast(omOrderDetail.ID as int) as ID
			  ,omOrderDetail.Discount as Discount
			  ,omOrderDetail.DiscountPrice as DiscountPrice
			  ,omOrderDetail.SaleTotal as SaleTotal
			  ,omOrderDetail.UnitID as UnitID
			  ,omOrderDetail.ItemID as ItemID
			  ,omOrderDetail.IsCombined as IsCombined
			  ,omOrderDetail.ReachQty as ReachQty
			  ,omOrderDetail.ConfirmQty as ConfirmQty
			  ,omOrderDetail.StopQty as StopQty,
			  (omOrderDetail.Qty-omOrderDetail.Reachqty-omOrderDetail.StopQty) as NoReachQty,
			  (select isnull(sum(ReachQty-ConfirmQty),0) from OM_Shipments where OM_Shipments.id=omOrderDetail.ID and [STATUS]=1) as NoConfirmQty ,
			  omOrder.SerialNo as BillCode,
			  Row_Number() OVER (ORDER BY omOrderDetail.id) as rownumberid 
			  ,cast(omOrderDetail.[STATUS] as varchar(50)) as [STATUS],
			  cast(omOrder.Status as varchar(50)) as BillStatus,
			  omOrder.TotalMoney as TotalMoney,
			  cast(omOrder.CreatedTime as varchar(50)) as BillDate,
			  pu.fullname as uname,
			  omOrder.CreatedTime,
			  (select isnull(sum(ReachQty),0) from om_backorderdetail where orderid=omOrderDetail.id) as backqty ,
			  ROW_NUMBER() OVER(Order by  omOrderDetail.ID) as RowID,
			  (SELECT  COUNT(*) FROM dbo.OM_OrderDetail od WHERE od.ConfirmQty<=0 AND od.billNumberID=omOrder.id) as notconfimqty,
			  (SELECT  COUNT(*) FROM dbo.OM_OrderDetail od WHERE od.billNumberID=omOrder.id) as detailcount,
			  (SELECT  MAX(ID) FROM dbo.OM_OrderDetail od WHERE od.billNumberID=omOrder.id) as maxdetailid,
			  (SELECT PreferenceMoney FROM dbo.OM_Order where ID= omOrder.ID) as PreferenceMoney
			FROM OM_OrderDetail omOrderDetail
			INNER JOIN OM_Order omOrder ON  omOrder.id=omOrderDetail.billNumberID
			INNER JOIN ptype p ON p.typeid=omOrderDetail.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=omOrderDetail.UnitID
			where omOrder.CreatorId='''+@CreatorId+'''
			'+@wherestate+'
			'+@wheretime+' )T WHERE RowID>='+CAST((@PageSize*(@PageNum-1)+1) AS varchar)+' AND RowID<='+CAST((@PageSize*@PageNum)AS varchar)+'			 
			 order by ID
			 '

			if(@keyword<>'')
			set @sql=

		'SELECT * FROM(SELECT cast(omOrderDetail.billNumberID as int) as billNumberID
			  ,omOrderDetail.ptypeid as ptypeid,omOrderDetail.pid,
			  p.usercode as UserCode,
			  p.fullname  as Fullname,
			  ROUND(omOrderDetail.qty,4) AS qty
			 ,ROUND(omOrderDetail.price,4) AS price
			  ,omOrderDetail.total as total
			  ,omOrderDetail.comment as comment
			  ,cast(omOrderDetail.ID as int) as ID
			  ,omOrderDetail.Discount as Discount
			  ,omOrderDetail.DiscountPrice as DiscountPrice
			  ,omOrderDetail.SaleTotal as SaleTotal
			  ,omOrderDetail.UnitID as UnitID
			  ,omOrderDetail.ItemID as ItemID
			  ,omOrderDetail.IsCombined as IsCombined
			  ,omOrderDetail.ReachQty as ReachQty
			  ,omOrderDetail.ConfirmQty as ConfirmQty
			  ,omOrderDetail.StopQty as StopQty,
			  (omOrderDetail.Qty-omOrderDetail.Reachqty-omOrderDetail.StopQty) as NoReachQty,
			  (select isnull(sum(ReachQty-ConfirmQty),0) from OM_Shipments where OM_Shipments.id=omOrderDetail.ID and [STATUS]=1) as NoConfirmQty ,
			  omOrder.SerialNo as BillCode,
			  Row_Number() OVER (ORDER BY omOrderDetail.id) as rownumberid 
			  ,cast(omOrderDetail.[STATUS] as varchar(50)) as [STATUS],
			  cast(omOrder.Status as varchar(50)) as BillStatus,
			  omOrder.TotalMoney as TotalMoney,
			  cast(omOrder.CreatedTime as varchar(50)) as BillDate,
			  pu.fullname as uname,
			  omOrder.CreatedTime ,
			  (select isnull(sum(ReachQty),0) from om_backorderdetail where orderid=omOrderDetail.id) as backqty,
			   ROW_NUMBER() OVER(Order by  omOrderDetail.ID) as RowID,
			   (SELECT COUNT(*) FROM dbo.OM_OrderDetail od WHERE od.ConfirmQty<=0 AND od.billNumberID=omOrder.id) as notconfimqty
			FROM OM_OrderDetail omOrderDetail
			INNER JOIN OM_Order omOrder ON  omOrder.id=omOrderDetail.billNumberID
			INNER JOIN ptype p ON p.typeid=omOrderDetail.ptypeid
			INNER JOIN ptype_units pu ON pu.UnitsId=omOrderDetail.UnitID
			where omOrder.CreatorId='''+@CreatorId+'''
			'+@wherestate+'
			'+@wheretime+' and (p.fullname  like ''%'+@keyword+'%'' or p.usercode like ''%'+@keyword+'%''
			or omOrder.SerialNo like ''%'+@keyword+'%''))T WHERE RowID>='+CAST((@PageSize*(@PageNum-1)+1) AS varchar)+' AND RowID<='+CAST((@PageSize*@PageNum)AS varchar)+'			 
			 order by id
			 '
	print(@sql)		

	exec(@sql)


 drop table #MyTempTable;

GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_OM_GetProductLeveal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GP_OM_GetProductLeveal]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


/***********************************  
 *Title: 商品分级层信息
 *CreatorName: 王涛
 *CreatedTime: 2014年11月14日 16:03:00
 *ModifierName: 
 *ModifiedTime: 
***********************************/

CREATE  PROCEDURE [dbo].GP_OM_GetProductLeveal
(
	@parid VARCHAR(50),
	@pagesize INT,
	@pagenumber INT ,
	@totalpage INT OUT 
)
--@encode$--
AS
SET NOCOUNT ON

PRINT(CONVERT(VARCHAR(30),GETDATE(),21))
DECLARE @startindex INT 
SET @startindex= @pagesize * (@pagenumber + 1)
;WITH  myptype AS
(
	SELECT DISTINCT p.typeId,p.sonnum,p.UserCode,p.FullName,p.ParId,p.leveal
	FROM  ptype p
	INNER JOIN (
				 SELECT typeId FROM ptype WHERE sonnum=0 AND OmUse=1 AND deleted=0
				) ps ON  LEFT(ps.typeId,LEN(p.typeid)) = p.typeId
	WHERE p.ParId=@parid  AND p.sonnum<>0
)
SELECT * 
INTO #ptype
FROM myptype ORDER BY typeid DESC
PRINT(CONVERT(VARCHAR(30),GETDATE(),21))

DECLARE @startid varchar(10),@topindex VARCHAR(10)
SET @startid =@pagesize*@pagenumber
SET @topindex=@pagesize*(@pagenumber+1)

	
DECLARE @sql VARCHAR(2000)
SET @sql='SELECT p1.typeid  as ptypeid,case when len(fullname)>10 then left(fullname,10)+''...'' else fullname end  as fullname ,parid,usercode,leveal ,fullname as displayname 
			 FROM #ptype p1, 
						( 
							SELECT TOP '+@topindex+' row_number() OVER (ORDER BY  typeid DESC) ID , typeId 
							FROM dbo.#ptype 							
						) p2 
			 WHERE p1.typeId = p2.typeId AND p2.ID > '+ @startid+' ORDER BY p2.ID ASC '   
PRINT(@sql)			 
EXEC(@sql)
PRINT(CONVERT(VARCHAR(30),GETDATE(),21))
SELECT @totalpage=COUNT(1) FROM dbo.#ptype where parid =@parid and sonnum<>0
GO











/****** Object:  StoredProcedure [dbo].[GP_OM_GetProducts]    Script Date: 08/22/2014 11:36:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_OM_GetProducts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GP_OM_GetProducts]
GO


/****** Object:  StoredProcedure [dbo].[GP_OM_GetProducts]    Script Date: 08/22/2014 11:36:24 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/***********************************  
 *任我行通用事业部 过账组 
 *Title: 商品信息展示
 *CreatorName: 杨川
 *CreatedTime: 2014-07-07
 *ModifierName: 
 *ModifiedTime: 
***********************************/

CREATE  PROCEDURE [dbo].[GP_OM_GetProducts]
(
--商品名称
 @ProductName NVARCHAR(50),
 --往来单位
 @BtypeID NVARCHAR(50),
 --分页大小
 @PageSize  Int,
 --页码
 @PageNumber  Int,
 --总数据,out参数
 @TotalPage  Int output
)
--@encode$--
AS
SET NOCOUNT ON
	
    --折扣，默认1（100%）
	DECLARE @discount  NUMERIC(24, 10) =1 
	--根据登录时的往来单位Id，获取折扣
	SELECT @discount=ISNULL(SaleZekou,1) FROM [dbo].[btype] WHERE typeId=@BtypeID
	
	if @ProductName<>''
	begin
	
			--分页数据总量
			select @TotalPage = COUNT(0) from [ptype] 
			where (FullName like '%'+ @ProductName +'%' or UserCode like '%'+ @ProductName +'%')  
			and soncount =0 AND OmUse=1 and deleted=0
			
			
			
			select * from ( 
				SELECT	
						Row_Number() OVER (ORDER BY typeid) as RownumberId ,
						typeId AS Ptypeid,
						product.UserCode,
						product.FullName,
						OmPrice AS Price, 
						@discount AS Discount,
						productUnit.FullName AS UnitName,
						inventoryExt.InventoryID as InventoryInfoID,
						inventoryExt.[Status] as InventoryInfo,
						SaleUnitId AS UnitID,
						ROUND(OmPrice*@discount,4) AS DiscountPrice
				FROM dbo.Ptype product
				LEFT JOIN dbo.PType_Units productUnit ON product.SaleUnitId=productUnit.UnitsId
				LEFT JOIN OM_Inventory_Ext inventoryExt on  product.TypeId=inventoryExt.PtypeId and inventoryExt.InventoryID=1
				WHERE product.sonnum=0 AND
				product.OmUse=1 AND product.deleted=0 and
				(product.FullName like '%'+ @ProductName +'%'  or product.UserCode like '%'+ @ProductName +'%')
			
				
			) as temp 
			where rownumberid BETWEEN (@PageNumber )*@PageSize+1 and (@PageNumber+1)*@pagesize
			ORDER BY PtypeId
	end

	else
	begin

			--数据总量
			select @TotalPage = COUNT(0) from [ptype] where parid<>'root' AND sonnum=0 AND OmUse=1 and deleted=0
			
			select * from ( 
				SELECT	
						Row_Number() OVER (ORDER BY TypeId) as RownumberId,
						typeId AS Ptypeid,
						product.UserCode,
						product.FullName,
						OmPrice AS Price, 
						@discount AS Discount,
						productUnit.FullName AS UnitName,
						inventoryExt.InventoryID as InventoryInfoID,
						inventoryExt.[Status] as InventoryInfo,
						SaleUnitId AS UnitID,
						ROUND(OmPrice*@discount,4) AS DiscountPrice
				FROM dbo.Ptype product
				LEFT JOIN dbo.PType_Units productUnit ON product.SaleUnitId=productUnit.UnitsId
				LEFT JOIN OM_Inventory_Ext inventoryExt on  product.TypeId=inventoryExt.PtypeId and inventoryExt.InventoryID=1
				where parid<>'root' AND
				product.sonnum=0 AND
				product.OmUse=1  and product.deleted=0
				/*AND
				product.typeid not in(
					select typeid from Ptype where typeid in (select substring(parid,0,6) from ptype where leveal=2)
				    
					)
				*/
			) as temp 
			where rownumberid BETWEEN (@PageNumber )*@PageSize+1 and (@PageNumber+1)*@pagesize
			ORDER BY PtypeId

	end


GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_OM_GetProductsByParid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GP_OM_GetProductsByParid]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


/***********************************  
 *Title: 商品信息展示
 *CreatorName: 王涛
 *CreatedTime: 2014-07-07
 *ModifierName: 
 *ModifiedTime: 
***********************************/

CREATE  PROCEDURE [dbo].[GP_OM_GetProductsByParid]
(
--商品名称
 @parid NVARCHAR(50),
 --往来单位
 @BtypeID NVARCHAR(50),
 --分页大小
 @PageSize  Int,
 --页码
 @PageNumber  Int,
 --总数据,out参数
 @TotalPage  Int output
)
--@encode$--
AS
SET NOCOUNT ON
	
    --折扣，默认1（100%）
	DECLARE @discount  NUMERIC(24, 10) =1 
	--根据登录时的往来单位Id，获取折扣
	SELECT @discount=ISNULL(SaleZekou,1) FROM [dbo].[btype] WHERE typeId=@BtypeID
	

			--分页数据总量
			select @TotalPage = COUNT(0) from [ptype] 
			WHERE typeid LIKE @parid+'%'
			and soncount =0 AND OmUse=1 and deleted=0
			
			
					
			select * from ( 
				SELECT	
						Row_Number() OVER (ORDER BY typeid) as RownumberId ,
						typeId AS Ptypeid,
						product.UserCode,
						product.FullName,
						OmPrice AS Price, 
						@discount AS Discount,
						productUnit.FullName AS UnitName,
						inventoryExt.InventoryID as InventoryInfoID,
						inventoryExt.[Status] as InventoryInfo,
						SaleUnitId AS UnitID,
						ROUND(OmPrice*@discount,4) AS DiscountPrice
				FROM dbo.Ptype product
				LEFT JOIN dbo.PType_Units productUnit ON product.SaleUnitId=productUnit.UnitsId
				LEFT JOIN OM_Inventory_Ext inventoryExt on  product.TypeId=inventoryExt.PtypeId and inventoryExt.InventoryID=1
				WHERE product.sonnum=0 AND
				product.OmUse=1 AND product.deleted=0 and
				product.typeid LIKE @parid+'%'
			
				
			) as temp 
			where rownumberid BETWEEN (@PageNumber )*@PageSize+1 and (@PageNumber+1)*@pagesize
			ORDER BY PtypeId
	
GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_OM_GetProductTreeList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GP_OM_GetProductTreeList]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


/***********************************  
 *Title: 显示商品树形列表
 *CreatorName: 王涛
 *CreatedTime: 2014年11月14日 16:03:00
 *ModifierName: 
 *ModifiedTime: 
***********************************/

CREATE  PROCEDURE [dbo].GP_OM_GetProductTreeList
(
	@parid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON


;WITH  myptype AS
(
	SELECT  p.typeId AS PtypeId,
			case when len(fullname)>10 then left(fullname,10)+'...' else fullname end  as fullname,
			fullname as FullNameAll
	FROM  ptype p
	INNER JOIN (
				 SELECT typeId FROM ptype WHERE sonnum=0 AND OmUse=1 AND deleted=0
				) ps ON  LEFT(ps.typeId,LEN(p.typeid)) = p.typeId
	WHERE p.ParId=@parid  AND p.sonnum<>0
)
SELECT PtypeId,FullName,FullNameAll,COUNT(PtypeId)-1 AS sonnum --除去本身一个
FROM myptype 
GROUP BY PtypeId,FullName,FullNameAll
ORDER BY PtypeId DESC


GO










GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_GetShipments]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_GetShipments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_GetShipments]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/***********************************  
 *任我行通用事业部 过账组 
 *Title: 发货情况查询
 *CreatorName: 杨川
 *CreatedTime: 2014-07-09
 *ModifierName: 
 *ModifiedTime: 
***********************************/



create  PROCEDURE [dbo].[Gp_OM_GetShipments]
(
 @OMBillID INT,
 @PageSize  int,
 @PageNum  int,
 @TotalPage  int output
)
--@encode$--
AS
SET NOCOUNT ON
	select @TotalPage = COUNT(0) FROM OM_Shipments WHERE OMBillID=@OMBillID
	select * from ( 
		select 
		cast(OM_Shipments.id as int) as id,
		cast(OM_Shipments.ombillid as int) as ombillid, 
		cast(orderDetail.[STATUS] as varchar(50)) as [STATUS],
		OM_Shipments.STATUS AS state, 
		OM_Shipments.reachqty,
		OM_Shipments.confirmqty,
		OM_Shipments.comment, 
		case when OM_Shipments.STATUS=1 then (OM_Shipments.reachqty-OM_Shipments.confirmqty) else '0' end as NoConfirmQty  ,ROW_NUMBER() over(order by OM_Shipments.id) rownumberid 
		from OM_Shipments
		INNER JOIN OM_OrderDetail orderDetail ON orderDetail.id=OM_Shipments.ombillid
		WHERE OMBillID=@OMBillID
	) as b 
	where rownumberid BETWEEN (@PageNum -1)*@pagesize+1 and @PageNum*@pagesize
	ORDER BY id
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_OM_GetTreeProductsByParid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GP_OM_GetTreeProductsByParid]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


/***********************************  
 *Title: 商品信息展示
 *CreatorName: 王涛
 *CreatedTime: 2014-07-07
 *ModifierName: 
 *ModifiedTime: 
***********************************/

CREATE  PROCEDURE [dbo].GP_OM_GetTreeProductsByParid
(
--商品名称
 @parid NVARCHAR(50),
 --分页大小
 @PageSize  Int,
 --页码
 @PageNumber  Int,
 --总数据,out参数
 @TotalPage  Int output
)
--@encode$--
AS
SET NOCOUNT ON
	
	--分页数据总量
	select @TotalPage = COUNT(0) 
	from [ptype] 
	WHERE typeid LIKE @parid+'%'
	and soncount =0 AND OmUse=1 and deleted=0
	
	select * from ( 
		SELECT	
				Row_Number() OVER (ORDER BY product.typeid) as RownumberId ,
				product.typeId AS Ptypeid,
				product.UserCode,
				product.fullname as FullNameAll,
				CASE WHEN LEN(product.FullName)<10 THEN product.FullName ELSE  left(product.FullName,10)+'...' END as FullName,
				OmPrice AS Price, 
				'' as GoodTreePicPath,
				pu.FullName AS UnitName,
				product.[Standard] AS standardname,
				product.[type] AS typename

		FROM dbo.Ptype product
		LEFT JOIN dbo.PType_Units pu ON product.SaleUnitId=pu.UnitsId
		WHERE product.sonnum=0 AND product.OmUse=1 AND product.deleted=0 and
		product.typeid LIKE @parid+'%'
	
		
	) as temp 
	where rownumberid BETWEEN (@PageNumber )*@PageSize+1 and (@PageNumber+1)*@pagesize
	ORDER BY PtypeId
	
GO







/****** Object:  StoredProcedure [dbo].[Gp_OM_QueryBillExpressInfo]    Script Date: 01/21/2015 10:05:51 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_QueryBillExpressInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_QueryBillExpressInfo]
GO


/****** Object:  StoredProcedure [dbo].[Gp_OM_QueryBillExpressInfo]    Script Date: 01/21/2015 10:05:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
OM前台查询订单明细物流信息
*/
CREATE PROCEDURE [dbo].[Gp_OM_QueryBillExpressInfo]
(
	@OMBillID INT
)
--@encode$--
AS
BEGIN
	SELECT waybillcode AS ExpressCode,Tel AS ExpressCompany,BillCode,a.MQty AS Qty FROM dbo.SaleBill a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId=b.BillNumberId
		WHERE a.OMBillID=@OMBillID AND B.RedWord=0
END

GO






/*
OM订单统计表
*/
/****** Object:  StoredProcedure [dbo].[Gp_OM_QueryOrderCount]    Script Date: 01/20/2015 11:14:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_QueryOrderCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_QueryOrderCount]
GO


/****** Object:  StoredProcedure [dbo].[Gp_OM_QueryOrderCount]    Script Date: 01/20/2015 11:14:01 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Gp_OM_QueryOrderCount]
(
	@startDate VARCHAR(20),
	@endDate VARCHAR(20),
	@pfilter VARCHAR(200),
	@currentPageIndex INT,
	@pageSize INT,
	@OperatorID VARCHAR(50)
	--@RowCount INT OUT,
	--@S_SaleTotal  NUMERIC(24, 10)  OUT,
	--@S_qty  NUMERIC(24, 10)  OUT,
	--@S_ReachQty  NUMERIC(24, 10)  OUT,
	--@S_ConfirmQty  NUMERIC(24, 10)  OUT,
	--@S_BackQty  NUMERIC(24, 10)  OUT,
	--@S_StopQty  NUMERIC(24, 10)  OUT
)
--@encode$--
AS
BEGIN
	SELECT b.ptypeid,p.UserCode,p.FullName,b.SaleTotal,b.qty,b.ReachQty,b.ConfirmQty,
		ISNULL((SELECT SUM(D.ReachQty) FROM dbo.OM_BackOrderDetail d WHERE d.OrderIndexId=b.billNumberID AND d.OrderId=b.ID),0) AS BackQty,
		b.StopQty INTO #t
		 FROM dbo.OM_Order a
		INNER JOIN dbo.OM_OrderDetail b ON a.Id=b.billNumberID
		INNER JOIN dbo.ptype P ON B.ptypeid=P.typeId
	 WHERE a.CreatedTime>=@startDate AND a.CreatedTime<=@endDate+' 23:59:00'
		AND CreatorId=@OperatorID
		AND (@pfilter='' OR (p.UserCode LIKE '%'+@pfilter+'%' 
								OR p.FullName LIKE '%'+@pfilter+'%'
								OR p.[Standard] LIKE '%'+@pfilter+'%'
								OR p.[Type] LIKE '%'+@pfilter+'%'))							
	
	SELECT ptypeid,UserCode,FullName,SUM(SaleTotal) AS SaleTotal,SUM(qty) AS qty,SUM(ReachQty) AS ReachQty,
		SUM(ConfirmQty) AS ConfirmQty,SUM(BackQty) AS BackQty,SUM(StopQty) AS StopQty,IDENTITY(INT,1,1) AS id INTO #a FROM #t
		GROUP BY ptypeid,UserCode,FullName
	ORDER BY UserCode
	
	SELECT * FROM #a WHERE id>=(@currentPageIndex-1)*@pageSize+1 AND id<=@currentPageIndex*@pageSize
	--SELECT @RowCount=COUNT(1),@S_SaleTotal=ISNULL(SUM(saletotal),0),@S_qty=ISNULL(SUM(qty),0),@S_ReachQty=ISNULL(SUM(ReachQty),0),
	--		@S_ConfirmQty=ISNULL(SUM(ConfirmQty),0),@S_BackQty=ISNULL(SUM(BackQty),0),@S_StopQty=ISNULL(SUM(StopQty),0)
	-- FROM #a
	
	SELECT COUNT(1) AS [RowCount],ISNULL(SUM(saletotal),0) AS S_SaleTotal,
			ISNULL(SUM(qty),0) AS S_qty,ISNULL(SUM(ReachQty),0) AS S_ReachQty,
			ISNULL(SUM(ConfirmQty),0) AS S_ConfirmQty,
			ISNULL(SUM(BackQty),0) AS S_BackQty,
			ISNULL(SUM(StopQty),0) AS S_StopQty
	 FROM #a
	DROP TABLE #t,#a
END

GO






/*
OM订单统计明细表
*/
/****** Object:  StoredProcedure [dbo].[Gp_OM_QueryOrderCount]    Script Date: 01/20/2015 11:14:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_QueryOrderDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_QueryOrderDetail]
GO


/****** Object:  StoredProcedure [dbo].[Gp_OM_QueryOrderCount]    Script Date: 01/20/2015 11:14:01 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Gp_OM_QueryOrderDetail]
(
	@startDate VARCHAR(20),
	@endDate VARCHAR(20),
	@ptypeid VARCHAR(50),
	@currentPageIndex INT,
	@pageSize INT,
	@OperatorID VARCHAR(50)--,
	--@RowCount INT OUT,
	--@S_SaleTotal  NUMERIC(24, 10)  OUT,
	--@S_qty  NUMERIC(24, 10)  OUT,
	--@S_ReachQty  NUMERIC(24, 10)  OUT,
	--@S_ConfirmQty  NUMERIC(24, 10)  OUT,
	--@S_BackQty  NUMERIC(24, 10)  OUT,
	--@S_StopQty  NUMERIC(24, 10)  OUT
)
--@encode$--
AS
BEGIN
	SELECT CONVERT(VARCHAR(10),a.CreatedTime,121) AS BillDate,
			a.SerialNo AS BillCode,
			b.Comment,
		 b.ptypeid,p.UserCode AS PUserCode,p.FullName AS PFullName,b.SaleTotal,b.qty,b.ReachQty,b.ConfirmQty,
		 b.DiscountPrice AS Price,
		 b.SaleTotal AS Total,
		ISNULL((SELECT SUM(d.ReachQty) FROM dbo.OM_BackOrderDetail d WHERE d.OrderIndexId=b.billNumberID AND d.OrderId=b.ID),0) AS BackQty,
		b.StopQty,
		p.comment AS PComment ,
		b.id AS ombillid,
		IDENTITY(INT,1,1) AS id 
		 INTO #t
		 FROM dbo.OM_Order a
		INNER JOIN dbo.OM_OrderDetail b ON a.Id=b.billNumberID
		INNER JOIN dbo.ptype P ON B.ptypeid=P.typeId
	 WHERE a.CreatedTime>=@startDate AND a.CreatedTime<=@endDate+' 23:59:00'
		AND b.ptypeid=@ptypeid					
	
	
	
	SELECT * FROM #t WHERE id>=(@currentPageIndex-1)*@pageSize+1 AND id<=@currentPageIndex*@pageSize
	
	SELECT COUNT(1) AS [RowCount],ISNULL(SUM(saletotal),0) AS S_SaleTotal,
			ISNULL(SUM(qty),0) AS S_qty,ISNULL(SUM(ReachQty),0) AS S_ReachQty,
			ISNULL(SUM(ConfirmQty),0) AS S_ConfirmQty,
			ISNULL(SUM(BackQty),0) AS S_BackQty,
			ISNULL(SUM(StopQty),0) AS S_StopQty
	 FROM #t
	DROP TABLE #t
END

GO






GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_SaveBackOrder]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_SaveBackOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_SaveBackOrder]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***********************************  
 *任我行通用事业部 过账组 
 *Title: 保存订单
 *CreatorName: 杨川
 *CreatedTime: 2014-07-07
 *ModifierName: 
 *ModifiedTime: 
***********************************/

Create PROCEDURE [dbo].[Gp_OM_SaveBackOrder]
(
@Id int,
@SerialNo varchar(50)
,@Quantity  NUMERIC(24, 10) 
,@Discount  NUMERIC(24, 10) 
,@TotalMoney  NUMERIC(24, 10) 
,@Comment nvarchar(200)
,@Status tinyint
,@BtypeId varchar(50)
,@BtypeName nvarchar(200)
,@CreatorId int
,@CreatorName  nvarchar(200)
,@CreatedTime datetime
,@ModifierId int
,@ModifierName nvarchar(200)
,@ModifiedTime DATETIME
,@OrderIndexId INT 
)
--@encode$--
AS 
SET NOCOUNT ON

IF @Id=0
BEGIN
	INSERT INTO [dbo].[OM_BackOrder]
           ([SerialNo]
           ,[Quantity]
           ,[Discount]
           ,[TotalMoney]
           ,[Comment]
           ,[Status]
           ,[BtypeId]
           ,[BtypeName]
           ,[CreatorId]
           ,[CreatorName]
           ,[CreatedTime]
           ,[ModifierId]
           ,[ModifierName]
           ,[ModifiedTime]
           ,OrderIndexId
            )
	VALUES  
	( 
           @SerialNo
           ,@Quantity
           ,@Discount
           ,@TotalMoney
           ,@Comment
           ,@Status
           ,@BtypeId
           ,@BtypeName
           ,@CreatorId
           ,@CreatorName
           ,@CreatedTime
           ,@ModifierId
           ,@ModifierName
           ,@ModifiedTime
           ,@OrderIndexId
	)
	RETURN @@IDENTITY
END
ELSE
BEGIN
	UPDATE dbo.OM_BackOrder
	SET TotalMoney=@TotalMoney,
		Quantity=@Quantity,
		Comment=@Comment
	WHERE id=@id
	RETURN 0
END
GO





/****** Object:  StoredProcedure [dbo].[Gp_OM_SaveBackOrderDetail]    Script Date: 11/11/2014 14:04:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_SaveBackOrderDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_SaveBackOrderDetail]
GO



/****** Object:  StoredProcedure [dbo].[Gp_OM_SaveBackOrderDetail]    Script Date: 11/11/2014 14:04:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/***********************************  
 *任我行通用事业部 过账组 
 *Title: 保存订单明细
 *CreatorName: 杨川
 *CreatedTime: 2014-07-08
 *ModifierName: 
 *ModifiedTime: 
***********************************/

create  PROCEDURE [dbo].[Gp_OM_SaveBackOrderDetail]
(
	@details TBType_OMBackBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @pfullname VARCHAR(50)
SET @pfullname=''

;WITH t AS(
SELECT a.ptypeid, a.qty,(b.ConfirmQty-ISNULL((SELECT SUM(ReachQty-StopQty) FROM dbo.OM_BackOrderDetail WHERE OrderId=a.orderid),0)) AS recqty 
	FROM @details a
	INNER JOIN dbo.OM_OrderDetail b ON a.OrderId=b.ID
)
SELECT @pfullname=@pfullname+fullname+',' FROM dbo.ptype p INNER JOIN t ON t.ptypeid=p.typeId
	WHERE qty>recqty
IF(@pfullname <>'')
BEGIN
	 SET @pfullname=SUBSTRING(@pfullname,1,LEN(@pfullname)-1)
	  DECLARE @msg VARCHAR(2000)
	  SELECT @msg='商品【'+@pfullname+'】退货数量超出了已收货数量！'
	 RAISERROR(@msg,16,1)
	 RETURN;
END

INSERT INTO dbo.OM_BackOrderDetail
( 
		billNumberID ,
		ptypeid ,
		qty ,
		price ,
		total ,
		Discount ,
		DiscountPrice ,
		SaleTotal ,
		UnitID ,
		ItemID ,
		IsCombined ,
		comment,
		OrderIndexId,
		OrderID
)
SELECT 	BillnumberID ,
		ptypeid ,
		Qty ,
		Price ,
		Total,
		DisCount ,
		DiscountPrice ,
		SaleTotal,
		UnitID ,
		ItemID,
		IsCombined,
		Comment ,
		OrderIndexId,
		OrderID
FROM @details


if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)

GO






/****** Object:  StoredProcedure [dbo].[Gp_OM_SaveInventory]    Script Date: 08/22/2014 11:33:25 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_OM_SaveInventory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_OM_SaveInventory]
GO


/****** Object:  StoredProcedure [dbo].[Gp_OM_SaveInventory]    Script Date: 08/22/2014 11:33:16 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/***********************************  
 *任我行通用事业部 过账组 
 
 *Title: 保存存货信息
 *CreatorName: 杨川
 *CreatedTime: 2014-07-28
 *ModifierName: 
 *ModifiedTime: 
***********************************/

CREATE PROCEDURE [dbo].[Gp_OM_SaveInventory]
(
	@inventoryid					INT,	
	@Flag							INT,
	@OMPtypes Type_OMPtypes			Readonly	    
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	BEGIN TRANSACTION
		DECLARE @errorSum	INT=0
	    IF @Flag=1
			BEGIN
				-------------删除以往数据 
				DELETE FROM dbo.OM_Inventory_Ext WHERE InventoryID=@inventoryid
				Set @errorSum=@errorSum+@@error	
				
				------------插入数据
				INSERT INTO OM_Inventory_Ext
					(
						 InventoryID,
						 Ptypeid,
						 [Status]
					)
				SELECT  InventoryID,
						 Ptypeid,
						 ISNULL([Status],'')
				FROM @OMPtypes
				SET @errorSum=@errorSum+@@error
			END
		ELSE 
			BEGIN
					--先修改
					UPDATE oe SET oe.[Status]=o.[Status]
					FROM OM_Inventory_Ext oe 
					JOIN @OMPtypes o ON oe.InventoryID=o.InventoryID AND oe.Ptypeid=o.Ptypeid
					SET @errorSum=@errorSum+@@error
					
					--后插入,防止批量修改的数据没有
					INSERT INTO OM_Inventory_Ext
					(
						 InventoryID,
						 Ptypeid,
						 [Status]
					)
					SELECT   o.InventoryID,
							 o.Ptypeid,
							 ISNULL(o.[Status],'')
					FROM  @OMPtypes o  
					LEFT JOIN OM_Inventory_Ext oe 
					 ON oe.InventoryID=o.InventoryID AND oe.Ptypeid=o.Ptypeid
					WHERE oe.InventoryID IS NULL
				 
				SET @errorSum=@errorSum+@@error
			END
		

	 
	IF @errorSum<>0  --如果有错误
		BEGIN
			ROLLBACK TRANSACTION 
			RETURN 0
		END
	ELSE
		BEGIN
			COMMIT TRANSACTION
			RETURN 1
		END
END
SET NOCOUNT OFF

GO







GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_SaveOrder]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_SaveOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_SaveOrder]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***********************************  
 *任我行通用事业部 过账组 
 *Title: 保存订单
 *CreatorName: 杨川
 *CreatedTime: 2014-07-07
 *ModifierName: 
 *ModifiedTime: 
***********************************/

Create PROCEDURE [dbo].[Gp_OM_SaveOrder]
(
@Id int,
@SerialNo varchar(50)
,@Quantity  NUMERIC(24, 10) 
,@Discount  NUMERIC(24, 10) 
,@TotalMoney  NUMERIC(24, 10) 
,@Comment nvarchar(200)
,@Status tinyint
,@BtypeId varchar(50)
,@BtypeName nvarchar(200)
,@CreatorId int
,@CreatorName  nvarchar(200)
,@CreatedTime datetime
,@ModifierId int
,@ModifierName nvarchar(200)
,@ModifiedTime DATETIME
,@PreferenceMoney  NUMERIC(24, 10) 
,@customerkey INT
,@bid INT 
)
--@Encode$--
AS 
SET NOCOUNT ON
DECLARE @tempbtypeid VARCHAR(50)
SELECT @tempbtypeid=typeid FROM dbo.btype WHERE Bid=@customerkey
IF ISNULL(@tempbtypeid,'')<>''
BEGIN
	SET @btypeid=@tempbtypeid
END
IF @Id=0
BEGIN
	INSERT INTO [dbo].[OM_Order]
           ([SerialNo]
           ,[Quantity]
           ,[Discount]
           ,[TotalMoney]
           ,[Comment]
           ,[Status]
           ,[BtypeId]
           ,[BtypeName]
           ,[CreatorId]
           ,[CreatorName]
           ,[CreatedTime]
           ,[ModifierId]
           ,[ModifierName]
           ,[ModifiedTime]
           ,PreferenceMoney
           ,bid
           )
	VALUES  
	( 
           @SerialNo
           ,@Quantity
           ,@Discount
           ,@TotalMoney
           ,@Comment
           ,@Status
           ,@BtypeId
           ,@BtypeName
           ,@CreatorId
           ,@CreatorName
           ,@CreatedTime
           ,@ModifierId
           ,@ModifierName
           ,@ModifiedTime
           ,@PreferenceMoney
           ,@bid
	)
	RETURN @@IDENTITY
END
ELSE
BEGIN
	UPDATE dbo.OM_Order
	SET TotalMoney=@TotalMoney,
		Quantity=@Quantity,
		Comment=@Comment
	WHERE id=@id
	RETURN 0
END
GO





GO
/****** Object:  StoredProcedure [dbo].[Gp_OM_SaveOrderDetail]    Script Date: 07/29/2014 18:11:52 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_SaveOrderDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_SaveOrderDetail]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***********************************  
 *任我行通用事业部 过账组 
 *Title: 保存订单明细
 *CreatorName: 杨川
 *CreatedTime: 2014-07-08
 *ModifierName: 
 *ModifiedTime: 
***********************************/

create  PROCEDURE [dbo].[Gp_OM_SaveOrderDetail]
(
	@details TBType_OMBill READONLY
)
--@Encode$--
AS 
SET NOCOUNT ON


INSERT INTO dbo.OM_OrderDetail
( 
		billNumberID ,
		ptypeid ,
		qty ,
		price ,
		total ,
		Discount ,
		DiscountPrice ,
		SaleTotal ,
		UnitID ,
		ItemID ,
		IsCombined ,
		comment,
		IsGift,
		Pid,
		taxprice,
		Tax
)
SELECT 	BillnumberID ,
		p.typeid ,
		d.Qty ,
		d.Price ,
		d.Total,
		d.DisCount ,
		d.DiscountPrice ,
		d.SaleTotal,
		d.UnitID ,
		d.ItemID,
		d.IsCombined,
		d.Comment,
		d.IsGift,
		d.pid,
		d.taxprice,
		d.tax
FROM @details d
INNER JOIN ptype p ON d.productkey=p.Pid

DECLARE @bid INT 
SET @bid=(SELECT TOP 1 bid FROM @details)

--修改购物车数据
UPDATE dbo.OM_ShoppingCart SET Quantity=s.Quantity-d.qty
FROM dbo.OM_ShoppingCart s
INNER JOIN @details d ON s.pid=d.pid AND s.bid=d.bid

DELETE FROM dbo.OM_ShoppingCart WHERE bid=@bid AND Quantity=0



DECLARE @msg VARCHAR(max)
SET @msg='插入单据发生错误！'+ERROR_MESSAGE()
if @@rowcount=0 or @@Error<>0
 RAISERROR(@msg,16,1)
GO





GO
/****** Object:  StoredProcedure [dbo].[Web_OMStypeSelectorQuery]    Script Date: 08/07/2014 09:35:35 ******/

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_OM_SelectInventory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

DROP PROCEDURE [dbo].[Gp_OM_SelectInventory]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/***********************************  
 *任我行通用事业部 过账组 
 *Title: 存货录入信息选择
 *CreatorName: 杨川
 *CreatedTime: 2014-08-07
 *ModifierName: 
 *ModifiedTime: 
***********************************/

create PROCEDURE [dbo].[Gp_OM_SelectInventory]
(
       @Query		   VARCHAR(100)  ---查询参数
)
--@encode$--
AS 
SET NOCOUNT ON
-------- 
IF(@Query!='')--不为空则进行过滤查询
  BEGIN
	SET @Query='%'+@Query+'%'
	SELECT ID AS InventoryID,FullName,UserCode FROM dbo.OM_Inventory WHERE UserCode LIKE @Query OR FullName LIKE @Query ORDER BY UserCode
  END
   
ELSE
BEGIN
   SELECT id AS InventoryID,FullName,UserCode FROM dbo.OM_Inventory ORDER BY UserCode
END


SET QUOTED_IDENTIFIER ON 




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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



/******
程序编写 吴德水
编写时间 2003-08-27
脚本功能 添加、修改相应单据的发票
参    数 注释见参数后的尾注释
************************************************************************************************/
CREATE                    PROCEDURE GP_OperateInvoice(
	@BillNumberID	numeric(10, 0),		--对应的单据编号
	@IfInVoice	char(1),		--是否开票
	@ETypeID	varchar(50),		--经手人编号
	@InvoiceStyle	char(1),		--发票类别 1、普通发票 2、增值税票
	@InvoiceNo	varchar(50),		--发票编号
	@InvoiceDate	datetime,		--开票日期
	@InvoiceTotal	 NUMERIC(24, 10) ,		--发票的金额
	@Explain	varchar(256),		--发票注释
	@isDraft	bit,			--草稿标记 0、过帐单据 1、草稿
	@opType		char(1) = '0'	-- 操作类型。0：开单、草稿中的对唯一发票进行新开、编辑；
								-- 1：原始单据、发票查询的新开发票，每次都是新开；
								-- 2：发票明细中的修改某一具体发票；
)
--@encode$--
AS

--处理类型:'ins'为添加，'edit'为修改
Declare @Type varchar(30)

-- 所有发票都置为过帐状态
SET @isDraft =0

IF @InvoiceDate = ''
	Set @invoiceDate = Null

IF @opType = '0'
BEGIN
	If Exists(Select BillNumberID From InvoiceBill Where BillNumberID = @BillNumberID)
		Set @Type = 'edit'
	Else
		Set @Type = 'ins'
END
ELSE IF @opType = '1'
	SET @Type = 'ins'

DECLARE @btypeid varchar(100)
DECLARE @EEtypeid varchar(100)
DECLARE @Ktypeid varchar(100)
DECLARE @Billtype int

SELECT @btypeid=BtypeID,@EEtypeid=EtypeID,@Ktypeid=KtypeID,@Billtype=Billtype FROM Billindex where BillnumberID =@BillNumberID
IF @Billtype =141 or @Billtype=145
BEGIN
	IF RTRIM(@BTypeID) <> ''
	BEGIN
	IF NOT EXISTS(SELECT * FROM Btype WHERE typeid<>'00001' AND typeID<>'00002' AND TypeID<>'00000' AND typeID=@btypeid )
		return -2
	END
	IF RTRIM(@EETypeID) <> '00001'
	BEGIN
	IF NOT EXISTS(SELECT * FROM Employee WHERE typeid<>'00001' AND typeID<>'00000'  AND typeID=@EEtypeid )
		return -3
	END
END
ELSE
BEGIN
	IF RTRIM(@BTypeID) <> ''
	BEGIN
	IF NOT EXISTS(SELECT * FROM Btype WHERE typeid<>'00001' AND typeID<>'00002' AND TypeID<>'00000' AND typeID=@btypeid )
		return -2
	END
	IF RTRIM(@EETypeID) <> '00001'
	BEGIN
	IF NOT EXISTS(SELECT * FROM Employee WHERE typeid<>'00001' AND typeID<>'00000'  AND typeID=@EEtypeid )
		return -3
	END
	IF RTRIM(@KTypeID) <> '00000'
	BEGIN
	IF NOT EXISTS(SELECT * FROM Stock WHERE  TypeID<>'00000' AND typeID=@Ktypeid )
		RETURN -4
	END
END

If @Type = 'ins'
BEGIN
	IF @ETypeID =''
	BEGIN
		IF EXISTS (SELECT etypeid FROM Billindex WHERE BillnumberID = @BillNumberID)
			SELECT @ETypeID=etypeid FROM Billindex WHERE BillnumberID = @BillNumberID			
	END
	IF EXISTS(SELECT TOP 1 1 FROM InvoiceBill WHERE BillNumberID = @BillNumberID AND InvoiceNo = @InvoiceNo)
		RETURN -5

	Insert Into invoicebill (
		BillNumberID,
		IfInVoice,
		ETypeID,
		InvoiceStyle,
		InvoiceTotal,
		Explain,
		InvoiceDate,
		InvoiceNo,
		isDraft
		)
	values(
		@BillNumberID,
		@IfInVoice,
		@ETypeID,
		@InvoiceStyle,
		@InvoiceTotal,
		@Explain,
		@InvoiceDate,
		@InvoiceNo,
		@isDraft
	)
END
ELSE IF @type = 'edit'
BEGIN
	IF @ETypeID =''
	BEGIN
		IF EXISTS (SELECT etypeid FROM Billindex WHERE BillnumberID = @BillNumberID)
			SELECT @ETypeID=etypeid FROM Billindex WHERE BillnumberID = @BillNumberID			
	END

	Update invoiceBill
	Set	IfInVoice	= @IfInVoice,
		ETypeID		= @ETypeID,
		InvoiceStyle	= @InvoiceStyle,
		InvoiceTotal	= @InvoiceTotal,
		Explain		= @Explain,
		InvoiceDate	= @InvoiceDate,
		InvoiceNo	= @InvoiceNo,
		isDraft		= @isDraft
	Where BillNumberId = @BillNumberID
END

If @@rowcount = 1
	return 0
else
	return -1



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






/*
*		订单自动生成预/收付款单草稿
*/

GO
IF EXISTS (SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_OrderBill_CreateBill',N'P') AND Name='GP_OrderBill_CreateBill')
BEGIN
	DROP PROC GP_OrderBill_CreateBill
END
GO

CREATE PROC GP_OrderBill_CreateBill
(
	@nBillID				NUMERIC(10,0),			-- 单据 ID 号
	@intReturnID			NUMERIC(10,0) OUT,		-- 新生成的单据的ID
	@strReturnBillCode		VARCHAR(200) OUT,			--新生成的单据类型
	@OperatorID				VARCHAR(100)=''			--操作员ID
)
AS
BEGIN
	DECLARE 
			@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
			@intReturnFlowID			INT, 			 --返回新生成的流水号
			@strSTypeID					VARCHAR(50),
			@strDTypeID					VARCHAR(50),
			@strETypeID					VARCHAR(50),
			@intFromBillNumberID		INT,
			@intFromBillType			INT,
			@BillCodeConfig				VARCHAR(100),
			@MONTH						VARCHAR(200),
			@DAY						VARCHAR(200),
			@ETypeID					VARCHAR(100),
			@KTypeID					VARCHAR(100),
			@VchHead					VARCHAR(100),
			@Re							INT,
			@intBillType				INT,
			@datBillDate				DATETIME,
			@strFromBillcode			VARCHAR(100),
			@strBTypeID					VARCHAR(100),
			@strComment					VARCHAR(1000),
			@strATypeID					VARCHAR(50),			--定金账户
			@numTotal					NUMERIC(24,10),			--生成表体金额		
			@numNTotal					NUMERIC(24,10),			
			@strATypeID1				VARCHAR(50),			--生成单据往来科目
			@intATID					INT,					--凭证模版
			@HasLIMIT					BIT,						--是否有相应单据权限
			@oldBillType				INT,
			@CHECKID					VARCHAR(50),
			@cefullname					VARCHAR(500)='',		--制单人
			@cdfullname					VARCHAR(500)=''			--部门
	
	--已生成
	IF EXISTS(SELECT 1 FROM dbo.PreBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0 WHERE RelevanceBillId=@nBillID 
		UNION ALL
			 SELECT 1 FROM dbo.PayBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0 WHERE RelevanceBillId=@nBillID
		UNION ALL
			 SELECT 1 FROM dbo.gatheringBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId AND B.RedWord=0 WHERE RelevanceBillId=@nBillID
	   )
		RETURN -1
				
    SELECT  @strSTypeID = Stypeid ,
            @strDTypeID = DTypeID ,
            @strETypeID = ETypeID ,
            @intFromBillNumberID = BillNumberID ,
            @intFromBillType = BillType ,
            @datBillDate = CONVERT(VARCHAR, GETDATE(), 111 ) ,
            @strBTypeID = BTypeID ,
            @strFromBillCode = BillCode,
            @strATypeID=ATypeID,
            @numNTotal=NCustomerTotal-TotalInMoney,
            @numTotal=CustomerTotal-NTotalInMoney,
            @oldBillType=billtype,
            @CHECKID=checke
    FROM    dbo.OrderIndex WITH(NOLOCK)
    WHERE   BillNumberID = @nBillID
	
	--单据类型、编号头、描述
	IF @intFromBillType=300
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='allowautocreatsale' AND Value=1)
			RETURN -2
		IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='allowautocreatsaleitem' AND Value=1)
		BEGIN
			SET @intBillType=189
			SET @VchHead='YSK'
			SET @strComment='该预收款单是从销售订单'+@strFromBillcode+'生成而来'
			IF @oldBillType=313
			BEGIN
				SET @strComment='该预收款单是从组合品销售订单'+@strFromBillcode+'生成而来'
			END
			IF @OperatorID<>''
			BEGIN
				EXEC @HasLIMIT=GP_CheckLimit @OperatorID,725
				IF @HasLIMIT=1
				BEGIN
					SET @strReturnBillCode=N'因没有预收款单录入权限，无法自动生单！'
					RETURN
				END
			END
		END
		ELSE 
		BEGIN
			SET @intBillType=4
			SET @VchHead='XS'
			SET @strComment='该收款单是从销售订单'+@strFromBillcode+'生成而来'
			IF @oldBillType=313
			BEGIN
				SET @strComment='该收款单是从组合品销售订单'+@strFromBillcode+'生成而来'
			END
			IF @OperatorID<>''
			BEGIN
				EXEC @HasLIMIT=GP_CheckLimit @OperatorID,53
				IF @HasLIMIT=1
				BEGIN
					SET @strReturnBillCode=N'因没有收款单录入权限，无法自动生单！'
					RETURN
				END
			END
		END
	END
	ELSE IF @intFromBillType=313
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='allowautocreatcombin' AND Value=1)
			RETURN -2
		IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='allowautocreatcombinitem' AND Value=1)
		BEGIN
			SET @intBillType=189
			SET @VchHead='YSK'
			SET @strComment='该预收款单是从组合品销售订单'+@strFromBillcode+'生成而来'
			IF @oldBillType=313
			BEGIN
				SET @strComment='该预收款单是从组合品销售订单'+@strFromBillcode+'生成而来'
			END
			IF @OperatorID<>''
			BEGIN
				EXEC @HasLIMIT=GP_CheckLimit @OperatorID,725
				IF @HasLIMIT=1
				BEGIN
					SET @strReturnBillCode=N'因没有预收款单录入权限，无法自动生单！'
					RETURN
				END
			END
		END
		ELSE 
		BEGIN
			SET @intBillType=4
			SET @VchHead='XS'
			SET @strComment='该收款单是从组合品销售订单'+@strFromBillcode+'生成而来'
			IF @oldBillType=313
			BEGIN
				SET @strComment='该收款单是从组合品销售订单'+@strFromBillcode+'生成而来'
			END
			IF @OperatorID<>''
			BEGIN
				EXEC @HasLIMIT=GP_CheckLimit @OperatorID,53
				IF @HasLIMIT=1
				BEGIN
					SET @strReturnBillCode=N'因没有收款单录入权限，无法自动生单！'
					RETURN
				END
			END
		END
	END      
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='allowautocreatbuy' AND Value=1)
			RETURN -2
		
		IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='allowautocreatbuyitem' AND Value=1)
		BEGIN
			SET @intBillType=190
			SET @VchHead='YFK'
			SET @strComment='该预付款单是从采购订单'+@strFromBillcode+'生成而来'
			IF @OperatorID<>''
			BEGIN
				EXEC @HasLIMIT=GP_CheckLimit @OperatorID,728
				IF @HasLIMIT=1
				BEGIN
					SET @strReturnBillCode=N'因没有预付款单录入权限，无法自动生单！'
					RETURN
				END
			END
		END
		ELSE
		BEGIN
			SET @intBillType=66
			SET @VchHead='JF'
			SET @strComment='该付款单是从采购订单'+@strFromBillcode+'生成而来'
		
			IF @OperatorID<>''
			BEGIN
				EXEC @HasLIMIT=GP_CheckLimit @OperatorID,64
				IF @HasLIMIT=1
				BEGIN
					SET @strReturnBillCode=N'因没有付款单录入权限，无法自动生单！'
					RETURN
				END
			END
		END
	END
	
	SELECT @intATID=AtId FROM Ac_Auditing_Template WHERE BillType=@intBillType and StypeId=@strSTypeID
	SELECT @strATypeID1=ATypeID FROM BillAtype	WHERE BillTypeId=CAST(@intBillType AS VARCHAR(50)) AND StypeId=@strSTypeID
	SELECT @ETypeID=@strETypeID,@KTypeID=''
	
	--种子配置
	SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
	BEGIN
		SELECT @MONTH = TypeId FROM Employee WHERE TypeID = @ETypeID
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @OperatorID
		SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @strDTypeID
	END
	ELSE
	BEGIN
		SET  @MONTH=ISNULL(@MONTH,'')
		SET  @DAY=ISNULL(@DAY,'')
	END
	
	--生成编号
		EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname
	IF @Re <> 0  RETURN -3	
	
	DECLARE @usebrandartype INT=0
	
	IF EXISTS (SELECT  TOP 1 1 FROM sysdata  WHERE subname='usebrandartype' AND SubValue ='1')
		SELECT  @usebrandartype=1
	--插入主表
    INSERT  INTO dbo.BillIndex
            ( BillDate ,
              BillCode ,
              BillType ,
              STypeID ,
              ETypeID ,
              ATypeID ,
              KTypeID ,
              KTypeID2 ,
              Comment ,
              totalmoney ,
              totalqty ,
              tax ,
              period ,
              explain ,
              waybillcode ,
              goodsnumber ,
              packway ,
              TEL ,
              AlertDay ,
              DTypeId ,
              CostSale ,
              FromBillNumberID ,
              ifcheck ,
              IfAudit ,
              draft ,
              OrderId ,
              checke ,
              btypeid ,
              NTotalMoney ,
              CID ,
              Rate ,
              AdPriceType ,
              DealBTypeID ,
              checkTime,
              posttime,
              ATypeID1,
              ATID,  
              totalinmoney,
              NTotalInMoney,
              isByBrandarType
            )
            SELECT  @datBillDate ,
                    @strBillCode ,
                    @intBillType ,
                    @strSTypeID ,
                    ETypeID ,
                    '' ,
                    '' ,
                    '' ,
                    @strComment ,
                    CustomerTotal-ISNULL(totalinmoney,0) ,
                    0 ,
                    tax ,
                    Period ,
                    explain ,
                    '' ,
                    '' ,
                    '' ,
                    '' ,
                    '' ,
                    DTypeID ,
                    0 ,
                    @nBillID,
                    'f' ,
                    0 ,
                    1 ,
                    0 ,
                    checke ,
                    BTypeID ,
                    NCustomerTotal-ISNULL(ntotalinmoney,0) ,
                    CID ,
                    Rate ,
                    0 ,--凭证模板选择要用 dbo.Ac_Auditing_Template 的 ISNULL(InOutType,0) 对应 billindex AdPriceType   所以要为0 才对
                    DealBTypeID ,
                    GETDATE() ,
                    NULL ,
                    @strATypeID1 ,
                    @intATID,
					CASE WHEN @intBillType IN(189,190) THEN 0 ELSE CustomerTotal END,
                    CASE WHEN @intBillType IN(189,190) THEN 0 ELSE NCustomerTotal END,
                    CASE WHEN @intBillType =4 AND @usebrandartype=1 THEN 1 ELSE 0 END --收款单 启用品牌 自动勾选上 按品牌收款
            FROM    dbo.OrderIndex
            WHERE   billNumberId = @nBillID
            
    SELECT @intReturnID=SCOPE_IDENTITY()
    
    --生成表体
    IF @intBillType IN(189,190)
    BEGIN
		IF @intBillType=190
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.BillMulAccount WHERE BillNumberId = @nBillID AND BillType =@intFromBillType)
			BEGIN
				INSERT INTO dbo.PreBill
						( BillNumberId ,
						  BillType ,
						  Comment ,
						  AtypeId ,
						  total ,
						  TeamNo ,
						  TeamNO1 ,
						  Stypeid ,
						  ntotal ,
						  vipcardid,
						  RelevanceBillId
						)
				SELECT  @intReturnID,
						@intBillType,
						@strComment,
						ATypeID,
						Total,
						NULL,
						NULL,
						@strSTypeID,
						NTotalMoney,
						VipCardID,
						@nBillID
				FROM	BillMulAccount
				WHERE	BillNumberId= @nBillID
						AND  BillType=@intFromBillType
			END
			ELSE
			BEGIN
				INSERT INTO dbo.PreBill
						( BillNumberId ,
						  BillType ,
						  Comment ,
						  AtypeId ,
						  total ,
						  TeamNo ,
						  TeamNO1 ,
						  Stypeid ,
						  ntotal ,
						  --vipcardid,
						  RelevanceBillId
						)
				SELECT  @intReturnID,
						@intBillType,
						@strComment,
						ATypeID,
						CustomerTotal,
						NULL,
						NULL,
						@strSTypeID,
						NCustomerTotal,
						--VipCardID,
						@nBillID
				FROM	dbo.OrderIndex
				WHERE	BillNumberId= @nBillID
						AND  BillType=@intFromBillType			
			END						
					
			UPDATE dbo.PreBill SET ShowOrder=ID WHERE BillNumberId=@intReturnID AND BillType=@intBillType
	    END 
	    ELSE  --189	预收款单 多账户明细汇总为表体
	    BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.BillMulAccount WHERE BillNumberId = @nBillID AND BillType =@intFromBillType)
			BEGIN
				INSERT INTO dbo.PreBill
						( BillNumberId ,
						  BillType ,
						  Comment ,
						  AtypeId ,
						  total ,
						  TeamNo ,
						  TeamNO1 ,
						  Stypeid ,
						  ntotal ,
						  vipcardid,
						  RelevanceBillId
						)	
				SELECT  @intReturnID,
						@intBillType,
						@strComment,
						ATypeID,
						Total,
						NULL,
						NULL,
						@strSTypeID,
						NTotalMoney,
						VipCardID,
						@nBillID
				FROM	BillMulAccount
				WHERE	BillNumberId= @nBillID
						AND  BillType=@intFromBillType
			END
			ELSE
			BEGIN
				INSERT INTO dbo.PreBill
						( BillNumberId ,
						  BillType ,
						  Comment ,
						  AtypeId ,
						  total ,
						  TeamNo ,
						  TeamNO1 ,
						  Stypeid ,
						  ntotal ,
						  vipcardid,
						  RelevanceBillId
						)	
				SELECT  @intReturnID,
						@intBillType,
						@strComment,
						ATypeID,
						CustomerTotal,
						NULL,
						NULL,
						@strSTypeID,
						NCustomerTotal,
						VipCardID,
						@nBillID
				FROM	dbo.OrderIndex
				WHERE	BillNumberId= @nBillID
						AND  BillType=@intFromBillType			
			END
			
		 UPDATE dbo.PreBill SET ShowOrder=ID WHERE BillNumberId=@intReturnID AND BillType=@intBillType
	    END 
    END
	ELSE
	BEGIN
		IF @intBillType=4 --4	收款单多账户明细汇总为表体
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.BillMulAccount WHERE BillNumberId = @nBillID AND BillType =@intFromBillType)
			BEGIN
				INSERT INTO dbo.gatheringBill
						( BillNumberId ,
						  AtypeId ,
						  total ,
						  Comment ,
						  TeamNo ,
						  TeamNO1 ,
						  Stypeid ,
						  ntotal ,
						  VipCardID,
						  RelevanceBillId
						)
				SELECT  @intReturnID,
						ATypeID,
						Total,
						@strComment,
						NULL,
						NULL,
						@strSTypeID,
						NTotalMoney,
						VipCardID,
						@nBillID
				FROM	BillMulAccount
				WHERE	BillNumberId= @nBillID
						AND  BillType=@intFromBillType
			END
			ELSE
			BEGIN
				INSERT INTO dbo.gatheringBill
						( BillNumberId ,
						  AtypeId ,
						  total ,
						  Comment ,
						  TeamNo ,
						  TeamNO1 ,
						  Stypeid ,
						  ntotal ,
						 -- VipCardID,
						  RelevanceBillId
						)
				SELECT  @intReturnID,
						ATypeID,
						CustomerTotal,
						@strComment,
						NULL,
						NULL,
						@strSTypeID,
						NCustomerTotal,
						--VipCardID,
						@nBillID
				FROM	dbo.OrderIndex
				WHERE	BillNumberId= @nBillID
						AND  BillType=@intFromBillType			
			END				
			
			UPDATE dbo.gatheringBill SET ShowOrder=ID WHERE BillNumberId=@intReturnID 
		END
		ELSE
		BEGIN
			--多账户生成
			IF EXISTS(SELECT TOP 1 1 FROM dbo.BillMulAccount WHERE BillNumberId = @nBillID AND BillType =@intFromBillType)
			BEGIN
				INSERT INTO dbo.PayBill
						( BillNumberId ,
						  AtypeId ,
						  total ,
						  Comment ,
						  TeamNo ,
						  TeamNO1 ,
						  Stypeid ,
						  ntotal ,
						  VipCardID,
						  RelevanceBillId
						)
				SELECT  @intReturnID,
						ATypeID,
						Total,
						@strComment,
						NULL,
						NULL,
						@strSTypeID,
						NTotalMoney,
						VipCardID,
						@nBillID
				FROM	BillMulAccount
				WHERE	BillNumberId= @nBillID
						AND  BillType=@intFromBillType
			END
			ELSE
			BEGIN
				INSERT INTO dbo.PayBill
						( BillNumberId ,
						  AtypeId ,
						  total ,
						  Comment ,
						  TeamNo ,
						  TeamNO1 ,
						  Stypeid ,
						  ntotal ,
						  --VipCardID,
						  RelevanceBillId
						)
				SELECT  @intReturnID,
						ATypeID,
						CustomerTotal,
						@strComment,
						NULL,
						NULL,
						@strSTypeID,
						NCustomerTotal,
						--VipCardID,
						@nBillID
				FROM	OrderIndex
				WHERE	BillNumberId= @nBillID
						AND  BillType=@intFromBillType			
			END
					
			UPDATE dbo.PayBill SET ShowOrder=ID WHERE BillNumberId=@intReturnID
		END

		
	END
	
	IF EXISTS(SELECT ConfigNo FROM Userconfig WHERE ConfigName='BillcodeCreateTime' AND Value=0)
	BEGIN
		EXEC GP_SaveBillCode_Seed
			@intReturnID,
			@datBillDate,
			@intBillType,
			@strBillCode
	END
	
	SET @strReturnBillCode=@strBillCode
	
	DECLARE @paygathLimit INT=0,
			@limit_pass INT = 0
	
	--先判断是否有总的过账权限
	EXEC @limit_pass = GP_CheckLimit @OperatorID,119
	
	IF  @limit_pass  = 0
	BEGIN
		IF @intBillType=190
			EXEC @paygathLimit=	GP_CheckLimit @OperatorID ,729 --预付
		ELSE IF @intBillType=189
			EXEC @paygathLimit=	GP_CheckLimit @OperatorID  ,726--预收
		ELSE IF @intBillType=66
			EXEC @paygathLimit=	GP_CheckLimit @OperatorID, 175 --付款单
		ELSE IF @intBillType=4
			EXEC @paygathLimit=	GP_CheckLimit @OperatorID ,170 	--收款单 过账权限
		ELSE
			SET @paygathLimit=0
			
		--收付款过账权限

		
		DECLARE @szPID					varchar(1000) ,		-- 返回出错商品 ID 值
				@KTypeIDs				varchar(50) = '' ,	-- 返回仓库ID值，针对多仓库应用
				@voucherMsg				VARCHAR(50) = '' ,	--返回凭证生成信息
				@VipCentInfo			VARCHAR(200) = '' ,				--返回会员卡积分调整信息
				@AssetMsg				VARCHAR(MAX)='' ,
				@VipCardCode			VARCHAR(200)='' ,
				@strReturnPayBillCode		VARCHAR(200)=''
				--@nret  int
		
		
		
		--自动过账
		IF ISNULL(@strBillCode,0)<>''
		BEGIN
			--预收、付款单 收付款单 审核流程，不执行;没有 预收、付款单 收付款单过账权限 不执行
			IF NOT EXISTS (SELECT AuditingID FROM AuditingFlowSet WHERE BillType=@intBillType AND stypeid=@strSTypeID AND IfUse = 1 AND LEFT(AuditingReason, 1) <> 1)
				AND(    (@oldBillType=300 AND EXISTS(SELECT ConfigNo FROM Userconfig WHERE ConfigName='saleorderbilltopreorgathbill_pass' AND Value=1))
						OR (@oldBillType=313 AND EXISTS(SELECT ConfigNo FROM Userconfig WHERE ConfigName='ptcombinorderbilltopreorgathbill_pass' AND Value=1))
						OR (@oldBillType=301 AND EXISTS(SELECT ConfigNo FROM Userconfig WHERE ConfigName='buyorderbilltopreorgathbill_pass' AND Value=1))
					)
				AND @paygathLimit=0
			BEGIN
				EXEC Gp_Auditing
								@intReturnID,
								@CHECKID,
								@szPID output,
								@OperatorID,
								@KTypeIDs output,
								@intBillType,
								@voucherMsg OUTPUT,
								@VipCentInfo OUTPUT,
								@AssetMsg OUTPUT,
								@VipCardCode OUTPUT,
								1,
								@strReturnPayBillCode OUT
			END		
		END
	END
END

GO

/*

	DECLARE
		@nBillID				NUMERIC(10,0),			-- 单据 ID 号
		@intReturnID			NUMERIC(10,0),		-- 新生成的单据的ID
		@strReturnBillCode		VARCHAR(200),
		@OperatorID				VARCHAR(100)			--操作员ID
		
	
	BEGIN TRAN
	
	SELECT
		@nBillID=4,
		@OperatorID='00001'
		
	EXEC	GP_OrderBill_CreateBill
			@nBillID,
			@intReturnID OUT,
			@strReturnBillCode OUT,
			@OperatorID
		
	SELECT @intReturnID,@strReturnBillCode
	
	ROLLBACK TRAN
		

*/



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_OtherInOutBillOperationCheck]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_OtherInOutBillOperationCheck]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：李海洋
	日期：2012-09-27
	描述：业务类别检测
	
	-- 9.4 2014-05-29 周华 修改类型,修改了验证方式
	
-------------------------------------------*/
CREATE PROCEDURE GP_OtherInOutBillOperationCheck
    (
      @BillType INT ,  ---单据类型
      @stypeid VARCHAR(100) ,
      @OperatorId VARCHAR(100),
      @othertypeid INT
    )
--@encode$--
AS 
    SET NOCOUNT ON

    CREATE TABLE #Ac_Items ( TypeID VARCHAR(50) )

    IF @BillType = 201
        BEGIN
            INSERT  INTO #Ac_Items
                    ( TypeId
                    )
                    SELECT  F.nid
                    FROM    F_GetManDetailATypeSr(@OperatorId) F
                            INNER JOIN Ac_Items_Detail I ON I.nId = F.nid
                    WHERE   I.STypeId = @stypeid
                    UNION
                    SELECT  a.nId
                    FROM    Ac_Items A
                            INNER JOIN Ac_Items_Detail I ON I.nId = A.nId
                    WHERE   A.nParId <> '0000300003'
                            AND I.STypeId = @stypeid
        END
    ELSE 
        BEGIN
            INSERT  INTO #Ac_Items
                    ( TypeId
                    )
                    SELECT  F.nid
                    FROM    F_GetManDetailATypeFy(@OperatorId) F
                            INNER JOIN Ac_Items_Detail I ON I.nId = F.nid
                    WHERE   I.STypeId = @stypeid
                    UNION
                    SELECT  a.nId
                    FROM    Ac_Items A
                            INNER JOIN Ac_Items_Detail I ON I.nId = A.nId
                    WHERE   A.nParId <> '0000400003'
                            AND I.STypeId = @stypeid
        END

    SELECT  o.id ,
            o.atypeid ,
            a.deleted
    FROM    OtherInOutType o
            INNER JOIN ac_items a ON a.nid = o.AtypeId AND o.InOutType=1 
				OR a.nid=o.ATypeID1 AND o.InOutType=0
				OR a.nId IN (o.ATypeID,o.ATypeID1) AND o.InOutType=2
            INNER JOIN #Ac_Items c ON c.typeid = o.AtypeId AND o.InOutType=1
				OR c.TypeID=o.ATypeID1 AND o.InOutType=0
				OR c.typeid IN (o.ATypeID,o.ATypeID1) AND o.InOutType=2
            
    WHERE   (o.BillType = @BillType AND o.InOutType<>2 OR o.InOutType=2)
			AND o.id = @othertypeid
			
    DROP TABLE #Ac_Items

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




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

SET	QUOTED_IDENTIFIER OFF 
GO
SET	ANSI_NULLS ON 
GO


/*

作者：冯波

按类批量修改其他科目

需要注意的是：对同价调拨单，变价调拨单，生产拆装单，因为出库的库存商品总值变了，所以要重算库存商品；
对于换货单，也需要这样检查
*/
CREATE   PROCEDURE Gp_OutBill_DealOtherAType 
(		
	@intBillType				INT,
	@strATypeID					VARCHAR(50),
	@strSTypeID					VARCHAR(50)
)

--@encode$--
AS

--要改ListTable,AType_Total,AType

--填入原值，现值  #ListTable
	DECLARE @sysID					INT
	

	SELECT @sysID = CID FROM Ac_Currency WHERE Sysrow = 1
	
	DECLARE
		@STOCKID	VARCHAR(50)
		
		
		SELECT @STOCKID = NID FROM Ac_Items WHERE UserCode='1241'
		
		
IF @intBillType=187
	AND EXISTS(
		SELECT BillNumberID
		FROM #AfterModifyBill
		WHERE BillType=187
		AND BillNumberID IN
		(
			SELECT BillNumberID 
			FROM BillIndex
			WHERE IfCheck='t' AND RedWord=0 AND BillType=187 AND CostSale=1
		)
	)
BEGIN
	
	CREATE TABLE #CostSTypeMoveBillList(BillNumberID BIGINT,BTypeID VARCHAR(50),STypeID VARCHAR(50),STypeID2 VARCHAR(50),
	ARMoney NUMERIC(24,10),NARMoney NUMERIC(24,10),CID INT)
	
	DECLARE
		@strTempCostSTypeMoveATypeID	VARCHAR(50),
		@InnerAR_ID						INT
		
	
	--这里需要先把BILLINDEX中的TOTALMONEY修改掉
	INSERT #CostSTypeMoveBillList(BillNumberID,BTypeID,STypeID,STypeID2,ARMoney,NARMoney,CID)
	SELECT DISTINCT a.BillNumberID,b.btypeid,b.Stypeid,b.Stypeid2,
	b.total,b.total,b.CID
	FROM #AfterModifyBill a
	INNER JOIN
	(
		SELECT a.BillNumberID,a.BTypeID,a.STypeID,
		(SELECT STypeID FROM STOCK WHERE TypeID=a.ktypeid2)  STypeID2,
		a.CID,b.Total
		FROM BillIndex a
		INNER JOIN 
		(
			SELECT BillNumberID,-total AS Total
			FROM ListTable
			WHERE AtypeID=@STOCKID
		) b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.ifcheck='t' AND a.RedWord=0 AND a.BillType=187 AND a.CostSale=1
	) b
	ON a.BillNumberID=b.BillNumberId
	WHERE a.BillType=187
	
	
	
	
	--SELECT '#CostSTypeMoveBillList',* FROM #CostSTypeMoveBillList
	--内部应收
	SELECT @InnerAR_ID=nId FROM Ac_Items WHERE UserCode='1132'  
	
	
	
	CREATE TABLE #CostSTypeMoveSumInfo(
		BTypeID						VARCHAR(50),
		STypeID						VARCHAR(50),
		STypeID2					VARCHAR(50),
		CID							INT,
		NewARTotal					NUMERIC(24,10),
		NewNARTotal					NUMERIC(24,10),
		OldARTotal					NUMERIC(24,10),
		OldNARTotal					NUMERIC(24,10)
	)	
	
	
	
	--重算内部应收
	--重算往来BTYPE_ARAPTOTAL
	
	
	INSERT #CostSTypeMoveSumInfo(BTypeID,STypeID,STypeID2,CID,NewARTotal,NewNARTotal,OldARTotal,OldNARTotal)
		
	SELECT a.BTypeID,a.STypeID,a.STypeID2,a.CID,a.NewARTotal,a.NewNARTotal,d.OldARTotal,d.OldNARTotal
	FROM 
	(
		SELECT BTypeID,STypeID,STypeID2,CID,SUM(ARMoney) AS NewARTotal,SUM(NARMoney) AS NewNARTotal
		FROM #CostSTypeMoveBillList 
		GROUP BY BTypeID,STypeID,STypeID2,CID
	) a
	LEFT JOIN 
	(
		SELECT BtypeId,STypeID,CID,SUM(Total) AS OldARTotal,SUM(NTotal) AS OldNARTotal
		FROM ListTable
		WHERE BillType=187 AND Audited=1
		AND BillNumberId IN 
		(
			SELECT BillNumberId
			FROM #CostSTypeMoveBillList
		)
		AND AtypeId=@InnerAR_ID
		GROUP BY BtypeId,STypeID,CID
	) d
	ON a.STypeID=d.STypeID AND a.CID=d.CID
	
	
	--处理LISTTABLE
	UPDATE ListTable
	SET Total=b.ARMoney,Ntotal=b.NARMoney
	FROM #CostSTypeMoveBillList b
	WHERE ListTable.BillType=187 AND ListTable.BillNumberId=b.BillNumberID
	AND ListTable.ATypeID=@InnerAR_ID
	
	--处理ATYPE_TOTAL
	
	
	
	
	UPDATE AType_Total
	SET Total=AType_Total.Total+ISNULL(b.ARTotal,0),Ntotal=AType_Total.Ntotal+ISNULL(b.NARTotal,0)
	FROM
	(
		SELECT STypeID,CID,-SUM(OldARTotal)+SUM(NewARTotal) AS ARTotal,
		-SUM(OldNARTotal)+SUM(NewNARTotal) AS NARTotal
		FROM #CostSTypeMoveSumInfo
		GROUP BY STypeID,CID
	) b
	WHERE AType_Total.ATypeID=@InnerAR_ID
	AND AType_Total.STypeID=b.STypeID
	AND AType_Total.CID=b.CID;
	
	--处理SType_InnerARTotal
	WITH innerCal
	AS 
	(
		SELECT a.BTypeID,a.STypeID,a.STypeID2,a.CID,a.NewARTotal,a.NewNARTotal,d.OldARTotal,d.OldNARTotal
		FROM 
		(
			SELECT BTypeID,STypeID,STypeID2,CID,SUM(ARMoney) AS NewARTotal,SUM(NARMoney) AS NewNARTotal
			FROM #CostSTypeMoveBillList 
			GROUP BY BTypeID,STypeID,STypeID2,CID
		) a
		LEFT JOIN 
		(
			SELECT b.btypeid,sc.stypeid AS  stypeid,st.stypeid AS stypeid2 ,b.cid,SUM(s.Total) AS OldARTotal,SUM(s.Total) AS OldNARTotal  FROM  dbo.STypeMoveBill s 
			INNER JOIN stock st ON s.ktypeid2 =st.typeId
			INNER  JOIN stock sc ON s.ktypeid =sc.typeId
			INNER JOIN billindex b  ON b.BillNumberId = s.BillNumberId AND b.RedWord=0 AND b.IFCHECK='t'
			 WHERE b.BILLTYPE =187 
			AND s.BillNumberId IN 
			(
				SELECT BillNumberId
				FROM #CostSTypeMoveBillList
			)
			GROUP BY BtypeId,sc.stypeid,st.stypeid,b.cid
		) d
		ON a.STypeID=d.STypeID AND a.STypeID2=d.STypeID2 AND a.CID=d.CID 
	
	)

	UPDATE SType_InnerARTotal
	SET InnerARTotal=SType_InnerARTotal.InnerARTotal+ISNULL(b.InnerARTotal,0)
	FROM
	(
		SELECT STypeID2,STypeID,-SUM(OldARTotal)+SUM(NewARTotal) AS InnerARTotal
		FROM innerCal
		GROUP BY STypeID2,STypeID
	) b
	WHERE SType_InnerARTotal.STypeID2=b.STypeID2
		AND SType_InnerARTotal.STypeID=b.STypeID
		
	--SELECT  * FROM SType_InnerARTotal
		
		
		
	
	
	DROP TABLE #CostSTypeMoveBillList
	DROP TABLE #CostSTypeMoveSumInfo
	
END		
		

--其他出库单要单独处理

TRUNCATE TABLE #ListTable

IF @intBillType NOT IN (17,202)
BEGIN
	EXEC Gp_DiffExchange_Else @intBillType,@strATypeID,@strSTypeID
END
ELSE IF @intBillType=202
BEGIN
	--其他出库单，对应的科目，这个要从BILLINDEX里去查，这里返回为空
	--这个要单独处理
	EXEC Gp_OutBill_Else @intBillType,@strSTypeID
	RETURN
END



--批量修改
IF @intBillType<>17
BEGIN
	
		UPDATE ListTable
		SET Total=b.NewValue,Ntotal=B.NewValue
		FROM #ListTable b
		WHERE ListTable.BillNumberId=b.BillNumberID
		AND ListTable.AtypeId=@strATypeID 
		AND ListTable.BillType=b.BillType
END

--修改AType_Total（同价调拨单不影响）
IF @intBillType<>17
BEGIN
		IF EXISTS(
			SELECT ATypeID
			FROM AType_Total
			WHERE STypeID=@strSTypeID AND ATypeID=@strATypeID  AND CID=@sysID
		)
		BEGIN
			UPDATE AType_Total
			SET Total=AType_Total.Total+ISNULL(b.DiffValue,0), NTotal=AType_Total.Ntotal+ISNULL(b.DiffValue,0)
			FROM 
			(
				SELECT -SUM(a.OldValue)+SUM(a.NewValue) AS DiffValue
				FROM #ListTable a 
			) b
			WHERE AType_Total.ATypeID=@strATypeID
			AND AType_Total.STypeID=@strSTypeID
			AND CID=@sysID			
		END
		ELSE
		BEGIN
			INSERT AType_Total(ATypeID,STypeID,Total,Ntotal,CID)
			SELECT @strATypeID,@strSTypeID,-SUM(a.OldValue)+SUM(a.NewValue) AS DiffValue, -SUM(a.OldValue)+SUM(a.NewValue) AS DiffValue,@sysID
			FROM #ListTable a
		END

END

--删除相关单据中TOTAL为0的


--成本价销售后要处理往来数据


IF @intBillType=11
	AND EXISTS(
		SELECT BillNumberID
		FROM #AfterModifyBill
		WHERE BillType=11
		AND BillNumberID IN
		(
			SELECT BillNumberID 
			FROM BillIndex
			WHERE IfCheck='t' AND RedWord=0 AND BillType=11 AND CostSale=1
		)
	)
BEGIN
	CREATE TABLE #CostSaleBillList(BillNumberID BIGINT,BTypeID VARCHAR(50),STypeID VARCHAR(50),
	SaleInComeMoney	NUMERIC(24,10),NSaleInComeMoney NUMERIC(24,10),TaxMoney NUMERIC(24,10),NTaxMoney NUMERIC(24,10),
	ARMoney NUMERIC(24,10),NARMoney NUMERIC(24,10),CID INT)
	

	
	DECLARE
		@strTempCostSaleATypeID			VARCHAR(50),
		@PAY_TAXMONEY_ID				INT,
		@SALE_INCOME_ID					INT,
		@AR_ID							INT,
		@decNewSaleIncomeTotal			NUMERIC(24,10),
		@decNewTaxTotal					NUMERIC(24,10),
		@decNewARTotal					NUMERIC(24,10),
		@decNewNSaleIncomeTotal			NUMERIC(24,10),
		@decNewNTaxTotal				NUMERIC(24,10),
		@decNewNARTotal					NUMERIC(24,10),
		@decOldSaleIncomeTotal			NUMERIC(24,10),
		@decOldTaxTotal					NUMERIC(24,10),
		@decOldARTotal					NUMERIC(24,10),
		@decOldNSaleIncomeTotal			NUMERIC(24,10),
		@decOldNTaxTotal				NUMERIC(24,10),
		@decOldNARTotal					NUMERIC(24,10)
	
	INSERT #CostSaleBillList(BillNumberID,BTypeID,STypeID,SaleInComeMoney,NSaleInComeMoney,TaxMoney,NTaxMoney,ARMoney,NARMoney,CID)
	SELECT DISTINCT a.BillNumberID,b.btypeid,b.Stypeid,b.SaleInComeMoney,b.NSaleInComeMoney,b.totalmoney-b.SaleInComeMoney,b.NTotalMoney-b.NSaleInComeMoney,
	b.totalmoney-b.totalinmoney-b.preferencemoney,b.NTotalMoney-b.NTotalInMoney-b.NPreferenceMoney,b.CID
	FROM #AfterModifyBill a
	INNER JOIN
	(
		SELECT a.BillNumberID,a.BTypeID,a.STypeID,a.CID,a.totalmoney,a.NTotalMoney,a.totalinmoney,a.NTotalInMoney,a.preferencemoney,a.NPreferenceMoney,
		SUM(b.total) AS SaleInComeMoney,SUM(b.NTotal) AS NSaleInComeMoney
		FROM BillIndex a
		INNER JOIN SaleBill b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.ifcheck='t' AND a.RedWord=0 AND a.BillType=11 AND CostSale=1
		GROUP BY a.BillNumberId,a.BTypeID,a.STypeID,a.CID,a.totalmoney,a.NTotalMoney,a.totalinmoney,a.NTotalInMoney,a.preferencemoney,a.NPreferenceMoney
	) b
	ON a.BillNumberID=b.BillNumberId
	WHERE a.BillType=11
	
	SELECT @SALE_INCOME_ID=NID FROM dbo.Ac_Items WHERE UserCode='5101'--『销售收入』,0000300001
	SELECT @PAY_TAXMONEY_ID=NID FROM dbo.Ac_Items WHERE UserCode='2171'--『应交税金』,0000200004
	SELECT @AR_ID=nId FROM Ac_Items WHERE UserCode='987'  --应收
	
	CREATE TABLE #CostSaleSumInfo(
		BTypeID						VARCHAR(50),
		STypeID						VARCHAR(50),
		CID							INT,
		NewSaleIncomeTotal			NUMERIC(24,10),
		NewNSaleIncomeTotal			NUMERIC(24,10),
		NewTaxTotal					NUMERIC(24,10),
		NewNTaxTotal				NUMERIC(24,10),
		NewARTotal					NUMERIC(24,10),
		NewNARTotal					NUMERIC(24,10),
		OldSaleIncomeTotal			NUMERIC(24,10),
		OldNSaleIncomeTotal			NUMERIC(24,10),
		OldTaxTotal					NUMERIC(24,10),
		OldNTaxTotal				NUMERIC(24,10),
		OldARTotal					NUMERIC(24,10),
		OldNARTotal					NUMERIC(24,10)
	)	
	
	
	
	--重算销售收入
	--重算税金
	--重算往来BTYPE_ARAPTOTAL
	/*
	SELECT '#CostSaleBillList',BTypeID,STypeID,CID,SUM(SaleInComeMoney) AS NewSaleIncomeTotal,SUM(NSaleInComeMoney) AS NewNSaleIncomeTotal,
		SUM(TaxMoney) AS NewTaxTotal,SUM(NTaxMoney) AS NewNTaxTotal,SUM(ARMoney) AS NewARTotal,SUM(NARMoney) AS NewNARTotal
		FROM #CostSaleBillList 
		GROUP BY BTypeID,STypeID,CID
	*/		
	INSERT #CostSaleSumInfo(BTypeID,STypeID,CID,NewSaleIncomeTotal,NewNSaleIncomeTotal,NewTaxTotal,NewNTaxTotal,
	NewARTotal,NewNARTotal,OldSaleIncomeTotal,OldNSaleIncomeTotal,OldTaxTotal,OldNTaxTotal,OldARTotal,OldNARTotal)
		
	SELECT a.BTypeID,a.STypeID,a.CID,a.NewSaleIncomeTotal,a.NewNSaleIncomeTotal,a.NewTaxTotal,a.NewNTaxTotal,
	a.NewARTotal,a.NewNARTotal,b.OldSaleIncomeTotal,b.OldNSaleIncomeTotal,c.OldTaxTotal,c.OldNTaxTotal,d.OldARTotal,d.OldNARTotal
	FROM 
	(
		SELECT BTypeID,STypeID,CID,SUM(SaleInComeMoney) AS NewSaleIncomeTotal,SUM(NSaleInComeMoney) AS NewNSaleIncomeTotal,
		SUM(TaxMoney) AS NewTaxTotal,SUM(NTaxMoney) AS NewNTaxTotal,SUM(ARMoney) AS NewARTotal,SUM(NARMoney) AS NewNARTotal
		FROM #CostSaleBillList 
		GROUP BY BTypeID,STypeID,CID
	) a
	LEFT JOIN 
	(
		SELECT BtypeId,STypeID,CID,SUM(Total) AS OldSaleIncomeTotal,SUM(NTotal) AS OldNSaleIncomeTotal
		FROM ListTable
		WHERE BillType=11 AND Audited=1
		AND BillNumberId IN 
		(
			SELECT BillNumberId
			FROM #CostSaleBillList
		)
		AND AtypeId=@SALE_INCOME_ID
		GROUP BY BtypeId,STypeID,CID
	) b
	ON a.BTypeID=b.BtypeId AND a.STypeID=b.STypeID AND a.CID=b.CID
	LEFT JOIN 
	(
		SELECT BtypeId,STypeID,CID,SUM(Total) AS OldTaxTotal,SUM(NTotal) AS OldNTaxTotal
		FROM ListTable
		WHERE BillType=11 AND Audited=1
		AND BillNumberId IN 
		(
			SELECT BillNumberId
			FROM #CostSaleBillList
		)
		AND AtypeId=@PAY_TAXMONEY_ID
		GROUP BY BtypeId,STypeID,CID
	) c
	ON a.BTypeID=c.BtypeId AND a.STypeID=c.STypeID AND a.CID=c.CID
	LEFT JOIN 
	(
		SELECT BtypeId,STypeID,CID,SUM(Total) AS OldARTotal,SUM(NTotal) AS OldNARTotal
		FROM ListTable
		WHERE BillType=11 AND Audited=1
		AND BillNumberId IN 
		(
			SELECT BillNumberId
			FROM #CostSaleBillList
		)
		AND AtypeId=@AR_ID
		GROUP BY BtypeId,STypeID,CID
	) d
	ON a.BTypeID=d.BtypeId AND a.STypeID=d.STypeID AND a.CID=d.CID
	
	--SELECT '#CostSaleSumInfo',* FROM  #CostSaleSumInfo
	--处理LISTTABLE
	UPDATE ListTable
	SET Total=b.SaleInComeMoney,Ntotal=b.NSaleInComeMoney
	FROM #CostSaleBillList b
	WHERE ListTable.BillType=11 AND ListTable.BillNumberId=b.BillNumberID
	AND ListTable.ATypeID=@SALE_INCOME_ID
	
	UPDATE ListTable
	SET Total=b.TaxMoney,Ntotal=b.NTaxMoney
	FROM #CostSaleBillList b
	WHERE ListTable.BillType=11 AND ListTable.BillNumberId=b.BillNumberID
	AND ListTable.ATypeID=@PAY_TAXMONEY_ID
	
	UPDATE ListTable
	SET Total=b.ARMoney,Ntotal=b.NARMoney
	FROM #CostSaleBillList b
	WHERE ListTable.BillType=11 AND ListTable.BillNumberId=b.BillNumberID
	AND ListTable.ATypeID=@AR_ID
	
	--处理ATYPE_TOTAL
	
	
	UPDATE AType_Total
	SET Total=AType_Total.Total+ISNULL(b.SaleIncomeTotal,0),Ntotal=AType_Total.Ntotal+ISNULL(b.NSaleIncomeTotal,0)
	FROM
	(
		SELECT STypeID,CID,-SUM(OldSaleIncomeTotal)+SUM(NewSaleIncomeTotal) AS SaleIncomeTotal,
		-SUM(OldNSaleIncomeTotal)+SUM(NewNSaleIncomeTotal) AS NSaleIncomeTotal
		FROM #CostSaleSumInfo
		GROUP BY STypeID,CID
	) b
	WHERE AType_Total.ATypeID=@SALE_INCOME_ID
	AND AType_Total.STypeID=b.STypeID
	AND AType_Total.CID=b.CID
	
	UPDATE AType_Total
	SET Total=AType_Total.Total+ISNULL(b.TaxTotal,0),Ntotal=AType_Total.Ntotal+ISNULL(b.NTaxTotal,0)
	FROM
	(
		SELECT STypeID,CID,-SUM(OldTaxTotal)+SUM(NewTaxTotal) AS TaxTotal,
		-SUM(OldNTaxTotal)+SUM(NewNTaxTotal) AS NTaxTotal
		FROM #CostSaleSumInfo
		GROUP BY STypeID,CID
	) b
	WHERE AType_Total.ATypeID=@PAY_TAXMONEY_ID
	AND AType_Total.STypeID=b.STypeID
	AND AType_Total.CID=b.CID
	
	
	UPDATE AType_Total
	SET Total=AType_Total.Total+ISNULL(b.ARTotal,0),Ntotal=AType_Total.Ntotal+ISNULL(b.NARTotal,0)
	FROM
	(
		SELECT STypeID,CID,-SUM(OldARTotal)+SUM(NewARTotal) AS ARTotal,
		-SUM(OldNARTotal)+SUM(NewNARTotal) AS NARTotal
		FROM #CostSaleSumInfo
		GROUP BY STypeID,CID
	) b
	WHERE AType_Total.ATypeID=@AR_ID
	AND AType_Total.STypeID=b.STypeID
	AND AType_Total.CID=b.CID
	
	--处理BTYPE_ARAPTOTAL
	UPDATE BTYPE_ARAPTOTAL
	SET ARTotal=BTYPE_ARAPTOTAL.ARTotal+ISNULL(b.ARTotal,0),NARTotal=BTYPE_ARAPTOTAL.NARTotal+ISNULL(b.NARTotal,0)
	FROM
	(
		SELECT BTypeID,STypeID,CID,-SUM(OldARTotal)+SUM(NewARTotal) AS ARTotal,
		-SUM(OldNARTotal)+SUM(NewNARTotal) AS NARTotal
		FROM #CostSaleSumInfo
		GROUP BY BTypeID,STypeID,CID
	) b
	WHERE BTYPE_ARAPTOTAL.BTypeID=b.BTypeID
		AND BTYPE_ARAPTOTAL.STypeID=b.STypeID
		AND BTYPE_ARAPTOTAL.CID=b.CID
		
	--处理结算状态
	IF EXISTS(
		SELECT BillNumberID
		FROM Billindex
		WHERE Billindex.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND totalinmoney>=totalmoney AND totalmoney=0
	)
	BEGIN
		UPDATE Billindex
		SET JsStyle=0,JsState=2
		WHERE Billindex.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND totalinmoney>=totalmoney AND totalmoney=0
	END
	
	IF EXISTS(
		SELECT BillNumberID
		FROM Billindex
		WHERE Billindex.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND totalinmoney>=totalmoney AND totalmoney<>0
	)
	BEGIN
		UPDATE Billindex
		SET JsStyle=1,JsState=2
		WHERE Billindex.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND totalinmoney>=totalmoney AND totalmoney<>0
	END
	
	IF EXISTS(
		SELECT BillNumberID
		FROM Billindex
		WHERE Billindex.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND totalinmoney<totalmoney AND totalinmoney=0
	)
	BEGIN
		UPDATE Billindex
		SET JsStyle=0,JsState=0
		WHERE Billindex.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND totalinmoney<totalmoney AND totalinmoney=0
	END
	
	
	IF EXISTS(
		SELECT BillNumberID
		FROM Billindex
		WHERE Billindex.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND totalinmoney<totalmoney AND totalmoney<>0 AND totalinmoney<>0
	)
	BEGIN
		UPDATE Billindex
		SET JsStyle=1,JsState=1
		WHERE Billindex.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND totalinmoney<totalmoney AND totalmoney<>0 AND totalinmoney<>0
	END
	
	--还需要更新结算状态
	
	
	--如果之前有关联OrderBill，那么需要回填ReachTotal,ReachTaxTotal
	
	IF EXISTS(
		SELECT BillNumberID
		FROM SaleBill
		WHERE OrderID>0 AND BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
	)
	BEGIN
		UPDATE OrderBill 
		SET 
		ReachTotal=ISNULL(ReachTotal,0)+b.total,
		ReachTaxTotal=ISNULL(ReachTaxTotal,0)+b.TaxTotal
		FROM SaleBill b
		WHERE b.BillNumberId IN
		(
			SELECT BillNumberID
			FROM #CostSaleBillList
		)
		AND OrderBill.OrderID=b.OrderID
	END
	
	DROP TABLE #CostSaleBillList
	DROP TABLE #CostSaleSumInfo
END


IF @intBillType=402 
	AND EXISTS(
		SELECT BillNumberID
		FROM #AfterModifyBill
		WHERE BillType=402
	)
BEGIN
	--发出商品出库单
	--处理BTYPE_ARAPTOTAL，FCTOTAL增加
	UPDATE BTYPE_ARAPTOTAL
	SET FCTotal=BTYPE_ARAPTOTAL.FCTotal+ISNULL(b.DiffValue,0), NFCTotal=BTYPE_ARAPTOTAL.NFCTotal+ISNULL(b.DiffValue,0)
	FROM 
	(
		SELECT a.BTypeID,a.STypeID,a.CID,-SUM(a.OldValue)+SUM(a.NewValue) AS DiffValue
		FROM #ListTable a
		WHERE a.ATypeID=@strATypeID
		AND a.STypeID=@strSTypeID
		AND a.BillType=@intBillType
		GROUP BY a.BTypeID,a.STypeID,a.CID
	) b
	WHERE BTYPE_ARAPTOTAL.BTypeID=b.BTypeID
	AND BTYPE_ARAPTOTAL.STypeID=@strSTypeID
	AND BTYPE_ARAPTOTAL.STypeID=b.STypeID
	AND BTYPE_ARAPTOTAL.CID=b.CID
END


IF @intBillType=403
	AND EXISTS(
		SELECT BillNumberID
		FROM #AfterModifyBill
		WHERE BillType=403
	)
BEGIN
	--发出商品退货单
	--处理BTYPE_ARAPTOTAL，FCTOTAL减少
	UPDATE BTYPE_ARAPTOTAL
	SET FCTotal=BTYPE_ARAPTOTAL.FCTotal-ISNULL(b.DiffValue,0), NFCTotal=BTYPE_ARAPTOTAL.NFCTotal-ISNULL(b.DiffValue,0)
	FROM 
	(
		SELECT a.BTypeID,a.STypeID,a.CID,-SUM(a.OldValue)+SUM(a.NewValue) AS DiffValue
		FROM #ListTable a
		WHERE a.ATypeID=@strATypeID
		AND a.STypeID=@strSTypeID
		AND a.BillType=@intBillType
		GROUP BY a.BTypeID,a.STypeID,a.CID
	) b
	WHERE BTYPE_ARAPTOTAL.BTypeID=b.BTypeID
	AND BTYPE_ARAPTOTAL.STypeID=@strSTypeID
	AND BTYPE_ARAPTOTAL.STypeID=b.STypeID
	AND BTYPE_ARAPTOTAL.CID=b.CID
END


--暂估退货单要处理往来数据
IF @intBillType=401
	AND EXISTS(
		SELECT BillNumberID
		FROM #AfterModifyBill
		WHERE BillType=401
	)
BEGIN
	--处理BTYPE_ARAPTOTAL
	UPDATE BTYPE_ARAPTOTAL
	SET GRIRTotal=BTYPE_ARAPTOTAL.GRIRTotal-ISNULL(b.DiffValue,0), NGRIRTotal=BTYPE_ARAPTOTAL.NGRIRTotal-ISNULL(b.DiffValue,0)
	FROM 
	(
		SELECT a.BTypeID,a.STypeID,a.CID,-SUM(a.OldValue)+SUM(a.NewValue) AS DiffValue
		FROM #ListTable a
		WHERE a.ATypeID=@strATypeID
		AND a.STypeID=@strSTypeID
		AND a.BillType=@intBillType
		GROUP BY a.BTypeID,a.STypeID,a.CID
	) b
	WHERE BTYPE_ARAPTOTAL.BTypeID=b.BTypeID
	AND BTYPE_ARAPTOTAL.STypeID=@strSTypeID
	AND BTYPE_ARAPTOTAL.STypeID=b.STypeID
	AND BTYPE_ARAPTOTAL.CID=b.CID
END



DELETE ListTable
WHERE Total=0
AND BillNumberId IN
(
	SELECT DISTINCT BillNumberID
	FROM #AfterModifyBill
)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






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

SET	QUOTED_IDENTIFIER OFF 
GO
SET	ANSI_NULLS ON 
GO


/*

作者：冯波

其他出入库单的处理
*/
CREATE   PROCEDURE Gp_OutBill_Else 
(		
	@intBillType				INT,
	@strSTypeID					VARCHAR(50)
)

--@encode$--
AS

--要改ListTable,AType_Total,AType

--填入原值，现值  #ListTable

--定义一堆常量
DECLARE	
		@GOODS_ID				varchar(50),
		@sysID					INT
	

SELECT @sysID = CID FROM Ac_Currency WHERE Sysrow = 1
SELECT @GOODS_ID=NID FROM Ac_Items WHERE UserCode='1241'	


--因为各单据对应的科目不同，所以需要按单分别来处理
INSERT #ListTable(BillNumberID,OldValue,NewValue,STypeID,BillType,BTypeID,CID)
SELECT a.BillNumberID,SUM(CASE b.AtypeId WHEN @GOODS_ID THEN 0 ELSE b.Total END),
SUM(CASE b.AtypeId WHEN @GOODS_ID THEN -b.Total ELSE 0 END),
@strSTypeID,@intBillType,b.BtypeId,b.CID
FROM 
(
	SELECT DISTINCT BillNumberId
	FROM #AfterModifyBill 
	WHERE BillType=@intBillType
) a
INNER JOIN ListTable b
ON a.BillNumberID=b.BillNumberId
GROUP BY a.BillNumberID,b.BtypeId,b.CID




UPDATE #ListTable
SET AtypeId=b.ATypeID
FROM ListTable b
WHERE #ListTable.BillNumberID=b.BillNumberId
AND b.AtypeId<>@GOODS_ID



--如果之前不存在此科目，则添加
IF EXISTS(
	SELECT a.BillNumberID
	FROM #ListTable a
	WHERE a.NewValue<>0
	AND Not EXISTS(
		SELECT b.BillNumberID
		FROM ListTable b
		WHERE b.BillNumberId=a.BillNumberID
		AND b.BillType=@intBillType
		AND b.AtypeId<>@GOODS_ID
		AND B.CID =@sysID
	)
)
BEGIN
	INSERT ListTable(BillNumberId,BillDate,BillType,AtypeId,BtypeId,EtypeId,
	Total,CostTotal,Audited,Ifout,DTypeID,STypeID,CID,Ntotal,Rate)
	SELECT DISTINCT a.BillNumberId,a.BillDate,a.BillType,d.ATypeID,
	CASE a.BtypeId WHEN '' THEN '0' ELSE a.BtypeId END,a.EtypeId,
	b.NewValue,0,1,0,a.DTypeID,a.STypeID,@sysID,b.NewValue,1
	FROM ListTable a
	INNER JOIN #ListTable b
	ON a.BillNumberId=b.BillNumberID
	INNER JOIN BillIndex c
	ON a.BillNumberId=c.BillNumberId
	INNER JOIN OtherInOutType d
	ON c.OtherInOutType=d.ID
	WHERE a.BillType=@intBillType
	AND Not EXISTS(
		SELECT b.BillNumberID
		FROM ListTable b
		WHERE b.BillNumberId=a.BillNumberID
		AND b.BillType=@intBillType
		AND b.AtypeId<>@GOODS_ID
		)
	GROUP BY a.BillNumberId,a.BillDate,a.BillType,d.ATypeID,
	CASE a.BtypeId WHEN '' THEN '0' ELSE a.BtypeId END,a.EtypeId,
	a.DTypeID,a.STypeID,b.NewValue
END

UPDATE ListTable
SET Total=b.NewValue,NTotal=b.NewValue
FROM #ListTable b
WHERE ListTable.BillNumberId=b.BillNumberID
AND ListTable.AtypeId=b.ATypeID



IF EXISTS(
	SELECT ATypeID
	FROM AType_Total
	WHERE STypeID=@strSTypeID 
	AND ATypeID IN 
	(
		SELECT ATypeID
		FROM #ListTable
	)
	AND CID=@sysID
	
)
BEGIN
	UPDATE AType_Total
	SET Total=AType_Total.Total+ISNULL(b.DiffValue,0)
	FROM 
	(
		SELECT ATypeID,-SUM(OldValue)+SUM(NewValue) AS DiffValue
		FROM #ListTable
		GROUP BY ATypeID
	) b
	WHERE AType_Total.ATypeID=b.ATypeID
	AND AType_Total.STypeID=@strSTypeID
	AND CID=@sysID
END
ELSE
BEGIN
	INSERT AType_Total(ATypeID,STypeID,Total,CID,Ntotal)
	SELECT a.ATypeID,@strSTypeID,-SUM(a.OldValue)+SUM(a.NewValue) AS DiffValue,@sysID,-SUM(a.OldValue)+SUM(a.NewValue) AS DiffValue
	FROM #ListTable a
	GROUP BY a.ATypeID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*

作者：冯波

得到所有出库单据的库存商品所对应的科目

这里需要注意的是：
因为存在参照成本的情形，所以对于参照成本的销售退货的入库还需要进行调整？

对于委托代销
对于维修
是否处理待确认


*/
CREATE   PROCEDURE Gp_OutBill_GetOtherAType 
(
	@intBillType			INT,
	@strATypeID				VARCHAR(50)	OUT
)
--@encode$--
AS


/*
CREATE TABLE #OtherAType(
	@intBillType			INT,
	@strATypeID				VARCHAR(50)
)



INSERT #OtherAType(BillType,ATypeID)
--采购退货单，影响采购退货差价（采购退货差价=应付账款合计-库存商品）
SELECT 6,'000030000200004'
UNION ALL
--采购换货单，影响采购退货差价（采购退货差价=应付账款合计-库存商品）
SELECT 161,'000030000200004'
UNION ALL
--受托代销退货单，影响受托退货差价（受托退货差价=代销商品款-库存商品）
SELECT 146,'000030000200009'
UNION ALL
--销售出库单，销售成本
SELECT 11,'0000400001'
UNION ALL
--销售换货单，销售成本
SELECT 160,'0000400001'
UNION ALL
--委托代销发货，委托代销商品（这个如果改变，会否影响其他？会，譬如委托代销退货单）
SELECT 140,'0000100008'
UNION ALL
--同价调拨单,17（会影响入库的库存商品总值，还会影响入库的InOutStockTable）
--变价调拨单，21,变价调拨差价
SELECT 21,'000030000200005'
UNION ALL
--分支机构调拨出库单，变价调拨差价
SELECT 187,'000030000200005'
UNION ALL
--其他出库单，对应的科目，这个要从BILLINDEX里去查
--报损单，商品报损
SELECT 9,'000040000200001'
UNION ALL
--商品拆装单，商品拆装差价
SELECT 16,'000030000200006'
--成本调价单，成本调价收入
SELECT 57,'000030000200003'


*/

SELECT @strATypeID=''

IF @intBillType=6
BEGIN
	--采购退货单，影响采购退货差价（采购退货差价=应付账款合计-库存商品）
	--SELECT 6,'000030000200004'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0324'--'000030000200004'
END
ELSE IF @intBillType=161
BEGIN
	--采购换货单，影响采购退货差价（采购退货差价=应付账款合计-库存商品）
	--SELECT 161,'000030000200004'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0324'-- '000030000200004'
END

ELSE IF @intBillType=146
BEGIN
	--受托代销退货单，影响受托退货差价（受托退货差价=代销商品款-库存商品）
	--SELECT 146,'000030000200009'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0329'--'000030000200009'
END
ELSE IF @intBillType IN (11,12)
BEGIN
	--销售出库单，销售成本
	--SELECT 11,'0000400001'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='5401'--'0000400001'
END
ELSE IF @intBillType IN (45,46)
BEGIN
	--销售退货单，销售成本
	--SELECT 45,'0000400001'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='5401'--'0000400001'
END
ELSE IF @intBillType=305
BEGIN
	--零售单，销售成本
	--SELECT 305,'0000400001'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='5401'--'0000400001'
END
ELSE IF @intBillType=215
BEGIN
	--零售退货单，销售成本
	--SELECT 215,'0000400001'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='5401'--'0000400001'
END
ELSE IF @intBillType=139
BEGIN
	--赠送单，商品赠出
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0422'--'000040000200002'
END
ELSE IF @intBillType=183
BEGIN
	--积分兑换单，商品赠出
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0422'--'000040000200002'
END
ELSE IF @intBillType=160
BEGIN
	--销售换货单，销售成本
	--SELECT 160,'0000400001'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='5401'--'0000400001'
END
ELSE IF @intBillType IN(140,142)
BEGIN
	--委托代销发货，委托代销商品（这个如果改变，会否影响其他？会，譬如委托代销退货单）
	--SELECT 140,'0000100008'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='1261'--'0000100008'
END
ELSE IF @intBillType IN(141)
BEGIN
	--委托代销结算,处理销售成本 委托代销商品在处理库存商品那已经处理了
	--SELECT 140,'0000100008'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='5401'--'0000100008'
END
ELSE IF @intBillType=17
BEGIN
	--同价调拨单,17（会影响入库的库存商品总值，还会影响入库的InOutStockTable）
	--SELECT 17,'000030000200005'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0325'--'000030000200005'
END
ELSE IF @intBillType=21
BEGIN
	--变价调拨单，21,变价调拨差价
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0325'--'000030000200005'
END
ELSE IF @intBillType=187
BEGIN
	--分支机构调拨出库单，变价调拨差价
	--SELECT 187,'000030000200005'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0325'--'000030000200005'
END
ELSE IF @intBillType=202
BEGIN
	--其他出库单，对应的科目，这个要从BILLINDEX里去查，这里返回为空
	SELECT @strATypeID=''
END
ELSE IF @intBillType=9
BEGIN
	--报损单，商品报损
	--SELECT 9,'000040000200001'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0421'--'000040000200001'
END
ELSE IF @intBillType=16
BEGIN
	--商品拆装单，商品拆装差价
	--SELECT 16,'000030000200006'
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0326'--'000030000200006'
END
ELSE IF @intBillType=173
BEGIN
	--维修品调入单，商品维修支出
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0423'--'000040000200003'
END
ELSE IF @intBillType=168
BEGIN
	--整机更换单，商品维修支出
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0423'--'000040000200003'
END
ELSE IF @intBillType=166
BEGIN
	--维修单，商品维修支出
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0423'--'000040000200003'
END
ELSE IF @intBillType=172
BEGIN
	--上门维修单，商品维修支出
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0423'--'000040000200003'
END
ELSE IF @intBillType=57
BEGIN
	--成本调价单，成本调价收入
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0323'--'000030000200003'
END
ELSE IF @intBillType=14
BEGIN
	--报溢单，商品报溢收入
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0321'--'000030000200001'
END
ELSE IF @intBillType=126
BEGIN
	--获赠单，商品获赠收入
	SELECT @strATypeID=nid FROM Ac_Items WHERE UserCode='0322'--'000030000200002'
END
ELSE IF @intBillType=401
BEGIN
	--暂估退货单 应付暂估增加
	SELECT @strATypeID=nId FROM dbo.Ac_Items WHERE UserCode='2122'		--应付暂估
END
ELSE IF @intBillType IN (402,403)
BEGIN
	--发出商品出库单  发出商品退货单,发出商品
	SELECT @strATypeID=nid	FROM dbo.Ac_Items WHERE UserCode='1251'			--发出商品
END


--成本价销售,成本价受托收货,暂估退货还需要处理其他项目




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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




/*
程序修改：吴德水
修改日期：2003-08-13 15:27
修改内容：添加单据的筛选（四个条件：仓库、职员、摘要、说明）
修改位置：添加四个输入参数 13 行,整理查询条件41行起

--陈启华 2004-06-24 
--                AND (a.ifStopMoney=''0'' or a.ifStopMoney is null)
*/
CREATE             PROCEDURE [Gp_OutDate_Gathering]              -----超期应收款
(
	@chrOperatorID 	VARCHAR(100),     -------操作员ID号
	@chvBillKind 	VARCHAR(20),             ------AlertDay列出超期应收单据,NoHaveAlertDay列出无超期应收期限单据
	@bgnBillDate 	VARCHAR(20) = '',	--起始开单日期
	@endBillDate 	VARCHAR(20) = '',	--截止开单日期
	@bgnAlertDay 	VARCHAR(20) = '',	--期限日期
	@endAlertDay 	VARCHAR(20) = '',	--期限日期
	@BFullName 		VARCHAR(50) = '',	--往来单位
	@KFullName 		VARCHAR(50) = '',	--仓库名称
	@EFullName 		VARCHAR(50) = '',	--职员名称
	@BillCode 		VARCHAR(200) = '',	--单据编号  -- #&**&#
	@Comment 		VARCHAR(50) = '',	--单据摘要
	@Explain 		VARCHAR(50) = ''	--单据说明
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chrOperatorID IS NULL RETURN -1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @chrOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re		
--------------------------------------------------------------得到数据-------------------------------------------------

DECLARE @SQL VARCHAR(2000),@whereSQL VARCHAR(500)

SET @whereSQL = ''

--如果BtypeId(往来单位编号)为空或为'00000'，则直接取其权限范围
--不为空，则进行权限范围的比较

SET @whereSQL = '
				AND (a.btypeid LIKE ''' + @MBtypeId + '%'' OR a.btypeid LIKE ''' + @MBtypeId2 + '%'')
				AND a.etypeid LIKE ''' + @MEtypeid +'%'''
IF @bgnBillDate <> ''
	SET @whereSQL = @whereSQL + '
				AND a.billdate >= ''' + @bgnBillDate + ''''
IF @endBillDate <> ''
	SET @whereSQL = @whereSQL + '
				AND a.billdate <= ''' + @endBillDate + ''''

IF @bgnAlertDay <> ''
	SET @whereSQL = @whereSQL + '
				AND (a.billdate + ISNULL(a.alertday,9999)) >= ''' + @bgnAlertDay + ''''
IF @endAlertDay <> ''
	SET @whereSQL = @whereSQL + '
				AND (a.billdate + ISNULL(a.alertday,9999)) <= ''' + @endAlertDay + ''''

IF @BillCode <> ''
	SET @whereSQL = @whereSQL + '
		AND a.billCode LIKE ''%' + @BillCode + '%'''
IF @Comment <> ''
	SET @whereSQL = @whereSQL + '
		AND a.Comment LIKE ''%' + @Comment + '%'''
IF @Explain <> ''
	SET @whereSQL = @whereSQL + '
		AND a.explain LIKE ''%' + @Explain + '%'''

IF @chvBillKind='AlertDay'
	BEGIN
		SET @SQL = '
		SELECT a.BillNumberID,
				a.BillDate,
				a.BillCode,
				b.fullname AS bName,
				k.fullname AS kName,
				e.fullname AS eName,
				(a.BillDate+a.AlertDay) AS AlertDay,
				ISNULL(a.TotalMoney,0) AS TotalMoney,
				(a.TotalMoney-ISNULL(a.TotalinMoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.preferenceMoney,0)) AS TotalLackMoney,
				a.comment,
				a.explain
		FROM billIndex a 
		LEFT JOIN btype b
			ON (a.btypeid=b.typeid)
		LEFT JOIN stock k
			ON (a.ktypeid=k.typeid)
		LEFT JOIN employee e
			ON (a.etypeid=e.typeid)
		WHERE a.billtype=11
				AND a.ifcheck=''t''
				AND (a.TotalMoney - ISNULL(a.TotalinMoney,0) - ISNULL(a.CompleteTotal,0)-ISNULL(a.preferenceMoney,0)) > 0
				AND DATEDIFF(DAY,DATEADD(DAY,a.AlertDay,a.BillDate),GETDATE())>0
				AND a.AlertDay <> 9999
				AND (a.ifStopMoney=''0'' or a.ifStopMoney is null)
				AND a.RedWord = 0
				AND b.fullname LIKE ''%' + @BFullName + '%''
				AND k.fullname LIKE ''%' + @KFullName + '%''
				AND e.fullname LIKE ''%' + @EFullName + '%'''
					+ @whereSQL + '
			ORDER BY a.BillDate+a.AlertDay'
	END
ELSE IF @chvBillKind='NoHaveAlertDay'
	BEGIN
		SET @SQL = '
		SELECT a.BillNumberID,
				a.BillDate,
				a.BillCode,
				b.fullname AS bName,
				k.fullname AS kName,
				e.fullname AS eName,
				9999 AS AlertDay,
				ISNULL(a.TotalMoney,0) AS TotalMoney,
				(a.TotalMoney-ISNULL(a.TotalinMoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.preferenceMoney,0)) AS TotalLackMoney,
				a.comment,
				a.explain
		FROM billIndex a
		LEFT JOIN btype b
			ON (a.btypeid=b.typeid)
		LEFT JOIN stock k
			ON (a.ktypeid=k.typeid)
		LEFT JOIN employee e
			ON (a.etypeid=e.typeid)
			WHERE a.billtype=11
				AND ifcheck=''t''
				AND (a.TotalMoney-ISNULL(a.TotalinMoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.preferenceMoney,0))>0
				AND ISNULL(a.AlertDay,9999)>=9999
				AND RedWord=0 
				AND (a.ifStopMoney=''0'' or a.ifStopMoney is null)
				AND b.fullname LIKE ''%' + @BFullName + '%''
				AND k.fullname LIKE ''%' + @KFullName + '%''
				AND e.fullname LIKE ''%' + @EFullName + '%'''
					+ @whereSQL + '
			ORDER BY a.BillDate+a.AlertDay'
	END
ELSE
   RETURN -1

--Print @SQL
EXEC (@SQL)


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：谢吉康

	日期：2004-09-15

	描述：超期应收款的处理
*/
CREATE PROCEDURE Gp_OutDate_GatheringBillDeal(
	@Bid	int,	--单据的BillNumberId
	@dType	int,		--操作类别 1.停止单据收款  2.取消单据期限
	@billtype INT,  --单据类型
	@detailId	INT
)
--@encode$--
AS 
IF @dType = 1
	BEGIN
		IF	@billtype IN(404,405)
		BEGIN
			UPDATE	ReceiptBillIndex SET IfStopMoney = 1 WHERE BillNumberId = @Bid
				IF @@ROWCOUNT <> 0
					BEGIN
						RETURN 0
					END
				ELSE
					BEGIN
						RETURN 1
					END
		END
		ELSE IF @billtype IN(115,116,128,129)
		BEGIN
			UPDATE	dbo.AdDebtBill SET IfStopMoney = 1 WHERE BillNumberId = @Bid AND id = @detailId
				IF @@ROWCOUNT <> 0
					BEGIN
						UPDATE dbo.BillIndex SET IfStopMoney=1 WHERE BillNumberId = @Bid AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.AdDebtBill WHERE BillNumberId=@Bid AND IfStopMoney<>1 )
						RETURN 0
					END
				ELSE
					BEGIN
						RETURN 1
					END
		END
		ELSE
		BEGIN
			UPDATE	BillIndex SET IfStopMoney = 1 WHERE BillNumberId = @Bid
				IF @@ROWCOUNT <> 0
					BEGIN
						RETURN 0
					END
				ELSE
					BEGIN
						RETURN 1
					END
		END
	END
ELSE
	BEGIN
	IF	@billtype IN(404,405)
		BEGIN
			UPDATE	ReceiptBillIndex SET AlertDay = 9999 WHERE BillNumberId = @Bid		
				IF @@ROWCOUNT <> 0
					RETURN 0
				ELSE
					RETURN 1
		END
		ELSE IF @billtype IN(115,116,128,129)
		BEGIN
			UPDATE	dbo.AdDebtBill SET AlertDay = 9999 WHERE BillNumberId = @Bid AND id = @detailId
				IF @@ROWCOUNT <> 0
					RETURN 0
				ELSE
					RETURN 1
		END
		ELSE
		BEGIN
			UPDATE	BillIndex SET AlertDay = 9999 WHERE BillNumberId = @Bid		
				IF @@ROWCOUNT <> 0
					RETURN 0
				ELSE
					RETURN 1
		END
		
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


/*
	作者：谢吉康

	日期：2004-09-15

	描述：超期应付款的处理
*/
CREATE PROCEDURE Gp_OutDate_Pay(
	@Bid	int,	--单据的BillNumberId
	@dType	int,		--操作类别 1.停止单据付款  2.取消单据期限
	@billtype int  --单据类型
)
--@encode$--
AS
IF @dType = 1
	BEGIN
		IF EXISTS(SELECT TOP 1 * FROM BillIndex 
						WHERE BillNumberId = @Bid AND RedWord = 0 
						AND ((IfCheck = 't' AND isini<>1 )OR (IfCheck='f' AND isini=1 )) 
						AND BillType = @billtype)
			BEGIN
				UPDATE	BillIndex SET IfStopMoney = 1 WHERE BillNumberId = @Bid
		
				IF @@ROWCOUNT <> 0
					BEGIN
						--RAISERROR('停止单据付款成功！',16,1)
						RETURN 0
					END
				ELSE
					BEGIN
						--RAISERROR('停止单据付款失败！',16,1)
						RETURN 1
					END
			END
		
			--发票
		IF EXISTS(SELECT TOP 1 * FROM ReceiptBillIndex WHERE BillNumberId = @Bid AND RedWord = 0 AND IfCheck = 't' AND BillType = @billtype)
		BEGIN
				UPDATE	ReceiptBillIndex SET IfStopMoney = 1 WHERE BillNumberId = @Bid
		
				IF @@ROWCOUNT <> 0
					BEGIN
						--RAISERROR('停止单据付款成功！',16,1)
						RETURN 0
					END
				ELSE
					BEGIN
						--RAISERROR('停止单据付款失败！',16,1)
						RETURN 1
					END
			END
	END
ELSE
	BEGIN
		IF EXISTS
		(
		SELECT TOP 1 * FROM BillIndex 
		WHERE BillNumberId = @Bid  and BillType=@billtype
		AND RedWord = 0 
		AND ((IfCheck = 't' AND isini<>1 )OR (IfCheck='f' AND isini=1 )) --isini=1表示期初单据 期初单据特殊处理
		AND AlertDay <> 9999
		)
			BEGIN
				UPDATE	BillIndex SET AlertDay = 9999 WHERE BillNumberId = @Bid		
				IF @@ROWCOUNT <> 0
					RETURN 0
				ELSE
					RETURN 1
			END
		--发票	
		IF EXISTS
		(
		SELECT TOP 1 * FROM ReceiptBillIndex 
		WHERE BillNumberId = @Bid and BillType=@billtype
		AND RedWord = 0 
		AND ((IfCheck = 't' AND isini<>1 )OR (IfCheck='f' AND isini=1 )) --isini=1表示期初单据 期初单据特殊处理
		AND AlertDay <> 9999
		)
			BEGIN
				UPDATE	ReceiptBillIndex SET AlertDay = 9999 WHERE BillNumberId = @Bid		
				IF @@ROWCOUNT <> 0
					RETURN 0
				ELSE
					RETURN 1
			END
		ELSE
			RETURN -1
	END














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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


/*
实物库存期初入出/库单保存
2016-07-16
*/
CREATE   PROCEDURE GP_PhysicalIndexSave
(	
	@details Tb_PhysicalBill READONLY,
	@typeid VARCHAR(50),
	@ktypeid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON 


--删除原来的数据
DELETE IniFactStocks WHERE PtypeId=@typeid AND KtypeId=@ktypeid
DELETE IniFactStocks_Qty WHERE PtypeId=@typeid AND KTypeID=@ktypeid
DELETE dbo.gp_iniFactPtypeSerial WHERE PtypeID = @typeid AND KtypeID = @ktypeid


--插入到主表
INSERT INTO IniFactStocks(PtypeId,KtypeId,Qty)
SELECT @typeid AS typeid,@ktypeid AS KtypeId,SUM(Qty) FROM @details WHERE QTY <> 0

--插入到详细表
INSERT INTO IniFactStocks_Qty(PtypeId,KtypeId,CargoID,ItemID,Qty,GoodsNumber,ProduceDate,ValidDate,Iscombined,NQty)
SELECT @typeid AS typeid,@ktypeid AS KtypeId,CargoID,ItemID,Qty,GoodsNumber,ProduceDate,ValidDate,Iscombined,NQty FROM @details WHERE (QTY <> 0 OR NQty <>0)

--插入到序列表
DECLARE @serial VARCHAR(max);
DECLARE @itemId INT;
DECLARE @goodsNumber VARCHAR(max);
DECLARE @IsCombined int;
DECLARE @ValidDate VARCHAR(50);
DECLARE @ProduceDate VARCHAR(50);
DECLARE @index INT = 1;
DECLARE @CargoId INT;
DECLARE CURSORT CURSOR FOR
SELECT goodsNumber, itemId, IsCombined, ProduceDate, ValidDate, Serial, CargoId FROM @details
OPEN CURSORT
FETCH NEXT FROM CURSORT INTO @goodsNumber,@itemId ,@IsCombined ,@ProduceDate ,@ValidDate, @serial, @CargoId
WHILE @@FETCH_STATUS = 0

BEGIN 
IF @Serial <> ''
BEGIN
IF(CHARINDEX('я',@Serial)=1)
BEGIN
	SET @Serial = SUBSTRING(@Serial,2,LEN(@Serial)-1)
END
			
INSERT INTO dbo.gp_iniFactPtypeSerial
        ( Serial ,
          KtypeID ,
          PtypeID ,
          InKtypeTime ,
          OutKtypeTime ,
          State ,
          Flag ,
          CommissionState ,
          iniFlag,
          ETypeID ,
          GoodsOrder ,
          GoodsNumber ,
          STypeId ,
          Comment1 ,
          ItemID ,
          IsCombined ,
          CargoID,
          ProduceDate ,
          ValidDate
        )
        SELECT a AS 'Serial',@ktypeid,@typeid,convert(varchar(10),getdate(),120),NULL,1,1,'', @index,'',0,ISNULL(@goodsNumber,''), (SELECT TOP 1 STypeID FROM dbo.Stock WHERE typeId = @ktypeid AND deleted = 0),'',ISNULL(@itemId, 0), ISNULL(@IsCombined, 0)
        ,@CargoId, ISNULL(@ProduceDate, ''), ISNULL(@ValidDate, '')
        FROM dbo.f_split(@serial, 'я')
			
SET @index = @index + 1;

END
ELSE
BEGIN
SET @index = @index + 1;
END
FETCH NEXT FROM CURSORT INTO @goodsNumber,@itemId ,@IsCombined ,@ProduceDate ,@ValidDate, @serial,@CargoId
		
END
CLOSE CURSORT
DEALLOCATE CURSORT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


--SELECT * FROM dbo.IniFactStocks
--SELECT * FROM dbo.IniFactStocks_Qty
--SELECT * FROM dbo.gp_iniFactPtypeSerial
--SELECT * FROM dbo.ptype 




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
实物库存期初查询
*/
CREATE PROCEDURE Gp_PhyStockIni
(
	@OperatorID varchar(50),  	    	--操作员ID号
	@typeid   	varchar(50)='00000',    --商品的父节点号
	@KtypeId  	varchar(1550)='',       --仓库id号
	@UserCode 	varchar(26)='',			--商品编号
	@FullName 	varchar(66)='',			--商品名称
	@ifLine		char(1) ='0',                  -- 0 代表树形表，1代表线性表
	@stypeid	VARCHAR(8000)
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @ssql NVARCHAR(MAX)='' --用于分支机构
DECLARE @Sql VARCHAR(8000)   ---加速库存状况查询
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
---------------检查是否开帐
DECLARE @IniCanModIFy VARCHAR(10)
SELECT @IniCanModIFy=subValue FROM sysdata WHERE SubName='inicanmodIFy'
---------------上步结束
IF @UserCode='' SET @UserCode='%' ELSE SET @UserCode='%'+@UserCode+'%'
IF @FullName='' SET @FullName='%' ELSE SET @FullName='%'+@FullName+'%'


CREATE TABLE #Ptype (TypeID varchar(50),Usercode varchar(200),fullname varchar(200))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,deleted int,parid VARCHAR(100),SortID INT)

INSERT INTO #Ptype(typeid,usercode,fullname) select P.typeid,usercode,fullname from ptype P, F_GetManDetailPType(@OperatorID) W WHERE P.typeid=W.typeid AND p.IsService = 0

DECLARE @Ksonnum int
SET @Ksonnum =0
IF @KtypeId=''
BEGIN
	INSERT INTO #Ktype select ks.typeid from F_GetManDetailKTypeSType(@OperatorID) ks
	SET @Ksonnum =1
END
ELSE
BEGIN
    --仓库
    INSERT INTO #Ktype(typeid) 
    select kb.TypeId  from F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorID) kb
	IF charindex(',',@KtypeId)>1
		SET @Ksonnum=1
	ELSE
		SELECT @Ksonnum =sonnum FROM Stock where typeid =@KtypeId
END


CREATE CLUSTERED INDEX CIX_k ON #Ktype(typeid)
DECLARE @sonnum INT
SET @sonnum =0
SELECT @sonnum = sonnum FROM Ptype WHERE Typeid=@typeid


IF @ifLine =1 -- 线性表  --cld
BEGIN   
		IF @typeid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId FROM Ptype p
			where typeid in (select typeid from F_GetManDetailPType(@OperatorID))  And p.typeid<>'00000'
			AND p.IsService = 0
			AND p.iscombinationproduct=0
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId FROM Ptype p
			where typeid in (select typeid from F_GetManDetailPType(@OperatorID) where typeid like @typeid+'%')  And p.typeid<>'00000'
			AND p.IsService = 0
			AND p.iscombinationproduct=0
END
ELSE
BEGIN
	IF @sonnum =0 	
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid) 
		SELECT DISTINCT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where typeid =@typeid) a where p.typeid=a.typeid And p.typeid<>'00000'
		AND p.IsService = 0
		AND p.iscombinationproduct=0
	ELSE
		IF @typeid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid,SortID) 
			SELECT DISTINCT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId ,p.SortID FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid And p.typeid<>'00000'
			AND p.IsService = 0
			AND p.iscombinationproduct=0
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid,SortID)  
			SELECT DISTINCT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId ,p.SortID FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid=@typeid) a where p.typeid=a.typeid And p.typeid<>'00000'
			AND p.IsService = 0
			AND p.iscombinationproduct=0

END

-- 哪果ktyeid为'',stypeid不为''，则是全选的情况，现在全选还要看分支机构，所以再排除一下
IF @stypeid<>''
BEGIN
	SET @ssql=';WITH cte AS(
		SELECT typeid,parid FROM Stype WHERE Typeid IN ('''+REPLACE(@stypeid,',',''',''')+''')
		UNION ALL
		SELECT a.typeid,a.parid FROM stype a JOIN cte b ON a.parid=b.typeid
	) DELETE FROM #Ktype WHERE typeid NOT IN (SELECT v.TypeId FROM cte W JOIN Stock v ON W.typeid=v.stypeid )';
	EXEC(@ssql);
END

---------------------------------期初
CREATE CLUSTERED INDEX IX_TEMP ON  #MainType(TYPEID)	
DECLARE @TMP VARCHAR(8000)


SET @TMP='
SELECT 
	p.typeid,
	ISNULL(p1.GQty,0)as	GQty
INTO #A
FROM  dbo.ptype  p LEFT JOIN (
SELECT	 A.TypeId,	dbo.F_RoundQty(SUM(G.Qty) ) AS GQty	FROM	IniFactStocks  G
 INNER JOIN #PType A ON G.PTypeId = A.TypeId '
IF NOT (@KtypeId = '' AND @MKTypeId = '00001')
      SELECT @TMP=@TMP + '  INNER JOIN #Ktype K ON  G.KtypeID = K.typeid '
SELECT @TMP=@TMP + ' WHERE	
					 A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
							AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
					GROUP BY A.TypeId
					) p1 ON p1.TypeId = p.typeId
					WHERE p.iscombinationproduct=0 AND
					p.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
							AND p.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'  
					CREATE CLUSTERED INDEX IX_TEMP ON  #A(TYPEID)'		

IF @ifLine=1
BEGIN
	 SELECT @Sql=@TMP+'

	SELECT 	a.typeid,
			a.fullname,
			a.usercode,
			a.sonnum,
			dbo.F_RoundQty( ISNULL(SUM(Z.Gqty),0)  )AS qty,			
	'+Convert(varchar(10),@Ksonnum)+' as ksonnum,
			a.parid
    FROM 	#MainType a
	INNER JOIN	#A  Z ON  z.TypeId = A.TypeId
			WHERE 1=1 ' 
	
IF @ifLine ='1'
	SET @SQL = @SQL + ' AND a.sonnum = 0 '	
  SET @SQL = @SQL + '
			AND A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
			AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
	GROUP BY
			a.typeid,
			a.fullname,
			a.usercode,
			a.sonnum,
			a.parid
	ORDER BY A.UserCode 
	'	

END	
ELSE
BEGIN
	SELECT @Sql=@TMP+'

		SELECT 	a.typeid,
				a.fullname,
				a.usercode,
				a.sonnum,
				dbo.F_RoundQty( ISNULL(SUM(Z.Gqty),0)  ) AS qty,				
		'+Convert(varchar(10),@Ksonnum)+' as ksonnum,
				a.parid
		FROM 	#MainType a
		LEFT JOIN	#A  Z ON 
				 z.TypeId like A.TypeId+''%''
				WHERE 1=1 ' 
		
	IF @ifLine ='1'
		SET @SQL = @SQL + ' AND a.sonnum = 0 '	
	  SET @SQL = @SQL + '
				AND A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
				AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
		GROUP BY
				a.typeid,
				a.fullname,
				a.usercode,
				a.sonnum,
				a.parid,
				a.SortID
		ORDER BY A.SortID asc 
		'	--cld
END


PRINT @SQL						
EXEC(@SQL)
DROP TABLE #Ptype,#Ktype,#MainType




--declare @sql nvarchar(max)
--set @sql=N'select p.typeId,p.FullName,p.UserCode,isnull(i.Qty,0) as Qty from ptype p left join  IniFactStocks i on p.typeId=i.PtypeId  '
--if not(@ktypeid <> '')
--set @sql=@sql+'where i.KtypeId='+@ktypeid+' and p.fullname LIKE '+char(39)+'%'+@fullname+'%'+char(39)+' and usercode like '+char(39)+'%'+@UserCode+'%'+char(39)+''
--exec (@sql);


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'Gp_PmPriceInfo')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE Gp_PmPriceInfo
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	时间：2014-068-10 
	作者：唐韬
	描述：导入商品物价信息
	
	时间：2016-11-8
	修改：舒珊
	描述：导入商品物价信息加入“计量单位编号”、“计量单位名称”
	
	时间：2017-01-11
	修改：舒珊
	描述：这个地方 不管系统配置 更改基本单位预设价格自动更改其他，不换算非基本单位的数据
	      多单位导入的时候在 商品档案那就有初始记录了，所以这不需要再insert
	

*/
CREATE    PROCEDURE Gp_PmPriceInfo
    (
      @UserCode [varchar](200) ,
      @FullName [varchar](200) ,
      @UUserCode [varchar](200) ,
      @UFullName [varchar](200) ,
      @StrPreBuyPrice1 [VARCHAR](25) ,
      @StrPreBuyPrice2 [VARCHAR](25) ,
      @StrPreBuyPrice3 [VARCHAR](25) ,
      @StrPreBuyPrice4 [VARCHAR](25) ,
      @StrPreBuyPrice5 [VARCHAR](25) ,
      @StrTopBuyPrice [VARCHAR](25) ,
      @StrPreSalePrice1 [VARCHAR](25) ,
      @StrPreSalePrice2 [VARCHAR](25) ,
      @StrPreSalePrice3 [VARCHAR](25) ,
      @StrPreSalePrice4 [VARCHAR](25) ,
      @StrPreSalePrice5 [VARCHAR](25) ,
      @StrPreSalePrice6 [VARCHAR](25) ,
      @StrPreSalePrice7 [VARCHAR](25) ,
      @StrPreSalePrice8 [VARCHAR](25) ,
      @StrPreSalePrice9 [VARCHAR](25) ,
      @StrPreSalePrice10 [VARCHAR](25) ,
      @StrReferprice [VARCHAR](25) ,
      @StrRetailPrice [VARCHAR](25) ,
      @StrTopSalePrice [VARCHAR](25) ,
      @StrLowSalePrice [VARCHAR](25) ,
      @ErrMsg VARCHAR(200) OUTPUT 
    )
--@encode$--    
AS 
SET NOCOUNT ON

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

IF(@UserCode = '' AND @FullName ='')
BEGIN
	SET @ErrMsg = '商品编号和商品名称不能同时为空'
	RETURN -1
END
ELSE IF(@UserCode <> '' AND NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @UserCode) OR @UserCode='0')
BEGIN
	SET @ErrMsg = '商品编号不存在'
	RETURN -1
END
ELSE IF (@FullName <> '' AND NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @FullName) OR @FullName='全部商品')
BEGIN
	SET @ErrMsg = '商品名称不存在'
	RETURN -1
END
ELSE IF(@FullName NOT IN (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @UserCode) AND @FullName <> '' AND @UserCode <> '')
BEGIN
	SET @ErrMsg = '商品编号与商品名称不匹配'
	RETURN -1
END

--“计量单位编号” (必填)、“计量单位名称”
IF(@UUserCode = '')
BEGIN
	SET @ErrMsg = '计量单位编号不能为空'
	RETURN -1
END
ELSE IF(@UUserCode <> '' AND NOT EXISTS(SELECT UnitsID FROM dbo.PType_units WHERE UserCode = @UUserCode) OR @UUserCode='0')
BEGIN
	SET @ErrMsg = '计量单位编号不存在'
	RETURN -1
END
ELSE IF (@UFullName <> '' AND NOT EXISTS(SELECT UnitsID FROM dbo.PType_units WHERE FullName = @UFullName))
BEGIN
	SET @ErrMsg = '计量单位名称不存在'
	RETURN -1
END
ELSE IF(@UUserCode <> '' AND NOT EXISTS(SELECT 1  FROM dbo.PType_Units_Ext pe INNER JOIN dbo.PType_Units pu ON pu.UnitsId = pe.UnitsId
INNER JOIN ptype p ON p.typeId = pe.PtypeID
WHERE pu.UserCode = @UUserCode AND p.UserCode=@UserCode))
BEGIN
	SET @ErrMsg = '导入商品不存在该计量单位'
	RETURN -1
END
ELSE IF(@UFullName NOT IN (SELECT TOP 1 fullname FROM dbo.PType_units WHERE UserCode = @UUserCode) AND @UFullName <> '' AND @UUserCode <> '')
BEGIN
	SET @ErrMsg = '计量单位编号与计量单位名称不匹配'
	RETURN -1
END

	DECLARE @d_price   VARCHAR(5),  --  单价小数位数  2    
			@d_price1  INT  ;      
    DECLARE @PTypeID VARCHAR(50),@maxPrice NUMERIC =  9999999999.9999999999
    SELECT @d_price            = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemId = 2
    SET @d_price1              = CONVERT(INT,@d_price)
    SELECT TOP 1  @PTypeID = typeId   FROM dbo.ptype WHERE UserCode = @UserCode 
    --AND FullName = @FullName
    
	DECLARE @UNITSID		INT=-1,
			@IsDefaultUnit	INT=-1,
			@RateType		int=-1;
	
	SELECT @UNITSID=E.UNITSID,
		   @IsDefaultUnit=E.IsDefaultUnit,
		   @RateType=E.RateType
	FROM PType_units_EXT E
	INNER JOIN PType_units U ON E.UNITSID=U.UNITSID
	WHERE E.PTYPEID=@PTypeID AND U.USERCODE=@UUserCode
	
IF(@RateType<>0)
BEGIN
	SET @ErrMsg = '计量单位不能为浮动单位'
	RETURN -1
END

    
    DECLARE @PreBuyPrice1  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice1 = '' ) 
        SET @PreBuyPrice1 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice1) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价1请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice1) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价1不能为负数'
                    RETURN -1
                END
            ELSE 
				BEGIN 
					IF( @d_price1 <( len(@StrPreBuyPrice1)-charindex('.',@StrPreBuyPrice1))AND charindex('.',@StrPreBuyPrice1) > 0)
					BEGIN
						SET @ErrMsg = '预设进价1小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SELECT  @PreBuyPrice1 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice1)
					IF(@PreBuyPrice1 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价1最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreBuyPrice2  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice2 = '' ) 
        SET @PreBuyPrice2 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice2) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价2请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice2) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价2不能为负数'
                    RETURN -1
                END
            ELSE 
				BEGIN
					IF( @d_price1 <( len(@StrPreBuyPrice2)-charindex('.',@StrPreBuyPrice2))AND charindex('.',@StrPreBuyPrice2) > 0)
					BEGIN
						SET @ErrMsg = '预设进价2小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreBuyPrice2 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice2)
					IF(@PreBuyPrice2 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价2最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END
                

    DECLARE @PreBuyPrice3  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice3 = '' ) 
        SET @PreBuyPrice3 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice3) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价3请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice3) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价3不能为负数'
                    RETURN -1
                END
            ELSE               
                BEGIN
					IF( @d_price1 <( len(@StrPreBuyPrice3)-charindex('.',@StrPreBuyPrice3))AND charindex('.',@StrPreBuyPrice3) > 0)
					BEGIN
						SET @ErrMsg = '预设进价3小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreBuyPrice3 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice3)
					IF(@PreBuyPrice3 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价3最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreBuyPrice4  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice4 = '' ) 
        SET @PreBuyPrice4 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice4) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价4请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice4) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价4不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreBuyPrice4)-charindex('.',@StrPreBuyPrice4))AND charindex('.',@StrPreBuyPrice4) > 0)
					BEGIN
						SET @ErrMsg = '预设进价4小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreBuyPrice4 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice4)
					IF(@PreBuyPrice4 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价4最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreBuyPrice5  NUMERIC(24, 10) 
    IF ( @StrPreBuyPrice5 = '' ) 
        SET @PreBuyPrice5 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreBuyPrice5) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设进价5请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreBuyPrice5) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设进价5不能为负数'
                    RETURN -1
                END
            ELSE     
                BEGIN
					IF( @d_price1 <( len(@StrPreBuyPrice5)-charindex('.',@StrPreBuyPrice5))AND charindex('.',@StrPreBuyPrice5) > 0)
					BEGIN
						SET @ErrMsg = '预设进价5小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreBuyPrice5 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice5)
					IF(@PreBuyPrice5 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设进价5最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @TopBuyPrice  NUMERIC(24, 10) 
    IF ( @StrTopBuyPrice = '' ) 
        SET @TopBuyPrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrTopBuyPrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最高进价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrTopBuyPrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最高进价不能为负数'
                    RETURN -1
                END
            ELSE            
                BEGIN
					IF( @d_price1 <( len(@StrTopBuyPrice)-charindex('.',@StrTopBuyPrice))AND charindex('.',@StrTopBuyPrice) > 0)
					BEGIN
						SET @ErrMsg = '最高进价小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @TopBuyPrice = CONVERT( NUMERIC(24, 10) , @StrTopBuyPrice)
					IF(@TopBuyPrice > @maxPrice)
					BEGIN
						SET @ErrMsg = '最高进价最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice1  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice1 = '' ) 
        SET @PreSalePrice1 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice1) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价1请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice1) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价1不能为负数'
                    RETURN -1
                END
            ELSE  
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice1)-charindex('.',@StrPreSalePrice1))AND charindex('.',@StrPreSalePrice1) > 0)
					BEGIN
						SET @ErrMsg = '预设售价1小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice1 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice1)
					IF(@PreSalePrice1 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价1最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice2  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice2 = '' ) 
        SET @PreSalePrice2 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice2) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价2请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice2) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价2不能为负数'
                    RETURN -1
                END
            ELSE 
                
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice2)-charindex('.',@StrPreSalePrice2))AND charindex('.',@StrPreSalePrice2) > 0)
					BEGIN
						SET @ErrMsg = '预设售价2小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice2 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice2)
					IF(@PreSalePrice2 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价2最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice3  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice3 = '' ) 
        SET @PreSalePrice3 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice3) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价3请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice3) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价3不能为负数'
                    RETURN -1
                END
            ELSE 
                
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice3)-charindex('.',@StrPreSalePrice3))AND charindex('.',@StrPreSalePrice3) > 0)
					BEGIN
						SET @ErrMsg = '预设售价3小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice3 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice3)
					IF(@PreSalePrice3 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价3最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice4  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice4 = '' ) 
        SET @PreSalePrice4 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice4) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价4请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice4) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价4不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice4)-charindex('.',@StrPreSalePrice4))AND charindex('.',@StrPreSalePrice4) > 0)
					BEGIN
						SET @ErrMsg = '预设售价4小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice4 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice4)
					IF(@PreSalePrice4 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价4最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice5  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice5 = '' ) 
        SET @PreSalePrice5 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice5) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价5请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice5) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价5不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice5)-charindex('.',@StrPreSalePrice5))AND charindex('.',@StrPreSalePrice5) > 0)
					BEGIN
						SET @ErrMsg = '预设售价5小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice5 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice5)
					IF(@PreSalePrice5 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价5最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice6  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice6 = '' ) 
        SET @PreSalePrice6 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice6) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价6请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice6) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价6不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice6)-charindex('.',@StrPreSalePrice6))AND charindex('.',@StrPreSalePrice6) > 0)
					BEGIN
						SET @ErrMsg = '预设售价6小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice6 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice6)
					IF(@PreSalePrice6 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价6最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice7  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice7 = '' ) 
        SET @PreSalePrice7 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice7) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价7请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice7) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价7不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice7)-charindex('.',@StrPreSalePrice7))AND charindex('.',@StrPreSalePrice7) > 0)
					BEGIN
						SET @ErrMsg = '预设售价7小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice7 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice7)
					IF(@PreSalePrice7 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价7最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice8  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice8 = '' ) 
        SET @PreSalePrice8 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice8) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价8请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( ( SELECT   CHARINDEX('-', @StrPreSalePrice8)
                 ) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价8不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice8)-charindex('.',@StrPreSalePrice8))AND charindex('.',@StrPreSalePrice8) > 0)
					BEGIN
						SET @ErrMsg = '预设售价8小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice8 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice8)
					IF(@PreSalePrice8 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价8最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice9  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice9 = '' ) 
        SET @PreSalePrice9 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice9) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价9请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice9) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价9不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice9)-charindex('.',@StrPreSalePrice9))AND charindex('.',@StrPreSalePrice9) > 0)
					BEGIN
						SET @ErrMsg = '预设售价9小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice9 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice9)
					IF(@PreSalePrice9 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价9最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @PreSalePrice10  NUMERIC(24, 10) 
    IF ( @StrPreSalePrice10 = '' ) 
        SET @PreSalePrice10 = 0
    ELSE 
        IF ( ISNUMERIC(@StrPreSalePrice10) <> 1 ) 
            BEGIN
                SET @ErrMsg = '预设售价10请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrPreSalePrice10) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '预设售价10不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrPreSalePrice10)-charindex('.',@StrPreSalePrice10))AND charindex('.',@StrPreSalePrice10) > 0)
					BEGIN
						SET @ErrMsg = '预设售价10小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @PreSalePrice10 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice10)
					IF(@PreSalePrice10 > @maxPrice)
					BEGIN
						SET @ErrMsg = '预设售价10最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END
    
    DECLARE @Referprice  NUMERIC(24, 10) 
    IF ( @StrReferprice = '' ) 
        SET @Referprice = 0
    ELSE 
        IF ( ISNUMERIC(@StrReferprice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '参考成本请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrReferprice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '参考成本不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrReferprice)-charindex('.',@StrReferprice))AND charindex('.',@StrReferprice) > 0)
					BEGIN
						SET @ErrMsg = '参考成本小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @Referprice = CONVERT( NUMERIC(24, 10) , @StrReferprice)
					IF(@Referprice > @maxPrice)
					BEGIN
						SET @ErrMsg = '参考成本最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @RetailPrice  NUMERIC(24, 10) 
    IF ( @StrRetailPrice = '' ) 
        SET @RetailPrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrRetailPrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '零售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrRetailPrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '零售价不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrRetailPrice)-charindex('.',@StrRetailPrice))AND charindex('.',@StrRetailPrice) > 0)
					BEGIN
						SET @ErrMsg = '零售价小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @RetailPrice = CONVERT( NUMERIC(24, 10) , @StrRetailPrice)
					IF(@RetailPrice > @maxPrice)
					BEGIN
						SET @ErrMsg = '零售价最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @TopSalePrice  NUMERIC(24, 10) 
    IF ( @StrTopSalePrice = '' ) 
        SET @TopSalePrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrTopSalePrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最高售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrTopSalePrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最高售价不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrTopSalePrice)-charindex('.',@StrTopSalePrice))AND charindex('.',@StrTopSalePrice) > 0)
					BEGIN
						SET @ErrMsg = '最高售价小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @TopSalePrice = CONVERT( NUMERIC(24, 10) , @StrTopSalePrice)
					IF(@TopSalePrice > @maxPrice)
					BEGIN
						SET @ErrMsg = '最高售价最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

    DECLARE @LowSalePrice  NUMERIC(24, 10) 
    IF ( @StrLowSalePrice = '' ) 
        SET @LowSalePrice = 0
    ELSE 
        IF ( ISNUMERIC(@StrLowSalePrice) <> 1 ) 
            BEGIN
                SET @ErrMsg = '最低售价请输入数字'
                RETURN -1
            END
        ELSE 
            IF ( CHARINDEX('-', @StrLowSalePrice) <> 0 ) 
                BEGIN
                    SET @ErrMsg = '最低售价不能为负数'
                    RETURN -1
                END
            ELSE 
                BEGIN
					IF( @d_price1 <( len(@StrLowSalePrice)-charindex('.',@StrLowSalePrice))AND charindex('.',@StrLowSalePrice) > 0)
					BEGIN
						SET @ErrMsg = '最低售价小数位数大于' +@d_price+'位，不允许导入'
						RETURN -1
					END
					SET @LowSalePrice = CONVERT( NUMERIC(24, 10) , @StrLowSalePrice)
					IF(@LowSalePrice > @maxPrice)
					BEGIN
						SET @ErrMsg = '最低售价最大单价不能大于9999999999.9999999999'
						RETURN -1
					END
                END

  
----------------------------------------------------------------------------------------------
   IF EXISTS(SELECT TOP 1 1 FROM PType_Price WHERE PTYPEID= @PTypeID AND UNITID=@UNITSID)
		UPDATE  dbo.PType_Price
		SET     PreBuyPrice1 = @PreBuyPrice1 ,
				PreBuyPrice2 = @PreBuyPrice2 ,
				PreBuyPrice3 = @PreBuyPrice3 ,
				PreBuyPrice4 = @PreBuyPrice4 ,
				PreBuyPrice5 = @PreBuyPrice5 ,
				TopBuyPrice =  @TopBuyPrice ,
				PreSalePrice1 = @PreSalePrice1 ,
				PreSalePrice2 = @PreSalePrice2 ,
				PreSalePrice3 = @PreSalePrice3 ,
				PreSalePrice4 = @PreSalePrice4 ,
				PreSalePrice5 = @PreSalePrice5 ,
				PreSalePrice6 = @PreSalePrice6 ,
				PreSalePrice7 = @PreSalePrice7 ,
				PreSalePrice8 = @PreSalePrice8 ,
				PreSalePrice9 = @PreSalePrice9 ,
				PreSalePrice10 = @PreSalePrice10 ,
				RetailPrice = @RetailPrice ,
				LowSalePrice = @LowSalePrice ,
				TopSalePrice = @TopSalePrice ,
				ReferPrice = @ReferPrice,
				UNITID=@UNITSID,
				IsDefaultUnit=@IsDefaultUnit
		WHERE   PTypeID = @PTypeID
		AND		UNITID=@UNITSID
	ELSE
		INSERT INTO dbo.PType_Price
        ( 
          PtypeID,
          UnitId,
          PreBuyPrice1 ,
          PreBuyPrice2 ,
          PreBuyPrice3 ,
          PreBuyPrice4 ,
          PreBuyPrice5 ,
          PreSalePrice1 ,
          PreSalePrice2 ,
          PreSalePrice3 ,
          PreSalePrice4 ,
          PreSalePrice5 ,
          PreSalePrice6 ,
          PreSalePrice7 ,
          PreSalePrice8 ,
          PreSalePrice9 ,
          PreSalePrice10 ,
          RetailPrice ,
          TopSalePrice ,
          LowSalePrice ,  
          TopBuyPrice  ,
          ReferPrice ,
          IsDefaultUnit
        )
	 SELECT  
			@PTypeID,
			@UNITSID,
			@PreBuyPrice1,
			@PreBuyPrice2,
			@PreBuyPrice3,
			@PreBuyPrice4,
			@PreBuyPrice5,
			@PreSalePrice1, 
			@PreSalePrice2,
			@PreSalePrice3,
			@PreSalePrice4,
			@PreSalePrice5,
			@PreSalePrice6,
			@PreSalePrice7,
			@PreSalePrice8,
			@PreSalePrice9,
			@PreSalePrice10,
			@RetailPrice ,
			@TopSalePrice ,
			@LowSalePrice ,  
			@TopBuyPrice ,
			@ReferPrice ,
			@IsDefaultUnit 
			
	--非基本单位 的 其他价格全部为0 则删除不保存到表里面
	DELETE   ptype_price 
	where	 ptypeid=@ptypeid
		and  IsDefaultUnit=0
	    and isnull( [PreBuyPrice1] ,0)=0 
		and isnull( [PreBuyPrice2] ,0)=0 
		and isnull( [PreBuyPrice3] ,0)=0 
		and isnull( [PreBuyPrice4] ,0)=0 
		and isnull( [PreBuyPrice5] ,0)=0 
		and isnull( [PreSalePrice1] ,0)=0 
		and isnull( [PreSalePrice2] ,0)=0 
		and isnull( [PreSalePrice3] ,0)=0 
		and isnull( [PreSalePrice4] ,0)=0 
		and isnull( [PreSalePrice5] ,0)=0 
		and isnull( [PreSalePrice6] ,0)=0 
		and isnull( [PreSalePrice7] ,0)=0 
		and isnull( [PreSalePrice8] ,0)=0 
		and isnull( [PreSalePrice10] ,0)=0 
		and isnull( [RetailPrice] ,0)=0 
		and isnull( [TopSalePrice] ,0)=0 
	    and isnull( [LowSalePrice] ,0)=0 
	    and isnull( TopBuyPrice,0)=0 
		and isnull( ReferPrice,0)=0 
		and isnull( RecAmgSTypeBuyPrice,0)=0
		and isnull( RecAmgSTypeSalePrice,0)=0
		
		
	DECLARE @XiWaMaxNumber INT
	SELECT @XiWaMaxNumber = MAX(XiWaMaxNumber)+1 FROM ptype
    Update dbo.ptype Set XiWaMaxNumber = @XiWaMaxNumber WHERE TypeID=@ptypeid
	select @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
	update PType_Price set XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@PTypeID
    IF @@ERROR <>0
    BEGIN
        SET @ErrMsg = '导入失败'
        RETURN -1
    END


GO





IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_PosAllotApplyBillIndexSave]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_PosAllotApplyBillIndexSave]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
CREATE PROC Gp_PosAllotApplyBillIndexSave
(
	@BillNumberId		INT,
	@BillType			INT,
	@BillCode			VARCHAR(200),
    @BillDate			DATETIME,
    @ApplyEtypeId		VARCHAR(200),
    @StypeId			VARCHAR(50),
    @DtypeId			VARCHAR(50),
    @KtypeId			VARCHAR(50),
    @InKtypeId			VARCHAR(50),
    @Qty				NUMERIC(24,10),
    @Total				NUMERIC(24,10),
    @Comment			VARCHAR(256),
    @Explain			VARCHAR(256),
    @BillState			INT,			--0未引用、1已引用未完成、2验收完成  
    @checkE				VARCHAR(200), 
    @IsAutoGenerate     INT = 0,
    @BillOver           INT,
    @StopReason			VARCHAR(256),
    @Isdone             INT,
    @checkTime          DATETIME,
    @RedWord            INT,
    @ifcheck            char(1),
    @Draft              int,
    @Checker            VARCHAR(200), 
    @CheckerTime        DATETIME,
    @Updater            VARCHAR(200),
    @UpdaterTime        DATETIME,
    @IsIni              int,
    @Cid				int,		--币种 默认为1(本位币)
    @WarehouseOutDay    int,
    @LinkTel            VARCHAR(256),
    @LinkAddr           VARCHAR(256),
    @LinkMan            VARCHAR(256),
    @CostSale           INT,
    @IsNeedTransport    int,
    @ifYearBill         int,
    @AtId				INT,
    @PosId				INT = 0
)
--@encode$--
AS 
SET NOCOUNT ON
-- ********	判断是否试用版 - Start	********
    DECLARE @N INT ,
			@intVersion INT

	-- 判断版本号，是否试用版
    SELECT @N = CAST(SubValue AS INT) FROM SysData1 WHERE SubNo = 2	-- 版本号
	IF @N IS NULL RETURN -1
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 6 AND SubValue = '1')
		AND (EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 10 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 9 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 11 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 13 AND ISNULL(SubValue,'') = ''))		 
	RETURN -3	

    DECLARE @intBit INT,@intMask INT
    SELECT  @intBit = @N & 15
    SELECT  @intMask = POWER(2, @intBit) ^ POWER(2, @intBit + 1) ^ POWER(2,
                                                              @intBit + 2)
            ^ POWER(2, @intBit + 3) ^ POWER(2, @intBit + 4) ^ POWER(2,
                                                              @intBit + 5)
    SELECT  @intVersion = ( @intMask & @N ) / POWER(2, @intBit)
-- ********	判断是否试用版 - END	********
	DECLARE @Re INT ,@Flag INT
    EXEC @Re= Gp_Validate 2, @Flag OUTPUT
    IF @Re <> 0 
        RETURN -3 --检查程序版本错误

    IF @intVersion NOT IN ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ) 
        BEGIN
			--RAISERROR('校验错误 ！',16,1) 
            RETURN -3 --检查程序版本错误
        END 
        
	IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
	BEGIN
		DECLARE @billnumberidcount int
		SELECT @billnumberidcount=ISNULL(COUNT(billnumberid),0) FROM PosAllotApplyBillIndex
		
		IF @billnumberidcount >= 200
		BEGIN
			--RAISERROR('试用版最多录200条单据 ！',16,1) 
			RETURN -1
		END
	END         
        
	DECLARE @intReturn INT
	SET @intReturn = 0
	IF @BillNumberId=-1
	BEGIN
		INSERT INTO [dbo].[PosAllotApplyBillIndex]
				   ([BillType] ,[BillCode],[BillDate],[ApplyEtypeId],[StypeId],[DtypeId],[KtypeId],[InKtypeId],[Qty],[Total],[Comment],[Explain],[BillState],[checkE],[IsAutoGenerate]
                   ,[BillOver],[StopReason],[Isdone],[checkTime],[RedWord],[ifcheck],[draft],[Checker] ,[CheckerTime],[Updater],[UpdaterTime],[IsIni] ,[ifYearBill],[CID] ,[WarehouseOutDay],[LinkTel],[LinkAddr] ,[LinkMan],CostSale,IsNeedTransport,Atid,PosId )
			 VALUES
				   (@BillType,@BillCode,@BillDate,@ApplyEtypeId,@StypeId,@DtypeId,@KtypeId,@InKtypeId,dbo.F_RoundQty(@Qty) ,dbo.F_RoundTotal(@Total),@Comment,@Explain,@BillState,@checkE,@IsAutoGenerate
				   ,@BillOver,@StopReason,@Isdone,GETDATE(),@RedWord,@ifcheck,@Draft,@Checker,@CheckerTime,@Updater,@UpdaterTime,@IsIni,@ifYearBill,@Cid, @WarehouseOutDay ,@LinkTel ,@LinkAddr ,@LinkMan,@CostSale,@IsNeedTransport,@AtId,@PosId)
		IF @@rowcount = 0 OR @@error <> 0
			RETURN -5
		SELECT  @intReturn = SCOPE_IDENTITY();
	END
	ELSE
	BEGIN
			
				UPDATE [dbo].[PosAllotApplyBillIndex]
				   SET [BillType] = @BillType
						  ,[BillCode] = @BillCode 
						  ,[BillDate] = @BillDate
						  ,[ApplyEtypeId] = @ApplyEtypeId
						  ,[StypeId] = @StypeId
						  ,[DtypeId] = @DtypeId
						  ,[KtypeId] = @KtypeId 
						  ,[InKtypeId] = @InKtypeId 
						  ,[Qty] = dbo.F_RoundQty(@Qty) 
						  ,[Total]= dbo.F_RoundTotal(@Total)
						  ,[Comment] = @Comment 
						  ,[Explain] = @Explain
						  ,[BillState] = @BillState 
						  ,[checkE] = @checkE 
						  ,[IsAutoGenerate] = @IsAutoGenerate 
						  ,[BillOver] = @BillOver 
						  ,[StopReason] = @StopReason 
						  ,[Isdone] = @Isdone 
						  ,[checkTime] = @checkTime 
						  ,[RedWord] = @RedWord 
						  ,[ifcheck] = @ifcheck 
						  ,[draft] = @draft
						  ,[Checker] = @Checker 
						  ,[CheckerTime] = @CheckerTime 
						  ,[Updater] = @Updater
						  ,[UpdaterTime] = @UpdaterTime 
						  ,[IsIni] = @IsIni 
						  ,[ifYearBill] = @ifYearBill 
						  ,[CID]=@Cid
						  ,[WarehouseOutDay]=@WarehouseOutDay 
						  ,[LinkTel]= @LinkTel        
                          ,[LinkAddr] =@LinkAddr         
                          ,[LinkMan] =@LinkMan 
                          ,CostSale=@CostSale 
                          ,IsNeedTransport=@IsNeedTransport        
				WHERE BillNumberId=@BillNumberId AND BillState IN (0,1)
				SET @intReturn =@BillNumberId
				IF @@rowcount = 0 OR @@error <> 0
					RETURN -5
			END


	--单据编号重复的检测	
	IF EXISTS(SELECT TOP 1 1 FROM PosAllotApplyBillIndex WHERE BillNumberId <> @intReturn AND BillCode = @BillCode)
		AND EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'BillCodeAllowRepeat' AND Value = '0')
	BEGIN
		RETURN -9
	END
	
	   DECLARE @BeginDate DATETIME ,
        @szItem VARCHAR(30) ,
        @szVchCode VARCHAR(30)
        
    --EXEC Gp_GetSubValue 'period', @STypeID, @szPeriod OUT
    SELECT TOP 1
            @BeginDate = startdate
    FROM    monthproc
    WHERE   MonthNo='本期' AND STypeID=@STypeID
    
	   IF @BillType  IN ( 326,327,328,329) --AND @intNeed=0
        BEGIN
            IF @isini = 1 
            BEGIN
				--增加独立开账期初时间判断
				DECLARE @iniBegindate DATETIME  --取会计期间开始时间
				IF NOT EXISTS(SELECT TOP 1 1  FROM dbo.sysdata WHERE SubName='stypeindependentopen' AND SubValue=1)
				BEGIN
					SELECT @iniBegindate=fBegin FROM dbo.Ac_Period 
					WHERE FYear IN (SELECT subvalue FROM dbo.sysdata WHERE subname ='fyear' ) AND FPeriod IN (SELECT subvalue FROM dbo.sysdata WHERE SubName='fmonth')
				END
				ELSE
				BEGIN
					SELECT @iniBeginDate=fbegin FROM dbo.Ac_Period A,dbo.SType_UserConfig B
					WHERE A.FPeriod=b.SFPeriod AND A.FYear=B.SFYear AND B.StypeId= @STypeID
				END
				IF @billdate >= @iniBegindate 
					RETURN -8
			END
            IF @BillDate < @BeginDate AND @isini = 0 
                BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
                    RETURN -2
                END
                

	---根据配置检查过帐日期是否当前日期  完毕
        END
	RETURN @intReturn
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






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

/****** Object:  StoredProcedure [dbo].[Gp_PosBalanceListInfo]    Script Date: 07/27/2011 10:27:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011年7月27日 10:05
-- Description:	获取结存小票数据列表
-- =============================================
CREATE PROCEDURE [dbo].[Gp_PosBalanceListInfo]
    @startdate  VARCHAR(50),     --开始日期
	@enddate    VARCHAR(50),     --结束日期
	@stypeid    VARCHAR(50),  --分支机构ID
	@posname    VARCHAR(100),  --POS名称
	@OperatorId VARCHAR(100)   --登陆操作员
--@encode$--
AS
declare  @SQL varchar(max)
CREATE TABLE #STYPE(stypeid varchar(50))
INSERT INTO #STYPE SELECT * FROM dbo.f_split(@stypeid,',')
SET @SQL='SELECT a.PosVchCode as vchid,
				 b.UserCode as usercode,
				 b.FullName as fullname,
				 CAST(a.SaleDate AS datetime) as saledate,
				 a.BillCode as billcode,
				 a.Branchid as branchid,
				 a.KtypeID as ktypeid,
			     a.Cashier  as cashier,
			     c.fullname as cashiername,
				 a.Salesman as salesman,
				 d.fullname as salesmanrname 
		  FROM CommonPosSaleIndex a
		  INNER JOIN
		  commonposinfo b ON a.PosID=b.PosID
		  LEFT JOIN
		  employee c ON a.Cashier=c.typeid
		  LEFT JOIN
		  employee d ON a.Salesman=d.typeid
		  WHERE b.FullName like ''%'+@posname+'%''  and a.draft=0'
IF(@startdate<>'' AND @enddate<>'')
	SET @SQL=@SQL+' AND a.SaleDate>='''+@startdate+''' AND a.SaleDate<='''+@enddate+''''
IF(@stypeid<>'')
	SET @SQL=@SQL+ ' AND a.branchid IN(SELECT stypeid FROM #STYPE)'
ELSE
    SET @SQL=@SQL+ ' AND a.branchid=(SELECT STypeID  FROM employee WHERE Typeid='''+@OperatorId+''') '
    
SET @SQL=@SQL+' ORDER BY a.SaleDate DESC'
--print(@SQL)
EXEC(@SQL)
DROP TABLE #STYPE


GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:韩林
	日期:2012-12-19
	功能:pos机绑定Mac地址
*/

CREATE PROC Gp_PosBandingMac
(
	@posid int,
	@macAddr varchar(200),
	@msg VARCHAR(MAX) OUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @UserCode VARCHAR(max)='',@KUserCode VARCHAR(max)='',@IsBinding INT=0
SELECT @UserCode = p.UserCode,@KUserCode=k.UserCode FROM dbo.PosInfo p INNER JOIN dbo.Stock k ON p.ktypeid=k.typeid WHERE MacAddress=@macAddr AND IsBinding=1 AND PosID <>@posid

SELECT @IsBinding=IsBinding FROM dbo.PosInfo WHERE PosID=@posid AND MacAddress<>@macAddr

IF @UserCode <>''
BEGIN
	SET @msg='Pos机已经和仓库['+@KUserCode+']的Pos机号['+@UserCode+']绑定，请联系管理员！'
	RETURN 
END
ELSE IF @IsBinding=1
BEGIN
	SET @msg='该Pos机号已经被绑定，请联系管理员！'
	RETURN
END
ELSE
	UPDATE dbo.PosInfo SET MacAddress=@macAddr,IsBinding=1 WHERE PosID=@posid
	
IF @@ERROR<>0
	SET @msg= '绑定MAC地址失败！'
ELSE
	SET @msg= '绑定成功！'
RETURN	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
	SELECT * 
	FROM dbo.sysobjects 
	WHERE id = OBJECT_ID(N'[dbo].[GP_PosInfo_Check]') 
		AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
	DROP PROCEDURE [dbo].[GP_PosInfo_Check]
GO

CREATE PROCEDURE GP_PosInfo_Check (
	 @UserID	VARCHAR(50)
	,@TableName	VARCHAR(50)
	,@TypeIDs	VARCHAR(MAX)
	,@excludeTypeId VARCHAR(50)
	,@PosInfoTable Type_PosInfo READONLY
)
--@encode$--
AS 
SET NOCOUNT ON 

CREATE TABLE #TYPEIDSTable
(
	typeid VARCHAR(50)
)
IF(@tablename = 'gridA')
BEGIN
	INSERT INTO #TYPEIDSTable SELECT Ac.nTypeId a FROM f_split(@TypeIDs, ',') A INNER JOIN Ac_Items Ac on ac.nId = A.a
END
ELSE
BEGIN 
	INSERT INTO #TYPEIDSTable SELECT a FROM f_split(@TypeIDs, ',')
END 


CREATE TABLE #TYPEIDS
(
	typeid VARCHAR(50)
)
INSERT INTO #TYPEIDS( typeid ) SELECT typeid FROM @PosInfoTable
DELETE FROM #TYPEIDS WHERE typeid = @excludeTypeId



--IF EXISTS(SELECT * FROM @PosInfoTable WHERE Typeid =  @TypeID OR (Typeid LIKE 
--CASE 
--WHEN @TableName = 'PosEmployee' OR @TableName = 'POSOperator' OR @TableName = 'Btype' THEN LEFT(@TypeID,10)
--WHEN @TableName = 'Ptype' OR @TableName = 'PosAccount' THEN LEFT(@TypeID,5)
--END +'%' AND LEN(Typeid) < LEN(@TypeID) 
--AND LEFT(@TypeID,LEN(Typeid)) = Typeid 
--))


DECLARE @TypeID VARCHAR(50)
DECLARE UserRange_Cursor CURSOR FOR
SELECT typeid FROM #TYPEIDSTable
FOR READ ONLY
OPEN UserRange_Cursor
FETCH NEXT FROM UserRange_Cursor 
INTO @TypeID
WHILE @@FETCH_STATUS = 0
BEGIN
IF EXISTS(SELECT * FROM #TYPEIDS WHERE @TypeID LIKE typeid+'%')
BEGIN
	RETURN -2
END


DELETE FROM #TYPEIDS WHERE Typeid LIKE @TypeID+'%'
INSERT #TYPEIDS SELECT @TypeID


FETCH NEXT FROM UserRange_Cursor INTO @TypeID
END
CLOSE UserRange_Cursor
DEALLOCATE UserRange_Cursor


IF(@tablename ='gridE')
BEGIN
	SELECT UserCode,FullName,Eid,Comment AS remark,e.typeId,e.sonnum FROM dbo.employee e INNER JOIN #TYPEIDS p ON p.typeid = e.typeId
END 
ELSE IF(@tablename = 'gridO')
BEGIN
	SELECT e.UserCode,e.FullName,e.Eid AS OperatorId,d.FullName AS dfullname,job AS positionname,e.typeId AS typeid,d.sonnum  FROM dbo.employee e INNER JOIN dbo.Department d ON e.DtypeID = d.typeid INNER JOIN #TYPEIDS p ON p.typeid = e.typeId
END 
ELSE IF(@tablename = 'gridA')
BEGIN
	SELECT FullName,UserCode,nId,Comment AS remark,nTypeId AS typeid,a.SonNum FROM dbo.Ac_Items a INNER JOIN #TYPEIDS p ON p.typeid = a.nTypeId
END 
ELSE IF(@tablename = 'gridP')
BEGIN
	SELECT FullName,UserCode,Pid,Comment AS remark,Standard,Type,MultEntryCode AS entrycode,ptype.typeId,sonnum FROM dbo.ptype INNER JOIN #TYPEIDS p ON p.typeid = ptype.typeId
END 
ELSE IF(@tablename = 'gridB')
BEGIN
	SELECT FullName,UserCode,Bid,Comment AS remark,TelAndAddress AS address,b.typeId,b.sonnum FROM dbo.btype b INNER JOIN #TYPEIDS p ON p.typeid = b.typeId
END 
	
RETURN 0

DROP TABLE #TYPEIDS

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_PosRegisterAddDelMod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_PosRegisterAddDelMod]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

--执行POS登记的插入。
CREATE PROCEDURE [dbo].[Gp_PosRegisterAddDelMod]
    (
      @PosID VARCHAR(50),
      @UserCode VARCHAR(26),
      @FullName VARCHAR(66),
      @szBranchid VARCHAR(50),
      @szETypeId VARCHAR(50),
      @szStockid VARCHAR(50),
      @szBTypeId VARCHAR(50),
      @IsKeyset INT,   --会员卡号不支持键盘输入  0是 1否
      @IsHeadquartersStock INT,   --允许查看总部其它仓库库存 0是 1否
      @IsJoinStock INT,  --允许查看其它加盟商库存   0是 1否
      @IsTicketCount INT,  --0存为小票 --1直接过账 
      @PosPassword VARCHAR(25),
      @Comment VARCHAR(100),
      @ETypeId1 VARCHAR(50), --pos对应的管理员	
      @Type INT  --1为insert，2为mod
    )
--@encode$--
AS 
    IF @Type = 1 
        BEGIN
            SELECT  @PosID = MAX(ISNULL(PosID, 0))
            FROM    dbo.CommonPosInfo
            IF @PosID IS NULL 
                SET @PosID = 0
            SET @PosID = @PosID + 1
            SET @IsJoinStock = 0
            INSERT  INTO dbo.CommonPosInfo
                    (
                      PosID,
                      FullName,
                      UserCode,
                      Branchid,
                      ETypeId,
                      Stockid,
                      BTypeId,
                      deleted,
                      IsKeyset,
                      IsHeadquartersStock,
                      IsJoinStock,
                      PosPassword,
                      Comment,
                      IsTicketCount,
		      ETypeId1
                    )
            VALUES  (
                      RIGHT('00000' + CAST(@PosID AS VARCHAR), 5),
                      @FullName,
                      @UserCode,
                      @szBranchid,
                      @szETypeId,
                      @szStockid,
                      @szBTypeId,
                      0,
                      @IsKeyset,
                      @IsHeadquartersStock,
                      @IsJoinStock,
                      @PosPassword,
                      @Comment,
                      @IsTicketCount,
		      @ETypeId1
                    )
        END
    IF @Type = 2 
        BEGIN
            UPDATE  dbo.CommonPosInfo
            SET     FullName = @FullName,
                    UserCode = @UserCode,
                    Branchid = @szBranchid,
                    ETypeId = @szETypeId,
                    Stockid = @szStockid,
                    BTypeId = @szBTypeId,
                    IsKeyset = @IsKeyset,
                    IsHeadquartersStock = @IsHeadquartersStock,
                    PosPassword = @PosPassword,
                    Comment = @Comment,
                    IsTicketCount = @IsTicketCount,
		    ETypeId1=@ETypeId1
            WHERE   PosID = @PosID
        END
GO





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

/****** Object:  StoredProcedure [dbo].[Gp_PosRegisterGetBaseInfo]    Script Date: 07/19/2011 12:33:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011年7月18日
-- Description:	POS登记修改时获取登记数据
-- =============================================
CREATE PROCEDURE [dbo].[Gp_PosRegisterGetBaseInfo]
(
	  @posid varchar(50) --POS机ID 
)
--@encode$--
AS
BEGIN
declare @SQL  varchar(MAX)
Set @SQL='SELECT a.Posid,
                 a.fullname,
                 a.usercode,
                 a.branchid,
                 s.fullname as sfullname,
                 a.etypeid1 as etypeid,
                 e.fullname as efullname,
                 a.stockid,
                 k.FullName as kfullname,
                 a.btypeid,
                 b.FullName as bfullname,
                 a.iskeyset,
                 a.isheadquartersstock,
                 CASE a.isticketcount WHEN 1 THEN 0 ELSE 1 END  AS ispasscheck,
                 a.isticketcount,a.Comment 
         FROM commonposinfo a
         LEFT JOIN
               stype s ON a.branchid=s.typeid
         LEFT JOIN 
               employee e ON a.etypeid1=e.typeid
         LEFT JOIN 
               stock k ON a.Stockid=k.typeId
         LEFT JOIN 
               btype b ON a.BTypeId=b.typeId'
SET @SQL=@SQL+' WHERE posid='''+@posid+''''
--print @SQL
exec(@SQL)
END

GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_PosRegisterListInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_PosRegisterListInfo]
GO
/****** Object:  StoredProcedure [dbo].[Gp_PosRegisterListInfo]    Script Date: 07/19/2011 12:32:20 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011年7月18日
-- Description:	POS登记列表
-- =============================================
CREATE PROCEDURE [dbo].[Gp_PosRegisterListInfo]
(
	@stypeid   VARCHAR(100), --分支机构ID
	@usercode  VARCHAR(100), --POS编号
	@fullname  VARCHAR(100), --POS名称
	@etypeid   VARCHAR(100)  --管理员ID
)	
--@encode$--
AS

DECLARE @SQL AS VARCHAR(MAX)
CREATE TABLE #STYPE(stypeid varchar(50))
INSERT INTO #STYPE SELECT TypeId FROM F_GetAllBaseTypeId(@stypeid,11)
CREATE TABLE #ETYPE(etypeid varchar(50))
INSERT INTO #ETYPE SELECT TypeId FROM F_GetAllBaseTypeId(@etypeid,3)
SET @SQL='SELECT posid,
                 fullname,
                 usercode,
                 branchid,
                 etypeid1 as etypeid,
                 stockid,
                 btypeid,
                 CASE iskeyset WHEN 1 THEN 0 ELSE 1 END AS iskeyset,
                 CASE isheadquartersstock WHEN 1 THEN 0 ELSE 1 END AS isheadquartersstock,
                 isticketcount AS ispasscheck, 
                 CASE isticketcount WHEN 1 THEN 0 ELSE 1 END AS isticketcount,
                 Comment 
          FROM commonposinfo 
          WHERE deleted=0 AND usercode LIKE ''%'+@usercode+'%''  AND fullname LIKE ''%'+@fullname+'%''' 
IF(@stypeid<>'')
BEGIN
	SET @SQL=@SQL+ ' AND branchid in (select stypeid from #STYPE)'
END
IF(@etypeid<>'')
BEGIN
	SET @SQL=@SQL+ ' AND etypeid1 in (select etypeid from #ETYPE)'
END

SET @SQL=@SQL+' ORDER BY usercode ASC'
--print @SQL
EXEC(@SQL)


GO





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

/****** Object:  StoredProcedure [dbo].[Gp_PosRetailCashAddMod]    Script Date: 08/01/2011 15:07:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011年8月1日
-- Description:	零售收银新增修改
-- =============================================
CREATE PROCEDURE [dbo].[Gp_PosRetailCashAddMod] 
	@stypeid  varchar(50), --分支机构ID
	@cashatypeid varchar(50),--收现对应科目ID
	@bankatypeid varchar(50),--银行对应科目ID
	@ysatypeid varchar(50),--预收对应科目ID
	@storecardatypeid varchar(50),--储值卡对应科目ID
	@tax  NUMERIC(24, 10) ,--税率
	@comment varchar(200),--备注
	@opertionmark int	--新增修改标志
--@encode$--	
AS
IF(@opertionmark=0)--新增
BEGIN
  INSERT INTO PosRetailCash  VALUES(
							 @stypeid,
							 @cashatypeid,
							 @bankatypeid,
							 @ysatypeid,
							 @storecardatypeid,
							 @tax,
							 @comment
  )
END
IF(@opertionmark=1)--修改
BEGIN
  UPDATE PosRetailCash 
  SET
  		 Stypeid=@stypeid,
		 CashAtypeid=@cashatypeid,
		 BankAtypeid=@bankatypeid,
		 YSAtypeid=@ysatypeid,
         StoreCardAtypeid=@storecardatypeid,
		 Tax=@tax,
		 Comment=@comment 
  WHERE Stypeid=@stypeid
END

GO





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

/****** Object:  StoredProcedure [dbo].[Gp_PosRetailCashListInfo]    Script Date: 07/29/2011 15:51:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011年7月29日
-- Description:	读取零售收银配置列表
-- =============================================
CREATE PROCEDURE [dbo].[Gp_PosRetailCashListInfo] 
	@stypeid  varchar(50), --分支机构ID
	@cashatypeid  varchar(50),--收现对应科目ID
	@bankatypeid  varchar(50), --银行对应科目ID
	@ysatypeid   varchar(50)  --预收对应科目ID
--@encode$--	
AS
 declare  @SQL varchar(max)
SET @SQL='SELECT a.stypeid,a.tax,a.comment,
				(SELECT ntypeid FROM ac_items WHERE nid=a.cashatypeid) AS cashatypeid,	
				(SELECT ntypeid FROM ac_items WHERE nid=a.bankatypeid) AS bankatypeid,
				(SELECT ntypeid FROM ac_items WHERE nid=a.ysatypeid) AS ysatypeid,
				(SELECT ntypeid FROM ac_items WHERE nid=a.storecardatypeid) AS storecardatypeid,
				b.usercode,b.branchid,b.fullname as bfullname
		  FROM PosRetailCash a
		  LEFT JOIN branchinfo b ON a.stypeid=b.branchid
		  WHERE 1=1
		  '
IF(@stypeid<>'')
   SET @SQL=@SQL+' AND a.stypeid='''+@stypeid+''''
IF(@cashatypeid<>'')
   SET @SQL=@SQL+' AND a.cashatypeid='''+@cashatypeid+''''
IF(@bankatypeid<>'')
   SET @SQL=@SQL+' AND a.bankatypeid='''+@bankatypeid+''''
IF(@ysatypeid<>'')
   SET @SQL=@SQL+' AND a.ysatypeid='''+@ysatypeid+''''
--print(@SQL)
EXEC(@SQL)  

GO





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

/****** Object:  StoredProcedure [dbo].[Gp_PosSaleCashListInfo]    Script Date: 08/12/2011 15:25:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011年08月12日
-- Description:	POS收银流水查询
-- =============================================
CREATE PROCEDURE [dbo].[Gp_PosSaleCashListInfo]
	@startdate varchar(50),  --开始日期
	@enddate   varchar(50),  --结束日期
	@stypeid   varchar(50),  --分支机构ID
	@ktypeid   varchar(50),  --仓库ID
	@posbillcode varchar(50),--POS流水号
	@posbilltype  int, --单据状态
	@ecashtypeid varchar(50),--收银员
	@esaletypeid varchar(50),--营业员
	@posname    varchar(200)--POS名称
--@encode$--	
AS
BEGIN
DECLARE @SQL VARCHAR(MAX)
CREATE TABLE #STYPE(stypeid varchar(50))
INSERT INTO #STYPE SELECT TypeId FROM F_GetAllBaseTypeId(@stypeid,11)

CREATE TABLE #KTYPE(ktypeid varchar(50))
INSERT INTO #KTYPE SELECT TypeId FROM F_GetAllBaseTypeId(@ktypeid,4)

CREATE TABLE #ECASHTYPE(etypeid varchar(50))
INSERT INTO #ECASHTYPE SELECT TypeId FROM F_GetAllBaseTypeId(@ecashtypeid,3)

CREATE TABLE #ESALETYPE(etypeid varchar(50))
INSERT INTO #ESALETYPE SELECT TypeId FROM F_GetAllBaseTypeId(@esaletypeid,3)

SET @SQL='	SELECT  case a.draft when ''0'' then ''未结转'' else ''已结转''  end as posbilltype,
					a.billcode,
					a.saledate,
					a.ktypeid,
					b.fullname as posname,
					a.total,
					a.billdiscount,
					a.retreplacecashsum,
					a.Cashier  as cashier,
					c.fullname as cashiername,
					a.Salesman as salesman,
					d.fullname as salesmanrname, 
					a.Branchid as stypeid,
					dbo.Pos_F_GetVipCode(a.PosVchcode) as vipcardcode,
					a.cashsum-a.changesum as cashsum,
					a.creditsum,
					a.replacecashsum,
					a.saveaccountsum,
					dbo.Pos_F_GetCxName(a.SGCXBillID) as cxname
			FROM 
			CommonPosSaleIndex a
			INNER JOIN
			CommonPosInfo b ON a.PosID=b.PosID
			INNER JOIN
			employee c ON a.Cashier=c.typeid
			INNER JOIN
			employee d ON a.Salesman=d.typeid
			WHERE a.billcode like ''%'+@posbillcode+'%''  
			'
IF(@posname<>'')
	SET @SQL+=' AND b.fullname like ''%'+@posname+'%'''
IF(@startdate<>''AND @enddate<>'')
	SET @SQL+=' AND  a.saledate >='''+@startdate+''' AND a.saledate<='''+@enddate+''''
IF(@stypeid<>'')
	SET @SQL+=' AND a.branchid in(select stypeid from #STYPE)'
IF(@ktypeid<>'')
	SET @SQL+=' AND a.ktypeid in(select ktypeid from #KTYPE)'
IF(@posbilltype=1)
	SET @SQL+=' AND a.draft=0' 
IF(@posbilltype=2)
	SET @SQL+=' AND a.draft<>0' 
--IF(@posbilltype=3)
--	SET @SQL+=' AND a.draft=0'   
IF(@ecashtypeid<>'')
	SET @SQL+=' AND a.cashier in(select etypeid from #ECASHTYPE)'
IF(@esaletypeid<>'')
	SET @SQL+=' AND a.salesman in(select etypeid from #ESALETYPE)'
SET @SQL+=' ORDER BY a.billcode'
EXEC(@SQL)
drop table #STYPE,#KTYPE,#ECASHTYPE,#ESALETYPE
END

GO





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

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date:2011年8月11
-- Description:	销售流水号查询
-- =============================================
CREATE PROCEDURE Gp_PosSaleSerialListInfo 
	@startdate varchar(50),  --开始日期
	@enddate   varchar(50),  --结束日期
	@stypeid   varchar(50),  --分支机构ID
	@ktypeid   varchar(50),  --仓库ID
	@posbillcode varchar(50),--POS流水号
	@possaletype  int ,--业务类型
	@posbilltype  int, --单据状态
	@ptypeid   varchar(50), --商品ID
	@ecashtypeid varchar(50),--收银员
	@esaletypeid varchar(50),--营业员
	@posname    varchar(200),--POS名称
	@vipcode    varchar(60),--vip卡号
	@OperatorId Varchar(100) --用户ID
--@encode$--		
AS
BEGIN
DECLARE @SQL VARCHAR(MAX)
CREATE TABLE #STYPE(stypeid varchar(50))
--INSERT INTO #STYPE SELECT * FROM dbo.f_split(@stypeid,',')
INSERT INTO #STYPE SELECT TypeId FROM F_GetAllBaseTypeId(@stypeid,11)


CREATE TABLE #KTYPE(ktypeid varchar(50))
INSERT INTO #KTYPE SELECT TypeId FROM F_GetAllBaseTypeId(@ktypeid,4)

CREATE TABLE #PTYPE(ptypeid varchar(50))
INSERT INTO #PTYPE SELECT TypeId FROM F_GetAllBaseTypeId(@ptypeid,1)

CREATE TABLE #ECASHTYPE(etypeid varchar(50))
INSERT INTO #ECASHTYPE SELECT TypeId FROM F_GetAllBaseTypeId(@ecashtypeid,3)

CREATE TABLE #ESALETYPE(etypeid varchar(50))
INSERT INTO #ESALETYPE SELECT TypeId FROM F_GetAllBaseTypeId(@esaletypeid,3)
--case when ((b.qty*b.retailprice)<0) then-(b.qty*b.retailprice)else (b.qty*b.retailprice) end as retailpricetotal, 
SET @SQL='	SELECT	case when (b.Qty<0) and (b.IsPresent<>1) then ''退货'' when (b.Qty>0) and (b.IsPresent<>1) then ''零售'' else ''赠送'' end as possaletype,
					case a.draft when ''0'' then ''未结转'' else ''已结转'' end as posbilltype,
					CAST(a.saledate AS datetime) as saledate,
					a.saletime,
					b.ptypeid,
					b.qty as qty,
					b.retailprice,
					b.qty*b.retailprice as retailpricetotal, 
					b.price,
					b.sum as sum,  
					b.discount,
					(b.discountrate/100) as discountrate,   
					a.Cashier  as cashier,
					f.fullname as cashiername,
					a.Salesman as salesman,
					g.fullname as salesmanrname, 
					a.ktypeid,
					e.FullName as posname,
					d.VipCardCode as vipcode,
					dbo.Pos_F_GetCxName(b.cxbillid) as cxbillname,
					a.billcode as billcode
			FROM CommonPosSaleIndex a
			INNER JOIN
			CommonPosSaleList b ON a.PosVchCode=b.PosVchCode
			LEFT JOIN
			CX_SalePlanIndex c ON a.SGCXBillID=c.BillNumberId
			LEFT JOIN
			nVipCardSign d ON a.VipCardID=d.VipCardID
			INNER JOIN
			CommonPosInfo e ON a.PosID=e.PosID
			INNER JOIN
			employee f ON a.Cashier=f.typeid
			INNER JOIN
			employee g ON a.Salesman=g.typeid
			WHERE a.billcode like ''%'+@posbillcode+'%''  
			'
IF(@posname<>'')
	SET @SQL+=' AND e.fullname like ''%'+@posname+'%'''
IF(@vipcode<>'')
	SET @SQL+=' AND d.VipCardCode like ''%'+@vipcode+'%'''
IF(@startdate<>''AND @enddate<>'')
	SET @SQL+=' AND  a.saledate >='''+@startdate+''' AND a.saledate<='''+@enddate+''''
IF(@stypeid<>'')
	SET @SQL+=' AND a.branchid in(select stypeid from #STYPE)'
IF(@ktypeid<>'')
	SET @SQL+=' AND a.ktypeid in(select ktypeid from #KTYPE)'
IF(@possaletype=1)
	SET @SQL+=' AND b.qty>0 AND b.IsPresent<>1'
IF(@possaletype=2)
	SET @SQL+=' AND b.qty<0 AND b.IsPresent<>1'
IF(@possaletype=3)
	SET @SQL+=' AND b.IsPresent=1'
IF(@posbilltype=1)
	SET @SQL+=' AND a.draft=0' 
IF(@posbilltype=2)
	SET @SQL+=' AND a.draft<>0' 
--IF(@posbilltype=3)
--	SET @SQL+=' AND a.draft=0'   
IF(@ptypeid<>'')
	SET @SQL+=' AND b.ptypeid in(select ptypeid from #PTYPE)'
IF(@ecashtypeid<>'')
	SET @SQL+=' AND a.cashier in(select etypeid from #ECASHTYPE)'
IF(@esaletypeid<>'')
	SET @SQL+=' AND a.salesman in(select etypeid from #ESALETYPE)'

SET @SQL+=' ORDER BY a.saledate DESC'
--print(@SQL)
EXEC(@SQL)
drop table #STYPE,#KTYPE,#PTYPE,#ECASHTYPE,#ESALETYPE
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_PosStockInventoryDetailInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_PosStockInventoryDetailInfo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年8月17日
-- Description:	读取盘点单详细信息
-- =============================================
CREATE PROCEDURE Gp_PosStockInventoryDetailInfo
	@startdate  VARCHAR(50),     --开始日期
	@enddate    VARCHAR(50),     --结束日期
	@ktypeid    VARCHAR(50),  --仓库ID
	@etypeid    VARCHAR(100),  --盘点人
	@pdnumber   VARCHAR(50),   --盘点单流水号
	@ptypeid    VARCHAR(50),   --产品ID号
	@posbilltype VARCHAR(10),  --盘点单状态
	@checkcode  VARCHAR(MAX)=''            --盘点单据ID
--@encode$--
AS
BEGIN
DECLARE  @SQL VARCHAR(max)
CREATE TABLE #KTYPE(ktypeid varchar(50))
INSERT INTO #KTYPE SELECT TypeId FROM F_GetAllBaseTypeId(@ktypeid,4)

CREATE TABLE #PTYPE(ptypeid varchar(50))
INSERT INTO #PTYPE SELECT TypeId FROM F_GetAllBaseTypeId(@ptypeid,1)

CREATE TABLE #ETYPE(etypeid varchar(50))
INSERT INTO #ETYPE SELECT TypeId FROM F_GetAllBaseTypeId(@etypeid,3)


SET @SQL='	SELECT	a.checkcode,
					CASE WHEN a.PDVchCode=0 THEN ''未结转'' ELSE ''已结转'' END AS posbilltype,
					a.pdnumber,
					CAST(pddate AS datetime) AS pddate,
					b.ptypeid,
					b.qty,
					c.retailprice,
					b.qty*c.retailprice AS sum,
					a.ktypeid,
					a.OperatorID AS etypeid
			FROM CommonPosPtypeCheckNdx a
			INNER JOIN
			CommonPosPtypeCheckList  b ON a.CheckCode=b.CheckCode
			INNER JOIN 
			PType_Price c  ON b.PtypeID=c.PTypeID	
			WHERE a.pdnumber LIKE ''%'+@pdnumber+'%'''
IF(@startdate<>'' AND @enddate<>'')
	SET @SQL=@SQL+' AND  a.PDDate>='''+@startdate+''' AND a.PDDate<='''+@enddate+''''
IF(@ktypeid<>'')
	SET @SQL=@SQL+ ' AND a.KtypeID in(SELECT ktypeid from #KTYPE)'	
IF(@etypeid<>'')
	SET @SQL=@SQL+ ' AND a.OperatorID in(SELECT etypeid from #ETYPE)'
IF(@ptypeid<>'')
	SET @SQL=@SQL+ ' AND b.ptypeid in(SELECT ptypeid from #PTYPE)'
IF(@posbilltype='2')
	SET @SQL=@SQL+ ' AND a.PDVchCode=0'
IF(@posbilltype='1')
	SET @SQL=@SQL+ ' AND a.PDVchCode<>0'

IF(@checkcode<>0)
	SET @SQL=@SQL+ ' AND a.checkcode='+@checkcode+'';
SET @SQL=@SQL+ ' ORDER BY a.pdnumber'
PRINT(@SQL)
EXEC(@SQL)
DROP TABLE #KTYPE,#ETYPE,#PTYPE
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_PosStockInventoryInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_PosStockInventoryInfo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年8月16日
-- Description:	读取POS盘点单列表
-- =============================================
CREATE PROCEDURE Gp_PosStockInventoryInfo
	@startdate  VARCHAR(50),     --开始日期
	@enddate    VARCHAR(50),     --结束日期
	@ktypeid    VARCHAR(50),  --仓库ID
	@etypeid    VARCHAR(100),  --盘点人
	@pdnumber   VARCHAR(50),   --盘点单流水号
	@posbilltype VARCHAR(10)   --盘点单状态
--@encode$--
AS
BEGIN
DECLARE  @SQL VARCHAR(max)
CREATE TABLE #KTYPE(ktypeid varchar(50))
INSERT INTO #KTYPE SELECT TypeId FROM F_GetAllBaseTypeId(@ktypeid,4)

CREATE TABLE #ETYPE(etypeid varchar(50))
INSERT INTO #ETYPE SELECT TypeId FROM F_GetAllBaseTypeId(@etypeid,3)


SET @SQL='	SELECT	a.checkcode,
					CASE WHEN a.PDVchCode=0 THEN ''未结转'' ELSE ''已结转'' END AS posbilltype,
					a.pdnumber,
					CAST(a.pddate AS datetime) AS pddate,
					a.ktypeid,
					a.OperatorID AS etypeid
			FROM CommonPosPtypeCheckNdx a
			LEFT JOIN
			stock b ON a.ktypeid=b.typeid
			LEFT JOIN
			employee c ON a.OperatorID=c.typeid
			WHERE pdnumber LIKE ''%'+@pdnumber+'%'' '
IF(@startdate<>'' AND @enddate<>'')
	SET @SQL=@SQL+' AND  PDDate>='''+@startdate+''' AND PDDate<='''+@enddate+''''
IF(@ktypeid<>'')
	SET @SQL=@SQL+ ' AND a.KtypeID in(SELECT ktypeid from #KTYPE)'	
IF(@etypeid<>'')
	SET @SQL=@SQL+ ' AND a.OperatorID in(SELECT etypeid from #ETYPE)'
	
IF(@posbilltype='2')
	SET @SQL=@SQL+ ' AND PDVchCode=0'
ELSE
	SET @SQL=@SQL+ ' AND PDVchCode<>0' 

SET @SQL=@SQL+ ' ORDER BY pdnumber'
--PRINT(@SQL)
EXEC(@SQL)
DROP TABLE #KTYPE,#ETYPE
END
GO




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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	获取小数位数,主要用于过账
	作    者：	冯波
	修改时间：
*/
CREATE             PROCEDURE GP_Post_Dot(
	@intQtyDot			INT OUT,
	@intPriceDot		INT	OUT,
	@intMoneyDot		INT	OUT,
	@intDiscountDot		INT	OUT,
	@intTaxDot			INT	OUT,
	@intCRateDot		INT	OUT,
	@intTRateDot		INT OUT
)
----@encode$--
AS
	
EXEC	@intQtyDot=Gp_GetDigit 1
EXEC	@intPriceDot=Gp_GetDigit 2
EXEC	@intMoneyDot=Gp_GetDigit 3
EXEC	@intDiscountDot=Gp_GetDigit 4
EXEC	@intTaxDot=Gp_GetDigit 5
EXEC	@intCRateDot=Gp_GetDigit 6
EXEC	@intTRateDot=Gp_GetDigit 8

	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

















/****
程序员:吴德水
最后修改:吴德水
最后时间:2004-01-05 10:29
修改内容：修改有效价格个数。即标准均售价
修改位置：第1行起
***/

CREATE          PROCEDURE GP_Priceinfo(
	@OperatorID 	varchar(100),
	@ParId 			varchar(100)='',
	@usercode 		varchar(100)='',
	@fullname 		varchar(100)='',
	@entrycode 		varchar(50)='',
	@standard 		varchar(50)='',
	@type 			varchar(50)='',
	@area 			varchar(50)='',
	@unit 			varchar(20)='',
	@g1 			 NUMERIC(24, 10) =0,
	@g2 			 NUMERIC(24, 10) =0,
	@SortFild		varchar(50)='UserCode',
	@SortType		varchar(50)=' ASC ',	
	@queryMode 		int=1
)

--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)


DECLARE @SQL varchar(8000),@strSQL varchar(8000)
BEGIN
SELECT @SQL=''
IF @parid<>''
	SELECT @SQL=@SQL+' 	AND p.typeid LIKE '''+@parid+'%''' /*AND P.TypeId IN (SELECT * FROM F_GetManDetailPType('+char(39)+@OperatorID+char(39)+'))*/

IF @usercode <>''
	SELECT @SQL=@SQL+' AND p.usercode LIKE ''%'+@usercode+'%'''
IF @fullname<>''
	SELECT @SQL=@SQL+' AND p.fullname LIKE ''%'+@fullname+'%'''
IF @entrycode<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.entrycode,'''') LIKE ''%'+@entrycode+'%'''
IF @standard<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.standard,'''') LIKE ''%'+@standard+'%'''
IF @type<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.type,'''') LIKE ''%'+@type+'%'''
IF @area<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.area,'''')  LIKE ''%'+@area+'%'''
IF @unit<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.unit1,'''') LIKE  ''%'+@unit+'%'''

DECLARE @SqlZero varchar(300)
SET @SqlZero=''
IF @queryMode = 1
	SET @SqlZero = @SqlZero + ' AND ISNULL(S.Qty,0)<>0 '


SELECT @strSQL='
			SELECT p.typeid,
					p.usercode,
					p.fullname,
					p.preprice1,
					p.preprice2,
					p.preprice3,
					p.preprice4,
					p.preprice5,
					p.recprice,
					p.comment,
					p.entrycode,
					p.standard,
					p.type,
					p.area,
					p.unit1
			INTO #Ptype		
			FROM	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') p '
IF @MPtypeid='-99999'
	SET @strSQL=@strSQL+' INNER JOIN #GetManPTypeId sp ON p.TypeId=sp.typeid '

SET @strSQL=@strSQL+' WHERE  p.sonnum=0  AND p.deleted=0  '

SET @strSQL=@strSQL+'
			SELECT 
					p.typeid,
					p.usercode,
					p.fullname,
					CAST(p.preprice1  AS  NUMERIC(24, 10) ) AS preprice1,
					CAST(p.preprice2  AS  NUMERIC(24, 10) ) AS preprice,
					CAST(p.preprice3  AS  NUMERIC(24, 10) ) AS preprice3,
					CAST(p.preprice4  AS  NUMERIC(24, 10) ) AS preprice4,
					CAST(p.preprice5  AS  NUMERIC(24, 10) ) AS preprice5,
					CAST(CASE 
						WHEN ISNULL(s.qty,0) = 0 THEN 0
						ELSE (s.total/s.qty)
						END AS  NUMERIC(24, 10) ) AS cost,
					p.recprice,
					CAST(CASE 
						WHEN ISNULL(s.qty,0) = 0 THEN 0 
						ELSE	CASE	WHEN (ISNULL(p.preprice1,0)+ISNULL(p.preprice2,0)+ISNULL(p.preprice3,0)+ISNULL(p.preprice4,0))/4=0 THEN 0
								ELSE	(
										(
											((ISNULL(p.preprice1,0) + ISNULL(p.preprice2,0) + ISNULL(p.preprice3,0) + ISNULL(p.preprice4,0))/( ISNULL(NULLIF(1, (ISNULL(p.preprice1,0) + 1)),0) + ISNULL(NULLIF(1, (ISNULL(p.preprice2,0) + 1)),0) +  ISNULL(NULLIF(1, (ISNULL(p.preprice3,0) + 1)),0) + ISNULL(NULLIF(1, (ISNULL(p.preprice4,0) + 1)),0)))
											- ISNULL(s.total,0) /s.qty
										) /
										(
											((ISNULL(p.preprice1,0) + ISNULL(p.preprice2,0) + ISNULL(p.preprice3,0) + ISNULL(p.preprice4,0))/( ISNULL(NULLIF(1, (ISNULL(p.preprice1,0) + 1)),0) + ISNULL(NULLIF(1, (ISNULL(p.preprice2,0) + 1)),0) +  ISNULL(NULLIF(1, (ISNULL(p.preprice3,0) + 1)),0) + ISNULL(NULLIF(1, (ISNULL(p.preprice4,0) + 1)),0)))
										)
									)*100
							END
						END 
					AS  NUMERIC(24, 10) )AS Gprofit,
					IsNULL(s.qty,0) as qty,
					p.comment
			INTO #Result
			FROM #Ptype p
				 LEFT JOIN  
				(
					SELECT 	s.ptypeid ,
						ISNULL(SUM(s.qty),0) AS qty,
						ISNULL(SUM(s.total),0) AS total
					FROM 	goodsstocks s INNER JOIN #GetManPTypeId p ON s.ptypeid=p.typeid
					GROUP BY ptypeid
				) s ON s.Ptypeid=p.typeid 
			WHERE  1=1' + @SQL+@SqlZero + ' 					
			ORDER BY P.UserCode 

		SELECT * FROM #Result WHERE Gprofit>='+CAST(@G1 AS varchar(100))+' AND Gprofit<='+CAST(@G2 AS varchar(100))+''


SET @strSQL=@strSQL+' ORDER BY '+ @SortFild +' '+@SortType+' '		 --haiquan添加排序


SET @strSQL=@strSQL+ ' DROP TABLE #Result,#Ptype '  
--PRINT(@strsql)
EXEC(@strSQL) 
END


DROP TABLE #GetManPTypeId












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

-- =============================================
-- Author:		杨鑫
-- Create date: 25/10/2017 
-- Description:	读取价格顺序设置保存
-- =============================================

CREATE PROCEDURE Gp_PriceOrderSet
(
	--@saleprice	INT,
	@advancedpriceds Tb_Gp_PriceOrderSet	READONLY
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE PriceRules_Order  SET [Priority] = D.[Priority]
FROM PriceRules_Order P
INNER JOIN @advancedpriceds D ON D.PriceType = P.PriceType


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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














CREATE   PROCEDURE [Gp_PriceProtectStat]
(
    @chvOperator	VARCHAR(100),
    @szMode     	VARCHAR(20),  --使用方式     
    @StartDate 		DATETIME,
    @EndDate 		DATETIME,
    @BUserCode 		VARCHAR(66),
    @BFullName 		VARCHAR(66),
    @PUserCode 		VARCHAR(66),
    @PFullName 		VARCHAR(66),
    @szSort 		CHAR(1)='',
	@BillType		VARCHAR(10),	--单据类型  149.价保执行	151.获得价保
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperator IS NULL RETURN 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @chvOperator,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperator)	

IF @szMode='Normal'
	BEGIN

		IF @BUserCode='' SELECT @BUserCode='%' ELSE SELECT @BUserCode='%'+@BUserCode+'%'
		IF @BFullName='' SELECT @BFullName='%' ELSE SELECT @BFullName='%'+@BFullName+'%'
		IF @PUserCode='' SELECT @PUserCode='%' ELSE SELECT @PUserCode='%'+@PUserCode+'%'
		IF @PFullName='' SELECT @PFullName='%' ELSE SELECT @PFullName='%'+@PFullName+'%'
		
		SELECT TypeID,UserCode,FullName INTO #TempTablePType  FROM F_GetManPTypeAll(@chvOperator) WHERE (UserCode LIKE @PUserCode AND FullName LIKE @PFullName) AND (sonnum=0) --AND (TypeID LIKE @MPTypeID+'%')
		SELECT TypeID,UserCode,FullName INTO #TempTableBType  FROM F_GetManBTypeAll(@chvOperator) WHERE (UserCode LIKE @BUserCode AND FullName LIKE @BFullName) AND (sonnum=0) --AND (TypeID LIKE CASE LEFT(TypeID,5) WHEN '00001' THEN @MBTypeID+'%' WHEN '00002' THEN @MBTypeID2+'%' END)

		SELECT 	a.Serial,
				a.OldTotal,
				a.NewPrice,
				a.Stypeid,
				b.TypeID AS PTypeID,
				b.UserCode AS PUserCode,
				b.FullName AS PFullName,
				c.TypeID AS BTypeID,
				c.UserCode AS BUserCode,
				c.FullName AS BFullName
		FROM 	PriceProtectList a
				INNER JOIN #TempTablePType b ON (a.PTypeID=b.TypeID)
                INNER JOIN #TempTableBType c ON (a.BTypeID=c.TypeID)
                INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
		WHERE 	b.TypeID<>'' 
				AND c.TypeID<>'' 
				AND b.TypeID<>NULL 
				AND c.TypeID<>NULL
				AND a.BillType = @BillType
		ORDER BY
				b.usercode,c.UserCode
	END
ELSE 
	IF @szMode='BillDetail'
		BEGIN

			SELECT 	DISTINCT 
					a.*,
					c.UserCode,
					c.FullName 
			INTO 	#TempTable 
			FROM 	Billindex a 
			INNER JOIN PriceProtectBill b ON (a.BillNumberID=b.BillNumberID) 
			INNER JOIN BType c ON (a.BTypeID=c.TypeID)
			INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
			WHERE 	a.BTypeID=@BUserCode 
					AND b.PTypeID=@PUserCode 
					AND a.BillType=@BillType
					AND a.BillDate<=@EndDate 
					AND a.BillDate>=@StartDate
					AND a.IfCheck = 't'
					AND a.RedWord = 0
					AND a.ifYearBill=0	 --年节存标志
			IF @szSort='1'
     			SELECT * FROM #TempTable ORDER BY BillDate ASC
			ELSE 
				IF @szSort='2'
					SELECT * FROM #TempTable ORDER BY BillCode ASC
				ELSE 
					IF @szSort='3'
						SELECT * FROM #TempTable ORDER BY TotalQty ASC
					ELSE 
						IF @szSort='4'
     						SELECT * FROM #TempTable ORDER BY TotalMoney ASC

		END


DROP TABLE #GetManSTypeId









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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







CREATE      PROCEDURE Gp_PriceRecUpdate(

	@OperatorID 	varchar(50),
	@ParId 			varchar(50)='',
	@usercode 		varchar(50)='',
	@fullname 		varchar(66)='',
	@entrycode 		varchar(50)='',
	@standard 		varchar(50)='',
	@type 			varchar(50)='',
	@area 			varchar(50)='',
	@unit 			varchar(20)='',
	@g1 			 NUMERIC(24, 10) =0,
	@g2 			 NUMERIC(24, 10) =0,
	@queryMode 		int=1,
	@strRow			varchar(100),	--修改什么价格
	@strPrice   	varchar(100),	--保存运算公式中，第一个数据信息
	@strGen			varchar(100), 	--运算符号
	@strPriceValue  varchar(100)	--值，保存运算公式中，第二个数据信息
)
--@encode$--
AS
SET NOCOUNT ON


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL varchar(8000),@strSQL varchar(8000)

CREATE TABLE #Result
(
	typeid    varchar(100),
	preprice1  NUMERIC(24, 10) ,
	preprice2  NUMERIC(24, 10) ,
	preprice3  NUMERIC(24, 10) ,
	preprice4  NUMERIC(24, 10) ,
	preprice5  NUMERIC(24, 10) ,
	recprice   NUMERIC(24, 10) ,
	Gprofit    NUMERIC(24, 10) 
)

/*-------------------------------获得ptypeid（摘自gp_priceinfo）-------------------------------*/
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@parid,1) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailPType(@OperatorID))

SELECT @SQL=''
IF @parid<>''
	SELECT @SQL=@SQL+' 	AND p.typeid LIKE '''+@parid+'%''
						AND P.TypeId IN (SELECT TypeId FROM #GetManPTypeId)'

IF @usercode <>''
	SELECT @SQL=@SQL+' AND p.usercode LIKE ''%'+@usercode+'%'''
IF @fullname<>''
	SELECT @SQL=@SQL+' AND p.fullname LIKE ''%'+@fullname+'%'''
IF @entrycode<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.entrycode,'''') LIKE ''%'+@entrycode+'%'''
IF @standard<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.standard,'''') LIKE ''%'+@standard+'%'''
IF @type<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.type,'''') LIKE ''%'+@type+'%'''
IF @area<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.area,'''')  LIKE ''%'+@area+'%'''
IF @unit<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.unit1,'''') LIKE  ''%'+@unit+'%'''

IF @queryMode = 1
	SET @SQL = @SQL + ' AND ISNULL(S.Qty,0)<>0 '

SELECT @strSQL='
			INSERT INTO #Result
			SELECT 
			p.typeid AS typeid,
			CAST(p.preprice1  AS  NUMERIC(24, 10) ) AS preprice1,
			CAST(p.preprice2  AS  NUMERIC(24, 10) ) AS preprice2,
			CAST(p.preprice3  AS  NUMERIC(24, 10) ) AS preprice3,
			CAST(p.preprice4  AS  NUMERIC(24, 10) ) AS preprice4,
			CAST(p.preprice5  AS  NUMERIC(24, 10) ) AS preprice5,
			p.recprice,
			CAST(CASE 
				WHEN ISNULL(s.qty,0) = 0 THEN 0 
				ELSE	CASE	WHEN (ISNULL(p.preprice1,0)+ISNULL(p.preprice2,0)+ISNULL(p.preprice3,0)+ISNULL(p.preprice4,0))/4=0 THEN 0
						ELSE	(
								(
									((ISNULL(p.preprice1,0) + ISNULL(p.preprice2,0) + ISNULL(p.preprice3,0) + ISNULL(p.preprice4,0))/( ISNULL(NULLIF(1, (ISNULL(p.preprice1,0) + 1)),0) + ISNULL(NULLIF(1, (ISNULL(p.preprice2,0) + 1)),0) +  ISNULL(NULLIF(1, (ISNULL(p.preprice3,0) + 1)),0) + ISNULL(NULLIF(1, (ISNULL(p.preprice4,0) + 1)),0)))
									- ISNULL(s.total,0) /s.qty
								) /
								(
									((ISNULL(p.preprice1,0) + ISNULL(p.preprice2,0) + ISNULL(p.preprice3,0) + ISNULL(p.preprice4,0))/( ISNULL(NULLIF(1, (ISNULL(p.preprice1,0) + 1)),0) + ISNULL(NULLIF(1, (ISNULL(p.preprice2,0) + 1)),0) +  ISNULL(NULLIF(1, (ISNULL(p.preprice3,0) + 1)),0) + ISNULL(NULLIF(1, (ISNULL(p.preprice4,0) + 1)),0)))
								)
							)*100
					END
				END 

			AS  NUMERIC(24, 10) )AS Gprofit
			FROM ptype p'
IF @queryMode=1
	SELECT @strSQL=@strSQL+' LEFT JOIN'

IF @queryMode=0
	SELECT @strSQL=@strSQL+' LEFT JOIN'

SELECT @strSQL=@strSQL+' (
							SELECT 	ptypeid ,
									ISNULL(SUM(qty),0) AS qty,
									ISNULL(SUM(total),0) AS total 
							FROM 	goodsstocks
							WHERE	PTypeId IN (SELECT TypeId FROM #GetManPTypeId)
							GROUP BY ptypeid
						) s ON (s.Ptypeid=p.typeid) 
			WHERE 	p.sonnum=0 
					AND P.TypeId IN (SELECT TypeId FROM #GetManPTypeId)
					AND p.deleted=0 ' + @SQL + ' 					
			ORDER BY P.UserCode '

EXEC(@strSQL)


DELETE FROM #Result WHERE Gprofit<CAST(@G1 AS varchar(100)) OR Gprofit>CAST(@G2 AS varchar(100))

--PRINT(@strsql)

/*----------构建临时表分别存储四个字符串的值，构件逻辑上的数组-------------*/

CREATE Table #Row
(
[id]    int IDENTITY (1, 1) NOT NULL,
Rvalue  int
)

CREATE Table #Price
(
[id]    int IDENTITY (1, 1) NOT NULL,
Pvalue  int 
)

CREATE Table #Gen
(
[id]    int IDENTITY (1, 1) NOT NULL,
Gvalue  int 
)

CREATE Table #Pvalue
(
[id]     int IDENTITY (1, 1) NOT NULL,
PVvalue   NUMERIC(24, 10)  NULL
)
/*-----------插值入表--------------*/
INSERT INTO #Row 	SELECT * FROM F_split(@strRow,',')
INSERT INTO #Price  SELECT * FROM F_split(@strPrice,',')
INSERT INTO #Gen 	SELECT * FROM F_split(@strGen,',')
INSERT INTO #Pvalue SELECT * FROM F_split(@strPriceValue,',')

/*------------声明变量-----------------*/
DECLARE @Rvalue [int]
DECLARE @Pvalue [int]
DECLARE @Gvalue [int]
DECLARE @Pvvalue varchar(30)
/*-------------保存sql语句元素-----------*/
DECLARE @strSQL2 varchar(100)
DECLARE @SQL2 varchar(8000)

DECLARE @C  NUMERIC(24, 10) 
DECLARE @Pid varchar(100)


DECLARE @i int
SELECT @i=1


/*--------------读取值，并做处理-------------------------*/
WHILE (@i<=6)
 BEGIN
	SELECT @Rvalue=null
    SELECT @strSQL2=''
	SELECT @Rvalue=Rvalue 	FROM #Row 	 WHERE [id]=@i
	SELECT @Pvalue=Pvalue 	FROM #Price  WHERE [id]=@i
	SELECT @Gvalue=Gvalue 	FROM #Gen 	 WHERE [id]=@i
	SELECT @Pvvalue=Pvvalue FROM #Pvalue WHERE [id]=@i
	
--print (@Rvalue)

	if (@Rvalue is null)
	BREAK

-------修改字段--------

	SELECT @strSQL2=
	CASE @Rvalue
		 WHEN 1 THEN
			'preprice1='
		 WHEN 2 THEN
			'preprice2='
		 WHEN 3 THEN
			'preprice3='
		 WHEN 4 THEN
			'preprice4='
		 WHEN 5 THEN
			'preprice5='
		 WHEN 6 THEN
			'recprice='
	END

-------第一个运算值--------

	SELECT @strSQL2=@strSQL2+
	CASE @Pvalue
		 WHEN 1 THEN
			'preprice1'
		 WHEN 2 THEN
			'preprice2'
		 WHEN 3 THEN
			'preprice3'
		 WHEN 4 THEN
			'preprice4'
		 WHEN 5 THEN
			'preprice5'
		 WHEN 6 THEN
			'recprice'
	END


-------运算符--------

	SELECT @strSQL2=@strSQL2+
	CASE @Gvalue
		 WHEN 1 THEN
			'+'
		 WHEN 2 THEN
			'-'
		 WHEN 3 THEN
			'*'
		 WHEN 4 THEN
			'/'
	END

	SELECT @SQL2='UPDATE #Result SET '+ @strSQL2 +@Pvvalue

	EXEC (@SQL2)	
	

	SELECT 	@Pid=null
	SELECT 	@Pid=typeid
	FROM #Result 
	WHERE 	CASE @Rvalue
				 WHEN 1 THEN
					preprice1
				 WHEN 2 THEN
					preprice2
				 WHEN 3 THEN
					preprice3
				 WHEN 4 THEN
					preprice4
				 WHEN 5 THEN
					preprice5
				 WHEN 6 THEN
					recprice
			END
			< 0

	IF (@Pid is not null) --如果单价小于0，返回商品id
		RETURN 3
	
    SET @i=@i+1
 END


BEGIN TRANSACTION --设定回滚

UPDATE 	Ptype 
SET 	preprice1 = R.preprice1,
		preprice2 = R.preprice2,
		preprice3 = R.preprice3,
		preprice4 = R.preprice4,
		preprice5 = R.preprice5,
		recprice  = R.recprice
FROM   	#Result R ,
	   	Ptype   P	
WHERE  	P.typeid = R.typeid
	   	AND p.sonnum=0
	   	AND p.deleted=0
		AND P.TypeID IN (SELECT TypeId FROM #GetManPTypeId)


/*---判断是否成功更新----*/

IF @@rowcount < 1
	BEGIN
		ROLLBACK TRANSACTION
		RETURN 2
	END
ELSE
	BEGIN
		COMMIT TRANSACTION
	END



DROP TABLE #Result
DROP TABLE #Row
DROP TABLE #Price
DROP TABLE #Gen
DROP TABLE #Pvalue
DROP TABLE #GetManPTypeId

RETURN 0













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2013-5-31
	描述：删除 作废 审核的批量操作
-------------------------------------------*/
CREATE PROCEDURE GP_PriceTableBatchDeleteStopAduit
(
	@PriceBillindexID	VARCHAR(MAX),--主表ID字符串
	@PriceDetailID		VARCHAR(MAX),--明细ID字符串
	@Oper				VARCHAR(20), --操作类型  delete aduit  stop deletestop
	@UserID				VARCHAR(50), --操作人员ID 
	@OperDate			DATETIME	 --操作时间
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #PriceBillindexID(ID NUMERIC(18,0))
INSERT #PriceBillindexID(ID) SELECT DISTINCT a FROM dbo.f_split(@PriceBillindexID,',')

CREATE TABLE #PriceDetailID(ID NUMERIC(18,0))
INSERT #PriceDetailID SELECT * FROM DBO.f_split(@PriceDetailID,',')


BEGIN TRANSACTION Oper

IF @Oper = 'stop'
BEGIN
	INSERT PriceDetailDeleted
	(	PriceBillIndexID,
		[State],
		Ptypeid,
		FreeID,
		IsCombined,
		UnitId,
		PriceStyle,
		Price,
		Discount,
		DiscountPrice,
		BeforeRetailPrice,
		Tax,
		TaxPrice,
		IsPriceControl,
		Comment,
		Checke,
		Checker,
		VaildDate,
		CreateDate,
		DeletedDate,
		DeletedR,
		SortID
		)
		SELECT	PriceBillIndexID,
				3,
				Ptypeid,
				FreeID,
				IsCombined,
				UnitId,
				PriceStyle,
				Price,
				Discount,
				DiscountPrice,
				BeforeRetailPrice,
				Tax,
				TaxPrice,
				IsPriceControl,
				Comment,
				Checke,
				Checker,
				VaildDate,
				CreateDate,
				@OperDate,	--删除时间
				@UserID,	--删除人
				--DeletedDate,
				--DeletedR,
				SortID
		FROM PriceDetail
		INNER JOIN #PriceDetailID I ON I.ID = PriceDetail.ID
		
	DELETE PriceDetail WHERE ID IN (SELECT ID FROM #PriceDetailID)
	
	--UPDATE PriceBillIndex SET [State]=3 WHERE ID IN (SELECT ID FROM #PriceBillindexID) AND ID NOT IN(SELECT PriceBillIndexID FROM PriceDetail)
	
END
ELSE IF @Oper = 'delete'
BEGIN
	DELETE PriceDetail WHERE ID IN (SELECT ID FROM #PriceDetailID)
	
	CREATE TABLE #DeleteID(ID NUMERIC(18,0))
	INSERT #DeleteID(ID)
	SELECT ID FROM #PriceBillindexID WHERE ID NOT IN(SELECT PriceBillIndexID FROM PriceDetail UNION ALL SELECT PriceBillIndexID FROM PriceDetailDeleted)
	
	CREATE TABLE #UserdPriceBillIndex(ID NUMERIC(18,0), FullName VARCHAR(200))
	INSERT INTO #UserdPriceBillIndex(ID,FullName)
	SELECT DISTINCT P.ID,B.FullName FROM #DeleteID P 
	INNER JOIN PriceRule R ON R.PriceBillIndexID = P.ID
	INNER JOIN PriceBillIndex B ON B.ID = P.ID
	IF EXISTS(SELECT TOP 1 1 FROM #UserdPriceBillIndex)
	BEGIN
		DECLARE @Result VARCHAR(MAX) = ''
		SELECT @Result=@Result+FullName+',' FROM #UserdPriceBillIndex
		SET @Result = SUBSTRING(@Result,1,LEN(@Result) - 1)
		DECLARE @MSG VARCHAR(MAX)='价格表【'+@Result+'】已被取价规则调用，不能将所有明细清除！'
		RAISERROR(@MSG,16,1)
		
		ROLLBACK TRANSACTION
		RETURN
	END

	DELETE PriceBillIndex WHERE ID IN (SELECT ID FROM #DeleteID)
	DELETE PriceBillIndex_Stype WHERE PriceBillIndexID IN (SELECT ID FROM #DeleteID)
	DELETE PriceDetailDeleted WHERE PriceBillIndexID IN (SELECT ID FROM #DeleteID)
	
	DROP TABLE #DeleteID,#UserdPriceBillIndex
END
ELSE IF @Oper = 'aduit'
BEGIN
	CREATE TABLE #AdjustDeletedID(ID NUMERIC(18,0))
	INSERT #AdjustDeletedID(ID)
	SELECT D.ID 
	FROM #PriceDetailID P
	INNER JOIN PriceDetail L ON L.ID=P.ID
	INNER JOIN PriceDetail D ON D.ID = L.OldID
	WHERE L.OldID > 0
	
	UPDATE PriceDetail SET [State] = 2,OldID = CASE WHEN ISNULL(OldID,0) > 0 THEN 0 ELSE OldID END, Checker = @UserID, VaildDate = @OperDate,
	RChecker='',RVaildDate=NULL
	FROM PriceDetail P
	WHERE P.ID IN (SELECT ID FROM #PriceDetailID)
	
	--把价格调整<-->已审核的数据作废
	INSERT PriceDetailDeleted
	(	PriceBillIndexID,
		[State],
		Ptypeid,
		FreeID,
		IsCombined,
		UnitId,
		PriceStyle,
		Price,
		Discount,
		DiscountPrice,
		BeforeRetailPrice,
		Tax,
		TaxPrice,
		IsPriceControl,
		Comment,
		Checke,
		Checker,
		VaildDate,
		CreateDate,
		DeletedDate,
		DeletedR,
		SortID
		)
		SELECT	PriceBillIndexID,
				3,
				Ptypeid,
				FreeID,
				IsCombined,
				UnitId,
				PriceStyle,
				Price,
				Discount,
				DiscountPrice,
				BeforeRetailPrice,
				Tax,
				TaxPrice,
				IsPriceControl,
				Comment,
				Checke,
				Checker,
				VaildDate,
				CreateDate,
				@OperDate,	--删除时间
				@UserID,	--删除人
				--DeletedDate,
				--DeletedR,
				SortID
		FROM PriceDetail
		INNER JOIN #AdjustDeletedID I ON I.ID = PriceDetail.ID
		
		DELETE PriceDetail WHERE ID IN (SELECT ID FROM #AdjustDeletedID)
		
		DROP TABLE #AdjustDeletedID
END
ELSE IF @Oper = 'deletestop'
BEGIN
	DELETE PriceDetailDeleted WHERE ID IN (SELECT ID FROM #PriceDetailID)
	CREATE TABLE #DeleteStopID(ID NUMERIC(18,0))
	
	INSERT #DeleteStopID(ID)
	SELECT ID FROM #PriceBillindexID WHERE ID NOT IN(SELECT PriceBillIndexID FROM PriceDetail UNION ALL SELECT PriceBillIndexID FROM PriceDetailDeleted)
	CREATE TABLE #UserdPriceBillIndex1(ID NUMERIC(18,0), FullName VARCHAR(200))
	INSERT INTO #UserdPriceBillIndex1(ID,FullName)
	SELECT DISTINCT P.ID,B.FullName FROM #DeleteStopID P 
	INNER JOIN PriceRule R ON R.PriceBillIndexID = P.ID
	INNER JOIN PriceBillIndex B ON B.ID = P.ID
	
	IF EXISTS(SELECT TOP 1 1 FROM #UserdPriceBillIndex1)
	BEGIN
		DECLARE @Result1 VARCHAR(MAX) = ''
		SELECT @Result1=@Result1+FullName+',' FROM #UserdPriceBillIndex1
		SET @Result1 = SUBSTRING(@Result1,1,LEN(@Result1) - 1)
		DECLARE @MSG1 VARCHAR(MAX)='价格表【'+@Result1+'】已被取价规则调用，不能将所有明细清除！'
		RAISERROR(@MSG1,16,1)
		
		ROLLBACK TRANSACTION
		RETURN
	END
	
	DELETE PriceBillIndex WHERE ID IN (SELECT D.ID FROM #DeleteStopID D)
	DELETE PriceBillIndex_Stype WHERE PriceBillIndexID IN (SELECT D.ID FROM #DeleteStopID D)
	DELETE PriceDetailDeleted WHERE PriceBillIndexID IN (SELECT D.ID FROM #DeleteStopID D)
	
	DROP TABLE #DeleteStopID,#UserdPriceBillIndex1
END
ELSE IF @Oper='reverseaudit'
BEGIN
	UPDATE PriceDetail SET [State] = 1,OldID = CASE WHEN ISNULL(OldID,0) > 0 THEN 0 ELSE OldID END, Checker = '', VaildDate = NULL,RChecker=@UserID,
	RVaildDate=GETDATE() FROM PriceDetail P
	WHERE P.ID IN (SELECT ID FROM #PriceDetailID)
END
--公用部分
UPDATE PriceBillIndex 
		SET [State] = CASE	WHEN ISNULL(A.Vailding,-1) <> 1 AND ISNULL(A.Vailded,-1) = 1 THEN 0		--全部审核
							WHEN ISNULL(A.Vailding,-1) = 1 AND ISNULL(A.Vailded,-1) = 1 THEN 1		--部分审核
							WHEN ISNULL(A.Vailding,-1) = 1 AND ISNULL(A.Vailded,-1) <> 1 THEN 2		--全部未审核
							WHEN ISNULL(A.Vailding,-1) <> 1 AND ISNULL(A.Vailded,-1) <> 1 AND ISNULL(A.deleted,-1) = 1 THEN 3	--其他状态
					END
		FROM PriceBillIndex P
		INNER JOIN #PriceBillindexID D ON D.ID = P.ID
		LEFT JOIN
		(
			SELECT	B.ID,
					(SELECT TOP 1 1 FROM  PriceDetail l WHERE l.PriceBillIndexID = b.ID and ([State] = 1 OR [State] = 4)) as Vailding,
					(SELECT TOP 1 1 FROM  PriceDetail l WHERE l.PriceBillIndexID = b.ID and [State] = 2) as Vailded,
					(SELECT TOP 1 1 FROM  PriceDetailDeleted l WHERE l.PriceBillIndexID = b.ID and [State] = 3) as deleted
			FROM #PriceBillindexID B 
		) A on a.ID = p.ID

IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION
	RETURN
END

COMMIT TRANSACTION  Oper


DROP TABLE #PriceBillindexID,#PriceDetailID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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



/*
	作者：徐辉
	日期：2010-03-28
	功能：批量更新价格跟踪，以前算法有问题，重新修改
	
	作者：陈强
	日期：2019-10-18
	说明：敏捷4683批量修改销售出库单价格跟踪信息bug
*/
CREATE PROCEDURE Gp_PriceTraceUpdate(
	@OperatOrId			varchar(100),
	@BtypeId			varchar(3000),
	@PtypeId			varchar(8000),
	@STypeId			varchar(max),
	@Price				varchar(100),--被加数
	@Caculate			varchar(100),--加减神除
	@ZhengLiang			varchar(100),--需要加减神除的值
	@QueryType			varchar(100),		--价格类型  0.销售订单  1.销售出库单  2.采购订单  3.采购入库单 4.报价单  5.询价单 6.发出商品出库单 7.暂估入库单
	@PUserCode			varchar(256)='',	--商品编号
	@PFullName			varchar(256)='',	--商品名称
	@BUserCode			varchar(256),	--客户编号
	@BFullName			varchar(256),	--客户名称
	@cid				INT,
	@uid				INT,
	@Flag				varchar(100),	--是否显示为零的价格跟踪
	@pricetype			INT, --1=扣率,2=单价,3=折后单价,4=税率,5=含税单价
	@rule				INT--规则
)
--@encode$--
AS
--SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @szSQL VARCHAR(MAX),@UPSQL VARCHAR(max)
DECLARE @szBTypeId VARCHAR(100),@szPTypeId VARCHAR(100)
DECLARE @strtempPrice VARCHAR(100),@strNewValue VARCHAR(100),@NewPrice VARCHAR(100),@updatePrice VARCHAR(100)
DECLARE @update VARCHAR(10)='';
DECLARE @introwcount int,@tablerow int
IF @BtypeId='00000'
	SET @BtypeId=''
IF @PtypeId='00000'
	SET @PtypeId=''

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@PTypeId,1) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailPType(@OperatorID))


--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@BTypeId,2) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailBType(@OperatorID))


--往来单位
CREATE TABLE #GetManSTypeId(TypeId	varchar(100),PriceType INT,JoinFlag INT  )
INSERT INTO #GetManSTypeId(TypeId,PriceType,JoinFlag) SELECT s.TypeId,s.PriceType,1 FROM F_GetAllBaseTypeId(@sTypeId,11) 
a INNER JOIN dbo.SType s ON a.TypeId=s.TypeId
 WHERE a.TypeId IN (SELECT TypeId FROM F_GetManDetailsType(@OperatorID))


--生成临时表
CREATE TABLE #PriceTrack
(
	BtypeId VARCHAR(100),
	BtypeFlag INT,
	PtypeId VARCHAR(100),
	StypeId VARCHAR(100),
	UId INT,
	CId INT,
	Price  NUMERIC(24, 10) ,
	DiscountRate  NUMERIC(24, 10) ,
	DiscountPrice  NUMERIC(24, 10) ,
	FreePrice  NUMERIC(24, 10),
	tax  NUMERIC(24, 10) ,
	taxprice  NUMERIC(24, 10),
	TrackTime DATETIME      
)
CREATE TABLE #NoExistPriceTrcak
(
	BtypeId VARCHAR(100),
	BtypeFlag INT,
	PtypeId VARCHAR(100),
	StypeId VARCHAR(100),
	UId INT,
	CId INT,
	Price  NUMERIC(24, 10) ,
	DiscountRate  NUMERIC(24, 10) ,
	DiscountPrice  NUMERIC(24, 10) ,
	FreePrice  NUMERIC(24, 10),
	tax  NUMERIC(24, 10) ,
	taxprice  NUMERIC(24, 10),
	TrackTime DATETIME   
)
CREATE TABLE #ExistPriceTrcak
(
	BtypeId VARCHAR(100),
	BtypeFlag INT,
	PtypeId VARCHAR(100),
	StypeId VARCHAR(100),
	UId INT,
	CId INT,
	Price  NUMERIC(24, 10) ,
	DiscountRate  NUMERIC(24, 10) ,
	DiscountPrice  NUMERIC(24, 10) ,
	FreePrice  NUMERIC(24, 10),
	tax  NUMERIC(24, 10) ,
	taxprice  NUMERIC(24, 10),
	TrackTime    DATETIME
)

--获取跟踪类型：往来单位/结算单位   0 结算单位 1往来单位
DECLARE @BtypeFlag VARCHAR(10)
IF(@QueryType = 0 OR @QueryType = 1 OR @QueryType = 4 OR @QueryType = 6)
	SELECT @BtypeFlag = Value FROM PriceTrackConfig WHERE Name = 'SaleBtypeFlag'
ELSE IF(@QueryType = 2 OR @QueryType = 3 OR @QueryType = 5 OR @QueryType = 7)
	SELECT @BtypeFlag = Value FROM PriceTrackConfig WHERE Name = 'BuyBtypeFlag'

IF(@BtypeFlag = -1)
	SET @BtypeFlag = 0

DECLARE @SQL VARCHAR(8000),@multiPrice VARCHAR(60)
IF(@PriceType = 1)
BEGIN
	IF @Price=1
		SET @strtempPrice='T.DiscountRate'
	IF @Price=2
		SET @strtempPrice='0'
END
ELSE IF(@PriceType = 2 OR @PriceType = 3 OR @PriceType = 5)
BEGIN
	IF @Price=1
		SET @strtempPrice='T.Price'
	IF @Price=2
		SET @strtempPrice='T.DiscountPrice'
	IF @Price=3
		SET @strtempPrice='0'
	IF @Price=4
		SET @strtempPrice='t.taxprice'	
	IF @Price=5
		SET @strtempPrice='PreSalePrice1'
	IF @Price=6
		SET @strtempPrice='PreSalePrice2'
	IF @Price=7
		SET @strtempPrice='PreSalePrice3'
	IF @Price=8
		SET @strtempPrice='PreSalePrice4'
	IF @Price=9
		SET @strtempPrice='PreSalePrice5'
	IF @Price=10
		SET @strtempPrice='PreSalePrice6'
	IF @Price=11
		SET @strtempPrice='PreSalePrice7'
	IF @Price=12
		SET @strtempPrice='PreSalePrice8'
	IF @Price=13
		SET @strtempPrice='PreSalePrice9'
	IF @Price=14
		SET @strtempPrice='PreSalePrice10'
	IF @Price=15
		SET @strtempPrice='PreBuyPrice1'
	IF @Price=16
		SET @strtempPrice='PreBuyPrice2'
	IF @Price=17
		SET @strtempPrice='PreBuyPrice3'
	IF @Price=18
		SET @strtempPrice='PreBuyPrice4'
	IF @Price=19
		SET @strtempPrice='PreBuyPrice5'
	IF @Price=20
		SET @strtempPrice='RetailPrice'
	IF @Price=21
		SET @strtempPrice='TopSalePrice'
	IF @Price=22
		SET @strtempPrice='LowSalePrice'
	IF @Price=23
		SET @strtempPrice='RetailPrice' --特殊处理，其实是不用的，为了组合sql语句需要	
END
ELSE IF(@PriceType =4)
BEGIN
	IF @Price=1
		SET @strtempPrice='T.tax'
	IF @Price=2
		SET @strtempPrice='0'
END	
DECLARE @UIDTYPE VARCHAR(20)
IF @UID=1
	SET @UIDTYPE = 'baseUnitId'
IF @uid = 2
	SET @UIDTYPE = 'BuyUnitId'
IF @uid = 3
	SET @UIDTYPE = 'SaleUnitId'
IF @uid = 4
	SET @UIDTYPE = 'StockUnitId'

--币种
CREATE TABLE #Ac_Currency
(
	CID INT,
	Cname VARCHAR(50),
	JoinFlag INT
)
INSERT INTO #Ac_Currency 
SELECT cid,fullname,1 FROM Ac_Currency
WHERE (NOT(@CID <> 0) 
	OR (@CID <> 0) AND CID = @CID)

--表名
DECLARE @TABLE VARCHAR(50)
IF(@QueryType = 0)
	SET @TABLE = 'PriceTrack_SaleOrder'
ELSE IF(@QueryType = 1)
	SET @TABLE = 'PriceTrack_Sale'
ELSE IF(@QueryType = 2)
	SET @TABLE = 'PriceTrack_BuyOrder'
ELSE IF(@QueryType = 3)
	SET @TABLE = 'PriceTrack_Buy'
ELSE IF(@QueryType = 4)
	SET @TABLE = 'PriceTrack_Quote'
ELSE IF(@QueryType = 5)
	SET @TABLE = 'PriceTrack_AskPrice'
ELSE IF(@QueryType = 6)
	SET @TABLE = 'PriceTrack_Send'
ELSE IF(@QueryType = 7)
	SET @TABLE = 'PriceTrack_Appraisal'
	
--DECLARE @IfStypePrice VARCHAR(2),@PriceTable VARCHAR(50)  
--SET @PriceTable='PType_Price'  
--SELECT @IfStypePrice=PriceType FROM SType WHERE typeid=@STypeId   
--IF @IfStypePrice='1'  
-- SET @PriceTable = 'PType_STypePrice'

DECLARE @nowtime NVARCHAR(100)
SET @nowtime= CONVERT(varchar(100), GETDATE(), 20) 


IF @Flag='true' OR @Flag='1' --显示零
	BEGIN
		CREATE TABLE #Btype(
			BTypeId varchar(100),
			JoinFlag int
		)
		--往来单位临时表
		INSERT INTO #Btype SELECT typeId AS BTypeId,1 AS JoinFlag FROM Btype 
		WHERE 	typeId LIKE @BtypeId+'%' AND SonNum=0 
				AND Deleted=0 
				AND TypeId IN (SELECT TypeId FROM #GetManBTypeId)
				AND UserCode LIKE '%'+@BUserCode+'%'
				AND FullName LIKE '%'+@BFullName+'%'
				
		CREATE TABLE #Ptype(
			PTypeId varchar(100),
			uid  INT,
            [FreePrice]  NUMERIC(24, 10)  NULL,
			JoinFlag int
		)
		
			--商品临时表
			SET @SQL='INSERT INTO #Ptype 
					  SELECT	p1.typeId AS PTypeId,
								pue.unitsid,
								'
								+ 
								CASE 
									WHEN @Price = 1 OR @Price = 2 OR @Price = 3 OR @Price = 4 OR  @Price = 23 THEN '0 AS FreePrice,'
									ELSE 'p.' + @strtempPrice + ' AS FreePrice,'
								END 
								+'
								1 AS JoinFlag  
					  FROM	Ptype  P1
					  LEFT JOIN PType_Price  P ON P1.typeid=p.PTypeID
					  INNER JOIN PType_Units_ext PUe ON (PUe.ptypeid = p1.typeid and p.UnitID=pue.UnitsId)
					  INNER JOIN PType_Units PU ON pu.unitsid = pue.unitsid
					  INNER JOIN #GetManPTypeId PK ON PK.TypeId=p1.TypeID
					  WHERE 	P1.SonNum=0 AND PUe.RATETYPE=0
								AND P1.UserCode LIKE ''%'+ISNULL(@PUserCode,'')+'%''
								AND P1.FullName LIKE ''%'+ISNULL(@PFullName,'')+'%''
								'
				IF @uid <> 0
					SET @SQL= @SQL+' AND PUe.unitsid=p1.'+@UIDTYPE
					
			EXEC(@SQL)

			--构造临时表
			SET @SQL='INSERT INTO #PriceTrack
					  SELECT 	B.BTypeId,
								' + @BtypeFlag + ' AS BtypeFlag,
								P1.PTypeId,
								s.typeid AS STypeId,
								p1.uid,
								ac.cid as cid,
								0 AS Price,
								1 AS DiscountRate,
								0 AS DiscountPrice,
								FreePrice,
								0 as tax,
								0 as taxprice,
								'''+@nowtime+'''
					FROM #Btype B 
					LEFT JOIN #Ptype P1 ON B.JoinFlag=P1.JoinFlag 
					INNER JOIN #Ac_Currency AC ON AC.JoinFlag = B.JoinFlag
					INNER JOIN #GetManSTypeId s ON b.JoinFlag=s.JoinFlag
						 WHERE s.pricetype=0
					 '    
			EXEC(@SQL)
			DELETE  #Ptype
			
			SET @SQL='INSERT INTO #Ptype 
				  SELECT	p1.typeId AS PTypeId,
							pue.unitsid,
							'
							+ 
							CASE 
								WHEN @Price = 1 OR @Price = 2 OR @Price = 3 OR @Price = 4 OR  @Price = 23 THEN '0 AS FreePrice,'
								ELSE 'p.' + @strtempPrice + ' AS FreePrice,'
							END 
							+'
							1 AS JoinFlag  
				  FROM	Ptype  P1
				  LEFT JOIN PType_STypePrice  P ON P1.typeid=p.PTypeID
				  INNER JOIN PType_Units_ext PUe ON (PUe.ptypeid = p1.typeid and p.UnitID=pue.UnitsId)
				  INNER JOIN PType_Units PU ON pu.unitsid = pue.unitsid
				  INNER JOIN #GetManPTypeId PK ON PK.TypeId=p1.TypeID
				  WHERE 	P1.SonNum=0 AND PUe.RATETYPE=0
							AND P1.UserCode LIKE ''%'+ISNULL(@PUserCode,'')+'%''
							AND P1.FullName LIKE ''%'+ISNULL(@PFullName,'')+'%''
							AND P.StypeID='+@STypeId
			IF @uid <> 0
				SET @SQL= @SQL+' AND PUe.unitsid=p1.'+@UIDTYPE
					
			EXEC(@SQL)
	        
       		--构造临时表
			SET @SQL='INSERT INTO #PriceTrack
					  SELECT 	B.BTypeId,
								' + @BtypeFlag + ' AS BtypeFlag,
								P1.PTypeId,
								s.typeid AS STypeId,
								p1.uid,
								ac.cid as cid,
								0 AS Price,
								1 AS DiscountRate,
								0 AS DiscountPrice,
								FreePrice,
								0 as tax,
								0 as taxprice,'''+@nowtime+'''
					FROM #Btype B 
					LEFT JOIN #Ptype P1 ON B.JoinFlag=P1.JoinFlag 
					INNER JOIN #Ac_Currency AC ON AC.JoinFlag = B.JoinFlag
					INNER JOIN #GetManSTypeId s ON b.JoinFlag=s.JoinFlag
						 WHERE s.pricetype=1
					 '
			EXEC(@SQL)
		
	DROP TABLE #Btype
	DROP TABLE #Ptype
	
		DECLARE @RecordSQL VARCHAR(MAX)
		--PriceTrack中没有的记录
		SET @RecordSQL = '
		INSERT INTO #NoExistPriceTrcak 
		SELECT * 
		FROM #PriceTrack P1
		WHERE NOT EXISTS (
		SELECT TOP 1 1 FROM ' + @TABLE + ' a 
		inner join #GetManSTypeId b on a.stypeid=b.typeid  
		WHERE BtypeId=P1.BTypeId AND PtypeId=P1.PTypeId 
		 AND p1.CID=cid AND p1.UID=UID AND BTypeFlag= ' + @BtypeFlag + ')
		'
		
		EXEC(@RecordSQL)
	
		--PriceTrack中有的记录
		SET @RecordSQL = '
		INSERT INTO #ExistPriceTrcak 
		SELECT * 
		FROM #PriceTrack P1
		WHERE EXISTS (
		SELECT TOP 1 1 FROM ' + @TABLE + ' a 
		inner join #GetManSTypeId b on a.stypeid=b.typeid 
		WHERE BtypeId=P1.BTypeId AND PtypeId=P1.PTypeId   
		 AND p1.CID=cid AND p1.UID=UID AND BTypeFlag=' + @BtypeFlag + ')
		'
		EXEC(@RecordSQL)
	
		--删除临时表
		DROP TABLE #PriceTrack

		IF(@PriceType = 1 OR @PriceType=4)
			SET @updatePrice = @strtempPrice
		ELSE IF(@PriceType = 2 OR @PriceType = 3 OR @PriceType=5)
		BEGIN
			IF(@Price < 5)
				SET @updatePrice = @strtempPrice
			ELSE
				SET @updatePrice = 'ISNULL(P.'+@strtempPrice+',0)'  
		END 

		IF @Caculate=1 --加
			SET @strNewValue=@updatePrice+'+'+CAST(@ZhengLiang AS varchar(100))
		IF @Caculate=2 --减
			SET @strNewValue=@updatePrice+'-'+CAST(@ZhengLiang AS varchar(100))
		IF @Caculate=3 --乘
			SET @strNewValue=@updatePrice+'*'+CAST(@ZhengLiang AS varchar(100))
		IF @Caculate=4 --除
			SET @strNewValue=@updatePrice+'/'+CAST(@ZhengLiang AS varchar(100))
					--select @strNewValue
					--select 3/Price from #NoExistPriceTrcak
					--RETURN 
		
		--折扣判断
		IF @PriceType = '1'
		BEGIN

             CREATE TABLE #Count1
             (
              count1 INT
             )				      
		     DECLARE @minDiscount NUMERIC(24,10) = 0;
		     DECLARE @count INT = 0;
		     DECLARE @discountStr varchar(max);
		     
		     SELECT @minDiscount = SaleMinvalue  FROM dbo.employee WHERE typeId = @OperatOrId;
		    SET @discountStr = 'Insert #Count1 SELECT Count(*) 
			FROM	' + @TABLE  + ' T
                    LEFT JOIN PType P1 ON  T.PTypeId = P1.TypeId	
				    LEFT JOIN BType B ON  T.BTypeId = B.TypeId
				    LEFT JOIN ptype_price P ON T.Ptypeid=p.PTypeID
                    inner join #GetManSTypeId  s on t.stypeid=s.typeid
			        WHERE   P1.UserCode LIKE '+char(39)+'%'+@PUserCode+'%'+char(39)+'
					AND P1.FullName LIKE '+char(39)+'%'+@PFullName+'%'+char(39)+'
					AND B.UserCode LIKE '+char(39)+'%'+@BUserCode+'%'+char(39)+'
					AND B.FullName LIKE '+char(39)+'%'+@BFullName+'%'+char(39)+'		
					AND T.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'					
					AND T.PTypeId IN (SELECT TypeId FROM #GetManPTypeId)
					AND T.BTypeId IN (SELECT TypeId FROM #GetManBTypeId)
			    	AND T.btypeflag='+char(39)+@BtypeFlag+char(39)+' 
					AND ISNULL(T.Price,0) <> 0
					AND ((' + @strNewValue + ') < ' + CAST(@minDiscount AS VARCHAR(200)) + ')';

			IF @cid <> 0
				SET @discountStr= @discountStr+' AND T.cid='+CAST(@cid AS VARCHAR)
			IF @uid <> 0
				SET @discountStr= @discountStr+' AND t.uid=p1.'+@UIDTYPE
		     
		     
		     --PRINT @discountStr;
		     exec(@discountStr);		    
		     
		     SELECT @count = count1 FROM #Count1;
		     --PRINT @count;
		     IF @count > 0
		     begin
		        return -999;
		     end
		     
		     drop table #COunt1;
		END
		
		--SELECT * FROM #NoExistPriceTrcak
		--处理PriceTrack中没有的记录
        SET @szSQL = 'UPDATE #NoExistPriceTrcak 
			SET 
			'
            + CASE WHEN @PriceType = '1'
                   THEN 'DiscountRate =CASE WHEN CASE WHEN CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) <= 0 THEN 1 ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) END > 9.9999999999 THEN 9.9999999999 ELSE CASE WHEN CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) <= 0 THEN 1 ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) END END '
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '1'
                          AND @rule = '1'
                     THEN ',taxprice=CASE WHEN (' + @strNewValue
                          + ') <= 0 THEN (T.Price * 1) WHEN (' + @strNewValue
                          + ') > 9.9999 THEN (T.Price * 9.9999) ELSE cast( Price * CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END *(1+tax/100)
                          ,DiscountPrice=CASE WHEN (' + @strNewValue
                          + ') <= 0 THEN (T.Price * 1) WHEN (' + @strNewValue
                          + ') > 9.9999 THEN (T.Price * 9.9999) ELSE cast( Price * CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '1'
                        AND @rule = '2'
                   THEN ',Price=CASE WHEN DiscountPrice = 0 THEN 0 ELSE cast( DiscountPrice / CASE WHEN CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) <=0 THEN 1 WHEN CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) > 9.9999 THEN 9.9999 ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) END AS  NUMERIC(24, 10) ) END'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '2'
                     THEN 'Price=CAST(' + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) )'
                     ELSE ''
                END + '
			' + CASE WHEN @PriceType = '2'
                          AND @rule = '1'
                     THEN '
                   ,taxprice=  cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) * DiscountRate AS  NUMERIC(24, 10) )*(1+tax/100)
                     
                     ,DiscountPrice=cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) * DiscountRate AS  NUMERIC(24, 10) )'
                     ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '2'
                        AND @rule = '2'
                   THEN ',DiscountRate=CASE WHEN DiscountPrice = 0 THEN 0 ELSE cast( DiscountPrice / CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '3'
                     THEN 'DiscountPrice=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN (T.Price * 1) ELSE CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '3'
                        AND @rule = '1'
                   THEN '
                    ,taxprice=  CASE WHEN ('
                        + @strNewValue + ') <=0 THEN 1 ELSE CAST( CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END*(1+tax/100)
                   ,DiscountRate=CASE WHEN Price <= 0 THEN 0 ELSE CASE WHEN ('
                        + @strNewValue + ') <=0 THEN 1 ELSE CAST( CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) / Price AS  NUMERIC(24, 10) ) END END'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '3'
                          AND @rule = '2'
                     THEN '
                     ,taxprice=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN 1 ELSE cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) )AS  NUMERIC(24, 10) ) END*(1+tax/100)
                     ,Price=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN 1 ELSE cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) / DiscountRate AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END + '
                
                '  + CASE WHEN @PriceType = '4'
                   THEN '
                      tax=    CASE WHEN ('
                        + @strNewValue + ') >99 THEN 99 
                        WHEN ('
                        + @strNewValue + ') <0 THEN 0
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end 
                        '
                   ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '4'
                        AND @rule = '1'
                   THEN '
                    ,DiscountPrice=  case when  1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 <=0 THEN taxprice
                         ELSE 
                           taxprice/CASE WHEN 1+('
                        + @strNewValue + ')/100 >99 THEN 99 
                        ELSE 1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end  end 
                           
                   ,price= case when DiscountRate=0 then 0 else  case when  1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 <=0 THEN taxprice
                         ELSE 
                           taxprice/CASE WHEN 1+ ('
                        + @strNewValue + ')/100 >99 THEN 99 
                        ELSE 1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end  end / DiscountRate end'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '4'
                          AND @rule = '2'
                     THEN '
                     ,taxprice= CASE WHEN 1+('
                        + @strNewValue + ')/100 >99 THEN 99   
                         when 1+('
                        + @strNewValue + ')/100 <0 THEN 1                           
                        ELSE 1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end *DiscountPrice                       
                     '
                     ELSE ''
                END + 
                '
                   '  + CASE WHEN @PriceType = '5'
                   THEN '
                      taxprice=  CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end 
                        '
                   ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '5'
                        AND @rule = '1'
                   THEN '
                    ,DiscountPrice= CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+tax/100)
                           
                   ,price= case when DiscountRate=0 THEN 0 ELSE CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+tax/100)/DiscountRate END '
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '5'
                          AND @rule = '2'
                     THEN '
                      ,DiscountPrice= CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+tax/100)
                           
                     ,DiscountRate= case when price=0 then 0 else   CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+tax/100)/price  end '
                     ELSE ''
                END + 
                ',
                TrackTime='''+@nowtime+'''
			FROM #NoExistPriceTrcak T   
                --LEFT JOIN Ptype P1 ON T.PtypeId=P1.typeId
                LEFT JOIN ptype_price P ON (T.Ptypeid=p.PTypeID and p.UnitID=T.UID)
           
           
               --WHERE	T.Stypeid=' + CHAR(39) + @STypeId + CHAR(39) + ''
 
		BEGIN TRANSACTION
		--PRINT @szSQL
		EXECUTE(@szSQL)
		SET @introwcount = @@rowcount
		SELECT @tablerow=COUNT(*) FROM #NoExistPriceTrcak
		IF @tablerow>0 AND @introwcount<1
		BEGIN
			ROLLBACK TRANSACTION
			RETURN -4
		END
		ELSE
		BEGIN
			COMMIT TRANSACTION
		END
	
		--从临时表导入新添加的记录
		BEGIN TRANSACTION
		DECLARE @TEMPSQL VARCHAR(MAX)

		SET @TEMPSQL = '
		INSERT INTO 
			' + @TABLE + '(BtypeID,BtypeFlag,PtypeId,StypeId,UId,CId,Price,DiscountRate,DiscountPrice,tax,taxprice,TrackTime)
			SELECT BtypeID,BtypeFlag,PtypeId,StypeId,UId,CId,Price,DiscountRate,DiscountPrice,tax,taxprice,TrackTime 
			FROM #NoExistPriceTrcak
		'
		
		EXECUTE(@TEMPSQL)
		SET @introwcount = @@rowcount
		--SELECT @introwcount
		IF @tablerow>0 AND @introwcount<1
		BEGIN
			ROLLBACK TRANSACTION
			RETURN -5
		END
		ELSE
		BEGIN
			COMMIT TRANSACTION
		END
		DROP TABLE #NoExistPriceTrcak
		
		--处理PriceTrack中有的记录
        SET @szSQL = 'UPDATE	' + @TABLE + ' 
			SET	
			'
            + CASE WHEN @PriceType = '1'
                       THEN 'DiscountRate = CASE WHEN CASE WHEN CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) <= 0 THEN 1 ELSE CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) END > 9.9999 THEN 9.9999 ELSE CASE WHEN CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) <= 0 THEN 1 ELSE CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) END END '
                       ELSE ''
                  END + '
			' + CASE WHEN @PriceType = '1'
                          AND @rule = '1'
                     THEN '
                        ,taxprice=CASE WHEN (' + @strNewValue
                          + ') <= 0 THEN (T.Price * 1) WHEN (' + @strNewValue
                          + ') > 9.9999 THEN (T.Price * 9.9999) ELSE cast( t.Price * CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END *(1+t.tax/100)
                     ,DiscountPrice=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN (T.Price * 1) WHEN (' + @strNewValue
                          + ') > 9.9999 THEN (T.Price * 9.9999) ELSE cast( T.Price * CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END + '
			'
                + CASE WHEN @PriceType = '1'
                            AND @rule = '2'
                       THEN ',Price=CASE WHEN T.DiscountPrice = 0 THEN 0 ELSE cast( T.DiscountPrice / CASE WHEN CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) <= 0 THEN 1 WHEN CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) > 9.9999 THEN 9.9999 ELSE CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) END AS  NUMERIC(24, 10) ) END'
                       ELSE ''
                  END + '
			' + CASE WHEN @PriceType = '2'
                     THEN 'Price=CAST(' + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) )'
                     ELSE ''
                END + '
			' + CASE WHEN @PriceType = '2'
                          AND @rule = '1'
                     THEN '
                         ,taxprice=  cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) * t.DiscountRate AS  NUMERIC(24, 10) )*(1+t.tax/100)
                     
                     ,DiscountPrice=cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) * T.DiscountRate AS  NUMERIC(24, 10) )'
                     ELSE ''
                END + '
			'
                + CASE WHEN @PriceType = '2'
                            AND @rule = '2'
                       THEN ',DiscountRate=CASE WHEN T.DiscountPrice = 0 THEN 0 ELSE cast( T.DiscountPrice / CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END'
                       ELSE ''
                  END + '
			' + CASE WHEN @PriceType = '3'
                     THEN 'DiscountPrice=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN (T.DiscountPrice * 1) ELSE CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END + '
			'
                + CASE WHEN @PriceType = '3'
                            AND @rule = '1'
                       THEN '
                           ,taxprice=  CASE WHEN ('
                        + @strNewValue + ') <=0 THEN 1 ELSE CAST( CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END*(1+t.tax/100)
                       ,DiscountRate=CASE WHEN T.Price <= 0 THEN 0 ELSE CASE WHEN ('
                            + @strNewValue
                            + ') <=0 THEN T.DiscountRate ELSE cast( CAST('
                            + CAST(@strNewValue AS VARCHAR(200))
                            + ' AS  NUMERIC(24, 10) ) / T.Price AS  NUMERIC(24, 10) ) END END'
                       ELSE ''
                  END + '
			' + CASE WHEN @PriceType = '3'
                          AND @rule = '2'
                     THEN '
                       ,taxprice=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN 1 ELSE cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) )AS  NUMERIC(24, 10) ) END*(1+t.tax/100)
                     ,Price=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN T.Price ELSE cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) / T.DiscountRate AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END +  '
                
                 
                '  + CASE WHEN @PriceType = '4'
                   THEN '
                      tax=    CASE WHEN ('
                        + @strNewValue + ') >99 THEN 99 
                        WHEN ('
                        + @strNewValue + ') <0 THEN 0
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end 
                        '
                   ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '4'
                        AND @rule = '1'
                   THEN '
                    ,DiscountPrice=  case when  1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100<=0 THEN t.taxprice
                         ELSE 
                           t.taxprice/CASE WHEN 1+ ('
                        + @strNewValue + ')/100 >99 THEN 99 
                        ELSE 1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end  end 
                           
                   ,price= case when t.DiscountRate=0 then 0 else  case when  1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100<=0 THEN t.taxprice
                         ELSE 
                           t.taxprice/CASE WHEN 1+('
                        + @strNewValue + ')/100 >99 THEN 99 
                        ELSE 1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end  end / t.DiscountRate end'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '4'
                          AND @rule = '2'
                     THEN '
                     ,taxprice= CASE WHEN 1+('
                        + @strNewValue + ')/100 >99 THEN 99
                         when 1+('
                        + @strNewValue + ')/100<0 THEN 1                    
                        ELSE 1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end *t.DiscountPrice                       
                     '
                     ELSE ''
                END + 
                '
                   '  + CASE WHEN @PriceType = '5'
                   THEN '
                      taxprice=  CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end 
                        '
                   ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '5'
                        AND @rule = '1'
                   THEN '
                    ,DiscountPrice= CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+t.tax/100)
                           
                   ,price= case when t.DiscountRate=0 THEN 0 ELSE CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+t.tax/100)/t.DiscountRate END '
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '5'
                          AND @rule = '2'
                     THEN '
                      ,DiscountPrice= CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+t.tax/100)
                           
                     ,DiscountRate= case when t.price=0 then 0 else   CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+t.tax/100)/t.price  end '
                     ELSE ''
                END + '
                ,
                TrackTime='''+@nowtime+'''
					FROM	' + @TABLE
            + ' T 
			INNER JOIN #ExistPriceTrcak TT ON(T.PtypeId=TT.PtypeId AND T.BtypeId=TT.BtypeId AND TT.STypeId = T.STypeId 
			AND T.UID=TT.UID AND T.CID = TT.CID AND T.btypeflag='
            + CHAR(39) + @BtypeFlag + CHAR(39) + ')
			LEFT JOIN ptype_price P ON (T.Ptypeid=p.PTypeID AND p.UnitID=T.UID)	 	 
							'
				
		BEGIN TRANSACTION
		--PRINT @szSQL
		EXECUTE(@szSQL)					
		SET @introwcount = @@rowcount
		SELECT @tablerow=COUNT(*) FROM #ExistPriceTrcak
		IF @tablerow>0 AND @introwcount<1
			BEGIN
				ROLLBACK TRANSACTION
				RETURN -2
			END
		ELSE
			BEGIN
				COMMIT TRANSACTION
			END
		
		--DROP TABLE #ExistPriceTrcak
							    
		----修改价格小于0的信息
		--SET @UPSQL = 
		--'
		--	UPDATE ' + @TABLE + ' SET Price = 0 WHERE Price < 0 OR Price IS NULL 
		--	UPDATE ' + @TABLE + ' SET DiscountRate = 1 WHERE DiscountRate IS NULL OR DiscountRate <= 0 
		--	UPDATE ' + @TABLE + ' SET DiscountPrice = 0 WHERE DiscountPrice < 0 OR DiscountPrice IS NULL 
		--	UPDATE ' + @TABLE + ' SET DiscountRate = 9.9999,DiscountPrice = Price * 9.9999 
		--	WHERE DiscountRate > 9.9999
		--'
		--EXEC(@UPSQL)
	END
ELSE --不显示跟踪价为零
	BEGIN
		SET	@szSQL = '
			INSERT INTO #PriceTrack
			SELECT	B.TypeId AS BTypeId,
					' + @BtypeFlag + ' AS BtypeFlag,
					P1.TypeId AS PTypeId,
					s.typeid AS STypeID,
					t.UID,
					t.CID,
					T.Price,
					T.DiscountRate,
					T.DiscountPrice,
					'
					+ 
							CASE 
								WHEN @Price = 1 OR @Price = 2 OR @Price = 3 OR @Price = 4 OR @price=23 THEN '0 AS FreePrice '
								ELSE 'P.' + @strtempPrice + ' AS FreePrice '
							END 
					+
					',
					T.tax,
					T.taxprice,
					t.TrackTime
			FROM	' + @TABLE + ' T
                    LEFT JOIN PType P1 ON  T.PTypeId = P1.TypeId	
				    LEFT JOIN BType B ON  T.BTypeId = B.TypeId
				    LEFT JOIN ptype_price P ON T.Ptypeid=p.PTypeID
                    inner join #GetManSTypeId  s on t.stypeid=s.typeid
			WHERE   P1.UserCode LIKE '+char(39)+'%'+@PUserCode+'%'+char(39)+'
					AND P1.FullName LIKE '+char(39)+'%'+@PFullName+'%'+char(39)+'
					AND B.UserCode LIKE '+char(39)+'%'+@BUserCode+'%'+char(39)+'
					AND B.FullName LIKE '+char(39)+'%'+@BFullName+'%'+char(39)+'		
					AND T.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
					
					AND T.PTypeId IN (SELECT TypeId FROM #GetManPTypeId)
					AND T.BTypeId IN (SELECT TypeId FROM #GetManBTypeId)
					AND T.btypeflag='+char(39)+@BtypeFlag+char(39)+' 
					AND ISNULL(T.Price,0) <> 0 
					'
			IF @cid <> 0
				SET @szSQL= @szSQL+' AND T.cid='+CAST(@cid AS VARCHAR)
			IF @uid <> 0
				SET @szSQL= @szSQL+' AND t.uid=p1.'+@UIDTYPE
				
		EXECUTE(@szSQL)
		
		IF(@PriceType = 1 OR @PriceType = 4)
			SET @updatePrice = @strtempPrice
		ELSE IF(@PriceType = 2 OR @PriceType = 3 OR @PriceType = 5)
		BEGIN
			IF(@Price < 5)
				SET @updatePrice = @strtempPrice
			ELSE
				SET @updatePrice = 'ISNULL(P.'+@strtempPrice+',0)'  
		END 
		
		--处理有价格跟踪的
		IF @Caculate=1 --加
			SET @strNewValue=@updatePrice+'+'+CAST(@ZhengLiang AS varchar(100))
		IF @Caculate=2 --减
			SET @strNewValue=@updatePrice+'-'+CAST(@ZhengLiang AS varchar(100))
		IF @Caculate=3 --乘
			SET @strNewValue=@updatePrice+'*'+CAST(@ZhengLiang AS varchar(100))
		IF @Caculate=4 --除
			SET @strNewValue=@updatePrice+'/'+CAST(@ZhengLiang AS varchar(100))


--折扣判断
		IF @PriceType = '1'
		BEGIN

             CREATE TABLE #Count
             (
              count1 INT
             )				      
		     DECLARE @minDiscount1 NUMERIC(24,10) = 0;
		     DECLARE @count1 INT = 0;
		     DECLARE @discountStr1 varchar(max);
		     
		     SELECT @minDiscount1 = SaleMinvalue  FROM dbo.employee WHERE typeId = @OperatOrId;
		    SET @discountStr1 = 'Insert #Count SELECT Count(*) 
			FROM	' + @TABLE  + ' T
                    LEFT JOIN PType P1 ON  T.PTypeId = P1.TypeId	
				    LEFT JOIN BType B ON  T.BTypeId = B.TypeId
				    LEFT JOIN ptype_price P ON T.Ptypeid=p.PTypeID
                    inner join #GetManSTypeId  s on t.stypeid=s.typeid
			        WHERE   P1.UserCode LIKE '+char(39)+'%'+@PUserCode+'%'+char(39)+'
					AND P1.FullName LIKE '+char(39)+'%'+@PFullName+'%'+char(39)+'
					AND B.UserCode LIKE '+char(39)+'%'+@BUserCode+'%'+char(39)+'
					AND B.FullName LIKE '+char(39)+'%'+@BFullName+'%'+char(39)+'		
					AND T.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'					
					AND T.PTypeId IN (SELECT TypeId FROM #GetManPTypeId)
					AND T.BTypeId IN (SELECT TypeId FROM #GetManBTypeId)
			    	AND T.btypeflag='+char(39)+@BtypeFlag+char(39)+' 
					AND ISNULL(T.Price,0) <> 0
					AND ((' + @strNewValue + ') < ' + CAST(@minDiscount1 AS VARCHAR(200)) + ')';

			IF @cid <> 0
				SET @discountStr1= @discountStr1+' AND T.cid='+CAST(@cid AS VARCHAR)
			IF @uid <> 0
				SET @discountStr1= @discountStr1+' AND t.uid=p1.'+@UIDTYPE
		     
		     
		     --PRINT @discountStr1;
		     exec(@discountStr1);		    
		     
		     SELECT @count1 = count1 FROM #Count;
		     --PRINT @count1;
		     IF @count1 > 0
		     begin
		        return -999;
		     end
		     
		     drop table #COunt;
		END

        SET @szSQL = 'UPDATE	' + @TABLE + ' 
			SET	
			'
            + CASE WHEN @PriceType = '1'
                   THEN 'DiscountRate = CASE WHEN CASE WHEN CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) <= 0 THEN 1 ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) END > 9.9999 THEN 9.9999 ELSE CASE WHEN CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) <= 0 THEN 1 ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) END END '
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '1'
                          AND @rule = '1'
                     THEN '
                     ,taxprice=CASE WHEN (' + @strNewValue
                          + ') <= 0 THEN (T.Price * 1) WHEN (' + @strNewValue
                          + ') > 9.9999999999 THEN (T.Price * 9.9999999999) ELSE cast( t.Price * CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END *(1+t.tax/100)
                     ,DiscountPrice=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN (T.Price * 1) WHEN (' + @strNewValue
                          + ') > 9.9999 THEN (T.Price * 9.9999999999) ELSE cast( T.Price * CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '1'
                        AND @rule = '2'
                   THEN ',Price=CASE WHEN T.DiscountPrice = 0 THEN 0 ELSE cast( T.DiscountPrice / CASE WHEN CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) <= 0 THEN 1 WHEN CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) > 9.9999 THEN 9.9999 ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) END AS  NUMERIC(24, 10) ) END'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '2'
                     THEN 'Price=CAST(' + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) )'
                     ELSE ''
                END + '
			' + CASE WHEN @PriceType = '2'
                          AND @rule = '1'
                     THEN '
                      ,taxprice=  cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) * t.DiscountRate AS  NUMERIC(24, 10) )*(1+t.tax/100)
                     ,DiscountPrice=cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) * T.DiscountRate AS  NUMERIC(24, 10) )'
                     ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '2'
                        AND @rule = '2'
                   THEN ',DiscountRate=CASE WHEN T.DiscountPrice = 0 THEN 0 ELSE cast( T.DiscountPrice / CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '3'
                     THEN 'DiscountPrice=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN (T.DiscountPrice * 1) ELSE CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '3'
                        AND @rule = '1'
                   THEN '
                       ,taxprice=  CASE WHEN ('
                        + @strNewValue + ') <=0 THEN 1 ELSE CAST( CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) END*(1+t.tax/100)
                   ,DiscountRate=CASE WHEN T.Price <= 0 THEN 0 ELSE CASE WHEN ('
                        + @strNewValue
                        + ') <=0 THEN T.DiscountRate ELSE cast( CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10) ) / T.Price AS  NUMERIC(24, 10) ) END END'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '3'
                          AND @rule = '2'
                     THEN '
                         ,taxprice=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN 1 ELSE cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) )AS  NUMERIC(24, 10) ) END*(1+t.tax/100)
                     
                     ,Price=CASE WHEN (' + @strNewValue
                          + ') <=0 THEN T.Price ELSE cast( CAST('
                          + CAST(@strNewValue AS VARCHAR(200))
                          + ' AS  NUMERIC(24, 10) ) / T.DiscountRate AS  NUMERIC(24, 10) ) END'
                     ELSE ''
                END + '
                
                   '  + CASE WHEN @PriceType = '4'
                   THEN '
                      tax=    CASE WHEN ('
                        + @strNewValue + ') >99 THEN 99 
                        WHEN ('
                        + @strNewValue + ') <0 THEN 0
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end 
                        '
                   ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '4'
                        AND @rule = '1'
                   THEN '
                    ,DiscountPrice=  case when  1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100<=0 THEN t.taxprice
                         ELSE 
                           t.taxprice/CASE WHEN 1+('
                        + @strNewValue + ')/100 >99 THEN 99 
                        ELSE  1+CAST ('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end  end 
                           
                   ,price= case when t.DiscountRate=0 then 0 else  case when  1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100<=0 THEN t.taxprice
                         ELSE 
                           t.taxprice/CASE WHEN 1+('
                        + @strNewValue + ')/100 >99 THEN 99 
                        ELSE 1+ CAST ('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end  end / t.DiscountRate end'
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '4'
                          AND @rule = '2'
                     THEN '
                     ,taxprice= CASE WHEN 1+('
                        + @strNewValue + ')/100 >99 THEN 99
                        when 1+('
                        + @strNewValue + ')/100<0 THEN 1
                                                
                        ELSE 1+ CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10))/100 end *t.DiscountPrice                       
                     '
                     ELSE ''
                END + 
                '
                   '  + CASE WHEN @PriceType = '5'
                   THEN '
                      taxprice=  CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end 
                        '
                   ELSE ''
                END + '
			'
            + CASE WHEN @PriceType = '5'
                        AND @rule = '1'
                   THEN '
                    ,DiscountPrice= CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+t.tax/100)
                           
                   ,price= case when t.DiscountRate=0 THEN 0 ELSE CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+t.tax/100)/t.DiscountRate END '
                   ELSE ''
              END + '
			' + CASE WHEN @PriceType = '5'
                          AND @rule = '2'
                     THEN '
                      ,DiscountPrice= CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+t.tax/100)
                           
                     ,DiscountRate= case when t.price=0 then 0 else   CASE WHEN ('
                        + @strNewValue + ') <0 THEN 0 
                        ELSE CAST('
                        + CAST(@strNewValue AS VARCHAR(200))
                        + ' AS  NUMERIC(24, 10)) end /(1+t.tax/100)/t.price  end '
                     ELSE ''
                END + '
                ,
                TrackTime='''+@nowtime+'''
					FROM	' + @TABLE
            + ' T 
							INNER JOIN #PriceTrack TT ON(T.PtypeId=TT.PtypeId AND T.BtypeId=TT.BtypeId AND TT.STypeId = T.STypeId AND T.UID=TT.UID AND T.CID = TT.CID AND T.btypeflag='
            + CHAR(39) + @BtypeFlag + CHAR(39) + ')
					LEFT JOIN ptype_price P ON (T.Ptypeid=p.PTypeID AND p.UnitID=TT.UID)	
							'
							
							
									   --print  @szSQL
									   
		BEGIN TRANSACTION 
		EXECUTE(@szSQL)
		
		IF @@rowcount < 1
			BEGIN
				ROLLBACK TRANSACTION
				RETURN -2
			END
		ELSE
			BEGIN
				COMMIT TRANSACTION
			END
		DROP TABLE #PriceTrack

		----修改价格小于0的信息
		--SET @UPSQL = 
		--'
		--	UPDATE ' + @TABLE + ' SET Price = 0 WHERE Price < 0 OR Price IS NULL 
		--	UPDATE ' + @TABLE + ' SET DiscountRate = 1 WHERE DiscountRate IS NULL OR DiscountRate <= 0
		--	UPDATE ' + @TABLE + ' SET DiscountPrice = 0 WHERE DiscountPrice < 0 OR DiscountPrice IS NULL 
		--	UPDATE ' + @TABLE + ' SET DiscountRate = 9.9999,DiscountPrice = Price * 9.9999 
		--	WHERE DiscountRate > 9.9999
		--'
		--EXEC(@UPSQL)
		--return 0
	END
	
	--修改价格小于0的信息
		SET @UPSQL = 
		'
			UPDATE ' + @TABLE + ' SET Price = 0 WHERE Price < 0 OR Price IS NULL 
			UPDATE ' + @TABLE + ' SET DiscountRate = 1 WHERE DiscountRate IS NULL OR DiscountRate <= 0
			UPDATE ' + @TABLE + ' SET DiscountPrice = 0 WHERE DiscountPrice < 0 OR DiscountPrice IS NULL 
			UPDATE ' + @TABLE + ' SET DiscountRate = 9.9999,DiscountPrice = Price * 9.9999999999 
			WHERE DiscountRate > 9.9999999999
			
			DELETE FROM '+@TABLE+' WHERE Price=0 OR DiscountPrice=0 OR taxprice=0;
		'
		--PRINT @UPSQL
		EXEC(@UPSQL)
		return 0

DROP TABLE #GetManPTypeId,#GetManBTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


/*
	作者：杨俊
	日期：2014-04-23
	描述：更换价格跟踪表-完全重写
	
	作者：陈强
	日期：2019-09-18
	描述：增加筛选条件(9.91)
*/
CREATE          PROCEDURE Gp_PriceTrack
(
	@chrOperatorID 		VARCHAR(500),    	--操作员ID号
	@BTypeId			VARCHAR(max),    	--往来单位的ID
	@PTypeId			VARCHAR(max),    	--商品的ID
	@STypeId			VARCHAR(max),		--分支机构
	@QueryType			INT,				--查询类型  0.销售订单价格跟踪 1.销售价格跟踪   2.采购订单价格跟踪 3.采购价格跟踪 4.报价单价格跟踪 5.询价单价格跟踪 6.发出商品出库单 7.暂估入库单
	@PUserCode			VARCHAR(600)='',	--商品编号
	@PFullName			VARCHAR(600)='',	--商品名称
	@BUserCode			VARCHAR(600)='',	--客户编号
	@BFullName			VARCHAR(600)='',	--客户名称
	@Flag				INT,				--是否显示价格跟踪为0的商品
	@cid				INT,				--0代表所有币种
	@uid				INT,				--0表示所有单位
	
	-----9.91新增------
	@standard			varchar(256)='',	--商品规格
	@type				varchar(256)='',	--商品型号
	@name				VARCHAR(256)='',	--商品简名
	@pycode				VARCHAR(256)='',	--商品拼音码
	@entrycode			varchar(256)='',	--商品条码
	@pcategoryid		varchar(MAX),		--商品类别
	@area				varchar(256)=''		--商品产地
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chrOperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chrOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF(@QueryType NOT IN(0,1,2,3,4,5,6,7)) RETURN

--单位类型
DECLARE @UIDTYPE VARCHAR(20)
IF(@uid = 1)
	SET @UIDTYPE = 'baseUnitId'
ELSE IF(@uid = 2)
	SET @UIDTYPE = 'BuyUnitId'
ELSE IF(@uid = 3)
	SET @UIDTYPE = 'SaleUnitId'
ELSE IF(@uid = 4)
	SET @UIDTYPE = 'StockUnitId'
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(500),JoinFlag INT )
INSERT INTO #GetManSTypeId(TypeId ,JoinFlag) SELECT TypeId,1 FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chrOperatorID)	

--获取跟踪类型：往来单位/结算单位   0 结算单位 1往来单位
DECLARE @BtypeFlag INT
IF(@QueryType = 0 OR @QueryType = 1 OR @QueryType = 4 OR @QueryType = 6)
	SELECT @BtypeFlag = Value FROM PriceTrackConfig WHERE Name = 'SaleBtypeFlag'
ELSE IF(@QueryType = 2 OR @QueryType = 3 OR @QueryType = 5 OR @QueryType = 7)
	SELECT @BtypeFlag = Value FROM PriceTrackConfig WHERE Name = 'BuyBtypeFlag'

IF(@BtypeFlag = -1)
	SET @BtypeFlag = 0

---=================9.91版本新增====================---
DECLARE @SqlWhere NVARCHAR(max)
SET @SqlWhere=' '

IF @PUserCode<>''
	SET @SqlWhere=@SqlWhere+' AND pb.usercode LIKE ''%'+@PUserCode+'%'''
IF @PFullName<>''
	SET @SqlWhere=@SqlWhere+' AND pb.fullname LIKE ''%'+@PFullName+'%'''
IF @standard<>''
	SET @SqlWhere=@SqlWhere+' AND ISNULL(pb.standard,'''') LIKE ''%'+@standard+'%'''	
IF @type<>''
	SET @SqlWhere=@SqlWhere+' AND ISNULL(pb.type,'''') LIKE ''%'+@type+'%'''
IF @name<>''
	SET @SqlWhere=@SqlWhere+' AND ISNULL(pb.Name,'''') LIKE ''%'+@name+'%'''	
IF @pycode<>''
	SET @SqlWhere=@SqlWhere+' AND ISNULL(pb.PyCode,'''') LIKE ''%'+@pycode+'%'''	
IF @entrycode<>''
	SET @SqlWhere=@SqlWhere+' AND ISNULL(pb.entrycode,'''') LIKE ''%'+@entrycode+'%'''
IF @area<>''
	SET @SqlWhere=@SqlWhere+' AND ISNULL(pb.area,'''')  LIKE ''%'+@area+'%'''


---=====================END=========================---	


--商品：
CREATE TABLE #GetSelPTypeId
(
	TypeId		varchar(500),
	UserCode	VARCHAR(500),
	FullName	VARCHAR(500),
	JoinFlag	INT ,
	baseunitid  varchar(500),
	buyunitid   varchar(500),
	SaleUnitId	varchar(500),
	StockUnitId	varchar(500)
)


DECLARE @Psqls NVARCHAR(max)
IF @pcategoryid = '00000' OR @pcategoryid = '' OR @pcategoryid = '%'
	SET @Psqls = 'INSERT INTO #GetSelPTypeId(TypeId,UserCode,FullName,baseunitid,buyunitid,SaleUnitId,StockUnitId,JoinFlag)
				SELECT pb.typeid,pb.UserCode,pb.FullName,pb.baseunitid,pb.buyunitid,pb.SaleUnitId,pb.StockUnitId,1
				FROM ptype AS pb
				INNER JOIN F_GetAllManagerBaseTypeId('''+@PTypeId+''',1,'''+@chrOperatorID+''') AS sp ON(pb.typeId = sp.TypeId)
				INNER JOIN F_GetManDetailPType('''+@chrOperatorID+''') AS P ON(sp.TypeId = p.TypeId) where 1=1 ' + @SqlWhere
ELSE
	SET @Psqls = 'INSERT INTO #GetSelPTypeId(TypeId,UserCode,FullName,baseunitid,buyunitid,SaleUnitId,StockUnitId,JoinFlag)
				SELECT pb.typeid,pb.UserCode,pb.FullName,pb.baseunitid,pb.buyunitid,pb.SaleUnitId,pb.StockUnitId,1
				FROM ptype AS pb
				INNER JOIN PTypeCategory ptc on ptc.typeid=pb.PtypeCategoryID
				INNER JOIN (SELECT A FROM dbo.F_Split('''+@PCategoryId+''','','')) B ON  ptc.typeid LIKE B.A +''%''
				INNER JOIN F_GetAllManagerBaseTypeId('''+@PTypeId+''',1,'''+@chrOperatorID+''') AS sp ON(pb.typeId = sp.TypeId)
				INNER JOIN F_GetManDetailPType('''+@chrOperatorID+''') AS P ON(sp.TypeId = p.TypeId) where 1=1 ' + @SqlWhere

EXEC(@Psqls)


--币种
CREATE TABLE #Ac_Currency
(
	CID INT,
	Cname VARCHAR(500),
	JoinFlag INT
)
INSERT INTO #Ac_Currency 
SELECT cid,fullname,1 FROM Ac_Currency
WHERE (NOT(@CID <> 0) 
	OR (@CID <> 0) AND CID = @CID)

--往来/结算单位
CREATE TABLE #Btype
(
	typeid VARCHAR(500),
	UserCode VARCHAR(500),
	FullName VARCHAR(500),
	JoinFlag INT 
)
INSERT INTO #Btype
SELECT B.typeid,B.UserCode,B.FullName,1 
FROM BType AS B 
INNER JOIN F_GetAllManagerBaseTypeId(@BTypeId,2,@chrOperatorID) AS sb ON(B.typeid = sb.typeid)
WHERE b.typeId LIKE '%'+@BTypeId+'%' AND SonNum = 0 AND B.UserCode LIKE '%'+@BUserCode+'%'
		AND B.FullName LIKE '%'+@BFullName+'%'
		AND (NOT(@MBtypeid='-99999') 
			OR (@MBtypeid='-99999') AND B.typeid IN(SELECT TypeId FROM F_GetManDetailBType(@chrOperatorID)))

--取出最大查询行数
DECLARE @PSQL VARCHAR(MAX),@MAXRowCount NUMERIC(22,0) = 0,@bcount NUMERIC(22,0) = 0,@pcount NUMERIC(22,0) = 0,@acount NUMERIC(22,0) = 0
DECLARE @VMAXCOUNT VARCHAR(20),@VCOUNT VARCHAR(20),@SQL VARCHAR(MAX),@TABLE VARCHAR(200)
SELECT @MAXRowCount = Value FROM Userconfig WHERE ConfigName='reportmaxcount'
SET @VMAXCOUNT = CAST(@MAXRowCount AS VARCHAR)

CREATE TABLE #ROWCOUNT
(
	COUNT INT
)
--选出价格跟踪表
CREATE TABLE #PriceTrack
(
	BtypeId VARCHAR(100),
	BtypeFlag INT,
	PtypeId VARCHAR(100),
	StypeId VARCHAR(100),
	UId INT,
	CId INT,
	Price  NUMERIC(24, 10) ,
	DiscountRate  NUMERIC(24, 10) ,
	DiscountPrice  NUMERIC(24, 10) ,
	baseUnitId INT,
	BuyUnitId INT,
	SaleUnitId INT,
	StockUnitId	INT,
	TrackTime   DATETIME,
	tax			NUMERIC(24, 10) ,
	taxprice	NUMERIC(24, 10) 
)
IF(@QueryType = 0)
	SET @TABLE = 'PriceTrack_SaleOrder'
ELSE IF(@QueryType = 1)
	SET @TABLE = 'PriceTrack_Sale'
ELSE IF(@QueryType = 2)
	SET @TABLE = 'PriceTrack_BuyOrder'
ELSE IF(@QueryType = 3)
	SET @TABLE = 'PriceTrack_Buy'
ELSE IF(@QueryType = 4)
	SET @TABLE = 'PriceTrack_Quote'
ELSE IF(@QueryType = 5)
	SET @TABLE = 'PriceTrack_AskPrice'
ELSE IF(@QueryType = 6)
	SET @TABLE = 'PriceTrack_Send'
ELSE IF(@QueryType = 7)
	SET @TABLE = 'PriceTrack_Appraisal'

SET @SQL = '
INSERT INTO #PriceTrack
SELECT A.BtypeId,A.BtypeFlag,A.PtypeId,A.StypeId,A.UId,A.CId,A.Price,A.DiscountRate,A.DiscountPrice,P.baseUnitId,P.BuyUnitId,P.SaleUnitId,P.StockUnitId,A.TrackTime ,a.tax,a.taxprice   
FROM ' + @TABLE + ' AS A 
INNER JOIN #GetSelPTypeId AS P ON(A.PTypeId = P.typeid) 
INNER JOIN #Btype AS B ON(A.BTypeId = B.TypeId) 
INNER JOIN #GetManSTypeId AS S ON(A.STypeId = S.TypeId) 
INNER JOIN #Ac_Currency AS ac ON(A.cid = ac.cid) 
WHERE BTypeFlag = ' + CAST(@BtypeFlag AS VARCHAR(10)) 

IF(@UID <> 0)
	SET @SQL +=' AND A.uid = P.' + @UIDTYPE
--(NOT(' + CAST(@Flag AS VARCHAR(10)) + ' = 0)
--OR (' + CAST(@Flag AS VARCHAR(10)) + ' = 0) AND ISNULL(A.Price,0) <> 0) 
--AND
--(NOT(' + CAST(@UID AS VARCHAR(10)) + ' <> 0) 
--			OR (' + CAST(@UID AS VARCHAR(10)) + ' <> 0) AND A.uid = P.'+CAST(@UIDTYPE AS VARCHAR(10)) + ' 
--		)

SET @SQL +=' 
INSERT INTO #ROWCOUNT
SELECT @@ROWCOUNT '
--PRINT @SQL
EXEC(@SQL)

--是否操过最大行数
SELECT @VCOUNT = COUNT FROM #ROWCOUNT
IF(@VCOUNT > @MAXRowCount)
BEGIN
	RAISERROR('显示结果集为%s条,大于允许的最大条数%s条,请调整查询条件后重试！',16,1,@VCOUNT,@VMAXCOUNT)
	RETURN
END			
------------------------------------------------显示最终数据--------------------------------------------
--不显示价格跟踪为0
IF(@Flag = 0)
BEGIN
	SELECT  P.TypeId AS PTypeId,
			P.UserCode AS PUserCode,
			B.TypeId AS BTypeId,
			B.UserCode AS BUserCode,
			A.StypeId,
			A.BtypeFlag,
			A.uid,
			A.cid,
			pu.fullname as ufullname,
			ac.cname as cname,
			ISNULL(A.Price,0) AS Price,
			ISNULL(A.DiscountRate,1) AS DiscountRate,
			ISNULL(A.DiscountPrice,0) AS DiscountPrice ,
			A.TrackTime,
			a.tax,
			a.taxprice
			FROM #PriceTrack AS A
			INNER JOIN #GetSelPTypeId AS p ON(A.PTypeId = p.typeid)
			INNER JOIN #Btype AS b ON(A.BTypeId = B.TypeId)
			INNER JOIN PType_Units AS pu ON(pu.UnitsId = CASE @UID 
															 WHEN 1 THEN A.baseunitid 
															 WHEN 2 THEN A.buyunitid 
															 WHEN 3 THEN A.SaleUnitId
															 WHEN 4 THEN A.StockUnitId
															 ELSE A.UId
														  END)
			INNER JOIN  #Ac_Currency AS ac ON(A.cid = ac.cid)
			WHERE ISNULL(A.Price,0) <> 0
				  AND (NOT(@STypeId = '' AND @MStypeid = '00000') AND (A.STypeId IN(SELECT TypeId FROM #GetManSTypeId)) 
						OR (@STypeId = '' AND @MStypeid = '00000')) 
			ORDER BY B.UserCode,P.UserCode
END
ELSE --显示价格跟踪为0
BEGIN	
					
CREATE TABLE #result
    (
      PTypeId NVARCHAR(200) ,
      PUserCode NVARCHAR(200) ,
      BTypeId NVARCHAR(200) ,
      BUserCode NVARCHAR(200) ,
      stypeid NVARCHAR(200) ,
      BtypeFlag INT ,
      uid INT ,
      cid INT ,
      ufullname NVARCHAR(200) ,
      cname NVARCHAR(200) ,
      Price DECIMAL(24, 10) ,
      DiscountRate DECIMAL(24, 10) ,
      DiscountPrice DECIMAL(24, 10) ,
      TrackTime DATETIME ,
      tax DECIMAL(24, 10) ,
      taxprice DECIMAL(24, 10)
    )

										 

---先找出价格跟踪的
	 INSERT INTO #result
           ( PTypeId ,
             PUserCode ,
             BTypeId ,
             BUserCode ,
             stypeid ,
             BtypeFlag ,
             uid ,
             cid ,
             ufullname ,
             cname ,
             Price ,
             DiscountRate ,
             DiscountPrice ,
             TrackTime ,
             tax ,
             taxprice
           )
		SELECT  P.TypeId AS PTypeId,
			P.UserCode AS PUserCode,
			B.TypeId AS BTypeId,
			B.UserCode AS BUserCode,
			A.StypeId,
			A.BtypeFlag,
			A.uid,
			A.cid,
			pu.fullname as ufullname,
			ac.cname as cname,
			ISNULL(A.Price,0) AS Price,
			ISNULL(A.DiscountRate,1) AS DiscountRate,
			ISNULL(A.DiscountPrice,0) AS DiscountPrice ,
			A.TrackTime,
			a.tax,
			a.taxprice
			FROM #PriceTrack AS A
			INNER JOIN #GetSelPTypeId AS p ON(A.PTypeId = p.typeid)
			INNER JOIN #Btype AS b ON(A.BTypeId = B.TypeId)
			INNER JOIN PType_Units AS pu ON(pu.UnitsId = CASE @UID 
															 WHEN 1 THEN A.baseunitid 
															 WHEN 2 THEN A.buyunitid 
															 WHEN 3 THEN A.SaleUnitId
															 WHEN 4 THEN A.StockUnitId
															 ELSE A.UId
														  END)
			INNER JOIN  #Ac_Currency AS ac ON(A.cid = ac.cid)
			WHERE ISNULL(A.Price,0) <> 0
				  AND (NOT(@STypeId = '' AND @MStypeid = '00000') AND (A.STypeId IN(SELECT TypeId FROM #GetManSTypeId)) 
						OR (@STypeId = '' AND @MStypeid = '00000')) 
						
	--找出除了价格跟踪外的等于0的
   INSERT INTO #result
           ( PTypeId ,
             PUserCode ,
             BTypeId ,
             BUserCode ,
             stypeid ,
             BtypeFlag ,
             uid ,
             cid ,
             ufullname ,
             cname ,
             Price ,
             DiscountRate ,
             DiscountPrice ,
             TrackTime ,
             tax ,
             taxprice
           )
	SELECT DISTINCT A.TypeId AS PTypeId,
			A.UserCode AS PUserCode,
			B.TypeId AS BTypeId,
			B.UserCode AS BUserCode,
			s.typeId AS stypeid,
			null AS BtypeFlag ,
			pu.unitsid as uid,
			ac.cid as cid,
			pu.fullname as ufullname,
			ac.cname as cname,
		    0 AS Price,
			1 AS DiscountRate,
			0 AS DiscountPrice,
			null AS TrackTime ,
			0 AS tax,
			0 AS taxprice
	FROM #GetSelPTypeId AS A 
	INNER JOIN #Btype AS B ON(A.JoinFlag = B.JoinFlag)
	INNER JOIN #GetManSTypeId AS s ON(A.JoinFlag = s.JoinFlag)
	INNER JOIN PType_Units_ext PUe ON PUe.ptypeid = A.typeid
	INNER JOIN PType_Units PU ON pu.unitsid = pue.unitsid
	INNER JOIN #Ac_Currency ac ON A.JoinFlag = AC.JoinFlag AND ac.JoinFlag = B.JoinFlag
	WHERE pue.RateType = 0 
		  AND (NOT(@UID <> 0)
				OR (@UID <> 0) AND PUe.UnitsId = CASE @UID 
													WHEN 1 THEN baseunitid 
													WHEN 2 THEN buyunitid 
													WHEN 3 THEN SaleUnitId
													WHEN 4 THEN StockUnitId
												 END) 	
			AND not EXISTS(SELECT 1 from #result  r where s.typeid=r.stypeid AND a.typeid=r.ptypeid  AND b.typeid=r.btypeid 
			AND pu.unitsid=r.uid AND ac.cid=r.cid
			 )									 					
												 
 SELECT * FROM #result 
 
 DROP TABLE #result
END

------------------------------------------------------------------------------------------------------------
DROP TABLE #GetManSTypeId,#GetSelPTypeId,#Ac_Currency,#Btype,#ROWCOUNT,#PriceTrack

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


/*
	作者：杨俊
	日期：2014-10-20
	描述：价格跟踪-批量删除
*/
CREATE	PROCEDURE Gp_PriceTrackBatchDel
(
	@chrOperatorID 		VARCHAR(100),    	--操作员ID号
	@BTypeId			VARCHAR(max),    	--往来单位的ID
	@PTypeId			VARCHAR(max),    	--商品的ID
	@STypeId			VARCHAR(max),		--分支机构
	@QueryType			INT,				--查询类型  0.销售订单价格跟踪 1.销售价格跟踪   2.采购订单价格跟踪 3.采购价格跟踪 4.报价单价格跟踪 5.询价单价格跟踪 6.发出商品出库单 7.暂估入库单
	@PUserCode			VARCHAR(600)='',	--商品编号
	@PFullName			VARCHAR(600)='',	--商品名称
	@BUserCode			VARCHAR(600)='',	--客户编号
	@BFullName			VARCHAR(600)='',	--客户名称
	@Flag				INT,				--是否显示价格跟踪为0的商品
	@cid				INT,				--0代表所有币种
	@uid				INT					--0表示所有单位
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chrOperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chrOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF(@QueryType NOT IN(0,1,2,3,4,5,6,7)) RETURN 0

--临时表
CREATE TABLE #PirceTrack
(
	PTypeId	VARCHAR(max),
	PUserCode VARCHAR(max),
	BTypeId VARCHAR(max),
	BUserCode VARCHAR(max),
	STypeId	VARCHAR(max),
	BtypeFlag INT,
	uid INT,
	cid INT,
	ufullname VARCHAR(max),
	cname VARCHAR(max),
	Price  NUMERIC(24, 10) ,
	DiscountRate  NUMERIC(24, 10) ,
	DiscountPrice  NUMERIC(24, 10), 
	tracktime		DATETIME,
	tax			NUMERIC(24, 10) ,
	taxprice	NUMERIC(24, 10) 
	
)
INSERT INTO #PirceTrack(PTypeId,PUserCode,BTypeId,BUserCode,STypeId,BtypeFlag,uid,cid,ufullname,cname,Price,DiscountRate,DiscountPrice,tracktime,tax,taxprice)
EXEC Gp_PriceTrack @chrOperatorID,@BTypeId,@PTypeId,@STypeId,@QueryType,@PUserCode,@PFullName,@BUserCode,@BFullName,@Flag,@cid,@uid
,@standard='',@type='',@name='',@pycode='',@entrycode='',@pcategoryid='',@area=''	


--获取表名
DECLARE @TABLE VARCHAR(200)
IF(@QueryType = 0)
	SET @TABLE = 'PriceTrack_SaleOrder'
ELSE IF(@QueryType = 1)
	SET @TABLE = 'PriceTrack_Sale'
ELSE IF(@QueryType = 2)
	SET @TABLE = 'PriceTrack_BuyOrder'
ELSE IF(@QueryType = 3)
	SET @TABLE = 'PriceTrack_Buy'
ELSE IF(@QueryType = 4)
	SET @TABLE = 'PriceTrack_Quote'
ELSE IF(@QueryType = 5)
	SET @TABLE = 'PriceTrack_AskPrice'
ELSE IF(@QueryType = 6)
	SET @TABLE = 'PriceTrack_Send'
ELSE IF(@QueryType = 7)
	SET @TABLE = 'PriceTrack_Appraisal'
	
--获取BtypeFlag
DECLARE @BtypeFlag INT
IF(@QueryType = 0 OR @QueryType = 1 OR @QueryType = 4 OR @QueryType = 6)
	SELECT @BtypeFlag = Value FROM PriceTrackConfig WHERE Name = 'SaleBtypeFlag'
ELSE IF(@QueryType = 2 OR @QueryType = 3 OR @QueryType = 5 OR @QueryType = 7)
	SELECT @BtypeFlag = Value FROM PriceTrackConfig WHERE Name = 'BuyBtypeFlag'

--执行删除
DECLARE @SQL VARCHAR(500)
SET @SQL = 'DELETE FROM ' + @TABLE + 
		  ' FROM ' + @TABLE + ' AS A ' +
		  ' INNER JOIN #PirceTrack AS B ' + 
		  'ON(A.BtypeId = B.BTypeId AND A.BtypeFlag = B.BtypeFlag 
				AND A.PtypeId = B.PTypeId AND A.StypeId = B.STypeId 
				AND A.UId = B.uid AND A.CId = B.cid)'

EXEC(@SQL)
RETURN 1
------------------------------------------------------------------------------------------------------------
DROP TABLE #PirceTrack

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

/*
	作者：杨俊
	日期：2015-04-29
	描述：价格跟踪复制
	EXEC Gp_PriceTrackCopy '0000100001','0000100007','1','0','00001','00001','00001'
*/
CREATE PROCEDURE Gp_PriceTrackCopy
(
	@YBTypeId			VARCHAR(max),    	--源单位ID
	@MBBTypeId			VARCHAR(max),    	--目标单位ID
	@QueryType			INT,				--查询类型  0.销售订单价格跟踪 1.销售价格跟踪   2.采购订单价格跟踪 3.采购价格跟踪 4.报价单价格跟踪 5.询价单价格跟踪 6.发出商品出库单 7.暂估入库单
	@IsCoverBtype		INT,				--是否覆盖目标单位中现有的价格跟踪信息
	@chrOperatorID 		VARCHAR(500),    	--操作员ID号
	@YSTypeId			VARCHAR(max),    	--源分支机构ID
	@MBSTypeId			VARCHAR(max)	   	--目标分支机构ID
)
--@encode$--
AS

--------------------------------------------------------------权限检查-------------------------------------------------------
if @chrOperatorID is null return 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chrOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
  
    
DECLARE @TABLE VARCHAR(200),@SQL VARCHAR(MAX)
IF(@QueryType = 0)
	SET @TABLE = 'PriceTrack_SaleOrder'
ELSE IF(@QueryType = 1)
	SET @TABLE = 'PriceTrack_Sale'
ELSE IF(@QueryType = 2)
	SET @TABLE = 'PriceTrack_BuyOrder'
ELSE IF(@QueryType = 3)
	SET @TABLE = 'PriceTrack_Buy'
ELSE IF(@QueryType = 4)
	SET @TABLE = 'PriceTrack_Quote'
ELSE IF(@QueryType = 5)
	SET @TABLE = 'PriceTrack_AskPrice'
ELSE IF(@QueryType = 6)
	SET @TABLE = 'PriceTrack_Send'
ELSE IF(@QueryType = 7)
	SET @TABLE = 'PriceTrack_Appraisal'

DECLARE @nowtime NVARCHAR(100)
SET @nowtime= CONVERT(varchar(100), GETDATE(), 20) 


IF(@IsCoverBtype = 1)
BEGIN
	IF @MPtypeid = '99999'
	BEGIN
		CREATE TABLE #temp1
		(
			btypeid		VARCHAR(50),
			ptypeid		VARCHAR(50),
			stypeid		VARCHAR(50)
		)
		
		SET @SQL = 'INSERT INTO #temp1(btypeid,ptypeid,stypeid)
					SELECT	DISTINCT
							p.btypeid,	
							'+CASE WHEN @MPtypeid = '99999' THEN ' p.ptypeid, ' ELSE '' END + '	
							p.stypeid
					FROM	' + @TABLE + ' p
					INNER JOIN (SELECT A FROM DBO.F_Split('''+@MBBTypeId+''','','') WHERE  ISNULL(A,'''') <> '''') FB ON FB.A = P.BtypeId
					'+CASE WHEN @MPtypeid = '99999' THEN ' INNER JOIN F_GetManDetailPType(''' + @chrOperatorID + ''') AS b ON (p.PtypeId = b.TypeId) ' ELSE '' END + ''		
		
		--PRINT  @SQL					
		EXEC(@SQL)
		
		CREATE NONCLUSTERED INDEX NCIX_Temp1_UIndex ON #temp1(btypeid,ptypeid,stypeid)
		
		SET @SQL = 'DELETE  
					FROM	' + @TABLE + '
					WHERE	EXISTS (
									SELECT	1						
									FROM	#temp1 b
									INNER JOIN (SELECT A FROM DBO.F_Split('''+@MBSTypeId+''','','') WHERE ISNULL(A,'''') <> '''') FS ON FS.A =b.stypeid
									WHERE   b.BtypeId = ' + @TABLE + '.BtypeId	
											AND b.PtypeId = ' + @TABLE + '.PtypeId	
											AND b.StypeId = ' + @TABLE + '.StypeId	
					) '
					
		EXEC(@SQL)		
	END
	ELSE
	BEGIN
		CREATE TABLE #temp2
		(
			btypeid		VARCHAR(50),
			stypeid		VARCHAR(50)
		)
		
		SET @SQL = 'INSERT INTO #temp2(btypeid,stypeid)
					SELECT	DISTINCT
							p.btypeid,	
							'+CASE WHEN @MPtypeid = '99999' THEN ' p.ptypeid, ' ELSE '' END + '	
							p.stypeid
					FROM	' + @TABLE + ' p
					INNER JOIN (SELECT A FROM DBO.F_Split('''+@MBBTypeId+''','','') WHERE  ISNULL(A,'''') <> '''') FB ON FB.A = P.BtypeId
					'+CASE WHEN @MPtypeid = '99999' THEN ' INNER JOIN F_GetManDetailPType(''' + @chrOperatorID + ''') AS b ON (p.PtypeId = b.TypeId) ' ELSE '' END + ''		
		
		--PRINT  @SQL					
		EXEC(@SQL)
		
		--源往来单位和分支机构相同的数据不能被删除
		DELETE FROM #temp2 WHERE btypeid = @YBTypeId AND stypeid = @YSTypeId
		
		CREATE NONCLUSTERED INDEX NCIX_Temp2_UIndex ON #temp2(btypeid,stypeid)
	
		SET @SQL = 'DELETE  
					FROM	' + @TABLE + '
					WHERE	EXISTS (
									SELECT	1						
									FROM	#temp2 b
									INNER JOIN (SELECT A FROM DBO.F_Split('''+@MBSTypeId+''','','') WHERE ISNULL(A,'''') <> '''') FS ON FS.A =b.stypeid
									WHERE    b.BtypeId = ' + @TABLE + '.BtypeId	
												AND b.StypeId = ' + @TABLE + '.StypeId	
					) '
					
		EXEC(@SQL)	
	END	
	
	IF @MPtypeid = '99999'
	BEGIN
		DROP TABLE #temp1
	END
	ELSE
	BEGIN
		DROP TABLE #temp2
	END	
END

DECLARE @i			int,
		@ncount		int,
		@Btypeid	varchar(50),
		@stypeid	varchar(50)	

CREATE TABLE #tempPriceTrackCopy
(
	nid			int IDENTITY(1,1),
	btypeid		varchar(50),
	stypeid		varchar(50)
)

INSERT INTO #tempPriceTrackCopy(btypeid,stypeid) 
SELECT	a.a AS btypeid,
		b.a AS stypeid 
FROM	F_Split(@MBBTypeId,',') a 
INNER JOIN  F_Split(@MBsTypeId,',')b ON 1=1

SET @ncount = @@rowcount

SET @i = 1

CREATE NONCLUSTERED INDEX NCIX_TempPriceTrackCopy_nid ON #tempPriceTrackCopy(btypeid,stypeid)

WHILE @i <= @ncount
BEGIN
	SELECT @btypeid = btypeid,@stypeid = stypeid FROM #tempPriceTrackCopy WHERE nid = @i --AND btypeid <> @YBTypeId AND stypeid <> @YSTypeId
	
	IF @btypeid <> @YBTypeId OR @stypeid <> @YSTypeId
	BEGIN
		SET @SQL = 'INSERT INTO ' + @TABLE + '(BtypeId,BtypeFlag,PtypeId,UId,CId,Price,DiscountRate,DiscountPrice,stypeid,tax,taxprice,TrackTime)
					SELECT ''' + @Btypeid + ''',BtypeFlag,PtypeId,UId,CId,Price,DiscountRate,DiscountPrice,''' + @stypeid + ''', tax,taxprice,''' + @nowtime + '''
					FROM ' + @TABLE + ' AS a '+CASE WHEN @MPtypeid = '99999' THEN ' INNER JOIN F_GetManDetailPType(''' + @chrOperatorID + ''') AS b ON(a.PtypeId = b.TypeId) ' ELSE '' END + '
					WHERE   a.btypeid = ''' + @YBTypeId + ''' 
							and   a.stypeid = ''' + @YsTypeId + ''' 
					'
		IF(@IsCoverBtype = 0)
			SET @SQL += '	AND NOT EXISTS(SELECT 1 FROM ' + @TABLE + ' WHERE BtypeId = ''' + @Btypeid + ''' 
							and stypeId = ''' + @stypeid + '''
							AND BtypeFlag = a.BtypeFlag AND PtypeId = a.PtypeId 
							AND UId = a.UId AND CId = a.CId)
						'
		--PRINT(@SQL)
		EXEC(@SQL)	
	END
		
	SET @i = @i + 1
END

TRUNCATE TABLE #tempPriceTrackCopy

RETURN 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-23
	描述：请购生单自动比价
*/

CREATE PROCEDURE Gp_ProduceBuyOrderBill 
(
	@billidlists			VARCHAR(100),	--单据ID集合
	@operatorid				VARCHAR(100),	--操作员id
	@reachdate				datetime,		--订货时间
	@ktypeid				varchar(max),	--仓库编号
	@btypeid				VARCHAR(max),	--供货商编号
	@stypeid				VARCHAR(max),	--分支机构编号
	@etypeid				VARCHAR(max),	--采购人员编号
	@dtypeid				VARCHAR(max),	--部门编号
	@ReturnBillCode varchar(max)='' OUTPUT	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @totalmoney  NUMERIC(24, 10) ,@totalqty  NUMERIC(24, 10) 
SELECT	@totalmoney=SUM(dbo.F_RoundTotal(CAST( CAST(Compareprice*Qty AS NUMERIC(22,10) )*(1+CompareTax/100) AS NUMERIC(22,10))) ),@totalqty= SUM(qty) 
FROM dbo.RequestBill 
WHERE ID IN ( SELECT * FROM DBO.f_split(@billidlists,','))
GROUP BY Btypeid2

DECLARE	@BillCodeConfig varchar(1),@billnumberid VARCHAR(max),
		@BillNum int,@BillCode varchar(300),@NowDate DATETIME,
		@Day varchar(100),@Month varchar(100),@Year varchar(100),@CargoSpace varchar(200),@cid INT,@rate numeric(24,10),
		@DFullName VARCHAR(500),
		@cefullname	VARCHAR(500)=''
		
SELECT @cid= CId,@rate=rate FROM dbo.Ac_Currency WHERE Sysrow = 1
SELECT @DFullName= FullName FROM dbo.Department WHERE typeid=@dtypeid
SELECT @ReturnBillCode = ''		
SELECT @NowDate=GETDATE()
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置

BEGIN TRANSACTION  DEL

IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =301 ) AND @BillCodeConfig='1' --单据编号自定义
	BEGIN
		SELECT @MONTH = TypeId FROM Employee WHERE TypeID = @ETypeId
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @operatorid
	END
ELSE
	BEGIN
		SELECT @Month=Month(GETDATE())
		SELECT @Day=DAY(GETDATE())
	END
	
EXEC Gp_GetBillCode 301,@Month,@Day,'JD',@NowDate,@stypeid,@BillCode OUTPUT,@DFullName,@cefullname
SELECT @ReturnBillCode = @BillCode

INSERT INTO [dbo].[OrderIndex] 
(
		[btypeid],
		[DealBTypeID],
		[etypeid],
		[ktypeid],
		[BillDate],
		[Billcode],
		[billtype],
		[totalmoney],
		[totalqty],
		[period],
		[checked],
		[redWord],
		[comment],
		[explain],
		[reachDate],
		[Checke],
		[Tax],
		[BillStatus],
		[DtypeId],
		[STypeID],
		[ifaudit],
		CustomerTotal,
		WayBillCode,
		Tel,
		GoodsNumber,
		PackWay,
		CID,
		Rate
) 
VALUES
(		@btypeid,
		@btypeid,
		@etypeid,
		@ktypeid,
		CONVERT(CHAR(10),GETDATE(),120),
		@BillCode,
		'301',
		@totalmoney,
		@totalqty,
		1,
		0,
		0,
		'',
		'该采购订单由请购单生成',
		@reachdate,
		@operatorid,
		0,
		0,
		@dtypeid,
		@stypeid,
		CASE
		     WHEN EXISTS(SELECT TOP 1 1 FROM dbo.AuditingFlowSet AFS INNER JOIN Stock K ON AFS.Stypeid = K.STypeID AND AFS.BillType = 301 AND AFS.ifuse = 1 AND K.typeId = @ktypeid) THEN 0
		     ELSE 1
		END,
		0,
		'',
		'',
		'',
		'',
		@cid,
		@rate
)


				
SET @billnumberid=SCOPE_IDENTITY();
IF NOT EXISTS(SELECT ConfigNo FROM Userconfig WHERE ConfigName='BillcodeCreateTime' AND Value=2)
	EXEC GP_SaveBillCode_Seed	@billnumberid,@NowDate,301,@BillCode
		
DECLARE @cargoid VARCHAR(1550)
SELECT @cargoid=CargoID FROM CargoType WHERE IsDefault=1 AND KtypeID=@KTYPEID
					
INSERT INTO OrderBill (
		BillNumberID,
		PTypeID,
		Qty,
		Price,
		SaleTotal,
		ReachQty,
		Discount,
		DiscountPrice,
		Total,
		Tax,
		TaxPrice,
		TaxTotal,
		KTypeID,
		STypeID,
		Comment,
		IsUnit2,
		RequestBillNumberID,
		RequestBillID,
		IsCombined,
		ItemID,
		UnitID,
		MUnitID,
		MUnitRate,
		NUnitID,
		MQty,
		NQty,
		TaxMoney,
		NSalePrice,
		NSaleTotal,
		NDiscountPrice,
		NTotal,
		NTaxPrice,
		NTaxTotal,
		NTaxMoney,
		UnitRate,
		NUnitMsg,
		MSalePrice,
		MDiscountPrice,
		MTaxPrice,
		CurMSalePrice,
		CurMDiscountPrice,
		CurMTaxPrice,
		CargoID,
		ShowOrder,
		isrequest
) 
SELECT	@billnumberid,
		M.PTypeId,
		M.Qty,
		dbo.F_RoundPrice(CAST(CAST(M.Qty*M.Compareprice AS NUMERIC(22,10))/M.CompareDiscount AS NUMERIC(22,10))/M.Qty),--price
		dbo.F_RoundTotal(CAST(M.Qty*M.Compareprice AS NUMERIC(22,10) )/M.CompareDiscount),--saletotal
		0,
		M.CompareDiscount,
		M.Compareprice,
		dbo.F_RoundTotal(CAST(M.Compareprice*M.Qty AS NUMERIC(22,10) )),--total
		M.comparetax,
		dbo.F_RoundPrice(dbo.F_RoundTotal( CAST(CAST(M.Compareprice*M.Qty AS NUMERIC(22,10) )*(1+M.CompareTax/100) AS NUMERIC(22,10) ) )/M.Qty),--taxprice
		dbo.F_RoundTotal(CAST(M.Compareprice*M.Qty AS NUMERIC(22,10) )*(1+M.CompareTax/100)),--taxtotal
		@ktypeid,
		M.stypeid,
		'',
		0,
		M.billnumberid,
		M.id,
		m.IsCombined,
		m.ItemID,
		m.UnitID,
		m.UnitID,
		1,--按照基本单位生成是，基本单位换算率为1，所以大单位衡为1.
		m.nUnitID,
		m.Qty,
		m.NQty,
		dbo.F_RoundTotal(CAST(m.qty*m.ComparePrice*m.CompareTax AS NUMERIC(22,10) )/100) AS TaxMoney,--本币税额
		dbo.F_RoundPrice(CAST(CAST(M.Qty*M.Compareprice AS NUMERIC(22,10) )/M.CompareDiscount AS NUMERIC(22,10) )/M.Qty),--nsaleprice原币单价
		dbo.F_RoundTotal(CAST(M.Qty*M.Compareprice AS NUMERIC(22,10) )/M.CompareDiscount),--nsaletotal原币金额
		dbo.F_RoundPrice(M.Compareprice),--NDiscountPrice原币折后单价
		dbo.F_RoundTotal(CAST(M.Compareprice*M.Qty AS NUMERIC(22,10) ) ),--Ntotal原币折后金额
		dbo.F_RoundPrice(dbo.F_RoundTotal(CAST(CAST(M.Compareprice*M.Qty AS NUMERIC(22,10) )*(1+M.CompareTax/100) AS NUMERIC(22,10) ) )/M.Qty),--NtaxPrice原币含税单价
		dbo.F_RoundTotal(CAST(M.Compareprice*M.Qty AS NUMERIC(22,10) )*(1+M.CompareTax/100)),--NtaxTotal原币价税合计
		(CAST(CAST(m.qty*m.ComparePrice AS NUMERIC(22,10) )*m.CompareTax AS NUMERIC(22,10) )/100) AS NTaxMoney,--NTaxmoney原币税额
		m.UnitRate,
		m.NUnitMsg,
		dbo.F_RoundPrice(CAST(CAST(M.Qty*M.Compareprice AS NUMERIC(22,10) )/M.CompareDiscount AS NUMERIC(22,10) )/M.Qty),--MSalePrice大单位单价
		dbo.F_RoundPrice(M.Compareprice),--MDiscountPrice大单位折后单价
		dbo.F_RoundPrice(dbo.F_RoundTotal(CAST(CAST(M.Compareprice*M.Qty AS NUMERIC(22,10) )*(1+M.CompareTax/100) AS NUMERIC(22,10) ) )/M.Qty),--MTaxPrice大单位含税单价
		dbo.F_RoundPrice(CAST(CAST(M.Qty*M.Compareprice AS NUMERIC(22,10) )/M.CompareDiscount AS NUMERIC(22,10) )/M.Qty),--CurMSalePrice大单位原币单价
		dbo.F_RoundPrice(M.Compareprice),--curmdiscountprice大单位原币折后单价
		dbo.F_RoundPrice(CAST(M.Compareprice*M.Qty*(1+M.CompareTax/100) AS  NUMERIC(24, 10) )/M.Qty),--curmtaxprice含税单价
		@cargoid, --货位
		M.ShowOrder,
		1 as isrequest
FROM    requestbill M,
		ptype p
WHERE   p.typeid=m.ptypeid
		AND m.id IN( SELECT * FROM DBO.f_split(@billidlists,','))
-- 更新生成单据的请购数量
UPDATE  requestbill SET	state=8,RequestQty=o.qty
FROM dbo.RequestBill r,dbo.OrderBill o
WHERE r.ID=o.RequestBillID AND	r.id IN( SELECT * FROM DBO.f_split(@billidlists,','))

--影响订单库存
EXEC GP_Deal_OrderQTY @billnumberid,301,'+'
			
IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('生成订单失败！',16,1)
END

COMMIT TRANSACTION  DEL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_ProductInfoSync]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_ProductInfoSync];
GO

/*
	作者:颜熙
	日期:2017-02-10
	描述:同步网店信息
*/
CREATE  PROCEDURE Gp_ProductInfoSync 
( 
	@ptypeid VARCHAR(MAX), --typeid
	@flag INT, --标志
	@id VARCHAR(MAX) --自由项id
)
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
    IF @flag =1 --商品信息
        SELECT DISTINCT
                p.IsService ,
                p.baseUnitId AS skucode ,
                pu.FullName AS stockunit ,
                p.typeId ,
                p.FullName AS goodsname ,
                p.UserCode AS goodscode ,
                p.Pid AS erpid ,
                p.weight AS weight ,
                p.volume AS size ,
                p.Comment AS remark ,
                PR.PreSalePrice1 AS price1 ,
                PR.PreSalePrice2 AS price2 ,
                PR.PreSalePrice3 AS price3 ,
                PR.PreSalePrice4 AS price4 ,
                PR.PreSalePrice5 AS price5 ,
                p.EntryCode AS barcode ,
                deleted
        FROM    ptype p
                INNER JOIN dbo.f_split(@ptypeid, ',') f ON p.typeId = f.a
                INNER JOIN PType_Units pu ON pu.UnitsId = p.baseUnitId
                INNER JOIN dbo.PType_Price PR ON p.typeId = PR.PTypeID
        WHERE   iscombinationproduct = 0
                AND PR.IsDefaultUnit = 1
                AND p.sonnum = 0
        UNION ALL
        SELECT DISTINCT
                p.IsService ,
                p.baseUnitId AS skucode ,
                pu.FullName AS stockunit ,
                p.typeId ,
                p.FullName AS goodsname ,
                p.UserCode AS goodscode ,
                p.Pid AS erpid ,
                p.weight AS weight ,
                p.volume AS size ,
                p.Comment AS remark ,
                PR.PreSalePrice1 AS price1 ,
                PR.PreSalePrice2 AS price2 ,
                PR.PreSalePrice3 AS price3 ,
                PR.PreSalePrice4 AS price4 ,
                PR.PreSalePrice5 AS price5 ,
                p.EntryCode AS barcode ,
                1 AS deleted
        FROM    ptype p
                INNER JOIN PType_Units pu ON pu.UnitsId = p.baseUnitId
                INNER JOIN dbo.PType_Price PR ON p.typeId = PR.PTypeID
        WHERE   p.sonnum <> 0 AND p.typeId IN (SELECT typeId FROM ptype WHERE  p.ParId IN (SELECT * FROM dbo.f_split(@ptypeid, ','))) AND p.WdSyncFlag = 1;
	ELSE IF @flag =2 --自由项信息
        SELECT  CAST(p.Pid AS VARCHAR) + '_1_' + CAST(id AS VARCHAR) + '_'
                + CAST(p.baseUnitId AS VARCHAR) AS erpid ,
                CAST(id AS VARCHAR) + '_' + CAST(p.baseUnitId AS VARCHAR) AS skucode ,
                c.Fullname + '_' + pu.FullName AS skuname ,
                p.typeId ,
                c.Fullname ,
                c.id AS itemid ,
                1 AS isCombined
        FROM    CustomReferenceValue AS c
                INNER JOIN ptype AS p ON p.customitemid = c.itemsid
                INNER JOIN PType_Units pu ON pu.UnitsId = p.baseUnitId
        WHERE   p.customitemfrom = 1
                AND p.typeId = @ptypeid
        UNION ALL
        SELECT  CAST(p.Pid AS VARCHAR) + '_0_' + CAST(_Id AS VARCHAR) + '_'
                + CAST(p.baseUnitId AS VARCHAR) AS erpid ,
                CAST(_Id AS VARCHAR) + '_' + CAST(p.baseUnitId AS VARCHAR) AS skucode ,
                x.FullName + '_' + pu.FullName AS skuname ,
                p.typeId ,
                x.FullName ,
                x._Id AS itemid ,
                0 AS isCombined
        FROM    xw_SelfData x
                INNER JOIN ptype AS p ON p.customitemid = x.DataTypeId
                INNER JOIN PType_Units pu ON pu.UnitsId = p.baseUnitId
        WHERE   p.customitemfrom = 0
                AND p.typeId = @ptypeid
                AND x.TypeId <> '00000';
	ELSE IF @flag = 3 --自由项信息（不包含自由项id）
        SELECT  CAST(p.Pid AS VARCHAR) + '_1_' + CAST(id AS VARCHAR) + '_'
                + CAST(p.baseUnitId AS VARCHAR) AS erpid ,
                CAST(id AS VARCHAR) + '_' + CAST(p.baseUnitId AS VARCHAR) AS skucode ,
                c.Fullname + '_' + pu.FullName AS skuname ,
                p.typeId ,
                c.Fullname
        FROM    CustomReferenceValue AS c
                INNER JOIN ptype AS p ON p.customitemid = c.itemsid
                INNER JOIN PType_Units pu ON pu.UnitsId = p.baseUnitId
        WHERE   p.customitemfrom = 1
                AND p.typeId = @ptypeid
                AND c.id <> @id
        UNION ALL
        SELECT  CAST(p.Pid AS VARCHAR) + '_0_' + CAST(_Id AS VARCHAR) + '_'
                + CAST(p.baseUnitId AS VARCHAR) AS erpid ,
                CAST(_Id AS VARCHAR) + '_' + CAST(p.baseUnitId AS VARCHAR) AS skucode ,
                x.FullName + '_' + pu.FullName AS skuname ,
                p.typeId ,
                x.FullName
        FROM    xw_SelfData x
                INNER JOIN ptype AS p ON p.customitemid = x.DataTypeId
                INNER JOIN PType_Units pu ON pu.UnitsId = p.baseUnitId
        WHERE   p.customitemfrom = 0
                AND p.typeId = @ptypeid
                AND x.TypeId <> '00000'
                AND x._Id <> @id;
	ELSE IF @flag = 4 --操作员信息
        SELECT  e.deleted ,
                e.UserCode AS operatorcode ,
                e.FullName AS operatorname ,
                e.Tel AS mobile ,
                e.Comment AS remark ,
                e.Eid AS erpid ,
                d.typeid AS dept_erpid ,
                lu.password
        FROM    employee AS e
                INNER JOIN loginuser AS lu ON e.typeId = lu.etypeid
                INNER JOIN Department AS d ON e.Department = d.FullName
                INNER JOIN dbo.f_split(@ptypeid, ',') f ON e.typeId = f.a
        WHERE   e.sonnum = 0
                AND e.deleted = 0
                AND e.leveal > 1;
	ELSE IF @flag =5 --删除职员信息
        SELECT  e.UserCode AS clerkcode ,
                Eid AS erpid
        FROM    employee AS e
                JOIN dbo.f_split(@ptypeid, ',') f ON e.typeId = f.a
       -- WHERE   e.sonnum = 0;
	ELSE IF @flag = 6 --同步职员信息
        SELECT  e.deleted ,
                e.UserCode AS clerkcode ,
                e.FullName AS clerkname ,
                e.Mob AS mobile ,
                e.Tel AS tel ,
                QQ ,
                Mail AS email ,
                e.Comment AS remark ,
                Eid AS erpid ,
                d.typeid AS dept_erpid
        FROM    employee AS e
                JOIN dbo.f_split(@ptypeid, ',') f ON e.typeId = f.a
                INNER JOIN Department AS d ON e.DtypeID = d.typeid
        WHERE   e.sonnum = 0;
	ELSE IF @flag = 7 --同步部门信息
        SELECT  d.deleted ,
                d.usercode AS deptcode ,
                d.FullName AS deptname ,
                d.Comment AS remark ,
                d.typeid AS erpid
        FROM    Department d
                INNER JOIN f_split(@ptypeid, ',') f ON d.typeid = f.a
        WHERE   d.sonnum = 0;
    ELSE IF @flag = 8 --同步账户信息
        SELECT  ac.UserCode AS accountcode ,
                ac.nId AS erpid
        FROM    Ac_Items ac
                JOIN dbo.f_split(@ptypeid, ',') f ON ac.nTypeId = f.a
        --WHERE   ac.SonNum = 0;
	ELSE IF @flag = 9 --删除仓库信息
        SELECT  FullName AS whsname ,
                UserCode AS whscode ,
                LinkMan AS linkman ,
                Tel AS tel ,
                Kid AS erpid
        FROM    Stock s
                JOIN dbo.f_split(@ptypeid, ',') f ON s.typeId = f.a
       -- WHERE   sonnum = 0;
	ELSE IF @flag = 10
	BEGIN
		SELECT  WdShopName ,
                WdShopType ,
                ISNULL(Btype, '') AS dealbtypeid ,
                ISNULL(b.FullName, '') AS dealbname ,
                ISNULL(s.FullName, '') AS sfullname ,
                ISNULL(w.PtypeId, '') AS typeid ,
                ISNULL(p.FullName, '') AS pfullname ,
                ac.FullName AS payitemfullname ,
                w.PayitemId AS payitem,
                StypeId ,
                PayitemFullname,
                w.pricetype
        FROM    WdShopConfig w
                LEFT JOIN SType s ON w.StypeId = s.TypeId
                LEFT JOIN ptype AS p ON w.PtypeId = p.UserCode
                LEFT JOIN btype AS b ON w.Btype = b.typeId
                LEFT JOIN dbo.Ac_Items ac ON w.PayitemId =ac.nId
        WHERE   Flag = 1;
        UPDATE  WdShopConfig
        SET     Flag = 0;
	END 
	ELSE IF @flag = 11 --按商品查商品仓库货位
	BEGIN
		IF @ptypeid=''
		BEGIN 
			SELECT PTypeID,KTypeID,CargoID FROM dbo.GOODSSTOCKS_QTY
		END 
		ELSE 
		BEGIN
            SELECT DISTINCT
                    p.Pid AS goodserpid ,
                    s.Kid AS whserpid ,
                    CargoID AS whspterpid ,
                    g.PTypeID ,
                    g.KTypeID ,
                    g.CargoID
            FROM    dbo.GOODSSTOCKS_QTY g
                    INNER JOIN ptype p ON p.typeId = g.PTypeID
                    INNER JOIN Stock s ON s.typeId = g.KTypeID
            WHERE   PTypeID IN ( SELECT *
                                 FROM   dbo.f_split(@ptypeid, ',') )
                    AND p.WdSyncFlag = 1
                    AND s.WdSyncFlag = 1;
		END 
	END
	ELSE IF @flag = 12 --查询出库的序列号信息,ptypeid是billnumberid
		BEGIN
            --当gp_inoutPtypeSerial表中字段state = 1并且关联billindxe表字段redword=1时既入库红冲，是序列号出库
            --当gp_inoutPtypeSerial表中字段state = 2并且关联billindxe表字段redword=0时既出库未红冲，是序列号出库
			--	CREATE TABLE #SerialInfo
			--	(
			--	  goodserpid INT,
			--	  PtypeID VARCHAR(50),
			--	  Serial VARCHAR(50),
			--	  whserpid INT,
			--	  whspterpid INT,
			--	  ItemID INT,
			--	  IsCombined INT 
			--	); 
			--	CREATE TABLE #Ptypeid
			--	(
			--		id INT IDENTITY(1,1),
			--		ptypeid VARCHAR(50)
			--	)
			--	CREATE TABLE #serial
			--	(
			--		id INT IDENTITY(1,1),
			--		serial VARCHAR(MAX)
			--	)
			--	CREATE TABLE #serialDetail
			--	(
			--		id INT IDENTITY(1,1),
			--		serial VARCHAR(MAX)
			--	)
			--	DECLARE @billnmuberid INT ,@sql VARCHAR(1000)
			--	DECLARE billnumberid_cursor cursor
			--	FOR SELECT	a AS billnumberid
			--		FROM	dbo.f_split(@ptypeid, ',') 					
			--	FOR READ only
			--	OPEN billnumberid_cursor
			--	FETCH NEXT FROM billnumberid_cursor INTO  @billnmuberid
			--	WHILE @@fetch_status=0
			--		BEGIN
			--			INSERT INTO #Ptypeid EXEC Gp_QueryPtypeID @billIDs=@billnmuberid
			--			DECLARE @n INT ,@i INT =1,@tablename VARCHAR(100)='' 
			--			SELECT @tablename = n.detailTable FROM dbo.BillIndex b INNER JOIN dbo.BillName n ON b.Billtype = n.BillType WHERE b.BillNumberId = @billnmuberid
			--			IF @tablename<>''
			--			BEGIN 
			--				SELECT @n = COUNT(*) FROM #Ptypeid
			--				WHILE(@i<=@n)
			--				BEGIN  
			--					DECLARE @typeid VARCHAR(50)
			--					SELECT @typeid = ptypeid FROM #Ptypeid WHERE id=@i
			--					IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(@tablename,N'U') AND Name='Serial')
			--					BEGIN 
			--						SET @sql = 'INSERT INTO #serial SELECT Serial FROM '+ @tablename+' WHERE billnumberid ='+CAST(@billnmuberid AS VARCHAR)+' and Ptypeid ='''+ @typeid+''''  
			--						EXEC(@sql)
			--						SELECT * FROM #serial
			--					END
			--					ELSE
			--						CONTINUE
			--					DECLARE @m INT,@k INT = 1
			--					SELECT @m = COUNT(*) FROM #serial
			--					WHILE(@k<=@m)
			--					BEGIN 
			--						DECLARE @serial VARCHAR(50)
			--						SELECT @serial=serial FROM #serial WHERE id=@k
			--						SELECT @serial
			--						IF NOT EXISTS(SELECT 1 FROM dbo.gp_CruPtypeSerial WHERE PtypeID = @typeid AND Serial = @serial)
			--							BEGIN
											--INSERT INTO #SerialInfo
											--SELECT  
											--p.Pid AS goodserpid ,
											--ios.PtypeID ,
											--ios.Serial ,
											--k.Kid AS whserpid ,
											--ios.CargoID AS whspterpid ,
											--ios.ItemID ,
											--ios.IsCombined
											--FROM    dbo.gp_inoutPtypeSerial ios
											--		INNER JOIN Stock k ON ios.OutKtyeID = k.typeId OR ios.InKtypeID = k.typeId
											--		INNER JOIN dbo.ptype p ON ios.PtypeID = p.typeId
											--		INNER JOIN dbo.BillIndex b ON b.BillNumberId = ios.BillNumberid
											--WHERE   ios.BillNumberid IN ( SELECT    *
											--							  FROM      dbo.f_split(@ptypeid, ',') )
											--		AND p.WdSyncFlag = 1
											--		AND k.WdSyncFlag = 1
											--		AND b.draft = 0 
											--		AND ((b.RedWord = 0  AND ios.[State] NOT in (1,7)) OR (b.RedWord = 1 AND ios.[State] IN(1,7)))	
			--							END 
			--						ELSE
			--							BEGIN 
			--								INSERT INTO #SerialInfo
			--								SELECT  DISTINCT 
			--								p.Pid AS goodserpid ,
			--								ios.PtypeID ,
			--								ios.Serial ,
			--								CASE WHEN b.BillType IN (173) THEN k2.Kid
			--								ELSE k.Kid
			--								END AS whserpid ,
			--								ios.CargoID AS whspterpid ,
			--								ios.ItemID ,
			--								ios.IsCombined
			--								FROM    dbo.gp_inoutPtypeSerial ios
			--										INNER JOIN Stock k2 ON ios.OutKtyeID = k2.typeId --OR ios.InKtypeID = k.typeId
			--										INNER JOIN dbo.ptype p ON ios.PtypeID = p.typeId
			--										INNER JOIN dbo.BillIndex b ON b.BillNumberId = ios.BillNumberid
			--										INNER JOIN dbo.gp_CruPtypeSerial cp ON cp.PtypeID = ios.PtypeID AND ios.Serial = cp.Serial
			--										INNER JOIN stock k ON k.typeId = cp.KtypeID
			--								WHERE   ios.BillNumberid IN ( SELECT * FROM dbo.f_split(@ptypeid, ',') )
			--										AND p.WdSyncFlag = 1
			--										AND k.WdSyncFlag = 1
			--										AND b.draft = 0 
			--										AND cp.[State] NOT IN (1,7)
			--							END 
			--						SET @k=@k+1
			--					END 
								 
			--					SET @i=@i+1
			--				END
			--			END 
			--			FETCH NEXT FROM billnumberid_cursor INTO  @billnmuberid
			--		END
			--	Close billnumberid_cursor
			--	Deallocate billnumberid_cursor
				
   --         SELECT * FROM #SerialInfo
            
   --         DROP TABLE #Ptypeid
			--DROP TABLE #serial
			--DROP TABLE #SerialInfo
            SELECT  DISTINCT
                    p.Pid AS goodserpid ,
                    ios.PtypeID ,
                    ios.Serial ,
                    CASE WHEN b.BillType IN ( 173 ) THEN k2.Kid
                         ELSE k.Kid
                    END AS whserpid ,
                    ios.CargoID AS whspterpid ,
                    ios.ItemID ,
                    ios.IsCombined,
                    p.baseUnitId
            FROM    dbo.gp_inoutPtypeSerial ios
                    INNER JOIN Stock k2 ON ios.OutKtyeID = k2.typeId --OR ios.InKtypeID = k.typeId
                    INNER JOIN dbo.ptype p ON ios.PtypeID = p.typeId
                    INNER JOIN dbo.BillIndex b ON b.BillNumberId = ios.BillNumberid
                    INNER JOIN dbo.gp_CruPtypeSerial cp ON cp.PtypeID = ios.PtypeID
                                                           AND ios.Serial = cp.Serial
                    INNER JOIN Stock k ON k.typeId = cp.KtypeID
            WHERE   ios.BillNumberid IN ( SELECT    *
                                          FROM      dbo.f_split(@ptypeid, ',') )
                    AND p.WdSyncFlag = 1
                    AND k.WdSyncFlag = 1
                    AND b.draft = 0
                    AND cp.[State] NOT IN ( 1, 7 )
            UNION
            SELECT  p.Pid AS goodserpid ,
                    ios.PtypeID ,
                    ios.Serial ,
                    k.Kid AS whserpid ,
                    ios.CargoID AS whspterpid ,
                    ios.ItemID ,
                    ios.IsCombined,
                    p.baseUnitId
            FROM    dbo.gp_inoutPtypeSerial ios
                    INNER JOIN Stock k ON ios.OutKtyeID = k.typeId
                                          OR ios.InKtypeID = k.typeId
                    INNER JOIN dbo.ptype p ON ios.PtypeID = p.typeId
                    INNER JOIN dbo.BillIndex b ON b.BillNumberId = ios.BillNumberid
            WHERE   ios.BillNumberid IN ( SELECT    *
                                          FROM      dbo.f_split(@ptypeid, ',') )
                    AND p.WdSyncFlag = 1
                    AND k.WdSyncFlag = 1
                    AND b.draft = 0
                    AND ios.Serial IN (
                    SELECT  isnotexist.Serial
                    FROM    ( SELECT    Serial ,
                                        PtypeID
                              FROM      dbo.gp_inoutPtypeSerial
                              EXCEPT
                              SELECT    Serial ,
                                        PtypeID
                              FROM      dbo.gp_CruPtypeSerial
                            ) isnotexist )
                    AND ios.BillNumberId IN ( SELECT    *
                                          FROM      dbo.f_split(@ptypeid, ',') );	
		
		END 
	ELSE IF @flag = 13 --查询入库的序列号信息,ptypeid是billnumberid
		BEGIN       
            --当gp_inoutPtypeSerial表中字段state = 1并且关联billindxe表字段redword=0时既入库未红冲，是序列号入库
            --当gp_inoutPtypeSerial表中字段state = 2并且关联billindxe表字段redword=1时既出库红冲，是序列号入库
            SELECT  DISTINCT 
					p.Pid AS goodserpid ,
                    cp.PtypeID ,
                    cp.Serial ,
                    k.Kid AS whserpid ,
                    cp.CargoID AS whspterpid ,
                    cp.ItemID ,
                    cp.IsCombined,
                    p.baseUnitId
            FROM    dbo.gp_inoutPtypeSerial ios
                    INNER JOIN dbo.ptype p ON ios.PtypeID = p.typeId
                    INNER JOIN dbo.BillIndex b ON b.BillNumberId = ios.BillNumberid
                    INNER JOIN dbo.gp_CruPtypeSerial cp ON cp.PtypeID = ios.PtypeID AND ios.Serial = cp.Serial
                    INNER JOIN Stock k ON cp.KtypeID = k.typeId  
            WHERE   ios.BillNumberid IN ( SELECT * FROM dbo.f_split(@ptypeid, ',') )
                    AND p.WdSyncFlag = 1
                    AND k.WdSyncFlag = 1
                    AND b.draft = 0
                    AND cp.[State]  IN (1,7)		
		END 
	ELSE IF @flag = 14 --按仓库查商品仓库货位
		BEGIN
			SELECT DISTINCT
					p.Pid AS goodserpid ,
					s.Kid AS whserpid ,
					CargoID AS whspterpid ,
					g.PTypeID ,
					g.KTypeID ,
					g.CargoID ,
					p.FullName AS goodsname
			FROM    dbo.GOODSSTOCKS_QTY g
					INNER JOIN ptype p ON p.typeId = g.PTypeID
					INNER JOIN Stock s ON s.typeId = g.KTypeID
			WHERE   s.typeId IN ( SELECT    *
								  FROM      dbo.f_split(@ptypeid, ',') )
					AND p.WdSyncFlag = 1
					AND s.WdSyncFlag = 1;       
		END
	ELSE IF @flag = 15 --按商品查商品仓库货位
		BEGIN
			SELECT DISTINCT
					p.Pid AS goodserpid ,
					s.Kid AS whserpid ,
					CargoID AS whspterpid ,
					g.PTypeID ,
					g.KTypeID ,
					g.CargoID ,
					p.FullName AS goodsname
			FROM    dbo.GOODSSTOCKS_QTY g
					INNER JOIN ptype p ON p.typeId = g.PTypeID
					INNER JOIN Stock s ON s.typeId = g.KTypeID
			WHERE   p.typeId IN ( SELECT    *
								  FROM      dbo.f_split(@ptypeid, ',') )
					AND p.WdSyncFlag = 1
					AND s.WdSyncFlag = 1;       
		END
	ELSE IF @flag = 16 --按仓库查商品仓库货位
	BEGIN
		SELECT DISTINCT
				p.Pid AS goodserpid ,
				s.Kid AS whserpid ,
				CargoID AS whspterpid ,
				g.PTypeID ,
				g.KTypeID ,
				g.CargoID ,
				p.FullName AS goodsname
		FROM    dbo.GOODSSTOCKS_QTY g
				INNER JOIN ptype p ON p.typeId = g.PTypeID
				INNER JOIN Stock s ON s.typeId = g.KTypeID
		WHERE   p.WdSyncFlag = 1
				AND s.WdSyncFlag = 1;       
	END
	ELSE IF @flag = 17 --按客户信息下载
	BEGIN
		SELECT DISTINCT
				typeid,
				UserCode btypecode ,
				FullName AS btypename ,
				Comment AS remark,
				CASE WHEN deleted  = 1 THEN 'N'
				WHEN deleted = 0 THEN 'Y'
				END AS isvalid,
				Bid AS erpid
		FROM    dbo.btype 
		WHERE   sonnum = 0     
		AND  typeId IN ( SELECT * FROM   dbo.f_split(@ptypeid, ',') )
	END
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ProductPriceUpdate]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ProductPriceUpdate]
GO


/****

By：Haiyang, Li
Date：2012-11-03
Description：New
***/

CREATE PROCEDURE GP_ProductPriceUpdate
(
	@OperatorID				VARCHAR(100) ,
	@pcategoryid			VARCHAR(MAX) ,			--商品类别id筛选
	@ptypeidfilter			VARCHAR(MAX) ,			--商品id筛选
	@ptypefilter			VARCHAR(MAX) ,			--商品基本信息过滤字段
	@unitfilter				VARCHAR(200) ,			--此处为基本计量单位名字
	@pricefilter			VARCHAR(1000) ,			--预设价格表过滤字段
	@costpricefilter		VARCHAR(200) ,			--成本价过滤字段
	@platformfilters		VARCHAR(MAX) ,			--平台过滤条件
	@updatesql				VARCHAR(MAX) ,			--修改价格SQL
	@updatezerosql			VARCHAR(MAX),			--更新小于0的数据sql
	@updateunit				VARCHAR(100)			--修改的目标单位
)

--@encode$--
AS 
SET NOCOUNT ON

BEGIN
	--------------------------------------------------------------权限检查-------------------------------------------------------
  IF @OperatorID IS NULL 
      RETURN 1
  DECLARE @Re INT ,
      @MAtypeid VARCHAR(50) ,
      @MBtypeid VARCHAR(50) ,
      @MBtypeid2 VARCHAR(50) ,
      @MEtypeid VARCHAR(50) ,
      @MKtypeid VARCHAR(50) ,
      @MPtypeid VARCHAR(50) ,
      @MExpense VARCHAR(50) ,
      @MIncome VARCHAR(50) ,
      @MCapital VARCHAR(50) ,
      @MDtypeid VARCHAR(50) ,
      @MStypeid VARCHAR(50)
  EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
      @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
      @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT,
      @MIncome OUTPUT, @MCapital OUTPUT, @MDtypeid OUTPUT,
      @MStypeid OUTPUT
  IF @Re <> 0 
      RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	--处理ptype筛选条件
  DECLARE @strSQL VARCHAR(8000)

	--权限返回类商品
	CREATE TABLE #PtypeID (ptypeid VARCHAR(50))
	INSERT INTO #PtypeID(ptypeid)
	SELECT TypeId FROM dbo.F_ManPTypeInCategoryID(@OperatorID,@ptypeidfilter,@pcategoryid)

  SELECT  @strSQL = 'SELECT 
	S1.* ,
	CAST(CASE WHEN ISNULL(S1.qty, 0) = 0 THEN 0
                ELSE ( S1.total / S1.qty )
           END AS  NUMERIC(24, 10) ) AS cost
	INTO  #gstock
	FROM  ( SELECT    s.ptypeid ,
                  ISNULL(SUM(s.qty), 0) AS qty ,
                  ISNULL(SUM(s.total), 0) AS total
        FROM      goodsstocks s 
'
  IF @MPtypeid = '-99999' 
      SET @strSQL = @strSQL
          + ' INNER JOIN dbo.ptype_l L ON L.etypeid=''' + @OperatorID
          + ''' AND s.PtypeId LIKE L.typeid + ''%'''

  SET @strSQL = @strSQL + ' WHERE 1 = 1
        GROUP BY  s.ptypeid
      ) S1 '


SET @strSQL = @strSQL + '
	SELECT	p.typeid,
			p.usercode,
			p.fullname,
			pp.recamgstypebuyprice,
			p.deleted,
			pp.PreBuyPrice1,
			pp.PreBuyPrice2,
			pp.PreBuyPrice3,
			pp.PreBuyPrice4,
			pp.TopBuyPrice,
			pp.PreBuyPrice5,
			pp.PreSalePrice1,
			pp.PreSalePrice2,
			pp.PreSalePrice3,
			pp.PreSalePrice4,
			pp.PreSalePrice5,
			pp.PreSalePrice6,
			pp.PreSalePrice7,
			pp.PreSalePrice8,
			pp.PreSalePrice9,
			pp.PreSalePrice10,
			pp.RetailPrice,
			pp.TopSalePrice,
			pp.LowSalePrice,
			pp.ReferPrice,
			CAST(CASE 
				WHEN ISNULL(s.qty,0) = 0 THEN 0
				ELSE (s.total/s.qty)
				END AS  NUMERIC(24, 10) ) AS costprice,
			s.qty,
			pp.unitid
	INTO	#Result
	FROM	ptype p 
	INNER JOIN #PtypeID PID ON PID.ptypeid=p.typeid
	LEFT JOIN #gstock s ON s.Ptypeid=p.typeid 
	LEFT JOIN PType_Price pp ON p.typeid = pp.ptypeid  '
	
  -- 单位 现在加了多单位，调整了这里 谢吉康 2019-11-05
  IF @updateunit = 'baseunitid' 
	SET @strSQL += 'INNER JOIN PType_Units U ON U.UnitsId = p.baseUnitId '
  ELSE IF @updateunit = 'saleunitid'      
	SET @strSQL += 'INNER JOIN PType_Units U ON U.UnitsId = p.SaleUnitId '
  ELSE IF @updateunit = 'buyunitid'      
	SET @strSQL += 'INNER JOIN PType_Units U ON U.UnitsId = p.buyunitid '
  ELSE IF @updateunit = 'stockunitid'      
	SET @strSQL += 'INNER JOIN PType_Units U ON U.UnitsId = p.buyunitid '	
ELSE IF @updateunit = 'assisunit1'      
	SET @strSQL += 'INNER JOIN PType_Units_Ext pue ON pue.PtypeID = p.typeId AND pue.IsDefaultUnit = 0 AND IsUse = 1 AND UnitsSortId = 2 '
ELSE IF @updateunit = 'assisunit2'      
	SET @strSQL += 'INNER JOIN PType_Units_Ext pue ON pue.PtypeID = p.typeId AND pue.IsDefaultUnit = 0 AND IsUse = 1 AND UnitsSortId = 3 '
ELSE IF @updateunit = 'assisunit3'      
	SET @strSQL += 'INNER JOIN PType_Units_Ext pue ON pue.PtypeID = p.typeId AND pue.IsDefaultUnit = 0 AND IsUse = 1 AND UnitsSortId = 4 '												


  SET @strSQL = @strSQL + '
	WHERE p.sonnum = 0 ' + @ptypefilter --基本信息过滤条件
	IF @updateunit = 'baseunitid' 
	BEGIN
		SET @strSQL = @strSQL + ' AND NOT EXISTS (select 1 from PType_Units_Ext e 
	where isdefaultunit=0  and isuse=1 AND e.PtypeID=pp.pTypeid AND pp.unitid=e.UnitsId)  '
	END
	
	IF (@updateunit = 'assisunit1')
	BEGIN
		SET @strSQL = @strSQL + ' AND  EXISTS (select 1 from PType_Units_Ext e 
	where isdefaultunit=0  and isuse=1 AND e.RateType=0 AND e.PtypeID=pp.pTypeid AND pp.unitid=e.UnitsId 
	AND e.UnitsSortId=2)  '
	END
	
	IF (@updateunit = 'assisunit2')
	BEGIN
		SET @strSQL = @strSQL + ' AND  EXISTS (select 1 from PType_Units_Ext e 
	where isdefaultunit=0  and isuse=1 AND e.RateType=0 AND e.PtypeID=pp.pTypeid AND pp.unitid=e.UnitsId 
	AND e.UnitsSortId=3)  '
	END
	
	IF (@updateunit = 'assisunit3')
	BEGIN
		SET @strSQL = @strSQL + ' AND  EXISTS (select 1 from PType_Units_Ext e 
	where isdefaultunit=0  and isuse=1 AND e.RateType=0 AND e.PtypeID=pp.pTypeid AND pp.unitid=e.UnitsId 
	AND e.UnitsSortId=4 )  '
	END
	
	
	SET @strSQL = @strSQL + @unitfilter --单位过滤条件
		  + @pricefilter --PType_Price表过滤
		  + @costpricefilter --成本价过滤
		  + @platformfilters --平台过滤条件
		  + ' ORDER BY P.UserCode  '
		  
SET @strSQL = @strSQL + '	  
--处理pos
IF NOT EXISTS(SELECT 1 FROM PosReDataGlobal WHERE  stypeid=''-99999'')
BEGIN
	INSERT INTO PosReDataGlobal VALUES(1,''-99999'')
END
ELSE
BEGIN
	IF  EXISTS(SELECT 1 FROM PosReDataGlobal WHERE ifredata=0) 
		BEGIN
			 UPDATE PosReDataGlobal SET ifredata=1,stypeid=''-99999''
		END
 END
	 
IF NOT EXISTS(SELECT 1 FROM PosIsUpdateData WHERE  tbType=''PType_Price'' )
BEGIN
	INSERT INTO PosIsUpdateData VALUES(''PType_Price'',0,1,''-99999'')
END
 ELSE
BEGIN
	IF  EXISTS(SELECT 1 FROM PosIsUpdateData WHERE  tbType=''PType_Price'' AND Tid=0 AND ifUpdate=1 AND stypeid=''-99999'' ) 
		BEGIN
			 UPDATE PosIsUpdateData SET ifUpdate=1,stypeid=''-99999'',tbType=''PType_Price'',Tid=0
		END
 END '
	 
--修改数据部分	 
SET @strSQL = @strSQL + @updatesql + '
	FROM	#Result a 
	WHERE	ptype_price.ptypeid=a.typeid 
			and ptype_price.unitid= a.unitid
				
	
	DELETE  ptype_price 
	FROM	ptype_price pr
	INNER JOIN #Result A ON pr.ptypeid=a.typeid and pr.unitid= a.unitid
	WHERE	pr.IsDefaultUnit=0
			and isnull(pr.PreBuyPrice1 ,0)=0 
			and isnull(pr.PreBuyPrice2 ,0)=0 
			and isnull(pr.PreBuyPrice3 ,0)=0 
			and isnull(pr.PreBuyPrice4 ,0)=0 
			and isnull(pr.PreBuyPrice5 ,0)=0 
			and isnull(pr.PreSalePrice1 ,0)=0 
			and isnull(pr.PreSalePrice2,0)=0 
			and isnull(pr.PreSalePrice3 ,0)=0 
			and isnull(pr.PreSalePrice4 ,0)=0 
			and isnull(pr.PreSalePrice5 ,0)=0 
			and isnull(pr.PreSalePrice6 ,0)=0 
			and isnull(pr.PreSalePrice7 ,0)=0 
			and isnull(pr.PreSalePrice8 ,0)=0 
			and isnull(pr.PreSalePrice10 ,0)=0 
			and isnull(pr.RetailPrice ,0)=0 
			and isnull(pr.TopSalePrice ,0)=0 
			and isnull(pr.LowSalePrice ,0)=0 
			and isnull(pr.TopBuyPrice,0)=0 
			and isnull(pr.ReferPrice,0)=0 
			and isnull(pr.RecAmgSTypeBuyPrice,0)=0
			and isnull(pr.RecAmgSTypeSalePrice,0)=0
				
	DROP TABLE #gstock
	DROP TABLE #Result'
  
	--PRINT ( @strSQL )
	EXEC(@strSQL)
	
	IF @updatezerosql <> '' 
		EXEC(@updatezerosql)

	DECLARE @XiWaMaxNumber INT=0	

	--修改商品档案的缓存最大值
	SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM PType

	UPDATE	P 
	SET		XiWaMaxNumber=@XiWaMaxNumber,
			@XiWaMaxNumber+=1
	FROM	PType P
	INNER JOIN #PtypeID T ON T.ptypeid=P.typeId
		
	DROP TABLE #PtypeID
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_ProductStypePriceUpdate]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_ProductStypePriceUpdate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-
	描述：分支机构物价信息查询
	
	作者：徐辉
	日期：2011-08-16
	描述：分支机构物价信息查询，更新物价信息表。
		为了只修改物价信息列出来的数据
*/

CREATE PROCEDURE GP_ProductStypePriceUpdate
    (
      @OperatorID VARCHAR(100) ,
      @STypeId VARCHAR(50) ,				--分支机构
      @ptypeidfilter VARCHAR(MAX) ,			--商品id筛选
      @ptypefilter VARCHAR(MAX) ,			--商品基本信息过滤字段
      @platformfilters VARCHAR(MAX) ,		--平台过滤条件
      @updatesql VARCHAR(MAX) ,				--修改价格SQL
      @updatezerosql VARCHAR(MAX),			--更新小于0的数据sql
      @displayzero	INT = 1			--是否显示为0的数据 1显示 0不显示
    )
--@encode$--
AS 
    SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT

    IF @Re <> 0 
        RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--处理筛选商品id
 CREATE TABLE #ptype 
 (
	typeid		VARCHAR(60),
	usercode    VARCHAR(200),
	fullname    VARCHAR(200)
 )
 
 
 IF @ptypeidfilter <> '' 
    BEGIN
		IF(@displayzero = 0)
		BEGIN
			INSERT  INTO #ptype ( typeid
					)
					SELECT P.TypeId FROM 
					(
						SELECT  P.TypeId 
						FROM F_GetManDetailPType(@OperatorId) AS P ,
						(select * from  dbo.f_split(@ptypeidfilter,',')) AS b 
						where left(P.typeid,len(b.a))=b.a
					) AS P 
					INNER JOIN ptype AS PT ON(P.TypeId = PT.typeId)
					INNER JOIN 
					(
						SELECT A.PtypeId FROM goodsstocks AS A INNER JOIN STOCK AS B ON(A.KtypeId = B.typeId)
						WHERE B.parid <> 'root'  AND B.STypeID = @STypeId 
						GROUP BY A.PtypeId
					) AS T ON(P.TypeId = T.PtypeId)
					WHERE PT.IsService = 0
					
					UNION ALL
					
					SELECT P.TypeId FROM 
					(
						SELECT  P.TypeId 
						FROM F_GetManDetailPType(@OperatorId) AS P ,
						(select * from  dbo.f_split(@ptypeidfilter,',')) AS b 
						where left(P.typeid,len(b.a))=b.a
					) AS P
					INNER JOIN ptype AS PT ON(P.TypeId = PT.typeId)
					WHERE PT.IsService = 1
		END
		ELSE
		BEGIN
			INSERT  INTO #ptype ( typeid
					)
					SELECT  P.TypeId 
					FROM F_GetManDetailPType(@OperatorId) AS P ,
					(select * from  dbo.f_split(@ptypeidfilter,',')) AS b 
					where left(P.typeid,len(b.a))=b.a
		END
    END
 ELSE 
    BEGIN
		IF(@displayzero = 0)
		BEGIN
			INSERT  INTO #ptype
					( typeid
					)
					SELECT  typeid
					FROM    ptype AS P 
					INNER JOIN 
					(
						SELECT A.PtypeId FROM goodsstocks AS A INNER JOIN STOCK AS B ON(A.KtypeId = B.typeId)
						WHERE B.parid <> 'root'  AND B.STypeID = @STypeId 
						GROUP BY A.PtypeId
					) AS T ON(P.TypeId = T.PtypeId)
					WHERE   typeid IN ( SELECT  typeid
										FROM    F_GetManDetailPType(@OperatorID) )
							AND sonnum = 0
							AND IsService = 0
					UNION ALL
					SELECT  typeid
					FROM    ptype
					WHERE   typeid IN ( SELECT  typeid
										FROM    F_GetManDetailPType(@OperatorID) )
							AND sonnum = 0
							AND IsService = 1  
		END
		ELSE
		BEGIN
			INSERT  INTO #ptype
					( typeid
					)
					SELECT  typeid
					FROM    ptype AS P
					WHERE   typeid IN ( SELECT  typeid
										FROM    F_GetManDetailPType(@OperatorID) )
							AND sonnum = 0
		END					      
    END


UPDATE  #ptype
SET     #ptype.fullname = a.fullname ,
        #ptype.usercode = a.usercode
FROM    ( SELECT    p.typeid ,
                    p.UserCode ,
                    p.FullName
          FROM      #ptype p1
                    INNER JOIN ptype p ON p1.typeid = p.typeId
        ) a
WHERE   a.typeId = #ptype.typeid

--SELECT  * FROM  #ptype

--DROP TABLE #ptype
--RETURN


DECLARE @SQL_WHERE VARCHAR(500)

SET @SQL_WHERE=' WHERE 1=1 '

IF @ptypefilter<>''
BEGIN
	SET  @SQL_WHERE= @SQL_WHERE + @ptypefilter
END

IF @platformfilters<>''
BEGIN
	SET  @SQL_WHERE= @SQL_WHERE + @platformfilters
END
  
--只修改基本单位物价信息
DECLARE @SQL NVARCHAR(MAX)=''
SET @SQL = 'SELECT	pt.TypeId as ptypeid,
					'''+@STypeId+''' as stypeid,
					ISNULL(M.RecPrice,0) AS RecPrice,
					ISNULL(M.PreBuyPrice1,0) AS PreBuyPrice1,
					ISNULL(M.PreBuyPrice2, 0) AS PreBuyPrice2,
					ISNULL(M.PreBuyPrice3,  0) AS PreBuyPrice3,
					ISNULL(M.PreBuyPrice4,  0) AS PreBuyPrice4,
					ISNULL(M.PreBuyPrice5,  0) AS PreBuyPrice5,
					ISNULL(M.PreSalePrice1,  0) AS PreSalePrice1,
					ISNULL(M.PreSalePrice2,  0) AS PreSalePrice2,
					ISNULL(M.PreSalePrice3,  0) AS PreSalePrice3,
					ISNULL(M.PreSalePrice4,  0) AS PreSalePrice4,
					ISNULL(M.PreSalePrice5,  0) AS PreSalePrice5,
					ISNULL(M.PreSalePrice6,  0) AS PreSalePrice6,
					ISNULL(M.PreSalePrice7,  0) AS PreSalePrice7,
					ISNULL(M.PreSalePrice8,  0) AS PreSalePrice8,
					ISNULL(M.PreSalePrice9,  0) AS PreSalePrice9,
					ISNULL(M.PreSalePrice10,  0) AS PreSalePrice10,
					ISNULL(M.RetailPrice,  0) AS RetailPrice,
					ISNULL(M.TopSalePrice,  0) AS TopSalePrice,
					ISNULL(M.LowSalePrice, 0) AS LowSalePrice,
					ISNULL(M.TopBuyPrice, 0) AS TopBuyPrice,
					ISNULL(M.referprice, 0) AS referprice,
					ext.unitsid as unitid,
					ext.isdefaultunit 
					
			INTO #result
			FROM	#ptype pt
			LEFT JOIN (
				SELECT	*
				FROM	PType_StypePrice
				WHERE	STypeId='''+@STypeId+'''
				and isdefaultunit=1						
			)M ON M.PTypeId = pt.TypeId  
			INNER JOIN PTYPE_UNITS_EXT EXT ON PT.TypeId=EXT.PTYPEID AND ext.ISDEFAULTUNIT=1
			 '+@SQL_WHERE

    SET @SQL = @SQL + '
			MERGE dbo.PType_STypePrice t
			USING #result s ON t.ptypeid = s.ptypeid AND t.stypeid =S.stypeid 
			WHEN NOT MATCHED THEN INSERT
			(
						 sTypeId,
						 PTYPEID,
				         RecPrice,
						 PreBuyPrice1,
						 PreBuyPrice2,
						 PreBuyPrice3,
						 PreBuyPrice4,
						 PreBuyPrice5,
						 PreSalePrice1,
						 PreSalePrice2, 
						 PreSalePrice3,
						 PreSalePrice4,
						 PreSalePrice5,
						 PreSalePrice6,
						 PreSalePrice7,
						 PreSalePrice8,
						 PreSalePrice9,
						 PreSalePrice10,
						 RetailPrice,
						 TopSalePrice,
						 LowSalePrice,
						 TopBuyPrice,
						 unitid,
						 isdefaultunit  
			)
			 VALUES(
						S.stypeid,
						S.ptypeId,
						S.RecPrice,
						S.PreBuyPrice1,
						S.PreBuyPrice2,
						S.PreBuyPrice3,
						S.PreBuyPrice4,
						S.PreBuyPrice5,
						S.PreSalePrice1,
						S.PreSalePrice2,
						S.PreSalePrice3,
						S.PreSalePrice4,
						S.PreSalePrice5,
						S.PreSalePrice6,
						S.PreSalePrice7,
						S.PreSalePrice8,
						S.PreSalePrice9,
						S.PreSalePrice10,
						S.RetailPrice,
						S.TopSalePrice,
						S.LowSalePrice,
						S.TopBuyPrice, 
						S.unitid,
						S.isdefaultunit  );
						
			' + @UpdateSQL +' AND Ptype_StypePrice.isdefaultunit=1 '
        + '   DROP TABLE #result '
--PRINT @SQL
    EXEC sp_executesql @SQL, N'@OperatorID nvarchar(50),@stypeid nvarchar(50)' ,@OperatorID,@Stypeid
    IF @UpdateZeroSql <> '' 
		set @UpdateZeroSql+=' and Ptype_StypePrice.isdefaultunit=1'
        EXEC(@UpdateZeroSql)
        
DELETE  FROM  PType_STypePrice 
WHERE STYPEID=@STypeID
AND IsDefaultUnit=0
and ISNULL(PreBuyPrice1,0)=0 
AND	ISNULL(PreBuyPrice2,0)=0
AND ISNULL(PreBuyPrice3,0)=0
AND	ISNULL(PreBuyPrice4,0)=0 
AND	ISNULL(PreBuyPrice5,0)=0
AND	ISNULL(PreSalePrice1,0)=0
AND	ISNULL(PreSalePrice2,0)=0 
AND	ISNULL(PreSalePrice3,0)=0 
AND	ISNULL(PreSalePrice4,0)=0 
AND	ISNULL(PreSalePrice5,0)=0 
AND	ISNULL(PreSalePrice6,0)=0 
AND	ISNULL(PreSalePrice7,0)=0 
AND	ISNULL(PreSalePrice8,0)=0 
AND	ISNULL(PreSalePrice9,0)=0 
AND	ISNULL(PreSalePrice10, 0)=0
AND	ISNULL(RetailPrice,0)=0 
AND	ISNULL(TopSalePrice,0)=0 
AND	ISNULL(LowSalePrice,0)=0
AND	ISNULL(RecPrice,0)=0
AND	ISNULL(TopBuyPrice,0)=0
AND	ISNULL(referprice,0)=0
AND ISNULL(RECSALEPRICE,0)=0
AND ISNULL(RECAPPRAISALPRICE,0)=0
AND ISNULL(RECSENDPRICE,0)=0

declare @xiwamaxnumber int

select @xiwamaxnumber=max(xiwamaxnumber) from ptype_stypeprice where STYPEID=@STypeID

update ptype_stypeprice set xiwamaxnumber=@xiwamaxnumber+1 where STYPEID=@STypeID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/05/17
	Description	:	保存计提减值准备
					1.该卡片是否配置减值科目，本期是否已经计提
					2.保存该条记录
					3.更新卡片信息，以及保存历史数据
					4 生成折旧计划表(本期是否已经计提，如果已经计提了本期就不重算，从下期算起。没计提就从本期算起)
					5 影响项目
					6 生成财务凭证
					7 特殊情况，删除该单据日期后的有所变更折旧单及历史记录
*/
CREATE PROCEDURE Gp_ProvisionForImpairment
(
	@CardID			INT,					--卡片ID
	@ChangeValue	 NUMERIC(24, 10) ,			--改变的值
	@IsCreateSchedule	INT,				--是否生成计划表 1 生成 0 不生成
	@businessdate		DATE,							
	@UserID			VARCHAR(50),			--操作员
    @ReturnValue	VARCHAR(MAX) out		--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Re				INT=0
DECLARE @newID			INT
DECLARE @DevalueATypeId VARCHAR(50)
DECLARE @date			DATE=GETDATE()
DECLARE @Stypeid VARCHAR(50),@Cid INT,@verifyStypeid VARCHAR(50)

SELECT @Cid=Cid FROM dbo.Ac_Currency WHERE Sysrow=1
SELECT  @Stypeid=ac.STypeId,@verifyStypeid=aac.StypeId 
FROM  dbo.AC_AssetsCards ac 
JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id 
WHERE ac.Id=@CardID


--1是否含有减值准备,本期是否已计提
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'isuseacsystem' AND SubValue = 1)
BEGIN
	SELECT  @DevalueATypeId=DevalueATypeId FROM dbo.Ac_AssetsCards WHERE ID=@CardID
	IF @DevalueATypeId IS NULL OR @DevalueATypeId=''
		BEGIN
			SET @ReturnValue='未配置减值准备科目，不能进行保存'
			RETURN -2
		END
END
DECLARE @FYear		VARCHAR(10),
		@FPeriod	INT
--获取指定分支机构当前年度,财务期间	
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @verifyStypeid)
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @verifyStypeid
ELSE 
	BEGIN
		SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName='fyear'
		SELECT @FPeriod=SubValue FROM dbo.sysdata WHERE SubName='fperiod'
	END

IF @Fperiod=13 SET @Fperiod=12    

DECLARE @DepreciationMean INT
SELECT @DepreciationMean = DepreciationMean FROM Ac_AssetsCards WHERE Id = @CardID

IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@FYear AND fperiod=@FPeriod AND PlanState=0 AND DepreciationMean=@DepreciationMean)
	BEGIN
		SET @ReturnValue='请先计提本期折旧'
		RETURN -2
	END
--2录入本条数据
INSERT INTO Ac_ProvisionForImpairment(CardId,DevalueReady,UsedDevalueReady,OperationDate,ETypeId,FYear,FPeriod,IfRecalculate,BusinessDate)
SELECT @CardID,dbo.F_RoundTotal(@ChangeValue),(SELECT dbo.F_RoundTotal(DevalueReady) FROM dbo.AC_AssetsCards WHERE ID=@CardID),@date,@UserID,@FYear,@FPeriod,@IsCreateSchedule,@businessdate

SELECT @newID=SCOPE_IDENTITY();        ----获取该条记录的生成的id，生成凭证用
 
--3修改卡片值,生成历史记录
UPDATE dbo.AC_AssetsCards SET DevalueReady=DevalueReady+@ChangeValue,NetValue=NetValue-@ChangeValue WHERE Id=@CardID

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AssetsCards WHERE Id=@CardID AND NetValue<0)
	BEGIN
		SET @ReturnValue='卡片净值小于0，不能保存'
		RETURN -2
	END

DECLARE @tempRe VARCHAR(max)
EXEC Gp_SaveAssetsCardHistory @verifyStypeid,@CardID,@UserID,@businessdate,-1,@newID,13,@tempRe OUT

--4 修改折旧表和重新生成折旧计划表
DECLARE @monthorder INT 
SELECT @monthorder=MonthOrder FROM dbo.Ac_DepreciationPlan ac WHERE ac.AssetCardId=@CardID AND PlanType=1 AND FYear=@FYear AND FPeriod=@FPeriod AND DepreciationMean=@DepreciationMean 

UPDATE ac SET  ac.DevalueReady=dbo.F_RoundTotal(aa.DevalueReady),ac.NetValue=dbo.F_RoundTotal(aa.NetValue)
FROM  dbo.Ac_DepreciationPlan ac 
JOIN Ac_AssetsCards aa ON aa.id=ac.AssetCardId AND AA.DepreciationMean=AC.DepreciationMean
WHERE ac.AssetCardId=@CardID AND  PlanType=1 AND MonthOrder>@monthorder 

IF @FPeriod=12
	UPDATE ac SET ac.DevalueReady=dbo.F_RoundTotal(aa.DevalueReady) ,ac.NetValue=dbo.F_RoundTotal(aa.NetValue)
	FROM  dbo.Ac_DepreciationPlan ac 
	JOIN Ac_AssetsCards aa ON aa.id=ac.AssetCardId AND AA.DepreciationMean = AC.DepreciationMean
	WHERE ac.AssetCardId=@CardID AND  PlanType=0 AND FYear>@FYear
ELSE 
	UPDATE ac SET ac.DevalueReady=dbo.F_RoundTotal(aa.DevalueReady) ,ac.NetValue=dbo.F_RoundTotal(aa.NetValue)
	FROM  dbo.Ac_DepreciationPlan ac 
	JOIN Ac_AssetsCards aa ON aa.id=ac.AssetCardId AND AA.DepreciationMean=AC.DepreciationMean
	WHERE ac.AssetCardId=@CardID AND  PlanType=0 AND FYear>=@FYear

IF @IsCreateSchedule=1 
	EXEC @Re=Gp_ReCreateDepreciationPlan @CardID,0

--5生成一张业务凭证,调用过账存储过程(直接影响项目,直接修改atype_total表  23 其他支出)
  --生成billcode
  DECLARE @billcode VARCHAR(200),@Dfullname VARCHAR(500),@dtypeid VARCHAR(50),@Etypeid varchar(100)
  SELECT @Dfullname=d.FullName,@dtypeid=aa.DTypeid,@Etypeid=ETypeId
  FROM dbo.Ac_AssetsCards aa 
  JOIN dbo.Department d ON aa.DTypeid=d.typeid
  WHERE id=@CardID
  
  IF EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='ifbillcode' AND Value=0)  --用户手工录入单据编号
		SET @billcode=''
  ELSE 
	BEGIN
	    --用户自定义单据编号
		IF EXISTS(SELECT TOP 1 1 FROM CodeConfig WHERE BillType=159) 
		AND EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName='BillCodeConfig' AND Value=1)
			BEGIN
				DECLARE @etypename VARCHAR(200),
						@cefullname	VARCHAR(200)=''
				SELECT @etypename=@Etypeid
				SELECT @cefullname=fullname FROM dbo.employee WHERE typeId=@UserID
				EXEC Gp_GetBillCode @BType=159,@MONTH=@etypename,@DAY='',@BillFlag='KP',@BillDate=@businessdate,@Stypeid=@Stypeid,@DFullName=@Dfullname,
				@BCode=@billcode OUTPUT,@CEFullName=@cefullname
			END
		ELSE --自动生成
			DECLARE @tMonthe VARCHAR(500),@tDay VARCHAR(50)
			SET @tMonthe=DateName(month,@businessdate)
			SET @tDay=DateName(day,@businessdate)
			EXEC Gp_GetBillCode @BType=159,@MONTH=@tMonthe,@DAY=@tDay,@BillFlag='KP',@BillDate=@businessdate,@Stypeid=@Stypeid,@DFullName=@Dfullname,
			@BCode=@billcode OUTPUT,@CEFullName=@cefullname
	END
	
DECLARE @period INT,@BillNumberId NUMERIC(18,0)
SELECT @period=SubValue FROM dbo.sysdata WHERE SubName='period'  --业务日期

INSERT INTO dbo.BillIndex
         (BillDate,BillCode,BillType,Comment,etypeid,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,explain,RedWord,btypeid,ktypeid,
          draft,OrderId,waybillcode,goodsnumber,packway,TEL,Uploaded,AlertDay,CompleteTotal,ID,Assessor,IfAudit,Audit_explain,IfStopMoney,preferencemoney,
          DTypeId,JF,VipCardID,vipCZMoney,jsStyle,jsState,JieJianBillNumberID,JieJianID,JieJianState,BaoXiuBillNumberID,BaoXiuID,
          wxTotal,ifHideJieJian,ifWX,ifYearBill,Stypeid,FromBillNumberID,CostSale,OtherInOutType,PosBillType,checkTime,ShareMode,IsIni,
          NCompleteTotal,ATID,IfCargo,InvoiceMoney,NInvoiceMoney,RedReason,PrePriceNum,AssetBusinessTypeId,
          PromoRuleId,BeforePromoBillNumberId,ImportType,NewPosBill,PromotionMsg,CWCheck,IfBargainOn,IfMulAccount,IsFreightMoney,IfInvoice,
          UF1,UF2,UF3,UF4,UF5,DealBTypeID,CID,Rate,NTotalMoney,NTotalInMoney,NPreferenceMoney,NVIPCZMoney,billproperty,TallyId)
VALUES   (@businessdate, -- BillDate - datetime
          @billcode, -- BillCode - varchar(200)
          159, -- BillType - numeric
          '固定资产卡片计提减值准备生成业务凭证', -- Comment - varchar(256)
          @UserID, -- etypeid - varchar(50)
          'f', -- ifcheck - char(1)
          @UserID, -- checke - varchar(50)
          0, -- totalmoney - numeric
          0, -- totalinmoney - numeric
          0, -- totalqty - numeric
          0, -- tax - numeric
          @period, -- period - smallint
          '', -- explain - varchar(256)
          0, -- RedWord - int
          '',  --btypeid
          '',  --ktypeid
          1, -- draft - bit
          0, -- OrderId - numeric
          '', -- waybillcode - varchar(20)
          '', -- goodsnumber - varchar(20)
          '', -- packway - varchar(20)
          '', -- TEL - varchar(60)
          0, -- Uploaded - bit
          9999, -- AlertDay - int
          0, -- CompleteTotal - numeric
          0, -- ID - numeric
          '', -- Assessor - varchar(50)
          '', -- IfAudit - char(1)
          '', -- Audit_explain - varchar(256)
          0, -- IfStopMoney - char(1)
          0, -- preferencemoney - numeric
          @dtypeid, -- DTypeId - varchar(50)
          0, -- JF - int
          -1, -- VipCardID - int
          0, -- vipCZMoney - numeric
          0, -- jsStyle - char(1)
          0, -- jsState - char(1)
          -1, -- JieJianBillNumberID - int
          -1, -- JieJianID - int
          -1, -- JieJianState - int
          -1, -- BaoXiuBillNumberID - int
          -1, -- BaoXiuID - int
          0, -- wxTotal - numeric
          0, -- ifHideJieJian - int
          0, -- ifWX - int
          0, -- ifYearBill - int
          @stypeid, -- Stypeid - varchar(50)
          0, -- FromBillNumberID - numeric
          0, -- CostSale - bit
          -1, -- OtherInOutType - int
          0, -- PosBillType - int
          GETDATE(), -- checkTime - datetime
          0, -- ShareMode - tinyint
          0, -- IsIni - bit
          0, -- NCompleteTotal - numeric
          0, -- ATID - int
          0, -- IfCargo - bit
          0, -- InvoiceMoney - numeric
          0, -- NInvoiceMoney - numeric
          '', -- RedReason - varchar(500)
          0, -- PrePriceNum - int
          0, -- AssetBusinessTypeId - int
          0, -- PromoRuleId - int
          0, -- BeforePromoBillNumberId - int
          0, -- ImportType - tinyint
          0, -- NewPosBill - tinyint
          0, -- PromotionMsg - nvarchar(500)
          0, -- CWCheck - int
          0, -- IfBargainOn - int
          0, -- IfMulAccount - int
          0, -- IsFreightMoney - int
          0, -- IfInvoice - int
          '', -- UF1 - varchar(200)
          '', -- UF2 - varchar(200)
          '', -- UF3 - varchar(200)
          '', -- UF4 - varchar(200)
          '', -- UF5 - varchar(200)
          '', -- DealBTypeID - varchar(50)
          @cid, -- CID - int
          1, -- Rate - numeric
          0, -- NTotalMoney - numeric
          0, -- NTotalInMoney - numeric
          0, -- NPreferenceMoney - numeric
          0, -- NVIPCZMoney - numeric
          -1, -- billproperty - int
          ''  -- TallyId - varchar(50)
          )
SELECT @BillNumberId=SCOPE_IDENTITY();

---更新种子
EXEC GP_SaveBillCode_Seed @BillNumberId,@businessdate,159,@billcode						----更新编号种子数

--回写表
UPDATE dbo.Ac_ProvisionForImpairment SET billnumberid=@BillNumberId WHERE id=@newID

-----------明细表
 --固定资产卡片原值
DECLARE @fixedassetsid INT
SELECT @fixedassetsid=nId FROM dbo.Ac_Items WHERE UserCode='SYC-1601'   
IF @ChangeValue>0 
	BEGIN
		--其他支出
		INSERT INTO dbo.AccountCredence(BillNumberID,TypeATypeID,ATypeID,J_Total,D_Total,Comment,Stypeid,NJ_Total,ND_Total,CID,Rate)
		VALUES   (@BillNumberId,23,23,dbo.F_RoundTotal(@ChangeValue),0,'',@stypeid,dbo.F_RoundTotal(@ChangeValue),0,@cid,1)
		 --固定资产卡片原值
		INSERT INTO dbo.AccountCredence(BillNumberID,TypeATypeID,ATypeID,J_Total,D_Total,Comment,Stypeid,NJ_Total,ND_Total,CID,Rate)
		VALUES   (@BillNumberId,@fixedassetsid,@fixedassetsid,0,dbo.F_RoundTotal(@ChangeValue),'',@stypeid,0,dbo.F_RoundTotal(@ChangeValue),@cid,1)
	END
ELSE 
	BEGIN
		DECLARE @changevalue1  NUMERIC(24, 10) 
		SET @changevalue1=ABS(@ChangeValue) 
		--其他支出
		INSERT INTO dbo.AccountCredence(BillNumberID,TypeATypeID,ATypeID,J_Total,D_Total,Comment,Stypeid,NJ_Total,ND_Total,CID,Rate)
		VALUES   (@BillNumberId,23,23,0,dbo.F_RoundTotal(@changevalue1),'',@stypeid,0,dbo.F_RoundTotal(@changevalue1),@cid,1)
		 --固定资产卡片原值
		INSERT INTO dbo.AccountCredence(BillNumberID,TypeATypeID,ATypeID,J_Total,D_Total,Comment,Stypeid,NJ_Total,ND_Total,CID,Rate)
		VALUES   (@BillNumberId,@fixedassetsid,@fixedassetsid,dbo.F_RoundTotal(@changevalue1),0,'',@stypeid,dbo.F_RoundTotal(@changevalue1),0,@cid,1)
	END




---为了过账不生成财务凭证，把系统里的IsUseAcSystem配置设置成0，过账后又改回来
DECLARE @tempStatus  VARCHAR(50)
SELECT @tempStatus=SubValue  FROM sysdata WHERE SubName = 'IsUseAcSystem' 
UPDATE dbo.sysdata SET SubValue=0 WHERE SubName = 'IsUseAcSystem'
--调用过账 
declare @p3 varchar(1000)
set @p3=''
declare @p5 varchar(50)
set @p5=''
declare @p7 varchar(50)
set @p7=''
declare @p9 varchar(200)
set @p9=''
declare @p10 varchar(max)
set @p10=''
exec Gp_Auditing @nBillID=@BillNumberId,@szCheckMan=@UserID,@szPID=@p3 output,@chvOpID=@UserID,@KTypeID=@p5 output,@billtype=159,@voucherMsg=@p7 output,@VipCentInfo=@p9 output,@AssetMsg=@p10 output

UPDATE dbo.sysdata SET SubValue=@tempStatus WHERE SubName = 'IsUseAcSystem'

--6按模版生成凭证
DECLARE @isPosting VARCHAR(10),@template VARCHAR(10),@vId INT,@revoucher INT
SELECT @isPosting=SubValue FROM dbo.sysdata WHERE SubName='postingparameter'
--IF @isPosting='0'  -- 1业务单据过账，可以不甩它；0及时过账，立马生成凭证
	--BEGIN
		EXEC @revoucher = Gp_CreateVoucher_Assets @newID,1,0,@date,@ReturnValue OUTPUT,@vId OUTPUT
		IF @revoucher<>0
			BEGIN
				DELETE FROM dbo.Ac_Voucher WHERE BillNumberId=@vId
				DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId=@vId
				DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId=@vId
			END
	--END

--7 删除变更单记录
DELETE Ac_DepreciationAlteration WHERE CardId=@CardID AND BusinessDate>=@businessdate AND DepreciationMean=@DepreciationMean 

DELETE dbo.Ac_AssetsCards_History WHERE AssertsCardId=@CardID AND BillType=-3 AND  BusinessDate>=@businessdate	AND DepreciationMean=@DepreciationMean 



IF @revoucher<>0  --凭证生成不成功，但不影响我计提的保存
	SET @Re=1
    
RETURN @Re
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：舒珊
	日期：2016.05.11
	描述：批量修改基础资料字段值
			
*/
CREATE PROCEDURE GP_PtypeBatchRevise
(
	@operateid  VARCHAR(100),	--操作员
	@FieldName	 VARCHAR(500),	--修改字段名称
	@FieldValue	 VARCHAR(MAX),	--字段值
	@IfTextFirst INT,			--字符串拼接格式 （文本在前还是字段值在前）	
	@FieldText	VARCHAR(50),	--拼接的字段名称
	@Stypeid	VARCHAR(50),	--分支机构ID 
    @MagEType	VARCHAR(50),
    @Mode		INT,
    @UserCode	VARCHAR(3000)='',
    @FullName	VARCHAR(3000)='',
    @parentname	VARCHAR(500)='',
    @FiltVal	VARCHAR(200)='',
    @EntryCode    VARCHAR(3000)='',       --商品条码
    @KtypeID    VARCHAR(50) = '',
	@ParID		VARCHAR(50)='',
	@StartDate	VARCHAR(50) ='',
	@EndDate	VARCHAR(50) ='',
	@ifdeleted	VARCHAR(2)=0,		--是否显示停用 1.显示停用 0.不显示停用
    @standard	varchar(200),		--商品规格
	@type		varchar(200),		--商品型号
	@name		varchar(200),		--商品简名
	@pycode		varchar(500),		--商品拼音码
	@area		varchar(200),		--商品产地
	@VpathVisible INT		,		--商品路径是否显示
	@StopBuy VARCHAR(50),			--停止采购
	@StopUse VARCHAR(50),			--停用,
	@customitemfrom [VARCHAR](20)='',--自由项
	@customitemrefid [VARCHAR](max)='',
	@updateCount INT = 0 OUTPUT, --修改数
	@totalCount INT = 0 OUTPUT --总条数
)
--@encode$--
AS
SET NOCOUNT ON

-----------------------------------------------------------商品结果集 查询 BEGIN--------------------------------------------
CREATE TABLE #MainType (TypeID VARCHAR(50))

DECLARE @SQLDB		VARCHAR(MAx)
DECLARE @SQLWHERE	VARCHAR(MAX)
DECLARE @dbname VARCHAR(100)
IF @KtypeID ='00000'
	SET @KtypeID=''
SELECT @SQLWHERE = ' Where [sonnum]=0 '

IF @Mode='1'
	SET @dbname='PTYPE'

CREATE TABLE #parTypeid(TypeID VARCHAR(50))
--类别查找特殊处理
IF @parentname IS NOT NULL AND @parentname<>''
BEGIN

	DECLARE @parsql VARCHAR(MAX)
	SET @parsql='
	INSERT INTO #parTypeid (typeid)
	SELECT TypeId FROM '+@dbname+'
    WHERE FullName LIKE ''%'+@parentname+'%'' 
    AND sonnum<>0
    '
   EXEC(@parsql)
    DELETE FROM #parTypeid 
    WHERE TypeID IN (	SELECT TypeID 
						FROM PType 
						WHERE ParId IN (SELECT TypeID FROM #parTypeid) 
						AND typeId IN (SELECT TypeID FROM #parTypeid))
END

INSERT INTO #MainType(typeid) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@ParID,1,@MagEType) F

DECLARE @whereDb VARCHAR(max)  =''  

					
	SELECT @SQLDB = '(	SELECT pt.*,
							 B.FullName as BFullName,
							 ROW_NUMBER() OVER (ORDER BY pt.usercode) AS rownum
						  FROM	ptype pt
						  INNER JOIN #MainType T ON T.typeid = pt.typeid
						  LEFT  JOIN QP_PType_Ext Q ON Q.PTypeID=pt.typeId
						  LEFT  JOIN BType        B ON Q.BTypeID=B.typeId
						  WHERE	pt.[sonnum]=0 
					'
	IF	@UserCode <> ''
		SET @whereDb+='	AND pt.UserCode LIKE ''%'+@UserCode+'%'' '
							  
	IF	@FullName <> ''
		SET @whereDb+='	AND pt.FullName LIKE ''%'+@FullName+'%'' '
							  
	IF	@standard <> ''
		SET @whereDb+='	AND pt.[standard] LIKE ''%'+@standard+'%'' '
							  
	IF	@type <> ''
		SET @whereDb+='	AND pt.[type]		LIKE ''%'+@type+'%'' '
	
	IF	@name <> ''
		SET @whereDb+='	AND pt.name		LIKE ''%'+@name+'%'' '
		
	IF	@pycode <> ''
		SET @whereDb+='	AND pt.pycode		LIKE ''%'+@pycode+'%'' '
					  
	IF	@area <> ''
		SET @whereDb+='	AND pt.area		LIKE ''%'+@area+'%'' '	
		
	/*是否停止采购--开始*/
	IF	@stopbuy ='stopbuyyes'
		SET @whereDb+='	AND pt.stopbuy=1'
	IF	@stopbuy ='stopbuyno'
		SET @whereDb+='	AND pt.stopbuy=0'
	/*是否停止采购--结束*/

	/*是否停用--开始*/
	IF @stopuse='stopuseyes'
		SET @whereDb+='	AND pt.deleted=1'
	IF @stopuse='stopuseno'
		SET @whereDb+='	AND pt.deleted=0'
	IF @stopuse='stopuseall' 
	BEGIN
		IF @ifdeleted=0
			SET @whereDb+='	AND pt.deleted=0'
	END
	/*是否停用--结束*/

	IF @parentname<>''
		SET @whereDb+='	AND EXISTS (SELECT TypeID FROM #parTypeid par WHERE LEFT(Pt.ParId,LEN(PAR.TYPEID))=PAR.TypeID) '
	
	IF @EntryCode <>''
		SET @whereDb+='	AND (pt.EntryCode LIKE ''%'+@EntryCode+'%'' OR  EXISTS (SELECT 1 FROM PType_Units_Ext UE WHERE PT.TYPEID=UE.PTYPEID AND UE.EntryCode LIKE ''%'+@EntryCode+'%'')) ' 
							
	   
	SELECT @SQLDB=@SQLDB+@whereDb
	
	SET @SQLDB+='				  
					  ) p '
	  
	
	IF @ParID ='00000'
		SET @ParID =''
	
	--商品查询集合
	CREATE TABLE #PTypeTemp(
			[typeId] [varchar](50)	,				--商品ID
			[PARId] [varchar](50)	,				--商品ID
            [FullName] [varchar](200),				--商品全名
            [Name] [varchar](200),					--商品简名
            [EntryCode] [varchar](200),				--商品条码
            [Standard] [varchar](200),				--商品规格
            [Type] [varchar](200),					--商品型号
            [PyCode] [varchar](500),				--商品拼音码
            [Area] [varchar](200),					--商品产地
            [Comment] [varchar](250),				--商品备注
            [SerialCount] [int] ,					--序列号位数
            [UsefulLifeDay] [smallint],				--有效期（天）
            IfUseEntryCode bit,						--启用条码
            IfUseGoodsNum bit,						--批号管理
            [IsService] INT,						--服务商品
            iscombinationproduct INT,				--组合品
            [IfSerial] [char](1),					--强制序列号管理
            BaseUnitId  INT ,						--基本计量单位
            SaleUnitId  INT,						--销售默认单位
            BuyUnitId   INT,						--采购默认单位
            StockUnitId INT,						--存货默认单位
            --KtypeId,								--默认仓库
            --InventoryType,						--存货类型
			--XXXXX,								---电子称计量
			StopBuy INT,							--停止采购
			[deleted] [bit]	,						--停用
			rownum INT,
			othercomment1	VARCHAR(500),			--备注1
			othercomment2	VARCHAR(500),			--备注2
			othercomment3	VARCHAR(500),			--备注3
			othercomment4	VARCHAR(500),			--备注4
			othercomment5	VARCHAR(500)				--备注5
            
		)

DECLARE @SELTEXT VARCHAR(8000)

		SET @selText=' INSERT INTO #PTypeTemp ( typeId,PARId,FullName,Name,EntryCode,Standard,Type,PyCode,Area,
												Comment,SerialCount,UsefulLifeDay,IfUseEntryCode,IfUseGoodsNum,IsService,iscombinationproduct,
												IfSerial,BaseUnitId,SaleUnitId,BuyUnitId,StockUnitId,StopBuy,deleted,rownum,othercomment1,othercomment2,
												othercomment3,othercomment4,othercomment5)
												
										SELECT  distinct typeId,PARId,FullName,Name,EntryCode,Standard,Type,PyCode,Area,
												Comment,SerialCount,UsefulLifeDay,IfUseEntryCode,IfUseGoodsNum,IsService,iscombinationproduct,
												IfSerial,BaseUnitId,SaleUnitId,BuyUnitId,StockUnitId,StopBuy,deleted,ROW_NUMBER() OVER (ORDER BY typeId) AS rownum,othercomment1,othercomment2,othercomment3,othercomment4,othercomment5	
								
										 FROM '	+ @SQLDB
exec(@seltext) 
-----------------------------------------------------------商品结果集 查询 END--------------------------------------------
DECLARE @MAXRowCNT int,@ROWCNT INT=1
SELECT @MAXRowCNT=MAX([rownum]) FROM #PTypeTemp 
SET @totalCount = @MAXRowCNT
DECLARE @TEMPTYPEID VARCHAR(50)
DECLARE @ResultCount INT --返回子脚本修改数
DECLARE @AllCount INT --返回子脚本总数
-----------------------------------------------------------商品 批量修改 BEGIN--------------------------------------------

DECLARE @SQL VARCHAR(max)=''
DECLARE @TempSQL NVARCHAR(1000),@TempFieldValue VARCHAR(max)
--商品全名
IF @FieldName = 'FullName'
	BEGIN			
		--商品不允许同名,商品名称不为空
		IF  EXISTS(SELECT VALUE FROM USERCONFIG WHERE LOWER(CONFIGNAME)='equalproname' AND VALUE=0 )
			BEGIN														
				SET @ROWCNT =1
				WHILE @ROWCNT<=@MAXRowCNT
					BEGIN
						SET @SQL=''
						SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT
						
						IF  @IfTextFirst=1
							BEGIN
								SET @SQL ='UPDATE PTYPE SET FULLNAME=CASE WHEN ISNULL (SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200),'''')<>''''
																			THEN SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200)
																			ELSE FULLNAME
																			END ,
										Pycode=CASE WHEN ISNULL (SUBSTRING(dbo.fun_getPY('''+ @FieldText+'''+'+@FieldValue+'),1,500),'''')<>''''
														THEN SUBSTRING(dbo.fun_getPY('''+ @FieldText+'''+'+@FieldValue+'),1,500)
														ELSE Pycode
														END
										WHERE TYPEID =''' +@TEMPTYPEID+''' 
										AND NOT EXISTS (SELECT FULLNAME  FROM PTYPE WHERE FULLNAME= (SELECT SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200) FROM PTYPE WHERE TYPEID=''' +@TEMPTYPEID+''' )
																				  AND  TYPEID <> '''+ @TEMPTYPEID+ ''')'										
								EXEC (@SQL) 
								SET @updateCount = @updateCount + @@ROWCOUNT		
							END
						ELSE IF  @IfTextFirst=0 
							BEGIN
								SET @SQL ='UPDATE PTYPE SET FULLNAME= CASE WHEN ISNULL (SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,200),'''')<>''''
																				THEN SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,200)
																				ELSE FULLNAME
																				END ,
										   Pycode= CASE WHEN ISNULL (SUBSTRING(dbo.fun_getPY('+ @FieldValue+'+'''+@FieldText+'''),1,500),'''')<>''''
															THEN SUBSTRING(dbo.fun_getPY('+ @FieldValue+'+'''+@FieldText+'''),1,500)
															ELSE Pycode
															END
										    WHERE TYPEID =''' +@TEMPTYPEID+''' 
										   AND NOT EXISTS (SELECT FULLNAME   PTYPE WHERE FULLNAME= (SELECT  SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,200)  FROM PTYPE WHERE TYPEID=''' +@TEMPTYPEID+''' )
																				AND  TYPEID <> '''+ @TEMPTYPEID+ ''')'
								EXEC (@SQL) 	
								SET @updateCount = @updateCount + @@ROWCOUNT			
							END
						SET @ROWCNT=@ROWCNT+1;
						
					END
			END	
		ELSE 
			BEGIN--商品名称不为空
				IF @IfTextFirst=1
					SET @SQL='UPDATE PTYPE SET FULLNAME=  CASE WHEN ISNULL (SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200),'''')<>''''
																		THEN SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200)
																		ELSE  FULLNAME
																		END,
											Pycode=CASE WHEN ISNULL(SUBSTRING(dbo.fun_getPY('''+ @FieldText+'''+'+@FieldValue+'),1,500) ,'''')<>''''
														THEN SUBSTRING(dbo.fun_getPY('''+ @FieldText+'''+'+@FieldValue+'),1,500)
														ELSE Pycode 
														END
											WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp )'
							
				ELSE 
					SET @SQL='UPDATE PTYPE SET FULLNAME= CASE WHEN ISNULL (SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,200),'''')<>''''
																	THEN SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,200)
																	ELSE FULLNAME
																	END ,
										   Pycode=CASE WHEN ISNULL(SUBSTRING(dbo.fun_getPY('+ @FieldValue+'+'''+@FieldText+'''),1,500) ,'''')<>''''
														THEN SUBSTRING(dbo.fun_getPY('+ @FieldValue+'+'''+@FieldText+'''),1,500)
														ELSE Pycode
														END
										   WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp )'
										   
				IF 	@SQL<>''
				EXEC (@SQL) 
				SET @updateCount = @@ROWCOUNT
				--print 	@SQL					   
			END	
		
												 
	END
ELSE IF @FieldName IN ('Name','Standard','Type','Area')
	BEGIN
		IF @IfTextFirst=1
			SET @SQL='UPDATE PTYPE SET '+@FieldName+'= SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200) 			
						WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp )'
		ELSE 
			SET @SQL='UPDATE PTYPE SET '+@FieldName+'= SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,200) 
						WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) '
		IF 	@SQL<>''
			EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT					
	END
	
ELSE IF @FieldName ='Pycode'
	BEGIN
		IF @IfTextFirst=1
			SET @SQL='UPDATE PTYPE SET Pycode=SUBSTRING(dbo.fun_getPY('''+ @FieldText+'''+'+@FieldValue+'),1,500)			
						WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) '
		ELSE 
			SET @SQL='UPDATE PTYPE SET Pycode=SUBSTRING(dbo.fun_getPY('+ @FieldValue+'+'''+@FieldText+'''),1,500)
						WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp )'
		IF 	@SQL<>''
			EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT
	END

ELSE IF @FieldName ='Comment'
	BEGIN
		IF @IfTextFirst=1
			SET @SQL='UPDATE PTYPE SET Comment=SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200) 			
						WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) '
		ELSE 
			SET @SQL='UPDATE PTYPE SET Comment=SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,250) 
						WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp )'
						
		IF 	@SQL<>''
			EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT
	END
ELSE IF @FieldName ='othercomment1'
	BEGIN
		SET @SQL='UPDATE PTYPE SET othercomment1=SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,250) 			
					WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) '
						
		IF 	@SQL<>''
			EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT
	END	
ELSE IF @FieldName ='othercomment2'
	BEGIN
		SET @SQL='UPDATE PTYPE SET othercomment2=SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,250) 			
					WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) '
						
		IF 	@SQL<>''
			EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT
	END	
ELSE IF @FieldName ='othercomment3'
	BEGIN
		SET @SQL='UPDATE PTYPE SET othercomment3=SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,250) 			
					WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) '
						
		IF 	@SQL<>''
			EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT
	END
ELSE IF @FieldName ='othercomment4'
	BEGIN
		SET @SQL='UPDATE PTYPE SET othercomment4=SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,250) 			
					WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) '
						
		IF 	@SQL<>''
			EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT
	END
ELSE IF @FieldName ='othercomment5'
	BEGIN
		SET @SQL='UPDATE PTYPE SET othercomment5=SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,250) 			
					WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) '
						
		IF 	@SQL<>''
			EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT
	END							
ELSE IF @FieldName = 'EntryCode'
	BEGIN	
		DELETE #PTypeTemp WHERE IfUseEntryCode=0
		
		---条码不允许重复
		IF  EXISTS(SELECT VALUE FROM USERCONFIG WHERE LOWER(CONFIGNAME)='equalentrycode' AND VALUE=0 )
			BEGIN
				IF @IfTextFirst=1 
				BEGIN
				
					SET @SQL='	UPDATE #PTYPETEMP SET ENTRYCODE =SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200);
								DELETE	#PTYPETEMP FROM #PTYPETEMP P1  WHERE ISNULL(P1.ENTRYCODE,'''') ='''' AND NOT EXISTS (SELECT P.ENTRYCODE FROM PType_Units_Ext P WHERE P1.TYPEID=P.PTYPEID AND ISNULL(P.ENTRYCODE,'''') <>'''');
								DELETE  FROM  #PTYPETEMP  WHERE ENTRYCODE IN (SELECT ENTRYCODE FROM #PTYPETEMP GROUP BY ENTRYCODE HAVING COUNT(ENTRYCODE)>1) and ROWNUM NOT IN (SELECT MIN(ROWNUM) FROM  #PTYPETEMP GROUP BY ENTRYCODE HAVING COUNT(ENTRYCODE)>1);
								DELETE  FROM  #PTYPETEMP  WHERE TYPEID IN (select u.typeid from #PTYPETEMP u where u.entrycode IN (select entrycode from ptype p where p.entrycode = u.entrycode ) );
								DELETE  FROM  #PTYPETEMP  WHERE TYPEID IN (select u.typeid from #PTYPETEMP  u where u.entrycode IN  (select entrycode from PType_Units_Ext p where p.entrycode = u.entrycode ));
								UPDATE PType_EntryCode_Ext SET ENTRYCODE = PT.ENTRYCODE FROM PType_EntryCode_Ext P INNER JOIN #PTYPETEMP PT ON  PT.TYPEID=P.PTYPEID AND P.IsDefaultEntryCode = 1;
								UPDATE PTYPE SET ENTRYCODE =PT.ENTRYCODE FROM PTYPE P INNER JOIN #PTYPETEMP PT ON  PT.TYPEID=P.TYPEID ;'
					EXEC(@SQL)	
					SET @updateCount = @@ROWCOUNT
				END
				ELSE
				BEGIN
						SET @SQL='	UPDATE #PTYPETEMP SET ENTRYCODE =SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,200);
									DELETE	#PTYPETEMP FROM #PTYPETEMP P1  WHERE ISNULL(P1.ENTRYCODE,'''') ='''' AND NOT EXISTS (SELECT P.ENTRYCODE FROM PType_Units_Ext P WHERE P1.TYPEID=P.PTYPEID AND ISNULL(P.ENTRYCODE,'''') <>'''');
									DELETE  FROM  #PTYPETEMP WHERE ENTRYCODE IN (SELECT ENTRYCODE FROM #PTYPETEMP GROUP BY ENTRYCODE HAVING COUNT(ENTRYCODE)>1) and ROWNUM NOT IN (SELECT MIN(ROWNUM) FROM  #PTYPETEMP GROUP BY ENTRYCODE HAVING COUNT(ENTRYCODE)>1);
									DELETE  FROM  #PTYPETEMP  WHERE TYPEID IN (select u.typeid from #PTYPETEMP u where u.entrycode IN (select entrycode from ptype p where p.entrycode = u.entrycode ) and u.entrycode <>'''');
									DELETE  FROM  #PTYPETEMP  WHERE TYPEID IN (select u.typeid from #PTYPETEMP  u where u.entrycode IN  (select entrycode from PType_Units_Ext p where p.entrycode = u.entrycode ) and u.entrycode <>'''');
									UPDATE PType_EntryCode_Ext SET ENTRYCODE = PT.ENTRYCODE FROM PType_EntryCode_Ext P INNER JOIN #PTYPETEMP PT ON  PT.TYPEID=P.PTYPEID AND P.IsDefaultEntryCode = 1;
									UPDATE PTYPE SET ENTRYCODE =PT.ENTRYCODE FROM PTYPE P INNER JOIN #PTYPETEMP PT ON  PT.TYPEID=P.TYPEID ;				'
					EXEC(@SQL)
					SET @updateCount = @@ROWCOUNT
				END
							
			END
		ELSE
		BEGIN
			IF @IfTextFirst=1
			SET @SQL='	UPDATE #PTYPETEMP SET ENTRYCODE =SUBSTRING(('''+ @FieldText+'''+'+@FieldValue+'),1,200);
						DELETE	#PTYPETEMP FROM #PTYPETEMP P1  WHERE ISNULL(P1.ENTRYCODE,'''') ='''' AND NOT EXISTS (SELECT P.ENTRYCODE FROM PType_Units_Ext P WHERE P1.TYPEID=P.PTYPEID AND ISNULL(P.ENTRYCODE,'''') <>'''');
						DELETE  FROM  #PTYPETEMP  WHERE TYPEID IN (select u.typeid from #PTYPETEMP  u where u.entrycode IN  (select entrycode from PType_Units_Ext p where p.entrycode = u.entrycode ) and u.entrycode <>'''');
						UPDATE PTYPE SET ENTRYCODE =PT.ENTRYCODE FROM PTYPE P INNER JOIN #PTYPETEMP PT ON  PT.TYPEID=P.TYPEID ;'
		ELSE 
			SET @SQL='	UPDATE #PTYPETEMP SET EntryCode= SUBSTRING(('+ @FieldValue+'+'''+@FieldText+'''),1,200)	;
						DELETE	#PTYPETEMP FROM #PTYPETEMP P1  WHERE ISNULL(P1.ENTRYCODE,'''') ='''' AND NOT EXISTS (SELECT P.ENTRYCODE FROM PType_Units_Ext P WHERE P1.TYPEID=P.PTYPEID AND ISNULL(P.ENTRYCODE,'''') <>'''');			  
						DELETE  FROM  #PTYPETEMP  WHERE TYPEID IN (select u.typeid from #PTYPETEMP  u where u.entrycode IN  (select entrycode from PType_Units_Ext p where p.entrycode = u.entrycode ) and u.entrycode <>'''');
						UPDATE PTYPE SET ENTRYCODE =PT.ENTRYCODE FROM PTYPE P INNER JOIN #PTYPETEMP PT ON  PT.TYPEID=P.TYPEID ;'
		IF 	@SQL<>''
		EXEC (@SQL) 
		SET @updateCount = @@ROWCOUNT	
		END					 
	END			
--序列号位数(组合品不允许修改) 有效期（天） 
ELSE IF @FieldName in ('SerialCount','UseFullifeDay')
	BEGIN
		IF @FieldName='SerialCount'
		BEGIN		
			UPDATE PTYPE SET SerialCount=CONVERT(INT,@FieldText) WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) AND IfSerial=1  and iscombinationproduct=0			
			SET @updateCount = @@ROWCOUNT
		END
			
		IF @FieldName='UseFullifeDay'	
		BEGIN		
			UPDATE PTYPE SET UseFullifeDay=CONVERT(smallint,@FieldText) WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp )			
			SET @updateCount = @@ROWCOUNT
		END
	END
	
---启用条码
ELSE IF @FieldName ='IfUseEntryCode' AND CONVERT (INT,@FieldValue)=1
	BEGIN
		SET @ROWCNT =1
		WHILE @ROWCNT<=@MAXRowCNT
			BEGIN
				SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT
				EXEC GP_BatchSetEntryCode @operateid, @TEMPTYPEID,@AllCount OUT,@ResultCount OUT
				SET @updateCount = @updateCount + @ResultCount
				SET @ROWCNT=@ROWCNT+1;
			END
	END
		
---取消启用条码
ELSE IF @FieldName ='IfUseEntryCode' AND CONVERT (INT,@FieldValue)=0
	BEGIN
		UPDATE PType SET IfUseEntryCode=0,EntryCode='' WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) AND IfUseEntryCode=1
		SET @updateCount = @@ROWCOUNT
		UPDATE PType_Units_Ext SET EntryCode='' WHERE PTYPEID IN (SELECT TYPEID FROM #PTypeTemp )
		DELETE FROM dbo.PType_EntryCode_Ext WHERE Ptypeid IN (SELECT TYPEID FROM #PTypeTemp )
		DELETE FROM dbo.PType_Units_EntryCode_Ext WHERE PtypeID IN (SELECT TYPEID FROM #PTypeTemp )
	END
	
---启用批号管理
ELSE IF @FieldName ='IfUseGoodsNum' AND CONVERT (INT,@FieldValue)=1
	BEGIN
		DECLARE @TYPEIDTEMP VARCHAR(MAX)
		SELECT  @TYPEIDTEMP=ISNULL(@TYPEIDTEMP +',','') + ISNULL (TYPEID,'') FROM #PTypeTemp
		IF @TYPEIDTEMP<>''
		BEGIN
			EXEC GP_BatchSetGoodsNumBer @operateid, @TYPEIDTEMP,@AllCount OUT,@ResultCount OUT
			SET @updateCount = @ResultCount
		END
	END
		
---取消启用批号管理
ELSE IF @FieldName ='IfUseGoodsNum' AND CONVERT (BIT,@FieldValue)=0
	BEGIN
		SET @ROWCNT =1
		WHILE @ROWCNT<=@MAXRowCNT
			BEGIN
				SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT
				---检测商品有没有使用过
				DECLARE @inReturnValue INT
				IF @TEMPTYPEID<>''
					EXEC Gp_IsUsedProduct @TEMPTYPEID,@inReturnValue OUT
				IF @inReturnValue =1
				BEGIN
					SET @ROWCNT=@ROWCNT+1;
					CONTINUE;
				END
				
				IF @inReturnValue <>1 --商品未使用过 非组合品
				    BEGIN
				    	UPDATE PType SET IfUseGoodsNum=0 WHERE TypeID=@TEMPTYPEID AND IfUseGoodsNum=1 and iscombinationproduct=0
						SET @updateCount = @updateCount + @@ROWCOUNT
				    END
				SET @ROWCNT=@ROWCNT+1;
			END
	END
	
---启用服务商品
ELSE IF @FieldName ='IsService' AND CONVERT (INT,@FieldValue)=1
	BEGIN
		---系统启用服务商品（批量修改界面已控制）
		---服务商品要求继承父类，则非第一层商品，服务商品选项不可编辑
		DELETE FROM #PTypeTemp  WHERE PARID<>'00000' OR len(TypeId)<>5
		SET  @inReturnValue = 0
		SET @ROWCNT =1
		WHILE @ROWCNT<=@MAXRowCNT
		BEGIN
			SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT 
			IF ISNULL(@TEMPTYPEID,'')<>''
			BEGIN 
			EXEC Gp_IsUsedProduct @TEMPTYPEID,@inReturnValue OUT
			IF(@inReturnValue = 0)--使用过的商品不允许修改
				BEGIN 
					UPDATE PType SET IsService=1,SerialCount=0,IfUseGoodsNum=0 WHERE  TYPEID =@TEMPTYPEID AND IsService=0  and iscombinationproduct=0
					IF EXISTS(SELECT SUBVALUE FROM SYSDATA WHERE LOWER(SUBNAME)='isfreeitem' AND SUBVALUE=1 )
						UPDATE PType SET CUSTOMITEMID = NULL,CUSTOMITEMFROM = NULL ,CUSTOMITEMNAME = NULL ,CUSTOMITEMREFID = NULL WHERE TYPEID = @TEMPTYPEID AND IsService=1 

					--清空该商品ID下的默认仓库(A8/V3 这里不考虑分支机构)
					DELETE FROM DefaultStock WHERE  PTYPEID = @TEMPTYPEID
		
					--将存货类型置为库存商品
					UPDATE ptype set InventoryTypeID =(select nid from Base_InventoryType where fullname='库存商品') where typeid = @TEMPTYPEID
				SET @updateCount = @updateCount + @@ROWCOUNT			
				END 
			END 				
			SET @ROWCNT=@ROWCNT+1;
		END 
		-----系统启用服务商品（批量修改界面已控制）
		-----服务商品要求继承父类，则非第一层商品，服务商品选项不可编辑
		--DELETE FROM #PTypeTemp  WHERE PARID<>'00000' OR len(TypeId)<>5
		--UPDATE PType SET IsService=1,SerialCount=0,IfUseGoodsNum=0 WHERE  TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) AND IsService=0  and iscombinationproduct=0

		----如果启用服务商品，系统自由项配置启用，清空自由项内容
		--IF EXISTS(SELECT SUBVALUE FROM SYSDATA WHERE LOWER(SUBNAME)='isfreeitem' AND SUBVALUE=1 )
		--UPDATE PType SET CUSTOMITEMID = NULL,CUSTOMITEMFROM = NULL ,CUSTOMITEMNAME = NULL ,CUSTOMITEMREFID = NULL WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp ) AND IsService=1 

		----清空该商品ID下的默认仓库(A8/V3 这里不考虑分支机构)
		--DELETE FROM DefaultStock WHERE  PTYPEID IN (SELECT TYPEID FROM #PTypeTemp )
		
		----将存货类型置为库存商品
		--update ptype set InventoryTypeID =(select nid from Base_InventoryType where fullname='库存商品') where typeid in (SELECT TYPEID FROM #PTypeTemp )
	END
	
---取消启用服务商品
ELSE IF @FieldName ='IsService' AND CONVERT (INT,@FieldValue)=0
	BEGIN
		SET  @inReturnValue = 0
		SET @ROWCNT =1
		WHILE @ROWCNT<=@MAXRowCNT
		BEGIN
			SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT 
			IF ISNULL(@TEMPTYPEID,'')<>''
			BEGIN 
				EXEC Gp_IsUsedProduct @TEMPTYPEID,@inReturnValue OUT
				IF(@inReturnValue = 0)--使用过的商品不允许修改
					BEGIN 
						DELETE FROM #PTypeTemp  WHERE PARID<>'00000' OR len(TypeId)<>5 
						UPDATE PType SET IsService=0 WHERE  TYPEID =@TEMPTYPEID AND IsService=1 
						SET @updateCount = @updateCount + @@ROWCOUNT
					END 
			END 				
			SET @ROWCNT=@ROWCNT+1;
		END 
	END 

---启用强制序列号
ELSE IF @FieldName ='IfSerial' AND CONVERT (INT,@FieldValue)=1
	BEGIN
		DECLARE @re_check INT
		EXEC @re_check=GP_CheckLimit @operateid,5164	--@re_check = 0 有权限  1.无权限		

		--已开账，非超级用户 不能修改序列号 不能启用强制序列号管理
		IF EXISTS(SELECT SUBVALUE FROM SYSDATA WHERE LOWER(SUBNAME)='inicanmodify' AND SUBVALUE='F') and @re_check <> 0 --@operateid<>'00001'
		RETURN;
		
		--已经有已过账的单据，不能启用强制序列号管理
		DELETE FROM #PTypeTemp WHERE TYPEID IN (SELECT a.PtypeId  FROM dbo.InOutstocktable a INNER JOIN dbo.BillIndex b ON a.BillNumberId=b.BillNumberId WHERE  b.RedWord=0)
		--检查是否序列号版本（通迅行业 或 电脑行业 或 DC）
		IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[a8ztinfo]') AND type in (N'U') )
			BEGIN 
				IF EXISTS ( SELECT a.*,b.* from SYSDATA a,SYSDATA1 b
							WHERE (lower(a.subName)='edition' and a.subvalue='2' and (lower(b.subName)='offline' and b.subvalue in ('4','5') ) ) 
							OR    (lower(a.subName)='edition' and a.subvalue='5' and (lower(b.subName)='offline' and b.subvalue in ('6','7') ) ) 
							OR    (lower(a.subName)='edition' and a.subvalue='8' and (lower(b.subName)='offline' and b.subvalue in ('10','11') ) ) 
				)
				BEGIN
					DECLARE @TYPEIDTEMP1 VARCHAR(MAX)
					SELECT  @TYPEIDTEMP1=ISNULL(@TYPEIDTEMP1 +',','') + ISNULL (TYPEID,'') FROM #PTypeTemp
					IF @TYPEIDTEMP1<>''
						EXEC GP_BatchSetSetSerial @operateid,@TYPEIDTEMP1,@AllCount OUT,@ResultCount OUT
					SET @updateCount = @ResultCount
				END
			END 
		ELSE IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[v3ztinfo]') AND type in (N'U') )
			BEGIN
				IF EXISTS ( SELECT a.*,b.* from SYSDATA a,SYSDATA1 b
								WHERE (lower(a.subName)='edition' and a.subvalue='2' and (lower(b.subName)='offline' and b.subvalue in ('4','5') ) ) 
								OR    (lower(a.subName)='edition' and a.subvalue='5' and (lower(b.subName)='offline' and b.subvalue in ('4','5') ) ) 
								OR    (lower(a.subName)='edition' and a.subvalue='8' and (lower(b.subName)='offline' and b.subvalue in ('10','11') ) ) 
				)
				BEGIN
					DECLARE @TYPEIDTEMP2 VARCHAR(MAX)
					SELECT  @TYPEIDTEMP2=ISNULL(@TYPEIDTEMP2 +',','') + ISNULL (TYPEID,'') FROM #PTypeTemp
					IF @TYPEIDTEMP2<>''
						EXEC GP_BatchSetSetSerial @operateid,@TYPEIDTEMP2,OUT,@ResultCount OUT
					SET @updateCount = @ResultCount
				END
			END

	END
	
---取消启用强制序列号
ELSE IF @FieldName ='IfSerial' AND CONVERT (INT,@FieldValue)=0
	BEGIN
		DELETE FROM #PTypeTemp WHERE IfSerial=0
		UPDATE  PType SET IfSerial=0,SerialCount=NULL WHERE TypeID IN (SELECT TYPEID FROM #PTypeTemp)
		SET @updateCount = @@ROWCOUNT
		--强制管理才删除
		IF EXISTS(SELECT SUBVALUE FROM SYSDATA WHERE LOWER(SUBNAME)='mngserial' AND SUBVALUE=1 )
			BEGIN
			   Delete From gp_initPtypeSerial where ptypeid=(SELECT TYPEID FROM #PTypeTemp)
			   Delete From gp_CruPtypeSerial where ptypeid=(SELECT TYPEID FROM #PTypeTemp)
			   Delete From gp_initLendPtypeSerial where ptypeid=(SELECT TYPEID FROM #PTypeTemp)
			   Delete From gp_LendPtypeSerial where ptypeid=(SELECT TYPEID FROM #PTypeTemp)
			   Delete From Gp_InOutPTypeSerial where ptypeid=(SELECT TYPEID FROM #PTypeTemp)
			END	
	END
	
--基本单位
ELSE IF @FieldName ='BaseUnitId' 
	BEGIN
		DELETE #PTypeTemp WHERE TYPEID IN (SELECT PTYPEID FROM PriceTrack T WHERE  UID=CONVERT(INT,@FieldValue))----价格跟踪
	
		SET @ROWCNT =1
		WHILE @ROWCNT<=@MAXRowCNT
			BEGIN
				SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT
				IF ISNULL(@TEMPTYPEID,'')=''
				BEGIN
					SET @ROWCNT=@ROWCNT+1
					CONTINUE;
				END
				ELSE
				BEGIN
					---检测商品有没有使用过
					DECLARE @inReturnValue1 INT
					EXEC Gp_IsUsedProduct @TEMPTYPEID,@inReturnValue1 OUT
					IF  @inReturnValue1=1 --商品使用过 
						DELETE  FROM #PTypeTemp WHERE TypeId=@TEMPTYPEID	
				END	
				SET @ROWCNT=@ROWCNT+1
		END
		--如果系统多单位配置未启用 更改基本计量单位后，对应的销售默认单位、采购默认单位、存货默认单位都要更改为本次所修改的基本计量单位
		IF EXISTS(SELECT CONFIGNAME FROM USERCONFIG WHERE LOWER(CONFIGNAME)='doubleunit' AND VALUE=0 )
			BEGIN
				UPDATE PTYPE SET BaseUnitId=CONVERT(INT,@FieldValue),SaleUnitId=CONVERT(INT,@FieldValue),
								BuyUnitId=CONVERT(INT,@FieldValue),StockUnitId=CONVERT(INT,@FieldValue) 
								WHERE TYPEID IN (SELECT TYPEID FROM #PTYPETEMP)
				SET @updateCount = @@ROWCOUNT		
				DELETE PType_Units_Ext where PtypeID IN (SELECT TYPEID FROM #PTYPETEMP)
				INSERT  PType_Units_Ext (PtypeID,UnitsId,RateType,Rate,EntryCode,IsDefaultUnit,IsUse)  
				SELECT	TypeId, CONVERT(INT,@FieldValue), 0, 1, '', 1,1
				FROM #PTYPETEMP
				
				--修改商品多条码的单位
				UPDATE dbo.PType_Units_EntryCode_Ext SET UnitsId = CONVERT(INT,@FieldValue) WHERE PtypeID IN (SELECT TYPEID FROM #PTYPETEMP)
				
				SELECT	TypeId, CONVERT(INT,@FieldValue), 0, 1, '', 1,1
				FROM #PTYPETEMP
				UPDATE PTYPE_PRICE SET UNITID=CONVERT(INT,@FieldValue) WHERE PTYPEID  IN (SELECT TYPEID FROM #PTYPETEMP) AND IsDefaultUnit=1
				UPDATE PType_STypePrice SET UNITID=CONVERT(INT,@FieldValue) WHERE PTYPEID  IN (SELECT TYPEID FROM #PTYPETEMP) AND IsDefaultUnit=1  
			END
		--启用了多单位的情况下，更改基本计量单位时，更改基本计量单位和多单位表里默认基本单位的单位名称。
		--销售默认单位、采购默认单位、存货默认单位】有默认的是基本计量单位的，也同时更改为本次所修改的基本计量单位
		ELSE 
			BEGIN 
				--多单位 如果包含了新单位 则不允许更新 比如  xx(原基本单位),xx1  ，不允许 更新到xx1
				DELETE #PTYPETEMP FROM #PTYPETEMP PT INNER JOIN PType_Units_Ext EX ON PT.TYPEID= EX.PTYPEID 
									WHERE (EX.UnitsId=CONVERT(INT,@FieldValue)) 
			    
			    --修改多条码的单位
			    UPDATE dbo.PType_Units_EntryCode_Ext SET UnitsId = CONVERT(INT,@FieldValue) WHERE PtypeID IN (SELECT TYPEID FROM #PTYPETEMP)
			    AND UnitsId IN (SELECT UnitsId FROM dbo.PType_Units_Ext WHERE IsDefaultUnit = 1)
			     
				UPDATE PType_Units_Ext SET UnitsId=CONVERT(INT,@FieldValue) WHERE PTYPEID  IN (SELECT TYPEID FROM #PTYPETEMP) AND IsDefaultUnit=1 
				
				UPDATE PTYPE_PRICE SET UNITID=CONVERT(INT,@FieldValue) WHERE PTYPEID  IN (SELECT TYPEID FROM #PTYPETEMP) AND IsDefaultUnit=1 
				
				UPDATE PType_STypePrice SET UNITID=CONVERT(INT,@FieldValue) WHERE PTYPEID  IN (SELECT TYPEID FROM #PTYPETEMP) AND IsDefaultUnit=1 
				
				UPDATE PTYPE SET BaseUnitId=CONVERT(INT,@FieldValue),
								SaleUnitId=(CASE WHEN SaleUnitId= BaseUnitId
												 THEN CONVERT(INT,@FieldValue)
												 ELSE SaleUnitId
												 END),
								BuyUnitId=(CASE WHEN BuyUnitId= BaseUnitId
												 THEN CONVERT(INT,@FieldValue)
												 ELSE BuyUnitId
												 END),
								StockUnitId=(CASE WHEN StockUnitId=BaseUnitId
												 THEN CONVERT(INT,@FieldValue)
												 ELSE StockUnitId
												 END)
								WHERE TYPEID IN (SELECT TYPEID FROM #PTYPETEMP)
				SET @updateCount = @@ROWCOUNT
				--自定义辅助单位 如果已有新单位 则不允许更新 			
				DELETE #PTYPETEMP FROM	#PTYPETEMP PT 
									INNER JOIN PType_AuxiliaryUnits_Ext PE ON PT.TYPEID=PE.PTYPEID 
									WHERE PE.SaleUnitID1 =CONVERT(INT,@FieldValue) 
									OR PE.SaleUnitID2 =CONVERT(INT,@FieldValue) 
									OR PE.SaleUnitID3 =CONVERT(INT,@FieldValue) 
								
				UPDATE PType_AuxiliaryUnits_Ext SET SaleUnitID1=(CASE WHEN SaleUnitID1= PT.BaseUnitId
																	 THEN CONVERT(INT,@FieldValue)
																	 ELSE SaleUnitID1
																	 END),
												 SaleUnitID2=(CASE WHEN SaleUnitID2= PT.BaseUnitId
																	 THEN CONVERT(INT,@FieldValue)
																	 ELSE SaleUnitID2
																	 END),
												 SaleUnitID3=(CASE WHEN SaleUnitID3= PT.BaseUnitId
																	 THEN CONVERT(INT,@FieldValue)
																	 ELSE SaleUnitID3
																	 END)
												FROM PType_AuxiliaryUnits_Ext PE
												INNER JOIN #PTYPETEMP PT ON PT.TYPEID=PE.PTYPEID
				
				
			END
	END
	
--销售默认单位、采购默认单位、存货默认单位
ELSE IF @FieldName IN ('SaleUnitId','BuyUnitId','StockUnitId')
	BEGIN
		SET @SQL=' UPDATE PTYPE SET '+ @FieldName+' = '+@FieldValue +' WHERE TYPEID IN (SELECT TYPEID FROM #PTYPETEMP) ';
		EXEC (@SQL)
		SET @updateCount = @@ROWCOUNT
	END
	
--默认仓库
ELSE IF @FieldName ='KtypeId'
	BEGIN
		DELETE #PTypeTemp WHERE  isservice=1
		
		IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[a8ztinfo]') AND type in (N'U') )
		BEGIN 
			--启用服务商品的 不更新
			SET @ROWCNT =1
			WHILE @ROWCNT<=@MAXRowCNT
			BEGIN
				SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT 
				IF ISNULL(@TEMPTYPEID,'')<>''
				BEGIN
					EXEC Gp_UpdateORAddDefaultStock @TEMPTYPEID,@Stypeid,@FieldValue
					SET @updateCount = @updateCount + @@ROWCOUNT
				END
				SET @ROWCNT=@ROWCNT+1;
			END 
		END
		ELSE IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[v3ztinfo]') AND type in (N'U') )
				OR EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[v1ztinfo]') AND type in (N'U') )
		BEGIN
			--启用服务商品的 不更新
			SET @ROWCNT =1
			WHILE @ROWCNT<=@MAXRowCNT
			BEGIN
				SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT 
				IF ISNULL(@TEMPTYPEID,'')<>''
				BEGIN
					EXEC Gp_UpdateORAddDefaultStock @TEMPTYPEID, '00001',@FieldValue
					SET @updateCount = @updateCount + @@ROWCOUNT
				END
				SET @ROWCNT=@ROWCNT+1;
			END 
	  END 
		--V3 默认分支机构 ‘00001’
	END
	
--存货类型
ELSE IF @FieldName ='InventoryType'
	BEGIN
		SET  @inReturnValue = 0
		--已勾选组合品 或者 服务商品的 不能修改存货类型
		DELETE #PTypeTemp WHERE isservice=1 or iscombinationproduct=1
		SET @ROWCNT =1
			WHILE @ROWCNT<=@MAXRowCNT
			BEGIN
				SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT 
				IF ISNULL(@TEMPTYPEID,'')<>''
				BEGIN 
				EXEC Gp_IsUsedProduct @TEMPTYPEID,@inReturnValue OUT
				IF(@inReturnValue = 0)--未使用过的商品才能修改存货类型
					update ptype set InventoryTypeID=@FieldValue where typeid =@TEMPTYPEID
					SET @updateCount = @updateCount + @@ROWCOUNT
				END 				
				SET @ROWCNT=@ROWCNT+1;
			END
	END
	
--停止采购
ELSE IF @FieldName ='StopBuy'
	BEGIN
		 UPDATE PTYPE SET StopBuy =CONVERT(INT, @FieldValue) WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp )
		 SET @updateCount = @@ROWCOUNT
	END
	
--商品类别	
ELSE IF @FieldName = 'ptypecategoryid'	
BEGIN
	UPDATE PType SET ptypecategoryid = CONVERT(VARCHAR(100), @FieldValue) WHERE TypeId IN (SELECT TypeId FROM #PTypeTemp )
	SET @updateCount = @@ROWCOUNT
END

--品牌名称
ELSE IF @FieldName = 'ptypebrandarid'
BEGIN
	SET @inReturnValue = 0		
	SET @Rowcnt =1	
		
	WHILE @Rowcnt<=@Maxrowcnt
	BEGIN
		SELECT @temptypeid = TypeId FROM #PTypeTemp WHERE [rownum]= @Rowcnt 
		IF ISNULL(@temptypeid,'')<>''
		BEGIN 
		EXEC @inReturnValue = Web_PTypeCheckBillUsedWhenModify @temptypeid,@FieldValue,''
		IF(@inReturnValue = 0)--未使用过的商品才能修改存货类型
			update ptype set brandartypeid=@FieldValue where typeid = @temptypeid
			SET @updateCount = @updateCount + @@ROWCOUNT
		END 				
		SET @Rowcnt=@Rowcnt+1;
	END
END

ELSE IF(@FieldName='integral')--积分兑换
BEGIN
	UPDATE PTYPE SET integral=@FieldValue WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp)	
	SET @updateCount = @@ROWCOUNT	
END

ELSE IF(@FieldName='IsCombinationProduct')--组合品 需判断
BEGIN
	SET  @inReturnValue = 0
	SET @ROWCNT =1
	WHILE @ROWCNT<=@MAXRowCNT
	BEGIN
		SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT 
		IF ISNULL(@TEMPTYPEID,'')<>''
		BEGIN 
			EXEC Gp_IsUsedProduct @TEMPTYPEID,@inReturnValue OUT
			IF(@inReturnValue = 0)--未使用过的商品才能修改存货类型
			BEGIN 
				update ptype set iscombinationproduct=@FieldValue where typeid =@TEMPTYPEID  AND IfUseGoodsNum = 0
				SET @updateCount = @updateCount + @@ROWCOUNT
			END 
		END 				
		SET @ROWCNT=@ROWCNT+1;
	END
END

ELSE IF(@FieldName='BTypeId')--供货商
BEGIN
	UPDATE QP_PType_Ext SET btypeid=@FieldValue WHERE PTypeID IN (SELECT TYPEID FROM #PTypeTemp)	
	SET @updateCount = @@ROWCOUNT
END

ELSE IF(@FieldName='CustomItemId')--自由项 需判断
BEGIN
	SET  @inReturnValue = 0
	SET @ROWCNT =1
	WHILE @ROWCNT<=@MAXRowCNT
	BEGIN
		SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT 
		IF ISNULL(@TEMPTYPEID,'')<>''
		BEGIN 
			EXEC Gp_IsUsedProduct @TEMPTYPEID,@inReturnValue OUT
			
			IF(@inReturnValue = 0)--未使用过的商品才能修改自由项
			BEGIN
				IF @FieldValue = ''
				BEGIN
					SET @FieldValue=NULL
					SET	@customitemfrom=NULL
					SET	@FieldText=NULL
					SET	@customitemrefid=NULL
				END
				UPDATE ptype 
				SET 
					CustomItemId=@FieldValue,
					customitemfrom=@customitemfrom,
					customitemname=@FieldText,
					customitemrefid=@customitemrefid
				WHERE typeid =@TEMPTYPEID
				SET @updateCount = @updateCount + @@ROWCOUNT
			END
		END 	
					
		SET @ROWCNT=@ROWCNT+1;
	END
END

ELSE IF(@FieldName='ValidDays')--近效期
BEGIN
	SET @ROWCNT =1
	WHILE @ROWCNT<=@MAXRowCNT
	BEGIN
		SELECT @TEMPTYPEID=TypeId FROM #PTypeTemp WHERE [rownum]=@ROWCNT 
		IF EXISTS(SELECT TOP 1 1 FROM ptype where typeId=@TEMPTYPEID AND usefullifeday>@FieldValue)--近效期必须小于有效期才允许更改
		BEGIN 
			UPDATE PTYPE SET ValidDays=@FieldValue WHERE TYPEID=@TEMPTYPEID
			SET @updateCount = @updateCount + @@ROWCOUNT
		END			
		SET @ROWCNT=@ROWCNT+1;
	END
END

ELSE IF(@FieldName='BuyDefaultRate')--采购默认税率值
BEGIN
	UPDATE PTYPE SET BuyDefaultRate=@FieldValue WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp)	
	SET @updateCount = @@ROWCOUNT
END

ELSE IF(@FieldName='SaleDefaultRate')--销售默认税率值
BEGIN
	UPDATE PTYPE SET SaleDefaultRate=@FieldValue WHERE TYPEID IN (SELECT TYPEID FROM #PTypeTemp)	
	SET @updateCount = @@ROWCOUNT
END

ELSE IF(@FieldName='CargoId')--默认货位
BEGIN
	IF EXISTS(SELECT * FROM SysData WHERE SubName='ProInfo' and SubValue=2)--A8
		BEGIN
			--UPDATE DefaultStock SET CargoId=@FieldValue WHERE Ptypeid IN(SELECT typeId FROM #PTypeTemp) AND Stypeid=@Stypeid AND ktypeid=@KtypeID
		    DELETE DefaultStock WHERE Ptypeid IN(SELECT typeId FROM #PTypeTemp) AND Stypeid=@Stypeid
			INSERT INTO DefaultStock(Ptypeid,Stypeid,ktypeid,CargoId)
			SELECT typeId,@Stypeid,@KtypeID,@FieldValue FROM #PTypeTemp WHERE NOT EXISTS(SELECT * FROM DefaultStock D WHERE D.Ptypeid=Ptypeid AND ktypeid=@KtypeID AND CargoId=@FieldValue AND Stypeid=@Stypeid)
			SET @updateCount = @@ROWCOUNT		
		END	
	ELSE 
		BEGIN
			--删除原纪录
			DELETE FROM DefaultStock WHERE Ptypeid IN(SELECT typeId FROM #PTypeTemp)
			
			INSERT INTO DefaultStock(Ptypeid,Stypeid,ktypeid,CargoId)
			SELECT typeId,@Stypeid,@KtypeID,@FieldValue FROM #PTypeTemp
			SET @updateCount = @@ROWCOUNT
		END
	
END
--修改缓存
DECLARE @XiWaMaxNumber INT 
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM ptype

UPDATE P set P.XiWaMaxNumber=@XiWaMaxNumber,@XiWaMaxNumber=@XiWaMaxNumber+1 
FROM ptype P
INNER JOIN #PTypeTemp T ON T.typeId=P.typeId

-----------------------------------------------------------商品 批量修改 END--------------------------------------------


drop table #MainType,#parTypeid,#PTypeTemp
			
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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


/****** Object:  StoredProcedure [dbo].[GP_PtypeCoverImport]    Script Date: 05/20/2011 17:29:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
	作 者：陈强
	日 期：2019-11-04
	描 述: 覆盖导入商品信息
*/
CREATE  PROCEDURE [dbo].[GP_PtypeCoverImport]
(
	@usercode		varchar(66),	--商品编号
    @fullname		varchar(256),	--商品名称
    @name			varchar(256),	--商品简名
    @pycode			varchar(500),	--拼音码
    @standard		varchar(500),	--规格
    @type			varchar(500),	--型号
	@area			varchar(500),	--产地
	@integral		varchar(500),   --兑换积分
	@btypeid		varchar(500),	--供应商编号
	@bfullname		varchar(500),	--供应商
	@ptypecategoryid		varchar(500),	--商品类别编号
	@categoryname			varchar(500),	--商品类别
	@brandartypeid			varchar(500),	--品牌编号
	@ptypebrandarfullname	varchar(500),	--商品品牌
	@saledefaultrate		varchar(500),	--销售默认税率值
	@buydefaultrate			varchar(500),	--采购默认税率值
	@comment				varchar(250),	--商品备注
	@othercomment1				varchar(250),	--商品备注1
	@othercomment2				varchar(250),	--商品备注2
	@othercomment3				varchar(250),	--商品备注3
	@othercomment4			varchar(250),	--商品备注4
	@othercomment5			varchar(250),	--商品备注5
	@ErrMsg			VARCHAR(200) output     --返回报错信息
	)
AS
SET NOCOUNT ON

-------------------------------------覆盖导入开始---------------------------------------------
DECLARE @newBtypeid varchar(100);			--供应商typeid
DECLARE @newPtypecatetypeid varchar(100);	--商品类别typeid
DECLARE @newBrandtypeid varchar(100);		--商品品牌typeid


IF(@usercode = '')
BEGIN
	SET @ErrMsg = '商品编号不能为空'
	RETURN -1
END

IF NOT EXISTS(select 1 from ptype where UserCode=@usercode and parid<>'root')
BEGIN
	SET @ErrMsg = '该【' + @FullName + '】商品编号有误!'
	RETURN -1
END

IF(@fullname = '')
BEGIN
	SET @ErrMsg = '商品名称不能为空'
	RETURN -1
END


--整数检查
DECLARE @ISNUM  INT 

IF ISNULL(@integral,'')<>''
BEGIN
	SELECT @ISNUM=PATINDEX('%[^0-9]%',@integral)
	IF (@ISNUM<>0)
	BEGIN
		SET @ErrMsg = '兑换积分请输入有效的数字'
		RETURN -1
	END
END
ELSE
BEGIN
	SET @integral=0
END

IF @saledefaultrate<>''
BEGIN
	SELECT @ISNUM=PATINDEX('%[^0-9]%',@saledefaultrate)
	IF (@ISNUM<>0)
	BEGIN
		SET @ErrMsg = '销售默认税率值请输入有效的整数数字(0-99)'
		RETURN -1
	END
	
	IF (@saledefaultrate >99)
	BEGIN
		SET @ErrMsg = '销售默认税率值请输入有效的整数数字(0-99)'
		RETURN -1
		
	END
END
ELSE
BEGIN
	SET @saledefaultrate=0
END

IF @buydefaultrate<>''
BEGIN
	SELECT @ISNUM=PATINDEX('%[^0-9]%',@buydefaultrate)
	IF (@ISNUM<>0)
	BEGIN
		SET @ErrMsg = '采购默认税率值请输入有效的整数数字(0-99)'
		RETURN -1
	END
	
	IF (@buydefaultrate >99)
	BEGIN
		SET @ErrMsg = '采购默认税率值请输入有效的整数数字(0-99)'
		RETURN -1
	END
END
ELSE
BEGIN
	SET @buydefaultrate=0
END


--判断供应商是否是父节点
DECLARE @sonnum int
SELECT  @sonnum=sonnum from btype where UserCode=@btypeid and LEFT(typeid,5)='00002'

IF ISNULL(@btypeid,'')<>''
BEGIN
	IF NOT Exists(select 1 from btype where UserCode=@btypeid and LEFT(typeid,5)='00002')
	BEGIN
		SET @ErrMsg = '没有此供应商!'
		RETURN -1
	END
	
	IF @sonnum<>0
	BEGIN
		SET @ErrMsg = '不能选择为父节点作为供应商!'
		RETURN -1
	END
	SELECT @newBtypeid=typeId from btype where UserCode=@btypeid
END
ELSE--供货商为空
BEGIN
	SELECT @newBtypeid=''
END

IF ISNULL(@ptypecategoryid,'')<>''
BEGIN
	IF NOT Exists(select 1 from PTypeCategory where UserCode=@ptypecategoryid)
	BEGIN
		SET @ErrMsg = '没有此商品类别!'
		RETURN -1
	END
	
	IF EXISTS(select 1 from  ptypecategory where usercode=@brandartypeid and parid='root')
	BEGIN
		SET @ErrMsg =   '该【' + @FullName + '】商品信息修改的类别有误，不能选择系统保留类别！'
		RETURN -1
	END
	
	SELECT @newPtypecatetypeid=typeid from PTypeCategory where UserCode=@ptypecategoryid
END


IF EXISTS(select 1 from sysdata WHERE SubName='usebrandartype' and SubValue=1)--系统启用了品牌
BEGIN
	IF ISNULL(@brandartypeid,'')=''
	BEGIN
		SET @ErrMsg = '商品品牌不能为空!'
		RETURN -1
	END
	ELSE
	BEGIN
		IF NOT Exists(select 1 from brandar_Commodity where UserCode=@brandartypeid)
		BEGIN
			SET @ErrMsg = '没有此商品品牌!'
			RETURN -1
		END
		
		IF EXISTS(select 1 from  brandar_Commodity where usercode=@brandartypeid and parid='root')
		BEGIN
			SET @ErrMsg =  '该【' + @FullName + '】商品信息修改的品牌有误，不能选择系统保留的品牌！'
			RETURN -1
		END
		
		--品牌不能选择大类
		DECLARE @ptypeTypeid_Check varchar(100)
		DECLARE @PtypeErrorMsg varchar(500)=''	
		DECLARE @OldBrandarTypeId varchar(100)
		
		
		SELECT TOP 1 @OldBrandarTypeId=BrandarTypeID from PTYPE where UserCode=@usercode
		SELECT TOP 1 @ptypeTypeid_Check=Typeid FROM brandar_Commodity where UserCode=@brandartypeid
		
		IF @OldBrandarTypeId<>@ptypeTypeid_Check
		BEGIN
			SELECT TOP 1 @ptypeTypeid_Check = typeid FROM PTYPE WHERE UserCode=@usercode
			EXEC Web_PTypeCheckBillUsedWhenModify @ptypeTypeid_Check,@OldBrandarTypeId,@PtypeErrorMsg OUT
			
			IF ISNULL(@PtypeErrorMsg,'')<>''
			BEGIN
				SET @ErrMsg = @PtypeErrorMsg
				RETURN -1
			END
		END
		
		IF Exists(select 1 from brandar_Commodity where UserCode=@brandartypeid AND SonNum<>0)
		BEGIN
			SET @ErrMsg = '品牌信息不能选择大类!'
			RETURN -1
		END
	END
	
	SELECT @newBrandtypeid=typeid from brandar_Commodity where UserCode=@brandartypeid
END


----------------------------------------------------------------------------------------------
-- 判断重复商品信息是否重复
DECLARE @ProName varchar(50)
select  @ProName=value from Userconfig where ConfigName = 'equalproname'

IF @ProName<>1  --不允许商品名称重复
begin
	if exists(select TypeID from ptype where UserCode<>@usercode and fullname=@fullname and deleted<>1 and ParId<>'Root')
	begin
		SET @ErrMsg = '该【' + @FullName + '】商品信息已经存在，请确认商品编号是否冲突!'
		RETURN -1
	end
	
	if exists(select TypeID from ptype where (usercode=@usercode and deleted=1) or (fullname=@fullname and deleted=1))
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @usercode + '使用，请更换或删除该停用的编号'
		RETURN -1
	end
end
else
begin
	if exists(select TypeID from ptype where usercode=@usercode and deleted=1)
	begin
		SET @ErrMsg = '该【' + @FullName + '】的编号已被已停用的' + @usercode + '使用，请更换或删除该停用的编号'
		RETURN -1
	end
end


BEGIN TRAN insertproc
DECLARE @PtypeId_Ext varchar(100)
DECLARE @UpSql varchar(max)

SELECT @PtypeId_Ext=typeId from ptype where UserCode=@usercode

SET @UpSql='UPDATE QP_PType_Ext SET BTypeID='''+@newBtypeid+''' WHERE PTypeID='''+@PtypeId_Ext+''''

exec(@UpSql)

SET @UpSql='
UPDATE	ptype
		SET [FullName] = '''+@fullname+'''
		,[Name] = '''+@name+'''
		,[Standard] = '''+@standard+'''
		,[Type] = '''+@type+'''
		,[Area] ='''+@area+'''
		,[Comment] = '''+@comment+'''
		,[PyCode] ='''+@pycode+'''
		,[BuyDefaultRate] =cast('''+@buydefaultrate+''' as  numeric(24, 10))
		,[SaleDefaultRate] =cast('''+@saledefaultrate +'''as  numeric(24, 10))'
IF EXISTS(select 1 from sysdata WHERE SubName='usebrandartype' and SubValue=1)--启用了品牌
BEGIN
	SET @UpSql+=',[BrandarTypeID] = '''+isnull(@newBrandtypeid,'')+''''
END

IF ISNULL(@ptypecategoryid,'')='' --商品类别编号为空
BEGIN
	SET @UpSql+=',[PtypeCategoryID] ='''' '
END
ELSE
BEGIN
	SET @UpSql+=',[PtypeCategoryID] =isnull('''+@newPtypecatetypeid+''','''')'
END

SET @UpSql+='
		,[Integral] = cast('''+@integral+''' as  numeric(24, 10))
		,[othercomment1]= isnull('''+@othercomment1+''','''')
		,[othercomment2]= isnull('''+@othercomment2+''','''')
		,[othercomment3]=isnull('''+@othercomment3+''','''')
		,[othercomment4]=isnull('''+@othercomment4+''','''')
		,[othercomment5]=isnull('''+@othercomment5+''','''')
		WHERE  UserCode='''+@usercode+''''
	
EXEC(@UpSql)	

if @@rowcount=0 
begin
	rollback tran insertproc 
	SET @ErrMsg = '覆盖失败'
	RETURN -1
end 


COMMIT TRAN insertproc

GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_PtypeIsStopBuy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_PtypeIsStopBuy
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2011-10-18
-- Description: 商品是否停止采购
-- =============================================
CREATE PROCEDURE Gp_PtypeIsStopBuy
(
	@ptypeidlist	varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #ptypeid(typeid varchar(50))
INSERT INTO #ptypeid(typeid) SELECT * FROM dbo.f_split(@ptypeidlist,',')

DECLARE @ptypeid varchar(50),@msg varchar(max)='',@fullname varchar(max)=''
DECLARE IndexCursor CURSOR FOR
	SELECT DISTINCT(typeid) FROM #ptypeid
	
OPEN IndexCursor
FETCH NEXT FROM IndexCursor INTO @ptypeid
WHILE @@FETCH_STATUS = 0
BEGIN	
	IF Exists(SELECT * FROM ptype WHERE typeId=@ptypeid AND StopBuy=1)
	BEGIN
		SELECT @fullname=FullName FROM ptype WHERE typeId=@ptypeid
		IF @msg=''
			SET @msg=@fullname
		ELSE
			SET @msg=@msg+','+@fullname
		END
	FETCH NEXT FROM IndexCursor INTO @ptypeid
END

IF @msg<>''
BEGIN
	SET @msg=@msg+'已停止采购，不能生成订单！'
	RAISERROR(@msg,16,1)
END
RETURN 0

DROP TABLE #ptypeid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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




--作者：徐辉
--时间：2007-3-13
--功能：商品多套编码往来单位之间复制

CREATE     PROCEDURE Gp_PtypeMultiCodeCopy
(
	@OperatorID	VARCHAR(100),
	@BtypeId	VARCHAR(100),   --源往来单位
	@ABtypeID	VARCHAR(max)	--要复制的目标往来单位(一个或多个)
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON

IF @BtypeId = '' OR @ABtypeId=''
	RETURN 1
--筛选商品
CREATE TABLE #GetManPTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@OperatorID)	

--筛选权限范围内往来单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT  INTO #GetManBTypeId( TypeId)
        SELECT  TypeId
        FROM    F_GetAllManagerBaseTypeId( @ABtypeID, 2, @OperatorID)
        WHERE   TypeId <> @BtypeId
     

--DELETE FROM #GetManBTypeId WHERE TypeId=@BtypeId

DECLARE @sql VARCHAR(2000)

DELETE 
FROM	PUserCode 
WHERE   EXISTS(SELECT 1 FROM #GetManBTypeId WHERE TypeId=Pusercode.btypeid)	
		AND EXISTS(SELECT 1 FROM #GetManPTypeId WHERE TypeId=Pusercode.ptypeid)


		
CREATE TABLE #ExistUserCode
(
	UserCode	VARCHAR(MAX)
)

INSERT INTO #ExistUserCode(UserCode)
SELECT	UserCode 
FROM	PUserCode a
WHERE A.btypeid=@BtypeId
--INNER JOIN #GetManBTypeId b ON a.btypeid=b.typeid


INSERT INTO PUserCode 
SELECT 	P.PtypeId AS PtypeId,
		B.TypeId AS BtypeId,
		P.UserCode AS UserCode 
FROM 	PUserCode P,#GetManBTypeId B,#GetManPTypeId MP
WHERE 	P.BtypeId=@BtypeId 		
		AND EXISTS  (SELECT UserCode FROM #ExistUserCode WHERE UserCode=p.usercode)
		AND P.ptypeid = MP.TypeId
		

DROP TABLE #ExistUserCode,#GetManPTypeId

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：郑红霞
	日期：2011-5-20
	描述：生成领料返回单据
-------------------------------------------*/

CREATE  PROCEDURE Gp_QP_AutoPickingBill
(
	@checke	         VARCHAR(100),
	@BillNumberId    VARCHAR(MAX),
	@Ids             VARCHAR(MAX),
	@edratype        VARCHAR(max),
	@KTypeId		 VARCHAR(200), 
    @btypeid         VARCHAR(max),
    @etypeid         VARCHAR(max),
    @quickrepairid   VARCHAR(max), 
    --@dtypeid         VARCHAR(max),  
	@OrderId         VARCHAR(500) OUTPUT
)
--@encode$--
AS
BEGIN TRANSACTION;
BEGIN TRY
	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF
	
	DECLARE @STypeID            VARCHAR(100),
	        @NowDate	        DATETIME,
	        @MONTH 				VARCHAR(50),
			@DAY 				VARCHAR(50),
			@BillCodeConfig		VARCHAR(10),
			@BillCode			VARCHAR(300),
			@Re					INT,
			@Tax				 NUMERIC(24, 10) ,
			@period				INT,
			@DTypeId			VARCHAR(200),
			@nBillId			NUMERIC(18,0),
			@Explain			VARCHAR(400),	
			@TotalQty			 NUMERIC(24, 10) ,
			@Comment			VARCHAR(600),
			@TotalMoney         VARCHAR(max),
			@szPeriod 			[SMALLINT],
			@PickingBillbackqty VARCHAR(max),
			@factbackqty VARCHAR(max),
			@cefullname			VARCHAR(500)='',		--制单人
			@cdfullname		VARCHAR(500)=''
SET @Tax = 0
SELECT @NowDate=GETDATE()
SET @Explain = '领料退回单据'
IF EXISTS(SELECT * FROM userconfig WHERE configname = 'Gridtype' and value = '1')
	SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'
SELECT @DTypeId = D.TypeId FROM Department D,Employee E WHERE E.Department = D.FullName AND E.TypeId = @ETypeId

SET @MONTH = month(getdate())
SET @DAY = day(getdate())
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
DECLARE @stockcheckid   NUMERIC(18,0),
        @datBillDate	DATETIME	
SELECT @datBillDate=CONVERT(VARCHAR(10),GetDate(),120)	
	
BEGIN
--生成单据编号
	IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 197) AND @BillCodeConfig = '1'
		BEGIN
			SELECT @MONTH = typeid FROM employee WHERE TypeID = @etypeid
			SELECT @DAY = fullname FROM Stock WHERE TypeID = @KTypeId
			SELECT @cefullname=FULLNAME FROM dbo.employee WHERE typeId=@checke
			SELECT @cdfullname=fullname FROM dbo.Department WHERE typeid=@DTypeId
		END
	SELECT @STypeID=STypeID FROM BillIndex WHERE BillNumberId = @BillNumberId				
	EXEC @Re=Gp_GetBillCode 197, @MONTH,@DAY,'LLT',@datBillDate,@STypeID,@BillCode OUTPUT,@cdfullname,@cefullname
	IF @Re <> 0
		RETURN -2
	DECLARE @BeginDate datetime
	EXEC Gp_GetSubValue 'period',@STypeID,@szPeriod out
	SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod			
--写入单据主表
SET @OrderId = @BillCode
INSERT INTO BillIndex (AlertDay,BillDate,BillCode,BillType,Comment, atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,IfWx,Stypeid,Assessor)
	   VALUES(9999,@datBillDate,@BillCode,197,'领料退回单','','',@btypeid,@etypeid,@ktypeid,'','f',@checke,0,0,0,@Tax,@szPeriod,0,1,0,'','','','',0,@DTypeId,@Explain,'0',@STypeID,'')
IF @@ROWCOUNT = 0
	RETURN -3
ELSE
	SET @nBillId = SCOPE_IDENTITY();		
DECLARE @cartypeid VARCHAR(max)	
SET @cartypeid =(SELECT TypeID FROM QP_RepairAutoInfo WHERE PlateNumber = @edratype)
INSERT INTO Billindex_CarRepair(BillNumberId,BillDate,BillType,RATypeID,OperationSort,RepairMode,Oil,Mileage,EpibolyItem,OtherItem,[Status],InPriceType,InvoiceMode,InsuranceStatus,RepairType ,
                                BespokeDate,ReceptionDate,CompleteDate,InFactoryDate,FactCompleteDate,BalanceDate,QuickRepairBillID)
       VALUES (@nBillId,@datBillDate,197,@cartypeid,'','','','','','',0,0,0,0,0,@datBillDate,@datBillDate,@datBillDate,@datBillDate,@datBillDate,@datBillDate,@quickrepairid )
															
INSERT INTO  Qp_PickingBackBill(BillNumberId,PickingId,KTypeID,PTypeID,Qty,Price,InputCostPrice,Total,Insurance,Comment)
	   SELECT        @nBillId AS BillNumberId,
					 q.ID AS PickingId,
					 q.KTypeID,
					 q.PTypeID,
					 (q.Qty-q.BackQty) as Qty,
					 q.Price,
					 q.InputCostPrice,
					 ((q.Qty-q.BackQty)*q.Price) as total,
					 q.Insurance,
					 r.Comment
	   FROM   Qp_PickingBill q
	                 INNER JOIN Qp_ReceptionBill_FactUsePType r on r.PickingId =q.ID
	   WHERE  r.ReceptionBillnumberId=@BillNumberId AND q.ID in (SELECT A FROM dbo.f_split(@Ids,',') WHERE ISNULL(A,'')<>'')
    
--修改BillIndex的TotalMoney
SELECT @TotalQty = SUM(Qty) FROM Qp_PickingBackBill WHERE BillNumberId = @nBillId
SELECT @TotalMoney = SUM(Total) FROM Qp_PickingBackBill WHERE BillNumberId = @nBillId
UPDATE BillIndex SET TotalQty = @TotalQty WHERE BillNumberId = @nBillId
UPDATE BillIndex SET totalmoney = @TotalMoney WHERE BillNumberId = @nBillId

END	
EXEC GP_SaveBillCode_Seed @nBillId,@datBillDate,197,@BillCode
END TRY
BEGIN CATCH
		IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
        DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH
IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：郑红霞
	日期：2011-06-09
	描述：给电脑配置单和销售出库单添加想关联的表,再把DiyIndex中的被调用次数加1
-------------------------------------------*/
CREATE PROCEDURE [dbo].[GP_Qp_InserInDiyBillTypePSaleTypeID]
(
    @SaleBillNumberId  VARCHAR(max),              --销售出库单Id
    @DiyBillId     VARCHAR(max),                   --电脑配置单Id
    @ifcheck		varchar(10)	--是否过账标识，t.过账 f.草稿
)
--@encode$--
AS

IF @ifcheck='t' 
BEGIN
	DECLARE  @Counts  VARCHAR(max) 
	SET @Counts = (SELECT Counts FROM DiyIndex WHERE BillNumberId IN (SELECT DiyBillTypeId FROM DiyBillTypePSaleTypeID WHERE SalebillNumberId=@SaleBillNumberId) )
	Update DiyIndex set Counts=(CAST(@Counts AS INT)+1) WHERE BillNumberId IN (SELECT DiyBillTypeId FROM DiyBillTypePSaleTypeID WHERE SalebillNumberId=@SaleBillNumberId)
END
IF @DiyBillId<>'0'
	BEGIN
		INSERT INTO DiyBillTypePSaleTypeID (SalebillNumberId,DiyBillTypeId,ifcheck) VALUES(@SaleBillNumberId,@DiyBillId,@ifcheck)
	END
ELSE
	BEGIN
		UPDATE DiyBillTypePSaleTypeID SET ifcheck=@ifcheck WHERE SalebillNumberId=@SaleBillNumberId
	END
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrAccount]
GO















/****** Object:  Stored Procedure dbo.Gp_qrAccount    Script Date: 2002-6-20 10:14:52 ******/

CREATE   proc Gp_qrAccount
( 
 @Parid  varchar(50),
 @cFlag  char(1),
 @dTotal  NUMERIC(24, 10)  output
)
--@encode$--
as
set nocount on
select @dTotal=sum(b.total) from atype b
where left(b.typeid,len(@parid))=@parid
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrAccountAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrAccountAll]
GO








CREATE    PROC Gp_qrAccountAll
( 
	@OperatorID	VARCHAR(50),	-- 操作员的ID号
	@parid   	VARCHAR(50),
	@cFlag   	CHAR(2),
	@szPeriod  	CHAR(2),
	@stypeid	varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON
-- 权限范围 ADD BY 刘畅2002-4-11
DECLARE @MATYPE  VARCHAR(50)
SELECT  @MATYPE = MangerATypeID FROM loginuser WHERE [EtypeID] = @OperatorID

DECLARE @SQL varchar(5000)
SET @SQL =''
IF @MATYPE='00000'
	SET @MATYPE='00001'

/*
IF LEFT(@parid,len(@MATYPE))<>@MATYPE
	SET @parid=LEFT(@MATYPE,len(@MATYPE)-5)
*/
IF @ParID <> '0000100002'
	SET @parid=@parid
ELSE
	SET @ParID = '0000100002'

declare @sonnum int
SET @Sonnum =0
SELECT @SonNum = SonNum FROM AType WHERE TypeId = @ParId AND Deleted = 0
Create table #Atype(typeid varchar(50),total00  NUMERIC(24, 10) )
CREATE TABLE #MainType(typeid varchar(50),usercode varchar(26),fullname varchar(66),sonnum int,sysflag int)
create table #stype(typeid varchar(100))

--分支机构
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

INSERT INTO #Atype(typeid,total00) 
	select A.ATypeID as typeid,sum(isnull(a.Total00,0)) 
	from AType_Total A ,F_GetManDetailAType(@OperatorID) W ,#stype s
	WHERE A.ATypeID=W.typeid and s.typeid=a.STypeID
	group by a.ATypeID


IF @sonnum =0 	
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sysflag) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.sysflag from atype a
	,(select * from F_GetManATypeAll(@OperatorID) where typeid =@Parid) b where a.typeid=b.typeid
ELSE
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sysflag) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.sysflag from atype a
	,(select * from F_GetManATypeAll(@OperatorID) where parid =@Parid) b where a.typeid=b.typeid


IF @szPeriod='' 
	BEGIN
		SELECT 	a.usercode,
				a.fullname,
				a.sonnum,
				a.typeid,
				(SELECT ISNULL(SUM(b.total),0) FROM atype b WHERE LEFT(b.typeid,len(a.typeid))=a.typeid ) AS 'total'
		FROM 	atype a 
		WHERE 	a.parid=@parid 
				AND sysflag=@cFlag 
				AND a.deleted=0 
				--AND typeid LIKE @MATYPE+'%'			--加入权限   谢吉康   暂时屏蔽				
		ORDER BY usercode
	END 
ELSE
	BEGIN
		
				SET @SQL ='
					SELECT 	a.usercode,
							a.fullname,
							a.sonnum,
							a.typeid,
							(SELECT ISNULL(SUM(b.total00),0) FROM #atype b WHERE LEFT(b.typeid,len(a.typeid))=a.typeid ) AS total
					FROM 	#MainType a 
					WHERE 	 sysflag='+char(39)+@cFlag +char(39)+'
							AND (TypeId LIKE ''0000100003%'' OR TypeId LIKE ''0000100004%'')
					ORDER BY usercode '
				--PRINT @SQL 
				EXEC(@SQL)
END
DROP TABLE #Atype,#stype, #MainType



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrAccountAll_CashBank]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrAccountAll_CashBank]
GO


CREATE  PROCEDURE Gp_qrAccountAll_CashBank
( 
	@chvOperatorID			VARCHAR(50),		-- 操作员的ID号
	@StypeID				VARCHAR(max),		-- 分支机构ID
	@Cid					INT,				-- 币别
	@NTypeid				VARCHAR(100)='',	-- 父节点
	@Type					INT=1,				--1：树形 0：线性
	@EndDate				varchar(50)='',		-- 结束日期
	@first					VARCHAR(10)='1'		--默认菜单进来  1.是  0.否
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------分支机构权限检查-----------------------------------
CREATE TABLE #stype(stypeid  varchar(50))
IF @StypeID=''
	INSERT INTO #stype
	SELECT TypeId from dbo.F_GetManDetailAllSType(@chvOperatorID) 
ELSE 
	INSERT INTO #stype
	SELECT B.typeid AS stypeid  FROM   dbo.f_split(@StypeID,',')  A 
	JOIN (SELECT * from dbo.F_GetManDetailAllSType(@chvOperatorID)) B ON  B.typeid LIKE A.a+'%' AND a<>''


CREATE TABLE #atype
(
	typeid INT,
	usercode VARCHAR(500),
	fullname VARCHAR(500),
	NTypeid VARCHAR(50),
	NParid VARCHAR(50),
	SonNum INT,
	Leveal INT,
)
CREATE NONCLUSTERED INDEX cix_atype_typeid ON #atype(typeid)

CREATE TABLE #TotalAll
(
	typeid INT,
	usercode VARCHAR(500),
	fullname VARCHAR(500),
	NTypeid VARCHAR(50),
	NParid VARCHAR(50),
	SonNum INT,
	Leveal INT,
	Total  NUMERIC(24, 10) ,
	TotalFor  NUMERIC(24, 10) ,
	Total1  NUMERIC(24, 10) 
)
CREATE NONCLUSTERED INDEX cix_totalall_typeid ON #TotalAll(typeid)

------------------------权限检查（项目）--------------------
INSERT INTO #atype
SELECT a.Typeid,a.UserCode,a.FullName,a.nTypeId,a.nParId,a.SonNum,b.Leveal
FROM F_AllTreeA(@chvOperatorID) a 
INNER JOIN dbo.Ac_Items b ON a.nTypeId = b.nTypeId 
WHERE a.TypeName ='B'

--菜单进来
IF @first = '1' OR CONVERT(VARCHAR(10),@EndDate,120) = CONVERT(VARCHAR(10),GETDATE(),120)
BEGIN
	INSERT INTO #TotalAll
	SELECT	a.Typeid,
			a.UserCode,
			a.FullName,
			a.nTypeId,
			a.nParId,
			a.SonNum,
			a.Leveal,
			ISNULL(SUM(b.Total),0) AS total,
			ISNULL(SUM(b.Ntotal),0) AS TotalFor,
			ISNULL(SUM(Total),0) AS Total1
	FROM #atype a 
	LEFT JOIN
	(
		SELECT  SUM(total) total, SUM(Ntotal) Ntotal, nTypeId
		FROM (
				SELECT b.Total,b.Ntotal,c.nTypeId 
				FROM AType_Total b
				INNER JOIN  #atype c  ON b.atypeid = c.typeid
				JOIN #stype s  ON b.stypeid = s.stypeid
				WHERE	CID=@Cid
			)x
		 GROUP BY X.nTypeId
	)b on b.ntypeid LIKE a.NTypeid+'%'
	GROUP BY A.TypeId,A.Leveal,A.UserCode,A.FullName,A.nTypeId,A.nParId,A.SonNum
END
ELSE
BEGIN
	INSERT INTO #TotalAll
	SELECT	a.Typeid,
			a.UserCode,
			a.FullName,
			a.nTypeId,
			a.nParId,
			a.SonNum,
			a.Leveal,
			ISNULL(SUM(b.Total),0) AS total,
			ISNULL(SUM(b.Ntotal),0) AS TotalFor,
			ISNULL(SUM(Total),0) AS Total1
	FROM #atype a 
	LEFT JOIN
	(
		SELECT  SUM(total) total, SUM(Ntotal) Ntotal, nTypeId
		FROM (
				SELECT	b.total,
						b.ntotal,
						c.nTypeId 
				FROM	ListTable b
				INNER JOIN  #atype c  ON b.atypeid = c.typeid
				JOIN #stype s  ON b.stypeid = s.stypeid
				WHERE	CID=@Cid
						AND B.BillDate<=@EndDate
				UNION ALL
				SELECT b.Total00,b.Ntotal00,c.nTypeId 
				FROM AType_Total b
				INNER JOIN  #atype c  ON b.atypeid = c.typeid
				JOIN #stype s  ON b.stypeid = s.stypeid
				WHERE	CID=@Cid
			)x
		 GROUP BY X.nTypeId
	)b on b.ntypeid LIKE a.NTypeid+'%'
	GROUP BY A.TypeId,A.Leveal,A.UserCode,A.FullName,A.nTypeId,A.nParId,A.SonNum
END	

------------------------根据条件输出结果---------------------------

IF @Type=0	--线性
	IF @NTypeid=''
		SELECT * FROM #TotalAll WHERE SonNum=0 ORDER BY UserCode
	ELSE
		SELECT * FROM #TotalAll WHERE SonNum=0 AND nTypeId LIKE @NTypeid+'%' ORDER BY UserCode

ELSE	--树形
BEGIN
	DECLARE @CurLevel INT 
	SELECT @CurLevel = ISNULL(Leveal,2) FROM #atype WHERE nTypeId=@NTypeid
	IF(@NTypeid='' OR @NTypeid IS NULL)
		SELECT * FROM #TotalAll WHERE Leveal=2 ORDER BY UserCode
	ELSE 
		SELECT * FROM #TotalAll WHERE Leveal=@CurLevel+1 AND nTypeId LIKE @NTypeid+'%' ORDER BY UserCode
END
DROP TABLE #atype,#TotalAll,#stype



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrAccountAll_FixedAssets]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrAccountAll_FixedAssets]
GO










--修改人：徐辉
--修改原因：添加了固定资产权限范围
--修改时间：2004-11-29


/****** Object:  Stored PROCEDURE dbo.Gp_qrAccountAll    Script Date: 2002-6-20 10:14:52 ******/
CREATE      PROC Gp_qrAccountAll_FixedAssets
( 
	@MagEType	VARCHAR(50),	-- 操作员的ID号
	@parid   	VARCHAR(50),
	@cFlag   	CHAR(2),
	@szPeriod  	CHAR(2)
)
--@encode$--
AS
SET NOCOUNT ON
-- 权限范围 ADD BY 刘畅2002-4-11
DECLARE @MATYPE  VARCHAR(50)
SELECT  @MATYPE = MangerCpaital FROM loginuser WHERE [EtypeID] = @MagEType

IF @MATYPE='00000'
	SET @MATYPE='000010002'

/*
IF LEFT(@parid,len(@MATYPE))<>@MATYPE
	SET @parid=LEFT(@MATYPE,len(@MATYPE)-5)
*/
IF @ParID <> '0000100002'
	SET @parid=@parid
ELSE
	SET @ParID = '0000100002'
IF @szPeriod='' 
	BEGIN
		SELECT 	a.usercode,
				a.fullname,
				a.parid,
				a.sonnum,
				a.leveal,
				a.typeid,
				(SELECT ISNULL(SUM(b.total),0) FROM atype b WHERE LEFT(b.typeid,len(a.typeid))=a.typeid ) AS 'total'
		FROM 	atype a 
		WHERE 	a.parid=@parid
				AND sysflag=@cFlag 
				AND a.deleted=0 
				AND typeid LIKE @MATYPE+'%'			--加入权限   谢吉康   暂时屏蔽
		ORDER BY usercode
	END 
ELSE
	BEGIN
		SELECT 	a.usercode,
				a.fullname,
				a.parid,
				a.sonnum,
				a.leveal,
				a.typeid,
				(SELECT ISNULL(SUM(b.total00),0) FROM atype b WHERE LEFT(b.typeid,len(a.typeid))=a.typeid ) AS 'total'
		FROM 	atype a 
		WHERE 	a.parid=@parid 
				AND sysflag=@cFlag 
				AND a.deleted=0 
				AND typeid LIKE @MATYPE+'%'			--加入权限  谢吉康   暂时屏蔽
		ORDER BY usercode
	END










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrAccountAll_FixedAssets_New]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrAccountAll_FixedAssets_New]
GO








/*
	作者：谢吉康
	日期：2005-11-8
	描述：重写固定资产起初
*/
CREATE     PROC Gp_qrAccountAll_FixedAssets_New
( 
	@OperatorID	VARCHAR(50),	-- 操作员的ID号
	@parid   	VARCHAR(50),
	@cFlag   	CHAR(2),
	@szPeriod  	CHAR(2),
	@stypeid	varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @MCType  	VARCHAR(100),
		@SQL		VARCHAR(8000),
		@SonNum		INT

SELECT  @MCType = MangerCpaital FROM loginuser WHERE [EtypeID] = @OperatorID

SELECT @SonNum = SonNum FROM AType WHERE TypeId = @ParId AND Deleted = 0

Create table #Atype(typeid varchar(50),total00  NUMERIC(24, 10) )
CREATE TABLE #MainType(typeid varchar(50),usercode varchar(26),fullname varchar(66),sonnum int,sysflag int)
create table #stype(typeid varchar(100))

--分支机构
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

INSERT INTO #Atype(typeid,total00) 
	select A.ATypeID as typeid,sum(isnull(a.Total00,0)) 
	from AType_Total A ,F_GetManDetailATypeZc(@OperatorID) W ,#stype s
	WHERE A.ATypeID=W.typeid and s.typeid=a.STypeID
	group by a.ATypeID

IF @sonnum =0 	
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sysflag) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.sysflag from atype a
	,(select * from F_GetManATypeZcAll(@OperatorID) where typeid =@Parid) b where a.typeid=b.typeid
ELSE
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sysflag) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.sysflag from atype a
	,(select * from F_GetManATypeZcAll(@OperatorID) where parid =@Parid) b where a.typeid=b.typeid


SET @SQL = '
			SELECT 	a.usercode,
					a.fullname,
					a.sonnum,
					a.typeid,
					(
						SELECT 	ISNULL(SUM(b.total00),0) 
						FROM 	#atype b 
						WHERE 	LEFT(b.typeid,len(a.typeid))=a.typeid 
					) AS ''total''
			FROM 	#MainType a '

SET @SQL = @SQL + ' ORDER BY a.usercode '


--PRINT(@SQL)
EXEC(@SQL)
DROP TABLE #Atype,#stype,#MainType










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrAcount23]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrAcount23]
GO


/****** Object:  Stored Procedure dbo.Gp_qrAcount23    Script Date: 2002-6-20 10:14:52 ******/


/*
    主要用于查询其他收入、费用的本期发生额和余额 树形结构
    @MagEType 操作员ID
    @Type     模式
    @szPeriod 期号
*/
CREATE      PROCEDURE Gp_qrAcount23
(
 @MagEType	varchar(50),		-- 操作员的ID号
 @Type		Int=0,			-- 模式 2:现金银行 0：其他收入 1：费用 3: 待摊费用
 @parid		varchar(50)='00000',	-- 树形结构的父节点
 @szPeriod	char(2)='1',		-- 00:期初
 @StypeId	varchar(1550)=''
)
--@encode$--
AS
SET NOCOUNT ON

-- 获得期初日期
DECLARE @BeginDate  varchar(20)
SELECT @BeginDate=[StartDate] 
FROM [MonthProc]
WHERE [MonthNo]='本期'

-- 获得权限
DECLARE @MATYPE  varchar(50)	-- 现金银行
DECLARE @MITYPE  varchar(50)	-- 一般收入
DECLARE @MFTYPE  varchar(50)	-- 费用
DECLARE @MDTYPE  varchar(50)    -- 待摊费用


SELECT   @MATYPE = MangerATypeID,
		 @MITYPE = MangerIncome,
		 @MFTYPE = MangerExpense
FROM [loginuser]
WHERE [EtypeID] = @MagEType

-- 根据管辖范围、模式范围、当前父节点范围获得结果
IF @MITYPE='00000'
	SET @MITYPE='0000300003'
IF @MFTYPE='00000'
	SET @MFTYPE='0000400003'
--IF @MDTYPE='00000'
SET @MDTYPE='0000100007'

-- 按模式获得本期、期末余额
--IF @Type=2	-- 2:现金银行
--BEGIN
--END
CREATE TABLE #Stype (TypeID varchar(50))

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@MagEType)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@MagEType) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a

SELECT p.nparid, p.deleted, p.ntypeId,p.leveal,p.UserCode,p.FullName,p.sonnum,
	s.Total,s.Total00
INTO 
	#Atype
FROM 
	AC_Items p
LEFT JOIN 
	(SELECT atypeid,Sum(isnull(total,0)) as total, Sum(isnull(total00,0)) as total00 
	FROM AType_Total WHERE Stypeid IN(SELECT typeId FROM #Stype) GROUP By ATypeID ) s
ON s.ATypeID=p.nid

IF @Type=0	-- 0：其他收入
BEGIN
	IF Left(@parid,len(@MITYPE))<>@MITYPE
		SET @parid=Left(@MITYPE,len(@MITYPE)-5)
	
	SELECT (
			SELECT ISNULL(SUM(Total),0) 
			FROM [ListTable] l
			INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
			WHERE AC.[NTypeId] LIKE a.[NTypeId]+'%'
				AND l.[BillDate]>=@BeginDate
		)AS BYTotal
		,(
			SELECT ISNULL(SUM(Total),0) 
			FROM [ListTable] l
		    INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
			WHERE AC.NTypeId LIKE a.[NTypeId]+'%'
		)AS LJTotal
		,*
	FROM AC_Items a
	WHERE [ntypeid] like @MITYPE+'%' 
			AND [parid] = @parid
			AND [deleted]=0
	ORDER BY [usercode]
END

IF @Type=1	-- 1：费用
BEGIN
	IF Left(@parid,len(@MFTYPE))<>@MFTYPE
		SET @parid=Left(@MFTYPE,len(@MFTYPE)-5)

	SELECT (
			SELECT ISNULL(SUM(Total),0) 
			FROM [ListTable] l
			INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
			WHERE AC.NtypeID LIKE a.[NTypeId]+'%'
				AND l.[BillDate]>=@BeginDate
		)AS BYTotal
		,(
			SELECT ISNULL(SUM(Total),0) 
			FROM [ListTable] l
			INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
			WHERE AC.NtypeID LIKE a.[NTypeId]+'%'
		)AS LJTotal
		,*
	FROM AC_Items a
	WHERE [ntypeid] like @MFTYPE+'%' 
		AND [parid] = @parid
		AND [deleted]=0
	ORDER BY [usercode]
END

IF @Type=3 	-- 3: 费用
--待摊费用为吴德水2002-10-31添加
BEGIN
	--SELECT * FROM #Atype WHERE nParId LIKE '0000100007%'
	IF Left(@parid,len(@MDTYPE))<>@MDTYPE
		SET @parid=Left(@MDTYPE,len(@MDTYPE)-5)
	
	--SELECT * FROM #Atype WHERE total IS NOT NULL
	
	CREATE TABLE #Ac_item( ntypeid VARCHAR(60))
	INSERT INTO #Ac_item SELECT nTypeId FROM  dbo.F_TreeGxAssets(@MagEType)
	SELECT x.parid,x.typeid,x.usercode,x.sonnum, x.BYTotal, x.BYTotal + x.jetotal AS 'jetotal' FROM (
SELECT b.nparid AS parid,
a.ntypeid as typeid,
a.usercode as usercode,b.sonnum,
(
	SELECT ISNULL(SUM(Total),0) 
	FROM [ListTable] l
	INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
	WHERE AC.NtypeID LIKE +a.NTypeId +'%'
	AND l.STypeID IN(SELECT typeId FROM #Stype)
	AND AC.nTypeId IN (SELECT nTypeId FROM #Ac_item)
)AS BYTotal --本期
,
(
	SELECT ISNULL(SUM(Total00),0) 
	FROM #Atype where NTypeId LIKE b.ntypeid+'%' 
	AND nTypeId IN (SELECT nTypeId FROM #Ac_item)
) AS jetotal --期初
 FROM (
SELECT * FROM  dbo.Ac_Items WHERE nParId = @parid) AS b   JOIN  #Atype a
ON b.nTypeId = a.nTypeId
JOIN #Ac_item c 
ON c.nTypeId = a.nTypeId
WHERE b.nTypeId like @MDTYPE+'%' 
	) AS x
	DROP TABLE #Ac_item
--	select X.LjTotal+x.total00 as jetotal,x.*  INTO 
--	#temps
--	from (
--		SELECT 
--			( 
--				SELECT ISNULL(SUM(Total),0) 
--				FROM [ListTable] l
--				INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
--				WHERE AC.[NTypeId] LIKE a.[NTypeId]+'%'
--					AND l.[BillDate]>=@BeginDate
--					AND l.STypeID IN(SELECT typeId FROM #Stype)
--			)AS BYTotal
--			,
--			(
--				SELECT ISNULL(SUM(Total),0) 
--				FROM [ListTable] l
--				INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
--				WHERE AC.[NTypeId] LIKE a.[NTypeId]+'%'
--					AND l.STypeID IN(SELECT typeId FROM #Stype)
--			)AS LJTotal,
--			a.ntypeid as typeid,
--			a.usercode as usercode,
--			a.total00
--		FROM #Atype a
--		WHERE [ntypeid] like @MDTYPE+'%' 
--				AND [nparid] = @parid
--				AND [deleted]=0
--	) X
--	ORDER BY X.[usercode]
END

DROP TABLE #Stype
DROP TABLE #Atype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrDealinCircs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrDealinCircs]
GO






CREATE          PROCEDURE Gp_qrDealinCircs
(
 @szFlag varchar(10)=null,
 @szPeriod varchar(2)=''
)
--@encode$--
AS
set nocount on
 declare  @GOODS_ID varchar(50),
   @CASH_ID  varchar(50),
   @CASH_BANK_ID varchar(50),
   @AR_ID varchar(50),
   @AP_ID varchar(50),
   @GOODS_LOSS_ID varchar(50),
   @GOODS_GET_ID varchar(50),
   @ALLOT_PRICE_ID varchar(50),
   @PRICE_INCOME_ID varchar(50),     
   @BORROW_BUY_PRICE_ID varchar(50), 
   @GOODS_GIVE_ID varchar(50),       
   @GOODS_PRODUCE_ID varchar(50),    
   @SALE_COST_ID varchar(50),        
   @SALE_INCOME_ID varchar(50),      
   @LEND_GOODS_ID varchar(50),       
   @BORROW_GOODS_ID varchar(50),     
   @BALANCE_ID varchar(50),          
   @DEPRECIATION_ID varchar(50),     
   @APPORTION_EXPENSE_ID varchar(50),
   @INIT_MONEY_ID varchar(50),       
   @ALL_INCOME_ID varchar(50),       
   @ALL_EXPENSE_ID varchar(50),      
   @PROFIT_ID varchar(50),           
   @ASSETS_ID varchar(50),           
   @DEBT_ID varchar(50),             
   @POWER_ID varchar(50),
   @ADDEBT_INCOME_ID varchar(50),
   @ADDEBT_LOSE_ID varchar(50),
   @PAIDUPCAPITAL_ID varchar(50) --实收资本 
 select @GOODS_ID='0000100001'
 select @CASH_ID='0000100003'
 select @CASH_BANK_ID='0000100004'
 select @AR_ID='0000100005'
 select @AP_ID='0000200001'
 select @GOODS_LOSS_ID='000040000200001' --           商品报损
 select @GOODS_GET_ID='000030000200001'  --           商品报溢收入
  select @ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
 select @PRICE_INCOME_ID='000030000200003'--成本调价收入
-- select @BORROW_BUY_PRICE_RECNO varchar(50)= 28;
-- select @GOODS_GIVE_RECNO = 000040000200002           商品赠出
 select @GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
 select @SALE_COST_ID='0000400001'--              『销售成本』
 select @SALE_INCOME_ID='0000300001'--            『销售收入』
-- select @LEND_GOODS_RECNO varchar(50),       = 21;
-- select @BORROW_GOODS_RECNO varchar(50),     = 24;
 select @BALANCE_ID='000030000200004'--           进货退货差价
 select @DEPRECIATION_ID='000040000300002'--      固定资产折旧
 select @APPORTION_EXPENSE_ID='0000100007'--      待摊费用
-- select @INIT_MONEY_RECNO varchar(50),       = 18;
 select @ALL_INCOME_ID='00003' --          【收入类】
 select @ALL_EXPENSE_ID='00004'--                 【支出类】
 select @ASSETS_ID ='00001'  --【资产合计】
 select @DEBT_ID='00002'   --【负债合计】
-- select @POWER_RECNO varchar(50)            = 4;
 select @ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
 select @ADDEBT_LOSE_ID='000040000300001' --调帐亏损
 select @PAIDUPCAPITAL_ID='0000500001'   --实收资本
 select @PROFIT_ID='0000500006'          --利润

declare @begindate datetime
declare @dTotalIncom  NUMERIC(24, 10) ,@dTotalExpense  NUMERIC(24, 10) 

if @szperiod=''
begin
 select @begindate=startdate from monthproc where monthno like '本期'
 if @szFlag='gain'  -- 损益表
 begin
delete from tmpgain where bqtotal=0
  select a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
   (select isnull(sum(b.total),0) from atype b
    where left(b.typeid,len(a.typeid))=a.typeid and a.deleted=0 and b.deleted=0
   ) as 'Total',
  
   (select isnull(sum(b.bqtotal),0) from tmpGain b
    where left(b.typeid,len(a.typeid))=a.typeid 
   ) as 'BqTotal'
 
  from atype a where (left(a.typeid,5)=@ALL_INCOME_ID or left(a.typeid,5)=@ALL_EXPENSE_ID) and a.deleted=0
 end else if @szFlag='asset'  -- 树型资产负债表(带本期值)
 begin
  select a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
   (select isnull(sum(b.total),0) from atype b
    where left(b.typeid,len(a.typeid))=a.typeid
   ) as 'Total',
 
   (select isnull(sum(b.total),0) from listtable b
    where left(b.atypeid,len(a.typeid))=a.typeid and billdate>=@begindate 
   ) as 'BqTotal'
 
  from atype a where (left(a.typeid,5)=@ASSETS_ID or left(a.typeid,5)=@DEBT_ID)  and a.deleted=0
 end 
else if @szFlag='bassert'  -- 平衡资产负债表
 begin
  select @dTotalIncom=isnull(sum(total),0) from atype where left(typeid,5)=@ALL_INCOME_ID and deleted=0
  select @dTotalExpense=isnull(sum(total),0) from atype where left(typeid,5)=@ALL_EXPENSE_ID and deleted=0  update atype set total=@dTotalIncom-@dTotalExpense where typeid=@PROFIT_ID

  select a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
   (select isnull(sum(b.total),0) from atype b
    where left(b.typeid,len(a.typeid))=a.typeid
   ) as 'Total' 
  from atype a where (left(a.typeid,5)=@ASSETS_ID or left(a.typeid,5)=@DEBT_ID or 
   (left(a.typeid,5)='00005' and a.typeid in ('00005','0000500001','0000500006')))  and a.deleted=0
 end
else if @szFlag='bassert00'  -- 平衡资产负债表期初
 begin

	
	declare @dTotalIncom00  NUMERIC(24, 10) ,@dTotalExpense00  NUMERIC(24, 10) 
	select @dTotalIncom00=isnull(sum(total00),0) from atype where left(typeid,5)=@ALL_INCOME_ID and deleted=0
	select @dTotalExpense00=isnull(sum(total00),0) from atype where left(typeid,5)=@ALL_EXPENSE_ID and deleted=0  update atype set total=@dTotalIncom00-@dTotalExpense00 where typeid=@PROFIT_ID
	/*
	select a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
	(select isnull(sum(b.total00),0) from atype b
	where left(b.typeid,len(a.typeid))=a.typeid
	) as 'Total' 
	from atype a where (left(a.typeid,5)=@ASSETS_ID   
	 or left(a.typeid,5)=@DEBT_ID or 	   (left(a.typeid,5)='00005' and a.typeid in ('00005','0000500001','0000500006'))) and a.deleted=0
	return
	*/
	
	Create TABLE #Bassert00
	(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	usercode varchar(26),
	fullname varchar(100),
	leveal int,
	typeid varchar(50),
	sonnum int,
	parid varchar(50),
	total  NUMERIC(24, 10) ,
	fullname1 varchar(100),
	leveal1 int,
	total1  NUMERIC(24, 10) ,
	parid1 varchar(50),
	typeid1 varchar(50),
	Sonnum1 int
	)
	DECLARE @MaxID int
	SET @MaxID =0
	INSERT INTO #Bassert00 (usercode,fullname,leveal,typeid,sonnum,parid,total)
	select a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
	(select isnull(sum(b.total00),0) from atype b
	where left(b.typeid,len(a.typeid))=a.typeid
	) as 'Total' 
	from atype a where left(a.typeid,5)=@ASSETS_ID  and a.typeid<>'0000200002' and a.typeid<>'0000100006'  and a.deleted=0
	order by a.typeid
	SET @MaxID =@@Rowcount
	
	DECLARE @fullname varchar(100)
	DECLARE @leveal int
	DECLARE @Total  NUMERIC(24, 10) 
	DECLARE @typeid varchar(50)
	DECLARE @parid varchar(50)
	DECLARE @sonnum int
	DECLARE @i int
	SET @i =1
	DECLARE BassCurSor CURSOR FOR	
	select a.fullname,a.leveal,a.typeid,a.parid,a.sonnum,
	(select isnull(sum(b.total00),0) from atype b
	where left(b.typeid,len(a.typeid))=a.typeid
	) as 'Total' 
	from atype a where a.deleted=0 and a.typeid<>'0000200002' and a.typeid<>'0000100006' and (left(a.typeid,5)=@DEBT_ID or 	   (left(a.typeid,5)='00005' and a.typeid in ('00005','0000500001','0000500006')))
	order by a.typeid
	OPEN BassCurSor
	FETCH NEXT FROM BassCurSor INTO @fullname,@leveal,@typeid,@parid,@sonnum,@Total
	WHILE @@FETCH_STATUS =0
	BEGIN
	IF @I<=@MaxID
	BEGIN
		UPDATE #Bassert00 SET fullname1=@fullname,leveal1=@leveal,total1=@Total,typeid1=@typeid,parid1=@parid,sonnum1=@sonnum WHERE [ID]=@i
	END	
	ELSE
	BEGIN
		INSERT INTO #Bassert00(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) SELECT @fullname,@leveal,@total,@typeid,@parid,@sonnum
	END
	SET @i = @i + 1
	FETCH NEXT FROM BassCurSor INTO @fullname,@leveal,@typeid,@parid,@sonnum,@Total
	END
	CLOSE BassCurSor
	DEALLOCATE BassCurSor
	
	
--select sum(isnull(total,0)) from #Bassert00 where parid='00001'


	-- 修改应收款合计
	UPDATE #Bassert00 SET total=(SELECT sum(artotal00)-sum(aptotal00) FROM BTYPE where sonnum=0 and deleted=0 and typeid like '00001%' ) where typeid='0000100005'
	-- 修改库存总值
	UPDATE #Bassert00 SET total=(Select sum(isnull(Total,0)) as total from inigoodsstocks ) where typeid='0000100001'
	-- 修改委托代销期初
	UPDATE #Bassert00 SET total=(Select sum(isnull(CostTotal,0)) as total from inicommissionstock Where type=140 ) where typeid='0000100008'


	UPDATE #Bassert00 SET total=(select sum(isnull(total,0)) from #Bassert00 where parid='00001' ) where typeid='00001'

	-- 修改应付款合计
	UPDATE #Bassert00 SET total1=(SELECT sum(aptotal00)-sum(artotal00) FROM BTYPE where sonnum=0 and deleted=0 and typeid like '00002%' ) where typeid1='0000200001'
	-- 修改代销商品期初
	UPDATE #Bassert00 SET total1=(Select sum(isnull(Total,0)) as total from inicommissionstock Where type=144 ) where typeid1='0000200003'

	-- 修改负债合计
	UPDATE #Bassert00 SET total1=(Select sum(isnull(Total1,0)) as total from #Bassert00 where  typeid1 NOT in ('0000200001','0000200002','0000200003') AND LEFT(parid1,5)='00002' and sonnum1=0 ) where typeid1='00002'
	UPDATE #Bassert00 SET total1=total1+(Select sum(isnull(Total1,0)) as total from #Bassert00 where  typeid1 ='0000200001' ) where typeid1='00002' -- +应付
	UPDATE #Bassert00 SET total1=total1+(Select sum(isnull(Total1,0)) as total from #Bassert00 where  typeid1 ='0000200003' ) where typeid1='00002' -- +代销

	-- 修改所有者权益 = 资产-负债
	UPDATE #Bassert00 SET total1=(Select total from #Bassert00 where typeid in ('00001'))-(Select total1 from #Bassert00 where typeid1 in ('00002') ) where typeid1='00005'

	--实收资本 == 所有者权益 - 利润 （=收入-支出）
	UPDATE #Bassert00 SET total1=(select total1 from #Bassert00 where typeid1='00005')- ((select sum(total) from atype where typeid like '00003%' and sonnum=0 and deleted=0)-(select sum(total) from atype where typeid like '00004%' and sonnum=0 and deleted=0 )) where typeid1='0000500001'
	
	--添加利润项
	IF @I<=@MaxID
	BEGIN
		UPDATE #Bassert00 SET fullname1='利  润',leveal1=2,total1=((select sum(total) from atype where typeid like '00003%' and sonnum=0 and deleted=0)-(select sum(total) from atype where typeid like '00004%' and sonnum=0 and deleted=0 )),typeid1='0000500004',parid1='00005',sonnum1=0 WHERE [ID]=@i
	END	
	ELSE
	BEGIN
		INSERT INTO #Bassert00(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) SELECT '利  润',2,((select sum(total) from atype where typeid like '00003%' and sonnum=0 and deleted=0)-(select sum(total) from atype where typeid like '00004%' and sonnum=0 and deleted=0 )),'0000500004','00005',0
	END



	UPDATE  #Bassert00 SET fullname='    '+isnull(fullname,'') where leveal=1 
	UPDATE  #Bassert00 SET fullname1='    '+isnull(fullname1,'') where leveal1=1

	UPDATE  #Bassert00 SET fullname='        '+isnull(fullname,'') where leveal=2
	UPDATE  #Bassert00 SET fullname1='        '+isnull(fullname1,'') where leveal1=2

	UPDATE  #Bassert00 SET fullname='            '+isnull(fullname,'') where leveal=3
	UPDATE  #Bassert00 SET fullname1='            '+isnull(fullname1,'') where leveal1=3

	UPDATE  #Bassert00 SET fullname='                '+isnull(fullname,'') where leveal=4
	UPDATE  #Bassert00 SET fullname1='                '+isnull(fullname1,'') where leveal1=4

	UPDATE  #Bassert00 SET fullname='                        '+isnull(fullname,'') where leveal=5
	UPDATE  #Bassert00 SET fullname1='                        '+isnull(fullname1,'') where leveal1=5

	select 
		isnull(typeid,'') as typeid,isnull(parid,'') as parid,isnull(usercode,'') as usercode,isnull(fullname,'') as fullname,isnull(sonnum,0) as sonnum,isnull(total,0) as total,
		isnull(typeid1,'') as typeid1,isnull(parid1,'') as parid1,isnull(fullname1,'') as fullname1,isnull(sonnum1,0) as sonnum1,isnull(total1,0) as total1
	from  #Bassert00
	
	end
end
else
begin
 if @szFlag='asset'  --获得树型资产负债表期初指
 begin
  select a.usercode,a.fullname,a.leveal,a.typeid,a.sysrow,a.sonnum,a.parid,
   (select isnull(sum(b.total00),0) from atype b
    where left(b.typeid,len(a.typeid))=a.typeid
   ) as 'Total',
 
   (select isnull(sum(b.total),0) from listtable b
    where left(b.atypeid,len(a.typeid))=a.typeid and billdate>=@begindate 
   ) as 'BqTotal'
 
  from atype a where (left(a.typeid,5)=@ASSETS_ID or left(a.typeid,5)=@DEBT_ID)  and a.deleted=0
 end
 else if @szFlag='bassert'  -- 历史平衡资产负债表
 begin
  select @dTotalIncom=isnull(sum(total),0) from monthatypehistory where left(atypeid,5)=@ALL_INCOME_ID AND Period = @szPeriod
  select @dTotalExpense=isnull(sum(total),0) from monthatypehistory where left(atypeid,5)=@ALL_EXPENSE_ID AND Period = @szPeriod update monthatypehistory set total=@dTotalIncom-@dTotalExpense where atypeid=@PROFIT_ID AND Period = @szPeriod

  select a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
   (select isnull(sum(b.total),0) from monthatypehistory b
    where b.atypeid=a.typeid AND b.Period = @szPeriod
   ) as 'Total' 
  from atype a where (left(a.typeid,5)=@ASSETS_ID or left(a.typeid,5)=@DEBT_ID or 
   (left(a.typeid,5)='00005' and a.typeid in ('00005','0000500001','0000500006')))  and a.deleted=0
 end
 if @szFlag='gain'  -- 历史损益表
 begin
delete from tmpgain where bqtotal=0
  select a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
   (select isnull(sum(b.total),0) from monthatypehistory b
    where b.atypeid=a.typeid AND b.Period = @szPeriod
   ) as 'Total',
  
   (select isnull(sum(b.bqtotal),0) from monthatypehistory b
    where b.atypeid=a.typeid AND b.Period = @szPeriod
   ) as 'BqTotal'
 
  from atype a where (left(a.typeid,5)=@ALL_INCOME_ID or left(a.typeid,5)=@ALL_EXPENSE_ID) and a.deleted=0
 end
end






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrDealinCircs_CarERP]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[Gp_qrDealinCircs_CarERP]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

-- 周华 2013-07-10 添加 内部应收
-- 周华 2013-07-19 添加 资产负债表 损益表 时间条件
-- 周华 2013-08-21 以分支机构初始化时间为标准判断是 固定资产是显示总和 还是 明细
-- 周华 2013-08-28 修改历史记录目录没有统计数据的问题
-- 周华 2013-09-27 资产负债表也调整计算合计的方式.
-- 周华 2013-12-17 性能优化，解决慢的问题
-- 周华 2014-02-25 调整资产负债表,历史记录 的其他资本为反算方式.
-- 周华 2014-03-13 9.4添加显示隐藏0功能

CREATE       PROCEDURE [dbo].[Gp_qrDealinCircs_CarERP]
(
	@OperatorID	varchar(50),		--操作员ID
	@szFlag		varchar(10)=null,
	@StypeId	varchar(max),		--分支机构id
	@szPeriod	varchar(2)='',
	@ifdate int=0,	-- 是否启用日期条件 如果@ifdate为2时 返回一个标识位 用于资产负债表
	@startdate VARCHAR(50)='',	-- 开时日期
	@enddate varchar(50)=''	-- 结束日期
	,@HideZero int=0	-- 0显示，1隐藏
	,@itemLeveal int = 10    --项目级次
)
--@encode$--
AS
set nocount on
declare  @GOODS_ID varchar(50),
@CASH_ID  varchar(50),
@CASH_BANK_ID varchar(50),
@AR_ID varchar(50),
@AP_ID varchar(50),
@GOODS_LOSS_ID varchar(50),
@GOODS_GET_ID varchar(50),
@ALLOT_PRICE_ID varchar(50),
@PRICE_INCOME_ID varchar(50),     
@BORROW_BUY_PRICE_ID varchar(50), 
@GOODS_GIVE_ID varchar(50),       
@GOODS_PRODUCE_ID varchar(50),    
@SALE_COST_ID varchar(50),        
@SALE_INCOME_ID varchar(50),      
@LEND_GOODS_ID varchar(50),       
@BORROW_GOODS_ID varchar(50),     
@BALANCE_ID varchar(50),          
@DEPRECIATION_ID varchar(50),     
@APPORTION_EXPENSE_ID varchar(50),
@INIT_MONEY_ID varchar(50),       
@ALL_INCOME_ID varchar(50),       
@ALL_EXPENSE_ID varchar(50),      
--@PROFIT_ID varchar(50),           
@ASSETS_ID varchar(50),           
@DEBT_ID varchar(50),             
@POWER_ID varchar(50),
@ADDEBT_INCOME_ID varchar(50),
@ADDEBT_LOSE_ID varchar(50),
@PAIDUPCAPITAL_ID varchar(50) --实收资本 
SELECT @GOODS_ID='0000100001'
SELECT @CASH_ID='0000100003'
SELECT @CASH_BANK_ID='0000100004'
SELECT @AR_ID='0000100005'
SELECT @AP_ID='0000200001'
SELECT @GOODS_LOSS_ID='000040000200001' --           商品报损
SELECT @GOODS_GET_ID='000030000200001'  --           商品报溢收入
SELECT @ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
SELECT @PRICE_INCOME_ID='000030000200003'--成本调价收入
-- SELECT @BORROW_BUY_PRICE_RECNO varchar(50)= 28;
-- SELECT @GOODS_GIVE_RECNO = 000040000200002           商品赠出
SELECT @GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
SELECT @SALE_COST_ID='0000400001'--              『销售成本』
SELECT @SALE_INCOME_ID='0000300001'--            『销售收入』
-- SELECT @LEND_GOODS_RECNO varchar(50),       = 21;
-- SELECT @BORROW_GOODS_RECNO varchar(50),     = 24;
SELECT @BALANCE_ID='000030000200004'--           进货退货差价
SELECT @DEPRECIATION_ID='000040000300002'--      固定资产折旧
SELECT @APPORTION_EXPENSE_ID='0000100007'--      待摊费用
-- SELECT @INIT_MONEY_RECNO varchar(50),       = 18;
SELECT @ALL_INCOME_ID='00003' --          【收入类】
SELECT @ALL_EXPENSE_ID='00004'--                 【支出类】
SELECT @ASSETS_ID ='00001'  --【资产合计】
SELECT @DEBT_ID='00002'   --【负债合计】
-- SELECT @POWER_RECNO varchar(50)            = 4;
SELECT @ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
SELECT @ADDEBT_LOSE_ID='000040000300001' --调帐亏损
SELECT @PAIDUPCAPITAL_ID='0000500001'   --实收资本
--SELECT @PROFIT_ID='0000500006'          --利润
SET @itemLeveal = @itemLeveal + 1
declare @BEGINdate datetime
declare @dTotalIncom  NUMERIC(24, 10) ,@dTotalExpense  NUMERIC(24, 10) 

DECLARE @proinfo varchar(5)
SELECT @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'


DECLARE @assetcard INT=0;
--DECLARE @assetcardIni INT=0;

-- 时间
DECLARE @sd DATETIME,@ed DATETIME;

SELECT @sd=CASE WHEN @startDate='' THEN  CAST('1900-01-01' AS DATE) ELSE cast(@startDate AS DATE) END,@ed= CASE WHEN @enddate='' THEN CAST('9999-12-31' AS DATE) ELSE CAST(@endDate AS DATE) END;

SELECT @sd=StartDate,@ed=enddate FROM dbo.MonthProc WHERE period=CAST(@szPeriod AS int) AND @szPeriod<>'' -- 历史记当的时间



CREATE TABLE #Stype (TypeID varchar(50),IfAssetsIni int)

IF @STypeID=''
BEGIN
	INSERT INTO #Stype(typeid,IfAssetsIni)  select a.typeid,b.IfAssetsIni from F_BaseGetManDetailSType(@OperatorID) a JOIN stype b ON a.typeid=b.TypeId;
END
ELSE
BEGIN
	INSERT INTO #Stype(typeid,IfAssetsIni)  select a.typeid,c.IfAssetsIni from F_BaseGetManDetailSType(@OperatorID) a 
		JOIN (select * from  dbo.f_split(@StypeID,',')) b on left(a.typeid,len(b.a))=b.a
		JOIN stype c ON a.typeid=c.TypeId
END

	--cte改成临时表
	CREATE TABLE #t1(atypeid NVARCHAR(50),stypeid NVARCHAR(1000),total  NUMERIC(24, 10) ,cid INT);
	CREATE TABLE #t2(atypeid NVARCHAR(50),stypeid NVARCHAR(1000),total00x  NUMERIC(24, 10) ,cid INT);

	INSERT INTO #t1 SELECT atypeid,stypeid,ISNULL(SUM(total),0) AS total ,cid FROM ListTable
	WHERE billdate BETWEEN @sd AND @ed AND STypeID IN ( SELECT typeId FROM #Stype )
	GROUP BY atypeid,stypeid,cid

	INSERT INTO #t2	SELECT atypeid,stypeid,ISNULL(SUM(total),0) AS total00x ,cid FROM ListTable
	WHERE billdate <@sd  AND STypeID IN ( SELECT typeId FROM #Stype )
	GROUP BY atypeid,stypeid,cid

--是否启用发票立账
DECLARE @isinvoice INT
SET @isinvoice = ISNULL((SELECT SubValue FROM dbo.sysdata WHERE SubName = 'isinvoice'),0)

	SELECT  p.nparid AS parid ,
			p.deleted ,
			p.leveal ,
			--2015-05-18 杨俊修改 因需求HH，强烈需要这样干，所以把[发出商品]放在[库存商品总值]下一行、[应付暂估]放在[应付合计]下一行
			p.ntypeId AS typeid,
			CASE FullName
				WHEN '发出商品' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '库存商品总值') + '1'
				WHEN '应付暂估' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '应付合计') + '1'
				ELSE p.ntypeId
			END AS ordertypeid,
			--p.ntypeId AS typeid ,
			p.Sysrow ,
			p.UserCode ,
			p.FullName ,
			p.sonnum ,
			ISNULL(s.Total,0) AS total ,
			ISNULL(s.Total00,0) AS total00 ,
			nId
	INTO    #Atype
	FROM    dbo.Ac_Items p
			LEFT JOIN ( SELECT  w.atypeid ,
								ISNULL(SUM(total), 0)+ISNULL(SUM(total00x),0)+ISNULL(SUM(total00), 0) AS total , -- 期末
								ISNULL(SUM(total00x),0)+ISNULL(SUM(total00), 0) AS total00  --期初
						FROM    --AType_Total
						(
							SELECT ISNULL(a.atypeid,b.atypeid) AS atypeid,ISNULL(a.total,0) AS total,ISNULL(a.stypeid,b.STypeID) AS stypeid
							,ISNULL(b.total00,0) AS total00,ISNULL(c.total00x,0) AS total00x FROM #t1 a 
								FULL JOIN dbo.AType_Total b ON a.atypeid=b.atypeid AND a.stypeid=b.stypeid AND a.cid=b.cid
								LEFT JOIN #t2 c ON ISNULL(a.atypeid,b.atypeid)=c.atypeid AND ISNULL(a.stypeid,b.STypeID)=c.stypeid AND ISNULL(a.cid,b.cid)=c.cid
						) w
						WHERE w.stypeid IN (SELECT typeid FROM #Stype)
						GROUP BY ATypeID
					  ) s ON s.ATypeID = p.nId
	WHERE   p.ntypeId <> '00000'
		AND (NOT(@isinvoice = 0)--是否启用发票立账
		OR (@isinvoice = 0) AND P.UserCode NOT IN('1251','2122'))
		
		
--
	CREATE TABLE #gdzc
	(
	  nid INT,
	  ntypeid VARCHAR(50)
	)
	INSERT INTO #gdzc ( nid, ntypeid )
		SELECT nid,ntypeid FROM dbo.Ac_Items WHERE ntypeid LIKE '0000100002%'
	
	 SELECT  w.stypeid,
			ISNULL(SUM(total), 0)+ISNULL(SUM(total00x),0)+ISNULL(SUM(total00), 0) AS total , -- 期末
			ISNULL(SUM(total00x),0)+ISNULL(SUM(total00), 0) AS total00,  --期初
			w.atypeid AS nid
	 INTO #AtypeX
	 FROM    
			(
				SELECT a.atypeid,ISNULL(b.total,0) AS total,a.stypeid AS stypeid
						,ISNULL(a.total00,0) AS total00,ISNULL(c.total00x,0) AS total00x
				FROM AType_Total a 
				LEFT JOIN #t1 b ON a.atypeid=b.atypeid AND a.stypeid=b.stypeid AND a.cid=b.cid
				LEFT JOIN #t2 c ON a.ATypeID=c.atypeid AND a.stypeid=c.stypeid AND a.CID=c.cid
				WHERE a.stypeid IN (SELECT typeid FROM #Stype)
				AND a.ATypeID IN(SELECT nid FROM #gdzc)
			) w
	 GROUP BY Stypeid,ATypeID

--	

--9.1中ac_items中没有这两个科目，需手动添加
		--手动添加'【所有者权益】'
		--INSERT INTO #Atype (parid,Deleted,Leveal,typeid,Sysrow,UserCode,FullName,SonNum,total,total00,nId) VALUES ('00000',0 ,1,'00005',0,'05','【所有者权益】',5 ,0,0,99999)
		--手动添加'『实收资本』'
		--INSERT INTO #Atype (parid,Deleted,Leveal,typeid,Sysrow,UserCode,FullName,SonNum,total,total00,nId) VALUES ('00005',0 ,2,'0000500001',0,'3101','『实收资本』',0,0,0,99998)

SELECT  m.period ,
        m.ATypeID ,
        a.typeid,
        SUM(ISNULL(m.total, 0)) AS Total ,
        SUM(ISNULL(m.bqtotal, 0)) AS bqTotal
INTO    #monthatypehistory
FROM    monthatypehistory m LEFT JOIN #Atype a ON a.nid=m.ATypeID
WHERE   StypeId IN ( SELECT typeid
                     FROM   #Stype )
GROUP BY m.StypeId ,
        m.period ,
        m.ATypeID,
        a.typeid



DECLARE @period VARCHAR(100)
SELECT @period=MAX(period) FROM monthatypehistory
		
--以stypeid聚合tmpgain表 修改人：赵斌 去掉tmpGain这张表 2012.01.31 
/*SELECT	l.AtypeId as typeid,
		isnull(sum(l.Total),0)-isnull(m.Total,0) as bqtotal 
INTO	#tmpGain
FROM	ListTable L LEFT JOIN (
									SELECT	period,
											ATypeID,
											Stypeid,
											SUM(Total ) AS Total
									FROM	monthatypehistory
									WHERE period=@period
									GROUP BY ATypeID,Stypeid,period
								)m ON L.AtypeId = m.ATypeID and l.STypeID = m.Stypeid
WHERE	l.STypeID IN(SELECT typeId FROM #Stype) 
GROUP BY l.AtypeId,m.Total
*/
-- 控制显示 
-- 资产负债表调整成分支机构合计的方式 --
DECLARE @display_1 INT=0;
DECLARE @sysDate DATETIME;

SELECT @sysDate=MIN(startdate) FROM dbo.MonthProc WHERE period=1;

DECLARE @stypeinfo_1 TABLE(stypeid VARCHAR(100),iniDate DATETIME,iscard INT,val  NUMERIC(24, 10) );
INSERT INTO @stypeinfo_1 SELECT a.typeid,b.InitDate,0,0.0 FROM #stype a LEFT JOIN (
	SELECT u.*,v.typeid FROM Ac_FixedAssetsInit_Stype u JOIN stype v ON u.stypeid=v.VerifyID
) b ON a.typeid=b.typeid;

--卡片模式才统计卡片的数据
IF  EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
BEGIN

	-- 取卡片的
	UPDATE @stypeinfo_1 SET iscard=1 WHERE iniDate>@sysDate AND @ed>=iniDate OR iniDate<=@sysDate;

	SELECT @display_1=1 WHERE EXISTS(SELECT 1 FROM @stypeinfo_1 WHERE iscard=1) --显示为卡片

	-- 卡片数据
	;WITH cte AS (
		SELECT rn=ROW_NUMBER() over(PARTITION BY STypeId,AssertsCardId ORDER BY BusinessDate desc,id desc),Id,STypeId,AssertsCardId,NetValue,a.BillType FROM Ac_AssetsCards_History a WHERE CAST(a.BusinessDate AS date)<=@ed AND a.audittype NOT IN (-3,-4)
		AND a.STypeId IN (SELECT typeid FROM #stype)
	)
	UPDATE a SET a.val=b.NetValue FROM @stypeinfo_1 a JOIN (
	SELECT stypeid,SUM(netvalue) AS netvalue FROM cte WHERE rn=1 AND (billtype<>213 OR billtype IS NULL) GROUP BY stypeid
	) b ON a.stypeid=b.stypeid WHERE a.iscard=1
END
-- 项目数据
UPDATE a SET a.val=b.total FROM @stypeinfo_1 a JOIN (SELECT stypeid,ISNULL(SUM(total),0) AS total FROM #atypex GROUP BY stypeid) b ON a.stypeid=b.stypeid
WHERE a.iscard=0

-- 
--SELECT * FROM @stypeinfo_1;
--SELECT @display_1;

IF @ifDate=2
BEGIN
	IF NOT EXISTS(SELECT 1 FROM @stypeinfo_1 WHERE iscard=0) --全部卡片
		SELECT 1 AS datacase
	ELSE IF EXISTS(SELECT 1 FROM @stypeinfo_1 WHERE iscard=1) --混合的
		SELECT 2 AS datacase
	ELSE --项目
		SELECT 0 AS datacase
END



IF @szFlag='bassert'
BEGIN
 --资产
create table #Tmp
(
	id   int IDENTITY (1,1),
	usercode varchar(300),
	fullname varchar(300),
	leveal int,
	typeid varchar(50),
	sonnum int,
	parid varchar(50),  
	total  NUMERIC(24, 10) ,      
)
--负债
create table #Tmp1
(
	id   int IDENTITY (1,1),
	fullname1 varchar(300),
	leveal1 int,
	total1  NUMERIC(24, 10) ,
	parid1 varchar(50),
	typeid1 varchar(50),
	Sonnum1 int       
)
--资产负债
create table #Tmp2
(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	usercode varchar(300),
	fullname varchar(300),
	leveal int,
	typeid varchar(50),
	sonnum int,
	parid varchar(50),
	total  NUMERIC(24, 10) ,
	fullname1 varchar(300),
	leveal1 int,
	total1  NUMERIC(24, 10) ,
	parid1 varchar(50),
	typeid1 varchar(50),
	Sonnum1 int              
)
END


IF @szperiod=''
BEGIN
	SELECT @BEGINdate=startdate FROM monthproc WHERE monthno like '本期'
	IF @szFlag='gain'  -- 损益表 --有时间条件
	BEGIN
		--SELECT '损益表'
		CREATE TABLE #gain(usercode varchar(300),fullname varchar(300),leveal int,typeid varchar(50),sonnum int,parid varchar(50),total  NUMERIC(24, 10) ,bqtotal  NUMERIC(24, 10) )	

		INSERT INTO #gain
		SELECT a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
	   ISNULL(a.total,0),
		(	
			--SELECT isnull(sum(b.bqtotal),0) 
			--FROM #tmpGain b
			--WHERE  b.typeid=a.nid
			-- 本期 =期末-期初
			a.total-a.total00
		) as 'BqTotal'
		FROM #Atype a 
		WHERE (left(a.typeid,5)=@ALL_INCOME_ID or left(a.typeid,5)=@ALL_EXPENSE_ID)

		INSERT INTO #gain(usercode,fullname,leveal,typeid,sonnum,parid,total,bqtotal) SELECT '','【利    润】',1,'999999999999999',0,'',(select sum(case when typeid LIKE'00003%' then total else -total end) as total from #gain),(select sum(case when typeid LIKE '00003%' then bqtotal else -bqtotal end) as bqtotal from #gain)
		update #gain set fullname ='    '+fullname where leveal =2
		update #gain set fullname ='        '+fullname where leveal =3
		update #gain set fullname ='            '+fullname where leveal =4
		update #gain set fullname ='                '+fullname where leveal =5
		update #gain set fullname ='                    '+fullname where leveal =6
		update #gain set fullname ='                        '+fullname where leveal =7
		update #gain set fullname ='                            '+fullname where leveal =8
		update #gain set fullname ='                                '+fullname where leveal =9
		update #gain set fullname ='                                    '+fullname where leveal =10

	;WITH cte AS
	(
		SELECT usercode,fullname,leveal,typeid,sonnum,parid,total,bqtotal
		FROM #gain
		--WHERE parid='00000'
		UNION ALL
		SELECT c.usercode,c.fullname,c.leveal,c.typeid,c.sonnum,c.parid,d.total,d.bqtotal
		FROM #gain AS C
		INNER JOIN cte AS D
			ON C.typeid=D.parid
	),c1 AS (
		SELECT #gain.usercode,#gain.fullname,#gain.leveal,#gain.typeid,#gain.sonnum,#gain.parid,SUM(ISNULL(cte.TOTAL,0)) TOTAL,
		SUM(ISNULL(cte.bqtotal,0)) bqtotal  
		FROM #gain INNER JOIN cte
		ON #gain.typeid=cte.typeid 
		GROUP BY #gain.usercode,#gain.fullname,#gain.leveal,#gain.typeid,#gain.sonnum,#gain.parid
	)
	SELECT b.usercode,b.fullname,b.leveal,a.typeid,b.sonnum,b.parid,A.TOTAL,a.bqtotal INTO #tempGainTable FROM 
	c1 A LEFT JOIN #gain B ON A.typeid=B.typeid
	WHERE @hidezero=1 AND (a.bqtotal<>0 OR a.TOTAL<>0) 
			AND NOT EXISTS (SELECT 1 FROM c1 b WHERE a.typeid LIKE b.typeid+'%' AND b.bqtotal=0 AND b.total=0 AND b.sonnum<>0)
		OR @hidezero=0 
	ORDER BY A.typeid
	--ORDER BY A.ordertypeid
	SELECT * FROM #tempGainTable WHERE leveal<=@itemLeveal
	DROP TABLE #tempGainTable
	
	END 
	ELSE IF @szFlag='asset'  -- 树型资产负债表(带本期值) 
	BEGIN
		SELECT a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
			(	SELECT isnull(sum(b.total),0) FROM #atype b
				WHERE left(b.typeid,len(a.nTypeId))=a.nTypeId
			) as 'Total',
			
			(	SELECT isnull(sum(b.total),0) FROM listtable b
				WHERE b.atypeid=a.nId and billdate>=@BEGINdate 
			) as 'BqTotal'
		FROM #Atype a WHERE (left(a.nTypeId,5)=@ASSETS_ID or left(a.nTypeId,5)=@DEBT_ID)
	END 
	ELSE IF @szFlag='bassert'  -- 平衡资产负债表 --有时间条件
	BEGIN
	--SELECT '资产负债表'
		SELECT @dTotalIncom=isnull(sum(total),0) FROM #Atype WHERE left(typeid,5)=@ALL_INCOME_ID
		SELECT @dTotalExpense=isnull(sum(total),0) FROM #Atype WHERE left(typeid,5)=@ALL_EXPENSE_ID
		--update #Atype set total=@dTotalIncom-@dTotalExpense WHERE typeid=@PROFIT_ID
		

		Create TABLE #Bassert
		(
			[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
			usercode varchar(300),
			fullname varchar(300),
			leveal int,
			typeid varchar(50),
			sonnum int,
			parid varchar(50),
			total  NUMERIC(24, 10) ,
			fullname1 varchar(300),
			leveal1 int,
			total1  NUMERIC(24, 10) ,
			parid1 varchar(50),
			typeid1 varchar(50),
			Sonnum1 int
		)
		DECLARE @MaxID int
		SET @MaxID =0

		INSERT  INTO #Bassert
				( usercode ,
				  fullname ,
				  leveal ,
				  typeid ,
				  sonnum ,
				  parid ,
				  total
				)
				SELECT  a.usercode ,
						a.fullname ,
						a.leveal ,
						a.typeid ,
						a.sonnum ,
						a.parid ,
						( SELECT    ISNULL(SUM(b.total), 0)
						  FROM      #Atype b
						  WHERE     LEFT(b.typeid, LEN(a.typeid)) = a.typeid
						) AS 'Total'
				FROM    #Atype a
				WHERE   LEFT(a.typeid, 5) = @ASSETS_ID
						AND a.typeid <> '0000200002'
						AND a.typeid <> '0000100006'
						-- 卡片管理 固定资产
						AND (@display_1=1 
								AND (a.typeid NOT LIKE '0000100002%' OR a.typeid ='0000100002')
							OR @display_1<>1)
						AND a.usercode NOT IN ('SYC-1601','SYC-1602')
				--ORDER BY a.typeid
				ORDER BY a.ordertypeid
		SET @MaxID =@@Rowcount

	--SELECT  * FROM #Bassert
	
		DECLARE @fullname1 varchar(300)
		DECLARE @leveal1 int
		DECLARE @Total1  NUMERIC(24, 10) 
		DECLARE @typeid1 varchar(50)
		DECLARE @parid1 varchar(50)
		DECLARE @sonnum1 int
		DECLARE @j int
		SET @j =1
		DECLARE BassCurSor CURSOR FOR	
		SELECT a.fullname,a.leveal,a.typeid,a.parid,a.sonnum,
		(
			SELECT isnull(sum(b.total),0) FROM #Atype b
			WHERE left(b.typeid,len(a.typeid))=a.typeid
		) as 'Total' 
		FROM #Atype a WHERE a.typeid<>'0000200002' and a.typeid<>'0000100006' and (left(a.typeid,5)=@DEBT_ID
			or (left(a.typeid,5)='00005' /*and a.typeid in ('00005','0000500001','0000500006')*/))
			--AND a.typeid <> '0000200010' AND  a.typeid <> '0000200011'
		--order by a.typeid
		order by a.ordertypeid
		
		OPEN BassCurSor
		FETCH NEXT FROM BassCurSor INTO @fullname1,@leveal1,@typeid1,@parid1,@sonnum1,@Total1
		WHILE @@FETCH_STATUS =0
		BEGIN
		IF @j<=@MaxID
		BEGIN
			UPDATE #Bassert SET fullname1=@fullname1,leveal1=@leveal1,total1=@Total1,typeid1=@typeid1,parid1=@parid1,sonnum1=@sonnum1 WHERE [ID]=@j
		END	
		ELSE
		BEGIN
			INSERT INTO #Bassert(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) SELECT @fullname1,@leveal1,@Total1,@typeid1,@parid1,@sonnum1
		END
		SET @j = @j + 1
		FETCH NEXT FROM BassCurSor INTO @fullname1,@leveal1,@typeid1,@parid1,@sonnum1,@Total1
		END
		CLOSE BassCurSor
		DEALLOCATE BassCurSor
		

		-- 修改库存总值
		UPDATE #Bassert SET total=(SELECT isnull(Total,0) as total FROM #Atype  WHERE typeid='0000100001' ) WHERE typeid='0000100001'
		
		--应收账款合计
		UPDATE #Bassert SET total=(  SELECT total FROM #atype WHERE nid=33
		--SELECT sum(isnull(artotal,0)) 
									--FROM BType_ARAPTotal  
									--where STypeID in(select typeid from #Stype) 
									/*SELECT ISNULL(SUM(total),0) FROM dbo.ListTable 
									WHERE atypeid=33 AND STypeID IN (SELECT typeid FROM #stype)
									AND billdate BETWEEN @sd AND @ed --这个同 billdate<=@ed
									)+(
										SELECT ISNULL(SUM(ARTotal00),0) FROM BType_ARAPTotal WHERE STypeID in(select typeid from #Stype)*/ 
									)
		WHERE typeid='0000100005'
		
		-- 内部应收合计
		UPDATE #Bassert SET total=(
				--SELECT ISNULL(SUM(innerArTotal),0) FROM dbo.SType_InnerARTotal WHERE stypeid IN (SELECT typeid FROM #stype)
				SELECT ISNULL(SUM(total),0) FROM dbo.ListTable
				WHERE atypeid=28 AND stypeid IN (SELECT typeid FROM #stype)
				AND billdate BETWEEN @sd AND @ed --同 billdate<=@ed
			)+(
				SELECT ISNULL(SUM(InnerARTotal00),0) FROM dbo.SType_InnerARTotal WHERE stypeid IN (SELECT typeid FROM #stype)
			)
		WHERE typeid='0000100010'

		IF(@display_1=1)
		BEGIN
			UPDATE #Bassert SET total=(
				SELECT SUM(val) FROM @stypeinfo_1
			)
			WHERE typeid='0000100002'
		END
				
		-- 资产合计
		UPDATE #Bassert SET total=(SELECT sum(isnull(total,0)) FROM #Bassert WHERE parid='00001' ) WHERE typeid='00001'
		
		--应付款合计
		UPDATE #Bassert SET total1=(
									SELECT total FROM #atype WHERE nid=35
									--SELECT sum(aptotal) FROM BType_ARAPTotal 
									--WHERE   STypeID in(select typeid from #Stype)
									/*SELECT ISNULL(SUM(total),0) FROM dbo.ListTable
									WHERE atypeid=35 AND stypeid IN (SELECT typeid FROM #stype)
									AND billdate BETWEEN @sd AND @ed
									)+(
										SELECT SUM(APTotal00) FROM BType_ARAPTotal WHERE  STypeID in(select typeid from #Stype)	*/						
									)
		WHERE typeid1='0000200001'
		
		-- 修改负债合计
		UPDATE #Bassert SET total1=(SELECT sum(isnull(Total1,0)) as total FROM #Bassert WHERE  typeid1 NOT in ('0000200001','0000200002') AND LEFT(parid1,5)='00002' and sonnum1=0 ) WHERE typeid1='00002'
		UPDATE #Bassert SET total1=total1+(SELECT sum(isnull(Total1,0)) as total FROM #Bassert WHERE  typeid1 ='0000200001' ) WHERE typeid1='00002' -- +应付
		
		
		-- 未分配利润
		UPDATE #Bassert SET total1=total1+((SELECT ISNULL(sum(total),0)-ISNULL(SUM(total00),0) FROM #Atype WHERE typeid like '00003%' and sonnum=0)-(SELECT ISNULL(sum(total),0)-ISNULL(SUM(total00),0) FROM #Atype WHERE typeid like '00004%' and sonnum=0)) WHERE typeid1='0000500005'
			
		-- 修改所有者权益 = 资产-负债
		UPDATE #Bassert SET total1=(SELECT total FROM #Bassert WHERE typeid in ('00001'))-(SELECT total1 FROM #Bassert WHERE typeid1 in ('00002') ) WHERE typeid1='00005'

		--其他资本
		UPDATE #Bassert SET total1=(SELECT total1 FROM #Bassert WHERE typeid1 ='00005')-(SELECT ISNULL(SUM(total1),0) FROM #Bassert WHERE typeid1 LIKE '00005%' AND typeid1<>'0000500002' AND sonnum1=0) WHERE typeid1='0000500002'
		
		/*
		--实收资本 == 所有者权益 - 利润 （=收入-支出）
		UPDATE #Bassert SET total1=(SELECT total1 FROM #Bassert WHERE typeid1='00005')- ((SELECT ISNULL(sum(total),0) FROM #Atype WHERE typeid like '00003%' and sonnum=0)-(SELECT ISNULL(sum(total),0) FROM #Atype WHERE typeid like '00004%' and sonnum=0)) WHERE typeid1='0000500001'


		--添加利润项
		IF @j<=@MaxID
		BEGIN
			UPDATE #Bassert SET fullname1='利  润',leveal1=1,total1=((SELECT sum(isnull(total,0)) FROM #Atype WHERE typeid like '00003%' and sonnum=0)-(SELECT sum(isnull(total,0)) FROM #Atype WHERE typeid like '00004%' and sonnum=0)),typeid1='0000500004',parid1='00005',sonnum1=0 WHERE [ID]=@j
		END	
		ELSE
		BEGIN
			INSERT INTO #Bassert(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) SELECT '利  润',1,((SELECT sum(isnull(total,0)) FROM #Atype WHERE typeid like '00003%' and sonnum=0)-(SELECT sum(isnull(total,0)) FROM #Atype WHERE typeid like '00004%' and sonnum=0)),'0000500004','00005',0
		END
		*/
		
		UPDATE  #Bassert SET fullname='    '+isnull(fullname,'') WHERE leveal=2 
		UPDATE  #Bassert SET fullname1='    '+isnull(fullname1,'') WHERE leveal1=2
		
		UPDATE  #Bassert SET fullname='        '+isnull(fullname,'') WHERE leveal=3
		UPDATE  #Bassert SET fullname1='        '+isnull(fullname1,'') WHERE leveal1=3
		
		UPDATE  #Bassert SET fullname='            '+isnull(fullname,'') WHERE leveal=4
		UPDATE  #Bassert SET fullname1='            '+isnull(fullname1,'') WHERE leveal1=4
		
		UPDATE  #Bassert SET fullname='                '+isnull(fullname,'') WHERE leveal=5
		UPDATE  #Bassert SET fullname1='                '+isnull(fullname1,'') WHERE leveal1=5

		UPDATE  #Bassert SET fullname='                    '+isnull(fullname,'') WHERE leveal=6
		UPDATE  #Bassert SET fullname1='                    '+isnull(fullname1,'') WHERE leveal1=6

		UPDATE  #Bassert SET fullname='                        '+isnull(fullname,'') WHERE leveal=7
		UPDATE  #Bassert SET fullname1='                        '+isnull(fullname1,'') WHERE leveal1=7

		UPDATE  #Bassert SET fullname='                            '+isnull(fullname,'') WHERE leveal=8
		UPDATE  #Bassert SET fullname1='                            '+isnull(fullname1,'') WHERE leveal1=8

		UPDATE  #Bassert SET fullname='                                '+isnull(fullname,'') WHERE leveal=9
		UPDATE  #Bassert SET fullname1='                                '+isnull(fullname1,'') WHERE leveal1=9

		UPDATE  #Bassert SET fullname='                                    '+isnull(fullname,'') WHERE leveal=10
		UPDATE  #Bassert SET fullname1='                                    '+isnull(fullname1,'') WHERE leveal1=10	

		IF @hidezero=1
		BEGIN
			;WITH c1 AS (
				SELECT rn=ROW_NUMBER() OVER(ORDER BY a.id),ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname,ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE ISNULL(a.total,0) END AS total ,a.Leveal
				FROM #Bassert a WHERE ISNULL(a.total,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #bassert b WHERE a.typeid like b.typeid+'%' AND b.total=0 AND b.sonnum<>0 )
			),c2 AS (
				SELECT rn=ROW_NUMBER() OVER(ORDER BY id), ISNULL(a.typeid1,'') AS typeid1,ISNULL(a.parid1,'') AS parid1,ISNULL(a.fullname1,'') AS fullname1,ISNULL(a.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(typeid1,'')='' THEN total1 ELSE  ISNULL(total1,0) END AS total1,a.Leveal1
				FROM #Bassert a WHERE ISNULL(total1,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #bassert b WHERE a.typeid1 LIKE b.typeid1+'%' AND b.total1=0 AND b.sonnum<>0 )
			)
			INSERT INTO #Tmp2
           ( typeid,parid,usercode , fullname , sonnum,total,  typeid1 ,  parid1 , fullname1 , Sonnum1,total1 ,leveal , leveal1)
			SELECT ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname, ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE  ISNULL(a.total,0) END  AS total
			,ISNULL(b.typeid1,'') AS typeid1,ISNULL(b.parid1,'') AS parid1,ISNULL(b.fullname1,'') AS fullname1,ISNULL(b.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(b.typeid1,'')='' THEN b.total1 ELSE ISNULL(b.total1,0) end AS total1 ,a.Leveal,b.Leveal1
			FROM c1 a FULL JOIN c2 b ON a.rn=b.rn;
			--SELECT * FROM #Tmp2
		END
		ELSE
		BEGIN
			INSERT INTO #Tmp2
           ( typeid,parid,usercode , fullname , sonnum,total,  typeid1 ,  parid1 , fullname1 , Sonnum1,total1 ,leveal , leveal1)
			SELECT 
				isnull(typeid,'') as typeid,isnull(parid,'') as parid,isnull(usercode,'') as usercode,isnull(fullname,'') as fullname,isnull(sonnum,0) as sonnum,case when isnull(typeid,'')='' then total else isnull(total,0)  end as total,
				isnull(typeid1,'') as typeid1,isnull(parid1,'') as parid1,isnull(fullname1,'') as fullname1,isnull(sonnum1,0) as sonnum1,case when isnull(typeid1,'')='' then total1 else isnull(total1,0)  end as total1,Leveal,Leveal1
			FROM  #Bassert
			DROP TABLE #Bassert
		END
	END
	ELSE IF @szFlag='bassert00'  -- 平衡资产负债表期初
	BEGIN
		declare @dTotalIncom00  NUMERIC(24, 10) ,@dTotalExpense00  NUMERIC(24, 10) 
		SELECT @dTotalIncom00=isnull(sum(total00),0) FROM #atype WHERE left(typeid,5)=@ALL_INCOME_ID
		SELECT @dTotalExpense00=isnull(sum(total00),0) FROM #atype WHERE left(typeid,5)=@ALL_EXPENSE_ID
		--Update #atype set total=@dTotalIncom00-@dTotalExpense00 WHERE typeid=@PROFIT_ID
		
		Create TABLE #Bassert00
		(
		[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
		usercode varchar(300),
		fullname varchar(300),
		leveal int,
		typeid varchar(50),
		sonnum int,
		parid varchar(50),
		total  NUMERIC(24, 10) ,
		fullname1 varchar(300),
		leveal1 int,
		total1  NUMERIC(24, 10) ,
		parid1 varchar(50),
		typeid1 varchar(50),
		Sonnum1 int
		)
		DECLARE @MaxID1 int
		SET @MaxID1 =0
		
		
		-- 期初固定资产计算 --
		-- 准备条件数据
		DECLARE @display INT=0;
		DECLARE @stypeinfo TABLE(stypeid VARCHAR(100),ifassetsini INT,ifopen INT,iscard INT,val  NUMERIC(24, 10) );
		INSERT INTO @stypeinfo SELECT a.typeid,a.ifassetsini,ISNULL(b.VALUE,0),0,0.0 FROM #stype a LEFT JOIN Stype_UserConfig b ON a.typeid=b.stypeid;

		UPDATE @stypeinfo SET iscard=1 
		WHERE ifassetsini=0 AND ifopen=0 AND EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')--未开账初始化 看配置
		OR ifopen=0 AND ifassetsini=1; --未开账 初始化
		
		UPDATE a SET a.iscard=1
		FROM @stypeinfo a JOIN 
		(SELECT u.*,v.typeid FROM Ac_FixedAssetsInit_Stype u JOIN stype v ON u.stypeid=v.VerifyID) b --处理非独立核算的
		ON a.stypeid=b.typeid
		WHERE a.ifopen=1 AND ifassetsini=1
		AND (SELECT MIN(startdate) FROM dbo.MonthProc WHERE period=1)>=b.InitDate --未开账,初始化 或 开账 初始化和时间判断
		
		-- 显示
		SELECT @display=1 WHERE EXISTS(SELECT 1 FROM @stypeinfo WHERE iscard=1) --显示为卡片
		
		-- 计算数据 卡片
		UPDATE a SET a.val=b.netvalue FROM @stypeinfo a JOIN (SELECT stypeid,ISNULL(SUM(w.netvalue),0) AS netvalue FROM Ac_AssetsCards w WHERE w.AssetsState IN(1,4) GROUP BY w.STypeId) b ON a.stypeid=b.stypeid
		WHERE a.iscard=1 AND ifassetsini=0; -- 卡片显示,未初始化的情况
							
		;WITH cte AS (
			SELECT rn=ROW_NUMBER() OVER(PARTITION BY AssertsCardId ORDER BY Id desc),* FROM Ac_AssetsCards_History WHERE BillType=0
		)
		UPDATE a SET a.val=b.netvalue FROM @stypeinfo a JOIN (SELECT stypeid,ISNULL(SUM(netvalue),0) AS netvalue FROM cte WHERE rn=1 GROUP BY stypeid) b ON a.stypeid=b.stypeid
		WHERE a.iscard=1 AND ifassetsini=1 -- 卡片显示,初始化的情况	

		-- 计算项目数据
		UPDATE a SET a.val=b.total00 FROM @stypeinfo a JOIN (SELECT stypeid,ISNULL(SUM(total00),0) AS total00 FROM #atypex GROUP BY stypeid) b ON a.stypeid=b.stypeid
		WHERE a.iscard=0
		--
		
		INSERT  INTO #Bassert00
				( usercode ,
				  fullname ,
				  leveal ,
				  typeid ,
				  sonnum ,
				  parid ,
				  total
				)
				SELECT  a.usercode ,
						a.fullname ,
						a.leveal ,
						a.typeid ,
						a.sonnum ,
						a.parid ,
						( SELECT    ISNULL(SUM(b.total00), 0)
						  FROM      #Atype b
						  WHERE     LEFT(b.typeid, LEN(a.typeid)) = a.typeid
						) AS 'Total'
				FROM    #Atype a
				WHERE   LEFT(a.typeid, 5) = @ASSETS_ID
						AND a.typeid <> '0000200002'
						AND a.typeid <> '0000100006'
	                    
						-- 卡片管理 固定资产
						AND (@display=1 
								AND (a.typeid NOT LIKE '0000100002%' OR a.typeid ='0000100002')
							OR @display<>1)
							
						AND a.usercode NOT IN ('SYC-1601','SYC-1602')
				--ORDER BY a.typeid
				ORDER BY a.ordertypeid
		SET @MaxID1 =@@Rowcount

		DECLARE @fullname varchar(300)
		DECLARE @leveal int
		DECLARE @Total  NUMERIC(24, 10) 
		DECLARE @typeid varchar(50)
		DECLARE @parid varchar(50)
		DECLARE @sonnum int
		DECLARE @i int
		SET @i =1
		DECLARE BassCurSor CURSOR FOR	
		SELECT  a.fullname ,
				a.leveal ,
				a.typeid ,
				a.parid ,
				a.sonnum ,
				( SELECT    ISNULL(SUM(b.total00), 0)
				  FROM      #Atype b
				  WHERE     LEFT(b.typeid, LEN(a.typeid)) = a.typeid
				) AS 'Total'
		FROM    #atype a
		WHERE   a.typeid <> '0000200002'
				AND a.typeid <> '0000100006'
				AND ( LEFT(a.typeid, 5) = @DEBT_ID
					  OR ( LEFT(a.typeid, 5) = '00005'
						   /*AND a.typeid IN ( '00005', '0000500001', '0000500006' )*/
						 )
					)

		--ORDER BY a.typeid
		ORDER BY a.ordertypeid
		OPEN BassCurSor
		FETCH NEXT FROM BassCurSor INTO @fullname,@leveal,@typeid,@parid,@sonnum,@Total
		WHILE @@FETCH_STATUS =0
		BEGIN
		IF @I<=@MaxID1
		BEGIN
			UPDATE #Bassert00 SET fullname1=@fullname,leveal1=@leveal,total1=@Total,typeid1=@typeid,parid1=@parid,sonnum1=@sonnum WHERE [ID]=@i
		END	
		ELSE
		BEGIN
			INSERT INTO #Bassert00(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) VALUES(@fullname,@leveal,@total,@typeid,@parid,@sonnum)
		END
		SET @i = @i + 1
		FETCH NEXT FROM BassCurSor INTO @fullname,@leveal,@typeid,@parid,@sonnum,@Total
		END
		CLOSE BassCurSor
		DEALLOCATE BassCurSor

		-- 修改应收款合计
		--UPDATE #Bassert00 SET total=(SELECT sum(artotal00) FROM BType_ARAPTotal WHERE btypeid like '00001%' and STypeID in(select typeid from #Stype) ) WHERE typeid='0000100005'
		UPDATE #Bassert00 SET total=(SELECT sum(isnull(artotal00,0)) FROM BType_ARAPTotal  where STypeID in(select typeid from #Stype) ) WHERE typeid='0000100005'
		
		-- 内部应收合计
		UPDATE #Bassert00 SET total=(SELECT ISNULL(SUM(innerArTotal00),0) FROM dbo.SType_InnerARTotal WHERE stypeid IN (SELECT typeid FROM #stype)) WHERE typeid='0000100010'

		-- 固定资产 卡片管理 更新

		IF(@display=1)
		BEGIN
			UPDATE #Bassert00 SET total=(
				SELECT SUM(val) FROM @stypeinfo
			)
			WHERE typeid='0000100002'
		END
		
		
		-- 修改库存总值
		UPDATE #Bassert00 SET total=(SELECT sum(isnull(i.Total,0)) as total FROM inigoodsstocks i inner join stock s on i.KtypeId=s.typeId where s.STypeID in(select typeId from #Stype)  ) WHERE typeid='0000100001'
		-- 修改委托代销期初
		UPDATE #Bassert00 SET total=(SELECT sum(isnull(CostTotal,0)) as total FROM inicommissionstock WHERE type=140 and STypeID in (select typeid from #Stype) ) WHERE typeid='0000100008'
		
		-- 资产合计
		UPDATE #Bassert00 SET total=(SELECT sum(isnull(total,0)) FROM #Bassert00 WHERE parid='00001' ) WHERE typeid='00001'
		
		-- 修改应付款合计
		--UPDATE #Bassert00 SET total1=(SELECT sum(aptotal00) FROM BType_ARAPTotal WHERE  BTypeID like '00002%' and STypeID in(select typeid from #Stype)) WHERE typeid1='0000200001'
		UPDATE #Bassert00 SET total1=(SELECT sum(aptotal00) FROM BType_ARAPTotal WHERE   STypeID in(select typeid from #Stype)) WHERE typeid1='0000200001'
		-- 修改代销商品期初
		UPDATE #Bassert00 SET total1=(SELECT sum(isnull(Total,0)) as total FROM inicommissionstock WHERE type=144 and STypeID in (select typeid from #Stype)) WHERE typeid1='0000200003'
		
		-- 修改负债合计
		UPDATE #Bassert00 SET total1=(SELECT sum(isnull(Total1,0)) as total FROM #Bassert00 WHERE  typeid1 NOT in ('0000200001','0000200002','0000200003') AND LEFT(parid1,5)='00002' and sonnum1=0 ) WHERE typeid1='00002'
		UPDATE #Bassert00 SET total1=total1+(SELECT sum(isnull(Total1,0)) as total FROM #Bassert00 WHERE  typeid1 ='0000200001' ) WHERE typeid1='00002' -- +应付
		UPDATE #Bassert00 SET total1=total1+(SELECT sum(isnull(Total1,0)) as total FROM #Bassert00 WHERE  typeid1 ='0000200003' ) WHERE typeid1='00002' -- +代销
		
		/*
		-- 修改所有者权益 = 资产-负债
		UPDATE #Bassert00 SET total1=
				(SELECT total FROM #Bassert00 WHERE typeid in ('00001'))-(SELECT total1 FROM #Bassert00 WHERE typeid1 in ('00002') ) 
		WHERE typeid1='00005'
		
		--实收资本 == 所有者权益 - 利润 （=收入-支出）
		UPDATE #Bassert00 SET total1=
				((SELECT total1 FROM #Bassert00 WHERE typeid1='00005')- ((SELECT sum(isnull(total00,0)) FROM #Atype WHERE typeid like '00003%' and sonnum=0)-(SELECT sum(isnull(total00,0)) FROM #Atype WHERE typeid like '00004%' and sonnum=0)))
		WHERE typeid1='0000500001'	
		
		
		--添加利润项
		IF @I<=@MaxID1
		BEGIN
			UPDATE #Bassert00 
			SET 
				fullname1='利  润',
				leveal1=1,
				total1=((SELECT sum(isnull(total00,0)) FROM #Atype WHERE typeid like '00003%' and sonnum=0)-(SELECT sum(isnull(total00,0)) FROM #Atype WHERE typeid like '00004%' and sonnum=0)),
				typeid1='0000500004',
				parid1='00005',
				sonnum1=0 
			WHERE [ID]=@i
		END	
		ELSE
		BEGIN
			INSERT INTO #Bassert00(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) 
				SELECT '利  润',1,((SELECT sum(isnull(total00,0)) FROM #Atype WHERE typeid like '00003%' and sonnum=0)-(SELECT sum(isnull(total00,0)) FROM #Atype WHERE typeid like '00004%' and sonnum=0)),'0000500004','00005',0
		END
		*/
		
		
		UPDATE  #Bassert00 SET fullname='    '+isnull(fullname,'') WHERE leveal=2 
		UPDATE  #Bassert00 SET fullname1='    '+isnull(fullname1,'') WHERE leveal1=2
		
		UPDATE  #Bassert00 SET fullname='        '+isnull(fullname,'') WHERE leveal=3
		UPDATE  #Bassert00 SET fullname1='        '+isnull(fullname1,'') WHERE leveal1=3
		
		UPDATE  #Bassert00 SET fullname='            '+isnull(fullname,'') WHERE leveal=4
		UPDATE  #Bassert00 SET fullname1='            '+isnull(fullname1,'') WHERE leveal1=4
		
		UPDATE  #Bassert00 SET fullname='                '+isnull(fullname,'') WHERE leveal=5
		UPDATE  #Bassert00 SET fullname1='                '+isnull(fullname1,'') WHERE leveal1=5

		UPDATE  #Bassert00 SET fullname='                    '+isnull(fullname,'') WHERE leveal=6
		UPDATE  #Bassert00 SET fullname1='                    '+isnull(fullname1,'') WHERE leveal1=6

		UPDATE  #Bassert00 SET fullname='                        '+isnull(fullname,'') WHERE leveal=7
		UPDATE  #Bassert00 SET fullname1='                        '+isnull(fullname1,'') WHERE leveal1=7

		UPDATE  #Bassert00 SET fullname='                            '+isnull(fullname,'') WHERE leveal=8
		UPDATE  #Bassert00 SET fullname1='                            '+isnull(fullname1,'') WHERE leveal1=8

		UPDATE  #Bassert00 SET fullname='                                '+isnull(fullname,'') WHERE leveal=9
		UPDATE  #Bassert00 SET fullname1='                                '+isnull(fullname1,'') WHERE leveal1=9

		UPDATE  #Bassert00 SET fullname='                                    '+isnull(fullname,'') WHERE leveal=10
		UPDATE  #Bassert00 SET fullname1='                                    '+isnull(fullname1,'') WHERE leveal1=10
		
		--update #Bassert00 set Fullname1='    『期初资本』' where typeid1='0000500001'
		IF @hidezero=1
		BEGIN
			;WITH c1 AS (
				SELECT rn=ROW_NUMBER() OVER(ORDER BY a.id),ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname,ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE ISNULL(a.total,0) END AS total 
				FROM #Bassert00 a WHERE ISNULL(a.total,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #bassert00 b WHERE a.typeid like b.typeid+'%' AND b.total=0 AND b.sonnum<>0 )
			),c2 AS (
				SELECT rn=ROW_NUMBER() OVER(ORDER BY id), ISNULL(a.typeid1,'') AS typeid1,ISNULL(a.parid1,'') AS parid1,ISNULL(a.fullname1,'') AS fullname1,ISNULL(a.sonnum1,0) AS sonnum1,ISNULL(total1,0) AS total1,a.Leveal
				FROM #Bassert00 a WHERE ISNULL(total1,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #bassert00 b WHERE a.typeid1 LIKE b.typeid1+'%' AND b.total1=0 AND b.sonnum<>0 )
			)
			SELECT ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname, ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE  ISNULL(a.total,0) END  AS total
			,ISNULL(b.typeid1,'') AS typeid1,ISNULL(b.parid1,'') AS parid1,ISNULL(b.fullname1,'') AS fullname1,ISNULL(b.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(b.typeid1,'')='' THEN b.total1 ELSE  ISNULL(b.total1,0) END AS total1 
			FROM c1 a FULL JOIN c2 b ON a.rn=b.rn;
		END
		ELSE
		BEGIN
			SELECT  ISNULL(typeid, '') AS typeid ,
					ISNULL(parid, '') AS parid ,
					ISNULL(usercode, '') AS usercode ,
					ISNULL(fullname, '') AS fullname ,
					ISNULL(sonnum, 0) AS sonnum ,
					CASE WHEN ISNULL(typeid, '') = '' THEN total
						 ELSE ISNULL(total, 0)
					END AS total ,
					ISNULL(typeid1, '') AS typeid1 ,
					ISNULL(parid1, '') AS parid1 ,
					ISNULL(fullname1, '') AS fullname1 ,
					ISNULL(sonnum1, 0) AS sonnum1 ,
					CASE WHEN ISNULL(typeid1, '') = '' THEN total1
						 ELSE ISNULL(total1, 0)
					END AS total1
			FROM    #Bassert00
		END
		
		DROP TABLE #Bassert00
		
		END
END
ELSE  --if @szperiod<>''
BEGIN
	IF @szFlag='asset'  --获得树型资产负债表期初指
	BEGIN
		SELECT a.usercode,a.fullname,a.leveal,a.nTypeId,a.sysrow,a.sonnum,a.nParId,
		(SELECT isnull(sum(b.total00),0) FROM #atype b
		WHERE left(b.typeid,len(a.nTypeId))=a.nTypeId
		) as 'Total',
		
		(SELECT isnull(sum(b.total),0) FROM listtable b
		WHERE b.atypeid=a.nId and billdate>=@BEGINdate 
		) as 'BqTotal'
		
		FROM #atype a WHERE (left(a.nTypeId,5)=@ASSETS_ID or left(a.nTypeId,5)=@DEBT_ID)
	END
	ELSE IF @szFlag='bassert'  -- 历史平衡资产负债表
	BEGIN
		--SELECT '历史资产负债表'
		SELECT @dTotalIncom=isnull(sum(total),0) FROM #monthatypehistory WHERE left(atypeid,5)=@ALL_INCOME_ID AND Period = @szPeriod
		SELECT @dTotalExpense=isnull(sum(total),0) FROM #monthatypehistory WHERE left(atypeid,5)=@ALL_EXPENSE_ID AND Period = @szPeriod
		--update #monthatypehistory set total=@dTotalIncom-@dTotalExpense WHERE atypeid=@PROFIT_ID AND Period = @szPeriod
		

		
		Create TABLE #BassertHistory
		(
			[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
			usercode varchar(300),
			fullname varchar(300),
			leveal int,
			typeid varchar(50),
			sonnum int,
			parid varchar(50),
			total  NUMERIC(24, 10) ,
			fullname1 varchar(300),
			leveal1 int,
			total1  NUMERIC(24, 10) ,
			parid1 varchar(50),
			typeid1 varchar(50),
			Sonnum1 int
		)
		DECLARE @MaxIDHis int
		SET @MaxIDHis =0

		--Select b.*,a.sonnum into #monthatypehistory1 FROM #monthatypehistory b,#atype a where b.atypeid=a.nid
		SELECT b.*,a.sonnum INTO #monthatypehistory1 FROM #monthatypehistory b  
		LEFT  JOIN #atype a ON  a.nid=b.atypeid
		where b.period=@szPeriod
		
		UPDATE #monthatypehistory1 SET sonnum=0 WHERE sonnum IS NULL  OR sonnum=''

		
        INSERT  INTO #BassertHistory
                ( usercode ,
                  fullname ,
                  leveal ,
                  typeid ,
                  sonnum ,
                  parid ,
                  total
                )
                SELECT  a.usercode ,
                        a.fullname ,
                        a.leveal ,
                        a.typeid ,
                        a.sonnum ,
                        a.parid ,
                        ( SELECT    ISNULL(SUM(b.total), 0)
                          FROM      #monthatypehistory1 b
                          WHERE     /*b.sonnum = 0
                                    --AND b.atypeid =CAST(a.nid AS VARCHAR(40))
                                    --AND ( b.atypeid =CAST(a.nid AS VARCHAR(40)) OR b.typeid LIKE a.typeid + '%')
                                    AND*/  b.typeid LIKE a.typeid + '%'
                                    AND b.Period = @szPeriod
                        ) AS 'Total'
                FROM    #Atype a
                WHERE   LEFT(a.typeid, 5) = @ASSETS_ID
                        AND a.typeid <> '0000200002'
                        AND a.typeid <> '0000100006'
                        -- 卡片管理 固定资产
						AND (@display_1=1
								AND (a.typeid NOT LIKE '0000100002%' OR a.typeid ='0000100002') 
							OR @display_1<>1)
						AND a.usercode NOT IN ('SYC-1601','SYC-1602')
                --ORDER BY a.typeid
                ORDER BY a.ordertypeid

		SET @MaxIDHis =@@Rowcount
		
		DECLARE @fullnameHis varchar(300)
		DECLARE @levealHis int
		DECLARE @TotalHis  NUMERIC(24, 10) 
		DECLARE @typeidHis varchar(50)
		DECLARE @paridHis varchar(50)
		DECLARE @sonnumHis int
		DECLARE @jHis int
		SET @jHis =1
		DECLARE BassCurSor CURSOR FOR	
        SELECT  a.fullname ,
                a.leveal ,
                a.typeid ,
                a.parid ,
                a.sonnum ,
                ( 
                SELECT    ISNULL(SUM(b.total), 0)
                  FROM      #monthatypehistory1 b
				WHERE /*b.sonnum=0 ANDb.atypeid=a.nid  
				      AND*/  b.Period = @szPeriod
				      AND left(b.typeid,len(a.typeid))=a.typeid
				      
			
                ) AS 'Total'
        FROM    #Atype a
        WHERE   ( LEFT(a.typeid, 5) = @DEBT_ID
                  OR ( LEFT(a.typeid, 5) = '00005'
                       --AND a.typeid IN ( '00005', '0000500001', '0000500006' )
                     )
                )
                AND a.typeid <> '0000200002'
                AND a.typeid <> '0000100006'
                --AND a.typeid <> '0000200010' AND  a.typeid <> '0000200011'
        --ORDER BY a.typeid
        ORDER BY a.ordertypeid
       
		OPEN BassCurSor
		FETCH NEXT FROM BassCurSor INTO @fullnameHis,@levealHis,@typeidHis,@paridHis,@sonnumHis,@TotalHis
		WHILE @@FETCH_STATUS =0
		BEGIN
		IF @jHis<=@MaxIDHis
		BEGIN
			UPDATE #BassertHistory 
			SET fullname1=@fullnameHis,leveal1=@levealHis,total1=@TotalHis,typeid1=@typeidHis,parid1=@paridHis,sonnum1=@sonnumHis 
			WHERE [ID]=@jHis
		END	
		ELSE
		BEGIN
			INSERT INTO #BassertHistory(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) 
			VALUES( @fullnameHis,@levealHis,@TotalHis,@typeidHis,@paridHis,@sonnumHis)
		END
		SET @jHis = @jHis + 1
		FETCH NEXT FROM BassCurSor INTO @fullnameHis,@levealHis,@typeidHis,@paridHis,@sonnumHis,@TotalHis
		END
		CLOSE BassCurSor
		DEALLOCATE BassCurSor
	
		--应付合计
		UPDATE #BassertHistory SET total1=(select sum(Total)  FROM #monthatypehistory1 where typeid='0000200001') where typeid1='0000200001' 
	

		DROP TABLE #monthatypehistory1

		-- 内部应收合计
		UPDATE #BassertHistory SET total=(
			SELECT ISNULL(SUM(total),0) FROM dbo.ListTable
			WHERE atypeid=28 AND stypeid IN (SELECT typeid FROM #stype)
			AND billdate <=@ed
		)+(
			SELECT ISNULL(SUM(InnerARTotal00),0) FROM dbo.SType_InnerARTotal WHERE stypeid IN (SELECT typeid FROM #stype)
		)
		WHERE typeid='0000100010'
				
		-- 卡片管理 更新
		UPDATE #BassertHistory SET total=(SELECT ISNULL(SUM(NetValue),0) FROM dbo.Ac_AssetsCards_History 
		WHERE BusinessDate=@ed and AuditType=-4 AND STypeId IN (SELECT typeid FROM #stype)) 
		WHERE typeid='0000100002' AND @display_1=1
		
		-- 修改库存总值
		UPDATE #BassertHistory SET total=(SELECT isnull(Total,0) as total FROM #Atype  WHERE typeid='0000100001' ) WHERE typeid='0000100001'
	
		-- 资产合计
		UPDATE #BassertHistory SET total=(SELECT isnull(sum(total),0) FROM #BassertHistory WHERE parid='00001' ) WHERE typeid='00001'
		

		-- 修改负债合计
		UPDATE #BassertHistory SET total1=(SELECT isnull(sum(Total1),0) as total FROM #BassertHistory WHERE  typeid1 NOT in ('0000200001','0000200002') AND LEFT(parid1,5)='00002' and sonnum1=0 ) WHERE typeid1='00002'
		UPDATE #BassertHistory SET total1=total1+(SELECT isnull(sum(Total1),0) as total FROM #BassertHistory WHERE  typeid1 ='0000200001' ) WHERE typeid1='00002' -- +应付

		-- 未分配利润
		UPDATE #BassertHistory SET total1=total1+(SELECT isnull(sum(m.total),0)/*-ISNULL(SUM(a.total00),0)*/ FROM 
		( SELECT ISNULL(SUM(total),0) AS total,ATypeID from monthatypehistory WHERE period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype) GROUP BY atypeid ) m,#atype a WHERE m.atypeid=a.nid AND a.typeid LIKE '00003%')
		-(SELECT isnull(sum(m.total),0)/*-ISNULL(SUM(a.total00),0)*/ FROM 
		(SELECT ISNULL(SUM(total),0) AS total,atypeid from monthatypehistory WHERE  period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype) GROUP BY atypeid ) m,#atype a WHERE m.atypeid= a.nid AND a.typeid LIKE '00004%'  ) WHERE typeid1='0000500005'
	
	
		-- 修改所有者权益 = 资产-负债
		UPDATE #BassertHistory SET total1=(SELECT total FROM #BassertHistory WHERE typeid in ('00001'))-(SELECT total1 FROM #BassertHistory WHERE typeid1 in ('00002') ) WHERE typeid1='00005'

		--其他资本
		UPDATE #BassertHistory SET total1=(SELECT total1 FROM #BassertHistory WHERE typeid1 ='00005')-(SELECT ISNULL(SUM(total1),0) FROM #BassertHistory WHERE typeid1 LIKE '00005%' AND typeid1<>'0000500002' AND sonnum1=0) WHERE typeid1='0000500002'

		/*
		-- 修改所有者权益 = 资产-负债
		UPDATE #BassertHistory SET total1=(SELECT total FROM #BassertHistory WHERE typeid in ('00001'))-(SELECT total1 FROM #BassertHistory WHERE typeid1 in ('00002') ) WHERE typeid1='00005'
		
		--实收资本 == 所有者权益 - 利润 （=收入-支出）
		UPDATE #BassertHistory 
		--SET    total1=(SELECT isnull(sum(total1),0) FROM #BassertHistory WHERE typeid1='00005')- ((SELECT isnull(sum(total),0) FROM monthatypehistory WHERE atypeid LIKE '00003%' and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))-(SELECT isnull(sum(total),0) FROM monthatypehistory WHERE atypeid LIKE '00004%'  and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))) 
		SET    total1=(SELECT isnull(sum(total1),0) FROM #BassertHistory WHERE typeid1='00005')- ((SELECT isnull(sum(m.total),0) FROM monthatypehistory m,#atype a WHERE m.atypeid=a.nid AND a.typeid LIKE '00003%' and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))-(SELECT isnull(sum(m.total),0) FROM monthatypehistory m,#atype a WHERE m.atypeid= a.nid AND a.typeid LIKE '00004%'   and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))) 
		WHERE typeid1='0000500001'
	
 
 
		--添加利润项
		IF @jHis<=@MaxIDHis
		BEGIN	
			UPDATE #BassertHistory 
			SET fullname1='利  润',
				leveal1=1,
				--total1=((SELECT isnull(sum(total),0) FROM monthatypehistory WHERE atypeid like '00003%' and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))-(SELECT isnull(sum(total),0) FROM monthatypehistory WHERE atypeid LIKE '00004%'  and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))),
				total1=((SELECT isnull(sum(m.total),0) FROM monthatypehistory m,#atype a WHERE m.atypeid= a.nid AND a.typeid LIKE '00003%' and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))-(SELECT isnull(sum(m.total),0) FROM monthatypehistory m,#atype a WHERE m.atypeid= a.nid AND a.typeid LIKE '00004%' and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))),
				typeid1='0000500004',
				parid1='00005',
				sonnum1=0 
			WHERE [ID]=@jHis
		END	
		ELSE
		BEGIN
			INSERT INTO #BassertHistory(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) 
				--SELECT '利  润',1,((SELECT isnull(sum(total),0) FROM monthatypehistory WHERE atypeid LIKE '00003%'  and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))-(SELECT sum(isnull(total,0)) FROM monthatypehistory WHERE atypeid LIKE '00004%' and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype) )),'0000500004','00005',0
				SELECT '利  润',1,((SELECT isnull(sum(m.total),0) FROM monthatypehistory m,#atype a WHERE m.atypeid= a.nid AND a.typeid LIKE '00003%'  and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype))-(SELECT sum(isnull(m.total,0)) FROM monthatypehistory m,#atype a WHERE m.atypeid= a.nid AND a.typeid LIKE '00004%' and period=@szPeriod AND Stypeid IN(SELECT typeid FROM #Stype) )),'0000500004','00005',0
		END
		*/
		
		UPDATE  #BassertHistory SET fullname='    '+isnull(fullname,'') WHERE leveal=2 
		UPDATE  #BassertHistory SET fullname1='    '+isnull(fullname1,'') WHERE leveal1=2
		
		UPDATE  #BassertHistory SET fullname='        '+isnull(fullname,'') WHERE leveal=3
		UPDATE  #BassertHistory SET fullname1='        '+isnull(fullname1,'') WHERE leveal1=3
		
		UPDATE  #BassertHistory SET fullname='            '+isnull(fullname,'') WHERE leveal=4
		UPDATE  #BassertHistory SET fullname1='            '+isnull(fullname1,'') WHERE leveal1=4
		
		UPDATE  #BassertHistory SET fullname='                '+isnull(fullname,'') WHERE leveal=5
		UPDATE  #BassertHistory SET fullname1='                '+isnull(fullname1,'') WHERE leveal1=5

		UPDATE  #BassertHistory SET fullname='                    '+isnull(fullname,'') WHERE leveal=6
		UPDATE  #BassertHistory SET fullname1='                    '+isnull(fullname1,'') WHERE leveal1=6
		
		UPDATE  #BassertHistory SET fullname='                        '+isnull(fullname,'') WHERE leveal=7
		UPDATE  #BassertHistory SET fullname1='                        '+isnull(fullname1,'') WHERE leveal1=7
		
		UPDATE  #BassertHistory SET fullname='                            '+isnull(fullname,'') WHERE leveal=8
		UPDATE  #BassertHistory SET fullname1='                            '+isnull(fullname1,'') WHERE leveal1=8
		
		UPDATE  #BassertHistory SET fullname='                                '+isnull(fullname,'') WHERE leveal=9
		UPDATE  #BassertHistory SET fullname1='                                '+isnull(fullname1,'') WHERE leveal1=9
		
		UPDATE  #BassertHistory SET fullname='                                    '+isnull(fullname,'') WHERE leveal=10
		UPDATE  #BassertHistory SET fullname1='                                    '+isnull(fullname1,'') WHERE leveal1=10
		

		IF @hidezero=1
		BEGIN
			;WITH c1 AS (
				SELECT rn=ROW_NUMBER() OVER(ORDER BY a.id),ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname,ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE ISNULL(a.total,0) END AS total ,a.leveal
				FROM #BassertHistory a WHERE ISNULL(a.total,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #BassertHistory b WHERE a.typeid like b.typeid+'%' AND b.total=0 AND b.sonnum<>0 )
			),c2 AS (
				SELECT rn=ROW_NUMBER() OVER(ORDER BY id), ISNULL(a.typeid1,'') AS typeid1,ISNULL(a.parid1,'') AS parid1,ISNULL(a.fullname1,'') AS fullname1,ISNULL(a.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(typeid1,'')='' THEN total1 ELSE  ISNULL(total1,0) END AS total1, a.leveal1
				FROM #BassertHistory a WHERE ISNULL(total1,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #BassertHistory b WHERE a.typeid1 LIKE b.typeid1+'%' AND b.total1=0 AND b.sonnum<>0 )
			)
			INSERT INTO #Tmp2
           ( typeid,parid,usercode , fullname , sonnum,total,  typeid1 ,  parid1 , fullname1 , Sonnum1,total1 , leveal , leveal1)
			SELECT ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname, ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE  ISNULL(a.total,0) END  AS total
			,ISNULL(b.typeid1,'') AS typeid1,ISNULL(b.parid1,'') AS parid1,ISNULL(b.fullname1,'') AS fullname1,ISNULL(b.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(b.typeid1,'')='' THEN b.total1 ELSE ISNULL(b.total1,0) end AS total1 ,a.leveal, b.leveal1
			FROM c1 a FULL JOIN c2 b ON a.rn=b.rn;
		END
		ELSE
		BEGIN
			INSERT INTO #Tmp2
           ( typeid,parid,usercode , fullname , sonnum,total,  typeid1 ,  parid1 , fullname1 , Sonnum1,total1 , leveal , leveal1)
			SELECT 
				isnull(typeid,'') as typeid,isnull(parid,'') as parid,isnull(usercode,'') as usercode,isnull(fullname,'') as fullname,isnull(sonnum,0) as sonnum,case when isnull(typeid,'')='' then total else isnull(total,0)  end as total,
				isnull(typeid1,'') as typeid1,isnull(parid1,'') as parid1,isnull(fullname1,'') as fullname1,isnull(sonnum1,0) as sonnum1,case when isnull(typeid1,'')='' then total1 else isnull(total1,0)  end as total1,leveal,leveal1
			FROM  #BassertHistory
		END
		DROP TABLE #BassertHistory
	END
	
	IF @szFlag='gain'  -- 历史损益表
	BEGIN
		--delete FROM #tmpGain WHERE bqtotal=0
		
		CREATE TABLE #gainHistory(usercode varchar(300),fullname varchar(300),leveal int,typeid varchar(50),sonnum int,parid varchar(50),total  NUMERIC(24, 10) ,bqtotal  NUMERIC(24, 10) )	

	    Select b.*,a.sonnum into #monthatypehistorynew FROM #monthatypehistory b,dbo.Ac_Items a where b.atypeid=a.nId
        INSERT  INTO #gainHistory
                SELECT  a.usercode ,
                        a.fullname ,
                        a.leveal ,
                        a.typeid ,
                        a.sonnum ,
                        a.parid ,
                        ( SELECT    ISNULL(SUM(b.total), 0)
                          FROM      #monthatypehistorynew b
                          WHERE     b.sonnum = 0
                                    AND b.atypeid = a.nid
                                    AND b.Period = @szPeriod
                                    
                                    
                        ) AS 'Total' ,
                        ( SELECT    ISNULL(SUM(b.bqtotal), 0)
                          FROM      #monthatypehistorynew b
                          WHERE     b.sonnum = 0
                                    AND b.atypeid = a.nid
                                    AND b.Period = @szPeriod
                        ) AS 'BqTotal'
                FROM    #Atype a
                WHERE   ( LEFT(a.typeid, 5) = @ALL_INCOME_ID
                          OR LEFT(a.typeid, 5) = @ALL_EXPENSE_ID
                        )

		Drop table #monthatypehistorynew
		INSERT INTO #gainHistory(usercode,fullname,leveal,typeid,sonnum,parid,total,bqtotal) 
			SELECT '','【利    润】',1,'999999999999999',0,'',(select sum(case when typeid LIKE'00003%' then total else -total end) as total from #gainHistory ),(select sum(case when typeid LIKE'00003%' then bqtotal else -bqtotal end) as bqtotal from #gainHistory)			
		update #gainHistory set fullname ='    '+fullname where leveal =2
		update #gainHistory set fullname ='        '+fullname where leveal =3
		update #gainHistory set fullname ='            '+fullname where leveal =4
		update #gainHistory set fullname ='                '+fullname where leveal =5

		update #gainHistory set fullname ='                    '+fullname where leveal =6
		update #gainHistory set fullname ='                        '+fullname where leveal =7
		update #gainHistory set fullname ='                            '+fullname where leveal =8
		update #gainHistory set fullname ='                                '+fullname where leveal =9
		update #gainHistory set fullname ='                                    '+fullname where leveal =10
		--SELECT '历史损益表'
		;WITH cte AS
		(
			SELECT usercode,fullname,leveal,typeid,sonnum,parid,total,bqtotal
			FROM #gainHistory
			--WHERE parid='00000'
			UNION ALL
			SELECT c.usercode,c.fullname,c.leveal,c.typeid,c.sonnum,c.parid,d.total,d.bqtotal
			FROM #gainHistory AS C
			INNER JOIN cte AS D
				ON C.typeid=D.parid
		),c1 AS (
			SELECT #gainHistory.usercode,#gainHistory.fullname,#gainHistory.leveal,#gainHistory.typeid,#gainHistory.sonnum,#gainHistory.parid,SUM(ISNULL(cte.TOTAL,0)) TOTAL,
			SUM(ISNULL(cte.bqtotal,0)) bqtotal  
			FROM #gainHistory INNER JOIN cte ON #gainHistory.typeid=cte.typeid 
			GROUP BY #gainHistory.usercode,#gainHistory.fullname,#gainHistory.leveal,#gainHistory.typeid,#gainHistory.sonnum,#gainHistory.parid
		)		
		SELECT b.usercode,b.fullname,b.leveal,a.typeid,b.sonnum,b.parid,A.TOTAL,a.bqtotal INTO #tempGainTable1 FROM c1 A 
		LEFT JOIN #gainHistory B ON A.typeid=B.typeid
		WHERE @hidezero=1 AND (a.bqtotal<>0 OR a.TOTAL<>0) 
			AND NOT EXISTS (SELECT 1 FROM c1 b WHERE a.typeid LIKE b.typeid+'%' AND b.bqtotal=0 AND b.total=0 AND b.sonnum<>0)
		OR @hidezero=0
		ORDER BY A.typeid
		--ORDER BY A.ordertypeid
		SELECT * FROM #tempGainTable1 WHERE leveal<=@itemLeveal
		DROP TABLE #tempGainTable1
	END
END

IF @szFlag='bassert' 
BEGIN

INSERT INTO #Tmp
        (  usercode , fullname ,  leveal , typeid ,  sonnum , parid ,  total)
        SELECT usercode , fullname ,  leveal , typeid ,  sonnum , parid ,  total FROM #Tmp2 WHERE leveal  <= @itemleveal

INSERT INTO #Tmp1
        (  fullname1 , leveal1 , total1 , parid1 ,typeid1 ,Sonnum1 )
         SELECT fullname1 , leveal1 , total1 , parid1 ,typeid1 ,Sonnum1 FROM #Tmp2 where leveal1 <= @itemleveal

TRUNCATE TABLE #Tmp2
--select * from #Tmp
--select * from #Tmp1

declare @RowCount int,@ii int,@TmpCount int, @TmpCount1 INT

select @TmpCount=COUNT(1) from #Tmp
select @TmpCount1=COUNT(1)  from #Tmp1

--print @TmpCount
--print @TmpCount1
if(@TmpCount <= @TmpCount1)
 set @RowCount = @TmpCount1
else
 set @RowCount = @TmpCount


set @RowCount = @RowCount + 1
set @ii = 1

--资产负债

DECLARE 	
	@usercodea varchar(300),
	@fullnamea varchar(300),
	@leveala int,
	@typeida varchar(50),
	@sonnuma int,
	@parida varchar(50),
	@totala  NUMERIC(24, 10) ,
	@fullname1a varchar(300),
	@leveal1a int,
	@total1a  NUMERIC(24, 10) ,
	@parid1a varchar(50),
	@typeid1a varchar(50),
	@Sonnum1a int 

while @ii < @RowCount
begin
	if(@ii < = @TmpCount)
	BEGIN
   		select @usercodea = usercode ,@fullnamea = fullname , @leveala = leveal,@typeida =typeid, @sonnuma = sonnum ,@parida = parid ,@totala = total 
   		from #Tmp where id = @ii
   	end
   	else
   	begin
   		set @usercodea = null 
   		set @fullnamea = null 
   		set @leveala = null 
   		set @typeida = null 
   		set @sonnuma = null 
   		set @parida = null 
   		set @totala = null 
   	end
   	if(@ii < = @TmpCount1)
   	BEGIN
   		select @fullname1a = fullname1 ,@leveal1a = leveal1 , @total1a = total1 ,@parid1a = parid1, @typeid1a = typeid1, @Sonnum1a = Sonnum1
   	    from #Tmp1 where id = @ii
   	end
   	else
   	begin
   		set @fullname1a = null 
   		set @leveal1a = null 
   		set @total1a = null  
   		set @parid1a = null  
   		set @typeid1a = null  
   		set @Sonnum1a = null  
   	end
   	insert into #Tmp2 values (@usercodea,@fullnamea,@leveala,@typeida,@sonnuma,@parida,@totala
   							,@fullname1a,@leveal1a,@total1a,@parid1a,@typeid1a,@Sonnum1a)
	Set @ii = @ii + 1
end
SELECT * FROM #Tmp2

DROP TABLE #Tmp2
DROP TABLE #Tmp1
DROP TABLE #Tmp

END


DROP TABLE #Atype,#monthatypehistory
DROP TABLE #t1,#t2;

GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
  SELECT 
	* 
  FROM dbo.sysobjects 
  WHERE id = OBJECT_ID(N'[dbo].[Gp_qrStockAll_Detail]') 
    AND OBJECTPROPERTY(id, N'IsProcedure') = 1
  )
	DROP procedure [dbo].[Gp_qrStockAll_Detail]
GO



/*
	作者：谢吉康
	日期：2009-12-03
	描述：库存状况表明细表
------------------------------------------------------------------------------
	Author:Wang Wei 
	Datetime: 2010-9-9
	Description:调整，仅控制仓库和配件权限。 Bug 1160
	
------------------------------------------------------------------------------
	修改：李海洋
	日期：2012-03-28
	描述：添加经手人筛选, 去掉 "调拔调阅(billtype 为17, 21) 加不限经手人权限"
------------------------------------------------------------------------------
    修改：黄飞佳
	日期：2012-05-28
	描述：添加货位、币种、自由项等数据
*/
CREATE PROCEDURE Gp_qrStockAll_Detail
( 
	@startdate		VARCHAR(25),
	@EndDate		VARCHAR(25),
	@AtypeId		VARCHAR(8000),
	@typeId			VARCHAR(max),
	@BtypeId		VARCHAR(8000),
	@KtypeId		VARCHAR(8000),
	@eTypeId		VARCHAR(8000),
	@cMode			VARCHAR(2),
	@sortfield		VARCHAR(25),
	@OperatorId     VARCHAR(100),			--操作员ID
	@showRedWord	CHAR(1)='0',
	@intType        INT='',
	@stypeid		VARCHAR(8000)='00001',	--分支机构
	@isshowstop     int=0,                  --是否显示停用 0显示停用，1为不显示。
	@IsReporting	INT,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@PageType		VARCHAR(50),		--if(PageType='V') 虚拟库存 else 库存状况表
	@ptypeCategoryid VARCHAR(max)='',
	@showstockstop INT =0 --是否显示停用仓库数据 1为不显示 0为显示
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
		   @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

-- 选择分支机构
CREATE TABLE #GetSelectSTypeId
(
  TypeId varchar(100)
)
INSERT INTO #GetSelectSTypeId(TypeId) 
  SELECT typeid 
  FROM F_GetAllManagerBaseTypeId(@stypeid, 11, @OperatorID)
		
--检测经手人权限是否有效
DECLARE @limt INT 
Exec @limt= GP_CheckLimit @OperatorID,2374


CREATE TABLE #GetSelETypeId
(
  TypeId VARCHAR(100)
)
IF @limt = 0 
    INSERT  INTO #GetSelETypeId (TypeId)
            SELECT  typeid
            FROM    F_GetAllManagerBaseTypeId(@eTypeId, 3, @OperatorID)
  
ELSE 
    INSERT  INTO #GetSelETypeId (TypeId)
            SELECT  TypeId
            FROM    F_GetAllBaseTypeId(@eTypeId, 3)
  

--筛选仓库
CREATE TABLE #GetSelKTypeId
(
  TypeId varchar(100)
)
  IF @showstockstop = 0 
  INSERT  INTO #GetSelKTypeId
            ( TypeId
            )
    SELECT  typeid
    FROM    F_GetAllManagerBaseTypeId(@KtypeId, 4, @OperatorID)
  ELSE 
    INSERT  INTO #GetSelKTypeId
            ( TypeId
            )
            SELECT  a.typeid
            FROM    F_GetAllManagerBaseTypeId(@KtypeId, 4, @OperatorID) a
                    INNER JOIN dbo.Stock b ON a.TypeId = b.typeId
            WHERE   b.deleted = 0
DELETE FROM #GetSelKTypeId --删除不在权限范围内的分支机构下的仓库
  WHERE TypeId NOT IN( SELECT TypeId FROM STOCK WHERE STypeID IN (SELECT TypeId FROM #GetSelectSTypeId))

---筛选往来单位
CREATE TABLE #GetBtype(Typeid NVARCHAR(200))
INSERT INTO #GetBtype(typeid)
SELECT TypeId FROM dbo.F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorId)
union all select '' as TypeId

---筛选商品
CREATE TABLE #GetManPType
(
  TypeId VARCHAR(100)
)
INSERT INTO #GetManPType(TypeId) 
  SELECT typeid 
  FROM dbo.F_ManPTypeInCategoryID(@OperatorId,@typeId,@ptypeCategoryid) 



---彭勇优化加索引

CREATE CLUSTERED INDEX IX_GetManPType_TypeID ON #GetManPType(TypeID)
  
  

DECLARE @strQuery VARCHAR(1000)
SELECT @strQuery=''

-- 根据经手人过滤 Add by Haiyang, Li 2012-03-27
--****************
IF @OperatorId <> ''
	BEGIN
		--超级管理员(Admin)为不限经手人查询
		IF @EtypeID = '00001' 
			SELECT @strQuery = ''
		ELSE
			SELECT @strQuery = ' where a.EtypeId IN (SELECT TypeId FROM #GetSelETypeId)';
	END
--****************

DECLARE @Sql VARCHAR (max)

SELECT @SQL='
SELECT 	c.BillNumberId,
		c.ID AS CustomdetailID,
		c.BillDate,
		c.billtype,
	    case when a.billtype=57   then 0 else	c.CostPrice end as costprice,
		c.Costtotal,
		c.atypeid,
		c.ktypeid,
		c.ptypeid,
	    case when a.billtype=57 then 0 else	c.qty end as qty,
		c.total,
		CASE WHEN   gtb.typeid is not null  THEN a.dealbtypeid ELSE ''****'' END btypeid,--彭勇加权限
		CASE WHEN   gtb.typeid is not null THEN bbb.usercode ELSE ''****'' END usercode,--彭勇加权限
		CASE WHEN   gtb.typeid is not null THEN bbb.fullname ELSE ''****'' END bfullname,--彭勇加权限,
		CASE WHEN   gtb.typeid is not null THEN  a.comment ELSE ''****'' END comment, 				
		c.EtypeId,
		c.posttime,
		c.cargoid,
		c.iscombined,
		c.itemid,
		c.munitid,
		c.nqty,
		c.goodsnumber,		
		p1.fullname,
		p1.baseUnitId
FROM	inoutstocktable c  
INNER JOIN (
				SELECT	billnumberid,
						billtype,
						dealbtypeid,
						billdate,
						ifcheck,
						redword,
						comment
				FROM	BillIndex
				WHERE	BillDate >= '+CHAR(39)+@startdate+CHAR(39)+'
						AND BillDate <= '+CHAR(39)+@enddate+CHAR(39)+'
						AND ifCheck = ''t''
				UNION ALL
				SELECT	billnumberid,
						billtype,
						'''' AS dealbtypeid,
						billdate,
						ifcheck,
						redword,
						comment
				FROM	PosAllotApplyBillIndex
				WHERE	BillDate >= '+CHAR(39)+@startdate+CHAR(39)+'
						AND BillDate <= '+CHAR(39)+@enddate+CHAR(39)+'
						AND ifCheck = ''t''
)a ON c.BillNumberId = a.BillNumberId AND a.billtype = c.billtype
INNER JOIN ptype p1 on  c.ptypeid=p1.typeid 
INNER JOIN #GetManPType on c.ptypeid = #GetManPType.typeid 
LEFT JOIN  btype bbb on bbb.typeid=c.btypeid
LEFT JOIN #GetBtype gtb on isnull(a.dealbtypeid ,'''')=gtb.typeid '
	
IF NOT(RTRIM(@ktypeid) ='0' AND @MKtypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetSelKTypeId sk ON sk.typeid = c.ktypeid ' 	

SET @SQL = @SQL +' WHERE	c.BillNumBerId<>0 
							and a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
							AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'  and a.ifcheck=''t'''
	
IF @showRedWord = '0'
	SELECT @SQL = @SQL + ' and a.redword =0  '				
IF @isshowstop=1
	SET @SQL = @SQL + ' and p1.deleted=0  '	
IF UPPER(@cMode) <> 'S' AND UPPER(@cMode) <> 'B'
	SET @SQL = @SQL + ' AND c.ktypeid <> '+ CHAR(39) + '10000' + CHAR(39) + '  '	

IF UPPER(@cMode) = 'S'
 	SET @SQL = @SQL +' AND C.billtype IN(11,141,45,305,402,403,12,46) '	
 
IF UPPER(@cMode)='B'
	SET @SQL = @SQL + ' AND C.billtype IN(34,6,145,400,401) '
 
IF RTRIM(@btypeid) <> '0' 
	SET @SQL = @SQL + ' AND LEFT(a.dealbtypeid,len(' + CHAR(39) + @btypeid+CHAR(39) + ')) = ' + CHAR(39) + @btypeid + CHAR(39) + ' ' 
	
SELECT @Sql ='
			SELECT	row_number() over (order by c.BillnumberID) as row_id,
					c.CustomdetailID,
					c.BillNumberId,
					c.BillDate,
					c.billtype,
					CASE WHEN a.billtype=145 AND -ISNULL(c.qty,0)>=0 THEN 	-ISNULL(c.qty,0)
						 WHEN a.billtype<>145 AND ISNULL(c.qty,0)>=0 THEN   ISNULL(c.qty,0)
					  end as rqty,
					CASE WHEN a.billtype=145 AND -ISNULL(c.qty,0)<0 THEN 	abs(ISNULL(c.qty,0))
						 WHEN a.billtype<>145 AND ISNULL(c.qty,0)<0 THEN    abs(ISNULL(c.qty,0))
					  end as cqty,
					CASE a.billtype WHEN 145 THEN -ISNULL(c.Costtotal,0)	else  ISNULL(c.Costtotal,0)	end as Costtotal,
					CASE a.billtype WHEN 145 THEN -ISNULL(c.total,0)	    else  ISNULL(c.total,0)	end as total,
					ISNULL(c.CostPrice,0) AS CostPrice,
					a.BillCode, 
					c.comment,
					a.RedWord, 
					CBillType= a.billtype,
					c.atypeid,
					c.btypeid,
					a.etypeid,
					c.ktypeid,
					c.ptypeid,				
					c.fullname,				
					c.bfullname,
					c.usercode,
					a.stypeid,					
					c.posttime,
					c.cargoid,
					c.goodsnumber,
					v.fullname AS itemfullname,
					c.nqty,
					p.fullname AS munitfullname,
					CASE WHEN a.billtype=145 AND -ISNULL(c.qty,0)>=0 THEN 	c.qty/pe.rate
						 WHEN a.billtype<>145 AND ISNULL(c.qty,0)>=0 THEN   c.qty/pe.rate
					  END AS rqnum,
					CASE WHEN a.billtype=145 AND -ISNULL(c.qty,0)<0 THEN    ABS(c.qty/pe.rate)
						 WHEN a.billtype<>145 AND ISNULL(c.qty,0)<0 THEN    ABS(c.qty/pe.rate)
					END AS cqnum,
					a.AdPriceType,
					c.baseUnitId
			FROM 	(
						SELECT	BillNumberId,
								BillType,
								BillCode,
								etypeid,
								stypeid,
								redword,
								adpricetype
						FROM	BillIndex
						UNION ALL
						SELECT	BillNumberId,
								BillType,
								BillCode,
								applyetypeid,
								stypeid,
								redword,
								0 as adpricetype
						FROM	PosAllotApplyBillIndex
			)a
			INNER JOIN  #GetSelectSTypeId ss on a.stypeid=ss.typeid 
			inner join #GetSelETypeId ee on ee.typeid=a.etypeid
			INNER JOIN	('+@sql+') c on	c.BillNumberId = a.BillNumberId and c.billtype = a.billtype
			LEFT JOIN  vWeb_ItemIDByIsCombined v on c.iscombined = v.iscombined AND c.itemid = v.id
			LEFT JOIN  PType_Units p on p.unitsid = c.munitid
			LEFT JOIN  ptype_units_ext pe on pe.unitsid = c.munitid AND pe.ptypeid = c.ptypeid
			 '
DECLARE @GroupBy VARCHAR(2000)
SELECT @GroupBy ='  
			GROUP BY 
					c.BillNumberId,
					c.billdate,
					c.billtype,
					a.billtype,
					c.costprice,
					c.qty,
					a.billcode,
					a.comment,
					a.redword,
					c.ptypeid,
					c.ktypeid,
					c.atypeid,
					a.btypeid,
					a.etypeid,
					a.stypeid,
					c.cargoid, 
					AdPriceType,
					c.baseUnitId'
					
					
--Group By
IF @sortfield = 'ByDate_a'
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @sortfield = 'ByBillNo_a' 
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @sortfield = 'ByBillType_a'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @sortfield = 'ByBillID_a'	
    SELECT @GroupBy = @GroupBy + ' a.posttime'
ELSE IF @sortfield = 'posttime_a'		
		SELECT @GroupBy = @GroupBy + ' a.BillDate,a.posttime'    
ELSE IF @sortfield = 'ByDate_d'		
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @sortfield = 'ByBillNo_d' 	
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @sortfield = 'ByBillType_d'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @sortfield = 'ByBillID_d'	
    SELECT @GroupBy = @GroupBy + ' a.posttime'
ELSE IF @sortfield = 'posttime_d'		
		SELECT @GroupBy = @GroupBy + ' a.BillDate,a.posttime'    
ELSE
    SELECT @GroupBy = @GroupBy + ' c.posttime'




DECLARE @SQLOrder	VARCHAR(150)
SELECT @SQLOrder = ''

DECLARE @qty NUMERIC(24,10)

CREATE TABLE #Qty
(
	qty			NUMERIC(24,10),
	Total       NUMERIC(24,10)
)

insert #Qty exec Gp_GetPreDateQtyOrTotal @OperatorID,
	@StartDate,	
	@typeId,	
	@KTypeId,	
	@etypeid,	
	@stypeid	
SELECT @qty=ISNULL(qty,0) FROM #Qty
DECLARE @tmpSQL NVARCHAR(3000)
SET @tmpSQL='dbo.F_GetCustomAssist(a.ptypeid,'+convert(nvarchar(100),@qty)+'+rqty-cqty)'


--ORDER BY
IF @sortfield = 'ByDate_a'		
	SELECT @SQLOrder = ' ORDER BY billdate, billtype, BillCode'
ELSE IF @sortfield = 'ByBillNo_a' 	
	SELECT @SQLOrder = ' ORDER BY BillCode'
ELSE IF @sortfield = 'ByBillType_a'	
	SELECT @SQLOrder = ' ORDER BY billtype, billdate, BillCode'
ELSE IF @sortfield = 'ByBillID_a'	
	SELECT @SQLOrder = ' ORDER BY posttime'
ELSE IF @sortfield = 'posttime_a'		
	SELECT @SQLOrder = ' ORDER BY BillDate ASC,posttime ASC'		
ELSE IF @sortfield = 'ByDate_d'		
	SELECT @SQLOrder = ' ORDER BY billdate DESC, billtype, BillCode'
ELSE IF @sortfield = 'ByBillNo_d' 	
	SELECT @SQLOrder = ' ORDER BY BillCode DESC'
ELSE IF @sortfield = 'ByBillType_d'	
	SELECT @SQLOrder = ' ORDER BY billtype DESC, billdate, BillCode'
ELSE IF @sortfield = 'ByBillID_d'	
	SELECT @SQLOrder = ' ORDER BY posttime DESC'
ELSE IF @sortfield = 'posttime_d'		
	SELECT @SQLOrder = ' ORDER BY BillDate DESC,posttime DESC'
ELSE
	SELECT @SQLOrder = ' ORDER BY posttime'

	SET @SQL ='SELECT *, CAST(0 AS NUMERIC(24,10)) AS ljcalCustomQty  ,IDENTITY(int,1,1) AS orderid  INTO #Result FROM (' + @SQL +') AS A ' + @SQLOrder +'	 
				
				UPDATE #Result SET ljcalCustomQty = (SELECT SUM(ISNULL(rqty,0) - ISNULL(cqty,0)) FROM #Result t WHERE t.orderid <=#Result.orderid)				
	
			  	SELECT  a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head, 
						SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,
						SysDiy24_head,SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,
						SysDiy31_head,SysDiy32_head,SysDiy33_head,
						SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
						SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
						SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
						SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
						SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,	'+convert(nvarchar(100),@qty)+'+ISNULL(rqty,0) - ISNULL(cqty,0) AS tex,
						customassist= dbo.F_GetCustomAssist(a.ptypeid,ljcalCustomQty),
						ISNULL(pr.RecAmgSTypeBuyPrice,0) as recprice			
				FROM #Result a 
				LEFT JOIN dbo.PType_Price pr ON a.pTypeId=pr.PTypeID AND a.baseUnitId=pr.UnitID
				LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype 
				LEFT JOIN Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid AND ((csdetail.billtype IN(12,46) AND csdetail.InOrOut = ''O'') OR csdetail.billtype not IN(12,46))	
						ORDER BY orderid
		
				DROP TABLE #Result
			   '
--PRINT(@SQL)
EXEC (@SQL)

----------------------------------------------------------
DROP TABLE #GetSelKTypeId, #GetSelectSTypeId, #GetManPType,#GetBtype,#GetSelETypeId,#Qty

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrStockAll_Line]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrStockAll_Line]
GO



CREATE PROCEDURE Gp_qrStockAll_Line
( 
	@OperatorID 		varchar(100),  	   		--操作员ID号
	@EndDataPoint  		varchar(20)='',      	--某一日期的库存
	@Parid   			varchar(100)='00000',   --商品的父节点号
	@szKtypeId  		varchar(8000)='',       --仓库id号
	@szPeriod  			char(2)='' ,            --期号,
	@usercode 			varchar(26)='',         --商品编号
	@fullname  			varchar(66)='',         --商品名称
	@sorttype 			varchar(20),            --按何种方式排序
	@SortField  		varchar(25),            --按具体的字段排序  
	@showzeroqty 		varchar(10),            --是否显示库存为0的记录   1---显示    0----不显示
	@IfLendBorrow 		char(1),                --是否显示借进借出
	@EntryCode			varchar(200),			--商品条码
	@Standard			varchar(200),			--商品规格
	@type				varchar(200),			--商品型号
	@area				varchar(200),			--商品产地
	@PriceType			int=0,					--价格方式
	@stypeid			VARCHAR(8000)='00001',	--分支机构
	@dwgno				VARCHAR(MAX)='',		--图号
	@generaldwgno		VARCHAR(MAX)='',		--通用车型
	@pycode				VARCHAR(MAX)='',			--拼音码,
	@isshowstop     int=0                   --是否显示停用 0显示停用，1为不显示。   
	
)
--@encode$--
AS


SET NOCOUNT ON
SET ANSI_WARNINGS OFF
DECLARE @Sql varchar(8000)   ---肖伟 2002-06-27加速库存状况查询


IF @Parid='00000' SET @Parid=''

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--商品

 
-- DECLARE
--	@strGetManPTypeId	VARCHAR(MAX)
	
	
--IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerPTypeID = '00000')
--BEGIN
-- IF @isshowstop=1
--	 BEGIN
--			SELECT @strGetManPTypeId='( SELECT TypeID FROM PType WHERE SonNum = 0 and deleted=0) '
--	 END
-- ELSE
--	 BEGIN
--				SELECT @strGetManPTypeId='( SELECT TypeID FROM PType WHERE SonNum = 0) '
--	 END
--END
--ELSE
--BEGIN
--  IF @isshowstop=1
--	BEGIN
--	SELECT @strGetManPTypeId='
--	(
--	SELECT	P.TypeId 
--	FROM	PType_L L
--	INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + ''%''
--	WHERE	L.etypeid = '+CHAR(39)+@OperatorID+CHAR(39)+'
--			AND L.flag = 1 
--			AND P.sonnum = 0	
--			and p.deleted=0
--	)'
--	END
--	ELSE
--	  BEGIN
--			   SELECT @strGetManPTypeId='
--			(
--			SELECT	P.TypeId 
--			FROM	PType_L L
--			INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + ''%''
--			WHERE	L.etypeid = '+CHAR(39)+@OperatorID+CHAR(39)+'
--					AND L.flag = 1 
--					AND P.sonnum = 0	
--			)'
--	  END 
--END

CREATE TABLE #GetManPTypeId(TypeId	VARCHAR(100))

IF @isshowstop=1
	BEGIN
		INSERT INTO #GetManPTypeId(TypeId) SELECT TypeID FROM dbo.F_GetManPTypeAll(@OperatorID) WHERE SonNum = 0 AND deleted=0
	END
	
ELSE
	BEGIN
		INSERT INTO #GetManPTypeId(TypeId) SELECT TypeID FROM dbo.F_GetManPTypeAll(@OperatorID) WHERE SonNum = 0
	END	
 IF @stypeid='' 
BEGIN
	SET @stypeid='00000'
END

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))

IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
BEGIN
	SELECT Typeid INTO #TempSType FROM F_GetManDetailSType(@OperatorID)

	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN #TempSType s
	ON A.TypeId=s.Typeid
END



--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT mk.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) mk
			INNER JOIN #GetSelectSTypeId s ON mk.STypeId=s.TypeId

--选择仓库
CREATE TABLE #GetSelectKTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectKTypeId(TypeId) 
SELECT A.Typeid FROM F_GetAllBaseTypeId(@szKtypeId,4) AS A  INNER JOIN (SELECT Typeid FROM #GetManKTypeId) K
ON A.TypeId=K.TypeId
CREATE TABLE #GOODSSTOCKS_QTY 
(
	PTYPEID		VARCHAR(50),
	KTYPEID		VARCHAR(50),
	NQTY		 NUMERIC(24, 10) 
)

DECLARE @tempSql NVARCHAR(4000)

SET @tempSql ='INSERT INTO #GOODSSTOCKS_QTY (PTYPEID,KTYPEID,NQTY)
SELECT	PTypeID,
		KTypeID,
		SUM(NQty) AS NQTY
FROM GOODSSTOCKS_QTY G
INNER JOIN #GetSelectKTypeId K	ON K.typeid=G.KtypeID
INNER JOIN #GetManPTypeId P ON G.PTypeId=P.typeid
GROUP BY PTypeID,KTypeID'
EXEC(@tempsql)

DECLARE
	@strGetManPTypeAll		VARCHAR(MAX)
	
	
	
/*	
IF	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerPTypeID = '00000')
BEGIN
	SELECT
		@strGetManPTypeAll='
	(
		SELECT 	P.typeId,
				P.UserCode,
				P.FullName		
		FROM 	PType P
		WHERE 	P.TypeId <> ''00000'' 
				AND UserCode LIKE ''%'+@UserCode+'%''
				AND FullName LIKE ''%'+@FullName+'%''
				AND ISNULL(EntryCode,'''') LIKE ''%' + @EntryCode + '%''
				AND ISNULL(Standard,'''') LIKE ''%' + @Standard + '%''
				AND ISNULL([Type],'''')   LIKE ''%' + @type + '%''
				AND ISNULL(Area,'''') 	 LIKE ''%' + @area + '%''
				AND TypeID<>''00000'' 
				AND TypeID LIKE '''+@parid+'%''
				AND ISNULL(DwgNo,'''') LIKE ''%'+@dwgno+'%''
				AND ISNULL(PyCode,'''') LIKE ''%'+@pycode+'%''
				AND Sonnum=0
	)
	'
END
ELSE
BEGIN
SELECT
	@strGetManPTypeAll='
	(
		SELECT 	P.typeId,
				P.UserCode,
				P.FullName
		FROM 	PType P 
		INNER JOIN  F_GetManPTypeDetailALL('+CHAR(39)+@OperatorID+CHAR(39)+') M ON P.TypeId = M.TypeId
		WHERE	P.TypeID LIKE '''+@parid+'%''
				AND UserCode LIKE ''%'+@UserCode+'%''
				AND FullName LIKE ''%'+@FullName+'%''
				AND ISNULL(EntryCode,'''') LIKE ''%' + @EntryCode + '%''
				AND ISNULL(Standard,'''') LIKE ''%' + @Standard + '%''
				AND ISNULL([Type],'''')   LIKE ''%' + @type + '%''
				AND ISNULL(Area,'''') 	 LIKE ''%' + @area + '%''
				AND P.TypeID<>''00000'' 
				AND ISNULL(DwgNo,'''') LIKE ''%'+@dwgno+'%''
				AND ISNULL(PyCode,'''') LIKE ''%'+@pycode+'%''
				AND Sonnum=0
	)
	'
	
END	*/
IF @isshowstop=1
BEGIN
SET @strGetManPTypeAll='
	(
		SELECT 	P.typeId,
				P.UserCode,
				P.FullName,
				p.sonnum,
				p.deleted,
				p.entrycode,
				u5.fullname assistantfullname,
				u1.fullname baseunitfullname,
				u4.fullname stockunitfullname,
				r4.rate stockUnitRate 
		FROM    F_GetManPTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') p  ' +dbo.F_GetPtypeUnitsAndRates('p','1,4,5','4')

	SET @strGetManPTypeAll +=' WHERE	P.TypeID LIKE '''+@parid+'%''
				AND p.UserCode LIKE ''%'+@UserCode+'%''
				AND p.FullName LIKE ''%'+@FullName+'%''
				AND ISNULL(p.EntryCode,'''') LIKE ''%' + @EntryCode + '%''
				AND ISNULL(p.Area,'''') 	 LIKE ''%' + @area + '%''
				AND ISNULL(p.Standard,'''') LIKE ''%' + @Standard + '%''
				AND ISNULL(p.[Type],'''')   LIKE ''%' + @type + '%''
				AND P.TypeID<>''00000'' 
				AND p.Sonnum=0
				and p.deleted=0
	)'
	END
ELSE
 BEGIN
	 SET @strGetManPTypeAll='
		(
			SELECT 	P.typeId,
					P.UserCode,
					P.FullName,
					p.sonnum,
					p.deleted,
					p.entrycode,
						u5.fullname assistantfullname,
				u1.fullname baseunitfullname,
				u4.fullname stockunitfullname,
				r4.rate stockUnitRate 
				FROM    F_GetManPTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') p  ' +dbo.F_GetPtypeUnitsAndRates('p','1,4,5','4')
			SET @strGetManPTypeAll +='	WHERE	P.TypeID LIKE '''+@parid+'%''
					AND p.UserCode LIKE ''%'+@UserCode+'%''
					AND p.FullName LIKE ''%'+@FullName+'%''
					AND ISNULL(p.EntryCode,'''') LIKE ''%' + @EntryCode + '%''
					AND ISNULL(p.Area,'''') 	 LIKE ''%' + @area + '%''
					AND ISNULL(p.Standard,'''') LIKE ''%' + @Standard + '%''
					AND ISNULL(p.[Type],'''')   LIKE ''%' + @type + '%''
					AND P.TypeID<>''00000'' 
					AND p.Sonnum=0
		)'
 
 END
PRINT  @strGetManPTypeAll
 
 IF @szKtypeId='' OR @szKtypeId='00000'   SELECT @szKtypeId='%'	-- 全部仓库

-------------------------------------------------------查询代销未结算情况------------------------------------
IF @IfLendBorrow = '1'						--===============================================================显示借欠
	BEGIN
		--历史状况才用到的临时表
		CREATE TABLE #InOutStockTable(
			PTypeId		varchar(100),
			Qty			 NUMERIC(24, 10) ,
			KTypeId		varchar(100),
			BillType	int,
			STypeId		VARCHAR(50)
		)
		DECLARE @XXX varchar(MAX)
		
		
		--缩小了的InOutStockTable
		IF ISDATE(@EndDataPoint) = 1 
			BEGIN
				SET @XXX = '
					INSERT INTO #InOutStockTable
					SELECT 	a.PTypeID,
							a.Qty,
							a.KTypeID,
							a.BillType,
							a.STypeId
					FROM 	InOutStockTable a
					INNER JOIN '+@strGetManPTypeAll+' b ON a.PTypeID=b.TypeID					
					WHERE 	a.Audited = 1
							AND a.Qty<>0
							AND a.BillType IN (140,142,144,146,141,145,205)
							AND (a.KTypeId IN (SELECT Typeid FROM #GetManKTypeId) OR a.KTypeId = ''10000'')
							AND a.Billdate <='+char(39)+@EndDataPoint+char(39)

				PRINT(@XXX)
				EXEC(@XXX)
			END	


		IF ISDATE(@EndDataPoint)=1	--历史的代销记录
		BEGIN
				--委托已发货
				SELECT  B.PTypeID,
						ABS(SUM(ISNULL(B.Qty,0))) AS Qty
				INTO    #TempWtyF
				FROM (
					SELECT	PTypeID,
							ABS(SUM(ISNULL(Qty,0))) AS Qty 				
					FROM	#InOutStockTable 
					WHERE 	(BillType=140) 
							AND KTypeID='10000'
					GROUP BY PTypeID
					UNION ALL
					SELECT	a.PTypeID,
							ABS(SUM(ISNULL(a.Qty,0))) AS Qty 
					FROM 	IniCommissionStock a
					INNER JOIN #GetSelectSTypeId b
					ON a.Stypeid=b.TypeId
					WHERE	a.Type = 140
					GROUP BY	a.PTypeID
				) B
				GROUP BY
					B.PTypeID

				--委托已结算		
				SELECT	PTypeID,
						ABS(SUM(ISNULL(Qty,0))) AS Qty 
				INTO	#TempWtyJ 
				FROM	#InOutStockTable 
				WHERE 	(BillType=141) 
						AND KTypeID='10000' 
				GROUP BY PTypeID


				--委托已退货
				SELECT	PTypeID,
						ABS(SUM(ISNULL(Qty,0))) AS Qty 
				INTO	#TempWtyT 
				FROM	#InOutStockTable 
				WHERE 	(BillType=142) 
						AND KTypeID='10000' 
				GROUP BY PTypeID


				SELECT 	F.PTypeID,
						Qty = ISNULL(SUM(F.Qty),0) - ISNULL(SUM(J.Qty),0) - ISNULL(SUM(T.Qty),0)
				INTO 	#TempDxyF1
				FROM    #TempWtyF F
						LEFT JOIN
						(
							SELECT	PTypeID,
									ISNULL(SUM(Qty),0) AS Qty
							FROM    #TempWtyJ
							GROUP  BY PTypeID
						)J ON (F.PTypeID = J.PTypeID)
						LEFT JOIN
						(
							SELECT	PTypeID,
									ISNULL(SUM(Qty),0) AS Qty
							FROM    #TempWtyT
							GROUP  BY PTypeID
						)T ON (F.PTypeID = T.PTypeID)
				GROUP  BY F.PTypeID

				SELECT  B.PTypeID,
						ABS(SUM(ISNULL(B.Qty,0))) AS Qty
				INTO    #TempStyF
				FROM (
					SELECT	PTypeID,
							ABS(SUM(ISNULL(Qty,0))) AS Qty 				
					FROM	#InOutStockTable 
					WHERE 	(BillType=144) 
							AND KTypeID='10000'
					GROUP BY PTypeID
					UNION ALL
					SELECT	PTypeID,
							ABS(SUM(ISNULL(Qty,0))) AS Qty 
					FROM 	IniCommissionStock a
					INNER JOIN #GetSelectSTypeId b
					ON a.Stypeid=b.TypeId
					WHERE	Type = 144
					GROUP	BY
							PTypeID
				) B
				GROUP BY
					B.PTypeID

				--受托已结算		
				SELECT	PTypeID,
						ABS(SUM(ISNULL(Qty,0))) AS Qty 
				INTO	#TempStyJ 
				FROM	#InOutStockTable 
				WHERE 	(BillType=145) 
						AND KTypeID='10000' 
				GROUP BY PTypeID

				--受托已退货
				SELECT	PTypeID,
						ABS(SUM(ISNULL(Qty,0))) AS Qty 
				INTO	#TempStyT 
				FROM	#InOutStockTable 
				WHERE 	(BillType=146) 
						AND KTypeID='10000' 
				GROUP BY PTypeID


				SELECT 	F.PTypeID,
						Qty = ISNULL(SUM(F.Qty),0) - ISNULL(SUM(J.Qty),0) - ISNULL(SUM(T.Qty),0)
				INTO 	#TempDxyS1
				FROM    #TempStyF F
						LEFT JOIN
						(
							SELECT	PTypeID,
									ISNULL(SUM(Qty),0) AS Qty
							FROM    #TempStyJ
							GROUP  BY PTypeID
						)J ON (F.PTypeID = J.PTypeID)
						LEFT JOIN
						(
							SELECT	PTypeID,
									ISNULL(SUM(Qty),0) AS Qty
							FROM    #TempStyT
							GROUP  BY PTypeID
						)T ON (F.PTypeID = T.PTypeID)
				GROUP  BY F.PTypeID
			END
		ELSE	
			BEGIN
				SELECT	ms.PTypeID,ISNULL(SUM(ms.Qty),0) AS Qty
				INTO 	#TempDxyF
				FROM 	CommissionStock  ms
						INNER JOIN #GetSelectSTypeId s ON ms.Stypeid=s.TypeId
				WHERE	ms.Type=140
				GROUP BY ms.PTypeID
		
				--谢吉康  2003-07-14 改变受托已收货的计算方式
				SELECT	ms.PTypeID,ISNULL(SUM(ms.Qty),0) AS Qty
				INTO 	#TempDxyS
				FROM 	CommissionStock ms
						INNER JOIN #GetSelectSTypeId s ON ms.Stypeid=s.TypeId
				WHERE	ms.Type=144
				GROUP BY ms.PTypeID
			END		
		--谢吉康    2003-8-20   改变写法，加快了速度
		DECLARE
			@strTemp	VARCHAR(MAX)
			
		CREATE TABLE #LastResult2(
			TypeID		VARCHAR(200),
			WnQty		 NUMERIC(24, 10) ,
			SnQty		 NUMERIC(24, 10) ,
			LendQty		 NUMERIC(24, 10) ,
			BorrowQty	 NUMERIC(24, 10) 
		)
		
		CREATE TABLE #LastResult(
			TypeID		VARCHAR(200),
			WnQty		 NUMERIC(24, 10) ,
			SnQty		 NUMERIC(24, 10) ,
			LendQty		 NUMERIC(24, 10) ,
			BorrowQty	 NUMERIC(24, 10) 
		)
		
		
		

		IF ISDATE(@EndDataPoint)=1	--历史的代销记录
			BEGIN
				SET @strTemp='	
				INSERT #LastResult2
				SELECT b.*
				FROM 
				(
					SELECT  c.TypeID,
							c.WnQty,
							c.SnQty,
							0 AS LendQty,
							0 AS BorrowQty
					FROM
					(				
						SELECT 	p.TypeID,
								ISNULL(SUM(a.Qty),0) AS WnQty,
								0 AS SnQty
						FROM 	'+@strGetManPTypeAll+' p,
								#TempDxyF1 a
						WHERE 	p.TypeID = a.PTypeID
						GROUP BY p.TypeID
						UNION ALL
						SELECT 	p.TypeID,
								0 AS WnQty,
								ISNULL(SUM(b.Qty),0) AS SnQty
						FROM 	'+@strGetManPTypeAll+' p,
								#TempDxyS1 b
						WHERE 	p.TypeID = b.PTypeID
						GROUP BY p.TypeID
					)c		
					UNION ALL
					SELECT	PtypeID,
							0 AS WnQty,
							0 AS SnQty,
							(ISNULL(SUM(LEND),0)-ISNULL(SUM(LENDBack),0))  AS LENDqty,
							(ISNULL(SUM(Borrow),0)-ISNULL(SUM(BorrowBack),0))  AS Borrowqty
					FROM 	V_LendStatus 
					WHERE 	PtypeID LIKE '''+@parid+'%''
							AND KtypeID IN (SELECT * FROM #GetSelectKTypeId)
							AND BillDate<= CASE isDate('+CHAR(39)+@ENDDataPoint+CHAR(39)+') WHEN 1 THEN '+CHAR(39)+@ENDDataPoint+CHAR(39)+' ELSE GETDATE()+5000 END
					GROUP BY PtypeID
				)B
				'
				
				--PRINT(@strTemp)
				
				EXEC(@strTemp)
			END
		ELSE
			BEGIN
				SET @strTemp='
				INSERT #LastResult		
				SELECT b.*
				FROM 
				(
					SELECT  c.TypeID,
							c.WnQty,
							c.SnQty,
							0 AS LendQty,
							0 AS BorrowQty
					FROM
					(				
						SELECT 	p.TypeID,
								ISNULL(SUM(a.Qty),0) AS WnQty,
								0 AS SnQty
						FROM 	'+@strGetManPTypeAll+' p,
								#TempDxyF a
						WHERE 	p.TypeID = a.PTypeID
						GROUP BY p.TypeID
						UNION ALL
						SELECT 	p.TypeID,
								0 AS WnQty,
								ISNULL(SUM(b.Qty),0) AS SnQty
						FROM 	'+@strGetManPTypeAll+' p,
								#TempDxyS b
						WHERE 	p.TypeID = b.PTypeID
						GROUP BY p.TypeID
					)c		
					UNION ALL
					SELECT	PtypeID,
							0 AS WnQty,
							0 AS SnQty,
							(ISNULL(SUM(Lend),0)-ISNULL(SUM(LendBack),0))  AS Lendqty,
							(ISNULL(SUM(Borrow),0)-ISNULL(SUM(BorrowBack),0))  AS Borrowqty
					FROM 	V_LendStatus a
					INNER JOIN #GetSelectKTypeId b
					ON a.KTypeID=b.TypeID
					WHERE 	PtypeID LIKE '''+@parid+'%''
							AND BillDate<= CASE isDate('+CHAR(39)+@ENDDataPoint+CHAR(39)+') WHEN 1 THEN '+CHAR(39)+@ENDDataPoint+CHAR(39)+' ELSE GETDATE()+5000 END
					GROUP BY PtypeID
				)B
				'
				--PRINT(@strTemp)
				EXEC(@strTemp)
			END
	END
ELSE							--===============================================================不显示借欠
	BEGIN
		SELECT 	'0' AS TypeID,
				0 AS WnQty,
				0 AS SnQty,
				0 AS Lendqty,
				0 AS BorrowQty
		INTO 	#LastResult1
		FROM    Ptype
		WHERE TypeId = '00000'
	END
-------------------------------------------------------查询代销未结算情况------------------------------------
BEGIN



--最终数据
CREATE TABLE #LastHisResult
(
	PTypeId		VARCHAR(100),
	Qty			 NUMERIC(24, 10) ,
	nqty		 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	LendQty		 NUMERIC(24, 10) ,
	BorrowQty	 NUMERIC(24, 10) ,
	WnQty		 NUMERIC(24, 10) ,
	SnQty		 NUMERIC(24, 10) 
)

--***************************************************************************************历史库存状况表 谢吉康  2003-09-18 新增
IF isDate(@EndDataPoint)=1
BEGIN
	--优化历史状况 谢吉康 2010-05-26
	CREATE TABLE #HisResult
	(
		PTypeId		VARCHAR(100),
		Qty			 NUMERIC(24, 10) ,
		nqty		 NUMERIC(24, 10) ,
		Total		 NUMERIC(24, 10) 
	)

	--算期初
	SET @SQL = 'INSERT INTO #HisResult
				(
					PTypeId,
					Qty,
					Total,
					nqty
				)
             	SELECT 	Q.PTypeId,
						ISNULL(SUM(a.Qty),0) AS Qty,
						ISNULL(SUM(a.Total),0) AS Total, 
						ISNULL(SUM(q.nQty),0) AS nQty
				FROM 	(SELECT SUM(QTY) AS qty,SUM(total) as total,ptypeid,ktypeid FROM IniGoodsStocks GROUP BY ptypeid,ktypeid) a
				RIGHT join ( SELECT SUM(NQty) AS NQTY,PTypeID,KTypeID FROM  dbo.Ini_GOODSSTOCKS_QTY GROUP BY PTypeID,KTypeID)   q  on a.ptypeid = q.ptypeid and a.ktypeid = q.ktypeid
				INNER JOIN #GetSelectKTypeId b
				ON a.KTypeID=b.TypeID
				INNER JOIN #GetManPTypeId c
				ON Q.PTypeID=c.TypeID
				GROUP BY Q.PTypeId	'
	EXEC(@SQL)

	--算历史库存	
	SET @SQL = 'INSERT INTO #HisResult
				(
					PTypeId,
					Qty,
					Total,
					nqty
				)
             	SELECT 	a.PTypeId,
						ISNULL(SUM(a.Qty),0) AS Qty,
						ISNULL(SUM(a.CostTotal),0) AS Total,
						ISNULL(SUM(a.nQty),0) AS nQty 
				FROM 	InOutStockTable a
				INNER JOIN #GetSelectKTypeId b ON a.KTypeID=b.TypeID
				INNER JOIN #GetManPTypeId c ON a.PTypeID=c.TypeID
				WHERE a.KTypeID<>''10000''
  					  AND a.Audited = 1 
					  AND a.billdate <='+char(39)+@EndDataPoint+char(39)+'
				GROUP BY a.PTypeId	'
	EXEC(@SQL)
	--最终数据
	

	SET @SQL = 'INSERT INTO #LastHisResult
				SELECT	B.PTypeId,
						ISNULL(SUM(B.Qty),0) AS Qty,
						ISNULL(SUM(b.nQty),0) AS nQty,
						ISNULL(SUM(B.Total),0) AS Total,
						ISNULL(SUM(B.LendQty),0) AS LendQty,
						ISNULL(SUM(B.BorrowQty),0) AS BorrowQty,
						ISNULL(SUM(B.WnQty),0) AS WnQty,
						ISNULL(SUM(B.SnQty),0) AS SnQty
				FROM	(
							SELECT	PTypeId,
									ISNULL(SUM(Qty),0) AS Qty,
									ISNULL(SUM(nqty),0) AS nQty,
									ISNULL(SUM(Total),0) AS Total,
									0 AS LendQty,
									0 AS BorrowQty,
									0 AS WnQty,
									0 AS SnQty
							FROM	#HisResult
							GROUP BY PTypeId
							UNION ALL
							SELECT	TypeID AS PTypeId,
									0 AS Qty,
									0 AS nqty,
									0 AS Total,
									LendQty,
									Borrowqty,
									WnQty,
									SnQty'
						IF @IfLendBorrow = '1'
							SELECT @SQL = @SQL +' FROM #LastResult2'
						ELSE
							SELECT @SQL = @SQL +' FROM	#LastResult1'
	SET @SQL = @SQL + ')B
				GROUP BY PTypeId'
	EXEC(@SQL)
	
	SELECT @SQL ='SELECT B.* FROM ('

	SELECT @SQL = @SQL + '
			SELECT	a.typeid,
					a.usercode,
					a.fullname,
					a.sonnum,
					a.deleted,
					a.entrycode,
					a.assistantfullname,
					a.baseunitfullname,
					a.stockunitfullname,
					ISNULL(SUM(b.qty),0)/a.stockUnitRate AS kqty,
					a.stockUnitRate, 
					SUM(ISNULL(b.qty,0)) AS qty,
					SUM(ISNULL(b.nqty,0)) AS nqty,'
		IF @IfLendBorrow = '1' 
          		SELECT @Sql=@Sql+' 
					ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.lENDqty),0)+ISNULL(SUM(b.borrowqty),0) AS sjczqty,
					ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.SnQty),0)+ISNULL(SUM(b.WnQty),0) AS sjyyqty,
					(ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.Lendqty),0)+ISNULL(SUM(b.Borrowqty),0)+ISNULL(SUM(b.WnQty),0)-ISNULL(SUM(b.SnQty),0)) AS factqty'
		ELSE
				SELECT @Sql=@Sql+'  
					0 AS sjczqty,
					0 AS sjyyqty,
					0 AS factqty '

				SELECT @Sql=@Sql+'  ,
					CASE
						WHEN '+CAST(@PriceType AS varchar(10))+'=0  THEN CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
						WHEN '+CAST(@PriceType AS varchar(10))+'=1  THEN Pr.PreSalePrice1
						WHEN '+CAST(@PriceType AS varchar(10))+'=2  THEN Pr.PreSalePrice2
						WHEN '+CAST(@PriceType AS varchar(10))+'=3  THEN Pr.PreSalePrice3
						WHEN '+CAST(@PriceType AS varchar(10))+'=4  THEN Pr.PreSalePrice4
						WHEN '+CAST(@PriceType AS varchar(10))+'=5  THEN Pr.PreSalePrice5
						WHEN '+CAST(@PriceType AS varchar(10))+'=6  THEN Pr.PreSalePrice6
						WHEN '+CAST(@PriceType AS varchar(10))+'=7  THEN Pr.PreSalePrice7
						WHEN '+CAST(@PriceType AS varchar(10))+'=8  THEN Pr.PreSalePrice8
						WHEN '+CAST(@PriceType AS varchar(10))+'=9  THEN Pr.PreSalePrice9
						WHEN '+CAST(@PriceType AS varchar(10))+'=10 THEN Pr.PreSalePrice10
						WHEN '+CAST(@PriceType AS varchar(10))+'=11 THEN Pr.PreBuyPrice1
						WHEN '+CAST(@PriceType AS varchar(10))+'=12 THEN Pr.PreBuyPrice2
						WHEN '+CAST(@PriceType AS varchar(10))+'=13 THEN Pr.PreBuyPrice3
						WHEN '+CAST(@PriceType AS varchar(10))+'=14 THEN Pr.PreBuyPrice4
						WHEN '+CAST(@PriceType AS varchar(10))+'=15 THEN Pr.PreBuyPrice5
						WHEN '+CAST(@PriceType AS varchar(10))+'=16 THEN Pr.RetailPrice
						WHEN '+CAST(@PriceType AS varchar(10))+'=17 THEN Pr.TopSalePrice
						WHEN '+CAST(@PriceType AS varchar(10))+'=18 THEN Pr.LowSalePrice
						WHEN '+CAST(@PriceType AS varchar(10))+'=19 THEN Pr.TopBuyPrice
						ELSE CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
					END AS price,
					CASE 
						WHEN '+CAST(@PriceType AS varchar(10))+'=0  THEN ISNULL(SUM(b.total),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=1  THEN ISNULL(Pr.PreSalePrice1,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=2  THEN ISNULL(Pr.PreSalePrice2,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=3  THEN ISNULL(Pr.PreSalePrice3,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=4  THEN ISNULL(Pr.PreSalePrice4,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=5  THEN ISNULL(Pr.PreSalePrice5,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=6  THEN ISNULL(Pr.PreSalePrice6,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=7  THEN ISNULL(Pr.PreSalePrice7,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=8  THEN ISNULL(Pr.PreSalePrice8,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=9  THEN ISNULL(Pr.PreSalePrice9,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=10 THEN ISNULL(Pr.PreSalePrice10,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=11 THEN ISNULL(Pr.PreBuyPrice1,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=12 THEN ISNULL(Pr.PreBuyPrice2,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=13 THEN ISNULL(Pr.PreBuyPrice3,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=14 THEN ISNULL(Pr.PreBuyPrice4,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=15 THEN ISNULL(Pr.PreBuyPrice5,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=16 THEN ISNULL(Pr.RetailPrice,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=17 THEN ISNULL(Pr.TopSalePrice,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=18 THEN ISNULL(Pr.LowSalePrice,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS varchar(10))+'=19 THEN ISNULL(Pr.TopBuyPrice,0)*ISNULL(SUM(b.Qty),0)
						ELSE ISNULL(SUM(b.total),0)
					END AS total '
			IF @IfLendBorrow = '1' 
				BEGIN
		          		SELECT @Sql=@Sql+' ,
							ISNULL(SUM(b.LENDqty),0) AS Lendqty,
							ISNULL(SUM(b.Borrowqty),0) AS Borrowqty,
							ISNULL(SUM(b.WnQty),0) AS WnQty,
							ISNULL(SUM(b.SnQty),0) AS SnQty'
				END
			ELSE
		        	SELECT @Sql=@Sql+' ,
						0 AS LENDqty,
						0 AS BorrowQty,
						0 AS WnQty,
						0 AS SnQty '
			SELECT @SQL = @SQL +'  
			        FROM '+@strGetManPTypeAll+' a
					INNER JOIN PType_Price Pr ON Pr.PTypeId = A.TypeId
					LEFT JOIN
			        (
						SELECT	PTypeId,
								Qty,
								nqty,
								Total,
								LendQty,
								BorrowQty,
								WnQty,
								SnQty
						FROM	#LastHisResult
					)b	ON a.TypeId=b.ptypeid'
			
			SELECT @SQL = @SQL +'
			GROUP BY 
					a.typeid,
					a.usercode,
					a.fullname,
					a.sonnum,
					a.deleted,
					a.entrycode,
					a.assistantfullname,
					a.baseunitfullname,
					a.stockunitfullname,
					a.stockUnitRate, 
					Pr.PreSalePrice1,
					Pr.PreSalePrice2,
					Pr.PreSalePrice3,
					Pr.PreSalePrice4,
					Pr.PreSalePrice5,
					Pr.PreSalePrice6,
					Pr.PreSalePrice7,
					Pr.PreSalePrice8,
					Pr.PreSalePrice9,
					Pr.PreSalePrice10,
					Pr.PreBuyPrice1,
					Pr.PreBuyPrice2,
					Pr.PreBuyPrice3,
					Pr.PreBuyPrice4,
					Pr.PreBuyPrice5,
					Pr.RetailPrice,
					Pr.TopSalePrice,
					Pr.LowSalePrice,
					Pr.TopBuyPrice'

			SELECT @SQL = @SQL +'
			)b'
				---------------------------------------------------// 判断实际库存是否为0 //--------------------------------------------------
				IF (@showzeroqty = '0' AND @IFLENDBorrow = '1')
					SELECT @SQL = @SQL +' WHERE  
						(ISNULL(b.qty,0)-ISNULL(b.Lendqty,0)+ISNULL(b.Borrowqty,0)) <> 0'
				ELSE
					BEGIN
						IF (@showzeroqty = '0')
							SELECT @SQL = @SQL + ' WHERE (ISNULL(b.Qty,0)<>0)'
					END
				---------------------------------------------------// 按照不同的字段排序 //---------------------------------------------------

				IF @SortField='usercode' SELECT @Sql=@Sql+' ORDER BY b.usercode'
				IF @SortField='fullname' SELECT @Sql=@Sql+' ORDER BY b.fullname'
				IF @SortField='qty' SELECT @Sql=@Sql+' ORDER BY b.qty'
				IF @SortField='borrowqty' SELECT @Sql=@Sql+' ORDER BY b.borrowqty'
				IF @SortField='lendqty' SELECT @Sql=@Sql+' ORDER BY b.lendqty'
				IF @SortField='price' SELECT @Sql=@Sql+' ORDER BY b.price'
				------------------------------------// 判断是否是按照升序排序还是按照降序排序 //-----------------------------------------------

				IF @sorttype='DESC' SELECT @Sql=@Sql+' DESC'
				IF @sorttype='ASC' SELECT @Sql=@Sql+' ASC'

				--PRINT(@SQL)
				EXEC(@SQL)

				DROP TABLE #HisResult
END
--***************************************************************************************
ELSE
	IF @szPeriod='' --本期
	BEGIN
		SET @SQL = 'INSERT INTO #LastHisResult
					SELECT 	g.ptypeid,
							SUM(g.qty) AS qty,
							0 AS nqty,
							SUM(g.total) AS total,
							0 AS LENDqty,
							0 AS Borrowqty,
							0 AS WnQty,
							0 AS SnQty 
					FROM Goodsstocks g
					
					INNER JOIN #GetManPTypeId b ON g.PTypeID=b.TypeID
					INNER JOIN #GetSelectKTypeId c ON g.KTypeID=c.TypeID
					WHERE	g.PTypeId LIKE '+char(39)+@Parid+'%'+char(39)+'
					GROUP BY g.ptypeid 	
					
					UNION ALL
						SELECT	GQ.PTypeId AS PTypeId,
											0	AS Qty,
											GQ.nqty AS nqty,
											0 AS Total,
											0 AS LendQty,
											0 AS BorrowQty,
											0 AS WnQty,
											0 AS SnQty
									FROM #GOODSSTOCKS_QTY GQ
									INNER JOIN #GetManPTypeId P ON P.TypeId = GQ.PtypeId
									INNER JOIN #GetManKTypeId MK ON MK.TypeId = GQ.KtypeId
									INNER JOIN PTYPE PP ON PP.TypeId = GQ.PtypeId
					UNION ALL
					SELECT	TypeID,
							0 AS Qty,
							0 AS nqty,
							0 AS Total,
							LENDqty,
							Borrowqty,
							WnQty,
							SnQty'
					IF @IfLendBorrow = '1'
						SELECT @SQL = @SQL +' FROM #LastResult'
					ELSE
						SELECT @SQL = @SQL +' FROM	#LastResult1' 
						
		
		EXEC(@SQL)	
	
		
		CREATE CLUSTERED INDEX CIX_PTypeID ON #LastHisResult(PTypeID)
		

		SELECT @SQL ='SELECT B.* FROM ('
	
	   --------------------------谢吉康 2002-06-27加速库存状况查询------------------------------------------

		SELECT @Sql=@SQL+'SELECT	a.typeid,
							a.fullname,
							a.usercode,
							a.sonnum,
							a.deleted,
							a.entrycode,
							ISNULL(a.assistantfullname,'''') AS assistantfullname,
							ISNULL(a.baseunitfullname,'''') AS baseunitfullname,
							ISNULL(a.stockunitfullname,'''') AS stockunitfullname,
							ISNULL(SUM(b.qty),0)/a.stockUnitRate AS kqty,
							--(''1''+ISNULL(a.stockunitfullname,'''')+''=''+ CAST(a.stockUnitRate AS varchar) + a.baseunitfullname) AS unitrate,
							a.stockUnitRate, 	
				 			ISNULL(SUM(b.qty),0)  AS qty, 
				 			ISNULL(SUM(b.nqty),0)  AS nqty,'
		IF @IFLENDBorrow = '1' 
          		SELECT @Sql=@Sql+' 
					ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.lENDqty),0)+ISNULL(SUM(b.borrowqty),0) AS sjczqty,
					ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.SnQty),0)+ISNULL(SUM(b.WnQty),0) AS sjyyqty,
					(ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.Lendqty),0)+ISNULL(SUM(b.Borrowqty),0)+ISNULL(SUM(b.WnQty),0)-ISNULL(SUM(b.SnQty),0)) AS factqty'
		ELSE

				SELECT @Sql=@Sql+'
					0 AS sjczqty,
					0 AS sjyyqty,
					0 AS factqty'
			

				SELECT @Sql=@Sql+'  ,
						CASE
							WHEN '+CAST(@PriceType AS varchar(10))+'=0  THEN CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
							WHEN '+CAST(@PriceType AS varchar(10))+'=1  THEN Pr.PreSalePrice1
							WHEN '+CAST(@PriceType AS varchar(10))+'=2  THEN Pr.PreSalePrice2
							WHEN '+CAST(@PriceType AS varchar(10))+'=3  THEN Pr.PreSalePrice3
							WHEN '+CAST(@PriceType AS varchar(10))+'=4  THEN Pr.PreSalePrice4
							WHEN '+CAST(@PriceType AS varchar(10))+'=5  THEN Pr.PreSalePrice5
							WHEN '+CAST(@PriceType AS varchar(10))+'=6  THEN Pr.PreSalePrice6
							WHEN '+CAST(@PriceType AS varchar(10))+'=7  THEN Pr.PreSalePrice7
							WHEN '+CAST(@PriceType AS varchar(10))+'=8  THEN Pr.PreSalePrice8
							WHEN '+CAST(@PriceType AS varchar(10))+'=9  THEN Pr.PreSalePrice9
							WHEN '+CAST(@PriceType AS varchar(10))+'=10 THEN Pr.PreSalePrice10
							WHEN '+CAST(@PriceType AS varchar(10))+'=11 THEN Pr.PreBuyPrice1
							WHEN '+CAST(@PriceType AS varchar(10))+'=12 THEN Pr.PreBuyPrice2
							WHEN '+CAST(@PriceType AS varchar(10))+'=13 THEN Pr.PreBuyPrice3
							WHEN '+CAST(@PriceType AS varchar(10))+'=14 THEN Pr.PreBuyPrice4
							WHEN '+CAST(@PriceType AS varchar(10))+'=15 THEN Pr.PreBuyPrice5
							WHEN '+CAST(@PriceType AS varchar(10))+'=16 THEN Pr.RetailPrice
							WHEN '+CAST(@PriceType AS varchar(10))+'=17 THEN Pr.TopSalePrice
							WHEN '+CAST(@PriceType AS varchar(10))+'=18 THEN Pr.LowSalePrice
							WHEN '+CAST(@PriceType AS varchar(10))+'=19 THEN Pr.TopBuyPrice
							ELSE CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
						END AS price,
						CASE 
							WHEN '+CAST(@PriceType AS varchar(10))+'=0  THEN ISNULL(SUM(b.total),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=1  THEN ISNULL(Pr.PreSalePrice1,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=2  THEN ISNULL(Pr.PreSalePrice2,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=3  THEN ISNULL(Pr.PreSalePrice3,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=4  THEN ISNULL(Pr.PreSalePrice4,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=5  THEN ISNULL(Pr.PreSalePrice5,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=6  THEN ISNULL(Pr.PreSalePrice6,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=7  THEN ISNULL(Pr.PreSalePrice7,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=8  THEN ISNULL(Pr.PreSalePrice8,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=9  THEN ISNULL(Pr.PreSalePrice9,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=10 THEN ISNULL(Pr.PreSalePrice10,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=11 THEN ISNULL(Pr.PreBuyPrice1,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=12 THEN ISNULL(Pr.PreBuyPrice2,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=13 THEN ISNULL(Pr.PreBuyPrice3,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=14 THEN ISNULL(Pr.PreBuyPrice4,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=15 THEN ISNULL(Pr.PreBuyPrice5,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=16 THEN ISNULL(Pr.RetailPrice,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=17 THEN ISNULL(Pr.TopSalePrice,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=18 THEN ISNULL(Pr.LowSalePrice,0)*ISNULL(SUM(b.Qty),0)
							WHEN '+CAST(@PriceType AS varchar(10))+'=19 THEN ISNULL(Pr.TopBuyPrice,0)*ISNULL(SUM(b.Qty),0)
							ELSE ISNULL(SUM(b.total),0)
						END AS total '
			IF @IFLENDBorrow = '1' 
				BEGIN
		          		SELECT @Sql=@Sql+' ,
							ISNULL(SUM(b.LENDqty),0) AS Lendqty,
							ISNULL(SUM(b.Borrowqty),0) AS Borrowqty,
							ISNULL(SUM(b.WnQty),0) AS WnQty,
							ISNULL(SUM(b.SnQty),0) AS SnQty'
				END
			ELSE
		        	SELECT @Sql=@Sql+' ,
						0 AS LENDqty,
						0 AS BorrowQty,
						0 AS WnQty,
						0 AS SnQty '
			SET @Sql=@Sql+					'
					FROM '+@strGetManPTypeAll+' a 
					INNER JOIN PType_Price Pr ON Pr.PTypeId = A.TypeId
				    LEFT JOIN
				            (
								SELECT	PTypeId,
										Qty,
										nqty,
										Total,
										LendQty,
										BorrowQty,
										WnQty,
										SnQty
								FROM	#LastHisResult
					     	) AS b ON (a.typeid=b.ptypeid)'							
	
				IF (@showzeroqty='0' AND @IFLENDBorrow <> '1') 
						SELECT @Sql=@Sql + ' WHERE b.Qty<>0 OR b.nqty!=0 '							
							
				SELECT @Sql=@Sql+' GROUP BY 
											a.typeid,
											a.fullname,
											a.usercode,
											a.sonnum,
											a.deleted,
											a.entrycode,
											a.assistantfullname,
											a.baseunitfullname,
											a.stockunitfullname,
											a.stockUnitRate, 
											Pr.PreSalePrice1,
											Pr.PreSalePrice2,
											Pr.PreSalePrice3,
											Pr.PreSalePrice4,
											Pr.PreSalePrice5,
											Pr.PreSalePrice6,
											Pr.PreSalePrice7,
											Pr.PreSalePrice8,
											Pr.PreSalePrice9,
											Pr.PreSalePrice10,
											Pr.PreBuyPrice1,
											Pr.PreBuyPrice2,
											Pr.PreBuyPrice3,
											Pr.PreBuyPrice4,
											Pr.PreBuyPrice5,
											Pr.RetailPrice,
											Pr.TopSalePrice,
											Pr.LowSalePrice,
											Pr.TopBuyPrice'
			SELECT @SQL = @SQL +'
			)b '
				---------------------------------------------------// 判断实际库存是否为0 //--------------------------------------------------
				IF (@showzeroqty = '0' AND @IFLENDBorrow = '1')
					SELECT @SQL = @SQL +' WHERE  
						(ISNULL(b.qty,0)-ISNULL(b.Lendqty,0)+ISNULL(b.Borrowqty,0)) <> 0'

				--排序
				SET @SQL = @SQL + ' ORDER BY B.'+@SortField+' '+@sorttype


				--PRINT(@Sql)
				EXEC (@Sql)	
				
				
	END 
END

DROP TABLE #GetManKTypeId,#GetSelectKTypeId,#LastHisResult,#GetSelectSTypeId










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_qrStockAll_List]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_qrStockAll_List]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2005-3-23
	描述：重写了期初的算法
	包含：1）当前库存状况标   2）历史库存状况表  3）库存期初
exec Gp_qrStockAll_List @OperatorID='00001',@EndDataPoint='',@Parid='00000',@szKtypeId='',@IFLENDBorrow='1',@szPeriod='',@UserCode='',@FullName='',@EntryCode='',@Standard='',@type='',@area='',@PriceType='0'
*/

CREATE	PROCEDURE Gp_qrStockAll_List
( 
	@OperatorID 	VARCHAR(100),  	    	--操作员ID号
	@EndDataPoint  	VARCHAR(10)='',      	--某一日期的库存
	@Parid   		VARCHAR(100)='00000',   --商品的父节点号
	@szKtypeId  	VARCHAR(8000)='',       --仓库id号
	@IfLendBorrow 	VARCHAR(1)=1,			--是否显示借欠
	@szPeriod  		VARCHAR(2)='',          --期号
	@UserCode 		VARCHAR(100)='',		--商品编号
	@FullName 		VARCHAR(66)='',			--商品名称
	@EntryCode		VARCHAR(200),			--商品条码
	@Standard		VARCHAR(200),			--商品规格
	@type			VARCHAR(200),			--商品型号
	@area			VARCHAR(200),			--商品产地
	@PriceType		INT=0,					--价格方式
	@stypeid		VARCHAR(8000)='',		--分支机构,
	@isshowstop     int=0                   --是否显示停用 0显示停用，1为不显示。   
)
--@encode$--
AS



SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
           @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL VARCHAR(MAX)

--商品线性表
CREATE TABLE #GetManPTypeId(TypeId	VARCHAR(100))

IF @isshowstop=1
	BEGIN
		INSERT INTO #GetManPTypeId(TypeId) SELECT TypeID FROM dbo.F_GetManPTypeAll(@OperatorID) WHERE SonNum = 0 AND deleted=0
	END
	
ELSE
	BEGIN
		INSERT INTO #GetManPTypeId(TypeId) SELECT TypeID FROM dbo.F_GetManPTypeAll(@OperatorID) WHERE SonNum = 0
	END	

--IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = '00001' AND MangerPTypeID = '00000')
--BEGIN
--	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeID FROM PType WHERE SonNum = 0
--END
--ELSE
--BEGIN
--IF @isshowstop=1
-- BEGIN
--  INSERT INTO #GetManPTypeId(TypeId)
--	SELECT	DISTINCT P.TypeId 
--	FROM	PType_L L
--	INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
--	WHERE	L.etypeid = @OperatorID
--			AND L.flag = 1 
--			AND P.sonnum = 0
--			AND p.deleted=0
-- END
--ELSE
-- BEGIN 
--	INSERT INTO #GetManPTypeId(TypeId)
--	SELECT	DISTINCT P.TypeId 
--	FROM	PType_L L
--	INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
--	WHERE	L.etypeid = @OperatorID
--			AND L.flag = 1 
--			AND P.sonnum = 0
--  END			
--END


DECLARE
	@strPTypeIDAll	VARCHAR(MAX)
	
IF	EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerPTypeID = '00000')
BEGIN
 IF @isshowstop =1
 BEGIN
	SET @strPTypeIDAll='
	SELECT 	P.typeId,
			P.ParId,
			P.leveal,
			p.deleted,
			P.sonnum,
			P.soncount,
			P.CanModify,
			P.UserCode,
			P.FullName,
			P.Name,
			P.Standard,
			P.Type,
			P.Area,
			P.Unit1,
			P.Unit2,
			P.UnitRate1,
			P.UnitRate2,
			P.EntryCode	
	FROM 	PType P
	WHERE 	P.TypeId <> ''00000'' and p.deleted=0
	'
	END
	ELSE
	BEGIN
	SET @strPTypeIDAll='
	SELECT 	P.typeId,
			P.ParId,
			P.leveal,
			p.deleted,
			P.sonnum,
			P.soncount,
			P.CanModify,
			P.UserCode,
			P.FullName,
			P.Name,
			P.Standard,
			P.Type,
			P.Area,
			P.Unit1,
			P.Unit2,
			P.UnitRate1,
			P.UnitRate2,
			P.EntryCode	
	FROM 	PType P
	WHERE 	P.TypeId <> ''00000'' 
	'
	END 
END
ELSE
BEGIN
  IF @isshowstop =1
  BEGIN 
  SET @strPTypeIDAll='
	SELECT 	P.typeId,
			P.ParId,
			P.leveal,
			p.deleted,
			P.sonnum,
			P.soncount,
			P.CanModify,
			P.UserCode,
			P.FullName,
			P.Name,
			P.Standard,
			P.Type,
			P.Area,
			P.Unit1,
			P.Unit2,
			P.UnitRate1,
			P.UnitRate2,
			P.EntryCode	
	FROM 	F_GetManDetailAllPType('+CHAR(39)+@OperatorID+CHAR(39)+') M
	INNER JOIN PType P ON P.TypeId = M.TypeId where p.deleted=0
	'
  END
ELSE
 BEGIN
 SET @strPTypeIDAll='
	SELECT 	P.typeId,
			P.ParId,
			P.leveal,
				p.deleted,
			P.sonnum,
			P.soncount,
			P.CanModify,
			P.UserCode,
			P.FullName,
			P.Name,
			P.Standard,
			P.Type,
			P.Area,
			P.Unit1,
			P.Unit2,
			P.UnitRate1,
			P.UnitRate2,
			P.EntryCode	
	FROM 	F_GetManDetailAllPType('+CHAR(39)+@OperatorID+CHAR(39)+') M
	INNER JOIN PType P ON P.TypeId = M.TypeId
	'
 END	
	
END
	
--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
		

CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT A.Typeid FROM F_GetAllBaseTypeId(@szKtypeId,4) AS A  
INNER JOIN F_GetManDetailKTypeSType(@OperatorID) mk
ON A.TypeId=mk.TypeId
INNER JOIN #GetSelectSTypeId s ON mk.STypeId=s.TypeId



CREATE CLUSTERED INDEX  CIX_PTypeID ON #GetManPTypeId(TypeID)
CREATE CLUSTERED INDEX  CIX_KTypeID ON #GetManKTypeId(TypeID)

CREATE TABLE #PU 
(
	PTYPEID		VARCHAR(50),
	ufullname	VARCHAR(400),
	UnitsId		INT,
	Rate		 NUMERIC(24, 10) 
)
INSERT INTO #PU (PTYPEID,ufullname,UnitsId,Rate)
SELECT	A.PtypeID AS PtypeID,
		B.FullName AS ufullname,
		A.UnitsId AS UnitsId,
		A.Rate AS Rate
FROM PTYPE_UNITS_EXT A
INNER JOIN PTYPE_UNITS B ON A.UnitsId=B.UnitsId


CREATE CLUSTERED INDEX CIX_Pu_PTypeID ON #PU(PTYPEID)

CREATE TABLE #GOODSSTOCKS_QTY 
(
	PTYPEID		VARCHAR(50),
	KTYPEID		VARCHAR(50),
	NQTY		 NUMERIC(24, 10) 
)
INSERT INTO #GOODSSTOCKS_QTY (PTYPEID,KTYPEID,NQTY)
SELECT	PTypeID,
		KTypeID,
		SUM(NQty) AS NQTY
FROM GOODSSTOCKS_QTY G
INNER JOIN #GetManKTypeId K	ON K.typeid=G.KtypeID
INNER JOIN #GetManPTypeId P ON G.PTypeId=P.typeid
GROUP BY PTypeID,KTypeID

CREATE TABLE #Ini_GOODSSTOCKS_QTY
(
	PTYPEID		VARCHAR(50),
	KTYPEID		VARCHAR(50),
	NQTY		 NUMERIC(24, 10) 
)
INSERT INTO #Ini_GOODSSTOCKS_QTY (PTYPEID,KTYPEID,NQTY)
SELECT	PTypeID,
		KTypeID,
		SUM(NQty) AS NQTY
FROM Ini_GOODSSTOCKS_QTY G
INNER JOIN #GetManKTypeId K	ON K.typeid=G.KtypeID
INNER JOIN #GetManPTypeId P ON G.PTypeId=P.typeid
GROUP BY PTypeID,KTypeID

DECLARE @PTypeIdMx 	VARCHAR(100),@SonNum		INT

IF @parid = '00000' AND @MPtypeid<>'-99999'
	SET @parid=@MPtypeid
	
SELECT	@SonNum = SonNum FROM PType WHERE TypeId = @Parid 

IF @parid = '00000'
	SET @PTypeIdMx = '%'
ELSE
	SET @PTypeIdMx = @ParId
	
IF @szKtypeId='' OR @szKtypeId='00000'   
	SET @szKtypeId='%'

IF @IfLendBorrow = '1'    --显示借进借出
	BEGIN
		--缩小的PType表
		DECLARE
			@strTempPType	VARCHAR(MAX)
		
		SELECT @strTempPType='
		SELECT 	A.Parid,
				A.TypeID,
				A.UserCode,
				A.FullName,
				A.Sonnum 
		FROM 	
		(
		'+@strPTypeIdAll+'
		) A
		WHERE 	A.UserCode LIKE ''%'+@UserCode+'%''
				AND A.FullName LIKE ''%'+@FullName+'%''
				AND ISNULL(A.EntryCode,'''') LIKE ''%' + @EntryCode + '%''
				AND ISNULL(A.Standard,'''') LIKE ''%' + @Standard + '%''
				AND ISNULL(A.[Type],'''')   LIKE ''%' + @type + '%''
				AND ISNULL(A.Area,'''') 	 LIKE ''%' + @area + '%''
				AND A.TypeID<>''00000'' 
				AND A.TypeID LIKE '''+@PTypeIdMx+'%''
				AND A.TypeID IN (SELECT Typeid FROM #GetManPTypeId)
		'		
		
		--缩小了的InOutStockTable
		DECLARE @InOutSQL	VARCHAR(MAX)

		CREATE TABLE #InOutStockTable(
			PTypeId		VARCHAR(100),
			ID			VARCHAR(100),
			BillNumberId VARCHAR(100),
			Qty			 NUMERIC(24, 10) ,
			KTypeId		VARCHAR(100),
			BillType	int
		)

	
		SET @InOutSQL = '
			INSERT INTO	#InOutStockTable 
			SELECT	PTypeId,
					ID,
					BillNumberId,
					Qty,
					KTypeId,
					BillType 			
			FROM	InOutStockTable
			WHERE 	Audited = 1
					AND KTypeID=''10000''
					AND BillType IN (140,142,144,146,141,145)					
					AND PTypeId IN (SELECT A.TypeId FROM ('+@strTempPType+') A )
					AND (KTypeId IN (SELECT Typeid FROM #GetManKTypeId) OR KTypeId = ''10000'')
					AND (STYPEID IN (SELECT typeid FROM #GetSelectSTypeId)) '

		IF IsDate(@EndDataPoint)=1
			SET @InOutSQL = @InOutSQL + ' AND billdate <='+CHAR(39)+@EndDataPoint+CHAR(39)
			
		EXEC(@InOutSQL)				

		SELECT  B.PTypeID,ABS(SUM(ISNULL(B.Qty,0))) AS Qty
		INTO    #TempWtyF
		FROM (
				SELECT	PTypeID,
						ABS(SUM(ISNULL(Qty,0))) AS Qty 				
				FROM	#InOutStockTable 
				WHERE 	(BillType=140) 
						AND KTypeID='10000'
				GROUP BY PTypeID
				UNION ALL
				SELECT	a.PTypeID,
						ABS(SUM(ISNULL(a.Qty,0))) AS Qty 
				FROM 	IniCommissionStock a
				INNER JOIN #GetSelectSTypeId b
				ON a.Stypeid=b.TypeId
				WHERE	a.Type = 140
				GROUP BY	a.PTypeID
		) B
		GROUP BY
			B.PTypeID
		
		--委托已结算		
		SELECT	PTypeID,
				ABS(SUM(ISNULL(Qty,0))) AS Qty 
		INTO	#TempWtyJ 
		FROM	#InOutStockTable 
		WHERE 	(BillType=141) 
				AND KTypeID='10000' 
		GROUP BY PTypeID

		--委托已退货
		SELECT	PTypeID,
				ABS(SUM(ISNULL(Qty,0))) AS Qty 
		INTO	#TempWtyT 
		FROM	#InOutStockTable 
		WHERE 	(BillType=142) 
				AND KTypeID='10000' 
		GROUP BY PTypeID

		SELECT 	F.PTypeID,
				Qty = ISNULL(SUM(F.Qty),0) - ISNULL(SUM(J.Qty),0) - ISNULL(SUM(T.Qty),0)
		INTO 	#TempDxyF1
		FROM    #TempWtyF F
				LEFT JOIN
				(
					SELECT	PTypeID,
							ISNULL(SUM(Qty),0) AS Qty
					FROM    #TempWtyJ
					GROUP  BY PTypeID
				)J ON (F.PTypeID = J.PTypeID)
				LEFT JOIN
				(
					SELECT	PTypeID,
							ISNULL(SUM(Qty),0) AS Qty
					FROM    #TempWtyT
					GROUP  BY PTypeID
				)T ON (F.PTypeID = T.PTypeID)
		GROUP  BY F.PTypeID

		--===========================================受托
		SELECT  B.PTypeID,
				ABS(SUM(ISNULL(B.Qty,0))) AS Qty
		INTO    #TempStyF
		FROM (
			SELECT	PTypeID,
					ABS(SUM(ISNULL(Qty,0))) AS Qty 				
			FROM	#InOutStockTable 
			WHERE 	(BillType=144) 
					AND KTypeID='10000'
			GROUP BY PTypeID
			UNION ALL
			SELECT	PTypeID,
					ABS(SUM(ISNULL(Qty,0))) AS Qty 
			FROM 	IniCommissionStock a
			INNER JOIN #GetSelectSTypeId b
			ON a.Stypeid=b.TypeId
			WHERE	Type = 144
			GROUP	BY
					PTypeID
		) B
		GROUP BY
			B.PTypeID

		--受托已结算		
		SELECT	PTypeID,
				ABS(SUM(ISNULL(Qty,0))) AS Qty 
		INTO	#TempStyJ 
		FROM	#InOutStockTable 
		WHERE 	(BillType=145) 
				AND KTypeID='10000' 
		GROUP BY PTypeID

		--受托已退货
		SELECT	PTypeID,
				ABS(SUM(ISNULL(Qty,0))) AS Qty 
		INTO	#TempStyT 
		FROM	#InOutStockTable 
		WHERE 	(BillType=146) 
				AND KTypeID='10000' 
		GROUP BY PTypeID


		SELECT 	F.PTypeID,
				Qty = ISNULL(SUM(F.Qty),0) - ISNULL(SUM(J.Qty),0) - ISNULL(SUM(T.Qty),0)
		INTO 	#TempDxyS1
		FROM    #TempStyF F
				LEFT JOIN
				(
					SELECT	PTypeID,
							ISNULL(SUM(Qty),0) AS Qty
					FROM    #TempStyJ
					GROUP  BY PTypeID
				)J ON (F.PTypeID = J.PTypeID)
				LEFT JOIN
				(
					SELECT	PTypeID,
							ISNULL(SUM(Qty),0) AS Qty
					FROM    #TempStyT
					GROUP  BY PTypeID
				)T ON (F.PTypeID = T.PTypeID)
		GROUP  BY F.PTypeID
		
		DROP Table #TempWtyF,#TempWtyJ,#TempWtyT,#TempStyF --Wang Wei 2010-7-7 删除不用的临时表				
			
		
		--代销汇总的处理
		CREATE TABLE #LastDxResult(
			TypeId	VARCHAR(100),
			Qty		 NUMERIC(24, 10) ,
			WnQty	 NUMERIC(24, 10) ,
			SnQty	 NUMERIC(24, 10) 
		)
		SELECT @SQL='		
				INSERT INTO #LastDxResult
				SELECT 	p.TypeID,
						p.Qty,
						p.WnQty,
						ISNULL(SUM(b.Qty),0) AS SnQty				
				FROM
				(
						SELECT 	p.TypeID,
								ISNULL(SUM(A.qty),0) AS qty,
								ISNULL(SUM(A.Qty),0) AS WnQty			
						FROM 	
						(
						'+@strTempPType+'
						) p
						LEFT JOIN 
						(
							SELECT 	PtypeID,ISNULL(SUM(Qty),0) AS Qty
							FROM 	#TempDxyF1
							GROUP BY PtypeID	
						)a ON (p.TypeID=LEFT(A.PTypeID,LEN(p.TypeID)))
						GROUP BY P.TypeID
				)p
				LEFT JOIN 
				(
					SELECT	PtypeID,ISNULL(SUM(Qty),0) AS Qty
					FROM 	#TempDxyS1
					GROUP BY PtypeID
				)b ON (p.TypeID=LEFT(b.PTypeID,LEN(p.TypeID)))	
				GROUP BY p.TypeID,p.Qty,p.WnQty
				
				DROP TABLE #TempDxyF1
				'
				
				--PRINT(@SQL)				
				EXEC(@SQL)
			
	END
	
--*********************************************************历史库存状况数据开始************************************************--
IF IsDate(@EndDataPoint)=1
	BEGIN
		--用临时表来收缩数据
		
		--预先处理期初和当前之前的数据
		IF @IfLendBorrow = '1'    --显示借进借出
			BEGIN
				SET @SQL = '
					WITH LSResult AS
					(
						SELECT	B.PTypeId,
								B.Rate AS Rate,
								SUM(B.Qty) AS Qty,
								SUM(B.Qty)/B.Rate AS kqty,
								SUM(B.NQTY) AS NQty,
								SUM(Total) AS Total,
								SUM(LendQty) AS LendQty,
								SUM(BorrowQty) AS BorrowQty,
								SUM(WnQty) AS WnQty,
								SUM(SnQty) AS SnQty
						FROM	(	
									SELECT	A.PTypeId AS PTypeId,
											A.Qty AS Qty,
											A.Total AS Total,
											Pu_k.Rate AS Rate,
											0 AS nqty,
											0 AS LendQty,
											0 AS BorrowQty,
											0 AS WnQty,
											0 AS SnQty
									FROM	IniGoodsStocks A
									INNER JOIN #GetManPTypeId P ON A.PTypeId=P.typeid
									INNER JOIN #GetManKTypeId K	ON K.typeid=A.KtypeID
									INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 
									UNION ALL
									SELECT	I.PTypeId,
											SUM(i.Qty) AS Qty,
											SUM(i.CostTotal) AS Total,
											Pu_k.Rate AS Rate,
											SUM(i.nQty) AS nqty,
											0 AS LendQty,
											0 AS BorrowQty,
											0 AS WnQty,
											0 AS SnQty
									FROM	InOutStockTable i
									INNER JOIN  #GetManPTypeId  p ON p.typeid=i.ptypeid
									INNER JOIn  #GetManKTypeId k ON k.typeid=i.ktypeid
									INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 
									WHERE	i.Audited = 1
											--AND i.Qty<>0
											AND i.KTypeId <> ''10000''
											AND i.billdate <='''+@EndDataPoint+'''
									GROUP BY	i.PTypeId,
												Pu_k.Rate
									UNION ALL
									SELECT	v.PTypeId,
											0 AS Qty,
											0 AS Total,
											Pu_k.Rate AS Rate,
											0 AS nqty,
											SUM(v.Lend-v.LendBack) AS LendQty,
											SUM(v.Borrow-v.BorrowBack) AS BorrowQty,
											0 AS WnQty,
											0 AS SnQty
									FROM	V_LendStatus  v
									INNER JOIN #GetManPTypeId p ON p.TypeId=v.pTypeID
									INNER JOIN #GetManKTypeId k ON k.TypeId=v.kTypeID
									INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 
									WHERE v.BillDate<='''+@EndDataPoint+'''
									GROUP BY	v.PTypeId,
												PU_K.Rate
									UNION ALL
									SELECT	l.TypeId AS PTypeId,
											0 AS Qty,
											0 AS Total,
											Pu_k.Rate AS Rate,
											0 AS nqty,
											0 AS LendQty,
											0 AS BorrowQty,
											SUM(l.WnQty) AS WnQty,
											SUM(l.SnQty) AS SnQty
									FROM	#LastDxResult	l
									INNER JOIN PTYPE PP ON PP.TypeId = L.typeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND L.typeId=PU_K.PtypeID 				
									GROUP BY	l.TypeId,
												PU_K.Rate
									UNION ALL
									SELECT	GQ.PTypeId AS PTypeId,
											0 AS Qty,
											0 AS Total,
											Pu_k.Rate AS Rate,
											GQ.nQty AS nqty,
											0 AS LendQty,
											0 AS BorrowQty,
											0 AS WnQty,
											0 AS SnQty
									FROM #Ini_GOODSSTOCKS_QTY GQ
									INNER JOIN #GetManPTypeId P ON GQ.PTypeId=P.typeid
									INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 
						)B 
						GROUP BY	B.PTypeId,
									B.Rate
					)'
			--PRINT @SQL
			END
		ELSE
			BEGIN
				SET @SQL = '
					WITH LSResult AS
					(
					SELECT	B.PTypeId,
							B.Rate AS Rate,
							SUM(B.Qty) AS Qty,
							SUM(B.Qty)/B.Rate AS kqty,
							SUM(B.NQTY) AS NQty,
							SUM(Total) AS Total,
							0 AS LendQty,
							0 AS BorrowQty,
							0 AS WnQty,
							0 AS SnQty
					FROM	(	
								SELECT	I.PTypeId,
										SUM(I.Qty) AS Qty,
										SUM(I.Total) AS Total,
										Pu_k.Rate AS Rate,
										0 AS nqty,
										0 AS LendQty,
										0 AS BorrowQty,
										0 AS WnQty,
										0 AS SnQty
								FROM	IniGoodsStocks I
								--INNER JOIN #GetSelectKTypeId  SK	ON I.KtypeID=SK.typeid
								INNER JOIN #GetManPTypeId  P		ON I.PTypeId=P.typeid
								INNER JOIN #GetManKTypeId K			ON K.typeid=I.KtypeID
								INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
								LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 
								GROUP BY	I.PTypeId,
											Pu_k.Rate 
								UNION ALL
								SELECT	I.PTypeId,
										SUM(I.Qty) AS Qty,
										SUM(CostTotal) AS Total,
										Pu_k.Rate AS Rate,
										SUM(i.nqty) AS nqty,
										0 AS LendQty,
										0 AS BorrowQty,
										0 AS WnQty,
										0 AS SnQty
								FROM	InOutStockTable i
								--INNER JOIN  #GetSelectKTypeId sk ON sk.typeid=i.ktypeid
								INNER JOIN  #GetManPTypeId  p ON p.typeid=i.ptypeid
								INNER JOIn  #GetManKTypeId k ON k.typeid=i.ktypeid
								INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
								LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 
								WHERE	i.Audited = 1
										--AND i.Qty<>0
										AND i.KTypeId <> ''10000''
										AND i.billdate <='''+@EndDataPoint+'''
								GROUP BY	I.PTypeId,
											PU_K.Rate
								UNION ALL
								SELECT	I.PTypeId,
										0 AS Qty,
										0 AS Total,
										Pu_k.Rate AS Rate,
										SUM(I.nQty) AS nqty,
										0 AS LendQty,
										0 AS BorrowQty,
										0 AS WnQty,
										0 AS SnQty
								FROM #Ini_GOODSSTOCKS_QTY I
								INNER JOIN #GetManPTypeId  P	ON I.PTypeId=P.typeid
								INNER JOIN #GetManKTypeId K		ON K.typeid=I.KtypeID
								INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
								LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 
								GROUP BY	I.PTypeId,
											Pu_k.Rate 
					)B 
					GROUP BY	B.PTypeId,
								B.Rate
					)'
			
			END
		--正式处理查询数据
		SET @SQL = @SQL+'
			SELECT	A.TypeID,
					A.fullname,
					A.usercode,
					ISNULL(A.EntryCode,'''') AS EntryCode,
					ISNULL(A.Standard,'''') AS Standard,
					ISNULL(A.Type,'''') AS Type,
					ISNULL(A.Area,'''') AS Area,
					A.sonnum,
					A.leveal,
					a.deleted,
					A.parid,
					ISNULL(A.unit1,'''') AS unit1,
					ISNULL(A.unit2,'''') AS unit2,
					A.unitrate1,
					B.*
			FROM ( '+@strPTypeIDAll+'
			) A
			INNER JOIN
			(
					SELECT 	A.typeid,
					ISNULL(Pu_k.Rate,0) AS Rate,
					PU_B.ufullname AS bufullname,
					ISNULL(SUM(b.qty),0) AS qty,
					PU_K.ufullname AS kufullname,
					ISNULL(SUM(b.kqty),0) AS kqty,
					PU_AS.ufullname AS asufullname,
					ISNULL(SUM(b.nqty),0) AS nqty,
					CASE
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=0  THEN CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=1  THEN Pr.PreSalePrice1
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=2  THEN Pr.PreSalePrice2
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=3  THEN Pr.PreSalePrice3
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=4  THEN Pr.PreSalePrice4
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=5  THEN Pr.PreSalePrice5
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=6  THEN Pr.PreSalePrice6
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=7  THEN Pr.PreSalePrice7
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=8  THEN Pr.PreSalePrice8
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=9  THEN Pr.PreSalePrice9
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=10 THEN Pr.PreSalePrice10
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=11 THEN Pr.PreBuyPrice1
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=12 THEN Pr.PreBuyPrice2
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=13 THEN Pr.PreBuyPrice3
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=14 THEN Pr.PreBuyPrice4
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=15 THEN Pr.PreBuyPrice5
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=16 THEN Pr.RetailPrice
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=17 THEN Pr.TopSalePrice
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=18 THEN Pr.LowSalePrice
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=19 THEN Pr.TopBuyPrice
						ELSE CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
					END AS price,
					CASE 
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=0  THEN ISNULL(SUM(b.total),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=1  THEN ISNULL(Pr.PreSalePrice1,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=2  THEN ISNULL(Pr.PreSalePrice2,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=3  THEN ISNULL(Pr.PreSalePrice3,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=4  THEN ISNULL(Pr.PreSalePrice4,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=5  THEN ISNULL(Pr.PreSalePrice5,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=6  THEN ISNULL(Pr.PreSalePrice6,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=7  THEN ISNULL(Pr.PreSalePrice7,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=8  THEN ISNULL(Pr.PreSalePrice8,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=9  THEN ISNULL(Pr.PreSalePrice9,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=10 THEN ISNULL(Pr.PreSalePrice10,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=11 THEN ISNULL(Pr.PreBuyPrice1,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=12 THEN ISNULL(Pr.PreBuyPrice2,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=13 THEN ISNULL(Pr.PreBuyPrice3,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=14 THEN ISNULL(Pr.PreBuyPrice4,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=15 THEN ISNULL(Pr.PreBuyPrice5,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=16 THEN ISNULL(Pr.RetailPrice,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=17 THEN ISNULL(Pr.TopSalePrice,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=18 THEN ISNULL(Pr.LowSalePrice,0)*ISNULL(SUM(b.Qty),0)
						WHEN '+CAST(@PriceType AS VARCHAR(10))+'=19 THEN ISNULL(Pr.TopBuyPrice,0)*ISNULL(SUM(b.Qty),0)
						ELSE ISNULL(SUM(b.total),0)
					END AS total '

			IF @IfLendBorrow = '1'    --显示借进借出
				SET @SQL=@SQL+',
						ISNULL(SUM(b.LendQty),0) AS LendQty,
						ISNULL(SUM(b.Borrowqty),0) AS Borrowqty,
						ISNULL(SUM(b.WnQty),0) AS WnQty,
						ISNULL(SUM(b.SnQty),0) AS SnQty,
						ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.LendQty),0)+ISNULL(SUM(b.borrowqty),0) AS sjczqty,
						ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.SnQty),0)+ISNULL(SUM(b.WnQty),0) AS sjyyqty '
			ELSE
				SET @SQL=@SQL+',
						0 AS LendQty,
						0 AS BorrowQty,
						0 AS WnQty,
						0 AS SnQty,
						0 AS sjczqty,
						0 AS sjyyqty '

			SET @SQL = @SQL + '
				FROM	
				(
				'+@strPTypeIDAll+'
				)  A
				INNER JOIN PType_Price Pr ON Pr.PTypeId = A.TypeId
				LEFT JOIN (
					SELECT	PTypeId,
							Rate,
							SUM(ISNULL(Qty,0)) AS Qty,
							SUM(ISNULL(KQty,0)) AS KQty,
							SUM(ISNULL(NQty,0)) AS NQty,
							SUM(ISNULL(Total,0)) AS Total,
							SUM(ISNULL(LendQty,0)) AS LendQty,
							SUM(ISNULL(BorrowQty,0)) AS BorrowQty,
							SUM(ISNULL(WnQty,0)) AS WnQty,
							SUM(ISNULL(SnQty,0)) AS SnQty
					FROM LSResult
					GROUP BY	PTypeId,
								Rate
				)B  ON LEFT(B.PTypeId,LEN(A.TypeId)) = A.TypeId
				INNER JOIN PTYPE PP ON PP.TypeId = a.typeId
				LEFT JOIN #PU PU_AS ON PU_AS.UnitsId=PP.AssistantUnitId AND a.typeId=PU_AS.PtypeID 
				LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND a.typeId=PU_K.PtypeID 
				LEFT JOIN #PU PU_B ON PU_B.UnitsId=PP.baseUnitId AND a.typeId=PU_B.PtypeID
				WHERE	A.TypeId <> ''00000''
						AND ISNULL(A.EntryCode,'''') LIKE '+CHAR(39)+'%'+@EntryCode+'%'+CHAR(39)+'
						AND ISNULL(A.Standard,'''')  LIKE '+CHAR(39)+'%'+@Standard+'%'+CHAR(39)+'
						AND ISNULL(A.[Type],'''')  LIKE '+CHAR(39)+'%'+@type+'%'+CHAR(39)+'
						AND ISNULL(A.Area,'''')  LIKE '+CHAR(39)+'%'+@area+'%'+CHAR(39)	

			IF @SonNum = 0
				SET @SQL = @SQL + ' AND A.TypeId LIKE '+CHAR(39)+@ParId+'%'+CHAR(39)
			ELSE
				SET @SQL = @SQL + ' AND A.ParId = '+CHAR(39)+@ParId+CHAR(39)

			SET	@SQL = @SQL + 'GROUP BY
					A.TypeID,
					Pr.PreSalePrice1,
					Pr.PreSalePrice2,
					Pr.PreSalePrice3,
					Pr.PreSalePrice4,
					Pr.PreSalePrice5,
					Pr.PreSalePrice6,
					Pr.PreSalePrice7,
					Pr.PreSalePrice8,
					Pr.PreSalePrice9,
					Pr.PreSalePrice10,
					Pr.PreBuyPrice1,
					Pr.PreBuyPrice2,
					Pr.PreBuyPrice3,
					Pr.PreBuyPrice4,
					Pr.PreBuyPrice5,
					Pr.RetailPrice,
					Pr.TopSalePrice,
					Pr.LowSalePrice,
					Pr.TopBuyPrice,
					Pu_k.Rate,
					PU_B.ufullname,
					PU_K.ufullname,
					PU_AS.ufullname
			
			) B ON A.TypeID=B.TypeID 
			ORDER BY A.UserCode '
			--PRINT @sql
			EXEC(@SQL)
			--删除临时表
	END
ELSE
	BEGIN
		--*********************************************************当前库存状况数据开始************************************************--
		IF @szPeriod='' --本期
			BEGIN
				--大数据量下首次要超时，重写算法
				
				IF @IfLendBorrow = '1'    --显示借进借出
				BEGIN
					SET @SQL='
					WITH TempResult
					AS
					(
						SELECT		B.PTypeId,
									B.Rate AS Rate,
									SUM(B.Qty) AS Qty,
									SUM(B.Qty)/B.Rate AS kqty,
									SUM(B.NQTY) AS NQty,
									SUM(B.Total) AS Total,
									SUM(B.LendQty) AS LendQty,
									SUM(B.BorrowQty) AS BorrowQty,
									SUM(B.WnQty) AS WnQty,
									SUM(B.SnQty) AS SnQty
						FROM	(
									SELECT	G.PTypeId AS PTypeId,
											G.Qty AS Qty,
											Total,
											Pu_k.Rate AS Rate,
											0 AS nqty,
											0 AS LendQty,
											0 AS BorrowQty,
											0 AS WnQty,
											0 AS SnQty
									FROM	GoodsStocks G
									INNER JOIN #GetManPTypeId P ON P.TypeId = G.PtypeId
									INNER JOIN #GetManKTypeId MK ON MK.TypeId = G.KtypeId
									INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 
									UNION ALL
									SELECT	G.PtypeId AS PTypeId,
											0 AS Qty,
											0 AS Total,
											Pu_k.Rate AS Rate,
											0 AS NQTY,
											(Lend-LendBack) AS LendQty,
											(Borrow-BorrowBack) AS BorrowQty,
											0 AS WnQty,
											0 AS SnQty
									FROM	V_LendStatus G
									INNER JOIN #GetManPTypeId P ON P.TypeId = G.PtypeId
									INNER JOIN #GetManKTypeId MK ON MK.TypeId = G.KtypeId	
									INNER JOIN PTYPE PP ON PP.TypeId = P.typeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND P.typeId=PU_K.PtypeID 							
									UNION ALL
									SELECT	L.TypeId AS PTypeId,
											0 AS qty,
											0 AS total,
											Pu_k.Rate AS Rate,
											0 AS NQTY,
											0 AS LendQty,
											0 AS BorrowQty,
											WnQty,
											SnQty
									FROM #LastDxResult L
									INNER JOIN PTYPE PP ON PP.TypeId = L.typeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND L.typeId=PU_K.PtypeID 
									UNION ALL
									SELECT	GQ.PTypeId AS PTypeId,
											0	AS Qty,
											0 AS Total,
											Pu_k.Rate AS Rate,
											GQ.nqty AS nqty,
											0 AS LendQty,
											0 AS BorrowQty,
											0 AS WnQty,
											0 AS SnQty
									FROM #GOODSSTOCKS_QTY GQ
									INNER JOIN #GetManPTypeId P ON P.TypeId = GQ.PtypeId
									INNER JOIN #GetManKTypeId MK ON MK.TypeId = GQ.KtypeId
									INNER JOIN PTYPE PP ON PP.TypeId = GQ.PtypeId
									LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND GQ.KtypeId=PU_K.PtypeID 
						)B 
						GROUP BY	B.PTypeId,
									B.Rate
					)
					'						
				END
				ELSE
				BEGIN
					SET @SQL = '
			WITH TempResult AS 
     (SELECT PtypeId ,
           SUM( Rate)rate ,
            SUM(Qty) AS qty ,
            SUM(Qty) /SUM( Rate) AS kqty ,
            SUM(nqty) AS nqty ,
            SUM(Total) AS Total ,
            0 AS LendQty ,
            0 AS BorrowQty ,
            0 AS WnQty ,
            0 AS SnQty
     FROM   ( SELECT    G.PtypeId ,
                        Pu_k.Rate AS Rate ,
                        SUM(G.Qty) AS qty ,
                        SUM(G.Qty) / pu_k.Rate AS kqty ,
                        0 AS nqty ,
                        SUM(G.Total) AS Total ,
                        0 AS LendQty ,
                        0 AS BorrowQty ,
                        0 AS WnQty ,
                        0 AS SnQty
              FROM      GoodsStocks G
                        INNER JOIN #GetManPTypeId P ON P.TypeId = G.PtypeId
                        INNER JOIN ptype PP ON P.TypeId = PP.typeId
                        INNER JOIN #GetManKTypeId MK ON MK.TypeId = G.KtypeId
                        LEFT JOIN #PU PU_K ON PU_K.UnitsId = PP.StockUnitId
                                              AND PP.typeId = PU_K.PtypeID
              GROUP BY  G.PTypeId ,
                        pu_k.Rate
              UNION ALL
              SELECT    GQ.PtypeId ,
                        0 AS Rate ,
                        0 AS qty ,
                        0 AS kqty ,
                        GQ.nQty AS nqty ,
                        0 AS Total ,
                        0 AS LendQty ,
                        0 AS BorrowQty ,
                        0 AS WnQty ,
                        0 AS SnQty
              FROM      #GOODSSTOCKS_QTY GQ
                        INNER JOIN #GetManPTypeId P ON P.TypeId = GQ.PtypeId
                        INNER JOIN #GetManKTypeId MK ON MK.TypeId = GQ.KtypeId
            ) b
     GROUP BY PtypeId)
					'
				END
				--正式处理查询数据
				SET @SQL = @SQL+'
					SELECT 
							A.typeid,
							A.fullname,
							A.usercode,
							ISNULL(A.EntryCode,'''') AS EntryCode,
							ISNULL(A.Standard,'''') AS Standard,
							ISNULL(A.Type,'''') AS Type,
							ISNULL(A.Area,'''') AS Area,
							A.sonnum,
							A.leveal,
							a.deleted,
							A.parid,
							ISNULL(A.unit1,'''') AS unit1,
							ISNULL(A.unit2,'''') AS unit2,
							A.unitrate1,
							b.*
					FROM 
					('+@strPTypeIDAll+'
					) A
					INNER JOIN
					(
				
						SELECT	A.TypeID,
								isnull(Pu_k.Rate,0) AS Rate,
								PU_B.ufullname AS bufullname,
								ISNULL(SUM(b.qty),0) AS qty,
								PU_K.ufullname AS kufullname,
								ISNULL(SUM(b.kqty),0) AS kqty,
								PU_AS.ufullname AS asufullname,
								ISNULL(SUM(b.nqty),0) AS nqty,
							CASE
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=0  THEN CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=1  THEN Pr.PreSalePrice1
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=2  THEN Pr.PreSalePrice2
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=3  THEN Pr.PreSalePrice3
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=4  THEN Pr.PreSalePrice4
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=5  THEN Pr.PreSalePrice5
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=6  THEN Pr.PreSalePrice6
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=7  THEN Pr.PreSalePrice7
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=8  THEN Pr.PreSalePrice8
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=9  THEN Pr.PreSalePrice9
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=10 THEN Pr.PreSalePrice10
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=11 THEN Pr.PreBuyPrice1
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=12 THEN Pr.PreBuyPrice2
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=13 THEN Pr.PreBuyPrice3
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=14 THEN Pr.PreBuyPrice4
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=15 THEN Pr.PreBuyPrice5
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=16 THEN Pr.RetailPrice
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=17 THEN Pr.TopSalePrice
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=18 THEN Pr.LowSalePrice
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=19 THEN Pr.TopBuyPrice
								ELSE CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
							END AS price,
							CASE 
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=0  THEN ISNULL(SUM(b.total),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=1  THEN ISNULL(Pr.PreSalePrice1,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=2  THEN ISNULL(Pr.PreSalePrice2,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=3  THEN ISNULL(Pr.PreSalePrice3,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=4  THEN ISNULL(Pr.PreSalePrice4,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=5  THEN ISNULL(Pr.PreSalePrice5,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=6  THEN ISNULL(Pr.PreSalePrice6,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=7  THEN ISNULL(Pr.PreSalePrice7,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=8  THEN ISNULL(Pr.PreSalePrice8,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=9  THEN ISNULL(Pr.PreSalePrice9,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=10 THEN ISNULL(Pr.PreSalePrice10,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=11 THEN ISNULL(Pr.PreBuyPrice1,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=12 THEN ISNULL(Pr.PreBuyPrice2,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=13 THEN ISNULL(Pr.PreBuyPrice3,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=14 THEN ISNULL(Pr.PreBuyPrice4,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=15 THEN ISNULL(Pr.PreBuyPrice5,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=16 THEN ISNULL(Pr.RetailPrice,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=17 THEN ISNULL(Pr.TopSalePrice,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=18 THEN ISNULL(Pr.LowSalePrice,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS VARCHAR(10))+'=19 THEN ISNULL(Pr.TopBuyPrice,0)*ISNULL(SUM(b.Qty),0)
								ELSE ISNULL(SUM(b.total),0)
							END AS total '
		
					IF @IfLendBorrow = '1'    --显示借进借出
						SET @SQL=@SQL+',
								ISNULL(SUM(b.LendQty),0) AS LendQty,
								ISNULL(SUM(b.Borrowqty),0) AS Borrowqty,
								ISNULL(SUM(b.WnQty),0) AS WnQty,
								ISNULL(SUM(b.SnQty),0) AS SnQty,
								ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.LendQty),0)+ISNULL(SUM(b.borrowqty),0) AS sjczqty,
								ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.SnQty),0)+ISNULL(SUM(b.WnQty),0) AS sjyyqty '
					ELSE
						SET @SQL=@SQL+',
								0 AS LendQty,
								0 AS BorrowQty,
								0 AS WnQty,
								0 AS SnQty,
								0 AS sjczqty,
								0 AS sjyyqty '
		
					SET @SQL = @SQL + '
						FROM	
						(
						'+@strPTypeIDAll+'
						) A
						INNER JOIN PType_Price Pr ON Pr.PTypeId = A.TypeId
						LEFT JOIN (
							SELECT	PTypeId,
									Rate,
									SUM(ISNULL(Qty,0)) AS Qty,
									SUM(ISNULL(KQty,0)) AS KQty,
									SUM(ISNULL(NQty,0)) AS NQty,
									SUM(ISNULL(Total,0)) AS Total,
									SUM(ISNULL(LendQty,0)) AS LendQty,
									SUM(ISNULL(BorrowQty,0)) AS BorrowQty,
									SUM(ISNULL(WnQty,0)) AS WnQty,
									SUM(ISNULL(SnQty,0)) AS SnQty
							FROM TempResult
							GROUP BY PTypeId,Rate
						)B ON LEFT(B.PTypeId,LEN(A.TypeId)) = A.TypeId				
						INNER JOIN PTYPE PP ON PP.TypeId = a.typeId
						LEFT JOIN #PU PU_AS ON PU_AS.UnitsId=PP.AssistantUnitId AND a.typeId=PU_AS.PtypeID 
						LEFT JOIN #PU PU_K ON PU_K.UnitsId=PP.StockUnitId AND a.typeId=PU_K.PtypeID 
						LEFT JOIN #PU PU_B ON PU_B.UnitsId=PP.baseUnitId AND a.typeId=PU_B.PtypeID
						WHERE	A.TypeId <> ''00000''
								AND ISNULL(A.EntryCode,'''') LIKE '+CHAR(39)+'%'+@EntryCode+'%'+CHAR(39)+'
								AND ISNULL(A.Standard,'''')  LIKE '+CHAR(39)+'%'+@Standard+'%'+CHAR(39)+'
								AND ISNULL(A.[Type],'''')  LIKE '+CHAR(39)+'%'+@type+'%'+CHAR(39)+'
								AND ISNULL(A.Area,'''')  LIKE '+CHAR(39)+'%'+@area+'%'+CHAR(39)	
		
					IF @SonNum = 0
						SET @SQL = @SQL + ' AND A.TypeId LIKE '+CHAR(39)+@ParId+'%'+CHAR(39)
					ELSE
						SET @SQL = @SQL + ' AND A.ParId = '+CHAR(39)+@ParId+CHAR(39)
		
					SET	@SQL = @SQL + '
					GROUP BY
							A.typeid,
							Pr.PreSalePrice1,
							Pr.PreSalePrice2,
							Pr.PreSalePrice3,
							Pr.PreSalePrice4,
							Pr.PreSalePrice5,
							Pr.PreSalePrice6,
							Pr.PreSalePrice7,
							Pr.PreSalePrice8,
							Pr.PreSalePrice9,
							Pr.PreSalePrice10,
							Pr.PreBuyPrice1,
							Pr.PreBuyPrice2,
							Pr.PreBuyPrice3,
							Pr.PreBuyPrice4,
							Pr.PreBuyPrice5,
							Pr.RetailPrice,
							Pr.TopSalePrice,
							Pr.LowSalePrice,
							Pr.TopBuyPrice,
							Pu_k.Rate,
							PU_B.ufullname,
							PU_K.ufullname,
							PU_AS.ufullname
							'
					
					SET @SQL=@SQL+'
					) B
					ON A.TypeID=B.TypeID
					ORDER BY A.UserCode
					'
					PRINT(@SQL)
					EXEC(@SQL)
					
					--删除临时表
					--DROP TABLE #xjkang
			END
		ELSE
		--*********************************************************期初库存状况数据开始************************************************--
			BEGIN				
		    	SELECT @SQL='
		    		WITH INIResult AS
		    		(
						SELECT	A.TypeId,
								SUM(G.Qty) AS GQty,
								SUM(G.Total) AS GTotal,
								CAST(ISNULL(SUM(g.total)/CASE WHEN SUM(g.qty)=0 THEN NULL ELSE SUM(g.qty) END ,0) AS  NUMERIC(24, 10) ) AS GPrice,
								0 AS ZQty,
								0 AS ZTotal,
								0 AS ZPrice
						FROM	IniGoodsStocks G
						INNER JOIN #PType A	ON G.PTypeId = A.TypeId
						INNER JOIN #GetManPTypeId p ON A.typeid=p.typeid
						INNER JOIN #GetManKTypeId k ON G.KTypeId=k.typeid ON sk.typeid=G.KTypeId									
						GROUP BY A.TypeId
						UNION ALL
						SELECT	A.TypeId,
								0 AS GQty,
								0 AS GTotal,
								0 AS GPrice,
								SUM(Z.Qty) AS ZQty,
								SUM(Z.Total) AS ZTotal,
								0 AS ZPrice
						FROM 	IniCommissionStock Z
						INNER JOIN #PType A	 ON Z.PTypeId = A.TypeId
						INNER JOIN #GetManPTypeId p	 ON p.TypeId = A.TypeId
						INNER JOIN #GetManKTypeId k	 ON Z.KTypeId = k.TypeId
						WHERE	Z.Type = 144
						GROUP BY A.TypeId
		    		)
		    	
		    	
		    		SELECT * 
		    		INTO #PType
		    		FROM PType A 
		    		WHERE  	A.SonNum = 0 
				    		AND A.UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
							AND A.FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+'	    		
		    		
					SELECT 	a.typeid,
							a.fullname,
							a.usercode,
							a.sonnum,
							a.leveal,
							a.deleted,
							a.parid,
							ISNULL(A.unit1,'''') AS unit1,0.
							ISNULL(A.unit2,'''') AS unit2,
							a.unitrate1,
							ISNULL(A.EntryCode,'''') AS EntryCode,
							ISNULL(A.Standard,'''') AS Standard,
							ISNULL(A.Type,'''') AS Type,
							ISNULL(A.Area,'''') AS Area,
							ISNULL(SUM(Z.Gqty),0) AS qty,
							CAST(ISNULL(SUM(Z.Gtotal)/CASE WHEN SUM(Z.Gqty)=0 THEN NULL ELSE SUM(Z.Gqty) END ,0) AS  NUMERIC(24, 10) ) AS Price,			
							ISNULL(SUM(Z.Gtotal),0) AS total,
							ISNULL(SUM(Z.Zqty),0) AS dxqty,
							ISNULL(SUM(Z.Ztotal),0) AS dxtotal
				    FROM 	
				    (
				    '+@strPTypeIDAll+'
				    ) a
					LEFT JOIN	INIResult Z ON LEFT(Z.TypeId,LEN(A.TypeId)) = A.TypeId
					WHERE	A.SonNum = 0 '
		
					--如果商品编号和商品名称都为空
					IF @SonNum>0
						SET @SQL = @SQL + ' AND A.ParId='+CHAR(39)+@ParId+CHAR(39)
					ELSE
						SET @SQL = @SQL + 'AND A.TypeId='+CHAR(39)+@ParId+CHAR(39)

					SET @SQL = @SQL + '
							AND A.UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
							AND A.FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+'
					GROUP BY
							a.typeid,
							a.fullname,
							a.usercode,
							a.sonnum,
							a.leveal,
							a.deleted,
							a.parid,
							a.unit1,
							a.unit2,
							a.unitrate1,
							a.EntryCode,
							a.Standard,
							a.Type,
							a.Area
					ORDER BY A.UserCode 
					
					DROP TABLE #PType '			
				
				--PRINT(@sql)						
				EXEC(@SQL)								
			END
	END


--DROP TABLE #GetManPTypeId,#GetManKTypeId,#PTypeIdAll,#GetSelectSTypeId
DROP TABLE #GetManPTypeId,#GetManKTypeId,#GetSelectSTypeId,#PU



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrStockIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrStockIni]
GO

/*
只用作库存期初树形表，线性表 cqhua 2009-10-19

作者：谢吉康
日期：2005-3-23
描述：重写了期初的算法
包含：1）当前库存状况标   2）历史库存状况表  3）库存期初

日期：2005-6-10
描述：增加了价格方式的选项

日期：2012-07-04
描述：周华添加了期初处理分支机构的情况 

日期：2012-10-12
描述：周华修改列表选取的Price地方，里面注释掉
日期：2012-11-19
描述：把里上面修改了price的地方改回来。

2012-12-25 周华 修改 要求库存期初显示出停用仓库的期初 把deleted的条件删除
*/

CREATE                          PROCEDURE Gp_qrStockIni
( 
	@OperatorID varchar(50),  	    	--操作员ID号
	@typeid   	varchar(50)='00000',    --商品的父节点号
	@KtypeId  	varchar(1550)='',       --仓库id号
	@UserCode 	varchar(26)='',			--商品编号
	@FullName 	varchar(66)='',			--商品名称
	@ifLine		char(1) ='0',                  -- 0 代表树形表，1代表线性表
	@stypeid	VARCHAR(8000),
	@frombilltype VARCHAR(50)=''
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

DECLARE @ssql NVARCHAR(MAX)='' --用于分支机构
DECLARE @Sql VARCHAR(8000)   ---肖伟 2002-06-27加速库存状况查询
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
---------------检查是否开帐
DECLARE @IniCanModIFy VARCHAR(10)
SELECT @IniCanModIFy=subValue FROM sysdata WHERE SubName='inicanmodIFy'
---------------上步结束
IF @UserCode='' SET @UserCode='%' ELSE SET @UserCode='%'+@UserCode+'%'
IF @FullName='' SET @FullName='%' ELSE SET @FullName='%'+@FullName+'%'


CREATE TABLE #Ptype (TypeID varchar(50),Usercode varchar(200),fullname varchar(200))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,deleted int,parid VARCHAR(100),SortID INT)

INSERT INTO #Ptype(typeid,usercode,fullname) select P.typeid,usercode,fullname from ptype P, F_GetManDetailPType(@OperatorID) W 
WHERE P.typeid=W.typeid AND p.IsService = 0 AND p.iscombinationproduct=0

DECLARE @Ksonnum int
SET @Ksonnum =0
IF @KtypeId=''
BEGIN
	INSERT INTO #Ktype select ks.typeid from F_GetManDetailKTypeSType(@OperatorID) ks
	SET @Ksonnum =1
END
ELSE
BEGIN
    --仓库
    INSERT INTO #Ktype(typeid) 
    select kb.TypeId  from F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorID) kb
	IF charindex(',',@KtypeId)>1
		SET @Ksonnum=1
	ELSE
		SELECT @Ksonnum =sonnum FROM Stock where typeid =@KtypeId
END


CREATE CLUSTERED INDEX CIX_k ON #Ktype(typeid)
DECLARE @sonnum INT
SET @sonnum =0
SELECT @sonnum = sonnum FROM Ptype WHERE Typeid=@typeid


IF @ifLine =1 -- 线性表  --cld
BEGIN   
		IF @typeid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId FROM Ptype p
			where typeid in (select typeid from F_GetManDetailPType(@OperatorID))  And p.typeid<>'00000'
			AND p.IsService = 0
			AND p.iscombinationproduct=0
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId FROM Ptype p
			where typeid in (select typeid from F_GetManDetailPType(@OperatorID) where typeid like @typeid+'%')  And p.typeid<>'00000'
			AND p.IsService = 0
			AND p.iscombinationproduct=0
END
ELSE
BEGIN
	IF @sonnum =0 	
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where typeid =@typeid) a where p.typeid=a.typeid And p.typeid<>'00000'
		AND p.IsService = 0
		AND p.iscombinationproduct=0
	ELSE
		IF @typeid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid,SortID) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId ,p.SortID FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid And p.typeid<>'00000'
			AND p.IsService = 0
			AND p.iscombinationproduct=0
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid,SortID)  
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId ,p.SortID FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid=@typeid) a where p.typeid=a.typeid And p.typeid<>'00000'
			AND p.IsService = 0
			AND p.iscombinationproduct=0

END

-- 哪果ktyeid为'',stypeid不为''，则是全选的情况，现在全选还要看分支机构，所以再排除一下
IF @stypeid<>''
BEGIN
	SET @ssql=';WITH cte AS(
		SELECT typeid,parid FROM Stype WHERE Typeid IN ('''+REPLACE(@stypeid,',',''',''')+''')
		UNION ALL
		SELECT a.typeid,a.parid FROM stype a JOIN cte b ON a.parid=b.typeid
	) DELETE FROM #Ktype WHERE typeid NOT IN (SELECT v.TypeId FROM cte W JOIN Stock v ON W.typeid=v.stypeid )';
	EXEC(@ssql);
END

---------------------------------期除

CREATE CLUSTERED INDEX IX_TEMP ON  #MainType(TYPEID)	
DECLARE @TMP VARCHAR(8000)
IF @frombilltype='fact' --实物库存
BEGIN
SET @TMP='
SELECT 
	p.typeid,
	ISNULL(p1.GQty,0)as	GQty,
	ISNULL(p1.GTotal,0) AS GTotal,
	ISNULL(p1.GPrice,0) AS GPrice,
	0 AS ZQty,
	0 AS ZTotal,
	0 AS ZPrice
INTO #A
FROM  dbo.ptype  p LEFT JOIN (

SELECT			A.TypeId,
							dbo.F_RoundQty(SUM(G.Qty) ) AS GQty,
							0 AS GTotal,
							0 AS GPrice,
							0 AS ZQty,
							0 AS ZTotal,
							0 AS ZPrice
							/*INTO #A*/
					FROM	IniFactStocks G
                            INNER JOIN #PType A ON G.PTypeId = A.TypeId '
IF NOT (@KtypeId = '' AND @MKTypeId = '00001')
      SELECT @TMP=@TMP + '  INNER JOIN #Ktype K ON  G.KtypeID = K.typeid '
SELECT @TMP=@TMP + ' WHERE	A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
							AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
					GROUP BY A.TypeId
					) p1 ON p1.TypeId = p.typeId
					WHERE  p.iscombinationproduct=0
							AND p.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
							AND p.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'  
							AND ISNULL(P.iscombinationproduct,0)=0
					CREATE CLUSTERED INDEX IX_TEMP ON  #A(TYPEID)'		

END

ELSE
BEGIN
SET @TMP='
SELECT 
	p.typeid,
	ISNULL(p1.GQty,0)as	GQty,
	ISNULL(p1.GTotal,0) AS GTotal,
	ISNULL(p1.GPrice,0) AS GPrice,
	0 AS ZQty,
	0 AS ZTotal,
	0 AS ZPrice
INTO #A
FROM  dbo.ptype  p LEFT JOIN (

SELECT			A.TypeId,
							dbo.F_RoundQty(SUM(G.Qty) ) AS GQty,
							dbo.F_RoundTotal( SUM(G.Total) ) AS GTotal,
							dbo.F_RoundPrice(CAST(ISNULL( dbo.F_RoundTotal(SUM(g.total))/CASE WHEN SUM(g.qty)=0 THEN NULL ELSE dbo.F_RoundQty(SUM(g.qty)) END ,0) AS  NUMERIC(24, 10) ))AS GPrice,
							--Max(g.Price) as Price,
							0 AS ZQty,
							0 AS ZTotal,
							0 AS ZPrice
							/*INTO #A*/
					FROM	IniGoodsStocks G
                            INNER JOIN #PType A ON G.PTypeId = A.TypeId '
IF NOT (@KtypeId = '' AND @MKTypeId = '00001')
      SELECT @TMP=@TMP + '  INNER JOIN #Ktype K ON  G.KtypeID = K.typeid '
SELECT @TMP=@TMP + ' WHERE	A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
							AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
					GROUP BY A.TypeId
					) p1 ON p1.TypeId = p.typeId
					WHERE p.iscombinationproduct=0
							AND p.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
							AND p.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'  
							AND ISNULL(P.iscombinationproduct,0)=0
					CREATE CLUSTERED INDEX IX_TEMP ON  #A(TYPEID)'		
END
					
IF @ifLine=1
BEGIN
	 SELECT @Sql=@TMP+'

	SELECT 	a.typeid,
			a.fullname,
			a.usercode,
			a.sonnum,
			dbo.F_RoundQty( ISNULL(SUM(Z.Gqty),0)  )AS qty,
			dbo.F_RoundPrice(CAST(ISNULL(dbo.F_RoundTotal(SUM(Z.Gtotal))/CASE WHEN SUM(Z.Gqty)=0 THEN NULL ELSE dbo.F_RoundQty(SUM(Z.Gqty)) END ,0) AS  NUMERIC(24, 10) ) ) AS Price,
			--Max(Z.Price) as Price,			
			dbo.F_RoundTotal(ISNULL(SUM(Z.Gtotal),0)) AS total,
			ISNULL(SUM(Z.Zqty),0) AS dxqty,
			ISNULL(SUM(Z.Ztotal),0) AS dxtotal,
	'+Convert(varchar(10),@Ksonnum)+' as ksonnum,
			a.parid
    FROM 	#MainType a
	INNER JOIN	#A  Z ON --LEFT(Z.TypeId,LEN(A.TypeId)) = A.TypeId  
			 z.TypeId = A.TypeId
			WHERE 1=1 ' 
	
IF @ifLine ='1'
	SET @SQL = @SQL + ' AND a.sonnum = 0 '	
  SET @SQL = @SQL + '
			AND A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
			AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
	GROUP BY
			a.typeid,
			a.fullname,
			a.usercode,
			a.sonnum,
			a.parid
	ORDER BY A.UserCode 
	'	
END					
ELSE
BEGIN
	SELECT @Sql=@TMP+'

		SELECT 	a.typeid,
				a.fullname,
				a.usercode,
				a.sonnum,
				dbo.F_RoundQty( ISNULL(SUM(Z.Gqty),0)  ) AS qty,
				dbo.F_RoundPrice(CAST(ISNULL( dbo.F_RoundTotal(SUM(Z.Gtotal))/CASE WHEN SUM(Z.Gqty)=0 THEN NULL ELSE dbo.F_RoundQty(SUM(Z.Gqty)) END ,0) AS  NUMERIC(24, 10) ) )AS Price,
				--Max(Z.Price) as Price,			
				dbo.F_RoundTotal(ISNULL(SUM(Z.Gtotal),0)) AS total,
				ISNULL(SUM(Z.Zqty),0) AS dxqty,
				ISNULL(SUM(Z.Ztotal),0) AS dxtotal,
		'+Convert(varchar(10),@Ksonnum)+' as ksonnum,
				a.parid
		FROM 	#MainType a
		LEFT JOIN	#A  Z ON --LEFT(Z.TypeId,LEN(A.TypeId)) = A.TypeId  
				 z.TypeId like A.TypeId+''%''
				WHERE 1=1 ' 
		
	IF @ifLine ='1'
		SET @SQL = @SQL + ' AND a.sonnum = 0 '	
	  SET @SQL = @SQL + '
				AND A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
				AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
		GROUP BY
				a.typeid,
				a.fullname,
				a.usercode,
				a.sonnum,
				a.parid,
				a.SortID
		ORDER BY A.SortID asc 
		'	--cld
END
--PRINT @SQL						
EXEC(@SQL)
DROP TABLE #Ptype,#Ktype,#MainType




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_qrWl_NewQC]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_qrWl_NewQC]
GO








/*
	查询往来对帐
	2002-1-25增加信誉额度的累加
	
	Modify	:	喻堂
	Date	:	2012/03/21
	Description:优化应收/应付线性表的执行时间
*/
CREATE          PROC Gp_qrWl_NewQC
( 
	@Parid   	VARCHAR(50),
	@szPeriod  	CHAR(2),
	@OperatorID VARCHAR(50)='00001',
	@UserCode	VARCHAR(50),	--往来单位的编号
	@FullName	VARCHAR(50),	--往来单位的名称
	@ifLine		char(1) ='0',    -- 0代表树形，1代表线性
	@Stypeid	varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


CREATE TABLE #stype(typeid VARCHAR(50))
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DECLARE @LEN1 	int
DECLARE @LEN2 	int
DECLARE @SonNum int


SELECT @SonNum = SonNum FROM BType WHERE TypeId = @Parid AND Deleted = 0

SET @LEN1 = Len(@MBtypeid)
SET @LEN2 = Len(@MBtypeid2)



CREATE TABLE #Btype 
(
	TypeID		varchar(50),
	arlimit		 NUMERIC(24, 10) ,
	artotal00	 NUMERIC(24, 10) ,
	ystotal00	 NUMERIC(24, 10) ,
	aptotal00	 NUMERIC(24, 10) ,
	yftotal00	 NUMERIC(24, 10) ,
	stypeid		varchar(50)
)

CREATE TABLE #MainType 
(
	TypeID		varchar(50),
	usercode	varchar(200),
	fullname	varchar(200),
	sonnum		int,
	leveal		int,
	arlimit		 NUMERIC(24, 10) ,
	artotal00	 NUMERIC(24, 10) ,
	aptotal00	 NUMERIC(24, 10) ,
	parid		varchar(200)
)


                                                                                                                                                
--往来单位  
IF @Stypeid<>'' or @MStypeid<>'00000'
begin
	INSERT INTO  #Btype(typeid,artotal00,aptotal00,stypeid,ystotal00,yftotal00) 
		select w.typeid,sum(isnull(a.ARTotal00,0)),sum(isnull(a.APTotal00,0)),s.typeid,sum(isnull(a.YSTotal00,0)) ,sum(isnull(a.YFTotal00,0))
		from F_GetAllManagerBaseTypeId(@parid,2,@OperatorID) W 
		inner join BType_ARAPTotal a on a.BTypeID=w.typeid
		inner join #stype s on s.typeid=a.STypeID
		group by w.TypeId,s.typeid
end
else
begin
	INSERT INTO  #Btype(typeid,artotal00,aptotal00,stypeid,ystotal00,yftotal00) 
		select w.typeid,sum(isnull(a.ARTotal00,0)),sum(isnull(a.APTotal00,0)),'',sum(isnull(a.YSTotal00,0)) ,sum(isnull(a.YFTotal00,0)) 
		from F_GetAllManagerBaseTypeId(@parid,2,@OperatorID) W 
		inner join BType_ARAPTotal a on a.BTypeID=w.typeid
		group by w.TypeId
end

SET @sonnum =0
SELECT @sonnum = sonnum FROM Btype WHERE Typeid=@parid



IF @ifLine <>'0' -- 线性表
BEGIN
		IF @parid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,leveal,arlimit,artotal00,aptotal00,parid) 
			SELECT b.typeid,b.usercode,b.fullname,b.sonnum,b.leveal,b.arlimit,b.artotal00,b.aptotal00,b.parid FROM Btype b
			where typeid in (select typeid from F_GetManDetailBtype(@OperatorID))
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,leveal,arlimit,artotal00,aptotal00,parid) 
			SELECT b.typeid,b.usercode,b.fullname,b.sonnum,b.leveal,b.arlimit,b.artotal00,b.aptotal00,b.parid FROM Btype b
			where typeid in (select typeid from F_GetManDetailBtype(@OperatorID) where typeid like @parid+'%')
END
ELSE
BEGIN
	IF @sonnum =0 	
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,leveal,arlimit,artotal00,aptotal00,parid) 
		SELECT b.typeid,b.usercode,b.fullname,b.sonnum,b.leveal,b.arlimit,b.artotal00,b.aptotal00,b.parid FROM Btype b
		,(select * from F_GetManBtypeAll(@OperatorID) where typeid =@parid) a where b.typeid=a.typeid
	ELSE
		IF @parid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,leveal,arlimit,artotal00,aptotal00,parid) 
			SELECT b.typeid,b.usercode,b.fullname,b.sonnum,b.leveal,b.arlimit,b.artotal00,b.aptotal00,b.parid FROM Btype b
			,(select * from F_GetManBtypeAll(@OperatorID) where parid='00000') a where b.typeid=a.typeid
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,leveal,arlimit,artotal00,aptotal00,parid) 
			SELECT b.typeid,b.usercode,b.fullname,b.sonnum,b.leveal,b.arlimit,b.artotal00,b.aptotal00,b.parid FROM Btype b
			,(select * from F_GetManBtypeAll(@OperatorID) where parid=@parid) a where b.typeid=a.typeid
END


--DECLARE @MBparid VARCHAR(50),@MBparid2 VARCHAR(50)
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL VARCHAR(8000)

IF @szperiod='' 
	BEGIN
    	IF @Parid<>'00000'
			BEGIN
				SELECT 	a.usercode,
						a.fullname,
						a.sonnum,
						a.typeid,
						a.parid,
						sum(isnull(b.arlimit,0)) as arlimit,
						sum(isnull(b.aptotal00,0)) as aptotal,
						sum(isnull(b.artotal00,0)) as artotal,
						sum(isnull(b.ystotal00,0)) as ystotal,
						sum(isnull(b.yftotal00,0)) as yftotal
				FROM 	btype a 
				left  join #Btype b on b.TypeID like a.typeId+'%'  and (
							b.aptotal00 <> 0
							or b.artotal00 <> 0
							or b.ystotal00 <> 0
							or b.yftotal00 <> 0
						)
				WHERE 	a.parid=@parid 
				group by	a.usercode,
							a.fullname,
							a.sonnum,
							a.typeid,
							a.parid
				ORDER BY usercode
		END
		IF @parid='00000'
			BEGIN
				SELECT 	a.usercode,
						a.fullname,
						a.sonnum,
						a.typeid,
						a.parid,
						sum(isnull(b.arlimit,0)) as arlimit,
						sum(isnull(b.aptotal00,0)) as aptotal,
						sum(isnull(b.artotal00,0)) as artotal,
						sum(isnull(b.ystotal00,0)) as ystotal,
						sum(isnull(b.yftotal00,0)) as yftotal
				FROM 	btype a 
				left join #Btype b on b.TypeID like a.typeId+'%'  and (
							b.aptotal00 <> 0
							or b.artotal00 <> 0
							or b.ystotal00 <> 0
							or b.yftotal00 <> 0
						)
				WHERE  (a.parid=@MBtypeid OR a.parid=@MBtypeid2) 
						AND (a.typeid LIKE @MBtypeid+'%' OR a.typeid LIKE @MBtypeid2+'%') 
				group by	a.usercode,
							a.fullname,
							a.sonnum,
							a.typeid,
							a.parid
				ORDER BY usercode
			END
	END 
ELSE	--期初
	BEGIN
		IF @parid<>'00000'
			BEGIN				
				SELECT @SQL = '
					SELECT 	a.usercode,
							a.fullname,
							a.sonnum,
							a.typeid,
							a.parid,
							sum(isnull(b.arlimit,0)) as arlimit,
							sum(isnull(b.aptotal00,0)) as aptotal,
							sum(isnull(b.artotal00,0)) as artotal,
							sum(isnull(b.ystotal00,0)) as ystotal,
							sum(isnull(b.yftotal00,0)) as yftotal
					FROM 	#MainType a 
					left join #btype b on b.TypeID like a.typeId+''%'' and (
							b.aptotal00 <> 0
							or b.artotal00 <> 0
							or b.ystotal00 <> 0
							or b.yftotal00 <> 0
						)
					WHERE 	1=1  '
						IF	@UserCode <> '' OR @FullName <> ''
						BEGIN
								SELECT @SQL = @SQL + '
										AND ISNULL(a.UserCode,'''') LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
										AND ISNULL(a.FullName,'''') LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+'
										AND a.SonNum = 0 '
						END
					set @SQL=@SQL+' 
						group by	a.usercode,
									a.fullname,
									a.sonnum,
									a.typeid,
									a.parid
									'

					SELECT @SQL = 'SELECT *,artotal as artotalEnd,aptotal as aptotalEnd ,ystotal as ystotalEnd,yftotal as yftotalEnd FROM ('+ @SQL +') X ORDER BY X.usercode'
					
					--PRINT(@SQL)
					EXEC(@SQL)
			END

			IF @parid='00000'
				BEGIN
					SELECT @SQL = '
						SELECT 	a.usercode,
								a.fullname,
								a.sonnum,
								a.typeid,
								a.parid,
								sum(isnull(b.arlimit,0)) as arlimit,
								sum(isnull(b.aptotal00,0)) as aptotal,
								sum(isnull(b.artotal00,0)) as artotal,
								sum(isnull(b.ystotal00,0)) as ystotal,
								sum(isnull(b.yftotal00,0)) as yftotal
						FROM 	#MainType a 
						left join #btype b on b.TypeID like a.typeId+''%'' and (
							b.aptotal00 <> 0
							or b.artotal00 <> 0
							or b.ystotal00 <> 0
							or b.yftotal00 <> 0
						)
						WHERE 	1=1
						'
						IF	@UserCode <> '' OR @FullName <> ''
						BEGIN
							SELECT @SQL = @SQL + '
									AND ISNULL(a.UserCode,'''') LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
									AND ISNULL(a.FullName,'''') LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+'
									AND a.SonNum = 0  '

						END
				set @SQL=@SQL+' 
						group by	a.usercode,
									a.fullname,
									a.sonnum,
									a.typeid,
									a.parid
									'
						SELECT @SQL ='SELECT *,artotal as artotalEnd,aptotal as aptotalEnd,ystotal as ystotalEnd,yftotal as yftotalEnd FROM ('+ @SQL + ') X ORDER BY X.usercode'
				
					--PRINT(@SQL)
					EXEC(@SQL)
				END
END


TRUNCATE TABLE #Btype;
TRUNCATE TABLE #MainType;
TRUNCATE TABLE #stype;
DROP TABLE #Btype,#MainType,#stype



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_qrWl30625]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[Gp_qrWl30625]
GO

/*
	作者：谢吉康
	日期：2004-11-11
	描述：重写应收、应付查询
          原来的算法有问题
    日期：2010-02-21
    作者：毛欣蓉
    描述：应收应付查询重做
    
    日期:2012-06-07
    作者:黄清
    描述:添加币别条件,调整科目
*/
CREATE  PROCEDURE [dbo].[Gp_qrWl30625]
( 
	@OperatorID 	VARCHAR(100) ,   --操作员id
	@btypeid 		VARCHAR(100),	--往来单位节点号
	@stypeid		VARCHAR(MAX),	--分支机构
	@dtypeid		VARCHAR(MAX),	--部门
	@DtypeIsVisible	INT,			--1=使用部门 0=不使用部门
	@StartDate		VARCHAR(50),
	@ENDDate		VARCHAR(50),
	@IncludePre		VARCHAR(10)='False',
	@option			INT=0,	--选项  0全部显示 1不显示金额为0 2只显示金额为0，3无发生额不显示
	@nType			INT,			--1,3  应收  2,4应付
	@etypeid        VARCHAR(MAX),	--经手人(这个字段为空,没使用,但是以后需求没事了,又会放开的)
	@cid			VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL		VARCHAR(MAX),
		@lstSQL		VARCHAR(1000),
		@SONNum		INT,
		@SqlWHERE	VARCHAR(1000),
		@SqlWHERE1	VARCHAR(1000),
		@preSql1	VARCHAR(1000), --应收增加条件(本币)
		@NpreSql1	VARCHAR(1000), --应收增加条件(原币)
		@preSql2	VARCHAR(1000), --应收减少条件(本币)
		@NpreSql2	VARCHAR(1000), --应收减少条件(原币)
		@AtypeType	VARCHAR(1000), --要查询的科目
		@QcSql		VARCHAR(1000),--期初sql  真正的期初+查询时间段前的数据（多了按部门添加，只能期初+开始前的数据+本期增加-本期减少）
		@aratypeID	VARCHAR(50),
		@ysatypeID	VARCHAR(50),
		@apatypeID	VARCHAR(50),
		@yfatypeID	VARCHAR(50)
		

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

SET @SqlWHERE=''
SET @SqlWHERE1=''

--IF @optiON=1
--BEGIN
--	SET @SqlWHERE=' AND m.qmtotal<>0 '
--	SET @SqlWHERE1=' WHERE a.qmtotal<>0 '
--END
--IF @optiON=2
--BEGIN
--	SET @SqlWHERE=' AND m.qmtotal=0 '
--	SET @SqlWHERE1=' WHERE a.qmtotal=0 '
--END
--IF @optiON=3
--BEGIN
--	SET @SqlWHERE=' AND (m.bqaddtotal<>0 or m.bqrectotal<>0) '
--	SET @SqlWHERE1=' WHERE a.bqaddtotal<>0 or a.bqrectotal<>0 '
--END
SET @preSql1=''
SET @preSql2=''	
SET @NpreSql1=''
SET @NpreSql2=''	

SELECT @SONNum = SONNum FROM BType WHERE TypeId = @btypeid

IF @btypeid='00000'
	BEGIN
		SET @lstSQL = ' b.parid=''00000'''
	END
ELSE
	BEGIN
		IF @SONNum > 0
			SET @lstSQL = ' b.ParId = ''' + @btypeid + ''''
		ELSE
			SET @lstSQL = ' b.TypeId = ''' + @btypeid + ''''		
	END

CREATE TABLE #stype(typeid	VARCHAR(50))
CREATE TABLE #btype1(typeid	VARCHAR(50))
CREATE TABLE #etype(typeid	VARCHAR(50))

DECLARE @sql1 VARCHAR(8000) 
SELECT @sql1=dbo.F_GetAllBaseInfoTypeId(@btypeid,2,@OperatorID,'#btype1')
SELECT @sql1=@sql1+dbo.F_GetAllBaseInfoTypeId(@etypeid,3,'00001','#etype')
SELECT @sql1=@sql1+dbo.F_GetAllBaseInfoTypeId(@stypeid,11,@OperatorID,'#stype')


CREATE TABLE #dtype(typeid	VARCHAR(50))
IF @DtypeIsVisible = 1 AND @dtypeid <> ''
	INSERT #dtype(typeid) SELECT TypeId FROM F_GetAllBaseTypeId(@dtypeid,9)
	
--PRINT @sql1
EXEC(@sql1)


DECLARE @araptotalSql  VARCHAR(MAX)
CREATE TABLE #BtypeIndex(btypeid VARCHAR(50))
IF EXISTS(SELECT 1 FROM #BTYPE1)
	BEGIN
		INSERT INTO #BtypeIndex(btypeid)
		SELECT typeid FROM #btype1
	END
ELSE 
	BEGIN
		INSERT INTO #BtypeIndex
		SELECT TypeID FROM BType WHERE sonnum=0
	END

CREATE TABLE #btype_araptotal
(
	btypeid		VARCHAR(50),
	artotal00	 NUMERIC(24, 10) ,
	aptotal00	 NUMERIC(24, 10) ,
	nartotal00	 NUMERIC(24, 10) ,
	naptotal00	 NUMERIC(24, 10) ,
	ystotal00	 NUMERIC(24, 10) ,
	yftotal00	 NUMERIC(24, 10) ,
	nystotal00	 NUMERIC(24, 10) ,
	nyftotal00	 NUMERIC(24, 10) 
)

SET @araptotalSql ='

	INSERT INTO #btype_araptotal
	
	SELECT	A.BTypeID,
			ISNULL(B.ARTotal00,0), ISNULL(B.APTotal00,0),
			ISNULL(B.nARTotal00,0), ISNULL(B.nAPTotal00,0),
			ISNULL(B.ysTotal00,0), ISNULL(B.yfTotal00,0),
			ISNULL(B.nysTotal00,0), ISNULL(B.nyfTotal00,0)
	FROM #BtypeIndex A
	LEFT JOIN
	(
		SELECT	a.BTypeID,
		SUM(a.ARTotal00)  AS ARTotal00,   SUM(a.APTotal00)AS APTotal00,
		SUM(a.nARTotal00) AS nARTotal00,  SUM(a.nAPTotal00)AS nAPTotal00 ,
		SUM(a.ysTotal00)  AS ysTotal00,   SUM(a.yfTotal00) AS yfTotal00,
	    SUM(a.nysTotal00) AS nysTotal00,  SUM(a.nyfTotal00) AS nyfTotal00
		FROM IniBType_ArApTotal a '
		
		IF EXISTS(SELECT 1 FROM #BTYPE1)
			SET @araptotalSql += ' INNER JOIN #BTYPE1 B1 ON a.BTYPEID=B1.TYPEID'+CHAR(13)

		IF EXISTS(SELECT 1 FROM #STYPE)
			SET @araptotalSql += ' INNER JOIN #STYPE S ON a.STYPEID=S.TYPEID'+CHAR(13)
		
		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @araptotalSql += ' INNER JOIN #DTYPE D ON a.DTYPEID=D.TYPEID'+CHAR(13)

		IF @cid<>0
			SET @araptotalSql += ' WHERE a.cid='+CHAR(39)+@cid+CHAR(39)	
	SET @araptotalSql += ' GROUP BY a.BTypeID  '
	
	SET @araptotalSql += ') B ON B.BTypeID = A.BTypeID '

EXEC (@araptotalSql)
	
CREATE TABLE #BType
(
	TypeId		VARCHAR(100),
	Total00		 NUMERIC(24, 10) ,
	NTotal00	 NUMERIC(24, 10) ,
	BqaddTotal	 NUMERIC(24, 10) ,
	NBqaddTotal	 NUMERIC(24, 10) ,
	BqrecTotal	 NUMERIC(24, 10) ,
	NBqrecTotal	 NUMERIC(24, 10) ,
	Qmtotal		 NUMERIC(24, 10) ,
	NQmtotal	 NUMERIC(24, 10) ,
	ArLimit		 NUMERIC(24, 10) 
)

DECLARE @BtypeSQL VARCHAR(50)
SET @BtypeSQL=' btype '
IF EXISTS(SELECT 1 FROM #BTYPE1)
SET @BtypeSQL= ' #btype1 '

--信用额度
SET @SQL=
'INSERT INTO #BType
(
	TypeId,
	Total00,
	NTotal00,
	BqaddTotal,
	NBqaddTotal,
	BqrecTotal,
	NBqrecTotal,
	Qmtotal,
	NQmtotal,
	ArLimit
)
SELECT	a.TypeId,
		0 AS Total00,
		0 AS NTotal00,
		0 AS BqaddTotal,
		0 AS NBqaddTotal,
		0 AS BqrecTotal,
		0 AS NBqrecTotal,
		0 AS Qmtotal,	
		0 AS NQmtotal,'
--汇率
IF(@cid=0)
	SET @SQL+='SUM(ISNULL(s.credit,0))  AS ArLimit'	
ELSE 
	BEGIN
		DECLARE @BasisType INT=0,@Rate VARCHAR(50)=1
		SELECT @BasisType=BasisType,@Rate=Rate FROM Ac_Currency WHERE CId=@cid
		
		SET @SQL+=CASE WHEN @BasisType=0 THEN 'SUM(ISNULL(s.credit,0))/'+@Rate ELSE 'SUM(ISNULL(s.credit,0))*'+@Rate END +' AS ArLimit'
	END
	
SET @SQL+='		
FROM	'+@BtypeSQL+' a
LEFT JOIN 
	(	SELECT c.credit,c.btypeid
		 FROM btype_credit c '
IF EXISTS(SELECT 1 FROM #stype)
	SET @SQL=@SQL+'	INNER JOIN  #stype s ON c.StypeId=s.typeid  '
SET @SQL=@SQL+'	
	)s ON s.BtypeId=a.typeId 
GROUP BY A.typeId '
EXEC(@sql)

--PRINT(@sql)
--RETURN
IF @nType=1 --应收
BEGIN
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@ysatypeID+CHAR(39)+','+CHAR(39)+@aratypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.Total) '
		SET @NpreSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.NTotal<0  THEN ABS(l.NTotal) '
		SET @preSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total>0 THEN l.Total '
		SET @NpreSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.NTotal>0 THEN l.NTotal '
		
		--期初
		SET @QcSql = ' SUM(ISNULL(a.ARTotal00,0)-ISNULL(a.ystotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
					   SUM(ISNULL(a.nARTotal00,0)-ISNULL(a.nystotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS NTotal00, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)
		
		SET @QcSql = ' SUM(ISNULL(a.ARTotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
					   SUM(ISNULL(a.nARTotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS NTotal00, '
		
	END
	
	----------------应收 计算期初 BEGIN
	SET @SQL='
	INSERT INTO #BType
	(
		TypeId,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	a.BTypeID,
			'+@QcSql+'
			0 AS BqaddTotal,
			0 AS NBqaddTotal,
			0 AS BqrecTotal,
			0 AS NBqrecTotal,
			0 as qmtotal,
			0 as Nqmtotal,
			0 AS arlimit
	FROM #btype_araptotal a '

	SET @SQL=@SQL+'	LEFT JOIN 
				(SELECT	L.BTypeId,
						SUM(CASE WHEN l.billtype IN(45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
								 WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN l.Total '+@preSql1+'
								 ELSE 0 
							END) AS addtotal,
						SUM(CASE WHEN l.billtype IN(45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
								 WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN l.NTotal '+@NpreSql1+'
								 ELSE 0 
							  END) AS Naddtotal,
						SUM(CASE WHEN l.billtype IN(4) AND l.AtypeId='+@aratypeID+'THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
								 WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN ABS(l.Total)'+@preSql2+'
							  ELSE 0 
							  END) AS rectotal,
						SUM(CASE WHEN l.billtype IN(4) AND l.AtypeId='+@aratypeID+'THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
								WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN ABS(l.NTotal)'+@NpreSql2+'
							  ELSE 0 
							  END) AS Nrectotal
				FROM	ListTABLE L 
				'

	IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
		SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
	
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' WHERE	L.BillDate < '''+@StartDate+''' 
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET @SQL=@SQL+'
		GROUP BY L.BTypeId) b ON a.BTypeID=b.BtypeId '
	SET @SQL=@SQL+'	GROUP BY a.btypeid
		'
	EXEC(@sql)
	
	----------------应收 计算期初 END
	
	
	----------------应收 计算本期增加，本期减少 BEGIN
	SET @SQL='	
	INSERT INTO #BType
	(
			TypeId,
			Total00,
			NTotal00,
			BqaddTotal,
			NBqaddTotal,
			BqrecTotal,
			NBqrecTotal,
			Qmtotal,
			NQmtotal,
			ArLimit
	)
	SELECT	L.BTypeId,
			0 AS total00,
			0 AS Ntotal00,
			SUM(CASE  WHEN l.billtype IN(45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					  WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN l.Total'+@preSql1+'
					  ELSE 0
				END) AS bqaddtotal,
			SUM(CASE  WHEN l.billtype IN(45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN l.NTotal '+@NpreSql1+'
					  ELSE 0
					END) AS Nbqaddtotal,
			SUM(CASE WHEN l.billtype IN(4) AND l.AtypeId='+@aratypeID+'THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
					 WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN ABS(l.Total)'+@preSql2+'
				 ELSE 0
				END) AS bqrectotal,
			SUM(CASE WHEN l.billtype IN(4)AND l.AtypeId='+@aratypeID+'THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
					 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN ABS(l.NTotal)'+@NpreSql2+'
				 ELSE 0
				END) AS Nbqrectotal,
			0 AS qmtotal,
			0 AS Nqmtotal,
			0 AS ArLimit	
	FROM	ListTable L'

			
	IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
		SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
	
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)
	
	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@ENDDate+' ''
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET	@SQL=@SQL+'	GROUP BY L.BTypeId '
	
	EXEC(@sql)
	------------------应收 计算本期增加，本期减少 END
END
ELSE
BEGIN 
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)+','+CHAR(39)+@yfatypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.Total) '
		SET @NpreSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.NTotal<0  THEN ABS(l.NTotal) '
		SET @preSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total>0 THEN l.Total '
		SET @NpreSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.NTotal>0 THEN l.NTotal '
		
		SET @QcSql = '
			SUM(ISNULL(a.ApTotal00,0)-ISNULL(a.yftotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00,
			SUM(ISNULL(a.NApTotal00,0)-ISNULL(a.Nyftotal00,0) + ISNULL(b.Naddtotal,0) - ISNULL(b.Nrectotal,0)) AS NTotal00, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)
		
		SET @QcSql = '
			SUM(ISNULL(a.ApTotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
			SUM(ISNULL(a.NApTotal00,0) + ISNULL(b.Naddtotal,0) - ISNULL(b.Nrectotal,0)) AS NTotal00,'
	END
	
	------------------应付 计算期初 BEGIN
	SET @SQL='
	INSERT INTO #BType
	(
		TypeId,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	a.BTypeID,
			'+@QcSql+'
			0 AS BqaddTotal,
			0 AS NBqaddTotal,
			0 AS BqrecTotal,
			0 AS NBqrecTotal,
			0 as qmtotal,
			0 as Nqmtotal,
			0 AS arlimit
	FROM  #btype_araptotal a '
		
	SET @SQL=@SQL+' 
	LEFT JOIN 
	(SELECT	L.BTypeId,
			SUM(CASE WHEN l.billtype IN(6,34,161,404,423) AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(6,34,161,404,423,66) THEN l.Total'+@preSql1+'
					 ELSE 0 END) AS addtotal,
			SUM(CASE WHEN l.billtype IN(6,34,161,404,423) AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(6,34,161,404,423,66) THEN l.NTotal'+@NpreSql1+'
					 ELSE 0 END) AS Naddtotal,
			SUM(CASE WHEN l.billtype IN(66) AND l.AtypeId='+@apatypeID+'THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,404,423,66) THEN ABS(l.Total)'+@preSql2+'
					 ELSE 0 END) AS rectotal,
			SUM(CASE WHEN l.billtype IN(66) AND l.AtypeId='+@apatypeID+'THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,404,423,66) THEN ABS(l.NTotal)'+@NpreSql2+'
					 ELSE 0 END) AS Nrectotal
	FROM	ListTABLE L '
	IF EXISTS(SELECT 1 FROM #BTYPE1)
	SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
	SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
	
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' WHERE	L.BillDate < '''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET @SQL=@SQL+'
		GROUP BY L.BTypeId) b ON a.BTypeID=b.BtypeId  '
	SET @SQL=@SQL+'
		GROUP BY a.btypeid'
	EXEC(@sql)
	------------------应付 计算期初 END
	
	
	------------------应付 计算本期增加，本期减少 BEGIN
	SET @SQL='
	INSERT INTO #BType
	(
			TypeId,
			Total00,
			NTotal00,
			BqaddTotal,
			NBqaddTotal,
			BqrecTotal,
			NBqrecTotal,
			Qmtotal,
			NQmtotal,
			ArLimit
	)
	SELECT	DISTINCT
			L.BTypeId,
			0 AS total00,
			0 AS Ntotal00,
			SUM(CASE  WHEN l.billtype IN(6,34,161,404,423) AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(6,34,161,404,423,66) THEN l.Total'+@preSql1+'
				  ELSE 0
			END) AS bqaddtotal,
			SUM(CASE  WHEN l.billtype IN(6,34,161,404,423)  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(6,34,161,404,423,66) THEN l.NTotal'+@NpreSql1+'
				  ELSE 0
			END) AS Nbqaddtotal,
			SUM(CASE WHEN l.billtype IN(66) AND l.AtypeId='+@apatypeID+'THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,404,423,66) THEN ABS(l.Total)'+@preSql2+'
					 ELSE 0
					END) AS bqrectotal,
			SUM(CASE WHEN l.billtype IN(66) AND l.AtypeId='+@apatypeID+'THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,404,423,66) THEN ABS(l.NTotal)'+@npreSql2+'
				 ELSE 0
			END) AS Nbqrectotal,
			0 AS qmtotal,
			0 AS Nqmtotal,
			0 AS ArLimit	
	FROM	ListTABLE L'
	IF EXISTS(SELECT 1 FROM #BTYPE1)
	SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
	SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
	SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)

	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@ENDDate+''' 
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET	@SQL=@SQL+'	GROUP BY L.BTypeId '
	EXEC(@sql)
	------------------应付 计算本期增加，本期减少 END
	

--PRINT(@sql)
END
CREATE CLUSTERED INDEX CIX_BTYPEID ON #BTYPE(TypeId)

 create TABLE #Allbtype
 (
	typeid VARCHAR(50),
	sonnum  INT,
	UserCode VARCHAR(200),
	Parid  VARCHAR(50)
 )
 SET @sql='
			INSERT INTO #Allbtype
					( typeid, sonnum, UserCode, Parid )
			SELECT typeid, sonnum, UserCode, Parid
			FROM	F_GetManBTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') B   WHERE '+@lstSQL
			
EXEC(@sql)
------------------------------------------------------------------------------------------------------------------------------------
DECLARE @Len int
if @btypeid='00000'
	SET @Len=5
ELSE 
	SET @Len=LEN(@btypeid)+5
IF @option='1'
BEGIN 
	 DELETE n 
	 FROM #BType n 
	 INNER JOIN  (
	 SELECT typeid ,
	 SUM(ISNULL(Total00,0)) AS Total00,
	SUM(ISNULL(NTotal00,0)) AS NTotal00,
	SUM(ISNULL(BqaddTotal,0)) AS bqaddtotal,
	SUM(ISNULL(NBqaddTotal,0)) AS Nbqaddtotal,
	SUM(ISNULL(BqrecTotal,0)) AS bqrectotal,
	SUM(ISNULL(NBqrecTotal,0)) AS Nbqrectotal
	 FROM #BType
	 GROUP BY typeid  
	 )m ON m.TypeId=n.TypeId
	 WHERE m.Total00+m.bqaddtotal-m.bqrectotal=0

END 

IF @option='2'
BEGIN 
	 DELETE n 
	 FROM #BType n 
	 INNER JOIN  (
	 SELECT typeid ,
	 SUM(ISNULL(Total00,0)) AS Total00,
	SUM(ISNULL(NTotal00,0)) AS NTotal00,
	SUM(ISNULL(BqaddTotal,0)) AS bqaddtotal,
	SUM(ISNULL(NBqaddTotal,0)) AS Nbqaddtotal,
	SUM(ISNULL(BqrecTotal,0)) AS bqrectotal,
	SUM(ISNULL(NBqrecTotal,0)) AS Nbqrectotal
	 FROM #BType
	 GROUP BY typeid  
	 )m ON m.TypeId=n.TypeId
	 WHERE m.Total00+m.bqaddtotal-m.bqrectotal<>0

END 

IF @option='3'
BEGIN 
	 DELETE n 
	 FROM #BType n 
	 INNER JOIN  (
	 SELECT typeid ,
	 SUM(ISNULL(Total00,0)) AS Total00,
	SUM(ISNULL(NTotal00,0)) AS NTotal00,
	SUM(ISNULL(BqaddTotal,0)) AS bqaddtotal,
	SUM(ISNULL(NBqaddTotal,0)) AS Nbqaddtotal,
	SUM(ISNULL(BqrecTotal,0)) AS bqrectotal,
	SUM(ISNULL(NBqrecTotal,0)) AS Nbqrectotal
	 FROM #BType
	 GROUP BY typeid  
	 )m ON m.TypeId=n.TypeId
	 WHERE m.bqaddtotal=0 AND m.bqrectotal=0

END 

SET @SQL='
SELECT	B.TypeId,
		B.SONNum,
		B.UserCode,
		SUM(ISNULL(M.Total00,0)) AS Total00,
		SUM(ISNULL(M.NTotal00,0)) AS NTotal00,
		SUM(ISNULL(m.BqaddTotal,0)) AS bqaddtotal,
		SUM(ISNULL(m.NBqaddTotal,0)) AS Nbqaddtotal,
		SUM(ISNULL(m.BqrecTotal,0)) AS bqrectotal,
		SUM(ISNULL(m.NBqrecTotal,0)) AS Nbqrectotal,
		SUM(ISNULL(M.ArLimit,0)) AS ArLimit,
		CASE WHEN SUM(ISNULL(M.arlimit,0))=0 OR SUM(ISNULL(M.Total00,0) + ISNULL(M.bqaddtotal,0) - ISNULL(M.bqrectotal,0)-ISNULL(M.arlimit,0))<=0
		     THEN NULL 
		     ELSE SUM(ISNULL(M.Total00,0) + ISNULL(M.bqaddtotal,0) - ISNULL(M.bqrectotal,0)-ISNULL(M.arlimit,0)) 
			 END AS limitartotal,
		--SUM(ISNULL(M.Total00,0) + ISNULL(M.bqaddtotal,0) - ISNULL(M.bqrectotal,0)) AS qmtotal,
		--SUM(ISNULL(M.NTotal00,0) + ISNULL(M.nbqaddtotal,0) - ISNULL(M.nbqrectotal,0)) AS nqmtotal 
		ISNULL(SUM(M.qmtotal),0) AS qmtotal,
		ISNULL(SUM(M.nqmtotal),0) AS nqmtotal'
SET @SQL += '								
FROM	#Allbtype B
inner JOIN (
	SELECT	substring(typeid,1,'+cast(@Len as varchar)+') as typeid,
			SUM(ISNULL(Total00,0)) AS Total00,
			SUM(ISNULL(NTotal00,0)) AS NTotal00,
			SUM(ISNULL(BqaddTotal,0)) AS bqaddtotal,
			SUM(ISNULL(NBqaddTotal,0)) AS Nbqaddtotal,
			SUM(ISNULL(BqrecTotal,0)) AS bqrectotal,
			SUM(ISNULL(NBqrecTotal,0)) AS Nbqrectotal,
			SUM(ISNULL(ArLimit,0)) AS ArLimit,
			SUM(ISNULL(Total00,0) + ISNULL(bqaddtotal,0) - ISNULL(bqrectotal,0)) AS qmtotal,
			SUM(ISNULL(NTotal00,0) + ISNULL(nbqaddtotal,0) - ISNULL(nbqrectotal,0)) AS nqmtotal
	FROM 	#BType
	GROUP BY substring(typeid,1,'+cast(@Len as varchar)+')
)M   ON M.TypeID=B.TypeID  '
		
SET @SQL=@SQL+'
WHERE 	'+@lstSQL+@SqlWHERE+' 
GROUP BY	B.TypeId,
			B.SONNum,
			B.UserCode
			 '

IF @optiON<>1
	SET @SQL='SELECT * FROM ('+@SQL+') AS a '+@SqlWHERE1+' ORDER BY usercode'
ELSE
	SET @SQL=@SQL+' ORDER BY B.UserCode'

--print(@SQL)
EXEC(@SQL)

DROP TABLE #BType,#stype,#btype1,#etype,#btype_araptotal,#dtype,#BtypeIndex	,#Allbtype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_qrWl30625WithSMS]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[Gp_qrWl30625WithSMS]
GO

/*
	作者：吕文祺
	日期：2017-06-29
	
   
*/
CREATE  PROCEDURE [dbo].[Gp_qrWl30625WithSMS]
( 
	@OperatorID 	VARCHAR(100) ,   --操作员id
	@btypeid 		VARCHAR(100),	--往来单位节点号
	@stypeid		VARCHAR(MAX),	--分支机构
	@dtypeid		VARCHAR(MAX),	--部门
	@DtypeIsVisible	INT,			--1=使用部门 0=不使用部门
	@StartDate		VARCHAR(50),
	@ENDDate		VARCHAR(50),
	@IncludePre		VARCHAR(10)='False',
	@option			INT=0,	--选项  0全部显示 1不显示金额为0 2只显示金额为0，3无发生额不显示
	@nType			INT,			--1,3  应收  2,4应付
	@etypeid        VARCHAR(MAX),	--经手人(这个字段为空,没使用,但是以后需求没事了,又会放开的)
	@cid			VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL		VARCHAR(MAX),
		@lstSQL		VARCHAR(1000),
		@SONNum		INT,
		@SqlWHERE	VARCHAR(1000),
		@SqlWHERE1	VARCHAR(1000),
		@preSql1	VARCHAR(1000), --应收增加条件(本币)
		@NpreSql1	VARCHAR(1000), --应收增加条件(原币)
		@preSql2	VARCHAR(1000), --应收减少条件(本币)
		@NpreSql2	VARCHAR(1000), --应收减少条件(原币)
		@AtypeType	VARCHAR(1000), --要查询的科目
		@QcSql		VARCHAR(1000),--期初sql  真正的期初+查询时间段前的数据（多了按部门添加，只能期初+开始前的数据+本期增加-本期减少）
		@aratypeID	VARCHAR(50),
		@ysatypeID	VARCHAR(50),
		@apatypeID	VARCHAR(50),
		@yfatypeID	VARCHAR(50)
		

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

SET @SqlWHERE=''
SET @SqlWHERE1=''

IF @optiON=1
BEGIN
	SET @SqlWHERE=' AND m.qmtotal<>0 '
	SET @SqlWHERE1=' WHERE a.qmtotal<>0 '
END
IF @optiON=2
BEGIN
	SET @SqlWHERE=' AND m.qmtotal=0 '
	SET @SqlWHERE1=' WHERE a.qmtotal=0 '
END
IF @optiON=3
BEGIN
	SET @SqlWHERE=' AND (m.bqaddtotal<>0 or m.bqrectotal<>0) '
	SET @SqlWHERE1=' WHERE a.bqaddtotal<>0 or a.bqrectotal<>0 '
END
SET @preSql1=''
SET @preSql2=''	
SET @NpreSql1=''
SET @NpreSql2=''	

SELECT @SONNum = SONNum FROM BType WHERE TypeId = @btypeid

IF @btypeid='00000'
	BEGIN
		SET @lstSQL = ' b.parid=''00000'''
	END
ELSE
	BEGIN
		IF @SONNum > 0
			SET @lstSQL = ' b.SonNum=0 and b.ParId Like ''' + @btypeid + '%'''
		ELSE
			SET @lstSQL = ' b.TypeId = ''' + @btypeid + ''''		
	END

CREATE TABLE #stype(typeid	VARCHAR(50))
CREATE TABLE #btype1(typeid	VARCHAR(50))
CREATE TABLE #etype(typeid	VARCHAR(50))

DECLARE @sql1 VARCHAR(8000) 
SELECT @sql1=dbo.F_GetAllBaseInfoTypeId(@btypeid,2,@OperatorID,'#btype1')
SELECT @sql1=@sql1+dbo.F_GetAllBaseInfoTypeId(@etypeid,3,'00001','#etype')
SELECT @sql1=@sql1+dbo.F_GetAllBaseInfoTypeId(@stypeid,11,@OperatorID,'#stype')


CREATE TABLE #dtype(typeid	VARCHAR(50))
IF @DtypeIsVisible = 1 AND @dtypeid <> ''
	INSERT #dtype(typeid) SELECT TypeId FROM F_GetAllBaseTypeId(@dtypeid,9)
	
--PRINT @sql1
EXEC(@sql1)


DECLARE @araptotalSql  VARCHAR(MAX)
CREATE TABLE #BtypeIndex(btypeid VARCHAR(50))

SET @araptotalSql = '
	INSERT INTO #BtypeIndex
	SELECT DISTINCT a.BTypeID
	FROM BType_ArApTotal a '
	
IF EXISTS(SELECT 1 FROM #BTYPE1)
	SET @araptotalSql += ' INNER JOIN #BTYPE1 B1 ON a.BTYPEID=B1.TYPEID'+CHAR(13)

IF EXISTS(SELECT 1 FROM #STYPE)
	SET @araptotalSql += ' INNER JOIN #STYPE S ON a.STYPEID=S.TYPEID'+CHAR(13)
	
IF @cid<>0
	SET @araptotalSql += ' WHERE a.cid='+CHAR(39)+@cid+CHAR(39)	

EXEC (@araptotalSql)	

CREATE TABLE #btype_araptotal
(
	btypeid		VARCHAR(50),
	artotal00	 NUMERIC(24, 10) ,
	aptotal00	 NUMERIC(24, 10) ,
	nartotal00	 NUMERIC(24, 10) ,
	naptotal00	 NUMERIC(24, 10) ,
	ystotal00	 NUMERIC(24, 10) ,
	yftotal00	 NUMERIC(24, 10) ,
	nystotal00	 NUMERIC(24, 10) ,
	nyftotal00	 NUMERIC(24, 10) 
)

SET @araptotalSql ='

	INSERT INTO #btype_araptotal
	
	SELECT	A.BTypeID,
			ISNULL(B.ARTotal00,0), ISNULL(B.APTotal00,0),
			ISNULL(B.nARTotal00,0), ISNULL(B.nAPTotal00,0),
			ISNULL(B.ysTotal00,0), ISNULL(B.yfTotal00,0),
			ISNULL(B.nysTotal00,0), ISNULL(B.nyfTotal00,0)
	FROM #BtypeIndex A
	LEFT JOIN
	(
		SELECT	a.BTypeID,
		SUM(a.ARTotal00)  AS ARTotal00,   SUM(a.APTotal00)AS APTotal00,
		SUM(a.nARTotal00) AS nARTotal00,  SUM(a.nAPTotal00)AS nAPTotal00 ,
		SUM(a.ysTotal00)  AS ysTotal00,   SUM(a.yfTotal00) AS yfTotal00,
	    SUM(a.nysTotal00) AS nysTotal00,  SUM(a.nyfTotal00) AS nyfTotal00
		FROM IniBType_ArApTotal a '
		
		IF EXISTS(SELECT 1 FROM #BTYPE1)
			SET @araptotalSql += ' INNER JOIN #BTYPE1 B1 ON a.BTYPEID=B1.TYPEID'+CHAR(13)

		IF EXISTS(SELECT 1 FROM #STYPE)
			SET @araptotalSql += ' INNER JOIN #STYPE S ON a.STYPEID=S.TYPEID'+CHAR(13)
		
		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @araptotalSql += ' INNER JOIN #DTYPE D ON a.DTYPEID=D.TYPEID'+CHAR(13)

		IF @cid<>0
			SET @araptotalSql += ' WHERE a.cid='+CHAR(39)+@cid+CHAR(39)	
	SET @araptotalSql += ' GROUP BY a.BTypeID  '
	
	SET @araptotalSql += ') B ON B.BTypeID = A.BTypeID '

EXEC (@araptotalSql)
	
CREATE TABLE #BType
(
	TypeId		VARCHAR(100),
	Total00		 NUMERIC(24, 10) ,
	NTotal00	 NUMERIC(24, 10) ,
	BqaddTotal	 NUMERIC(24, 10) ,
	NBqaddTotal	 NUMERIC(24, 10) ,
	BqrecTotal	 NUMERIC(24, 10) ,
	NBqrecTotal	 NUMERIC(24, 10) ,
	Qmtotal		 NUMERIC(24, 10) ,
	NQmtotal	 NUMERIC(24, 10) ,
	ArLimit		 NUMERIC(24, 10) 
)

DECLARE @BtypeSQL VARCHAR(50)
SET @BtypeSQL=' btype '
IF EXISTS(SELECT 1 FROM #BTYPE1)
SET @BtypeSQL= ' #btype1 '

--信用额度
SET @SQL=
'INSERT INTO #BType
(
	TypeId,
	Total00,
	NTotal00,
	BqaddTotal,
	NBqaddTotal,
	BqrecTotal,
	NBqrecTotal,
	Qmtotal,
	NQmtotal,
	ArLimit
)
SELECT	a.TypeId,
		0 AS Total00,
		0 AS NTotal00,
		0 AS BqaddTotal,
		0 AS NBqaddTotal,
		0 AS BqrecTotal,
		0 AS NBqrecTotal,
		0 AS Qmtotal,	
		0 AS NQmtotal,		
		SUM(ISNULL(s.credit,0)) AS ArLimit
FROM	'+@BtypeSQL+' a
LEFT JOIN 
	(	SELECT c.credit,c.btypeid
		 FROM btype_credit c '
IF EXISTS(SELECT 1 FROM #stype)
	SET @SQL=@SQL+'	INNER JOIN  #stype s ON c.StypeId=s.typeid  '
SET @SQL=@SQL+'	
	)s ON s.BtypeId=a.typeId 
GROUP BY A.typeId '
EXEC(@sql)

--PRINT(@sql)
--RETURN
IF @nType=1 --应收
BEGIN
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@ysatypeID+CHAR(39)+','+CHAR(39)+@aratypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.Total) '
		SET @NpreSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.NTotal<0  THEN ABS(l.NTotal) '
		SET @preSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total>0 THEN l.Total '
		SET @NpreSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.NTotal>0 THEN l.NTotal '
		--期初
		SET @QcSql = ' SUM(ISNULL(a.ARTotal00,0)-ISNULL(a.ystotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
					   SUM(ISNULL(a.nARTotal00,0)-ISNULL(a.nystotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS NTotal00, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)
		
		SET @QcSql = ' SUM(ISNULL(a.ARTotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
					   SUM(ISNULL(a.nARTotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS NTotal00, '
		
	END
	
	----------------应收 计算期初 BEGIN
	SET @SQL='
	INSERT INTO #BType
	(
		TypeId,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	a.BTypeID,
			'+@QcSql+'
			0 AS BqaddTotal,
			0 AS NBqaddTotal,
			0 AS BqrecTotal,
			0 AS NBqrecTotal,
			0 as qmtotal,
			0 as Nqmtotal,
			0 AS arlimit
	FROM #btype_araptotal a '

	SET @SQL=@SQL+'	LEFT JOIN 
				(SELECT	L.BTypeId,
						SUM(CASE  WHEN l.billtype=45 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
							  WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
							  WHEN l.BillType=11  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
							  WHEN l.BillType=405  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
							  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
							  WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405) THEN l.Total '+@preSql1+'
							  ELSE 0 
							  END) AS addtotal,
						SUM(CASE  WHEN l.billtype=45 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
								WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
							  WHEN l.BillType=11  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
							    WHEN l.BillType=405  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
							  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
							  WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405) THEN l.NTotal '+@NpreSql1+'
							  ELSE 0 
							  END) AS Naddtotal,
						SUM(CASE  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405) THEN ABS(l.Total)'+@preSql2+'
							  ELSE 0 
							  END) AS rectotal,
						SUM(CASE  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(45,215,11,160,405) THEN ABS(l.NTotal)'+@NpreSql2+'
							  ELSE 0 
							  END) AS Nrectotal
				FROM	ListTABLE L 
				'

	IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
		SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
	
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' WHERE	L.BillDate < '''+@StartDate+''' 
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET @SQL=@SQL+'
		GROUP BY L.BTypeId) b ON a.BTypeID=b.BtypeId '
	SET @SQL=@SQL+'	GROUP BY a.btypeid
		'
	EXEC(@sql)
	
	----------------应收 计算期初 END
	
	
	----------------应收 计算本期增加，本期减少 BEGIN
	SET @SQL='	
	INSERT INTO #BType
	(
			TypeId,
			Total00,
			NTotal00,
			BqaddTotal,
			NBqaddTotal,
			BqrecTotal,
			NBqrecTotal,
			Qmtotal,
			NQmtotal,
			ArLimit
	)
	SELECT	L.BTypeId,
			0 AS total00,
			0 AS Ntotal00,
			SUM(CASE  WHEN l.billtype=45 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
						WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					  WHEN l.BillType=11  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					   WHEN l.BillType=405  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405) THEN l.Total'+@preSql1+'
					  ELSE 0
				END) AS bqaddtotal,
			SUM(CASE  WHEN l.billtype=45 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					  WHEN l.BillType=11  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					   WHEN l.BillType=405  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(45,215,11,160,405) THEN l.NTotal'+@NpreSql1+'
					  ELSE 0
					END) AS Nbqaddtotal,
			SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405) THEN ABS(l.Total)'+@preSql2+'
				 ELSE 0
				END) AS bqrectotal,
			SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(45,215,11,160,405) THEN ABS(l.NTotal)'+@NpreSql2+'
				 ELSE 0
				END) AS Nbqrectotal,
			0 AS qmtotal,
			0 AS Nqmtotal,
			0 AS ArLimit	
	FROM	ListTable L'

			
	IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
		SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
	
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)
	
	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@ENDDate+' ''
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET	@SQL=@SQL+'	GROUP BY L.BTypeId '
	
	EXEC(@sql)
	------------------应收 计算本期增加，本期减少 END
END
ELSE
BEGIN 
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)+','+CHAR(39)+@yfatypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.Total) '
		SET @NpreSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.NTotal<0  THEN ABS(l.NTotal) '
		SET @preSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total>0 THEN l.Total '
		SET @NpreSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.NTotal>0 THEN l.NTotal '
		
		SET @QcSql = '
			SUM(ISNULL(a.ApTotal00,0)-ISNULL(a.yftotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00,
			SUM(ISNULL(a.NApTotal00,0)-ISNULL(a.Nyftotal00,0) + ISNULL(b.Naddtotal,0) - ISNULL(b.Nrectotal,0)) AS NTotal00, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)
		
		SET @QcSql = '
			SUM(ISNULL(a.ApTotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
			SUM(ISNULL(a.NApTotal00,0) + ISNULL(b.Naddtotal,0) - ISNULL(b.Nrectotal,0)) AS NTotal00,'
	END
	
	------------------应付 计算期初 BEGIN
	SET @SQL='
	INSERT INTO #BType
	(
		TypeId,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	a.BTypeID,
			'+@QcSql+'
			0 AS BqaddTotal,
			0 AS NBqaddTotal,
			0 AS BqrecTotal,
			0 AS NBqrecTotal,
			0 as qmtotal,
			0 as Nqmtotal,
			0 AS arlimit
	FROM  #btype_araptotal a '
		
	SET @SQL=@SQL+' 
	LEFT JOIN 
	(SELECT	L.BTypeId,
			SUM(CASE  WHEN l.billtype=6 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN l.BillType=34  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				   WHEN l.BillType=404  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN l.billtype=161 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(6,34,161,404) THEN l.Total'+@preSql1+'
				  ELSE 0 END) AS addtotal,
			SUM(CASE  WHEN l.billtype=6 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN l.BillType=34  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN l.BillType=404  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN l.billtype=161 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(6,34,161,404) THEN l.NTotal'+@NpreSql1+'
				  ELSE 0 END) AS Naddtotal,
			SUM(CASE 
				 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,404) THEN ABS(l.Total)'+@preSql2+'
				 ELSE 0 END) AS rectotal,
			SUM(CASE 
				 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,404) THEN ABS(l.NTotal)'+@NpreSql2+'
				 ELSE 0 END) AS Nrectotal
	FROM	ListTABLE L '
	IF EXISTS(SELECT 1 FROM #BTYPE1)
	SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
	SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
	
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' WHERE	L.BillDate < '''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET @SQL=@SQL+'
		GROUP BY L.BTypeId) b ON a.BTypeID=b.BtypeId  '
	SET @SQL=@SQL+'
		GROUP BY a.btypeid'
	EXEC(@sql)
	------------------应付 计算期初 END
	
	
	------------------应付 计算本期增加，本期减少 BEGIN
	SET @SQL='
	INSERT INTO #BType
	(
			TypeId,
			Total00,
			NTotal00,
			BqaddTotal,
			NBqaddTotal,
			BqrecTotal,
			NBqrecTotal,
			Qmtotal,
			NQmtotal,
			ArLimit
	)
	SELECT	DISTINCT
			L.BTypeId,
			0 AS total00,
			0 AS Ntotal00,
			SUM(CASE  WHEN l.billtype=6 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN l.BillType=34  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				    WHEN l.BillType=404  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN l.billtype=161  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(6,34,161,404) THEN l.Total'+@preSql1+'
				  ELSE 0
			END) AS bqaddtotal,
			SUM(CASE  WHEN l.billtype=6 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN l.BillType=34  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				   WHEN l.BillType=404  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN l.billtype=161  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(6,34,161,404) THEN l.NTotal'+@npreSql1+'
				  ELSE 0
			END) AS Nbqaddtotal,
			SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,404) THEN ABS(l.Total)'+@preSql2+'
				 ELSE 0
			END) AS bqrectotal,
			SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,404) THEN ABS(l.NTotal)'+@npreSql2+'
				 ELSE 0
			END) AS Nbqrectotal,
			0 AS qmtotal,
			0 AS Nqmtotal,
			0 AS ArLimit	
	FROM	ListTABLE L'
	IF EXISTS(SELECT 1 FROM #BTYPE1)
	SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
	SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
	SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)

	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@ENDDate+''' 
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET	@SQL=@SQL+'	GROUP BY L.BTypeId '
	EXEC(@sql)
	------------------应付 计算本期增加，本期减少 END
	

--PRINT(@sql)
END
CREATE CLUSTERED INDEX CIX_BTYPEID ON #BTYPE(TypeId)

 create TABLE #Allbtype
 (
	typeid VARCHAR(50),
	sonnum  INT,
	UserCode VARCHAR(200),
	Parid  VARCHAR(50)
 )
 SET @sql='
			INSERT INTO #Allbtype
					( typeid, sonnum, UserCode, Parid )
			SELECT typeid, sonnum, UserCode, Parid
			FROM	F_GetManBTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') B   WHERE '+@lstSQL
			
EXEC(@sql)
------------------------------------------------------------------------------------------------------------------------------------
DECLARE @Len int
if @btypeid='00000'
	SET @Len=5
ELSE 
	SET @Len=LEN(@btypeid)+5


SET @SQL='
SELECT	B.TypeId,
		B.SONNum,
		B.UserCode,
		SUM(ISNULL(M.Total00,0)) AS Total00,
		SUM(ISNULL(M.NTotal00,0)) AS NTotal00,
		SUM(ISNULL(m.BqaddTotal,0)) AS bqaddtotal,
		SUM(ISNULL(m.NBqaddTotal,0)) AS Nbqaddtotal,
		SUM(ISNULL(m.BqrecTotal,0)) AS bqrectotal,
		SUM(ISNULL(m.NBqrecTotal,0)) AS Nbqrectotal,
		SUM(ISNULL(M.ArLimit,0)) AS ArLimit,
		CASE WHEN SUM(ISNULL(M.arlimit,0))=0 OR SUM(ISNULL(M.Total00,0) + ISNULL(M.bqaddtotal,0) - ISNULL(M.bqrectotal,0)-ISNULL(M.arlimit,0))<=0
		     THEN NULL 
		     ELSE SUM(ISNULL(M.Total00,0) + ISNULL(M.bqaddtotal,0) - ISNULL(M.bqrectotal,0)-ISNULL(M.arlimit,0)) 
			 END AS limitartotal,
		--SUM(ISNULL(M.Total00,0) + ISNULL(M.bqaddtotal,0) - ISNULL(M.bqrectotal,0)) AS qmtotal,
		--SUM(ISNULL(M.NTotal00,0) + ISNULL(M.nbqaddtotal,0) - ISNULL(M.nbqrectotal,0)) AS nqmtotal 
		ISNULL(SUM(M.qmtotal),0) AS qmtotal,
		ISNULL(SUM(M.nqmtotal),0) AS nqmtotal'
SET @SQL += '								
FROM	#Allbtype B
LEFT JOIN (
	SELECT	substring(typeid,1,'+cast(@Len as varchar)+') as typeid,
			SUM(ISNULL(Total00,0)) AS Total00,
			SUM(ISNULL(NTotal00,0)) AS NTotal00,
			SUM(ISNULL(BqaddTotal,0)) AS bqaddtotal,
			SUM(ISNULL(NBqaddTotal,0)) AS Nbqaddtotal,
			SUM(ISNULL(BqrecTotal,0)) AS bqrectotal,
			SUM(ISNULL(NBqrecTotal,0)) AS Nbqrectotal,
			SUM(ISNULL(ArLimit,0)) AS ArLimit,
			SUM(ISNULL(Total00,0) + ISNULL(bqaddtotal,0) - ISNULL(bqrectotal,0)) AS qmtotal,
			SUM(ISNULL(NTotal00,0) + ISNULL(nbqaddtotal,0) - ISNULL(nbqrectotal,0)) AS nqmtotal
	FROM 	#BType
	GROUP BY substring(typeid,1,'+cast(@Len as varchar)+')
)M   ON M.TypeID=B.TypeID  '
		
SET @SQL=@SQL+'
WHERE 	'+@lstSQL+@SqlWHERE+' 
GROUP BY	B.TypeId,
			B.SONNum,
			B.UserCode
			 '

IF @optiON<>1
	SET @SQL='SELECT * FROM ('+@SQL+') AS a '+@SqlWHERE1+' ORDER BY usercode'
ELSE
	SET @SQL=@SQL+' ORDER BY B.UserCode'

--print(@SQL)
EXEC(@SQL)

DROP TABLE #BType,#stype,#btype1,#etype,#btype_araptotal,#dtype,#BtypeIndex	,#Allbtype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO 
	--
	--				成本计算获取需要计算的子类商品ID
	--
	IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_Query_CostCompute_ChildPType',N'P'))
	BEGIN
		DROP PROC GP_Query_CostCompute_ChildPType
	END
GO
	CREATE PROC GP_Query_CostCompute_ChildPType	
	(
		@PTypeID	VARCHAR(100),
		@STypeID	VARCHAR(100),
		@startData	VARCHAR(50)		--计算开始日期
	)
	AS
	BEGIN
		SET @PTypeID=ISNULL(@PTypeID,'')
		SELECT TypeID AS PTypeID FROM PType WHERE typeId LIKE @PTypeID+'%' AND sonnum=0 AND iscombinationproduct=0 AND IsService=0
	 --   CREATE TABLE #ModifyPTypeInfo ( PTypeID VARCHAR(50) )
	 --   CREATE TABLE #RedWordPTypeInfo ( PTypeID VARCHAR(50) )
		
	 --   DECLARE @strInsertPTypeInfo VARCHAR(MAX) ,
		--		@datMonthProc DATETIME
		--	--月结时间
		--IF @startData=''
		--BEGIN
		--	SELECT  @datMonthProc = StartDate
		--	FROM    MonthProc
		--	WHERE   MonthNo = '本期' AND STypeID=@STypeID
	 --   END
	 --   ELSE
		--	SET @datMonthProc=CAST(@startData AS DATETIME)
		----这里还需要参考那2个不参与成本计算的配置,来过滤单据类型
		----关联的红冲商品信息（这里还需要考虑过滤掉@strPTypeID,@strSTypeID）
		----PRINT(@datPostTime)
		
		--SET @PTypeID=ISNULL(@PTypeID,'')
		--SET @STypeID=ISNULL(@STypeID,'')
	 --   IF EXISTS ( 
		--			SELECT BillNumberId
		--			FROM   InOutstocktable
		--			WHERE  BillType IN ( 34, 11, 45, 6, 160, 161, 9, 14,
		--							  57, 17, 21, 187, 188, 201, 202,
		--							  16, 139, 126, 305, 400, 401, 402,
		--							  403, 404, 144, 140, 142, 146,183,174,168,172,173 )
		--				AND Audited = 0  --红冲单据
		--				AND PostTime >= @datMonthProc
		--				AND STypeID = @STypeID
		--				AND PtypeId LIKE + @PTypeID + '%'

		--				AND IsService = 0 
		--			UNION 
		--			SELECT a.BillNumberID
		--			FROM ReceiptBill a
		--			INNER JOIN ReceiptBillIndex b
		--			ON a.BillNumberID=b.BillNumberID
		--			WHERE a.BillType=404 AND b.RedWord=1
		--			AND b.PostTime >= @datMonthProc
		--			AND b.STypeID = @STypeID
		--			AND a.PtypeId LIKE + @PTypeID + '%'

	 --                           )
	 --   BEGIN
	 --       INSERT  #RedWordPTypeInfo
	 --               ( PTypeID
	 --               )
	 --               SELECT DISTINCT
	 --                       PtypeId
	 --               FROM    InOutstocktable
	 --               WHERE   BillType IN ( 34, 11, 45, 6, 160, 161, 9, 14,
	 --                                     57, 17, 21, 187, 188, 201, 202,
	 --                                     16, 139, 126, 305, 400, 401, 402,
	 --                                     403, 404, 144, 140, 142, 146,183,174,168,172,173 )
	 --                       AND Audited = 0  --红冲单据
	 --                       AND PostTime >= @datMonthProc
	 --                       AND STypeID = @STypeID
	 --                       AND PtypeId LIKE + @PTypeID + '%'
	            
	 --                       AND IsService = 0
	 --                       AND KtypeId <> '10000' --是否排除代销，要看委托代销退货单
	 --               UNION 
		--			SELECT a.PTypeID
		--			FROM ReceiptBill a
		--			INNER JOIN ReceiptBillIndex b
		--			ON a.BillNumberID=b.BillNumberID
		--			WHERE a.BillType=404 AND b.RedWord=1
		--			AND b.PostTime >= @datMonthProc
		--			AND b.STypeID = @STypeID
		--			AND a.PtypeId LIKE + @PTypeID + '%'
	 --   END
		
		----判断是否存在过账后修改的单据,Old_Bill中的商品都是非服务类商品
		----关联的修改单据的商品信息（这里还需要考虑过滤掉@strPTypeID,@strSTypeID），这个稍后处理

	 --   IF EXISTS ( SELECT DISTINCT
	 --                       PTYPEID
	 --               FROM    dbo.CostRe_Bill
	 --               WHERE   BillType IN ( 34, 11, 45, 6, 160, 161, 9, 14, 57, 17,
	 --                                     21, 187, 188, 201, 202, 16, 139, 126,
	 --                                     305, 400, 401, 402, 403, 404 )
	 --                       AND PostTime >= @datMonthProc
	 --                       AND STypeID = @STypeID )
	 --       BEGIN
	 --           INSERT  #ModifyPTypeInfo
	 --                   ( PTypeID
	 --                   )
	 --                   SELECT DISTINCT
	 --                           PTYPEID
	 --                   FROM    dbo.CostRe_Bill
	 --                   WHERE   BillType IN ( 34, 11, 45, 6, 160, 161, 9, 14, 57,
	 --                                         17, 21, 187, 188, 201, 202, 16, 139,
	 --                                         126, 305, 400, 401, 402, 403, 404 )
	 --                           AND PostTime >= @datMonthProc
	 --                           AND STypeID = @STypeID
	 --                           AND PTypeID LIKE @PTypeID + '%'
							
	 --       END

	 --   SELECT  PTypeID
	 --   FROM    #RedWordPTypeInfo
	 --   UNION
	 --   SELECT  PTypeID
	 --   FROM    #ModifyPTypeInfo
		
		--DROP TABLE #RedWordPTypeInfo,#ModifyPTypeInfo
	END
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_Query_PosTermineInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_Query_PosTermineInfo];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2017-10-24
	描述：Pos终端信息查询
*/
CREATE PROCEDURE Gp_Query_PosTermineInfo
    (
      @Type VARCHAR(50) = '' ,
      @OperatorID VARCHAR(100) = '' , 	-- 操作员ID
      @posid INT--pos机id
    )

--@encode$--
AS
    SET NOCOUNT ON;
    BEGIN
        IF @Type = 'employee'
            BEGIN			
                SELECT  e.Eid ,
                        e.UserCode AS usercode ,
                        e.fullname AS fullname ,
                        e.typeId AS typeid,
                        e.Comment AS remark,
                        e.sonnum
                FROM    dbo.POSEmployee p
                        INNER JOIN dbo.employee e ON e.Eid = p.Eid
                      --  INNER JOIN F_GetAllManagerBaseTypeId('',3,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = e.typeId
                WHERE   p.Posid = @posid;
            END;      
        ELSE
            IF ( @Type = 'POSOperator' )
                BEGIN
                    SELECT  e.UserCode ,
                            e.FullName ,
                            e.Eid AS OperatorId ,
                            d.FullName AS dfullname ,
                            Job AS positionname,
                            e.typeId AS typeid,
                            e.sonnum
                    FROM    dbo.employee e
                            INNER JOIN dbo.Department d ON e.DtypeID = d.typeid
                            INNER JOIN dbo.POSOperator p ON p.Eid = e.Eid
                         --   INNER JOIN F_GetAllManagerBaseTypeId('',3,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = e.typeId
                    WHERE   p.Posid = @posid; 
                END; 
            ELSE
                IF ( @Type = 'PosAccount' )
                    BEGIN
                        SELECT  A.FullName ,
                                A.UserCode ,
                                A.nId ,
                                A.Comment AS remark ,
                                A.nTypeId AS typeid,
                                A.SonNum
                        FROM    dbo.Ac_Items A
                        INNER JOIN dbo.POSAccount P ON P.nid = A.nId 
                  --      INNER JOIN F_GetAllManagerBaseTypeId('',5,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = A.nid
                        WHERE   P.Posid = @posid;
                    END; 
                ELSE 
                    IF ( @Type = 'Ptype' )
                        BEGIN
                            SELECT  P.FullName ,
                                    P.UserCode ,
                                    P.Pid ,
                                    P.Comment AS remark ,
                                    P.Standard ,
                                    P.Type ,
									p.MultEntryCode  AS entrycode,
                                    P.typeId AS typeid,
                                    P.sonnum
                            FROM    dbo.ptype P
                            INNER JOIN dbo.POSPtype PT ON P.Pid = PT.pid
                   --         INNER JOIN F_GetManPTypeIdS(@OperatorID) ON F_GetManPTypeIdS.TypeId = p.typeId
                            WHERE   PT.Posid = @posid;
                        END; 
                    ELSE
                        IF ( @Type = 'btype' )
                            BEGIN
                                SELECT  B.FullName ,
                                        B.UserCode ,
                                        B.Bid ,
                                        B.Comment AS remark ,
                                        TelAndAddress AS address,
                                        B.typeId AS typeid,
                                        B.sonnum
                                FROM    dbo.btype B
                                INNER JOIN dbo.POSBtype P ON P.bid = B.Bid
                       --         INNER JOIN F_GetAllManagerBaseTypeId('',2,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = p.typeId
                                WHERE   P.Posid = @posid;
			
                            END;   
    END;



GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_Query_WdConfig]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_Query_WdConfig];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2016-11-20
	描述：读取网店配置信息
	EXEC Gp_Query_WdConfig
*/
CREATE PROCEDURE Gp_Query_WdConfig

--@encode$--
AS
    SET NOCOUNT ON;

    BEGIN
        CREATE TABLE #WdConfigTable
            (
              summary BIT ,
              buyermessage BIT ,
              detailaddress BIT ,
              mobile BIT ,
              buyername BIT ,
              DirectPost BIT ,
              InventoryRefreshIntime BIT ,
              BaseInfoRefresh BIT ,
              autoSync BIT ,
              refreshTime VARCHAR(50),
              collectBill BIT,
              goodsPrice VARCHAR(50) ,
              addsync BIT,
              billcode BIT,
              batchNumberDeal INT,
              yddsc				VARCHAR(10),	--是否启用1688
              dp1688			VARCHAR(10),	--对应店铺
              dpdw				INT,			--上传1688订单数量单位 
              dmf				VARCHAR(10),		--收款账户
              markername		VARCHAR(200)		--专业市场代码
            );
        DECLARE @Value VARCHAR(60) ,
            @summary BIT = 0 ,
            @buyermessage BIT= 0 ,
            @detailaddress BIT = 0 ,
            @mobile BIT = 0 ,
            @buyername BIT = 0 ,
            @DirectPost BIT= 0 ,
            @InventoryRefreshIntime BIT = 0 ,
            @BaseInfoRefresh BIT = 0 ,
            @addsync BIT = 0,
            @autoSync BIT = 0 ,
            @collectBill BIT=0,
            @refreshTime VARCHAR(50)= '0',
            @goodsPrice VARCHAR(50)='网店商品单价',
            @billcode VARCHAR(50),
            @batchNumberDeal int=2,
            @isUse1688		varchar(10),
            @dpl1688id		varchar(10),
            @dpdw			varchar(10),
            @dmf			varchar(10),
            @markername		VARCHAR(200)
            
            
        SELECT @isUse1688 = Value FROM WdShopBaseInfo WHERE Field = 'isUse1688'
        SELECT @dpl1688id = Value FROM WdShopBaseInfo WHERE Field = 'dpl1688id'
        SELECT @dpdw = Value FROM WdShopBaseInfo WHERE Field = 'dpdw'
        SELECT @dmf = Value FROM WdShopBaseInfo WHERE Field = 'dmf'  
        SELECT @markername = Value FROM WdShopBaseInfo WHERE Field = 'markername'  
        
		SELECT @batchNumberDeal = Value FROM dbo.WdShopBaseInfo WHERE Field ='BatchNumberDeal';
	
        IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'SummaryItem' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'SummaryItem';
                IF @Value IS NOT NULL
                    OR @Value <> ''
                    BEGIN
                        IF CHARINDEX('summary', @Value) > 0
                            SET @summary = 1;
                        IF CHARINDEX('buyermessage', @Value) > 0
                            SET @buyermessage = 1;
                        IF CHARINDEX('detailaddress', @Value) > 0
                            SET @detailaddress = 1;
                        IF CHARINDEX('mobile', @Value) > 0
                            SET @mobile = 1;
                        IF CHARINDEX('buyername', @Value) > 0
                            SET @buyername = 1;
						IF CHARINDEX('billcode', @Value) > 0
							SET @billcode = 1;
                    END;
            END;	
        IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'DirectPost' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'DirectPost';
                IF ( @Value = 'True' )
                    SET @DirectPost = 1;
            END;
	                        
        IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'InventoryRefreshIntime' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'InventoryRefreshIntime';
                IF ( @Value = 'True' )
                    SET @InventoryRefreshIntime = 1;
            END;
				
		IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'addsync' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'addsync';
                IF ( @Value = 'True' )
                    SET @addsync = 1;
            END;
		
        IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'BaseInfoRefresh' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'BaseInfoRefresh';
                IF ( @Value = 'True' )
                    SET @BaseInfoRefresh = 1;			
            END;
				 
        IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'autoSync' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'autoSync';
                IF ( @Value = 'True' )
                    SET @autoSync = 1;	
            END;
            
         IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'collectBill' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'collectBill';
                IF ( @Value = 'True' )
                    SET @collectBill = 1;	
            END;
				  
        IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'refreshTime' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'refreshTime';
                IF ( @Value IS NOT NULL
                     OR @Value <> ''
                   )
                    SET @refreshTime = @Value;
            END;
            
        IF EXISTS ( SELECT  1
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'goodsPrice' )
            BEGIN
                SELECT  @Value = Value
                FROM    WdShopBaseInfo
                WHERE   Field = 'goodsPrice';
                IF ( @Value IS NOT NULL
                     OR @Value <> ''
                   )
                    SET @goodsPrice = @Value;
            END;
            
            
				   
        INSERT  INTO #WdConfigTable
                ( summary ,
                  buyermessage ,
                  detailaddress ,
                  mobile ,
                  buyername ,
                  DirectPost ,
                  InventoryRefreshIntime ,
                  BaseInfoRefresh ,
                  autoSync ,
                  refreshTime,
                  collectBill,
                  goodsPrice,
                  addsync,
                  billcode,
                  batchNumberDeal,
                  yddsc,
                  dp1688,
                  dpdw,
                  dmf,
                  markername
				 )
        VALUES  ( @summary ,
                  @buyermessage ,
                  @detailaddress ,
                  @mobile ,
                  @buyername ,
                  @DirectPost ,
                  @InventoryRefreshIntime ,
                  @BaseInfoRefresh ,
                  @autoSync ,
                  @refreshTime,
                  @collectBill,
                  @goodsPrice ,
                  @addsync,
                  @billcode,
                  @batchNumberDeal,
                  @isUse1688,
                  @dpl1688id,
                  @dpdw,
                  @dmf,
                  @markername
				 );
				           
        SELECT  *
        FROM    #WdConfigTable;
    END;


GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_Query_WdGoods]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_Query_WdGoods];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2016-11-20
	描述：网店商品信息查询
*/
CREATE PROCEDURE Gp_Query_WdGoods
    (
      @typeid	VARCHAR(MAX) ,	--商品编号
      @displayAll	INT ,	-- 是否展示全部商品 1：是 0：否 2:未上传网店商品
      @OperatorID	VARCHAR(100) = '' 	-- 操作员ID
    )

--@encode$--
AS
    SET NOCOUNT ON;

    BEGIN
        IF @typeid <> ''
            AND @typeid IS NOT NULL
            BEGIN
                SELECT DISTINCT  p.Pid AS erpid ,
                        p.deleted ,
                        p.weight ,
                        p.volume ,
                        p.typeId ,
                        p.FullName ,
                        p.Name ,
                        p.UserCode ,
                        p.EntryCode ,
                        p.Standard ,
                        p.Type ,
                        p.Area ,
                        p.Comment ,
                        p.deleted ,
                        pr.RetailPrice ,
                        pr.PreSalePrice1 ,
                        pr.PreSalePrice2 ,
                        pr.PreSalePrice3 ,
                        pr.PreSalePrice4 ,
                        pr.PreSalePrice5 ,
                        pr.PreSalePrice6 ,
                        pr.PreSalePrice7 ,
                        pr.PreSalePrice8 ,
                        pr.PreSalePrice9 ,
                        pr.PreSalePrice10 ,
                        CASE p.WdSyncFlag
                          WHEN 1 THEN '√'
                          WHEN 0 THEN ''
                        END AS syncFlag
                FROM    ptype AS p
                        INNER JOIN PType_Price AS pr ON p.typeId = pr.PTypeID
                                                        AND p.sonnum = 0
                        INNER JOIN dbo.f_split(@typeid, ',') f ON p.UserCode = f.a
                        INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = p.typeId
                        WHERE pr.IsDefaultUnit = 1 AND p.iscombinationproduct =0
                        ORDER BY p.UserCode;
                RETURN; 
            END;  
        IF @displayAll = 1
            BEGIN
                SELECT  p.Pid AS erpid ,
                        p.deleted ,
                        p.weight ,
                        p.volume ,
                        p.typeId ,
                        p.FullName ,
                        p.Name ,
                        p.UserCode ,
                        p.EntryCode ,
                        p.Standard ,
                        p.Type ,
                        p.Area ,
                        p.Comment ,
                        p.deleted ,
                        pr.RetailPrice ,
                        pr.PreSalePrice1 ,
                        pr.PreSalePrice2 ,
                        pr.PreSalePrice3 ,
                        pr.PreSalePrice4 ,
                        pr.PreSalePrice5 ,
                        pr.PreSalePrice6 ,
                        pr.PreSalePrice7 ,
                        pr.PreSalePrice8 ,
                        pr.PreSalePrice9 ,
                        pr.PreSalePrice10 ,
                        CASE p.WdSyncFlag
                          WHEN 1 THEN '√'
                          WHEN 0 THEN ''
                        END AS syncFlag
                FROM    ptype AS p
                        INNER JOIN PType_Price AS pr ON p.typeId = pr.PTypeID AND p.sonnum = 0
                        INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = p.typeId
                        WHERE pr.IsDefaultUnit = 1  AND p.iscombinationproduct =0
                        ORDER BY p.UserCode; 
            END;
        IF @displayAll = 0
            BEGIN
                SELECT  p.Pid AS erpid ,
                        p.deleted ,
                        p.weight ,
                        p.volume ,
                        p.typeId ,
                        p.FullName ,
                        p.Name ,
                        p.UserCode ,
                        p.EntryCode ,
                        p.Standard ,
                        p.Type ,
                        p.Area ,
                        p.Comment ,
                        p.deleted ,
                        pr.RetailPrice ,
                        pr.PreSalePrice1 ,
                        pr.PreSalePrice2 ,
                        pr.PreSalePrice3 ,
                        pr.PreSalePrice4 ,
                        pr.PreSalePrice5 ,
                        pr.PreSalePrice6 ,
                        pr.PreSalePrice7 ,
                        pr.PreSalePrice8 ,
                        pr.PreSalePrice9 ,
                        pr.PreSalePrice10 ,
                        CASE p.WdSyncFlag
                          WHEN 1 THEN '√'
                          WHEN 0 THEN ''
                        END AS syncFlag
                FROM    ptype AS p
                        INNER JOIN PType_Price AS pr ON p.typeId = pr.PTypeID AND p.sonnum = 0 AND p.WdSyncFlag = 1
                        INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = p.typeId
                        WHERE pr.IsDefaultUnit = 1
                        ORDER BY p.UserCode;
            END; 
        IF @displayAll = 2
        BEGIN
			SELECT  p.Pid AS erpid ,
                        p.deleted ,
                        p.weight ,
                        p.volume ,
                        p.typeId ,
                        p.FullName ,
                        p.Name ,
                        p.UserCode ,
                        p.EntryCode ,
                        p.Standard ,
                        p.Type ,
                        p.Area ,
                        p.Comment ,
                        p.deleted ,
                        pr.RetailPrice ,
                        pr.PreSalePrice1 ,
                        pr.PreSalePrice2 ,
                        pr.PreSalePrice3 ,
                        pr.PreSalePrice4 ,
                        pr.PreSalePrice5 ,
                        pr.PreSalePrice6 ,
                        pr.PreSalePrice7 ,
                        pr.PreSalePrice8 ,
                        pr.PreSalePrice9 ,
                        pr.PreSalePrice10 ,
                        CASE p.WdSyncFlag
                          WHEN 1 THEN '√'
                          WHEN 0 THEN ''
                        END AS syncFlag
                FROM    ptype AS p
                        INNER JOIN PType_Price AS pr ON p.typeId = pr.PTypeID AND p.sonnum = 0 AND p.WdSyncFlag = 0
                        INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = p.typeId
                        WHERE pr.IsDefaultUnit = 1  AND p.iscombinationproduct =0
                        ORDER BY p.UserCode;
        END 
       
    END;


GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryAllBillExLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryAllBillExLine]
GO




/*
	作者：谢吉康
	日期：2007-3-21
	描述：单据统计的处理
*/


CREATE	PROCEDURE Gp_QueryAllBillExLine
(    
	@chvOperatorID  	varchar(100),     -------操作员ID号
	@VchType 			numeric(4,0),  
	@BeginDate 			varchar(30),
	@EndDate 			varchar(30),	
	@Parid    			varchar(50),
	@chvBtypeName 		VarChar(MAX)='',
	@chvEtypeName 		varchar(MAX)='',
	@chvKtypeName 		varchar(MAX)='',
	@IFCheck 			char(1)='t',             
	@BillCode       	varchar(50)='',
	@Comment        	varchar(256)='', 
	@chvKtypeName2 		varchar(MAX)='',
	@STypeId			varchar(MAX),
	@ifAssets			varchar(10)			--资产管理模式："0"：非总账模式(项目管理)，="1"：总账模式(卡片管理)
)
--@encode$--
AS
SET nocount ON
SET ANSI_WARNINGS  off

DECLARE @cz_Dx varchar(50),@DbName  varchar(30)
DECLARE @SQL varchar (8000)
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID is null RETURN -1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re		


DECLARE @ASQL varchar(2000)
DECLARE @BSQL varchar(2000)
DECLARE @PSQL varchar(2000)
DECLARE @ESQL varchar(2000)
DECLARE @KSQL varchar(2000)
DECLARE @SQLM_WHERE varchar(2000)

SET @ASQL=''
SET @BSQL=''
SET @PSQL=''
SET @ESQL=''
SET @KSQL=''
SET @SQLM_WHERE=''

--================================================= 定义通用条件 BEGIN

DECLARE @CurSONNum int       --检测当前的SONNum 
DECLARE @BtypeAll int
SELECT @BtypeAll=value FROM UserCONfig WHERE CONfigName='BtypeAll'
		
DECLARE @PTypeID   varchar(50)
DECLARE @SQL_WHERE varchar(4000)
DECLARE @SQL_Group varchar(4000)
SET @PTypeID = @parid


SELECT @SQL_WHERE = ''
												
-----------------------------------------------判断商品的范围
CREATE TABLE #PTYPE(Typeid varchar(100))
INSERT INTO #PTYPE(Typeid)	SELECT TypeId  FROM F_GetManDetailPType(@chvOperatorID)
IF @Ptypeid <> '00000'
	SET @PSQL = @PSQL + ' AND a.PTypeID Like '+char(39)+@PtypeID+'%'+char(39)

IF @MPTypeId = '-99999'
	SET @PSQL = @PSQL +' AND a.PTypeID IN (SELECT TypeId FROM #PTYPE)'
-----------------------------------------------判断客户的范围
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF NOT (@chvBtypeName='' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	BEGIN
		INSERT INTO #GetManBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvBtypeName,2,@chvOperatorID) S
		IF @VchType IN (191,197) AND @chvBtypeName = ''
		BEGIN
			INSERT INTO #GetManBTypeId(TypeId)VALUES('')
		END		
		SET @BSQL = @BSQL +' AND M.TypeId IN (SELECT * FROM #GetManBTypeId)'
	END
-----------------------------------------------判断职员的范围
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF NOT (@chvEtypeName='' AND @METypeId = '00001')
	BEGIN
		INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvEtypeName,3,@chvOperatorID) S
		SET @ESQL = @ESQL +' AND E.TypeId IN (SELECT * FROM #GetManETypeId)'
	END
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperatorID)			

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)

--仓库信息必须单独处理
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@chvOperatorID)

CREATE TABLE #Stock1(TypeId	varchar(100))
CREATE TABLE #Stock2(TypeId	varchar(100))

DECLARE @TypeId	varchar(100),
		@SonNum	int

IF @VchType = 17 OR @VchType = 21
	BEGIN
		IF EXISTS(SELECT Value FROM UserConfig WHERE ConfigName ='MoveInOutKLimit' AND Value='1') -- 调拔单中仓库权限有效
			BEGIN
								--出库仓库
				INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName,4,@chvOperatorID) S
		
				--入库仓库
				INSERT INTO #Stock2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName2,4,@chvOperatorID) S

				--组织查询条件				
				SET @KSQL = @KSQL + ' AND (B.KTypeId IN (SELECT TypeId FROM #Stock1) AND B.KTypeId2 IN (SELECT TypeId FROM #Stock2))'
			END
		ELSE
			BEGIN
								--出库仓库
				INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName,4,'00001') S
		
				--入库仓库
				INSERT INTO #Stock2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName2,4,'00001') S

				--组织查询条件
				SET @KSQL = @KSQL + ' AND (B.KTypeId IN (SELECT TypeId FROM #Stock1) OR B.KTypeId2 IN (SELECT TypeId FROM #Stock2))'
			END
	END
ELSE IF @VchType = 16 OR @VchType = 160 OR @VchType = 161 OR @VchType = 166 OR @VchType = 172 OR @VchType = 173  OR @VchType = 174  OR @VchType = 175
	BEGIN
		IF @VchType = 160
			BEGIN
				--出库仓库		
				INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName2,4,@chvOperatorID) S
				--入库仓库
				INSERT INTO #Stock2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName,4,@chvOperatorID) S
			END
		ELSE
			BEGIN
				--出库仓库		
				INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName,4,@chvOperatorID) S
				--入库仓库
				INSERT INTO #Stock2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName2,4,@chvOperatorID) S
			END

		--组织查询条件
		IF @VchType IN (166,172)
			BEGIN
				SET @KSQL = @KSQL + ' AND ('
				IF @chvKtypeName = '' AND @chvKtypeName2 = ''
					BEGIN
						SET @KSQL = @KSQL +' (B.KTypeId IN (SELECT * FROM #GetManKTypeId) OR B.KTypeId2 IN (SELECT * FROM #GetManKTypeId))'
						SET @KSQL = @KSQL +' OR (B.KTypeId IN (SELECT * FROM #GetManKTypeId) AND B.KTypeId2='''')'
						SET @KSQL = @KSQL +' OR (B.KTypeId='''' AND B.KTypeId2 IN (SELECT * FROM #GetManKTypeId))'
						SET @KSQL = @KSQL +' OR (B.KTypeId='''' AND B.KTypeId2='''')'
					END
				ELSE IF @chvKtypeName = '' AND @chvKtypeName2 <> ''
					BEGIN
						SET @KSQL = @KSQL + ' ((B.KTypeId='''' OR B.KTypeId IN (SELECT * FROM #GetManKTypeId)) AND (B.KTypeId2 IN (SELECT * FROM #Stock2)))'
					END
				ELSE IF @chvKtypeName <> '' AND @chvKtypeName2 = ''
					BEGIN
						SET @KSQL = @KSQL + ' ((B.KTypeId IN (SELECT * FROM #Stock1)) AND B.KTypeId2 IN (SELECT * FROM #GetManKTypeId UNION SELECT ''''))'
					END
				ELSE
					BEGIN
						SET @KSQL = @KSQL + ' (B.KTypeId IN (SELECT * FROM #Stock1) AND B.KTypeId2 IN (SELECT * FROM #Stock2))'
					END
				SET @KSQL = @KSQL + ' )'
			END
		ELSE IF @VchType IN (16,160,161)
			BEGIN
				DECLARE @Ksql1	VARCHAR(MAX),
						@Ksql2	VARCHAR(MAX)

				SET @Ksql1 = ' AND 1 = 1 '
				SET @Ksql2 = ' AND 1 = 1 '				

				IF @chvKtypeName = '' AND @chvKtypeName2 = ''
					BEGIN
						IF @MKTypeId = '-99999'
							BEGIN
								SET @Ksql1 = ' AND A.KTypeId IN (SELECT * FROM #GetManKTypeId)'
								SET @Ksql2 = ' AND A.KTypeId IN (SELECT * FROM #GetManKTypeId)'
							END
					END
				ELSE
					BEGIN
						SET @Ksql1 = ' AND A.KTypeId IN (SELECT TypeId FROM #Stock1) '
						SET @Ksql2 = ' AND A.KTypeId IN (SELECT * FROM #Stock2) '
					END
			END
		ELSE IF @VchType IN (173,174,175)
			BEGIN
				IF @chvKtypeName = '' AND @chvKtypeName2 = ''
					BEGIN
						IF @MKTypeId = '-99999'
							SET @KSQL = @KSQL + ' AND ((B.KTypeId IN (SELECT * FROM #GetManKTypeId)) OR (B.KTypeId2 IN (SELECT * FROM #GetManKTypeId)))'
					END
				ELSE
					BEGIN
						IF @chvKtypeName <> '' AND @chvKtypeName2 = ''
							SET @KSQL = @KSQL + ' AND B.KTypeId IN (SELECT TypeId FROM #Stock1) AND B.KTypeId2 IN (SELECT * FROM #GetManKTypeId) '
						ELSE
							SET @KSQL = @KSQL + ' AND B.KTypeId IN (SELECT * FROM #Stock1) AND B.KTypeId2 IN (SELECT TypeId FROM #Stock2)'
					END
			END
	END
ELSE
	BEGIN
		INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@chvKTypeName,4) S,F_GetManDetailKType(@chvOperatorID) M WHERE S.TypeId = M.TypeId
		--组织查询条件
		IF @vchType = 57
			BEGIN
				IF @chvKtypeName = ''		
					BEGIN
						IF @MKTypeId = '00000'
							SET @KSQL = @KSQL + ' AND A.KTypeID IN (SELECT TypeId FROM #Stock1 UNION SELECT ''00000'') '
						ELSE
							SET @KSQL = @KSQL + ' AND (A.KTypeID IN (SELECT TypeId FROM #Stock1)) '
					END
				ELSE
					SET @KSQL = @KSQL + ' AND A.KTypeID IN (SELECT TypeId FROM #Stock1)'
			END
		ELSE
			BEGIN
				IF @chvKtypeName <> ''		
					SET @KSQL = @KSQL + ' AND A.KTypeID IN (SELECT TypeId FROM #Stock1)'
				ELSE
					IF @MKTypeId = '-99999'
						SET @KSQL = @KSQL + ' AND A.KTypeId IN (SELECT * FROM #Stock1 UNION SELECT ''10000'')'
			END
	END

--===================================================================日期
IF  @VchType in(11,45,34,6,9,14,17,21,16,57,126,139,140,142,143,144,146,147,160,161,178,187,188,191,196,197,201,202,305,215,12,46) 
	OR @VchType in(4,66,115,116,128,129,36,93,77,84,85,78,5,10,141,145,158,159,189,190,212,213,214) 
	OR @VchType IN (165,167,169,170)
	--发票立账相关单据
	OR @VchType IN (400,401,402,403)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND a.billdate>='+char(39)+@BeginDate+char(39)+' AND a.billdate<='+char(39)+@EndDate+char(39)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.billdate>='+char(39)+@BeginDate+char(39)+' AND b.billdate<='+char(39)+@EndDate+char(39)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.BillCode like '+ char(39)+'%'+@BillCode+'%'+char(39)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.Comment like '+ char(39)+'%'+@Comment+'%'+char(39)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.IFCheck ='+ char(39)+ 't'+ char(39) 
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.RedWord ='+ char(39)+ '0'+ char(39) 
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.IfYearBill = 0 '
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.DTypeId IN (SELECT * FROM #GetManDTypeId) '

--================================================= 定义通用条件 END


-------------------------------------------------------------------------------------------------------------------------------
IF  @VchType in(11,45,34,6,17,21,9,14,16,57,126,139,305,140,142,143,144,146,147,155,160,161,178,187,188,191,196,197,201,202,215,400,401,402,403,12,46) 
	SET @DbName = 'InOutstocktable'  
ELSE IF @VchType in(4,66,115,116,128,129,36,93,77,84,85,78,5,10,141,145,148,149,150,151,158,159,189,190,212,213,214) 
	SET @DbName = 'listtable'
ELSE IF @VchType IN (165,167,168,169,170,171)
	SET @DbName = 'Wx_InOutStockTable'
ELSE IF @VchType = 166
	SET @DbName = 'Wx_Bill_Self'
ELSE IF @VchType = 172
	SET @DbName = 'Wx_Bill_GoTo'
ELSE IF @VchType = 173
	SET @DbName = 'Wx_Bill_In'
ELSE IF @VchType = 174
	SET @DbName = 'Wx_Bill_Out'
ELSE IF @VchType = 175
	SET @DbName = 'Wx_Bill_Move'
ELSE 
	RETURN -1
-------------------------------------------------------------------------------------------------------------------------------



DECLARE @BtypeIDLen int
DECLARE @PtypeidLen int
DECLARE @AtypeidLen int

DECLARE @dbNameB varchar(120) --(由于单据统计中的合计不正确，加上权限范围限制,2002-12-2吴德水加)
SELECT @dbNameB='SELECT * FROM '+@dbName+' WHERE EtypeId like '+char(39)+@MEtypeid+'%'+char(39)

IF @VchType IN (6,11,34,45,305,140,142,144,146,178,215,400,401,402,403,139,126,12,46)
	BEGIN
		SELECT @dbNameB=@dbName
		IF @vchtype=140  or @vchtype=142 or @vchtype=144 or @vchtype=146
			BEGIN
				SET @KSQL = @KSQL + 'AND a.ktypeid<>'+char(39)+'10000'+char(39)
			END
		SET @SQL_WHERE = @SQL_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
	
		IF @Parid = '00000'
			SET @Parid =''
		 SET @SQL='	SELECT	a.ptypeid ,
							abs( isnull(SUM(  a.qty), 0)) AS Qty,
							abs( isnull(SUM(a.Total), 0)) AS Total,
							CASE when  isnull(SUM( a.qty), 0)=0 then 0 ELSE ISNULL((isnull(CAST(SUM(a.Total) AS NUMERIC(24,10)),0)/abs(isnull(cast(SUM(a.qty) AS NUMERIC(24,10)), 0))),0) END  AS Price,
				            CASE when  isnull(SUM( a.qty), 0)=0 then 0 ELSE ISNULL((isnull(CAST(SUM(a.Total) AS NUMERIC(24,10)),0)/isnull(CAST(SUM(a.qty) AS NUMERIC(24,10)), 0)),0) END  AS Price2,
								isnull(sum(a.TaxTotal),0) AS TaxTotal
		     		FROM  	'+@dbnameB+' a 
		     		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)	'
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY	a.ptypeid '
	
		SET @SQL = 'SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.total,0) as Total,
							isnull(x.price,0) as Price,
							isnull(x.Price2,0) as Price2,
							isnull(x.TaxTotal,0) as TaxTotal ,
							dbo.F_RoundQty(x.qty/ue.Rate) as Mqty  ,
							pu.fullname as Munitfullname,
							dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname as rateralation,
							pu1.fullname as basefullname
			   		FROM 	Ptype p  
			   		left JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId
			   		inner join ('+@SQL+') as x ON p.typeid=x.Ptypeid   '
		 IF @vchtype IN(305,11,215,45,402,403,140,142,139,12,46)
			SET @SQL =@SQL+ ' 
					INNER JOIN dbo.PType_Units_Ext ue on	 p.SaleUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN dbo.PType_Units pu ON p.SaleUnitId=  pu.UnitsId
			'	
			ELSE
				SET @SQL =@SQL+ ' 
							INNER JOIN dbo.PType_Units_Ext ue on	 p.BuyUnitId=ue.UnitsId AND p.typeId=ue.PtypeID	
							INNER JOIN dbo.PType_Units pu ON p.BuyUnitId=  pu.UnitsId '  
							
			SET @SQL =@SQL+ '   		WHERE	p.TypeID LIKE '''+@Parid +'%'' '+' order by p.sortid'
			--print @SQL
			EXEC(@SQL)
	END      
ELSE IF  @VchType = 165 Or @VchType = 167 Or @VchType = 169 Or @VchType = 170 --报损、报溢、赠送及获赠（赠为吴德水2002-10-29添加）
		BEGIN
			SELECT @dbNameB=@dbName
			SET @SQL_WHERE = @SQL_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		
			IF @Parid = '00000'
				SET 	@Parid =''
			 SET @SQL=' 
				SELECT	a.ptypeid,
			            abs( isnull(SUM(a.qty), 0)) AS Qty,
						abs( isnull(SUM(a.CostTotal), 0)) AS Total				        	       
			    FROM  	'+@dbnameB+' a 
			    INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)   '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
				WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
				GROUP BY a.ptypeid'
		
			SET @SQL = 'SELECT	p.typeid as typeid,
								p.usercode as usercode,
								p.fullname as fullname,
								p.sONnum as sONnum,
								p.parid as parid,
								p.leveal as leveal,
								isnull(x.qty,0) as qty,
								isnull(x.total,0) as Total							
				   		FROM 	Ptype p join ('+@SQL+') as x ON p.typeid=x.Ptypeid
				   		WHERE	p.TypeID LIKE '''+@Parid +'%''
						order by p.sortid'
			--PRINT @SQL
			EXEC(@SQL)		
			RETURN		
		END
ELSE IF @vchtype=115 or @vchtype=116 or @vchtype=128 or @vchtype=129 --应收款减少      应收款增加，     应付款增加       应付款减少	
	BEGIN
		CREATE TABLE #BaseBtype(typeid varchar(100))
		INSERT INTO #BaseBtype SELECT typeId FROM F_GetAllBaseTypeId(@chvBtypeName,2)
		CREATE TABLE #Btype(typeid varchar(100),
							parid varchar(100),
							UserCode VARCHAR(200),
							FullName VARCHAR(200),
							sonnum int,
							leveal	int
							)
		INSERT INTO #BType SELECT typeId,parid,UserCode,FullName,sonnum,leveal FROM F_GetManBType(@chvOperatorID)
		CREATE TABLE #DetailBtype(typeid varchar(100))
		INSERT INTO #DetailBType SELECT typeId FROM F_GetManDetailBType(@chvOperatorID)
		
		SELECT @dbNameB=@dbName
		IF @Parid<>'00000'
			SET @BSQL=' AND a.Btypeid like ' + char(39) +@Parid+'%'+char(39)
		ELSE
			SET @BSQL =' '
	
		SET @BSQL = @BSQL + ' AND a.BTypeId IN (SELECT TypeId FROM #BaseBtype) AND a.BTypeId IN (SELECT TypeId FROM #DetailBtype)'
	
		--PRINT @BSQL
		IF @Parid = '00000'
			SET 	@Parid =''
		SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +REPLACE(@BSQL,'M.TypeId','A.BTypeId')+@SQLM_WHERE
		SET @SQL=' 
			SELECT	a.btypeid,
		                ( isnull(SUM(abs(isnull(a.Total,0))), 0)) AS Total --#01 徐辉 2004-11-19
	        	FROM  '+@dbnameB+' a 
				INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
				WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
				GROUP BY a.btypeid'

		SET @SQL = 'SELECT	b.typeid as typeid,
							b.usercode as usercode,
							b.fullname as fullname,
							b.sONnum as sONnum,
							b.parid as parid,
							b.leveal as leveal,
							(isnull(x.total,0)) as Total
					FROM	#Btype b 
					INNER JOIN	('+@SQL+') as x ON b.typeid=x.btypeid
					WHERE	b.TypeID LIKE '+char(39)+@parid+'%'+char(39)+'							
					order by b.usercode'
		--PRINT @SQL	
		EXEC(@SQL)
		DROP TABLE #BaseBtype,#Btype,#DetailBtype
		RETURN
	END 
ELSE IF @vchtype=36 or @vchtype=93 or @vchtype=84 or @vchtype=85 or @vchtype=78 or @vchtype=5 or @vchtype=10  or @vchtype=77 or @vchtype=212 or @vchtype=213 or @vchtype=214 
-- or @vchtype=158   9.5 BUG 1053，由于现金费用单需要统计表体经手人，所以拆分开单独查询
	BEGIN
	--费用，其他收入  固定资产购买   (、  固定资产变卖、固定资产折旧、待摊费用发生、摊销   77转款   158 现金费用单
		CREATE TABLE #AtypeFy(typeid varchar(100))
		INSERT INTO #AtypeFy SELECT nid FROM F_GetManDetailATypeFy(@chvOperatorID)
		CREATE TABLE #AtypeSr(typeid varchar(100))
		INSERT INTO #AtypeSr SELECT nid FROM F_GetManDetailATypeSr(@chvOperatorID)
		CREATE TABLE #AtypeZc(typeid varchar(100))
		INSERT INTO #AtypeZc SELECT nid FROM F_GetManDetailATypeZc(@chvOperatorID)
				
		SELECT @dbNameB=@dbName
		--PRINT @dbNameB
		SET @SQL_WHERE = ''
		IF @Parid='root' 
			SET @Parid='00000'
		/*IF @Parid='00000'
			SET @ASQL=' AND a.atypeid like ' + char(39) +''+'%'+char(39)
		ELSE
			SET @ASQL=' AND a.atypeid like ' + char(39) +@Parid+'%'+char(39)*/
	
		
		IF  @vchtype=84 or @vchtype=85 or @vchtype=212 or @vchtype=213
			SET @ASQL = @ASQL + '  AND a.atypeid IN (SELECT * FROM #AtypeZc)'
		IF @vchtype =78 or @vchtype=214
			SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeFy) ' 
		IF @vchtype =36
			SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeFy)'
		--IF @vchtype =158
		--	SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeFy)'
		IF @vchtype =93
			SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeSr)'
	/*
		IF @vchtype=5 or @vchtype=10
			SET @ASQL = @ASQL + ' AND a.atypeid like ' + char(39) +'0000100007'+'%'+char(39)
		IF @vchtype=36
			SET @ASQL = @ASQL + ' AND a.atypeid like ' + char(39) +'0000400003'+'%'+char(39)*/
		
		
		IF @vchtype=93 or @vchtype=84 or @vchtype=85 or @vchtype=36 or @vchtype=212 or @vchtype=213
			SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@ASQL+@SQLM_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')
		ELSE
			SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@ASQL+@SQLM_WHERE
		IF @Parid = '00000'
			SET 	@Parid =''
		SET @SQL=' 
			SELECT	a.atypeid,
			        abs( isnull(SUM(a.Total), 0)) AS Total
			FROM  '+@dbnameB+' a 
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
			
		SET @SQL=@SQL +	'
		WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
		GROUP BY
			a.atypeid'
		SET @SQL = 'SELECT 	a.ntypeid as typeid,
							a.usercode as usercode,
							a.fullname as fullname,
							a.sONnum as sONnum,
							a.parid as parid,
							a.leveal as leveal,
							abs(isnull(x.total,0)) as Total
		   			FROM 	ac_items a Join ('+@SQL+') as x ON a.nid=x.atypeid '
		 IF @parid<>'' 
		   	SET @SQL=@SQL+'	WHERE A.nid not in(29,36,1)	and a.IsBank<>1 
		   					AND a.nTypeID LIKE '+CHAR(39)+@parid+'%'+CHAR(39)+''			
		  	SET @SQL=@SQL+'	ORDER by a.usercode '
		
		EXEC(@SQL)
		DROP TABLE #AtypeFy,#AtypeSr,#AtypeZc
		RETURN  
	END
ELSE IF @vchtype=158 -- 现金费用单
	BEGIN
		CREATE TABLE #AtypeFy1(typeid varchar(100))
		INSERT INTO #AtypeFy1 SELECT nid FROM F_GetManDetailATypeFy(@chvOperatorID)
		SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeFy1)'
	
		SELECT @dbNameB = @dbName
		SET @SQL_WHERE = ''
		IF @Parid='root' 
			SET @Parid='00000'
		
		SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','M.ETypeId') + @ASQL + @SQLM_WHERE
		
		IF @Parid = '00000'
			SET @Parid = ''
			
		SET @SQL=' 
			SELECT	tempN.atypeid,
			        abs( isnull(SUM(tempN.Total), 0)) AS Total
			FROM  (select DISTINCT a.Total,m.atypeid,M.ShowOrder,M.billnumberid 
			FROM '+@dbnameB+' a 
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  
			INNER JOIN moneybill AS M ON(A.BillNumberId = M.BillNumberId AND A.AtypeId = M.AtypeId AND A.Total = M.total) 
			INNER JOIN #GetManDTypeId D ON D.typeid = M.dtypeid '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		--现金费用单部分通过表体统计，需要排除筛选表头部门条件	
		SET @SQL_WHERE = REPLACE(@SQL_WHERE,'AND b.DTypeId IN (SELECT * FROM #GetManDTypeId)','')
		SET @SQL=@SQL +	'
		WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +') as tempN '+
		'GROUP BY 
			tempN.atypeid '

		SET @SQL ='SELECT 	a.ntypeid as typeid,
							a.usercode as usercode,
							a.fullname as fullname,
							a.sONnum as sONnum,
							a.parid as parid,
							a.leveal as leveal,
							abs(isnull(x.total,0)) as Total
		   			FROM 	ac_items a Join ('+@SQL+') as x ON a.nid=x.atypeid '
		 IF @parid<>'' 
		   	SET @SQL=@SQL+'	WHERE A.nid not in(29,36,1)	and a.IsBank<>1 
		   					AND a.nTypeID LIKE '+CHAR(39)+@parid+'%'+CHAR(39)+''			
		  	SET @SQL=@SQL+'	ORDER by a.usercode '
		
		--PRINT @SQL
		EXEC(@SQL)
		DROP TABLE #AtypeFy1
		RETURN  
	END
ELSE IF  @vchtype=159 -- 会计凭证
	BEGIN
		CREATE TABLE #Temp
		(
			TypeId	VARCHAR(MAX)			
		)
		
		CREATE TABLE #KjPzTable
		(
			TypeId	VARCHAR(MAX)			
		)
		
		--删除不符合的数据
		INSERT INTO #Temp SELECT nid FROM F_GetManDetailAType(@chvOperatorID)
		INSERT INTO #Temp SELECT nid FROM F_GetManDetailATypeFy(@chvOperatorID)
		INSERT INTO #Temp SELECT nid FROM F_GetManDetailATypeSr(@chvOperatorID)
		INSERT INTO #Temp SELECT nid FROM F_GetManDetailATypeZc(@chvOperatorID)
		
		INSERT INTO #Temp(TypeId) 
		SELECT	nId 
		FROM	Ac_Items 
		WHERE	sonnum = 0 
				AND nId NOT IN (
									SELECT	nid 
									FROM	Ac_Items 
									WHERE	(nTypeId LIKE '0000100004%' OR nTypeId = '0000100003'	--At
											OR nTypeId LIKE '0000400003%'						--Fy
											OR nTypeId LIKE '0000300003%'						--Sr
											OR nTypeId LIKE '0000100002%')						--Zc					
								  ) 
				and nId not in(54,55)
								  
		INSERT INTO #KjPzTable(TypeId) SELECT DISTINCT TypeId FROM #Temp
		
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = ''
		--IF @Parid='00000'
		--	SET @ASQL=' AND a.atypeid like ' + char(39) +''+'%'+char(39)
		--ELSE
		--	SET @ASQL=' AND a.atypeid like ' + char(39) +@Parid+'%'+char(39)
		IF @Parid='00000'
		   SET @Parid =''	
		
		
		SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@ASQL+@SQLM_WHERE
		SET @SQL=' 
		SELECT	a.atypeid,
		        isnull(SUM(a.Total), 0) AS Total
		FROM  '+@dbnameB+' a 
		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
		INNER JOIN #KjPzTable T ON T.TypeId = A.ATypeId  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
		WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
		GROUP BY a.atypeid'
		
		SET @SQL = 'SELECT	a.nTypeId as typeid,
							a.usercode as usercode,
							a.fullname as fullname,
							a.sONnum as sONnum,
							a.parid as parid,
							a.leveal as leveal,
							isnull(x.total,0) as Total
		   			FROM 	ac_items a Join ('+@SQL+') as x ON a.nid=x.atypeid'
		IF @parid<>'' 
		   	SET @SQL=@SQL+'	WHERE 	a.nTypeID  LIKE '+CHAR(39)+@parid+'%'+CHAR(39)
		  	SET @SQL=@SQL+'	ORDER by a.usercode '
		  	
		  	
		  	--PRINT @SQL
		EXEC(@SQL)
		
		DROP TABLE #Temp,#KjPzTable
		
		RETURN
	END
-- ==============================================
ELSE IF @vchtype=66 or @vchtype=4 OR @VchType = 189 OR @VchType = 190 --付款单、收款单、预收款单、预付款单
	BEGIN
		DECLARE @Temp varchar(200),
				@YF_ID  VARCHAR(50)
				
		SELECT @YF_ID=NID FROM Ac_Items WHERE UserCode='1151'
		SET @Temp=''
		SELECT @dbNameB=@dbName
		
		CREATE TABLE #AType
		(
			TypeId		VARCHAR(50),
			ntypeid		VARCHAR(50),
			ParId		VARCHAR(50),
			Leveal		VARCHAR(50),
			SonNum		VARCHAR(50),
			SonCount	VARCHAR(50),
			UserCode	VARCHAR(300),
			FullName	VARCHAR(300),
			Deleted		VARCHAR(10)
		)

		INSERT INTO #AType 
		SELECT	typeId,ntypeid,nparid,1,sonnum,soncount,UserCode,FullName,deleted 
		FROM	F_GetManAType(@chvOperatorID)		
		
		SET @SQL_WHERE = ''

			
		--权限范围	
		IF @VchType = 4
			BEGIN
				INSERT INTO #AType 
				SELECT	nId,ntypeid,nparid,leveal,sonnum,soncount,UserCode,FullName,deleted 
				FROM	Ac_Items
				WHERE	UserCode = '2131'
			END
		ELSE IF @VchType = 66
			BEGIN
				INSERT INTO #AType 
				SELECT	nid,ntypeid,nparid,leveal,sonnum,soncount,UserCode,FullName,deleted 
				FROM	Ac_Items
				WHERE	UserCode = '1151'	
			END
		ELSE	
			
	
		SET @atypeidLen=len(@Parid)+5	
		SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@ASQL+@SQLM_WHERE+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')
		SET @SQL=' 
			SELECT	a.atypeid as atypeid,
					isnull(SUM(
								CASE 
									WHEN A.BillType IN (4,189) THEN A.Total
									WHEN A.BillType = 190 THEN -1*A.Total
									WHEN A.BillType = 66 AND A.ATypeId = '+@YF_ID+' THEN A.Total
									WHEN A.BillType = 66 AND A.ATypeId <> '+@YF_ID+' THEN -1*A.Total
									ELSE A.Total
								END
							  ), 0) AS Total
	       	FROM  	'+@dbnameB+' a 
	       	INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
	       	INNER JOIN #AType AT ON AT.typeid = A.ATypeId  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
			WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +@Temp+' 			
			GROUP BY a.atypeid'
		
		IF @parid='00000'
			BEGIN
				--SET @ASQL=' AND a.typeid like ' + char(39) ++'%'+char(39)
				SET @SQL = 'SELECT 	a.ntypeid as typeid,
									a.usercode as usercode,
									a.fullname as fullname,
									a.sONnum as sONnum,
									a.parid as parid,
									a.leveal as leveal,
									isnull(sum(x.total),0) as Total
					   		FROM 	#AType a INNER Join ('+@SQL+') as x ON a.typeid=x.atypeid
						    WHERE 	1= 1 '+@ASQL+'
						    GROUP by a.ntypeid,a.usercode,a.fullname,a.sONnum,a.parid,a.leveal
							ORDER BY a.UserCode'
				
			END	
		ELSE
			BEGIN
				--SET @ASQL=' AND a.typeid like ' + char(39) ++'%'+char(39)
				SET @SQL = 'SELECT 	a.ntypeid as typeid,
									a.usercode as usercode,
									a.fullname as fullname,
									a.sONnum as sONnum,
									a.parid as parid,
									a.leveal as leveal,
									isnull(sum(x.total),0) as Total
				   			FROM 	#AType a Join ('+@SQL+') as x ON a.typeid=x.atypeid
				   			WHERE 	1= 1 '+@ASQL+@Temp+ '
									AND a.nTypeID LIKE '+char(39)+@parid+'%'+char(39)+'
				   			GROUP by a.ntypeid,a.usercode,a.fullname,a.sONnum,a.parid,a.leveal
							ORDER BY a.UserCode '
			END		
			PRINT(@sql)
		EXEC(@SQL)
		
		DROP TABLE #AType
		RETURN
	END
ELSE IF @vchtype=57 --调价单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid='00000'
		   SET @Parid =''
			 SET @SQL=' 
				SELECT	a.ptypeid,
			            abs( isnull(SUM(  a.qty), 0)) AS Qty,
						abs( isnull(SUM(a.CostTotal), 0)) AS Total		        	        
		     	FROM  	'+@dbnameB+' a 
				INNER join BillIndex b 	ON(a.BillnumberID=b.BillNumberID)		  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '	
				WHERE 	b.draft = 0 
						AND a.qty>=0 
						AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
				GROUP BY a.ptypeid'
		
			SET @SQL = 'SELECT 	p.typeid as typeid,
								p.usercode as usercode,
								p.fullname as fullname,
								p.sONnum as sONnum,
								p.parid as parid,
								p.leveal as leveal,
								isnull(x.qty,0) as qty,
								isnull(x.Total,0) as Total
				   		FROM 	Ptype p INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
				   		WHERE	p.TypeID LIKE '''+@Parid +'%''								
						order by p.sortid'		
		
		EXEC(@SQL)
		RETURN
	END
ELSE IF @vchtype=21 or @vchtype=17 	--变价调拨       同价调拨
	BEGIN 
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid='00000'
		   SET @Parid =''
			 SET @SQL=' 
				select a.ptypeid,sum(a.qty) as qty ,sum(a.cqty) as cqty ,sum(a.rqty) as rqty ,sum(a.ctotal) as ctotal ,sum(a.rtotal) as rtotal
				from(
				SELECT	a.ptypeid,
				        a.qty as qty,
						abs( isnull(SUM(CASE when  a.qty<0   then a.qty END),0))  as CQty,			
						abs( isnull(SUM(CASE when  a.qty>0   then a.qty END),0))  as RQty,
						abs( isnull(SUM(CASE when  a.CostTotal<0   then a.CostTotal END),0))  as CTotal,
						abs( isnull(SUM(CASE when  a.CostTotal>0   then a.CostTotal END),0))  as RTotal	        	        
				FROM  	'+@dbnameB+' a 
				INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)	  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '	
				WHERE b.draft = 0  AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'			
				GROUP BY
						a.ptypeid,a.qty
						) a  group by a.ptypeid '
		
			SET @SQL = '
				SELECT	p.typeid as typeid,
						p.usercode as usercode,
						p.fullname as fullname,
						p.sONnum as sONnum,
						p.parid as parid,
						p.leveal as leveal,
						isnull(x.Cqty,0) as Cqty,
						isnull(x.Rqty,0) as Rqty,
						isnull(x.CTotal,0) as CTotal,
						isnull(x.RTotal,0) as RTotal,
						dbo.F_RoundQty(x.qty/ue.Rate) as Mqty  ,
						pu.fullname as Munitfullname,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end as rateralation ,
						pu1.fullname as basefullname
				FROM 	Ptype p 
				left JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId
				INNER JOIN dbo.PType_Units_Ext ue on	 p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
				INNER JOIN dbo.PType_Units pu ON p.StockUnitId=  pu.UnitsId
		
				INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
				WHERE	p.TypeID LIKE '''+@Parid +'%''						
				ORDER BY p.sortid'
		
			--PRINT (@SQL)
			EXEC(@SQL)
			RETURN
	END
ELSE IF @vchtype=148 or @vchtype=150     --返利、获利
	BEGIN
		SET @SQL_WHERE = ''
		SET @SQL_WHERE = @SQL_WHERE +@SQLM_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@PSQL
		SELECT @dbNameB=@dbName
		IF @Parid='00000'
		   SET @Parid =''	
		 SET @SQL='SELECT	a.ptypeid,
							isnull(SUM(  a.qty),0) AS Qty,
							isnull(SUM(a.Total),0) AS Total        	        
		     		FROM  	Advantage a 
					INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND a.qty>0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY a.ptypeid'
		
		SET @SQL = 'SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.Total,0) as Total
			   		FROM 	Ptype p INNER join ('+@SQL+') as x ON  p.typeid=x.Ptypeid
			   		WHERE	p.TypeID LIKE '''+@Parid +'%''							
					ORDER BY p.sortid'
	
		EXEC(@SQL)
		RETURN
	END
ELSE 
IF @vchtype=149  or @vchtype =151--价保
	BEGIN
		SET @SQL_WHERE = ''
		SET @SQL_WHERE = @SQL_WHERE +@SQLM_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@PSQL
		SELECT @dbNameB=@dbName
						
		IF @Parid='00000'
			SET @Parid =''	

		SET @SQL=' 
				SELECT	a.ptypeid,
						isnull(SUM( a.qty),0) AS Qty,
						isnull(SUM(a.Total),0) AS Total	        	        
			    FROM  	PriceProtectBill a 
			    INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
				WHERE 	b.draft = 0  
						AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
				GROUP BY a.ptypeid'
		
		SET @SQL = 'SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.Total,0) as Total
			   		FROM 	Ptype p INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
			   		WHERE	p.TypeID LIKE '''+@Parid +'%''							
					ORDER BY p.sortid'
		
		--PRINT (@SQL)
		EXEC(@SQL)
		RETURN
	END
ELSE IF @VchType IN (166,172)	--维修单、上门维修单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid = '00000'
			SET @Parid =''
		SET @SQL=' 
			SELECT	a.ptypeid,
		            SUM(CASE WHEN a.InOrOut=''o'' THEN a.Qty ELSE 0 END) as CQty,				
					SUM(CASE WHEN a.InOrOut=''i'' THEN a.Qty ELSE 0 END) as RQty,	
					0  as CTotal,	
					0  as RTotal		        	        
			FROM  	'+@dbNameB+' a 
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
			WHERE 	b.draft = 0  
					AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'				
			GROUP BY a.ptypeid'
		
			SET @SQL = 'SELECT	p.typeid as typeid,
								p.usercode as usercode,
								p.fullname as fullname,
								p.sONnum as sONnum,
								p.parid as parid,
								p.leveal as leveal,
								isnull(x.Cqty,0) as Cqty,
								isnull(x.Rqty,0) as Rqty,
								isnull(x.CTotal,0) as CTotal,
								isnull(x.RTotal,0) as RTotal
						FROM 	PType p INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
						WHERE	p.TypeID LIKE '''+@Parid +'%''								
						ORDER BY p.sortid'	
		
			--PRINT (@SQL)
			EXEC(@SQL)
			RETURN
	END
ELSE IF @VchType = 168	--整机更换单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@KSQL,'A.KTypeID','B.KTypeID')+@SQLM_WHERE
	
		IF @Parid = '00000'
			SET @Parid =''

		SET @SQL='	SELECT	a.ptypeid,
					        abs(isnull(SUM(a.qty), 0)) AS Qty,
							0 AS Total				        	       
		 			FROM  	Wx_Bill_Replace a 
		 			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY a.ptypeid'
		
		SET @SQL = 'SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.total,0) as Total							
		   			FROM 	Ptype p join ('+@SQL+') as x ON p.typeid=x.Ptypeid 
					WHERE	p.TypeID LIKE '''+@Parid +'%''							
					order by p.sortid'
		--PRINT @SQL
		EXEC(@SQL)		
		RETURN		
	END
ELSE IF @VchType IN (173,174,175) --维修品调入单、维修品调出单、维修品调拨单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid = '00000'
			SET @Parid =''

		SET @SQL=' 
			SELECT	a.ptypeid,
		            abs(isnull(SUM(a.Qty),0)) as CQty,				
					abs(isnull(SUM(a.Qty),0)) as RQty,	
					0 as CTotal,	
					0 as RTotal		        	        
			FROM  	'+@dbNameB+' a 
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
			WHERE 	b.draft = 0  
					AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'				
			GROUP BY a.ptypeid'
	
		SET @SQL = 'SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.Cqty,0) as Cqty,
							isnull(x.Rqty,0) as Rqty,
							isnull(x.CTotal,0) as CTotal,
							isnull(x.RTotal,0) as RTotal
					FROM 	PType p INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
					WHERE	p.TypeID LIKE '''+@Parid +'%''							
					ORDER BY p.sortid'	
	
		--PRINT (@SQL)
		EXEC(@SQL)
		RETURN	
	END
ELSE IF @VchType = 171	--报修单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@SQLM_WHERE
	
		IF @Parid = '00000'
			SET @Parid =''

		SET @SQL='	SELECT	a.ptypeid,
					        abs(isnull(SUM(a.qty), 0)) AS Qty,
							0 AS Total				        	       
		 			FROM  	Wx_Bill_Call a 
		 			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY a.ptypeid'
		
		SET @SQL = 'SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.total,0) as Total							
		   			FROM 	Ptype p join ('+@SQL+') as x ON p.typeid=x.Ptypeid 
					WHERE	p.TypeID LIKE '''+@Parid +'%''							
					order by p.sortid'
		--PRINT @SQL
		EXEC(@SQL)		
		RETURN		
	END
ELSE IF @VchType IN (9,14,201,202)
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		IF @VchType IN (9,14)		
			SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		ELSE
			SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@KSQL+@SQLM_WHERE
	
		IF @Parid = '00000'
			SET @Parid =''

		SET @SQL='	SELECT	a.ptypeid,
					        abs(isnull(SUM(a.qty), 0)) AS Qty,
							abs(isnull(SUM(a.CostTotal), 0)) AS Total				        	       
		     		FROM  	InOutStockTable a 
		     		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY a.ptypeid'
		
		SET @SQL = 'SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.total,0) as Total,
							dbo.F_RoundQty(x.qty/ue.Rate) as Mqty  ,
							pu.fullname as Munitfullname,
							dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname as rateralation,
			   				pu1.fullname as basefullname					
		   			FROM 	Ptype p 
		   			left JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId
					INNER JOIN dbo.PType_Units_Ext ue on	 p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN dbo.PType_Units pu ON p.StockUnitId=  pu.UnitsId
		   			inner join ('+@SQL+') as x ON p.typeid=x.Ptypeid 
					WHERE	p.TypeID LIKE '''+@Parid +'%''							
					order by p.sortid'
		--PRINT @SQL
		EXEC(@SQL)	
		RETURN		
	END
ELSE IF @vchType = 16  --生产拆装单
	BEGIN 
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid='00000'
	  	SET @Parid =''
		SET @SQL=' 
			SELECT	a.ptypeid,
					abs( isnull(SUM(CASE when  a.qty<0   then a.qty END),0))  as CQty,			
					abs( isnull(SUM(CASE when  a.qty>0   then a.qty END),0))  as RQty,
					abs( isnull(SUM(CASE when  a.CostTotal<0   then a.CostTotal END),0))  as CTotal,
					abs( isnull(SUM(CASE when  a.CostTotal>0   then a.CostTotal END),0))  as RTotal	        	        
			FROM  	(
						SELECT	A.BillNumberId,
								A.Billdate,
								A.PTypeId,
								A.Qty,
								A.Total,
								A.CostTotal
						FROM	'+@dbnameB+' A
						WHERE	A.Audited = 1
								AND A.BillType = 16
								AND A.Qty < 0
								'+@Ksql1+'
						UNION ALL
						SELECT	A.BillNumberId,
								A.Billdate,
								A.PTypeId,
								A.Qty,
								A.Total,
								A.CostTotal
						FROM	'+@dbnameB+' A
						WHERE	A.Audited = 1
								AND A.BillType = 16
								AND A.Qty > 0
								'+@Ksql2+'
					) a INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)	  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '	
			WHERE b.draft = 0  AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'			
			GROUP BY
					a.ptypeid'
	
		SET @SQL = '
			SELECT	p.typeid as typeid,
					p.usercode as usercode,
					p.fullname as fullname,
					p.sONnum as sONnum,
					p.parid as parid,
					p.leveal as leveal,
					isnull(x.Cqty,0) as Cqty,
					isnull(x.Rqty,0) as Rqty,
					isnull(x.CTotal,0) as CTotal,
					isnull(x.RTotal,0) as RTotal
			FROM 	Ptype p INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
			WHERE	p.TypeID LIKE '''+@Parid +'%''					
			ORDER BY p.sortid'
	
		--PRINT (@SQL)
		EXEC(@SQL)
		RETURN
	END
ELSE IF @vchType = 161 --采购换货单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@KSQL+@SQLM_WHERE
		IF @Parid='00000'
		SET @Parid =''
		
		SET @SQL=' 
			SELECT	a.ptypeid,
					abs( isnull(SUM(CASE when  a.qty<0   then a.qty END),0))  as CQty,			
					abs( isnull(SUM(CASE when  a.qty>0   then a.qty END),0))  as RQty,
					abs( isnull(SUM(CASE when  a.Total<0   then a.Total END),0))  as CTotal,
					abs( isnull(SUM(CASE when  a.CostTotal>0   then a.CostTotal END),0))  as RTotal	        	        
			FROM  	(
					SELECT	A.BillNumberId,
							A.Billdate,
							A.PTypeId,
							A.Qty,
							A.Total,
							A.CostTotal
					FROM	'+@dbnameB+' A
					WHERE	A.Audited = 1
							AND A.BillType = 161
							AND A.Qty < 0
							'+@Ksql1+'
					UNION ALL
					SELECT	A.BillNumberId,
							A.Billdate,
							A.PTypeId,
							A.Qty,
							A.Total,
							A.CostTotal
					FROM	'+@dbnameB+' A
					WHERE	A.Audited = 1
							AND A.BillType = 161
							AND A.Qty > 0
							'+@Ksql2+'
					) a INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)	  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '		
			WHERE b.draft = 0  AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'			
			GROUP BY
					a.ptypeid'
	
		SET @SQL = '
			SELECT	p.typeid as typeid,
					p.usercode as usercode,
					p.fullname as fullname,
					p.sONnum as sONnum,
					p.parid as parid,
					p.leveal as leveal,
					isnull(x.Cqty,0) as Cqty,
					isnull(x.Rqty,0) as Rqty,
					isnull(x.CTotal,0) as CTotal,
					isnull(x.RTotal,0) as RTotal,
					dbo.F_RoundQty(x.cqty/ue.Rate) as Mqty  ,
					pu.fullname as Munitfullname,
					dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname AS rateralation,
					pu1.fullname as basefullname
			FROM 	Ptype p 
				   	INNER JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId
			    
					INNER JOIN dbo.PType_Units_Ext ue on	 p.BuyUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN dbo.PType_Units pu ON p.BuyUnitId=  pu.UnitsId
			
			INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
			WHERE	p.TypeID LIKE '''+@Parid +'%''					
			ORDER BY p.sortid'
	
		--PRINT (@SQL)
		EXEC(@SQL)
		RETURN
	END
ELSE IF @vchType = 160
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@KSQL+@SQLM_WHERE
		IF @Parid='00000'
	    SET @Parid =''
		
		SET @SQL=' 
			SELECT	a.ptypeid,
					abs( isnull(SUM(CASE when  a.qty<0   then a.qty END),0))  as CQty,			
					abs( isnull(SUM(CASE when  a.qty>0   then a.qty END),0))  as RQty,
					abs( isnull(SUM(CASE when  a.qty<0   then a.Total END),0))  as CTotal,
					abs( isnull(SUM(CASE when  a.qty>0   then a.Total END),0))  as RTotal	        	        
			FROM  	(
					SELECT	A.BillNumberId,
							A.Billdate,
							A.PTypeId,
							A.Qty,
							A.Total,
							A.CostTotal
					FROM	'+@dbnameB+' A
					WHERE	A.Audited = 1
							AND A.BillType = 160
							AND A.Qty < 0
							'+@Ksql2+'
					UNION ALL
					SELECT	A.BillNumberId,
							A.Billdate,
							A.PTypeId,
							A.Qty,
							A.Total,
							A.CostTotal
					FROM	'+@dbnameB+' A
					WHERE	A.Audited = 1
							AND A.BillType = 160
							AND A.Qty > 0
							'+@Ksql1+'
					) a 
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)		  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
			WHERE b.draft = 0  AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'			
			GROUP BY
					a.ptypeid'
	
		SET @SQL = '
			SELECT	p.typeid as typeid,
					p.usercode as usercode,
					p.fullname as fullname,
					p.sONnum as sONnum,
					p.parid as parid,
					p.leveal as leveal,
					isnull(x.Cqty,0) as Cqty,
					isnull(x.Rqty,0) as Rqty,
					isnull(x.CTotal,0) as CTotal,
					isnull(x.RTotal,0) as RTotal ,
					dbo.F_RoundQty(x.cqty/ue.Rate) as Mqty  ,
					pu.fullname as Munitfullname,
					dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  AS rateralation,
					pu1.fullname as basefullname
			FROM 	Ptype p 
				left JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId
			    
					INNER JOIN dbo.PType_Units_Ext ue on	 p.SaleUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN dbo.PType_Units pu ON p.SaleUnitId=  pu.UnitsId
			INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
			WHERE	p.TypeID LIKE '''+@Parid +'%''					
			ORDER BY p.sortid'
	
		--PRINT (@SQL)
		EXEC(@SQL)
		RETURN
	END
ELSE IF @VchType IN (187,188)
	BEGIN 
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid='00000'
		   SET @Parid =''
		   
		 SET @SQL=' 
			SELECT	a.ptypeid,
					abs( isnull(SUM(a.Qty),0))  as Qty,			
					abs( isnull(SUM(a.Total),0))  as Total
			FROM  	'+@dbnameB+' a 
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)	  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '	
				WHERE b.draft = 0  AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'			
				GROUP BY
						a.ptypeid'
		
			SET @SQL = '
				SELECT	p.typeid as typeid,
						p.usercode as usercode,
						p.fullname as fullname,
						p.sONnum as sONnum,
						p.parid as parid,
						p.leveal as leveal,
						isnull(x.qty,0) as qty,
						isnull(x.Total,0) as Total   ,
						dbo.F_RoundQty(x.qty/ue.Rate) as Mqty  ,
						pu.fullname as Munitfullname,
						dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname AS rateralation,
						pu1.fullname as basefullname 
				FROM 	Ptype p 
				INNER JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId
			    
					INNER JOIN dbo.PType_Units_Ext ue on	 p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN dbo.PType_Units pu ON p.StockUnitId=  pu.UnitsId
				INNER join ('+@SQL+') as x ON p.typeid=x.Ptypeid
				WHERE	p.TypeID LIKE '''+@Parid +'%''						
				ORDER BY p.sortid'
		
			--PRINT (@SQL)
			EXEC(@SQL)
			RETURN
	END	
ELSE IF @VchType IN (191,197,196)	--领料出库单、领料退回单、救援单
	BEGIN
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@KSQL+@SQLM_WHERE
	
		IF @Parid='00000'
		   SET @Parid =''

		 SET @SQL='SELECT	a.ptypeid,
				            abs(isnull(SUM(a.qty), 0)) AS Qty,
				            CAST(CASE WHEN isnull(SUM(a.qty), 0)=0 THEN 0 ELSE ISNULL((isnull(SUM(a.Total),0)/abs(isnull(SUM(a.qty), 0))),0) END AS Money) AS Price,
							abs(isnull(SUM(a.Total), 0)) AS Total,				        	       
							abs(isnull(SUM(a.TaxTotal), 0)) AS TaxTotal
		     		FROM	'+@dbnameB+' a 
		     		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY a.ptypeid'
	
		SET @SQL = 'SELECT  p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.price,0) as price,
							isnull(x.total,0) as Total,
							isnull(x.TaxTotal,0) as TaxTotal						
			   		FROM 	Ptype p join ('+@SQL+') as x ON p.typeid=x.Ptypeid
			   		WHERE	p.TypeID LIKE '''+@Parid +'%''							
					order by p.sortid'

		--PRINT @SQL
		EXEC(@SQL)	

		RETURN		
	END		

DROP TABLE #Stock1,#Stock2,#GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManSTypeId,#GetManDTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryAllBillExList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryAllBillExList]
GO


/*
	作者：谢吉康
	日期：2007-3-21
	描述：单据统计的处理
*/
CREATE	PROCEDURE Gp_QueryAllBillExList
(    
	@chvOperatorID  	VARCHAR(100),     -------操作员ID号
	@VchType 			NUMERIC(4,0),  
	@BeginDate 			VARCHAR(30),
	@EndDate 			VARCHAR(30),	
	@Parid    			VARCHAR(50),
	@chvBtypeName 		VARCHAR(MAX)='',
	@chvEtypeName 		VARCHAR(MAX)='',
	@chvKtypeName 		VARCHAR(MAX)='',
	@IFCheck 			CHAR(1)='t',             
	@BillCode       	VARCHAR(200)='',
	@Comment        	VARCHAR(256)='', 
	@chvKtypeName2 		VARCHAR(MAX)='',
	@STypeId			VARCHAR(MAX),		--分支机构
	@ifAssets			VARCHAR(10)			--资产管理模式："0"：非总账模式(项目管理)，="1"：总账模式(卡片管理)
)
--@encode$--
AS
SET nocount ON
SET ANSI_WARNINGS  off

DECLARE @cz_Dx varchar(50),@DbName  varchar(30)
DECLARE @SQL varchar (MAX)
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID is null RETURN -1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re		

DECLARE @ASQL varchar(MAX)
DECLARE @BSQL varchar(MAX)
DECLARE @PSQL varchar(MAX)
DECLARE @ESQL varchar(MAX)
DECLARE @KSQL varchar(MAX)
DECLARE @SQLM_WHERE varchar(MAX)

SET @ASQL=''
SET @BSQL=''
SET @PSQL=''
SET @ESQL=''
SET @KSQL=''
SET @SQLM_WHERE=''

--================================================= 定义通用条件 BEGIN

DECLARE @CurSONNum int       --检测当前的SONNum 
DECLARE @BtypeAll int
SELECT @BtypeAll=value FROM UserConfig WHERE CONfigName='BtypeAll'
		
DECLARE @PTypeID   varchar(100)
DECLARE @SQL_WHERE varchar(MAX)
DECLARE @SQL_Group varchar(MAX)
SET @PTypeID = @parid

SELECT @SQL_WHERE = ''

-----------------------------------------------判断商品的范围
--商品
CREATE TABLE #PTYPE(Typeid varchar(100))
INSERT INTO #PTYPE(Typeid)	SELECT TypeId  FROM F_GetManDetailPType(@chvOperatorID)
IF @Ptypeid <> '00000'
	SET @PSQL = @PSQL + ' AND a.PTypeID Like '+char(39)+@PtypeID+'%'+char(39)

IF @MPTypeId = '-99999'
	SET @PSQL = @PSQL +' AND a.PtypeID IN (SELECT * FROM #PTYPE)'

-----------------------------------------------判断客户的范围
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF NOT (@chvBtypeName='' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	BEGIN
		INSERT INTO #GetManBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvBtypeName,2,@chvOperatorID) S
		IF @VchType IN (191,197) AND @chvBtypeName = ''
		BEGIN
			INSERT INTO #GetManBTypeId(TypeId)VALUES('')
		END
		SET @BSQL = @BSQL +' AND M.TypeId IN (SELECT * FROM #GetManBTypeId)'
	END
-----------------------------------------------判断职员的范围
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF NOT (@chvEtypeName='' AND @METypeId = '00001')
	BEGIN
		INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvEtypeName,3,@chvOperatorID) S
		SET @ESQL = @ESQL +' AND E.TypeId IN (SELECT * FROM #GetManETypeId)'
	END
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperatorID)		
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)	

--仓库信息必须单独处理
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@chvOperatorID)

CREATE TABLE #Stock1(TypeId	varchar(100))
CREATE TABLE #Stock2(TypeId	varchar(100))

DECLARE @TypeId	varchar(100),
		@SonNum	int

IF @VchType = 17 OR @VchType = 21
	BEGIN
		IF EXISTS(SELECT Value FROM UserConfig WHERE ConfigName ='MoveInOutKLimit' AND Value='1') -- 调拔单中仓库权限有效
			BEGIN
				--出库仓库
				INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName,4,@chvOperatorID) S
		
				--入库仓库
				INSERT INTO #Stock2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName2,4,@chvOperatorID) S

				--组织查询条件				
				SET @KSQL = @KSQL + ' AND (B.KTypeId IN (SELECT TypeId FROM #Stock1) AND B.KTypeId2 IN (SELECT TypeId FROM #Stock2))'
			END
		ELSE
			BEGIN
				--出库仓库
				INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName,4,'00001') S
		
				--入库仓库
				INSERT INTO #Stock2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName2,4,'00001') S

				--组织查询条件
				SET @KSQL = @KSQL + ' AND (B.KTypeId IN (SELECT TypeId FROM #Stock1) OR B.KTypeId2 IN (SELECT TypeId FROM #Stock2))'
			END
	END
ELSE IF @VchType = 16 OR @VchType = 160 OR @VchType = 161 OR @VchType = 166 OR @VchType = 172 OR @VchType = 173  OR @VchType = 174  OR @VchType = 175
	BEGIN
		IF @VchType = 160
			BEGIN
				--出库仓库		
				INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName2,4,@chvOperatorID) S
				--入库仓库
				INSERT INTO #Stock2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName,4,@chvOperatorID) S
			END
		ELSE
			BEGIN
				--出库仓库		
				INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName,4,@chvOperatorID) S
				--入库仓库
				INSERT INTO #Stock2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeName2,4,@chvOperatorID) S
			END

		--组织查询条件
		IF @VchType IN (166,172)
			BEGIN
				SET @KSQL = @KSQL + ' AND ('
				IF @chvKtypeName = '' AND @chvKtypeName2 = ''
					BEGIN
						SET @KSQL = @KSQL +' (B.KTypeId IN (SELECT * FROM #GetManKTypeId) OR B.KTypeId2 IN (SELECT * FROM #GetManKTypeId))'
						SET @KSQL = @KSQL +' OR (B.KTypeId IN (SELECT * FROM #GetManKTypeId) AND B.KTypeId2='''')'
						SET @KSQL = @KSQL +' OR (B.KTypeId='''' AND B.KTypeId2 IN (SELECT * FROM #GetManKTypeId))'
						SET @KSQL = @KSQL +' OR (B.KTypeId='''' AND B.KTypeId2='''')'
					END
				ELSE IF @chvKtypeName = '' AND @chvKtypeName2 <> ''
					BEGIN
						SET @KSQL = @KSQL + ' ( B.KTypeId IN (SELECT * FROM #GetManKTypeId UNION SELECT '''')) AND (B.KTypeId2 IN (SELECT * FROM #Stock2))'
					END
				ELSE IF @chvKtypeName <> '' AND @chvKtypeName2 = ''
					BEGIN
						SET @KSQL = @KSQL + ' ((B.KTypeId IN (SELECT * FROM #Stock1)) AND  B.KTypeId2 IN (SELECT * FROM #GetManKTypeId UNION SELECT '''') )'
					END
				ELSE
					BEGIN
						SET @KSQL = @KSQL + ' (B.KTypeId IN (SELECT * FROM #Stock1) AND B.KTypeId2 IN (SELECT * FROM #Stock2))'
					END
				SET @KSQL = @KSQL + ' )'
			END
		ELSE IF @VchType IN (16,160,161)
			BEGIN
				DECLARE @Ksql1	VARCHAR(MAX),
						@Ksql2	VARCHAR(MAX)

				SET @Ksql1 = ' AND 1 = 1 '
				SET @Ksql2 = ' AND 1 = 1 '				

				IF @chvKtypeName = '' AND @chvKtypeName2 = ''
					BEGIN
						IF @MKTypeId = '-99999'
							BEGIN
								SET @Ksql1 = ' AND A.KTypeId IN (SELECT * FROM #GetManKTypeId)'
								SET @Ksql2 = ' AND A.KTypeId IN (SELECT * FROM #GetManKTypeId)'
							END
					END
				ELSE
					BEGIN
						SET @Ksql1 = ' AND A.KTypeId IN (SELECT TypeId FROM #Stock1) '
						SET @Ksql2 = ' AND A.KTypeId IN (SELECT * FROM #Stock2) '
					END
			END
		ELSE IF @VchType IN (173,174,175)
			BEGIN
				IF @chvKtypeName = '' AND @chvKtypeName2 = ''
					BEGIN
						IF @MKTypeId = '-99999'
							SET @KSQL = @KSQL + ' AND ((B.KTypeId IN (SELECT * FROM #GetManKTypeId)) OR (B.KTypeId2 IN (SELECT * FROM #GetManKTypeId)))'
					END
				ELSE
					BEGIN
						IF @chvKtypeName <> '' AND @chvKtypeName2 = ''
							SET @KSQL = @KSQL + ' AND B.KTypeId IN (SELECT TypeId FROM #Stock1) AND B.KTypeId2 IN (SELECT * FROM #GetManKTypeId) '
						ELSE
							SET @KSQL = @KSQL + ' AND B.KTypeId IN (SELECT * FROM #Stock1) AND B.KTypeId2 IN (SELECT TypeId FROM #Stock2)'								
					END
			END
	END
ELSE
	BEGIN
		INSERT INTO #Stock1(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@chvKTypeName,4) S,F_GetManDetailKType(@chvOperatorID) M WHERE S.TypeId = M.TypeId
		--组织查询条件
		IF @vchType = 57
			BEGIN
				IF @chvKtypeName = ''		
					BEGIN
						IF @MKTypeId = '00000'
							SET @KSQL = @KSQL + ' AND A.KTypeID IN (SELECT TypeId FROM #Stock1 UNION SELECT ''00000'') '
						ELSE
							SET @KSQL = @KSQL + ' AND (A.KTypeID IN (SELECT TypeId FROM #Stock1)) '
					END
				ELSE
					SET @KSQL = @KSQL + ' AND A.KTypeID IN (SELECT TypeId FROM #Stock1)'
			END
		ELSE
			BEGIN
				IF @chvKtypeName <> ''		
					SET @KSQL = @KSQL + ' AND A.KTypeID IN (SELECT TypeId FROM #Stock1)'
				ELSE
					IF @MKTypeId = '-99999'
						SET @KSQL = @KSQL + ' AND  A.KTypeId IN (SELECT TypeId FROM #Stock1 UNION SELECT ''10000'') '
			END
	END

--===================================================================日期
IF  @VchType in(11,45,215,34,6,9,14,17,21,16,57,126,139,140,142,143,144,146,147,160,161,178,187,188,191,196,197,201,202,305,12,46) 
	OR @VchType in(4,66,115,116,128,129,36,93,77,84,85,78,5,10,141,145,158,159,189,190) 
	OR @VchType IN (165,167,169,170)
	--发票立账相关单据
	OR @VchType IN (400,401,402,403)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND a.billdate>='+char(39)+@BeginDate+char(39)+' AND a.billdate<='+char(39)+@EndDate+char(39)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.billdate>='+char(39)+@BeginDate+char(39)+' AND b.billdate<='+char(39)+@EndDate+char(39)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.BillCode like '+ char(39)+'%'+@BillCode+'%'+char(39)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.Comment like '+ char(39)+'%'+@Comment+'%'+char(39)
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.IFCheck ='+ char(39)+ 't'+ char(39) 
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.RedWord ='+ char(39)+ '0'+ char(39) 
SET @SQLM_WHERE = @SQLM_WHERE + ' AND b.IfYearBill = 0 '
--================================================= 定义通用条件 END

-------------------------------------------------------------------------------------------------------------------------------
IF  @VchType in(11,45,215,34,6,9,14,17,21,16,57,126,139,305,140,142,143,144,146,147,160,161,178,187,188,191,196,197,201,202,400,401,402,403,12,46) 
	SET @DbName = 'InOutstocktable' 
ELSE IF @VchType in(4,66,115,116,128,129,36,93,77,84,85,78,5,10,141,145,148,149,150,151,158,159,189,190,450) 
	SET @DbName = 'listtable'
ELSE IF @VchType IN (165,167,168,169,170,171)
	SET @DbName = 'Wx_InOutStockTable'
ELSE IF @VchType = 166
	SET @DbName = 'Wx_Bill_Self'
ELSE IF @VchType = 172
	SET @DbName = 'Wx_Bill_GoTo'
ELSE IF @VchType = 173
	SET @DbName = 'Wx_Bill_In'
ELSE IF @VchType = 174
	SET @DbName = 'Wx_Bill_Out'
ELSE IF @VchType = 175
	SET @DbName = 'Wx_Bill_Move'
ELSE
	RETURN -1
-------------------------------------------------------------------------------------------------------------------------------

DECLARE @BtypeIDLen int
DECLARE @PtypeidLen int
DECLARE @AtypeidLen int

DECLARE @dbNameB varchar(120) --(由于单据统计中的合计不正确，加上权限范围限制,2002-12-2吴德水加)
SELECT @dbNameB='SELECT * FROM '+@dbName+' WHERE EtypeId IN (SELECT * FROM F_GetManDetailEType('+char(39)+@chvOperatorID+char(39)+'))'

DECLARE @TempTable VARCHAR(100)
SELECT @TempTable='#Temp'+REPLACE(NEWID(),'-','')

IF @VchType IN (6,11,34,45,215,305,140,142,144,146,178,400,401,402,403,139,126,12,46)
BEGIN
	SELECT @dbNameB=@dbName
	IF @vchtype=140  or @vchtype=142 or @vchtype=144 or @vchtype=146
		BEGIN
			SET @KSQL = @KSQL + 'AND a.ktypeid<>'+char(39)+'10000'+char(39)
		END
	SET @SQL_WHERE = @SQL_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE

	IF @Parid = '00000'
		SET @PtypeidLen=5
	ELSE
		SET @PtypeidLen=len(@Parid)+5	

	 SET @SQL=' 
			SELECT  a.ptypeid,
					abs( isnull(SUM(  a.qty), 0)) AS Qty,
					abs( isnull(SUM(a.Total), 0)) AS Total,
					--CASE when  isnull(SUM( a.qty), 0)=0 then 0 ELSE ISNULL((isnull(CAST(SUM(a.Total) AS NUMERIC(24,10)),0)/abs(isnull(cast(SUM(a.qty) AS NUMERIC(24,10)), 0))),0) END  AS Price,
					--CASE when  isnull(SUM( a.qty), 0)=0 then 0 ELSE ISNULL((isnull(CAST(SUM(a.Total) AS NUMERIC(24,10)),0)/isnull(CAST(SUM(a.qty) AS NUMERIC(24,10)), 0)),0) END  AS Price2,
					isnull(sum(a.TaxTotal),0) AS TaxTotal,
					abs(sum(dbo.F_RoundQty(a.qty/ue.Rate))) as Mqty
		    INTO '+@TempTable+'
			FROM  '+@dbnameB+' A
			INNER JOIN dbo.ptype p ON a.PtypeId=p.typeId
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
		    INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid '
		   IF @vchtype IN(305,11,215,45,402,403,140,142,139,12,46)
			SET @SQL =@SQL+ ' 
					INNER JOIN dbo.PType_Units_Ext ue on	 p.SaleUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
			'	
			ELSE
					SET @SQL =@SQL+ ' 
							INNER JOIN dbo.PType_Units_Ext ue on	 p.BuyUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
							
					'	
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
			
			SET @SQL = @SQL + '
				WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE 
				
			SET @SQL = @SQL + '  GROUP BY a.ptypeid '

	SET @SQL =@SQL+ '
				SELECT	p.typeid,										    
						p.usercode,
						p.fullname,
						p.sONnum,
						p.parid,
						p.leveal,
						p.sortid,
						sum(isnull(x.qty,0)) as qty,
						sum(isnull(x.total,0)) as Total,
						CASE when  isnull(SUM( x.qty), 0)=0 then 0 ELSE ISNULL((isnull(CAST(SUM(x.Total) AS NUMERIC(24,10)),0)/abs(isnull(cast(SUM(x.qty) AS NUMERIC(24,10)), 0))),0) END  AS Price,
						CASE when  isnull(SUM( x.qty), 0)=0 then 0 ELSE ISNULL((isnull(CAST(SUM(x.Total) AS NUMERIC(24,10)),0)/isnull(CAST(SUM(x.qty) AS NUMERIC(24,10)), 0)),0) END  AS Price2,
						sum(isnull(x.TaxTotal,0)) as TaxTotal,
						case when p.sonnum=0 then pu.fullname else '''' end as Munitfullname ,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end as rateralation ,
						sum(x.Mqty) as Mqty,
						case when p.sonnum=0 THEN pu1.fullname ELSE '''' END as basefullname
				FROM 	Ptype p
				INNER JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId 	 
				'
	  IF @vchtype IN(305,11,215,45,402,403,140,142,139,12,46)
			SET @SQL =@SQL+ ' 
					INNER JOIN dbo.PType_Units_Ext ue on	 p.SaleUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN dbo.PType_Units pu ON p.SaleUnitId=  pu.UnitsId
			'	
			ELSE
					SET @SQL =@SQL+ ' 
							INNER JOIN dbo.PType_Units_Ext ue on	 p.BuyUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
							INNER JOIN dbo.PType_Units pu ON p.BuyUnitId=  pu.UnitsId
					'							
	SET @SQL =@SQL+ ' inner join '
				+@TempTable+' x ON   x.Ptypeid  like p.typeid+''%'' 
		   		WHERE	p.parid='''+@Parid +''''+' 
		   		group by  	
		   				p.typeid,
						p.usercode,
						p.fullname,
						p.sONnum,
						p.parid,
						p.leveal,
						p.sortid,
						pu1.fullname,
						case when p.sonnum=0 then pu.fullname else '''' end,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end 
						
		   		order by p.sortid'
	--PRINT(@SQL)
	EXEC(@SQL)
END      
ELSE IF @VchType = 165 Or @VchType = 167 Or @VchType = 169 Or @VchType = 170
	BEGIN
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
	
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		 SET @SQL='SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
				            abs( isnull(SUM(a.qty), 0)) AS Qty,
							abs( isnull(SUM(a.CostTotal), 0)) AS Total
					INTO '+@TempTable+'				        	       
		     		FROM  '+@dbnameB+' a 
		     		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)  
		     		INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid  '
		
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
	
		SET @SQL = @sql + ' 
					SELECT  p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							0 as mqty,
							isnull(x.total,0) as Total							
	   				FROM 	Ptype p join '
	   				+@TempTable+' x ON p.typeid=x.Ptypeid
	   				WHERE	p.parid='''+@Parid +'''
					order by p.sortid'

		--PRINT @SQL
		EXEC(@SQL)		
		--RETURN		
	END
ELSE IF @vchtype=115 or @vchtype=116 or @vchtype=128 or @vchtype=129 
--应收款减少      应收款增加，     应付款增加       应付款减少
BEGIN
	CREATE TABLE #Btype(typeid varchar(100),
							parid varchar(100),
							UserCode VARCHAR(200),
							FullName VARCHAR(200),
							sonnum int,
							leveal	int
							)
	INSERT INTO #BType SELECT typeId,parid,UserCode,FullName,sonnum,leveal FROM F_GetManBType(@chvOperatorID)
	SELECT @dbNameB=@dbName
	IF @Parid<>'00000'
		SET @BSQL=' AND a.Btypeid like ' + char(39) +@Parid+'%'+char(39)

	SET @BSQL = @BSQL
	
	SET @BtypeIDLen=len(@Parid)+5	
	SET @SQL_WHERE = @SQL_WHERE +REPLACE(@ESQL,'E.TypeId','B.ETypeId') +REPLACE(@BSQL,'M.TypeId','A.BTypeId')+@SQLM_WHERE
	SET @SQL='SELECT	substring(a.btypeid,1,'+cast(@BtypeIDLen as varchar)+') as btypeid,
	            		(isnull(SUM(abs(isnull(a.Total,0))), 0)) AS Total
	          INTO '+@TempTable+'	 		
        	  FROM  '+@dbnameB+' a 
        	  INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
        	  INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid '
		
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
			
			SET @SQL = @SQL + '		
			  WHERE 	b.draft = 0 
						AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
			  GROUP BY 	substring(a.btypeid,1,'+cast(@BtypeIDLen as varchar)+')'

	SET @SQL = @sql + '
			  SELECT	b.typeid as typeid,
						b.usercode as usercode,
						b.fullname as fullname,
						b.sONnum as sONnum,
						b.parid as parid,
						b.leveal as leveal,
						(isnull(x.total,0)) as Total
			  FROM 		#Btype  b Join '
			  +@TempTable+' x ON b.typeid=x.btypeid
			  WHERE 	'
	IF @parid='00000'
		SET @SQL = @SQL + '
			(b.Parid='+char(39)+'00001'+char(39)+' OR b.Parid='+char(39)+'00002'+char(39)+') 
			order by b.usercode'
	ELSE
		SET @SQL = @SQL + '
			b.Parid='+char(39)+@parid+char(39)+'
			order by b.usercode'		
	
	--PRINT @SQL	
	EXEC(@SQL)
	DROP TABLE #Btype
	--RETURN
END 
ELSE IF  @vchtype=36 or @vchtype=93 or @vchtype=84 or @vchtype=85 or @vchtype=78 or @vchtype=5 or @vchtype=10  or @vchtype=77 
--or @vchtype=158   9.5 BUG 745，由于现金费用单需要统计表体经手人，所以拆分开单独查询
BEGIN
	--费用，其他收入 --转款   固定资产购买   (、  固定资产变卖、固定资产折旧、待摊费用发生、摊销为吴德水2002-10-30日添加)
	
	CREATE TABLE #AtypeFy(typeid varchar(100))
	INSERT INTO #AtypeFy SELECT nid FROM F_GetManDetailATypeFy(@chvOperatorID)
	CREATE TABLE #AtypeSr(typeid varchar(100))
	INSERT INTO #AtypeSr SELECT nid FROM F_GetManDetailATypeSr(@chvOperatorID)
	CREATE TABLE #AtypeZc(typeid varchar(100))
	INSERT INTO #AtypeZc SELECT nid FROM F_GetManDetailATypeZc(@chvOperatorID)
	
	SELECT @dbNameB=@dbName
	PRINT @dbNameB
	SET @SQL_WHERE = ''
	IF @Parid='root' 
		SET @Parid='00000'
	
	
	IF  @vchtype=84 or @vchtype=85 
		SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeZc)'
	IF @vchtype =78
		SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeFy) '
	IF @vchtype =36
		SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeFy)'
	--IF @vchtype =158
	--	SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeFy)'
	IF @vchtype =93
		SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeSr)'
	
	IF @Parid='00000' or @parid=''''
		SET @atypeidLen =5
	ELSE
		SET @atypeidLen=len(@Parid)+5	
	IF @vchtype=93 or @vchtype=84 or @vchtype=85 or @vchtype=36 
		SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@ASQL+@SQLM_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')
	ELSE
		SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@ASQL+@SQLM_WHERE
	SET @SQL=' 
		SELECT	substring(ac.ntypeid,1,'+cast(@atypeidLen as VARCHAR)+') as atypeid,
		        abs( isnull(SUM(a.Total), 0)) AS Total
		INTO '+@TempTable+'
		FROM  '+@dbnameB+' a 
		inner join ac_items ac on a.atypeid=ac.nid
		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
		INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid  '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		

	SET @SQL=@SQL +	'
		WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
		GROUP BY substring(ac.ntypeid,1,'+cast(@atypeidLen as VARCHAR)+')'

	SET @SQL = @SQL + '
		SELECT	a.nTypeId as typeid,
				a.usercode as usercode,
				a.fullname as fullname,
				a.sONnum as sONnum,
				a.parid as parid,
				a.leveal as leveal,
				abs(isnull(x.total,0)) as Total
		FROM 	ac_items a Join '
		+@TempTable+' x ON a.ntypeid=x.atypeid
		WHERE A.nid not in(29,36,1)	and a.IsBank<>1  AND a.nParid='+CHAR(39)+@parid+CHAR(39)+''
IF @Parid='00001'
	set @SQL=@sql+' AND a.typeName in(''B'',''C'',''F'') '
SET @SQL=@SQL+' ORDER by a.usercode '

	--PRINT @SQL								
	EXEC(@SQL)
	DROP TABLE #AtypeFy,#AtypeSr,#AtypeZc
	--RETURN  
END
ELSE IF	 @vchtype=158 -- 现金费用单
BEGIN
	CREATE TABLE #AtypeFy1(typeid varchar(100))
	INSERT INTO #AtypeFy1 SELECT nid FROM F_GetManDetailATypeFy(@chvOperatorID)
	SET @ASQL = @ASQL + ' AND a.atypeid IN (SELECT * FROM #AtypeFy1)'
	
	SELECT @dbNameB=@dbName
	--PRINT @dbNameB
	SET @SQL_WHERE = ''
	IF @Parid='root' 
		SET @Parid='00000'
	
	IF @Parid='00000' or @parid=''''
		SET @atypeidLen =5
	ELSE
		SET @atypeidLen=len(@Parid)+5
			
	SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','M.ETypeId') + @ASQL + @SQLM_WHERE
	
	SET @SQL=' 
		SELECT	substring(tempN.ntypeid,1,'+cast(@atypeidLen as VARCHAR)+') as atypeid,
		        abs( isnull(SUM(tempN.Total), 0)) AS Total
		INTO '+@TempTable+'
		FROM (select DISTINCT a.Total,ac.nTypeId,M.ShowOrder,M.billnumberid
        FROM '+@dbnameB+' a 
		inner join ac_items ac on a.atypeid=ac.nid
		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)   
		INNER JOIN moneybill AS M ON(A.BillNumberId = M.BillNumberId AND A.AtypeId = M.AtypeId AND A.Total = M.total) 
		INNER JOIN #GetManDTypeId D ON D.typeid = M.dtypeid '

	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		

	SET @SQL=@SQL +	'
		WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +') as tempN '+
		'GROUP BY substring(tempN.ntypeid,1,'+cast(@atypeidLen as VARCHAR)+') '

	SET @SQL = @SQL + '
		SELECT	a.nTypeId as typeid,
				a.usercode as usercode,
				a.fullname as fullname,
				a.sONnum as sONnum,
				a.parid as parid,
				a.leveal as leveal,
				abs(isnull(x.total,0)) as Total
		FROM 	ac_items a Join '
		+@TempTable+' x ON a.ntypeid=x.atypeid
		WHERE A.nid not in(29,36,1)	and a.IsBank<>1  AND a.nParid='+CHAR(39)+@parid+CHAR(39)+''
	IF @Parid='00001'
		set @SQL=@sql+' AND a.typeName in(''B'',''C'',''F'') '
	SET @SQL=@SQL+' ORDER by a.usercode '
--SELECT * FROM #AtypeFy1
		PRINT @SQL								
		EXEC(@SQL)
		DROP TABLE #AtypeFy1
		--RETURN
END
ELSE IF  @vchtype=159 -- 会计凭证
	BEGIN
		CREATE TABLE #Temp
		(
			TypeId	VARCHAR(MAX)			
		)
		
		CREATE TABLE #KjPzTable
		(
			TypeId	VARCHAR(MAX)			
		)
		--B.现金银行 G.收入 E.费用 F.固定资产 C.资产类 L.负责类
		--删除不符合的数据
		INSERT INTO #Temp SELECT nid FROM F_GetManDetailAType(@chvOperatorID)
		INSERT INTO #Temp SELECT nid FROM F_GetManDetailATypeFy(@chvOperatorID)
		INSERT INTO #Temp SELECT nid FROM F_GetManDetailATypeSr(@chvOperatorID)
		INSERT INTO #Temp SELECT nid FROM F_GetManDetailATypeZc(@chvOperatorID)
		
		INSERT INTO #Temp(TypeId) 
		SELECT	nId 
		FROM	Ac_Items 
		WHERE	SonNum=0
			AND nId NOT IN (
									
									SELECT	nid 
									FROM	Ac_Items 
									WHERE	( nTypeId LIKE '0000100004%' OR nTypeId = '0000100003'	--At
											OR nTypeId LIKE '0000400003%'						--Fy
											OR nTypeId LIKE '0000300003%'						--Sr
											OR nTypeId LIKE '0000100002%')						--Zc					
								  )
		and nId not in(54,55)
								  
		INSERT INTO #KjPzTable(TypeId) SELECT DISTINCT TypeId FROM #Temp
				
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = ''
		IF @Parid='00000'
			SET @ASQL=' AND ac.ntypeid like ' + char(39) +''+'%'+char(39)
		ELSE
			SET @ASQL=' AND ac.ntypeid like ' + char(39) +@Parid+'%'+char(39)
		IF @Parid='00000'
			SET @atypeidLen=5
		ELSE
			SET @atypeidLen=len(@Parid)+5	
		
		SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@ASQL+@SQLM_WHERE
		SET @SQL=' 	SELECT	substring(ac.ntypeid,1,'+cast(@atypeidLen as VARCHAR)+') as atypeid,
					        isnull(SUM(a.Total), 0) AS Total
					INTO '+@TempTable+'
					FROM  	'+@dbnameB+' a 
					INNER JOIN ac_items ac on a.atypeid=ac.nid
					INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
					INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid 
					INNER JOIN #KjPzTable T ON A.ATypeId = T.TypeId  '
		
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '		
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY	substring(ac.ntypeid,1,'+cast(@atypeidLen as VARCHAR)+')'
		SET @SQL = @SQL + '
					SELECT	a.ntypeid as typeid,
							a.usercode as usercode,
							a.fullname as fullname,
							a.sONnum as sONnum,	
							a.parid as parid,
							a.leveal as leveal,
							isnull(x.total,0) as Total
   					FROM 	ac_items a Join '
   					+@TempTable+' x ON a.ntypeid=x.atypeid
   					WHERE 	a.nParid='+char(39)+@parid+char(39)+'		
    				ORDER by a.usercode '
		    				
		--PRINT @SQL								
		EXEC(@SQL)
		
		DROP TABLE #Temp,#KjPzTable
		
		--RETURN			
	END
-- ==============================================
ELSE IF @vchtype=66 or @vchtype=4 OR @VchType = 189 OR @VchType = 190 --付款单、收款单、预收款单、预付款单
BEGIN
	DECLARE @Temp varchar(200),
			@YF_ID  VARCHAR(50)
				
	SELECT @YF_ID=NID FROM Ac_Items WHERE UserCode='1151'
	SET @Temp=''
	SELECT @dbNameB=@dbName
	
	CREATE TABLE #AType
	(
		TypeId		VARCHAR(50),
		ParId		VARCHAR(50),
		nid			INT,
		Leveal		VARCHAR(50),
		SonNum		VARCHAR(50),
		SonCount	VARCHAR(50),
		UserCode	VARCHAR(300),
		FullName	VARCHAR(300),
		Deleted		VARCHAR(10)
	)
	
	INSERT INTO #AType 
	SELECT	ntypeId,nparid,nid,1,sonnum,soncount,UserCode,FullName,deleted 
	FROM	F_GetManAType(@chvOperatorID)
	
	SET @SQL_WHERE = ''
	/*IF @parid='00000'
		BEGIN
			--SET @ASQL=' AND a.atypeid like ' + char(39) +'%'+char(39)			
			SET @Temp = ' AND (A.ATypeId = ''0000100003'' OR A.ATypeId LIKE ''0000100004%'' OR A.ATypeId = ''0000100009'' OR A.ATypeId = ''0000200006'')	'
		END
	ELSE
		BEGIN
			--SET @ASQL=' AND a.atypeid like ' + char(39) +@Parid+'%'+char(39)
			SET @atypeidLen=len(@Parid)+5			
		END*/
		
	--权限范围	
	IF @VchType = 4
		BEGIN
			IF @parid='00000'
				INSERT INTO #AType 
				SELECT	ntypeid,nparid,nid,leveal,sonnum,soncount,UserCode,FullName,deleted 
				FROM	Ac_Items
				WHERE	UserCode = '2131'
				

			--SET @ASQL = @ASQL + ' AND (A.ATypeId = ''0000100003'' OR A.ATypeId LIKE ''0000100004%'' OR A.ATypeId = ''0000200006'')	'
		END
	ELSE IF @VchType = 66
		BEGIN
			IF @parid='00000'
				INSERT INTO #AType 
				SELECT	ntypeid,nparid,nid,leveal,sonnum,soncount,UserCode,FullName,deleted 
				FROM	Ac_Items
				WHERE	UserCode = '1151'		
				
			--SET @ASQL = @ASQL + ' AND (A.ATypeId = ''0000100003'' OR A.ATypeId LIKE ''0000100004%'' OR A.ATypeId = ''0000100009'')	'
		END
	--ELSE
	--	SET @ASQL = @ASQL + ' AND (A.ATypeId = ''0000100003'' OR A.ATypeId LIKE ''0000100004%'')	'	

	SET @atypeidLen=len(@Parid)+5	
	SET @SQL_WHERE = @SQL_WHERE + REPLACE(@ESQL,'E.TypeId','B.ETypeId') +@ASQL+@SQLM_WHERE+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')
	SET @SQL='SELECT	at.typeid as atypeid,
						isnull(SUM(
									CASE 
										WHEN A.BillType IN (4,189) THEN A.Total
										WHEN A.BillType = 190 THEN -1*A.Total
										WHEN A.BillType = 66 AND A.ATypeId = '+@YF_ID+' THEN A.Total
										WHEN A.BillType = 66 AND A.ATypeId <> '+@YF_ID+' THEN -1*A.Total
										ELSE A.Total
									END
								  ), 0) AS Total
			  INTO '+@TempTable+'
        	  FROM		'+@dbnameB+' a 
			  INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
			  INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid 
			  INNER JOIN #AType AT ON AT.nid = A.ATypeId  '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
	
	SET @SQL = @SQL + '		
			WHERE	b.draft = 0 
					AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +@Temp+' 			
			GROUP BY at.typeid'
				
	
	IF @parid='00000'
		BEGIN
			--SET @ASQL=' AND a.typeid like ' + char(39) ++'%'+char(39)
			SET @SQL = @SQL + '
			SELECT 	a.typeid as typeid,
					a.usercode as usercode,
					a.fullname as fullname,
					a.SonNum as SonNum,
					a.parid as parid,
					a.leveal as leveal, 
					isnull(sum(x.total),0) as Total
			FROM 	#AType a Join '
			+@TempTable+' x  ON a.typeid=left(x.atypeid,10)
			WHERE 	1= 1 '+@ASQL+'								
			GROUP by a.typeid,a.usercode,a.fullname,a.SonNum,a.parid,a.leveal
			ORDER BY a.usercode'
			
		END	
	ELSE
		BEGIN
			--SET @ASQL=' AND a.typeid like ' + char(39) ++'%'+char(39)
			SET @SQL = @SQL + '
			SELECT	a.typeid as typeid,
					a.usercode as usercode,
					a.fullname as fullname,
					a.sONnum as sONnum,
					a.parid as parid,
					a.leveal as leveal,
					isnull(sum(x.total),0) as Total
			FROM 	#AType a Join '
			+@TempTable+' x ON   a.typeid=left(x.atypeid,'+cast(@atypeidLen as varchar)+')
			WHERE 	1= 1 '+@ASQL+@Temp+ '
					AND a.parid='+char(39)+@parid+char(39)+'
			GROUP by a.typeid,a.usercode,a.fullname,a.SonNum,a.parid,a.leveal
			ORDER BY a.usercode'
		END		
	--print @SQL
	EXEC(@SQL)
	
	DROP TABLE #AType
	--RETURN
END
ELSE IF @vchtype=57
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5
		
		 SET @SQL=' SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
		                	abs( isnull(SUM(  a.qty), 0)) AS Qty,
		                	0 as mqty,
							--abs( isnull(SUM(a.CostTotal), 0)) AS Total bug225
							isnull(SUM(a.CostTotal), 0) AS Total
					INTO '+@TempTable+'	        	        
		     		FROM  	'+@dbnameB+' a 
		     		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
		     		INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid '
		
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '		
					WHERE 	b.draft = 0 
							AND a.qty>=0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
	
		SET @SQL = @SQL + '
					SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							0 as mqty,
							isnull(x.Total,0) as Total
   					FROM 	Ptype p INNER join '
   					+@TempTable+' x ON p.typeid=x.Ptypeid
   					WHERE	p.parid='''+@Parid +'''							
					order by p.sortid'
			
		--PRINT (@SQL)
		EXEC(@SQL)
		--RETURN
	END
ELSE IF @vchtype=21 or @vchtype=17
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid = '00000'
			BEGIN
				SET @PtypeidLen=5
			END
		ELSE
			BEGIN
				SET @PtypeidLen=len(@Parid)+5	
			END
			SET @SQL=' 
				SELECT	a.ptypeid as ptypeid,
			            abs( isnull(SUM(CASE when  a.qty<0   then a.qty END),0))  as CQty,				
						abs( isnull(SUM(CASE when  a.qty>0   then a.qty END),0))  as RQty,	
						abs( isnull(SUM(CASE when  a.CostTotal<0   then a.CostTotal END),0))  as CTotal,	
						abs( isnull(SUM(CASE when  a.CostTotal>0   then a.CostTotal END),0))  as RTotal	,
					   abs(sum(dbo.F_RoundQty(a.qty/ue.Rate))) as Mqty
					 INTO '+@TempTable+'
					FROM  '+@dbnameB+' A
					INNER JOIN dbo.ptype p ON a.PtypeId=p.typeId
					INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
					INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid 
					INNER JOIN dbo.PType_Units_Ext ue on	 p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID '	
					
					IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
					
					SET @SQL = @SQL + '
						WHERE b.draft = 0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE 
						
					SET @SQL = @SQL + '  GROUP BY a.ptypeid '
				
		
			SET @SQL = @SQL + '
				SELECT	p.typeid as typeid,
						p.usercode as usercode,
						p.fullname as fullname,
						p.sONnum as sONnum,
						p.parid as parid,
						p.leveal as leveal,
						SUM(isnull(x.Cqty,0)) as Cqty,
						SUM(isnull(x.Rqty,0)) as Rqty,
						SUM(isnull(x.CTotal,0)) as CTotal,
						SUM(isnull(x.RTotal,0)) as RTotal,
						case when p.sonnum=0 then pu.fullname else '''' end as Munitfullname ,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end as rateralation ,
						sum(x.Mqty) as Mqty,
						case when p.sonnum=0 THEN pu1.fullname ELSE '''' END as basefullname
				FROM 	PType p
				INNER JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId 
				INNER JOIN dbo.PType_Units_Ext ue ON p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
				INNER JOIN dbo.PType_Units pu ON p.StockUnitId=  pu.UnitsId
				inner join '
				+@TempTable+' x ON  x.Ptypeid  like p.typeid+''%'' 
				WHERE	p.parid='''+@Parid +'''	
				group by 
						p.typeid ,
						p.usercode ,
						p.fullname,
						p.sONnum ,
						p.parid,
						p.leveal,	
						p.SortID,
						pu1.fullname,
						case when p.sonnum=0 then pu.fullname else '''' end  ,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end 
										
				ORDER BY p.SortID'	
		
			--PRINT (@SQL)
			EXEC(@SQL)
			--RETURN		
	END
ELSE IF @vchtype=148 or @vchtype=150     --返利、获利
BEGIN
	SET @SQL_WHERE = ''
	SET @SQL_WHERE = @SQL_WHERE +@SQLM_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+REPLACE(@ESQL,'E.TypeId','B.eTypeId') +@PSQL
	SELECT @dbNameB=@dbName

	IF @Parid = '00000'
		SET @PtypeidLen=5
	ELSE
		SET @PtypeidLen=len(@Parid)+5	
	 SET @SQL=' 
		SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
				isnull(SUM(a.qty), 0) AS Qty,
				isnull(SUM(a.Total), 0) AS Total
		INTO '+@TempTable+'
     	FROM  Advantage a 
		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
		INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
		WHERE b.draft = 0 AND a.qty>0 AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
		GROUP BY
			substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
	
	SET @SQL = @sql + '
		SELECT	p.typeid as typeid,
				p.usercode as usercode,
				p.fullname as fullname,
				p.sONnum as sONnum,
				p.parid as parid,
				p.leveal as leveal,
				isnull(x.qty,0) as qty,
				isnull(x.Total,0) as Total
   		FROM 	Ptype p INNER join '
   		+@TempTable+' x ON p.typeid=x.Ptypeid
   		WHERE	p.parid='''+@Parid +'''						
		ORDER BY p.SortID'

	--PRINT @SQL_WHERE
	--PRINT (@SQL)
	EXEC(@SQL)
	--RETURN
END
ELSE IF @vchtype=149  or  @vchtype =151--价保
	BEGIN
		SET @SQL_WHERE = ''
		SET @SQL_WHERE = @SQL_WHERE +@SQLM_WHERE +REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId') +@PSQL
		SELECT @dbNameB=@dbName
						
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	
		SET @SQL=' 
				SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
			            isnull(SUM( a.qty), 0) AS Qty,
						isnull(SUM(a.Total), 0) AS Total
				INTO '+@TempTable+'	        	        
		     	FROM  PriceProtectBill a 
				INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
				INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid   '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
				WHERE b.draft = 0  AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
				GROUP BY
					substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
		
		SET @SQL = @SQL + '
				SELECT	p.typeid as typeid,
						p.usercode as usercode,
						p.fullname as fullname,
						p.sONnum as sONnum,
						p.parid as parid,
						p.leveal as leveal,
						isnull(x.qty,0) as qty,
						isnull(x.Total,0) as Total
			   FROM 	Ptype p INNER join '
			   +@TempTable+' x ON p.typeid=x.Ptypeid
			   WHERE	p.parid='''+@Parid +'''							
			   ORDER BY p.SortID'
	
		--PRINT (@SQL)
		EXEC(@SQL)
		--RETURN
	END
ELSE IF @VchType IN (166,172)	--维修单、上门维修单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		SET @SQL=' 
			SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
		            SUM(CASE WHEN a.InOrOut=''o'' THEN a.Qty ELSE 0 END) as CQty,				
					SUM(CASE WHEN a.InOrOut=''i'' THEN a.Qty ELSE 0 END) as RQty,	
					0  as CTotal,	
					0  as RTotal
			INTO '+@TempTable+'		        	        
			FROM  	'+@dbNameB+' a 
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)	
			INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid   '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '		
			WHERE 	b.draft = 0  
					AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'				
			GROUP BY substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
		
			SET @SQL = @SQL + '
			SELECT	p.typeid as typeid,
					p.usercode as usercode,
					p.fullname as fullname,
					p.sONnum as sONnum,
					p.parid as parid,
					p.leveal as leveal,
					isnull(x.Cqty,0) as Cqty,
					isnull(x.Rqty,0) as Rqty,
					isnull(x.CTotal,0) as CTotal,
					isnull(x.RTotal,0) as RTotal
			FROM 	PType p INNER join '
			+@TempTable+' x ON p.typeid=x.Ptypeid
			WHERE	p.parid='''+@Parid +'''								
			ORDER BY p.SortID'	
		
			--PRINT (@SQL)
			EXEC(@SQL)
			--RETURN
	END
ELSE IF @VchType = 168	--整机更换单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@KSQL,'A.KTypeID','B.KTypeID')+@SQLM_WHERE
	
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		SET @SQL='	SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
					        abs(isnull(SUM(a.qty), 0)) AS Qty,
							0 AS Total	
					INTO '+@TempTable+'			        	       
		 			FROM  	Wx_Bill_Replace a 
		 			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
		 			INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
		
		SET @SQL = @SQL + '
					SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.total,0) as Total							
		   			FROM 	Ptype p join '
		   			+@TempTable+' x ON p.typeid=x.Ptypeid 
					WHERE	p.parid='''+@Parid +'''							
					order by p.SortID'
		--PRINT @SQL
		EXEC(@SQL)		
		--RETURN		
	END
ELSE IF @VchType IN (173,174,175) --维修品调入单、维修品调出单、维修品调拨单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		SET @SQL=' 
			SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
		            abs(isnull(SUM(a.Qty),0)) as CQty,				
					abs(isnull(SUM(a.Qty),0)) as RQty,	
					0 as CTotal,	
					0 as RTotal	
			INTO '+@TempTable+'	        	        
			FROM  	'+@dbNameB+' a 
			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
			INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
			WHERE 	b.draft = 0  
					AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'				
			GROUP BY substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
	
		SET @SQL = @SQL +  '
			SELECT	p.typeid as typeid,
					p.usercode as usercode,
					p.fullname as fullname,
					p.sONnum as sONnum,
					p.parid as parid,
					p.leveal as leveal,
					isnull(x.Cqty,0) as Cqty,
					isnull(x.Rqty,0) as Rqty,
					isnull(x.CTotal,0) as CTotal,
					isnull(x.RTotal,0) as RTotal
			FROM 	PType p INNER join '
			+@TempTable+' x ON p.typeid=x.Ptypeid
			WHERE	p.parid='''+@Parid +'''							
			ORDER BY p.SortID'	
	
		--PRINT (@SQL)
		EXEC(@SQL)
		--RETURN	
	END
ELSE IF @VchType = 171	--报修单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@SQLM_WHERE
	
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		SET @SQL='	SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
					        abs(isnull(SUM(a.qty), 0)) AS Qty,
							0 AS Total
					INTO '+@TempTable+'				        	       
		 			FROM  	Wx_Bill_Call a 
		 			INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
		 			INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid   '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
		
		SET @SQL =  @sql +'
					SELECT	p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.total,0) as Total							
		   			FROM 	Ptype p join '
		   			+@TempTable+' x ON p.typeid=x.Ptypeid 
					WHERE	p.parid='''+@Parid +'''							
					order by p.SortID'
		--PRINT @SQL
		EXEC(@SQL)		
		--RETURN		
	END
ELSE IF @VchType IN (9,14,201,202)
	BEGIN
		SELECT @dbNameB=@dbName
		IF @VchType IN (9,14)
			SET @SQL_WHERE = @SQL_WHERE+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		ELSE
			SET @SQL_WHERE = @SQL_WHERE+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@KSQL+@SQLM_WHERE

		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		 SET @SQL='SELECT	a.ptypeid,
				            abs(isnull(SUM(a.qty), 0)) AS Qty,
							abs(isnull(SUM(a.CostTotal), 0)) AS Total,
							abs(sum(dbo.F_RoundQty(a.qty/ue.Rate))) as Mqty
					INTO '+@TempTable+'				        	       
		     		FROM	InOutStockTable a 
		     		INNER JOIN dbo.ptype p ON a.PtypeId=p.typeId
					INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
					INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid 
					INNER JOIN dbo.PType_Units_Ext ue on p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY a.ptypeid '
	
		SET @SQL = @SQL + '
					SELECT  p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							sum(isnull(x.qty,0)) as qty,
							sum(isnull(x.total,0)) as Total	,
							case when p.sonnum=0 then pu.fullname else '''' end as Munitfullname ,
							case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end as rateralation ,
							sum(x.Mqty) as Mqty,
							case when p.sonnum=0 THEN pu1.fullname ELSE '''' END as basefullname						
			   		FROM 	Ptype p 
			   		INNER JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId 
					INNER JOIN dbo.PType_Units_Ext ue ON p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN dbo.PType_Units pu ON p.StockUnitId=  pu.UnitsId
					INNER join   '
					+@TempTable+' x ON  x.Ptypeid  like p.typeid+''%'' 

			   		WHERE	p.parid='''+@Parid +'''	
			   		
			   		group by 
						p.typeid ,
						p.usercode ,
						p.fullname,
						p.sONnum ,
						p.parid,
						p.leveal,	
						p.SortID,
						pu1.fullname,
						case when p.sonnum=0 then pu.fullname else '''' end  ,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end
									
					order by p.SortID'

		--PRINT @SQL
		EXEC(@SQL)	
		--RETURN		
	END
ELSE IF @vchtype=16
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@SQLM_WHERE
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		SET @SQL=' 
			SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
		            abs( isnull(SUM(CASE when  a.qty<0   then a.qty END),0))  as CQty,				
					abs( isnull(SUM(CASE when  a.qty>0   then a.qty END),0))  as RQty,	
					abs( isnull(SUM(CASE when  a.CostTotal<0   then a.CostTotal END),0))  as CTotal,	
					abs( isnull(SUM(CASE when  a.CostTotal>0   then a.CostTotal END),0))  as RTotal
			INTO '+@TempTable+'			        	        
			FROM  	(
						SELECT	A.BillNumberId,
								A.Billdate,
								A.PTypeId,
								A.Qty,
								A.Total,
								A.CostTotal
						FROM	'+@dbnameB+' A
						WHERE	A.Audited = 1
								AND A.BillType = 16
								AND A.Qty < 0
								AND a.billdate>='+char(39)+@BeginDate+char(39)+' 
								AND a.billdate<='+char(39)+@EndDate+char(39)+'
								'+@Ksql1+'
						UNION ALL
						SELECT	A.BillNumberId,
								A.Billdate,
								A.PTypeId,
								A.Qty,
								A.Total,
								A.CostTotal
						FROM	'+@dbnameB+' A
						WHERE	A.Audited = 1
								AND A.BillType = 16
								AND A.Qty > 0
								AND a.billdate>='+char(39)+@BeginDate+char(39)+' 
								AND a.billdate<='+char(39)+@EndDate+char(39)+'
								'+@Ksql2+'
					) a INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
					INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
			WHERE 	b.draft = 0  
					AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'				
			GROUP BY
					substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
	
		SET @SQL = @SQL + '
			SELECT	p.typeid as typeid,
					p.usercode as usercode,
					p.fullname as fullname,
					p.sONnum as sONnum,
					p.parid as parid,
					p.leveal as leveal,
					isnull(x.Cqty,0) as Cqty,
					isnull(x.Rqty,0) as Rqty,
					isnull(x.CTotal,0) as CTotal,
					isnull(x.RTotal,0) as RTotal
			FROM 	PType p
			INNER join '
			+@TempTable+' x ON p.typeid=x.Ptypeid
			WHERE	p.parid='''+@Parid +'''					
			ORDER BY p.SortID'	
		
			--PRINT (@SQL)
			EXEC(@SQL)
			--RETURN	
	END
ELSE IF @vchType = 161 --采购换货单
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@SQLM_WHERE
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		SET @SQL=' 
			SELECT	a.ptypeid,
		            abs( isnull(SUM(CASE when  a.qty<0   then a.qty END),0))  as CQty,				
					abs( isnull(SUM(CASE when  a.qty>0   then a.qty END),0))  as RQty,	
					abs( isnull(SUM(CASE when  a.Total<0   then a.Total END),0))  as CTotal,	
					abs( isnull(SUM(CASE when  a.CostTotal>0   then a.CostTotal END),0))  as RTotal	,
					abs(sum(dbo.F_RoundQty(a.qty/ue.Rate))) as Mqty
			INTO '+@TempTable+'		        	        
			FROM  	(
						SELECT	A.BillNumberId,
								A.Billdate,
								A.PTypeId,
								A.Qty,
								A.Total,
								A.CostTotal
						FROM	'+@dbnameB+' A
						WHERE	A.Audited = 1
								AND A.BillType = 161
								AND A.Qty < 0
								AND a.billdate>='+char(39)+@BeginDate+char(39)+' 
								AND a.billdate<='+char(39)+@EndDate+char(39)+'
								'+@Ksql1+'
						UNION ALL
						SELECT	A.BillNumberId,
								A.Billdate,
								A.PTypeId,
								A.Qty,
								A.Total,
								A.CostTotal
						FROM	'+@dbnameB+' A
						WHERE	A.Audited = 1
								AND A.BillType = 161
								AND A.Qty > 0
								AND a.billdate>='+char(39)+@BeginDate+char(39)+' 
								AND a.billdate<='+char(39)+@EndDate+char(39)+'
								'+@Ksql2+'
					) a INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
					INNER JOIN dbo.ptype p ON a.PtypeId=p.typeId
					INNER JOIN dbo.PType_Units_Ext ue on	 p.BuyUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
			WHERE 	b.draft = 0  
					AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'				
			GROUP BY
					a.ptypeid '
	
		SET @SQL = @SQL + '
			SELECT	p.typeid as typeid,
					p.usercode as usercode,
					p.fullname as fullname,
					p.sONnum as sONnum,
					p.parid as parid,
					p.leveal as leveal,
					sum(isnull(x.Cqty,0)) as Cqty,
					sum(isnull(x.Rqty,0)) as Rqty,
					sum(isnull(x.CTotal,0)) as CTotal,
					sum(isnull(x.RTotal,0)) as RTotal,
					case when p.sonnum=0 then pu.fullname else '''' end as Munitfullname ,
					case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end as rateralation ,
					sum(x.Mqty) as Mqty,
					case when p.sonnum=0 THEN pu1.fullname ELSE '''' END as basefullname
			FROM 	PType p
			INNER JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId 
				INNER JOIN dbo.PType_Units_Ext ue ON p.BuyUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
				INNER JOIN dbo.PType_Units pu ON p.BuyUnitId=  pu.UnitsId
				
			INNER join '
			+@TempTable+' x ON x.Ptypeid  like p.typeid+''%'' 
			WHERE	p.parid='''+@Parid +'''	
			group by 
						p.typeid ,
						p.usercode ,
						p.fullname,
						p.sONnum ,
						p.parid,
						p.leveal,	
						p.SortID,
						pu1.fullname,
						case when p.sonnum=0 then pu.fullname else '''' end  ,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end
			ORDER BY p.sortid'	
	
		--PRINT (@SQL)
		EXEC(@SQL)
		--RETURN	
	END
ELSE IF @vchType = 160				--销售换货单
	BEGIN 
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@SQLM_WHERE
		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	
        
        print @dbNameB
        
		SET @SQL=' 
			SELECT	a.ptypeid,
		            abs( isnull(SUM(CASE when  a.qty<0   then a.qty END),0))  as CQty,				
					abs( isnull(SUM(CASE when  a.qty>0   then a.qty END),0))  as RQty,	
					abs( isnull(SUM(CASE when  a.qty<0   then a.Total END),0))  as CTotal,	
					abs( isnull(SUM(CASE when  a.qty>0   then a.Total END),0))  as RTotal,
					abs(sum(dbo.F_RoundQty(a.qty/ue.Rate))) as Mqty
			INTO '+@TempTable+'			        	        
			FROM  	(
						SELECT	A.BillNumberId,
								A.Billdate,
								substring(A.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
								A.Qty,
								A.Total,
								A.CostTotal
						FROM	'+@dbnameB+' A
						WHERE	A.Audited = 1
								AND A.BillType = 160
								AND A.Qty < 0
								AND a.billdate>='+char(39)+@BeginDate+char(39)+' 
								AND a.billdate<='+char(39)+@EndDate+char(39)+'
								'+@Ksql2+'
						UNION ALL
						SELECT	A.BillNumberId,
								A.Billdate,
								substring(A.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
								A.Qty,
								A.Total,
								A.CostTotal
						FROM	'+@dbnameB+' A
						WHERE	A.Audited = 1
								AND A.BillType = 160
								AND A.Qty > 0
								AND a.billdate>='+char(39)+@BeginDate+char(39)+' 
								AND a.billdate<='+char(39)+@EndDate+char(39)+'
								'+@Ksql1+'
					) a INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
					INNER JOIN dbo.ptype p ON a.PtypeId=p.typeId
					INNER JOIN dbo.PType_Units_Ext ue on	 p.SaleUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
					INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid 	  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '		
			WHERE 	b.draft = 0  
					AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'				
			GROUP BY
					a.ptypeid'
	
  
	   
		SET @SQL = @SQL + '
			SELECT	p.typeid as typeid,
					p.usercode as usercode,
					p.fullname as fullname,
					p.sONnum as sONnum,
					p.parid as parid,
					p.leveal as leveal,
					sum(isnull(x.Cqty,0)) as Cqty,
					sum(isnull(x.Rqty,0)) as Rqty,
					sum(isnull(x.CTotal,0)) as CTotal,
					sum(isnull(x.RTotal,0)) as RTotal,
						case when p.sonnum=0 then pu.fullname else '''' end as Munitfullname ,
					case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end as rateralation ,
						sum(x.Mqty) as Mqty,
					case when p.sonnum=0 THEN pu1.fullname ELSE '''' END as basefullname
					
			FROM 	PType p
			
				INNER JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId 
				INNER JOIN dbo.PType_Units_Ext ue ON p.SaleUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
				INNER JOIN dbo.PType_Units pu ON p.SaleUnitId=  pu.UnitsId
				
			INNER join '
			+@TempTable+' x ON p.typeid=x.Ptypeid
			WHERE	p.parid='''+@Parid +'''	
			group by 
						p.typeid ,
						p.usercode ,
						p.fullname,
						p.sONnum ,
						p.parid,
						p.leveal,	
						p.SortID,
						pu1.fullname,
						case when p.sonnum=0 then pu.fullname else '''' end  ,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end
										
			ORDER BY p.sortid'	
	
		--PRINT (@SQL)
		EXEC(@SQL)
		--RETURN	
	END
ELSE IF @VchType IN (187,188)	
	BEGIN
		SET @SQL_WHERE = ''
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE +@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+@KSQL+@SQLM_WHERE
		IF @Parid = '00000'
			BEGIN
				SET @PtypeidLen=5
			END
		ELSE
			BEGIN
				SET @PtypeidLen=len(@Parid)+5	
			END
			SET @SQL=' 
				SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
			            abs( isnull(SUM(a.Qty),0))  as Qty,	
			            abs( isnull(SUM(a.Total),0))  as Total,
			            abs(sum(dbo.F_RoundQty(a.qty/ue.Rate))) as Mqty
			    INTO '+@TempTable+'	        
				FROM  	'+@dbnameB+' a 
				INNER JOIN dbo.ptype p ON a.PtypeId=p.typeId
				INNER JOIN dbo.PType_Units_Ext ue on	 p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
				INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID)
				INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid   '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '		
				WHERE 	b.draft = 0  
						AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'				
				GROUP BY
						substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
		
			SET @SQL = @SQL + '
				SELECT	p.typeid as typeid,
						p.usercode as usercode,
						p.fullname as fullname,
						p.sONnum as sONnum,
						p.parid as parid,
						p.leveal as leveal,
						sum(isnull(x.qty,0)) as qty,	
						sum(isnull(x.Total,0)) as Total   ,
						case when p.sonnum=0 then pu.fullname else '''' end as Munitfullname ,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end as rateralation ,
						sum(x.Mqty) as Mqty,
						case when p.sonnum=0 THEN pu1.fullname ELSE '''' END as basefullname
				FROM 	PType p
				INNER JOIN dbo.PType_Units pu1 ON p.baseUnitId=  pu1.UnitsId 
				INNER JOIN dbo.PType_Units_Ext ue ON p.StockUnitId=ue.UnitsId AND p.typeId=ue.PtypeID
				INNER JOIN dbo.PType_Units pu ON p.StockUnitId=  pu.UnitsId
	
				INNER join '
				+@TempTable+' x ON x.Ptypeid  like p.typeid+''%'' 
				WHERE	p.parid='''+@Parid +'''	
				
				group by 
						p.typeid ,
						p.usercode ,
						p.fullname,
						p.sONnum ,
						p.parid,
						p.leveal,	
						p.SortID,
						pu1.fullname,
						case when p.sonnum=0 then pu.fullname else '''' end  ,
						case when p.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(ue.rate,''qty'')+pu1.fullname  else '''' end 
								
				ORDER BY p.SortID'	
		
			--PRINT (@SQL)
			EXEC(@SQL)
			--RETURN	
	END
ELSE IF @VchType IN (191,197,196)	--领料出库单、领料退回单、救援单
	BEGIN
		SELECT @dbNameB=@dbName
		SET @SQL_WHERE = @SQL_WHERE+@PSQL+REPLACE(@ESQL,'E.TypeId','B.ETypeId')+REPLACE(@BSQL,'M.TypeId','B.dealBTypeId')+@KSQL+@SQLM_WHERE

		IF @Parid = '00000'
			SET @PtypeidLen=5
		ELSE
			SET @PtypeidLen=len(@Parid)+5	

		 SET @SQL='SELECT	substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+') as ptypeid,
				            abs(isnull(SUM(a.qty), 0)) AS Qty,
				            CAST(CASE WHEN isnull(SUM(a.qty), 0)=0 THEN 0 ELSE ISNULL((isnull(CAST(SUM(a.Total) AS NUMERIC(24,10)),0)/abs(isnull(CAST(SUM(a.qty) AS NUMERIC(24,10)), 0))),0) END AS Money) AS Price,
				            abs(isnull(SUM(a.Total), 0)) AS Total,
							abs(isnull(SUM(a.TaxTotal), 0)) AS TaxTotal	
					INTO '+@TempTable+'				        	       
		     		FROM	'+@dbnameB+' a 
		     		INNER join BillIndex b ON(a.BillnumberID=b.BillNumberID) 
		     		INNER JOIN #GetManDTypeId D ON D.typeid=b.dtypeid  '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
		
		SET @SQL = @SQL + '
					WHERE 	b.draft = 0 
							AND b.billtype = '+cast(@vchtype as varchar)+@SQL_WHERE +'
					GROUP BY substring(a.ptypeid,1,'+cast(@PtypeidLen as varchar)+')'
	
		SET @SQL = @SQL + '
					SELECT  p.typeid as typeid,
							p.usercode as usercode,
							p.fullname as fullname,
							p.sONnum as sONnum,
							p.parid as parid,
							p.leveal as leveal,
							isnull(x.qty,0) as qty,
							isnull(x.price,0) as price,
							isnull(x.Total,0) as Total,
							isnull(x.TaxTotal,0) as TaxTotal							
			   		FROM 	Ptype p join '
			   		+@TempTable+' x ON p.typeid=x.Ptypeid
			   		WHERE	p.parid='''+@Parid +'''							
					order by p.SortID'

		--PRINT @SQL
		EXEC(@SQL)	
		--RETURN		
	END	

--DECLARE @TABLE VARCHAR(MAX)=''
--SET @TABLE='DROP TABLE '+@TempTable
--EXEC(@TABLE)
--PRINT @SQL	
DROP TABLE #Stock1,#Stock2,#GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManSTypeId,#GetManDTypeId,#PTYPE


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryAutoSaveBuyBillDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryAutoSaveBuyBillDraft]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：谢吉康
	日期：2019-12-24
	描述：调入自动保存的采购草稿
	
*/
CREATE  PROCEDURE Gp_QueryAutoSaveBuyBillDraft
( 
	@BillGuid	varchar(max),
	@chvOperatorId 	varchar(50),		--操作员ID
	@chvType       	varchar(5),			--单据类型
	@chvPType		varchar(250)=''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

---- ******** 权限范围单独处理 - Start ********
CREATE TABLE #Ptype(typeid VARCHAR(50))
INSERT INTO #Ptype SELECT TYPEID FROM dbo.F_GetAllManagerBaseTypeId('',1,@chvOperatorId)

---- ******** 权限范围单独处理 - End ********
SELECT	a.*,
		cbd.*,
		e.fullname as efullnamecustom,
		p.fullname as pfullnamecustom,
		b.fullname as bfullnamecustom,
		d.fullname as dfullnamecustom,
		k.fullname as kfullnamecustom,
		s.fullname as sfullnamecustom,
		CT.fullname AS cargofullname
 FROM 
(
	SELECT  a.BillGuid,
			a.BillNumberId,
			c.typeid,
			ABS(a.qty) as qtyx,
			a.comment,
			a.stypeid,a.id as backitemid,
			c.usercode,
			c.fullname,
			c.baseUnitId AS UnitID,
			c.AssistantUnitId AS NUnitID,		
			u.FullName AS unit,
			v.FullName AS nunit,	
			c.customitemid ,
			c.customitemfrom ,
			c.customitemname,
			c.customitemrefid,		        
			itemid=a.ItemId,
			@chvType AS billtype,
			itemname= CASE WHEN a.IsCombined = 0  THEN
					 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
			iscombined=a.IsCombined,
			c.unitstype,
			c.serialcount,
			CAST(c.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
			CASE 
			WHEN ISNULL(c.AssistantUnitId,0)=0 THEN NULL
			ELSE a.UnitRate END AS unitrate,
			a.NQty,	
			a.GoodsNumber,
			a.serial,
			0 as backqty,
			0 as qty, -- 由于用名称绑定的原因，所在这里其它是差 qtyx是数量
			0 as shouldqty,
			c.IfSerial,
			1 AS isloadbill,
			0 AS buyqty,
			a.id,
			a.cargoid,
			a.ktypeid,
			a.comment as base, --用于验证的，由于上面所有的字段都是绑定的，所以我要保存一个初始的值好像没有办法
			aux.auxfullname1,aux.auxfullname2,aux.auxfullname3,aux.auxrate1,aux.auxrate2,aux.auxrate3,
			CASE WHEN @chvType=71 THEN u1.UnitsId ELSE u2.UnitsId END as munitid,
			CASE WHEN @chvType=71 THEN u1.fullname ELSE u2.fullname END as munit,
			CASE WHEN @chvType=71 THEN e1.rate ELSE e2.rate END as munitrate,
			CASE WHEN @chvType=71 THEN '1'+u1.fullname +'='+ CAST(DBO.F_ClearInvalidDecimal(e1.rate) AS VARCHAR)+ u.fullname 
			ELSE '1'+u2.fullname +'='+ CAST(DBO.F_ClearInvalidDecimal(e2.rate) AS VARCHAR) + u.fullname END as conversionrelationship,
			'' AS etypeid,
			'' as efullname,
			'' as eusercode,
			a.ProduceDate,a.ValidDate,
			dbo.F_GetAllEntrycode(c.typeid,c.saleunitid,2) AS salemunitcode,
			dbo.F_GetAllEntrycode(c.typeid,c.buyunitid,2) AS buymunitcode,
			C.brandartypeid,
			bc.usercode as brandaruercode,
			bc.fullname as brandarfullname			
	FROM	BuyBillAutoDraft a
	INNER JOIN #Ptype P ON A.PtypeId=P.typeid
	INNER JOIN ptype c ON a.ptypeid=c.typeid	
	INNER JOIN brandar_Commodity bc ON bc.typeid = C.brandartypeid
	LEFT  JOIN PType_Units u ON u.UnitsId=c.baseUnitId
	LEFT  JOIN PType_Units v ON v.UnitsId=c.AssistantUnitId
	LEFT  JOIN PType_Units u1 ON u1.UnitsId=c.buyunitid
	LEFT  JOIN PType_Units u2 ON u2.UnitsId=c.saleunitid
	LEFT  JOIN PType_Units_Ext e ON (e.UnitsId=c.AssistantUnitId AND e.PtypeID=c.typeId)
	LEFT  JOIN PType_Units_Ext e1 ON (e1.UnitsId=c.buyunitid AND e1.PtypeID=c.typeId)
	LEFT  JOIN PType_Units_Ext e2 ON (e2.UnitsId=c.saleunitid AND e2.PtypeID=c.typeId)
	LEFT  JOIN 
	(
		SELECT aux.ptypeid,pu.fullname as auxfullname1, pu1.fullname as auxfullname2, pu2.fullname as auxfullname3,
		aux.saleunitrate1 as auxrate1,aux.saleunitrate2 as auxrate2,aux.saleunitrate3 as auxrate3
		FROM PType_AuxiliaryUnits_Ext aux 
		LEFT JOIN PType_Units pu ON aux.saleunitid1=pu.unitsid
		LEFT JOIN PType_Units pu1 ON aux.saleunitid2=pu1.unitsid
		LEFT JOIN PType_Units pu2 ON aux.saleunitid3=pu2.unitsid
	) aux ON aux.ptypeid=c.typeid
	WHERE a.billguid = @BillGuid
	GROUP BY	a.BillGuid,
				a.BillNumberId,
				c.typeid,
				a.qty,
				a.comment,
				a.stypeid,
				a.id,
				c.usercode,
				c.fullname,
				c.unit1,
				c.IfSerial,			 
				c.customitemid ,
				c.customitemfrom ,
				c.customitemname,
				c.customitemrefid,		        
				a.itemid,
				a.IsCombined,
				a.GoodsNumber,	
				a.NQty,	
				CAST(ISNULL(a.serial,'') AS VARCHAR(MAX)),	 
				c.unitstype,
				c.serialcount,
				c.IfUseGoodsNum,
				c.baseUnitId,
				c.AssistantUnitId,
				u.FullName,
				v.FullName,
				a.UnitRate,
				a.serial,
				a.cargoid,a.ktypeid,
				--i.billtype,
				u1.UnitsId,
				u2.UnitsId
				,u1.fullname,u2.fullname,e1.rate,e2.rate,
				aux.auxfullname1,aux.auxfullname2,aux.auxfullname3,aux.auxrate1,aux.auxrate2,aux.auxrate3,			
				a.ProduceDate,a.ValidDate,c.SaleUnitId,c.BuyUnitId,
				C.brandartypeid,
				bc.usercode,
				bc.fullname
) a 
LEFT JOIN custom_billdetailsAutoDraft cbd on cbd.BillGuid=a.BillGuid AND cbd.detailid=a.id and cbd.billtype=@chvType
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
LEFT JOIN dbo.CargoType CT ON a.CargoID = CT.CargoID
ORDER BY a.id


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryAutoSaveSaleBillDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryAutoSaveSaleBillDraft]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：谢吉康
	日期：2019-12-24
	描述：调入自动保存的销售草稿
	
*/
CREATE  PROCEDURE Gp_QueryAutoSaveSaleBillDraft
( 
	@BillGuid	varchar(max),
	@chvOperatorId 	varchar(50),		--操作员ID
	@chvType       	varchar(5),			--单据类型
	@chvPType		varchar(250)=''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

---- ******** 权限范围单独处理 - Start ********
CREATE TABLE #Ptype(typeid VARCHAR(50))
INSERT INTO #Ptype SELECT TYPEID FROM dbo.F_GetAllManagerBaseTypeId('',1,@chvOperatorId)

---- ******** 权限范围单独处理 - End ********
SELECT	a.*,
		cbd.*,
		e.fullname as efullnamecustom,
		p.fullname as pfullnamecustom,
		b.fullname as bfullnamecustom,
		d.fullname as dfullnamecustom,
		k.fullname as kfullnamecustom,
		s.fullname as sfullnamecustom,
		CT.fullname AS cargofullname
 FROM 
(
	SELECT a.BillNumberId,
			c.typeid,
			ABS(a.qty) as qtyx,
			a.comment,
			a.stypeid,a.id as backitemid,
			c.usercode,
			c.fullname,
			c.baseUnitId AS UnitID,
			c.AssistantUnitId AS NUnitID,		
			u.FullName AS unit,
			v.FullName AS nunit,	
			c.customitemid ,
			c.customitemfrom ,
			c.customitemname,
			c.customitemrefid,		        
			itemid=a.ItemId,
			@chvType AS billtype,
			itemname= CASE WHEN a.IsCombined = 0  THEN
					 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
			iscombined=a.IsCombined,
			c.unitstype,
			c.serialcount,
			CAST(c.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
			CASE 
			WHEN ISNULL(c.AssistantUnitId,0)=0 THEN NULL
			ELSE a.UnitRate END AS unitrate,
			a.NQty,	
			a.GoodsNumber,
			a.serial,
			0 as backqty,
			0 as qty, -- 由于用名称绑定的原因，所在这里其它是差 qtyx是数量
			0 as shouldqty,
			c.IfSerial,
			1 AS isloadbill,
			0 AS buyqty,
			a.id,
			a.cargoid,
			a.ktypeid,
			a.comment as base, --用于验证的，由于上面所有的字段都是绑定的，所以我要保存一个初始的值好像没有办法
			aux.auxfullname1,aux.auxfullname2,aux.auxfullname3,aux.auxrate1,aux.auxrate2,aux.auxrate3,
			CASE WHEN @chvType=71 THEN u1.UnitsId ELSE u2.UnitsId END as munitid,
			CASE WHEN @chvType=71 THEN u1.fullname ELSE u2.fullname END as munit,
			CASE WHEN @chvType=71 THEN e1.rate ELSE e2.rate END as munitrate,
			CASE WHEN @chvType=71 THEN '1'+u1.fullname +'='+ CAST(DBO.F_ClearInvalidDecimal(e1.rate) AS VARCHAR)+ u.fullname 
			ELSE '1'+u2.fullname +'='+ CAST(DBO.F_ClearInvalidDecimal(e2.rate) AS VARCHAR) + u.fullname END as conversionrelationship,
			'' AS etypeid,
			'' as efullname,
			'' as eusercode,
			a.ProduceDate,a.ValidDate,
			dbo.F_GetAllEntrycode(c.typeid,c.saleunitid,2) AS salemunitcode,
			dbo.F_GetAllEntrycode(c.typeid,c.buyunitid,2) AS buymunitcode,
			C.brandartypeid,
			bc.usercode as brandaruercode,
			bc.fullname as brandarfullname			
	FROM	SaleBillAutoDraft a
	INNER JOIN #Ptype P ON A.PtypeId=P.typeid
	INNER JOIN ptype c ON a.ptypeid=c.typeid	
	INNER JOIN brandar_Commodity bc ON bc.typeid = C.brandartypeid
	LEFT  JOIN PType_Units u ON u.UnitsId=c.baseUnitId
	LEFT  JOIN PType_Units v ON v.UnitsId=c.AssistantUnitId
	LEFT  JOIN PType_Units u1 ON u1.UnitsId=c.buyunitid
	LEFT  JOIN PType_Units u2 ON u2.UnitsId=c.saleunitid
	LEFT  JOIN PType_Units_Ext e ON (e.UnitsId=c.AssistantUnitId AND e.PtypeID=c.typeId)
	LEFT  JOIN PType_Units_Ext e1 ON (e1.UnitsId=c.buyunitid AND e1.PtypeID=c.typeId)
	LEFT  JOIN PType_Units_Ext e2 ON (e2.UnitsId=c.saleunitid AND e2.PtypeID=c.typeId)
	LEFT  JOIN 
	(
		SELECT aux.ptypeid,pu.fullname as auxfullname1, pu1.fullname as auxfullname2, pu2.fullname as auxfullname3,
		aux.saleunitrate1 as auxrate1,aux.saleunitrate2 as auxrate2,aux.saleunitrate3 as auxrate3
		FROM PType_AuxiliaryUnits_Ext aux 
		LEFT JOIN PType_Units pu ON aux.saleunitid1=pu.unitsid
		LEFT JOIN PType_Units pu1 ON aux.saleunitid2=pu1.unitsid
		LEFT JOIN PType_Units pu2 ON aux.saleunitid3=pu2.unitsid
	) aux ON aux.ptypeid=c.typeid
	WHERE a.billguid = @BillGuid
	GROUP BY	a.BillNumberId,
				c.typeid,
				a.qty,
				a.comment,
				a.stypeid,
				a.id,
				c.usercode,
				c.fullname,
				c.unit1,
				c.IfSerial,			 
				c.customitemid ,
				c.customitemfrom ,
				c.customitemname,
				c.customitemrefid,		        
				a.itemid,
				a.IsCombined,
				a.GoodsNumber,	
				a.NQty,	
				CAST(ISNULL(a.serial,'') AS VARCHAR(MAX)),	 
				c.unitstype,
				c.serialcount,
				c.IfUseGoodsNum,
				c.baseUnitId,
				c.AssistantUnitId,
				u.FullName,
				v.FullName,
				a.UnitRate,
				a.serial,
				a.cargoid,a.ktypeid,
				--i.billtype,
				u1.UnitsId,
				u2.UnitsId
				,u1.fullname,u2.fullname,e1.rate,e2.rate,
				aux.auxfullname1,aux.auxfullname2,aux.auxfullname3,aux.auxrate1,aux.auxrate2,aux.auxrate3,			
				a.ProduceDate,a.ValidDate,c.SaleUnitId,c.BuyUnitId,
				C.brandartypeid,
				bc.usercode,
				bc.fullname
) a 
LEFT JOIN custom_billdetails cbd on cbd.BillId=a.billnumberid AND cbd.detailid=a.id and cbd.billtype=@chvType
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
LEFT JOIN dbo.CargoType CT ON a.CargoID = CT.CargoID
ORDER BY a.id


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_queryBarCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_queryBarCode]
GO














CREATE    PROCEDURE GP_queryBarCode  

(
    @Parid 		varchar(25),
  	@szValue 	varchar(30),
 	@szflag 	char(2),
  	@DbName 	varchar(30),
    @ifDeleted int=0   --显示停用信息
)
--@encode$--
as
SET NOCOUNT ON 
declare @SonNum  int
declare @sql [varchar](500)
declare @Deleted varchar(15)
DECLARE @Value 		varchar(30)


if @ifDeleted=0
	set @Deleted=' and deleted=0'
else
	set @Deleted=''
IF @szValue = ''
   	SET @Value='%'
ELSE
	SET @Value=@szValue



IF @szflag=1
BEGIN
if @DbName='ptype'
    begin
     if @ifDeleted=0
    	select @SonNum=sonnum from ptype  where typeid=@Parid and deleted=0
    else
	select @SonNum=sonnum from ptype  where typeid=@Parid
                 if @SonNum= 0 and @parid<>'00000'
                    Select @sql='
						select * from ptype  
						where typeId='+CHAR(39)+@parid+CHAR(39)+@deleted+'
						AND		UserCode LIKE '+CHAR(39)+@Value+CHAR(39)+'
						ORDER BY UserCode'
                 else 
                    Select @sql='
						select * from ptype  
						where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'
						AND	UserCode LIKE '+CHAR(39)+'%'+@Value+'%'+CHAR(39)+'
					ORDER BY  usercode'
		END
END
ELSE
BEGIN
if @DbName='ptype'
    begin
     if @ifDeleted=0
    	select @SonNum=sonnum from ptype  where typeid=@Parid and deleted=0
    else
	select @SonNum=sonnum from ptype  where typeid=@Parid
                 if @SonNum= 0 and @parid<>'00000'
							
	  Select @sql='
						select * from ptype  
						where typeId='+CHAR(39)+@parid+CHAR(39)+@deleted+'
						AND		FullName LIKE '+CHAR(39)+'%'+@Value+'%'+CHAR(39)+'
						ORDER BY UserCode'
                 else 
                    Select @sql='
						select * from ptype  
						where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'
						AND	FullName LIKE '+CHAR(39)+'%'+@Value+'%'+CHAR(39)+'
						ORDER BY  usercode'							
	END						
  	END




exec (@sql)
--print(@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryBaseInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryBaseInfo]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryBaseInfo    Script Date: 2002-6-20 10:14:50 ******/

CREATE  PROCEDURE Gp_QueryBaseInfo 
(
     @DbName  varchar(30),
 @UserCode  varchar(33),
     @FullName  varchar(66)
)
--@encode$--
as
SET NOCOUNT ON
declare @sql [varchar](500)
select @sql='select * from '+@dbname
if @userCode<>'' select @sql=@sql+' where deleted=0 and sonnum=0 and usercode='+CHAR(39)+@userCode+char(39)
if @Fullname<>'' select @sql=@sql+' where deleted=0 and sonnum=0 and fullname='+CHAR(39)+@fullname+char(39)+' and fullname <> '+char(39)+'root'+char(39)
--print @sql
exec (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryBillBrandarInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryBillBrandarInfo]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

------------------------------------------
-- 描述：获取单据在收款单上的结算信息
-------------------------------------------

CREATE   PROCEDURE Gp_QueryBillBrandarInfo
(
	@GoodsBillId			INT,	-- 业务单据id
	@BillType				INT,	--业务单据类型
	@MoneyBillId			INT,	--收款单id
	@DetailId				INT		--应收增加/减少单明细id
)
AS
SET NOCOUNT ON 

DECLARE @TableName			VARCHAR(50),
		@sql				VARCHAR(2000),
		@TableNameIndex		VARCHAR(50),
		@billsql			VARCHAR(1000)

SELECT @TableNameIndex = IndexTable FROM dbo.BillName WHERE Billtype = @BillType		
SELECT @TableName = detailTable FROM dbo.BillName WHERE Billtype = @BillType

IF @BillType =12
	SET @TableName = 'PT_Combin_SaleBill'
ELSE IF @BillType = 46
	SET @TableName = 'PT_Combin_SaleBackBill'

IF @BillType IN(115,116) --应收增加/减少单
BEGIN
	SET @billsql = '
			SELECT	d.brandartypeid,
					d.id AS DetailId,
					SUM('+CASE WHEN @BillType IN (115) THEN '-d.NTotal' ELSE 'd.NTotal' END +') AS billtotal,
					SUM(NCompleteTotal) AS billNCompleteTotal
			FROM	' + @TableName + ' d
			WHERE	d.BillNumberId = '+CAST(@GoodsBillId AS varchar)+CASE WHEN @DetailId = -1 THEN '' ELSE ' AND d.id = '+CAST(@DetailId AS VARCHAR) END +'
			GROUP BY d.brandartypeid,d.id
			'
END 
ELSE IF @TableName IN('moneybill')
BEGIN
	SET @billsql = '
			SELECT	d.brandartypeid,
					0 AS DetailId,
					SUM('+CASE WHEN @BillType IN (36) THEN '-d.NTotal' ELSE 'd.NTotal' END +') AS billtotal,
					0 AS billNCompleteTotal 
			FROM	' + @TableName + ' d
			WHERE	d.BillNumberId = '+CAST(@GoodsBillId AS varchar)+' 
			GROUP BY d.brandartypeid
			'
END			
ELSE IF @BillType IN(160) --换货单有上下两个表体
BEGIN
	SET @billsql = '
			SELECT	p.brandartypeid,
					0 AS DetailId,
					SUM(CASE WHEN InOrOut = ''I'' THEN -d.NTaxTotal ELSE d.NTaxTotal END ) AS billtotal,
					0 AS billNCompleteTotal  
			FROM	' + @TableName + ' d
			INNER JOIN dbo.ptype p ON p.typeId = d.ptypeid
			WHERE d.BillNumberId = '+CAST(@GoodsBillId AS varchar)+'  
			GROUP BY p.brandartypeid
		'
END 
ELSE
BEGIN	
	SET @billsql = '
			SELECT	p.brandartypeid,
					0 AS DetailId,
					SUM('+CASE WHEN @BillType IN(45,46) THEN '-d.NTaxTotal' ELSE 'd.NTaxTotal' END +') AS billtotal,
					0 AS billNCompleteTotal  
			FROM	' + @TableName + ' d
			INNER JOIN dbo.ptype p ON p.typeId = d.ptypeid
			WHERE d.BillNumberId = '+CAST(@GoodsBillId AS varchar)+'  
			GROUP BY p.brandartypeid
	'

END	

SET @sql = '	
	SELECT	a.BrandarTypeID
			,bc.FullName AS brandarfullname
			,bi.Cid 
			,ac.FullName AS cidname
			,a.billtotal
			,ISNULL(cbt.nCompleteTotal,0) AS ncompletetotal
			,ISNULL(ncompleted.NCompletedTotal,0) AS NCompletedTotal
			,(ABS(a.billtotal)-ABS(a.billNCompleteTotal) -'+CASE WHEN @BillType IN(115,116) THEN ' 0' ELSE ' ABS(ISNULL(ncompleted.NCompletedTotal,0))' END + ' - ABS(ISNULL(bmb.NTotalInMoney,0)) - ABS(ISNULL(bmb.NPreferenceMoney,0)) - ABS(ISNULL(bmb.NYSTotalInMoney,0)))*CASE WHEN a.billtotal > 0 THEN 1 ELSE -1 END  AS nocompletetotal
			,ISNULL(cbt.Comment,'''') AS base
			,a.DetailId
	FROM (		
				'+@billsql+'
		) a '
	IF(@BillType IN(115,116) AND @DetailId=-1)
		SET @sql+='INNER JOIN dbo.CompleteBrandarTotal cbt ON a.brandartypeid = cbt.BrandarTypeID AND CBT.DetailId=a.DetailId AND cbt.GoodsBillID = '+CAST(@GoodsBillId AS varchar)
	ELSE 
		SET @sql+='LEFT JOIN dbo.CompleteBrandarTotal cbt ON a.brandartypeid = cbt.BrandarTypeID AND cbt.GoodsBillID = '+CAST(@GoodsBillId AS varchar)+' '
	SET @sql+='
		AND cbt.BillType = '+CAST(@BillType AS varchar)+' 
		AND cbt.MoneyBillId = '+CAST(@MoneyBillId AS varchar)+'
	LEFT JOIN dbo.brandar_Commodity bc ON bc.TypeId = a.BrandarTypeID
	LEFT JOIN '+@TableNameIndex+' bi ON bi.BillnumberId = '+CAST(@GoodsBillId AS varchar)+' 
	LEFT JOIN dbo.Ac_Currency ac ON ac.CId = bi.Cid
	LEFT JOIN (SELECT	BrandarTypeID
						,DetailId
						,SUM(NCompleteTotal) AS NCompletedTotal 
				FROM dbo.CompleteBrandarTotal 
				WHERE GoodsBillID = '+CAST(@GoodsBillId AS varchar)+' AND BillType='+CAST(@BillType AS varchar)+' AND IsDraft = 0
				GROUP BY BrandarTypeID,DetailId
		) ncompleted ON ncompleted.BrandarTypeID = a.BrandarTypeID AND ncompleted.DetailId = a.DetailId
	LEFT JOIN dbo.BillMulBrand bmb ON bmb.BillnumberId = '+CAST(@GoodsBillId AS varchar)+' AND bmb.BillType='+CAST(@BillType AS varchar)+' AND bmb.BrandarTypeID = a.BrandarTypeID
	'
	
--PRINT(@SQL)
EXEC(@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryBillIndexAuditing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryBillIndexAuditing]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2004-11-04
	描述：重写了单据导入草稿的存储过程
*/
CREATE  PROCEDURE Gp_QueryBillIndexAuditing
( 
	@BEGINDate		VARCHAR(25),
	@EndDate  		VARCHAR(25),
	@DealBtypeId	VARCHAR(50),
	@EtypeId  		VARCHAR(50),
	@KtypeId  		VARCHAR(50),
	@PtypeId  		VARCHAR(50),
	@OrderBy  		VARCHAR(50) = 'billdate DESC',
	@BillType  		VARCHAR(5) = '',
	@FilterBill 	VARCHAR(500) = '' ,--需要附加的相关条件(1=接待登记单调估价单的时候，调入档的；接待登录调估价)
	@InOut   		VARCHAR(10) = '',
	@Draft  		BIT = 0,
	@ManEtype 		VARCHAR(50) = '',
	@IfAudit		VARCHAR(2),			-- 审核的类型   -1.审核不通过  0.待审核   1.审核通过  2.没有审核  兼容以前草稿  AuditingBill 中的IfAudit
	@BillIndexType	CHAR(1), 
	-----------------------------------------------新加
	@checke 		VARCHAR(50) = '',
	@BillCode 		VARCHAR(200) = '',	-- #&**&#
	@comment 		VARCHAR(256) = '',
	@chrCheckAudit 	CHAR(1) = '',
	@DTypeID  		VARCHAR(100) = '',	-- 部门查询 Wang Wei 2010-8-13
	@RATypeID		VARCHAR(50) = '',	-- 车牌号ID，查询报表的表头条件
	@Stypeid		varchar(50)='',
	@strCurrencyID	varchar(50)='',
	@IsIni			int=0,				--1为期初单据，0为非期初单据
	@BtypeId		VARCHAR(50)='',		--结算单位
	@stypeid2		VARCHAR(50)='',
	@fapiaobillcode VARCHAR(200)='',		--发票编号
	@chargeofftype	varchar(10)=''
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @checke
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 分支机构
IF @Stypeid<>'' or @chvMStypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)
	IF(@BillType = 310)
	BEGIN
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON (a.sTypeID = s.TypeID OR a.sTypeID2=s.TypeID)'
	END
	ELSE
	BEGIN
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
	END
END

-- 部门
IF @DTypeID<>'' or @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaseTypeId(@DTypeID,9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON (a.dTypeID = d.TypeID)'
	insert into #F_BaseGetManDetaildType values('')
END


-- 往来单位
CREATE TABLE #F_BaseGetManDetailBType(TypeID varchar(100))
IF (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999') 
	AND @BillType IN (305,11,45,34,6,4,66,36,35,84,85,93,139,126,140,141,142,144,143,145,146,147,148,149,150,160,161,165,
	166,167,168,169,170,171,172,177,178,183,184,185,186,189,190,191,192,195,196,197,198,199,200,201,202,400,401,402,403,
	404,405,423,424,425,426)
BEGIN
	INSERT INTO #F_BaseGetManDetailBType SELECT TypeID FROM F_BaseGetManDetailBType(@chvOperatorID)
	INSERT INTO #F_BaseGetManDetailBType(TypeID) VALUES('')
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailBType B ON a.DealBtypeID = B.TypeID '
END

-- 结算单位
CREATE TABLE #F_BaseGetManDetailBType1(TypeID varchar(100))
IF (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999') 
	AND @BillType IN (305,11,45,34,6,4,66,36,35,84,85,93,139,126,140,141,142,144,143,145,146,147,148,149,150,160,161,165,
	166,167,168,169,170,171,172,177,178,183,184,185,186,189,190,191,192,195,196,197,198,199,200,201,202,400,401,402,403,
	404,405,423,424,425,426)
BEGIN
	INSERT INTO #F_BaseGetManDetailBType1 SELECT TypeID FROM F_BaseGetManDetailBType(@chvOperatorID)
	INSERT INTO #F_BaseGetManDetailBType1(TypeID) VALUES('')
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailBType1 B1 ON ISNULL(a.BtypeID,'''') = B1.TypeID '
END

-- 职员
IF @chvMETypeID = '-99999' AND @BillType <> 177
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	
	IF @BillType IN(327,328,329)
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON (a.ApplyEtypeId = E.TypeID) '
	ELSE
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON (a.ETypeID = E.TypeID) '
	insert into #F_BaseGetManDetailEType values('')
END


-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)

	IF @BillType IN (305,11,45,34,6,9,14,139,126,140,142,144,146,165,167,168,169,170,171,177,178,183,191,196,197,201,202,400,401,402,403)
	BEGIN
		INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
	END

	IF @BillType IN (16,155,160,161)
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID OR a.KTypeID2 = K.TypeID '

	/*
	姜毅对维修的三种调拨单仓库权限控制备注
	请开发修改为：
	如操作员有单据入库仓库或出库仓库的任意一个的权限范围，
	a.对于单据的出入库仓库都为非空--可在调用草稿中查询出该单据。
	b.单据的出入库仓库其中一个为非空--可在调用草稿中查询出该单据。
	c.单据的出入库仓库都为空--可在调用草稿中查询出该单据。
	
	如操作员没有单据入库仓库或出库仓库的任意一个的权限范围，
	a.对于单据的出入库仓库都为非空--不能在调用草稿中查询出该单据。
	b.单据的出入库仓库其中一个为非空--不能在调用草稿中查询出该单据。
	c.单据的出入库仓库都为空--可在调用草稿中查询出该单据。
	*/
	IF @BillType IN (166,172,173,174,175)
	BEGIN
		INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID2<>'''' AND a.KTypeID2=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''') '
	END

	IF @BillType = 57
	BEGIN	
		DECLARE @KtypeLimit varchar(50)
		SELECT @KtypeLimit = MangerKtypeId FROM LoginUser WHERE ETypeID = @checke
		IF @KtypeLimit <> '00000'	-- 没有全部权限控制仓库
		BEGIN
			INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
			INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('00000')
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
		END
	END

	--修改人：谢吉康
	--日  期：2005-05-15
	--描  述：根据系统配置调拨当中仓库权限无效	
	IF @BillType IN (17,21)
	BEGIN
		/*
			作者：谢吉康
			日期：2005-4-15
			描述：增加调拨单中入库仓库的权限范围无效
		*/
		DECLARE @MoveInOutKLimit int
		SELECT @MoveInOutKLimit = Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit'
		IF @MoveInOutKLimit = 1 SET @MoveInOutKLimit = 0 --出入库都带权限
		ELSE SET @MoveInOutKLimit = 1	--控制出库的权限，入库不控制

		INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
		IF @MoveInOutKLimit = 1
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''') '
		ELSE  ----出入库都带权限
			SET @SQL_Man = @SQL_Man +'  INNER JOIN #F_BaseGetManDetailKType K ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''')
										INNER JOIN #F_BaseGetManDetailKType K1 ON (a.KTypeID2<>'''' AND a.KTypeID2=K1.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K1.TypeID='''') '
		
		
		--IF @MoveInOutKLimit = 1
		--	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID2<>'''' AND a.KTypeID2=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''') '
		--ELSE  ----出入库都带权限
		--	SET @SQL_Man = @SQL_Man +'  INNER JOIN #F_BaseGetManDetailKType K ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''')
		--								INNER JOIN #F_BaseGetManDetailKType K1 ON (a.KTypeID2<>'''' AND a.KTypeID2=K1.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K1.TypeID='''') '
	END
	
	IF @BillType IN (327,328,329)
	BEGIN
		DECLARE @postransktypelimit int
		SELECT @postransktypelimit = Value FROM UserConfig WHERE ConfigName = 'postransktypelimit'

		INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
		IF @postransktypelimit = 0
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.inKTypeID<>'''' AND a.inKTypeID=K.TypeID) '
		ELSE  ----出入库都带权限
			SET @SQL_Man = @SQL_Man +'  INNER JOIN #F_BaseGetManDetailKType K ON  a.KTypeID=K.TypeID
										INNER JOIN #F_BaseGetManDetailKType K1 ON a.inKTypeID=K1.TypeID '
	END
	
	IF @BillType=187
	BEGIN
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID2<>'''' AND a.KTypeID2=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''') '
	END
	IF @BillType=188
	BEGIN
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K1 ON (a.KTypeID2<>'''' AND a.KTypeID2=K1.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K1.TypeID='''') '
	END
	--优惠券入库\退货单
	IF @BillType IN (423,426)
	BEGIN
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.InKTypeID = K.TypeID '
	END
	--优惠券入库\退货单
	ELSE IF @BillType IN (424)
	BEGIN
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.OutKTypeID = K.TypeID '
	END
	----优惠券调拨单出入库都带权限
	ELSE IF @BillType IN (425)
	BEGIN
		SET @SQL_Man = @SQL_Man +'  INNER JOIN #F_BaseGetManDetailKType K ON a.InKTypeID = K.TypeID
									INNER JOIN #F_BaseGetManDetailKType K1 ON a.OutKTypeID = K1.TypeID '
	END							
END
-- ******** 权限范围单独处理 - End ********

DECLARE @re 			int,	-- 修改他人草稿的权限
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@ReLimitPass 	int		-- 单据过帐权限
/*
	修改人：谢吉康
	日  期：2004-04-10
	描  述：有审核权限的人不受是否修改他人草稿权限的限制[修改成修改他人草稿权限优先]
*/
IF (@checke = '00001') or @BillType in (184,185,193,194) --询价单、报价单不受修改他人草稿权限控制
	SET @re = 0
ELSE
BEGIN	
	EXEC @Re467 = GP_CheckLimit @checke,467  --查看他人业务草稿
	EXEC @re = GP_CheckLimit @checke,135  --修改草稿
	IF @Re467=1 SET @re=1 
	IF @re = 1 AND (@IfAudit = 0 OR @IfAudit = 1)
	BEGIN
		IF @IfAudit=0
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet
				WHERE BillType = @BillType AND IfUse = 1 AND LEFT(AuditingReason,1) <> 1)	-- 检查单据是否有审核流程
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet A,AuditingFlowDetail B
					WHERE A.AuditingID = B.AuditingID AND A.BillType = @BillType AND A.IfUse = 1
					AND LEFT(A.AuditingReason,1) <> 1 AND B.ETypeID = @checke)	-- 检测具体人针对具体的单据是否有审核流程
				BEGIN
					IF @Re467 = 0
						SET @re = 0
					ELSE
						SET @re = 1
				END
				ELSE
					IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail B,AuditingFlowSet A
						WHERE A.AuditingID = B.AuditingID AND B.ETypeID = @checke
						AND B.AuditingStep = 0 AND A.BillType = @BillType)	-- 检测用户是否具有特批人权限
					BEGIN
						IF @Re467 = 0
							SET @re = 0
						ELSE
							SET @re = 1
					END
			END
		END
		ELSE 
			SET @re = 0
	END
END


IF @re = 2 RETURN @re

---------------- 判断单据是否有审核流程 谢吉康  2003-11-20
DECLARE @IsExistFlowSet int
IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType AND IfUse = 1 AND Substring(AuditingReason,1,1)<>1)
	SELECT @IsExistFlowSet = 1
ELSE
	SELECT @IsExistFlowSet = 0
-----------------------------------------------------------------------------------------------
DECLARE @IndexTable VARCHAR(200)
SET @IndexTable = ' BillIndex '
IF @BillType=404 OR @BillType=405
BEGIN
	SET @IndexTable=' ReceiptBillIndex '
END
ELSE IF @BillType= 412 OR @BillType=413
BEGIN
	SET	@IndexTable=' onShelvespickIndex '
END
ELSE IF @BillType IN (423,424,425,426,428,429)
BEGIN
	SET	@IndexTable=' Coupon_BillIndex '
END
ELSE IF @BillType IN (327,328,329)
	set @IndexTable = ' PosAllotApplyBillIndex'
	
DECLARE @SQL varchar(MAX)

IF @BillType IN (412,413)
BEGIN
SET @SQL = '
	SELECT	DISTINCT
			a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.STypeID,
			a.Checke,
			a.DTypeID,
			a.Explain,
			a.Comment,'
END
ELSE IF @BillType IN (423,424,425,426,428,429)
BEGIN
SET @SQL = '
	SELECT	DISTINCT
			a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.STypeID,
			a.Maker AS Checke,
			a.DTypeID,
			a.Explain,
			a.BTypeId,
			a.Comment,'
END
ELSE IF @BillType IN(327,328,329)
	SET @SQL = '
	SELECT DISTINCT
			a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ApplyEtypeId AS ETypeID, 
			a.STypeID,
			a.Checke,
			a.DTypeID,
			a.Explain,
			a.Comment,
			'
ELSE
SET @SQL = '
	SELECT	DISTINCT
			a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.dealbtypeid AS BTypeID,
			a.STypeID,
			a.Checke,
			a.DTypeID,
			a.Explain,
			a.Comment,
			a.dealbtypeid,
			a.btypeid as jstypeid,
			btype.fullname as bfullname,
			a.totalmoney,'
IF @BillType=450
BEGIN
	SET @SQL = @SQL + ' CASE a.chargeofftype 
						WHEN 0 THEN ''应收冲应付'' 
						WHEN 1 THEN ''预收冲预付''
						WHEN 2 THEN ''应收转应收''
						WHEN 3 THEN ''应付转应付''
						WHEN 4 THEN ''预收转应付''
						WHEN 5 THEN ''预付转应收'' 
						END AS chargeofftypename,
						a.chargeofftype,'
END

IF @BillType NOT IN (412,413,423,424,425,426,428,429,327,328,329)
BEGIN	
	IF @BillType NOT IN (404,405)
	BEGIN
		SET @SQL = @SQL +' a.tel,'
	END
	ELSE
		SET @SQL = @SQL + ' a.fapiaocode,'
END

IF @BillType IN (177, 178,191,192,195,196,199)
	SET @SQL = @SQL + ' c.TypeID AS RATypeID'
ELSE	
	SET @SQL = @SQL + ' RATypeID = '''''

IF @BillType IN (412,413,327,328,329,423,424,425,426,428,429)
BEGIN
	SET @SQL = @SQL + ' FROM '+@IndexTable+' a ' + @SQL_Man	
END
ELSE
	SET @SQL = @SQL + ' FROM '+@IndexTable+' a ' + @SQL_Man + ' LEFT JOIN btype ON btype.typeid=a.btypeid '	
					
IF @BillType IN (177, 178,191,192,195,196,199)
BEGIN
	SET @SQL = @SQL + ' INNER JOIN Billindex_CarRepair be ON a.BillNumberID = be.BillNumberID
	LEFT JOIN QP_RepairAutoInfo c ON be.RATypeID = c.TypeID'
END

IF @BillType=192
BEGIN
	Set @sql=@sql+' INNER JOIN Qp_BackingOut_Bill back  '
	if @FilterBill='1'
		SET @sql=@sql+' ON (a.billnumberid=back.billnumberid and back.backingoutstate=1)' 
	ELSE
		SET @sql=@sql+' ON (a.billnumberid=back.billnumberid)' 
END

IF @IfAudit = 2
BEGIN
	IF @BillType=404 OR @BillType=405
	BEGIN
		SET @SQL = @SQL + ' WHERE	NOT EXISTS( SELECT ab.BillNumberID FROM AuditingBill ab WHERE a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 5 ) AND '
	END
	ELSE IF @BillType IN (412,423,424,425,426,428,429)--上架单没有审核，调草稿时不判断审核--优惠券单据没有审核
		SET @SQL = @SQL + ' WHERE 1=1 AND '
	ELSE IF @BillType IN (327,328,329)
	BEGIN
		SET @SQL = @SQL + ' WHERE	NOT EXISTS( SELECT ab.BillNumberID FROM AuditingBill ab WHERE a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 9 ) AND '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' WHERE	NOT EXISTS( SELECT ab.BillNumberID FROM AuditingBill ab WHERE a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 2 ) AND '
	END
END
ELSE
BEGIN
	IF @BillType=404 OR @BillType=405
	BEGIN
		SET @SQL = @SQL + ' INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 5 AND ab.IfAudit = ''' + @IfAudit + ''' WHERE	1=1 AND '
	END
	ELSE IF @BillType IN (423,424,425,426,428,429)--优惠券单据没有审核
	BEGIN
		SET @SQL = @SQL + ' INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 9 AND ab.IfAudit = ''' + @IfAudit + ''' WHERE	1=1 AND '
	END
	ELSE IF @BillType IN (327,328,329) -- 门店配送单据
	BEGIN
		SET @SQL = @SQL + ' INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 8 AND ab.IfAudit = ''' + @IfAudit + ''' WHERE	1=1 AND '	
	END
	ELSE
	BEGIN
		SET @SQL = @SQL + ' INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 2 AND ab.IfAudit = ''' + @IfAudit + ''' WHERE	1=1 AND '	
	END
END

IF @BEGINDate<>''
	SET @SQL = @SQL +' a.BillDate >= ''' + @BEGINDate + ''' AND '
IF 	@EndDate<>''
	SET @SQL = @SQL +' a.BillDate <= ''' + @EndDate + ''' AND '
SET @SQL = @SQL +' a.BillType = ''' + @BillType + ''''

--IF @BillType NOT IN (412,413)
--BEGIN
	IF @IsIni = 1 
		SET @SQL = @SQL + ' AND a.IsIni=1 '
	ELSE
	BEGIN
		SET @SQL = @SQL + ' AND a.IsIni=0 '
		IF @FilterBill='1'
		BEGIN
			IF @Billtype='192'
				SET @SQL = @SQL + ' AND a.ifCheck=''t'' AND a.Draft = 0 '
		END
		ELSE IF @Billtype=192
		   SET @SQL = @SQL + ' '
		ELSE IF @Billtype IN (423,424,425,426)
		   SET @SQL = @SQL + ' AND a.ifCheck=''f'' AND a.Draft=1 '
		ELSE
			SET @SQL = @SQL + 'AND a.ifCheck=''f'' AND a.Draft = 1 '				   

		SET @SQL = @SQL + 'AND a.RedWord = 0'

		IF @BillType='195' 
			SET @SQL=@SQL+' AND BE.BillState=1 '
	END
--END
IF @BillCode <> '' 
	SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @stypeid <> '' AND @billtype=310
BEGIN
	SET @SQL = @SQL + ' AND a.stypeid='''+@stypeid+''''
END
IF @stypeid2 <> ''
	SET @SQL = @SQL + ' AND a.stypeid2='''+@stypeid2+''''
IF @fapiaobillcode<>''
	SET @SQL=@SQL+' AND a.fapiaocode LIKE ''%' + @fapiaobillcode + '%'''
IF ISNULL(@chargeofftype,'') <> '' AND @chargeofftype <> '99' AND @Billtype=450
BEGIN
	SET @SQL = @SQL +' AND a.chargeofftype='''+@chargeofftype+''' '
END
----------------------------胡小科2012-6-11 控制单据查看权限-------------------------------------	
DECLARE @viewOtherBillindex VARCHAR(2);
 SELECT @viewOtherBillindex=SUBSTRING(lim,467,1) FROM dbo.loginuser WHERE etypeid=@checke
	
IF (@viewOtherBillindex<> 1  
AND @FilterBill='' 
AND @BillType IN (305,11,45,160,139,140,142,143,141,34,6,161,126,144,146,147,145,17,21,201,202,9,14,16,116,115,128,129,4,189,66,190,148,150,149,151,36,158,77,93,5,10,84,85,78,57,159,165,166,167,168,169,170,171,172,173,174,175,183,310,400,401,402,403,404,405,423,424,425,426,327,328)
--超级管理员不判断该权限
AND @checke<>'00001')
BEGIN
	IF @BillType IN (423,424,425,426)
		SET @SQL = @SQL + ' AND ( a.Maker = ''' + @checke + ''' or a.Maker='''' ) '
	ELSE
		SET @SQL = @SQL + ' AND ( a.Checke = ''' + @checke + ''' or a.checke='''' ) '
END
-----------------------------------------------------------------------------------

IF @DealBtypeId <> '' 
	SET @SQL = @SQL + ' AND a.dealbtypeid=''' + @DealBtypeId + ''''

IF @BtypeId <> '' 
	SET @SQL = @SQL + ' AND a.btypeid=''' + @BtypeId + ''''
		
IF @ETypeID <> '' 
begin
	if @BillType in(327,328,329)
		SET @SQL = @SQL + ' AND a.ApplyEtypeId=''' + @ETypeID + ''''
	else
		SET @SQL = @SQL + ' AND a.ETypeID=''' + @ETypeID + ''''
end
	
IF @DTypeID <> '' 
	SET @SQL = @SQL + ' AND a.DTypeID=''' + @DTypeID + ''''
	
IF @RATypeID <> '' 	
	SET @SQL = @SQL + ' AND be.RATypeID = ''' + @RATypeID + ''''
	
IF @strCurrencyID <> '' 		
	SET @SQL = @SQL + ' AND  a.CID =  ''' + @strCurrencyID + ''''
	
	
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC, a.BillCode'

PRINT(@SQL)
EXEC (@SQL)

DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' AND @BillType <> 177 DROP TABLE #F_BaseGetManDetailEType
IF @Stypeid<>'' or @chvMStypeid<>'00000' DROP TABLE #F_BaseGetManDetailSType
IF @DTypeID<>'' or @chvMDtypeid <>'00000' DROP TABLE #F_BaseGetManDetailDType 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryBillIndexAutoDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryBillIndexAutoDraft]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2004-11-04
	描述：重写了单据导入草稿的存储过程
	EXEC Gp_QueryBillIndexAutoDraft '2010-01-01','2020-12-31','34',00001
*/
CREATE  PROCEDURE Gp_QueryBillIndexAutoDraft
(
	@BeginDate		VARCHAR(25),	--开始时间
	@EndDate  		VARCHAR(25),	--截止时间
	@BillType		VARCHAR(10),	--单据类型 
	@OperatorId		VARCHAR(50)		--当前操作员
)
AS
SET NOCOUNT ON 

SELECT	DISTINCT
		a.createdate,
		a.billguid,
		a.BillNumberID,
		a.BillType,
		a.BillDate,
		a.BillCode,
		a.ETypeID,
		e.fullname AS efullname,
		a.dealbtypeid AS BTypeID,
		a.STypeID,
		s.FullName AS sfullname,
		a.Checke,
		a.DTypeID,
		d.FullName AS dfullname,
		a.Explain,
		a.Comment,
		a.dealbtypeid,
		db.FullName AS dbfullname,
		a.btypeid as jstypeid,
		btype.fullname as bfullname,
		a.totalmoney, a.tel, 
		RATypeID = '',
		a.explain,
		a.Comment,
		a.ktypeid,
		k.FullName AS kfullname,
		a.Stypeid,
		s.fullname AS sfullname,
		a.preferencemoney,
		a.VipCardID,
		a.warehouseoutday,
		a.linkAddr,
		a.linkman,
		a.linktel,
		a.ystotal,
		a.yftotal,
		a.costsale,
		a.ifinvoice,
		a.islend,
		a.isneedtransport,
		a.alertday,
		a.stockindeadline
FROM	BillIndexAutoDraft  a  
LEFT JOIN stype s ON a.sTypeID = s.TypeID  
LEFT JOIN btype ON btype.typeid=a.btypeid
LEFT JOIN btype db ON db.typeid = a.DealBTypeID
LEFT JOIN dbo.employee e ON e.typeid = a.etypeid  
LEFT JOIN dbo.Department d ON d.typeid = a.DTypeId
LEFT JOIN dbo.Stock k ON k.typeid = a.ktypeid
WHERE	a.BillDate >= @BeginDate 
		AND  a.BillDate <= @EndDate
		AND  a.BillType = @BillType
		AND  A.checke = @OperatorId
ORDER BY a.CreateDate DESC, a.BillCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON  
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryBillIndexDay]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryBillIndexDay]
GO


/*
	作者：谢吉康
	日期：2009-12-15
	描述：经营日报查询
	修改：增加折扣列
	
	作者：张陈仁
	日期：2011-7-18
	描述：经营日报查询
	
	修改：增加含税单价\含税金额\扣率\折后单价\折后金额\税率字段
	作者：黄清
	日期：2012-03-15
	
	修改：增加基本计量单位名称
	作者：杨俊
	日期：2014-10-17
	
	修改：增加pos名称查询
	作者: 陈强
	日期：2019-09-17
*/
CREATE PROCEDURE Gp_QueryBillIndexDay
(
	@chvStartDate		varchar(30),			--  2、查询起始时间
	@chvEndDate			varchar(30),			--  3、查询结束时间
	@chvPTypeID			varchar(max),			--  5、商品ID
	@dealBTypeID		varchar(max),			--  6、往来单位 ID
	@chvETypeID			varchar(max),			--  7、职员类 ID
	@chvKTypeID			varchar(max),			--  8、仓库 ID
	@STypeId			varchar(max),			--  分支机构
	@chvOrderBy			varchar(500),			--  9、明细表排序方式
	@chvCheckeCode		varchar(max)	= '',	-- 10、制单人编号
	@chvCheckeName		varchar(max)	= '',	-- 11、制单人名称
	@intPageNo			int		= '',			-- 12、当前查询的页码
	@intPageSize		int		= '',			-- 13、每页的显示记录数
	@chvOperatorID		varchar(500),			-- 14、操作员 ID ( 作权限范围检查用 )
	@chvDX				char(1) ='0',
	@chrFlag			char(1),					-- 15、功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@billtypes			VARCHAR(max),			--9.3新加单据类型
	@ptypecategoryid	varchar(max),			--商品类别
    @flag               INT,                    --0为不显示序列号,1为显示序列号 
    @posid				VARCHAR(256)			--新增	对应版本9.91
)
--@encode$--

AS
SET ANSI_WARNINGS ON
SET NOCOUNT ON 
--------	权限检查 - Start	--------

if @chvOperatorID is null return 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
if @intRe <> 0 return @intRe
--------	权限检查 - End		--------     

if  @chvPTypeID ='' 
	SET @chvPTypeID= '00000'

if @dealBTypeID =''
	SET @dealBTypeID= '00000'

if @chvETypeID =''
	SET @chvETypeID= '00001'

if @chvKTypeID =''
	SET @chvKTypeID= '00000'

-- 定义 SQL 条件语句变量
DECLARE @SQL_WHERE varchar(max)
SELECT @SQL_WHERE = ''

-- ********	确定查询时间段 - End	********
DECLARE @sqlman VARCHAR(max)='' 

/**/
CREATE TABLE #GetManPTypeId(TypeId	varchar(500))
CREATE TABLE #GetManBTypeId(TypeId	varchar(500))
CREATE TABLE #GetManETypeId(TypeId	varchar(500))
CREATE TABLE #GetManDTypeId(TypeId	varchar(500))
CREATE TABLE #GetManKTypeID(TypeId	varchar(500))
CREATE TABLE #GetManSTypeId(TypeId	varchar(500))
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@STypeId,11,@chvOperatorID,'#GetManSTypeId')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@dealBTypeID,2,@chvOperatorID,'#GetManBTypeId')
--SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@chvPTypeID,1,@chvOperatorID,'#GetManPTypeId')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@chvETypeID,3,@chvOperatorID,'#GetManETypeId')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId('',9,@chvOperatorID,'#GetManDTypeId')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@chvKTypeID,4,@chvOperatorID,'#GetManKTypeID')

--PRINT @sqlman
EXEC(@sqlman)

IF @dealBTypeID = '00000'
	INSERT INTO #GetManBTypeId(TypeId)VALUES('')

IF @ptypecategoryid<>'' OR @MPtypeid='-99999' OR @chvPTypeID<>''
	INSERT #GetManPTypeId
	SELECT TypeId
	FROM dbo.F_ManPTypeInCategoryID(@chvOperatorID,@chvPTypeID,@ptypecategoryid)

--*******************************************************************************************************特殊处理仓库*******************************************************************************************************--

IF @chvKTypeID <> '00000'
	BEGIN
		IF @chvDX ='1'
			INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')			
	END
ELSE
	INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')



IF NOT (@dealBTypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	CREATE CLUSTERED INDEX CIX_BID ON #GetManBTypeId(typeid)
IF NOT (@chvKTypeID = '00000' AND @MKTypeId = '00000')
	CREATE CLUSTERED INDEX CIX_BID ON #GetManKTypeId(typeid)
IF NOT @MDtypeid = '00000'
	CREATE CLUSTERED INDEX CIX_BID ON #GetManDTypeId(typeid)
IF NOT (@chvPTypeId = '00000' AND @MPTypeId = '00000')	
	CREATE CLUSTERED INDEX CIX_BID ON #GetManPTypeId(typeid)	
IF NOT (@chvETypeId = '00001' AND @METypeId = '00001')
	CREATE CLUSTERED INDEX CIX_BID ON #GetManETypeId(typeid)


--删除仓库内的数据
IF  NOT (@STypeId = '' AND @MStypeid = '00000'  )
	DELETE FROM #GetManKTypeId WHERE TypeId NOT IN (SELECT TypeId FROM Stock WHERE STypeID IN (SELECT TypeId FROM #GetManSTypeId))

/*select k.TypeId into #aa from #GetManKTypeId k inner join Stock  k1 on k.TypeId=k1.typeId inner join #GetManSTypeId s on k1.STypeID=s.TypeId
truncate table #GetManKTypeId
insert into #GetManKTypeId select * from #aa*/
--*******************************************************************************************************特殊处理仓库*******************************************************************************************************--

-- 筛选制单人
IF @chvCheckeCode <> '' OR @chvCheckeName <> ''
	SELECT @SQL_WHERE = @SQL_WHERE + ' and c.usercode like '+char(39)+'%'+@chvCheckeCode+'%'+char(39) + ' and c.fullname like '+char(39)+'%'+@chvCheckeName+'%'+char(39)

-- ********	排序方式 - Start	********

-- 定义排序的 SQL 条件语句变量
DECLARE @SQL_ORDER varchar(max)
SELECT @SQL_ORDER = ''

SELECT @SQL_ORDER = 
	CASE @chvOrderBy
		WHEN 'ByDate_a'		THEN ' ORDER BY a.BillDate,b.BillCode,a.BillType'	-- 按日期排序
		WHEN 'ByBillNo_a'	THEN ' ORDER BY b.BillCode'				-- 按单据编号排序
		WHEN 'ByBillType_a'	THEN ' ORDER BY a.BillType, a.BillDate, b.BillCode'	-- 按单据类型排序
		WHEN 'ByBillID_a'	THEN ' ORDER BY b.posttime,b.BillCode'					-- 按单据真实过帐顺序排序
		WHEN 'ByDate_d'		THEN ' ORDER BY a.Billdate DESC,b.BillCode,a.BillType'
		WHEN 'ByBillNo_d'	THEN ' ORDER BY b.BillCode DESC'
		WHEN 'ByBillType_d'	THEN ' ORDER BY a.BillType DESC,b.BillCode,a.BillDate'
		WHEN 'ByBillID_d'	THEN ' ORDER BY b.posttime desc,b.BillCode DESC'
		WHEN 'ByBillID_a'	THEN ' ORDER BY b.posttime asc,b.BillCode asc'
		ELSE ' ORDER BY a.BillDate,b.BillCode'
		END
-- ********	排序方式 - End	********

-- 定义 SQL 主体语句变量
DECLARE @SQL varchar(max)
SELECT @SQL = ''


-- 建立查询临时表 ( 表中的记录条数将为 intPageSize )
CREATE TABLE #Detail (
	nID				numeric(18,0),	--ID
	BillNumberID	numeric(10,0),	-- 单据ID值
	BillDate		datetime,	-- 单据日期
	BillCode		varchar(200),	-- 单据编号  -- #&**&#
	BillType		numeric(4,0),	-- 单据类型
	BillTypeName	varchar(20), -- 单据类型名称
	PName	        varchar(100),-- 商品名称
	BName			varchar(100),	-- 客户名称
	STypeId			varchar(max),	-- 分支机构
	Qty				 NUMERIC(24, 10) ,	-- 数量
	Discount		 NUMERIC(24, 10) ,	-- 折扣
	salePrice			 NUMERIC(24, 10) ,	-- 单价
	saleTotal			 NUMERIC(24, 10) ,	-- 销售金额 ( 折后、税前 )
	CostPrice		 NUMERIC(24, 10) ,	-- 成本单价
	CostTotal		 NUMERIC(24, 10) ,	-- 成本金额
	preferencemoney  NUMERIC(24, 10) , --优惠金额
	MaoLi			 NUMERIC(24, 10) ,	-- 毛利
	EName			varchar(500),	-- 经手人名称
	KName			varchar(500),	-- 仓库名称
	checke			varchar(500),	-- 制单人id
	RowsCount		numeric(18,0),
	Comment			varchar(2000),
	Explain			varchar(2000),
	TaxPrice		 NUMERIC(24, 10) ,  --含税单价
	TaxTotal		 NUMERIC(24, 10) ,	--含税金额
	Tax				 NUMERIC(24, 10) ,	--税率
	Price	 NUMERIC(24, 10) ,	--折后单价
	Total	 NUMERIC(24, 10) ,	--折后金额
	CustomdetailID   INT,
	Serial                     VARCHAR(200),
	goodsnumber               VARCHAR(100),
	redword INT,
	baseUnitName VARCHAR(20),   --基本计量单位名称 9.5增加
	posid			INT			--pos名称	9.91增加
)

-- 数据库游标方式查询明细记录
-- 1 - 按 @intPageSize 记录数进行分页查询；
-- 2 - 查询所有记录 ( 打印报表专用 )；

-- 获取记录总行数
DECLARE @RowsCount 	int,
		@nID		int


	BEGIN
		CREATE TABLE #InOutStockTable
		(
			BillNumberId		numeric(18,0),
			BillDate			datetime,
			BillType			int,
			PTypeId				varchar(500),
			KTypeID				varchar(500),
			Qty					 NUMERIC(24, 10) ,
			salePrice			 NUMERIC(24, 10) ,
			saleTotal			 NUMERIC(24, 10) ,
			CostPrice			 NUMERIC(24, 10) ,
			Discount             NUMERIC(24, 10) ,
			CostTotal			 NUMERIC(24, 10) ,
			TaxPrice			 NUMERIC(24, 10) ,  --含税单价
			TaxTotal			 NUMERIC(24, 10) ,	--含税金额
			Tax					 NUMERIC(24, 10) ,	--税率
			Price		 NUMERIC(24, 10) ,	--折后单价
			Total		 NUMERIC(24, 10) ,	--折后金额
			id			INT,
			goodsnumber VARCHAR(200)
		)
	SET @SQL = @SQL +'
		INSERT INTO #InOutStockTable(BillNumberId,BillDate,BillType,PTypeId,KTypeID,Qty,salePrice,saleTotal,CostPrice,Discount,CostTotal,TaxPrice,TaxTotal,Tax,Price,Total,id,goodsnumber)
		'						  			
		--EXEC(@SQL)
		SET @SQL += '
		SELECT	
		        DISTINCT
		        InOutStockTable.BillNumberId,
				InOutStockTable.BillDate,
				InOutStockTable.BillType,
				InOutStockTable.PTypeId,
				
				InOutStockTable.KTypeID,
				Qty,
				case  
					when InOutStockTable.BillType = 17 then 0
					else isnull(saleprice,0)
				end as saleprice,	--折前单价
				case 
					WHEN InOutStockTable.BillType IN( 17,9,14,126,139) THEN 0
					ELSE isnull(saleTotal,0)
				end as saleTotal,	--折前金额
				CostPrice,
				InOutStockTable.Discount,
				CostTotal,
				case 
					WHEN InOutStockTable.BillType IN( 201,202) THEN 0
					ELSE isnull(TaxPrice,0)
				end as TaxPrice,
				case 
					WHEN InOutStockTable.BillType IN( 201,202) THEN 0
					ELSE isnull(TaxTotal,0)
				end as TaxTotal,
				InOutStockTable.Tax,	--税率
				case  
					when InOutStockTable.BillType in ( 17,9,14,126,139,201,202) then 0
					else isnull(price,0)
				end as price,	--折后单价
				case 
					WHEN InOutStockTable.BillType IN( 17,9,14,126,139,201,202) THEN 0
					ELSE isnull(Total,0)
				end as Total,	--折后金额
				InOutStockTable.id,
				InOutStockTable.goodsnumber
		FROM	InOutStockTable WITH(INDEX(CIX_INOUTSTOCKTABLE_BillDate))
				inner join billindex b ON b.billnumberid=inoutstocktable.billnumberid AND inoutstocktable.billtype = b.billtype '
	IF	@chvKTypeID !='00000' /*选了具体仓库,调全部仓库的成本调价单不显示*/
			SET @SQL+=' AND b.ktypeid<>''00000'' '
	
	SET @SQL+=' left  JOIN Employee c ON b.Checke = c.TypeId '
	SET @SQL=@SQL+@SQL_WHERE
		IF NOT (@chvPTypeId = '00000' AND @MPTypeId = '00000' AND @ptypecategoryid='')
			SET @SQL = @SQL + ' INNER JOIN #GetManPTypeId P ON P.TypeId = inoutstocktable.PTypeId '

		IF NOT (@dealBTypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId MB ON MB.TypeId = inoutstocktable.btypeid '

		IF NOT (@chvETypeId = '00001' AND @METypeId = '00001')
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = inoutstocktable.ETypeId '

		IF NOT (@chvKTypeID = '00000' AND @MKTypeId = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId M ON M.TypeId = InOutStockTable.KTypeId OR  InOutStockTable.KTypeId=''10000'' '	
					
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON InOutStockTable.STypeId = S.TypeId '	
			
		IF NOT @MDtypeid = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = InOutStockTable.DTypeId '	
		SET @SQL = @SQL +'		
		WHERE	
		InOutStockTable.BillDate>='''+@chvStartDate+'''
				AND InOutStockTable.BillDate<='''+@chvEndDate+'''
				AND Audited = 1 
				AND InOutStockTable.BillType NOT IN (178,186,205,206)
				AND InOutStockTable.KTypeID <>
						    case when InOutStockTable.BillType in (140,142,144,146) THEN ''10000''
								 else ''''
							end 
				 '		--代销库	
		IF @chvCheckeCode <> '' 
		BEGIN 
			SET @SQL=@SQL+' AND c.usercode like '+char(39)+'%'+@chvCheckeCode+'%'+char(39)+' '
		END
		IF @chvCheckeName <> ''
		BEGIN
			SET @SQL=@SQL+' AND c.FULLNAME like '+char(39)+'%'+@chvCheckeName+'%'+char(39)+' '
		END	
		IF @billtypes<>''
		BEGIN
			SET @sql=@sql+' AND InOutStockTable.BILLTYPE IN ('+@billtypes+')'
		END	
		
		EXEC(@SQL)
		
		
	
		SELECT @RowsCount = @@ROWCOUNT
		
		SET @sql = ' INSERT INTO #InOutStockTable(BillNumberId,BillDate,BillType,PTypeId,KTypeID,Qty,salePrice,saleTotal,CostPrice,Discount,CostTotal,TaxPrice,TaxTotal,Tax,Price,Total,id,goodsnumber)
		SELECT	Wx_InOutStockTable.BillNumberId,
				Wx_InOutStockTable.BillDate,
				Wx_InOutStockTable.BillType,
				Wx_InOutStockTable.PTypeId,
				Wx_InOutStockTable.KTypeID,
				Qty,
				case  
					when Wx_InOutStockTable.BillType = 17 then 0
					else isnull(saleprice,0)
				end as saleprice,	--折前单价
				case 
					WHEN Wx_InOutStockTable.BillType IN( 17,9,14,126,139,201,202) THEN 0
					ELSE isnull(saleTotal,0)
				end as saleTotal,	--折前金额
				CostPrice,
				Wx_InOutStockTable.Discount,
				CostTotal,
				TaxPrice,	--含税单价
				TaxTotal,	--含税金额
				Wx_InOutStockTable.Tax,		--税率
				case  
					when Wx_InOutStockTable.BillType = 17 then 0
					else isnull(price,0)
				end as price,	--折后单价
				case 
					WHEN Wx_InOutStockTable.BillType IN( 17,9,14,126,139,201,202) THEN 0
					ELSE isnull(Total,0)
				end as Total,	--折后金额
				Wx_InOutStockTable.id,
				Wx_InOutStockTable.goodsnumber
		FROM	Wx_InOutStockTable 
				inner join billindex b on b.billnumberid=Wx_InOutStockTable.billnumberid and Wx_InOutStockTable.billtype = b.billtype
				INNER JOIN Employee c ON b.Checke = c.TypeId '
	SET @SQL=@SQL+@SQL_WHERE 
		IF NOT (@chvPTypeId = '00000' AND @MPTypeId = '00000'  AND @ptypecategoryid='')
			SET @SQL = @SQL + ' INNER JOIN #GetManPTypeId P ON P.TypeId = Wx_InOutStockTable.PTypeId '

		IF NOT (@dealBTypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId MB ON MB.TypeId = Wx_InOutStockTable.btypeid '

		IF NOT (@chvETypeId = '00001' AND @METypeId = '00001')
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = Wx_InOutStockTable.ETypeId '

		IF NOT (@chvKTypeID = '00000' AND @MKTypeId = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId M ON M.TypeId = Wx_InOutStockTable.KTypeId '	
					
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Wx_InOutStockTable.STypeId = S.TypeId '	
			
		IF NOT @MDtypeid = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Wx_InOutStockTable.DTypeId '	
		SET @SQL = @SQL +'		
		WHERE	Wx_InOutStockTable.BillDate>='''+@chvStartDate+'''
				AND Wx_InOutStockTable.BillDate<='''+@chvEndDate+'''
				and
				b.BillDate>='+char(39)+@chvStartDate+char(39)+'
						AND b.BillDate<='+char(39)+@chvEndDate+char(39)+'
						AND Wx_InOutStockTable.BillDate>='+char(39)+@chvStartDate+char(39)+'
						AND Wx_InOutStockTable.BillDate<='+char(39)+@chvEndDate+char(39)+'
				
				
				AND b.RedWord = ''0''
						AND b.Draft = ''0''	
						AND b.IfYearBill = 0					
						AND b.BillType NOT IN (178,186,205,206)
						AND Wx_InOutStockTable.KTypeID <>
						    case when Wx_InOutStockTable.BillType in (140,142,144,146) THEN ''10000''
								 else ''''
							end '			
		IF @chvCheckeCode <> '' 
		BEGIN 
			SET @SQL=@SQL+' AND c.usercode like '+char(39)+'%'+@chvCheckeCode+'%'+char(39)+' '
		END
		IF @chvCheckeName <> ''
		BEGIN
			SET @SQL=@SQL+' AND c.FULLNAME like '+char(39)+'%'+@chvCheckeName+'%'+char(39)+' '
		END			
		IF @billtypes<>''
		BEGIN
			SET @sql=@sql+' AND Wx_InOutStockTable.BILLTYPE IN ('+@billtypes+')'
		END	
		--PRINT(@sql)
		EXEC(@SQL)
		SELECT @RowsCount = @RowsCount+@@ROWCOUNT
				
	CREATE TABLE #Serial
	( 
	   billnumberid NVARCHAR(200),
	   id            INT,
	   Serial		 NVARCHAR(200)
	)
	
	CREATE TABLE #temp
	(
	   tablename NVARCHAR(200)

	)
	
IF @billtypes!=''	
 BEGIN
    INSERT INTO #temp( tablename )
	SELECT detailTable FROM dbo.BillName a INNER JOIN dbo.f_split(@billtypes,',') b ON a.Billtype= b.a GROUP BY a.detailTable
END 
ELSE
  BEGIN
	INSERT INTO #temp( tablename )
	SELECT detailTable FROM dbo.BillName a WHERE Billtype IN ('305','215','11','45','160','139','140','34','6','161','126','17','21','187','201','9','14','16','165','166','167','168','169','170','172','173','174','175','183','400','401','402','403','57','12','46')
  END
 
--SELECT * FROM  #temp --测试代码
 DECLARE @tablename VARCHAR(800);
 DECLARE @aaa NVARCHAR(max)=''
 IF @flag=1
 BEGIN
	   -- 定义游标.
	   DECLARE c_test_main CURSOR FAST_FORWARD FOR
		 SELECT tablename FROM #temp;
	   -- 打开游标.
	   OPEN c_test_main;
	   --填充数据.
	   FETCH NEXT FROM c_test_main INTO @tablename;
	   --假如检索到了数据，才处理.
	   WHILE @@fetch_status = 0
	   BEGIN
		 SET @aaa= 'INSERT INTO #Serial( billnumberid, id, Serial )
		 (select
	   a.BillNumberId,a.ID,b.Serial
		from 
		(SELECT a.BillNumberId ,a.ID,Serial=convert(xml,''<root><v>''+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),Serial),''&'',''&amp;'')),''я'',''</v><v>'')+''</v></root>'') from '+ @tablename +' a INNER        JOIN #InOutStockTable b ON a.BillNumberId=b.BillNumberId AND a.id=b.id GROUP BY a.BillNumberId,a.ID ,CONVERT(varchar(max),Serial) )a 
		outer apply
		(select Serial=C.v.value(''.'',''nvarchar(100)'') from a.Serial.nodes(''/root/v'')C(v))b WHERE b.Serial!='''')'
		--PRINT @aaa
		EXEC(@aaa)
		 --填充下一条数据.
		 FETCH NEXT FROM c_test_main INTO @tablename;
	   END;
	   -- 关闭游标
	   CLOSE c_test_main;
	   --释放游标.
	   DEALLOCATE c_test_main;
 END;
	IF @flag = 1
	BEGIN 
		SELECT @RowsCount = COUNT(1) FROM #InOutStockTable a
	lEFT JOIN #Serial cru  ON a.BillNumberID = cru.BillNumberID  
			AND cru.id=a.id
	END

	END

IF @chrFlag = '1' OR @chrFlag = '2'		/*1 - 分页查询记录；2 - 打印查询所有记录---------开始*/
	BEGIN
	
		-- 定义相关数据变量
		-- 单据编号自定义改变长度  200  chen_qihua -- #&**&#		
		DECLARE @BillNumberID numeric(10,0), @BillDate datetime, @BillCode varchar(200), @BillType numeric(4,0), @PTypeID varchar(500), @BTypeID varchar(500), @Qty  NUMERIC(24, 10) ,@Discount  NUMERIC(24, 10) ,@Price  NUMERIC(24, 10) , @Total  NUMERIC(24, 10) , @CostPrice  NUMERIC(24, 10) , @CostTotal  NUMERIC(24, 10) ,@preferencemoney  NUMERIC(24, 10) , @ETypeID varchar(500), @KTypeID varchar(500), @Checke varchar(500), @ID numeric(10,0)
		
		DECLARE @BillTypeName varchar(500), @FullName varchar(500), @BName varchar(500), @EName varchar(500), @KName varchar(500), @CheckeName varchar(500), @MaoLi  NUMERIC(24, 10) , @MaoLiLu  NUMERIC(24, 10) 
		DECLARE @UserCode varchar(200),@Comment varchar(2000),@Standard varchar(200),@Type varchar(500),@Area varchar(500),@Unit varchar(500),@Explain varchar(2000),@BSTypeId varchar(500)




		SELECT @SQL = '
				SELECT	top 100 PERCENT
						b.BillNumberID,
						a.BillDate,
						b.BillCode,
						a.BillType,
						a.PTypeID,
						b.dealbtypeid,
						b.STypeID,
						isnull(a.Qty,0) as qty,
						ISNULL(a.discount,1) AS discount,
						a.saleprice,
						a.saleTotal,
						isnull(a.CostPrice,0) as costPrice,
						isnull(a.CostTotal,0) as CostTotal,
						isnull(b.preferencemoney,0) as preferencemoney,
						b.ETypeID,
						a.KTypeID,
						b.Checke,
						b.Comment,
						b.Explain,
						a.TaxPrice, 
						a.TaxTotal,	
						a.Tax,
						a.price,
						a.Total,
						case when a.BillType  IN (155,157,160,166,172) and qty<0 then ( abs(Total) - abs(CostTotal) )
							when a.BillType= 160 and qty>0 then ( abs(CostTotal) - abs(Total) )
							when a.BillType IN(45,215,197,46) then -( abs(Total) - abs(CostTotal) )
							when a.BillType in(11,305,141,187,188,196,191,12) then ( abs(Total) - abs(CostTotal) )
							when a.BillType in(400,402) then ( abs(Total) - abs(CostTotal) )
							when a.BillType in(401,403) then -( abs(Total) - abs(CostTotal) )
							else 0
						end as maoli,	-- 毛利 
						a.id as  CustomdetailID ,
						a.goodsnumber, '
						IF @flag=1
						 	set @sql+='cru.Serial, '
						 else 	
				        	set @sql+='NULL AS Serial, '
					 set @sql+=' ROW_NUMBER() OVER( '+@SQL_ORDER+') as rownum,a.id,
					 b.redword,
					 PU.FullName AS baseUnitName ,
					 b.AdPriceType, --业务类型
					 b.posid
				FROM	BillIndex b
				INNER JOIN Employee c ON b.Checke = c.TypeId
				inner JOIN #InOutStockTable  a ON a.BillNumberID = b.BillNumberID  
				--基本计量单位名称 9.5增加
				INNER JOIN Ptype AS P ON(A.PTypeID = P.Typeid)
				INNER JOIN PType_Units AS PU ON(P.baseUnitId = PU.UnitsId)  '
				IF @flag=1
				  Begin 
				     set @sql+=' LEFT JOIN #Serial cru  ON b.BillNumberID = cru.BillNumberID  
				AND cru.id=a.id ' 
				  end  	
			  set @sql+='	WHERE 1=1'+@SQL_WHERE

			SET @SQL = '
						INSERT INTO #Detail (	
								nID,				
								BillNumberID,	-- 单据ID值
								BillDate	,	-- 单据日期
								BillCode	,	-- 单据编号
								BillType	,	-- 单据类型
								BillTypeName,	-- 单据类型名称
								PName		,	-- 商品名称
								BName		,	-- 客户名称
								STypeId		,	-- 分支机构
								Qty		    ,	-- 数量
								Discount    ,   -- 折扣
								salePrice		,	-- 折前单价
								saleTotal		,	-- 折前金额 
								CostPrice	,	-- 成本单价
								CostTotal	,	-- 成本金额
								preferencemoney,-- 优惠金额
								MaoLi		,	-- 毛利
								EName		,	-- 经手人名称
								KName		,	-- 仓库名称
								checke	,	-- 制单人ID
								RowsCount	, 
								Comment,
								Explain,
								TaxPrice,  --含税单价
								TaxTotal,	--含税金额
								Tax	,	--税率
								Price,	--折后单价
								Total,	--折后金额
								CustomdetailID,
								Serial,                  
								goodsnumber,
								redword,
								baseUnitName,
								posid
								)
						SELECT  
								rownum,
								BillNumberID,	-- 单据ID值
								BillDate	,	-- 单据日期
								BillCode	,	-- 单据编号
								BillType	,	-- 单据类型
								'''' as BillTypeName,			-- 单据类型名称
								ptypeid		,	-- 商品名称
								dealbtypeid		,	-- 客户名称
								STypeId		,	-- 分支机构
								Qty		    ,	-- 数量
								Discount    ,   --折扣
								salePrice		,	-- 折前单价
								saleTotal		,	-- 折前金额 ( 折后、税前 )
								CostPrice	,	-- 成本单价
								costtotal=CASE WHEN a.BillType IN(45,215,197,46)  THEN -(CASE WHEN a.AdPriceType=1 THEN CostTotal	ELSE ABS(CostTotal) END) ELSE (CASE WHEN a.AdPriceType=1 THEN CostTotal	ELSE ABS(CostTotal) END) END ,	-- 成本金额
								preferencemoney,--优惠金额
								a.maoli,	-- 毛利
								etypeid		,	-- 经手人名称
								ktypeid		,	-- 仓库名称
								checke	,	-- 制单人ID
								-1 as rowscount	, 
								Comment,
								Explain,
								TaxPrice,  --含税单价
								TaxTotal,	--含税金额
								Tax,	--税率
								Price,	--折后单价
								Total,	--折后金额
								CustomdetailID,
								Serial       ,
								goodsnumber,
								redword,
								baseUnitName,
								posid
					FROM 	('+@SQL+') a '
	IF @chrFlag = '1'
		set @SQL=@SQL+'
					WHERE  	
							 a.rownum>'+CAST((@intPageNo-1)*@intPageSize as varchar(100))+'
							AND a.rownum<='+CAST(@intPageNo*@intPageSize as varchar(100))	
	
	
		-----9.91新增 根据posid进行筛选-----
		IF @posid <>''
			SELECT @SQL = @SQL +' AND a.posid in('+@posid+') '
	
		--PRINT(@SQL)				
		EXEC(@SQL)
		--成本调价单以下几列处理为0 (961需求)
		UPDATE #Detail SET saleprice=0,saleTotal=0,Price=0,Total=0,TaxPrice=0,TaxTotal=0,MaoLi=0 WHERE BillType=57
		
		--=========================================明细自定义==================================================
			
			IF @chrFlag = '1'
			BEGIN
						--总的记录数
						--SELECT @RowsCount = COUNT(1) FROM #BillIndex
						-- 在临时表最后增加一行，记录总记录行数
						INSERT INTO #Detail (
							nID,
							RowsCount
						)
						VALUES (
							999989976,
							@RowsCount
						)
			  END		
			
			  SELECT	R.*,SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head,
				SysDiy33_head,
				SysDiy34_head,
				SysDiy35_head,
				SysDiy36_head,
				SysDiy37_head,
				SysDiy38_head,
				SysDiy39_head,
				SysDiy40_head,
				csdetail.*,
				r.billtype as billtypes,r.qty as qty1
				FROM	#Detail R 
				left join Custom_BillIndex csindex on r.billnumberid=csindex.BillId and r.billtype=csindex.billtype
				left join Custom_BillDetails csdetail on r.billnumberid=csdetail.BillId and r.billtype=csdetail.billtype AND r.CustomdetailID=csdetail.Detailid
				LEFT JOIN employee e ON e.typeId = r.Checke ORDER BY R.nID
			  --SELECT d.*,e.FullName AS CheckeName FROM #Detail d LEFT join employee e ON e.typeId = d.Checke ORDER BY d.nID
			END
			
										/*1 - 分页查询记录；2 - 打印查询所有记录---------结束*/
	
	
	
	


-- 所有明细合计，合计项如下：

-- 1、数量
-- 2、销售金额 ( 折后、税前 )
-- 3、价税合计
-- 4、成本金额
-- 5、毛利 ( 不在存储过程中合计，而在 ASP 页面中用 销售金额合计值 - 成本金额合计值 )

IF @chrFlag = '3'	/*3 - 合计值---------开始*/
	BEGIN
	
		CREATE TABLE #Temp_Table
		(
			BillNumberId		numeric(18,0),
			--PTypeId				varchar(100),
			Sum_Qty				 NUMERIC(24, 10) ,
			Sum_saleTotal		 NUMERIC(24, 10) ,
			Sum_Total			 NUMERIC(24, 10) ,
			Sum_taxTotal		 NUMERIC(24, 10) ,
			Sum_CostTotal		 NUMERIC(24, 10) ,
			Sum_preferencemoney	 NUMERIC(24, 10) ,
			Sum_MaoLi			 NUMERIC(24, 10) ,
			goodsnumber         varchar(200),
			BillType		numeric(4,0),	-- 单据类型
		)

		SELECT @SQL = '	SELECT	 A.billnumberid,
								 SUM(a.qty) AS Sum_Qty,
								 SUM(a.saleTotal) AS Sum_saleTotal,
								 SUM(A.Total) AS Sum_Total,
								 SUM(A.taxTotal) AS Sum_taxTotal,
								   SUM(CASE WHEN a.BillType IN(45,215,197,46) THEN -(CASE WHEN b.AdPriceType=1 THEN A.CostTotal ELSE ABS(A.CostTotal) END) 
												ELSE (CASE WHEN b.AdPriceType=1 THEN A.CostTotal ELSE ABS(A.CostTotal) END) END ) AS Sum_CostTotal,
								 sum(isnull(b.preferencemoney,0)) AS preferencemoney,
								 SUM(case when a.BillType  IN (155,157,160,166,172) and qty<0 then ( abs(Total) - abs(CostTotal) )
									when a.BillType= 160 and qty>0 then ( abs(CostTotal) - abs(Total) )
									when a.BillType IN(45,215,197,46,403) then -( abs(Total)-abs(CostTotal) )
									when a.BillType in(11,305,141,187,188,196,191,12,402) then ( abs(Total) - abs(CostTotal) )
									else 0
								end)  AS Sum_MaoLi,
								a.goodsnumber,
								b.billtype
						FROM	BillIndex b						
								INNER JOIN #InOutStockTable a ON B.BillNumberID = A.BillNumberID '

		-- 筛选制单人
		IF @chvCheckeCode <> '' OR @chvCheckeName <> ''
			SELECT @SQL = @SQL + ' INNER JOIN Employee c ON b.Checke = c.TypeId '

		SELECT @SQL = @SQL + '
			WHERE	b.BillDate>='+char(39)+@chvStartDate+char(39)+'
					AND b.BillDate<='+char(39)+@chvEndDate+char(39)+'
					AND a.BillDate>='+char(39)+@chvStartDate+char(39)+'
					AND a.BillDate<='+char(39)+@chvEndDate+char(39)+'
					AND b.RedWord = ''0''
					AND b.Draft = ''0''
					AND b.BillType NOT IN (178,186,205,206)
						'

		SELECT @SQL = @SQL + @SQL_WHERE +' GRoup by A.billnumberid,a.goodsnumber,b.billtype'
		
		SET @SQL = 'INSERT INTO #Temp_Table '+@SQL
		
	
		PRINT(@SQL)
		EXEC (@SQL)
		--成本调价单以下两列给0 (961需求)
		UPDATE #Temp_Table SET Sum_saleTotal=0,sum_total=0,Sum_taxTotal=0,Sum_MaoLi=0 WHERE billtype=57  
		
		IF EXISTS(select TOP 1 BillnumberID FROM #Temp_Table where BillnumberID IN (select BillnumberID From billindex where (BillType ='34'  or BillType ='21' or BillType ='16' or BillType ='57' or BillType ='6' or BillType ='17' or BillType ='144' or BillType ='145' or BillType ='146' or BillType ='147' or BillType ='155' or BillType ='157' or BillType ='173' or BillType ='174' or BillType ='187'or BillType ='188')))
			BEGIN
				SELECT 
						isnull(sum(isnull(X.sum_qty,0)),0) as sum_qty,
						isnull(sum(isnull(X.Sum_saleTotal,0)),0) as Sum_saleTotal,
						isnull(sum(isnull(X.Sum_Total,0)),0) as Sum_Total,
						isnull(sum(isnull(X.Sum_taxTotal,0)),0) as Sum_taxTotal,
						isnull(sum(isnull(X.Sum_CostTotal,0)),0) as Sum_CostTotal,
						CAST(isnull(sum(isnull(X.sum_preferencemoney,0)/qty),0) AS  NUMERIC(24, 10) ) as sum_preferencemoney,
						isnull(sum(isnull(X.Sum_MaoLi,0)),0) as Sum_MaoLi,
						haveCost ='1'
				FROM (
					SELECT 	a.*,
							b.qty 
					FROM	#Temp_Table a,
							(SELECT  billnumberid ,count(billnumberid) as qty from  #Temp_Table GROUP BY Billnumberid) b 
					where a.billnumberid=b.billnumberid
				) X
			END
		ELSE
			BEGIN
				SELECT 
						isnull(sum(isnull(X.sum_qty,0)),0) as sum_qty,
						isnull(sum(isnull(X.Sum_saleTotal,0)),0) as Sum_saleTotal,
						isnull(sum(isnull(X.Sum_Total,0)),0) as Sum_Total,
						isnull(sum(isnull(X.Sum_taxTotal,0)),0) as Sum_taxTotal,
						isnull(sum(isnull(X.Sum_CostTotal,0)),0) as Sum_CostTotal,
						CAST(isnull(sum(isnull(X.sum_preferencemoney,0)/qty),0) AS  NUMERIC(24, 10) ) as sum_preferencemoney,
						isnull(sum(isnull(X.Sum_MaoLi,0)),0) as Sum_MaoLi,
						haveCost ='0'
				FROM (
					SELECT	a.*,
							b.qty 
					FROM 	#Temp_Table a,
						(SELECT  billnumberid ,count(billnumberid) as qty from  #Temp_Table GROUP BY Billnumberid) b 
					where a.billnumberid=b.billnumberid
				) X
			END
		DROP TABLE #Temp_Table
	END

					/*3 - 合计值---------结束*/
DROP TABLE #GetManKTypeID,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#InOutStockTable,#Detail

--IF @chrFlag <>3 
--BEGIN
--	DROP TABLE #tmp_result_t
--END

IF EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[#tmp_result_t]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	DROP TABLE #tmp_result_t
END

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryBillIndexLi]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryBillIndexLi]
GO



/*
	作者：谢吉康
	日期：2007-3-7
	描述：经营历程的报表查询
*/
/*
	修改：李灏龙
	日期：2012年4月19日10:05:09
	描述：增添标识销售单按成本出售
		  具体修改：zs001
*/
/*
	修改：杨俊
	日期：2014-10-15
	描述：9.5新增查询条件
*/
/*
	修改：陈强
	日期：2019-09-17
	描述：9.91新增查询条件(根据Pos名称查询)
*/


CREATE PROCEDURE Gp_QueryBillIndexLi
( 
	@OperatorID			varchar(100) 	,  			-- 操作员
	@BillType	 		varchar(MAX)   	='',		-- 单据类型
	@BeginDate	 		varchar(25)  	='', 		-- 开始时间
	@EndDate	 		varchar(25)  	='',   		-- 结束时间
	@BillCode	 		varchar(200) 	='',  		-- 单据编号#&**&#
	@EtypeName	 		varchar(MAX)	='',    	-- 经手人名称
	@BtypeName	 		varchar(MAX)	='',     	-- 结算单位名称
	@KtypeName	 		varchar(MAX)	='', 		-- 仓库1
	@KtypeName2 		varchar(MAX)	='',		-- 仓库2
	@AtypeName	 		varchar(MAX)	='',		-- 科目
	@PTypeName    		varchar(MAX)	='',  		-- 商品id 
	@ptypecategoryid    varchar(MAX)	='',  		-- 商品类别id 
	@Comment	 		varchar(2000)	='',		-- 摘要
	@OrderBy	 		varchar(MAX)	='',     	-- 排序
	@Filter 			varchar(250)	='',    	-- 过滤条件
	@ZYDetail   		varchar(255)	='',  		-- 单据明细摘要
	@StartMoney 		NUMERIC(24, 10) 	,  			-- 金额起始
	@EndMoney   		NUMERIC(24, 10) 	,  			-- 金额大于
	@redword    		varchar(66)		='',   		-- 是否红冲
	@chrFlag			char(1)		    ='1',		-- 功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@PageNo        		int,
	@Department			varchar(MAX)	='',		-- 部门
	@Area				varchar(MAX)	='',		-- 地区
	@Explain			varchar(2000)	='',		-- 说明
	@cUserCode			varchar(300)    ='',		-- 制单人编号
	@cFullName			varchar(300)    ='',		-- 制单人名称
	@stypeid			varchar(MAX)	='00001',  	-- 分支机构
	@Yh					VARCHAR(10) = '9',			--优惠金额
	@hy					VARCHAR(10) = '9',			--会员情况
	@Price				VARCHAR(10) = '9',			--商品单价
	@PriceValue			NUMERIC(24, 10)  = 0,			--单价值
	@Discount			VARCHAR(10) = '9',			--商品折扣
	@DiscountValue		NUMERIC(24, 10)  = 0,			--折扣价
	@Tax				VARCHAR(10) = '9',			--商品税率
	@TaxValue			NUMERIC(24, 10)  = 0,			--税率值	
	@UETypeId			VARCHAR(MAX) = '',			--修改人
	@PETypeId			VARCHAR(MAX) = '',			--过账人
	@kcsp				VARCHAR(MAX) = '',          --商品名称
	@ifvoucher			INT,						--是否生成凭证
	@dealBtypeID		VARCHAR(MAX) = '',			--往来单位
	@UserDeRowCount		INT,
	@ifvchtemplate		VARCHAR(10),				--"1"为凭证模板单据、"2"为非凭证模板单据，当"-1"时，表示单据为"非所有单据"，不做判断
	--@ifAssets			varchar(10),				--"0"：项目管理(非总账模式)，="1"：卡片管理(总账模式)
	@checke_s			VARCHAR(20),				--制单时间start
	@checke_e			VARCHAR(20),				--制单时间end
	@stypeidin			VARCHAR(MAX) = '',			--资金调拨单-调入机构
	@transfertype		INT = 0,					--资金调拨单-业务类型0=全部,1=现金调拨,2=账户转账
	@iscwcheck			INT = 0,					--是否财务审核
	@posttime_s			VARCHAR(20),				--过账时间start
	@posttime_e			VARCHAR(20),				--过账时间end
	@isaddebtbill		VARCHAR(5),					--所选单据类型中是否只包含【应收增加单、应收减少单、应付增加单、应付减少单】，1=是，0=否,用来区分结算单位是搜索表体还是表头
	@printcount			VARCHAR(10),				--9.6增加 打印次数
	@waybillcode		VARCHAR(200),				--9.6增加 运单号（销售出库单）
	@tel				VARCHAR(200),				--9.6增加 承运单位（销售出库单）
	@packway			VARCHAR(200),				--9.6增加 包装方式（销售出库单）
	@goodsnumber		VARCHAR(200),				--9.6增加 物件数量（销售出库单）
	@deliveryaddress	VARCHAR(256),				--9.8.3 送货地址
	@posid				VARCHAR(256),				--9.91增加 POS编号
	@showprintcount		VARCHAR(10)='0'				--9.91 1.显示打印记录 0.不显示打印记录
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON

IF @UserDeRowCount = 0
	SET @UserDeRowCount = (SELECT UserDeRowCount FROM loginuser WHERE ETYPEID = @OperatorID)
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @BillType = '-1' 
	SET @BillType = ''

DECLARE @SQL		VARCHAR(MAX)
DECLARE @SQL_LIST	VARCHAR(MAX)
DECLARE @SQL_FROM	VARCHAR(MAX)
DECLARE @SQL_WHERE	VARCHAR(MAX)
DECLARE @SQL_ORDER	VARCHAR(MAX)
DECLARE @FiltVal	VARCHAR(MAX)
DECLARE @SQL_SUM	VARCHAR(MAX)
DECLARE @SQL_JOIN	VARCHAR(MAX)
SET @SQL_SUM = ''

SELECT @SQL_LIST  = ''
SELECT @SQL_WHERE = ''
SELECT @SQL_FROM  = ''
SELECT @SQL_ORDER = ''
SELECT @SQL  = ''
SELECT @SQL_JOIN  = ''

DECLARE @SQL_DEBT VARCHAR(2000)='' -- 输入往来单位时用来统计调帐单

--Ac_ProvisionForImpairment表中固定资产这边--做减值准备后台自动生成的一个凭证，生成凭证目的只为影响项目的值 对客户来说，这张凭证是不存在的
--IF EXISTS(SELECT TOP 1 1 FROM Ac_ProvisionForImpairment )
--	SET @SQL_JOIN+=' 
--					LEFT JOIN Ac_ProvisionForImpairment ACP ON BI.BILLNUMBERID =ACP.BILLNUMBERID AND ACP.BILLNUMBERID IS NULL '

SET @SQL_WHERE = 'WHERE Bi.BillType NOT IN (176,177,180,182,184,185,192,198,414)
						AND NOT Exists (SELECT 1 FROM Ac_ProvisionForImpairment ac where ac.BILLNUMBERID=BI.BILLNUMBERID) '
						
----------------------判断系统未启用某些配置时不应该显示的单据   start--------------------------------------
DECLARE @ifAssets INT  ,@combinationproduct INT,@usetransport INT
--固定资产
SELECT @ifAssets=SubValue FROM dbo.sysdata WHERE SubName='assets'
IF @ifAssets <> 1
	SET	@SQL_WHERE += ' AND Bi.BillType NOT IN (212,213,214)'
--组合品
SELECT @combinationproduct=SubValue FROM sysdata WHERE SubName = 'combinationproduct'  
IF @combinationproduct<>1
	 SET @SQL_WHERE += ' AND Bi.BillType NOT IN (12,46)'
--物流运输单
SELECT @usetransport=SubValue FROM sysdata WHERE SubName = 'usetransport'  
IF @usetransport<>1
	 SET @SQL_WHERE += ' AND Bi.BillType NOT IN (414)'
----------------------判断系统未启用某些配置时不应该显示的单据 end----------------------------------------


----===========================================版本新增条件======================================================----
--9.5增加过账时间条件
IF(@posttime_s <> '')
	SET @SQL_WHERE += ' AND Bi.posttime >= ''' + CONVERT(varchar(100), @posttime_s, 21) + '.000'''
IF(@posttime_e <> '')
	SET @SQL_WHERE += ' AND Bi.posttime <= ''' + CONVERT(varchar(100), @posttime_e, 21) + '.999'''

--9.5增加财务审核条件
 IF @iscwcheck=1 --查询财务审核单据
 BEGIN
	SET @SQL_WHERE += ' AND bi.CwCheck = 1' 
 END
 IF @iscwcheck=2 --查询财未审核
  BEGIN
	SET @SQL_WHERE += ' AND bi.CwCheck = 0' 
 END


DECLARE @notInclude VARCHAR(200)=''
--9.6增加					
IF(@printcount <> '')
	BEGIN
		SET @SQL_WHERE += ' 
							AND ISNULL(pCount.printcount,''0'') = ''' + @printcount + ''''	
		SET @notInclude += ' 
							AND ISNULL(pCount.printcount,''0'') = ''' + @printcount + ''''	
	END				
IF(@BillType = '11')
BEGIN
	IF(@waybillcode <> '')
		SET @SQL_WHERE += ' 
						AND Bi.waybillcode LIKE ''%' + @waybillcode + '%'''
	IF(@tel <> '')
		SET @SQL_WHERE += ' 
						AND Bi.tel LIKE ''%' + @tel + '%'''
	IF(@packway <> '')
		SET @SQL_WHERE += ' 
						AND Bi.packway LIKE ''%' + @packway + '%'''
	IF(@goodsnumber <> '')
		SET @SQL_WHERE += ' 
						AND Bi.goodsnumber LIKE ''%' + @goodsnumber + '%'''
END

IF @deliveryaddress <> ''
	SET @SQL_WHERE += ' AND Bi.deliveryaddress LIKE ''%' + @deliveryaddress + '%'''
----------------------------

IF(@checke_s <> '')
	SET @SQL_WHERE = @SQL_WHERE + ' AND BI.CHECKTIME>='''+CONVERT(varchar(100), @checke_s, 21)+'.000'''
IF(@checke_e <> '')
	SET @SQL_WHERE = @SQL_WHERE + ' AND BI.CHECKTIME<='''+CONVERT(varchar(100), @checke_e, 21)+'.999'''




--9.91增加POS名称条件 (2019 09 17 陈强)
IF @posid<>''
	SET @SQL_WHERE+=' AND bi.PosId in ('+@posid+') '
	
----===========================================新增条件结束======================================================----

--是否凭证模板单据
IF  @ifvchtemplate<>'-1'
BEGIN
	DECLARE @HasVoucherTemplateBillType  VARCHAR(2000)	='305,11,45,160,139,140,142,141,34,6,161,126,144,146,145,21,187,188,9,14,16,202,201,166,167,168,170,172,173,174,116,115,128,129,4,189,66,190,148,150,149,151,36,158,77,93,5,10,84,85,78,57,205,159,181,183,215,147,310,312,400,401,402,403,12,46,414,212,213,214,450,427'
	IF @ifvchtemplate='1'
		SET @SQL_WHERE += ' AND Bi.BillType IN ('+@HasVoucherTemplateBillType+')'
	ELSE
		SET @SQL_WHERE += ' AND Bi.BillType NOT IN ('+@HasVoucherTemplateBillType+')'
END


--查看他人经营历程 LIMIT_VIEWOTHER_BILL = 745
DECLARE @LimitRe INT
EXEC @LimitRe = GP_CheckLimit @OperatorID,745
IF @LimitRe = 1
	SET @SQL_WHERE += ' AND Bi.Checke = ''' + @OperatorID + ''''
						
--查优惠的情况,0.无优惠  1.有优惠
IF @Yh <> 9	
BEGIN
	SET @SQL_WHERE += ' AND Bi.BillType IN (305,11,45,160,34,6,161,4,66,178,195,167,168,170,172,181,215,12,46,312) '
	IF @Yh = 0
		SET @SQL_WHERE += ' AND ISNULL(Bi.preferencemoney,0) = 0'
	ELSE
		SET @SQL_WHERE += ' AND ISNULL(Bi.preferencemoney,0) <> 0'
END

--会员卡情况
IF @hy <> 9
BEGIN
	SET @SQL_WHERE += ' AND Bi.BillType IN (305,11,45,178,179,183,195,215,167,168,172,12,46,427) '
	IF @hy = 0
		SET @SQL_WHERE += ' AND ISNULL(Bi.VipCardID,0) = -1'
	ELSE
		SET @SQL_WHERE += ' AND ISNULL(Bi.VipCardID,0) <> -1'
END
--是否生成凭证
IF @ifvoucher <> 0
BEGIN
	SET @SQL_WHERE +=' AND  dbo.F_IsHasVoucher(bi.billnumberid,bi.billtype)= '+CAST(@ifvoucher AS VARCHAR(10))
END

--价格筛选
CREATE TABLE #PTypePriceBillId
(
	BillNumberId NUMERIC(18,0)
)
CREATE CLUSTERED INDEX CIX_PTypePriceBillId ON #PTypePriceBillId(BillNumberId) 

--零售、销售出库、销售退货、销售换货、委托代销发货、委托代销退货、委托代销结算、委托调价、采购入库、采购退货、采购换货、受托收货、受托退货、受托结算、受托调价、变价调拨、成本调价、生产拆装、零售退货单
IF @Price <> 9 AND CHARINDEX(',',@BillType) = 0 AND (@BillType IN (305,11,45,215,160,140,141,142,143,34,6,161,144,145,146,147,17,21,57,16,400,401,402,403,12,46) OR @BillType = '') 
BEGIN	
	DECLARE @PTypePriceSql			VARCHAR(MAX),
			@PTypePriceCondition	VARCHAR(MAX)
	SET @PTypePriceSql = ''
	SET @PTypePriceCondition = ''
	IF @Price = '0'
		SET @PTypePriceCondition = '>' + CAST(@PriceValue AS VARCHAR(100))
	ELSE IF @Price = '1'
		SET @PTypePriceCondition = '=' + CAST(@PriceValue AS VARCHAR(100))
	ELSE IF @Price = '2'
		SET @PTypePriceCondition = '<' + CAST(@PriceValue AS VARCHAR(100))
	ELSE IF @Price = '3'
		SET @PTypePriceCondition = '<=' + CAST(@PriceValue AS VARCHAR(100))
	ELSE IF @Price = '4'
		SET @PTypePriceCondition = '>=' + CAST(@PriceValue AS VARCHAR(100))
		
	
	SET @PTypePriceSql = '	INSERT INTO #PTypePriceBillId(BillNumberid)
							SELECT DISTINCT	BillNumberId
							FROM InOutStockTable(NOLOCK) 
							WHERE SalePrice	 ' + @PTypePriceCondition 
	IF @BillType<>''
		SET @PTypePriceSql+= '
								AND billtype='+@BillType	
	SET @PTypePriceSql+= '		AND billtype IN (305,11,45,215,160,140,141,142,143,34,6,161,144,145,146,147,17,21,57,16,400,401,402,403,12,46)'
					  
	EXEC(@PTypePriceSql)
		
	SET @SQL_JOIN+=' 
					INNER JOIN #PTypePriceBillId PPB ON BI.BILLNUMBERID=PPB.BillNumberId '	
						 
END

--折扣
CREATE TABLE #PTypeDiscountBillId
(
	BillNumberId NUMERIC(18,0)
)
CREATE CLUSTERED INDEX CIX_PTypeDiscountBillId ON #PTypeDiscountBillId(BillNumberId) 

IF @Discount <> 9 AND CHARINDEX(',',@BillType) = 0 AND (@BillType IN (305,11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403,12,46) OR @BillType = '')	--零售、销售出库、销售退货、销售换货、委托代销发货、委托代销退货、委托代销结算、采购入库、采购退货、采购换货、受托收货、受托退货、受托结算、零售退货单
BEGIN
	DECLARE @DiscountPriceSql		VARCHAR(MAX),
			@DiscountPriceCondition	VARCHAR(MAX)
	SET @DiscountPriceSql = ''
	SET @DiscountPriceCondition = ''			
	IF @Discount = '0'
		SET @DiscountPriceCondition = '>' + CAST(@DiscountValue AS VARCHAR(100))
	ELSE IF @Discount = '1'
		SET @DiscountPriceCondition = '=' + CAST(@DiscountValue AS VARCHAR(100))
	ELSE IF @Discount = '2'
		SET @DiscountPriceCondition = '<' + CAST(@DiscountValue AS VARCHAR(100))
	ELSE IF @Discount = '3'
		SET @DiscountPriceCondition = '<=' + CAST(@DiscountValue AS VARCHAR(100))
	ELSE IF @Discount = '4'
		SET @DiscountPriceCondition = '>=' + CAST(@DiscountValue AS VARCHAR(100))
		
	SET @DiscountPriceSql = 'INSERT INTO #PTypeDiscountBillId(BillNumberId)
							 SELECT DISTINCT	BillNumberId
							 FROM InOutstocktable(NOLOCK) 
							 WHERE Discount ' + @DiscountPriceCondition 
	IF @BillType<>''
		SET @DiscountPriceSql+= '
								AND billtype='+@BillType
									
	SET @DiscountPriceSql+= '	AND billtype IN (305,11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403,12,46) '
					  	
	EXEC(@DiscountPriceSql)	
	
	SET @SQL_WHERE += ' AND Bi.BillNumberId IN (SELECT BillNumberId FROM #PTypeDiscountBillId)  '			
END

--税率
CREATE TABLE #PTypeTaxBillId
(
	BillNumberId NUMERIC(18,0)
)
CREATE CLUSTERED INDEX CIX_PTypeTaxBillId ON #PTypeTaxBillId(BillNumberId) 

IF @Tax <> 9 AND CHARINDEX(',',@BillType) = 0 AND (@BillType IN (11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403,12,46) OR @BillType = '')	--销售出库、销售退货、销售换货、委托代销发货、委托代销退货、委托代销结算、采购入库、采购退货、采购换货、受托收货、受托退货、受托结算、零售退货单
BEGIN
	DECLARE @TaxPriceSql		VARCHAR(MAX),
			@TaxPriceCondition	VARCHAR(MAX)
	SET @TaxPriceSql = ''
	SET @TaxPriceCondition = ''			
	IF @Tax = '0'
		SET @TaxPriceCondition = '>' + CAST(@TaxValue AS VARCHAR(100))
	ELSE IF @Tax = '1'
		SET @TaxPriceCondition = '=' + CAST(@TaxValue AS VARCHAR(100))
	ELSE IF @Tax = '2'
		SET @TaxPriceCondition = '<' + CAST(@TaxValue AS VARCHAR(100))
	ELSE IF @Tax = '3'
		SET @TaxPriceCondition = '<=' + CAST(@TaxValue AS VARCHAR(100))
	ELSE IF @Tax = '4'
		SET @TaxPriceCondition = '>=' + CAST(@TaxValue AS VARCHAR(100))
		
	SET @TaxPriceSql = 'INSERT INTO #PTypeTaxBillId(BillNumberId)
							 SELECT DISTINCT  BillNumberId 
							 FROM InOutstocktable(NOLOCK) 
							 WHERE Tax ' + @TaxPriceCondition 
							 
	IF @BillType<>''
		SET @TaxPriceSql+= '
							AND billtype='+@BillType
									
	SET @TaxPriceSql+= '	AND billtype IN (11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403,12,46) '
	
	EXEC(@TaxPriceSql)	
	
	SET @SQL_JOIN+=' 
					INNER JOIN #PTypeTaxBillId PTB ON BI.BILLNUMBERID=PTB.BillNumberId '	
				
END					

IF @BillType <> ''
	SET @SQL_WHERE += ' AND Bi.BillType IN (SELECT * FROM F_Split('''+@BillType+''','',''))'						

IF RTRIM(@BillCode)<>''
	SELECT @SQL_WHERE += ' AND bi.[BillCode] LIKE ''%' + @BillCode +'%'''
IF RTRIM(@Explain)<>''
	SELECT @SQL_WHERE += ' AND bi.[Explain] LIKE ''%' + @Explain +'%'''
IF RTRIM(@Comment)<>''
	SELECT @SQL_WHERE += ' AND bi.[Comment] LIKE ''%' + @Comment +'%'''
IF RTRIM(@redword)=1
	SELECT @SQL_WHERE += ' AND bi.[redword]=0 ' 
ELSE IF RTRIM(@redword)=2
	SELECT @SQL_WHERE += ' AND (bi.[redword]=1  OR bi.[redword]=2)  ' 
	

--处理部门信息
CREATE TABLE #Department(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_Department ON #Department(TypeId) 
SET @Department = RTRIM(LTRIM(@Department))

IF @Department <> '' OR @MDTypeId = '-99999'
BEGIN
	INSERT INTO #Department(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Department,9,@OperatorID)
	SET @SQL_JOIN+=' INNER JOIN #Department DT1 ON BI.DTypeId=DT1.TypeId '
END	

--筛选制单人
IF @cUserCode<>'' OR @cFullName<>''
	SET @SQL_WHERE  += 'AND E.UserCode LIKE ''%'+@cUserCode+'%'' AND E.FullName LIKE ''%'+@cFullName+'%'''
	
--筛选经手人
CREATE TABLE #Employee(TypeId 	varchar(100))
CREATE CLUSTERED INDEX CIX_Employee ON #Employee(TypeId) 
SET @EtypeName = LTRIM(RTRIM(@EtypeName))

IF @EtypeName<>'' OR @METypeId = '-99999'
BEGIN
	INSERT INTO #Employee(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@EtypeName,3,@OperatorID)
	SET @SQL_JOIN+=' INNER JOIN #Employee ET1 ON BI.ETypeId=ET1.TypeId '	
END


--筛选修改人
CREATE TABLE #UEmployee(TypeID VARCHAR(100))
CREATE CLUSTERED INDEX CIX_UEmployee ON #UEmployee(TypeId) 
SET @UETypeId = LTRIM(RTRIM(@UETypeId))
IF NOT (@UETypeId = '')
BEGIN
	INSERT INTO #UEmployee(TypeID) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@UETypeId,3,@OperatorID)
	SET @SQL_JOIN+=' INNER JOIN #UEmployee UET1 ON BI.updatee=UET1.TypeId '		
END

--筛选过账人
CREATE TABLE #PEmployee(TypeID VARCHAR(100))
CREATE CLUSTERED INDEX CIX_PEmployee ON #PEmployee(TypeId) 
SET @PETypeId = LTRIM(RTRIM(@PETypeId))
IF NOT (@PETypeId = '')
BEGIN
	INSERT INTO #PEmployee(TypeID) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PETypeId,3,@OperatorID)
	SET @SQL_JOIN+=' INNER JOIN #PEmployee pET1 ON BI.Poster=pET1.TypeId '			
END

--筛选分支机构
CREATE TABLE #Stype(TypeId 	varchar(100))
CREATE CLUSTERED INDEX CIX_Stype ON #Stype(TypeId) 
SET @stypeid = LTRIM(RTRIM(@stypeid))
IF  @stypeid<>'' OR @MStypeid <> '00000'
BEGIN
	INSERT INTO #Stype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	--当单据为资金调拨单，并且调出机构未选择时。 将 调出、调入机构的关系变为OR（主要根据调入机构来查询）
	IF(@BillType = '310' AND @sTypeId = '')
		SET @SQL_WHERE = @SQL_WHERE
	ELSE
		SET @SQL_JOIN+=' INNER JOIN #Stype ST1 ON BI.sTypeId=ST1.TypeId '			
END

CREATE TABLE #btype_l(Typeid VARCHAR(50))
CREATE NONCLUSTERED INDEX CIX_BType_1_TypeId ON #btype_l(Typeid)

IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerBTypeID = '00001')
		INSERT INTO #btype_l(Typeid) SELECT TypeID FROM BType WHERE SonNum = 0 AND TypeId LIKE '00001%'
	ELSE
		INSERT INTO #btype_l(Typeid) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @OperatorID
				AND B.typeId LIKE '00001%'
				AND L.flag = 1 
				AND B.sonnum = 0				

--供货商
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerBTypeID2 = '00002')
	INSERT INTO #btype_l(Typeid) SELECT TypeID FROM BType WHERE SonNum = 0 AND TypeId LIKE '00002%'
ELSE
	INSERT INTO #btype_l(Typeid) 
	SELECT	B.TypeId 
	FROM	BType_L L
	INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
	WHERE	L.etypeid = @OperatorID
			AND B.typeId LIKE '00002%'
			AND L.flag = 1 
			AND B.sonnum = 0

--往来单位
CREATE TABLE #dealBtype(TypeID VARCHAR(100))
CREATE CLUSTERED INDEX CIX_dealBtype ON #dealBtype(TypeId) 

IF @dealBtypeID = '00000' OR @dealBtypeID = '' OR @dealBtypeID = '%'
	INSERT INTO #dealBtype(TypeId) SELECT TypeId FROM #btype_l
ELSE
BEGIN
	INSERT INTO #dealBtype(TypeId)
	SELECT 	DISTINCT A.TypeId 
	FROM 	#btype_l A, 
			(SELECT A FROM dbo.F_Split(@dealBtypeID,',')) B 
	WHERE	A.TypeId LIKE B.A + '%'
END

IF @dealBtypeID<>''
BEGIN
	SET @SQL_JOIN+=' 
					INNER JOIN #dealBtype dbt1 ON BI.dealBtypeID=dbt1.TypeId '	
	
END
ELSE
BEGIN
	IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	BEGIN
		INSERT INTO #dealBtype(TypeId) SELECT '' as TypeId
	    SET @SQL_JOIN+=' 
						INNER JOIN #dealBtype dbt1 ON BI.dealBtypeID=dbt1.TypeId '	
	 END
		
END

-- 限制条件(Btype)
SET @BtypeName = LTRIM(RTRIM(@BtypeName))
CREATE TABLE #BType(TypeId VARCHAR(100))
CREATE CLUSTERED INDEX CIX_BType ON #BType(TypeId) 

IF @BtypeName = '00000' OR @BtypeName = '' OR @BtypeName = '%'
	INSERT INTO #BType(TypeId) SELECT TypeId FROM #btype_l
ELSE
BEGIN
	INSERT INTO #BType(TypeId)
	SELECT 	DISTINCT A.TypeId 
	FROM 	#btype_l A, 
			(SELECT A FROM dbo.F_Split(@BtypeName,',')) B 
	WHERE	A.TypeId LIKE B.A + '%'
END

DROP TABLE #btype_l

--结算单位
IF RTRIM(@BtypeName)<>''  --选择了具体的结算单位，则对应收增加等单据筛选表体 其他单据筛选表头  往来核销和转入单位做或筛选
	BEGIN
		IF(@isaddebtbill = '1')	--是否只含应收增加、减少 应付增加、减少
		BEGIN
			SELECT @SQL_WHERE +=' AND Bi.BillType in('+@BillType+') '
			SET @SQL_JOIN+='
							INNER JOIN (SELECT BillnumberID FROM AdDebtBill A inner JOIN #BType B ON A.BTYPEID=B.TYPEID ) ADBT1 ON Bi.BillnumberID=ADBT1.BillnumberID '
		END
		ELSE	--单据类型多选
		BEGIN
			SET @SQL_JOIN+=' 
							INNER JOIN #BType bt1 ON (CASE WHEN  BI.BILLTYPE=450 THEN bi.ChargeOffBtypeid ELSE  BI.BtypeID END) =bt1.TypeId '
		END
	END
ELSE  --没有选择则只判断表头结算单位权限 
	BEGIN
		 IF (@MBTypeId <> '00001' OR @MBTypeId2 <> '00002')  --没有全部权限范围
		 BEGIN
			INSERT INTO #BType(TypeId) SELECT '' as TypeId
			SET @SQL_JOIN+=' 
							INNER JOIN #BType bt1 ON BI.BtypeID=bt1.TypeId '
		END	
	END


--处理地区信息
IF RTRIM(LTRIM(@Area))<>''
	BEGIN	
		SET @Area = LTRIM(RTRIM(@Area))
		CREATE TABLE #AreaType(TypeId		varchar(100))
		CREATE CLUSTERED INDEX CIX_AreaType ON #AreaType(TypeId) 
		INSERT INTO #AreaType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Area,10,@OperatorID)
		
		SET @SQL_JOIN+=' 
						INNER JOIN (SELECT a.TypeId FROM BType A inner JOIN #AreaType B ON ISNULL(A.AreaTypeId,'''')=B.TYPEID ) BT2 ON Bi.BtypeID=BT2.TypeId '	
						
		SET @SQL_WHERE += ' AND Bi.BillType NOT IN (5,9,10,14,16,17,21,57,78,158,159,77,187,188,191,197,205,206)'

	END

-- 限制条件(Atype)
IF RTRIM(@AtypeName)<>''
	BEGIN	
		SET @AtypeName = LTRIM(RTRIM(@AtypeName))
		CREATE TABLE #AType(TypeId varchar(100))
		CREATE CLUSTERED INDEX CIX_AType ON #AType(TypeId) 
		INSERT INTO #AType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@AtypeName,5,@OperatorID) S		
		IF CHARINDEX('34',@AtypeName)>0
			INSERT INTO #AType(TypeId)VALUES('34')
		IF CHARINDEX('39',@AtypeName)>0
			INSERT INTO #AType(TypeId)VALUES('39')
		IF CHARINDEX('27',@AtypeName)>0
			INSERT INTO #AType(TypeId)VALUES('27')
			
		CREATE TABLE #ListTable (Billnumberid numeric(10,0))
		INSERT INTO #ListTable (Billnumberid)
		SELECT DISTINCT Billnumberid 
		FROM  ListTable a
		inner join	#AType b on a.atypeid=b.typeid
		WHERE a.BillType NOT IN (140,142,143,144,146,147,16,17,14,21,9,57,115,116,128,129,78,5,10,139,126,159,165,166,169,171,173,174,175,183,186,187,188,205,206) 
	
		
		SET @SQL_JOIN+=' 
						INNER JOIN #ListTable  LST1 ON bi.Billnumberid=LST1.Billnumberid '		
	END	
	


-- 限制Ktype
CREATE TABLE #KType(TypeId		varchar(100))
CREATE CLUSTERED INDEX CIX_KType ON #KType(TypeId) 
CREATE TABLE #KType2(TypeId		varchar(100))
CREATE CLUSTERED INDEX #CIX_KType2 ON #KType2(TypeId) 
IF RTRIM(@KtypeName)<>''
	BEGIN
		SET @KtypeName = LTRIM(RTRIM(@KtypeName))
		IF CHARINDEX(',',@BillType)=0 AND @BillType IN (17,21,187,188)
		BEGIN
			INSERT INTO #KType(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@KtypeName,4) S
		END
		ELSE
		BEGIN
			INSERT INTO #KType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KtypeName,4,@OperatorID) S
		END
	END

IF RTRIM(@KtypeName2)<>''
	BEGIN
		SET @KtypeName2 = LTRIM(RTRIM(@KtypeName2))
		IF CHARINDEX(',',@BillType)=0 AND @BillType IN (17,21,187,188)
		BEGIN
			INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@KtypeName2,4) S
			
		END
		ELSE
		BEGIN
			INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KtypeName2,4,@OperatorID) S
		END
	END

-------------------------------------------------商品筛选------------------------
CREATE TABLE #PType(TypeId		varchar(100))
CREATE CLUSTERED INDEX CIX_PType ON #PType(TypeId) 

IF (RTRIM(@PTypeName)<>''  OR @ptypecategoryid<>'') and @kcsp=''
  INSERT INTO #PType(TypeId) 
  SELECT S.TypeId FROM F_ManPTypeInCategoryID(@OperatorID,@PTypeName,@ptypecategoryid) S
IF @kcsp <>''
  INSERT INTO #PType(TypeId) 
  SELECT P.TypeId 
  FROM  F_ManPTypeInCategoryID(@OperatorID,@PTypeName,@ptypecategoryid) S 
  INNER JOIN ptype p ON s.TypeId = p.typeId 
  WHERE (P.FullName like +'%'+@kcsp+'%'  OR  P.UserCode Like +'%'+@kcsp+'%' ) 



IF EXISTS (SELECT top 1 1  FROM #PType)
BEGIN
	--出去固定资产单据、固定资产单据于商品无关
	SELECT @SQL_WHERE += ' AND Bi.BillType NOT IN (4,66,115,116,128,129,36,158,93,77,84,85,78,5,10,159,179,189,190,205,206,212,213,214)'	
END

IF @StartMoney=0 AND @EndMoney=0
BEGIN
	 SET @StartMoney=-999999999999
	 SET @EndMoney= 999999999999
END

IF @StartMoney<>-999999999999
	BEGIN
		SELECT @SQL_WHERE += ' AND Bi.BillType NOT IN (16,17,9,14,139,126,175)'
		SELECT @SQL_WHERE += ' AND (
							(bi.[Totalmoney]>=' + Convert(varchar(20),(@StartMoney)) + ' AND bi.redword <>2)  
							 OR 
							(-bi.[Totalmoney]>=' + Convert(varchar(20),(@StartMoney)) + ' AND bi.redword =2)
							)'
	
	END

IF @EndMoney<>999999999999
	BEGIN
		SELECT @SQL_WHERE += ' AND Bi.BillType NOT IN (16,17,9,14,139,126,175)'
		SELECT @SQL_WHERE += ' AND (
							(bi.[Totalmoney]<=' + Convert(varchar(20),(@EndMoney)) + ' AND bi.redword <>2)  
							 OR 
							(-bi.[Totalmoney]<=' + Convert(varchar(20),(@EndMoney)) + ' AND bi.redword =2)
							)'
	END

DECLARE @BillTypeList VARCHAR(MAX)
DECLARE @LimitList VARCHAR(MAX)
DECLARE @BillTypes VARCHAR(2000)
SET @BillTypes ='(9999'

--单据调阅权限
SET @BillTypeList = '450,305, 11, 45, 215,  4,144,145,146,147,140,141,142,143, 34,  6, 66, 17, 21,  9, 14,139,126, 57, 16,116,115,128,129, 36, 93, 77, 84, 85,'
SET @LimitList    = '4667,349,350,351,2588,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,'

SET @BillTypeList += ' 78, 212, 213, 214,  5, 10,148,149,150,151,158,159,160,161,165,166,167,168,169,170,171,172,173,174,175, 178, 179, 183, 186,187,188,189,400,401,402,403,310,'
SET @LimitList    += '381,2531,2536,2541,382,383,384,385,386,502,501,550,583,585,678,679,680,681,682,683,684,685,686,687,688,1377,1378,1386,1375,718,721,727,4576,4585,4597,4606,4318,'


SET @BillTypeList += '190, 191, 192, 197, 195, 196, 200, 201, 202, 203, 205, 206, 181, 312,427,327,328,329 '
SET @LimitList    += '730,1473,1536,1475,1533,1535,1479,1553,1557,1551,1941,1946,1379,4497,4215,5239,5248,5257'

--不是总账则不显示资金调拨单
IF((SELECT SubValue FROM SYSDATA WHERE SUBNAME = 'isuseacsystem') = 1)
BEGIN
	--9.4解决资金调拨单无法查询问题 增加单据类型310
	SET @BillTypeList += ',310'
	SET @LimitList    += ',4455'
	
END
--启用组合品销售
IF EXISTS(SELECT TOP 1 1 FROM SYSDATA WHERE SUBNAME = 'combinationproduct' AND SubValue= 1)
BEGIN
	SET @BillTypeList += ',12,46'
	SET @LimitList    += ',4749,4757'
END

IF @OperatorID<>'00001'  -- 相关单据调阅权限
BEGIN
	SELECT @BillTypes = @BillTypes + CASE WHEN SUBSTRING(L.lim,T.OFFSET,1) = 1 THEN ',' + T.BillType ELSE ''  END 
	FROM(
		SELECT A.ID,A.a AS BillType,CONVERT(INT,B.a) AS OFFSET
		FROM(
			SELECT ROW_NUMBER() OVER (ORDER BY(SELECT 0)) AS ID,a
			FROM f_split(@BillTypeList,',')	
		) A
		INNER JOIN(
			SELECT ROW_NUMBER() OVER (ORDER BY(SELECT 0)) AS ID,a
			FROM f_split(@LimitList,',')	
		)B ON A.ID = B.ID
	) T,loginuser L
	WHERE L.etypeid = @OperatorID			
END 

SET @BillTypes = @BillTypes +' ) '

IF @OperatorID<>'00001'
	SELECT @SQL_WHERE += ' AND Bi.BillType in ' +@BillTypes

 --仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_GetManKTypeId ON #GetManKTypeId(TypeId) 

INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)
IF @KtypeName = '' AND @KtypeName2 = ''
	INSERT INTO #GetManKTypeId(TypeId)VALUES('00000')

IF @BillType = '' OR CHARINDEX(',',@BillType)>0
	BEGIN
		SET @SQL_WHERE += ' AND ('
		IF RTRIM(@KTypeName)<>''
			BEGIN
				SET @SQL_WHERE +='	Exists (select 1 from #KTYPE K where K.TYPEID=BI.KTYPEID) 
									OR (  Exists (select 1 from #KTYPE k WHERE K.TYPEID=bi.KTypeId2) AND BI.BILLTYPE IN (16,17,21,160,161,166,172,173,174,175,187,188) )  '
				--SET @SQL_WHERE += ' (Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.BillType NOT IN (16,17,21,160,161,166,172,173,174,175,187,188))'
				--SET @SQL_WHERE += ' OR (Bi.KTypeId2 IN (SELECT * FROM #KType) AND Bi.BillType IN (188))'
				--SET @SQL_WHERE +='  OR (((Bi.KTypeId IN (SELECT * FROM #KType)) OR (Bi.KTypeId2 IN (SELECT * FROM #KType))) AND Bi.BillType IN (16,160,161,166,172,173,174,175))'
				--SET @SQL_WHERE += ' OR ((Bi.KTypeId IN (SELECT * FROM #KType)) OR (Bi.KTypeId2 IN (SELECT * FROM #KType)) AND Bi.BillType IN (17,21,187,188)) '
			END
		ELSE
			BEGIN
				IF @MKTypeId = '00000'
					SET @SQL_WHERE += ' 1=1'
				ELSE
					BEGIN
						SET @SQL_WHERE += ' (Bi.KTypeId='''' AND Bi.BillType IN (4,141,143,66,145,147,115,116,128,129,36,158,93,77,84,85,78,5,10,148,149,150,151,159,171,179,186,189,190,195,200,192,205,206,181,212,213,214,312,57,450,427))'				
						SET @SQL_WHERE += ' OR Bi.KTypeId = ''00000'' OR Bi.KTypeId = ''10000'''
						SET @SQL_WHERE += ' OR (Exists (SELECT 1 FROM #GetManKTypeId  k where Bi.KTypeId=k.typeid) AND Bi.BillType NOT IN (16,160,161,166,172,173,174,175,187,188))' -- 17,21
						SET @SQL_WHERE += ' OR ( Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)  AND Bi.BillType IN (188,17,21))'
						SET @SQL_WHERE +=' OR (( Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId=k.typeid) OR  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)) AND Bi.BillType IN (166,172))'
						
						SET @SQL_WHERE +=' OR ((Bi.KTypeId='''' AND Bi.KTypeId2='''') AND Bi.BillType IN (166,172))'
						SET @SQL_WHERE +='  OR (( Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId=k.typeid) OR  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)) AND Bi.BillType IN (16,160,161,173,174,175))'
						SET @SQL_WHERE += ' OR (( Exists (SELECT 1 FROM #KType k where Bi.KTypeId=k.typeid)) OR ( Exists (SELECT 1 FROM #KType k where Bi.KTypeId2=k.typeid)) AND Bi.BillType IN (17,21,187,188)) '
						
								---分支机构调拨出入库单在操作员那儿查不到，所以放出来，尹聪要求
						IF EXISTS(SELECT Value FROM userconfig WHERE ConfigName ='MoveInOutKLimit' AND Value='1')
							--2015-06-09 9.6BUG 141：测试要求，取消当时需求定的勾选【调拨单中，仓库的权限有效】就不查询出同价调拨等单的处理。
							--SET @SQL_WHERE += ' OR Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId) AND Bi.BillType IN (17,21,187,188) '
							SET @SQL_WHERE += ' OR Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId) AND Bi.BillType IN (17,21,187,188) '
						ELSE
							SET @SQL_WHERE += ' OR ((Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND Bi.BillType IN (17,21,187,188)) '
					END
			END
		SET @SQL_WHERE += ' )'
	END
ELSE
	BEGIN
		IF @BillType NOT IN (4,141,143,66,145,147,115,116,128,129,36,158,93,77,84,85,78,5,10,148,149,150,151,159,171,179,186,189,190,195,200,192,205,206,181,212,213,214,427)
			BEGIN
				SET @SQL_WHERE += ' AND ('
				--分支机构调拨出入库单，需要和同价调拨单处理成一样,加了类型187,188
				IF @BillType NOT IN (16,17,21,160,161,166,172,173,174,175,187,188)
					BEGIN
						IF RTRIM(@KTypeName)<>''
							SET @SQL_WHERE += ' ( Exists (SELECT 1 FROM #KType k where Bi.KTypeId=k.typeid))'
						ELSE
							BEGIN
								IF @MKTypeId = '00000'
									SET @SQL_WHERE += ' 1=1 '
								ELSE
									BEGIN
										SET @SQL_WHERE += ' ( Exists (SELECT 1 FROM #GetManKTypeId  k where Bi.KTypeId=k.typeid) OR Bi.KTypeId='''' OR Bi.KTypeId=''10000'')'
									END
							END
					END
				--分支机构调拨出入库单，需要和同价调拨单处理成一样,加了类型187,188
				ELSE IF @BillType IN (17,21)--187,188同价调拨单不处理
					BEGIN
						IF EXISTS(SELECT Value FROM userconfig WHERE ConfigName ='MoveInOutKLimit' AND Value='1')
							BEGIN
								IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
									BEGIN
										SET @SQL_WHERE += ' Exists (SELECT 1 FROM #GetManKTypeId  k where Bi.KTypeId=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid) '
									END
								ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
									BEGIN
										SET @SQL_WHERE += ' Exists (SELECT 1 FROM #GetManKTypeId  k where Bi.KTypeId=k.typeid) AND  Exists (SELECT 1 FROM #KType2 k where Bi.KTypeId2=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid) '
									END
								ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
									BEGIN
										SET @SQL_WHERE += ' Exists (SELECT 1 FROM #KType  k where Bi.KTypeId=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid) '
									END
								ELSE
									BEGIN
										SET @SQL_WHERE += ' Exists (SELECT 1 FROM #KType  k where Bi.KTypeId=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId=k.typeid) AND  Exists (SELECT 1 FROM #KType2 k where Bi.KTypeId2=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid) '
									END
							END
						ELSE
							BEGIN
								IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
									BEGIN
										SET @SQL_WHERE += ' (Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid) OR Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)) '
									END
								ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
									BEGIN
										SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid) OR  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)) AND  Exists (SELECT 1 FROM #KType2 k where Bi.KTypeId2=k.typeid)) '
									END
								ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
									BEGIN
										SET @SQL_WHERE += ' ( Exists (SELECT 1 FROM #KType K where Bi.KTypeId=k.typeid) AND ( Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId=k.typeid) OR  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid))) '
									END
								ELSE
									BEGIN
										SET @SQL_WHERE += ' ( (  Exists (SELECT 1 FROM #KType  K where Bi.KTypeId=k.typeid) AND Exists (SELECT 1 FROM #KType2 k where Bi.KTypeId2=k.typeid) ) AND ( Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId=k.typeid) OR  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid))) '
									END
							END
					END
				ELSE IF @BillType IN (166,172)
					BEGIN
						IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE +=' (Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid) OR Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid))'
								SET @SQL_WHERE +=' OR ( Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid) AND Bi.KTypeId2='''')'
								SET @SQL_WHERE +=' OR (Bi.KTypeId='''' AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid))'
								SET @SQL_WHERE +=' OR (Bi.KTypeId='''' AND Bi.KTypeId2='''')'
							END
						ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId='''' OR  Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid)) AND (Exists (SELECT 1 FROM #KType2 k where Bi.KTypeId2=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)))'
							END
						ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' ((Exists (SELECT 1 FROM #KType K where Bi.KTypeId=k.typeid) AND Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid)) AND (Bi.KTypeId2='''' OR  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)))'
							END
						ELSE
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #KType K where Bi.KTypeId=k.typeid) AND Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid)) AND ( Exists (SELECT 1 FROM #KType2 k where Bi.KTypeId2=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)))'
							END
					END
				ELSE IF @BillType = 160
					BEGIN
						IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)) OR ( Exists (SELECT 1 FROM #GetManKTypeId  K where Bi.KTypeId=k.typeid))) '
							END
						ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)) AND ( Exists (SELECT 1 FROM #KType2  K where Bi.KTypeId=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId  K where Bi.KTypeId=k.typeid))) '
							END
						ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #KType k where Bi.KTypeId2=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)) AND ( Exists (SELECT 1 FROM #GetManKTypeId  K where Bi.KTypeId=k.typeid))) '
							END
						ELSE
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #KType k where Bi.KTypeId2=k.typeid) AND Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid)) AND ( Exists (SELECT 1 FROM #KType2  K where Bi.KTypeId=k.typeid) AND Exists (SELECT 1 FROM #GetManKTypeId  K where Bi.KTypeId=k.typeid))) '
							END
					END
				ELSE
					BEGIN
						IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid )) OR ( Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid))) '
							END
						ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #KType2 k where Bi.KTypeId2=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid))) '
							END
						ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #KType K where Bi.KTypeId=k.typeid) AND Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid)) )
									 '
							END
						ELSE
							BEGIN
								SET @SQL_WHERE += ' (( Exists (SELECT 1 FROM #KType K where Bi.KTypeId=k.typeid) AND  Exists (SELECT 1 FROM #GetManKTypeId K where Bi.KTypeId=k.typeid)) AND ( Exists (SELECT 1 FROM #KType2 k where Bi.KTypeId2=k.typeid ) AND  Exists (SELECT 1 FROM #GetManKTypeId k where Bi.KTypeId2=k.typeid))) '
							END
					END
				SET @SQL_WHERE += ' )'
			END
	END
-- 单据明细摘要查询 
IF RTRIM(@ZYDetail)<>''
	BEGIN          
		-- 建立包含一个BillNumberID字段的临时表
		CREATE TABLE #commentTable(billnumberid INT)
		CREATE CLUSTERED INDEX CIX_commentTable ON #commentTable(billnumberid) 
	
		DECLARE @TempTableSQL varchar(MAX)
		 
        SELECT @TempTableSQL=' INSERT INTO #commentTable
							   SELECT DISTINCT t.billnumberid FROM 
							   (
									select  billnumberid,comment from accountcredence union 
									select  billnumberid,comment from addebtbill union 
									select  billnumberid,comment from adpricebill union 
									select  billnumberid,comment from advantage union 
									select  billnumberid,comment from AssetIncDecBill union 
									select  billnumberid,comment from buybackbill union 
									select  billnumberid,comment from buybill union 
									select  billnumberid,comment from buygoodsexchangebill union 
									select  billnumberid,comment from chargeoffbill union 
									select  billnumberid,comment from commissionbill union 
									select  billnumberid,comment from DepBill union 
									select  billnumberid,comment from disassemblebill union 
									select  billnumberid,comment from gatheringbill union 
									select  billnumberid,comment from givebill union 
									select  billnumberid,comment from givemebill union 
									select  billnumberid,comment from integralexchangebill union 
									select  billnumberid,comment from losebill union 
									select  billnumberid,comment from moneybill union 
									select  billnumberid,comment from movebill union 
									select  billnumberid,comment from movebjbill union 
									select  billnumberid,comment from movemoneybill union 
									select  billnumberid,comment from otherinoutbill union 
									select  billnumberid,comment from overflowbill union 
									select  billnumberid,comment from paybill union 
									select  billnumberid,comment from prebill union 
									select  billnumberid,comment from priceprotectbill union 
									select  billnumberid,comment from RetailBackBill union 
									select  billnumberid,comment from retailbill union 
									select  billnumberid,comment from salebackbill union 
									select  billnumberid,comment from salebill union 
									select  billnumberid,comment from salegoodsexchangebill union 
									select  billnumberid,comment from sharesourcebill union 
									select  billnumberid,comment from stypemovebill union 
									select  billnumberid,comment from VipAddMoneyBatchBill union 
									select  billnumberid,comment from wx_bill_call union 
									select  billnumberid,comment from wx_bill_getback union 
									select  billnumberid,comment from wx_bill_goto union 
									select  billnumberid,comment from wx_bill_in union 
									select  billnumberid,comment from wx_bill_jiejian union 
									select  billnumberid,comment from wx_bill_move union 
									select  billnumberid,comment from wx_bill_out union 
									select  billnumberid,comment from wx_bill_replace union 
									select  billnumberid,comment from wx_bill_self union 
									select  billnumberid,comment from wx_bill_send union 
									select  billnumberid,comment from wx_bill_sendback union 
									select  billnumberid,comment from quotepricebill UNION
									--一下部分是以前漏加了的单据类型  谢吉康 9.8.3 2017-10-16
									--上表体
									select  billnumberid,comment from PT_Combin_SaleBill UNION
									select  billnumberid,comment from PT_Combin_SaleBackBill UNION
									select  billnumberid,comment from RetailCombinationBill UNION
									--下表体
									select  billnumberid,comment from PT_Combin_SaleBillDetail UNION
									select  billnumberid,comment from PT_Combin_SaleBackBillDetail UNION
									select  billnumberid,comment from askpricebill UNION
									select  billnumberid,comment from stypemovebill UNION
									select  billnumberid,comment from prebill UNION
									select  billnumberid,comment from sharesourcebill UNION
									select  billnumberid,comment from AssetIncDecBill UNION
									select  billnumberid,comment from FixedAssetsDetails UNION
									select  billnumberid,comment from CapitalTransfer_Bill UNION	
									select  billnumberid,comment from AppraisalBill UNION
									select  billnumberid,comment from AppraisalBackBill UNION
									select  billnumberid,comment from SendBill UNION
									select  billnumberid,comment from SendBackBill UNION
									select  billnumberid,comment from Transportbill 
							   ) t WHERE t.COMMENT LIKE ''%'+@ZYDetail+'%'' '
							   IF (@BillType = '')
							   BEGIN
									SET @TempTableSQL+=   ' UNION ALL  SELECT DISTINCT billnumberid FROM moneybill WHERE COMMENT LIKE ''%'+@ZYDetail+'%'' '
                               END  
                               ELSE 
                               BEGIN
                                IF exists(SELECT top 1 1  FROM dbo.f_split(@BillType,',') fs where  fs.a='36' )
									SET @TempTableSQL+=   ' UNION ALL  SELECT DISTINCT billnumberid FROM moneybill WHERE COMMENT LIKE ''%'+@ZYDetail+'%'' '
                               END  
                         
        EXEC(@TempTableSQL)
       
        SELECT @SQL_Join +=' 
							INNER JOIN #commentTable CMT1 ON  bi.[BillNumberID]=CMT1.BillNumberID ' 
	END


-------------9.4新增资金调拨单-----------------杨俊增加
	IF(@BillType = '310')
	BEGIN	
		--调出分支机构
		CREATE TABLE #GetManSTypeId2(TypeId	VARCHAR(100))
		CREATE CLUSTERED INDEX CIX_GetManSTypeId2 ON #GetManSTypeId2(TypeId) 
		INSERT INTO #GetManSTypeId2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@stypeidin,11,@OperatorID) S

		--调出机构未选择时，如果调入机构也未选择，则默认筛选调出、调入机构有权限的单据（OR关系）
		--调出有时，则按公共筛选分支机构方式筛选调出机构
		--调入有时，则在查询条件后加上调入机构（AND关系）
		IF(@sTypeId = '')
		BEGIN
			IF(@stypeidin <> '')
				SELECT @SQL_WHERE = @SQL_WHERE + ' 
								AND bi.StypeID2 IN(SELECT TypeId FROM #GetManSTypeId2) '
			ELSE
				SELECT @SQL_WHERE = @SQL_WHERE + ' AND (bi.StypeID IN(SELECT TypeId FROM #Stype) 
								OR bi.StypeID2 IN(SELECT TypeId FROM #GetManSTypeId2)) '
		END
		ELSE
		BEGIN
			IF(@stypeidin <> '')
				SELECT @SQL_WHERE = @SQL_WHERE + ' 
								AND bi.StypeID2 IN(SELECT TypeId FROM #GetManSTypeId2) '
		END
							
		IF(@transfertype <> 0)
			SELECT @SQL_WHERE = @SQL_WHERE + ' 
							AND bi.TransferType = ' + CAST(@transfertype AS VARCHAR(10)) + ' '
	END
--===============--
-- 过滤
IF LTRIM(RTRIM(@Filter))<>''
BEGIN
	-- 符号变换
	SELECT @FiltVal = @Filter
	SELECT @FiltVal = REPLACE(@FiltVal,'!','''')
	SELECT @FiltVal = REPLACE(@FiltVal,'$','%')
	SELECT @FiltVal = REPLACE(@FiltVal,'{','>')
	SELECT @FiltVal = REPLACE(@FiltVal,'}','<')
	IF CHARINDEX('AND',LTRIM(UPPER(@FiltVal))) = 1
		SELECT @SQL_WHERE += ' ' + RTRIM(@FiltVal)
	ELSE
		SELECT @SQL_WHERE += ' AND ' + RTRIM(@FiltVal)
END

-- 打印记录
CREATE TABLE #PrintCount(printcount INT, billnumberid NUMERIC(10,0),billtype NUMERIC(10,0))
CREATE CLUSTERED INDEX CIX_#PrintCount ON #PrintCount(BillNumberId) 
CREATE NONCLUSTERED INDEX  Ncix_printcount on  #PrintCount(printcount,billnumberid,billtype)   

IF @showprintcount = '1'
BEGIN
	DECLARE @PrintCountSql VARCHAR(8000)
	SET @PrintCountSql ='
	INSERT INTO #PrintCount(printcount,billnumberid,billtype)
	SELECT	SUM(PrintCount) AS printcount,
			p.billnumberid,
			p.BillType 
	FROM	PrintRecord p 
	INNER JOIN billindex(NOLOCK) bi on bi.[BillDate] BETWEEN ''' + @BeginDate +''' AND ''' + @EndDate +''' AND bi.IfCheck = ''t'' AND Bi.IfYearBill =0  AND bi.Billnumberid = p.billnumberid And bi.billtype = p.billtype 
	INNER JOIN Employee E ON E.TypeId = BI.checke
	'++ CASE WHEN @notInclude<>'' THEN REPLACE(@SQL_WHERE,@notInclude,'') ELSE @SQL_WHERE END+' 
	and	p.billtype not in (300,301) 
	GROUP BY p.billnumberid,p.BillType'
	
	--PRINT @PrintCountSql 
	EXEC(@PrintCountSql)
END	

CREATE TABLE #Ac_GoodsBill_VoucherBill( GoodsBillId NUMERIC(10,0),iscost int)
CREATE NONCLUSTERED INDEX  Ncix_acv_GoodsBillId on  #Ac_GoodsBill_VoucherBill(GoodsBillId )  

INSERT INTO #Ac_GoodsBill_VoucherBill( GoodsBillId,iscost) 
SELECT	DISTINCT 
		a.GoodsBillId ,
		a.iscost 
FROM	Ac_GoodsBill_VoucherBill a 
WHERE	a.iscost in (1,2)


CREATE TABLE #AuditingBill( BillNumberId NUMERIC(10,0),BillDetail [text])
CREATE NONCLUSTERED INDEX   Ncix_AuditingBill_BillNumberId on  #AuditingBill(BillNumberId)  

DECLARE @AuditingBillSql VARCHAR(8000)
SET @AuditingBillSql = 'INSERT INTO #AuditingBill(BillNumberId ,BillDetail )
						SELECT	a.BillNumberId,
								a.BillDetail
						FROM	AuditingBill a 
						inner join billindex(NOLOCK) bi on a.billnumberid=bi.billnumberid  
						INNER JOIN Employee E ON E.TypeId = BI.checke
						'+ CASE WHEN @notInclude<>'' THEN REPLACE(@SQL_WHERE,@notInclude,'') ELSE @SQL_WHERE END +'
								AND	a.IfAudit = 1
								AND a.BillIndexType = 2
								AND DATALENGTH(a.BillDetail) <> 0'
--PRINT @AuditingBillSql
EXEC(@AuditingBillSql)

CREATE TABLE #BillInout( BillNumberId NUMERIC(10,0))
CREATE NONCLUSTERED INDEX   Ncix_BillInout_BillNumberId on  #BillInout(BillNumberId )

IF @PTypeName <> ''  OR @kcsp <>''   OR @ptypecategoryid<>''
BEGIN
	INSERT INTO #BillInout(BillNumberId)
	SELECT DISTINCT BillNumberId FROM InOutStockTable T INNER JOIN #PType P ON T.PTypeId = P.TypeId
	UNION ALL 
	SELECT DISTINCT BillNumberId FROM Wx_inoutstocktable T INNER JOIN #PType P ON T.PTypeId = P.TypeId
	UNION ALL 
	SELECT DISTINCT BillNumberId FROM Wx_Bill_Call T INNER JOIN #PType P ON T.PTypeId = P.TypeId
	UNION ALL 
	SELECT DISTINCT BillNumberId FROM Advantage T INNER JOIN #PType P ON T.PTypeId = P.TypeId
	UNION ALL 
	SELECT DISTINCT BillNumberId FROM PriceProtectBill T INNER JOIN #PType P ON T.PTypeId = P.TypeId
	UNION ALL 
	SELECT DISTINCT BillNumberId FROM dbo.PT_Combin_SaleBackBill T INNER JOIN #PType P ON T.PTypeId = P.TypeId
	UNION ALL 
	SELECT DISTINCT BillNumberId FROM dbo.PT_Combin_SaleBill T INNER JOIN #PType P ON T.PTypeId = P.TypeId
	UNION ALL 
	SELECT DISTINCT BillNumberId FROM dbo.RetailCombinationBill T INNER JOIN #PType P ON T.PTypeId = P.TypeId
END

		
--优化，分页前只提取billnumberid，分页后再提取数据
CREATE TABLE #temp1
(
	BillnumberID 	numeric(10,0),
	Billdate 		varchar(23),
	BillCode 		varchar(200),
	Comment 		varchar(2000),	
	Explain			varchar(2000),
	DTypeId1		varchar(256),
	CwCheck			varchar(20),
	TotalQty 		 NUMERIC(24, 10) ,
	TotalMoney 		 NUMERIC(24, 10) ,
	TotalInMoney 	 NUMERIC(24, 10) ,
	redword 		int,
	[ID] 			INT,
	BillType 		INT ,
	Etype 			varchar(100),
	btype 			varchar(100),
	stype 			varchar(100),
	StypeID2 		VARCHAR(100),
	atype			VARCHAR(100),
	KTypeId			VARCHAR(100),
	KTypeId1		VARCHAR(100),
	KTypeId2		VARCHAR(100),
	PrintCount		INT,				--打印记录
	CheckTime		DATETIME,			--制单时间
	UpdateEfullname	VARCHAR(200),		--修改人
    LastUpdateTime	DATETIME,			--修改时间
    postName		VARCHAR(200),--过账人
    PostTime		DATETIME,
    costsale		VARCHAR(10)	,		--zs001:增添按成本销售标识
    NTOTALMONEY      NUMERIC(24, 10) ,		    --原币总金额
	NTOTALINMONEY	 NUMERIC(24, 10) ,		    --原币收现金额
	currencyFullName      varchar(100),		--原币币别
	dealbtypeid           VARCHAR(100),      --结算单位
	TallyId			VARCHAR(50),--记账人
	tallyname	VARCHAR(max),
	checke VARCHAR(100),--制单人
	redreason		VARCHAR(500),
	billdetail VARCHAR(max),
	IfConfirm		INT,					--是否入账
	TransferType	INT,					--资金调拨单 业务类型
	IsAuto INT,								--IaAuto = 1 自动的，手动0
	newposbill tinyint,
	waybillcode VARCHAR(200),
	tel VARCHAR(200),
	packway VARCHAR(200),
	goodsnumbers VARCHAR(200),
	existsattachfiles VARCHAR(2),
	adpricetype INT,
	ChargeOffTotal  NUMERIC(24, 10) ,
    cwchecker   VARCHAR(50), --账务审核人
    chargeofftype	VARCHAR(3)   ,
    iscost		VARCHAR(10),
    molingmoney NUMERIC(24, 10) ,--抹零金额
	preferencemoney NUMERIC(24, 10),--优惠金额
	deliveryaddress	VARCHAR(256),	--记账人
    sid numeric(10,0) IDENTITY (1, 1) NOT NULL,
    rcwchecker NVARCHAR(200),		--反审核人  2019-09-11 陈强 新增：对应版本9.91
    rcwchecktime	DATETIME,		--发审核时间 2019-09-11 陈强 新增：对应版本9.91
    posid	INT,					--POS编号   2019-09-16 陈强 新增：对应版本9.91
    fullname	NVARCHAR(200)		--pos名称   2019-09-16 陈强 新增：对应版本9.91    
)
CREATE NONCLUSTERED INDEX CIX_Temp_BillId ON #temp1(BillnumberId,BillType)


--处理排序
DECLARE @orderyWhere VARCHAR(1000)   =''
IF  CHARINDEX('stype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN Stype or_st ON bi.stype=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'stype_','or_st.') 
END
IF  CHARINDEX('dtypeid1',@OrderBy)>0
BEGIN
	SET @orderyWhere='	LEFT JOIN Department or_de ON bi.dtypeid1=or_de.typeID '
	SET @OrderBy= REPLACE(@OrderBy,'dtypeid1_','or_de.') 
END
IF  CHARINDEX('etype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN employee or_em ON bi.etype=or_em.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'etype_','or_em.') 
END
IF  CHARINDEX('btype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN btype or_bt ON bi.btype=or_bt.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'btype_','or_bt.') 
END
IF  CHARINDEX('dealbtypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN btype or_bt1 ON bi.dealbtypeid=or_bt1.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'dealbtypeid_','or_bt1.') 
END
IF  CHARINDEX('atype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN ac_items or_at ON bi.atype= or_at.nTypeid '
	SET @OrderBy= REPLACE(@OrderBy,'atype_','or_at.') 
END
IF  CHARINDEX('ktypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON bi.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid_','or_st.') 
END	
IF  CHARINDEX('ktypeid1',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON bi.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid1_','or_st.') 
END	
IF  CHARINDEX('ktypeid2',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON bi.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid2_','or_st.') 
END	

IF @PTypeName<>'' OR @kcsp <>''
	SELECT @SQL_LIST = 'SELECT 	distinct '
ELSE
	SELECT @SQL_LIST = 'SELECT '

SELECT @SQL_LIST = @SQL_LIST+'
								Bi.BillnumberID,
								CONVERT(varchar(100), bi.billdate,23) as billdate,--------
								bi.BillCode,
								bi.Comment,
								Bi.Explain,
								bi.DTypeId AS dtypeid1,
								CASE
								WHEN ISNULL(bi.CwCheck,0) = 0 THEN ''否''
								ELSE ''是''
								END AS CwCheck,
								Convert( NUMERIC(24, 10) ,case when bi.billtype=57 THEN 0   WHEN bi.redword=2 then -bi.TotalQty else bi.TotalQty end) as TotalQty,
								Convert( NUMERIC(24, 10) ,isnull(
								case WHEN bi.billtype=159 and bi.redword = 2  
										THEN (SELECT -sum(J_Total) FROM accountcredence WHERE BillNumberID=bi.billnumberid)
									WHEN bi.billtype=159 
										THEN (SELECT sum(J_Total) FROM accountcredence WHERE BillNumberID=bi.billnumberid)
									when bi.billtype=17 and bi.redword = 2  
										then -TotalInMoney 
									when  bi.billtype=17 and bi.redword in (0,1)  
										then bi.TotalInMoney 
									when  bi.billtype not in (17,159) and bi.redword = 2  
										then -TotalMoney 
									else bi.TotalMoney end,0)) as TotalMoney,
								Convert( NUMERIC(24, 10) ,isnull(case bi.redword when 2 then -bi.TotalInMoney else bi.TotalInMoney end,0)) as TotalInMoney,
								bi.redword,
								bi.ID,
								bi.billtype,
								ISNULL(bi.etypeid,'''') AS etype,
								ISNULL(bi.btypeid,'''') AS btype, 
								ISNULL(bi.stypeid,'''') AS stype,
								ISNULL(bi.StypeID2,'''') AS StypeID2,	--资金调拨单取出调入机构
								CASE
								WHEN bi.IfMulAccount = 1 THEN ''-99999''
											ELSE ISNULL(acs.nTypeId,'''')
								END AS atype,
								CASE
									WHEN Bi.BillType = 188 THEN Bi.KTypeId2
									ELSE Bi.KTypeId
								END AS KTypeId,
								CASE
									WHEN Bi.BillType = 160 THEN Bi.KTypeId2
									ELSE Bi.ktypeid 
								END AS KTypeId1,
								CASE
									WHEN Bi.BillType = 160 THEN Bi.KTypeId
									ELSE Bi.KTypeId2
								END AS KTypeId2,
								ISNULL(pCount.printcount,''0'') AS PrintCount,
								bi.checktime,
								e1.fullname as updateefullname,
								bi.lastupdatetime,
								e2.fullname as postname,
								bi.posttime,
								bi.costsale,
								Convert( NUMERIC(24, 10) ,isnull(
								case WHEN bi.billtype=159 and bi.redword = 2  
										THEN (SELECT -sum(nJ_Total) FROM accountcredence WHERE BillNumberID=bi.billnumberid)
									WHEN bi.billtype=159 
										THEN (SELECT sum(nJ_Total) FROM accountcredence WHERE BillNumberID=bi.billnumberid)
									when bi.billtype=17 and bi.redword = 2  
										then -nTotalInMoney 
									when  bi.billtype=17 and bi.redword in (0,1)  
										then bi.nTotalInMoney 
									when  bi.billtype not in (17,159) and bi.redword = 2  
										then -nTotalMoney 
									else bi.NTotalMoney end,0)) as nTotalMoney,
								Convert( NUMERIC(24, 10) ,isnull(case bi.redword when 2 then -bi.ntotalinmoney else bi.ntotalinmoney end,0)) as NTOTALINMONEY,
								ac.FullName as currencyFullName, 
								ISNULL(bi.dealbtypeid ,'''') AS dealbtypeid,     
								bi.TallyId,
								tallyname=e3.fullname,
								checkeName=E.FULLNAME,
								bi.redreason,
								CAST(AB.BillDetail AS VARCHAR(MAX)) AS BillDetail,
								bi.IfConfirm,
								bi.TransferType,
								bi.IsAuto,
								bi.newposbill,
								bi.waybillcode,
								bi.tel,
								bi.packway,
								bi.goodsnumber AS goodsnumbers,
								CASE 
									WHEN ISNULL((SELECT COUNT(1) FROM BillAttachFiles WHERE BillNumberId = bi.BillNumberId GROUP BY BillNumberId),0) > 0 THEN ''有'' 
									ELSE ''无'' 
								END AS existsattachfiles,
								bi.adpricetype ,
								ChargeOffTotal,
								bi.cwchecker,bi.chargeofftype,
								case when acv.iscost in(1,2) then ''是'' else ''否'' end as iscost,
								CASE
								WHEN bi.billtype in (9,4,66,12,46,34,6,161,167,170,305,215,11,45,160,168,170,172,312,181,4,66) THEN bi.NPreferencemoney  END AS molingmoney,	
								CASE 
								WHEN bi.billtype in (4,66) THEN bi.NPreferencemoney  END  AS preferencemoney,
								bi.deliveryaddress,
								bi.RChecker,
								cast(nullif(bi.RVaildDate,'''') as datetime) as rcwchecktime,
								bi.PosId,
								pi.Fullname'
            
-- 基本列表的SQL
SELECT @SQL_FROM='	FROM BillIndex(NOLOCK) bi 
					INNER JOIN Employee E ON bi.[BillDate] BETWEEN ''' + @BeginDate +''' AND ''' + @EndDate +''' AND bi.IfCheck = ''t'' AND Bi.IfYearBill = 0 AND  E.TypeId = BI.checke
					left JOIN PosInfo pi on pi.PosID=bi.PosId				
					left join ac_items acs on bi.atypeid=acs.nid 
					left join #Ac_GoodsBill_VoucherBill acv on bi.billnumberid=acv.GoodsBillId '

--打印记录
SELECT @SQL_FROM += ' 
				LEFT JOIN #PrintCount pCount ON (bi.BillNumberId = pCount.billnumberid and bi.billtype=pcount.billtype) '
					
SELECT @SQL_FROM += ' 
					LEFT JOIN employee E1 ON bi.updatee=e1.typeid 
					LEFT JOIN employee E2 ON bi.Poster=e2.typeid  
					LEFT JOIN employee E3 ON bi.TallyId=e3.typeid  
					LEFT JOIN AC_CURRENCY ac ON bi.cid = ac.CID
					LEFT JOIN #AuditingBill AB ON Bi.BillNumberId = AB.BillNumberId    '

SELECT @SQL_FROM +=' '+@SQL_JOIN

IF @PTypeName <> ''  OR @kcsp <>''   OR @ptypecategoryid<>''
BEGIN
	SET @SQL_FROM = @SQL_FROM + '
		INNER JOIN #BillInout T ON Bi.BillNumberId = T.BillNumberId
	'
END
-- 排序

SELECT @SQL = @SQL_LIST + @SQL_FROM + @SQL_WHERE


-- 求总记录数的语句
DECLARE @RowCount int
IF @PTypeName<>'' OR @BtypeName <> '' OR @kcsp <>'' OR @ptypecategoryid<>''
	BEGIN
	
		SELECT @SQL_SUM  = 'SELECT 
								Distinct case when bi.billtype=57 then 0 else isnull(bi.TotalQty,0) end as TotalQty,
								isnull(bi.TotalMoney,0) as TotalMoney,
								isnull(bi.TotalInMoney,0) as TotalInMoney,
								isnull(bi.NTOTALMONEY,0) as NTOTALMONEY,
								isnull(bi.NTOTALINMONEY,0) as NTOTALINMONEY,
								isnull(bi.NPreferenceMoney,0) as NPreferenceMoney,
								bi.redword,
								Bi.BillnumberID  
								 '+@SQL_FROM + @SQL_WHERE
		SELECT @SQL_SUM ='SELECT 
								isnull(SUM(CASE X.redword when 2 then -X.TotalQty else X.TotalQty END),0) as TotalQty,
								isnull(SUM(CASE X.redword when 2 then -X.TotalMoney else x.TotalMoney END),0) as TotalMoney,
								isnull(SUM(CASE X.redword when 2 Then -X.TotalInMoney else X.TotalInMoney END),0) as TotalInMoney ,
								isnull(SUM(CASE X.redword when 2 then -X.NTOTALMONEY else x.NTOTALMONEY END),0) as NTOTALMONEY,
								isnull(SUM(CASE X.redword when 2 Then -X.NTOTALINMONEY else X.NTOTALINMONEY END),0) as NTOTALINMONEY,
								isnull(SUM(CASE X.redword when 2 Then -X.NPreferencemoney else X.NPreferencemoney END),0) as molingmoney 
						  FROM (' + @SQL_SUM +') X'
							
	END
ELSE
	BEGIN
		SELECT @SQL_SUM  = 'SELECT  
								isnull(SUM(isnull(case when bi.billtype=57 then 0 when bi.redword=2 then -bi.TotalQty else bi.TotalQty end,0)),0) as TotalQty,
								isnull(SUM(isnull(case bi.redword when 2 then -bi.TotalMoney else bi.TotalMoney end,0)),0) as TotalMoney,
								isnull(SUM(isnull(case bi.redword when 2 then -bi.TotalInMoney else bi.TotalInMoney end,0)),0) as TotalInMoney,
								isnull(SUM(isnull(case bi.redword when 2 then -bi.NTOTALMONEY else bi.NTOTALMONEY end,0)),0) as NTOTALMONEY,
								isnull(SUM(isnull(case bi.redword when 2 then -bi.NTOTALINMONEY else bi.NTOTALINMONEY end,0)),0) as NTOTALINMONEY,
								isnull(SUM(isnull(case bi.redword when 2 then -bi.NPreferencemoney else bi.NPreferencemoney end,0)),0) as molingmoney
							 '+@SQL_FROM + @SQL_WHERE
	END

DECLARE @PageNum int
DECLARE @PageBegin int
DECLARE @PageEnd int
SET @PageNum =@PageNo *@UserDeRowCount

SET @PageBegin=(@PageNo-1)*@UserDeRowCount+1
SET @PageEnd=(@PageNo)*@UserDeRowCount



IF @OrderBy<>''
BEGIN
	SET @OrderBy=' ORDER BY ' +@OrderBy
END
ELSE
BEGIN
	SET @OrderBy=' ORDER BY bi.billdate desc,BI.billcode desc'
END

SET @SQL ='	INSERT INTO #temp1  SELECT bi.* FROM (SELECT DISTINCT X.* FROM ('+@SQL +') X )  bi      '+@orderyWhere+@OrderBy


--PRINT(@SQL_ORDER)
--PRINT(@SQL)
EXEC(@SQL)

SET @RowCount = @@ROWCOUNT


IF @PageNo <>0
BEGIN
		SET @SQL = 'select a.*					
					From  (
							SELECT 	A.*,
									SysDiy1_head,
									SysDiy2_head,
									SysDiy3_head,
									SysDiy4_head, 
									SysDiy5_head,
									SysDiy6_head,
									SysDiy7_head,
									SysDiy8_head,
									SysDiy9_head,
									SysDiy10_head,
									SysDiy11_head,
									SysDiy12_head,
									SysDiy13_head,
									SysDiy14_head,
									SysDiy15_head,
									SysDiy16_head,
									SysDiy17_head,
									SysDiy18_head,
									SysDiy19_head,
									SysDiy20_head,
									SysDiy21_head,
									SysDiy22_head,
									SysDiy23_head,
									SysDiy24_head,
									SysDiy25_head,
									SysDiy26_head,
									SysDiy27_head,
									SysDiy28_head,
									SysDiy29_head,
									SysDiy30_head,
									SysDiy31_head,
									SysDiy32_head,
									SysDiy33_head,
									SysDiy34_head,
									SysDiy35_head,
									SysDiy36_head,
									SysDiy37_head,
									SysDiy38_head,
									SysDiy39_head,
									SysDiy40_head,
									'+Convert(varchar(100),@RowCount)+' as TotalNum
							FROM 	#temp1 a  
							LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
							)a inner join billindex bi on a.billnumberid=bi.billnumberid 
								WHERE 	A.sid>='+convert(varchar(10),@PageBegin) +'
										AND A.sid<='+convert(varchar(10),@PageEnd)+'
							ORDER BY A.sid'
		--PRINT @SQL	
	
		EXEC (@SQL)
		
		IF @BillType<>'' AND CHARINDEX(',',@BillType)<=0  -- 算合计
		BEGIN	
			--PRINT @SQL_SUM
			EXEC (@SQL_SUM)
		END
		
	END
ELSE
	BEGIN	
		SET @SQL = 'select a.*						
						FROM (	
								SELECT 	a.*,SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
										SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
										SysDiy17_head,
										SysDiy18_head,
										SysDiy19_head,
										SysDiy20_head,
										SysDiy21_head,
										SysDiy22_head,
										SysDiy23_head,
										SysDiy24_head,
										SysDiy25_head,
										SysDiy26_head,
										SysDiy27_head,
										SysDiy28_head,
										SysDiy29_head,
										SysDiy30_head,
										SysDiy31_head,
										SysDiy32_head,
										SysDiy33_head,
										SysDiy34_head,
										SysDiy35_head,
										SysDiy36_head,
										SysDiy37_head,
										SysDiy38_head,
										SysDiy39_head,
										SysDiy40_head,
										'+Convert(varchar(100),@RowCount)+' as TotalNum
								FROM 	#temp1 a  
								LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
								) A INNER JOIN BILLINDEX BI ON A.BILLNUMBERID=BI.BILLNUMBERID ORDER BY A.sid'
		--PRINT @SQL  	
		EXEC (@SQL)	
		
	END
-- 单据明细摘要查询


-- ========================================= 删除临时表
IF RTRIM(@ZYDetail)<>'' 
	BEGIN
		drop table #commentTable
	END

DROP TABLE #temp1

--IF RTRIM(@BtypeName)<>''
	DROP TABLE #BType

IF RTRIM(LTRIM(@Area))<>''
	DROP TABLE #AreaType


IF RTRIM(@AtypeName)<>''
	DROP TABLE #AType

IF RTRIM(@AtypeName)<>''
	DROP TABLE #listtable
	
IF RTRIM(@KtypeName)<>''
	DROP TABLE #KType

IF RTRIM(@KtypeName2)<>''
	DROP TABLE #KType2
	
IF NOT (@stypeid='' AND @MStypeid = '00000')
	DROP TABLE #Stype	

DROP TABLE #GetManKTypeId,#Employee,#Department,#PTypePriceBillId,#PTypeDiscountBillId,#PTypeTaxBillId,#UEmployee,#PEmployee,#PType,#dealBtype,
			#AuditingBill,#Ac_GoodsBill_VoucherBill,#BillInout

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryBuyRequestBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_QueryBuyRequestBillIndex
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2011-8-16
	描述：请购单单据调阅
*/
CREATE PROCEDURE Gp_QueryBuyRequestBillIndex
( 
	@MagEType		varchar(50),
	@BillType		varchar(5)='',
	@BeginDate		varchar(25)='',
	@EndDate		varchar(25)='',
	@BillCode		varchar(200)='',
	@EtypeName		varchar(200)='',
	@BtypeName		varchar(200)='',
	@IfAudit		CHAR(2) = '1' ,
	@AtypeName		varchar(200)='',
	@RelatBtype		varchar(200)='0',		--订单调用请购单的时候如果全部明细已经是订单或入库状态的单据不显示
	@Comment		varchar(256)='',
	@BillNumberId	numeric(10)=0,
	@OrderBy		varchar(250)='',
	@FilterBill		varchar(250)='',
	@stypeid		varchar(50),
	@DTypeID  		VARCHAR(100) = '',
	@IsIni			int=0,						--1为期初单据，0为非期初单据
	@RequestDate	varchar(25)='',
	@dealbtypeid	varchar(100)='',
	@checketypeid	VARCHAR(200)='',
	@ptypeid		VARCHAR(200)='',
	@explain		VARCHAR(1000)='',
	@cid            VARCHAR(50) = ''
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @MagEType
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 分支机构
IF @Stypeid<>'' or @chvMStypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END

-- 部门
IF @chvMDtypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetaildType FROM F_BaseGetManDetailDType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END

DECLARE @re 			int,	-- 修改他人草稿的权限\
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@offset			INT
IF (@chvOperatorID = '00001')
	SET @re = 0
ELSE
BEGIN	
	SELECT @offset = 135	-- 检查某人是否有查看管辖职员草稿得权限
	EXEC @re = GP_CheckLimit @chvOperatorID,@offset
END	
-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(3000)
SET @SQL = '
	SELECT DISTINCT	a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.DTypeID,
			a.StypeID,
			a.Explain,
			a.checke,
			a.Comment,
			CASE WHEN a.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE a.CID END  as cid,
			CASE WHEN a.CID=0 THEN
			(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
			ELSE
			(select fullname from Ac_Currency where cid=a.CID) END as fullname
	FROM	RequestIndex a ' + @SQL_Man 
IF @IfAudit<>2 
begin
	
	IF @RelatBtype='1' 
	BEGIN
		SET @SQL=@SQL+ ' and(
								( a.billnumberid in 
								   (
								    SELECT BillNumberID FROM dbo.AuditingBill b
								    INNER JOIN  AuditingFlowSet c
								    ON b.AuditingID=c.AuditingID 
								    AND b.IfAudit = ''1''
								    where billtype=204
								    )
								 ) 
								 OR
							     ( a.BillNumberId NOT IN 
							        ( SELECT b.BillNumberID FROM dbo.AuditingBill b
									  INNER JOIN dbo.AuditingFlowSet c
									  ON b.AuditingID=c.AuditingID 
								    )
								   OR ISNULL(a.IfAudit,'''')=''''
								 ) 
							)
							AND a.billnumberid not in
					          (
								SELECT BILLNUMBERID FROM RequestIndex B
								WHERE BILLTYPE='+@BillType+' AND B.IFAUDIT=''0'' AND B.BILLNUMBERID
								NOT IN (
								SELECT BILLNUMBERID FROM AuditingBill A 
								INNER JOIN AuditingFlowSet C ON A.AuditingID=C.AuditingID
								WHERE C.BILLTYPE='+@BillType+')
					          )
							'
		
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+ 'INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID  and billindextype=3  AND ab.IfAudit = ''' + @IfAudit + ''''
	END
END
SET @SQL = @SQL + ' INNER JOIN RequestBill b ON a.BillNumberId=b.BillNumberId '
SET @SQL = @SQL + '	WHERE	a.BillDate >= ''' + @BeginDate + ''' AND a.BillDate <= ''' + @EndDate + '''
					AND a.BillType = ' + @BillType 

IF @EtypeName <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EtypeName + ''''
IF @DTypeID <> '' SET @SQL = @SQL + ' AND a.DTypeID=''' + @DTypeID + ''''
IF @RelatBtype='1' SET @SQL=@SQL+' AND a.billnumberid in (SELECT rb.billnumberid FROM requestbill rb
WHERE rb.[state] <= 8 AND rb.isstop <> 1 and rb.qty-rb.RequestQty<>0)'
IF @RequestDate <>'' 
BEGIN
	SET @SQL = @SQL +' AND CONVERT(VARCHAR(10),b.RequestDate,25)='''+@RequestDate+''''
END
IF @dealbtypeid <>''
BEGIN
	SET @SQL = @SQL +' AND b.btypeid='''+@dealbtypeid+''''
END
IF @IsIni = 1 SET @SQL = @SQL + ' AND a.IsIni=1 '
ELSE
BEGIN
	SET @SQL = @SQL + ' AND a.IsIni=0 ' 
	IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''	
	--去掉该权限
	--IF @re <> 0 SET @SQL = @SQL + ' AND a.Checke = ''' + @chvOperatorID + ''''
END	
IF @IfAudit = 2
			SET @SQL = @SQL + '
	AND	NOT EXISTS(
				SELECT ab.BillNumberID FROM AuditingBill ab
				WHERE a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 3
			) '
IF @checketypeid <>''
BEGIN
    SET @SQL+=' AND a.checke='+@checketypeid+''
END
IF @ptypeid<>''
BEGIN
    SET @SQL+=' AND b.PtypeId='+@ptypeid+''
END
IF @cid <>''
BEGIN
    SET @SQL+=' AND a.cid='+@cid+''
END
IF @Comment<>''
BEGIN
    SET @SQL+=' AND a.comment LIKE ''%' + @Comment + '%'''
END
IF @explain<>''
BEGIN
    SET @SQL+=' AND a.Explain like ''%' + @Explain + '%'''
END

SET @SQL = @SQL + ' AND  a.isstop <> 1  ORDER BY a.BillDate DESC, a.BillCode'

PRINT(@SQL)
EXEC (@SQL)
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMDtypeid  = '-99999' DROP TABLE #F_BaseGetManDetaildType 
IF @Stypeid<>'' or @chvMStypeid<>'00000' DROP TABLE #F_BaseGetManDetailSType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryByBtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryByBtype]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryByBtype    Script Date: 2002-6-20 10:14:50 ******/

CREATE  PROCEDURE Gp_QueryByBtype 
(    
 @BeginDate  varchar(30),
     @EndDate  varchar(30), 
     @ParId    varchar(25),
     @BtypeId  varchar(25)
)
--@encode$--
as
SET NOCOUNT ON
declare @cz_Query varchar(600),@Sql varchar(2000),@cz_where varchar(50)
declare @ap_id varchar(25),@ar_id varchar(25),@p_id varchar(25)
select @ap_id = '0000200001'    --应付
select @ar_id = '0000100005'    --应收
select @p_id = '0'
select @cz_query=''
select @cz_where= ''
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=' and (c.billdate>='+char(39)+@begindate+char(39)+' and c.billdate<='+char(39)+@enddate+char(39)+') '
if rtrim(@btypeid) <> ''
 select @cz_where=' and a.typeid='+char(39)+@btypeid+char(39)
--select @cz_query=substring(@cz_query,1,len(@cz_query)-4)
select @Sql='SELECT typeId, Parid, leveal,sonnum, FullName, UserCode,
          (SELECT isnull(abs(SUM(b.total)), 0)
         FROM inoutstocktable b, BillIndex c
         WHERE b.billnumberid = c.billnumberid AND LEFT(b.Btypeid, len(a.typeid)) 
               = a.typeid AND (c.BillType = 11 or c.billtype=203) AND b.ptypeid <>'+char(39)+@p_id+char(39)+@cz_query+') AS Saletotal,
          (SELECT isnull(abs(SUM(b.costtotal - b.total)), 0)
         FROM inoutstocktable b, BillIndex c
         WHERE b.billnumberid = c.billnumberid AND LEFT(b.btypeid, len(a.typeid)) 
               = a.typeid AND (c.BillType = 11 or c.billtype=203) AND b.ptypeid <> '+char(39)+@p_id+char(39)+@cz_query+') AS CostTotal,
          (SELECT isnull(abs(SUM(b.total)), 0)
         FROM gatheringbill b, BillIndex c
         WHERE b.billnumberid = c.billnumberid AND LEFT(c.Btypeid, len(a.typeid)) 
               = a.typeid'+ @cz_query+') AS backtotal
FROM Btype a
WHERE Parid ='+ char(39)+@parid+char(39) + @cz_where
--print @sql
exec(@sql)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryByEtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryByEtype]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryByEtype    Script Date: 2002-6-20 10:14:50 ******/

CREATE  PROCEDURE Gp_QueryByEtype 
(    
 @BeginDate  varchar(30),
     @EndDate  varchar(30), 
     @Etypeid  varchar(25),
     @Parid    varchar(25)
)
--@encode$--
as
SET NOCOUNT ON
declare @cz_Query varchar(600),@Sql varchar(2000),@cz_where varchar(50)
declare @ap_id varchar(25),@ar_id varchar(25),@p_id varchar(25)
select @ap_id = '0000200001'    --应付
select @ar_id = '0000100005'    --应收
select @p_id = '0'
select @cz_query=''
select @cz_where= ''
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=' and (c.billdate>='+char(39)+@begindate+char(39)+' and c.billdate<='+char(39)+@enddate+char(39)+') '
if rtrim(@etypeid) <> ''
 select @cz_where=' and a.typeid='+char(39)+@etypeid+char(39)
--select @cz_query=substring(@cz_query,1,len(@cz_query)-4)
select @Sql='SELECT typeId, leveal,Parid, sonnum, FullName, UserCode,
          (SELECT isnull(abs(SUM(b.total)), 0)
         FROM inoutstocktable b, BillIndex c
         WHERE b.billnumberid = c.billnumberid AND LEFT(b.etypeid, len(a.typeid)) 
               = a.typeid AND (c.BillType = 11 or c.billtype=203) AND b.ptypeid <>'+char(39)+@p_id+char(39)+@cz_query+') AS Saletotal,
          (SELECT isnull(abs(SUM(b.costtotal - b.total)), 0)
         FROM inoutstocktable b, BillIndex c
         WHERE b.billnumberid = c.billnumberid AND LEFT(b.etypeid, len(a.typeid)) 
               = a.typeid AND (c.BillType = 11 or c.billtype=203) AND b.ptypeid <> '+char(39)+@p_id+char(39)+@cz_query+') AS CostTotal,
          (SELECT isnull(abs(SUM(b.total)), 0)
         FROM listtable b, BillIndex c
         WHERE b.billnumberid = c.billnumberid AND LEFT(b.etypeid, len(a.typeid)) 
               = a.typeid AND b.Atypeid = '+char(39)+@ar_id+char(39)+@cz_query+') AS ARtotal,
          (SELECT isnull(abs(SUM(b.total)), 0)
         FROM listtable b, BillIndex c
         WHERE b.billnumberid = c.billnumberid AND LEFT(b.etypeid, len(a.typeid)) 
               = a.typeid AND b.Atypeid ='+ char(39)+@ap_id+char(39)+@cz_query+') AS APtotal,
          (SELECT isnull(SUM(b.total), 0)
         FROM gatheringbill b, BillIndex c
         WHERE b.billnumberid = c.billnumberid AND LEFT(c.etypeid, len(a.typeid)) 
               = a.typeid'+ @cz_query+') AS backtotal
FROM employee a
WHERE Parid ='+ char(39)+@parid+char(39) + @cz_where
--print @sql
exec(@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryCarFeeIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryCarFeeIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-22
	描述：调入车辆费用单
*/
CREATE PROCEDURE [dbo].[Gp_QueryCarFeeIndex]
( 
	@MagEType		varchar(50),
	@BillType		varchar(5)='',
	@BeginDate		varchar(25)='',
	@EndDate		varchar(25)='',
	@BillCode		varchar(200)='',
	@EtypeName		varchar(200)='',
	@BtypeName		varchar(200)='',
	@IfAudit		CHAR(2) = '1' ,
	@AtypeName		varchar(200)='',
	@RelatBtype		varchar(200)='',
	@Comment		varchar(256)='',
	@BillNumberId		numeric(10)=0,
	@OrderBy		varchar(250)='',
	@FilterBill		varchar(250)='',
	@stypeid		varchar(50),
	@DTypeID  		VARCHAR(100) = '',
	@raTypeID		varchar(50)=''
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @MagEType
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 分支机构
IF @Stypeid<>'' or @chvMStypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END


-- 部门
IF @chvMDtypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetaildType FROM F_BaseGetManDetailDType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END

/*--有审核过账的单据应该加上以下权限控制
DECLARE @re 			int,	-- 修改他人草稿的权限\
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@offset			INT
--IF (@chvOperatorID = '00001')
	--SET @re = 0
--ELSE
--BEGIN	
	SELECT @offset = 135	-- 检查某人是否有查看管辖职员草稿得权限
	EXEC @re = GP_CheckLimit @chvOperatorID,@offset
--END	
*/
-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(3000)
SET @SQL = '
	SELECT	a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.DTypeID,
			a.StypeID,
			a.Explain,
			a.checke,
			a.Comment
	FROM	CM_FeeIndex a ' + @SQL_Man + '
	WHERE	a.BillDate >= ''' + @BeginDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			AND a.BillType = ' + @BillType

IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @EtypeName <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EtypeName + ''''
IF @DTypeID <> '' SET @SQL = @SQL + ' AND a.DTypeID=''' + @DTypeID + ''''
--IF @re <> 0 SET @SQL = @SQL + ' AND a.Checke = ''' + @chvOperatorID + ''''
IF @raTypeID <> '' SET @SQL = @SQL + ' AND a.CarId=''' +@raTypeID+ ''''
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC, a.BillCode'

--PRINT(@SQL)
EXEC (@SQL)
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMDtypeid  = '-99999' DROP TABLE #F_BaseGetManDetaildType 
IF @Stypeid<>'' or @chvMStypeid<>'00000' DROP TABLE #F_BaseGetManDetailSType



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryCarUseIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryCarUseIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-22
	描述：调入车辆使用登记单
*/
CREATE PROCEDURE [dbo].[Gp_QueryCarUseIndex]
( 
	@MagEType		varchar(50),
	@BillType		varchar(5)='',
	@BeginDate		varchar(25)='',
	@EndDate		varchar(25)='',
	@BillCode		varchar(200)='',
	@EtypeName		varchar(200)='',
	@BtypeName		varchar(200)='',
	@IfAudit		CHAR(2) = '1' ,
	@AtypeName		varchar(200)='',
	@RelatBtype		varchar(200)='',
	@Comment		varchar(256)='',
	@BillNumberId		numeric(10)=0,
	@OrderBy		varchar(250)='',
	@FilterBill		varchar(250)='',
	@stypeid		varchar(50),
	@DTypeID  		VARCHAR(100) = ''
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @MagEType
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 分支机构
IF @Stypeid<>'' or @chvMStypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END


-- 部门
IF @chvMDtypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetaildType FROM F_BaseGetManDetailDType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END
-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(3000)
SET @SQL = '
	SELECT	a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.DTypeID,
			a.StypeID,
			a.Explain,
			a.checke,
			a.Comment
	FROM	CM_CarUseIndex a ' + @SQL_Man + '
	WHERE	a.BillDate >= ''' + @BeginDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			AND a.BillType = ' + @BillType

IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @EtypeName <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EtypeName + ''''
IF @DTypeID <> '' SET @SQL = @SQL + ' AND a.DTypeID=''' + @DTypeID + ''''
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC, a.BillCode'

--PRINT(@SQL)
EXEC (@SQL)
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMDtypeid  = '-99999' DROP TABLE #F_BaseGetManDetaildType 
IF @Stypeid<>'' or @chvMStypeid<>'00000' DROP TABLE #F_BaseGetManDetailSType



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_QueryCombMxCashBank]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_QueryCombMxCashBank]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


-- 现金银行查询明细账
-- 徐辉 2011-04-22
-- 分机机构调整
CREATE     PROCEDURE Gp_QueryCombMxCashBank
( 
	@TypeId			VARCHAR(50),		--查询ID
	@OperatorId		VARCHAR(50),		--操作员Id
	@queryType		VARCHAR(5),			--1:结算单位 2：职员 3：仓库
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate			VARCHAR(20),		--结束日期
	@ItemTypeID		VARCHAR(MAX),		--账户名称
	@StypeId			VARCHAR(MAX),		--分支机构Id
	@DealBTypeId	VARCHAR(MAX),		--往来单位
	@BTypeId			VARCHAR(MAX),		--结算单位
	@ETypeID			VARCHAR(MAX),		--经手人
	@DTypeID			VARCHAR(MAX),		--部门
	@Cid					INT,						--币种ID

	 @OrderBy		 VARCHAR(50),
	 @chkRed       int				--是否显示红冲 0为不显示红冲，1为显示红冲	
)

--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------

--=============================基本信息权限范围获取【BEGIN】=======================================
--账户信息
CREATE TABLE #Item(RowId INT,Nid INT,TypeID VARCHAR(50),UserCode VARCHAR(200),Fullname VARCHAR(200)) CREATE CLUSTERED INDEX #Stype_P_K ON #Item(TypeId)
INSERT INTO #Item(RowId,Nid,TypeID,UserCode,Fullname)
SELECT 
	ROW_NUMBER()OVER(ORDER BY I.usercode) RowId,
	I.nId,
	i.nTypeId,
	i.UserCode,
	i.FullName
FROM dbo.F_GetAllManagerBaseTypeId(@ItemTypeID,5,@OperatorId) F
INNER JOIN Ac_Items I ON I.nId=F.TypeId AND I.SonNum=0 AND F.TypeId NOT IN(27,39)--排除(1151-预付资金 2131-预收资金)


--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
INSERT INTO #Stype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorId)

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #DealBtype_P_K ON #DealBtype(TypeId)
INSERT INTO #DealBtype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId)
IF(ISNULL(@DealBTypeId,'')='' AND @queryType IN('E','D'))
	BEGIN
		INSERT INTO #DealBtype(TypeID) VALUES('')
	END


--结算单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(@queryType='B')
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@TypeId,2,@OperatorId)
	END
ELSE 
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorId)
	END
IF(ISNULL(@BTypeId,'')='' AND @queryType IN('E','D'))
	BEGIN
		INSERT INTO #Btype(TypeID) VALUES('')
	END

--经手人
CREATE TABLE #Etype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF(@queryType='E')
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@TypeId,3,@OperatorId) WHERE TypeId<>'00001'
	END
ELSE 
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeID,3,@OperatorId) WHERE TypeId<>'00001'
	END
--部门
CREATE TABLE #Dtype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
	IF(@queryType='D')
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@TypeId,9,@OperatorId)
	END
ELSE 
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorId)
	END

--=============================基本信息权限范围获取【END】=======================================

--=============================业务处理【BEGIN】=====================================
DECLARE 
	@SQL VARCHAR(MAX)='',
	@OrderStr VARCHAR(MAX)=''
	
IF @OrderBy = 'ByDate_a'		--ORDER BY date
    SET @OrderStr= ' ORDER BY Bill.billdate,Bill.billtype, Bill.BillCode'

ELSE IF @OrderBy = 'ByBillNo_a' 	--ORDER BY Bill No.
    SET @OrderStr= ' ORDER BY Bill.BillCode'

ELSE IF @OrderBy = 'ByBillType_a'	--ORDER BY Bill type
    SET @OrderStr= ' ORDER BY Bill.billtype, Bill.billdate, Bill.BillCode'

ELSE IF @OrderBy = 'ByBillID_a'	--ORDER BY Bill ID
    SET @OrderStr= ' ORDER BY Bill.posttime'

ELSE IF @OrderBy = 'ByDate_d'		--ORDER BY date DESC 
    SET @OrderStr= ' ORDER BY Bill.billdate DESC, Bill.billtype, Bill.BillCode'

ELSE IF @OrderBy = 'ByBillNo_d' 	--ORDER BY Bill No. DESC 
    SET @OrderStr= ' ORDER BY Bill.BillCode DESC'

ELSE IF @OrderBy = 'ByBillType_d'	--ORDER BY Bill type DESC 
    SET @OrderStr= ' ORDER BYBill. billtype DESC, Bill.billdate, Bill.BillCode'

ELSE IF @OrderBy = 'ByBillID_d'	--ORDER BY Bill ID DESC 
    SET @OrderStr= ' ORDER BY Bill.posttime DESC'
ELSE
    SET @OrderStr= ' ORDER BY Bill.billdate'

SET @SQL='
	SELECT
		Row_Number() over ('+@OrderStr+'  ) id  ,
		Bill.billnumberid,
		Bill.RedWord,
		Bill.BillDate,
		Bill.BillCode,
		Bill.billtype,
		T.BillName,
		Bill.STypeID,
		Bill.BtypeId,
		Bill.EtypeId,
		Bill.DTypeID,
		bill.Comment,
		bill.explain,
		Bill.posttime,
		SUM(CASE WHEN L.Total>0 THEN L.NTotal ELSE 0  END) addtotalfor,
		SUM(CASE WHEN L.Total>0 THEN L.Total ELSE 0 END) addtotal,
		SUM(CASE WHEN L.Total<0 THEN -1*L.NTotal ELSE 0 END) dectotalfor,
		SUM(CASE WHEN L.Total<0 THEN -1*L.Total ELSE 0 END) dectotal
	INTO #temp
	FROM ListTable L
	INNER JOIN BillIndex Bill ON Bill.BillNumberId=L.BillNumberId AND L.BillType=Bill.BillType
	INNER JOIN BillName T ON T.Billtype=L.BillType
	INNER JOIN #Item A ON A.Nid=L.AtypeId
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	INNER JOIN #Dtype D ON D.TypeID=L.DtypeId
	INNER JOIN #Stype S ON S.TypeID=L.STypeID--分支机构
	INNER JOIN #Btype B ON B.TypeID=Bill.btypeid
	INNER JOIN #DealBtype DB ON DB.TypeID=Bill.DealBTypeID
	WHERE	bill.BillDate BETWEEN '''+@StartDate+'''  AND '''+@EndDate+'''
			AND L.CID='+CAST(@Cid AS VARCHAR)

	--是否显示红单
	IF(@chkRed=0)
		SET @SQL+='	AND bill.RedWord=0'

	SET @SQL+='
	GROUP BY 
		Bill.billnumberid,
		Bill.RedWord,
		Bill.BillDate,
		Bill.BillCode,
		Bill.billtype,
		T.BillName,
		Bill.STypeID,
		Bill.BtypeId,
		Bill.EtypeId,
		Bill.DTypeID,
		bill.Comment,
		bill.explain,
		Bill.posttime

SELECT 
	T.* ,
	(SELECT SUM(addtotalfor-dectotalfor) FROM #temp  WHERE Id<=T.Id)  jetotalfor,
	(SELECT SUM(addtotal-dectotal) FROM  #temp WHERE Id<=T.Id)  jetotal
FROM #temp T
ORDER BY Id 

DROP TABLE #temp
'
EXEC(@SQL)
--=============================业务处理【END】=======================================

--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#DealBtype,#Dtype,#Etype,#Item,#Stype

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryCouponBillIndexLi]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryCouponBillIndexLi]
GO





CREATE PROCEDURE Gp_QueryCouponBillIndexLi
( 
	@OperatorID		varchar(100) 	,  			-- 操作员
	@BeginDate	 	varchar(25)  	='', 		-- 开始时间
	@EndDate	 	varchar(25)  	='',   		-- 结束时间
    @dealBTypeId	VARCHAR(8000)='',--结算单位
	@deal_btypeid	VARCHAR(8000)='',--往来单位
	@ETypeId	VARCHAR(8000)='',
	@KTypeId	VARCHAR(8000)='',
	@STypeId	VARCHAR(8000)='',
	@billtype	VARCHAR(100)='',
	@UserDeRowCount INT,
	@PageNo        	INT,
	@billstate      INT ,
	@OrderBy	 		varchar(MAX)=''	    	-- 排序
	
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON



CREATE TABLE #Btype (TypeID VARCHAR(50),UserCode VARCHAR(26),FullName VARCHAR(66))
CREATE TABLE #deal_btype(TypeID VARCHAR(50),UserCode VARCHAR(26),FullName VARCHAR(66))
CREATE TABLE #Etype (TypeID VARCHAR(50))
CREATE TABLE #Ktype (TypeID VARCHAR(50))
CREATE TABLE #Stype (TypeID VARCHAR(50))



DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT


-----处理时间

IF @dealBTypeId =''--结算单位
	INSERT INTO #Btype(typeid,UserCode,FullName) SELECT typeid,usercode,fullname FROM btype WHERE  typeid IN  ( SELECT  typeid FROM  F_GetManDetailBType(@OperatorID))
ELSE
	INSERT INTO #Btype(typeid,UserCode,FullName) SELECT typeid,usercode,fullname FROM btype WHERE  typeid IN  ( SELECT  a.typeid FROM  F_GetManDetailBType(@OperatorID) a, (SELECT  * FROM   dbo.f_split(@dealBTypeId,',')) b WHERE  left(a.typeid,len(b.a))=b.a)

IF @deal_btypeid=''--往来单位
	INSERT INTO #deal_btype(typeid,UserCode,FullName) SELECT b.typeid,b.UserCode,b.FullName FROM dbo.btype b,F_GetManDetailBType(@OperatorID) F WHERE  B.Typeid = F.typeid  
ELSE
	INSERT INTO #deal_btype( typeid,UserCode,FullName ) SELECT typeid,UserCode,FullName FROM btype WHERE typeid in ( SELECT a.typeid FROM  F_GetManDetailBType(@OperatorID) a, (SELECT  * FROM   dbo.f_split(@deal_BTypeId,',')) b WHERE  left(a.typeid,len(b.a))=b.a)

IF @ETypeID=''
	INSERT INTO #Etype SELECT  typeid FROM  F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype SELECT  a.typeid FROM  F_GetManDetailEType(@OperatorID) a, (SELECT  * FROM   dbo.f_split(@EtypeID,',')) b WHERE  left(a.typeid,len(b.a))=b.a

IF @KTypeID=''
BEGIN
	INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorID)
	insert into #Ktype select '10000'
END
ELSE
	INSERT INTO #Ktype select a.typeid from F_GetManDetailKType(@OperatorID) a,  (select * from  dbo.f_split(@KtypeID,',')) b where left(a.typeid,len(b.a))=b.a

INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)


DECLARE @SQL		VARCHAR(MAX)
DECLARE @SQL_LIST	VARCHAR(MAX)
DECLARE @SQL_FROM	VARCHAR(MAX)
DECLARE @SQL_WHERE	VARCHAR(MAX)
DECLARE @SQL_ORDER	VARCHAR(MAX)
DECLARE @FiltVal	VARCHAR(MAX)
DECLARE @SQL_SUM	VARCHAR(MAX)

SET @SQL_SUM = ''

SELECT @SQL_LIST  = ''
SELECT @SQL_WHERE = ''
SELECT @SQL_FROM  = ''
SELECT @SQL_ORDER = ''
SELECT @SQL  = ''

DECLARE @SQL_DEBT VARCHAR(2000)='' 


SET @SQL_WHERE = '  WHERE	bi.[BillDate]>=''' + @BeginDate +'''
							AND bi.[BillDate]<=''' + @EndDate +'''
							AND bi.ifyearbill = 0 and bi.IsIni = 0
					  '

--IF @billstate <> 0 --全部
--BEGIN
 IF @billstate= 1 --保存状态
	SET @SQL_WHERE = @SQL_WHERE+' AND bi.IfCheck = ''f'' '
 IF @billstate= 0 --过账状态
	SET @SQL_WHERE = @SQL_WHERE+' AND bi.IfCheck = ''t'' '
--END

IF @BillType <> ''
 SET @SQL_WHERE = @SQL_WHERE+ ' AND Bi.BillType IN (' + @BillType +') '
ELSE
 SET @SQL_WHERE = @SQL_WHERE+ ' AND Bi.BillType NOT IN (423,424,425,426,428,429) '
 
--临时表
CREATE TABLE #temp1
(
    BillNumberID		BIGINT		,		 
	BillDate			DATETIME,
	BillCode			VARCHAR(50)	,		
	BillType			INT			,	
	billtypename        VARCHAR(100)	,
	dealusercode        VARCHAR(100)	,
	dealfullname        VARCHAR(100)	,
	btypeusercode       VARCHAR(100)	,
	btypefullname       VARCHAR(100)	,
	dfullname           VARCHAR(100)	,
	etypename	        VARCHAR(100)	,
	checkename	        VARCHAR(100)	,
	stypename	        VARCHAR(100)	,
	FromType			VARCHAR(50)	    ,				
	STypeID				VARCHAR(100)	,	
	DTypeID				VARCHAR(100)	,	
	ETypeID				VARCHAR(100)	,	
	InKTypeId			VARCHAR(100)	,	
	OutKTypeId			VARCHAR(100)	,	
	CID					INT				,	
	Rate				NUMERIC(24,10)	,	
	TotalQty			NUMERIC(24,10)	,	--合计数量
	TotalMoney			NUMERIC(24,10)	,	--合计金额
	CompleteTotal		NUMERIC(24,10)	,	
	TotalInMoney		NUMERIC(24,10)	,	--收付款金额
	NTotalInMoney		NUMERIC(24,10)	,	
	IfMulAccount		BIT				,	
	ATypeID				VARCHAR(100)	,	
	BTypeID				VARCHAR(100)	,	
	DealBTypeID			VARCHAR(100)	,	
	Comment				VARCHAR(500)	,	
	Poster				VARCHAR(100)	,	
	PostTime			DATETIME		,
	postname			VARCHAR(200)	,
	Checke				VARCHAR(100)	,	
	CheckeTime			DATETIME		,	
	IfAudit				CHAR(1)			,	
	Draft				INT				,	
	IfCheck				CHAR(1)			,	
	RedWord				INT				,	
	IsIni				INT				,	
	IfYearBill			INT				,	
	ATypeID1			VARCHAR(50)		,
	BillState			VARCHAR(50)		,
	redreason			VARCHAR(500)	,
	posid               INT,
	nfromtype           INT ,
    sid numeric(10,0)  IDENTITY (1, 1) NOT NULL
)




SELECT @SQL_LIST = 'SELECT 
					distinct
					bi.BillNumberID	
					,bi.BillDate		
					,bi.BillCode		
					,bi.BillType
					,bm.billname as billtypename
					,wl.usercode as dealusercode
					,wl.fullname as dealfullname
					,js.usercode as btypeusercode
					,js.fullname as btypefullname
					,dp.fullname as dfullname
					,el.fullname as etypename
					,zd.fullname as checkename
					,st.fullname as stypename
					,case 	
					when Bi.FromType = 1 AND Bi.BILLTYPE = 423 THEN ''自制''
					when BI.FROMTYPE = 2 AND Bi.BILLTYPE = 423 THEN ''外购''
					when BI.FROMTYPE = 3 AND Bi.BILLTYPE = 423 THEN ''报溢''
					when BI.FROMTYPE = 2 AND Bi.BILLTYPE = 424 THEN ''对外''
					when BI.FROMTYPE = 1 AND Bi.BILLTYPE = 424 THEN ''对内''
					when BI.FROMTYPE = 3 AND Bi.BILLTYPE = 424 THEN ''报损''
					else ''其他'' end 
					,bi.STypeID			
					,bi.DTypeID			
					,bi.ETypeID			
					,bi.InKTypeId			
					,bi.OutKTypeId		
					,bi.CID				
					,bi.Rate			
					,case bi.redword when 2 then -1 * bi.TotalQty
					else bi.TotalQty end as TotalQty		
					,case bi.redword when 2 then -1 * bi.TotalMoney		
					else bi.TotalMoney end as TotalMoney	
					,bi.CompleteTotal	
					,CASE bi.redword 
						when 2 then -1*bi.TotalInMoney	
						else bi.TotalInMoney
					 END AS TotalInMoney
					,CASE bi.redword 
						when 2 then -1*bi.NTotalInMoney	
						else bi.NTotalInMoney
					 END AS NTotalInMoney
					,bi.IfMulAccount	
					,bi.ATypeID			
					,bi.BTypeID			
					,bi.DealBTypeID		
					,bi.Comment					
					,bi.Poster
					,bi.PostTime
					,e2.fullname as postname				
					,bi.Checker			
					,bi.CheckeTime		
					,bi.IfAudit			
					,bi.Draft			
					,bi.IfCheck			
					,bi.RedWord			
					,bi.IsIni			
					,bi.IfYearBill			
					,bi.ATypeID1
					,case when bi.ifcheck = ''t'' then ''过账单据'' else ''草稿单据'' end as billstate
					,bi.redreason
					,posid
					,bi.fromtype '
					
            
-- 基本列表的SQL
SELECT @SQL_FROM='	FROM coupon_BillIndex bi 
                    INNER JOIN BillName bm on bm.billtype=bi.BillType
                    LEFT JOIN Department dp on dp.typeid=bi.DTypeID
                    INNER JOIN employee el on el.typeid=bi.ETypeID
                    LEFT JOIN employee E2 ON bi.Poster=e2.typeid  
                    INNER JOIN employee zd on zd.typeid=bi.Maker
                    INNER JOIN stype st on st.typeid=bi.stypeid
                    '



	SET @SQL_FROM = @SQL_FROM+' INNER JOIN #Etype e ON Bi.etypeid=e.typeid '
    SET @SQL_FROM = @SQL_FROM+ ' INNER JOIN #Stype S ON bi.stypeID =S.typeid ' 
    SET @SQL_FROM = @SQL_FROM+ ' INNER JOIN #Ktype k ON bi.InKTypeId =k.typeid or bi.OutKTypeId = k.typeid'   
    
	IF @dealBTypeId =''--结算单位
		 SET @SQL_FROM = @SQL_FROM+ '   LEFT JOIN #Btype js on js.typeid=bi.BTypeID ' 
	ELSE
		 SET @SQL_FROM = @SQL_FROM+ '   INNER JOIN #Btype js on js.typeid=bi.BTypeID ' 

	IF @deal_btypeid=''--往来单位
		 SET @SQL_FROM = @SQL_FROM+ '   LEFT JOIN #deal_btype wl on wl.typeid=bi.DealBTypeID ' 
	ELSE
		 SET @SQL_FROM = @SQL_FROM+ '   INNER JOIN #deal_btype wl on wl.typeid=bi.DealBTypeID ' 


DECLARE @PageNum int
DECLARE @PageBegin int
DECLARE @PageEnd int
DECLARE @RowCount int

SET @PageNum =@PageNo *@UserDeRowCount
SET @PageBegin=(@PageNo-1)*@UserDeRowCount+1
SET @PageEnd=(@PageNo)*@UserDeRowCount

--处理排序
DECLARE @orderyWhere VARCHAR(1000)   =''
IF  CHARINDEX('stype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN Stype or_st ON bi.stypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'stype_','or_st.') 
END
IF  CHARINDEX('dtypeid1',@OrderBy)>0
BEGIN
	SET @orderyWhere='	LEFT JOIN Department or_de ON bi.dtypeid1=or_de.typeID '
	SET @OrderBy= REPLACE(@OrderBy,'dtypeid1_','or_de.') 
END
IF  CHARINDEX('etype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN employee or_em ON bi.etypeid=or_em.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'etype_','or_em.') 
END
IF  CHARINDEX('btype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN btype or_bt ON bi.btypeid=or_bt.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'btype_','or_bt.') 
END
IF  CHARINDEX('dealbtypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN btype or_bt1 ON bi.dealbtypeid=or_bt1.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'dealbtypeid_','or_bt1.') 
END
IF  CHARINDEX('atype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN ac_items or_at ON bi.atypeid= or_at.nTypeid '
	SET @OrderBy= REPLACE(@OrderBy,'atype_','or_at.') 
END
IF  CHARINDEX('ktypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON bi.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid_','or_st.') 
END	
IF  CHARINDEX('ktypeid1',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON bi.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid1_','or_st.') 
END	
IF  CHARINDEX('ktypeid2',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON bi.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid2_','or_st.') 
END	



IF @OrderBy<>''
BEGIN
	SET @OrderBy=' ORDER BY ' +@OrderBy
END
ELSE
BEGIN
	SET @OrderBy=' ORDER BY bi.billdate desc,BI.billcode desc'
END

SET @SQL ='	INSERT INTO #temp1
			(
				BillNumberID	
				,BillDate		
				,BillCode		
				,BillType		
				,billtypename    
				,dealusercode    
				,dealfullname    
				,btypeusercode   
				,btypefullname   
				,dfullname       
				,etypename	 
				,checkename  
				,stypename 
				,FromType			
				,STypeID			
				,DTypeID			
				,ETypeID			
				,InKTypeId			
				,OutKTypeId		
				,CID				
				,Rate			
				,TotalQty		
				,TotalMoney			
				,CompleteTotal	
				,TotalInMoney	
				,NTotalInMoney	
				,IfMulAccount	
				,ATypeID			
				,BTypeID			
				,DealBTypeID		
				,Comment					
				,Poster			
				,PostTime
				,postname					
				,Checke			
				,CheckeTime		
				,IfAudit			
				,Draft			
				,IfCheck			
				,RedWord			
				,IsIni			
				,IfYearBill		
				,ATypeID1
				,BillState
				,redreason
				,posid
				,nfromtype
			)   '+@SQL_LIST+@SQL_FROM+@orderyWhere+@SQL_WHERE+@OrderBy 
			


--print @SQL
EXEC(@SQL)
SET @RowCount = @@ROWCOUNT


SET @SQL = 'select a.*,'+Convert(varchar(100),@RowCount)+' as TotalNum   FROM 	#temp1 a  
WHERE 	A.sid>='+convert(varchar(10),@PageBegin) +'  AND A.sid<='+convert(varchar(10),@PageEnd)+'
ORDER BY A.sid'

EXEC (@SQL)

SELECT @SQL_SUM =  'SELECT ISNULL(SUM(ISNULL(totalqty,0)),0) AS totalqty,ISNULL(SUM(ISNULL(totalmoney,0)),0) AS totalmoney,ISNULL(SUM(ISNULL(TotalInMoney,0)),0) AS TotalInMoney  
FROM 	#temp1 a  
WHERE 	A.sid>='+convert(varchar(10),@PageBegin) +'  AND A.sid<='+convert(varchar(10),@PageEnd)
--+'ORDER BY A.sid'
--PRINT @SQL_SUM
EXEC (@SQL_SUM)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_QueryCouponCustomReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_QueryCouponCustomReport]
GO

/*
	作者：李德强
	日期：2017-12-06
	描述：优惠券消费报表查询
*/

CREATE PROCEDURE [Gp_QueryCouponCustomReport](
		@OperatorID NVARCHAR(20),		
		@StartDate NVARCHAR(20) ,			--查询开始时间
		@EndDate NVARCHAR(20) ,				--查询结束时间
		@CustonDepart NVARCHAR(2000) = '' ,	--消费机构
		@CustonStock NVARCHAR(2000)  = '',	--消费仓库
		@couponTypedjq TINYINT = 0,			--券类型：代金券
		@couponTypezkq TINYINT = 0,			--券类型：折扣券
		@couponTypedhq TINYINT = 0,			--券类型：兑换券
		@CouponID NVARCHAR(2000) = 0,		--券名称ID
		@CouponCode NVARCHAR(200) = '',		--券编码
		@BillTypes NVARCHAR(100) = '',		--单据类型
		@BalanceUnit NVARCHAR(200) = '',	--结算单位
		@BusinessUnit NVARCHAR(200) = ''	--往来单位
)
AS
BEGIN

	CREATE TABLE #Stock (TypeId VARCHAR(100)) --消费仓库
	CREATE TABLE #SType(TypeId	varchar(100)) --消费机构
	CREATE TABLE #Balance(TypeId	varchar(100)) --结算单位  
	CREATE TABLE #DealB(TypeId	varchar(100)) --往来单位
	
	INSERT INTO #Stype( TypeID ) SELECT TypeId FROM dbo.F_GetAllManagerBaseTypeId(@CustonDepart,11,@OperatorID) 
	INSERT INTO #Stock( TypeID ) SELECT TypeId FROM dbo.F_GetAllManagerBaseTypeId(@CustonStock,4,@OperatorID) 
	INSERT INTO #Balance( TypeID ) SELECT TypeId FROM dbo.F_GetAllManagerBaseTypeId(@BalanceUnit,2,@OperatorID) 
	INSERT INTO #DealB( TypeID ) SELECT TypeId FROM dbo.F_GetAllManagerBaseTypeId(@BusinessUnit,2,@OperatorID) 
	  
	DECLARE @SQL NVARCHAR(MAX)
 
	SET @SQL = 
	'SELECT
		TI.fullName AS fullname,
		TI.usercode,
		CASE TI.couponType 
			WHEN 1 THEN ''代金券''
			WHEN 2 THEN ''折扣券''
			WHEN 3 THEN ''兑换券'' END AS couponType,
		CCIO.couponCode,
		dbo.SType.FullName AS sendUnitFullname, --发券机构
		dbo.Department.FullName AS sendDepFullname,	--发券部门
		dbo.employee.FullName AS employeeFullname, --发券人员
		CASE TI.couponType 
			WHEN 1 THEN TI.couponValue
			ELSE NULL END AS couponValue,
		cusT.FullName AS customSFullname,
		CBI.STypeId AS customSID,
		ST.FullName AS customStockFullname,
		CBI.ktypeid AS customStockID,
		BT.FullName AS balanceUnitFullname, --结算单位
		CBI.btypeid AS balanceUnitID,
		BT2.FullName AS dealBFullname, --往来单位
		CBI.DealBTypeID AS dealBTypeID,
		CBI.billType,
		CASE CBI.billType
			WHEN 305 THEN ''零售单''
			WHEN 215 THEN ''零售退货单''
			WHEN 11 THEN ''销售出库单''
			WHEN 45 THEN ''销售退货单''
			WHEN 12 THEN ''组合品销售出库单''
			WHEN 46 THEN ''组合品销售退货单'' END AS billTypeName,
		CBI.billCode,
		ABS(CBI.NTotalMoney) AS nTaxTotal,
		CASE 
			WHEN TI.couponType = 1 THEN (SELECT TOP 1 BA.Total FROM dbo.BillMulAccount BA
											INNER JOIN dbo.Ac_Items AI ON  BA.ATypeID = AI.nId
											WHERE BA.yhType = 1 AND AI.UserCode = 2191 AND BA.BillNumberId = CBI.BillNumberId)
		ELSE NULL END AS couponPayValue,
		CBI.BillNumberId,
		CBI.posttime,
		CBI.RedWord
	FROM dbo.Coupon_BillUsed usedBill 
	INNER JOIN dbo.BillIndex CBI ON usedBill.BillnumberId = CBI.BillNumberId AND CBI.BillType IN (305,215,11,45,12,46) AND ( CBI.ifcheck = ''t'' OR CBI.IsIni = 1 ) 
	INNER JOIN ( SELECT DISTINCT CouponCode,CouponId FROM dbo.Coupon_CodeInfo ) CCIO ON CCIO.CouponCode = usedBill.CouponCode
	INNER JOIN dbo.Coupon_TypeInfo TI ON TI.CouponId = CCIO.CouponId
	INNER JOIN dbo.SType ON dbo.SType.TypeId = CBI.STypeId
	INNER JOIN dbo.Department ON dbo.Department.typeid = CBI.DTypeId
	INNER JOIN dbo.employee ON dbo.employee.typeId = CBI.ETypeId 
	INNER JOIN dbo.Stype cusT ON cusT.typeid = CBI.STypeID
	INNER JOIN dbo.Stock ST ON ST.typeId = CBI.KtypeId
	INNER JOIN dbo.btype BT ON BT.typeId = CBI.BtypeId
	INNER JOIN dbo.btype BT2 ON BT2.typeId = CBI.DealBTypeID
	INNER JOIN #Stock ON CBI.ktypeid = #Stock.TypeID
	INNER JOIN #SType ON CBI.STypeId = #SType.TypeID
	INNER JOIN #Balance ON CBI.BtypeId = #Balance.TypeID
	INNER JOIN #DealB ON CBI.DealBTypeID = #DealB.TypeID
	WHERE CBI.RedWord = 0 AND '
	
	--查询日期
	SET @SQL = @SQL + ' ( (CBI.IsIni = 0 AND CBI.posttime BETWEEN ''' + @StartDate + ''' AND DATEADD(DAY,1,''' + @EndDate+ ''') ) 
						OR 
						(CBI.IsIni = 1 AND CBI.checkTime BETWEEN ''' + @StartDate + ''' AND DATEADD(DAY,1,''' + @EndDate+ ''') ) ) ' 
	
	IF @CouponID <> ''
	BEGIN
		SET @SQL = @SQL + ' AND TI.CouponId IN (SELECT * FROM dbo.f_split(''' + @CouponID + ''','',''))' 
	END
	
	IF @CouponCode <> ''
	BEGIN
		SET @SQL = @SQL + ' AND CCIO.CouponCode LIKE ''%' + @CouponCode + '%'''
	END
	
	SET @SQL = @SQL + ' AND TI.couponType IN (9 ' 
	IF @couponTypedjq = 1 OR @couponTypezkq = 1 OR @couponTypedhq = 1
	BEGIN 
		
		IF @couponTypedjq = 1
		BEGIN
			SET @SQL = @SQL + ' ,1 '
		END 
		IF @couponTypezkq = 1
		BEGIN
			SET @SQL = @SQL + ' ,2 '
		END 
		IF @couponTypedhq = 1
		BEGIN
			SET @SQL = @SQL + ' ,3 '
		END 
	END
	SET @SQL = @SQL + ') '
	
	IF @BillTypes <> ''
	BEGIN
		SET @SQL = @SQL + ' AND CBI.BillType IN (SELECT * FROM dbo.f_split(''' + @BillTypes + ''','','')) '
	END
	
	--默认按过账时间排序
	SET @SQL = @SQL + ' ORDER BY  CBI.posttime'
	 
	EXEC (@SQL)
	
	DROP TABLE #Stock
	DROP TABLE #SType
	DROP TABLE #Balance
	DROP TABLE #DealB
	
END
 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



 




 



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = OBJECT_ID(N'[dbo].[Gp_QueryCouponStatisticReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE Gp_QueryCouponStatisticReport
GO

/*
	作者： 李德强
	日期： 2017-12-05
	描述： 优惠券统计报表
*/

CREATE PROCEDURE  Gp_QueryCouponStatisticReport
( 
	@operatorid		nvarchar(100),  				-- 操作员 
	@couponid	    nVARCHAR(MAX)='',				-- 券编码，以逗号隔开
	@stypeid		nvarchar(100),  				-- 操作员
	@coupondjq		VARCHAR(10),					--券类型	代金券
	@couponzkq		VARCHAR(10),					--券类型	折扣券
	@coupondhq		VARCHAR(10)						--券类型	兑换券
)

AS 
BEGIN

	--消费机构
	CREATE TABLE #SType(TypeId	varchar(100))
	--券名称
	CREATE TABLE #Coupon(CouponID	varchar(100))
	--券类型
	CREATE TABLE #CouponType (TypeID INT )
	
	INSERT INTO #Stype( TypeID ) SELECT TypeId FROM dbo.F_GetAllManagerBaseTypeId(@stypeid,11,@operatorid) 
	
	IF @CouponID = ''
		BEGIN
			INSERT INTO #Coupon ( CouponID ) SELECT DISTINCT CouponId FROM dbo.Coupon_TypeInfo
		END
	ELSE
		BEGIN
			INSERT INTO #Coupon ( CouponID ) SELECT * FROM dbo.f_split(@CouponID,',')
		END 
	
	IF @Coupondjq = '1' OR @Couponzkq = '1' OR @Coupondhq = '1'
		BEGIN
			IF @coupondjq = '1'
				INSERT INTO #CouponType ( TypeID ) VALUES  ( 1 )
			IF @couponzkq = '1'
				INSERT INTO #CouponType ( TypeID ) VALUES  ( 2 )
			IF @coupondhq = '1'
				INSERT INTO #CouponType ( TypeID ) VALUES  ( 3 )
		END	
	ELSE
		BEGIN
			INSERT INTO #CouponType ( TypeID ) VALUES  ( 9 )
		END 
	
	CREATE TABLE #OverDueData(CouponId NVARCHAR(200),OverDueSum INT)
	--查找过期的优惠券
	INSERT INTO #OverDueData( CouponId, OverDueSum )
	
	SELECT CouponId,COUNT(CouponCode) AS OverDueSum FROM 
	(
		SELECT CCI.CouponId,CouponCode,KTYPE.STypeID,CTI.CouponType  
		FROM dbo.Coupon_CodeInfo CCI
			INNER JOIN dbo.Stock KTYPE ON CCI.KtypeId = KTYPE.typeId
			INNER JOIN dbo.Coupon_TypeInfo CTI ON CTI.CouponId = CCI.CouponId
			INNER JOIN #SType ON #SType.TypeId = KTYPE.STypeId				--分支机构
			INNER JOIN #Coupon ON #Coupon.CouponID = CCI.CouponId			--券名称
			INNER JOIN #CouponType ON #CouponType.TypeID = CTI.CouponType	--券类型
		WHERE CCI.InvalidDate IS NOT NULL AND CCI.InvalidDate < convert(char(10),GETDATE(),120) 
	) overdue GROUP BY CouponId

	SELECT 
		BasData.CouponId,
		INFO.FullName,
		CASE INFO.CouponType WHEN 1 THEN '代金券' WHEN 2 THEN '折扣券' WHEN 3 THEN '兑换券' END AS CouponTypeName,
		BasData.zkCount,
		BasData.ckCount,
		BasData.xfCount,
		ISNULL(OverDueSum,0) AS gqCount ,
		BasData.hcCount,
		BasData.thCount,
		BasData.stypeckcount
	FROM (
		SELECT  CCI.CouponId,			
			SUM(case WHEN [STATE] IN (1,8) THEN 1 ELSE 0 END ) AS zkCount,
			SUM(case WHEN [STATE] IN (2,6) THEN 1 ELSE 0 END ) AS ckCount,
			SUM(case WHEN [STATE] IN (3) THEN 1 ELSE 0 END ) AS xfCount,
			SUM(case WHEN [STATE] IN (4) THEN 1 ELSE 0 END ) AS hcCount,
			SUM(case WHEN [STATE] IN (5) THEN 1 ELSE 0 END ) AS thCount,
			SUM(case when [state] in(7) then 1 else 0 end ) as stypeckcount
		FROM dbo.Coupon_CodeInfo CCI
			INNER JOIN dbo.Stock K ON CCI.KtypeId = K.typeId
			INNER JOIN dbo.Coupon_TypeInfo CTI ON CTI.CouponId = CCI.CouponId
			INNER JOIN #SType ON #SType.TypeId = K.STypeId				--分支机构
			INNER JOIN #Coupon ON #Coupon.CouponID = CCI.CouponId			--券名称
			INNER JOIN #CouponType ON #CouponType.TypeID = CTI.CouponType	--券类型  
			GROUP BY CCI.CouponId
	) BasData 
	INNER JOIN dbo.Coupon_TypeInfo INFO ON INFO.CouponId = BasData.CouponId
	LEFT JOIN #OverDueData ON BasData.CouponId = #OverDueData.CouponId
	
	DROP TABLE #SType
	DROP TABLE #CouponType
	DROP TABLE #Coupon
	DROP TABLE #OverDueData
END
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryCouponTraceReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryCouponTraceReport]
GO



/*
	作者：颜熙
	日期：2017-11-30
	描述：优惠券跟踪报表查询
*/

CREATE PROCEDURE Gp_QueryCouponTraceReport
( 
	@OperatorID		varchar(100) 	,  			-- 操作员
	@BeginDate	 	varchar(200)  	='', 		-- 开始时间
	@EndDate	 	varchar(200)  	='',   		-- 结束时间
	@couponstate	VARCHAR(100)='',			--事件
	@couponusercode	VARCHAR(500)='',            --券面码
	@couponname	    VARCHAR(MAX)=''             --券名称，以逗号隔开
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON
BEGIN
	CREATE TABLE #Etype (TypeID VARCHAR(50),UserCode VARCHAR(50),FullName VARCHAR(500))
	CREATE TABLE #Stype (TypeID VARCHAR(50),UserCode VARCHAR(50),FullName VARCHAR(500))
	CREATE TABLE #Dtype (TypeID VARCHAR(50),UserCode VARCHAR(50),FullName VARCHAR(500))
	CREATE TABLE #State (Value VARCHAR(500))
	CREATE TABLE #State2 (Value VARCHAR(500))
	
	INSERT INTO #Etype(TypeID,UserCode,FullName) SELECT E.typeId,E.UserCode,E.FullName from F_GetManDetailEType(@OperatorID) INNER JOIN dbo.employee E ON E.typeId = F_GetManDetailEType.TypeId
	INSERT INTO #Stype(TypeID,UserCode,FullName) SELECT S.TypeId,S.UserCode,S.FullName FROM dbo.F_BaseGetManDetailSType(@OperatorID) F INNER JOIN dbo.SType S ON S.TypeId = F.TypeId
	INSERT INTO #Dtype(TypeID,UserCode,FullName) SELECT D.TypeID,D.usercode,D.FullName FROM dbo.F_BaseGetManDetailDType(@OperatorID) F INNER JOIN dbo.Department D ON D.typeid = F.TypeId
	
	IF(CHARINDEX('5',@couponstate)>0)
	INSERT INTO #State
	        ( Value )
	SELECT '消费退货'
	
	IF(CHARINDEX('4',@couponstate)>0)
	INSERT INTO #State
	        ( Value )
	SELECT '消费红冲'
	
	IF(CHARINDEX('3',@couponstate)>0)
	INSERT INTO #State
	        ( Value )
	SELECT '消费'
	
	IF(CHARINDEX('6',@couponstate)<=0)
	INSERT INTO #State2
	        ( Value )
	SELECT '退库'

	SELECT DISTINCT * FROM (
	SELECT * FROM 
	(
		SELECT  BI.MakeTime AS operationdate,--制单时间
				CASE WHEN cio.State = 1 AND bi.FromType = 1 THEN '（入库）自制'
				WHEN cio.State = 1 AND bi.FromType = 2 THEN '（入库）外购'
				WHEN cio.State = 1 AND bi.FromType = 3  THEN '（入库）报溢'
				WHEN cio.State = 1 AND bi.BillType = 428 THEN '（入库）分支机构调拨入库'
				WHEN cio.State = 2 AND bi.FromType = 1 THEN '（出库）对内'
				WHEN cio.State = 2 AND bi.FromType = 2 THEN '（出库）对外'
				WHEN cio.State = 2 AND bi.FromType = 3 THEN '（出库）报损'
				WHEN cio.State = 3 THEN '消费'
				WHEN cio.State = 4 THEN '消费红冲'
				WHEN cio.state = 5 THEN '消费退货'
				WHEN cio.State = 1 AND bi.BillType = 426 THEN '退库'
				WHEN cio.State = 7 AND bi.BillType = 429 THEN '（出库）分支机构调拨出库'
				WHEN bi.BillType = 425 THEN '调拨'
				END AS billstate,S.FullName AS stypename,D.FullName AS dtypename,E.FullName AS etypename,
				cio.CouponCode,BI.BillNumberId,BI.BillType,BI.RedWord
		FROM	dbo.Coupon_CodeInOut cio 
		INNER JOIN dbo.Coupon_BillIndex BI ON BI.BillNumberId = cio.BillNumberId
		INNER JOIN dbo.coupon_CodeInfo I ON I.CouponCode = cio.CouponCode
		INNER JOIN dbo.Coupon_TypeInfo T ON T.CouponId = I.CouponId 
		INNER JOIN #Stype S ON s.TypeID = BI.STypeId
		INNER JOIN #Etype E ON E.TypeID = Bi.ETypeId
		INNER JOIN #Dtype D ON BI.DTypeId = D.TypeID	
		WHERE cio.CouponCode LIKE @couponusercode AND (cio.State IN (SELECT a FROM dbo.f_split(@couponstate,',')) OR (CHARINDEX('6',@couponstate)>0 AND cio.State = 1 AND BI.BillType = 426))
		AND cio.BillDate >= @BeginDate AND cio.BillDate <= @EndDate AND bi.Draft = 0 AND (@couponname = '' OR T.FullName IN (SELECT a FROM dbo.f_split(@couponname,';')))
	) c WHERE c.billstate NOT IN (SELECT Value FROM #State2)
	UNION ALL
	--消费
	SELECT * FROM 
	(
		SELECT  BI.checkTime AS operationdate,
				CASE WHEN BI.RedWord IN (0) AND B.BillType IN (11,12,305) THEN '消费'
				WHEN BI.RedWord IN (0) AND B.BillType NOT IN (11,12,305) THEN '消费退货'
				WHEN BI.RedWord IN(1, 2 )AND B.BillType IN (11,12,305) THEN '消费红冲'
				WHEN BI.RedWord IN(1, 2 )AND B.BillType NOT IN (11,12,305) THEN '消费退货红冲'
				END AS billstate,S.FullName AS stypename,D.FullName AS dtypename,E.FullName AS etypename,
				B.CouponCode,BI.BillNumberId,BI.BillType,BI.RedWord
		FROM dbo.Coupon_BillUsed B
		INNER JOIN dbo.Coupon_CodeInfo I ON I.CouponCode = B.CouponCode
		INNER JOIN dbo.Coupon_TypeInfo T ON T.CouponId = I.CouponId 
		INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = B.BillnumberId
		INNER JOIN #Stype S ON s.TypeID = BI.STypeId
		INNER JOIN #Etype E ON E.TypeID = BI.ETypeId
		INNER JOIN #Dtype D ON D.TypeId = BI.DTypeID
		WHERE B.CouponCode LIKE @couponusercode --AND 3 IN (SELECT a FROM dbo.f_split(@couponstate,','))
		AND BI.BillDate >= @BeginDate AND BI.BillDate <= @EndDate AND bi.draft = 0 AND (@couponname = '' OR T.FullName IN (SELECT a FROM dbo.f_split(@couponname,';')))
		) A WHERE A.billstate IN (SELECT Value FROM #State)
	) T ORDER BY CouponCode,T.operationdate
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryDayOrMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryDayOrMonth]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryDayOrMonth    Script Date: 2002-6-20 10:14:50 ******/

--date:2001-08-29
CREATE  PROCEDURE Gp_QueryDayOrMonth 
( 
 @ktypeid varchar(26)='',
 @BeginDate  varchar(20),
 @EndDate  varchar(20),
 @Day   varchar(20),
 @Parid  varchar(25),
 @BillType  numeric(4,0),
 @BillType1  numeric(4,0)
)
--@encode$--
AS
SET NOCOUNT ON
declare @cz_Query varchar(600),@Sql varchar(2000),@cz_where varchar(50),@cz_Dx varchar(50)
declare @p_id varchar(25),@a_id Varchar(25)
select @p_id = '0'
if @Parid='' select @Parid='00000'
select @a_id = '0000100001'
select @cz_query=''
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=' and (b.billdate>='+char(39)+@begindate+char(39)+' and b.billdate<='+char(39)+@enddate+char(39)+') '
if rtrim(@Day) <> ''
 select @cz_Query=' and b.BillDate='+char(39)+@Day+char(39)
if rtrim(@ktypeid)<> ''
 select @cz_query=@cz_query+' and b.Ktypeid='+char(39)+@ktypeid+Char(39)
if @billtype=11 
 select @cz_Dx=' or b.billtype=203'
else 
 select @cz_dx=''
if (@billTYpe=34 or @billTYpe=6) or (@billTYpe1=34 or @billTYpe1=6)  --进货
select @sql='SELECT a.typeId, a.Parid, a.leveal,a.sonnum, a.FullName, a.UserCode,cast(t.qty as  NUMERIC(24, 10) ) as qty,cast(t.total as  NUMERIC(24, 10) ) as total,cast(t.taxtotal as  NUMERIC(24, 10) ) as taxtotal
             from ptype a 
             inner join
             (select left(b.ptypeid,len(a.typeid)) as typeid, sum(b.qty) as qty,sum(b.total) as total,sum(b.total*(1+c.tax/100)) as taxtotal    from  inoutstocktable b  inner join billindex c on(b.billnumberid=c.billnumberid)   inner join ptype a on(left(b.ptypeid,len(a.typeid))=a.typeid) where (b.billtype = '+cast(@billtype as varChar(10))+' or b.billtype = '+cast(@billtype1 as varchar(10))+@cz_Dx++')  '+@cz_Query+' and b.atypeid='''+@a_id+''' and a.deleted=0 and a.parid='''+@parid+''' group by left(b.ptypeid,len(a.typeid))) t
            on (a.typeid=t.typeid) where a.deleted=0 order by a.usercode'
else --销售
if (@billTYpe=11 or @billTYpe=45) or (@billTYpe1=11 or @billTYpe1=45)  --进货
select @sql='SELECT a.typeId, a.Parid, a.leveal,a.sonnum, a.FullName, a.UserCode,cast(-1 *t.qty as  NUMERIC(24, 10) ) as qty,cast(-1 * t.total as  NUMERIC(24, 10) ) as total,cast(-1 * t.taxtotal as  NUMERIC(24, 10) ) as taxtotal
             from ptype a 
             inner join
             (select left(b.ptypeid,len(a.typeid)) as typeid, sum(b.qty) as qty,sum(b.total) as total,sum(b.total*(1+c.tax/100)) as taxtotal    from  inoutstocktable b  inner join billindex c on(b.billnumberid=c.billnumberid)   inner join ptype a on(left(b.ptypeid,len(a.typeid))=a.typeid) where (b.billtype = '+cast(@billtype as varChar(10))+' or b.billtype = '+cast(@billtype1 as varchar(10))+@cz_Dx++')  '+@cz_Query+' and b.atypeid='''+@a_id+''' and a.deleted=0 and a.parid='''+@parid+''' group by left(b.ptypeid,len(a.typeid))) t
            on (a.typeid=t.typeid) where a.deleted=0 order by a.usercode'
exec(@sql)
--print(@sql)
/*
--print @cz_query
--select @cz_query=substring(@cz_query,1,len(@cz_query)-4)
select @Sql='SELECT typeId, Parid, leveal,sonnum, FullName, UserCode,
          (SELECT isnull(abs(SUM(b.qty)), 0)
         FROM inoutstocktable b 
         WHERE (b.billtype = '+cast(@billtype as Char)+' or b.billtype = '+cast(@billtype1 as char)+@cz_Dx+
  ') AND LEFT(b.ptypeid, len(a.typeid)) 
               = a.typeid  AND b.ptypeid <>'+char(39)+@p_id+char(39)+' and b.atypeid='+char(39)+@a_id+char(39)+
  @cz_query+') AS Qty,
          (SELECT isnull(abs(SUM(b.total)), 0)
         FROM inoutstocktable b
         WHERE (b.billtype = '+cast(@billtype as char)+' or b.billtype = '+cast(@billtype1 as char)+@cz_Dx+
  ') AND LEFT(b.ptypeid, len(a.typeid)) 
               = a.typeid AND b.ptypeid <>'+char(39)+@p_id+char(39)+' and b.atypeid='+char(39)+@a_id+char(39)+
   @cz_query+') AS total
FROM ptype a
WHERE Parid ='+ char(39)+@parid+char(39)+' and deleted=0' 
--print @sql
declare @cz_Query varchar(600),@Sql varchar(2000),@cz_where varchar(50),@cz_Dx varchar(50)
declare @p_id varchar(25),@a_id Varchar(25)
select @p_id = '0'
select @a_id = '0000100001'
select @cz_query=''
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=' and (b.billdate>='+char(39)+@begindate+char(39)+' and b.billdate<='+char(39)+@enddate+char(39)+') '
if rtrim(@Day) <> ''
 select @cz_Query=' and b.BillDate='+char(39)+@Day+char(39)
if rtrim(@ktypeid)<> ''
 select @cz_query=@cz_query+' and b.Ktypeid='+char(39)+@ktypeid+Char(39)
if @billtype=11 
 select @cz_Dx=' or b.billtype=203'
else 
 select @cz_dx=''
--print @cz_query
--select @cz_query=substring(@cz_query,1,len(@cz_query)-4)
select @Sql='SELECT typeId, Parid, leveal,sonnum, FullName, UserCode,
          (SELECT isnull(abs(SUM(b.qty)), 0)
         FROM inoutstocktable b 
         WHERE (b.billtype = '+cast(@billtype as Char)+' or b.billtype = '+cast(@billtype1 as char)+@cz_Dx+
  ') AND LEFT(b.ptypeid, len(a.typeid)) 
               = a.typeid  AND b.ptypeid <>'+char(39)+@p_id+char(39)+' and b.atypeid='+char(39)+@a_id+char(39)+
  @cz_query+') AS Qty,
          (SELECT isnull(abs(SUM(b.total)), 0)
         FROM inoutstocktable b
         WHERE (b.billtype = '+cast(@billtype as char)+' or b.billtype = '+cast(@billtype1 as char)+@cz_Dx+
  ') AND LEFT(b.ptypeid, len(a.typeid)) 
               = a.typeid AND b.ptypeid <>'+char(39)+@p_id+char(39)+' and b.atypeid='+char(39)+@a_id+char(39)+
   @cz_query+') AS total
FROM ptype a
WHERE Parid ='+ char(39)+@parid+char(39)+' and deleted=0' 
--print @sql
exec(@sql)
                (SELECT isnull(avg(b.price), 0)
         FROM inoutstocktable b
         WHERE (b.billtype = '+cast(@billtype as char)+' or b.billtype = '+cast(@billtype1 as char)+
  ') AND LEFT(b.ptypeid, len(a.typeid)) 
               = a.typeid AND b.ptypeid <>'+char(39)+@p_id+char(39)+' and b.atypeid='+char(39)+@a_id+char(39)+
   @cz_query+') AS price
*/















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryDayOrMonthEX]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryDayOrMonthEX]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryDayOrMonthEX    Script Date: 2002-6-20 10:14:50 ******/


--王浩2001－09－11改动,因为加管辖单位问题，加参数Btypeid
--王浩2001－10－11改动,因为加管辖单位问题，加参数Ptypeid,Eypeid,Kypeid
--date:2001-08-29
-----2002-4-8王跃加零售单

CREATE  PROCEDURE Gp_QueryDayOrMonthEX
( 
 @ktypeid varchar(26)='',
 @BeginDate  varchar(20),
 @EndDate  varchar(20),
 @Day   varchar(20),
 @Parid  varchar(25),
 @BillType  numeric(4,0),
 @BillType1  numeric(4,0),
 @BTypeid  varchar(40)='',
 @PTypeid  varchar(40)='',
 @ETypeid  varchar(40)=''
)
--@encode$--
AS
SET NOCOUNT ON 
declare @cz_Query varchar(600),@Sql varchar(2000),@cz_where varchar(50),@cz_Dx varchar(50)
declare @p_id varchar(25),@a_id Varchar(25)
select @p_id = '0'
if @Parid='' select @Parid='00000'
select @a_id = '0000100001'
select @cz_query=''
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=' and (b.billdate>='+char(39)+@begindate+char(39)+' and b.billdate<='+char(39)+@enddate+char(39)+') '
if rtrim(@Day) <> ''
 select @cz_Query=' and b.BillDate='+char(39)+@Day+char(39)
if rtrim(@ktypeid)<> ''
 select @cz_query=@cz_query+' and b.Ktypeid='+char(39)+@ktypeid+Char(39)
if @billtype=11 
 select @cz_Dx=' or b.billtype=203 or b.billtype=305 '
else 
 select @cz_dx=''


if (@billTYpe=34 or @billTYpe=6) or (@billTYpe1=34 or @billTYpe1=6)  --进货
select @sql='SELECT a.typeId, a.Parid, a.leveal,a.sonnum, a.FullName, a.UserCode,cast(t.qty as  NUMERIC(24, 10) ) as qty,cast(t.total as  NUMERIC(24, 10) ) as total,cast(t.taxtotal as  NUMERIC(24, 10) ) as taxtotal
             from ptype a 
             inner join
             (select left(b.ptypeid,len(a.typeid)) as typeid, sum(b.qty) as qty,sum(b.total) as total,sum(b.total*(1+c.tax/100)) as taxtotal    from  inoutstocktable b  inner join billindex c on(b.billnumberid=c.billnumberid)   inner join ptype a on(left(b.ptypeid,len(a.typeid))=a.typeid) where (b.billtype = '+cast(@billtype as varChar(10))+' or b.billtype = '+cast(@billtype1 as varchar(10))+@cz_Dx++')  '+@cz_Query+' and b.atypeid='''+@a_id+''' and a.deleted=0 and a.parid='''+@parid+''' AND b.BtypeId Like '+CHAR(39)+@BTypeId+'%'+CHAR(39)+' AND b.PtypeId Like '+CHAR(39)+@PTypeId+'%'+CHAR(39)+'AND b.EtypeId Like '+CHAR(39)+@ETypeId+'%'+CHAR(39)+'group by left(b.ptypeid,len(a.typeid))) t
            on (a.typeid=t.typeid) where a.deleted=0 order by a.usercode'
else --销售
if (@billTYpe=11 or @billTYpe=45) or (@billTYpe1=11 or @billTYpe1=45)  --进货
select @sql='SELECT a.typeId, a.Parid, a.leveal,a.sonnum, a.FullName, a.UserCode,cast(-1 *t.qty as  NUMERIC(24, 10) ) as qty,cast(-1 * t.total as  NUMERIC(24, 10) ) as total,cast(-1 * t.taxtotal as  NUMERIC(24, 10) ) as taxtotal
             from ptype a 
             inner join
             (select left(b.ptypeid,len(a.typeid)) as typeid, sum(b.qty) as qty,sum(b.total) as total,sum(b.total*(1+c.tax/100)) as taxtotal    from  inoutstocktable b  inner join billindex c on(b.billnumberid=c.billnumberid)   inner join ptype a on(left(b.ptypeid,len(a.typeid))=a.typeid)  where (b.billtype = '+cast(@billtype as varChar(10))+' or b.billtype = '+cast(@billtype1 as varchar(10))+@cz_Dx++')  '+@cz_Query+' and b.atypeid='''+@a_id+''' and a.deleted=0 and a.parid='''+@parid+''' AND b.BtypeId Like '+CHAR(39)+@BTypeId+'%'+CHAR(39)+' AND b.PtypeId Like '+CHAR(39)+@PTypeId+'%'+CHAR(39)+'AND b.EtypeId Like '+CHAR(39)+@ETypeId+'%'+CHAR(39)+'group by left(b.ptypeid,len(a.typeid))) t
            on (a.typeid=t.typeid) where a.deleted=0 order by a.usercode'
--print(@sql)
exec(@sql)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryDayOrMonthEX23]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryDayOrMonthEX23]
GO

/*
	作者：谢吉康
	日期：2007-3-21
	描述：销售报表
*/
/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE                                  PROCEDURE Gp_QueryDayOrMonthEX23
( 
	@OperatorID 	VARCHAR(50),
	@QueryType 		VARCHAR(20)='sale' ,            ----------------sale:销售，buy：进货
	@ktypeid 		VARCHAR(MAX)='',
	@BEGINDate  	VARCHAR(20),
	@EndDate  		VARCHAR(20),
	@DAY   			VARCHAR(20),
	@Parid  		VARCHAR(50),
	--@chvOrder 	varchar(100)  =''
    @sortField      VARCHAR(25)='',
    @sortType       VARCHAR(25)='',
    @Stypeid		VARCHAR(MAX),
    @IsCountSendPtype INT			--是否统计发出商品,发出商品出库单、发出商品退货单、销售发货开票
)
--@encode$--
AS

SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1


DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT


CREATE TABLE #Ptype (TypeID varchar(50),saleunitrate  NUMERIC(24, 10) )
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Stype	(TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #MainType (TypeID varchar(50),parid varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,leveal int,unit1 varchar(max),unit2 varchar(max),unitrate1 varchar(max),SortID NUMERIC(10,0))

INSERT INTO #Ptype(typeid,saleunitrate) SELECT typeid,saleUnitRate FROM F_GetManPTypeDetailALL(@OperatorID)
INSERT INTO #Btype SELECT a.typeid FROM F_GetManDetailBType(@OperatorID) a
INSERT INTO #Etype SELECT typeid FROM F_GetManDetailEType(@OperatorID)
--分支机构
INSERT INTO #Stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID)
INSERT INTO #Dtype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)
IF @KTypeID=''
BEGIN
	INSERT INTO #Ktype SELECT typeid FROM F_GetManDetailKType(@OperatorID) UNION ALL SELECT '10000'
END
ELSE
	INSERT INTO #Ktype SELECT a.typeid FROM F_GetManDetailKType(@OperatorID) a,  (SELECT * FROM  dbo.f_split(@ktypeID,',')) b WHERE  a.typeid like b.a+'%'  --left(a.typeid,len(b.a))=b.a

DECLARE @sonnum int 
SET @sonnum =0

SELECT @sonnum = sonnum FROM Ptype WHERE Typeid =@parid
IF @sonnum =0 
	INSERT INTO #MainType(typeid,parid,usercode,fullname,sonnum,leveal,unit1,unit2,unitrate1,SortID) 
	SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.Unit1,p.Unit2,p.UnitRate1,P.SortID
	FROM	Ptype p,
			(SELECT typeId FROM F_GetManPTypeAll(@OperatorID) WHERE typeid =@parid) a 
	WHERE	p.typeid=a.typeid
ELSE
	INSERT INTO #MainType(typeid,parid,usercode,fullname,sonnum,leveal,unit1,unit2,unitrate1,SortID) 
	SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.Unit1,p.Unit2,p.UnitRate1 ,P.SortID
	FROM	Ptype p,
			(SELECT typeId FROM F_GetManPTypeAll(@OperatorID) WHERE parid=@parid) a 
	WHERE	p.typeid=a.typeid

DECLARE @cz_Query VARCHAR(600),@Sql VARCHAR(MAX),@cz_WHERE VARCHAR(50)


DECLARE @TempLen NUMERIC(18,0)
IF @parid = '' OR @Parid = '00000'
	BEGIN
		SET @TempLen = 5
	END
ELSE
	BEGIN
		SET @TempLen = Len(@Parid) + 5
	END


SELECT @cz_query=''

IF isdate(@BEGINdate)=1  SELECT @cz_Query=@cz_Query+'AND  b.billdate>='+CHAR(39)+@BEGINdate+CHAR(39)--+' AND c.billdate>='+CHAR(39)+@BEGINdate+CHAR(39)
IF isdate(@enddate)=1     SELECT @cz_Query=@cz_Query+'AND b.billdate<='+CHAR(39)+@enddate+CHAR(39)--+' AND c.billdate<='+CHAR(39)+@enddate+CHAR(39)
IF isdate(@DAY)=1            SELECT @cz_Query=@cz_Query+' AND b.billdate='+CHAR(39)+@DAY+CHAR(39)--+' AND c.billdate='+CHAR(39)+@DAY+CHAR(39)
--IF RTRIM(@ktypeid)<> ''      SELECT @cz_query=@cz_query+' AND b.Ktypeid='+CHAR(39)+@ktypeid+CHAR(39) 


IF UPPER(@QueryType)='SALE' 
BEGIN
	--9.6需求增加发出商品出库单、发出商品退货单、ReceiptBill	
	IF(@IsCountSendPtype = 1)
	BEGIN
		SET @sql = 'SELECT	Substring(PtypeID,1,'+CAST( @TempLen AS VARCHAR)+') as PtypeID,
						SUM(qty) AS qty,
						SUM(fzslqty) AS fzslqty,
						SUM(total) AS total,
						SUM(taxtotal) AS taxtotal,
						sum(nqty) as nqty
				INTO #SALETEMP
				FROM 
				(
					SELECT	b.PtypeID,
					b.qty,
					b.qty/p.saleunitrate AS fzslqty,
					b.total,
					Cast(b.taxtotal as  NUMERIC(24, 10) ) AS taxtotal,
					b.nqty 
					FROM inoutstocktable B
					INNER JOIN #ptype p ON  b.ptypeid=p.typeid
				'
					IF @MDtypeid='-99999'	SET @Sql=@Sql+' INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)
					IF @MBtypeid='-99999' OR @MBTypeID2='-99999'	SET @Sql=@Sql+'	INNER JOIN #btype bt ON  b.btypeid=bt.typeid	'+CHAR(13)
					IF @METypeID='-99999'	SET @Sql=@Sql+'	INNER JOIN #etype e ON  b.etypeid=e.typeid	'+CHAR(13)
					IF @MKTypeID='-99999' OR @KTypeID<>''	SET @Sql=@Sql+'	INNER JOIN #ktype k ON  b.ktypeid=k.typeid	'+CHAR(13)
					IF @MStypeid<>'00000' OR @Stypeid <>''	SET @Sql=@Sql+'	INNER JOIN #Stype s ON  b.stypeid=s.typeid	'+CHAR(13)
					SET @Sql+='
					WHERE b.billtype IN(11,45,305,141,160,215,12,46)  
							'+@cz_Query+' 
							AND b.Audited=1	
							
					UNION ALL
					--发出商品出库单
					SELECT A.PtypeId,
					-(A.Qty - A.InvoiceQty) AS Qty,
					-((A.Qty - A.InvoiceQty) / p.saleunitrate) AS fzslqty,
					CASE A.InvoiceQty
						WHEN 0 THEN -A.total
						ELSE -((A.Qty - A.InvoiceQty) * A.DiscountPrice)
					END AS total,
					CASE A.InvoiceQty
						WHEN 0 THEN -A.TaxTotal
						ELSE -((A.Qty - A.InvoiceQty) * A.TaxPrice)
					END AS taxtotal,
					-(A.NQty - A.InvoiceNQty) AS NQty 
					FROM SendBill AS A 
					INNER JOIN BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
					INNER JOIN #ptype AS p ON(A.ptypeid = p.typeid) 
					'
					IF @MDtypeid='-99999'	SET @Sql=@Sql+' INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)
					IF @MBtypeid='-99999' OR @MBTypeID2='-99999'	SET @Sql=@Sql+'	INNER JOIN #btype bt ON  b.btypeid=bt.typeid	'+CHAR(13)
					IF @METypeID='-99999'	SET @Sql=@Sql+'	INNER JOIN #etype e ON  b.etypeid=e.typeid	'+CHAR(13)
					IF @MKTypeID='-99999' OR @KTypeID<>''	SET @Sql=@Sql+'	INNER JOIN #ktype k ON  A.ktypeid=k.typeid	'+CHAR(13)
					IF @MStypeid<>'00000' OR @Stypeid <>''	SET @Sql=@Sql+'	INNER JOIN #Stype s ON  A.stypeid=s.typeid	'+CHAR(13)
					SET @Sql += '
					WHERE B.ifcheck = ''t'' 
						AND B.draft = 0
						'+@cz_Query+'
						AND B.RedWord = 0
						AND B.ifYearBill=''0''
					
					UNION ALL
					--发出商品退货单
					SELECT A.PtypeId,
					A.Qty - A.InvoiceQty AS Qty,
					(A.Qty - A.InvoiceQty) / p.saleunitrate AS fzslqty,
					CASE A.InvoiceQty
						WHEN 0 THEN A.total
						ELSE (A.Qty - A.InvoiceQty) * A.DiscountPrice
					END AS total,
					CASE A.InvoiceQty
						WHEN 0 THEN A.TaxTotal
						ELSE (A.Qty - A.InvoiceQty) * A.TaxPrice
					END AS taxtotal,
					A.NQty - A.InvoiceNQty AS NQty
					FROM SendBackBill AS A 
					INNER JOIN BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
					INNER JOIN #ptype AS p ON(A.ptypeid = p.typeid) 
				    '
				    IF @MDtypeid='-99999'	SET @Sql=@Sql+' INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)
					IF @MBtypeid='-99999' OR @MBTypeID2='-99999'	SET @Sql=@Sql+'	INNER JOIN #btype bt ON  b.btypeid=bt.typeid	'+CHAR(13)
					IF @METypeID='-99999'	SET @Sql=@Sql+'	INNER JOIN #etype e ON  b.etypeid=e.typeid	'+CHAR(13)
					IF @MKTypeID='-99999' OR @KTypeID<>''	SET @Sql=@Sql+'	INNER JOIN #ktype k ON  A.ktypeid=k.typeid	'+CHAR(13)
					IF @MStypeid<>'00000' OR @Stypeid <>''	SET @Sql=@Sql+'	INNER JOIN #Stype s ON  A.stypeid=s.typeid	'+CHAR(13)
					SET @Sql += '
					WHERE B.ifcheck = ''t'' 
						AND B.draft = 0
						'+@cz_Query+'
						AND B.RedWord = 0
						AND B.ifYearBill=''0''
						
					UNION ALL
					--销售发货开票
					SELECT A.PTypeID,
					-A.Qty,
					-(A.qty / P.saleunitrate) AS fzslqty,
					-A.total,
					-A.taxtotal,
					-A.NQty 
					FROM ReceiptBill AS A
					INNER JOIN dbo.ReceiptBillIndex AS B ON(A.BillNumberID = B.BillNumberID AND A.BillType = B.BillType)
					INNER JOIN #ptype AS p ON(A.ptypeid = p.typeid) 
					'
					IF @MDtypeid='-99999'	SET @Sql=@Sql+' INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)
					IF @MBtypeid='-99999' OR @MBTypeID2='-99999'	SET @Sql=@Sql+'	INNER JOIN #btype bt ON  b.btypeid=bt.typeid	'+CHAR(13)
					IF @METypeID='-99999'	SET @Sql=@Sql+'	INNER JOIN #etype e ON  b.etypeid=e.typeid	'+CHAR(13)
					IF @MKTypeID='-99999' OR @KTypeID<>''	SET @Sql=@Sql+'	INNER JOIN #ktype k ON  A.ktypeid=k.typeid	'+CHAR(13)
					IF @MStypeid<>'00000' OR @Stypeid <>''	SET @Sql=@Sql+'	INNER JOIN #Stype s ON  A.stypeid=s.typeid	'+CHAR(13)
					SET @Sql += '
					WHERE B.ifcheck = ''t'' 
						AND B.draft = 0
						'+@cz_Query+'
						AND B.RedWord = 0
						AND b.ifYearBill=''0''
						AND B.BillType = 405
					'
				
	SET @sql += '	
				) AS A 
				GROUP BY Substring(PtypeID,1,'+CAST( @TempLen AS VARCHAR)+')
				'
	END
	ELSE
	BEGIN
		SELECT @sql='SELECT	Substring(b.PtypeID,1,'+CAST( @TempLen AS VARCHAR)+') as PtypeID,
						SUM(b.qty) AS qty,
						SUM(b.qty/p.saleunitrate) AS fzslqty,
						SUM(b.total) AS total,
						SUM(Cast(b.taxtotal as  NUMERIC(24, 10) )) AS taxtotal,
						sum(b.nqty) as nqty
				INTO #SALETEMP
				FROM  	inoutstocktable b 
						INNER JOIN #ptype p ON  b.ptypeid=p.typeid '

					--IF @MPtypeid='-99999'	SET @Sql=@Sql+' 	'+CHAR(13)
					IF @MDtypeid='-99999'	SET @Sql=@Sql+' INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)
					IF @MBtypeid='-99999' OR @MBTypeID2='-99999'	SET @Sql=@Sql+'	INNER JOIN #btype bt ON  b.btypeid=bt.typeid	'+CHAR(13)
					IF @METypeID='-99999'	SET @Sql=@Sql+'	INNER JOIN #etype e ON  b.etypeid=e.typeid	'+CHAR(13)
					IF @MKTypeID='-99999' OR @KTypeID<>''	SET @Sql=@Sql+'	INNER JOIN #ktype k ON  b.ktypeid=k.typeid	'+CHAR(13)
					IF @MStypeid<>'00000' OR @Stypeid <>''	SET @Sql=@Sql+'	INNER JOIN #Stype s ON  b.stypeid=s.typeid	'+CHAR(13)

					SET @Sql=@Sql+'
						WHERE 	
								b.billtype IN(11,45,305,141,160,215,12,46)  
								'+@cz_Query+' 
								AND b.Audited=1	
						GROUP BY 
						Substring(b.PtypeID,1,'+CAST( @TempLen AS VARCHAR)+') 
						'	
	END
	
	SET @sql+=' 
		SELECT	a.typeId, 
				a.Parid, 
				a.leveal,
				a.sonnum, 
				a.FullName, 
				a.UserCode,
				a.unit1,
				a.unit2,
				a.unitrate1,
				-1 *CAST(t.qty AS  NUMERIC(24, 10) ) AS qty,
				-1 *CAST(t.nqty AS  NUMERIC(24, 10) ) AS nqty,
				-1*CAST(t.fzslqty AS  NUMERIC(24, 10) ) AS fzsl,
				-1 * CAST(t.total AS  NUMERIC(24, 10) ) AS total,
				-1 * CAST(t.taxtotal AS  NUMERIC(24, 10) ) AS taxtotal,
				price =Convert( NUMERIC(24, 10) ,case when -1 *CAST(t.qty AS  NUMERIC(24, 10) ) =0 then 0 else -1 * CAST(t.total AS  NUMERIC(24, 10) )/-1 *CAST(t.qty AS  NUMERIC(24, 10) ) end)				
		FROM 	#MainType a 
		INNER JOIN	#SALETEMP t
	            ON a.typeid=t.ptypeid '
                IF(@sortField<>'' and @sortType<>'')
					SET @sql = @sql + ' Order by '+@sortField + ' ' + @sortType
				ELSE
					SET @sql = @sql + ' Order by a.SortID '
		
	SET @Sql += ' 
				DROP TABLE #SALETEMP'		
END

IF UPPER(@QueryType)='BUY'   
BEGIN

	SELECT @sql='SELECT 	
						Substring(b.PtypeID,1,'+CAST( @TempLen AS VARCHAR)+') as PtypeID,
						b.BillType,
						SUM_Qty= CASE b.BillType WHEN 145 THEN  -1*cast(SUM(b.Qty) as NUMERIC(24, 10) ) ELSE SUM(b.Qty) END,					
						SUM_Total=CASE b.BillType WHEN 145 THEN -1*SUM(b.Total) ELSE SUM(b.Total) END,
						SUM_TaxTotal=CASE b.BillType WHEN 145 THEN -1*SUM(CAST(b.taxtotal as  NUMERIC(24, 10) )) ELSE SUM((CAST(b.taxtotal as  NUMERIC(24, 10) )) ) END 
						--CASE b.BillType WHEN 145 THEN -1*b.Qty ELSE b.Qty END AS SUM_Qty,					
						--CASE b.BillType WHEN 145 THEN -1*b.Total ELSE b.Total END AS SUM_Total,
						--CASE b.BillType WHEN 145 THEN -1*CAST(b.taxtotal as  NUMERIC(24, 10) ) ELSE CAST(b.taxtotal as  NUMERIC(24, 10) )  END  AS SUM_TaxTotal  
						
					INTO	#BUYTEMP		
					FROM	InOutstocktable b
								'

					IF @MPtypeid='-99999'	SET @Sql=@Sql+' INNER JOIN #ptype p ON  b.ptypeid=p.typeid	'+CHAR(13)
					IF @MDtypeid='-99999'	SET @Sql=@Sql+' INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)
					IF @MBtypeid='-99999' OR @MBTypeID2='-99999'	SET @Sql=@Sql+'	INNER JOIN #btype bt ON  b.btypeid=bt.typeid	'+CHAR(13)
					IF @METypeID='-99999'	SET @Sql=@Sql+'	INNER JOIN #etype e ON  b.etypeid=e.typeid	'+CHAR(13)
					IF @MKTypeID='-99999' OR @KTypeID<>''	SET @Sql=@Sql+'	INNER JOIN #ktype k ON  b.ktypeid=k.typeid	'+CHAR(13)
					IF @MStypeid<>'00000' OR @Stypeid<>''	SET @Sql=@Sql+'	INNER JOIN #Stype s ON  b.stypeid=s.typeid	'+CHAR(13)
					SET @Sql=@Sql+'

					WHERE 	
							b.BillType in (34,6,145,161)
							'+@cz_Query+' 
							AND b.Audited=1	
					GROUP BY  
						b.BillType,
						Substring(b.PtypeID,1,'+CAST( @TempLen AS VARCHAR)+')
						'

	SET @sql+=' 
			SELECT  b.TypeID,
					b.ParID,
					b.leveal,
					b.UserCode,
					b.FullName,
					b.sonnum,
					b.unit1,
					b.unit2,
					b.unitrate1,
					ISNULL(SUM(SUM_Qty),0) AS Qty,
					ISNULL(SUM(SUM_Total),0) AS Total,
					ISNULL(SUM(SUM_TaxTotal),0) AS TaxTotal,
					price =case when ISNULL(SUM(SUM_Qty),0) =0 then 0 else cast( ISNULL(SUM(SUM_Total),0)as NUMERIC(24, 10))/cast( ISNULL(SUM(SUM_Qty),0) as NUMERIC(24, 10)) end,
					customassist=dbo.F_GetCustomAssist(b.TypeID, ISNULL(SUM(SUM_Qty),0) )				
			FROM 
					#BUYTEMP a , #MainType b
			WHERE	a.ptypeid=b.typeid 
			GROUP	BY b.ParID,b.leveal,b.typeid,b.Usercode,b.Fullname,b.sonnum,b.unit1,b.unitrate1,b.SortID,
					b.unit2 ORDER BY b.SortID
				
		'
		
	SET @Sql += ' 
				DROP TABLE #BUYTEMP'	
END

--PRINT(@SQL)
EXEC(@sql)


DROP TABLE #MainType,#Ptype,#Btype,#Etype,#Ktype,#Stype,#Dtype			


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryDXBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryDXBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：销售退货，采购退货调原来的销售单，采购入库单
--			返回单据信息
-- 作者：	陈启华
-- 最后修改时间：	2004-06-17
-- ========================================================================
CREATE              PROCEDURE Gp_QueryDXBill
( 
	 @chvBeginDate	VARCHAR(max),
	 @chvEndDate	VARCHAR(25),
	 @chvBtype	 	VARCHAR(250),
	 @chvEtype		VARCHAR(250),
	 @chvKtype		VARCHAR(250),
	 @chvstype		varchar(250),
	 @chvPtype		VARCHAR(250),
	 @chvOperatorId VARCHAR(50),       --操作员ID
	 @chvType       VARCHAR(5),
	 @sh			int=-1,
	 @IsIni			int=0,			   --1为期初单据，0为非期初单据
	 @cid			varchar(50)='',    --币种 
	 @btypeid   	varchar(50)='',
	 @areatypeid	VARCHAR(max)='',	--地区（多选,不确定值的大小所以用max）
	 @checkEtypeid	VARCHAR(max)='',	--制单人（多选,不确定值的大小所以用max） 
	 @explain		VARCHAR(255),		--说明
	 @comment		VARCHAR(255)		--摘要
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 往来单位
IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
BEGIN
	DECLARE @chvBTypeAll char(1)
	SET @chvBTypeAll = '0'
	SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'
	
	SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)
	
	DECLARE @SQL_ManB varchar(100)
	SET @SQL_ManB = ' INNER JOIN #F_BaseGetManDetailBType B ON a.DealBTypeID = B.TypeID '
	
	IF @chvBTypeAll = '0'
	BEGIN
		IF @chvType = '140' AND @chvMBTypeID = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00001%'' '
	
		IF @chvType = '144' AND @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00002%'' '
	END
	ELSE
	BEGIN
		IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB
	END
END
-- 结算单位
IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
BEGIN
	DECLARE @chvBTypeAll1 char(1)
	SET @chvBTypeAll1 = '0'
	SELECT @chvBTypeAll1 = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'
	
	SELECT TypeID INTO #F_BaseGetManDetailBType1 FROM F_BaseGetManDetailBType(@chvOperatorID)
	
	DECLARE @SQL_ManB1 varchar(100)
	SET @SQL_ManB1 = ' INNER JOIN #F_BaseGetManDetailBType1 B1 ON a.BTypeID = B1.TypeID '
	
	IF @chvBTypeAll1 = '0'
	BEGIN
		IF @chvType = '140' AND @chvMBTypeID = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB1 + ' AND B1.TypeID LIKE ''00001%'' '
	
		IF @chvType = '144' AND @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB1 + ' AND B1.TypeID LIKE ''00002%'' '
	END
	ELSE
	BEGIN
		IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB1
	END
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END

-- 商品
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailPType P ON detail.PTypeID = P.TypeID '
END

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
END

-- 分支机构
IF @chvMStypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailsType FROM F_BaseGetManDetailSType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailsType s ON a.sTypeID = s.TypeID '
END

--部门
IF  @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END
-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(2000)
SET @SQL = '
	SELECT	DISTINCT a.BillNumberID,a.BillType,a.BillDate,a.BillCode,a.ETypeID,a.DealBTypeID AS BTypeID,a.KTypeID,a.Comment,a.stypeid,a.explain
	FROM	Billindex a
			INNER JOIN CommissionBill detail ON a.BillNumberID=detail.BillNumberID AND ISNULL(detail.Qty,0)-ISNULL(detail.BackQty,0)-ISNULL(detail.BQty,0) > 0
	' + CASE WHEN @chvPType <> '' THEN ' AND detail.PTypeID=''' + @chvPType + '''' ELSE '' END + @SQL_Man + '
	WHERE	a.BillDate >= ''' + @chvBeginDate + ''' AND a.BillDate <= ''' + @chvEndDate + '''
			AND a.BillType=' + @chvType + '
			AND a.Draft=0
			AND a.RedWord=0
			AND a.ifCheck=''t'''
			
--增加摘要说明
SET @SQL = @SQL + ' AND a.explain LIKE ''%'+@explain+'%'''
SET @SQL = @SQL + ' AND a.comment LIKE ''%'+@comment+'%'''			

IF @IsIni = 1	   SET @SQL = @SQL + ' AND a.IsIni=1'
ELSE SET @SQL = @SQL + ' AND a.IsIni=0 '
IF @cid <> '' SET @SQL = @SQL + ' AND  a.CID =  ''' + @cid + ''''
IF @chvBType <> '' SET @SQL = @SQL + ' AND a.DealBTypeID=''' + @chvBType + ''''
IF @chvEType <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @chvEType + ''''
IF @chvKType <> '' SET @SQL = @SQL + ' AND a.KTypeID=''' + @chvKType + ''''
IF @chvstype <> '' SET @SQL = @SQL + ' AND a.sTypeID=''' + @chvstype + ''''
IF @btypeid <> '' SET @SQL = @SQL + ' AND a.btypeid=''' + @btypeid + ''''
IF @areatypeid<>''
BEGIN
	SET @SQL = @SQL+' AND a.dealbtypeid IN (SELECT typeid FROM btype WHERE areatypeid in ('''+REPLACE(@areatypeid,',',''',''')+'''))'
END
IF @checkEtypeid<>''
BEGIN
	SET @SQL = @SQL+' AND a.CHECKE IN ('''+REPLACE(@checkEtypeid,',',''',''')+''')'
END
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC'

--PRINT(@SQL)
EXEC (@SQL)


IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999' DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMPTypeID = '-99999' DROP TABLE #F_BaseGetManDetailPType
IF @chvMStypeid = '-99999' DROP TABLE #F_BaseGetManDetailsType
IF @chvMdtypeid = '-99999' DROP TABLE #F_BaseGetManDetaildType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryExchangePType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryExchangePType]
GO












/*
	作者：谢吉康
	日期：2003-12-24
	描述：商品换货查询
*/
CREATE         PROCEDURE GP_QueryExchangePType
(
	@OperatorID 	VARCHAR(50),	--操作员的ID
	@StartDate	VARCHAR(50),		--开始日期
	@EndDate	VARCHAR(50),		--结束日期
	@PtypeID	VARCHAR(50),		--商品的ID
	@EtypeID	VARCHAR(50),		--职员的ID
	@KtypeID	VARCHAR(50),		--仓库的ID
	@KtypeID1	VARCHAR(50),		--仓库的ID
	@SortFild	VARCHAR(50),		--排序字段
	@SortKind	INT,				--排序方式   0.升序  1.倒序
	@QueryType  INT,				--0.全部维修类型
	@BillType	INT					--单据的类型
)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)	--树型结果
	DECLARE @PTypeIDmx VARCHAR(50)
	DECLARE @PsonNum INT
	
	IF @KTypeID = '00000'
		SELECT @KTypeID = '%'

	IF @KTypeID1 = '00000'
		SELECT @KTypeID1 = '%'

	IF @PTypeID = '00000'
		BEGIN
			SELECT @PTypeIDmx = '%'
			IF @MPTypeId <> ''
				SELECT @PTypeId = @MPTypeId
		END
	ELSE
		SELECT @PTypeIDmx = @PTypeID

	SELECT @PsonNum = SonNum FROM PType WHERE TypeID = @PTypeID AND Deleted = 0


BEGIN	
	SELECT @SQL='
		SELECT	a.typeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				ISNULL(SUM(b.InQty),0) AS InQty,
				ISNULL(SUM(b.OutQty),0) AS OutQty
		FROM	PType a
		LEFT JOIN 
			(
				SELECT	B.PTypeID,
						ISNULL(SUM(B.Qty),0) AS InQty,
						0 As OutQty
				FROM 	BillIndex A,
						InOutStockTable B
				WHERE 	A.BillNumberID = B.BillNumberID
						AND A.IfCheck = ''t''
						AND A.Draft = 0
						AND A.RedWord =0 
						AND A.BillDate>='+char(39)+@StartDate+char(39)+'
						AND A.BillDate<='+char(39)+@EndDate+char(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@KTypeID1+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND B.Qty >0
						AND A.BillType =155
				GROUP BY
						B.PTypeID
				UNION 
				SELECT	B.PTypeID,
						0 AS InKQty,
						ISNULL(SUM(B.Qty),0) As OutQty
				FROM 	BillIndex A,
						InOutStockTable B
				WHERE 	A.BillNumberID = B.BillNumberID
						AND A.IfCheck = ''t''
						AND A.Draft = 0
						AND A.RedWord =0
						AND A.BillDate>='+char(39)+@StartDate+char(39)+'
						AND A.BillDate<='+char(39)+@EndDate+char(39)+' 
						AND B.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						AND A.KTypeID LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+'
						AND A.KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND B.Qty<0
						AND A.BillType =155
				GROUP BY
						B.PTypeID
			)b ON a.TypeID=LEFT(b.PtypeID,len(a.Typeid))'


			IF @PsonNum > 0
				SELECT @SQL = @SQL + ' WHERE a.ParID = '+CHAR(39)+@PTypeID+CHAR(39)
			ELSE
				SELECT @SQL = @SQL + ' WHERE a.TypeID = '+CHAR(39)+@PTypeID+CHAR(39)

			SELECT @SQL = @SQL +'
				AND a.deleted = 0
				AND a.TypeId <> ''00000''
				AND a.TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
			GROUP BY
				a.TypeID,
				a.UserCode,
				a.FullName,
				a.SonNum
			ORDER BY a.UserCode'


		--PRINT(@SQL)
		EXEC(@SQL)

END














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryExchangePTypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryExchangePTypeDetail]
GO












/*
	作者：谢吉康
	日期：2003-12-24
	描述：商品换货查询明细表
*/
CREATE          PROCEDURE GP_QueryExchangePTypeDetail
(
	@OperatorID VARCHAR(50),		--操作员的ID
	@StartDate	VARCHAR(50),		--开始日期
	@EndDate	VARCHAR(50),		--结束日期
	@PtypeID	VARCHAR(50),		--商品的ID
	@EtypeID	VARCHAR(50),		--职员的ID
	@KtypeID	VARCHAR(50),		--仓库的ID
	@KtypeID1	VARCHAR(50),		--仓库的ID
	@SortFild	VARCHAR(50),		--排序字段
	@SortKind	INT,				--排序方式   0.升序  1.倒序
	@QueryType  INT,				--0.全部维修类型
	@BillType	INT,				--单据的类型
	@WhichK     INT					--更据OutKQty,InKQty的数量来判定哪个仓库的ID有效  0.两个仓库的参数都有效  1.KtypeID有效  2.KtypeID1有效
)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)
	
	IF @KTypeID = '00000'
		SELECT @KTypeID = '%'

	IF @KTypeID1 = '00000'
		SELECT @KTypeID1 = '%'
	
BEGIN
	SELECT @SQL = '
		SELECT	A.BillNumberID,
				A.BillCode,
				A.BillDate,
				E.FullName AS EFullName,
				P.UserCode,
				P.FullName AS PFullName,			
				B.CostPrice,
				A.Comment,
				A.KTypeID2 AS InK,
				A.KTypeID AS OutK,
				ABS(ISNULL(SUM(B.Qty),0)) AS Qty				
		FROM 	BillIndex A,
				InOutStockTable B,
				PType P,
				Employee E
		WHERE   A.BillNumberID = B.BillNumberID
				AND P.TypeID = B.PTypeID
				AND E.TypeID = A.ETypeID
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.Draft = 0
				AND A.BillType = 155
				AND A.BillDate>='+char(39)+@StartDate+char(39)+'
				AND A.BillDate<='+char(39)+@EndDate+char(39)+'
				AND B.PTypeID LIKE '+CHAR(39)+@PTypeID + '%' + CHAR(39)+'
				AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID + '%' + CHAR(39)+'
				AND A.ETypeID LIKE '+CHAR(39)+@ETypeID + '%' + CHAR(39)+'
				AND A.ETypeID LIKE '+CHAR(39)+@METypeID + '%' + CHAR(39)
		IF  @WhichK=1	--判断仓库的有效性
			SELECT @SQL = @SQL +'	
				AND A.KTypeID LIKE '+CHAR(39)+@KTypeID + '%' + CHAR(39)+'
				AND B.Qty<0
				AND A.KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)
		ELSE
			BEGIN
				IF  @WhichK=2 
					SELECT @SQL = @SQL + '
						AND A.KTypeID2 LIKE '+CHAR(39)+@KTypeID1+ '%'+CHAR(39)+'
						AND B.Qty>0
						AND A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)
				ELSE
					SELECT @SQL = @SQL + '
						AND B.Qty>0
						AND A.KTypeID LIKE '+CHAR(39)+@KTypeID + '%' + CHAR(39)+'	
						AND A.KTypeID2 LIKE '+CHAR(39)+@KTypeID1+ '%'+CHAR(39)+'
						AND A.KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)

			END

		SELECT @SQL = @SQL + ' 
			GROUP BY
				A.BillNumberID,
				A.BillCode,
				A.BillDate,
				A.Comment,
				E.FullName,
				P.UserCode,
				P.FullName,			
				B.CostPrice,
				A.KTypeID,
				A.KTypeID2'

			--构造排序字段  
			IF @SortFild=''
				SELECT @SQL=@SQL+' Order By A.BillDate'
			ELSe
				BEGIN
					IF @SortFild='BillDate'		SELECT @SQL=@SQL+' Order By A.BillDate' 		--单据日期
					IF @SortFild='BillCode'		SELECT @SQL=@SQL+' Order By A.BillCode' 		--单据编号
					IF @SortFild='EtypeID'		SELECT @SQL=@SQL+' Order By eFullName' 		--经手人
					IF @SortFild='PUserCode'	SELECT @SQL=@SQL+' Order By P.UserCode' 		--商品编号
					IF @SortFild='PFullName'	SELECT @SQL=@SQL+' Order By P.FullName' 		--商品名称
					IF @SortFild='Qty'			SELECT @SQL=@SQL+' Order By B.Qty'	 		--数量
					IF @SortFild='CostTotal'	SELECT @SQL=@SQL+' Order By B.CostTotal' 		--成本金额
					IF @SortFild='CostPrice'	SELECT @SQL=@SQL+' Order By B.CostPrice' 		--单价
					IF @SortFild='KtypeID'		SELECT @SQL=@SQL+' Order By A.KtypeID'  		--调出仓库
					IF @SortFild='KtypeID1' 	SELECT @SQL=@SQL+' Order By A.KtypeID2' 		--调入仓库
				END
			--构造排序的方式
			IF @SortKind=0
				SELECT @SQL=@SQL+' ASC'	--升序
			ELSE
				SELECT @SQL=@SQL+' DESC'	--降序

	
		--PRINT(@SQL)
		EXEC(@SQL)
END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryExchangePTypeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryExchangePTypeLine]
GO











/*
	作者：谢吉康
	日期：2003-12-24
	描述：商品换货线性查询
*/
CREATE         PROCEDURE GP_QueryExchangePTypeLine
(
	@OperatorID 	VARCHAR(50),	--操作员的ID
	@StartDate	VARCHAR(50),		--开始日期
	@EndDate	VARCHAR(50),		--结束日期
	@PtypeID	VARCHAR(50),		--商品的ID
	@EtypeID	VARCHAR(50),		--职员的ID
	@KtypeID	VARCHAR(50),		--仓库的ID
	@KtypeID1	VARCHAR(50),		--仓库的ID
	@SortFild	VARCHAR(50),		--排序字段
	@SortKind	INT,				--排序方式   0.升序  1.倒序
	@QueryType  INT,				--0.全部维修类型
	@BillType	INT					--单据的类型
)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)	--树型结果
	DECLARE @PTypeIDmx VARCHAR(50)
	DECLARE @PsonNum INT

	SELECT @PsonNum = SonNum FROM PType WHERE TypeID = @PTypeID AND Deleted = 0
	
	IF @KTypeID = '00000'
		SELECT @KTypeID = '%'

	IF @KTypeID1 = '00000'
		SELECT @KTypeID1 = '%'

	IF @PTypeID = '00000'
		BEGIN
			SELECT @PTypeID = '%'
			SELECT @PTypeIDmx = '%'
		END
	ELSE
		SELECT @PTypeIDmx = @PTypeID


BEGIN	
	SELECT @SQL='
		SELECT	a.typeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				ISNULL(SUM(b.InQty),0) AS InQty,
				ISNULL(SUM(b.OutQty),0) AS OutQty
		FROM	PType a
		LEFT JOIN 
			(
				SELECT	B.PTypeID,
						ISNULL(SUM(B.Qty),0) AS InQty,
						0 As OutQty
				FROM 	BillIndex A,
						InOutStockTable B
				WHERE 	A.BillNumberID = B.BillNumberID
						AND A.IfCheck = ''t''
						AND A.Draft = 0
						AND A.RedWord =0 
						AND A.BillDate>='+char(39)+@StartDate+char(39)+'
						AND A.BillDate<='+char(39)+@EndDate+char(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@KTypeID1+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND B.Qty >0
						AND A.BillType =155
				GROUP BY
						B.PTypeID
				UNION 
				SELECT	B.PTypeID,
						0 AS InKQty,
						ISNULL(SUM(B.Qty),0) As OutQty
				FROM 	BillIndex A,
						InOutStockTable B
				WHERE 	A.BillNumberID = B.BillNumberID
						AND A.IfCheck = ''t''
						AND A.Draft = 0
						AND A.RedWord =0 
						AND A.BillDate>='+char(39)+@StartDate+char(39)+'
						AND A.BillDate<='+char(39)+@EndDate+char(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						AND A.KTypeID LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+'
						AND A.KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND B.Qty<0
						AND A.BillType =155
				GROUP BY
						B.PTypeID
			)b ON a.TypeID=b.PtypeID
		WHERE 	a.TypeID LIKE '+CHAR(39)+@PTypeID+'%'+CHAR(39)+'
				AND a.deleted = 0
				AND a.SonNum = 0
				AND a.TypeId <> ''00000''
				AND a.TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
			GROUP BY
				a.TypeID,
				a.UserCode,
				a.FullName,
				a.SonNum
			ORDER BY a.UserCode'


		--Print(@SQL)
		EXEC(@SQL)

END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryFactBillIndexLi]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryFactBillIndexLi]
GO



/*
	作者：魏伟
	日期：2016-07-13
	描述：经营历程的报表查询
*/
 


CREATE PROCEDURE Gp_QueryFactBillIndexLi
( 
	@OperatorID		varchar(100) 	,  			-- 操作员
	@BillType	 	varchar(MAX)   	='',		-- 单据类型
	@OtherType	 	varchar(MAX)   	='',		-- 出入库类型
	@BeginDate	 	varchar(25)  	='', 		-- 开始时间
	@EndDate	 	varchar(25)  	='',   		-- 结束时间
	@BillCode	 	varchar(200) 	='',  		-- 单据编号#&**&#
	@EtypeName	 	varchar(MAX)	='',    	-- 经手人名称
	@KtypeName	 	varchar(MAX)	='', 		-- 仓库1
	@KtypeName2 	varchar(MAX)	='',		-- 仓库2   
	@Comment	 	varchar(256)	='',		-- 摘要  
	@ZYDetail   	varchar(255)	='',  		-- 备注 
	@chrFlag		char(1)		    ='1',		-- 功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@PageNo        	int, 
	@Explain		varchar(1000)	='',		-- 说明 
	@stypeid        varchar(MAX)	='00001',  	-- 分支机构   
	@OrderBy	 	varchar(MAX)	='',     	-- 排序
	@UserDeRowCount INT 
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON

IF @UserDeRowCount = 0
	SET @UserDeRowCount = (SELECT UserDeRowCount FROM loginuser WHERE ETYPEID = @OperatorID)
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @BillType = '-1' 
	SET @BillType = ''
IF @OtherType='-1'
    SET @OtherType = ''

DECLARE @SQL		VARCHAR(MAX)
DECLARE @SQL_LIST	VARCHAR(MAX)
DECLARE @SQL_FROM	VARCHAR(MAX)
DECLARE @SQL_WHERE	VARCHAR(MAX)
DECLARE @SQL_ORDER	VARCHAR(MAX)
DECLARE @FiltVal	VARCHAR(MAX)
DECLARE @SQL_SUM	VARCHAR(MAX)
SET @SQL_SUM = ''

SELECT @SQL_LIST  = ''
SELECT @SQL_WHERE = ''
SELECT @SQL_FROM  = ''
SELECT @SQL_ORDER = ''
SELECT @SQL  = ''

DECLARE @SQL_DEBT VARCHAR(2000)='' -- 输入往来单位时用来统计调帐单

--Ac_ProvisionForImpairment表中固定资产这边--做减值准备后台自动生成的一个凭证，生成凭证目的只为影响项目的值 对客户来说，这张凭证是不存在的
SET @SQL_WHERE = 'WHERE bi.[BillDate]>=''' + @BeginDate +'''
						AND bi.[BillDate]<=''' + @EndDate +'''
						AND bi.IfCheck = ''t'' 
						AND(BI.Frombilltype IS NULL OR  Bi.Frombilltype NOT IN (176,177,180,182,184,185,192,198) )
						AND BI.BILLNUMBERID NOT IN (SELECT BILLNUMBERID FROM Ac_ProvisionForImpairment) '
										
IF @EtypeName<>'' AND  @EtypeName IS NOT NULL
	BEGIN
		SET  @SQL_WHERE += 'AND BI.etypeid in (select  * from f_split(''' + @EtypeName+''','','') ) '
	END 
						
----------------------判断系统未启用某些配置时不应该显示的单据   start--------------------------------------
DECLARE   @combinationproduct INT,@usetransport INT
 
 
--组合品
SELECT @combinationproduct=SubValue FROM sysdata WHERE SubName = 'combinationproduct'  
IF @combinationproduct<>1
	 SET @SQL_WHERE += ' AND Bi.BillType NOT IN (12,46)'
--物流运输单
SELECT @usetransport=SubValue FROM sysdata WHERE SubName = 'usetransport'  
IF @usetransport<>1
	 SET @SQL_WHERE += ' AND Bi.BillType NOT IN (414)'
----------------------判断系统未启用某些配置时不应该显示的单据 end-------------------------------------- 
 


--查看他人经营历程 LIMIT_VIEWOTHER_BILL = 745
DECLARE @LimitRe INT
EXEC @LimitRe = GP_CheckLimit @OperatorID,745
IF @LimitRe = 1
	SET @SQL_WHERE += ' AND Bi.Checke = ''' + @OperatorID + '''' 
 
 

IF @BillType <> ''
	SET @SQL_WHERE += ' AND Bi.BillType IN (SELECT * FROM F_Split('''+@BillType+''','',''))'	
	ELSE 
     SET @SQL_WHERE += ' AND Bi.BillType IN (418,419,420)'	 
IF @OtherType <> '' 
    SET @SQL_WHERE += ' AND Bi.Frombilltype IN (SELECT * FROM F_Split('''+@OtherType+''','',''))'	 

IF RTRIM(@BillCode)<>''
	SELECT @SQL_WHERE += ' AND bi.[BillCode] LIKE ''%' + @BillCode +'%'''
IF RTRIM(@Explain)<>''
	SELECT @SQL_WHERE += ' AND bi.[Explain] LIKE ''%' + @Explain +'%'''
IF RTRIM(@Comment)<>''
	SELECT @SQL_WHERE += ' AND bi.[Comment] LIKE ''%' + @Comment +'%''' 

--筛选经手人
CREATE TABLE #Employee(TypeId 	varchar(100))
SET @EtypeName = LTRIM(RTRIM(@EtypeName))
INSERT INTO #Employee(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@EtypeName,3,@OperatorID)	
 
--END
  
--筛选分支机构
CREATE TABLE #Stype(TypeId 	varchar(100))
SET @stypeid = LTRIM(RTRIM(@stypeid))
IF  @stypeid<>'' OR @MStypeid <> '00000'
BEGIN
	INSERT INTO #Stype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	--当单据为资金调拨单，并且调出机构未选择时。 将 调出、调入机构的关系变为OR（主要根据调入机构来查询） 
	  SELECT @SQL_WHERE += ' AND bi.stypeid in ( SELECT typeid FROM #Stype) '
END

 
-- 限制Ktype
CREATE TABLE #KType(TypeId		varchar(100))
CREATE TABLE #KType2(TypeId		varchar(100))
IF RTRIM(@KtypeName)<>''
	BEGIN
		SET @KtypeName = LTRIM(RTRIM(@KtypeName))
		IF CHARINDEX(',',@OtherType)=0 AND @OtherType IN (17,21,187,188)
		BEGIN
			INSERT INTO #KType(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@KtypeName,4) S
		END
		ELSE
		BEGIN
			INSERT INTO #KType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KtypeName,4,@OperatorID) S
		END
	END

IF RTRIM(@KtypeName2)<>''
	BEGIN
		SET @KtypeName2 = LTRIM(RTRIM(@KtypeName2))
		IF CHARINDEX(',',@OtherType)=0 AND @OtherType IN (17,21,187,188)
		BEGIN
			INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@KtypeName2,4) S
			
		END
		ELSE
		BEGIN
			INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KtypeName2,4,@OperatorID) S
		END
	END 
	
DECLARE @BillTypeList VARCHAR(MAX)
DECLARE @LimitList VARCHAR(MAX)
DECLARE @BillTypes VARCHAR(2000)
SET @BillTypes ='(9999'

--单据调阅权限
SET @BillTypeList = '450,305, 11, 45, 215,  4,144,145,146,147,140,141,142,143, 34,  6, 66, 17, 21,  9, 14,139,126, 57, 16,116,115,128,129, 36, 93, 77, 84, 85,'
SET @LimitList    = '4667,349,350,351,2588,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,'

SET @BillTypeList += ' 78, 212, 213, 214,  5, 10,148,149,150,151,158,159,160,161,165,166,167,168,169,170,171,172,173,174,175, 178, 179, 183, 186,187,188,189,400,401,402,403,'
SET @LimitList    += '381,2531,2536,2541,382,383,384,385,386,502,501,550,583,585,678,679,680,681,682,683,684,685,686,687,688,1377,1378,1386,1375,718,721,727,4576,4585,4597,4606,'


SET @BillTypeList += '190, 191, 192, 197, 195, 196, 200, 201, 202, 203, 205, 206, 181, 312,418,419 ,420'
SET @LimitList    += '730,1473,1536,1475,1533,1535,1479,1553,1557,1551,1941,1946,1379,4497,4829,4837,4845'

--不是总账则不显示资金调拨单
IF((SELECT SubValue FROM SYSDATA WHERE SUBNAME = 'isuseacsystem') = 1)
BEGIN
	--9.4解决资金调拨单无法查询问题 增加单据类型310
	SET @BillTypeList += ',310'
	SET @LimitList    += ',4455'
	
END
--启用组合品销售
IF EXISTS(SELECT TOP 1 1 FROM SYSDATA WHERE SUBNAME = 'combinationproduct' AND SubValue= 1)
BEGIN
	SET @BillTypeList += ',12,46'
	SET @LimitList    += ',4749,4757'
END

IF @OperatorID<>'00001'  -- 相关单据调阅权限
BEGIN
	SELECT @BillTypes = @BillTypes + CASE WHEN SUBSTRING(L.lim,T.OFFSET,1) = 1 THEN ',' + T.BillType ELSE ''  END 
	FROM(
		SELECT A.ID,A.a AS BillType,CONVERT(INT,B.a) AS OFFSET
		FROM(
			SELECT ROW_NUMBER() OVER (ORDER BY(SELECT 0)) AS ID,a
			FROM f_split(@BillTypeList,',')	
		) A
		INNER JOIN(
			SELECT ROW_NUMBER() OVER (ORDER BY(SELECT 0)) AS ID,a
			FROM f_split(@LimitList,',')	
		)B ON A.ID = B.ID
	) T,loginuser L
	WHERE L.etypeid = @OperatorID			
END 

SET @BillTypes = @BillTypes +' ) '

IF @OperatorID<>'00001'
	SELECT @SQL_WHERE += ' AND Bi.BillType in ' +@BillTypes

 --仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)
IF @KtypeName = '' AND @KtypeName2 = ''
	INSERT INTO #GetManKTypeId(TypeId)VALUES('00000')
	
IF @OtherType = '' OR CHARINDEX(',',@OtherType)>0
	BEGIN
		SET @SQL_WHERE += ' AND ('
		IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
			BEGIN
				SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) OR (Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))) '
			END
		ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
			BEGIN
				SET @SQL_WHERE += ' (--(Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) AND 
										 (Bi.KTypeId2 IN (SELECT * FROM #KType2) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))) '
			END
		ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
			BEGIN
				SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) --AND (Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))
					) '
			END
		ELSE
			BEGIN
				SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) AND (Bi.KTypeId2 IN (SELECT * FROM #KType2) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))) '
			END
		SET @SQL_WHERE += ' )'
	END
ELSE
	BEGIN
		IF @OtherType NOT IN (4,141,143,66,145,147,115,116,128,129,36,158,93,77,84,85,78,5,10,148,149,150,151,159,171,179,186,189,190,195,200,192,205,206,181,212,213,214)
			BEGIN
				SET @SQL_WHERE += ' AND ('
				--分支机构调拨出入库单，需要和同价调拨单处理成一样,加了类型187,188
				IF @OtherType NOT IN (16,17,21,160,161,166,172,173,174,175,187,188)
					BEGIN
						IF RTRIM(@KTypeName)<>''
							 
							SET @SQL_WHERE += ' (Bi.KTypeId IN (SELECT * FROM #KType))'
						ELSE
							BEGIN
								IF @MKTypeId = '00000'
									SET @SQL_WHERE += ' 1=1 '
								ELSE
									BEGIN
										--IF @OtherType = 188
										--	SET @SQL_WHERE += ' (Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId='''' OR Bi.KTypeId=''10000'')'
										--ELSE
										SET @SQL_WHERE += ' (Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId='''' OR Bi.KTypeId=''10000'')'
									END
							END
					END
				--分支机构调拨出入库单，需要和同价调拨单处理成一样,加了类型187,188
				ELSE IF @OtherType IN (17,21,187,188)
					BEGIN
						IF EXISTS(SELECT Value FROM userconfig WHERE ConfigName ='MoveInOutKLimit' AND Value='1')
							BEGIN
								IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
									BEGIN
										SET @SQL_WHERE += ' Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId) '
									END
								ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
									BEGIN
										SET @SQL_WHERE += ' Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bi.KTypeId2 IN (SELECT * FROM #KType2) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId) '
									END
								ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
									BEGIN
										SET @SQL_WHERE += ' Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId) '
									END
								ELSE
									BEGIN
										SET @SQL_WHERE += ' Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bi.KTypeId2 IN (SELECT * FROM #KType2) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId) '
									END
							END
						ELSE
							BEGIN
								IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
									BEGIN
										SET @SQL_WHERE += ' (Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) '
									END
								ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
									BEGIN
										SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND Bi.KTypeId2 IN (SELECT * FROM #KType2)) '
									END
								ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
									BEGIN
										SET @SQL_WHERE += ' (Bi.KTypeId IN (SELECT * FROM #KType) AND (Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))) '
									END
								ELSE
									BEGIN
										SET @SQL_WHERE += ' ( ( Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId2 IN (SELECT * FROM #KType2) ) AND (Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))) '
									END
							END
					END
				ELSE IF @OtherType IN (166,172)
					BEGIN
						IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE +=' (Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))'
								SET @SQL_WHERE +=' OR (Bi.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bi.KTypeId2='''')'
								SET @SQL_WHERE +=' OR (Bi.KTypeId='''' AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))'
								SET @SQL_WHERE +=' OR (Bi.KTypeId='''' AND Bi.KTypeId2='''')'
							END
						ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId='''' OR Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) AND (Bi.KTypeId2 IN (SELECT * FROM #KType2) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)))'
							END
						ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) AND (Bi.KTypeId2='''' OR Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)))'
							END
						ELSE
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) AND (Bi.KTypeId2 IN (SELECT * FROM #KType2) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)))'
							END
					END
				ELSE IF @OtherType = 160
					BEGIN
						IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) OR (Bi.KTypeId IN (SELECT * FROM #GetManKTypeId))) '
							END
						ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND (Bi.KTypeId IN (SELECT * FROM #KType2) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId))) '
							END
						ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId2 IN (SELECT * FROM #KType) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND (Bi.KTypeId IN (SELECT * FROM #GetManKTypeId))) '
							END
						ELSE
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId2 IN (SELECT * FROM #KType) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND (Bi.KTypeId IN (SELECT * FROM #KType2) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId))) '
							END
					END
				ELSE
					BEGIN
						IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) OR (Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))) '
							END
						ELSE IF RTRIM(@KTypeName)='' AND RTRIM(@KTypeName2)<>''
							BEGIN
								SET @SQL_WHERE += ' (--(Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) AND 
														 (Bi.KTypeId2 IN (SELECT * FROM #KType2) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))) '
							END
						ELSE IF RTRIM(@KTypeName)<>'' AND RTRIM(@KTypeName2)=''
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) --AND (Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))
									) '
							END
						ELSE
							BEGIN
								SET @SQL_WHERE += ' ((Bi.KTypeId IN (SELECT * FROM #KType) AND Bi.KTypeId IN (SELECT * FROM #GetManKTypeId)) AND (Bi.KTypeId2 IN (SELECT * FROM #KType2) AND Bi.KTypeId2 IN (SELECT * FROM #GetManKTypeId))) '
							END
					END
				SET @SQL_WHERE += ' )'
			END
	END

-- 单据明细摘要查询 
IF RTRIM(@ZYDetail)<>''
	BEGIN          
		-- 建立包含一个BillNumberID字段的临时表
		CREATE TABLE #commentTable(billnumberid INT)	
		DECLARE @TempTableSQL varchar(2000)
        
        SELECT @TempTableSQL=' INSERT INTO #commentTable
							   SELECT DISTINCT billnumberid FROM FactInOut WHERE COMMENT LIKE ''%'+@ZYDetail+'%'' 
							   UNION ALL
							   SELECT DISTINCT billnumberid FROM FactDepotInOut WHERE COMMENT LIKE ''%'+@ZYDetail+'%'' 
							   ' 
        
        EXEC(@TempTableSQL)
		SELECT @SQL_WHERE += ' AND bi.[BillNumberID] in ( SELECT billnumberid FROM #commentTable) '
	END 
-- 打印记录
CREATE TABLE #PrintCount(printcount INT, billnumberid NUMERIC(10,0),billtype NUMERIC(10,0))
INSERT INTO #PrintCount(printcount,billnumberid,billtype)
SELECT	SUM(PrintCount) printcount,billnumberid,BillType 
FROM	PrintRecord
WHERE	billtype not in (300,301)
GROUP BY billnumberid,BillType
  
CREATE CLUSTERED INDEX  cix_printcount on  #PrintCount(billnumberid)   

--优化，分页前只提取billnumberid，分页后再提取数据
CREATE TABLE #temp1
(
	BillnumberID 	numeric(10,0),
	Billdate 		datetime,
	BillCode 		varchar(200),
	Comment 		varchar(256),	
	Explain			varchar(256),
	DTypeId1		varchar(256), 
	TotalQty 		 NUMERIC(24, 10) , 
	redword 		int, 
	BillType 		INT,
	BillTypeName    VARCHAR(100),
	Frombilltype 		INT,
	OtherTypeName   VARCHAR(100),
	Etype 			varchar(100), 
	stype 			varchar(100), 
	KTypeId			VARCHAR(100),
	KTypeId1		VARCHAR(100),
	KTypeId2		VARCHAR(100),
	PrintCount		INT,				--打印记录
	CheckTime		DATETIME,			--制单时间
	UpdateEfullname	VARCHAR(200),		--修改人
    LastUpdateTime	DATETIME,			--修改时间   
	dealbtypeid           VARCHAR(100),      --结算单位 
	checke VARCHAR(100),--制单人
	redreason		VARCHAR(500),    
    sid numeric(10,0) IDENTITY (1, 1) NOT NULL
)

--处理排序
--处理排序
DECLARE @orderyWhere VARCHAR(1000)   =''
IF  CHARINDEX('stype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN Stype or_st ON bi.stype=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'stype_','or_st.') 
END
IF  CHARINDEX('dtypeid1',@OrderBy)>0
BEGIN
	SET @orderyWhere='	LEFT JOIN Department or_de ON bi.dtypeid1=or_de.typeID '
	SET @OrderBy= REPLACE(@OrderBy,'dtypeid1_','or_de.') 
END
IF  CHARINDEX('etype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN employee or_em ON bi.etype=or_em.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'etype_','or_em.') 
END
IF  CHARINDEX('btype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN btype or_bt ON bi.btype=or_bt.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'btype_','or_bt.') 
END
IF  CHARINDEX('dealbtypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN btype or_bt1 ON bi.dealbtypeid=or_bt1.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'dealbtypeid_','or_bt1.') 
END
IF  CHARINDEX('atype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN ac_items or_at ON bi.atype=or_at.nid  '
	SET @OrderBy= REPLACE(@OrderBy,'atype_','or_at.') 
END
  
SELECT @SQL_LIST = 'SELECT '

SELECT @SQL_LIST = @SQL_LIST+'
								Bi.BillnumberID,
								bi.billdate, 
								bi.BillCode,
								bi.Comment,
								Bi.Explain,
								bi.DTypeId AS dtypeid1, 
								Convert( NUMERIC(24, 10) ,case when bi.billtype=57 THEN 0   WHEN bi.redword=2 then -bi.TotalQty else bi.TotalQty end) as TotalQty, 
								bi.redword, 
								bi.billtype,
								bn.billname as billtypename,
								bi.Frombilltype,
								bn1.billname as othertypename,
								ISNULL(bi.etypeid,'''') AS etype, 
								ISNULL(bi.stypeid,'''') AS stype, 
								CASE
									WHEN Bi.BillType = 188 THEN Bi.KTypeId2
									ELSE Bi.KTypeId
								END AS KTypeId,
								CASE
									WHEN Bi.BillType = 160 THEN Bi.KTypeId2
									ELSE Bi.ktypeid 
								END AS KTypeId1,
								CASE
									WHEN Bi.BillType = 160 THEN Bi.KTypeId
									ELSE Bi.KTypeId2
								END AS KTypeId2,
								ISNULL(pCount.printcount,''0'') AS PrintCount,
								bi.checktime,
								e1.fullname as updateefullname,
								bi.lastupdatetime,    
								ISNULL(bi.dealbtypeid ,'''') AS dealbtypeid,      
								checkeName=E.FULLNAME,
								bi.redreason
						'
            
-- 基本列表的SQL
SELECT @SQL_FROM='	FROM FactIndex bi '
					 

SELECT @SQL_FROM += ' 
					LEFT JOIN #PrintCount pCount ON (bi.BillNumberId = pCount.billnumberid and bi.billtype=pcount.billtype) '
SELECT @SQL_FROM += ' 
                    left join billname bn on bi.billtype=bn.billtype
                    left join billname bn1 on bi.Frombilltype=bn1.billtype  
					LEFT JOIN employee E1 ON bi.updatee=e1.typeid  
					INNER JOIN Employee E ON E.TypeId = BI.checke
					 INNER JOIN #Employee EL ON EL.TYPEID = bi.etypeid
					   '
 
-- 排序
SELECT @SQL = @SQL_LIST + @SQL_FROM + @SQL_WHERE

-- 求总记录数的语句
DECLARE @RowCount int

SELECT @SQL_SUM  = 'SELECT  
						isnull(SUM(isnull(case when bi.billtype=57 then 0 when bi.redword=2 then -bi.TotalQty else bi.TotalQty end,0)),0) as TotalQty
					 '+@SQL_FROM + @SQL_WHERE
	

DECLARE @PageNum int
DECLARE @PageBegin int
DECLARE @PageEnd int
SET @PageNum =@PageNo *@UserDeRowCount

SET @PageBegin=(@PageNo-1)*@UserDeRowCount+1
SET @PageEnd=(@PageNo)*@UserDeRowCount

IF @OrderBy<>''
BEGIN
	SET @OrderBy=' ORDER BY ' +@OrderBy
END
ELSE
BEGIN
	SET @OrderBy=' ORDER BY bi.billdate desc,BI.billcode desc'
END

--PRINT @SQL	
SET @SQL ='	INSERT INTO #temp1  SELECT  bi.* FROM ('+@SQL +') bi      '+@orderyWhere+@OrderBy
--PRINT(@SQL_ORDER)
--SELECT * FROM #GetManKTypeId
--SELECT @SQL
EXEC(@SQL)
--SELECT * FROM #temp1
SET @RowCount = @@ROWCOUNT
	
IF @PageNo <>0
BEGIN
		IF @chrFlag='3'  -- 算合计
			BEGIN	
				--PRINT @SQL_SUM
				EXEC (@SQL_SUM)
				RETURN
			END
		ELSE
			BEGIN
				SET @SQL = 'select a.*
							into ##ORDERTABLE
							From  (SELECT 	A.*,SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head,
				
				
				'+Convert(varchar(100),@RowCount)+' as TotalNum
											FROM 	#temp1 a  
											 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
									)a inner join factindex bi on a.billnumberid=bi.billnumberid 
										WHERE 	A.sid>='+convert(varchar(10),@PageBegin) +'
													AND A.sid<='+convert(varchar(10),@PageEnd)+'
									ORDER BY A.sid'
				--PRINT @SQL	
			
				EXEC (@SQL)	
			END
	END
ELSE
	BEGIN	 
		SET @SQL = 'select a.*
					 
						FROM (	SELECT 	a.*,SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head,
				'+Convert(varchar(100),@RowCount)+' as TotalNum
								FROM 	#temp1 a  
								 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.Frombilltype=csindex.billtype
								) A INNER JOIN factindex BI ON A.BILLNUMBERID=BI.BILLNUMBERID '
		--PRINT @SQL  	
		
		 
		EXEC (@SQL)	
		
	END
-- 单据明细摘要查询
-- SELECT * FROM ##ORDERTABLE 
EXEC('SELECT * FROM ##ORDERTABLE  DROP TABLE ##ORDERTABLE')

-- ========================================= 删除临时表
IF RTRIM(@ZYDetail)<>'' 
	BEGIN
		drop table #commentTable
	END

DROP TABLE #temp1 
IF RTRIM(@KtypeName)<>''
	DROP TABLE #KType

IF RTRIM(@KtypeName2)<>''
	DROP TABLE #KType2
	
IF NOT (@stypeid='' AND @MStypeid = '00000')
	DROP TABLE #Stype	

DROP TABLE #GetManKTypeId,#Employee,#PrintCount

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
  SELECT 
	* 
  FROM dbo.sysobjects 
  WHERE id = OBJECT_ID(N'[dbo].[Gp_QueryFactStocks_Detail]') 
    AND OBJECTPROPERTY(id, N'IsProcedure') = 1
  )
	DROP procedure [dbo].[Gp_QueryFactStocks_Detail]
GO

CREATE PROCEDURE Gp_QueryFactStocks_Detail
( 
	@startdate		VARCHAR(25),
	@EndDate		VARCHAR(25),
	@typeId			VARCHAR(max),
	@BtypeId		VARCHAR(8000),
	@KtypeId		VARCHAR(8000),
	@eTypeId		VARCHAR(8000),
	@OperatorId     VARCHAR(100),			--操作员ID
	@stypeid		VARCHAR(8000),	--分支机构
	@isshowstop     int=0                --是否显示停用 0显示停用，1为不显示。
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

DECLARE @showRedWord CHAR(1)='0'
DECLARE @showstockstop INT=0
DECLARE @ptypeCategoryid VARCHAR(max)=''
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE 
  @Re INT,
  @MAtypeid	  VARCHAR(50), 
  @MBtypeid	  VARCHAR(50), 
  @MBtypeid2  VARCHAR(50), 
  @MEtypeid	  VARCHAR(50),
  @MKtypeid	  VARCHAR(50), 
  @MPtypeid	  VARCHAR(50), 
  @MExpense	  VARCHAR(50), 
  @MIncome	  VARCHAR(50),
  @MCapital	  VARCHAR(50),
  @MDtypeid	  VARCHAR(50),
  @MStypeid	  VARCHAR(50)

EXEC @Re = GP_CheckOperatorRight23_Rep 
			@OperatorID, 
			@MAtypeid OUTPUT,
			@MBtypeid OUTPUT,
			@MBtypeid2 OUTPUT,
			@MEtypeid OUTPUT,
			@MKtypeid OUTPUT,
			@MPtypeid OUTPUT,
			@MExpense OUTPUT,
			@MIncome OUTPUT,
			@MCapital OUTPUT,
			@MDtypeid OUTPUT,
			@MStypeid OUTPUT
IF @Re <> 0 
  RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
-- 选择分支机构
CREATE TABLE #GetSelectSTypeId
(
  TypeId varchar(100)
)
INSERT INTO #GetSelectSTypeId(TypeId) 
  SELECT typeid 
  FROM F_GetAllManagerBaseTypeId(@stypeid, 11, @OperatorID)


CREATE TABLE #GetSelETypeId
(
  TypeId VARCHAR(100)
)
INSERT  INTO #GetSelETypeId
        ( TypeId
        )
        SELECT  TypeId
        FROM    F_GetAllBaseTypeId(@eTypeId, 3)
  
--****************

--筛选仓库
CREATE TABLE #GetSelKTypeId
(
  TypeId varchar(100)
)
  IF @showstockstop = 0 
  INSERT  INTO #GetSelKTypeId
            ( TypeId
            )
    SELECT  typeid
    FROM    F_GetAllManagerBaseTypeId(@KtypeId, 4, @OperatorID)
  ELSE 
    INSERT  INTO #GetSelKTypeId
            ( TypeId
            )
            SELECT  a.typeid
            FROM    F_GetAllManagerBaseTypeId(@KtypeId, 4, @OperatorID) a
                    INNER JOIN dbo.Stock b ON a.TypeId = b.typeId
            WHERE   b.deleted = 0
DELETE FROM #GetSelKTypeId --删除不在权限范围内的分支机构下的仓库
  WHERE TypeId NOT IN( SELECT TypeId FROM STOCK WHERE STypeID IN (SELECT TypeId FROM #GetSelectSTypeId))
  
---筛选往来单位
CREATE TABLE #GetBtype(Typeid NVARCHAR(200))
INSERT INTO #GetBtype(typeid)
SELECT TypeId FROM dbo.F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorId)


---筛选商品
CREATE TABLE #GetManPType
(
  TypeId VARCHAR(100)
)
INSERT INTO #GetManPType(TypeId) 
  SELECT typeid 
  FROM dbo.F_ManPTypeInCategoryID(@OperatorId,@typeId,@ptypeCategoryid) 
CREATE CLUSTERED INDEX IX_GetManPType_TypeID ON #GetManPType(TypeID)

DECLARE @strQuery VARCHAR(1000)
SELECT @strQuery=''

-- 根据经手人过滤 Add by Haiyang, Li 2012-03-27
--****************
IF @OperatorId <> ''
	BEGIN
		--超级管理员(Admin)为不限经手人查询
	    SELECT @strQuery = ''
	END
--****************

DECLARE @Sql VARCHAR (max)

SELECT @SQL='
SELECT DISTINCT 	c.BillNumberId,
		c.ID AS CustomdetailID,
		c.BillDate,
		c.billtype,
		c.ktypeid,
		c.ptypeid,
	    c.qty,
		CASE WHEN   ISNULL(a.dealbtypeid,'''') ='''' or a.dealbtypeid IN (select * from #GetBtype) THEN ISNULL(a.dealbtypeid,'''') ELSE ''****'' END btypeid,
		CASE WHEN   ISNULL(a.dealbtypeid,'''') ='''' or a.dealbtypeid IN (select * from #GetBtype) THEN ISNULL(a.dealbtypeid,'''') ELSE ''****'' END comment, 				
		c.EtypeId,
		c.posttime,
		c.cargoid,
		c.iscombined,
		c.itemid,
		c.nqty,
		c.goodsnumber 
		,p1.fullname
		,p1.baseUnitId
FROM Fact_InOutstocktable c  
INNER JOIN FactIndex a ON c.BillNumberId = a.BillNumberId  
INNER JOIN ptype p1 on  c.ptypeid=p1.typeid 
INNER JOIN #GetManPType on c.ptypeid = #GetManPType.typeid 
	'

IF NOT(RTRIM(@ktypeid) ='0' AND @MKtypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetSelKTypeId sk ON sk.typeid = c.ktypeid ' 	

SET @SQL = @SQL +' WHERE c.BillNumBerId<>0 and a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
					AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'  and a.ifcheck=''t'''

IF @showRedWord = '0'
	SELECT @SQL = @SQL + ' and a.redword =0  '				
IF @isshowstop=1
	SET @SQL = @SQL + ' and p1.deleted=0  '	
	
CREATE TABLE #FromBillType
(
    BillNumberId INT,
    FromBillType VARCHAR(200)
)
INSERT INTO #FromBillType
( 
	BillNumberId, 
	FromBillType 
)
SELECT	BillNumberId,
		FromBillType
FROM
(
    SELECT	f.BillNumberId,
			b.BillName AS FromBillType
    FROM FactIndex f
    LEFT JOIN (SELECT Billtype,BillName FROM dbo.BillName) b ON b.Billtype = f.FromBillType
) A
 
IF RTRIM(@btypeid) <> '0' 
	SET @SQL = @SQL + ' AND LEFT(a.dealbtypeid,len(' + CHAR(39) + @btypeid+CHAR(39) + ')) = ' + CHAR(39) + @btypeid + CHAR(39) + ' ' 
	
SELECT @Sql ='
			SELECT	DISTINCT   
					c.CustomdetailID,
					c.BillNumberId,
					c.BillDate as billdatefact,
					c.billtype as billtype,
					CASE WHEN a.billtype=418 AND ISNULL(c.qty,0)>=0 THEN ISNULL(c.qty,0)
						 WHEN a.billtype=420 AND ISNULL(c.qty,0)>=0 THEN ISNULL(c.qty,0)
					  end as frqty,
					CASE WHEN a.billtype=419 AND -ISNULL(c.qty,0)>=0 THEN abs(ISNULL(c.qty,0))
						 WHEN a.billtype=420 AND -ISNULL(c.qty,0)>=0 THEN abs(ISNULL(c.qty,0))
					  end as fcqty,
					a.BillCode as billcodefact, 
					f.FromBillType as inouttype,
					c.comment,
					a.RedWord, 
					CBillType= a.billtype,
					c. btypeid,
					a.etypeid,
					c.ktypeid,
					c.ptypeid,
					c.fullname,
					----------
					a.stypeid,
					c.posttime,
					----------
					c.cargoid,
					c.goodsnumber,
					v.fullname AS itemfullname,
					c.nqty,
					p.fullname AS munitfullname
			FROM 	FactIndex a
			INNER JOIN  #GetSelectSTypeId ss on a.stypeid=ss.typeid 
			inner join #GetSelETypeId ee on ee.typeid=a.etypeid
			INNER JOIN	('+@sql+') c on	c.BillNumberId = a.BillNumberId
			left JOIN  vWeb_ItemIDByIsCombined v on c.iscombined = v.iscombined AND c.itemid = v.id
			left JOIN  PType_Units p on p.UnitsId = c.baseUnitId
			left JOIN  ptype_units_ext pe on pe.ptypeid = c.ptypeid
			left JOIN  #FromBillType f on f.BillNumberId=a.BillNumberID
			UNION ALL
			SELECT	DISTINCT   
					c.CustomdetailID,
					c.BillNumberId,
					c.BillDate as billdatefact,
					c.billtype as billtype,
					CASE WHEN a.billtype=418 AND ISNULL(c.qty,0)>=0 THEN ISNULL(c.qty,0)
						 WHEN a.billtype=420 AND ISNULL(c.qty,0)>=0 THEN ISNULL(c.qty,0)
					  end as frqty,
					CASE WHEN a.billtype=419 AND -ISNULL(c.qty,0)>=0 THEN abs(ISNULL(c.qty,0))
						 WHEN a.billtype=420 AND -ISNULL(c.qty,0)>=0 THEN abs(ISNULL(c.qty,0))
					  end as fcqty,
					a.BillCode as billcodefact, 
					f.FromBillType as inouttype,
					c.comment,
					a.RedWord, 
					CBillType= a.billtype,
					c. btypeid,
					a.etypeid,
					c.ktypeid,
					c.ptypeid,
					c.fullname,
					----------
					a.stypeid,
					c.posttime,
					----------
					c.cargoid,
					c.goodsnumber,
					v.fullname AS itemfullname,
					c.nqty,
					p.fullname AS munitfullname
			FROM 	FactIndex a
			INNER JOIN  #GetSelectSTypeId ss on a.stypeid=ss.typeid 
			inner join #GetSelETypeId ee on ee.typeid=a.etypeid
			INNER JOIN	('+@sql+') c on	c.BillNumberId = a.BillNumberId
			left JOIN  vWeb_ItemIDByIsCombined v on c.iscombined = v.iscombined AND c.itemid = v.id
			left JOIN  PType_Units p on p.UnitsId = c.baseUnitId
			left JOIN  ptype_units_ext pe on pe.ptypeid = c.ptypeid
			left JOIN  #FromBillType f on f.BillNumberId=a.BillNumberID	
			WHERE	a.BillType IN (327,328,329)		
			 '
					
DECLARE @SQLOrder	VARCHAR(150)
SELECT @SQLOrder = ''					

DECLARE @qty NUMERIC(24,10)

CREATE TABLE #Qty(qty NUMERIC(24,10),
Total         NUMERIC(24,10)
)

insert #Qty 
exec Gp_GetPreDateQtyOrTotal 
		@OperatorID,
		@StartDate,	
		@typeId,	
		@KTypeId,	
		@etypeid,	
		@stypeid	
		
SELECT @qty=ISNULL(qty,0) FROM #Qty
		
SET @SQL ='SELECT *  INTO #Result FROM (' + @SQL +') AS A ' + @SQLOrder 
	+' 
				
			  	SELECT a.* '					
			SET @SQL +='
					  FROM #Result a 
					 
				DROP TABLE #Result
			   '

--print @sql
EXEC (@SQL)
	
----------------------------------------------------------
DROP TABLE #GetSelKTypeId, #GetSelectSTypeId, #GetManPType,#GetBtype,#GetSelETypeId,#FromBillType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtypefact=csindex.billtype
--left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtypefact=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid	' + @SQLOrder +'
--customassist= dbo.F_GetCustomAssist(a.ptypeid,ljcalCustomQty)
--+convert(nvarchar(100),@qty)+'+ISNULL(frqty,0) - ISNULL(fcqty,0) AS tex,'
--declare @iqty numeric(24,10) = '+ cast(@qty as varchar(50))+'
--update #Result set @iqty = @iqty+ISNULL(frqty,0) - ISNULL(fcqty,0),  ljcalCustomQty=@iqty
--CAST(0 AS NUMERIC(24,10)) AS ljcalCustomQty
--DECLARE @tmpSQL NVARCHAR(3000)
--SET @tmpSQL='dbo.F_GetCustomAssist(a.ptypeid,'+convert(nvarchar(100),@qty)+'+rqty-cqty)'	



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryFactStocksSerialBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryFactStocksSerialBill]
GO

/*
	作者：谢吉康
	日期：2016-06-07
	描述：实物库存序列号跟踪
*/
CREATE               PROCEDURE Gp_QueryFactStocksSerialBill
( 
	@OperatorId		VARCHAR(100),
	@Serial    		VARCHAR(50),
	@querytype   	INT,  			--是否模糊查找  1.是  0.精确查找
	@ETypeId		VARCHAR(MAX) = '',
	@DTypeId		VARCHAR(MAX) = '',
	@STypeId		VARCHAR(MAX) = '',
	@dealbtypeid		VARCHAR(MAX) = '',
	@KTypeId		VARCHAR(MAX) = '',
	@PTypeId		VARCHAR(MAX) = ''
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
create table #temp
(
	sid				int identity(1,1),
	checke			VARCHAR(200),
	ID				INT,
	billnumberID	NUMERIC(10,0),
	BillDate		DATETIME,
	BillCode		VARCHAR(100),
	BillType		INT,
	Comment			VARCHAR(500),
	Explain			VARCHAR(500),
	RedWord			INT,
	EtypeId			VARCHAR(50),
	StypeId			VARCHAR(50),
	KtypeId			VARCHAR(50),
	dealbtypeid		VARCHAR(50),
	PtypeId			VARCHAR(50)
)
IF ISNULL(@Serial,'')='' --没有录入序列号条件，则返回空表结构
BEGIN
	SELECT * FROM #temp
	RETURN
END 
	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT a.TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorId) a INNER JOIN dbo.ptype b ON a.TypeId=b.typeId WHERE b.IsService=0

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorId)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorId)
IF @KTypeId = ''
BEGIN
	INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')
	INSERT INTO #GetManKTypeId(TypeId)VALUES('')
END

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

CREATE CLUSTERED INDEX CIX_BID ON #GetManETypeId(typeid)	
CREATE CLUSTERED INDEX CIX_BID ON #GetManPTypeId(typeid)	
CREATE CLUSTERED INDEX CIX_BID ON #GetManKTypeId(typeid)	
CREATE CLUSTERED INDEX CIX_BID ON #GetManSTypeId(typeid)	
CREATE CLUSTERED INDEX CIX_BID ON #GetManDTypeId(typeid)	

DECLARE @SQL VARCHAR(8000)
--自定义行数
DECLARE @uCount int
SELECT @uCount = ISNULL(UserDeRowCount,0) FROM LoginUser WHERE ETypeId = @OperatorId
IF @uCount = 0 SET @uCount = 14


SET @SQL = '
		SELECT 	a.*,
				SysDiy1_head,
				SysDiy2_head,
				SysDiy3_head,
				SysDiy4_head, 
				SysDiy5_head,
				SysDiy6_head,
				SysDiy7_head,
				SysDiy8_head,
				SysDiy9_head,
				SysDiy10_head,
				SysDiy11_head,
				SysDiy12_head,
				SysDiy13_head,
				SysDiy14_head,
				SysDiy15_head,
				SysDiy16_head  
		FROM (
				SELECT	DISTINCT
						bi.checke,  					
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						bi.BillType,
						bi.Comment,
						bi.explain,
						Bi.RedWord,
						bi.etypeid,
						bi.stypeid,
						CASE WHEN bi.BillType = 418 THEN InOut.InKtypeId 
							 WHEN bi.BillType = 420 and InOut.InKtypeId is null  THEN InOut.OutKTyeId 
							 WHEN bi.BillType = 420 and InOut.OutKTyeId is null  THEN InOut.InKtypeId 
						ELSE InOut.OutKTyeId END AS KTypeId,						
						inout.PtypeId
				FROM 	FactIndex Bi
				INNER JOIN Fact_InoutPtypeSerial InOut ON InOut.BillNumberId = Bi.BillNumberId
				INNER JOIN #GetManPTypeId P ON P.TypeId = InOut.PtypeID
				INNER JOIN #GetManDTypeId D ON D.TypeId = Bi.DTypeId
				INNER JOIN #GetManSTypeId S ON S.TypeId = Bi.STypeId
				INNER JOIN #GetManETypeId E ON E.TypeId = Bi.ETypeId				
				WHERE   Bi.IfCheck = ''t''
						AND InOut.BillType=Bi.BillType
						AND Bi.RedWord = 0
						AND Bi.BillType NOT IN (71,72,87,88,203) '
						
IF NOT (@KTypeId = '' AND @MKtypeid = '00000')
	SET @SQL = @SQL + ' AND (InOut.InKTypeId IN (SELECT * FROM #GetManKTypeId) OR InOut.OutKTyeId IN (SELECT * FROM #GetManKTypeId)) '


IF @querytype = '1'
				SET @SQL = @SQL + ' AND InOut.Serial LIKE ''%' + @Serial + '%'''
			ELSE
				SET @SQL = @SQL + ' AND InOut.Serial =''' + @Serial + ''''

				
set @SQL=@SQL+'	
		) a 
		LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
		
		 ORDER BY a.BillDate'
			
PRINT(@SQL)
EXEC(@sql)

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryGiveFromSaleOrBuy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryGiveFromSaleOrBuy]
GO















/*
	作者：谢吉康
	日期：2003-12-12
	描述：查询赠送获赠与采购和销售的关联单据
*/
CREATE    PROCEDURE GP_QueryGiveFromSaleOrBuy
(
	@OperatorID		VARCHAR(50),	--操作员ID
	@StartDate		VARCHAR(20),	--开始时间
	@EndDate		VARCHAR(20),	--结束时间
	@STypeId		VARCHAR(max)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetManDetailBType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetManDetailDType(@OperatorID)

SELECT 	Bil.BillNumberID,
		Bil.BillDate,
		Bil.BillType,
		Bil.ETypeID,
		Bil.DTypeId,
		bil.DealBTypeID
INTO 	#BillIndex
FROM 	BillIndex Bil
WHERE  	Bil.ifCheck = 't'
		AND Bil.RedWord = 0		
		AND Bil.ifYearBill='0'			--年节存标志
SELECT	A.BillType,
		Count(A.BillType) AS BillCount
FROM 	#BillIndex A 
		INNER JOIN GiveFromSaleOrBuy B  ON A.BillNumberID=B.SourceBillNumberId
		INNER JOIN #GetManETypeId e ON e.TypeId=A.ETypeID
		INNER JOIN #GetManDTypeId d ON d.TypeId=A.DTypeID
		INNER JOIN #GetManBTypeId mb ON A.DealBTypeID=mb.TypeId
		INNER JOIN #GetManKTypeId k ON B.KTypeID=k.TypeId
WHERE 	A.BillDate>=@StartDate
		AND DestBillNumberID in (SELECT BillNumberID FROM #BillIndex)
		AND A.BillDate<=@EndDate
		AND A.BillType IN (11,34)
		AND B.ifcheck='t'			
GROUP BY A.BillType

DROP TABLE #BillIndex,#GetManETypeId,#GetManBTypeId,#GetManKTypeId









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryGiveFromSaleOrBuyDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryGiveFromSaleOrBuyDetail]
GO


/*
	作者：谢吉康
	日期：2003-12-12
	描述：查询赠送获赠与采购和销售的关联单据[明细]
	
	作者：徐辉
	日期：2011-04-02
	描述：权限调整
	
	【修改】：鲁大林
	日期：2012-07-09
	描述：添加往来单位
*/
CREATE       PROCEDURE Gp_QueryGiveFromSaleOrBuyDetail
(
	@OperatorID			VARCHAR(100),	--操作员ID
	@StartDate			VARCHAR(20),	--开始时间
	@EndDate			VARCHAR(20),	--结束时间
	@BTypeID			VARCHAR(8000),	--往来单位
	@JTypeID			VARCHAR(8000),	--往来单位
	@ETypeID			VARCHAR(8000),	--职员ID
	@KTypeID			VARCHAR(8000),	--仓库ID
	@BillType			VARCHAR(20),	--单据类型
	@BillCode			VARCHAR(200),	--单据编号  -- #&**&#
	@Comment			VARCHAR(300),	--备注
	@SortField			VARCHAR(50),	--排序字段
	@SortType			VARCHAR(10),	--排序方式
	@QueryType 			VARCHAR(10),	--查询方式   CX=查赠送获赠单 ZH=查采购销售单
	@xjkBillNumberID    VARCHAR(10),	--单据编号
	@STypeId			VARCHAR(max),	--分支机构
	@DTypeId			VARCHAR(max),	--部门id
	@IsReporting		INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL VARCHAR(8000)
SELECT  @SQL = ''

IF @QueryType='CX'
	BEGIN
		IF @BillType<>''
			IF @BillType = '34'
				SELECT @BillType = '126'
			ELSE
				SELECT @BillType = '139'
				
	END
ELSE
	BEGIN
		IF @BillType<>''
			IF @BillType = '126'
				SELECT @BillType = '34'
			ELSE
				SELECT @BillType = '11,12'
	
	END

DECLARE @BTypeAll INT
SELECT TOP 1 @BTypeAll = value FROM UserConfig WHERE ConfigName = 'BTypeAll'
DECLARE @BTypeId_t VARCHAR(8000),@JTypeId_t VARCHAR(8000)
SELECT  @BTypeId_t=@BTypeId,@JTypeId_t=@JTypeId

IF @BTypeId=''
	SET @BTypeId='00001'
IF @JTypeId=''
	SET @JTypeId='00002'
	
--SELECT *FROM BTYPE

CREATE TABLE #GetSelBTypeId(TypeId varchar(100))
INSERT INTO  #GetSelBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

CREATE TABLE #GetSelJTypeId(TypeId varchar(100))
INSERT INTO  #GetSelJTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@JTypeId,2,@OperatorID)


CREATE TABLE #GetSelETypeId(TypeId varchar(100))
INSERT INTO  #GetSelETypeId(TypeId) SELECT se.TypeId FROM F_GetAllBaseTypeId(@ETypeId,3) se INNER JOIN F_GetManDetailEType(@OperatorID) e ON se.TypeId = e.TypeId

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

CREATE TABLE #GetSelKTypeId(TypeId varchar(100))
INSERT INTO  #GetSelKTypeId(TypeId) SELECT sk.TypeId FROM F_GetAllBaseTypeId(@KTypeId,4) sk INNER JOIN F_GetManDetailKType(@OperatorID) k ON sk.TypeId=k.TypeId
--删除仓库中的对于STypeId
DELETE FROM #GetSelKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))	


CREATE TABLE #GetManBTypeId(TypeId varchar(100))
INSERT INTO  #GetManBTypeId(TypeId) SELECT typeid FROM  F_GetManDetailBType(@OperatorID)

IF @QueryType='CX'
BEGIN
	SELECT @SQL = '
		SELECT	DISTINCT
				A.BillNumberID,				
				A.BillDate,
				A.BillCode,
				A.BillType,
				A.Etypeid,
				A.Btypeid,
				A.DealBTypeID,--往来单位
				A.kTypeID,
				A.Comment,
				A.TotalQty,
				B.FullName AS BFullName,
				E.FullName AS EFullName,
				K.FullName AS KFullName,
				A.TotalMoney
		FROM 	BillIndex A,
				GiveFromSaleOrBuy G,
				Btype B,
				Employee e,
				stock k
		WHERE 	A.BillNumberID = G.DestBillNumberID 
				AND A.BTypeID = B.TypeID
				AND A.ETypeID = E.TypeID
				AND A.KTypeID = K.TypeID
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND G.ifcheck=''t''
				AND A.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
				AND A.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
				AND G.SourceBillNumberId IN (SELECT BillNumberID FROM BillIndex Where IfCheck = ''t'' AND RedWord = 0)'
		IF @BillType<>''				
			SELECT @SQL = @SQL + ' AND A.BillType  in (select a from dbo.f_split( '''+@BillType+''','','') )'
			
		IF @BillCode<>''							
			SELECT @SQL = @SQL + ' AND A.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
	    IF @Comment<>''	
			SELECT @SQL = @SQL + ' AND A.Comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)
		IF @BTypeId_t='' OR  @JTypeId_t=''
		SELECT @SQL = @SQL + ' AND ((A.dealBTypeID IN (SELECT * FROM #GetSelBTypeId) OR  A.dealBTypeID IN (SELECT * FROM #GetSelJTypeId)))'
		
		IF @BTypeId_t<>''
		SELECT @SQL = @SQL + ' AND A.dealBTypeID IN (SELECT * FROM #GetSelBTypeId) '
		
		IF @JTypeId_t<>''
		SELECT @SQL = @SQL + ' AND A.dealBTypeID IN (SELECT * FROM #GetSelJTypeId) '
		
		SELECT @SQL = @SQL + ' 
				AND A.ETypeID IN (SELECT * FROM #GetSelETypeId)
				AND A.KTypeID IN (SELECT * FROM #GetSelKTypeId)
				AND A.STypeId IN (SELECT * FROM #GetManSTypeId)
				AND A.DTypeId IN (SELECT * FROM #GetManDTypeId) '
				
		IF @xjkBillNumberID<>''		
			SELECT @SQL = @SQL + ' AND G.SourceBillNumberID LIKE '+CHAR(39)+@xjkBillNumberID+CHAR(39)
END
ELSE
BEGIN
	SELECT @SQL = '
		SELECT	DISTINCT
				A.BillNumberID,				
				A.BillDate,
				A.BillCode,
				A.BillType,
				A.Etypeid,
				A.Btypeid,
				A.DealBTypeID,--往来单位
				A.kTypeID,
				A.Comment,
				A.TotalQty,
				B.FullName AS BFullName,
				E.FullName AS EFullName,
				K.FullName AS KFullName,
				A.TotalMoney
		FROM 	BillIndex A,
				GiveFromSaleOrBuy G,
				BType B,
				Employee E,
				Stock K
		WHERE 	A.BillNumberID = G.SourceBillNumberID
				AND A.BTypeID = B.TypeID
				AND A.ETypeID = E.TypeID
				AND A.KTypeID = K.TypeID
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND G.ifcheck=''t''
				AND A.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
				AND A.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
				AND G.DestBillNumberID IN (SELECT BillNumberID FROM BillIndex Where IfCheck = ''t'' AND RedWord = 0)'
				
		IF @BillType<>''		
			SELECT @SQL = @SQL +' AND A.BillType in (select a from dbo.f_split( '''+@BillType+''','','') )'
			
		IF @BillCode<>''	
			SELECT @SQL = @SQL +' AND A.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
			
		IF @Comment<>''	
			SELECT @SQL = @SQL +' AND A.Comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)
			
		SELECT @SQL = @SQL + ' AND ((A.dealBTypeID IN (SELECT * FROM #GetSelBTypeId) OR A.dealBTypeID IN (SELECT * FROM #GetSelJTypeId)))'
	
		
		SELECT @SQL = @SQL +' 
				AND A.ETypeID IN (SELECT * FROM #GetSelETypeId)
				AND A.KTypeID IN (SELECT * FROM #GetSelKTypeId)
				AND A.STypeId IN (SELECT * FROM #GetManSTypeId)
				AND A.DTypeId IN (SELECT * FROM #GetManDTypeId) '
				
		IF @xjkBillNumberID<>''		
			SELECT @SQL = @SQL + ' AND G.SourceBillNumberID LIKE '+CHAR(39)+@xjkBillNumberID+CHAR(39)

		END	

--SELECT @SQL = @SQL + ' ORDER BY ' + @SortField + ' '+ @SortType

--PRINT(@SQL)
--EXEC(@SQL)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
IF(@IsReporting = 0)
BEGIN
	SELECT @SQL = @SQL + ' ORDER BY ' + @SortField + ' '+ @SortType
	--PRINT @SQL
	EXEC(@SQL)
END
ELSE IF(@IsReporting = 1)
BEGIN
	CREATE TABLE #tmp_result
	(
		billnumberid VARCHAR(100),
		billtype     VARCHAR(100),
		Costom1		VARCHAR(max),
		Costom2		VARCHAR(max),
		Costom3		VARCHAR(max),
		Costom4		VARCHAR(max),
		Costom5		VARCHAR(max),
		Costom6		VARCHAR(max),
		Costom7		VARCHAR(max),
		Costom8		VARCHAR(max),
		Costom9		VARCHAR(max),
		Costom10	VARCHAR(max),
		Costom11	VARCHAR(max),
		Costom12	VARCHAR(max),
		Costom13	VARCHAR(max),
		Costom14	VARCHAR(max),
		Costom15	VARCHAR(max),
		Costom16	VARCHAR(max)
	)

	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ORDER BY ' +  @SortField + ' '+ @SortType + 
			  '
			   DECLARE @p1 dbo.TBType_SelfType  
			   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
			   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 
			   
				--显示最终结果
				SELECT a.*,
						  b.Costom1,
						  b.Costom2,
						  b.Costom3,
						  b.Costom4,
						  b.Costom5,
						  b.Costom6,
						  b.Costom7,
						  b.Costom8,
						  b.Costom9,
						  b.Costom10,
						  b.Costom11,
						  b.Costom12,
						  b.Costom13,
						  b.Costom14,
						  b.Costom15,
						  b.Costom16 
						  FROM #temp1 a 
						  left join #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
						  
				DROP TABLE #temp1,#tmp_result
			   '
	--print @SQL
	EXEC (@SQL)
END
----------------------------------------------------------

DROP TABLE #GetSelBTypeId,#GetSelJTypeId,#GetSelETypeId,#GetSelKTypeId,#GetManSTypeId



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryGoodsLocal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryGoodsLocal]
GO















/*
	作者：谢吉康
	日期：2003-12-16
	描述：物流单据查询表
*/
CREATE       PROCEDURE GP_QueryGoodsLocal
(
	@OperatorID	VARCHAR(50),	--操作员ID
	@StartDate	VARCHAR(20),	--开始日期
	@EndDate 	VARCHAR(20),	--结束日期
	@BTypeID	VARCHAR(50),	--往来单位ID
	@ETypeID	VARCHAR(50),	--职员ID
	@KTypeID 	VARCHAR(50),	--仓库ID
	@BillCode	VARCHAR(200),	--单据编号
	@BillType	VARCHAR(10),	--单据类型
	@SortFild	VARCHAR(50),	--排序字段
	@SortType	VARCHAR(50),	--排序方式
	@JTypeID	VARCHAR(50)		--供应商ID
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL VARCHAR(8000)
SELECT  @SQL = ''

IF @BillType = '-1'
	SELECT @BillType = '%'

IF @BTypeID = '00000'
	SELECT @BTypeID = '%'

IF @JTypeID = '00000'
	SELECT @JTypeID = '%'

IF @KTypeID = '00000'
	SELECT @KTypeID = '%'


BEGIN
	SELECT @SQL = '
		SELECT 	DISTINCT
				A.BillNumberID,				
				A.BillDate,
				A.BillCode,
				A.BillType,
				E.FullName,
				A.TotalQty,
				A.TotalMoney,
				A.Comment,
				B.BillCode AS BBillCode,
				B.BillNumberID AS BID,
				B.EtypeID,
				B.BillDate,
				B.TotalQty
		FROM 	BillIndex A,
				LocalIndex B,
				Employee E,
				LocalDetail D
		WHERE 	A.BillNumberID = B.BID
				AND B.BillNumberID = D.BillNumberID
				AND E.TypeID = A.ETypeID
				AND A.IfCheck = ''t''
				AND A.Draft = 0
				AND A.RedWord = 0
				AND B.IfCheck = ''t''
				AND B.Draft = 0
				AND B.RedWord = 0								
				AND E.Deleted = 0
				AND A.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
				AND A.BillDate <='+CHAR(39)+@EndDate+CHAR(39)+'
				AND (A.BTypeID LIKE '+CHAR(39)+@BTypeID+'%'+CHAR(39)+' OR A.BTypeID LIKE '+CHAR(39)+@JTypeID+'%'+CHAR(39)+' OR A.BTypeID = '''')
				AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
				AND (A.KTypeID LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+' OR A.KTypeID2 LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+')
				AND A.BillType LIKE '+CHAR(39)+@BillType+CHAR(39)+'
				AND A.BillCode LIKE '+CHAR(39)+@BillCode+'%'+CHAR(39)

		SELECT @SQL = @SQL + ' 	AND (A.BTypeID LIKE '+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' OR A.BTypeID LIKE '+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+' OR A.BTypeID = '''')
								AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
								AND (A.KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+' OR A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+')
								AND D.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)

		SELECT @SQL = @SQL + ' ORDER BY '+ ' '+@SortFild+' ' + @SortType


	--PRINT(@SQL)
	EXEC(@SQL)
END















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryGoodsLocalBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryGoodsLocalBill]
GO














/*
	作者：谢吉康
	日期：2003-12-16
	描述：货位单据查询表
*/
CREATE       PROCEDURE GP_QueryGoodsLocalBill
(
	@OperatorID	VARCHAR(50),	--操作员ID
	@StartDate	VARCHAR(20),	--开始日期
	@EndDate 	VARCHAR(20),	--结束日期
	@BTypeID	VARCHAR(50),	--往来单位ID
	@ETypeID	VARCHAR(50),	--职员ID
	@KTypeID 	VARCHAR(50),	--仓库ID
	@BillCode	VARCHAR(200),	--单据编号
	@BillType	VARCHAR(10),	--单据类型
	@SortFild	VARCHAR(50),	--排序字段
	@SortType	VARCHAR(50),	--排序方式
	@JTypeID	VARCHAR(50)		--供应商ID
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL VARCHAR(8000)
SELECT  @SQL = ''

IF @BillType = '-1'
	SELECT @BillType = '%'

IF @BTypeID = '00000'
	SELECT @BTypeID = '%'

IF @JTypeID = '00000'
	SELECT @JTypeID = '%'


IF @KTypeID = '00000'
	SELECT @KTypeID = '%'


BEGIN
	SELECT @SQL = '
		SELECT 	B.BillNumberID,				
				B.BillDate,
				B.BillCode,
				B.BillType,
				E.FullName,
				B.TotalQty,
				B.Comment,
				B.BCode AS ABillCode,
				B.BID AS BID
		FROM 	LocalIndex B,
				Employee E
		WHERE 	E.TypeID = B.ETypeID
				AND B.IfCheck = ''t''
				AND B.Draft = 0
				AND B.RedWord = 0								
				AND E.Deleted = 0
				AND B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
				AND B.BillDate <='+CHAR(39)+@EndDate+CHAR(39)+'
				AND B.ETypeID1 LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
				AND (B.KTypeID LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+')
				AND B.BillType LIKE '+CHAR(39)+@BillType+CHAR(39)+'
				AND B.BillCode LIKE '+CHAR(39)+@BillCode+'%'+CHAR(39)

		SELECT @SQL = @SQL + ' 	AND (B.ETypeID1 LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+' OR B.ETypeID2 LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+')
								AND (B.KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+')'

		SELECT @SQL = @SQL + ' ORDER BY '+ ' '+@SortFild+' ' + @SortType


	--PRINT(@SQL)
	EXEC(@SQL)
END












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryGoodsLocalDistribute]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryGoodsLocalDistribute]
GO












/*
	作者：谢吉康
	日期：2003-12-17
	描述：货位分布状况表

	GP_QueryGoodsLocalDistribute '00001','00055','','',14,1,1
*/
CREATE     PROCEDURE GP_QueryGoodsLocalDistribute
(
	@OperatorID		VARCHAR(50),	--操作员ID
	@KTypeID		VARCHAR(50),	--仓库ID
	@UserCode		VARCHAR(50),	--商品编号
	@FullName 		VARCHAR(50),	--商品名称
	@PageSize 		INT,			--显示记录数
	@PPageNo		INT,			--商品的页数
	@LPageNo		INT				--仓库的页数
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @PSQL VARCHAR(8000)
DECLARE @KSQL VARCHAR(8000)

DECLARE @PTypeID  VARCHAR(50)
DECLARE @PUserCode VARCHAR(256)
DECLARE @PFullName VARCHAR(256)


DECLARE @LTypeID  VARCHAR(50)
DECLARE @LUserCode VARCHAR(256)
DECLARE @LFullName VARCHAR(256)

DECLARE @TableSql VARCHAR(8000)
DECLARE @TableName VARCHAR(50)
DECLARE @DropTableSql VARCHAR(8000)
DECLARE @InsertTableSQL VARCHAR(8000)
DECLARE @SelectTableSQL VARCHAR(8000)

DECLARE @AlterSQL	VARCHAR(8000)

DECLARE @TmpPTypeID VARCHAR(50)
DECLARE @Qty VARCHAR(50)

DECLARE @UpdateDataSQL	VARCHAR(8000)
DECLARE @UpdateTotalDataSQL	VARCHAR(8000)

DECLARE @LineTotal VARCHAR(100)
DECLARE @ColTotal VARCHAR(100)

DECLARE @UpdateGoodsLocalSQL VARCHAR(8000)

BEGIN
		--==========缩减LType基本表
		SELECT 	DISTINCT
				L.TypeID,
				L.KTypeID,
				L.Deleted,
				L.UserCode,
				L.FullName,
				L.SonNum
		INTO    #LType
		FROM 	GoodsLocal G,
				LType L,
				PType P
		WHERE   L.TypeID = G.LTypeID
				AND G.PTypeID = P.TypeID
				AND L.Deleted = 0
				AND L.KTypeID = @KTypeID
				AND P.UserCode LIKE '%'+@UserCode+'%'
				AND P.FullName LIKE '%'+@FullName+'%'
				AND G.QTY>0
		ORDER BY L.UserCode
	--==========缩减LType基本表


	--==========缩减PType基本表
		SELECT 	DISTINCT
				P.TypeID,
				P.UserCode,
				P.FullName,
				P.Deleted,
				P.SonNum
		INTO    #PType
		FROM 	GoodsLocal G,
				PType P,
				#LType L				
		WHERE   P.TypeID = G.PTypeID
				AND G.LTypeID = L.TypeID
				AND L.KTypeID = @KTypeID
				AND P.Deleted = 0
				AND G.QTY>0
		ORDER BY P.UserCode
	--==========缩减PType基本表


	SELECT 	@TableName='Web'+CONVERT(VARCHAR(2),DATEPART(dd,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(hh,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(m,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(s,GETDATE()))+CONVERT(VARCHAR(4),DATEPART(ms,GETDATE()))
	SELECT 	@TableSql='CREATE TABLE '+N'##'+@TableName+'([PTypeID] [VARCHAR] (50),[商品编号] [VARCHAR] (226),[商品名称] [VARCHAR] (256) , [总计] [VARCHAR] (100))'
	EXEC	(@TableSql)
--------------------------------------------------------商品定义游标的算法
	SELECT @PSQL = '    
	DECLARE Ptype_Cursor Cursor    FOR
    SELECT  TOP ' + CAST(@PageSize AS VARCHAR(50)) + ' TypeID,UserCode,FullName            
    FROM    #Ptype
    WHERE   Deleted = 0
			AND SonNum = 0
            AND TypeID <> ''00000''
			AND TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
            AND UserCode NOT IN                    
            (
                SELECT    TOP ' + CAST((@PPageNo-1) * @PageSize AS VARCHAR(50)) + '  UserCode
                FROM      #Ptype
                WHERE     Deleted = 0
                          AND SonNum = 0
                          AND TypeID <> ''00000''
						  AND UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
						  AND FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+'
						  AND TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
                ORDER BY     UserCode
            )                            
			AND UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
			AND FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+'
			AND TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
    ORDER BY UserCode'

    EXEC(@PSQL)                    --执行游标算法
    
    OPEN Ptype_Cursor            --打开游标
    
    FETCH NEXT FROM Ptype_Cursor INTO @PTypeID,@PUserCode,@PFullName

    WHILE @@FETCH_STATUS = 0    --循环写入临时表
        BEGIN

			--计算行的合计

			SELECT 	@LineTotal = ISNULL(SUM(A.Qty),0)
			FROM 	GoodsLocal A,
					#LType L,
					#PType P 
			WHERE 	A.LTypeID = L.TypeID 
					AND P.TypeID = A.PTypeID 
					AND P.Deleted = 0 
					AND L.KTypeID = @KTypeID
					AND A.PTypeID = @PTypeID


			SELECT @InsertTableSQL = 'INSERT INTO '+N'##'+@TableName+'
			(
				[PTypeID],
				[商品编号],
				[商品名称],
				[总计]
			)
			VALUES
			(
				'+CHAR(39)+@PTypeID+CHAR(39)+',
				'+CHAR(39)+@PUserCode+CHAR(39)+',
				'+CHAR(39)+@PFullName+CHAR(39)+',
				'+CHAR(39)+@LineTotal+CHAR(39)+'
			)'

			EXEC(@InsertTableSQL)
			
            IF @@ERROR <> 0     --错误处理
                BEGIN
                    CLOSE Ptype_Cursor
                    DEALLOCATE Ptype_Cursor                                
                END 
            FETCH NEXT FROM Ptype_Cursor INTO @PTypeID,@PUserCode,@PFullName                    
        END

    CLOSE Ptype_Cursor            --关闭游标
    DEALLOCATE Ptype_Cursor        --释放游标资源	
--------------------------------------------------------货位定义游标的算法
	SELECT @KSQL = '    
	DECLARE   LType_Cursor Cursor FOR	
    SELECT    TOP ' + CAST(@PageSize AS VARCHAR(50)) + ' TypeID,UserCode,FullName            
    FROM      #LType
    WHERE     Deleted = 0
            AND SonNum = 0
            AND TypeID <> ''00000''
			AND KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
			AND KTypeID LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+'
            AND UserCode NOT IN                    
            (
                SELECT    TOP ' + CAST((@LPageNo-1) * @PageSize AS VARCHAR(50)) + '  UserCode
                FROM      #LType
                WHERE     Deleted = 0
						  AND SonNum = 0
                          AND TypeID <> ''00000''
						  AND KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						  AND KTypeID LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+'
                ORDER BY     UserCode
            )                            
    ORDER BY UserCode'

    EXEC(@KSQL)                    --执行游标算法
    
    OPEN LType_Cursor            --打开游标   

	FETCH NEXT FROM LType_Cursor INTO @LTypeID,@LUserCode,@LFullName


    WHILE @@FETCH_STATUS = 0    --循环写入临时表
        BEGIN			

			SELECT @AlterSQL = '	ALTER TABLE '+N'##'+@TableName+' ADD ['+@LFullName+'|'+@LUserCode+']  VARCHAR(256)'

			EXEC (@AlterSQL)			

			SELECT @UpdateDataSQL = 'UPDATE '+N'##'+@TableName+' SET ['+@LFullName+'|'+@LUserCode+'] = B.Qty FROM '+N'##'+@TableName+' A ,GoodsLocal B WHERE A.PTypeID = B.PTypeID AND  B.LTypeID = '+CHAR(39)+@LTypeID+CHAR(39)
	

			EXEC (@UpdateDataSQL)
			
            IF @@ERROR <> 0     --错误处理
                BEGIN
                    CLOSE LType_Cursor
                    DEALLOCATE LType_Cursor                                
                END 
            FETCH NEXT FROM LType_Cursor INTO @LTypeID,@LUserCode,@LFullName                    
        END

    CLOSE LType_Cursor            --关闭游标
    DEALLOCATE LType_Cursor        --释放游标资源

----------------------------------------------------------------------------------------------------------------------取基本信息数据结束
	SELECT @SelectTableSQL = 'SELECT * FROM '+N'##'+@TableName

	EXEC(@SelectTableSQL)

	SELECT @DropTableSQL = 'Drop TABLE '+N'##'+@TableName

	DROP TABLE #PType
	DROP TABLE #LType

END












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryGoodsLocalDistribute_test]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryGoodsLocalDistribute_test]
GO









/*
	作者：谢吉康
	日期：2003-12-17
	描述：货位分布状况表

	GP_QueryGoodsLocalDistribute '00001','00055','','',14,1,1
*/
CREATE  PROCEDURE GP_QueryGoodsLocalDistribute_test
(
	@OperatorID		VARCHAR(50),	--操作员ID
	@KTypeID		VARCHAR(50),	--仓库ID
	@UserCode		VARCHAR(50),	--商品编号
	@FullName 		VARCHAR(50),	--商品名称
	@PageSize 		INT,			--显示记录数
	@PPageNo		INT,			--商品的页数
	@LPageNo		INT				--仓库的页数
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @PSQL VARCHAR(8000)
DECLARE @KSQL VARCHAR(8000)

DECLARE @PTypeID  VARCHAR(50)
DECLARE @PUserCode VARCHAR(256)
DECLARE @PFullName VARCHAR(256)


DECLARE @LTypeID  VARCHAR(50)
DECLARE @LUserCode VARCHAR(256)
DECLARE @LFullName VARCHAR(256)

DECLARE @TableSql VARCHAR(8000)
DECLARE @TableName VARCHAR(50)
DECLARE @DropTableSql VARCHAR(8000)
DECLARE @InsertTableSQL VARCHAR(8000)
DECLARE @SelectTableSQL VARCHAR(8000)

DECLARE @AlterSQL	VARCHAR(8000)


BEGIN
	CREATE TABLE #Ptype
	(
        TypeID    	VARCHAR(50),
        UserCode    VARCHAR(256),
        FullName    VARCHAR(256)
    )
	CREATE TABLE #LType
	(
		TypeID		VARCHAR(50),
		UserCode	VARCHAR(256),
		FullName 	VARCHAR(256)
	)

	SELECT 	@TableName='Web'+CONVERT(VARCHAR(2),DATEPART(dd,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(hh,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(m,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(s,GETDATE()))+CONVERT(VARCHAR(4),DATEPART(ms,GETDATE()))
	SELECT 	@TableSql='CREATE TABLE '+N'##'+@TableName+'([PTypeID] [VARCHAR] (50),[商品编号] [VARCHAR] (226),[商品名称] [VARCHAR] (256) , [总计] [VARCHAR] (100),[仓库ID] VARCHAR(50))'
	EXEC	(@TableSql)

--------------------------------------------------------货位定义游标的算法
	SELECT @KSQL = '    
	DECLARE   LType_Cursor Cursor FOR	
    SELECT    TOP ' + CAST(@PageSize AS VARCHAR(50)) + ' TypeID,UserCode,FullName            
    FROM      LType
    WHERE     Deleted = 0
            AND SonNum = 0
            AND TypeID <> ''00000''
			AND KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
			AND KTypeID LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+'
            AND UserCode NOT IN                    
            (
                SELECT    TOP ' + CAST((@LPageNo-1) * @PageSize AS VARCHAR(50)) + '  UserCode
                FROM      LType
                WHERE     Deleted = 0
						  AND SonNum = 0
                          AND TypeID <> ''00000''
						  AND KTypeID LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						  AND KTypeID LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+'
                ORDER BY     UserCode
            )                            
    ORDER BY UserCode
'

    EXEC(@KSQL)                    --执行游标算法
    
    OPEN LType_Cursor            --打开游标
	FETCH NEXT FROM LType_Cursor INTO @LTypeID,@LUserCode,@LFullName 
    WHILE @@FETCH_STATUS = 0    --循环写入临时表
        BEGIN			
            INSERT INTO #LType
                (
                    TypeID,
                    UserCode,
                    FullName
                )
                VALUES
                (
                    @LTypeID,
                    @LUserCode,
                    @LFullName
                )    	
			SELECT @AlterSQL = 'ALTER TABLE '+N'##'+@TableName+' ADD ['+@LFullName+']  VARCHAR(256)'
			EXEC (@AlterSQL)			

            IF @@ERROR <> 0     --错误处理

                    BEGIN
                        CLOSE LType_Cursor
                        DEALLOCATE LType_Cursor                                
                    END 
            FETCH NEXT FROM LType_Cursor INTO @LTypeID,@LUserCode,@LFullName                    
        END

    CLOSE LType_Cursor            --关闭游标
    DEALLOCATE LType_Cursor        --释放游标资源
--------------------------------------------------------商品定义游标的算法
	SELECT @PSQL = '    
	DECLARE    Ptype_Cursor Cursor    FOR
    SELECT    TOP ' + CAST(@PageSize AS VARCHAR(50)) + ' TypeID,UserCode,FullName            
    FROM     Ptype
    WHERE     Deleted = 0
            AND SonNum = 0
            AND TypeID <> ''00000''
			AND TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
            AND UserCode NOT IN                    
            (
                SELECT    TOP ' + CAST((@PPageNo-1) * @PageSize AS VARCHAR(50)) + '  UserCode
                FROM     Ptype
                WHERE     Deleted = 0
                        AND SonNum = 0
                        AND TypeID <> ''00000''
						AND TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
                ORDER BY     UserCode
            )                            
    ORDER BY UserCode'

    EXEC(@PSQL)                    --执行游标算法
    
    OPEN Ptype_Cursor            --打开游标
    
    FETCH NEXT FROM Ptype_Cursor INTO @PTypeID,@PUserCode,@PFullName

    WHILE @@FETCH_STATUS = 0    --循环写入临时表
        BEGIN
            INSERT INTO #Ptype
                        (
                            TypeID,
                            UserCode,
                            FullName
                        )
                        VALUES
                        (
                            @PTypeID,
                            @PUserCode,
                            @PFullName
                        )    
			SELECT @InsertTableSQL = 'INSERT INTO '+N'##'+@TableName+'
			(
				[PTypeID],
				[商品编号],
				[商品名称],
				[总计],
				[仓库ID]
			)
			VALUES
			(
				'+CHAR(39)+@PTypeID+CHAR(39)+',
				'+CHAR(39)+@PUserCode+CHAR(39)+',
				'+CHAR(39)+@PFullName+CHAR(39)+',
				'+CHAR(39)+'0'+CHAR(39)+',
				'+CHAR(39)+@KTypeID+CHAR(39)+'
			)'
			EXEC(@InsertTableSQL)
			
            IF @@ERROR <> 0     --错误处理
                BEGIN
                    CLOSE Ptype_Cursor
                    DEALLOCATE Ptype_Cursor                                
                END 
            FETCH NEXT FROM Ptype_Cursor INTO @PTypeID,@PUserCode,@PFullName                    
        END

    CLOSE Ptype_Cursor            --关闭游标
    DEALLOCATE Ptype_Cursor        --释放游标资源


----------------------------------------------------------------------------------------------------------------------取基本信息数据结束


--    SELECT * FROM #Ptype
--   SELECT * FROM #LType
	SELECT @SelectTableSQL = 'SELECT * FROM '+N'##'+@TableName

	EXEC(@SelectTableSQL)

    DROP TABLE #Ptype
	DROP TABLE #LType

	SELECT @DropTableSQL = 'Drop TABLE '+N'##'+@TableName
END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryGuestBackIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryGuestBackIndex]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryGuestBackIndex    Script Date: 2002-6-20 10:14:50 ******/

CREATE  PROCEDURE Gp_QueryGuestBackIndex
( 
 @BeginDate  varchar(25),
 @EndDate  varchar(25),
 @BtypeId  varchar(25),
 @EtypeId  varchar(25),
 @ktypeId  varchar(25),
 @OrderBy  varchar(50) = 'billdate',
 @BillType  varchar(5) = '',
 @Checke varchar(25)='',
 @BtypeName varchar(66)=''
-- @FilterBill bit = 0 
)
--@encode$--
AS
SET NOCOUNT ON 
declare @cz_query varchar(8000)
declare @Sql varchar (8000)
select @cz_Query=''
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=@cz_query+' a.billdate>='+char(39)+@begindate+char(39)+' and a.billdate<='+char(39)+@enddate+char(39)+' and '
--if rtrim(@Atypeid) <>''
-- select @cz_query=@cz_query+' a.atypeid='+char(39)+@atypeid+char(39)+' and '
if rtrim(@etypeid) <> ''
 select @cz_query=@cz_query+' a.etypeid='+char(39)+@etypeid+char(39)+' and '
if rtrim(@ktypeid) <>'' 
 select @cz_query=@cz_query+' a.ktypeid='+char(39)+@ktypeid+char(39)+' and '
if rtrim(@BtypeName) <> ''
 select @cz_query=@cz_query+' b.fullname='+char(39)+@BtypeName+char(39)+' and '
if @BtypeId<>'00000'
 if rtrim(@btypeid) <> '' 
  select @cz_query=@cz_query+' left(a.btypeid,len('+char(39)+@btypeid+char(39)+'))='+char(39)+@btypeid+char(39)+' and '
if rtrim(@billtype)<> ''
 select @cz_query=@cz_query+' a.billtype='+char(39)+@billtype+char(39) + ' and'
if rtrim(@Checke)<> ''
 select @cz_query=@cz_query+' a.Checke='+char(39)+@Checke+char(39) + ' and'
--if @filterbill=1
--begin
-- select @cz_query=@cz_query+' a.billtype<>4 and a.billtype<>66 and a.billtype<>116
--    and a.billtype<>115 and a.billtype<>129 and a.billtype<>128 and a.billtype<>77 and a.ifcheck=''f'' and'
--end else
--begin
-- select @cz_query =@cz_query+' a.ifcheck=''t'' and'
--end
select @cz_query=substring(@cz_query,1,len(@cz_query)-4)
select @Sql ='SELECT *, CBillType=
  case billtype 
  when 300 then ''销售订单''
  when 301 then ''进货订单''
  end,
          isnull(e.fullname,'''') AS etype
          ,isnull(s.fullname,'''') AS Ktype
          ,isnull(b.fullname,'''') AS btype
FROM GuestBackIndex a 
inner join btype b on a.btypeid = b.typeid
left join stock s on a.Ktypeid = s.typeid
inner join employee e on a.etypeid = e.typeid '
if rtrim(@cz_query) <> ''
  select @Sql=@Sql+' where '+@cz_query 
if rtrim(@orderby) <> ''
  select @Sql=@Sql+' order by '+@orderby
--print @sql
exec (@Sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryGuestPayIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryGuestPayIndex]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryGuestPayIndex    Script Date: 2002-6-20 10:14:50 ******/

CREATE  PROCEDURE Gp_QueryGuestPayIndex
( 
 @BeginDate  varchar(25),
 @EndDate  varchar(25),
 @BtypeId  varchar(25),
 @EtypeId  varchar(25),
 @ktypeId  varchar(25),
 @OrderBy  varchar(50) = 'billdate',
 @BillType  varchar(5) = '',
 @Checke varchar(25)='',
 @BtypeName varchar(66)=''
-- @FilterBill bit = 0 
)
--@encode$--
AS
SET NOCOUNT ON 
declare @cz_query varchar(8000)
declare @Sql varchar (8000)
select @cz_Query=''
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=@cz_query+' a.billdate>='+char(39)+@begindate+char(39)+' and a.billdate<='+char(39)+@enddate+char(39)+' and '
--if rtrim(@Atypeid) <>''
-- select @cz_query=@cz_query+' a.atypeid='+char(39)+@atypeid+char(39)+' and '
if rtrim(@etypeid) <> ''
 select @cz_query=@cz_query+' a.etypeid='+char(39)+@etypeid+char(39)+' and '
if rtrim(@ktypeid) <>'' 
 select @cz_query=@cz_query+' a.ktypeid='+char(39)+@ktypeid+char(39)+' and '
if rtrim(@BtypeName) <> ''
 select @cz_query=@cz_query+' b.fullname='+char(39)+@BtypeName+char(39)+' and '
if @BtypeId<>'00000'
 if rtrim(@btypeid) <> '' 
  select @cz_query=@cz_query+' left(a.btypeid,len('+char(39)+@btypeid+char(39)+'))='+char(39)+@btypeid+char(39)+' and '
if rtrim(@billtype)<> ''
 select @cz_query=@cz_query+' a.billtype='+char(39)+@billtype+char(39) + ' and'
if rtrim(@Checke)<> ''
 select @cz_query=@cz_query+' a.Checke='+char(39)+@Checke+char(39) + ' and'
select @cz_query=substring(@cz_query,1,len(@cz_query)-4)
select @Sql ='SELECT *, CBillType=
  case billtype 
  when 300 then ''销售订单''
  when 301 then ''进货订单''
  end,a.comment as icom,
          isnull(e.fullname,'''') AS etype
          ,isnull(s.fullname,'''') AS Ktype
          ,isnull(b.fullname,'''') AS btype
FROM  GuestPayIndex a 
inner join btype b on a.btypeid = b.typeid
left join stock s on a.Ktypeid = s.typeid
inner join employee e on a.etypeid = e.typeid '
if rtrim(@cz_query) <> ''
  select @Sql=@Sql+' where '+@cz_query 
if rtrim(@orderby) <> ''
  select @Sql=@Sql+' order by '+@orderby
--print @sql
exec (@Sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryLendDetailT2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryLendDetailT2]
GO















-- 借进借出查询单据
-- 2002-7-1 王峰
CREATE   PROCEDURE Gp_QueryLendDetailT2
( 
 @BeginDate	varchar(25)='',
 @EndDate	varchar(25)='',
 @BillCode	varchar(200)='',  --单据号
 @BillType	varchar(5)='',    --单据类型
 @EtypeName	varchar(66)='',  --经手人
 @BtypeName	varchar(66)='',  --客户
 @KtypeName	varchar(66)='',  --仓库
 @PtypeName    varchar(66)='',  --产品
 @Comment	varchar(256)='',
 @BillNumberId	numeric(10)=0,
 @OrderBy	varchar(250)='',
 @FilterBill	varchar(250)=''
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @SQLFrom  varchar(500)
DECLARE @SQLList  varchar(2000)
DECLARE @SQLWhere varchar(8000)
DECLARE @SQLOrder varchar(200)

SELECT @SQLFrom  = ''
SELECT @SQLList  = ''
SELECT @SQLWhere = ''
SELECT @SQLOrder = ''

-- 基本列表的SQL
SELECT @SQLFrom=' FROM LendBill lb '
                                 +'INNER JOIN LendIndex li ON li.BillNumberId = lb.BillNumberId '
                                 +'INNER JOIN ptype p ON lb.PtypeId = p.typeId '
                                 +'INNER JOIN btype b ON li.btypeid = b.typeId '
                                 +'INNER JOIN Stock k ON li.ktypeid = k.typeId '
                                 +'INNER JOIN Employee e ON li.etypeid = e.typeId '

-- 基本的显示字段
SELECT @SQLList = 'SELECT p.UserCode AS pUserCode, p.FullName AS pFullName, lb.PtypeId AS pTypeID, '
                                +'k.UserCode AS kUserCode, k.FullName AS kFullName, li.kTypeID, '
                                +'b.UserCode AS bUserCode, b.FullName AS bFullName, li.bTypeID, '
                                +'e.UserCode AS eUserCode, e.FullName AS eFullName, li.eTypeID, '
                                +'li.BillNumberID, li.BillDate, li.BillType, li.BillCode, lb.Comment AS Comment, lb.Qty AS Qty, '
                                +'CASE li.BillType WHEN 71 THEN Qty ELSE 0 END AS Borrow, '
                                +'CASE li.BillType WHEN 72 THEN - Qty ELSE 0 END AS BorrowBack, '
                                +'CASE li.BillType WHEN 87 THEN - Qty ELSE 0 END AS Lend, '
                                +'CASE li.BillType WHEN 88 THEN Qty ELSE 0 END AS LendBack '

-- 限制条件
IF RTRIM(@BeginDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND li.[BillDate]>=''' + @BeginDate +''' '
IF RTRIM(@EndDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND li.[BillDate]<=''' + @EndDate +''' '
IF @BillNumberId<>0
	SELECT @SQLWhere = @SQLWhere + ' AND li.[BillNumberID]=' + STR(@BillNumberId) +' '
IF RTRIM(@BillCode)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND li.[BillCode] LIKE ''%' + @BillCode +'%'' '
IF RTRIM(@BillType)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND li.[BillType] = ' + @BillType +' '

IF RTRIM(@Comment)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND lb.[Comment] LIKE ''%' + @Comment +'%'' '
IF RTRIM(@EtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (e.[FullName] LIKE ''%' + @EtypeName +'%'' OR e.[UserCode] LIKE ''%' + @EtypeName +'%'') '
IF RTRIM(@BtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (b.[FullName] LIKE ''%' + @BtypeName +'%'' OR b.[UserCode] LIKE ''%' + @BtypeName +'%'') '
IF RTRIM(@KtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (k.[FullName] LIKE ''%' + @KtypeName +'%'' OR k.[UserCode] LIKE ''%' + @KtypeName +'%'') '
IF RTRIM(@PtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (p.[FullName] LIKE ''%' + @PtypeName +'%'' OR p.[UserCode] LIKE ''%' + @PtypeName +'%'') '

-- 去掉多余的 AND
IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + Right(@SQLWhere,LEN(@SQLWhere)-4)

-- 排序
IF RTRIM(@OrderBy)<>''
	SELECT @SQLOrder = ' Order By ' + RTRIM(@OrderBy)
ELSE
	SELECT @SQLOrder = ' Order By  lb.BillNumberId'

exec (@SQLList + @SQLFrom + @SQLWhere + @SQLOrder)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryLendIndexCard]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryLendIndexCard]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：zhangtao
	日期：2016-06-07
	描述：固定资产变更草稿查询
*/
create  PROCEDURE Gp_QueryLendIndexCard 
(  
	@startdate		varchar(20),
	@enddate		varchar(20),
	@dtypeid		varchar(50),
	@etypeid		varchar(50),
	@stypeid       varchar(50),
	@billcode		varchar(50),
	@cid		int=0
)

AS
SET NOCOUNT ON
declare @sql nvarchar(max)
set @sql=N'select billdate,acastypeid,ass.dtypeid,em.department,em.fullname,etypeid,billcode,acasfullname,total,deptotal,totaldif,deptotaldif,
       [Id]
      ,ass.[TypeId]
      ,ass.[Parid]
      ,[AcAsUserCode]
      ,[AcAsFullName]
      ,ass.[Stypeid]
      ,[ChangeReasonID]
      ,[CID]
      ,[Rate]
      ,[BusinessTypeId]
      ,ass.[BtypeId]
      ,[OldF_Total]
      ,[OldTotal]
      ,[OldNetValue]
      ,[OldRate]
      ,[OldDepTotal]
      ,[OldDevalueReady]
      ,[OldNetSalvage]
      ,[F_Total]
      ,[NetValue]
      ,[F_TotalDif]
      ,[NetValueDif]
      ,ass.[XiWaMaxNumber]
      ,[Draft]
      ,[DELETE]
       from AssetIncChangeBill ass 
inner join employee em on ass.Stypeid=em.typeid where ass.draft=1'  
if(isnull(@startdate,'') <> '')
begin
set @sql=@sql+' and billdate>='''+@startdate+''''
end


if(isnull(@enddate,'') <> '')
begin
set @sql=@sql+' and billdate<='''+@enddate+''''
end

if(isnull(@dtypeid,'') <> '')
begin
set @sql=@sql+' and ass.dtypeid='''+@dtypeid+''''
end 

if(isnull(@etypeid,'') <> '')
begin
set @sql=@sql+' and ass.etypeid='''+@etypeid+''''
end

if(isnull(@etypeid,'') <> '')
begin
set @sql=@sql+' and ass.stypeid='''+@stypeid+''''
end

if(isnull(@billcode,'') <> '')
begin
set @sql=@sql+' and billcode='''+@billcode+''''
end

if(@cid <> -1)
begin
set @sql=@sql+' and cid='+ltrim(rtrim(@cid)) 
end
--print @sql;
exec sp_executesql  @sql;
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryLendIndexLi]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryLendIndexLi]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2008-05-05
	描述：借欠单据增加审核
*/
CREATE               PROCEDURE Gp_QueryLendIndexLi
( 
	@MagEType		varchar(50),
	@BillType		varchar(5)='',
	@BeginDate		varchar(25)='',
	@EndDate		varchar(25)='',
	@BillCode		varchar(200)='',
	@EtypeName		varchar(200)='',
	@BtypeName		varchar(200)='',
	@IfAudit		CHAR(2) = '1' ,
	@KtypeName		varchar(200)='',
	@KtypeName2		varchar(200)='',
	@AtypeName		varchar(200)='',
	@RelatBtype		varchar(200)='',
	@Comment		varchar(256)='',
	@BillNumberId		numeric(10)=0,
	@OrderBy		varchar(250)='',
	@FilterBill		varchar(250)='',
	@stypeid		varchar(50),
	@DTypeID  		VARCHAR(100) = '',
	@IsIni			int=0							--1为期初单据，0为非期初单据
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @MagEType
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 分支机构
IF @Stypeid<>'' or @chvMStypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END


-- 往来单位
IF (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999')
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailBType B ON a.DealBTypeID = B.TypeID '
	INSERT INTO #F_BaseGetManDetailBType(TypeID) VALUES('')
END


-- 结算单位
IF (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999')
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailBType1 FROM F_BaseGetManDetailBType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailBType1 B1 ON a.BTypeID = B1.TypeID '
	INSERT INTO #F_BaseGetManDetailBType1(TypeID) VALUES('')
END


-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
	insert into #F_BaseGetManDetailEType values('')
END

	
-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID OR a.KTypeID2 = K.TypeID '
	--insert into #F_BaseGetManDetailKType values('')
END

-- 部门
IF @chvMDtypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetaildType FROM F_BaseGetManDetailDType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
		insert into #F_BaseGetManDetaildType values('')
END

-- ******** 权限范围单独处理 - End ********

DECLARE @re 			int,	-- 修改他人草稿的权限
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@ReLimitPass 	int		-- 单据过帐权限

EXEC @Re467 = GP_CheckLimit @MagEType,467  --查看他人业务草稿
EXEC @re = GP_CheckLimit @MagEType,135  --修改草稿
IF @Re467=1 
	SET @re=1 
IF @re = 1 AND (@IfAudit = 0 OR @IfAudit = 1)
BEGIN
	IF @IfAudit=0
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet
			WHERE BillType = @BillType AND IfUse = 1 AND LEFT(AuditingReason,1) <> 1)	-- 检查单据是否有审核流程
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet A,AuditingFlowDetail B
				WHERE A.AuditingID = B.AuditingID AND A.BillType = @BillType AND A.IfUse = 1
				AND LEFT(A.AuditingReason,1) <> 1 AND B.ETypeID = @MagEType)	-- 检测具体人针对具体的单据是否有审核流程
			BEGIN
				IF @Re467 = 0
					SET @re = 0
				ELSE
					SET @re = 1
		END
		ELSE
			IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail B,AuditingFlowSet A
					WHERE A.AuditingID = B.AuditingID AND B.ETypeID = @MagEType
					AND B.AuditingStep = 0 AND A.BillType = @BillType)	-- 检测用户是否具有特批人权限
			BEGIN
				IF @Re467 = 0
					SET @re = 0
				ELSE
					SET @re = 1
			END
		END
	END
	ELSE 
		SET @re = 0
END
IF @re = 2 RETURN @re


DECLARE @SQL varchar(3000)
SET @SQL = '
	SELECT	a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.DealBtypeid AS BTypeID,
			a.StypeID,
			a.Explain,
			a.dtypeid,
			a.checke,
			a.Comment
	FROM	LendIndex a ' + @SQL_Man 

IF @IfAudit = 2
BEGIN
	SET @SQL = @SQL + '
	WHERE	NOT EXISTS(
				SELECT ab.BillNumberID FROM AuditingBill ab
				WHERE a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 1
			) AND '
END
ELSE
BEGIN
	SET @SQL = @SQL + '
	INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 1 AND ab.IfAudit = ''' + @IfAudit + '''
	WHERE	1=1 AND '
END

SET @SQL = @SQL + '	a.BillDate >= ''' + @BeginDate + ''' AND a.BillDate <= ''' + @EndDate + '''
					AND a.BillType = ' + @BillType+' AND a.draft=1'

IF @IsIni=1 
	SET @SQL = @SQL + ' AND a.IsIni=1 '
ELSE
	SET @SQL = @SQL + ' AND a.IsIni=0 '
	
IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @BtypeName <> '' SET @SQL = @SQL + ' AND a.BTypeID=''' + @BtypeName + ''''
IF @EtypeName <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EtypeName + ''''
IF @DTypeID <> '' SET @SQL = @SQL + ' AND a.DTypeID=''' + @DTypeID + ''''
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC, a.BillCode'

--PRINT(@SQL)
EXEC (@SQL)
IF (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999') DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMDtypeid  = '-99999' DROP TABLE #F_BaseGetManDetaildType 
IF @Stypeid<>'' or @chvMStypeid<>'00000' DROP TABLE #F_BaseGetManDetailSType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryLendIndextT2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryLendIndextT2]
GO



-- 借进借出查询单据
-- 2002-6-27 王峰

--修改作者：谢吉康
--修改日期：2003-11-18
--修改描述：按照单据的日期排序
--修改结果：测试正确
CREATE          PROCEDURE Gp_QueryLendIndextT2
( 
	@OperatorID		VARCHAR(50),
	@BeginDate		VARCHAR(25)='',
	@EndDate		VARCHAR(25)='',
	@BillCode		VARCHAR(200)='',
	@BillType		VARCHAR(5)='',
	@EtypeName		VARCHAR(max)='',  --经手人
	@BtypeName		VARCHAR(max)='',  --客户
	@KtypeName		VARCHAR(max)='',  --仓库
	@Comment		VARCHAR(256)='',
	@Explain		VARCHAR(256)='',
	@Memo			VARCHAR(256)='',
	@BillNumberId	NUMERIC(10)=0,
	@OrderBy		VARCHAR(250)='',
	@FilterBill		VARCHAR(250)='',
	@STypeId		VARCHAR(MAX),
	@showway		VARCHAR(50),	--allbill=全部单据,notshowred=不显红冲,onlyshowred=只显红冲
	@IsReporting	INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQLFrom  VARCHAR(1000)
DECLARE @SQLList  VARCHAR(2000)
DECLARE @SQLWhere VARCHAR(8000)
DECLARE @SQLOrder VARCHAR(200)

SELECT @SQLFrom  = ''
SELECT @SQLList  = ''
SELECT @SQLWhere = ''
SELECT @SQLOrder = ''

--多级权限
SELECT a.* INTO #btype FROM F_GetManBtypeAll(@OperatorID) a --往来单位权限
SELECT a.* INTO #stock FROM F_GetManKtypeAll(@OperatorID) a --仓库权限
SELECT a.TypeId INTO #employee FROM F_GetManDetailEtype(@OperatorID) a --职员权限
IF ISNULL(@EtypeName,'') = ''
	INSERT INTO #employee(TypeId)VALUES('')


-- 基本的显示字段
SELECT @SQLList = 'SELECT bi.*'
			 +',totalqtys= bi.totalqty '	
		     +',CBillType= '
		     +' CASE BillType '
		     +' WHEN 71 THEN ''借进开单'' '
		     +' WHEN 72  THEN ''借进还出单'' '
		     +' WHEN 87  THEN ''借出开单'' '
		     +' WHEN 88 THEN ''借出还回单'' '
		     +' END '
             +',ISNULL(e.TypeId,'''') AS etype '
		     +',ISNULL(k1.TypeId,'''') AS Ktype '
		     +',ISNULL(k1.usercode,'''') AS kusercode '
		     +',ISNULL(k2.FULLNAME,'''') AS Ktype2 '
		     +',ISNULL(b.TypeId,'''') AS btype '
		     +',ISNULL(a.TypeId,'''') AS atype '
		     +',ISNULL(p.TypeId,'''') AS ptype '
		     +',ISNULL(e.FULLNAME,'''') AS checkman ' --经手人
		     +',ISNULL(e1.FULLNAME,'''') AS checkefullname ' --制单人
		     
-- 基本列表的SQL
SELECT @SQLFrom=' FROM LendIndex bi '
		      +' LEFT JOIN Btype b ON (bi.[dealBTypeId] = b.[TypeId]) '
		      +' LEFT JOIN Stock k1 ON (bi.[KtypeId] = k1.[Typeid]) '
		      +' LEFT JOIN Employee e ON (bi.[EtypeId] = e.[Typeid]) '
		      +' LEFT JOIN Employee e1 ON (bi.[checke] = e1.[Typeid]) '
		      +' LEFT  JOIN Atype a ON (bi.[AtypeId] = a.[TypeId]) '
		      +' LEFT  JOIN Ptype p ON (bi.[PtypeId] = p.[TypeId]) '
		      +' LEFT  JOIN Stock k2 ON (bi.[KtypeId2] = k2.[Typeid])'
                                 +' RIGHT OUTER JOIN (SELECT dbo.lendbill.billNumberId FROM lendbill WHERE (dbo.LendBill.comment LIKE ''%'
		      +RTRIM(@Memo)
		      +'%'') GROUP BY dbo.LendBill.billNumberId)  lb ON (bi.BillNumberId = lb.BillNumberId) '

SELECT @SQLWhere=@SQLWhere+' WHERE 1=1 '

-- 限制条件
IF RTRIM(@BeginDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillDate]>=''' + RTRIM(@BeginDate) +''' '
IF RTRIM(@EndDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillDate]<=''' + RTRIM(@EndDate) +''' '
IF @BillNumberId<>0
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillNumberID]=' + STR(@BillNumberId) +' '
IF RTRIM(@BillCode)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillCode] LIKE ''%' + RTRIM(@BillCode) +'%'' '
IF RTRIM(@Comment)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[Comment] LIKE ''%' + RTRIM(@Comment) +'%'' '
IF RTRIM(@Explain)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[Explain] LIKE ''%' + RTRIM(@Explain) +'%'' '
IF RTRIM(@BillType)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillType] = ' + RTRIM(@BillType) +' '

IF RTRIM(@EtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.[etypeid] IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@EtypeName+''',3))) '
IF RTRIM(@BtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.dealbtypeid IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@BtypeName+''',2))) '
IF RTRIM(@KtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.[ktypeid] IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@KtypeName+''',4))) '

SELECT @SQLWhere = @SQLWhere + ' AND bi.STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''+@STypeId+''',11,'''+@OperatorID+''')) '	
SELECT @SQLWhere = @SQLWhere + ' AND (bi.DTypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''',9,'''+@OperatorID+''')) OR ISNULL(bi.DTypeId,'''')='''' )'	
	
--多级权限过滤
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[etypeid] IN (SELECT typeid FROM #employee))'
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[dealbtypeid] IN (SELECT typeid FROM #btype))'
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[ktypeid] IN (SELECT typeid FROM #stock))'

--单据过滤 	@showway	--allbill=全部单据,notshowred=不显红冲,onlyshowred=只显红冲

IF @showway='allbill'    --全部单据  
	SELECT @SQLWhere = @SQLWhere + ' AND ifcheck=''t''  '

IF @showway='notshowred' --不显红冲  
	SELECT @SQLWhere = @SQLWhere + ' AND ifcheck=''t'' AND RedWord=0  '

IF @showway='onlyshowred' --只显红冲  
	SELECT @SQLWhere = @SQLWhere + ' AND ifcheck=''t'' AND (RedWord=1 OR  RedWord=2 )'



-- 排序
IF RTRIM(@OrderBy)<>''
	SELECT @SQLOrder = ' ORDER BY ' + RTRIM(@OrderBy)
ELSE
	SELECT @SQLOrder = ' ORDER BY  bi.[BillDate], bi.[BillCode] '


--PRINT(@SQLList + @SQLFrom + @SQLWhere +  @SQLOrder )
--EXEC (@SQLList + @SQLFrom + @SQLWhere +  @SQLOrder )


----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题

	DECLARE @SQL VARCHAR(MAX)
	SET @SQL ='SELECT * INTO #Result FROM (' + @SQLList + @SQLFrom + @SQLWhere + ') AS bi ' + @SQLOrder + 
			  ' 
			
SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head

					  FROM #Result a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype

				
				DROP TABLE #Result
			   '
	EXEC (@SQL)

----------------------------------------------------------


--删除零时表
DROP TABLE #btype 
DROP TABLE #stock
DROP TABLE #employee



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryLineTable23]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryLineTable23]
GO

/*
	作者：谢吉康
	日期：2007-3-21
	描述：销售报表
*/

/*
	优化：董湛
	日期：2012-11-20
	描述：1.把F_GetManDetailPType,F_GetManPTypeDetailALL表值函数变为临时表#PtypeDetail，#PtypeDetailALL
		   2.新增临时表#Ptype，把@strPType里的查询内容插入#Ptype中
*/

/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE               PROCEDURE GP_QueryLineTable23 
(
   @OperatORID varchar(50),
   @QueryType  varchar(25),
   @PtypeId  varchar(50),
   @KtypeId  varchar(1550),
   @StarDate varchar(25),
   @ENDDate varchar(25),
   @UserCode varchar(40),
   @FullName varchar(80),
   --@ORDERFild varchar(25) ,
   @sortField varchar(25)='',
   @sortType  varchar(25)='', 
   @PageSize int,
   @PageNO int,
   @NoZero  int =0,
   @BtypeID varchar(50)='',
   @StypeID varchar(8000),
   @unitvalue		INT,			--单位选择值：销售单位0，采购单位1，存货单位2，基本单位3
   @IsCountSendPtype INT			--是否统计发出商品,发出商品出库单、发出商品退货单、销售发货开票
)
--@encode$--
AS
Set Nocount ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatORID is null return 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT


--  参数初始值
IF @QueryType='' SELECT @QueryType='Sale'
--  @QueryType 的取值
--    1. Sale    : 销售
--    2. InGoods : 进货
--    3. InOut   : 往来 
IF @PtypeId='00000'  SELECT @PtypeId=''  


CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #stype (TypeID varchar(50))
CREATE TABLE #dtype	(TypeID varchar(50))


INSERT INTO #Dtype(typeid) select typeid from F_GetAllManagerBaseTypeId('',9,@OperatorID)

INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
--分支机构
INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID)

CREATE TABLE #PtypeDetail (TypeID varchar(50))
INSERT INTO #PtypeDetail (TypeID) SELECT typeid FROM F_GetManDetailPType(@OperatorID)

SELECT * INTO #PtypeDetailALL  FROM F_GetManPTypeDetailALL(@OperatorID)

IF @KTypeID=''
BEGIN
	INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorID)
	insert into #Ktype select '10000'
END
ELSE
	INSERT INTO #Ktype select a.typeid from F_GetManDetailKType(@OperatorID) a
	INNER JOIN dbo.f_split(@ktypeID,',') b 
	ON b.a=left(a.typeid,len(b.a))

DECLARE @sonnum INT=0 

DECLARE
	@strPType	VARCHAR(MAX)
	
CREATE TABLE #Ptype	
(
	typeid VARCHAR(50),
	parid  VARCHAR(50),
	usercode VARCHAR(200),
	fullname VARCHAR(200),
	sonnum	INT,
	leveal	SMALLINT,
	unit1	VARCHAR(8),
	unit2	VARCHAR(8),
	unitrate1	 NUMERIC(24, 10) 
)
IF @PtypeID=''
		INSERT INTO #Ptype
		SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.unit1,p.unit2,p.unitrate1
		FROM	Ptype p
		INNER JOIN #PtypeDetail a
		ON p.typeid=a.typeid
	--SELECT @strPType='
	--(
	--	SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.unit1,p.unit2,p.unitrate1
	--	FROM	Ptype p
	--	INNER JOIN #PtypeDetail a
	--	ON p.typeid=a.typeid
	--)
	--'
   
ELSE
        INSERT INTO #Ptype
   		SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.unit1,p.unit2,p.unitrate1
		FROM	Ptype p
		INNER JOIN #PtypeDetail a 
		ON  p.typeid=a.typeid AND a.typeid like @PtypeID+'%'
	--SELECT @strPType='
	--(
	--	SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.unit1,p.unit2,p.unitrate1
	--	FROM	Ptype p
	--	INNER JOIN 
	--	(
	--		select typeId from #PtypeDetail where typeid like '''+@PtypeID+'%''
	--	) a
	--	ON p.typeid=a.typeid
	--)
	--'
    
IF @PageSize='' SELECT @PageSize=14
IF (@PageNO='') OR (@PageNO < 1)  SELECT @PageNO=1
IF @UserCode='' SELECT @UserCode=''
IF @FullName='' SELECT @FullName=''

--采购线性表，仓库权限保持原样不动 
DECLARE @KtypeId1 varchar(200)
SET @KtypeId1 =@KtypeId

SELECT @PtypeId = @PtypeId + '%'
IF @KtypeId='' SELECT @KtypeId='%'




-- =====================modIFy BY chen_qihua 2004-06-08 #01========================================

-- ********* 保留变量用于其他的几种查询
declare @UserCodeTemp1 varchar(MAX)
declare @FullNameTemp1 varchar(MAX)

SET @UserCodeTemp1 =@UserCode
SET @FullNameTemp1 =@FullName


declare @userCodeTemp varchar(500)
declare @i int
--SELECT @UserCode = @UserCode + '%'
declare @SQL_UserCode varchar(MAX)

SET @SQL_UserCode=''
SET @i=charindex('#',@UserCode)  -- 取得'，'的位置常量


WHILE @i>=1
    BEGIN
		
		SET @UserCodeTemp = LEFT(@UserCode,@i-1)
		IF @SQL_UserCode =''
			SET @SQL_UserCode =' AND p.usercode like '+char(39)+'%'+@userCodeTemp+'%'+char(39)
		ELSE
			SET @SQL_UserCode =@SQL_UserCode+' AND p.usercode like '+char(39)+'%'+@userCodeTemp+'%'+char(39)

		SET @UserCode=SUBSTRING(@UserCode,@i+1,len(@UserCode)-@i)
			
        SET @i=charindex('#',@UserCode)

    END
IF @UserCode<>''
	BEGIN
		IF @SQL_UserCode =''
			SET @SQL_UserCode =' AND p.usercode like '+char(39)+'%'+@UserCode+'%'+char(39)
		ELSE
			SET @SQL_UserCode =@SQL_UserCode+' AND p.usercode like '+char(39)+'%'+@UserCode+'%'+char(39)

	END


declare @FullNameTemp varchar(500)
declare @j int

declare @SQL_FullName varchar(2000)
--print @SQL_UserCode
--return

SET @SQL_FullName=''
SET @j=charindex('#',@FullName)  -- 取得'，'的位置常量


WHILE @j>=1
    BEGIN
		
		SET @FullNameTemp = LEFT(@FullName,@j-1)
		IF @SQL_FullName =''
			SET @SQL_FullName =' AND p.fullname like '+char(39)+'%'+@FullNameTemp+'%'+char(39)
		ELSE
			SET @SQL_FullName =@SQL_FullName+' AND p.fullname like '+char(39)+'%'+@FullNameTemp+'%'+char(39)

		SET @FullName=SUBSTRING(@FullName,@j+1,len(@FullName)-@j)
			
        SET @j=charindex('#',@FullName)

    END
IF @FullName<>''
	BEGIN
		IF @SQL_FullName =''
			SET @SQL_FullName =' AND p.fullname like '+char(39)+'%'+@FullName+'%'+char(39)
		ELSE
			SET @SQL_FullName =@SQL_FullName+' AND p.fullname like '+char(39)+'%'+@FullName+'%'+char(39)

	END

-- ====================================== END ==========================================================================


SELECT @UserCode = @UserCodeTemp1 + '%'
SELECT @FullName = @FullNameTemp1 + '%'










SELECT @BtypeID = @BtypeID + '%'

Declare @PageCount int              -- 记录数量
Declare @SQLText    varchar(MAX)    -- 结果语句
Declare @TableName  varchar(250)     -- 临时表名
Declare @iIndexStar int
Declare @iLoop   int
Declare @cPTypeId varchar(50),
  @cUserCode varchar(26),  -- 商品编号
  @cFullName varchar(66),  -- 商品名称
  @cSaleNum  NUMERIC(24, 10) , -- 数量
  @cSalePrice  NUMERIC(24, 10) , -- 均价
  @cSaleTotal  NUMERIC(24, 10)   -- 金额

-- ********	卢春 2003-03-05	- Start	********



-- ********	卢春 2003-03-05	- END	********

------------------------------------------------------销售线性表----------------------------------------------------------------------
DECLARE 
		@tempqty			NVARCHAR(1000),
		@unitname			VARCHAR(500),	--计量单位name	
		@temptable          NVARCHAR(2000),
		@assistantfullname	 NVARCHAR(2000),
		@unitRelation  NVARCHAR(2000)=''
SET 	@assistantfullname ='u5.fullname'
IF @unitvalue=0
BEGIN
 SELECT @tempqty='q.Qty/isnull(r3.rate,1) ',
		@unitname='u3.fullname as unitfullname,u5.fullname as assistantfullname,',
		@temptable =dbo.F_GetPtypeUnitsAndRates('p1','1,3,5','3'),
		@unitRelation='''1''+u3.fullname+''=''+convert(varchar(200),CAST(r3.rate  AS real))+u1.fullname as unitRelation,'
END
IF @unitvalue=1
BEGIN
 SELECT @tempqty='q.Qty/isnull(r2.rate,1)  ',
		@unitname='u2.fullname as unitfullname,u5.fullname as assistantfullname,',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,2,5','2'),
		@unitRelation='''1''+u2.fullname+''=''+convert(varchar(200),CAST(r2.rate  AS real))+u1.fullname as unitRelation,'
END
IF @unitvalue=2
BEGIN
 SELECT @tempqty='q.Qty/isnull(r4.rate,1) ',
		@unitname='u4.fullname as unitfullname,u5.fullname as assistantfullname,',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,4,5','4'),
		@unitRelation='''1''+u4.fullname+''=''+convert(varchar(200),CAST(r4.rate  AS real))+u1.fullname as unitRelation,'
END
IF @unitvalue=3
BEGIN
 SELECT @tempqty='q.Qty  ',
		@unitname='u1.fullname as unitfullname,u5.fullname as assistantfullname,',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,5','1'),
		@unitRelation='''1''+u1.fullname+''=''+convert(varchar(200),CAST(r1.rate  AS real))+u1.fullname as unitRelation,'
END 


IF @QueryType='Sale' 

/**********************************
*销售线性表检查btypeid,ktypeid,etypeid,ktypeid 权限
*/
BEGIN

	IF(@IsCountSendPtype = 1)
	BEGIN
		SET @SQLText ='
			SELECT	p.TypeID AS PTypeID,
					p.UserCode AS UserCode,
					p.FullName AS FullName,
					p.SonNum,
					p.Unit1,
					p.Unit2,
					p.unitrate1,
					--q.Qty AS Qty,
					'+@tempqty+' as qty,
					u1.fullname baseunitfullname,--基本单位
					'+@assistantfullname+',--浮动单位
					'+@unitname+'
					'+@unitRelation+'
					q.nqty,
					q.Total As Total,
					q.TaxTotal As TaxTotal,
					price =case when q.Qty =0 then 0 else cast( q.Total as NUMERIC(24, 10))/ cast(('+@tempqty+')as NUMERIC(24, 10)) end,
					customassist=dbo.F_GetCustomAssist(p.TypeId, q.Qty)
			FROM	#Ptype p 
			JOIN (
					SELECT 	ISNULL(SUM(-t.qty), 0) AS qty,
							isnull(SUM(-t.NQty), 0) AS nqty,
							isnull(SUM(-t.total), 0) AS Total,
							isnull(SUM(-t.TaxTotal), 0) AS TaxTotal,
							t.PtypeID AS ptypeid
					FROM 
					(
						SELECT a.qty,
						a.NQty,
						a.total,
						a.TaxTotal,
						a.PtypeID
						FROM inoutstocktable  a
						INNER JOIN billindex b on a.billnumberid=b.billnumberid 
						'
						IF @MPTypeID='-99999' OR @PTypeID	NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #Ptype p on a.ptypeid=p.typeid '+CHAR(13)
						IF @MBTypeID='-99999' OR @MBTypeID2='-99999' OR @BTypeID NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #btype bt on a.btypeid=bt.typeid '+CHAR(13)
						IF @METypeID='-99999' SET @SQLText=@SQLText+' INNER JOIN #etype e on a.etypeid=e.typeid '+CHAR(13)
						IF @MKTypeID='-99999' OR @KTypeID NOT IN ('','00000','%')	SET @SQLText=@SQLText+' INNER JOIN #ktype k on a.ktypeid=k.typeid '+CHAR(13)
						IF @MStypeid<>'00000' OR @Stypeid <>''	SET @SQLText=@SQLText+'	INNER JOIN #Stype s ON  a.stypeid=s.typeid	'+CHAR(13)
						IF @MDtypeid<>'00000' 	SET @SQLText=@SQLText+'	INNER JOIN #dtype d ON  a.dtypeid=d.typeid	'+CHAR(13)
						SET @SQLText += ' 
						WHERE 	a.Audited=1 
								AND A.BillType IN (11,45,141,305,160,215,12,46)
								AND b.ifYearBill=''0''			--年节存标志
								--AND a.atypeid='+char(39)+'0000100001' +char(39)+'
								AND a.billdate>='+char(39)+@StarDate+char(39)+'
								AND a.billdate<='+char(39)+@ENDDate+char(39)
						SET @SQLText += ' 
							
						UNION ALL
						--发出商品出库单
						SELECT -(a.Qty - a.InvoiceQty) AS Qty,
						-(a.NQty - a.InvoiceNQty) AS NQty,
						CASE a.InvoiceQty
							WHEN 0 THEN -a.total
							ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice)
						END AS total,
						CASE a.InvoiceQty
							WHEN 0 THEN -a.TaxTotal
							ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice)
						END AS taxtotal,
						a.PtypeID 
						FROM SendBill AS a 
						INNER JOIN BillIndex AS b ON(A.BillNumberId = B.BillNumberId)
						'
						IF @MPTypeID='-99999' OR @PTypeID	NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #Ptype p on a.ptypeid=p.typeid '+CHAR(13)
						IF @MBTypeID='-99999' OR @MBTypeID2='-99999' OR @BTypeID NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #btype bt on b.btypeid=bt.typeid '+CHAR(13)
						IF @METypeID='-99999' SET @SQLText=@SQLText+' INNER JOIN #etype e on b.etypeid=e.typeid '+CHAR(13)
						IF @MKTypeID='-99999' OR @KTypeID NOT IN ('','00000','%')	SET @SQLText=@SQLText+' INNER JOIN #ktype k on a.ktypeid=k.typeid '+CHAR(13)
						IF @MStypeid<>'00000' OR @Stypeid <>''	SET @SQLText=@SQLText+'	INNER JOIN #Stype s ON  a.stypeid=s.typeid	'+CHAR(13)
						IF @MDtypeid<>'00000' 	SET @SQLText=@SQLText+'	INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)
						SET @SQLText += '
						WHERE b.ifcheck = ''t'' 
							AND b.ifYearBill=''0''			--年节存标志
							AND b.draft = 0
							AND b.RedWord = 0
							AND b.billdate>='+char(39)+@StarDate+char(39)+'
							AND b.billdate<='+char(39)+@ENDDate+char(39)+'
						
						UNION ALL
						
						--发出商品退货单
						SELECT a.Qty - a.InvoiceQty AS Qty,
						a.NQty - a.InvoiceNQty AS NQty,
						CASE a.InvoiceQty
							WHEN 0 THEN a.total
							ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice
						END AS total,
						CASE a.InvoiceQty
							WHEN 0 THEN a.TaxTotal
							ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice
						END AS taxtotal,
						a.PtypeId 
						FROM SendBackBill AS a 
						INNER JOIN BillIndex AS b ON(A.BillNumberId = B.BillNumberId)
						'
						IF @MPTypeID='-99999' OR @PTypeID	NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #Ptype p on a.ptypeid=p.typeid '+CHAR(13)
						IF @MBTypeID='-99999' OR @MBTypeID2='-99999' OR @BTypeID NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #btype bt on b.btypeid=bt.typeid '+CHAR(13)
						IF @METypeID='-99999' SET @SQLText=@SQLText+' INNER JOIN #etype e on b.etypeid=e.typeid '+CHAR(13)
						IF @MKTypeID='-99999' OR @KTypeID NOT IN ('','00000','%')	SET @SQLText=@SQLText+' INNER JOIN #ktype k on a.ktypeid=k.typeid '+CHAR(13)
						IF @MStypeid<>'00000' OR @Stypeid <>''	SET @SQLText=@SQLText+'	INNER JOIN #Stype s ON  a.stypeid=s.typeid	'+CHAR(13)
						IF @MDtypeid<>'00000' 	SET @SQLText=@SQLText+'	INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)
						SET @SQLText += '
						WHERE b.ifcheck = ''t'' 
							AND b.ifYearBill=''0''			--年节存标志
							AND b.draft = 0
							AND b.RedWord = 0
							AND b.billdate>='+char(39)+@StarDate+char(39)+'
							AND b.billdate<='+char(39)+@ENDDate+char(39)+'
						
						UNION ALL
						--销售发货开票
						SELECT -B.Qty,
						-B.NQty,
						-B.total,
						-B.taxtotal,
						B.PTypeID 
						FROM ReceiptBill AS B
						INNER JOIN dbo.ReceiptBillIndex AS A ON(A.BillNumberID = B.BillNumberID AND A.BillType = B.BillType)
						'
						IF @MPTypeID='-99999' OR @PTypeID	NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #Ptype p on B.ptypeid=p.typeid '+CHAR(13)
						IF @MBTypeID='-99999' OR @MBTypeID2='-99999' OR @BTypeID NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #btype bt on a.btypeid=bt.typeid '+CHAR(13)
						IF @METypeID='-99999' SET @SQLText=@SQLText+' INNER JOIN #etype e on a.etypeid=e.typeid '+CHAR(13)
						IF @MStypeid<>'00000' OR @Stypeid <>''	SET @SQLText=@SQLText+'	INNER JOIN #Stype s ON  B.stypeid=s.typeid	'+CHAR(13)
						IF @MDtypeid<>'00000' 	SET @SQLText=@SQLText+'	INNER JOIN #dtype d ON  a.dtypeid=d.typeid	'+CHAR(13)
						SET @SQLText += '
						WHERE A.ifcheck = ''t'' 
							AND A.ifYearBill=''0''			--年节存标志
							AND A.draft = 0
							AND A.RedWord = 0
							AND A.BillType = 405
							AND A.billdate>='+char(39)+@StarDate+char(39)+'
							AND A.billdate<='+char(39)+@ENDDate+char(39)+'
						'
									
			SELECT @SQLText= @SQLText +'
					) as t
					 Group BY t.PtypeID
				) q ON q.PtypeID = p.typeid 
				INNER JOIN  #PtypeDetailALL c ON p.typeid=c.typeID 
				INNER JOIN ptype p1 on q.ptypeid=  p1.typeid
				'+@temptable+'
				WHERE	  p.sonnum =0 '+@SQL_UserCode+@SQL_FullName+''
			IF(@sortField<>'' and @sortType<>'')
			   SET @SQLText =@SQLText+' ORDER BY '+@sortField +' '+@sortType
			ELSE
			   SET @SQLText =@SQLText+' ORDER BY p.UserCode '
	END
	ELSE
	BEGIN
		SET @SQLText ='
			SELECT	p.TypeID AS PTypeID,
					p.UserCode AS UserCode,
					p.FullName AS FullName,
					p.SonNum,
					p.Unit1,
					p.Unit2,
					p.unitrate1,
					--q.Qty AS Qty,
					'+@tempqty+' as qty,
					u1.fullname baseunitfullname,--基本单位
					'+@assistantfullname+',--浮动单位
					'+@unitname+'
					'+@unitRelation+'
					q.nqty,
					q.Total As Total,
					q.TaxTotal As TaxTotal,
					price =case when q.Qty =0 then 0 else cast( q.Total as NUMERIC(24, 10))/ cast(('+@tempqty+')as NUMERIC(24, 10)) end,
					customassist=dbo.F_GetCustomAssist(p.TypeId, q.Qty)
			FROM	#Ptype p JOIN (
								SELECT 	ISNULL(SUM(-a.qty), 0) AS qty,
										isnull(SUM(-a.NQty), 0) AS nqty,
										isnull(SUM(-a.total), 0) AS Total,
										isnull(SUM(-a.TaxTotal), 0) AS TaxTotal,
										a.PtypeID AS ptypeid
	     						FROM 	inoutstocktable  a
								INNER JOIN billindex b on a.billnumberid=b.billnumberid 
			'
			IF @MPTypeID='-99999' OR @PTypeID	NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #Ptype p on a.ptypeid=p.typeid '+CHAR(13)
			IF @MBTypeID='-99999' OR @MBTypeID2='-99999' OR @BTypeID NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #btype bt on a.btypeid=bt.typeid '+CHAR(13)
			IF @METypeID='-99999' SET @SQLText=@SQLText+' INNER JOIN #etype e on a.etypeid=e.typeid '+CHAR(13)
			IF @MKTypeID='-99999' OR @KTypeID NOT IN ('','00000','%')	SET @SQLText=@SQLText+' INNER JOIN #ktype k on a.ktypeid=k.typeid '+CHAR(13)
			IF @MStypeid<>'00000' OR @Stypeid <>''	SET @SQLText=@SQLText+'	INNER JOIN #Stype s ON  a.stypeid=s.typeid	'+CHAR(13)
			IF @MDtypeid<>'00000' 	SET @SQLText=@SQLText+'	INNER JOIN #dtype d ON  a.dtypeid=d.typeid	'+CHAR(13)
			SET @SQLText=@SQLText+' 
								WHERE 	a.Audited=1 
										AND A.BillType IN (11,45,141,305,160,215,12,46)
										AND b.ifYearBill=''0''			--年节存标志
										--AND a.atypeid='+char(39)+'0000100001' +char(39)+'
										AND a.billdate>='+char(39)+@StarDate+char(39)+'
										AND a.billdate<='+char(39)+@ENDDate+char(39)
			SELECT @SQLText= @SQLText +'
					 Group BY a.PtypeID
				) q ON q.PtypeID = p.typeid 
				INNER JOIN  #PtypeDetailALL c ON p.typeid=c.typeID 
				INNER JOIN ptype p1 on q.ptypeid=  p1.typeid
				'+@temptable+'
				WHERE	  p.sonnum =0 '+@SQL_UserCode+@SQL_FullName+''
			IF(@sortField<>'' and @sortType<>'')
			   SET @SQLText =@SQLText+' ORDER BY '+@sortField +' '+@sortType
			ELSE
			   SET @SQLText =@SQLText+' ORDER BY p.UserCode '
	END

	--PRINT(@SQLText)
	EXEC(@SQLText)
END
------------------------------------------------------进货线性表----------------------------------------------------------------------

IF @unitvalue=0
BEGIN
 SELECT @tempqty='q.Qty/isnull(r3.rate,1) ',
		@unitname='u3.fullname as unitfullname,u5.fullname as assistantfullname,',
		@temptable =dbo.F_GetPtypeUnitsAndRates('p1','1,3,5','3'),
		@unitRelation='''1''+u3.fullname+''=''+convert(varchar(200),FLOOR(r3.rate))+u1.fullname as unitRelation,'
END
IF @unitvalue=1
BEGIN
 SELECT @tempqty='q.Qty/isnull(r2.rate,1)  ',
		@unitname='u2.fullname as unitfullname,u5.fullname as assistantfullname,',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,2,5','2'),
		@unitRelation='''1''+u2.fullname+''=''+convert(varchar(200),FLOOR(r2.rate))+u1.fullname as unitRelation,'
END
IF @unitvalue=2
BEGIN
 SELECT @tempqty='q.Qty/isnull(r4.rate,1) ',
		@unitname='u4.fullname as unitfullname,u5.fullname as assistantfullname,',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,4,5','4'),
		@unitRelation='''1''+u4.fullname+''=''+convert(varchar(200),FLOOR(r4.rate))+u1.fullname as unitRelation,'
END
IF @unitvalue=3
BEGIN
 SELECT @tempqty='q.Qty  ',
		@unitname='u1.fullname as unitfullname,u5.fullname as assistantfullname,',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,5','1'),
		@unitRelation='''1''+u1.fullname+''=''+convert(varchar(200),FLOOR(r1.rate))+u1.fullname as unitRelation,'
END 

IF @QueryType='InGoods'
/**********************************
*进货线性表检查btypeid,ktypeid,etypeid,ktypeid 权限
*
*
*
*
*/

BEGIN
	SELECT @SQLText='
				SELECT 
						p.TypeId AS PtypeId,
						p.UserCode As UserCode,
						p.fullname As FullName,
						--q.Qty As Qty,
						'+@tempqty+' as qty,
						q.NQty AS NQty,--浮动数量
						c.baseunitfullname,--基本单位
		                c.assistantfullname,--浮动单位
		                '+@unitname+'
		                '+@unitRelation+'
						q.Total  As Total,
						q.TaxTotal As TaxTotal,
					
			price =case when q.Qty =0 then 0 else cast( q.Total as NUMERIC(24, 10))/ cast(('+@tempqty+')as NUMERIC(24, 10)) end,				
						customassist=dbo.F_GetCustomAssist(p.TypeId, q.Qty)
				FROM #Ptype p JOIN
				 (
					SELECT 
						isnull(SUM(case a.billtype when  145 then -a.qty ELSE a.qty END ), 0) AS qty,
						isnull(SUM(case a.billtype when  145 then -a.nqty ELSE a.nqty END ), 0) AS nqty,
						isnull(SUM(case a.billtype when  145 then -a.total ELSE a.total END), 0) AS Total ,
						isnull(SUM(case a.billtype when  145 then -a.TaxTotal ELSE a.TaxTotal END), 0) AS TaxTotal ,
						a.PtypeID
				    FROM inoutstocktable  a
					INNER JOIN billindex b ON a.billnumberid=b.billnumberid 
	'
	IF @MPTypeID='-99999' OR @PTypeID	NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #Ptype p on a.ptypeid=p.typeid '+CHAR(13)
	IF @MBTypeID='-99999' OR @MBTypeID2='-99999' OR @BTypeID NOT IN ('','00000')	SET @SQLText=@SQLText+' INNER JOIN #btype bt on a.btypeid=bt.typeid '+CHAR(13)
	IF @METypeID='-99999' SET @SQLText=@SQLText+' INNER JOIN #etype e on a.etypeid=e.typeid '+CHAR(13)
	IF @MKTypeID='-99999' OR @KTypeID NOT IN ('','00000','%')	SET @SQLText=@SQLText+' INNER JOIN #ktype k on a.ktypeid=k.typeid '+CHAR(13)
	IF @MStypeid<>'00000' OR @Stypeid <>''	SET @SQLText=@SQLText+'	INNER JOIN #Stype s ON  a.stypeid=s.typeid	'+CHAR(13)
	IF @MDtypeid<>'00000' 	SET @SQLText=@SQLText+'	INNER JOIN #dtype d ON  b.dtypeid=d.typeid	'+CHAR(13)

	SET @SQLText=@SQLText+' 
				    WHERE  b.redwORd=0 
						  AND (a.billtype = 34 OR a.billtype =6 OR a.billtype =145  OR a.BillType = 161)
			  			  AND b.ifYearBill=''0''			--年节存标志
			  			  AND a.ptypeid <>'+char(39)+'0'+char(39)+' 
						--  AND a.atypeid='+char(39)+'0000100001' +char(39)+'
						  AND a.billdate>='+char(39)+@StarDate+char(39)+'
						  AND a.billdate<='+char(39)+@ENDDate+char(39)

	SET @SQLText = @SQLText +' 
						Group BY a.PtypeID
					) q 
				 ON (q.ptypeid = p.typeid  )
				 LEFT JOIN  #PtypeDetailALL c ON p.typeid=c.typeID
				 INNER JOIN ptype p1 on q.ptypeid=  p1.typeid
				 '+@temptable+'
				 WHERE p.sonnum =0 '+@SQL_UserCode+@SQL_FullName+'
				 ORDER BY p.usercode'
--print @SQLText
EXEC(@SQLText)
END
------------------------------------------------------往来单位线性表----------------------------------------------------------------------
ELSE IF @QueryType='InOut'
BEGIN
 SELECT @SQLText='SELECT *,(artotal)As arTotal01,(aptotal)As apTotal01 FROM btype '
  +' WHERE sONnum = 0'
  +' AND deleted = 0'
  +' AND UserCode like '''+'%'+@UserCode+'%'+''''
  +' AND FullName like '''+'%'+@FullName+'%'+''''
IF @NoZero=0
 SELECT @SQLText=@SQLText  +' AND (artotal+artotal00+aptotal+aptotal00) <> 0'
IF @PtypeId <> '00000' SELECT @SQLText = @SQLText + ' AND typeId Like ''' + @PtypeId + '%'''
SELECT @SQLText=@SQLText+' ORDER BY usercode'
SELECT @PageCount=@@ROWCOUNT
EXEC(@SQLText)
END 
------------------------------------------------------往来单位线性表(In)----------------------------------------------------------------------
ELSE IF @QueryType='In'
BEGIN
 SELECT @SQLText='SELECT a.usercode,a.fullname,a.parid,a.sONnum,a.leveal,a.typeid,isnull(a.arlimit,0) as arlimit, '
		+'a.artotal-a.aptotal as arTotal01,0 as apTotal01 '
		+'FROM btype a  '
		+' WHERE a.sONnum = 0'
		+' AND a.deleted = 0'
		+' AND a.UserCode like '''+'%'+@UserCode+'%'+''''
		+' AND a.FullName like '''+'%'+@FullName+'%'+''''
		+' AND left(a.typeid,5)=''00001'' '
IF @NoZero=0
 SELECT @SQLText=@SQLText+' AND (artotal+artotal00+aptotal+aptotal00) <> 0'
IF @PtypeId = '' 
	SELECT @PtypeID='00001'	
SELECT @SQLText = @SQLText + ' AND a.typeId Like ''' + @PtypeId + '%'''
SELECT @SQlText=@SqlText+' ORDER BY a.usercode '
SELECT @PageCount=@@ROWCOUNT
EXEC(@SQLText)
END 
------------------------------------------------------往来单位线性表(out)----------------------------------------------------------------------
ELSE IF @QueryType='Out'
BEGIN
 SELECT @SQLText='SELECT a.usercode,a.fullname,a.parid,a.sONnum,a.leveal,a.typeid,isnull(a.arlimit,0) as arlimit, '
		+'0 as arTotal01,a.aptotal-a.artotal as apTotal01 '
		+'FROM btype a  '
		+' WHERE a.sONnum = 0'
		+' AND a.deleted = 0'
		+' AND a.UserCode like '''+'%'+@UserCode+'%'+''''
		+' AND a.FullName like '''+'%'+@FullName+'%'+''''
		+' AND left(a.typeid,5)=''00002'' '
IF @NoZero=0
 SELECT @SQLText=@SQLText+' AND (artotal+artotal00+aptotal+aptotal00) <> 0'
IF @PtypeId = '' 
	SELECT @PtypeID='00001'	
SELECT @SQLText = @SQLText + ' AND a.typeId Like ''' + @PtypeId + '%'''
SELECT @SQlText=@SqlText+' ORDER BY a.usercode '
SELECT @PageCount=@@ROWCOUNT
EXEC(@SQLText)
END

DROP TABLE #Btype,#Etype,#Ktype,#stype








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryLocal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryLocal]
GO









/****** Object:  Stored Procedure dbo.GP_QueryLocal    Script Date: 2004-2-13 16:33:00 ******/

/****** Object:  Stored Procedure dbo.GP_QueryLocal    Script Date: 2004-2-11 13:57:42 ******/

/****** Object:  Stored Procedure dbo.GP_QueryLocal    Script Date: 2004-2-9 16:13:30 ******/


/****** Object:  Stored Procedure dbo.GP_QueryLocal    Script Date: 2003-12-18 9:58:36 ******/
/*
	--编程：Roamer Wu
	--时间：2003-12-29
	--功能：货位选择
*/
CREATE     PROCEDURE GP_QueryLocal
(
@OperatorID		 Varchar(50),		-- 审核人 ID 值
@StockName		 Varchar(50),
@ParId			 Varchar(50),
@UserCode		 Varchar(50),		--商品编码
@IsShowZero		 Int
)
--@encode$--
AS
set nocount on

--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

Declare @KTypeId varchar(50),@PTypeId varchar(50)

Select @PTypeId = TypeId From PType Where UserCode = @UserCode

Select @KTypeId = TypeId from Stock Where FullName = @StockName AND Deleted = 0 AND SonNum = 0

IF Not  (@KTypeid Like @MKTypeId + '%' OR @MKTypeId = '00000')
	Return -1		---没有此仓库的权限

IF NOT (@PTypeId Like @MPTypeId + '%' OR @PTypeId = '00000' OR @PTypeId = '')
	Return -2		--没有此商品权限

--IF @IsShowZero = 0
--BEGIN
	If @Parid = ''
		Set @Parid = '00000'
	
	Select	 a.* ,
		 Case a.sonnum
			 When 0 THEN
				 IsNull(b.QTY,0)
			 Else
				 (
				 Select IsNull(Sum(c.QTY),0)
				 From GoodsLocal c
				 Where c.LTypeId Like a.TypeId + '%'
				 )
		 END
		 as QTY
	
	From LType a
	
	LEFT JOIN GoodsLocal b
	ON	 a.TypeId = b.LTypeId
		 AND b.PTypeId = @PTypeId
	
	Where	 a.KTypeId = @KTypeId 
		 AND a.Deleted = 0
		 AND a.Parid = @ParId
	ORDER BY a.UserCode
--END
/*
ELSE
BEGIN
	If @Parid = ''
		Set @Parid = '00000'
	
	Select	 a.TypeId,a.KTypeId,a.UserCode,a.FullName,a.SonNum ,
		 Sum(IsNull(b.QTY,0)) as QTY
	
	From LType a
	
	Right JOIN GoodsLocal b
	ON	 a.TypeId = b.LTypeId
		 AND b.PTypeId = @PTypeId
	
	Where	 a.KTypeId = @KTypeId 
		 AND a.Deleted = 0
		 AND a.Parid = @ParId
		 AND b.LTypeId like '0000%'
		 AND b.Qty <> 0
	Group By a.TypeId,a.KTypeId,a.UserCode,a.FullName,a.SonNum
	ORDER BY a.UserCode
END

ELSE
BEGIN
	If @Parid = ''
		Set @Parid = '00000'
	
	Select	 a.* ,
		 IsNull(b.QTY,0) as QTY
	
	From LType a
	
	INNER JOIN	(	Select LTypeID,IsNull(Sum(Qty),0)
				From GoodsLocal
				
			) b
	ON	 a.TypeId = b.LTypeId
		 AND b.PTypeId = @PTypeId
	
	Where	 a.KTypeId = @KTypeId 
		 AND a.Deleted = 0
		 AND a.Parid = @ParId
		 AND b.LTypeId like a.TypeId + '%'
		 AND b.Qty <> 0
	Group By a.TypeId,a.KTypeId,a.UserCode,a.FullName,a.SonNum
	ORDER BY a.UserCode
END
*/








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryMoveInPTypeInTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryMoveInPTypeInTime]
GO









/*
	作者：刘戈 引用 谢吉康 GP_QueryPTypeInTime
	日期：2003-12-31
	描述：调拨单仓库数量实时查询
    优化：haiquan 2007-9-9
*/

CREATE                 PROCEDURE dbo.GP_QueryMoveInPTypeInTime

(
	@OperatorID		VARCHAR(50),	--操作员ID
	@PUserCode 		VARCHAR(8000),	--商品ID
    @outKUserCode    VARCHAR(256),	--出货仓库ID
	@inKUserCode		VARCHAR(256)	--入货仓库ID

)
--@encode$--
AS

	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #plist(
	[id] [numeric](10, 0) IDENTITY (1, 1),
	typeid 			varchar(100),
	Usercode  		varchar (26),
	FullName		VARCHAR(255),		
	SonNum			INT,
	PrePrice1		 NUMERIC(24, 10) ,
	PrePrice2		 NUMERIC(24, 10) ,
	PrePrice3		 NUMERIC(24, 10) ,
	PrePrice4		 NUMERIC(24, 10) 
)
Insert INTO #plist SELECT  '',a,'',null,null,null,null,null FROM F_Split(@PUserCode,'|')


update #plist 
set typeid=p.typeid,
	Usercode=p.usercode,
	FullName=p.FullName,		
	SonNum=p.SonNum,
	PrePrice1=p.PrePrice1	,
	PrePrice2=p.PrePrice2,
	PrePrice3=p.PrePrice3,
	PrePrice4=p.PrePrice4
from ptype p,#plist a 
where p.usercode=a.usercode 
	and deleted=0 
	and p.sonnum=0
	and p.typeid like @MPtypeid+'%'

delete from #plist where typeid='' --删除不在权限范围内的，或者错误的商品

select distinct typeid into #plist2 from #plist --取出唯一typeid避免重复统计

	declare @strKtypeid varchar(50)
	declare @strKtypeid2 varchar(50)
			
	select @strKtypeid2=Rtrim(Ltrim(@inKUserCode))
	select @strKtypeid=Rtrim(Ltrim(@outKUserCode))




/************************************************/

/*缩小billindex*/

SELECT Billnumberid,Draft,Ktypeid,Ktypeid2 
			 Into   #BillIndex
			 FROM   BillIndex
			 WHERE  draft=1

			 AND (  
					((ktypeid=@strKtypeid AND ktypeid LIKE @MKtypeid+'%')
				 OR (ktypeid2=@strKtypeid AND ktypeid2 LIKE @MKtypeid+'%'))

				 OR ((ktypeid=@strKtypeid2 AND ktypeid LIKE @MKtypeid+'%')
				 OR (ktypeid2=@strKtypeid2 AND ktypeid2 LIKE @MKtypeid+'%'))
				 )
			 AND Billtype in (34,45,142,144,14,126,11,305,140,146,6,17,21,9,139,17,21,161,16,157,160)
--return

/****************************************************/

CREATE TABLE #BillTable(
	typeid varchar(100),
	Billnumberid int,
	InOrOut char(1),
	Billtype int,
	Canqty  NUMERIC(24, 10) 
) 

--select * from #billIndex

--return



Insert into #BillTable
		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				34 as Billtype,
				Bill.qty as CanQTY
		FROM 	BuyBill bill,   --采购入库单
				#plist2 p 
		WHERE  Bill.ptypeid = p.typeid
		--	   AND Billnumberid in (select billnumberid from #BillIndex)
	--		   AND Bi.Ktypeid=@strKtypeid 
	--		   AND Bi.ktypeid LIKE @MKtypeid+'%'




Insert into #BillTable		
		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				45 as Billtype,
				Bill.qty as CanQTY
		FROM 	SaleBackBill bill,  --销售退货单
				#plist2 p 
		WHERE  Bill.ptypeid = p.typeid
		--	   AND Billnumberid in (select billnumberid from #BillIndex)
	--		    AND Bi.Ktypeid=@strKtypeid 
	--			AND Bi.ktypeid LIKE @MKtypeid+'%'




Insert into #BillTable


		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				Bill.type as Billtype,
				Bill.qty as CanQTY
		FROM 	CommissionBill bill,  --委托代销退货，受托代销收货单
				#plist2 p 
        WHERE  Bill.ptypeid = p.typeid
		--	   AND Billnumberid in (select billnumberid from #BillIndex)
        --     AND Bi.Ktypeid=@strKtypeid 
		--	   AND Bi.ktypeid LIKE @MKtypeid+'%'
			   AND (bill.type=142 or bill.type=144)




Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				14 as Billtype,
				Bill.qty as CanQTY
		FROM 	overflowBill bill,  --报溢单
				#plist2 p 
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
			--  AND Bi.Ktypeid=@strKtypeid 
			--	AND Bi.ktypeid LIKE @MKtypeid+'%'




Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				Bill.InOrOut as InOrOut,
				16 as Billtype,
				Bill.qty as CanQTY
		FROM 	DisassembleBill  bill,  --生产拆装单
				#plist2 p    
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
			  	AND bill.InOrOut='I'
		--		AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%'








Insert into #BillTable


		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				Bill.InOrOut as InOrOut,
				160 as Billtype,
				Bill.qty as CanQTY
		FROM 	saleGoodsExchangeBill  bill,  --销售换货单 入库部分
				#plist2 p       
        WHERE  Bill.ptypeid = p.typeid
		--	   AND Billnumberid in (select billnumberid from #BillIndex)
		--	   AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%' --和其他单据不一样
			   AND InOrOut='I'



Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				InOrOut as InOrOut,
				160 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	saleGoodsExchangeBill  bill,  --销售换货单 出库部分
				#plist2 p 	       
        WHERE  Bill.ptypeid = p.typeid
		--	   AND Billnumberid in (select billnumberid from #BillIndex)
		--	   AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%'
			   AND InOrOut='O'





Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Bill.Billnumberid,
				'' as InOrOut,
				17 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	movebill  bill,  --同价调拨单
				#plist2 p,
				#billindex Bi 		      
        WHERE  Bill.ptypeid = p.typeid
			   AND Bi.billnumberid=bill.billnumberid
--			   AND Billnumberid in (select billnumberid from #BillIndex)
			   AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'




Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				bill.Billnumberid,
				'' as InOrOut,
				21 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	MoveBjBill  bill,  --变价调拨单
				#plist2 p,
				#billindex Bi 	        
        WHERE  Bill.ptypeid = p.typeid
	--		   AND Billnumberid in (select billnumberid from #BillIndex)
			   AND Bi.billnumberid=bill.billnumberid
			   AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'



Insert into #BillTable


		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				126 as Billtype,
				Bill.qty as CanQTY
		FROM 	GivemeBill  bill,  --获赠单
				#plist2 p       
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
		--	    AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'



Insert into #BillTable


		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				Bill.InOrOut as InOrOut,
				157 as Billtype,
				Bill.qty as CanQTY
		FROM 	RepairDealDetail  bill,  --维修受理单 入库部分
				#plist2 p 	    
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
		--	    AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%'
				AND InOrOut='I'


---------以下数量为负---------------


Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				InOrOut as InOrOut,
				157 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	RepairDealDetail  bill,  --维修受理单 出库部分
				#plist2 p       
        WHERE  Bill.ptypeid = p.typeid
		--	   AND Billnumberid in (select billnumberid from #BillIndex)
		--	    AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'
				AND InOrOut='O'



Insert into #BillTable


		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				11 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	salebill bill,  --销售出库单
				#plist2 p 		      
        WHERE  Bill.ptypeid = p.typeid
		--	   AND Billnumberid in (select billnumberid from #BillIndex)
		--	   AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'		   





Insert into #BillTable


		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				305 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	retailBill bill,  --零售单
				#plist2 p 	      
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
		--	   AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'




Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				Bill.type as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	CommissionBill bill,  --委托代销发货,受托代销退货
				#plist2 p 	      
        WHERE  Bill.ptypeid = p.typeid
		--	   AND Billnumberid in (select billnumberid from #BillIndex)
			   AND (bill.type=140 or bill.type=146)
		--	   AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'			   




Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				6 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	buybackbill bill,  --采购退货单
				#plist2 p 	      
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
		--	   AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'




Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				9 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	LoseBill bill,  --报损单
				#plist2 p 	      
        WHERE  Bill.ptypeid = p.typeid
			  -- AND Billnumberid in (select billnumberid from #BillIndex)
		--	   	AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'






Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				Bill.InOrOut as InOrOut,
				16 as Billtype, 
				-1*Bill.qty as CanQTY
		FROM 	DisassembleBill  bill,  --生产拆装单
				#plist2 p 	      
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
		--	   AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'
			   AND bill.InOrOut='O'




Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Bill.Billnumberid,
				'' as InOrOut,
				17 as Billtype,
				Bill.qty as CanQTY
		FROM 	movebill  bill,  --同价调拨单
				#plist2 p,
				#Billindex Bi 	    	      
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
			   And Bill.BillnumberId=Bi.BillNumberID
			   AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%'


Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Bill.Billnumberid,
				'' as InOrOut,
				21 as Billtype,
				Bill.qty as CanQTY
		FROM 	MoveBjBill  bill,  --变价调拨单
				#plist2 p,
				#Billindex Bi 	      
        WHERE  Bill.ptypeid = p.typeid
			 --  AND Billnumberid in (select billnumberid from #BillIndex)
			   And Bill.BillnumberId=Bi.BillNumberID
		       AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%'




Insert into #BillTable


		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				Bill.InOrOut as InOrOut,
				161 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	buyGoodsExchangeBill  bill,  --采购换货单 出库部分
				#plist2 p       
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
		--	   	AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'
			    AND bill.InOrOut='O'



Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				Bill.InOrOut as InOrOut,
				161 as Billtype,
				Bill.qty as CanQTY
		FROM 	buyGoodsExchangeBill  bill,  --采购换货单 入库部分
				#plist2 p       
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
		--		AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%'
			    AND bill.InOrOut='I'



Insert into #BillTable


		SELECT 	Bill.ptypeid as typeid,
				Billnumberid,
				'' as InOrOut,
				139 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	GiveBill  bill,  --赠送单
				#plist2 p 	      
        WHERE  Bill.ptypeid = p.typeid
			 --  AND Billnumberid in (select billnumberid from #BillIndex)
		--	  	AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%'
--select * from #BillTable
--return

SELECT typeid,SUM(CanQTY) as CanQTY
INTO #Tablecan 
FROM #BillTable a,#BillIndex Bi

WHERE a.Billnumberid=Bi.Billnumberid
	  AND ((Billtype in (34,45,142,144,14,126,11,305,140,146,6,17,21,9,139) AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%')
	  OR  (Billtype in (17,21) AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%')
	  OR  (Billtype in (161,16,157) AND InOrOut='I' AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%')
	  OR  (Billtype in (161,16,157) AND InOrOut='O' AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%')
	  OR  (Billtype=160 AND InOrOut='O' AND Bi.Ktypeid2=@strKtypeid AND Bi.ktypeid2 LIKE @MKtypeid+'%')
	  OR  (Billtype=160 AND InOrOut='I' AND Bi.Ktypeid=@strKtypeid AND Bi.ktypeid LIKE @MKtypeid+'%')
)


GROUP BY typeid


delete from #BillTable where billtype=17 or billtype=21


/*特殊处理变价调拨，同价调拨单*/
Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Bill.Billnumberid,
				'' as InOrOut,
				17 as Billtype,
				Bill.qty as CanQTY
		FROM 	movebill  bill,  --同价调拨单
				#plist2 p,
				#Billindex Bi 	    	      
        WHERE  Bill.ptypeid = p.typeid
			--   AND Billnumberid in (select billnumberid from #BillIndex)
			   And Bill.BillnumberId=Bi.BillNumberID
			   AND Bi.Ktypeid2=@strKtypeid2 AND Bi.ktypeid2 LIKE @MKtypeid+'%'


Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Bill.Billnumberid,
				'' as InOrOut,
				21 as Billtype,
				Bill.qty as CanQTY
		FROM 	MoveBjBill  bill,  --变价调拨单
				#plist2 p,
				#Billindex Bi 	      
        WHERE  Bill.ptypeid = p.typeid
			 --  AND Billnumberid in (select billnumberid from #BillIndex)
			   And Bill.BillnumberId=Bi.BillNumberID
		       AND Bi.Ktypeid2=@strKtypeid2 AND Bi.ktypeid2 LIKE @MKtypeid+'%'



Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				Bill.Billnumberid,
				'' as InOrOut,
				17 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	movebill  bill,  --同价调拨单
				#plist2 p,
				#billindex Bi 		      
        WHERE  Bill.ptypeid = p.typeid
			   AND Bi.billnumberid=bill.billnumberid
--			   AND Billnumberid in (select billnumberid from #BillIndex)
			   AND Bi.Ktypeid=@strKtypeid2 AND Bi.ktypeid LIKE @MKtypeid+'%'




Insert into #BillTable

		SELECT 	Bill.ptypeid as typeid,
				bill.Billnumberid,
				'' as InOrOut,
				21 as Billtype,
				-1*Bill.qty as CanQTY
		FROM 	MoveBjBill  bill,  --变价调拨单
				#plist2 p,
				#billindex Bi 	        
        WHERE  Bill.ptypeid = p.typeid
	--		   AND Billnumberid in (select billnumberid from #BillIndex)
			   AND Bi.billnumberid=bill.billnumberid
			   AND Bi.Ktypeid=@strKtypeid2 AND Bi.ktypeid LIKE @MKtypeid+'%'





SELECT typeid,SUM(CanQTY) as CanQTY
INTO #Tablecan2 
FROM #BillTable a,#BillIndex Bi

WHERE a.Billnumberid=Bi.Billnumberid
	  AND ((Billtype in (34,45,142,144,14,126,11,305,140,146,6,17,21,9,139) AND Bi.Ktypeid=@strKtypeid2 AND Bi.ktypeid LIKE @MKtypeid+'%')
	  OR  (Billtype in (17,21) AND Bi.Ktypeid2=@strKtypeid2 AND Bi.ktypeid2 LIKE @MKtypeid+'%')
	  OR  (Billtype in (161,16,157) AND InOrOut='I' AND Bi.Ktypeid2=@strKtypeid2 AND Bi.ktypeid2 LIKE @MKtypeid+'%')
	  OR  (Billtype in (161,16,157) AND InOrOut='O' AND Bi.Ktypeid=@strKtypeid2 AND Bi.ktypeid LIKE @MKtypeid+'%')
	  OR  (Billtype=160 AND InOrOut='O' AND Bi.Ktypeid2=@strKtypeid2 AND Bi.ktypeid2 LIKE @MKtypeid+'%')
	  OR  (Billtype=160 AND InOrOut='I' AND Bi.Ktypeid=@strKtypeid2 AND Bi.ktypeid LIKE @MKtypeid+'%')
)


Group by typeid


------------------end草稿中商品的数量------


		SELECT	P.TypeID,
				IsNull(Sum(A.Qty),0) As outQty
		into #table1
			FROM 	#plist2 p
			LEFT 	JOIN 
				(
					SELECT 	PTypeID,
						  	KTypeID,
							Qty
					FROM 	GoodsStocks
					WHERE   KTypeID  LIKE @outKUserCode+'%'
							AND KTypeID  LIKE @MKTypeID+'%'
				)A ON P.TypeID=A.PtypeID
	
			GROUP BY P.TypeID





			SELECT	P.TypeID,
					IsNull(Sum(a.Qty),0) As inQty
			into #table2
            FROM 	#plist2 P        
			LEFT 	JOIN 
				(
					SELECT 	PTypeID,
						  	KTypeID,
							Qty
					FROM 	GoodsStocks
					WHERE   KTypeID  LIKE @inKUserCode
							AND KTypeID  LIKE @MKTypeID+'%'
				)A ON P.TypeID=A.PtypeID
			 					
			GROUP BY P.TypeID

--haiquan-*****************************
			SELECT	P.TypeID as typeid,
					IsNull(Sum(A.canQty),0) As outCanQty 
			into #table4
			FROM 	#plist2 P
			LEFT JOIN
			#Tablecan A
			ON P.TypeID=A.typeID

			GROUP BY P.TypeID



			SELECT	P.TypeID as typeid,
					IsNull(Sum(A.canQty),0) As INCanQty 
			into #table5
			FROM 	#plist2 P
			LEFT 	JOIN 
			#Tablecan2 A
			ON P.TypeID=A.typeID

			GROUP BY P.TypeID



			SELECT	P.UserCode,
					P.FullName,
					P.TypeID,
					IsNull(p.SonNum,0) AS SonNum,			
					IsNull(p.PrePrice1,0) AS PrePrice1,		
					IsNull(p.PrePrice2,0) AS PrePrice2,		
					IsNull(p.PrePrice3,0) AS PrePrice3,		
					IsNull(p.PrePrice4,0) AS PrePrice4,	
					IsNull(outQty,0) AS outQty,			
					IsNull(inQty,0) AS inQty,
					isnull(OutCanQty,0)+IsNull(outQty,0) AS OutCanQty,
					isnull(inCanQty,0)+IsNull(inQty,0) AS inCanQty
			FROM 	#Plist P
			left	JOIN #table1
				  A On A.TypeID=P.TypeID
			left 	JOIN #table2
				  B On B.TypeID=P.TypeID
			left 	JOIN #table4
				  C On C.TypeID=P.TypeID
			left 	JOIN #table5
				  D On D.TypeID=P.TypeID
			left 	JOIN #plist
				  E On E.TypeID=P.TypeID
				
			GROUP  BY
					P.TypeID,
					P.SonNum,
					P.UserCode,
					P.FullName,
 					outQty,
					inQty,
					OutCanQty,
					inCanQty,
                    P.PrePrice1,
					P.PrePrice2,
					P.PrePrice3,
					P.PrePrice4,
					P.[id]
			ORder BY P.[id]


--select * from #table3
--return


		DROP TABLE #table1
		DROP TABLE #table2
		DROP TABLE #table4
		DROP TABLE #table5
		DROP TABLE #tablecan
		DROP TABLE #tablecan2
		DROP TABLE #Plist
		DROP TABLE #plist2

			

	
		--PRINT(@SQL)	
		--EXEC(@SQL)



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryMoveInPTypeInTime_yyi]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryMoveInPTypeInTime_yyi]
GO
















/*
	作者：刘戈 引用 谢吉康 GP_QueryPTypeInTime
	日期：2003-12-31
	描述：调拨单仓库数量实时查询
*/

Create      PROCEDURE dbo.GP_QueryMoveInPTypeInTime_yyi 

(
	@OperatorID		VARCHAR(50),	--操作员ID
	@PUserCode 		VARCHAR(8000),	--商品ID
	@inKUserCode		VARCHAR(256),	--入货仓库ID
    @outKUserCode    VARCHAR(256)	--出货仓库ID
)
--@encode$--
AS
--exec GP_QueryMoveInPTypeInTime_yyi '00001','my002,my001,,,,,,,,,','00055','00055'
	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @szPUserCode VARCHAR(8000)
	DECLARE @i INT
	DECLARE @SQL VARCHAR(8000)
BEGIN
	SELECT @szPUserCode = @PUserCode
	SELECT @i=charindex(',',@PUserCode)  -- 取得'，'的位置常量
		
			SELECT	P.TypeID,
					IsNull(Sum(A.Qty),0) As outQty Into #table1
			FROM 	PType P
			LEFT 	JOIN 
				(
					SELECT 	PTypeID,
						  	KTypeID,
							Qty
					FROM 	GoodsStocks
					WHERE   KTypeID  LIKE @inKUserCode+'%'
							AND KTypeID  LIKE @MKTypeID+'%'
				)A ON P.TypeID=LEFT(A.PtypeID,len(P.Typeid))
			
			Where   P.SonNum = 0
					AND P.Deleted = 0
					--AND ( P.UserCode LIKE (@PUserCode+',%') Or P.UserCode LIKE ('%,'+@PUserCode) )	
					AND ( @PUserCode LIKE ('%,'+P.UserCode+',%') Or @PUserCode LIKE ('%,'+P.UserCode) Or @PUserCode LIKE (P.UserCode+',%')  )
					AND P.TypeID  LIKE @MPTypeID+'%'

			GROUP BY P.TypeID

			SELECT	P.TypeID,
					IsNull(Sum(a.Qty),0) As inQty Into #table2
            FROM 	PType P        
			LEFT 	JOIN 
				(
					SELECT 	PTypeID,
						  	KTypeID,
							Qty
					FROM 	GoodsStocks
					WHERE   KTypeID  LIKE @outKUserCode
							AND KTypeID  LIKE @MKTypeID+'%'
				)A ON P.TypeID=LEFT(A.PtypeID,len(P.Typeid))
			
			Where   P.SonNum = 0
					AND P.Deleted = 0
					AND ( @PUserCode LIKE ('%,'+P.UserCode+',%') Or @PUserCode LIKE ('%,'+P.UserCode) Or @PUserCode LIKE (P.UserCode+',%')  )					
					AND P.TypeID  LIKE @MPTypeID+'%'

			GROUP BY P.TypeID

		CREATE TABLE #table3
		(
			UserCode		VARCHAR(255),
			FullName		VARCHAR(255),
			TypeID			VARCHAR(100),
			SonNum			INT,
			PrePrice1		 NUMERIC(24, 10) ,
			PrePrice2		 NUMERIC(24, 10) ,
			PrePrice3		 NUMERIC(24, 10) ,
			PrePrice4		 NUMERIC(24, 10) ,
			outQty			 NUMERIC(24, 10) ,
			inQty			 NUMERIC(24, 10) 
		)
		
WHILE @i>=1
BEGIN
		--print @szPUserCode
		SET @szPUserCode = LEFT(@PUserCode,@i-1)
		INSERT INTO #table3
			SELECT	P.UserCode,
					P.FullName,
					P.TypeID,
					P.SonNum,
					P.PrePrice1,
					P.PrePrice2,
					P.PrePrice3,
					P.PrePrice4,				
                    outQty,
					inQty        
			FROM 	PType P
			LEFT 	JOIN #table1
				  A On A.TypeID=P.TypeID
            LEFT 	JOIN #table2
                  B On B.TypeID=P.TypeID
				
            WHERE 	P.SonNum = 0
					AND P.Deleted = 0
					AND @szPUserCode LIKE P.UserCode
					AND P.TypeID  LIKE @MPTypeID+'%'
			GROUP  BY
					P.TypeID,
					P.SonNum,
					P.UserCode,
					P.FullName,
					outQty,
                    
					inQty,
                    P.PrePrice1,
					P.PrePrice2,
					P.PrePrice3,
					P.PrePrice4


	SET @PUserCode=SUBSTRING(@PUserCode,@i+1,len(@PUserCode)-@i)
	SET @i=charindex(',',@PUserCode)

END
		SELECT * FROM #table3
		DROP TABLE #table3
		--PRINT(@SQL)	
		--EXEC(@SQL)
END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryMultiEmployee]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryMultiEmployee]
GO












/*
	作者：谢吉康
	日期：2003-11-28
	描述：多级仓库的查询数型表
*/
CREATE     PROCEDURE GP_QueryMultiEmployee
(
	@OperatorID		VARCHAR(50),
	@StartDate		VARCHAR(20),
	@PTypeID		VARCHAR(50),
	@KTypeID		VARCHAR(800),
	@UserCode		VARCHAR(80),
	@FullName		VARCHAR(80),

	@szPEntryCode	VARCHAR(200),			--商品条码
	@szPStandard	VARCHAR(200),			--商品规格
	@szPType		VARCHAR(200),			--商品型号
	@szPArea		VARCHAR(200)			--商品产地

)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)
	SELECT  @SQL = ''

	DECLARE @PSonNum INT
	DECLARE @KSonNum INT

	DECLARE @PTypeIDmx	VARCHAR(50)	--LEFT JOIN 中使用的PTypeID
	DECLARE @KTypeIDmx	VARCHAR(50)	--LEFT JOIN 中使用的KTypeID

	IF @PTypeID = '00000'
		BEGIN
			SELECT @PTypeIDmx = '%'
			SELECT @PSonNum = 1
		END
	ELSE
		BEGIN
			SELECT @PSonNum = SonNum FROM PType WHERE TypeID = @PTypeID AND Deleted = 0		
			SELECT @PTypeIDmx = @PTypeID
		END

	IF @KTypeID = '00000'
		BEGIN
			SELECT @KTypeIDmx = '%'			
			SELECT @KSonNum = 1
		END
	ELSE
		SELECT @KSonNum = SonNum FROM Employee WHERE TypeID = @KTypeID AND Deleted = 0	

--=========================================================================================================当前库存状况表
IF IsDate(@StartDate)<>1
	BEGIN
		SELECT @SQL = '
				SELECT	a.typeid,
						a.fullname,
						a.usercode,
						a.EntryCode,
						a.Standard,
						a.Type,
						a.Area,
						a.sonnum,
						a.leveal,
						a.parid,
						a.unit1,
						a.unit2,
						a.unitrate1,
						ISNULL(SUM(d.qty),0) AS qty,
						ISNULL(SUM(d.total),0) AS total,
						CAST(ISNULL(SUM(d.total)/CASE WHEN SUM(d.qty)=0 THEN NULL ELSE SUM(d.qty) END ,0) AS  NUMERIC(24, 10) ) AS price,
						ISNULL(SUM(d.LENDqty),0) AS LENDqty,
						ISNULL(SUM(d.Borrowqty),0) AS Borrowqty,
						ISNULL(SUM(d.WnQty),0) AS WnQty,
						ISNULL(SUM(d.SnQty),0) AS SnQty,
						ISNULL(SUM(d.qty),0)-ISNULL(SUM(d.lENDqty),0)+ISNULL(SUM(d.borrowqty),0) AS sjczqty
				FROM ptype a 
				LEFT JOIN
				(
					SELECT	g.ptypeid,
							SUM(g.qty) AS qty,
							SUM(g.total) AS total,
							0 AS LENDqty,
							0 AS Borrowqty,
							0 AS WnQty,
							0 AS SnQty
					FROM 	goodsstocks g,
							ptype p
					WHERE 	g.ptypeid LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
							AND g.ktypeid IN ('+''''+REPLACE(@KTypeID,',',''',''')+''''+')	
							AND g.ptypeid = p.typeid 
							AND p.deleted = 0 
							AND g.ptypeid LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
							AND g.ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
					GROUP BY g.ptypeid 
				UNION                      
					SELECT	a.typeid,
							0 AS qty,
							0 AS total,
							SUM(l.Lend-l.LendBack) AS Lendqty,
							SUM(l.Borrow-l.BorrowBack) AS  Borrowqty,
							0 AS WnQty,
							0 AS SnQty
					FROM 	V_LendStatus l INNER JOIN ptype a ON a.typeid=l.ptypeid
					WHERE 	a.deleted=0 
							AND l.ptypeid LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+' 
							AND l.ktypeid IN ('+''''+REPLACE(@KTypeID,',',''',''')+''''+') 
							AND l.ptypeid LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
							AND l.ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'

					GROUP BY a.typeid		     
				)d  ON LEFT(d.ptypeid,len(a.typeid)) = a.typeid'



		IF @PSonNum >=1 
			SELECT @SQL = @SQL + '	WHERE	a.ParID='+CHAR(39)+@PTypeID+CHAR(39)+' AND a.TypeID <>'+CHAR(39)+@PTypeID+CHAR(39)
		ELSE
			SELECT @SQL = @SQL + '	WHERE	a.TypeID='+CHAR(39)+@PTypeID+CHAR(39)
	
		

		SELECT @SQL = @SQL +' AND a.deleted=0
							  AND a.UserCode LIKE '+CHAR(39)+@UserCode+'%'+CHAR(39)+'
							  AND a.FullName LIKE '+CHAR(39)+@FullName+'%'+CHAR(39)+'
							  AND a.TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)

		--=================================谢吉康   2003-12-8 增加商品基本属性的查询
		SELECT @SQL = @SQL +'   AND ISNULL(a.EntryCode,'''') LIKE '+CHAR(39)+@szPEntryCode+'%'+CHAR(39)+'
								AND ISNULL(a.Standard,'''')  LIKE '+CHAR(39)+@szPStandard+'%'+CHAR(39)+'
								AND ISNULL(a.[Type],'''')  LIKE '+CHAR(39)+@szPType+'%'+CHAR(39)+'
								AND ISNULL(a.Area,'''')  LIKE '+CHAR(39)+@szPArea+'%'+CHAR(39)+'


		GROUP BY a.typeid,
				a.fullname,
				a.usercode,
				a.EntryCode,
				a.Standard,
				a.Type,
				a.Area,
				a.sonnum,
				a.leveal,
				a.parid,
				a.unit1,
				a.unit2,
				a.unitrate1
		ORDER BY a.usercode'

			--PRINT(@SQL)
			EXEC(@SQL)
	END
--=========================================================================================================历史库存状况表
IF IsDate(@StartDate)=1
	BEGIN
		SELECT @SQL = '		
			SELECT 	a.typeid,
					a.fullname,
					a.usercode,
					a.EntryCode,
					a.Standard,
					a.Type,
					a.Area,
					a.sonnum,
					a.leveal,
					a.parid,
					a.unit1,
					a.unit2,
					a.unitrate1,
					ISNULL(SUM(b.qty),0) AS qty,
					CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) AS price,
					ISNULL(SUM(b.total),0) AS total ,
					ISNULL(SUM(b.LendQty),0) AS LENDqty,
					ISNULL(SUM(b.Borrowqty),0) AS Borrowqty,
					ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.lENDqty),0)+ISNULL(SUM(b.borrowqty),0) AS sjczqty			
			FROM ptype a 
					LEFT JOIN
					(  
	               		SELECT 	b.ptypeid,
								SUM(b.qty) AS qty,
								SUM(b.total) AS total,
								0 AS LendQty,
								0 AS BorrowQty
	              		FROM
					    (  
							SELECT 	ng.ptypeid,
									ng.ktypeid,
									ISNULL(SUM(ng.qty),0) AS qty,
									ISNULL(SUM(ng.total),0) AS total 
							FROM
	             				(
							    	SELECT 	ptypeid,
											ktypeid,
											ISNULL(qty,0) AS qty,
											ISNULL(total,0) AS total 
									FROM 	inigoodsstocks
	             					UNION ALL
	     							SELECT 	ptypeid,
											ktypeid,
											SUM(qty) AS qty,
											SUM(CostTotal) AS Total 
									FROM 	inoutstocktable 
									WHERE 	KTypeID<>''10000'' 
											AND Billdate<='+CHAR(39)+@StartDate+CHAR(39)+'  
									GROUP BY 	ptypeid,
												ktypeid
	              						)  ng
	                   				WHERE 	ng.ktypeid IN ('+''''+REPLACE(@KTypeID,',',''',''')+''''+') 				
											AND ng.ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
									GROUP BY ng.ktypeid,ng.ptypeid
							)  b 
							WHERE	b.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
									AND b.ptypeid LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
							GROUP BY b.ptypeid 
						UNION ALL
			               	SELECT	a.typeid,
									0 AS Qty,
									0 AS Total,
									-CAST(SUM(t.LEND) AS  NUMERIC(24, 10) ) AS LendQty, 
									CAST(SUM(t.Borrow) AS  NUMERIC(24, 10) ) AS Borrowqty
					        FROM 
								(
			               			SELECT	PtypeId,
											CASE WHEN (Qty > 0) THEN Qty ELSE 0 END AS Borrow,
											CASE WHEN (Qty < 0) THEN Qty ELSE 0 END AS LEND
									FROM 	[IniGoodsLEND] 
									WHERE 	KtypeID IN ('+''''+REPLACE(@KTypeID,',',''',''')+''''+') 
											AND ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
								UNION ALL
									SELECT  lb.PtypeId,
											CASE li.BillType WHEN 71 THEN Qty WHEN 72 THEN Qty ELSE 0 END AS Borrow,
											CASE li.BillType WHEN 87 THEN Qty WHEN 88 THEN Qty ELSE 0 END AS LEND
									FROM 	[LENDIndex] li JOIN [LENDBill] lb ON (li.BillNumberid=lb.BillNumberId)
									WHERE 	BillDate <= '+CHAR(39)+@StartDate+CHAR(39)+' 
											AND  li.Ktypeid IN ('+''''+REPLACE(@KTypeID,',',''',''')+''''+') 
											AND  li.ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
								) t  INNER JOIN ptype a ON(a.typeid=t.ptypeid) 
							WHERE	a.TypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
							GROUP BY a.typeid
							) b ON a.typeid=LEFT(b.ptypeid,LEN(a.TypeID)) '
							IF @PSonNum >=1 
								SELECT @SQL = @SQL + '	WHERE	a.ParID='+CHAR(39)+@PTypeID+CHAR(39)+' AND a.TypeID <>'+CHAR(39)+@PTypeID+CHAR(39)
							ELSE
								SELECT @SQL = @SQL + '	WHERE	a.TypeID='+CHAR(39)+@PTypeID+CHAR(39)
							
							SELECT @SQL = @SQL + '
						 			AND a.deleted=0 
									AND a.typeid LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)

			--=================================谢吉康   2003-12-8 增加商品基本属性的查询
			SELECT @SQL = @SQL +'   AND ISNULL(a.EntryCode,'''') LIKE '+CHAR(39)+@szPEntryCode+'%'+CHAR(39)+'
									AND ISNULL(a.Standard,'''')  LIKE '+CHAR(39)+@szPStandard+'%'+CHAR(39)+'
									AND ISNULL(a.[Type],'''')  LIKE '+CHAR(39)+@szPType+'%'+CHAR(39)+'
									AND ISNULL(a.Area,'''')  LIKE '+CHAR(39)+@szPArea+'%'+CHAR(39)+'

						GROUP BY 
						 	a.typeid,
							a.fullname,
							a.usercode,
							a.EntryCode,
							a.Standard,
							a.Type,
							a.Area,
							a.sonnum,
							a.leveal,
							a.parid,
							a.unit1,
							a.unit2,
							a.unitrate1 ORDER BY a.usercode'
		--PRINT(@SQL)
		EXEC(@SQL)

	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryMultiStock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryMultiStock]
GO




















/*
	作者：谢吉康
	日期：2003-11-28
	描述：多级仓库的查询数型表
*/
CREATE      PROCEDURE GP_QueryMultiStock
(
	@OperatorID		VARCHAR(50),
	@StartDate		VARCHAR(20),
	@PTypeID		VARCHAR(50),
	@KTypeID		VARCHAR(8000),
	@UserCode		VARCHAR(80),
	@FullName		VARCHAR(80),

	@szPEntryCode	VARCHAR(200),			--商品条码
	@szPStandard	VARCHAR(200),			--商品规格
	@szPType		VARCHAR(200),			--商品型号
	@szPArea		VARCHAR(200)			--商品产地

)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)
	SELECT  @SQL = ''

	DECLARE @PSonNum INT
	DECLARE @KSonNum INT

	DECLARE @PTypeIDmx	VARCHAR(50)	--LEFT JOIN 中使用的PTypeID
	DECLARE @KTypeIDmx	VARCHAR(50)	--LEFT JOIN 中使用的KTypeID

	IF @PTypeID = '00000'
		BEGIN
			SELECT @PTypeIDmx = '%'
			SELECT @PSonNum = 1
		END
	ELSE
		BEGIN
			SELECT @PSonNum = SonNum FROM PType WHERE TypeID = @PTypeID
			SELECT @PTypeIDmx = @PTypeID
		END

	IF @KTypeID = '00000'
		BEGIN
			SELECT @KTypeIDmx = '%'			
			SELECT @KSonNum = 1
		END
	ELSE
		SELECT @KSonNum = SonNum FROM Stock WHERE TypeID = @KTypeID

DECLARE @gKTypeID	 varchar(8000),
		@lKTypeId	 varchar(8000),		
		@ngKTypeId	 varchar(8000),	
		@liKTypeId	 varchar(8000),
		@szKTypeId	 varchar(8000),	
		@SQL2  		 varchar(8000),
		@SQL3  		 varchar(8000),
		@SQL4  		 varchar(8000)

SELECT  @gKTypeID = REPLACE(@KTypeID,'OR','OR g.KTypeId')
SELECT  @gKTypeID = REPLACE(@gKTypeID,',','')


SELECT  @lKTypeID = REPLACE(@KTypeID,'OR','OR l.KTypeId')
SELECT  @lKTypeID = REPLACE(@lKTypeID,',','')

SELECT  @ngKTypeID = REPLACE(@KTypeID,'OR','OR ng.KTypeId')
SELECT  @ngKTypeID = REPLACE(@ngKTypeID,',','')

SELECT  @liKTypeID = REPLACE(@KTypeID,'OR','OR li.KTypeId')
SELECT  @liKTypeID = REPLACE(@liKTypeID,',','')

SELECT  @szKTypeId = REPLACE(@KTypeID,'OR','OR KTypeId')
SELECT  @szKTypeId = REPLACE(@szKTypeId,',','')


--=========================================================================================================当前库存状况表
IF IsDate(@StartDate)<>1
	BEGIN
		SELECT @SQL = '
				SELECT	a.typeid,
						a.fullname,
						a.usercode,
						a.EntryCode,
						a.Standard,
						a.Type,
						a.Area,
						a.sonnum,
						a.leveal,
						a.parid,
						a.unit1,
						a.unit2,
						a.unitrate1,
						ISNULL(SUM(d.qty),0) AS qty,
						ISNULL(SUM(d.total),0) AS total,
						CAST(ISNULL(SUM(d.total)/CASE WHEN SUM(d.qty)=0 THEN NULL ELSE SUM(d.qty) END ,0) AS  NUMERIC(24, 10) ) AS price,
						ISNULL(SUM(d.LENDqty),0) AS LENDqty,
						ISNULL(SUM(d.Borrowqty),0) AS Borrowqty,
						ISNULL(SUM(d.WnQty),0) AS WnQty,
						ISNULL(SUM(d.SnQty),0) AS SnQty,
						ISNULL(SUM(d.qty),0)-ISNULL(SUM(d.lENDqty),0)+ISNULL(SUM(d.borrowqty),0) AS sjczqty
				FROM ptype a 
				LEFT JOIN
				(
					SELECT	g.ptypeid,
							SUM(g.qty) AS qty,
							SUM(g.total) AS total,
							0 AS LENDqty,
							0 AS Borrowqty,
							0 AS WnQty,
							0 AS SnQty
					FROM 	goodsstocks g,
							ptype p
					WHERE 	g.ptypeid LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
							AND (g.ktypeid '+@gKTypeID+')'

		SELECT @SQL2 ='		AND g.ptypeid = p.typeid 
							AND g.ptypeid LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
							AND g.ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
					GROUP BY g.ptypeid 
				UNION                      
					SELECT	a.typeid,
							0 AS qty,
							0 AS total,
							SUM(l.Lend-l.LendBack) AS Lendqty,
							SUM(l.Borrow-l.BorrowBack) AS  Borrowqty,
							0 AS WnQty,
							0 AS SnQty
					FROM 	V_LendStatus l INNER JOIN ptype a ON a.typeid=l.ptypeid
					WHERE 	l.ptypeid LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+' 
							AND (l.ktypeid '+@lKTypeID+')'

		SELECT @SQL3=' 
							AND l.ptypeid LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
							AND l.ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'

					GROUP BY a.typeid		     
				)d  ON LEFT(d.ptypeid,len(a.typeid)) = a.typeid'



		IF @PSonNum >=1 
			SELECT @SQL4 = '	WHERE	a.ParID='+CHAR(39)+@PTypeID+CHAR(39)+' AND a.TypeID <>'+CHAR(39)+@PTypeID+CHAR(39)
		ELSE
			SELECT @SQL4 = '	WHERE	a.TypeID='+CHAR(39)+@PTypeID+CHAR(39)
	
		

		SELECT @SQL4 = @SQL4 +' a.UserCode LIKE '+CHAR(39)+@UserCode+'%'+CHAR(39)+'
							  AND a.FullName LIKE '+CHAR(39)+@FullName+'%'+CHAR(39)+'
							  AND a.TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)

		--=================================谢吉康   2003-12-8 增加商品基本属性的查询
		SELECT @SQL4 = @SQL4 +'   AND ISNULL(a.EntryCode,'''') LIKE '+CHAR(39)+@szPEntryCode+'%'+CHAR(39)+'
								AND ISNULL(a.Standard,'''')  LIKE '+CHAR(39)+@szPStandard+'%'+CHAR(39)+'
								AND ISNULL(a.[Type],'''')  LIKE '+CHAR(39)+@szPType+'%'+CHAR(39)+'
								AND ISNULL(a.Area,'''')  LIKE '+CHAR(39)+@szPArea+'%'+CHAR(39)+'


		GROUP BY a.typeid,
				a.fullname,
				a.usercode,
				a.EntryCode,
				a.Standard,
				a.Type,
				a.Area,
				a.sonnum,
				a.leveal,
				a.parid,
				a.unit1,
				a.unit2,
				a.unitrate1
		ORDER BY a.usercode'

			--PRINT(@SQL+@SQL2+@SQL3+@SQL4)
			EXEC(@SQL+@SQL2+@SQL3+@SQL4)
	END
--=========================================================================================================历史库存状况表
IF IsDate(@StartDate)=1
	BEGIN
		SELECT @SQL = '		
			SELECT 	a.typeid,
					a.fullname,
					a.usercode,
					a.EntryCode,
					a.Standard,
					a.Type,
					a.Area,
					a.sonnum,
					a.leveal,
					a.parid,
					a.unit1,
					a.unit2,
					a.unitrate1,
					ISNULL(SUM(b.qty),0) AS qty,
					CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) AS price,
					ISNULL(SUM(b.total),0) AS total ,
					ISNULL(SUM(b.LendQty),0) AS LENDqty,
					ISNULL(SUM(b.Borrowqty),0) AS Borrowqty,
					ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.lENDqty),0)+ISNULL(SUM(b.borrowqty),0) AS sjczqty			
			FROM ptype a 
					LEFT JOIN
					(  
	               		SELECT 	b.ptypeid,
								SUM(b.qty) AS qty,
								SUM(b.total) AS total,
								0 AS LendQty,
								0 AS BorrowQty
	              		FROM
					    (  
							SELECT 	ng.ptypeid,
									ng.ktypeid,
									ISNULL(SUM(ng.qty),0) AS qty,
									ISNULL(SUM(ng.total),0) AS total 
							FROM
	             				(
							    	SELECT 	ptypeid,
											ktypeid,
											ISNULL(qty,0) AS qty,
											ISNULL(total,0) AS total 
									FROM 	inigoodsstocks
									UNION ALL
									SELECT	PTypeId,
											KTypeId,
											ISNULL(qty,0) AS qty,
											ISNULL(Total,0) AS Total
									FROM	iniCommissionStock
									WHERE	Type = 144
	             					UNION ALL
	     							SELECT 	ptypeid,
											ktypeid,
											SUM(qty) AS qty,
											SUM(CostTotal) AS Total 
									FROM 	inoutstocktable 
									WHERE 	KTypeID<>''10000'' 
											AND Audited = 1
											AND Billdate<='+CHAR(39)+@StartDate+CHAR(39)+'  
									GROUP BY 	ptypeid,
												ktypeid
	              						)  ng
	                   				WHERE 	(ng.ktypeid '+@ngKTypeID+')'

		SELECT @SQL2='				AND ng.ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
									GROUP BY ng.ktypeid,ng.ptypeid
							)  b 
							WHERE	b.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
									AND b.ptypeid LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
							GROUP BY b.ptypeid 
						UNION ALL
			               	SELECT	a.typeid,
									0 AS Qty,
									0 AS Total,
									-CAST(SUM(t.LEND) AS  NUMERIC(24, 10) ) AS LendQty, 
									CAST(SUM(t.Borrow) AS  NUMERIC(24, 10) ) AS Borrowqty
					        FROM 
								(
			               			SELECT	PtypeId,
											CASE WHEN (Qty > 0) THEN Qty ELSE 0 END AS Borrow,
											CASE WHEN (Qty < 0) THEN Qty ELSE 0 END AS LEND
									FROM 	[IniGoodsLEND] 
									WHERE 	(KtypeID '+@szKTypeID+')'

		SELECT @SQL3='						AND ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
								UNION ALL
									SELECT  lb.PtypeId,
											CASE li.BillType WHEN 71 THEN Qty WHEN 72 THEN Qty ELSE 0 END AS Borrow,
											CASE li.BillType WHEN 87 THEN Qty WHEN 88 THEN Qty ELSE 0 END AS LEND
									FROM 	[LENDIndex] li JOIN [LENDBill] lb ON (li.BillNumberid=lb.BillNumberId)
									WHERE 	BillDate <= '+CHAR(39)+@StartDate+CHAR(39)+' 
											AND (li.Ktypeid '+@liKTypeID+')'

		SELECT @SQL4='
											AND  li.ktypeid LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
								) t  INNER JOIN ptype a ON(a.typeid=t.ptypeid) 
							WHERE	a.TypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
							GROUP BY a.typeid
							) b ON a.typeid=LEFT(b.ptypeid,LEN(a.TypeID)) '
							IF @PSonNum >=1 
								SELECT @SQL4 = @SQL4 + '	WHERE	a.ParID='+CHAR(39)+@PTypeID+CHAR(39)+' AND a.TypeID <>'+CHAR(39)+@PTypeID+CHAR(39)
							ELSE
								SELECT @SQL4 = @SQL4 + '	WHERE	a.TypeID='+CHAR(39)+@PTypeID+CHAR(39)
							
							SELECT @SQL4 = @SQL4 + '
									AND a.typeid LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)

			--=================================谢吉康   2003-12-8 增加商品基本属性的查询
			SELECT @SQL4 = @SQL4 +'   AND ISNULL(a.EntryCode,'''') LIKE '+CHAR(39)+@szPEntryCode+'%'+CHAR(39)+'
									AND ISNULL(a.Standard,'''')  LIKE '+CHAR(39)+@szPStandard+'%'+CHAR(39)+'
									AND ISNULL(a.[Type],'''')  LIKE '+CHAR(39)+@szPType+'%'+CHAR(39)+'
									AND ISNULL(a.Area,'''')  LIKE '+CHAR(39)+@szPArea+'%'+CHAR(39)+'

						GROUP BY 
						 	a.typeid,
							a.fullname,
							a.usercode,
							a.EntryCode,
							a.Standard,
							a.Type,
							a.Area,
							a.sonnum,
							a.leveal,
							a.parid,
							a.unit1,
							a.unit2,
							a.unitrate1 ORDER BY a.usercode'
			--PRINT(@SQL+@SQL2+@SQL3+@SQL4)
			EXEC(@SQL+@SQL2+@SQL3+@SQL4)

	END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryMultiStockDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryMultiStockDetail]
GO
/*
	作者：谢吉康
	日期：2003-11-28
	描述：多级仓库的查询明细表
*/
CREATE   PROCEDURE GP_QueryMultiStockDetail
(
	@OperatorID		VARCHAR(50),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@PTypeID		VARCHAR(50),
	@KTypeID		VARCHAR(8000),
	@UserCode		VARCHAR(80),
	@FullName		VARCHAR(80),
	@SortType		VARCHAR(20) = 'ASC',
	@sortfield		VARCHAR(20) = 'BillDate',
	@stypeid		VARCHAR(8000),
	@showstockstop INT =0 ,--是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid   VARCHAR(max)=''
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	 
IF @stypeid='' 
BEGIN
	SET @stypeid='00000'
END

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))


IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN (SELECT Typeid FROM F_GetManDetailSType(@OperatorID)) s
	ON A.TypeId=s.Typeid

--仓库权限
CREATE TABLE #Result
(
	TypeId		varchar(100)
)
DECLARE @KSQL VARCHAR(3000)
	IF  @showstockstop=0
SET @KSQL='
	INSERT INTO #Result
	SELECT k.typeId 
	FROM  stock k	
		INNER JOIN 	(SELECT A FROM dbo.f_split('+CHAR(39)+@KTypeID+CHAR(39)+','','')) b	ON k.typeid like b.a+''%''
		INNER JOIN 	F_GetManDetailKTypeStype('+CHAR(39)+@OperatorID+CHAR(39)+') mk	ON k.typeId=mk.TypeId
		INNER JOIN  #GetSelectSTypeId s ON mk.stypeid=s.typeid
	WHERE	SonNum = 0'
ELSE
	SET @KSQL='
	INSERT INTO #Result
	SELECT k.typeId 
	FROM  stock k	
		INNER JOIN 	(SELECT A FROM dbo.f_split('+CHAR(39)+@KTypeID+CHAR(39)+','','')) b	ON k.typeid like b.a+''%''
		INNER JOIN 	F_GetManDetailKTypeStype('+CHAR(39)+@OperatorID+CHAR(39)+') mk	ON k.typeId=mk.TypeId
		INNER JOIN  #GetSelectSTypeId s ON mk.stypeid=s.typeid
	WHERE	SonNum = 0 and deleted=0'
	
EXEC(@KSQL)

--商品权限
CREATE TABLE #GetManPType(typeid VARCHAR(100))

DECLARE @PSQL  VARCHAR(1000)

SET @PSQL='
	INSERT INTO #GetManPType 
	SELECT 	p.typeid 
	FROM 	ptype p	
			INNER JOIN  F_ManPTypeInCategoryID('+CHAR(39)+@OperatorID+CHAR(39)+' ,'+CHAR(39)+@ptypeid+CHAR(39)+','+CHAR(39)+@ptypeCategoryid+CHAR(39)+') mp	ON p.typeId=mp.TypeId			
	WHERE 1=1
'
IF	@UserCode<>''
	SET @PSQL=@PSQL+' AND p.UserCode like '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)
	
IF 	@FullName<>''
	SET @PSQL=@PSQL+' AND p.FullName like '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)
	--PRINT @PSQL
EXEC(@PSQL)	


DECLARE @SQL VARCHAR(8000)
SELECT  @SQL = ''

DECLARE @PTypeIDmx	VARCHAR(50)	--LEFT JOIN 中使用的PTypeID

IF @PTypeID = '00000'
	BEGIN
		SELECT @PTypeIDmx = '%'
	END
ELSE
	BEGIN
		SELECT @PTypeIDmx = @PTypeID
	END

--=========================================================================================获取当前数据
SELECT @SQL ='
	SELECT	c.BillNumberId,
			c.BillDate,
			a.BillDate,
			c.billtype,
			CASE  
				WHEN a.billtype=145 THEN -c.qty 
				WHEN a.billtype=57 AND a.AdPriceType<>0 THEN 0 
				ELSE c.qty	
			END as qty,
			CASE a.billtype WHEN 145 THEN -c.Costtotal else  c.Costtotal end as Costtotal,
			CASE a.billtype WHEN 145 THEN -c.total else  c.total	end as total,
			c.CostPrice,
			a.BillCode, 
			a.Comment,
			a.RedWord, 
			a.posttime,
			a.billtype,
			c.ktypeid,
			a.stypeid,
			 SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head, 
						SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,
						SysDiy24_head,SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,
						SysDiy31_head,SysDiy32_head,
						SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
						SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
						SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
						SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32
	FROM 	InOutStockTable c
			INNER JOIN 
			(
				SELECT	Billnumberid,
						BillDate,
						BillCode,
						Comment,
						RedWord,
						posttime,
						billtype,
						stypeid,
						AdPriceType,
						IfCheck
				FROM	BillIndex
				UNION	ALL
				SELECT	Billnumberid,
						BillDate,
						BillCode,
						Comment,
						RedWord,
						'''' as posttime,
						billtype,
						stypeid,
						0 as AdPriceType,
						IfCheck
				FROM	PosAllotApplyBillIndex WHERE Billtype IN(327,328,329)
			) a	ON a.BillNumberID=c.BillNumberID AND a.Billtype=c.Billtype
			INNER JOIN #Result r	ON c.KTypeID=r.typeid
			INNER JOIN #GetManPType p On c.PTypeId=p.typeid
			left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND c.id=csdetail.Detailid
	WHERE	c.ktypeid<>'+CHAR(39)+'10000'+CHAR(39)+' 
			AND c.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
			AND c.billdate >='+CHAR(39)+@StartDate+CHAR(39)+'
			AND c.billdate <='+CHAR(39)+@EndDate+CHAR(39)+'		
			AND A.IfCheck=''t''
			AND	A.RedWord=''0''		
ORDER  BY  '+ @sortfield + ' ' + @SortType
	
EXEC(@SQL)

DROP TABLE #GetManPType,#Result		

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryMultiStockLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryMultiStockLine]
GO



/*
	作者：谢吉康
	日期：2003-11-28
	描述：多级仓库的查询线性表
*/
CREATE        PROCEDURE GP_QueryMultiStockLine
(
	@OperatorID		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@PTypeID		VARCHAR(8000),
	@KTypeID		VARCHAR(8000),
	@UserCode		VARCHAR(80),
	@FullName		VARCHAR(80),
	@showzeroqty		INT = '1',
	@sortfield		VARCHAR(80),
	@SortType		VARCHAR(10),
	@EntryCode	VARCHAR(200),			--商品条码
	@Standard	VARCHAR(200),			--商品规格
	@type		VARCHAR(200),			--商品型号
	@area		VARCHAR(200),			--商品产地
	@stypeid		VARCHAR(8000),
    @showstockstop INT =0, --是否显示停用仓库数据 1为不显示 0为显示
    @ptypeCategoryid   VARCHAR(max)=''

)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	 
IF @stypeid='' 
BEGIN
	SET @stypeid='00000'
END

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))


IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN (SELECT Typeid FROM F_GetManDetailSType(@OperatorID)) s
	ON A.TypeId=s.Typeid

		
	
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId)  SELECT TypeId FROM dbo.F_ManPTypeInCategoryID(@OperatorID,@ptypeid,@ptypeCategoryid)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
	IF  @showstockstop=0
INSERT INTO #GetManKTypeId(TypeId) 
SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k  INNER JOIN #GetSelectSTypeId s ON s.TypeId=k.STypeId 
ELSE
INSERT INTO #GetManKTypeId(TypeId) 
SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k  INNER JOIN #GetSelectSTypeId s ON s.TypeId=k.STypeId INNER JOIN dbo.Stock ss  ON k.TypeId = ss.typeId WHERE ss.deleted=0

DECLARE @TypeId 	varchar(100)

CREATE TABLE #Result
(
	TypeId		varchar(100)
)

DECLARE stockCursor CURSOR FOR
	SELECT * FROM dbo.f_split(@KTypeID,',')

OPEN stockCursor

FETCH NEXT FROM stockCursor INTO @TypeId

WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO #Result(TypeId) SELECT TypeId FROM Stock WHERE SonNum = 0 AND TypeId LIKE @TypeId + '%' AND TypeId IN (SELECT * FROM #GetManKTypeId)

		FETCH NEXT FROM stockCursor INTO @TypeId
	END

CLOSE stockCursor
DEALLOCATE stockCursor

DECLARE @SQL VARCHAR(8000)
SELECT  @SQL = ''

DECLARE @PSonNum INT
DECLARE @KSonNum INT

DECLARE @PTypeIDmx	VARCHAR(50)	--LEFT JOIN 中使用的PTypeID
DECLARE @KTypeIDmx	VARCHAR(50)	--LEFT JOIN 中使用的KTypeID

IF @PTypeID = '00000'
	BEGIN
		SELECT @PTypeIDmx = '%'
		SELECT @PSonNum = 1
	END
ELSE
	BEGIN
		SELECT @PSonNum = SonNum FROM PType WHERE TypeID = @PTypeID
		SELECT @PTypeIDmx = @PTypeID
	END

IF @KTypeID = '00000'
	BEGIN
		SELECT @KTypeIDmx = '%'			
		SELECT @KSonNum = 1
	END
ELSE
	SELECT @KSonNum = SonNum FROM Stock WHERE TypeID = @KTypeID 

DECLARE @gKTypeID	 varchar(8000),
		@lKTypeId	 varchar(8000),		
		@ngKTypeId	 varchar(8000),	
		@liKTypeId	 varchar(8000),
		@szKTypeId	 varchar(8000),	
		@SQL2  		 varchar(8000),
		@SQL3  		 varchar(8000),
		@SQL4  		 varchar(8000)

SELECT  @gKTypeID = REPLACE(@KTypeID,'OR','OR g.KTypeId')
SELECT  @gKTypeID = REPLACE(@gKTypeID,',','')


SELECT  @lKTypeID = REPLACE(@KTypeID,'OR','OR l.KTypeId')
SELECT  @lKTypeID = REPLACE(@lKTypeID,',','')

SELECT  @ngKTypeID = REPLACE(@KTypeID,'OR','OR ng.KTypeId')
SELECT  @ngKTypeID = REPLACE(@ngKTypeID,',','')

SELECT  @liKTypeID = REPLACE(@KTypeID,'OR','OR li.KTypeId')
SELECT  @liKTypeID = REPLACE(@liKTypeID,',','')

SELECT  @szKTypeId = REPLACE(@KTypeID,'OR','OR KTypeId')
SELECT  @szKTypeId = REPLACE(@szKTypeId,',','')

--=========================================================================================================当前库存状况表
IF IsDate(@StartDate)<>1
	BEGIN
		SELECT @SQL = '
		SELECT	A.*
		FROM (
				SELECT	a.typeid,
						a.fullname,
						a.usercode,
						a.EntryCode,
						a.Standard,
						a.Type,
						a.Area,
						a.sonnum,
						a.leveal,
						a.parid,
						a.unit1,
						a.unit2,
						a.unitrate1,
						ISNULL(SUM(b.qty),0) AS qty,
						ISNULL(SUM(b.total),0) AS total,
						CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) AS price,
						ISNULL(SUM(b.LENDqty),0) AS LENDqty,
						ISNULL(SUM(b.Borrowqty),0) AS Borrowqty,
						ISNULL(SUM(b.WnQty),0) AS WnQty,
						ISNULL(SUM(b.SnQty),0) AS SnQty,
						ISNULL(SUM(b.qty),0)-ISNULL(SUM(b.lENDqty),0)+ISNULL(SUM(b.borrowqty),0) AS sjczqty
				FROM 	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') a 
				inner join #GetManPTypeId pp on pp.typeid=a.typeid
				LEFT JOIN
				(
					SELECT	g.ptypeid,
							SUM(g.qty) AS qty,
							SUM(g.total) AS total,
							0 AS LENDqty,
							0 AS Borrowqty,
							0 AS WnQty,
							0 AS SnQty
					FROM 	goodsstocks g,
							ptype p
					WHERE 	g.ptypeid LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
							AND (g.ktypeid IN (SELECT TypeId FROM #Result))	'

		SELECT @SQL2='
							AND g.ptypeid = p.typeid 
							AND g.ptypeid IN (SELECT * FROM #GetManPTypeId)
							AND g.ktypeid IN (SELECT * FROM #GetManKTypeId)
					GROUP BY g.ptypeid 
				UNION                      
					SELECT	a.typeid,
							0 AS qty,
							0 AS total,
							SUM(l.Lend-l.LendBack-l.saleqty) AS Lendqty,
							SUM(l.Borrow-l.BorrowBack-l.buyqty) AS  Borrowqty,
							0 AS WnQty,
							0 AS SnQty
					FROM 	V_LendStatus01 l INNER JOIN ptype a ON a.typeid=l.ptypeid
					WHERE 	l.ptypeid LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+' 
							AND (l.ktypeid IN (SELECT TypeId FROM #Result)) '
		SELECT @SQL3='
							AND l.ptypeid IN (SELECT * FROM #GetManPTypeId)
							AND l.ktypeid IN (SELECT * FROM #GetManKTypeId)
					GROUP BY a.typeid		     
				)b  ON b.ptypeid = a.typeid'

		SELECT @SQL4 = '	WHERE	a.TypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)
	
		
		SELECT @SQL4 = @SQL4 +' AND a.SonNum=0
								and a.IsService=0
								and a.iscombinationproduct = 0
								AND a.UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
								AND a.FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)

		--=================================谢吉康   2003-12-8 增加商品基本属性的查询
		SELECT @SQL4 = @SQL4 +' AND ((ISNULL('''+@EntryCode+''','''')<>'''' AND EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=a.typeId AND E.EntryCode LIKE ''%'+@EntryCode+'%'')) OR ISNULL('''+@EntryCode+''','''')='''')
								AND ISNULL(a.Standard,'''')  LIKE '+CHAR(39)+'%'+@Standard+'%'+CHAR(39)+'
								AND ISNULL(a.[Type],'''')  LIKE '+CHAR(39)+'%'+@type+'%'+CHAR(39)+'
								AND ISNULL(a.Area,'''')  LIKE '+CHAR(39)+'%'+@area+'%'+CHAR(39)+'


				GROUP BY a.typeid,
						a.fullname,
						a.usercode,
						a.EntryCode,
						a.Standard,
						a.Type,
						a.Area,
						a.sonnum,
						a.leveal,
						a.parid,
						a.unit1,
						a.unit2,
						a.unitrate1
		) A '
		IF @showzeroqty = 0
			SELECT @SQL4 = @SQL4 + ' WHERE ISNULL(A.sjczqty,0)<>0  '
		
		SELECT @SQL4 = @SQL4 +'	ORDER BY '+ @sortfield + ' ' + @SortType

			--PRINT(@SQL+@SQL2+@SQL3+@SQL4)
			EXEC(@SQL+@SQL2+@SQL3+@SQL4)
	END
--=========================================================================================================历史库存状况表
IF IsDate(@StartDate)=1
	BEGIN
		SELECT @SQL = '
		SELECT A.*
		FROM (		
			SELECT 	a.typeid,
					a.fullname,
					a.usercode,
					a.EntryCode,
					a.Standard,
					a.Type,
					a.Area,
					a.sonnum,
					a.leveal,
					a.parid,
					a.unit1,
					a.unit2,
					a.unitrate1,
					ISNULL(SUM(b.qty),0) AS qty,
					CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) AS price,
					ISNULL(SUM(b.total),0) AS total ,
					ISNULL(SUM(b.LendQty),0)-ISNULL(sum(b.saleqty),0 )AS LENDqty,
					ISNULL(SUM(b.Borrowqty),0)-ISNULL(sum(b.buyqty),0) AS Borrowqty,
					ISNULL(SUM(b.qty),0)-(ISNULL(SUM(b.lENDqty),0)-ISNULL(sum(b.saleqty),0 ))+(ISNULL(SUM(b.borrowqty),0) -ISNULL(sum(b.buyqty),0))AS sjczqty
					
					
			FROM 	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') a 
					LEFT JOIN
					(  
	               		SELECT 	b.ptypeid,
								SUM(b.qty) AS qty,
								SUM(b.total) AS total,
								0 AS LendQty,
								0 AS BorrowQty,
									0 as saleqty,
								0 as buyqty
	              		FROM
					    (  
							SELECT 	ng.ptypeid,
									ng.ktypeid,
									ISNULL(SUM(ng.qty),0) AS qty,
									ISNULL(SUM(ng.total),0) AS total ,
									0 as saleqty,
								    0 as buyqty
							FROM
	             				(
							    	SELECT 	ptypeid,
											ktypeid,
											ISNULL(qty,0) AS qty,
											ISNULL(total,0) AS total 
									FROM 	inigoodsstocks
									UNION ALL
									SELECT	PTypeId,
											KTypeId,
											ISNULL(qty,0) AS qty,
											ISNULL(Total,0) AS Total
									FROM	iniCommissionStock
									WHERE	Type = 144
	             					UNION ALL
	     							SELECT 	ptypeid,
											ktypeid,
											SUM(qty) AS qty,
											SUM(CostTotal) AS Total 
									FROM 	inoutstocktable 
									WHERE 	KTypeID<>''10000'' 
											AND Audited = 1
											AND billdate <='+CHAR(39)+@StartDate+CHAR(39)+'  
									GROUP BY 	ptypeid,
												ktypeid
	              						)  ng
	                   				WHERE 	(ng.ktypeid IN (SELECT TypeId FROM #Result))'
			SELECT @SQL2=' 				
											AND ng.ktypeid IN (SELECT * FROM #GetManKTypeId)
									GROUP BY ng.ktypeid,ng.ptypeid
							)  b 
							WHERE	b.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
									AND b.ptypeid LIKE '+CHAR(39)+'%'+CHAR(39)+'
							GROUP BY b.ptypeid 
						UNION ALL
			               	SELECT	a.typeid,
									0 AS Qty,
									0 AS Total,
									-CAST(SUM(t.LEND) AS  NUMERIC(24, 10) ) AS LendQty, 
									CAST(SUM(t.Borrow) AS  NUMERIC(24, 10) ) AS Borrowqty,
									 SUM(t.saleqty),
								  SUM(t.buyqty)
					        FROM 
								(
			               			SELECT	PtypeId,
											CASE WHEN (Qty > 0) THEN Qty ELSE 0 END AS Borrow,
											CASE WHEN (Qty < 0) THEN Qty ELSE 0 END AS LEND,0 AS saleqty,0 AS buyqty
									FROM 	[IniGoodsLEND] 
									WHERE 	(KtypeID IN (SELECT TypeId FROM #Result)) '
			SELECT @SQL3='
											AND ktypeid IN (SELECT * FROM #GetManKTypeId)
								UNION ALL
									SELECT  lb.PtypeId,
											CASE li.BillType WHEN 71 THEN Qty WHEN 72 THEN Qty ELSE 0 END AS Borrow,
											CASE li.BillType WHEN 87 THEN Qty WHEN 88 THEN Qty ELSE 0 END AS LEND,0,0
									FROM 	[LENDIndex] li JOIN [LENDBill] lb ON (li.BillNumberid=lb.BillNumberId)
									WHERE 	BillDate <= '+CHAR(39)+@StartDate+CHAR(39)+' 
											AND  (li.Ktypeid IN (SELECT TypeId FROM #Result)) 
											AND li.ifcheck = ''t'' AND li.Draft =0 AND li.RedWord =0
									UNION ALL		
									SELECT  lb.PtypeId,
											0,
											0,
											lb.qty,
											0
									FROM 	[billindex] li JOIN [SaleBill] lb ON (li.BillNumberid=lb.BillNumberId)
									WHERE 	BillDate <= '+CHAR(39)+@StartDate+CHAR(39)+' 
											AND (li.Ktypeid IN (SELECT TypeId FROM #Result))
											and  li.IsLend=1
											AND RedWord=0
											AND ifcheck=''t''
											
								UNION ALL
									SELECT  lb.PtypeId,
											0,
											0,
											0,
											lb.qty
									FROM 	BillIndex li JOIN BuyBill lb ON (li.BillNumberid=lb.BillNumberId)
									WHERE 	BillDate <= '+CHAR(39)+@StartDate+CHAR(39)+' 
											AND (li.Ktypeid IN (SELECT TypeId FROM #Result))
											and  li.IsLend=1
											AND RedWord=0
											AND ifcheck=''t''		
											
											'
			SELECT @SQL4='
											AND  li.ktypeid IN (SELECT * FROM #GetManKTypeId)
								) t  INNER JOIN ptype a ON(a.typeid=LEFT(t.ptypeid,len(a.typeid))) 
							WHERE	a.TypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
							GROUP BY a.typeid
							) b ON a.typeid=b.ptypeid '

							SELECT @SQL4 = @SQL4 + '	WHERE	a.TypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)							

							SELECT @SQL4 = @SQL4 + '
									AND a.SonNum=0
									and a.IsService=0
									and a.iscombinationproduct = 0
									AND a.UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
							  		AND a.FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)

		--=================================谢吉康   2003-12-8 增加商品基本属性的查询
		SELECT @SQL4 = @SQL4 +' AND ((ISNULL('''+@EntryCode+''','''')<>'''' AND EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=a.typeId AND E.EntryCode LIKE ''%'+@EntryCode+'%'')) OR ISNULL('''+@EntryCode+''','''')='''')
								AND ISNULL(a.Standard,'''')  LIKE '+CHAR(39)+'%'+@Standard+'%'+CHAR(39)+'
								AND ISNULL(a.[Type],'''')  LIKE '+CHAR(39)+'%'+@type+'%'+CHAR(39)+'
								AND ISNULL(a.Area,'''')  LIKE '+CHAR(39)+'%'+@area+'%'+CHAR(39)+'

						GROUP BY 
						 	a.typeid,
							a.fullname,
							a.usercode,
							a.EntryCode,
							a.Standard,
							a.Type,
							a.Area,
							a.sonnum,
							a.leveal,
							a.parid,
							a.unit1,
							a.unit2,
							a.unitrate1 
		) A '
			IF @showzeroqty = 0
				SELECT @SQL4 = @SQL4 + ' WHERE ISNULL(A.sjczqty,0)<>0 '
		
		SELECT @SQL4 = @SQL4 +'	ORDER BY '+ @sortfield + ' ' + @SortType

			--PRINT(@SQL+@SQL2+@SQL3+@SQL4)
			EXEC(@SQL+@SQL2+@SQL3+@SQL4)

	END

	DROP TABLE #Result,#GetManPTypeId,#GetManKTypeId,#GetSelectSTypeId



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[GP_QUERYMULTISTOCKLIST]') AND OBJECTPROPERTY(ID, N'ISPROCEDURE') = 1)
DROP PROCEDURE [DBO].[GP_QUERYMULTISTOCKLIST]
GO

/*
	作者：谢吉康
	日期：2003-11-28
	描述：多级仓库的查询数型表
	GP_QUERYMULTISTOCK '00001','','00000','LIKE ''00055%'' OR LIKE ''00061%'' OR LIKE ''00063%'' ','','','','','','' 
*/
CREATE      PROCEDURE GP_QUERYMULTISTOCKLIST
(
	@OPERATORID		VARCHAR(100),
	@STARTDATE		VARCHAR(20),
	@PTYPEID		VARCHAR(100),
	@KTYPEID		VARCHAR(8000),
	@USERCODE		VARCHAR(80),
	@FULLNAME		VARCHAR(80),
	@ENTRYCODE		VARCHAR(200),			--商品条码
	@STANDARD	VARCHAR(200),			--商品规格
	@TYPE		VARCHAR(200),			--商品型号
	@AREA		VARCHAR(200),			--商品产地
	@STYPEID	VARCHAR(8000),
	@SHOWSTOCKSTOP INT =0 ,--是否显示停用仓库数据 1为不显示 0为显示
	@PTYPECATEGORYID   VARCHAR(MAX)=''
)
--@ENCODE$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OPERATORID IS NULL RETURN 1
DECLARE @RE INT,@MATYPEID VARCHAR(50), @MBTYPEID VARCHAR(50), @MBTYPEID2 VARCHAR(50), @METYPEID VARCHAR(50),
           @MKTYPEID VARCHAR(50), @MPTYPEID VARCHAR(50), @MEXPENSE VARCHAR(50), @MINCOME VARCHAR(50),@MCAPITAL VARCHAR(50),@MDTYPEID VARCHAR(50),@MSTYPEID VARCHAR(50)
EXEC @RE=GP_CHECKOPERATORRIGHT23_REP @OPERATORID,@MATYPEID OUTPUT,@MBTYPEID OUTPUT,@MBTYPEID2 OUTPUT,@METYPEID OUTPUT,@MKTYPEID OUTPUT,@MPTYPEID OUTPUT,@MEXPENSE OUTPUT,@MINCOME OUTPUT,@MCAPITAL OUTPUT,@MDTYPEID OUTPUT,@MSTYPEID OUTPUT
IF @RE<>0 RETURN @RE
--------------------------------------------------------------权限检查-------------------------------------------------------
	 
IF @STYPEID='' 
BEGIN
	SET @STYPEID='00000'
END

--选择分支机构
CREATE TABLE #BTTYPE(TYPEID	VARCHAR(100))


IF @MSTYPEID='00000'
	INSERT INTO #BTTYPE(TYPEID) 
		SELECT A.TYPEID FROM F_GETALLBASETYPEID(@STYPEID,11) AS A
ELSE
	INSERT INTO #BTTYPE(TYPEID) 
	SELECT A.TYPEID FROM F_GETALLBASETYPEID(@STYPEID,11) AS A  INNER JOIN (SELECT TYPEID FROM F_GETMANDETAILSTYPE(@OPERATORID)) S
	ON A.TYPEID=S.TYPEID
	
DECLARE @SONNUM INT;
DECLARE @INNERPTYPEID VARCHAR(100)='';
IF @PTYPEID='00000' AND @MPTYPEID<>'-99999'
	SET @PTYPEID=@MPTYPEID;
SELECT @SONNUM=SONNUM FROM PTYPE WHERE TYPEID=@PTYPEID;
IF @PTYPEID<>'00000'
	SET @INNERPTYPEID=@PTYPEID;
	
DECLARE @LEN INT
IF @PTYPEID = '00000'
	SET @LEN = 5
ELSE
	SET @LEN = LEN(@PTYPEID) + 5
		
--商品
CREATE TABLE #PTYPE(TYPEID	VARCHAR(100))
INSERT INTO #PTYPE(TYPEID) SELECT TYPEID FROM DBO.F_LINEPC(@OPERATORID,@PTYPECATEGORYID) A 

CREATE TABLE #MAINTYPE ( TYPEID VARCHAR(50), PARID  VARCHAR(50), LEVEAL INT, 
						 SONNUM INT, USERCODE VARCHAR(200), FULLNAME VARCHAR(200), [STANDARD] VARCHAR(200), 
						 [TYPE] VARCHAR(200), AREA  VARCHAR(200), UNIT1 VARCHAR(8),UNIT2 VARCHAR(8), UNITRATE1 NUMERIC(24,10), DELETED BIT,
						 ENTRYCODE  VARCHAR(200), ISSERVICE INT, SORTID INT, PTYPECATEGORYID VARCHAR(50) , 
						 ISCOMBINATIONPRODUCT INT)

SELECT @SONNUM = SONNUM FROM PTYPE WHERE TYPEID =@PTYPEID
IF @SONNUM =0 
	INSERT INTO #MAINTYPE( TYPEID, PARID, LEVEAL, SONNUM, USERCODE, FULLNAME, [STANDARD], [TYPE], AREA, UNIT1, UNIT2, UNITRATE1, DELETED, ENTRYCODE, ISSERVICE, SORTID, PTYPECATEGORYID, ISCOMBINATIONPRODUCT) 
	SELECT  C.TYPEID, C.PARID, C.LEVEAL, C.SONNUM, C.USERCODE, C.FULLNAME, C.[STANDARD], C.[TYPE], C.AREA, C.UNIT1,UNIT2, C.UNITRATE1, C.DELETED, C.ENTRYCODE, C.ISSERVICE, C.SORTID, C.PTYPECATEGORYID, C.ISCOMBINATIONPRODUCT
	FROM  DBO.F_ALLTREEP(@OPERATORID) C 
	INNER JOIN  #PTYPE PT ON PT.TYPEID LIKE C.TYPEID + '%'
	WHERE C.TYPEID =@PTYPEID  
	AND C.ISSERVICE<>1
	AND C.ISCOMBINATIONPRODUCT = 0
	AND  ISNULL(C.ENTRYCODE,'''') LIKE CHAR(39)+'%'+@ENTRYCODE+'%'+CHAR(39)
	AND  ISNULL(C.[STANDARD],'''') LIKE CHAR(39)+'%'+@STANDARD+'%'+CHAR(39)
	AND  ISNULL(C.[TYPE],'''') LIKE CHAR(39)+'%'+@TYPE+'%'+CHAR(39)
	AND  ISNULL(C.AREA,'''') LIKE CHAR(39)+'%'+@AREA+'%'+CHAR(39)
 
ELSE
	INSERT INTO #MAINTYPE( TYPEID, PARID, LEVEAL, SONNUM, USERCODE, FULLNAME, [STANDARD], [TYPE], AREA, UNIT1,UNIT2, UNITRATE1, DELETED, ENTRYCODE, ISSERVICE, SORTID, PTYPECATEGORYID, ISCOMBINATIONPRODUCT) 
	SELECT DISTINCT  C.TYPEID, C.PARID, C.LEVEAL, C.SONNUM, C.USERCODE, C.FULLNAME, C.[STANDARD], C.[TYPE], C.AREA, C.UNIT1,UNIT2, C.UNITRATE1, C.DELETED, C.ENTRYCODE, C.ISSERVICE, C.SORTID, C.PTYPECATEGORYID, C.ISCOMBINATIONPRODUCT
	FROM F_ALLTREEP(@OPERATORID) C
	INNER JOIN #PTYPE PT ON  PT.TYPEID LIKE C.TYPEID + '%'
	WHERE C.PARID=@PTYPEID 
	AND C.ISSERVICE<>1
	AND C.ISCOMBINATIONPRODUCT = 0
	AND  ISNULL(C.ENTRYCODE,'''') LIKE'%'+@ENTRYCODE+'%'
	AND  ISNULL(C.[STANDARD],'''') LIKE '%'+@STANDARD+'%'
	AND  ISNULL(C.[TYPE],'''') LIKE '%'+@TYPE+'%'
	AND  ISNULL(C.AREA,'''') LIKE '%'+@AREA+'%'
CREATE CLUSTERED INDEX #MAINTYPE_K ON #MAINTYPE(TYPEID)

--select  * from #ptype

--select * from #MAINTYPE

--把权限函数提出来 仓库（带分支ID）
CREATE TABLE #KSTYPE(TYPEID VARCHAR(50),STYPEID VARCHAR(50));
CREATE CLUSTERED INDEX #KSTYPE_T ON #KSTYPE(TYPEID);
INSERT INTO #KSTYPE SELECT TYPEID,STYPEID  FROM F_GETMANDETAILKTYPESTYPE(@OPERATORID);


--仓库
CREATE TABLE #KTYPE(TYPEID VARCHAR(50));
CREATE CLUSTERED INDEX #KTYPE_T ON #KTYPE(TYPEID);
IF  @SHOWSTOCKSTOP=0
	INSERT INTO #KTYPE SELECT TYPEID FROM F_GETALLBASETYPEID(@KTYPEID,4) 
ELSE
	INSERT INTO #KTYPE SELECT A.TYPEID FROM F_GETALLBASETYPEID(@KTYPEID,4)A INNER JOIN DBO.STOCK S ON A.TYPEID=S.TYPEID  WHERE  S.DELETED=0

CREATE TABLE #CTE
(
		PTYPEID VARCHAR(50),
		QTY  NUMERIC(24, 10) ,
		TOTAL  NUMERIC(24, 10) ,
		LENDQTY  NUMERIC(24, 10) ,
		BORROWQTY  NUMERIC(24, 10) ,
		WNQTY  NUMERIC(24, 10) ,
		SNQTY  NUMERIC(24, 10),
		SALEQTY NUMERIC(24, 10),
		BUYQTY NUMERIC(24, 10)
);
CREATE CLUSTERED INDEX #CTE_P ON #CTE(PTYPEID);

	
--临时表存汇总数据
CREATE TABLE #T(	
		PTYPEID VARCHAR(50),
		QTY  NUMERIC(24, 10) ,
		TOTAL  NUMERIC(24, 10) ,
		LENDQTY  NUMERIC(24, 10) ,
		BORROWQTY  NUMERIC(24, 10) ,
		WNQTY  NUMERIC(24, 10) ,
		SNQTY  NUMERIC(24, 10),
		SALEQTY NUMERIC(24, 10),
		BUYQTY NUMERIC(24, 10)
		)
CREATE CLUSTERED INDEX #T_P ON #T(PTYPEID);

DECLARE @SQL_CET  VARCHAR(8000)=''
IF ISDATE(@STARTDATE)<>1
BEGIN
	SET @SQL_CET='	INSERT INTO #CTE
						 SELECT	B.PTYPEID,
								SUM(B.QTY) AS QTY,
								SUM(B.TOTAL) AS TOTAL,
								SUM(B.LENDQTY)  AS LENDQTY,
								SUM(B.BORROWQTY)  AS BORROWQTY,
								SUM(B.WNQTY)  AS WNQTY,
								SUM(B.SNQTY)  AS SNQTY,
								0 AS SALEQTY,
								0 AS BUYQTY
							FROM (
									SELECT	G.PTYPEID,
											G.QTY AS QTY,
											G.TOTAL AS TOTAL,
											0 AS LENDQTY,
											0 AS BORROWQTY,
											0 AS WNQTY,
											0 AS SNQTY,
											0 AS SALEQTY,
											0 AS BUYQTY
									FROM 	GOODSSTOCKS G 
									INNER JOIN #KTYPE K1 ON K1.TYPEID=G.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=G.KTYPEID --操作员仓库权限
									WHERE 	G.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+'
											
								UNION ALL                     
								SELECT	L.PTYPEID,
										0 AS QTY,
										0 AS TOTAL,
										L.LEND-L.LENDBACK-L.SALEQTY AS LENDQTY,
										L.BORROW-L.BORROWBACK-L.BUYQTY AS  BORROWQTY,
										0 AS WNQTY,
										0 AS SNQTY,
										0 AS SALEQTY,
										0 AS BUYQTY
								FROM 	V_LENDSTATUS01 L 
								INNER JOIN #KTYPE K1 ON K1.TYPEID=L.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=L.KTYPEID --操作员仓库权限
								WHERE 	L.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+' 
										) B '
										
							IF @PTYPEID<>'00000' OR @MPTYPEID='-99999' OR @PTYPECATEGORYID<>''
								SET @SQL_CET=@SQL_CET+' INNER JOIN #PTYPE P ON	B.PTYPEID=P.TYPEID	'
	SET @SQL_CET+=' GROUP BY B.PTYPEID '
END
ELSE 
BEGIN
	SET @SQL_CET='     INSERT INTO #CTE
						 SELECT	B.PTYPEID,
								SUM(B.QTY) AS QTY,
								SUM(B.TOTAL) AS TOTAL,
								SUM(B.LENDQTY)  AS LENDQTY,
								SUM(B.BORROWQTY)  AS BORROWQTY,
								SUM(B.WNQTY)  AS WNQTY,
								SUM(B.SNQTY)  AS SNQTY,
								0 AS SALEQTY,
								0 AS BUYQTY
							FROM (
							    	SELECT 	L.PTYPEID,
											L.KTYPEID,
											ISNULL(SUM(L.QTY),0) AS QTY,
											ISNULL(SUM(L.TOTAL),0) AS TOTAL ,
											0  AS LENDQTY,
											0 AS BORROWQTY,
											0 AS WNQTY,
											0 AS SNQTY,
											0 AS SALEQTY,
											0 AS BUYQTY
									FROM 	INIGOODSSTOCKS L
									INNER JOIN #KTYPE K1 ON K1.TYPEID=L.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=L.KTYPEID --操作员仓库权限
									WHERE L.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+' 
									GROUP BY L.PTYPEID,L.KTYPEID
									UNION ALL
									SELECT	L.PTYPEID,
											L.KTYPEID,
											ISNULL(SUM(L.QTY),0) AS QTY,
											ISNULL(SUM(L.TOTAL),0) AS TOTAL ,
											0  AS LENDQTY,
											0 AS BORROWQTY,
											0 AS WNQTY,
											0 AS SNQTY,
											0 AS SALEQTY,
											0 AS BUYQTY
									FROM	INICOMMISSIONSTOCK L
									INNER JOIN #KTYPE K1 ON K1.TYPEID=L.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=L.KTYPEID --操作员仓库权限
									WHERE	L.TYPE = 144 AND 	L.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+' 
									GROUP BY L.PTYPEID,L.KTYPEID
	             					UNION ALL
	     							SELECT 	L.PTYPEID,
											L.KTYPEID,
									        CASE WHEN L.BILLTYPE=57 THEN 0 ELSE ISNULL(SUM(L.QTY),0)  END AS QTY,
											ISNULL(SUM(L.CostTOTAL),0) AS TOTAL ,
											0 AS LENDQTY,
											0 AS BORROWQTY,
											0 AS WNQTY,
											0 AS SNQTY,
											0 AS SALEQTY,
											0 AS BUYQTY
									FROM 	INOUTSTOCKTABLE  L
									INNER JOIN #KTYPE K1 ON K1.TYPEID=L.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=L.KTYPEID --操作员仓库权限
									WHERE 	L.KTYPEID<>''10000'' 
											AND L.AUDITED = 1
											AND  L.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+' 
											AND L.BILLDATE <='+CHAR(39)+@STARTDATE+CHAR(39)+'  	
									GROUP BY L.PTYPEID,L.KTYPEID,L.BILLTYPE	) B '
				IF @PTYPEID<>'00000' OR @MPTYPEID='-99999' OR @PTYPECATEGORYID<>''
					SET @SQL_CET=@SQL_CET+' INNER JOIN #PTYPE P ON B.PTYPEID=P.TYPEID	'
				SET @SQL_CET+='
					GROUP BY B.PTYPEID '
				--后半部分
				SET @SQL_CET+='		
									UNION ALL
			               			SELECT	T.TYPEID,
											0 AS QTY,
											0 AS TOTAL,
											-CAST(SUM(T.LEND) AS  NUMERIC(24, 10) ) AS LENDQTY, 
											CAST(SUM(T.BORROW) AS  NUMERIC(24, 10) ) AS BORROWQTY,
											0 AS WNQTY,
											0 AS SNQTY,
											SUM(T.SALEQTY),
										    SUM(T.BUYQTY)
										    
								 FROM 
									(
			               			SELECT	L.PTYPEID AS TYPEID,
			               					0 AS QTY,
			               					0 AS TOTAL,
											CASE WHEN (L.QTY > 0) THEN L.QTY ELSE 0 END AS BORROW,
											CASE WHEN (L.QTY < 0) THEN L.QTY ELSE 0 END AS LEND,
											0 AS SALEQTY,
											0 AS BUYQTY,
											0 AS WNQTY,
											0 AS SNQTY
									FROM 	[INIGOODSLEND]  L
									INNER JOIN #KTYPE K1 ON K1.TYPEID=L.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=L.KTYPEID --操作员仓库权限
									WHERE	L.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+' 
								
								UNION ALL
									SELECT  LB.PTYPEID AS TYPEID,
											0 AS QTY,
			               					0 AS TOTAL,
											CASE LI.BILLTYPE WHEN 71 THEN QTY WHEN 72 THEN QTY ELSE 0 END AS BORROW,
											CASE LI.BILLTYPE WHEN 87 THEN QTY WHEN 88 THEN QTY ELSE 0 END AS LEND,
											0 AS SALEQTY,
											0 AS BUYQTY,
											0 AS WNQTY,
											0 AS SNQTY
									FROM 	[LENDINDEX] LI 
									JOIN	[LENDBILL] LB ON (LI.BILLNUMBERID=LB.BILLNUMBERID)
									INNER JOIN #KTYPE K1 ON K1.TYPEID=LI.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=LI.KTYPEID --操作员仓库权限
												
									WHERE 	BILLDATE <= '+CHAR(39)+@STARTDATE+CHAR(39)+' 
									AND		LI.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+' 
								UNION ALL
									SELECT  LB.PTYPEID AS TYPEID,
											0 AS QTY,
			               					0 AS TOTAL,
			               					0 AS BORROW,
			               					0 AS LEND,
											LB.QTY AS SALEQTY,
											0 AS BUYQTY, 
											0 AS WNQTY,
											0 AS SNQTY
									FROM 	[BILLINDEX] LI 
									JOIN	[SALEBILL] LB ON (LI.BILLNUMBERID=LB.BILLNUMBERID)
									INNER JOIN #KTYPE K1 ON K1.TYPEID=LI.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=LI.KTYPEID --操作员仓库权限
												
									WHERE 	BILLDATE <= '+CHAR(39)+@STARTDATE+CHAR(39)+' 
											AND	LI.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+' 
											AND  LI.ISLEND=1
											AND REDWORD=0
											AND IFCHECK=''T''
											
								UNION ALL
									SELECT  LB.PTYPEID AS TYPEID,
											0 AS QTY,
			               					0 AS TOTAL,
			               					0 AS BORROW,
			               					0 AS LEND,
											0 AS SALEQTY,
											LB.QTY AS BUYQTY,
											0 AS WNQTY,
											0 AS SNQTY
									FROM 	BILLINDEX LI 
									JOIN	BUYBILL LB ON (LI.BILLNUMBERID=LB.BILLNUMBERID)
									INNER JOIN #KTYPE K1 ON K1.TYPEID=LI.KTYPEID
									INNER JOIN (
												SELECT U.TYPEID 
												FROM #KSTYPE U 
												JOIN #BTTYPE V 
												ON U.STYPEID=V.TYPEID) K ON K.TYPEID=LI.KTYPEID --操作员仓库权限
												
									WHERE 	BILLDATE <= '+CHAR(39)+@STARTDATE+CHAR(39)+' 
											AND  LI.ISLEND=1
											AND REDWORD=0
											AND IFCHECK=''T''						
											AND	LI.PTYPEID LIKE '+CHAR(39)+@INNERPTYPEID+'%'+CHAR(39)+' 					
										
										
								) T 
							GROUP BY T.TYPEID 
							'
								
END	
IF @SQL_CET<>''
EXEC (@SQL_CET)
INSERT INTO #T 
	SELECT	LEFT(W.PTYPEID,@LEN) AS PTYPEID,
			SUM(QTY) AS QTY,
			SUM(TOTAL) AS TOTAL,
			SUM(W.LENDQTY) AS LENDQTY,
			SUM(W.BORROWQTY)AS BORROWQTY,
			SUM(W.WNQTY) AS WNQTY,
			SUM(W.SNQTY) AS SNQTY,
			SUM(SALEQTY) AS SALEQTY,
			SUM(BUYQTY)	AS BUYQTY
	FROM	#CTE W  
	GROUP BY LEFT(W.PTYPEID,@LEN) 
	

DECLARE @SQL VARCHAR(8000)
SELECT  @SQL = ''

--=========================================================================================================当前库存状况表
IF ISDATE(@STARTDATE)<>1
	BEGIN
		SELECT @SQL = '
				SELECT	A.TYPEID,
						A.FULLNAME,
						A.USERCODE,
						A.ENTRYCODE,
						A.STANDARD,
						A.TYPE,
						A.AREA,
						A.SONNUM,
						A.LEVEAL,
						A.PARID,
						A.UNIT1,
						A.UNIT2,
						A.UNITRATE1,
						ISNULL(SUM(D.QTY),0) AS QTY,
						ISNULL(SUM(D.TOTAL),0) AS TOTAL,
						CAST(ISNULL(SUM(D.TOTAL)/CASE WHEN SUM(D.QTY)=0 THEN NULL ELSE SUM(D.QTY) END ,0) AS  NUMERIC(24, 10) ) AS PRICE,
						ISNULL(SUM(D.LENDQTY),0) AS LENDQTY,
						ISNULL(SUM(D.BORROWQTY),0) AS BORROWQTY,
						ISNULL(SUM(D.WNQTY),0) AS WNQTY,
						ISNULL(SUM(D.SNQTY),0) AS SNQTY,
						ISNULL(SUM(D.QTY),0)-ISNULL(SUM(D.LENDQTY),0)+ISNULL(SUM(D.BORROWQTY),0) AS SJCZQTY
				FROM #MAINTYPE  A 
				LEFT JOIN #T D ON A.TYPEID =  D.PTYPEID
				
				GROUP BY A.TYPEID,
						A.FULLNAME,
						A.USERCODE,
						A.ENTRYCODE,
						A.STANDARD,
						A.TYPE,
						A.AREA,
						A.SONNUM,
						A.LEVEAL,
						A.PARID,
						A.UNIT1,
						A.UNIT2,
						A.SORTID,
						A.UNITRATE1
				ORDER BY A.SORTID '

		EXEC(@SQL)
	END
--=========================================================================================================历史库存状况表
IF ISDATE(@STARTDATE)=1
	BEGIN
		SELECT @SQL = '		
			SELECT 	A.TYPEID,
					A.FULLNAME,
					A.USERCODE,
					A.ENTRYCODE,
					A.STANDARD,
					A.TYPE,
					A.AREA,
					A.SONNUM,
					A.LEVEAL,
					A.PARID,
					A.UNIT1,
					A.UNIT2,
					A.UNITRATE1,
					ISNULL(SUM(B.QTY),0) AS QTY,
					CAST(ISNULL(SUM(B.TOTAL)/CASE WHEN SUM(B.QTY)=0 THEN NULL ELSE SUM(B.QTY) END ,0) AS  NUMERIC(24, 10) ) AS PRICE,
					ISNULL(SUM(B.TOTAL),0) AS TOTAL ,
					ISNULL(SUM(B.LENDQTY),0)-ISNULL(SUM(B.SALEQTY),0 )AS LENDQTY,
					ISNULL(SUM(B.BORROWQTY),0)-ISNULL(SUM(B.BUYQTY),0) AS BORROWQTY,
					ISNULL(SUM(B.QTY),0)-(ISNULL(SUM(B.LENDQTY),0)-ISNULL(SUM(B.SALEQTY),0 ))+(ISNULL(SUM(B.BORROWQTY),0) -ISNULL(SUM(B.BUYQTY),0))AS SJCZQTY
			FROM 	 #MAINTYPE  A 
			LEFT JOIN #T B ON A.TYPEID = B.PTYPEID
				
			GROUP BY	A.TYPEID,
						A.FULLNAME,
						A.USERCODE,
						A.ENTRYCODE,
						A.STANDARD,
						A.TYPE,
						A.AREA,
						A.SONNUM,
						A.LEVEAL,
						A.PARID,
						A.UNIT1,
						A.UNIT2,
						A.SORTID,
						A.UNITRATE1 
				ORDER BY A.SORTID'
			EXEC(@SQL)
END


DROP TABLE #BTTYPE,#KTYPE,#PTYPE,#MAINTYPE,#KSTYPE,#CTE,#T













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryMx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryMx]
GO












/****** Object:  Stored PROCEDURE dbo.Gp_QueryMx    Script Date: 2002-6-20 10:14:51 ******/

---2002-4-8添加零售单
---2002-7-4 添加OrderBy参数及排序功能	王峰
--2002-12-4添加权限检查及赠送单。。。等    吴德水

--Gp_QueryMX  '2003-7-1','2003-7-31','00001000040000100004','0','0','0','','','','billdate','00001',''

CREATE                                PROCEDURE Gp_QueryMx
( 
	 @BeginDate	VARCHAR(25),
	 @EndDate	VARCHAR(25),
	 @AtypeId	VARCHAR(50),
	 @PtypeId	VARCHAR(50),
	 @BtypeId	VARCHAR(50),
	 @KtypeId	VARCHAR(50),
	 @cMode		VARCHAR(2),
	 @PreQty	 NUMERIC(24, 10)  OUTPUT,
	 @PreTotal	 NUMERIC(24, 10)  OUTPUT,
	 @OrderBy	VARCHAR(50),
	 @OperatorId     VARCHAR(50),       --操作员ID
	 @intType          INT=0,
	 @Flag            varchar(10)=''     -- 为00时，只取 output的值
)

--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @strQuery VARCHAR(1000)
SELECT @strQuery=''




-- 调拔调阅 加不限经手人权限 add by chen_qihua 2004-2-13 ===========

Declare @lim varchar(1)
SET @lim ='0'

SELECT   @lim =substring(b.lim,439,1)
FROM employee a inner join loginuser b 
on (a.typeid=b.etypeid)
inner join btype c on (b.btypeid=c.typeid)
where  b.etypeid=@OperatorId

IF @OperatorId<>''
BEGIN
	if @lim ='1' 
	BEGIN
		SELECT @strQuery=' AND c.EtypeId LIKE '+' case a.billtype when 17 then '+CHAR(39)+''+'%'+CHAR(39) +' when 21 then '+CHAR(39)+''+'%'+ char(39)+' else ' +char(39)+@MEtypeid+'%'+char(39)+'end'
	END
	else
	BEGIN
		SELECT @strQuery=' AND c.EtypeId LIKE '+ char(39)+@MEtypeid+'%'+char(39) --原来如此
	END
END

--由于此存储过程只统计现金银行明细财，因此不存在统计调拔单的问题 cqhua 2009-11-02
SET @strQuery =''

-- 职员权限
CREATE TABLE #Ktype (TypeID varchar(50),fullname varchar(66))
INSERT INTO #Ktype(typeid,fullname) select typeid,fullname from stock where typeid in (select typeid from F_GetManDetailKType(@OperatorID))


 -- ====================== end =================================

--IF @OperatorId<>''
  -- SELECT @strQuery=' AND c.EtypeId LIKE '+CHAR(39)+@MEtypeid+'%'+CHAR(39)

IF @AtypeId='' SELECT @AtypeId='0'
IF @PtypeId='' SELECT @PtypeId='0'
IF @BtypeId='' SELECT @BtypeId='0'
IF @KtypeId='' SELECT @KtypeId='0'
DECLARE @cz_query VARCHAR(8000),@dbname VARCHAR(20)
DECLARE @TempTotal  NUMERIC(24, 10) ,@TempQty  NUMERIC(24, 10) 
DECLARE @Sql VARCHAR (8000)
DECLARE  @GOODS_ID VARCHAR(50),
   @CASH_ID  VARCHAR(50),
   @CASH_BANK_ID VARCHAR(50),
   @AR_ID VARCHAR(50),
   @AP_ID VARCHAR(50),
   @GOODS_LOSS_ID VARCHAR(50),
   @GOODS_GET_ID VARCHAR(50),
   @ALLOT_PRICE_ID VARCHAR(50),
   @PRICE_INCOME_ID VARCHAR(50),     
   @BORROW_BUY_PRICE_ID VARCHAR(50), 
   @GOODS_GIVE_ID VARCHAR(50),       
   @GOODS_PRODUCE_ID VARCHAR(50),    
   @SALE_COST_ID VARCHAR(50),        
   @SALE_INCOME_ID VARCHAR(50),      
   @LEND_GOODS_ID VARCHAR(50),       
   @BORROW_GOODS_ID VARCHAR(50),     
   @BALANCE_ID VARCHAR(50),          
   @DEPRECIATION_ID VARCHAR(50),     
   @APPORTION_EXPENSE_ID VARCHAR(50),
   @INIT_MONEY_ID VARCHAR(50),       
   @ALL_INCOME_ID VARCHAR(50),       
   @ALL_EXPENSE_ID VARCHAR(50),      
   @PROFIT_ID VARCHAR(50),           
   @ASSETS_ID VARCHAR(50),           
   @DEBT_ID VARCHAR(50),             
   @POWER_ID VARCHAR(50),
   @ADDEBT_INCOME_ID VARCHAR(50),
   @ADDEBT_LOSE_ID VARCHAR(50)
 SELECT @GOODS_ID='0000100001'
 SELECT @CASH_ID='0000100003'
 SELECT @CASH_BANK_ID='0000100004'
 SELECT @AR_ID='0000100005'
 SELECT @AP_ID='0000200001'
 SELECT @GOODS_LOSS_ID='000040000200001' --           商品报损
 SELECT @GOODS_GET_ID='000030000200001'  --           商品报溢收入
  SELECT @ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
 SELECT @PRICE_INCOME_ID='000030000200003'--成本调价收入

-- SELECT @BORROW_BUY_PRICE_RECNO VARCHAR(50)= 28;
-- SELECT @GOODS_GIVE_RECNO = 000040000200002           商品赠出
 SELECT @GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
 SELECT @SALE_COST_ID='0000400001'--              『销售成本』
 SELECT @SALE_INCOME_ID='0000300001'--            『销售收入』
-- SELECT @LEND_GOODS_RECNO VARCHAR(50),       = 21;
-- SELECT @BORROW_GOODS_RECNO VARCHAR(50),     = 24;
 SELECT @BALANCE_ID='000030000200004'--           进货退货差价
 SELECT @DEPRECIATION_ID='000040000300002'--      固定资产折旧
 SELECT @APPORTION_EXPENSE_ID='0000100007'--      待摊费用
-- SELECT @INIT_MONEY_RECNO VARCHAR(50),       = 18;
 SELECT @ALL_INCOME_ID='00003' --          【收入类】
 SELECT @ALL_EXPENSE_ID='00004'--                 【支出类】
-- SELECT @PROFIT_RECNO VARCHAR(50),           = 19;

 SELECT @ASSETS_ID ='00001'  --【资产合计】
 SELECT @DEBT_ID='00002'   --【负债合计】
-- SELECT @POWER_RECNO VARCHAR(50)            = 4;
 SELECT @ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
 SELECT @ADDEBT_LOSE_ID='000040000300001' --调帐亏损





SELECT @dbname='listtable'
IF @ptypeid<>'0' AND @atypeid=@GOODS_ID
	BEGIN 
		SELECT @dbname='inoutstocktable'

		IF @ktypeid<>'0'
  			SELECT 	@preQty=ISNULL(SUM(a.qty),0),
					@preTotal=ISNULL(SUM(a.costtotal),0) 
			FROM 	inoutstocktable  a
                --过滤掉蓝单，红单
                Inner Join BillIndex b
                On a.BillNumberId=b.BillNumberId And b.RedWord=0
  			WHERE 	a.billdate<@begindate 
					AND a.ktypeid LIKE @ktypeid+'%' 
					AND a.KTypeID<>'10000' 
					AND a.KTypeID LIKE @MKTypeID+'%' 
					AND LEFT(a.ptypeid,len(@ptypeid))=@ptypeid 
					AND a.atypeid=@GOODS_ID
					 
 		ELSE
  			SELECT 	@preQty=ISNULL(SUM(a.qty),0),
					@preTotal=ISNULL(SUM(a.costtotal),0) 
  			FROM 	inoutstocktable a
                --过滤掉蓝单，红单
                Inner Join BillIndex b
                On a.BillNumberId=b.BillNumberId And b.RedWord=0
			WHERE 	a.billdate<@begindate 
					AND a.KTypeID<>'10000' 
					AND a.KTypeID LIKE @MKTypeID+'%' 
					AND LEFT(a.ptypeid,len(@ptypeid))=@ptypeid 
					AND a.atypeid=@GOODS_ID

		EXEC 	gp_getdbf @GOODS_ID,@ptypeid,'0','0',@ktypeid,'00','',@TempQty OUTPUT,@TempTotal OUTPUT
		
		SELECT 	@preQty=@preQty+@TempQty
 		
		SELECT @preTotal=@preTotal+@TempTotal
	END 
ELSE
	IF @btypeid<>'0' AND (@atypeid=@AR_ID OR @atypeid=@AP_ID)
		BEGIN
 			IF @atypeid=@AR_ID
 				BEGIN
  					SELECT 	@preTotal=ISNULL(SUM(total),0) 
  					FROM 	listtable 
  					WHERE 	billdate<@begindate 
							AND LEFT(btypeid,len(@btypeid))=@btypeid 
							AND atypeid=@AR_ID 
							AND audited=1
 
  					EXEC 	gp_getdbf @AR_ID,'0',@btypeid,'0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT
  
					SELECT 	@preQty=@preQty+@TempQty
  					SELECT 	@preTotal=@preTotal+@TempTotal
 				END 
			ELSE 
				IF @atypeid=@AP_ID
 					BEGIN
  						SELECT 	@preTotal=ISNULL(SUM(total),0) 
  						FROM 	listtable 
  						WHERE 	billdate<@begindate 
								AND LEFT(btypeid,len(@btypeid))=@btypeid 
								AND atypeid=@AP_ID 
								AND audited=1
 
  						EXEC 	gp_getdbf @AP_ID,'0',@btypeid,'0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT

  						SELECT @preQty=@preQty+@TempQty
  						SELECT @preTotal=@preTotal+@TempTotal
					END 
		END 
	ELSE 
		BEGIN
  			SELECT 	@preTotal=ISNULL(SUM(total),0) 
			--  FROM inoutstocktable 
  			FROM 	listtable 
  			WHERE 	billdate<@begindate 
					AND LEFT(atypeid,len(@atypeid))=@atypeid 
					AND audited=1 --AND btypeid='0' AND ptypeid='0' AND ktypeid='0'
 
  			EXEC 	gp_getdbf @atypeid,'0','0','0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT
  		
			SELECT @preQty=@preQty+@TempQty
  			SELECT @preTotal=@preTotal+@TempTotal

		END

SELECT @cz_Query=''
IF (RTRIM(@begindate) <>'' AND RTRIM(@enddate) <>'')
	SELECT @cz_Query=@cz_query+' a.billdate>='+CHAR(39)+@begindate+CHAR(39)+' AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+' AND '
IF RTRIM(@ptypeid)<>'0' AND RTRIM(@atypeid)=@GOODS_ID
BEGIN
	SELECT @cz_query=@cz_query+' LEFT(c.ptypeid,len('+CHAR(39)+@ptypeid+CHAR(39)+'))='+CHAR(39)+@ptypeid+CHAR(39)
	+' AND c.billnumberid=a.billnumberid'+ ' AND'
	SELECT @cz_query=@cz_query+' c.atypeid='+CHAR(39)+@GOODS_ID+CHAR(39) +' AND'
	SELECT @cz_query=@cz_query+' a.ifcheck='+CHAR(39)+'t'+CHAR(39) +' AND'
END
IF RTRIM(@ktypeid) <>'0'
	 SELECT @cz_query=@cz_query+' c.ktypeid LIKE '+CHAR(39)+@ktypeid+'%'+CHAR(39)
	  +' AND c.billnumberid=a.billnumberid'+ ' AND' 
IF RTRIM(@btypeid) <> '0' 
	 SELECT @cz_query=@cz_query+' LEFT(c.btypeid,len('+CHAR(39)+@btypeid+CHAR(39)+'))='+CHAR(39)+@btypeid+CHAR(39)
	  +' AND c.billnumberid=a.billnumberid'+ ' AND' 
IF RTRIM(@atypeid) <> '0' 
	 SELECT @cz_query=@cz_query+' LEFT(c.atypeid,len('+CHAR(39)+@atypeid+CHAR(39)+'))='+CHAR(39)+@atypeid+CHAR(39)
	  +' AND c.billnumberid=a.billnumberid '+ ' AND' 
IF UPPER(@cMode)='S'
	SELECT @cz_query=@cz_query+' (c.billtype=11 OR c.billtype=141 OR c.billtype=45 OR c.billtype=305 OR c.billtype = 155 OR c.billtype = 157) AND'
IF UPPER(@cMode)='B'
BEGIN	
	SELECT @cz_query=@cz_query+' (c.billtype=34 OR c.billtype=6 OR c.billtype = 145 OR c.billtype = 155 OR c.billtype = 157) AND'
END

-- 维修受理单和换货单加的条件
IF UPPER(@cMode)='S' AND @dbname='inoutstocktable'
	 SELECT @cz_query=@cz_query+' ((c.Billtype in (155,157) and c.qty<0 ) OR (c.Billtype not in (155,157))) AND'
IF UPPER(@cMode)='B' AND @dbname='inoutstocktable'
	 SELECT @cz_query=@cz_query+' ((c.Billtype in (155,157) and c.qty>0 ) OR (c.Billtype not in (155,157))) AND'
-- end
SELECT @cz_query=SUBSTRING(@cz_query,1,len(@cz_query)-4)



---- ADD BY MJG  2003-07-31 FOR Inoutstocktable 管理权限 
IF @intType = 1
	SELECT @cz_Query = @cz_Query +' AND ( c.btypeid LIKE '+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' OR c.btypeid LIKE '+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+') '

-- 销售，采购报表加上往来单位的权限
IF UPPER(@cMode)='S' OR  UPPER(@cMode)='B'
	SELECT @cz_Query = @cz_Query +' AND ( c.btypeid LIKE '+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' OR c.btypeid LIKE '+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+') '


--  OrderBy  --
--  ADD BY wangfeng  --
DECLARE @SQLOrder	VARCHAR(150)
SELECT @SQLOrder = ''

IF @OrderBy = 'ByDate_a'		--ORDER BY date
    SELECT @SQLOrder = ' ORDER BY c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 	--ORDER BY Bill No.
    SELECT @SQLOrder = ' ORDER BY a.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	--ORDER BY Bill type
    SELECT @SQLOrder = ' ORDER BY c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	--ORDER BY Bill ID
    SELECT @SQLOrder = ' ORDER BY a.ID'
ELSE IF @OrderBy = 'ByDate_d'		--ORDER BY date DESC 
    SELECT @SQLOrder = ' ORDER BY c.billdate DESC, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	--ORDER BY Bill No. DESC 
    SELECT @SQLOrder = ' ORDER BY a.BillCode DESC'
ELSE IF @OrderBy = 'ByBillType_d'	--ORDER BY Bill type DESC 
    SELECT @SQLOrder = ' ORDER BY c.billtype DESC, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	--ORDER BY Bill ID DESC 
    SELECT @SQLOrder = ' ORDER BY a.ID DESC'
ELSE
    SELECT @SQLOrder = ' ORDER BY c.billdate'


 SELECT @Sql ='SELECT 
					c.BillNumberId,
					c.BillDate,
					c.billtype,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.qty),0)	else  ISNULL(SUM(c.qty),0)	end as qty,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.Costtotal),0)	else  ISNULL(SUM(c.Costtotal),0)	end as Costtotal,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.total),0)	else  ISNULL(SUM(c.total),0)	end as total,
					c.CostPrice,
					a.BillCode, 
					a.Comment,
					a.RedWord, 
					CBillType=
						CASE a.billtype 
							WHEN 305 THEN ''零售单''
							WHEN 300 THEN ''销售订单''
							WHEN 11  THEN ''销售出库单''
							WHEN 45  THEN ''销售退货单''
							WHEN 4   THEN ''收款单''
							WHEN 144 THEN ''受托代销收货单''
							WHEN 145 THEN ''受托代销结算单''
							WHEN 146 THEN ''受托代销退货单''
							WHEN 147 THEN ''受托代销调价单''
							WHEN 140 THEN ''委托代销发货单''
							WHEN 141 THEN ''委托代销结算单''
							WHEN 142 THEN ''委托代销退货单''
							WHEN 143 THEN ''委托代销调价单''
							WHEN 301 THEN ''采购订单''
							WHEN 34  THEN ''采购入库单''
							WHEN 6   THEN ''采购退货''
							WHEN 66  THEN ''付款单''
							WHEN 17  THEN ''同价调拨''
							WHEN 21  THEN ''变价调拨''
							WHEN 9   THEN ''报损单''
							WHEN 14  THEN ''报溢单''
							WHEN 139 THEN ''赠送单''
							WHEN 126 THEN ''获赠单''
							WHEN 57  THEN ''调价单''
							WHEN 16  THEN ''商品拆装单''
							WHEN 87  THEN ''借出开单''
							WHEN 71  THEN ''借进开单''
							WHEN 88  THEN ''借出还回''
							WHEN 72  THEN ''借进还出''
							WHEN 116 THEN ''应收款增加''
							WHEN 115 THEN ''应收款减少''
							WHEN 128 THEN ''应付款增加''
							WHEN 129 THEN ''应付款减少''
							WHEN 36  THEN ''费用单''
							WHEN 93  THEN ''其他收入单''
							WHEN 77  THEN ''转款单''
							WHEN 84  THEN ''固定资产购买''
							WHEN 85  THEN ''固定资产变卖''
							WHEN 78  THEN ''固定资产折旧''
							WHEN 5   THEN ''待摊费用发生''
							WHEN 10  THEN ''待摊费用摊销''
							WHEN 148 THEN ''返利核算执行单''
							WHEN 149 THEN ''价保执行单''
							WHEN 150 THEN ''获利核算执行单''
							WHEN 155 THEN ''换货单''
							WHEN 157 THEN ''维修受理单''
							WHEN 158 THEN ''现金费用单''
							WHEN 159 THEN ''会计凭证''
							WHEN 160 THEN ''销售换货单''
							WHEN 161 THEN ''采购换货单''
							
						END,
			        (SELECT ISNULL(fullname,'''')
				    FROM ptype b
         			WHERE c.ptypeid = b.typeid) AS ptype,
        			case a.billtype when 145 then ''代销库'' 	else (SELECT ISNULL(fullname,'''')
					FROM Stock b
         			WHERE c.Ktypeid = b.typeid) 
					end
					AS Ktype,
		          	(SELECT ISNULL(fullname,'''')
        			FROM atype b
         			WHERE c.atypeid = b.typeid) AS Atype,
          			(SELECT ISNULL(fullname,'''')
         			FROM btype b
         			WHERE a.btypeid = b.typeid) AS btype,
					(SELECT ISNULL(fullname,'''')
         			FROM Employee e
         			WHERE a.etypeid = e.typeid) AS etype
		FROM '+@dbname+' c,BillIndex a WHERE '

IF UPPER(@cMode) <> 'S' AND UPPER(@cMode) <> 'B'
BEGIN --多级权限改的 cqhua 2009-11-02
	--	SELECT @SQL = @SQL + 'c.ktypeid<>'+CHAR(39)+'10000'+CHAR(39)+ ' AND c.KTypeID LIKE CASE c.KTypeID WHEN ''0'' THEN ''%'' WHEN '''' THEN ''%'' ELSE '''+@MKTypeID+'%'' END   AND '
	insert into #Ktype(typeid,fullname) select '0',''
	insert into #Ktype(typeid,fullname) select '','' -- 转款单的ktypeid=''
	SELECT @SQL = @SQL +'c.ktypeid in (select typeid from #Ktype) AND '
END
-- ============== add by chen_qihua 加红单限制
SELECT @SQL = @SQL + ' a.redword =0 AND '

-- ============== add by chen_qihua 销售，采购报表加仓库权限限制  2004-11-23
IF @dbname='inoutstocktable'
	SELECT @SQL = @SQL + '  (c.ktypeid='+CHAR(39)+'10000'+CHAR(39)+ ' OR c.KTypeID LIKE CASE c.KtypeID WHEN ''0'' THEN ''%'' WHEN '''' THEN ''%'' ELSE '''+@MKTypeID+'%'' END  ) AND '



DECLARE @GroupBy VARCHAR(2000)

SELECT @GroupBy ='  GROUP BY 
					c.BillNumberId,
					c.billdate,
					c.billtype,
					a.billtype,
					c.costprice,
					c.qty,
					a.billcode,
					a.comment,
					a.redword,
					c.ptypeid,
					c.ktypeid,
					c.atypeid,
					a.btypeid,
					a.etypeid,'

IF @OrderBy = 'ByDate_a'
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	
    SELECT @GroupBy = @GroupBy + ' a.ID'
ELSE IF @OrderBy = 'ByDate_d'		
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @OrderBy = 'ByBillType_d'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	
    SELECT @GroupBy = @GroupBy + ' a.ID'
ELSE
    SELECT @GroupBy = @GroupBy + ' c.billdate,a.BillCode' --默认排序方式



SELECT @SQL = @SQL + @cz_query +@strQuery+@GroupBy+@SQLOrder

IF @Flag ='00'
	RETURN 0
--print @sql
EXEC (@Sql)


DROP TABLE #Ktype























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





								SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryMx_Cqh]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryMx_Cqh]
GO

/*
 描述：添加批号 自由项，币种，汇率 基本计量单位 相关的原币等信息
  作者：彭勇
  日期：2012-05-27
*/

/*
  修改：添加货位列cargoid
  作者：黄飞佳
  日期：2012-4-24
  描述：添加cargoid列，查询出该列添加到明细表显示
*/

/*
	修改：增加折扣列
	作者：张陈仁
	日期：2011-7-18
	描述：只查销售、采购明细表
	
*/
/****** Object:  Stored PROCEDURE dbo.Gp_QueryMx    Script Date: 2002-6-20 10:14:51 ******/
-- 2009-10-28 cqhua
--只查销售、采购明细表

/*
       修改：优化
       作者：董湛
       日期：2012-11-20
       描述：把表值函数F_GetManPTypeDetailALL改为临时表#PtypeDetailALL
*/

/*
       修改：优化
       作者：杨俊
       日期：2014-12-25
       描述：去除多余的临时表，规范使用if的where条件。
*/
		
/*
    修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
*/


/*
  修改： 魏伟
  日期： 2016-06-07
  描述： 添加 换算率变更前采购单位数量 查询

*/

/*
  修改： 舒珊	
  日期： 2016-06-21
  描述： 添加 换算率变更前销售单位数量 查询

*/
CREATE PROCEDURE Gp_QueryMx_Cqh 
( 
	 @BeginDate		VARCHAR(25),
	 @EndDate		VARCHAR(25),
	 @AtypeId		VARCHAR(50),
	 @PtypeId		VARCHAR(50),
	 @BtypeId		VARCHAR(50),
	 @KtypeId		VARCHAR(MAX),
	 @cMode			VARCHAR(2),
	 @PreQty		 NUMERIC(24, 10)  OUTPUT,
	 @PreTotal		 NUMERIC(24, 10)  OUTPUT,
	 @OrderBy		VARCHAR(25),
     @sortfield		VARCHAR(25) = '',
	 @OperatorId	VARCHAR(50),    --操作员ID
	 @intType		INT = 0,
	 @Stypeid		VARCHAR(MAX),
	 @dtypeid		VARCHAR(50),	
	 @billtype		VARCHAR(50),    --默认为0时，全部单据
	 @item_id		VARCHAR(50),    --自由项id
	 @iscombined	VARCHAR(50),
	 @IsReporting	INT,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
	 @IsCountSendPtype INT			--是否统计发出商品,发出商品出库单、发出商品退货单、销售发货开票
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),
@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid 
OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense 
OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
-----------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------临时表---------------------------------------------------------
--商品
CREATE TABLE #Ptype
(
	TypeID VARCHAR(50)
)
IF(@PTypeID = '')
	INSERT INTO #Ptype(typeid) 
	SELECT typeid FROM F_GetManDetailPType(@OperatorID)
ELSE
	INSERT INTO #Ptype(typeid)
	SELECT a.typeid FROM F_GetManDetailPType(@OperatorID) a,(SELECT * FROM dbo.f_split(@PTypeID,',')) b 
	WHERE LEFT(a.typeid,LEN(b.a)) = b.a

--仓库
CREATE TABLE #Ktype
(
	TypeID VARCHAR(50)
)


IF(@KTypeID = '')
BEGIN
	INSERT INTO #Ktype(typeid)
	SELECT typeid FROM F_GetManDetailKType(@OperatorID)
	UNION
	SELECT '10000'
END
ELSE
	INSERT INTO #Ktype(typeid)
	SELECT a.typeid FROM F_GetManDetailKType(@OperatorID) a,(SELECT a FROM  dbo.f_split(@KTypeID,',')) b 
	WHERE LEFT(a.typeid,LEN(b.a)) = b.a
-----------------------------------------------------------------------------------------------------------------------------
DECLARE @SQL VARCHAR(MAX),@SQLOrder VARCHAR(MAX)

IF(@IsCountSendPtype = 1)
BEGIN
	SET @SQL = '
	SELECT 
	BillNumberId,
	CustomdetailID,
	BillDate,
	posttime,
	billtype,
	max(Convert( NUMERIC(24, 10) ,ISNULL(Price,0))) AS price,
	max(Convert( NUMERIC(24, 10) ,ISNULL(nprice,0)))AS nprice,
	Convert( NUMERIC(24, 10) ,ISNULL(Discount,1)) AS discount,
	CASE billtype 
		WHEN 145 THEN -ISNULL(SUM(qty),0)	
		ELSE ISNULL(SUM(qty),0)
	END AS qty,
	CASE
		WHEN billtype=145 or (billtype=160 and	qty<0) THEN -ISNULL(SUM(nqty),0) 
		ELSE ISNULL(SUM(nqty),0) 
	END AS nqty,
	CASE billtype 
		WHEN 145 THEN -ISNULL(SUM(Costtotal),0)
		ELSE ISNULL(SUM(Costtotal),0)
	END AS Costtotal,
	CASE billtype 
		WHEN 145 THEN -ISNULL(SUM(total),0)
		ELSE ISNULL(SUM(total),0)
	END AS total,
	CASE billtype 
		WHEN 145 THEN -ISNULL(SUM(ntotal),0)
		ELSE ISNULL(SUM(ntotal),0)
	END AS ntotal,				
	CostPrice,
	BillCode, 
	Comment,
	RedWord, 
	CBillType,
	ptype,
	dealbtype,
	btype,
	ktype,
	stype,	
	cargoid,
	ifullname,					--自由 项
	acfullname,					--币种
	goodsnumber,
	currate,
	rate,
	abs(SUM(nbrcqty)) AS nbrcqty,				--换算率变更前销售单位数量
	assistantfullname,			--浮动单位
	baseunitfullname,			--基本单位
	ufullname ,					--计量单位
	SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
	SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
	SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
	SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
	SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
	SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
	SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
	SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
	SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	,
	SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40,
	customassist=dbo.F_GetCustomAssist(c.ptype, ISNULL(SUM(c.qty),0) )
	FROM (
		SELECT 
			c.BillNumberId,
			c.id AS CustomdetailID,
			c.BillDate,
			a.posttime,
			c.billtype,
			ISNULL(c.Price,0) AS price,
			ISNULL(c.nprice,0)AS nprice,
			ISNULL(c.Discount,1) AS discount,
			ISNULL(c.qty,0) AS qty,
			ISNULL(c.nqty,0) AS nqty,
			ISNULL(c.Costtotal,0) AS Costtotal,
			ISNULL(c.total,0) AS total,
			ISNULL(c.ntotal,0) AS ntotal,				
			c.CostPrice,
			a.BillCode, 
			a.Comment,
			a.RedWord, 
			(SELECT BillName FROM BillName WHERE Billtype = c.billtype) AS CBillType,
			c.ptypeid AS ptype,
			a.DealBTypeID AS dealbtype,
			a.btypeid AS btype,
			c.ktypeid AS ktype,
			c.stypeid AS stype,	
			c.cargoid,
			b1.fullname AS ifullname,
			d1.fullname AS acfullname,
			c.goodsnumber,
			a.rate AS currate,
			d2.rate,
			CAST(c.qty/c.MUnitRate AS  NUMERIC(24, 10) )  AS nbrcqty,--换算率变更前销售单位数量
			u5.fullname AS assistantfullname,			--浮动单位
			u1.fullname AS baseunitfullname,			--基本单位
			e1.fullname AS ufullname ,					--计量单位	
			SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
			SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
			SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
			SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
			SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
			SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
			SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
			SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
			SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40		      
		FROM InoutStocktable c 
		INNER JOIN BillIndex a ON(c.billnumberid = a.billnumberid)
		LEFT JOIN vWeb_ItemIDByIsCombined b1 ON(b1.iscombined = c.IsCombined AND b1.id = c.ItemID)
		LEFT JOIN  Ac_Currency d1 ON(a.cid = d1.CId)
		LEFT JOIN PType_Units_Ext d2 ON(c.PtypeId = d2.PtypeID AND c.MUNITID = d2.UnitsId) 
		LEFT JOIN PType_Units e1 ON(d2.UnitsId = e1.UnitsId)
		INNER JOIN ptype p1 ON(c.ptypeid = p1.typeid)
		LEFT JOIN dbo.PType_Units u1 ON(u1.UnitsId = p1.baseUnitId)
		LEFT JOIN dbo.PType_Units u5 ON(u5.UnitsId = p1.AssistantUnitId)
		LEFT JOIN PType_Units_Ext r1 ON(r1.PTypeId = p1.TypeId AND p1.baseUnitId = r1.UnitsId)
		left join Custom_BillIndex csindex on c.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on c.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND c.id=csdetail.Detailid 
AND csdetail.InOrOut=CASE WHEN c.billtype IN(12,46) THEN ''O'' ELSE csdetail.InOrOut END

		WHERE c.billdate BETWEEN ''' + @begindate + ''' AND ''' + @enddate + '''
			AND a.draft = 0 
			AND a.redword = 0
			AND a.IsIni = 0
			AND (NOT(UPPER(''' + @cMode + ''') = ''B'') 
				OR (UPPER(''' + @cMode + ''') = ''B'') AND (NOT(''' + @billtype + ''' = ''0'') AND c.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
												OR (''' + @billtype + ''' = ''0'') AND c.billtype IN (34,6,145,161)
											 )
				)	
			AND (NOT(UPPER(''' + @cMode + ''') = ''S'')
				OR (UPPER(''' + @cMode + ''') = ''S'') AND (NOT(''' + @billtype + ''' = ''0'') AND c.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
												OR (''' + @billtype + ''' = ''0'') AND c.billtype IN (11,45,305,141,160,215,12,46)
											 )
				)
			AND (NOT(''' + @item_id + ''' <> '''') 
				OR (''' + @item_id + ''' <> '''') AND C.itemid = ''' + @item_id + ''')
			AND (NOT(''' + @iscombined + ''' <> '''') 
				OR (''' + @iscombined + ''' <> '''') AND C.iscombined = ''' + @iscombined + ''')
			AND a.ifYearBill = ''0'' 
			AND (NOT(''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999)
				OR (''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999) AND c.ptypeid IN (SELECT TypeID FROM #Ptype))
			AND (NOT(''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999)
				OR (''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999) AND c.btypeid IN (SELECT TypeID FROM F_GetManDetailBType(''' + @OperatorID + ''')))
			AND (NOT(''' + @METypeID + ''' = -99999)
				OR (''' + @METypeID + ''' = -99999) AND c.etypeid IN (SELECT typeid FROM F_GetManDetailEType(''' + @OperatorID + ''')))
			AND (NOT(''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999)
				OR (''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999) AND c.ktypeid IN (SELECT TypeID FROM #Ktype))
			AND (NOT(''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''')
				OR (''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''') AND c.stypeid IN (SELECT TypeID FROM F_GetAllManagerBaseTypeId(''' + @STypeID + ''',11,''' + @OperatorID + ''')))
			AND (NOT(''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''')
				OR (''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''') AND c.dtypeid IN (SELECT typeid FROM F_GetAllManagerBaseTypeId(''' + @dtypeid + ''',9,''' + @OperatorID + '''))) 	
				
		UNION ALL
		--发出商品出库单
		SELECT 
			c.BillNumberId,
			c.id AS CustomdetailID,
			A.BillDate,
			a.posttime,
			A.billtype,
			ISNULL(c.DiscountPrice,0) AS price,
			ISNULL(c.NDiscountPrice,0) AS nprice,
			ISNULL(c.Discount,1) AS discount,
			-ISNULL(c.Qty - c.InvoiceQty,0) AS qty,
			-ISNULL(c.NQty - c.InvoiceNQty,0) AS nqty,
			-ISNULL(c.Costtotal - c.InvoiceCostTotal,0) AS Costtotal,
			CASE c.InvoiceQty
				WHEN 0 THEN -c.total
				ELSE -(ISNULL(c.Qty - c.InvoiceQty,0) * c.DiscountPrice) 
			END AS total,
			CASE c.InvoiceQty
				WHEN 0 THEN -c.ntotal
				ELSE -(ISNULL(c.Qty - c.InvoiceQty,0) * c.NDiscountPrice)
			END AS ntotal,
			c.CostPrice,
			a.BillCode, 
			a.Comment,
			a.RedWord, 
			(SELECT BillName FROM BillName WHERE Billtype = A.billtype) AS CBillType,
			c.ptypeid AS ptype,
			a.DealBTypeID AS dealbtype,
			a.btypeid AS btype,
			c.ktypeid AS ktype,
			c.stypeid AS stype,	
			c.cargoid,
			b1.fullname AS ifullname,
			d1.fullname AS acfullname,
			c.goodsnumber,
			a.rate AS currate,
			d2.rate,
			c.MQty  AS nbrcqty,--换算率变更前销售单位数量
			u5.fullname AS assistantfullname,			--浮动单位
			u1.fullname AS baseunitfullname,			--基本单位
			e1.fullname AS ufullname ,					--计量单位	
			SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
			SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
			SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
			SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
			SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
			SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
			SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
			SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
			SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40	
		FROM SendBill AS C
		INNER JOIN BillIndex AS A ON(C.BillNumberId = A.BillNumberId)
		LEFT JOIN vWeb_ItemIDByIsCombined b1 ON(b1.iscombined = c.IsCombined AND b1.id = c.ItemID)
		LEFT JOIN  Ac_Currency d1 ON(a.cid = d1.CId)
		LEFT JOIN PType_Units_Ext d2 ON(c.PtypeId = d2.PtypeID AND c.MUNITID = d2.UnitsId) 
		LEFT JOIN PType_Units e1 ON(d2.UnitsId = e1.UnitsId)
		INNER JOIN ptype p1 ON(c.ptypeid = p1.typeid)
		LEFT JOIN dbo.PType_Units u1 ON(u1.UnitsId = p1.baseUnitId)
		LEFT JOIN dbo.PType_Units u5 ON(u5.UnitsId = p1.AssistantUnitId)
		LEFT JOIN PType_Units_Ext r1 ON(r1.PTypeId = p1.TypeId AND p1.baseUnitId = r1.UnitsId)
			left join Custom_BillIndex csindex on c.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on c.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND c.id=csdetail.Detailid
			
		WHERE A.billdate BETWEEN ''' + @begindate + ''' AND ''' + @enddate + '''
			AND a.draft = 0 
			AND a.redword = 0
			AND a.IsIni = 0
			AND a.ifYearBill = ''0'' 
			AND (NOT(UPPER(''' + @cMode + ''') = ''B'') 
				OR (UPPER(''' + @cMode + ''') = ''B'') AND (NOT(''' + @billtype + ''' = ''0'') AND a.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
												OR (''' + @billtype + ''' = ''0'') AND a.billtype IN (34,6,145,161)
											 )
				)	
			AND (NOT(UPPER(''' + @cMode + ''') = ''S'')
				OR (UPPER(''' + @cMode + ''') = ''S'') AND (NOT(''' + @billtype + ''' = ''0'') AND a.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
												OR (''' + @billtype + ''' = ''0'') AND a.billtype IN (402)
											 )
				)
			AND (NOT(''' + @item_id + ''' <> '''') 
				OR (''' + @item_id + ''' <> '''') AND C.itemid = ''' + @item_id + ''')
			AND (NOT(''' + @iscombined + ''' <> '''') 
				OR (''' + @iscombined + ''' <> '''') AND C.iscombined = ''' + @iscombined + ''')
			AND (NOT(''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999)
				OR (''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999) AND c.ptypeid IN (SELECT TypeID FROM #Ptype))
			AND (NOT(''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999)
				OR (''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999) AND A.btypeid IN (SELECT TypeID FROM F_GetManDetailBType(''' + @OperatorID + ''')))
			AND (NOT(''' + @METypeID + ''' = -99999)
				OR (''' + @METypeID + ''' = -99999) AND A.etypeid IN (SELECT typeid FROM F_GetManDetailEType(''' + @OperatorID + ''')))
			AND (NOT(''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999)
				OR (''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999) AND c.ktypeid IN (SELECT TypeID FROM #Ktype))
			AND (NOT(''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''')
				OR (''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''') AND c.stypeid IN (SELECT TypeID FROM F_GetAllManagerBaseTypeId(''' + @STypeID + ''',11,''' + @OperatorID + ''')))
			AND (NOT(''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''')
				OR (''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''') AND A.dtypeid IN (SELECT typeid FROM F_GetAllManagerBaseTypeId(''' + @dtypeid + ''',9,''' + @OperatorID + '''))) 	
				
			UNION ALL
			--发出商品退货单
			SELECT 
				c.BillNumberId,
				c.id AS CustomdetailID,
				A.BillDate,
				a.posttime,
				A.billtype,
				ISNULL(c.DiscountPrice,0) AS price,
				ISNULL(c.NDiscountPrice,0) AS nprice,
				ISNULL(c.Discount,1) AS discount,
				ISNULL(c.Qty - c.InvoiceQty,0) AS qty,
				ISNULL(c.NQty - c.InvoiceNQty,0) AS nqty,
				ISNULL(c.Costtotal - c.InvoiceCostTotal,0) AS Costtotal,
				CASE c.InvoiceQty
					WHEN 0 THEN c.total
					ELSE ISNULL(c.Qty - c.InvoiceQty,0) * c.DiscountPrice
				END AS total,
				CASE c.InvoiceQty
					WHEN 0 THEN c.ntotal
					ELSE ISNULL(c.Qty - c.InvoiceQty,0) * c.NDiscountPrice
				END AS ntotal,
				c.CostPrice,
				a.BillCode, 
				a.Comment,
				a.RedWord, 
				(SELECT BillName FROM BillName WHERE Billtype = A.billtype) AS CBillType,
				c.ptypeid AS ptype,
				a.DealBTypeID AS dealbtype,
				a.btypeid AS btype,
				c.ktypeid AS ktype,
				c.stypeid AS stype,	
				c.cargoid,
				b1.fullname AS ifullname,
				d1.fullname AS acfullname,
				c.goodsnumber,
				a.rate AS currate,
				d2.rate,
				c.MQty  AS nbrcqty,--换算率变更前销售单位数量
				u5.fullname AS assistantfullname,			--浮动单位
				u1.fullname AS baseunitfullname,			--基本单位
				e1.fullname AS ufullname 	,				--计量单位	
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
				SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40	
			FROM SendBackBill AS C
			INNER JOIN BillIndex AS A ON(C.BillNumberId = A.BillNumberId)
			LEFT JOIN vWeb_ItemIDByIsCombined b1 ON(b1.iscombined = c.IsCombined AND b1.id = c.ItemID)
			LEFT JOIN  Ac_Currency d1 ON(a.cid = d1.CId)
			LEFT JOIN PType_Units_Ext d2 ON(c.PtypeId = d2.PtypeID AND c.MUNITID = d2.UnitsId) 
			LEFT JOIN PType_Units e1 ON(d2.UnitsId = e1.UnitsId)
			INNER JOIN ptype p1 ON(c.ptypeid = p1.typeid)
			LEFT JOIN dbo.PType_Units u1 ON(u1.UnitsId = p1.baseUnitId)
			LEFT JOIN dbo.PType_Units u5 ON(u5.UnitsId = p1.AssistantUnitId)
			LEFT JOIN PType_Units_Ext r1 ON(r1.PTypeId = p1.TypeId AND p1.baseUnitId = r1.UnitsId)
				left join Custom_BillIndex csindex on c.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on c.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND c.id=csdetail.Detailid
			WHERE A.billdate BETWEEN ''' + @begindate + ''' AND ''' + @enddate + '''
				AND a.draft = 0 
				AND a.redword = 0
				AND a.IsIni = 0
				AND a.ifYearBill = ''0'' 
				AND (NOT(UPPER(''' + @cMode + ''') = ''B'') 
					OR (UPPER(''' + @cMode + ''') = ''B'') AND (NOT(''' + @billtype + ''' = ''0'') AND a.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
													OR (''' + @billtype + ''' = ''0'') AND a.billtype IN (34,6,145,161)
												 )
					)	
				AND (NOT(UPPER(''' + @cMode + ''') = ''S'')
					OR (UPPER(''' + @cMode + ''') = ''S'') AND (NOT(''' + @billtype + ''' = ''0'') AND a.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
													OR (''' + @billtype + ''' = ''0'') AND a.billtype IN (403)
												 )
					)
				AND (NOT(''' + @item_id + ''' <> '''') 
					OR (''' + @item_id + ''' <> '''') AND C.itemid = ''' + @item_id + ''')
				AND (NOT(''' + @iscombined + ''' <> '''') 
					OR (''' + @iscombined + ''' <> '''') AND C.iscombined = ''' + @iscombined + ''')
				AND (NOT(''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999)
					OR (''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999) AND c.ptypeid IN (SELECT TypeID FROM #Ptype))
				AND (NOT(''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999)
					OR (''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999) AND A.btypeid IN (SELECT TypeID FROM F_GetManDetailBType(''' + @OperatorID + ''')))
				AND (NOT(''' + @METypeID + ''' = -99999)
					OR (''' + @METypeID + ''' = -99999) AND A.etypeid IN (SELECT typeid FROM F_GetManDetailEType(''' + @OperatorID + ''')))
				AND (NOT(''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999)
					OR (''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999) AND c.ktypeid IN (SELECT TypeID FROM #Ktype))
				AND (NOT(''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''')
					OR (''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''') AND c.stypeid IN (SELECT TypeID FROM F_GetAllManagerBaseTypeId(''' + @STypeID + ''',11,''' + @OperatorID + ''')))
				AND (NOT(''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''')
					OR (''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''') AND A.dtypeid IN (SELECT typeid FROM F_GetAllManagerBaseTypeId(''' + @dtypeid + ''',9,''' + @OperatorID + '''))) 	
				
			UNION ALL
			--销售发货开票
			SELECT 
				c.BillNumberId,
				c.id AS CustomdetailID,
				A.BillDate,
				a.posttime,
				c.billtype,
				ISNULL(c.Price,0) AS price,
				ISNULL(c.NPrice,0) AS nprice,
				ISNULL(c.Discount,1) AS discount,
				-ISNULL(c.Qty,0) AS qty,
				-ISNULL(c.NQty,0) AS nqty,
				-ISNULL(c.InvoiceCostTotal,0) AS Costtotal,
				-ISNULL(c.total,0) AS total,
				-ISNULL(c.ntotal,0) AS ntotal,
				c.InvoiceCostPrice AS CostPrice,
				a.BillCode, 
				a.Comment,
				a.RedWord, 
				(SELECT BillName FROM BillName WHERE Billtype = c.billtype) AS CBillType,
				c.ptypeid AS ptype,
				a.DealBTypeID AS dealbtype,
				a.btypeid AS btype,
				c.ktypeid AS ktype,
				c.stypeid AS stype,	
				c.cargoid,
				b1.fullname AS ifullname,
				d1.fullname AS acfullname,
				c.goodsnumber,
				a.rate AS currate,
				d2.rate,
				c.MQty  AS nbrcqty,--换算率变更前销售单位数量
				u5.fullname AS assistantfullname,			--浮动单位
				u1.fullname AS baseunitfullname,			--基本单位
				e1.fullname AS ufullname ,					--计量单位
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
				SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40	
			FROM ReceiptBill AS C
			INNER JOIN dbo.ReceiptBillIndex AS A ON(A.BillNumberID = C.BillNumberID AND A.BillType = C.BillType)
			LEFT JOIN vWeb_ItemIDByIsCombined b1 ON(b1.iscombined = c.IsCombined AND b1.id = c.ItemID)
			LEFT JOIN  Ac_Currency d1 ON(a.cid = d1.CId)
			LEFT JOIN PType_Units_Ext d2 ON(c.PtypeId = d2.PtypeID AND c.MUNITID = d2.UnitsId) 
			LEFT JOIN PType_Units e1 ON(d2.UnitsId = e1.UnitsId)
			INNER JOIN ptype p1 ON(c.ptypeid = p1.typeid)
			LEFT JOIN dbo.PType_Units u1 ON(u1.UnitsId = p1.baseUnitId)
			LEFT JOIN dbo.PType_Units u5 ON(u5.UnitsId = p1.AssistantUnitId)
			LEFT JOIN PType_Units_Ext r1 ON(r1.PTypeId = p1.TypeId AND p1.baseUnitId = r1.UnitsId)
				left join Custom_BillIndex csindex on c.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on c.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND c.id=csdetail.Detailid
			WHERE A.billdate BETWEEN ''' + @begindate + ''' AND ''' + @enddate + '''
				AND a.draft = 0 
				AND a.redword = 0
				AND a.IsIni = 0
				AND A.BillType = 405
				AND a.ifYearBill = ''0'' 
				AND (NOT(UPPER(''' + @cMode + ''') = ''B'') 
					OR (UPPER(''' + @cMode + ''') = ''B'') AND (NOT(''' + @billtype + ''' = ''0'') AND a.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
													OR (''' + @billtype + ''' = ''0'') AND a.billtype IN (34,6,145,161)
												 )
					)	
				AND (NOT(UPPER(''' + @cMode + ''') = ''S'')
					OR (UPPER(''' + @cMode + ''') = ''S'') AND (NOT(''' + @billtype + ''' = ''0'') AND a.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
													OR (''' + @billtype + ''' = ''0'') AND a.billtype IN (405)
												 )
					)
				AND (NOT(''' + @item_id + ''' <> '''') 
					OR (''' + @item_id + ''' <> '''') AND C.itemid = ''' + @item_id + ''')
				AND (NOT(''' + @iscombined + ''' <> '''') 
					OR (''' + @iscombined + ''' <> '''') AND C.iscombined = ''' + @iscombined + ''')
				AND (NOT(''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999)
					OR (''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999) AND c.ptypeid IN (SELECT TypeID FROM #Ptype))
				AND (NOT(''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999)
					OR (''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999) AND A.btypeid IN (SELECT TypeID FROM F_GetManDetailBType(''' + @OperatorID + ''')))
				AND (NOT(''' + @METypeID + ''' = -99999)
					OR (''' + @METypeID + ''' = -99999) AND A.etypeid IN (SELECT typeid FROM F_GetManDetailEType(''' + @OperatorID + ''')))
				AND (NOT(''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999)
					OR (''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999) AND c.ktypeid IN (SELECT TypeID FROM #Ktype))
				AND (NOT(''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''')
					OR (''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''') AND c.stypeid IN (SELECT TypeID FROM F_GetAllManagerBaseTypeId(''' + @STypeID + ''',11,''' + @OperatorID + ''')))
				AND (NOT(''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''')
					OR (''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''') AND A.dtypeid IN (SELECT typeid FROM F_GetAllManagerBaseTypeId(''' + @dtypeid + ''',9,''' + @OperatorID + '''))) 	
	'
	--分组
	SET @SQL += '
					) AS c 
					GROUP BY BillNumberId,CustomdetailID,billdate,posttime,billtype,costprice,qty,Discount,billcode,
						comment,redword,CBillType,ptype,dealbtype,btype,ktype,stype,cargoid,ifullname,acfullname,
						goodsnumber,currate,rate,nqty,baseunitfullname,assistantfullname,ufullname,
						SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
						SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
						SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
						SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
						SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
						SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
						SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
						SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	,
						SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40	,'
	IF @OrderBy = 'ByDate_a'
		SET @SQL += 'billdate,billtype,BillCode '
	ELSE IF @OrderBy = 'ByBillNo_a' 
		SET @SQL += 'BillCode'
	ELSE IF @OrderBy = 'ByBillType_a'	
		SET @SQL += 'billtype,billdate,BillCode '
	ELSE IF @OrderBy = 'ByBillID_a'	
		SET @SQL += 'posttime '
	ELSE IF @OrderBy = 'ByDate_d'		
		SET @SQL += 'billdate,billtype,BillCode '
	ELSE IF @OrderBy = 'ByBillNo_d' 	
		SET @SQL += 'BillCode'
	ELSE IF @OrderBy = 'ByBillType_d'	
		SET @SQL += 'billtype,billdate,BillCode '
	ELSE IF @OrderBy = 'ByBillID_d'	
		SET @SQL += 'posttime '
	ELSE
		SET @SQL += 'billdate '
	--排序
	IF @OrderBy = 'ByDate_a'
		SET @SQLOrder = '
					ORDER BY billdate,billtype,BillCode'
	ELSE IF @OrderBy = 'ByBillNo_a'
		SET @SQLOrder = '
					ORDER BY BillCode'
	ELSE IF @OrderBy = 'ByBillType_a'
		SET @SQLOrder = '
					ORDER BY billtype,billdate,BillCode'
	ELSE IF @OrderBy = 'ByBillID_a'
		SET @SQLOrder = '
					ORDER BY posttime'
	ELSE IF @OrderBy = 'ByDate_d'
		SET @SQLOrder = '
					ORDER BY billdate DESC,billtype,BillCode'
	ELSE IF @OrderBy = 'ByBillNo_d'
		SET @SQLOrder = '
					ORDER BY BillCode DESC'
	ELSE IF @OrderBy = 'ByBillType_d'
		SET @SQLOrder = '
					ORDER BY billtype DESC,billdate,BillCode'
	ELSE IF @OrderBy = 'ByBillID_d'
		SET @SQLOrder = '
					ORDER BY posttime DESC'
	ELSE
		SET @SQLOrder = '
					ORDER BY billdate'
END
ELSE
BEGIN
	SET @SQL = '
	SELECT 
		c.BillNumberId,
		c.id AS CustomdetailID,
		c.BillDate,
		a.posttime,
		c.billtype,
		max(Convert( NUMERIC(24, 10) ,ISNULL(c.Price,0))) AS price,
		max(Convert( NUMERIC(24, 10) ,ISNULL(c.nprice,0)))AS nprice,
		Convert( NUMERIC(24, 10) ,ISNULL(c.Discount,1)) AS discount,
		CASE a.billtype 
			WHEN 145 THEN -ISNULL(SUM(c.qty),0)	
			ELSE ISNULL(SUM(c.qty),0)
		END AS qty,
		CASE a.billtype 
			WHEN 145 THEN -ISNULL(SUM(c.Costtotal),0)
			ELSE ISNULL(SUM(c.Costtotal),0)
		END AS Costtotal,
		CASE a.billtype 
			WHEN 145 THEN -ISNULL(SUM(c.total),0)
			ELSE ISNULL(SUM(c.total),0)
		END AS total,
		CASE a.billtype 
			WHEN 145 THEN -ISNULL(SUM(c.ntotal),0)
			ELSE ISNULL(SUM(c.ntotal),0)
		END AS ntotal,				
		c.CostPrice,
		a.BillCode, 
		a.Comment,
		a.RedWord, 
		(SELECT BillName FROM BillName WHERE Billtype = a.billtype) AS CBillType,
		c.ptypeid AS ptype,
		a.DealBTypeID AS dealbtype,
		a.btypeid AS btype,
		c.ktypeid AS ktype,
		c.stypeid AS stype,	
		c.cargoid,
		b1.fullname AS ifullname,					--自由 项
		d1.fullname AS acfullname,					--币种
		c.goodsnumber,
		a.rate AS currate,
		d2.rate,
		abs(CAST(SUM(c.qty)/c.MUnitRate AS  NUMERIC(24, 10) ) ) AS nbrcqty,--换算率变更前销售单位数量
		--abs(SUM(c.MQTY)) as nbrcqty,								--换算率变更前销售单位数量
		CASE
			WHEN a.billtype=145 or (a.billtype=160 and	c.qty<0) THEN -ISNULL(SUM(c.nqty),0) 
			ELSE ISNULL(SUM(c.nqty),0) 
		END AS nqty,
		u5.fullname AS assistantfullname,			--浮动单位
		u1.fullname AS baseunitfullname	,			--基本单位
		e1.fullname AS ufullname 	,				--计量单位	
		SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
		SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
		SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
		SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
		SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
		SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
		SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
		SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
		SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
		SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40
	FROM InoutStocktable c 
	INNER JOIN BillIndex a ON(c.billnumberid = a.billnumberid)
	LEFT JOIN vWeb_ItemIDByIsCombined b1 ON(b1.iscombined = c.IsCombined AND b1.id = c.ItemID)
	LEFT JOIN  Ac_Currency d1 ON(a.cid = d1.CId)
	LEFT JOIN PType_Units_Ext d2 ON(c.PtypeId = d2.PtypeID AND c.MUNITID = d2.UnitsId) 
	--LEFT JOIN #Rate AS rate ON (rate.PtypeID = c.PtypeId )  
	LEFT JOIN PType_Units e1 ON(d2.UnitsId = e1.UnitsId)
	INNER JOIN ptype p1 ON(c.ptypeid = p1.typeid)
	LEFT JOIN dbo.PType_Units u1 ON(u1.UnitsId = p1.baseUnitId)
	LEFT JOIN dbo.PType_Units u5 ON(u5.UnitsId = p1.AssistantUnitId)
	LEFT JOIN PType_Units_Ext r1 ON(r1.PTypeId = p1.TypeId AND p1.baseUnitId = r1.UnitsId)
	left join Custom_BillIndex csindex on c.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on c.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND c.id=csdetail.Detailid 
AND csdetail.InOrOut=CASE WHEN c.billtype IN(12,46) THEN ''O'' ELSE csdetail.InOrOut END
	WHERE c.billdate BETWEEN ''' + @begindate + ''' AND ''' + @enddate + '''
		AND a.draft = 0 
		AND a.redword = 0
		AND a.IsIni = 0
		AND (NOT(UPPER(''' + @cMode + ''') = ''B'') 
			OR (UPPER(''' + @cMode + ''') = ''B'') AND (NOT(''' + @billtype + ''' = ''0'') AND c.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
											OR (''' + @billtype + ''' = ''0'') AND c.billtype IN (34,6,145,161)
										 )
			)	
		AND (NOT(UPPER(''' + @cMode + ''') = ''S'')
			OR (UPPER(''' + @cMode + ''') = ''S'') AND (NOT(''' + @billtype + ''' = ''0'') AND c.billtype IN (SELECT A FROM dbo.F_Split(''' + @billtype + ''','',''))
											OR (''' + @billtype + ''' = ''0'') AND c.billtype IN (11,45,305,141,160,215,12,46)
										 )
			)
		AND (NOT(''' + @item_id + ''' <> '''') 
			OR (''' + @item_id + ''' <> '''') AND C.itemid = ''' + @item_id + ''')
		AND (NOT(''' + @iscombined + ''' <> '''') 
			OR (''' + @iscombined + ''' <> '''') AND C.iscombined = ''' + @iscombined + ''')
		AND a.ifYearBill = ''0'' 
		AND (NOT(''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999)
			OR (''' + @PTypeID + ''' <> '''' OR ''' + @MPTypeID + ''' = -99999) AND c.ptypeid IN (SELECT TypeID FROM #Ptype))
		AND (NOT(''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999)
			OR (''' + @BTypeID + ''' <> '''' OR ''' + @MBTypeID + ''' = -99999) AND c.btypeid IN (SELECT TypeID FROM F_GetManDetailBType(''' + @OperatorID + ''')))
		AND (NOT(''' + @METypeID + ''' = -99999)
			OR (''' + @METypeID + ''' = -99999) AND c.etypeid IN (SELECT typeid FROM F_GetManDetailEType(''' + @OperatorID + ''')))
		AND (NOT(''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999)
			OR (''' + @KTypeID + ''' <> '''' OR ''' + @MKTypeID + ''' = -99999) AND c.ktypeid IN (SELECT TypeID FROM #Ktype))
		AND (NOT(''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''')
			OR (''' + @MStypeid + ''' <> ''00000'' OR ''' + @Stypeid + ''' <> '''') AND c.stypeid IN (SELECT TypeID FROM F_GetAllManagerBaseTypeId(''' + @STypeID + ''',11,''' + @OperatorID + ''')))
		AND (NOT(''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''')
			OR (''' + @MDtypeid + ''' <> ''00000'' OR ''' + @dtypeid + ''' <> '''') AND c.dtypeid IN (SELECT typeid FROM F_GetAllManagerBaseTypeId(''' + @dtypeid + ''',9,''' + @OperatorID + '''))) 	
	'
	--分组
	SET @SQL += '
					GROUP BY c.BillNumberId,c.id,c.billdate,a.posttime,c.billtype,a.billtype,c.costprice,c.qty,c.MUnitRate,c.Discount,a.billcode,
						a.comment,a.redword,c.ptypeid,a.DealBTypeID,a.btypeid,c.ktypeid,c.stypeid,c.cargoid,b1.fullname,d1.fullname,
						c.goodsnumber,a.rate,d2.rate,c.nqty,u1.fullname,u5.fullname,e1.fullname,
						SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
						SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
						SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
						SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
						SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
						SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
						SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
						SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	,
						SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40,'
	IF @OrderBy = 'ByDate_a'
		SET @SQL += 'c.billdate,c.billtype,a.BillCode '
	ELSE IF @OrderBy = 'ByBillNo_a' 
		SET @SQL += 'a.BillCode'
	ELSE IF @OrderBy = 'ByBillType_a'	
		SET @SQL += 'c.billtype,c.billdate,a.BillCode '
	ELSE IF @OrderBy = 'ByBillID_a'	
		SET @SQL += 'a.posttime '
	ELSE IF @OrderBy = 'ByDate_d'		
		SET @SQL += 'c.billdate,c.billtype,a.BillCode '
	ELSE IF @OrderBy = 'ByBillNo_d' 	
		SET @SQL += 'a.BillCode'
	ELSE IF @OrderBy = 'ByBillType_d'	
		SET @SQL += 'c.billtype,c.billdate,a.BillCode '
	ELSE IF @OrderBy = 'ByBillID_d'	
		SET @SQL += 'a.posttime '
	ELSE
		SET @SQL += 'c.billdate '
	--排序
	IF @OrderBy = 'ByDate_a'
		SET @SQLOrder = '
					ORDER BY c.billdate,c.billtype,a.BillCode'
	ELSE IF @OrderBy = 'ByBillNo_a'
		SET @SQLOrder = '
					ORDER BY a.BillCode'
	ELSE IF @OrderBy = 'ByBillType_a'
		SET @SQLOrder = '
					ORDER BY c.billtype,c.billdate,a.BillCode'
	ELSE IF @OrderBy = 'ByBillID_a'
		SET @SQLOrder = '
					ORDER BY a.posttime'
	ELSE IF @OrderBy = 'ByDate_d'
		SET @SQLOrder = '
					ORDER BY c.billdate DESC,c.billtype,a.BillCode'
	ELSE IF @OrderBy = 'ByBillNo_d'
		SET @SQLOrder = '
					ORDER BY a.BillCode DESC'
	ELSE IF @OrderBy = 'ByBillType_d'
		SET @SQLOrder = '
					ORDER BY c.billtype DESC,c.billdate,a.BillCode'
	ELSE IF @OrderBy = 'ByBillID_d'
		SET @SQLOrder = '
					ORDER BY a.posttime DESC'
	ELSE
		SET @SQLOrder = '
					ORDER BY c.billdate'	
END				
----------------------------------------------------------

SET @SQL = @SQL + @SQLOrder
--PRINT @SQL
EXEC(@SQL)
	
------------------------------------------------------------

DROP TABLE #Ptype,#Ktype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryMx_New]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryMx_New]
GO



---2002-4-8添加零售单
---2002-7-4 添加OrderBy参数及排序功能	王峰
--2002-12-4添加权限检查及赠送单。。。等    吴德水
--2004-3-31添加经手人查询条件限制     徐辉  记号：#-01

--Gp_QueryMX  '2003-7-1','2003-7-31','00001000040000100004','0','0','0','','','','billdate','00001',''

CREATE                  PROCEDURE Gp_QueryMx_New
( 
	 @BeginDate		varchar(25),
	 @EndDate		varchar(25),
	 @AtypeId		varchar(8000),
	 @PtypeId		varchar(8000),
	 @BtypeId		varchar(8000),
	 @KtypeId		varchar(8000),
     @EtypeId   	varchar(8000),                    --经手人   #-01
	 @cMode			varchar(2),
	 @PreQty		 NUMERIC(24, 10)  OUTPUT,
	 @PreTotal		 NUMERIC(24, 10)  OUTPUT,
	 @OrderBy		varchar(25),
	 @OperatorId    varchar(100),       --操作员ID
	 @intType       int=''
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetManDetailEType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetManDetailBType(@OperatorID)

DECLARE @strQuery varchar(8000)
SELECT @strQuery=''

CREATE TABLE #GetSelETypeId(TypeId	varchar(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT * FROM F_GetAllBaseTypeId(@ETypeId,3)

CREATE TABLE #GetSelKTypeId(TypeId	varchar(100))
INSERT INTO #GetSelKTypeId(TypeId) SELECT * FROM F_GetAllBaseTypeId(@KTypeId,4)

-- 调拔调阅 加不限经手人权限 ADD BY chen_qihua 2004-2-13 ===========

DECLARE @lim VARCHAR(1)
SET @lim ='0'

SELECT   @lim =SUBSTRING(b.lim,439,1)
FROM employee a INNER JOIN loginuser b 
ON (a.typeid=b.etypeid)
INNER JOIN btype c ON (b.btypeid=c.typeid)
WHERE  b.etypeid=@OperatorId

IF @OperatorId<>''
   	BEGIN
		IF @lim ='1' --SELECT @strQuery=' AND c.EtypeId LIKE '+' CASE a.billtype WHEN 17 THEN '+char(39)+''+'%'+char(39) +' WHEN 21 THEN '+char(39)+''+'%'+ CHAR(39)+' ELSE ' +CHAR(39)+@MEtypeid+'%'+CHAR(39)+'END'
			SELECT @strQuery=' AND ((a.billtype in (17,21) and c.EtypeId like ''%'') OR (a.billtype not in (17,21) and c.ETypeId IN (SELECT * FROM #GetManETypeId) AND c.ETypeId IN (SELECT * FROM #GetSelETypeId))'
		ELSE
			SELECT @strQuery=' AND c.EtypeId IN (SELECT * FROM #GetManETypeId) AND c.ETypeId IN (SELECT * FROM #GetSelETypeId)' --原来如此
	END

--  加经手人限制,若是全部经手人，没有该限制  徐辉  2004-3-30       #-01
IF @EtypeId<>''
  	BEGIN
		SELECT @strQuery=' AND c.EtypeId IN (SELECT * FROM #GetManETypeId) AND c.ETypeId IN (SELECT * FROM #GetSelETypeId)'
	END

 -- ====================== END =================================

IF @AtypeId='' SELECT @AtypeId='0'
IF @PtypeId='' SELECT @PtypeId='0'
IF @BtypeId='' SELECT @BtypeId='0'
IF @KtypeId='' SELECT @KtypeId='0'
DECLARE @cz_query varchar(8000),@dbname varchar(20)
DECLARE @TempTotal  NUMERIC(24, 10) ,@TempQty  NUMERIC(24, 10) 
DECLARE @Sql varchar (8000)
DECLARE @GOODS_ID varchar(100),
		@CASH_ID  varchar(100),
		@CASH_BANK_ID varchar(100),
		@AR_ID varchar(100),
		@AP_ID varchar(100),
		@GOODS_LOSS_ID varchar(100),
		@GOODS_GET_ID varchar(100),
		@ALLOT_PRICE_ID varchar(100),
		@PRICE_INCOME_ID varchar(100),     
		@BORROW_BUY_PRICE_ID varchar(100), 
		@GOODS_GIVE_ID varchar(100),       
		@GOODS_PRODUCE_ID varchar(100),    
		@SALE_COST_ID varchar(100),        
		@SALE_INCOME_ID varchar(100),      
		@LEND_GOODS_ID varchar(100),       
		@BORROW_GOODS_ID varchar(100),     
		@BALANCE_ID varchar(100),          
		@DEPRECIATION_ID varchar(100),     
		@APPORTION_EXPENSE_ID varchar(100),
		@INIT_MONEY_ID varchar(100),       
		@ALL_INCOME_ID varchar(100),       
		@ALL_EXPENSE_ID varchar(100),      
		@PROFIT_ID varchar(100),           
		@ASSETS_ID varchar(100),           
		@DEBT_ID varchar(100),             
		@POWER_ID varchar(100),
		@ADDEBT_INCOME_ID varchar(100),
		@ADDEBT_LOSE_ID varchar(100)
		SELECT @GOODS_ID='0000100001'
		SELECT @CASH_ID='0000100003'
		SELECT @CASH_BANK_ID='0000100004'
		SELECT @AR_ID='0000100005'
		SELECT @AP_ID='0000200001'
		SELECT @GOODS_LOSS_ID='000040000200001' --           商品报损
		SELECT @GOODS_GET_ID='000030000200001'  --           商品报溢收入
		SELECT @ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
		SELECT @PRICE_INCOME_ID='000030000200003'--成本调价收入
		-- SELECT @BORROW_BUY_PRICE_RECNO varchar(25)= 28;
		-- SELECT @GOODS_GIVE_RECNO = 000040000200002           商品赠出
		SELECT @GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
		SELECT @SALE_COST_ID='0000400001'--              『销售成本』
		SELECT @SALE_INCOME_ID='0000300001'--            『销售收入』
		-- SELECT @LEND_GOODS_RECNO varchar(25),       = 21;
		-- SELECT @BORROW_GOODS_RECNO varchar(25),     = 24;
		SELECT @BALANCE_ID='000030000200004'--           进货退货差价
		SELECT @DEPRECIATION_ID='000040000300002'--      固定资产折旧
		SELECT @APPORTION_EXPENSE_ID='0000100007'--      待摊费用
		-- SELECT @INIT_MONEY_RECNO varchar(25),       = 18;
		SELECT @ALL_INCOME_ID='00003' --          【收入类】
		SELECT @ALL_EXPENSE_ID='00004'--                 【支出类】
		-- SELECT @PROFIT_RECNO varchar(25),           = 19;
		
		SELECT @ASSETS_ID ='00001'  --【资产合计】
		SELECT @DEBT_ID='00002'   --【负债合计】
		-- SELECT @POWER_RECNO varchar(25)            = 4;
		SELECT @ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
		SELECT @ADDEBT_LOSE_ID='000040000300001' --调帐亏损


SELECT @dbname='listtable'
IF @ptypeid<>'0' AND @atypeid=@GOODS_ID
	BEGIN 
		SELECT @dbname='inoutstocktable'

		IF @ktypeid<>'0'
  			SELECT 	@preQty=ISNULL(SUM(a.qty),0),
					@preTotal=ISNULL(SUM(a.costtotal),0) 
			FROM 	inoutstocktable  a,
					BillIndex b
  			WHERE 	a.BillNumberId=b.BillNumberId 
					AND b.RedWord=0
					AND b.ETypeId LIKE @EtypeId+'%'
					AND a.billdate<@begindate 
					AND a.ktypeid LIKE @ktypeid+'%' 
					AND a.KTypeID<>'10000' 
					AND a.KTypeID LIKE @MKTypeID+'%' 
					AND LEFT(a.ptypeid,len(@ptypeid))=@ptypeid 
					AND a.atypeid=@GOODS_ID 
 		ELSE
  			SELECT 	@preQty=ISNULL(SUM(a.qty),0),
					@preTotal=ISNULL(SUM(a.costtotal),0) 
  			FROM 	inoutstocktable a,    
					BillIndex b
			WHERE 	a.BillNumberId=b.BillNumberId 
					AND b.RedWord=0
					AND b.ETypeId LIKE @EtypeId+'%'
					AND a.billdate<@begindate 
					AND a.KTypeID<>'10000' 
					AND a.KTypeID LIKE @MKTypeID+'%' 
					AND LEFT(a.ptypeid,len(@ptypeid))=@ptypeid 
					AND a.atypeid=@GOODS_ID

		EXEC 	Gp_GetDbf_InOutStockTable @GOODS_ID,@ptypeid,'0','0',@ktypeid,'00','',@TempQty OUTPUT,@TempTotal OUTPUT
		
		SELECT 	@preQty=@preQty+@TempQty
 		
		SELECT @preTotal=@preTotal+@TempTotal
	END 
ELSE
	IF @btypeid<>'0' AND (@atypeid=@AR_ID OR @atypeid=@AP_ID)
		BEGIN
 			IF @atypeid=@AR_ID
 				BEGIN
  					SELECT 	@preTotal=ISNULL(SUM(total),0) 
  					FROM 	listtable 
  					WHERE 	billdate<@begindate 
							AND LEFT(btypeid,len(@btypeid))=@btypeid 
							AND atypeid=@AR_ID 
							AND audited=1
 
  					EXEC 	Gp_GetDbf_InOutStockTable @AR_ID,'0',@btypeid,'0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT
  
					SELECT 	@preQty=@preQty+@TempQty
  					SELECT 	@preTotal=@preTotal+@TempTotal
 				END 
			ELSE 
				IF @atypeid=@AP_ID
 					BEGIN
  						SELECT 	@preTotal=ISNULL(SUM(total),0) 
  						FROM 	listtable 
  						WHERE 	billdate<@begindate 
								AND LEFT(btypeid,len(@btypeid))=@btypeid 
								AND atypeid=@AP_ID 
								AND audited=1
 
  						EXEC 	gp_getdbf @AP_ID,'0',@btypeid,'0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT

  						SELECT @preQty=@preQty+@TempQty
  						SELECT @preTotal=@preTotal+@TempTotal
					END 
		END 
	ELSE 
		BEGIN
  			SELECT 	@preTotal=ISNULL(SUM(total),0) 
			--  FROM inoutstocktable 
  			FROM 	listtable 
  			WHERE 	billdate<@begindate 
					AND LEFT(atypeid,len(@atypeid))=@atypeid 
					AND audited=1 --AND btypeid='0' AND ptypeid='0' AND ktypeid='0'
 
  			EXEC 	Gp_GetDbf_InOutStockTable @atypeid,'0','0','0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT
  		
			SELECT @preQty=@preQty+@TempQty
  			SELECT @preTotal=@preTotal+@TempTotal
		END

SELECT @cz_Query=''
IF (RTRIM(@begindate) <>'' AND RTRIM(@enddate) <>'')
 SELECT @cz_Query=@cz_query+' a.billdate>='+char(39)+@begindate+char(39)+' AND a.billdate<='+char(39)+@enddate+char(39)+' AND '

IF RTRIM(@ptypeid)<>'0' AND RTRIM(@atypeid)=@GOODS_ID
BEGIN
 SELECT @cz_query=@cz_query+' LEFT(c.ptypeid,len('+char(39)+@ptypeid+char(39)+'))='+char(39)+@ptypeid+char(39)
  +' AND c.billnumberid=a.billnumberid'+ ' AND'
 SELECT @cz_query=@cz_query+' c.atypeid='+char(39)+@GOODS_ID+char(39) +' AND'
 SELECT @cz_query=@cz_query+' a.ifcheck='+char(39)+'t'+char(39) +' AND'
END
IF RTRIM(@ktypeid) <>'0'
 SELECT @cz_query=@cz_query+' c.ktypeid IN (SELECT * FROM #GetSelKTypeId) AND c.billnumberid=a.billnumberid'+ ' AND' 
IF RTRIM(@btypeid) <> '0' 
 SELECT @cz_query=@cz_query+' LEFT(c.btypeid,len('+char(39)+@btypeid+char(39)+'))='+char(39)+@btypeid+char(39)
  +' AND c.billnumberid=a.billnumberid'+ ' AND' 
IF RTRIM(@atypeid) <> '0' 
 SELECT @cz_query=@cz_query+' LEFT(c.atypeid,len('+char(39)+@atypeid+char(39)+'))='+char(39)+@atypeid+char(39)
  +' AND c.billnumberid=a.billnumberid '+ ' AND' 
IF UPPER(@cMode)='S'
 SELECT @cz_query=@cz_query+' (c.billtype=11 OR c.billtype=141 OR c.billtype=45 OR c.billtype=305) AND'
IF UPPER(@cMode)='B'
 SELECT @cz_query=@cz_query+' (c.billtype=34 OR c.billtype=6 OR c.billtype = 145) AND'
SELECT @cz_query=SUBSTRING(@cz_query,1,len(@cz_query)-4)

IF @intType = 1
	SELECT @cz_Query = @cz_Query +' AND c.btypeid IN (SELECT * FROM #GetManBTypeId) '

DECLARE @SQLOrder	varchar(150)
SELECT @SQLOrder = ''

IF @OrderBy = 'ByDate_a'		--ORDER BY date
    SELECT @SQLOrder = ' ORDER BY c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 	--ORDER BY Bill No.
    SELECT @SQLOrder = ' ORDER BY a.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	--ORDER BY Bill type
    SELECT @SQLOrder = ' ORDER BY c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	--ORDER BY Bill ID
    SELECT @SQLOrder = ' ORDER BY a.ID'
ELSE IF @OrderBy = 'ByDate_d'		--ORDER BY date DESC 
    SELECT @SQLOrder = ' ORDER BY c.billdate DESC, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	--ORDER BY Bill No. DESC 
    SELECT @SQLOrder = ' ORDER BY a.BillCode DESC'
ELSE IF @OrderBy = 'ByBillType_d'	--ORDER BY Bill type DESC 
    SELECT @SQLOrder = ' ORDER BY c.billtype DESC, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	--ORDER BY Bill ID DESC 
    SELECT @SQLOrder = ' ORDER BY a.ID DESC'
ELSE
    SELECT @SQLOrder = ' ORDER BY c.billdate'


 SELECT @Sql ='SELECT 
					c.BillNumberId,
					c.BillDate,
					c.billtype,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.qty),0)	ELSE  ISNULL(SUM(c.qty),0)	END AS qty,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.Costtotal),0)	ELSE  ISNULL(SUM(c.Costtotal),0)	END AS Costtotal,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.total),0)	ELSE  ISNULL(SUM(c.total),0)	END AS total,
					c.CostPrice,
					a.BillCode, 
					a.Comment,
					a.RedWord, 
					CBillType=a.billtype,
			        (SELECT ISNULL(fullname,'''')
				    FROM ptype b
         			WHERE c.ptypeid = b.typeid) AS ptype,
        			CASE a.billtype WHEN 145 THEN ''代销库'' 	ELSE (SELECT ISNULL(fullname,'''')
					FROM Stock b
         			WHERE c.Ktypeid = b.typeid) 
					END
					AS Ktype,
		          	(SELECT ISNULL(fullname,'''')
        			FROM atype b
         			WHERE c.atypeid = b.typeid) AS Atype,
          			(SELECT ISNULL(fullname,'''')
         			FROM btype b
         			WHERE a.btypeid = b.typeid) AS btype,
					(SELECT ISNULL(fullname,'''')
         			FROM Employee e
         			WHERE a.etypeid = e.typeid) AS etype
		FROM '+@dbname+' c,BillIndex a WHERE '

IF UPPER(@cMode) <> 'S' AND UPPER(@cMode) <> 'B'
	SELECT @SQL = @SQL + 'c.ktypeid<>'+CHAR(39)+'10000'+CHAR(39)+ ' AND c.KTypeID IN (SELECT * FROM #GetManKTypeId)  AND '

-- ============== ADD BY chen_qihua 加红单限制
SELECT @SQL = @SQL + ' a.redword =0 AND '

DECLARE @GroupBy varchar(2000)

SELECT @GroupBy ='  GROUP BY 
					c.BillNumberId,
					c.billdate,
					c.billtype,
					a.billtype,
					c.costprice,
					c.qty,
					a.billcode,
					a.comment,
					a.redword,
					c.ptypeid,
					c.ktypeid,
					c.atypeid,
					a.btypeid,
					a.etypeid,'

IF @OrderBy = 'ByDate_a'
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	
    SELECT @GroupBy = @GroupBy + ' a.ID'
ELSE IF @OrderBy = 'ByDate_d'		
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @OrderBy = 'ByBillType_d'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	
    SELECT @GroupBy = @GroupBy + ' a.ID'
ELSE
    SELECT @GroupBy = @GroupBy + ' c.billdate'



SELECT @SQL = @SQL + @cz_query +@strQuery+@GroupBy+@SQLOrder

--PRINT @sql
EXEC (@Sql)


DROP TABLE #GetManETypeId,#GetManKTypeId,#GetManBTypeId,#GetSelETypeId,#GetSelKTypeId


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryMx_Xjk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryMx_Xjk]
GO












---2002-4-8		添加零售单
---2002-7-4 	添加OrderBy参数及排序功能	王峰
---2002-12-4	添加权限检查及赠送单。。。等    吴德水

--Gp_QueryMX  '2003-7-1','2003-7-31','00001000040000100004','0','0','0','','','','billdate','00001',''

CREATE                  PROCEDURE Gp_QueryMx_Xjk
( 
	@BeginDate		VARCHAR(25),
	@EndDate		VARCHAR(25),
	@AtypeId		VARCHAR(8000),
	@PtypeId		VARCHAR(8000),
	@BtypeId		VARCHAR(8000),
	@KtypeId		VARCHAR(8000),
	@cMode			VARCHAR(2),
	@PreQty			 NUMERIC(24, 10)  OUTPUT,
	@PreTotal		 NUMERIC(24, 10)  OUTPUT,
	@OrderBy		VARCHAR(25),
	@OperatorId     VARCHAR(100),       --操作员ID
	@showRedWord	char(1)='0',
	@intType        INT=''
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetManDetailEType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetManDetailBType(@OperatorID)

--仓库：
CREATE TABLE #GetSelKTypeId(TypeId varchar(100))
INSERT INTO #GetSelKTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@KTypeId,4)

DECLARE @strQuery VARCHAR(1000)
SELECT @strQuery=''

-- 调拔调阅 加不限经手人权限 add by chen_qihua 2004-2-13 ===========
Declare @lim varchar(1)
SET @lim ='0'

SELECT   @lim =substring(b.lim,439,1)
FROM employee a inner join loginuser b 
on (a.typeid=b.etypeid)
inner join btype c on (b.btypeid=c.typeid)
where  b.etypeid=@OperatorId

IF @OperatorId<>'' --SELECT @strQuery=' AND ((a.billtype in (17,21) and c.EtypeId like ''%'')  OR (a.billtype not in (17,21) and c.ETypeId IN (SELECT TypeId FROM #GetManETypeId)))'
   	BEGIN
		if @lim ='1' --SELECT @strQuery=' AND c.EtypeId LIKE '+' case a.billtype when 17 then '+CHAR(39)+''+'%'+CHAR(39) +' when 21 then '+CHAR(39)+''+'%'+ char(39)+' else ' +char(39)+@MEtypeid+'%'+char(39)+'end'
			BEGIN
				SELECT @strQuery=' AND ((a.billtype in (17,21) and c.EtypeId like ''%'')  OR (a.billtype not in (17,21) and c.ETypeId IN (SELECT TypeId FROM #GetManETypeId)))'
			END
		else
			BEGIN
				SELECT @strQuery=' AND c.EtypeId IN (SELECT * FROM #GetManETypeId)' --原来如此				
			END
	END

IF @AtypeId='' SELECT @AtypeId='0'
IF @PtypeId='' SELECT @PtypeId='0'
IF @BtypeId='' SELECT @BtypeId='0'
IF @KtypeId='' SELECT @KtypeId='0'
DECLARE @GroupBy VARCHAR(2000)
DECLARE @cz_query VARCHAR(8000),@dbname VARCHAR(20)
DECLARE @TempTotal  NUMERIC(24, 10) ,@TempQty  NUMERIC(24, 10) 
DECLARE @Sql VARCHAR (8000)
DECLARE @GOODS_ID VARCHAR(100),
		@CASH_ID  VARCHAR(100),
		@CASH_BANK_ID VARCHAR(100),
		@AR_ID VARCHAR(100),
		@AP_ID VARCHAR(100),
		@GOODS_LOSS_ID VARCHAR(100),
		@GOODS_GET_ID VARCHAR(100),
		@ALLOT_PRICE_ID VARCHAR(100),
		@PRICE_INCOME_ID VARCHAR(100),     
		@BORROW_BUY_PRICE_ID VARCHAR(100), 
		@GOODS_GIVE_ID VARCHAR(100),       
		@GOODS_PRODUCE_ID VARCHAR(100),    
		@SALE_COST_ID VARCHAR(100),        
		@SALE_INCOME_ID VARCHAR(100),      
		@LEND_GOODS_ID VARCHAR(100),       
		@BORROW_GOODS_ID VARCHAR(100),     
		@BALANCE_ID VARCHAR(100),          
		@DEPRECIATION_ID VARCHAR(100),     
		@APPORTION_EXPENSE_ID VARCHAR(100),
		@INIT_MONEY_ID VARCHAR(100),       
		@ALL_INCOME_ID VARCHAR(100),       
		@ALL_EXPENSE_ID VARCHAR(100),      
		@PROFIT_ID VARCHAR(100),           
		@ASSETS_ID VARCHAR(100),           
		@DEBT_ID VARCHAR(100),             
		@POWER_ID VARCHAR(100),
		@ADDEBT_INCOME_ID VARCHAR(100),
		@ADDEBT_LOSE_ID VARCHAR(100)
		SELECT @GOODS_ID='0000100001'
		SELECT @CASH_ID='0000100003'
		SELECT @CASH_BANK_ID='0000100004'
		SELECT @AR_ID='0000100005'
		SELECT @AP_ID='0000200001'
		SELECT @GOODS_LOSS_ID='000040000200001' --           商品报损
		SELECT @GOODS_GET_ID='000030000200001'  --           商品报溢收入
		SELECT @ALLOT_PRICE_ID='000030000200005'-- 变价调拨差价
		SELECT @PRICE_INCOME_ID='000030000200003'--成本调价收入
		-- SELECT @BORROW_BUY_PRICE_RECNO VARCHAR(25)= 28;
		-- SELECT @GOODS_GIVE_RECNO = 000040000200002           商品赠出
		SELECT @GOODS_PRODUCE_ID='000030000200006'--      商品拆装差价
		SELECT @SALE_COST_ID='0000400001'--              『销售成本』
		SELECT @SALE_INCOME_ID='0000300001'--            『销售收入』
		-- SELECT @LEND_GOODS_RECNO VARCHAR(25),       = 21;
		-- SELECT @BORROW_GOODS_RECNO VARCHAR(25),     = 24;
		SELECT @BALANCE_ID='000030000200004'--           进货退货差价
		SELECT @DEPRECIATION_ID='000040000300002'--      固定资产折旧
		SELECT @APPORTION_EXPENSE_ID='0000100007'--      待摊费用
		-- SELECT @INIT_MONEY_RECNO VARCHAR(25),       = 18;
		SELECT @ALL_INCOME_ID='00003' --          【收入类】
		SELECT @ALL_EXPENSE_ID='00004'--                 【支出类】
		-- SELECT @PROFIT_RECNO VARCHAR(25),           = 19;
		
		SELECT @ASSETS_ID ='00001'  --【资产合计】
		SELECT @DEBT_ID='00002'   --【负债合计】
		-- SELECT @POWER_RECNO VARCHAR(25)            = 4;
		SELECT @ADDEBT_INCOME_ID='000030000300001'-- 调帐收入
		SELECT @ADDEBT_LOSE_ID='000040000300001' --调帐亏损


SELECT @dbname='listtable'
IF @ptypeid<>'0' AND @atypeid=@GOODS_ID
	BEGIN 
		SELECT @dbname='inoutstocktable'

		IF @ktypeid<>'0'
  			SELECT 	@preQty=ISNULL(SUM(a.qty),0),
					@preTotal=ISNULL(SUM(a.costtotal),0) 
			FROM 	inoutstocktable  a
                --过滤掉蓝单，红单
                Inner Join BillIndex b
                On a.BillNumberId=b.BillNumberId And b.RedWord=0
  			WHERE 	a.billdate<@begindate 
					AND a.ktypeid LIKE @ktypeid+'%' 
					AND a.KTypeID<>'10000' 
					AND a.KTypeID in (select * from #GetManKTypeId)
					AND LEFT(a.ptypeid,len(@ptypeid))=@ptypeid 
					AND a.ptypeid in (select * from #GetManPTypeId)
					AND a.atypeid=@GOODS_ID 
 		ELSE
  			SELECT 	@preQty=ISNULL(SUM(a.qty),0),
					@preTotal=ISNULL(SUM(a.costtotal),0) 
  			FROM 	inoutstocktable a
                --过滤掉蓝单，红单
                Inner Join BillIndex b
                On a.BillNumberId=b.BillNumberId And b.RedWord=0
			WHERE 	a.billdate<@begindate 
					AND a.KTypeID<>'10000' 
					AND a.KTypeID in (select * from #GetManKTypeId)
					AND LEFT(a.ptypeid,len(@ptypeid))=@ptypeid 
					AND a.ptypeid in (select * from #GetManPTypeId)
					AND a.atypeid=@GOODS_ID

		EXEC 	gp_getdbf_Stock @OperatorId,@GOODS_ID,@ptypeid,'0','0',@ktypeid,'00','',@TempQty OUTPUT,@TempTotal OUTPUT
		
		SELECT 	@preQty=@preQty+@TempQty
 		
		SELECT @preTotal=@preTotal+@TempTotal
	END 
ELSE
	IF @btypeid<>'0' AND (@atypeid=@AR_ID OR @atypeid=@AP_ID)
		BEGIN
 			IF @atypeid=@AR_ID
 				BEGIN
  					SELECT 	@preTotal=ISNULL(SUM(total),0) 
  					FROM 	listtable 
  					WHERE 	billdate<@begindate 
							AND LEFT(btypeid,len(@btypeid))=@btypeid 
							AND atypeid=@AR_ID 
							AND audited=1
 
  					EXEC 	gp_getdbf_Stock @OperatorId,@AR_ID,'0',@btypeid,'0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT
  
					SELECT 	@preQty=@preQty+@TempQty
  					SELECT 	@preTotal=@preTotal+@TempTotal
 				END 
			ELSE 
				IF @atypeid=@AP_ID
 					BEGIN
  						SELECT 	@preTotal=ISNULL(SUM(total),0) 
  						FROM 	listtable 
  						WHERE 	billdate<@begindate 
								AND LEFT(btypeid,len(@btypeid))=@btypeid 
								AND atypeid=@AP_ID 
								AND audited=1
 
  						EXEC 	gp_getdbf @OperatorId,@AP_ID,'0',@btypeid,'0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT

  						SELECT @preQty=@preQty+@TempQty
  						SELECT @preTotal=@preTotal+@TempTotal
					END 
		END 
	ELSE 
		BEGIN
  			SELECT 	@preTotal=ISNULL(SUM(total),0) 
			--  FROM inoutstocktable 
  			FROM 	listtable 
  			WHERE 	billdate<@begindate 
					AND LEFT(atypeid,len(@atypeid))=@atypeid 
					AND audited=1 --AND btypeid='0' AND ptypeid='0' AND ktypeid='0'
 
  			EXEC 	gp_getdbf_Stock @OperatorId,@atypeid,'0','0','0','0','00','',@TempQty OUTPUT,@TempTotal OUTPUT
  		
			SELECT @preQty=@preQty+@TempQty
  			SELECT @preTotal=@preTotal+@TempTotal
		END

SELECT @cz_Query=''
IF (RTRIM(@begindate) <>'' AND RTRIM(@enddate) <>'')
 SELECT @cz_Query=@cz_query+' a.billdate>='+CHAR(39)+@begindate+CHAR(39)+' AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+' AND '
IF RTRIM(@ptypeid)<>'0' AND RTRIM(@atypeid)=@GOODS_ID
	BEGIN
		SELECT @cz_query=@cz_query+' LEFT(c.ptypeid,len('+CHAR(39)+@ptypeid+CHAR(39)+'))='+CHAR(39)+@ptypeid+CHAR(39)+' and c.ptypeid in (select * from #GetManPTypeId) AND c.billnumberid=a.billnumberid'+ ' AND'
		SELECT @cz_query=@cz_query+' c.atypeid='+CHAR(39)+@GOODS_ID+CHAR(39) +' AND'
		SELECT @cz_query=@cz_query+' a.ifcheck='+CHAR(39)+'t'+CHAR(39) +' AND'
	END

IF RTRIM(@ktypeid) <>'0'
 SELECT @cz_query=@cz_query+' c.ktypeid IN (SELECT * FROM #GetSelKTypeId) AND c.billnumberid=a.billnumberid'+ ' AND' 
IF RTRIM(@btypeid) <> '0' 
 SELECT @cz_query=@cz_query+' LEFT(c.btypeid,len('+CHAR(39)+@btypeid+CHAR(39)+'))='+CHAR(39)+@btypeid+CHAR(39) +' AND c.billnumberid=a.billnumberid'+ ' AND' 
IF RTRIM(@atypeid) <> '0' 
 SELECT @cz_query=@cz_query+' LEFT(c.atypeid,len('+CHAR(39)+@atypeid+CHAR(39)+'))='+CHAR(39)+@atypeid+CHAR(39) +' AND c.billnumberid=a.billnumberid '+ ' AND' 
IF UPPER(@cMode)='S'
 SELECT @cz_query=@cz_query+' (c.billtype=11 OR c.billtype=141 OR c.billtype=45 OR c.billtype=305) AND'

IF UPPER(@cMode)='B'
  SELECT @cz_query=@cz_query+' (c.billtype=34 OR c.billtype=6 OR c.billtype = 145) AND'

SELECT @cz_query=SUBSTRING(@cz_query,1,len(@cz_query)-4)


---- ADD BY MJG  2003-07-31 FOR Inoutstocktable 管理权限 
IF @intType = 1
	SELECT @cz_Query = @cz_Query +' AND c.btypeid IN (SELECT * FROM #GetManBTypeId) '




--  OrderBy  --
--  ADD BY wangfeng  --
DECLARE @SQLOrder	VARCHAR(150)
SELECT @SQLOrder = ''

IF @OrderBy = 'ByDate_a'		--ORDER BY date
    SELECT @SQLOrder = ' ORDER BY c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 	--ORDER BY Bill No.
    SELECT @SQLOrder = ' ORDER BY a.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	--ORDER BY Bill type
    SELECT @SQLOrder = ' ORDER BY c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	--ORDER BY Bill ID
    SELECT @SQLOrder = ' ORDER BY a.ID'
ELSE IF @OrderBy = 'ByDate_d'		--ORDER BY date DESC 
    SELECT @SQLOrder = ' ORDER BY c.billdate DESC, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	--ORDER BY Bill No. DESC 
    SELECT @SQLOrder = ' ORDER BY a.BillCode DESC'
ELSE IF @OrderBy = 'ByBillType_d'	--ORDER BY Bill type DESC 
    SELECT @SQLOrder = ' ORDER BY c.billtype DESC, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	--ORDER BY Bill ID DESC 
    SELECT @SQLOrder = ' ORDER BY a.ID DESC'
ELSE
    SELECT @SQLOrder = ' ORDER BY c.billdate'


 SELECT @Sql ='SELECT	c.BillNumberId,
						c.BillDate,
						c.billtype,
						CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.qty),0)	else  ISNULL(SUM(c.qty),0)	end as qty,
						CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.Costtotal),0)	else  ISNULL(SUM(c.Costtotal),0)	end as Costtotal,
						CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.total),0)	else  ISNULL(SUM(c.total),0)	end as total,
						ISNULL(c.CostPrice,0) AS CostPrice,
						a.BillCode, 
						a.Comment,
						a.RedWord, 
						CBillType= a.billtype,
				        (SELECT ISNULL(fullname,'''') FROM ptype b WHERE c.ptypeid = b.typeid) AS ptype,
	        			case a.billtype when 145 then ''代销库'' else (SELECT ISNULL(fullname,'''') FROM Stock b WHERE c.Ktypeid = b.typeid) end AS Ktype,
			          	(SELECT ISNULL(fullname,'''') FROM atype b WHERE c.atypeid = b.typeid) AS Atype,
	          			(SELECT ISNULL(fullname,'''') FROM btype b WHERE a.btypeid = b.typeid) AS btype,
						(SELECT ISNULL(fullname,'''') FROM Employee e WHERE a.etypeid = e.typeid) AS etype
			FROM 	'+@dbname+' c,
					BillIndex a 
			WHERE '

IF UPPER(@cMode) <> 'S' AND UPPER(@cMode) <> 'B'
	SELECT @SQL = @SQL + 'c.ktypeid<>'+CHAR(39)+'10000'+CHAR(39)+ ' AND c.KTypeID IN (SELECT * FROM #GetManKTypeId)  AND '

IF @showRedWord = '0'
	SELECT @SQL = @SQL + ' a.redword =0 AND '

SELECT @GroupBy ='  GROUP BY 
					c.BillNumberId,
					c.billdate,
					c.billtype,
					a.billtype,
					c.costprice,
					c.qty,
					a.billcode,
					a.comment,
					a.redword,
					c.ptypeid,
					c.ktypeid,
					c.atypeid,
					a.btypeid,
					a.etypeid,'

IF @OrderBy = 'ByDate_a'
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	
    SELECT @GroupBy = @GroupBy + ' a.ID'
ELSE IF @OrderBy = 'ByDate_d'		
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @OrderBy = 'ByBillType_d'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	
    SELECT @GroupBy = @GroupBy + ' a.ID'
ELSE
    SELECT @GroupBy = @GroupBy + ' c.billdate'



SELECT @SQL = @SQL + @cz_query +@strQuery+@GroupBy+@SQLOrder

--print @sql
EXEC (@Sql)


DROP TABLE #GetManETypeId,#GetManKTypeId,#GetManBTypeId,#GetSelKTypeId,#GetManPTypeId















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryMxCashBank]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryMxCashBank]
GO





-- 现金银行查询明细账
-- 徐辉 2011-04-22
-- 分机机构调整


CREATE     PROCEDURE Gp_QueryMxCashBank
( 
	 @StartDate		VARCHAR(25),
	 @EndDate		VARCHAR(25),
	 @AtypeId		VARCHAR(50),
	 @StypeId		VARCHAR(MAX),		--分支机构
	 @Cid			INT, 
	 @PreQty		 NUMERIC(24, 10)  OUTPUT,
	 @PreTotal		 NUMERIC(24, 10)  OUTPUT,
	 @PreTotalFor	 NUMERIC(24, 10)  OUTPUT,
	 @OrderBy		VARCHAR(50),
	 @OperatorId    VARCHAR(50),       --操作员ID
	 @Flag          varchar(10)='',     -- 为00时，只取 output的值
	 @chkRed       int				--是否显示红冲 0为不显示红冲，1为显示红冲	

)

--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Stype (TypeID varchar(50))
IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a



DECLARE @TempQty  NUMERIC(24, 10) 
DECLARE @TempTotal  NUMERIC(24, 10) 
DECLARE @TempTotalFor  NUMERIC(24, 10) 
SET @TempTotal= 0
SET @TempQty =0
SET @TempTotalFor=0

SELECT 	@preTotal=ISNULL(SUM(total),0),
		@PreTotalFor=ISNULL(SUM(Ntotal),0)
FROM 	listtable 
WHERE 	billdate<@StartDate 
		AND atypeid=@atypeid 
		AND STypeID IN(SELECT TypeID FROM #Stype)
		AND audited=1
		AND CID=@Cid
		
SELECT @TempTotal=ISNULL(Sum(Total00),0),
	   @TempTotalFor=ISNULL(Sum(NTotal00),0)  
  FROM AType_Total 
 WHERE ATypeID=@atypeid 
	   AND STypeID IN(SELECT typeid FROM #Stype)
       AND CID=@Cid
----计算期初值       
SELECT @preQty=@preQty+@TempQty
SELECT @preTotal=@preTotal+@TempTotal
SELECT @preTotalFor=@preTotalFor+@TempTotalFor

IF @Flag='00'
BEGIN
	DROP TABLE #Stype
	RETURN 
END

--收缩listtable
SELECT * INTO #listtable FROM Listtable WHERE STypeID IN(SELECT TypeID FROM #Stype) AND atypeid=@atypeid AND CID=@Cid

SELECT * INTO #tempBillindex FROM (
SELECT    AssetBusinessTypeId ,
                        ifYearBill ,
                        Rate ,
                        Comment ,
                        BillNumberId ,
                        BillDate ,
                        BillCode ,
                        BillType ,
                        atypeid ,
                        btypeid ,
                        etypeid ,
                        ktypeid ,
                        ifcheck ,
                        totalmoney ,
                        totalinmoney ,
                        RedWord ,
                        draft ,
                        preferencemoney ,
                        DTypeId,
                        explain,
                        Stypeid,
                        posttime
              FROM      dbo.BillIndex
              UNION ALL
              SELECT    0 AssetBusinessTypeId ,
                        IfYearBill ,
                        Rate ,
                        Comment ,
                        BillNumberID ,
                        BillDate ,
                        BillCode ,
                        BillType ,
                        ATypeID ,
                        BTypeID ,
                        ETypeID ,
                        CASE WHEN InKTypeId IS NULL OR InKTypeId = ''
                        THEN OutKTypeId
                        ELSE InKTypeId END AS KTypeId,
						ifCheck ,
                        TotalMoney ,
                        TotalInMoney ,
                        RedWord ,
                        Draft ,
                        0 preferencemoney ,
                        DTypeID,
                        '' AS explain,
                        STypeID,
                        PostTime
              FROM      dbo.Coupon_BillIndex
) AS tempTable

DECLARE @SQL varchar(8000)
DECLARE @SQL_WHERE varchar(2000)
SELECT @SQL_WHERE=''
IF (RTRIM(@StartDate) <>'' AND RTRIM(@enddate) <>'')
	SELECT @SQL_WHERE=@SQL_WHERE+' AND a.billdate>='+CHAR(39)+@StartDate+CHAR(39)+' AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)

--  OrderBy  --
--  ADD BY wangfeng  --
DECLARE @SQLOrder	VARCHAR(150)
SELECT @SQLOrder = ''

IF @OrderBy = 'ByDate_a'		--ORDER BY date
    SELECT @SQLOrder = ' ORDER BY c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 	--ORDER BY Bill No.
    SELECT @SQLOrder = ' ORDER BY a.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	--ORDER BY Bill type
    SELECT @SQLOrder = ' ORDER BY c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	--ORDER BY Bill ID
    SELECT @SQLOrder = ' ORDER BY a.posttime'
ELSE IF @OrderBy = 'ByDate_d'		--ORDER BY date DESC 
    SELECT @SQLOrder = ' ORDER BY c.billdate DESC, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	--ORDER BY Bill No. DESC 
    SELECT @SQLOrder = ' ORDER BY a.BillCode DESC'
ELSE IF @OrderBy = 'ByBillType_d'	--ORDER BY Bill type DESC 
    SELECT @SQLOrder = ' ORDER BY c.billtype DESC, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	--ORDER BY Bill ID DESC 
    SELECT @SQLOrder = ' ORDER BY a.posttime DESC'
ELSE
    SELECT @SQLOrder = ' ORDER BY c.billdate'


 SELECT @Sql ='SELECT 
					c.BillNumberId,
					c.BillDate,
					c.billtype,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.qty),0)	else  ISNULL(SUM(c.qty),0)	end as qty,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.Costtotal),0)	else  ISNULL(SUM(c.Costtotal),0)	end as Costtotal,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.total),0)	else  ISNULL(SUM(c.total),0)	end as total,
					CASE a.billtype WHEN 145 THEN -ISNULL(SUM(c.Ntotal),0)	else  ISNULL(SUM(c.Ntotal),0)	end as totalfor,
					c.CostPrice,
					a.BillCode, 
					a.Comment,
					a.explain,
					a.redword, 
					a.billtype,
			        (	
						SELECT ISNULL(fullname,'''')
					    FROM ptype b
	         				WHERE c.ptypeid = b.typeid) AS ptype,
	        					case a.billtype when 145 then ''代销库'' 	
							else (SELECT ISNULL(fullname,'''')
						FROM Stock b
	         			WHERE c.Ktypeid = b.typeid) 
					end	AS Ktype,
		          	(
						SELECT ISNULL(fullname,'''')
	        			FROM ac_items b
	         			WHERE c.atypeid = b.nid
					) AS Atype,
          			a.btypeid,
					a.etypeid,
					a.stypeid
				
			FROM #listtable c
			INNER JOIN #tempBillindex a ON C.BillNumberId = a.BillNumberId AND c.BillType = a.BillType	
			WHERE  a.ifYearBill= 0 '    --年节存标志

IF @chkRed=0
	BEGIN
	   SELECT @SQL+=' and a.redword=0'
	END
DECLARE @GroupBy VARCHAR(2000)

SELECT @GroupBy ='  GROUP BY 
					c.BillNumberId,
					c.billdate,
					c.billtype,
					a.billtype,
					c.costprice,
					c.qty,
					a.billcode,
					a.comment,
					a.explain,
					a.redword,
					c.ptypeid,
					c.ktypeid,
					c.atypeid,
					a.btypeid,
					a.etypeid,
					a.stypeid,'

IF @OrderBy = 'ByDate_a'
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_a'	
    SELECT @GroupBy = @GroupBy + ' a.posttime'
ELSE IF @OrderBy = 'ByDate_d'		
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @OrderBy = 'ByBillType_d'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @OrderBy = 'ByBillID_d'	
    SELECT @GroupBy = @GroupBy + ' a.posttime'
ELSE
    SELECT @GroupBy = @GroupBy + ' c.billdate,a.BillCode' --默认排序方式



SELECT @SQL = @SQL + @SQL_WHERE +@GroupBy+@SQLOrder

--PRINT @SQL
EXEC (@Sql)
DROP TABLE #Stype
DROP TABLE #listtable





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryOfflineBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryOfflineBillIndex]
GO


-- CopyRight@ 成都任我行软件公司 2001
-- 作者 ： 刘畅
-- 时间 ： 2001-11-21
-- 查询所管辖仓库的离线版本的单据Index
CREATE  PROCEDURE Gp_QueryOfflineBillIndex
( 
 @BeginDate  varchar(100),
 @EndDate  varchar(100),
 @EtypeID varchar(100)='',    -- 操作员 （没有控制）
 @TaskID  varchar(100)=''     -- 任务号
)
--@encode$--
AS
SET NOCOUNT ON 
declare @Sql varchar (8000)
declare @Mag_KtypeID varchar (100)
select @Sql=''
select @Mag_KtypeID=''
-- 获得管辖仓库
select @Mag_KtypeID=MangerKtypeID
from loginuser
where etypeid=@EtypeID
if @Mag_KtypeID='00000' select @Mag_KtypeID=''
-- 查询结果
select @Sql =
'SELECT BillNumberId,BillDate, BillCode,billtype,redword
 , a.Comment AS Comment,a.explain as explain, CBillType=
  case billtype 
  when 305 then "零售"
  when 11 then ''销售''
  when 4 then ''收款单''
  when 6 then ''进货退货''
  when 45 then ''销售退货''
  when 66 then ''付款单''
  when 57 then  ''商品调价''
  when 17 then  ''同价调拨''
  when 34 then  ''进货''
  WHEN 21 THEN  ''变价调拨''
  WHEN 9 THEN  ''报损''
  WHEN 14 THEN  ''报溢''
  WHEN 116 THEN  ''应收增加''
  WHEN 115 THEN  ''应收减少''
  WHEN 129 THEN  ''应付减少''
  WHEN 128 THEN  ''应付增加''
  WHEN 77 THEN  ''转款''
  WHEN 16 THEN ''拆装''
  WHEN 201 THEN ''代销发货''
  WHEN 202 THEN ''代销退货''
  when 203 then ''代销结算''
  when 36  then ''费用''
  when 93  then ''其他收入''
  when 139 then ''赠送单''
  when 126  then ''获增单''   
  when 84 then ''固定资产购买''
  when 85 then ''固定资产变卖''
  when 78 then ''固定资产折旧''
  when 5 then ''待摊费用发生''
  when 10 then ''待摊费用摊销''
  end
  ,a.totalqty,a.totalmoney,a.totalinmoney
  ,isnull(e.fullname,'''') AS etype
  ,isnull(s.fullname,'''') AS Ktype
  ,isnull(b.fullname,'''') AS btype
  ,isnull(i.fullname,'''') AS atype
  ,a.btypeid,a.OFF_ID
FROM Offline_BillIndex a 
left join btype b on a.btypeid = b.typeid
left join stock s on a.Ktypeid = s.typeid
inner join employee e on a.etypeid = e.typeid
left join atype i on a.atypeid = i.typeid'
--select @Sql=@Sql + ' where a.StockID like ''' + @Mag_KtypeID + '%'' '
select @Sql=@Sql + ' where a.TaskID = ''' + @TaskID + ''' '
if @BeginDate <> '' 
  select @Sql=@Sql + ' and a.BillDate >= ''' + @BeginDate + ''' '
if @EndDate <> '' 
  select @Sql=@Sql + ' and a.BillDate <= ''' + @EndDate + ''' '
-- 加入状态的标志判断
select @Sql=@Sql+' and Import = 0'
select @Sql=@Sql+' order by StockID, BillDate desc ,billcode'
--print @sql
exec (@Sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryOldBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryOldBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：谢吉康
	日期：2008-07-128
	描述：采购、退货单调原采购单、销售单、零售单
*/
/*
	修改：李灏龙
	日期：2012年4月9日14:02:36
	描述：增加IfYearBill = 0条件控制年结前单据不显示
		  具体修改：zs0001
*/
CREATE            PROCEDURE Gp_QueryOldBill
( 
	 @chvBeginDate	VARCHAR(25),
	 @chvEndDate	VARCHAR(25),
	 @chvBtype		VARCHAR(50),
	 @chvEtype		VARCHAR(50),
	 @chvKtype		VARCHAR(50),
	 @chvStype		varchar(50),
	 @chvOperatorId VARCHAR(50),       --操作员ID
	 @chvType       VARCHAR(5),
	 @chvPType		varchar(50)='',
	 @IsIni			int=0,			   --1为期初单据，0为非期初单据
	 @QueryType		VARCHAR(20),	   --normal为非期初单据
	 @cid			varchar(50)='',    --币种
	 @btypeid		varchar(50)='',
	 @areatypeid	VARCHAR(max)='',	--地区（多选,不确定值的大小所以用max）
	 @checkEtypeid	VARCHAR(max)='',	--制单人（多选,不确定值的大小所以用max）    
	 @explain		VARCHAR(2000),		--说明
	 @comment		VARCHAR(2000)		--摘要
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(MAX)
SET @SQL_Man = ''

-- 往来单位
IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
BEGIN
	DECLARE @chvBTypeAll char(1)
	SET @chvBTypeAll = '0'
	SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'
	
	SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)
	
	DECLARE @SQL_ManB varchar(100)
	SET @SQL_ManB = ' INNER JOIN #F_BaseGetManDetailBType B ON a.DealBTypeID = B.TypeID '
	
	IF @chvBTypeAll = '0'
	BEGIN
		IF (@chvType = '11' OR @chvType = '305' OR @chvType = '402') AND @chvMBTypeID = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00001%'' '
	
		IF (@chvType = '34' OR @chvType = '400') AND @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00002%'' '
	END
	ELSE
	BEGIN
		IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB
	END
END

-- 结算单位
IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
BEGIN
	DECLARE @chvBTypeAll1 char(1)
	SET @chvBTypeAll1 = '0'
	SELECT @chvBTypeAll1 = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'
	
	SELECT TypeID INTO #F_BaseGetManDetailBType1 FROM F_BaseGetManDetailBType(@chvOperatorID)
	
	DECLARE @SQL_ManB1 varchar(100)
	SET @SQL_ManB1 = ' INNER JOIN #F_BaseGetManDetailBType1 B1 ON a.BTypeID = B1.TypeID '
	
	IF @chvBTypeAll1 = '0'
	BEGIN
		IF (@chvType = '11' OR @chvType = '305' OR @chvType = '402') AND @chvMBTypeID = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB1 + ' AND B1.TypeID LIKE ''00001%'' '
	
		IF (@chvType = '34' OR @chvType = '400') AND @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB1 + ' AND B1.TypeID LIKE ''00002%'' '
	END
	ELSE
	BEGIN
		IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB1
	END
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END

-- 商品
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailPType P ON detail.PTypeID = P.TypeID '
END

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
END

-- 分支机构
IF @chvMStypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailsType FROM F_BaseGetManDetailSType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailsType s ON a.sTypeID = s.TypeID '
END

--部门
IF  @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END
-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(MAX)
SET @SQL = '
	SELECT	DISTINCT 
			a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,			
			a.DealBTypeID as btypeid,
			a.KTypeID,
			a.Comment,
			a.stypeid,
			a.costsale,
			a.explain
	FROM	Billindex a
	INNER JOIN ' + CASE @chvType WHEN '11' THEN 'SaleBill' WHEN '305' THEN 'RetailBill' 
	WHEN '402' THEN 'SendBill' WHEN '400' THEN 'AppraisalBill' WHEN '12' THEN 'PT_Combin_SaleBill' ELSE 'BuyBill' END
	+ ' detail ON a.BillNumberID=detail.BillNumberID AND ISNULL(detail.Qty,0)-ISNULL(detail.BackQty,0) > 0
	' + CASE WHEN @chvPType <> '' THEN ' AND detail.PTypeID=''' + @chvPType + '''' ELSE '' END + @SQL_Man + '
	WHERE	a.BillDate >= ''' + @chvBeginDate + ''' AND a.BillDate <= ''' + @chvEndDate + '''
			AND a.BillType=' + @chvType 
			
IF @IsIni = 1	   
	SET @SQL = @SQL + ' AND a.IsIni=1'			
ELSE		
	SET @SQL = @SQL + '	AND a.Draft=0
						AND a.RedWord=0
						AND a.ifCheck=''t''
						AND a.IsIni=0
						AND a.IfYearBill=0 '--zs0001:增加IfYearBill = 0条件控制年结前单据不显示					 		

--增加摘要说明
SET @SQL = @SQL + ' AND a.explain LIKE ''%'+@explain+'%'''
SET @SQL = @SQL + ' AND a.comment LIKE ''%'+@comment+'%'''

IF @cid <> '' SET @SQL = @SQL + ' AND  a.CID =  ''' + @cid + ''''
IF @chvBType <> '' SET @SQL = @SQL + ' AND a.DealBTypeID=''' + @chvBType + ''''
IF @chvEType <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @chvEType + ''''
IF @chvKType <> '' SET @SQL = @SQL + ' AND a.KTypeID=''' + @chvKType + ''''
IF @chvstype <> '' SET @SQL = @SQL + ' AND a.sTypeID=''' + @chvstype + ''''
IF @btypeid <> '' SET @SQL = @SQL + ' AND a.btypeid=''' + @btypeid + ''''
IF @areatypeid<>''
BEGIN
	SET @SQL = @SQL+' AND a.dealbtypeid IN (SELECT typeid FROM btype WHERE areatypeid in ('''+REPLACE(@areatypeid,',',''',''')+'''))'
END
IF @checkEtypeid<>''
BEGIN
	SET @SQL = @SQL+' AND a.CHECKE IN ('''+REPLACE(@checkEtypeid,',',''',''')+''')'
END

SET @SQL = @SQL + ' ORDER BY a.BillDate DESC'

--PRINT(@SQL)
EXEC (@SQL)

IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999' DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMPTypeID = '-99999' DROP TABLE #F_BaseGetManDetailPType
IF @chvMStypeid = '-99999' DROP TABLE #F_BaseGetManDetailsType
IF @chvMDtypeid = '-99999' DROP TABLE #F_BaseGetManDetailDType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryOldDXPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryOldDXPtype]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

-- ========================================================================
-- 功能说明：销售退货，采购退货调原来的销售单，采购入库单商品信息
--			返回商品信息
-- 作者：	陈启华
-- 最后修改时间：	2004-06-17
-- ========================================================================
CREATE                            PROCEDURE Gp_QueryOldDXPtype 
( 
	 @BillNumberID	varchar(5000),
	 @chvOperatorId varchar(50),       --操作员ID
	 @chvType       varchar(5),
	 @sh			int
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 商品
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailPType P ON a.PTypeID = P.TypeID '
END
-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(2000)
SET @SQL = '
	SELECT	a.BillNumberID,
			a.PTypeID,
			pt.usercode,
			pt.fullname,
			a.ID,
			CONVERT(varchar(8000),a.Serial) AS Serial,
			a.Qty,
			a.SalePrice,
			a.nsaleprice,
			a.SaleTotal AS Total,
			a.Discount,
			a.DiscountPrice,
			a.Total AS DiscountTotal,
			a.Tax,
			a.TaxPrice,
			a.TaxTotal,
			a.Comment,
			a.GoodsNumber,
			ISNULL(a.BackQty,0) AS BackQty,
			ISNULL(a.BQty,0) AS BQty,
			ISNULL(a.Qty,0) - ISNULL(a.BackQty,0) - ISNULL(a.BQty,0) AS RemainQty,
			a.stypeid,
			a.producedate,
			a.validdate,
			CASE WHEN a.IsCombined = 0  THEN (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END AS itemname 
	FROM	CommissionBill a LEFT JOIN PTYPE pt ON a.PTypeID= pt.typeid ' + @SQL_Man 
	
SET @SQL = @SQL	+ '	WHERE	a.BillNumberID IN (SELECT A FROM DBO.F_Split(''' + @BillNumberID + ''','','') WHERE ISNULL(A,'''') <> '''')
					AND a.Type = ' + @chvType  + '
					AND ISNULL(a.Qty,0) - ISNULL(a.BackQty,0) - ISNULL(a.BQty,0) > 0'
SET @SQL = @SQL	+ ' ORDER BY a.[ID]'

--PRINT(@SQL)
EXEC(@SQL)
IF @chvMPTypeID = '-99999' DROP TABLE #F_BaseGetManDetailPType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryOldLendOrBorrowBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryOldLendOrBorrowBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：李灏龙
	日期：2012-2-2 13:47:58
	描述：借出还回单调原借出单据
	
	修改：周华
	日期：2012-04-19 17:48:19.223
	描述：判断条件变化了,现在是以明细id为准
*/
CREATE            PROCEDURE Gp_QueryOldLendOrBorrowBill
( 
	 @chvBeginDate	VARCHAR(25),
	 @chvEndDate	VARCHAR(25),
	 @chvBtype		VARCHAR(50),
	 @chvEtype		VARCHAR(50),
	 @chvKtype		VARCHAR(50),
	 @chvStype		varchar(50),
	 @chvOperatorId VARCHAR(50),       --操作员ID
	 @chvType       VARCHAR(5),
	 @chvPType		varchar(50)='',
	 @billtype		INT,
	 @areatypeid	VARCHAR(max)='',		--地区（多选,不确定值的大小所以用max）
	 @checkEtypeid	VARCHAR(max)=''		--制单人（多选,不确定值的大小所以用max）
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
----往来权限----	 
CREATE TABLE #btype
(	
	btypeid VARCHAR(8000)
)
INSERT INTO #btype 
SELECT TypeId AS btypeid
FROM F_GetAllManagerBASeTypeId(@chvBtype,2,@chvOperatorId) 
	 
----职员权限----	 
CREATE TABLE #etype
(
	etypeid VARCHAR(8000)	
)
INSERT INTO #etype
SELECT TypeId AS etypeid
FROM F_GetAllManagerBASeTypeId(@chvEtype,3,@chvOperatorId)
	 
----仓库权限----	 
CREATE TABLE #ktype
(	
	ktypeid VARCHAR(8000)
)
INSERT INTO #ktype
SELECT TypeId AS ktypeid
FROM F_GetAllManagerBASeTypeId(@chvKtype,4,@chvOperatorId)

---- ******** 权限范围单独处理 - End ********
IF @chvKtype IS NULL
BEGIN
	SET @chvKtype = ''
END
DECLARE @LBSUM	 NUMERIC(24, 10) ,
		@OISUM	 NUMERIC(24, 10) ,
		@INIQTY	 NUMERIC(24, 10)	--期初借欠数量
IF @chvType = '87'
BEGIN
	SELECT @LBSUM=ISNULL(SUM(totalqty),0) FROM LendIndex WHERE BillType=87 AND Stypeid= @chvStype AND Btypeid= @chvBtype AND IFCHECK='t' AND DRAFT=0 AND redword=0
	SELECT @OISUM=ISNULL(SUM(totalqty),0) FROM LendIndex WHERE BillType=88 AND Stypeid= @chvStype AND Btypeid= @chvBtype AND IFCHECK='t' AND DRAFT=0 AND redword=0
END
ELSE
BEGIN
	SELECT @LBSUM=ISNULL(SUM(totalqty),0) FROM LendIndex WHERE BillType=71 AND Stypeid= @chvStype AND Btypeid= @chvBtype AND IFCHECK='t' AND DRAFT=0 AND redword=0
	SELECT @OISUM=ISNULL(SUM(totalqty),0) FROM LendIndex WHERE BillType=72 AND Stypeid= @chvStype AND Btypeid= @chvBtype AND IFCHECK='t' AND DRAFT=0 AND redword=0
END
--期初借欠数量
IF EXISTS (SELECT TOP 1 1 FROM dbo.IniGoodsLend WHERE BtypeId=@chvBtype)
BEGIN
	SELECT @INIQTY=SUM(BorrowQty)-SUM(LendQty) FROM dbo.IniGoodsLend WHERE BtypeId=@chvBtype GROUP BY BtypeId 	
END
ELSE
BEGIN
	SELECT @INIQTY=0
END

SELECT A.BackItemId,SUM(ISNULL(A.Qty,0)) AS QTY 
INTO #lend 
FROM LendBill a 
INNER JOIN LendIndex li ON a.Billnumberid=li.billnumberid
WHERE (a.BackItemId<>0) AND A.BackItemId IS NOT NULL 
 AND li.draft=0 and li.redword=0 and li.ifcheck='t'
GROUP BY A.BackItemId
CREATE TABLE #Lendback
(
	ptypeid varchar(50),
	ktypeid varchar(50),
	btypeid varchar(50)
)
CREATE TABLE #LendDataTotal
(
	pTypeID varchar(50),
	kTypeID varchar(50),
	bTypeID varchar(50),
	Qty		 NUMERIC(24, 10) ,
	Borrow		 NUMERIC(24, 10) ,
	BorrowBack		 NUMERIC(24, 10) ,
	Lend		 NUMERIC(24, 10) ,
	LendBack		 NUMERIC(24, 10) ,
	NBorrow		 NUMERIC(24, 10) ,
	NBorrowBack		 NUMERIC(24, 10) ,
	NLend		 NUMERIC(24, 10) ,
	NLendBack		 NUMERIC(24, 10) ,
)
INSERT INTO #LendDataTotal
SELECT	pTypeID,kTypeID,bTypeID,SUM(Qty) AS Qty,SUM(Borrow) AS Borrow,SUM(BorrowBack) AS BorrowBack,SUM(Lend) AS Lend,SUM(LendBack) AS LendBack,SUM(NBorrow) AS NBorrow,SUM(NBorrowBack) AS NBorrowBack,SUM(NLend) AS NLend,SUM(NLendBack) AS NLendBack
FROM(
	SELECT pTypeID,kTypeID,bTypeID,qty,Borrow,BorrowBack,Lend,LendBack,NBorrow,NBorrowBack,NLend,NLendBack
	FROM V_LendFace WHERE draft=0 and ifcheck='t' and redword=0
	UNION ALL
	SELECT pTypeID,kTypeID,bTypeID,qty,Borrow,0 AS BorrowBack,Lend,0 AS LendBack,NBorrow,0 AS NBorrowBack,NLend,0 AS NLendBack
	FROM V_LendFace00
	) AS	Lend
GROUP BY pTypeID,kTypeID,bTypeID
		
IF @billtype IN (88,87)
BEGIN
	INSERT INTO #Lendback
	SELECT  pTypeID,kTypeID,bTypeID
	 FROM #LendDataTotal
	GROUP BY pTypeID,kTypeID,bTypeID
	HAVING ISNULL(SUM(Lend),0) > ISNULL(SUM(LendBack),0)
END
ELSE
BEGIN
	 INSERT INTO #Lendback
	 SELECT pTypeID,kTypeID,bTypeID
	 FROM #LendDataTotal
	 GROUP BY pTypeID,kTypeID,bTypeID
	 HAVING ISNULL(SUM(Borrow),0) > ISNULL(SUM(BorrowBack),0)
END

--select * from #Lendback

IF @LBSUM+@OISUM+@INIQTY<>0
BEGIN
	DECLARE @TEMP VARCHAR(MAX)=''
	IF @chvEtype != ''
		SET @TEMP = @TEMP + ' AND l.etypeid = ''' + @chvEtype + ''''
	IF @chvKtype != ''
		SET @TEMP = @TEMP + ' AND l.ktypeid = ''' + @chvKtype + ''''
	IF @chvPType != ''
		SET @TEMP = @TEMP + ' AND l.BillNumberId IN( SELECT BillNumberId FROM LendBill WHERE ptypeid = ''' + @chvPType + ''')'
	IF @areatypeid<>''
	BEGIN
		SET @TEMP = @TEMP+' AND l.dealbtypeid IN (SELECT typeid FROM btype WHERE areatypeid in ('''+REPLACE(@areatypeid,',',''',''')+'''))'
	END
	IF @checkEtypeid<>''
	BEGIN
		SET @TEMP = @TEMP+' AND l.CHECKE IN ('''+REPLACE(@checkEtypeid,',',''',''')+''')'
	END
	DECLARE @SQL VARCHAR(3000)
	SET @SQL = 'SELECT	billdate,billcode,ABS(totalqty) AS totalqty, '''+CAST(ABS(@OISUM) AS VARCHAR(50))+'''  AS backqty,l.Stypeid,l.etypeid,l.dealbtypeid as btypeid,l.ktypeid,l.Comment,l.BillNumberId,l.BillType,l.dtypeid,
				em.fullname as efullname,de.fullname as dfullname,s.fullname as kfullname
				FROM	lendindex l
						INNER JOIN #btype b ON b.btypeid = l.btypeid
						INNER JOIN #etype e ON e.etypeid = l.etypeid
						INNER JOIN #ktype k ON k.ktypeid = l.ktypeid
						INNER JOIN employee em ON l.etypeid=em.typeid
						INNER JOIN Department de ON l.dtypeid=de.typeid
						INNER JOIN stock s ON l.ktypeid=s.typeid
						INNER JOIN 
						(
							SELECT SUM(ABS(QTY)) AS qty,
							SUM(ABS(BUYQTY)) as buyqty,
							SUM(ABS(SALEQTY)) as saleqty,
							BillNumberId 
							FROM LendBill 
							GROUP BY BillNumberId
						) t ON l.BillNumberId=t.billnumberid AND t.qty-t.buyqty-t.saleqty > 0
				WHERE	BillType= '''+@chvType  +''' 
						AND ifcheck=''t''--9.6功能，只能调已经过账的
						AND l.redword=0
						AND EXISTS(SELECT 1 FROM lendbill bill, #Lendback b WHERE bill.billnumberid=l.billnumberid and b.pTypeID=bill.PTYPEID  AND B.kTypeID=l.ktypeid AND B.bTypeID=l.btypeid )
						AND BillDate >= ''' + @chvBeginDate+
						''' AND BillDate <= ''' + @chvEndDate + 
						''' AND l.Stypeid= ''' + @chvStype + 
						''' AND l.Btypeid= ''' + @chvBtype + 
						'''' + @TEMP 
						-- 添加的条件
						+' AND EXISTS(
							SELECT a.Id FROM LendBill a 
							INNER JOIN LendIndex li ON li.BillNumberId=a.BillNumberId
							LEFT JOIN #lend  b ON a.Id=b.BackItemId
							WHERE (a.BackItemId=0 OR a.BackItemId IS NULL) AND l.BillNumberId=a.BillNumberId
							GROUP BY a.BillNumberId,a.Id
							HAVING ABS(ISNULL(SUM(ISNULL(a.qty,0)),0))>ABS(SUM(ISNULL(b.qty,0)))
						)'
	--print(@SQL)
	EXEC(@SQL)		
END

drop table #Lendback,#btype,#etype,#ktype,#lend,#LendDataTotal
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryOldLendOrBorrowPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryOldLendOrBorrowPtype]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：李灏龙
	日期：2012-2-2 16:49:30
	描述：借出还回单调原借出单据(具体商品部分)

	修改:周华
	日期：2012-04-16 14:18:47.627
	描述：调原借欠单 现求显出还了多少商品的信息
		从9.0上搬到这里来，注意一般更新这里可能会更新9.0;
	
*/
CREATE  PROCEDURE Gp_QueryOldLendOrBorrowPtype 
( 
	@BillNumberID	varchar(max),
	@chvOperatorId 	varchar(50),       --操作员ID
	@chvType       	varchar(5),
	@chvPType		varchar(250)=''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

---- ******** 权限范围单独处理 - Start ********
CREATE TABLE #Ptype(typeid VARCHAR(50))
INSERT INTO #Ptype SELECT TYPEID FROM dbo.F_GetAllManagerBaseTypeId('',1,@chvOperatorId)
---- ******** 权限范围单独处理 - End ********
SELECT	a.*,
		cbd.*,
		e.fullname as efullnamecustom,
		p.fullname as pfullnamecustom,
		b.fullname as bfullnamecustom,
		d.fullname as dfullnamecustom,
		k.fullname as kfullnamecustom,
		s.fullname as sfullnamecustom,
		CT.fullname AS cargofullname
 FROM 
(
	SELECT a.BillNumberId,
			c.typeid,
			ABS(a.qty) as qtyx,
			a.comment,
			a.stypeid,a.id as backitemid,
			c.usercode,
			c.fullname,
			c.baseUnitId AS UnitID,
			c.AssistantUnitId AS NUnitID,		
			u.FullName AS unit,
			v.FullName AS nunit,	
			c.customitemid ,
			c.customitemfrom ,
			c.customitemname,
			c.customitemrefid,		        
			itemid=a.ItemId,
			i.billtype,
			itemname= CASE WHEN a.IsCombined = 0  THEN
					 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
			iscombined=a.IsCombined,
			c.unitstype,
			c.serialcount,
			CAST(c.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
			CASE WHEN ISNULL(c.AssistantUnitId,0)=0 THEN NULL
			ELSE a.UnitRate END AS unitrate,
			--WHEN CAST(ABS(a.NQty+SUM(ISNULL(b.NQty,0))) AS  NUMERIC(24, 10) )=0 THEN 0 
			--ELSE CAST(ABS(a.qty+SUM(ISNULL(b.qty,0))) AS  NUMERIC(24, 10) )/CAST(ABS(a.NQty+SUM(ISNULL(b.NQty,0))) AS  NUMERIC(24, 10) ) END AS unitrate,
			CASE WHEN ISNULL(c.AssistantUnitId,0)=0 THEN NULL
			ELSE ABS(a.NQty+SUM(ISNULL(d.NQty,0))) END AS NQty,	
			a.GoodsNumber,
			a.serial,
			ABS(SUM(ISNULL(d.qty,0.0000))) as backqty,
			ABS(a.qty+SUM(ISNULL(d.qty,0))) as qty, -- 由于用名称绑定的原因，所在这里其它是差 qtyx是数量
			ABS(a.qty+SUM(ISNULL(d.qty,0))) as shouldqty,
			c.IfSerial,
			1 AS isloadbill,
			a.buyqty,a.saleqty,a.id,a.cargoid,i.ktypeid,
			a.comment+':'+i.BillCode as base, --用于验证的，由于上面所有的字段都是绑定的，所以我要保存一个初始的值好像没有办法
			aux.auxfullname1,aux.auxfullname2,aux.auxfullname3,aux.auxrate1,aux.auxrate2,aux.auxrate3,
			CASE WHEN @chvType=71 THEN u1.UnitsId ELSE u2.UnitsId END as munitid,
			CASE WHEN @chvType=71 THEN u1.fullname ELSE u2.fullname END as munit,
			CASE WHEN @chvType=71 THEN e1.rate ELSE e2.rate END as munitrate,
			CASE WHEN @chvType=71 THEN '1'+u1.fullname +'='+ CAST(DBO.F_ClearInvalidDecimal(e1.rate) AS VARCHAR)+ u.fullname 
			ELSE '1'+u2.fullname +'='+ CAST(DBO.F_ClearInvalidDecimal(e2.rate) AS VARCHAR) + u.fullname END as conversionrelationship,
			re.typeid AS etypeid,re.fullname as efullname,re.usercode as eusercode,
			a.ProduceDate,a.ValidDate,
			dbo.F_GetAllEntrycode(c.typeid,c.saleunitid,2) AS salemunitcode,
			dbo.F_GetAllEntrycode(c.typeid,c.buyunitid,2) AS buymunitcode,
			C.brandartypeid,
			bc.usercode as brandaruercode,
			bc.fullname as brandarfullname,
			dbo.F_GetCustomAssist(c.typeid,a.qty) customassistantunit
	FROM LendBill a
	INNER JOIN #Ptype P ON A.PtypeId=P.typeid
	LEFT JOIN 
	(
		SELECT lb.id,lb.QTY,lb.NQty,lb.BackItemId,lb.BillNumberId 
		FROM LendBill lb INNER JOIN LendIndex lbi ON lb.BillNumberId=lbi.BillNumberId
		AND lbi.draft=0 AND lbi.ifcheck='t' AND lbi.redword=0
	) d ON a.id=d.BackItemId
	INNER JOIN ptype c ON a.ptypeid=c.typeid	
	INNER JOIN brandar_Commodity bc ON bc.typeid = C.brandartypeid 
	INNER join LendIndex i on a.BillNumberId=i.BillNumberId
	INNER JOIN dbo.employee re ON i.etypeid=re.typeId
	LEFT  JOIN PType_Units u ON u.UnitsId=c.baseUnitId
	LEFT  JOIN PType_Units v ON v.UnitsId=c.AssistantUnitId
	LEFT  JOIN PType_Units u1 ON u1.UnitsId=c.buyunitid
	LEFT  JOIN PType_Units u2 ON u2.UnitsId=c.saleunitid
	LEFT  JOIN PType_Units_Ext e ON (e.UnitsId=c.AssistantUnitId AND e.PtypeID=c.typeId)
	LEFT  JOIN PType_Units_Ext e1 ON (e1.UnitsId=c.buyunitid AND e1.PtypeID=c.typeId)
	LEFT  JOIN PType_Units_Ext e2 ON (e2.UnitsId=c.saleunitid AND e2.PtypeID=c.typeId)
	LEFT  JOIN 
	(
		SELECT aux.ptypeid,pu.fullname as auxfullname1, pu1.fullname as auxfullname2, pu2.fullname as auxfullname3,
		aux.saleunitrate1 as auxrate1,aux.saleunitrate2 as auxrate2,aux.saleunitrate3 as auxrate3
		FROM PType_AuxiliaryUnits_Ext aux 
		LEFT JOIN PType_Units pu ON aux.saleunitid1=pu.unitsid
		LEFT JOIN PType_Units pu1 ON aux.saleunitid2=pu1.unitsid
		LEFT JOIN PType_Units pu2 ON aux.saleunitid3=pu2.unitsid
	) aux ON aux.ptypeid=c.typeid
	WHERE a.BillNumberId IN (SELECT a FROM DBO.F_Split(@BillNumberId,',')) 
	GROUP BY a.BillNumberId,
			 c.typeid,
			 a.qty,
			 a.comment,
			 a.stypeid,
			 a.id,
			 c.usercode,
			 c.fullname,
			 c.unit1,
			 c.IfSerial,
			 i.BillCode,
			 c.customitemid ,
			 c.customitemfrom ,
			 c.customitemname,
			 c.customitemrefid,		        
			 a.itemid,
			 a.IsCombined,
			 a.GoodsNumber,	
			 a.NQty,	
			 CAST(ISNULL(a.serial,'') AS VARCHAR(MAX)),	 
			 c.unitstype,
			 c.serialcount,
			 c.IfUseGoodsNum,
			 c.baseUnitId,
			 c.AssistantUnitId,
			 u.FullName,
			 v.FullName,
			 a.UnitRate,a.serial,a.buyqty,a.saleqty,
			 a.cargoid,i.ktypeid,i.billtype,u1.UnitsId,u2.UnitsId
			 ,u1.fullname,u2.fullname,e1.rate,e2.rate,
			 aux.auxfullname1,aux.auxfullname2,aux.auxfullname3,aux.auxrate1,aux.auxrate2,aux.auxrate3
			 ,re.typeId,re.UserCode,re.FullName,
			a.ProduceDate,a.ValidDate,c.SaleUnitId,c.BuyUnitId,
			C.brandartypeid,
			bc.usercode,
			bc.fullname
	having(  ABS(a.qty)> ABS(SUM(ISNULL(d.qty,0.0000))) )--借出必须大于还回数量
) a 
LEFT JOIN custom_billdetails cbd on cbd.BillId=a.billnumberid AND cbd.detailid=a.id and cbd.billtype=a.billtype
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
LEFT JOIN dbo.CargoType CT ON a.CargoID = CT.CargoID
WHERE qtyx - backqty - buyqty - saleqty > 0
ORDER BY a.id
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryOldPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryOldPtype]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：谢吉康
	日期：2008-07-128
	描述：采购、退货单调原采购单、销售单、零售单(具体商品部分)
*/
CREATE                           PROCEDURE Gp_QueryOldPtype 
( 
	@BillNumberID	varchar(max),
	@chvOperatorId 	varchar(50),       --操作员ID
	@chvType       	varchar(5),
	@chvPType		varchar(250)=''	
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(MAX)=''

-- 商品
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
	
	IF @chvType='305'
	BEGIN
		SET @SQL_Man='  INNER JOIN #F_BaseGetManDetailPType P ON 
							CASE WHEN ISNULL(iscombinationstyle,0)=1 
								 THEN combination.PTypeID 
							ELSE A.PTypeID END = P.TypeID '
	END
	ELSE
	BEGIN
		SET @SQL_Man=' INNER JOIN #F_BaseGetManDetailPType P ON a.PTypeID = P.TypeID '
	END
END
-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(MAX)
SET @SQL = '
	SELECT	a.BillNumberID
			,a.PTypeID
			,pt.usercode
			,pt.fullname
			,a.ID
			,'+ CASE @chvType WHEN '12' THEN '''''' ELSE ' CONVERT(varchar(8000),a.Serial) ' END +' AS Serial
			,'+ CASE @chvType WHEN '12' THEN '''''' ELSE ' a.ProduceDate ' END +' AS ProduceDate
			,'+ CASE @chvType WHEN '12' THEN '''''' ELSE ' a.ValidDate ' END +' AS ValidDate
			,'+ CASE @chvType WHEN '12' THEN '''''' ELSE ' a.GoodsNumber ' END +' AS GoodsNumber
			,a.Qty
			,a.SalePrice
			,a.nsaleprice
			,a.SaleTotal AS Total
			,a.Discount
			,a.DiscountPrice
			,a.NDiscountPrice
			,a.Total AS DiscountTotal
			,a.Tax
			,a.TaxPrice
			,a.TaxTotal
			,a.Comment
			,ISNULL(a.BackQty,0) AS BackQty
			,ISNULL(a.Qty,0) - ISNULL(a.BackQty,0) AS RemainQty
			,a.stypeid
			,bi.NewPosBill
			,bi.costsale
			,CASE 
					WHEN a.IsCombined = 0  THEN (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) 
			END AS itemname
			,pt.brandartypeid
			,bc.usercode as brandaruercode
			,bc.fullname as brandarfullname '
			
IF @chvType IN ('11','305')
BEGIN
	SET @SQL =@SQL + ' ,re.usercode as eusercode,re.fullname as efullname,re.typeid as etypeid '
END

SET @SQL =@SQL + ''+ CASE  @chvType WHEN  '12' THEN ' ,a.pindexid ' ELSE ',''''' END +' AS pindexid
	FROM	' + CASE @chvType WHEN '11' THEN 'SaleBill' WHEN '305' THEN 'RetailBill' 
	WHEN '402' THEN 'SendBill' WHEN '400' THEN 'AppraisalBill' WHEN '12' THEN 'PT_Combin_SaleBill' ELSE 'BuyBill' END + ' a '
	+'INNER JOIN BillIndex bi ON a.billnumberid = bi.billnumberid
	INNER JOIN Ptype pt ON a.ptypeid=pt.typeid
	INNER JOIN brandar_Commodity bc ON bc.typeid = pt.brandartypeid 
	'

--零售单组合品样式商品权限使用上表格商品
IF @chvType='305' AND @chvMPTypeID = '-99999'
BEGIN
	SET @SQL=@SQL+' LEFT JOIN  RetailCombinationBill Combination ON A.PIndexId=Combination.PIndexID '
END

SET @SQL=@SQL+@SQL_Man 

IF @chvType IN ('11','305')
BEGIN
	SET @SQL =@SQL + ' LEFT JOIN employee re ON re.typeid=a.etypeid '
END

SET @SQL = @SQL + '	WHERE	a.BillNumberID IN (SELECT * FROM DBO.F_Split(''' + @BillNumberID + ''','','') WHERE ISNULL(A,'''') <> '''')
					AND ISNULL(a.Qty,0) - ISNULL(a.BackQty,0) > 0'					
					+CASE WHEN @chvType='305' THEN ' AND A.iscombination=0 ' ELSE '' END		
		
IF @chvPType <> '' SET @SQL = @SQL + ' AND a.PTypeID = ''' + @chvPType + ''''

--零售单，只调入普通商品，组合品排除
IF @chvType = '305'
BEGIN
	SET @SQL = @SQL + ' AND a.iscombination=0 '
END

SET @SQL = @SQL + ' ORDER BY a.[ID]'

--PRINT(@SQL)
EXEC(@SQL)

IF @chvMPTypeID = '-99999' DROP TABLE #F_BaseGetManDetailPType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryOrderIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryOrderIndex]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryOrderIndex    Script Date: 2002-6-20 10:14:51 ******/

CREATE  PROCEDURE Gp_QueryOrderIndex
( 
 @BeginDate  varchar(25),
 @EndDate  varchar(25),
 @BtypeId  varchar(25),
 @EtypeId  varchar(25),
 @ktypeId  varchar(25),
 @OrderBy  varchar(50) = 'billdate',
 @BillType  varchar(5) = '',
 @Checke varchar(25)=''
-- @FilterBill bit = 0 
)
--@encode$--
AS
SET NOCOUNT ON 
declare @cz_query varchar(8000)
declare @Sql varchar (8000)
select @cz_Query=''
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=@cz_query+' a.billdate>='+char(39)+@begindate+char(39)+' and a.billdate<='+char(39)+@enddate+char(39)+' and '
--if rtrim(@Atypeid) <>''
-- select @cz_query=@cz_query+' a.atypeid='+char(39)+@atypeid+char(39)+' and '
if rtrim(@etypeid) <> ''
 select @cz_query=@cz_query+' a.etypeid='+char(39)+@etypeid+char(39)+' and '
if rtrim(@ktypeid) <>'' 
 select @cz_query=@cz_query+' a.ktypeid='+char(39)+@ktypeid+char(39)+' and '
if rtrim(@btypeid) <> '' 
 select @cz_query=@cz_query+' left(a.btypeid,len('+char(39)+@btypeid+char(39)+'))='+char(39)+@btypeid+char(39)+' and '
if rtrim(@billtype)<> ''
 select @cz_query=@cz_query+' a.billtype='+char(39)+@billtype+char(39) + ' and'
if rtrim(@Checke)<> ''
 select @cz_query=@cz_query+' a.Checke='+char(39)+@Checke+char(39) + ' and'
--if @filterbill=1
--begin
-- select @cz_query=@cz_query+' a.billtype<>4 and a.billtype<>66 and a.billtype<>116
--    and a.billtype<>115 and a.billtype<>129 and a.billtype<>128 and a.billtype<>77 and a.ifcheck=''f'' and'
--end else
--begin
-- select @cz_query =@cz_query+' a.ifcheck=''t'' and'
--end
select @cz_query=substring(@cz_query,1,len(@cz_query)-4)
select @Sql ='SELECT *, CBillType=
  case billtype 
  when 300 then ''销售订单''
  when 301 then ''进货订单''
  end,
          (SELECT isnull(fullname,'''')
         FROM employee b
         WHERE a.etypeid = b.typeid) AS etype,
          (SELECT isnull(fullname,'''')
         FROM Stock b
         WHERE a.Ktypeid = b.typeid) AS Ktype,
          (SELECT isnull(fullname,'''')
         FROM btype b
         WHERE a.btypeid = b.typeid) AS btype
 FROM OrderIndex a where'+@cz_query +' order by '+@orderby
--print @sql
exec (@Sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryPByNameCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryPByNameCode]
GO














/****** Object:  Stored Procedure dbo.Gp_QueryPByNameCode    Script Date: 2002-6-20 10:14:51 ******/

CREATE  PROCEDURE Gp_QueryPByNameCode 
(
    @DbName  varchar(30),
    @Code  varchar(33),
    @FullName  varchar(66)
)
--@encode$--
as
SET NOCOUNT ON 
declare @sql [varchar](5000)
select @sql='select * from '+@dbname
if @Code<>'' select @sql=@sql+' where sonnum =0 and deleted=0 and usercode like'+CHAR(39)+'%'+@Code+'%'+char(39)
if @Fullname<>'' select @sql=@sql+' where sonnum=0 and deleted=0 and fullname like'+CHAR(39)+'%'+@fullname+'%'+char(39)+'and fullname <> '+char(39)+'root'+char(39)
exec (@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryPosAllotApplyBillIndexLi]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryPosAllotApplyBillIndexLi]
GO

/*
	author:	chenqiang
	comment:门店配送单据查询
*/


CREATE PROCEDURE Gp_QueryPosAllotApplyBillIndexLi
( 
	@OperatorID		varchar(100) 	,  			-- 操作员
	@BeginDate	 	varchar(25)  	='', 		-- 开始时间
	@EndDate	 	varchar(25)  	='',   		-- 结束时间
	@Billcode	 	varchar(200)  	='', 		-- 单据编号
	@stypeid		varchar(MAX)	='00001',  	-- 分支机构
	@ETypeId		VARCHAR(8000)='',			--经手人
	@DTypeId		VARCHAR(8000)='',			--部门
	@KTypeId		VARCHAR(8000)='',			--出库仓库		
	@KTypeId2		VARCHAR(8000)='',			--入库仓库
	@ptypeCategoryid	VARCHAR(max),			--商品类别
	@PTypeId		VARCHAR(100)='',			--商品ID
	@billstate		varchar(100),				--单据状态
	@ifcheck		varchar(50),				--是否过账单据(0 过账，1 草稿)
	@billtype		varchar(50),				--单据类型
	@Explain		varchar(200),				--说明
	@Comment		varchar(200),				--摘要
	@showredword	int=1						--是否显示红冲
)

AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPTypeId VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPTypeId OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--权限处理部分
DECLARE @re_pass		INT,
		@re_draft		INT,
		@offset_pass	INT = 745,	--查看他人经营历程
		@offset_draft	INT	= 467,	--查看他人业务草稿
		@SQL_Limit      VARCHAR(max) = '' --权限条件
EXEC @re_draft =GP_CheckLimit @OperatorID,@offset_draft
EXEC @re_pass = GP_CheckLimit @OperatorID,@offset_pass

IF (@re_draft = 1 AND @ifcheck = 1) OR (@re_pass = 1 AND @ifcheck = 0)  --没有查看他人草稿的权限，查草稿 OR 没有查看他人经营历程的权限，查过账
BEGIN
	SET @SQL_Limit = ' AND (bi.Checke = '''+@OperatorID+''' OR ISNULL(bi.Checke,'''') = '''') '
END	

IF @OperatorID <> '00001'  -- 相关单据查看权限，除开管理员
BEGIN
    DECLARE @BillTypeList1 VARCHAR(MAX)
    DECLARE @LimitList1 VARCHAR(MAX)
    DECLARE @BillTypes1 VARCHAR(2000)

   --单据查看权限
    SELECT  @BillTypes1 = '(9999'
    SET @BillTypeList1 = '327,328,329'
    SET @LimitList1 = '5244,5253,5256'					

    SELECT  @BillTypes1 = @BillTypes1
            + CASE WHEN SUBSTRING(L.lim, T.OFFSET, 1) = 1
                   THEN ',' + T.BillType
                   ELSE ''
              END
    FROM    ( SELECT    A.ID ,
                        A.a AS BillType ,
                        CONVERT(INT, B.a) AS OFFSET
              FROM      ( SELECT    ROW_NUMBER() OVER ( ORDER BY ( SELECT
                                              0
                                              ) ) AS ID ,
                                    a
                          FROM      f_split(@BillTypeList1,
                                            ',')
                        ) A
                        INNER JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY ( SELECT
                                              0
                                              ) ) AS ID ,
                                            a
                                     FROM   f_split(@LimitList1,
                                              ',')
                                   ) B ON A.ID = B.ID
            ) T ,
            loginuser L
    WHERE   L.etypeid = @OperatorID			

    SET @BillTypes1 = @BillTypes1 + ' ) '

    SET @SQL_Limit = @SQL_Limit + ' AND bi.BillType IN '
        + @BillTypes1
    
END     


CREATE TABLE #Stype (TypeId varchar(100))		--分支机构
CREATE TABLE #Ptype (TypeID varchar(200))		--商品
CREATE TABLE #EType	(TypeId VARCHAR(100))		--经手人
CREATE TABLE #Dtype (TypeID varchar(50))		--部门
CREATE TABLE #ETypeChecke	(TypeId VARCHAR(100))		--控制制单人

--筛选分支机构
CREATE CLUSTERED INDEX CIX_Stype ON #Stype(TypeId) 
SET @stypeid = LTRIM(RTRIM(@stypeid))
IF NOT(@stypeid='' and @MStypeid='00000')
BEGIN
	INSERT INTO #Stype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)		
END


IF @PTypeId =''
	INSERT INTO #Ptype(typeid) SELECT typeid FROM F_LinePC(@OperatorID,@ptypecategoryid) 
ELSE
	INSERT INTO #Ptype(typeid) 
	SELECT a.typeid 
	FROM F_ManPTypeInCategoryID (@OperatorID,@PTypeId,@ptypecategoryid) a,(SELECT * FROM  dbo.f_split(@PTypeId,',')) b 
	WHERE A.TypeId LIKE B.a+'%'

--职员(制单人)
DECLARE @Etypelimt INT 
DECLARE @LimitNum INT 
IF @ifcheck = 0 --过账
	SET @LimitNum = 745 --查看他人经营历程
ELSE 
	SET @LimitNum = 467	--查看他人业务草稿

Exec @Etypelimt= GP_CheckLimit @OperatorID,@LimitNum
IF @Etypelimt <> 0
BEGIN
	INSERT INTO #ETypeChecke(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)
END	
ELSE
BEGIN 
	INSERT INTO #ETypeChecke(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId('00001',3)
END	

--职员(经手人)
IF @ETypeId = ''
	INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)
ELSE 
	INSERT INTO #EType(TypeId) SELECT * FROM dbo.f_split(@ETypeId,',')

--部门
INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

CREATE TABLE #KTypeId(TypeId	VARCHAR(50))
CREATE TABLE #KTypeIdIn(TypeId	VARCHAR(50))

DECLARE @limt INT ,
		@checkStock VARCHAR(200)
SELECT @limt = Value FROM dbo.Userconfig WHERE ConfigName = 'postransktypelimit'
SET @checkStock = ''

INSERT INTO #KTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)
INSERT INTO #KTypeIdIn(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid2,4,@OperatorID)

IF @limt = 0
BEGIN
	INSERT INTO #KTypeId(TypeId)
	SELECT TypeId
	FROM dbo.Stock s 
	INNER JOIN (SELECT a FROM dbo.f_split(@KtypeID,',')) f ON s.typeId LIKE f.a+'%'
	
	INSERT INTO #KTypeIdin(TypeId)
	SELECT TypeId
	FROM dbo.Stock s 
	INNER JOIN (SELECT a FROM dbo.f_split(@KtypeID2,',')) f ON s.typeId LIKE f.a+'%'
END

IF @MKtypeid='-99999' AND @OperatorID<>'00001'  
BEGIN
	
	IF @limt = 1
		SET @checkStock = ' AND (EXISTS (SELECT TOP 1 1 FROM #KTypeId WHERE TypeId = bi.ktypeid) AND EXISTS (SELECT TOP 1 1 FROM #KTypeIdIn WHERE TypeId = bi.inktypeid))'
	ELSE
		SET @checkStock = ' AND (EXISTS (SELECT TOP 1 1 FROM #KTypeId WHERE TypeId = bi.ktypeid) OR EXISTS (SELECT TOP 1 1 FROM #KTypeIdIn WHERE TypeId = bi.inktypeid))'
END

--状态表  
CREATE TABLE #billexecstate(execstate int,BillNumberId  NUMERIC(10, 0))
CREATE TABLE #BillNumberId(BillNumberId  NUMERIC(10, 0))

--门店配送单据的状态
INSERT INTO #BillNumberId(BillNumberId)
SELECT	DISTINCT 
		PB.BillNumberId 
FROM	PosAllotApplyBillIndex PB
WHERE	PB.BILLTYPE = 327 
		AND (@PTypeId = '' OR EXISTS(SELECT TOP 1 1 FROM  DeliveryBill B WHERE B.BillNumberId = PB.BillNumberId AND B.PTypeId = @PTypeId))
		
INSERT INTO #BILLEXECSTATE (EXECSTATE,BillNumberId)
SELECT CASE WHEN PB.Isdone = 1 THEN 10  -- 已完成（没有已完成，这里是验收过账完成）
			WHEN PB.QTY = M.GZQTY THEN 10  --验收过账完成
			WHEN PB.QTY = M.YYQTY THEN 9  --验收未过账
			--WHEN M.YYQTY = 0 OR M.BillNumberId IS NULL THEN 8		--未引用
			WHEN M.BillNumberId IS NULL THEN
			(CASE WHEN  de.decheckqty = 0 and  de.debackqty =0  THEN 8 ELSE 6 END )
			ELSE 6 END AS EXECSTATE,  --已引用未完成
			PB.BillNumberId
FROM PosAllotApplyBillIndex PB
INNER JOIN #BillNumberId B ON B.BillNumberId = PB.BillNumberId
INNER JOIN (
	SELECT	de.BillNumberId,
			SUM(de.Qty) as deQty,
			SUM(checkqty) as decheckqty,
			SUM(Backqty) as debackqty
	FROM	DeliveryBill  de
	INNER JOIN PosAllotApplyBillIndex pob on pob.BillNumberId=de.BillNumberId
	where pob.RedWord=0
	group by de.BillNumberId
)de on de.BillNumberId=pb.BillNumberId
LEFT JOIN (
			SELECT BillNumberId,SUM(GZQTY) AS GZQTY,SUM(YYQTY) AS YYQTY 
			FROM 
			(
				SELECT	DB.BillNumberId,
						CASE WHEN DB.QTY < DBB.QTY THEN DB.QTY ELSE DBB.QTY END AS GZQTY,
						0 AS YYQTY 
				FROM	DeliveryBill DB
				INNER JOIN DeliveryBackBill DBB ON DBB.DELIVERYID = DB.ID  --门店配送退货单
				INNER JOIN PosAllotApplyBillIndex PABI ON PABI.BillNumberId = DBB.BillNumberId AND PABI.REDWORD = 0 AND PABI.DRAFT = 0
				UNION ALL
				SELECT	DB.BillNumberId,
						CASE WHEN DB.QTY < DCB.QTY THEN DB.QTY ELSE DCB.QTY END AS GZQTY,
						0 AS YYQTY 
				FROM	DeliveryBill DB
				INNER JOIN DeliveryCheckBill DCB ON DCB.DELIVERYID = DB.ID  --门店配送验收单
				INNER JOIN PosAllotApplyBillIndex PABI ON PABI.BillNumberId = DCB.BillNumberId AND PABI.REDWORD = 0 AND PABI.DRAFT = 0
				UNION ALL 
				SELECT	DB.BillNumberId, 
						0 AS GZQTY,
						CASE WHEN DB.QTY < DBB.QTY THEN DB.QTY ELSE DBB.QTY END AS YYQTY 
				FROM	DeliveryBill DB
				INNER JOIN DeliveryBackBill DBB ON DBB.DELIVERYID = DB.ID  --门店配送退货单
				INNER JOIN PosAllotApplyBillIndex PABI ON PABI.BillNumberId = DBB.BillNumberId AND PABI.REDWORD = 0
				UNION ALL
				SELECT	DB.BillNumberId,
						0 AS GZQTY,
						CASE WHEN DB.QTY < DCB.QTY THEN DB.QTY ELSE DCB.QTY END AS YYQTY 
				FROM	DeliveryBill DB
				INNER JOIN DeliveryCheckBill DCB ON DCB.DELIVERYID = DB.ID  --门店配送验收单
				INNER JOIN PosAllotApplyBillIndex PABI ON PABI.BillNumberId = DCB.BillNumberId AND PABI.REDWORD = 0
			) X
			GROUP BY BillNumberId
		) M ON M.BillNumberId = PB.BillNumberId


DECLARE @SQL	VARCHAR(MAX)
DECLARE @SQL_WHERE	VARCHAR(MAX)
SET @SQL_WHERE=''


IF ISNULL(@PTypeId,'')<>''
BEGIN
	SET @SQL_WHERE+=' AND pt.typeid ='''+@PTypeId+''' '
END

--临时表数据
CREATE TABLE #TempDb
(
	BillNumberId	NUMERIC(10, 0),
	BillDate		datetime,
	billcode		varchar(100),
	billtype		NUMERIC(4, 0),
	qty				NUMERIC(24, 10),
	Total			NUMERIC(24, 10),
	ysrkqty			varchar(100),
	thqty			varchar(100),
	wysqty			varchar(100),
	wgzthqty		varchar(100),
	Remark			varchar(256),
	billstate		varchar(100),
	billstatename	varchar(100)
)

SET @SQL='INSERT INTO #TempDb(BillNumberId,BillDate,billcode,billtype,qty,Total,ysrkqty,thqty,wysqty,wgzthqty,Remark,billstate,billstatename)
	SELECT	A.BillNumberId,
			A.BillDate,
			A.BillCode,
			A.BillType,
			case when a.billtype =328 then -CAST(qty AS NUMERIC(24,10)) else CAST(qty AS NUMERIC(24,10)) end as qty,
			case when a.billtype =328 then -CAST(Total AS NUMERIC(24,10)) else CAST(Total AS NUMERIC(24,10)) end as Total,
			ysrkqty,
			thqty,
			wysqty,
			wgzthqty,
			Remark,
			billstate,
			billstatename
	FROM (
'
	

--门店配送单
IF EXISTS(SELECT 1 FROM  dbo.f_split(@billtype,',') a where a.a=327)
BEGIN
	SET @SQL+='
		SELECT	A.BillNumberId,
				A.billdate,
				A.BillCode,
				A.BillType,
				CAST(SUM(A.Qty) AS VARCHAR(100)) as qty,	--配送数量
				CAST(SUM(A.Total) AS VARCHAR(100)) as Total,	--配送金额
				CAST(sum(A.checkqty) AS VARCHAR(100)) as ysrkqty,--验收入库数量
				CAST(sum(A.backqty) AS VARCHAR(100)) as thqty,--退货数量 
				CAST(SUM(A.Qty)-sum(A.checkqty)-sum(A.backqty) AS VARCHAR(100)) as wysqty,
				CAST(sum(A.draftbackqty) AS VARCHAR(100)) AS wgzthqty,		--未过账退货数量
				A.Comment as Remark,
				BS.ExecState billstate,
				CASE 
				WHEN bs.execstate=10 THEN ''验收过账完成''  
				WHEN bs.execstate=9 THEN ''验收未过账'' 
				WHEN bs.execstate=8 THEN ''未引用'' 
				WHEN bs.execstate=7 THEN ''已完成'' 
				WHEN bs.execstate=6 THEN ''已引用未完成''  
				WHEN A.BillState=0 THEN ''原始单据'' 
				WHEN A.BillState=1 THEN ''已审核''
				WHEN A.BillState=2 THEN ''已接受''
				WHEN A.BillState=3 THEN ''已拒绝''
				WHEN A.BillState=4 THEN ''已作废'' 
				ELSE ''未引用'' END  as billstatename
		FROM
		(
			SELECT	pb.BillNumberId,
					pb.billdate,
					pb.billcode,
					pb.billtype,
					pb.stypeid,
					de.PTypeId,
					pb.applyetypeid,
					pb.checke,
					pb.dtypeid,
					pb.ifcheck,
					pb.redword,
					pb.billstate,
					de.qty,
					de.total,
					dbo.F_RoundQty(de.CheckQty) as checkqty,
					dbo.F_RoundQty((de.qty-de.CheckQty-back.thqyt)/de.MUnitRate) as wwcqty,					
					dbo.F_RoundQty(isnull((isnull(de.backqty,0)+isnull(back.thwgzqyt,0)),0)) as backqty,					
					dbo.F_RoundQty(isnull(back.thwgzqyt,0)) as draftbackqty,
					pb.Comment,pb.Explain,
					pb.IsIni
			FROM PosAllotApplyBillIndex pb 
			INNER JOIN DeliveryBill de on pb.BillNumberId=de.BillNumberId
			left join PType_Units puu on puu.UnitsId = de.UnitID
			left join PType_Units puum on puum.UnitsId = de.MUnitID
			LEFT JOIN 
			(
				select	bak.DeliveryID,
						sum(case when b.draft = 0 then bak.Qty else 0 end) as thqyt,
						sum(case when b.draft = 1 then bak.Qty else 0 end) as thwgzqyt
				from DeliveryBackBill bak
				inner join PosAllotApplyBillIndex b on b.BillNumberId = bak.BillNumberId
				inner join DeliveryBill db on db.ID = bak.DeliveryID
				where b.redword=0	
				group by bak.DeliveryID		
			) back on back.DeliveryID = de.ID 
		)A
		INNER join #BillNumberId b on b.BillNumberId = A.BillNumberId
		LEFT  join #billexecstate bs on A.BillNumberId = bs.BillNumberId	'
		IF NOT(@stypeid='' and @MStypeid='00000')
				SET @SQL+=' INNER JOIN #Stype st  ON  st.typeid=A.stypeid '
		-- INNER JOIN #Stype st on st.typeid=A.stypeid
		SET @SQL+='
		INNER JOIN #Ptype pt on pt.typeid=A.PTypeId
		INNER JOIN #EType et on	et.typeid=A.applyetypeid
		INNER JOIN #ETypeChecke ec on ec.typeid=A.checke
		INNER JOIN #Dtype dt on	dt.typeid=A.dtypeid
		WHERE 1=1 '+@SQL_WHERE+' '
		IF ISNULL(@billstate,'')<>''
		BEGIN
			SET @SQL+=' AND ('+@billstate+') '
		END
		
		--过账单据
		IF ISNULL(@ifcheck,'0')=0
		BEGIN
			SET @SQL +=' AND A.ifcheck=''t'' and a.IsIni<>1 '
			IF @showredword = 0 
			SET @SQL = @SQL + ' and A.RedWord = 0 '
		END
		ELSE
		BEGIN
			SET @SQL +=' AND A.ifcheck=''f''  '
			IF @showredword = 0 
			SET @SQL = @SQL + ' and A.RedWord = 0 '
		END
		
		IF ISNULL(@Billcode,'')<>''
		BEGIN
			SET @SQL+=' AND A.Billcode like ''%'+@Billcode+'%'' '
		END
				
		SET @SQL+='
		GROUP by A.BillNumberId,A.BillCode,A.billdate,A.BillType,A.Comment,bs.ExecState,A.BillState
		'
END

--配送退货单
IF EXISTS(SELECT 1 FROM  dbo.f_split(@billtype,',') a where a.a=328)
BEGIN
	IF EXISTS(SELECT 1 FROM  dbo.f_split(@billtype,',') a where a.a=327)
	BEGIN
			SET @SQL+=' UNION ALL '
	END
	SET @SQL+='
		SELECT	bi.BillNumberId,
				bi.billdate,
				bi.BillCode,
				bi.BillType,
				SUM(A.Qty) as qty,	--配送数量
				SUM(A.Total) as Total,	--配送金额
				CAST(''-''  AS VARCHAR(10) )as  ysrkqty,	--验收入库数量
				CAST(''-''  AS VARCHAR(10) )as thqty,		--退货数量
				CAST(''-''  AS VARCHAR(10) )as wysqty,		--未验收数量
				CAST(''-''  AS VARCHAR(10) )as wgzthqty,	--未过账退货数量
				A.Comment as Remark,
				bi.billstate,
				CASE	WHEN  bi.ifcheck = ''f'' AND bi.redword=0 THEN ''未引用'' 
						WHEN  bi.ifcheck = ''t'' AND bi.redword=0 THEN ''验收过账完成'' 
						WHEN  (bi.ifcheck = ''t'') AND (bi.redword=1 OR bi.redword=2) THEN ''已过账'' 
				END as billstatename
		FROM	DeliveryBackBill A			--门店配送退货单
		INNER JOIN PosAllotApplyBillIndex bi ON A.BillNumberId=bi.BillNumberId	'
		IF NOT(@stypeid='' and @MStypeid='00000')
			SET @SQL+=' INNER JOIN #Stype st  on st.typeid=bi.stypeid '
		-- INNER JOIN #Stype st on st.typeid=A.stypeid
		SET @SQL+='	
		INNER JOIN #Ptype pt on pt.typeid=A.PTypeId
		INNER JOIN #EType et on	et.typeid=bi.applyetypeid
		INNER JOIN #ETypeChecke ec on ec.typeid=bi.checke
		INNER JOIN #Dtype dt on	dt.typeid=bi.dtypeid
		WHERE 1=1  '+@SQL_WHERE+' '
		--过账单据
		IF ISNULL(@ifcheck,'0')=0
		BEGIN
			SET @SQL +=' AND bi.ifcheck=''t''  '
			IF @showredword = 0 
			SET @SQL = @SQL + ' and bi.RedWord = 0 '
		END
		ELSE
		BEGIN
			SET @SQL +=' AND bi.ifcheck=''f''  '
			IF @showredword = 0 
			SET @SQL = @SQL + ' and bi.RedWord = 0 '
		END
		
		IF ISNULL(@Billcode,'')<>''
		BEGIN
			SET @SQL+=' AND bi.Billcode like ''%'+@Billcode+'%'' '
		END
		
		SET @SQL+='
		GROUP by bi.BillNumberId,bi.BillCode,bi.billdate,bi.BillType,A.Comment,bi.BillState,bi.ifcheck,bi.redword '
END

--验收单
IF EXISTS(SELECT 1 FROM  dbo.f_split(@billtype,',') a where a.a=329)
BEGIN
	IF ISNULL(@ifcheck,'0')=0
	BEGIN	
		IF EXISTS(SELECT 1 FROM  dbo.f_split(@billtype,',') a where a.a in(327,328))
		BEGIN
			SET @SQL+=' UNION ALL '
		END
	
		SET @SQL+='
			SELECT	bi.BillNumberId,
					bi.billdate,
					bi.BillCode,
					bi.BillType,
					SUM(A.Qty) as qty,	--配送数量
					SUM(A.Total) as Total,	--配送金额
					CAST(''-''  AS VARCHAR(10) )as  ysrkqty,	--验收入库数量
					CAST(''-''  AS VARCHAR(10) )as thqty,		--退货数量
					CAST(''-''  AS VARCHAR(10) )as wysqty,		--未验收数量
					CAST(''-''  AS VARCHAR(10) )as wgzthqty,	--未过账退货数量
					A.Comment as Remark,
					bi.billstate,
					''已过账'' as billstatename
			FROM	DeliveryCheckBill A
			INNER JOIN PosAllotApplyBillIndex bi ON A.BillNumberId=bi.BillNumberId	'
			
			IF NOT(@stypeid='' and @MStypeid='00000')
				SET @SQL+=' INNER JOIN #Stype st  on st.typeid=bi.stypeid '
			SET @SQL+='	
			INNER JOIN #Ptype pt on pt.typeid=A.PTypeId
			INNER JOIN #EType et on	et.typeid=bi.applyetypeid
			INNER JOIN #ETypeChecke ec on ec.typeid=bi.checke
			INNER JOIN #Dtype dt on	dt.typeid=bi.dtypeid
			WHERE 1=1  '+@SQL_WHERE+' '
			--过账单据
			IF ISNULL(@ifcheck,'0')=0
			BEGIN
				SET @SQL +=' AND bi.ifcheck=''t''  '
				IF @showredword = 0 
				SET @SQL = @SQL + ' and bi.RedWord = 0 '
			END
			ELSE
			BEGIN
				SET @SQL +=' AND bi.ifcheck=''f''  '
				IF @showredword = 0 
				SET @SQL = @SQL + ' and bi.RedWord = 0 '
			END
			
			IF ISNULL(@Billcode,'')<>''
			BEGIN
				SET @SQL+=' AND bi.Billcode like ''%'+@Billcode+'%'' '
			END
			
			SET @SQL+='
			GROUP by bi.BillNumberId,bi.BillCode,bi.billdate,bi.BillType,A.Comment,bi.BillState '
	END
END

SET @SQL+=' )A '

--PRINT(@SQL)
EXEC (@SQL)

SET @SQL='
SELECT	CONVERT(varchar(100), A.BillDate,23) as billdate,
		A.BillCode, 
		bi.BillType,
		bi.RedWord,
		bi.total as atotal,
		bi.checke,
		checker.fullname AS checkename,
		bi.BillNumberId,
		CASE Bi.BillType 
		WHEN 327 THEN ''门店配送单'' 
		WHEN 328 THEN ''门店配送退货单'' 
		WHEN 329 THEN ''配送验收单''
		END billname,
		CASE WHEN bi.RedWord=2 THEN -A.qty ELSE A.qty END AS qty,
		CASE WHEN bi.RedWord=2 THEN -A.Total ELSE A.Total END AS Total,
		CASE WHEN bi.RedWord=2 THEN CASE WHEN A.ysrkqty=''-'' THEN ''-'' ELSE -CAST(A.ysrkqty AS NUMERIC(24,10)) END 
			 ELSE A.ysrkqty END AS ysrkqty,
		CASE WHEN bi.RedWord=2 THEN CASE WHEN A.thqty=''-'' THEN ''-'' ELSE -CAST(A.thqty AS NUMERIC(24,10)) END
			 ELSE A.thqty END AS thqty,
		CASE WHEN bi.RedWord=2 THEN CASE WHEN A.wysqty=''-'' THEN ''-'' ELSE -CAST(A.wysqty AS NUMERIC(24,10)) END
			 ELSE A.wysqty END AS wysqty,
		CASE WHEN bi.RedWord=2 THEN CASE WHEN A.wgzthqty=''-'' THEN ''-'' ELSE -CAST(A.wgzthqty AS NUMERIC(24,10)) END
			 ELSE A.wgzthqty END AS wgzthqty,
		A.Remark,
		bi.Explain,
		bi.Comment,
		bi.ApplyEtypeid as etypeid,
		bi.stypeid,
		bi.dtypeid,
		bi.KtypeId,
		bi.InKtypeId as ktypeid1,
		A.billstate,
		A.billstatename,
		k.fullname as kfullname,--出库仓库
		k1.fullname as kfullname2 --入库仓库
FROM	#TempDb A
INNER JOIN PosAllotApplyBillIndex bi ON bi.BillNumberId=A.BillNumberId 
LEFT JOIN STOCK K1 ON K1.typeId=bi.InKtypeId
LEFT JOIN STOCK K ON K.typeId=bi.KtypeId
LEFT JOIN employee checker on checker.typeid = bi.checke
WHERE 1=1 ' + @SQL_Limit

IF ISNULL(@Explain,'')<>''
BEGIN
	SET @SQL+=' AND bi.Explain like ''%'+@Explain+'%'' '
END

IF ISNULL(@Comment,'')<>''
BEGIN
	SET @SQL+=' AND bi.Comment like ''%'+@Comment+'%'' '
END

IF @BeginDate<>''
	SET @SQL+=' AND bi.BillDate>='''+@BeginDate+''''
IF @EndDate<>''
	SET @SQL+=' AND bi.BillDate<='''+@EndDate+''''
	
IF ISNULL(@ktypeid,'') <> ''
	SET @SQL += ' AND bi.ktypeid IN (SELECT typeid FROM #ktypeid) '
	
if isnull(@ktypeid2,'') <> ''
	set @sql += ' AND bi.InKtypeId IN (SELECT typeid FROM #ktypeidin) ' 

set @sql += @checkStock

SET @SQL+=' ORDER BY  A.BillDate DESC,A.BillCode'

--PRINT @sql
EXEC(@SQL)


DROP Table #Stype,#Ptype,#EType,#ETypeChecke,#Dtype,#KTypeid,#KTypeidin,#billexecstate,#BillNumberId,#TempDb

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_QueryPT_Combin_OrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryPT_Combin_OrderBill]
GO

CREATE PROCEDURE [Gp_QueryPT_Combin_OrderBill]          
(
	@chvOperatorID  	VARCHAR(200),
	@BillNumberID VARCHAR(200),
	@BillType VARCHAR(200)=''
)
--@encode$--
AS
SET NOCOUNT ON 

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype 
(
	TypeID		VARCHAR(50),
	UserCode	VARCHAR(200),
	FullName VARCHAR(200)
)
INSERT INTO #Ptype(TypeId,UserCode,FullName) 
SELECT P.TypeId,p.UserCode,p.FullName
FROM ptype p
INNER JOIN  dbo.F_BaseGetManPTypeAll(@chvOperatorID)P1 ON P.typeId=P1.TypeId 

CREATE TABLE #PrintRecord( 
 billnumberid  NUMERIC(10,0),
 PrintCount  int
)
INSERT INTO #PrintRecord
        ( billnumberid, PrintCount )
SELECT BillNumberId,SUM(PrintCount) FROM dbo.PrintRecord WHERE BillType=313 GROUP BY BillNumberId

CREATE TABLE #order
( orderid INT)
INSERT INTO #order
        ( orderid )
SELECT OrderID FROM dbo.PT_Combin_SaleBill WHERE BillNumberId=@BillNumberID
CREATE TABLE #orderbill
( OrderBillId NUMERIC(18,0))
INSERT INTO #orderbill
        ( OrderBillId )
SELECT billNumberID FROM dbo.PT_Combin_OrderBill WHERE OrderID IN (SELECT orderid FROM #order)


DECLARE @SQL VARCHAR(MAX)
SET @SQL =  'SELECT	
						DISTINCT(a.BillNumberID),
						CONVERT(VARCHAR(10),a.ReachDate,120) AS ReachDate ,
						CONVERT(VARCHAR(10),a.BillDate,120) AS BillDate ,
						a.checktime,
						a.BillCode,
						a.etypeid AS etypeid,
						a.DealBTypeID,
						a.btypeid as btypeid,
						states.StateName,
						a.orderstate,
						a.CustomerTotal, 
						a.NCustomerTotal,
						Convert( NUMERIC(24, 10) ,isnull(O.TotalQty,0)) as OrderQty,
						Convert( NUMERIC(24, 10) ,isnull(O.TotalMoney,0)) as OrderMoney,
						Convert( NUMERIC(24, 10) ,isnull(O.ReachQty,0)) AS ReachQty, /*已发货数量 || 已到货数量 */
						O.locknumber as locknumber,/*已锁定数量*/
						Convert( NUMERIC(24, 10) ,O.ReachMoney) AS  ReachMoney, /*已发货金额 || 已到货金额*/
						NoReachQty=Convert( NUMERIC(24, 10) ,A.TotalQty-ISNULL(O.ReachQty,0)),
						NoReachMoney=Convert( NUMERIC(24, 10) ,A.TotalMoney)-Convert( NUMERIC(24, 10) ,O.ReachMoney),
						a.Comment,
						a.BillOver AS IFStop,
						a.Billtype,
						A.stypeid,
						a.checke,
						case WHEN a.isyapi=1 THEN ''云分销订单'' ELSE ''正常订单'' END AS type,
						a.isyapi,
						CASE
							WHEN ISNULL(AB.CheckState,'''') = '''' THEN ''原始单据''
							ELSE AB.CheckState
						END AS CheckState,
						AC.CId AS accrencyid,
						AC.FullName AS accrencyname,
						a.dtypeid,
						a.totalinmoney,
						a.Ntotalinmoney,
						isnull(pri.PrintCount,0)as printcount,
						SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
						SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
						SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head
				
               	FROM 	OrderIndex a 
               			LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
               			
               			INNER JOIN (	/*状态集合*/
               							SELECT	StateName = case dbo.F_GetCombinOrderState(BillNumberID,313)  
               												when ''1'' then ''已引用未完成''
															when ''2'' then ''已完成''
															when ''4'' then ''未引用''
															else '''' end ,
												billnumberid 
												FROM dbo.OrderIndex 
						
               						) states  ON a.billnumberid=states.billnumberid
                   '
SET @sql=@sql+'  left join #PrintRecord pri on  a.billnumberid=pri.billnumberid '  
SET @SQL=@SQL+'    LEFT JOIN Ac_Currency AC ON AC.CId=a.CID  
	INNER JOIN 
	(
		SELECT 	A.BillNumberID,
		Convert( NUMERIC(24, 10) ,sum(isnull(a.Qty,0))) AS TotalQty,
		Convert( NUMERIC(24, 10) ,ISNULL(SUM(a.Total),0)) AS  TotalMoney  ,
		Convert( NUMERIC(24, 10) ,sum(isnull(a.ReachQty,0))) AS ReachQty,
		Convert( NUMERIC(24, 10) ,sum(isnull(a.ReachTaxTotal,0))) AS  ReachMoney  ,
		(select sum(isnull(LockNumber,0)) from PT_Combin_OrderBillDetail where BillNumberID = A.BillNumberID) as locknumber
		FROM dbo.PT_Combin_OrderBill A '

SET @SQL =@SQL+'  WHERE 1=1 '	
SET @SQL =@SQL+' AND A.ptypeid IN (SELECT typeid AS CombinationProductPtypeId FROM #PType)'
SET @SQL=@SQL+	'		
							/*剔除 委托代销发货单 草稿*/
							AND NOT EXISTS 
										 (	
											SELECT aa.OrderID
											FROM CommissionBill aa 
											INNER JOIN BillIndex b ON aa.BillNumberId=b.BillNumberId 
											WHERE b.billtype=140 AND b.draft=1 AND aa.OrderID=A.OrderID
											AND NOT EXISTS( SELECT 1 FROM PT_Combin_OrderBillDetail WHERE OrderID=aa.OrderID)
										  ) 		
										  	
							GROUP BY
												A.BillNumberID		
						 )O ON a.billNumberId=O.billNumberID '
SET @SQL = @SQL + ' LEFT JOIN (
											SELECT	A.BillNumberId,
													CASE A.IfAudit
														WHEN 0 THEN ''待审核单据''
														WHEN 1 THEN ''审核通过单据''
														ELSE ''审核不通过单据''
													END AS CheckState
											FROM	AuditingBill A
											INNER JOIN AuditingFlowSet F ON A.AuditingId = F.AuditingId AND F.BillType = 313
											WHERE	A.BillIndexType = 0
									   )AB ON AB.BillNumberId = A.BillNumberId '
SET @SQL = @SQL + ' WHERE a.billnumberid IN (select OrderBillId from #orderbill) '

--PRINT @SQL
EXEC(@SQL)

DROP TABLE #PrintRecord,#Ptype,#order,#orderbill



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_QueryPTypeBaseInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_QueryPTypeBaseInfo]
GO

/*
By：Haiyang, Li
Date：2015-06-12
Description：商品基本信息查询, 
*/
CREATE PROCEDURE [dbo].[GP_QueryPTypeBaseInfo]
(
  @PTypeId VARCHAR(50) 	-- 商品ID
)
--@encode$--
AS 
    SET NOCOUNT ON 
    SELECT  P.typeid ,
            P.usercode ,
            P.FullName AS ptypefullname , --P.Name, P.Standard, P.Type, P.Area, -- 基本信息
            P.customitemid ,
            P.customitemname ,
            P.customitemfrom , -- 自由项
            P.ifusegoodsnum , -- 是否启用批号
            P.IfSerial, -- 是否启用序列号标识
            P.baseunitid ,
            U.FullName AS baseunit , --基本单位
            P.assistantunitid ,
            U2.FullName AS assistantunit , -- 浮动单位
            U3.rate
    FROM    ( SELECT    typeId ,
                        UserCode ,
                        FullName , --Name, Standard, Type, Area, -- 基本信息
                        customitemid ,
                        customitemname ,
                        customitemfrom ,  -- 自由项
                        ifusegoodsnum ,		-- 是否采用严格启用批号
                        baseUnitId ,			-- 基本单位id
                        AssistantUnitId,		-- 浮动单位id
                        IfSerial				-- 是否启用序列号标识
              FROM      dbo.ptype
              WHERE     typeId = @PTypeId
            ) P
            INNER JOIN dbo.PType_Units U ON P.baseUnitId = U.UnitsId
            LEFT JOIN dbo.PType_Units U2 ON P.AssistantUnitId = U2.UnitsId
            LEFT JOIN dbo.PType_Units_Ext U3 ON p.AssistantUnitId = U3.UnitsId
                                                 AND P.typeId = U3.PtypeID
            
   
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_QueryPtypeID]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_QueryPtypeID];
GO

/*
	作者:颜熙
	日期:2017-03-23
	描述:查询过账单据包含的商品id
*/
CREATE  PROCEDURE Gp_QueryPtypeID
( 
	@billIDs VARCHAR(MAX) --billnumberid
)
AS
    --SET NOCOUNT ON;
    BEGIN
		DECLARE @count INT 
		CREATE TABLE #BillName (billname VARCHAR(100),ID INT IDENTITY(1,1)) 
		CREATE TABLE #PtypeTemp (TypeId VARCHAR(50)) 
		INSERT INTO #BillName(billname) SELECT DISTINCT detailTable FROM dbo.BillName WHERE Billtype IN  (SELECT DISTINCT BillType FROM dbo.BillIndex WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@billIDs,',')))
		SELECT @count = COUNT(*) FROM #BillName
		IF @count >= 1
		BEGIN
		DECLARE @n INT=1 ,@tablename VARCHAR(100),@sql NVARCHAR(500)
		WHILE(@n<=@count)
		BEGIN
		SELECT @tablename = billname FROM #BillName WHERE ID = @n
		IF EXISTS(SELECT 1 FROM SysColumns WHERE ID=OBJECT_ID(@tablename,N'U') AND Name='Ptypeid')
		BEGIN 
		SET @sql = 'INSERT INTO #PtypeTemp SELECT Ptypeid FROM '+ @tablename+' WHERE billnumberid in (select * from f_split(@billIDs,'',''))'  
		EXEC SP_EXECUTESQL @sql, N'@billIDs VARCHAR(MAX)',@billIDs;
		END 
		SET @n=@n+1
		END 
		END 
		SELECT DISTINCT P.TypeId FROM #PtypeTemp INNER JOIN PTYPE P ON P.typeId = #PtypeTemp.TypeId WHERE P.WdSyncFlag = 1
		DROP TABLE #BillName
		DROP TABLE #PtypeTemp 
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryPTypeInTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryPTypeInTime]
GO









/*
	作者：谢吉康
	日期：2003-12-31
	描述：仓库数量实时查询
*/
CREATE  PROCEDURE GP_QueryPTypeInTime
(
	@OperatorID		VARCHAR(50),	--操作员ID
	@PUserCode 		VARCHAR(8000),	--商品ID
	@KUserCode		VARCHAR(256)	--仓库ID
)
--@encode$--
AS
	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------

	DECLARE @SQL VARCHAR(8000)
BEGIN
	SELECT @SQL = '		
			SELECT	P.UserCode,
					P.FullName,
					P.TypeID,
					P.SonNum,
					P.PrePrice1,
					P.PrePrice2,
					P.PrePrice3,
					P.PrePrice4,
					ISNULL(SUM(A.Qty),0) AS Qty
			FROM 	PType P
			LEFT 	JOIN 
				(
					SELECT 	PTypeID,
						  	KTypeID,
							Qty
					FROM 	GoodsStocks
					WHERE   KTypeID  LIKE '+CHAR(39)+@KUserCode+'%'+CHAR(39)+'
							AND KTypeID  LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
				)A ON P.TypeID=LEFT(A.PtypeID,len(P.Typeid))
			WHERE 	P.SonNum = 0
					AND P.Deleted = 0
					AND P.UserCode IN ('+''''+REPLACE(@PUserCode,',',''',''')+''''+')					
					AND P.TypeID  LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
			GROUP  BY
					P.TypeID,
					P.SonNum,
					P.UserCode,
					P.FullName,
					P.PrePrice1,
					P.PrePrice2,
					P.PrePrice3,
					P.PrePrice4
			ORDER BY P.UserCode'


--		PRINT(@SQL)	
		EXEC(@SQL)
END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryRepairDealPType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryRepairDealPType]
GO
















/*
	作者：谢吉康
	日期：2003-12-24
	描述：商品维修受理查询
*/
CREATE                          PROCEDURE GP_QueryRepairDealPType
(
	@OperatorID		VARCHAR(50),	--操作员ID
	@StartDate		VARCHAR(20),	--开始日期
	@EndDate		VARCHAR(20),	--截止日期
	@PTypeID		VARCHAR(50),	--商品ID
	@ETypeID		VARCHAR(50),	--接件人ID
	@WTypeID		VARCHAR(50),	--维修工程师ID
	@JJDBillCode	VARCHAR(200),	--接件单编号
	@SLDBillCode	VARCHAR(200),	--受理单编号
	@SLDState		VARCHAR(1),		--受理单状态
	@GivePerson		VARCHAR(20),	--送修人
	@Serial			VARCHAR(200),	--序列号
	@ModType		VARCHAR(256),	--维修类型
	@BTypeID		VARCHAR(50),	--往来单位的ID
	@AttType		VARCHAR(50),	--送修属性
	@SPState		VARCHAR(1),		--受理单状态
	@PTypeIDo		VARCHAR(50),	--出库商品ID
	@Enc			VARCHAR(50),	--出库商品条码
	@Com			VARCHAR(50)		--出库商品备注
)
--@encode$--
AS
	SET NOCOUNT ON 
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)
	DECLARE @IfCheck VARCHAR(1)
	DECLARE @Draft VARCHAR(1)
	DECLARE @ModiStat  VARCHAR(1)


	DECLARE @TempPTypeIDo varchar(50)
	SET @TempPTypeIDo=@PTypeIDo
	CREATE TABLE #TEMPBillID
	(
		BillnumberID numeric(18,0)
	)	


	IF @PTypeID = '00000'
		SET @PTypeID = '%'
	IF @PTypeIDo = '00000'
		SET @PTypeIDo = '%'

	IF @BTypeID = '00000'
		SET @BTypeID = '%'

	IF @BTypeID = '00001'
		SET @BTypeID = '%'
	
	IF @ETypeID = '00001'
		SET @ETypeID = '%'
	IF @ModType = 7
		SET @ModType = ''
	IF @AttType = 4
		SET @AttType = ''
	IF @WTypeID ='00001'
		SET @WTypeID ='%'

	SET @PTypeID  = @PTypeID + '%'
	SET @PTypeIDo = @PTypeIDo + '%'
	SET @BTypeID  = @BTypeID + '%'
	SET @ETypeID  = @ETypeID + '%'
	SET @WTypeID  = @WTypeID + '%'

IF @TempPTypeIDo='00000'
	SET @TempPTypeIDo=''
DECLARE @TEMPSQL varchar(2000)
IF @TempPTypeIDo<>'' or  @Enc<>'' or @Com<>''
BEGIN
	IF @TempPTypeIDo<>''
	BEGIN
		SET @TEMPSQL='
			INSERT into #TEMPBillID select distinct BillnumberID from RepairDealDetail 
				where Ptypeid in (SELECT typeID as PtypeID FROM Ptype where typeID LIKE '+ char(39)+@TempPTypeIDo+ '%'+char(39)+' AND EntryCode like '+char(39)+'%'+@Enc+'%'+char(39)+' ) 
				AND Comment like '+char(39)+'%'+@Com+'%'+char(39)+' 
				AND inorout='+char(39)+'O'+char(39)
	END
	ELSE
	BEGIN
		IF @Enc<>'' AND @Com=''
			SET @TEMPSQL='
				INSERT into #TEMPBillID select distinct BillnumberID from RepairDealDetail 
					where Ptypeid in (SELECT typeID as PtypeID FROM Ptype where  EntryCode like '+char(39)+'%'+@Enc+'%'+char(39)+' ) 
					AND inorout='+char(39)+'O'+char(39)
		IF @Enc='' AND @Com<>''
			SET @TEMPSQL='
				INSERT into #TEMPBillID select distinct BillnumberID from RepairDealDetail 
					where  Comment like '+char(39)+'%'+@Com+'%'+char(39)+' 
					AND inorout='+char(39)+'O'+char(39)
		IF @Enc<>'' AND @Com<>''
			SET @TEMPSQL='
				INSERT into #TEMPBillID select distinct BillnumberID from RepairDealDetail 
					where Ptypeid in (SELECT typeID as PtypeID FROM Ptype where EntryCode like '+char(39)+'%'+@Enc+'%'+char(39)+' ) 
					AND Comment like '+char(39)+'%'+@Com+'%'+char(39)+' 
					AND inorout='+char(39)+'O'+char(39)
	END
EXEC(@TEMPSQL)
--PRINT @TEMPSQL
END	

--SELECT * FROM #TEMPBillID

    -- 表repairDeal 字段说明
	--	EtypeID 经手人
	--	EtypeID1 维修工程师
	--	EtypeID2   检测划价人 
DECLARE @SQL_WHERE varchar(2000)
SET @SQL_WHERE= ''
SET @SQL_WHERE = @SQL_WHERE +' AND (bil.ktypeID like '+char(39)+ @MKtypeid +'%'+char(39) + ' OR bil.KtypeID ='+char(39)+''+char(39) +')'
SET @SQL_WHERE = @SQL_WHERE +' AND (bil.ktypeID2 like '+char(39)+ @MKtypeid +'%'+char(39) + ' OR bil.KtypeID2 ='+char(39)+''+char(39) +')'


IF @SLDState = 0 							--草稿单据
	BEGIN
		SELECT @SQL = '
			SELECT	
					R.BillNumberID,
					R.BillDate,
					R.BillCode,
					P.UserCode,
					P.FullName AS PFullName,
					A.Serial,
					A.RepairType AS AttType,
					BFullname = (SELECT FullName FROM BType WHERE TypeID = Bil.BTypeID AND SonNum = 0 AND Deleted = 0),
					R.Method AS RepairType,
					RepairName = (SELECT FullName FROM Employee WHERE TypeID = R.ETypeID1 AND SonNum = 0 AND Deleted = 0),
					A.Brief,
					A.EtypeNAME1,
					R.MoneyRepair,
					A.Comment,
					A.Config,
					A.SaleBillID,
					A.Tel,
					A.buyDate,
					R.PayDate,
					R.comment as Comment1,
					A.Fault,
					Bil.Comment as Comment2,
					R.IfPay,
					A.SaleBtypeName as SaleBtypeName
					
			FROM 	RepairEngage A,
					RepairDeal R,
					PType P,
					Employee E,
					BillIndex Bil				
			WHERE 	A.PTypeID = P.TypeID
					AND A.ETypeID1 = E.TypeID
					AND A.BillNumberID = R.EngageBillID
					AND Bil.BillNumberID = R.BillNumberID
					AND E.Deleted = 0
					AND P.Deleted = 0
					AND A.BillDate >='+CHAR(39)+@StartDate+CHAR(39)+'
					AND A.BillDate <='+CHAR(39)+@EndDate+CHAR(39)+'
					AND A.PTypeID LIKE '+CHAR(39)+@PTypeID+'%'+CHAR(39)+'
					--AND R.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'	
					AND R.ETypeID1 LIKE '+CHAR(39)+@WTypeID+'%'+CHAR(39)+'
					AND A.BillCode LIKE '+CHAR(39)+'%'+@JJDBillCode+'%'+CHAR(39)+'	
					AND R.IfCheck = ''f''
					AND R.Draft = 1
					AND R.BillCode LIKE '+CHAR(39)+'%'+@SLDBillCode+'%'+CHAR(39)+'
					AND R.Method LIKE '+CHAR(39)+@ModType+'%'+CHAR(39)+'
					AND A.RepairType LIKE '+CHAR(39)+@AttType+'%'+CHAR(39)+'
					AND A.RedWord = 0
					AND Bil.RedWord = 0
					AND A.EtypeName1 LIKE '+CHAR(39)+'%'+@GivePerson+'%'+CHAR(39)+'
					AND A.Serial LIKE '+CHAR(39)+'%'+@Serial+'%'+CHAR(39)+'
					AND A.PTypeID LIKE '+CHAR(39)+@PTypeID+CHAR(39)+'
					AND (Bil.BTypeID LIKE '+CHAR(39)+@BTypeID+CHAR(39)+')
					AND A.ETypeID1 LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
					AND A.ETypeID1 LIKE '+CHAR(39)+@MEtypeid+'%'+CHAR(39)	
	

			--SELECT @SQL = @SQL + ' ORDER BY R.BillDate'

	END
ELSE 									--已过帐单据
	BEGIN
		SELECT @SQL = '
			SELECT	
					R.BillNumberID,
					R.BillDate,
					R.BillCode,
					P.UserCode,
					P.FullName AS PFullName,
					A.Serial,
					A.RepairType AS AttType,
					BFullname = (SELECT FullName FROM BType WHERE TypeID = Bil.BTypeID AND SonNum = 0 AND Deleted = 0),
					R.Method AS RepairType,
					RepairName = (SELECT FullName FROM Employee WHERE TypeID = R.ETypeID1 AND SonNum = 0 AND Deleted = 0),
					A.Brief,
					A.EtypeNAME1,
					R.MoneyRepair,
					A.Comment,
					A.Config,
					A.SaleBillID,
					A.Tel,
					A.buyDate,
					R.PayDate,
					R.comment as Comment1,
					A.Fault,
					Bil.Comment as Comment2,
					R.IfPay,
					A.SaleBtypeName as SaleBtypeName
			FROM 	RepairEngage A,
					RepairDeal R,
					PType P,
					Employee E,
					BillIndex Bil				
			WHERE 	A.PTypeID = P.TypeID
					AND A.ETypeID1 = E.TypeID
					AND A.BillNumberID = R.EngageBillID
					AND Bil.BillNumberID = R.BillNumberID
					AND E.Deleted = 0
					AND P.Deleted = 0
					AND A.BillDate >='+CHAR(39)+@StartDate+CHAR(39)+'
					AND A.BillDate <='+CHAR(39)+@EndDate+CHAR(39)+'
					AND A.PTypeID LIKE '+CHAR(39)+@PTypeID+'%'+CHAR(39)+'
					--AND R.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'	
					AND R.ETypeID1 LIKE '+CHAR(39)+@WTypeID+'%'+CHAR(39)+'
					AND A.BillCode LIKE '+CHAR(39)+'%'+@JJDBillCode+'%'+CHAR(39)+'	
					AND R.IfCheck = ''t''
					AND R.Draft = 0
					AND R.BillCode LIKE '+CHAR(39)+'%'+@SLDBillCode+'%'+CHAR(39)+'
					AND R.Method LIKE '+CHAR(39)+@ModType+'%'+CHAR(39)+'
					AND A.RepairType LIKE '+CHAR(39)+@AttType+'%'+CHAR(39)+'

					AND A.RedWord = 0
					AND Bil.RedWord = 0
					AND A.EtypeName1 LIKE '+CHAR(39)+'%'+@GivePerson+'%'+CHAR(39)+'
					AND A.Serial LIKE '+CHAR(39)+'%'+@Serial+'%'+CHAR(39)+'
					AND A.PTypeID LIKE '+CHAR(39)+@PTypeID+CHAR(39)+'
					AND (Bil.BTypeID LIKE '+CHAR(39)+@BTypeID+CHAR(39)+' )
					AND A.ETypeID1 LIKE '+CHAR(39)+@ETypeID+CHAR(39)+'
					AND R.ETypeID LIKE '+CHAR(39)+@MEtypeid+'%'+CHAR(39)

			--SELECT @SQL = @SQL + ' ORDER BY R.BillDate'

	END
	IF @TempPTypeIDo<>'' or  @Enc<>'' or @Com<>''
		SELECT @SQL = @SQL +' AND bil.BillnumberID in ( SELECT BillnumberID FROM  #TEMPBillID )'
	IF @SPState <> '2'  --是否取件
		SET @SQL = @SQL + 'AND R.IfPay = '+CHAR(39)+@SPState+CHAR(39)

	SET @SQL = @SQL +@SQL_WHERE
	
	SET @SQL ='
	   SELECT  a.*,
		   isnull(b.CostTotal,0) as CostTotal,
		   isnull(c.CostTotal,0) as CostTotal1 
	   From (' +@SQL+') a LEFT JOIN '
	   +'( SELECT BillnumberID,sum(isnull(CostTotal,0)) as  CostTotal FROM InoutStockTable where billtype ='+char(39)+'157'+char(39)+' AND qty>0 AND billdate>='+char(39)+@StartDate+char(39)+' AND billdate<='+char(39)+@EndDate+char(39)+' GROUP BY BillnumberID) b ON a.BillnumberID=b.BillnumberID 
	   LEFT JOIN ( SELECT BillnumberID,sum(isnull(CostTotal,0)) as  CostTotal FROM InoutStockTable where billtype ='+char(39)+'157'+char(39)+' AND qty<0 AND billdate>='+char(39)+@StartDate+char(39)+' AND billdate<='+char(39)+@EndDate+char(39)+' GROUP BY BillnumberID) c ON a.BillnumberID=c.BillnumberID '
	SELECT @SQL = @SQL + ' ORDER BY a.BillDate'
	-- PRINT(@SQL)
	EXEC(@SQL)
	DROP TABLE #TEMPBillID















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryRepairEngage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryRepairEngage]
GO




















/*
	作者：谢吉康
	日期：2003-12-24
	描述：商品维修接件查询
*/
CREATE          PROCEDURE GP_QueryRepairEngage
(
	@OperatorID		VARCHAR(50),	--操作员ID
	@StartDate		VARCHAR(20),	--开始日期
	@EndDate		VARCHAR(20),	--截止日期
	@PTypeID		VARCHAR(50),	--商品ID
	@ETypeID		VARCHAR(50),	--职员ID
	@BillCode		VARCHAR(200),	--单据编号
	@GivePerson		VARCHAR(20),	--送修人
	@GetPerson		VARCHAR(20),	--终端用户
	@Serial			VARCHAR(256),	--序列号
	@State 			VARCHAR(1),		--状态
    @Summary		VARCHAR(256),	--摘要
    @Remark			VARCHAR(256)	--备注
)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)
	DECLARE @IfCheck VARCHAR(1)
	DECLARE @Draft VARCHAR(1)
	DECLARE @ModiStat  VARCHAR(1)
	
	IF @State = 2
		BEGIN
			SELECT @State = '%'
			SELECT @IfCheck = '%'
			SELECT @Draft = '%'
			SELECT @ModiStat = '%'
		END
	ELSE
		BEGIN
			IF @State = 1 
				BEGIN
					SELECT @IfCheck = 't'
					SELECT @Draft = 0
					SELECT @ModiStat = '3'
				END
			ELSE
				BEGIN
					SELECT @IfCheck = 'f'
					SELECT @Draft = 1
					SELECT @ModiStat = '1'
				END
		END

	IF @PTypeID = '00000'
		SELECT @PTypeID = '%'

	
BEGIN
	SELECT @SQL = '
		SELECT	DISTINCT
				A.BillNumberID,
				A.BillDate,
				A.BillCode,
				A.EtypeName1 AS RepairEType,
				E.FullName AS JJR,
				P.UserCode,
				P.FullName AS PFullName,
				A.Fault,
				A.Comment,
				A.Stat,
				Serial
		FROM 	RepairEngage A,
				PType P,
				Employee E
		WHERE 	A.PTypeID = P.TypeID
				AND A.ETypeID1 = E.TypeID
				AND E.Deleted = 0
				AND P.Deleted = 0
				AND A.BillDate >='+CHAR(39)+@StartDate+CHAR(39)+'
				AND A.BillDate <='+CHAR(39)+@EndDate+CHAR(39)+'
				AND A.IfCheck LIKE '+CHAR(39)+@IfCheck+'%'+CHAR(39)+'
				AND A.Draft  LIKE '+CHAR(39)+@Draft+'%'+CHAR(39)+'
				AND A.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
				AND A.RedWord = 0
				AND A.PTypeID LIKE '+CHAR(39)+@PTypeID+'%'+CHAR(39)+'
				AND A.ETypeID1 LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
				AND A.EtypeName1 LIKE '+CHAR(39)+'%'+@GivePerson+'%'+CHAR(39)+'
				AND A.Buyer LIKE '+CHAR(39)+'%'+@GetPerson+'%'+CHAR(39)+'
				AND A.Serial LIKE '+CHAR(39)+'%'+@Serial+'%'+CHAR(39)+'
				AND A.Brief  LIKE '+CHAR(39)+'%'+@Summary+'%'+CHAR(39)+'
				AND A.Comment LIKE '+CHAR(39)+'%'+@Remark+'%'+CHAR(39)+'
				AND (A.Stat  LIKE '+CHAR(39)+@State+'%'+CHAR(39)+' OR A.Stat LIKE '+CHAR(39)+@ModiStat+'%'+CHAR(39)+')
				AND A.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
				AND A.ETypeID1 LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
		ORDER BY A.BillDate ASC
				
				'

		--PRINT(@SQL)
		EXEC(@SQL)
END




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryRepairEngagePType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryRepairEngagePType]
GO



















/*
	作者：谢吉康
	日期：2003-12-24
	描述：维修商品查询

	修改日期：2004-08-18
	修改作者：谢吉康
	修改原因：去掉一个查询备注和摘要的Left Join  LN100
*/
CREATE                PROCEDURE GP_QueryRepairEngagePType
(
	@OperatorID 	VARCHAR(50),	--操作员的ID
	@StartDate	VARCHAR(50),		--开始日期
	@EndDate	VARCHAR(50),		--结束日期
	@PtypeID	VARCHAR(50),		--商品的ID
	@EtypeID	VARCHAR(50),		--职员的ID
	@KtypeID	VARCHAR(50),		--仓库的ID
	@KtypeID1	VARCHAR(50),		--仓库的ID
	@SortFild	VARCHAR(50),		--排序字段
	@SortKind	INT,				--排序方式   0.升序  1.倒序
	@QueryType  INT,				--0.全部维修类型
	@BillType	INT,				--单据的类型
	@Summary	VARCHAR(100),		--摘要
	@Comment	VARCHAR(100)		--备注
)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)	--树型结果
	DECLARE @PTypeIDmx VARCHAR(50)
	DECLARE @PsonNum INT

	SELECT @PsonNum = SonNum FROM PType WHERE TypeID = @PTypeID AND Deleted = 0
	
	IF @KTypeID = '00000'
		SELECT @KTypeID = '%'

	IF @KTypeID1 = '00000'
		SELECT @KTypeID1 = '%'

	IF @PTypeID = '00000'
		SELECT @PTypeIDmx = '%'
	ELSE
		SELECT @PTypeIDmx = @PTypeID


BEGIN	
	SELECT @SQL='
		SELECT	a.typeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				ISNULL(SUM(b.InQty),0) AS InQty,
				ISNULL(SUM(b.OutQty),0) AS OutQty
		FROM	PType a	
		LEFT JOIN 
			(
				SELECT	B.PTypeID,
						ISNULL(SUM(B.Qty),0) AS InQty,
						0 As OutQty
				FROM 	RepairDeal A,
						RepairDealDetail B,
						BillIndex Bil,
						RepairEngage R
				WHERE 	A.BillNumberID = B.BillNumberID
						AND A.BillNumberID = Bil.BillNumberID
						AND R.BillNumberID = A.EngageBillID
						AND Bil.IfCheck = ''t''
						AND A.Draft = 0
						AND Bil.RedWord =0 
						AND B.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@KTypeID1+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND R.Brief LIKE '+CHAR(39)+'%'+@Summary+'%'+CHAR(39)+'
						AND R.comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)+'
						AND bil.Billdate>='+char(39)+@StartDate+char(39)+'
						AND bil.Billdate<='+char(39)+@EndDate+char(39)+'
						AND B.InOrOut =''I'' 
				GROUP BY
						B.PTypeID
				UNION 
				SELECT	B.PTypeID,
						0 AS InKQty,
						ISNULL(SUM(B.Qty),0) As OutQty
				FROM 	RepairDeal A,
						RepairDealDetail B,
						BillIndex Bil,
						RepairEngage R
				WHERE 	A.BillNumberID = B.BillNumberID
						AND A.BillNumberId = Bil.BillNumberId
						AND R.BillNumberID = A.EngageBillID
						AND Bil.IfCheck = ''t''
						AND A.Draft = 0
						AND Bil.RedWord =0 
						AND B.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						AND A.KTypeID1 LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+'
						AND A.KTypeID1 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND R.Brief LIKE '+CHAR(39)+'%'+@Summary+'%'+CHAR(39)+'
						AND R.comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)+'
						AND bil.Billdate>='+char(39)+@StartDate+char(39)+'

						AND bil.Billdate<='+char(39)+@EndDate+char(39)+'
						AND B.InOrOut =''O''
				GROUP BY
						B.PTypeID
			)b ON a.TypeID=LEFT(b.PtypeID,len(a.Typeid))'


			IF @PsonNum > 0
				SELECT @SQL = @SQL + ' WHERE a.ParID = '+CHAR(39)+@PTypeID+CHAR(39)
			ELSE
				SELECT @SQL = @SQL + ' WHERE a.TypeID = '+CHAR(39)+@PTypeID+CHAR(39)

			SELECT @SQL = @SQL +'
				AND a.deleted = 0
				AND a.TypeId <> ''00000''
				AND a.TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
			GROUP BY
				a.TypeID,
				a.UserCode,
				a.FullName,
				a.SonNum
			ORDER BY a.UserCode'


		--Print(@SQL)
		EXEC(@SQL)

END





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryRepairEngagePTypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryRepairEngagePTypeDetail]
GO














/*
	作者：谢吉康
	日期：2003-12-24
	描述：商品维修查询明细表
*/
CREATE             PROCEDURE GP_QueryRepairEngagePTypeDetail
(
	@OperatorID VARCHAR(50),		--操作员的ID
	@StartDate	VARCHAR(50),		--开始日期
	@EndDate	VARCHAR(50),		--结束日期
	@PtypeID	VARCHAR(50),		--商品的ID
	@EtypeID	VARCHAR(50),		--职员的ID
	@KtypeID	VARCHAR(50),		--仓库的ID
	@KtypeID1	VARCHAR(50),		--仓库的ID
	@SortFild	VARCHAR(50),		--排序字段
	@SortKind	INT,				--排序方式   0.升序  1.倒序
	@QueryType  INT,				--0.全部维修类型
	@BillType	INT,				--单据的类型
	@WhichK     INT,				--更据OutKQty,InKQty的数量来判定哪个仓库的ID有效  0.两个仓库的参数都有效  1.KtypeID有效  2.KtypeID1有效
	@Summary	VARCHAR(100),		--摘要
	@Comment	VARCHAR(100)		--备注
)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)
	
	IF @KTypeID = '00000'
		SELECT @KTypeID = '%'

	IF @KTypeID1 = '00000'
		SELECT @KTypeID1 = '%'
	
BEGIN
	SELECT @SQL = '
		SELECT	A.BillNumberID,
				A.BillCode,
				A.BillDate,
				E.FullName AS EFullName,
				P.UserCode,
				P.FullName AS PFullName,			
				B.CostPrice,
				A.Comment,
				ISNULL(SUM(Case B.InOrOut when ''I'' then B.Qty else 0 end),0) AS IQty,
				ISNULL(SUM(Case B.InOrOut when ''O'' then B.Qty else 0 end),0) AS OQty,
				A.KTypeID1 AS OutK,
				A.KTypeID2 AS InK
		FROM 	RepairDeal A,
				RepairDealDetail B,
				PType P,
				Employee E,
				BillIndex Bil,
				RepairEngage R
		WHERE   A.BillNumberID = B.BillNumberID
				AND A.BillNumberId = Bil.BillNumberId
				AND R.BillNumberID = A.EngageBillID
				AND P.TypeID = B.PTypeID
				AND E.TypeID = A.ETypeID
				AND Bil.IfCheck = ''t''
				AND Bil.RedWord = 0
				AND A.Draft = 0
				AND B.PTypeID LIKE '+CHAR(39)+@PTypeID + '%' + CHAR(39)+'
				AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID + '%' + CHAR(39)+'
				AND A.ETypeID LIKE '+CHAR(39)+@ETypeID + '%' + CHAR(39)+'
				AND R.Brief LIKE '+CHAR(39)+'%'+@Summary+'%'+CHAR(39)+'
				AND R.comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)+'
				AND Bil.Billdate>='+char(39)+@StartDate+char(39)+'
				AND Bil.Billdate<='+char(39)+@EndDate+char(39)+'
				AND A.ETypeID LIKE '+CHAR(39)+@METypeID + '%' + CHAR(39)
		IF  @WhichK=1	--判断仓库的有效性
			SELECT @SQL = @SQL +'	
				AND A.KTypeID1 LIKE '+CHAR(39)+@KTypeID + '%' + CHAR(39)+'
				AND B.InOrOut = ''O''
				AND A.KTypeID1 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)
		ELSE
			BEGIN
				IF  @WhichK=2 
					SELECT @SQL = @SQL + '
						AND A.KTypeID2 LIKE '+CHAR(39)+@KTypeID1+ '%'+CHAR(39)+'
						AND B.InOrOut = ''I''
						AND A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)
				ELSE
					SELECT @SQL = @SQL + '
						AND (( A.KTypeID1 LIKE '+CHAR(39)+@KTypeID + '%' + CHAR(39)+'	
						AND  A.KTypeID1 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+' 
						AND b.InorOut=''O'') OR

						(A.KTypeID2 LIKE '+CHAR(39)+@KTypeID1+ '%'+CHAR(39)+'						
						AND  A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39) +'
						AND b.InorOut=''I''))'

			END

		SELECT @SQL = @SQL + ' 
			GROUP BY
				A.BillNumberID,
				A.BillCode,
				A.BillDate,
				A.Comment,
				E.FullName,
				P.UserCode,
				P.FullName,			
				B.CostPrice,
				A.KTypeID1,
				A.KTypeID2'

			--构造排序字段  
			IF @SortFild=''
				SELECT @SQL=@SQL+' Order By A.BillDate'
			ELSe
				BEGIN
					IF @SortFild='BillDate'		SELECT @SQL=@SQL+' Order By A.BillDate' 		--单据日期
					IF @SortFild='BillCode'		SELECT @SQL=@SQL+' Order By A.BillCode' 		--单据编号
					IF @SortFild='EtypeID'		SELECT @SQL=@SQL+' Order By eFullName' 		--经手人
					IF @SortFild='PUserCode'	SELECT @SQL=@SQL+' Order By P.UserCode' 		--商品编号
					IF @SortFild='PFullName'	SELECT @SQL=@SQL+' Order By P.FullName' 		--商品名称
					IF @SortFild='OQty'			SELECT @SQL=@SQL+' Order By OQty'	 		--出库数量
					IF @SortFild='IQty'			SELECT @SQL=@SQL+' Order By IQty'	 		--入库数量
					IF @SortFild='CostTotal'	SELECT @SQL=@SQL+' Order By B.CostTotal' 		--成本金额
					IF @SortFild='CostPrice'	SELECT @SQL=@SQL+' Order By B.CostPrice' 		--单价
					IF @SortFild='KtypeID'		SELECT @SQL=@SQL+' Order By A.KtypeID1' 		--调出仓库
					IF @SortFild='KtypeID1' 	SELECT @SQL=@SQL+' Order By A.KtypeID2' 		--调入仓库
				END
			--构造排序的方式
			IF @SortKind=0
				SELECT @SQL=@SQL+' ASC'	--升序
			ELSE
				SELECT @SQL=@SQL+' DESC'	--降序


	
		--PRINT(@SQL)
		EXEC(@SQL)
END















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_QueryRepairEngagePTypeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_QueryRepairEngagePTypeLine]
GO















/*
	作者：谢吉康
	日期：2003-12-24
	描述：维修商品线性查询
*/
CREATE             PROCEDURE GP_QueryRepairEngagePTypeLine
(
	@OperatorID 	VARCHAR(50),	--操作员的ID
	@StartDate	VARCHAR(50),		--开始日期
	@EndDate	VARCHAR(50),		--结束日期
	@PtypeID	VARCHAR(50),		--商品的ID
	@EtypeID	VARCHAR(50),		--职员的ID
	@KtypeID	VARCHAR(50),		--仓库的ID
	@KtypeID1	VARCHAR(50),		--仓库的ID
	@SortFild	VARCHAR(50),		--排序字段
	@SortKind	INT,				--排序方式   0.升序  1.倒序
	@QueryType  INT,				--0.全部维修类型
	@BillType	INT,				--单据的类型
	@Summary	VARCHAR(100),		--摘要
	@Comment	VARCHAR(100)		--备注
)
--@encode$--
AS
	SET NOCOUNT ON 
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
	
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @SQL VARCHAR(8000)	--树型结果
	DECLARE @PTypeIDmx VARCHAR(50)
	DECLARE @PsonNum INT

	SELECT @PsonNum = SonNum FROM PType WHERE TypeID = @PTypeID AND Deleted = 0
	
	IF @KTypeID = '00000'
		SELECT @KTypeID = '%'

	IF @KTypeID1 = '00000'
		SELECT @KTypeID1 = '%'

	IF @PTypeID = '00000'
		BEGIN
			SELECT @PTypeID = '%'
			SELECT @PTypeIDmx = '%'
		END
	ELSE
		SELECT @PTypeIDmx = @PTypeID


BEGIN	
	SELECT @SQL='
		SELECT	a.typeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				ISNULL(SUM(b.InQty),0) AS InQty,
				ISNULL(SUM(b.OutQty),0) AS OutQty
		FROM	PType a
		LEFT JOIN 
			(
				SELECT	B.PTypeID,
						ISNULL(SUM(B.Qty),0) AS InQty,
						0 As OutQty
				FROM 	RepairDeal A,
						RepairDealDetail B,
						BillIndex Bil,
						RepairEngage R
				WHERE 	A.BillNumberID = B.BillNumberID
						AND A.BillNumberId = Bil.BillNumberId
						AND R.BillNumberID = A.EngageBillID
						AND Bil.IfCheck = ''t''
						AND A.Draft = 0
						AND Bil.RedWord =0 
						AND B.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@KTypeID1+'%'+CHAR(39)+'
						AND A.KTypeID2 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND R.Brief LIKE '+CHAR(39)+'%'+@Summary+'%'+CHAR(39)+'
						AND R.comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)+'
						AND Bil.Billdate>='+char(39)+@StartDate+char(39)+'
						AND Bil.Billdate<='+char(39)+@EndDate+char(39)+'
						AND B.InOrOut =''I''
				GROUP BY
						B.PTypeID
				UNION 
				SELECT	B.PTypeID,
						0 AS InKQty,
						ISNULL(SUM(B.Qty),0) As OutQty
				FROM 	RepairDeal A,
						RepairDealDetail B,
						BillIndex Bil,
						RepairEngage R
				WHERE 	A.BillNumberID = B.BillNumberID
						AND A.BillNumberId = Bil.BillNumberId
						AND R.BillNumberID = A.EngageBillID
						AND Bil.IfCheck = ''t''
						AND A.Draft = 0
						AND Bil.RedWord =0 
						AND B.PTypeID LIKE '+CHAR(39)+@PTypeIDmx+'%'+CHAR(39)+'
						AND B.PTypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@ETypeID+'%'+CHAR(39)+'
						AND A.ETypeID LIKE '+CHAR(39)+@METypeID+'%'+CHAR(39)+'
						AND A.KTypeID1 LIKE '+CHAR(39)+@KTypeID+'%'+CHAR(39)+'
						AND A.KTypeID1 LIKE '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						AND R.Brief LIKE '+CHAR(39)+'%'+@Summary+'%'+CHAR(39)+'
						AND R.comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)+'
						AND Bil.Billdate>='+char(39)+@StartDate+char(39)+'
						AND Bil.Billdate<='+char(39)+@EndDate+char(39)+'
						AND B.InOrOut =''O''
				GROUP BY
						B.PTypeID
			)b ON a.TypeID=b.PtypeID
		WHERE 	a.TypeID LIKE '+CHAR(39)+@PTypeID+'%'+CHAR(39)+'
				AND a.deleted = 0
				AND a.SonNum = 0
				AND a.TypeId <> ''00000''
				AND a.TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
			GROUP BY
				a.TypeID,
				a.UserCode,
				a.FullName,
				a.SonNum
			ORDER BY a.UserCode'


		--Print(@SQL)
		EXEC(@SQL)

END

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QuerySearReportPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QuerySearReportPtype]
GO














/****** Object:  Stored Procedure dbo.Gp_QuerySearReportPtype    Script Date: 2002-6-20 10:14:51 ******/

CREATE  PROCEDURE [Gp_QuerySearReportPtype] 
(
 @BeginDate  varchar(25),
 @EndDate  varchar(25),
 @BtypeId  varchar(25),
 @EtypeId  varchar(25),
 @KtypeId  varchar(25),
 @OrderBy  varchar(50) = 'pUser'
)
--@encode$--
AS
SET NOCOUNT ON 
if @BtypeId='00000' select @BtypeId=''
if @BtypeId='00001' select @BtypeId=''
declare @cz_query varchar(8000)
declare @Sql varchar (8000)
select @cz_Query=''
--日期限制
if (rtrim(@begindate) <>'' and rtrim(@enddate) <>'')
 select @cz_Query=@cz_query+' i.billdate>='+char(39)+@begindate+char(39)+' and i.billdate<='+char(39)+@enddate+char(39)+' and '
if rtrim(@etypeid) <> ''
 select @cz_query=@cz_query+' i.etypeid='+char(39)+@etypeid+char(39)+' and '
if rtrim(@ktypeid) <>'' 
 select @cz_query=@cz_query+' i.ktypeid='+char(39)+@ktypeid+char(39)+' and '
if rtrim(@btypeid) <> '' 
 select @cz_query=@cz_query+' left(i.btypeid,len('+char(39)+@btypeid+char(39)+'))='+char(39)+@btypeid+char(39)+' and '
select @cz_query =@cz_query+' i.ifcheck=''t'' and i.draft=''0'' and' 
select @cz_query=substring(@cz_query,1,len(@cz_query)-4)
select @Sql ='select p.UserCode As pUser,p.fullname As pFull,p.Unit1 As pUnit,Sum(s.Qty) As Qty,Sum(s.TaxTotal) As TaxToTal
from BillIndex i
  inner join SaleBill s on s.BillNumberId=i.BillNumberId
  inner join Ptype p on p.TypeId = s.ptypeId
'
--  inner join Btype b on b.TypeId = i.btypeId
if rtrim(@cz_query) <> ''
select @Sql=@Sql+' where '+@cz_query 
select @Sql=@Sql+' Group by p.UserCode,p.fullname,p.Unit1'
if rtrim(@orderby) <> ''
select @Sql=@Sql+' order by '+@orderby
--print @sql
exec (@Sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QuerySerialBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QuerySerialBill]
GO

/*
	作者：徐辉
	日期：2011-04-25
	描述：权限修改

	卢春 2006-03-14 序列号模糊查找大数据量提速
*/
CREATE               PROCEDURE Gp_QuerySerialBill
( 
	@OperatorId		VARCHAR(100),
	@Serial    		VARCHAR(1000),
	@querytype   	INT,  			--是否模糊查找  1.是  0.精确查找
	@ETypeId		VARCHAR(MAX) = '',
	@DTypeId		VARCHAR(MAX) = '',
	@STypeId		VARCHAR(MAX) = '',
	@dealbtypeid		VARCHAR(MAX) = '',
	@KTypeId		VARCHAR(MAX) = '',
	@PTypeId		VARCHAR(MAX) = ''
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
create table #temp
(
	sid  int identity(1,1),
	checke VARCHAR(200),
	ID INT,
	billnumberID NUMERIC(10,0),
	BillDate DATETIME,
	BillCode	VARCHAR(100),
	BillType	INT,
	Comment		VARCHAR(500),
	Explain		VARCHAR(500),
	RedWord		INT,
	EtypeId		VARCHAR(50),
	StypeId		VARCHAR(50),
	KtypeId		VARCHAR(50),
	dealbtypeid		VARCHAR(50),
	PtypeId		VARCHAR(50)
)
IF ISNULL(@Serial,'')='' --没有录入序列号条件，则返回空表结构
BEGIN
	SELECT * FROM #temp
	RETURN
END 
	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT a.TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorId) a INNER JOIN dbo.ptype b ON a.TypeId=b.typeId WHERE b.IsService=0

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorId)
IF @dealbtypeid = ''
	INSERT INTO #GetManBTypeId(TypeId)VALUES('')

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorId)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorId)
IF @KTypeId = ''
BEGIN
	INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')
	INSERT INTO #GetManKTypeId(TypeId)VALUES('')
END

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

CREATE CLUSTERED INDEX CIX_BID ON #GetManETypeId(typeid)	
CREATE CLUSTERED INDEX CIX_BID ON #GetManPTypeId(typeid)	
CREATE CLUSTERED INDEX CIX_BID ON #GetManBTypeId(typeid)
CREATE CLUSTERED INDEX CIX_BID ON #GetManKTypeId(typeid)	
CREATE CLUSTERED INDEX CIX_BID ON #GetManSTypeId(typeid)	
CREATE CLUSTERED INDEX CIX_BID ON #GetManDTypeId(typeid)	

DECLARE @SQL VARCHAR(8000)
--自定义行数
DECLARE @uCount int
SELECT @uCount = ISNULL(UserDeRowCount,0) FROM LoginUser WHERE ETypeId = @OperatorId
IF @uCount = 0 SET @uCount = 14


SET @SQL = '
		SELECT 	a.*,
				SysDiy1_head,
				SysDiy2_head,
				SysDiy3_head,
				SysDiy4_head, 
				SysDiy5_head,
				SysDiy6_head,
				SysDiy7_head,
				SysDiy8_head,
				SysDiy9_head,
				SysDiy10_head,
				SysDiy11_head,
				SysDiy12_head,
				SysDiy13_head,
				SysDiy14_head,
				SysDiy15_head,
				SysDiy16_head  
		FROM (
				SELECT	
						bi.checke,  
						bi.[id],
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						bi.BillType,
						bi.Comment,
						bi.explain,
						Bi.RedWord,
						bi.etypeid,
						bi.stypeid,
						CASE 
								WHEN ISNULL(InOut.InKtypeID,'''') <> '''' THEN InOut.InKtypeID
								ELSE InOut.OutKtyeID
							END AS KTypeId,
						bi.dealbtypeid as dealbtypeid,
						inout.PtypeId
				FROM 	BillIndex Bi
				INNER JOIN gp_inoutPtypeSerial InOut ON InOut.BillNumberId = Bi.BillNumberId
				INNER JOIN #GetManPTypeId P ON P.TypeId = InOut.PtypeID
				INNER JOIN #GetManDTypeId D ON D.TypeId = Bi.DTypeId
				INNER JOIN #GetManSTypeId S ON S.TypeId = Bi.STypeId
				INNER JOIN #GetManETypeId E ON E.TypeId = Bi.ETypeId
				INNER JOIN #GetManBTypeId B ON B.TypeId = Bi.dealbtypeid					
				WHERE   Bi.IfCheck = ''t''
						AND InOut.BillType=Bi.BillType
						AND Bi.RedWord = 0
						AND Bi.BillType NOT IN (71,72,87,88,203) '
IF NOT (@KTypeId = '' AND @MKtypeid = '00000')
	SET @SQL = @SQL + ' AND (InOut.InKtypeID IN (SELECT * FROM #GetManKTypeId) OR InOut.OutKtyeID IN (SELECT * FROM #GetManKTypeId)) '
IF @querytype = '1'
				SET @SQL = @SQL + ' AND InOut.Serial LIKE ''%' + @Serial + '%'''
			ELSE
				SET @SQL = @SQL + ' AND InOut.Serial =''' + @Serial + ''''
				
set @SQL=@SQL+'	UNION ALL
				SELECT	 
						Li.checke,  
						Li.[OrderID] as [id],
						Li.BillNumberId,
						Li.BillDate,
						Li.BillCode,
						Li.BillType,
						Li.Comment,
						Li.explain,
						Li.RedWord,
						li.etypeid,
						li.stypeid,
						li.ktypeid,
						li.dealbtypeid,
						inout.PtypeId
				FROM 	LendIndex Li
				INNER JOIN gp_inoutPtypeSerial InOut ON InOut.BillNumberId = li.BillNumberId
				INNER JOIN #GetManDTypeId D ON D.TypeId = Li.DTypeId
				INNER JOIN #GetManSTypeId S ON S.TypeId = Li.STypeId
				INNER JOIN #GetManETypeId E ON E.TypeId = Li.ETypeId			
				INNER JOIN #GetManBTypeId B ON B.TypeId = Li.dealbtypeid
				INNER JOIN #GetManKTypeId K ON K.TypeId = Li.KTypeId
				INNer join #GetManPTypeId p on inout.PtypeID=p.typeid
				WHERE   li.BillType IN (71,72,87,88) 
						AND InOut.BillType=li.BillType '
IF @querytype = '1'
				SET @SQL = @SQL + ' AND InOut.Serial LIKE ''%' + @Serial + '%'''
			ELSE
				SET @SQL = @SQL + ' AND InOut.Serial = '''+ @Serial + ''''
set @SQL=@SQL+'				
				UNION ALL
				--加上序列号调整单的数据
				SELECT	
						bi.checke,  
						null as id,
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						bi.BillType,
						bi.Comment,
						bi.explain,
						Bi.RedWord,
						bi.etypeid,
						bi.stypeid,
						NULL AS ktypeid,
						bi.btypeid as dealbtypeid,
						inout.PtypeId
				FROM 	SerialAdjustIndex Bi
				INNER JOIN gp_inoutPtypeSerial InOut ON InOut.BillNumberId = Bi.BillNumberId
				INNER JOIN #GetManDTypeId D ON D.TypeId = Bi.DTypeId
				INNER JOIN #GetManSTypeId S ON S.TypeId = Bi.STypeId
				INNER JOIN #GetManETypeId E ON E.TypeId = Bi.ETypeId
				INNER JOIN #GetManBTypeId B ON B.TypeId = Bi.btypeid
				INNER JOIN #GetManKTypeId K ON K.TypeId = InOut.inktypeid
				INNer join #GetManPTypeId p on inout.PtypeID=p.typeid					
				WHERE   Bi.IfCheck = ''t''
						AND InOut.BillType=Bi.BillType
						AND Bi.RedWord = 0
						AND InOut.BillType = 203 '
IF @querytype = '1'
				SET @SQL = @SQL + ' AND InOut.Serial LIKE ''%' + @Serial + '%'''
			ELSE
				SET @SQL = @SQL + ' AND InOut.Serial = '''+ @Serial + ''''
set @SQL=@SQL+'         UNION ALL
	                    SELECT	
						bi.checke,  
						0,
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						bi.BillType,
						bi.Comment,
						bi.explain,
						Bi.RedWord,
						bi.ApplyEtypeId,
						bi.stypeid,
						CASE 
								WHEN ISNULL(InOut.InKtypeID,'''') <> '''' THEN InOut.InKtypeID
								ELSE InOut.OutKtyeID
							END AS KTypeId,
						'''',
						inout.PtypeId
				FROM 	PosAllotApplyBillIndex Bi
				INNER JOIN gp_inoutPtypeSerial InOut ON InOut.BillNumberId = Bi.BillNumberId
				INNER JOIN #GetManPTypeId P ON P.TypeId = InOut.PtypeID
				INNER JOIN #GetManDTypeId D ON D.TypeId = Bi.DTypeId
				INNER JOIN #GetManSTypeId S ON S.TypeId = Bi.STypeId
				INNER JOIN #GetManETypeId E ON E.TypeId = Bi.ApplyEtypeId
							
				WHERE   Bi.IfCheck = ''t''
						AND InOut.BillType=Bi.BillType
						AND Bi.RedWord = 0
						AND Bi.BillType  IN (327,328,329) '
IF NOT (@KTypeId = '' AND @MKtypeid = '00000')
	SET @SQL = @SQL + ' AND (InOut.InKtypeID IN (SELECT * FROM #GetManKTypeId) OR InOut.OutKtyeID IN (SELECT * FROM #GetManKTypeId)) '
IF @querytype = '1'
				SET @SQL = @SQL + ' AND InOut.Serial LIKE ''%' + @Serial + '%'''
			ELSE
				SET @SQL = @SQL + ' AND InOut.Serial =''' + @Serial + ''''

set @SQL=@SQL+'	
		) a 
		LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
		
		 ORDER BY a.BillDate'
			
PRINT(@SQL)
EXEC(@sql)
SELECT * FROM  #temp



DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryStockIoutIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryStockIoutIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
仓库出入库单据 调入草稿
*/
CREATE PROCEDURE [dbo].[Gp_QueryStockIoutIndex]
( 
	@MagEType		VARCHAR(50),
	@BillType		VARCHAR(5)='',
	@BeginDate		VARCHAR(25)='',
	@EndDate		VARCHAR(25)='',
	@BillCode		VARCHAR(200)='',
	@EtypeName		VARCHAR(200)='',
	@stypeid		VARCHAR(50),
	@ktypeid		VARCHAR(50),
	@DTypeID  		VARCHAR(100) = '',
	@frombilltype	VARCHAR(50),
	@check			VARCHAR(50),
	@IfAudit		VARCHAR(2)			-- 审核的类型   -1.审核不通过  0.待审核   1.审核通过  2.没有审核  兼容以前草稿  AuditingBill 中的IfAudit
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID VARCHAR(50)
SET @chvOperatorID = @MagEType
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID VARCHAR(50), @chvMBTypeID VARCHAR(50), @chvMBTypeID2 VARCHAR(50), @chvMETypeID VARCHAR(50), @chvMKTypeID VARCHAR(50), @chvMPTypeID VARCHAR(50), @chvMExpense VARCHAR(50), @chvMIncome VARCHAR(50), @chvMCapital VARCHAR(50), @chvMDtypeid VARCHAR(50), @chvMStypeid VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man VARCHAR(1000)
SET @SQL_Man = ''

-- 分支机构
IF @Stypeid<>'' or @chvMStypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END

--仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	IF @BillType in ('418','419','420' )
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType SK ON a.KTypeID = SK.TypeID '
	IF @BillType in ('420')
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType SK2 ON a.KTypeID2 = SK2.TypeID '
	
END

-- 部门
IF @chvMDtypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetaildType FROM F_BaseGetManDetailDType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END

--有审核过账的单据应该加上以下权限控制
DECLARE @re 			int,	-- 修改他人草稿的权限\
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@offset			INT
--IF (@chvOperatorID = '00001')
	--SET @re = 0
--ELSE
--BEGIN	
	SELECT @offset = 135	-- 检查某人是否有查看管辖职员草稿得权限
	EXEC @re = GP_CheckLimit @chvOperatorID,@offset
--END	

-- ******** 权限范围单独处理 - End ********

/*因为仓库出入库单和调拨单的表不一样 所以这里必须定义动态表*/
DECLARE @tablename VARCHAR(50)
IF @BillType IN('418','419')
SET @tablename='FactDepotInOut'
IF @BillType='420'
SET @tablename='FactDepotAllot'
--end

DECLARE @SQL VARCHAR(3000)
SET @SQL = '
	SELECT	distinct a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ktypeid,
			a.ETypeID,
			a.DTypeID,
			a.StypeID,
			a.Explain,
			a.checke,
			a.Comment,
			(select billname from billname where billtype=a.FromBillType) as frombilltype
	FROM	FactIndex a ' + @SQL_Man + '
	INNER JOIN '+@tablename+' O ON A.BILLNUMBERID=O.BILLNUMBERID '
	
--加入审核判断条件
IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType AND IfUse = 1 AND LEFT(AuditingReason,1) <> 1) 	-- 检查单据是否有审核流程
BEGIN
	SET @SQL = @SQL + ' WHERE 1 = 1'
END
ELSE IF  @IfAudit='2' --没有审核
BEGIN
	SET @SQL = @SQL + ' WHERE	NOT EXISTS( SELECT ab.BillNumberID FROM AuditingBill ab WHERE a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 7 )  '
END 
ELSE
BEGIN
	SET @SQL = @SQL + ' WHERE A.BillNumberId IN (SELECT ab.BillNumberID FROM AuditingBill ab WHERE ifAudit = ' + @IfAudit +' AND ab.BillIndexType = 7)'
END
	
	
SET @SQL = @SQL + '	AND a.BillDate >= ''' + @BeginDate + ''' 
					AND a.BillDate <= ''' + @EndDate + '''
					AND a.ifcheck=''f'' 
					AND a.draft=1 
					AND a.redword=0 
					AND a.BillType = ' + @BillType

IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @EtypeName <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EtypeName + ''''
IF @DTypeID <> '' SET @SQL = @SQL + ' AND a.DTypeID=''' + @DTypeID + ''''
IF @stypeid <> '' SET @SQL = @SQL + ' AND a.sTypeID=''' + @stypeid + ''''
IF @frombilltype <> '' SET @SQL = @SQL + ' AND a.frombilltype=''' + @frombilltype + ''''
IF @ktypeid <> '' SET @SQL = @SQL + ' AND a.ktypeid=''' + @ktypeid + ''''
IF @check <> '' SET @SQL = @SQL + ' AND a.checke=''' + @check + ''''
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC, a.BillCode'

PRINT(@SQL)
EXEC (@SQL)

IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMDtypeid  = '-99999' DROP TABLE #F_BaseGetManDetaildType 
IF @Stypeid<>'' or @chvMStypeid<>'00000' DROP TABLE #F_BaseGetManDetailSType



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--SELECT * FROM FactIndex
--SELECT * FROM dbo.FactDepotInOut










SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryStockQuantity]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryStockQuantity]
GO










/*
	描述：实时库存
*/

CREATE PROCEDURE Gp_QueryStockQuantity
(
	@OperatorID		VARCHAR(50),	--操作员ID
	@strPtypeid 	VARCHAR(MAX),	--商品ID
	@strKtypeid		VARCHAR(MAX),	--仓库ID
	@strQty			VARCHAR(MAX),  --单据数量
	@strUnit		VARCHAR(MAX),	--是否使用了双单位
	@stypeid		VARCHAR(50),		--分支机构，查询商品物价信息用
	@cargoidin		VARCHAR(MAX)='',		--货位ID
	@cargofullnamein VARCHAR(MAX)='',		--货位Name
	@outcargoid		VARCHAR(MAX)='',		--货位ID
	@outcargofullname VARCHAR(MAX)='',		--货位Name
	@goodsnumbers     VARCHAR(MAX),
	@ProduceDates     VARCHAR(MAX),
	@ValidDates       VARCHAR(MAX),
	@ItemIDs          VARCHAR(MAX),
    @IsCombineds      VARCHAR(MAX),
    @isap             INT           
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #A
(
	TypeId	varchar(100)
)

CREATE TABLE #Goodsnumbers
(
    nID int identity(1,1),
	number	varchar(100)
)

CREATE TABLE #ProduceDates
(
    nID int identity(1,1),
	pdate	varchar(100)
)

CREATE TABLE #ValidDates 
(
    nID int identity(1,1),
	vdate	varchar(100)
)

CREATE TABLE #ItemIDs
(
    nID int identity(1,1),
	itemid	varchar(100)
)

CREATE TABLE #IsCombineds
(
    nID int identity(1,1),
	iscombined	varchar(100)
)


CREATE TABLE #CargoidIDS
(
nID int identity(1,1),
	Id	varchar(100)
)
CREATE TABLE #CargoidNames
(
nID int identity(1,1),
	Name	varchar(100)
)

CREATE TABLE #outCargoidIDS
(
nID int identity(1,1),
	Id	varchar(100)
)
CREATE TABLE #outCargoidNames
(
nID int identity(1,1),
	Name	varchar(100)
)

CREATE TABLE #B
(
	nID int identity(1,1),
	Qty	 NUMERIC(24, 10) 
)

CREATE TABLE #C
(
	nID 	int identity(1,1),
	UTow	 NUMERIC(24, 10) 
)

CREATE TABLE #K1
(
	nID 	int identity(1,1),
	TypeId	varchar(100)
)

CREATE TABLE #K
(
	TypeId	varchar(100)
)
CREATE TABLE #A1
(
	nID 	int identity(1,1),
	TypeId	varchar(100)
)

INSERT INTO #A1
SELECT	*
FROM 	F_Split(@strPtypeid,'|')

INSERT INTO #Goodsnumbers
SELECT	*
FROM 	F_Split(@Goodsnumbers,'|')

INSERT INTO #ProduceDates
SELECT	*
FROM 	F_Split(@ProduceDates,'|')

INSERT INTO #ValidDates
SELECT	*
FROM 	F_Split(@ValidDates,'|')

INSERT INTO #ItemIDs
SELECT	*
FROM 	F_Split(@ItemIDs,'|')

INSERT INTO #IsCombineds
SELECT	*
FROM 	F_Split(@IsCombineds,'|')

INSERT INTO #CargoidIDS
SELECT	*
FROM 	F_Split(@cargoidin,'|')

INSERT INTO #CargoidNames
SELECT	*
FROM 	F_Split(@cargofullnamein,'|')


INSERT INTO #outCargoidIDS
SELECT	*
FROM 	F_Split(@outcargoid,'|')

INSERT INTO #outCargoidNames
SELECT	*
FROM 	F_Split(@outcargofullname,'|')


INSERT INTO #B
SELECT	ISNULL(A,0)
FROM	F_Split(@strQty,'|')

INSERT INTO #C
SELECT	ISNULL(A,0)
FROM	F_Split(@strUnit,'|')

INSERT INTO #K1
SELECT 	ISNULL(A,0)
FROM	F_Split(@strKTypeId,',')

INSERT INTO #K
SELECT DISTINCT TypeId FROM #K1
INSERT INTO #A
SELECT DISTINCT TypeId FROM #A1


DECLARE @szKTypeId varchar(100)
IF @strKtypeid = ''
	SET @szKTypeId = 'xjkang'
ELSE IF CHARINDEX(',',@strKTypeId)>0
	SET @szKTypeId = ''
ELSE
	SET @szKTypeId = @strKTypeId

CREATE TABLE #BillIndex
(
	BillNumberId	NUMERIC(18,0),
	BillType		INT,
	KTypeId			VARCHAR(100),
	KTypeId2		VARCHAR(100)
)

--计算草稿库存
INSERT INTO #BillIndex
SELECT	BillNumberId,
		BillType,
		KTypeId,
		KTypeId2
FROM	BillIndex
WHERE	BillType IN (11,45,160,140,142,34,6,161,144,146,16,178,183,187,188,201,202,191,196,197,17,21,9,14,305,126,139,400,401,402,403)
		AND Draft = 1	
		AND IfWx = 0
		
--维修单据
SELECT	BillNumberId,
		BillType,
		KTypeId,
		KTypeId2
INTO	#WxBillIndex
FROM	BillIndex
WHERE	BillType IN (166,168,172,173,174)
		AND Draft = 1

CREATE TABLE #DGS
(
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	RQty		 NUMERIC(24, 10) ,
	CQty		 NUMERIC(24, 10) ,
	CargoID     INT,
	goodsnumber varchar(100),
	ProduceDate varchar(100),
	ValidDate   varchar(100),
	ItemID      varchar(100),
    IsCombined  varchar(100)           
)
INSERT INTO #DGS
(
	PTypeId,
	KTypeId,
	RQty,
	CQty,
	CargoID,
	goodsnumber,
	ProduceDate,
	ValidDate,
	ItemID,
	IsCombined
)
SELECT	B.PTypeId,
		B.KtypeId AS Typeid,
		ISNULL(SUM(B.RQty),0) AS RQty,
		ISNULL(SUM(B.CQty),0) AS CQty,
		B.CargoID,
		B.goodsnumber,
		B.ProduceDate,
		B.ValidDate,
		B.ItemID,
		B.IsCombined
FROM GoodsStocks_Draft B INNER JOIN #A P ON P.TypeId=B.PtypeId			
              INNER	JOIN	#K K ON B.KtypeId = K.TypeId
			GROUP BY B.PTypeId,B.KtypeId,B.CargoID,B.goodsnumber,B.ProduceDate,B.ValidDate,B.ItemID,B.IsCombined

/*/******************************************************************************************************************/
--采购入库单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN BuyBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE   Bil.BillType = 34




--暂估入库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN AppraisalBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE   Bil.BillType = 400


--暂估退货单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN AppraisalBackBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE   Bil.BillType = 401


--发出商品出库单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN SendBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE   Bil.BillType = 402




--发出商品退货单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN SendBackBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE   Bil.BillType = 403



--采购退货
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN BuyBackBill S ON Bil.BillNumberId=S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 6
		
--采购换货入库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN BuyGoodsExchangeBill S ON Bil.BillNumberId=S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 161
		AND S.InOrOut = 'I'
		
--采购换货出库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN BuyGoodsExchangeBill S ON Bil.BillNumberId=S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 161
		AND S.InOrOut = 'O'
		
--销售出库单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
        INNER JOIN SaleBill S ON Bil.BillNumberId = S.BillNumberId
        INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE   Bil.BillType = 11
		
--销售退货
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		s.GoodsNumber,
		s.ProduceDate,
		s.ValidDate,
		s.ItemID,
		s.IsCombined
FROM	#BillIndex Bil
		INNER JOIN  SaleBackBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 45
	
		
--其他出库单
INSERT INTO #DGS
SELECT	o.PTypeId,
		o.KTypeId,
		0 AS RQty,
		o.Qty AS CQty,
		o.CargoID,
		o.GoodsNumber,
		o.ProduceDate,
		o.ValidDate,
		o.ItemID,
		o.IsCombined
FROM	#BillIndex Bil
	    INNER JOIN 	OtherInOutBill o ON Bil.BillNumberId=O.BillNumberId
	    INNER JOIN #K K ON K.TypeId=O.KTypeId
        INNER JOIN #A A ON A.TypeId=O.PtypeId
WHERE	 Bil.BillType = 202
		
		
--其他入库单
INSERT INTO #DGS
SELECT	o.PTypeId,
		o.KTypeId,
		o.Qty AS RQty,
		0 AS CQty,
		o.CargoID,
		o.GoodsNumber,
		o.ProduceDate,
		o.ValidDate,
		o.ItemID,
		o.IsCombined
FROM	#BillIndex Bil
		INNER JOIN OtherInOutBill o ON Bil.BillNumberId=O.BillNumberId
	    INNER JOIN #K K ON K.TypeId=O.KTypeId
        INNER JOIN #A A ON A.TypeId=O.PtypeId
WHERE	 Bil.BillType = 201
		
--销售换货入库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN SaleGoodsExchangeBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 160
		AND S.InOrOut = 'I'
		
--销售换货出库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN SaleGoodsExchangeBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 160
		AND S.InOrOut = 'O'
		
--同价调拨入库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId2,
		S.Qty AS RQty,
		0 AS CQty,
		S.InCargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
        INNER JOIN MoveBill S ON Bil.BillNumberId = S.BillNumberId
        INNER JOIN #K K ON K.TypeId=S.KTypeId2
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 17


--同价调拨出库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.OutCargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
        INNER JOIN MoveBill S ON Bil.BillNumberId = S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 17

--变价调拨入库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId2,
		S.Qty AS RQty,
		0 AS CQty,
		S.InCargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN MoveBjBill S ON Bil.BillNumberId=S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId2
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 21
		AND S.Qty>0
		--GROUP BY S.InCargoID,S.PTypeId,Bil.KTypeId2,S.Qty
		
		
--变价调拨出库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.OutCargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN MoveBjBill S ON Bil.BillNumberId=S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
		INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 21
--GROUP BY S.OutCargoID

		
--拆装单入库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN DisassembleBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 16
		AND S.InOrOut = 'I'
--拆装单出库
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
	    S.CargoID,
	    S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN DisassembleBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 16
		AND S.InOrOut = 'O'
--报溢单
INSERT INTO #DGS
SELECT	S.PTypeId,
		Bil.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN #K K ON K.TypeId=BIL.KTypeId
		INNER JOIN overflowBill S ON bil.BillNumberId=s.BillNumberId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 14

--报损单
INSERT INTO #DGS
SELECT	S.PTypeId,
		Bil.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN #K K ON K.TypeId=BIL.KTypeId
		INNER JOIN LoseBill S ON bil.BillNumberId=s.BillNumberId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 9

--受托收货
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN CommissionBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 144

--受托退货
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN CommissionBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 146

--委托发货
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN CommissionBill  S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 140

--委托退货
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN CommissionBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 142
		

--零售单
INSERT INTO #DGS
SELECT	S.PTypeId,
		Bil.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN #K K ON K.TypeId=Bil.KTypeId
		INNER JOIN RetailBill S  ON bil.BillNumberId=s.BillNumberId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 305
		
--赠送单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
        INNER JOIN GiveBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 139
		
--获赠单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
        INNER JOIN GiveMeBill S ON bil.BillNumberId=s.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 126
		
--维修单
INSERT INTO #DGS
SELECT	S.PTypeId,
		Bil.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#WxBillIndex Bil
		INNER JOIN #K K ON K.TypeId=Bil.KTypeId
		INNER JOIN Wx_Bill_Self S  ON bil.BillNumberId=s.BillNumberId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 166
		AND S.InOrOut = 'O' 
		AND S.WxProperty = 0
		
--整机更换单
INSERT INTO #DGS
SELECT	S.PTypeId,
		Bil.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#WxBillIndex Bil
	    INNER JOIN #K K ON K.TypeId=Bil.KTypeId
		INNER JOIN Wx_Bill_REPLACE S  ON bil.BillNumberId=s.BillNumberId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 168
		AND S.WxProperty = 0
		
--上门维修单
INSERT INTO #DGS
SELECT	S.PTypeId,
		Bil.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#WxBillIndex Bil
		INNER JOIN #K K ON K.TypeId=Bil.KTypeId
		INNER JOIN Wx_Bill_GoTo S ON bil.BillNumberId=s.BillNumberId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 172
		AND S.InOrOut = 'O' 
		AND S.WxProperty = 0

--维修品调入单
INSERT INTO #DGS
SELECT	S.PTypeId,
		Bil.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#WxBillIndex Bil
		INNER JOIN #K K ON K.TypeId=Bil.KTypeId
		INNER JOIN Wx_Bill_OUT S ON bil.BillNumberId=s.BillNumberId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 173

--维修品调出单
INSERT INTO #DGS
SELECT	S.PTypeId,
		Bil.KTypeId2,
		S.Qty AS RQty,
		0 AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#WxBillIndex Bil
		INNER JOIN #K K ON K.TypeId=Bil.ktypeid2
		INNER JOIN  Wx_Bill_OUT S ON bil.BillNumberId=s.BillNumberId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 174
		
--快修单
--INSERT INTO #DGS
--SELECT	S.PTypeId,
--		S.KTypeId,
--		0 AS RQty,
--		S.Qty AS CQty,
--		S.CargoSpace
--FROM	#BillIndex Bil
--		INNER JOIN QP_QuickRepairBill_PType S ON bil.BillNumberId=s.BillNumberId
--		INNER JOIN #K K ON K.TypeId=S.KTypeId
--        INNER JOIN #A A ON A.TypeId=S.PtypeId
--WHERE	 Bil.BillType = 178
	
	   
--领料出库单
--INSERT INTO #DGS
--SELECT P.PTypeID,
--	   p.KTypeID,
--	   0 AS RQty,
--	   P.Qty AS CQty,
--	   P.CargoSpace
--FROM   #BillIndex Bil
--	   INNER JOIN   Qp_PickingBill P ON Bil.BillNumberId = P.BillNumberId
--	   INNER JOIN #K K ON K.TypeId=P.KTypeId
--       INNER JOIN #A A ON A.TypeId=P.PtypeId
--	   WHERE Bil.BillType = 191
	   
--领料退回单
--INSERT INTO #DGS
--SELECT P.PTypeID,
--	   p.KTypeID,
--	   P.Qty AS RQty,
--	   0 AS CQty,
--	   P.c
--FROM   #BillIndex Bil
--	   INNER JOIN   Qp_PickingBackBill P ON Bil.BillNumberId = P.BillNumberId
--	   INNER JOIN #K K ON K.TypeId=P.KTypeId
--       INNER JOIN #A A ON A.TypeId=P.PtypeId
--	   WHERE Bil.BillType = 197
		

--救援单
--INSERT INTO #DGS
--SELECT S.PTypeID,
--		s.KTypeId,
--	   0 AS RQty,
--	   S.Qty AS CQty,
--	   S.CargoSpace
--FROM   #BillIndex Bil
--       INNER JOIN   Qp_SuccorBill_PType S ON Bil.BillNumberId = S.BillNumberId
--       INNER JOIN #K K ON K.TypeId=S.KTypeId
--       INNER JOIN #A A ON A.TypeId=S.PtypeId
--	   WHERE Bil.BillType = 196
	   		
--积分兑换单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.CargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN IntegralExchangeBill S   ON Bil.BillNumberId=S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	Bil.BillNumberId = S.BillNumberId
		AND Bil.BillType = 183
		
--分支机构调拨出库单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.KTypeId,
		0 AS RQty,
		S.Qty AS CQty,
		S.OutCargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN STypeMoveBill S ON Bil.BillNumberId=S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.KTypeId
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 187
		
--分支机构调拨入库单
INSERT INTO #DGS
SELECT	S.PTypeId,
		S.Ktypeid2 AS ktypeid,
		S.Qty AS RQty,
		0 AS CQty,
		S.InCargoID,
		S.GoodsNumber,
		S.ProduceDate,
		S.ValidDate,
		S.ItemID,
		S.IsCombined
FROM	#BillIndex Bil
		INNER JOIN STypeMoveBill S ON Bil.BillNumberId=S.BillNumberId
		INNER JOIN #K K ON K.TypeId=S.Ktypeid2
        INNER JOIN #A A ON A.TypeId=S.PtypeId
WHERE	 Bil.BillType = 188
	
/******************************************************************************************************************/*/


CREATE TABLE #Result(
	nID				int identity(1,1),
	bID				int,
	TypeId			varchar(50),
	UserCode		varchar(256),
	FullName  	  	varchar(256),
	UnitRate		 NUMERIC(24, 10)  default(0),
	Qty				 NUMERIC(24, 10) ,
	BQty			 NUMERIC(24, 10) ,
	Factqty			 NUMERIC(24, 10) ,
	LendQty			 NUMERIC(24, 10) ,
	BorrowQty		 NUMERIC(24, 10) ,	
	BuyOrderQty		 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	SaleCanQty		 NUMERIC(24, 10) ,
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	KFHQty			 NUMERIC(24, 10) ,
	WxQty			 NUMERIC(24, 10) ,
	PrePrice1		 NUMERIC(24, 10) ,
	PrePrice2		 NUMERIC(24, 10) ,
	PrePrice3		 NUMERIC(24, 10) ,
	PrePrice4		 NUMERIC(24, 10) ,
	recPrice		 NUMERIC(24, 10) ,
	Price			 NUMERIC(24, 10) ,
	KTypeId			varchar(100) default(''),
	cargoidin       varchar(100) default(''),
	cargofullnamein varchar(100) default(''),
	outcargoid      varchar(100) default(''),
	outcargofullname varchar(100) default(''),
	GoodsNumber      varchar(100),
    ProduceDate      varchar(100),
    ValidDate        varchar(100),
    ItemID           varchar(100),
    IsCombined       varchar(100),
    IsService        varchar(100),
    unit             varchar(100)
)

CREATE TABLE #tempResult(
	
	TypeId			varchar(50),
	KTypeId			varchar(100) default(''),
	GoodsNumber      varchar(100),
    ItemID           varchar(100),
    IsCombined       varchar(100)      
)

CREATE TABLE #tempResultByCargoType(
	
	TypeId			varchar(50),
	KTypeId			varchar(100) default(''),
	cargoidin       varchar(100) default(''),
	GoodsNumber      varchar(100),
    ItemID           varchar(100),
    IsCombined       varchar(100)      
)

--更新单据数量

DECLARE @nID 			        int,
		@numQty			         NUMERIC(24, 10) ,
		@pUserCode		        varchar(256),
		@UnitRate		         NUMERIC(24, 10) ,
		@recPrice		         NUMERIC(24, 10) ,
        @cargoidinid            varchar(100),
        @cargofullnameinname    varchar(100),
        @outcargoidin           varchar(100),
        @outcargofullnamename   varchar(100),
        @GoodsNumber            varchar(100),
        @ProduceDate            varchar(100),
        @ValidDate              varchar(100),
        @ItemID                 varchar(100),
        @IsCombined             varchar(100)
IF(@cargoidin <> '' AND @outcargoid <> '')
BEGIN

        --select * from #A1
        -- select * from #CargoidIDS
        --  select * from #CargoidNames
        --return
--显示基本单位的进价
DECLARE TC CURSOR FOR
	SELECT DISTINCT  A.nID,A.TypeId,P.UnitRate1,CASE WHEN @isap=1 THEN ps.RecAppraisalPrice ELSE ps.RecPrice END AS RecPrice,cid.Id,cname.Name,outcid.Id,outcname.Name,gnumber.number,prodate.pdate
	,valdate.vdate,	itemids.itemid,iscom.iscombined
	FROM #A1 A--, PType P
	LEFT JOIN #CargoidIDS cid ON cid.nid=A.nID
	LEFT JOIN #CargoidNames cname ON cname.nid=A.nID
	LEFT JOIN #outCargoidIDS outcid ON outcid.nid=A.nID
	LEFT JOIN #outCargoidNames outcname ON outcname.nid=A.nID
	LEFT JOIN #Goodsnumbers gnumber ON gnumber.nid=A.nID
	LEFT JOIN #ProduceDates prodate ON prodate.nid=A.nID
	LEFT JOIN #ValidDates   valdate ON valdate.nid=A.nID
	LEFT JOIN #ItemIDs      itemids ON itemids.nid=A.nID
	LEFT JOIN #IsCombineds  iscom   ON iscom.nid=A.nID
	LEFT JOIN PType P ON  A.TypeId = P.TypeId 
	LEFT JOIN PType_STypePrice ps ON P.typeid=ps.PTypeID AND ps.STypeID=@stypeid  AND ps.UnitID=p.baseUnitId
	--WHERE A.TypeId = P.TypeId  --AND A.nid=cid.nid AND A.nid=cname.nid AND A.nid=outcid.nid AND A.nid=outcname.nid
	ORDER BY A.nID ASC

OPEN TC

FETCH NEXT FROM TC INTO @nID,@pUserCode,@UnitRate,@recPrice,@cargoidinid,@cargofullnameinname,@outcargoidin,@outcargofullnamename,@GoodsNumber,@ProduceDate,@ValidDate,@ItemID,@IsCombined

WHILE @@FETCH_STATUS = 0
	BEGIN
	IF @GoodsNumber is null
	SET @GoodsNumber=''
	IF @ProduceDate is null
	SET @ProduceDate=''
	IF @ValidDate is null
	SET @ValidDate=''
	IF  @ItemID is null
	SET @ItemID=''
	IF @IsCombined is null
	SET @IsCombined=''           
				   
		--写入商品
		INSERT INTO  #Result(
				bID,
				TypeId,
				UserCode,
				FullName,
				UnitRate,
				Qty,
				BQty,
				Factqty,
				LendQty,
				BorrowQty,		
				BuyOrderQty,
				SaleOrderQty,
				SaleCanQty,
				RQty,
				CQty,
				KFHQty,
				WxQty,
				PrePrice1,
				PrePrice2,
				PrePrice3,
				PrePrice4,
				recPrice,
				Price,
				cargoidin,
	            cargofullnamein,
	            outcargoid,
	            outcargofullname,
	            GoodsNumber,      
				ProduceDate,     
				ValidDate,        
				ItemID,          
				IsCombined,
				IsService,
				unit   
		    )VALUES(
				@nID,
				@pUserCode,
				' ',
				' ',
				0,
				@UnitRate,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				@recPrice,
				0,
				@cargoidinid,
				@cargofullnameinname,
				@outcargoidin,
				@outcargofullnamename,
				@GoodsNumber,           
				@ProduceDate,            
				@ValidDate,            
				@ItemID,                
				@IsCombined,
				(select isservice from ptype where typeid=@pUserCode),
				(select fullname from ptype_units where unitsid=(select baseunitid from ptype where typeid=@pUserCode))            
		)
		SET @numQty = 0

		SELECT @numQty = Qty FROM #B WHERE nID = @nID

		--计算单据数量（分大小单位）
		IF EXISTS(SELECT * FROM #C WHERE nID = @nID AND UTow = 1)
			UPDATE 	#Result
			SET		BQty = CAST(@numQty*@UnitRate AS  NUMERIC(24, 10) )
			WHERE	bID = @nID
		ELSE
			UPDATE 	#Result
			SET		BQty = @numQty
			WHERE	bID = @nID		

		UPDATE #Result SET KTypeId = (SELECT TypeId FROM #K1 WHERE nID = @nID) WHERE	bID = @nID

		FETCH NEXT FROM TC INTO @nID,@pUserCode,@UnitRate,@recPrice,@cargoidinid,@cargofullnameinname,@outcargoidin,@outcargofullnamename,@GoodsNumber,@ProduceDate,@ValidDate,@ItemID,@IsCombined
	END

CLOSE TC
DEALLOCATE TC

DROP TABLE #A1,#B,#C,#K,#A,#CargoidIDS,#CargoidNames,#outCargoidIDS,#outCargoidNames

insert into #tempResultByCargoType  select r.TypeId,r.KtypeId,r.cargoidin,r.GoodsNumber,r.ItemID,r.Iscombined from #Result r  group by r.TypeId,r.KtypeId,r.cargoidin,r.GoodsNumber,r.ItemID,r.Iscombined	

--==============================================修改当前数量



UPDATE	#Result
SET		Qty = ISNULL(t.Qty,0),
		FactQty = ISNULL(t.Qty,0),
		Price = ISNULL(g.Price,0)
FROM	#Result R
inner JOIN(	
	
		select r.TypeId ,r.KtypeId,r.GoodsNumber,
		CASE WHEN ISNULL(SUM(g.Qty),0) = 0 THEN 0 ELSE ISNULL(cast(SUM(g.Total) as NUMERIC(24, 10)),0) / ISNULL(SUM(g.Qty),0) END AS Price
		from #tempResultByCargoType r left join GOODSSTOCKS g
		on g.PtypeId = r.TypeId and g.KtypeId = r.KTypeId and ((g.GoodsNumber =r.GoodsNumber and g.GoodsNumber <> '') or r.GoodsNumber='' or r.GoodsNumber <> '') 
		group by r.TypeId ,r.KtypeId,r.GoodsNumber
	) g on g.TypeId = r.TypeId and g.KtypeId = r.KTypeId and g.GoodsNumber =r.GoodsNumber
	left join
	(
		 select r.TypeId,r.KtypeId,r.cargoidin,r.GoodsNumber,r.ItemID,r.Iscombined,sum(t.Qty) Qty
		 from #tempResultByCargoType r inner join
		 GOODSSTOCKS_QTY t 
		 on t.PTypeID = r.TypeId and t.KTypeID = r.KtypeId and t.CargoID=r.cargoidin and (t.GoodsNumber =r.GoodsNumber or r.GoodsNumber='') and (t.ItemID =r.ItemID or r.ItemID='') and (t.Iscombined =r.IsCombined or r.IsCombined='')
		 group by r.TypeId,r.KtypeId,r.cargoidin,r.GoodsNumber,r.ItemID,r.Iscombined	
 	) t --on t.PTypeID = r.TypeId and t.KTypeID = r.KtypeId and t.CargoID=r.cargoidin and t.GoodsNumber like '%'+r.GoodsNumber+'%' and ( (LEN(t.GoodsNumber) = LEN(r.GoodsNumber) and r.GoodsNumber != '' ) OR r.GoodsNumber = '') and t.ProduceDate like '%'+r.ProduceDate+'%' and t.ProduceDate like '%'+r.ProduceDate+'%' and t.ItemID like '%'+r.ItemID+'%' and ( (LEN(t.ItemID) = LEN(r.ItemID) and r.ItemID != '' ) OR r.ItemID = '') and t.Iscombined like '%'+r.IsCombined+'%'
 	on t.TypeId = r.TypeId and t.KTypeID = r.KtypeId and t.cargoidin=r.cargoidin and t.GoodsNumber = r.GoodsNumber and t.ItemID =r.ItemID  and t.Iscombined =r.IsCombined
 	

--==============================================修改借欠数量

UPDATE	#Result
SET		FactQty   = ISNULL((ISNULL(R.Qty,0)+ISNULL(L.BorrowQty,0)-ISNULL(L.LendQty,0)),0),		
		LendQty   = ISNULL(L.LendQty,0),
		BorrowQty = ISNULL(L.BorrowQty,0)
FROM	#Result R
LEFT JOIN (
	--SELECT 	PTypeID,
	--		KTypeID,
	--		LendQty   =  ISNULL(SUM(Lend-LendBack),0),
	--		BorrowQty =  ISNULL(SUM(Borrow-BorrowBack),0),
	--		ItemID,IsCombined,GoodsNumber,ProduceDate,ValidDate
	--FROM 	V_LendStatus
	--GROUP BY PTypeID,KTypeID,GoodsNumber,IsCombined,ItemID,producedate,ValidDate
	
	     select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined, ISNULL(SUM(Lend-LendBack),0) LendQty,ISNULL(SUM(Borrow-BorrowBack),0) BorrowQty
		 from #tempResultByCargoType r inner join
		 V_LendStatus t
		 on t.PTypeID = r.TypeId and t.KTypeID = r.KtypeId and (t.GoodsNumber=r.GoodsNumber or r.GoodsNumber='') and  (t.ItemID =r.ItemID or r.ItemID='') and (t.Iscombined =r.IsCombined or r.IsCombined='')
		 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined	
	
)L ON ( R.TypeID = L.TypeId AND R.KTypeId = L.KTypeId and L.GoodsNumber =r.GoodsNumber and L.IsCombined =R.IsCombined and L.ItemID=r.ItemID  )


--==============================================修改订单数量

UPDATE	#Result
SET		SaleCanQty     = CASE
							WHEN (ISNULL(L.SaleOrderQty,0)>=0 AND ISNULL(L.BuyOrderQty,0)>=0)    THEN ISNULL((ISNULL(R.Qty,0) + ISNULL(L.BuyOrderQty,0) - ISNULL(L.SaleOrderQty,0)),0)
							WHEN (ISNULL(L.SaleOrderQty,0)>=0 AND ISNULL(L.BuyOrderQty,0)<0)     THEN ISNULL(R.Qty,0) - ISNULL(L.SaleOrderQty,0)
							WHEN (ISNULL(L.SaleOrderQty,0)<0  AND ISNULL(L.BuyOrderQty,0)>=0)    THEN ISNULL(R.Qty,0) + ISNULL(L.BuyOrderQty,0)
							WHEN (ISNULL(L.SaleOrderQty,0)<0  AND ISNULL(L.BuyOrderQty,0)<0)     THEN ISNULL(R.Qty,0)
						 END,							
		SaleOrderQty   = CASE WHEN ISNULL(L.SaleOrderQty,0)>=0 THEN ISNULL(L.SaleOrderQty,0) ELSE 0 END,
		BuyOrderQty    = CASE WHEN ISNULL(L.BuyOrderQty,0)>=0 THEN ISNULL(L.BuyOrderQty,0) ELSE 0 END
FROM	#Result R
LEFT JOIN (
	--SELECT 	PTypeID,
	--		KTypeID,
	--		SaleOrderQty = ISNULL(SUM(SaleOrderQty),0)-ISNULL(SUM(SaleReachQty),0),
	--		BuyOrderQty   =  ISNULL(SUM(BuyOrderQty),0)-ISNULL(SUM(BuyReachQty),0),
	--		CargoID,
	--		ItemID,IsCombined,GoodsNumber
	--FROM 	V_VirtualStockOrderStatus	
	--GROUP BY PTypeID,KTypeID,CargoID,ItemID,IsCombined,GoodsNumber
	
	     select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,r.cargoidin,
	     CASE WHEN SUM(ISNULL(L.SaleOrderQty,0)-ISNULL(L.LimitSaleQty,0)) >=0 
			THEN SUM(ISNULL(L.SaleOrderQty,0)-ISNULL(L.LimitSaleQty,0)) ELSE 0 
			END AS SaleOrderQty,
			CASE WHEN SUM(ISNULL(L.BuyOrderQty,0)-ISNULL(L.LimitBuyQty,0))>=0 
			THEN SUM(ISNULL(L.BuyOrderQty,0)-ISNULL(L.LimitBuyQty,0)) ELSE 0 
			END AS BuyOrderQty
		 from #tempResultByCargoType r inner join
		 GoodsStocks_order L
		 on R.TypeID = L.PTypeID AND R.KTypeId = L.KTypeID AND L.CargoID=r.cargoidin and (L.GoodsNumber=r.GoodsNumber or r.GoodsNumber='' ) and (L.IsCombined =R.IsCombined or R.IsCombined='')  and (L.ItemID =r.ItemID or r.ItemID='' )
		 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,r.cargoidin 	
	
	
)L ON ( R.TypeID = L.TypeId AND R.KTypeId = L.KTypeID AND L.cargoidin=R.cargoidin and L.GoodsNumber =r.GoodsNumber and L.IsCombined =R.IsCombined and L.ItemID =r.ItemID )

--==============================================修改草稿数量

UPDATE	#Result
SET		RQty = ISNULL(L.RQty,0),
		CQty = ISNULL(L.CQty,0),
		KFHQty = ISNULL(R.Qty,0)+ISNULL(L.RQty,0)-ISNULL(L.CQty,0)
FROM	#Result R
LEFT JOIN (
	--SELECT	PTypeId,
	--		KTypeId,
	--		SUM(RQty) AS RQty,
	--		SUM(CQty) AS CQty,
	--		CargoID,
	--		ItemID,IsCombined,GoodsNumber,ProduceDate,ValidDate
	--FROM	#DGS
	--GROUP BY PTypeId,KTypeId,CargoID,goodsnumber,ProduceDate,ValidDate,ItemID,IsCombined
	
	    select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,r.cargoidin,SUM(L.RQty) AS RQty,SUM(L.CQty) AS CQty
		 from #tempResultByCargoType r inner join
		 #DGS L
		 ON R.TypeId = L.PTypeId AND R.KTypeId = L.KTypeId AND  L.CargoID=R.cargoidin and (L.GoodsNumber =r.GoodsNumber or r.GoodsNumber='') and (L.IsCombined =R.IsCombined or R.IsCombined='')  and (L.ItemID =r.ItemID or r.ItemID='')
		 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,r.cargoidin
	
	
	
)L ON R.TypeId = L.TypeId AND R.KTypeId = L.KTypeId AND  L.cargoidin=R.cargoidin and L.GoodsNumber =r.GoodsNumber and L.IsCombined =R.IsCombined and L.ItemID =r.ItemID 


--==============================================维修库存数量

UPDATE	#Result
SET		WxQty = ISNULL(L.Qty,0)
FROM	#Result R
LEFT JOIN (
	
	--SELECT	PTypeId,
	--		KTypeId,
	--		SUM(Qty) AS Qty,
	--		CargoID,
	--		GoodsNumber,
	--		ProduceDate,
	--		ValidDate,
	--		ItemID,
	--		IsCombined
	--FROM	Wx_GoodsStocks 
	--GROUP BY PTypeId,KTypeId,CargoID,goodsnumber,ProduceDate,ValidDate,ItemID,IsCombined
	
	 select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,r.cargoidin,SUM(L.Qty) AS Qty
	 from #tempResultByCargoType r inner join
	 Wx_GoodsStocks L
	 ON R.TypeId = L.PTypeId AND R.KTypeId = L.KTypeId AND  L.CargoID=R.cargoidin and (L.GoodsNumber =r.GoodsNumber or r.GoodsNumber='') and (L.IsCombined =R.IsCombined or R.IsCombined='')  and (L.ItemID =r.ItemID or r.ItemID='') 
	 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,r.cargoidin
	
	
)L ON ( R.TypeId = L.TypeId AND R.KTypeId = L.KTypeId AND  L.cargoidin=R.cargoidin and L.GoodsNumber =r.GoodsNumber and L.IsCombined =R.IsCombined and L.ItemID =r.ItemID)


END
ELSE
BEGIN
--新加

DECLARE TC CURSOR FOR
	SELECT A.nID,A.TypeId,P.UnitRate1,CASE WHEN @isap=1 THEN ps.RecAppraisalPrice ELSE ps.RecPrice END AS RecPrice,gnumber.number,prodate.pdate
	,valdate.vdate,	itemids.itemid,iscom.iscombined
	FROM #A1 A--,  PType P
	LEFT JOIN #Goodsnumbers gnumber ON gnumber.nid=A.nID
	LEFT JOIN #ProduceDates prodate ON prodate.nid=A.nID
	LEFT JOIN #ValidDates   valdate ON valdate.nid=A.nID
	LEFT JOIN #ItemIDs      itemids ON itemids.nid=A.nID
	LEFT JOIN #IsCombineds  iscom   ON iscom.nid=A.nID
	LEFT JOIN PType P ON  A.TypeId = P.TypeId 
	LEFT JOIN PType_STypePrice ps ON P.typeid=ps.PTypeID AND ps.STypeID=@stypeid  AND ps.UnitID=p.baseUnitId
	--WHERE A.TypeId = P.TypeId
	ORDER BY A.nID ASC

OPEN TC

FETCH NEXT FROM TC INTO @nID,@pUserCode,@UnitRate,@recPrice,@GoodsNumber,@ProduceDate,@ValidDate,@ItemID,@IsCombined

WHILE @@FETCH_STATUS = 0
	BEGIN
	IF @GoodsNumber is null
	SET @GoodsNumber=''
	IF @ProduceDate is null
	SET @ProduceDate=''
	IF @ValidDate is null
	SET @ValidDate=''
	IF  @ItemID is null
	SET @ItemID=''
	IF @IsCombined is null
	SET @IsCombined=''           
		--写入商品
		INSERT INTO  #Result(
				bID,
				TypeId,
				UserCode,
				FullName,
				UnitRate,
				Qty,
				BQty,
				Factqty,
				LendQty,
				BorrowQty,		
				BuyOrderQty,
				SaleOrderQty,
				SaleCanQty,
				RQty,
				CQty,
				KFHQty,
				WxQty,
				PrePrice1,
				PrePrice2,
				PrePrice3,
				PrePrice4,
				recPrice,
				Price,
				GoodsNumber,      
				ProduceDate,     
				ValidDate,        
				ItemID,          
				IsCombined,
				IsService ,  
		        unit
		)VALUES(
				@nID,
				@pUserCode,
				' ',
				' ',
				0,
				@UnitRate,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				0,
				@recPrice,
				0,
				@GoodsNumber,           
				@ProduceDate,            
				@ValidDate,            
				@ItemID,                
				@IsCombined,
				(select isservice from ptype where typeid=@pUserCode),
				(select fullname from ptype_units where unitsid=(select baseunitid from ptype where typeid=@pUserCode)) 
		)
		SET @numQty = 0

		SELECT @numQty = Qty FROM #B WHERE nID = @nID

		--计算单据数量（分大小单位）
		IF EXISTS(SELECT * FROM #C WHERE nID = @nID AND UTow = 1)
			UPDATE 	#Result
			SET		BQty = CAST(@numQty*@UnitRate AS  NUMERIC(24, 10) )
			WHERE	bID = @nID
		ELSE
			UPDATE 	#Result
			SET		BQty = @numQty
			WHERE	bID = @nID		

		UPDATE #Result SET KTypeId = (SELECT TypeId FROM #K1 WHERE nID = @nID) WHERE	bID = @nID

		FETCH NEXT FROM TC INTO @nID,@pUserCode,@UnitRate,@recPrice,@GoodsNumber,@ProduceDate,@ValidDate,@ItemID,@IsCombined
	END

CLOSE TC
DEALLOCATE TC

DROP TABLE #A1,#B,#C,#K,#A,#CargoidIDS,#CargoidNames,#outCargoidIDS,#outCargoidNames
--==============================================修改当前数量

insert into #tempResult  select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined from #Result r  group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined	

UPDATE	#Result
SET		Qty = ISNULL(t.Qty,0),
		FactQty = ISNULL(t.Qty,0),
		Price = ISNULL(g.Price,0)
FROM	#Result R
inner JOIN(	
	
		select r.TypeId ,r.KtypeId,r.GoodsNumber,
		CASE WHEN ISNULL(SUM(g.Qty),0) = 0 THEN 0 ELSE ISNULL(cast(SUM(g.Total) as NUMERIC(24, 10)),0) / ISNULL(SUM(g.Qty),0) END AS Price
		from #tempResult r left join GOODSSTOCKS g
		on g.PtypeId = r.TypeId and g.KtypeId = r.KTypeId and ((g.GoodsNumber =r.GoodsNumber and g.GoodsNumber <> '') or r.GoodsNumber='' or r.GoodsNumber <> '') 
		group by r.TypeId ,r.KtypeId,r.GoodsNumber
	) g on g.TypeId = r.TypeId and g.KtypeId = r.KTypeId and g.GoodsNumber =r.GoodsNumber 
	left join
	(
		 select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,sum(t.Qty) Qty
		 from #tempResult r inner join
		 GOODSSTOCKS_QTY t 
		 on t.PTypeID = r.TypeId and t.KTypeID = r.KtypeId  and (t.GoodsNumber =r.GoodsNumber or r.GoodsNumber='') and (t.ItemID =r.ItemID or r.ItemID='') and (t.Iscombined =r.IsCombined or r.IsCombined='')
		 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined	
 	) t --on t.PTypeID = r.TypeId and t.KTypeID = r.KtypeId and t.CargoID=r.cargoidin and t.GoodsNumber like '%'+r.GoodsNumber+'%' and ( (LEN(t.GoodsNumber) = LEN(r.GoodsNumber) and r.GoodsNumber != '' ) OR r.GoodsNumber = '') and t.ProduceDate like '%'+r.ProduceDate+'%' and t.ProduceDate like '%'+r.ProduceDate+'%' and t.ItemID like '%'+r.ItemID+'%' and ( (LEN(t.ItemID) = LEN(r.ItemID) and r.ItemID != '' ) OR r.ItemID = '') and t.Iscombined like '%'+r.IsCombined+'%'
 	on t.TypeId = r.TypeId and t.KTypeID = r.KtypeId  and t.GoodsNumber = r.GoodsNumber and t.ItemID =r.ItemID  and t.Iscombined =r.IsCombined

--select * from #Result
--return

--==============================================修改借欠数量

UPDATE	#Result
SET		FactQty   = ISNULL((ISNULL(R.Qty,0)+ISNULL(L.BorrowQty,0)-ISNULL(L.LendQty,0)),0),		
		LendQty   = ISNULL(L.LendQty,0),
		BorrowQty = ISNULL(L.BorrowQty,0)
FROM	#Result R
LEFT JOIN (
	--SELECT 	PTypeID,
	--		KTypeID,
	--		LendQty   =  ISNULL(SUM(Lend-LendBack),0),
	--		BorrowQty =  ISNULL(SUM(Borrow-BorrowBack),0),
	--		ItemID,IsCombined,GoodsNumber,ProduceDate,ValidDate
	--FROM 	V_LendStatus
	--GROUP BY PTypeID,KTypeID,GoodsNumber,IsCombined,ItemID,producedate,ValidDate
	
	     select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined, ISNULL(SUM(Lend-LendBack),0) LendQty,ISNULL(SUM(Borrow-BorrowBack),0) BorrowQty
		 from #tempResult r inner join
		 V_LendStatus t
		 on t.PTypeID = r.TypeId and t.KTypeID = r.KtypeId and (t.GoodsNumber=r.GoodsNumber or r.GoodsNumber='')  and  (t.ItemID =r.ItemID or r.ItemID='') and (t.Iscombined =r.IsCombined or r.IsCombined='')
		 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined	
	
)L ON ( R.TypeID = L.TypeId AND R.KTypeId = L.KTypeId and L.GoodsNumber =r.GoodsNumber and L.IsCombined =R.IsCombined and L.ItemID=r.ItemID )

--==============================================修改订单数量

UPDATE	#Result
SET		SaleCanQty     = CASE
							WHEN (ISNULL(L.SaleOrderQty,0)>=0 AND ISNULL(L.BuyOrderQty,0)>=0)    THEN ISNULL((ISNULL(R.Qty,0) + ISNULL(L.BuyOrderQty,0) - ISNULL(L.SaleOrderQty,0)),0)
							WHEN (ISNULL(L.SaleOrderQty,0)>=0 AND ISNULL(L.BuyOrderQty,0)<0)     THEN ISNULL(R.Qty,0) - ISNULL(L.SaleOrderQty,0)
							WHEN (ISNULL(L.SaleOrderQty,0)<0  AND ISNULL(L.BuyOrderQty,0)>=0)    THEN ISNULL(R.Qty,0) + ISNULL(L.BuyOrderQty,0)
							WHEN (ISNULL(L.SaleOrderQty,0)<0  AND ISNULL(L.BuyOrderQty,0)<0)     THEN ISNULL(R.Qty,0)
						 END,							
		SaleOrderQty   = CASE WHEN ISNULL(L.SaleOrderQty,0)>=0 THEN ISNULL(L.SaleOrderQty,0) ELSE 0 END,
		BuyOrderQty    = CASE WHEN ISNULL(L.BuyOrderQty,0)>=0 THEN ISNULL(L.BuyOrderQty,0) ELSE 0 END
FROM	#Result R
LEFT JOIN (
	--SELECT 	PTypeID,
	--		KTypeID,
	--		SaleOrderQty = ISNULL(SUM(SaleOrderQty),0)-ISNULL(SUM(SaleReachQty),0),
	--		BuyOrderQty   =  ISNULL(SUM(BuyOrderQty),0)-ISNULL(SUM(BuyReachQty),0),
	--		CargoID,
	--		ItemID,IsCombined,GoodsNumber
	--FROM 	V_VirtualStockOrderStatus	
	--GROUP BY PTypeID,KTypeID,CargoID,ItemID,IsCombined,GoodsNumber
	
	     select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,
	      CASE WHEN SUM(ISNULL(L.SaleOrderQty,0)-ISNULL(L.LimitSaleQty,0)) >=0 
			THEN SUM(ISNULL(L.SaleOrderQty,0)-ISNULL(L.LimitSaleQty,0)) ELSE 0 
			END AS SaleOrderQty,
			CASE WHEN SUM(ISNULL(L.BuyOrderQty,0)-ISNULL(L.LimitBuyQty,0))>=0 
			THEN SUM(ISNULL(L.BuyOrderQty,0)-ISNULL(L.LimitBuyQty,0)) ELSE 0 
			END AS BuyOrderQty
		 from #tempResult r inner join
		 GoodsStocks_order L
		 on R.TypeID = L.PTypeID AND R.KTypeId = L.KTypeID  and (L.GoodsNumber=r.GoodsNumber or r.GoodsNumber='' ) and (L.IsCombined =R.IsCombined or R.IsCombined='')  and (L.ItemID =r.ItemID or r.ItemID='' )
		 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined	
	
	
)L ON ( R.TypeID = L.TypeId AND R.KTypeId = L.KTypeID  and L.GoodsNumber =r.GoodsNumber and L.IsCombined =R.IsCombined and L.ItemID =r.ItemID )

--==============================================修改草稿数量

UPDATE	#Result
SET		RQty = ISNULL(L.RQty,0),
		CQty = ISNULL(L.CQty,0),
		KFHQty = ISNULL(R.Qty,0)+ISNULL(L.RQty,0)-ISNULL(L.CQty,0)
FROM	#Result R
LEFT JOIN (
	--SELECT	PTypeId,
	--		KTypeId,
	--		SUM(RQty) AS RQty,
	--		SUM(CQty) AS CQty,
	--		CargoID,
	--		ItemID,IsCombined,GoodsNumber,ProduceDate,ValidDate
	--FROM	#DGS
	--GROUP BY PTypeId,KTypeId,CargoID,goodsnumber,ProduceDate,ValidDate,ItemID,IsCombined
	
	    select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,SUM(L.RQty) AS RQty,SUM(L.CQty) AS CQty
		 from #tempResult r inner join
		 #DGS L
		 ON R.TypeId = L.PTypeId AND R.KTypeId = L.KTypeId  and (L.GoodsNumber =r.GoodsNumber or r.GoodsNumber='') and (L.IsCombined =R.IsCombined or R.IsCombined='')  and (L.ItemID =r.ItemID or r.ItemID='')
		 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined 
	
	
	
)L ON R.TypeId = L.TypeId AND R.KTypeId = L.KTypeId AND  L.GoodsNumber =r.GoodsNumber and L.IsCombined =R.IsCombined and L.ItemID =r.ItemID

--==============================================维修库存数量

UPDATE	#Result
SET		WxQty = ISNULL(L.Qty,0)
FROM	#Result R
LEFT JOIN (
	
	--SELECT	PTypeId,
	--		KTypeId,
	--		SUM(Qty) AS Qty,
	--		CargoID,
	--		GoodsNumber,
	--		ProduceDate,
	--		ValidDate,
	--		ItemID,
	--		IsCombined
	--FROM	Wx_GoodsStocks 
	--GROUP BY PTypeId,KTypeId,CargoID,goodsnumber,ProduceDate,ValidDate,ItemID,IsCombined
	
	 select r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined,SUM(L.Qty) AS Qty
	 from #tempResult r inner join
	 Wx_GoodsStocks L
	 ON R.TypeId = L.PTypeId AND R.KTypeId = L.KTypeId  and (L.GoodsNumber =r.GoodsNumber or r.GoodsNumber='') and (L.IsCombined =R.IsCombined or R.IsCombined='')  and (L.ItemID =r.ItemID or r.ItemID='') 
	 group by r.TypeId,r.KtypeId,r.GoodsNumber,r.ItemID,r.Iscombined 

	
	
)L ON ( R.TypeId = L.TypeId AND R.KTypeId = L.KTypeId and L.GoodsNumber =r.GoodsNumber and L.IsCombined =R.IsCombined and L.ItemID =r.ItemID )


--
END

DECLARE @SQL varchar(8000)

SELECT @SQL = 'SELECT * FROM #Result '

--PRINT(@SQL)
EXEC(@SQL)
DROP TABLE #Result,#DGS,#BillIndex,#WxBillIndex,#K1,#tempResult,#tempResultByCargoType






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryToolIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryToolIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2011-04-27
	描述：工具出入库单据
*/
CREATE PROCEDURE Gp_QueryToolIndex
( 
	@MagEType		varchar(50),
	@BillType		varchar(5)='',
	@BeginDate		varchar(25)='',
	@EndDate		varchar(25)='',
	@BillCode		varchar(200)='',
	@EtypeName		varchar(200)='',
	@BtypeName		varchar(200)='',
	@IfAudit		CHAR(2) = '1' ,
	@AtypeName		varchar(200)='',
	@RelatBtype		varchar(200)='',
	@Comment		varchar(256)='',
	@BillNumberId		numeric(10)=0,
	@OrderBy		varchar(250)='',
	@FilterBill		varchar(250)='',
	@stypeid		varchar(50),
	@DTypeID  		VARCHAR(100) = ''
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @MagEType
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 分支机构
IF @Stypeid<>'' or @chvMStypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END


-- 部门
IF @chvMDtypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetaildType FROM F_BaseGetManDetailDType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END

DECLARE @re 			int,	-- 修改他人草稿的权限\
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@offset			INT
IF (@chvOperatorID = '00001')
	SET @re = 0
ELSE
BEGIN	
	SELECT @offset = 135	-- 检查某人是否有查看管辖职员草稿得权限
	EXEC @re = GP_CheckLimit @chvOperatorID,@offset
END	
-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(3000)
SET @SQL = '
	SELECT	a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.DTypeID,
			a.StypeID,
			a.Explain,
			a.InOutType,
			a.checke,
			a.Comment
	FROM	ToolIndex a ' + @SQL_Man + '
	WHERE	a.BillDate >= ''' + @BeginDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			AND a.BillType = ' + @BillType

IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @EtypeName <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EtypeName + ''''
IF @DTypeID <> '' SET @SQL = @SQL + ' AND a.DTypeID=''' + @DTypeID + ''''
IF @re <> 0 SET @SQL = @SQL + ' AND a.Checke = ''' + @chvOperatorID + ''''
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC, a.BillCode'

--PRINT(@SQL)
EXEC (@SQL)
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMDtypeid  = '-99999' DROP TABLE #F_BaseGetManDetaildType 
IF @Stypeid<>'' or @chvMStypeid<>'00000' DROP TABLE #F_BaseGetManDetailSType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_QueryVipAddMoneyBillIndexAuditing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryVipAddMoneyBillIndexAuditing]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王珏
	日期：2014-05-09
	描述：会员充值单据导入草稿的存储过程
*/
CREATE  PROCEDURE Gp_QueryVipAddMoneyBillIndexAuditing
( 
	@StartDate		VARCHAR(25),
	@EndDate  		VARCHAR(25),
	@BillCode 		VARCHAR(200) = '',
	@BtypeId		VARCHAR(50)='',		--结算单位
	@EtypeId  		VARCHAR(50),
	@IfAudit		VARCHAR(2),			-- 审核的类型   -1.审核不通过  0.待审核   1.审核通过  2.没有审核  兼容以前草稿  AuditingBill 中的IfAudit
	@DTypeID  		VARCHAR(100) = '',	
	@Stypeid		varchar(50)='',
	@strCurrencyID	varchar(50)='',
	@checke			VARCHAR(50) = '',
	@BillType		VARCHAR(5)='181'
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @checke
--DECLARE @BillType VARCHAR(5)
--SET  @BillType='181'
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 分支机构
IF @Stypeid<>'' or @chvMStypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

-- 部门
IF @DTypeID<>'' or @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaseTypeId(@DTypeID,9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON (a.dTypeID = d.TypeID)'
	insert into #F_BaseGetManDetaildType values('')
END

-- 结算单位
CREATE TABLE #F_BaseGetManDetailBType1(TypeID varchar(100))
IF (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999')
BEGIN
	INSERT INTO #F_BaseGetManDetailBType1 SELECT TypeID FROM F_BaseGetManDetailBType(@chvOperatorID)
	INSERT INTO #F_BaseGetManDetailBType1(TypeID) VALUES('')
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailBType1 B1 ON ISNULL(a.BtypeID,'''') = B1.TypeID '
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON (a.ETypeID = E.TypeID) '
	insert into #F_BaseGetManDetailEType values('')
END

-- ******** 权限范围单独处理 - End ********

DECLARE @re 			int,	-- 修改他人草稿的权限
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@ReLimitPass 	int		-- 单据过帐权限

IF (@checke = '00001') 
	SET @re = 0
ELSE
BEGIN	
	EXEC @Re467 = GP_CheckLimit @checke,467  --查看他人业务草稿
	EXEC @re = GP_CheckLimit @checke,135  --修改草稿
	IF @Re467=1 SET @re=1 
	IF @re = 1 AND (@IfAudit = 0 OR @IfAudit = 1)
	BEGIN
		IF @IfAudit=0
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet
				WHERE BillType = @BillType AND IfUse = 1 AND LEFT(AuditingReason,1) <> 1)	-- 检查单据是否有审核流程
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet A,AuditingFlowDetail B
					WHERE A.AuditingID = B.AuditingID AND A.BillType = @BillType AND A.IfUse = 1
					AND LEFT(A.AuditingReason,1) <> 1 AND B.ETypeID = @checke)	-- 检测具体人针对具体的单据是否有审核流程
				BEGIN
					IF @Re467 = 0
						SET @re = 0
					ELSE
						SET @re = 1
				END
				ELSE
					IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail B,AuditingFlowSet A
						WHERE A.AuditingID = B.AuditingID AND B.ETypeID = @checke
						AND B.AuditingStep = 0 AND A.BillType = @BillType)	-- 检测用户是否具有特批人权限
					BEGIN
						IF @Re467 = 0
							SET @re = 0
						ELSE
							SET @re = 1
					END
			END
		END
		ELSE 
			SET @re = 0
	END
END


IF @re = 2 RETURN @re

DECLARE @IsExistFlowSet int
IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType AND IfUse = 1 AND Substring(AuditingReason,1,1)<>1)
	SELECT @IsExistFlowSet = 1
ELSE
	SELECT @IsExistFlowSet = 0
-----------------------------------------------------------------------------------------------
DECLARE @SQL varchar(MAX)
SET @SQL = '
			SELECT 
			a.BillNumberId,
			a.BillDate,
			a.BillCode,	
			a.Stypeid,
			a.DTypeId,
			a.etypeid,
			a.btypeid,		
			a.explain,
			a.comment,
			a.checke
'

SET @SQL = @SQL + '
	FROM	BillIndex a ' + @SQL_Man

IF @IfAudit = 2
	SET @SQL = @SQL + '
	WHERE	NOT EXISTS(
				SELECT ab.BillNumberID FROM AuditingBill ab
				WHERE a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 2
			) AND'
ELSE
	SET @SQL = @SQL + '
	INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 2 AND ab.IfAudit = ''' + @IfAudit + '''
	WHERE	1=1 AND '

IF @StartDate<>''
	SET @SQL = @SQL +' a.BillDate >= ''' + @StartDate + ''' AND '
IF 	@EndDate<>''
	SET @SQL = @SQL +' a.BillDate <= ''' + @EndDate + ''' AND '

SET @SQL = @SQL +' a.BillType = ''' + @BillType + ''''
	
SET @SQL = @SQL + ' AND a.IsIni=0 
					AND a.ifCheck=''f'' 
					AND a.Draft = 1 				   
					AND a.RedWord = 0'
IF @BillCode <> '' 
	SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
----------------------------胡小科2012-6-11 控制单据查看权限-------------------------------------	
DECLARE @viewOtherBillindex VARCHAR(2);
 SELECT @viewOtherBillindex=SUBSTRING(lim,467,1) FROM dbo.loginuser WHERE etypeid=@checke
	
IF (@viewOtherBillindex<> 1 
--超级管理员不判断该权限
AND @checke<>'00001')	
	SET @SQL = @SQL + ' AND ( a.Checke = ''' + @checke + ''' or a.checke='''' ) '
-----------------------------------------------------------------------------------

IF @BtypeId <> '' 
	SET @SQL = @SQL + ' AND a.btypeid=''' + @BtypeId + ''''
		
IF @ETypeID <> '' 
	SET @SQL = @SQL + ' AND a.ETypeID=''' + @ETypeID + ''''
	
IF @DTypeID <> '' 
	SET @SQL = @SQL + ' AND a.DTypeID=''' + @DTypeID + ''''
	
IF @strCurrencyID <> '' 		
	SET @SQL = @SQL + ' AND  a.CID =  ''' + @strCurrencyID + ''''
	
	
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC, a.BillCode'

PRINT(@SQL)
EXEC (@SQL)

IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' AND @BillType <> 177 DROP TABLE #F_BaseGetManDetailEType
IF @Stypeid<>'' or @chvMStypeid<>'00000' DROP TABLE #F_BaseGetManDetailSType
IF @DTypeID<>'' or @chvMDtypeid <>'00000' DROP TABLE #F_BaseGetManDetailDType 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_QueryWdOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_QueryWdOrder]
GO

/*
	作者:颜熙
	日期:2016-11-30
	描述:查询网店订单
*/
CREATE  PROCEDURE Gp_QueryWdOrder
(
	@bstype 	int , --单据类型 0：已发货单据 1：仅退款单据 2：退货单据 3：换货
	@startdate  varchar(50),--开始日期
	@enddate    varchar(50),--截止日期
	@eshopid    varchar(50),--网店名称
	@etypeid    varchar(50), --经手人
	@ordersourcecodes varchar(50),--原始网店订单编号
	@tradeids   varchar(50),  --网店单据编号
	@billGeneState INT, --单据生成状态 0：未生成 1：全部 2：已生成(过账) 3：草稿
	@billInfoState INT --0：正常，1：异常
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE @SQL VARCHAR(MAX),@bstypename VARCHAR(20)
	IF @bstype =0 SET @bstypename='已发货'
	ELSE IF @bstype=1 SET @bstypename='退款不退货'
	ELSE IF @bstype=2 SET @bstypename='退款退货'
	ELSE IF @bstype=3 SET @bstypename='换货'
		BEGIN
			IF @billGeneState = 3 --草稿
				BEGIN
					SET @SQL='SELECT 
					wo.*,
					CONVERT(VARCHAR(100),CAST(wo.datetime AS DATETIME),23 ) AS datetiemN,
					case draft
					when 0 then ''已过账''
					when 1 then ''已生成草稿''
					end
					as billstate,
					b.BillCode as billnumber,
					b.billnumberid
					FROM WdOrder wo
					inner join WdShopBillRelation wb on wo.wdbillnumber=wb.WdShopBillID
					inner join BillIndex b on b.BillNumberId=wb.Billnumberid
					where draft = 1 and wo.[datetime] >='''+ @startdate+''' and wo.[datetime] <='''+@enddate+''' and wo.[isexception] ='''+CAST(@billInfoState AS VARCHAR(10))+''' and wo.BillType='''+@bstypename+''''
					
					IF @etypeid IS NOT NULL AND @etypeid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.employeeid ='''+@etypeid+''''
							--select @SQL
						END
					IF @eshopid IS NOT NULL AND @eshopid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.wdname ='''+@eshopid+''''
							--select @SQL
						END
					IF @ordersourcecodes IS NOT NULL AND @ordersourcecodes <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.ordernumber like ''%'+@ordersourcecodes+'%'''
						END
					IF @tradeids IS NOT NULL AND @tradeids <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.wdbillnumber like ''%'+@tradeids+'%'''
						END
						--SELECT @SQL
				--	EXEC(@SQL)
				END
			IF @billGeneState = 2 --过账
				BEGIN
					SET @SQL='SELECT 
					wo.*,
					CONVERT(VARCHAR(100),CAST(wo.datetime AS DATETIME),23 ) AS datetiemN,
					case draft
					when 0 then ''已过账''
					when 1 then ''已生成草稿''
					end
					as billstate,
					b.BillCode as billnumber,
					b.billnumberid
					FROM WdOrder wo
					inner join WdShopBillRelation wb on wo.wdbillnumber=wb.WdShopBillID
					inner join BillIndex b on b.BillNumberId=wb.Billnumberid
					where draft = 0 and wo.[datetime] >='''+ @startdate+''' and wo.[datetime] <='''+@enddate+''' and wo.[isexception] ='''+CAST(@billInfoState AS VARCHAR(10))+''' and wo.BillType='''+@bstypename+''''
					
					IF @etypeid IS NOT NULL AND @etypeid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.employeeid ='''+@etypeid+''''
							--select @SQL
						END
					IF @eshopid IS NOT NULL AND @eshopid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.wdname ='''+@eshopid+''''
							--select @SQL
						END
					IF @ordersourcecodes IS NOT NULL AND @ordersourcecodes <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.ordernumber like ''%'+@ordersourcecodes+'%'''
						END
					IF @tradeids IS NOT NULL AND @tradeids <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.wdbillnumber like ''%'+@tradeids+'%'''
						END
						--SELECT @SQL
				--	EXEC(@SQL)
				END
			IF  @billGeneState=1
				BEGIN
					SET @SQL='SELECT 
					wo.*,
					CONVERT(VARCHAR(100),CAST(wo.datetime AS DATETIME),23 ) AS datetiemN,
					case draft
					when 0 then ''已过账''
					when 1 then ''已生成草稿''
					end
					as billstate,
					b.BillCode as billnumber,
					b.billnumberid
					FROM WdOrder wo
					inner join WdShopBillRelation wb on wo.wdbillnumber=wb.WdShopBillID
					inner join BillIndex b on b.BillNumberId=wb.Billnumberid
					where wo.[datetime] >='''+ @startdate+''' and wo.[datetime] <='''+@enddate+''' and wo.[isexception] ='''+CAST(@billInfoState AS VARCHAR(10))+''' and wo.BillType='''+@bstypename+''''
					
					IF @etypeid IS NOT NULL AND @etypeid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.employeeid ='''+@etypeid+''''
							--select @SQL
						END
					IF @eshopid IS NOT NULL AND @eshopid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.wdname ='''+@eshopid+''''
							--select @SQL
						END
					IF @ordersourcecodes IS NOT NULL AND @ordersourcecodes <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.ordernumber like ''%'+@ordersourcecodes+'%'''
						END
					IF @tradeids IS NOT NULL AND @tradeids <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.wdbillnumber like ''%'+@tradeids+'%'''
						END
						--SELECT @SQL
				--	EXEC(@SQL)
				END
			IF @billGeneState = 0 OR @billGeneState ='' OR @billGeneState IS NULL
				BEGIN
					SET @SQL='SELECT 
					wo.*,
					CONVERT(VARCHAR(100),CAST(wo.datetime AS DATETIME),23 ) AS datetiemN,
					''未生成''
					as billstate,
					'''' as billnumber,
					-9999 as billnumberid
					FROM WdOrder as wo
					where wdbillnumber not in (select wdshopbillid from WdShopBillRelation) and wo.[datetime] >='''+ @startdate+''' and wo.[datetime] <='''+@enddate+''' and wo.[isexception] ='''+CAST(@billInfoState AS VARCHAR(10))+''' and wo.BillType='''+@bstypename+''''
					
					IF @etypeid IS NOT NULL AND @etypeid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.employeeid ='''+@etypeid+''''
							--select @SQL
						END
					IF @eshopid IS NOT NULL AND @eshopid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.wdname ='''+@eshopid+''''
							--select @SQL
						END
					IF @ordersourcecodes IS NOT NULL AND @ordersourcecodes <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.ordernumber like ''%'+@ordersourcecodes+'%'''
						END
					IF @tradeids IS NOT NULL AND @tradeids <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.wdbillnumber like ''%'+@tradeids+'%'''
						END
						--SELECT @SQL
				--	EXEC(@SQL)
				END
			IF @billGeneState = 1
				BEGIN
					SET @SQL=@SQL + '
					UNION ALL
					SELECT 
					wo.*,
					CONVERT(VARCHAR(100),CAST(wo.datetime AS DATETIME),23 ) AS datetiemN,
					''未生成''
					as billstate,
					'''' as billnumber,
					-9999 as billnumberid
					FROM WdOrder as wo
					where wdbillnumber not in (select wdshopbillid from WdShopBillRelation) and wo.[datetime] >='''+ @startdate+''' and wo.[datetime] <='''+@enddate+''' and wo.[isexception] ='''+CAST(@billInfoState AS VARCHAR(10))+''' and wo.BillType='''+@bstypename+''''
					
					IF @etypeid IS NOT NULL AND @etypeid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.employeeid ='''+@etypeid+''''
							--select @SQL
						END
					IF @eshopid IS NOT NULL AND @eshopid <> ''
						BEGIN
							SET @SQL=@SQL +' and wo.wdname ='''+@eshopid+''''
							--select @SQL
						END
					IF @ordersourcecodes IS NOT NULL AND @ordersourcecodes <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.ordernumber like ''%'+@ordersourcecodes+'%'''
						END
					IF @tradeids IS NOT NULL AND @tradeids <> ''
						BEGIN
							SET @SQL=@SQL+' and wo.wdbillnumber like ''%'+@tradeids+'%'''
						END
						--SELECT @SQL
				--	EXEC(@SQL)
				END
			EXEC(@SQL)
		END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Raise_Ac_Items_From_OldData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Raise_Ac_Items_From_OldData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-06-01
	描述：升级老的会计科目数据
	TRUNCATE TABLE Ac_Items
	EXEC Gp_Raise_Ac_Items_From_OldData
	SELECT * FROM Ac_Items WHERE STypeId = '00001'
*/
CREATE PROCEDURE Gp_Raise_Ac_Items_From_OldData
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE ISNULL(TypeId,'') = '')
	OR NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items)
BEGIN
	--建立标注预制数据主表
	DECLARE @Ac_Items_Standard TABLE 
	(
		nId           INT NOT NULL,
		TypeId        VARCHAR (50) NOT NULL,
		ParId         VARCHAR (50) NOT NULL,
		Leveal        INT NOT NULL,
		SonNum        INT NOT NULL,
		SonCount      INT NOT NULL,
		UserCode      VARCHAR (200) NOT NULL,
		FullName      VARCHAR (200) NOT NULL,
		Name          VARCHAR (200) NULL,
		CreateBank    VARCHAR (400) NULL,
		IsBank        INT NULL,
		Comment       VARCHAR (400) NULL,
		PyCode        VARCHAR (200) NULL,
		Deleted       INT DEFAULT ((0)) NOT NULL,
		TypeName      VARCHAR (2) NULL,
		XiWaMaxNumber INT DEFAULT ((1)) NULL,
		BankType      VARCHAR (400) DEFAULT ('') NULL,
		Sysrow        INT DEFAULT ((0)) NULL,
		IsModify      INT DEFAULT ((0)) NULL
	)
	--现金
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(1,'','',1,0,0,'1001','现金',1,0,'B','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(2,'','',1,0,0,'5288','银行存款-中国银行',1,1,'B','','',1,'','',0)
	--收入
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(3,'','',1,0,0,'0321','商品报溢收入',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(4,'','',1,0,0,'0322','商品获赠收入',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(5,'','',1,0,0,'0323','成本调价收入',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(6,'','',1,0,0,'0324','采购退货差价',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(7,'','',1,0,0,'0325','变价调拨差价',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(8,'','',1,0,0,'0326','商品拆装差价',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(9,'','',1,0,0,'0328','商品维修收入',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(10,'','',1,0,0,'0329','受托退货差价',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(11,'','',1,0,0,'5101','销售收入',1,0,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(12,'','',1,0,0,'5103','返点获利收入',1,0,'G','','',0,'','',0)
	--以上项目单据上默认不出,业务凭证除外
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(13,'','',1,0,0,'0332','利息收入',1,1,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(14,'','',1,0,0,'0333','其他收入',1,1,'G','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(15,'','',1,0,0,'03333','调账收入',1,0,'G','','',0,'','',0)

	--支出,费用
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(16,'','',1,0,0,'0404','销售折扣返利支出',1,0,'E','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(17,'','',1,0,0,'0421','商品报损',1,0,'E','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(18,'','',1,0,0,'0422','商品赠出',1,0,'E','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(19,'','',1,0,0,'0423','商品维修支出',1,0,'E','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(20,'','',1,0,0,'0424','商品送修支出',1,0,'E','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(21,'','',1,0,0,'5401','销售成本',1,0,'E','','',0,'','',0)
	--以上项目单据上默认不出,业务凭证除外
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(22,'','',1,0,0,'0431','调账亏损',1,0,'E','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(23,'','',1,0,0,'0455','其他支出',1,1,'E','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(24,'','',1,0,0,'0456','优惠/抹零金额',1,0,'E','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(25,'','',1,0,0,'0432','固定资产折旧',1,0,'E','','',0,'','',0)

	--固定资产
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(26,'','',1,0,0,'1501','固定资产',1,1,'F','','',0,'','',0)

	--资产
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(27,'','',1,0,0,'1151','预付资金',1,0,'C','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(28,'','',1,0,0,'1132','内部应收',1,0,'C','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(29,'','',1,0,0,'1133','其他应收',1,0,'C','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(30,'','',1,0,0,'1241','库存商品总值',1,0,'C','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(31,'','',1,0,0,'1261','委托代销商品',1,0,'C','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(32,'','',1,0,0,'1301','待摊费用',1,0,'C','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(33,'','',1,0,0,'987','应收合计',1,0,'C','','',0,'','',0)
	--负债
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(34,'','',1,0,0,'2181','会员储值',1,0,'L','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(35,'','',1,0,0,'2121','应付合计',1,0,'L','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(36,'','',1,0,0,'2132','其他应付',1,0,'L','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(37,'','',1,0,0,'2141','代销商品',1,0,'L','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(38,'','',1,0,0,'2171','应交税金',1,0,'L','','',0,'','',0)
	INSERT INTO @Ac_Items_Standard(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(39,'','',1,0,0,'2131','预收资金',1,0,'L','','',0,'','',0)
		
	--建立主表
	DECLARE @Ac_Items TABLE 
	(
		nId           INT NOT NULL,
		TypeId        VARCHAR (50) NOT NULL,
		ParId         VARCHAR (50) NOT NULL,
		Leveal        INT NOT NULL,
		SonNum        INT NOT NULL,
		SonCount      INT NOT NULL,
		UserCode      VARCHAR (200) NOT NULL,
		FullName      VARCHAR (200) NOT NULL,
		Name          VARCHAR (200) NULL,
		CreateBank    VARCHAR (400) NULL,
		IsBank        INT NULL,
		Comment       VARCHAR (400) NULL,
		PyCode        VARCHAR (200) NULL,
		Deleted       INT DEFAULT ((0)) NOT NULL,
		TypeName      VARCHAR (2) NULL,
		XiWaMaxNumber INT DEFAULT ((1)) NULL,
		BankType      VARCHAR (400) DEFAULT ('') NULL,
		Sysrow        INT DEFAULT ((0)) NULL,
		IsModify      INT DEFAULT ((0)) NULL
	)
	
	--先清除预制的数据	
	TRUNCATE TABLE Ac_Items
	TRUNCATE TABLE Ac_Items_Detail
	
	--先写标准数据
	INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)
	SELECT nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted FROM @Ac_Items_Standard
	
	--客户自建的会计科目需要处理
	DECLARE @upATypeId	VARCHAR(50),
			@nIdAc		INT,
			@upUserCode VARCHAR(200),
			@upFullName VARCHAR(500),
			@upDeleted  VARCHAR(10),
			@upComment	VARCHAR(400),
			@upSysrow	INT
			
	DECLARE AType_Up_Cursor CURSOR FOR
		SELECT	TypeId,
				UserCode,
				FullName,
				Deleted,
				Comment,
				sysrow
		FROM	AType 
		WHERE	sonnum = 0 
				AND TypeId NOT IN ('0000500001','0000500002','0000500003','0000500004','0000500005','0000100003','0000100004')
				AND FullName NOT LIKE '%『%'
				AND UserCode NOT IN (SELECT UserCode FROM @Ac_Items)
	OPEN AType_Up_Cursor
	FETCH NEXT FROM AType_Up_Cursor INTO @upATypeId,@upUserCode,@upFullName,@upDeleted,@upComment,@upSysrow
	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		--判断新项目表时候有编号相同的情况
		IF EXISTS(SELECT TOP 1 1 FROM @Ac_Items WHERE UserCode = @upUserCode)
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE UserCode = @upUserCode AND (ISNULL(TypeId,'')='' OR ISNULL(ParId,'')=''))
					BEGIN
						UPDATE Ac_Items SET UserCode+='&'+CAST(nId AS VARCHAR(50)) WHERE UserCode=@upUserCode
					END
				ELSE 
					SET @upUserCode = @upUserCode + '&' + @upATypeId
			END
		--判断新项目表时候有编号相同的情况
		IF EXISTS(SELECT TOP 1 1 FROM @Ac_Items WHERE FullName = @upFullName)
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE FullName = @upFullName AND (ISNULL(TypeId,'')='' OR ISNULL(ParId,'')=''))
					BEGIN
							UPDATE Ac_Items SET FullName+='&'+CAST(nId AS VARCHAR(50)) WHERE FullName=@upFullName
					END
				ELSE 
					SET @upFullName = @upFullName + '&' + @upATypeId
			END
			
		IF LEFT(@upATypeId,5) = '00001'	--【资产合计】
		BEGIN			
			IF LEFT(@upATypeId,LEN('0000100004')) = '0000100004'
			BEGIN
				IF @upATypeId <> '000010000400001'
					INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@upATypeId,'',1,0,0,@upUserCode,@upFullName,@upSysrow,1,'B','','',1,@upComment,'',@upDeleted)
			END
			ELSE IF LEFT(@upATypeId,LEN('0000100002')) = '0000100002'
				INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@upATypeId,'',1,0,0,@upUserCode,@upFullName,@upSysrow,1,'F','','',0,@upComment,'',@upDeleted)
			ELSE	
				INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@upATypeId,'',1,0,0,@upUserCode,@upFullName,@upSysrow,1,'C','','',0,@upComment,'',@upDeleted)
		END
		IF LEFT(@upATypeId,5) = '00002'	--【负债合计】
		BEGIN
			INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@upATypeId,'',1,0,0,@upUserCode,@upFullName,@upSysrow,1,'L','','',0,@upComment,'',@upDeleted)
		END
		IF LEFT(@upATypeId,5) = '00003'	--【收入类】
		BEGIN
			INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@upATypeId,'',1,0,0,@upUserCode,@upFullName,@upSysrow,1,'G','','',0,@upComment,'',@upDeleted)				
		END
		IF LEFT(@upATypeId,5) = '00004'	--【支出类】
		BEGIN
			INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@upATypeId,'',1,0,0,@upUserCode,@upFullName,@upSysrow,1,'E','','',0,@upComment,'',@upDeleted)
		END
		IF LEFT(@upATypeId,5) = '00005'	--【所有者权益】
		BEGIN
			PRINT('所有者权益')
		END
		
		FETCH NEXT FROM AType_Up_Cursor INTO @upATypeId,@upUserCode,@upFullName,@upDeleted,@upComment,@upSysrow
	END
	CLOSE AType_Up_Cursor
	DEALLOCATE AType_Up_Cursor
	
	UPDATE	@Ac_Items 
	SET		TypeId = A.TypeId,
			ParId = A.Parid
	FROM	@Ac_Items I
	INNER JOIN AType A ON I.UserCode = A.UserCode
	WHERE	A.sonnum = 0				
	
	--======================得到atype里面与@Ac_Items里面usercode重复的数据 by:glj date:2012-12-18==============================
	--客户自建的会计科目与系统默认数据UserCode重复需要处理
	DECLARE @reTypeID		VARCHAR(50),
			@reParId		VARCHAR(50),
			@reUserCode		VARCHAR(200),
			@reFullName		VARCHAR(500),
			@reDeleted		VARCHAR(10),
			@reComment		VARCHAR(400),
			@reSysrow		INT
			
	DECLARE AType_Repeat_Cursor CURSOR FOR
		SELECT	TypeId,
				UserCode,
				FullName,
				Deleted,
				ParId,
				Comment,
				sysrow
		FROM	AType 
		WHERE	sonnum = 0
				AND TypeId NOT IN (SELECT TypeId FROM @Ac_Items)
	
	OPEN AType_Repeat_Cursor
	FETCH NEXT FROM AType_Repeat_Cursor INTO @reTypeID,@reUserCode,@reFullName,@reDeleted,@reParId,@reComment,@reSysrow
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--判断新项目表时候有编号相同的情况
		IF EXISTS(SELECT TOP 1 1 FROM @Ac_Items WHERE UserCode = @reUserCode)
			SET @reUserCode = @reUserCode + '&' + @reTypeID
		--判断新项目表时候有编号相同的情况
		IF EXISTS(SELECT TOP 1 1 FROM @Ac_Items WHERE FullName = @reFullName)
			SET @reFullName = @reFullName + '&' + @reTypeID
			
		IF LEFT(@reTypeID,5) = '00001'	--【资产合计】
		BEGIN			
			IF LEFT(@reTypeID,LEN('0000100004')) = '0000100004'
			BEGIN
				IF(@reTypeID<>'000010000400001')
					INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@reTypeID,@reParId,1,0,0,@reUserCode,@reFullName,@reSysrow,1,'B','','',1,@reComment,'',@reDeleted)
			END
			ELSE IF LEFT(@reTypeID,LEN('0000100002')) = '0000100002'
				INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@reTypeID,@reParId,1,0,0,@reUserCode,@reFullName,@reSysrow,1,'F','','',0,@reComment,'',@reDeleted)
			ELSE	
				INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@reTypeID,@reParId,1,0,0,@reUserCode,@reFullName,@reSysrow,1,'C','','',0,@reComment,'',@reDeleted)
		END
		IF LEFT(@reTypeID,5) = '00002'	--【负债合计】
		BEGIN
			INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@reTypeID,@reParId,1,0,0,@reUserCode,@reFullName,@reSysrow,1,'L','','',0,@reComment,'',@reDeleted)
		END
		IF LEFT(@reTypeID,5) = '00003'	--【收入类】
		BEGIN
			INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@reTypeID,@reParId,1,0,0,@reUserCode,@reFullName,@reSysrow,1,'G','','',0,@reComment,'',@reDeleted)				
		END
		IF LEFT(@reTypeID,5) = '00004'	--【支出类】
		BEGIN
			INSERT INTO @Ac_Items(nId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Sysrow,IsModify,TypeName,Name,CreateBank,IsBank,Comment,PyCode,Deleted)VALUES(0,@reTypeID,@reParId,1,0,0,@reUserCode,@reFullName,@reSysrow,1,'E','','',0,@reComment,'',@reDeleted)
		END
		IF LEFT(@reTypeID,5) = '00005'	--【所有者权益】
		BEGIN
			PRINT('所有者权益')
		END
		
		FETCH NEXT FROM AType_Repeat_Cursor INTO @reTypeId,@reUserCode,@reFullName,@reDeleted,@reParId,@reComment,@reSysrow
	END
	CLOSE AType_Repeat_Cursor
	DEALLOCATE AType_Repeat_Cursor
	
	--单独处理NId=2的项目
	IF EXISTS(SELECT 1 FROM Atype WHERE TypeID='000010000400001')
		BEGIN
			DECLARE 
					@NidTypeID VARCHAR(50),
					@NidParId VARCHAR(50),
					@NidUserCode VARCHAR(200),
					@NidFullName VARCHAR(200),
					@NidComment	VARCHAR(400),
					@NidSysrow	INT
					
			SELECT @NidTypeID=typeId,@NidParId=parid,@NidUserCode=UserCode,@NidFullName=FullName,@NidComment=Comment,@NidSysrow=sysrow  FROM Atype WHERE TypeID='000010000400001'
				
			UPDATE @Ac_Items SET TypeId = @NidTypeID,ParId =@NidParId,UserCode =@NidUserCode,FullName = @NidFullName ,Comment=@NidComment,Sysrow=@NidSysrow
			WHERE nid=2
		END
	--=======================================================================
	
	
	--*************关键点【处理科目nID】 开始*************--	
	DECLARE @UserCode	VARCHAR(400),
			@MaxNid		INT
			
	DECLARE Ac_Items_Cursor_B CURSOR FOR
		SELECT UserCode FROM @Ac_Items WHERE nId = 0
		
	OPEN Ac_Items_Cursor_B
	
	FETCH NEXT FROM Ac_Items_Cursor_B INTO @UserCode
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT @MaxNid = MAX(nId)+1 FROM @Ac_Items
		UPDATE @Ac_Items SET nId = @MaxNid WHERE UserCode = @UserCode
	
		FETCH NEXT FROM Ac_Items_Cursor_B INTO @UserCode
	END
	
	CLOSE Ac_Items_Cursor_B
	DEALLOCATE Ac_Items_Cursor_B
	
	SET IDENTITY_INSERT Ac_Items OFF
	
	INSERT INTO Ac_Items(TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,CreateBank,IsBank,Comment,PyCode,Deleted,TypeName,XiWaMaxNumber,BankType,Sysrow,IsModify)
	SELECT	TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,CreateBank,IsBank,Comment,PyCode,Deleted,TypeName,XiWaMaxNumber,BankType,Sysrow,IsModify
	FROM	@Ac_Items
	
	SET IDENTITY_INSERT Ac_Items ON
	
	--写入明细数据
	IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items_Detail)
	BEGIN
		DECLARE @nId INT
		
		DECLARE Ac_Items_Cursor CURSOR FOR
			SELECT nId FROM Ac_Items ORDER BY nId
			
		OPEN Ac_Items_Cursor
		
		FETCH NEXT FROM Ac_Items_Cursor INTO @nId
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO Ac_Items_Detail(nId,STypeId,ATypeId,DepATypeId,DisATypeId)
			SELECT	@nId AS nId,TypeId AS STypeId,'' AS ATypeId,'' AS DepATypeId,'' AS DisATypeId
			FROM	SType
			WHERE	SonNum = 0
			
			FETCH NEXT FROM Ac_Items_Cursor INTO @nId
		END
		
		CLOSE Ac_Items_Cursor
		DEALLOCATE Ac_Items_Cursor
	END	
		
	--处理会计期间
	IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period)
	BEGIN
		DECLARE @Year	VARCHAR(10),
				@TMonth VARCHAR(10)
				
		SET @Year = YEAR(GETDATE())
		SET @TMonth = @Year + '-02-29'
		
		IF ISDATE(@TMonth) <> 1
			SET @TMonth = @Year + '-02-28'		
		
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,1, @Year + '-01-01',@Year + '-01-31',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,2, @Year + '-02-01',@TMonth,0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,3, @Year + '-03-01',@Year + '-03-31',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,4, @Year + '-04-01',@Year + '-04-30',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,5, @Year + '-05-01',@Year + '-05-31',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,6, @Year + '-06-01',@Year + '-06-30',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,7, @Year + '-07-01',@Year + '-07-31',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,8, @Year + '-08-01',@Year + '-08-31',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,9, @Year + '-09-01',@Year + '-09-30',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,10,@Year + '-10-01',@Year + '-10-31',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,11,@Year + '-11-01',@Year + '-11-30',0,0)
		INSERT INTO Ac_Period (FYear, FMonth, IsNature, NatureCount, FPeriod, FBegin, FEnd, Deleted, IsDynamic)VALUES (@Year,'1',1,12,12,@Year + '-12-01',@Year + '-12-31',0,0)
		
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'fyear')
			UPDATE sysdata SET SubValue = @Year WHERE SubName = 'fyear'
		ELSE
			INSERT INTO sysdata values('718','fyear',@Year,null)
			
		UPDATE sysdata SET SubValue = 1 WHERE SubName = 'FPeriod'
	END
	
	--启用账套
	UPDATE sysdata SET SubValue = '1' WHERE SubName = 'isinvocation'
	
	--处理非常规数据
	UPDATE Ac_Items SET BankType = '' WHERE BankType IS NULL
END		

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_ReAuditedAcVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_ReAuditedAcVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查询反审核
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_ReAuditedAcVoucherBill
(
	@BillNumberId	VARCHAR(50)='',			--单据ID
	@OpertionId		VARCHAR(50)=''			--当前操作人	
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@fchecked		VARCHAR(2)='',
	@recheckid		VARCHAR(2)='',
	@ifcheck		VARCHAR(2)='',
    @markerror		VARCHAR(200)='',
    @Opertion		VARCHAR(50)='',
	@ErrorCount		INT=0 --审核 复核 过账 错误条数
	
SELECT 
	@fchecked=ISNULL(FChecked,''),
	@recheckid=ISNULL(ReCheckId,''),
	@ifcheck=ISNULL(IfCheck,''),
    @markerror=ISNULL(markerror,''),
    @Opertion=ISNULL(AuditId,'')
FROM Ac_Voucher
WHERE BillNumberId=@BillNumberId 
		 
IF @@ROWCOUNT = 0--判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN -1
END
IF(@Opertion<>@OpertionId)
	BEGIN
		RAISERROR('您选择的凭证审核人与反审核人不为同一人！请确认后重试！',16,1)
		RETURN -1
	END

IF(@ifcheck='t')
	BEGIN
		RAISERROR('凭证已经记账!请确认！',16,1)--记账
		RETURN -1
	END
IF(@fchecked='0')
	BEGIN
		RAISERROR('凭证未审核!请确认！',16,1)--/审核
		RETURN -1
	END
IF(@fchecked='-1')
	BEGIN
		RAISERROR('凭证已经作废!请确认！',16,1)--/作废
		RETURN -1
	END

IF(@markerror<>'')
	BEGIN
		RAISERROR('凭证已经标错!请确认！',16,1)--/审核
		RETURN -1
	END	
	
UPDATE Ac_Voucher SET FChecked=0,AuditId=NULL,RChecker=@OpertionId WHERE BillNumberId=@BillNumberID --反审核 记账凭证主表
SET @ErrorCount+=@@ERROR

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='反审核凭证单据错误，请确认！'
		RAISERROR(@MSG2,16,1)
		RETURN -1
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReCalBrandarArAp_YearProcDateTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_ReCalBrandarArAp_YearProcDateTime]
GO


/*
	品牌应收 指定时间年结存 重新计算
	应收款单据和结算单据在同一时间段 
*/						
CREATE   PROCEDURE GP_ReCalBrandarArAp_YearProcDateTime
(
	@yearendDatetime VARCHAR(20)			--   -年结存的日期		
)
--@encode$--
AS	
	DECLARE @ExpenseToAr INT=0
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';
	DECLARE	@YS_ID INT
	SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE FullName='预收资金';		

	
	INSERT INTO #BrandarARAPTotal
	(		
			BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			ARTotal ,
			YSTotal ,
			nARTotal ,
			nYSTotal,
			Total,
			NTotal
	)
	SELECT	BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal),
			SUM(YSTotal),
			SUM(nARTotal),
			SUM(nYSTotal),
			0,
			0
	FROM (		     	
		--销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0 AND b.billtype=11
			     AND b.billdate <@yearendDatetime
			         AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		 UNION ALL      
		--组合品销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.PT_Combin_SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0 AND b.billtype=12
			       AND b.billdate <@yearendDatetime
			         AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL
		--销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntaxtotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.salebackbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0 AND b.billtype=45
			       AND b.billdate <@yearendDatetime
			         AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--组合品销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntaxtotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.PT_Combin_SaleBackBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0 AND b.billtype=46
				AND  b.billdate <@yearendDatetime 
				  AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--销售换货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN s.InOrOut='O' THEN  s.taxtotal 
										ELSE -( s.taxtotal )
										END AS  ARTotal,
				0 AS YSTotal ,
				CASE WHEN s.InOrOut='O' THEN  s.ntaxtotal
										ELSE -(s.ntaxtotal)
										END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.salegoodsexchangebill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0 AND b.billtype=160
			   AND  b.billdate <@yearendDatetime 
			     AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--委托代销结算单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.commissionbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0 AND  b.billtype=141
				   AND  b.billdate <@yearendDatetime 
				     AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--销售发货开票
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal AS  ARTotal,
				0 AS YSTotal ,
				s.ntaxtotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.ReceiptBill s
			INNER JOIN  ReceiptBillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0 AND b.billtype=405
			      AND  b.billdate <@yearendDatetime 
			        AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--预收款
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS  ARTotal,
				s.total AS YSTotal ,
				0 AS nARTotal ,
				s.ntotal AS nYSTotal 
			FROM dbo.prebill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0 
			      AND b.billtype=189 
			      AND ISNULL( B.NChargeOffTotal,0)=0 	
			      AND ISNULL(s.BrandarTypeId,'') <> ''
			      AND  b.billdate <@yearendDatetime 
			        AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--应收增加单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				s.total AS  ARTotal,
				0 AS YSTotal ,
				s.ntotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.billtype=116 				
			      AND ISNULL(s.BrandarTypeId,'') <> ''
			      AND  b.billdate <@yearendDatetime 
			        AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--应收减少单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				-(s.total) AS  ARTotal,
				0 AS YSTotal ,
				-(s.ntotal) AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.billtype=115 
			      AND ISNULL(s.BrandarTypeId,'') <> ''
			      AND  b.billdate <@yearendDatetime 
			        AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--其他收入单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.total AS  ARTotal,
				0 AS YSTotal ,
				s.NTotal AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
			WHERE b.IsIni=0
			      AND b.billtype=93 
			      AND ISNULL(s.BrandarTypeId,'') <> ''
			      AND  b.billdate <@yearendDatetime 
			        AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'
		UNION ALL 
		--费用单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.total
					  ELSE 0
					  END  AS  ARTotal,
				0 AS YSTotal ,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.NTotal
					  ELSE 0
					  END  AS nARTotal ,
				0 AS nYSTotal 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE b.IsIni=0
				  AND b.billtype=93 
			      AND ISNULL(s.BrandarTypeId,'') <> ''
			      AND  b.billdate <@yearendDatetime 
			        AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t' 
		UNION ALL
		--业务凭证
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.atypeid,
				s.CID,
				CASE  WHEN s.TypeATypeID=33  THEN s.J_Total-s.D_Total ELSE 0 END ARTotal,
				CASE  WHEN s.TypeATypeID=39  THEN s.D_Total-s.J_Total ELSE 0 END YSTotal,
				CASE  WHEN s.TypeATypeID=33  THEN s.NJ_Total-s.ND_Total ELSE 0 END nARTotal,
				CASE  WHEN s.TypeATypeID=39  THEN s.ND_Total-s.NJ_Total ELSE 0 END nYSTotal
		FROM	dbo.AccountCredence s
		INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
		INNER JOIN btype bt on s.ATypeID=bt.typeid and bt. IsUseBrandarType=1	
		WHERE b.IsIni=0
		      AND b.billtype=159	
		      AND ISNULL(s.BrandarTypeId,'') <> ''	
		      AND  b.billdate <@yearendDatetime 
		       AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'			      
		UNION ALL 
		--收款单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.total+s.PreferenceMoney) AS  ARTotal,
				CASE WHEN s.AtypeId=@YS_ID THEN -s.total ELSE 0 END AS YSTotal ,--预收 不包含优惠
				-(s.ntotal+s.NPreferenceMoney )AS nARTotal ,
				CASE WHEN s.AtypeId=@YS_ID THEN  -s.ntotal ELSE 0 END  AS nYSTotal  
			FROM dbo.gatheringbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1	
			WHERE b.IsIni=0
			      AND b.billtype=4
			      AND ISNULL(s.BrandarTypeId,'') <> ''
			      AND B.isByBrandarType=1 --勾选了 按品牌收款 才算品牌往来
			      AND  b.billdate <@yearendDatetime 
			       AND b.RedWord=0
			      AND b.draft=0
			      AND b.ifcheck='t'	
		UNION ALL 
		--从多账户取出来的
		SELECT  b.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN b.billtype IN (215,45,142,46)
					 THEN (b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
					 WHEN b.billtype =36  THEN CASE WHEN  b.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
													THEN (b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
													ELSE 0
													END 
						 
					 ELSE -(b.PreferenceMoney+b.TotalInMoney+b.YSTotalInMoney )
				END AS ARTotal,				
				CASE WHEN b.billtype IN (11,12,160,141,93,405) 
					THEN -(b.YSTotalInMoney  )
					ELSE b.YSTotalInMoney 
				END AS YSTotal,
				CASE WHEN b.billtype IN (215,45,142,46)
					 THEN(b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
					 WHEN b.billtype =36 THEN CASE WHEN  b.btypeid like '00001%' AND @ExpenseToAr=1 --费用单
													THEN (b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
													ELSE 0 
													END 			
					 ELSE -(b.nPreferenceMoney+b.nTotalInMoney+b.NYSTotalInMoney )
				END AS nARTotal,
				CASE WHEN b.billtype IN (11,12,160,141,93,405) 
					THEN -(b.NYSTotalInMoney  )
					ELSE b.NYSTotalInMoney 
				END AS nYSTotal
		FROM	dbo.BillMulBrand b
		INNER JOIN  BillIndex bil ON b.billnumberid=bil.billnumberid AND b.billtype=bil.billtype
		INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
		WHERE	bil.billdate <@yearendDatetime 	
				AND b.isini=0 
				AND  b.BillType  NOT IN (305,215)
				 AND bil.RedWord=0
			      AND bil.draft=0
			      AND bil.ifcheck='t'
			UNION ALL 
		--从多账户取出来的
		SELECT  b.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS ARTotal,				
				CASE WHEN b.billtype IN (305) 
					THEN -(b.YSTotalInMoney  )
					ELSE b.YSTotalInMoney 
				END AS YSTotal,
				0 AS nARTotal,
				CASE WHEN b.billtype IN (305) 
					THEN -(b.NYSTotalInMoney  )
					ELSE b.NYSTotalInMoney 
				END AS nYSTotal
		FROM	dbo.BillMulBrand b
		INNER JOIN  BillIndex bil ON b.billnumberid=bil.billnumberid AND b.billtype=bil.billtype
		INNER JOIN btype bt on b.btypeid=bt.typeid and bt. IsUseBrandarType=1
		WHERE	bil.billdate <@yearendDatetime 	
				AND b.isini=0 
				AND  b.BillType   IN (305,215)
				 AND bil.RedWord=0
			      AND bil.draft=0
			      AND bil.ifcheck='t'
	     	
		
	)total
	GROUP BY BrandarTypeID,stypeid,btypeid,cid
	

    DELETE FROM #BrandarARAPTotal 
    WHERE YSTotal=0  AND ARTotal=0  AND nYSTotal=0 
    AND nARTotal=0  
	-- 写入 brandar_ArApTotal 
	UPDATE	b 
	SET		b.ARTotal00=ISNULL(a.ARTotal00,0),
			b.YSTotal00=ISNULL(a.YSTotal00,0),
			b.nARTotal00=ISNULL(a.nARTotal00,0),
			b.nYSTotal00=ISNULL(a.nYSTotal00,0)
		
	FROM  #BrandarARAPTotal b JOIN dbo.brandar_ArApTotal a  
	ON a.stypeid=b.stypeid AND a.btypeid=b.btypeid AND a.CID=b.cid and a.BrandarTypeID=b.BrandarTypeID
	
	--SELECT * FROM #BrandarARAPTotal
	INSERT INTO #BrandarARAPTotal (
		BTypeID,
		STypeID,
		BrandarTypeID,
		CID,
		ARTotal,
		YSTotal,
		ARTotal00,
		YSTotal00,
		nARTotal,
		nYSTotal,
		nARTotal00,
		nYSTotal00

	) SELECT 
		b.btypeId,
		b.stypeid,
		b.BrandarTypeID,
		b.cid,
		0 AS ARTotal,
		0 AS YSTotal,
		b.ARTotal00,
		b.YSTotal00,
		0 AS nARTotal,
		0 AS nYSTotal,
		b.nARTotal00,
		b.nYSTotal00
		
	FROM brandar_ArApTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM #BrandarARAPTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid AND a.BrandarTypeID=b.BrandarTypeID)

	DELETE  FROM #BrandarARAPTotal WHERE ISNULL(ARTotal00,0)=0 AND ISNULL(YSTotal00,0)=0 
	AND ISNULL(ARTotal,0)=0  AND ISNULL(YSTotal,0)=0 
	AND ISNULL(nARTotal00,0)=0  AND ISNULL(NYSTotal00,0)=0 
	AND ISNULL(nARTotal,0)=0 AND ISNULL(nYSTotal,0)=0 

	--DROP TABLE #BrandarARAPTotal;
	
	IF @@ERROR>0
	RETURN -1;
	
	ELSE
	RETURN 0;
	--这里不能删除临时表
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReCalBtypeArAp_YearProcDateTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_ReCalBtypeArAp_YearProcDateTime]
GO


/*
    往来余额 指定时间年结存 重新计算
	应收款单据和结算单据在同一时间段 
*/						
CREATE   PROCEDURE GP_ReCalBtypeArAp_YearProcDateTime
(
	@yearendDatetime VARCHAR(20)			--   -年结存的日期		
)
--@encode$--
AS	
	DECLARE @ExpenseToAr INT=0
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';
	DECLARE	@YS_ID INT
	SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE FullName='预收资金';		

	--应收ar 33  ap 35 ys30 yf27  应付暂估 60  发出商品 59
	
	CREATE  TABLE  #BtypeARAPTOAL 
	(
	    [BTypeID] [varchar] (50) NOT NULL,
		[STypeID] [varchar] (50) ,
		[ARTotal] numeric(24,10) ,
		[APTotal] numeric(24,10) ,
		[YSTotal] numeric(24,10) ,
		[YFTotal] numeric(24,10) ,
		[ARTotal00] numeric(24,10) ,
		[APTotal00] numeric(24,10),
		[YSTotal00] numeric(24,10) ,
		[YFTotal00] numeric(24,10) ,
		[nARTotal] numeric(24,10) ,
		[nAPTotal] numeric(24,10) ,
		[nYSTotal] numeric(24,10) ,
		[nYFTotal] numeric(24,10) ,
		[nARTotal00] numeric(24,10) ,
		[nAPTotal00] numeric(24,10) ,
		[nYSTotal00] numeric(24,10) ,
		[nYFTotal00] numeric(24,10) ,
		[CID]	INT NULL,
		[GRIRTotal]		numeric(24,10) ,
		[NGRIRTotal]	numeric(24,10) ,
		[GRIRTotal00]	numeric(24,10) ,
		[NGRIRTotal00]	numeric(24,10) ,
		[FCTotal]		numeric(24,10) ,
		[NFCTotal]	numeric(24,10) ,
		[FCTotal00]	numeric(24,10) ,
		[NFCTotal00]	numeric(24,10)
	)
	
	
	INSERT INTO #BtypeARAPTOAL (
	    [BTypeID],
	    [STypeID] ,
		[ARTotal]  ,
		[APTotal]  ,
		[YSTotal]  ,
		[YFTotal]  ,
		[ARTotal00]  ,
		[APTotal00] ,
		[YSTotal00]  ,
		[YFTotal00]  ,
		[nARTotal]  ,
		[nAPTotal]  ,
		[nYSTotal]  ,
		[nYFTotal]  ,
		[nARTotal00]  ,
		[nAPTotal00]  ,
		[nYSTotal00]  ,
		[nYFTotal00]  ,
		[CID]	,
		[GRIRTotal]		 ,
		[NGRIRTotal]	 ,
		[GRIRTotal00]	 ,
		[NGRIRTotal00]	 ,
		[FCTotal]		 ,
		[NFCTotal]	 ,
		[FCTotal00]	 ,
		[NFCTotal00]	
	
	) 
	SELECT  
	    [BTypeID], [STypeID] ,SUM( ISNULL([ARTotal],0) ) ,SUM( ISNULL( [APTotal],0) ) ,SUM( ISNULL(  [YSTotal],0))  ,SUM( ISNULL(  [YFTotal],0))  ,
	    SUM( ISNULL( [ARTotal00] ,0) ),SUM( ISNULL( [APTotal00],0)) ,SUM( ISNULL( [YSTotal00],0) ) ,SUM( ISNULL( [YFTotal00],0))  ,SUM( ISNULL([nARTotal] ,0)) ,
	    SUM( ISNULL(  [nAPTotal] ,0) ),SUM( ISNULL(  [nYSTotal] ,0)) ,SUM( ISNULL([nYFTotal],0))  ,SUM( ISNULL([nARTotal00],0))  ,SUM( ISNULL([nAPTotal00],0))  ,
	    SUM( ISNULL([nYSTotal00],0) ) ,SUM( ISNULL([nYFTotal00] ,0)) ,[CID]	,SUM( ISNULL([GRIRTotal],0)) ,SUM( ISNULL([NGRIRTotal],0)) ,SUM( ISNULL([GRIRTotal00],0))	 ,
	    SUM( ISNULL([NGRIRTotal00],0)),SUM( ISNULL([FCTotal],0)),SUM( ISNULL([NFCTotal],0)),SUM( ISNULL([FCTotal00],0))	 ,SUM( ISNULL([NFCTotal00],0) )
	 FROM  (
	
	
		SELECT [BTypeID], [STypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,0 AS  [YFTotal]  ,[ARTotal00]  ,[APTotal00] ,[YSTotal00]  ,[YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,[nARTotal00]  ,[nAPTotal00]  ,[nYSTotal00]  ,[nYFTotal00]  ,[CID]	,[GRIRTotal] ,
		[NGRIRTotal]	 ,[GRIRTotal00]	 ,[NGRIRTotal00]	 ,[FCTotal]		 ,[NFCTotal]	 ,[FCTotal00]	 ,[NFCTotal00] FROM IniBType_ArApTotal 
		union all
		SELECT    [BTypeID], [STypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,total AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,ntotal AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=27 AND billdate <@yearendDatetime --预付
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,total AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,ntotal AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=39  AND billdate <@yearendDatetime--预收
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,0 AS [ARTotal]  ,total AS [APTotal]  ,0 AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,ntotal AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=35  AND billdate <@yearendDatetime--应付
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,total AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		ntotal AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=33  AND billdate <@yearendDatetime--应收
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,total AS [GRIRTotal] ,
		ntotal AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=60  AND billdate <@yearendDatetime--应付暂估
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,total AS [FCTotal]		 ,ntotal AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=59  AND billdate <@yearendDatetime--发出商品
	)A
	GROUP BY  A.BTYPEID,A.STYPEID,A.CID
	
    DELETE FROM #BtypeARAPTOAL 
    WHERE [ARTotal] =0 AND
		[APTotal]  =0 AND
		[YSTotal]  =0 AND
		[YFTotal]  =0 AND
		[ARTotal00]  =0 AND
		[APTotal00] =0 AND
		[YSTotal00]  =0 AND
		[YFTotal00]  =0 AND
		[nARTotal]  =0 AND
		[nAPTotal]  =0 AND
		[nYSTotal]  =0 AND
		[nYFTotal]  =0 AND
		[nARTotal00]  =0 AND
		[nAPTotal00]  =0 AND
		[nYSTotal00]  =0 AND
		[nYFTotal00]  =0 AND
		[GRIRTotal]		 =0 AND
		[NGRIRTotal]	 =0 AND
		[GRIRTotal00]	 =0 AND
		[NGRIRTotal00]	 =0 AND
		[FCTotal]		 =0 AND
		[NFCTotal]	 =0 AND
		[FCTotal00]	 =0 AND
		[NFCTotal00] =0
	--修改往来期初汇总值	
	UPDATE	B 
	SET		B.ARTotal00 = br.ARTotal+br.ARTotal00,
			B.APTotal00 = br.APTotal+ br.APTotal00,
			B.YSTotal00 = br.YSTotal+br.YSTotal00,
			B.YFTotal00 = br.YFTotal+br.YFTotal00,
			B.nARTotal00 = br.nARTotal+br.nARTotal00,
			B.nAPTotal00 = br.nAPTotal+br.nAPTotal00,
			B.nYSTotal00 = br.nYSTotal+br.nYSTotal00,
			B.nYFTotal00 =br.nYFTotal+br.nYFTotal00,
			B.GRIRTotal00=br.GRIRTotal+br.GRIRTotal00,
			B.NGRIRTotal00=br.NGRIRTotal+br.NGRIRTotal00,
			B.FCTotal00=br.FCTotal+br.FCTotal00,
			B.NFCTotal00=br.NFCTotal+br.NFCTotal00
	FROM  dbo.BType_ArApTotal B
	INNER JOIN #BtypeARAPTOAL BR ON B.BTypeID=BR.BTypeID AND B.STypeID=BR.STYPEID AND B.CID=BR.CID
	
			

	
		
	INSERT INTO BType_ArApTotal (
		  [BTypeID],
	    [STypeID] ,
		[ARTotal]  ,
		[APTotal]  ,
		[YSTotal]  ,
		[YFTotal]  ,
		[ARTotal00]  ,
		[APTotal00] ,
		[YSTotal00]  ,
		[YFTotal00]  ,
		[nARTotal]  ,
		[nAPTotal]  ,
		[nYSTotal]  ,
		[nYFTotal]  ,
		[nARTotal00]  ,
		[nAPTotal00]  ,
		[nYSTotal00]  ,
		[nYFTotal00]  ,
		[CID]	,
		[GRIRTotal]		 ,
		[NGRIRTotal]	 ,
		[GRIRTotal00]	 ,
		[NGRIRTotal00]	 ,
		[FCTotal]		 ,
		[NFCTotal]	 ,
		[FCTotal00]	 ,
		[NFCTotal00]	

	) SELECT 
		 [BTypeID],
	    [STypeID] ,
		0 AS [ARTotal]  ,
		0 AS [APTotal]  ,
		0 AS [YSTotal]  ,
		0 AS [YFTotal]  ,
		ISNULL([ARTotal],0)+ISNULL([ARTotal00],0)  ,
		ISNULL([APTotal],0)+ISNULL([APTotal00],0) ,
		ISNULL([YSTotal],0)+ISNULL([YSTotal00] ,0) ,
		ISNULL([YFTotal],0)+ISNULL([YFTotal00],0)  ,
		0 AS [nARTotal]  ,
		0 AS [nAPTotal]  ,
		0 AS [nYSTotal]  ,
		0 AS [nYFTotal]  ,
		ISNULL([nARTotal],0)+ISNULL([nARTotal00],0)  ,
		ISNULL([nAPTotal],0)+ISNULL([nAPTotal00],0)  ,
		ISNULL([nYSTotal],0)+ISNULL([nYSTotal00],0)  ,
		ISNULL([nYFTotal],0)+ISNULL([nYFTotal00],0)  ,
		[CID]	,
		0 AS  [GRIRTotal]		 ,
		0 AS [NGRIRTotal]	 ,
		ISNULL([GRIRTotal],0)+ISNULL([GRIRTotal00],0)	 ,
		ISNULL([NGRIRTotal],0)+ISNULL([NGRIRTotal00],0)	 ,
		0 AS [FCTotal]		 ,
		0 AS [NFCTotal]	 ,
		ISNULL([FCTotal],0)+ISNULL([FCTotal00],0)	 ,
		ISNULL(NFCTotal,0)+ISNULL([NFCTotal00],0)	
		
	FROM #BtypeARAPTOAL b 
	WHERE NOT EXISTS(SELECT 1 FROM BType_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid )

	
--升级数据 FcTotal NFcTotal....为NULL 		
	DELETE FROM dbo.BType_ArApTotal	 WHERE  ISNULL(YSTotal00,0)=0 AND  ISNULL(nYSTotal00,0)=0
									   AND  ISNULL(YFTotal00,0)=0 AND ISNULL(nYFTotal00,0)=0
									   AND  ISNULL(ARTotal00,0)=0 AND ISNULL(nARTotal00,0)=0	
									   AND  ISNULL(APTotal00,0)=0 AND ISNULL(nAPTotal00,0)=0
    								   AND  ISNULL(GRIRTotal00,0)=0 AND ISNULL(NGRIRTotal00,0)=0
									   AND  ISNULL(FCTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0	
									   AND  ISNULL(YSTotal,0)=0 AND ISNULL(nYSTotal,0)=0
									   AND  ISNULL(YFTotal,0)=0 AND ISNULL(nYFTotal,0)=0
									   AND  ISNULL(ARTotal,0)=0 AND ISNULL(nARTotal,0)=0	
									   AND  ISNULL(APTotal,0)=0 AND ISNULL(nAPTotal,0)=0
    								   AND  ISNULL(GRIRTotal,0)=0 AND ISNULL(NGRIRTotal,0)=0
									   AND ( ISNULL(FCTotal,0)=0 OR ISNULL(NFCTotal,0)=0)
	DROP TABLE #BtypeARAPTOAL;
	
	IF @@ERROR>0
	RETURN -1;
	
	ELSE
	RETURN 0;
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ReCalIniBtypeARAPTotal_DateTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_ReCalIniBtypeARAPTotal_DateTime]
GO

--====================================================================================
-----------------功能：将预收预付余额、业务凭证中的应收应付余额转成期初单据 
-----------------作者：韩林						   
-----------------日期：2012-06-15                 
--====================================================================================

CREATE    PROC Gp_ReCalIniBtypeARAPTotal_DateTime
(
	@yearendmode			CHAR(1) = '1',	-- 1 - 按余额转期初(arap_total)；0 - 按单据转期初(AccountCredence)
	@yearendDatetime        VARCHAR(20)			--   -年结存的日期		
)	

--@encode$--
AS
SET NOCOUNT ON
	CREATE  TABLE  #REBtypeARAPTOAL 
	(
	    [BTypeID] [varchar] (50) NOT NULL,
		[STypeID] [varchar] (50) ,
		[DTypeID] [varchar] (50) ,
		[ETypeID] [varchar] (50) ,
		[ARTotal] numeric(24,10) ,
		[APTotal] numeric(24,10) ,
		[YSTotal] numeric(24,10) ,
		[YFTotal] numeric(24,10) ,
		[ARTotal00] numeric(24,10) ,
		[APTotal00] numeric(24,10),
		[YSTotal00] numeric(24,10) ,
		[YFTotal00] numeric(24,10) ,
		[nARTotal] numeric(24,10) ,
		[nAPTotal] numeric(24,10) ,
		[nYSTotal] numeric(24,10) ,
		[nYFTotal] numeric(24,10) ,
		[nARTotal00] numeric(24,10) ,
		[nAPTotal00] numeric(24,10) ,
		[nYSTotal00] numeric(24,10) ,
		[nYFTotal00] numeric(24,10) ,
		[CID]	INT NULL,
		[GRIRTotal]		numeric(24,10) ,
		[NGRIRTotal]	numeric(24,10) ,
		[GRIRTotal00]	numeric(24,10) ,
		[NGRIRTotal00]	numeric(24,10) ,
		[FCTotal]		numeric(24,10) ,
		[NFCTotal]	numeric(24,10) ,
		[FCTotal00]	numeric(24,10) ,
		[NFCTotal00]	numeric(24,10)
	)
	
	
	INSERT INTO #REBtypeARAPTOAL (
	    [BTypeID],
	    [STypeID] ,
	    [DTypeID] ,
		[ETypeID] ,
		[ARTotal]  ,
		[APTotal]  ,
		[YSTotal]  ,
		[YFTotal]  ,
		[ARTotal00]  ,
		[APTotal00] ,
		[YSTotal00]  ,
		[YFTotal00]  ,
		[nARTotal]  ,
		[nAPTotal]  ,
		[nYSTotal]  ,
		[nYFTotal]  ,
		[nARTotal00]  ,
		[nAPTotal00]  ,
		[nYSTotal00]  ,
		[nYFTotal00]  ,
		[CID]	,
		[GRIRTotal]		 ,
		[NGRIRTotal]	 ,
		[GRIRTotal00]	 ,
		[NGRIRTotal00]	 ,
		[FCTotal]		 ,
		[NFCTotal]	 ,
		[FCTotal00]	 ,
		[NFCTotal00]	
	
	) 
	SELECT  
	    [BTypeID], [STypeID] , [DTypeID], [ETypeID] ,SUM( ISNULL([ARTotal],0) ) ,SUM( ISNULL( [APTotal],0) ) ,SUM( ISNULL(  [YSTotal],0))  ,SUM( ISNULL(  [YFTotal],0))  ,
	    SUM( ISNULL( [ARTotal00] ,0) ),SUM( ISNULL( [APTotal00],0)) ,SUM( ISNULL( [YSTotal00],0) ) ,SUM( ISNULL( [YFTotal00],0))  ,SUM( ISNULL([nARTotal] ,0)) ,
	    SUM( ISNULL(  [nAPTotal] ,0) ),SUM( ISNULL(  [nYSTotal] ,0)) ,SUM( ISNULL([nYFTotal],0))  ,SUM( ISNULL([nARTotal00],0))  ,SUM( ISNULL([nAPTotal00],0))  ,
	    SUM( ISNULL([nYSTotal00],0) ) ,SUM( ISNULL([nYFTotal00] ,0)) ,[CID]	,SUM( ISNULL([GRIRTotal],0)) ,SUM( ISNULL([NGRIRTotal],0)) ,SUM( ISNULL([GRIRTotal00],0))	 ,
	    SUM( ISNULL([NGRIRTotal00],0)),SUM( ISNULL([FCTotal],0)),SUM( ISNULL([NFCTotal],0)),SUM( ISNULL([FCTotal00],0))	 ,SUM( ISNULL([NFCTotal00],0) )
	 FROM  (
	
	
		SELECT [BTypeID], [STypeID] ,[DTypeID], [ETypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,0 AS  [YFTotal]  ,[ARTotal00]  ,[APTotal00] ,[YSTotal00]  ,[YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,[nARTotal00]  ,[nAPTotal00]  ,[nYSTotal00]  ,[nYFTotal00]  ,[CID]	,[GRIRTotal] ,
		[NGRIRTotal]	 ,[GRIRTotal00]	 ,[NGRIRTotal00]	 ,[FCTotal]		 ,[NFCTotal]	 ,[FCTotal00]	 ,[NFCTotal00] FROM IniBType_ArApTotal 
		union all
		SELECT    [BTypeID], [STypeID] ,[DTypeID], [ETypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,total AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,ntotal AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=27 AND billdate <@yearendDatetime --预付
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,[DTypeID], [ETypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,total AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,ntotal AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=39  AND billdate <@yearendDatetime--预收
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,[DTypeID], [ETypeID] ,0 AS [ARTotal]  ,total AS [APTotal]  ,0 AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,ntotal AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=35  AND billdate <@yearendDatetime--应付
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,[DTypeID], [ETypeID] ,total AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		ntotal AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=33  AND billdate <@yearendDatetime--应收
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,[DTypeID], [ETypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,total AS [GRIRTotal] ,
		ntotal AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,0 AS [FCTotal]		 ,0 AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=60  AND billdate <@yearendDatetime--应付暂估
		UNION ALL
		SELECT    [BTypeID], [STypeID] ,[DTypeID], [ETypeID] ,0 AS [ARTotal]  ,0 AS [APTotal]  ,0 AS [YSTotal]  ,0 AS [YFTotal]  ,0 AS [ARTotal00]  ,0 AS [APTotal00] ,0 AS [YSTotal00]  ,0 AS [YFTotal00]  ,
		0 AS [nARTotal]  ,0 AS [nAPTotal]  ,0 AS [nYSTotal]  ,0 AS [nYFTotal]  ,0 AS [nARTotal00]  ,0 AS [nAPTotal00]  ,0 AS [nYSTotal00]  ,0 AS [nYFTotal00]  ,[CID]	,0 AS [GRIRTotal] ,
		0 AS [NGRIRTotal]	 ,0 AS [GRIRTotal00]	 ,0 AS [NGRIRTotal00]	 ,total AS [FCTotal]		 ,ntotal AS [NFCTotal]	 ,0 AS [FCTotal00]	 ,0 AS [NFCTotal00]	
		FROM dbo.ListTable WHERE AtypeId=59  AND billdate <@yearendDatetime--发出商品
	)A
	GROUP BY  A.BTYPEID,A.STYPEID,[DTypeID], [ETypeID] ,A.CID
	
	--SELECT * FROM #REBtypeARAPTOAL
    DELETE FROM #REBtypeARAPTOAL 
    WHERE [ARTotal] =0 AND
		[APTotal]  =0 AND
		[YSTotal]  =0 AND
		[YFTotal]  =0 AND
		[ARTotal00]  =0 AND
		[APTotal00] =0 AND
		[YSTotal00]  =0 AND
		[YFTotal00]  =0 AND
		[nARTotal]  =0 AND
		[nAPTotal]  =0 AND
		[nYSTotal]  =0 AND
		[nYFTotal]  =0 AND
		[nARTotal00]  =0 AND
		[nAPTotal00]  =0 AND
		[nYSTotal00]  =0 AND
		[nYFTotal00]  =0 AND
		[GRIRTotal]		 =0 AND
		[NGRIRTotal]	 =0 AND
		[GRIRTotal00]	 =0 AND
		[NGRIRTotal00]	 =0 AND
		[FCTotal]		 =0 AND
		[NFCTotal]	 =0 AND
		[FCTotal00]	 =0 AND
		[NFCTotal00] =0

	TRUNCATE TABLE IniBType_ArApTotal
	INSERT INTO IniBType_ArApTotal (
		[BTypeID],
		[STypeID] ,
		[DTypeID] ,
		[ETypeID] ,
		[ARTotal00]  ,
		[APTotal00] ,
		[YSTotal00]  ,
		[YFTotal00]  ,
		[nARTotal00]  ,
		[nAPTotal00]  ,
		[nYSTotal00]  ,
		[nYFTotal00]  ,
		[CID]	,
		[GRIRTotal00]	 ,
		[NGRIRTotal00]	 ,
		[FCTotal00]	 ,
		[NFCTotal00]	

	) SELECT 
		[BTypeID],
		[STypeID] ,
		[DTypeID] ,
		[ETypeID] ,
		isnull([ARTotal],0)+ISNULL([ARTotal00] ,0) ,
		isnull([APTotal],0)+ISNULL([APTotal00] ,0),
		isnull( [YSTotal],0)+ISNULL([YSTotal00],0)  ,
		isnull( [YFTotal],0)+ISNULL([YFTotal00],0)  ,
		isnull([nARTotal],0)+ISNULL([nARTotal00] ,0) ,
		isnull([nAPTotal],0)+ISNULL([nAPTotal00] ,0),
		isnull( [nYSTotal],0)+ISNULL([nYSTotal00],0)  ,
		isnull( [nYFTotal],0)+ISNULL([nYFTotal00],0)  ,
		[CID]	,
		isnull([GRIRTotal],0)+ISNULL([GRIRTotal00] ,0) ,
		isnull([NGRIRTotal],0)+ISNULL([NGRIRTotal00] ,0),
		isnull( [FCTotal],0)+ISNULL([FCTotal00],0)  ,
		isnull( [NFCTotal],0)+ISNULL([NFCTotal00],0)  

		
	FROM #REBtypeARAPTOAL b 
	WHERE NOT EXISTS(SELECT 1 FROM IniBType_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid and a.dtypeid=b.dtypeid AND a.eTypeID=b.etypeid)

	
--升级数据 FcTotal NFcTotal....为NULL 		
								   
	DELETE FROM dbo.IniBType_ArApTotal	 WHERE  ISNULL(YSTotal00,0)=0 AND  ISNULL(nYSTotal00,0)=0
								   AND  ISNULL(YFTotal00,0)=0 AND ISNULL(nYFTotal00,0)=0
								   AND  ISNULL(ARTotal00,0)=0 AND ISNULL(nARTotal00,0)=0	
								   AND  ISNULL(APTotal00,0)=0 AND ISNULL(nAPTotal00,0)=0
								   AND  ISNULL(GRIRTotal00,0)=0 AND ISNULL(NGRIRTotal00,0)=0
								   AND  ISNULL(FCTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0		
								   AND  ISNULL(GRIRTotal,0)=0 AND ISNULL(NGRIRTotal,0)=0
								   AND  (ISNULL(FCTotal,0)=0 OR ISNULL(NFCTotal,0)=0)
									   
									   
	DROP TABLE #REBtypeARAPTOAL;
	
	IF @@ERROR>0
	RETURN -1;
	
	ELSE
	RETURN 0;
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReCalSerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_ReCalSerial
GO


-- ========================================================================
-- 功能说明：		重算序列号出入库表的 detailid
-- 最后修改：		shushan
-- 修改时间：		
-- ========================================================================
CREATE    PROCEDURE GP_ReCalSerial

--@encode$--
AS
SET NOCOUNT ON
IF NOT EXISTS (SELECT TOP 1 1 FROM dbo.gp_inoutPtypeSerial WHERE ISNULL(detailid,-1)=-1)
RETURN

CREATE TABLE #allserial
(	
	Billtype INT ,
	Billnumberid VARCHAR(50),
	ptypeid  VARCHAR(50),
	DetailID INT ,
	Serial	 VARCHAR (50)
)

--序列号出入库记录
CREATE TABLE #gp_inoutPtypeSerial
(
	BillNumberId		NUMERIC(18,0),
	PTypeId				VARCHAR(50),
	BillType			INT,
	DetailId			INT,
	Serial				VARCHAR (50)
)	
CREATE CLUSTERED INDEX #gp_inoutPtypeSerial_ix_ptypeid ON #gp_inoutPtypeSerial(PTypeId)

INSERT INTO #gp_inoutPtypeSerial(BillNumberId,PTypeId,BillType,DetailId,Serial)
SELECT	BillNumberId,PTypeId,BillType,DetailId,Serial
FROM	dbo.gp_inoutPtypeSerial
WHERE	BillType IN (305,215,11,45,160,140,142,12,46,402,403)

--分段收集数据
CREATE TABLE #Temp
(
	BillType			INT,
	BillNumberId		NUMERIC(18,0),
	PTypeId				VARCHAR(50),	
	ID					INT,
	StrXml				XML
)

---------------------------------------------零售单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	305 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml = convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.retailbill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=305 
					AND ISNULL(g.detailid ,-1)=-1
		) A 

INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)				
SELECT	DISTINCT  
		305 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A

TRUNCATE TABLE #Temp

---------------------------------------------零售退货单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	215 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml = convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.RetailBackBill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=215 
					AND ISNULL(g.detailid ,-1)=-1
		) A 

INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)				
SELECT	DISTINCT  
		215 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A

TRUNCATE TABLE #Temp	
	 
---------------------------------------------销售出库单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	11 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml = convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.salebill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=11 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)			
SELECT	DISTINCT  
		11 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp

---------------------------------------------销售退货单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	45 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml = convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.salebackbill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=45 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)				
SELECT	DISTINCT  
		45 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp

---------------------------------------------销售换货单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	160 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml = convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.salegoodsexchangebill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=160 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)				
SELECT	DISTINCT  
		160 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp

---------------------------------------------委托代销发货单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	140 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml = convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.commissionbill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=140 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)				
SELECT	DISTINCT  
		140 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp
---------------------------------------------委托代销退货单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	142 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml = convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.commissionbill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=142 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)				
SELECT	DISTINCT  
		142 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp

---------------------------------------------组合品销售出库单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	12 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml =convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.PT_Combin_SaleBillDetail r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=12 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)			
SELECT	DISTINCT  
		12 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp

---------------------------------------------组合品销售退货单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	46 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml =convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.PT_Combin_SaleBackBillDetail r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=46 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)				
SELECT	DISTINCT  
		46 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp

---------------------------------------------发出商品出库单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	402 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml =convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.SendBill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=402 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)				
SELECT	DISTINCT  
		402 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp

---------------------------------------------发出商品退货单---------------------------------------------
INSERT INTO #Temp(BillType,BillNumberId,PTypeId,ID,StrXml)
SELECT	403 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID,
		A.StrXml
FROM    (
			SELECT	StrXml =convert(xml,'<root><v>'+replace(CONVERT(varchar(max),REPLACE(CONVERT(varchar(max),r.Serial),'&','&amp;')),'я','</v><v>')+'</v></root>') , 
					r.ID,
					r.ptypeid,
					r.BillNumberId     
			FROM    dbo.SendBackBill r ,
					#gp_inoutPtypeSerial g
			WHERE	r.BillNumberId=g.BillNumberid 
					AND r.ptypeid=g.PtypeID 
					AND g.billtype=403 
					AND ISNULL(g.detailid ,-1)=-1
		) A
		
INSERT INTO #allserial(Billtype,Billnumberid,ptypeid,DetailID,Serial)		
SELECT	DISTINCT  
		403 AS Billtype,
		a.BillNumberId,
		a.ptypeid, 
		A.ID ,  
		a.Serial
FROM    (
			SELECT	A.strXml,
					A.ID,
					A.ptypeid,
					A.BillNumberId,
					B.StrColumn AS Serial
			FROM	#Temp a 
			OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(50)')  FROM   A.StrXml.nodes('/root/v') N (v))B
		 )A
	 
TRUNCATE TABLE #Temp


-- 修改数据
UPDATE  a
SET		detailid =s.detailid
FROM	Gp_InOutPtypeSerial a
INNER JOIN #allserial s ON a.BillNumberid=s.Billnumberid AND a.BillType=s.Billtype AND a.PtypeID=s.ptypeid AND a.Serial=s.Serial
WHERE ISNULL(a.detailid,-1)=-1

DROP TABLE #allserial,#Temp,#Gp_InOutPtypeSerial


-- 操作返回值
IF @@ERROR = 0
	RETURN 0	-- 成功
ELSE
	RETURN -1	-- 失败



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_ReCanceledAcVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_ReCanceledAcVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查询反作废
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_ReCanceledAcVoucherBill
(
	@BillNumberId	VARCHAR(50)=''			-- 单据ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@fchecked		VARCHAR(2)='',
	@recheckid		VARCHAR(2)='',
	@ifcheck		VARCHAR(2)='',
	@Fperiod		VARCHAR(2)='',
	@StypeID		VARCHAR(50)='',
	@FYear			INT,
	@NowFYear		INT,			--当前分支当前年度
	@nowFperiod		VARCHAR(2)='',	--当前分支当前期间
	@ErrorCount		INT=0--审核 复核 过账 凭证类型
	
SELECT 
	@fchecked=ISNULL(FChecked,''),
	@recheckid=ISNULL(ReCheckId,''),
	@ifcheck=ISNULL(IfCheck,''),
	@Fperiod=ISNULL(FPeriod,''),
	@StypeID=STypeId,
	@FYear=FYear
FROM Ac_Voucher
WHERE BillNumberId=@BillNumberId
		
--取当前的期号
IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID)
	SELECT @nowFperiod=FPeriod,@NowFYear=FYear FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID
ELSE 
	BEGIN
		SELECT	TOP 1 @nowFperiod = SubValue FROM sysdata WHERE	SubName = 'FPeriod'	
		SELECT	TOP 1 @NowFYear = SubValue FROM sysdata WHERE	SubName = 'fyear'	
	END	

 
IF @@ROWCOUNT = 0--判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN
END

IF (@FYear = @NowFYear AND @Fperiod < @nowFperiod)
	OR
	(@FYear < @NowFYear)--当前期间及之后的凭证都才可反作废
	BEGIN
		RAISERROR('您选择的凭证有部份所在期间小于当前期间,请确认！',16,1)
		RETURN
	END

IF(@fchecked='1' OR @fchecked<>'-1' OR @recheckid <>'' OR @ifcheck='t')
	BEGIN
		RAISERROR('您选择的凭证有部份未作废或者已审核/复核/记账！请确认后重试！',16,1)
		RETURN
	END
UPDATE Ac_Voucher SET FChecked=0 WHERE BillNumberId=@BillNumberID--作废 凭证主表

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='反作废凭证单据错误，请确认！'
		RAISERROR(@MSG2,16,1)
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Receipt_Deal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_Receipt_Deal
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2015-05-27
	描述：暂估发票过账后修改原来的开票状态,回写开票数量和金额
	
*/

CREATE PROCEDURE [dbo].[GP_Receipt_Deal]
(
	@strReceiptBillNumberID		VARCHAR(50),		--发票BILLNUBERID
	@intRedWord					INT
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #ListID(BillNumberID VARCHAR(50),BillType INT)

---------------回写单据的开票金额,状态-----------------
INSERT INTO #ListID(BillNumberID,BillType) 
SELECT DISTINCT MainBillNumberID,MainBillType FROM ReceiptBill 
WHERE BillNumberID=@strReceiptBillNumberID AND MainBillNumberID > = 0 



--------更新状态
DECLARE @strGoodsBillNumberID VARCHAR(50),@intBillType INT
DECLARE GoodsBill CURSOR  ------查询游标
	LOCAL SCROLL STATIC 
	FOR SELECT BillNumberID,BillType FROM #ListID
	OPEN GoodsBill
	FETCH NEXT FROM GoodsBill
	INTO @strGoodsBillNumberID,@intBillType

	WHILE @@FETCH_STATUS=0
	BEGIN	
		EXEC GP_UpdateReceiptState @strGoodsBillNumberID,@intBillType,@strReceiptBillNumberID,@intRedWord	
		FETCH NEXT FROM GoodsBill
		INTO @strGoodsBillNumberID,@intBillType
	END
	CLOSE GoodsBill
	DEALLOCATE GoodsBill


DROP TABLE #ListID
---------------回写单据的开票金额,状态 end-----------------


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReceiptBill_AfterRedWord]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_ReceiptBill_AfterRedWord]
GO




/*

功能说明：		采购暂估发票红冲后删除可能存在的成本条件单

作    者：       冯波


时间：       2015-05-25

*/

CREATE PROCEDURE [GP_ReceiptBill_AfterRedWord]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0)			-- 单据 ID 号
)
--@encode$--        
AS

--红冲成本调价单
IF EXISTS(
	SELECT BillNumberId
	FROM AdPriceBill
	WHERE FromBillNumberID=@nBillID
)
BEGIN
	DECLARE
		@intAdPriceBillNumberID			INT,
		@strPTypeIDOutPut				VARCHAR(500)
		
	SELECT @intAdPriceBillNumberID=BillNumberId
	FROM AdPriceBill
	WHERE FromBillNumberID=@nBillID
	
	
	
	--删除自动生成的成本调价单
	DELETE ListTable WHERE BillNumberId=@nBillID AND BillType=57
	
	DELETE InOutstocktable WHERE BillNumberId=@nBillID AND BillType=57
	
	
	DELETE Billindex WHERE BillNumberId IN (
		SELECT BillNumberId
		FROM AdPriceBill
		WHERE FromBillNumberID=@nBillID
	)
	
	DELETE AdPriceBill WHERE BillNumberId IN (
		SELECT BillNumberId
		FROM AdPriceBill
		WHERE FromBillNumberID=@nBillID
	)
	
	
END
		
	


GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReceiptBill_CreateBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_ReceiptBill_CreateBill]
GO




/*

功能说明：		采购暂估发票生成成本调价单

作    者：       冯波


时间：       2015-05-25

修改人：冯波   时间：2017-04-25   如果价格没变化，则不生成

*/

CREATE PROCEDURE [GP_ReceiptBill_CreateBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

SET @strErrMsg=''

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
*/

DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT


SELECT @intReturnID=0

IF NOT EXISTS(
	SELECT BillNumberID
	FROM ReceiptBill
	WHERE BillNumberID=@nBillID AND (BeforeTotal<>Total OR NBeforeTotal<>NTotal)
)
BEGIN
	--不生成相应的成本调价单
	RETURN
END
ELSE
BEGIN
	IF NOT EXISTS(
		SELECT BillNumberID
		FROM ReceiptBill
		WHERE BillNumberID=@nBillID AND BeforePrice<>Price
	)
	BEGIN
		--不生成相应的成本调价单
		RETURN
	END
	
END

DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号



--生成新的单据编号

DECLARE
	@strSTypeID					VARCHAR(50),
	@strDTypeID					VARCHAR(50),
	@strETypeID					VARCHAR(50),
	@intFromBillNumberID		INT,
	@intFromBillType			INT
	
DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@ETypeID			VARCHAR(100),
	@KTypeID			VARCHAR(100),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@intBillType		INT,
	@datBillDate		DATETIME,
	@strFromBillcode	VARCHAR(100),
	@strBTypeID			VARCHAR(100),
	@cefullname			VARCHAR(500)='',
	@cdfullname			VARCHAR(500)=''			--部门

SELECT  @strSTypeID = Stypeid ,
        @strDTypeID = DTypeID ,
        @strETypeID = ETypeID ,
        @intFromBillNumberID = BillNumberID ,
        @intFromBillType = BillType ,
        @datBillDate = BillDate ,
        @strBTypeID = BTypeID ,
        @strFromBillCode = BillCode
FROM    ReceiptBillIndex
WHERE   BillNumberID = @nBillID



DECLARE
	@datPostTime		DATETIME
	
IF EXISTS(
	SELECT BillNumberId
	FROM Old_ListTable
	WHERE BillNumberId=@nBillID AND BillType=404
)	
BEGIN
	SELECT @datPostTime=Posttime
	FROM ReceiptBillIndex
	WHERE BillNumberId=@nBillID AND BillType=404
END
ELSE
BEGIN
	SELECT @datPostTime=GETDATE()
END


SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT
	@ETypeID=@strETypeID,
	@KTypeID='',
	@VchHead='TJ',
	@intBillType=57
	
	

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = typeid FROM Employee WHERE TypeID = @ETypeID
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
	SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @chvOpID
	SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @strDTypeID
END

SELECT 
	@MONTH=ISNULL(@MONTH,''),
	@DAY=ISNULL(@DAY,'')


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname


SET @strBillCode=ISNULL(@strBillCode,'')

IF @Re <> 0
RETURN -2	



DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000)
	
	
SELECT 
	@strComment='该成本调价单是从采购暂估发票'+@strFromBillCode+'生成而来的！'
	
	
DECLARE
	@strTempATypeID1		VARCHAR(100)
	
SELECT
	@strTempATypeID1=ATypeID
FROM BillAtype
WHERE BillTypeId='57'
AND StypeId=@strSTypeID


SELECT @strTempATypeID1=ISNULL(@strTempATypeID1,'')

DECLARE @ATID INT

SELECT @ATID=AtId
FROM Ac_Auditing_Template
WHERE BillType=57 AND InOutType=1

--生成成本调价单的草稿
--生成表头

INSERT BillIndex(BillDate,BillCode,BillType,STypeID,ETypeID,
ATypeID,KTypeID,KTypeID2,Comment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,AlertDay,DTypeId,CostSale,FromBillNumberID,
ifcheck,IfAudit,draft,OrderId,checke,btypeid,NTotalMoney,CID,Rate,AdPriceType,
DealBTypeID,posttime,ATypeID1,ATID)
SELECT BillDate,@strBillCode,@intBillType,@strSTypeID,
ETypeID,'','','',@strComment,totalmoney,totalqty,tax,Period,explain,
'','','','',AlertDay,DTypeID,0,BillNumberId,
't',0,0,0,checke,BTypeID,NTotalMoney,CID,Rate,1,
DealBTypeID,@datPostTime,@strTempATypeID1,@ATID
FROM ReceiptBillIndex
WHERE BillNumberId=@nBillID



SELECT @intReturnID=SCOPE_IDENTITY();

--生成表体

INSERT AdPriceBill(BillNumberId,Comment,PtypeId,Qty,Price,Total,
ChangeAllStock,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
HandZeroCost,Stypeid,ktypeid,Serial,NQty,UnitRate,ItemID,IsCombined,cargoID,NPrice,NTotal,ChangeTotal,
FromBillNumberID,FromBillType,FromBillID,ShowOrder)
SELECT @intReturnID,@strComment,a.PTypeID,a.Qty,a.Price-a.BeforePrice,ROUND((a.Price-a.BeforePrice)*a.Qty,@intMoneyDot),
0,a.GoodsNumber,a.ProduceDate,a.ValidDate,0,
1,a.Stypeid,a.ktypeid,a.Serial,a.NQty,a.UnitRate,a.ItemID,a.IsCombined,a.cargoID,a.Nprice-a.Nbeforeprice,ROUND((a.NPrice-a.Nbeforeprice)*a.Qty,@intMoneyDot),ROUND((a.Price-a.BeforePrice)*a.Qty,@intMoneyDot),
@intFromBillNumberID,@intFromBillType,a.ID,ShowOrder
FROM ReceiptBill a
WHERE a.BillNumberId=@nBillID
AND (a.BeforeTotal<>a.Total OR a.NBeforeTotal<>a.NTotal) AND (a.Price<>a.BeforePrice)


--根据汇率算原币

DECLARE 
		@strOPRate	VARCHAR(50),
		@CID		INT,
		@SysCid		INT,
		@decRate	 NUMERIC(24, 10) 
		
	--本位币	
	SELECT @SysCid= CID FROM dbo.Ac_Currency WHERE Sysrow=1
		
	SELECT @CID=CID,@decRate=Rate
	FROM ReceiptBillIndex
	WHERE BillNumberID=@nBillID 	
	
	SELECT @strOPRate=BasisType
	FROM Ac_Currency				
	WHERE CId=@CID


DECLARE
	@decTotalMoney		 NUMERIC(24, 10) ,
	@decNTotalMoney		 NUMERIC(24, 10) ,
	@decTotalQty		 NUMERIC(24, 10) 
	
SELECT
	@decTotalMoney=SUM(Total),
	@decNTotalMoney=SUM(NTotal),
	@decTotalQty=SUM(Qty)
FROM AdPriceBill
WHERE BillNumberId=@intReturnID	


UPDATE Billindex
SET totalmoney=@decTotalMoney,NTotalMoney=@decNTotalMoney,totalqty=@decTotalQty
WHERE BillNumberId=@intReturnID

DECLARE 
	@dChange			 NUMERIC(24, 10) ,
	@GOODS_ID			VARCHAR(50),
	@APAppraisal		VARCHAR(50)
	
SELECT @dChange=@decTotalMoney


SELECT @GOODS_ID=nId FROM dbo.Ac_Items WHERE UserCode='1241'  --『库存商品总值合计』,0000100001
SELECT @APAppraisal=nId FROM dbo.Ac_Items WHERE UserCode='2122'		--应付暂估

SELECT @SysCid= CID FROM dbo.Ac_Currency WHERE Sysrow=1

--要处理INOUTSTOCKTABLE和GOODSSTOCKS





INSERT Inoutstocktable(BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,
Qty,Price,Total,CostPrice,CostTotal,Audited,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
HandZeroCost,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,DTypeID,STypeID,PostTime,
CargoID,NPrice,NTotal,NSalePrice,NSaleTotal,NTaxPrice,NTaxTotal,ItemID,IsCombined,NQty,UnitRate,
MUNITID,IsGift,IsService,Comment
)
SELECT @intReturnID,BillDate,BillType,@GOODS_ID,a.PtypeId,BtypeId,EtypeId,a.KtypeId,
Qty,Price,Total,0,Total,1,a.GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
HandZeroCost,a.ID,0,1,0,Total,0,Total,DTypeID,b.STypeID,@datPostTime,
CargoID,NPrice,NTotal,0,NTotal,0,NTotal,ItemID,IsCombined,NQty,UnitRate,c.baseUnitId,0,0,b.Comment
FROM AdPriceBill a
INNER JOIN BillIndex b
ON a.BillNumberId=b.BillNumberId
INNER JOIN Ptype c
ON a.PtypeId=c.typeId
WHERE a.BillNumberId=@intReturnID

SELECT PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,Total
	FROM AdPriceBill
	WHERE BillNumberID=@intReturnID
	


MERGE GoodsStocks AS t
USING(
	SELECT PTypeID,KTypeID,SUM(Total) AS Total
	FROM AdPriceBill
	WHERE BillNumberID=@intReturnID
	GROUP BY PTypeID,KTypeID
) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
WHEN MATCHED THEN 
	UPDATE SET t.Total=t.Total+s.Total,t.Price=CASE t.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(t.Total+s.Total AS  NUMERIC(24, 10) )/CAST(t.Qty AS  NUMERIC(24, 10) ),@intPriceDot) END
WHEN NOT MATCHED BY TARGET THEN 
	INSERT (PtypeId,KTypeID,Qty,Price,Total) 
	VALUES(s.PtypeId,s.KTypeID,0,0,s.Total);
	
	
MERGE GoodsStocks_Qty AS t
USING(
	SELECT DISTINCT PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID
	FROM AdPriceBill
	WHERE BillNumberID=@intReturnID
) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
AND t.GoodsNumber=s.GoodsNumber AND t.ProduceDate=s.ProduceDate AND t.ValidDate=s.ValidDate
AND t.CargoID=s.CargoID
WHEN NOT MATCHED BY TARGET THEN 
	INSERT (PtypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,CargoID,ItemID,IsCombined) 
	VALUES(s.PtypeId,s.KTypeID,s.GoodsNumber,s.ProduceDate,s.ValidDate,0,0,0,s.CargoID,0,0);	

--GOODSSTOCKS_QTY不变

--处理LISTTABLE



--库存商品，借
INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
		total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
SELECT @intReturnID,BillDate,BillType,@GOODS_ID,'0',Btypeid,Etypeid,'0',
		@decTotalMoney,@decTotalMoney,'','',DTypeID,STypeID,@syscid,@dChange,1,1
FROM BillIndex
WHERE BillNumberID=@intReturnID	

UPDATE AType_Total
SET Total=Total+@dChange,Ntotal=Ntotal+@dChange
WHERE ATypeID=@GOODS_ID AND STypeID=@strSTypeID AND CID=@SysCid	
		
--应付，贷
INSERT INTO Listtable(BillNumberId,BillDate,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
		total,costtotal,JobNumber,OutFactoryDate,DTypeID,STypeID,CID,Ntotal,Audited,Rate)
SELECT @intReturnID,BillDate,BillType,@APAppraisal,'0',Btypeid,Etypeid,'0',
		@decTotalMoney,@decTotalMoney,'','',DTypeID,STypeID,@CID,@decNTotalMoney,1,1		
FROM BillIndex
WHERE BillNumberID=@intReturnID				

IF EXISTS(
	SELECT ATypeID
	FROM AType_Total
	WHERE ATypeID=@APAppraisal AND STypeID=@strSTypeID AND CID=@CID
)
BEGIN
	UPDATE AType_Total
	SET Total=Total+@decTotalMoney,Ntotal=Ntotal+@decNTotalMoney
	WHERE ATypeID=@APAppraisal AND STypeID=@strSTypeID AND CID=@CID
END
ELSE
BEGIN
	INSERT AType_Total(ATypeID,STypeID,Total00,Total,CID,Ntotal00,Ntotal)
	SELECT @APAppraisal,@strSTypeID,0,@decTotalMoney,@CID,0,@decNTotalMoney
END

IF EXISTS(
	SELECT BTypeID
	FROM BType_ArApTotal
	WHERE BTypeID=@strBTypeID AND STypeID=@strSTypeID AND CID=@CID
)
BEGIN
	UPDATE BType_ArApTotal
	SET GRIRTotal=GRIRTotal+@decTotalMoney,NGRIRTotal=NGRIRTotal+@decNTotalMoney
	WHERE BTypeID=@strBTypeID AND STypeID=@strSTypeID AND CID=@CID
END
ELSE
BEGIN
	INSERT BType_ArApTotal(BTypeID,STypeID,CID,GRIRTotal,NGRIRTotal)
	SELECT @strBTypeID,@strSTypeID,@CID,@decTotalMoney,@decNTotalMoney
END


--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END    

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END


IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 1)
		AND	EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'postingparameter' AND SubValue = 0)--即时过账，即时生成凭证
		AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'aloneusebsys' AND SubValue = 0)--使用总账系统
		
BEGIN

	--SELECT @atid = atid FROM dbo.BillIndex WHERE BillNumberId = @intReturnID
	EXEC .Gp_AutoCreate_Voucher @intReturnID,@chvOpID,@atid,'',@strErrMsg OUTPUT,57
END
ELSE
	SET @strErrMsg = ''


GO


/*

DECLARE
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0),			--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100),
	@strErrMsg				VARCHAR(100)			--出错信息
	
SELECT
	@chvOpID=1,
	@nBillID=1
	
	

EXEC	GP_ReceiptBill_CreateBill
	@chvOpID,
	@nBillID,
	@intReturnID OUT,
	@strReturnBillCode OUT,
	@strErrMsg OUT

SELECT @strReturnBillCode,@strErrMsg


*/




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ReceptionBill_Deal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_ReceptionBill_Deal]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	接待登记单进厂
	作    者：	冯波
	修改时间：	2011-5-10
*/
CREATE             PROCEDURE Gp_ReceptionBill_Deal
(
	@nBillID				numeric(10,0)				-- 单据 ID 号
)
--@encode$--
AS
	SET NOCOUNT ON
	
	/*
		进厂：
		维修进度变成在修。同时记录进厂日期，格式为日期+时分秒。
		项目进度变成未派工。
	*/
	IF EXISTS(
		SELECT BillNumberID FROM Billindex_CarRepair
		WHERE BillNumberId=@nBillID AND BillState=2
	)
	BEGIN
		RETURN -1
	END
	
	DECLARE
		@chvSTypeID		VARCHAR(100)
		
	SELECT
		@chvSTypeID=STypeID
	FROM BillIndex
	WHERE BillNumberId=@nBillID
	
	IF NOT EXISTS (
		SELECT	TOP 1 1
		FROM	SType_UserConfig
		WHERE	ConfigNo = 1
				AND Value = 1
				AND STypeID=@chvSTypeID
	)
	BEGIN
		RETURN 3	-- 没有开帐不允许过帐
	END
	
	UPDATE Billindex_CarRepair
	SET 
		InFactoryDate=GETDATE(),
		BillState=2
	WHERE BillNumberId=@nBillID
	
	
	UPDATE Qp_ReceptionBill_RepairItems
	SET
		RepairProcess=1
	WHERE BillNumberId=@nBillID
	
	RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_ReCheckedAcVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_ReCheckedAcVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查询反复核
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_ReCheckedAcVoucherBill
(
	@BillNumberId	VARCHAR(50)='',			--单据ID
	@OpertionId		VARCHAR(50)=''			--操作人
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@fchecked		VARCHAR(2)='',
	@recheckid		VARCHAR(50)='',
	@ifcheck		VARCHAR(2)='',
    @markerror		VARCHAR(200)='',
	@ErrorCount		INT=0 --审核 复核 过账 错误条数
	
SELECT 
	@fchecked=ISNULL(FChecked,''),
	@recheckid=ISNULL(ReCheckId,''),
	@ifcheck=ISNULL(IfCheck,''),
    @markerror=isnull(markerror,'')
FROM Ac_Voucher
WHERE BillNumberId=@BillNumberId 
		 
IF @@ROWCOUNT = 0--判断单据是否存在
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN -1
END
IF(@recheckid<>@OpertionId)
	BEGIN
		RAISERROR('您选择的凭证复核人与反复核人不为同一人！请确认后重试！!!',16,1)
		RETURN -1
	END
DECLARE @SubValue VARCHAR(2)=''
SELECT @SubValue=ISNULL(SubValue,'') FROM sysdata WHERE SubName='acvhrchk'

IF(@ifcheck='t')
	BEGIN
		RAISERROR('凭证已经记账!请确认！',16,1)--记账
		RETURN -1
	END
IF(@recheckid ='')
	BEGIN
		RAISERROR('凭证未复核!请确认！',16,1)--/复核
		RETURN -1
	END
IF(@fchecked='-1')
	BEGIN
		RAISERROR('凭证已经作废!请确认！',16,1)--/作废
		RETURN -1
	END

IF(@markerror<>'')
	BEGIN
		RAISERROR('凭证已经标错!请确认！',16,1)--/审核
		RETURN -1
	END

UPDATE Ac_Voucher SET ReCheckId='' WHERE BillNumberId=@BillNumberID--反复核 凭证主表
SET @ErrorCount+=@@ERROR

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='反复核凭证单据错误，请确认！'
		RAISERROR(@MSG2,16,1)
		RETURN -1
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RecieptToInibill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_RecieptToInibill]
GO

--====================================================================================
-----------------功能：将暂估，发出商品余额转为单据
-----------------作者：冯波						   
-----------------日期：2015-06-02                 
--====================================================================================

CREATE    PROC Gp_RecieptToInibill

--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #GRIRTotal
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	Total DECIMAL(22,10),
	NTotal DECIMAL(22,10),
	Billtype VARCHAR(50),
	Comment VARCHAR(50),
	Sort int
)

DECLARE @startdate DATETIME,@Comment VARCHAR(500)
SELECT @startdate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth



	
--按余额转入期初，将BType_ARAPTotal暂估余额转入期初单据
IF EXISTS(SELECT TOP 1 1 FROM dbo.BType_ARAPTotal WHERE (GRIRTotal<>0 AND NGRIRTotal<>0)) 
BEGIN
	
	--之前生成的未结算完成的应付增加或减少应该已经被删除了
	
	
	
	SET @Comment='数据结转时暂估余额转入！'
	INSERT INTO #GRIRTotal
	( 
			BTypeID ,
			STypeID ,
			DtypeId,
			EtypeId,
			CID ,
			Total ,
			NTotal ,
			billtype ,
			Comment ,
			Sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			ABS(SUM(Total)),
			ABS(SUM(NTotal)),
			CASE WHEN SUM(Total)>0 
					THEN 128
				 ELSE 129
			END,
			'数据结转时暂估余额转入',
			0						
	FROM	--BType_ARAPTotal 
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total,NTotal 
		FROM dbo.ListTable 
		WHERE AtypeId IN
		(SELECT NID FROM Ac_Items WHERE UserCode='2122')
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,CID,GRIRTotal00,NGRIRTotal00 
		FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(Total)<>0 AND SUM(Total)<>0
	

END

DECLARE @newid varchar(9)	


	
IF EXISTS(SELECT 1 FROM #GRIRTotal) 
BEGIN
	
	SET @newid=LEFT(NEWID(),9)   --避免同一天连续年节产生的期初单据编号相等
	
	INSERT INTO [dbo].[BillIndex] 
	(
		[ifyearbill],
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DEALBTYPEID,
		cid,	
		rate,	
		NTotalmoney,
		NTotalinmoney,	
		npreferencemoney,	
		nvipczmoney,	
		atypeid1,
		billproperty,
		ncompletetotal,
		IsIni
	)

	SELECT	
		1,
		0.00,
		CONVERT(DATE, @startdate),
		CASE Billtype 
			WHEN '116' THEN 'IniYzBill-' 
			WHEN '115' THEN 'IniYjBill-' 
			WHEN '128' THEN 'IniFzBill-'
			WHEN '129' THEN 'IniFjBill-'
		END + @newid + STypeID+'-'+CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(Sort AS VARCHAR(10)),
		billtype,
		Comment,
		'',
		'',
		'',
		etypeid,
		'',
		'',
		't',
		'',
		0,
		Total,
		0,
		0,
		1,
		'',
		0,
		0,
		0,
		'',
		'',
		'',
		'',
		0,
		9999,
		0,
		'',
		'',
		'',
		dtypeid,
		'',
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		STypeID,
		0,
		0,
		0,
		-1,
		'',
		@startdate,
		NULL,
		0,
		'',
		'',
		'',
		'',
		'',
		'',
		cid,	
		CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN Total/NTotal ELSE NTotal/Total END,	
		NTotal,
		0,	
		0,	
		0,	
		(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
		1,
		0,
		1
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY stypeid,DTypeId,etypeid,cid) Sort,
				Stypeid,	
				DTypeId,
				etypeid,
				CID,
				BillType,
				Comment,
				SUM(Total) AS Total,
				SUM(NTotal) AS NTotal
		FROM #GRIRTotal
		GROUP BY Stypeid,DTypeId,etypeid,CID,BillType,Comment
	)b	

	INSERT INTO dbo.AdDebtBill
	( 
			  BillNumberId ,
	          Comment ,
	          BtypeId ,
	          total ,
	          CompleteTotal ,
	          Stypeid ,
	          NTotal ,
	          NCompleteTotal
	)
	SELECT	  b.BillNumberId,
			  '',
			  ba.btypeid,
			  Total,
			  0,
			  ba.stypeid,
			  NTotal,
			  0
	FROM	#GRIRTotal ba
	INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid
	WHERE	b.BillType IN (128,129)
			AND b.IsIni=1
			AND ifYearBill=0
			AND b.Comment=ba.comment
	
	IF @@ERROR<>0
		RAISERROR('处理暂估余额失败！',16,1)       
END

--按余额转入期初，将BType_ARAPTotal发出商品余额转入期初单据
--按余额转入期初，将BType_ARAPTotal发出商品余额转入期初单据



TRUNCATE TABLE #GRIRTotal

IF EXISTS(SELECT TOP 1 1 FROM dbo.BType_ARAPTotal WHERE (FCTotal<>0 AND NFCTotal<>0)) 
BEGIN
	--之前生成的未结算完成的应收增加或减少应该已经被删除了
	SET @Comment='数据结转时发出商品余额转入！'
	INSERT INTO #GRIRTotal
	( 
			BTypeID ,
			STypeID ,
			DtypeId,
			EtypeId,
			CID ,
			Total ,
			NTotal ,
			billtype ,
			Comment ,
			Sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			ABS(SUM(Total)),
			ABS(SUM(NTotal)),
			CASE WHEN SUM(Total)>0 
					THEN 116
				 ELSE 115
			END,
			'数据结转时发出商品余额转入',
			0						
	FROM	--BType_ARAPTotal 
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total,NTotal 
		FROM dbo.ListTable 
		WHERE AtypeId IN
		(SELECT NID FROM Ac_Items WHERE UserCode='1251')
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,CID,FCTotal00,NFCTotal00 
		FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(Total)<>0 AND SUM(Total)<>0
END

	
	
IF EXISTS(SELECT 1 FROM #GRIRTotal) 
BEGIN
	SET @newid=LEFT(NEWID(),9)   --避免同一天连续年节产生的期初单据编号相等
	
	INSERT INTO [dbo].[BillIndex] 
	(
		[ifyearbill],
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DEALBTYPEID,
		cid,	
		rate,	
		NTotalmoney,
		NTotalinmoney,	
		npreferencemoney,	
		nvipczmoney,	
		atypeid1,
		billproperty,
		ncompletetotal,
		IsIni
	)

	SELECT	
		1,
		0.00,
		CONVERT(DATE, @startdate),
		CASE Billtype 
			WHEN '116' THEN 'IniYzBill-' 
			WHEN '115' THEN 'IniYjBill-' 
			WHEN '128' THEN 'IniFzBill-'
			WHEN '129' THEN 'IniFjBill-'
		END + @newid + STypeID+'-'+CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(Sort AS VARCHAR(10)),
		billtype,
		Comment,
		'',
		'',
		'',
		etypeid,
		'',
		'',
		't',
		'',
		0,
		Total,
		0,
		0,
		1,
		'',
		0,
		0,
		0,
		'',
		'',
		'',
		'',
		0,
		9999,
		0,
		'',
		'',
		'',
		dtypeid,
		'',
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		STypeID,
		0,
		0,
		0,
		-1,
		'',
		@startdate,
		NULL,
		0,
		'',
		'',
		'',
		'',
		'',
		'',
		cid,	
		CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN Total/NTotal ELSE NTotal/Total END,	
		NTotal,
		0,	
		0,	
		0,	
		(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
		1,
		0,
		1
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY stypeid,DTypeId,etypeid,cid) Sort,
				Stypeid,	
				DTypeId,
				etypeid,
				CID,
				BillType,
				Comment,
				SUM(Total) AS Total,
				SUM(NTotal) AS NTotal
		FROM #GRIRTotal
		GROUP BY Stypeid,DTypeId,etypeid,CID,BillType,Comment
	)b	

	INSERT INTO dbo.AdDebtBill
	( 
			  BillNumberId ,
	          Comment ,
	          BtypeId ,
	          total ,
	          CompleteTotal ,
	          Stypeid ,
	          NTotal ,
	          NCompleteTotal
	)
	SELECT	  b.BillNumberId,
			  '',
			  ba.btypeid,
			  Total,
			  0,
			  ba.stypeid,
			  NTotal,
			  0
	FROM	#GRIRTotal ba
	INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid
	WHERE	b.BillType IN (116,115)
			AND b.IsIni=1
			AND ifYearBill=0
			AND b.Comment=ba.comment
	
	IF @@ERROR<>0
		RAISERROR('处理发出商品余额失败！',16,1)       
END


TRUNCATE TABLE #GRIRTotal
DROP TABLE #GRIRTotal

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ReCreateDepreciationPlan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_ReCreateDepreciationPlan
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/05/22
	Description	:	从新生成折旧计划表
*/
CREATE PROCEDURE Gp_ReCreateDepreciationPlan
(
	@CardID				INT,    				--卡片ID
	@PeriodFlag			INT						--0 从下期开始，1从本期开始算
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE  @Stypeid	VARCHAR(50),
		 @FYear		VARCHAR(10),
		 @FPeriod	 INT,     
		 @YearOrder  INT=-1,      --当期期的年次
		 @MonthOrder INT=-1,      --当前期的月次
		 @PlanState  INT       --当前期是否折旧

SELECT @Stypeid=aac.StypeId 
FROM  dbo.AC_AssetsCards ac 
JOIN dbo.Ac_AssetsCategory aac ON ac.CategoryId=aac.Id 
WHERE ac.Id=@CardID

--获取指定分支机构当前年度,财务期间	
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Stypeid)
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Stypeid
ELSE 
	BEGIN
		SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName='fyear'
		SELECT @FPeriod=SubValue FROM dbo.sysdata WHERE SubName='fperiod'
	END
		
IF @Fperiod=13 SET @Fperiod=12       

--如果本来就是手工折旧，一期有多次折旧，取最大的monthorder，所以要order by desc
SELECT TOP 1 @YearOrder=ISNULL(YearOrder,-1),@MonthOrder=ISNULL(MonthOrder,-1),@PlanState=PlanState  
FROM Ac_DepreciationPlan 
WHERE AssetCardId=@CardID AND Fyear=@Fyear AND Fperiod=@FPeriod AND plantype=1 
ORDER BY MonthOrder DESC

---修改bug，证明中间有断层（比如先双倍后改为手工，期末结账几期后又改回双倍）
IF @YearOrder=-1 OR @MonthOrder=-1
	SELECT TOP 1 @YearOrder=ISNULL(YearOrder,0),@MonthOrder=ISNULL(MonthOrder,0)+1  --这里必须+1，在取旧折旧数据的时候才正确
	FROM Ac_DepreciationPlan 
	WHERE AssetCardId=@CardID  AND plantype=1  --AND PlanState = 1
	ORDER BY MonthOrder DESC

DECLARE ---卡片参数
		@CardNetValue		 NUMERIC(24, 10) ,
		@DepreciationMean	INT,
        @DepreciationMonth	INT,             --已折旧月份
        @Depreciation		 NUMERIC(24, 10) ,
        @YearRate			 NUMERIC(24, 10) ,
        @DurYear			INT,			 --折旧年限的总年数
        @DurMonth			INT,			 --折旧年限的月数
        @DevalueReady		 NUMERIC(24, 10) ,  --当前卡片的减值准备
		@DepTotal            NUMERIC(24, 10) ,	 --卡片上的累计折旧额
        @Total				 NUMERIC(24, 10) ,  --原值
		@NetValue			 NUMERIC(24, 10) ,  --净值
		@NetSalvage			 NUMERIC(24, 10) ,  --账面净残值
		---辅助参数
		@tempFyear INT=CONVERT(INT,@FYear),   
		@tempFperiod int=@FPeriod,
        @Months INT,					--折旧年限的总月次
        --@planMonth INT,					--预计还折旧月数,@Months-@tempMonth+1
        @tempYear int,					--年次
		@tempMonth INT=@MonthOrder+1,   --即将折旧的期间变量
		@tempPeriod int=1,				--临时期间数，每12期重算一次月折旧额
		@tempDepTotal		 NUMERIC(24, 10) ,	 --临时累计折旧额
		@AVGMonthValue		 NUMERIC(24, 10) ,   --月折旧额
		@tempAVGMonthValue	 NUMERIC(24, 10) ,   --临时月折旧额
		---双倍法的参数
        @RemainMonth INT,
        @tempYears INT,
        @YearPeriod INT=12,
        @tempYearOrder INT=1,
        @tempMonthOrder INT=1,
        @AVGYears INT,
        @tempAVGYearValue    NUMERIC(24, 10) ,
        @tempDoubleYearValue  NUMERIC(24, 10) ,
        @Flag INT=0,--转换标志   
	    @LoopMonth INT
	

SELECT @DurYear=DurYear,@Durmonth=durmonth,@DepreciationMean=DepreciationMean,@DepreciationMonth=DepreciationMonth,
	   @DevalueReady=DevalueReady,@Total=total,@NetSalvage=NetSalvage,@DepTotal=DepTotal,@CardNetValue=NetValue
FROM Ac_AssetsCards WHERE ID=@CardID

SET @Months=@DurYear*12+@Durmonth
SET @tempYear=@YearOrder
--SET @planMonth=@Months-@tempMonth+1

IF (@Months- @DepreciationMonth)=0 AND (@DepreciationMean=2 OR @DepreciationMean=3)--已折旧完
			RETURN -1
IF (@CardNetValue=@NetSalvage) --无可折旧额
			RETURN -3


SET @tempAVGMonthValue=(@Total-@NetSalvage-@DepTotal-@DevalueReady)/(@Months- @DepreciationMonth)  --平均年限法的月折旧额
SET @YearRate=2/(@DurYear+0.0)     --+0.0才能商小数
SET @AVGYears=@DurYear             --当做除数

CREATE TABLE #oldData
(
		STypeId			VARCHAR(50),
		DTypeid			VARCHAR(50),
		CategoryId		INT,
		InAccountDate	DATETIME,
		UserCode		VARCHAR(200),
		FullName		VARCHAR(200),
		DepreciationMean	INT,
		YearOrder		INT,
		MonthOrder		INT,
		FYear			INT,
		FPeriod			INT,
		PlanType		INT,
		AssetCardId		INT,
		LocationId		INT,
		DisATypeId		VARCHAR(50),
		Depreciation	 NUMERIC(24, 10) ,
		DepTotal		 NUMERIC(24, 10) ,
		Total			 NUMERIC(24, 10) ,
		DevalueReady	 NUMERIC(24, 10) ,
		NetValue		 NUMERIC(24, 10) ,
		NetSalvage		 NUMERIC(24, 10) ,
		PlanState		INT,
		billnumberid    int
)
----1 把月计划表当期及以前的数据和年计划表当年以前的数据保存起来
IF @DepreciationMean=2 
		 INSERT INTO #oldData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,FYear,FPeriod,
						  PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,billnumberid)
		 SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,FYear,FPeriod,
				PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,billnumberid
		 FROM Ac_DepreciationPlan
		 WHERE AssetCardId=@CardID AND ((@PeriodFlag=0 AND MonthOrder<=@MonthOrder) OR (@PeriodFlag=1 AND MonthOrder<@MonthOrder)) AND plantype=1							--月 
ELSE IF @DepreciationMean=3 
		INSERT INTO #oldData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,FYear,FPeriod,
							 PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,billnumberid)
		 SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,FYear,FPeriod,
				PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,billnumberid
		 FROM Ac_DepreciationPlan
		 WHERE AssetCardId=@CardID AND ((@PeriodFlag=0 AND MonthOrder<=@MonthOrder) OR (@PeriodFlag=1 AND MonthOrder<@MonthOrder)) AND plantype=1                          --月 	
ELSE IF @DepreciationMean=1 OR @DepreciationMean=0 OR @DepreciationMean=5     --改为手工或不折旧，把原生成的折旧表后面的数据删除掉,年折旧重新生成
	BEGIN
		IF @PeriodFlag=1  --当期的也要删除
			DELETE FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND monthorder>=@MonthOrder
		ELSE 
			DELETE FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND monthorder>@MonthOrder
		DELETE FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=0 AND YearOrder>=@YearOrder
		
		
		---重算年折旧
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@FYear)
			BEGIN
				 ;WITH t AS 
				(
					SELECT AssetCardId,SUM(Depreciation) AS Depreciation,COUNT(*) AS fperiod,fyear,MAX(MonthOrder) AS MonthOrder
					FROM Ac_DepreciationPlan WHERE PlanType=1 AND AssetCardId=@CardID AND FYear=@FYear GROUP BY AssetCardId,FYear	
				)
				INSERT INTO Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
								FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
				SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,n.YearOrder,NULL,@Fyear,t.fperiod,
								   0,n.AssetCardId,LocationId,DisATypeId,dbo.F_RoundTotal(t.Depreciation),dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),1
				FROM t 
				JOIN Ac_DepreciationPlan n ON t.AssetCardId=n.AssetCardId AND t.MonthOrder=n.MonthOrder AND n.PlanType=1 
			END
		DROP TABLE #oldData
		RETURN
	END


CREATE TABLE #newData
(
		STypeId			VARCHAR(50),
		DTypeid			VARCHAR(50),
		CategoryId		INT,
		InAccountDate	DATETIME,
		UserCode		VARCHAR(200),
		FullName		VARCHAR(200),
		DepreciationMean	INT,
		YearOrder		INT,
		MonthOrder		INT,
		FYear			INT,
		FPeriod			INT,
		PlanType		INT,
		AssetCardId		INT,
		LocationId		INT,
		DisATypeId		VARCHAR(50),
		Depreciation	 NUMERIC(24, 10) ,
		DepTotal		 NUMERIC(24, 10) ,
		Total			 NUMERIC(24, 10) ,
		DevalueReady	 NUMERIC(24, 10) ,
		NetValue		 NUMERIC(24, 10) ,
		NetSalvage		 NUMERIC(24, 10) ,
		PlanState		INT,
		billnumberid    int
)
 

IF @PeriodFlag=0 --从下期算
	BEGIN
		SET @tempMonth =@MonthOrder+1
		SET @LoopMonth = @Months - @DepreciationMonth + 1
		SET @tempFperiod =@FPeriod
	END
	
ELSE 
	BEGIN
		SET @tempMonth =@MonthOrder
		SET @LoopMonth = @Months - @DepreciationMonth 
		IF @FPeriod=1
		begin
		    set @tempFyear=@tempFyear-1
			SET @tempFperiod=12
			end
		ELSE 
			SET @tempFperiod =@FPeriod-1
	END
	
----2 平均年限法先重算月计划表
IF @DepreciationMean=2 
BEGIN
	WHILE @tempMonth<=@Months
		BEGIN
			IF @PeriodFlag=0  --从下期开始算
				BEGIN
					--取累计数,第一期从#olddata取，以后期从#newData取前一期的
					IF @tempMonth=@MonthOrder+1
						SELECT @tempDepTotal=DepTotal FROM #oldData WHERE MonthOrder=@MonthOrder 
					ELSE 
						SELECT @tempDepTotal=DepTotal FROM #newData  WHERE MonthOrder=@tempMonth-1
				END
			ELSE 
				BEGIN
					--取累计数,第一期从#olddata取，以后期从#newData取前一期的
					IF @tempMonth=@MonthOrder
						SELECT @tempDepTotal=DepTotal FROM #oldData WHERE MonthOrder=@MonthOrder-1 
					ELSE 
						SELECT @tempDepTotal=DepTotal FROM #newData  WHERE MonthOrder=@tempMonth-1
				END
			 
		
			--计算月折旧额,重算的最后一期或者每12期比较特殊 
			IF @tempMonth=@Months  --最后一期
					set @AVGMonthValue=@Total-@NetSalvage-@DevalueReady-@tempDepTotal
			ELSE IF @tempPeriod%12=0
				SET @AVGMonthValue=(@Total-@NetSalvage-@DepTotal-@DevalueReady)*12/(@Months- @DepreciationMonth)-@tempAVGMonthValue*11
			ELSE 
				SET @AVGMonthValue=@tempAVGMonthValue 
			
			--计算累计折旧额
			SET @tempDepTotal=@tempDepTotal+@AVGMonthValue 
			
			--计算账面净值
			IF @PeriodFlag=0  --从下期开始算
				BEGIN
					IF @tempMonth=@MonthOrder+1
						BEGIN
							--SELECT @NetValue=NetValue FROM #oldData WHERE MonthOrder=@MonthOrder 
							--SET @NetValue=@NetValue-@DevalueReady-@AVGMonthValue
							SET @NetValue=@Total-@tempDepTotal-@DevalueReady
						END
					ELSE IF @tempMonth=@Months  --最后一期
						SET @NetValue=@NetSalvage
					ELSE 
						BEGIN
							SELECT @NetValue=NetValue FROM #newData  WHERE MonthOrder=@tempMonth-1
							SET @NetValue=@NetValue-@AVGMonthValue
						END
				END
			ELSE 
				BEGIN
					IF @tempMonth=@MonthOrder
							SET @NetValue=@Total-@tempDepTotal-@DevalueReady
					ELSE IF @tempMonth=@Months  --最后一期
						SET @NetValue=@NetSalvage
					ELSE 
						BEGIN
							SELECT @NetValue=NetValue FROM #newData  WHERE MonthOrder=@tempMonth-1
							SET @NetValue=@NetValue-@AVGMonthValue
						END
				END
					
			
			--年份，期间特殊处理
			IF @tempFperiod>=12
				BEGIN
					SET @tempFperiod=1
					SET @tempFyear=@tempFyear+1
					SET @tempYear=@tempYear+1    
				END
			ELSE 
				SET @tempFperiod=@tempFperiod+1
		
		    
			--插入数据
			INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
					FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,billnumberid)
			SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@tempYear,@tempMonth,@tempFyear,@tempFperiod,
				   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,NetSalvage,0,0
			FROM Ac_AssetsCards WHERE ID=@CardID 
			
			SET @tempPeriod=@tempPeriod+1  
			SET @tempMonth=@tempMonth+1
		END
		
	    --重算年
	    ;WITH t AS 
	    (
	    SELECT AssetCardId,YearOrder,SUM(Depreciation) AS Depreciation,MAX(MonthOrder) AS MonthOrder,COUNT(*) AS fperiod,Fyear 
		FROM 
		(
			SELECT AssetCardId,YearOrder,MonthOrder,Depreciation,FYear FROM #newData 
			UNION ALL 
			SELECT AssetCardId,YearOrder,MonthOrder,Depreciation,FYear FROM #oldData WHERE plantype=1
		) t 
		GROUP BY AssetCardId,YearOrder,FYear
	    )
		INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
							FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,billnumberid)
		SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,t.YearOrder,null,t.fyear,t.fperiod,
						   0,n.AssetCardId,LocationId,DisATypeId,t.Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,0,0 
		FROM t 
		JOIN 
		(
			SELECT * FROM #newData 
			UNION ALL 
			SELECT * FROM #oldData WHERE plantype=1
		) n ON t.YearOrder=n.YearOrder AND t.MonthOrder=n.MonthOrder
		 
		 
	   --清空数据
	   DELETE dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardId AND (PlanType=0 OR PlanType=1)
	    
	   --插入数据
	      INSERT INTO dbo.Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,FYear,MonthOrder,
					  PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,BillNumberId,FPeriod)
		SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,FYear,MonthOrder,
			  PlanType,AssetCardId,LocationId,DisATypeId,dbo.F_RoundTotal(Depreciation),dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),PlanState,BillNumberId,FPeriod
		FROM #newData	 
		UNION ALL 
		SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,FYear,MonthOrder,
			  PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,BillNumberId,FPeriod
		FROM #oldData	 
	
END
----3 双倍余额法
IF @DepreciationMean=3
	BEGIN
	    --剩余月数
		SET @RemainMonth=@DurYear*12-@DepreciationMonth
		IF @RemainMonth%12=0
			SET @tempYears=@RemainMonth/12
		ELSE 
			SET @tempYears=@RemainMonth/12 + 1
        
        SET @YearOrder=1
        SET @AVGYears=@tempYears
        WHILE @YearOrder<=@tempYears
			BEGIN
				IF @Flag=1   --已经是平均年限法了
					BEGIN
						--先取上一期的账面净值,累计折旧额
						SELECT @NetValue=NetValue,@tempDepTotal=DepTotal FROM #newData WHERE YearOrder=@YearOrder-1
						
						--最后一年,年折旧计算
						IF @YearOrder=@tempYears
							BEGIN
								SET @tempAVGYearValue=@Total-@tempDepTotal-@NetSalvage-@DevalueReady
								IF @RemainMonth%12<>0
									SET  @YearPeriod=@RemainMonth%12
							END
							
						--计算账面净值
						IF @YearOrder=@tempYears
							SET @NetValue=@NetSalvage
						ELSE 
							SET @NetValue=@NetValue-@tempAVGYearValue
						
						--计算累计折旧额
						SET @tempDepTotal=@tempDepTotal+@tempAVGYearValue
						
						 INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
						FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
						SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,@YearPeriod,
							   0,@CardID,LocationId,DisATypeId,@tempAVGYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
						FROM Ac_AssetsCards WHERE ID=@CardID 
					END
				ELSE 
					BEGIN
						--先取上一期的账面净值,因为双倍余额法不可能出现双倍算法到最后一期的情况，所以不用考虑最后一期,这里净值是取当期月净值
						IF @YearOrder=1    --当我是第一年的时候，取的是当前净值
							--SELECT TOP 1 @NetValue=NetValue FROM #oldData ORDER BY monthorder DESC        --最大月次的净值
							SELECT  @NetValue=NetValue FROM dbo.Ac_AssetsCards WHERE Id=@CardID
						ELSE 
							SELECT @NetValue=NetValue,@tempDepTotal=DepTotal FROM #newData WHERE YearOrder=@YearOrder-1
							
						--根据净值算年额度
						SET @tempDoubleYearValue=@NetValue*@YearRate
						SET @tempAVGYearValue=	(@NetValue-@NetSalvage)/@AVGYears
						
						---取上一期年积累折旧额
						IF @YearOrder=1     
							SELECT TOP 1  @tempDepTotal=DepTotal  FROM #oldData ORDER BY monthorder DESC        --最大月次的累计值
						ELSE 
							SELECT @tempDepTotal=DepTotal FROM #newData  WHERE YearOrder=@YearOrder-1
								
						--比较大小，看使用哪种方式
						IF (@tempDoubleYearValue<=@tempAVGYearValue) OR ((@NetValue-@tempDoubleYearValue)<@NetSalvage)    --符合转换条件，改用平均年限法
							BEGIN
								--计算累计折旧额
								SET @tempDepTotal=@tempDepTotal+@tempAVGYearValue
								
								--计算账面净值
								SET @NetValue=@NetValue-@tempAVGYearValue
						         
						         IF @YearOrder=@tempYears AND @RemainMonth%12<>0
									SET  @YearPeriod=@RemainMonth%12
						         		
								 INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
								FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
								SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,@YearPeriod,
									   0,@CardID,LocationId,DisATypeId,@tempAVGYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
								FROM Ac_AssetsCards WHERE ID=@CardID 
								
								SET @Flag=1         
							END
						ELSE 
							BEGIN
								 --计算累计折旧额
								SET @tempDepTotal=@tempDepTotal+@tempDoubleYearValue 
								
								--计算账面净值
								SET @NetValue=@NetValue-@tempDoubleYearValue
								
								INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
								FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
								SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,null,null,12,
									   0,@CardID,LocationId,DisATypeId,@tempDoubleYearValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
								FROM Ac_AssetsCards WHERE ID=@CardID 
							END
					END
				
				SET @YearOrder=@YearOrder+1
				SET @AVGYears=@AVGYears-1
			END
			
		--算月
		WHILE @tempYearOrder<=@tempYears
			BEGIN
				 --上期年净值，累计折旧额
				 IF @tempYearOrder=1 
					SELECT  @NetValue=NetValue,@tempDepTotal=deptotal FROM dbo.Ac_AssetsCards WHERE Id=@CardID
				 ELSE
				 	 SELECT @NetValue=NetValue,@tempDepTotal=deptotal FROM #newData WHERE YearOrder=@tempYearOrder-1
				 --本年的折旧额
				 SELECT @Depreciation=Depreciation FROM #newData WHERE YearOrder=@tempYearOrder
				 --月折旧额
				 IF (@tempYearOrder<>@tempYears OR  @RemainMonth%12=0 )
					SET @tempAVGMonthValue=@Depreciation/12
				 ELSE 
					SET @tempAVGMonthValue=@Depreciation/(@RemainMonth%12)
				 
				 SET @LoopMonth=1
				 
				 IF (@tempYearOrder<>@tempYears OR  @RemainMonth%12=0 )
					BEGIN
						WHILE @LoopMonth<=12
							BEGIN
								--月折旧额
								IF @LoopMonth=12
									SET @AVGMonthValue=@Depreciation-@tempAVGMonthValue*11
								ELSE
									SET @AVGMonthValue=@tempAVGMonthValue
								
								--累计折旧额
								SET @tempDepTotal=@tempDepTotal+@AVGMonthValue
								
								--账面净值 
								SET @NetValue=@NetValue-@AVGMonthValue
								
								--年份，期间特殊处理
								IF @tempFperiod>=12
									BEGIN
										SET @tempFperiod=1
										SET @tempFyear=@tempFyear+1
									END
								ELSE 
									SET @tempFperiod=@tempFperiod+1
									
								--插入数据
								INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
										FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
								SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@tempYearOrder,@tempMonthOrder,@tempFyear,@tempFperiod,
									   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
								FROM Ac_AssetsCards WHERE ID=@CardID 
								
								SET @LoopMonth=@LoopMonth+1
								SET @tempMonthOrder=@tempMonthOrder+1
							END	 
					END
				ELSE                       --最后一年且最后一年不满12个月的特殊处理
					BEGIN
							DECLARE @tempM INT
							SET @tempM=@RemainMonth%12
							
							WHILE @LoopMonth<=@tempM
								BEGIN
									--月折旧额
									IF @LoopMonth=@tempM
										SET @AVGMonthValue=@Depreciation-@tempAVGMonthValue*(@tempM-1)
									ELSE
										SET @AVGMonthValue=@tempAVGMonthValue
									
									--累计折旧额
									SET @tempDepTotal=@tempDepTotal+@AVGMonthValue
									
									--账面净值 
									SET @NetValue=@NetValue-@AVGMonthValue
									
									--年份，期间特殊处理
									IF @tempFperiod>=12
										BEGIN
											SET @tempFperiod=1
											SET @tempFyear=@tempFyear+1
										END
									ELSE 
										SET @tempFperiod=@tempFperiod+1
										
									--插入数据
									INSERT INTO #newData(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
											FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
									SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@tempYearOrder,@tempMonthOrder,@tempFyear,@tempFperiod,
										   1,@CardID,LocationId,DisATypeId,@AVGMonthValue,@tempDepTotal,Total,DevalueReady,@NetValue,@NetSalvage,0
									FROM Ac_AssetsCards WHERE ID=@CardID 
									
									SET @LoopMonth=@LoopMonth+1
									SET @tempMonthOrder=@tempMonthOrder+1
								END
					END
				SET @tempYearOrder=@tempYearOrder+1
			END
		
		---直接删除后面的数据
		DELETE FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND MonthOrder NOT IN (SELECT MonthOrder FROM #oldData)
		--更新月折旧表的月次
		UPDATE #newData SET monthorder=monthorder+@DepreciationMonth
		--插入月折旧表
		INSERT INTO dbo.Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,FYear,MonthOrder,
					  PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,BillNumberId,FPeriod)
		SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,FYear,MonthOrder,
			  PlanType,AssetCardId,LocationId,DisATypeId,dbo.F_RoundTotal(Depreciation),dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),PlanState,BillNumberId,FPeriod
		FROM #newData WHERE PlanType=1  
		
		--更新月折旧的年次
		UPDATE ac SET YearOrder=t.YearOrder
		FROM Ac_DepreciationPlan ac JOIN 
		(
		 SELECT ROW_NUMBER() OVER (ORDER BY FYear) AS YearOrder,FYear FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardId AND PlanType=1 GROUP BY FYear
		) t ON ac.Fyear=T.Fyear
		WHERE ac.AssetCardId=@CardId AND ac.PlanType=1
	 
		---直接删除年
		DELETE FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=0
		
		--重算年
		 ;WITH t AS 
		(
			SELECT AssetCardId,YearOrder,SUM(Depreciation) AS Depreciation,COUNT(*) AS fperiod,fyear,MAX(MonthOrder) AS MonthOrder
			FROM Ac_DepreciationPlan WHERE AssetCardId=@CardId AND PlanType=1  GROUP BY AssetCardId,YearOrder,FYear	
		)
		INSERT INTO Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
						FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
		SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,t.YearOrder,NULL,t.FYear,t.fperiod,
						   0,n.AssetCardId,LocationId,DisATypeId,dbo.F_RoundTotal(t.Depreciation),dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),0 
		FROM t 
		JOIN Ac_DepreciationPlan n ON t.YearOrder=n.YearOrder AND t.MonthOrder=n.MonthOrder  AND n.AssetCardId=@CardId
		
		--修改年状态
		IF EXISTS(SELECT TOP 1 1 FROM Ac_DepreciationPlan WHERE AssetCardId=@CardId AND PlanState=1)
			UPDATE ac SET PlanState=1
			from Ac_DepreciationPlan ac
			JOIN (
					SELECT DISTINCT fyear FROM  Ac_DepreciationPlan WHERE AssetCardId=@CardId AND PlanState=1 AND PlanType=1
			     ) t ON ac.FYear=t.Fyear
			WHERE AssetCardId=@CardId AND ac.PlanType=0
	END
----4 年数总和法
IF @DepreciationMean=4
BEGIN
	DECLARE  @PlanNetVale	 NUMERIC(24, 10)    --还将折旧额
			,@PlanDurYear	 INT				--还将折旧年度
			,@MonthNetVale	 NUMERIC(24, 10)    --每月账面净值
			,@tempYearDepRate  NUMERIC(24, 10)     --每年次的年折旧率
			,@tempYearDep		 NUMERIC(24, 10)     --年折旧额
			,@tempMonthDep		 NUMERIC(24, 10)     --月折旧额
			,@tempMonthDepTotal		 NUMERIC(24, 10)     --月累计折旧额
			,@tempCurrentYearDep	 NUMERIC(24, 10)  --当前年份折旧额
			,@currentDepTotal	 NUMERIC(24, 10)   -- 已累积折旧额
			,@tempYearPeriod		INT			--年期间数
			,@Loop					INT
			
	SELECT @tempFperiod = FPeriod,@tempMonth =MonthOrder,@tempFyear = FYear,@tempYearOrder = YearOrder 
	FROM dbo.Ac_DepreciationPlan 
	WHERE AssetCardId = @CardID AND FYear = @FYear AND FPeriod = @FPeriod AND PlanType = 1
		
	SELECT @tempYearPeriod = COUNT(1),@tempCurrentYearDep = SUM(Depreciation)
	FROM dbo.Ac_DepreciationPlan 
	WHERE AssetCardId = @CardID AND YearOrder = @tempYearOrder AND PlanState = 1 AND PlanType = 1 AND MonthOrder <= @tempMonth
	
	SELECT @PlanNetVale = ISNULL(NetValue - NetSalvage,0),@MonthNetVale = NetValue 
	FROM Ac_AssetsCards 
	WHERE ID = @CardID
	
	IF @PeriodFlag=0 --从下期算
	BEGIN
		SET @tempFperiod +=1
		SET @tempYearPeriod += 1
		SET @tempMonth +=1
		
		IF @tempFperiod > 12
		BEGIN
			SET @tempFperiod = 1
			SET @tempYearOrder += 1
			SET @tempYearPeriod = 1
			SET @tempCurrentYearDep = 0
		END
	END
	
	DELETE FROM Ac_DepreciationPlan WHERE AssetCardId=@CardID AND (MonthOrder >= @tempMonth OR (YearOrder >=@tempYearOrder AND PlanType =0))  --删除后面的折旧计划
	
	SET @LoopMonth = @Months-@DepreciationMonth	
	SET @PlanDurYear = CEILING(@LoopMonth/12.00)
	SET @tempYear = 1
	SET @tempPeriod = 1
	SET @tempMonthDepTotal = @DepTotal
	SET @tempYearDepRate = (@PlanDurYear + 1 - @tempYear)/(@PlanDurYear * (@PlanDurYear + 1) / 2 + 0.0000000000)      --计算年折旧率
	SET @tempYearDep = @PlanNetVale * @tempYearDepRate  --计算年折旧额
	SET @tempMonthDep = @tempYearDep / 12   --用年折旧额除以该年总月次得到月折旧额
	SET @Loop = 1
	
	--如果最后一年不足12月的情况，要重新分摊每月折旧额
	IF @tempYear = @PlanDurYear
		SET @tempMonthDep = @tempYearDep / (@LoopMonth%12)   --用年折旧额除以该年总月次得到月折旧额	
	
	WHILE @Loop <= @LoopMonth
	BEGIN		
		SET @tempMonthDepTotal += @tempMonthDep   --计算月累计折旧额
		SET @tempCurrentYearDep += @tempMonthDep   --计算当前年份折旧额
		SET @MonthNetVale -= @tempMonthDep   --计算月账面净值
		
		INSERT INTO Ac_DepreciationPlan(
				STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
		SELECT	STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,4,@tempYearOrder,@tempMonth,@tempFyear,@tempFperiod,1,n.id,LocationId,DisATypeId,dbo.F_RoundTotal(@tempMonthDep),dbo.F_RoundTotal(@tempMonthDepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(@MonthNetVale),dbo.F_RoundTotal(NetSalvage),0 
		FROM Ac_AssetsCards n
		WHERE n.Id = @CardID 
		
		--当计划执行12个月后，即满1年后，重新计算月折旧额数据
		IF @tempPeriod = 12
		BEGIN 			
			SET @tempPeriod = 1
			SET @tempYear +=1
			SET @tempYearDepRate = (@PlanDurYear + 1 - @tempYear)/(@PlanDurYear * (@PlanDurYear + 1) / 2 + 0.0000000000)      --计算年折旧率
			SET @tempYearDep = @PlanNetVale * @tempYearDepRate  --计算年折旧额
			SET @tempMonthDep = @tempYearDep / 12   --用年折旧额除以该年总月次得到月折旧额	
			
			--如果最后一年不足12月的情况，要重新分摊每月折旧额
			IF @tempYear = @PlanDurYear
				SET @tempMonthDep = @tempYearDep / (@LoopMonth%12)   --用年折旧额除以该年总月次得到月折旧额						
		END 
		ELSE
		BEGIN
			SET @tempPeriod +=1
		END
		
		--到下一个期间年或最后一个折旧期间时，要写入当前年度计划
		IF @tempFperiod = 12 OR @Loop = @LoopMonth 
		BEGIN
			----------插入年计划---------
			INSERT INTO Ac_DepreciationPlan(
					STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,FYear,FPeriod,PlanType,AssetCardId,LocationId,DisATypeId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
			SELECT	STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,4,@tempYearOrder,NULL,@tempFyear,@tempYearPeriod,0,n.id,LocationId,DisATypeId,dbo.F_RoundTotal(@tempCurrentYearDep),dbo.F_RoundTotal(@tempMonthDepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(@MonthNetVale),dbo.F_RoundTotal(NetSalvage),0 
			FROM Ac_AssetsCards n
			WHERE n.Id = @CardID 
			
			SET @tempFperiod = 1
			SET @tempYearPeriod = 1
			SET @tempFyear += 1
			SET @tempYearOrder += 1
			SET @tempCurrentYearDep = 0
		END 
		ELSE
		BEGIN
			SET @tempFperiod +=1
			SET @tempYearPeriod += 1
		END
				
		SET @tempMonth +=1
		SET @Loop += 1
	END
	
END 
 
 
  
RETURN 0
DROP TABLE #oldData,#newData

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	

 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RedWordDeleteData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_RedWordDeleteData
GO

-- =============================================
-- Author:		唐韬
-- Create date: 2015-06-09 08:20:14.200
-- Description: 单据红冲前删除关联数据
-- =============================================

CREATE PROCEDURE Gp_RedWordDeleteData
(
	@nBillID NUMERIC(10,0),
	@nBillType INT
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

CREATE TABLE #tempbillid(BillNumberId NUMERIC(10,0))

IF @nBillType=400 
BEGIN
		--暂估入库单涉及到有暂估退货单草稿
		INSERT INTO #tempbillid
		SELECT b.BillNumberId FROM BillIndex a JOIN  AppraisalBackBill b
		ON a.BillNumberId = b.BillNumberId
		WHERE b.OldBillNumberID = @nBillID
		AND a.ifcheck='f' AND a.draft='1'
END
ELSE IF @nBillType=402
BEGIN 
		--发出商品出库单涉及到有发出商品退货单草稿
		INSERT INTO #tempbillid
		SELECT b.BillNumberId  FROM BillIndex a JOIN  SendBackBill b
		ON a.BillNumberId = b.BillNumberId
		WHERE b.OldBillNumberID = @nBillID
		AND a.ifcheck='f' AND draft='1'		
END

DECLARE @count INT = 0
SELECT @count = COUNT(1) FROM  #tempbillid

IF @count > 0
BEGIN

	IF @nBillType=400 
	BEGIN
		DELETE FROM a FROM AppraisalBackBill a  JOIN #tempbillid b ON a.BillNumberId = b.BillNumberId
	END
	ELSE IF @nBillType=402
	BEGIN 
		DELETE FROM a FROM SendBackBill a		JOIN #tempbillid b ON a.BillNumberId = b.BillNumberId
	END
	
	DELETE FROM a FROM BillIndex a				JOIN #tempbillid b ON a.BillNumberId = b.BillNumberId
	
END

DROP TABLE #tempbillid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RedWordInsertBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_RedWordInsertBill
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-14
-- Description: 单据红冲插入红单主表和明细

--修改人：冯波  发票立账各种处理  2015-05-26
-- =============================================

CREATE PROCEDURE Gp_RedWordInsertBill
(
	@nBillID			NUMERIC(10,0),
	@nNewBillID			NUMERIC(10,0) output,
	@nBillType			INT,
	@strPTypeIDOutPut	varchar(500) output,
	@tBillDate			DATETIME,
	@etypeid			varchar(50)	
)
--@encode$--

AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

DECLARE @nRet INT,
		@date DATETIME,
		@STypeID VARCHAR(100),					
		@vipBillStoredByStypeId INT=0--会员储值结算使用单据所选分支机构进行储值余额判断
SELECT @vipBillStoredByStypeId=Value FROM Userconfig WHERE ConfigName='vipBillStoredByStypeId'
					
SET @date=GETDATE()

IF @nBillType IN (71,72,87,88)
BEGIN
 INSERT INTO [dbo].[LendIndex] ([BillDate] ,[BillCode] ,[BillType] ,[Comment] ,[atypeid] ,[ptypeid] ,[btypeid] ,[dealbtypeid] ,[etypeid] ,[ktypeid] ,[ktypeid2] ,[ifcheck] ,[checke] ,[totalmoney] ,[totalinmoney] ,[totalqty]  , [tax] ,[period] ,[explain] ,[RedWord] ,[draft] ,[OrderId] ,[waybillcode] ,[goodsnumber] ,[packway] ,[TEL] ,[Uploaded] ,[OFF_ID] ,[DTypeID] ,[ID] ,[IfAudit] ,[Stypeid] ,[IsIni])
                         SELECT [BillDate] ,[BillCode] ,[BillType] ,[Comment] ,[atypeid] ,[ptypeid] ,[btypeid] ,[dealbtypeid] ,[etypeid] ,[ktypeid] ,[ktypeid2] ,[ifcheck] ,[checke] ,[totalmoney] ,[totalinmoney] ,-[totalqty] , [tax] , [period] , [explain] , 2 , [draft] , [OrderId] , [waybillcode] , [goodsnumber] , [packway] , [TEL] , [Uploaded] , [OFF_ID] , [DTypeID] , [ID] , [IfAudit] , [Stypeid] , [IsIni] FROM [dbo].[LendIndex] WHERE BillNumberId=@nBillID
END
ELSE IF @nBillType IN (404,405)
BEGIN
	--暂估发票	
	INSERT INTO ReceiptBillIndex(BillDate,BillCode,BillType,FaPiaoType,Comment,Explain,
	BTypeID,ETypeID,DTypeID,checke,Assessor,Tax,TotalQty,TotalMoney,TaxTotalMoney,
	Stypeid,OtherTotal,ifYearBill,IsIni,CID,Rate,NTotalMoney,NTaxTotalMoney,DealBTypeID,
	TaskType,AlertDay,RedWord,ifcheck,IfStopMoney,CompleteTotal,NCompleteTotal,Draft,
	JSState,JSStyle,Poster,checkTime,Posttime,UpdateE,ATypeID1,ATypeID2,Period,FaPiaoCode,IfAudit,ChargeOffTotal,NChargeOffTotal)
	SELECT BillDate,BillCode,BillType,FaPiaoType,Comment,Explain,
	BTypeID,ETypeID,DTypeID,checke,Assessor,Tax,TotalQty,TotalMoney,TaxTotalMoney,
	Stypeid,OtherTotal,ifYearBill,IsIni,CID,Rate,NTotalMoney,NTaxTotalMoney,DealBTypeID,
	TaskType,AlertDay,2,ifcheck,IfStopMoney,CompleteTotal,NCompleteTotal,Draft,
	JSState,JSStyle,Poster,checkTime,@date,UpdateE,ATypeID1,ATypeID2,Period,FaPiaoCode,IfAudit,ChargeOffTotal,NChargeOffTotal
	FROM ReceiptBillIndex
	WHERE BillNumberID=@nBillID
	
	SELECT @STypeID=STypeID FROM dbo.ReceiptBillIndex WHERE BillNumberID=@nBillID
END
ELSE IF @nBillType IN(412,413)
BEGIN
	--上架单、拣货单
	INSERT  INTO dbo.onShelvespickIndex ( etypeid ,ktypeid , BillDate , Billcode , billtype ,totalqty ,period , comment , explain ,
	          Checke , IfAudit ,DtypeId ,Stypeid ,draft ,checkTime , posttime , updateE ,Poster , LastUpdateTime ,IsIni ,ifYearBill ,
	          RedWord , IfCheck , citestate ,RedReason
	        )
	SELECT etypeid ,ktypeid , BillDate , Billcode , billtype ,totalqty ,period , comment , explain ,
	          Checke , IfAudit ,DtypeId ,Stypeid ,draft ,checkTime , @date , updateE ,Poster , LastUpdateTime ,IsIni ,ifYearBill ,
	          2 , IfCheck , citestate ,RedReason
	FROM dbo.onShelvespickIndex WHERE billNumberId=@nBillID
	
	SELECT @STypeID=STypeID FROM dbo.onShelvespickIndex WHERE BillNumberID=@nBillID
END
ELSE IF @nBillType IN(418,419,420)
BEGIN
	INSERT INTO dbo.FactIndex
	        ( 
			  BillDate , BillCode , BillType ,Stypeid ,OtherType,dtypeId,
	          etypeid ,ktypeid , ktypeid2 , ifcheck ,checke ,checkTime ,RedWord ,
	          RedReason ,draft ,totalqty ,IsIni ,EntryCode ,Comment ,
	          explain ,updateE , Poster ,PostTime,FromBillType,ifcargo
	        )
	SELECT 	  BillDate , BillCode , BillType  ,Stypeid , OtherType,dtypeId,
	          etypeid ,ktypeid , ktypeid2 , ifcheck ,checke ,checkTime ,2 ,
	          RedReason ,draft ,totalqty ,IsIni ,EntryCode ,Comment ,
	          explain ,updateE , Poster ,PostTime,FromBillType,ifcargo
	FROM dbo.FactIndex WHERE BillNumberId=@nBIllID
	
	SELECT @STypeID=STypeID FROM dbo.FactIndex WHERE BillNumberID=@nBillID
END
ELSE IF @nBillType IN(327,328,329)--991新增门店配送单，门店配送退货单，门店验收单
BEGIN
    INSERT INTO dbo.PosAllotApplyBillIndex
	        ( 
			     [BillType],[BillCode],[BillDate],[ApplyEtypeId],[StypeId],[DtypeId],[KtypeId]
                ,[InKtypeId] ,[Qty] ,[Comment],[Explain] ,[BillState],[checkE] ,[IsAutoGenerate],[BillOver],[StopReason]
				 ,[Isdone] ,[checkTime],[RedWord],[ifcheck],[draft],[Checker],[CheckerTime],[Updater],[UpdaterTime],[CID],[Total])
	  SELECT 	[BillType],[BillCode],[BillDate],[ApplyEtypeId],[StypeId],[DtypeId],[KtypeId]
				 ,[InKtypeId] ,[Qty] ,[Comment],[Explain] ,[BillState],[checkE] ,[IsAutoGenerate],[BillOver],[StopReason]
				  ,[Isdone] ,[checkTime],2,[ifcheck],[draft],[Checker],[CheckerTime],[Updater],[UpdaterTime],[CID],[Total]
	FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId=@nBIllID
	
	SELECT @STypeID=STypeID FROM dbo.PosAllotApplyBillIndex WHERE BillNumberID=@nBillID
end
ELSE
BEGIN
	-----------------------------------------插入billindex start-----------------------------------
	INSERT INTO BillIndex (
			BillDate,
			BillCode,
			BillType,
			Comment,
			ATypeID,
			PTypeID,
			BTypeID,
			ETypeID,
			STypeID,
			KTypeID,
			KTypeID2,
			IfCheck,
			Checke,
			TotalQty,
			TotalMoney,
			TotalInMoney,
			Discount,
			Tax,
			Period,
			Explain,
			Draft,
			RedWord,
			OrderID,
			alertday,
			WayBillCode,
			GoodsNumber,
			PackWay,
			Tel,
			CompleteTotal,
			ID,
			preferencemoney,
			DTypeId,
			JF,
			VipCardID,
			vipCZMoney,
			--
			KTypeID3,
			LinkMan,
			LinkTel,
			LinkAddr,
			wxManID,
			JieJianBillNumberID,
			JieJianID,
			JieJianState,
			BaoXiuBillNumberID,
			BaoXiuID,
			BuyDate,
			Serial,
			wxTotal,
			ErrDes,
			ifHideJieJian,
			ifWX,
			ifYearBill,
			CWCheck,
			IfBargainOn,
			FromBillNumberID,
			CostSale,
			OtherInOutType,
			IfMulAccount,
			checkTime,
			posttime,
			updateE,
			poster,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			FreightAddr,
			FreightPerson,
			FreightTel,
			IsFreightMoney,
			TransportId,
			DealBTypeID,
			cid,
			Rate,
			NTotalMoney,
			NTotalInMoney,
			NPreferenceMoney,
			NVIPCZMoney,
			Atypeid1,
			NCompleteTotal,
			IfCargo,
			ARTotal,
			APTotal,
			YSTotal,
			YFTotal,
			AssetBusinessTypeId,
			PromoRuleId,
			BeforePromoBillNumberId,
			NewPosBill,
			PromotionMsg  ,
			IsYapi,
			StypeID2,
			IfConfirm,
			TransferType ,
			IsAuto,
			Billtime,
			AdPriceType,
			ChargeOffBtypeid,
			ChargeOffType,
			ChargeOffTotal,
			NChargeOffTotal
			,IsLend
			,iscombinationstyle
			,DeliveryAddress
			,PromonIds
			,isByBrandarType --收款单 是否按品牌收款
			,yjkbillcode
		)
		SELECT BillDate,
			BillCode,
			BillType,
			Comment,
			ATypeID,
			PTypeID,
			BTypeID,
			ETypeID,
			STypeID,
			KTypeID,
			KTypeID2,
			IfCheck,
			Checke,
			TotalQty,
			TotalMoney,
			TotalInMoney,
			Discount,
			Tax,
			Period,
			Explain,
			Draft,
			2,
			OrderID,
			AlertDay,
			waybillcode,
			goodsnumber,
			PackWay,
			Tel,
			CompleteTotal,
			0,
			preferencemoney,
			DTypeId,
			JF,
			VipCardID,
			vipCZMoney,
			KTypeID3,
			LinkMan,
			LinkTel,
			LinkAddr,
			wxManID,
			JieJianBillNumberID,
			JieJianID,
			JieJianState,
			BaoXiuBillNumberID,
			BaoXiuID,
			BuyDate,
			Serial,
			wxTotal,
			ErrDes,
			ifHideJieJian,
			ifWX,
			ifYearBill,
			CWCheck,
			IfBargainOn,
			FromBillNumberID,
			CostSale,
			OtherInOutType,
			IfMulAccount,
			checkTime,
			@date,
			updateE,
			poster,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			FreightAddr,
			FreightPerson,
			FreightTel,
			IsFreightMoney,
			TransportId,
			DealBTypeID,
			cid,
			Rate,
			NTotalMoney,
			NTotalInMoney,
			NPreferenceMoney,
			NVIPCZMoney,
			ATypeID1,
			NCompleteTotal,
			IfCargo,
			ARTotal,
			APTotal,
			YSTotal,
			YFTotal,
			AssetBusinessTypeId,
			PromoRuleId,
			BeforePromoBillNumberId,
			NewPosBill,
			PromotionMsg ,
			IsYapi,
			StypeID2,
			IfConfirm,
			TransferType  ,
			IsAuto,
			Billtime,
			AdPriceType,
			ChargeOffBtypeid,
			ChargeOffType,
			ChargeOffTotal,
			NChargeOffTotal,
			islend,
			iscombinationstyle,
			DeliveryAddress,
			PromonIds,
			isByBrandarType,
			yjkbillcode
		FROM BillIndex WHERE BillNumberId=@nBillID
		
		SELECT @STypeID=STypeID FROM dbo.BillIndex WHERE BillNumberID=@nBillID
END


	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
		RETURN -10
	ELSE
		SET @nNewBillId = SCOPE_IDENTITY();
	declare @szDate varchar(100),@DBName varchar(50)
	SET @szDate = CAST(YEAR(@tBillDate) AS varchar) + '-' + CAST(MONTH(@tBillDate) AS varchar) + '-' + CAST(DAY(@tBillDate) AS varchar)

	-- 取操作员名称
	DECLARE @strEmployeeFullName varchar(500)
	SET @strEmployeeFullName = ''

	IF @EtypeID = '' OR @EtypeID = '00001'
		SET @strEmployeeFullName = '超级用户'
	ELSE
	BEGIN
		SELECT	@strEmployeeFullName = ISNULL(FullName,'')
		FROM	Employee
		WHERE	TypeID = @EtypeID
	END
	IF @strEmployeeFullName <> '' SET @strEmployeeFullName = '【红冲人】' + @strEmployeeFullName + ' '

	IF @nBillType IN (71,72,87,88)
	BEGIN
		UPDATE	dbo.LendIndex
		SET		Comment = CAST( @strEmployeeFullName + '红字反冲:' + @szDate + Comment AS varchar(256))
		WHERE	BillNumberID = @nNewBillID
	END
	ELSE IF @nBillType IN (418,419,420) --仓库入库单,仓库出库单,仓库调拨单
	BEGIN
		UPDATE	factindex
		SET		Comment = CAST( @strEmployeeFullName + '红字反冲:' + @szDate + Comment AS varchar(256))
		WHERE	BillNumberID = @nNewBillID		
	END
	ELSE IF @nBillType IN (404,405)
	BEGIN
		UPDATE	ReceiptBillIndex
		SET		Comment = CAST( @strEmployeeFullName + '红字反冲:' + @szDate + Comment AS varchar(256))
		WHERE	BillNumberID = @nNewBillID
	END
	ELSE IF @nBillType IN(412,413)
	BEGIN
		UPDATE  dbo.onShelvespickIndex 
		SET 	Comment = CAST( @strEmployeeFullName + '红字反冲:' + @szDate + Comment AS varchar(256))
		WHERE	BillNumberID = @nNewBillID
	END
	ELSE IF @nBillType IN(327,328,329)--991新增
	BEGIN
		UPDATE  dbo.PosAllotApplyBillIndex 
		SET 	Comment = CAST( @strEmployeeFullName + '红字反冲:' + @szDate + Comment AS varchar(256))
		WHERE	BillNumberID = @nNewBillID
	END
	ELSE
	BEGIN	
		UPDATE	BillIndex
		SET		Comment = CAST( @strEmployeeFullName + '红字反冲:' + @szDate + Comment AS varchar(256))
		WHERE	BillNumberID = @nNewBillID
	-----------------------------------------插入billindex end-----------------------------------
	END

	-----------------------------插入明细------------------------------------------
	CREATE TABLE #temptable(id INT IDENTITY(1,1),detailid INT)
     IF @nBillType = 11 --销售出库单
		BEGIN
	        INSERT INTO salebill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,PriceSource,IsGift,promoType ,LendBillID,LendBillNumberID,ShowOrder,etypeid,DraftFlag,IsIniFlag,PromonIds,couponcode,IsPromotion,IsVipPoint)
			OUTPUT INSERTED.ID INTO #temptable					
			SELECT	@nNewBillID,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,PriceSource,IsGift,promoType,LendBillID,LendBillNumberID,ShowOrder,etypeid,DraftFlag,IsIniFlag,PromonIds,couponcode,IsPromotion,IsVipPoint
			FROM SaleBill WHERE BillNumberID=@nBillID
		END
     ELSE IF @nBillType = 45 --销售退货单
		BEGIN
			INSERT INTO salebackbill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
									TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,promoType,ShowOrder,OldBillNumberID,OldID,etypeid,DraftFlag,IsIniFlag,couponcode)
			OUTPUT INSERTED.ID INTO #temptable	
			SELECT @nNewBillID,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
									TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,promoType,ShowOrder,OldBillNumberID,OldID,etypeid,DraftFlag,IsIniFlag,couponcode
			FROM  salebackbill  WHERE BillNumberID=@nBillID
		END
	 ELSE IF @nBillType = 12 --组合品销售出库单
		BEGIN
	        INSERT INTO PT_Combin_SaleBillDetail(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,PriceSource,IsGift,promoType ,LendBillID,LendBillNumberID,ShowOrder
								,DiyID,pindexid,combinationptypeid,DraftFlag,IsIniFlag)
			OUTPUT INSERTED.ID INTO #temptable					
			SELECT	@nNewBillID,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,PriceSource,IsGift,promoType,LendBillID,LendBillNumberID,ShowOrder
								,DiyID,pindexid,combinationptypeid,DraftFlag,IsIniFlag
			FROM PT_Combin_SaleBillDetail WHERE BillNumberID=@nBillID
			
			INSERT INTO PT_Combin_SaleBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,OrderID,
			TeamNo,TeamNO1,IsUnit2,InputCostPrice,GoodsOrder,BackQty,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax,KTypeID,Stypeid,ShareFee,TaxMoney,
			NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,
			MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,BeforePromoID,ReferPrice,PriceStyle,
			PriceSource,PromoType,CompleteTotal,NCompleteTotal,LendBillID,LendBillNumberID,ShowOrder,DiyID,pindexid,PromonIds,couponcode,IsPromotion,IsVipPoint)
			SELECT	@nNewBillID,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,OrderID,
			TeamNo,TeamNO1,IsUnit2,InputCostPrice,GoodsOrder,BackQty,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax,KTypeID,Stypeid,ShareFee,TaxMoney,
			NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,
			MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,BeforePromoID,ReferPrice,PriceStyle,
			PriceSource,PromoType,CompleteTotal,NCompleteTotal,LendBillID,LendBillNumberID,ShowOrder,DiyID,pindexid,PromonIds,couponcode,IsPromotion,IsVipPoint
			FROM PT_Combin_SaleBill
			WHERE BillNumberID=@nBillID
		
		END
	 ELSE IF @nBillType = 46 --组合品销售退货单
		BEGIN
			INSERT INTO PT_Combin_SaleBackBillDetail(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
									TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,promoType,ShowOrder,OldBillNumberID,OldID,
									pindexid,combinationptypeid,DraftFlag,IsIniFlag)
			OUTPUT INSERTED.ID INTO #temptable	
			SELECT @nNewBillID,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
									TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,promoType,ShowOrder,OldBillNumberID,OldID,
									pindexid,combinationptypeid,DraftFlag,IsIniFlag
			FROM  PT_Combin_SaleBackBillDetail  WHERE BillNumberID=@nBillID
			
			
			INSERT INTO PT_Combin_SaleBackBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,TeamNo,TeamNO1,
			IsUnit2,OldID,CostPrice,OldBillNumberID,InputCostPrice,GoodsOrder,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax,KTypeID,Stypeid,
			FromBillNumberID,FromBillID,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,
			MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,InvoiceQty,InvoiceMoney,NInvoiceMoney,
			IsGift,ReferPrice,PriceStyle,PromoType,CompleteTotal,NCompleteTotal,pindexid,ShowOrder,couponcode)
			SELECT @nNewBillID,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,total,OutFactoryDate,TaxPrice,TaxTotal,comment,TeamNo,TeamNO1,
			IsUnit2,OldID,CostPrice,OldBillNumberID,InputCostPrice,GoodsOrder,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQTY,SaleTotal,Tax,KTypeID,Stypeid,
			FromBillNumberID,FromBillID,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,
			MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,InvoiceQty,InvoiceMoney,NInvoiceMoney,
			IsGift,ReferPrice,PriceStyle,PromoType,CompleteTotal,NCompleteTotal,pindexid,ShowOrder,couponcode
			FROM PT_Combin_SaleBackBill
			WHERE BillNumberID=@nBillID
			
		END
     ELSE IF @nBillType = 4 --收款单
		 BEGIN
				INSERT INTO gatheringbill(BillNumberId,AtypeId,total,Comment,TeamNo,TeamNO1,STypeID,VipCardID,ntotal,ShowOrder,DraftFlag,IsIniFlag,BrandarTypeID,PreferenceMoney,NPreferenceMoney)
				OUTPUT INSERTED.ID INTO #temptable	
				SELECT @nNewBillID,AtypeId,total,Comment,TeamNo,TeamNO1,STypeID,VipCardID,ntotal,ShowOrder,DraftFlag,IsIniFlag,BrandarTypeID,PreferenceMoney,NPreferenceMoney
				FROM gatheringbill  WHERE BillNumberID=@nBillID
		 END
     ELSE IF @nBillType = 34 --采购入库单
		BEGIN
	        INSERT INTO buybill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNo1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,IsGift,LendBillID,LendBillNumberID,ShowOrder,AskBillID,AskBillNumberID,DraftFlag,IsIniFlag)
			OUTPUT INSERTED.ID INTO #temptable	
			SELECT @nNewBillID,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNo1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,IsGift,LendBillID,LendBillNumberID,ShowOrder,AskBillID,AskBillNumberID,DraftFlag,IsIniFlag
			FROM buybill WHERE BillNumberID=@nBillID
		END
     ELSE IF @nBillType = 6 --进货退货单
        INSERT INTO buybackbill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNo1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,ShowOrder,OldBillNumberID,OldID,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNo1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,ShowOrder,OldBillNumberID,OldID,DraftFlag,IsIniFlag
		FROM buybackbill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 66 --付款单
        INSERT INTO paybill(BillNumberId,AtypeId,total,Comment,TeamNo,TeamNO1,STypeID,VipCardID,ntotal,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,AtypeId,total,Comment,TeamNo,TeamNO1,STypeID,VipCardID,ntotal,ShowOrder,DraftFlag,IsIniFlag
		FROM paybill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 21 --变价调拨单
        INSERT INTO movebjbill(BillNumberId,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,KTypeId,KTypeId2,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,InCargoID,OutCargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,KTypeId,KTypeId2,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,InCargoID,OutCargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag
		FROM movebjbill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 17 --同价调拨单
        INSERT INTO movebill(BillNumberId,Comment,PtypeId,Qty,Price,Total,Jobnumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,KTypeId,KTypeId2,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,InCargoID,OutCargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,Comment,PtypeId,Qty,Price,Total,Jobnumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,KTypeId,KTypeId2,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,InCargoID,OutCargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag
		FROM movebill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 57 --调价单
        INSERT INTO adpricebill(BillNumberId,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate,ChangeAllStock,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,BeforePrice,BeforeTotal,Rate,NQty,UnitRate,IsCombined,ItemID,cargoID,ktypeid,Serial,ShowOrder,ChangeTotal,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate,ChangeAllStock,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,BeforePrice,BeforeTotal,Rate,NQty,UnitRate,IsCombined,ItemID,cargoID,ktypeid,Serial,ShowOrder,ChangeTotal,DraftFlag,IsIniFlag
		FROM adpricebill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 9 --报损单
        INSERT INTO losebill(BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,Price,Total,IsUnit2,STypeID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,CargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag,ktypeid)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,Price,Total,IsUnit2,STypeID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,CargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag,ktypeid
		FROM losebill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 139 --赠送单
        INSERT INTO GiveBill(BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,CargoID,ItemID,IsCombined,KTypeId,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,CargoID,ItemID,IsCombined,KTypeId,ShowOrder,DraftFlag,IsIniFlag
		FROM GiveBill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 14 --报溢单
        INSERT INTO overflowbill(BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,Price,Total,IsUnit2,STypeID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,CargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag,ktypeid)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,Price,Total,IsUnit2,STypeID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,CargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag,ktypeid
		FROM overflowbill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 126 --获增单
        INSERT INTO GivemeBill(BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,CargoID,ItemID,IsCombined,KTypeId,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,STypeID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,CargoID,ItemID,IsCombined,KTypeId,ShowOrder,DraftFlag,IsIniFlag
		FROM GivemeBill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType IN(36,93,5,10,78,84,85,158) -- 费用，其他收入
        INSERT INTO moneybill(BillNumberId,AtypeId,total,Comment,STypeID,NTotal,DTypeId,ETypeId,ShowOrder,DraftFlag,IsIniFlag,BrandarTypeId)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,AtypeId,total,Comment,STypeID,NTotal,DTypeId,ETypeId,ShowOrder,DraftFlag,IsIniFlag,BrandarTypeId
		FROM moneybill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType IN(77) -- 转款单
        INSERT INTO movemoneybill(BillNumberId,AtypeId,total,Comment,STypeID,ntotal,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,AtypeId,total,Comment,STypeID,ntotal,ShowOrder,DraftFlag,IsIniFlag
		FROM movemoneybill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType IN(115,116,128,129) -- 调帐单
        INSERT INTO addebtbill(BillNumberId,Comment,BtypeId,total,TeamNo,TeamNO1,STypeID,NTotal,CompleteTotal,nCompleteTotal,ShowOrder,AlertDay,DraftFlag,IsIniFlag,BrandarTypeId,jsstyle,jsState)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,Comment,BtypeId,total,TeamNo,TeamNO1,STypeID,NTotal,CompleteTotal,nCompleteTotal,ShowOrder,AlertDay,DraftFlag,IsIniFlag,BrandarTypeId,jsstyle,jsState
		FROM addebtbill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 16 --拆装单
        INSERT INTO DisassembleBill(BillNumberId,PtypeId,Qty,costprice,jobnumber,total,inorout,outfactorydate,comment,goodsno,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,KTypeID,STypeID,IsUnit2,NQty,UnitRate,CargoID,ItemID,IsCombined,MUnitId,MUnitRate,MQty,CurMSalePrice,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PtypeId,Qty,costprice,jobnumber,total,inorout,outfactorydate,comment,goodsno,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,KTypeID,STypeID,IsUnit2,NQty,UnitRate,CargoID,ItemID,IsCombined,MUnitId,MUnitRate,MQty,CurMSalePrice,ShowOrder,DraftFlag,IsIniFlag
		FROM DisassembleBill WHERE BillNumberID=@nBillID
      ELSE IF @nBillType = 305 --零售单
    BEGIN
     
		INSERT INTO RetailCombinationBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,
		OutFactoryDate,TaxPrice,TaxTotal,IsUnit2,BackQTY,SaleTotal,Tax,Stypeid,TaxMoney,NSalePrice,
		NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,
		CurMDiscountPrice,CurMTaxPrice,CargoID,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,PosId,
		BeforePromoID,PriceDetailId,PriceRuleId,PriceSource,PriceStyle,PromoType,pindexid,comment,ETypeID,itemid,iscombined,PromonIds,couponcode,IsPromotion,IsVipPoint)
	
		SELECT 
			@nNewBillID,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,
		OutFactoryDate,TaxPrice,TaxTotal,IsUnit2,BackQTY,SaleTotal,Tax,Stypeid,TaxMoney,NSalePrice,
		NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,
		CurMDiscountPrice,CurMTaxPrice,CargoID,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,PosId,
		BeforePromoID,PriceDetailId,PriceRuleId,PriceSource,PriceStyle,PromoType,pindexid,comment,ETypeID,itemid,iscombined,PromonIds,couponcode,IsPromotion,IsVipPoint
		FROM RetailCombinationBill WHERE BillNumberId=@nBillID
	

        INSERT INTO retailbill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,PosId,PriceDetailId,PriceRuleId,PriceSource,promoType,ETypeID,ShowOrder,DraftFlag,IsIniFlag,PromonIds,couponcode,IsPromotion,IsVipPoint,ktypeid)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,PosId,PriceDetailId,PriceRuleId,PriceSource,promoType,ETypeID,ShowOrder,DraftFlag,IsIniFlag,PromonIds,couponcode,IsPromotion,IsVipPoint,ktypeid
		FROM retailbill WHERE BillNumberID=@nBillID
		
		 
	END	
	ELSE IF @nBillType = 215 --零售退货单
        INSERT INTO RetailBackBill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,PosId,promoType,ETypeID,ShowOrder,DraftFlag,IsIniFlag,couponcode,KTypeID)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,STypeID,
								TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,PosId,promoType,ETypeID,ShowOrder,DraftFlag,IsIniFlag,couponcode,KTypeID
		FROM retailBackbill WHERE BillNumberID=@nBillID
     ELSE IF (@nBillType = 148 OR @nBillType = 150)--返利执行单、获利执行单
        INSERT INTO Advantage(BillNumberId,Ptypeid,StartDate,EndDate,StandardCode,Type,Qty,Total,comment,Serial,BillType,STypeID,IsCombined,ItemID,GoodsNumber,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,Ptypeid,StartDate,EndDate,StandardCode,Type,Qty,Total,comment,Serial,BillType,STypeID,IsCombined,ItemID,GoodsNumber,DraftFlag,IsIniFlag
		FROM Advantage WHERE BillNumberID=@nBillID
     ELSE IF @nBillType IN (149,151) --价保执行单
		BEGIN
	        INSERT INTO PriceProtectBill(BillNumberid,Ptypeid,OldPrice,Qty,NewPrice,Total,Comment,Serial,STypeID,IsCombined,ItemID,GoodsNumber,DraftFlag,IsIniFlag)
			OUTPUT INSERTED.ID INTO #temptable	
			SELECT @nNewBillID,Ptypeid,OldPrice,Qty,NewPrice,Total,Comment,Serial,STypeID,IsCombined,ItemID,GoodsNumber,DraftFlag,IsIniFlag
			FROM PriceProtectBill WHERE BillNumberID=@nBillID	
		END
     ELSE IF @nBillType IN(140,141,142,143,144,145,146,147) --  委托代销发货单;  委托代销结算单; 委托代销退货单; 委托代销调价单; 受托代销收货单; 受托代销结算单;  受托代销退货单;受托代销调价单;
        INSERT INTO Commissionbill(BillNumberId,type,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
									TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,type,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,IsUnit2,SaleTotal,Tax,KTypeID,STypeID,
									TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag
		FROM Commissionbill WHERE BillNumberID=@nBillID
     ELSE IF @nBillType = 155 --商品换货单
        INSERT INTO GoodsExchangeBill(BillNumberId,InOrOut,PTypeID,Qty,SalePrice,Discount,DiscountPrice,CostPrice,JobNumber,GoodsNo,Total,OutFactoryDate,TaxPrice,TaxTotal,Comment,OrderID,TeamNo,TeamNO1,IsUnit2,Serial)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,InOrOut,PTypeID,Qty,SalePrice,Discount,DiscountPrice,CostPrice,JobNumber,GoodsNo,Total,OutFactoryDate,TaxPrice,TaxTotal,Comment,OrderID,TeamNo,TeamNO1,IsUnit2,Serial
		FROM GoodsExchangeBill WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 157	-- 商品维修受理单
	BEGIN
			INSERT INTO RepairDealDetail(BillNumberId,InOrOut,PTypeID,Qty,SalePrice,Discount,DiscountPrice,CostPrice,JobNumber,GoodsNo,Total,OutFactoryDate,TaxPrice,TaxTotal,Comment,OrderID,TeamNo,TeamNO1,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost)
			SELECT @nNewBillID,InOrOut,PTypeID,Qty,SalePrice,Discount,DiscountPrice,CostPrice,JobNumber,GoodsNo,Total,OutFactoryDate,TaxPrice,TaxTotal,Comment,OrderID,TeamNo,TeamNO1,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost
			FROM RepairDealDetail WHERE BillNumberID=@nBillID
		INSERT INTO RepairDeal(BillNumberId,EngageBillID,BillDate,BillCode,BillType,PTypeID,ETypeID,IfCheck,Checke,RedWord,Draft,Stat,Fault,Comment,Method,KTypeID1,KTypeID2,MoneyChange,MoneyRepair,TotalMoney,TotalInMoney,BTypeID,ATypeID,Brief,NotFree,FreeMemo,ETypeID1,ETypeID2,PayDate,IfPay,IDCard)
		SELECT	@nNewBillId,EngageBillID,BillDate,BillCode,BillType,PTypeID,ETypeID,IfCheck,Checke,RedWord,Draft,Stat,Fault,Comment,Method,KTypeID1,KTypeID2,MoneyChange,MoneyRepair,TotalMoney,TotalInMoney,BTypeID,ATypeID,Brief,NotFree,FreeMemo,ETypeID1,ETypeID2,PayDate,IfPay,IDCard
		FROM	RepairDeal
		WHERE	BillNumberID = @nBillID
		
	END
	ELSE IF @nBillType = 159	-- 会计凭证
	BEGIN
        INSERT INTO AccountCredence(BillNumberID,TypeATypeID,ATypeID,J_Total,D_Total,Comment,STypeID,NJ_Total,ND_Total,CID,Rate,DraftFlag,IsIniFlag,BrandarTypeId,ETypeID,DTypeID)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,TypeATypeID,ATypeID,dbo.F_RoundTotal(J_Total),dbo.F_RoundTotal(D_Total),Comment,STypeID,dbo.F_RoundTotal(NJ_Total),dbo.F_RoundTotal(ND_Total),CID,dbo.F_RoundExchangeRate(Rate),DraftFlag,IsIniFlag,BrandarTypeId,ETypeID,DTypeID
		FROM AccountCredence WHERE BillNumberID=@nBillID
	END
	ELSE IF @nBillType = 160	-- 销售换货单
        INSERT INTO SaleGoodsExchangeBill(BillNumberId,InOrOut,PTypeID,Qty,SalePrice,Discount,DiscountPrice,CostPrice,JobNumber,GoodsNo,Total,OutFactoryDate,TaxPrice,TaxTotal,Comment,OrderID,TeamNo,TeamNO1,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,SaleTotal,Tax,KTypeID,STypeID,
										TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,ShowOrder,OldBillNumberID,OldID,etypeid,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,InOrOut,PTypeID,Qty,SalePrice,Discount,DiscountPrice,CostPrice,JobNumber,GoodsNo,Total,OutFactoryDate,TaxPrice,TaxTotal,Comment,OrderID,TeamNo,TeamNO1,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,SaleTotal,Tax,KTypeID,STypeID,
										TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,ShowOrder,OldBillNumberID,OldID,etypeid,DraftFlag,IsIniFlag
		FROM SaleGoodsExchangeBill WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 161	-- 采购换货单
        INSERT INTO BuyGoodsExchangeBill(BillNumberId,InOrOut,PTypeID,Qty,SalePrice,Discount,DiscountPrice,CostPrice,JobNumber,GoodsNo,Total,OutFactoryDate,TaxPrice,TaxTotal,Comment,OrderID,TeamNo,TeamNO1,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,SaleTotal,Tax,KTypeID,STypeID,
										TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,ShowOrder,OldBillNumberID,OldID,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,InOrOut,PTypeID,Qty,SalePrice,Discount,DiscountPrice,CostPrice,JobNumber,GoodsNo,Total,OutFactoryDate,TaxPrice,TaxTotal,Comment,OrderID,TeamNo,TeamNO1,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,SaleTotal,Tax,KTypeID,STypeID,
										TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,IsGift,ShowOrder,OldBillNumberID,OldID,DraftFlag,IsIniFlag
		FROM BuyGoodsExchangeBill WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 165	-- 新维修 - 接件单
        INSERT INTO wx_Bill_JieJian(BillNumberID,PTypeID,Qty,IsUnit2,Serial,BuyDate,ErrDes,Total,AddTotal,ErrDeal,RepairMode,ETypeID,BaoXiu,Comment,State,SendBackPTypeID,SendBackSerial,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,Serial,BuyDate,ErrDes,Total,AddTotal,ErrDeal,RepairMode,ETypeID,BaoXiu,Comment,State,SendBackPTypeID,SendBackSerial,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_JieJian WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 166	-- 新维修 - 维修单
        INSERT INTO wx_Bill_Self(BillNumberID,InOrOut,PTypeID,Qty,IsUnit2,Price,Total,Comment,Serial,wxProperty,OutFactoryDate,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,STypeID,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,InOrOut,PTypeID,Qty,IsUnit2,Price,Total,Comment,Serial,wxProperty,OutFactoryDate,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,STypeID,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_Self WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 167	-- 新维修 - 取件单
        INSERT INTO wx_Bill_GetBack(BillNumberID,PTypeID,Qty,IsUnit2,Comment,Serial,JieJianBillNumberID,JieJianID,JieJianPTypeID,JieJianState,Total,CompleteQty,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,Comment,Serial,JieJianBillNumberID,JieJianID,JieJianPTypeID,JieJianState,Total,CompleteQty,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_GetBack WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 168	-- 新维修 - 整机更换单
        INSERT INTO wx_Bill_Replace(BillNumberID,PTypeID,Qty,IsUnit2,Total,Comment,Serial,JieJianBillNumberID,JieJianID,JieJianPTypeID,JieJianState,OutFactoryDate,wxProperty,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQty,Stypeid,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,Total,Comment,Serial,JieJianBillNumberID,JieJianID,JieJianPTypeID,JieJianState,OutFactoryDate,wxProperty,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,CompleteQty,Stypeid,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_Replace WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 169	-- 新维修 - 送修单
        INSERT INTO wx_Bill_Send(BillNumberID,PTypeID,Qty,IsUnit2,SendBackQty,Total,Comment,Serial,JieJianBillNumberID,JieJianID,JieJianPTypeID,JieJianState,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,SendBackQty,Total,Comment,Serial,JieJianBillNumberID,JieJianID,JieJianPTypeID,JieJianState,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_Send WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 170	-- 新维修 - 送修返回单
        INSERT INTO wx_Bill_SendBack(BillNumberID,PTypeID,Qty,IsUnit2,Total,Comment,Serial,SendBillNumberID,SendID,SendPTypeID,CompleteQty,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,Total,Comment,Serial,SendBillNumberID,SendID,SendPTypeID,CompleteQty,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_SendBack WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 171	-- 新维修 - 报修单
        INSERT INTO wx_Bill_Call(BillNumberID,PTypeID,Qty,IsUnit2,Serial,BuyDate,ErrDes,Total,ErrDeal,ETypeID,BaoXiu,Comment,State,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,Serial,BuyDate,ErrDes,Total,ErrDeal,ETypeID,BaoXiu,Comment,State,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_Call WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 172	-- 新维修 - 上门维修单
        INSERT INTO wx_Bill_Goto(BillNumberID,InOrOut,PTypeID,Qty,IsUnit2,Price,Total,Comment,Serial,wxProperty,OutFactoryDate,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,STypeID,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,InOrOut,PTypeID,Qty,IsUnit2,Price,Total,Comment,Serial,wxProperty,OutFactoryDate,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,STypeID,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_Goto WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 173	-- 新维修 - 维修品调入单
        INSERT INTO wx_Bill_In(BillNumberID,PTypeID,Qty,IsUnit2,Price,Total,Comment,Serial,OutFactoryDate,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,STypeID,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,Price,Total,Comment,Serial,OutFactoryDate,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,STypeID,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_In WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 174	-- 新维修 - 维修品调出单
        INSERT INTO wx_Bill_Out(BillNumberID,PTypeID,Qty,IsUnit2,Price,Total,Comment,Serial,OutFactoryDate,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,STypeID,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,Price,Total,Comment,Serial,OutFactoryDate,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,STypeID,ItemID,IsCombined,NQty,UnitRate,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_Out WHERE BillNumberID=@nBillID
	ELSE IF @nBillType = 175	-- 新维修 - 维修品调拨单
        INSERT INTO wx_Bill_Move(BillNumberID,PTypeID,Qty,IsUnit2,Comment,Serial,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,PTypeID,Qty,IsUnit2,Comment,Serial,OutFactoryDate,STypeID,ItemID,IsCombined,NQty,UnitRate,GoodsNumber,CargoID,ShowOrder,DraftFlag,IsIniFlag
		FROM wx_Bill_Move WHERE BillNumberID=@nBillID
	ELSE IF @nBillType =183    --积分兑换单
		INSERT INTO IntegralExchangeBill(BillNumberID,KTypeID,PTypeID,Qty,Price,Total,Comment,IsUnit2,Serial,STypeID,NQty,UnitRate,CargoID,ItemID,IsCombined,GoodsCostPrice,GoodsCostTotal,HandZeroCost,GoodsNumber,ProduceDate,ValidDate,ShowOrder,SendedQty,PickedQty,OutFactQty,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,KTypeID,PTypeID,Qty,Price,Total,Comment,IsUnit2,Serial,STypeID,NQty,UnitRate,CargoID,ItemID,IsCombined,GoodsCostPrice,GoodsCostTotal,HandZeroCost,GoodsNumber,ProduceDate,ValidDate,ShowOrder,SendedQty,PickedQty,OutFactQty,DraftFlag,IsIniFlag
		FROM IntegralExchangeBill WHERE BillNumberID=@nBillID
	ELSE IF @nBillType IN (187,188)
	BEGIN
		INSERT INTO STypeMoveBill(BillNumberId,BillType,Comment,PtypeId,Qty,Price,Total,Jobnumber,GoodsNo,OutFactoryDate,IsUnit2,Serial,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,
								Stypeid,Ktypeid,Ktypeid2,FromBillNumberID,FromBillID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,InCargoID,OutCargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT  @nNewBillID,BillType,Comment,PtypeId,Qty,Price,Total,Jobnumber,GoodsNo,OutFactoryDate,IsUnit2,Serial,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,HandZeroCost,
				Stypeid,Ktypeid,Ktypeid2,FromBillNumberID,FromBillID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,InCargoID,OutCargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag
		FROM STypeMoveBill 
		WHERE BillNumberID=@nBillID
	END
	ELSE IF @nBillType IN (189,190)
	BEGIN
		INSERT INTO PreBill(BillNumberId,BillType,Comment,AtypeId,total,TeamNo,TeamNO1,Stypeid,vipcardid,ntotal,ShowOrder,DraftFlag,IsIniFlag,BrandarTypeId)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,BillType,Comment,AtypeId,total,TeamNo,TeamNO1,Stypeid ,vipcardid,ntotal,ShowOrder,DraftFlag,IsIniFlag,BrandarTypeId
		FROM PreBill WHERE BillNumberID=@nBillID
	END
	ELSE IF @nBillType IN (201,202)
	BEGIN	
		INSERT OtherInOutBill(BillNumberId,BillType,PtypeId,KtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,comment,IsUnit2,Serial,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,
							HandZeroCost,Price,Total,Stypeid,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,CargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,BillType,PtypeId,KtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,comment,IsUnit2,Serial,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,
							HandZeroCost,Price,Total,Stypeid,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,CargoID,ItemID,IsCombined,ShowOrder,DraftFlag,IsIniFlag
		FROM OtherInOutBill WHERE BillNumberID=@nBillID
	END
	ELSE IF @nBillType IN (212,213)
	BEGIN
		INSERT AssetIncDecBill( BillNumberId,AssetCardId,BillType,NTotal,Total,Tax,NTaxMoney,TaxMoney,NTaxTotal,TaxTotal,NDepTotal,DepTotal,
		          NNetValue,NetValue,Comment,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,AssetCardId,BillType,NTotal,Total,Tax,NTaxMoney,TaxMoney,NTaxTotal,TaxTotal,NDepTotal,DepTotal,NNetValue,NetValue,Comment,DraftFlag,IsIniFlag
		FROM AssetIncDecBill WHERE BillNumberID=@nBillID
	END
	ELSE IF @nBillType IN (214)
	BEGIN
		INSERT dbo.DepBill
		        ( BillNumberId ,AssetCardId ,Depreciation ,Comment,WorkTime,WorkUnit,DTypeId,DraftFlag,IsIniFlag)
		 OUTPUT INSERTED.ID INTO #temptable	  
		 SELECT @nNewBillID,AssetCardId,Depreciation,Comment,WorkTime,WorkUnit,DTypeID,DraftFlag,IsIniFlag
		 FROM dbo.DepBill   WHERE BillNumberID=@nBillID  
	END
	ELSE IF @nBillType IN (205,206)
	BEGIN
		INSERT ShareSourceBill(BillNumberID,BillType,FromBillNumberID,FromBillID,FromBillType,ShareFee,Comment,ShowOrder,DraftFlag,IsIniFlag)
		SELECT @nNewBillID,BillType,FromBillNumberID,FromBillID,FromBillType,ShareFee,Comment,ShowOrder,DraftFlag,IsIniFlag
		FROM ShareSourceBill WHERE BillNumberID=@nBillID
		
		INSERT ShareFeeBill(BillNumberID,BillType,FromBillNumberID,FromBillID,Comment,ShowOrder)
		SELECT @nNewBillId,BillType,FromBillNumberID,FromBillID,Comment,ShowOrder
		FROM ShareFeeBill
		WHERE BillNumberID=@nBillID
		
		IF @nBillType=206
		BEGIN
			--销售出库单费用分摊
			UPDATE SaleBill
			SET ShareFee=ISNULL(SaleBill.ShareFee,0)-b.ShareFee
			From ShareSourceBill b
			WHERE b.BillNumberId=@nBillID
			AND SaleBill.ID=b.FromBillID
			AND FromBillType=11
			
			
			UPDATE PT_Combin_SaleBillDetail
			SET ShareFee=ISNULL(PT_Combin_SaleBillDetail.ShareFee,0)-b.ShareFee
			From ShareSourceBill b
			WHERE b.BillNumberId=@nBillID
			AND PT_Combin_SaleBillDetail.ID=b.FromBillID
			AND FromBillType=12
			
			--零售单费用分摊
			UPDATE dbo.retailBill
			SET ShareFee=ISNULL(retailBill.ShareFee,0)-b.ShareFee
			From ShareSourceBill b
			WHERE b.BillNumberId=@nBillID
			AND retailBill.ID=b.FromBillID
			AND FromBillType=305
			
			UPDATE InOutstocktable
			SET ShareFee=ISNULL(InOutStockTable.ShareFee,0)+b.ShareFee
			From ShareSourceBill b
			WHERE b.BillNumberId=@nBillID
			AND InOutstocktable.BillNumberId=b.FromBillNumberID
			AND InOutstocktable.ID=b.FromBillID
		END
		ELSE
		BEGIN
			--采购费用分摊单(要注意回滚的情形)
			--InOutStockTable应该先插入（在后面处理InOutStockTable的地方先排除此类单据）
			INSERT INTO InOutStockTable(BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,
			Qty,Price,Total,CostPrice,CostTotal,JobNumber,GoodsNo,OutFactoryDate,Audited,GoodsNumber,ProduceDate,ValidDate,
			GoodsBTypeID,GoodsCostPrice,HandZeroCost,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,
			DTypeID,STypeID,PostTime,ShareFee,CargoID)
			SELECT	@nNewBillID,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,
			Qty,Price,Total,CostPrice,-CostTotal,JobNumber,GoodsNo,OutFactoryDate,0,GoodsNumber,ProduceDate,ValidDate,
			GoodsBTypeID,GoodsCostPrice,HandZeroCost,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,
			DTypeID,STypeID,PostTime,ShareFee,CargoID
			FROM InOutStockTable
			WHERE BillNumberID=@nBillID
			
			EXEC Gp_BuyShareFee_RedWord @nBillID,@nNewBillID,@nBillType,@nRet OUT,@strPTypeIDOutPut OUT
			
			-----自定义-----
			INSERT INTO CustomBillColumns 
             (
				billnumberid,billtype,Costom1,Costom2,Costom3,Costom4,
				Costom5,Costom6,Costom7,Costom8,Costom9,Costom10,Costom11,
				Costom12,Costom13,Costom14,Costom15,Costom16,Costom17,Costom18,Costom19,Costom20
			 ) 
			SELECT 
				@nNewBillID,billtype,Costom1,Costom2,Costom3,Costom4,
				Costom5,Costom6,Costom7,Costom8,Costom9,Costom10,Costom11,
				Costom12,Costom13,Costom14,Costom15,Costom16,Costom17,Costom18,Costom19,Costom20
			FROM CustomBillColumns WHERE billnumberid=@nBillID AND billtype=@nBillType	
			--表体处理
			INSERT INTO dbo.CustomBillDetailColumns
			( 
				billnumberid ,billtype ,detailId ,InOrOut ,Costom1 ,Costom2 ,Costom3 ,Costom4 ,Costom5 ,Costom6 ,Costom7 ,Costom8 ,
				Costom9 ,Costom10 ,Costom11 ,Costom12 ,Costom13 ,Costom14 ,Costom15 ,Costom16 ,Costom17 ,Costom18 ,Costom19 ,Costom20
			)
			SELECT @nNewBillID ,billtype ,detailid ,InOrOut ,Costom1 ,Costom2 ,Costom3 ,Costom4 ,Costom5 ,Costom6 ,Costom7 ,Costom8 ,
				Costom9 ,Costom10 ,Costom11 ,Costom12 ,Costom13 ,Costom14 ,Costom15 ,Costom16 ,Costom17 ,Costom18 ,Costom19 ,Costom20
			FROM 
			(
				SELECT c.*,t.detailid FROM
				(
				SELECT RANK() OVER
					(PARTITION BY billnumberid ORDER BY ID)id,
					billnumberid ,billtype,InOrOut ,Costom1 ,Costom2 ,Costom3 ,Costom4 ,Costom5 ,Costom6 ,Costom7 ,Costom8 ,
					Costom9 ,Costom10 ,Costom11 ,Costom12 ,Costom13 ,Costom14 ,Costom15 ,Costom16 ,Costom17 ,Costom18 ,Costom19 ,Costom20
					FROM CustomBillDetailColumns 
					WHERE billnumberid=@nBillID AND billtype=@nBillType
				)c
				INNER JOIN #temptable t ON t.id=c.id
			)a	
			------自定义END---------
			RETURN @nRet
		END
	END
	ELSE IF @nBillType=310
	BEGIN
		--资金调拨单
		INSERT CapitalTransfer_Bill(BillNumberId,BankAccountOut,BankAccountIn,TransferPrice,DeductPrice,NTransferPrice,NDeductPrice,Comment,DraftFlag,IsIniFlag)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT @nNewBillID,BankAccountOut,BankAccountIn,TransferPrice,DeductPrice,NTransferPrice,NDeductPrice,Comment,DraftFlag,IsIniFlag
		FROM CapitalTransfer_Bill WHERE BillNumberID=@nBillID
	END
	ELSE IF @nBillType IN (71,72,87,88)
	BEGIN
		--借欠单据
		--UPDATE LendCheck  SET Qty +=  -Qty  , NQty+= -NQty WHERE BillNumberID = @nBillID 
		INSERT dbo.LendBill (BillNumberId , PtypeId , Qty , JobNumber , GoodsNo , OutFactoryDate , COMMENT , Serial , BackQty , Stypeid , CargoID , BackItemId , ItemID , IsCombined , NQty , GoodsNumber , ProduceDate , ValidDate , UnitRate ,BuyQty,SaleQty,ShowOrder)
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT				  @nNewBillID , PtypeId , -Qty , JobNumber , GoodsNo , OutFactoryDate , COMMENT , Serial , BackQty , Stypeid , CargoID , BackItemId , ItemID , IsCombined , -NQty , GoodsNumber , ProduceDate , ValidDate , UnitRate ,BuyQty,SaleQty,ShowOrder
		FROM dbo.LendBill WHERE BillNumberID=@nBillID
	END
	ELSE IF @nBillType=400
	BEGIN
		--暂估入库单
		INSERT AppraisalBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,TaxPrice,TaxTotal,comment,
		TeamNo1,TeamNo,orderid,Serial,InputCostPrice,GoodsOrder,BackQty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,HandZeroCost,
		SaleTotal,Tax,KTypeID,Stypeid,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,UnitID,NUnitID,NQty,
		UnitRate,MUnitID,MUnitRate,MUnitMsg,MSalePrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,InvoiceQty,
		InvoiceMoney,NInvoiceMoney,IsGift,InvoiceMoneyEX,NInvoiceMoneyEX,InvoiceCostTotal,OldID,OldBillNumberID,InvoiceNQty,NTaxMoney,MQty,MDiscountPrice,ShowOrder,DraftFlag,IsIniFlag)
		SELECT @nNewBillID,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,TaxPrice,TaxTotal,comment,
		TeamNo1,TeamNo,orderid,Serial,InputCostPrice,GoodsOrder,BackQty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,HandZeroCost,
		SaleTotal,Tax,KTypeID,Stypeid,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,UnitID,NUnitID,NQty,
		UnitRate,MUnitID,MUnitRate,MUnitMsg,MSalePrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,InvoiceQty,
		InvoiceMoney,NInvoiceMoney,IsGift,InvoiceMoneyEX,NInvoiceMoneyEX,InvoiceCostTotal,OldID,OldBillNumberID,InvoiceNQty,NTaxMoney,MQty,MDiscountPrice,ShowOrder,DraftFlag,IsIniFlag
		FROM AppraisalBill
		WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=401
	BEGIN
		--暂估退货单
		INSERT AppraisalBackBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,TaxPrice,TaxTotal,comment,
		TeamNo1,TeamNo,Serial,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,HandZeroCost,
		SaleTotal,Tax,KTypeID,Stypeid,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,UnitID,NUnitID,NQty,
		UnitRate,MUnitID,MUnitRate,MUnitMsg,MSalePrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,InvoiceQty,
		InvoiceMoney,NInvoiceMoney,IsGift,InvoiceMoneyEX,NInvoiceMoneyEX,InvoiceCostTotal,OldID,OldBillNumberID,InvoiceNQty,costprice,CostTotal,NTaxMoney,MQty,MDiscountPrice,ShowOrder,DraftFlag,IsIniFlag)
		SELECT @nNewBillID,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,TaxPrice,TaxTotal,comment,
		TeamNo1,TeamNo,Serial,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,HandZeroCost,
		SaleTotal,Tax,KTypeID,Stypeid,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,UnitID,NUnitID,NQty,
		UnitRate,MUnitID,MUnitRate,MUnitMsg,MSalePrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,InvoiceQty,
		InvoiceMoney,NInvoiceMoney,IsGift,InvoiceMoneyEX,NInvoiceMoneyEX,InvoiceCostTotal,OldID,OldBillNumberID,InvoiceNQty,costprice,CostTotal,NTaxMoney,MQty,MDiscountPrice,ShowOrder,DraftFlag,IsIniFlag
		FROM AppraisalBackBill
		WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=404
	BEGIN
		--采购暂估开票
		INSERT ReceiptBill(BillNumberID,BillType,MainBillNumberID,KTypeID,PTypeID,Qty,Price,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,
		discount,BeforePrice,BeforeTotal,RecordedItemId,Nprice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,CargoID,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,MTaxPrice,CurMPrice,CurMTaxPrice,ItemID,IsCombined,Nbeforeprice,Nbeforetotal,
		goodsnumber,saleprice,saletotal,nsaleprice,nsaletotal,curmsaleprice,curmsaletotal,taxmoney,CompleteQty,CompleteTotal,
		NCompleteTotal,IsGift,TeamNO,TeamNO1,InvoiceCostTotal,MainBillType,InvoiceCostPrice,ShowOrder)
		SELECT @nNewBillID,BillType,MainBillNumberID,KTypeID,PTypeID,Qty,Price,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,
		discount,BeforePrice,BeforeTotal,RecordedItemId,Nprice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,CargoID,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,MTaxPrice,CurMPrice,CurMTaxPrice,ItemID,IsCombined,Nbeforeprice,Nbeforetotal,
		goodsnumber,saleprice,saletotal,nsaleprice,nsaletotal,curmsaleprice,curmsaletotal,taxmoney,CompleteQty,CompleteTotal,
		NCompleteTotal,IsGift,TeamNO,TeamNO1,InvoiceCostTotal,MainBillType,InvoiceCostPrice,ShowOrder
		FROM ReceiptBill
		WHERE BillNumberID=@nBillID
	END
	ELSE IF @nBillType=402
	BEGIN
		--发出商品出库单
		INSERT SendBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,total,TaxPrice,TaxTotal,comment,OrderID,
		TeamNo,TeamNO1,Serial,InputCostPrice,GoodsOrder,BackQty,GoodsNumber,ProduceDate,ValidDate,HandZeroCost,SaleTotal,Tax,KTypeID,
		Stypeid,ShareFee,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,
		UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
		CargoID,ItemID,IsCombined,entryCode,InvoiceQty,InvoiceMoney,NInvoiceMoney,PriceSource,IsGift,ReferPrice,PriceStyle,
		InvoiceMoneyEX,NInvoiceMoneyEX,InvoiceCostTotal,OldID,OldBillNumberID,InvoiceNQty,CostTotal,ShowOrder,DraftFlag,IsIniFlag)
		SELECT @nNewBillID,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,total,TaxPrice,TaxTotal,comment,OrderID,
		TeamNo,TeamNO1,Serial,InputCostPrice,GoodsOrder,BackQty,GoodsNumber,ProduceDate,ValidDate,HandZeroCost,SaleTotal,Tax,KTypeID,
		Stypeid,ShareFee,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,
		UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
		CargoID,ItemID,IsCombined,entryCode,InvoiceQty,InvoiceMoney,NInvoiceMoney,PriceSource,IsGift,ReferPrice,PriceStyle,
		InvoiceMoneyEX,NInvoiceMoneyEX,InvoiceCostTotal,OldID,OldBillNumberID,InvoiceNQty,CostTotal,ShowOrder,DraftFlag,IsIniFlag
		FROM SendBill
		WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=403
	BEGIN
		--发出商品退货单
		INSERT SendBackBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,total,TaxPrice,TaxTotal,comment,
		TeamNo,TeamNO1,Serial,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,HandZeroCost,SaleTotal,Tax,KTypeID,
		Stypeid,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,
		UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
		CargoID,ItemID,IsCombined,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,ReferPrice,PriceStyle,
		InvoiceMoneyEX,NInvoiceMoneyEX,InvoiceCostTotal,OldID,OldBillNumberID,InvoiceNQty,CostTotal,ShowOrder,DraftFlag,IsIniFlag)
		SELECT @nNewBillID,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,total,TaxPrice,TaxTotal,comment,
		TeamNo,TeamNO1,Serial,InputCostPrice,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,HandZeroCost,SaleTotal,Tax,KTypeID,
		Stypeid,TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,
		UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,
		CargoID,ItemID,IsCombined,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,ReferPrice,PriceStyle,
		InvoiceMoneyEX,NInvoiceMoneyEX,InvoiceCostTotal,OldID,OldBillNumberID,InvoiceNQty,CostTotal,ShowOrder,DraftFlag,IsIniFlag
		FROM SendBackBill
		WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=405
	BEGIN
		--销售发货开票
		INSERT ReceiptBill(BillNumberID,BillType,MainBillNumberID,KTypeID,PTypeID,Qty,Price,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,
		discount,BeforePrice,BeforeTotal,RecordedItemId,Nprice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,CargoID,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,MTaxPrice,CurMPrice,CurMTaxPrice,ItemID,IsCombined,Nbeforeprice,Nbeforetotal,
		goodsnumber,saleprice,saletotal,nsaleprice,nsaletotal,curmsaleprice,curmsaletotal,taxmoney,CompleteQty,CompleteTotal,
		NCompleteTotal,IsGift,TeamNO,TeamNO1,InvoiceCostTotal,MainBillType,InvoiceCostPrice,ShowOrder)
		SELECT @nNewBillID,BillType,MainBillNumberID,KTypeID,PTypeID,Qty,Price,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,
		discount,BeforePrice,BeforeTotal,RecordedItemId,Nprice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,CargoID,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MPrice,MTaxPrice,CurMPrice,CurMTaxPrice,ItemID,IsCombined,Nbeforeprice,Nbeforetotal,
		goodsnumber,saleprice,saletotal,nsaleprice,nsaletotal,curmsaleprice,curmsaletotal,taxmoney,CompleteQty,CompleteTotal,
		NCompleteTotal,IsGift,TeamNO,TeamNO1,InvoiceCostTotal,MainBillType,InvoiceCostPrice,ShowOrder
		FROM ReceiptBill
		WHERE BillNumberID=@nBillID
	END	
	ELSE IF @nBillType=450
	BEGIN
		--往来核销单
		INSERT ChargeOffBill( BillNumberId ,FromBillNumberid ,FromBillType ,FromBillID ,ChargeOffType , IsCharged , BTypeID , ChargeOffValue ,NChargeOffValue ,TeamNo ,Comment,ShowOrder,DraftFlag,IsIniFlag)
		SELECT @nNewBillID,FromBillNumberid ,FromBillType ,FromBillID  ,ChargeOffType , IsCharged , BTypeID , ChargeOffValue ,NChargeOffValue ,TeamNo ,Comment,ShowOrder,DraftFlag,IsIniFlag
		FROM ChargeOffBill
		WHERE BillNumberID=@nBillID
	END 
	ELSE IF @nBillType=412
	BEGIN
		--上架单
		INSERT dbo.onShelvesbill
				(  
				   billNumberID ,  ptypeid , qty ,comment ,GoodsBillNumberID ,GoodsBillID ,
		           GoodsBillType ,ItemID ,IsCombined ,  GoodsNumber , GoodsOrder ,
		           Serial , ProduceDate ,ValidDate ,CargoID ,ShowOrder
		        )
		OUTPUT INSERTED.ID INTO #temptable	
		SELECT    @nNewBillID ,  ptypeid , qty ,comment ,GoodsBillNumberID ,GoodsBillID ,
		          GoodsBillType ,ItemID ,IsCombined ,  GoodsNumber , GoodsOrder ,
		          Serial , ProduceDate ,ValidDate ,CargoID ,ShowOrder
		FROM onShelvesbill WHERE billNumberID=@nBillID
	END	
	ELSE IF @nBillType=413
	BEGIN
		--拣货单
		INSERT dbo.pickbill
		        ( 
		          billNumberID , ptypeid ,behooveQty , qty ,comment ,GoodsBillNumberID , GoodsBillCode ,
		          GoodsBillID ,GoodsBillType ,ItemID ,IsCombined ,GoodsNumber ,GoodsOrder ,Serial ,
		          ProduceDate ,ValidDate ,CargoID ,ShowOrder
		        )
		OUTPUT INSERTED.ID INTO #temptable	        
		SELECT    @nNewBillID , ptypeid ,behooveQty , qty ,comment ,GoodsBillNumberID , GoodsBillCode ,
		          GoodsBillID ,GoodsBillType ,ItemID ,IsCombined ,GoodsNumber ,GoodsOrder ,Serial ,
		          ProduceDate ,ValidDate ,CargoID ,ShowOrder
		FROM dbo.pickbill WHERE billNumberID=@nBillID
	END
	ELSE IF @nBillType=414
	BEGIN
		--运输配送单
		
		INSERT dbo.Transportcontrastbill
		        ( billNumberID ,
		          saleBillNumberID ,
		          saleBillType ,
		          ShowOrder
		        )
		SELECT	@nNewBillID ,
		        saleBillNumberID ,
		        saleBillType ,
		        ShowOrder
		FROM Transportcontrastbill WHERE billNumberID=@nBillID
		
		INSERT dbo.Transportbill
		        ( 
		          billNumberID , ptypeid ,qty ,behooveQty , comment ,GoodsBillNumberID , GoodsBillID ,GoodsBillType ,ItemID ,
		          IsCombined ,GoodsNumber ,GoodsOrder ,Serial ,weight ,ShowOrder,Volume
		        )
		OUTPUT INSERTED.ID INTO #temptable	        
		SELECT    @nNewBillID , ptypeid ,qty ,behooveQty , comment ,GoodsBillNumberID , GoodsBillID ,GoodsBillType ,ItemID ,
		          IsCombined ,GoodsNumber ,GoodsOrder ,Serial ,weight ,ShowOrder,Volume
		FROM Transportbill WHERE billNumberID=@nBillID
	END
	ELSE IF @nBillType IN(418,419)  --仓库入库单 仓库出库单
	BEGIN
		INSERT INTO dbo.FactDepotInOut
		        ( BillNumberID ,
		          BillType ,
		          ptypeid ,
		          ktypeid ,
		          qty ,
		          UnitID ,
		          UnitRate ,
		          NQty ,
		          NUnitID ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          ItemID ,
		          IsCombined ,
		          GoodsOrder ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          CargoID ,
		          FromBillID ,
		          FromBillNumberID ,
		          FromBillType ,
		          Serial ,
		          comment ,
		          entryCode,
		          BillDate,
		          Stypeid
		        )
		OUTPUT INSERTED.ID INTO #temptable
		SELECT 	  @nNewBillID ,
		          BillType ,
		          ptypeid ,
		          ktypeid ,
		          qty ,
		          UnitID ,
		          UnitRate ,
		          NQty ,
		          NUnitID ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          ItemID ,
		          IsCombined ,
		          GoodsOrder ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          CargoID ,
		          FromBillID ,
		          FromBillNumberID ,
		          FromBillType ,
		          Serial ,
		          comment ,
		          entryCode,
		          BillDate,
		          STypeId
		FROM dbo.FactDepotInOut WHERE  billNumberID=@nBillID
	END
	ELSE IF @nBillType=420
	BEGIN
		INSERT INTO dbo.FactDepotAllot
		        ( 
		          BillNumberId ,Comment ,PtypeId ,Qty ,Jobnumber ,GoodsNo ,OutFactoryDate ,IsUnit2 ,
		          Serial ,GoodsOrder , GoodsNumber , ProduceDate ,ValidDate , UnitID , NUnitID ,
		          NQty , UnitRate ,NUnitMsg ,MUnitID ,MQty , MUnitRate ,MUnitMsg  ,InCargoID ,
		          OutCargoID ,ItemID ,IsCombined ,KTypeId ,KTypeId2
		        )
		OUTPUT INSERTED.ID INTO #temptable        
		SELECT 	  @nNewBillID ,Comment ,PtypeId ,Qty ,Jobnumber ,GoodsNo ,OutFactoryDate ,IsUnit2 ,
		          Serial ,GoodsOrder , GoodsNumber , ProduceDate ,ValidDate , UnitID , NUnitID ,
		          NQty , UnitRate ,NUnitMsg ,MUnitID ,MQty , MUnitRate ,MUnitMsg  ,InCargoID ,
		          OutCargoID ,ItemID ,IsCombined ,KTypeId ,KTypeId2
		FROM FactDepotAllot WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=327------991新增
	BEGIN
	
     INSERT INTO dbo.DeliveryBill(
      [BillNumberId],[ShowOrder],[Serial],[ktypeidout],[CargoIDout],[ktypeidin],[CargoIDin],[PtypeId],[ItemID],[IsCombined],[GoodsNumber]
      ,[ProduceDate],[ValidDate],[Qty],[Price],[Total],[UnitID],[MUnitID],[MQty],[MUnitRate],[MUnitMsg],[MPrice],[NUnitID],[NUnitRate],[NQty],[NUnitMsg],[Comment],[PickedQty],[CheckQty],[BackQty]
      ,GoodsCostPrice,GoodsCostTotal)
      OUTPUT INSERTED.ID INTO #temptable        
		SELECT 	  @nNewBillID ,[ShowOrder],[Serial],[ktypeidout],[CargoIDout],[ktypeidin],[CargoIDin],[PtypeId],[ItemID],[IsCombined],[GoodsNumber]
      ,[ProduceDate],[ValidDate],[Qty],[Price],[Total],[UnitID],[MUnitID],[MQty],[MUnitRate],[MUnitMsg],[MPrice],[NUnitID],[NUnitRate],[NQty],[NUnitMsg],[Comment],[PickedQty],[CheckQty],[BackQty]
      ,GoodsCostPrice,GoodsCostTotal
		FROM DeliveryBill WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=328 -----------991新增
	BEGIN	
     INSERT INTO dbo.DeliveryBackBill(
      [BillNumberId],[ShowOrder],[Serial],[outktypeid],[outCargoID],[inktypeid],[inCargoID],[PtypeId],[ItemID],[IsCombined],[GoodsNumber],[ProduceDate],[ValidDate]
      ,[Qty],[Price],[Total],[UnitID],[MUnitID],[MQty],[MUnitRate],[MUnitMsg],[MPrice],[NUnitID],[NUnitRate],[NQty],[NUnitMsg],[Comment],[InflowQty] ,[DeliveryID],GoodsCostPrice,GoodsCostTotal
     )

      OUTPUT INSERTED.ID INTO #temptable        
		SELECT 	 @nNewBillID,[ShowOrder],[Serial],[outktypeid],[outCargoID],[inktypeid],[inCargoID],[PtypeId],[ItemID],[IsCombined],[GoodsNumber],[ProduceDate],[ValidDate]
      ,[Qty],[Price],[Total],[UnitID],[MUnitID],[MQty],[MUnitRate],[MUnitMsg],[MPrice],[NUnitID],[NUnitRate],[NQty],[NUnitMsg],[Comment],[InflowQty] ,[DeliveryID],GoodsCostPrice,GoodsCostTotal
		FROM DeliveryBackBill WHERE BillNumberId=@nBillID
	END
	ELSE IF @nBillType=329--------------991新增
	BEGIN	
     INSERT INTO dbo.DeliveryCheckBill(
     [BillNumberId],[ShowOrder],[Serial],[outktypeid],[outCargoID],[inktypeid],[inCargoID],[PtypeId],[ItemID],[IsCombined],[GoodsNumber],[ProduceDate],[ValidDate]
      ,[Qty],[Price],[Total],[UnitID],[MUnitID],[MQty],[MUnitRate],[MUnitMsg],[MPrice],[NUnitID],[NUnitRate],[NQty],[NUnitMsg],[Comment],[InflowQty] ,[DeliveryID],GoodsCostPrice,GoodsCostTotal)
      OUTPUT INSERTED.ID INTO #temptable        
		SELECT 	 @nNewBillID,[ShowOrder],[Serial],[outktypeid],[outCargoID],[inktypeid],[inCargoID],[PtypeId],[ItemID],[IsCombined],[GoodsNumber],[ProduceDate],[ValidDate]
      ,[Qty],[Price],[Total],[UnitID],[MUnitID],[MQty],[MUnitRate],[MUnitMsg],[MPrice],[NUnitID],[NUnitRate],[NQty],[NUnitMsg],[Comment],[InflowQty] ,[DeliveryID],GoodsCostPrice,GoodsCostTotal
		FROM DeliveryCheckBill WHERE BillNumberId=@nBillID
	END
	IF ( (@@ROWCOUNT = 0 AND @nBillType NOT IN (157,166,172,149,151,178,186,205)) OR @@ERROR <> 0 ) 
	BEGIN
		DROP TABLE #TempTable
		RETURN -10
	END
	
	--------------- 插入多账户明细并处理会员余额等-----------------------------------------
	DECLARE
					@chvATypeID			VARCHAR(50),
					@numTotal			 NUMERIC(24, 10) ,		--主要用于会员卡
					@intVipCardID		INT

	--如果是多账户，那么还需要复制账户表
	IF EXISTS(
		SELECT BillNumberId 
		FROM BillMulAccount
		WHERE BillNumberId=@nBillID
	) AND @nBillType NOT IN (71,72,87,88,400,401,402,403,404,405,412,413,327,328,329)--991新增327 328 329 没有多账户收款
	BEGIN
		--INSERT BillMulAccount(BillNumberId,ATypeID,Total,VipCardID,NTotalMoney)
		--SELECT @nNewBillID,ATypeID,Total,VipCardID,NTotalMoney
		--FROM BillMulAccount
		--WHERE BillNumberId=@nBillID
			INSERT BillMulAccount(BillNumberId ,
						  ATypeID ,
						  Total ,
						  Comment ,
						  VipCardID ,
						  NTotalMoney ,
						  paymoney ,
						  TradeNo ,
						  PayType ,
						  BillType ,
						  yhType ,
						  CouponCode,
						  viptotal)
			SELECT @nNewBillID,
				  ATypeID ,
				  Total ,
				  Comment ,
				  VipCardID ,
				  NTotalMoney ,
				  paymoney ,
				  TradeNo ,
				  PayType ,
				  BillType ,
				  yhType ,
				  CouponCode,
				  viptotal
			FROM BillMulAccount
			WHERE BillNumberId=@nBillID AND BillType=@nBillType

		IF EXISTS(
				SELECT BillNumberId 
				FROM BillMulAccount
				WHERE BillNumberId=@nBillID  AND BillType=@nBillType AND ATypeID=(SELECT nid FROM dbo.Ac_Items WHERE UserCode='2181') AND VipCardID>0
		)
		BEGIN
			DECLARE CreateAType_CURSOR CURSOR FOR
			SELECT	ATypeID,Total,VipCardID
			FROM	BillMulAccount
			WHERE	BillNumberId = @nBillID AND BillType=@nBillType AND ATypeID=(SELECT nid FROM dbo.Ac_Items WHERE UserCode='2181')AND VipCardID>0

			OPEN CreateAType_CURSOR
			FETCH NEXT FROM CreateAType_CURSOR INTO	@chvATypeID,
													@numTotal,
													@intVipCardID
			WHILE @@FETCH_STATUS = 0
			BEGIN
				-- 循环写入 ListTable
				IF @nBillType IN (45,46,215)
				BEGIN
					--储值金额是否够支付
					IF EXISTS(SELECT VipCardID FROM nVipCardSign WHERE VipCardID=@intVipCardID  AND cZyeMoney<@numTotal)
					BEGIN
						RETURN 704
					END
					
					IF(@vipBillStoredByStypeId=1 AND EXISTS(SELECT * FROM nVipCardSignStype WHERE VipCardID=@intVipCardID AND StypeId=@STypeID AND cZyeMoney<@numTotal))
					BEGIN				
						RETURN 707
					END
					
					UPDATE	nVipCardSignSType
					SET		
						cZyeMoney = cZyeMoney - @numTotal,
						lJxFczMoney=lJxFczMoney+@numTotal,
						bNxFczMoney=bNxFczMoney+@numTotal
					WHERE	VipCardID = @intVipCardID AND StypeId=@STypeID
					
					UPDATE	nVipCardSign
					SET		
						cZyeMoney = cZyeMoney - @numTotal
					WHERE	VipCardID = @intVipCardID
				END
				ELSE
				BEGIN
					UPDATE	nVipCardSign
					SET		
						cZyeMoney = cZyeMoney + @numTotal
					WHERE	VipCardID = @intVipCardID
					
					UPDATE	nVipCardSignSType
					SET		
						cZyeMoney = cZyeMoney + @numTotal,
						lJxFczMoney=lJxFczMoney-@numTotal,
						bNxFczMoney=bNxFczMoney-@numTotal
					WHERE	VipCardID = @intVipCardID AND StypeId=@STypeID
				END

				FETCH NEXT FROM CreateAType_CURSOR INTO	@chvATypeID,
														@numTotal,
														@intVipCardID
			END
			CLOSE CreateAType_CURSOR
			DEALLOCATE CreateAType_CURSOR
		END
	END
	
	
	--如果是多账户，那么还需要品牌应收
	IF EXISTS(
		SELECT BillNumberId 
		FROM  dbo.BillMulBrand
		WHERE BillNumberId=@nBillID 
	) AND @nBillType NOT IN (71,72,87,88,400,401,402,403,404,405,412,413,327,328,329)
	BEGIN
		INSERT INTO dbo.BillMulBrand
		        ( STypeID ,
		          BTypeID ,
		          BrandarTypeID ,
		          BillNumberId ,
		          BillType ,
		          Cid ,
		          Rate ,
		          TaxTotal ,
		          NTaxTotal ,
		          PreferenceMoney ,
		          NPreferenceMoney ,
		          TotalInMoney ,
		          NTotalInMoney ,
		          TheOrderARTotal ,
		          NTheOrderARTotal ,
		          YSTotalInMoney,
		          NYSTotalInMoney,
		          isIni
		        )		
		SELECT	  STypeID ,
		          BTypeID ,
		          BrandarTypeID ,
		          @nNewBillID ,
		          BillType ,
		          Cid ,
		          Rate ,
		          TaxTotal ,
		          NTaxTotal ,
		          PreferenceMoney ,
		          NPreferenceMoney ,
		          TotalInMoney ,
		          NTotalInMoney ,
		          TheOrderARTotal ,
		          NTheOrderARTotal ,
		          YSTotalInMoney,
		          NYSTotalInMoney,
		          isIni
		FROM BillMulBrand
		WHERE BillNumberId=@nBillID AND BillType=@nBillType
	END 

	/*-------------------------------*/

    /*-------------红冲时复制自定义-  张陈仁 2012-07-13---------------*/
    --表头处理
    INSERT INTO CustomBillColumns 
    (
		billnumberid,billtype,Costom1,Costom2,Costom3,Costom4,
		Costom5,Costom6,Costom7,Costom8,Costom9,Costom10,Costom11,
		Costom12,Costom13,Costom14,Costom15,Costom16,Costom17,Costom18,Costom19,Costom20
	) 
	SELECT 
		@nNewBillID,billtype,Costom1,Costom2,Costom3,Costom4,
		Costom5,Costom6,Costom7,Costom8,Costom9,Costom10,Costom11,
		Costom12,Costom13,Costom14,Costom15,Costom16,Costom17,Costom18,Costom19,Costom20
	FROM CustomBillColumns WHERE billnumberid=@nBillID AND billtype=@nBillType	
	
	INSERT INTO dbo.Custom_BillIndex
	        ( BillId ,
	          BillType ,
	          SysDiy1_head ,
	          SysDiy2_head ,
	          SysDiy3_head ,
	          SysDiy4_head ,
	          SysDiy5_head ,
	          SysDiy6_head ,
	          SysDiy7_head ,
	          SysDiy8_head ,
	          SysDiy9_head ,
	          SysDiy10_head ,
	          SysDiy11_head ,
	          SysDiy12_head ,
	          SysDiy13_head ,
	          SysDiy14_head ,
	          SysDiy15_head ,
	          SysDiy16_head ,
	          SysDiy17_head ,
	          SysDiy18_head ,
	          SysDiy19_head ,
	          SysDiy20_head ,
	          SysDiy21_head ,
	          SysDiy22_head ,
	          SysDiy23_head ,
	          SysDiy24_head ,
	          SysDiy25_head ,
	          SysDiy26_head ,
	          SysDiy27_head ,
	          SysDiy28_head ,
	          SysDiy29_head ,
	          SysDiy30_head ,
	          SysDiy31_head ,
	          SysDiy32_head
	        )
			SELECT 
				  @nNewBillID,
				  BillType ,
				  SysDiy1_head ,
				  SysDiy2_head ,
				  SysDiy3_head ,
				  SysDiy4_head ,
				  SysDiy5_head ,
				  SysDiy6_head ,
				  SysDiy7_head ,
				  SysDiy8_head ,
				  SysDiy9_head ,
				  SysDiy10_head ,
				  SysDiy11_head ,
				  SysDiy12_head ,
				  SysDiy13_head ,
				  SysDiy14_head ,
				  SysDiy15_head ,
				  SysDiy16_head ,
				  SysDiy17_head ,
				  SysDiy18_head ,
				  SysDiy19_head ,
				  SysDiy20_head ,
				  SysDiy21_head ,
				  SysDiy22_head ,
				  SysDiy23_head ,
				  SysDiy24_head ,
				  SysDiy25_head ,
				  SysDiy26_head ,
				  SysDiy27_head ,
				  SysDiy28_head ,
				  SysDiy29_head ,
				  SysDiy30_head ,
				  SysDiy31_head ,
				  SysDiy32_head
		FROM Custom_BillIndex WHERE BillId=@nBillID AND billtype=@nBillType	
	
	
	--表体处理
	INSERT INTO dbo.CustomBillDetailColumns
    ( 
		billnumberid ,billtype ,detailId ,InOrOut ,Costom1 ,Costom2 ,Costom3 ,Costom4 ,Costom5 ,Costom6 ,Costom7 ,Costom8 ,
		Costom9 ,Costom10 ,Costom11 ,Costom12 ,Costom13 ,Costom14 ,Costom15 ,Costom16 ,Costom17 ,Costom18 ,Costom19 ,Costom20
    )
    SELECT @nNewBillID ,billtype ,detailid ,InOrOut ,Costom1 ,Costom2 ,Costom3 ,Costom4 ,Costom5 ,Costom6 ,Costom7 ,Costom8 ,
		Costom9 ,Costom10 ,Costom11 ,Costom12 ,Costom13 ,Costom14 ,Costom15 ,Costom16 ,Costom17 ,Costom18 ,Costom19 ,Costom20
	FROM 
	(
		SELECT c.*,t.detailid FROM
		(
		SELECT RANK() OVER
			(PARTITION BY billnumberid ORDER BY detailid)id,
			billnumberid ,billtype,InOrOut ,Costom1 ,Costom2 ,Costom3 ,Costom4 ,Costom5 ,Costom6 ,Costom7 ,Costom8 ,
			Costom9 ,Costom10 ,Costom11 ,Costom12 ,Costom13 ,Costom14 ,Costom15 ,Costom16 ,Costom17 ,Costom18 ,Costom19 ,Costom20
			FROM CustomBillDetailColumns 
			WHERE billnumberid=@nBillID AND billtype=@nBillType
		)c
		INNER JOIN #temptable t ON t.ID=c.id
	)a		
	
	INSERT INTO dbo.Custom_BillDetails
	        ( BillId ,
	          Detailid ,
	          BillType ,
	          SysDiy1 ,
	          SysDiy2 ,
	          SysDiy3 ,
	          SysDiy4 ,
	          SysDiy5 ,
	          SysDiy6 ,
	          SysDiy7 ,
	          SysDiy8 ,
	          SysDiy9 ,
	          SysDiy10 ,
	          SysDiy11 ,
	          SysDiy12 ,
	          SysDiy13 ,
	          SysDiy14 ,
	          SysDiy15 ,
	          SysDiy16 ,
	          SysDiy17 ,
	          SysDiy18 ,
	          SysDiy19 ,
	          SysDiy20 ,
	          SysDiy21 ,
	          SysDiy22 ,
	          SysDiy23 ,
	          SysDiy24 ,
	          SysDiy25 ,
	          SysDiy26 ,
	          SysDiy27 ,
	          SysDiy28 ,
	          SysDiy29 ,
	          SysDiy30 ,
	          SysDiy31 ,
	          SysDiy32 ,
	          iscombination
	        )
		SELECT @nNewBillID ,
	          Detailid ,
	          BillType ,
	          SysDiy1 ,
	          SysDiy2 ,
	          SysDiy3 ,
	          SysDiy4 ,
	          SysDiy5 ,
	          SysDiy6 ,
	          SysDiy7 ,
	          SysDiy8 ,
	          SysDiy9 ,
	          SysDiy10 ,
	          SysDiy11 ,
	          SysDiy12 ,
	          SysDiy13 ,
	          SysDiy14 ,
	          SysDiy15 ,
	          SysDiy16 ,
	          SysDiy17 ,
	          SysDiy18 ,
	          SysDiy19 ,
	          SysDiy20 ,
	          SysDiy21 ,
	          SysDiy22 ,
	          SysDiy23 ,
	          SysDiy24 ,
	          SysDiy25 ,
	          SysDiy26 ,
	          SysDiy27 ,
	          SysDiy28 ,
	          SysDiy29 ,
	          SysDiy30 ,
	          SysDiy31 ,
	          SysDiy32 ,
	          iscombination
	FROM 
	(
		SELECT c.*,t.detailid FROM
		(
		SELECT RANK() OVER
			(PARTITION BY BillId ORDER BY detailid)id,
			  BillId ,
	          BillType ,
	          SysDiy1 ,
	          SysDiy2 ,
	          SysDiy3 ,
	          SysDiy4 ,
	          SysDiy5 ,
	          SysDiy6 ,
	          SysDiy7 ,
	          SysDiy8 ,
	          SysDiy9 ,
	          SysDiy10 ,
	          SysDiy11 ,
	          SysDiy12 ,
	          SysDiy13 ,
	          SysDiy14 ,
	          SysDiy15 ,
	          SysDiy16 ,
	          SysDiy17 ,
	          SysDiy18 ,
	          SysDiy19 ,
	          SysDiy20 ,
	          SysDiy21 ,
	          SysDiy22 ,
	          SysDiy23 ,
	          SysDiy24 ,
	          SysDiy25 ,
	          SysDiy26 ,
	          SysDiy27 ,
	          SysDiy28 ,
	          SysDiy29 ,
	          SysDiy30 ,
	          SysDiy31 ,
	          SysDiy32 ,
	          iscombination
			FROM Custom_BillDetails 
			WHERE BillId=@nBillID AND billtype=@nBillType
		)c
		INNER JOIN #temptable t ON t.ID=c.id
	)a		
	
	DROP TABLE #temptable		
 /*-------------红冲时复制自定义----------------*/
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID			NUMERIC(10,0),
	@nNewBillID			NUMERIC(10,0),
	@nBillType			INT,
	@strPTypeIDOutPut	varchar(500),
	@tBillDate			DATETIME,
	@etypeid			varchar(50)	


SELECT
	@nBillID=3,
	@nBillType=12,
	@tBillDate=GETDATE(),
	@etypeid='00001'


BEGIN TRAN

EXEC	Gp_RedWordInsertBill
	@nBillID,
	@nNewBillID output,
	@nBillType,
	@strPTypeIDOutPut output,
	@tBillDate,
	@etypeid
	
SELECT @nNewBillID,@strPTypeIDOutPut


SELECT * FROM dbo.PT_Combin_SaleBill WHERE BillNumberId=@nNewBillID

SELECT * FROM dbo.PT_Combin_SaleBillDetail WHERE BillNumberId=@nNewBillID	


ROLLBACK TRAN


*/



SET QUOTED_IDENTIFIER ON  
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RedWordInsertCouponBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_RedWordInsertCouponBill
GO

-- =============================================
-- Author:		shushan
-- Create date:
-- Description: 优惠券单据红冲插入红单主表和明细
-- =============================================

CREATE PROCEDURE Gp_RedWordInsertCouponBill
(
	@nBillID			NUMERIC(10,0),
	@nNewBillID			NUMERIC(10,0) output,
	@nBillType			INT,
	@strPTypeIDOutPut	varchar(500) output,
	@tBillDate			DATETIME,
	@etypeid			varchar(50)	
)
--@encode$--

AS
DECLARE @nRet INT,
		@date DATETIME,
		@STypeID VARCHAR(100),
		@isini INT ,
		@inktypeid VARCHAR(50),
		@outktypeid  VARCHAR(50),
		@incargoid	VARCHAR (50),
		@outcargoid VARCHAR (50)
		
SET @date=GETDATE()
-----------------------------------------插入billindex start-----------------------------------
INSERT INTO Coupon_BillIndex (
		BillDate,
		BillCode,
		BillType,
		FromType,
		STypeID,
		DTypeID,
		ETypeID,
		OutKTypeID,
		InKTypeId,
		CID,
		Rate,
		TotalQty,
		TotalMoney,
		NTotalMoney,
		CompleteTotal,
		NCompleteTotal,
		TotalInMoney,
		NTotalInMoney,
		IfMulAccount,
		ATypeID,
		BTypeID,
		DealBTypeID,
		Comment,
		Poster,
		PostTime,
		MakeTime,
		Maker,
		Checker,
		CheckeTime,
		IfAudit,
		Draft,
		IfCheck,
		RedWord,
		IsIni,
		IfYearBill,
		RedReason,
		ATypeID1,
		ATID,
		TallyId,
		ChargeOffTotal,
		NChargeOffTotal,
		JsState,
		updateE,
		LastUpdateTime,
		PosId,
		Checke,
		PreferenceMoney,
		NPreferenceMoney,
		PosBillCode

	)
SELECT BillDate,
	BillCode,
	BillType,
	FromType,
	STypeID,
	DTypeID,
	ETypeID,
	OutKTypeID,
	InKTypeId,
	CID,
	Rate,
	TotalQty,
	TotalMoney,
	NTotalMoney,
	CompleteTotal,
	NCompleteTotal,
	TotalInMoney,
	NTotalInMoney,
	IfMulAccount,
	ATypeID,
	BTypeID,
	DealBTypeID,
	Comment,
	Poster,
	PostTime,
	MakeTime,
	Maker,
	Checker,
	CheckeTime,
	IfAudit,
	Draft,
	IfCheck,
	2,
	IsIni,
	IfYearBill,
	RedReason,
	ATypeID1,
	ATID,
	TallyId,
	ChargeOffTotal,
	NChargeOffTotal,
	JsState,
	updateE,
	LastUpdateTime,
	PosId,
	Checke,
	PreferenceMoney,
	NPreferenceMoney,
	PosBillCode
FROM Coupon_BillIndex WHERE BillNumberId=@nBillID

SELECT @STypeID=STypeID, @isini=IsIni,@inktypeid=InKTypeId,@outktypeid=outktypeid FROM dbo.Coupon_BillIndex WHERE BillNumberID=@nBillID

IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN -10
ELSE
	SET @nNewBillId = SCOPE_IDENTITY();
declare @szDate varchar(100),@DBName varchar(50)
SET @szDate = CAST(YEAR(@tBillDate) AS varchar) + '-' + CAST(MONTH(@tBillDate) AS varchar) + '-' + CAST(DAY(@tBillDate) AS varchar)

-- 取操作员名称
DECLARE @strEmployeeFullName varchar(500)
SET @strEmployeeFullName = ''

IF @EtypeID = '' OR @EtypeID = '00001'
	SET @strEmployeeFullName = '超级用户'
ELSE
BEGIN
	SELECT	@strEmployeeFullName = ISNULL(FullName,'')
	FROM	Employee
	WHERE	TypeID = @EtypeID
END
IF @strEmployeeFullName <> '' SET @strEmployeeFullName = '【红冲人】' + @strEmployeeFullName + ' '



UPDATE	Coupon_BillIndex
SET	
	Comment = CAST( @strEmployeeFullName + '红字反冲:' + @szDate + Comment AS varchar(256))
WHERE	BillNumberID = @nNewBillID
-----------------------------------------插入billindex end-----------------------------------

 	
CREATE TABLE #curcouponcode
(
	Couponcode varchar(200),
	ID	INT
)
-----------------------------插入明细------------------------------------------
CREATE TABLE #temptable(id INT IDENTITY(1,1),detailid INT)
 IF @nBillType = 423 --优惠券入库单
BEGIN
---敏捷4631 优惠券查询过慢

--优惠券入库单
		  DECLARE @inBillcode VARCHAR(MAX)	
		  INSERT INTO #curcouponcode 
		(	
			CouponCode
				
		)		
          SELECT   CouponCode FROM Coupon_CodeInOut WHERE BillNumberId =@nBillID 

	INSERT INTO dbo.Coupon_InBill
	        ( BillNumberId ,
	          CouponId ,
	          CouponCode ,
	          Comment ,
	          Qty ,
	          InDate ,
	          InvalidDate ,
	          CostPrice ,
	          NCostPrice ,
	          CostTotal ,
	          NCostTotal ,
	          CargoId
	        )

    OUTPUT INSERTED.ID INTO #temptable					
	SELECT	@nNewBillID,
			CouponId ,
			CouponCode ,
			Comment ,
			Qty ,
			InDate ,
			InvalidDate ,
			CostPrice ,
			NCostPrice ,
			CostTotal ,
			NCostTotal ,
            CargoId
	FROM Coupon_InBill WHERE BillNumberID=@nBillID
	
	--处理券状态信息表
	

	
	--期初单据保留	
	UPDATE A 
	SET [State]=A.IniState 
	FROM  Coupon_CodeInfo  A 
	INNER  JOIN  #curcouponcode C ON A.COUPONCODE=C.Couponcode 
	WHERE A.isini=1
	
	--开账后写入的删掉	
	DELETE	A 
	FROM	dbo.Coupon_CodeInfo A
	INNER  JOIN  #curcouponcode C ON A.COUPONCODE=C.Couponcode 
	WHERE A.isini<>1
	
END
ELSE IF @nBillType = 424 --优惠券出库单
BEGIN
		  DECLARE @OutBillBillcode VARCHAR(MAX)	
		    INSERT INTO #curcouponcode 
		(	
			CouponCode
				
		)		
          SELECT   CouponCode FROM Coupon_CodeInOut WHERE BillNumberId =@nBillID 
         -- SELECT @OutBillBillcode = CouponCode FROM Coupon_OutBill WHERE BillNumberId =@nBillID 
    
	INSERT INTO dbo.Coupon_OutBill
	        ( BillNumberId ,
	          CouponId ,
	          CouponCode ,
	          Comment ,
	          Qty ,
	          Price ,
	          NPrice ,
	          Total ,
	          NTotal ,
	          OutDate ,
	          InvalidDate ,
	          CargoId ,
	          BackQty
	        )
	OUTPUT INSERTED.ID INTO #temptable	
	SELECT @nNewBillID,
			CouponId ,
			CouponCode ,
			Comment ,
			Qty ,
		    Price ,
			NPrice ,
			Total ,
			NTotal ,
			OutDate ,
			InvalidDate ,
			CargoId ,
			BackQty
	FROM  Coupon_OutBill  WHERE BillNumberID=@nBillID
	--处理券状态信息表
	--	INSERT INTO #curcouponcode 
	--	(	
	--		CouponCode
				
	--	)		
	--SELECT * FROM f_split(@OutBillBillcode,'я')
	
	UPDATE A 
	SET [State]=1,
		OutDate = NULL,
		InvalidDate= CASE  WHEN ct.InvalidType=1 THEN  A.InvalidDate
						   WHEN ct.InvalidType=3 THEN  A.InvalidDate
						   WHEN ct.InvalidType=2 THEN  CASE WHEN ct.InvalidStartDateType =1 THEN A.InvalidDate
															WHEN ct.InvalidStartDateType =2 THEN '9999-12-31' --入库的时候 判断不到出库日期 不写
															ELSE '9999-12-31' END 
									ELSE '9999-12-31'   
									
							END 
	FROM  Coupon_CodeInfo  A 
	INNER JOIN coupon_TypeInfo ct ON ct.CouponId=A.CouponId
	INNER  JOIN  #curcouponcode C ON A.COUPONCODE=C.Couponcode 
END
ELSE IF @nBillType = 425  --优惠券调拨单
BEGIN
         DECLARE @AllotBillcode VARCHAR(MAX)
		  DECLARE @AllotBillid VARCHAR(MAX)		
          --SELECT @AllotBillcode = CouponCode FROM Coupon_AllotBill WHERE BillNumberId =@nBillID
            
		      INSERT INTO #curcouponcode 
		(	
			CouponCode
				
		)		
          SELECT   CouponCode FROM Coupon_CodeInOut WHERE BillNumberId =@nBillID  
          SELECT @AllotBillid = id FROM Coupon_AllotBill WHERE BillNumberId =@nBillID 
	INSERT INTO dbo.Coupon_AllotBill
	        ( BillNumberId ,
	          CouponId ,
	          CouponCode ,
	          InCargoId ,
	          OutCargoId,
	          qty,
	          Comment
	        )
	OUTPUT INSERTED.ID INTO #temptable	
	SELECT @nNewBillID,
		   CouponId ,
		   CouponCode ,
		   InCargoId ,
		   OutCargoId,
		   qty,
		   Comment
	FROM  Coupon_AllotBill  WHERE BillNumberID=@nBillID
	
	--处理券状态信息表
	--INSERT INTO #curcouponcode 
	--	(	
	--		CouponCode
				
	--	)
	--SELECT * FROM f_split(@AllotBillcode,'я')
	
	--仓库信息,货位ID
	UPDATE A 
	SET  KtypeId=@outktypeid,CargoId=OutCargoId
	FROM  Coupon_CodeInfo  A 
	INNER  JOIN  #curcouponcode C ON A.COUPONCODE=C.Couponcode 
	LEFT JOIN Coupon_AllotBill CA ON CA.ID=@AllotBillid
	
	
END
ELSE IF @nBillType = 426	--优惠券退货单
BEGIN
			DECLARE @BackBillcode VARCHAR(MAX)
		  DECLARE @BackBillid VARCHAR(MAX)	
		  
		      INSERT INTO #curcouponcode 
		(	
			CouponCode
				
		)		
          SELECT   CouponCode FROM Coupon_CodeInOut WHERE BillNumberId =@nBillID 
		  
		  	
         -- SELECT @BackBillcode = CouponCode FROM Coupon_BackBill WHERE BillNumberId =@nBillID 
          
          SELECT @BackBillid = id FROM Coupon_BackBill WHERE BillNumberId =@nBillID 
	INSERT INTO dbo.Coupon_BackBill
	        ( BillNumberId ,
	          CouponId ,
	          CouponCode ,
	          Qty ,
	          Price ,
	          NPrice ,
	          Total ,
	          NTotal ,
	          Comment ,
	          CargoId ,
	          OutBillId
	        )
	OUTPUT INSERTED.ID INTO #temptable	
	SELECT @nNewBillID,
		   CouponId ,
		   CouponCode ,
		   Qty ,
		   Price ,
		  NPrice ,
		  Total ,
		  NTotal ,
		  Comment ,
		  CargoId ,
		  OutBillId
		FROM  Coupon_BackBill  WHERE BillNumberID=@nBillID
		
	--处理券状态信息表
	--INSERT INTO #curcouponcode 
	--	(	
	--		CouponCode
				
	--	)
	--	SELECT * FROM f_split(@BackBillcode,'я')
	
	--出库
	UPDATE A 
	SET [State]=2,
		KtypeId=CASE WHEN inout.OutKtypeId IS NULL THEN a.IniKtypeId ELSE  inout.OutKtypeId END,--期初出库的券用初始值
		CargoId=CASE WHEN inout.OutCargoId IS NULL THEN a.IniCargoId ELSE  inout.OutCargoId	END
	FROM  Coupon_CodeInfo  A 
	INNER  JOIN  #curcouponcode C ON A.COUPONCODE=C.Couponcode 
	LEFT JOIN (SELECT outktypeid ,outcargoid,CouponCode
				from Coupon_CodeInOut a 
				INNER JOIN (
				SELECT TOP 1 BillNumberId FROM Coupon_BillIndex a WHERE PostTime<(
				SELECT PostTime FROM dbo.Coupon_BillIndex WHERE BillNumberId=@nBillID) AND a.BillType=424)cb ON cb.BillNumberId=a.billnumberid
				WHERE [state]=2  AND billtype=424
	) inout ON C.Couponcode=inout.Couponcode
	
	
	--更新出库单退货的数量
	UPDATE A
	SET BackQty=a.backqty-b.Qty
	FROM  dbo.Coupon_OutBill a
	INNER JOIN coupon_backbill b ON a.id=b.OutBillId
	WHERE b.BillNumberID=@nBillID
	
	
END
ELSE IF @nBillType = 429   --分支机构调拨出库
BEGIN
--优惠券分支机构调拨出库单
		  DECLARE @AllotBillStypecode VARCHAR(MAX)			
         -- SELECT @AllotBillStypecode = CouponCode FROM Coupon_AllotBillStype WHERE BillNumberId =@nBillID 
            
		      INSERT INTO #curcouponcode 
		(	
			CouponCode
				
		)		
          SELECT   CouponCode FROM Coupon_CodeInOut WHERE BillNumberId =@nBillID 
          
	INSERT INTO dbo.Coupon_AllotBillStype
	        ( BillNumberId ,
	          CouponId ,
	          CouponCode ,
	          Comment ,
	          InCargoId ,
	          OutCargoId,
	          Qty ,
	          Price,
	          Total,
	          InvalidDate ,	        
	          InStockDate,
	          OutDate	      	       
	        )

    OUTPUT INSERTED.ID INTO #temptable					
	SELECT	@nNewBillID,
			 CouponId ,
	          CouponCode ,
	          Comment ,
	          InCargoId ,
	          OutCargoId,
	          Qty ,
	          Price,
	          Total,
	          InvalidDate ,	        
	          InStockDate,
	          OutDate
	FROM Coupon_AllotBillStype WHERE BillNumberID=@nBillID
	--处理券状态信息表
	--INSERT INTO #curcouponcode 
	--	(	
	--		CouponCode
				
	--	)
	--  SELECT * FROM f_split(@AllotBillStypecode,'я')
    --红冲出库把状态改回1
	UPDATE A 
	SET [State]=1,
	KtypeId=ci.OutKtypeId,
	CargoId=ci.OutCargoId		
	FROM  Coupon_CodeInfo  A 
	INNER JOIN   coupon_TypeInfo ct ON ct.CouponId=A.CouponId
	INNER JOIN  Coupon_CodeInOut ci ON ci.BillNumberId=@nBillID
	INNER  JOIN  #curcouponcode C ON A.COUPONCODE=C.Couponcode 
	
END
ELSE IF @nBillType = 428   --分支机构调拨入库
BEGIN
--优惠券分支机构调拨入库单
		  DECLARE @AllotinBillStypecode1 VARCHAR(MAX)	
		  DECLARE @AllotBillidStypeid VARCHAR(MAX)
         -- SELECT @AllotinBillStypecode1 = CouponCode FROM Coupon_AllotBillStype WHERE BillNumberId =@nBillID 
            
		      INSERT INTO #curcouponcode 
		(	
			CouponCode
				
		)		
          SELECT   CouponCode FROM Coupon_CodeInOut WHERE BillNumberId =@nBillID 
          
          SELECT @AllotBillidStypeid= frombillnumberid FROM Coupon_BillIndex WHERE BillNumberId =@nBillID 
	INSERT INTO dbo.Coupon_AllotBillStype
	        ( BillNumberId ,
	          CouponId ,
	          CouponCode ,
	          Comment ,
	          InCargoId ,
	          OutCargoId,
	          Qty ,
	          Price,
	          Total,
	          InvalidDate ,	        
	          InStockDate,
	          OutDate	      	       
	        )

    OUTPUT INSERTED.ID INTO #temptable					
	SELECT	@nNewBillID,
			 CouponId ,
	          CouponCode ,
	          Comment ,
	          InCargoId ,
	          OutCargoId,
	          Qty ,
	          Price,
	          Total,
	          InvalidDate ,	        
	          InStockDate,
	          OutDate
	FROM Coupon_AllotBillStype WHERE BillNumberID=@nBillID
	
	--处理券状态信息表
	--INSERT INTO #curcouponcode 
	--	(	
	--		CouponCode
				
	--	)
	--  SELECT * FROM f_split(@AllotinBillStypecode1,'я')
    
    --992调整：调拨入库回写可以直接回写到主表的往来仓库，不需再去Coupon_CodeInOut寻找关联的单据，
    DECLARE @CotCargoId VARCHAR(100)
    SELECT TOP 1 @CotCargoId=OutCargoId FROM  Coupon_AllotBillStype WHERE BillNumberId=@nBillID
    
    --红冲出库把状态改回7,分支机构优惠券调拨出库
	UPDATE A 
	SET [State]=7,	
	KtypeId=@outktypeid,
	CargoId= @CotCargoId
	FROM  Coupon_CodeInfo  A 
	INNER JOIN   coupon_TypeInfo ct ON ct.CouponId=A.CouponId
	--INNER JOIN   Coupon_CodeInOut cto ON cto.BillNumberId=@AllotBillidStypeid
	INNER  JOIN  #curcouponcode C ON A.COUPONCODE=C.Couponcode 
	
END
--如果是多账户，那么还需要复制账户表
IF EXISTS(
	SELECT BillNumberId 
	FROM BillMulAccount
	WHERE BillNumberId=@nBillID
	AND billtype IN (423,424,425,426)
) 
BEGIN
	INSERT BillMulAccount(BillNumberId ,
						  ATypeID ,
						  Total ,
						  Comment ,
						  VipCardID ,
						  NTotalMoney ,
						  paymoney ,
						  TradeNo ,
						  PayType ,
						  BillType ,
						  yhType ,
						  CouponCode,
						  viptotal)
	SELECT @nNewBillID,
		  ATypeID ,
		  Total ,
		  Comment ,
		  VipCardID ,
		  NTotalMoney ,
		  paymoney ,
		  TradeNo ,
		  PayType ,
		  BillType ,
		  yhType ,
		  CouponCode,
		  viptotal
	FROM BillMulAccount
	WHERE BillNumberId=@nBillID AND billtype=@nBillType
END

/*-------------------------------*/

DROP TABLE #curcouponcode
 
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RedWordInsertInOutListDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_RedWordInsertInOutListDetail
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-14
-- Description: 单据红冲反向插入InOutStockTable，wx_InOutStockTable，listtable明细
-- =============================================

CREATE PROCEDURE Gp_RedWordInsertInOutListDetail
(
	@nBillID NUMERIC(10,0),
	@nNewBillID NUMERIC(10,0),
	@nBillType INT
)
--@encode$--

AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

	--------- 反向插入 InOutStockTable 数据表相关记录---------------------------
	IF EXISTS(SELECT * FROM InOutStockTable WHERE BillNumberID = @nBillID AND BillType=@nBillType)
	BEGIN
		UPDATE	InOutStockTable
		SET		Audited = 0
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10
		
		IF @nBillType<>205
		BEGIN 
			SELECT	*
			INTO	#TempTable1
			FROM	InOutStockTable
			WHERE	BillNumberID = @nBillID AND BillType=@nBillType
			IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
				RETURN  -10

			UPDATE	#TempTable1
			SET		BillNumberID = @nNewBillID,
					Qty = -Qty,
					NQty=-NQty,
					Total = -Total,
					CostTotal = -CostTotal,
					GoodsCostPrice = CostPrice,
					SaleTotal = -SaleTotal,
					TaxTotal = -TaxTotal,
					NSALETOTAL=-NSALETOTAL,
					NTAXTOTAL=-NTAXTOTAL,
					NTOTAL=-NTOTAL,
					PostTime=GETDATE()					
			WHERE	BillNumberID = @nBillID AND BillType=@nBillType
			
			UPDATE	#TempTable1
			SET		HandZeroCost = 1	-- 确认指定0成本
			WHERE	BillNumberID = @nNewBillID
					AND CostPrice = 0
					AND CostTotal = 0
					AND BillType=@nBillType
					
			IF @@ERROR <> 0 
				RETURN  -10

			INSERT INTO InOutStockTable(BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,
			Qty,Price,Total,CostPrice,CostTotal,JobNumber,GoodsNo,OutFactoryDate,Audited,GoodsNumber,ProduceDate,ValidDate,
			GoodsBTypeID,GoodsCostPrice,HandZeroCost,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,
			DTypeID,STypeID,PostTime,ShareFee,CargoID,NPrice,NTotal,NSalePrice,NSaleTotal,NTaxPrice,NTaxTotal,ItemID,IsCombined,NQty,UnitRate,MUNITID,
			IsGift,IsService,Comment,MUnitRate)
			SELECT	BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,
			Qty,Price,Total,CostPrice,CostTotal,JobNumber,GoodsNo,OutFactoryDate,Audited,GoodsNumber,ProduceDate,ValidDate,
			GoodsBTypeID,GoodsCostPrice,HandZeroCost,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,
			DTypeID,STypeID,PostTime,ShareFee,CargoID,NPrice,NTotal,NSalePrice,NSaleTotal,NTaxPrice,NTaxTotal,ItemID,IsCombined,NQty,UnitRate,MUNITID,
			IsGift,IsService,Comment,MUnitRate
			
			FROM	#TempTable1
			WHERE	BillNumberID = @nNewBillID AND BillType=@nBillType
			
			IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			BEGIN
				RETURN  -10
			END
			
			--将明细id 更新成新的明细id
			CREATE TABLE #temptable(orderid INT IDENTITY(1,1),detailid INT)
			
			DECLARE @sql VARCHAR(2000),@tablename VARCHAR(200)=''
			SELECT @tablename = detailTable FROM dbo.BillName WHERE Billtype= @nBillType
			SET @sql='
			INSERT INTO #temptable SELECT id AS detailid 
			FROM '+@tablename+'
			WHERE BillNumberId =  '+CAST( @nNewBillID  AS VARCHAR)
			EXEC (@sql)
			
			UPDATE a
			SET ID=b.detailid
			FROM InOutStockTable a,
			#temptable b ,
			( SELECT RANK() OVER
				(PARTITION BY billnumberid ORDER BY ID)orderid,id
			 FROM #TempTable1 
			 WHERE billnumberid=@nNewBillID AND billtype=@nBillType)c
			WHERE b.orderid=c.orderid AND a.ID=c.ID  AND a.BillNumberId=@nNewBillID
			AND a.BillType=@nBillType

			IF  @@ERROR <> 0 
				RETURN  -10
			DROP TABLE #TempTable1,#temptable
		END
	END
-------------------- 反向插入 wx_InOutStockTable 数据表相关记录----------------------------------------
	IF EXISTS(SELECT * FROM wx_InOutStockTable WHERE BillNumberID = @nBillID AND BillType=@nBillType)
	BEGIN
		UPDATE	wx_InOutStockTable
		SET		Audited = 0
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN -10

		SELECT	BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,Qty,Price,Total,CostPrice,CostTotal,
		JobNumber,GoodsNo,OutFactoryDate,Audited,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,HandZeroCost,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,DTypeID,STypeID,CargoID,NPrice,NTotal,NSalePrice,NSaleTotal,
		NTaxPrice,NTaxTotal,ItemID,IsCombined,NQty,UnitRate,MUNITID,IsService,Comment,MUnitRate
		INTO	#TempTable3
		FROM	wx_InOutStockTable
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10

		

		UPDATE	#TempTable3
		SET		BillNumberID = @nNewBillID,
				Qty = -Qty,
				NQty=-NQty,
				Total = -Total,
				CostTotal = -CostTotal,
				GoodsCostPrice = CostPrice,
				SaleTotal = -SaleTotal,
				TaxTotal = -TaxTotal,
				NSALETOTAL=-NSALETOTAL,
				NTAXTOTAL=-NTAXTOTAL,
				NTOTAL=-NTOTAL		
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10

		UPDATE	#TempTable3
		SET		HandZeroCost = 1	-- 确认指定0成本
		WHERE	BillNumberID = @nNewBillID
				AND CostPrice = 0
				AND CostTotal = 0
				AND BillType=@nBillType
		IF @@ERROR <> 0 
			RETURN  -10

		INSERT INTO wx_InOutStockTable(BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,Qty,Price,Total,CostPrice,CostTotal,
		JobNumber,GoodsNo,OutFactoryDate,Audited,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,HandZeroCost,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,DTypeID,STypeID,CargoID,NPrice,NTotal,NSalePrice,NSaleTotal,
		NTaxPrice,NTaxTotal,ItemID,IsCombined,NQty,UnitRate,MUNITID,IsService,Comment,MUnitRate)
		SELECT	BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,Qty,Price,Total,CostPrice,CostTotal,
		JobNumber,GoodsNo,OutFactoryDate,Audited,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,HandZeroCost,ID,Tax,Discount,SalePrice,SaleTotal,TaxPrice,TaxTotal,DTypeID,STypeID,CargoID,NPrice,NTotal,NSalePrice,NSaleTotal,
		NTaxPrice,NTaxTotal,ItemID,IsCombined,NQty,UnitRate,MUNITID,IsService,Comment,MUnitRate
		FROM	#TempTable3
		WHERE	BillNumberID = @nNewBillID
		AND BillType=@nBillType
		
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
		BEGIN
			RETURN  -10
		END
		
		DROP TABLE #TempTable3
		IF @@ERROR <> 0 
			RETURN  -10
	END

    -------------------- 反向插入 Fact_InOutStockTable 数据表相关记录----------------------------------------
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Fact_InOutstocktable WHERE BillNumberID = @nBillID AND BillType=@nBillType)
	BEGIN
		UPDATE	Fact_InOutstocktable
		SET		Audited = 0
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN -10

		SELECT	*
		INTO	#TempTable4
		FROM	Fact_InOutstocktable
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10

		UPDATE	#TempTable4
		SET		BillNumberID = @nNewBillID,
				Qty = -Qty,
				NQty=-NQty
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10
			
		INSERT INTO dbo.Fact_InOutstocktable
	        ( BillNumberId ,
	          BillDate ,
	          BillType ,
	          PtypeId ,
	          EtypeId ,
	          KtypeId ,
	          Qty ,
	          OutFactoryDate ,
	          Audited ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsOrder ,
	          ID ,
	          DTypeID ,
	          STypeID ,
	          PostTime ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          NQty ,
	          UnitRate ,
	          Comment ,
	          MUnitID ,
	          MUnitRate ,
	          UnitID
	        )
		SELECT BillNumberId ,
	          BillDate ,
	          BillType ,
	          PtypeId ,
	          EtypeId ,
	          KtypeId ,
	          Qty ,
	          OutFactoryDate ,
	          Audited ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsOrder ,
	          ID ,
	          DTypeID ,
	          STypeID ,
	          PostTime ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          NQty ,
	          UnitRate ,
	          Comment ,
	          MUnitID ,
	          MUnitRate ,
	          UnitID
		FROM	#TempTable4
		WHERE	BillNumberID = @nNewBillID
		AND BillType=@nBillType
		
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
		BEGIN
			RETURN  -10
		END
		
		DROP TABLE #TempTable4
		IF @@ERROR <> 0 
			RETURN  -10
	END
	-------------------- 反向插入 Coupon_CodeInOut 数据表相关记录----------------------------------------
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Coupon_CodeInOut WHERE BillNumberID = @nBillID AND BillType=@nBillType)
	BEGIN
		SELECT	*
		INTO	#TempTable5
		FROM	Coupon_CodeInOut
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10

		UPDATE	#TempTable5
		SET		BillNumberID = @nNewBillID,
				total = -total,
				Ntotal=-Ntotal
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10
			
		INSERT INTO dbo.Coupon_CodeInOut
		        ( BillNumberId ,
		          BillType ,
		          BillDate ,
		          DetailId ,
		          CouponCode ,
		          CouponId ,
		          [State] ,
		          InKtypeId ,
		          InCargoId ,
		          OutKtypeId ,
		          OutCargoId ,
		          Total ,
		          NTotal
		        )
		SELECT	  BillNumberId ,
		          BillType ,
		          BillDate ,
		          DetailId ,
		          CouponCode ,
		          CouponId ,
		          [State] ,
		          InKtypeId ,
		          InCargoId ,
		          OutKtypeId ,
		          OutCargoId ,
		          Total ,
		          NTotal
		FROM	#TempTable5
		WHERE	BillNumberID = @nNewBillID
		AND BillType=@nBillType
		
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
		BEGIN
			RETURN  -10
		END
		
		DROP TABLE #TempTable5
		IF @@ERROR <> 0 
			RETURN  -10
	END
	
	--------------------- 反向插入 ListTable 数据表相关记录，且 Audited = 0 ( 代表红冲记录 ) 红冲不再向listtable插入数据-------------------
	IF EXISTS(SELECT * FROM ListTable WHERE BillNumberID = @nBillID AND BillType=@nBillType) 
	BEGIN
		UPDATE	ListTable
		SET		Audited = 0
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10

		SELECT	--*
		-- listTable　有自增列写出列字
		BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,Qty,Price,Total,CostPrice,CostTotal,JobNumber,GoodsNo,OutFactoryDate,Audited,Ifout,DTypeID,STypeID,STypeID2,CID,Ntotal,Rate
		INTO	#TempTable2
		FROM	ListTable
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10

		UPDATE	#TempTable2
		SET		BillNumberID = @nNewBillID,
				Total = -Total,
				CostTotal = -CostTotal,
				Ntotal = -Ntotal
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10
			


		INSERT INTO ListTable
		SELECT	--*
		BillNumberId,BillDate,BillType,AtypeId,PtypeId,BtypeId,EtypeId,KtypeId,Qty,Price,Total,CostPrice,CostTotal,JobNumber,GoodsNo,OutFactoryDate,Audited,Ifout,DTypeID,STypeID,STypeID2,CID,Ntotal,Rate
		FROM	#TempTable2
		WHERE	BillNumberID = @nNewBillID AND BillType=@nBillType
		IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
			RETURN  -10
		DROP TABLE #TempTable2
		IF @@ERROR <> 0 
			RETURN  -10
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillID NUMERIC(10,0),
	@nNewBillID NUMERIC(10,0),
	@nBillType INT,
	@nRet	INT
	
SELECT
	@nBillID=1,
	@nNewBillID=2,
	@nBillType=404	

BEGIN TRAN

EXEC @nRet=
Gp_RedWordInsertInOutListDetail
	@nBillID,
	@nNewBillID,
	@nBillType
	


ROLLBACK TRAN
*/



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RedWordPostmortem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_RedWordPostmortem
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-14
-- Description: 单据红冲事后处理

--修改:冯波
-- =============================================

CREATE PROCEDURE Gp_RedWordPostmortem
(
	@nBillID NUMERIC(10,0),
	@nNewBillID NUMERIC(10,0),
	@nBillType INT
)
--@encode$--

AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

DECLARE @nRet INT

DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'
/*----------------  按单结算红冲或删除时原被结算单的已结算金额还原 
				    按单结算加了可以负金额过帐，因此此处加绝对值 ----------------*/


IF @nBillType NOT IN(327,328,329)
BEGIN
UPDATE	BillIndex
SET		CompleteTotal = ISNULL(a.CompleteTotal,0) + ISNULL(b.CompleteTotal,0),
		nCompleteTotal = ISNULL(a.nCompleteTotal,0) + ISNULL(b.nCompleteTotal,0)
FROM	BillIndex a,
		(
			SELECT	GoodsBillID,MoneyBillID,SUM(CompleteTotal) AS CompleteTotal,SUM(NCompleteTotal) AS NCompleteTotal,BillType
			FROM	dbo.CompleteTotal c
			WHERE MoneyBillID = @nBillID
			GROUP BY GoodsBillID,MoneyBillID,BillType
		)b
WHERE	a.BillNumberID = b.GoodsBillID
		AND b.MoneyBillID = @nBillID
		AND a.BillType=b.BillType
		AND (a.Billtype in (45,6,148,149,150,151,115,129,404,46)
			OR (a.Billtype=36 AND @ExpenseToAr=1 AND LEFT(a.btypeid,5)='00001'))
			

			
UPDATE	BillIndex
SET		CompleteTotal = ISNULL(a.CompleteTotal,0) - ISNULL(b.CompleteTotal,0),
		nCompleteTotal = ISNULL(a.nCompleteTotal,0) - ISNULL(b.nCompleteTotal,0)
FROM	BillIndex a,
		(
			SELECT	GoodsBillID,MoneyBillID,SUM(CompleteTotal) AS CompleteTotal,SUM(NCompleteTotal) AS NCompleteTotal,BillType
			FROM	dbo.CompleteTotal c
			WHERE MoneyBillID = @nBillID
			GROUP BY GoodsBillID,MoneyBillID,BillType
		)b
WHERE	a.BillNumberID = b.GoodsBillID
		AND b.MoneyBillID = @nBillID
		AND a.BillType=b.BillType 
		AND (a.Billtype not in (45,6,148,149,150,151,115,129,36,46)
			OR (a.Billtype=36 AND (@ExpenseToAr=0 OR LEFT(a.btypeid,5)='00002')))
			
			
UPDATE	dbo.Coupon_BillIndex
SET		CompleteTotal = ISNULL(a.CompleteTotal,0) - ISNULL(b.CompleteTotal,0),
		nCompleteTotal = ISNULL(a.nCompleteTotal,0) - ISNULL(b.nCompleteTotal,0)
FROM	Coupon_BillIndex a,
		(
			SELECT	GoodsBillID,MoneyBillID,
					CASE WHEN  billtype =426 THEN SUM(CompleteTotal)*-1 ELSE  SUM(CompleteTotal) END  AS CompleteTotal,
					CASE WHEN  billtype =426 THEN SUM(NCompleteTotal)*-1 ELSE SUM(CompleteTotal) END AS NCompleteTotal,
					BillType
			FROM	dbo.CompleteTotal c
			WHERE MoneyBillID = @nBillID
			GROUP BY GoodsBillID,MoneyBillID,BillType
		)b
WHERE	a.BillNumberID = b.GoodsBillID
		AND b.MoneyBillID = @nBillID
		AND a.BillType=b.BillType
						
			
UPDATE	ReceiptBillIndex
SET		CompleteTotal = ISNULL(a.CompleteTotal,0) - ISNULL(b.CompleteTotal,0),
		nCompleteTotal = ISNULL(a.nCompleteTotal,0) - ISNULL(b.nCompleteTotal,0)
FROM	ReceiptBillIndex a,
		(
			SELECT	GoodsBillID,MoneyBillID,SUM(CompleteTotal) AS CompleteTotal,SUM(NCompleteTotal) AS NCompleteTotal,BillType
			FROM	dbo.CompleteTotal c
			WHERE MoneyBillID = @nBillID
			GROUP BY GoodsBillID,MoneyBillID,BillType
		)b
WHERE	a.BillNumberID = b.GoodsBillID
		AND b.MoneyBillID = @nBillID
		AND a.BillType=b.BillType
		AND (a.Billtype IN (404,405))
END					
		
IF @nBillType IN (4,66,189)
BEGIN
	EXEC Gp_Deal_JS @nBillID,@nBillType
END
ELSE
BEGIN
	---------- 处理按单结算的收付款红冲返回问题----------------------
	-- 处理按单结算的问题
	DELETE FROM CompleteTotal WHERE (GoodsBillID = @nBillID OR MoneyBillID = @nBillID) AND BillType=@nBillType	
	-- 处理按商品结算的问题
	DELETE FROM CompleteGoodTotal WHERE (GoodsBillID = @nBillID OR MoneyBillID = @nBillID) AND BillType=@nBillType
	--处理按品牌结算的问题
	DELETE FROM dbo.CompleteBrandarTotal WHERE (GoodsBillID = @nBillID OR MoneyBillID = @nBillID) AND BillType=@nBillType
	------------------- 处理按单结算的收付款红冲返回问题 - End ---------------------
END
-------------------------销售出库单红冲删除引用此单的退货单，换货单草稿----------	
IF @nBillType=11
BEGIN		
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM SaleBackBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 DELETE FROM BillIndex WHERE BillNumberID IN (SELECT A.BillNumberID FROM SaleBackBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 
		 
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM SaleGoodsExchangeBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 DELETE FROM BillIndex WHERE BillNumberID IN (SELECT A.BillNumberID FROM SaleGoodsExchangeBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)		 
END	


-------------------------组合销售出库单红冲删除引用此单的退货单----------	
IF @nBillType=12
BEGIN		
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM PT_Combin_SaleBackBillDetail A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 DELETE FROM BillIndex WHERE BillNumberID IN (SELECT A.BillNumberID FROM PT_Combin_SaleBackBillDetail A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
END	
	
-------------------------销售出库单红冲删除引用此单的退货单草稿 END----------	

--采购入库红冲删除引用此单的退货，换货单草稿---------------
IF @nBillType=34
BEGIN		
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM BuyBackBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 DELETE FROM BillIndex WHERE BillNumberID IN (SELECT A.BillNumberID FROM BuyBackBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 
		 
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM BuyGoodsExchangeBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 DELETE FROM BillIndex WHERE BillNumberID IN (SELECT A.BillNumberID FROM BuyGoodsExchangeBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)		 
END	
--采购入库红冲删除引用此单的退货，换货单草稿 END---------------


-------------------------零售单红冲删除引用此单的退货单，换货单草稿----------
IF @nBillType=305
BEGIN			
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM RetailBackBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 DELETE FROM BillIndex WHERE BillNumberID IN (SELECT A.BillNumberID FROM RetailBackBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM SaleGoodsExchangeBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		 DELETE FROM BillIndex WHERE BillNumberID IN (SELECT A.BillNumberID FROM SaleGoodsExchangeBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)		 
END
-------------------------零售单红冲删除引用此单的退货单草稿 END----------	

--------------------------------红冲该单据时,删除引用了该单据的仓库出/入库单的草稿单据 start-----------------------------------------
IF EXISTS(
	SELECT TOP 1 A.BillNumberID 
	FROM (SELECT * FROM FactDepotInOut WHERE FromBillNumberID=@nBillId AND FromBillType=@nBillType) A,factindex B 
	WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1
)
BEGIN
	DELETE FROM factindex 
	WHERE BillNumberID IN (
		SELECT A.BillNumberID 
		FROM (
			SELECT * FROM FactDepotInOut 
			WHERE FromBillNumberID=@nBillId AND FromBillType=@nBillType
		) A,factindex B 
		WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1
	)		
	
	DELETE FactDepotInOut 
	WHERE FromBillNumberID = @nBillId AND FromBillType=@nBillType AND BillNumberID NOT IN (SELECT BillNumberID FROM factindex)
END
--------------------------------红冲该单据时,删除引用了该单据的仓库出/入库单的草稿单据 end-----------------------------------------

/*----START------红冲反算销售、采购订单的已发货、已到货数量----------*/
EXEC GP_Deal_All @nBillID,@nBillType,@nNewBillID

IF @nBillType IN (11,12,34,140,144,400,402)
BEGIN
	-- 检测销售、采购单关联订单的完成状态
	EXEC @nRet = GP_AuditingCheckOrderState @nBillID,1
	
	IF @nRet <> 0 RETURN -1
	IF @nBillType=11
	BEGIN
		IF EXISTS(
			SELECT TOP 1 1
			FROM SaleBill a
			INNER JOIN OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN OrderIndex c
			ON b.billNumberID=c.billNumberId
			WHERE a.BillNumberId=@nBillID
			AND a.OrderID<>-1 
			AND c.BillOver=1
		)
		BEGIN
			UPDATE OrderIndex
			SET OrderState=1
			FROM
			(
				SELECT DISTINCT a.BillNumberId,c.billNumberId AS OrderBillNumberID
				FROM SaleBill a
				INNER JOIN OrderBill b
				ON a.OrderID=b.OrderID
				INNER JOIN OrderIndex c
				ON b.billNumberID=c.billNumberId
				WHERE a.BillNumberId=@nBillID
				AND a.OrderID<>-1 
				AND c.BillOver=1
			) b
			WHERE OrderIndex.billNumberId=b.OrderBillNumberID
		END
	END
	ELSE IF @nBillType=12
	BEGIN
		IF EXISTS(
			SELECT TOP 1 1
			FROM PT_Combin_SaleBillDetail a
			INNER JOIN PT_Combin_OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN OrderIndex c
			ON b.billNumberID=c.billNumberId
			WHERE a.BillNumberId=@nBillID
			AND a.OrderID<>-1 
			AND c.BillOver=1
		)
		BEGIN
			UPDATE OrderIndex
			SET OrderState=1
			FROM
			(
				SELECT DISTINCT a.BillNumberId,c.billNumberId AS OrderBillNumberID
				FROM PT_Combin_SaleBillDetail a
				INNER JOIN PT_Combin_OrderBill b
				ON a.OrderID=b.OrderID
				INNER JOIN OrderIndex c
				ON b.billNumberID=c.billNumberId
				WHERE a.BillNumberId=@nBillID
				AND a.OrderID<>-1 
				AND c.BillOver=1
			) b
			WHERE OrderIndex.billNumberId=b.OrderBillNumberID
		END
	END
	ELSE IF @nBillType=140
	BEGIN
		IF EXISTS(
			SELECT TOP 1 1
			FROM dbo.CommissionBill a
			INNER JOIN OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN OrderIndex c
			ON b.billNumberID=c.billNumberId
			WHERE a.BillNumberId=@nBillID
			AND a.OrderID<>-1 
			AND c.BillOver=1
		)
		BEGIN
			UPDATE OrderIndex
			SET OrderState=1
			FROM
			(
				SELECT DISTINCT a.BillNumberId,c.billNumberId AS OrderBillNumberID
				FROM CommissionBill a
				INNER JOIN OrderBill b
				ON a.OrderID=b.OrderID
				INNER JOIN OrderIndex c
				ON b.billNumberID=c.billNumberId
				WHERE a.BillNumberId=@nBillID
				AND a.OrderID<>-1 
				AND c.BillOver=1
			) b
			WHERE OrderIndex.billNumberId=b.OrderBillNumberID
		END
	END
	ELSE IF @nBillType=402
	BEGIN
		IF EXISTS(
			SELECT TOP 1 1
			FROM SendBill a
			INNER JOIN OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN OrderIndex c
			ON b.billNumberID=c.billNumberId
			WHERE a.BillNumberId=@nBillID
			AND a.OrderID<>-1 
			AND c.BillOver=1
		)
		BEGIN
			UPDATE OrderIndex
			SET OrderState=1
			FROM
			(
				SELECT DISTINCT a.BillNumberId,c.billNumberId AS OrderBillNumberID
				FROM SendBill a
				INNER JOIN OrderBill b
				ON a.OrderID=b.OrderID
				INNER JOIN OrderIndex c
				ON b.billNumberID=c.billNumberId
				WHERE a.BillNumberId=@nBillID
				AND a.OrderID<>-1 
				AND c.BillOver=1
			) b
			WHERE OrderIndex.billNumberId=b.OrderBillNumberID
		END
	END
	ELSE IF @nBillType=34
	BEGIN
		IF EXISTS(
			SELECT TOP 1 1
			FROM BuyBill a
			INNER JOIN OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN OrderIndex c
			ON b.billNumberID=c.billNumberId
			WHERE a.BillNumberId=@nBillID
			AND a.OrderID<>-1 
			AND c.BillOver=1
		)
		BEGIN
			UPDATE OrderIndex
			SET OrderState=1
			FROM
			(
				SELECT DISTINCT a.BillNumberId,c.billNumberId AS OrderBillNumberID
				FROM BuyBill a
				INNER JOIN OrderBill b
				ON a.OrderID=b.OrderID
				INNER JOIN OrderIndex c
				ON b.billNumberID=c.billNumberId
				WHERE a.BillNumberId=@nBillID
				AND a.OrderID<>-1 
				AND c.BillOver=1
			) b
			WHERE OrderIndex.billNumberId=b.OrderBillNumberID
		END
	END 
	ELSE IF @nBillType=144
	BEGIN
		IF EXISTS(
			SELECT TOP 1 1
			FROM dbo.CommissionBill a
			INNER JOIN OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN OrderIndex c
			ON b.billNumberID=c.billNumberId
			WHERE a.BillNumberId=@nBillID
			AND a.OrderID<>-1 
			AND c.BillOver=1
		)
		BEGIN
			UPDATE OrderIndex
			SET OrderState=1
			FROM
			(
				SELECT DISTINCT a.BillNumberId,c.billNumberId AS OrderBillNumberID
				FROM CommissionBill a
				INNER JOIN OrderBill b
				ON a.OrderID=b.OrderID
				INNER JOIN OrderIndex c
				ON b.billNumberID=c.billNumberId
				WHERE a.BillNumberId=@nBillID
				AND a.OrderID<>-1 
				AND c.BillOver=1
			) b
			WHERE OrderIndex.billNumberId=b.OrderBillNumberID
		END
	END
	ELSE IF @nBillType=400
	BEGIN
		IF EXISTS(
			SELECT TOP 1 1
			FROM AppraisalBill a
			INNER JOIN OrderBill b
			ON a.OrderID=b.OrderID
			INNER JOIN OrderIndex c
			ON b.billNumberID=c.billNumberId
			WHERE a.BillNumberId=@nBillID
			AND a.OrderID<>-1 
			AND c.BillOver=1
		)
		BEGIN
			UPDATE OrderIndex
			SET OrderState=1
			FROM
			(
				SELECT DISTINCT a.BillNumberId,c.billNumberId AS OrderBillNumberID
				FROM AppraisalBill a
				INNER JOIN OrderBill b
				ON a.OrderID=b.OrderID
				INNER JOIN OrderIndex c
				ON b.billNumberID=c.billNumberId
				WHERE a.BillNumberId=@nBillID
				AND a.OrderID<>-1 
				AND c.BillOver=1
			) b
			WHERE OrderIndex.billNumberId=b.OrderBillNumberID
		END
	END
END
/*------------红冲反算销售、采购订单的已发货、已到货数量 end----------*/


	
------------------------业绩分配的处理 start------------------------------
IF EXISTS(SELECT TOP 1 1 FROM PerformanceDistribution WHERE BillNumberId = @nBillID)
BEGIN
	DELETE FROM PerformanceDistribution WHERE BillNumberId = @nBillID
END
------------------------业绩分配的处理 end------------------------------

--销售出库单回写OM发货数量
IF @nBillType=11
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.SaleBill WHERE BillNumberId=@nBillID AND OMBillID<>0)
	BEGIN
		UPDATE dbo.OM_OrderDetail SET ReachQty-=c.mqty
		FROM dbo.SaleBill c  WHERE dbo.OM_OrderDetail.id=c.ombillid AND c.BillNumberId=@nbillid
				
		UPDATE dbo.OM_OrderDetail SET STATUS=0
		WHERE ReachQty=0 AND id IN (SELECT ombillid FROM dbo.SaleBill WHERE billNumberID =@nbillid)
		
		DELETE FROM dbo.OM_Shipments WHERE GoodsBillID IN (SELECT ID FROM dbo.SaleBill WHERE billNumberID =@nbillid)
	END
END

--销售退货单回写OM已开单数量
IF @nBillType=45
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.saleBackBill WHERE BillNumberId=@nBillID AND OMBillID<>0)
	BEGIN
		UPDATE dbo.OM_BackOrderDetail SET ReachQty-=c.mqty ,
			[status]=(CASE WHEN OM_BackOrderDetail.ReachQty-c.MQty >=OM_BackOrderDetail.Qty THEN 2  --完成状态 
						   WHEN ReachQty-c.MQty <OM_BackOrderDetail.Qty AND ReachQty-c.MQty >0 THEN 3  --开单未完成
						   ELSE 0 END )  --提交未开单
		FROM dbo.saleBackBill c  WHERE dbo.OM_BackOrderDetail.id=c.ombillid AND c.BillNumberId=@nbillid
								
	END
END

/******lend to buy sale******/
IF @nBillType = 34  
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.BuyBill WHERE BillNumberId=@nBillID AND LendBillNumberID<>0)
	BEGIN
		UPDATE A SET A.BuyQty = ISNULL( A.BuyQty ,0) - B.Qty
		FROM LendBill A JOIN (
			 SELECT @nBillID AS BillNumberId, LendBillNumberID,SUM(qty) AS Qty 
			 FROM dbo.BuyBill
			 WHERE BillNumberId = @nBillID AND LendBillNumberID <> 0
			 GROUP BY LendBillNumberID
		) B ON A.ID=B.LendBillNumberID
	END
END
IF @nBillType = 11  
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.SaleBill WHERE BillNumberId=@nBillID AND LendBillNumberID<>0)
	BEGIN
		UPDATE A SET A.SaleQty = ISNULL( A.SaleQty ,0) - B.Qty
		FROM LendBill A JOIN (
			SELECT @nBillID AS BillNumberId, LendBillNumberID,SUM(qty) AS Qty 
			FROM dbo.SaleBill
			WHERE BillNumberId = @nBillID AND LendBillNumberID <> 0
			GROUP BY LendBillNumberID
		) B ON A.ID=B.LendBillNumberID
	END 
END
IF @nBillType IN (11,34) AND EXISTS( SELECT TOP 1 1  FROM dbo.BillIndex WHERE BillNumberId = @nBillID AND IsLend= 1)
BEGIN
	DECLARE 
	@KtypeID		VARCHAR(50),
	@BtypeID		VARCHAR(50)
	CREATE TABLE #tempbill
	(
		PtypeId				VARCHAR(50),
		KtypeId				VARCHAR(50),
		ItemID				INT,
		IsCombined			INT,
		GoodsNumber			VARCHAR(100),
		Qty					NUMERIC(24,10),
		NQty				NUMERIC(24,10)
	)
	SELECT @KtypeID = ktypeid , @BtypeID = DealBTypeID FROM dbo.BillIndex WHERE BillNumberId = @nBillID
	/****** 更新借欠库存 begin******/
	IF @nBillType = 11 
	BEGIN
		INSERT INTO #tempbill( PtypeId ,KtypeId, ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
		SELECT PtypeId, KTypeID, ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
		FROM dbo.SaleBill WHERE BillNumberId = @nBillID 
		GROUP BY PtypeId,KTypeID, ItemID,IsCombined,GoodsNumber
	END
	ELSE 
	BEGIN
		INSERT INTO #tempbill( PtypeId ,KtypeId, ItemID ,IsCombined ,GoodsNumber , Qty , NQty)
		SELECT PtypeId, KTypeID,ItemID, IsCombined, GoodsNumber ,SUM(Qty) Qty,SUM(NQty)NQty
		FROM dbo.BuyBill WHERE BillNumberId = @nBillID 
		GROUP BY PtypeId, KTypeID,ItemID,IsCombined,GoodsNumber
	END
	SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber,
	SUM(BorrowQty) BorrowQty,SUM(NBorrowQty) NBorrowQty,SUM(LendQty) LendQty,SUM(NLendQty) NLendQty
	INTO #goodslendtemp 
	FROM (
		SELECT		
			t1.PtypeId, 	
			t1.KtypeId,
			@BtypeID AS bTypeID,
			t1.ItemID,
			t1.IsCombined,
			t1.GoodsNumber,
			CASE @nBillType WHEN 34 THEN  Qty   ELSE 0 END AS BorrowQty, --借进
			CASE @nBillType WHEN 34 THEN  NQty  ELSE 0 END AS NBorrowQty,
			CASE @nBillType WHEN 11 THEN  Qty   ELSE 0 END AS LendQty,
			CASE @nBillType WHEN 11 THEN  NQty  ELSE 0 END AS NLendQty
		FROM #tempbill t1 
		UNION ALL
		SELECT a.PtypeId,a.KtypeId,a.BtypeId,a.ItemID,a.Iscombined,a.GoodsNumber,a.BorrowQty,a.NBorrowQty,a.LendQty,a.NLendQty 
		FROM dbo.GoodsLend a JOIN #tempbill b
		ON (a.PtypeId = b.PtypeId 
			AND a.KtypeId = b.KtypeId
			AND a.ItemID = b.ItemID
			AND a.Iscombined = b.IsCombined
			AND a.GoodsNumber = b.GoodsNumber
			AND a.BtypeId = @BtypeID)
	)AS t2 GROUP BY PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber
	DELETE b FROM #goodslendtemp a JOIN GoodsLend b 
	ON b.PtypeId = a.PtypeId 
	AND b.KtypeId = a.KtypeId
	AND b.BtypeId = a.BtypeId
	AND b.ItemID = a.ItemID
	AND b.Iscombined = a.Iscombined
	AND b.GoodsNumber = a.GoodsNumber
	INSERT INTO dbo.GoodsLend( PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,LendQty,NLendQty,Qty,NQty)
	SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,LendQty,NLendQty, 
	(BorrowQty - LendQty) AS Qty, (NBorrowQty - NLendQty) AS NQty FROM #goodslendtemp
	DROP TABLE #goodslendtemp
	--DELETE GoodsLend WHERE Qty = 0 AND NQty = 0
END
/******lend to buy sale******/

/******处理核销单据相关数据 start******/
IF @nBillType = 450
  EXEC Gp_Deal_ChargeOff @nBillID
/******处理核销单据相关数据 end  ******/

------------------------------------存在关联的订单需要把订单的实付金额抵消掉,并将关联ID置为0 start---------------------------------------------------
DECLARE @total NUMERIC(24,10)
DECLARE @ntotal NUMERIC(24,10)
DECLARE @relevanceBillId NUMERIC(10,0)
IF @nBillType = 4 --收款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM dbo.gatheringBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
	BEGIN
		UPDATE OrderIndex SET totalinmoney=totalinmoney-B.total,ntotalinmoney=ntotalinmoney-B.ntotal
		FROM OrderIndex A  
		INNER JOIN (SELECT SUM(p.total) total,SUM(p.ntotal) ntotal,p.RelevanceBillId FROM dbo.gatheringBill P		
			where P.RelevanceBillId IN(SELECT RelevanceBillId FROM gatheringBill WHERE BillNumberId=@nBillID) AND RelevanceBillId>0 AND p.BillNumberId=@nBillID
			 GROUP BY p.RelevanceBillId	) B on  A.billNumberId = B.RelevanceBillId
		UPDATE dbo.gatheringBill SET RelevanceBillId=0 WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	END
END
ELSE IF @nBillType = 66 --付款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM dbo.PayBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
	BEGIN
		UPDATE OrderIndex SET totalinmoney=totalinmoney-B.total,ntotalinmoney=ntotalinmoney-B.ntotal
		FROM OrderIndex A
		INNER JOIN (SELECT SUM(p.total) total,SUM(p.ntotal) ntotal,p.RelevanceBillId FROM dbo.PayBill P		
			where P.RelevanceBillId IN(SELECT RelevanceBillId FROM PayBill WHERE BillNumberId=@nBillID) AND RelevanceBillId>0 AND p.BillNumberId=@nBillID
			 GROUP BY p.RelevanceBillId	) B on  A.billNumberId = B.RelevanceBillId 
		UPDATE dbo.PayBill SET RelevanceBillId=0 WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	END
END
ELSE IF @nBillType IN (189,190)--预收、付款单
BEGIN
	IF EXISTS(
		SELECT BillNumberId 
		FROM dbo.PreBill
		WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	)
	BEGIN
		UPDATE OrderIndex SET totalinmoney=totalinmoney-B.total,ntotalinmoney=ntotalinmoney-B.ntotal
		FROM OrderIndex A
		INNER JOIN (SELECT SUM(p.total) total,SUM(p.ntotal) ntotal,p.RelevanceBillId FROM dbo.PreBill P		
			where P.RelevanceBillId IN(SELECT RelevanceBillId FROM PreBill WHERE BillNumberId=@nBillID) AND RelevanceBillId>0  AND p.BillNumberId=@nBillID
			 GROUP BY p.RelevanceBillId	) B on  A.billNumberId = B.RelevanceBillId 
		UPDATE dbo.PreBill SET RelevanceBillId=0 WHERE BillNumberId=@nBillID AND RelevanceBillId>0
	END
END
------------------------------------存在关联的订单需要把订单的实付金额抵消掉,并将关联ID置为0 end-----------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RedWordValidate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_RedWordValidate
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-10
-- Description: 单据红冲前关联关系检查
--修改：冯波 处理暂估等
-- =============================================

CREATE PROCEDURE Gp_RedWordValidate
(
	@nBillID NUMERIC(10,0),
	@nBillType INT,
	@szPeriod1 DATETIME 
)
--@encode$--

AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

--已经被仓库出入库单引用的单据不能被红冲
IF EXISTS(
	SELECT a.BillNumberId
	FROM 
	(
		SELECT * 
		FROM FactDepotInOut 
		WHERE FromBillNumberID=@nBillID AND FromBillType=@nBillType
	)	a
	INNER JOIN factindex b
	ON a.BillNumberId=b.BillNumberId
	WHERE b.ifcheck='t' AND b.RedWord=0 
)
BEGIN
	RETURN -202 --已经被仓库出入库单引用的单据不能被红冲
END

IF @nBillType=36 --费用单
BEGIN
	--已费用分摊的费用单不能被红冲
	IF EXISTS(
		SELECT a.BillNumberId
		FROM ShareFeeBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID
		AND b.ifcheck='t' AND b.RedWord=0
	)
	BEGIN
		RETURN -200 --已被分摊的费用单不能被红冲
	END
END

IF @nBillType IN (34,11,305,12,16) --采购入库单，销售出库单，组合销售出库单
BEGIN
	--已费用分摊的采购入库单，销售出库单不能被红冲
	IF EXISTS(
		SELECT a.BillNumberId
		FROM ShareSourceBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID
		AND b.ifcheck='t' AND b.RedWord=0
	)
	BEGIN
		RETURN -201 --已被分摊的物流单据不能被红冲
	END
END

IF @nBillType IN (205,206) --采购费用分摊 销售费用分摊
BEGIN
	--费用分摊单不能红冲月结前的单据
	IF EXISTS(
		SELECT a.BillNumberId
		FROM ShareSourceBill a
		INNER JOIN BillIndex b
		ON a.FromBillNumberID=b.BillNumberId
		WHERE a.BillNumberId=@nBillID
		AND b.BillDate<@szPeriod1
		UNION ALL
		SELECT a.BillNumberId
		FROM ShareFeeBill a
		INNER JOIN BillIndex b
		ON a.FromBillNumberID=b.BillNumberId
		WHERE a.BillNumberId=@nBillID
		AND b.BillDate<@szPeriod1
	)
	BEGIN
		RETURN -454 --费用分摊单不能红冲月结前的单据
	END
END

IF @nBillType=159
BEGIN
	IF EXISTS(SELECT 1 FROM Ac_ProvisionForImpairment WHERE BillnumberId=@nBillID)
		RETURN -301
END

IF @nBillType =212
BEGIN
	IF EXISTS(SELECT 1 FROM dbo.Ac_AssetsCards_History WHERE AssertsCardId IN (SELECT AssetCardId FROM dbo.AssetIncDecBill WHERE BillNumberId=@nbillid) AND BillType<>212)
		RETURN -300
END
IF @nBillType =214
BEGIN
	IF EXISTS(
		SELECT 1 FROM Ac_AssetsCards_History AC1 INNER JOIN
		(
			SELECT BusinessDate,AssertsCardId 
			FROM dbo.Ac_AssetsCards_History AC INNER JOIN dbo.DepBill D ON AC.AssertsCardId=D.AssetCardId AND AC.BillId=D.BillNumberId
			WHERE D.BillNumberId=@nBillID AND AC.BillType=214
		)A ON AC1.AssertsCardId=A.AssertsCardId WHERE AC1.BusinessDate>A.BusinessDate

	)
		RETURN -300
END

CREATE TABLE #tmp_BillNumberID(BillNumberID INT)

IF @nBillType=305
BEGIN
	--零售单
	
	/*
		当零售退货单都为草稿未过账状态时，对原发出商品出库单红冲时，与之关联的未过账状态的零售退货单一并删除
	*/	
	INSERT #tmp_BillNumberID
	SELECT DISTINCT a.BillNumberId
	FROM RetailBackBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	WHERE  b.ifcheck='f' AND a.OldBillNumberID=@nBillID
		
	IF EXISTS(
		SELECT BillNumberID
		FROM #tmp_BillNumberID
	)
	BEGIN
		DELETE RetailBackBill
		WHERE BillNumberId IN
		(
			SELECT BillNumberID
			FROM #tmp_BillNumberID
		)
		
		DELETE Billindex
		WHERE BillNumberId IN
		(
			SELECT BillNumberID
			FROM #tmp_BillNumberID
		)
	END
	
	/*
	零售退货单过账后，控制原零售单不能红冲，提示：关联的退货单已被过账，不能红冲该单据！
	
	*/
	
	IF EXISTS(
		SELECT a.BillNumberId
		FROM RetailBackBill a
		INNER JOIN Billindex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.OldBillNumberID=@nBillID
		AND b.ifcheck='t' AND b.RedWord=0
	)
	BEGIN	
		RETURN -402
	END
END

IF @nBillType=400
BEGIN
	--暂估入库单
	/*
		当暂估退货单都为草稿未过账状态时，对原暂估入库单红冲时，与之关联的未过账状态的采购暂估发票、暂估退货单一并删除
	*/
	
	
	INSERT #tmp_BillNumberID
	SELECT DISTINCT a.BillNumberId
	FROM AppraisalBackBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	WHERE  b.ifcheck='f' AND a.OldBillNumberID=@nBillID
	
	IF EXISTS(
		SELECT BillNumberID
		FROM #tmp_BillNumberID
	)
	BEGIN
		DELETE AppraisalBackBill
		WHERE BillNumberId IN
		(
			SELECT BillNumberID
			FROM #tmp_BillNumberID
		)
		
		DELETE Billindex
		WHERE BillNumberId IN
		(
			SELECT BillNumberID
			FROM #tmp_BillNumberID
		)
		
		
	END
	
	
	
	
	/*
	当暂估退货单、发出商品退货单过账后，控制原暂估入库单、发出商品出库单不能红冲，提示：关联的退货单已被过账，不能红冲该单据！
	
	*/
	
	IF EXISTS(
		SELECT a.BillNumberId
		FROM AppraisalBackBill a
		INNER JOIN Billindex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.OldBillNumberID=@nBillID
		AND b.ifcheck='t' AND b.RedWord=0
	)
		RETURN -400
		
	/*
		当存在采购暂估开票不管是草稿还是已过帐状态，在红冲原单时，均控制不能红冲，提示：此业务单据已经关联了发票不允许红冲，请删除关联发票数据后再操作！
	*/
	
	IF EXISTS(
		SELECT a.BillNumberID
		FROM ReceiptBill a
		INNER JOIN ReceiptBillIndex b
		ON a.BillNumberID=b.BillNumberID
		WHERE a.MainBillNumberID=@nBillID
		AND b.RedWord=0
	)
	BEGIN
		RETURN -444
	END
	
END 

IF @nBillType=401
BEGIN
	--暂估退货单
	
	
	

	
	/*
		当存在采购暂估开票不管是草稿还是已过帐状态，在红冲原单时，均控制不能红冲，提示：此业务单据已经关联了发票不允许红冲，请删除关联发票数据后再操作！
	*/
	
	IF EXISTS(
		SELECT a.BillNumberID
		FROM ReceiptBill a
		INNER JOIN ReceiptBillIndex b
		ON a.BillNumberID=b.BillNumberID
		WHERE a.MainBillNumberID=@nBillID
		AND b.RedWord=0
	)
	BEGIN
		RETURN -444
	END
	
END

IF @nBillType=404
BEGIN
	--采购暂估开票
	/*
		红冲的条件：
 		单据状态为已过帐；
 		处于未生成凭证状态；
 		此发票【已结算金额】为0；
 		与之关联的成本调价单为未生成凭证状态；

	*/
	IF EXISTS(
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE BillNumberID=@nBillID AND CompleteTotal<>0
	)
		RETURN -455  --此发票存在已结算数据，请取消结算后再进行红冲操作！
		
	IF EXISTS(
		SELECT VourchBillId FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId = @nBillID
		AND VourchBillId IN 
			(
				SELECT BillNumberId 
				FROM Ac_Voucher 
			)
	)
		RETURN -466  --此发票已经生成会计凭证，不能进行红冲操作！
		
	IF EXISTS(
		SELECT a.FromBillNumberID
		FROM AdPriceBill a
		INNER JOIN Billindex b
		ON a.BillNumberId=b.BillNumberId
		WHERE b.FromBillNumberID=@nBillID
		AND b.ifcheck='t' AND b.RedWord=0
	)
	BEGIN
		DECLARE @intAdPriceBillNumberID INT
		
		SELECT @intAdPriceBillNumberID=a.BillNumberID
		FROM AdPriceBill a
		INNER JOIN Billindex b
		ON a.BillNumberId=b.BillNumberId
		WHERE b.FromBillNumberID=@nBillID
		AND b.ifcheck='t' AND b.RedWord=0
		
		
		IF EXISTS(
			SELECT VourchBillId FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId = @intAdPriceBillNumberID
			AND VourchBillId IN 
				(
					SELECT BillNumberId 
					FROM Ac_Voucher 
				)
		)
		RETURN -477  --此发票关联的成本调价单已生成凭证，请删除调价单凭证后再进行红冲操作！
	END
END

IF @nBillType=402
BEGIN
	--发出商品出库单
	
	/*
		当发出商品退货单都为草稿未过账状态时，对原发出商品出库单红冲时，与之关联的未过账状态的销售发货开票、发出商品退货单一并删除
	*/
	
	
	
	INSERT #tmp_BillNumberID
	SELECT DISTINCT a.BillNumberId
	FROM SendBackBill a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	WHERE  b.ifcheck='f' AND a.OldBillNumberID=@nBillID
		
	IF EXISTS(
		SELECT BillNumberID
		FROM #tmp_BillNumberID
	)
	BEGIN
		DELETE SendBackBill
		WHERE BillNumberId IN
		(
			SELECT BillNumberID
			FROM #tmp_BillNumberID
		)
		
		DELETE Billindex
		WHERE BillNumberId IN
		(
			SELECT BillNumberID
			FROM #tmp_BillNumberID
		)
		
		
	END
	
	
	
	/*
	当暂估退货单、发出商品退货单过账后，控制原暂估入库单、发出商品出库单不能红冲，提示：关联的退货单已被过账，不能红冲该单据！
	
	*/
	
	IF EXISTS(
		SELECT a.BillNumberId
		FROM SendBackBill a
		INNER JOIN Billindex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.OldBillNumberID=@nBillID
		AND b.ifcheck='t' AND b.RedWord=0
	)
	BEGIN
		RETURN -402
	END
		
	/*
		当存在销售发货开票不管是草稿还是已过帐状态，在红冲原单时，均控制不能红冲，提示：此业务单据已经关联了发票不允许红冲，请删除关联发票数据后再操作！
	*/
	
	IF EXISTS(
		SELECT a.BillNumberID
		FROM ReceiptBill a
		INNER JOIN ReceiptBillIndex b
		ON a.BillNumberID=b.BillNumberID
		WHERE a.MainBillNumberID=@nBillID
		AND b.RedWord=0
	)
	BEGIN
		RETURN -444
	END
END

IF @nBillType=403
BEGIN
	--发出商品退货单
	
	
	/*
		当存在销售发货开票不管是草稿还是已过帐状态，在红冲原单时，均控制不能红冲，提示：此业务单据已经关联了发票不允许红冲，请删除关联发票数据后再操作！
	*/
	
	IF EXISTS(
		SELECT a.BillNumberID
		FROM ReceiptBill a
		INNER JOIN ReceiptBillIndex b
		ON a.BillNumberID=b.BillNumberID
		WHERE a.MainBillNumberID=@nBillID
		AND b.RedWord=0
	)
	BEGIN
		RETURN -444
	END
END

IF @nBillType=405
BEGIN
	--销售暂估开票
	/*
		红冲的条件：
 		单据状态为已过帐；
 		处于未生成凭证状态；
	*/
	IF EXISTS(
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE BillNumberID=@nBillID AND CompleteTotal<>0
	)
		RETURN -455
		
	IF EXISTS(
		SELECT VourchBillId FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId = @nBillID
		AND VourchBillId IN 
			(
				SELECT BillNumberId 
				FROM Ac_Voucher
			)
	)
		RETURN -466  --此发票已经生成会计凭证，不能进行红冲操作！
END

IF @nBillType=57 --成本调价单
BEGIN
	--自动生成的成本调价单不能进行红冲操作
	IF EXISTS(
		SELECT a.BillNumberId
		FROM AdPriceBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.BillNumberId = @nBillID
		AND ISNULL(a.FromBillNumberID ,0) <> 0
		AND b.ifcheck='t' AND b.RedWord=1
	)
	BEGIN
		RETURN -571 --自动生成的成本调价单不能进行红冲操作
	END
END


IF @nBillType=450
BEGIN
	--往来核销单
	/*
		红冲的条件：
 		单据状态为已过帐；
 		处于未生成凭证状态；
	*/
	IF NOT EXISTS(
		SELECT BillNumberID
		FROM BillIndex
		WHERE BillNumberID=@nBillID AND ifcheck='t' AND draft=0
	)
		RETURN -455 --单据未过账，不能进行红冲操作
		
	IF EXISTS(
		SELECT VourchBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId = @nBillID
		AND VourchBillId IN 
			(
				SELECT BillNumberId 
				FROM Ac_Voucher
			)
	)
		RETURN -466  --此发票已经生成会计凭证，不能进行红冲操作！
END

IF @nBillType = 71   --借进开单  
BEGIN
	IF EXISTS(
		SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId IN 
		(
			SELECT b.BillNumberId
			FROM dbo.LendBill a
			INNER JOIN dbo.BuyBill b
			ON a.BillNumberId=b.LendBillID
			WHERE a.BillNumberId = @nBillID
		)
		AND ifcheck='t' AND RedWord = 0
	)
	BEGIN
		RETURN -572   -- 关联的采购入库单已被过账，不能红冲该单据！
	END

END
IF @nBillType = 87   --借出开单 
BEGIN
	IF EXISTS(
		SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId IN 
		(
			SELECT b.BillNumberId
			FROM dbo.LendBill a
			INNER JOIN dbo.SaleBill b
			ON a.BillNumberId=b.LendBillID
			WHERE a.BillNumberId = @nBillID
		)
		AND ifcheck='t' AND RedWord = 0  
	)
	BEGIN
		RETURN -573   -- 关联的销售出库单已被过账，不能红冲该单据！
	END
END

IF @nBillType=413		--拣货单
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Transportbill A INNER JOIN BillIndex B ON A.BillNumberID=B.billNumberID AND B.RedWord=0 WHERE GoodsBillNumberID=@nBillID)
	BEGIN
		RETURN -574  --拣货单已被运输单引用
	END
END

/***物流单据引用判断***/
IF @nBillType IN(11,12,160,139,140,6,161,146,17,21,187,202,16,183,401,402)
BEGIN
	IF EXISTS(
				SELECT TOP 1 1 FROM dbo.pickbill A INNER JOIN dbo.onShelvespickIndex B ON A.billNumberID=B.billNumberId AND B.RedWord=0 
				WHERE a.GoodsBillNumberID=@nBillID AND A.GoodsBillType=@nBillType
			)
	BEGIN
		RETURN -575 --出库单被拣货单引用
	END
END

IF @nBillType IN(215,45,46,160,142,34,161,126,144,17,21,188,201,16,400,403)
BEGIN
	IF EXISTS(
				SELECT TOP 1 1 FROM dbo.onShelvesbill A INNER JOIN dbo.onShelvespickIndex B ON A.billNumberID=B.billNumberId AND B.RedWord=0 
				WHERE a.GoodsBillNumberID=@nBillID AND A.GoodsBillType=@nBillType
			)
	BEGIN
		RETURN -576 --入库单被上架单引用
	END
END

--借欠单据判断实物库存单据引用
IF @nBillType IN(71,72) AND EXISTS(SELECT TOP 1 1 FROM dbo.FactIndex A INNER JOIN dbo.FactDepotInOut B ON A.BillNumberId=B.BillNumberID
	WHERE B.FromBillType=@nBillType AND B.FromBillNumberID=@nBillID AND A.RedWord=0
)
BEGIN
	RETURN -577	--被仓库入库单调用
END

IF @nBillType IN(87,88) AND EXISTS(SELECT TOP 1 1 FROM dbo.FactIndex A INNER JOIN dbo.FactDepotInOut B ON A.BillNumberId=B.BillNumberID
	WHERE B.FromBillType=@nBillType AND B.FromBillNumberID=@nBillID AND A.RedWord=0
)
BEGIN
	RETURN -578	--被仓库出库单调用
END

/***物流单据引用判断***/

DROP TABLE #tmp_BillNumberID

--判断物流单据生成的会计凭证信息，如果没有审核或者记账，则可以红冲，否则不允许红冲
--DECLARE @nVoucherId NUMERIC(18,0)

--SELECT @nVoucherId = VourchBillId FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId = @nBillID

--IF @@ROWCOUNT <> 0
--BEGIN
--	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE FChecked = 1)
--	BEGIN
--		RAISERROR('凭证已经被审核或者过账，不能红冲物流单据！',16,1)
--		RETURN -1
--	END
--END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RedWordValidateTip]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_RedWordValidateTip
GO

-- =============================================
-- Author:		唐韬
-- Create date: 2015-06-09 08:20:14.200
-- Description: 单据红冲前关联关系检查确定提示
-- =============================================

CREATE PROCEDURE Gp_RedWordValidateTip
(
	@nBillID NUMERIC(10,0),
	@nBillType INT
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

DECLARE @msg VARCHAR(200)='',@returnid INT = 0

IF @nBillType=400
BEGIN
	--billtype 400 暂估入库单涉及到有暂估退货单草稿
	IF EXISTS(
		SELECT b.BillNumberId FROM BillIndex a JOIN  AppraisalBackBill b
		ON a.BillNumberId = b.BillNumberId
		WHERE b.OldBillNumberID = @nBillID
		AND a.ifcheck='f' AND a.draft='1')
	BEGIN
		SET @msg = '本张暂估入库单涉及到有暂估退货单草稿，对应的暂估退货单草稿将被系统强制删除，是否继续？'
		SET @returnid = -1
	END
	
END
ELSE IF @nBillType=402
BEGIN 
	--billtype 402 发出商品出库单涉及到有发出商品退货单草稿
	IF EXISTS(
		SELECT b.BillNumberId  FROM BillIndex a JOIN  SendBackBill b
		ON a.BillNumberId = b.BillNumberId
		WHERE b.OldBillNumberID = @nBillID
		AND a.ifcheck='f' AND draft='1')
	BEGIN
		SET @msg = '本张发出商品出库单涉及到有发出商品退货单草稿，对应的发出商品退货单草稿将被系统强制删除，是否继续？'
		SET @returnid = -1
	END
	
END
ELSE IF @nBillType=11 
BEGIN	
	--销售出库单红冲删除引用此单的退货单，换货单草稿
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM SaleBackBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
	BEGIN
		SET @msg = '本张销售出库单涉及到有退货单草稿，对应的退货单草稿将被系统强制删除，是否继续？'
		SET @returnid = -1
	END	 
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM SaleGoodsExchangeBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
		BEGIN
		SET @msg = '本张销售出库单涉及到有换货单草稿，对应的换货单草稿将被系统强制删除，是否继续？'
		SET @returnid = -1
	END				 
END	
IF @nBillType=34
BEGIN		
	--采购入库红冲删除引用此单的退货，换货单草稿-
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM BuyBackBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
	BEGIN
		SET @msg = '本张采购入库单涉及到有退货单草稿，对应的退货单草稿将被系统强制删除，是否继续？'
		SET @returnid = -1
	END	 
	IF EXISTS(SELECT TOP 1 A.BillNumberID FROM BuyGoodsExchangeBill A,BillIndex B WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 AND A.OldBillNumberID = @nBillId)
	BEGIN
		SET @msg = '本张采购入库单涉及到有换货单草稿，对应的换货单草稿将被系统强制删除，是否继续？'
		SET @returnid = -1
	END	
END

IF EXISTS(
	SELECT TOP 1 A.BillNumberID 
	FROM (SELECT * FROM FactDepotInOut WHERE FromBillNumberID=@nBillID AND FromBillType=@nBillType) A,factindex B 
	WHERE A.BillNumberID = B.BillNumberID AND B.IfCheck='f' AND B.Redword=0 AND B.Draft=1 
)
BEGIN
	SET @msg = '本张单据涉及到有仓库出/入库单草稿，对应的仓库出/入库单草稿将被系统强制删除，是否继续？'
	SET @returnid = -1
END	

SELECT @returnid AS 'returnid' ,@msg AS 'msg' 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReInsertCompleteTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_ReInsertCompleteTotal]
GO






















-- ========================================================================
-- 功能说明：		重新按单结算
-- 最后修改作者：  cqhua
-- 最后修改时间：	2005-07-29
-- 添加对草稿所对应的按单结算物流单据进行删除
-- ========================================================================
Create           PROCEDURE [GP_ReInsertCompleteTotal]
(
@intGoodsNumberId int,
@intMoneyNumberId int,
@decCompleteTotal  NUMERIC(24, 10) ,
@decNCompleteTotal  NUMERIC(24, 10) 
)
--@encode$--
AS
SET NOCOUNT ON


IF(not exists(SELECT 1 FROM Billindex WHERE BillnumberID=@intGoodsNumberId))
	RETURN 1 -------------指定的单据不存在
IF NOT EXISTS(SELECT BillnumberID FROM Billindex WHERE BillnumberID=@intMoneyNumberId)
	RETURN 1

DECLARE @Billtype  int -- 收、付款单据类型
DECLARE @Billtype1 int -- 物流单据类型
DECLARE @szBtypeid VARCHAR(50) --结算单位
DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

SELECT @Billtype =Billtype,@szBtypeid=btypeid FROM Billindex WHERE  BillnumberID=@intMoneyNumberId
SELECT @Billtype1=Billtype FROM Billindex WHERE  BillnumberID=@intGoodsNumberId


DECLARE @CompleteTotal  NUMERIC(24, 10) 
SET @CompleteTotal = 0

DECLARE @CompleteTotal1  NUMERIC(24, 10) 
SET @CompleteTotal1 = 0
SET @CompleteTotal1 = @decCompleteTotal

DECLARE @NCompleteTotal  NUMERIC(24, 10) 
SET @NCompleteTotal = 0

DECLARE @NCompleteTotal1  NUMERIC(24, 10) 
SET @NCompleteTotal1 = 0
SET @NCompleteTotal1 = @decNCompleteTotal

IF EXISTS (SELECT * FROM CompleteTotal WHERE  Draft=0 AND GoodsBillID=@intGoodsNumberId  AND MoneyBillID=@intMoneyNumberId ) 
BEGIN	
	SELECT @CompleteTotal=CompleteTotal,@NCompleteTotal=NCompleteTotal FROM CompleteTotal WHERE  Draft=0 AND GoodsBillID=@intGoodsNumberId  AND MoneyBillID=@intMoneyNumberId  
	SELECT @decCompleteTotal = @decCompleteTotal - @CompleteTotal
	SELECT @decNCompleteTotal = @decNCompleteTotal - @NCompleteTotal
END


-- 收款单

IF @Billtype=4
BEGIN
	IF @Billtype1=157 -- 其实维修受理的两种情况都是一样的处理
	BEGIN
		IF EXISTS(SELECT * FROM Billindex WHERE BillnumberID =@intGoodsNumberId AND Billtype ='157' AND TotalMoney>0)
		BEGIN
			UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = isnull(NCompleteTotal,0)+@decNCompleteTotal WHERE BillnumberID=@intGoodsNumberId
		END
		IF EXISTS(SELECT * FROM Billindex WHERE BillnumberID =@intGoodsNumberId AND Billtype ='157' AND TotalMoney<0)
		BEGIN
			UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = isnull(NCompleteTotal,0)+@decNCompleteTotal WHERE BillnumberID=@intGoodsNumberId
		END
	END
	ELSE
	BEGIN
		IF @Billtype1 =45 OR @Billtype1=148 OR @Billtype1=149 OR (@Billtype1=36 AND @ExpenseToAr=1 AND LEFT(@szBtypeid,5)='00001')
 -- 销售退货单45 返利执行单148  价保执行单149 启用了配置后的费用单
		BEGIN
			UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+(-@decCompleteTotal),NCompleteTotal = isnull(NCompleteTotal,0)+(-@decNCompleteTotal) WHERE BillnumberID=@intGoodsNumberId
		END
		ELSE  -- 销售出库单11  委托代销结算141 其他收入单93 固定资产变卖85  
		BEGIN
			UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = isnull(NCompleteTotal,0)+@decNCompleteTotal WHERE BillnumberID=@intGoodsNumberId
		END
	END
END


-- 付款单
IF @Billtype=66
BEGIN
	IF @Billtype1 =6 OR @Billtype1=150 OR @Billtype1=151  -- 采购退货单6 获利核算执行单150 获得价保执行单151  
	BEGIN
		UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+(-@decCompleteTotal),NCompleteTotal = isnull(NCompleteTotal,0)+(-@decNCompleteTotal) WHERE BillnumberID=@intGoodsNumberId
	END
	ELSE  -- 采购入库单34  受托代销结算145 费用单36 固定资产购买84
	BEGIN
		UPDATE Billindex SET CompleteTotal = isnull(CompleteTotal,0)+@decCompleteTotal,NCompleteTotal = isnull(NCompleteTotal,0)+@decNCompleteTotal WHERE BillnumberID=@intGoodsNumberId
	END
END

IF EXISTS(SELECT * FROM Billindex where BillnumberID=@intGoodsNumberId AND (isnull(TotalInMoney,0)+isnull(CompleteTotal,0)+isnull(preferencemoney,0)>isnull(TotalMoney,0)) )
	RETURN 3


SET  @decCompleteTotal = @CompleteTotal1 
SET  @decNCompleteTotal = @NCompleteTotal1

DECLARE @Billdate datetime
DECLARE @EtypeID varchar(50)
SET @EtypeID =''
IF EXISTS (SELECT etypeid FROM Billindex WHERE BillnumberID =@intMoneyNumberId)
SELECT @Billdate =billdate,@EtypeID=etypeid FROM Billindex WHERE BillnumberID =@intMoneyNumberId

IF @@error<>0 RETURN 2 ------------发生错误
 --先删除CompleteTotal中可能有的草稿的按单结算记录
 -- DELETE FROM CompleteTotal WHERE MoneyBillID=@intMoneyNumberId And Draft=1
 -- IF @@error<>0 RETURN 2 ------------发生错误
IF EXISTS (SELECT * FROM CompleteTotal WHERE GoodsBillID=@intGoodsNumberId  AND MoneyBillID=@intMoneyNumberId) 
 	DELETE FROM CompleteTotal WHERE GoodsBillID=@intGoodsNumberId  AND MoneyBillID=@intMoneyNumberId
--UPDATE	CompleteTotal SET CompleteTotal=CompleteTotal+@decCompleteTotal  WHERE GoodsBillID=@intGoodsNumberId  AND MoneyBillID=@intMoneyNumberId

	INSERT completeTotal(GoodsBillID,MoneyBillID,CompleteTotal,Billdate,etypeid,NCompleteTotal)
	 VALUES(@intGoodsNumberId,@intMoneyNumberId,@decCompleteTotal,@Billdate,@EtypeID,@decCompleteTotal)
IF @@error<>0 RETURN 2 ------------发生错误
ELSE
	RETURN 0


























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_RemoveLogin]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_RemoveLogin]
GO
/*
修改：毛欣蓉
时间：2010-06-09 
内容：删除操作员时间限制表LoginUserTimeSet中的信息
*/

CREATE       PROCEDURE Gp_RemoveLogin
(
	@szEtypeId varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON 
IF EXISTS(SELECT EtypeID FROM AuditingFlowDetail WHERE EtypeID=@szEtypeId)
	RETURN -2
	
IF EXISTS(SELECT ETypeId FROM LoginUser WHERE ETypeID = @szEtypeId AND IsMobile = 1)	--2015-11-05 9.7bug433 pos操作员可以直接删除不判断
	RETURN -3	

IF EXISTS( SELECT  Etypeid FROM dbo.PromoRule a INNER JOIN dbo.PromoRule_Detail_EConfig b ON a.ID = b.PromoRuleID WHERE   ETypeID =@szEtypeId)
OR EXISTS(SELECT  Etypeid FROM dbo.PriceRule a INNER JOIN dbo.PriceRule_Detail_EConfig b ON a.ID = b.PriceRuleID WHERE   ETypeID = @szEtypeId)
	RETURN -4 


DELETE loginuser WHERE etypeid=@szetypeid
IF @@rowcount=0 RETURN -1

DELETE LoginManageInfo WHERE Etypeid=@szetypeid
DELETE FROM loginuserCol WHERE etypeid = @szetypeid
DELETE etypemacandip WHERE Etypeid=@szetypeid--删除mac地址和硬盘号

-- 删除各多级权限范围相关记录
DELETE FROM PType_L WHERE ETypeID=@szEtypeId
DELETE FROM EType_L WHERE ETypeID=@szEtypeId
DELETE FROM KType_L WHERE ETypeID=@szEtypeId
DELETE FROM BType_L WHERE ETypeID=@szEtypeId
DELETE FROM AType_L WHERE ETypeID=@szEtypeId
DELETE FROM DType_L WHERE ETypeID=@szEtypeId
DELETE FROM SType_l WHERE ETypeID=@szEtypeId
DELETE FROM LoginUserTimeSet WHERE EtypeID=@szEtypeId
DELETE FROM OftenMenu WHERE ETypeID=@szEtypeId
DELETE FROM RetailConfig WHERE ETypeID=@szEtypeId
DELETE FROM nVipConfiscateConfig WHERE ETypeID=@szEtypeId
DELETE FROM nVipWashCarTimesConfig WHERE ETypeID=@szEtypeId
DELETE FROM LoginUserCol WHERE ETypeID=@szEtypeId

DECLARE @EID VARCHAR(50)
SELECT @EID=Eid FROM employee WHERE typeId=@szEtypeId

--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','LoginUser',@EID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ReNameDocFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_ReNameDocFile
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-12-19
	描述：文档管理系统文档共享
*/
CREATE PROCEDURE Gp_ReNameDocFile
(
	@id					int,				--文档id
	@etypeid			varchar(50),		--上传者id
	@pathid				varchar(50),		--路径id
	@newfilename		varchar(200),		--文件名称
	@filename1			varchar(50)			--文件类型
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT * FROM DocFile WHERE ID<>@id AND etypeid=@etypeid AND pathId=@pathid AND FullName=@newfilename+@filename1)
BEGIN
	RAISERROR('该文件夹下相同文件名的文档！',16,1)
	RETURN
END

UPDATE DocFile SET FullName=@newfilename+@filename1 WHERE ID=@id

IF @@ERROR<>0
	RAISERROR('重命名文档失败！',16,1)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RenameFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_RenameFolder]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-12-15
	描述：文件管理系统重命名文件夹
*/
CREATE PROCEDURE Gp_RenameFolder
(
	@FullName	[varchar](200),			--文件夹名称
	@ParId		[varchar](50),			--父目录id
	@CurrentLevel [int],				--当前层级
	@etypeid	[varchar](50)			--创建者id
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @leveal SMALLINT

--生成层级
SELECT  @leveal = leveal
FROM    DocFilePath
WHERE   typeid = @ParId

SELECT  @leveal = @leveal + 1

IF EXISTS (	SELECT	FullName 
			FROM	DocFilePath 
			WHERE	etypeid = @etypeid 
					AND FullName = @FullName
					AND leveal = @CurrentLevel + 1 
					AND LEFT(typeid,5) = LEFT(@ParId,5))
BEGIN
	RAISERROR('文件夹名称重复!请确认后重试!',16,1)
	RETURN
END
	
BEGIN TRAN insertproc
            
	update	DocFilePath 
	set		fullname= @FullName
	where	typeid = @ParId
	
IF @@rowcount = 0 
BEGIN
    ROLLBACK TRAN insertproc 
    RAISERROR('重命名文件夹发生错误!请确认后重试!',16,1)
END
COMMIT TRAN insertproc

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RepairAttemerUpdateBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_RepairAttemerUpdateBillIndex
GO


-- ========================================================================
-- 功能说明：		维修调度的派工明细
-- 最后修改：		毛欣蓉
-- 修改时间：		2011-05-12
-- ========================================================================
CREATE    PROCEDURE Gp_RepairAttemerUpdateBillIndex
(
	@BillNumberID		numeric(10,0),	-- 单据 ID 值
	@ItemPrincipal		varchar(50),	--项目负责人
	@MonitorPrincipal	varchar(50),	--监理负责人
	@completedate		DateTime,
	@billstate			int,
	@BTypeId			varchar(50),
	@AccidentAddr		varchar(1000),
	@AccidentReason		varchar(2000),
	@AccidentDate		DateTime,
	@FactCompleteDate	DateTime
)
--@encode$--
AS

	SET NOCOUNT ON
	IF @AccidentDate='9999-12-31 23:59:59.997'
		Set @AccidentDate=null
	IF @billstate<>3
		set @FactCompleteDate=null
	-- 写入数据表
	UPDATE BillIndex_CarRepair SET 
		ItemPrincipal=@ItemPrincipal ,
		MonitorPrincipal=@MonitorPrincipal,
		completedate=@completedate,
		billstate=@billstate,
		FactCompleteDate=@FactCompleteDate
	WHERE Billnumberid=@billnumberid
	
	UPDATE Qp_ReceptionBill_Insurance SET
		BTypeId = @BTypeId,
	    AccidentAddr = @AccidentAddr,
	    AccidentReason = @AccidentReason,
	    AccidentDate = @AccidentDate
	WHERE Billnumberid = @billnumberid
	    
	delete from Qp_ReceptionBill_RepairItems where billnumberid=@billnumberid
    delete from Qp_AttemperBill_RepairItemsPerson where billnumberid=@billnumberid 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RepairSelect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_RepairSelect]
GO













-------------------------------------------------------------------------
--维修接件单、受理单调入单据查询
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23

--修改作者：谢吉康
--修改日期：2004-08-17
--修改原因：没有判断是否有修改他人草稿的权限
-------------------------------------------------------------------------
CREATE                    PROCEDURE [Gp_RepairSelect]
(
	@QueryType 		VARCHAR(20),	--查询类型，engage表示查维修接件单，deal表示表示查维修受理单
	@IfCheck		VARCHAR(20),	--单据查询状态条件，=t表示查询已过帐的单据，=f表示查询草稿单据
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@RepairDate		VARCHAR(20),	--送修日期
	@ETypeID 		VARCHAR(25),	--指定要查询的制单人ID
	@ETypeID1		VARCHAR(25),	--指定要查询的接件人ID
	@BillCode		VARCHAR(200),	--单据编号
	@PTypeID		VARCHAR(25),	--产品编号
	@ETypeName1		VARCHAR(25),	--送修人
	@OperatorID 	VARCHAR(25)		--操作员ID号
)
--@encode$--
AS

SET NOCOUNT ON

--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @OperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------


DECLARE @SQL VARCHAR(8000)
DECLARE @SQL_WHERE VARCHAR(8000)
DECLARE @SQL_WHERE1 VARCHAR(8000)
--PRINT @chvMETypeID
IF @chvMETypeID<>'00001' OR @chvMETypeID<>'' OR @chvMETypeID<>'00000'
	BEGIN
		SET @SQL_WHERE =' AND R.EtypeID1 LIKE '+char(39)+@chvMETypeID+'%'+char(39)
		SET @SQL_WHERE1 =' AND A.EtypeID LIKE '+char(39)+@chvMETypeID+'%'+char(39)
	END
ELSE
	BEGIN
		SET @SQL_WHERE= ''
		SET @SQL_WHERE1= ''
	END
/*
IF @chvMKTypeID <>'' or @chvMKTypeID<>'00000'
BEGIN
	SET @SQL_WHERE1= @SQL_WHERE1 + ' AND (( A.KtypeID1 LIKE '+char(39)+@chvMKTypeID+'%'+char(39) + ' OR A.KtypeID1=''''' +')'
	SET @SQL_WHERE1= @SQL_WHERE1 + ' OR ( A.KtypeID2 LIKE '+char(39)+@chvMKTypeID+'%'+char(39) + ' OR A.KtypeID2=''''' +'))'
END
*/
IF @chvMKTypeID <>'' or @chvMKTypeID<>'00000'
	BEGIN
		SET @SQL_WHERE1 = @SQL_WHERE1 + ' AND ((A.KTypeId1 = '+char(39)+''+char(39)+' AND A.KTypeId2 LIKE '+char(39)+@chvMKTypeId+'%'+char(39)+') OR (A.KTypeId2 = '+char(39)+''+char(39)+' AND A.KTypeId1 LIKE '+char(39)+@chvMKTypeId+'%'+char(39)+') OR (A.KTypeId1 = '+char(39)+''+char(39)+' AND A.KTypeId2 = '+char(39)+''+char(39)+')  OR (A.KTypeId1 LIKE '+char(39)+@chvMKTypeID+'%'+char(39)+' OR A.KTypeId2 LIKE '+char(39)+@chvMKTypeID+'%'+char(39)+'))'
	END

SET @SQL_WHERE1= @SQL_WHERE1 + 'AND ( C.BtypeID LIKE '+char(39) + @chvMBTypeID +'%'+char(39)+ ' OR C.BtypeID LIKE '+char(39)+@chvMBTypeID2+'%'+char(39)+')'

DECLARE @offset int,		--是否有修改他人草稿的权限
		@re     int
SELECT 	@offset=135 							--检查某人是否有查看管辖职员草稿得权限
EXEC 	@re=GP_CheckLimit @OperatorID,@offset

IF LOWER(@QueryType)='engage'
	BEGIN
		SET @SQL='
		SELECT 
			r.BillNumberID,
			r.BillDate,
			r.RepairDate,
			r.BillCode,
			ISNULL(e.FullName,'''') AS ETypeName,
			ISNULL(e1.FullName,'''') AS ETypeName1,
			r.ETypeName1 AS RETypeName,
			ISNULL(p.UserCode,'''') AS PTypeUserCode,
			ISNULL(p.FullName,'''') AS PTypeName,
			ISNULL(r.Serial,'''') AS Serial,
			CASE r.stat
				WHEN 0 THEN ''等待受理''
				WHEN 1 THEN ''已受理''
				WHEN 2 THEN ''已取件''
			END AS stat
		FROM RepairEngage r
        Inner Join Ptype x On r.PtypeId=x.TypeId
		LEFT JOIN(
			SELECT TypeID,FullName FROM Employee
		)e ON e.TypeID=r.ETypeID
		LEFT JOIN(
			SELECT TypeID,FullName FROM Employee
		)e1 ON e1.TypeID=r.ETypeID1
		LEFT JOIN(
			SELECT TypeID,UserCode,FullName FROM PType
		)p ON p.TypeID=r.PTypeID
		WHERE 
			r.IfCheck=''' + @IfCheck + '''
			AND r.Stat IN (0,1,2)
			AND r.BillDate>=''' + @BillDateBegin + '''
			AND r.BillDate<=''' + @BillDateEnd + ''''
			+ @SQL_WHERE
		IF @RepairDate<>'' SET @SQL=@SQL + '
			AND r.RepairDate=''' + @RepairDate + ''''
		IF @ETypeID<>'' AND @ETypeID<>'00001' SET @SQL=@SQL + '
			AND r.ETypeID=''' + @ETypeID + ''''
		IF @ETypeID1<>'' AND @ETypeID1<>'00001' SET @SQL=@SQL + '
			AND r.ETypeID1=''' + @ETypeID1 + ''''
		IF @BillCode<>'' SET @SQL=@SQL + '
			AND r.BillCode LIKE ''' +'%'+ @BillCode + '%'''
		IF @PTypeID<>'' AND @PTypeID<>'00000' SET @SQL=@SQL + '
			AND ( (x.UserCode LIKE ''' + @PTypeID + '%'' ) Or   (x.TypeId LIKE ''' + @PTypeID + '%'' )  Or (x.FullName LIKE ''' + @PTypeID + '%'' )) ' 
		IF @ETypeName1<>'' SET @SQL=@SQL + '
			AND r.ETypeName1 LIKE ''%' + @ETypeName1 + '%'''
		-- 排序
		SELECT @SQL = @SQL +  ' ORDER BY R.BillDate DESC '
	END 



IF LOWER(@QueryType)='deal'
	BEGIN
		SET @SQL='
		SELECT 
			a.BillNumberId,
			c.BillDate,
			b.RepairDate,
			a.BillCode,
			b.ETypeName,
			b.ETypeName1,
			b.RETypeName,
			b.PTypeUserCode,
			b.PTypeName,
			b.Serial,
			CASE a.stat
				WHEN 1 THEN ''已受理''
				WHEN 2 THEN ''已取件''
			END AS stat
		FROM RepairDeal a,
		(
			SELECT 
				r.BillNumberID,
				r.BillDate,
				r.RepairDate,
				ISNULL(e.FullName,'''') AS ETypeName,
				ISNULL(e1.FullName,'''') AS ETypeName1,
				r.ETypeName1 AS RETypeName,
				ISNULL(p.UserCode,'''') AS PTypeUserCode,
				ISNULL(p.FullName,'''') AS PTypeName,
				ISNULL(r.Serial,'''') AS Serial
			FROM RepairEngage r
			LEFT JOIN(
				SELECT TypeID,FullName FROM Employee
			)e ON e.TypeID=r.ETypeID
			LEFT JOIN(
				SELECT TypeID,FullName FROM Employee
			)e1 ON e1.TypeID=r.ETypeID1
			LEFT JOIN(
				SELECT TypeID,UserCode,FullName FROM PType
			)p ON p.TypeID=r.PTypeID
			WHERE 1=1 '

		IF @RepairDate<>'' SET @SQL=@SQL + '
				AND r.RepairDate=''' + @RepairDate + ''''
		IF @ETypeID<>'' AND @ETypeID<>'00001' SET @SQL=@SQL + '
				AND r.ETypeID=''' + @ETypeID + ''''
		IF @ETypeID1<>'' AND @ETypeID1<>'00001' SET @SQL=@SQL + '
			AND r.ETypeID1=''' + @ETypeID1 + ''''

		IF @PTypeID<>'' AND @PTypeID<>'00000' SET @SQL=@SQL + '
				AND r.PTypeID LIKE ''' + @PTypeID + '%'''
		IF @ETypeName1<>'' SET @SQL=@SQL + '
				AND r.ETypeName1 LIKE ''%' + @ETypeName1 + '%'''
		SET @SQL=@SQL +'
		) b,Billindex c
		WHERE	a.IfCheck=''f'' 
				AND c.BillDate>='+char(39)+@BillDateBegin+char(39)+'
				AND c.BillDate<='+char(39)+@BillDateEnd+char(39)+'
				AND a.EngageBillID=b.BillNumberID -- modify by chen_qihua #01
				AND a.BillNumberID=c.BillNumberID
				and c.ifCheck =''f'''+@SQL_WHERE1
		IF @BillCode<>'' 
			SET @SQL=@SQL + 'AND a.BillCode LIKE ''' +'%'+ @BillCode + '%'''

		IF @re=1	--没有修改他人草稿的权限，则只能看自己做的草稿单据
			SELECT @SQL = @SQL + ' AND c.Checke='+char(39)+@OperatorID+char(39)
		-- 排序
		SELECT @SQL = @SQL +  ' ORDER BY c.BillDate DESC '

	END 


--print @SQL
EXEC(@SQL)
--EXECUTE Gp_RepairSelect 'engage','2003-1-1','2004-1-1','2003-12-29','00001','WJ','0000000091','w','00001'
--EXECUTE Gp_RepairSelect 'deal','2003-1-1','2004-1-1','','','','','','00001'















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_RepairSelectByID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_RepairSelectByID]
GO













-------------------------------------------------------------------------
--受理单调入单据数据
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23


--谢吉康 2004-03-12调整了格式
-------------------------------------------------------------------------
CREATE      PROCEDURE [GP_RepairSelectByID]
(
	@BillNumberID	INT,			--单据编号
	@OperatorID 	VARCHAR(25)		--操作员ID号
)
--@encode$--
AS

SET NOCOUNT ON

 --查询结果集合-----------------------------------------------------------------
 --录单日期 --单据编号 --前台接件人 --送修日期 --送修人 --联系电话
 --购买日期 --销售单号 --销售单位 --终端用户 --地址 --摘要 --商品名称
 --序列号 --配置情况 --送修属性 --商品附件 --故障描述 --备注
 --受理故障描述 --受理检测备注 --受理维修方法 --不收费 --理由
 --取件时间 --维修工程师 --检测划价人 --未取件已取件 --取件人身份证 
 --对应的接件单编号 --维修费用小计
 -------------------------------------------------------------------------------
SELECT	a.BillDate,
		a.BillCode,
		(SELECT ISNULL(FullName,'''') FROM Employee e WHERE e.TypeID = a.ETypeID1) AS ETypeName,
		a.RepairDate,
		ISNULL(a.ETypeName1,'') AS ETypeName_SXR,
		ISNULL(a.Tel,'') AS tel,a.BuyDate,
		ISNULL(a.SaleBillID,'') AS SaleBillID,
		ISNULL(a.SaleBTypeName,'') AS SaleBTypeName,
		ISNULL(a.Buyer,'') AS Buyer,
		ISNULL(a.Address,'') AS Address,
		ISNULL(a.Brief,'') AS Brief,
		(SELECT ISNULL(FullName,'''') FROM PType p WHERE p.TypeID = a.PTypeID) AS PTypeName,
		a.Serial,
		ISNULL(a.Config,'') AS Config,
		a.RepairType,
		ISNULL(a.Attach,'') AS Attach,
		ISNULL(a.Fault,'') AS Fault,
		ISNULL(a.Comment,'') AS Comment,
		ISNULL(b.Fault,'') AS Fault_Deal,
		ISNULL(b.Comment,'') AS Comment_Deal,
		b.Method,
		b.NotFree,
		ISNULL(b.FreeMemo,'') AS FreeMemo,
		b.PayDate,
		(SELECT ISNULL(FullName,'''') FROM Employee e WHERE e.TypeID = b.ETypeID1) AS ETypeName1,
		(SELECT ISNULL(FullName,'''') FROM Employee e WHERE e.TypeID = b.ETypeID2) AS ETypeName2,
		b.IfPay,
		b.IDCard,
		b.EngageBillID,
		b.MoneyRepair
FROM 
		RepairEngage a,
		RepairDeal b
WHERE
		a.BillNumberID=b.EngageBillID	
		AND b.BillNumberID=@BillNumberID


--EXECUTE GP_RepairSelectByID 1,'00001'












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RepairTalkBackQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_RepairTalkBackQuery]
GO


/****** Object:  StoredProcedure [dbo].[Gp_RepairTalkBackQuery]    Script Date: 06/22/2011 10:45:19 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		丁超
-- Create date: 2011-06-21  11:20
-- Description:	维修回访提醒查询
-- =============================================
CREATE PROCEDURE [dbo].[Gp_RepairTalkBackQuery] 
(
    @OperatorId		varchar(100),		--操作员ID
    @startDate  varchar(100),           --开始日期
    @endDate   varchar(100),            --结束日期
    @stypeid  varchar(100),             --分支机构ID
    @btypeid varchar(100),              --往来单位ID
    @ratypeid varchar(100)              --车辆ID
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON;
--------------------------------------------------------------权限排查------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限排查------------------------------------------------------
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #Ratype (TypeID varchar(50))

INSERT INTO #Btype select typeid from F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorId)                        --寰�鏉ュ崟浣嶆潈闄愰浂鏃惰〃
INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)                       --鍒嗘敮鏈烘瀯鏉冮檺闆舵椂琛?
INSERT INTO #Ratype select typeid from F_GetAllManagerBaseTypeId(@ratypeid,12,@OperatorId) 
--------------------------------------------------------------查询语句------------------------------------------------------
declare @SQL varchar(max)
declare @DayAdd int  --预计回访时间
select  @DayAdd=value from Userconfig where ConfigName='HFDay'

set @SQL='Select a.BillNumberId as wxbillnumberid,
                 a.BillCode,
                 a.billtype,
                 a.btypeid,
                 b.RATypeID,
                 b.BalanceDate,
                 b.IntendingTalkBackDate as IntendingTalkBackDate
          from BillIndex  a 
          inner join
	      Billindex_CarRepair 
          b  on a.BillNumberId=b.BillNumberId'  
SET @SQL = @SQL+' where convert(varchar(10),b.IntendingTalkBackDate,120) between '''+@startDate+''' and '''+@endDate+''''
SET @SQL = @SQL+' and  a.stypeid in ( select typeid from #Stype)' 
SET @SQL = @SQL+' and  a.btypeid in ( select typeid from #Btype)'
SET @SQL = @SQL+' and  b.RATypeID in( select typeid from #Ratype)'
SET @SQL = @SQL+' and  a.ifcheck=''t'' and a.billtype=195 and b.IsTalkBackOver=0 and redword=0'
SET @Sql=@Sql + ' AND  a.ifYearBill= 0 '    --年节存标志
SET @SQL = @SQL+' order by a.BillCode asc,b.IntendingTalkBackDate asc'

--print @SQL
exec(@SQL)
drop table #Btype
drop table #Stype
END


GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_RepairTalkBackUpdateQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_RepairTalkBackUpdateQuery]
GO

/****** Object:  StoredProcedure [dbo].[Gp_RepairTalkBackUpdateQuery]    Script Date: 06/24/2011 16:01:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011-06-24 11:03
-- Description:	维修回访单调入草稿后查询数据
-- =============================================
CREATE PROCEDURE [dbo].[Gp_RepairTalkBackUpdateQuery]
(
	@billnumberid as numeric(18, 0) --单据ID
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON;
declare @SQL as varchar(max)
SET @SQL='select isnull(a.btypeid,'''') as btypeid,
				 a.BillNumberId  as billnumberid,
				 a.BillType as billtype,
				 isnull(a.checke,'''')  as makebillid,  
				 isnull(a.BillDate,'''')  as billdate,
			     a.BillCode as billcode,
				 isnull(a.explain,'''') as explain,
			     isnull(a.Comment,'''') as comment,
			     isnull(a.frombillnumberid,'''') as frombillnumberid,
			     a2.BillCode as rtypeid,
			     isnull(b.RATypeID,'''') as ratypeid,
			     isnull(b.BalanceDate,'''') as balancedate,
			     isnull(c.RepairContentmentDegree,'''') as repaircontentmentdegree,
			     isnull(c.CompContentmentDegree,'''') as compcontentmentdegree,     
                 isnull(c.CustomerQuestion,'''') as customerquestion,
                 isnull(c.DealResult,'''') as dealresult,
                 isnull(c.Comment,'''') as talkbackcomment,
				 isnull(d.FullName,'''')  as checke,    
                 isnull(a.etypeid,'''')  as etypeid,
                 isnull(d2.FullName,'''')  as efullname,
                 isnull(e.TypeId,'''') as stypeid,
                 isnull(e.FullName,'''') as sfullname,
                 isnull(f.typeid,'''') as dtypeid,
                 isnull(f.FullName,'''') as dfullname,
                 isnull(g.fullname,'''') as bfullname,
                 isnull(h.platenumber,'''') as rafullname
         from BillIndex a
         inner join
              Billindex_CarRepair b
              on a.BillNumberId=b.BillNumberId
         inner join
              Qp_IntendingTalkBack_Bill c
              on a.BillNumberId=c.BillNumberId 
         inner join
              employee d
              on a.checke=d.typeId
         inner join
              employee d2
              on a.etypeid=d2.typeId
         inner join
              stype e
              on a.Stypeid=e.TypeId
         inner join
              Department f
              on a.DTypeId=f.typeid
         inner join
              btype g
              on a.btypeid=g.typeid
         inner join
              QP_RepairAutoInfo h
              on b.ratypeid=h.typeid
         inner join
              BillIndex  a2
              on a.FromBillNumberId=a2.BillNumberID 
         where a.BillNumberId='+cast(@billnumberid as varchar(max))
print @SQL
exec(@SQL)
    
END

GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ReplaceSchemeDetailValue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_ReplaceSchemeDetailValue]
GO

/*
	作者：谢吉康
	日期：2012-02-16
	描述：处理查询方案的保存值
	EXEC Gp_ReplaceSchemeDetailValue '0000100004',''
*/

CREATE PROCEDURE Gp_ReplaceSchemeDetailValue
(
	@RpValue	VARCHAR(MAX),		--替换的值
	@SqlWhere	VARCHAR(MAX) = '',	--附加条件
	@SrTypeId   VARCHAR(MAX) = '',	--原来的数据
	@DeTypeId	VARCHAR(MAX) = ''	--目标数据
) 
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'DECLARE @Result TABLE
			(
				nid				INT IDENTITY(1,1),
				srid			INT,
				DataValue		VARCHAR(MAX),
				NewDataValue	VARCHAR(MAX)
			)

			DECLARE @i			INT,
					@rowCount	INT,
					@DataValue	VARCHAR(MAX)
					
			SET @i = 1		

			INSERT INTO @Result(srid,DataValue,NewDataValue) 
			SELECT	nId,DataValue,'''' 
			FROM	SchemeDetail 
			WHERE	ControlType = ''XWSelectorEdit'' 
					AND ISNULL(DataValue,'''')<>''''
					'+@SqlWhere+'

			SET @rowCount = @@ROWCOUNT

			WHILE @i <= @rowCount
			BEGIN
				SELECT @DataValue = DataValue FROM @Result WHERE nid = @i '

--数据搬移				
IF @SrTypeId <> '' AND @DeTypeId <> ''
	SET @SQL+= '	UPDATE	@Result 
					SET		NewDataValue = DBO.F_GetValidUserDataId(REPLACE(@DataValue,'''+@SrTypeId+''','''+@DeTypeId+'''))
					WHERE   nid = @i '
--删除全部操作员权限
ELSE IF @RpValue='00000'
   SET @SQL+= '	UPDATE	@Result 
					SET		NewDataValue = ''''
					WHERE   nid = @i '
ELSE			
	SET @SQL+= '	UPDATE	@Result 
					SET		NewDataValue = DBO.F_ReplaceSchemeDataValue(@DataValue,'''+@RpValue+''')
					WHERE   nid = @i '
				
SET @SQL+= '	SET @i += 1
			END

			UPDATE  SchemeDetail
			SET		DataValue = R.NewDataValue
			FROM    SchemeDetail S,
					@Result R
			WHERE	R.srid = S.nId '
			
--PRINT(@SQL)			
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ResetAlertSave]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_ResetAlertSave]
GO









-- ========================================================================
-- 功能说明：	  订单恢复报警
-- 最后修改作者：  cqhua
-- 最后修改时间：  2005-08-19

-- ========================================================================
CREATE             PROCEDURE [GP_ResetAlertSave]
(
@intBillNumberID int
)
--@encode$--
AS
SET NOCOUNT ON


--select * from orderindex 

Update Orderindex Set CanAlert='1',DelayType='0',DelayValue='0' WHERE BillnumberID=@intBillNumberID

-- Select * from orderindex


RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_RetailBillConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_RetailBillConfig]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO














-- ===================================================================================
-- 功能说明：		根据相应的操作员，配置零售单相关信息 ( 往来单位、仓库、账户 )
-- 编写作者：		卢春
-- 最后修改时间：	2003-04-10

-- 修改作者：谢吉康
-- 修改日期：2004-04-23
-- 修改描述：当改变操作员的权限范围的到时候没有更新RetailConfig中的ATypeID字段

-- 修改作者：徐辉
-- 修改日期：2004-05-19
-- 修改描述：增加权限限制
-- 修改标志：#-01
-- ===================================================================================
CREATE                   PROCEDURE GP_RetailBillConfig
(
	@chvFlag		varchar(1),		    -- 操作标识。1：读取配置信息；2：新增或更新配置信息
	@chvOperatorID	varchar(50),		-- 操作员 ID 值
	@chvBTypeID		varchar(100) = '',	-- 往来单位 ID 值
	@chvKTypeID		varchar(100) = '',	-- 仓库 ID 值
	@chvATypeID		varchar(100) = '',	-- 账户 ID 值
	@chvETypeID		varchar(100) = ''	-- 经手人ID 值
)
--@encode$--
AS
	SET NOCOUNT ON
	-- 读取配置信息
IF @chvOperatorID IS null RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
	DECLARE @intRe int, 
	@chvMAtypeid varchar(50), 
	@chvMBtypeid varchar(50), 
	@chvMBtypeid2 varchar(50), 
	@chvMEtypeid varchar(50), 
	@chvMKtypeid varchar(50), 
	@chvMPtypeid varchar(50), 
	@chvMExpense varchar(50), 
	@chvMIncome varchar(50),
	@chvMCapital varchar(50),
	@chvMDtypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMAtypeid output, @chvMBtypeid output, @chvMBtypeid2 output, @chvMEtypeid output, @chvMKtypeid output, @chvMPtypeid output, @chvMExpense output, @chvMIncome output,@chvMCapital output,@chvMDtypeid output
IF @intRe <> 0 RETURN @intRe

	IF @chvFlag = '1'
		BEGIN
									
			SELECT	BFullName = (	-- 往来单位名称
					SELECT	FullName
					FROM	BType
					WHERE	TypeID = a.BTypeID  AND deleted=0
				),
				discount = (
					SELECT	salezekou
					FROM	BType
					WHERE	TypeID = a.BTypeID AND deleted=0
				),
				pricetype = (
					SELECT	price
					FROM	BType
					WHERE	TypeID = a.BTypeID  AND deleted=0
				),
				KFullName = (	-- 仓库名称
					SELECT	FullName
					FROM	Stock
					WHERE	TypeID = a.KTypeID AND deleted=0
				),
				sFullName = (	-- 仓库分支机构
					SELECT	FullName
					FROM	SType
					WHERE	TypeID = (SELECT stypeid FROM Stock WHERE TypeId=a.KTypeID)
				),
				stypeid = (	-- 仓库分支机构Id
					SELECT	stypeid
					FROM	Stock
					WHERE	TypeID = a.KTypeID  AND deleted=0
				),
				AFullName = (	-- 账户名称
					SELECT	FullName
					FROM	Ac_Items
					WHERE	nid = a.ATypeID  AND deleted=0
				),
				EFullName = (	-- 经手人名称
					SELECT	FullName
					FROM	Employee
					WHERE	TypeID = a.ETypeID  AND deleted=0
				),
				dFullName = (	-- 经手人部门
					SELECT	d.fullname
					FROM	Department d
					LEFT JOIN Employee e ON d.typeid = e.dtypeid
					WHERE   e.TypeID = a.ETypeID
						AND d.deleted=0
				),
				dtypeid = (	-- 经手人部门
					SELECT	d.typeid
					FROM	Department d
					LEFT JOIN Employee e ON d.typeid = e.dtypeid
					WHERE   e.TypeID = a.ETypeID
						AND d.deleted=0
				),
				a.BTypeID,
				a.KTypeID,
				a.ATypeID,
				a.EtypeId,
				b.Cid,
				rate = (
					SELECT	c.Rate
					FROM	Ac_Currency c
					WHERE	c.CId = b.CID
				),
				cidissysrow = (
					SELECT	c.Sysrow
					FROM	Ac_Currency c
					WHERE	c.CId = b.CID
				)
			FROM	RetailConfig a
			left join btype b on b.typeId = a.BTypeID
			WHERE	LoginUserId = @chvOperatorID
				and a.BtypeID IN(SELECT typeid FROM F_GetManDetailBtype(@chvOperatorID)) --#-01
				and a.KTypeID IN(SELECT typeid FROM F_GetManDetailKtype(@chvOperatorID))		--#-01
				and (a.ATypeID IN(SELECT nid FROM F_LINEA(@chvOperatorID)) Or a.AtypeId IS null or a.AtypeId = '' OR a.ATypeID=0 or a.ATypeID='39' or a.ATypeID='34' OR a.ATypeID='-99999')		--#-01
				and a.EtypeId IN(SELECT typeid FROM F_GetManDetailEtype(@chvOperatorID))		--#-01
		END
	-- 新增 或 更新配置信息
	ELSE
		BEGIN
			-- 是否存在此操作员的零售单配置信息，1：存在；0：不存在
			DECLARE @chrIfExitInfo int
			SELECT @chrIfExitInfo =
				CASE
					WHEN EXISTS( SELECT TOP 1 * FROM RetailConfig WHERE LoginUserId = @chvOperatorID ) THEN 1
					ELSE 0
					END

			IF @chrIfExitInfo = 1
				BEGIN
					-- 当有此操作员配置信息时，更改记录
					UPDATE	RetailConfig
					SET	BTypeID = @chvBTypeID,
						KTypeID = @chvKTypeID,
						ATypeID = CASE WHEN @chvATypeID = '34' THEN '' ELSE @chvATypeID END,
						ETypeID = @chvETypeID
					WHERE	LoginUserId = @chvOperatorID

					-- 操作返回值
					IF @@ROWCOUNT = 0
						BEGIN
							--RAISERROR('更新零售单配置信息失败！',16,1)
							RETURN -1
						END
				END
			ELSE
				BEGIN
					-- 当无此操作员的配置信息时，新增记录
					INSERT INTO RetailConfig (
						LoginUserId,
						ETypeID,
						BTypeID,
						KTypeID,
						ATypeID
					)
					VALUES (
						@chvOperatorID,
						@chvETypeID,
						@chvBTypeID,
						@chvKTypeID,
						CASE WHEN @chvATypeID = '34' THEN '' ELSE @chvATypeID END
					)

					-- 操作返回值
					IF @@ROWCOUNT = 0
						BEGIN
							--RAISERROR('新增零售单配置信息失败！',16,1)

							RETURN -2
						END
				END
		END














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ReturnAssetsCardHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_ReturnAssetsCardHistory
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/07/2 
	Description	:	固定资产卡片红冲或删除对折旧表历史表的操作
*/
CREATE PROCEDURE Gp_ReturnAssetsCardHistory
(
	@StypeID			varchar(50),
	@CardID				INT,    				--卡片ID
	@billtype			INT,					--单据对应billname表的id，0是初始化,减值准备是-1，部门转移是-2,折旧方式变更是-3,月结是-4
	@billnumberid		NUMERIC(18,0)           --单据蓝单id 或 变更单id
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Fyear INT,@Fperiod INT,@billDate DATETIME
--@VeriryStypeid VARCHAR(50)
--SELECT @VeriryStypeid=VerifyID FROM dbo.SType WHERE TypeId=@StypeID 

----获取指定分支机构当前年度,财务期间	
--IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @VeriryStypeid)
--	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @VeriryStypeid
--ELSE 
--	BEGIN
--		SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName='fyear'
--		SELECT @FPeriod=SubValue FROM dbo.sysdata WHERE SubName='fperiod'
--	END

--按照单据日期来取期间
SELECT @billDate=BillDate FROM dbo.BillIndex WHERE BillNumberId=@billnumberid
SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_Period WHERE @billDate>=FBegin AND @billDate<=FEnd


IF @billtype=212  --增加单
	BEGIN
		--修改卡片状态
		UPDATE dbo.Ac_AssetsCards SET AssetsState=2 WHERE Id=@CardID --未入账
		
		--删除折旧表
		DELETE FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID
		
		--删除历史记录
		DELETE FROM dbo.Ac_AssetsCards_History WHERE AssertsCardId=@CardID AND BillType=212 
	END

IF @billtype=214  --折旧单 
	BEGIN
		DECLARE @DepreciationMean INT
		SELECT @DepreciationMean=DepreciationMean FROM Ac_AssetsCards WHERE ID=@CardID
		
		IF @DepreciationMean<>1 AND @DepreciationMean <> 5  --不是手工折旧的卡片
			--折旧表当期改为未折旧,清空billnumberid
			UPDATE dbo.Ac_DepreciationPlan SET BillNumberId=0,PlanState=0 
			WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@Fyear AND fperiod=@Fperiod
		ELSE 
			DELETE dbo.Ac_DepreciationPlan WHERE BillNumberId=@billnumberid AND AssetCardId=@CardID AND PlanType=1 AND FYear=@Fyear AND fperiod=@Fperiod
		
		--累计折旧数改回来
		UPDATE ac SET NetValue=NetValue+d.Depreciation,DepTotal=DepTotal-d.Depreciation,ac.DepreciationMonth=ac.DepreciationMonth-1,ac.FinishWork = ac.FinishWork - d.WorkTime
		FROM dbo.Ac_AssetsCards ac
		JOIN  dbo.DepBill d ON ac.Id=d.AssetCardId AND d.BillNumberId=@billnumberid
		WHERE ac.Id=@CardID
		
		IF @DepreciationMean<>1  AND @DepreciationMean <> 5 --不是手工折旧的卡片
			BEGIN
				IF @Fperiod=12
					UPDATE dbo.Ac_DepreciationPlan SET PlanState=0 
					WHERE AssetCardId=@CardID  AND PlanType=0 AND FYear=@Fyear 
			END
		ELSE 
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@Fyear)
					DELETE FROM Ac_DepreciationPlan WHERE  AssetCardId=@CardID AND PlanType=0 AND FYear=@Fyear 
				ELSE   --修改年折旧 
					UPDATE ap SET  ap.DepTotal=dbo.F_RoundTotal(ac.DepTotal), 
						   ap.Depreciation=dbo.F_RoundTotal((SELECT SUM(Depreciation) FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND FYear=@Fyear AND PlanType=1 GROUP BY FYear )),
						   ap.NetValue=dbo.F_RoundTotal(ac.NetValue),
						   ap.FPeriod=(SELECT COUNT(*) FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND FYear=@Fyear AND PlanType=1 GROUP BY FYear )
						   ,ap.FinishWork = ac.FinishWork
					FROM Ac_DepreciationPlan ap 
					JOIN dbo.Ac_AssetsCards ac ON ap.AssetCardId=ac.Id 
					WHERE  AssetCardId=@CardID AND PlanType=0 AND FYear=@Fyear 
			END
				
		--修改卡片状态，只有第一期折旧单红冲后才修改卡片状态，改为已入账(从历史表中看该卡片当期以前是否还有折旧)
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards_History ah WHERE id<(SELECT Id FROM dbo.Ac_AssetsCards_History WHERE AssertsCardId=@CardID AND BillType=214 AND BillId=@billnumberid) AND ah.AssertsCardId=@CardID AND ah.BillType=214)  --不存在折旧单
		   UPDATE dbo.Ac_AssetsCards SET AssetsState=3 WHERE Id=@CardID --已入账
		   
		--删除历史记录
		DELETE FROM dbo.Ac_AssetsCards_History WHERE AssertsCardId=@CardID AND BillType=214 AND BillId=@billnumberid
	END
IF @billtype=213     --减少单，折旧计划表状态改变,planstate=2的全部还原
	BEGIN
		--修改卡片状态
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards_History ah WHERE id<(SELECT Id FROM dbo.Ac_AssetsCards_History WHERE AssertsCardId=@CardID AND BillType=213 AND BillId=@billnumberid) AND ah.AssertsCardId=@CardID AND ah.BillType=214)  --不存在折旧单
		   UPDATE dbo.Ac_AssetsCards SET AssetsState=3 WHERE Id=@CardID --已入账
		ELSE 
			UPDATE dbo.Ac_AssetsCards SET AssetsState=4 WHERE Id=@CardID --已计提
			
		--折旧表
		UPDATE dbo.Ac_DepreciationPlan SET PlanState=0 WHERE AssetCardId=@CardID AND PlanState=2
		DELETE FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=3    --删除“清理”状态的数据
		
		--重算折旧表
		IF @Fperiod!=12
			BEGIN
				UPDATE ad SET ad.Depreciation=dbo.F_RoundTotal(t.Depreciation),ad.Fperiod=t.fperiod,
							  ad.NetValue=dbo.F_RoundTotal(ad1.NetValue),ad.DepTotal=dbo.F_RoundTotal(ad1.DepTotal) 
				FROM dbo.Ac_DepreciationPlan ad JOIN
				(
					---当年已经计提的期数
					SELECT AssetCardId,SUM(Depreciation) AS Depreciation,COUNT(*) AS fperiod,MAX(MonthOrder) AS MonthOrder
					FROM Ac_DepreciationPlan 
					WHERE PlanType=1 AND FYear=@Fyear AND AssetCardId=@CardID --AND PlanState=1--算的是所有
					GROUP BY AssetCardId,FYear	
				) t ON ad.AssetCardId=t.AssetCardId 
				JOIN Ac_DepreciationPlan ad1 ON ad1.AssetCardId=t.AssetCardId AND ad1.PlanType=1 AND ad1.MonthOrder=t.MonthOrder
				WHERE ad.AssetCardId=@CardID AND ad.PlanType=0 AND ad.FYear=@Fyear
			END
			
		--删除历史记录
		DELETE FROM  dbo.Ac_AssetsCards_History WHERE AssertsCardId=@CardID AND BillType=213 
	END
	 
	 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReturnMsg_LackQty]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_ReturnMsg_LackQty]
GO




/*

功能说明：		库存不足(非手工指定法)

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_ReturnMsg_LackQty]
(
	@intRe					INT,					--过账返回的出错代号
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
)
--@encode$--        
AS

/*
INSERT #AuditReturnResult(PFullName,KFullName,PTypeID,KTypeID,BillQty,Qty)
SELECT PFullName,KFullName,PTypeID,KTypeID,BillQty,Qty
FROM #AuditGetResult
*/


INSERT #AuditReturnResult(PTypeID,KTypeID,BillQty,Qty)
SELECT PTypeID,KTypeID,BillQty,Qty
FROM #AuditGetResult


GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReturnMsg_LackSerial]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_ReturnMsg_LackSerial]
GO




/*

功能说明：		序列号不在库

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_ReturnMsg_LackSerial]
(
	@intRe					INT,					--过账返回的出错代号
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
)
--@encode$--        
AS

IF @intBillType NOT IN (11,305,17,21,187,140)
	RETURN

IF @intRe<>-907 RETURN

DECLARE
	@strTableName	VARCHAR(100)
	
SELECT @strTableName=TableName
FROM f_AllBillType()
WHERE BillType=@intBillType	

IF @strTableName='' RETURN

DECLARE
	@strSql			VARCHAR(MAX)
	

ALTER TABLE #AuditReturnResult ADD Serial VARCHAR(1000),PTypeID VARCHAR(50),KTypeID VARCHAR(50),PFullName VARCHAR(200)

ALTER TABLE #AuditReturnResult DROP COLUMN NORETURNTABLE

/*
DECLARE Serial_cursor CURSOR FOR 
SELECT Serial
FROM @strTableName a
INNER JOIN PType b
ON a.PTypeID=b.TypeID
WHERE a.BillNumberID=@intBillNumberID
AND b.IfSerial=1
AND CAST(a.Serial AS VARCHAR(50))<>''

OPEN Serial_cursor

FETCH NEXT FROM Serial_cursor 
INTO @Serial

WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT @Serial=SUBSTRING(@Serial,2,len(@Serial)-2)

	SELECT @Serial=REPLACE(@Serial,'я',CHAR(39)+','+CHAR(39))

	SELECT @Serial=CHAR(39)+@Serial+CHAR(39)

	SELECT @Serial='SELECT '+REPLACE(@Serial,',',' UNION ALL SELECT ')
	
	SELECT @Serial='SELECT NULL AS Serial UNION '+@Serial
	
	SELECT @strSql='
	INSERT #AuditReturnResult
	SELECT a.Serial FROM 
	('+@Serial+'
	) a
	WHERE NOT EXISTS
	(
		SELECT * FROM gp_CruPtypeSerial b
		WHERE a.Serial=b.Serial AND b.State=1
	)'
	
	EXEC(@strSql)

    FETCH NEXT FROM Serial_cursor INTO @Serial
END
CLOSE Serial_cursor
DEALLOCATE Serial_cursor

EXEC(@strSql)
*/

DECLARE
	@strKTypeID		VARCHAR(50)

IF @intBillType IN (17,21,305)
BEGIN
	SELECT @strKTypeID=KTypeID
	FROM BillIndex
	WHERE BillNumberId=@intBillNumberID
END

SELECT @strSql='
DECLARE
	@Serial			VARCHAR(MAX),
	@PTypeID		VARCHAR(50),
	@KTypeID		VARCHAR(50),
	@PFullName		VARCHAR(200),
	@strTempSql		VARCHAR(MAX)

DECLARE Serial_cursor CURSOR FOR 
SELECT a.Serial,a.PTypeID,'

IF @intBillType NOT IN (17,21,305)
BEGIN
	SELECT @strSql=@strSql+'a.KTypeID,'
END
ELSE
BEGIN
	SELECT @strSql=@strSql+CHAR(39)+@strKTypeID+CHAR(39)+','
END

SET @strSql=@strSql+'b.FullName
FROM '+@strTableName+' a
INNER JOIN PType b
ON a.PTypeID=b.TypeID
WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
AND b.IfSerial=1
AND CAST(a.Serial AS VARCHAR(50))<>''''

OPEN Serial_cursor

FETCH NEXT FROM Serial_cursor 
INTO @Serial,@PTypeID,@KTypeID,@PFullName

WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT @Serial=SUBSTRING(@Serial,2,len(@Serial)-2)

	SELECT @Serial=REPLACE(@Serial,''я'',CHAR(39)+'',''+CHAR(39))

	SELECT @Serial=CHAR(39)+@Serial+CHAR(39)

	SELECT @Serial=''SELECT ''+REPLACE(@Serial,'','','' UNION ALL SELECT '')
	
	SELECT @Serial=''SELECT NULL AS Serial UNION ''+@Serial
	
	SELECT @strTempSql=''
	INSERT #AuditReturnResult
	SELECT a.Serial,''+CHAR(39)+@PTypeID+CHAR(39)+'',''+CHAR(39)+@KTypeID+CHAR(39)+'',''+CHAR(39)+@PFullName+CHAR(39)+''
	FROM 
	(''+@Serial+''
	) a
	WHERE a.Serial IS NOT NULL AND NOT EXISTS
	(
		SELECT a.Serial FROM gp_CruPtypeSerial b
		WHERE a.Serial=b.Serial AND b.State IN (1,7)
	)''
	
	EXEC(@strTempSql)

    FETCH NEXT FROM Serial_cursor INTO @Serial,@PTypeID,@KTypeID,@PFullName
END
CLOSE Serial_cursor
DEALLOCATE Serial_cursor

'
EXEC(@strSql)


--PRINT @strSql



GO

/*

DECLARE
	@intRe					INT,					--过账返回的出错代号
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
	
SELECT
	@intRe=-907,
	@intBillType=11,
	@intBillNumberID=14	

EXEC GP_ReturnMsg_LackSerial
	@intRe,
	@intBillType,
	@intBillNumberID


*/



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReturnMsg_SerialCount]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_ReturnMsg_SerialCount]
GO




/*

功能说明：		序列号个数不一致

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_ReturnMsg_SerialCount]
(
	@intRe					INT,					--过账返回的出错代号
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
)
--@encode$--        
AS

IF @intBillType NOT IN (11,305,17,21,187)
	RETURN
	
IF @intRe<>-904 RETURN	

DECLARE
	@strTableName	VARCHAR(100)
	
SELECT @strTableName=TableName
FROM f_AllBillType()
WHERE BillType=@intBillType	

IF @strTableName='' RETURN

DECLARE
	@strSql			VARCHAR(8000)

ALTER TABLE #AuditReturnResult ADD PTypeID VARCHAR(50),KTypeID VARCHAR(50),PFullName VARCHAR(200),SerialQty  NUMERIC(24, 10) ,BillQty  NUMERIC(24, 10) 

ALTER TABLE #AuditReturnResult DROP COLUMN NORETURNTABLE

DECLARE
	@strTempKTypeID		VARCHAR(50)
	
IF @intBillType=305
BEGIN
	SELECT @strTempKTypeID=KTypeID
	FROM BillIndex
	WHERE BillNumberId=@intBillNumberID
END


SELECT @strSql='
INSERT #AuditReturnResult
SELECT a.PTypeID,'

IF @intBillType=305
BEGIN
	SELECT @strSql=@strSql+CHAR(39)+@strTempKTypeID+CHAR(39)
END
ELSE
BEGIN
	SELECT @strSql=@strSql+'a.KTypeID'
END

SELECT @strSql=@strSql+',b.FullName AS PFullName,dbo.FN_GetAllCharCount('+CHAR(39)+'я'+CHAR(39)+',a.Serial)-1 AS SerialQty,a.Qty AS BillQty
FROM '+@strTableName+' a
INNER JOIN PType b
ON a.PtypeId=b.typeId
WHERE a.BillNumberID='+CAST(@intBillNumberID AS VARCHAR(100))+'
AND dbo.FN_GetAllCharCount('+CHAR(39)+'я'+CHAR(39)+',a.Serial)-1<>a.Qty
AND b.IfSerial=1
'


--PRINT @strSql

EXEC(@strSql)

GO

/*

DECLARE
	@intRe					INT,					--过账返回的出错代号
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
	
SELECT
	@intRe=-904,
	@intBillType=11,
	@intBillNumberID=15


EXEC	GP_ReturnMsg_SerialCount
	@intRe,
	@intBillType,
	@intBillNumberID



*/



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ReturnMsg_StockLack]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_ReturnMsg_StockLack]
GO




/*

功能说明：		库存不足

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_ReturnMsg_StockLack]
(
	@intRe					INT,					--过账返回的出错代号(-1表示库存不足;序列号部分还在做)
	@intBillType			INT,					
	@intBillNumberID		numeric(10,0)
)
--@encode$--        
AS


IF @intBillType NOT IN (11,305,17,21,187,140)
	RETURN

/*
ALTER TABLE #AuditReturnResult
ADD PFullName	VARCHAR(200),KFullName VARCHAR(200),PTypeID VARCHAR(50),KTypeID VARCHAR(50),
BillQty  NUMERIC(24, 10) ,Qty  NUMERIC(24, 10) 
*/

ALTER TABLE #AuditReturnResult
ADD PTypeID VARCHAR(50),KTypeID VARCHAR(50),
BillQty  NUMERIC(24, 10) ,Qty  NUMERIC(24, 10) 


ALTER TABLE #AuditReturnResult DROP COLUMN NORETURNTABLE


EXEC GP_ReturnMsg_LackQty
	@intRe,
	@intBillType,
	@intBillNumberID


GO





IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[GP_RWXZTSelect]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[GP_RWXZTSelect]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[GP_RWXZTSelect] 
(
	@zttablename as varchar(100)
)
AS
BEGIN
	DECLARE		@I		INT=1,
				@J		INT=0,
				@SQL	NVARCHAR(1000)='',
				@DBName	VARCHAR(100)='',
				@NidStr	VARCHAR(2000)=''

	CREATE TABLE #SystemTaleb
	(
		NId		INT IDENTITY(1,1),
		[Name]	VARCHAR(100) NOT NULL,
		[dbid]	VARCHAR(100) NOT NULL
	)
	INSERT INTO #SystemTaleb(Name,dbid)
	SELECT [name],dbid FROM master..sysdatabases WHERE [name] NOT IN ('master','tempdb','model','msdb','SysDataDB') AND [name] NOT LIKE '%ReportServer%'	
	SELECT @J=@@ROWCOUNT
	
	WHILE(@I<=@J)
		BEGIN
			BEGIN TRY
				SELECT @DBName=Name FROM #SystemTaleb WHERE NId=@I
				SET @SQL='USE ['+@DBName+'] IF (SELECT ObjectProperty(Object_ID( '''+@zttablename+'''),''IsUserTable''))=1
	SET @NidStr+='','+CAST(@I AS VARCHAR(5))+''''+CHAR(13)
				EXEC sp_executesql @SQL,N'@NidStr VARCHAR(2000) OUT',@NidStr OUT
			END TRY
			BEGIN CATCH
				PRINT ''
			END CATCH
			
			SET @I+=1
		END	

	IF(ISNULL(@NidStr,'')<>'')
		BEGIN
			SET @SQL='SELECT [Name],[dbid] FROM #SystemTaleb WHERE NId IN('+SUBSTRING(@NidStr,2,LEN(@NidStr))+')' 
			EXEC(@SQL)
		END
	ELSE 
		SELECT '' [Name],'' [dbid]
	
	DROP TABLE #SystemTaleb
END	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaleBill_CostSale]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_SaleBill_CostSale]
GO



/*

功能说明：      成本价处理

作    者：       冯波

创建日期：       2011-1-26

返回结果： 

备注：		
		
*/

CREATE PROCEDURE [GP_SaleBill_CostSale]
(
	@nBillID			NUMERIC(10,0)				--单据ID
)
--@encode$--        
AS

DECLARE
	@intMoneyDot				INT,						--金额的小数位数
	@intPriceDot				INT						--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4


--如果属于按成本价销售，那么需要用成本均价来回写销售价
DECLARE @intCostSale INT			--0表示不按成本销售，1表示按成本销售

SELECT @intCostSale=CostSale FROM BillIndex WHERE BillNumberId=@nBillID

IF @intCostSale=1
BEGIN
	--按成本价销售（用成本均价回写销售价，需要注意的是在有外币的时候该如何回写）
	UPDATE SaleBill
	SET DisCountPrice=ROUND(a.CostPrice,@intPriceDot)
	FROM 
	(
		SELECT ID,CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(ROUND(CostTotal,@intMoneyDot)) AS  NUMERIC(24, 10) )/CAST(SUM(Qty) AS  NUMERIC(24, 10) ),@intPriceDot) END AS CostPrice
		FROM InoutStockTable 
		WHERE BillNumberID=@nBillID GROUP BY ID
	) a
	WHERE SaleBill.ID=a.ID AND SaleBill.BillNumberID=@nBillID


	UPDATE SaleBill
	SET SalePrice=CASE Discount WHEN 0 THEN 0 ELSE ROUND(ISNULL(DisCountPrice/Discount,0),@intPriceDot) END,
	TaxPrice=CASE Discount WHEN 0 THEN 0 ELSE ROUND(ISNULL(DisCountPrice*(1+Tax/100),0),@intPriceDot) END
	WHERE BillNumberID=@nBillID
	

	UPDATE SaleBill
	SET SaleTotal=ROUND(ISNULL(SalePrice*Qty,0),@intMoneyDot),Total=ROUND(ISNULL(DisCountPrice*Qty,0),@intMoneyDot),
	TaxTotal=ROUND(ISNULL(TaxPrice*Qty,0),@intMoneyDot)
	WHERE BillNumberID=@nBillID

	--修改表头金额（TaxTotal,TotalDiscount,TotalTax）
	UPDATE BillIndex
	SET totalinmoney=ROUND(ISNULL(b.TaxTotal,0),@intMoneyDot)
	FROM 
	(
		SELECT BillNumberID,ROUND(SUM(ROUND(TaxTotal,@intMoneyDot)),@intMoneyDot) AS TaxTotal
		FROM SaleBill 
		WHERE BillNumberID=@nBillID
		GROUP BY BillNumberID
	) b
	WHERE BillIndex.BillNumberId=@nBillID AND BillIndex.BillNumberId=b.BillNumberID


	--处理InoutStockTable
	UPDATE InoutStockTable
	SET SalePrice=b.SalePrice,SaleTotal=ROUND(InoutStockTable.Qty*ROUND(b.SalePrice,@intPriceDot),@intMoneyDot),DisCount=b.DisCount,
	Price=b.DisCountPrice,Total=ROUND(InoutStockTable.Qty*ROUND(b.DisCountPrice,@intPriceDot),@intMoneyDot),
	Tax=b.Tax,TaxPrice=b.TaxPrice,TaxTotal=ROUND(InoutStockTable.Qty*ROUND(b.TaxPrice,@intPriceDot),@intMoneyDot)
	FROM SaleBill b
	WHERE InoutStockTable.BillNumberID=@nBillID AND InoutStockTable.ID=b.ID
END

GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaleBill_CreateBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_SaleBill_CreateBill]
GO




/*

功能说明：		销售出库单过帐后生成采购入库单的草稿

作    者：       冯波


返回结果：       

修改：陈强
日期：2019-10-23
说明：敏捷4690 系统重建 第一次生成采购入库生成不了

*/

CREATE PROCEDURE [GP_SaleBill_CreateBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
*/
DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT


SELECT @intReturnID=0

DECLARE 
	@strSaleBTypeID					VARCHAR(50),		--销售客户的信息	
	@strSaleSTypeID					VARCHAR(50),		--销售客户对应的分支机构
	@strBuyBTypeID					VARCHAR(50),		--采购客户
	@strBuySTypeID					VARCHAR(50),
	@decTax							 NUMERIC(24, 10) ,
	@strFromBillCode 				VARCHAR(100),
	@datBillDate					DATETIME,
	@ceDtypeid			VARCHAR(100),
	@cdfullname			VARCHAR(500)=''			--部门

SELECT 
	@strSaleBTypeID=a.DealBTypeID,@strSaleSTypeID=a.sTypeId,@ceDtypeid=DTypeId,
	@strBuyBTypeID=c.BTypeID2,@strBuySTypeID=b.typeid,
	@decTax=a.tax,@strFromBillCode=a.BillCode,@datBillDate=a.BillDate
FROM BillIndex a
INNER JOIN SType b 
ON a.DealBTypeID=b.btypeId1
INNER JOIN SType c
ON a.Stypeid=c.TypeId
WHERE a.BillNumberId=@nBillID

SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

--判断是否属于分支机构间的采购，销售
IF NOT EXISTS(SELECT TypeID FROM SType WHERE TypeId=@strBuySTypeID AND @strBuySTypeID IS NOT NULL AND sonnum=0)
BEGIN
	SET @strErrMsg='该单据不是分支机构间的采购销售！'
	RETURN
END


IF NOT EXISTS(SELECT TypeID FROM SType WHERE BTypeID2=@strBuyBTypeID AND @strBuyBTypeID IS NOT NULL)
BEGIN
	SET @strErrMsg='该单据不是分支机构间的采购销售！'
	RETURN
END


IF @nBillID<>1
BEGIN
	IF EXISTS(SELECT BillNumberId FROM BillIndex WHERE FromBillNumberID=@nBillID AND BillType=34)
	BEGIN
		SET @strErrMsg='该销售出库单已生成有相应的采购入库单草稿！'	
		RETURN
	END
END

IF ISNULL(@strBuyBTypeID,'')='' OR ISNULL(@strBuySTypeID,'')=''	RETURN

DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号

/*

生成新的单据编号

DECLARE
	@strTempSID			VARCHAR(100),
	@strTempDID			VARCHAR(100),
	@strTempEID			VARCHAR(100)

SELECT @strTempSID=@strSaleSTypeID

SELECT @strTempEID=''

SELECT @strTempDID='',@strTempEID=''

DECLARE
	@intNewSeed		BigInt



EXEC GP_CreateBillCode
	'',
	@strTempSID,
	@datBillDate,
	@intBillType,
	1,
    @strBillCode OUT,
    @intNewSeed OUT,
    @strErrMsg OUT
*/

DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@ETypeID			VARCHAR(100),
	@KTypeID			VARCHAR(100),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@intBillType		INT,
	@cefullname			VARCHAR(500)=''

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT
	@ETypeID='',
	@KTypeID='',
	@VchHead='JK',
	@intBillType=34

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = typeid FROM Employee WHERE TypeID = @ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
	SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
END
ELSE
BEGIN
	SELECT	@MONTH=ISNULL(@MONTH,''),
			@DAY=ISNULL(@DAY,'')
END
	


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strBuySTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname


IF @Re <> 0
RETURN -2	


--SELECT @strBillCode='tmpcgrkd'  --因为单据编号要调整，暂时屏蔽生成单据编号那段代码

DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000)
	
	
SELECT 
	@strComment='该采购入库单是从销售出库单'+@strFromBillCode+'生成而来的！'


--生成采购入库单的草稿
--生成表头

DECLARE
	@strdenominatedid VARCHAR(50)
	
SELECT 	@strdenominatedid=denominatedid
FROM BType
WHERE typeId=@strBuyBTypeID

DECLARE
	@strTempATypeID		VARCHAR(100),
	@VerifyID		VARCHAR(50)		--记账单位，往来科目取记账单位对应往来科目

SELECT @VerifyID=VerifyID FROM dbo.SType WHERE TypeId=@strBuySTypeID
	
SELECT
	@strTempATypeID=ATypeID
FROM BillAtype
WHERE BillTypeId='34'
AND StypeId=@VerifyID

SELECT @strTempATypeID=ISNULL(@strTempATypeID,'')


INSERT BillIndex(BillDate,BillCode,BillType,DealBTypeID,BTypeID,STypeID,KTypeID,ETypeID,
ATypeID,KTypeID2,KTypeID3,Comment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,AlertDay,DTypeId,CostSale,FromBillNumberID,
ifcheck,IfAudit,draft,OrderId,checke,Ntotalmoney,CID,Rate,ATypeID1)
SELECT BillDate,@strBillCode,@intBillType,@strBuyBTypeID,@strdenominatedid,@strBuySTypeID,
'','','','','',@strComment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,AlertDay,'',CostSale,BillNumberId,
'f',0,1,0,'',NTotalMoney,CID,Rate,@strTempATypeID
FROM BillIndex
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();

--表头自定义
INSERT INTO Custom_BillIndex (BillId, BillType, SysDiy1_head, SysDiy2_head, SysDiy3_head, SysDiy4_head, SysDiy5_head, SysDiy6_head, SysDiy7_head, SysDiy8_head, SysDiy9_head, SysDiy10_head, SysDiy11_head, SysDiy12_head, SysDiy13_head, SysDiy14_head, SysDiy15_head, SysDiy16_head, SysDiy17_head, SysDiy18_head, SysDiy19_head, SysDiy20_head, SysDiy21_head, SysDiy22_head, SysDiy23_head, SysDiy24_head, SysDiy25_head, SysDiy26_head, SysDiy27_head, SysDiy28_head, SysDiy29_head, SysDiy30_head, SysDiy31_head, SysDiy32_head, SysDiy33_head, SysDiy34_head, SysDiy35_head, SysDiy36_head, SysDiy37_head, SysDiy38_head, SysDiy39_head, SysDiy40_head)
SELECT	@intReturnID, @intBillType, SysDiy1_head, SysDiy2_head, SysDiy3_head, SysDiy4_head, SysDiy5_head, SysDiy6_head, SysDiy7_head, SysDiy8_head, SysDiy9_head, SysDiy10_head, SysDiy11_head, SysDiy12_head, SysDiy13_head, SysDiy14_head, SysDiy15_head, SysDiy16_head, SysDiy17_head, SysDiy18_head, SysDiy19_head, SysDiy20_head, SysDiy21_head, SysDiy22_head, SysDiy23_head, SysDiy24_head, SysDiy25_head, SysDiy26_head, SysDiy27_head, SysDiy28_head, SysDiy29_head, SysDiy30_head, SysDiy31_head, SysDiy32_head, SysDiy33_head, SysDiy34_head, SysDiy35_head, SysDiy36_head, SysDiy37_head, SysDiy38_head, SysDiy39_head, SysDiy40_head
FROM	Custom_BillIndex
WHERE	BillId  = @nBillID

--生成表体

INSERT BuyBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,OutFactoryDate,
TaxPrice,TaxTotal,comment,IsUnit2,Serial,GoodsNumber,ProduceDate,ValidDate,
GoodsBTypeID,GoodsCostPrice,GoodsCostTotal,SaleTotal,Tax,KTypeID,Stypeid,
FromBillNumberID,FromBillID,OrderID,
TaxMoney,NSalePrice,NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,
NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,
CurMSalePrice,CurMDiscountPrice,CurMTaxPrice,CargoID,ItemID,IsCombined,entryCode,IsGift,ShowOrder)


SELECT @intReturnID,a.PtypeId,a.Qty,a.SalePrice,a.discount,a.DiscountPrice,a.total,a.OutFactoryDate,
a.TaxPrice,a.TaxTotal,a.comment,a.IsUnit2,a.Serial,a.GoodsNumber,a.ProduceDate,a.ValidDate,
a.GoodsBTypeID,a.GoodsCostPrice,a.GoodsCostTotal,a.SaleTotal,a.Tax,'',@strBuySTypeID,
a.BillNumberID,a.ID,ISNULL(c.OrderID,-1),
a.TaxMoney,a.NSalePrice,a.NSaleTotal,a.NDiscountPrice,a.NTotal,a.NTaxPrice,a.NTaxTotal,a.NTaxMoney,a.UnitID,
a.NUnitID,a.NQty,a.UnitRate,a.NUnitMsg,a.MUnitID,a.MQty,a.MUnitRate,a.MUnitMsg,a.MSalePrice,a.MDiscountPrice,a.MTaxPrice,
a.CurMSalePrice,a.CurMDiscountPrice,a.CurMTaxPrice,0,a.ItemID,a.IsCombined,a.entryCode,a.IsGift,a.ShowOrder
FROM SaleBill a
LEFT JOIN OrderBill b
ON a.OrderID=b.OrderID
LEFT JOIN OrderBill c
ON b.FromBillID=c.OrderID
WHERE a.BillNumberId=@nBillID

--表体自定义
INSERT INTO Custom_BillDetails (BillId, Detailid, BillType, SysDiy1, SysDiy2, SysDiy3, SysDiy4, SysDiy5, SysDiy6, SysDiy7, SysDiy8, SysDiy9, SysDiy10, SysDiy11, SysDiy12, SysDiy13, SysDiy14, SysDiy15, SysDiy16, SysDiy17, SysDiy18, SysDiy19, SysDiy20, SysDiy21, SysDiy22, SysDiy23, SysDiy24, SysDiy25, SysDiy26, SysDiy27, SysDiy28, SysDiy29, SysDiy30, SysDiy31, SysDiy32, iscombination, InOrOut, SysDiy33, SysDiy34, SysDiy35, SysDiy36, SysDiy37, SysDiy38, SysDiy39, SysDiy40)
SELECT	O.billNumberID, O.ID, @intBillType, SysDiy1, SysDiy2, SysDiy3, SysDiy4, SysDiy5, SysDiy6, SysDiy7, SysDiy8, SysDiy9, SysDiy10, SysDiy11, SysDiy12, SysDiy13, SysDiy14, SysDiy15, SysDiy16, SysDiy17, SysDiy18, SysDiy19, SysDiy20, SysDiy21, SysDiy22, SysDiy23, SysDiy24, SysDiy25, SysDiy26, SysDiy27, SysDiy28, SysDiy29, SysDiy30, SysDiy31, SysDiy32, iscombination, InOrOut, SysDiy33, SysDiy34, SysDiy35, SysDiy36, SysDiy37, SysDiy38, SysDiy39, SysDiy40
FROM	BuyBill O
INNER JOIN Custom_BillDetails C ON C.BillId = O.FromBillNumberId AND O.FromBillId = C.Detailid
WHERE	O.billNumberID = @intReturnID

--写WaitQty
UPDATE	dbo.OrderBill
SET		WaitQty = ISNULL(WaitQty,0) + ISNULL(b.Qty,0)
FROM	orderbill o
INNER JOIN (
				SELECT	orderid,
						SUM(ISNULL(qty,0)) AS qty
				FROM	buybill 
				WHERE	BillNumberId = @intReturnID
				GROUP BY orderid
)b ON b.orderid = o.orderid 
WHERE o.orderid <> -1

IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END		

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END

-- 自动生成的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @intReturnID,@intBillType

GO




GO
IF EXISTS(SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'Gp_SaleGoodsExchangeCheck',N'P'))
BEGIN
	DROP PROC Gp_SaleGoodsExchangeCheck
END
GO

/*
	销售换货单按单退货数量检查
*/
CREATE PROC Gp_SaleGoodsExchangeCheck
(
	@Details TBType_SaleGoodsExchange READONLY
)
--@encode$--
AS
BEGIN
	SELECT 1 AS RET FROM SaleBill A JOIN @Details B ON A.BillNumberId=B.OldBillNumberId AND A.Id=B.OldId
	WHERE B.OldBillNumberId<>0 AND ISNULL(A.Qty,0)-ISNULL(A.Backqty,0)<B.Qty 
END
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_SaleOrderToBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_SaleOrderToBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-12-05
--	描述：未完成的销售订单生成销售出库单
--	作者：鲁大林
--	日期：2012-05-22
--	描述：【修改】添加未完成生成销售出库单中币别和自由项
--	作者：鲁大林
--	日期：2012-06-27
--	描述：【修改】添加结算单位
---------------------------------------------
CREATE PROCEDURE GP_SaleOrderToBill
( 
	@OperatorID		VARCHAR(50),
	@orderid		VARCHAR(MAX),
	@ifetype		VARCHAR(10),
	@ifktype		VARCHAR(10),
	@clientip		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #SType(TypeId	varchar(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorID)

--往来单位
CREATE TABLE #BType(TypeId	varchar(100))
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)

--仓库
CREATE TABLE #KType(TypeId	varchar(100))
INSERT INTO #KType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)	

--职员
CREATE TABLE #EType(TypeId	varchar(100))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)	

--商品
CREATE TABLE #PType(TypeId	varchar(100))
INSERT INTO #PType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@OperatorID)	


----BEGIN---------------------判断是否存在未完成的订单，处理出库单过账后未完成订单没有刷新页面的同步操作情况-------------------------

IF EXISTS(SELECT 1 FROM dbo.OrderIndex a INNER JOIN dbo.OrderBill b ON a.billNumberId = b.billNumberID 
			WHERE OrderState='1' AND b.OrderID IN (SELECT * FROM f_split(@orderid,',')))
BEGIN
	RAISERROR('存在已完成的单据，请刷新页面重试！',16,1) 
	RETURN 
END

----END------------------------------------------------------------------------------------------------------------------------------

--草稿库存
CREATE TABLE #DraftGoodsStocks
(
	PTypeId			VARCHAR(100),
	KTypeId			VARCHAR(100),
	Qty				 NUMERIC(24, 10) ,
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) ,
	SaleReachQty	 NUMERIC(24, 10) ,
	BuyReachQty		 NUMERIC(24, 10) 
)


CREATE TABLE #OrderBillNumberID
(
	id	VARCHAR(1000)
)

CREATE TABLE #atypeid1(id VARCHAR(1000),NAME VARCHAR(1000),flag varchar(10))


INSERT INTO #OrderBillNumberID (id)
SELECT billNumberID FROM OrderBill WHERE OrderID IN (SELECT *FROM f_split(@orderid,',')) GROUP BY billNumberID


CREATE TABLE #MANTYPE
(	
	GoodsNumber VARCHAR(50),
	rate		VARCHAR(50),
	cid			VARCHAR(50),
	stypeid		VARCHAR(50),
	btypeid		VARCHAR(50),
	dealbtypeid VARCHAR(50),
	dtypeid		VARCHAR(50),	
	etypeid		VARCHAR(50),
	ktypeid		VARCHAR(50)	
)

DECLARE @SQL VARCHAR(MAX)
DECLARE @colname	VARCHAR(MAX)
DECLARE @GroupByCol	VARCHAR(MAX)
DECLARE @atypeid1 VARCHAR(max)

SET @colname='a.GoodsNumber,a.rate,a.cid as cid,a.stypeid AS stypeid,ISNULL(a.btypeid,'''') AS btypeid,ISNULL(a.dealbtypeid,'''') AS dealbtypeid,
				ISNULL(a.dtypeid,'''') as dtypeid '

SET @GroupByCol='a.GoodsNumber,a.rate,a.cid,a.stypeid,a.btypeid,a.dealbtypeid,a.dtypeid '

IF @ifetype='1'
	BEGIN
		SET @colname=@colname+',a.etypeid AS etypeid'
		SET @GroupByCol=@GroupByCol+',a.etypeid '
	END
ELSE
	SET @colname=@colname+','''' AS etypeid'
IF @ifktype='1'
	BEGIN
		SET @colname=@colname+',a.ktypeid AS ktypeid'
		SET @GroupByCol=@GroupByCol+',a.ktypeid '
	END
ELSE
	SET @colname=@colname+','''' AS ktypeid'

SET @SQL='
INSERT INTO #MANTYPE(GoodsNumber,rate,cid,stypeid,btypeid,dealbtypeid,dtypeid,etypeid,ktypeid)
SELECT '+@colname+'
FROM orderindex a
INNER JOIN #OrderBillNumberID b ON b.id=a.billNumberID
GROUP BY '+@GroupByCol
--PRINT(@sql)
EXEC (@SQL)

DECLARE @billdate		DATETIME,
		@billcode		VARCHAR(MAX),
		@stypeid		VARCHAR(MAX),
		@etypeid		VARCHAR(MAX),
		@btypeid		VARCHAR(MAX),
		@dtypeid		VARCHAR(max),
		@ktypeid		VARCHAR(MAX),
		@totalmoney		NUMERIC(24, 10) ,
		@totalqty		NUMERIC(24, 10) ,
		@tax			NUMERIC(24, 10) ,
		@BillNumberId	NUMERIC(24, 10) ,
		@DAY			VARCHAR(MAX),
		@MONTH			VARCHAR(MAX),
		--以下参数用于处理明细超过500条的情况
		@rowcount		INT,	--明细总行数
		@maxcount		INT,	--明细最大行数（500条）
		@pagecount		INT,		--明细页数
		@dealbtypeid	VARCHAR(100),--结算单位
		@cid			VARCHAR(100),
		@rate			VARCHAR(100),
		@GoodsNumber	VARCHAR(100),
		@intQtyDot		INT,
		@cefullname		VARCHAR(500)='',
		@dfullname		VARCHAR(500)='',
		@explain		VARCHAR(2000)=''
		
		
SET @rowcount=0
SET @maxcount=500
SET @pagecount=0

--数量的小数位数
EXEC	@intQtyDot=Gp_GetDigit 1
		
CREATE TABLE #billnumberid(ID VARCHAR(MAX))

DECLARE @billtype	VARCHAR(10)
SET @billtype='11'
--取当前时间
SET @billdate=GETDATE()
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
SET @billdate=(SELECT CONVERT (VARCHAR(10),@billdate,120))

SET @SQL='
DECLARE indexcursor CURSOR FOR 
	SELECT  '+@colname+',
			SUM(b.qty-b.ReachQty) AS totalqty,
			ROUND(SUM((b.qty-b.ReachQty)*taxprice),2) AS totalmoney
	FROM	#MANTYPE a
	INNER JOIN ORDERINDEX I ON  I.Stypeid=a.stypeid AND ISNULL(I.dealbtypeid,'''')=ISNULL(a.dealbtypeid,'''') AND ISNULL(I.btypeid,'''')=ISNULL(a.btypeid,'''') and (a.dtypeid='''' or I.dtypeid=a.dtypeid) AND (a.etypeid='''' OR I.etypeid=a.etypeid) AND (a.ktypeid='''' OR I.ktypeid=a.Ktypeid)
	INNER JOIN OrderBill B ON I.billNumberId=B.billNumberID
	WHERE (b.qty-b.ReachQty)<>0 and B.OrderID IN (SELECT *FROM f_split('''+@orderid+''','','')) 
	GROUP BY '+@GroupByCol

EXEC (@SQL)

OPEN indexcursor

FETCH NEXT FROM indexcursor INTO	@GoodsNumber,
									@rate,
									@cid,
									@sTypeID,
									@BTypeID,
									@dealbtypeid,
									@dtypeid,									
									@eTypeID,
									@kTypeID,
									@totalqty,
									@totalmoney--@tax


WHILE @@FETCH_STATUS=0
BEGIN
	--是否自定义单据编号
	IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =11)
	BEGIN
		SELECT @MONTH = typeid  FROM employee WHERE typeId=@ETypeId
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @OperatorID
		SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId = @dtypeid
	END
		
	SELECT @rowcount=COUNT(1)
	FROM	OrderBill a
	INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
	WHERE	A.OrderID IN (SELECT * FROM f_split(@orderid,','))
	AND		I.Stypeid=@Stypeid
	AND		ISNULL(I.dealbtypeid,'')=ISNULL(@dealbtypeid,'')
	AND		ISNULL(I.DtypeId,'')=ISNULL(@dtypeid,'')
	AND		(@Etypeid='' OR I.Etypeid=@Etypeid)
	AND		(@Ktypeid='' OR I.Ktypeid=@Ktypeid)
	AND		(a.qty-a.ReachQty)<>0
	
	SET @pagecount=@rowcount/@maxcount+1

	IF @rowcount%500=0
		SET @pagecount=@pagecount-1

	WHILE(@pagecount>0)
	BEGIN
		--生成单据编号
		EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'XK',@billdate,@STypeId,@billcode OUT,@dfullname,@cefullname,-999

		--主表数据写入
		SET @BillNumberId = 0
		
		INSERT INTO #atypeid1
		        ( id, NAME,flag )
		EXEC dbo.Web_GetAtype @billtypeid = @billtype, -- varchar(50)
		    @stypeid = @stypeid -- varchar(50)
		
		SELECT @atypeid1=id FROM #atypeid1
		
DECLARE @recvalue INT=0		
EXEC @recvalue=Gp_InsertBillIndex 
			@BillDate=@billdate,
			@BillCode=@billcode,
			@BillType=@billtype,
			@Comment='未完成的销售订单生成的销售出库单',
			@ATypeID='',
			@PTypeID='',
			@BTypeID=@btypeid,
			@ETypeID=@etypeid,
			@KTypeID=@ktypeid,
			@KTypeID2='',
			@IfCheck='f',
			@CheckE=@OperatorID,
			@TotalMoney=@totalmoney,
			@TotalQty=@totalqty,
			@TotalInMoney=0,
			@Tax='0',
			@szPeriod=1,
			@Explain='',	--@explain,
			@Draft='True',
			@RedWord='False',
			@OrderID=0,
			@WayBillCode='',
			@Goodsnumber=@GoodsNumber,
			@PackWay='',
			@Tel='',
			@preferencemoney=0,
			@AlertDay=9999,
			@Assessor='',
			@IfAudit='',
			@Audit_Explain='',
			@Dtypeid=@dtypeid,
			@VipCardID=-1,
			@KTypeID3='',
			@LinkMan='',
			@LinkTel='',
			@LinkAddr='',
			@wxManID='',
			@JieJianBillNumberID=-1,
			@JieJianID=-1,
			@BaoXiuBillNumberID=-1,
			@BaoXiuID=-1,
			@BuyDate='',
			@Serial='',
			@wxTotal=0,
			@ErrDes='',
			@ifHideJieJian=0,
			@ifWX=0,
			@IfBargainOn=0,
			@STypeID=@stypeid,
			@FromBillNumberID=0,
			@CostSale=0,
			@completedate='9999-12-31 23:59:59',
			@billstate=1,
			@ifmulaccount=0,
			@vipczmoney=0,
			@otherinouttype=-1,
			@czbeforetimes=0,
			@posbilltype=0,
			@TransportId=0,
			@IsFreightMoney=0,
			@FreightAddr=NULL,
			@freightperson=NULL,
			@freighttel=NULL,
			@ShareMode=0,
			@uf1='',
			@uf2='',
			@uf3='',
			@uf4='',
			@uf5='',
			--9.0新字段
			@dealbtypeid=@dealbtypeid,		--结算单位
			@cid=@cid,			--外币币种id
			@rate=@rate,			--汇率
			@ntotalmoney=@totalmoney,		--原币种金额
			@ntotalinmoney=0,	--原币收现金额
			@npreferencemoney=0,	--原币优惠金额
			@nvipczmoney=0,		--原币会员卡充值金额
			@atypeid1=@atypeid1,
			@billproperty=-1,					--单据属性
			@ncompletetotal	=0,		--原币结算金额
			@isini=0,
			@ATID=0,					--过账模板
			@CompleteTotal=0,
			@IfCargo=0,
			@IfInvoice=0,
			@promoruleid=0,
			@beforepromobillnumberid=0,
			@promotionmsg='',
			@isyapi=0,
			@yapiorderid=0	,
			@DeliveryAddress='',
			@Discount=1,
			@AdpriceType=0,	
			@checkSave='bill_allow_save'
			
 IF @recvalue = -1 
    BEGIN
        RAISERROR('试用版最多录200条单据！',16,1)
        RETURN
    END
 IF @recvalue = -2 
    BEGIN
        RAISERROR('录单日期小于本期开始日期！',16,1)
        RETURN
    END
 IF @recvalue = -3 
    BEGIN
        RAISERROR('校验错误 ！',16,1)
        RETURN
    END
 IF @recvalue = -4
    BEGIN
        RAISERROR('录单日期必须与当前日期一致！',16,1)
        RETURN
    END
 IF @recvalue = -5 
    BEGIN
        RAISERROR('更新单据发生错误！',16,1)
        RETURN
    END

		--IF @@ROWCOUNT = 0
		--	RETURN -10
		--ELSE	
		--SELECT @recvalue		
		
		SET @BillNumberId = @recvalue

		IF @BillNumberId IS NULL
			RETURN -10
			
		--写单据操作日志
		INSERT INTO BillOperateLog(billnumberid,operatetype,etypeid,OperateTime,ip) values(@BillNumberId,'制单',@OperatorID,GETDATE(),@clientip)

		--保存单据编号的种子数
		EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
		
		INSERT INTO #billnumberid (ID) VALUES(@BillNumberId)
		--明细表数据写入
		INSERT INTO SaleBill 
		(
			[BillNumberId],
			[PtypeId],
			[Qty],
			[SalePrice],
			[discount],
			[DiscountPrice],
			[jobnumber],
			[total],
			[OutFactoryDate],
			[TaxPrice],
			[TaxTotal],
			[comment],
			OrderID,
			[isUnit2],
			[Serial],
			[GoodsNumber],
			[ProduceDate],
			[ValidDate],
			[GoodsBTypeID],
			Tax,
			SaleTotal,
			KTypeID,
			STypeID,--,ShareFee
			ItemID,--自由项id
			CargoID,
			CurMDiscountPrice,
			CurMSalePrice,
			CurMTaxPrice,
			UnitID,
			UnitRate,
			NTotal,
			TaxMoney,
			NDiscountPrice,
			NQty,
			NSalePrice,
			NSaleTotal,
			NTaxMoney,
			NTaxPrice,
			NTaxTotal,
			NUnitID,
			NUnitMsg,
			MDiscountPrice,
			MQty,
			MSalePrice,
			MTaxPrice,
			MUnitID,
			MUnitMsg,
			MUnitRate,
			IsCombined,
			pricesource,
			promotype,
			goodscostprice,
			ETypeID
		)
		SELECT TOP (@maxcount) * 
		FROM
		(	SELECT TOP (@rowcount-@maxcount*(@pagecount-1)) *
			FROM (
					SELECT	TOP (@maxcount*@pagecount)
							@BillNumberId AS BillNumberId,
							a.ptypeid AS ptypeid,
							(a.qty-a.ReachQty) AS qty,
							a.price AS saleprice,
							a.Discount AS discount,
							a.DiscountPrice AS discountprice,
							'' AS jobnumber,
							CASE 
								WHEN a.reachqty = 0 THEN a.total
								ELSE ROUND((a.qty-a.ReachQty)*a.DiscountPrice,2)
							END AS total,
							@billdate AS OutFactoryDate,
							a.TaxPrice AS taxprice,
							CASE
								WHEN a.reachqty = 0 THEN a.TaxTotal
								ELSE ROUND((a.qty-a.ReachQty)*a.TaxPrice,2)
							END AS TaxTotal,
							CASE
								WHEN LEN(I.Billcode+';'+a.comment)>256 THEN LEFT(I.Billcode+';'+a.comment,256)
								ELSE I.Billcode+';'+a.comment
							END AS comment,--983 540 测试提的bug
							a.OrderID AS orderid,
							a.IsUnit2 AS isunit2,
							'' AS serial,
							a.GoodsNumber,
							a.ProduceDate AS ProduceDate,
							a.ValidDate AS ValidDate,
							'' AS GoodsBTypeID,
							a.Tax AS tax,
							CASE
								WHEN a.reachqty = 0 THEN a.saletotal
								ELSE ROUND((a.qty-a.ReachQty)*a.price,2)
							END AS saletotal,
							CASE @ifktype 
								WHEN '1' THEN a.KTypeID
								ELSE @ktypeid END AS ktypeid,
							a.Stypeid AS stypeid,--,'' AS ShareFeeBill
							a.ItemID,
							--a.CargoID,
							CASE @ifktype WHEN '1' THEN a.CargoID ELSE NULL END AS cargoid,
							
							a.curmdiscountprice AS curmdiscountprice,--大单位原币折后价
							a.curmsaleprice as curmsaleprice,--大单位原币单价
							a.curmtaxprice AS curmtaxprice,--大单位原币含税价
							a.UnitID,
							a.UnitRate,
							CASE
								WHEN a.reachqty = 0 THEN a.ntotal
								--ELSE a.NTotal*(1-a.ReachQty/a.qty)
								ELSE ROUND((a.qty-a.ReachQty)*a.nDiscountPrice,2)
							END AS ntotal,
							ROUND(a.TaxMoney*(a.qty-a.ReachQty)/a.qty,2) AS TaxMoney,--本币税额
							a.NDiscountPrice,--原币折后单价
							a.NQty*(1-a.ReachQty/a.qty) AS nqty,
							a.NSalePrice,--原币单价
							CASE
								WHEN a.reachqty = 0 THEN a.nsaletotal
								ELSE ROUND((a.qty-a.ReachQty)*a.NSalePrice,2)
							END AS nsaletotal,--原币金额
							ROUND(a.NTaxMoney*(a.qty-a.ReachQty)/a.qty,2) AS NTaxMoney,--原币税额
							a.NTaxPrice,--原币含税单价
							CASE
								WHEN a.reachqty = 0 THEN a.ntaxtotal
								ELSE ROUND((a.qty-a.ReachQty)*NTaxPrice,2)
							END AS ntaxtotal,						--原币价税合计
							a.NUnitID,
							a.NUnitMsg,
							a.MDiscountPrice AS MDiscountPrice,--大单位折后价							
							ROUND((a.Qty-a.ReachQty)/isnull(a.MunitRate,1),@intQtyDot) AS mqty,--大单位数量
							a.MSalePrice,--大单位单价
							a.MTaxPrice,--大单位含税价
							a.munitid ,
							a.MUnitMsg,
							a.MunitRate,
							a.IsCombined,
							'来自销售订单生成：['+a.pricesource+']' AS pricesource,
							a.promotype,
							-1 as goodscostprice,
							I.etypeid
					FROM	OrderBill a
					INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
					WHERE	A.OrderID IN (SELECT *FROM f_split(@orderid,','))
							AND I.GoodsNumber=@GoodsNumber
							AND I.Rate=@rate 
							AND I.CID=@cid
							AND	I.Stypeid=@Stypeid
							AND I.btypeid=@btypeid
							AND I.DtypeId=@dtypeid
							AND	ISNULL(I.dealbtypeid,'')=ISNULL(@dealbtypeid,'')
							AND	(@Etypeid='' OR I.Etypeid=@Etypeid)
							AND	(@Ktypeid='' OR I.Ktypeid=@Ktypeid)
							AND	(a.qty-a.ReachQty)<>0
					ORDER BY a.OrderID
					) A 
			ORDER BY A.orderid DESC) B 
		ORDER BY B.orderid
		
		UPDATE dbo.SaleBill SET ShowOrder=ID WHERE BillNumberId=@BillNumberId
		SET @pagecount=@pagecount-1
		
		UPDATE a SET WaitQty=ISNULL(WaitQty,0)+ISNULL(b.Qty,0)
		FROM OrderBill a 
		JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM salebill b WHERE b.OrderId<>-1 AND b.billNumberID=@BillNumberId GROUP BY orderid)b ON b.orderid=a.OrderID

			
		-- 自动生成的单据会影响草稿库存
		EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,@billtype
		
		--表体自定义
		INSERT INTO Custom_BillDetails (BillId, Detailid, BillType, SysDiy1, SysDiy2, SysDiy3, SysDiy4, SysDiy5, SysDiy6, SysDiy7, SysDiy8, SysDiy9, SysDiy10, SysDiy11, SysDiy12, SysDiy13, SysDiy14, SysDiy15, SysDiy16, SysDiy17, SysDiy18, SysDiy19, SysDiy20, SysDiy21, SysDiy22, SysDiy23, SysDiy24, SysDiy25, SysDiy26, SysDiy27, SysDiy28, SysDiy29, SysDiy30, SysDiy31, SysDiy32, iscombination, InOrOut, SysDiy33, SysDiy34, SysDiy35, SysDiy36, SysDiy37, SysDiy38, SysDiy39, SysDiy40)
		SELECT	@BillNumberId, O.ID, 11, SysDiy1, SysDiy2, SysDiy3, SysDiy4, SysDiy5, SysDiy6, SysDiy7, SysDiy8, SysDiy9, SysDiy10, SysDiy11, SysDiy12, SysDiy13, SysDiy14, SysDiy15, SysDiy16, SysDiy17, SysDiy18, SysDiy19, SysDiy20, SysDiy21, SysDiy22, SysDiy23, SysDiy24, SysDiy25, SysDiy26, SysDiy27, SysDiy28, SysDiy29, SysDiy30, SysDiy31, SysDiy32, iscombination, InOrOut, SysDiy33, SysDiy34, SysDiy35, SysDiy36, SysDiy37, SysDiy38, SysDiy39, SysDiy40
		FROM	OrderBill O
		INNER JOIN dbo.SaleBill S ON S.OrderID = O.Id
		INNER JOIN Custom_BillDetails C ON C.BillId = O.BillNumberId AND O.ID = C.Detailid
		WHERE	S.billNumberID = @BillNumberId		
	END
	---读取下一行数据
	FETCH NEXT FROM indexcursor INTO	@GoodsNumber,
										@rate,
										@cid,
										@sTypeID,
										@BTypeID,
										@dealbtypeid,
										@dtypeid,										
										@eTypeID,
										@kTypeID,
										@totalqty,
										@totalmoney--,@tax		
END
CLOSE indexcursor
DEALLOCATE  indexcursor

--UPDATE OrderBill SET WaitQty=WaitQty+qty-ReachQty WHERE	OrderID IN (SELECT *FROM f_split(@orderid,',')) 

SELECT BillCode AS billcode FROM BillIndex BI
INNER JOIN #billnumberid B ON  BI.BillNumberId=B.ID

DROP TABLE #MANTYPE,#atypeid1,#DraftGoodsStocks,#OrderBillNumberID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaleOrderToWmsSaleBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_SaleOrderToWmsSaleBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：谢吉康
	日期：2018-10-19
	描述：销售订单生成WMS销售出库单
*/
CREATE PROCEDURE Gp_SaleOrderToWmsSaleBill
( 
	@OperatorID		VARCHAR(50),
	@orderid		VARCHAR(MAX),
	@ifetype		VARCHAR(10) = '1',
	@ifktype		VARCHAR(10) = '1',
	@clientip		VARCHAR(MAX) = '',
	@errormsg		VARCHAR(100) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON
SET @errormsg = ''
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #SType(TypeId	varchar(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorID)

--往来单位
CREATE TABLE #BType(TypeId	varchar(100))
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)

--仓库
CREATE TABLE #KType(TypeId	varchar(100))
INSERT INTO #KType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)	

--职员
CREATE TABLE #EType(TypeId	varchar(100))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)	

--商品
CREATE TABLE #PType(TypeId	varchar(100))
INSERT INTO #PType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@OperatorID)	


----BEGIN---------------------判断是否存在未完成的订单，处理出库单过账后未完成订单没有刷新页面的同步操作情况-------------------------

IF EXISTS(SELECT 1 FROM dbo.OrderIndex a INNER JOIN dbo.OrderBill b ON a.billNumberId = b.billNumberID 
			WHERE OrderState='1' AND b.OrderID IN (SELECT * FROM f_split(@orderid,',')))
BEGIN
	--RAISERROR('存在已完成的单据，请刷新页面重试！',16,1) 
	SET @errormsg = '存在已完成的单据，请刷新页面重试！'
	RETURN 
END

----END------------------------------------------------------------------------------------------------------------------------------

--草稿库存
CREATE TABLE #DraftGoodsStocks
(
	PTypeId			VARCHAR(100),
	KTypeId			VARCHAR(100),
	Qty				 NUMERIC(24, 10) ,
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) ,
	SaleReachQty	 NUMERIC(24, 10) ,
	BuyReachQty		 NUMERIC(24, 10) 
)


CREATE TABLE #OrderBillNumberID
(
	id	VARCHAR(1000)
)

CREATE TABLE #atypeid1(id VARCHAR(1000),NAME VARCHAR(1000),flag varchar(10))


INSERT INTO #OrderBillNumberID (id)
SELECT billNumberID FROM OrderBill WHERE OrderID IN (SELECT *FROM f_split(@orderid,',')) GROUP BY billNumberID


CREATE TABLE #MANTYPE
(	
	GoodsNumber VARCHAR(50),
	rate	VARCHAR(50),
	cid  VARCHAR(50),
	stypeid	VARCHAR(50),
	btypeid	VARCHAR(50),
	dealbtypeid VARCHAR(50),
	dtypeid	VARCHAR(50),
	etypeid	VARCHAR(50),
	ktypeid	VARCHAR(50)
)

DECLARE @SQL VARCHAR(MAX)
DECLARE @colname	VARCHAR(MAX)
DECLARE @GroupByCol	VARCHAR(MAX)
DECLARE @atypeid1 VARCHAR(max)

SET @colname='a.GoodsNumber,a.rate,a.cid as cid,a.stypeid AS stypeid,ISNULL(a.btypeid,'''') AS btypeid,ISNULL(a.dealbtypeid,'''') AS dealbtypeid,
				ISNULL(a.dtypeid,'''') as dtypeid '
SET @GroupByCol='a.GoodsNumber,a.rate,a.cid,a.stypeid,a.btypeid,a.dealbtypeid,a.dtypeid '
IF @ifetype='1'
	BEGIN
		SET @colname=@colname+',a.etypeid AS etypeid'
		SET @GroupByCol=@GroupByCol+',a.etypeid '
	END
ELSE
	SET @colname=@colname+','''' AS etypeid'
IF @ifktype='1'
	BEGIN
		SET @colname=@colname+',a.ktypeid AS ktypeid'
		SET @GroupByCol=@GroupByCol+',a.ktypeid '
	END
ELSE
	SET @colname=@colname+','''' AS ktypeid'

SET @SQL='
INSERT INTO #MANTYPE(GoodsNumber,rate,cid,stypeid,btypeid,dealbtypeid,dtypeid,etypeid,ktypeid)
SELECT '+@colname+'
FROM orderindex a
INNER JOIN #OrderBillNumberID b ON b.id=a.billNumberID
GROUP BY '+@GroupByCol
--PRINT(@sql)
EXEC (@SQL)

DECLARE @billdate		DATETIME,
		@billcode		VARCHAR(MAX),
		@stypeid		VARCHAR(MAX),
		@etypeid		VARCHAR(MAX),
		@btypeid		VARCHAR(MAX),
		@dtypeid		VARCHAR(max),
		@ktypeid		VARCHAR(MAX),
		@totalmoney		NUMERIC(24, 10) ,
		@totalqty		NUMERIC(24, 10) ,
		@tax			NUMERIC(24, 10) ,
		@BillNumberId	NUMERIC(24, 10) ,
		@DAY			VARCHAR(MAX),
		@MONTH			VARCHAR(MAX),
		--以下参数用于处理明细超过500条的情况
		@rowcount		INT,	--明细总行数
		@maxcount		INT,	--明细最大行数（500条）
		@pagecount		INT,		--明细页数
		@dealbtypeid	VARCHAR(100),--结算单位
		@cid			VARCHAR(100),
		@rate			VARCHAR(100),
		@GoodsNumber	VARCHAR(100),
		@intQtyDot		INT,
		@cefullname		VARCHAR(500)='',
		@dfullname		VARCHAR(500)=''
		
		
SET @rowcount=0
SET @maxcount=500
SET @pagecount=0

--数量的小数位数
EXEC	@intQtyDot=Gp_GetDigit 1
		
CREATE TABLE #billnumberid(ID VARCHAR(MAX))

DECLARE @billtype	VARCHAR(10)
SET @billtype='11'
--取当前时间
SET @billdate=GETDATE()
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
SET @billdate=(SELECT CONVERT (VARCHAR(10),@billdate,120))

SET @SQL='
DECLARE indexcursor CURSOR FOR 
	SELECT  '+@colname+',
			SUM(b.qty-b.ReachQty) AS totalqty,
			ROUND(SUM((b.qty-b.ReachQty)*taxprice),2) AS totalmoney
	FROM	#MANTYPE a
	INNER JOIN ORDERINDEX I ON  I.Stypeid=a.stypeid AND ISNULL(I.dealbtypeid,'''')=ISNULL(a.dealbtypeid,'''') AND ISNULL(I.btypeid,'''')=ISNULL(a.btypeid,'''') and (a.dtypeid='''' or I.dtypeid=a.dtypeid) AND (a.etypeid='''' OR I.etypeid=a.etypeid) AND (a.ktypeid='''' OR I.ktypeid=a.Ktypeid)
	INNER JOIN OrderBill B ON I.billNumberId=B.billNumberID
	WHERE (b.qty-b.ReachQty)<>0 and B.OrderID IN (SELECT *FROM f_split('''+@orderid+''','','')) 
	GROUP BY '+@GroupByCol

EXEC (@SQL)

OPEN indexcursor

FETCH NEXT FROM indexcursor INTO	@GoodsNumber,
									@rate,
									@cid,
									@sTypeID,
									@BTypeID,
									@dealbtypeid,
									@dtypeid,
									@eTypeID,
									@kTypeID,
									@totalqty,
									@totalmoney--@tax


WHILE @@FETCH_STATUS=0
BEGIN
	--是否自定义单据编号
	IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =11)
	BEGIN
		SELECT @MONTH = typeid  FROM employee WHERE typeId=@ETypeId
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.TypeId FROM Employee E WHERE E.TypeId = @OperatorID
		SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId = @dtypeid
	END
		
	SELECT @rowcount=COUNT(1)
	FROM	OrderBill a
	INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
	WHERE	A.OrderID IN (SELECT * FROM f_split(@orderid,','))
	AND		I.Stypeid=@Stypeid
	AND		ISNULL(I.dealbtypeid,'')=ISNULL(@dealbtypeid,'')
	AND		ISNULL(I.DtypeId,'')=ISNULL(@dtypeid,'')
	AND		(@Etypeid='' OR I.Etypeid=@Etypeid)
	AND		(@Ktypeid='' OR I.Ktypeid=@Ktypeid)
	AND		(a.qty-a.ReachQty)<>0
	
	SET @pagecount=@rowcount/@maxcount+1

	IF @rowcount%500=0
		SET @pagecount=@pagecount-1

	WHILE(@pagecount>0)
	BEGIN
		--生成单据编号
		EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'XK',@billdate,@STypeId,@billcode OUT,@dfullname,@cefullname,-999

		--主表数据写入
		SET @BillNumberId = 0
		
		INSERT INTO #atypeid1
		        ( id, NAME,flag )
		EXEC dbo.Web_GetAtype @billtypeid = @billtype, -- varchar(50)
		    @stypeid = @stypeid -- varchar(50)
		
		SELECT @atypeid1=id FROM #atypeid1
		
		DECLARE @recvalue INT=0		
		EXEC @recvalue=Gp_InsertBillIndex 
					@BillDate=@billdate,
					@BillCode=@billcode,
					@BillType=@billtype,
					@Comment='未完成的销售订单生成的WMS销售出库单',
					@ATypeID='',
					@PTypeID='',
					@BTypeID=@btypeid,
					@ETypeID=@etypeid,
					@KTypeID=@ktypeid,
					@KTypeID2='',
					@IfCheck='f',
					@CheckE=@OperatorID,
					@TotalMoney=@totalmoney,
					@TotalQty=@totalqty,
					@TotalInMoney=0,
					@Tax='0',
					@szPeriod=1,
					@Explain='',
					@Draft='True',
					@RedWord='False',
					@OrderID=0,
					@WayBillCode='',
					@Goodsnumber=@GoodsNumber,
					@PackWay='',
					@Tel='',
					@preferencemoney=0,
					@AlertDay=9999,
					@Assessor='',
					@IfAudit='',
					@Audit_Explain='',
					@Dtypeid=@dtypeid,
					@VipCardID=-1,
					@KTypeID3='',
					@LinkMan='',
					@LinkTel='',
					@LinkAddr='',
					@wxManID='',
					@JieJianBillNumberID=-1,
					@JieJianID=-1,
					@BaoXiuBillNumberID=-1,
					@BaoXiuID=-1,
					@BuyDate='',
					@Serial='',
					@wxTotal=0,
					@ErrDes='',
					@ifHideJieJian=0,
					@ifWX=0,
					@IfBargainOn=0,
					@STypeID=@stypeid,
					@FromBillNumberID=0,
					@CostSale=0,
					@completedate='9999-12-31 23:59:59',
					@billstate=1,
					@ifmulaccount=0,
					@vipczmoney=0,
					@otherinouttype=-1,
					@czbeforetimes=0,
					@posbilltype=0,
					@TransportId=0,
					@IsFreightMoney=0,
					@FreightAddr=NULL,
					@freightperson=NULL,
					@freighttel=NULL,
					@ShareMode=0,
					@uf1='',
					@uf2='',
					@uf3='',
					@uf4='',
					@uf5='',
					--9.0新字段
					@dealbtypeid=@dealbtypeid,		--结算单位
					@cid=@cid,			--外币币种id
					@rate=@rate,			--汇率
					@ntotalmoney=@totalmoney,		--原币种金额
					@ntotalinmoney=0,	--原币收现金额
					@npreferencemoney=0,	--原币优惠金额
					@nvipczmoney=0,		--原币会员卡充值金额
					@atypeid1=@atypeid1,
					@billproperty=-1,					--单据属性
					@ncompletetotal	=0,		--原币结算金额
					@isini=0,
					@ATID=0,					--过账模板
					@CompleteTotal=0,
					@IfCargo=0,
					@IfInvoice=0,
					@promoruleid=0,
					@beforepromobillnumberid=0,
					@promotionmsg='',
					@isyapi=0,
					@yapiorderid=0	,
					@DeliveryAddress='',
					@Discount=1,
					@AdpriceType=0,	
					@checkSave='bill_allow_save'
					
		 IF @recvalue = -1 
			BEGIN
				--RAISERROR('试用版最多录200条单据！',16,1)
				SET @errormsg = '试用版最多录200条单据！'
				RETURN
			END
		 IF @recvalue = -2 
			BEGIN
				--RAISERROR('录单日期小于本期开始日期！',16,1)
				SET @errormsg = '录单日期小于本期开始日期！'
				RETURN
			END
		 IF @recvalue = -3 
			BEGIN
				--RAISERROR('校验错误 ！',16,1)
				SET @errormsg = '校验错误 ！'
				RETURN
			END
		 IF @recvalue = -4
			BEGIN
				--RAISERROR('录单日期必须与当前日期一致！',16,1)
				SET @errormsg = '录单日期必须与当前日期一致！'
				RETURN
			END
		 IF @recvalue = -5 
			BEGIN
				--RAISERROR('更新单据发生错误！',16,1)
				SET @errormsg = '更新单据发生错误！'
				RETURN
			END

		
		SET @BillNumberId = @recvalue

		IF @BillNumberId IS NULL
			RETURN -10
			
		--写单据操作日志
		INSERT INTO BillOperateLog(billnumberid,operatetype,etypeid,OperateTime,ip) values(@BillNumberId,'制单',@OperatorID,GETDATE(),@clientip)

		--保存单据编号的种子数
		EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
		
		INSERT INTO #billnumberid (ID) VALUES(@BillNumberId)
		--明细表数据写入
		INSERT INTO SaleBill 
		(
			[BillNumberId],
			[PtypeId],
			[Qty],
			[SalePrice],
			[discount],
			[DiscountPrice],
			[jobnumber],
			[total],
			[OutFactoryDate],
			[TaxPrice],
			[TaxTotal],
			[comment],
			OrderID,
			[isUnit2],
			[Serial],
			[GoodsNumber],
			[ProduceDate],
			[ValidDate],
			[GoodsBTypeID],
			Tax,
			SaleTotal,
			KTypeID,
			STypeID,--,ShareFee
			ItemID,--自由项id
			CargoID,
			CurMDiscountPrice,
			CurMSalePrice,
			CurMTaxPrice,
			UnitID,
			UnitRate,
			NTotal,
			TaxMoney,
			NDiscountPrice,
			NQty,
			NSalePrice,
			NSaleTotal,
			NTaxMoney,
			NTaxPrice,
			NTaxTotal,
			NUnitID,
			NUnitMsg,
			MDiscountPrice,
			MQty,
			MSalePrice,
			MTaxPrice,
			MUnitID,
			MUnitMsg,
			MUnitRate,
			IsCombined,
			pricesource,
			promotype,
			goodscostprice,
			ETypeID
		)
		SELECT TOP (@maxcount) * 
		FROM
		(	SELECT TOP (@rowcount-@maxcount*(@pagecount-1)) *
			FROM (
					SELECT	TOP (@maxcount*@pagecount)
							@BillNumberId AS BillNumberId,
							a.ptypeid AS ptypeid,
							(a.qty-a.ReachQty) AS qty,
							a.price AS saleprice,
							a.Discount AS discount,
							a.DiscountPrice AS discountprice,
							'' AS jobnumber,
							CASE 
								WHEN a.reachqty = 0 THEN a.total
								ELSE ROUND((a.qty-a.ReachQty)*a.DiscountPrice,2)
							END AS total,
							@billdate AS OutFactoryDate,
							a.TaxPrice AS taxprice,
							CASE
								WHEN a.reachqty = 0 THEN a.TaxTotal
								ELSE ROUND((a.qty-a.ReachQty)*a.TaxPrice,2)
							END AS TaxTotal,
							I.Billcode AS comment,--983 540 测试提的bug
							a.OrderID AS orderid,
							a.IsUnit2 AS isunit2,
							'' AS serial,
							a.GoodsNumber,
							a.ProduceDate AS ProduceDate,
							a.ValidDate AS ValidDate,
							'' AS GoodsBTypeID,
							a.Tax AS tax,
							CASE
								WHEN a.reachqty = 0 THEN a.saletotal
								ELSE ROUND((a.qty-a.ReachQty)*a.price,2)
							END AS saletotal,
							CASE @ifktype 
								WHEN '1' THEN a.KTypeID
								ELSE @ktypeid END AS ktypeid,
							a.Stypeid AS stypeid,--,'' AS ShareFeeBill
							a.ItemID,
							--a.CargoID,
							CASE @ifktype WHEN '1' THEN a.CargoID ELSE NULL END AS cargoid,
							
							a.curmdiscountprice AS curmdiscountprice,--大单位原币折后价
							a.curmsaleprice as curmsaleprice,--大单位原币单价
							a.curmtaxprice AS curmtaxprice,--大单位原币含税价
							a.UnitID,
							a.UnitRate,
							CASE
								WHEN a.reachqty = 0 THEN a.ntotal
								--ELSE a.NTotal*(1-a.ReachQty/a.qty)
								ELSE ROUND((a.qty-a.ReachQty)*a.nDiscountPrice,2)
							END AS ntotal,
							a.TaxMoney,--本币税额
							a.NDiscountPrice,--原币折后单价
							a.NQty*(1-a.ReachQty/a.qty) AS nqty,
							a.NSalePrice,--原币单价
							CASE
								WHEN a.reachqty = 0 THEN a.nsaletotal
								ELSE ROUND((a.qty-a.ReachQty)*a.NSalePrice,2)
							END AS nsaletotal,--原币金额
							a.NTaxMoney,--原币税额
							a.NTaxPrice,--原币含税单价
							CASE
								WHEN a.reachqty = 0 THEN a.ntaxtotal
								ELSE ROUND((a.qty-a.ReachQty)*NTaxPrice,2)
							END AS ntaxtotal,						--原币价税合计
							a.NUnitID,
							a.NUnitMsg,
							a.MDiscountPrice AS MDiscountPrice,--大单位折后价							
							ROUND((a.Qty-a.ReachQty)/isnull(a.MunitRate,1),@intQtyDot) AS mqty,--大单位数量
							a.MSalePrice,--大单位单价
							a.MTaxPrice,--大单位含税价
							a.munitid ,
							a.MUnitMsg,
							a.MunitRate,
							a.IsCombined,
							'来自销售订单生成：['+a.pricesource+']' AS pricesource,
							a.promotype,
							-1 as goodscostprice,
							I.etypeid
					FROM	OrderBill a
					INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
					WHERE	
						A.OrderID IN (SELECT *FROM f_split(@orderid,','))
						AND I.GoodsNumber=@GoodsNumber
						AND I.Rate=@rate 
						AND I.CID=@cid
						AND	I.Stypeid=@Stypeid
						AND I.btypeid=@btypeid
						AND I.DtypeId=@dtypeid
						AND	ISNULL(I.dealbtypeid,'')=ISNULL(@dealbtypeid,'')
						AND	(@Etypeid='' OR I.Etypeid=@Etypeid)
						AND	(@Ktypeid='' OR I.Ktypeid=@Ktypeid)
						AND	(a.qty-a.ReachQty)<>0
					ORDER BY a.OrderID
					) A 
			ORDER BY A.orderid DESC) B 
		ORDER BY B.orderid
		
		UPDATE dbo.SaleBill SET ShowOrder=ID WHERE BillNumberId=@BillNumberId
		SET @pagecount=@pagecount-1
		
		-- 自动生成的单据会影响草稿库存
		EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,@billtype
	END
	---读取下一行数据
	FETCH NEXT FROM indexcursor INTO	@GoodsNumber,
										@rate,
										@cid,
										@sTypeID,
										@BTypeID,
										@dealbtypeid,
										@dtypeid,
										@eTypeID,
										@kTypeID,
										@totalqty,
										@totalmoney--,@tax		
END
CLOSE indexcursor
DEALLOCATE  indexcursor

UPDATE OrderBill SET WaitQty=WaitQty+qty-ReachQty WHERE	OrderID IN (SELECT *FROM f_split(@orderid,',')) 

SELECT BillCode AS billcode FROM BillIndex BI
INNER JOIN #billnumberid B ON  BI.BillNumberId=B.ID

DROP TABLE #MANTYPE,#atypeid1,#DraftGoodsStocks,#OrderBillNumberID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_Save_WdConfig]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_Save_WdConfig];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2016-11-20
	描述：保存网店配置信息
*/
CREATE PROCEDURE Gp_Save_WdConfig
    (
      @billSummary VARCHAR(200) ,	-- 摘要
      @DirectPost VARCHAR(10) ,	-- 直接过账
      @InventoryRefreshIntime VARCHAR(10) ,			-- 库存实时更新
      @BaseInfoRefresh VARCHAR(10) ,			-- 基本信息实时更新
      @autoSync VARCHAR(10) ,			-- 自动下载
      @refreshTime VARCHAR(50),	-- 下载时间间隔
      @collectBill VARCHAR(50), --汇总生成单据
      --@goodsPrice VARCHAR(50)--单据商品单价
      @addsync VARCHAR(10),
      @batchnumberdeal INT, --批次号处理
      @isUse1688		VARCHAR(10) = '',		--启用1688
      @dpl1688id		VARCHAR(200)= '',		--1688ID
      @dpl1688name		VARCHAR(200)= '',		--dpl1688Name
      @dpdw				VARCHAR(10) = '0',		--上传默认单位  0.小单位 1.销售单位
      @dmf				VARCHAR(10) = '',		--默认收款账户
      @markername		VARCHAR(200) = ''		--专业市场代码
    )

--@encode$--
AS
    SET NOCOUNT ON;

    BEGIN
        IF EXISTS ( SELECT  *
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'SummaryItem' )
            UPDATE  WdShopBaseInfo
            SET     Value = @billSummary
            WHERE   Field = 'SummaryItem';
        ELSE
            INSERT  INTO WdShopBaseInfo
                    ( Field, Value )
            VALUES  ( 'SummaryItem', @billSummary ); 
            
        IF EXISTS ( SELECT  *
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'DirectPost' )
            UPDATE  WdShopBaseInfo
            SET     Value = @DirectPost
            WHERE   Field = 'DirectPost';
        ELSE
            INSERT  INTO WdShopBaseInfo
                    ( Field, Value )
            VALUES  ( 'DirectPost', @DirectPost );
            
        IF EXISTS ( SELECT  *
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'InventoryRefreshIntime' )
            UPDATE  WdShopBaseInfo
            SET     Value = @InventoryRefreshIntime
            WHERE   Field = 'InventoryRefreshIntime';
        ELSE
            INSERT  INTO WdShopBaseInfo
                    ( Field ,
                      Value
                    )
            VALUES  ( 'InventoryRefreshIntime' ,
                      @InventoryRefreshIntime
                    );
                    
        IF EXISTS ( SELECT  *
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'BaseInfoRefresh' )
            UPDATE  WdShopBaseInfo
            SET     Value = @BaseInfoRefresh
            WHERE   Field = 'BaseInfoRefresh';
        ELSE
            INSERT  INTO WdShopBaseInfo
                    ( Field ,
                      Value
                    )
            VALUES  ( 'BaseInfoRefresh' ,
                      @BaseInfoRefresh
                    );
                    
        IF EXISTS ( SELECT  *
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'autoSync' )
            UPDATE  WdShopBaseInfo
            SET     Value = @autoSync
            WHERE   Field = 'autoSync';
        ELSE
            INSERT  INTO WdShopBaseInfo
                    ( Field, Value )
            VALUES  ( 'autoSync', @autoSync );
            
        IF EXISTS ( SELECT  *
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'refreshTime' )
            UPDATE  WdShopBaseInfo
            SET     Value = @refreshTime
            WHERE   Field = 'refreshTime'; 
        ELSE
            INSERT  INTO WdShopBaseInfo
                    ( Field, Value )
            VALUES  ( 'refreshTime', @refreshTime );  
            
        IF EXISTS ( SELECT  *
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'collectBill' )
            UPDATE  WdShopBaseInfo
            SET     Value = @collectBill
            WHERE   Field = 'collectBill'; 
        ELSE
            INSERT  INTO WdShopBaseInfo
                    ( Field, Value )
            VALUES  ( 'collectBill', @collectBill );  
            
        IF EXISTS ( SELECT  *
                    FROM    WdShopBaseInfo
                    WHERE   Field = 'addsync' )
            UPDATE  WdShopBaseInfo
            SET     Value = @addsync
            WHERE   Field = 'addsync';
        ELSE
            INSERT  INTO WdShopBaseInfo
                    ( Field, Value )
            VALUES  ( 'addsync', @addsync ); 
            
		UPDATE dbo.WdShopBaseInfo SET Value = @batchnumberdeal WHERE Field = 'BatchNumberDeal';  
		
		UPDATE WdShopBaseInfo SET Value = @isUse1688 WHERE Field = 'isUse1688'
		UPDATE WdShopBaseInfo SET Value = @dpl1688id WHERE Field = 'dpl1688id'
		UPDATE WdShopBaseInfo SET Value = @dpl1688name WHERE Field = 'dpl1688name'
		UPDATE WdShopBaseInfo SET Value = @dpdw WHERE Field = 'dpdw'	
		UPDATE WdShopBaseInfo SET Value = @dmf WHERE Field = 'dmf'
		UPDATE WdShopBaseInfo SET Value = @markername WHERE Field = 'markername'
    END;


GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveAc_VoucherBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SaveAc_VoucherBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014-04-13
	描述：凭证明细保存
*/
CREATE PROCEDURE GP_SaveAc_VoucherBill
(
	@billnumberid		NUMERIC(18,0),			--单据ID
	@summary			VARCHAR(400)='',		--摘要
	@atypeid			VARCHAR(50),			--会计科目
	@atypeid2			VARCHAR(50)='',			--对方会计科目
	@fdc				INT,					--借贷方向,1.借方 -1.贷方
	@f_exchidfor		VARCHAR(50)='',			--外币
	@fdebittotal		 NUMERIC(24, 10) =0,		--借方本币金额
	@fcredittotal		 NUMERIC(24, 10) =0,		--贷方本币金额
	@fdebittotalfor		 NUMERIC(24, 10) =0,		--借方原币金额
	@fcredittotalfor	 NUMERIC(24, 10) =0,		--贷方原币金额
	@fcashflowitem		INT=0,					--现金流量项目
	@fsettleno			VARCHAR(200)='',		--结算号
	@fsettletypeid		INT=NULL,				--结算方式
	@comment			VARCHAR(500)='',		--备注
	@rowno				INT,					--分录号
	@cid				INT,					--币别
	@rate				 NUMERIC(24, 10) ,			--汇率
	@fadc				INT,					--分录借贷方向
	@stypeid			VARCHAR(50),			--分支机构
	@billdate			DATETIME,				--凭证日期
	@oldbillnumberid	INT=0,					--原凭证编号
	@fsettledate		DATETIME=NULL,			--结算日期
	@fdebitqty			NUMERIC(24,10)=0,
	@fcreditqty			NUMERIC(24,10)=0
)
--@encode$--
AS
SET NOCOUNT ON

IF @fsettledate = ''
	SET @fsettledate = NULL

--取会计期间
DECLARE @fyear INT,@fperiod INT

SELECT @fyear = FYear,@fperiod = FPeriod FROM dbo.Ac_Period WHERE @billdate >= FBegin AND @billdate <= FEnd

DECLARE	 @f_exchid		VARCHAR(50)			--本币
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

DECLARE @AdjustAccounts	INT
SELECT @AdjustAccounts = AdjustAccounts FROM Ac_Account WHERE StypeId = @stypeid and TypeId = @atypeid

IF @AdjustAccounts = 0
BEGIN
	SET @fdebitqty = 0
	SET @fcreditqty	= 0
END


INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FCreditTotal ,
          FDebitTotalFor,
          FCreditTotalFor,
          FCashFlowItem ,
          FSettleNo ,
          FSettleTypeID,
          FSettleDate,
          Comment,
          RowNo,
          Cid,
          Rate,
          fadc,
          stypeid,
          fyear,
          fperiod,
          fdebitqty,
          fcreditqty
        )
VALUES  ( 	@billnumberid,
			@summary,
			@atypeid,
			@atypeid2,
			@fdc,			
			@f_exchid,			
			@f_exchidfor,	
			dbo.F_RoundTotal(@fdebittotal),
			dbo.F_RoundTotal(@fcredittotal),
			dbo.F_RoundTotal(@fdebittotalfor),
			dbo.F_RoundTotal(@fcredittotalfor),
			@fcashflowitem,			
			@fsettleno,		
			@fsettletypeid,	
			@fsettledate,
			@comment,
			@rowno,
			@cid,
			@rate,
			@fadc,
			@stypeid,
			@fyear,
			@fperiod,
			@fdebitqty,
			@fcreditqty
        )
        
        
IF @@ROWCOUNT = 0
	RAISERROR('保存凭证明细失败！',16,1)

RETURN SCOPE_IDENTITY();

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveAc_VoucherIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SaveAc_VoucherIndex]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012-04-12
	描述：凭证索引保存
*/
CREATE PROCEDURE GP_SaveAc_VoucherIndex
(
	@stypeid			VARCHAR(50),		--分支机构
	@vgid				INT,				--凭证字ID			
	@billdate			DATETIME,			--凭证日期
	@billcode			VARCHAR(400)='',	--单据编号
	@flowno				INT=0,				--流水号
	@attachfilecount	INT=0,				--附件数
	@tallyid			VARCHAR(50)='',		--记账人
	@fchecked			INT=0,				--是否审核 0.未审核 1.已审核 -1.作废
	@auditid			VARCHAR(50)='',		--审核人
	@etypeid			VARCHAR(50),		--制单人
	@recheckid			VARCHAR(50)='',		--复核人
	@markerror			VARCHAR(200)='',	--错误信息
	@fcredittotal		NUMERIC(24, 10)=0,	--贷方合计
	@fdebittotal		NUMERIC(24, 10)=0,	--借方合计
	@fentrycount		INT=0,				--分录数
	@fmodifytime		DATETIME='',	--修改时间
	@fcomment			VARCHAR(400)= '',	--备注
	@ffootnote			VARCHAR(400)= '',	--批注
	@audited			INT = 0,			--是否过账 0.未过账 1.已过账
	@ifcheck			VARCHAR(1) = 'f',	--是否过账 t.是 f.否
	@oldbillnumberid	INT=0,				--凭证编号，0表示新凭证
	@type				INT=0,				--凭证类型：0.手工录入 1.期末调汇 2.结转损益 3.业务单据生成 7.出纳
	@IsCommission		INT=0				--1.提成单 3:优惠券
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********
DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -1

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)
-- ********	判断是否试用版 - END	********

DECLARE @Re int,@Flag int
EXEC @Re=Gp_Validate 2, @Flag OUTPUT
IF @Re <>0 RETURN -3 --检查程序版本错误

IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
BEGIN
	--RAISERROR('校验错误 ！',16,1) 
	RETURN -3 --检查程序版本错误
END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM Ac_Voucher
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -1
	END
END

--9.4 对资金调拨生成凭证，保存时，校验与总账联用时期间应一致
IF @type = 7
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @stypeid AND IsConnect = 1)
		AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period T1 
				INNER JOIN dbo.Ac_AccountsPeroid_Stype T2 ON T1.STypeId = T2.Stypeid AND T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod)
	BEGIN
		RAISERROR('出纳当前期间与总账期间不一致，不能保存凭证',16,1)
		RETURN -4
	END
END


--取会计期间
DECLARE @fyear		INT,
		@fperiod	INT
		
--SELECT @fyear = SubValue FROM sysdata WHERE SubName = 'FYear'		
--SELECT @fperiod = SubValue FROM sysdata WHERE SubName = 'Period'		

SELECT @fyear = FYear,@fperiod = FPeriod FROM dbo.Ac_Period WHERE @billdate >= FBegin AND @billdate <= FEnd

--自动补断号配置
DECLARE @config INT


SELECT @config = SubValue FROM sysdata WHERE SubName = 'acvhflowno'

IF @oldbillnumberid = 0
	--凭证号重复，重新获取
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE FlowNo = @flowno AND FYear = @fyear AND FPeriod = @fperiod AND STypeId = @stypeid AND VgId = @vgid)OR @flowno = 0
	BEGIN
		IF @config = 0
			SELECT @flowno = ISNULL(MAX(flowno),0)+1  FROM AC_VOUCHER WHERE FYear = @fyear AND FPeriod = @fperiod AND STypeId = @stypeid AND VgId = @vgid
		ELSE--补断号
		BEGIN
			SELECT FlowNo,FYear,FPeriod,VgId,STypeId
			INTO #tmpAc
			FROM dbo.Ac_Voucher
			WHERE FYear=@fyear AND FPeriod=@fperiod AND VgId=@vgid AND STypeId=@stypeid
			UNION
			SELECT 0 AS flowno, @fyear,@fperiod,@vgid,@stypeid
			
			SELECT @flowno = ISNULL(MIN(flowno+1),1)
			FROM #tmpAc 
			WHERE (NOT((flowno+1)IN(SELECT flowno from #tmpAc WHERE FYear=@fyear AND FPeriod=@fperiod AND VgId=@vgid AND STypeId=@stypeid)))
			
			DROP TABLE #tmpAc
		END
			
	END
	
IF @oldbillnumberid < 1
BEGIN

	BEGIN TRAN insertTranNew--开始事务
	INSERT INTO dbo.Ac_Voucher
        ( STypeId ,
          VgId ,
          BillDate ,
          BillCode ,
          FlowNo ,
          AttachFileCount ,
          TallyId ,
          FChecked ,
          AuditId ,
          ETypeId ,
          FYear ,
          FPeriod ,
          MarkError ,
          FCreditTotal ,
          FDebitTotal ,
          FEntryCount ,
          FModifyTime ,
          FComment ,
          FFootNote ,
          Audited ,
          FSerialNum ,
          ReCheckId ,
          IfCheck,
          VoucherType,
          IsCommission
        )
	VALUES  ( @stypeid , -- STypeId - varchar(50)
			  @vgid , -- VgId - int
			  @billdate , -- BillDate - datetime
			  @billcode , -- BillCode - varchar(400)
			  @flowno , -- FlowNo - int
			  @attachfilecount , -- AttachFileCount - int
			  @tallyid, -- TallyId - varchar(50)
			  @fchecked , -- FChecked - int
			  @auditid , -- AuditId - varchar(50)
			  @etypeid , -- ETypeId - varchar(50)
			  @fyear , -- FYear - varchar(10)
			  @fperiod , -- FPeriod - int
			  @markerror , -- MarkError - varchar(200)
			  dbo.F_RoundTotal(@fcredittotal) , -- FCreditTotal - numeric
			  dbo.F_RoundTotal(@fdebittotal) , -- FDebitTotal - numeric
			  @fentrycount , -- FEntryCount - int
			  GETDATE() , -- FModifyTime - datetime
			  @fcomment , -- FComment - varchar(400)
			  @ffootnote , -- FFootNote - varchar(400)
			  @audited , -- Audited - int
			  0,  -- FSerialNum - int
			  @recheckid,
			  @ifcheck,
			  @type,
			  @IsCommission
			)
	        
	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN insertTranNew
		RAISERROR('保存凭证失败，请确认！',16,1)
		RETURN -1
	END
	
	COMMIT TRAN insertTranNew

	DECLARE @voucherid INT
	SET @voucherid = SCOPE_IDENTITY();
	
	IF EXISTS (SELECT TOP 1 FlowNo FROM Ac_Voucher WHERE FlowNo = @flowno AND FYear = @fyear AND FPeriod = @fperiod AND STypeId = @stypeid AND VgId = @vgid  GROUP BY flowno,STypeId,FYear,FPeriod HAVING COUNT(flowno) >1)
	BEGIN
		IF @config = 0
			SELECT @flowno = ISNULL(MAX(flowno),0)+1  FROM AC_VOUCHER WHERE FYear = @fyear AND FPeriod = @fperiod AND STypeId = @stypeid AND VgId = @vgid
		ELSE--补断号
		BEGIN			
			SELECT @flowno = ISNULL(MIN(flowno+1),1)
			FROM Ac_Voucher 
			WHERE  FYear = @fyear AND FPeriod = @fperiod AND STypeId = @stypeid AND VgId = @vgid 
				AND (NOT((flowno+1)IN(SELECT flowno from Ac_Voucher WHERE FYear=@fyear AND FPeriod=@fperiod AND VgId=@vgid AND STypeId=@stypeid)))
		END
		UPDATE Ac_Voucher SET FlowNo = @flowno
		WHERE BillNumberId = @voucherid 
	END
	--返回单据编号
	RETURN @voucherid;
	--返回单据编号
	--RETURN SCOPE_IDENTITY();
END
ELSE
BEGIN
	BEGIN TRAN insertTranOld--开始事务
	UPDATE dbo.Ac_Voucher
	SET 
		  STypeId = @stypeid,
          VgId  = @vgid,
          BillDate = @billdate,
          BillCode = @billcode,
          FlowNo  = @flowno,
          AttachFileCount = @attachfilecount,
          TallyId  = @tallyid,
          FChecked = @fchecked,
          AuditId  = @auditid,
          ETypeId  = @etypeid,
          FYear  = @fyear,
          FPeriod = @fperiod,
          MarkError = @markerror,
          FCreditTotal = dbo.F_RoundTotal(@fcredittotal),
          FDebitTotal = dbo.F_RoundTotal(@fdebittotal),
          FEntryCount = @fentrycount,
          FModifyTime = GETDATE(),
          FComment = @fcomment,
          FFootNote = @ffootnote,
          Audited = @audited,
          ReCheckId = @recheckid,
          IfCheck = @ifcheck
	WHERE BillNumberId = @oldbillnumberid
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN insertTranOld
		RETURN -1
	END

	COMMIT TRAN insertTranOld
	--如果更改了期间，现金流量明细这个期间也要修改
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_CashMoneyItems WHERE BillNumberId=@oldbillnumberid)
	BEGIN
	     UPDATE Ac_Voucher_Bill_CashMoneyItems SET FPeriod = @fperiod 	WHERE BillNumberId = @oldbillnumberid
	END 	
	RETURN @oldbillnumberid
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_SaveAcAccount]')
                    AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_SaveAcAccount] ;
GO

SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO

----========================
----作者：喻堂
----日期：2012-04-13
----描述：会计科目新增/保存
----========================
CREATE    PROCEDURE [dbo].[Gp_SaveAcAccount]
(
	 @typeid VARCHAR(50),
	 @stypeid VARCHAR(50),
	 @ParId VARCHAR(50),
	 @UserCode VARCHAR(200),
	 @FullName VARCHAR(200),
	 @Pycode VARCHAR(200),
	 @Name VARCHAR(200),
	 @fdc INT,
	 @iscash INT,
	 @isbank INT,
	 @isdiary INT,
	 @etypeid VARCHAR(200),
	 @mainitems VARCHAR(200),
	 @additionitems VARCHAR(200),
	 @isother INT,
	 @cid INT,
	 @ascids VARCHAR(200),
	 @group INT,
	 @fadjustrate INT,
	 @fcontact    INT,
	 @checktype   INT,
	 @chvoperator VARCHAR(50),
	 @AdjustAccounts	BIT,--数量核算
	 @UnitID			INT,--计量单位
	 @AcID			INT--科目表ID 
)
--@encode$--
AS 
SET NOCOUNT ON ;

DECLARE @leveal INT ;
DECLARE @fleveal INT ;

IF EXISTS(SELECT 1 FROM Ac_Account WHERE TypeId=@Parid AND Deleted=1 AND StypeId=@stypeid )
BEGIN
	 RAISERROR ( '父节点已停用不能分类。', 16, 1) RETURN -1
END

IF @stypeid<>'00000' AND NOT EXISTS(SELECT 1 FROM F_TreeAccount(@chvoperator,@stypeid) WHERE TypeId=@Parid)
BEGIN
	RAISERROR ('你没有当前操作的多级权限范围，请确认后重试', 16, 1)
END


----V3标示
DECLARE @ISv3 INT SET @ISv3=(SELECT  SubValue FROM sysdata WHERE SubName='ProInfo'  )


SET @fleveal = LEN(@ParId) / 5 ;
SET @leveal = @fleveal + 1 ;

IF @typeid IS NULL 
    SET @typeid = '' ;
    
    
IF @ParId = '00000' AND @ISv3<>1 
    BEGIN
        RAISERROR ( '不允许新建分类。', 16, 1 ) ;
        RETURN -1 ;
    END
    
-- 判断重复的UserCode
IF EXISTS ( SELECT  TypeID
            FROM    Ac_Account
            WHERE   usercode = @UserCode
                    AND typeid <> @typeid
                    AND stypeid = @stypeid ) 
    BEGIN
        RAISERROR ( '该编号[%s]已经存在，会计科目编号不能相同。', 16, 1, @UserCode ) ;
        RETURN -1 ;
    END

DECLARE @needParent INT 

IF NOT EXISTS ( SELECT  1
                FROM    Ac_Account
                WHERE   TypeId = @ParId
                        AND stypeid = @stypeid ) 
    BEGIN
        IF @parid NOT IN ('00001','00002','00003','00004','00005','00006') AND LEN(@typeid) > 0
        BEGIN
            RAISERROR ( '父节点信息[%s]不存在。', 16, 1, @Parid ) ;
            RETURN -1 ;
        END
        
        SET @needParent = 1
    END
    
    
IF NOT EXISTS ( SELECT  1
                FROM    Ac_Account
                WHERE   TypeId = @parid
                        AND @UserCode LIKE usercode + '%'
                        AND stypeid = @stypeid ) 
    BEGIN
        DECLARE @prefix VARCHAR(50) ;
        SELECT  @prefix = usercode
        FROM    Ac_Account
        WHERE   typeid = @parid
                AND stypeid = @stypeid ;
        
        RAISERROR ( '编码必须以[%s]开头.', 16, 1, @prefix ) ;
        RETURN -1 ;
    END
    
DECLARE @lenthisLeveal INT ;
DECLARE @sql NVARCHAR(MAX) ;

SET @sql = '
DECLARE @len1 INT,
    @len2 INT,
    @len3 INT,
    @len4 INT,
    @len5 INT,
    @len6 INT,
    @len7 INT,
    @len8 INT,
    @len9 INT,
    @len10 INT ;
    
SELECT  @len1 = Len1,
        @len2 = Len2 + @len1,
        @len3 = Len3 + @len2,
        @len4 = Len4 + @len3,
        @len5 = Len5 + @len4,
        @len6 = Len6 + @len5,
        @len7 = Len7 + @len6,
        @len8 = Len8 + @len7,
        @len9 = Len9 + @len8,
        @len10 = Len10 + @len9
        FROM Ac_Table;

SELECT TOP 1 @lenthisLeveal = @len'
    + CAST(@fleveal AS VARCHAR(10)) ;

EXEC SP_EXECUTESQL @sql,
    N'@lenthisLeveal varchar(2000) output',
    @lenthisLeveal OUTPUT ;

    --为null的原因是添加的层次超出了预定
IF @lenthisLeveal IS NULL 
    BEGIN
        RAISERROR ( "添加的科目超出科目表中设置，请检查", 16, 1 ) ;
        RETURN -1 ;
    END

IF @lenthisLeveal <> LEN(@UserCode) 
    BEGIN
        RAISERROR ( "编码长度不正确，应该为[%d]位.", 16, 1, @lenthisLeveal ) ;
        RETURN -1 ;
    END


SELECT  a AS ascids
INTO    #temp_ascids
FROM    dbo.f_split(@ascids, ',') ;

CREATE TABLE #temp_currency
(
cid INT
);

IF @cid = 0 
    BEGIN
        INSERT  INTO #temp_currency
                SELECT  cid
                FROM    Ac_Currency
    END
ELSE 
    BEGIN
        INSERT  INTO #temp_currency
                SELECT  @cid  
    END


IF (SELECT  COUNT(1)
    FROM    #temp_ascids) <> (SELECT    COUNT(DISTINCT ascids)
                              FROM      #temp_ascids) 
    BEGIN
        RAISERROR ( '不能选择相同的辅助核算项目。', 16, 1, @lenthisLeveal ) ;
        RETURN -1 ;
    END


DECLARE @facnt INT
IF EXISTS (SELECT a FROM dbo.f_split(@ascids, ','))
    SET @facnt = 1
ELSE 
    SET @facnt = 0


DECLARE @isuseforeigncurrency INT
DECLARE @syscid INT
SELECT TOP 1 @isuseforeigncurrency = SubValue FROM sysdata WHERE SubName='isforeigncurrency'
SELECT TOP 1 @syscid = cid FROM Ac_Currency WHERE Sysrow = 1
IF @syscid IS NULL OR @isuseforeigncurrency IS NULL OR (@isuseforeigncurrency = 0 AND @syscid <> @cid)
BEGIN
        RAISERROR ( '系统未启用外币核算，不能设置外币核算，保存失败。', 16, 1, @lenthisLeveal ) ;
        RETURN -1 ;
END



DECLARE @exchid INT ;
SET @exchid = 0 ;

IF @cid = (SELECT TOP 1
                    CId
           FROM     Ac_Currency
           WHERE    Sysrow = 1) 
    BEGIN
        SET @exchid = 1 ;	
    END



DECLARE @ThisXiWaNo INT ;
SELECT @ThisXiWaNo = ISNULL(MAX(XiWaMaxNumber),0)+1 FROM Ac_Account 

  
-- 新增
IF LTRIM(RTRIM(@typeid)) = ''
    OR @typeid IS NULL 
    BEGIN
        DECLARE @parentUsed INT
        DECLARE @parentonlystypeused INT
        
--判断是否存在与新建科目同级次的分配下来的科目
        IF @stypeid <> '00000' AND  @ISv3<>1
            AND EXISTS ( SELECT TOP 1
                                1
                         FROM   Ac_Account
                         WHERE  IsDist = 1
                                AND ParId = @parid
                                AND STypeid = @stypeid ) 
            BEGIN
                RAISERROR ( '只能在分配的会计科目的下级新建会计科目。', 16, 1 ) ;
                RETURN -1 ;
            END
    
    
-- 判断重复的UserCode
        IF EXISTS ( SELECT  TypeID
                    FROM    [Ac_Account]
                    WHERE   usercode = @UserCode
                            AND stypeid = @stypeid ) 
            BEGIN
                RAISERROR ( '该编号[%s]已经存在，会计科目编号不能相同。', 16, 1, @UserCode ) ;
                RETURN -1 ;
            END
    
        DECLARE @nRet INT ;
        
        DECLARE @thisUsed1 INT
        SET @thisUsed1 = 0 ;
	    --判断子节点是否被使用
	    EXEC @thisUsed1 = GP_CheckAccountUsage @stypeid = @stypeid,@atypeid = @ParId
	    --新增不需要判断
  --      IF @thisUsed1>0
  --      BEGIN
  --              --判断外币核算
  --              DECLARE @oldcid INT ;
  --              SELECT  @oldcid = cid
  --              FROM    Ac_Account
  --              WHERE   StypeId = @stypeid
  --                      AND TypeId = @ParId ;
            
  --              IF @cid <> @oldcid
  --                  AND @cid <> 0 
  --                  BEGIN
  --                      RAISERROR ( '该会计科目已经在使用中，外币核算只允许从具体币别调整到所有币别。', 16,
  --                              1 ) ;
  --                      RETURN ;
  --                  END
		--END
	-- 获得新的ID号
        EXEC @nRet= Gp_Create_Ac_Account_Id @Stypeid, @ParId,
            'Ac_Account', @typeid OUT, 0, 0

        IF @nRet = -1 
            BEGIN
                RAISERROR ( '科目的分类不能超过10层', 16, 1 )
                RETURN -1 ;
            END
        IF @nRet = -2 
            BEGIN
                RAISERROR ( '无法添加基本信息', 16, 1 )
                RETURN -1 ;
            END
            
            
        IF EXISTS ( SELECT TOP 1
                            1
                    FROM    Ac_Account
                    WHERE   stypeid = @stypeid
                            AND typeid = @typeid ) 
            BEGIN
                RAISERROR ( '系统在生成编号时发生错误，请联系支持人员。', 16, 1 )
                RETURN -1 ;
            END

            		
        BEGIN TRAN
        -- 插入所缺少的分类。
        -- 缺少分类的原因是因为在反分配所有科目后，系统为了父节点能够被正常反分配，需要删除其分类
        -- 就导致在下次插入数据的时候缺少分类
        -- 故需要在此处插入分类
        INSERT INTO Ac_Account (StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,Fdc,IsCash,IsBank,IsDiary,
        Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,
        FintRate,FLeveal,Deleted,XiWaMaxNumber,IsOther,Cid,IsDist,[Group],IsPreGather,IsPrePay,IsGather,IsPay,IsVip,CheckType,AdjustAccounts,UnitID,AcId)
        SELECT * FROM (
            SELECT StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,Fdc,IsCash,IsBank,IsDiary,
            Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,
            FintRate,FLeveal,Deleted,XiWaMaxNumber,IsOther,Cid,IsDist,[Group],IsPreGather,IsPrePay,IsGather,IsPay,IsVip,CheckType,AdjustAccounts,UnitID,AcId
            FROM Ac_Account 
            WHERE 1=2
            UNION ALL 
            SELECT @stypeid, '00001', '00000', 1, 0, 0, '', '资产', '', -1, 0, 0, 0, 
                    '', 'ZC' ,@etypeid, GETDATE(), '', '', -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '100', 0, 0, 0, 0, 0, 0,0,0,@AcID
             UNION ALL
             SELECT @stypeid, '00002', '00000', 1, 0, 0, '', '负债', '', -1, 0, 0, 0, 
                    '', 'FZ' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '200', 0, 0, 0, 0, 0, 0,0,0,@AcID      
             UNION ALL
             SELECT @stypeid, '00003', '00000', 1, 0, 0, '', '损益', '', -1, 0, 0, 0, 
                    '', 'SY' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '500', 0, 0, 0, 0, 0, 0,0,0,@AcID
             UNION ALL
             SELECT @stypeid, '00004', '00000', 1, 0, 0, '', '成本', '', -1, 0, 0, 0, 
                    '', 'CB' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '400', 0, 0, 0, 0, 0, 0,0,0,@AcID
             UNION ALL
             SELECT @stypeid, '00005', '00000', 1, 0, 0, '', '权益', '', -1, 0, 0, 0, 
                    '', 'QY' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '300', 0, 0, 0, 0, 0, 0,0,0,@AcID
             UNION ALL
             SELECT @stypeid, '00006', '00000', 1, 0, 0, '', '共同', '', -1, 0, 0, 0, 
                    '', 'gt' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '700', 0, 0, 0, 0, 0, 0,0,0,@AcID       
         ) t WHERE typeid = @ParId
         AND (NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=t.StypeId AND TypeId=t.TypeId))
    
        INSERT  INTO Ac_Account (StypeId, typeId, Parid,
                                 leveal, soncount, sonnum,
                                 FullName, pycode, Name,
                                 UserCode, FLeveal, Fdc,
                                 IsCash, IsBank, IsDiary,
                                 Comment, ETypeId,
                                 CreateDateTime, MainItems,
                                 AdditionItems, exchid,
                                 IsOther, Cid, FAcnt,
                                 FAdjustRate,[Group],fcontact,checktype, XiWaMaxNumber,AdjustAccounts,UnitID,AcId)
        VALUES  (@stypeid, @typeid, @ParId, @leveal, 0, 0,
                 @fullname, @Pycode, @Name, @UserCode,
                 @fleveal, @fdc, @iscash, @isbank, @isdiary,
                 '',--@comment ,`
                 @etypeid, GETDATE(), @mainitems,
                 @additionitems, @exchid, @isother, @cid,
                 @facnt, @fadjustrate,@group,@fcontact, @checktype,@ThisXiWaNo,@AdjustAccounts,@UnitID,@AcID) ;
                 
		--操作失败，返回-1
        IF @@ROWCOUNT = 0 
            BEGIN
                ROLLBACK TRAN ;
                RETURN -1 ;
            END
        
		--update soncount sonnum
        UPDATE  Ac_Account
        SET     SonNum = (SELECT    COUNT(1)
                          FROM      Ac_Account a
                          WHERE     a.ParId = ac.TypeId
                                    AND a.Leveal = ac.Leveal + 1
                                    AND a.StypeId = ac.StypeId
                         ),
                SonCount = ISNULL(CAST((SELECT MAX(Right(TypeID,5))
                            FROM    Ac_Account a
                            WHERE   a.ParId = ac.TypeId
                                    AND a.Leveal = ac.Leveal + 1
                                    AND a.StypeId = ac.StypeId
                           ) AS int),0),
                           FAcctint = 0,
                           AscIds = '',
                           FInterest = 0,
                           FintRate = 0,
                           --Deleted = 0,	//状态不能改变
                           IsPreGather = 0,
                           IsPrePay = 0,
                           IsGather = 0,
                           IsPay = 0,
                           IsVip = 0
        From Ac_Account ac
        WHERE stypeid = @stypeid;

		--V3保存默认分支机构科目的时候，科目分配标志写为1
		--IF EXISTS(SELECT *FROM sysdata WHERE SubName='ProInfo' AND SubValue='1') AND @stypeid='00001'
		--	UPDATE Ac_Account SET IsDist=1 WHERE StypeId=@stypeid AND TypeId=@TYPEID
		
        --父节点不能有辅助核算项目,搬移至子节点
        UPDATE Ac_Account_Assist_CheckItems SET ATypeId=@typeid WHERE STypeId=@stypeid AND ATypeId=@ParId
        UPDATE Ac_Balance_Assist_CheckItems SET ATypeId=@typeid WHERE STypeId=@stypeid AND ATypeId=@ParId
        UPDATE Ac_Balance_Assist_CheckItems_Detail SET ATypeId=@typeid WHERE STypeId=@stypeid AND ATypeId=@ParId
        UPDATE Ac_IniAccount_Assist_CheckItems SET ATypeId=@typeid WHERE STypeId=@stypeid AND ATypeId=@ParId
        UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET ATypeId=@typeid WHERE STypeId=@stypeid AND ATypeId=@ParId
        
        --父节点不勾选核算项目 
        UPDATE Ac_Account SET FContact = 0 WHERE StypeId = @StypeId AND typeid = @parid;
        
        --父节点会计凭证转移至子节点
        UPDATE Ac_Voucher_Bill SET ATypeId=@typeid WHERE  StypeId = @StypeId AND Atypeid = @parid
        UPDATE Ac_Voucher_Bill SET ATypeId2=@typeid WHERE  StypeId = @StypeId AND Atypeid2 = @parid
        
        --期初 余额
        UPDATE Ac_IniAccount SET ATypeId=@typeid WHERE  StypeId = @StypeId AND Atypeid = @parid
		UPDATE Ac_Balance SET ATypeId=@typeid WHERE  StypeId = @StypeId AND Atypeid = @parid
        
        --单据上往来科目
        UPDATE BillIndex SET ATypeId1=@typeid WHERE  StypeId = @StypeId AND Atypeid1 = @parid 
                
        --凭证模版
        UPDATE Ac_Auditing_Template_Detail SET ATypeId=@typeid
        FROM Ac_Auditing_Template  WHERE  Ac_Auditing_Template.StypeId = @StypeId AND Atypeid = @parid 
        AND Ac_Auditing_Template.AtId=Ac_Auditing_Template_Detail.Atid
        
		--项目关联
		UPDATE Ac_Items_Detail SET ATypeId=@typeid
		FROM Ac_Items_Detail D 
		INNER JOIN SType S ON S.TypeId=D.STypeID AND S.VerifyID= @StypeId AND D.ATypeId = @parid
		
		
        --更新分支机构中的会计科目中对父节点的引用为当前
        UPDATE SType SET ATypeID = @typeid WHERE Typeid = @stypeid AND ATypeID = @parid
        UPDATE SType SET ATypeID2 = @typeid WHERE Typeid = @stypeid AND ATypeID2 = @parid
        UPDATE SType SET ATypeID3 = @typeid WHERE Typeid = @stypeid AND ATypeID3 = @parid
        UPDATE SType SET ATypeID4 = @typeid WHERE Typeid = @stypeid AND ATypeID4 = @parid
        UPDATE BillAtype SET AtypeId = @typeid	WHERE stypeid = @stypeid AND atypeid = @parid
        
        --将固定资产类别中的父节点信息调整为子节点
        UPDATE Ac_AssetsCategory SET DepATypeId=@typeid WHERE StypeId=@stypeid AND DepATypeId=@ParId
        UPDATE Ac_AssetsCategory SET ExpenseATypeId=@typeid WHERE StypeId=@stypeid AND ExpenseATypeId=@ParId
        UPDATE Ac_AssetsCategory SET AssertATypeId=@typeid WHERE StypeId=@stypeid AND AssertATypeId=@ParId
        
        --将固定资产卡片中的父节点信息调整为子节点      
		UPDATE Ac_AssetsCards SET AssertATypeId=@typeid WHERE StypeId IN (SELECT TypeId FROM SType WHERE VerifyID=@stypeid) AND AssertATypeId=@ParId
        UPDATE Ac_AssetsCards SET DepATypeId=@typeid WHERE StypeId IN (SELECT TypeId FROM SType WHERE VerifyID=@stypeid) AND DepATypeId=@ParId
        UPDATE Ac_AssetsCards SET DisATypeId=@typeid WHERE StypeId IN (SELECT TypeId FROM SType WHERE VerifyID=@stypeid) AND DisATypeId=@ParId
        UPDATE Ac_AssetsCards SET DevalueATypeId=@typeid WHERE StypeId IN (SELECT TypeId FROM SType WHERE VerifyID=@stypeid) AND DevalueATypeId=@ParId AND DevalueATypeId<>''
        
        --处理卡片历史和变更历史
        UPDATE Ac_AssetsCards_History SET AssertATypeId=@typeid WHERE StypeId IN (SELECT typeid FROM SType WHERE VerifyID=@stypeid) AND AssertATypeId=@ParId
        UPDATE Ac_AssetsCards_History SET DepATypeId=@typeid WHERE StypeId IN (SELECT typeid FROM SType WHERE VerifyID=@stypeid) AND DepATypeId=@ParId
        UPDATE Ac_AssetsCards_History SET DisATypeId=@typeid WHERE StypeId IN (SELECT typeid FROM SType WHERE VerifyID=@stypeid) AND DisATypeId=@ParId
        UPDATE Ac_AssetsCards_History SET DevalueATypeId=@typeid WHERE StypeId IN (SELECT typeid FROM SType WHERE VerifyID=@stypeid) AND DevalueATypeId=@ParId AND DevalueATypeId<>''
         --折旧计划表
        UPDATE Ac_DepreciationPlan SET DisATypeId=@typeid WHERE StypeId IN (SELECT typeid FROM SType WHERE VerifyID=@stypeid) AND DisATypeId=@ParId AND DisATypeId<>''
        
        --存货类型
		UPDATE Base_InventoryTypeDetails SET StockATypeID=@typeid
		FROM Base_InventoryTypeDetails D 
		INNER JOIN SType S ON S.TypeId=D.STypeID AND S.VerifyID= @StypeId AND D.StockATypeID = @parid
		
		UPDATE Base_InventoryTypeDetails SET IncomeATypeID=@typeid
		FROM Base_InventoryTypeDetails D 
		INNER JOIN SType S ON S.TypeId=D.STypeID AND S.VerifyID= @StypeId AND D.IncomeATypeID = @parid
		
		UPDATE Base_InventoryTypeDetails SET CostATypeID=@typeid
		FROM Base_InventoryTypeDetails D 
		INNER JOIN SType S ON S.TypeId=D.STypeID AND S.VerifyID= @StypeId AND D.CostATypeID = @parid
       
        --UPDATE Ac_AssetsModifyRecords SET OldDTypeId=@typeid WHERE 
        UPDATE Ac_AssetsModifyRecords
        SET OldDisATypeId=@typeid 
        FROM Ac_AssetsCards A 
        WHERE A.Id=Ac_AssetsModifyRecords.CardId
        AND A.STypeId IN (SELECT TypeId FROM SType WHERE VerifyID=@stypeid)
        AND OldDisATypeId=@ParId
        
        UPDATE Ac_AssetsModifyRecords
        SET DisATypeId=@typeid 
        FROM Ac_AssetsCards A 
        WHERE A.Id=Ac_AssetsModifyRecords.CardId
        AND A.STypeId IN (SELECT TypeId FROM SType WHERE VerifyID=@stypeid)
        AND Ac_AssetsModifyRecords.DisATypeId=@ParId
        
        --更新银行账关联科目
        UPDATE Te_BankAccount
        SET 
			ATypeId=@typeid,
			Cid=@cid
        WHERE ATypeId=@ParId AND STypeId=@stypeid
        
        --更新资金调拨单对应科目
        UPDATE CapitalTransfer_Bill
        SET BankAccountIn=@typeid
        FROM BillIndex B 
        WHERE B.BillNumberId=CapitalTransfer_Bill.BillNumberId
        AND B.Stypeid2=@stypeid
        AND BankAccountIn=@ParId
        
        UPDATE CapitalTransfer_Bill
        SET BankAccountOut=@typeid
        FROM BillIndex B 
        WHERE B.BillNumberId=CapitalTransfer_Bill.BillNumberId
        AND B.Stypeid=@stypeid
        AND BankAccountOut=@ParId
        
        --更新出纳初始化数据录入对应科目数据
        UPDATE Te_InitDataDetail
        SET AtypeId=@typeid
        FROM Te_InitDataIndex TI
        WHERE TI.Id=Te_InitDataDetail.IndexId
        AND TI.STypeId=@stypeid
        AND AtypeId=@ParId
        
        --更新未达账表头 Te_AccountInTransit_Index
        UPDATE Te_AccountInTransit_Index
        SET ATypeId=@typeid
        FROM Te_BankAccount B
        WHERE B.Id=Te_AccountInTransit_Index.AccountId
        AND B.STypeId=@stypeid 
        AND Te_AccountInTransit_Index.ATypeId=@ParId
        
        --更新出纳余额表中对应科目
        UPDATE Te_Balance
        SET ATypeId=@typeid
        WHERE STypeId=@stypeid AND ATypeId=@ParId
        
        --更新出纳日记账中对应科目
        UPDATE Te_Journal
        SET ATypeId=@typeid
        WHERE STypeId=@stypeid AND ATypeId=@ParId
        
        --更新出纳日记账明细中对应科目
        UPDATE Te_Journal_Detail
        SET ATypeId=@typeid
        WHERE STypeId=@stypeid AND ATypeId=@ParId
        
        --更新常用凭证模版明细中对应科目
        UPDATE Ac_Voucher_Commonly_Bill
        SET ATypeId=@typeid
        WHERE STypeId=@stypeid AND ATypeId=@ParId
		    
    END
ELSE 
    BEGIN
        IF NOT EXISTS ( SELECT  1
                        FROM    Ac_Account
                        WHERE   typeid = @typeId
                                AND stypeid = @stypeid ) 
            BEGIN
                RAISERROR ( '该科目已经被删除', 16, 1 )
                RETURN -1 ;
            END
        
        IF @stypeid = '00000' AND @ISv3<>1 
            AND EXISTS ( SELECT 1
                         FROM   Ac_Account
                         WHERE  StypeId > '00000'
                                AND typeid = @typeid ) 
            BEGIN
                RAISERROR ( '该会计科目已经被分发到下级分支机构，不允许修改。', 16, 1 ) ;
                RETURN ;
            END

        DECLARE @thisUsed INT
        SET @thisUsed = 0 ;
	    --判断子节点是否被使用
	    EXEC @thisUsed = GP_CheckAccountUsage @stypeid = @stypeid,@atypeid = @typeid
	    
			
        IF EXISTS ( SELECT TOP 1
                            1
                    FROM    Ac_Account
                    WHERE   typeid = @typeid
                            AND StypeId = @stypeid
                            AND UserCode <> @usercode ) 
            BEGIN
                IF @thisUsed > 0 
                    BEGIN
                        RAISERROR ( '该科目已经被使用，不允许修改编码。', 16, 1 )
                        RETURN -1 ;
                    END
                    
                DECLARE @subUsed INT ; 
                EXEC @subUsed = GP_CheckChildAccountUsage @stypeid = @stypeid,@atypeid = @typeid
                
                IF @subUsed > 0 
                    BEGIN
                        RAISERROR ( '该科目已经存在下级科目且下级科目已被使用，不允许修改编码。', 16, 1 )
                        RETURN -1 ;
                    END
            END

        IF @thisUsed > 0 
            BEGIN
                    -- 判断辅助核算
                DECLARE @equal TINYINT
                    -- 两个(A,B)集合相同
                    -- COUNT(A) = COUNT(B)
                    -- 不存在元素 C IN (A) AND C NOT IN (B) 
                IF EXISTS ( SELECT  a
                            FROM    dbo.f_split(@Ascids, ',')
                            EXCEPT
                            SELECT  DISTINCT Ascids
                            FROM    Ac_Account_Assist_CheckItems
                            WHERE   ATypeId = @typeid
                                    AND StypeId = @stypeid )
                    OR (SELECT  COUNT(1)
                        FROM    dbo.f_split(@Ascids, ',')) <> (SELECT
                                            COUNT(DISTINCT Ascids)
                                            FROM
                                            Ac_Account_Assist_CheckItems
                                            WHERE
                                            ATypeId = @typeid
                                            AND StypeId = @stypeid) 
                    SET @equal = 1
                ELSE 
                    SET @equal = 0
                IF @equal = 1 
                    BEGIN	
                        RAISERROR ( '该会计科目辅助核算已经在使用中，不允许修改辅助核算项目！', 16, 1 ) ;
                        RETURN ;
                    END
                        
                    --判断外币核算
                DECLARE @oldcid1 INT ;
                SELECT  @oldcid1 = cid
                FROM    Ac_Account
                WHERE   StypeId = @stypeid
                        AND TypeId = @typeid ;
            
                IF @cid <> @oldcid1
                    AND @cid <> 0 
                    BEGIN
                        RAISERROR ( '该会计科目已经在使用中，外币核算只允许从具体币别调整到所有币别。', 16,
                                1 ) ;
                        RETURN ;
                    END
                
                DECLARE @oldfadjustrate INT
                SELECT @oldfadjustrate = FAdjustRate FROM Ac_Account
                WHERE stypeid = @stypeid AND typeid = @typeid
                
                
                IF @oldfadjustrate = 1 AND @fadjustrate = 0
                BEGIN
                    RAISERROR ( '该会计科目已经在使用中，不允许取消【期末调汇】。', 16,1 ) ;
                    RETURN -1;
                END
                
                
                IF EXISTS ( SELECT  fdc, iscash, isbank,--isdiary,
                                    isother, facnt                                    
                            FROM    Ac_Account
                            WHERE   Typeid = @typeid
                                    AND StypeId = @stypeid
                            EXCEPT
                            SELECT  @fdc, @iscash, @isbank,--@isdiary,
                                    @isother, @facnt ) 
                    BEGIN
                        RAISERROR ( '该会计科目已经在使用中，只允许修改名称，简称，拼音码，主/附表项目。', 16,
                                1 ) ;
                        RETURN -1;
                    END                    
            END
            
        BEGIN TRAN
            
        DECLARE @oldUsercode VARCHAR(50)
            
        SELECT  @oldUsercode = usercode
        FROM    Ac_Account
        WHERE   typeid = @typeid
                AND StypeId = @stypeid 
        
        UPDATE  Ac_Account
        SET     UserCode = @usercode, fullname = @FullName,
                Pycode = @Pycode, NAME = @Name, fdc = @fdc,
                mainitems = @mainitems,
                additionitems = @additionitems, cid = @cid,
                exchid = @exchid, facnt = @facnt,
                fadjustrate = @fadjustrate,
                [Group] = @group,fcontact=@fcontact,checktype=@checktype,
                XiWaMaxNumber = @ThisXiWaNo,
                AdjustAccounts=@AdjustAccounts,
                UnitID=@UnitID
        WHERE   typeid = @typeid
                AND StypeId = @stypeid ;
                
        --操作失败，返回-1
        IF @@ROWCOUNT = 0 
            BEGIN
                ROLLBACK TRAN ;
                RETURN -1 ;
            END   
            
        --更新自己及其子节点的信息
        UPDATE Ac_Account
        SET     iscash = @iscash, isbank = @isbank,
                IsOther = @isother,isdiary = @isdiary
        WHERE STypeId = @stypeid AND TypeId LIKE @typeid+'%'       
        
        --更新对应银行账户的外币核算
        UPDATE Te_BankAccount
        SET Cid=@cid
        WHERE ATypeId=@typeid
        
        IF @oldUsercode <> @usercode 
            BEGIN
                UPDATE  Ac_Account
                SET     usercode = @usercode + SUBSTRING(UserCode,
                                                    LEN(@oldusercode)
                                                    + 1,
                                                    LEN(usercode)
                                                    - LEN(@oldusercode))
                WHERE   ParId LIKE @typeid + '%'
                        AND StypeId = @stypeid ;
            END
                
   END                 

-- 先清除设置的辅助核算项目
DELETE  Ac_Account_Assist_CheckItems
WHERE   STypeID = @stypeid
        AND ATypeId = @typeid ;

-- 重新填写辅助核算项目
INSERT  INTO Ac_Account_Assist_CheckItems (STypeId,
                            ATypeId, Cid,
                            Ascids,AcId)
        SELECT  @stypeid, @typeid, cid, AscIds,@AcID
        FROM    #temp_currency,
                #temp_ascids

COMMIT TRAN ; 

DROP TABLE #temp_currency,#temp_ascids

GO


SET ANSI_NULLS ON ;
GO

SET QUOTED_IDENTIFIER OFF ;
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveAcPeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SaveAcPeriod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:郑红霞
	日期：2012-4-9
	描述：保存会计期初
*/
CREATE PROCEDURE GP_SaveAcPeriod
(
  @Fyear            VARCHAR(10),  --启用年度
  @Fmonth           VARCHAR(10),  --启用月度
  @Isnature         INT,          --是否自然年度
  @Naturecount      INT,          --NATURECOUNT	期间数
  @Fperiod          INT,          --会计期间 1~13
  @Fbegin           DATETIME,     --开始日期
  @Fend             DATETIME,     --截至日期
  @Deleted          INT,          --是否停用
  @iffirst          INT,          --是否第一条数据插入
  @isdynamic		INT,			--是否动态	
  @IsCurrent		INT				--是否系统配置的会计期间
)
--@encode$--
AS
SET NOCOUNT ON
 
 IF EXISTS(SELECT * FROM Ac_Period) AND @iffirst=1
	DELETE Ac_Period
IF(@IsCurrent=0) AND EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE IsCurrent=0)
	BEGIN
		DELETE FROM Ac_Period WHERE IsCurrent=0
	END
  
  
 INSERT INTO Ac_Period
 (
	Fyear,
	Fmonth,
	Isnature,
	Naturecount,
	Fperiod,
	Fbegin,
	Fend,
	Deleted,
	isdynamic,
	IsCurrent
 )VALUES(
	@Fyear,
	@Fmonth,
	@Isnature,
	@Naturecount,
	@Fperiod,
	@Fbegin,
	@Fend,
	@Deleted,
	@isdynamic,
	@IsCurrent
 )
 
 --IF @@ERROR<>0
 --	RAISERROR('会计期间保存失败！',16,1)	
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'Type_AcPeriodInitail' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_SaveAcPeriodInitail]') AND TYPE in (N'P', N'PC'))
		BEGIN
			DROP PROC GP_SaveAcPeriodInitail
		END
	DROP TYPE Type_AcPeriodInitail
END
GO
-- ==============================================
-- 描述：	返回会计期间表变量
-- date:2016-07-16
-- 作者：	glj
-- =============================================
CREATE TYPE Type_AcPeriodInitail AS TABLE
(
	FPeriod			INT,
	FBegin			DATETIME ,
	FEnd			DATETIME
);
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_SaveAcPeriodInitail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[GP_SaveAcPeriodInitail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===============================
--by:glj	
--date:2016-07-16
--9.8 分支机构独立开账-会计期间维护
--===============================
CREATE PROCEDURE GP_SaveAcPeriodInitail
(
  @Fyear			INT,			--启用年度
  @Fmonth			INT,			--启用期间
  @IsNature			INT,			--是否自然年度
  @Naturecount		INT,			--期间条数
  @isdynamic		INT,			--是否动态
  @OperatorID		VARCHAR(50),	--当前操作员
  @Type				INT,			--1:运维平台 2：会计期间维护
  @Grid				Type_AcPeriodInitail READONLY	--期间数据
)
--@encode$--
AS
SET NOCOUNT ON
IF @Type=1 AND EXISTS(SELECT * FROM SysData WHERE SubName='stypeindependentopen' AND SubValue='1')
	BEGIN
		RAISERROR('已经启用分支机构独立开账，不允许此操作！',16,1) RETURN 
	END
IF EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE Value=1) OR EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE IsUse=1)
	BEGIN
		RAISERROR('分支机构已经开账，不允许修改期间表！',16,1) RETURN 
	END
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='assets' AND SubValue='1') AND (SELECT COUNT(*) FROM @Grid)<12
	BEGIN
		RAISERROR('系统已经设置为卡片管理模式，会计期间数不能小于12期，请确认！',16,1) RETURN 
	END
BEGIN TRAN 
DECLARE @Error	INT=0
--删除原期间数据
DELETE FROM Ac_Period
SET @Error+=@@ERROR
INSERT INTO Ac_Period
 (
	Fyear,
	Fmonth,
	Isnature,
	Naturecount,
	Fperiod,
	Fbegin,
	Fend,
	Deleted,
	isdynamic,
	IsCurrent
 )
 SELECT
	@Fyear,
	@Fmonth,
	@IsNature,
	@Naturecount,
	FPeriod,
	FBegin,
	FEnd,
	0 Deleted,
	@isdynamic,
	1 IsCurrent 
 FROM @Grid
SET @Error+=@@ERROR

--修改sysdata表年度、期间值
UPDATE SysData SET SubValue=@Fyear WHERE SubName='fyear'
SET @Error+=@@ERROR
UPDATE sysdata SET SubValue=@Fmonth WHERE SubName IN('FPeriod','fmonth')
SET @Error+=@@ERROR

--如果是运维平台保存会计期间直接修改整个分支机构启用期间
IF @Type=1 OR EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='ProInfo' AND SubValue='1') OR EXISTS(SELECT * FROM SysData WHERE SubName='stypeindependentopen' AND SubValue='0')
	BEGIN
		--总账处理
		UPDATE Ac_AccountsPeroid_Stype SET SFYear=@Fyear,SFPeriod=@Fmonth,FYear=@Fyear,FPeriod=@Fmonth
		SET @Error+=@@ERROR
		--分支机构未插入默认数据
		INSERT INTO Ac_AccountsPeroid_Stype(Stypeid,SFYear,SFPeriod,FYear,FPeriod,IsUse)
		SELECT TypeId,@Fyear,@Fmonth,@Fyear,@Fmonth,0 FROM SType  WHERE IsSelfVerify=1 AND TypeId<>'00000' AND TypeId NOT IN(SELECT Stypeid FROM Ac_AccountsPeroid_Stype)
		SET @Error+=@@ERROR	
		
		--业务处理
		UPDATE SType_UserConfig SET SFYear=@Fyear,SFPeriod=@Fmonth
		SET @Error+=@@ERROR
		
		--本期处理
		DECLARE @StartDate DATETIME--启用期间开始时间
		SELECT @StartDate=FBegin FROM Ac_Period WHERE FYear=@Fyear AND FPeriod=@Fmonth
		UPDATE MonthProc SET [Year]=@Fyear,period=@Fmonth,StartDate=@StartDate WHERE MonthNo='本期'
		SET @Error+=@@ERROR
		

		--原逻辑添加期初数据期间更改
		UPDATE Ac_IniAccount SET FYear=@Fyear,FPeriod=@Fmonth
		SET @Error+=@@ERROR
		UPDATE Ac_IniAccount_Assist_CheckItems SET FYear=@Fyear,FPeriod=@Fmonth
		SET @Error+=@@ERROR
		UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYear=@Fyear,FPeriod=@Fmonth
		SET @Error+=@@ERROR
		
		IF @Fmonth = 1
		BEGIN
			UPDATE Ac_IniAccount SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0,iniYTotal = iniTotal,iniYTotalFor = iniTotalFor,IniYqty=iniqty
			UPDATE Ac_IniAccount_Assist_CheckItems SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0,iniYTotal = iniTotal,iniYTotalFor = iniTotalFor,IniYqty=iniqty
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0,iniYTotal = iniTotal,iniYTotalFor = iniTotalFor,IniYqty=iniqty
		END
	END
IF(@Error<>0)
	BEGIN
		ROLLBACK TRAN
		RETURN 0
	END
ELSE 
	BEGIN
		COMMIT TRAN
		RETURN 1
	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_SaveAcTable]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_SaveAcTable]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/31
	Description	: 保存科目表
*/

CREATE PROCEDURE GP_SaveAcTable
(
	@AcID		INT = NULL,
	@UserCode	VARCHAR(200),
	@FullName	VARCHAR(200),
	@Comment	VARCHAR(200),
	@Len1		INT = NULL,
	@Len2		INT = NULL,
	@Len3		INT = NULL,
	@Len4		INT = NULL,
	@Len5		INT = NULL,
	@Len6		INT = NULL,
	@Len7		INT = NULL,
	@Len8		INT = NULL,
	@Len9		INT = NULL,
	@Len10		INT = NULL,
	@ETypeId	VARCHAR(50)
)
--@encode$--
AS 
SET NOCOUNT ON

IF ISNULL(@AcID,0)=0 
    BEGIN 
		IF(SELECT COUNT(*) FROM Ac_Table)>5
            BEGIN
                RAISERROR ('仅能增加5套科目体系表！', 15, 1) ;
                RETURN -1 ;
            END
		
        IF NOT EXISTS ( SELECT 1 FROM Employee WHERE TypeId = @ETypeId ) 
            BEGIN
                RAISERROR ('不存在职员%s.', 15, 1, @ETypeId) ;
                RETURN -1 ;
            END
        IF EXISTS ( SELECT  1 FROM Ac_Table WHERE UserCode = @UserCode ) 
            BEGIN
                RAISERROR ('编码[%s]已经被其他科目表使用.', 15, 1, @UserCode) ;
                RETURN ;
            END
        IF EXISTS ( SELECT  1 FROM Ac_Table WHERE FullName = @FullName ) 
            BEGIN
                RAISERROR (N'名称[%s]已经被其他科目表使用.', 15, 1, @FullName) ;
                RETURN -1 ;
            END
    END
ELSE 
    BEGIN
        IF NOT EXISTS ( SELECT  1 FROM Ac_Table WHERE AcId = @AcID ) 
            BEGIN
                RAISERROR ('要修改的科目表不存在.', 15, 1, @UserCode) ;
                RETURN ;
            END

        IF EXISTS ( SELECT  1 FROM Ac_Table WHERE UserCode = @UserCode AND AcId <> @AcID ) 
            BEGIN
                RAISERROR ('编码[%s]已经被其他科目表使用.', 15, 1, @UserCode) ;
                RETURN ;
            END

        IF EXISTS ( SELECT  1 FROM Ac_Table WHERE FullName = @FullName AND AcId <> @AcID ) 
            BEGIN
                RAISERROR ('名称[%s]已经被其他科目表使用.', 15, 1, @FullName) ;
                RETURN -1 ;
            END
    END

IF LTRIM(RTRIM(@UserCode)) = '' 
    BEGIN
        RAISERROR ('编码不能为空.', 15, 1) ;
        RETURN -1 ;
    END

IF LTRIM(RTRIM(@FullName)) = '' 
    BEGIN
        RAISERROR ('名称不能为空.', 15, 1) ;
        RETURN -1 ;
    END

IF @Len1 IS NULL
    OR @Len1 <= 0 
    BEGIN
        RAISERROR ('第一级长度必须大于0.', 15, 1) ;
        RETURN -1 ;
    END

DECLARE @ThisXiWaNo INT ;
SELECT @ThisXiWaNo = ISNULL(MAX(XiWaMaxNumber),0)+1 FROM Ac_Account 


IF ISNULL(@AcID,0)=0 
    BEGIN
        INSERT  INTO Ac_Table
            (
             UserCode,
             FullName,
             Comment,
             Len1,
             Len2,
             Len3,
             len4,
             len5,
             Len6,
             Len7,
             len8,
             Len9,
             Len10,
             EType,
             CreateDateTime
		)
        VALUES  (
                 @UserCode,
                 @FullName,
                 @Comment,
                 @Len1,
                 @Len2,
                 @Len3,
                 @Len4,
                 @Len5,
                 @Len6,
                 @Len7,
                 @Len8,
                 @Len9,
                 @Len10,
                 @ETypeId,
                 GETDATE()) ;
	
		IF @@ROWCOUNT = 0
			RETURN -1;
		-- 科目表树ID
		SELECT @AcID=@@IDENTITY
	
	    -- 如果没有总条目
        IF NOT EXISTS ( SELECT TOP 1 1 FROM Ac_Account WHERE STypeId = '00000' AND TypeId = '00000' AND AcId=@AcID)
            BEGIN
                INSERT  INTO Ac_Account(StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,
				Fdc,IsCash,IsBank,IsDiary,Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,
				ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,FintRate,[group],XiWaMaxNumber,AcId)
                VALUES  (
					'00000', '00000', 'root', 0, 0, 0, 'root', '', '',
					1, 0, 0, 0, '', 'root', '00001', '1900-01-01', '', '',
					-1, -1, -1, -1, 0, -1, -1, -1,'',@ThisXiWaNo,@AcID
                );
			END ;

        --插入不存在的一级科目
        INSERT INTO Ac_Account (StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,Fdc,IsCash,IsBank,IsDiary,
        Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,
        FintRate,FLeveal,Deleted,XiWaMaxNumber,IsOther,Cid,IsDist,[Group],IsPreGather,IsPrePay,IsGather,IsPay,IsVip,CheckType,AcId)
        SELECT * FROM (
            SELECT StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,Fdc,IsCash,IsBank,IsDiary,
            Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,
            FintRate,FLeveal,Deleted,XiWaMaxNumber,IsOther,Cid,IsDist,[Group],IsPreGather,IsPrePay,IsGather,IsPay,IsVip,CheckType,AcId 
            FROM Ac_Account WHERE 1=2
            UNION ALL 
            SELECT '00000', '00001', '00000', 1, 0, 0, '', '资产', '', -1, 0, 0, 0, 
                    '', 'ZC' ,@etypeid, GETDATE(), '', '', -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '100', 0, 0, 0, 0, 0, 0,@AcID
             UNION ALL
             SELECT '00000', '00002', '00000', 1, 0, 0, '', '负债', '', -1, 0, 0, 0, 
                    '', 'FZ' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '200', 0, 0, 0, 0, 0, 0 ,@AcID        
             UNION ALL
             SELECT '00000', '00003', '00000', 1, 0, 0, '', '损益', '', -1, 0, 0, 0, 
                    '', 'SY' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '500', 0, 0, 0, 0, 0, 0,@AcID
             UNION ALL
             SELECT '00000', '00004', '00000', 1, 0, 0, '', '成本', '', -1, 0, 0, 0, 
                    '', 'CB' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '400', 0, 0, 0, 0, 0, 0,@AcID
             UNION ALL
             SELECT '00000', '00005', '00000', 1, 0, 0, '', '权益', '', -1, 0, 0, 0, 
                    '', 'QY' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '300', 0, 0, 0, 0, 0, 0,@AcID
             UNION ALL
             SELECT '00000', '00006', '00000', 1, 0, 0, '', '共同', '', -1, 0, 0, 0, 
                    '', 'gt' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '700', 0, 0, 0, 0, 0, 0 ,@AcID        
         ) t WHERE   NOT EXISTS ( SELECT
                                1
                                FROM
                                Ac_Account a
                                WHERE
                                a.TypeId = t.TypeId
                                AND a.StypeId = '00000'
                                AND AcId=@AcID )
        
        UPDATE  Ac_Account
        SET     SonNum = (SELECT    COUNT(*)
                      FROM      Ac_Account a
                      WHERE     a.ParId = ac.TypeId
                                AND a.Leveal = ac.Leveal + 1
                                AND a.StypeId = ac.StypeId
                                AND AcId=@AcID
                     ),
            SonCount = (SELECT  COUNT(*)
                        FROM    Ac_Account a
                        WHERE   a.ParId = ac.TypeId
                                AND a.Leveal = ac.Leveal + 1
                                AND a.StypeId = ac.StypeId
                                AND AcId=@AcID
                       )
        From Ac_Account ac WHERE ac.StypeId='00000' AND AcId=@AcID;
        
        DECLARE @IsV3 INT SET  @IsV3= (SELECT SubValue  FROM sysdata WHERE SubName='ProInfo')
        IF(@IsV3=1)
          BEGIN
          --V3版本默认机构自动插入一级科目
        INSERT INTO Ac_Account (StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,Fdc,IsCash,IsBank,IsDiary,
        Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,
        FintRate,FLeveal,Deleted,XiWaMaxNumber,IsOther,Cid,IsDist,[Group],IsPreGather,IsPrePay,IsGather,IsPay,IsVip,CheckType,AcId)
        SELECT * FROM (
            SELECT StypeId,TypeId,ParId,Leveal,SonNum,SonCount,UserCode,FullName,Name,Fdc,IsCash,IsBank,IsDiary,
            Comment,PyCode,ETypeId,CreateDateTime,MainItems,AdditionItems,ExchId,FAcctint,FAcnt,AscIds,FAdjustRate,FContact,FInterest,
            FintRate,FLeveal,Deleted,XiWaMaxNumber,IsOther,Cid,IsDist,[Group],IsPreGather,IsPrePay,IsGather,IsPay,IsVip,CheckType,AcId
            FROM Ac_Account WHERE 1=2
            UNION ALL 
            SELECT '00001', '00001', '00000', 1, 0, 0, '', '资产', '', -1, 0, 0, 0, 
                    '', 'ZC' ,@etypeid, GETDATE(), '', '', -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '100', 0, 0, 0, 0, 0, 0,@AcID
             UNION ALL
             SELECT '00001', '00002', '00000', 1, 0, 0, '', '负债', '', -1, 0, 0, 0, 
                    '', 'FZ' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '200', 0, 0, 0, 0, 0, 0 ,@AcID       
             UNION ALL
             SELECT '00001', '00003', '00000', 1, 0, 0, '', '损益', '', -1, 0, 0, 0, 
                    '', 'SY' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '500', 0, 0, 0, 0, 0, 0,@AcID
             UNION ALL
             SELECT '00001', '00004', '00000', 1, 0, 0, '', '成本', '', -1, 0, 0, 0, 
                    '', 'CB' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '400', 0, 0, 0, 0, 0, 0,@AcID
             UNION ALL
             SELECT '00001', '00005', '00000', 1, 0, 0, '', '权益', '', -1, 0, 0, 0, 
                    '', 'QY' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '300', 0, 0, 0, 0, 0, 0,@AcID
             UNION ALL
             SELECT '00001', '00006', '00000', 1, 0, 0, '', '共同', '', -1, 0, 0, 0, 
                    '', 'gt' ,@etypeid, GETDATE(), '', '',  -1, 0, 0, '', 0, 0, 0,
                    0, 0, 0, @ThisXiWaNo, 0, -1, 0, '700', 0, 0, 0, 0, 0, 0,@AcID         
         ) t WHERE   NOT EXISTS ( SELECT
                                1
                                FROM
                                Ac_Account a
                                WHERE
                                a.TypeId = t.TypeId
                                AND a.StypeId = '00001'
                                AND AcId=@AcID )
        
        END
        
    END
ELSE 
    BEGIN
	
        UPDATE  Ac_Table
        SET     UserCode = @UserCode,
                FullName = @FullName,
                Comment = @Comment,
                Len1 = @len1,
                Len2 = @Len2,
                Len3 = @Len3,
                len4 = @len4,
                len5 = @len5,
                Len6 = @Len6,
                Len7 = @Len7,
                len8 = @len8,
                Len9 = @Len9,
                Len10 = @Len10
        WHERE   AcId = @AcID ;
	
        IF @@ROWCOUNT = 0
			RETURN -1;
    END
RETURN 0;



GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveAssetsCardHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveAssetsCardHistory
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*   
	Created	:	董湛
	Date	:	2013/06/20
	Description	:	保留卡片历史记录(三种单据过账对历史表，折旧表的影响)
*/

/*   
	修改:	黄清
	时间:	2013年8月23日 15:41:09
	内容:	历史业务类型根据单据类型填写，方便查询
*/
CREATE PROCEDURE Gp_SaveAssetsCardHistory
(
	@StypeID			varchar(50),
	@CardID				INT,    				--卡片ID
	@Etypeid			VARCHAR(50),			--操作人员
	@Businessdate		DATETIME,					--业务日期，单据上的时期，变更单是保存时间
	@billtype			INT,					--单据对应billname表的id，0是初始化,减值准备是-1，部门转移是-2,折旧方式变更是-3,月结是-4
	@billnumberid		NUMERIC(18,0),           --单据id或变更单对应表中的数据id
	@AuditType			INT,                      --业务类型
	@ReturnValue		VARCHAR(MAX) out		--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Fyear INT,@Fperiod INT,@VeriryStypeid VARCHAR(50)
SELECT @VeriryStypeid=VerifyID FROM dbo.SType WHERE TypeId=@StypeID 
 
--获取指定分支机构当前年度,财务期间	
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @VeriryStypeid)
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @VeriryStypeid
ELSE 
	BEGIN
		SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName='fyear'
		SELECT @FPeriod=SubValue FROM dbo.sysdata WHERE SubName='fperiod'
	END


DECLARE @iniTime DATETIME
DECLARE @sfullname nVARCHAR(max)
DECLARE @version INT
SELECT @version=SubValue FROM dbo.sysdata WHERE SubName='ProInfo' 
SELECT @sfullname=FullName FROM dbo.SType WHERE TypeId=@VeriryStypeid
--判断是否初始化
IF @billtype=212 OR @billtype=213 OR @billtype=214
	BEGIN
		IF EXISTS (SELECT TOP 1 1 FROM dbo.SType WHERE IfAssetsIni=0 AND TypeId=@VeriryStypeid)
			BEGIN
				IF @version=2 --A8
					SET @ReturnValue='分支机构'+@sfullname+'固定资产未初始化'
				ELSE 
					SET @ReturnValue='固定资产未初始化'
				RETURN 215
			END
		ELSE 
			SELECT @iniTime=InitDate  FROM dbo.Ac_FixedAssetsInit_Stype WHERE StypeId=@VeriryStypeid
	END	
	
	
IF @billtype=212  --增加单
BEGIN
	IF EXISTS (SELECT * FROM Ac_AssetsCards WHERE AssetsState=3 AND Id=@CardID)
		BEGIN
			DECLARE @cUsercode NVARCHAR(200) 
			SELECT @cUsercode=UserCode FROM dbo.Ac_AssetsCards WHERE id=@CardID
			SET @ReturnValue='资产编号'+@cUsercode+'已入账'
			RETURN 212
		END
	
	IF EXISTS (SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillDate<@iniTime AND BillNumberId=@billnumberid)	
		BEGIN
			IF @version=2 --A8
				SET @ReturnValue='录单日期必须大于等于该分支机构的初始化日期'
			ELSE 
				SET @ReturnValue='录单日期必须大于等于初始化日期'
			RETURN 212
		END
		
	--修改卡片状态
	UPDATE dbo.Ac_AssetsCards SET AssetsState=3 WHERE Id=@CardID --已经入账 
	
	SELECT @AuditType=AuditType FROM Ac_AssetBusinessType WHERE ID=@AuditType
END

IF @billtype=214  --折旧单，对折旧计划表的操作
	BEGIN
		DECLARE @DepreciationMean INT
		SELECT @DepreciationMean=DepreciationMean FROM Ac_AssetsCards WHERE ID=@CardID
		
		IF @DepreciationMean<>1 AND @DepreciationMean <> 5  --不是手工折旧的卡片，如果当期已经折旧过了，就不需要折旧了;增加工作量方式，和手工类似
			BEGIN
				IF EXISTS (SELECT TOP 1  1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND PlanState=1 AND FYear=@Fyear AND FPeriod=@Fperiod) --已经折旧
					BEGIN
						DECLARE @cccUsercode NVARCHAR(200) 
						SELECT @cccUsercode=UserCode FROM dbo.Ac_AssetsCards WHERE id=@CardID
						SET @ReturnValue='资产编号'+@cccUsercode+'当期已折旧'
						RETURN 214
					END
					
					
					
				DECLARE @temp1  NUMERIC(24, 10) =0,  --折旧单上的折旧额
					    @temp2  NUMERIC(24, 10) =0   --计划表中的折旧额
				SELECT @temp1=Depreciation FROM dbo.DepBill WHERE BillNumberId=@billnumberid AND AssetCardId=@CardID
				SELECT @temp2=ISNULL(Depreciation,0) FROM Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@Fyear AND FPeriod=@Fperiod
				IF @temp1<>@temp2
					BEGIN
						DECLARE @cccUsercode1 NVARCHAR(200) 
						SELECT @cccUsercode1=UserCode FROM dbo.Ac_AssetsCards WHERE id=@CardID
						SET @ReturnValue='资产编号'+@cccUsercode1+'折旧额与计划不符'
						RETURN 214
					END
			END
		
		--修改卡片状态
		UPDATE dbo.Ac_AssetsCards SET AssetsState=4 WHERE Id=@CardID --已折旧 
		
		--修改卡片值
		UPDATE ac SET NetValue=NetValue-d.Depreciation,DepTotal=DepTotal+d.Depreciation,ac.DepreciationMonth=ac.DepreciationMonth+1,FinishWork = ISNULL(FinishWork,0)+ISNULL(d.worktime,0)    --更新工作量的值
		FROM dbo.Ac_AssetsCards ac
		JOIN  dbo.DepBill d ON ac.Id=d.AssetCardId AND d.BillNumberId=@billnumberid
		WHERE ac.Id=@CardID
		
		--如果净值小于0,返回错误码-10
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AssetsCards WHERE id=@CardID AND NetValue<0)
				RETURN -10
		IF @DepreciationMean=1 OR @DepreciationMean=5 --手工折旧
			BEGIN
				DECLARE @Depreciation  NUMERIC(24, 10)           --折旧额度
				SELECT @Depreciation=Depreciation FROM dbo.DepBill WHERE BillNumberId=@billnumberid AND AssetCardId=@CardID
			
				--有数据的情况下
				IF EXISTS (SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1)
					BEGIN
						DECLARE @MontherOrder INT,@YearOrder INT,@PreDepTotal  NUMERIC(24, 10)    --上期的累计折旧额
						---存在有本期的数据
						IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@FYear AND fperiod=@FPeriod)
							BEGIN
								SELECT TOP 1 @MontherOrder=monthorder+1,@YearOrder=YearOrder 
								FROM Ac_DepreciationPlan 
								WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@FYear AND fperiod=@FPeriod
								ORDER BY MonthOrder DESC
							END
						ELSE 
							BEGIN
								--月次
								SELECT TOP 1 @MontherOrder=monthorder+1 FROM Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 ORDER BY MonthOrder DESC
								--如果有同年的，年次不变，否则年次加1
								IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@FYear)
									SELECT TOP 1 @YearOrder=YearOrder FROM Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 ORDER BY MonthOrder DESC
								ELSE 
									SELECT TOP 1 @YearOrder=YearOrder+1 FROM Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 ORDER BY MonthOrder DESC
							END
						
						--上期累计折旧额
						SELECT TOP 1 @PreDepTotal=ISNULL(DepTotal,0) FROM Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=1 ORDER BY MonthOrder DESC
						
						---月
						INSERT INTO dbo.Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,FYear,fperiod,MonthOrder,
															PlanType,AssetCardId,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,Depreciation,BillNumberId,LocationId,DisATypeId,ExpectWork,FinishWork,WorkUnit)
						SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,@Fyear,@FPeriod,
								@MontherOrder,1,@CardID,dbo.F_RoundTotal(@PreDepTotal+@Depreciation),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),1,@Depreciation,@billnumberid,LocationId,DisATypeId,ExpectWork,FinishWork,WorkUnit
						FROM dbo.Ac_AssetsCards WHERE Id=@CardID
						
						---年,先删除，后重算
						DELETE FROM dbo.Ac_DepreciationPlan WHERE AssetCardId=@CardID AND PlanType=0 AND FYear=@FYear
						
						 ;WITH t AS 
						(
							SELECT AssetCardId,SUM(Depreciation) AS Depreciation,COUNT(*) AS fperiod,fyear,MAX(MonthOrder) AS MonthOrder
							FROM Ac_DepreciationPlan WHERE PlanType=1 AND AssetCardId=@CardID AND FYear=@FYear GROUP BY AssetCardId,FYear	
						)
						INSERT INTO Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
										FYear,FPeriod,PlanType,AssetCardId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,ExpectWork,FinishWork,WorkUnit)
						SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,@YearOrder,NULL,@Fyear,t.fperiod,
										   0,n.AssetCardId,t.Depreciation,dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),1,n.ExpectWork,n.FinishWork,n.WorkUnit
						FROM t 
						JOIN Ac_DepreciationPlan n ON t.AssetCardId=n.AssetCardId AND t.MonthOrder=n.MonthOrder AND n.PlanType=1 
						
					END
				ELSE    --一条数据都没有的情况下
					BEGIN
						---月
						INSERT INTO dbo.Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,FYear,fperiod,MonthOrder,
															PlanType,AssetCardId,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,Depreciation,BillNumberId,LocationId,DisATypeId,ExpectWork,FinishWork,WorkUnit)
						SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,1,@Fyear,@FPeriod,
								1,1,@CardID,DepTotal,Total,DevalueReady,NetValue,NetSalvage,1,@Depreciation,@billnumberid,LocationId,DisATypeId,ExpectWork,FinishWork,WorkUnit
						FROM dbo.Ac_AssetsCards WHERE Id=@CardID
						
						--年
						INSERT INTO dbo.Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,FYear,fperiod,MonthOrder,
															PlanType,AssetCardId,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState,Depreciation,BillNumberId,LocationId,DisATypeId,ExpectWork,FinishWork,WorkUnit)
						SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,1,@Fyear,1,
								null,0,@CardID,dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),1,@Depreciation,0,LocationId,DisATypeId,ExpectWork,FinishWork,WorkUnit
						FROM dbo.Ac_AssetsCards WHERE Id=@CardID
					END
			END
		ELSE                    --按照折旧表折旧
			BEGIN
				--更新月计划表
				UPDATE dbo.Ac_DepreciationPlan SET BillNumberId=@billnumberid,PlanState=1 
				WHERE AssetCardId=@CardID AND PlanType=1 AND FYear=@Fyear AND fperiod=@Fperiod
			    
				IF @Fperiod=12
					UPDATE dbo.Ac_DepreciationPlan SET PlanState=1 
					WHERE AssetCardId=@CardID  AND PlanType=0 AND FYear=@Fyear 
			END
				
		
		SELECT @AuditType=14
	END
IF @billtype=213     --减少单，折旧计划表状态改变,planstate=2的是不要的
	BEGIN
		IF EXISTS (SELECT * FROM Ac_AssetsCards WHERE AssetsState=5 AND Id=@CardID)
		BEGIN
			DECLARE @ccUsercode NVARCHAR(200) 
			SELECT @ccUsercode=UserCode FROM dbo.Ac_AssetsCards WHERE id=@CardID
			SET @ReturnValue='资产编号'+@ccUsercode+'已清理'
			RETURN 213
		END
		
		--修改卡片状态
		UPDATE dbo.Ac_AssetsCards SET AssetsState=5 WHERE Id=@CardID --已清理  
		 
		--折旧表新增一条清理数据
		--期间减少单
		DECLARE @BillFyear int,@BillPeriod INT
		SELECT @BillPeriod=ap.FPeriod,@BillFyear=ap.FYear
		FROM dbo.Ac_Period ap
		JOIN  dbo.BillIndex b ON b.BillNumberId=@billnumberid AND ap.FBegin<=b.BillDate AND ap.FEnd>=b.BillDate
		 
		INSERT INTO Ac_DepreciationPlan(STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,YearOrder,MonthOrder,
								FYear,FPeriod,PlanType,AssetCardId,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,PlanState)
		SELECT STypeId,DTypeid,CategoryId,InAccountDate,UserCode,FullName,DepreciationMean,999999,999999,
								@BillFyear,@BillPeriod,3,@CardID,0,dbo.F_RoundTotal(DepTotal),dbo.F_RoundTotal(Total),DevalueReady,dbo.F_RoundTotal(NetValue),dbo.F_RoundTotal(NetSalvage),0 
		FROM dbo.Ac_AssetsCards WHERE ID=@CardID
	
		DECLARE @monthorder INT,@Planstate INT
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_DepreciationPlan WHERE  AssetCardId=@CardID AND PlanType=1 AND FYear=@Fyear AND fperiod=@Fperiod)
			SELECT @monthorder=MonthOrder,@Planstate=PlanState FROM dbo.Ac_DepreciationPlan WHERE  AssetCardId=@CardID AND PlanType=1 AND FYear=@Fyear AND fperiod=@Fperiod
	    ELSE     --做增加单，然后当期做减少单，从下期取
			SELECT @monthorder=MonthOrder,@Planstate=PlanState FROM dbo.Ac_DepreciationPlan WHERE  AssetCardId=@CardID AND PlanType=1 AND FYear=@Fyear AND fperiod=@Fperiod+1
	    
	    --把未计提折旧的全部变成清理（当期是否清理看是否已计提）
		UPDATE dbo.Ac_DepreciationPlan SET PlanState=2 WHERE AssetCardId=@CardID AND PlanType=1 AND MonthOrder>=@monthorder AND PlanState=0 
		
		UPDATE dbo.Ac_DepreciationPlan SET PlanState=2 WHERE AssetCardId=@CardID AND PlanType=0 AND FYear>@Fyear
		
		--重算当年的年折旧   
		IF @Fperiod!=12
			BEGIN
				---当年已经计提的期数
				SELECT AssetCardId,SUM(Depreciation) AS Depreciation,COUNT(*) AS fperiod,MAX(MonthOrder) AS MonthOrder
				INTO #tempData
				FROM Ac_DepreciationPlan 
				WHERE PlanType=1 AND FYear=@Fyear AND  MonthOrder<= @monthorder AND AssetCardId=@CardID AND PlanState=1
				GROUP BY AssetCardId,FYear	
			    
			    IF EXISTS(SELECT TOP 1 1 FROM #tempData)  --有值
					UPDATE ad SET ad.Depreciation=t.Depreciation,ad.Fperiod=t.fperiod,
								  ad.NetValue=ad1.NetValue,ad.DepTotal=ad1.DepTotal 
					FROM dbo.Ac_DepreciationPlan ad 
					JOIN #tempData t ON ad.AssetCardId=t.AssetCardId 
					JOIN Ac_DepreciationPlan ad1 ON ad1.AssetCardId=t.AssetCardId AND ad1.PlanType=1 AND ad1.MonthOrder=t.MonthOrder
					WHERE ad.AssetCardId=@CardID AND ad.PlanType=0 AND ad.FYear=@Fyear
				ELSE                                      --特殊情况，当期初始化，当期未折旧进行了减少单操作
					UPDATE Ac_DepreciationPlan  
					SET Depreciation=0,
						Fperiod=0,
						NetValue=dbo.F_RoundTotal(Total),
						DepTotal=0,
						PlanState=2
					WHERE AssetCardId=@CardID AND PlanType=0 AND FYear=@Fyear
					
				DROP TABLE #tempData
			END
			
		SELECT @AuditType=AuditType FROM Ac_AssetBusinessType WHERE ID=@AuditType
	END

--计提减值
IF @billtype=-1
 BEGIN
	SELECT @AuditType=13
 END
 --部门转移
 IF @billtype=-2
 BEGIN
	SELECT @AuditType=12
 END  

--折旧方式变更  
IF @billtype=-3
 BEGIN
	SELECT @AuditType=-3
 END
 
 --初始化
 IF @billtype=0
 BEGIN
	SELECT @AuditType=0
 END
     
	INSERT INTO Ac_AssetsCards_History(AssertsCardId,TypeId,Parid,UserCode,FullName,STypeId,AssertATypeId,DepATypeId,DisATypeId,DevalueATypeId,CategoryId,LocationId,
									   ConditionId,Size,DTypeid,InAccountDate,BusinessTypeId,Total,Cid,F_Total,Rate,DepTotal,DevalueReady,NetValue,NetSalvage,NetSalvageRate,
									   DepreciationMean,DurYear,durmonth,DepreciationMonth,Comment,AssetsState,OperationDate,ETypeId,Businessdate,BillId,billtype,AuditType,barcode,ExpectWork,FinishWork,WorkUnit)
	SELECT @CardID,TypeId,Parid,UserCode,FullName,STypeId,AssertATypeId,DepATypeId,DisATypeId,DevalueATypeId,CategoryId,LocationId,
		   ConditionId,Size,DTypeid,InAccountDate,BusinessTypeId,Total,Cid,F_Total,Rate,DepTotal,DevalueReady,NetValue,NetSalvage,NetSalvageRate,
		   DepreciationMean,DurYear,durmonth,DepreciationMonth,Comment,AssetsState,GETDATE(),@Etypeid,@Businessdate,@billnumberid,@billtype,@AuditType,BarCode,ExpectWork,FinishWork,WorkUnit
	FROM dbo.Ac_AssetsCards WHERE Id=@CardID
 
RETURN 0
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveAttendanceTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveAttendanceTime
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-10-27
	描述：保存考勤时间
*/

/*
郑红霞
修改关于迟到不对的地方
*/


CREATE PROCEDURE Gp_SaveAttendanceTime
(
	@etypeid			varchar(50),		--打卡人员名称
	@date				varchar(max),		--当前日期
	@time				time				--当前时间
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT * FROM AttendanceTime WHERE CONVERT(varchar(10),date)=@date AND etypeid=@etypeid)
BEGIN
	DECLARE @late INT=1,@starttime time='09:00:00',@latetime int=0,@lastdate date = GETDATE()
	
	SELECT @starttime=StartTime,@latetime=LateTime FROM WorkTime W 
	INNER JOIN employee E ON E.STypeID=W.stypeid 
	WHERE E.typeId=@etypeid
	
--	SELECT top 1 @lastdate = date from AttendanceTime where etypeid = @etypeid order by date desc

	--WHILE DATEDIFF(DAY,@lastdate,GETDATE()) > 1
	--BEGIN
	--IF DATEDIFF(MINUTE,CAST(@starttime AS TIME),CAST(@time)<=@latetime AND DATEDIFF(MINUTE,CAST(@starttime AS TIME),CAST(@time AS TIME))>0 
	--	SET @late=0
	--	SET @lastdate = DATEADD(DAY,1,@lastdate)
	--	INSERT INTO AttendanceTime
	--	(
	--		etypeid,
	--		date,
	--		StartTime,
	--		ISLATE
	--	)
	--	VALUES
	--	(
	--		@etypeid,
	--		@lastdate,
	--		'00:00:00',
	--		@late
	--	)
	--END
	IF DATEDIFF(MINUTE,CAST(@starttime AS TIME),CAST(@time AS TIME))<=@latetime AND DATEDIFF(MINUTE,CAST(@starttime AS TIME),CAST(@time AS TIME))>0
		SET @late=0
	INSERT INTO AttendanceTime
	(
		etypeid,
		date,
		StartTime,
		ISLATE
	)
	VALUES
	(
		@etypeid,
		@date,
		@time,
		@late
	)
	
	
END
ELSE
	UPDATE AttendanceTime
	SET	EndTime=@time
	WHERE	date=@date
			AND etypeid=@etypeid

IF @@ERROR<>0
	RAISERROR('考勤数据写入失败！',16,1)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveBaseInfoTreeExpand]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[Gp_SaveBaseInfoTreeExpand]
GO


/****** Object:  StoredPROCEDURE [dbo].[Gp_InsertAc_AssetsCards]    Script Date: 05/17/2011 20:20:00 ******/

----========================
----修改者：黄清
----日期：2013-06-27
----描述：保存基本信息树是否展开
----========================
CREATE    PROCEDURE [dbo].[Gp_SaveBaseInfoTreeExpand]
(
	@baseinfoname   VARCHAR(100),
	@etypeid		VARCHAR(50),
	@isexpand		BIT
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS (SELECT 1 FROM BaseInfoTreeExpand WHERE BaseInfoName=@baseinfoname AND ETypeid=@etypeid)
BEGIN
	UPDATE BaseInfoTreeExpand
	SET IsExpand=@isexpand
	WHERE BaseInfoName=@baseinfoname AND ETypeid=@etypeid
END
ELSE
BEGIN
	INSERT INTO BaseInfoTreeExpand
	(
		BaseInfoName,
		ETypeid,
		IsExpand
	)VALUES
	(
		@baseinfoname,
		@etypeid,
		@isexpand
	)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveBillCode_maxSeed]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_SaveBillCode_maxSeed]
GO





/*

功能说明：       保存单据编号的种子数

作    者：       冯波

创建日期：       2010-8-23

返回结果：       

*/

CREATE PROCEDURE [GP_SaveBillCode_maxSeed]
(	
	@dBillDate					datetime,			--制单日期
	@intBillType				int,				--单据类型
    @strBillDate				datetime,			--单据日期
    @ETypeID					VARCHAR(100)='',
	@KTypeID					VARCHAR(100)='',
	@DTypeID					VARCHAR(100)='',
	@STypeID					VARCHAR(100)='',
	@maxgroupid					int	,				--增长的种子数 先占位置 避免并发
	@curmaxseed				int output
)
--@encode$--
AS
-- BEGIN
-- 修 改 人：罗淮文
-- 修改日期：2014-05-26
-- 内容描述：FllwNo字段不再取制单日期，更改为单据编号中的日期。
IF NOT EXISTS (SELECT * FROM CodeConfig WHERE BillType=@intBillType)
BEGIN
	IF ISDATE(@strBillDate)=1
	BEGIN
		SELECT @dBillDate = @strBillDate
	END
	ELSE
	BEGIN
		SELECT @dBillDate=GETDATE()
	END
END
-- END

DECLARE @BillCodeConfig varchar(1),@FlowLen INT
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置

SELECT @FlowLen=CAST(Value AS INT)+3 FROM UserConfig WHERE ConfigName='FlowLen'

DECLARE
	@MONTH 						VARCHAR(500), 		--自动产生编号时为月份，自定义编号时是经手人名字
	@DAY 						VARCHAR(500)		--自动产生编号时为日期，自定义编号时为仓库名


IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@intBillType ) AND @BillCodeConfig='1'
 --单据采用自定义编号 #02
BEGIN
	DECLARE @Code1 varchar(100),@Code2 varchar(100),@Code3 varchar(100),@Code4 varchar(100),@Code5 varchar(100),
			@Code6 varchar(100),@Code7 varchar(100),@Code8 varchar(100),@Code9 varchar(100),@Code10 varchar(100),
			@Code11 varchar(100),@Code12 varchar(100)

	IF @ETypeID IS NULL SET @ETypeID=''
	IF @KTypeID IS NULL SET @KTypeID=''
	IF @DTypeID IS NULL SET @DTypeID=''
	IF @STypeID IS NULL SET @STypeID=''

	DECLARE
		@intFlowType				INT,		--1，按日，2按月，3按年
		@TempCode					VARCHAR(1000),
		@strFlowDate				VARCHAR(100)


	SELECT 	@Code1=code1,@Code2=code2,@Code3=code3,@Code4=code4,@Code5=code5,@Code6=code6,@Code7=code7,@Code8=code8,
			@Code9=code9,@Code10=code10,@Code11=code11,@Code12=code12  FROM CodeConfig WHERE BillType = @intBillType



	SET @TempCode = @Code1 +'*'+ @Code2 +'*'+ @Code3 +'*'+ @Code4 +'*'+ @Code5 +'*'+ @Code6 +'*'+ @Code7 +'*'+ @Code8 +'*'+ @Code9 +'*'+ @Code10 +'*'+ @Code11 +'*'+ @Code12	

	
	IF @Code1<>'仓库编号' AND @Code2<>'仓库编号' AND @Code3<>'仓库编号' AND @Code4<>'仓库编号' AND @Code5<>'仓库编号' AND @Code6<>'仓库编号' AND @Code7<>'仓库编号' AND @Code8<>'仓库编号' AND @Code9<>'仓库编号' AND @Code10<>'仓库编号' AND @Code11<>'仓库编号' AND @Code12<>'仓库编号'
	BEGIN
		SET @KTypeID=''
	END

	IF @Code1<>'经手人编号' AND @Code2<>'经手人编号' AND @Code3<>'经手人编号' AND @Code4<>'经手人编号' AND @Code5<>'经手人编号' AND @Code6<>'经手人编号' AND @Code7<>'经手人编号' AND @Code8<>'经手人编号' AND @Code9<>'经手人编号' AND @Code10<>'经手人编号' AND @Code11<>'经手人编号' AND @Code12<>'经手人编号'
	BEGIN
		SET @ETypeID=''
	END
	
	IF @Code1<>'部门编号' AND @Code2<>'部门编号' AND @Code3<>'部门编号' AND @Code4<>'部门编号' AND @Code5<>'部门编号' AND @Code6<>'部门编号' AND @Code7<>'部门编号' AND @Code8<>'部门编号' AND @Code9<>'部门编号' AND @Code10<>'部门编号' AND @Code11<>'部门编号' AND @Code12<>'部门编号'
	BEGIN
		SET @DTypeID=''
	END

END
else
begin
	--没启用自定义 就不用这些查了
	SET @KTypeID=''
	SET @ETypeID=''
	SET @DTypeID=''
end


SELECT @intFlowType=Value
FROM UserConfig
WHERE ConfigName='FlowSet'
	
IF @intFlowType=0
BEGIN
	--按日
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@dBillDate) AS VARCHAR(2)),'0')+DBO.FN_FixStr(2,CAST(DAY(@dBillDate) AS VARCHAR(2)),'0')
END
ELSE IF @intFlowType=1
BEGIN
	--按月
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@dBillDate) AS VARCHAR(2)),'0')
END
ELSE IF @intFlowType=2
BEGIN
	--按年
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')
END

DECLARE @intDBSeed NUMERIC(18,0)

SELECT @intDBSeed = -1

SELECT @intDBSeed = ISNULL(MAX(Seed), -1) FROM BillCode_Seed 
WHERE BillType = @intBillType AND FlowDate=@strFlowDate AND ETypeID=@ETypeID AND KTypeID=@KTypeID AND DTypeID=@DTypeId AND STypeID=@STypeID

select @curmaxseed=@intDBSeed
--对于提成单，不记录分支机构
IF @intBillType=164 SET @STypeID=''

IF (@intDBSeed = -1)
BEGIN
	INSERT INTO BillCode_Seed(BillType,FlowDate, STypeID,ETypeID,KTypeID,DTypeID,Seed)
		VALUES(@intBillType, @strFlowDate,@STypeID,@ETypeID,@KTypeID,@DTypeId, @maxgroupid)
END
ELSE
BEGIN
	IF (@maxgroupid+@intDBSeed > @intDBSeed)
	BEGIN
		UPDATE BillCode_Seed SET Seed = @maxgroupid+@intDBSeed WHERE BillType = @intBillType AND FlowDate=@strFlowDate AND ETypeID=@ETypeID AND KTypeID=@KTypeID AND DTypeID=@DTypeID AND STypeID=@STypeID
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveBillCode_Seed]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_SaveBillCode_Seed]
GO





/*

功能说明：       保存单据编号的种子数

作    者：       冯波

创建日期：       2010-8-23

返回结果：       

*/

CREATE PROCEDURE [GP_SaveBillCode_Seed]
(	
	@intBillNumberID			INT,
	@dBillDate					datetime,			--制单日期
	@intBillType				int,				--单据类型
    @strBillCode				varchar(200)		--单据编号
)
--@encode$--
AS
--根据单据编号得到种子数

IF ( CHARINDEX('-', @strBillCode) = 0 )
BEGIN
	RETURN
END


DECLARE @strSeed VARCHAR(200)

SELECT @strSeed = RTRIM(LTRIM(REVERSE(SUBSTRING(REVERSE(@strBillCode), 1 , CHARINDEX('-', REVERSE(@strBillCode))-1))))

IF ISNUMERIC(@strSeed) = 0
BEGIN
	RETURN
END

-- BEGIN
-- 修 改 人：罗淮文
-- 修改日期：2014-05-26
-- 内容描述：FllwNo字段不再取制单日期，更改为单据编号中的日期。
--IF NOT EXISTS (SELECT * FROM CodeConfig WHERE BillType=@intBillType)
--BEGIN
	DECLARE @splitIndex int = 0
	DECLARE @s varchar(200)
	--去掉末尾流水号：10000-70-70-4102-T-GJZFRM-TX => 70-70-4102-T-GJZFRM-TX
	SELECT @s = SUBSTRING(REVERSE(@strBillCode),CHARINDEX('-',REVERSE(@strBillCode))+1,len(@strBillCode))
	--获取第一个出现'-'字符的位置
	SELECT @splitIndex = CHARINDEX('-',@s)
	--如果第一个出现'-'字符的位置大于3，则表明日期格式不是以'-'分割。如：70704102-T-GJZFRM-TX
	DECLARE @isdatestr VARCHAR(200)

	IF @splitIndex > 3
	BEGIN
		--SELECT @dBillDate = CAST(REVERSE(SUBSTRING(@s,0,CHARINDEX('-',@s))) AS DATETIME)
		SELECT @isdatestr = REVERSE(SUBSTRING(@s,0,CHARINDEX('-',@s)))
	END
	ELSE
	BEGIN
		--SELECT @dBillDate = CAST(REVERSE(SUBSTRING(@s,1,len('yyyy-MM-dd'))) AS DATETIME)
		SELECT @isdatestr = REVERSE(SUBSTRING(@s,1,len('yyyy-MM-dd')))
	END
	IF ((SELECT value  FROM UserConfig WHERE ConfigName='billcodedateseparator')=2)
	BEGIN
		SET @isdatestr=replace(replace( replace(@isdatestr,'日',''),'月','-'),'年','-')
	END
	IF ISDATE(@isdatestr)=1
	BEGIN
		SELECT @dBillDate = CAST(@isdatestr as DATETIME)
	END
--END


DECLARE @intSeed NUMERIC(18,0)


SELECT @intSeed = CAST(@strSeed AS NUMERIC(18,0))	


--取得数据库当前种子数
DECLARE	@intFlowMode	INT		--流水依据，1表示按日2表示按月3表示按年

DECLARE @BillCodeConfig varchar(1),@FlowLen INT
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置

SELECT @FlowLen=CAST(Value AS INT)+3 FROM UserConfig WHERE ConfigName='FlowLen'

DECLARE
	@MONTH 						VARCHAR(500), 		--自动产生编号时为月份，自定义编号时是经手人名字
	@DAY 						VARCHAR(500)		--自动产生编号时为日期，自定义编号时为仓库名


DECLARE
		@ETypeID	VARCHAR(100),
		@KTypeID	VARCHAR(100),
		@DTypeID	VARCHAR(100),
		@CETypeID	VARCHAR(100),
		@STypeID	VARCHAR(100)

IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@intBillType AND (Code1<>'' or Code2<>'' OR Code3<>'' OR Code4<>''
OR Code5<>'' OR Code6<>'' OR Code7<>'' OR Code8<>'' OR Code9<>'' OR Code10<>'' OR Code11<>'' OR Code12<>'' OR Code13<>'' )) AND @BillCodeConfig='1'
 --单据采用自定义编号 #02
BEGIN
	DECLARE @Code1 varchar(100),@Code2 varchar(100),@Code3 varchar(100),@Code4 varchar(100),@Code5 varchar(100),
			@Code6 varchar(100),@Code7 varchar(100),@Code8 varchar(100),@Code9 varchar(100),@Code10 varchar(100),
			@Code11 varchar(100),@Code12 varchar(100)

	--多仓库中，只有采购换货是按的入库，其余的都是按的出库
	IF @intBillType IN (300,301,313)
	BEGIN
		SELECT @ETypeID=ETypeID,@KTypeID=KTypeID,@DTypeID=DtypeId,@CETypeID=Checke,@STypeID=STypeID
		FROM OrderIndex
		WHERE BillNumberID=@intBillNumberID 
	END	
	ELSE IF @intBillType IN (306)
	BEGIN
		SELECT @ETypeID=a.ETypeID,@KTypeID=a.KTypeID,@CETypeID=Checke,@STypeID=b.STypeID
		FROM StockCheckIndex a
		INNER JOIN Stock b
		ON a.KTypeID=b.TypeID
		WHERE a.StockCheckID=@intBillNumberID
	END
	ELSE IF @intBillType IN (71,72,87,88)
	BEGIN
		SELECT @ETypeID=ETypeID,@KTypeID=KTypeID,@DTypeID=DtypeId,@CETypeID=Checke,@STypeID=STypeID
		FROM LendIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType IN (162,163,207)
	BEGIN
		SELECT @ETypeID=ETypeID,@DTypeId=DTypeID,@CETypeID=Checke,@STypeID=STypeID
		FROM FaPiaoBillIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType IN (193,194)
	BEGIN
		SELECT @ETypeID=ETypeID,@DTypeId=DTypeID,@CETypeID=Checke,@STypeID=STypeID
		FROM ToolIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =204
	BEGIN
		SELECT @ETypeID=ETypeID,@DTypeId=dtypeid,@CETypeID=Checke,@STypeID=STypeID
		FROM dbo.RequestIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =203
	BEGIN
		SELECT @ETypeID=ETypeID,@DTypeId=dtypeid,@CETypeID=Checke,@STypeID=STypeID
		FROM dbo.SerialAdjustIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =208
	BEGIN
		SELECT @STypeID=STypeID
		FROM dbo.CM_CarUseIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =209
	BEGIN
		SELECT @STypeID=STypeID,@CETypeID=Checke
		FROM dbo.CM_FeeIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =311
	BEGIN
		SELECT	@CETypeID=Checke,
				@STypeID=STypeID
		FROM	dbo.CommissionBillNew
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType=307
	BEGIN
		SELECT @ETypeID=ETypeID,@DTypeId=dtypeid,@STypeID=STypeID
		FROM FixedAssetsIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType IN (404,405)
	BEGIN
		SELECT @ETypeID=ETypeID,@DTypeId=dtypeid,@CETypeID=Checke,@STypeID=STypeID
		FROM ReceiptBillIndex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE IF @intBillType IN (22) --调货申请单
	BEGIN
		SELECT @ETypeID=ApplyETypeID,@DTypeId=dtypeid,@CETypeID=Checke,@STypeID=STypeID,@KTypeID=KTypeID
		FROM posallotapplybillindex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE IF @intBillType IN (412,413)
	BEGIN
		SELECT @ETypeID=etypeid,@DTypeId=dtypeid,@STypeID=STypeID,@KTypeID=KTypeID
		FROM onShelvespickIndex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE IF @intBillType IN(418,419,420,421,422)
	BEGIN
		SELECT @ETypeID=etypeid,@DTypeId=dtypeid,@STypeID=STypeID,@KTypeID=KTypeID
		FROM FactIndex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE IF  @intBillType IN(423,424,425,426,428,429)
	BEGIN
		SELECT @ETypeID=etypeid,@DTypeId=dtypeid,@CETypeID=Checke,@STypeID=STypeID,@KTypeID=CASE WHEN @intBillType IN (424,425) THEN OutKTypeId ELSE InKTypeId END
		FROM dbo.Coupon_BillIndex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE IF  @intBillType IN(327)
	BEGIN
		SELECT @ETypeID=ApplyEtypeId,@DTypeId=dtypeid,@CETypeID=Checke,@STypeID=STypeID,@KTypeID=KTypeID
		FROM dbo.PosAllotApplyBillIndex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE IF @intBillType IN(326,328,329)
	BEGIN
		SELECT @ETypeID=ApplyEtypeId,@DTypeId=dtypeid,@CETypeID=Checke,@STypeID=STypeID,@KTypeID=CASE WHEN ISNULL(KTypeID,'')='' THEN InKtypeId ELSE KtypeId END
		FROM dbo.PosAllotApplyBillIndex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE
	BEGIN
		SELECT @ETypeID=ETypeID,
				@KTypeID=CASE WHEN @intBillType IN (161,160,188) THEN KTypeID2 
							  WHEN @intBillType =166 THEN Ktypeid3 
							  ELSE KTypeID END,
				@DTypeId=DTypeId,
				@CETypeID=Checke,
				@STypeID=STypeID
		FROM BillIndex
		WHERE BillNumberID=@intBillNumberID
	END
	

	IF @ETypeID IS NULL SET @ETypeID=''
	IF @KTypeID IS NULL SET @KTypeID=''
	IF @DTypeID IS NULL SET @DTypeID=''
	IF @CETypeID IS NULL SET @CETypeID=''
	IF @STypeID IS NULL SET @STypeID=''

	DECLARE
		@intFlowType				INT,		--1，按日，2按月，3按年
		@TempCode					VARCHAR(1000),
		@strFlowDate				VARCHAR(100)


	SELECT 	@Code1=code1,@Code2=code2,@Code3=code3,@Code4=code4,@Code5=code5,@Code6=code6,@Code7=code7,@Code8=code8,
			@Code9=code9,@Code10=code10,@Code11=code11,@Code12=code12  FROM CodeConfig WHERE BillType = @intBillType



	SET @TempCode = @Code1 +'*'+ @Code2 +'*'+ @Code3 +'*'+ @Code4 +'*'+ @Code5 +'*'+ @Code6 +'*'+ @Code7 +'*'+ @Code8 +'*'+ @Code9 +'*'+ @Code10 +'*'+ @Code11 +'*'+ @Code12	

	
	IF @Code1<>'仓库编号' AND @Code2<>'仓库编号' AND @Code3<>'仓库编号' AND @Code4<>'仓库编号' AND @Code5<>'仓库编号' AND @Code6<>'仓库编号' AND @Code7<>'仓库编号' AND @Code8<>'仓库编号' AND @Code9<>'仓库编号' AND @Code10<>'仓库编号' AND @Code11<>'仓库编号' AND @Code12<>'仓库编号'
	BEGIN
		SET @KTypeID=''
	END

	IF @Code1<>'经手人编号' AND @Code2<>'经手人编号' AND @Code3<>'经手人编号' AND @Code4<>'经手人编号' AND @Code5<>'经手人编号' AND @Code6<>'经手人编号' AND @Code7<>'经手人编号' AND @Code8<>'经手人编号' AND @Code9<>'经手人编号' AND @Code10<>'经手人编号' AND @Code11<>'经手人编号' AND @Code12<>'经手人编号'
	BEGIN
		SET @ETypeID=''
	END
	
	IF @Code1<>'部门编号' AND @Code2<>'部门编号' AND @Code3<>'部门编号' AND @Code4<>'部门编号' AND @Code5<>'部门编号' AND @Code6<>'部门编号' AND @Code7<>'部门编号' AND @Code8<>'部门编号' AND @Code9<>'部门编号' AND @Code10<>'部门编号' AND @Code11<>'部门编号' AND @Code12<>'部门编号'
	BEGIN
		SET @DTypeID=''
	END
	
	IF @Code1<>'制单人编号' AND @Code2<>'制单人编号' AND @Code3<>'制单人编号' AND @Code4<>'制单人编号' AND @Code5<>'制单人编号' AND @Code6<>'制单人编号' AND @Code7<>'制单人编号' AND @Code8<>'制单人编号' AND @Code9<>'制单人编号' AND @Code10<>'制单人编号' AND @Code11<>'制单人编号' AND @Code12<>'制单人编号'
	BEGIN
		SET @CETypeID=''
	END

	/*
	IF @Code1<>'分支机构编号' AND @Code2<>'分支机构编号' AND @Code3<>'分支机构编号' AND @Code4<>'分支机构编号' AND @Code5<>'分支机构编号' AND @Code6<>'分支机构编号' AND @Code7<>'分支机构编号' AND @Code8<>'分支机构编号' AND @Code9<>'分支机构编号' AND @Code10<>'分支机构编号' AND @Code11<>'分支机构编号' AND @Code12<>'分支机构编号'
	BEGIN
		SET @STypeID=''
	END
	*/
END
ELSE
BEGIN
	SELECT 
			@ETypeID='',
			@KTypeID='',
			@DTypeID='',
			@CETypeID=''
			
	IF @intBillType IN (300,301,313)
	BEGIN
		SELECT @STypeID=STypeID
		FROM OrderIndex
		WHERE BillNumberID=@intBillNumberID 
	END	
	ELSE IF @intBillType IN (306)
	BEGIN
		SELECT @STypeID=b.STypeID
		FROM StockCheckIndex a
		INNER JOIN Stock b
		ON a.KTypeID=b.TypeID
		WHERE a.StockCheckID=@intBillNumberID
	END
	ELSE IF @intBillType IN (71,72,87,88)
	BEGIN
		SELECT @STypeID=STypeID
		FROM LendIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType IN (162,163,207)
	BEGIN
		SELECT @STypeID=STypeID
		FROM FaPiaoBillIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType IN (193,194)
	BEGIN
		SELECT @STypeID=STypeID
		FROM ToolIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =204
	BEGIN
		SELECT @STypeID=STypeID
		FROM dbo.RequestIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =203
	BEGIN
		SELECT @STypeID=STypeID
		FROM dbo.SerialAdjustIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =208
	BEGIN
		SELECT @STypeID=STypeID
		FROM dbo.CM_CarUseIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =209
	BEGIN
		SELECT @STypeID=STypeID
		FROM dbo.CM_FeeIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType =311
	BEGIN
		SELECT @STypeID=STypeID
		FROM dbo.CommissionBillNew
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType=307
	BEGIN
		SELECT @STypeID=STypeID
		FROM FixedAssetsIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType=309 --参照计划提成
	BEGIN
	  SET @STypeID=''
	END
	ELSE IF @intBillType IN (404,405)
	BEGIN
		SELECT @STypeID=STypeID 
		FROM dbo.ReceiptBillIndex
		WHERE BillNumberID=@intBillNumberID
	END
	ELSE IF @intBillType IN (22,326)
	BEGIN
		SELECT @STypeID=STypeID
		FROM posallotapplybillindex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE IF @intBillType IN (412,413)
	BEGIN
		SELECT @STypeID=STypeID
		FROM onShelvespickIndex
		WHERE BillNumberID=@intBillNumberID 
	END
	ELSE IF @intBillType IN(418,419,420,421,422)
	BEGIN
		SELECT @STypeID=STypeID FROM FactIndex WHERE billNumberID=@IntBillNumberID
	END
	ELSE IF  @intBillType IN(423,424,425,426,428,429)
	BEGIN 
		SELECT @STypeID=STypeID
		FROM dbo.Coupon_BillIndex
		WHERE BillNumberID=@intBillNumberID
	END 
	ELSE IF  @intBillType IN(327,328,329)
	BEGIN 
		SELECT @STypeID=STypeID
		FROM dbo.PosAllotApplyBillIndex
		WHERE BillNumberID=@intBillNumberID
	END 
	ELSE
	BEGIN
		SELECT @STypeID=STypeID
		FROM BillIndex
		WHERE BillNumberID=@intBillNumberID
	END

	IF @STypeID IS NULL SET @STypeID=''
	
END

--2019-10-28 陈强
--这里取单据自己设置的编号

SET @intFlowType=999999--代表没有设置单据编号规则
SELECT  @intFlowType=CodeFlowset FROM CodeConfig WHERE Billtype= @intBillType

IF @intFlowType=999999
BEGIN
	SELECT @intFlowType=Value
	FROM UserConfig
	WHERE ConfigName='FlowSet'
END
	
IF @intFlowType=0
BEGIN
	--按日
	--print '1'
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@dBillDate) AS VARCHAR(2)),'0')+DBO.FN_FixStr(2,CAST(DAY(@dBillDate) AS VARCHAR(2)),'0')
END
ELSE IF @intFlowType=1
BEGIN
	--按月
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')+DBO.FN_FixStr(2,CAST(MONTH(@dBillDate) AS VARCHAR(2)),'0')
END
ELSE IF @intFlowType=2
BEGIN
	--按年
	SELECT @strFlowDate=DBO.FN_FixStr(4,CAST(YEAR(@dBillDate) AS VARCHAR(4)),'0')
END

DECLARE @intDBSeed NUMERIC(18,0)

SELECT @intDBSeed = -1

SELECT	@intDBSeed = ISNULL(MAX(Seed), -1) 
FROM	BillCode_Seed 
WHERE	BillType = @intBillType 
		AND FlowDate=@strFlowDate 
		AND ETypeID=@ETypeID 
		AND KTypeID=@KTypeID 
		AND DTypeID=@DTypeId 
		AND CETypeID=@CETypeId
		AND STypeID=@STypeID

--对于提成单，不记录分支机构
IF @intBillType=164 SET @STypeID=''

IF (@intDBSeed = -1)
BEGIN
	INSERT INTO BillCode_Seed(BillType,FlowDate, STypeID,ETypeID,KTypeID,DTypeID,CETypeId,Seed)
		VALUES(@intBillType, @strFlowDate,@STypeID,@ETypeID,@KTypeID,@DTypeId, @CETypeId, @intSeed)
END
ELSE
BEGIN   
	IF (@intSeed > @intDBSeed)
	BEGIN	   
		UPDATE	BillCode_Seed 
		SET		Seed = @intSeed 
		WHERE	BillType = @intBillType 
				AND FlowDate=@strFlowDate 
				AND ETypeID=@ETypeID 
				AND KTypeID=@KTypeID 
				AND DTypeID=@DTypeID 
				AND CETypeID=@CETypeID
				AND STypeID=@STypeID
	END
END



GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveBillCodeConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SaveBillCodeConfig]
GO


--功能：保存单据编号配置
--作者：徐辉
CREATE     PROCEDURE GP_SaveBillCodeConfig
(
	@IfBillCode				INT,
	@NoBillCode				INT,
	@FlowLen				INT,
	@Billcodeindex			VARCHAR(4),
	@PassOneDay				INT,
	@BillcodeDateSeparator	INT,
	@AlertBillcodeRepeat	INT,
	@BillcodeAllowRepeat	INT,
	@FlowSet				INT,
	@BillcodeCreateTime		INT,
	@AlertBillcodeChange	INT
)
--@encode$--
AS
SET NOCOUNT ON 
IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='IfBillCode')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('IfBillCode',@IfBillCode,'00001','')
ELSE 
	UPDATE UserConfig SET Value=@IfBillCode WHERE ConfigName='IfBillCode'
	
IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='NoBillCode')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('NoBillCode',@NoBillCode,'00001','')
ELSE
	UPDATE UserConfig SET Value=@NoBillCode WHERE ConfigName='NoBillCode'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='FlowLen')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowLen',@FlowLen,'','')
ELSE
	UPDATE UserConfig SET Value=@FlowLen WHERE ConfigName='FlowLen'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='Billcodeindex')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('Billcodeindex',@Billcodeindex,'00001','')
ELSE
	UPDATE UserConfig SET Value=@Billcodeindex WHERE ConfigName='Billcodeindex'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='passoneday')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('passoneday',@PassOneDay,'','')
ELSE
	UPDATE UserConfig SET Value=@PassOneDay WHERE ConfigName='passoneday'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='BillcodeDateSeparator')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeDateSeparator',@BillcodeDateSeparator,'','')
ELSE
	UPDATE UserConfig SET Value=@BillcodeDateSeparator WHERE ConfigName='BillcodeDateSeparator'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='AlertBillcodeRepeat')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('AlertBillcodeRepeat',@AlertBillcodeRepeat,'','')
ELSE
	UPDATE UserConfig SET Value=@AlertBillcodeRepeat WHERE ConfigName='AlertBillcodeRepeat'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='BillcodeAllowRepeat')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeAllowRepeat',@BillcodeAllowRepeat,'','')
ELSE
	UPDATE UserConfig SET Value=@BillcodeAllowRepeat WHERE ConfigName='BillcodeAllowRepeat'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='FlowSet')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('FlowSet',@FlowSet,'','')
ELSE
	UPDATE UserConfig SET Value=@FlowSet WHERE ConfigName='FlowSet'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='BillcodeCreateTime')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('BillcodeCreateTime',@BillcodeCreateTime,'','')
ELSE
	UPDATE UserConfig SET Value=@BillcodeCreateTime WHERE ConfigName='BillcodeCreateTime'

IF NOT EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='AlertBillcodeChange')
	INSERT INTO UserConfig(ConfigName,Value,ETypeId,IsAll)VALUES('AlertBillcodeChange',@AlertBillcodeChange,'','')
ELSE
	UPDATE UserConfig SET Value=@AlertBillcodeChange WHERE ConfigName='AlertBillcodeChange'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveBillDiyColumnsConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_SaveBillDiyColumnsConfig
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：	  MXRong
	日期：2015-10-22
	描述：单据自定义配置--保存
-------------------------------------------*/
CREATE PROCEDURE GP_SaveBillDiyColumnsConfig
(
	@Details	Tb_BillDiyColumnsConfig	READONLY
)
--@encode$--
AS
SET NOCOUNT ON

	--表头自定义
	MERGE Custom_Column_BillIndex AS target
	USING 
		(
			SELECT BillType ,CustomColumnId ,Label ,IsVisible ,IsRequired 
			FROM @Details
			WHERE ifindex=1	 AND isdisplay=0
		) AS source (BillType ,CustomColumnId ,Label ,IsVisible ,IsRequired)
		ON 
		(
			 target.BillType=source.BillType
			AND target.CustomColumnId=source.CustomColumnId
		
		)
		WHEN MATCHED 
		THEN UPDATE SET TARGET.Label = SOURCE.Label, target.IsVisible =source.IsVisible	,target.IsRequired =source.IsRequired
		WHEN NOT MATCHED BY TARGET 
		THEN INSERT( BillType ,CustomColumnId ,Label ,IsVisible ,IsRequired )
			VALUES (SOURCE.BillType,source.CustomColumnId,source.Label,source.IsVisible,source.IsRequired);

		--表头显示字段
	MERGE Custom_DisplayColumn_BillIndex AS target
	USING 
		(
			SELECT BillType ,CustomColumnId AS orderid,Label ,IsVisible ,CustomDisColumnId 
			FROM @Details
			WHERE ifindex=1	AND isdisplay=1
		) AS source (BillType ,orderid ,Label ,IsVisible ,CustomDisColumnId)
		ON 
		(
			 target.BillType=source.BillType
			AND target.orderid=source.orderid
		
		)
		WHEN MATCHED 
		THEN UPDATE SET TARGET.Label = SOURCE.Label, target.IsVisible =source.IsVisible	,target.CustomDisColumnId =source.CustomDisColumnId
		WHEN NOT MATCHED BY TARGET 
		THEN INSERT( BillType ,OrderId ,Label ,IsVisible ,CustomDisColumnId )
			VALUES (SOURCE.BillType,source.OrderId,source.Label,source.IsVisible,source.CustomDisColumnId);
			
	  --表体
		MERGE Custom_Column_BillDetail AS target
		USING 
		(
			SELECT BillType ,CustomColumnId ,Label ,IsVisible ,IsRequired,inout
			FROM @Details
			WHERE ifindex=0	 AND isdisplay=0
		) AS source (BillType ,CustomColumnId ,Label ,IsVisible ,IsRequired,inout)
		ON 
		(
			 target.BillType=source.BillType
			AND target.CustomColumnId=source.CustomColumnId
			AND ISNULL(target.inout,'')=ISNULL(source.inout,'')
		
		)
		WHEN MATCHED 
		THEN UPDATE SET TARGET.Label = SOURCE.Label, target.IsVisible =source.IsVisible	,target.IsRequired =source.IsRequired
		WHEN NOT MATCHED BY TARGET 
		THEN INSERT( BillType ,CustomColumnId ,Label ,IsVisible ,IsRequired,inout )
			VALUES (SOURCE.BillType,source.CustomColumnId,source.Label,source.IsVisible,source.IsRequired,ISNULL(source.inout,''));
		


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveBillPrintConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SaveBillPrintConfig]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-11-3
	描述：单据打印配置--保存
-------------------------------------------*/
CREATE PROCEDURE GP_SaveBillPrintConfig
(
	@PassWord	VARCHAR(10),
	@Details	Tb_BillPrintConfig	READONLY
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE BillPrintConfig 
	SET BillTypes = D.BillTypes,BillType = D.BillType,AddState=D.AddState,
		SaveState = D.SaveState,PassState=D.PassState,SaveAlert=D.SaveAlert,PassAlert=D.PassAlert,PrintNum=D.PrintNum
FROM @Details D
INNER JOIN BillPrintConfig B ON B.BillType = D.BillType

DECLARE @PassWordKey VARCHAR(100)
SET @PassWordKey = 'fullPrintPassword'
  
--判断解锁密码是否存在相关记录
IF NOT EXISTS (SELECT TOP 1 1 FROM Userconfig WHERE ConfigName=@PassWordKey)
  BEGIN 
      INSERT INTO Userconfig (ConfigName,Value) VALUES (@PassWordKey,@PassWord)
  END
ELSE
  BEGIN
      UPDATE Userconfig SET Value=@PassWord WHERE ConfigName=@PassWordKey
  END   


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveCommissionScheme]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SaveCommissionScheme]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：王珏
	日期：2014-04-22
	描述：保存提成方案
*/
CREATE	PROCEDURE	Gp_SaveCommissionScheme
(
	@BillNumberId			NUMERIC(18,0),
	--@SchemeStart			DATETIME,
	--@SchemeEnd				DATETIME,
	@SchemeName				VARCHAR(256),	--方案名称
	@CommissionRuleID		NUMERIC(18,0),	--提成规则
	@ReferencePlanID		NUMERIC(18,0),	--参照计划提成
	@Comment				VARCHAR(256),	--摘要
	@Checke					VARCHAR(50),	--制单人
	@CheckeTime				DATETIME,		--制单时间
	@stypeid				VARCHAR(MAX),	--分支机构
	@flag					INT				--1：新增，2：修改	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @CommissionRuleState INT
DECLARE @ReferencePlanState INT
IF @CommissionRuleID <> -1
	SELECT @CommissionRuleState = UseState FROM CommissionRule WHERE BillNumberId = @CommissionRuleID

IF @ReferencePlanID <> -1
	SELECT @ReferencePlanState = UseState FROM ReferencePlanCommission WHERE BillNumberId = @ReferencePlanID
	
IF @flag =1
BEGIN
	INSERT INTO CommissionScheme ( --SchemeStart,
								   --SchemeEnd,
							       SchemeName,
							       CommissionRuleID,
								   ReferencePlanID,
								   Comment,
								   Checke,							
								   Checker,
								   CheckeTime,
								   CheckerTime,
								   BillState,
								   UseState,
							       IsStop
							      )
							VALUES( --@SchemeStart,
									--@SchemeEnd,
									@SchemeName,
									@CommissionRuleID,		
									@ReferencePlanID,
									@Comment,
									@Checke,
									'',
									@CheckeTime,
									NULL,
									1,
									1,
									0
								   )
	SELECT  @BillNumberId = @@IDENTITY
	
	INSERT INTO CommissionSchemeStype
	SELECT @BillNumberId,s.a FROM (SELECT a FROM f_split(@stypeid,',')) s
END					
ELSE
BEGIN
	UPDATE CommissionScheme SET	--SchemeStart=@SchemeStart,
								--SchemeEnd=@SchemeEnd,
								SchemeName=@SchemeName,
								CommissionRuleID=@CommissionRuleID,
								ReferencePlanID=@ReferencePlanID,
								Comment=@Comment
	WHERE  BillNumberId=@BillNumberId
	
	DELETE FROM CommissionSchemeStype WHERE BillNumberId=@BillNumberId
	
	INSERT INTO CommissionSchemeStype
	SELECT @BillNumberId,s.a FROM (SELECT a FROM f_split(@stypeid,',')) s
END

--提成规则和参照计划被引用后，要改写状态    UseState--使用状态  1=未引用  2=引用  3=部分完成 4=全部完成
--当引用前是未引用状态，保存后变为引用状态。当引用前是全部完成状态，保存后变为部分完成状态。其他情况状态不变
IF @CommissionRuleID <> -1 AND (@CommissionRuleState =1 OR @CommissionRuleState = 4)
BEGIN
	DECLARE @NewCommissionRuleState INT	
	IF @CommissionRuleState = 1
		SET @NewCommissionRuleState =2
	ELSE IF @CommissionRuleState = 4
		SET @NewCommissionRuleState =3
		
	UPDATE CommissionRule SET UseState = @NewCommissionRuleState WHERE BillNumberId = @CommissionRuleID
END

IF @ReferencePlanID <> -1 AND (@ReferencePlanState =1 OR @ReferencePlanState = 4)
BEGIN
	DECLARE @NewReferencePlanState INT	
	IF @ReferencePlanState = 1
		SET @NewReferencePlanState =2		
	ELSE IF @ReferencePlanState = 4
		SET @NewReferencePlanState =3
		
	UPDATE ReferencePlanCommission SET UseState = @NewReferencePlanState WHERE BillNumberId = @ReferencePlanID
END
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveCouponExchangePtype]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_SaveCouponExchangePtype
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回优惠券兑换商品方案列表
-- 时间：	2016-07-27
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_SaveCouponExchangePtype
(
	@Billnumberid			INT,			--类型ID
	@BillCode				VARCHAR(200),	--编号
	@BillName				VARCHAR(200),	--名称
	@Comment				VARCHAR(1000),	--备注
	@GridData	Type_CouponExchangePtypeBill READONLY,
	@chvOperatorID			VARCHAR(50),
	@optype					CHAR(1)			--a 添加，m 修改	
)

--@encode$--
AS
SET NOCOUNT ON 

DECLARE	
	@Name	VARCHAR(200),
	@Error	INT=0
	
--判断编号是否重复
SELECT @Name=BillName FROM CouponExchangePtypeIndex WHERE  billcode=@BillCode AND ((@optype='m' AND billnumberid<>@Billnumberid) OR @optype='a')
IF ISNULL(@Name,'')<>''
	BEGIN
		RAISERROR('与【%s】的编号相同 ，请重新进行编号！',16,1,@Name) RETURN
	END
--判断名称是否重复
SELECT @Name=BillName FROM CouponExchangePtypeIndex WHERE  billname=@BillName AND ((@optype='m' AND billnumberid<>@Billnumberid) OR @optype='a')
IF(ISNULL(@Name,'')<>'')
	BEGIN
		RAISERROR('与【%s】的名称相同 ，请重新进行编号！',16,1,@Name) RETURN
	END
BEGIN TRAN

IF LOWER(@optype)='a'--添加
BEGIN
	INSERT INTO CouponExchangePtypeIndex
		(
			billcode,
			billname,
			Comment,
			ETypeId,
			IsVaild,
			billdate
			
		) 
		VALUES
		(
			@BillCode,
			@BillName,
			@Comment,
			@chvOperatorID,
			0,
			getdate()
		)
		SET @Billnumberid=@@IDENTITY
		SET @Error+=@@ERROR
		INSERT INTO [CouponExchangePtypeBill]
		(
			BillNumberId,	
			--ID				
			PtypeId	,		
			Qty	,			
			UnitId	,		
			IsDefault		
		)
		SELECT 		
			@Billnumberid BillNumberId,	
			PtypeId	,		
			Qty,			
			UnitId,		
			IsDefault		
		FROM @GridData
		SET @Error+=@@ERROR
END
ELSE IF  LOWER(@optype)='m' --修改
BEGIN
--检查是否被引用
		DECLARE @IsUsed INT=0
		--SELECT @IsUsed=dbo.Fn_GetIsUse_Items(@NID,100)
		IF(@IsUsed=1)
			BEGIN
				SET @Error+=@@ERROR
			END
		ELSE 
			BEGIN
				UPDATE [CouponExchangePtypeIndex] 
				SET 
					BillCode=@billcode,
					BillName=@billname,
					Comment=@Comment
				WHERE billnumberid=@Billnumberid
				SET @Error+=@@ERROR
				
				--更新已有明细
				
				delete from [CouponExchangePtypeBill] where billnumberid=@Billnumberid
				
				--插入新增明细
				INSERT INTO [CouponExchangePtypeBill]
				(
					BillNumberId,	
					--ID				
					PtypeId	,		
					Qty	,			
					UnitId	,		
					IsDefault		
				)
				SELECT 		
					@Billnumberid BillNumberId,	
					PtypeId	,		
					Qty,			
					UnitId,		
					IsDefault		
				FROM @GridData
						
				SET @Error+=@@ERROR
			END


END

IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
RETURN @Error
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.GP_SaveCouponInfo') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.GP_SaveCouponInfo
GO

/*
作者：舒珊
描述：保存单据使用优惠券情况
*/
CREATE              PROCEDURE GP_SaveCouponInfo
(
	@billtype INT,
	@billnumberid INT,
	@CouponCode VARCHAR(max)
)
--@encode$--
AS 
SET NOCOUNT ON
	IF @billtype NOT  IN (305,215,11,45,12,46)
	RETURN;
	IF @billnumberid=-1
	RETURN ;
	
	--删除多的
	DELETE FROM Coupon_BillUsed 
	WHERE BillnumberId=@billnumberid 
	AND billtype= @billtype 
	AND NOT EXISTS  (SELECT  a FROM dbo.f_split(@CouponCode,',') f  where f.a=Coupon_BillUsed.couponcode)
	
	--已有的保持不动
	--添加新增的
	INSERT INTO Coupon_BillUsed
		(		BillnumberId,
				BillType,
				CouponCode,
				CouponId
		)
	SELECT distinct @billnumberid,
			@billtype,
			a.a,
			c.CouponId
		FROM dbo.f_split(@CouponCode,',') A 
		INNER JOIN  coupon_codeinfo c ON a.a=c.CouponCode
		WHERE ISNULL(A,'')<>'' 
		AND NOT EXISTS (SELECT couponcode
						FROM Coupon_BillUsed 
						WHERE BillnumberId=@billnumberid 
						AND billtype= @billtype
						AND A.a= Coupon_BillUsed.CouponCode)
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'dbo.GP_SaveCouponInfoAutoDraft') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.GP_SaveCouponInfoAutoDraft
GO

/*
作者：舒珊
描述：保存单据使用优惠券情况
*/
CREATE              PROCEDURE GP_SaveCouponInfoAutoDraft
(
	@billtype		INT,
	@billguid		VARCHAR(100),
	@CouponCode		VARCHAR(max)
)
--@encode$--
AS 
SET NOCOUNT ON

IF @billtype NOT  IN (305,215,11,45,12,46)
RETURN;
	
--删除多的
DELETE 
FROM	Coupon_BillUsedAutoDraft 
WHERE	BillGuid	=  @billguid 
		AND billtype = @billtype 
		AND NOT EXISTS  (SELECT  a FROM dbo.f_split(@CouponCode,',') f  where f.a=Coupon_BillUsedAutoDraft.couponcode)
	
--已有的保持不动
--添加新增的
INSERT INTO Coupon_BillUsedAutoDraft
(		
		BillGuid,
		BillnumberId,
		BillType,
		CouponCode,
		CouponId
)
SELECT	DISTINCT  
		@billguid,
		-1,
		@billtype,
		a.a,
		c.CouponId
FROM dbo.f_split(@CouponCode,',') A 
INNER JOIN  coupon_codeinfo c ON a.a=c.CouponCode
WHERE ISNULL(A,'')<>'' 
AND NOT EXISTS (
	SELECT	couponcode
	FROM	Coupon_BillUsedAutoDraft 
	WHERE	BillGuid=@billguid 
			AND billtype= @billtype
			AND A.a= Coupon_BillUsedAutoDraft.CouponCode
)
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveCurrency]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_SaveCurrency]
GO    

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		彭勇
-- Create date: 2012-03-31
-- Description:	币种基础资料的数据库操作-添加、修改、删除
--返回:	成功:1 失败：0 记录重复：2 
-- =============================================
CREATE PROCEDURE [dbo].[Gp_SaveCurrency]
(
    @cid		INT,			--ID  
    @usercode	VARCHAR(200),	--代码
    @fullname	VARCHAR(200),	--名称
    @rate		 NUMERIC(24, 10) ,	--税率
    @basistype	INT,			--方式
	@type		INT				--操作类型：1：新增 2：编辑 3:删除 4：启用 5：停用
)      
--@encode$--
AS 
SET NOCOUNT ON 
IF(@type=1 OR @type=2)
	BEGIN
		DECLARE @Name VARCHAR(200)

		--判断编号是否重复
		IF(ISNULL(@cid,0)>0)
			SELECT @Name=FullName FROM Ac_Currency WHERE UserCode=@usercode AND cid<>@cid
		ELSE
			SELECT @Name=FullName FROM Ac_Currency WHERE UserCode=@usercode
		IF(ISNULL(@Name,'')<>'')
			BEGIN
				DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
				RAISERROR(@MSG,16,1)RETURN
			END
		--判断名称是否重复
		IF(ISNULL(@cid,0)>0)
			SELECT @Name=FullName FROM Ac_Currency WHERE FullName=@fullname AND cid<>@cid
		ELSE
			SELECT @Name=FullName FROM Ac_Currency WHERE FullName=@fullname
		IF(ISNULL(@Name,'')<>'')
			BEGIN
				DECLARE @MSG1 VARCHAR(100)='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
				RAISERROR(@MSG1,16,1)RETURN
			END	
		IF (@type=1) --新增
			BEGIN
				INSERT INTO Ac_Currency
				(
					UserCode,
					FullName,
					Rate,
					BasisType,
					PyCode,
					Deleted,
					sysrow
				)VALUES
				(
					@usercode,
					@fullname,
					@rate,
					@basistype,
					NULL,
					0,
					0
				) 
				
				DECLARE @ID NUMERIC(18,0)
				SET  @ID= SCOPE_IDENTITY();
				INSERT  INTO dbo.Ac_Account_Assist_CheckItems(STypeId,ATypeId,Cid,Ascids,IsRequired,DTypeID,AcId)
				SELECT  t1.STypeId,
						t2.ATypeId,
						@ID,
						t2.AscIds,
						1 AS IsRequired,
						'',
						T1.AcId
				FROM    dbo.Ac_Account t1
						INNER JOIN dbo.Ac_Account_Assist_CheckItems t2 ON t1.StypeId = t2.STypeId AND t1.TypeId = t2.ATypeId
				WHERE   t1.cid = 0
				GROUP BY t1.STypeId,t2.ATypeId,t2.AscIds,T1.AcId

			END
		ELSE IF (@type=2) --修改
			BEGIN
				UPDATE Ac_Currency
				SET	
					UserCode=@usercode,
					FullName=@fullname,
					Rate=@rate,
					BasisType=@basistype
				WHERE CId=@cid 
			END	
	END
ELSE IF(@type=3)--删除
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Currency WHERE CId=@cid)
			BEGIN
				RAISERROR('该信息已经删除！不能执行该操作',16,1)RETURN
			END
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Currency WHERE Sysrow=1 AND CId=@cid)
			BEGIN
				RAISERROR('系统默认数据，不能删除！',16,1)RETURN
			END
		--判断是否被使用
		DECLARE @Ret INT
		SELECT @Ret=dbo.[Fn_GetIsUse_Items](@cid,1) 
		IF(@Ret=1)
			BEGIN
				RAISERROR('该信息已被使用！不能删除',16,1)RETURN
			END
		DELETE FROM Ac_Account_Assist_CheckItems WHERE Cid=@cid--删除科目——币种辅助表
		
		DELETE FROM Ac_Currency WHERE CId=@cid

	END

IF @type<>3
BEGIN
	EXEC Gp_DataSaveForPosDown '-99999','Ac_Currency','0'
END
ELSE
BEGIN
	EXEC Gp_DataSaveForPosDown '-99999','Ac_Currency',@cid
END

IF(@@ERROR<>0)
	RAISERROR('执行异常！',16,1)
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_DealStockAlerm' AND ss.name=N'dbo')
	BEGIN
		IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveDealStockAlermSetList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
			DROP PROCEDURE [dbo].[Gp_SaveDealStockAlermSetList]
		DROP type [dbo].Type_DealStockAlerm 
	END
GO
CREATE TYPE Type_DealStockAlerm AS TABLE
(
	KTypeId		VARCHAR(50),--仓库ID     
	PTypeId		VARCHAR(50),--商品ID 
	UpLimitQty	NUMERIC(24,10),--库存上限  
	DownLimitQty NUMERIC(24,10),--库存下限  
	OrderQty	NUMERIC(24,10)--订货库存
)
GO

IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveDealStockAlermSetList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_SaveDealStockAlermSetList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


-- ========================================================================
-- 描述：	ptype 保存库存预警设置
-- 时间：	2018-04-03
-- 作者：	GLJ
-- ========================================================================
CREATE PROCEDURE Gp_SaveDealStockAlermSetList
(
	@PtypeList		Type_DealStockAlerm READONLY,
	@OperatorId		VARCHAR(50)--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Error INT=0

BEGIN TRAN

DELETE FROM StockAlarm 
FROM StockAlarm S 
INNER JOIN @PtypeList P ON P.PTypeId=s.PTypeId AND P.KTypeId=S.KTypeId
SET @Error+=@@ERROR

INSERT INTO StockAlarm
(
	PTypeId,
	KTypeId,
	UpLimitQty,
	DownLimitQty,
	OrderQty
)
SELECT 
	PTypeId,
	KTypeId,
	UpLimitQty,
	DownLimitQty,
	OrderQty
FROM @PtypeList
WHERE 
	UpLimitQty<>0 
	OR DownLimitQty<>0 
	OR OrderQty<>0
SET @Error+=@@ERROR


IF(@Error=0)
	BEGIN
		COMMIT TRAN
		RETURN 1
	END
ELSE 
	BEGIN
		ROLLBACK TRAN
		RETURN 0
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveDepositBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveDepositBillDT
GO

/*
作者：吕文祺
描述：写入寄存单据明细表(表值)
*/
CREATE  PROCEDURE Gp_SaveDepositBillDT
(
	@details TBType_DepositBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO dbo.DepositBillDetail
(		
		DepositBillID,	
		BillNumberID,	
		PID,
		PosBillDetailID,
		UnitID,
		BaseUnitId,
		UnitRate,				
		total,			
		price,			
		saleqty,			
		depositedqty,	
		depositqty,		
		pickupqty,		
		pickedupqty,		
		depositprice,	
		remainqty,		
		pickupprice,		
		unpickupqty,		
		unpickupmoney,
		Guid	
)
SELECT 	
        a.DepositBillID,	
		a.PosBillNumberID,	
		a.PID,
		a.PosBillDetailID,
		a.UnitID,
		a.BaseUnitId,
		a.UnitRate,				
		a.total,			
		a.price,			
		a.saleqty,			
		a.depositedqty,	
		a.depositqty,		
		a.pickupqty,		
		a.pickedupqty,		
		a.depositprice,	
		a.remainqty,		
		a.pickupprice,		
		a.unpickupqty,		
		a.unpickupmoney,
		a.Guid	
		
FROM @details a

		
if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据明细发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveDepositBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveDepositBillIndex
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：吕文祺
	日期：2017-8-01
	描述：保存寄存单据主表
-------------------------------------------*/
CREATE PROCEDURE [dbo].Gp_SaveDepositBillIndex
(
	@DepositBillID						INT,
	@DepositIndexID						INT,
	@PosBillNumberID					INT,
	@BillCode							VARCHAR(50),
	@SaleTime                           VARCHAR(50),
	@DepositBillTime					VARCHAR(50),
	@PickUpBillTime						VARCHAR(50),
	@SID								INT,
	@BID								INT,
	@KID								INT,
	@EID								INT,
	@POSID								INT,
	@DepositPerson						VARCHAR(200),
	@PickUpPerson						VARCHAR(200),
	@Guid								VARCHAR(50)
)
--@encode$--
AS 
SET NOCOUNT ON


INSERT INTO dbo.DepositBillIndex
( 
	DepositIndexID	,
	PosBillNumberID,
	BillCode,
	SaleTime,
	DepositBillTime ,
	PickUpBillTime ,
	SID ,
	BID ,
	KID ,
	EID ,
	POSID ,
	DepositPerson ,
	PickUpPerson,
	Guid
)
VALUES  
( 
	@DepositIndexID	,
	@PosBillNumberID,
	@BillCode	,
	@SaleTime	,
	@DepositBillTime,
	@PickUpBillTime	,
	@SID,		
	@BID,			
	@KID,			
	@EID,			
	@POSID,			
	@DepositPerson,	
	@PickUpPerson,
	@Guid	
)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveDocFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveDocFile
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-10-27
	描述：保存文档管理系统文档
*/
CREATE PROCEDURE Gp_SaveDocFile
(
	@etypeid			varchar(50),		--上传者id
	@uploaddate			datetime,			--上传时间
	@pathid				varchar(50),		--路径id
	@filesize			int,				--文件大小
	@filename			varchar(200),		--文件名称
	@filetype			varchar(50),		--文件类型
	@binarydata			image				--文件内容
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @doccapacity int=50,@sum numeric(18,0)=0

SELECT @doccapacity=Value FROM Userconfig WHERE ConfigName='doccapacity'
SELECT @sum=SUM(FileSize) FROM DocFile WHERE etypeid=@etypeid AND LEFT(pathId,5)='00002'

if(@doccapacity*1024*1024<@sum+@filesize)
BEGIN
	RAISERROR('我的文档剩余容量小于当前上传文档大小！',16,1)
	RETURN
END

IF EXISTS(SELECT * FROM DocFile WHERE etypeid=@etypeid AND pathId=@pathid AND FullName=@filename)
BEGIN
	RAISERROR('该文件夹下已存在相同文件名的文档，请更换文件名后重试！',16,1)
	RETURN
END

INSERT INTO DocFile
(
	etypeid,
	UploadDate,
	pathId,
	FileSize,
	FileType,
	FullName,
	Binarydata
)
VALUES
(
	@etypeid,
	@uploaddate,
	@pathid,
	@filesize,
	@filetype,
	@filename,
	@binarydata
)

IF @@ERROR<>0
	RAISERROR('上传文件失败！',16,1)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_SaveHyyunAcountInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Gp_SaveHyyunAcountInfo]
GO

/*
	作者：谢吉康
	日期：2018-10-15
	描述：保存行业云短信账号信息
*/
CREATE PROCEDURE Gp_SaveHyyunAcountInfo
(
	@smsusercode			VARCHAR(200),		--账号
	@smspassword			VARCHAR(200),		--密码
	@smsappkey				VARCHAR(200)		--appKey信息
)
AS
SET NOCOUNT ON

UPDATE	dbo.sysdata
SET		SubValue = @smsusercode
WHERE	SubName  = 'hyyunsms_usercode'

UPDATE	dbo.sysdata
SET		SubValue = @smspassword
WHERE	SubName  = 'hyyunsms_password'

UPDATE	dbo.sysdata
SET		SubValue = @smsappkey
WHERE	SubName  = 'hyyunsms_appkey'
		
		
RETURN 0		

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveIniBillEffect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Gp_SaveIniBillEffect
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================
-- 描述：保存期初单据用到的存储过程，主要是
--		 影响应收应付，预收预付
--		 参考Gp_IniToArApTotal
-- 时间：2013-06-26 11:03:41.940
-- 作者：周华
-- 2013-09-04 修改 写入atype_total表有误的bug
-- 2015-06-10 修改，增加发票类单据,增加billtype参数
-- ==========================================
CREATE PROCEDURE Gp_SaveIniBillEffect
(
	@billNumberId INT,
	@billType	  INT=-1
)
--@encode$--	
AS
BEGIN
	DECLARE @stypeid VARCHAR(50)='';
	DECLARE @btypeid VARCHAR(50)='';
	DECLARE @ExpenseToAr INT=0,
			@TotalDigit  INT;
	DECLARE	@AR_ID INT,@AP_ID INT,@YS_ID INT,@YF_ID INT,@APP_ID INT,@SEND_ID INT;
	
	IF @billType=404 OR @billType=405
		SELECT @stypeid=Stypeid,@btypeid=btypeid FROM dbo.ReceiptBillIndex WHERE BillNumberID=@billNumberId
	ELSE
		SELECT @stypeid=Stypeid,@btypeid=btypeid FROM dbo.BillIndex WHERE BillNumberId=@billNumberId;
		
	IF EXISTS(SELECT 1 FROM dbo.SType_UserConfig WHERE StypeId=@stypeid AND Value='1' AND ConfigNo='1')
		RETURN ;
		
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr';
	SELECT @TotalDigit=DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName='total'
	
	CREATE TABLE #billindexARAPTotal
	(
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		APTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		YFTotal00  NUMERIC(24, 10) ,
		FCTotal00  NUMERIC(24, 10) ,
		GRIRTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10) ,
		nAPTotal00  NUMERIC(24, 10) ,
		nYSTotal00  NUMERIC(24, 10) ,
		nYFTotal00  NUMERIC(24, 10) ,
		NFCTotal00  NUMERIC(24, 10) ,
		NGRIRTotal00  NUMERIC(24, 10) 
	)

	INSERT INTO #billindexARAPTotal
	( 
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			APTotal00 ,
			YSTotal00 ,
			YFTotal00 ,
			FCTotal00,
			GRIRTotal00,
			nARTotal00 ,
			nAPTotal00 ,
			nYSTotal00 ,
			nYFTotal00,
			NFCTotal00,
			NGRIRTotal00
	)
	SELECT	stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(APTotal00),
			SUM(YSTotal00),
			SUM(YFTotal00),
			SUM(FCTotal00),
			SUM(GRIRTotal00),
			SUM(nARTotal00),
			SUM(nAPTotal00),
			SUM(nYSTotal00),
			SUM(nYFTotal00),
			SUM(NFCTotal00),
			SUM(NGRIRTotal00)
	FROM
	(
		SELECT	stypeid ,
				btypeid ,
				cid ,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					ELSE 0 
				END AS artotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)) 
					ELSE 0 
				END AS aptotal00,
				CASE WHEN billtype =189 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS ystotal00,
				CASE WHEN billtype =190 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS yftotal00,
				0 AS FCTotal00,
				0 AS  GRIRTotal00,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS nartotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0) 
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS naptotal00,
				CASE WHEN billtype =189 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nystotal00,
				CASE WHEN billtype =190 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nyftotal00,
				0 AS NFCTotal00,
				0 AS  NGRIRTotal00
		FROM dbo.BillIndex
		WHERE	BillType IN(4,66,11,12,45,46,85,93,141,148,149,160,167,168,172,181,6,34,36,84,145,150,151,161,170,189,190,213,212,312)
				AND IsIni=1 
				AND	stypeid =@stypeid
				AND BillNumberId=@billNumberId  AND BillType=@billType
		UNION ALL
		SELECT  b.stypeid ,
				a.btypeid ,
				b.cid ,
				CASE WHEN b.billtype = 116
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					ELSE 0
				END AS artotal00,
				CASE WHEN b.billtype = 128
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					 ELSE 0
				END AS aptotal00,
				0 AS ystotal00,
				0 AS yftotal00,
				0 AS FCTotal00,
				0 AS GRIRTotal00,
				CASE WHEN b.billtype = 116
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					ELSE 0
				END AS nartotal00,
				CASE WHEN b.billtype = 128
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					 ELSE 0
				END AS naptotal00,
				0 AS nystotal00,
				0 AS nyftotal00,
				0 AS NFcTotal00,
				0 AS NGRIRTotal00
		FROM	AdDebtBill a 
		INNER JOIN billindex b ON a.BillNumberId =b.BillNumberId
		WHERE	BillType IN(115,116,128,129)
				AND IsIni=1 
				AND	b.stypeid =@stypeid
				AND b.BillNumberId=@billNumberId  AND BillType=@billType
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=402
				   THEN ROUND((A.Qty-A.InvoiceQty)*A.costprice,@TotalDigit)
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYFTotal00,
			   0 AS NYSTotal00,
			   CASE WHEN B.BillType=402
					THEN ROUND((A.Qty-A.InvoiceQty)*A.costprice,@TotalDigit)
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
				
		FROM SendBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid=@stypeid AND B.BillNumberId=@billNumberId AND BillType=@billType
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=403
				   THEN ROUND(-(A.Qty-A.InvoiceQty)*A.costprice,@TotalDigit)
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   CASE WHEN B.BillType=403
					THEN ROUND(-(A.Qty-A.InvoiceQty)*A.costprice,@TotalDigit)
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
		FROM SendBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid=@stypeid AND B.BillNumberId=@billNumberId AND BillType=@billType
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.Total
					ELSE ROUND((A.Qty-A.InvoiceQty)*A.DiscountPrice,@TotalDigit)
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.NTotal
					ELSE ROUND((A.Qty-A.InvoiceQty)*A.NDiscountPrice,@TotalDigit)
					END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid=@stypeid AND B.BillNumberId=@billNumberId AND BillType=@billType
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.Total
					ELSE ROUND(-(A.Qty-A.InvoiceQty)*A.DiscountPrice,@TotalDigit)
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.NTotal
					ELSE ROUND(-(A.Qty-A.InvoiceQty)*A.NDiscountPrice,@TotalDigit)
					END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND B.Stypeid=@stypeid AND B.BillNumberId=@billNumberId AND BillType=@billType
		
		
		UNION ALL
		SELECT 
			  B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.BillType=405
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.BillType=405
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM ReceiptBillIndex B 
		WHERE B.BillNumberID=@billNumberId AND BillType=@billType AND B.IsIni=1 AND B.Stypeid=@stypeid
		
		UNION ALL
		SELECT 
		B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.totalmoney
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.ChargeOffType IN (3,4)
				   THEN B.totalmoney
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.NTotalMoney
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.ChargeOffType IN (3,4)
				   THEN B.NTotalMoney
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM dbo.BillIndex B 
		 WHERE B.BillNumberId=@billNumberId AND BillType=450 AND B.IsIni=1 AND B.Stypeid=@stypeid
		 
	) total
	GROUP BY stypeid,btypeid,cid

	DELETE FROM #billindexARAPTotal WHERE YSTotal00=0 AND YFTotal00=0 AND ARTotal00=0 AND APTotal00=0 AND nYSTotal00=0 AND nYFTotal00=0 AND nARTotal00=0 AND nAPTotal00=0 
	AND GRIRTotal00=0 AND NGRIRTotal00=0 AND FCTotal00=0 AND NFCTotal00=0


	-- 写入 BType_ArAPTotal 期初
	UPDATE a SET 
		a.ARTotal00=ISNULL(a.ARTotal00,0)+ISNULL(b.ARTotal00,0),
		a.APTotal00=ISNULL(a.APTotal00,0)+ISNULL(b.APTotal00,0),
		a.YSTotal00=ISNULL(a.YSTotal00,0)+ISNULL(b.YSTotal00,0),
		a.YFTotal00=ISNULL(a.YFTotal00,0)+ISNULL(b.YFTotal00,0),
		a.nARTotal00=ISNULL(a.nARTotal00,0)+ISNULL(b.nARTotal00,0),
		a.nAPTotal00=ISNULL(a.nAPTotal00,0)+ISNULL(b.nAPTotal00,0),
		a.nYSTotal00=ISNULL(a.nYSTotal00,0)+ISNULL(b.nYSTotal00,0),
		a.nYFTotal00=ISNULL(a.nYFTotal00,0)+ISNULL(b.nYFTotal00,0),
		a.FCTotal00=ISNULL(a.FCTotal00,0)+ISNULL(b.FCTotal00,0),
		a.NFCTotal00=ISNULL(a.NFCTotal00,0)+ISNULL(b.NFCTotal00,0),
		a.GRIRTotal00=ISNULL(a.GRIRTotal00,0)+ISNULL(b.GRIRTotal00,0),
		a.NGRIRTotal00=ISNULL(a.NGRIRTotal00,0)+ISNULL(b.NGRIRTotal00,0)
	FROM dbo.BType_ArApTotal a JOIN #billindexARAPTotal b ON a.stypeid=b.stypeid AND a.btypeid=b.btypeid AND a.CID=b.cid
	
	INSERT INTO BType_ArApTotal(
		BTypeID,
		STypeID,
		ARTotal,
		APTotal,
		YSTotal,
		YFTotal,
		ARTotal00,
		APTotal00,
		YSTotal00,
		YFTotal00,
		nARTotal,
		nAPTotal,
		nYSTotal,
		nYFTotal,
		nARTotal00,
		nAPTotal00,
		nYSTotal00,
		nYFTotal00,
		CID,
		FCTotal00,
		NFCTotal00,
		GRIRTotal00,
		NGRIRTotal00
	) SELECT 
		b.btypeId,
		b.stypeid,
		0,0,0,0,
		b.ARTotal00,b.APTotal00,b.YSTotal00,b.YFTotal00,
		0,0,0,0,
		b.nARTotal00,b.nAPTotal00,b.nYSTotal00,b.nYFTotal00,
		b.cid,
		b.FCTotal00,
		b.NFCTotal00,
		b.GRIRTotal00,
		b.NGRIRTotal00
	FROM #billindexARAPTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM BType_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid)


	DELETE  FROM BType_ArApTotal WHERE ISNULL(ARTotal,0)=0 AND ISNULL(APTotal,0)=0 AND ISNULL(YSTotal,0)=0 AND ISNULL(YFTotal,0)=0
	AND ISNULL(ARTotal00,0)=0 AND ISNULL(APTotal00,0)=0 AND ISNULL(YSTotal00,0)=0 AND ISNULL(YFTotal00,0)=0
	AND ISNULL(nARTotal,0)=0 AND ISNULL(nAPTotal,0)=0 AND ISNULL(NYSTotal,0)=0 AND ISNULL(NYFTotal,0)=0
	AND ISNULL(NARTotal00,0)=0 AND ISNULL(NAPTotal00,0)=0 AND ISNULL(NYSTotal00,0)=0 AND ISNULL(NYFTotal00,0)=0
	AND ISNULL(FCTotal,0)=0 AND ISNULL(NFCTotal,0)=0 AND ISNULL(NGRIRTotal,0)=0 AND ISNULL(GRIRTotal,0)=0
	AND ISNULL(FCTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0 AND ISNULL(NGRIRTotal00,0)=0 AND ISNULL(GRIRTotal00,0)=0
	AND STypeID = @stypeid;
	

	
	SELECT @AR_ID=nid FROM dbo.Ac_Items WHERE FullName='应收合计';		
	SELECT @AP_ID=nid FROM dbo.Ac_Items WHERE FullName='应付合计';		
	SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE FullName='预收资金';		
	SELECT @YF_ID=nid FROM dbo.Ac_Items WHERE FullName='预付资金';
	SELECT @APP_ID=NID FROM dbo.Ac_Items WHERE FullName='应付暂估';
	SELECT @SEND_ID=NID FROM dbo.Ac_Items WHERE FullName='发出商品';
	-- 写入 期初余额
	
	SELECT stypeid,cid
	,ISNULL(SUM(artotal00),0) AS artotal00,ISNULL(SUM(nartotal00),0) AS nartotal00 
	,ISNULL(SUM(aptotal00),0) AS aptotal00,ISNULL(SUM(naptotal00),0) AS naptotal00
	,ISNULL(SUM(ystotal00),0) AS ystotal00,ISNULL(SUM(nystotal00),0) AS nystotal00
	,ISNULL(SUM(yftotal00),0) AS yftotal00,ISNULL(SUM(nyftotal00),0) AS nyftotal00
	,ISNULL(SUM(GRIRTotal00),0) AS GRIRTotal00,ISNULL(SUM(NGRIRTotal00),0) AS NGRIRTotal00
	,ISNULL(SUM(FCTotal00),0) AS FCTotal00,ISNULL(SUM(NFCTotal00),0) AS NFCTotal00
	INTO #atype_total 
	FROM #billindexARAPTotal GROUP BY stypeid,cid
	
	UPDATE a SET a.total00=a.total00+b.artotal00,a.ntotal00=a.ntotal00+b.nartotal00
	FROM AType_Total a JOIN --#billindexARAPTotal b 
	#atype_total b
	ON a.STypeID=b.stypeid AND a.CID=b.cid
	WHERE a.ATypeID=@AR_ID; --应收
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @AR_ID,b.StypeId,b.artotal00,b.nartotal00,b.cid FROM --#billindexARAPTotal b 
	#atype_total b
	LEFT JOIN AType_Total a ON a.stypeid=b.stypeid AND a.CID=b.cid AND a.ATypeID=@AR_ID
	WHERE a.STypeID IS NULL AND b.artotal00<>0 ;
	
	UPDATE a SET a.total00=a.total00+b.aptotal00,a.ntotal00=a.ntotal00+b.naptotal00
	FROM AType_Total a JOIN #atype_total b ON a.STypeID=b.stypeid AND a.CID=b.cid
	WHERE a.ATypeID=@AP_ID; --应付
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @AP_ID,b.StypeId,b.aptotal00,b.naptotal00,b.cid FROM #atype_total b LEFT JOIN  AType_Total a ON a.stypeid=b.stypeid AND a.CID=b.cid AND a.ATypeID=@AP_ID
	WHERE a.ATypeID IS NULL AND b.aptotal00<>0;

	UPDATE a SET a.total00=a.total00+b.ystotal00,a.ntotal00=a.ntotal00+b.nystotal00
	FROM AType_Total a JOIN #billindexARAPTotal b ON a.STypeID=b.stypeid AND a.CID=b.cid
	WHERE a.ATypeID=@YS_ID; --预收
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @YS_ID,b.StypeId,b.ystotal00,b.nystotal00,b.cid FROM #atype_total b LEFT JOIN AType_Total a ON a.stypeid=b.stypeid AND a.CID=b.cid AND a.ATypeID=@YS_ID
	WHERE a.ATypeID IS NULL AND b.ystotal00<>0;

	UPDATE a SET a.total00=a.total00+b.yftotal00,a.ntotal00=a.ntotal00+b.nyftotal00
	FROM AType_Total a JOIN #atype_total b ON a.STypeID=b.stypeid AND a.CID=b.cid
	WHERE a.ATypeID=@YF_ID; --预付
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @YF_ID,b.StypeId,b.yftotal00,b.nyftotal00,b.cid FROM #atype_total b LEFT JOIN AType_Total a ON a.stypeid=b.stypeid AND a.CID=b.cid AND a.ATypeID=@YF_ID
	WHERE a.ATypeID IS NULL AND b.yftotal00<>0;
	
	UPDATE A SET A.Total00=A.Total00+B.GRIRTotal00,
				 A.Ntotal00=A.Ntotal00+B.NGRIRTotal00
	FROM AType_Total A JOIN #atype_total B ON A.STypeID=B.STypeID AND a.CID=b.CID
	WHERE a.ATypeID=@APP_ID; --应付暂付
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @APP_ID,b.StypeId,b.GRIRTotal00,b.NGRIRTotal00,b.CID FROM #atype_total b 
	LEFT JOIN AType_Total A ON A.STypeID=b.STypeID AND a.CID=b.CID AND A.ATypeID=@APP_ID
	WHERE a.ATypeID IS NULL AND b.GRIRTotal00<>0;
	
	UPDATE A SET A.Total00=A.Total00+B.FCTotal00,
				 A.Ntotal00=A.Ntotal00+B.NFCTotal00
	FROM AType_Total A JOIN #atype_total B ON A.STypeID=B.STypeID AND a.CID=b.CID
	WHERE a.ATypeID=@SEND_ID; --发出商品
	
	INSERT INTO AType_Total(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)SELECT @SEND_ID,B.StypeId,B.FCTotal00,B.NFCTotal00,B.CID FROM #atype_total B 
	LEFT JOIN AType_Total A ON A.STypeID=b.STypeID AND A.CID=B.CID AND A.ATypeID=@SEND_ID
	WHERE a.ATypeID IS NULL AND b.FCTotal00<>0;
	
	DELETE FROM AType_Total WHERE total00=0 AND Total=0 AND Ntotal00=0 AND Ntotal=0 AND STypeID = @stypeid;
	
	DECLARE @SQL VARCHAR(1280),
			@TableName VARCHAR(100),	--明细表名
			@IndexName VARCHAR(50),		--主表表名
			@DraftFlag BIT = 1,
			@IsiniFlag BIT = 0
			
	SELECT @DraftFlag=draft,@IsiniFlag=IsIni FROM dbo.BillIndex WHERE BillNumberId=@billNumberId AND BillType=@billtype

	-- 设置明细表表名
	SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType
	
	IF @IndexName='BillIndex'
	BEGIN
		-- 处理单据明细与主表的过账及期初字段
		SET @SQL = 'UPDATE ' + @TableName + ' SET DraftFlag=' + CAST(@DraftFlag as varchar(4)) + ',IsIniFlag=' + CAST(@IsiniFlag as varchar(4)) + '
					WHERE BillNumberId=' + CAST(@billNumberId as varchar(20)) + ' AND (DraftFlag!=' + CAST(@DraftFlag as varchar(4)) + ' OR IsIniFlag!=' + CAST(@IsiniFlag as varchar(4))+')';
		EXEC (@SQL)
	END
	DROP TABLE #billindexARAPTotal;
	DROP TABLE #atype_total;

	--------------------------------------------品牌应收 begin --------------------------------
	IF NOT EXISTS(SELECT TOP 1 1 FROM  sysdata WHERE SubName='usebrandartype' AND SubValue='1')
	RETURN ;--系统配置未启用品牌应收 则返回不计算
	--IF NOT EXISTS(SELECT 1 FROM dbo. btype WHERE typeid =@btypeid and IsUseBrandarType=1)
    --RETURN ;--如果该往来单位不启用品牌应收 则 返回不计算

	CREATE TABLE #BrandarARAPTotal
	(
		BrandarTypeID VARCHAR(50),
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10),
		nYSTotal00  NUMERIC(24, 10) ,
		Total00		NUMERIC(24, 10) ,
		NTotal00	NUMERIC(24, 10)
	)

	INSERT INTO #BrandarARAPTotal
	(		
			BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			YSTotal00 ,
			nARTotal00 ,
			nYSTotal00,
			Total00,
			NTotal00
	)
	SELECT	BrandarTypeID,
			stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(YSTotal00),
			SUM(nARTotal00),
			SUM(nYSTotal00),
			0,
			0
			
	FROM
	(	--销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=11
		UNION ALL      
		--组合品销售出库单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.PT_Combin_SaleBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=12
		UNION ALL
		--销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal00,
				0 AS YSTotal00 ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.salebackbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId 
			      AND @billType=45
		UNION ALL 
		--组合品销售退货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.taxtotal-s.CompleteTotal) AS  ARTotal00,
				0 AS YSTotal00 ,
				-(s.ntaxtotal-s.NCompleteTotal) AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.PT_Combin_SaleBackBill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=46 
		UNION ALL 
		--销售换货单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
			   CASE WHEN s.InOrOut='O' THEN s.taxtotal-s.CompleteTotal
										ELSE -( s.taxtotal-s.CompleteTotal) 
										END AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE WHEN s.InOrOut='O' THEN s.ntaxtotal-s.NCompleteTotal 
										ELSE -(s.ntaxtotal-s.NCompleteTotal )
										END AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.salegoodsexchangebill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=160 
		UNION ALL 
		--委托代销结算单
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.commissionbill s
			INNER JOIN  billindex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
				  AND  b.Stypeid=@stypeid
				  AND b.BillNumberId=@billNumberId AND @billType=141 
		UNION ALL 
		--销售发货开票
		SELECT  p.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.taxtotal-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntaxtotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.ReceiptBill s
			INNER JOIN  ReceiptBillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN ptype p ON p.typeid=s.PtypeId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=405 	
		UNION ALL 
		--期初预收款
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				0 AS  ARTotal00,
				s.total AS YSTotal00 ,
				0 AS nARTotal00 ,
				s.ntotal AS nYSTotal00 
			FROM dbo.prebill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN  btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=189 
			      AND ISNULL(B.NChargeOffTotal,0)=0 	
		UNION ALL 
		--应收增加单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				s.total-s.CompleteTotal AS  ARTotal00,
				0 AS YSTotal00 ,
				s.ntotal-s.NCompleteTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=116 				
		UNION ALL 
		--应收减少单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				s.btypeid,
				b.cid,
				-(s.total-s.CompleteTotal) AS  ARTotal00,
				0 AS YSTotal00 ,
				-(s.ntotal-s.NCompleteTotal) AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.addebtbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on s.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=115 
		UNION ALL 
		--其他收入单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				s.total AS  ARTotal00,
				0 AS YSTotal00 ,
				s.NTotal AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=93 
		UNION ALL 
		--费用单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.total
					  ELSE 0
					  END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE  WHEN btypeid like '00001%' AND @ExpenseToAr=1
					  THEN -s.NTotal
					  ELSE 0
					  END  AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM dbo.moneybill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1	
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=36	
		UNION ALL 
		--收款单
		SELECT  s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				-(s.total+s.PreferenceMoney) AS  ARTotal00,
				CASE WHEN s.AtypeId=@YS_ID THEN -s.total ELSE 0 END   AS YSTotal00 , --预收 不包含优惠
				-(s.ntotal+s.NPreferenceMoney) AS nARTotal00 ,
				CASE WHEN s.AtypeId=@YS_ID THEN -s.ntotal ELSE 0 END  AS nYSTotal00 
			FROM dbo.gatheringbill s
			INNER JOIN  BillIndex  b  ON b.BillNumberId = s.BillNumberId
			INNER JOIN btype bt on b.btypeid=bt.typeid and bt.IsUseBrandarType=1	
			WHERE b.IsIni=1
			      AND  b.Stypeid=@stypeid
			      AND b.BillNumberId=@billNumberId AND @billType=4
		UNION ALL 
		--多账户
		SELECT	s.BrandarTypeID,
				b.stypeid,
				b.btypeid,
				b.cid,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.PreferenceMoney+S.TotalInMoney+s.YSTotalInMoney )
					ELSE s.PreferenceMoney+S.TotalInMoney+s.YSTotalInMoney 
					END  AS  ARTotal00,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.YSTotalInMoney  )
					ELSE s.YSTotalInMoney 
					END AS YSTotal00 ,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.NPreferenceMoney+S.NTotalInMoney+s.NYSTotalInMoney )
					ELSE s.NPreferenceMoney+S.NTotalInMoney+s.NYSTotalInMoney 
					END  AS nARTotal00 ,
				CASE WHEN @billtype IN (11,12,160,141,93,405) 
					THEN -(s.NYSTotalInMoney  )
					ELSE s.NYSTotalInMoney 
					END AS nYSTotal00  
			FROM BillMulBrand s
			INNER JOIN BILLINDEX B ON s.billnumberid=b.billnumberid
			WHERE s.BillNumberId=@billNumberId 
				   AND s.billtype=@billType
				   AND b.Stypeid=@stypeid
				   AND b.isini=1
				   AND  s.BillType  NOT IN (305,215)
		UNION ALL 
	 	SELECT	s.BrandarTypeID,
			b.stypeid,
			b.btypeid,
			b.cid,
			0  AS  ARTotal00,
			CASE WHEN @billtype IN (305) 
				THEN -(s.YSTotalInMoney  )
				ELSE s.YSTotalInMoney 
				END AS YSTotal00 ,
			0  AS nARTotal00 ,
			CASE WHEN @billtype IN (305) 
				THEN -(s.NYSTotalInMoney  )
				ELSE s.NYSTotalInMoney 
				END AS nYSTotal00  
		FROM BillMulBrand s
		INNER JOIN BILLINDEX B ON s.billnumberid=b.billnumberid
		WHERE s.BillNumberId=@billNumberId 
			   AND s.billtype=@billType
			   AND b.Stypeid=@stypeid
			   AND b.isini=1
			   AND  s.BillType   IN (305,215)
		UNION ALL 
		--品牌结算
		SELECT	s.BrandarTypeID,
				s.stypeid,
				s.btypeid,
				s.cid,
				CASE 
					WHEN @billtype IN (11,12,160,141,93,405,45,46) THEN -s.CompleteTotal
					ELSE s.CompleteTotal 
				END  AS  ARTotal00,
				0 AS YSTotal00 ,
				CASE 
					WHEN @billtype IN (11,12,160,141,93,405,45,46) THEN -s.NCompleteTotal
					ELSE s.NCompleteTotal
				END  AS nARTotal00 ,
				0 AS nYSTotal00 
			FROM CompleteBrandarTotal s
			WHERE s.GoodsBillID=@billNumberId 
				   AND s.billtype=@billType
				   AND s.Stypeid=@stypeid
				   AND S.isDraft=0  --不是草稿的
				   AND s.isini=1		
	)total
	GROUP BY BrandarTypeID,stypeid,btypeid,cid
	
	DELETE FROM #BrandarARAPTotal WHERE YSTotal00=0  AND ARTotal00=0  AND nYSTotal00=0 AND nARTotal00=0 
	
	
	-- 写入 brandar_ArApTotal 期初
	UPDATE	a 
	SET		a.ARTotal00=ISNULL(a.ARTotal00,0)+ISNULL(b.ARTotal00,0),
			a.YSTotal00=ISNULL(a.YSTotal00,0)+ISNULL(b.YSTotal00,0),
			a.nARTotal00=ISNULL(a.nARTotal00,0)+ISNULL(b.nARTotal00,0),
			a.nYSTotal00=ISNULL(a.nYSTotal00,0)+ISNULL(b.nYSTotal00,0)		
	FROM dbo.brandar_ArApTotal a 
	JOIN #BrandarARAPTotal b ON a.stypeid=b.stypeid AND a.btypeid=b.btypeid AND a.CID=b.cid and a.BrandarTypeID=b.BrandarTypeID
	
	INSERT INTO brandar_ArApTotal
	(
		BTypeID,
		STypeID,
		BrandarTypeID,
		CID,
		ARTotal,
		YSTotal,
		ARTotal00,
		YSTotal00,
		nARTotal,
		nYSTotal,
		nARTotal00,
		nYSTotal00
	) 
	SELECT	b.btypeId,
			b.stypeid,
			B.BrandarTypeID,
			b.cid,
			0,
			0,
			b.ARTotal00,
			b.YSTotal00,
			0,
			0,
			b.nARTotal00,
			b.nYSTotal00		
	FROM #BrandarARAPTotal b 
	WHERE NOT EXISTS(SELECT 1 FROM brandar_ArApTotal a WHERE a.stypeid=b.stypeid AND a.BTypeID=b.btypeid AND a.cid=b.cid AND a.BrandarTypeID=b.BrandarTypeID)

	DELETE  
	FROM	brandar_ArApTotal 
	WHERE	ISNULL(ARTotal,0)=0 AND ISNULL(YSTotal,0)=0 
			AND ISNULL(ARTotal00,0)=0  AND ISNULL(YSTotal00,0)=0 
			AND ISNULL(nARTotal,0)=0  AND ISNULL(NYSTotal,0)=0 
			AND ISNULL(NARTotal00,0)=0 AND ISNULL(NYSTotal00,0)=0 
			AND STypeID = @stypeid;
			
	DROP TABLE #BrandarARAPTotal;
	--------------------------------------------品牌应收 end --------------------------------
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveItemsini]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SaveItemsini]
GO

-----------------功能：项目期初保存----------
-----------------作者：韩林			 ----------
-----------------日期：2012-06-07    ----------


CREATE    PROC Gp_SaveItemsini
( 
	@typeid		VARCHAR(50),	
	@stypeid	varchar(50),
	@total00	DECIMAL(22,2),
	@ntotal00	DECIMAL(22,2),
	@cid		int
)
--@encode$--
AS
SET NOCOUNT ON

--未启用外币的情况下
IF @cid IS NULL
BEGIN
	DELETE FROM dbo.AType_Total where atypeid=@typeid and stypeid=@stypeid
	SELECT @cid=cid FROM dbo.Ac_Currency WHERE Sysrow=1
END

IF @total00<>0 AND @ntotal00<>0
	INSERT INTO dbo.AType_Total
			( ATypeID ,
			  STypeID ,
			  Total00 ,
			  Total ,
			  CID ,
			  Ntotal,
			  Ntotal00
			)
	VALUES  ( @typeid,
			  @stypeid,
			  @total00,
			  0,
			  @cid,
			  0,
			  @ntotal00
			)
        
IF @@ERROR<>0
	RAISERROR('期初保存不成功',16,1)            

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveItemType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SaveItemType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.11.22
	描述：项目分类的新建、修改
*/
CREATE PROCEDURE GP_SaveItemType
(
	@stypeid			VARCHAR(50),
	@typeid				VARCHAR(50),	--结点id
	@usercode			VARCHAR(200),
	@fullname			VARCHAR(200),
	@attribute			INT,			--0,1,2 分类、统计、末级
	@comment			VARCHAR(250),
	@isModify			INT				--操作类型：0新增，1修改
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PyCode VARCHAR(200),@newTypeid VARCHAR(50),@parid VARCHAR(50),
		@nReturntype INT,@dbname VARCHAR(50),@nSonnum INT,
		@nSoncount INT,@xiwanumber INT,@level INT

SET @dbname = 'itemtype'

SET @PyCode = dbo.Fun_GetPy(@FullName)--拼音码

SELECT @xiwanumber = MAX(ISNULL(XiWaMaxNumber,0)) + 1 FROM dbo.ItemType


IF @isModify = 0
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.ItemType WHERE STypeid = @stypeid AND typeId='00000')
		INSERT INTO dbo.ItemType(typeId,ParId,leveal,sonnum,soncount,CanModify,UserCode,FullName,Name,Attribute,Comment,STypeid,deleted,PyCode,XiWaMaxNumber)
				VALUES  ('00000','',0,0,0,0,'','','',0,'',@stypeid,0,'',0)

	IF @attribute = 0 --分类级
	BEGIN
		SET @parid = '00000'
	END
	ELSE
	BEGIN
		SET @parid = @typeid
		IF EXISTS(SELECT TOP 1 1 FROM dbo.ItemType WHERE typeId = @typeid AND Attribute = 2)
		BEGIN
			RAISERROR('末级不允许新建子目录！',16,1)
			RETURN -1
		END	
	END
	
	SELECT @level = leveal + 1 FROM dbo.ItemType WHERE typeId = @parid AND STypeid = @stypeid
	
	IF LEN(@Parid)=50
	BEGIN
		RAISERROR('分类不能超过10层',16,1)
		RETURN -1
	END
	DECLARE @execsql	VARCHAR(500)
	DECLARE @szTypeId	VARCHAR(50),
			@sonnum		INT,
			@par		VARCHAR(50),
			@soncount	INT

	SELECT @execsql='
		DECLARE checkid_CURSOR CURSOR FOR 	
			SELECT 	typeid,
					sonnum,
					parid,
					soncount 
			FROM 	'+@dbname+' 
			WHERE 	typeid= '+''''+@parid+''' AND stypeid = '''+ @stypeid+''''

	EXEC (@execsql)

	OPEN checkid_CURSOR

	FETCH NEXT FROM checkid_CURSOR INTO @szTypeId, @sonnum, @par,@soncount
	 
	IF  @@FETCH_STATUS = -1
		BEGIN
			CLOSE checkid_CURSOR
			DEALLOCATE checkid_CURSOR
			RETURN -1
		END 
	ELSE
		BEGIN
			DECLARE @tempId 	VARCHAR(5),
					@nReturn 	INT
			SELECT @soncount=@soncount+1
			EXEC @nReturn=inttostr @soncount,@tempId out
			IF @nReturn=-1  
				BEGIN
					CLOSE checkid_CURSOR
					DEALLOCATE checkid_CURSOR
					RAISERROR('无法添加',16,1)
					RETURN -2
				END 
			ELSE
				BEGIN
					IF @sztypeid='00000' 
						SELECT @newTypeid=@tempId			
					ELSE 
						SELECT @newTypeid=RTRIM(@szTypeid)+@tempId
				END
		END
		
	 CLOSE checkid_CURSOR
	 DEALLOCATE checkid_CURSOR

	
	BEGIN TRAN saveItemTran--开始事务
		INSERT INTO dbo.ItemType
				( typeId ,
				  ParId ,
				  leveal ,
				  sonnum ,
				  soncount ,
				  CanModify ,
				  UserCode ,
				  FullName ,
				  Name ,
				  Attribute ,
				  Comment ,
				  STypeid ,
				  deleted ,
				  PyCode ,
				  XiWaMaxNumber
				)
		VALUES  ( @newTypeid , -- typeId - varchar(50)
				  @parid , -- ParId - varchar(50)
				  @level , -- leveal - smallint
				  0 , -- sonnum - int
				  0 , -- soncount - int
				  '' , -- CanModify - char(1)
				  @usercode , -- UserCode - varchar(200)
				  @fullname , -- FullName - varchar(200)
				  '' , -- Name - varchar(200)
				  @attribute , -- Attribute - smallint
				  @comment , -- Comment - varchar(250)
				  @stypeid , -- STypeid - varchar(50)
				  0 , -- deleted - bit
				  @PyCode , -- PyCode - varchar(500)
				  @xiwanumber  -- XiWaMaxNumber - numeric
				)
		UPDATE dbo.ItemType SET soncount = soncount + 1, sonnum = sonnum + 1 WHERE typeId = @parid AND STypeid = @stypeid
	IF @@ERROR <> 0--出错
		ROLLBACK TRAN saveItemTran
	ELSE
		COMMIT TRAN saveItemTran
END
ELSE IF @isModify = 1--修改
BEGIN
	UPDATE dbo.ItemType 
	SET UserCode = @usercode,FullName = @fullname,PyCode = @PyCode,Attribute = @attribute,XiWaMaxNumber = @xiwanumber,
		Comment = @comment
	WHERE typeId = @typeid AND STypeid = @stypeid
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE id = OBJECT_ID(N'[dbo].[GP_SaveLastSelectPtype]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_SaveLastSelectPtype]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：罗淮文	
	日期：2016-02-17
	描述：商品选择记忆
*/
CREATE PROCEDURE GP_SaveLastSelectPtype
(
	@typeid		varchar(50),
	@parid		varchar(50),
	@usercode	varchar(200),
	@fullname	varchar(200),
	@operatorid	varchar(200),
	@intBillType	int,
	@isservice		int=0
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE @RowIndex INT=1;
	IF @intBillType IN(34,204,301,400) 
	BEGIN
		IF(@isservice=0)
		BEGIN
			SELECT @RowIndex = T.RowID FROM
			(
				SELECT ROW_NUMBER()OVER(order by SortID) AS RowID, typeid,parid,usercode,fullname FROM ptype
				WHERE parid=@parid AND deleted=0 AND SonNum=0 AND isservice=0  
				AND ISNULL(stopbuy,0)=0
			) T WHERE T.typeid=@typeid
		END
		ELSE
		BEGIN
			SELECT @RowIndex = T.RowID FROM
			(
				SELECT ROW_NUMBER()OVER(order by SortID) AS RowID, typeid,parid,usercode,fullname FROM ptype
				WHERE parid=@parid AND deleted=0 AND SonNum=0 
				AND ISNULL(stopbuy,0)=0
			) T WHERE T.typeid=@typeid
		END
	END
	ELSE
	BEGIN
		IF(@isservice=0)
		BEGIN
			SELECT @RowIndex = T.RowID FROM
			(
				SELECT ROW_NUMBER()OVER(order by SortID) AS RowID, typeid,parid,usercode,fullname FROM ptype
				WHERE parid=@parid AND deleted=0 AND SonNum=0 AND isservice=0  
			) T WHERE T.typeid=@typeid
		END
		ELSE
		BEGIN
			SELECT @RowIndex = T.RowID FROM
			(
				SELECT ROW_NUMBER()OVER(order by SortID) AS RowID, typeid,parid,usercode,fullname FROM ptype
				WHERE parid=@parid AND deleted=0 AND SonNum=0 
			) T WHERE T.typeid=@typeid
		END
	END

	IF EXISTS(SELECT 1 FROM RecordLastSelectPtype WHERE OperatorID=@operatorid)
	BEGIN
		UPDATE RecordLastSelectPtype SET TypeId=@typeid,ParId=@parid,UserCode=@usercode,FullName=@fullname,
		SelectedIndex=@RowIndex  
		WHERE OperatorID=@operatorid
	END
	ELSE
	BEGIN
		INSERT INTO RecordLastSelectPtype(TypeId,ParId,UserCode,FullName,OperatorID,SelectedIndex)
		VALUES(@typeid,@parid,@usercode,@fullname,@operatorid,@RowIndex)
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveLeaveHandle]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveLeaveHandle
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-11-01
	描述：考勤补打卡保存
*/


/*
   作者：郑红霞
   日期：2012-02-09
   描述：处理没有打卡的时候的问题以及一些不正确的地方
*/

CREATE PROCEDURE Gp_SaveLeaveHandle
(
	@attendancetimeid	numeric(10, 0),		--考勤明细ID
	@etypeid			varchar(max),		--请假操作员id
	@leavereasonid		int,				--请假类型 
	@leavereason		varchar(max),		--请假原因 
	@datetime           DATETIME,           --请假日期
	@employeeid           varchar(max)        --职员id
)
--@encode$--
AS
SET NOCOUNT ON
IF @attendancetimeid<>0
BEGIN

UPDATE	attendancetime
SET		leavereasonid	=@leavereasonid,
		comment			=@leavereason
WHERE   id=@attendancetimeid
	
END
ELSE 
  INSERT INTO attendancetime (
						etypeid,
						date,
						StartTime,
						EndTime,
						LeaveReasonID,
						Comment,
						Islate
						)
  VALUES (
		@employeeid,
		@datetime,
		'00:00:00',
		'00:00:00',
		@leavereasonid,
		@leavereason,
		1
		)

IF @@ERROR<>0
	RAISERROR('考勤登记失败！',16,1)	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveManualRegist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveManualRegist
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-11-01
	描述：考勤补打卡保存
*/

/*
   作者：郑红霞
   日期：2012-02-09
   描述：处理没有打卡的时候的问题以及一些不正确的地方
*/
CREATE PROCEDURE Gp_SaveManualRegist
(
	@attendancetimeid	numeric(10, 0),		--考勤明细ID
	@etypeid			varchar(max),		--补打卡操作员id
	@registstarttime	varchar(max),		--补打卡开始时间
	@registendtime		varchar(max),		--补打卡结束时间
	@registreason		varchar(max),    	--补打卡原因 
	@datetime           DATETIME,           --请假日期
	@employeeid           varchar(max)        --职员id
)
--@encode$--
AS
SET NOCOUNT ON

SELECT 
	e.typeId,
	e.STypeID,
	w.StartTime,
	DATEADD(MINUTE,LateTime,StartTime) AS laststarttime
INTO #WorkTime
FROM dbo.employee e
INNER JOIN WorkTime w ON w.STypeID = e.STypeID
WHERE e.typeId = @employeeid

DECLARE @islate INT = 1
IF @registstarttime > (SELECT StartTime FROM #WorkTime ) AND @registstarttime<(SELECT laststarttime FROM #WorkTime)
	SET @islate = 0
	
IF @attendancetimeid =0
BEGIN
	INSERT INTO attendancetime (
					etypeid,
					date,
					StartTime,
					EndTime,
					LeaveReasonID,
					Comment,
					Islate
					)
	VALUES (
			@employeeid,
			@datetime,
			'00:00:00',
			'00:00:00',
			0,
			'',
			@islate
			)
	SET @attendancetimeid = SCOPE_IDENTITY();
END
ELSE
	UPDATE attendancetime SET Islate=@islate WHERE ID=@attendancetimeid

IF NOT EXISTS(SELECT * FROM ManualRegist WHERE AttendanceTimeid=@attendancetimeid)
	BEGIN
		INSERT INTO ManualRegist
		(
			AttendanceTimeId,
			etypeid,
			RegistStartTime,
			RegistEndTime,
			RegistReason
		)
		VALUES
		(
			@attendancetimeid,
			@etypeid,
			@registstarttime,
			@registendtime,
			@registreason
		)
	END
ELSE 
	BEGIN
		UPDATE	ManualRegist
		SET		etypeid			=@etypeid,
				RegistStartTime	=@registstarttime,
				RegistEndTime	=@registendtime,
				registreason	=@registreason
		WHERE   AttendanceTimeId=@attendancetimeid
	END

IF @@ERROR<>0
	RAISERROR('考勤登记失败！',16,1)	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveNewAcPeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_SaveNewAcPeriod
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:韩林
	日期：2012-7-31
	描述：年结时保存会计期初
*/
CREATE PROCEDURE GP_SaveNewAcPeriod
(
  @Fyear            VARCHAR(10),  --启用年度
  @Fmonth           VARCHAR(10),  --启用月度
  @Isnature         INT,          --是否自然年度
  @Naturecount      INT,          --NATURECOUNT	期间数
  @Fperiod          INT,          --会计期间 1~13
  @Fbegin           DATETIME,     --开始日期
  @Fend             DATETIME,     --截至日期
  @Deleted          INT,          --是否停用
  @iffirst          INT,          --是否第一条数据插入
  @isdynamic		INT			  --是否动态	
)
--@encode$--
AS
SET NOCOUNT ON
 
IF @iffirst=1 AND @Fbegin<(SELECT FBegin FROM dbo.Ac_Period WHERE FPeriod=(SELECT SubValue FROM dbo.sysdata WHERE SubName='Fperiod'))
BEGIN
	RAISERROR('新年度期间开始日期必须大于本年度最后一期的结束时间',16,1)
END

IF EXISTS(SELECT * FROM Ac_Period) AND @iffirst=1
	DELETE Ac_Period
  
  
 INSERT INTO Ac_Period
 (
	Fyear,
	Fmonth,
	Isnature,
	Naturecount,
	Fperiod,
	Fbegin,
	Fend,
	Deleted,
	isdynamic
 )VALUES(
	@Fyear,
	@Fmonth,
	@Isnature,
	@Naturecount,
	@Fperiod,
	@Fbegin,
	@Fend,
	@Deleted,
	@isdynamic
 )
 
 --IF @@ERROR<>0
 --	RAISERROR('会计期间保存失败！',16,1)	
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_SaveNotePad]    Script Date: 03/16/2011 14:48:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveNotePad]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SaveNotePad]
GO

-- =============================================
-- Author:		王刚
-- Create date: 07/21/2011 
-- Description:	添加记事
-- =============================================

CREATE PROCEDURE [dbo].[Gp_SaveNotePad]
(
	@createtime DATETIME,			--创建日期
	--@alerttime  DATETIME,			--提醒时期
	@userid		VARCHAR(MAX),		--创建者
	@content    VARCHAR(MAX),		--内容
	@optype	    VARCHAR(MAX),		--添加和修改
	@flag	    INT,				--记事状态
	@id			INT					--唯一标示符
	--@scantimes	INT					--从提醒框打开的记事次数
)
--@encode$--
AS
SET NOCOUNT ON

IF @opType = 'a'         
	BEGIN
		INSERT INTO NotePad
		(
			CreateTime,
			--AlertTime,
			UserId,
			Content,
			Flag,
			Importance,
			scantimes	
		)
		VALUES
		(	
			@createtime,
			--@alerttime,
			@userid,
			@content,
			@flag,
			1,
			0
		)
		
		IF @@ROWCOUNT = 0
			RETURN -2
	END
	
ELSE IF @opType = 'm'
	BEGIN
		UPDATE	NotePad
		SET		--AlertTime		= @alerttime,
				Content			= @content,
				Flag			= @Flag,
				ScanTimes		= 0
		WHERE	ID		=@id
		
		IF	@@ROWCOUNT = 0
			RETURN	-2			
	END
	
ELSE IF @opType = 'n'
	BEGIN
		UPDATE	NotePad
		SET		Content			= @content,
				Flag			= @Flag
		WHERE	ID		=@id
		
		IF	@@ROWCOUNT = 0
			RETURN	-2			
	END

RETURN 0

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SaveOperatorConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SaveOperatorConfig]
GO












/****** Object:  Stored Procedure dbo.GP_SaveOperatorConfig    Script Date: 2004-7-19 16:29:43 ******/
CREATE      PROCEDURE GP_SaveOperatorConfig(
	@ETypeID varchar(50),
	@PriceValue varchar(50),
	@UnitsIdValue INT,
	@ifAssociate varchar(50)
)
--@encode$--
AS

IF Exists ( Select * From OperatorConfig Where [ETypeID] = @ETypeID )
	Update OperatorConfig Set [price] =@PriceValue,unitsid = @UnitsIdValue,[associate]=@ifAssociate Where [ETypeID] = @ETypeID 
ELSE
	Insert Into OperatorConfig ([ETypeID],[price],unitsid,[associate]) values(@ETypeID,@PriceValue,@UnitsIdValue,@ifAssociate)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO
	--支付信息保存  --time
IF EXISTS ( SELECT  1
            FROM    SysObjects
            WHERE   ID = OBJECT_ID(N'GP_SavePayConfigInfo', N'P') )
    BEGIN
        DROP PROC GP_SavePayConfigInfo
    END
GO
CREATE PROC GP_SavePayConfigInfo
(
	@ID				INT=0,
	@PID			VARCHAR(100),
	@APPID			VARCHAR(100),
	@KeyWord		VARCHAR(MAX),
	@PayType        INT,
	@KeyWordPublic  VARCHAR(MAX),
	@UserCode       VARCHAR(200),
	@FullName		VARCHAR(200),
	@stypeidlist	VARCHAR(8000),
	@BankCardID		INT=NULL,
	@Comment		VARCHAR(250),
	@IsDefault		BIT=0,
	@posidlist		VARCHAR(8000),
	@alipaysigntype	VARCHAR(10) = '-1'		--支付宝密匙长度  1.1024  2.2048
)
AS
BEGIN
	IF LEN(@posidlist)>0
	BEGIN
		CREATE TABLE #PosIdList
		(
			PayConfigID		INT,
			PosID			INT
		)
	END
	
	IF LEN(@stypeidlist)>0
	BEGIN
		CREATE TABLE #StypeIdList
		(
			PayConfigID		INT,
			StypeID			VARCHAR(50)
		)
	END


	IF EXISTS(SELECT 1 FROM PayConfigInfo WHERE ID=@ID)
	BEGIN
		UPDATE	PayConfigInfo 
		SET		PID=@PID,
				APPID=@APPID,
				KeyWord=@KeyWord,
				KeyWordPublic=@KeyWordPublic,
				UserCode=@UserCode,
				FullName=@FullName,
				BankCardID=@BankCardID,
				Comment=@Comment,
				IsDefault=@IsDefault,
				alipaysigntype = @alipaysigntype
		WHERE	ID=@ID
		
		IF @@ERROR=0 
		BEGIN
			IF LEN(@posidlist)>0
			BEGIN	
				INSERT INTO #PosIdList(PayConfigID,PosID) SELECT @ID,A FROM DBO.f_splitAN(@posidlist,',') ORDER BY ID ASC	
								
				DELETE FROM POSPayConfigInfo WHERE PayConfigID=@ID
				
				INSERT INTO POSPayConfigInfo(PayConfigID,PosID) SELECT * FROM #PosIdList
			END
			ELSE IF LEN(@posidlist)=0
			BEGIN
				DELETE FROM POSPayConfigInfo WHERE PayConfigID=@ID
			END
			
			IF LEN(@stypeidlist)>0
			BEGIN
				INSERT INTO #StypeIdList(PayConfigID,StypeID) SELECT @ID,A FROM DBO.f_splitAN(@stypeidlist,',') ORDER BY ID ASC	
				
				DELETE FROM StypePayConfigInfo WHERE PayConfigID=@ID
				
				INSERT INTO StypePayConfigInfo(PayConfigID,StypeID) SELECT * FROM #StypeIdList
			END
			ELSE IF LEN(@stypeidlist)=0
			BEGIN
				DELETE FROM StypePayConfigInfo WHERE PayConfigID=@ID
			END
		END
	END
	
	ELSE 
	BEGIN
		INSERT INTO PayConfigInfo
		(
			PID,
			APPID,
			KeyWord,
			PayType,
			keywordpublic,
			UserCode,
			FullName,
			BankCardID,
			Comment,
			IsDefault,
			alipaysigntype
		) 
		SELECT @PID,@APPID,@KeyWord,@PayType,@KeyWordPublic,@UserCode,@FullName,@BankCardID,@Comment,@IsDefault,@alipaysigntype
		
		SELECT @ID=@@IDENTITY
		
		IF @@ERROR=0 AND LEN(@posidlist)>0
		BEGIN
			INSERT INTO #PosIdList(PayConfigID,PosID) SELECT @ID,A FROM DBO.f_splitAN(@posidlist,',') ORDER BY ID ASC			
			INSERT INTO POSPayConfigInfo(PayConfigID,PosID) SELECT * FROM #PosIdList
		END		
		
		IF @@ERROR=0 AND LEN(@stypeidlist)>0
		BEGIN	
			INSERT INTO #StypeIdList(PayConfigID,StypeID) SELECT @ID,A FROM DBO.f_splitAN(@stypeidlist,',') ORDER BY ID ASC		
			INSERT INTO StypePayConfigInfo(PayConfigID,StypeID) SELECT * FROM #StypeIdList
		END	
	END		
	
	IF LEN(@posidlist)>0
	BEGIN
		DROP TABLE #PosIdList
	END
	
	IF LEN(@stypeidlist)>0
	BEGIN
		DROP TABLE #StypeIdList
	END
		
	--修改支付配置表
	--IF @alipaysigntype <> '-1'
	--BEGIN
	--	UPDATE dbo.sysdata SET SubValue = @alipaysigntype WHERE SubName = 'alipaysigntype'	
	--END
END
GO



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SavePhysicalInventoryConfig]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_SavePhysicalInventoryConfig]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	实物库存出入库汇总表 表格配置
-- 时间：	2017-06-29
-- 作者：	glj
-- ========================================================================
CREATE PROCEDURE Gp_SavePhysicalInventoryConfig
(
	@OperatorId			VARCHAR(50),--当前操作员
	@InBillTypes		VARCHAR(500),--入库
	@OutBillTypes		VARCHAR(500)--出库
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Error INT=0
IF NOT EXISTS(SELECT TOP 1 * FROM PhysicalInventoryConfig WHERE ETypeId = @OperatorId)
	BEGIN
		INSERT INTO PhysicalInventoryConfig
		(
			ETypeId,
			InBillTypes,
			OutBillTypes
		)
		VALUES
		(
			@OperatorId,
			@InBillTypes,
			@OutBillTypes
		)
		SET @Error+=@@ERROR
	END
ELSE
	BEGIN
		UPDATE PhysicalInventoryConfig 
		SET 
			InBillTypes=@InBillTypes,
			OutBillTypes=@OutBillTypes 
		WHERE ETypeId=@OperatorId
		SET @Error+=@@ERROR
	END

RETURN @Error

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GP_SavePosAllotApplyBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_SavePosAllotApplyBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
CREATE PROC GP_SavePosAllotApplyBill
(
	@details TBType_PosAllotApplyBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

	DELETE A FROM dbo.PosAllotApplyBill A,@Details B WHERE A.BillNumberId=B.BillNumberId AND 
		   NOT EXISTS(SELECT ID FROM @Details B WHERE A.ID=B.ID
												 AND A.BillNumberiD=B.BillNumberiD
												 AND B.ID<>0)
												 
	INSERT INTO [dbo].[PosAllotApplyBill]
	([BillNumberId],[ptypeid],[qty],[BaseUnitid],[KtypeId],[InKtypeId],[ItemId],[IsCombined],[comment],MUnitId,MQty,MUnitRate)
	SELECT BillNumberId,ptypeid,qty,BaseUnitid,KtypeId,InKtypeId,ItemId,IsCombined,comment ,MUnitId,MQty,MUnitRate
	FROM @details

	UPDATE A
	   SET [ptypeid] = B.ptypeid
		  ,[qty] = B.qty
		  ,[BaseUnitid] = B.BaseUnitid
		  ,[KtypeId] = B.KtypeId
		  ,[InKtypeId] = B.InKtypeId
		  ,[ItemId] = B.ItemId
		  ,[IsCombined] = B.IsCombined
		  ,[comment] = B.comment
		  ,MUnitId = B.MUnitId
		  ,MQty = B.MQty
		  ,MUnitRate = B.MUnitRate
	 FROM dbo.PosAllotApplyBill A,@details B 
	 WHERE A.ID=B.ID AND A.BillNumberiD=B.BillNumberiD
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GP_SavePosAllotApplyBillIndex]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_SavePosAllotApplyBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
CREATE PROC GP_SavePosAllotApplyBillIndex
(
	@BillNumberId		INT,
	@BillType			INT,
	@BillCode			VARCHAR(200),
    @BillDate			DATETIME,
    @ApplyEtypeId		VARCHAR(200),
    @StypeId			VARCHAR(50),
    @DtypeId			VARCHAR(50),
    @KtypeId			VARCHAR(50),
    @InKtypeId			VARCHAR(50),
    @Qty				NUMERIC(24,10),
    @Comment			VARCHAR(256),
    @Explain			VARCHAR(256),
    @checkE				VARCHAR(200),
    @OperSate			INT,			--0,保存;1,审核;2,接受;3,拒绝;4,作废;5,已生单;6,已执行
    @Cid				int,
    @IsAutoGenerate     INT = 0,
    @total				DECIMAL(24,10)=0,	--金额
    @OperatorId			varchar(50)=''   --操作员
)
--@encode$--
AS 
SET NOCOUNT ON
-- ********	判断是否试用版 - Start	********
    DECLARE @N INT ,
			@intVersion INT

	-- 判断版本号，是否试用版
    SELECT @N = CAST(SubValue AS INT) FROM SysData1 WHERE SubNo = 2	-- 版本号
	IF @N IS NULL RETURN -1
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 6 AND SubValue = '1')
		AND (EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 10 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 9 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 11 AND ISNULL(SubValue,'') = '')
			 OR  EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubNo = 13 AND ISNULL(SubValue,'') = ''))		 
	RETURN -3	

    DECLARE @intBit INT,@intMask INT
    SELECT  @intBit = @N & 15
    SELECT  @intMask = POWER(2, @intBit) ^ POWER(2, @intBit + 1) ^ POWER(2,
                                                              @intBit + 2)
            ^ POWER(2, @intBit + 3) ^ POWER(2, @intBit + 4) ^ POWER(2,
                                                              @intBit + 5)
    SELECT  @intVersion = ( @intMask & @N ) / POWER(2, @intBit)
-- ********	判断是否试用版 - END	********
	DECLARE @Re INT ,@Flag INT
    EXEC @Re= Gp_Validate 2, @Flag OUTPUT
    IF @Re <> 0 
        RETURN -3 --检查程序版本错误

    IF @intVersion NOT IN ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ) 
        BEGIN
			--RAISERROR('校验错误 ！',16,1) 
            RETURN -3 --检查程序版本错误
        END 
        
    IF @Cid IS NULL OR @Cid = 0
		SELECT @Cid = CID FROM Ac_Currency WHERE Sysrow = 1
        
	DECLARE @intReturn INT
	SET @intReturn = 0
	IF @BillNumberId=-1
	BEGIN
		INSERT INTO [dbo].[PosAllotApplyBillIndex]
				   ([BillType],[BillCode],[BillDate],[ApplyEtypeId],[StypeId]
				   ,[DtypeId],[KtypeId],[InKtypeId],[Qty],[Comment],[Explain]
				   ,[BillState],[checkE],[IsAutoGenerate],[checkTime],CID,[Total])
			 VALUES
				   (@BillType,@BillCode,@BillDate,@ApplyEtypeId,@StypeId
				   ,@DtypeId,@KtypeId,@InKtypeId,@Qty,@Comment,@Explain
				   ,@OperSate,@checkE,@IsAutoGenerate,GETDATE(),@Cid,@total)
		IF @@rowcount = 0 OR @@error <> 0
			RETURN -5
		SELECT  @intReturn = SCOPE_IDENTITY();
	END
	ELSE
	BEGIN
		IF @OperSate=4
		BEGIN
			UPDATE [dbo].[PosAllotApplyBillIndex]
			   SET [BillType] =@BillType
				  ,[BillCode] =@BillCode
				  ,[BillDate] =@BillDate
				  ,[ApplyEtypeId] =@ApplyEtypeId
				  ,[StypeId] =@StypeId
				  ,[DtypeId] =@DtypeId
				  ,[KtypeId] =@KtypeId
				  ,[InKtypeId] =@InKtypeId
				  ,[Qty] =@Qty
				  ,[Comment] =@Comment
				  ,[Explain] =@Explain
				  --,[checkE] =@checkE
				  ,[BillState]=@OperSate
				  ,[IsAutoGenerate]=@IsAutoGenerate
				  ,[CID]=@Cid
				  ,[Total]=@total
				  ,Updater = @OperatorId
				  ,UpdaterTime = GETDATE()
			WHERE BillNumberId=@BillNumberId AND billstate in (0,3,4)
			SET @intReturn =@BillNumberId
			IF @@rowcount = 0 OR @@error <> 0
				RETURN -6
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM PosAllotApplyBillIndex WHERE BillNumberId = @BillNumberId AND BillState IN (0,3,4))
			BEGIN		
				UPDATE [dbo].[PosAllotApplyBillIndex]
				   SET [BillType] =@BillType
					  ,[BillCode] =@BillCode
					  ,[BillDate] =@BillDate
					  ,[ApplyEtypeId] =@ApplyEtypeId
					  ,[StypeId] =@StypeId
					  ,[DtypeId] =@DtypeId
					  ,[KtypeId] =@KtypeId
					  ,[InKtypeId] =@InKtypeId
					  ,[Qty] =@Qty
					  ,[Comment] =@Comment
					  ,[Explain] =@Explain
					  --,[checkE] =@checkE
					  ,[BillState]=@OperSate
					  ,[IsAutoGenerate]=@IsAutoGenerate
					  ,[CID]=@Cid
					  ,[Total]=@total
					  ,Updater = @OperatorId
					  ,UpdaterTime = GETDATE()
				WHERE BillNumberId=@BillNumberId AND BillState IN (0,3,4)
				SET @intReturn =@BillNumberId
				IF @@rowcount = 0 OR @@error <> 0
					RETURN -5
			END
			ELSE
				RETURN -7
		END
	END
	
	--单据编号重复的检测	
	IF EXISTS(SELECT TOP 1 1 FROM PosAllotApplyBillIndex WHERE BillNumberId <> @intReturn AND BillCode = @BillCode)
		AND EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'BillCodeAllowRepeat' AND Value = '0')
	BEGIN
		RETURN -9
	END
	DECLARE @BeginDate DATETIME ,
        @szItem VARCHAR(30) ,
        @szVchCode VARCHAR(30)
	 SELECT TOP 1
            @BeginDate = startdate
    FROM    monthproc
    WHERE   MonthNo='本期' AND STypeID=@STypeID
    
	   IF @BillType  =326 and  @BillDate < @BeginDate --AND @intNeed=0    
                BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
                    RETURN -2
                END
	RETURN @intReturn
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SavePosBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SavePosBillDT
GO

/*
作者：韩林
描述：写入POS小票明细表(表值)
*/
CREATE  PROCEDURE Gp_SavePosBillDT
(
	@details TBType_PosSale READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

CREATE TABLE #temp(id INT IDENTITY(1,1),detalid INT)

INSERT INTO dbo.PosSaleBill
(
		BillnumberID ,
		PID ,
		Qty ,
		BackQty ,
		RetailPrice ,
		Tax ,
		DisCount ,
		Price ,
		RetailTotal ,
		Total ,
		UnitID ,
		UnitRate ,
		ItemID ,
		IsCombined ,
		BarCode,
		IsGift,
		Comment,
		BaseUnitID,
		PromoType,
		SaleEid ,
		validdate,
		producedate,
		goodsnumber,
		serial,
		goodscostprice,
		[guid],
		couponcode,
		pricesource,
		PromoIDs
)
OUTPUT INSERTED.ID INTO #temp
SELECT 	a.BillnumberID ,
		a.PID ,
		a.Qty ,
		a.BackQty ,
		a.RetailPrice ,
		a.Tax ,
		a.DisCount ,
		a.Price ,
		a.RetailTotal,
		a.Total ,
		a.UnitID ,
		a.UnitRate,
		a.ItemID,
		a.IsCombined,
		a.BarCode,
		a.IsGift,
		a.Comment,
		a.BaseUnitID,
		a.PromoType,
		a.SaleEid ,
		a.validdate,
		a.producedate,
		a.goodsnumber,
		a.serial,
		a.goodscostprice,
		a.[guid],
		a.couponcode,
		a.pricesource,
		a.PromoIDs
FROM @details a
--where not exists (select 1 from dbo.PosSaleBill b where a.[guid]=b.[guid])
ORDER BY ID
		
if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)
 



INSERT INTO dbo.PosSaleBillAll
(			
		BillnumberID ,
		ID ,
		PID ,
		Qty ,
		BackQty ,
		RetailPrice ,
		Tax ,
		DisCount ,
		Price ,
		RetailTotal ,
		Total ,
		UnitID ,
		UnitRate ,
		ItemID ,
		IsCombined ,
		BarCode,
		IsGift,
		Comment,
		BaseUnitID,
		PromoType,
		SaleEid,
		validdate,
		producedate,
		goodsnumber,
		serial,
		goodscostprice,
		[guid],
		couponcode,
		pricesource,
		PromoIDs
)
SELECT 	BillnumberID ,
		a.detalid ,
		PID ,
		Qty ,
		BackQty ,
		RetailPrice ,
		Tax ,
		DisCount ,
		Price ,
		RetailTotal ,
		Total ,
		UnitID ,
		UnitRate ,
		ItemID ,
		IsCombined ,
		BarCode,
		IsGift,
		Comment,
		BaseUnitID,
		PromoType,
		SaleEid,
		validdate,
		producedate,
		goodsnumber,
		serial,
		goodscostprice,
		[guid],
		couponcode,
		pricesource,
		PromoIDs
FROM #temp a INNER JOIN
(
		SELECT    RANK() OVER(ORDER BY ID)id,
				  BillnumberID ,
				  PID ,
				  Qty ,
				  BackQty ,
				  RetailPrice ,
				  Tax ,
				  DisCount ,
				  Price ,
				  RetailTotal ,
				  Total ,
				  UnitID ,
				  UnitRate ,
				  ItemID ,
				  IsCombined ,
				  BarCode,
				  IsGift,
				  Comment,
				  BaseUnitID,
				  PromoType,
				  SaleEid,
				  validdate,
				  producedate,
				  goodsnumber,
				  serial,
				  goodscostprice,
				  [guid],
				  couponcode,
				  pricesource,
				  PromoIDs
		FROM @details
)b ON a.id=b.id





if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)
 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SavePosBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SavePosBillIndex
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2013-1-15
	描述：保存pos小票主表
-------------------------------------------*/
CREATE PROCEDURE [dbo].Gp_SavePosBillIndex
(
	@billdate VARCHAR(20),
	@billtype INT,
	@billcode VARCHAR(50),
	@SID INT,
	@BID INT,
	@KID INT,
	@EID INT,
	@POSID INT,
	@VipCardID INT,
	@TotalQty  NUMERIC(24, 10) ,
	@DisCount  NUMERIC(24, 10) ,
	@TotalMoney  NUMERIC(24, 10) ,
	@PreferenceMoney  NUMERIC(24, 10) ,
	@premoney  NUMERIC(24, 10) ,
	@TotalInMoney  NUMERIC(24, 10) ,
	@CashMoney  NUMERIC(24, 10) ,
	@ChangeMoney  NUMERIC(24, 10) ,
	@BackBillnumberID INT,
	@UpLoadBillnumberID INT,
	@PromoRuleId INT,
	@PromoIDs VARCHAR(200),
	@PromotionMsg VARCHAR(200),
	@BuyBackType INT,
	@billtime VARCHAR(20),
	@SaveInCzMoney NUMERIC(24,10)=0,
	@guid VARCHAR(50) = '',
	@BillDescription VARCHAR(2000) = '',
	@CouponCode VARCHAR(2000)
)
--@encode$--
AS 
SET NOCOUNT ON

IF @guid = '' OR @guid is null 
BEGIN
	IF EXISTS(select 1 from possalebillindexall with(nolock) 
			where billcode=@billcode
				and UpLoadBillnumberID=@UpLoadBillnumberID 
				and posid=@POSID)
		RETURN -1;
END
ELSE
BEGIN
	--改为Guid验证方式保证数据能上传
	IF EXISTS(select 1 from possalebillindexall with(nolock) 
			where [guid]=@guid
				and posid=@POSID)
		RETURN -1;
END

--强加单据编号判断
--IF EXISTS(select 1 from possalebillindexall with(nolock) where billcode=@billcode and posid=@POSID)
--	RETURN -1

--反号问题
--IF (ABS(@TotalInMoney)+ABS(@ChangeMoney)-ABS(@CashMoney)<0)
--SET @premoney=-1*ABS(@premoney)
--ELSE
--SET @premoney=ABS(@premoney)

INSERT INTO dbo.PosSaleBillIndex
( 
	billdate ,
	Billtype,
	BillCode ,
	SID ,
	BID ,
	KID ,
	EID ,
	PosID ,
	VipCardID ,
	TotalQty ,
	Discount ,
	TotalMoney ,
	preferencemoney ,
	premoney,
	Totalinmoney ,
	CashMoney ,
	ChangeMoney ,
	SaveInCzMoney,
	BackBillnumberID ,
	UpLoadBillnumberID,
	PromoRuleId,
	PromoIDs,
	PromotionMsg,
	BuyBackType,
	billtime,
	[guid],
	BillDescription,
	CouponCode
)
VALUES  
( 
	@billdate,
	@billtype,
	@billcode,
	@SID ,
	@BID ,
	@KID ,
	@EID ,
	@POSID ,
	@VipCardID ,
	@TotalQty ,
	@DisCount ,
	@TotalMoney,
	@PreferenceMoney,
	@premoney,
	@TotalInMoney ,
	@CashMoney ,
	@ChangeMoney ,
	@SaveInCzMoney,
	@BackBillnumberID ,
	@UpLoadBillnumberID,
	@PromoRuleId,
	@PromoIDs,
	@PromotionMsg,
	@BuyBackType,
	@billtime,
	@guid,
	@BillDescription,
	@CouponCode
)
DECLARE @billnumberid INT=SCOPE_IDENTITY();

INSERT INTO dbo.PosSaleBillIndexAll
( 
	BillnumberID,
	Billtype ,
	billdate ,
	BillCode ,
	SID ,
	BID ,
	KID ,
	EID ,
	PosID ,
	VipCardID ,
	TotalQty ,
	Discount ,
	TotalMoney ,
	preferencemoney ,
	premoney,
	Totalinmoney ,
	CashMoney ,
	ChangeMoney ,
	SaveInCzMoney,
	BackBillnumberID ,
	UpLoadBillnumberID,
	PromoRuleId,
	PromoIDs,
	PromotionMsg,
	BuyBackType,
	billtime,
	[guid],
	BillDescription,
	CouponCode
)
VALUES  
( 
	@billnumberid,
	@billtype,
	@billdate,
	@billcode,
	@SID ,
	@BID ,
	@KID ,
	@EID ,
	@POSID ,
	@VipCardID ,
	@TotalQty ,
	@DisCount ,
	@TotalMoney,
	@PreferenceMoney,
	@premoney,
	@TotalInMoney ,
	@CashMoney ,
	@ChangeMoney ,
	@SaveInCzMoney,
	@BackBillnumberID ,
	@UpLoadBillnumberID,
	@PromoRuleId,
	@PromoIDs,
	@PromotionMsg,
	@BuyBackType,
	@billtime,
	@guid,
	@BillDescription,
	@CouponCode
)
RETURN @billnumberid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GP_SavePosDeliveryApplyBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_SavePosDeliveryApplyBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
CREATE PROC GP_SavePosDeliveryApplyBill
(
	@details TBType_PosAllotApplyBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

	declare @billnumberid bigint
	
	select top 1 @billnumberid =  billnumberid from @details
	
	DELETE A FROM dbo.DeliveryApplyBill A WHERE A.BillNumberId=@billnumberid 
												 
	INSERT INTO [dbo].[DeliveryApplyBill]
	([BillNumberId],[ptypeid],Price,[qty],Total,[Unitid],MUnitID,MUnitRate,MPrice,MQty,[ItemId],[IsCombined],[comment],ShowOrder)
	SELECT BillNumberId,b.ptypeid,0,b.qty*ISNULL(puem.rate,1),0,pue.UnitsId,BaseUnitid,puem.Rate,0,qty,ItemId,IsCombined,comment,b.ID 
	FROM @details b
	left join PType_Units_Ext pue on pue.PtypeID = b.ptypeid and pue.IsDefaultUnit = 1
	left join PType_Units_Ext puem on puem.PtypeID = b.ptypeid and puem.UnitsId = b.BaseUnitid
	
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






GO
--零售月结时间设置
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_SavePosMonthEndConfig',N'P'))
BEGIN
	DROP PROC GP_SavePosMonthEndConfig
END
GO

CREATE PROC GP_SavePosMonthEndConfig
(
	@PosID INT,
	@Year INT,
	@Month INT,
	@EndDate DATETIME,
	@EndTime DATETIME
)
AS
BEGIN
	INSERT INTO PosMonthEndConfig(PosID,Year,Month,EndDate,EndTime) SELECT @PosID,@Year,@Month,@EndDate,@EndTime
END
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SavePriceAdjustment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SavePriceAdjustment]
GO

CREATE PROCEDURE Gp_SavePriceAdjustment
(
	@PriceBillIndexID numeric(18), 
	@State int,   
	@Ptypeid varchar(50),
	@FreeID int, 
	@IsCombined tinyint,
	@UnitId int,
	@PriceStyle int,
	@Price  NUMERIC(24, 10) ,
	@Discount  NUMERIC(24, 10) ,
	@DiscountPrice  NUMERIC(24, 10) ,
	@BeforeRetailPrice  NUMERIC(24, 10) ,
	@Tax  NUMERIC(24, 10) ,
	@TaxPrice  NUMERIC(24, 10) ,
	@IsPriceControl tinyint,
	@Comment varchar(256),
	@Checke varchar(50),
	@Checker varchar(50),
	@VaildDate datetime,
	@CreateDate datetime,
	@DeletedDate datetime,
	@DeletedR varchar(50),
	@OldID  numeric(18,0)
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE PriceBillIndex SET State=1 WHERE ID=@PriceBillIndexID --修改主表状态为部分审核

INSERT INTO PriceDetail(
	PriceBillIndexID,    -- 价格主表ID 
	State,    -- --0=新增 1=待审核  2=已审核 3=作废 
	Ptypeid,
	FreeID,    -- 自由项 
	IsCombined,    -- 是否为组合自由项 1=组合  0=非组合 
	UnitId,    -- 报价计量单位 
	PriceStyle,    -- 报价方式 0=单价(默认) 1=折后单价 2=含税单价 
	Price,    -- 单价 
	Discount,    -- 扣率 
	DiscountPrice,    -- 折后单价 
	BeforeRetailPrice,    -- 含税折前单价 
	Tax,    -- 税率 
	TaxPrice,    -- 含税折后单价 
	IsPriceControl,    -- 限价控制  1=勾选(默认) 0=未勾选 
	Comment,    -- 备注 
	Checke,    -- 填制人 
	Checker,
	VaildDate,    -- 审核时间 
	CreateDate,    -- 填制日期 
	DeletedDate,    -- 作废时期 
	DeletedR,    -- 作废人 
	OldID
)
VALUES(
	@PriceBillIndexID, 
	@State,   
	@Ptypeid,
	@FreeID, 
	@IsCombined,
	@UnitId,
	@PriceStyle,
	@Price,
	@Discount,
	@DiscountPrice,
	@BeforeRetailPrice,
	@Tax,
	@TaxPrice,
	@IsPriceControl,
	@Comment,
	@Checke,
	@Checker,
	@VaildDate,
	@CreateDate,
	@DeletedDate,
	@DeletedR,
	@OldID
)



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SavePtypeUnit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SavePtypeUnit]
GO




/*
	保存或者修改计量单位
*/
CREATE PROCEDURE Gp_SavePtypeUnit
(
	@Unitsid			INT,
	@UserCode			VARCHAR(200),
	@FullName			VARCHAR(200),
	@Comment			VARCHAR(500),
	@optype				VARCHAR(10)
)
--@encode$--
AS
SET NOCOUNT ON

IF @optype = 'm' ---修改
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Ptype_Units WHERE FullName = @FullName AND UnitsId <> @Unitsid)
	BEGIN
		RAISERROR('名称已存在，请修改后再保存。',16,1) 
		RETURN
	END
	ELSE IF EXISTS(SELECT TOP 1 1 FROM Ptype_Units WHERE UserCode = @usercode AND UnitsId <> @Unitsid)
	BEGIN
		RAISERROR('编号已存在，请修改后再保存。',16,1) 
		RETURN
	END
	ELSE
		BEGIN
			UPDATE	Ptype_Units
			SET		FullName = @FullName,
					Comment = @Comment,
					UserCode=@UserCode
			WHERE	Unitsid = @Unitsid
		END
	
	IF EXISTS (SELECT 1 FROM PType WHERE AssistantUnitId=@Unitsid OR SaleUnitId=@Unitsid OR BuyUnitId=@Unitsid OR ProduceUnitId=@Unitsid OR JobUnitId=@Unitsid OR baseUnitId=@Unitsid)
	BEGIN
		CREATE TABLE #tempP (typeid VARCHAR(50),[XiWaMaxNumber] [numeric](18, 0))
		INSERT INTO #tempP (typeid,XiWaMaxNumber)
		SELECT typeId,XiWaMaxNumber FROM PTYPE
		WHERE AssistantUnitId=@Unitsid 
		OR SaleUnitId=@Unitsid 
		OR BuyUnitId=@Unitsid 
		OR ProduceUnitId=@Unitsid 
		OR JobUnitId=@Unitsid 
		OR baseUnitId=@Unitsid
		ORDER BY typeId DESC
		
		INSERT INTO #tempP (typeid,XiWaMaxNumber)
		SELECT PtypeID,P.XiWaMaxNumber
		FROM PType_AuxiliaryUnits_Ext PE
		INNER JOIN PTYPE P ON PE.PtypeID=P.typeId AND PE.PtypeID NOT IN (SELECT typeId FROM #tempP)
		WHERE PE.SaleUnitID1=@Unitsid
		OR PE.SaleUnitID2=@Unitsid
		OR PE.SaleUnitID3=@Unitsid
		
		DECLARE @RCOUNT INT
		DECLARE @NOWTYPEID VARCHAR(50)
		DECLARE @XiWaMaxNumber numeric(18,0)

		SELECT COUNT(1) FROM #tempP
		WHILE (@RCOUNT<0)
		BEGIN
			SELECT TOP (@RCOUNT) @NOWTYPEID=typeid FROM #tempP
			SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM PType
			UPDATE PType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @NOWTYPEID
			SET @RCOUNT=@RCOUNT-1
		END
		
		--POS下载处理
		EXEC Gp_DataSaveForPosDown '-99999','Ptype','0'
	END
END

IF @optype = 'a'---新增
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Ptype_Units WHERE UserCode = @UserCode)
	BEGIN
		RAISERROR('编号已存在，请修改后再保存。',16,1) 
		RETURN
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM Ptype_Units WHERE FullName = @FullName)
	BEGIN
		RAISERROR('名称已存在，请修改后再保存。',16,1)
		RETURN
	END
	
	INSERT INTO Ptype_Units(UserCode,FullName,Comment)
	VALUES(
		@UserCode,
		@FullName,
		@Comment		
	)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_SaveSrialInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_SaveSrialInfo];
GO

/*
	作者:颜熙
	日期:2017-08-18
	描述:存储网店序列号信息
*/
CREATE  PROCEDURE Gp_SaveSrialInfo
( 
	@ordercode VARCHAR(MAX), --订单编号
	@goodscode VARCHAR(500), --商品编号
	@sku_erpid VARCHAR(500), --规格编号
	@serial VARCHAR(MAX), --序列号
	@whstpt_erpid VARCHAR(50), --货位id
	@serialRelationCargoStr VARCHAR(8000), --序列号关联货位id
	@mid INT --行号
)
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
		DECLARE @serialRelationId INT 
		SELECT	@serialRelationId = serialRelationId
		FROM      WdCargoDetail
		WHERE     whstpt_erpid = @whstpt_erpid
				  AND sku_erpid = @sku_erpid
				  AND ordercode = @ordercode
				  AND CAST(serialRelationId AS INT)  IN (SELECT a FROM dbo.f_split(@serialRelationCargoStr,','));

		 IF @serialRelationId =NULL
		 BEGIN
			SET @serialRelationId = 99999
		 END 
        INSERT  INTO WdSerialsDetail
                ( ordercode ,
                  goodscode ,
                  whstpt_erpid ,
                  serial ,
                  sku_erpid ,
                  serialRelationId,
                  mid
                )
        VALUES  ( @ordercode ,
                  @goodscode ,
                  @whstpt_erpid ,
                  @serial ,
                  @sku_erpid ,
                  @serialRelationId,
                  @mid
                ); 
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveStockUserConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SaveStockUserConfig]
GO





/*
	保存进销存汇总表的个人配置
*/
CREATE PROCEDURE Gp_SaveStockUserConfig
(
	@chvOperatorId		varchar(200),
	@strBillTypes		varchar(200),
	@strShowMoney		varchar(10),
	@strBdPtype			varchar(10),
	@strSum				varchar(10),
	@nFlag				varchar(10)
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 * FROM StockTotalConfig WHERE ETypeId = @chvOperatorId)
	INSERT INTO StockTotalConfig
	(
		ETypeId,
		BillTypes,
		ShowMoney,
		ShowBdPType,
		ShowSum
	)VALUES(
		@chvOperatorId,
		@strBillTypes,
		@strShowMoney,
		@strBdPtype,
		@strSum
	)
ELSE
	UPDATE	StockTotalConfig
	SET		BillTypes 	= @strBillTypes,
			ShowMoney 	= @strShowMoney,
			ShowBdPType	= @strBdPtype,
			ShowSum		= @strSum
	WHERE	ETypeId		= @chvOperatorId


IF @@ROWCOUNT = 0
	RETURN -1
ELSE
	RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_SAVETe_InitDataDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_SAVETe_InitDataDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*
	作者：黄清	
	日期：2014-05-19
	描述：出纳系统初始化数据明细保存

*/
CREATE PROCEDURE [dbo].[GP_SAVETe_InitDataDetail]
(
	@indexid		varchar(100),	--表头ID
	@atypeid		VARCHAR(50),	--科目ID
	@fdebit			 NUMERIC(24, 10) ,	--借方累计发生
	@fcredit		 NUMERIC(24, 10) ,	--贷方累计发生
	@initbalance	 NUMERIC(24, 10) ,	--期初余额
	@accountid		VARCHAR(50)		--银行存款ID
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @rate  NUMERIC(24, 10) =1.0
DECLARE @CID INT=0
DECLARE @stypeid VARCHAR(50)=''
DECLARE @BasisType INT=0
DECLARE @fdebitori  NUMERIC(24, 10) =0
DECLARE @fcreditori  NUMERIC(24, 10) =0
DECLARE @initbalanceori  NUMERIC(24, 10) =0

SELECT @CID=Cid,@rate=Rate,@stypeid=STypeId FROM Te_InitDataIndex WHERE id = @indexid
SELECT @BasisType=BasisType FROM Ac_Currency WHERE CId=@CID

DECLARE @AFullName VARCHAR(200)
SELECT @AFullName=FullName FROM Ac_Account WHERE TypeId=@atypeid AND StypeId=@stypeid

--检查科目是否存在
IF NOT EXISTS (SELECT 1 FROM Ac_Account WHERE TypeId=@atypeid AND StypeId=@stypeid)
BEGIN
	RAISERROR('明细数据中包含不存在的科目，确认后将关闭窗口，请重新录入初始化数据',16,1,@AFullName)RETURN -1 --RETURN -4
END

--检查科目币种是否停用
IF EXISTS (SELECT 1 FROM Ac_Account WHERE TypeId=@atypeid AND Deleted='1' AND StypeId=@stypeid)
BEGIN
	RAISERROR('科目【%s】已停用，确认后将关闭窗口，请重新录入初始化数据',16,1,@AFullName)RETURN--RETURN -4
END

--检查科目是否被分类
IF EXISTS (SELECT 1 FROM Ac_Account WHERE TypeId=@atypeid AND SonNum<>0 AND StypeId=@stypeid)
BEGIN
	RAISERROR('科目【%s】已被分类，确认后将关闭窗口，请重新录入初始化数据',16,1,@AFullName)RETURN--RETURN -4
END

--检查科目币种是否正确
IF EXISTS (SELECT 1 FROM Ac_Account WHERE TypeId=@atypeid AND StypeId=@stypeid AND Cid<>@CID AND Cid<>0)
BEGIN
	RAISERROR('科目【%s】币种信息已变更，确认后将关闭窗口，请重新录入初始化数据',16,1,@AFullName)RETURN--RETURN -4
END

IF @accountid IS NOT NULL OR @accountid <>''
BEGIN
	DECLARE @tebankname VARCHAR(50)
	SELECT @tebankname=FullName FROM Te_BankAccount WHERE id=@accountid

	--检查银行账户是否存在
	IF NOT EXISTS (SELECT * FROM Te_BankAccount WHERE id=@accountid)
	BEGIN
		RAISERROR('银行账户存在异常，确认后将关闭窗口，请重新录入初始化数据',16,1)RETURN--RETURN -4
	END

	--检查银行账户是否销户
	IF EXISTS (SELECT * FROM Te_BankAccount WHERE id=@accountid AND IsDestroy='1')
	BEGIN
		RAISERROR('银行账户【%s】已销户，确认后将关闭窗口，请重新录入初始化数据',16,1,@tebankname)RETURN--RETURN -4
	END

	--检查银行账户分支机构是否正确
	IF NOT EXISTS (SELECT * FROM Te_BankAccount WHERE id=@accountid AND STypeId=@stypeid)
	BEGIN
		RAISERROR('银行账户【%s】分支机构不正确，确认后将关闭窗口，请重新录入初始化数据',16,1,@tebankname)RETURN--RETURN -4
	END
	
	--检查银行账户对应科目
	IF NOT EXISTS (SELECT *FROM Te_BankAccount WHERE id=@accountid AND aTypeId=@Atypeid)
	BEGIN
		RAISERROR('银行账户【%s】对应科目不正确，确认后将关闭窗口，请重新录入初始化数据',16,1,@tebankname)RETURN--RETURN -4
	END
END


IF @BasisType=0
	BEGIN
		SET @fdebitori=dbo.f_roundtotal(@fdebit*@rate)
		SET @fcreditori=dbo.f_roundtotal(@fcredit*@rate)
		SET @initbalanceori=dbo.f_roundtotal(@initbalance*@rate)
	END
ELSE
	BEGIN
		SET @fdebitori=dbo.f_roundtotal(@fdebit/@rate)
		SET @fcreditori=dbo.f_roundtotal(@fcredit/@rate)
		SET @initbalanceori=dbo.f_roundtotal(@initbalance/@rate)
	END



INSERT INTO Te_InitDataDetail
(
	AtypeId,
	IndexId,
	FDebit,
	FCredit,
	InitBalance,
	FDebitOri,
	FCreditOri,
	InitBalanceOri,
	AccountId
)VALUES
(
	@atypeid,
	@indexid,
	@fdebit,
	@fcredit,
	@initbalance,
	@fdebitori,
	@fcreditori,
	@initbalanceori,
	@accountid
)

IF @@ROWCOUNT=0
	RETURN -1
	
--清除全为0的数据
DELETE FROM Te_InitDataDetail WHERE FDebit=0 AND FCredit=0 AND InitBalance=0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_SAVETe_InitDataIndex]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_SAVETe_InitDataIndex]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*
	作者：黄清	
	日期：2014-05-19
	描述：出纳系统初始化数据表头保存

*/
CREATE PROCEDURE [dbo].[GP_SAVETe_InitDataIndex]
(	
	@stypeid	varchar(100),	--分支机构ID
	@buid		VARCHAR(5),		--业务类型ID
	@cid		VARCHAR(5),		--币种ID
	@OperatorID	VARCHAR(50)		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @stypeid AND IsUse = 1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		RAISERROR('该分支机构已经结束初始化，不能保存初始化数据',16,1)
	ELSE
		RAISERROR('已经结束初始化，不能保存初始化数据',16,1)
END

DECLARE @rate  NUMERIC(24, 10) 
SELECT @rate=Rate FROM AC_CURRENCY WHERE CId=@cid

DECLARE @INDEXID INT

IF EXISTS(SELECT * FROM Te_InitDataIndex WHERE STypeId=@stypeid AND BUId=@buid AND Cid=@cid)
BEGIN
	SELECT @INDEXID=ID FROM Te_InitDataIndex WHERE STypeId=@stypeid AND BUId=@buid AND Cid=@cid

	UPDATE Te_InitDataIndex
	SET Rate=@rate
	WHERE ID=@INDEXID
	RETURN @INDEXID
END

INSERT INTO Te_InitDataIndex
(
	STypeId,
	BUId,
	Cid,
	Finish,
	Rate
)VALUES
(
	@stypeid,
	@buid,
	@cid,
	'0',
	@rate
)

IF @@ROWCOUNT=0
	RETURN -1
ELSE 
	RETURN @@IDENTITY

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveTeAccountInitialTransit]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_SaveTeAccountInitialTransit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--==================================================
--by:glj
--date:2016-02-17
--description:期初未达账保存
--==================================================
CREATE PROCEDURE Gp_SaveTeAccountInitialTransit
(
	@OperatorId		VARCHAR(50),		-- 当前操作员ID
	@STypeId		VARCHAR(50),		-- 分支机构
	@Type			INT,				-- 类型 0.银行未达账 1.企业未达账
	@Data			Type_AccountInTransit READONLY--表值参数 未达账明细
)
--@encode$--
AS
SET NOCOUNT ON

--开始事务
IF EXISTS(SELECT TOP 1 1 FROM @Data T1 
		WHERE  CreateDate>=(SELECT T3.FBegin
				from dbo.Te_StartPeriod T2
				INNER JOIN dbo.Ac_Period T3 ON T2.SFYear = T3.FYear AND T2.SFPeriod = T3.FPeriod
			WHERE T2.STypeId = @STypeId)
		)
BEGIN
	RAISERROR('业务日期必须小于启用期间,无法保存！',16,1)
	RETURN -1
END
BEGIN TRAN
DECLARE 
	@I		INT=1,
	@Error	INT=0,
	@IndexId INT=0,--新增表头ID
	@COUNT	INT

CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200))
INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName) 
SELECT L.Typeid,L.Stypeid,A.FullName FROM F_LineAccount(@OperatorID,@STypeID) L
INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
WHERE A.Deleted<>'1' 

CREATE TABLE #t_temp(ID INT)
insert into #t_temp(ID)
SELECT  T1.ID
FROM dbo.Te_AccountInTransit_Index T1
INNER JOIN dbo.Te_AccountInTransit_Detail T2 ON T1.id = T2.IndexId
INNER JOIN dbo.Te_BankAccount T3 ON T1.AccountId = T3.Id
INNER JOIN Ac_Account A ON A.StypeId=T3.STypeId AND A.TypeId=T3.ATypeId
LEFT JOIN #Ac_Account_L T4 ON T3.ATypeId = T4.TypeId AND T3.STypeId = T4.StypeId
WHERE 
T1.Type = @Type 
AND T1.IsInit = 1
AND  T3.STypeId=@STypeID 
	
--修改已经存在的数据
UPDATE Te_AccountInTransit_Index
SET 
	AccountId=T.AccountId,
	FDebitTotal=T.FDebit,
	FCreditTotal=T.FCredit,
	ATypeId=T.ATypeId,
	Cid=T.Cid,
	Rate=C.Rate,
	FDebitTotalOri=dbo.f_roundtotal(CASE WHEN C.BasisType = 0 THEN T.FDebit * C.Rate ELSE T.FDebit /C.Rate END),
	FCreditTotalOri=dbo.f_roundtotal(CASE WHEN C.BasisType = 0 THEN T.FCredit * C.Rate ELSE T.FCredit / C.Rate END)
FROM Te_AccountInTransit_Index I
INNER JOIN @Data T ON T.IndexId=I.Id AND T.IsEdit=1
INNER JOIN Ac_Currency C ON C.CId=T.Cid 
SET @Error+=@@ERROR

UPDATE Te_AccountInTransit_Detail
SET
	CreateDate=T.CreateDate,
	Summary=T.Summary,
	ETypeId=T.ETypeId,
	FSettleId=T.FSettleId,
	FSettleNo=T.FSettleNo,
	FDebit=T.FDebit,
	FCredit=T.FCredit,
	FDebitOri=dbo.f_roundtotal(CASE WHEN C.BasisType = 0 THEN T.FDebit * C.Rate ELSE T.FDebit / C.Rate END),
	FCreditOri=dbo.f_roundtotal(CASE WHEN C.BasisType = 0 THEN T.FCredit * C.Rate ELSE T.FCredit / C.Rate END)
FROM Te_AccountInTransit_Detail D
INNER JOIN @Data T ON T.IndexId=D.IndexId AND T.IsEdit=1
INNER JOIN Ac_Currency C ON C.CId=T.Cid 
SET @Error+=@@ERROR
--新增
DECLARE @DataTemp TABLE(NID INT IDENTITY(1,1),RowID INT)
INSERT INTO @DataTemp(RowID)
SELECT RowId FROM @Data WHERE IndexId=0 
SELECT @COUNT=@@ROWCOUNT

WHILE(@I<=@COUNT)
	BEGIN
		INSERT INTO Te_AccountInTransit_Index(AccountId,FDebitTotal,FCreditTotal,Type,IsInit,ATypeId,Cid,Rate,FDebitTotalOri,FCreditTotalOri)
		SELECT 
			T.AccountId,
			T.FDebit,
			T.FCredit,
			@Type,
			1,
			T.ATypeId,
			T.Cid,
			C.Rate,
			dbo.f_roundtotal(CASE WHEN C.BasisType = 0 THEN T.FDebit * C.Rate ELSE T.FDebit / C.Rate END),
			dbo.f_roundtotal(CASE WHEN C.BasisType = 0 THEN T.FCredit * C.Rate ELSE T.FCredit / C.Rate END) 
		FROM @Data T
		INNER JOIN @DataTemp TT ON TT.RowID=T.RowId AND TT.NID=@I 
		INNER JOIN Ac_Currency C ON C.CId=T.Cid
		SET @Error+=@@ERROR
		SELECT @IndexId=@@IDENTITY--新增表头ID
		
		INSERT INTO Te_AccountInTransit_Detail(IndexId,CreateDate,Summary,ETypeId,FSettleId,FSettleNo,FDebit,FCredit,FDebitOri,FCreditOri)
		SELECT 
			@IndexId,
			T.CreateDate,
			T.Summary,
			T.ETypeId,
			T.FSettleId,
			T.FSettleNo,
			T.FDebit,
			T.FCredit,
			dbo.f_roundtotal(CASE WHEN C.BasisType = 0 THEN T.FDebit * C.Rate ELSE T.FDebit / C.Rate END),
			dbo.f_roundtotal(CASE WHEN C.BasisType = 0 THEN T.FCredit * C.Rate ELSE T.FCredit / C.Rate END)
		FROM @Data T
		INNER JOIN @DataTemp TT ON TT.RowID=T.RowId AND TT.NID=@I 
		INNER JOIN Ac_Currency C ON C.CId=T.Cid
		SET @Error+=@@ERROR
		
		SET @I+=1
	END
--删除都没有的

	
delete #t_temp where exists(select T.IndexId from  @Data T where T.IndexId=#t_temp.Id)

delete Te_AccountInTransit_Index 
where exists (select   t1.id from #t_temp t1 where t1.id=Te_AccountInTransit_Index.id) 
 
delete Te_AccountInTransit_Detail 
where exists (select   t1.id from #t_temp t1 where t1.id=Te_AccountInTransit_Detail.IndexId) 
	
drop table #Ac_Account_L,#t_temp

IF(@Error>0)
	BEGIN
		ROLLBACK TRAN
		RETURN  0
	END
ELSE 
	BEGIN
		COMMIT TRAN 
		RETURN 1
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveTeAccountInTransit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SaveTeAccountInTransit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.05.16
	描述：未达账保存
*/
CREATE PROCEDURE Gp_SaveTeAccountInTransit
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@STypeId			VARCHAR(50),		-- 分支机构
	@AccountId			INT,				-- 银行账户
	@Cid				INT,				-- 数据币种
	@Type				INT,				-- 类型 0.银行未达账 1.企业未达账
	@IsInit				INT,				-- 是否期初 0.非期初 1.期初
	@Table	TbType_AccountInTransit READONLY,--表值参数 未达账明细
	@RowId				INT=0				--待修改明细ID
)
--@encode$--
AS
SET NOCOUNT ON

--开始事务
BEGIN TRAN


IF EXISTS(SELECT TOP 1 1 FROM @Table T1 
		WHERE createdate <(SELECT T3.FBegin
				from dbo.Te_StartPeriod T2
				INNER JOIN dbo.Ac_Period T3 ON T2.SFYear = T3.FYear AND T2.SFPeriod = T3.FPeriod
			WHERE T2.STypeId = @STypeId)
		)
	AND @IsInit = 0
BEGIN
	RAISERROR('业务日期小于启用期间第一天，无法保存！',16,1)
	ROLLBACK TRAN
	RETURN -1
END


--获取科目、汇率
DECLARE @ATypeId VARCHAR(50),@Rate  NUMERIC(24, 10) ,@BasisType INT

SELECT @ATypeId = ATypeId FROM dbo.Te_BankAccount WHERE Id = @AccountId
SELECT @Rate = Rate,@BasisType = BasisType FROM dbo.Ac_Currency WHERE CId = @Cid

--表头id
DECLARE @Id INT

--修改的情况
IF @RowId > 0
BEGIN
	
	SELECT @id = IndexId FROM dbo.Te_AccountInTransit_Detail WHERE Id= @RowId
	
	SELECT @Rate = Rate FROM dbo.Te_AccountInTransit_Index 
	WHERE Id = @Id

	UPDATE T1
		SET CreateDate = T2.CreateDate,
          Summary = T2.Summary,
          ETypeId = T2.ETypeId,
          FSettleId = T2.FSettleId,
          FSettleNo = T2.FSettleNo,
          FDebit = T2.FDebit,
          FCredit = T2.FCredit,
          FDebitOri = CASE WHEN @BasisType = 0 THEN T2.FDebit / @Rate
							ELSE T2.FDebit * @Rate
						END,
		  FCreditOri = CASE WHEN @BasisType = 0 THEN T2.FCredit / @Rate
							ELSE T2.FCredit * @Rate
						END
   FROM Te_AccountInTransit_Detail T1
	INNER JOIN @Table T2 ON T1.Id = T2.rowid
END

ELSE--新建保存
BEGIN
	--插入表头
	INSERT INTO dbo.Te_AccountInTransit_Index
			( AccountId ,
			  FDebitTotal ,
			  FCreditTotal ,
			  Type ,
			  IsInit ,
			  ATypeId ,
			  Cid ,
			  Rate ,
			  FDebitTotalOri ,
			  FCreditTotalOri
			)
	VALUES(@AccountId,
			0,
			0,
			@Type,
			@IsInit,
			@ATypeId,
			@Cid,
			@Rate,
			0,
			0
			)

	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RAISERROR('未达账保存异常，请重试！',16,1)
		RETURN
	END

	SET @Id = @@Identity

	--插入明细
	INSERT INTO dbo.Te_AccountInTransit_Detail
			( IndexId ,
			  CreateDate ,
			  Summary ,
			  ETypeId ,
			  FSettleId ,
			  FSettleNo ,
			  FDebit ,
			  FCredit ,
			  FDebitOri ,
			  FCreditOri
			)
	SELECT  @Id,
			CreateDate,
			Summary,
			ETypeId,
			FSettleId,
			FSettleNo,
			FDebit,
			FCredit,
			CASE WHEN @BasisType = 0 THEN FDebit / @Rate
					ELSE FDebit * @Rate
			END,
			CASE WHEN @BasisType = 0 THEN FCredit / @Rate
					ELSE FCredit * @Rate
			END
	FROM @Table

	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RAISERROR('未达账明细保存异常，请重试！',16,1)
		RETURN
	END

END

--更新表头借贷金额

--总金额
DECLARE @FDebit  NUMERIC(24, 10) ,@FCredit  NUMERIC(24, 10) ,@FDebitOri  NUMERIC(24, 10) ,@FCreditOri  NUMERIC(24, 10) 

SELECT  @FDebit = SUM(FDebit),
		@FCredit = SUM(FCredit),
		@FDebitOri = SUM(FDebitOri),
		@FCreditOri = SUM(FCreditOri)
FROM dbo.Te_AccountInTransit_Detail
WHERE IndexId = @Id

UPDATE dbo.Te_AccountInTransit_Index 
	SET FDebitTotal = @FDebit,
		FCreditTotal = @FCredit,
		FDebitTotalOri = @FDebitOri,
		FCreditTotalOri = @FCreditOri
WHERE Id = @Id
--提交事务
COMMIT TRAN

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveUnitsTrack]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SaveUnitsTrack]
GO
/*
	作者: 魏伟
	时间: 2015-05-26
	描述: 计量单位与往来单位跟踪表数据新增及修改
*/

CREATE PROCEDURE [Gp_SaveUnitsTrack]
( 
		@BillType           INT,          ---单据类型
		@BillDate           DATETIME,
		@BTypeId            VARCHAR(50),  ---往来单位ID
		@PTypeId			VARCHAR(50),  ---商品ID
		@UnitId				INT,		  ---计量单位ID
		@optype				VARCHAR(10),   ---新增或修改标志  m 修改  a 添加
		@Id                 varchar(100)  ---表单id
)
--@encode$--
AS
SET NOCOUNT ON 
IF @optype = 'a'---新增
BEGIN 
IF EXISTS(SELECT TOP 1 1 FROM dbo.UnitsTrack WHERE BillType = @BillType AND BtypeId=@BTypeId AND PtypeId= @PTypeId AND UnitId=@UnitId)
	BEGIN
		RAISERROR('数据库中存在相同的往来单位和商品记录',16,1) 
		RETURN
	END
INSERT INTO UnitsTrack
(
		PTypeid,
		BillType,
		BillDate,
		BTypeId,
		UnitId
)
VALUES
(
		@PTypeId,
		@BillType,
		@BillDate,
		@BTypeId,
		@UnitId
)
END 


IF @optype = 'm' ---修改
BEGIN
IF EXISTS(SELECT TOP 1 1 FROM dbo.UnitsTrack WHERE BillType = @BillType AND BtypeId=@BTypeId AND PtypeId= @PTypeId AND UnitId=@UnitId)
	BEGIN
		RAISERROR('数据库中存在相同的往来单位和商品记录',16,1)	
		RETURN
	END
	 UPDATE UnitsTrack
	 SET  PTypeid  =@PTypeId,
		  BillType=@BillType,
		  BillDate=@BillDate,
		  BTypeId=@BTypeId,
		  UnitId=@UnitId
		  WHERE ID=@Id
	 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveVacation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveVacation
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-10-27
	描述：考勤节假日设置
*/
CREATE PROCEDURE Gp_SaveVacation
(
	@fullname			varchar(max),		--节假日名称
	@stypeid			varchar(max),		--分支机构
	@starttime			varchar(max),		--节假日开始时间
	@endtime			varchar(max),		--节假日结束时间
	@otype				varchar(2)	,		--类型 a.新增  m.修改 
	@datestring			varchar(max),		--假日明细
	@id					int
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @date varchar(10)='',@INDEXID INT=0 
IF @otype = 'a' 
	BEGIN
		IF EXISTS(SELECT * FROM Vacation WHERE Fullname=@fullname AND STypeID=@stypeid)
			BEGIN
				RAISERROR('此节假日已存在，请确认后重试！',16,1)
				RETURN
			END
		INSERT INTO Vacation
		(
			Fullname,
			STypeID,
			StartTime,
			EndTime
		)
		VALUES
		(
			@fullname,
			@stypeid,
			@starttime,
			@endtime
		)
		SET @INDEXID=SCOPE_IDENTITY();
		WHILE @datestring<>''
		BEGIN
			SET @date=SUBSTRING(@datestring,2,10)
			SET @datestring=RIGHT(@datestring,LEN(@datestring)-11)
			INSERT INTO VacationDetails
			(
				IndexId,
				VacationDetailsDate
			)
			VALUES
			(
				@INDEXID,
				@date
			)
		END
		IF @@ERROR<>0
			RAISERROR('添加节假日失败！',16,1)
	END
ELSE 
	BEGIN
		IF EXISTS(SELECT * FROM Vacation WHERE Fullname=@fullname AND STypeID=@stypeid AND ID<>@id)
				BEGIN
					RAISERROR('此节假日已存在，请确认后重试！',16,1)
					RETURN
				END
		UPDATE	Vacation
		SET		Fullname	=@fullname,
				STypeID		=@stypeid,
				StartTime	=@starttime,
				EndTime		=@EndTime
		WHERE   ID=@id
		
		DELETE FROM VacationDetails WHERE IndexId=@id
		WHILE @datestring<>''
		BEGIN
			SET @date=SUBSTRING(@datestring,2,10)
			SET @datestring=RIGHT(@datestring,LEN(@datestring)-11)
			INSERT INTO VacationDetails
			(
				IndexId,
				VacationDetailsDate
			)
			VALUES
			(
				@id,
				@date
			)
		END
		IF @@ERROR<>0
			RAISERROR('修改节假日信息失败！',16,1)	
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM DBO.SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[GP_SaveVoucherCommonlyBillDetail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
	DROP PROCEDURE [dbo].[GP_SaveVoucherCommonlyBillDetail]
END
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*************************************************************************
* 创建人：罗淮文
* 创建日期：2014-05-13
* 内容描述：常用凭证模板明细保存
**************************************************************************/
CREATE PROCEDURE GP_SaveVoucherCommonlyBillDetail
(
	@BillNumberId VARCHAR(50)
	,@Summary VARCHAR(200)
	,@STypeId VARCHAR(50)
	,@ATypeId VARCHAR(50)
	,@Fdc INT
	,@FAdc INT
	,@FDebitTotal  NUMERIC(24, 10) 
	,@FCreditTotal  NUMERIC(24, 10) 
	,@FYear VARCHAR(10)
	,@FPeriod INT
	,@Comment VARCHAR(200)
	,@RowNo INT
	,@OldBillNumberId VARCHAR(50)
	,@AscIds VARCHAR(4000)
)
--@encode$-- 
AS
SET NOCOUNT ON
BEGIN
	--新增常用凭证模板
	INSERT INTO [dbo].[Ac_Voucher_Commonly_Bill]
       ([BillNumberId]
       ,[Summary]
       ,[STypeId]
       ,[ATypeId]
       ,[Fdc]
       ,[FAdc]
       ,[FDebitTotal]
       ,[FCreditTotal]
       ,[FYear]
       ,[FPeriod]
       ,[Comment]
       ,[RowNo]
       ,[AscIds])
	VALUES
       (@BillNumberId
       ,@Summary
       ,@STypeId
       ,@ATypeId
       ,@Fdc
       ,@FAdc
       ,@FDebitTotal
       ,@FCreditTotal
       ,@FYear
       ,@FPeriod
       ,@Comment
       ,@RowNo
       ,@AscIds)
	IF(@@ROWCOUNT = 0 OR @@ERROR <> 0)
	BEGIN
		RAISERROR('常用凭证模板明细保存失败，请确认！',16,1)
		RETURN -1
	END
	RETURN SCOPE_IDENTITY()
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM DBO.SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[GP_SaveVoucherCommonlyBillIndex]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
	DROP PROCEDURE [dbo].[GP_SaveVoucherCommonlyBillIndex]
END
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*************************************************************************
* 创建人：罗淮文
* 创建日期：2014-05-13
* 内容描述：常用凭证模板保存
**************************************************************************/
CREATE PROCEDURE GP_SaveVoucherCommonlyBillIndex
(
	@BillCode VARCHAR(50)
	,@BillName VARCHAR(200)
	,@STypeId VARCHAR(50)
	,@VgId INT
	,@AttachFileCount INT
	,@ETypeId VARCHAR(50)
	,@FYear VARCHAR(10)
	,@FPeriod INT
	,@FDebitTotal  NUMERIC(24, 10) 
	,@FCreditTotal  NUMERIC(24, 10) 
	,@FEntryCount INT
	,@FComment VARCHAR(200)
	,@OldBillNumberId INT
)
--@encode$-- 
AS
SET NOCOUNT ON
BEGIN
	--新增常用凭证模板
	IF(@OldBillNumberId < 1)
	BEGIN
		--判断编码/名称是否重复
		IF EXISTS(SELECT 1 FROM [dbo].[Ac_Voucher_Commonly] WHERE [BillCode]=@BillCode)
		BEGIN
			RAISERROR('常用凭证模板编码重复，请确认！',16,1)
			RETURN -1
		END
		INSERT INTO [dbo].[Ac_Voucher_Commonly]
			   ([BillCode]
			   ,[BillName]
			   ,[STypeId]
			   ,[VgId]
			   ,[AttachFileCount]
			   ,[ETypeId]
			   ,[FYear]
			   ,[FPeriod]
			   ,[FDebitTotal]
			   ,[FCreditTotal]
			   ,[FEntryCount]
			   ,[FModifyTime]
			   ,[FComment])
		 VALUES
			   (@BillCode
			   ,@BillName
			   ,@STypeId
			   ,@VgId
			   ,@AttachFileCount
			   ,@ETypeId
			   ,@FYear
			   ,@FPeriod
			   ,@FDebitTotal
			   ,@FCreditTotal
			   ,@FEntryCount
			   ,GETDATE()
			   ,@FComment)
		IF(@@ROWCOUNT = 0 OR @@ERROR <> 0)
		BEGIN
			RAISERROR('常用凭证模板保存失败，请确认！',16,1)
			RETURN -1
		END
		RETURN SCOPE_IDENTITY()
	END
	--修改常用凭证模板
	ELSE
	BEGIN
		--判断编码/名称是否重复
		IF EXISTS(SELECT 1 FROM [dbo].[Ac_Voucher_Commonly] WHERE [BillCode]=@BillCode AND BillNumberId != @oldbillnumberid)
		BEGIN
			RAISERROR('常用凭证模板编码重复，请确认！',16,1)
			RETURN -1
		END
		UPDATE [dbo].[Ac_Voucher_Commonly]
		SET [BillCode] = @BillCode
		  ,[BillName] = @BillName
		  ,[STypeId] = @STypeId
		  ,[VgId] = @VgId
		  ,[AttachFileCount] = @AttachFileCount
		  ,[ETypeId] = @ETypeId
		  ,[FYear] = @FYear
		  ,[FPeriod] = @FPeriod
		  ,[FDebitTotal] = @FDebitTotal
		  ,[FCreditTotal] = @FCreditTotal
		  ,[FEntryCount] = @FEntryCount
		  ,[FModifyTime] = GETDATE()
		  ,[FComment] = @FComment
		WHERE BillNumberId = @oldbillnumberid
		IF @@ERROR <> 0
		BEGIN
			RETURN -1 
		END
		RETURN @oldbillnumberid
	END
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_SaveWdorder]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_SaveWdorder];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2017-02-09
	描述：保存网店订单
*/
CREATE PROCEDURE Gp_SaveWdorder
	(
      @ordercode VARCHAR(200) ,	-- 网店订单号
      @sourceplatformnae VARCHAR(200) ,	--原平台名字
      @ordersourcecode VARCHAR(200) ,	-- 原始订单号
      @eshopname VARCHAR(200) ,			-- 店铺名字
      @logisticscode VARCHAR(50) ,			-- 运单号
      @logisticsname VARCHAR(200),--承运公司
      @clerk_erpid VARCHAR(50),	-- 职员id
      @whs_erpid VARCHAR(50), --仓库id
      @total NUMERIC(24, 10), --金额
      @buyeraccount VARCHAR(50),--买家账号
      @qty NUMERIC(24, 10),--数量
      @buyermessage VARCHAR(200) ,--买家留言
      @privilege NUMERIC(24, 10),--优惠金额
      @buyfreight NUMERIC(24, 10),--运费
      @remark VARCHAR(5000) ,--备注
      @name VARCHAR(200) ,--姓名
      @postcode VARCHAR(200) ,
      @tel VARCHAR(200) ,--电话
      @mobile VARCHAR(200) ,--电话
      @province VARCHAR(200) ,--省份
      @city VARCHAR(200) ,--城市
      @area VARCHAR(200) ,--地区
      @detailaddress VARCHAR(5000) ,--详细地址
      @createtime VARCHAR(200) ,--创建时间
      @orderstatus VARCHAR(200) ,--订单状态
      @buyerName VARCHAR(200) ,--买家姓名
      @iscod VARCHAR(200) ,--是否货到付款
      @senddate VARCHAR(200) --发货时间
    )

--@encode$--
AS
    SET NOCOUNT ON;

    BEGIN
      DECLARE @isExist BIT
      IF EXISTS (select 1 from WdOrderBody where ordercode = @ordercode)
		SET @isExist =1
	  ELSE SET @isExist = 0
	  IF(@isExist=0)
	  BEGIN
		Insert into WdOrderBody(ordercode,sourceplatformnae,ordersourcecode,eshopname,logisticscode,logisticsname,clerk_erpid,whs_erpid,total,buyeraccount,qty,buyermessage,privilege,buyfreight,remark,name,postcode,tel,mobile,province,city,area,detailaddress,createtime,orderstatus,buyerName,iscod,senddate) 
		VALUES(@ordercode,@sourceplatformnae,@ordersourcecode,@eshopname,@logisticscode,@logisticsname,@clerk_erpid,@whs_erpid,@total,@buyeraccount,@qty,@buyermessage,@privilege,@buyfreight,@remark,@name,@postcode,@tel,@mobile,@province,@city,@area,@detailaddress,@createtime,@orderstatus,@buyerName,@iscod,@senddate)
		
		DECLARE @etypeid VARCHAR(50)='',@efullname VARCHAR(200)
		SELECT @etypeid = typeId,@efullname = FullName from employee where Eid =@clerk_erpid
		IF(@etypeid IS NULL OR @etypeid ='' OR @efullname IS NULL OR @etypeid = '')
		SET @efullname ='系统中不存在该经手人！'
		
		DECLARE @ktypeid VARCHAR(50)='',@kfullname VARCHAR(200)
		SELECT @kfullname = FullName,@ktypeid = typeId FROM dbo.Stock where Kid = @whs_erpid
		IF(@kfullname IS NULL OR @kfullname ='' OR @ktypeid IS NULL OR @ktypeid = '')
		SET @kfullname = '系统中不存在该仓库！'
	  END 
    END;


GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveWmsErpContrastSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_SaveWmsErpContrastSetting]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	WmsErp XXX ContrastSetting 
-- 时间：	2018-10-12
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [Gp_SaveWmsErpContrastSetting]
(
	@Data			Type_WmsErpContrast	READONLY,
	@Type			INT--1=仓库信息 2=客户信息  4=职员信息 5=项目信息--3=供货商信息
)
--WITH ENCRYPTION

AS
SET NOCOUNT ON

DECLARE @MSG VARCHAR(MAX)=''

SET @MSG='章鱼侠信息编号为【'+(SELECT WMS_UserCode+'、' 
FROM @Data 
WHERE ERP_TypeId <> '' AND ERP_TypeId IN(
	SELECT ERP_TypeId  FROM @Data GROUP BY ERP_TypeId HAVING COUNT(ERP_TypeId)>1
	) 
FOR XML PATH(''))

IF(ISNULL(@MSG,'')<>'')
	BEGIN
		SET @MSG=SUBSTRING(@MSG,1,LEN(@MSG)-1)+'】对照关系重复，请确认！'
		RAISERROR(@MSG,16,1) RETURN
	END
			
IF(@Type=1)--仓库信息
	BEGIN
		
		--删除重复数据
		DELETE FROM  F
		FROM WmsErpStockContrastSetting F
		INNER JOIN @Data D ON D.WMS_TypeId=F.WMS_TypeId
		
		--插入数据
		INSERT INTO WmsErpStockContrastSetting
		(
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			ERP_TypeId
		)
		SELECT 
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			ISNULL(ERP_TypeId,'')
		FROM @Data
		
		--记录同步关系
		UPDATE P SET P.IsWmsSync=1
		FROM Stock P
		INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
		WHERE ISNULL(ERP_TypeId,'')<>''

		--删除同步关系
		UPDATE P SET P.IsWmsSync=0
		FROM Stock P
		INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
		WHERE ISNULL(ERP_TypeId,'')=''
	END
ELSE IF(@Type=2)--客户信息
	BEGIN
			
		--删除重复数据
		DELETE FROM F
		FROM WmsErpBTypeContrastSetting F 
		INNER JOIN @Data D ON D.WMS_TypeId=F.WMS_TypeId
		
		--插入数据
		INSERT INTO WmsErpBTypeContrastSetting
		(
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			ERP_TypeId
		)
		SELECT 
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			ISNULL(ERP_TypeId,'')
		FROM @Data
		
		--记录同步关系
		UPDATE P SET P.IsWmsSync=1
		FROM btype P
		INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
		WHERE ISNULL(ERP_TypeId,'')<>''

		--删除同步关系
		UPDATE P SET P.IsWmsSync=0
		FROM btype P
		INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
		WHERE ISNULL(ERP_TypeId,'')=''

	END
--ELSE IF(@Type=3)--供货商信息
--	BEGIN
			
--		--删除重复数据
--		DELETE FROM F
--		FROM WmsErpBTypeContrastSetting F 
--		INNER JOIN @Data D ON D.WMS_TypeId=F.WMS_TypeId AND LEFT(D.ERP_TypeId,5)='00002'
		
--		--插入数据		
--		INSERT INTO WmsErpBTypeContrastSetting
--		(
--			WMS_TypeId,
--			WMS_UserCode,
--			WMS_FullName,
--			ERP_TypeId
--		)
--		SELECT 
--			WMS_TypeId,
--			WMS_UserCode,
--			WMS_FullName,
--			ERP_TypeId
--		FROM @Data
		
		----记录同步关系
		--UPDATE P SET P.IsWmsSync=1
		--FROM btype P
		--INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
		--WHERE ISNULL(ERP_TypeId,'')<>''

		----删除同步关系
		--UPDATE P SET P.IsWmsSync=0
		--FROM btype P
		--INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
		--WHERE ISNULL(ERP_TypeId,'')=''
--	END
ELSE IF(@Type=4)--职员信息
	BEGIN

		--删除重复数据
		DELETE FROM F
		FROM WmsErpEmployeeContrastSetting F 
		INNER JOIN @Data D ON D.WMS_TypeId=F.WMS_TypeId
		
		--插入数据
		INSERT INTO WmsErpEmployeeContrastSetting
		(
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			ERP_TypeId
		)
		SELECT 
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			ISNULL(ERP_TypeId,'')
		FROM @Data
		
		--记录同步关系
		UPDATE P SET P.IsWmsSync=1
		FROM employee P
		INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
		WHERE ISNULL(ERP_TypeId,'')<>''

		--删除同步关系
		UPDATE P SET P.IsWmsSync=0
		FROM employee P
		INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
		WHERE ISNULL(ERP_TypeId,'')=''
		
	END
ELSE IF(@Type=5)--项目信息
	BEGIN			
		--删除重复数据
		DELETE FROM F
		FROM WmsErpItemContrastSetting F 
		INNER JOIN @Data D ON D.WMS_TypeId=F.WMS_TypeId
		
		--插入数据
		INSERT INTO WmsErpItemContrastSetting
		(
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			ERP_TypeId
		)
		SELECT 
			WMS_TypeId,
			WMS_UserCode,
			WMS_FullName,
			ISNULL(ERP_TypeId,'')
		FROM @Data
		
		--记录同步关系
		UPDATE P SET P.IsWmsSync=1
		FROM Ac_Items P
		INNER JOIN @Data D ON P.nTypeId=D.ERP_TypeId
		WHERE ISNULL(ERP_TypeId,'')<>''

		--删除同步关系
		UPDATE P SET P.IsWmsSync=0
		FROM Ac_Items P
		INNER JOIN @Data D ON P.nTypeId=D.ERP_TypeId
		WHERE ISNULL(ERP_TypeId,'')=''
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SaveWmsErpPtypeContrastSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_SaveWmsErpPtypeContrastSetting]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	WmsErp XXX ContrastSetting 
-- 时间：	2018-10-12
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [Gp_SaveWmsErpPtypeContrastSetting]
(
	@Data			Type_WmsErpPtypeContrast	READONLY
)

AS
SET NOCOUNT ON

DECLARE @MSG VARCHAR(MAX)=''

SET @MSG='章鱼侠信息编号为【'+(SELECT WMS_UserCode+'、' 
FROM @Data 
WHERE ERP_TypeId <> '' AND ERP_TypeId IN(
	SELECT DISTINCT ERP_TypeId  
	FROM @Data D 
	INNER JOIN ptype P ON P.typeId=D.ERP_TypeId AND P.customitemid>0 AND D.ERP_SKUId=''
	) 
FOR XML PATH(''))

IF(ISNULL(@MSG,'')<>'')
	BEGIN
		SET @MSG=SUBSTRING(@MSG,1,LEN(@MSG)-1)+'】ERP商品为自由项商品，自由项不能为空。请确认！'
		RAISERROR(@MSG,16,1) RETURN
	END
	

SET @MSG='章鱼侠信息编号为【'+(SELECT WMS_UserCode+'、' 
FROM @Data 
WHERE ERP_TypeId <> '' AND ERP_TypeId IN(
	SELECT ERP_TypeId  FROM @Data GROUP BY ERP_TypeId,ERP_SKUId HAVING COUNT(*)>1
	) 
FOR XML PATH(''))

IF(ISNULL(@MSG,'')<>'')
	BEGIN
		SET @MSG=SUBSTRING(@MSG,1,LEN(@MSG)-1)+'】对照关系重复，请确认！'
		RAISERROR(@MSG,16,1) RETURN
	END
	

--删除重复数据
DELETE FROM F
FROM WmsErpPtypeContrastSetting F 
INNER JOIN @Data D ON F.WMS_TypeId=D.WMS_TypeId AND F.WMS_SKUId=D.WMS_SKUId

INSERT INTO WmsErpPtypeContrastSetting
(
	WMS_TypeId,
	WMS_UserCode,
	WMS_FullName,
	WMS_Standard,
	WMS_Type,	
	WMS_Unit1,	
    WMS_SKUId,	
	WMS_Prop1,
	WMS_Prop1Name,
	WMS_Prop2,
	WMS_Prop2Name,
	ERP_TypeId,	
	ERP_SKUId,
	ERP_CustomItemFrom,
	ERP_CustomItemId,
	Erp_CustomItemName
)
SELECT 
	WMS_TypeId,
	WMS_UserCode,
	WMS_FullName,
	WMS_Standard,
	WMS_Type,
	WMS_Unit1,
    WMS_SKUId,
	WMS_Prop1,
	WMS_Prop1Name,
	WMS_Prop2,
	WMS_Prop2Name,
	ISNULL(ERP_TypeId,''),
	CASE WHEN ISNULL(ERP_SKUId,'')='' THEN '0' ELSE ERP_SKUId END,
	ISNULL(ERP_CustomItemFrom,0),
	ISNULL(ERP_CustomItemId,0),
	ISNULL(ERP_CustomItemName,'')
FROM @Data D

--记录同步关系
UPDATE P SET P.IsWmsSync=1
FROM ptype P
INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
WHERE ISNULL(ERP_TypeId,'')<>''

--删除同步关系
UPDATE P SET P.IsWmsSync=0
FROM ptype P
INNER JOIN @Data D ON P.typeId=D.ERP_TypeId
WHERE ISNULL(ERP_TypeId,'')=''

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveWorkTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_SaveWorkTime
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-10-27
	描述：考勤节假日设置
*/
CREATE PROCEDURE Gp_SaveWorkTime
(
	@stypeid			varchar(50),		--分支机构
	@starttime			varchar(max),		--上班时间
	@endtime			varchar(max),		--下班时间
	@latetime			int,				--可迟到时间
	@workday			varchar(max)		--工作日
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT * FROM WorkTime WHERE stypeid=@stypeid)
BEGIN
	INSERT INTO WorkTime
	(
		stypeid,
		StartTime,
		EndTime,
		LateTime,
		WorkDay
	)
	VALUES
	(
		@stypeid,
		@starttime,
		@endtime,
		@latetime,
		@workday
	)
END
ELSE
	UPDATE worktime 
	SET starttime	=	@starttime,
		endtime		=	@endtime,
		workday		=	@workday,
		latetime	=	@latetime 
	where stypeid	=	@stypeid

IF @@ERROR<>0
	RAISERROR('考勤规则设置失败！',16,1)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SaveWxStockUserConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SaveWxStockUserConfig]
GO






/*
	保存维修品进销存汇总表的个人配置
*/
CREATE PROCEDURE Gp_SaveWxStockUserConfig
(
	@chvOperatorId		varchar(200),
	@strBillTypes		varchar(200),
	@strBdPtype			varchar(10),
	@strSum				varchar(10),
	@nFlag				varchar(10)
)
--@encode$--
AS
SET NOCOUNT ON

IF @nFlag = 'P'
	SELECT @strBdPtype = ShowBdPType FROM Wx_StockTotalConfig WHERE ETypeId = @chvOperatorId

IF NOT EXISTS(SELECT TOP 1 * FROM Wx_StockTotalConfig WHERE ETypeId = @chvOperatorId)
	INSERT INTO Wx_StockTotalConfig
	(
		ETypeId,
		BillTypes,
		ShowBdPType,
		ShowSum
	)VALUES(
		@chvOperatorId,
		@strBillTypes,
		@strBdPtype,
		@strSum
	)
ELSE
	UPDATE	Wx_StockTotalConfig
	SET		BillTypes 	= @strBillTypes,	
			ShowBdPType	= @strBdPtype,
			ShowSum		= @strSum
	WHERE	ETypeId		= @chvOperatorId


IF @@ROWCOUNT = 0
	RETURN -1
ELSE
	RETURN 0






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_SearchCommission]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[gp_SearchCommission]
GO
























--==========================================
--作者：谢吉康
--日期：2003-03-18
--描述：代销库存报表，包含委托代销和受托代销
--==========================================
CREATE                                                  PROCEDURE [gp_SearchCommission] 
(
	@OperatorID varchar(25),	--操作员ID 
	@startDate     varchar(20),           --开始时间
	@endDate      varchar(20),
	@qType varchar(20),		--查询的大类  W=委托代销查询    S=受托代销查询
	@mType varchar(20),		--查询的小类  WB=委托客户查询	WK=委托仓库查询	WJ=委托结算	 SB=受托客户查询	SK=受托仓库查询	SJ=受托结算	
	@pTypeId varchar(25),		--商品的ID
	@bTypeId varchar(25),		--客户的ID
	@kTypeId varchar(25),		--仓库的ID
	@ifLine int,			--1.线性表 0.树型表 2.明细表
	@sortFild varchar(20),		--排序字段
	@sortType int,			--1.升序  0.降序
	@isSon	int,			--0.子节点  1.父节点
	@showZero int,			--1=显示库存为0    0=不显示库存为0
	@Jtype  int			--结算类型  0.非结算  1.全部发货        2.已结算             3.未结算
)
--@encode$--
AS

SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL varchar(8000)
DECLARE @CurSonNum int       --检测当前的SonNum 
DECLARE @CurPSonNum int     --结算的时候检测PtypeID的SonNum
SELECT @SQL=''
DECLARE @BtypeAll int
SELECT  @BtypeAll=value FROM userconfig WHERE configname='btypeall'
DECLARE @SortSQL  varchar(2000)
SELECT  @SortSQL=''
BEGIN
--=============================================================================================委托代销
	IF @qType='W'
	BEGIN
                           --================================================委托客户代销
		IF @mType='WB'
		BEGIN
			SELECT @CurSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID	
                                        --=============================树型表
			IF @ifLine='0'			BEGIN
							
				SELECT @SQL='
						SELECT  b.usercode,b.fullname,b.sonnum,b.typeid,a.type as billtype,sum(isnull(a.qty,0)) as qty,sum(isnull(a.total,0)) as total,sum(isnull(a.costtotal,0)) as costtotal	
						FROM Btype b
							LEFT JOIN
								(
									SELECT qty,costtotal,total,ptypeid,btypeid,type
									FROM  commissionstock
									WHERE     Type in (140,141,142)	
										     '
									IF @pTypeID='00000'
										SELECT @SQL=@SQL+' AND PtypeId Like '+char(39)+'%'+char(39)
									Else	
										IF @CurSonNum>=1 
											SELECT @SQL=@SQL+' AND PtypeId  Like '+char(39)+@pTypeID+'%'+char(39)
										Else
											SELECT @SQL=@SQL+' AND PtypeId  = '+char(39)+@pTypeID+char(39)

								SELECT @SQL=@SQL+' AND pTypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
											  AND ( bTypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bTypeID Like '+char(39)+@MBTypeID2+'%'+char(39)+')'

				SELECT @SQL=@SQL+'	)a
						ON   b.typeid=left(a.btypeid,len(b.typeid))  '
 				IF @bTypeId='00000' 
					IF @BtypeAll=1 
						SELECT @SQL=@SQL+' WHERE  b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')'+' AND (b.parid = '+char(39)+'00001'+char(39)+' Or b.parid = '+char(39)+'00002'+char(39)+')'					
					ELSE
						SELECT @SQL=@SQL+' WHERE  b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')'+' AND b.parid = '+char(39)+'00001'+char(39)
				IF @bTypeId='00001'
					SELECT @SQL=@SQL+' WHERE b.parid = '+char(39)+'00001'+char(39)+' AND b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')' 					
				IF @bTypeId='00002'
					SELECT @SQL=@SQL+' WHERE b.parid = '+char(39)+'00002'+char(39)+' and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')' 					
				--树结点
				IF @bTypeId<>'00000' AND @bTypeId<>'00001' AND @bTypeId<>'00002' AND @isSon=1
					SELECT @SQL=@SQL+' WHERE b.parid ='+char(39)+@bTypeId+char(39)+' AND b.typeid<>'+char(39)+@bTypeId+char(39)+' AND b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')' 					 					
				--叶子结点
				IF @bTypeId<>'00000' AND @bTypeId<>'00001' AND @bTypeId<>'00002' AND @isSon=0
					SELECT @SQL=@SQL+' WHERE                                            b.typeid = '+char(39)+@bTypeId+char(39)+' AND b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')' 										
				SELECT @SQL=@SQL+' GROUP BY b.usercode,b.fullname,b.sonnum,b.typeid,a.type'
				
				SELECT @SortSQL=@SortSQL+' Order By b.UserCode'
			END
                                        --=============================线型表
			IF @ifLine='1'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID		
				SELECT @SQL='
						SELECT  b.usercode,b.fullname,b.sonnum,b.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.total,0)) as total,sum(isnull(a.costtotal,0)) as costtotal	
						FROM Btype b
							LEFT JOIN
								(
									SELECT qty,costtotal,total,ptypeid,btypeid
									FROM  commissionstock
									WHERE     Type in (140,141,142)	
										      '
									IF @pTypeID='00000'
										SELECT @SQL=@SQL+' AND PtypeId Like '+char(39)+'%'+char(39)
									Else	
										IF @CurSonNum>=1 
											SELECT @SQL=@SQL+' AND PtypeId  Like '+char(39)+@pTypeID+'%'+char(39)
										Else
											SELECT @SQL=@SQL+' AND PtypeId  = '+char(39)+@pTypeID+char(39)

								SELECT @SQL=@SQL+' AND pTypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
											  AND ( bTypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bTypeID Like '+char(39)+@MBTypeID2+'%'+char(39)+')'

				SELECT @SQL=@SQL+'	)a
						ON   b.typeid=a.btypeid'
 				IF @bTypeId='00000' 
					IF @BtypeAll=1 
						SELECT @SQL=@SQL+' WHERE b.sonnum=0 AND  b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')'--+' AND (b.parid = '+char(39)+'00001'+char(39)+' Or b.parid = '+char(39)+'00002'+char(39)+')'					
					ELSE
						SELECT @SQL=@SQL+' WHERE b.sonnum=0 AND  b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')'--+' AND b.parid = '+char(39)+'00001'+char(39)
				IF @bTypeId='00001'
					SELECT @SQL=@SQL+' WHERE b.parid like '+char(39)+'00001%'+char(39)+' AND b.sonnum=0'+' AND b.deleted=0' 					
				IF @bTypeId='00002'
					SELECT @SQL=@SQL+' WHERE b.parid like '+char(39)+'00002%'+char(39)+' AND b.sonnum=0'+' AND b.deleted=0' 					
				IF @bTypeId<>'00000' AND @bTypeId<>'00001' AND @bTypeId<>'00002' AND @isSon=1
					SELECT @SQL=@SQL+' WHERE b.parid like  '+char(39)+@bTypeId+'%'+char(39)+' AND b.typeid<>'+char(39)+@bTypeId+char(39)+'AND b.sonnum=0 AND b.deleted=0' 					
				IF @bTypeId<>'00000' AND @bTypeId<>'00001' AND @bTypeId<>'00002' AND @isSon=0
					SELECT @SQL=@SQL+' WHERE b.typeid like '+char(39)+@bTypeId+'%'+char(39)+' AND b.deleted=0' 					
				IF @showZero=0 
					SELECT @SQL=@SQL+' AND qty<>0'
				SET @SQL=@SQL+' AND (b.typeid like '+char(39)+@MBtypeid+'%'+char(39) +' OR b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+') '
				SELECT @SQL=@SQL+' GROUP BY b.usercode,b.fullname,b.sonnum,b.typeid'

				IF @sortFild ='qty'
						SELECT @SortSQL=' Order By Qty '					
				IF @sortFild ='CostTotal'
					SELECT @SortSQL=' Order By Total '	
				IF @SortSQL=''
				SELECT @SortSQL=@SortSQL+' Order By b.UserCode'
			END
                                        --=============================明细表
			IF @ifLine='2'
			BEGIN
				SELECT @SQL='
						SELECT 	bil.btypeid,
								bil.billnumberid,

								bil.billdate,sum(isnull(b.total,0)) as total,
								sum(b.qty) as qty,
								b.price,
								bil.ktypeid,
								bil.billcode,
								bil.comment,
								bil.billtype
						FROM    BillIndex  bil,InOutStockTable b		
						WHERE 	bil.billnumberid=b.billnumberid
								AND bil.draft=0
								AND bil.RedWord=0
								AND bil.ifcheck=''t''
								AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
								AND bil.billtype in (140,141,142,143)
								AND b.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
								AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
								AND ( bil.KtypeID Like '+char(39)+@MKTypeID+'%'+char(39)+' Or bil.ktypeid=''10000'' )'
						IF @bTypeId='00000'
								SELECT @SQL=@SQL+'  AND (b.btypeid like '+char(39)+'00001'+'%'+char(39)+' Or b.btypeid like '+char(39)+'00002'+'%'+char(39)+')'
						IF @bTypeId='00001'
								SELECT @SQL=@SQL+'  AND b.btypeid like '+char(39)+'00001'+'%'+char(39)
						IF @bTypeId='00002'
								SELECT @SQL=@SQL+'  AND b.btypeid like '+char(39)+'00002'+'%'+char(39)
						IF @bTypeId<>'00001' AND @bTypeId<>'00002' AND @bTypeId<>'00000'
								SELECT @SQL=@SQL+'  AND b.btypeid like  '+char(39)+@bTypeId+'%'+char(39)
						SELECT @SQL=@SQL+' Group By bil.btypeid,bil.billnumberid,bil.billdate,bil.ktypeid,bil.billcode,b.price,bil.comment,bil.billtype'
						
						SELECT @SortSQL=''
						IF @sortFild='BillDate'   SELECT @SortSQL=@SortSQL+' Order By bil.billdate '
						IF @sortFild='BillCode'   SELECT @SortSQL=@SortSQL+' Order By bil.BillCode '
						IF @sortFild='Qty'  	  SELECT @SortSQL=@SortSQL+' Order By Qty '
						IF @sortFild='BillType'   SELECT @SortSQL=@SortSQL+' Order By bil.BillType '
						IF @SortSQL =''
						SELECT @SortSQL=@SortSQL+' Order By bil.billcode'
			END
		END
                           --===============================================委托仓库代销
		IF @mType='WK'
		BEGIN
                                        --=============================委托仓库代销树型表
			IF @ifLine='0'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID
				SELECT @SQL='
						SELECT  p.typeid,p.usercode,p.fullname,p.sonnum,sum(isnull(b.qty,0)) as qty,sum(isnull(b.price,0)) as price,sum(isnull(b.total,0)) as total,sum(isnull(b.costprice,0)) as costprice,sum(isnull(b.costtotal,0)) as costtotal 
						FROM ptype p
							LEFT JOIN
							(
								SELECT	qty,
										ptypeid,
										total,
										costtotal,
										price=case when qty <> 0 then (total/qty) else 0 end,
										costprice=case when qty <> 0 then (costtotal/qty) else 0 end
								FROM 	commissionstock
								WHERE   type in (140,141,142)
									   AND qty>=0'	
								IF @bTypeID='00000'				               
									SELECT @SQL=@SQL+' AND bTypeID Like '+char(39)+'%'+char(39)
								Else
									IF @CurSonNum>=1 
										SELECT @SQL=@SQL+' AND bTypeID Like '+char(39)+@bTypeID+'%'+char(39)
									ELSE									
										SELECT @SQL=@SQL+' AND bTypeID = '+char(39)+@bTypeID+char(39)

								SELECT @SQL=@SQL+' AND pTypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
											  AND ( bTypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bTypeID Like '+char(39)+@MBTypeID2+'%'+char(39)+')'

				SELECT @SQL=@SQL+')b
						ON p.typeid=left(b.ptypeid,len(p.typeid))
						WHERE p.typeid<>'+char(39)+'00000'+char(39)
				IF @PTypeId='00000'
					SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@PTypeId+char(39)+' AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
				IF @PTypeId<>'00000' AND @isSon=1
					SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@PTypeId+char(39)+' AND p.typeId<>'+char(39)+@PTypeId+char(39)+' AND p.deleted=0'		
				IF @PTypeId<>'00000' AND @isSon=0
					SELECT @SQL=@SQL+' AND p.typeid ='+char(39)+@PTypeId+char(39)+' AND p.deleted=0'
				SELECT @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.fullname,p.sonnum'

				SELECT @SortSQL=@SortSQL+' Order By p.UserCode'
			END
                                        --=============================委托仓库代销线型表
			IF @ifLine='1'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID
				SELECT @SQL='
						SELECT  p.typeid,p.usercode,p.fullname,p.sonnum,sum(isnull(b.qty,0)) as qty,sum(isnull(b.price,0)) as price,sum(isnull(b.total,0)) as total,sum(isnull(b.costprice,0)) as costprice,sum(isnull(b.costtotal,0)) as costtotal 
						FROM ptype p
							LEFT JOIN
							(
								SELECT	qty,

										ptypeid,
										total,
										costtotal,
										price=case when qty <> 0 then (total/qty) else 0 end,
										costprice=case when qty <> 0 then (costtotal/qty) else 0 end
								FROM 	commissionstock
								WHERE   type in (140,141,142)
'					               
								IF @bTypeID='00000'				               
									SELECT @SQL=@SQL+' AND bTypeID Like '+char(39)+'%'+char(39)
								Else
									IF @CurSonNum>=1 
										SELECT @SQL=@SQL+' AND bTypeID Like '+char(39)+@bTypeID+'%'+char(39)
									ELSE									
										SELECT @SQL=@SQL+' AND bTypeID = '+char(39)+@bTypeID+char(39)

								SELECT @SQL=@SQL+' AND pTypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
											  AND ( bTypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bTypeID Like '+char(39)+@MBTypeID2+'%'+char(39)+')'

				SELECT @SQL=@SQL+')b
						ON p.typeid=b.ptypeid
						WHERE p.typeid<>'+char(39)+'00000'+char(39)
				IF @pTypeId='00000'
					SELECT @SQL=@SQL+' AND  p.sonnum=0 AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
				IF @pTypeId<>'00000' AND @isSon=1
					SELECT @SQL=@SQL+' AND p.typeid like  '+char(39)+@pTypeId+'%'+char(39)+' AND p.deleted=0 AND p.sonnum=0'
				IF @pTypeId<>'00000' AND @isSon=0
					SELECT @SQL=@SQL+' AND p.typeid like  '+char(39)+@pTypeId+'%'+char(39)+' AND p.deleted=0'
				IF @showZero=0 
					SELECT @SQL=@SQL+' AND qty<>0'
				SELECT @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.fullname,p.sonnum'

				
				--=======================================构造排序字段
				IF @sortFild='Qty'  	   SELECT @SortSQL=' Order By b.Qty '
				IF @sortFild='CostTotal'   SELECT @SortSQL=' Order By b.CostTotal '
				IF @SortSQL=''             SELECT @SortSQL=' Order By p.UserCode'	


			END
                                        --=============================委托仓库代销明细表
			IF @ifLine='2'
			BEGIN
				SELECT @SQL='
						  SELECT 	
								bil.billdate,
								bil.billcode,
								p.usercode as pusercode,
								p.fullname as pfullname,
								p.standard,
								p.type,
								p.entrycode,
								p.unit1,
								bt.usercode as busercode,
								bt.fullname as bfullname,
								sum(isnull(case b.billtype when ''140'' then -b.qty when ''142'' then -b.qty else b.qty end,0)) as qty,
								sum(isnull( b.costprice,0)) as costprice,
								sum(isnull(case b.Billtype when ''140'' then -b.costtotal when ''142'' then -b.costtotal else b.costtotal end,0)) as costtotal,
								bil.billtype,
								bil.billnumberid,
								--sum(isnull(b.price,0)) as price,
								sum(isnull(case b.Billtype when ''140'' then -b.total when ''142'' then -b.total else b.total end,0)) as total,
								bil.checke,
								e.fullname as efullname,							
								bil.totalmoney,
								bil.comment,
								bil.tax,
								bil.ktypeid,
								bil.etypeid ,
								b.price 
						  FROM          InOutStockTable b,
								billindex bil,
								ptype p,
								btype bt,
								employee e						
						  WHERE         bil.billnumberid=b.billnumberid
								AND bil.etypeId=e.TypeID								
							        AND bil.draft=0
							        AND bil.RedWord=0
  							        AND bil.ifcheck=''t''
								AND b.ptypeid=p.typeid
								AND bil.btypeid=bt.typeid
								AND b.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
								AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
								AND 
									(
										(b.billtype=140 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
									  	(b.billtype=141 AND b.ktypeid=''10000'' )    OR
										(b.billtype=142 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
										(b.billtype=143 AND b.ktypeid=''10000'')
									)'

								--AND ( bil.KtypeID Like '+char(39)+@MKTypeID+'%'+char(39)+' or Bil.ktypeid='+char(39)+'10000'+char(39)+' )'
								
								SELECT @SQL=@SQL+' AND bil.billtype in (140,141,142,143)'
								--SELECT @SQL=@SQL+'AND b.ktypeid='+char(39)+'10000'+char(39)+'
								SELECT @SQL=@SQL + ' 
								AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
								AND b.ptypeid like '+char(39)+@ptypeId+'%'+char(39)+'
								AND (bil.BtypeID like '+char(39)+@MBtypeId+'%'+char(39)+' OR bil.BtypeID like '+char(39)+@MBtypeId2+'%'+char(39)+')'
						IF @bTypeID<>'00000'
							SELECT @SQL = @SQL+'AND bil.BtypeID like '+char(39)+@bTypeId+'%'+char(39)
						SELECT @SQL=@SQL+'GROUP BY  
									bil.billdate,
									bil.billcode,
									p.fullname,
									bt.fullname,
									bil.billtype,
									bil.billnumberid,
									bil.checke,
									e.fullname,
									bt.usercode,									
									p.usercode,
									p.standard,
									p.type,
									p.entrycode,
									p.unit1,
									bil.totalmoney,
									bil.comment,
									bil.tax,
									bil.ktypeid,
									--b.qty,
									bil.etypeid,
									b.price'	
						--=======================================构造排序字段
						SELECT @SortSQL=@SortSQL+' Order By '

						IF @sortFild='BillDate'   SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='BillCode'   SELECT @SortSQL=@SortSQL+' bil.BillCode '
						IF @sortFild='EtypeID'    SELECT @SortSQL=@SortSQL+' bil.EtypeID '
						IF @sortFild='PUserCode'  SELECT @SortSQL=@SortSQL+' p.usercode '
						IF @sortFild='PFullName'  SELECT @SortSQL=@SortSQL+' p.fullname '
						IF @sortFild='Qty'  	  SELECT @SortSQL=@SortSQL+' b.Qty '
						IF @sortFild='Checke'     SELECT @SortSQL=@SortSQL+' bil.Checke '
						IF @sortFild='BillType'   SELECT @SortSQL=@SortSQL+' bil.BillType '
						IF @sortFild='KtypeID'    SELECT @SortSQL=@SortSQL+' bil.KtypeID '
						IF @sortFild='UserCode'   SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='CostTotal'   SELECT @SortSQL=@SortSQL+' b.CostTotal '
						

						
			END
		END
                           --===============================================委托结算代销
		IF @mType='WJ'
		BEGIN
                    --==============================委托结算代销树型表
			IF @ifLine='0'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID	
				SELECT @SQL='
						SELECT  p.usercode,p.fullname,p.sonnum,p.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.costprice,0)) as costprice,sum(isnull(a.costtotal,0)) as costtotal	
						FROM Ptype p
							LEFT JOIN
								('
								IF @Jtype=1	
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(-a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(-a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
											 		BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  	   		    			   AND bil.BillType in (140,142) '+'	
														AND 
															(
																(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
															  	(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
															)'											
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1

															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										



												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END
								IF @Jtype=2
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid

												FROM    InOutStockTable a,
						 							BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid										
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  			             		   AND bil.billtype=''141''
													   AND bil.KtypeId=''10000'''		
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1

															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
													   						  			
												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)																		


												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END
								IF @Jtype=3
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull( case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end,0) as qty,isnull(a.costprice,0) as costprice,isnull(case a.billtype when ''140'' then -a.costtotal when ''142'' then -a.costtotal else a.costtotal end ,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
											 		BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
													   AND bil.BillType in (140,141,142) '	+'
													   AND 
														(
															(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
														  	(a.billtype=141 AND a.ktypeid=''10000'' )    OR
															(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
															(a.billtype=143 AND a.ktypeid=''10000'')
														)'												
																	
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										



												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END										
 						SELECT @SQL=@SQL+')a
						ON   p.typeid=left(a.ptypeid,len(p.typeid))
						WHERE p.typeid<>'+char(39)+'00000'+char(39)
				IF @pTypeId='00000'
					SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@pTypeId+char(39)+' AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
				IF @pTypeId<>'00000' AND @isSon=1
					SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@pTypeId+char(39)+' AND p.typeId<>'+char(39)+@pTypeId+char(39)+' AND p.deleted=0'			
				IF @pTypeId<>'00000' AND @isSon=0
					SELECT @SQL=@SQL+' AND p.typeid ='+char(39)+@pTypeId+char(39)+' AND p.deleted=0'	
				SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'

				SELECT @SortSQL=@SortSQL+' Order By p.UserCode'	
			END
                                       --===============================委托结算代销线型表
			IF @ifLine='1'
			BEGIN

				SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID
				SELECT @SQL='
						SELECT  p.usercode,p.fullname,p.sonnum,p.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.costprice,0)) as costprice,sum(isnull(a.costtotal,0)) as costtotal	
						FROM Ptype p
							LEFT JOIN
								('
								IF @Jtype=1	
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(-a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(-a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
											 		BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid				
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  	   		    			AND bil.BillType in (140,141,142,143) AND a.KtypeId<>''10000'''	

													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										

												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')
															  AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END
								IF @Jtype=2
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
						 							BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid	
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  			               AND bil.billtype=141' +'
													   AND 
														(
														  	(a.billtype=141 AND a.ktypeid=''10000'' ) 
					
														)'		
			
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
				  			
												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)																		

												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END
								IF @Jtype=3
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end,0) as qty,isnull(a.costprice,0) as costprice,isnull(case a.billtype when ''140'' then -a.costtotal when ''142'' then -a.costtotal else a.costtotal end ,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
											 		BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid				
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  	   		    			AND bil.BillType in (140,141,142) '	+ '
														AND 
														(
															(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
														  	(a.billtype=141 AND a.ktypeid=''10000'' )    OR
															(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
															(a.billtype=143 AND a.ktypeid=''10000'')
														)'	
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										

												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END	
 						SELECT @SQL=@SQL+')a
						ON   p.typeid=a.ptypeid
						WHERE p.typeid<>'+char(39)+'00000'+char(39)
				IF @pTypeId='00000'
					SELECT @SQL=@SQL+' AND  p.sonnum=0 AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 							
				IF @pTypeId<>'00000' AND @isSon=1
					SELECT @SQL=@SQL+' AND p.typeid like '+char(39)+@pTypeId+'%'+char(39)+' AND p.typeId<>'+char(39)+@pTypeId+char(39)+' AND p.deleted=0 AND p.sonnum=0'			
				IF @pTypeId<>'00000' AND @isSon=0
					SELECT @SQL=@SQL+' AND p.typeid ='+char(39)+@pTypeId+char(39)+' AND p.deleted=0'	
				IF @showZero=0 
					SELECT @SQL=@SQL+' AND qty<>0'
				SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'
				--print @SQL
				SELECT @SortSQL = ''
	
				-- 全部发货，已结算，未结算的排序字段一样
				IF @sortFild ='Qty'
					SET @SortSQL = ' ORDER By Qty '
				IF @sortFild ='CostTotal'
					SET @SortSQL = ' ORDER By CostTotal  '
				
				IF @SortSQL =''
				SELECT @SortSQL=@SortSQL+' Order By p.UserCode'	

			END
                                        --==============================委托结算代销明细表
			IF @ifLine='2'
			BEGIN
				SELECT @SQL='
						  SELECT 	bil.billdate,
								bil.billcode,
								p.usercode as pusercode,
								p.fullname as pfullname,
								p.standard,
								p.type,
								p.entrycode,
								p.unit1,
								bt.usercode as busercode,
								bt.fullname as bfullname,
								isnull(sum(case b.billtype when ''140'' then -b.qty when ''142'' then -b.qty else b.qty end),0) as qty,
								isnull(sum(b.costprice),0) as costprice,
								isnull(sum(case b.billtype when ''140'' then -b.costtotal when ''142'' then -b.costtotal else b.costtotal end ),0) as costtotal,
								bil.billtype,
								bil.billnumberid,
								sum(isnull(b.price,0)) as price,
								sum(isnull(case b.billtype when ''140'' then -b.total when ''142'' then -b.total else b.total end ,0)) as total,
								bil.checke,
								e.fullname as efullname,					
								bil.totalmoney,			
								bil.comment,
								bil.tax,
								bil.ktypeid,
								bil.etypeid 
						  FROM          InOutStockTable b,
								billindex bil,
								ptype p,
								btype bt,
								employee e																								
						  WHERE         bil.billnumberid=b.billnumberid
								AND bil.etypeId=e.TypeID						 				
							        AND bil.draft=0
							        AND bil.RedWord=0
  							        AND bil.ifcheck=''t''
								AND b.ptypeid=p.typeid
								AND bil.btypeid=bt.typeid								
								AND b.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
								AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+''
								--AND ( bil.KtypeID Like '+char(39)+@MKTypeID+'%'+char(39)+' )'
								IF @Jtype=1
									SELECT @SQL=@SQL+' AND bil.Billtype in (140,142) ' +'
									AND
									(
										(b.billtype=140 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
									  	(b.billtype=142 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
									)'	


								IF @Jtype=2
									SELECT @SQL=@SQL+' AND bil.ktypeid='+char(39)+'10000'+char(39)+' AND bil.billtype=''141'''								
								IF @Jtype=3
									SELECT @SQL=@SQL+' AND bil.billtype in (140,141,142,143)' +'
									AND
									(
										(b.billtype=140 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
									  	(b.billtype=141 AND b.ktypeid=''10000'' )    OR
										(b.billtype=142 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
										(b.billtype=143 AND b.ktypeid=''10000'')
									)'	

									-- 委托代销未结算查询增加 调价单  2004-08-24 chen_qihua
									-- SELECT @SQL=@SQL+' AND bil.billtype in (140,141,142)'
								SELECT @SQL=@SQL+'
								AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
								AND b.ptypeid like '+char(39)+@ptypeId+'%'+char(39)+'	
								AND (bil.BtypeID like '+char(39)+@MBtypeId+'%'+char(39)+' OR bil.BtypeID like '+char(39)+@MBtypeId2+'%'+char(39)+')'
						IF @bTypeID<>'00000'
							SELECT @SQL = @SQL+'AND bil.BtypeID like '+char(39)+@bTypeId+'%'+char(39)
						
						SELECT @SQL=@SQL+'GROUP BY  
									bil.billdate,
									bil.billcode,
									p.fullname,
									bt.fullname,
									bil.billtype,
									bil.billnumberid,
									bil.checke,
									e.fullname,
									bt.usercode,															
									p.usercode,
									p.standard,
									p.type,
									p.entrycode,
									p.unit1,
									bil.totalmoney,
									bil.comment,
									bil.tax,
									bil.ktypeid,
									bil.etypeid,
									b.qty'	
									-- chen_qihua 加  group by qty  2004-08-24

						--=======================================构造排序字段
						SELECT @SortSQL=''		
						SELECT @SortSQL=@SortSQL+' Order By '
						IF @sortFild='BillDate'   SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='BillCode'   SELECT @SortSQL=@SortSQL+' bil.BillCode '
						IF @sortFild='EtypeID'    SELECT @SortSQL=@SortSQL+' bil.EtypeID '
						IF @sortFild='PUserCode'  SELECT @SortSQL=@SortSQL+' p.usercode '
						IF @sortFild='PFullName'  SELECT @SortSQL=@SortSQL+' p.fullname '
						IF @sortFild='Qty'  	  SELECT @SortSQL=@SortSQL+' b.Qty '
						IF @sortFild='Checke'     SELECT @SortSQL=@SortSQL+' bil.Checke '
						IF @sortFild='BillType'   SELECT @SortSQL=@SortSQL+' bil.BillType '
						IF @sortFild='KtypeID'    SELECT @SortSQL=@SortSQL+' bil.KtypeID '
						IF @sortFild='UserCode'   SELECT @SortSQL=@SortSQL+' bil.billdate '		
						IF @sortFild='CostTotal'   SELECT @SortSQL=@SortSQL+' b.CostTotal '	
			END
		END

	END 
--=============================================================================================受托代销
	IF @qType='S'
	BEGIN
                           --================================================受托客户代销
		IF @mType='SB'
		BEGIN
                                        --==============================受托客户代销树型表
			IF @ifLine='0'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID	
				SELECT @SQL='
						SELECT  b.usercode,b.fullname,b.sonnum,b.typeid,a.type as billtype,sum(isnull(a.qty,0)) as qty,sum(isnull(a.total,0)) as total,sum(isnull(a.costtotal,0)) as costtotal	
						FROM Btype b
							LEFT JOIN
								(
									SELECT qty,costtotal,total,ptypeid,btypeid,type
									FROM  commissionstock
									WHERE     Type in (144,145,146)	
										      '		--#-01 Modify by tq  
									IF @pTypeID='00000'
										SELECT @SQL=@SQL+' AND pTypeID Like '+char(39)+@MPTypeID+'%'+char(39)
									Else	
										IF @CurSonNum>=1 
											SELECT @SQL=@SQL+' AND PtypeId  Like '+char(39)+@pTypeID+'%'+char(39)
										Else
											SELECT @SQL=@SQL+' AND PtypeId  = '+char(39)+@pTypeID+char(39)



								SELECT @SQL=@SQL+' AND ( bTypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bTypeID Like '+char(39)+@MBTypeID2+'%'+char(39)+')'

				SELECT @SQL=@SQL+'	)a

						ON   b.typeid=left(a.btypeid,len(b.typeid))'
 				IF @bTypeId='00000' 
					IF @BtypeAll=1
						SELECT @SQL=@SQL+' WHERE  b.deleted=0 AND (b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+') AND (b.parid = '+char(39)+'00001'+char(39)+' Or b.parid like '+char(39)+'00002'+char(39)+')'
					Else	
						SELECT @SQL=@SQL+' WHERE  b.deleted=0 AND (b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+') AND b.parid = '+char(39)+'00002'+char(39)
				IF @bTypeId='00001'
					SELECT @SQL=@SQL+' WHERE b.parid = '+char(39)+'00001'+char(39)+' and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')' 					
				IF @bTypeId='00002'
					SELECT @SQL=@SQL+' WHERE b.parid = '+char(39)+'00002'+char(39)+' and  ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')' 					
				IF @bTypeId<>'00000' AND @bTypeId<>'00001' AND @bTypeId<>'00002' AND @isSon=1
					SELECT @SQL=@SQL+' WHERE b.parid ='+char(39)+@bTypeId+char(39)+' AND b.typeid<>'+char(39)+@bTypeId+char(39)+' and  ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')' 					
				IF @bTypeId<>'00000' AND @bTypeId<>'00001' AND @bTypeId<>'00002' AND @isSon=0
					SELECT @SQL=@SQL+' WHERE b.typeid = '+char(39)+@bTypeId+char(39)+' and  ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')' 					

				SELECT @SQL=@SQL+' GROUP BY b.usercode,b.fullname,b.sonnum,b.typeid,a.type'

				SELECT @SortSQL=@SortSQL+' Order By b.UserCode'
			END
                                        --==============================受托客户代销线型表
			IF @ifLine='1'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID	
				SELECT @SQL='
						SELECT  b.usercode,b.fullname,b.sonnum,b.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.total,0)) as total,sum(isnull(a.costtotal,0)) as costtotal	
						FROM Btype b
							LEFT JOIN
								(
									SELECT qty,costtotal,total,ptypeid,btypeid
									FROM  commissionstock
									WHERE     Type in (144,145,146)	
										     '
									IF @pTypeID='00000'
										SELECT @SQL=@SQL+' AND PtypeId Like '+char(39)+'%'+char(39)
									Else	
										IF @CurSonNum>=1 
											SELECT @SQL=@SQL+' AND PtypeId  Like '+char(39)+@pTypeID+'%'+char(39)
										Else
											SELECT @SQL=@SQL+' AND PtypeId  = '+char(39)+@pTypeID+char(39)

								SELECT @SQL=@SQL+' AND pTypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
											  AND ( bTypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bTypeID Like '+char(39)+@MBTypeID2+'%'+char(39)+')'

				SELECT @SQL=@SQL+'	)a
						ON   b.typeid=a.btypeid'
 				IF @bTypeId='00000' 
					IF @BtypeAll=1 
						SELECT @SQL=@SQL+' WHERE b.sonnum=0 AND  b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')'--+' AND (b.parid = '+char(39)+'00001'+char(39)+' Or b.parid = '+char(39)+'00002'+char(39)+')'					
					ELSE
						SELECT @SQL=@SQL+' WHERE b.sonnum=0 AND  b.deleted=0 and ( b.typeid like '+char(39)+@MBtypeid+'%'+char(39)+' or b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+')'--+' AND b.parid = '+char(39)+'00001'+char(39)
				IF @bTypeId='00001'
					SELECT @SQL=@SQL+' WHERE b.parid like '+char(39)+'00001%'+char(39)+' AND b.sonnum=0 AND b.deleted=0'
				IF @bTypeId='00002'
					SELECT @SQL=@SQL+' WHERE b.parid like '+char(39)+'00002%'+char(39)+' AND b.sonnum=0 AND b.deleted=0'
				IF @bTypeId<>'00000' AND @bTypeId<>'00001' AND @bTypeId<>'00002' AND @isSon=1
					SELECT @SQL=@SQL+' WHERE b.typeid like '+char(39)+@bTypeId+'%'+char(39)+' AND b.typeid<>'+char(39)+@bTypeId+char(39)+' AND b.deleted=0 AND b.sonnum=0'
				IF @bTypeId<>'00000' AND @bTypeId<>'00001' AND @bTypeId<>'00002' AND @isSon=0

					SELECT @SQL=@SQL+' WHERE b.typeid = '+char(39)+@bTypeId+char(39)+'  AND b.deleted=0'
				IF @showZero=0 
					SELECT @SQL=@SQL+' AND qty<>0'
				SET @SQL=@SQL+' AND (b.typeid like '+char(39)+@MBtypeid+'%'+char(39) +' OR b.typeid like '+char(39)+@MBtypeid2+'%'+char(39)+') '
				SELECT @SQL=@SQL+' GROUP BY b.usercode,b.fullname,b.sonnum,b.typeid'
				
				IF @sortFild ='qty'
						SELECT @SortSQL=@SortSQL+' Order By Qty '					
				IF @sortFild ='CostTotal'
					SELECT @SortSQL=@SortSQL+' Order By Total '	
				IF @SortSQL =''
					SELECT @SortSQL=@SortSQL+' Order By b.UserCode'

			END
                                        --==============================受托客户代销明细表
			IF @ifLine='2'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID	
				SELECT @SQL='
						SELECT 	bil.btypeid,
								bil.billnumberid,
								bil.billdate,
								sum(isnull(b.total,0)) as total,
								sum(isnull(b.qty,0)) as qty,
								b.price,
								bil.ktypeid,
								bil.billcode,
								bil.comment,
								bil.billtype
						FROM    BillIndex  bil,InOutStockTable b		
						WHERE 	bil.billnumberid=b.billnumberid
								AND bil.draft=0
								AND bil.RedWord=0
  							        AND bil.ifcheck=''t''
								AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
								AND bil.billtype in (144,145,146,147)
								AND b.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
								AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
								AND ( bil.KtypeID Like '+char(39)+@MKTypeID+'%'+char(39)+' or bil.ktypeid ='+char(39)+'10000'+char(39)+')'
								IF @pTypeID='00000'
									SELECT @SQL=@SQL+' AND b.PtypeId Like '+char(39)+'%'+char(39)
								Else	
									IF @CurSonNum>=1 
										SELECT @SQL=@SQL+' AND b.PtypeId  Like '+char(39)+@pTypeID+'%'+char(39)
									Else
										SELECT @SQL=@SQL+' AND b.PtypeId  = '+char(39)+@pTypeID+char(39)

	
						IF @bTypeId='00000'								
								SELECT @SQL=@SQL+'  AND (b.btypeid like '+char(39)+'00001'+'%'+char(39)+' Or b.btypeid like '+char(39)+'00002'+'%'+char(39)+')'
						IF @bTypeId='00001'
								SELECT @SQL=@SQL+'  AND b.btypeid like '+char(39)+'00001'+'%'+char(39)
						IF @bTypeId='00002'
								SELECT @SQL=@SQL+'  AND b.btypeid like '+char(39)+'00002'+'%'+char(39)
						IF @bTypeId<>'00001' AND @bTypeId<>'00002' AND @bTypeId<>'00000'
								SELECT @SQL=@SQL+'  AND b.btypeid like  '+char(39)+@bTypeId+'%'+char(39)
						SELECT @SQL=@SQL+' Group By bil.btypeid,bil.billnumberid,bil.billdate,bil.ktypeid,bil.billcode,bil.comment,b.price,bil.billtype'
				
						--SELECT @SortSQL=@SortSQL+' Order By bil.billdate'
						--=======================================构造排序字段
						SELECT @SortSQL=''
						SELECT @SortSQL=@SortSQL+' Order By '
						IF @sortFild='BillDate'   SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='BillCode'   SELECT @SortSQL=@SortSQL+' bil.BillCode '
						IF @sortFild='EtypeID'    SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='PUserCode'  SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='PFullName'  SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='Qty'  	  SELECT @SortSQL=@SortSQL+' b.Qty '
						IF @sortFild='Checke'     SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='BillType'   SELECT @SortSQL=@SortSQL+' bil.BillType '
						IF @sortFild='KtypeID'    SELECT @SortSQL=@SortSQL+' bil.KtypeID '
						IF @sortFild='UserCode'   SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='CostTotal'   SELECT @SortSQL=@SortSQL+' b.Total '
			END
		END
                           --==================================================受托仓库代销
		IF @mType='SK'
		BEGIN
                                        --==============================受托仓库代销树型表
			IF @ifLine='0'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID
				SELECT @SQL='
						SELECT  p.typeid,p.usercode,p.fullname,p.sonnum,b.type as billtype,sum(isnull(b.qty,0)) as qty,sum(isnull(b.price,0)) as price,sum(isnull(b.total,0)) as total,sum(isnull(b.costprice,0)) as costprice,sum(isnull(b.costtotal,0)) as costtotal 
						FROM ptype p
							LEFT JOIN
							(
								SELECT	qty,
										ptypeid,
										total,
										costtotal,
										price=case when qty <> 0 then (total/qty) else 0 end,
										costprice=case when qty <> 0 then (costtotal/qty) else 0 end,
										type					
								FROM 	commissionstock
								WHERE   type in (144,145,146)

									   AND qty>=0'
								IF @bTypeID='00000'				               
									SELECT @SQL=@SQL+' AND bTypeID Like '+char(39)+'%'+char(39)
								Else
									IF @CurSonNum>=1 
										SELECT @SQL=@SQL+' AND bTypeID Like '+char(39)+@bTypeID+'%'+char(39)
									ELSE									
										SELECT @SQL=@SQL+' AND bTypeID = '+char(39)+@bTypeID+char(39)

								SELECT @SQL=@SQL+' AND pTypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
											  AND ( bTypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bTypeID Like '+char(39)+@MBTypeID2+'%'+char(39)+')'

				SELECT @SQL=@SQL+')b		               
						ON p.typeid=left(b.ptypeid,len(p.typeid))
						WHERE p.typeid<>'+char(39)+'00000'+char(39)
				IF @PTypeId='00000'
					SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@PTypeId+char(39)+' AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
				IF @PTypeId<>'00000' AND @isSon=1
					SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@PTypeId+char(39)+' AND p.typeId<>'+char(39)+@PTypeId+char(39)+' AND p.deleted=0'		
				IF @PTypeId<>'00000' AND @isSon=0
					SELECT @SQL=@SQL+' AND p.typeid ='+char(39)+@PTypeId+char(39)+' AND p.deleted=0'
				SELECT @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.fullname,p.sonnum,b.type'

				SELECT @SortSQL=@SortSQL+' Order By p.UserCode'	

			END
                                        --==============================受托仓库代销线型表
			IF @ifLine='1'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID
				SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
				SELECT @SQL='
						SELECT  p.typeid,p.usercode,p.fullname,p.sonnum,sum(isnull(b.qty,0)) as qty,sum(isnull(b.price,0)) as price,sum(isnull(b.total,0)) as total,sum(isnull(b.costprice,0)) as costprice,sum(isnull(b.costtotal,0)) as costtotal 
						FROM ptype p
							LEFT JOIN
							(
								SELECT	qty,
										ptypeid,
										total,
										costtotal,
										price=case when qty <> 0 then (total/qty) else 0 end,
										costprice=case when qty <> 0 then (costtotal/qty) else 0 end
								FROM 	commissionstock
								WHERE   type in (144,145,146)
									   AND qty>=0'					               
								IF @bTypeID='00000'				               
									SELECT @SQL=@SQL+' AND bTypeID Like '+char(39)+'%'+char(39)
								Else
									IF @CurSonNum>=1 
										SELECT @SQL=@SQL+' AND bTypeID Like '+char(39)+@bTypeID+'%'+char(39)
									ELSE									
										SELECT @SQL=@SQL+' AND bTypeID = '+char(39)+@bTypeID+char(39)

								SELECT @SQL=@SQL+' AND pTypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
											  AND ( bTypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bTypeID Like '+char(39)+@MBTypeID2+'%'+char(39)+')'

				SELECT @SQL=@SQL+')b		               
						ON p.typeid=b.ptypeid
						WHERE p.typeid<>'+char(39)+'00000'+char(39)
				IF @kTypeId='00000'
					SELECT @SQL=@SQL+'  AND p.sonnum=0 AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
				IF @kTypeId<>'00000' AND @CurPSonNum>=1
					SELECT @SQL=@SQL+' AND p.typeid like '+char(39)+@kTypeId+'%'+char(39)+' AND p.deleted=0 AND p.sonnum=0'
				Else	
					IF @kTypeID<>'00000' AND @CurPSonNum=0
						SELECT @SQL=@SQL+' AND p.typeid =  '+char(39)+@kTypeId+char(39)+' AND p.deleted=0'
				IF @showZero=0 
					SELECT @SQL=@SQL+' AND qty<>0'
				SELECT @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.fullname,p.sonnum'

				IF @sortFild ='qty'
						SELECT @SortSQL=@SortSQL+' Order By Qty '					
				IF @sortFild ='CostTotal'
					SELECT @SortSQL=@SortSQL+' Order By Total '	
				IF @SortSQL =''
					SELECT @SortSQL=@SortSQL+' Order By p.UserCode'					
			END
                                        --==============================受托仓库代销明细表
			IF @ifLine='2'
			BEGIN
				SELECT @SQL='
						  SELECT 	bil.billdate,
								bil.billcode,
								p.usercode as pusercode,
								p.fullname as pfullname,
								p.standard,
								p.type,
								p.entrycode,
								p.unit1,
								bt.usercode as busercode,
								bt.fullname as bfullname,
								sum(isnull(b.qty,0)) as qty,
								b.price,
								sum(isnull(b.costprice,0)) as costprice,
								sum(isnull(b.costtotal,0)) as costtotal,
								bil.billtype,
								bil.billnumberid,
								--sum(isnull(b.price,0)) as price,
								sum(isnull(b.total,0)) as total,
								bil.checke,
								e.fullname as efullname,
								bil.totalmoney,
								bil.comment,
								bil.tax,
								bil.ktypeid,

								bil.etypeid 
						  FROM          InOutStockTable b,
								billindex bil,
								ptype p,
								btype bt,
								employee e						
						  WHERE         bil.billnumberid=b.billnumberid
								AND bil.etypeId=e.TypeID								
							        AND bil.draft=0
							        AND bil.RedWord=0
  							        AND bil.ifcheck=''t''
								AND b.ptypeid=p.typeid
								AND bil.btypeid=bt.typeid
								AND b.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'								
								AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
								AND ( bil.KtypeID Like '+char(39)+@MKTypeID+'%'+char(39)+' or bil.ktypeid='+char(39)+'10000'+char(39)+' )'

								SELECT @SQL=@SQL+' AND bil.billtype in (144,145,146,147)'
								SELECT @SQL=@SQL+'AND b.ktypeid='+char(39)+'10000'+char(39)+'
								AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
								AND b.ptypeid like '+char(39)+@ptypeId+'%'+char(39)+'
								AND (bil.BtypeID like '+char(39)+@MBtypeId+'%'+char(39)+' OR bil.BtypeID like '+char(39)+@MBtypeId2+'%'+char(39)+')'
						IF @bTypeID<>'00000'
							SELECT @SQL = @SQL+'AND bil.BtypeID like '+char(39)+@bTypeId+'%'+char(39)
						
						SELECT @SQL=@SQL+' GROUP BY  
									bil.billdate,
									bil.billcode,
									p.fullname,
									bt.fullname,
									bil.billtype,
									bil.billnumberid,
									bil.checke,
									e.fullname,
									bt.usercode,									
									p.usercode,
									p.standard,
									p.type,
									p.entrycode,
									p.unit1,
									bil.totalmoney,
									bil.comment,
									bil.tax,
									--b.qty,
									b.price,
									bil.ktypeid,
									bil.etypeid'
						--=======================================构造排序字段
						SELECT @SortSQL=''
						SELECT @SortSQL=@SortSQL+' Order By '
						IF @sortFild='BillDate'   SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='BillCode'   SELECT @SortSQL=@SortSQL+' bil.BillCode '
						IF @sortFild='EtypeID'    SELECT @SortSQL=@SortSQL+' bil.EtypeID '
						IF @sortFild='PUserCode'  SELECT @SortSQL=@SortSQL+' p.usercode '
						IF @sortFild='PFullName'  SELECT @SortSQL=@SortSQL+' p.fullname '
						IF @sortFild='Qty'  	  SELECT @SortSQL=@SortSQL+' b.Qty '
						IF @sortFild='Checke'     SELECT @SortSQL=@SortSQL+' bil.Checke '
						IF @sortFild='BillType'   SELECT @SortSQL=@SortSQL+' bil.BillType '
						IF @sortFild='KtypeID'    SELECT @SortSQL=@SortSQL+' bil.KtypeID '
						IF @sortFild='UserCode'   SELECT @SortSQL=@SortSQL+' bil.billdate '							
						IF @sortFild='CostTotal'   SELECT @SortSQL=@SortSQL+' b.CostTotal '
			END
		END
                          --===================================================受托结算代销
		IF @mType='SJ'
		BEGIN
                                        --==============================树型表
			BEGIN
				SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID	
				SELECT @SQL='
						SELECT  p.usercode,p.fullname,p.sonnum,p.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.costprice,0)) as costprice,sum(isnull(a.costtotal,0)) as costtotal
						FROM Ptype p
							LEFT JOIN
								('

								IF @Jtype=1	
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
											 		BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid		
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  	   		    			AND bil.BillType in (144,146) AND a.KtypeId<>''10000'''	
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										
												
												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')
															  AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)
								END
								IF @Jtype=2
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
						 							BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid	
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
								  			             		   AND bil.KtypeId=''10000''
													   AND bil.billtype=''145'''			
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
					  			
												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)																		

												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END
								IF @Jtype=3
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
											 		BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid		
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  	   		    			AND bil.BillType in (144,145,146) AND a.KtypeId=''10000'''	
							  	   		
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										
												
												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)
								END	
						SELECT @SQL=@SQL+')a
						ON   p.typeid=left(a.ptypeid,len(p.typeid))
						WHERE p.typeid<>'+char(39)+'00000'+char(39)
				IF @pTypeId='00000'
					SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@pTypeId+char(39)+' AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
				IF @pTypeId<>'00000' AND @isSon=1
					SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@pTypeId+char(39)+' AND p.typeId<>'+char(39)+@pTypeId+char(39)+' AND p.deleted=0 '		
				IF @pTypeId<>'00000' AND @isSon=0
					SELECT @SQL=@SQL+' AND p.typeid ='+char(39)+@pTypeId+char(39)+' AND p.deleted=0'
				
					SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'		
		
					SELECT @SortSQL=@SortSQL+' Order By p.UserCode'
				
			END
                                       --===============================线型表
			IF @ifLine='1'
			BEGIN
				SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID	
				SELECT @SQL='
						SELECT  p.usercode,p.fullname,p.sonnum,p.typeid,abs(sum(isnull(a.qty,0))) as qty,sum(isnull(a.costprice,0)) as costprice,abs(sum(isnull(a.costtotal,0))) as costtotal	
						FROM Ptype p
							LEFT JOIN
								('
								IF @Jtype=1	
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
											 		BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  	   		    			AND bil.BillType in (144,145,146) AND a.KtypeId<>''10000'''	
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										

												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')
															  AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)



								END
								IF @Jtype=2
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
						 							BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid	
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
													AND bil.BillType=145' +'
													 AND 
														(
															(a.billtype=145 AND a.ktypeid=''10000'' )    
															
														)'
														
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
						  			
												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)																		


												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END
								IF @Jtype=3
								BEGIN
									SELECT @SQL=@SQL+'
												SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
												FROM    InOutStockTable a,
											 		BillIndex bil
												WHERE   a.billnumberid=bil.billnumberid
													   AND bil.draft=0
													   AND bil.RedWord=0
						  							   AND bil.ifcheck=''t''
							  	   		    			AND bil.BillType in (144,145,146) '	 +'
						 								AND 
															(
																(a.billtype=144 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
															  	(a.billtype=145 AND a.ktypeid=''10000'' )    OR
																(a.billtype=146 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
															)'
													SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
													IF @pTypeID='00000'
														SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurPSonNum>=1
															SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
														Else

															SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
													IF @bTypeID='00000'
														SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
													ELSE
														IF @CurSonNum>=1
															SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
														Else
															SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

												SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										

												SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
															  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
															  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
															 -- AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

								END	
											
						SELECT @SQL=@SQL+')a
						ON   p.typeid=a.ptypeid
						WHERE p.typeid<>'+char(39)+'00000'+char(39)
				IF @pTypeId='00000'
					SELECT @SQL=@SQL+' AND  p.sonnum=0 AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
				IF @pTypeId<>'00000' AND @isSon=0
					SELECT @SQL=@SQL+' AND  p.typeId='+char(39)+@pTypeId+char(39)+' AND p.deleted=0'		
				IF @pTypeId<>'00000' AND @isSon=1
					SELECT @SQL=@SQL+' AND p.typeid like '+char(39)+@pTypeId+'%'+char(39)+' AND p.deleted=0 AND p.sonnum=0'
				IF @showZero=0 
					SELECT @SQL=@SQL+' AND qty<>0'
				SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'

				SELECT @SortSQL=''
				IF @sortFild ='qty'
					SELECT @SortSQL =' ORDER BY TT.qty '
				IF @sortFild='CostTotal'
					SELECT @SortSQL =' ORDER BY TT.CostTotal '
				IF @SortSQL=''
					SELECT @SortSQL=@SortSQL+' Order By TT.UserCode'
				--@sortFild varchar(20),		--排序字段


			END
                                        --==============================明细表
			IF @ifLine='2'
			BEGIN			
				SELECT @SQL='
						  
						  SELECT 	bil.billdate,
								bil.billcode,
								p.usercode as pusercode,
								p.fullname as pfullname,
								p.standard,
								p.type,
								p.entrycode,

								p.unit1,
								bt.usercode as busercode,
								bt.fullname as bfullname,
								sum(isnull(b.qty,0)) as qty,
								sum(isnull(b.costprice,0)) as costprice,
								sum(isnull(b.costtotal,0)) as costtotal,
								bil.billtype,
								bil.billnumberid,
								sum(isnull(b.price,0)) as price,
								sum(isnull(b.total,0)) as total,
								bil.checke,
								e.fullname as efullname,
								bil.totalmoney,
								bil.comment,
								bil.tax,
								bil.ktypeid,
								bil.etypeid 
						  FROM          InOutStockTable b,
								billindex bil,
								ptype p,
								btype bt,
								employee e
						  WHERE         bil.billnumberid=b.billnumberid
								AND bil.etypeId=e.TypeID
							        AND bil.draft=0
							        AND bil.RedWord=0
  							        AND bil.ifcheck=''t''
								AND b.ptypeid=p.typeid
								AND bil.btypeid=bt.typeid	
								AND b.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
								AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+''
								--AND ( bil.KtypeID Like '+char(39)+@MKTypeID+'%'+char(39)+' )'

								IF @Jtype=1
									SELECT @SQL=@SQL+' AND bil.Billtype in (144,146) '+'
									 AND 
										(
											(b.billtype=144 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
											(b.billtype=146 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
										)'
								IF @Jtype=2
									SELECT @SQL=@SQL+' AND bil.ktypeid='+char(39)+'10000'+char(39)+' AND bil.billtype=''145'''								
								IF @Jtype=3
									SELECT @SQL=@SQL+' AND bil.billtype in (144,145,146,147)'+
								    ' AND 
									(
										(b.billtype=144 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
									  	(b.billtype=145 AND b.ktypeid=''10000'' )    OR
										(b.billtype=146 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
										(b.billtype=147 AND b.ktypeid=''10000'')
									)'
									
									-- 受托代销查询增加调价单  2004-08-24  chen_qihua
									-- SELECT @SQL=@SQL+' AND bil.billtype in (144,145,146)'
								SELECT @SQL=@SQL+'
										AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
										AND b.ptypeid like '+char(39)+@ptypeId+'%'+char(39)+'	
										AND (bil.BtypeID like '+char(39)+@MBtypeId+'%'+char(39)+' OR bil.BtypeID like '+char(39)+@MBtypeId2+'%'+char(39)+')'
								IF @bTypeID<>'00000'
									SELECT @SQL = @SQL+'AND bil.BtypeID like '+char(39)+@bTypeId+'%'+char(39)
						

								SELECT @SQL=@SQL+' GROUP BY  
											bil.billdate,
											bil.billcode,
											p.fullname,
											bt.fullname,
											bil.billtype,
											bil.billnumberid,
											bil.checke,
											e.fullname,
											bt.usercode,																										
											p.usercode,
											p.standard,
											p.type,
											p.entrycode,
											p.unit1,
											bil.totalmoney,
											bil.comment,
											bil.tax,
											bil.ktypeid,		
											bil.etypeid,
											b.qty'	
											-- chen_qihua 加  group by qty  2004-08-24
						--=======================================构造排序字段
						SELECT @SortSQL=''
						SELECT @SortSQL=@SortSQL+' Order By '
						IF @sortFild='BillDate'   SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='BillCode'   SELECT @SortSQL=@SortSQL+' bil.BillCode '
						IF @sortFild='EtypeID'    SELECT @SortSQL=@SortSQL+' bil.EtypeID '
						IF @sortFild='PUserCode'  SELECT @SortSQL=@SortSQL+' p.usercode '
						IF @sortFild='PFullName'  SELECT @SortSQL=@SortSQL+' p.fullname '
						IF @sortFild='Qty'  	  SELECT @SortSQL=@SortSQL+' b.Qty '
						IF @sortFild='Checke'     SELECT @SortSQL=@SortSQL+' bil.Checke '
						IF @sortFild='BillType'   SELECT @SortSQL=@SortSQL+' bil.BillType '
						IF @sortFild='KtypeID'    SELECT @SortSQL=@SortSQL+' bil.KtypeID '
						IF @sortFild='UserCode'   SELECT @SortSQL=@SortSQL+' bil.billdate '
						IF @sortFild='CostTotal'   SELECT @SortSQL=@SortSQL+' b.CostTotal '
						--PRINT @SQL
			END
		END
	END 


	--======================================================================================排序语句构造
	IF RTRIM(LTRIM(@SortSQL))<>''
	BEGIN	
		IF @mType ='SJ' AND @ifLine='1'
		BEGIN
			IF @sortType=1
				SELECT @SQL='SELECT * FROM ('+@SQL+') TT '+@SortSQL+'  ASC'
			IF @sortType=0
				SELECT @SQL='SELECT * FROM ('+@SQL+') TT '+@SortSQL+'  DESC'
		END
		ELSE IF @mType ='WJ' AND @ifLine='1' AND @Jtype ='2'
		BEGIN
			IF @sortType=1
				SELECT @SQL=@SQL+@SortSQL+'  desc'
			IF @sortType=0
				SELECT @SQL=@SQL+@SortSQL+'  asc'	
		END
		ELSE
		BEGIN
			IF @sortType=1
				SELECT @SQL=@SQL+@SortSQL+'  ASC'
			IF @sortType=0
				SELECT @SQL=@SQL+@SortSQL+'  DESC'	
		END
	END
--=============================================================================================代销语句构造结束

-- PRINT (@SQL)
EXEC (@SQL)

END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SearchCruPtypeSerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SearchCruPtypeSerial]
GO

/*
--=============================
--作者：谢吉康
--日期：2003-03-17
--描述：重写该算法
--卢春 2006-03-09 查询提速
--=============================
 Author:WangWei
 datetime:2010-8-18
 Description:优化
 
 2016-04-18增加序列号库龄，计算规则如下：
	 出库时间有值的：序列号库龄=出库时间-入库时间+1；
	 出库时间无值的：序列号库龄=系统日期（取服务器日期）-入库时间+1；
	 去掉分页数据源
--=============================
--修改：武智均
--日期：2019-09-30
--描述：状态为“库存中、受托代销库存中、维修库存中”时，序列号库龄=系统当前时间-入库时间+1；
--=============================
 */
CREATE                              PROCEDURE [Gp_SearchCruPtypeSerial] 
(
	@OperatorID		varchar(100),	--1.操作员的ID 
	@StartDate  	varchar(20),    --2.开始时间
	@EndDate    	varchar(20),	--3.结束时间
	@pTypeID    	varchar(8000),	--4.商品的ID 
	@dealbTypeID    	varchar(8000),	--5.客户或供货商   00000=客户和供货商统一  00001=客户   00002=供应商
	@kTypeID    	varchar(8000)='',	--6.仓库的ID
	@pSerial    	varchar(1000)='',	--7.序列号
	@pUsercode  	varchar(100),	--8.商品编号
	@pFullname  	varchar(100),	--9.商品名称
	@pState     	varchar(200),	--10.商品状态
	@searchMode 	int,			--11.查询类型   1.精确匹配 0.模糊查找
	@isModal    	int, 			--12.时间的模糊查询   1.是  0.否
	@bTypeID2   	varchar(8000),    --13.查询销售商
	@USER			varchar(200),   --14.终端用户
	@Note			varchar(200),	--15.备注
	@ShowAllUser	int,			--16.显示终端用户
	@radValue		int,			--17.开始日期有效  0.入库日期有效   1.出库日期有效	
	@showIniSerial  int,			--18.是否仅显示期初序列号	1.是   0.否
	@BTypeName		varchar(8000),	--19.客户名称
	@JTypeName		varchar(8000),	--20.供货商
	@tablename		varchar(100),
	@stypeID		VARCHAR(max),	--分支机构
	@comment1		varchar(256),
	@comment2		varchar(256),
	@comment3		varchar(256),
	@itemid			VARCHAR(200),--自由项
	@cargoid		VARCHAR(200),--货位
	@producedate	VARCHAR(20),--生成日期 
	@validdate		VARCHAR(20),--效期至
	@ptypecategoryid	VARCHAR(max)=''
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId
(
	TypeId		varchar(50),
	UserCode 	VARCHAR(200),
	fullname 	VARCHAR(200),
	EntryCode 	VARCHAR(200),
	Standard	VARCHAR(200),
	Type		VARCHAR(200),
	Area		VARCHAR(200)
)

/*
IF @MPtypeid<>'-99999'
	INSERT INTO #GetManPTypeId(TypeId,UserCode,fullname,EntryCode,Standard,Type,Area) 
	SELECT b.typeid,b.usercode,b.fullname,b.entrycode,b.standard,b.type,b.area  
	From  dbo.F_ManPTypeInCategoryID(@OperatorID,@pTypeID,@ptypecategoryid) p 
	INNER JOIN Ptype b ON b.typeid=p.typeid
ELSE
	INSERT INTO #GetManPTypeId(TypeId,UserCode,fullname,EntryCode,Standard,Type,Area)
	SELECT b.typeid,b.usercode,b.fullname,b.entrycode,b.standard,b.type,b.area 
	FROM F_GetManDetailPType(@OperatorID) p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp  ON p.TypeId = sp.TypeId  
	INNER JOIN Ptype b ON b.typeid=p.typeid	 */
	
	INSERT INTO #GetManPTypeId(TypeId,UserCode,fullname,EntryCode,Standard,Type,Area) 
	SELECT b.typeid,b.usercode,b.fullname,b.entrycode,b.standard,b.type,b.area  
	From  dbo.F_ManPTypeInCategoryID(@OperatorID,@pTypeID,@ptypecategoryid) p 
	INNER JOIN Ptype b ON b.typeid=p.typeid

CREATE CLUSTERED INDEX [CIX_PTYPE_Typeid] ON [dbo].#GetManPTypeId 
(
	[typeId] ASC
) ON [PRIMARY]

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999' OR @MBtypeid2='-99999'
	INSERT INTO #GetManBTypeId(TypeId) SELECT b.TypeId FROM F_GetManDetailBType(@OperatorID) b INNER JOIN F_GetAllBaseTypeId(@dealbTypeID,2) sb ON b.TypeId = sb.TypeId
ELSE
	INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@dealbTypeID,2)
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@kTypeID,4,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
--删除仓库中的对于STypeId
DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		

IF @kTypeID='' --全部仓库时，加入代销库 Wang Wei Add 2010-8-26 
	INSERT INTO #GetManKTypeId(TypeId) values('10000')
	
IF @tablename <> '' --只有在@tablename 表存在的情况下，才能正确查询
    BEGIN
        DECLARE  @mycount INT
        CREATE TABLE #MYCOUNT
		(
          	MYCOUNT INT
		)
        EXEC( 'insert into #mycount select count(name)  from sysobjects where type=''u'' and [name]=''' + @tablename + '''')
        SELECT @mycount = MYCOUNT
        FROM   #MYCOUNT
        IF @mycount <= 0
            SET @tablename = ''
        DROP TABLE #MYCOUNT
    END

DECLARE @SQL varchar(MAX)	-- 查询的SQL
SET @SQL=''

/*处理参数*/
SET	@SQL = '
	SELECT  a.BTypeId1,
			a.BTypeId2,
			a.Serial,
			a.state,
			a.InKtypeTime,	
			a.OutKtypeTime,
			a.[USER],
			a.note,
			a.KTypeID,
			a.iniFlag,
			b.UserCode,
			b.typeid  As PTypeId,
			b.fullname As pFullname,
			b.EntryCode,
			b.Standard,
			b.Type,
			b.Area,
			a.STypeId,
			identity(int,1,1) AS sid,
			a.comment1,
			a.Comment2,
			a.comment3,
			e.fullname as efullname,
			a.itemid,
			cargoid,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice
	INTO	#temp1
	FROM 	GP_CruPTypeSerial a  
	INNER JOIN #GetManPTypeId b ON b.typeid=a.PTypeID 
	INNER JOIN #GetManKTypeId  k  ON a.KtypeID=k.TypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId = a.STypeId
	left join vWeb_ItemIDByIsCombined e on (a.Iscombined=e.iscombined AND e.id=a.ItemID ) 
	 '
 	IF  @cargoid<>''
			SET @SQL+=' INNER JOIN dbo.f_split('''+@cargoid+''','','') d ON a.CargoID =d.a '	    
SET	@SQL =@SQL+' WHERE 	1=1 '
	
IF @showIniSerial = 1 --是否仅显示期初的序列号
	SET @SQL = @SQL + ' AND a.iniFlag = 1 '

/*处理日期 0.入库时间有效  1.出库时间有效*/
IF @radValue = 0
	SET @SQL = @SQL + ' AND a.InKtypeTime>='+char(39)+@StartDate+char(39)+' 
						AND a.InKtypeTime<='+char(39)+@EndDate+char(39)
ELSE
	SET @SQL = @SQL + ' AND a.OutKtypeTime>='+char(39)+@StartDate+char(39)+' 
						AND a.OutKtypeTime<='+char(39)+@EndDate+char(39)
/*查询时往来单位有效*/
IF @dealbTypeID <> '00000'
	SET @SQL = @SQL + ' AND ((a.BTypeId1 IN (SELECT TypeId FROM #GetManBTypeId)) OR (a.BTypeId2 IN (SELECT TypeId FROM #GetManBTypeId)))'


IF @searchMode=0   --1.精确匹配 0.模糊查找
	BEGIN
		IF(@tablename<>'') ----haiquan多项筛选
		    BEGIN
				IF @pSerial<>''
				   SET @SQL=@SQL+' AND (a.Serial LIKE '+char(39)+'%'+@pSerial+'%'+char(39)+' OR a.Serial in (SELECT Serial FROM '+@tablename+'))'
			    ELSE
				   SET @SQL=@SQL+'AND a.Serial in (SELECT Serial FROM '+@tablename+')'
		    END
		ELSE
		BEGIN
			IF @pSerial<>''
				SET @SQL=@SQL+' AND a.Serial LIKE '+char(39)+'%'+@pSerial+'%'+char(39)
			IF @pUsercode<>''
				SET @SQL=@SQL+' AND b.usercode LIKE '+char(39)+'%'+@pUsercode+'%'+char(39)
			IF @pFullname<>''
				SET @SQL=@SQL+' AND b.fullname LIKE '+char(39)+'%'+@pFullname+'%'+char(39)
			
			IF @USER<>''
				SET @SQL=@SQL+' AND a.[USER] LIKE '+char(39)+'%'+@USER+'%'+char(39)
			IF @Note<>''
				SET @SQL=@SQL+' AND a.Note LIKE '+char(39)+'%'+@Note+'%'+char(39)	
			IF @comment1<>''
				SET @SQL=@SQL+' AND a.comment1 LIKE '+char(39)+'%'+@comment1+'%'+char(39)
			IF @comment2<>''
				SET @SQL=@SQL+' AND a.comment2 LIKE '+char(39)+'%'+@comment2+'%'+char(39)
			IF @comment3<>''
				SET @SQL=@SQL+' AND a.comment3 LIKE '+char(39)+'%'+@comment3+'%'+char(39)
		END


		IF @ShowAllUser=1
			SET @SQL=@SQL+' AND ISNULL(a.[USER],'''')='''''
		ELSE IF @ShowAllUser=2
			SET @SQL = @SQL + 'AND ISNULL(a.[USER],'''')<>'''''

	END 
ELSE  			--1.精确匹配 0.模糊查找
	BEGIN
		IF (@tablename<>'')
		     BEGIN
				IF @pSerial<>''
			   		SET @SQL=@SQL+'AND (a.Serial = '+char(39)+@pSerial+char(39)+' OR a.Serial in (SELECT Serial FROM '+@tablename+'))' 
		     	ELSE
			  	 	SET @SQL=@SQL+'AND a.Serial in (SELECT Serial FROM '+@tablename+')'
		     END
		ELSE
			SET @SQL=@SQL+'AND a.Serial = '+char(39)+@pSerial+char(39) 
		
		SET @SQL=@SQL+'	AND b.UserCode = '+char(39)+@pUsercode+char(39)+'
						AND b.FullName = '+char(39)+@pFullname+char(39)+''	
	END

IF @pState<>''
	SET @SQL=@SQL+' AND a.state in ('+@pState+')'
IF @itemid!=''
    SET @SQL=@SQL+' AND e.itemid = '+char(39)+@itemid+char(39)+''
IF @producedate!=''
    SET @SQL=@SQL+' and a.ProduceDate='+char(39)+@ProduceDate+char(39)+''
IF @validdate!=''
    SET @SQL=@SQL+' AND a.ValidDate='+char(39)+@ValidDate+char(39)+''        
  
SET @SQL = @SQL + '   ORDER BY a.Serial'
/*IF @chrRowsReturn = '0'
BEGIN
	SET @SQL = @SQL + '
	DECLARE @RowsCount numeric(18,0)
	SELECT @RowsCount = COUNT(*) FROM #temp1'
END

--自定义行数
DECLARE @uCount int
SELECT @uCount = ISNULL(UserDeRowCount,0) FROM LoginUser WHERE ETypeId = @OperatorID
IF @uCount = 0 SET @uCount = 14
*/
SET @SQL = @SQL + '
	SELECT  a.BTypeId1,
			a.BTypeId2,
			XUserCode = CASE
							WHEN ISNULL(a.BTypeId1,'''') = '''' THEN ''''
							WHEN EXISTS (SELECT TOP 1 1 FROM F_GetManBTypeAll('''+@OperatorID+''') WHERE deleted = 0 and sonnum = 0 and typeid = a.BTypeId1) THEN (SELECT UserCode FROM BType WHERE TypeId = a.BTypeId1)
							ELSE ''****''
						END,			
			Xfullname = CASE
							WHEN ISNULL(a.BTypeId1,'''') = '''' THEN ''''
							WHEN EXISTS (SELECT TOP 1 1 FROM F_GetManBTypeAll('''+@OperatorID+''') WHERE deleted = 0 and sonnum = 0 and typeid = a.BTypeId1) THEN (SELECT FullName FROM BType WHERE TypeId = a.BTypeId1)
							ELSE ''****''
						END,
			Gfullname = CASE
							WHEN ISNULL(a.BTypeId2,'''') = '''' THEN ''''
							WHEN EXISTS (SELECT TOP 1 1 FROM F_GetManBTypeAll('''+@OperatorID+''') WHERE deleted = 0 and sonnum = 0 and typeid = a.BTypeId2) THEN (SELECT FullName FROM BType WHERE TypeId = a.BTypeId2)
							ELSE ''****''
						END,
			a.Serial,
			a.state,
			a.STypeId,
			a.InKtypeTime,	
			a.OutKtypeTime,
			a.[USER],
			a.note,
			a.UserCode,
			a.PTypeId,
			a.pFullname,
			a.EntryCode,
			a.Standard,
			a.Type,
			a.Area,
			a.comment1,
			a.comment2,
			a.comment3,
			a.KTypeId,
			efullname,
			itemid,
			cargoid,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice,
			kFullName = (SELECT FullName FROM Stock WHERE TypeID = a.KTypeID),
			CASE WHEN a.iniFlag = 1 THEN ''√''
				ELSE NULL
				END AS iniFlag,
			case when a.OutKtypeTime is null or a.OutKtypeTime='''' or a.state in (1,7,25) then DATEDIFF(day, a.InKtypeTime, getdate()) +1
				else DATEDIFF(day, a.InKtypeTime, a.OutKtypeTime) +1
			END AS Serialage
	FROM	#temp1 a
	ORDER BY a.sid'


--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_SearchGiveOrGiveMe]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[gp_SearchGiveOrGiveMe]
GO




--================================
--作者：谢吉康
--日期：2003-03-13
--描述：根据条件查询赠送或获赠记录
--修改记录：
--1.修改日期：2003-06-02
--  修改人：　谢吉康
--  修改描述：职员赠送的树型表查询不正确，显示处理父节点下的所有数据。　

--	谢吉康 判断客户和供货商是否统一  2003-08-12	
--修改历史：
--         陈启华  2004-06-02 #01 明细表加上商品的一些规格，型号，产地等信息
--修改历史：
--         刘  戈  2004-07-09 #02 查询添加条件
	
--================================
--=========================midify by tq ======================
--作者：滕强      #-01   是不是应该加上仓库、商品的权限
--修改时间：2004-9-2 
--修改描述：没有加供应商和客户的权限
--============================================================
CREATE                             PROCEDURE [gp_SearchGiveOrGiveMe] 
(
 	@OperatorID VARCHAR(100),  ----操作员ID
	@type  VARCHAR(100),            ----查询的大类别   G=赠送   M=获赠
	@qtype  VARCHAR(100),          ----查询的小类别   GP=商品赠送      GB=客户赠送      GE=经手人赠送        MP=商品获赠        MB=供应商获赠
	@startdate VARCHAR(20),      ----开始日期
	@enddate  VARCHAR(20),      ----截止日期
	@ptypeid    VARCHAR(100),     ----商品ID
	@btypeid    VARCHAR(100),     ----客户或供应商ID
	@etypeid    VARCHAR(100),     ----经手人ID
	@szetypeid	VARCHAR(100),	------公有经手人ID选项
	@szbtypeid  VARCHAR(100),	------公有往来单位ID选项
	@szptypeid  VARCHAR(100),	------公有商品ID选项
	@szktypeid  VARCHAR(100),	------公有仓库ID选项
	@ifline CHAR(10),                           ----是否是线性列表查询        1.明细表   0.不是   2.线性表
	@sortfield   VARCHAR(100),      ----排序的字段
	@sorttype   CHAR(10),          ----排序的方式    1.升序   2.降序 
	@isSon       CHAR(10),           ----是否是子节点  1.是  0.否
	@showZero INT		    --1.=显示数量为0   0.=不显示数量为0的商品
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL VARCHAR(8000)
DECLARE @SonNum INT
SELECT @SQL=''
-----------------------------------谢吉康   判断客户和供货商是否统一  2003-08-12
DECLARE	@BtypeAll INT
SELECT @BtypeAll=VALUE FROM UserConfig WHERE ConfigName='BtypeAll'

DECLARE @BSonNum2 		INT				--供应商的SonNum
DECLARE @BTypeID1		VARCHAR(50)		--客户的权限ID
DECLARE @BTypeID2		VARCHAR(50)		--供应商的权限ID
DECLARE @MBSQL_WHERE 	VARCHAR(8000)	--MB的条件

SELECT @MBSQL_WHERE = ' WHERE a.Deleted = 0 '

IF @szbtypeid='00000'
	SET @szbtypeid=''

IF @szptypeid='00000'
	SET @szptypeid=''

IF @szktypeid='00000'
	SET @szktypeid=''


-----------------------------------赠送查询
IF @type='G'
BEGIN
--------------------------------------------------------------------------------------------商品赠送查询(树型表)
   IF @qtype='GP'
   BEGIN
      -----------------------------------树性表
      IF @ifline=0
      	BEGIN
			IF @PTypeID <> ''
				SELECT @SonNum = SonNum FROM Ptype WHERE TypeId = @PtypeId AND Deleted = 0
			ELSE			
				BEGIN	
					IF @MPTypeID = ''
						BEGIN
							SELECT @SonNum = 1
							SELECT @PTypeID = '00000'
						END
					ELSE
						SELECT @SonNum = SonNum FROM PType WHERE TypeID = @MPTypeID AND Deleted = 0
				END
      		SELECT @SQL='
				SELECT 	a.TypeID,
						a.UserCode,
						a.FullName,
						a.sonnum,
						SUM(ISNULL(b.Qty,0)) AS qty, 
						SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
						SUM(ISNULL(b.CostTotal,0)) AS CostTotal
				FROM	PType a
                        LEFT JOIN
             			( 
					        SELECT	ISNULL(a.Qty,0) AS qty, 
									a.PTypeID,
					    	        a.CostPrice, 
				    	         	a.CostTotal
			        		FROM	InOutStockTable   a,
									BillIndex b
			 			    WHERE   a.BillNumberId=b.BillNumberId
				           			AND b.Draft=0
				           			AND b.RedWord=0
			                        AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
									AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
									AND b.ptypeid like'+CHAR(39)+@szptypeid+'%'+CHAR(39)+'
									AND b.etypeid like'+CHAR(39)+@szetypeid+'%'+CHAR(39)+'
									AND b.btypeid like'+CHAR(39)+@szbtypeid+'%'+CHAR(39)+'
									AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
				          			AND b.BillType=139
									AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
									AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
									AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
						) b	ON	a.TypeID = LEFT(b.PTypeID,len(a.TypeID))'
			IF @ptypeid='' 			--默认参数 
				BEGIN
					IF @SonNum>=1
						SELECT @SQL=@SQL+' WHERE a.ParID ='+CHAR(39)+@MPtypeid+CHAR(39)+' AND a.deleted=0'
					ELSE
						SELECT @SQL=@SQL+' WHERE a.TypeId LIKE'+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.deleted=0'
				END
			IF @ptypeid<>''			--具体的参数
				BEGIN
					IF LEN(@PTypeID)>=LEN(@MPTypeID)
						BEGIN
							IF @SonNum>=1
								SELECT @SQL=@SQL+' WHERE a.ParID = '+CHAR(39)+@PTypeID+CHAR(39)+' AND a.deleted = 0'
							ELSE
								SELECT @SQL=@SQL+' WHERE a.TypeID = '+CHAR(39)+@PTypeID+CHAR(39)+' AND a.deleted = 0'
						END
					ELSE
						IF @SonNum>=1
							SELECT @SQL=@SQL+' WHERE a.ParID ='+CHAR(39)+@MPtypeid+CHAR(39)+' AND a.deleted=0'
						ELSE
							SELECT @SQL=@SQL+' WHERE a.TypeId LIKE'+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.deleted=0'
				END 
					
					SELECT @SQL = @SQL +' AND a.TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)
		            SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum  ORDER BY a.UserCode,b.'+@sortfield
			--print @SQL
	   END   
      -----------------------------------明细表       
      IF @ifline=1 -- #01 明细表加上商品的一些规格，型号，产地等信息
	BEGIN
		SELECT @SQL='SELECT bil.billdate,bil.billcode,e.fullname AS empfullname,b.fullname AS bfullname,k.fullname AS kfullname,SUM(ISNULL(a.qty,0)) AS qty,SUM(ISNULL(a.costtotal,0)) AS costtotal,a.ptypeid,a.btypeid,a.ktypeid,bil.btypeid,
					a.etypeid,bil.billnumberid,p.usercode,p.fullname,isnull(p.type,'''') as type,isnull(p.Area,'''') as Area,isnull(p.Standard,'''') as Standard
				FROM inoutstocktable a 
				INNER JOIN billindex bil
					ON a.billnumberid=bil.billnumberid
				INNER JOIN stock k
					ON bil.ktypeid=k.typeid
				INNER JOIN employee e
					ON bil.etypeid=e.typeid
				INNER JOIN btype b
					ON bil.btypeid=b.typeid
				INNER JOIN ptype p
					ON a.ptypeid=p.typeid'
		IF @ptypeid='00000'
			SELECT @SQL=@SQL+' WHERE  a.billtype=139 AND bil.redword=0 AND bil.draft=0  AND bil.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND bil.billdate<='+CHAR(39)+@enddate+CHAR(39)+' AND p.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39)

		IF @ptypeid<>'00000'
			SELECT @SQL=@SQL+' WHERE a.ptypeid LIKE '+CHAR(39)+@ptypeid+'%'+CHAR(39)+' AND  a.billtype=139 AND bil.redword=0 AND bil.draft=0  AND bil.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND bil.billdate<='+CHAR(39)+@enddate+CHAR(39)+' AND p.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39) +'AND bil.etypeid like '+CHAR(39)+@szetypeid+'%'+CHAR(39) +'AND bil.btypeid like '+CHAR(39)+@szbtypeid+'%'+CHAR(39)+'AND bil.ktypeid like '+CHAR(39)+@szktypeid+'%'+CHAR(39)
			
			SELECT @SQL=@SQL+'  AND k.TypeID LIKE '+CHAR(39)+@MKtypeID+'%'+CHAR(39)+'AND p.TypeID LIKE '+CHAR(39)+@MPtypeID+'%'+CHAR(39)+'AND (b.TypeID LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+'OR b.TypeID LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'   --#-01
            
  		
		SELECT @SQL=@SQL+' GROUP BY bil.billdate,bil.billcode,e.fullname,b.fullname,k.fullname,a.ptypeid,a.btypeid,a.ktypeid,bil.btypeid,
					a.etypeid,bil.billnumberid,p.usercode,p.fullname,p.type,p.Area,p.Standard'
		 
		SELECT @SQL=@SQL+'  ORDER BY a.'+@sortfield				
	--print @SQL        
    END
   -------------------------------------线性表
    IF @ifline=2 
      	BEGIN
      		SELECT @SQL='SELECT a.TypeID,
			a.UserCode,
			a.FullName,
			a.sonnum,
		             SUM(ISNULL(b.Qty,0)) AS qty, 
		             SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
		             SUM(ISNULL(b.CostTotal,0)) AS CostTotal
		 FROM	PType a
                                         LEFT JOIN
             			( 
			        SELECT	ISNULL(a.Qty,0) AS qty, 
					a.PTypeID,
				             a.CostPrice, 
				             a.CostTotal
			        FROM	InOutStockTable   a,BillIndex b
			        WHERE   a.BillNumberId=b.BillNumberId
							AND b.Draft=0
							AND b.RedWord=0
							AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
							AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
							AND b.etypeid like'+CHAR(39)+@szetypeid+'%'+CHAR(39)+'
							AND b.btypeid like'+CHAR(39)+@szbtypeid+'%'+CHAR(39)+'
							AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
					        AND b.BillType=139
							AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
							AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
							AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
		             ) b
	             ON	a.TypeID = b.PTypeID'
		IF  @ptypeid='00000'
			SELECT @SQL=@SQL+' WHERE  a.sonnum=0 AND a.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.deleted=0'
		IF @ptypeid<>'00000' AND @isSon=0
			SELECT @SQL=@SQL+' WHERE a.typeid LIKE '+CHAR(39)+@ptypeid+'%'+CHAR(39)+' AND a.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.deleted=0'
		IF @ptypeid<>'00000' AND @isSon=1
			SELECT @SQL=@SQL+' WHERE a.typeid LIKE  '+CHAR(39)+@ptypeid+'%'+CHAR(39)+' AND a.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.sonnum=0'+' AND a.deleted=0'
		IF @showZero=0
			SELECT @SQL=@SQL+' AND qty<>0'
	             SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum  ORDER BY b.'+@sortfield
	   END   
   END
------------------------------------------------------------------------------------------客户赠送查询(树型表)
   IF @qtype='GB'
      BEGIN
		IF @ifline=0
	  		BEGIN
	             SELECT @SQL='
						SELECT	a.TypeID,
								a.UserCode,
								a.FullName,
								a.sonnum,
					            SUM(ISNULL(b.Qty,0)) AS qty, 
				             	SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
					            SUM(ISNULL(b.CostTotal,0)) AS CostTotal
						FROM	BType a  
							LEFT JOIN	
								( 
	        						SELECT	ISNULL(a.Qty,0) AS qty, 
											b.BTypeID,
				          	             	a.CostPrice, 
				             		        a.CostTotal
	        						FROM	InOutStockTable   a,
											BillIndex b
		  		             		WHERE   a.BillNumberId=b.BillNumberId
  		                           			AND b.Draft=0
					                        AND b.RedWord=0
	                           			    AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
											AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
											AND a.ptypeid like'+CHAR(39)+@szptypeid+'%'+CHAR(39)+'
											AND b.etypeid like'+CHAR(39)+@szetypeid+'%'+CHAR(39)+'
											AND b.btypeid like '+CHAR(39)+@szBtypeid+'%'+CHAR(39)+'
											AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
					                        AND b.BillType=139
											AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
											AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
											AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
                     			) b  ON	  a.TypeID = LEFT(b.BTypeID,len(a.typeID))'
				--=======================================================================================================判断范围
				IF @BTypeID <> ''
					BEGIN
						IF @BTypeAll = 1								--统一客户和供应商
							BEGIN
								IF LEN(@BTypeID)>=LEN(@MBTypeID)		--判断客户
									BEGIN				
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0						
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.ParID = '+CHAR(39)+ISNULL(@BTypeID,'')+CHAR(39)
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID,'')+'%'+CHAR(39)
									END
								ELSE
									BEGIN
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @MBTypeId AND Deleted = 0
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.ParID = '+CHAR(39)+ISNULL(@MBTypeID,'')+CHAR(39)
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.TypeID LIKE '+CHAR(39)+ISNULL(@MBTypeID,'')+'%'+CHAR(39)											
									END

								IF LEN(@BTypeID)>=LEN(@MBTypeID2)		--判断供应商
									BEGIN				
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0						
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR  a.ParID = '+CHAR(39)+ISNULL(@BTypeID,'')+CHAR(39)+' ) '
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR  a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID,'')+'%'+CHAR(39)+' ) '
									END
								ELSE
									BEGIN
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @MBTypeId2 AND Deleted = 0
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR  a.ParID = '+CHAR(39)+ISNULL(@MBTypeID,'')+CHAR(39)+' ) '
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR  a.TypeID LIKE '+CHAR(39)+ISNULL(@MBTypeID,'')+'%'+CHAR(39)+' ) '
									END


							END
						ELSE											--客户
							BEGIN
								IF LEN(@BTypeID)>=LEN(@MBTypeID)
									BEGIN				
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0						
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.ParID = '+CHAR(39)+ISNULL(@BTypeID,'')+CHAR(39)
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID,'')+'%'+CHAR(39)
									END
								ELSE
									BEGIN
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @MBTypeId AND Deleted = 0
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.ParID = '+CHAR(39)+ISNULL(@MBTypeID,'')+CHAR(39)
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.TypeID LIKE '+CHAR(39)+ISNULL(@MBTypeID,'')+'%'+CHAR(39)											
									END								
							END
					END
				ELSE			
					BEGIN	
						IF @MBTypeID = ''	--判断客户的范围
							BEGIN
								SELECT @SonNum = 1
								SELECT @BTypeID1 = '00001'
							END
						ELSE	
							BEGIN
								SELECT @SonNum = SonNum FROM BType WHERE TypeID = @MBTypeID AND Deleted = 0
								IF @SonNum >= 1
									SELECT @SonNum = 1
								ELSE
									SELECT @SonNum = 0
								SELECT @BTypeID1 = @MBTypeID
							END
						--=====================================构造@MBSQL_WHERE的条件(客户)
						IF @BTypeAll = 1
							BEGIN
								IF @SonNum = 1				
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.ParID = '+CHAR(39)+ISNULL(@BTypeID1,'')+CHAR(39)								
								ELSE
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID1,'')+'%'+CHAR(39)
							END
						ELSE
							BEGIN
								IF @SonNum = 1				
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.ParID = '+CHAR(39)+ISNULL(@MBTypeID,'')+CHAR(39)								
								ELSE
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.TypeID LIKE '+CHAR(39)+ISNULL(@MBTypeID,'')+'%'+CHAR(39)								
							END

						--=====================================构造@MBSQL_WHERE的条件(客户)
						IF @BTypeAll = 1
							BEGIN
								IF @MBTypeID2 = ''	--判断供应商的范围
									BEGIN
										SELECT @BSonNum2 = 1
										SELECT @BTypeID2 = '00002'
									END
								ELSE	
									BEGIN
										SELECT @BSonNum2 = SonNum FROM BType WHERE TypeID = @MBTypeID2 AND Deleted = 0
										IF @BSonNum2 >= 1
											SELECT @BSonNum2 = 1
										ELSE
											SELECT @BSonNum2 = 0
										SELECT @BTypeID2 = @MBTypeID2
									END
								--=====================================构造@MBSQL_WHERE的条件(供应商)
								IF @BSonNum2 = 1
									BEGIN
										IF @BtypeAll = 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR a.ParID = '+CHAR(39)+ISNULL(@BTypeID2,'')+CHAR(39)+' )'
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.ParID = '+CHAR(39)+ISNULL(@BTypeID2,'')+CHAR(39)
									END
								ELSE
									BEGIN
										IF @BTypeAll = 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID2,'')+'%'+CHAR(39)+' )'	
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID2,'')+'%'+CHAR(39)
									END						
								--=====================================构造@MBSQL_WHERE的条件(供应商)
							END
					END
					
					SELECT @MBSQL_WHERE = @MBSQL_WHERE +' AND ( a.TypeID LIKE '+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' OR a.TypeID LIKE '+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+' ) '		

					SELECT @SQL = @SQL + @MBSQL_WHERE
				--=======================================================================================================判断范围  
                     SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum  ORDER BY  a.UserCode,b.'+@sortfield
		END         
      -----------------------------------明细表            
      IF @ifline=1-- #01 明细表加上商品的一些规格，型号，产地等信息
	BEGIN
		SELECT @SQL='
				SELECT bil.billdate,bil.billcode,e.fullname AS empfullname,b.fullname AS bfullname,k.fullname AS kfullname,b.sonnum,SUM(ISNULL(IOut.qty,0)) AS qty,SUM(ISNULL(IOut.CostTotal,0)) AS CostTotal,
				bil.btypeid,IOut.ptypeid,bil.billnumberid,p.usercode,p.fullname,isnull(p.type,'''') as type,isnull(p.Area,'''') as Area,isnull(p.Standard,'''') as Standard
				FROM billindex bil,employee e,btype b,stock k,InoutstockTable IOut,ptype p
				WHERE   bil.billnumberid=Iout.billnumberid
				AND bil.etypeid=e.typeid
				AND bil.btypeid=b.typeid
				AND bil.ktypeid=k.typeid
				AND IOut.ptypeid=p.typeid
				AND bil.billtype=139
				AND Bil.IfCheck = ''t''
				AND Bil.RedWord = 0
				AND bil.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND bil.billdate<='+CHAR(39)+@enddate+CHAR(39) --+'AND bil.etypeid like '+CHAR(39)+@szetypeid+'%'+CHAR(39) +'AND IOut.ptypeid like '+CHAR(39)+@szptypeid+'%'+CHAR(39)
		DECLARE @CurSon INT
		SELECT @CurSon=sonnum FROM Btype WHERE TypeId=''+@BtypeId+''
		
		IF @CurSon=0 
			SELECT @SQL=@SQL+' AND (bil.btypeid LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+' OR bil.btypeid LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+') AND bil.btypeid='+CHAR(39)+@BtypeID+CHAR(39)+'AND bil.etypeid like '+CHAR(39)+@szetypeid+'%'+CHAR(39) +'AND IOut.ptypeid like '+CHAR(39)+@szptypeid+'%'+CHAR(39)+'AND bil.ktypeid like '+CHAR(39)+@szktypeid+'%'+CHAR(39)
		ELSE
			SELECT @SQL=@SQL+' AND (bil.btypeid LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+' OR bil.btypeid LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+') AND bil.btypeid LIKE '+CHAR(39)+@BtypeID+'%'+CHAR(39)+'AND bil.etypeid like '+CHAR(39)+@szetypeid+'%'+CHAR(39) +'AND IOut.ptypeid like '+CHAR(39)+@szptypeid+'%'+CHAR(39)+'AND bil.ktypeid like '+CHAR(39)+@szktypeid+'%'+CHAR(39)
			SELECT @SQL=@SQL+'  AND k.TypeID LIKE '+CHAR(39)+@MKtypeID+'%'+CHAR(39)+'AND p.TypeID LIKE '+CHAR(39)+@MPtypeID+'%'+CHAR(39)+'AND (b.TypeID LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+'OR b.TypeID LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'   --#-01
		SELECT @SQL=@SQL+' GROUP BY bil.billdate,bil.billcode,e.fullname,b.fullname,k.fullname,b.sonnum,
							bil.btypeid,IOut.ptypeid,bil.billnumberid,p.usercode,p.fullname,p.type,p.Area,p.Standard'
		SELECT @SQL=@SQL+' ORDER BY IOut.'+@sortfield
	END
   -------------------------------------线性表
    IF @ifline=2 
		BEGIN
	    	SELECT @SQL='
				SELECT	A.TypeID,
						a.UserCode,
						a.FullName,
						a.sonnum,
	            		SUM(ISNULL(b.Qty,0)) AS qty, 
             			SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
	             		SUM(ISNULL(b.CostTotal,0)) AS CostTotal
				FROM	BType a  
				LEFT JOIN
					( 
	        			SELECT	ISNULL(a.Qty,0) AS qty, 
								b.BTypeID,
		          	            a.CostPrice, 
		             		    a.CostTotal
	        			FROM	InOutStockTable   a,
								BillIndex b
						WHERE   a.BillNumberId=b.BillNumberId
  		                        AND b.Draft=0
		                        AND b.RedWord=0
                                AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
								AND a.ptypeid like '+CHAR(39)+@szPtypeid+'%'+CHAR(39)+'
								AND b.btypeid like '+CHAR(39)+@szBtypeid+'%'+CHAR(39)+'
								AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
								AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
                                AND b.BillType=139
								AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
								AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
                     ) b ON	  a.TypeID = b.BTypeID'
			IF @btypeid='00001'
				SELECT @SQL=@SQL+' WHERE  a.typeid LIKE '+CHAR(39)+@btypeid+'%'+CHAR(39)+'  AND a.typeid<>'+CHAR(39)+'00001'+CHAR(39)+' AND a.sonnum=0'+' AND a.deleted=0'
	       	IF @btypeid='00000'
				SELECT @SQL=@SQL+' WHERE a.sonnum=0'+' AND a.deleted=0'
	       	IF @btypeid<>'00000' AND @btypeid<>'00001'
				SELECT @SQL=@SQL+' WHERE a.typeid  LIKE '+CHAR(39)+@btypeid+'%'+CHAR(39)+' AND a.sonnum=0'+' AND a.deleted=0'

			SET @SQL = @SQL + ' AND (A.TypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR A.TypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')'

  	        IF @showZero=0
				SELECT @SQL=@SQL+' AND qty<>0'
                     SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum  ORDER BY   b.'+@sortfield
		END         
   END
------------------------------------------------------------------------------------------经手人赠送查询(树型表)
   IF @qtype='GE'
       BEGIN
            IF @ifline=0
	   BEGIN
	      SELECT @SQL='SELECT	a.TypeID,
		a.UserCode,
		a.FullName,
		a.sonnum,
	             SUM(ISNULL(b.Qty,0)) AS qty, 
             		SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
	             SUM(ISNULL(b.CostTotal,0)) AS CostTotal
             		FROM	Employee a   LEFT JOIN
		             ( 
	        			SELECT	ISNULL(a.Qty,0) AS qty, 
					a.ETypeID,
		          	             		a.CostPrice, 
		             		              a.CostTotal
	        			FROM	InOutStockTable   a,BillIndex b
		  	             WHERE   a.BillNumberId=b.BillNumberId
  		                           AND b.Draft=0
		                           AND b.RedWord=0
	                               AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
								   AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
									AND a.ptypeid like'+CHAR(39)+@szptypeid+'%'+CHAR(39)+'
									AND b.btypeid like'+CHAR(39)+@szbtypeid+'%'+CHAR(39)+'
									AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
		                           AND b.BillType=139
									AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
									AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
									AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
                     ) b
                     ON	  a.TypeID = LEFT(b.ETypeID,len(a.TypeID))'
		IF @etypeid=''
		BEGIN	
			IF @MEtypeid='' OR @MEtypeid='00001'
				SELECT @SQL=@SQL+' WHERE a.parid=''00001'''+' AND a.deleted=0'
			ELSE	
				BEGIN							
					SELECT @CurSon=Sonnum FROM employee WHERE typeid=''+@MEtypeID+''
					IF @CurSon=1	
						SELECT @SQL=@SQL+' WHERE a.parid = '+CHAR(39)+@MEtypeid+CHAR(39)
					ELSE
						SELECT @SQL=@SQL+' WHERE a.typeid = '+CHAR(39)+@MEtypeid+CHAR(39)					
				END		
		END
	        IF @etypeid<>''
	        BEGIN	
		        IF @etypeid='00001'
			SELECT @SQL=@SQL+' WHERE a.parid = '+CHAR(39)+'00001'+CHAR(39)+' AND a.deleted=0 AND a.typeid LIKE'+CHAR(39)+@MEtypeid+'%'+CHAR(39)					
		        IF @etypeid<>'00001' AND @isSon=0
			SELECT @SQL=@SQL+' WHERE a.typeid = '+CHAR(39)+@etypeid+CHAR(39)+' AND a.deleted=0  AND a.typeid LIKE '+CHAR(39)+@MEtypeid+'%'+CHAR(39)
		        IF @etypeid<>'00001' AND @isSon=1
			SELECT @SQL=@SQL+' WHERE a.parid = '+CHAR(39)+@etypeid+CHAR(39)+'  AND a.deleted=0 AND a.typeid LIKE '+CHAR(39)+@MEtypeid+'%'+CHAR(39)
		        SELECT @SQL=@SQL+' AND a.deleted=0'
	        END
                     SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum    ORDER BY   a.UserCode,b.'+@sortfield
                 END
--+' AND bil.btypeid<='+CHAR(39)+@szbtypeid+CHAR(39)+' AND a.ptypeid<='+CHAR(39)+@szptypeid+CHAR(39)
      -----------------------------------明细表       
	IF @ifline=1-- #01 明细表加上商品的一些规格，型号，产地等信息
	BEGIN
		SELECT @SQL='
				SELECT bil.billdate,bil.billcode,e.fullname AS empfullname,b.fullname AS bfullname,k.fullname AS kfullname,SUM(ISNULL(a.qty,0)) AS qty,SUM(ISNULL(a.costtotal,0)) AS costtotal,a.ptypeid,a.btypeid,a.ktypeid,
				bil.btypeid,a.etypeid,bil.billnumberid,p.usercode,p.fullname,isnull(p.type,'''') as type,isnull(p.Area,'''') as Area,isnull(p.Standard,'''') as Standard
				FROM inoutstocktable a 
				INNER JOIN billindex bil
					ON a.billnumberid=bil.billnumberid
				INNER JOIN stock k
					ON bil.ktypeid=k.typeid
				INNER JOIN employee e
					ON bil.etypeid=e.typeid
				INNER JOIN btype b
					ON bil.btypeid=b.typeid
				INNER JOIN ptype p
					ON a.ptypeid=p.typeid
				WHERE  a.etypeid LIKE '+CHAR(39)+@etypeid+'%'+CHAR(39)+' AND a.billtype=139 AND bil.redword=0 AND bil.draft=0  AND bil.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND bil.billdate<='+CHAR(39)+@enddate+CHAR(39)+' AND bil.btypeid like'+CHAR(39)+@szbtypeid+'%'+CHAR(39)+' AND a.ptypeid like'+CHAR(39)+@szptypeid+'%'+CHAR(39)+'AND bil.ktypeid like '+CHAR(39)+@szktypeid+'%'+CHAR(39)
				SELECT @SQL=@SQL+'  AND k.TypeID LIKE '+CHAR(39)+@MKtypeID+'%'+CHAR(39)+'AND p.TypeID LIKE '+CHAR(39)+@MPtypeID+'%'+CHAR(39)+'AND (b.TypeID LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+'OR b.TypeID LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'   --#-01
  				 
				SELECT @SQL=@SQL+' GROUP BY bil.billdate,bil.billcode,e.fullname,b.fullname,k.fullname,a.ptypeid,a.btypeid,a.ktypeid,
									bil.btypeid,a.etypeid,bil.billnumberid,p.usercode,p.fullname,p.type,p.Area,p.Standard'
				
				SELECT @SQL=@SQL+' ORDER BY a.'+@sortfield				
	END
   -------------------------------------线性表
        IF @ifline=2 
	   BEGIN
	      SELECT @SQL='SELECT	a.TypeID,
		a.UserCode,
		a.FullName,
		a.sonnum,
	             SUM(ISNULL(b.Qty,0)) AS qty, 
             		SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
	             SUM(ISNULL(b.CostTotal,0)) AS CostTotal
             		FROM	Employee a   LEFT JOIN
		             ( 
	        			SELECT	ISNULL(a.Qty,0) AS qty, 
					a.ETypeID,
		          	             		a.CostPrice, 
		             		              a.CostTotal
	        			FROM	InOutStockTable   a,BillIndex b
		  	             WHERE   a.BillNumberId=b.BillNumberId
  		                           AND b.Draft=0
		                           AND b.RedWord=0
	                                        AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
									AND a.ptypeid like'+CHAR(39)+@szptypeid+'%'+CHAR(39)+'
									AND b.btypeid like'+CHAR(39)+@szbtypeid+'%'+CHAR(39)+'
									AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
		                           AND b.BillType=139
									AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
									AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
									AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
                     ) b
                     ON	  a.TypeID = b.ETypeID'

	        IF @etypeid='00001'
			SELECT @SQL=@SQL+' WHERE a.parid LIKE  '+CHAR(39)+@etypeid+'%'+CHAR(39)+' AND a.deleted=0 AND a.sonnum=0 AND a.typeid LIKE '+CHAR(39)+@MEtypeid+'%'+CHAR(39)
		IF @etypeid<>'00001' AND @isSon=0 
			SELECT @SQL=@SQL+' WHERE a.typeid = '+CHAR(39)+@etypeid+CHAR(39)+' AND a.deleted=0 AND a.typeid LIKE '+CHAR(39)+@MEtypeid+'%'+CHAR(39)
		IF @etypeid<>'00001' AND @isSon=1
			SELECT @SQL=@SQL+' WHERE a.typeid LIKE '+CHAR(39)+@etypeid+'%'+CHAR(39)+' AND a.typeid<>'+CHAR(39)+@etypeid+CHAR(39)+ ' AND a.sonnum=0'+' AND a.deleted=0 AND a.typeid LIKE '+CHAR(39)+@MEtypeid+'%'+CHAR(39)
  	        IF @showZero=0
		SELECT @SQL=@SQL+' AND qty<>0'
                     SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum    ORDER BY   b.'+@sortfield
                 END
     END
END
--=============================================获赠查询
IF @type='M'
BEGIN
   IF @qtype='MP'
--------------------------------------------------------------------------------------------商品获赠查询
   BEGIN
       IF @ifline=0
	 	BEGIN
			IF @PTypeID <> ''
				SELECT @SonNum = SonNum FROM Ptype WHERE TypeId = @PtypeId AND Deleted = 0
			ELSE			
				BEGIN	
					IF @MPTypeID = ''
						BEGIN
							SELECT @SonNum = 1
							SELECT @PTypeID = '00000'
						END
					ELSE
						SELECT @SonNum = SonNum FROM PType WHERE TypeID = @MPTypeID AND Deleted = 0
				END
      		SELECT @SQL='
				SELECT 	a.TypeID,
						a.UserCode,
						a.FullName,
						a.sonnum,
						SUM(ISNULL(b.Qty,0)) AS qty, 
						SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
						SUM(ISNULL(b.CostTotal,0)) AS CostTotal
				FROM	PType a
                        LEFT JOIN
             			( 
					        SELECT	ISNULL(a.Qty,0) AS qty, 
									a.PTypeID,
					    	        a.CostPrice, 
				    	         	a.CostTotal
			        		FROM	InOutStockTable   a,BillIndex b
			 			    WHERE   a.BillNumberId=b.BillNumberId
				           			AND b.Draft=0
				           			AND b.RedWord=0
			                        AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
									AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
									AND b.etypeid like'+CHAR(39)+@szetypeid+'%'+CHAR(39)+'
									AND b.btypeid like'+CHAR(39)+@szbtypeid+'%'+CHAR(39)+'
									AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
				          			AND b.BillType=126
									AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
									AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
									AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
		             	) b	ON	a.TypeID = LEFT(b.PTypeID,len(a.TypeID))'
			IF @ptypeid='' 			--默认参数 
				BEGIN
					IF @SonNum>=1
						SELECT @SQL=@SQL+' WHERE a.ParID ='+CHAR(39)+@MPtypeid+CHAR(39)+' AND a.deleted=0'
					ELSE
						SELECT @SQL=@SQL+' WHERE a.TypeId LIKE'+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.deleted=0'
				END
			IF @ptypeid<>''			--具体的参数
				BEGIN
					IF LEN(@PTypeID)>=LEN(@MPTypeID)
						BEGIN
							IF @SonNum>=1
								SELECT @SQL=@SQL+' WHERE a.ParID = '+CHAR(39)+@PTypeID+CHAR(39)+' AND a.deleted = 0'
							ELSE
								SELECT @SQL=@SQL+' WHERE a.TypeID = '+CHAR(39)+@PTypeID+CHAR(39)+' AND a.deleted = 0'
						END
					ELSE
						IF @SonNum>=1
							SELECT @SQL=@SQL+' WHERE a.ParID ='+CHAR(39)+@MPtypeid+CHAR(39)+' AND a.deleted=0'
						ELSE
							SELECT @SQL=@SQL+' WHERE a.TypeId LIKE'+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.deleted=0'
				END 
					
					SELECT @SQL = @SQL +' AND a.TypeID LIKE '+CHAR(39)+@MPTypeID+'%'+CHAR(39)
		            SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum  ORDER BY a.UserCode,b.'+@sortfield
	   END   
      -----------------------------------明细表              
      IF @ifline=1-- #01 明细表加上商品的一些规格，型号，产地等信息
	BEGIN
		SELECT @SQL='
				SELECT bil.billdate,bil.billcode,e.fullname AS empfullname,b.fullname AS bfullname,k.fullname AS kfullname,SUM(ISNULL(a.qty,0)) AS qty,SUM(ISNULL(a.costtotal,0)) AS costtotal,a.ptypeid,a.btypeid,a.ktypeid,
				bil.btypeid,a.etypeid,bil.billnumberid,p.usercode,p.fullname,isnull(p.type,'''') as type,isnull(p.Area,'''') as Area,isnull(p.Standard,'''') as Standard
				FROM inoutstocktable a 
				INNER JOIN billindex bil
					ON a.billnumberid=bil.billnumberid
				INNER JOIN stock k
					ON bil.ktypeid=k.typeid
				INNER JOIN employee e
					ON bil.etypeid=e.typeid
				INNER JOIN btype b
					ON bil.btypeid=b.typeid
				INNER JOIN ptype p
					ON a.ptypeid=p.typeid'
				 --WHERE a.billtype=126 AND bil.redword=0 AND bil.draft=0 AND bil.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND bil.billdate<='+CHAR(39)+@enddate+CHAR(39)
				IF @ptypeid='00000'
					SELECT @SQL=@SQL+' WHERE  a.billtype=126 AND bil.redword=0 AND bil.draft=0  AND bil.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND bil.billdate<='+CHAR(39)+@enddate+CHAR(39)+' AND p.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39)
				IF @ptypeid<>'00000'
					SELECT @SQL=@SQL+' WHERE a.ptypeid LIKE '+CHAR(39)+@ptypeid+'%'+CHAR(39)+' AND  a.billtype=126 AND bil.redword=0 AND bil.draft=0  AND bil.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND bil.billdate<='+CHAR(39)+@enddate+CHAR(39)+' AND p.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39)+'AND bil.etypeid like '+CHAR(39)+@szetypeid+'%'+CHAR(39)+'AND bil.btypeid like '+CHAR(39)+@szbtypeid+'%'+CHAR(39)+'AND bil.ktypeid like '+CHAR(39)+@szktypeid+'%'+CHAR(39)
					SELECT @SQL=@SQL+'  AND k.TypeID LIKE '+CHAR(39)+@MKtypeID+'%'+CHAR(39)+'AND p.TypeID LIKE '+CHAR(39)+@MPtypeID+'%'+CHAR(39)+'AND (b.TypeID LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+'OR b.TypeID LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'   --#-01
	  			
				SELECT @SQL=@SQL+' GROUP BY bil.billdate,bil.billcode,e.fullname,b.fullname,k.fullname,a.ptypeid,a.btypeid,a.ktypeid,
									bil.btypeid,a.etypeid,bil.billnumberid,p.usercode,p.fullname,p.type,p.Area,p.Standard'	 
				
  				SELECT @SQL=@SQL+'  ORDER BY a.'+@sortfield				
	END
   -------------------------------------线性表
        IF @ifline=2 
         	BEGIN
      		SELECT @SQL='SELECT a.TypeID,
			a.UserCode,
			a.FullName,
			a.sonnum,
		             SUM(ISNULL(b.Qty,0)) AS qty, 
		             SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
		             SUM(ISNULL(b.CostTotal,0)) AS CostTotal
		 FROM	PType a
                                         LEFT JOIN
             			( 
			        SELECT	ISNULL(a.Qty,0) AS qty, 
					a.PTypeID,
				             a.CostPrice, 
				             a.CostTotal
			        FROM	InOutStockTable   a,BillIndex b
			        WHERE   a.BillNumberId=b.BillNumberId
							AND b.Draft=0
							AND b.RedWord=0
							AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
							AND b.etypeid like'+CHAR(39)+@szetypeid+'%'+CHAR(39)+'
							AND b.btypeid like'+CHAR(39)+@szbtypeid+'%'+CHAR(39)+'
							AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
							AND b.BillType=126
							AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
							AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
							AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
		             ) b
	             ON	a.TypeID = b.PTypeID'
		IF  @ptypeid='00000'
			SELECT @SQL=@SQL+' WHERE  a.sonnum=0 AND a.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.deleted=0'
		IF @ptypeid<>'00000' AND @isSon=0
			SELECT @SQL=@SQL+' WHERE a.typeid LIKE '+CHAR(39)+@ptypeid+'%'+CHAR(39)+' AND a.typeid LIKE '+CHAR(39)+@MPtypeid+'%'+CHAR(39)+' AND a.deleted=0'
		IF @ptypeid<>'00000' AND @isSon=1
			SELECT @SQL=@SQL+' WHERE a.typeid LIKE '+CHAR(39)+@ptypeid+'%'+CHAR(39)+' AND a.typeid <> '+CHAR(39)+@Ptypeid+CHAR(39)+' AND a.sonnum=0'+' AND a.deleted=0'
		IF @showZero=0
			SELECT @SQL=@SQL+' AND qty<>0'
	             SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum  ORDER BY  b.'+@sortfield
	   END   
   END
--------------------------------------------------------------------------------------供应商获赠(树型表)
   IF @qtype='MB'
         BEGIN
            IF @ifline=0
                   BEGIN
				      SELECT @SQL='
						SELECT		a.TypeID,
									a.UserCode,
									a.FullName,
									a.sonnum,
						            SUM(ISNULL(b.Qty,0)) AS qty, 
             						SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
	             					SUM(ISNULL(b.CostTotal,0)) AS CostTotal
						FROM		BType a      
							LEFT JOIN
								( 
	        						SELECT	ISNULL(a.Qty,0) AS qty, 
											b.BTypeID,
		          	             			a.CostPrice, 
		             		              	a.CostTotal 	        			
									FROM	InOutStockTable   a,
											BillIndex b
									WHERE   a.BillNumberId=b.BillNumberId
  		                           			AND b.Draft=0
		                           			AND b.RedWord=0
	                                        AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
											AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'
											AND b.etypeid like'+CHAR(39)+@szetypeid+'%'+CHAR(39)+'
											AND a.ptypeid like'+CHAR(39)+@szptypeid+'%'+CHAR(39)+'
											AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
		                           			AND b.BillType=126
											AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
											AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
											AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
                     			) b   ON	  a.TypeID =LEFT(b.BTypeID,len(a.TypeID))'
				--=======================================================================================================判断范围
				IF @BTypeID <> ''
					BEGIN
						IF @BTypeAll = 1								--统一客户和供应商
							BEGIN
								IF LEN(@BTypeID)>=LEN(@MBTypeID)		--判断客户
									BEGIN				
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0						
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.ParID = '+CHAR(39)+ISNULL(@BTypeID,'')+CHAR(39)
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID,'')+'%'+CHAR(39)
									END
								ELSE
									BEGIN
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @MBTypeId AND Deleted = 0
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.ParID = '+CHAR(39)+ISNULL(@MBTypeID,'')+CHAR(39)
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.TypeID LIKE '+CHAR(39)+ISNULL(@MBTypeID,'')+'%'+CHAR(39)											
									END

								IF LEN(@BTypeID)>=LEN(@MBTypeID2)		--判断供应商
									BEGIN				
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0						
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR  a.ParID = '+CHAR(39)+ISNULL(@BTypeID,'')+CHAR(39)+' ) '
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR  a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID,'')+'%'+CHAR(39)+' ) '
									END
								ELSE
									BEGIN
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @MBTypeId2 AND Deleted = 0
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR  a.ParID = '+CHAR(39)+ISNULL(@MBTypeID,'')+CHAR(39)+' ) '
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR  a.TypeID LIKE '+CHAR(39)+ISNULL(@MBTypeID,'')+'%'+CHAR(39)+' ) '
									END



							END
						ELSE											--供应商
							BEGIN
								IF LEN(@BTypeID)>=LEN(@MBTypeID2)
									BEGIN				
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0						

										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.ParID = '+CHAR(39)+ISNULL(@BTypeID,'')+CHAR(39)
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID,'')+'%'+CHAR(39)
									END
								ELSE
									BEGIN
										SELECT @SonNum = SonNum FROM BType WHERE TypeId = @MBTypeId2 AND Deleted = 0
										IF @SonNum >= 1
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.ParID = '+CHAR(39)+ISNULL(@MBTypeID2,'')+CHAR(39)
										ELSE
											SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.TypeID LIKE '+CHAR(39)+ISNULL(@MBTypeID2,'')+'%'+CHAR(39)											
									END								
							END
					END
				ELSE			
					BEGIN	
						IF @MBTypeID = ''	--判断客户的范围
							BEGIN
								SELECT @SonNum = 1
								SELECT @BTypeID1 = '00001'
							END
						ELSE	
							BEGIN
								SELECT @SonNum = SonNum FROM BType WHERE TypeID = @MBTypeID AND Deleted = 0
								IF @SonNum >= 1
									SELECT @SonNum = 1
								ELSE
									SELECT @SonNum = 0
								SELECT @BTypeID1 = @MBTypeID
							END
						--=====================================构造@MBSQL_WHERE的条件(客户)
						IF @BTypeAll = 1
							BEGIN
								IF @SonNum = 1				
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.ParID = '+CHAR(39)+ISNULL(@BTypeID1,'')+CHAR(39)								
								ELSE
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND ( a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID1,'')+'%'+CHAR(39)
							END
						--=====================================构造@MBSQL_WHERE的条件(客户)

						IF @MBTypeID2 = ''	--判断供应商的范围
							BEGIN
								SELECT @BSonNum2 = 1
								SELECT @BTypeID2 = '00002'
							END
						ELSE	
							BEGIN
								SELECT @BSonNum2 = SonNum FROM BType WHERE TypeID = @MBTypeID2 AND Deleted = 0
								IF @BSonNum2 >= 1
									SELECT @BSonNum2 = 1
								ELSE
									SELECT @BSonNum2 = 0
								SELECT @BTypeID2 = @MBTypeID2
							END
						--=====================================构造@MBSQL_WHERE的条件(供应商)
						IF @BSonNum2 = 1
							BEGIN
								IF @BtypeAll = 1
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR a.ParID = '+CHAR(39)+ISNULL(@BTypeID2,'')+CHAR(39)+' )'
								ELSE
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.ParID = '+CHAR(39)+ISNULL(@BTypeID2,'')+CHAR(39)
							END
						ELSE
							BEGIN
								IF @BTypeAll = 1
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' OR a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID2,'')+'%'+CHAR(39)+' )'	
								ELSE
									SELECT @MBSQL_WHERE = @MBSQL_WHERE + ' AND a.TypeID LIKE '+CHAR(39)+ISNULL(@BTypeID2,'')+'%'+CHAR(39)
							END						
						--=====================================构造@MBSQL_WHERE的条件(供应商)
					END
					
					SELECT @MBSQL_WHERE = @MBSQL_WHERE +' AND ( a.TypeID LIKE '+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' OR a.TypeID LIKE '+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+' ) '		


					SELECT @SQL = @SQL + @MBSQL_WHERE
				--=======================================================================================================判断范围     
             	SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum  ORDER BY   a.UserCode,b.'+@sortfield
		END
      -----------------------------------明细表             
      IF @ifline=1-- #01 明细表加上商品的一些规格，型号，产地等信息
	BEGIN
		SELECT @SQL='
				SELECT bil.billdate,bil.billcode,e.fullname AS empfullname,b.fullname AS bfullname,k.fullname AS kfullname,SUM(ISNULL(a.qty,0)) AS qty,SUM(ISNULL(a.costtotal,0)) AS costtotal,a.ptypeid,a.btypeid,a.ktypeid,
				bil.btypeid,a.etypeid,bil.billnumberid,p.usercode,p.fullname,isnull(p.type,'''') as type,isnull(p.Area,'''') as Area,isnull(p.Standard,'''') as Standard
				FROM inoutstocktable a 
				INNER JOIN billindex bil
					ON a.billnumberid=bil.billnumberid
				INNER JOIN stock k
					ON bil.ktypeid=k.typeid
				INNER JOIN employee e
					ON bil.etypeid=e.typeid
				INNER JOIN btype b
					ON bil.btypeid=b.typeid
				INNER JOIN ptype p
					ON a.ptypeid=p.typeid
				WHERE 	bil.btypeid LIKE'+CHAR(39)+@ptypeid+'%'+CHAR(39)+' 
					AND  a.billtype=126 
					AND bil.redword=0 
					AND bil.draft=0  	
					AND bil.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
					AND bil.billdate<='+CHAR(39)+@enddate+CHAR(39)+' 
					AND ( bil.btypeid LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+' 
					OR bil.btypeid LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'
					SELECT @CurSon=sonnum FROM Btype WHERE TypeId=''+@BtypeID+''
					IF @CurSon=0  
						SELECT @SQL=@SQL+' AND bil.BtypeID='+CHAR(39)+@BtypeID+CHAR(39)+'AND bil.etypeid like '+CHAR(39)+@szetypeid+'%'+CHAR(39)+'AND a.ptypeid like '+CHAR(39)+@szptypeid+'%'+CHAR(39)+'AND bil.ktypeid like '+CHAR(39)+@szktypeid+'%'+CHAR(39)
					ELSE
						SELECT @SQL=@SQL+' AND bil.BtypeID LIKE '+CHAR(39)+@BtypeID+'%'+CHAR(39)+'AND bil.etypeid like '+CHAR(39)+@szetypeid+'%'+CHAR(39)+'AND a.ptypeid like '+CHAR(39)+@szptypeid+'%'+CHAR(39)+'AND bil.ktypeid like '+CHAR(39)+@szktypeid+'%'+CHAR(39)
						SELECT @SQL=@SQL+'  AND k.TypeID LIKE '+CHAR(39)+@MKtypeID+'%'+CHAR(39)+'AND p.TypeID LIKE '+CHAR(39)+@MPtypeID+'%'+CHAR(39)+'AND (b.TypeID LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+'OR b.TypeID LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'   --#-01
					  SELECT @SQL=@SQL+' GROUP BY bil.billdate,bil.billcode,e.fullname,b.fullname,k.fullname,a.ptypeid,a.btypeid,a.ktypeid,
										bil.btypeid,a.etypeid,bil.billnumberid,p.usercode,p.fullname,p.type,p.Area,p.Standard'
	  				   SELECT @SQL=@SQL+' ORDER BY a.'+@sortfield				
	END
   -------------------------------------线性表
        IF @ifline=2 
                   BEGIN
	      SELECT @SQL='SELECT	a.TypeID,
		a.UserCode,
		a.FullName,
		a.sonnum,
	             SUM(ISNULL(b.Qty,0)) AS qty, 
             		SUM(ISNULL(b.CostPrice,0)) AS CostPrice, 
	             SUM(ISNULL(b.CostTotal,0)) AS CostTotal
             		FROM	BType a      LEFT JOIN
		             ( 
	        			SELECT	ISNULL(a.Qty,0) AS qty, 
					b.BTypeID, 		          	             		a.CostPrice, 
		             		              a.CostTotal
	        			FROM	InOutStockTable   a,BillIndex b
		  	             WHERE   a.BillNumberId=b.BillNumberId
  		                           AND b.Draft=0
		                           AND b.RedWord=0
	                                        AND a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'											
											AND b.etypeid like'+CHAR(39)+@szetypeid+'%'+CHAR(39)+'
											AND a.ptypeid like'+CHAR(39)+@szptypeid+'%'+CHAR(39)+'
											AND b.ktypeid like'+CHAR(39)+@szktypeid+'%'+CHAR(39)+'
		                           			AND b.BillType=126
											AND (b.btypeid like'+CHAR(39)+@MBTypeID+'%'+CHAR(39)+' or b.btypeid like'+CHAR(39)+@MBTypeID2+'%'+CHAR(39)+')   --#-01
											AND a.pTypeID like '+CHAR(39)+@MPTypeID+'%'+CHAR(39)+'
											AND b.kTypeID like '+CHAR(39)+@MKTypeID+'%'+CHAR(39)+'
                     ) b
                     ON	  a.TypeID = b.BTypeID'
	     
	       IF @btypeid='00002'
			SELECT @SQL=@SQL+' WHERE  a.typeid LIKE '+CHAR(39)+@btypeid+'%'+CHAR(39)+'  AND a.typeid<>'+CHAR(39)+'00001'+CHAR(39)+' AND a.sonnum=0'+' AND a.deleted=0 AND (a.typeid LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+' OR a.typeid LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'
	       IF @btypeid='00000'
			SELECT @SQL=@SQL+' WHERE a.sonnum=0'+' AND a.deleted=0 AND (a.typeid LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+' OR a.typeid LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'
	       IF @btypeid<>'00000' AND @btypeid<>'00002' AND @isSon=1
			SELECT @SQL=@SQL+' WHERE a.typeid  LIKE  '+CHAR(39)+@btypeid+'%'+CHAR(39)+' AND a.sonnum=0'+' AND a.deleted=0 AND (a.typeid LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+' OR a.typeid LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'
	       IF @btypeid<>'00000' AND @btypeid<>'00002' AND @isSon=0
			SELECT @SQL=@SQL+' WHERE a.typeid  = '+CHAR(39)+@btypeid+CHAR(39)+' AND a.deleted=0 AND (a.typeid LIKE '+CHAR(39)+@MBtypeid+'%'+CHAR(39)+' OR a.typeid LIKE '+CHAR(39)+@MBtypeid2+'%'+CHAR(39)+')'
  	       IF @showZero=0
		SELECT @SQL=@SQL+' AND qty<>0'
                     SELECT @SQL=@SQL+' GROUP BY a.TypeID, a.UserCode, a.FullName,a.sonnum  ORDER BY   b.'+@sortfield

                   END
         END
END
       IF @sorttype=1
            SELECT @SQL=@SQL+ ' ASC'
       IF @sorttype=0
            SELECT @SQL=@SQL+ ' DESC'    
-----------------------------------执行SQL 
--PRINT (@SQL)
EXEC(@SQL)






























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SearchOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SearchOrderBill]
GO

/*
	作者：谢吉康
	日期：2007-3-7
	描述：销售、采购订单的查询
*/
--作者：鲁大林
--日期：2012-05-22
--描述：【修改】添加币别
/*
	修改：舒珊
	日期：2016年2月23日15:59:00
	描述：增添表头自定义显示字段
*/
/*
	修改：舒珊
	日期：2016年4月14日15:43:00
	描述：增添制单时间checkTime
*/

/*
    修改: 魏伟
    日期: 2015-05-23
    描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_ManPTypeInCategoryID
*/

/*
    修改: 舒珊
    日期: 2015-05-31
    描述: 增加表头新增的自定义字段查询
*/
CREATE                                 PROCEDURE [Gp_SearchOrderBill]            ----订单查询和统计 肖伟 2002-7-12
(
	@chvOperatorID  	VARCHAR(50),
	@chrOrderType 		CHAR(10),                        --Sale OR Buy  
	@dtmStartDate 		VARCHAR(30),
	@dtmEndDate 		VARCHAR(30),
	@dtmReachStartDate 	VARCHAR(30),
	@dtmReachENDDate 	VARCHAR(30),
	@chvBillCode 		VARCHAR(200)='',
	@chvEtype 			VARCHAR(MAX)='',
	@chvBtype 			VARCHAR(MAX)='',
	@chvKtype 			VARCHAR(MAX)='',
	@chvPtype 			VARCHAR(MAX)='',
	@chvstype 			VARCHAR(MAX)='',
	@chvComment 		VARCHAR(256)='',
	@chvExplain 		VARCHAR(256)='',
	@chvWayBillCode 	VARCHAR(200)='',
	@chvTel 			VARCHAR(60)='',
	@chvGoodsNumber 	VARCHAR(20)='',
	@chvPackWay 		VARCHAR(50)='',
	@chvBeiZhu 			VARCHAR(256)='',
	@chrOpType 			CHAR(20),                       --操作类型
	@INTOrderSortType 	int,                            --1.已引用未完成订单 2.已完成订单 3.中止订单 4.未引用订单 0.全部订单
	@strSortField		VARCHAR(100)='BillDate',		--排序字段	
	@strSortType		VARCHAR(100)='DESC',			--排序类型  ASC升序 DESC降序
	@userCode           VARCHAR(200)='',
	@fullName           VARCHAR(200)='',
	@shzt				VARCHAR(10)='9',				--审核状态
	@cid				VARCHAR(10)	,					--币别
	@dtypeid            VARCHAR(max),					-- 新增部门控制 
	@IsReporting		INT,				--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@ptypecategoryid VARCHAR(MAX )     --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL VARCHAR(MAX)
SET @SQL=''

DECLARE @TEMP_SQL VARCHAR(2000)
--------------------------------------------------------初始传入数据---------------------------------------------------------
IF @chvBillCode='' SET @chvBillCode='%' ELSE SET @chvBillCode ='%'+ @chvBillCode +'%'
IF @chvComment='' SET @chvComment='%' ELSE SET @chvComment='%'+ @chvComment +'%'
IF @chvExplain='' SET @chvExplain='%' ELSE SET @chvExplain='%'+ @chvExplain +'%'
IF @chvWayBillCode='' SET @chvWayBillCode='%' ELSE SET @chvWayBillCode='%'+ @chvWayBillCode +'%'
IF @chvTel='' SET @chvTel='%' ELSE SET @chvTel='%'+ @chvTel +'%'
IF @chvGoodsNumber='' SET @chvGoodsNumber='%' ELSE SET @chvGoodsNumber='%'+ @chvGoodsNumber +'%'
IF @chvPackWay='' SET @chvPackWay='%' ELSE SET @chvPackWay='%'+ @chvPackWay +'%'   
IF @chvBeiZhu='' SET @chvBeiZhu='%' ELSE SET @chvBeiZhu='%'+@chvBeiZhu+'%'

--商品
CREATE TABLE #Ptype 
(
	TypeID		VARCHAR(50),
	UserCode	VARCHAR(200),
	FullName VARCHAR(200)
)CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeID)
IF @chrOpType='SearchOrder'
BEGIN
	INSERT INTO #Ptype(TypeId) 
	SELECT P.TypeId
	FROM F_ManPTypeInCategoryID(@chvOperatorID,@chvPtype,@ptypecategoryid) P
END
ELSE
BEGIN
	INSERT INTO #Ptype(TypeId,UserCode,FullName) 
	SELECT P.TypeId,UserCode,FullName 
	FROM Ptype P 
	INNER JOIN F_ManPTypeInCategoryID(@chvOperatorID,@chvPtype,@ptypecategoryid) P1 ON P.typeId=P1.TypeId
	where p.sonnum=0 
END


CREATE TABLE #PrintRecord
( 
	billnumberid  NUMERIC(10,0),
	PrintCount  int
)
CREATE CLUSTERED INDEX #PrintRecord_P_K ON #PrintRecord(BillNumberId)

IF @chrOrderType='sale'
BEGIN
	INSERT INTO #PrintRecord
	( 
		billnumberid, 
		PrintCount 
	)
	SELECT	p.BillNumberId,
			SUM(p.PrintCount) 
	FROM	dbo.PrintRecord p,
			dbo.OrderIndex O
	WHERE	p.BillNumberId = O.billNumberId			
			AND O.BillDate >= @dtmStartDate
			AND O.BillDate <= @dtmEndDate
			AND p.BillType=300
	GROUP BY p.BillNumberId
END
ELSE
BEGIN
	INSERT INTO #PrintRecord
	( 
		billnumberid, 
		PrintCount 
	)
	SELECT	p.BillNumberId,
			SUM(p.PrintCount) 
	FROM	dbo.PrintRecord p,
			dbo.OrderIndex O
	WHERE	p.BillNumberId = O.billNumberId			
			AND O.BillDate >= @dtmStartDate
			AND O.BillDate <= @dtmEndDate
			AND p.BillType=301
	GROUP BY p.BillNumberId
END

-----------------往来权限临时表-------------------------------
CREATE TABLE #btype_l(Typeid VARCHAR(50))
--CREATE CLUSTERED INDEX CIX_btype_l ON #btype_l(TypeId) 

IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorID AND MangerBTypeID = '00001')
		INSERT INTO #btype_l(Typeid) SELECT TypeID FROM BType WHERE SonNum = 0 AND TypeId LIKE '00001%'
	ELSE
		INSERT INTO #btype_l(Typeid) 
		SELECT	B.TypeId 
		FROM	BType_L L
		INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @chvOperatorID
				AND B.typeId LIKE '00001%'
				AND L.flag = 1 
				AND B.sonnum = 0				

--供货商
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @chvOperatorID AND MangerBTypeID2 = '00002')
	INSERT INTO #btype_l(Typeid) SELECT TypeID FROM BType WHERE SonNum = 0 AND TypeId LIKE '00002%'
ELSE
	INSERT INTO #btype_l(Typeid) 
	SELECT	B.TypeId 
	FROM	BType_L L
	INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
	WHERE	L.etypeid = @chvOperatorID
			AND B.typeId LIKE '00002%'
			AND L.flag = 1 
			AND B.sonnum = 0
-----------------往来权限临时表end-------------------------------

--往来单位    
CREATE TABLE #Btype (TypeID VARCHAR(50))CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeID)

IF @chvBtype = '00000' OR @chvBtype = '' OR @chvBtype = '%'
	INSERT INTO #Btype(TypeId) SELECT TypeId FROM #btype_l
ELSE
BEGIN
	INSERT INTO #Btype(TypeId)
	SELECT 	DISTINCT A.TypeId 
	FROM 	#btype_l A, 
			(SELECT A FROM dbo.F_Split(@chvBtype,',')) B 
	WHERE	A.TypeId LIKE B.A + '%'
END

DROP TABLE #btype_l

-- 由于复制订单时，客户数据有的没有复制过来,所以插入一个空的记录(对于所有单位或所有客户或所有供货商才查得到）
IF @chvBtype='' OR @chvBtype ='00000'-- OR @chvBtype='00001' OR @chvBtype ='00002'
BEGIN
	INSERT INTO #btype (TypeID)  VALUES ('')
	INSERT INTO #Btype(TypeID) VALUES(null)
END

--职员
CREATE TABLE #Etype (TypeID VARCHAR(50))CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeID)
INSERT INTO #Etype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvEtype,3,@chvOperatorID)
IF @chvEtype=''
BEGIN
	INSERT INTO #Etype(TypeID) VALUES('')
	INSERT INTO #Etype(TypeID) VALUES('00001')
END

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50))CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeID)
INSERT INTO #Ktype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvKType,4,@chvOperatorID)
IF @chvKtype='' OR @chvKtype ='00000'
	INSERT INTO #ktype(typeid) VALUES('')
	
--部门
CREATE TABLE #dtype (TypeID VARCHAR(50))CREATE CLUSTERED INDEX #dtype_P_K ON #dtype(TypeID)
INSERT INTO #dtype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)
IF @dtypeid='' 
	INSERT INTO #dtype(typeid) VALUES('')

--分支机构
CREATE TABLE #stype (TypeID VARCHAR(50))CREATE CLUSTERED INDEX #stype_P_K ON #stype(TypeID)
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvstype,11,@chvOperatorID)
INSERT INTO #stype ( TypeID )VALUES  ( '' )

--查询订单状态
DECLARE @orderBillType INT
SET @orderBillType = 301		--采购订单
IF @chrOrderType = 'sale'		--销售订单
	SET @orderBillType = 300	

CREATE TABLE #AuditingBill
(
	BillNumberId NUMERIC(18,0),
	CheckState	 VARCHAR(50)
)
CREATE CLUSTERED INDEX #AuditingBill_P_K ON #AuditingBill(BillNumberId)

IF @shzt <> '9' --非全部状态(9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据)
	BEGIN
			IF @shzt = '0'	--原始单据
				INSERT INTO #AuditingBill(BillNumberId,CheckState)
				SELECT	B.BillNumberId,
						'原始单据' AS CheckState
				FROM	OrderIndex B			
				WHERE	B.BillDate >= @dtmStartDate
						AND B.BillDate <= @dtmEndDate
						AND B.billtype = @orderBillType
						AND B.billNumberId NOT IN 
						(
							SELECT	A.billNumberId 
							FROM	AuditingBill A
							INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
							INNER JOIN #stype S ON S.TypeID = F.Stypeid											
							WHERE	BillIndexType = 0					
						)
			ELSE
				INSERT INTO #AuditingBill(BillNumberId,CheckState)
				SELECT	A.BillNumberId,
						CASE @shzt
							WHEN '1' THEN '待审核单据'
							WHEN '2' THEN '审核通过单据'
							ELSE '审核不通过单据'
						END AS CheckState
				FROM	AuditingBill A
				INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
				INNER JOIN #stype S ON S.TypeID = F.Stypeid
				WHERE	A.BillDate >= @dtmStartDate
						AND A.BillDate <= @dtmEndDate													
						AND F.IfUse = 1
						AND A.BillIndexType = 0
						AND A.IfAudit = CASE
											WHEN @shzt = '1' THEN '0'
											WHEN @shzt = '2' THEN '1'
											ELSE '-1'
										END		
		--END
	END
ELSE 
	BEGIN
			INSERT INTO #AuditingBill(BillNumberId,CheckState)
			SELECT	A.BillNumberId,
					CASE A.IfAudit
						WHEN 0 THEN '待审核单据'
						WHEN 1 THEN '审核通过单据'
						WHEN -1 THEN '审核不通过单据'
						ELSE ''
					END AS CheckState
			FROM	AuditingBill A
			INNER JOIN AuditingFlowSet F ON A.AuditingId = F.AuditingId AND F.BillType =@orderBillType
			WHERE	
				A.BillIndexType = 0
				AND A.BillDate BETWEEN @dtmStartDate AND @dtmEndDate
	END

--------------------------------------------------------取得数据---------------------------------------------------------
IF @chrOpType='SearchOrder'    --订单查询
BEGIN
	SET  @SQL +=  '
	SELECT ROW_NUMBER() OVER (Order by '+@strSortField+' '+@strSortType+') AS sid,* FROM (
	SELECT	
						a.BillNumberID,
						a.ReachDate,	
						a.BillDate,
						a.checktime,
						a.BillCode,
						a.etypeid AS etypeid,
						a.DealBTypeID,
						a.btypeid as btypeid,
						states.StateName,
						a.orderstate,
						a.CustomerTotal, 
						a.NCustomerTotal,
						Convert( NUMERIC(24, 10) ,isnull(a.TotalQty,0)) as OrderQty,
						Convert( NUMERIC(24, 10) ,isnull(a.TotalMoney,0)) as OrderMoney,
						Convert( NUMERIC(24, 10) ,O.ReachQty) AS ReachQty, /*已发货数量 || 已到货数量 */
						O.locknumber as locknumber,/*已锁定数量*/
						Convert( NUMERIC(24, 10) ,O.ReachMoney) AS  ReachMoney, /*已发货金额 || 已到货金额*/
						NoReachQty=Convert( NUMERIC(24, 10) ,A.TotalQty-ISNULL(O.ReachQty,0)),
						NoReachMoney=Convert( NUMERIC(24, 10) ,A.TotalMoney)-Convert( NUMERIC(24, 10) ,O.ReachMoney),
						a.Comment,
						a.BillOver AS IFStop,
						a.Billtype,
						A.stypeid,
						a.checke,
						case WHEN a.isyapi=1 THEN ''云分销订单'' ELSE ''正常订单'' END AS type,
						a.isyapi,
						CASE
							WHEN ISNULL(AB.CheckState,'''') = '''' THEN ''原始单据''
							ELSE AB.CheckState
						END AS CheckState,
						AC.CId AS accrencyid,
						AC.FullName AS accrencyname,
						a.dtypeid,
						a.totalinmoney,
						a.Ntotalinmoney,
						isnull(pri.PrintCount,0)as printcount,
						CASE WHEN T.SALENUMBERID IS NULL THEN 0 ELSE 1 END AS issaleused,--订单下面只要汇总的SaleOrderReachQty 不为0 该销售订单就是被采购订单引用了
						SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
						SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
						SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
						SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
						explain,
						tel,
						goodsnumber as wjsl,
						packway,
						waybillcode,
						O.BillOverNumber,
						O.BillOverTotal
               	FROM OrderIndex a
				INNER JOIN #stype s ON a.stypeid=s.typeid
				INNER JOIN #btype b ON a.dealbtypeid=b.typeid 
				INNER JOIN #etype e ON a.etypeid=e.typeid
				INNER JOIN #dtype d ON a.dtypeid=d.typeid  
				INNER JOIN #ktype k ON a.ktypeid=k.typeid
				INNER JOIN (	/*状态集合*/
       							SELECT	StateName = case dbo.F_GetOrderState(BillNumberID,'+CONVERT (VARCHAR(10),@orderBillType)+')  
       												when ''1'' then ''已引用未完成''
													when ''2'' then ''已完成''
													when ''4'' then ''未引用''
													else '''' end ,
										billnumberid 
										FROM dbo.OrderIndex 
										where BillDate BETWEEN '''+convert(varchar(10),@dtmStartDate,120) +''' AND '''+convert(varchar(10),@dtmENDDate,120)+''' AND billtype='+CAST(@orderBillType AS VARCHAR)+'
       						) states  ON a.billnumberid=states.billnumberid'
	SET @SQL+='
				INNER JOIN 
				(
					SELECT
						A.BillNumberID,
						Convert( NUMERIC(24, 10) ,SUM(ReachQty)) AS ReachQty,
						Convert( NUMERIC(24, 10) ,SUM(ReachTaxTotal)) AS  ReachMoney,
						SUM(isnull(LockNumber,0))  LockNumber,
						SUM(CASE WHEN BillOver=1 THEN qty-ReachQty ELSE 0 END) BillOverNumber,
						SUM(CASE WHEN BillOver=1 THEN total-ReachTotal ELSE 0 END) BillOverTotal
					FROM OrderBill A
					INNER JOIN #PType P ON P.Typeid=a.ptypeid '

	IF @chvBeiZhu<>'%'
				SET @SQL+=' WHERE  a.Comment LIKE '+char(39)+@chvBeiZhu+char(39)
	SET @SQL+='		
					GROUP BY
								A.BillNumberID		
					 )O ON a.billNumberId=O.billNumberID  
				LEFT JOIN Ac_Currency AC ON AC.CId=a.CID  
				LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype  
       			LEFT JOIN #TempData T ON t.SaleNumberID=a.billNumberId 
				left join #PrintRecord pri on  a.billnumberid=pri.billnumberid --加入了打印次数  
				 '    
				 --直接left join时速度很慢，还是提成临时表进行关联	
				SELECT DISTINCT billNumberID SaleNumberID INTO #TempData FROM OrderBill  WHERE OrderID IN (SELECT SaleOrderID FROM OrderBill WHERE SaleOrderID<>0)
	IF @shzt <> '9'
		SET @SQL = @SQL + ' INNER JOIN #AuditingBill AB ON AB.BillNumberId = A.BillNumberId '
	ELSE
		SET @SQL = @SQL + ' LEFT JOIN #AuditingBill AB ON AB.BillNumberId = A.BillNumberId '

	SET @SQL+='WHERE 
				a.BillDate BETWEEN '''+convert(varchar(10),@dtmStartDate,120) +''' AND '''+convert(varchar(10),@dtmENDDate,120) +'''
				AND a.billtype= '+CAST(@orderBillType AS VARCHAR)+'
				AND a.checked=0 '

		IF ISNULL(@dtmReachStartDate,'')<>''
			SET @SQL+=' AND  a.ReachDate>= '+char(39)+convert(varchar(10),@dtmReachStartDate,120) +char(39)
		IF ISNULL(@dtmReachENDDate,'')<>''
			SET @SQL+=' AND a.ReachDate<='+char(39)+convert(varchar(10),@dtmReachENDDate,120)+char(39)
			
					
		IF @cid!=''      
		SET @SQL+=' AND a.CID='+@cid+' ' 	
		
		IF @chvBillCode<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.BillCode like '+char(39)+@chvBillCode +char(39)
		END
		IF @chvComment<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.Comment like '+char(39)+@chvComment+char(39)
		END
		IF @chvExplain<>'%'
		BEGIN
			SET @SQL=@SQL+' AND isnull(a.Explain,'''') like '+char(39)+@chvExplain +char(39)
		END
		IF @chvWayBillCode<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.WayBillCode like '+char(39)+@chvWayBillCode+char(39)
		END
		IF @chvTel<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.Tel like '+char(39)+@chvTel +char(39)
		END
		IF @chvGoodsNumber<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.GoodsNumber like '+char(39)+@chvGoodsNumber +char(39)
		END
		IF @chvPackWay<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.PackWay like '+char(39)+@chvPackWay+char(39)
		END
		
		SET @SQL+=') TT WHERE 1=1'
		IF @intOrderSortType = 1 --已引用未完成
			SET  @SQL+='  and TT.StateName=''已引用未完成'' '
		
		IF @intOrderSortType = 3 --未完成
			SET  @SQL+='  and (TT.StateName=''已引用未完成'' OR  TT.StateName=''未引用'' )'

	    IF @intOrderSortType = 2 --已完成
			SET  @SQL+= '  and TT.StateName=''已完成'' '
			
		IF @intOrderSortType = 4 --未引用
			SET  @SQL +='  and TT.StateName=''未引用'' '
----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--未找到“计算合计”的地方，先不考虑
	IF(@IsReporting = 0)
	BEGIN
		SET @SQL+=' Order by '+@strSortField+' '+@strSortType 
		--PRINT @SQL
		EXEC(@SQL)
	END
	ELSE IF(@IsReporting = 1)
	BEGIN
		CREATE TABLE #tmp_result
		(
			billnumberid VARCHAR(100),
			billtype     VARCHAR(100),
			Costom1		VARCHAR(max),
			Costom2		VARCHAR(max),
			Costom3		VARCHAR(max),
			Costom4		VARCHAR(max),
			Costom5		VARCHAR(max),
			Costom6		VARCHAR(max),
			Costom7		VARCHAR(max),
			Costom8		VARCHAR(max),
			Costom9		VARCHAR(max),
			Costom10	VARCHAR(max),
			Costom11	VARCHAR(max),
			Costom12	VARCHAR(max),
			Costom13	VARCHAR(max),
			Costom14	VARCHAR(max),
			Costom15	VARCHAR(max),
			Costom16	VARCHAR(max)
		)
		SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ' + ' Order by '+@strSortField+' '+@strSortType + 
				  ' 
				   DECLARE @p1 dbo.TBType_SelfType  
				   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
				   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 
				   
					SELECT a.*,
						  b.Costom1,
						  b.Costom2,
						  b.Costom3,
						  b.Costom4,
						  b.Costom5,
						  b.Costom6,
						  b.Costom7,
						  b.Costom8,
						  b.Costom9,
						  b.Costom10,
						  b.Costom11,
						  b.Costom12,
						  b.Costom13,
						  b.Costom14,
						  b.Costom15,
						  b.Costom16 
						  FROM #temp1 a 
						  left join #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
					
					DROP TABLE #temp1,#tmp_result'
		--PRINT @SQL	
		EXEC(@SQL)
	END
----------------------------------------------------------
END
--***************************************************************************订单汇总***************************************************************--		
IF @chrOpType='GatherOrder'          
BEGIN
	DECLARE @SQL_WHERE VARCHAR(2000)
	SET @SQL_WHERE=''
	IF @userCode<>''
		SET @SQL_WHERE=@SQL_WHERE+' WHERE P.userCode LIKE '+CHAR(39)+'%'+@userCode+'%'+CHAR(39)
	IF @fullName<>''
		IF @SQL_WHERE=''
			SET @SQL_WHERE=' WHERE P.fullName LIKE '+CHAR(39)+'%'+@fullName+'%'+CHAR(39)
		ELSe
			SET @SQL_WHERE=@SQL_WHERE+' AND P.fullName LIKE '+CHAR(39)+'%'+@fullName+'%'+CHAR(39)
		
	SET @TEMP_SQL =''
	IF @INTOrderSortType = 1
		SET  @TEMP_SQL = @TEMP_SQL + ' AND o.BillnumberID IN ( SELECT BillnumberID FROM OrderBill WHERE ReachQty<Qty)'
	IF @INTOrderSortType = 2
		SET  @TEMP_SQL = @TEMP_SQL + ' AND o.BillnumberID NOT IN ( SELECT BillnumberID FROM OrderBill WHERE ReachQty<Qty)'

	CREATE TABLE #OrderBill(BillNumberId numeric(10,0))

	SET @SQL ='	INSERT INTO #OrderBill(BillNumberId) SELECT DISTINCT O.BillNumberId
				FROM	OrderBill O 
				INNER JOIN (SELECT BillnumberID FROM OrderBill  WHERE Comment LIKE '+CHAR(39)+@chvBeiZhu+CHAR(39) + ' ) T  '
				
	IF NOT (@chvPtype ='' AND @MPtypeid = '00000' AND @ptypecategoryid='')
		SET @SQL =@SQL+'  INNER JOIN (SELECT BillnumberID FROM OrderBill  INNER JOIN #PType P ON OrderBill.PTypeId = P.TypeId )  P  ON P.BillnumberID=T.BillnumberID  '

	SET @SQL =@SQL+'  ON O.BillNumberId=T.BillnumberID   ' 

	IF @INTOrderSortType = 1
		SET  @SQL = @SQL + '  WHERE o.BillnumberID IN ( SELECT BillnumberID FROM OrderBill WHERE ReachQty<Qty)'
		
	IF @INTOrderSortType = 2
		SET  @SQL = @SQL + '  WHERE o.BillnumberID NOT IN ( SELECT BillnumberID FROM OrderBill WHERE ReachQty<Qty)'

	--PRINT @SQL
	EXEC(@SQL) 

	SET @SQL=' SELECT	p.usercode,
						p.fullname,
						p.typeid,
						I.OrderQty,
						I. OrderMoney,
						I.ReachQty,
						I.ReachMoney 
						FROM 
						(SELECT x.ptypeid,
						sum(x.Qty) as OrderQty,
						sum(isnull(x.TaxTotal,0)) as OrderMoney,
						sum(x.ReachQty) as ReachQty,
						sum(isnull(x.TaxTotal/x.Qty*x.ReachQty,0)) as ReachMoney 
				FROM (
						SELECT	DISTINCT x.BillNumberID,x.PTypeID,x.OrderID,x.Qty,x.TaxTotal,x.ReachQty
						FROM	OrderIndex a 
						INNER JOIN OrderBill x  ON A.BillNumberId=X.BillNumberId 
						INNER JOIN #OrderBill TOrder ON x.BillNumberID=TOrder.BillNumberId  '

	IF NOT (@chvBtype = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' INNER JOIN #btype b on (a.dealbtypeid=b.typeid 	OR a.dealbtypeid IS NULL OR a.dealbtypeid='''') '

	IF NOT (@chvEType= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' INNER JOIN #etype e on (a.etypeid=e.typeid or a.etypeid=''00001'') '

	IF NOT (@chvKType = '' AND @MKTypeId = '00000')
		SET @SQL =@SQL+' INNER JOIN #ktype k on (a.ktypeid=k.typeid		OR a.KTypeID='''') '
		

		 SET @SQL = @SQL +' INNER JOIN #dtype d on (a.dtypeid=d.typeid) '
	     
	SET @SQL =@SQL+'WHERE	a.BillCode like '+CHAR(39)+@chvBillCode+'%'+CHAR(39)+'
							AND a.Comment like ' +CHAR(39)+@chvComment+'%'+CHAR(39)+'
							AND a.Explain like ' +CHAR(39)+@chvExplain+'%'+CHAR(39)+' 
		    				AND a.WayBillCode like '+CHAR(39)+@chvWayBillCode+'%'+CHAR(39)+'
							AND a.Tel like '+CHAR(39)+@chvTel+'%'+CHAR(39)+'
							AND a.GoodsNumber like '+CHAR(39)+@chvGoodsNumber+CHAR(39)+'
							AND a.PackWay like '+CHAR(39)+@chvPackWay+'%'+CHAR(39)
							
				SET @SQL = @SQL +' 
		    				AND a.BillDate>='+CHAR(39)+convert(VARCHAR(50),@dtmStartDate)+CHAR(39)+'
							AND a.BillDate<='+CHAR(39)+convert(VARCHAR(50),@dtmEndDate)+CHAR(39)+'
							AND a.checked=0 '
							
				SET @SQL = @SQL +'	
							AND a.billtype= case '+CHAR(39)+@chrOrderType+CHAR(39)+ ' when '+CHAR(39)+'Sale'+CHAR(39)+' then '+CHAR(39)+'300'+CHAR(39)+' else '+CHAR(39)+'301'+CHAR(39)+' END '
							
				IF ISNULL(@dtmReachStartDate,0)<>''
					SET @SQL = @SQL + '
						AND a.ReachDate>='+CHAR(39)+convert(VARCHAR(10),@dtmReachStartDate,120)+CHAR(39)
				IF @dtmReachENDDate<>''
					SET @SQL = @SQL + '
						AND a.ReachDate<='+CHAR(39)+convert(VARCHAR(10),@dtmReachENDDate,120)+CHAR(39)
				SET @SQL = @SQL +'
					AND ( a.BillOver = CASE '+convert(VARCHAR(10),@INTOrderSortType) +' WHEN 1 THEN 0 WHEN 2 THEN 0 WHEN 0 THEN 0 WHEN 3 THEN 1 END
					   OR a.BillOver = CASE '+convert(VARCHAR(10), @INTOrderSortType)+' WHEN 1 THEN 0 WHEN 2 THEN 0 WHEN 0 THEN 1 WHEN 3 THEN 1 END ) 
			) x '
		
	SET @SQL =@SQL+ ' GROUP by  x.ptypeid ) I INNER JOIN  ptype p ON (I.ptypeid=p.typeid)  ' +@SQL_WHERE  + ' order by 	Usercode '
	
	--PRINT @SQL
	EXEC(@SQL)
END	
--PRINT @SQL
DROP TABLE #Ptype,#Btype,#Etype,#Ktype,#stype,#dtype,#AuditingBill,#PrintRecord

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SearchPriceProtectper]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SearchPriceProtectper]
GO




















--=======================
--作者：haiquan 引用 xjk写法
--日期：2005-01-04
--描述：重写算法

--作者：xuhui
--日期：2011-04-01
--描述：加分支机构，数量要加分支机构限制
--=======================
CREATE               PROCEDURE [Gp_SearchPriceProtectper] 
(
	@OperatorID 	varchar(100),	--当前操作员的ID
	@StartDate    	datetime,	--开始日期
	@EndDate     	datetime,	--截止日期
	@PTypeId       	varchar(100),	--商品ID
	@BTypeId       	varchar(100),	--客户ID 
	@BTypeId2     	varchar(100),	--供应商ID
	@ETypeId       	varchar(100),	--经手人ID
	@State	        int,			--1.有效   0.无效
	@Query			char(1)	= '',	--1.调入价保时用	
	@BillType 		varchar(10),		--单据类型  149.价保执行  151.获得价保
	@CurId			INT,  			--价保id号
	@STypeId       	varchar(50)		--分支机构ID
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #stypeid(typeid VARCHAR(100))
IF @STypeId=''
	INSERT #stypeid (typeid ) SELECT typeid FROM F_GetManDetailSType(@OperatorID) 
ELSE
	INSERT #stypeid (typeid ) SELECT typeid FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

DECLARE @Value int
SELECT	@Value = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

IF @Value = 1
	BEGIN
		IF @BTypeId = '00001'
			SET @BTypeId = '00000'

		IF @BTypeId2 = '00002'
			SET @BTypeId2 = '00000'
	END

IF @PTypeId = '00000'
	SET @PTypeId = '%'

IF @BTypeId = '00000'
	SET @BTypeId = '%'

IF @BTypeId2 = '00000'
	SET @BTypeId2 = '%'

CREATE TABLE #PriceProtect
(
	PriceId		int,
	UserCode	varchar(1000),
	PFullName	varchar(1000),
	BFullName	varchar(1000),
	OldPrice	 NUMERIC(24, 10) ,
	NewPrice	 NUMERIC(24, 10) ,
	StartDate	datetime,
	EndDate		datetime,
	[Date]		datetime,
	State		varchar(10),
	WriteDate	datetime,
	FullName	varchar(1000),
	SaleQty		 NUMERIC(24, 10) ,
	OldTotal	 NUMERIC(24, 10) ,
	BillType	int
)

DECLARE	@PriceId 	int,
		@PPTypeId	varchar(50),
		@BBTypeId	varchar(50),
		@OldPrice	 NUMERIC(24, 10) ,
		@NewPrice	 NUMERIC(24, 10) ,
		@Date		datetime,
		@WriteDate	datetime,
		@WriteId	varchar(50),
		@SState		varchar(10),
		@SStartDate	datetime,
		@EEndDate	datetime,
		@BBillType	int,
	
		@PUserCode	varchar(1000),
		@PFullName	varchar(1000),
		@BFullName	varchar(1000),
		@EFullName	varchar(1000),
		@SaleQty	 NUMERIC(24, 10) ,
		@OldTotal	 NUMERIC(24, 10) 

	IF @Query = ''
			SELECT	@PriceId=PriceId,
					@PPTypeId=PTypeId,
					@BBTypeId=BTypeId,
					@OldPrice=OldPrice,
					@NewPrice=NewPrice,
					@Date=[Date],
					@WriteDate=WriteDate,
					@WriteId=WriteId,
					@SState=State,
					@SStartDate=StartDate,
					@EEndDate=EndDate,
					@BillType=BillType
			FROM	PriceProtect
			WHERE	BillType = @BillType
					AND PTypeId LIKE @PTypeId + '%'
					AND (BTypeId LIKE @BTypeId + '%' OR BTypeId LIKE @BTypeId2 + '%')
					AND WriteId LIKE @ETypeId + '%'
					AND StartDate>=@StartDate
					AND EndDate<=@EndDate
					AND BTypeId LIKE CASE
										WHEN @BillType = 149 THEN @BTypeId + '%'
										ELSE @BTypeId2 + '%'
									 END
					AND (BTypeId LIKE @BTypeId + '%' OR BTypeId LIKE @BTypeId2 + '%')
					AND PriceId=@CurId
	ELSE

			SELECT	@PriceId=PriceId,
					@PPTypeId=PTypeId,
					@BBTypeId=BTypeId,
					@OldPrice=OldPrice,
					@NewPrice=NewPrice,
					@Date=[Date],
					@WriteDate=WriteDate,
					@WriteId=WriteId,
					@SState=State,
					@SStartDate=StartDate,
					@EEndDate=EndDate,
					@BillType=BillType
			FROM	PriceProtect
			WHERE	BillType = @BillType
					AND PTypeId LIKE @PTypeId + '%'
					AND (BTypeId LIKE @BTypeId + '%' OR BTypeId LIKE @BTypeId2 + '%')
					AND WriteId LIKE @ETypeId + '%'
					AND StartDate<=@EndDate
					AND EndDate>=@StartDate
					AND BTypeId LIKE CASE
										WHEN @BillType = 149 THEN @BTypeId + '%'
										ELSE @BTypeId2 + '%'
									 END
					AND (BTypeId LIKE @BTypeId + '%' OR BTypeId LIKE @BTypeId2 + '%')
					AND PriceId=@CurId



			SELECT	@PUserCode = UserCode,@PFullName = FullName FROM PType WHERE TypeId = @PPTypeId

			SELECT	@BFullName = FullName FROM BType WHERE TypeId = @BBTypeId

			SELECT	@EFullName = FullName FROM Employee WHERE TypeId = @WriteId

			--计算数量	

	IF @BillType = 149
				SELECT  @SaleQty =-1* ISNULL(SUM(A.Qty),0)
				FROM	(
							SELECT 	
									K.BillNumberId,
									ISNULL(K.Qty,0) AS Qty
							FROM 	InOutStockTable K
							LEFT JOIN PriceProtect L ON k.PtypeId=L.Ptypeid
							LEFT JOIN BillIndex bi ON K.BillNumberId=bi.BillNumberId
							WHERE 	K.BillType IN (11,305,45,141,160,215)
									AND K.BillDate>=@SStartDate
									AND K.BillDate<=@EEndDate
									AND K.PTypeId = @PPTypeId 
									AND bi.BTypeID = @BBTypeId 
									AND K.Audited = 1	
									AND L.PriceId = @PriceId	
									AND k.stypeid IN(SELECT typeid FROM  #stypeid)					
						)A
			ELSE
				SELECT	@SaleQty = ISNULL(SUM(A.QTY),0)
				FROM	(
							SELECT	
									ISNULL(X.QTY,0) AS Qty,
									X.BillNumberId
							FROM 	InOutStockTable X									
							LEFT JOIN PriceProtect Y ON X.PTypeId = Y.PTypeId
							LEFT JOIN BillIndex bi ON X.BillNumberId=bi.BillNumberId
							WHERE 	X.BillType IN (34,6,161)
									AND X.BillDate>=@SStartDate
									AND X.BillDate<=@EEndDate
									AND X.PTypeId = @PPTypeId 
									AND bi.BTypeID = @BBTypeId  
									AND X.Audited = 1
									AND Y.PriceId = @PriceId	
									AND X.stypeid IN(SELECT typeid FROM  #stypeid)					
							UNION ALL
							SELECT	
									ISNULL(ABS(M.QTY),0) AS Qty,
									M.BillNumberId
							FROM 	InOutStockTable M
							LEFT JOIN PriceProtect N ON M.PTypeId = N.PTypeId
							LEFT JOIN BillIndex bi ON M.BillNumberId=bi.BillNumberId
							WHERE	M.BillType=145
									AND M.BillDate>=@SStartDate
									AND M.BillDate<=@EEndDate
									AND M.PTypeId = @PPTypeId 
									AND bi.BTypeID = @BBTypeId 
									AND M.Audited = 1
									AND N.PriceId = @PriceId
									AND M.stypeid IN(SELECT typeid FROM  #stypeid)		
				)A

			--计算金额
			SELECT  @OldTotal = 0
			SELECT 	@OldTotal = ISNULL(OldTotal,0)
			FROM 	PriceProtectList 
			WHERE	PTypeId = @PPTypeId
					AND BTypeId = @BBTypeId
			

			--处理是否有效
			IF CONVERT(varchar(10),@Date,120) >= CONVERT(varchar(10),GETDATE(),120)
				SET @SState = '有效'
			ELSE
				SET @SState = '无效'

			INSERT INTO #PriceProtect
			(
				PriceId,
				UserCode,
				PFullName,
				BFullName,
				OldPrice,
				NewPrice,
				StartDate,
				EndDate,
				[Date],
				State,
				WriteDate,
				FullName,
				SaleQty,
				OldTotal,
				BillType
			)VALUES(
				@PriceId,
				@PUserCode,
				@PFullName,
				@BFullName,
				@OldPrice,
				@NewPrice,
				@SStartDate,
				@EEndDate,
				@Date,
				@SState,
				@WriteDate,
				@EFullName,
				ISNULL(@SaleQty,0),
				ISNULL(@OldTotal,0),
				@BillType
			)


IF @State = 1
	SELECT *FROM #PriceProtect WHERE CONVERT(varchar(10),Date,120) >= CONVERT(varchar(10),GETDATE(),120) ORDER BY [Date] DESC
ELSE
	SELECT * FROM #PriceProtect WHERE CONVERT(varchar(10),Date,120) < CONVERT(varchar(10),GETDATE(),120)  ORDER BY [Date] DESC


DROP TABLE #PriceProtect




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SearchPriceProtectStandard]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SearchPriceProtectStandard]
GO

--=======================
--作者：徐辉
--日期：2011-04-02
--描述：重写
--=======================
CREATE          PROCEDURE [Gp_SearchPriceProtectStandard] 
(
	@OperatorID 	varchar(100),	--当前操作员的ID
	@StartDate    	datetime,		--开始日期
	@EndDate     	datetime,		--截止日期
	@PTypeId       	varchar(8000),	--商品ID
	@BTypeId       	varchar(8000),	--客户ID 
	@BTypeId2     	varchar(8000),	--供应商ID
	@ETypeId       	varchar(8000),	--登记人ID
	@State	        int,			--1.有效   0.无效
	@Query			char(1)	= '',	--1.调入价保时用	
	@BillType 		varchar(10),	--单据类型  149.价保执行  151.获得价保
	@STypeid		varchar(max)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)

--删除服务类商品
DELETE #GetManPTypeId WHERE TypeId IN (SELECT p.typeId FROM ptype p WHERE p.IsService = 1)

--客户
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@Btypeid,2,@OperatorID)

--供货商
CREATE TABLE #GetManBTypeId2(TypeId	varchar(100))
INSERT INTO #GetManBTypeId2(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@Btypeid2,2,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)
--所有职员能看到超级用户建立的价保通知
--INSERT #GetManETypeId (TypeId ) VALUES ( '00001' )  9.1版本调整，去掉该特性 


--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

IF @State <> 1
	SET @State=0

IF @Query = '' --价保通知设置
	SELECT a.*,
	b.UserCode AS usercode,b.FullName AS pfullname, c.FullName AS bfullname,CAST(b.ifusegoodsnum AS INT) AS ifusegoodsnum,
	CASE WHEN a.StateFlag=1 THEN '有效' ELSE '无效' END AS [state] 
	FROM (
			SELECT	PriceId,
					PTypeId,
					BTypeId,
					OldPrice,
					NewPrice,
					[Date],
					WriteDate,
					WriteId,
					StartDate,
					EndDate,
					BillType,
					fullname=(SELECT fullname FROM employee WHERE typeid=WriteId),
					StypeID,
					CASE WHEN CONVERT(varchar(10),[Date],120) >= CONVERT(varchar(10),GETDATE(),120) THEN 
						1
					ELSE
						0
					END  AS [StateFlag]
			FROM	PriceProtect
			WHERE	BillType = @BillType
					AND PTypeId IN (SELECT TypeId FROM #GetManPTypeId)
					AND (BTypeId IN (SELECT TypeId FROM #GetManBTypeId2))
					AND StartDate>=@StartDate
					AND EndDate<=@EndDate
					AND (STypeId IN (SELECT * FROM #GetManSTypeId)  OR StypeID='')
					AND (WriteId IN (SELECT typeid FROM #GetManETypeId))
		) a
	LEFT JOIN ptype b ON a.PTypeId=b.typeId
	LEFT JOIN btype c ON a.BTypeId=c.typeId
	WHERE a.[StateFlag]=@State
	ORDER BY a.[Date] DESC
ELSE --调入价保通知
		SELECT a.*,e.typeid AS etypeid,e.fullname AS efullname,d.typeid AS dtypeid,d.fullname AS dfullname,
	b.UserCode AS usercode,b.FullName AS pfullname, c.FullName AS bfullname,
	b.customitemid ,
	b.customitemfrom ,
	b.customitemname,
	b.customitemrefid,	
	CAST(b.ifusegoodsnum AS INT) AS ifusegoodsnum,
	(select denominatedid from btype where typeId=a.BTypeId) as denid,
	(select fullname from btype where typeId=(select denominatedid from btype where typeId=a.BTypeId)) as denname,
	CASE WHEN a.StateFlag=1 THEN '有效' ELSE '无效' END AS [state] 
	FROM (
			SELECT	PriceId,
					PTypeId,
					BTypeId,
					OldPrice,
					NewPrice,
					[Date],
					WriteDate,
					WriteId,
					StartDate,
					EndDate,
					BillType,
					
					fullname=(SELECT fullname FROM employee WHERE typeid=WriteId),
					StypeID,				
					CASE WHEN CONVERT(varchar(10),[Date],120) >= CONVERT(varchar(10),GETDATE(),120) THEN 
						1
					ELSE
						0
					END  AS [StateFlag]
			FROM	PriceProtect
			WHERE	BillType = @BillType
					AND PTypeId IN (SELECT TypeId FROM #GetManPTypeId)
					AND (BTypeId IN (SELECT TypeId FROM #GetManBTypeId))
					AND StartDate<=@EndDate
					AND EndDate>=@StartDate
					AND (STypeId IN (SELECT * FROM #GetManSTypeId)  OR StypeID='')
					AND (WriteId IN (SELECT typeid FROM #GetManETypeId))
		) a
	LEFT JOIN ptype b ON a.PTypeId=b.typeId
	LEFT JOIN btype c ON a.BTypeId=c.typeId
	LEFT JOIN Employee e ON c.etypeid=e.typeid
	LEFT JOIN Department d ON d.typeid=e.dtypeid 
	WHERE a.[StateFlag]=@State
	ORDER BY a.[Date] DESC


DROP TABLE #GetManPTypeId,#GetManBTypeId,#GetManBTypeId2,#GetManETypeId,#GetManSTypeId





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SearchPT_Combin_OrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SearchPT_Combin_OrderBill]
GO

 
CREATE                                 PROCEDURE [Gp_SearchPT_Combin_OrderBill]          
(
	@chvOperatorID  	VARCHAR(50),
	@chrOrderType 		CHAR(10),                        --Sale OR Buy  
	@dtmStartDate 		VARCHAR(30),
	@dtmEndDate 		VARCHAR(30),
	@dtmReachStartDate 	VARCHAR(30),
	@dtmReachENDDate 	VARCHAR(30),
	@chvBillCode 		VARCHAR(200)='',
	@chvEtype 			VARCHAR(1550)='',
	@chvBtype 			VARCHAR(1550)='',
	@chvKtype 			VARCHAR(1550)='',
	@chvPtype 			VARCHAR(1550)='',
	@chvstype 			VARCHAR(1550)='',
	@chvComment 		VARCHAR(256)='',
	@chvExplain 		VARCHAR(256)='',
	@chvWayBillCode 	VARCHAR(200)='',
	@chvTel 			VARCHAR(60)='',
	@chvGoodsNumber 	VARCHAR(20)='',
	@chvPackWay 		VARCHAR(50)='',
	@chvBeiZhu 			VARCHAR(256)='',
	@chrOpType 			CHAR(20),                       --操作类型
	@INTOrderSortType 	int,                            --1.已引用未完成订单 2.已完成订单 3.中止订单 4.未引用订单 0.全部订单
	@strSortField		VARCHAR(100)='BillDate',		--排序字段	
	@strSortType		VARCHAR(100)='DESC',			--排序类型  ASC升序 DESC降序
	@userCode           VARCHAR(200)='',
	@fullName           VARCHAR(200)='',
	@shzt				VARCHAR(10)='9',				--审核状态
	@cid				VARCHAR(10)	,					--币别
	@dtypeid            VARCHAR(max),					-- 新增部门控制 
	@IsReporting		INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL VARCHAR(MAX)
SET @SQL=''

-- 增加客户供货商统一判断
DECLARE @BTypeAll VARCHAR(50), @MBTypeID_Temp VARCHAR(50)
SELECT @BTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'
DECLARE @TEMP_SQL VARCHAR(2000)
--------------------------------------------------------初始传入数据---------------------------------------------------------
IF @chvBillCode='' SET @chvBillCode='%' ELSE SET @chvBillCode ='%'+ @chvBillCode +'%'
IF @chvComment='' SET @chvComment='%' ELSE SET @chvComment='%'+ @chvComment +'%'
IF @chvExplain='' SET @chvExplain='%' ELSE SET @chvExplain='%'+ @chvExplain +'%'
IF @chvWayBillCode='' SET @chvWayBillCode='%' ELSE SET @chvWayBillCode='%'+ @chvWayBillCode +'%'
IF @chvTel='' SET @chvTel='%' ELSE SET @chvTel='%'+ @chvTel +'%'
IF @chvGoodsNumber='' SET @chvGoodsNumber='%' ELSE SET @chvGoodsNumber='%'+ @chvGoodsNumber +'%'
IF @chvPackWay='' SET @chvPackWay='%' ELSE SET @chvPackWay='%'+ @chvPackWay +'%'   
IF @chvBeiZhu='' SET @chvBeiZhu='%' ELSE SET @chvBeiZhu='%'+@chvBeiZhu+'%'

--商品
DECLARE @ptypecategoryid VARCHAR(MAX)     --商品类别ID
SET @ptypecategoryid=''
CREATE TABLE #Ptype 
(
	TypeID		VARCHAR(50),
	UserCode	VARCHAR(200),
	FullName VARCHAR(200)
)
--组合品报表不显示服务类商品
IF @chrOpType='SearchOrder'
BEGIN
	INSERT INTO #Ptype(TypeId) 
	SELECT P.TypeId
	FROM ptype p
	INNER JOIN  F_ManPTypeInCategoryID(@chvOperatorID,@chvPtype,@ptypecategoryid)P1 ON P.typeId=P1.TypeId 
	WHERE p.IsService=0
END
ELSE
BEGIN
	INSERT INTO #Ptype(TypeId,UserCode,FullName) 
	SELECT P.TypeId,UserCode,FullName 
	FROM Ptype P 
	INNER JOIN F_ManPTypeInCategoryID(@chvOperatorID,@chvPtype,@ptypecategoryid) P1 ON P.typeId=P1.TypeId
	where 
		p.sonnum=0  
		AND p.IsService=0
END

CREATE TABLE #PrintRecord( 
 billnumberid  NUMERIC(10,0),
 PrintCount  int

)


INSERT INTO #PrintRecord
        ( billnumberid, PrintCount )
SELECT BillNumberId,SUM(PrintCount) FROM dbo.PrintRecord WHERE BillType=313 GROUP BY BillNumberId


--往来单位    
CREATE TABLE #Btype (TypeID VARCHAR(50))
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBtype,2,@chvOperatorID)

-- 由于复制订单时，客户数据有的没有复制过来,所以插入一个空的记录(对于所有单位或所有客户或所有供货商才查得到）
IF @chvBtype='' OR @chvBtype ='00000'-- OR @chvBtype='00001' OR @chvBtype ='00002'
BEGIN
	INSERT INTO #btype (TypeID)  VALUES ('')
	INSERT INTO #Btype(TypeID) VALUES(null)
END

--职员
CREATE TABLE #Etype (TypeID VARCHAR(50))
INSERT INTO #Etype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvEtype,3,@chvOperatorID)
IF @chvEtype=''
BEGIN
	INSERT INTO #Etype(TypeID) VALUES('')
	INSERT INTO #Etype(TypeID) VALUES('00001')
END

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50))
INSERT INTO #Ktype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvKType,4,@chvOperatorID)
IF @chvKtype='' OR @chvKtype ='00000'
	INSERT INTO #ktype(typeid) VALUES('')
	
--部门
CREATE TABLE #dtype (TypeID VARCHAR(50))
INSERT INTO #dtype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)
IF @dtypeid='' 
	INSERT INTO #dtype(typeid) VALUES('')

--分支机构
CREATE TABLE #stype (TypeID VARCHAR(50))
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvstype,11,@chvOperatorID)
INSERT INTO #stype ( TypeID )VALUES  ( '' )

--查询订单状态
DECLARE @orderBillType INT
 
SET @orderBillType = 313	 

CREATE TABLE #AuditingBill
(
	BillNumberId NUMERIC(18,0),
	CheckState	 VARCHAR(50)
)

IF @shzt <> '9' --非全部状态(9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据)
BEGIN
	--IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @orderBillType AND IfUse = 1)
	--BEGIN
		IF @shzt = '0'	--原始单据
			INSERT INTO #AuditingBill(BillNumberId,CheckState)
			SELECT	B.BillNumberId,
					'原始单据' AS CheckState
			FROM	OrderIndex B			
			WHERE	B.BillDate >= @dtmStartDate
					AND B.BillDate <= @dtmEndDate
					AND B.billtype = @orderBillType
					AND B.billNumberId NOT IN 
					(
						SELECT	A.billNumberId 
						FROM	AuditingBill A
						INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						INNER JOIN #stype S ON S.TypeID = F.Stypeid											
						WHERE	BillIndexType = 0					
					)
		ELSE
			INSERT INTO #AuditingBill(BillNumberId,CheckState)
			SELECT	A.BillNumberId,
					CASE @shzt
						WHEN '1' THEN '待审核单据'
						WHEN '2' THEN '审核通过单据'
						ELSE '审核不通过单据'
					END AS CheckState
			FROM	AuditingBill A
			INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
			INNER JOIN #stype S ON S.TypeID = F.Stypeid
			WHERE	A.BillDate >= @dtmStartDate
					AND A.BillDate <= @dtmEndDate													
					AND F.IfUse = 1
					AND A.BillIndexType = 0
					AND A.IfAudit = CASE
										WHEN @shzt = '1' THEN '0'
										WHEN @shzt = '2' THEN '1'
										ELSE '-1'
									END		
	--END
END


--------------------------------------------------------取得数据---------------------------------------------------------
IF @chrOpType='SearchOrder'    --订单查询
BEGIN
	SET  @SQL +=  'SELECT	
						DISTINCT(a.BillNumberID),
						CONVERT(VARCHAR(10),a.ReachDate,120) AS ReachDate ,
						CONVERT(VARCHAR(10),a.BillDate,120) AS BillDate ,
						a.checktime,
						a.BillCode,
						a.etypeid AS etypeid,
						a.DealBTypeID,
						a.btypeid as btypeid,
						states.StateName,
						a.orderstate,
						a.CustomerTotal, 
						a.NCustomerTotal,
						Convert( NUMERIC(24, 10) ,isnull(o.TotalQty,0)) as OrderQty,
						Convert( NUMERIC(24, 10) ,isnull(o.TotalMoney,0)) as OrderMoney,
						Convert( NUMERIC(24, 10) ,O.ReachQty) AS ReachQty, /*已发货数量 || 已到货数量 */
						O.locknumber as locknumber,/*已锁定数量*/
						Convert( NUMERIC(24, 10) ,O.ReachMoney) AS  ReachMoney, /*已发货金额 || 已到货金额*/
						NoReachQty=Convert( NUMERIC(24, 10) ,A.TotalQty-ISNULL(O.ReachQty,0)),
						NoReachMoney=Convert( NUMERIC(24, 10) ,A.TotalMoney)-Convert( NUMERIC(24, 10) ,O.ReachMoney),
						a.Comment,
						a.BillOver AS IFStop,
						a.Billtype,
						A.stypeid,
						a.checke,
						case WHEN a.isyapi=1 THEN ''云分销订单'' ELSE ''正常订单'' END AS type,
						a.isyapi,
						CASE
							WHEN ISNULL(AB.CheckState,'''') = '''' THEN ''原始单据''
							ELSE AB.CheckState
						END AS CheckState,
						AC.CId AS accrencyid,
						AC.FullName AS accrencyname,
						a.dtypeid,
						a.totalinmoney,
						a.Ntotalinmoney,
						isnull(pri.PrintCount,0)as printcount,
						SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
						SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
						SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
						explain,
						tel,
						goodsnumber as wjsl,
						packway,
						waybillcode
               	FROM 	OrderIndex a 
       			LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
       			
       			INNER JOIN (	/*状态集合*/
       							SELECT	StateName = case dbo.F_GetCombinOrderState(BillNumberID,'+CONVERT (VARCHAR(10),@orderBillType)+')  
       												when ''1'' then ''已引用未完成''
													when ''2'' then ''已完成''
													when ''4'' then ''未引用''
													else '''' end ,
										billnumberid 
										FROM dbo.OrderIndex 
				
       						) states  ON a.billnumberid=states.billnumberid
                   '
              --加入了打印次数   
                 SET @sql=@sql+'  left join #PrintRecord pri on  a.billnumberid=pri.billnumberid '      			
     SET @SQL=@SQL+'    LEFT JOIN Ac_Currency AC ON AC.CId=a.CID  
						INNER JOIN 
						(
							SELECT 	A.BillNumberID,
							Convert( NUMERIC(24, 10) ,ISNULL(SUM(A.Qty),0)) AS TotalQty,
							Convert( NUMERIC(24, 10) ,ISNULL(SUM(A.Total),0)) AS  TotalMoney  ,
							Convert( NUMERIC(24, 10) ,ISNULL(SUM(A.ReachQty),0)) AS ReachQty,
							Convert( NUMERIC(24, 10) ,ISNULL(SUM(A.ReachTaxTotal),0)) AS  ReachMoney  ,
							(select sum(isnull(LockNumber,0)) from PT_Combin_OrderBillDetail where BillNumberID = A.BillNumberID) as locknumber
							FROM dbo.PT_Combin_OrderBill A
							 '
							
						
			SET @SQL =@SQL+'  WHERE 1=1 '
			
			IF NOT (@chvPtype ='' AND @MPtypeid = '00000' AND @ptypecategoryid='')
            --SET @SQL =@SQL+'  INNER JOIN #PType P ON P.Typeid=a.ptypeid  '
              SET @SQL =@SQL+' AND A.ptypeid IN (SELECT typeid AS CombinationProductPtypeId FROM #PType)'
								 

	IF @chvBeiZhu<>'%'
		BEGIN
			SET @SQL=@SQL+' AND  a.Comment LIKE '+char(39)+@chvBeiZhu+char(39)
		END
	SET @SQL=@SQL+	'		  	
							GROUP BY
								A.BillNumberID		
						 )O ON a.billNumberId=O.billNumberID '
						
	IF @shzt <> '9'
		SET @SQL = @SQL + ' INNER JOIN #AuditingBill AB ON AB.BillNumberId = A.BillNumberId '
	ELSE
		SET @SQL = @SQL + ' LEFT JOIN (
											SELECT	A.BillNumberId,
													CASE A.IfAudit
														WHEN 0 THEN ''待审核单据''
														WHEN 1 THEN ''审核通过单据''
														ELSE ''审核不通过单据''
													END AS CheckState
											FROM	AuditingBill A
											INNER JOIN AuditingFlowSet F ON A.AuditingId = F.AuditingId AND F.BillType = '+CAST(@orderBillType AS VARCHAR(10))+'
											WHERE	A.BillIndexType = 0
													AND A.BillDate >= '''+@dtmStartDate+'''
													AND A.BillDate <= '''+@dtmEndDate+'''
									   )AB ON AB.BillNumberId = A.BillNumberId '

	IF NOT (@chvBtype = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		 SET @SQL = @SQL +' INNER JOIN #btype b on (a.dealbtypeid=b.typeid ) '

	IF NOT (@chvEType = '' AND @METypeId = '00001')
		 SET @SQL = @SQL +' INNER JOIN #etype e on (a.etypeid=e.typeid) '
	     
	IF NOT (@chvstype = '' AND @MStypeid  = '00000')
		 SET @SQL = @SQL +' INNER JOIN #stype s on (a.stypeid=s.typeid) '
	     
     --IF NOT (@dtypeid = '' AND @dtypeid = '00000')

		 SET @SQL = @SQL +' INNER JOIN #dtype d on (a.dtypeid=d.typeid) '

	IF NOT (@chvKType = '' AND @MKTypeId = '00000')
		 SET @SQL = @SQL +' INNER JOIN #ktype k on (a.ktypeid=k.typeid) '
	  
	SET @SQL = @SQL + ' WHERE a.billtype= case '+char(39)+@chrOrderType+char(39)+' when '+char(39)+'Sale'+char(39)+' then '+char(39)+'303'+char(39)+ 'when'+char(39)+'CSale'+char(39)+' then '+char(39)+'313'+char(39)+' else '+char(39)+'301'+char(39)+' END '
		SET @SQL = @SQL +'
			AND a.BillDate>= '+char(39)+convert(varchar(10),@dtmStartDate,120) +char(39)+'
			AND a.BillDate<='+char(39)+convert(varchar(10),@dtmENDDate,120) +char(39)+'
			AND a.checked=0 '
		IF ISNULL(@dtmReachStartDate,'')<>''
			SET @SQL = @SQL + ' AND  a.ReachDate>= '+char(39)+convert(varchar(10),@dtmReachStartDate,120) +char(39)
		IF ISNULL(@dtmReachENDDate,'')<>''
			SET @SQL = @SQL + ' AND a.ReachDate<='+char(39)+convert(varchar(10),@dtmReachENDDate,120)+char(39)
			
		IF @intOrderSortType = 1 --已引用未完成
		BEGIN
			SET  @SQL = @SQL + '  and StateName=''已引用未完成'' '
		END
		
		IF @intOrderSortType = 3 --未完成
		BEGIN
			SET  @SQL = @SQL + '  and (StateName=''已引用未完成'' OR  StateName=''未引用'' )'
		END

		
	    IF @intOrderSortType = 2 --已完成
			SET  @SQL = @SQL + '  and StateName=''已完成'' '
			
		IF @intOrderSortType = 4 --未引用
		BEGIN
			SET  @SQL = @SQL + '  and StateName=''未引用'' '
		END	
					
		IF @cid!=''      
		SET @SQL=@SQL+' AND a.CID='+@cid+' ' 	
		
		IF @chvBillCode<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.BillCode like '+char(39)+@chvBillCode +char(39)
		END
		IF @chvComment<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.Comment like '+char(39)+@chvComment+char(39)
		END
		IF @chvExplain<>'%'
		BEGIN
			SET @SQL=@SQL+' AND isnull(a.Explain,'''') like '+char(39)+@chvExplain +char(39)
		END
		IF @chvWayBillCode<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.WayBillCode like '+char(39)+@chvWayBillCode+char(39)
		END
		IF @chvTel<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.Tel like '+char(39)+@chvTel +char(39)
		END
		IF @chvGoodsNumber<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.GoodsNumber like '+char(39)+@chvGoodsNumber +char(39)
		END
		IF @chvPackWay<>'%'
		BEGIN
			SET @SQL=@SQL+' AND a.PackWay like '+char(39)+@chvPackWay+char(39)
		END
----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--未找到“计算合计”的地方，先不考虑
	IF(@IsReporting = 0)
	BEGIN
		SET @SQL = @SQL + ' Order by '+@strSortField+' '+@strSortType 
		--PRINT @SQL
		EXEC(@SQL)
	END
	ELSE IF(@IsReporting = 1)
	BEGIN
		CREATE TABLE #tmp_result
		(
			billnumberid VARCHAR(100),
			billtype     VARCHAR(100),
			Costom1		VARCHAR(max),
			Costom2		VARCHAR(max),
			Costom3		VARCHAR(max),
			Costom4		VARCHAR(max),
			Costom5		VARCHAR(max),
			Costom6		VARCHAR(max),
			Costom7		VARCHAR(max),
			Costom8		VARCHAR(max),
			Costom9		VARCHAR(max),
			Costom10	VARCHAR(max),
			Costom11	VARCHAR(max),
			Costom12	VARCHAR(max),
			Costom13	VARCHAR(max),
			Costom14	VARCHAR(max),
			Costom15	VARCHAR(max),
			Costom16	VARCHAR(max)
		)
		SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ' + ' Order by '+@strSortField+' '+@strSortType + 
				  ' 
				   DECLARE @p1 dbo.TBType_SelfType  
				   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
				   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 
				   
					SELECT a.*,
						  b.Costom1,
						  b.Costom2,
						  b.Costom3,
						  b.Costom4,
						  b.Costom5,
						  b.Costom6,
						  b.Costom7,
						  b.Costom8,
						  b.Costom9,
						  b.Costom10,
						  b.Costom11,
						  b.Costom12,
						  b.Costom13,
						  b.Costom14,
						  b.Costom15,
						  b.Costom16 
						  FROM #temp1 a 
						  left join #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
					
					DROP TABLE #temp1,#tmp_result'
		--PRINT @SQL	
		EXEC(@SQL)
	END
----------------------------------------------------------
END
--***************************************************************************订单汇总***************************************************************--		
IF @chrOpType='GatherOrder'          
BEGIN
	DECLARE @SQL_WHERE VARCHAR(2000)
	SET @SQL_WHERE=''
	IF @userCode<>''
		SET @SQL_WHERE=@SQL_WHERE+' WHERE P.userCode LIKE '+CHAR(39)+'%'+@userCode+'%'+CHAR(39)
	IF @fullName<>''
		IF @SQL_WHERE=''
			SET @SQL_WHERE=' WHERE P.fullName LIKE '+CHAR(39)+'%'+@fullName+'%'+CHAR(39)
		ELSe
			SET @SQL_WHERE=@SQL_WHERE+' AND P.fullName LIKE '+CHAR(39)+'%'+@fullName+'%'+CHAR(39)
		
	SET @TEMP_SQL =''
	IF @INTOrderSortType = 1
		SET  @TEMP_SQL = @TEMP_SQL + ' AND o.BillnumberID IN ( SELECT BillnumberID FROM PT_Combin_OrderBill WHERE ReachQty<Qty)'
	IF @INTOrderSortType = 2
		SET  @TEMP_SQL = @TEMP_SQL + ' AND o.BillnumberID NOT IN ( SELECT BillnumberID FROM PT_Combin_OrderBill WHERE ReachQty<Qty)'

	CREATE TABLE #PT_Combin_OrderBill(BillNumberId numeric(10,0))

	SET @SQL ='	INSERT INTO #PT_Combin_OrderBill(BillNumberId) SELECT DISTINCT O.BillNumberId
				FROM	PT_Combin_OrderBill O 
				INNER JOIN (SELECT BillnumberID FROM PT_Combin_OrderBill  WHERE Comment LIKE '+CHAR(39)+@chvBeiZhu+CHAR(39) + ' ) T  '
				
	IF NOT (@chvPtype ='' AND @MPtypeid = '00000' AND @ptypecategoryid='')
		SET @SQL =@SQL+'  INNER JOIN (SELECT BillnumberID FROM PT_Combin_OrderBill  INNER JOIN #PType P ON PT_Combin_OrderBill.PTypeId = P.TypeId )  P  ON P.BillnumberID=T.BillnumberID  '

	SET @SQL =@SQL+'  ON O.BillNumberId=T.BillnumberID   ' 

	IF @INTOrderSortType = 1
		SET  @SQL = @SQL + '  WHERE o.BillnumberID IN ( SELECT BillnumberID FROM PT_Combin_OrderBill WHERE ReachQty<Qty)'
		
	IF @INTOrderSortType = 2
		SET  @SQL = @SQL + '  WHERE o.BillnumberID NOT IN ( SELECT BillnumberID FROM PT_Combin_OrderBill WHERE ReachQty<Qty)'

	PRINT @SQL
	EXEC(@SQL) 

	SET @SQL=' SELECT	p.usercode,
						p.fullname,
						p.typeid,
						I.OrderQty,
						I. OrderMoney,
						I.ReachQty,
						I.ReachMoney 
						FROM 
						(SELECT x.ptypeid,
						sum(x.Qty) as OrderQty,
						sum(isnull(x.TaxTotal,0)) as OrderMoney,
						sum(x.ReachQty) as ReachQty,
						sum(isnull(x.TaxTotal/x.Qty*x.ReachQty,0)) as ReachMoney 
				FROM (
						SELECT	DISTINCT x.BillNumberID,x.PTypeID,x.OrderID,x.Qty,x.TaxTotal,x.ReachQty
						FROM	OrderIndex a 
						INNER JOIN PT_Combin_OrderBill x  ON A.BillNumberId=X.BillNumberId 
						INNER JOIN #PT_Combin_OrderBill TOrder ON x.BillNumberID=TOrder.BillNumberId  '

	IF NOT (@chvBtype = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' INNER JOIN #btype b on (a.dealbtypeid=b.typeid 	OR a.dealbtypeid IS NULL OR a.dealbtypeid='''') '

	IF NOT (@chvEType= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' INNER JOIN #etype e on (a.etypeid=e.typeid or a.etypeid=''00001'') '

	IF NOT (@chvKType = '' AND @MKTypeId = '00000')
		SET @SQL =@SQL+' INNER JOIN #ktype k on (a.ktypeid=k.typeid		OR a.KTypeID='''') '
		

		 SET @SQL = @SQL +' INNER JOIN #dtype d on (a.dtypeid=d.typeid) '
	     
	SET @SQL =@SQL+'WHERE	a.BillCode like '+CHAR(39)+@chvBillCode+'%'+CHAR(39)+'
							AND a.Comment like ' +CHAR(39)+@chvComment+'%'+CHAR(39)+'
							AND a.Explain like ' +CHAR(39)+@chvExplain+'%'+CHAR(39)+' 
		    				AND a.WayBillCode like '+CHAR(39)+@chvWayBillCode+'%'+CHAR(39)+'
							AND a.Tel like '+CHAR(39)+@chvTel+'%'+CHAR(39)+'
							AND a.GoodsNumber like '+CHAR(39)+@chvGoodsNumber+CHAR(39)+'
							AND a.PackWay like '+CHAR(39)+@chvPackWay+'%'+CHAR(39)
							
				SET @SQL = @SQL +' 
		    				AND a.BillDate>='+CHAR(39)+convert(VARCHAR(50),@dtmStartDate)+CHAR(39)+'
							AND a.BillDate<='+CHAR(39)+convert(VARCHAR(50),@dtmEndDate)+CHAR(39)+'
							AND a.checked=0 '
							
				SET @SQL = @SQL +'	
							AND a.billtype= case '+CHAR(39)+@chrOrderType+CHAR(39)+ ' when '+CHAR(39)+'Sale'+CHAR(39)+' then '+CHAR(39)+'303'+CHAR(39)+' else '+CHAR(39)+'301'+CHAR(39)+' END '
							
				IF ISNULL(@dtmReachStartDate,0)<>''
					SET @SQL = @SQL + '
						AND a.ReachDate>='+CHAR(39)+convert(VARCHAR(10),@dtmReachStartDate,120)+CHAR(39)
				IF @dtmReachENDDate<>''
					SET @SQL = @SQL + '
						AND a.ReachDate<='+CHAR(39)+convert(VARCHAR(10),@dtmReachENDDate,120)+CHAR(39)
				SET @SQL = @SQL +'
					AND ( a.BillOver = CASE '+convert(VARCHAR(10),@INTOrderSortType) +' WHEN 1 THEN 0 WHEN 2 THEN 0 WHEN 0 THEN 0 WHEN 3 THEN 1 END
					   OR a.BillOver = CASE '+convert(VARCHAR(10), @INTOrderSortType)+' WHEN 1 THEN 0 WHEN 2 THEN 0 WHEN 0 THEN 1 WHEN 3 THEN 1 END ) 
			) x '
		
	SET @SQL =@SQL+ ' GROUP by  x.ptypeid ) I INNER JOIN  ptype p ON (I.ptypeid=p.typeid)  ' +@SQL_WHERE  + ' order by 	Usercode '
	
	--PRINT @SQL
	EXEC(@SQL)
END	

DROP TABLE #Ptype,#Btype,#Etype,#Ktype,#stype,#dtype,#AuditingBill

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SearchSaleOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SearchSaleOrderBill]
GO

/*
	作者：俞俊杰
	日期：2007-3-7
	描述：根据销售出库单/发出商品出库单查询销售订单
*/
/*
	修改：舒珊
	日期：2016年2月23日15:59:00
	描述：增添表头自定义显示字段
*/
/*
	修改：舒珊
	日期：2016年4月14日15:43:00
	描述：增添制单时间checkTime
*/
 /*
    修改: 舒珊
    日期: 2015-05-31
    描述: 增加表头新增的自定义字段查询
*/
 
CREATE  PROCEDURE [Gp_SearchSaleOrderBill]            
(
	@chvOperatorID  	VARCHAR(50),
	@billnumberid		VARCHAR(50),
	@billType			VARCHAR(50) = '',			--源单据类型
	@IsReporting		INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
  
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL VARCHAR(MAX)
SET @SQL=''

-- 增加客户供货商统一判断
DECLARE @BTypeAll VARCHAR(50), @MBTypeID_Temp VARCHAR(50)
SELECT @BTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'
DECLARE @TEMP_SQL VARCHAR(2000)

--商品
CREATE TABLE #Ptype 
(
	TypeID		VARCHAR(50),
	UserCode	VARCHAR(200),
	FullName VARCHAR(200)
)

CREATE TABLE #PrintRecord
( 
	billnumberid  NUMERIC(10,0),
	PrintCount  int
)


INSERT INTO #Ptype(TypeId) 
SELECT P.TypeId
FROM F_GetAllManagerBaseTypeId('',1,@chvOperatorID) P


--往来单位    
CREATE TABLE #Btype (TypeID VARCHAR(50))
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID)

-- 由于复制订单时，客户数据有的没有复制过来,所以插入一个空的记录(对于所有单位或所有客户或所有供货商才查得到）
INSERT INTO #Btype (TypeID)  VALUES ('')
INSERT INTO #Btype(TypeID) VALUES(null)


--职员
CREATE TABLE #Etype (TypeID VARCHAR(50))
INSERT INTO #Etype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID)
INSERT INTO #Etype(TypeID) VALUES('')
INSERT INTO #Etype(TypeID) VALUES('00001')

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50))
INSERT INTO #Ktype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',4,@chvOperatorID)
INSERT INTO #ktype(typeid) VALUES('')
	
--部门
CREATE TABLE #dtype (TypeID VARCHAR(50))
INSERT INTO #dtype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)
INSERT INTO #dtype(TypeID) VALUES('')
INSERT INTO #dtype(TypeID) VALUES(null)

--分支机构
CREATE TABLE #stype (TypeID VARCHAR(50))
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID)
INSERT INTO #stype ( TypeID )VALUES  ( '' )
--查询订单状态
DECLARE @orderBillType INT
SET @orderBillType = 300	--销售订单

INSERT INTO #PrintRecord
	( 
		billnumberid, 
		PrintCount 
	)
	SELECT	p.BillNumberId,
			SUM(p.PrintCount) 
	FROM	dbo.PrintRecord p,
			dbo.OrderIndex O
	WHERE	p.BillNumberId = O.billNumberId			
			AND p.BillType=300
	GROUP BY p.BillNumberId


--------------------------------------------------------取得数据---------------------------------------------------------
	SET  @SQL =  'SELECT	
						DISTINCT(a.BillNumberID),
						a.ReachDate,	
						a.BillDate,
						a.checktime,
						a.BillCode,
						a.etypeid AS etypeid,
						a.DealBTypeID,
						a.btypeid as btypeid,
						states.StateName,
						a.orderstate,
						a.CustomerTotal, 
						a.NCustomerTotal,
						Convert( NUMERIC(24, 10) ,isnull(a.TotalQty,0)) as OrderQty,
						Convert( NUMERIC(24, 10) ,isnull(a.TotalMoney,0)) as OrderMoney,
						Convert( NUMERIC(24, 10) ,O.ReachQty) AS ReachQty,
						O.locknumber as locknumber,
						Convert( NUMERIC(24, 10) ,O.ReachMoney) AS  ReachMoney,
						NoReachQty=Convert( NUMERIC(24, 10) ,A.TotalQty-ISNULL(O.ReachQty,0)),
						NoReachMoney=Convert( NUMERIC(24, 10) ,A.TotalMoney)-Convert( NUMERIC(24, 10) ,O.ReachMoney),
						a.Comment,
						a.BillOver AS IFStop,
						a.Billtype,
						A.stypeid,
						a.checke,case WHEN a.isyapi=1 THEN ''云分销订单'' ELSE ''正常订单'' END AS type,
						CASE
							WHEN ISNULL(AB.CheckState,'''') = '''' THEN ''原始单据''
							ELSE AB.CheckState
						END AS CheckState,
						AC.CId AS accrencyid,
						AC.FullName AS accrencyname,
						a.dtypeid,
						isnull(pri.PrintCount,0)as printcount,
						CASE WHEN T.SALENUMBERID IS NULL THEN 0 ELSE 1 END AS issaleused,--订单下面只要汇总的SaleOrderReachQty 不为0 该销售订单就是被采购订单引用了
						SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
						SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
						SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
						O.BillOverNumber,
						O.BillOverTotal,
						a.Ntotalinmoney
			 	FROM 	OrderBill BI 
               			INNER JOIN OrderIndex a ON BI.BillNumberId=a.billNumberId 
               			LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
               			LEFT JOIN Ac_Currency AC ON AC.CId=a.CID
               			INNER JOIN (	/*状态集合*/
               							SELECT	StateName = case dbo.F_GetOrderState(BillNumberID,'+CONVERT (VARCHAR(10),@orderBillType)+')  
               												when ''1'' then ''已引用未完成''
															when ''2'' then ''已完成''
															when ''4'' then ''未引用''
															else '''' end ,
												billnumberid 
												FROM dbo.OrderIndex 
						
               						) states  ON a.billnumberid=states.billnumberid  
               			LEFT join (
               							SELECT DISTINCT BILLNUMBERID  AS SALENUMBERID
               							FROM ORDERBILL 
               							WHERE ORDERID IN (SELECT SALEORDERID FROM ORDERBILL WHERE SALEORDERID<>0)
									)  T on t.SALENUMBERID=a.billNumberId 
                        '
                --加入了打印次数   
                 SET @SQL=@SQL+'  left join #PrintRecord pri on  BI.billnumberid=pri.billnumberid '   
     SET @SQL=@SQL+' INNER JOIN (
										SELECT 	A.BillNumberID,
										Convert( NUMERIC(24, 10) ,SUM(ReachQty)) AS ReachQty,
										Convert( NUMERIC(24, 10) ,SUM(ReachTaxTotal)) AS  ReachMoney,
										sum(isnull(locknumber,0)) as locknumber,
										SUM(CASE WHEN BillOver=1 THEN qty-ReachQty ELSE 0 END) BillOverNumber,
										SUM(CASE WHEN BillOver=1 THEN total-ReachTotal ELSE 0 END) BillOverTotal
										FROM 	OrderBill A '								
	IF NOT (@MPtypeid = '00000')
            SET @SQL =@SQL+'  INNER JOIN #PType P ON P.Typeid=a.ptypeid  '
            
	SET @SQL=@SQL+	'				GROUP BY
												A.BillNumberID		
						 )O ON A.billNumberId=O.billNumberID 
						 LEFT JOIN (
											SELECT	A.BillNumberId,
													CASE A.IfAudit
														WHEN 0 THEN ''待审核单据''
														WHEN 1 THEN ''审核通过单据''
														ELSE ''审核不通过单据''
													END AS CheckState
											FROM	AuditingBill A
											INNER JOIN AuditingFlowSet F ON A.AuditingId = F.AuditingId AND F.BillType = '+CAST(@orderBillType AS VARCHAR(10))+'
											WHERE	A.BillIndexType = 0
									   )AB ON AB.BillNumberId = A.BillNumberId  '
	IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
		 SET @SQL = @SQL +' INNER JOIN #btype b on (a.dealbtypeid=b.typeid ) '

	IF NOT (@METypeId = '00001')
		 SET @SQL = @SQL +' INNER JOIN #etype e on (a.etypeid=e.typeid) '
	     
	IF NOT (@MStypeid  = '00000')
		 SET @SQL = @SQL +' INNER JOIN #stype s on (a.stypeid=s.typeid) '
	     
	IF  @MDtypeid <> '00000'
		 SET @SQL = @SQL +' INNER JOIN #dtype d on (a.dtypeid=d.typeid) '

	IF NOT (@MKTypeId = '00000')
		 SET @SQL = @SQL +' INNER JOIN #ktype k on (a.ktypeid=k.typeid) '
		 
	IF @billType='402'
		SET @SQL = @SQL + 'WHERE OrderID IN (SELECT OrderID FROM dbo.SendBill WHERE BillNumberId = '+@billnumberid+' ) '
	ELSE
		SET @SQL = @SQL + 'WHERE OrderID IN (SELECT OrderID FROM dbo.SaleBill WHERE BillNumberId = '+@billnumberid+' ) '
		
		
	--SET @SQL = @SQL + ' Order by billdate desc' 
	
	--PRINT(@SQL)
	--EXEC(@SQL)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
	IF(@IsReporting = 0)
	BEGIN
		SET @SQL = @SQL + ' Order by billdate desc' 
		--PRINT @SQL
		EXEC(@SQL)
	END
	ELSE IF(@IsReporting = 1)
	BEGIN
		CREATE TABLE #tmp_result
		(
			billnumberid VARCHAR(100),
			billtype     VARCHAR(100),
			Costom1		VARCHAR(max),
			Costom2		VARCHAR(max),
			Costom3		VARCHAR(max),
			Costom4		VARCHAR(max),
			Costom5		VARCHAR(max),
			Costom6		VARCHAR(max),
			Costom7		VARCHAR(max),
			Costom8		VARCHAR(max),
			Costom9		VARCHAR(max),
			Costom10	VARCHAR(max),
			Costom11	VARCHAR(max),
			Costom12	VARCHAR(max),
			Costom13	VARCHAR(max),
			Costom14	VARCHAR(max),
			Costom15	VARCHAR(max),
			Costom16	VARCHAR(max)
		)
		SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ' + ' Order by billdate desc ' + 
				  ' 
				   DECLARE @p1 dbo.TBType_SelfType  
				   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
				   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 
				   
					--显示最终结果
					SELECT a.*,
						  b.Costom1,
						  b.Costom2,
						  b.Costom3,
						  b.Costom4,
						  b.Costom5,
						  b.Costom6,
						  b.Costom7,
						  b.Costom8,
						  b.Costom9,
						  b.Costom10,
						  b.Costom11,
						  b.Costom12,
						  b.Costom13,
						  b.Costom14,
						  b.Costom15,
						  b.Costom16 
						  FROM #temp1 a 
						  left join #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
					
					DROP TABLE #temp1,#tmp_result'
		EXEC(@SQL)
	END

DROP TABLE #Ptype,#Btype,#Etype,#Ktype,#stype,#dtype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SelectBatchOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SelectBatchOrder]
GO















/****** Object:  Stored Procedure dbo.Gp_SelectBatchOrder    Script Date: 2002-6-20 10:14:51 ******/

CREATE  PROCEDURE  Gp_SelectBatchOrder
(       @PtypeId   varchar(100),
        @KtypeId   varchar(100)
)         
--@encode$--
AS
SET NOCOUNT ON 
select * from goodsstocks where 
PtypeId=@PtypeId and KtypeId=@KtypeId
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SelectBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SelectBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
修改原因：调草稿时也调出vip信息
修 改 人：徐辉
修改标记：#01
修改时间：2004-7-15
*/
CREATE          PROCEDURE GP_SelectBillIndex 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @sql VARCHAR (8000)
SELECT @sql='
			SELECT CASE WHEN ISNULL(a.CwCheck,0) = 0 THEN ''否'' ELSE ''是'' END AS CwCheck,
			a.*,
			u.FullName,
			u.Rate,
			b.FullName AS dealbname,
			(SELECT c.VipCardNo
			FROM VipCardSign c,VipCardSet d,VipCardConsume e
			WHERE c.VipCardNo = e.VipCardNo AND d.VipCardId = c.VipCardId AND e.BillNumberID = '+cast(@billnumberid as char)+') AS VipCardNo,
			(SELECT d.VipCardKL  
			FROM VipCardSign c,VipCardSet d,VipCardConsume e
			WHERE c.VipCardNo = e.VipCardNo AND d.VipCardId = c.VipCardId AND e.BillNumberID = '+cast(@billnumberid as char)+') AS VipCardKL,
			ISNull(au.BillDetail,'''') AS BillDetail,
			(SELECT isnull(fullname,'''')
			FROM ptype p
			WHERE a.ptypeid = p.typeid) AS ptype, 
			(SELECT isnull(fullname,'''')
			FROM employee b
			WHERE a.etypeid = b.typeid) AS etype,
			(SELECT isnull(fullname,'''')
			FROM Stock b
			WHERE a.Ktypeid = b.typeid) AS Ktype,
			(SELECT isnull(fullname,'''')
			FROM Stock b
			WHERE a.Ktypeid2 = b.typeid) AS Ktype2,
			(SELECT isnull(fullname,'''')
			FROM Stock b
			WHERE a.Ktypeid3 = b.typeid) AS Ktype3,
			(
			CASE ISNULL(a.IfMulAccount,''0'') WHEN 1 THEN ''【多账户】''
			ELSE isnull(atype.fullname,'''') END
			) AS Atype,
			c.fullname AS btype,
			CASE ISNULL(CAST(b.price AS NUMERIC(24,10)),''0'') WHEN 0 THEN 1 ELSE b.price END AS saleprice,
			CASE ISNULL(CAST(b.buyprice AS NUMERIC(24,10)),''0'') WHEN 0 THEN 1 ELSE b.buyprice END AS buyprice,
			(SELECT isnull(fullname,'''')
			FROM department b
			WHERE a.dtypeid = b.typeid) AS Dtype,
			(SELECT isnull(fullname,'''')
			FROM employee b
			WHERE a.checke = b.typeid) AS checkman,
			(SELECT isnull(fullname,'''')
			FROM employee b
			WHERE a.wxmanid = b.typeid) AS wxmanfullname,
			(SELECT isnull(billcode,'''')
			FROM orderindex b
			WHERE a.orderid = b.billnumberid) AS ordercode,
			(SELECT isnull(fullname,'''')
			FROM Stype b
			WHERE a.stypeid = b.typeid) AS sfullname,
			a.stypeid,
			a.costSale,
			t.fullname as tranfullname,
			t.typeid as btrantypeid,
			t.bfullname as btranfullname,
			a.posbilltype,
			a.NCompleteTotal,
			a.CompleteTotal,
			a.atypeid1,
			a.ntotalinmoney,
			a.preferencemoney,
			a.npreferencemoney,
			w.fullname AS atypeid1name,
			e2.fullname as tallyer,
			(SELECT isnull(fullname,'''')
			FROM OtherInOutType o
			WHERE a.OtherInOutType=o.id) AS othertypefullname,
			a.nchargeofftotal as nchargeofftotal,
			a.chargeofftotal as chargeofftotal 
FROM billindex a
LEFT JOIN AuditingBill au	ON (au.billnumberid=a.billnumberid AND Au.BillIndexType = 2)
LEFT JOIN atype ON a.atypeid = atype.typeid
LEFT JOIN btype b ON a.dealbtypeid = b.typeId
LEFT JOIN btype c ON a.btypeid = c.typeId
LEFT JOIN Stype S ON S.TypeId= A.Stypeid 
LEFT JOIN (
			SELECT	t.id,
					t.fullname,
					b.typeid,
					b.fullname as bfullname 
			FROM	QP_Transport t LEFT JOIN btype b on b.typeid = t.btypeid
		   )t
		   ON a.TransportId = t.id
LEFT JOIN Ac_Currency u ON u.CId=a.CID
LEFT JOIN Ac_Account w ON w.typeid=a.atypeid1 and w.StypeId=s.VerifyID
LEFT JOIN employee e2 ON A.TallyId=e2.typeId 
WHERE a.billnumberid = '+cast(@billnumberid as char)
		
--print @sql
exec (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SelectBillList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SelectBillList]
GO














/****** Object:  Stored Procedure dbo.GP_SelectBillList    Script Date: 2002-6-20 10:14:45 ******/

CREATE  PROCEDURE GP_SelectBillList
( 
 @DbName  varchar(50),
 @BillnumberId  numeric(10,0),
 @InOrOut  char(1)=''
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar(500)
select @dbname=upper(@dbname)
if @dbname='DISASSEMBLEBILL'
 SELECT a.*,b.*,a.comment as AComment,b.comment as Bcomment FROM DisassembleBill
 a INNER JOIN ptype b ON b.typeId = a.PtypeId 
 WHERE billnumberid=@billnumberid and inorout=@inorout
else if @dbname='ADDEBTBILL'
 SELECT a.*,b.*,a.comment as AComment,b.comment as Bcomment FROM AdDebtBill
  a INNER JOIN btype b ON b.typeId = a.btypeId 
  WHERE billnumberid=@billnumberid
else if @dbname='MOVEMONEYBILL' or @dbname='PAYBILL' or @dbname='GATHERINGBILL'
begin
 select @sql='SELECT a.*,b.fullname,b.usercode,a.comment as AComment,b.comment as Bcomment FROM '+@dbname+
  ' a INNER JOIN Atype b ON b.typeId = a.AtypeId 
  WHERE billnumberid='+cast(@billnumberid as char)
exec(@sql)
end
else if upper(@dbname)='ORDERBILL'
 SELECT c.tax,a.*,b.*,a.comment as AComment,b.comment as Bcomment FROM OrderBill
   a INNER JOIN ptype b ON b.typeId = a.PtypeId inner join OrderIndex c on(a.billnumberid=c.billnumberid)
  WHERE a.billnumberid=@billnumberid
else if upper(@dbname)='GUESTBACK'
 Select * 
 From GuestBack g 
 Inner Join GuestBackIndex i On i.BillNumberId=g.BillNumberId
 Inner Join PType p On g.PtypeId=p.TypeId
 Where g.BillNumberId=@billnumberid
else if upper(@dbname)='GUESTPAY'
 Select g.total as gtotal,g.comment as gcom,* 
 From GuestPay g 
 Inner Join GuestPayIndex i On i.BillNumberId=g.BillNumberId
 Inner Join AType p On g.AtypeId=p.TypeId
 Where g.BillNumberId=@billnumberid
else
begin
 select @sql='SELECT a.*,b.*,a.comment as AComment,b.comment as Bcomment FROM '+@dbname+
  ' a INNER JOIN ptype b ON b.typeId = a.PtypeId 
  WHERE billnumberid='+cast(@billnumberid as char)
exec(@sql)
end
--print @sql















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SelectBillListByAtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SelectBillListByAtype]
GO














/****** Object:  Stored Procedure dbo.GP_SelectBillListByAtype    Script Date: 2002-6-20 10:14:45 ******/

CREATE  PROCEDURE GP_SelectBillListByAtype
( 
 @DbName  varchar(50),
 @BillNumberId  numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar(500)
select @sql='SELECT a.*,b.* FROM '+@dbname+
 ' a INNER JOIN Atype b ON b.typeId = a.AtypeId 
 WHERE billnumberid='+cast(@billnumberid as char)
--print @sql
exec(@sql)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SelectLocalBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SelectLocalBill]
GO










/****** Object:  Stored Procedure dbo.GP_SelectLocalBill    Script Date: 2003-12-26 15:38:26 ******/

/****** Object:  Stored Procedure dbo.GP_SelectLocalBill    Script Date: 2003-12-26 11:27:40 ******/

/****** Object:  Stored Procedure dbo.GP_SelectLocalBill    Script Date: 2003-12-26 9:44:39 ******/

/****** Object:  Stored Procedure dbo.GP_SelectLocalBill    Script Date: 2003-12-25 19:32:16 ******/
/*
	--编程：Roamer Wu
	--时间：2003-12-29
	--功能：查询货位单据的索引，将所有系统代码转化为相应的名称
*/
CREATE     Procedure GP_SelectLocalBill(
@nBillId		 NUMERIC(24, 10) 
)
--@encode$--
AS
SET NOCOUNT ON

Select	 a.BillNumberId,
	 a.BillCode,
	 a.BillDate,
	 a.BillType,
	 a.BID,
	 a.BCode,
	 a.Comment,
	 a.Explain,
	 b.FullName as EType,
	 c.FullName as KType,
	 d.FullName as EType1,
	 d.FullName as EType2
From	 LocalIndex a,
	 Employee b,
	 Stock c,
	 Employee d
Where	 a.BillNumberId = @nBillId
	 And a.ETypeId = b.TypeId
	 And a.KTypeId = c.TypeId
	 And a.ETypeId1 = d.TypeId
	 And a.ETypeId2 = d.TypeId








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SelectLocalDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SelectLocalDetail]
GO










/****** Object:  Stored Procedure dbo.GP_SelectLocalDetail    Script Date: 2003-12-26 15:20:00 ******/

/****** Object:  Stored Procedure dbo.GP_SelectLocalDetail    Script Date: 2003-12-26 10:49:03 ******/

/****** Object:  Stored Procedure dbo.GP_SelectLocalDetail    Script Date: 2003-12-26 9:19:53 ******/

/****** Object:  Stored Procedure dbo.GP_SelectLocalDetail    Script Date: 2003-12-25 19:35:10 ******/
/*
	--编程：Roamer Wu
	--时间：2003-12-29
	--功能：查询货位单据的明细，把商品代码转化为商品名称及相关商品的属性
*/
CREATE     PROCEDURE GP_SelectLocalDetail(
@nBillId	 Numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON

Select	 a.QTY,
	 a.LTypeId,
	 a.LTypeId2,
	 a.IsUnit2,
	 a.Comment,
	 a.Serial,
	 a.Price,
	 a.Total,
	 b.UserCode,
	 b.FullName,
	 b.Unit1,
	 b.Unit2,
	 b.UnitRate1,
	 b.EntryCode,
	 b.Standard ,
	 b.Type ,
	 b.Area ,
	 b.IfSerial

From	 LocalDetail a, PType b
Where	 a.BillNumberID = @nBillId
	 AND a.PtypeID = b.TypeId







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SelectOACount_UpdateOnlineUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SelectOACount_UpdateOnlineUser]
GO



CREATE PROCEDURE Gp_SelectOACount_UpdateOnlineUser
(
	@chvETypeID	VARCHAR(500),
	@intMAXIDLESECOND	INT
)
--@encode$--
AS

SET NOCOUNT ON

SELECT COUNT(1) AS Qty FROM (SELECT TOP 1 1 Qty FROM OA_Message WHERE ETypeID_CreatorTypeID=@chvETypeID AND ETypeID_ReceiverTypeID=@chvETypeID AND IsRead=0) a

--更新自己最近一次与服务器联系的时间
UPDATE OA_OnlineUser SET [LatestConnectTime] = GETDATE() WHERE [ETypeID_UserTypeID] = @chvETypeID

--删除不在线用户
--DELETE OA_OnlineUser WHERE DATEDIFF(second,LatestConnectTime,GETDATE()) > @intMAXIDLESECOND

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SelectOffLineBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SelectOffLineBill]
GO
















/****** Object:  Stored Procedure dbo.GP_SelectOffLineBill    Script Date: 2002-6-20 10:14:45 ******/

-- CopyRight@ 成都任我行软件公司 2001
-- 作者 ： 刘畅
-- 时间 ： 2001-11-21
-- 查询离线版本的单据明细
CREATE  PROCEDURE GP_SelectOffLineBill 
( 
 @BillNumberId varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (1600)
select @sql='SELECT a.*
	  ,isnull(p.usercode,'''') AS ptypeusercode
	  ,isnull(p.fullname,'''') AS ptypename
	  ,isnull(p.Unit1,'''') AS Unit1
	  ,isnull(p.Unit2,'''') AS Unit2
	  ,isnull(p.UnitRate1,0) AS UnitRate1
	  ,isnull(b.usercode,'''') AS btypeusercode
	  ,isnull(b.fullname,'''') AS btypename
  	  ,isnull(i.usercode,'''') AS atypeusercode
	  ,isnull(i.fullname,'''') AS atypename
	FROM Offline_Bill a 
	left join ptype p on a.ptypeid = p.typeid 
	left join btype b on a.btypeid = b.typeid
	left join atype i on a.atypeid = i.typeid 
	WHERE a.OFF_ID = '''+cast(@billnumberid as varchar(200))+''' '
--print @sql
exec (@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SelectOffLineBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SelectOffLineBillIndex]
GO
















/****** Object:  Stored Procedure dbo.GP_SelectOffLineBillIndex    Script Date: 2002-6-20 10:14:45 ******/

-- CopyRight@ 成都任我行软件公司 2001
-- 作者 ： 刘畅
-- 时间 ： 2001-11-21
-- 查询离线版本的单据Index
CREATE  PROCEDURE GP_SelectOffLineBillIndex 
( 
 @BillNumberId varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (1600)
select @sql='SELECT *,
         (SELECT isnull(fullname,'''')
         FROM employee b
         WHERE a.etypeid = b.typeid) AS etype,
          (SELECT isnull(fullname,'''')
         FROM Stock b
         WHERE a.Ktypeid = b.typeid) AS Ktype,
          (SELECT isnull(fullname,'''')
         FROM Stock b
         WHERE a.Ktypeid2 = b.typeid) AS Ktype2,
          (SELECT isnull(fullname,'''')
         FROM atype b
         WHERE a.atypeid = b.typeid) AS Atype,
          (SELECT isnull(fullname,'''')
         FROM btype b
         WHERE a.btypeid = b.typeid) AS btype,
         (SELECT isnull(fullname,'''')
         FROM employee b
         WHERE a.checke = b.typeid) AS checkman,
          (SELECT isnull(billcode,'''')
         FROM orderindex b
         WHERE a.orderid = b.billnumberid) AS ordercode
FROM Offline_BillIndex a
WHERE a.OFF_ID = '''+cast(@billnumberid as varchar(200))+''' '
--print @sql
exec (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SelectorderIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SelectorderIndex]
GO















/****** Object:  Stored Procedure dbo.GP_SelectorderIndex    Script Date: 2002-6-20 10:14:45 ******/

CREATE   PROCEDURE GP_SelectorderIndex 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (1600)
select @sql='SELECT *,
 (SELECT isnull(fullname,'''')
         FROM employee b
         WHERE a.etypeid = b.typeid) AS etype,
          (SELECT isnull(fullname,'''')
         FROM Stock b
         WHERE a.Ktypeid = b.typeid) AS Ktype,
		 (SELECT isnull(fullname,'''')
         FROM Detpartment b
         WHERE a.Dtypeid = b.typeid) AS Dtype,
          (SELECT isnull(fullname,'''')
         FROM btype b
         WHERE a.btypeid = b.typeid) AS btype FROM orderindex a
WHERE a.billnumberid = '+cast(@billnumberid as char)
--print @sql
exec (@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SendBackBill_CreateReciptBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_SendBackBill_CreateReciptBill]
GO




/*

功能说明：		发出商品退货单过帐后生成销售发货开票的草稿

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_SendBackBill_CreateReciptBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
*/
DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT


SELECT @intReturnID=0

DECLARE 
	@strFromBillCode 				VARCHAR(100),
	@datBillDate					DATETIME





DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号


DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@strETypeID			VARCHAR(50),
	@strKTypeID			VARCHAR(50),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@intBillType		INT,
	@strSTypeID			VARCHAR(50),
	@strBTypeID			VARCHAR(50),
	@intCID				INT,
	@OldRate			 NUMERIC(24, 10) ,
	@NewRate			 NUMERIC(24, 10) ,
	@ceDtypeid			VARCHAR(100),
	@cefullname			VARCHAR(500)='',		--制单人
	@cdfullname			VARCHAR(500)=''			--部门
	
DECLARE 
		@strOPRate	VARCHAR(50),
		@CID		INT,
		@SysCid		INT
		
--本位币	
SELECT @SysCid= CID FROM dbo.Ac_Currency WHERE Sysrow=1	


	
SELECT @strETypeID=ETypeID,@strKTypeID=KTypeID,@datBillDate=BillDate,@strSTypeID=StypeID,@strFromBillCode=BillCode,@ceDtypeid=DTypeId,
	@intCID=CID,@OldRate=Rate
FROM BillIndex
WHERE BillNumberID=@nBillID	

SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

SELECT @strOPRate=BasisType,@NewRate=Rate
FROM Ac_Currency				
WHERE CId=@intCID

IF @strOPRate='0'
BEGIN
	SELECT @strOPRate='*'
END
ELSE
BEGIN
	SELECT @strOPRate='/'
END

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT @VchHead='XFH',
	@intBillType=405
	
IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = typeid FROM Employee WHERE TypeID = @strETypeID
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @strKTypeID
END
ELSE
BEGIN
	SELECT 
		@MONTH=ISNULL(@MONTH,''),
		@DAY=ISNULL(@DAY,'')
END


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname

IF @Re <> 0
RETURN -2	




DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000),
	@BillName		VARCHAR(50)
	
SELECT @BillName=BillName
FROM BillName
WHERE 	Billtype=403
	
	
SELECT 
	@strComment='该销售发货开票是从'+@BillName+@strFromBillCode+'生成而来的！'

--生成销售发货开票单的草稿
--生成表头




DECLARE
	@strTempATypeID1		VARCHAR(100)
	
SELECT
	@strTempATypeID1=ATypeID
FROM BillAtype
WHERE BillTypeId='405'
AND StypeId=@strSTypeID


SELECT @strTempATypeID1=ISNULL(@strTempATypeID1,'')


INSERT ReceiptBillIndex(BillDate,BillCode,BillType,DealBTypeID,BTypeID,STypeID,ETypeID,
Comment,totalmoney,totalqty,tax,period,explain,AlertDay,DTypeId,
ifcheck,IfAudit,draft,checke,NTotalMoney,CID,Rate,ATypeID1,TaxTotalMoney,NTaxTotalMoney)
SELECT BillDate,@strBillCode,@intBillType,DealBTypeID,btypeid,@strSTypeID,
etypeid,@strComment,-totalmoney,-totalqty,tax,period,explain,AlertDay,DTypeId,
'f',0,1,@chvOpID,NTotalMoney,CID,Rate,@strTempATypeID1,-totalmoney,-NTotalMoney
FROM BillIndex
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();


--生成表体



INSERT ReceiptBill(BillNumberId,BillType,MainBillNumberID,RecordedItemId,MainBillType,
KTypeID,PTypeID,Qty,Price,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,discount,Nprice,NTotal,NTaxPrice,NTaxTotal,taxmoney,NTaxMoney,
CargoID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MUnitRate,MUnitMsg,MTaxPrice,CurMPrice,CurMTaxPrice,
ItemID,IsCombined,BeforePrice,BeforeTotal,Nbeforeprice,NBeforeTotal,goodsnumber,
saleprice,saletotal,nsaleprice,nsaletotal,curmsaleprice,curmsaletotal,IsGift,ProduceDate,ValidDate,
Serial,InvoiceCostPrice,InvoiceCostTotal,MQty,ShowOrder)
SELECT @intReturnID,405,BillNumberId,ID,403,
KTypeID,PTypeID,-Qty,DiscountPrice,-Total,Tax,TaxPrice,-TaxTotal,Comment,Stypeid,1,NDiscountPrice,-NTotal,NTaxPrice,-NTaxTotal,-taxmoney,-NTaxMoney,
CargoID,UnitID,NUnitID,-NQty,UnitRate,NUnitMsg,MUnitID,MUnitRate,MUnitMsg,MTaxPrice,CurMDiscountPrice,CurMTaxPrice,
ItemID,IsCombined,DiscountPrice,-Total,NDiscountPrice,-NTotal,goodsnumber,
DiscountPrice,-total,NDiscountPrice,-NTotal,CurMDiscountPrice,-NTotal,IsGift,ProduceDate,ValidDate,
Serial,costprice,-CostTotal,-MQty,ShowOrder
FROM SendBackBill
WHERE BillNumberId=@nBillID


--同步自定义字段
IF EXISTS(SELECT 1 FROM dbo.Custom_BillIndex WHERE BillId=@nBillID AND BillType=403)
BEGIN
	INSERT INTO dbo.Custom_BillIndex( BillId ,BillType ,
			  SysDiy1_head ,SysDiy2_head ,SysDiy3_head ,
			  SysDiy4_head ,SysDiy5_head ,SysDiy6_head ,
	          SysDiy7_head ,SysDiy8_head ,SysDiy9_head ,
	          SysDiy10_head ,SysDiy11_head ,SysDiy12_head ,
	          SysDiy13_head ,SysDiy14_head ,SysDiy15_head ,
	          SysDiy16_head
	        )
	SELECT	  @intReturnID ,405 ,SysDiy1_head ,SysDiy2_head ,
	          SysDiy3_head ,SysDiy4_head ,SysDiy5_head ,
	          SysDiy6_head ,SysDiy7_head ,SysDiy8_head ,
	          SysDiy9_head ,SysDiy10_head ,SysDiy11_head ,
	          SysDiy12_head ,SysDiy13_head , SysDiy14_head ,
	          SysDiy15_head ,SysDiy16_head
	FROM dbo.Custom_BillIndex WHERE BillId=@nBillID AND BillType=403
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Custom_BillDetails WHERE BillId=@nBillID AND BillType=403)
BEGIN
	INSERT INTO dbo.Custom_BillDetails( BillId ,Detailid ,BillType ,
	          SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,
	          SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,
	          SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16
	        )
	SELECT	  @intReturnID ,B.ID ,405 ,
	          A.SysDiy1 ,A.SysDiy2 ,A.SysDiy3 ,A.SysDiy4 ,A.SysDiy5 ,A.SysDiy6 ,
	          A.SysDiy7 ,A.SysDiy8 ,A.SysDiy9 ,A.SysDiy10 ,A.SysDiy11 ,A.SysDiy12 ,
	          A.SysDiy13 ,A.SysDiy14 ,A.SysDiy15 ,A.SysDiy16
	FROM dbo.Custom_BillDetails A INNER JOIN dbo.ReceiptBill B ON A.Detailid=B.RecordedItemId 
		 AND A.BillId=B.MainBillNumberID AND A.BillType=B.MainBillType
		 WHERE A.BillId=@nBillID AND A.BillType=403 AND B.BillNumberID=@intReturnID
END

DECLARE
	@decTotalmoney	 NUMERIC(24, 10) ,
	@decNTotalMoney	 NUMERIC(24, 10) ,
	@decTaxTotalMoney	 NUMERIC(24, 10) ,
	@decNTaxTotalMoney	 NUMERIC(24, 10) 
	
SELECT @decTotalmoney=SUM(-Total),@decNTotalMoney=SUM(-NTotal),@decTaxTotalMoney=SUM(-TaxTotal),@decNTaxTotalMoney=SUM(-NTaxTotal)
FROM SendBackBill
WHERE BillNumberID=@nBillID	


UPDATE ReceiptBillIndex
SET TotalMoney=@decTotalmoney,NTotalMoney=@decNTotalMoney,TaxTotalMoney=@decTaxTotalMoney,NTaxTotalMoney=@decNTaxTotalMoney
WHERE BillNumberID=@intReturnID


IF @intCID<>@SysCid AND @NewRate<>@OldRate
BEGIN
	--先根据原币计算表体的本币
	IF @strOPRate='*'
	BEGIN
		UPDATE ReceiptBill
		SET Total=ROUND(Ntotal*CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot),
		TaxTotal=ROUND(NTaxTotal*CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot)
		WHERE BillNumberId=@intReturnID 
	END
	ELSE
	BEGIN
		UPDATE ReceiptBill
		SET Total=ROUND(NTotal/CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot),
		TaxTotal=ROUND(NTaxTotal/CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot)
		WHERE BillNumberId=@intReturnID 
	END
	
	UPDATE ReceiptBill
	SET Price=CASE QTY WHEN 0 THEN 0 ELSE ROUND(CAST(Total AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) END,
	TaxPrice=CASE QTY WHEN 0 THEN 0 ELSE ROUND(CAST(TaxTotal AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) END
	WHERE BillNumberId=@intReturnID 
	--再根据表体的本币得到表头的本币
	
	SELECT @decTotalmoney=SUM(Total),@decTaxTotalMoney=SUM(TaxTotal)
	FROM ReceiptBill
	WHERE BillNumberID=@intReturnID	
	
	UPDATE ReceiptBillIndex
	SET TotalMoney=@decTotalmoney,Rate=@NewRate,TaxTotalMoney=@decTaxTotalMoney
	WHERE BillNumberID=@intReturnID
END



--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END


GO


/*

DECLARE
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0),			--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100),
	@strErrMsg				VARCHAR(100)			--出错信息
	
SELECT
	@chvOpID=1,
	@nBillID=1
	
BEGIN TRAN	

EXEC	GP_SendBackBill_CreateReciptBill
	@chvOpID,
	@nBillID,
	@intReturnID OUT,
	@strReturnBillCode OUT,
	@strErrMsg OUT

SELECT @strReturnBillCode,@strErrMsg

SELECT * FROM receiptbillindex

SELECT * FROM receiptBill

ROLLBACK TRAN

*/





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SendBill_CreateReciptBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_SendBill_CreateReciptBill]
GO




/*

功能说明：		发出商品出库单过帐后生成销售发货开票的草稿

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_SendBill_CreateReciptBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
*/
DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT


SELECT @intReturnID=0

DECLARE 
	@strFromBillCode 				VARCHAR(100),
	@datBillDate					DATETIME





DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号


DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@strETypeID			VARCHAR(50),
	@strKTypeID			VARCHAR(50),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@intBillType		INT,
	@strSTypeID			VARCHAR(50),
	@strBTypeID			VARCHAR(50),
	@intCID				INT,
	@OldRate			 NUMERIC(24, 10) ,
	@NewRate			 NUMERIC(24, 10) ,
	@ceDtypeid			VARCHAR(100),
	@cefullname			VARCHAR(500)='',		--制单人
	@cdfullname			VARCHAR(500)=''			--部门
	
DECLARE 
		@strOPRate	VARCHAR(50),
		@CID		INT,
		@SysCid		INT
		
--本位币	
SELECT @SysCid= CID FROM dbo.Ac_Currency WHERE Sysrow=1	
	
	
SELECT @strETypeID=ETypeID,@strKTypeID=KTypeID,@datBillDate=BillDate,@strSTypeID=StypeID,@strFromBillCode=BillCode,@ceDtypeid=DTypeId,
	@intCID=CID,@OldRate=Rate
FROM BillIndex
WHERE BillNumberID=@nBillID	

SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

SELECT @strOPRate=BasisType,@NewRate=Rate
FROM Ac_Currency				
WHERE CId=@intCID

IF @strOPRate='0'
BEGIN
	SELECT @strOPRate='*'
END
ELSE
BEGIN
	SELECT @strOPRate='/'
END
		

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT @VchHead='XFH',
		@intBillType=405
	
IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = typeid FROM Employee WHERE TypeID = @strETypeID
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @strKTypeID
END
ELSE
BEGIN
	SELECT @MONTH=ISNULL(@MONTH,''),
			@DAY=ISNULL(@DAY,'')
END


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname

IF @Re <> 0
RETURN -2	




DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000),
	@BillName		VARCHAR(50)
	
SELECT @BillName=BillName
FROM BillName
WHERE 	Billtype=402
	
	
SELECT 
	@strComment='该销售发货开票是从'+@BillName+@strFromBillCode+'生成而来的！'

--生成销售发货开票单的草稿
--生成表头




DECLARE
	@strTempATypeID1		VARCHAR(100)
	
SELECT
	@strTempATypeID1=ATypeID
FROM BillAtype
WHERE BillTypeId='405'
AND StypeId=@strSTypeID



SELECT @strTempATypeID1=ISNULL(@strTempATypeID1,'')


INSERT ReceiptBillIndex(BillDate,BillCode,BillType,DealBTypeID,BTypeID,STypeID,ETypeID,
Comment,totalmoney,totalqty,tax,period,explain,AlertDay,DTypeId,
ifcheck,IfAudit,draft,checke,NTotalMoney,CID,Rate,ATypeID1,TaxTotalMoney,NTaxTotalMoney)
SELECT BillDate,@strBillCode,@intBillType,DealBTypeID,btypeid,@strSTypeID,
etypeid,@strComment,totalmoney,totalqty,tax,period,explain,AlertDay,DTypeId,
'f',0,1,@chvOpID,NTotalMoney,CID,Rate,@strTempATypeID1,totalmoney,NTotalMoney
FROM BillIndex
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();


--生成表体



INSERT ReceiptBill(BillNumberId,BillType,MainBillNumberID,RecordedItemId,MainBillType,
KTypeID,PTypeID,Qty,Price,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,discount,Nprice,NTotal,NTaxPrice,NTaxTotal,taxmoney,NTaxMoney,
CargoID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MUnitRate,MUnitMsg,MTaxPrice,CurMPrice,CurMTaxPrice,
ItemID,IsCombined,BeforePrice,BeforeTotal,Nbeforeprice,NBeforeTotal,goodsnumber,
saleprice,saletotal,nsaleprice,nsaletotal,curmsaleprice,curmsaletotal,IsGift,ProduceDate,ValidDate,
Serial,InvoiceCostPrice,InvoiceCostTotal,MQty,ShowOrder)
SELECT @intReturnID,405,BillNumberId,ID,402,
KTypeID,PTypeID,Qty,DiscountPrice,Total,Tax,TaxPrice,TaxTotal,Comment,Stypeid,1,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,taxmoney,NTaxMoney,
CargoID,UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MUnitRate,MUnitMsg,MTaxPrice,CurMDiscountPrice,CurMTaxPrice,
ItemID,IsCombined,DiscountPrice,Total,NDiscountPrice,NTotal,goodsnumber,
DiscountPrice,total,NDiscountPrice,NTotal,CurMDiscountPrice,NTotal,IsGift,ProduceDate,ValidDate,
Serial,costprice,CostTotal,MQty,ShowOrder
FROM SendBill
WHERE BillNumberId=@nBillID


--同步自定义字段
IF EXISTS(SELECT 1 FROM dbo.Custom_BillIndex WHERE BillId=@nBillID AND BillType=402)
BEGIN
	INSERT INTO dbo.Custom_BillIndex( BillId ,BillType ,
			  SysDiy1_head ,SysDiy2_head ,SysDiy3_head ,
			  SysDiy4_head ,SysDiy5_head ,SysDiy6_head ,
	          SysDiy7_head ,SysDiy8_head ,SysDiy9_head ,
	          SysDiy10_head ,SysDiy11_head ,SysDiy12_head ,
	          SysDiy13_head ,SysDiy14_head ,SysDiy15_head ,
	          SysDiy16_head
	        )
	SELECT	  @intReturnID ,405 ,SysDiy1_head ,SysDiy2_head ,
	          SysDiy3_head ,SysDiy4_head ,SysDiy5_head ,
	          SysDiy6_head ,SysDiy7_head ,SysDiy8_head ,
	          SysDiy9_head ,SysDiy10_head ,SysDiy11_head ,
	          SysDiy12_head ,SysDiy13_head , SysDiy14_head ,
	          SysDiy15_head ,SysDiy16_head
	FROM dbo.Custom_BillIndex WHERE BillId=@nBillID AND BillType=402
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.Custom_BillDetails WHERE BillId=@nBillID AND BillType=402)
BEGIN
	INSERT INTO dbo.Custom_BillDetails( BillId ,Detailid ,BillType ,
	          SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,
	          SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,
	          SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16
	        )
	SELECT	  @intReturnID ,B.ID ,405 ,
	          A.SysDiy1 ,A.SysDiy2 ,A.SysDiy3 ,A.SysDiy4 ,A.SysDiy5 ,A.SysDiy6 ,
	          A.SysDiy7 ,A.SysDiy8 ,A.SysDiy9 ,A.SysDiy10 ,A.SysDiy11 ,A.SysDiy12 ,
	          A.SysDiy13 ,A.SysDiy14 ,A.SysDiy15 ,A.SysDiy16
	FROM dbo.Custom_BillDetails A INNER JOIN dbo.ReceiptBill B ON A.Detailid=B.RecordedItemId 
		 AND A.BillId=B.MainBillNumberID AND A.BillType=B.MainBillType
		 WHERE A.BillId=@nBillID AND A.BillType=402 AND B.BillNumberID=@intReturnID
END


DECLARE
	@decTotalmoney	 NUMERIC(24, 10) ,
	@decNTotalMoney	 NUMERIC(24, 10) ,
	@decTaxTotalMoney	 NUMERIC(24, 10) ,
	@decNTaxTotalMoney	 NUMERIC(24, 10) 
	
SELECT @decTotalmoney=SUM(Total),@decNTotalMoney=SUM(NTotal),@decTaxTotalMoney=SUM(TaxTotal),@decNTaxTotalMoney=SUM(NTaxTotal)
FROM SendBill
WHERE BillNumberID=@nBillID	


UPDATE ReceiptBillIndex
SET TotalMoney=@decTotalmoney,NTotalMoney=@decNTotalMoney,TaxTotalMoney=@decTaxTotalMoney,NTaxTotalMoney=@decNTaxTotalMoney
WHERE BillNumberID=@intReturnID


IF @intCID<>@SysCid AND @NewRate<>@OldRate
BEGIN
	--先根据原币计算表体的本币
	IF @strOPRate='*'
	BEGIN
		UPDATE ReceiptBill
		SET Total=ROUND(Ntotal*CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot),
		TaxTotal=ROUND(NTaxTotal*CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot)
		WHERE BillNumberId=@intReturnID 
	END
	ELSE
	BEGIN
		UPDATE ReceiptBill
		SET Total=ROUND(NTotal/CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot),
		TaxTotal=ROUND(NTaxTotal/CAST(@NewRate AS  NUMERIC(24, 10) ),@intMoneyDot)
		WHERE BillNumberId=@intReturnID 
	END
	
	UPDATE ReceiptBill
	SET Price=CASE QTY WHEN 0 THEN 0 ELSE ROUND(CAST(Total AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) END,
	TaxPrice=CASE QTY WHEN 0 THEN 0 ELSE ROUND(CAST(TaxTotal AS  NUMERIC(24, 10) )/CAST(Qty AS  NUMERIC(24, 10) ),@intPriceDot) END
	WHERE BillNumberId=@intReturnID 
	--再根据表体的本币得到表头的本币
	
	SELECT @decTotalmoney=SUM(Total),@decTaxTotalMoney=SUM(TaxTotal)
	FROM ReceiptBill
	WHERE BillNumberID=@intReturnID	
	
	UPDATE ReceiptBillIndex
	SET TotalMoney=@decTotalmoney,Rate=@NewRate,TaxTotalMoney=@decTaxTotalMoney
	WHERE BillNumberID=@intReturnID
END


--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END


GO


/*

DECLARE
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0),			--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100),
	@strErrMsg				VARCHAR(100)			--出错信息
	
SELECT
	@chvOpID=1,
	@nBillID=1
	
BEGIN TRAN	

EXEC	GP_SendBill_CreateReciptBill
	@chvOpID,
	@nBillID,
	@intReturnID OUT,
	@strReturnBillCode OUT,
	@strErrMsg OUT

SELECT @strReturnBillCode,@strErrMsg

SELECT * FROM receiptbillindex

SELECT * FROM receiptBill

ROLLBACK TRAN

*/





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialInMyTable]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialInMyTable]
GO




--haiquan 用来临时存储要批量筛选的序列号v39
--原理：每次批量插入前，先删除上次的全局临时表，然后再新建

CREATE        PROCEDURE Gp_SerialInMyTable
(
	@OperatorId		varchar(50),	--操作员ID
	@times			varchar(100)
)
--@encode$--
AS

declare @tablename varchar(200)

if exists (select name from sysobjects where type='u' and  name like 'myserial'+@OperatorId+'%')
BEGIN
	DECLARE tableCursor CURSOR FOR
	SELECT  [name]
	FROM 	sysobjects 
	WHERE 	type='u' 
		and  [name] like 'myserial'+@OperatorId+'%'
	
	OPEN tableCursor
	
	FETCH NEXT FROM tableCursor INTO  @tablename
	WHILE @@FETCH_STATUS = 0
		BEGIN
			Exec('DROP Table '+@tablename)
	
			FETCH NEXT FROM tableCursor INTO @tablename
		END
	
	CLOSE tableCursor
	DEALLOCATE tableCursor

END
 
Exec('Create table myserial'+@OperatorId+''+@times+' (serial varchar(100))')




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_AdPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_AdPrice]
GO






/*
	作者：冯波
	日期：2015-06-02
	描述：手工指定法下序列号调价
	
	
*/
CREATE   PROCEDURE Gp_SerialOperate_AdPrice
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@IfWx				int,
		@STypeId			varchar(50)


--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@billType	= BillType,
		@IfWx		= IfWx,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'


--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) ,
	Price		 NUMERIC(24, 10) 
)



--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	KTypeId			varchar(100),
	State			int,
	CommissionState	varchar(5),
	ID				BIGINT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--成本调价单



SET @mxTableName = 'AdPriceBill'
SET @State = 1
SET @InOutState = 1
SET @Flag = 0



IF @nCostingMethod<>3 OR (@nCostingMethod=3 AND @intserialrelation<>1) RETURN --如果不是手工指定法，那么不处理序列号

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,'
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+					
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END, '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0, '
END					
					
SET @SQL=@SQL+' M.Price
FROM 	'+@mxTableName+' M,
		PType P
WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
		AND P.TypeId = M.PTypeId
		AND P.SonNum = 0
		AND P.Deleted = 0 '
		
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

--PRINT(@SQL)

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial

--打开具体的游标
OPEN MngSerialNormal01
--处理结果

FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN

		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					KTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				) '
				

		--判断是否启用了多仓库
		IF EXISTS(SELECT TOP 1 1 FROM DBO.SYSOBJECTS S,dbo.syscolumns C WHERE s.id = c.id and S.name = @mxTableName AND C.name = 'KTypeId')
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
		ELSE
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@InKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))

		SET @SerialSQL = @SerialSQL + '
				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TKTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TKTypeId = KTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
	
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,KTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,KTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,KTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)

		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				
			
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				
				
				
				
				
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET KTypeId = @inKTypeId WHERE ISNULL(KTypeId,'')=''
UPDATE #AllSerial SET KTypeId = @inKTypeId WHERE ISNULL(KTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END


--从新置空错误ID的提示
SET @ErrId = 0



--判断商品属性是否正确
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId <> T.PTypeId					
							AND P.IfSerial = @intSysMngSerial
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId <> T.PTypeId					
				AND P.IfSerial = @intSysMngSerial
				AND T.ID = d.ID
	)a

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
		RETURN -907 --失败
	END

IF @BillType <> 141
BEGIN
		--序列号（判断仓库属性）
	SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
	FROM(
			SELECT P.nId,T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId <> T.KTypeId	--@inKTypeId	
								AND P.IfSerial = @intSysMngSerial		
					)d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId <> T.KTypeId	--@inKTypeId	
					AND P.IfSerial = @intSysMngSerial		
					AND T.ID = d.ID
		)a

			IF @@ROWCOUNT <> 0
				BEGIN
					SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
					RETURN -907 --失败
				END

			--判断序列号是否在库存中
			
	SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
	FROM(
			SELECT P.nId,T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = T.KTypeId	--@inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State = 25)
					)d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = T.KTypeId	--@inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State = 25)
					AND T.ID = d.ID
		)a	

			IF @@ROWCOUNT <> 0
				BEGIN
					SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
					RETURN -907 --失败
				END
END
ELSE	--委托代销结算必须是委托发货的序列号
BEGIN
		--判断分支机构
		
		SELECT	@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId			
									AND P.IfSerial = @intSysMngSerial			
									AND G.STypeId <> @STypeId
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId			
						AND P.IfSerial = @intSysMngSerial			
						AND G.STypeId <> @STypeId
						AND T.ID = d.ID
			)a	
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】分支机构属性不正确，不能过账！'	
						RETURN -907 --失败
					END			
		
END		



IF EXISTS(
	SELECT a.Serial FROM #AllSerial a
	INNER JOIN #TmpPType b
	ON a.ID=b.ID
	LEFT JOIN gp_CruPtypeSerial c
	ON a.Serial=c.Serial
	WHERE (b.ItemID <> c.ItemID
	OR b.Iscombined<>c.IsCombined
	OR b.GoodsNumber<>c.GoodsNumber
	OR b.ProduceDate<>c.ProduceDate
	OR b.ValidDate<>c.ValidDate
	OR b.CargoID<>c.CargoID
	OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
	)
	AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.CargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END	


--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	KTypeId,
	State,
	CommissionState,
	ID
)						
SELECT	T.Serial,
		T.PTypeId,
		T.KTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND T.PTypeId = G.PTypeId



--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
SELECT	TOP 1 
		@ErrId = P.nId,
		@ErrSerial = T.Serial 	
FROM	#AllSerial T,			
		#TmpPType P
WHERE	T.PTypeId = P.PTypeId		
		AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
ORDER BY T.Id ASC	


IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
		RETURN -907 --失败
	END

--写序列号的出入口记录
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		OutKTyeID,
		IfCheck,
		BillType,
		BTypeID1,
		BTypeID2,
		InKtypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	A.Serial,
		A.PTypeId,
		@nBillId,
		A.KTypeId,	--@inKTypeId,
		't',
		@BillType,
		'',
		'',
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.Price,
		B.Id
FROM	#UnionSerial A,#TmpPType B
WHERE A.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的调价记录失败！'
		RETURN -901
	END			



--修改当前出库的序列号状态
UPDATE	Gp_CruPTypeSerial
SET		CostPrice=P.Price
FROM 	Gp_CruPTypeSerial G,
		#UnionSerial T,
		#TmpPType P,
		#AllSerial B
WHERE	G.Serial = T.Serial 
		AND G.PTypeId = T.PTypeId
		AND G.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND P.ID=B.ID
		AND T.ID=P.ID
	

IF @@ERROR <> 0
BEGIN
	SET @szPID='修改序列号的调价记录失败！'
	RETURN -903
END		


--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000),
	@nRet		INT
	
SELECT
	@nBillId=2,
	@OperatorId='00001'
	

BEGIN TRAN

select CostPrice,* from gp_CruPtypeSerial

EXEC @nRet= Gp_SerialOperate_AdPrice
	@nBillId,						--单据的Id
	@OperatorId,				--操作员的Id
	@szPID 	output		--返回信息

SELECT @nRet,@szPID

select CostPrice,* from gp_CruPtypeSerial
SELECT COSTPRICE,* FROM gp_inoutPtypeSerial

ROLLBACK TRAN



*/





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_BuyExChangeGrid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_BuyExChangeGrid]
GO







/*
	作者：谢吉康
	日期：2007-3-19
	描述：采购换货单的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 13:35:26
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	时间:2015-05-12
	描述:序列号严密关联成本等
	
*/
CREATE   PROCEDURE Gp_SerialOperate_BuyExChangeGrid
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@STypeId			varchar(50)

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@outKTypeId	= KTypeId,
		@inKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'



--建立商品临时表
CREATE TABLE #TmpPType
(
	nId			int identity(1,1),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int,
	IfSerial	int,
	SerialCount	int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeid	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	InKTypeId		varchar(100),
	OutKTypeid		varchar(100),
	State			int,
	CommissionState	varchar(10),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeid	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 161	--采购换货单
	BEGIN
		SET @mxTableName = 'BuyGoodsExchangeBill'
		SET @State = 1
		SET @Flag  = 1
		SET @InOutState = 1
		SET @CinOutState = 1
		SET @Cstate = 1
	END


--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+				
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END
					
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
		PType P
WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
		AND P.TypeId = M.PTypeId
		AND P.SonNum = 0
		AND P.Deleted = 0
		AND M.InOrOut = ''O'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@OutKTypeId+''' AS InKTypeId,KTypeId AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''O'' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='出库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET InKTypeId = @inKTypeId WHERE ISNULL(InKTypeId,'')=''
UPDATE #AllSerial SET InKTypeId = @inKTypeId WHERE ISNULL(InKTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1
	BEGIN
	
	SELECT
			@ErrId = a.nId,
			@ErrSerial = a.Serial
	FROM
	(		
		SELECT 	P.nId, T.Serial
		FROM	#AllSerial T,
				Gp_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 0 and G.State IN(18)
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 0  and G.State IN(18)
				AND T.ID=d.ID
	) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
IF @mngLendSerial = 1
	BEGIN
	
	SELECT
			@ErrId = a.nId,
			@ErrSerial = a.Serial
	FROM
	(		
		SELECT 	P.nId, T.Serial
		FROM	#AllSerial T,
				Gp_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 1 and G.State IN(17)
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1  and G.State IN(17)
				AND T.ID=d.ID
	) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END

--从新置空错误ID的提示
SET @ErrId = 0

--对出库序列号进行判断	
IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.CargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		)
		AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.CargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END
	

--****************************************************************************************************************处理出库序列号*****************************************************************************************************************--
IF EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--序列号（判断仓库属性）
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断商品属性是否正确
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = T.OutKTypeId	--@outKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State NOT IN (1,7))
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = T.OutKTypeId	--@outKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State NOT IN (1,7))
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			InKTypeId,
			OutKTypeid,
			State,
			CommissionState,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				T.InKTypeId,
				T.OutKTypeid,
				G.State,
				ISNULL(G.CommissionState,'') AS CommissionState,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.OutKTypeid	--@outKTypeId
				AND G.Flag = 1

		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT  P.nId,
					T.Serial
			FROM	#AllSerial	T,
					#TmpPType	P,
					(
						SELECT	MIN(T.Id) AS ID
						FROM	#AllSerial T,
								#TmpPType P
						WHERE	T.PTypeId = P.PTypeId		
								AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					)d
					WHERE	T.PTypeId = P.PTypeId		
							AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
							AND T.Id = d.ID
		)a

		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
				RETURN -907 --失败
			END

		--判断序列号是否是未结算的序列号
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND ISNULL(G.CommissionState,'')='0'
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND ISNULL(G.CommissionState,'')='0' 
					AND T.ID=d.ID
		) a

		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】未结算前不允许采购换货出库！'	
				RETURN -907 --失败
			END
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID2,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				U.OutKTypeId,	--@outKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				CASE
					WHEN U.CommissionState='0' THEN 3
					WHEN U.CommissionState=''  THEN 3
					ELSE 3
				END,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice	,
				B.Id
		FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
		WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID

		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901

			END
		
		--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
		UPDATE	Gp_CruPTypeSerial
		SET		BTypeId2= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId2 END,								
				OutKTypeTime = @BillDate,
				State	= CASE
							WHEN T.CommissionState='0' THEN 3
							WHEN T.CommissionState=''  THEN 3
							ELSE 3
						  END,
				Flag 	= 0
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND T.PTypeId = P.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@outKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1
				AND T.ID=P.ID
				
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的出库记录失败！'
				RETURN -903
			END	
			
		--重算当前序列号库中的STypeId
		UPDATE	gp_CruPtypeSerial
		SET		STypeId = S.STypeID
		FROM    gp_CruPtypeSerial C,
				Stock S,
				#AllSerial A
		WHERE	C.KtypeID = S.typeId
				AND C.Serial = A.Serial
				AND C.KtypeID <> '10000'			
	END
--****************************************************************************************************************处理入库序列号*****************************************************************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial

--初始化错误值，重要，不然判断要出错
SET @ErrId = 0

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+				
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN  M.Discountprice ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END
					
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0					
					AND M.InOrOut = ''I'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal02 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal02
--处理结果
FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeid	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId AS InKTypeId,'''+@InKTypeId+''' AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''I'' ORDER BY ID

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='入库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='入库表格第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal02
DEALLOCATE MngSerialNormal02	

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''
UPDATE #AllSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--正式批量处理入库的序列号
--委托发货的序列号不允许入库 2008-04-22 V39
SELECT	TOP 1
		@ErrSerial = T.Serial
FROM	#AllSerial T,
		GP_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND G.State = 13 

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='委托发货的序列号【'+CAST(@ErrSerial AS varchar(100))+'】在结算前不允许再次入库！'
		RETURN -907 --失败
	END

--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
	
	SELECT
			@ErrId = a.nId,
			@ErrSerial = a.Serial
	FROM
	(		
		SELECT 	P.nId, T.Serial
		FROM	#AllSerial T,
				GP_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.State IN (17,20) 				
							AND G.Flag = 1 
							AND G.BFlag = 1
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.State IN (17,20) 				
				AND G.Flag = 1 
				AND G.BFlag = 1 
				AND T.ID=d.ID
	) a

		IF @ErrId <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--处理入库的序列号

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 1
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND P.IfSerial = @intSysMngSerial
			AND G.Flag = 1 
			AND T.ID=d.ID
) a

IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END


SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND ISNULL(G.CommissionState,'')='0' 
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND ISNULL(G.CommissionState,'')='0' 
			AND T.ID=d.ID
) a

IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在受托代销结算之前不允许再次入库！'
		RETURN -908 --失败
	END	

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	InKTypeId,
	OutKTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		T.InKTypeId,
		T.OutKTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial



--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		U.InKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		1,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	A.Serial,
		A.PTypeId,
		@nBillId,
		A.InKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		1,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID2,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	A.Serial,
		A.InKTypeId,	--@inKTypeId,
		A.PTypeId,
		@BTypeId,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
--注意只处理入库类序列号
UPDATE	Gp_CruPTypeSerial
SET		BTypeId2= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId2 END,
		PTypeId = T.PTypeId,
		KTypeId = T.InKTypeId,	--@inKTypeId,								
		InKTypeTime = @BillDate,
		State	= 1,
		Flag 	= 1,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=p.cargoID,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND P.ID=B.ID
		AND T.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_BuyExChangeGrid_ks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_BuyExChangeGrid_ks]
GO









/*
	作者：谢吉康
	日期：2007-3-19
	描述：采购换货单的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 15:18:00
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	时间:2015-05-12
	描述:序列号严密关联成本等
*/
CREATE   PROCEDURE Gp_SerialOperate_BuyExChangeGrid_ks
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@STypeId			varchar(50)

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@outKTypeId	= KTypeId,
		@inKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId				int identity(1,1),
	Serial 			varchar(200),
	Serial1			varchar(200),
	PTypeId			varchar(100),
	InKTypeId		varchar(100),
	OutKTypeId		varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int
	
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	InKTypeId		varchar(100),
	OutKTypeId		varchar(100),
	State			int,
	CommissionState	varchar(10),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 161	--采购换货单
	BEGIN
		SET @mxTableName = 'BuyGoodsExchangeBill'
		SET @State = 1
		SET @Flag  = 1
		SET @InOutState = 1
		SET @CinOutState = 1
		SET @Cstate = 1
	END


--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+				
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END
					
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0
					AND M.InOrOut = ''O'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@InKTypeId+''' AS InKTypeId,KTypeId AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''O'' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='出库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET InKTypeId = @inKTypeId WHERE ISNULL(InKTypeId,'')=''
UPDATE #AllSerial SET InKTypeId = @inKTypeId WHERE ISNULL(InKTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1
	BEGIN
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				Gp_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 0 and G.State IN(18)
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 0 and G.State IN(18)
				AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END

	--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
IF @mngLendSerial = 1
	BEGIN
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				Gp_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 1 and G.State IN(17)
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1 and G.State IN(17)
				AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
--从新置空错误ID的提示
SET @ErrId = 0

--对出库序列号进行判断	
IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
		)
		AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END
	


--*******************************************************************************************************************处理出库序列号*****************************************************************************************************************--
IF EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--序列号（判断仓库属性）
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
							AND P.IfSerial = @intSysMngSerial	
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
				AND P.IfSerial = @intSysMngSerial	
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断商品属性是否正确
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId <> T.PTypeId					
							AND P.IfSerial = @intSysMngSerial	
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId <> T.PTypeId					
				AND P.IfSerial = @intSysMngSerial
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断序列号是否在库存中
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = T.OutKTypeId	--@outKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State NOT IN (1,7))	
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@outKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND (G.Flag = 0 OR G.State NOT IN (1,7))
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			InKTypeId,
			OutKTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				T.InKTypeId,
				T.OutKTypeId,
				G.State,
				ISNULL(G.CommissionState,'') AS CommissionState,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@outKTypeId
				AND G.Flag = 1

		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则强行写入
		
		SELECT	@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G
					WHERE	T.Serial = G.Serial
							AND G.Flag = 0	
				) d
		WHERE	T.Serial = G.Serial
				AND G.Flag = 0
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】已有出库记录，不能出库！'	
				RETURN -907 --失败
			END
			
		
		--判断序列号是否是未结算的序列号
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND ISNULL(G.CommissionState,'')='0'
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND ISNULL(G.CommissionState,'')='0' 
				AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】未结算前不允许采购换货出库！'	
				RETURN -907 --失败
			END

		INSERT INTO Gp_CruPTypeSerial
		(
			Serial,
			KTypeID,
			PTypeID,
			BTypeID1,
			BTypeID2,
			InKTypeTime,
			OutKTypeTime,
			State,
			Flag,
			CommissionState,
			ItemID,
			IsCombined,
			CargoID,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice
		)
		SELECT	a.Serial,
				a.OutKTypeId,	--@outKTypeId,
				a.PTypeId,
				'',
				@BTypeId,
				@BillDate,
				@BillDate,
				@State,
				@Flag,
				'',
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice		
		FROM	#AllSerial a,#TmpPType B
		WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)
		
		INSERT	INTO #UnionSerial
		(
			Serial,
			PTypeID,
			InKTypeId,
			OutKTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	Serial,
				PTypeId,
				InKTypeId,
				OutKTypeId,
				@State,
				'',
				ID
		FROM	#AllSerial
		WHERE	Serial NOT IN (SELECT Serial FROM #UnionSerial)
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID2,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				U.OutKTypeId,	--@outKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				CASE
					WHEN U.CommissionState='0' THEN 3
					WHEN U.CommissionState=''  THEN 3
					ELSE 3
				END,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=B.ID

		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901

			END
		
		--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
		UPDATE	Gp_CruPTypeSerial
		SET		BTypeId2= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId2 END,								
				OutKTypeTime = @BillDate,
				State	= CASE
							WHEN T.CommissionState='0' THEN 3
							WHEN T.CommissionState=''  THEN 3
							ELSE 3
						  END,
				Flag 	= 0
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P
		WHERE	T.Serial = G.Serial
				AND G.PTypeId = T.PTypeId
				AND T.PTypeId = P.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@outKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1
				AND T.ID=P.Id
		
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的出库记录失败！'
				RETURN -903
			END	
			
		--重算当前序列号库中的STypeId
		UPDATE	gp_CruPtypeSerial
		SET		STypeId = S.STypeID
		FROM    gp_CruPtypeSerial C,
				Stock S,
				#AllSerial A
		WHERE	C.KtypeID = S.typeId
				AND C.Serial = A.Serial
				AND C.KtypeID <> '10000'			
	END
--*******************************************************************************************************************处理入库序列号*****************************************************************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial

--初始化错误值，重要，不然判断要出错
SET @ErrId = 0

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+				
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN  M.Discountprice ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END
					
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0					
					AND M.InOrOut = ''I'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal02 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal02
--处理结果
FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId AS InKTypeId,'''+@OutKTypeId+''' AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''I'' ORDER BY ID

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='入库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='入库表格第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal02
DEALLOCATE MngSerialNormal02	

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''
UPDATE #AllSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--正式批量处理入库的序列号
--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.State IN (17,20) 				
							AND G.Flag = 1 
							AND G.BFlag = 1
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.State IN (17,20) 				
				AND G.Flag = 1 
				AND G.BFlag = 1
				AND T.ID=d.ID
		IF @ErrId <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--处理入库的序列号

		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 1 	
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1 	
				AND T.ID=d.ID
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END

		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND ISNULL(G.CommissionState,'')='0' 	
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND ISNULL(G.CommissionState,'')='0' 
				AND T.ID=d.ID
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在受托代销结算之前不允许再次入库！'
		RETURN -908 --失败
	END	

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	InKTypeId,
	OutKTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		T.InKTypeId,
		T.OutKTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 


--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		U.InKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		1,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		a.InKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		1,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.ID	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID2,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		a.InKTypeId,	--@inKTypeId,
		a.PTypeId,
		@BTypeId,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
UPDATE	Gp_CruPTypeSerial
SET		BTypeId2= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId2 END,
		PTypeId = T.PTypeId,
		KTypeId = T.InKTypeId,	--@inKTypeId,								
		InKTypeTime = @BillDate,
		State	= 1,
		Flag 	= 1,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=p.cargoID,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND B.ID=P.ID
		AND T.ID=B.ID
	

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_ck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_ck]
GO


/*
	作者：谢吉康
	日期：2006-3-3
	描述：出库的序列号单独过帐	
	
	修改：毛欣蓉
	日期：2011-08-31
	描述：增加其他出库单序列号过账（单据编号202）
	
	修改：赵斌
	时间：2012年2月10日 11:16:10
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改：冯波
	时间：2015-04-21
	描述：序列号严密关联
*/
CREATE  PROCEDURE Gp_SerialOperate_ck
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id						
	@szPID 		varchar(1000)	output,		--返回信息
	@BillType    INT = 0	--单据类型
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		--@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@IfWx				int,
		@STypeId			varchar(50)


--获取该单据的具体信息
if @BillType =327             --991新增门店配送单
begin
	SELECT	@BillDate	= BillDate,
			@BTypeId 	= '',
			@inKTypeId	= KTypeId,
			@billType	= BillType,
			@IfWx		= '',
			@STypeId    = STypeId
	FROM	PosAllotApplyBillIndex
	WHERE	BillNumberId = @nBillId
end
else
begin
	SELECT	@BillDate	= BillDate,
			@BTypeId 	= DealBTypeID,
			@inKTypeId	= KTypeId,
			@billType	= BillType,
			@IfWx		= IfWx,
			@STypeId    = STypeId
	FROM	BillIndex
	WHERE	BillNumberId = @nBillId
end
SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'
--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	KTypeId			varchar(100),
	State			int,
	CommissionState	varchar(5),
	ID				BIGINT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 305	--零售单
	BEGIN
		SET @mxTableName = 'RetailBill'
		SET @State = 2
		SET @InOutState = 2
		SET @Flag = 0
	END

IF @billType = 11	--销售出库单
	BEGIN
		SET @mxTableName = 'SaleBill'
		SET @State = 2
		SET @InOutState = 2
		SET @Flag = 0
	END
	
IF @billType = 12	--组合品销售出库单
	BEGIN
		SET @mxTableName = 'PT_Combin_SaleBillDetail'
		SET @State = 2
		SET @InOutState = 2
		SET @Flag = 0
	END	
	
IF @billType = 402	--发出商品出库单
	BEGIN
		SET @mxTableName = 'SendBill'
		SET @State = 2
		SET @InOutState = 2
		SET @Flag = 0
	END
	

IF @billType = 6	--采购退货
	BEGIN
		SET @mxTableName = 'BuyBackBill'
		SET @State = 3
		SET @InOutState = 3
		SET @Flag = 0
	END
	
IF @billType = 401	--暂估退货
	BEGIN
		SET @mxTableName = 'AppraisalBackBill'
		SET @State = 3
		SET @InOutState = 3
		SET @Flag = 0
	END	

IF @billType = 146	--受托代销退货
	BEGIN
		SET @mxTableName = 'CommissionBill'
		SET @State = 8
		SET @InOutState = 8
		SET @Flag = 0
	END

IF @billType = 140	--委托代销发货
	BEGIN
		SET @mxTableName = 'CommissionBill'
		SET @State = 13
		SET @InOutState = 13
		SET @Flag = 0
	END

IF @billType = 141	--委托代销结算
	BEGIN
		SET @mxTableName = 'CommissionBill'
		SET @State = 14
		SET @InOutState = 14
		SET @Flag = 0
	END

IF @billType = 9 	--报损单
	BEGIN
		SET @mxTableName = 'LoseBill'
		SET @State = 4
		SET @InOutState = 4
		SET @Flag = 0
	END

IF @billType = 139	--赠送单
	BEGIN
		SET @mxTableName = 'GiveBill'
		SET @State = 5
		SET @Flag = 5
		SET @InOutState = 5
		SET @CInOutState = 5
		SET @Cstate	= 5
	END
	
IF @billType = 183	--积分兑换单
	BEGIN
		SET @mxTableName = 'IntegralExchangeBill'		
		SET @State = 5
		SET @Flag = 5
		SET @InOutState = 5
		SET @CInOutState = 5
		SET @Cstate	= 5
	END		
	
IF @BillType = 187 --分支机构调拨出库单
	BEGIN
		SET @mxTableName = 'STypeMoveBill'		
		SET @State = 30
		SET @InOutState = 30
		SET @Flag = 0
	END	
	
IF @billType = 202	--其他出库单
	BEGIN
		SET @mxTableName = 'OtherInOutBill'
		SET @State = 31
		SET @InOutState = 2
		SET @Flag = 0
	END
IF @billType = 327	--门店配送单
	BEGIN
		SET @mxTableName = 'DeliveryBill'
		SET @State = 35
		SET @InOutState = 35
		SET @Flag = 0
	END
--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+'M.ItemID,
	M.IsCombined,'
					
	IF @BillType in(187,328,329)
		SET @SQL=@SQL+'M.OutCargoID,'
	ELSE if @BillType=327
	SET @SQL=@SQL+'M.CargoIDout,'					
	ELSE
		SET @SQL=@SQL+'M.CargoID,'
		
						
	SET @SQL=@SQL+'		M.ProduceDate,
						M.ValidDate,
						M.GoodsNumber,
						CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
			SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0 '
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '
--print @SQL
EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial

--打开具体的游标
OPEN MngSerialNormal01
--处理结果

FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--select '1', @PTypeId,@Qty,@Id,@ErrId

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN

		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					KTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				) '

		--判断是否启用了多仓库
	IF(@BillType =327)
		 BEGIN
		   IF EXISTS(SELECT TOP 1 1 FROM Qp_MulStockConfig WHERE IsChecked=1 AND BillType=327)
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeIdOut,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
		ELSE
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@InKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))  
		 END 
	ELSE
		BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM DBO.SYSOBJECTS S,dbo.syscolumns C WHERE s.id = c.id and S.name = @mxTableName AND C.name = 'KTypeId')
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
		ELSE
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@InKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
        END
		SET @SerialSQL = @SerialSQL + '
				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TKTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TKTypeId = KTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
	
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,KTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,KTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,KTypeId,Qty,Id
				FROM #TmpSerial
				'	
        --print(@SerialSQL)
		EXEC(@SerialSQL)

		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET KTypeId = @inKTypeId WHERE ISNULL(KTypeId,'')=''
UPDATE #AllSerial SET KTypeId = @inKTypeId WHERE ISNULL(KTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END
DECLARE @IsLend	INT =0 
SELECT  @IsLend = islend from billindex where billnumberid = @nBillId

--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1 AND @IsLend = 0
	BEGIN
		SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_LendPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_LendPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND P.IfSerial = @intSysMngSerial
									AND G.Flag = 0 and G.State IN(18)
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 0 and G.State IN(18)
						AND T.ID = d.ID
			)a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				
				RETURN -907 --失败
			END
	END
	
		
	--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
IF @mngLendSerial = 1 AND @IsLend = 0
	BEGIN
		SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_LendPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_LendPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND P.IfSerial = @intSysMngSerial
									AND G.Flag = 1 and G.State IN(17)
								
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 1 and G.State IN(17)
						AND T.ID = d.ID
			)a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				
				RETURN -907 --失败
			END
	END


/******借欠转销售更新借欠序列号状态******/

IF @billType IN (11,12) AND EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@nBillId AND IsLend = 1)
BEGIN
	UPDATE a SET a.STATE = 33,Flag=1 FROM dbo.gp_LendPtypeSerial  a JOIN #AllSerial b
	ON a.Serial = b.Serial
END

/******借欠转销售更新借欠序列号状态******/

--从新置空错误ID的提示
SET @ErrId = 0

--判断商品属性是否正确
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId <> T.PTypeId					
							AND P.IfSerial = @intSysMngSerial
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId <> T.PTypeId					
				AND P.IfSerial = @intSysMngSerial
				AND T.ID = d.ID
	)a

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
		RETURN -907 --失败
	END

IF @BillType <> 141
BEGIN
		--序列号（判断仓库属性）
		SELECT	@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId
									AND G.KTypeId <> T.KTypeId	--@inKTypeId	
									AND P.IfSerial = @intSysMngSerial		
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId
						AND G.KTypeId <> T.KTypeId	--@inKTypeId	
						AND P.IfSerial = @intSysMngSerial		
						AND T.ID = d.ID
			)a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END
		--判断序列号是否在库存中
		
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = T.KTypeId	--@inKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State = 25)
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.KTypeId	--@inKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND (G.Flag = 0 OR G.State = 25)
				AND T.ID = d.ID
	)a	

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END
	END
ELSE	--委托代销结算必须是委托发货的序列号
	BEGIN
		--判断分支机构
		
		SELECT	@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId			
									AND P.IfSerial = @intSysMngSerial			
									AND G.STypeId <> @STypeId
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId			
						AND P.IfSerial = @intSysMngSerial			
						AND G.STypeId <> @STypeId
						AND T.ID = d.ID
			)a	
			
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】分支机构属性不正确，不能过账！'	
				RETURN -907 --失败
			END			
		
		
		SELECT	@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId
									AND P.IfSerial = @intSysMngSerial
									AND G.State NOT IN (13,32)
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.State NOT IN (13,32)
						AND T.ID = d.ID
			)a	
	
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在委托代销库中不存在，不能过账！'	
				RETURN -907 --失败
			END

		--判断委托结算的时候往来单位的属性是否正确
		SELECT	@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId
									AND P.IfSerial = @intSysMngSerial
									AND G.State = 13
									AND G.BTypeId1 <> @BTypeId
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.State = 13
						AND G.BTypeId1 <> @BTypeId
						AND T.ID = d.ID
			)a	
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】往来单位的属性不正确！'	
				RETURN -907 --失败
			END
	END


--采购退货的序列号在结算之前不允许采购退货
IF @BillType = 6
	BEGIN
		--判断序列号是否是未结算的序列号
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND ISNULL(G.CommissionState,'')='0'	
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND ISNULL(G.CommissionState,'')='0'	
				AND T.ID = d.ID
	)a	

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】未结算前不允许采购退货出库！'	
				RETURN -907 --失败
			END
	END
	
--暂估退货的序列号在结算之前不允许暂估退货
IF @BillType = 401
	BEGIN
		--判断序列号是否是未结算的序列号
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND ISNULL(G.CommissionState,'')='0'	
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND ISNULL(G.CommissionState,'')='0'	
				AND T.ID = d.ID
	)a	

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】未结算前不允许暂估退货出库！'	
				RETURN -907 --失败
			END
	END	
	
--分支机构调拨的序列号在结算之前不允许采购退货
IF @BillType = 187
BEGIN
		--判断序列号是否是未结算的序列号
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND ISNULL(G.CommissionState,'')='0'
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND ISNULL(G.CommissionState,'')='0'	
				AND T.ID = d.ID
	)a	
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】未结算前不允许分支机构调拨出库！'	
				RETURN -907 --失败
			END
	END	

--已经受托结算了的序列号不能做受托代销退货
IF @BillType = 146
BEGIN
		--判断受托代销收货的序列号往来单位是否正确
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId				
							AND P.IfSerial = @intSysMngSerial
							AND G.BTypeId2 <> @BTypeId
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId				
				AND P.IfSerial = @intSysMngSerial
				AND G.BTypeId2 <> @BTypeId
				AND T.ID = d.ID
	)a	
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】往来单位属性不正确！'
				RETURN -907 --失败
			END

		--判断序列号是否在库存中(已结算或者是非受托库存的序列号)
		
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId				
							AND P.IfSerial = @intSysMngSerial
							AND (ISNULL(G.CommissionState,'') = '1' OR ISNULL(G.CommissionState,'') = '')
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId				
				AND P.IfSerial = @intSysMngSerial
				AND (ISNULL(G.CommissionState,'') = '1' OR ISNULL(G.CommissionState,'') = '')
				AND T.ID = d.ID
	)a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】状态不正确，不能受托退货！'
				RETURN -907 --失败
			END
	END

	
--其他出库单只能对state=1 即在库的序列号进行出库
/*
	其他出库单 202
	门店配送单 327
*/
IF @BillType IN (202,327)
BEGIN		
	SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
	FROM(
			SELECT P.nId,T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.State<>1						
					)d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.State<>1						
					AND T.ID = d.ID
		)a
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】状态不正确，不能出库！'	
				RETURN -907 --失败
			END
	END	


--判断序列号的基本信息中单据明细中的是否一致,对于代销的，对于成本的判断等，动态


IF @BillType IN (305,11,12,402,6,401,146,140,9,139,183,187,202)
BEGIN
	IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.CargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		)
		AND @intserialrelation=1
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR b.CargoID<>c.CargoID
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			
			RETURN -907 --失败
	END
END
ELSE
BEGIN
	--146 
	IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
			--OR b.CargoID<>c.CargoID
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END
END	



--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	KTypeId,
	State,
	CommissionState,
	ID
)						
SELECT	T.Serial,
		T.PTypeId,
		T.KTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND T.PTypeId = G.PTypeId



--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
SELECT	TOP 1 
		@ErrId = P.nId,
		@ErrSerial = T.Serial 	
FROM	#AllSerial T,			
		#TmpPType P
WHERE	T.PTypeId = P.PTypeId		
		AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
ORDER BY T.Id ASC	


IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
		RETURN -907 --失败
	END

--写序列号的出入口记录
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		OutKTyeID,
		IfCheck,
		BillType,
		BTypeID1,
		BTypeID2,
		OutKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	A.Serial,
		A.PTypeId,
		@nBillId,
		A.KTypeId,	--@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (305,11,12,140,141,139,183,202,402) THEN @BTypeID
			ELSE ''
		END,
		CASE
			WHEN @BillType IN (6,146,401) THEN @BTypeID
			ELSE ''
		END,
		@BillDate,
		CASE 
			WHEN State = 7 AND @BillType IN (305,11,12,402) THEN 9
			WHEN State = 7 AND @BillType = 187 THEN 31
			WHEN State = 7 AND @BillType = 9 THEN 10
			WHEN State = 7 AND @BillType IN (139,183) THEN 11
			WHEN State = 7 AND @BillType = 140 THEN 32
			WHEN ISNULL(A.CommissionState,'')='0' AND @BillType = 141 THEN 14
			WHEN State IN (2,4,5,9,10,11,12,13,15,16,21,22,23,402) THEN 2
			ELSE @State
		END,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#UnionSerial A,#TmpPType B
WHERE A.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END			

--修改当前出库的序列号状态
UPDATE	Gp_CruPTypeSerial
SET		BTypeID1 = 
					CASE
						WHEN @BillType IN (305,11,12,140,141,139,183,202,402) THEN @BTypeID
						ELSE BTypeID1
					END,
		BTypeId2 = 
					CASE
						WHEN @BillType IN (6,146,401) THEN @BTypeID
						ELSE BTypeID2
					END,
		OutKTypeTime = @BillDate,
		Flag = 0,
		State =	CASE
					WHEN T.State = 7 AND @BillType IN (305,11,12,402) THEN 9
					WHEN T.State = 7 AND @BillType = 187 THEN 31
					WHEN T.State = 7 AND @BillType = 9 THEN 10
					WHEN T.State = 7 AND @BillType IN (139,183) THEN 11
					WHEN T.State = 7 AND @BillType = 140 THEN 32
					WHEN ISNULL(T.CommissionState,'')='0' AND @BillType = 141 THEN 14
					WHEN T.State IN (2,4,5,9,10,11,12,13,15,16,21,22,23,402) THEN 2
					ELSE @State
				END,
		CommissionState = CASE
							WHEN @BillType IN (146) THEN NULL
							ELSE G.CommissionState
						  END
FROM 	Gp_CruPTypeSerial G,
		#UnionSerial T,
		#TmpPType P
WHERE	G.Serial = T.Serial 
		AND G.PTypeId = T.PTypeId
		AND G.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND T.ID=P.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END		

--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'
		


--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000),
	@nRet		INT
	
SELECT
	@nBillId=9,
	@OperatorId='00001'
	
BEGIN TRAN

EXEC @nRet=Gp_SerialOperate_ck
	@nBillId,
	@OperatorId,
	@szPID	output
	
SELECT @nRet,@szPID

ROLLBACK TRAN	



*/





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_ck_ks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_ck_ks]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Gp_SerialOperate_ck_ks 2,'00001',''
	作者：谢吉康
	日期：2006-3-3
	描述：出库的序列号单独过帐	
	
	修改：毛欣蓉
	日期：2011-08-31
	描述：增加其他出库单序列号过账（单据编号202）
	
	修改：赵斌
	时间：2012年2月10日 14:54:37
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	
	修改：冯波
	时间：2015-05-16
	描述：序列号严密关联
*/
CREATE   PROCEDURE Gp_SerialOperate_ck_ks
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output,		--返回信息
	@BillType    INT = 0	--单据类型
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		--@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@IfWx				int,
		@STypeId			varchar(50)


--获取该单据的具体信息
if @BillType =327             --991新增门店配送单
begin
SELECT	@BillDate	= BillDate,
		@BTypeId 	= '',
		@inKTypeId	= KTypeId,
		@billType	= BillType,
		@IfWx		= '',
		@STypeId    = STypeId
FROM	PosAllotApplyBillIndex
WHERE	BillNumberId = @nBillId
end
else
begin
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,		
		@billType	= BillType,
		@IfWx		= IfWx,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId
end
SET @CommissionState = NULL
SET @ErrId = 0


DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	KTypeId			varchar(100),
	State			int,
	CommissionState	varchar(5),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 305	--零售单
	BEGIN
		SET @mxTableName = 'RetailBill'
		SET @State = 2
		SET @InOutState = 2
		SET @Flag = 0
	END

IF @billType = 11	--销售出库单
	BEGIN
		SET @mxTableName = 'SaleBill'
		SET @State = 2
		SET @InOutState = 2
		SET @Flag = 0
	END
	

IF @billType = 12	--组合品销售出库单
	BEGIN
		SET @mxTableName = 'PT_Combin_SaleBillDetail'
		SET @State = 2
		SET @InOutState = 2
		SET @Flag = 0
	END	
	
IF @billType = 402	--发出商品出库单
	BEGIN
		SET @mxTableName = 'SendBill'
		SET @State = 2
		SET @InOutState = 2
		SET @Flag = 0
	END
		

IF @billType = 6	--采购退货
	BEGIN
		SET @mxTableName = 'BuyBackBill'
		SET @State = 3
		SET @InOutState = 3
		SET @Flag = 0
	END
	
	
IF @billType = 401	--暂估退货
	BEGIN
		SET @mxTableName = 'AppraisalBackBill'
		SET @State = 3
		SET @InOutState = 3
		SET @Flag = 0
	END		

IF @billType = 146	--受托代销退货
	BEGIN
		SET @mxTableName = 'CommissionBill'
		SET @State = 8
		SET @InOutState = 8
		SET @Flag = 0
	END

IF @billType = 140	--委托代销发货
	BEGIN

		SET @mxTableName = 'CommissionBill'
		SET @State = 13
		SET @InOutState = 13
		SET @Flag = 0
	END

IF @billType = 141	--委托代销结算
	BEGIN
		SET @mxTableName = 'CommissionBill'
		SET @State = 14
		SET @InOutState = 14
		SET @Flag = 0
	END

IF @billType = 9 	--报损单
	BEGIN
		SET @mxTableName = 'LoseBill'
		SET @State = 4
		SET @InOutState = 4
		SET @Flag = 0
	END

IF @billType = 139	--赠送单
	BEGIN
		SET @mxTableName = 'GiveBill'
		SET @State = 5
		SET @Flag = 5
		SET @InOutState = 5
		SET @CInOutState = 5
		SET @Cstate	= 5
	END	
	
IF @billType = 183	--积分兑换单
	BEGIN
		SET @mxTableName = 'IntegralExchangeBill'
		SET @State = 5
		SET @Flag = 5
		SET @InOutState = 5
		SET @CInOutState = 5
		SET @Cstate	= 5
	END	
	
IF @BillType = 187 --分支机构调拨出库单
	BEGIN
		SET @mxTableName = 'STypeMoveBill'		
		SET @State = 30
		SET @InOutState = 30
		SET @Flag = 0
	END	
	
IF @billType = 202	--其他出库单
	BEGIN
		SET @mxTableName = 'OtherInOutBill'
		SET @State = 31
		SET @InOutState = 2
		SET @Flag = 0
	END	
IF @billType = 327	--门店配送单
	BEGIN
		SET @mxTableName = 'DeliveryBill'
		SET @State = 35
		SET @InOutState = 35
		SET @Flag = 0
	END
--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+'M.ItemID,
	M.IsCombined,'
					
	IF @BillType in(187,328,329)
		SET @SQL=@SQL+'M.OutCargoID,'
	ELSE if @BillType=327
	SET @SQL=@SQL+'M.CargoIDout,'							
	ELSE
		SET @SQL=@SQL+'M.CargoID,'
		
						
	SET @SQL=@SQL+'		M.ProduceDate,
						M.ValidDate,
						M.GoodsNumber,
						CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
			SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0 '
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

--PRINT(@SQL)

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标

OPEN MngSerialNormal01

--处理结果

FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN

		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					KTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				) '
									
		--判断是否启用了多仓库
		IF(@BillType =327)
		 BEGIN
		   IF EXISTS(SELECT TOP 1 1 FROM Qp_MulStockConfig WHERE IsChecked=1 AND BillType=327)
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeIdOut,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
		ELSE
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@InKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))  
		 END 
	ELSE
		BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM DBO.SYSOBJECTS S,dbo.syscolumns C WHERE s.id = c.id and S.name = @mxTableName AND C.name = 'KTypeId')
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
		ELSE
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@inKTypeId+''' AS KTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
       END
		SET @SerialSQL = @SerialSQL + '
				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TKTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TKTypeId = KTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,KTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,KTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,KTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)

		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
	
--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET KTypeId = @inKTypeId WHERE ISNULL(KTypeId,'')=''
UPDATE #AllSerial SET KTypeId = @inKTypeId WHERE ISNULL(KTypeId,'')=''	

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END
DECLARE @IsLend	INT =0 
SELECT  @IsLend = islend from billindex where billnumberid = @nBillId

--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1 AND @IsLend = 0
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.Flag = 0 and G.State IN(18)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.Flag = 0 and G.State IN(18)
					AND T.ID=d.ID
		) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
		--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
	IF @mngLendSerial = 1 AND @IsLend = 0
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.Flag = 1 and G.State IN(17)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.Flag = 1 and G.State IN(17)
					AND T.ID=d.ID
		) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
/******借欠转销售更新借欠序列号状态******/

IF @billType IN (11,12) AND EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillNumberId=@nBillId AND IsLend = 1)
BEGIN
	UPDATE a SET a.STATE = 33,Flag=1 FROM dbo.gp_LendPtypeSerial  a JOIN #AllSerial b
	ON a.Serial = b.Serial
END

/******借欠转销售更新借欠序列号状态******/

--从新置空错误ID的提示
SET @ErrId = 0

--判断商品属性是否正确

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId <> T.PTypeId					
						AND P.IfSerial = @intSysMngSerial	
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId <> T.PTypeId					
			AND P.IfSerial = @intSysMngSerial	 
			AND T.ID=d.ID
) a
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
		RETURN -907 --失败
	END

IF @BillType <> 141
	BEGIN
		--序列号（判断仓库属性）
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId <> T.KTypeId	--@inKTypeId	
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId <> T.KTypeId	--@inKTypeId	
					AND P.IfSerial = @intSysMngSerial	 
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	

				RETURN -907 --失败
			END

		--判断序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = T.KTypeId	--@inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State = 25)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = T.KTypeId	--@inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State = 25)	 
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END
	END
ELSE	--委托代销结算必须是委托发货的序列号
	BEGIN
		--判断分支机构
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId			
							AND P.IfSerial = @intSysMngSerial			
							AND G.STypeId <> @STypeId
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId			
				AND P.IfSerial = @intSysMngSerial			
				AND G.STypeId <> @STypeId 
				AND T.ID=d.ID


		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】分支机构属性不正确，不能过账！'	
				RETURN -907 --失败
			END
				
				
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.State NOT IN( 13,32)
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.State NOT IN( 13,32)
				AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在委托代销库中不存在，不能过账！'	
				RETURN -907 --失败
			END

		SELECT	TOP 1
				@ErrSerial = Serial
		FROM	#AllSerial
		WHERE	Serial NOT IN (SELECT Serial FROM GP_CruPTypeSerial WHERE State IN(13,32))

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在委托代销库中不存在，不能过账！'	
				RETURN -907 --失败
			END

		--判断委托结算的时候往来单位的属性是否正确
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.State = 13
							AND G.BTypeId1 <> @BTypeId
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.State = 13
				AND G.BTypeId1 <> @BTypeId
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】往来单位的属性不正确！'	
				RETURN -907 --失败
			END
	END


--采购退货的序列号在结算之前不允许采购退货
IF @BillType = 6
	BEGIN
		--判断序列号是否是未结算的序列号
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND ISNULL(G.CommissionState,'')='0'
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND ISNULL(G.CommissionState,'')='0'
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】未结算前不允许采购退货出库！'	
				RETURN -907 --失败
			END
	END
	
--分支机构调拨的序列号在结算之前不允许采购退货
IF @BillType = 187
	BEGIN
		--判断序列号是否是未结算的序列号
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND ISNULL(G.CommissionState,'')='0'
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND ISNULL(G.CommissionState,'')='0'
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】未结算前不允许分支机构调拨出库！'	
				RETURN -907 --失败
			END
	END		

--已经受托结算了的序列号不能做受托代销退货
IF @BillType = 146
	BEGIN
		--判断受托代销收货的序列号往来单位是否正确
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId				
							AND P.IfSerial = @intSysMngSerial
							AND G.BTypeId2 <> @BTypeId
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId				
				AND P.IfSerial = @intSysMngSerial
				AND G.BTypeId2 <> @BTypeId
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】往来单位属性不正确！'
				RETURN -907 --失败
			END

		--判断序列号是否在库存中(已结算或者是非受托库存的序列号)
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId				
							AND P.IfSerial = @intSysMngSerial
							AND (ISNULL(G.CommissionState,'') = '1' OR ISNULL(G.CommissionState,'') = '')
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId				
				AND P.IfSerial = @intSysMngSerial
				AND (ISNULL(G.CommissionState,'') = '1' OR ISNULL(G.CommissionState,'') = '')
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】状态不正确，不能受托退货！'
				RETURN -907 --失败
			END
	END

IF @IfWx = 0 AND @BillType <> 141
	BEGIN
		--判断序列号是否在【正常】库存中
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = T.KTypeId	--@inKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State = 25)
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.KTypeId	--@inKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND (G.Flag = 0 OR G.State = 25)
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END
	END
	
		
--其他出库单只能对state=1 即在库的序列号进行出库
/*
	其他出库单 202
	门店配送单 327
*/
IF @BillType IN (202,327)
	BEGIN	
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.State<>1					
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.State<>1					
				AND T.ID=d.ID
				
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】状态不正确，不能出库！'	
				RETURN -907 --失败
			END
	END	


--判断序列号的基本信息中单据明细中的是否一致,对于代销的，对于成本的判断等，动态
IF @BillType IN (305,11,12,402,6,401,146,140,9,139,183,187,202)
BEGIN
	IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
		)
		AND @intserialrelation=1
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
			--OR b.CargoID<>c.CargoID
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END
END
ELSE
BEGIN
	--146 
	IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			--OR b.CargoID<>c.CargoID
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END
END	



--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	KTypeId,
	State,
	CommissionState,
	ID
)						
SELECT	T.Serial,
		T.PTypeId,
		T.KTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND T.PTypeId = G.PTypeId


--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则强行写入库中
IF @BillType <> 141
	BEGIN
		SELECT	TOP 1 				
				@ErrSerial = T.Serial 	
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial
				AND G.Flag = 0
		ORDER BY T.Id ASC	
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】已有出库记录，不能出库！'	
				RETURN -907 --失败
			END
	END

--写序列号的出入口记录
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		OutKTyeID,
		IfCheck,
		BillType,
		BTypeID1,
		BTypeID2,
		InKTypeTime,
		OutKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		a.KTypeId,	--@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (305,11,12,140,141,139,183,202,402) THEN @BTypeID
			ELSE ''
		END,
		CASE
			WHEN @BillType IN (6,146,401) THEN @BTypeID
			ELSE ''
		END,
		@BillDate,
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id		
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)


INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID1,
	BTypeID2,
	InKTypeTime,
	OutKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		a.KTypeId,	--@inKTypeId,
		a.PTypeId,
		BTypeID1 = 
					CASE
						WHEN @BillType IN (305,11,12,140,141,139,183,202,402) THEN @BTypeID
						ELSE ''
					END,
		BTypeId2 = 
					CASE
						WHEN @BillType IN (6,146,401) THEN @BTypeID
						ELSE ''
					END,
		@BillDate,
		@BillDate,
		@State,
		0,
		'',
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)


--写序列号的出入口记录
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		OutKTyeID,
		IfCheck,
		BillType,
		BTypeID1,
		BTypeID2,
		OutKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		U.KTypeId,	--@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (305,11,12,140,141,139,183,202,402) THEN @BTypeID
			ELSE ''
		END,
		CASE
			WHEN @BillType IN (6,146,401) THEN @BTypeID
			ELSE ''
		END,
		@BillDate,
		CASE 
			WHEN State = 7 AND @BillType IN (305,11,12,402) THEN 9
			WHEN State = 7 AND @BillType = 187 THEN 31
			WHEN State = 7 AND @BillType = 9 THEN 10
			WHEN State = 7 AND @BillType IN (139,183) THEN 11
		  WHEN State = 7 AND @BillType IN (140) THEN 32
			WHEN ISNULL(U.CommissionState,'')='0' AND @BillType = 141 THEN 14
			WHEN U.State IN (2,4,5,9,10,11,12,13,15,16,21,22,23,402) THEN 2
			ELSE @State
		END,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID
		
IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END			
SELECT State, * FROM dbo.gp_inoutPtypeSerial WHERE Serial='020302'
--修改当前出库的序列号状态
UPDATE	Gp_CruPTypeSerial
SET		BTypeID1 = 
					CASE
						WHEN @BillType IN (305,11,12,140,141,139,183,202,402) THEN @BTypeID
						ELSE BTypeID1
					END,
		BTypeId2 = 
					CASE
						WHEN @BillType IN (6,146,401) THEN @BTypeID
						ELSE BTypeID2
					END,
		OutKTypeTime = @BillDate,
		Flag = 0,
		State =	CASE
					WHEN T.State = 7 AND @BillType IN (305,11,12,402) THEN 9
					WHEN T.State = 7 AND @BillType = 187 THEN 31
					WHEN T.State = 7 AND @BillType = 9 THEN 10
					WHEN T.State = 7 AND @BillType IN (139,183) THEN 11
					WHEN T.State = 7 AND @BillType = 140 THEN 32
					WHEN ISNULL(T.CommissionState,'')='0' AND @BillType = 141 THEN 14
					WHEN T.State IN (2,4,5,9,10,11,12,13,15,16,21,22,23,402) THEN 2
					ELSE @State
				END,
		CommissionState = CASE
							WHEN @BillType IN (146) THEN NULL
							ELSE G.CommissionState
						  END
FROM 	Gp_CruPTypeSerial G,
		#UnionSerial T,
		#TmpPType P
WHERE	G.Serial = T.Serial
		AND G.PTypeId = T.PTypeId
		AND G.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND T.ID=P.ID
	

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END		
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

SELECT * FROM dbo.gp_CruPtypeSerial WHERE Serial='01101'

SELECT * FROM dbo.gp_inoutPtypeSerial WHERE Serial='01101'


--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_db]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_db]
GO


/*
	作者：谢吉康
	日期：2006-3-3
	描述：调拨的序列号单独过帐	
	
	修改：赵斌
	日期：2012年2月10日 10:47:52
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改：冯波
	时间：2015-04-21
	描述：序列号严密关联
*/
CREATE  PROCEDURE Gp_SerialOperate_db
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@STypeId			varchar(50)


--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@outKTypeId	= KTypeId,
		@inKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId	= STypeID
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0


DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod OUTPUT




DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'



--建立商品临时表
CREATE TABLE #TmpPType
(
	nId			int identity(1,1),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int,
	IfSerial	int,
	ItemID			INT,
	IsCombined		INT,
	InKTypeID		VARCHAR(50),
	InCargoID		INT,
	OutKTypeID		VARCHAR(50),
	OutCargoID		INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) ,
	GoodsCostPrice	 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int,
	CostPrice			 NUMERIC(24, 10) ,
	GoodsNumber			VARCHAR(100),
	GoodsOrder			INT
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 				varchar(200),
	PTypeId				varchar(100),
	InKTypeId			varchar(100),
	OutKTypeId			varchar(100),
	State				int,
	CommissionState		varchar(5),
	ID					BIGINT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int,
	CostPrice			 NUMERIC(24, 10) ,
	GoodsNumber			VARCHAR(100),
	GoodsOrder			INT
)

IF @billType = 17	--同价调拨单
	BEGIN
		SET @mxTableName = 'MoveBill'
		SET @State = 1
		SET @InOutState = 1
		SET @CinOutState = 2
		SET @Flag = 1
	END

IF @billType = 21 --变价调拨
	BEGIN
		SET @mxTableName = 'MoveBjBill'
		SET @State = 1
		SET @InOutState = 1
		SET @CinOutState = 2
		SET @Flag = 1
	END	

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'





--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,'
					
IF @intserialrelation=1
BEGIN					
	SET @SQL = @SQL + 'M.ItemID,
	M.IsCombined,'
END
ELSE
BEGIN
	SET @SQL = @SQL + '0,0,'
END					

SET @SQL = @SQL + 'M.KTypeID2,'
	
IF @intserialrelation=1
BEGIN	
	SET @SQL = @SQL + 'M.InCargoID,'
END
ELSE
BEGIN
	SET @SQL = @SQL + '0,'
END					

SET @SQL = @SQL +'M.KTypeID,'
					
IF @intserialrelation=1
BEGIN					
	SET @SQL = @SQL +'M.OutCargoID,
	M.ProduceDate,
	M.ValidDate,
	M.GoodsNumber,
	CASE '+@nCostingMethod+' WHEN 3 THEN CASE '+CAST(@billType AS VARCHAR(50))+' WHEN 21  THEN M.Price ELSE CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END END ELSE 0 END,
	CASE '+@nCostingMethod+' WHEN 3 THEN M.GoodsCostPrice  ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL = @SQL +'	0,'''','''','''',
						CASE '+@nCostingMethod+' WHEN 3 THEN CASE '+CAST(@billType AS VARCHAR(50))+' WHEN 21  THEN M.Price ELSE CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END END ELSE 0 END,
						0 '
END		
			
SET @SQL = @SQL +' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0 '
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

--PRINT(@SQL)
EXEC(@SQL)



--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		--DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				) '
										
		--判断是否启用了多仓库
		IF EXISTS(SELECT TOP 1 1 FROM DBO.SYSOBJECTS S,dbo.syscolumns C WHERE s.id = c.id and S.name = @mxTableName AND C.name = 'KTypeId')
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId2,KTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
		ELSE
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@inKTypeId+''','''+@outKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
					

		SET @SerialSQL = @SerialSQL + '
				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

					
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeID,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeID,Qty,Id)
				SELECT Serial,Serial1,PTypeId,@TInKTypeId,@TOutKTypeId,Qty,Id
				FROM #TmpSerial
					
					'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01	

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		--DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

	
--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET InKTypeId =@InKTypeId WHERE ISNULL(InKTypeId,'')=''
UPDATE #AllSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''	


--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1
	BEGIN
		SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_LendPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_LendPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND P.IfSerial = @intSysMngSerial
									AND G.Flag = 0 and G.State IN(18)
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 0 and G.State IN(18)
						AND T.ID = d.ID
			)a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
		--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
	IF @mngLendSerial = 1
	BEGIN
		SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_LendPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_LendPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND P.IfSerial = @intSysMngSerial
									AND G.Flag = 1 and G.State IN(17)
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 1 and G.State IN(17)
						AND T.ID = d.ID
			)a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END

--从新置空错误ID的提示
SET @ErrId = 0

--判断商品属性是否正确
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId <> T.PTypeId					
							AND P.IfSerial = @intSysMngSerial
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId <> T.PTypeId					
				AND P.IfSerial = @intSysMngSerial
				AND T.ID = d.ID
	)a			
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
		RETURN -907 --失败
	END

--序列号（判断仓库属性）
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId <> T.OutKTypeId	--@inKTypeId	
							AND P.IfSerial = @intSysMngSerial
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId <> T.OutKTypeId	--@inKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND T.ID = d.ID
	)a
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
		RETURN -907 --失败
	END

--判断序列号是否在库存中
SELECT	@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM(
		SELECT P.nId,T.Serial
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = T.OutKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State NOT IN (1,7))
				)d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@inKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND (G.Flag = 0 OR G.State NOT IN (1,7))
				AND T.ID = d.ID
	)a
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
		RETURN -907 --失败
	END


--判断序列号的基本信息中单据明细中的是否一致,对于代销的，对于成本的判断等，动态
IF EXISTS(
	SELECT a.Serial FROM #AllSerial a
	INNER JOIN #TmpPType b
	ON a.ID=b.ID
	LEFT JOIN gp_CruPtypeSerial c
	ON a.Serial=c.Serial
	WHERE (b.ItemID <> c.ItemID
	OR b.Iscombined<>c.IsCombined
	OR b.GoodsNumber<>c.GoodsNumber
	OR b.ProduceDate<>c.ProduceDate
	OR b.ValidDate<>c.ValidDate
	OR b.OutCargoID<>c.CargoID
	OR (@nCostingMethod=3 AND b.GoodsCostPrice<>c.CostPrice)
	)
	AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.OutCargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.GoodsCostPrice<>c.CostPrice)
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END



--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	InKTypeId,
	OutKTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		T.InKTypeId,
		T.OutKTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 
		AND G.Flag = 1
		AND G.KTypeId = T.OutKTypeId	--@inKTypeId
		AND G.PTypeId IN (SELECT PTypeId FROM #TmpPType)

--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
SELECT	TOP 1 
		@ErrId = P.nId,
		@ErrSerial = T.Serial
FROM	#AllSerial T,
		#TmpPType P
WHERE	T.PTypeId = P.PTypeId		
		AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
ORDER BY T.Id ASC	

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
		RETURN -907 --失败
	END

--写序列号跟踪记录（出库）
INSERT INTO Gp_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		OutKTyeID,
		IfCheck,
		BillType,
		BTypeID1,
		OutKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		detailID
		
)
SELECT	A.Serial,
		A.PTypeId,
		@nBillId,
		B.OutKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		@CinOutState,
		B.ItemID,
		B.IsCombined,
		B.OutCargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#UnionSerial A,#TmpPType B
WHERE A.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO Gp_InOutPTypeSerial (
	Serial,
	PTypeID,
	BillNumberID,
	InKTypeID,
	IfCheck,
	BillType,
	BTypeID2,
	InKTypeTime,
	State,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice,
	detailID
)
SELECT	T.Serial,
		B.PTypeId,
		@nBillId,
		B.InKTypeId,	--@outKTypeID,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		State,
		B.ItemID,
		B.IsCombined,
		B.InCargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END		
	


--修改调拨序列号的仓库、入库时间等的信息【InKTypeTime = @BillDate 调拨入库的时间不动 V366修改】

/*
SELECT '#TmpPType',* FROM #TmpPType
SELECT '#AllSerial',* FROM #AllSerial
SELECT '#UnionSerial',* FROM #UnionSerial

SELECT @intserialrelation,@intSysMngSerial

SELECT 'result',P.InKTypeId
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeID
		AND G.PTypeId = P.PTypeId
		AND G.Flag = 1
		AND G.KTypeId = T.OutKTypeId	--@inKTypeId
		AND P.IfSerial = @intSysMngSerial
		AND ISNULL(G.GoodsNumber,'')=ISNULL(P.GoodsNumber,'')
		AND ISNULL(G.ProduceDate,'')=ISNULL(P.ProduceDate,'')
		AND ISNULL(G.ValidDate,'')=ISNULL(P.ValidDate,'')
		AND ((ISNULL(G.CostPrice,0)=ISNULL(P.GoodsCostPrice,0) AND @intserialrelation=1 AND @nCostingMethod=3) OR (@nCostingMethod<>3))
		AND ISNULL(G.ItemID,0)=ISNULL(P.ItemID,0)
		AND ISNULL(G.IsCombined,0)=ISNULL(P.IsCombined,0)
		AND B.Id=P.Id
		AND B.Id=T.ID
*/	
		
UPDATE	Gp_CruPTypeSerial 
SET		KTypeId  = P.InKTypeId,	--@outKTypeID
		CargoID=P.InCargoID,
		CostPrice=P.CostPrice
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeID
		AND G.PTypeId = P.PTypeId
		AND G.Flag = 1
		AND G.KTypeId = T.OutKTypeId	--@inKTypeId
		AND P.IfSerial = @intSysMngSerial
		AND 
		(
			(
			@intserialrelation=1
			AND ISNULL(G.GoodsNumber,'')=ISNULL(P.GoodsNumber,'')
			AND ISNULL(G.ProduceDate,'')=ISNULL(P.ProduceDate,'')
			AND ISNULL(G.ValidDate,'')=ISNULL(P.ValidDate,'')
			AND ISNULL(G.ItemID,0)=ISNULL(P.ItemID,0)
			AND ISNULL(G.IsCombined,0)=ISNULL(P.IsCombined,0)
			) OR @intserialrelation=0
		)
		AND ( (ISNULL(G.CostPrice,0)=ISNULL(P.GoodsCostPrice,0) AND @intserialrelation=1 AND @nCostingMethod=3) OR (@nCostingMethod<>3) OR (@intserialrelation=0 AND @nCostingMethod=3) )
		
		AND B.Id=P.Id
		AND B.Id=T.ID
		

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的入库记录失败！'
		RETURN -903
	END
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	
	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000),
	@nRet		INT
	
SELECT
	@nBillId=1196714,
	@OperatorId='00001'
	

BEGIN TRAN

select KtypeID,CargoID,* from gp_CruPtypeSerial
where serial='357555055357414'


EXEC @nRet=Gp_SerialOperate_db
	@nBillId,
	@OperatorId,
	@szPID	OUT
	
SELECT @nRet,@szPID

select KtypeID,CargoID,* from gp_CruPtypeSerial
where serial='357555055357414'

ROLLBACK TRAN




*/






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_dgrid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_dgrid]
GO






/*
	作者：谢吉康
	日期：2006-3-3
	描述：拆装、换货、维修的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 11:30:10
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	EXEC Gp_SerialOperate_dgrid 115,'',''
	
	修改:冯波
	日期:2015-05-14
	描述:序列号严密关联
*/
CREATE    PROCEDURE Gp_SerialOperate_dgrid
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(MAX),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(MAX),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@STypeId			varchar(50)
		

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@outKTypeId	= KTypeId,
		@inKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId	= STypeID
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	InKTypeId		varchar(100),
	OutKTypeId		varchar(100),
	State			int,
	CommissionState	varchar(10),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 16	--生产拆装单
	BEGIN
		SET @mxTableName = 'DisassembleBill'
		SET @State = 1
		SET @Flag  = 1
		SET @InOutState = 1
		SET @CinOutState = 15
		SET @Cstate = 15
	END

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.InOrOut WHEN '+CHAR(39)+'I'+CHAR(39)+' THEN M.CostPrice ELSE CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
					
			SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0
					AND M.InOrOut = ''O'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

--PRINT(@SQL)

EXEC(@SQL)




--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@inKTypeId+''' AS InKTypeId,KTypeId AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''O'' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				
				'	
		--PRINT(@SerialSQL)							
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='出库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''
UPDATE #AllSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.Flag = 0 and G.State IN(18)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.Flag = 0 and G.State IN(18)
					AND T.ID=d.ID
		) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
	
	--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.Flag = 1 and G.State IN(17)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.Flag = 1 and G.State IN(17)
					AND T.ID=d.ID
		) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
--从新置空错误ID的提示
SET @ErrId = 0

--********************************************************************************************************************正式处理【出库】的序列号，如果拆分后的序列号表中的序列号为空，则表明是宽松管理的商品或者在宽松管理模式下没有录入任何的序列号*******************************************************************************************--
IF EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--序列号（判断仓库属性）
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId <> T.OutKTypeId	--@inKTypeId	
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId <> T.OutKTypeId	--@inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断商品属性是否正确
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId <> T.PTypeId					
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId <> T.PTypeId					
					AND P.IfSerial = @intSysMngSerial
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = T.OutKTypeId	--@inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State NOT IN (1,7))
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = T.InKTypeId	--@inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State NOT IN (1,7))
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END
			
		--序列号状态为33的只允许门店退货和门店验收 入库

		IF @BillType =16
			BEGIN
			SELECT
					@ErrId = a.nId,
					@ErrSerial = a.Serial
			FROM
			(		
				SELECT 	P.nId, T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT 	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.Flag = 0
									AND G.State IN (35) 
						) d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.Flag = 0
						AND G.State IN (35)
						AND T.ID=d.ID
				
			) a
			END
			IF @ErrId <> 0
				BEGIN
					SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在配送在途的状态！'
					RETURN -907 --失败
				END	
				
	
	--判断出库部分
	IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.CargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		)
		AND @intserialrelation=1
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR b.CargoID<>c.CargoID
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END	
			

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			InKTypeId,
			OutKTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				T.InKTypeId,
				T.OutKTypeId,
				G.State,
				ISNULL(G.CommissionState,'') AS CommissionState,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@inKTypeId
				AND G.Flag = 1
		
		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT  P.nId,
					T.Serial
			FROM	#AllSerial	T,
					#TmpPType	P,
					(
						SELECT	MIN(T.Id) AS ID
						FROM	#AllSerial T,
								#TmpPType P
						WHERE	T.PTypeId = P.PTypeId		
								AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					)d
			WHERE	T.PTypeId = P.PTypeId		
					AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					AND T.Id = d.ID
		)a
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
				RETURN -907 --失败
			END
		
		--写序列号跟踪记录（出库）
		INSERT INTO Gp_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				U.OutKTypeId,	--@inKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				CASE
					WHEN U.CommissionState='0' AND @BillType = 16 	THEN 16
					WHEN U.CommissionState='0' AND @BillType = 155 	THEN 22
					WHEN U.CommissionState=''  AND @BillType = 16 	THEN 15
					WHEN U.CommissionState='1' AND @BillType = 16 	THEN 15
					WHEN U.CommissionState=''  AND @BillType = 155 	THEN 21
					WHEN U.CommissionState='1' AND @BillType = 155 	THEN 21
					WHEN @BillType = 157 							THEN 23
				END,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=B.ID

		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901

			END
		
		--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
		UPDATE	Gp_CruPTypeSerial
		SET		BTypeId1= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId1 END,								
				OutKTypeTime = @BillDate,
				State	= CASE
							WHEN T.CommissionState='0' AND @BillType = 16 	THEN 16
							WHEN T.CommissionState='0' AND @BillType = 155 	THEN 22									
							WHEN @BillType = 16 	THEN 15
							WHEN @BillType = 155 	THEN 21
							WHEN @BillType = 157 	THEN 23
						  END,
				Flag 	= 0
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND T.PTypeId = P.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@inKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1
				AND T.ID=P.ID
				
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的出库记录失败！'
				RETURN -903
			END	
	END
--**********************************************************************************************************************************************************************************************处理【入库】序列号******************************************************************************************************************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial

--初始化错误值，重要，不然判断要出错
SET @ErrId = 0

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.InOrOut WHEN '+CHAR(39)+'I'+CHAR(39)+' THEN M.CostPrice ELSE CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
					
			SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0					
					AND M.InOrOut = ''I'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

--PRINT(@SQL)
EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal02 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal02
--处理结果
FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId AS InKTypeId,'''+@OutKTypeId+''' AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''I'' ORDER BY ID

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				
				 '	
		--PRINT(@SerialSQL)		
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='入库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='入库表格第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal02
DEALLOCATE MngSerialNormal02	

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
	 
--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET InKTypeId = @InKTypeId WHERE ISNULL(InKTypeId,'')=''
UPDATE #AllSerial SET InKTypeId = @InKTypeId WHERE ISNULL(InKTypeId,'')=''	

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--正式批量处理入库的序列号
--委托发货的序列号不允许入库 2008-04-22 V39
SELECT	TOP 1
		@ErrSerial = T.Serial
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND G.State = 13 

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='委托发货的序列号【'+CAST(@ErrSerial AS varchar(100))+'】在结算前不允许再次入库！'
		RETURN -907 --失败
	END

--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.State IN (17,20) 				
								AND G.Flag = 1 
								AND G.BFlag = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.State IN (17,20) 				
					AND G.Flag = 1 
					AND G.BFlag = 1 
					AND T.ID=d.ID
		) a

		IF @ErrId <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--处理入库的序列号

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			Gp_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						Gp_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 1 	
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND P.IfSerial = @intSysMngSerial
			AND G.Flag = 1 	 
			AND T.ID=d.ID
) a
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END

--受托代销未结算的商品不允许拆装入库
IF @BillType = 16
	BEGIN
	
	SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
	FROM
	(		
		SELECT 	P.nId, T.Serial
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND ISNULL(G.CommissionState,'')='0'  	
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND ISNULL(G.CommissionState,'')='0'  	 
				AND T.ID=d.ID
	) a
		IF @ErrId <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在受托代销结算之前不允许拆装入库！'
				RETURN -908 --失败
			END	
	END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	InKTypeId,
	OutKTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		T.InKTypeId,
		T.OutKTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 


--写序列号跟踪记录（入库）
INSERT INTO Gp_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		U.InKTypeId,	--@outKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		CASE
			WHEN U.CommissionState='0' AND @BillType IN (155,157) 	THEN 7
			ELSE 1
		END,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID


IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO Gp_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		a.InKTypeId,	--@outKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		1,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID2,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		a.InKTypeId,	--@outKTypeId,
		a.PTypeId,
		@BTypeId,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
UPDATE	Gp_CruPTypeSerial
SET		BTypeId2= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId2 END,
		PTypeId = T.PTypeId,
		KTypeId = T.InKTypeId,	--@outKTypeId,								
		OutKTypeTime = @BillDate,
		State	= CASE
					WHEN T.CommissionState='0' AND @BillType IN (155,157) 	THEN 7
					ELSE 1
				  END,
		Flag 	= 1,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=p.cargoID,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined

FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND B.ID=P.ID
		AND T.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)


SELECT
	@nBillId=51,
	@OperatorId='00001'


BEGIN TRAN
select CostPrice,KtypeID,CargoID,* from gp_CruPtypeSerial where serial='forfb'
EXEC Gp_SerialOperate_dgrid

	@nBillId,						--单据的Id
	@OperatorId,				--操作员的Id
	@szPID	output		--返回信息

SELECT @szPID
select CostPrice,KtypeID,CargoID,* from gp_CruPtypeSerial where serial='forfb'

--ROLLBACK TRAN

COMMIT TRAN

*/
--10.0000	00002	4	forfb	00002	00015		0000200001	2015-07-28 00:00:00.000	NULL		1		1	NULL	NULL	NULL	0	10.0000	0	a	00001				2	0	4	2015-07-28	2015-08-07




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_dgrid_ks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_dgrid_ks]
GO









/*
	作者：谢吉康
	日期：2006-3-3
	描述：拆装、换货、维修的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 15:06:45
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	时间:2015-05-18
	描述:序列号严密关联成本等
*/
CREATE    PROCEDURE Gp_SerialOperate_dgrid_ks
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@STypeId			varchar(50)

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@outKTypeId	= KTypeId,
		@inKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId	= STypeID
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'


--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	InKTypeId		varchar(100),
	OutKTypeId		varchar(100),
	State			int,
	CommissionState	varchar(10),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 16	--生产拆装单
	BEGIN
		SET @mxTableName = 'DisassembleBill'
		SET @State = 1
		SET @Flag  = 1
		SET @InOutState = 1
		SET @CinOutState = 15
		SET @Cstate = 15
	END

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
					
			SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0
					AND M.InOrOut = ''O'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@InKTypeId+''' AS InKTypeId,KTypeId AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''O'' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='出库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET InKTypeId = @InKTypeId WHERE ISNULL(InKTypeId,'')=''
UPDATE #AllSerial SET InKTypeId = @InKTypeId WHERE ISNULL(InKTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END
--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1
	BEGIN
	
	SELECT @ErrId =	P.nId,
			@ErrSerial = T.Serial
	FROM	#AllSerial T,
			Gp_LendPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						Gp_LendPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 0 and G.State IN(18)
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND P.IfSerial = @intSysMngSerial
			AND G.Flag = 0 and G.State IN(18)
			AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
	
	--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
IF @mngLendSerial = 1
	BEGIN
	
	SELECT @ErrId =	P.nId,
			@ErrSerial = T.Serial
	FROM	#AllSerial T,
			Gp_LendPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						Gp_LendPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 1 and G.State IN(17)
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND P.IfSerial = @intSysMngSerial
			AND G.Flag = 1 and G.State IN(17)
			AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
--从新置空错误ID的提示
SET @ErrId = 0

--********************************************************************************************************************正式处理【出库】的序列号，如果拆分后的序列号表中的序列号为空，则表明是宽松管理的商品或者在宽松管理模式下没有录入任何的序列号*******************************************************************************************--
IF EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--序列号（判断仓库属性）
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId <> T.OutKTypeId	--@inKTypeId	
							AND P.IfSerial = @intSysMngSerial
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId <> T.OutKTypeId	--@inKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断商品属性是否正确
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId <> T.PTypeId					
							AND P.IfSerial = @intSysMngSerial
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId <> T.PTypeId					
				AND P.IfSerial = @intSysMngSerial
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断序列号是否在库存中
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId =	T.OutKTypeId	--@inKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State NOT IN (1,7))
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId =	T.OutKTypeId	--@inKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND (G.Flag = 0 OR G.State NOT IN (1,7))
				AND T.ID=d.ID
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END
		
       --序列号状态为33的只允许门店退货和门店验收 入库

		IF @BillType =16
			BEGIN
			SELECT
					@ErrId = a.nId,
					@ErrSerial = a.Serial
			FROM
			(		
				SELECT 	P.nId, T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT 	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.Flag = 0
									AND G.State IN (35) 
						) d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.Flag = 0
						AND G.State IN (35)
						AND T.ID=d.ID
				
			) a
			END
			IF @ErrId <> 0
				BEGIN
					SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在配送在途的状态！'
					RETURN -907 --失败
				END	
			
		--判断出库部分
	IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
		)
		AND @intserialrelation=1
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
			--OR b.CargoID<>c.CargoID
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END	
			

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			InKTypeId,
			OutKTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				T.InKTypeId,
				T.OutKTypeId,
				G.State,
				ISNULL(G.CommissionState,'') AS CommissionState,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = t.OutKTypeId
				AND G.Flag = 1

		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则强行入库
		
		SELECT 	@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G
					WHERE	T.Serial = G.Serial
							AND G.Flag = 0
				) d
		WHERE	T.Serial = G.Serial
				AND G.Flag = 0
				AND T.ID=d.ID
				
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】已有出库记录，不能出库！'	
				RETURN -907 --失败
			END

		INSERT INTO Gp_CruPTypeSerial
		(
			Serial,
			KTypeID,
			PTypeID,
			BTypeID1,
			InKTypeTime,
			OutKTypeTime,
			State,
			Flag,
			CommissionState,
			ItemID,
			IsCombined,
			CargoID,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice
		)
		SELECT	a.Serial,
				a.OutKTypeId,	--@inKTypeId,
				a.PTypeId,
				@BTypeId,
				@BillDate,
				@BillDate,
				@State,
				@Flag,
				'',
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice		
		FROM	#AllSerial a,#TmpPType B
		WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)
		
		INSERT	INTO #UnionSerial
		(
			Serial,
			PTypeID,
			InKTypeId,
			OutKTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	Serial,
				PTypeId,
				InKTypeId,
				OutKTypeId,
				@State,
				'',
				ID
		FROM	#AllSerial
		WHERE	Serial NOT IN (SELECT Serial FROM #UnionSerial)
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				U.OutKTypeId,	--@inKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				CASE
					WHEN U.CommissionState='0' AND @BillType = 16 	THEN 16
					WHEN U.CommissionState='0' AND @BillType = 155 	THEN 22
					WHEN U.CommissionState=''  AND @BillType = 16 	THEN 15
					WHEN U.CommissionState='1' AND @BillType = 16 	THEN 15
					WHEN U.CommissionState=''  AND @BillType = 155 	THEN 21
					WHEN U.CommissionState='1' AND @BillType = 155 	THEN 21
					WHEN @BillType = 157 							THEN 23
				END,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=B.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901

			END
		
		--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
		UPDATE	Gp_CruPTypeSerial
		SET		BTypeId1= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId1 END,								
				OutKTypeTime = @BillDate,
				State	= CASE
							WHEN T.CommissionState='0' AND @BillType = 16 	THEN 16
							WHEN T.CommissionState='0' AND @BillType = 155 	THEN 22									
							WHEN @BillType = 16 	THEN 15
							WHEN @BillType = 155 	THEN 21
							WHEN @BillType = 157 	THEN 23
						  END,
				Flag 	= 0
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND T.PTypeId = P.PTypeId
				AND G.KTypeId = t.OutKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1
				AND T.ID=P.Id
				
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的出库记录失败！'
				RETURN -903
			END	
	END
--**********************************************************************************************************************************************************************************************处理【入库】序列号******************************************************************************************************************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial

--初始化错误值，重要，不然判断要出错
SET @ErrId = 0

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN M.GoodsCostPrice ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
					
			SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0					
					AND M.InOrOut = ''I'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)

	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal02 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal02
--处理结果
FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId AS InKTypeId,'''+@OutKTypeId+''' AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''I'' ORDER BY ID

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='入库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='入库表格第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal02
DEALLOCATE MngSerialNormal02	

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
	
--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET inKTypeId = @inKTypeId WHERE ISNULL(inKTypeId,'')=''
UPDATE #AllSerial SET inKTypeId = @inKTypeId WHERE ISNULL(inKTypeId,'')=''	

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--正式批量处理入库的序列号
--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.State IN (17,20) 				
							AND G.Flag = 1 
							AND G.BFlag = 1
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.State IN (17,20) 				
				AND G.Flag = 1 
				AND G.BFlag = 1
				AND T.ID=d.ID

		IF @ErrId <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--处理入库的序列号

		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 1 
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1 
				AND T.ID=d.ID
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END

--受托代销未结算的商品不允许拆装入库
IF @BillType = 16
	BEGIN
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND ISNULL(G.CommissionState,'')='0'  
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND ISNULL(G.CommissionState,'')='0' 
				AND T.ID=d.ID
		IF @ErrId <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在受托代销结算之前不允许拆装入库！'
				RETURN -908 --失败
			END	
	END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	InKTypeId,
	OutKTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		T.InKTypeId,
		T.OutKTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 


--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		U.inKTypeId,	--@outKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		CASE
			WHEN U.CommissionState='0' AND @BillType IN (155,157) 	THEN 7
			ELSE 1
		END,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		a.inKTypeId,	--@outKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		1,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)


IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID2,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		a.inKTypeId,	--@outKTypeId,
		a.PTypeId,
		@BTypeId,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
UPDATE	Gp_CruPTypeSerial
SET		BTypeId2= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId2 END,
		PTypeId = T.PTypeId,
		KTypeId = T.inKTypeId,	--@outKTypeId,								
		OutKTypeTime = @BillDate,
		State	= CASE
					WHEN T.CommissionState='0' AND @BillType IN (155,157) 	THEN 7
					ELSE 1
				  END,
		Flag 	= 1,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=p.cargoID,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND P.ID=B.ID
		AND T.ID=B.ID
	

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/*
*		实物库存  仓库入库单、仓库出库单、仓库调拨单  序列号处理
*/
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_SerialOperate_Fact',N'P'))
BEGIN
	DROP PROC GP_SerialOperate_Fact
END
GO

CREATE PROC GP_SerialOperate_Fact
(
	@BillNumberID   INT,
	@BillType       INT,
	@OperatorId		VARCHAR(100),				--操作员的Id
	@szPID 			VARCHAR(1000)	OUTPUT		--返回信息
)
AS
BEGIN
	DECLARE		@Mngserial         INT,					/*严密序列号*/
				@FromBillType      INT,					/*来源单单据类型*/
				@RowID             INT,					
				@RowCount          INT,					/*单明细行数*/
				@Qty			   NUMERIC(24,10),		/*数量*/
				@IfSerial		   CHAR(1),				/*商品严密序列号*/
				@SerialCount	   INT,					/*序列号长度*/
				@Serial			   NVARCHAR(MAX),
				@SQL			   NVARCHAR(1000),
				@ErrorID		   INT,
				@ErrorSerial	   VARCHAR(100),
				@BillDate		   DATETIME,
				@STypeID		   VARCHAR(100)
	
	DECLARE		@TmpAllSerial      TABLE
	(
		Serial	   VARCHAR(1000),
		ID		   INT	
	)
	
	DECLARE		@TmpUnionSerial    TABLE
	(
		Serial    VARCHAR(1000)
	)
	
	DECLARE	    @Tmp			   TABLE
	(
		PTypeID			 VARCHAR(100),
		FullName         VARCHAR(100),
		Qty				 NUMERIC(24,10),
		ETypeID			 VARCHAR(50),
		Serial			 NVARCHAR(MAX),
		IfSerial		 CHAR(1),
		SerialCount      INT,
		ItemID			 INT,
		IsCombined		 INT,
		ProduceDate      VARCHAR(50),
		ValidDate        VARCHAR(50),
		GoodsNumber		 VARCHAR(100),
		InKTypeID		 VARCHAR(100),
		InCargoID		 INT,
		OutKTypeID		 VARCHAR(100),
		OutCargoID		 INT,
		FromBillType     INT,
		ID			     INT
	)
	SELECT @BillDate=BilLDate,@STypeID=STypeID FROM dbo.FactIndex WHERE BillNumberId=@BillNumberID
	
	/***仓库入库单***/
	IF @BillType IN(418,419)
	BEGIN
		INSERT INTO @Tmp
					( 
					  Qty ,
					  Serial,
					  IfSerial,
					  SerialCount,
					  FromBillType,
					  ID,
					  PTypeID,
					  FullName,
					  ItemID,
					  IsCombined,
					  ProduceDate,
					  ValidDate,
					  GoodsNumber,
					  InKTypeID,
					  InCargoID,
					  OutKTypeID,
					  OutCargoID,
					  ETypeID
					)
			SELECT A.Qty,
				   A.Serial,
				   B.IfSerial,
				   B.SerialCount,
				   A.FromBillType,
				   ROW_NUMBER()OVER(ORDER BY A.ID ASC) AS ID,
				   A.PTypeID,
				   B.FullName,
				   A.ItemID,
				   A.IsCombined,
				   A.ProduceDate,
				   A.ValidDate,
				   A.GoodsNumber,
				   CASE WHEN C.BillType=418 THEN A.ktypeid ELSE '' END,
				   CASE WHEN C.BillType=418 THEN A.CargoID ELSE 0 END,
				   CASE WHEN C.BillType=419 THEN A.ktypeid ELSE '' END,
				   CASE WHEN C.BillType=419 THEN A.CargoID ELSE 0 END,
				   C.etypeid
			FROM dbo.FactDepotInOut A 
			INNER JOIN dbo.ptype B ON A.ptypeid=B.typeId
			INNER JOIN dbo.FactIndex C ON A.BillNumberID=C.BillNumberID
			WHERE C.BillNumberID=@billNumberID
	END
	ELSE	
	BEGIN
		INSERT INTO @Tmp
		        ( 
				  Qty ,
				  Serial,
				  IfSerial,
				  SerialCount,
		          FromBillType,
		          ID,
		          PTypeID,
		          FullName,
		          ItemID,
				  IsCombined,
				  ProduceDate,
				  ValidDate,
				  GoodsNumber,
				  InKTypeID,
				  InCargoID,
				  OutKTypeID,
				  OutCargoID,
				  ETypeID
		        )
			SELECT A.Qty,
				   A.Serial,
				   B.IfSerial,
				   B.SerialCount,
				   0,
				   ROW_NUMBER()OVER(ORDER BY A.ID ASC) AS ID,
				   A.PTypeID,
				   B.FullName,
				   A.ItemID,
				   A.IsCombined,
				   A.ProduceDate,
				   A.ValidDate,
				   A.GoodsNumber,
				   A.KTypeId2,
				   A.InCargoID,
				   A.KTypeId,
				   A.OutCargoID,
				   C.ETypeID
			FROM dbo.FactDepotAllot A 
			INNER JOIN dbo.ptype B ON A.ptypeid=B.typeId
			INNER JOIN dbo.FactIndex C ON A.BillNumberId=C.BillNumberId
			WHERE A.BillNumberID=@BillNumberID
	END	
	SELECT @Mngserial=Value FROM dbo.Userconfig WHERE ConfigName='Mngserial'
	SELECT @RowID=1,@RowCount=COUNT(1) FROM @Tmp
	

	
	WHILE(@RowID<=@RowCount)
	BEGIN
		SELECT @Qty=Qty,
			   @Serial=Serial,
			   @IfSerial=IfSerial,
			   @SerialCount=SerialCount
		FROM @Tmp WHERE ID=@RowID
		INSERT INTO @TmpAllSerial (Serial,ID) 
		SELECT A,@RowID
		FROM dbo.f_splitAN(ISNULL(@Serial,''),'я')
		WHERE A<>''
		
		/*严密序列号验证*/
		IF @Mngserial=1 AND @IfSerial=1
		BEGIN
			--序列号长度
			IF EXISTS(SELECT TOP 1  1 FROM @TmpAllSerial WHERE ID=@RowID AND LEN(Serial)<>@SerialCount AND @SerialCount<>0)
			BEGIN
				SET @szPID='第 '+CAST(@RowID AS varchar(1000))+' 行商品存在序列号长度与设置长度 '+CAST(@SerialCount AS varchar(1000))+' 不符的情况！'
					RETURN -905
			END
			SELECT @SerialCount=COUNT(1) FROM @TmpAllSerial WHERE ID=@RowID
			
			--序列号数量验证
			IF  @Qty<>@SerialCount 
			BEGIN
				SET @szPID='第 '+CAST(@RowID AS VARCHAR(1000))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
				RETURN -904
			END
		END
		SET @RowID=@RowID+1
	END	

	/*没有序列号*/
	IF NOT EXISTS(SELECT TOP 1 1 FROM @TmpAllSerial)
	BEGIN
		RETURN 0 
	END
	/*序列号重复*/
	IF EXISTS(SELECT TOP 1 1 FROM @TmpAllSerial GROUP BY Serial HAVING COUNT(1)>1)
	BEGIN
		SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
		RETURN -904
	END

	/*******************序列号出库*******************/
	IF  @BillType IN(419,420)
	BEGIN
		--序列号交集
		DELETE FROM @TmpUnionSerial
		INSERT INTO @TmpUnionSerial ( Serial ) SELECT A.Serial FROM @TmpAllSerial A INNER JOIN dbo.gp_FactPtypeSerial B ON A.Serial=B.Serial
		SET @ErrorID=0
		
		SELECT TOP 1 @ErrorID=A.ID,@ErrorSerial=A.Serial
		FROM @TmpAllSerial A,@Tmp B,dbo.gp_FactPtypeSerial C
		WHERE A.ID=B.ID AND C.Serial=A.Serial AND B.PTypeID<>C.PTypeID --AND B.IfSerial=1
		
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @szPID='序列号【'+CAST(@ErrorSerial AS varchar(1000))+'】商品属性不正确，不能过账！'	
			RETURN -907 --失败
		END
		
		SELECT TOP 1 @ErrorID=A.ID,@ErrorSerial=A.Serial
		FROM @TmpAllSerial A ,@Tmp B ,gp_FactPtypeSerial C 
		WHERE A.ID=B.ID AND C.Serial=A.Serial AND B.PTypeID=C.PTypeID  AND B.OutKTypeID<>C.KTypeID
		
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @szPID='序列号【'+CAST(@ErrorSerial AS varchar(1000))+'】仓库属性不正确，不能过账！'	
			RETURN -907 --失败
		END
		
		SELECT TOP 1 @ErrorID=A.ID,@ErrorSerial=A.Serial
		FROM @TmpAllSerial A ,@Tmp B,dbo.gp_FactPtypeSerial C
		WHERE A.ID=B.ID AND C.Serial=A.Serial AND B.PTypeID=C.PTypeID  AND B.OutKTypeID=C.KTypeID AND C.Flag=0
		
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @szPID='序列号【'+CAST(@ErrorSerial AS varchar(1000))+'】在当前库存中不存在！'	
			RETURN -907 --失败
		END
		
		SELECT TOP 1 @ErrorID=A.ID,@ErrorSerial=A.Serial
		FROM @TmpAllSerial A ,@Tmp B,dbo.gp_FactPtypeSerial C 
		WHERE A.ID=B.ID AND C.Serial=A.Serial AND B.PTypeID=C.PTypeID AND B.OutKTypeID=C.KTypeID AND C.STypeID<>@STypeID
		
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @szPID='序列号【'+CAST(@ErrorSerial AS varchar(1000))+'】分支机构属性不正确，不能过账！'	
			RETURN -907 --失败
		END	
		
		SELECT TOP 1 @ErrorID=A.ID,@ErrorSerial=A.Serial
		FROM @TmpAllSerial A ,
		@Tmp B,
		dbo.gp_FactPtypeSerial C
		WHERE A.ID=B.ID AND C.Serial=A.Serial AND B.PTypeID=C.PTypeID AND C.State<>1
		
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @szPID='序列号【'+CAST(@ErrorSerial AS varchar(1000))+'】状态不正确，不能出库！'	
			RETURN -907 --失败
		END
		
		SELECT TOP 1 @ErrorID=A.ID,@ErrorSerial=A.Serial
		FROM @TmpAllSerial A,
		@Tmp B 
		WHERE A.ID=B.ID AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.gp_FactPtypeSerial B WHERE A.Serial=B.Serial)
		
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @szPID='序列号【'+CAST(@ErrorSerial AS varchar(1000))+'】在当前库存中不存在!'	
			RETURN -907 --失败
		END
		
		--SELECT TOP 1 @ErrorID=A.ID,@ErrorSerial=A.Serial
		--FROM @TmpAllSerial A ,@Tmp B,dbo.gp_FactPtypeSerial C
		--WHERE A.ID=B.ID AND A.Serial=A.Serial AND B.PTypeID=C.PTypeID AND A.Serial NOT IN(SELECT Serial FROM @TmpUnionSerial)
		
		--IF @@ROWCOUNT <> 0
		--BEGIN
		--	SET @szPID='序列号【'+CAST(@ErrorSerial AS varchar(100))+'】在当前库存中不存在!'	
		--	RETURN -907 --失败
		--END
		
		INSERT INTO dbo.Fact_InoutPtypeSerial
		        ( Serial ,
		          PtypeID ,
		          BillNumberid ,
		          OutKtyeID ,
		          IfCheck ,
		          BillType ,
		          OutKtypeTime ,
		          State ,
		          GoodsNumber ,
		          LendState ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		          ProduceDate ,
		          ValidDate ,
		          Flag
		        )
		SELECT  
				  A.Serial ,
		          B.PTypeID,
		          @BillNumberID, 
		          B.OutKTypeID, 
		          't' , 
		          @BillType, 
		          @BillDate ,
		          2 , 
		          B.GoodsNumber ,
		          CASE WHEN B.FromBillType=87 THEN 2 
					   WHEN B.FromBillType=72 THEN 3
				  ELSE 0 END,
		          B.OutCargoID, 
		          B.ItemID , 
		          B.IsCombined , 
		          B.ProduceDate ,
		          B.ValidDate ,
		          0  
		FROM @TmpAllSerial A,@Tmp B 
		WHERE A.ID=B.ID
		
		IF @@ERROR <> 0
		BEGIN
			SET @szPID='写序列号的出入库记录失败！'
			RETURN -901
		END			
		
		UPDATE	dbo.gp_FactPtypeSerial
		SET		OutKTypeTime = @BillDate,
				Flag = 0,
				State =2,
				ETypeID=P.ETypeID,
				LendState= CASE WHEN P.FromBillType=87 THEN 2 
							    WHEN P.FromBillType=72 THEN 3
				           ELSE 0 END
		FROM 	gp_FactPtypeSerial G,
				@TmpAllSerial T,
				@Tmp P
		WHERE	G.Serial = T.Serial 
				AND G.PTypeId = P.PTypeId
				AND T.ID=P.ID

		IF @@ERROR <> 0
		BEGIN
			SET @szPID='修改序列号的出库记录失败！'
			RETURN -903
		END		

		--重算当前序列号库中的STypeId
	   UPDATE dbo.gp_FactPtypeSerial SET STypeId=S.STypeID
	   FROM gp_FactPtypeSerial A,@TmpAllSerial B,@Tmp C,dbo.Stock S
	   WHERE A.Serial=B.Serial AND B.ID=C.ID AND C.OutKTypeID=S.typeId 
	END
	/*******************序列号出库*******************/
	
	
	/*******************序列号入库*******************/
	IF @BillType IN(418,420)
	BEGIN
		--序列号交集
		DELETE FROM @TmpUnionSerial	
		INSERT INTO @TmpUnionSerial ( Serial ) SELECT A.Serial FROM @TmpAllSerial A INNER JOIN dbo.gp_FactPtypeSerial B ON A.Serial=B.Serial
	
		SET @ErrorID=0
		SELECT TOP 1 @ErrorID=A.ID,
				     @ErrorSerial=A.Serial 
		FROM @TmpAllSerial A
		INNER JOIN @Tmp B ON A.ID=B.ID 
		INNER JOIN dbo.gp_FactPtypeSerial C ON C.Serial=A.Serial AND C.PtypeID=C.PtypeID 
		WHERE C.Flag=1
		
		IF @ErrorID <> 0
		BEGIN
			SET @szPID='序列号【'+CAST(@ErrorSerial AS varchar(1000))+'】在当前序列号库中已存在！'
			RETURN -907 --失败
		END
		
		INSERT INTO dbo.Fact_InoutPtypeSerial
		        ( Serial ,
		          PtypeID ,
		          BillNumberid ,
		          InKtypeID ,
		          IfCheck ,
		          BillType ,
		          InKtypeTime ,
		          State ,
		          GoodsNumber ,
		          LendState ,
		          ItemID,
		          Flag,
		          IsCombined,
		          ProduceDate,
		          ValidDate,
		          CargoID
		        )
		SELECT
				  A.Serial , 
		          B.PTypeID , 
		          @BillNumberID, 
		          B.InKTypeID ,
		          't' ,
		          @BillType, 
		          @BillDate ,
		          1 , 
		          B.GoodsNumber , 
		          CASE WHEN B.FromBillType=71 THEN 1
					   WHEN B.FromBillType=88 THEN 4
					   ELSE 0
				  END, 
		          B.ItemID,
		          1,
		          B.IsCombined,
		          B.ProduceDate,
		          B.ValidDate,
		          B.InCargoID
		FROM @TmpAllSerial A,@Tmp B 
		WHERE A.ID=B.ID
		 
		IF @@ERROR <> 0
		BEGIN
			SET @szPID='写序列号的出入库记录失败！'
			RETURN -901
		END
		
		--修改已出库序列号--
		UPDATE	gp_FactPtypeSerial 
		SET		KTypeId  = c.InKTypeId,	
				PTypeId  = c.PTypeId,
				InKTypeTime = @BillDate,
				[State] = 1,
				Flag = 1,
				GoodsNumber=c.GoodsNumber,
				CargoID=c.IncargoID,
				ProduceDate=c.ProduceDate,
				ValidDate=c.ValidDate,
				ItemID=c.ItemID,
				ETypeID=C.ETypeID,
				IsCombined=c.IsCombined,
				LendState=CASE WHEN C.FromBillType=71 THEN 1
							   WHEN C.FromBillType=88 THEN 4
						  ELSE 0
						  END
		FROM gp_FactPtypeSerial A,@TmpAllSerial B,@Tmp c
		WHERE A.Serial=B.Serial 
		AND B.ID=C.ID 
		AND A.Flag=0 
		AND B.Serial IN(SELECT Serial FROM @TmpUnionSerial)
		
		
		INSERT INTO dbo.gp_FactPtypeSerial
		        ( 
				  Serial ,
		          KtypeID ,
		          PtypeID ,
		          InKtypeTime ,
		          State ,
		          Flag ,
		          GoodsNumber ,
		          ItemID ,
		          IsCombined ,
		          CargoID ,
		          ProduceDate ,
		          ValidDate,
		          LendState,
		          ETypeID
		        )
		SELECT   
				  A.Serial ,
		          B.InKTypeID, 
		          B.PTypeID , 
		          @BillDate , 
		          1 , 
		          1 , 
		          B.GoodsNumber , 
		          B.ItemID ,
		          B.IsCombined , 
				  B.InCargoID,
		          B.ProduceDate , 
		          B.ValidDate,
		          CASE WHEN B.FromBillType=71 THEN 1
					   WHEN B.FromBillType=88 THEN 4
				  ELSE 0
				  END,
				  B.ETypeID
	   FROM @TmpAllSerial A,@Tmp B
	   WHERE A.ID=B.ID AND A.Serial NOT IN(SELECT Serial FROM @TmpUnionSerial)
	   
	   --重算分支机构
	   UPDATE dbo.gp_FactPtypeSerial SET STypeId=S.STypeID
	   FROM gp_FactPtypeSerial A,@TmpAllSerial B,@Tmp C,dbo.Stock S
	   WHERE A.Serial=B.Serial AND B.ID=C.ID AND C.InKTypeID=S.typeId 
	END
	/*******************序列号入库*******************/
	
END
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_Manager]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_Manager]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-21
	描述：序列号总的处理
	
	修改:冯波
	日期:2015-04-20
	描述:序列号严密关联
*/

CREATE PROCEDURE Gp_SerialOperate_Manager
(
	@nBillId		int,						--单据的Id
	@OperatorId		varchar(100),				--操作员的Id
	@chvOpID		varchar(50) = '',			-- 当前操作员 ID 值
	@szCheck		VARCHAR(10),
	@ifWx			TINYINT,
	@chvBTypeID		VARCHAR(50),
	@chvSTypeID		VARCHAR(50),
	@szPID 			varchar(1000)	output,		--返回信息
	@billtype		INT = 0						--单据类型
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
/*
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
*/
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--判断（物流单据才进入序列号过帐，否则跳过）

DECLARE @nRet int				-- 返回的出错值

--注意检查新的几张单据的序列号处理,没加BILLTYPE

--零售单、销售出库单、销售退货单、委托发货、委托结算、委托退货、采购入库、采购退货、受托收货、受托结算、受托退货、同价调拨、变价调拨、报损单、
--报溢单、拆装单、换货单、维修受理单、赠送单、获赠单、维修接件单、维修单、维修取件单、整机更换单、送修单、送修返回单、上门维修单、维修品调入单、
--维修品调出单、维修品调拨单、分支机构调拨出库单、分支机构调拨入库单,序列号调整、门店配送退货单
IF @billtype IN (305,11,12,6,140,141,142,34,45,46,144,145,146,17,21,9,14,16,155,157,139,126,160,161,165,166,
167,168,169,170,172,173,174,175,183,187,188,201,202,203,215,57,400,401,402,403,328,327,329)
BEGIN
	IF @chvOpID = ''
		SET @chvOpID = @OperatorId
		
	IF EXISTS(SELECT TOP 1 1  FROM UserConfig WHERE ConfigName = 'mngSerial' AND Value = 1)
		BEGIN
			IF @billtype IN (34,144,126,45,46,142,188,201,215,400,403,328,329)
				EXEC @nRet = Gp_SerialOperate_rk @nBillID,@chvOpID,@szPID output,@billtype
			ELSE IF @billtype IN (17,21) 
				EXEC @nRet = Gp_SerialOperate_db @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 9
				BEGIN
					IF @ifWx = 1
						EXEC @nRet = Gp_SerialOperate_Wx_ck @nBillID,@chvOpID,@szPID output
					ELSE
						EXEC @nRet = Gp_SerialOperate_ck @nBillID,@chvOpID,@szPID output
				END
			ELSE IF @billtype = 14
				BEGIN
					IF @ifWx = 1
						EXEC @nRet = Gp_SerialOperate_Wx_rk @nBillID,@chvOpID,@szPID output
					ELSE
						EXEC @nRet = Gp_SerialOperate_rk @nBillID,@chvOpID,@szPID output
				END
			ELSE IF @billtype IN (305,11,12,6,146,140,141,139,183,187,202,401,402,327)
			begin
				EXEC @nRet = Gp_SerialOperate_ck @nBillID,@chvOpID,@szPID output,@billtype
				end
			ELSE IF @billtype = 145
				EXEC @nRet = Gp_SerialOperate_stjs @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (16)
				EXEC @nRet = Gp_SerialOperate_dgrid @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 160
				EXEC @nRet = Gp_SerialOperate_SaleExChangeGrid @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 161
				EXEC @nRet = Gp_SerialOperate_BuyExChangeGrid @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (165,170)
				EXEC @nRet = Gp_SerialOperate_Wx_rk @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (166,172)
				EXEC @nRet = Gp_SerialOperate_Wx_dgrid @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (167,168,169)
				EXEC @nRet = Gp_SerialOperate_Wx_ck @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (173,174,175)
				EXEC @nRet = Gp_SerialOperate_Wx_db @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 203
				EXEC @nRet =  Gp_SerialOperate_SerialAdjus @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 57
				EXEC @nRet =  Gp_SerialOperate_AdPrice @nBillID,@chvOpID,@szPID output
			ELSE
				BEGIN
					SET @szPID = '您现在进入序列号处理旧流程，请与开发人员联系！'
					RETURN -907
				END
		END
	ELSE
		BEGIN
			IF @billtype IN (34,144,126,45,46,142,188,201,215,400,403,328,329)
				EXEC @nRet = Gp_SerialOperate_rk @nBillID,@chvOpID,@szPID output,@billtype
			ELSE IF @billtype IN (17,21) 
				EXEC @nRet = Gp_SerialOperate_db @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 9
				BEGIN
					IF @ifWx = 1
						EXEC @nRet = Gp_SerialOperate_Wx_ck_ks @nBillID,@chvOpID,@szPID output
					ELSE
						EXEC @nRet = Gp_SerialOperate_ck_ks @nBillID,@chvOpID,@szPID output
				END
			ELSE IF @billtype = 14
				BEGIN
					IF @ifWx = 1
						EXEC @nRet = Gp_SerialOperate_Wx_rk @nBillID,@chvOpID,@szPID output
					ELSE
						EXEC @nRet = Gp_SerialOperate_rk @nBillID,@chvOpID,@szPID output
				END						
			ELSE IF @billtype IN (305,11,12,6,146,140,141,139,183,187,202,401,402,327)
				EXEC @nRet = Gp_SerialOperate_ck_ks @nBillID,@chvOpID,@szPID output,@billtype

			ELSE IF @billtype = 145
				EXEC @nRet = Gp_SerialOperate_stjs @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (16)
				EXEC @nRet = Gp_SerialOperate_dgrid_ks @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 160
				EXEC @nRet = Gp_SerialOperate_SaleExChangeGrid_ks @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 161
				EXEC @nRet = Gp_SerialOperate_BuyExChangeGrid_ks @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (165,170)
				EXEC @nRet = Gp_SerialOperate_Wx_rk @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (166,172)
				EXEC @nRet = Gp_SerialOperate_Wx_dgrid_ks @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (167,168,169)
				EXEC @nRet = Gp_SerialOperate_Wx_ck_ks @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype IN (173,174,175)
				EXEC @nRet = Gp_SerialOperate_Wx_db @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 203
				EXEC @nRet =  Gp_SerialOperate_SerialAdjus @nBillID,@chvOpID,@szPID output
			ELSE IF @billtype = 57
				EXEC @nRet =  Gp_SerialOperate_AdPrice @nBillID,@chvOpID,@szPID output
			ELSE 
				BEGIN
					SET @szPID = '您现在进入序列号处理旧流程，请与开发人员联系！'
					RETURN -907
				END
		END	

	IF @nRet <> 0
	BEGIN
		--ROLLBACK TRAN
		RETURN @nRet
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_rk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_rk]
GO






/*
	作者：谢吉康
	日期：2006-3-3
	描述：入库的序列号单独过帐	
	
	修改：毛欣蓉
	日期：2011-08-31
	描述：增加其他入库单序列号过账（单据编号203）
	
	修改：赵斌
	时间：2012年2月10日 10:46:53
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	日期:2015-05-14
	描述:序列号严密关联
*/
CREATE   PROCEDURE Gp_SerialOperate_rk
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output	,	--返回信息
	@BillType    INT = 0	--单据类型
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		--@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@STypeID			varchar(max)
		
				

--获取该单据的具体信息
--获取该单据的具体信息
if @BillType in (328,329)             --991新增门店配送单
begin
SELECT	@BillDate	= BillDate,
		@BTypeId 	= '',
		@inKTypeId	= InKtypeId,
		@billType	= BillType,		
		@STypeId    = STypeId
FROM	PosAllotApplyBillIndex
WHERE	BillNumberId = @nBillId
end
else
begin
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,		
		@billType	= BillType,
		@STypeID    = Stypeid 
FROM	BillIndex
WHERE	BillNumberId = @nBillId
end
SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'




--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 				varchar(200),
	PTypeId				varchar(100),
	KTypeId				varchar(100),
	State				int,
	CommissionState		varchar(5),
	ID					INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--处理单据的明细表名称
IF @billType = 34	--采购
	BEGIN
		SET @mxTableName = 'BuyBill'
		SET	@State = 1
		SET @InOutState = 1
		SET @Flag  = 1
	
	END
	
IF @billType = 400	--暂估入库
	BEGIN
		SET @mxTableName = 'AppraisalBill'
		SET	@State = 1
		SET @InOutState = 1
		SET @Flag  = 1
		
	END
	


IF @billType = 144	--受托代销收货
	BEGIN
		SET @mxTableName = 'CommissionBill'
		SET @State = 7
		SET @InOutState = 7
		SET @Flag = 1
		SET @CommissionState = 0
		
	END

IF @billType = 14	--报溢单
	BEGIN
		SET @mxTableName = 'OverflowBill'
		SET @State = 1
		SET @InOutState = 1
		SET @Flag = 1
		
	END

IF @billType = 126 	--获赠单
	BEGIN
		SET @mxTableName = 'GiveMeBill'
		SET @State = 1
		SET @Flag = 1
		SET @InOutState = 1
		
	END	

IF @billType = 45	--销售退货单
	BEGIN
		SET @mxTableName = 'SaleBackBill'
		SET @State = 1
		SET @InOutState = 1
		SET @Flag = 1
		EXEC @SerialSaleBack = GP_CheckLimit @OperatorID,342
		
	END
	
IF @billType = 46	--组合品销售退货单
	BEGIN
		SET @mxTableName = 'PT_Combin_SaleBackBillDetail'
		SET @State = 1
		SET @InOutState = 1
		SET @Flag = 1
		EXEC @SerialSaleBack = GP_CheckLimit @OperatorID,342
		
	END	
	
IF @billType = 403	--发出商品退货单
	BEGIN
		SET @mxTableName = 'SendBackBill'
		SET @State = 1
		SET @InOutState = 1
		SET @Flag = 1
		EXEC @SerialSaleBack = GP_CheckLimit @OperatorID,342
		
	END
	

IF @billType = 142	--委托代销退货
	BEGIN
		SET @mxTableName = 'CommissionBill'
		SET @State = 1
		SET @InOutState = 1
		SET @Flag = 1
		
		
	END
	
IF @BillType = 188 --分支机构调拨入库单
	BEGIN
		SET @mxTableName = 'STypeMoveBill'
		SET @State = 1
		SET @Flag = 1
		SET @InOutState = 1
		
		
	END

IF @billType = 201	--其他入库单
	BEGIN
		SET @mxTableName = 'OtherInOutBill'
		SET	@State = 1
		SET @InOutState = 1
		SET @Flag  = 1
		
		
	END

IF @billType = 215	--零售退货单
	BEGIN
		SET @mxTableName = 'RetailBackBill'
		SET	@State = 1
		SET @InOutState = 1
		SET @Flag  = 1
		EXEC @SerialSaleBack = GP_CheckLimit @OperatorID,342
		
		
	END	
IF @billType = 328	--门店配送退货
BEGIN
	SET @mxTableName = 'DeliveryBackBill'
	SET @State = 1
	SET @InOutState = 1
	SET @Flag = 1
END
IF @billType = 329	--门店验收单
BEGIN
	SET @mxTableName = 'DeliveryCheckBill'
	SET @State = 1
	SET @InOutState = 1
	SET @Flag = 1
END
		
	
--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN									
	SET @SQL=@SQL+'
					M.ItemID,
					M.IsCombined,'

	IF @BillType=188 
		SET @SQL=@SQL+'M.InCargoID,'					
	ELSE
	BEGIN
		IF @BillType IN (328,329)  
			SET @SQL=@SQL+'M.InCargoID,'
		ELSE
			SET @SQL=@SQL+'M.CargoID,'
	END
						
	SET @SQL=@SQL+'M.ProduceDate,
						M.ValidDate,
						M.GoodsNumber,'
	
	IF @billType IN (201,188)
	BEGIN
		SET @SQL=@SQL+'CASE '+@nCostingMethod+' WHEN 3 THEN M.Price ELSE 0 END  '
	END
	ELSE IF @BillType IN (126,14,142,45,46,215,144)
	BEGIN
		SET @SQL=@SQL+' CASE '+@nCostingMethod+' WHEN 3 THEN (
			SELECT CostPrice
			FROM InoutStockTable
			WHERE BillNumberID = '+CAST(@nBillId AS varchar(100))+'
			AND ID=M.ID '
			
			IF @BillType IN (142,144)
			BEGIN
				SET @SQL=@SQL+' AND KTypeID<>'+CHAR(39)+'10000'+CHAR(39)
			END
			
		SET @SQL=@SQL+' ) ELSE 0 END	'
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END  ELSE 0 END  '
	END					
						
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
			SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0 '


--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

--PRINT @SQL

EXEC(@SQL)

--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		

		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	

					Serial 	varchar(max),
					PTypeId	varchar(100),
					KTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				) '
      	if(@BillType = 327 or @BillType = 328 or @BillType = 329 )
		begin
		IF EXISTS(SELECT top 1 1 FROM	Qp_MulStockConfig where BillType=327 and  ischecked=1)
		        IF @BillType = 327
				SET @SerialSQL = @SerialSQL + '	INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
				ELSE
				--启用多仓库是表体
				SET @SerialSQL = @SerialSQL + '	INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,inKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
		ELSE
		--没启用多仓库是表头
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@inKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100)) 
		end
		else
		begin
		--判断是否启用了多仓库
		IF EXISTS(SELECT TOP 1 1 FROM DBO.SYSOBJECTS S,dbo.syscolumns C WHERE s.id = c.id and S.name = @mxTableName AND C.name = 'KTypeId')
			IF @BillType = 188
				SET @SerialSQL = @SerialSQL + '	INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId2,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
			ELSE
				SET @SerialSQL = @SerialSQL + '	INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
		ELSE
			SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,KTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@inKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100)) 
       end
		SET @SerialSQL = @SerialSQL + '
				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(MAX),
						@TPTypeId			varchar(100),
						@TKTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TKTypeId = KTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,KTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,KTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,KTypeId,Qty,Id
				FROM #TmpSerial
			
					'								
		--PRINT(@SerialSQL)
		EXEC(@SerialSQL)
		
		--PRINT('bbb')
		--PRINT(@SerialCount)
		--PRINT('cc')
		
		--PRINT(@Qty)
	
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id
				IF @Qty<>@SerialCount
					BEGIN						
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
	
--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET KTypeId = @inKTypeId WHERE ISNULL(KTypeId,'')=''
UPDATE #AllSerial SET KTypeId = @inKTypeId WHERE ISNULL(KTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--正式批量判断和写入序列号
--委托发货的序列号不允许入库 2008-04-22 V39
IF @BillType <> 142 AND @intSysMngSerial = 1
	BEGIN
		SELECT	TOP 1
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G
		WHERE	T.Serial = G.Serial
				AND G.State = 13 
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='委托发货的序列号【'+CAST(@ErrSerial AS varchar(100))+'】在结算前不允许再次入库！'
				RETURN -907 --失败
			END
	END
DECLARE @IsLend	INT =0 
SELECT  @IsLend = islend from billindex where billnumberid = @nBillId
--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1 AND @IsLend = 0
	BEGIN
		
	SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
	FROM(
			SELECT P.nId,T.Serial
			FROM	#AllSerial T,
					GP_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.State IN (17,20) 
								AND G.Flag = 1 
								AND G.BFlag = 1
					)d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.State IN (17,20) 
					AND G.Flag = 1 
					AND G.BFlag = 1
					AND T.ID = d.ID
		)a

		IF @ErrId <> 0
			BEGIN				
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--序列号状态为33的只允许门店退货和门店验收 入库

IF @BillType NOT IN (328,329)
BEGIN
SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.Flag = 0
						AND G.State IN (35) 
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.Flag = 0
			AND G.State IN (35)
			AND T.ID=d.ID
	
) a
END
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在配送在途的状态！'
		RETURN -907 --失败
	END
	
SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.Flag = 1
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.Flag = 1 
			AND T.ID=d.ID
	
) a

IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END
	
--受托代销的序列号在结算之前只允许“销售退货”，“委托代销退货”入库
IF @BillType NOT IN (45,46,142,188,215,403)
	BEGIN
		
		SELECT	@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM	(
					SELECT	p.nId,
							T.Serial
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P,
							(
								SELECT	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										GP_CruPTypeSerial G,
										#TmpPType P
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND ISNULL(G.CommissionState,'')='0'
							)d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND ISNULL(G.CommissionState,'')='0'	
							AND T.ID = d.ID
		)a

		IF @ErrId <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在受托代销结算之前不允许再次入库！'
				RETURN -908 --失败
			END	
	END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial
(
	Serial,
	PTypeId,
	KTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		T.KTypeId,
		G.State,
		CASE
			WHEN ISNULL(G.CommissionState,'')='' OR ISNULL(G.CommissionState,'')='1' THEN @CommissionState
			ELSE ISNULL(G.CommissionState,'')
		END AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 

SET @UnionCount = @@ROWCOUNT
SELECT @Qty = ISNULL(COUNT(*),0) FROM #AllSerial

--委托代销退货的序列号必须是委托发货的序列号,否则代销库会产生负库存
IF @BillType = 142
	BEGIN	
		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
		SELECT	TOP 1 
				@ErrId = P.nId,
				@ErrSerial = T.Serial 	
		FROM	#AllSerial T,			
				#TmpPType P
		WHERE	T.PTypeId = P.PTypeId		
				AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
		ORDER BY T.Id ASC			
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
				RETURN -907 --失败
			END

		--委托代销发货的序列号才能委托代销退货
		
		SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId
									AND P.IfSerial = @intSysMngSerial
									AND G.State Not IN (13,32)
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.State Not IN (13,32)
						AND T.ID = d.ID
			)a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在委托代销库中不存在，不能过账！'	
				RETURN -907 --失败
			END

		--判断委托结算的时候往来单位的属性是否正确
		
		SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId
									AND P.IfSerial = @intSysMngSerial
									AND G.State IN (13,32)
									AND G.BTypeId1 <> @BTypeId
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.State IN (13,32)
						AND G.BTypeId1 <> @BTypeId
						AND T.ID = d.ID
			)a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】往来单位的属性不正确！'	
				RETURN -907 --失败
			END	
			
		--判断分支机构
		
		SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId			
									AND P.IfSerial = @intSysMngSerial			
									AND G.[State] IN (13,32)				
									AND G.STypeId <> @STypeId
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId			
						AND P.IfSerial = @intSysMngSerial			
						AND G.[State] IN (13,32)				
						AND G.STypeId <> @STypeId
						AND T.ID = d.ID
			)a

		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】分支机构属性不正确，不能过账！'	
				RETURN -907 --失败
			END				
	END		
	
--销售退货需要判断分支机构和原来是否一致，如果不一致则不能退货入库	
IF @BillType IN(45,46,215)
	BEGIN
		--判断分支机构
		
		SELECT	@ErrId = a.nId,
			@ErrSerial = a.Serial
		FROM(
				SELECT P.nId,T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						(
							SELECT	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND G.PTypeId = T.PTypeId			
									AND P.IfSerial = @intSysMngSerial			
									AND G.[State] IN (8,9,10,11,16,31)
									AND G.STypeId <> @STypeId
						)d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId			
						AND P.IfSerial = @intSysMngSerial			
						AND G.[State] IN (8,9,10,11,16,31)
						AND G.STypeId <> @STypeId
						AND T.ID = d.ID
			)a
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】分支机构属性不正确，不能过账！'	
				RETURN -907 --失败
			END	
	END

--判断是否有“允许未销售过的序列号销售退货入库”的权限
IF @SerialSaleBack = 1 AND @BillType IN( 45,46,215,403)
	BEGIN							
		SELECT	TOP 1
				@ErrSerial = T.Serial 	
		FROM	#AllSerial T
		WHERE	T.Serial NOT IN (SELECT Serial FROM Gp_CruPTypeSerial WHERE State IN (2,9))
		ORDER BY T.Id ASC			
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='您没有“允许未销售过的序列号销售退货、零售退货、发出商品退货入库”的权限，不能过帐！'
				RETURN -907 --失败
			END
	END					

--写序列号跟踪记录（如果是当前序列号库中的序列号，如果受托未被结算，则入库状态是受托代销库存中，否则未库存中）


INSERT INTO GP_InOutPTypeSerial (
	Serial,
	PTypeID,
	BillNumberID,
	InKTypeID,
	IfCheck,
	BillType,
	BTypeID1,
	BTypeID2,
	InKTypeTime,
	State,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice,
	detailID
	
)



SELECT	T.Serial,
		T.PTypeId,
		@nBillId,
		T.KTypeId,	--@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (45,46,142,215,403) THEN @BTypeId
			ELSE ''
		END,
		CASE 
			WHEN @BillType IN (34,144,126,201,400) THEN @BTypeId
			ELSE ''
		END,
		@BillDate,
		CASE
			WHEN ISNULL(U.CommissionState,'')='0' THEN 7
			ELSE @InOutState
		END,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.ID
		
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--新入库的序列号，则未为库存中
INSERT INTO GP_InOutPTypeSerial (
	Serial,
	PTypeID,
	BillNumberID,
	InKTypeID,
	IfCheck,
	BillType,
	BTypeID1,
	BTypeID2,
	InKTypeTime,
	State,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice,
	detailID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		a.KTypeId,	--@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (45,46,142,215,403) THEN @BTypeId
			ELSE ''
		END,
		CASE 
			WHEN @BillType IN (34,144,126,201,400) THEN @BTypeId
			ELSE ''
		END,
		@BillDate,
		@InOutState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END




--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID1,
	BTypeID2,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		a.KTypeId,	--@inKTypeId,
		a.PTypeId,
		CASE
			WHEN @BillType IN (45,46,142,215,403) THEN @BTypeId
			ELSE ''
		END,
		CASE 
			WHEN @BillType IN (34,144,126,201,400) THEN @BTypeId
			ELSE ''
		END,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END
	
	

--修改已经出库了的序列号的状态【InKTypeTime = @BillDate 销售退货已经在库的序列号，时间不动 V366修改】
UPDATE	Gp_CruPTypeSerial 
SET		KTypeId  = T.KTypeId,	--@inKTypeId,
		PTypeId  = T.PTypeId,
		BTypeID1 = 
					CASE
						WHEN @BillType IN (45,46,142,215,403) THEN @BTypeId
						ELSE BTypeID1
					END,
		BTypeID2 = 
					CASE 
						WHEN @BillType IN (34,144,126,201,400) THEN @BTypeId
						ELSE BTypeID2
					END,
		InKTypeTime = 
				CASE
					WHEN @BillType IN (45,46,142,215,403) THEN InKTypeTime
					ELSE @BillDate
				END,
		State = CASE
					WHEN ISNULL(T.CommissionState,'')='0' THEN 7
					ELSE @InOutState
			     END,
		Flag = @Flag,
		CommissionState = CASE
							WHEN ISNULL(T.CommissionState,'')='' THEN @CommissionState
							ELSE ISNULL(T.CommissionState,'')
						  END,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=p.cargoID,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined

		
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND T.Serial=B.Serial
		AND P.ID=B.ID
		AND T.ID=B.ID


IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的入库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

/******借欠转采购更新借欠序列号状态******/

IF @billType = 34 AND @IsLend = 1
BEGIN
	UPDATE a SET a.STATE = 34 FROM dbo.gp_LendPtypeSerial  a JOIN #AllSerial b
	ON a.Serial = b.Serial
	WHERE a.STATE <> 18
END

/******借欠转采购更新借欠序列号状态******/

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000),
	@nRet		INT
	
SELECT
	@nBillId=4,
	@OperatorId='00001'
	

BEGIN TRAN

update GP_CruPTypeSerial
set flag=0


EXEC @nRet=Gp_SerialOperate_rk
	@nBillId,
	@OperatorId,
	@szPID	OUT
	
SELECT @nRet,@szPID


SELECT CostPrice,* from gp_CruPtypeSerial

ROLLBACK TRAN

	


*/





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_SaleExChangeGrid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_SaleExChangeGrid]
GO








/*
	作者：谢吉康
	日期：2007-3-19
	描述：销售换货单序列号单独过帐
	
	修改：赵斌
	时间：2012年2月10日 13:22:38
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	时间:2015-05-13
	描述:序列号严密关联成本等
*/
CREATE   PROCEDURE Gp_SerialOperate_SaleExChangeGrid
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@STypeId			varchar(50)

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	InKTypeId		varchar(100),
	OutKTypeId		varchar(100),	
	State			int,
	CommissionState	varchar(10),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),	
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 160	--销售换货单
	BEGIN
		SET @mxTableName = 'SaleGoodsExchangeBill'
		SET @State = 1
		SET @Flag  = 1
		SET @InOutState = 1
		SET @CinOutState = 2
		SET @Cstate = 2
	END


--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--*****************************************************************************************************************************处理出库序列号*******************************************************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial

--初始化错误值，重要，不然判断要出错
SET @ErrId = 0

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+					
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END	

				
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
		PType P
WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
		AND P.TypeId = M.PTypeId
		AND P.SonNum = 0
		AND P.Deleted = 0
		AND M.InOrOut = ''O'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)


--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@InKTypeId+''' AS InKTypeId,KTypeId AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''O'' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='出库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''
UPDATE #AllSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''

--判断是否有相同的序列号




IF EXISTS(
	SELECT Serial 
	FROM #AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)
BEGIN
		SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
		RETURN -904
END

--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1
	BEGIN
	
	SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
	FROM
	(		
		SELECT 	P.nId, T.Serial
		FROM	#AllSerial T,
				Gp_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 0 and G.State IN(18)
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 0 
				AND T.ID=d.ID
	) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
	--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库	
	IF @mngLendSerial = 1
	BEGIN
	
	SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
	FROM
	(		
		SELECT 	P.nId, T.Serial
		FROM	#AllSerial T,
				Gp_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 1 and G.State IN(17)
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 0 
				AND T.ID=d.ID
	) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
	
--对出库序列号进行判断	
IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.CargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		)
		AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.CargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END
	

--从新置空错误ID的提示
SET @ErrId = 0

--正式处理出库的序列号，如果拆分后的序列号表中的序列号为空，则表明是宽松管理的商品或者在宽松管理模式下没有录入任何的序列号
IF EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--序列号（判断仓库属性）
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
					AND P.IfSerial = @intSysMngSerial 
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断商品属性是否正确
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId <> T.PTypeId					
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId <> T.PTypeId					
					AND P.IfSerial = @intSysMngSerial 
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = T.OutKTypeId	--@outKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State NOT IN (1,7))
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = T.OutKTypeId	--@outKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State NOT IN (1,7)) 
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			InKTypeId,
			OutKTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				T.InKTypeId,
				T.OutKTypeId,
				G.State,
				ISNULL(G.CommissionState,'') AS CommissionState,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@outKTypeId
				AND G.Flag = 1

		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885	
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT  P.nId,
					T.Serial
			FROM	#AllSerial	T,
					#TmpPType	P,
					(
						SELECT	MIN(T.Id) AS ID
						FROM	#AllSerial T,
								#TmpPType P
						WHERE	T.PTypeId = P.PTypeId		
								AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					)d
			WHERE	T.PTypeId = P.PTypeId		
					AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					AND T.Id = d.ID
		)a
		
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
				RETURN -907 --失败
			END
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				U.OutKTypeId,	--@outKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				CASE
					WHEN U.CommissionState='0' THEN 9
					WHEN U.CommissionState=''  THEN 2
					ELSE 2
				END,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice	,
				B.Id
		FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
		WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901

			END
		
		--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
		UPDATE	Gp_CruPTypeSerial
		SET		BTypeId1= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId1 END,								
				OutKTypeTime = @BillDate,
				State	= CASE
							WHEN T.CommissionState='0' THEN 9							
							WHEN T.CommissionState=''  THEN 2
							ELSE 2
						  END,
				Flag 	= 0
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P
		WHERE	T.Serial = G.Serial
				AND G.PTypeId = T.PTypeId
				AND T.PTypeId = P.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@outKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1
				AND T.ID=P.ID
				
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的出库记录失败！'
				RETURN -903
			END	
	END

--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'
		
--*****************************************************************************************************************************处理入库序列号*******************************************************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial
--从新置空错误ID的提示
SET @ErrId = 0
	
--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+					
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN CASE M.InputCostPrice WHEN 0 THEN DBO.F_GetRecPrice(M.STypeID,M.PTypeID) ELSE InputCostPrice END ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END	

				
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0					
					AND M.InOrOut = ''I'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)

--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal02 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal02
--处理结果
FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId AS InKTypeId,'''+@OutKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''I'' ORDER BY ID

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='入库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='入库表格第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal02
DEALLOCATE MngSerialNormal02	

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET InKTypeId = @inKTypeId WHERE ISNULL(InKTypeId,'')=''
UPDATE #AllSerial SET InKTypeId = @inKTypeId WHERE ISNULL(InKTypeId,'')=''

--判断是否有相同的序列号


	
IF EXISTS(
	SELECT Serial 
	FROM #AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)
BEGIN
		SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
		RETURN -904
END
	
	
--委托发货的序列号不允许入库 2008-04-22 V39
SELECT	TOP 1
		@ErrSerial = T.Serial
FROM	#AllSerial T,
		GP_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND G.State = 13 

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='委托发货的序列号【'+CAST(@ErrSerial AS varchar(100))+'】在结算前不允许再次入库！'
		RETURN -907 --失败
	END

--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.State IN (17,20) 				
								AND G.Flag = 1 
								AND G.BFlag = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.State IN (17,20) 				
					AND G.Flag = 1 
					AND G.BFlag = 1
					AND T.ID=d.ID
		) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--处理入库的序列号

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 1
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND P.IfSerial = @intSysMngSerial
			AND G.Flag = 1
			AND T.ID=d.ID
) a
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	InKTypeId,
	OutKTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		T.InKTypeId,
		T.OutKTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 

SET @UnionCount = @@ROWCOUNT
SELECT @Qty = ISNULL(COUNT(*),0) FROM #AllSerial

--判断是否有“允许未销售过的序列号销售退货入库”的权限
EXEC @SerialSaleBack = GP_CheckLimit @OperatorID,342
IF @SerialSaleBack = 1
	BEGIN									
		IF @Qty <> @UnionCount
			BEGIN
				SET @szPID='您没有“允许未销售过的序列号销售退货入库”的权限，不能过帐！'
				RETURN -907 --失败
			END
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID1,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		U.InKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		CASE
			WHEN U.CommissionState='0' THEN 7
			ELSE 1
		END,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID
		
IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID1,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	A.Serial,
		A.PTypeId,
		@nBillId,
		A.InKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		1,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.ID	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)


IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID1,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	A.Serial,
		A.InKTypeId,	--@inKTypeId,
		A.PTypeId,
		@BTypeId,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
UPDATE	Gp_CruPTypeSerial
SET		BTypeId1= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId1 END,
		PTypeId = T.PTypeId,
		KTypeId = T.InKTypeId,	--@inKTypeId,								
		InKTypeTime = CASE WHEN ISNULL(InKTypeTime,'')<>'' THEN InKTypeTime ELSE @BillDate END,
		State	= CASE
					WHEN T.CommissionState='0' THEN 7
					ELSE 1
				  END,
		Flag 	= 1,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=p.cargoID,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined

FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND P.ID=B.ID
		AND T.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	


--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_SaleExChangeGrid_ks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_SaleExChangeGrid_ks]
GO










/*
	作者：谢吉康
	日期：2007-3-19
	描述：销售换货单序列号单独过帐
	
	修改：赵斌
	时间：2012年2月10日 15:11:39
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	时间:2015-05-11
	描述:序列号严密关联成本等
*/
CREATE   PROCEDURE Gp_SerialOperate_SaleExChangeGrid_ks
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@STypeId			varchar(50)

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	InKTypeId		varchar(100),
	OutKTypeId		varchar(100),
	State			int,
	CommissionState	varchar(10),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	InKTypeId	varchar(100),
	OutKTypeId	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 160	--销售换货单
	BEGIN
		SET @mxTableName = 'SaleGoodsExchangeBill'
		SET @State = 1
		SET @Flag  = 1
		SET @InOutState = 1
		SET @CinOutState = 2
		SET @Cstate = 2
	END


--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'



--***********************************************************************************************************处理出库序列号********************************************************************************************--

--初始化错误值，重要，不然判断要出错
SET @ErrId = 0

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+					
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END	

				
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0
					AND M.InOrOut = ''O'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)

--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@InKTypeId+''' AS InKTypeId,KTypeId AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''O'' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='出库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET InKTypeId = @inKTypeId WHERE ISNULL(InKTypeId,'')=''
UPDATE #AllSerial SET InKTypeId = @inKTypeId WHERE ISNULL(InKTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END
--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1
	BEGIN
	
	SELECT	@ErrId =	P.nId,
			@ErrSerial = T.Serial
	FROM	#AllSerial T,
			Gp_LendPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						Gp_LendPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 0 and G.State IN(18)
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND P.IfSerial = @intSysMngSerial
			AND G.Flag = 0 and G.State IN(18)
			AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
		--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
	IF @mngLendSerial = 1
	BEGIN
	
	SELECT	@ErrId =	P.nId,
			@ErrSerial = T.Serial
	FROM	#AllSerial T,
			Gp_LendPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						Gp_LendPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 1 and G.State IN(17)
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND P.IfSerial = @intSysMngSerial
			AND G.Flag = 1 and G.State IN(17)
			AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
	
--对出库序列号进行判断	
IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
		)
		AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END	

--从新置空错误ID的提示
SET @ErrId = 0

--正式处理出库的序列号，如果拆分后的序列号表中的序列号为空，则表明是宽松管理的商品或者在宽松管理模式下没有录入任何的序列号
IF EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--序列号（判断仓库属性）
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
							AND P.IfSerial = @intSysMngSerial
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId <> T.OutKTypeId	--@outKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断商品属性是否正确
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId <> T.PTypeId					
							AND P.IfSerial = @intSysMngSerial	
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId <> T.PTypeId					
				AND P.IfSerial = @intSysMngSerial	
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断序列号是否在库存中
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = T.OutKTypeId	--@outKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State NOT IN (1,7))	
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@outKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND (G.Flag = 0 OR G.State NOT IN (1,7))	
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			InKTypeId,
			OutKTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				T.InKTypeId,
				T.OutKTypeId,
				G.State,
				ISNULL(G.CommissionState,'') AS CommissionState,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = T.OutKTypeId	--@outKTypeId
				AND G.Flag = 1

		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则强行写入
		
		SELECT	@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G
					WHERE	T.Serial = G.Serial
							AND G.Flag = 0	
				) d
		WHERE	T.Serial = G.Serial
				AND G.Flag = 0	
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】已有出库记录，不能出库！'	
				RETURN -907 --失败
			END

		INSERT INTO Gp_CruPTypeSerial
		(
			Serial,
			KTypeID,
			PTypeID,
			BTypeID1,
			BTypeID2,
			InKTypeTime,
			OutKTypeTime,
			State,
			Flag,
			CommissionState,
			ItemID,
			IsCombined,
			CargoID,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice
		)
		SELECT	a.Serial,
				a.OutKTypeId,	--@outKTypeId,
				a.PTypeId,
				@BTypeId,
				'',
				@BillDate,
				@BillDate,
				@State,
				@Flag,
				'',
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice		
		FROM	#AllSerial a,#TmpPType B
		WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)
		
		INSERT	INTO #UnionSerial
		(
			Serial,
			PTypeID,
			InKTypeId,
			OutKTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	Serial,
				PTypeId,
				InKTypeId,
				OutKTypeId,
				@State,
				'',
				ID
		FROM	#AllSerial
		WHERE	Serial NOT IN (SELECT Serial FROM #UnionSerial)
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				U.OutKTypeId,	--@outKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				CASE
					WHEN U.CommissionState='0' THEN 9
					WHEN U.CommissionState=''  THEN 2
					ELSE 2
				END,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=B.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901

			END
		
		--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
		UPDATE	Gp_CruPTypeSerial
		SET		BTypeId1= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId1 END,								
				OutKTypeTime = @BillDate,
				State	= CASE
							WHEN T.CommissionState='0' THEN 9							
							WHEN T.CommissionState=''  THEN 2
							ELSE 2
						  END,
				Flag 	= 0
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND T.PTypeId = P.PTypeId
				AND G.KTypeId = @outKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1
				AND T.ID=P.ID
			
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的出库记录失败！'
				RETURN -903
			END	
	END

--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'
		
--从新置空错误ID的提示
SET @ErrId = 0

--***********************************************************************************************************处理入库序列号********************************************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+					
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN CASE M.InputCostPrice WHEN 0 THEN DBO.F_GetRecPrice(M.STypeID,M.PTypeID) ELSE InputCostPrice END ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END	

				
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0					
					AND M.InOrOut = ''I'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)

--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal02 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal02
--处理结果
FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 		varchar(max),
					PTypeId		varchar(100),
					InKTypeId	varchar(100),
					OutKTypeId	varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Id			int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId AS InKTypeId,'''+@OutKTypeId+''' AS OutKTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''I'' ORDER BY ID

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TInKTypeId			varchar(100),
						@TOutKTypeId		varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,InKTypeId,OutKTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='入库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='入库表格第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal02
DEALLOCATE MngSerialNormal02	

/*
--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
*/

--如果仓库信息为空，则修改成表头的仓库信息
UPDATE #TmpSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''
UPDATE #AllSerial SET OutKTypeId = @OutKTypeId WHERE ISNULL(OutKTypeId,'')=''

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.State IN (17,20) 				
							AND G.Flag = 1 
							AND G.BFlag = 1
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.State IN (17,20) 				
				AND G.Flag = 1 
				AND G.BFlag = 1
				AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--处理入库的序列号

		SELECT @ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 1 
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1 
				AND T.ID=d.ID
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	InKTypeId,
	OutKTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		T.InKTypeId,
		T.OutKTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial

SET @UnionCount = @@ROWCOUNT
SELECT @Qty = ISNULL(COUNT(*),0) FROM #AllSerial

--判断是否有“允许未销售过的序列号销售退货入库”的权限
EXEC @SerialSaleBack = GP_CheckLimit @OperatorID,342
IF @SerialSaleBack = 1
	BEGIN									
		IF @Qty <> @UnionCount
			BEGIN
				SET @szPID='您没有“允许未销售过的序列号销售退货入库”的权限，不能过帐！'
				RETURN -907 --失败
			END
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID1,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		U.InKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		CASE
			WHEN U.CommissionState='0' THEN 7
			ELSE 1
		END,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID


IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID1,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		a.InKTypeId,	--@inKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		1,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID1,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		a.InKTypeId,	--@inKTypeId,
		a.PTypeId,
		@BTypeId,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改当前商品换货单、维修受理单的序列号的状态【拆装单不需要修改BTypeId1】
UPDATE	Gp_CruPTypeSerial
SET		BTypeId1= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId1 END,
		PTypeId = T.PTypeId,
		KTypeId = T.InKTypeId,	--@inKTypeId,								
		InKTypeTime = CASE WHEN ISNULL(InKTypeTime,'')<>'' THEN InKTypeTime ELSE @BillDate END,
		State	= CASE
					WHEN T.CommissionState='0' THEN 7
					ELSE 1
				  END,
		Flag 	= 1,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=p.cargoID,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND B.ID=P.ID
		AND T.ID=B.ID


IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_SerialAdjus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_SerialOperate_SerialAdjus
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉t
-- Create date: 2011-08-27
-- Description: 序列号调整单过账
-- =============================================
/*
	修改：赵斌
	时间：2012年2月10日 14:47:59
	描述：优化
*/
CREATE PROCEDURE Gp_SerialOperate_SerialAdjus
(
	@nBillId	INT,						--单据的Id
	@OperatorId	VARCHAR(100),				--操作员的Id
	@szPID 		VARCHAR(1000)	OUTPUT		--返回信息
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--BEGIN TRAN T1

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nid			INT IDENTITY(1,1),
	ID			INT,
	Serial 		VARCHAR(1000),
	oldSerial	VARCHAR(1000),
	PTypeId		VARCHAR(100)
)

INSERT INTO #TmpSerial
	SELECT ID,Serial,OldSerial,PtypeID FROM SerialAdjustBill WHERE BillNumberId=@nBillId ORDER BY ID
DECLARE @SQL				VARCHAR(MAX),
		@tmpnId				INT, 
		@tmpid				INT, 
		@tmpPtypeid			VARCHAR(50),
		@tmpBillnumberid	INT,
		@tmpSerial			VARCHAR(1000),
		@tmpOldSerial		VARCHAR(1000),
		@tmpKtypeid			VARCHAR(50),
		@tmpBtypeid1		VARCHAR(50),
		@tmpBtypeid2		VARCHAR(50),
		@tmpInKtypeTime		DATETIME,
		@tmpOutKtypeTime	DATETIME,
		@tmpState			INT,
		@tmpNote			VARCHAR(256)



DECLARE CurSType CURSOR FOR 
	SELECT ID,BillNumberId,Serial,OldSerial,KtypeID,PtypeID,BTypeID1,BTypeID2,InKtypeTime,OutKtypeTime,State,Note
	FROM  SerialAdjustBill	WHERE BillNumberId=@nBillId 
OPEN CurSType
FETCH NEXT FROM CurSType INTO @tmpId,@tmpBillnumberid,@tmpSerial,@tmpOldSerial,@tmpKtypeid,@tmpPtypeid,@tmpBtypeid1,@tmpBtypeid2,
								@tmpInKtypeTime,@tmpOutKtypeTime,@tmpState,@tmpNote
WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE @subSerial VARCHAR(50), @subOldSerial VARCHAR(50)
		SELECT TOP 1 @subSerial=A   FROM f_split(@tmpSerial,'я') B WHERE B.a<>''
		SELECT TOP 1 @subOldSerial=A   FROM f_split(@tmpOldSerial,'я')B WHERE B.a<>''
		
		--检测原来的序列号
		IF NOT EXISTS(SELECT Serial FROM gp_CruPtypeSerial WHERE Serial=@subOldSerial ) 
		BEGIN
			--RAISERROR('原序列号【%s】不存在！',16,1,@tmpOldSerial) 
			SET @szPID='原序列号【 '+CAST(@subOldSerial AS varchar(50))+'】不存在！'
			----CLOSE CurSType
			--DEALLOCATE CurSType
			RETURN -907
		END
		IF (SELECT COUNT(*) FROM #TmpSerial WHERE oldSerial=@subOldSerial)>1 
		BEGIN
			--RAISERROR('您在本张单据中录入了相同的序列号，单据过账失败！',16,1) 
			SET @szPID='您在本张单据中录入了相同的序列号，单据过账失败！'
			--CLOSE CurSType
			--DEALLOCATE CurSType
			RETURN -904
		END
			
		--检测新序列号
		DECLARE @intSerialCount INT,@intNid INT
		SELECT @intSerialCount=SerialCount FROM PType WHERE typeId=@tmpPtypeid
		SELECT @intNid=nid FROM #TmpSerial WHERE PTypeId=@tmpPtypeid AND ID=@tmpid
		IF (LEN(@subSerial) <> @intSerialCount AND  @intSerialCount<>0)
			BEGIN
					SET @szPID='第 '+CAST(@intNid AS varchar(10))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(10))+' 不符的情况！'
				--	RAISERROR('第%d行商品存在序列号长度与设置长度%d不符的情况！',16,1,@intNid,@intSerialCount) 
					--CLOSE CurSType
					--DEALLOCATE CurSType
					RETURN -905
			END
		IF  EXISTS(SELECT Serial FROM gp_CruPtypeSerial WHERE Serial=@subSerial ) 
		BEGIN
			--RAISERROR('序列号【%s】已经存在，请另设一个序列号！',16,1,@tmpOldSerial)
			SET @szPID='新序列号【 '+CAST(@subSerial AS varchar(50))+'】已经存在，请另设一个序列号！'
			--CLOSE CurSType
			--DEALLOCATE CurSType 
			RETURN -907
		END
		IF  EXISTS(SELECT Serial FROM gp_LendPtypeSerial WHERE Serial=@subSerial ) --AND EXISTS(SELECT  1 FROM UserConfig WHERE ConfigName = 'mngLendSerial' AND Value=1) 
		BEGIN
			--RAISERROR('序列号【%s】已经存在，请另设一个序列号！',16,1,@tmpOldSerial)
			--SET @szPID='由于系统采用了借欠序列号的校验模式，不能修改为序列号【 '+CAST(@subSerial AS varchar(10))+'】，请另设一个序列号！'
			SET @szPID='序列号【 '+CAST(@subSerial AS varchar(10))+'】在借欠序列号库中已存在，请另设一个序列号！'
			--CLOSE CurSType
			--DEALLOCATE CurSType 
			RETURN -907
		END
		IF (SELECT COUNT(*) FROM #TmpSerial WHERE Serial=@subSerial)>1 
		BEGIN
			--RAISERROR('您在本张单据中录入了相同的序列号，单据过账失败！',16,1) 
			SET @szPID='您在本张单据中录入了相同的序列号，单据过账失败！'
			--CLOSE CurSType
			--DEALLOCATE CurSType
			RETURN -904
		END
		IF  EXISTS(SELECT 1 FROM gp_CruPtypeSerial WHERE Serial=@subOldSerial AND KtypeID<>@tmpKtypeid)
		BEGIN
			SET @szPID='第 '+CAST(@intNid AS varchar(10))+' 行序列号的仓库属性不正确！'	
				RETURN -907 --失败
		END
		IF  EXISTS(SELECT 1 FROM gp_CruPtypeSerial WHERE Serial=@subOldSerial AND PtypeID<>@tmpPtypeid)
		BEGIN
			SET @szPID='第 '+CAST(@intNid AS varchar(10))+' 行序列号的商品属性不正确！'	
				RETURN -907 --失败
		END
		IF  EXISTS(SELECT 1 FROM gp_CruPtypeSerial WHERE Serial=@subOldSerial AND State<>@tmpState)
		BEGIN
			SET @szPID='第 '+CAST(@intNid AS varchar(10))+' 行序列号的状态不正确！'	
				RETURN -907 --失败
		END
		IF  EXISTS(SELECT 1 FROM gp_CruPtypeSerial WHERE Serial=@subOldSerial AND BTypeID1<>@tmpBtypeid1)
		BEGIN
			SET @szPID='第 '+CAST(@intNid AS varchar(10))+' 行序列号的销售商属性不正确！'	
				RETURN -907 --失败
		END
		IF  EXISTS(SELECT 1 FROM gp_CruPtypeSerial WHERE Serial=@subOldSerial AND BTypeID2<>@tmpBtypeid2)
		BEGIN
			SET @szPID='第 '+CAST(@intNid AS varchar(10))+' 行序列号的供应商属性不正确！'	
				RETURN -907 --失败
		END
		IF  EXISTS(SELECT 1 FROM gp_CruPtypeSerial WHERE Serial=@subOldSerial AND InKtypeTime<>@tmpInKtypeTime)
		BEGIN
			SET @szPID='第 '+CAST(@intNid AS varchar(10))+' 行序列号的入库时间不正确！'	
				RETURN -907 --失败
		END
		IF  EXISTS(SELECT 1 FROM gp_CruPtypeSerial WHERE Serial=@subOldSerial AND OutKtypeTime<>@tmpOutKtypeTime)
		BEGIN
			SET @szPID='第 '+CAST(@intNid AS varchar(10))+' 行序列号的出库时间不正确！'	
				RETURN -907 --失败
		END
		
		--正式开始过账
		UPDATE gp_CruPtypeSerial SET Serial=@subSerial WHERE PtypeID=@tmpPtypeid AND Serial=@subOldSerial 
		UPDATE gp_LendPtypeSerial SET Serial=@subSerial WHERE PtypeID=@tmpPtypeid AND Serial=@subOldSerial 
		
		--UPDATE gp_initPtypeSerial SET Serial=@subSerial WHERE PtypeID=@tmpPtypeid AND Serial=@subOldSerial 
		INSERT INTO gp_inoutPtypeSerial(Serial,PtypeID,BillNumberid,InKtypeID,OutKtyeID,IfCheck,BillType,BTypeID1,BTypeID2,InKtypeTime,OutKtypeTime,[User],State,DETAILID) VALUES(@subOldSerial,@tmpPtypeid,@tmpBillnumberid,'','','t','203',@tmpBtypeid1,@tmpBtypeid2,null,null,'',@tmpState,@tmpId) 
		INSERT INTO gp_inoutPtypeSerial(Serial,PtypeID,BillNumberid,InKtypeID,OutKtyeID,IfCheck,BillType,BTypeID1,BTypeID2,InKtypeTime,OutKtypeTime,[User],State,DETAILID) VALUES(@subSerial,@tmpPtypeid,@tmpBillnumberid,'','','t','203',@tmpBtypeid1,@tmpBtypeid2,null,null,'',@tmpState,@tmpId) 

	FETCH NEXT FROM CurSType INTO @tmpId,@tmpBillnumberid,@tmpSerial,@tmpOldSerial,@tmpKtypeid,@tmpPtypeid,@tmpBtypeid1,@tmpBtypeid2,
								@tmpInKtypeTime,@tmpOutKtypeTime,@tmpState,@tmpNote
	END
CLOSE CurSType
DEALLOCATE CurSType
IF @@Error<>0
				BEGIN
					ROLLBACK TRANSACTION T1
					RAISERROR('修改序列号失败！',16,1) RETURN
				END	

DROP TABLE  #TmpSerial

--COMMIT TRAN T1

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_stjs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_stjs]
GO

/*
	作者：谢吉康
	日期：2006-3-3
	描述：销售退货、委托代销退货的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 15:06:18
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	日期:2015-04-20
	描述:序列号严密关联
*/
CREATE  PROCEDURE Gp_SerialOperate_stjs
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@STypeId			varchar(50)


--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'
--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 		varchar(200),
	PTypeId		varchar(100),
	State		int,
	ID			INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 145	--受托代销结算
	BEGIN
		SET @mxTableName = 'CommissionBill'
		SET @State = 1
		SET @InOutState = 1
		SET @Flag = 1
	END

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,'

IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+					
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0'
END					
					
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
		PType P
WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
		AND P.TypeId = M.PTypeId
		AND P.SonNum = 0
		AND P.Deleted = 0 '
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				)

				
				INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,Qty,Id
				FROM #TmpSerial
				
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--正式开始处理序列号
--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.State IN (17,20) 				
								AND G.Flag = 1 
								AND G.BFlag = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.State IN (17,20) 				
					AND G.Flag = 1 
					AND G.BFlag = 1 
					AND T.ID=d.ID
		) a

		IF @ErrId <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END
	
--判断分支机构

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId			
						AND P.IfSerial = @intSysMngSerial			
						AND G.STypeId <> @STypeId
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId = T.PTypeId			
			AND P.IfSerial = @intSysMngSerial			
			AND G.STypeId <> @STypeId
			AND T.ID=d.ID
) a
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】分支机构属性不正确，不能过账！'	
		RETURN -907 --失败
	END	

--判断商品的属性是否正确

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId <> T.PTypeId			
						AND P.IfSerial = @intSysMngSerial
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId <> T.PTypeId			
			AND P.IfSerial = @intSysMngSerial
			AND T.ID=d.ID
) a

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
		RETURN -907 --失败
	END

--受托代销的序列号在未结算之前不允许结算入库

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND T.PTypeId = G.PTypeId
						AND ISNULL(G.CommissionState,'')='1'
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND T.PTypeId = G.PTypeId
			AND ISNULL(G.CommissionState,'')='1'
			AND T.ID=d.ID
) a
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】已经被受托结算入库！'
		RETURN -908 --失败
	END	

--判断往来单位是否是正确的

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND T.PTypeId = G.PTypeId
						AND G.BTypeId2 <> @BTypeId
						AND ISNULL(G.CommissionState,'')='0'
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND T.PTypeId = G.PTypeId
			AND G.BTypeId2 <> @BTypeId
			AND ISNULL(G.CommissionState,'')='0'
			AND T.ID=d.ID
) a
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】往来单位的属性不正确！'
		RETURN -908 --失败
	END	

--V3.8新加判断，如果输入了非受托代销库存中的序列号，则不允许过帐

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND T.PTypeId = G.PTypeId
						AND G.BTypeId2 = @BTypeId
						AND ISNULL(G.CommissionState,'')<>'0'
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND T.PTypeId = G.PTypeId
			AND G.BTypeId2 = @BTypeId
			AND ISNULL(G.CommissionState,'')<>'0'
			AND T.ID=d.ID
) a
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的状态不正确，不允许结算！'
		RETURN -908 --失败
	END	


IF EXISTS(
	SELECT a.Serial FROM  #AllSerial a
	INNER JOIN #TmpPType b
	ON a.ID=b.ID
	LEFT JOIN gp_CruPtypeSerial c
	ON a.Serial=c.Serial
	WHERE (b.ItemID <> c.ItemID
	OR b.Iscombined<>c.IsCombined
	OR b.GoodsNumber<>c.GoodsNumber
	OR b.ProduceDate<>c.ProduceDate
	OR b.ValidDate<>c.ValidDate
	OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
	--OR b.CargoID<>c.CargoID
	)
	AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
		Serial,
		PTypeId,
		State,
		ID
)
SELECT	T.Serial,
		T.PTypeId,
		G.State,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 

--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
SELECT	TOP 1 
		@ErrId = P.nId,
		@ErrSerial = T.Serial 	
FROM	#AllSerial T,			
		#TmpPType P
WHERE	T.PTypeId = P.PTypeId		
		AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
ORDER BY T.Id ASC	


IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
		RETURN -907 --失败
	END

--写序列号跟踪记录
INSERT INTO GP_InOutPTypeSerial (
	Serial,
	PTypeID,
	BillNumberID,
	InKTypeID,
	IfCheck,
	BillType,
	BTypeID2,
	InKTypeTime,
	State,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice,
	DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		@inKTypeID,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		CASE
			WHEN U.State = 7 		THEN 1
			WHEN U.State = 9 		THEN 2
			WHEN U.State = 10 	THEN 4
			WHEN U.State = 11 	THEN 5
			WHEN U.State = 13 	THEN 13
			WHEN U.State = 14		THEN 2
			WHEN U.State = 16		THEN 15
			WHEN U.State = 22		THEN 21
			WHEN U.State = 23		THEN 23
			WHEN U.State = 31     THEN 30
			WHEN U.State = 32     THEN 13
		END,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END	

--结算序列号
UPDATE	GP_CruPTypeSerial
SET		BTypeID2 	= @BTypeID,
		InKTypeTime = CASE 
						WHEN ISNULL(InKTypeTime,'')='' THEN @BillDate
						ELSE InKTypeTime
					  END,
		State = CASE
					WHEN G.State = 7 	THEN 1
					WHEN G.State = 9 	THEN 2
					WHEN G.State = 10 	THEN 4
					WHEN G.State = 11 	THEN 5
					WHEN G.State = 13 	THEN 13
					WHEN G.State = 14	THEN 2
					WHEN G.State = 16	THEN 15
					WHEN G.State = 22	THEN 21
					WHEN G.State = 23	THEN 23
					WHEN G.State = 31   THEN 30
					WHEN G.State = 32   THEN 13
				END,
		Flag  = CASE WHEN G.State IN (1,7) THEN 1 ELSE 0 END,
		CommissionState = 1	--代销结算后这个值为1
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND T.PTypeId = G.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND ISNULL(G.CommissionState,'') = '0'
		AND T.ID=P.ID
	

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改当前序列号记录失败！'
		RETURN -901
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0



































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_Wx_ck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_Wx_ck]
GO











/*
	作者：谢吉康
	日期：2006-3-3
	描述：出库的序列号单独过帐	
	
	修改：赵斌
	日期：2012年2月10日 11:06:41
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	日期:2015-05-14
	描述:序列号严密关联
*/
CREATE  PROCEDURE Gp_SerialOperate_Wx_ck
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@STypeId			varchar(50)


--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	State			int,
	CommissionState	varchar(5),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 167	--取件单
	BEGIN
		SET @mxTableName = 'wx_Bill_GetBack'
		SET @State = 27
		SET @InOutState = 27
		SET @Flag = 0
	END

IF @billType = 168	--整机更换单
	BEGIN
		SET @mxTableName = 'wx_Bill_Replace'
		SET @State = 28
		SET @InOutState = 28
		SET @Flag = 0
	END

IF @billType = 169  --送修单	
	BEGIN
		SET @mxTableName = 'wx_Bill_Send'
		SET @State = 29
		SET @InOutState = 29
		SET @Flag = 0
	END

IF @billType = 9  --报损单
	BEGIN
		SET @mxTableName = 'LoseBill'
		SET @State = 4
		SET @InOutState = 4
		SET @Flag = 0
	END

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
IF @BillType = 9
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						M.Qty,
						M.Id,
						P.IfSerial,'
						
	IF @intserialrelation=1
	BEGIN						
		SET @SQL=@SQL+						
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						M.ProduceDate,
						M.ValidDate,
						M.GoodsNumber,
						CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END						
		SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
						PType P
				WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
						AND P.TypeId = M.PTypeId
						AND P.SonNum = 0
						AND P.Deleted = 0 '
END						
ELSE IF @BillType=169
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						M.Qty,
						M.Id,
						P.IfSerial,'
	IF @intserialrelation=1
	BEGIN						
		SET @SQL=@SQL+					
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						'''' AS ProduceDate,
						'''' AS ValidDate,
						M.GoodsNumber,
						0 AS GoodsCostPrice  '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END	
						
	SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
			PType P
	WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
			AND P.TypeId = M.PTypeId
			AND P.SonNum = 0
			AND P.Deleted = 0 '
END												
ELSE IF @BillType=168
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						1 AS Qty,
						M.Id,
						P.IfSerial,'
						
	IF @intserialrelation=1
	BEGIN						
		SET @SQL=@SQL+					
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						M.ProduceDate,
						M.ValidDate,
						M.GoodsNumber,
						CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END		
					
	SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
			PType P
	WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
			AND P.TypeId = M.PTypeId
			AND P.SonNum = 0
			AND P.Deleted = 0 '
END						
ELSE
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						1 AS Qty,
						M.Id,
						P.IfSerial,'
		
	IF @intserialrelation=1
	BEGIN						
		SET @SQL=@SQL+				
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						'''' AS ProduceDate,
						'''' AS ValidDate,
						M.GoodsNumber,
						0 AS GoodsCostPrice  '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END	
						
	SET @SQL=@SQL+'FROM 	'+@mxTableName+' M,
			PType P
	WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
			AND P.TypeId = M.PTypeId
			AND P.SonNum = 0
			AND P.Deleted = 0 '
END						
						
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果

FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		IF @BillType = 169
			SET @SerialSQL = '
					DECLARE  @TmpBill TABLE
					(	
						Serial 	varchar(max),
						PTypeId	varchar(100),
						Qty		 NUMERIC(24, 10) ,
						Id		int
					)
	
					INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' 
	
					DECLARE	@i 					int,				--计数器
							@j 					int,				--计数器
							@k					int,				--计数器
							@l					int,
							@intGoOn			int,
							@Serial_str			varchar(MAX),
							@Serial_tmp			varchar(1000),
							@TPTypeId			varchar(100),
							@TQty				 NUMERIC(24, 10) ,
							@TXId				int
	
					
						
					DECLARE
						@strSplit			VARCHAR(100)
					
					SELECT 
						@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
					FROM @TmpBill
					
					
					
					SET @strSplit=''я''
		
					
					
					
					INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
					FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
					ORDER BY ShowOrder
				
					INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial1,PTypeId,Qty,Id
					FROM #TmpSerial
						'
		ELSE
			SET @SerialSQL = '
					DECLARE  @TmpBill TABLE
					(	
						Serial 	varchar(max),
						PTypeId	varchar(100),
						Qty		 NUMERIC(24, 10) ,
						Id		int
					)
	
					INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,1 AS Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' 
	
					DECLARE	@i 					int,				--计数器
							@j 					int,				--计数器
							@k					int,				--计数器
							@l					int,
							@intGoOn			int,
							@Serial_str			varchar(MAX),
							@Serial_tmp			varchar(1000),
							@TPTypeId			varchar(100),
							@TQty				 NUMERIC(24, 10) ,
							@TXId				int
	
					
					
					DECLARE
						@strSplit			VARCHAR(100)
					
					SELECT 
						@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
					FROM @TmpBill
					
					
					
					SET @strSplit=''я''
		
					
					
					
					INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
					FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
					ORDER BY ShowOrder
				
					INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial1,PTypeId,Qty,Id
					FROM #TmpSerial
					
					'
								
		EXEC(@SerialSQL)

		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END
--从新置空错误ID的提示
SET @ErrId = 0

--判断商品属性是否正确


SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId <> T.PTypeId					
						AND P.IfSerial = @intSysMngSerial
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId <> T.PTypeId					
			AND P.IfSerial = @intSysMngSerial
			AND T.ID=d.ID
) a

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
		RETURN -907 --失败
	END

--序列号（判断仓库属性）

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId
						AND G.KTypeId <> @inKTypeId	
						AND P.IfSerial = @intSysMngSerial
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId = T.PTypeId
			AND G.KTypeId <> @inKTypeId	
			AND P.IfSerial = @intSysMngSerial
			AND T.ID=d.ID
) a
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
		RETURN -907 --失败
	END

IF @BillType <> 168
	BEGIN
		--判断序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State <> 25)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = @inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State <> 25)
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END
	END

IF @BillType = 168 	--整机更换单
	BEGIN
		--正常商品出库必须是库存中的序列号
		SELECT	TOP 1 
				@ErrId = P.nId,
				@ErrSerial = T.Serial 	
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				Wx_Bill_Replace S
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND T.ID = S.ID
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = @inKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND (G.Flag = 0 OR G.State <> 1)
				AND S.WxProperty = 0
		ORDER BY T.Id ASC	
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END		

			--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
		IF @mngLendSerial = 1
			BEGIN
				SELECT 	TOP 1
						@ErrId = P.nId,
						@ErrSerial = T.Serial
				FROM	#AllSerial T,
						Gp_LendPTypeSerial G,
						#TmpPType P,
						Wx_Bill_Replace S
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND T.ID = S.ID
						AND P.IfSerial = @intSysMngSerial
						AND S.WxProperty = 0
						AND G.Flag = 0 and G.State IN(18)
				ORDER BY T.Id ASC
		
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
						RETURN -907 --失败
					END
			END
			
		--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
		IF @mngLendSerial = 1
			BEGIN
				SELECT 	TOP 1
						@ErrId = P.nId,
						@ErrSerial = T.Serial
				FROM	#AllSerial T,
						Gp_LendPTypeSerial G,
						#TmpPType P,
						Wx_Bill_Replace S
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND T.ID = S.ID
						AND P.IfSerial = @intSysMngSerial
						AND S.WxProperty = 0
						AND G.Flag = 1 and G.State IN(17)
				ORDER BY T.Id ASC
		
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
						RETURN -907 --失败
					END
			END
		--维修商品出库必须是维修库存中的序列号
		SELECT	TOP 1 
				@ErrId = P.nId,
				@ErrSerial = T.Serial 	
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				Wx_Bill_Replace S
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND T.ID = S.ID
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = @inKTypeId	
				AND P.IfSerial = @intSysMngSerial
				AND (G.Flag = 0 OR G.State <> 25)
				AND S.WxProperty = 1
		ORDER BY T.Id ASC	
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END	
	END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	State,
	CommissionState,
	ID
)						
SELECT	T.Serial,
		T.PTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND T.PTypeId = G.PTypeId

--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
SELECT	TOP 1 
		@ErrId = P.nId,
		@ErrSerial = T.Serial 	
FROM	#AllSerial T,			
		#TmpPType P
WHERE	T.PTypeId = P.PTypeId		
		AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
ORDER BY T.Id ASC	

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
		RETURN -907 --失败
	END
	
DECLARE
	@intIfwx	INT
	
SELECT @intIfwx=1

IF @BillType=9
BEGIN
	SELECT @intIfwx=ifWX
	FROM Billindex
	WHERE BillNumberId=@nBillId
END		

IF @BillType=9 AND @intIfwx=0
BEGIN
	IF EXISTS
	(
			SELECT a.Serial FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE (b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR b.CargoID<>c.CargoID
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
			)
			AND @intserialrelation=1
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR b.CargoID<>c.CargoID
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END	
END
ELSE
BEGIN
	
	IF EXISTS
	(
			SELECT a.Serial FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE (b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			--OR b.CargoID<>c.CargoID
			)
			AND @intserialrelation=1
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			--OR b.CargoID<>c.CargoID
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END	
END	

--写序列号的出入口记录
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		OutKTyeID,
		IfCheck,
		BillType,
		BTypeID1,
		BTypeID2,
		OutKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	T.Serial,
		T.PTypeId,
		@nBillId,
		@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (167,168) THEN @BTypeID
			ELSE ''
		END,

		CASE
			WHEN @BillType = 169 THEN @BTypeId
			ElSE ''
		END,
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END			

--修改当前出库的序列号状态
UPDATE	Gp_CruPTypeSerial
SET		BTypeID1 = 
					CASE
						WHEN @BillType IN (167,168) THEN @BTypeID
						ELSE BTypeID1
					END,
		BTypeId2 = 
					CASE
						WHEN @BillType IN (169) THEN @BTypeID
						ELSE BTypeID2
					END,
		OutKTypeTime = @BillDate,
		Flag = 0,
		State =	@State,
		CommissionState = @CommissionState
FROM 	Gp_CruPTypeSerial G,
		#UnionSerial T,
		#TmpPType P
WHERE	G.Serial = T.Serial
		AND G.PTypeId = T.PTypeId
		AND G.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND T.ID=P.ID
		

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END		

--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_Wx_ck_ks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_Wx_ck_ks]
GO
/*
	作者：谢吉康
	日期：2006-3-3
	描述：出库的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 14:48:57
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	时间:2015-05-19
	描述:序列号严密关联成本等
*/
CREATE  PROCEDURE Gp_SerialOperate_Wx_ck_ks
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@STypeId			varchar(50)


--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10)

	
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	State			int,
	CommissionState	varchar(5),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 167	--取件单
	BEGIN
		SET @mxTableName = 'wx_Bill_GetBack'
		SET @State = 27
		SET @InOutState = 27
		SET @Flag = 0
	END

IF @billType = 168	--整机更换单
	BEGIN
		SET @mxTableName = 'wx_Bill_Replace'
		SET @State = 28
		SET @InOutState = 28
		SET @Flag = 0
	END

IF @billType = 169  --送修单	
	BEGIN
		SET @mxTableName = 'wx_Bill_Send'
		SET @State = 29
		SET @InOutState = 29
		SET @Flag = 0
	END

IF @billType = 9  --报损单
	BEGIN
		SET @mxTableName = 'LoseBill'
		SET @State = 4
		SET @InOutState = 4
		SET @Flag = 0
	END

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
IF @BillType = 9
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						M.Qty,
						M.Id,
						P.IfSerial,'
						
	IF @intserialrelation=1
	BEGIN						
		SET @SQL=@SQL+						
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						M.ProduceDate,
						M.ValidDate,
						M.GoodsNumber,
						CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END						
		SET @SQL=@SQL+' 
		 FROM 	'+@mxTableName+' M,
						PType P
				WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
						AND P.TypeId = M.PTypeId
						AND P.SonNum = 0
						AND P.Deleted = 0 '
END						
ELSE IF @BillType=169
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						M.Qty,
						M.Id,
						P.IfSerial,'
	IF @intserialrelation=1
	BEGIN						
		SET @SQL=@SQL+										
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						'''' AS ProduceDate,
						'''' AS ValidDate,
						M.GoodsNumber,
						0 AS GoodsCostPrice '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END							
	
	SET @SQL=@SQL+'
				 FROM 	'+@mxTableName+' M,
						PType P
				WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
						AND P.TypeId = M.PTypeId
						AND P.SonNum = 0
						AND P.Deleted = 0 '	
END													
ELSE IF @BillType = 168
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						1 AS Qty,
						M.Id,
						P.IfSerial,'
	IF @intserialrelation=1
	BEGIN						
		SET @SQL=@SQL+										
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						M.ProduceDate,
						M.ValidDate,
						M.GoodsNumber,
						CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END							
						
	SET @SQL=@SQL+' 
				FROM 	'+@mxTableName+' M,
						PType P
				WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
						AND P.TypeId = M.PTypeId
						AND P.SonNum = 0
						AND P.Deleted = 0 '
END						
ELSE
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						1 AS Qty,
						M.Id,
						P.IfSerial,'
	IF @intserialrelation=1
	BEGIN						
		SET @SQL=@SQL+									
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						'''' AS ProduceDate,
						'''' AS ValidDate,
						M.GoodsNumber,
						0 AS GoodsCostPrice '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END							
	
	SET @SQL=@SQL+' 
				FROM 	'+@mxTableName+' M,
						PType P
				WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
						AND P.TypeId = M.PTypeId
						AND P.SonNum = 0
						AND P.Deleted = 0 '						
END						
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果

FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		IF @BillType = 169
			SET @SerialSQL = '
					DECLARE  @TmpBill TABLE
					(	
						Serial 	varchar(max),
						PTypeId	varchar(100),
						Qty		 NUMERIC(24, 10) ,
						Id		int
					)
	
					INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' 
	
					DECLARE	@i 					int,				--计数器
							@j 					int,				--计数器
							@k					int,				--计数器
							@l					int,
							@intGoOn			int,
							@Serial_str			varchar(MAX),
							@Serial_tmp			varchar(1000),
							@TPTypeId			varchar(100),
							@TQty				 NUMERIC(24, 10) ,
							@TXId				int
	
					
					
					
					DECLARE
						@strSplit			VARCHAR(100)
					
					SELECT 
						@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
					FROM @TmpBill
					
					
					
					SET @strSplit=''я''
		
					
					
					
					INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
					FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
					ORDER BY ShowOrder
				
					INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial1,PTypeId,Qty,Id
					FROM #TmpSerial
					'
		ELSE
			SET @SerialSQL = '
					DECLARE  @TmpBill TABLE
					(	
						Serial 	varchar(max),
						PTypeId	varchar(100),
						Qty		 NUMERIC(24, 10) ,
						Id		int
					)
	
					INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,1 AS Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' 
	
					DECLARE	@i 					int,				--计数器
							@j 					int,				--计数器
							@k					int,				--计数器
							@l					int,
							@intGoOn			int,
							@Serial_str			varchar(MAX),
							@Serial_tmp			varchar(1000),
							@TPTypeId			varchar(100),
							@TQty				 NUMERIC(24, 10) ,
							@TXId				int
	
					
						
					DECLARE
						@strSplit			VARCHAR(100)
					
					SELECT 
						@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
					FROM @TmpBill
					
					
					
					SET @strSplit=''я''
		
					
					
					
					INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
					FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
					ORDER BY ShowOrder
				
					INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial1,PTypeId,Qty,Id
					FROM #TmpSerial
						'
								
		EXEC(@SerialSQL)

		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END
--从新置空错误ID的提示
SET @ErrId = 0

--判断商品属性是否正确

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId <> T.PTypeId					
						AND P.IfSerial = @intSysMngSerial
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId <> T.PTypeId					
			AND P.IfSerial = @intSysMngSerial
			AND T.ID=d.ID
) a


IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
		RETURN -907 --失败
	END

--序列号（判断仓库属性）

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId
						AND G.KTypeId <> @inKTypeId	
						AND P.IfSerial = @intSysMngSerial
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId = T.PTypeId
			AND G.KTypeId <> @inKTypeId	
			AND P.IfSerial = @intSysMngSerial
			AND T.ID=d.ID
) a
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
		RETURN -907 --失败
	END

IF @BillType <> 168
	BEGIN
		--判断序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State <> 25)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = @inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State <> 25)
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END
	END

IF @BillType = 168 	--整机更换单
	BEGIN
		--正常商品出库必须是库存中的序列号
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					Wx_Bill_Replace S,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P,
								Wx_Bill_Replace S
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND T.ID = S.ID
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State <> 1)
								AND S.WxProperty = 0
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND T.ID = S.ID
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = @inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State <> 1)
					AND S.WxProperty = 0
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END		

			--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
		IF @mngLendSerial = 1
			BEGIN
			
				SELECT
						@ErrId = a.nId,
						@ErrSerial = a.Serial
				FROM
				(		
					SELECT 	P.nId, T.Serial
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P,
							Wx_Bill_Replace S,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										Gp_LendPTypeSerial G,
										#TmpPType P,
										Wx_Bill_Replace S
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND T.ID = S.ID
										AND P.IfSerial = @intSysMngSerial
										AND S.WxProperty = 0
										AND G.Flag = 0 and G.State IN(18)
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND T.ID = S.ID
							AND P.IfSerial = @intSysMngSerial
							AND S.WxProperty = 0
							AND G.Flag = 0 and G.State IN(18)
							AND T.ID=d.ID
				) a
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
						RETURN -907 --失败
					END
			END
			
	--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
		IF @mngLendSerial = 1
			BEGIN
			
				SELECT
						@ErrId = a.nId,
						@ErrSerial = a.Serial
				FROM
				(		
					SELECT 	P.nId, T.Serial
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P,
							Wx_Bill_Replace S,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										Gp_LendPTypeSerial G,
										#TmpPType P,
										Wx_Bill_Replace S
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND T.ID = S.ID
										AND P.IfSerial = @intSysMngSerial
										AND S.WxProperty = 0
										AND G.Flag = 1 and G.State IN(17)
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND T.ID = S.ID
							AND P.IfSerial = @intSysMngSerial
							AND S.WxProperty = 0
							AND G.Flag = 1 and G.State IN(17)
							AND T.ID=d.ID
				) a
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
						RETURN -907 --失败
					END
			END

		--维修商品出库必须是维修库存中的序列号
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					Wx_Bill_Replace S,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P,
								Wx_Bill_Replace S
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND T.ID = S.ID
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State <> 25)
								AND S.WxProperty = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND T.ID = S.ID
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = @inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State <> 25)
					AND S.WxProperty = 1
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END	
	END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	State,
	CommissionState,
	ID
)						
SELECT	T.Serial,
		T.PTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND T.PTypeId = G.PTypeId


IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
		)
		AND @intserialrelation=1
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
			--OR b.CargoID<>c.CargoID
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END	

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID1,
	BTypeID2,
	InKTypeTime,
	OutKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		@inKTypeId,
		a.PTypeId,
		CASE
			WHEN @BillType IN (167,168) THEN @BTypeId
			ELSE ''
		END,
		CASE 
			WHEN @BillType IN (169) THEN @BTypeId
			ELSE ''
		END,
		@BillDate,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--写序列号的出入口记录
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		OutKTyeID,
		IfCheck,
		BillType,
		BTypeID1,
		BTypeID2,
		OutKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (167,168) THEN @BTypeID
			ELSE ''
		END,
		CASE
			WHEN @BillType = 169 THEN @BTypeId
			ElSE ''
		END,
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号的出入口记录
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		OutKTyeID,
		IfCheck,
		BillType,
		BTypeID1,
		BTypeID2,
		OutKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (167,168) THEN @BTypeID
			ELSE ''
		END,
		CASE
			WHEN @BillType = 169 THEN @BTypeId
			ElSE ''
		END,
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END			

--修改当前出库的序列号状态
UPDATE	Gp_CruPTypeSerial
SET		BTypeID1 = 
					CASE
						WHEN @BillType IN (167,168) THEN @BTypeID
						ELSE BTypeID1
					END,
		BTypeId2 = 
					CASE
						WHEN @BillType IN (169) THEN @BTypeID
						ELSE BTypeID2
					END,
		OutKTypeTime = @BillDate,
		Flag = 0,
		State =	@State,
		CommissionState = @CommissionState
FROM 	Gp_CruPTypeSerial G,
		#UnionSerial T,
		#TmpPType P
WHERE	G.Serial = T.Serial
		AND G.PTypeId = T.PTypeId
		AND G.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND T.ID=P.ID


IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END		
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	


--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_Wx_db]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_Wx_db]
GO









/*
	作者：谢吉康
	日期：2006-3-3
	描述：调拨的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 15:30:38
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	日期:2015-05-14
	描述:序列号严密关联
*/
CREATE  PROCEDURE Gp_SerialOperate_Wx_db
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@STypeId			varchar(50)


--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@billType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'
--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 		varchar(200),
	PTypeId		varchar(100),
	State		int,
	ID			INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 173	--维修品调入单
	BEGIN
		SET @mxTableName = 'wx_Bill_In'
		SET @State = 25
		SET @InOutState = 25
		SET @CinOutState = 26
		SET @Flag = 1
	END

IF @billType = 174	--维修品调出单
	BEGIN
		SET @mxTableName = 'wx_Bill_Out'
		SET @State = 1
		SET @InOutState = 1
		SET @CinOutState = 26
		SET @Flag = 1
	END

IF @billType = 175	--维修品调拨单
	BEGIN
		SET @mxTableName = 'wx_Bill_Move'
		SET @State = 25
		SET @InOutState = 25
		SET @CinOutState = 26
		SET @Flag = 1
	END

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表

IF @BillType=175
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,'
	
	IF @intserialrelation=1
	BEGIN					
		SET @SQL=@SQL+'M.ItemID,
		M.IsCombined,
		M.CargoID,'
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'
	END
					
	SET @SQL=@SQL+''''' AS ProduceDate,
	'''' AS ValidDate,'
					
	IF @intserialrelation=1
	BEGIN					
		SET @SQL=@SQL+'M.GoodsNumber,
					0 AS GoodsCostPrice  '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+''''',0 '
	END					
					
	SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
			PType P
	WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
			AND P.TypeId = M.PTypeId
			AND P.SonNum = 0
			AND P.Deleted = 0 '
END
ELSE
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						M.Qty,
						M.Id,
						P.IfSerial,'
	
	IF @intserialrelation=1
	BEGIN					
		SET @SQL=@SQL+					
						'M.ItemID,
						M.IsCombined,
						M.CargoID,
						M.ProduceDate,
						M.ValidDate,
						M.GoodsNumber,'
						
		IF @BillType=173
		BEGIN
						SET @SQL=@SQL+'CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
		END
		ELSE
		BEGIN
						SET @SQL=@SQL+'CASE '+@nCostingMethod+' WHEN 3 THEN M.Price ELSE 0 END '
		END
							
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
	END						
						
	SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
			PType P
	WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
			AND P.TypeId = M.PTypeId
			AND P.SonNum = 0
			AND P.Deleted = 0 '
END					
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	TEXT,
					PTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01	

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--判断商品属性是否正确

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId <> T.PTypeId					
						AND P.IfSerial = @intSysMngSerial
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId <> T.PTypeId					
			AND P.IfSerial = @intSysMngSerial
			AND T.ID=d.ID
) a

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
		RETURN -907 --失败
	END

--序列号（判断仓库属性）

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.PTypeId = T.PTypeId
						AND G.KTypeId <> @inKTypeId	
						AND P.IfSerial = @intSysMngSerial
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.PTypeId = T.PTypeId
			AND G.KTypeId <> @inKTypeId	
			AND P.IfSerial = @intSysMngSerial
			AND T.ID=d.ID
) a
IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
		RETURN -907 --失败
	END
--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.Flag = 0 and G.State IN(18)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.Flag = 0 and G.State IN(18)
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END
	
	--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					Gp_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.Flag = 1 and G.State IN(17)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.Flag = 1 and G.State IN(17)
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
				RETURN -907 --失败
			END
	END


IF @BillType = 173	--维修品调入单
	BEGIN
		--判断出库序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State <> 1)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = @inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State <> 1)
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END

		--判断入库序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.State = 25
								AND G.Flag = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.State = 25
					AND G.Flag = 1
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中已存在！'	
				RETURN -907 --失败
			END

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			State,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				G.State,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial
				AND G.Flag = 1
				AND G.KTypeId = @inKTypeId
				AND G.PTypeId IN (SELECT PTypeId FROM #TmpPType)
		
		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT  P.nId,
					T.Serial
			FROM	#AllSerial	T,
					#TmpPType	P,
					(
						SELECT	MIN(T.Id) AS ID
						FROM	#AllSerial T,
								#TmpPType P
						WHERE	T.PTypeId = P.PTypeId		
						AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					)d
			WHERE	T.PTypeId = P.PTypeId		
					AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					AND T.Id = d.ID
		)a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
				RETURN -907 --失败
			END
			
		IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR b.CargoID<>c.CargoID
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		)
		AND @intserialrelation=1
	)
	BEGIN
		SELECT @ErrSerial=a.Serial 
		FROM
		(
			SELECT TOP 1 a.Serial
			FROM #AllSerial a
			INNER JOIN #TmpPType b
			ON a.ID=b.ID
			LEFT JOIN gp_CruPtypeSerial c
			ON a.Serial=c.Serial
			WHERE b.ItemID <> c.ItemID
			OR b.Iscombined<>c.IsCombined
			OR b.GoodsNumber<>c.GoodsNumber
			OR b.ProduceDate<>c.ProduceDate
			OR b.ValidDate<>c.ValidDate
			OR b.CargoID<>c.CargoID
			OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		) a
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
			RETURN -907 --失败
	END
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	T.Serial,
				T.PTypeId,
				@nBillId,
				@inKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				@CinOutState,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice,
				B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=T.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901
			END
		
		--写序列号跟踪记录（入库）
		INSERT INTO GP_InOutPTypeSerial (
			Serial,
			PTypeID,
			BillNumberID,
			InKTypeID,
			IfCheck,
			BillType,
			BTypeID2,
			InKTypeTime,
			State,
			ItemID,
			IsCombined,
			CargoID,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice,
			DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				@outKTypeID,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				@State,
				B.ItemID,
				B.IsCombined,
				0,
				'',
				'',
				B.GoodsNumber,
				0,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=T.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901
			END		
		
		--修改调拨序列号的仓库、入库时间等的信息【InKTypeTime = @BillDate 调拨入库的时间不动 V366修改】
		UPDATE	Gp_CruPTypeSerial
		SET		KTypeId  = @outKTypeID,
				State    = @State,
				GoodsNumber=p.GoodsNumber,
				CargoID=0,
				ProduceDate='',
				ValidDate='',
				ItemID=p.ItemID,
				IsCombined=p.IsCombined,
				CostPrice=0
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P,
				#AllSerial B
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeID
				AND G.PTypeId = P.PTypeId
				AND G.Flag = 1
				AND G.KTypeId = @inKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND P.ID=B.ID
				AND T.ID=P.ID
				
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的入库记录失败！'
				RETURN -903
			END
	END
ELSE IF @BillType = 174			--维修品调出单
	BEGIN
		--判断出库序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State <> 25)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = @inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State <> 25)
					AND T.ID=d.ID
		) a
	
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END

		--判断入库序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND P.IfSerial = @intSysMngSerial
								AND G.State IN (1,7)
								AND G.Flag = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND P.IfSerial = @intSysMngSerial
					AND G.State IN (1,7)
					AND G.Flag = 1
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中已存在！'	
				RETURN -907 --失败
			END

		--判断是否采用了借欠的效验模式
		IF @mngLendSerial = 1
			BEGIN
			
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.State IN (17,20) 
								AND G.Flag = 1 
								AND G.BFlag = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.State IN (17,20) 
					AND G.Flag = 1 
					AND G.BFlag = 1
					AND T.ID=d.ID
		) a
				IF @ErrId <> 0
					BEGIN				
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
						RETURN -907 --失败
					END
			END		

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			State,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				G.State,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial
				AND G.Flag = 1
				AND G.KTypeId = @inKTypeId
				AND G.PTypeId IN (SELECT PTypeId FROM #TmpPType)
		
		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT  P.nId,
					T.Serial
			FROM	#AllSerial	T,
					#TmpPType	P,
					(
						SELECT	MIN(T.Id) AS ID
						FROM	#AllSerial T,
								#TmpPType P
						WHERE	T.PTypeId = P.PTypeId		
								AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					)d
			WHERE	T.PTypeId = P.PTypeId		
					AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					AND T.Id = d.ID
		)a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
				RETURN -907 --失败
			END
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	T.Serial,
				T.PTypeId,
				@nBillId,
				@inKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				@CinOutState,
				B.ItemID,
				B.IsCombined,
				0,
				'',
				'',
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND T.ID=U.ID
				
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901
			END
		
		--写序列号跟踪记录（入库）
		INSERT INTO GP_InOutPTypeSerial (
			Serial,
			PTypeID,
			BillNumberID,
			InKTypeID,
			IfCheck,
			BillType,
			BTypeID2,
			InKTypeTime,
			State,
			ItemID,
			IsCombined,
			CargoID,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice,
			DETAILID
		)
		SELECT	T.Serial,
				T.PTypeId,
				@nBillId,
				@outKTypeID,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				@State,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice,
				B.ID	
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=T.ID

		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901
			END		
		
		--修改调拨序列号的仓库、入库时间等的信息【InKTypeTime = @BillDate 调拨入库的时间不动 V366修改】
		UPDATE	Gp_CruPTypeSerial
		SET		KTypeId  = @outKTypeID,
				State    = @State,
				GoodsNumber=p.GoodsNumber,
				CargoID=p.cargoID,
				ProduceDate=p.ProduceDate,
				ValidDate=p.ValidDate,
				ItemID=p.ItemID,
				IsCombined=p.IsCombined,
				CostPrice=p.CostPrice
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P,
				#AllSerial B
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeID
				AND G.PTypeId = P.PTypeId
				AND G.Flag = 1
				AND G.KTypeId = @inKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND B.ID=P.ID
				AND T.ID=P.ID
				
				
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的入库记录失败！'
				RETURN -903
			END
	END
ELSE			--维修品调拨单175
	BEGIN
		--判断序列号是否在库存中
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State <> 25)
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId = @inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND (G.Flag = 0 OR G.State <> 25) 
					AND T.ID=d.ID
		) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
				RETURN -907 --失败
			END

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			State,
			id
		)
		SELECT	T.Serial,
				T.PTypeId,
				G.State,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.Flag = 1
				AND G.KTypeId = @inKTypeId
				AND G.PTypeId IN (SELECT PTypeId FROM #TmpPType)
		
		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT  P.nId,
					T.Serial
			FROM	#AllSerial	T,
					#TmpPType	P,
					(
						SELECT	MIN(T.Id) AS ID
						FROM	#AllSerial T,
								#TmpPType P
						WHERE	T.PTypeId = P.PTypeId		
								AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					)d
			WHERE	T.PTypeId = P.PTypeId		
					AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					AND T.Id = d.ID
		)a
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
				RETURN -907 --失败
			END
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	T.Serial,
				T.PTypeId,
				@nBillId,
				@inKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				@CinOutState,
				B.ItemID,
				B.IsCombined,
				0,
				'',
				'',
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=B.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901
			END
		
		--写序列号跟踪记录（入库）
		INSERT INTO GP_InOutPTypeSerial (
			Serial,
			PTypeID,
			BillNumberID,
			InKTypeID,
			IfCheck,
			BillType,
			BTypeID2,
			InKTypeTime,
			State,
			ItemID,
			IsCombined,
			CargoID,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice,
			DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				@outKTypeID,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				State,
				B.ItemID,
				B.IsCombined,
				0,
				'',
				'',
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=B.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901
			END		
		
		--修改调拨序列号的仓库、入库时间等的信息【InKTypeTime = @BillDate 调拨入库的时间不动 V366修改】
		UPDATE	Gp_CruPTypeSerial 
		SET		KTypeId  = @outKTypeID,
				CostPrice=p.CostPrice,
				GoodsNumber=p.GoodsNumber,
				CargoID=0,
				ProduceDate='',
				ValidDate='',
				ItemID=p.ItemID,
				IsCombined=p.IsCombined
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P,
				#AllSerial B
		WHERE	T.Serial = G.Serial 
				AND T.PTypeId = P.PTypeID
				AND G.PTypeId = P.PTypeId
				AND G.Flag = 1
				AND G.KTypeId = @inKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND P.ID=B.ID
				AND T.ID=P.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的入库记录失败！'
				RETURN -903
			END
	END
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	


--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000),
	@nRet		INT
	
SELECT goodsnumber,cargoid,ktypeid,* FROM 	gp_CruPtypeSerial	where Serial='kcqc-x01序列号-01(自由项 批号) hw1 01'
	
SELECT
	@nBillID=3,
	@OperatorId='00001'	

BEGIN TRAN

EXEC @nRet=Gp_SerialOperate_Wx_db
	@nBillId,
	@OperatorId,
	@szPID	output
	
SELECT goodsnumber,cargoid,ktypeid,* FROM 	gp_CruPtypeSerial where Serial='kcqc-x01序列号-01(自由项 批号) hw1 01'
	
ROLLBACK TRAN	

select * from billindex where ifcheck='f'

select serial,ktypeid,ktypeid2,incargoid,outcargoid,* from movebill where billnumberid=3





select * from movebill where billnumberid=4

select serial,ktypeid,ktypeid2,incargoid,outcargoid,* from movebill where billnumberid=4

*/





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_Wx_dgrid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_Wx_dgrid]
GO




















/*
	作者：谢吉康
	日期：2006-3-3
	描述：拆装、换货、维修的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 13:56:13
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	日期:2015-05-15
	描述:序列号严密关联
*/
CREATE    PROCEDURE Gp_SerialOperate_Wx_dgrid
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@WxPTypeId			varchar(100),
		@WxSerial			varchar(100),
		@intWxSerialCount	int,
		@WxIfSerial			int,
		@WxPFullName		varchar(100),
		@KTypeID3			varchar(100),
		@STypeId			varchar(50)

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@billType	= BillType,
		@WxPTypeId  = PTypeId,
		@WxSerial	= Serial,
		@KTypeID3   = KTypeId3,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'


--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	State			int,
	CommissionState	varchar(10),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 166	--维修单
	BEGIN
		SET @mxTableName = 'wx_Bill_Self'
		SET @State = 25
		SET @Flag  = 1
		SET @InOutState = 25
		SET @CinOutState = 26
		SET @Cstate = 26
	END

IF @billType = 172	--上门维修单
	BEGIN
		SET @mxTableName = 'wx_Bill_Goto'
		SET @State = 25
		SET @Flag  = 1
		SET @InOutState = 25
		SET @CinOutState = 26
		SET @Cstate = 26
	END

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+	'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
	SET @SQL=@SQL+'	FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0
					AND M.InOrOut = ''O'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				)

					INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''O'' 
				
				
					
					DECLARE
						@strSplit			VARCHAR(100),
						@Serial_str			varchar(8000),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int
					
					SELECT 
						@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
					FROM @TmpBill
					
					
					
					SET @strSplit=''я''
		
					
					
					
					INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
					FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
					ORDER BY ShowOrder
				
					INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial1,PTypeId,Qty,Id
					FROM #TmpSerial
					
					'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='出库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断是否有相同的序列号
SET @sCount0 = 0
SET @sCount1 = 0

SELECT	Serial 
FROM 	#AllSerial
SET @sCount0 = @@ROWCOUNT

SELECT	DISTINCT Serial FROM #AllSerial
SET @sCount1 = @@ROWCOUNT

IF @sCount0 <> @sCount1
	BEGIN
		SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
		RETURN -904
	END

--从新置空错误ID的提示
SET @ErrId = 0

IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
		)
		AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END

--*******************************************************正式处理出库的序列号，如果拆分后的序列号表中的序列号为空，则表明是宽松管理的商品或者在宽松管理模式下没有录入任何的序列号*******************************************************--
IF EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--序列号（判断仓库属性）
		
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId <> @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId = T.PTypeId
					AND G.KTypeId <> @inKTypeId	
					AND P.IfSerial = @intSysMngSerial
					AND T.ID=d.ID
		) a

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断商品属性是否正确
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.PTypeId <> T.PTypeId					
								AND P.IfSerial = @intSysMngSerial
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.PTypeId <> T.PTypeId					
					AND P.IfSerial = @intSysMngSerial
					AND T.ID=d.ID
		) a
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--维修单根据维修的属性来控制出库的序列号WxProperty
		IF @BillType = 166	--维修单
			BEGIN
				
				SELECT
						@ErrId = a.nId,
						@ErrSerial = a.Serial
				FROM
				(		
					SELECT 	P.nId, T.Serial
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P,
							wx_Bill_Self S,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										GP_CruPTypeSerial G,
										#TmpPType P,
										wx_Bill_Self S
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND T.ID = S.ID
										AND G.PTypeId = T.PTypeId
										AND G.KTypeId = @inKTypeId	
										AND P.IfSerial = @intSysMngSerial
										AND (G.Flag = 0 OR G.State <> 1)
										AND S.WxProperty = 0
										AND S.InOrOut = 'O'
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND T.ID = S.ID
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = @inKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State <> 1)
							AND S.WxProperty = 0
							AND S.InOrOut = 'O'
							AND T.ID=d.ID
				) a
				
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
						RETURN -907 --失败
					END

					--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
				IF @mngLendSerial = 1
					BEGIN
					
					SELECT
							@ErrId = a.nId,
							@ErrSerial = a.Serial
					FROM
					(		
						SELECT 	P.nId, T.Serial
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P,
								wx_Bill_Self S,
								(
									SELECT 	MIN(T.ID) AS ID
									FROM	#AllSerial T,
											Gp_LendPTypeSerial G,
											#TmpPType P,
											wx_Bill_Self S
									WHERE	T.Serial = G.Serial
											AND T.PTypeId = P.PTypeId
											AND T.ID = S.ID
											AND P.IfSerial = @intSysMngSerial
											AND S.WxProperty = 0
											AND G.Flag = 0 AND G.State IN(18)
								) d
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND T.ID = S.ID
								AND P.IfSerial = @intSysMngSerial
								AND S.WxProperty = 0
								AND G.Flag = 0  AND G.State IN(18)
								AND T.ID=d.ID
					) a
						IF @@ROWCOUNT <> 0
							BEGIN
								SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
								RETURN -907 --失败
							END
					END
	
			--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
				IF @mngLendSerial = 1
					BEGIN
					
					SELECT
							@ErrId = a.nId,
							@ErrSerial = a.Serial
					FROM
					(		
						SELECT 	P.nId, T.Serial
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P,
								wx_Bill_Self S,
								(
									SELECT 	MIN(T.ID) AS ID
									FROM	#AllSerial T,
											Gp_LendPTypeSerial G,
											#TmpPType P,
											wx_Bill_Self S
									WHERE	T.Serial = G.Serial
											AND T.PTypeId = P.PTypeId
											AND T.ID = S.ID
											AND P.IfSerial = @intSysMngSerial
											AND S.WxProperty = 0
											AND G.Flag = 1 AND G.State IN(17)
								) d
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND T.ID = S.ID
								AND P.IfSerial = @intSysMngSerial
								AND S.WxProperty = 0
								AND G.Flag = 1  AND G.State IN(17)
								AND T.ID=d.ID
					) a
						IF @@ROWCOUNT <> 0
							BEGIN
								SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
								RETURN -907 --失败
							END
					END
	
					--正常商品出库必须是库存中的序列号
					
					SELECT
							@ErrId = a.nId,
							@ErrSerial = a.Serial
					FROM
					(		
						SELECT 	P.nId, T.Serial
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P,
								wx_Bill_Self S,
								(
									SELECT 	MIN(T.ID) AS ID
									FROM	#AllSerial T,
											GP_CruPTypeSerial G,
											#TmpPType P,
											wx_Bill_Self S
									WHERE	T.Serial = G.Serial
											AND T.PTypeId = P.PTypeId
											AND T.ID = S.ID
											AND G.PTypeId = T.PTypeId
											AND G.KTypeId = @inKTypeId	
											AND P.IfSerial = @intSysMngSerial
											AND (G.Flag = 0 OR G.State <> 25)
											AND S.WxProperty = 1
											AND S.InOrOut = 'O'
								) d
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND T.ID = S.ID
								AND G.PTypeId = T.PTypeId
								AND G.KTypeId = @inKTypeId	
								AND P.IfSerial = @intSysMngSerial
								AND (G.Flag = 0 OR G.State <> 25)
								AND S.WxProperty = 1
								AND S.InOrOut = 'O'
								AND T.ID=d.ID
					) a
					IF @@ROWCOUNT <> 0
						BEGIN
							SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
							RETURN -907 --失败
						END	

					--特殊处理维修单表头的序列号
					IF @intSysMngSerial = 1	--维修单表头序列号的处理
						BEGIN
							SELECT @WxIfSerial = IfSerial,@intWxSerialCount = ISNULL(SerialCount,0),@WxPFullName = FullName FROM PType WHERE TypeId = @WxPTypeId AND Deleted = 0 AND SonNum = 0
							IF @WxIfSerial = 1
								BEGIN
									IF @WxSerial = ''
										BEGIN
											SET @szPID='表头商品 '+CAST(@WxPFullName AS varchar(100))+' 采用了序列号管理，没有录入序列号，请确认！'
											RETURN -904
										END
									IF NOT EXISTS(SELECT TOP 1 1 FROM Gp_CruPTypeSerial WHERE Serial = @WxSerial AND State = 25)
										BEGIN
											SET @szPID='表头序列号'+CAST(@WxSerial AS varchar(100))+'不存在或者状态不正确！'
											RETURN -904
										END
									IF EXISTS(SELECT TOP 1 1 FROM Gp_CruPTypeSerial WHERE Serial = @WxSerial AND (KTypeId <> @KTypeID3 OR PTypeId <> @WxPTypeId))
										BEGIN
											SET @szPID='表头序列号'+CAST(@WxSerial AS varchar(100))+'商品或者仓库的属性不正确！'
											RETURN -904
										END
									ELSE
										BEGIN
											INSERT INTO GP_InOutPTypeSerial (
													Serial,
													PTypeID,
													BillNumberID,
													InKTypeID,
													IfCheck,
													BillType,
													BTypeID1,
													OutKTypeTime,
													State,
													ItemID,
													IsCombined,
													CargoID,
													ProduceDate,
													ValidDate,
													GoodsNumber,
													CostPrice,
													DETAILID
											)
											SELECT	G.Serial,
													G.PTypeId,
													@nBillId,
													@KTypeID3,
													't',
													@BillType,
													G.BTypeId1,
													G.OutKTypeTime,
													G.State,
													G.ItemID,
													G.IsCombined,
													G.CargoID,
													G.ProduceDate,
													G.ValidDate,
													G.GoodsNumber,
													G.CostPrice,
													-1				----表头为默认值 -1 
											FROM	Gp_CruPTypeSerial G
											WHERE	Serial = @WxSerial
					
											IF @@ERROR <> 0
												BEGIN
													SET @szPID='写入序列号的出库记录失败！'
													RETURN -903
												END	
										END
								END
							ELSE IF @WxSerial <> ''
								BEGIN
									SET @szPID='表头商品 '+CAST(@WxPFullName AS varchar(100))+' 没有采用序列号管理，不能录入序列号！'
									RETURN -904
								END
						END
			END
		ELSE				--上门维修单
			BEGIN
				--库存商品
				
				SELECT
							@ErrId = a.nId,
							@ErrSerial = a.Serial
				FROM
				(		
					SELECT 	P.nId, T.Serial
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P,
							Wx_Bill_GoTo S,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										GP_CruPTypeSerial G,
										#TmpPType P,
										Wx_Bill_GoTo S
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND T.ID = S.ID
										AND G.PTypeId = T.PTypeId
										AND G.KTypeId = @inKTypeId	
										AND P.IfSerial = @intSysMngSerial
										AND (G.Flag = 0 OR G.State <> 1)
										AND S.WxProperty = 0
										AND S.InOrOut = 'O'
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND T.ID = S.ID
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = @inKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State <> 1)
							AND S.WxProperty = 0
							AND S.InOrOut = 'O'
							AND T.ID=d.ID
				) a
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
						RETURN -907 --失败
					END		

			--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
			IF @mngLendSerial = 1
				BEGIN
				
					SELECT
							@ErrId = a.nId,
							@ErrSerial = a.Serial
					FROM
					(		
						SELECT 	P.nId, T.Serial
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P,
								Wx_Bill_GoTo S,
								(
									SELECT 	MIN(T.ID) AS ID
									FROM	#AllSerial T,
											Gp_LendPTypeSerial G,
											#TmpPType P,
											Wx_Bill_GoTo S
									WHERE	T.Serial = G.Serial
											AND T.PTypeId = P.PTypeId
											AND T.ID = S.ID
											AND P.IfSerial = @intSysMngSerial
											AND S.WxProperty = 0
											AND G.Flag = 0
								) d
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND T.ID = S.ID
								AND P.IfSerial = @intSysMngSerial
								AND S.WxProperty = 0
								AND G.Flag = 0
								AND T.ID=d.ID
					) a
					IF @@ROWCOUNT <> 0
						BEGIN
							SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
							RETURN -907 --失败
						END
				END	

				--维修品
				
				SELECT
						@ErrId = a.nId,
						@ErrSerial = a.Serial
				FROM
				(		
					SELECT 	P.nId, T.Serial
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P,
							Wx_Bill_GoTo S,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										GP_CruPTypeSerial G,
										#TmpPType P,
										Wx_Bill_GoTo S
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND T.ID = S.ID
										AND G.PTypeId = T.PTypeId
										AND G.KTypeId = @inKTypeId	
										AND P.IfSerial = @intSysMngSerial
										AND (G.Flag = 0 OR G.State <> 25)
										AND S.WxProperty = 1
										AND S.InOrOut = 'O'
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND T.ID = S.ID
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = @inKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State <> 25)
							AND S.WxProperty = 1
							AND S.InOrOut = 'O'
							AND T.ID=d.ID
				) a
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
						RETURN -907 --失败
					END	
			END
          	IF @BillType IN (166,172)
				BEGIN
				SELECT
						@ErrId = a.nId,
						@ErrSerial = a.Serial
				FROM
				(		
					SELECT 	P.nId, T.Serial
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										GP_CruPTypeSerial G,
										#TmpPType P
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND G.Flag = 0
										AND G.State IN (35) 
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.Flag = 0
							AND G.State IN (35)
							AND T.ID=d.ID
					
				) a
				END
				IF @ErrId <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在配送在途的状态！'
						RETURN -907 --失败
					END

		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	T.Serial,

				T.PTypeId,
				G.State,
				ISNULL(G.CommissionState,'') AS CommissionState,
				T.Id
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = @inKTypeId
				AND G.Flag = 1

		--判断是否所有的序列号都是在库存中的序列号，如果有序列号不在库存中了，则不允许出库Mantis 3885
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT  P.nId,
					T.Serial
			FROM	#AllSerial	T,
					#TmpPType	P,
					(
						SELECT	MIN(T.Id) AS ID
						FROM	#AllSerial T,
								#TmpPType P
						WHERE	T.PTypeId = P.PTypeId		
								AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					)d
			WHERE	T.PTypeId = P.PTypeId		
					AND T.Serial NOT IN (SELECT Serial FROM #UnionSerial)
					AND T.Id = d.ID
		)a
	
		
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在!'	
				RETURN -907 --失败
			END
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				@inKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				@Cstate,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=B.ID

		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901

			END
		
		--修改出库序列号的状态
		UPDATE	Gp_CruPTypeSerial
		SET		BTypeId1= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId1 END,								
				OutKTypeTime = @BillDate,
				State	= @Cstate,
				Flag 	= 0
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND T.PTypeId = P.PTypeId
				AND G.KTypeId = @inKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1
				AND T.ID=P.Id
				
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的出库记录失败！'
				RETURN -903
			END	
	END
ELSE IF @BillType = 166	--特殊处理维修单表头信息
	BEGIN
		--特殊处理维修单表头的序列号
		IF @intSysMngSerial = 1	--维修单表头序列号的处理
			BEGIN
				SELECT @WxIfSerial = IfSerial,@intWxSerialCount = ISNULL(SerialCount,0),@WxPFullName = FullName FROM PType WHERE TypeId = @WxPTypeId AND Deleted = 0 AND SonNum = 0
				IF @WxIfSerial = 1
					BEGIN
						IF @WxSerial = ''
							BEGIN
								SET @szPID='表头商品 '+CAST(@WxPFullName AS varchar(100))+' 采用了序列号管理，没有录入序列号，请确认！'
								RETURN -904
							END
						IF NOT EXISTS(SELECT TOP 1 1 FROM Gp_CruPTypeSerial WHERE Serial = @WxSerial AND State = 25)
							BEGIN
								SET @szPID='表头序列号'+CAST(@WxSerial AS varchar(100))+'不存在或者状态不正确！'
								RETURN -904
							END
						IF EXISTS(SELECT TOP 1 1 FROM Gp_CruPTypeSerial WHERE Serial = @WxSerial AND (KTypeId <> @KTypeID3 OR PTypeId <> @WxPTypeId))
							BEGIN
								SET @szPID='表头序列号'+CAST(@WxSerial AS varchar(100))+'商品或者仓库的属性不正确！'
								RETURN -904
							END
						ELSE
							BEGIN
								INSERT INTO GP_InOutPTypeSerial (
										Serial,
										PTypeID,
										BillNumberID,
										InKTypeID,
										IfCheck,
										BillType,
										BTypeID1,
										OutKTypeTime,
										State,
										ItemID,
										IsCombined,
										CargoID,
										ProduceDate,
										ValidDate,
										GoodsNumber,
										CostPrice,
										DETAILID
								)
								SELECT	Serial,
										PTypeId,
										@nBillId,
										@KTypeID3,
										't',
										@BillType,
										BTypeId1,
										OutKTypeTime,
										State,
										ItemID,
										IsCombined,
										CargoID,
										ProduceDate,
										ValidDate,
										GoodsNumber,
										CostPrice,
										-1
								FROM	Gp_CruPTypeSerial
								WHERE	Serial = @WxSerial
		
								IF @@ERROR <> 0
									BEGIN
										SET @szPID='写入序列号的出库记录失败！'
										RETURN -903
									END	
							END
					END
				ELSE IF @WxSerial <> ''
					BEGIN
						SET @szPID='表头商品 '+CAST(@WxPFullName AS varchar(100))+' 没有采用序列号管理，不能录入序列号！'
						RETURN -904
					END
			END
	END
--****************************************************************处理入库序列号*************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial

--初始化错误值，重要，不然判断要出错
SET @ErrId = 0

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+					
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE M.wxProperty WHEN 0 THEN M.Price ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END
					
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
		PType P
WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
		AND P.TypeId = M.PTypeId
		AND P.SonNum = 0
		AND P.Deleted = 0					
		AND M.InOrOut = ''I'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal02 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal02
--处理结果
FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''I'' ORDER BY ID

				
				
				DECLARE
					@strSplit			VARCHAR(100),
					@Serial_str			varchar(8000),
					@Serial_tmp			varchar(1000),
					@TPTypeId			varchar(100),
					@TQty				 NUMERIC(24, 10) ,
					@TXId				int
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='入库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='入库表格第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal02
DEALLOCATE MngSerialNormal02	

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END
--从新置空错误ID的提示
SET @ErrId = 0

--委托发货的序列号不允许入库 2008-04-22 V39
SELECT	TOP 1
		@ErrSerial = T.Serial
FROM	#AllSerial T,
		GP_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND G.State = 13 

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='委托发货的序列号【'+CAST(@ErrSerial AS varchar(100))+'】在结算前不允许再次入库！'
		RETURN -907 --失败
	END

--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.State IN (17,20) 				
								AND G.Flag = 1 
								AND G.BFlag = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.State IN (17,20) 				
					AND G.Flag = 1 
					AND G.BFlag = 1 
					AND T.ID=d.ID
		) a

		IF @ErrId <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--受托代销未结算的商品不允许入库

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND ISNULL(G.CommissionState,'')='0' 
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND ISNULL(G.CommissionState,'')='0' 
			AND T.ID=d.ID
) a

IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在受托代销结算之前不允许入库！'
		RETURN -908 --失败
	END	

--处理入库的序列号

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND P.IfSerial = @intSysMngSerial
						AND G.Flag = 1
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND P.IfSerial = @intSysMngSerial
			AND G.Flag = 1
			AND T.ID=d.ID
) a

IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END



--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial


--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		@outKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		@outKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)
IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID2,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		@outKTypeId,
		a.PTypeId,
		@BTypeId,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改当前序列号的状态
UPDATE	Gp_CruPTypeSerial
SET		BTypeId2= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId2 END,
		PTypeId = T.PTypeId,

		KTypeId = @outKTypeId,								
		InKTypeTime = @BillDate,
		State = @State,
		Flag  = 1,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=0,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND P.ID=B.ID
		AND T.ID=B.ID
		

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_Wx_dgrid_ks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_Wx_dgrid_ks]
GO





















/*
	作者：谢吉康
	日期：2006-3-3
	描述：拆装、换货、维修的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 15:23:29
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	时间:2015-05-19
	描述:序列号严密关联成本等
	
*/
CREATE    PROCEDURE Gp_SerialOperate_Wx_dgrid_ks
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(8000),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(8000),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@WxPTypeId			varchar(100),
		@WxSerial			varchar(100),
		@intWxSerialCount	int,
		@WxIfSerial			int,
		@WxPFullName		varchar(100),
		@KTypeID3			varchar(100),
		@JieJianBillId		numeric(18,0),
		@STypeId			varchar(50)

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@KTypeID3   = KTypeId3,
		@billType	= BillType,
		@WxPTypeId  = PTypeId,
		@WxSerial	= Serial,
		@JieJianBillId = JieJianBillNumberId,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SELECT @PTypeId = PTypeId FROM Wx_Bill_JIEJIAN WHERE BillNumberId = @JieJianBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 			varchar(200),
	PTypeId			varchar(100),
	State			int,
	CommissionState	varchar(10),
	ID				INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

IF @billType = 166	--维修单
	BEGIN
		SET @mxTableName = 'wx_Bill_Self'
		SET @State = 25
		SET @Flag  = 1
		SET @InOutState = 25
		SET @CinOutState = 26
		SET @Cstate = 26
	END

IF @billType = 172	--上门维修单
	BEGIN
		SET @mxTableName = 'wx_Bill_Goto'
		SET @State = 25
		SET @Flag  = 1
		SET @InOutState = 25
		SET @CinOutState = 26
		SET @Cstate = 26
	END

--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+	'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE '+@nCostingMethod+' WHEN 3 THEN CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END					
	SET @SQL=@SQL+'	FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0
					AND M.InOrOut = ''O'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''O'' 

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@l					int,
						@intGoOn			int,
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int


				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='出库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

IF EXISTS(
		SELECT a.Serial FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE (b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
		)
		AND @intserialrelation=1
)
BEGIN
	SELECT @ErrSerial=a.Serial 
	FROM
	(
		SELECT TOP 1 a.Serial
		FROM #AllSerial a
		INNER JOIN #TmpPType b
		ON a.ID=b.ID
		LEFT JOIN gp_CruPtypeSerial c
		ON a.Serial=c.Serial
		WHERE b.ItemID <> c.ItemID
		OR b.Iscombined<>c.IsCombined
		OR b.GoodsNumber<>c.GoodsNumber
		OR b.ProduceDate<>c.ProduceDate
		OR b.ValidDate<>c.ValidDate
		OR (@nCostingMethod=3 AND b.CostPrice<>c.CostPrice)
		--OR b.CargoID<>c.CargoID
	) a
	SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】的批号/生产日期/效期至/自由项/货位/成本价等跟库存序列号的不一致，不能出库！'	
		RETURN -907 --失败
END

--*******************************************************正式处理出库的序列号，如果拆分后的序列号表中的序列号为空，则表明是宽松管理的商品或者在宽松管理模式下没有录入任何的序列号*******************************************************--
IF EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--序列号（判断仓库属性）
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId <> @inKTypeId	
							AND P.IfSerial = @intSysMngSerial
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId <> @inKTypeId	
				AND P.IfSerial = @intSysMngSerial 
				AND T.ID=d.ID

		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】仓库属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--判断商品属性是否正确
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.PTypeId <> T.PTypeId					
							AND P.IfSerial = @intSysMngSerial
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.PTypeId <> T.PTypeId					
				AND P.IfSerial = @intSysMngSerial 
				AND T.ID=d.ID
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】商品属性不正确，不能过账！'	
				RETURN -907 --失败
			END

		--维修单根据维修的属性来控制出库的序列号WxProperty
		IF @BillType = 166	--维修单
			BEGIN
				
				SELECT	@ErrId =	P.nId,
						@ErrSerial = T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						Wx_Bill_Self S,
						(
							SELECT 	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									Wx_Bill_Self S,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND T.ID = S.ID
									AND G.PTypeId = T.PTypeId
									AND G.KTypeId = @inKTypeId	
									AND P.IfSerial = @intSysMngSerial
									AND (G.Flag = 0 OR G.State <> 1)
									AND S.WxProperty = 0
									AND S.InOrOut = 'O'
						) d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND T.ID = S.ID
						AND G.PTypeId = T.PTypeId
						AND G.KTypeId = @inKTypeId	
						AND P.IfSerial = @intSysMngSerial
						AND (G.Flag = 0 OR G.State <> 1)
						AND S.WxProperty = 0
						AND S.InOrOut = 'O' 
						AND T.ID=d.ID
				
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
						RETURN -907 --失败
					END

				--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
				IF @mngLendSerial = 1
					BEGIN
						
						SELECT	@ErrId =	P.nId,
								@ErrSerial = T.Serial
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P,
								Wx_Bill_Self S,
								(
									SELECT 	MIN(T.ID) AS ID
									FROM	#AllSerial T,
											Gp_LendPTypeSerial G,
											Wx_Bill_Self S,
											#TmpPType P
									WHERE	T.Serial = G.Serial
											AND T.PTypeId = P.PTypeId
											AND T.ID = S.ID
											AND P.IfSerial = @intSysMngSerial
											AND S.WxProperty = 0
											AND G.Flag = 0 and G.State IN(18)
								) d
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND T.ID = S.ID
								AND P.IfSerial = @intSysMngSerial
								AND S.WxProperty = 0
								AND G.Flag = 0 and G.State IN(18)
								AND T.ID=d.ID
						IF @@ROWCOUNT <> 0
							BEGIN
								SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
								RETURN -907 --失败
							END
					END
					
		--如果系统采用了借欠序列号的校验模式，借进的序列号只有在做了借进还回后才能出库
				IF @mngLendSerial = 1
					BEGIN
						
						SELECT	@ErrId =	P.nId,
								@ErrSerial = T.Serial
						FROM	#AllSerial T,
								Gp_LendPTypeSerial G,
								#TmpPType P,
								Wx_Bill_Self S,
								(
									SELECT 	MIN(T.ID) AS ID
									FROM	#AllSerial T,
											Gp_LendPTypeSerial G,
											Wx_Bill_Self S,
											#TmpPType P
									WHERE	T.Serial = G.Serial
											AND T.PTypeId = P.PTypeId
											AND T.ID = S.ID
											AND P.IfSerial = @intSysMngSerial
											AND S.WxProperty = 0
											AND G.Flag = 1 and G.State IN(17)
								) d
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND T.ID = S.ID
								AND P.IfSerial = @intSysMngSerial
								AND S.WxProperty = 0
								AND G.Flag = 1 and G.State IN(17)
								AND T.ID=d.ID
						IF @@ROWCOUNT <> 0
							BEGIN
								SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
								RETURN -907 --失败
							END
					END


				--正常商品出库必须是库存中的序列号
				
				SELECT	@ErrId =	P.nId,
						@ErrSerial = T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						Wx_Bill_Self S,
						(
							SELECT 	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									Wx_Bill_Self S,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND T.ID = S.ID
									AND G.PTypeId = T.PTypeId
									AND G.KTypeId = @inKTypeId	
									AND P.IfSerial = @intSysMngSerial
									AND (G.Flag = 0 OR G.State <> 25)
									AND S.WxProperty = 1
									AND S.InOrOut = 'O'
						) d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND T.ID = S.ID
						AND G.PTypeId = T.PTypeId
						AND G.KTypeId = @inKTypeId	
						AND P.IfSerial = @intSysMngSerial
						AND (G.Flag = 0 OR G.State <> 25)
						AND S.WxProperty = 1
						AND S.InOrOut = 'O'
						AND T.ID=d.ID
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
						RETURN -907 --失败
					END	
			END	
		ELSE				--上门维修单
			BEGIN
				
				SELECT	@ErrId =	P.nId,
						@ErrSerial = T.Serial
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P,
						Wx_Bill_GoTo S,
						(
							SELECT 	MIN(T.ID) AS ID
							FROM	#AllSerial T,
									GP_CruPTypeSerial G,
									Wx_Bill_GoTo S,
									#TmpPType P
							WHERE	T.Serial = G.Serial
									AND T.PTypeId = P.PTypeId
									AND T.ID = S.ID
									AND G.PTypeId = T.PTypeId
									AND G.KTypeId = @inKTypeId	
									AND P.IfSerial = @intSysMngSerial
									AND (G.Flag = 0 OR G.State <> 1)
									AND S.WxProperty = 0
									AND S.InOrOut = 'O'
						) d
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND T.ID = S.ID
						AND G.PTypeId = T.PTypeId
						AND G.KTypeId = @inKTypeId	
						AND P.IfSerial = @intSysMngSerial
						AND (G.Flag = 0 OR G.State <> 1)
						AND S.WxProperty = 0
						AND S.InOrOut = 'O'
						AND T.ID=d.ID
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
						RETURN -907 --失败
					END		
	
			--如果系统采用了借欠序列号的校验模式，借出的序列号只有在做了借出还回后才能出库
			IF @mngLendSerial = 1
				BEGIN
					
					SELECT	@ErrId =	P.nId,
							@ErrSerial = T.Serial
					FROM	#AllSerial T,
							Gp_LendPTypeSerial G,
							#TmpPType P,
							Wx_Bill_GoTo S,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										Gp_LendPTypeSerial G,
										Wx_Bill_GoTo S,
										#TmpPType P
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND T.ID = S.ID
										AND P.IfSerial = @intSysMngSerial
										AND S.WxProperty = 0
										AND G.Flag = 0
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND T.ID = S.ID
							AND P.IfSerial = @intSysMngSerial
							AND S.WxProperty = 0
							AND G.Flag = 0
							AND T.ID=d.ID
					IF @@ROWCOUNT <> 0
						BEGIN
							SET @szPID='由于系统采用了借欠序列号的校验模式，序列号【'+CAST(@ErrSerial AS varchar(100))+'】不能进行出库操作，请重新选择出库序列号！'	
							RETURN -907 --失败
						END
				END	
				
				
					SELECT	@ErrId =	P.nId,
							@ErrSerial = T.Serial
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P,
							Wx_Bill_GoTo S,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										GP_CruPTypeSerial G,
										Wx_Bill_GoTo S,
										#TmpPType P
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND T.ID = S.ID
										AND G.PTypeId = T.PTypeId
										AND G.KTypeId = @inKTypeId	
										AND P.IfSerial = @intSysMngSerial
										AND (G.Flag = 0 OR G.State <> 25)
										AND S.WxProperty = 1
										AND S.InOrOut = 'O'
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND T.ID = S.ID
							AND G.PTypeId = T.PTypeId
							AND G.KTypeId = @inKTypeId	
							AND P.IfSerial = @intSysMngSerial
							AND (G.Flag = 0 OR G.State <> 25)
							AND S.WxProperty = 1
							AND S.InOrOut = 'O'
							AND T.ID=d.ID
				IF @@ROWCOUNT <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前库存中不存在！'	
						RETURN -907 --失败
					END	
			END
        
				IF @BillType IN (166,172)
				BEGIN
				SELECT
						@ErrId = a.nId,
						@ErrSerial = a.Serial
				FROM
				(		
					SELECT 	P.nId, T.Serial
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P,
							(
								SELECT 	MIN(T.ID) AS ID
								FROM	#AllSerial T,
										GP_CruPTypeSerial G,
										#TmpPType P
								WHERE	T.Serial = G.Serial
										AND T.PTypeId = P.PTypeId
										AND G.Flag = 0
										AND G.State IN (35) 
							) d
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.Flag = 0
							AND G.State IN (35)
							AND T.ID=d.ID
					
				) a
				END
				IF @ErrId <> 0
					BEGIN
						SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在配送在途的状态！'
						RETURN -907 --失败
					END


		--求当前序列号和序列号库的交集
		INSERT INTO #UnionSerial(
			Serial,
			PTypeId,
			State,
			CommissionState,
			ID
		)
		SELECT	T.Serial,
				T.PTypeId,
				G.State,
				ISNULL(G.CommissionState,'') AS CommissionState,
				T.ID
		FROM	#AllSerial T,
				Gp_CruPTypeSerial G
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND G.KTypeId = @inKTypeId
				AND G.Flag = 1


		--写或者修改序列号信息
		INSERT INTO Gp_CruPTypeSerial
		(
			Serial,
			KTypeID,
			PTypeID,
			BTypeID1,
			BTypeID2,
			InKTypeTime,
			OutKTypeTime,
			State,
			Flag,
			CommissionState,
			ItemID,
			IsCombined,
			CargoID,
			ProduceDate,
			ValidDate,
			GoodsNumber,
			CostPrice
		)
		SELECT	a.Serial,
				@inKTypeId,
				a.PTypeId,
				@BTypeId,
				'',
				@BillDate,
				@BillDate,
				@Cstate,
				0,
				@CommissionState,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice		
		FROM	#AllSerial a,#TmpPType B
		WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)
		
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的入库记录失败！'
				RETURN -902
			END
		
		--写序列号的出入口记录
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				BTypeID2,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	a.Serial,
				a.PTypeId,
				@nBillId,
				@inKTypeId,
				't',
				@BillType,
				@BTypeID,
				'',
				@BillDate,
				@Cstate,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice	,
				B.Id	
		FROM	#AllSerial a,#TmpPType B
		WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)
		
		--写序列号跟踪记录（出库）
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State,
				ItemID,
				IsCombined,
				CargoID,
				ProduceDate,
				ValidDate,
				GoodsNumber,
				CostPrice,
				DETAILID
		)
		SELECT	U.Serial,
				U.PTypeId,
				@nBillId,
				@inKTypeId,
				't',
				@BillType,
				@BTypeId,
				@BillDate,
				@Cstate,
				B.ItemID,
				B.IsCombined,
				B.CargoID,
				B.ProduceDate,
				B.ValidDate,
				B.GoodsNumber,
				B.CostPrice,
				B.Id
		FROM	#AllSerial T,
				#UnionSerial U,
				#TmpPType B
		WHERE	T.Serial = U.Serial 
				AND T.PTypeId = U.PTypeId
				AND T.id=B.ID
				AND U.ID=B.ID
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写序列号的出入库记录失败！'
				RETURN -901

			END
		
		--修改出库序列号的状态
		UPDATE	Gp_CruPTypeSerial
		SET		BTypeId1= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId1 END,								
				OutKTypeTime = @BillDate,
				State	= @Cstate,
				Flag 	= 0,
				--CostPrice=p.CostPrice,
				GoodsNumber=p.GoodsNumber,
				--CargoID=p.cargoID,
				ProduceDate=p.ProduceDate,
				ValidDate=p.ValidDate
		FROM	#UnionSerial T,
				Gp_CruPTypeSerial G,
				#TmpPType P,
				#AllSerial B
		WHERE	T.Serial = G.Serial 
				AND G.PTypeId = T.PTypeId
				AND T.PTypeId = P.PTypeId
				AND G.KTypeId = @inKTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1
				AND B.Id=P.Id
				AND T.ID=B.Id
		
		IF @@ERROR <> 0
			BEGIN
				SET @szPID='修改序列号的出库记录失败！'
				RETURN -903

			END	
	END

--特殊处理维修单表头的序列号
IF @BillType = 166 AND @WxSerial <> '' AND EXISTS(SELECT TOP 1 1 FROM Gp_CruPTypeSerial WHERE Serial = @WxSerial) --维修单表头序列号的处理
	BEGIN
		
		INSERT INTO GP_InOutPTypeSerial (
				Serial,
				PTypeID,
				BillNumberID,
				InKTypeID,
				IfCheck,
				BillType,
				BTypeID1,
				OutKTypeTime,
				State
		)
		SELECT	Serial,
				PTypeId,
				@nBillId,
				@KTypeID3,
				't',
				@BillType,
				BTypeId1,
				OutKTypeTime,
				State
		FROM	Gp_CruPTypeSerial
		WHERE	Serial = @WxSerial

		IF @@ERROR <> 0
			BEGIN
				SET @szPID='写入序列号的出库记录失败！'
				RETURN -903
			END	
	END
--****************************************************************处理入库序列号*************************************************************--
TRUNCATE TABLE #TmpPType
TRUNCATE TABLE #TmpSerial
TRUNCATE TABLE #AllSerial
TRUNCATE TABLE #UnionSerial

--初始化错误值，重要，不然判断要出错
SET @ErrId = 0

--将序列号严密管理的商品写入临时表
SET @SQL = 'INSERT INTO #TmpPType 
			SELECT	M.PTypeId,
					M.Qty,
					M.Id,
					P.IfSerial,
					P.SerialCount,'
					
IF @intserialrelation=1
BEGIN						
	SET @SQL=@SQL+					
					'M.ItemID,
					M.IsCombined,
					M.CargoID,
					M.ProduceDate,
					M.ValidDate,
					M.GoodsNumber,
					CASE M.wxProperty WHEN 0 THEN M.Price ELSE 0 END '
END
ELSE
BEGIN
	SET @SQL=@SQL+'0,0,0,'''','''','''',0 '
END
					
SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
					PType P
			WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
					AND P.TypeId = M.PTypeId
					AND P.SonNum = 0
					AND P.Deleted = 0					
					AND M.InOrOut = ''I'''
--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

EXEC(@SQL)
--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END
--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal02 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal02
--处理结果
FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		SET @SerialSQL = '
				DECLARE  @TmpBill TABLE
				(	
					Serial 	varchar(max),
					PTypeId	varchar(100),
					Qty		 NUMERIC(24, 10) ,
					Id		int
				)

				INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' AND InOrOut = ''I'' ORDER BY ID

				DECLARE	@i 					int,				--计数器
						@j 					int,				--计数器
						@k					int,				--计数器
						@Serial_str			varchar(MAX),
						@Serial_tmp			varchar(1000),
						@TPTypeId			varchar(100),
						@TQty				 NUMERIC(24, 10) ,
						@TXId				int

				
				
				DECLARE
					@strSplit			VARCHAR(100)
				
				SELECT 
					@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
				FROM @TmpBill
				
				
				
				SET @strSplit=''я''
	
				
				
				
				INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
				FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
				ORDER BY ShowOrder
			
				INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
				SELECT Serial,Serial1,PTypeId,Qty,Id
				FROM #TmpSerial
				'								
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id	
				IF @Qty<>@SerialCount
					BEGIN
						SET @szPID='入库 第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='入库表格第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal02 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END							
--关闭并释放游标资源
CLOSE MngSerialNormal02
DEALLOCATE MngSerialNormal02	

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--委托发货的序列号不允许入库 2008-04-22 V39
SELECT	TOP 1
		@ErrSerial = T.Serial
FROM	#AllSerial T,
		GP_CruPTypeSerial G
WHERE	T.Serial = G.Serial
		AND G.State = 13 

IF @@ROWCOUNT <> 0
	BEGIN
		SET @szPID='委托发货的序列号【'+CAST(@ErrSerial AS varchar(100))+'】在结算前不允许再次入库！'
		RETURN -907 --失败
	END

--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_LendPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_LendPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND G.State IN (17,20) 				
							AND G.Flag = 1 
							AND G.BFlag = 1
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND G.State IN (17,20) 				
				AND G.Flag = 1 
				AND G.BFlag = 1
				AND T.ID=d.ID
		IF @ErrId <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--受托代销未结算的商品不允许入库

		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND ISNULL(G.CommissionState,'')='0' 
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND ISNULL(G.CommissionState,'')='0' 
				AND T.ID=d.ID
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在受托代销结算之前不允许入库！'
		RETURN -908 --失败
	END	

--处理入库的序列号

		SELECT	@ErrId =	P.nId,
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G,
				#TmpPType P,
				(
					SELECT 	MIN(T.ID) AS ID
					FROM	#AllSerial T,
							GP_CruPTypeSerial G,
							#TmpPType P
					WHERE	T.Serial = G.Serial
							AND T.PTypeId = P.PTypeId
							AND P.IfSerial = @intSysMngSerial
							AND G.Flag = 1 		
				) d
		WHERE	T.Serial = G.Serial
				AND T.PTypeId = P.PTypeId
				AND P.IfSerial = @intSysMngSerial
				AND G.Flag = 1 		
				AND T.ID=d.ID
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END

--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial(
	Serial,
	PTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		G.State,
		ISNULL(G.CommissionState,'') AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 


--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	U.Serial,
		U.PTypeId,
		@nBillId,
		@outKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		AND U.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写序列号跟踪记录（入库）
INSERT INTO GP_InOutPTypeSerial (
		Serial,
		PTypeID,
		BillNumberID,
		InKTypeID,
		IfCheck,
		BillType,
		BTypeID2,
		InKTypeTime,
		State,
		ItemID,
		IsCombined,
		CargoID,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		CostPrice,
		DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		@outKTypeId,
		't',
		@BillType,
		@BTypeId,
		@BillDate,
		@State,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)


IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID2,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		@outKTypeId,
		a.PTypeId,
		@BTypeId,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		B.CargoID,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.ID=B.id
		AND a.Serial NOT IN (
		SELECT	Serial
		FROM	#UnionSerial
)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改当前序列号的状态
UPDATE	Gp_CruPTypeSerial
SET		BTypeId2= CASE WHEN ISNULL(@BTypeId,'')<>'' THEN @BTypeId ELSE BTypeId2 END,
		--PTypeId = T.PTypeId,
		KTypeId = @outKTypeId,								
		InKTypeTime = @BillDate,
		State = @State,
		Flag  = 1,
		CostPrice=p.CostPrice,
		GoodsNumber=p.GoodsNumber,
		CargoID=0,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined
FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial 
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND P.ID=B.ID
		AND T.ID=B.ID

IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的出库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperate_Wx_rk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperate_Wx_rk]
GO











/*
	作者：谢吉康
	日期：2006-3-3
	描述：入库的序列号单独过帐	
	
	修改：赵斌
	时间：2012年2月10日 13:55:47
	描述：优化
	
	修改：冯波
	时间：2014年7月1日
	描述：拆分优化
	
	修改:冯波
	日期:2015-05-15
	描述:序列号严密关联
*/
CREATE   PROCEDURE Gp_SerialOperate_Wx_rk
(
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000)	output		--返回信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@intSysMngSerial 	int,
		@mngLendSerial		int,
		@PTypeId			varchar(100),
		@Qty				 NUMERIC(24, 10) ,
		@Id					int,
		@SerialSQL			varchar(MAX),
		@ErrId				int,
		@ErrSerial			varchar(200),
		@BillDate			datetime,
		@BTypeId			varchar(100),
		@inKTypeId			varchar(100),
		@outKTypeId			varchar(100),
		@BillType			int,
		@SerialCount		int,
		@mxTableName		varchar(100),
		@State				int,
		@InOutState			int,
		@Flag				int,
		@CommissionState	varchar(100),
		@SerialSaleBack		int,
		@Cstate				int,
		@CinOutState		int,
		@SQL				varchar(MAX),
		@UnionCount			int,
		@PFullName 			varchar(1000),
		@sCount0			numeric(18,0),
		@sCount1			numeric(18,0),
		@intSerialCount		int,
		@STypeId			varchar(50)

--获取该单据的具体信息
SELECT	@BillDate	= BillDate,
		@BTypeId 	= DealBTypeID,
		@inKTypeId	= KTypeId,
		@outKTypeId	= KTypeId2,
		@BillType	= BillType,
		@STypeId    = STypeId
FROM	BillIndex
WHERE	BillNumberId = @nBillId

SET @CommissionState = NULL
SET @ErrId = 0

DECLARE
	@nCostingMethod	VARCHAR(50)

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

--建立商品临时表
CREATE TABLE #TmpPType
(
	nId				int identity(1,1),
	PTypeId			varchar(100),
	Qty				 NUMERIC(24, 10) ,
	Id				int,
	IfSerial		int,
	SerialCount		int,
	ItemID			INT,
	IsCombined		INT,
	CargoID			INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	CostPrice		 NUMERIC(24, 10) 
)

--建立序列号临时表
CREATE TABLE #TmpSerial
(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--交集序列号
CREATE TABLE #UnionSerial
(
	Serial 				varchar(200),
	PTypeId				varchar(100),
	State				int,
	CommissionState		varchar(5),
	ID					INT
)

--收集所有行数的序列号
CREATE TABLE #AllSerial(
	nId			int identity(1,1),
	Serial 		varchar(200),
	Serial1		varchar(200),
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Id			int
)

--处理单据的明细表名称
IF @BillType = 165	--维修接件单
	BEGIN
		SET @mxTableName = 'wx_Bill_JieJian'
		SET	@State = 25
		SET @InOutState = 25
		SET @Flag  = 1
	END

IF @BillType = 170	--送修返回单
	BEGIN
		SET @mxTableName = 'wx_Bill_SendBack'
		SET	@State = 25
		SET @InOutState = 25
		SET @Flag  = 1
	END

IF @BillType = 14	--报溢单
	BEGIN
		SET @mxTableName = 'OverFlowBill'
		SET	@State = 25
		SET @InOutState = 25
		SET @Flag  = 1
	END


--判断系统是否是序列号强制管理
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
--序列号借欠出入库校验模式
SELECT  @mngLendSerial = Value FROM UserConfig WHERE ConfigName = 'mngLendSerial'

--将序列号严密管理的商品写入临时表
IF @BillType = 170 OR @BillType = 14
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						M.Qty,
						M.Id,
						P.IfSerial,
						P.SerialCount,'
	IF @intserialrelation=1
	BEGIN					
		SET @SQL=@SQL+'M.ItemID,
		M.IsCombined,
		M.CargoID,'
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'
	END
	
	SET @SQL=@SQL+''''' AS ProduceDate,
	'''' AS ValidDate,'
						
	IF @intserialrelation=1
	BEGIN					
		SET @SQL=@SQL+'M.GoodsNumber,
						0 AS GoodsCostPrice '
	END
	ELSE
		SET @SQL=@SQL+''''',0 '
	BEGIN	
						
		SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
				PType P
		WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
				AND P.TypeId = M.PTypeId
				AND P.SonNum = 0
				AND P.Deleted = 0 '
	END
END						
ELSE
BEGIN
	SET @SQL = 'INSERT INTO #TmpPType 
				SELECT	M.PTypeId,
						1 AS Qty,
						M.Id,
						P.IfSerial,
						P.SerialCount,'
						
	IF @intserialrelation=1
	BEGIN					
		SET @SQL=@SQL+						
						'M.ItemID,
						M.IsCombined,
						M.CargoID,'
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'0,0,0,'
	END						
				
	SET @SQL=@SQL+''''' AS ProduceDate,
						'''' AS ValidDate,'
						
	IF @intserialrelation=1
	BEGIN					
		SET @SQL=@SQL+
						' M.GoodsNumber,
						0 AS GoodsCostPrice '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+''''',0 '
	END		
					
	SET @SQL=@SQL+' FROM 	'+@mxTableName+' M,
			PType P
	WHERE 	M.BillNumberId = '+CAST(@nBillId AS varchar(100))+'
			AND P.TypeId = M.PTypeId
			AND P.SonNum = 0
			AND P.Deleted = 0 '
END

--在序列号宽松模式下，只取有序列号内容的商品来过帐
IF @intSysMngSerial = 0
	SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

SET @SQL = @SQL + ' ORDER BY M.ID '

--PRINT(@SQL)
EXEC(@SQL)

--判断单据明细中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--游标循环商品的明细行数，一行一行的写入序列号数据
DECLARE MngSerialNormal01 CURSOR FOR
	SELECT PTypeId,Qty,Id,nId,SerialCount FROM #TmpPType WHERE IfSerial = @intSysMngSerial
--打开具体的游标
OPEN MngSerialNormal01
--处理结果
FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount

--如果记录存在
WHILE @@FETCH_STATUS = 0
	BEGIN
		TRUNCATE TABLE #TmpSerial
		--写序列号入临时表
		IF @BillType = 170
			SET @SerialSQL = '
					DECLARE  @TmpBill TABLE
	
					(	
	
						Serial 	varchar(max),
						PTypeId	varchar(100),
						Qty		 NUMERIC(24, 10) ,
						Id		int
					)
	
					INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' 
	
					DECLARE	@i 					int,				--计数器
							@j 					int,				--计数器
							@k					int,				--计数器
							@l					int,
							@intGoOn			int,
							@Serial_str			varchar(MAX),
							@Serial_tmp			varchar(1000),
							@TPTypeId			varchar(100),
							@TQty				 NUMERIC(24, 10) ,
							@TXId				int
	
					
					
					DECLARE
						@strSplit			VARCHAR(100)
					
					SELECT 
						@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
					FROM @TmpBill
					
					
					
					SET @strSplit=''я''
		
					
					
					
					INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
					FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
					ORDER BY ShowOrder
				
					INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial1,PTypeId,Qty,Id
					FROM #TmpSerial
					'								
		ELSE
			SET @SerialSQL = '
					DECLARE  @TmpBill TABLE
	
					(	
	
						Serial 	varchar(max),
						PTypeId	varchar(100),
						Qty		 NUMERIC(24, 10) ,
						Id		int
					)
	
					
					INSERT INTO @TmpBill(Serial,PTypeId,Qty,Id) SELECT Serial,PTypeId,1 AS Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@nBillId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))+' 
	
					DECLARE	@i 					int,				--计数器
							@j 					int,				--计数器
							@k					int,				--计数器
							@l					int,
							@intGoOn			int,
							@Serial_str			varchar(MAX),
							@Serial_tmp			varchar(1000),
							@TPTypeId			varchar(100),
							@TQty				 NUMERIC(24, 10) ,
							@TXId				int
	
					
					
					DECLARE
						@strSplit			VARCHAR(100)
					
					SELECT 
						@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id 
					FROM @TmpBill
					
					
					
					SET @strSplit=''я''
		
					
					
					
					INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial,@TPTypeId,@TQty,@TXId 
					FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
					ORDER BY ShowOrder
				
					INSERT INTO #AllSerial(Serial,Serial1,PTypeId,Qty,Id)
					SELECT Serial,Serial1,PTypeId,Qty,Id
					FROM #TmpSerial
					'	
		--PRINT(@SerialSQL)							
		EXEC(@SerialSQL)
		--序列号严密管理模式
		IF @intSysMngSerial = 1
			BEGIN
				--判断序列号数量和商品的数量是否相等
				SELECT @SerialCount=COUNT(*) FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id
				IF @Qty<>@SerialCount
					BEGIN						
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行的序列号数量'+dbo.F_DecimalDisplay(@SerialCount,'qty')+'与商品数量'+dbo.F_DecimalDisplay(@Qty,'qty')+'不一致！'
						RETURN -904
					END

				-- 判断序列号位数
				IF @intSerialCount <> 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM #TmpSerial WHERE PTypeId = @PTypeId AND Id = @Id AND LEN(Serial) <> @intSerialCount)
					BEGIN
						SET @szPID='第 '+CAST(@ErrId AS varchar(50))+' 行商品存在序列号长度与设置长度 '+CAST(@intSerialCount AS varchar(50))+' 不符的情况！'
						RETURN -905
					END
				END
			END
		--循环下一个游标
		FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId,@intSerialCount
	END
--关闭并释放游标资源
CLOSE MngSerialNormal01
DEALLOCATE MngSerialNormal01

--判断拆分的序列号表中是否有序列号，如果没有序列号直接就退出了
IF NOT EXISTS(SELECT TOP 1 1 FROM #AllSerial)
	BEGIN
		--删除存储过程中的临时表
		DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
		RETURN 0		
	END

--判断是否有相同的序列号
IF EXISTS(
	SELECT	 Serial 
	FROM	#AllSerial
	GROUP BY Serial
	HAVING COUNT(*)>1
)	
BEGIN
	SET @szPID = '您在本张单据中录入了相同的序列号，单据过账失败！'
	RETURN -904
END

--从新置空错误ID的提示
SET @ErrId = 0

--校验序列号是否在库存中已经存在，如果存在，则不允许再此入库

SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.Flag = 1
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.Flag = 1 
			AND T.ID=d.ID
) a

IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在！'
		RETURN -907 --失败
	END

--判断是否采用了借欠的效验模式
IF @mngLendSerial = 1
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_LendPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_LendPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND G.State IN (17,20) 				
								AND G.Flag = 1 
								AND G.BFlag = 1
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND G.State IN (17,20) 				
					AND G.Flag = 1 
					AND G.BFlag = 1
					AND T.ID=d.ID
		) a

		IF @ErrId <> 0
			BEGIN
				SET @szPID='入库 序列号【'+CAST(@ErrSerial AS varchar(100))+'】在借欠序列号库中已存在，不能入库！'
				RETURN -907 --失败
			END
	END

--受托代销的序列号在结算之前只允许“销售退货”，“委托代销退货”入库
IF @BillType NOT IN (45,142)
	BEGIN
		
		SELECT
				@ErrId = a.nId,
				@ErrSerial = a.Serial
		FROM
		(		
			SELECT 	P.nId, T.Serial
			FROM	#AllSerial T,
					GP_CruPTypeSerial G,
					#TmpPType P,
					(
						SELECT 	MIN(T.ID) AS ID
						FROM	#AllSerial T,
								GP_CruPTypeSerial G,
								#TmpPType P
						WHERE	T.Serial = G.Serial
								AND T.PTypeId = P.PTypeId
								AND ISNULL(G.CommissionState,'')='0'
					) d
			WHERE	T.Serial = G.Serial
					AND T.PTypeId = P.PTypeId
					AND ISNULL(G.CommissionState,'')='0'
					AND T.ID=d.ID
		) a
		IF @ErrId <> 0
			BEGIN
				SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在受托代销结算之前不允许再次入库！'
				RETURN -908 --失败
			END	
	END

--委托发货的序列号不允许入库 2008-04-22 V39
IF @BillType <> 142 AND @intSysMngSerial = 1
	BEGIN
		SELECT	TOP 1
				@ErrSerial = T.Serial
		FROM	#AllSerial T,
				GP_CruPTypeSerial G
		WHERE	T.Serial = G.Serial
				AND G.State = 13 
		
		IF @@ROWCOUNT <> 0
			BEGIN
				SET @szPID='委托发货的序列号【'+CAST(@ErrSerial AS varchar(100))+'】在结算前不允许再次入库！'
				RETURN -907 --失败
			END
	END
	
	
IF @BillType =165
BEGIN
SELECT
		@ErrId = a.nId,
		@ErrSerial = a.Serial
FROM
(		
	SELECT 	P.nId, T.Serial
	FROM	#AllSerial T,
			GP_CruPTypeSerial G,
			#TmpPType P,
			(
				SELECT 	MIN(T.ID) AS ID
				FROM	#AllSerial T,
						GP_CruPTypeSerial G,
						#TmpPType P
				WHERE	T.Serial = G.Serial
						AND T.PTypeId = P.PTypeId
						AND G.Flag = 0
						AND G.State IN (35) 
			) d
	WHERE	T.Serial = G.Serial
			AND T.PTypeId = P.PTypeId
			AND G.Flag = 0
			AND G.State IN (35)
			AND T.ID=d.ID
	
) a
END
IF @ErrId <> 0
	BEGIN
		SET @szPID='序列号【'+CAST(@ErrSerial AS varchar(100))+'】在当前序列号库中已存在配送在途的状态！'
		RETURN -907 --失败
	END


--求当前序列号和序列号库的交集
INSERT INTO #UnionSerial
(
	Serial,
	PTypeId,
	State,
	CommissionState,
	ID
)
SELECT	T.Serial,
		T.PTypeId,
		G.State,
		CASE
			WHEN ISNULL(G.CommissionState,'')='' OR ISNULL(G.CommissionState,'')='1' THEN @CommissionState
			ELSE ISNULL(G.CommissionState,'')
		END AS CommissionState,
		T.ID
FROM	#AllSerial T,
		Gp_CruPTypeSerial G
WHERE	T.Serial = G.Serial 

SET @UnionCount = @@ROWCOUNT
SELECT @Qty = ISNULL(COUNT(*),0) FROM #AllSerial

--写序列号跟踪记录（如果是当前序列号库中的序列号，如果受托未被结算，则入库状态是受托代销库存中，否则未库存中）
INSERT INTO GP_InOutPTypeSerial (
	Serial,
	PTypeID,
	BillNumberID,
	InKTypeID,
	IfCheck,
	BillType,
	BTypeID1,
	BTypeID2,
	InKTypeTime,
	State,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice,
	DETAILID
)
SELECT	T.Serial,
		T.PTypeId,
		@nBillId,
		@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (165) THEN @BTypeId
			ELSE ''
		END,
		CASE 
			WHEN @BillType IN (170) THEN @BTypeId
			ELSE ''
		END,
		@BillDate,
		@InOutState,
		B.ItemID,
		B.IsCombined,
		CASE WHEN @BillType IN (165) THEN 0 ELSE   B.CargoID END,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice,
		B.Id
FROM	#AllSerial T,
		#UnionSerial U,
		#TmpPType B
WHERE	T.Serial = U.Serial 
		AND T.PTypeId = U.PTypeId
		AND T.id=B.ID
		
IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--新入库的序列号，则未为库存中
INSERT INTO GP_InOutPTypeSerial (
	Serial,
	PTypeID,
	BillNumberID,
	InKTypeID,
	IfCheck,
	BillType,
	BTypeID1,
	BTypeID2,
	InKTypeTime,
	State,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice,
	DETAILID
)
SELECT	a.Serial,
		a.PTypeId,
		@nBillId,
		@inKTypeId,
		't',
		@BillType,
		CASE
			WHEN @BillType IN (165) THEN @BTypeId
			ELSE ''
		END,
		CASE 
			WHEN @BillType IN (170) THEN @BTypeId
			ELSE ''
		END,
		@BillDate,
		@InOutState,
		B.ItemID,
		B.IsCombined,
		CASE WHEN @BillType IN (165) THEN 0 ELSE   B.CargoID END,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice	,
		B.Id	
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的出入库记录失败！'
		RETURN -901
	END

--写或者修改序列号信息
INSERT INTO Gp_CruPTypeSerial
(
	Serial,
	KTypeID,
	PTypeID,
	BTypeID1,
	BTypeID2,
	InKTypeTime,
	State,
	Flag,
	CommissionState,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	GoodsNumber,
	CostPrice
)
SELECT	a.Serial,
		@inKTypeId,
		a.PTypeId,
		CASE
			WHEN @BillType IN (165) THEN @BTypeId
			ELSE ''
		END,
		CASE 
			WHEN @BillType IN (170) THEN @BTypeId
			ELSE ''
		END,
		@BillDate,
		@State,
		@Flag,
		@CommissionState,
		B.ItemID,
		B.IsCombined,
		CASE
			WHEN @BillType IN (165) THEN 0
			ELSE B.CargoID
		END,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		B.CostPrice		
FROM	#AllSerial a,#TmpPType B
WHERE	a.id=B.Id  AND a.Serial NOT IN (SELECT Serial FROM #UnionSerial)

IF @@ERROR <> 0
	BEGIN
		SET @szPID='写序列号的入库记录失败！'
		RETURN -902
	END

--修改已经出库了的序列号的状态【InKTypeTime = @BillDate 销售退货已经在库的序列号，时间不动 V366修改】
UPDATE	Gp_CruPTypeSerial 
SET		KTypeId  = @inKTypeId,
		PTypeId  = T.PTypeId,
		BTypeID1 = 	CASE
						WHEN @BillType IN (165) THEN @BTypeId
						ELSE BTypeID1
					END,
		BTypeID2 = 	CASE 
						WHEN @BillType IN (170) THEN @BTypeId
						ELSE BTypeID2
					END,
		InKTypeTime = @BillDate,
		State = @State,
		Flag = @Flag,
		CommissionState = @CommissionState,
		GoodsNumber=p.GoodsNumber,
		CargoID=0,
		ProduceDate=p.ProduceDate,
		ValidDate=p.ValidDate,
		ItemID=p.ItemID,
		IsCombined=p.IsCombined,
		CostPrice=0

FROM	#UnionSerial T,
		Gp_CruPTypeSerial G,
		#TmpPType P,
		#AllSerial B
WHERE	T.Serial = G.Serial
		AND T.PTypeId = P.PTypeId
		AND P.IfSerial = @intSysMngSerial
		AND G.Flag = 0
		AND B.ID=P.ID
		AND B.ID=T.ID

		


IF @@ERROR <> 0
	BEGIN
		SET @szPID='修改序列号的入库记录失败！'
		RETURN -903
	END	
	
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S,
		#AllSerial A
WHERE	C.KtypeID = S.typeId
		AND C.Serial = A.Serial
		AND C.KtypeID <> '10000'	

--删除存储过程中的临时表
DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial

RETURN 0











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@nBillId	int,						--单据的Id
	@OperatorId	varchar(100),				--操作员的Id
	@szPID 		varchar(1000),				--返回信息
	@nRet		INT
	
SELECT
	@nBillId=3,
	@OperatorId	='00001'
	
BEGIN TRAN	

select ItemID,GoodsNumber,* from gp_CruPtypeSerial


	EXEC @nRet=Gp_SerialOperate_Wx_rk
		@nBillId,
		@OperatorId,
		@szPID	output

	SELECT @nRet,@szPID
	
select ItemID,GoodsNumber,cargoid,* from gp_CruPtypeSerial

select cargoid,* from gp_inoutPtypeSerial

ROLLBACK TRAN



*/





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialOperateForLend]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialOperateForLend]
GO








/*
	作者：谢吉康
	日期：2003-12-18
	描述：处理借欠的序列号

	17：借进
	18：借出
	19：借进还出
	20：借出还回
*/
CREATE PROCEDURE Gp_SerialOperateForLend
(
	@chrOperateType		int,				-- 相应单据的操作标识
	@chvSerial			varchar(50),		-- 序列号值
	@chvBillNumberID	varchar(50)	= '',	-- 单据编号
	@intBillType		int			= '',	-- 单据类型
	@chvBillDate		varchar(50)	= '',	-- 单据日期。出库记入 InKTypeTime，入库记入 OutKTypeTime
	@chvPTypeID			varchar(50)	= '',	-- 商品 ID 值
	@chvKTypeID			varchar(50)	= '',	-- 仓库 ID 值。出库记入 OutKTypeID，入库记入 InKTypeID
	@chvInKTypeID		varchar(50)	= '',	-- 调拨时的入库仓库 ID 值。记入 InKTypeID
	@chvBTypeID			varchar(50)	= '',	-- 往来单位 ID 值。出库记入 BTypeID1 ( 客户 )；入库记入 BTypeID2 ( 供货商 )
	@chvItemId			int=0,				-- 自由项
	@chvGoodsNumber		varchar(100)='',	-- 批号
	@chvIsCombined		bit=0				-- 组合
)
--@encode$--
AS		
SET NOCOUNT ON
DECLARE @mngSerial  	INT, 		--当前系统是否采用序列号严密管理	
		@intSerialExit 	BIT,		--是否有符合条件的序列号存在
		@mngLendSerial  INT,		--序列号借欠出入库校验模式
		@tmpKTypeID     VARCHAR(50),--原始仓库
		@serialRelation INT		--序列号关联货位、自由项、批次批号

SELECT @mngSerial = VALUE FROM UserConfig WHERE ConfigName = 'mngSerial'	
SELECT @mngLendSerial = VALUE FROM UserConfig WHERE ConfigName = 'mngLendSerial'
SELECT @serialRelation = VALUE FROM UserConfig WHERE ConfigName = 'serialRelation'

IF @serialRelation = 0
BEGIN
	SET @chvGoodsNumber = ''
	SET @chvItemId = 0
	SET @chvIsCombined = 0
END
--*********************************************************************************************************【借进】*********************************************************************************************************
IF @chrOperateType = 17		
	BEGIN
		IF @mngLendSerial = 1
			BEGIN
				SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @chvSerial AND Flag = 1

				IF @@ROWCOUNT <> 0 
				BEGIN
					RETURN -100 --失败
				END
					
				IF	EXISTS(SELECT TOP 1 1 FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND State=17)
				BEGIN
					RETURN -100
				END
			END
        --配送单35状态不能借进入库
        SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @chvSerial AND Flag = 0 AND State=35
        IF @@ROWCOUNT <> 0 
				BEGIN
					RETURN -101 --失败
				END
		SELECT * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial	AND Flag = 1 AND BFlag = 1  AND State <> 34 -- 检查该序列号是否存在于借欠序列号库存状况表中，Flag 为 1 ( 库存中 )
		
		IF @@ROWCOUNT <> 0 --借欠序列号库中有此序列号
			RETURN -1 --失败
		DELETE GP_LendPTypeSerial WHERE Serial = @chvSerial	AND Flag = 1 AND BFlag = 1  AND State <> 34
		-- 写入序列号出入库明细表
		INSERT INTO GP_InOutPTypeSerial (
			Serial,
			PTypeID,
			BillNumberID,
			InKTypeID,
			IfCheck,
			BillType,
			BTypeID2,	-- 客户
			InKTypeTime,
			STATE,
			GoodsNumber,
			ItemID ,
			IsCombined
		)
		VALUES (
			@chvSerial,
			@chvPTypeID,
			@chvBillNumberID,
			@chvKTypeID,
			't',
			@intBillType,
			@chvBTypeID,
			@chvBillDate,
			17		-- 库存中
			,@chvGoodsNumber
			,@chvItemId
			,@chvIsCombined
		)

		IF @@ROWCOUNT = 0
			RETURN -2	-- 失败

		IF EXISTS(SELECT TOP 1 * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial)	--有状态不在库的当前序列号,更新序列号
			BEGIN
				UPDATE 	GP_LendPTypeSerial
				SET 	State = 17,
						Flag  = 1,
						BFlag = 1,
						PTypeId = @chvPTypeID,
						KTypeID = @chvKTypeID,
						InKTypeTime = @chvBillDate,
						BTypeID2 = @chvBTypeID,
						OutKTypeTime = NULL,
						ItemID = @chvItemId,
					    GoodsNumber = @chvGoodsNumber,
					    IsCombined = @chvIsCombined
				WHERE 	Serial = @chvSerial

				IF @@ROWCOUNT = 0 
					RETURN -3	-- 失败
			END
		ELSE				--序列号不在库中，写入序列号信息
			BEGIN
				INSERT INTO GP_LendPTypeSerial
				(
					Serial,
					KTypeID,
					PTypeID,
					BTypeID2,	--客户
					InKTypeTime,
					State,
					Flag,
					BFlag,
					GoodsNumber,
					ItemID ,
					IsCombined
				)
				VALUES
				(
					@chvSerial,
					@chvKTypeID,
					@chvPTypeID,
					@chvBTypeID,
					@chvBillDate,
					17,
					1,
					1
					,@chvGoodsNumber
					,@chvItemId
					,@chvIsCombined
				)
			
				IF @@ROWCOUNT = 0 
					RETURN -4
			END
	END

--*********************************************************************************************************【借出】*********************************************************************************************************
IF @chrOperateType = 18	
	BEGIN
		IF @mngSerial = 1
		BEGIN
			--有借出还回，但是正常库中有非借进的数据，可能是销售 
			IF EXISTS(SELECT TOP 1 1 FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND State =20)	 
			BEGIN
					IF EXISTS (SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @chvSerial )
					AND NOT EXISTS(SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND State IN (1,7))
					BEGIN
							RETURN -5
					END
			END
			--严密管理就必须应该是在库序列号,才能借出;以前是判断的序列号是如果序列号没借出,才判断是否在库 BUG 1742 981
			IF NOT EXISTS(SELECT TOP 1 1 FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND State in (17,20))
			BEGIN	
					IF NOT EXISTS(SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND State IN (1,7))
					BEGIN
							RETURN -5
					END
			END
			
			IF	EXISTS(SELECT TOP 1 1 FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND State=18)
			BEGIN
				RETURN -1
			END
			
		END
		--9.6.1 借出开单、非严密序列号，录入不存在序列号，允许过账
		IF @mngSerial=1 AND NOT EXISTS(SELECT TOP 1 1 FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND PtypeID = @chvPTypeID )
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND State IN (1,7) AND PtypeID = @chvPTypeID )
				RETURN -4
		END
		
		IF @serialRelation = 1		
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 1 FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND PtypeID = @chvPTypeID AND ItemID = @chvItemId AND GoodsNumber = @chvGoodsNumber)
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND State IN (1,7) AND PtypeID = @chvPTypeID AND ItemID = @chvItemId AND GoodsNumber = @chvGoodsNumber)
					RETURN -4
			END
		END	
		
		--9.6.1 借出开单、非严密序列号，录入不存在序列号，允许过账
		IF @mngSerial=1 AND NOT EXISTS(SELECT TOP 1 1  FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND KtypeID = @chvKTypeID)
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 1 FROM GP_CruPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND KtypeID = @chvKTypeID)
			BEGIN
				RETURN -88	
			END
		END
		
		SELECT TOP 1 1 FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 0
			
		IF @@ROWCOUNT <> 0 --序列号已经借出
			RETURN -1	
		ELSE
			BEGIN		   -- 写入序列号出入库明细表
				INSERT INTO GP_InOutPTypeSerial (
					Serial,
					PTypeID,
					BillNumberID,
					OutKTyeID,
					IfCheck,
					BillType,
					BTypeID1,	-- 客户
					OutKTypeTime,
					State,
					GoodsNumber,
					ItemID ,
					IsCombined
				)
				VALUES (
					@chvSerial,
					@chvPTypeID,
					@chvBillNumberID,
					@chvKTypeID,
					't',
					@intBillType,
					@chvBTypeID,
					@chvBillDate,
					18		-- 已借出
					,@chvGoodsNumber
					,@chvItemId
					,@chvIsCombined
				)

				IF @@ROWCOUNT = 0
					RETURN -2	-- 失败

				IF EXISTS(SELECT TOP 1 * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial) --修改记录
					BEGIN
						UPDATE	GP_LendPTypeSerial
						SET 	State = 18,
								Flag = 0,
								PTypeID = @chvPTypeID,
								BTypeID1 = @chvBTypeID,
								KTypeID = @chvKTypeID,
								OutKTypeTime = @chvBillDate,
								ItemID = @chvItemId,
								GoodsNumber = @chvGoodsNumber,
								IsCombined = @chvIsCombined
						WHERE 	Serial = @chvSerial			
					
						IF @@ROWCOUNT = 0
							RETURN -3
					END							
				ELSE				--写入借欠数据库
					BEGIN
						INSERT INTO GP_LendPTypeSerial
						(
							Serial,
							KTypeID,
							PTypeID,
							BTypeID1,	--供货商
							OutKTypeTime,
							State,
							Flag,
							GoodsNumber,
							ItemID ,
							IsCombined
						)
						VALUES
						(
							@chvSerial,
							@chvKTypeID,
							@chvPTypeID,
							@chvBTypeID,
							@chvBillDate,
							18,
							0,
							@chvGoodsNumber
							,@chvItemId
							,@chvIsCombined
						)
					
						IF @@ROWCOUNT = 0 
							RETURN -4
					END
			END
	END

--*********************************************************************************************************【借进还出】*********************************************************************************************************
IF @chrOperateType = 19 
	BEGIN
		SELECT * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND BFlag = 1 AND State IN (17,20) -- 17 借进 20 借出还回

		IF @@ROWCOUNT = 0 
			RETURN -1

		IF NOT EXISTS(SELECT TOP 1 * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND BTypeID2 = @chvBTypeID AND PTypeID = @chvPTypeID) 
			RETURN -4
		IF @serialRelation = 1		
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND BTypeID2 = @chvBTypeID AND PTypeID = @chvPTypeID AND ItemID = @chvItemId AND GoodsNumber = @chvGoodsNumber) 
				RETURN -4
		END
		
		IF NOT EXISTS(SELECT TOP 1 1  FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 1 AND KtypeID = @chvKTypeID)
		BEGIN
			RETURN -88	
		END
	
		-- 写入序列号出入库明细表
		INSERT INTO GP_InOutPTypeSerial (
			Serial,
			PTypeID,
			BillNumberID,
			OutKTyeID,
			IfCheck,
			BillType,
			BTypeID2,	-- 供货商
			OutKTypeTime,
			State,
			GoodsNumber,
			ItemID ,
			IsCombined
		)
		VALUES (
			@chvSerial,
			@chvPTypeID,
			@chvBillNumberID,
			@chvKTypeID,
			't',
			@intBillType,
			@chvBTypeID,
			@chvBillDate,
			19		-- 已出库
			,@chvGoodsNumber
			,@chvItemId
			,@chvIsCombined
		)

		-- 操作返回值
		IF @@ROWCOUNT = 0
			RETURN -2	-- 失败

		IF EXISTS(SELECT TOP 1 * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial)	--序列号存在，修改记录
			BEGIN
				UPDATE	GP_LendPTypeSerial
				SET 	State = 19,
						Flag  = 0,
						PTypeID = @chvPTypeID,
						BTypeID2 = @chvBTypeID,
						OutKTypeTime = @chvBillDate,
						ItemID = @chvItemId,
					    GoodsNumber = @chvGoodsNumber,
					    IsCombined = @chvIsCombined
				WHERE 	Serial = @chvSerial
			
				IF @@ROWCOUNT = 0 
					RETURN -3
			END
		ELSE
			RETURN -4
	END

--*********************************************************************************************************【借出还回】*********************************************************************************************************
IF @chrOperateType = 20
	BEGIN
		SELECT * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 0 AND State=18 --18借出
		
		IF @@ROWCOUNT = 0	--序列号没有借出记录
			RETURN -1 --失败

		IF NOT EXISTS(SELECT TOP 1 * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND PTypeID = @chvPTypeID AND BTypeID1 = @chvBTypeID )
			RETURN -4
			
		IF @serialRelation = 1		
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND PTypeID = @chvPTypeID AND BTypeID1 = @chvBTypeID AND ItemID = @chvItemId AND GoodsNumber = @chvGoodsNumber)
			RETURN -4
		END
		
		IF NOT EXISTS(SELECT TOP 1 1  FROM GP_LendPTypeSerial WHERE Serial = @chvSerial AND Flag = 0 AND KtypeID = @chvKTypeID)
		BEGIN
			RETURN -88	
		END
		
		-- 写入序列号出入库明细表
		INSERT INTO GP_InOutPTypeSerial (
			Serial,
			PTypeID,
			BillNumberID,
			InKTypeID,
			IfCheck,
			BillType,
			BTypeID1,	--客户
			InKTypeTime,
			State,
			GoodsNumber,
			ItemID ,
			IsCombined
		)
		VALUES (
			@chvSerial,
			@chvPTypeID,
			@chvBillNumberID,
			@chvKTypeID,
			't',
			@intBillType,
			@chvBTypeID,
			@chvBillDate,
			20		-- 已出库
			,@chvGoodsNumber
			,@chvItemId
			,@chvIsCombined
		)

		IF @@ROWCOUNT = 0
			RETURN -2	-- 失败

		IF EXISTS(SELECT TOP 1 * FROM GP_LendPTypeSerial WHERE Serial = @chvSerial)	--修改序列号信息
			BEGIN
				UPDATE	GP_LendPTypeSerial 
				SET 	State = 20,
						Flag  = 1,
						PTypeID = @chvPTypeID,
						KTypeID = @chvKTypeID,
						BTypeID1 = @chvBTypeID,
						InKTypeTime = @chvBillDate,
						ItemID = @chvItemId,
					    GoodsNumber = @chvGoodsNumber,
					    IsCombined = @chvIsCombined
														
				WHERE 	Serial = @chvSerial

				IF @@ROWCOUNT = 0
					RETURN -3
			END
		ELSE
			RETURN -4					
	END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_SerialOperateForLendDT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].Gp_SerialOperateForLendDT
GO

/*
	作者：周华
	时间：2012-05-11 09:45:33.390
	描述：处理借欠所有单据的序列号dt版
*/
CREATE PROCEDURE Gp_SerialOperateForLendDT
(
	@opType INT
	,@billNumberId INT
	,@billType INT
	,@billDate DATETIME
	,@kTypeId INT
	,@bTypeId INT
	,@tb TbType_SerialNo READONLY
)
--@encode$--	
AS
BEGIN
	DECLARE @mngSerial INT -- 当前系统是否采用序列号严密管理
			,@mngLendSerial INT;-- 序列号借欠出入库校验模式
	DECLARE @rn INT
			,@sn VARCHAR(50);
			
	SELECT @mngSerial=value FROM UserConfig WHERE ConfigName='mngSerial'
	
	IF @opType=17  -- 借进 --
	BEGIN 
		-- 判断是否是新序列号，就是库存中不能存在
		SELECT TOP 1 @rn=b.rn,@sn=b.sn FROM GP_CruPTypeSerial a JOIN @tb b ON a.Serial=b.sn WHERE a.Flag=1 AND @mngLendSerial=1 ORDER BY b.rn;
		IF @rn IS NOT NULL AND @sn IS NOT NULL 
		BEGIN
			SELECT '第【'+CAST(@rn AS VARCHAR(10))+'】行 序列号【'+CAST(@sn AS VARCHAR(50))+'】已经存在，不能入库';
			RETURN;
		END
		
		SELECT TOP 1 @rn=b.rn,@sn=b.sn FROM GP_LendPTypeSerial a JOIN @tb b ON a.Serial=b.sn WHERE a.Flag=1 AND BFlag=1 ORDER BY b.rn;
		IF @rn IS NOT NULL AND @sn IS NOT NULL 
		BEGIN
			SELECT '第【'+CAST(@rn AS VARCHAR(10))+'】行 序列号【'+CAST(@sn AS VARCHAR(50))+'】有误，请确认后重试';
			RETURN;
		END
		-- 写入 --
		INSERT INTO GP_InOutPTypeSerial(
			Serial,
			PTypeID,
			BillNumberID,
			InKTypeID,
			IfCheck,
			BillType,
			BTypeID2,	-- 客户
			InKTypeTime,
			[State]
		) SELECT sn,pTypeId,@billNumberId,@kTypeId,'t',@billType,@bTypeId,@billDate,17 FROM @tb;
		
		-- 有状态不在库的当前序列号,更新序列号
		UPDATE a SET
		[State]=17
		,Flag=1
		,BFlag=1
		,PTypeId=b.pTypeId
		,KTypeId=@kTypeId
		,InKTypeTime=@billDate
		,BTypeID2=@bTypeId
		,OutKTypeTime=NULL
		FROM GP_LendPTypeSerial a JOIN @tb b ON A.Serial=b.sn 
		
		-- 序列号不在库中，写入序列号信息
		INSERT INTO GP_LendPTypeSerial(
			Serial,
			KTypeID,
			PTypeID,
			BTypeID2,	--客户
			InKTypeTime,
			[State],
			Flag,
			BFlag
		) SELECT sn,@kTypeId,pTypeId,@bTypeId,@billDate,17,1,1 FROM @tb;
		
	END
	ELSE IF @opType=18 -- 借出 --
	BEGIN 
		-- 判断是否是库存中的，是否已经借出了
		IF @mngSerial=1
			AND NOT EXISTS(SELECT * FROM GP_LendPTypeSerial a JOIN @tb b on a.Serial=b.sn AND a.Flag=1)
			AND NOT EXISTS(SELECT * FROM GP_CruPTypeSerial a JOIN @tb b ON a.Serial=b.sn AND a.Flag=1 AND a.[state] IN (1,7))
		BEGIN
			SELECT '序列号不存在存库中，请确认后重试';
			RETURN;
		END
		
		
		SELECT TOP 1 @rn=b.rn,@sn=b.sn FROM GP_LendPTypeSerial a JOIN @tb b ON a.Serial=b.sn WHERE a.Flag=0 ORDER BY b.rn;
		IF @rn IS NOT NULL AND @sn IS NOT NULL 
		BEGIN 
			SELECT '第【'+CAST(@rn AS VARCHAR(10))+'】行 序列号【'+CAST(@sn AS VARCHAR(50))+'】已经借出，请确认后重试';
			RETURN;
		END
		
		INSERT INTO GP_InOutPTypeSerial(
				Serial,
				PTypeID,
				BillNumberID,
				OutKTyeID,
				IfCheck,
				BillType,
				BTypeID1,	-- 客户
				OutKTypeTime,
				[State]
		) SELECT a.sn,a.pTypeId,@billNumberId,@kTypeId,'t',@billType,@btypeId,@billDate,18
		FROM @tb a JOIN GP_LendPTypeSerial b ON a.sn=b.serial WHERE b.Flag<>0
		
		UPDATE a SET [State] = 18
		,Flag = 0
		,pTypeId=b.pTypeId
		,bTypeId1=@bTypeId
		,kTypeId=@kTypeId
		,OutKTypeTime=@billDate
		FROM GP_LendPTypeSerial a JOIN @tb b ON a.serial=b.sn
		INSERT INTO GP_LendPTypeSerial(
				Serial,
				KTypeID,
				PTypeID,
				BTypeID1,	--供货商
				OutKTypeTime,
				[State],
				Flag
		) SELECT sn,@kTypeId,pTypeId,@bTypeId,@billDate,18,0 FROM @tb;
	END
	ELSE IF @opType=19 -- 借进还出 --
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM GP_LendPTypeSerial a JOIN @tb b ON a.Serial=b.sn WHERE Flag=1 AND BFlag=1)
		BEGIN
			SELECT '不存在记录，请确认后重试';
			RETURN ;
		END
		
		IF NOT EXISTS(SELECT 1 FROM GP_LendPTypeSerial a JOIN @tb b ON a.Serial=b.sn AND a.pTypeId=b.pTypeId WHERE bTypeId2=@btypeId )
		BEGIN
			SELECT '不存在借进的记录，请确认后重试';
			RETURN ;
		END
		
		INSERT INTO GP_InOutPTypeSerial(
			Serial,
			PTypeID,
			BillNumberID,
			OutKTyeID,
			IfCheck,
			BillType,
			BTypeID2,	-- 供货商
			OutKTypeTime,
			[State]
		) SELECT sn,pTypeId,@billNumberId,@kTypeId,'t',@billType,@btypeId,@billDate,19 FROM @tb;
		
		UPDATE a SET [state]=19
		,Flag=0
		,pTypeId=b.pTypeId
		,bTypeId2=@bTypeId
		,OutKTypeTime=@billDate
		FROM GP_LendPTypeSerial a JOIN @tb b ON a.serial=b.sn;
		
	END
	ELSE IF @opType=20 -- 借出还进 --
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM GP_LendPTypeSerial a JOIN @tb b ON a.serial=b.sn WHERE a.Flag=0)
		BEGIN
			SELECT '不存在记录，请确认后重试';
			RETURN ;
		END
		
		IF NOT EXISTS(SELECT 1 FROM GP_LendPTypeSerial a JOIN @tb b ON a.Serial=b.sn AND a.pTypeId=b.pTypeId WHERE bTypeId1=@btypeId )
		BEGIN
			SELECT '不存在借出的记录，请确认后重试'
			RETURN ;
		END
		
		INSERT INTO GP_InOutPTypeSerial(
			Serial,
			PTypeID,
			BillNumberID,
			InKTypeID,
			IfCheck,
			BillType,
			BTypeID1,	--客户
			InKTypeTime,
			[State]
		) SELECT sn,pTypeId,@billNumberId,@ktypeId,'t',@billType,@bTypeId,@billDate,20 FROM @tb;
		
		UPDATE a SET [State]=20
		,Flag=1
		,pTypeId=b.pTypeId
		,kTypeId=@kTypeId
		,bTypeId1=@bTypeId
		,InKTypeTime=@billDate
		FROM GP_LendPTypeSerial a JOIN @tb b ON a.Serial=b.sn;
	END
	
	SELECT ''; --成功
END
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialRedWord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialRedWord]
GO


/*
	作者：谢吉康
	时间：2003-12-3 
	原因：重写序列号红冲的算法
	
	修改:冯波  
*/
CREATE  PROCEDURE Gp_SerialRedWord
(
	@BillNumberId	varchar(50),	-- 单据编号
	@intBillType	int				-- 单据类型
)
--@encode$--
AS
SET NOCOUNT ON	
DECLARE @DelID			int,			--需要删除的单据的过帐ID   BillIndex->ID
		@laterSerial	varchar(100),	--Gp_InOutPTypeSerial中的序列号
		@returnValue 	INT			,
		@mngLendSerial	VARCHAR(10),	--系统采用序列号借欠出入库校验模式
		@preKTypeId		VARCHAR(50),	--上张单据的仓库
		@cruKTypeId		VARCHAR(50),	--当前前单据中序列号仓库
		@cruSTypeId		VARCHAR(50),	--当前单据的分支机构
		@cruState		VARCHAR(10),	--当前单据中序列号状态
		@nowState		VARCHAR(10),	--序列号库存中的状态
		@nowKtypeId		VARCHAR(50),	--序列号库存中的仓库
		@nowSTypeId		VARCHAR(50),		--序列号库存中的分支机构
		@lastKTypeId      VARCHAR(50) , --上一个在库仓库
		@lastSTypeId      VARCHAR(50)  --上一个在库分支机构
		
SET @returnValue = 0
SELECT @mngLendSerial = Value FROM dbo.Userconfig WHERE ConfigName= 'mngLendSerial'

--获取需要删除的单据的过帐Id
----SELECT @DelID = [ID] FROM Gp_InOutPTypeSerial WHERE BillNumberID = @BillNumberID AND 

--循环用游标来判断是否存在后续的单据
DECLARE LaterSerial CURSOR FOR
	SELECT	Serial 
	FROM	Gp_InOutPTypeSerial 
	WHERE	BillNumberId = @BillNumberId 
			AND BillType=@intBillType
			AND BillType NOT IN (71,72,88)

OPEN LaterSerial

FETCH NEXT FROM LaterSerial INTO @laterSerial
WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT	TOP 1 
				@DelID = [ID],
				@cruState = [state],
				@cruKTypeId = CASE WHEN [state] IN (1,7) THEN InKtypeID ELSE OutKtyeID END
		FROM	Gp_InOutPTypeSerial 
		WHERE	BillNumberID = @BillNumberID  
				AND BillType =  @intBillType 
				AND Serial = @laterSerial
	
		--普通物流单据
		IF EXISTS(
			SELECT	Bil.BillNumberId
			FROM	BillIndex Bil,
					Gp_InOutPTypeSerial G
			WHERE	Bil.BillNumberId = G.BillNumberId
					AND Bil.IfCheck = 't'
					AND Bil.RedWord = 0
					AND G.Serial = @laterSerial
					AND g.Id>@DelId
					AND G.BillType NOT IN (71,72,88,203,327,328,329)
		)
		BEGIN
			CLOSE LaterSerial
			DEALLOCATE LaterSerial
			RETURN -11
		END
		
		--门店配送类单据
		IF EXISTS(
			SELECT	Bil.BillNumberId
			FROM	dbo.PosAllotApplyBillIndex Bil,
					Gp_InOutPTypeSerial G
			WHERE	Bil.BillNumberId = G.BillNumberId
					AND Bil.IfCheck = 't'
					AND Bil.RedWord = 0
					AND G.Serial = @laterSerial
					AND g.Id>@DelId
					AND G.BillType NOT IN (71,72,88,203)and bil.billtype = g.billtype 				
		)
		BEGIN
			CLOSE LaterSerial
			DEALLOCATE LaterSerial
			RETURN -11
		END		
		
		IF  @mngLendSerial = '1'
		BEGIN
			IF EXISTS(
				SELECT	Bil.BillNumberId
				FROM    LendIndex Bil,
						Gp_InOutPTypeSerial G
				WHERE	Bil.BillNumberId = G.BillNumberId
						AND Bil.IfCheck = 't'
						AND Bil.RedWord = 0
						AND G.Serial = @laterSerial
						AND g.Id>@DelId
						AND G.BillType = 87
			)
			BEGIN
				--PRINT @laterSerial
				--RAISERROR('有后续的单据存在，不允许红冲！',16,1)
				CLOSE LaterSerial
				DEALLOCATE LaterSerial
				RETURN -11
			END
		END
		
		--判断序列号是否做过序列号调整单
		IF EXISTS(SELECT TOP 1 1 FROM SerialAdjustBill s,SerialAdjustIndex i WHERE  I.BillNumberId=S.BillNumberId AND I.draft=0	 AND s.OldSerial= 'я'+@laterSerial+'я' )
		BEGIN
			--做过序列号调整单，不允许红冲
			CLOSE LaterSerial
			DEALLOCATE LaterSerial
			RETURN -13
		END
		
		FETCH NEXT FROM LaterSerial INTO @laterSerial
	END

CLOSE LaterSerial
DEALLOCATE LaterSerial

--必须特殊处理调拨、拆装单、销售换货单、采购换货单、维修单、上门维修单、维修品调入单、维修品调出单、维修品调拨单
--积分兑换单、分支机构调拨出库单、分支机构调拨入库单
IF @intBillType IN (17,21,16,160,161,166,172,173,174,175)
	EXEC @returnValue = Gp_SerialRedWord_dGrid @BillNumberId,@intBillType
ELSE
	EXEC @returnValue = Gp_SerialRedWord_sGrid @BillNumberId,@intBillType
	
	
IF EXISTS(
	SELECT Serial
	FROM gp_CruPtypeSerial
	WHERE State IN (1,7) AND (OutKTypeTime IS NOT NULL OR BTypeID1<>'')
	AND Serial IN
	(
		SELECT Serial
		FROM gp_inoutPtypeSerial
		WHERE BillNumberid=@BillNumberId
	) 
)
BEGIN
	UPDATE gp_CruPtypeSerial
	SET OutKTypeTime=NULL,BTypeID1=''
	WHERE State IN (1,7) AND (OutKTypeTime IS NOT NULL OR BTypeID1<>'')
	AND Serial IN
	(
		SELECT Serial
		FROM gp_inoutPtypeSerial
		WHERE BillNumberid=@BillNumberId
	)
END
ELSE IF EXISTS(
	SELECT Serial
	FROM gp_CruPtypeSerial
	WHERE State IN (13)  ----委托代销结算单
	AND Serial IN
	(
		SELECT Serial
		FROM gp_inoutPtypeSerial
		WHERE BillNumberid=@BillNumberId
	) 
)
BEGIN
	UPDATE gp_CruPtypeSerial
	SET OutKTypeTime=NULL
	WHERE State IN (13)
	AND Serial IN
	(
		SELECT Serial
		FROM gp_inoutPtypeSerial
		WHERE BillNumberid=@BillNumberId
	)
END

RETURN @returnValue



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@BillNumberId	varchar(50),	-- 单据编号
	@intBillType	int,			-- 单据类型
	@nRet			INT

SELECT
	@BillNumberId=49,
	@intBillType=145


BEGIN TRAN
EXEC @nRet=Gp_SerialRedWord
	@BillNumberId,
	@intBillType
	
SELECT @nRet	

ROLLBACK TRAN
*/



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
/*
*		门点配送单据库存序列号红冲
*/
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_SerialRedWord_Delivery',N'P'))
BEGIN
	DROP PROC GP_SerialRedWord_Delivery
END
GO

CREATE PROC GP_SerialRedWord_Delivery
(
	@BillNumberId	varchar(50),	-- 单据编号
	@intBillType	int				-- 单据类型
)
--@encode$--
AS
SET NOCOUNT ON	
DECLARE 
		@Serial		varchar(100),			--单个的序列号
		@PTypeId			varchar(100),	--商品的Id
		@inKTypeId			varchar(100),	--入库仓库的Id
		@outKTypeId			varchar(100),	--出库仓库的Id
		@inKTypeTime		datetime,		--入库时间
		@OutKTypeTime		datetime,		--出库时间
		@State				int,			--序列号的状态
		@Flag				int,			--判断是否在库
		@BillType			int,			--单据类型
		@recBillNumberId 	int,			 --最近的Id
		@ID					NUMERIC(10,0),
		@GoodsOrder			INT,			--批次
		@GoodsNumber		VARCHAR(100),	--批号
		@CargoID			INT,
		@ValidDate			VARCHAR(50),
		@ProduceDate		VARCHAR(50),
		@ItemID				INT,
		@IsCombined			INT,
		@LendState          INT,
		@AfterBillNumberID  INT,				--本单之后的单据编号
		@OldSerial			VARCHAR(50),
		@NowState			TINYINT

SET @recBillNumberId = 0

--循环处理序列号
DECLARE SerialCursor CURSOR FOR
	SELECT Serial FROM Gp_InOutPTypeSerial WHERE BillNumberId = @BillNumberId AND BillType = @intBillType
OPEN SerialCursor

FETCH NEXT FROM SerialCursor INTO @Serial

WHILE @@FETCH_STATUS = 0	
BEGIN
		SET @recBillNumberId = 0
		--查询红冲前的最近一张单据
		SELECT TOP 1 @ID=MIN(ID) FROM gp_inoutPtypeSerial WHERE Serial=@Serial and BillNumberid=@BillNumberID
		SELECT @OldSerial = dbo.F_GetOldSerial(@Serial,@ID) 
		IF ISNULL(@OldSerial,'')='' SET @OldSerial=@Serial
		
		--主表分支判断
		IF EXISTS(
					SELECT TOP 1 1							
					FROM	gp_inoutPtypeSerial a,
							dbo.PosAllotApplyBillIndex Bil 
					WHERE	a.BillNumberid=bil.BillNumberId
							AND a.ID<@ID
							AND A.Serial = @Serial
							AND Bil.RedWord =0 
							AND Bil.IfCheck = 't' 
					ORDER BY a.ID DESC
		)
		BEGIN
			SELECT TOP 1 
					@recBillNumberId = ISNULL(a.BillNumberId,0),
					@BillType = a.BillType
			FROM	gp_inoutPtypeSerial a,
					dbo.PosAllotApplyBillIndex Bil 
			WHERE	a.BillNumberid=bil.BillNumberId
					AND a.ID<@ID
					AND A.Serial = @Serial
					AND Bil.RedWord =0 
					AND Bil.IfCheck = 't' 
			ORDER BY a.ID DESC		
		END	
		ELSE
		BEGIN
			SELECT TOP 1 
					@recBillNumberId = ISNULL(a.BillNumberId,0),
					@BillType = a.BillType
			FROM	gp_inoutPtypeSerial a,
					dbo.BillIndex Bil 
			WHERE	a.BillNumberid=bil.BillNumberId
					AND a.ID<@ID
					AND A.Serial = @Serial
					AND Bil.RedWord =0 
					AND Bil.IfCheck = 't' 
			ORDER BY a.ID DESC			
		END				
	    
	    --之后的单据
	    SELECT  TOP 1 
				@AfterBillNumberID = ISNULL(a.BillNumberId,0),
				@BillType = a.BillType
		FROM	gp_inoutPtypeSerial a
		WHERE	a.BillNumberid=a.BillNumberId
				AND a.ID>@ID
				AND A.Serial = @Serial				
		ORDER BY a.ID DESC
						
		--序列号被之后单据引用
		IF @AfterBillNumberID<>0
		BEGIN
			RETURN -11
		END
		
		IF @recBillNumberId = 0	--之前没有单据了，判断是否有期初序列号了
		BEGIN	
			SELECT 	TOP 1 
					@PTypeId = PTypeId,
					@inKTypeId	= KTypeId,
					@State = State,
					@Flag = Flag,
					@GoodsOrder = GoodsOrder,
					@GoodsNumber = GoodsNumber,
					@CargoID=CargoID,
					@ValidDate	=ValidDate,
					@ProduceDate=ProduceDate,
					@ItemID		=ItemID,
					@IsCombined	=IsCombined
			FROM 	dbo.Gp_initPTypeSerial 
			WHERE 	Serial = @Serial

			--如果有期初序列号
			IF @@ROWCOUNT <> 0
			BEGIN
				UPDATE	Gp_CruPTypeSerial
				SET		KTypeId	= @inKTypeId,
						PTypeId = @PTypeId,
						State	= @State,
						Flag	= @Flag,
						GoodsOrder = @GoodsOrder,
						GoodsNumber = @GoodsNumber,
						CargoID=@CargoID,
						ValidDate	=@ValidDate,
						ProduceDate=@ProduceDate,
						ItemID		=@ItemID,
						IsCombined	=@IsCombined						
				WHERE	Serial  = @Serial
				
				IF @@ROWCOUNT = 0
					RETURN -901
			END
			ELSE
			BEGIN
				DELETE FROM Gp_CruPTypeSerial WHERE Serial = @Serial
				IF @@ROWCOUNT = 0
					RETURN -900
			END
		END				
		ELSE		
		/**********如果红冲门店验收，单据最近的一张单据是门店配送单 退回到配送在途状态**********************/
		BEGIN							
		IF @BillType=329
		BEGIN
			SELECT 	TOP 1 
					@PTypeId = PTypeId,
					@inKTypeId	= inKTypeId,
					@outKTypeId = outKTyeId,
					@State = State,
					@GoodsOrder = GoodsOrder,
					@GoodsNumber = GoodsNumber,
					@CargoID=CargoID,
					@ValidDate	=ValidDate,
					@ProduceDate=ProduceDate,
					@ItemID		=ItemID,
					@IsCombined	=IsCombined
					
			FROM 	Gp_InOutPTypeSerial 
			WHERE 	Serial = @Serial 
					AND BillNumberId = @recBillNumberId 
					AND State=35
			
			IF @@ROWCOUNT <> 0
			BEGIN
				UPDATE	Gp_CruPTypeSerial
				SET		PTypeId = @PTypeId,
						KTypeId = @inKTypeId,
						State	= @State,
						Flag	= 1,
						GoodsOrder	= @GoodsOrder,
						GoodsNumber = @GoodsNumber,
						CargoID=@CargoID,
						ValidDate	=@ValidDate,
						ProduceDate=@ProduceDate,
						ItemID		=@ItemID,
						IsCombined	=@IsCombined
						
				WHERE	Serial  = @Serial
				
				IF @@ROWCOUNT = 0
					RETURN -901
			END
		END
		/********红冲门店退货，最近的单据是门店配送单，*********/
		ELSE IF @BillType=328
		BEGIN
				SELECT 	TOP 1 
					@PTypeId = PTypeId,
					@inKTypeId	= inKTypeId,
					@outKTypeId = outKTyeId,
					@State = State,
					@GoodsOrder = GoodsOrder,
					@GoodsNumber = GoodsNumber,
					@CargoID=CargoID,
					@ValidDate	=ValidDate,
					@ProduceDate=ProduceDate,
					@ItemID		=ItemID,
					@IsCombined	=IsCombined
					
			FROM 	Gp_InOutPTypeSerial 
			WHERE 	Serial = @Serial 
					AND BillNumberId = @recBillNumberId 
					AND State=35
			
			IF @@ROWCOUNT <> 0
			BEGIN
				UPDATE	Gp_CruPTypeSerial
				SET		PTypeId = @PTypeId,
						KTypeId = @inKTypeId,
						State	= @State,
						Flag	= 0,
						GoodsOrder	= @GoodsOrder,
						GoodsNumber = @GoodsNumber,
						CargoID=@CargoID,
						ValidDate	=@ValidDate,
						ProduceDate=@ProduceDate,
						ItemID		=@ItemID,
						IsCombined	=@IsCombined
						
				WHERE	Serial  = @Serial
				
			IF @@ROWCOUNT = 0
				RETURN -901
			END
		END
		/********红冲门店配送单，最近的单据是入库单，做入库处理*********/
		ELSE IF @BillType=327
		PRINT 1
		BEGIN
			SELECT 	TOP 1 
				@PTypeId = PTypeId,
				@inKTypeId	= inKTypeId,
				@outKTypeId = outKTyeId,
				@State = State,
				@GoodsOrder = GoodsOrder,
				@GoodsNumber = GoodsNumber,
				@CargoID=CargoID,
				@ValidDate	=ValidDate,
				@ProduceDate=ProduceDate,
				@ItemID		=ItemID,
				@IsCombined	=IsCombined
				
			FROM 	Gp_InOutPTypeSerial 
			WHERE 	Serial = @Serial 
					AND BillNumberId = @recBillNumberId 
					AND State=1		
			IF @@ROWCOUNT <> 0
			BEGIN
				UPDATE	Gp_CruPTypeSerial
				SET		PTypeId = @PTypeId,
						KTypeId = @inKTypeId,
						State	= @State,
						Flag	= 1,
						GoodsOrder	= @GoodsOrder,
						GoodsNumber = @GoodsNumber,
						CargoID=@CargoID,
						ValidDate	=@ValidDate,
						ProduceDate=@ProduceDate,
						ItemID		=@ItemID,
						IsCombined	=@IsCombined
						
				WHERE	Serial  = @Serial
				
				IF @@ROWCOUNT = 0
					RETURN -901
			END
		END
	END	
	FETCH NEXT FROM SerialCursor INTO @Serial
END	

CLOSE SerialCursor
DEALLOCATE SerialCursor

--重算当前序列号库中的STypeId
--性能优化：以前没加条件判断，是更新所有库存序列号，容易造成死锁
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S
WHERE	C.KtypeID = S.typeId		
		AND C.KtypeID <> '10000'
		AND EXISTS
		(
			SELECT a.Serial 
			FROM Gp_InOutPTypeSerial a
			WHERE a.BillNumberId = @BillNumberId
			AND a.Serial=c.Serial
		)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialRedWord_dGrid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialRedWord_dGrid]
GO



/*
	作者：谢吉康
	时间：2009-12-29 
	原因：重写序列号红冲的算法【双仓库序列号】
	
	修改:冯波,序列号关联,分支机构控制
*/
CREATE  PROCEDURE Gp_SerialRedWord_dGrid
(
	@BillNumberId	varchar(50),	-- 单据编号
	@intBillType	int				-- 单据类型
)
--@encode$--
AS
SET NOCOUNT ON	
DECLARE @IOPSBilNumID 		int,			--序列号出入库中的BillNumberID
		@BilNumID 			int,			--主索引表中的BillNumberID
		@SrcSerial			varchar(200),	--查询的序列号
		@RedSerial_SQL 		varchar(8000),	--使用游标的SQL
		--@DelID				int,			--需要删除的单据的过帐ID   BillIndex->ID
		@MaxID				int,			--需要删除最大单据的过帐ID GP_InOutPTypeSerial->BillIndex->ID
		@singleSerial		varchar(100),	--单个的序列号
		@laterSerial		varchar(100),	--Gp_InOutPTypeSerial中的序列号
		@CruOutKTypeId		varchar(100),	--当前单据的出库仓库的ID
		@CruInKTypeId		varchar(100),	--当前单据的入库仓库的ID
		@recBillId 			int,			--最近单据的物流过账真是的ID
		@CruBillType 		int,												
		@PTypeId			varchar(100),	--商品的Id
		@BTypeId1			varchar(100),	--客户
		@BTypeId2			varchar(100),	--供货商
		@inKTypeId			varchar(100),	--入库仓库的Id
		@outKTypeId			varchar(100),	--出库仓库的Id
		@inKTypeTime		datetime,		--入库时间
		@OutKTypeTime		datetime,		--出库时间
		@State				int,			--序列号的状态
		@Flag				int,			--判断是否在库
		@BillType			int,			--单据类型
		@tmpBillNumberId	int,			--临时的BillNumberId
		@recBillNumberId 	int,			--最近的Id
		@ID					NUMERIC(10,0),	--出入库明细表的id
		@OldSerial			VARCHAR(50),
		@LastSerial			VARCHAR(50),
		@CostPrice			 NUMERIC(24, 10) ,	--成本单价
		@GoodsOrder			INT,			--批次
		@GoodsNumber		VARCHAR(100),	--批号
		@CargoID			INT,
		@ValidDate			VARCHAR(50),
		@ProduceDate		VARCHAR(50),
		@ItemID				INT,
		@IsCombined			INT,
		@NowState			TINYINT,
		@LastState			TINYINT
		

SET @recBillNumberId = 0

SELECT @billType=@intBillType

--判断系统是否是序列号强制管理
DECLARE @intSysMngSerial INT,@SQL VARCHAR(MAX)
SELECT @intSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'

DECLARE
	@nCostingMethod	VARCHAR(50),@STypeID	VARCHAR(50),@SerialSQL VARCHAR(MAX)
	
SELECT @STypeID=StypeID
FROM Billindex
WHERE BillNumberId=@BillNumberId	

-- 得到成本核算法
EXEC Gp_GetSubValue 'costing',@STypeID, @nCostingMethod output


DECLARE
	@intserialrelation	INT
	
SET @intserialrelation=0	

SELECT
	@intserialrelation=	Value
FROM Userconfig
WHERE ConfigName='serialrelation'

DECLARE
	@Qty				 NUMERIC(24, 10) ,
	@mxTableName		VARCHAR(100),
	@ErrId				int



--必须特殊处理调拨、拆装单、销售换货单、采购换货单、维修单、上门维修单、维修品调入单、维修品调出单、维修品调拨单、分支机构调拨出库单、分支机构调拨入库单
--首先处理调拨的序列号
IF @intBillType IN (17,21,175)
BEGIN	
		
		SELECT	TOP 1
				@BTypeId1 	= BTypeId1,
				@BTypeId2	= BTypeId2,
				@inKTypeTime= inKTypeTime,
				@outKTypeTime=outKTypeTime,
				@outKTypeId=OutKtyeID,
				@CargoID=CargoID
				
		FROM 	Gp_InOutPTypeSerial
		WHERE	BillNumberId = @BillNumberId
				AND BillType = @intBillType
				AND ISNULL(outKTyeId,'')<>''
				AND BillType NOT IN (71,72,87,88,203)

		IF @@ROWCOUNT <> 0
		BEGIN	--001001001
			UPDATE	Gp_CruPTypeSerial
			SET		BTypeId1 	= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
					BTypeId2 	= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END
			WHERE	Serial IN (
								SELECT	Serial
								FROM 	Gp_InOutPTypeSerial
								WHERE	BillNumberId = @BillNumberId
										AND BillType = @intBillType
										AND ISNULL(outKTyeId,'')<>''
							  )
							  
			IF @@ROWCOUNT = 0
				RETURN -901				  
							  
			IF @intBillType IN (175)
			BEGIN				  
				UPDATE 	Gp_CruPTypeSerial
				SET CostPrice=0,CargoID=@CargoID,KtypeID=@outKTypeId
				FROM 	Gp_InOutPTypeSerial	b
				WHERE 	b.BillNumberId = @BillNumberId
				AND ISNULL(b.OutKtyeID,'')<>''	
				AND Gp_CruPTypeSerial.Serial=b.Serial	
				
				IF @@ROWCOUNT = 0
				RETURN -901		   
			END
			
		
			
		END		
			
		--新的处理方式
		IF @intBillType=21	SET  @mxTableName='MoveBjBill'
		ELSE IF @intBillType=17 SET  @mxTableName='MoveBill'
		
			
		IF @intBillType IN (21,17)
		BEGIN
			
			
		
			--建立商品临时表
			CREATE TABLE #TmpPType
			(
				nId			int identity(1,1),
				PTypeId		varchar(100),
				Qty			 NUMERIC(24, 10) ,
				Id			int,
				IfSerial	int,
				ItemID			INT,
				IsCombined		INT,
				InKTypeID		VARCHAR(50),
				InCargoID		INT,
				OutKTypeID		VARCHAR(50),
				OutCargoID		INT,
				ProduceDate		VARCHAR(50),
				ValidDate		VARCHAR(50),
				GoodsNumber		VARCHAR(100),
				CostPrice		 NUMERIC(24, 10) ,
				GoodsCostPrice	 NUMERIC(24, 10) 
			)

			--建立序列号临时表
			CREATE TABLE #TmpSerial
			(
				nId			int identity(1,1),
				Serial 		varchar(200),
				Serial1		varchar(200),
				PTypeId		varchar(100),
				InKTypeId	varchar(100),
				OutKTypeId	varchar(100),
				Qty			 NUMERIC(24, 10) ,
				Id			int,
				CostPrice			 NUMERIC(24, 10) ,
				GoodsNumber			VARCHAR(100),
				GoodsOrder			INT
			)


			--收集所有行数的序列号
			CREATE TABLE #AllSerial(
				nId			int identity(1,1),
				Serial 		varchar(200),
				Serial1		varchar(200),
				PTypeId		varchar(100),
				InKTypeId	varchar(100),
				OutKTypeId	varchar(100),
				Qty			 NUMERIC(24, 10) ,
				Id			int,
				CostPrice			 NUMERIC(24, 10) ,
				GoodsNumber			VARCHAR(100),
				GoodsOrder			INT
			)
		
		
			--将序列号严密管理的商品写入临时表
			SET @SQL = 'INSERT INTO #TmpPType 
						SELECT	M.PTypeId,
								M.Qty,
								M.Id,
								P.IfSerial,'
								
			IF @intserialrelation=1
			BEGIN					
				SET @SQL = @SQL + 'M.ItemID,
				M.IsCombined,'
			END
			ELSE
			BEGIN
				SET @SQL = @SQL + '0,0,'
			END					

			SET @SQL = @SQL + 'M.KTypeID2,'
				
			IF @intserialrelation=1
			BEGIN	
				SET @SQL = @SQL + 'M.InCargoID,'
			END
			ELSE
			BEGIN
				SET @SQL = @SQL + '0,'
			END					

			SET @SQL = @SQL +'M.KTypeID,'
								
			IF @intserialrelation=1
			BEGIN					
				SET @SQL = @SQL +'M.OutCargoID,
				M.ProduceDate,
				M.ValidDate,
				M.GoodsNumber,
				CASE '+@nCostingMethod+' WHEN 3 THEN CASE '+CAST(@billType AS VARCHAR(50))+' WHEN 21  THEN M.Price ELSE CASE M.GoodsCostPrice WHEN -1 THEN InputCostPrice ELSE M.GoodsCostPrice END END ELSE 0 END,M.GoodsCostPrice  '
			END
			ELSE
			BEGIN
				SET @SQL = @SQL +'0,'''','''','''',0,0 '
			END		
						
			SET @SQL = @SQL +' FROM 	'+@mxTableName+' M,
								PType P
						WHERE 	M.BillNumberId = '+CAST(@BillNumberId AS varchar(100))+'
								AND P.TypeId = M.PTypeId
								AND P.SonNum = 0
								AND P.Deleted = 0 '
			--在序列号宽松模式下，只取有序列号内容的商品来过帐
			IF @intSysMngSerial = 0
				SET @SQL = @SQL + ' AND DataLength(M.Serial)>0 '

			SET @SQL = @SQL + ' ORDER BY M.ID '


			
			--PRINT(@SQL)

			EXEC(@SQL)
			--判断单据明细中是否有序列号，如果没有序列号直接就退出了
			IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpPType)
				BEGIN
					--删除存储过程中的临时表
					--DROP TABLE #TmpPType,#TmpSerial,#UnionSerial,#AllSerial
					RETURN 0		
				END
			--游标循环商品的明细行数，一行一行的写入序列号数据
			DECLARE MngSerialNormal01 CURSOR FOR
				SELECT PTypeId,Qty,Id,nId FROM #TmpPType WHERE IfSerial = @intSysMngSerial
			--打开具体的游标
			OPEN MngSerialNormal01
			--处理结果
			FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
			--如果记录存在
			WHILE @@FETCH_STATUS = 0
				BEGIN
					TRUNCATE TABLE #TmpSerial
					--写序列号入临时表
					SET @SerialSQL = '
							DECLARE  @TmpBill TABLE
							(	
								Serial 		varchar(max),
								PTypeId		varchar(100),
								InKTypeId	varchar(100),
								OutKTypeId	varchar(100),
								Qty			 NUMERIC(24, 10) ,
								Id			int
							) '
													
					--判断是否启用了多仓库
					IF EXISTS(SELECT TOP 1 1 FROM DBO.SYSOBJECTS S,dbo.syscolumns C WHERE s.id = c.id and S.name = @mxTableName AND C.name = 'KTypeId')
						SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,KTypeId2,KTypeId,Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@BillNumberId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
					ELSE
						SET @SerialSQL = @SerialSQL + ' INSERT INTO @TmpBill(Serial,PTypeId,InKTypeId,OutKTypeId,Qty,Id) SELECT Serial,PTypeId,'''+@inKTypeId+''','''+@outKTypeId+''',Qty,Id FROM '+@mxTableName+' WHERE BillNumberId = '+CAST(@BillNumberId AS varchar(100))+' AND PTypeId = '''+CAST(@PTypeId AS varchar(100))+''' AND Id = '+CAST(@Id AS varchar(100))
								

					SET @SerialSQL = @SerialSQL + '
							DECLARE	@i 					int,				--计数器
									@j 					int,				--计数器
									@k					int,				--计数器
									@l					int,
									@intGoOn			int,
									@Serial_str			varchar(MAX),
									@Serial_tmp			varchar(1000),
									@TPTypeId			varchar(100),
									@TInKTypeId			varchar(100),
									@TOutKTypeId		varchar(100),
									@TQty				 NUMERIC(24, 10) ,
									@TXId				int

								
							DECLARE
								@strSplit			VARCHAR(100)
							
							SELECT 
								@Serial_str=Serial,@TPTypeId=PTypeId,@TQty=Qty,@TXId=Id,@TInKTypeId=InKTypeId,@TOutKTypeId=OutKTypeId 
							FROM @TmpBill
							
							
							
							SET @strSplit=''я''
				
							
							INSERT INTO #TmpSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeID,Qty,Id)
							SELECT Serial,Serial,@TPTypeId,@TInKTypeId,@TOutKTypeId,@TQty,@TXId 
							FROM dbo.F_SplitSerial(@Serial_str,@strSplit)
							ORDER BY ShowOrder
							
							
							INSERT INTO #AllSerial(Serial,Serial1,PTypeId,InKTypeId,OutKTypeID,Qty,Id)
							SELECT Serial,Serial1,PTypeId,@TInKTypeId,@TOutKTypeId,Qty,Id
							FROM #TmpSerial
						
							
								
								'								
					EXEC(@SerialSQL)
					
					--循环下一个游标
					FETCH NEXT FROM MngSerialNormal01 INTO @PTypeId,@Qty,@Id,@ErrId
				END							
			--关闭并释放游标资源
			CLOSE MngSerialNormal01
			DEALLOCATE MngSerialNormal01
			
			
			
			UPDATE 	Gp_CruPTypeSerial
			SET CostPrice=CASE WHEN @nCostingMethod<>3 AND @intBillType=17 THEN 0 ELSE b.GoodsCostPrice END,
				CargoID=b.OutCargoID,
				KtypeID=b.OutKTypeID
			FROM #AllSerial a,
			#TmpPType b
			WHERE Gp_CruPTypeSerial.Serial=a.Serial
			AND a.Id=b.Id
		
		END
			
END		
ELSE IF @intBillType = 173 --维修品调入单
	BEGIN
		SELECT	TOP 1
				@BTypeId1 	= BTypeId1,
				@BTypeId2	= BTypeId2,
				@inKTypeId	= inKTypeId,
				@outKTypeId	= outKTyeId,
				@inKTypeTime= inKTypeTime,
				@outKTypeTime=outKTypeTime,
				@CostPrice = CostPrice,
				@GoodsOrder = GoodsOrder
		FROM 	Gp_InOutPTypeSerial
		WHERE	BillNumberId = @BillNumberId
				AND BillType = @intBillType
				AND ISNULL(outKTyeId,'')<>''
				AND BillType NOT IN (71,72,87,88,203)
		
		IF @@ROWCOUNT <> 0
			BEGIN	
				UPDATE	Gp_CruPTypeSerial
				SET		BTypeId1 	= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
						BTypeId2 	= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
						KTypeId	 	= @outKTypeId,
						inKTypeTime = CASE WHEN ISNULL(inKTypeTime,'')='' THEN @inKTypeTime ELSE inKTypeTime END,
						outKTypeTime= NULL,
						GoodsOrder	= @GoodsOrder,
						State = 1
				WHERE	Serial IN (
									SELECT	Serial
									FROM 	Gp_InOutPTypeSerial
									WHERE	BillNumberId = @BillNumberId
											AND BillType = @intBillType
											AND ISNULL(outKTyeId,'')<>''
								  )
								  
				
				UPDATE	Gp_CruPTypeSerial
				SET		
						CostPrice=a.CostPrice,
						CargoID=a.CargoID,
						GoodsNumber=a.GoodsNumber,
						ValidDate=a.ValidDate,
						ProduceDate=a.ProduceDate,
						ItemID=a.ItemID,
						IsCombined=a.IsCombined
				FROM
				(
					SELECT Serial,CostPrice,CargoID,
					GoodsNumber,
					ValidDate,
					ProduceDate,
					ItemID,
					IsCombined
					FROM Gp_InOutPTypeSerial
					WHERE BillNumberid=@BillNumberId AND BillType = @intBillType
											AND ISNULL(outKTyeId,'')<>''
				) a
				WHERE	Gp_CruPTypeSerial.Serial=a.Serial AND  Gp_CruPTypeSerial.Serial IN (
									SELECT	Serial
									FROM 	Gp_InOutPTypeSerial
									WHERE	BillNumberId = @BillNumberId
											AND BillType = @intBillType
											AND ISNULL(outKTyeId,'')<>''
								  )				  
												  
				
				IF @@ROWCOUNT = 0
					RETURN -901
			END
	END
ELSE IF @intBillType = 174 --维修品调出单
	BEGIN
		SELECT	TOP 1
				@BTypeId1 	= BTypeId1,
				@BTypeId2	= BTypeId2,
				@inKTypeId	= inKTypeId,
				@outKTypeId	= outKTyeId,
				@inKTypeTime= inKTypeTime,
				@outKTypeTime=outKTypeTime,
				@CostPrice = CostPrice,
				@GoodsOrder = GoodsOrder,
				@GoodsNumber =  GoodsNumber
		FROM 	Gp_InOutPTypeSerial
		WHERE	BillNumberId = @BillNumberId
				AND BillType = @intBillType
				AND ISNULL(outKTyeId,'')<>''
				AND BillType NOT IN (71,72,87,88,203)
		
		IF @@ROWCOUNT <> 0
			BEGIN	
				UPDATE	Gp_CruPTypeSerial
				SET		BTypeId1 	= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
						BTypeId2 	= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
						KTypeId	 	= @outKTypeId,
						inKTypeTime = CASE WHEN ISNULL(inKTypeTime,'')='' THEN @inKTypeTime ELSE inKTypeTime END,
						outKTypeTime= NULL,
						CostPrice	= 0,
						GoodsOrder	= 0,
						CargoID=0,
						State = 25
				WHERE	Serial IN (
									SELECT	Serial
									FROM 	Gp_InOutPTypeSerial
									WHERE	BillNumberId = @BillNumberId
											AND BillType = @intBillType
											AND ISNULL(outKTyeId,'')<>''
								  )

				IF @@ROWCOUNT = 0
					RETURN -901
			END
	END
ELSE--********************************************************************************************处理拆装、销售换货单、维修单、上门维修单的【入库】********************************************************************************************
	BEGIN
		DECLARE DoubleSerialIn CURSOR FOR
			SELECT Serial FROM Gp_InOutPTypeSerial WHERE BillNumberId = @BillNumberId AND BillType = @intBillType AND State IN (1,7,25) AND BillType NOT IN (71,72,87,88,203)
		
		OPEN DoubleSerialIn
		
		FETCH NEXT FROM DoubleSerialIn INTO @singleSerial
		
		WHILE @@FETCH_STATUS = 0
			BEGIN	
				--查询入库的序列号是否在出库的序列号中【只有拆装单才有这个可能】
				IF EXISTS(SELECT TOP 1 Serial FROM Gp_InOutPTypeSerial WHERE Serial = @singleSerial AND BillNumberId = @BillNumberId  AND BillType = @intBillType AND State NOT IN (1,7,25) AND BillType NOT IN (71,72,87,88,203))
					BEGIN	
						SELECT	TOP 1
								@PTypeId	= PTypeId,
								@inKTypeId	= inKTypeId,
								@outKTypeId	= outKTyeId,
								@BTypeId1	= BTypeId1,
								@BTypeId2	= BTypeId2,
								@inKTypeTime= inKTypeTime,
								@outKTypeTime=outKTypeTime,
								@CostPrice	= CostPrice,
								@GoodsOrder	= GoodsOrder,
								@GoodsNumber = GoodsNumber,
								@State		= State,
								@ValidDate	=ValidDate,
								@ProduceDate=ProduceDate,
								@ItemID		=ItemID,
								@IsCombined	=IsCombined,
								@CargoID=CargoID
						FROM 	Gp_InOutPTypeSerial
						WHERE	Serial = @singleSerial
								AND BillNumberId = @BillNumberId
								AND BillType = @intBillType
								AND State NOT IN (1,7,25)
								AND BillType NOT IN (71,72,87,88,203)

						IF @@ROWCOUNT <> 0
							BEGIN	
								UPDATE	Gp_CruPTypeSerial
								SET		PTypeId 	= @PTypeId,
										BTypeId1	= CASE WHEN ISNULL(BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
										BTypeId2	= CASE WHEN ISNULL(BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
										KTypeId 	= @outKTypeId,
										inKTypeTime	= CASE WHEN ISNULL(inKTypeTime,'')='' THEN @inKTypeTime ELSE inKTypeTime END,
										outKTypeTime= NULL,
										State		= @State,
										Flag		= 1,
										CostPrice	= @CostPrice,
										GoodsOrder = @GoodsOrder,
										GoodsNumber = @GoodsNumber,
										ValidDate	=@ValidDate,
										ProduceDate=@ProduceDate,
										ItemID		=@ItemID,
										IsCombined	=@IsCombined,
										CargoID=@CargoID
								WHERE	Serial = @singleSerial

								IF @@ROWCOUNT = 0
									RETURN -901
							END		

					END		
				ELSE
					BEGIN	
						--获取最近的单据
						SET @recBillNumberId = 0
					
						SELECT TOP 1 @ID=MIN(ID) FROM gp_inoutPtypeSerial WHERE Serial=@singleSerial and BillNumberid=@BillNumberID
						SELECT @OldSerial = dbo.F_GetOldSerial(@singleSerial,@ID) 
						IF ISNULL(@OldSerial,'')='' SET @OldSerial=@singleSerial
						--查询红冲前的最近一张单据
						
						SELECT	TOP 1
								@recBillNumberId = B.BillNumberId,
								@BillType = B.BillType
						FROM	(
									SELECT  TOP 1 
											ISNULL(a.BillNumberId,0) AS BillNumberId,
											a.BillType,
											a.ID
									FROM	gp_inoutPtypeSerial a,
											PosAllotApplyBillIndex Bil
									WHERE a.BillNumberid=bil.BillNumberId
											AND a.ID<@ID
											AND A.Serial = @OldSerial
											AND Bil.RedWord =0 
											AND Bil.IfCheck = 't' 
											AND a.BillType NOT IN (71,72,87,88,203) 
									ORDER BY a.ID DESC
									UNION ALL
									SELECT  TOP 1 
											ISNULL(a.BillNumberId,0) AS BillNumberId,
											a.BillType,
											a.ID
									FROM	gp_inoutPtypeSerial a,
											BillIndex Bil
									WHERE a.BillNumberid=bil.BillNumberId
											AND a.ID<@ID
											AND A.Serial = @OldSerial
											AND Bil.RedWord =0 
											AND Bil.IfCheck = 't' 
											AND a.BillType NOT IN (71,72,87,88,203) 
									ORDER BY a.ID DESC	
						)B ORDER BY B.ID DESC
												
						--运输配送类单据
						IF @BillType IN (327,328,329)
						BEGIN
							SELECT  TOP 1 
									@recBillNumberId = ISNULL(a.BillNumberId,0),
									@BillType = a.BillType
							FROM	gp_inoutPtypeSerial a,
									PosAllotApplyBillIndex Bil
							WHERE a.BillNumberid=bil.BillNumberId
									AND a.ID<@ID
									AND A.Serial = @OldSerial
									AND Bil.RedWord =0 
									AND Bil.IfCheck = 't' 
									AND a.BillType NOT IN (71,72,87,88,203) 
							ORDER BY a.ID DESC						
						END
						ELSE
						BEGIN					
							SELECT  TOP 1 
									@recBillNumberId = ISNULL(a.BillNumberId,0),
									@BillType = a.BillType
							FROM	gp_inoutPtypeSerial a,
									BillIndex Bil
							WHERE a.BillNumberid=bil.BillNumberId
									AND a.ID<@ID
									AND A.Serial = @OldSerial
									AND Bil.RedWord =0 
									AND Bil.IfCheck = 't' 
									AND a.BillType NOT IN (71,72,87,88,203) 
							ORDER BY a.ID DESC
						END
						
						IF @recBillNumberId = 0	--如果没有记录，则需要判断期初
							BEGIN	
								SELECT	TOP 1
										@PTypeId	= PTypeId,
										@inKTypeId	= KTypeId,												
										@BTypeId1	= BTypeId1,
										@BTypeId2	= BTypeId2,
										@inKTypeTime= inKTypeTime,
										@outKTypeTime=outKTypeTime,
										@State		= State,
										@CostPrice	= CostPrice,
										@GoodsOrder = GoodsOrder,
										@GoodsNumber = GoodsNumber,
										@ValidDate	=ValidDate,
										@ProduceDate=ProduceDate,
										@ItemID		=ItemID,
										@IsCombined	=IsCombined
								FROM 	Gp_initPTypeSerial
								WHERE	Serial = @OldSerial
								
								IF @@ROWCOUNT = 0
									BEGIN	
										DELETE FROM Gp_CruPTypeSerial WHERE Serial = @singleSerial	

										IF @@ROWCOUNT = 0
											RETURN -900														
									END		
								ELSE
									BEGIN	
										UPDATE	Gp_CruPTypeSerial
										SET		PTypeId = @PTypeId,
												KTypeId = @inKTypeId,
												BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
												BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
												State 	= @State,
												Flag	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
												CostPrice	= @CostPrice,
												GoodsOrder = @GoodsOrder,
												GoodsNumber = @GoodsNumber,
												ValidDate	=@ValidDate,
												ProduceDate=@ProduceDate,
												ItemID		=@ItemID,
												IsCombined	=@IsCombined
										WHERE	Serial = @singleSerial		

										IF @@ROWCOUNT = 0
											RETURN -901
									END		
							END		
						ELSE
							BEGIN	
								--如果是调拨、拆装单、销售换货单、采购换货单、维修单、上门维修单、维修品调入单、维修品调出单、维修品调拨单
								IF @BillType IN (17,21,16,160,161,166,172,173,174,175)
									BEGIN	
										IF @BillType = 173 AND EXISTS(SELECT TOP 1 1 FROM Gp_InOutPTypeSerial WHERE Serial = @OldSerial  AND BillNumberId = @recBillNumberId AND State IN (1,7,25))
											BEGIN
												SELECT	TOP 1
														@PTypeId 	= PTypeId,
														@inKTypeId	= inKTypeId,
														@outKTypeId	= outKTyeId,
														@BTypeId1	= BTypeId1,
														@BTypeId2	= BTypeId2,
														@inKTypeTime= inKTypeTime,
														@outKTypeTime=outKTypeTime,
														@State		= State,
														@CostPrice	= CostPrice,
														@GoodsOrder = GoodsOrder,
														@GoodsNumber = GoodsNumber,
														@ValidDate	=ValidDate,
														@ProduceDate=ProduceDate,
														@ItemID		=ItemID,
														@IsCombined	=IsCombined
												FROM	Gp_InOutPTypeSerial
												WHERE	State IN (1,7,25)
														AND Serial = @OldSerial
														AND BillNumberId = 	@recBillNumberId
														AND BillType 	 =  @BillType
														AND BillType NOT IN (71,72,87,88,203)

												--如果有结果集
												IF @@ROWCOUNT <> 0
													BEGIN	
														UPDATE	Gp_CruPTypeSerial
														SET		PTypeId 	= @PTypeId,
																KTypeId		= @inKTypeId,
																BTypeId1	= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																BTypeId2	= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																InKTypeTime	= CASE WHEN ISNULL(inKTypeTime,'')='' THEN @inKTypeTime ELSE inKTypeTime END,
																OutKTypeTime= CASE WHEN ISNULL(@outKTypeTime,'')<>'' THEN @outKTypeTime ELSE outKTypeTime END,
																State		= @State,
																Flag		= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																CostPrice	= @CostPrice,
																GoodsOrder = @GoodsOrder,
																GoodsNumber = @GoodsNumber,
																ValidDate	=@ValidDate,
																ProduceDate=@ProduceDate,
																ItemID		=@ItemID,
																IsCombined	=@IsCombined
														WHERE	Serial = @singleSerial
		
														IF @@ROWCOUNT = 0
															RETURN -901
													END
											END
										ELSE
											BEGIN
												
												SELECT	TOP 1
														@PTypeId 	= PTypeId,
														@inKTypeId	= inKTypeId,
														@outKTypeId	= outKTyeId,
														@BTypeId1	= BTypeId1,
														@BTypeId2	= BTypeId2,
														@inKTypeTime= inKTypeTime,
														@outKTypeTime=outKTypeTime,
														@State		= State,
														@CostPrice	= CostPrice,
														@GoodsOrder = GoodsOrder,
														@GoodsNumber = GoodsNumber,
														@ValidDate	=ValidDate,
														@ProduceDate=ProduceDate,
														@ItemID		=ItemID,
														@IsCombined	=IsCombined
												FROM	Gp_InOutPTypeSerial
												WHERE	State NOT IN (1,7,25)
														AND Serial = @OldSerial 
														AND BillNumberId = 	@recBillNumberId
														AND BillType 	 =  @BillType
														AND BillType NOT IN (71,72,87,88,203)
														
												
	
												--如果有结果集
												IF @@ROWCOUNT <> 0
													BEGIN	
														UPDATE	Gp_CruPTypeSerial
														SET		PTypeId 	= @PTypeId,
																KTypeId		= @outKTypeId,
																BTypeId1	= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																BTypeId2	= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																InKTypeTime	= CASE WHEN ISNULL(inKTypeTime,'')='' THEN @inKTypeTime ELSE inKTypeTime END,
																OutKTypeTime= CASE WHEN ISNULL(@outKTypeTime,'')<>'' THEN @outKTypeTime ELSE outKTypeTime END,
																State		= @State,
																Flag		= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																CostPrice	= @CostPrice,
																GoodsOrder = @GoodsOrder,
																GoodsNumber = @GoodsNumber,
																ValidDate	=@ValidDate,
																ProduceDate=@ProduceDate,
																ItemID		=@ItemID,
																IsCombined	=@IsCombined
														WHERE	Serial = @singleSerial	
		
														IF @@ROWCOUNT = 0
															RETURN -901
													END
											END
									END		
								ELSE	--一般物流单据
									BEGIN	
										SELECT	TOP 1
												@PTypeId 	= PTypeId,
												@inKTypeId	= inKTypeId,
												@outKTypeId	= outKTyeId,
												@BTypeId1	= BTypeId1,
												@BTypeId2	= BTypeId2,
												@inKTypeTime= inKTypeTime,
												@outKTypeTime=outKTypeTime,
												@State		= State,
												@CostPrice	= CostPrice,
												@GoodsOrder = GoodsOrder,
												@GoodsNumber = GoodsNumber,
												@ValidDate	=ValidDate,
												@ProduceDate=ProduceDate,
												@ItemID		=ItemID,
												@IsCombined	=IsCombined
										FROM	Gp_InOutPTypeSerial
										WHERE	Serial = @OldSerial
												AND BillNumberId = 	@recBillNumberId
												AND BillType 	 =  @BillType
												AND BillType NOT IN (71,72,87,88,203)
										--判断结果集
										IF @@ROWCOUNT <> 0
											BEGIN													
												IF (ISNULL(@inKTypeId,'')='10000' OR ISNULL(@outKTypeId,'')='10000')	--*************************特殊处理上一张单据是代销结算单*************************
													BEGIN	
														SELECT  @recBillId = MIN(Id) FROM Gp_InOutPTypeSerial WHERE BillNumberId = @recBillNumberId	AND Serial=@OldSerial
														SELECT  @LastSerial=dbo.F_GetOldSerial(@OldSerial,@recBillId)
														IF ISNULL(@LastSerial,'')='' SET @LastSerial=@OldSerial
														SELECT	TOP 1
																@CruBillType   = G.BillType,
																@CruInKTypeId  = G.inKTypeId,
																@CruOutKTypeId = G.outKTyeId,
																@CostPrice	= G.CostPrice,
																@GoodsOrder = G.GoodsOrder,
																@GoodsNumber = G.GoodsNumber,
																@ValidDate	=ValidDate,
																@ProduceDate=ProduceDate,
																@ItemID		=ItemID,
																@IsCombined	=IsCombined
														FROM	Gp_InOutPTypeSerial G,
																BillIndex B
														WHERE	G.BillNumberId = B.BillNumberId
																AND g.Serial = @LastSerial 
																AND B.IfCheck = 't'
																AND B.RedWord = 0
																AND G.BillType NOT IN (71,72,87,88,203)
																AND (ISNULL(G.inKTypeId,'')<>'10000' AND ISNULL(G.outKTyeId,'')<>'10000')
																AND g.Id<@recBillId
														ORDER BY g.Id DESC
													
											
													
														IF @@ROWCOUNT = 0
															BEGIN
																SELECT	@PTypeId 	= PTypeId,
																		@inKTypeId	= KTypeId,
																		@outKTypeId	= KTypeId,
																		@BTypeId1	= BTypeId1,
																		@BTypeId2	= BTypeId2,
																		@State		= State,
																		@CostPrice	= CostPrice,
																		@GoodsOrder = GoodsOrder,
																		@GoodsNumber = GoodsNumber,
																		@ValidDate	=ValidDate,
																		@ProduceDate=ProduceDate,
																		@ItemID		=ItemID,
																		@IsCombined	=IsCombined
																FROM 	Gp_initPTypeSerial
																WHERE	Serial = @LastSerial

																IF @@ROWCOUNT = 0 
																	BEGIN	
																		DELETE FROM Gp_CruPTypeSerial WHERE Serial = @singleSerial	
																		IF @@ROWCOUNT = 0
																			RETURN -900														
																	END		
																ELSE
																	BEGIN	
																		UPDATE	Gp_CruPTypeSerial
																		SET		PTypeId = @PTypeId,
																				KTypeId = @inKTypeId,
																				BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																				BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																				State	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 2 END,
																				Flag	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																				CostPrice	= @CostPrice,
																				GoodsOrder = @GoodsOrder,
																				GoodsNumber = @GoodsNumber,
																				ValidDate	=@ValidDate,
																				ProduceDate=@ProduceDate,
																				ItemID		=@ItemID,
																				IsCombined	=@IsCombined
																		WHERE 	Serial = @singleSerial	

																		IF @@ROWCOUNT = 0
																			RETURN -901
																	END		
															END
														ELSE
															BEGIN
																IF @State IN (1,7,25)
																	SELECT	TOP 1																			
																			@CruOutKTypeId = inKTypeId,
																			@CostPrice	= G.CostPrice,
																			@GoodsOrder = G.GoodsOrder,
																			@GoodsNumber = G.GoodsNumber,
																			@ValidDate	=ValidDate,
																			@ProduceDate=ProduceDate,
																			@ItemID		=ItemID,
																			@IsCombined	=IsCombined
																	FROM	Gp_InOutPTypeSerial G,
																			BillIndex B
																	WHERE	G.BillNumberId = B.BillNumberId
																			AND g.Serial = @LastSerial
																			AND B.IfCheck = 't'
																			AND B.RedWord = 0
																			AND G.BillType NOT IN (71,72,87,88,203)
																			AND (ISNULL(inKTypeId,'')<>'10000' AND ISNULL(outKTyeId,'')<>'10000')
																			AND G.Id<@recBillId
																	ORDER BY G.Id DESC
																ELSE
																	SELECT	TOP 1																			
																			@CruOutKTypeId = outKTyeId,
																			@CostPrice	= G.CostPrice,
																			@GoodsOrder = G.GoodsOrder,
																			@GoodsNumber = G.GoodsNumber,
																			@ValidDate	=ValidDate,
																			@ProduceDate=ProduceDate,
																			@ItemID		=ItemID,
																			@IsCombined	=IsCombined
																	FROM	Gp_InOutPTypeSerial G,
																			BillIndex B
																	WHERE	G.BillNumberId = B.BillNumberId
																			AND g.Serial = @LastSerial 
																			AND B.IfCheck = 't'
																			AND B.RedWord = 0
																			AND G.BillType NOT IN (71,72,87,88,203)
																			AND (ISNULL(inKTypeId,'')<>'10000' AND ISNULL(outKTyeId,'')<>'10000')
																			AND G.Id<@recBillId
																	ORDER BY G.Id DESC	
																	
															

																UPDATE	Gp_CruPTypeSerial
																SET		PTypeId 	= @PTypeId,
																		KTypeId		= CASE
																						WHEN (ISNULL(@inKTypeId,'')='10000' OR ISNULL(@outKTypeId,'')='10000') THEN @CruOutKTypeId
																						WHEN @State IN (1,7,25) THEN @inKTypeId
																						WHEN @State NOT IN (1,7,25) THEN @outKTypeId																				
																						ELSE KTypeId 
																					  END,
																		BTypeId1	= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																		BTypeId2	= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																		InKTypeTime	= CASE WHEN @State IN (1,7,25) THEN inKTypeTime ELSE inKTypeTime END,
																		outKTypeTime= CASE WHEN @State IN (1,7,25) THEN outKTypeTime ELSE outKTypeTime END,
																		State		= CASE 
																						   WHEN @State IN (1,7,25) THEN 1
																						   WHEN ISNULL(CommissionState,'')='0' THEN @State
																						   ELSE 2 
																					  END,
																		Flag		= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																		CostPrice	= @CostPrice,
																		GoodsOrder = @GoodsOrder,
																		GoodsNumber = @GoodsNumber,
																		ValidDate	=@ValidDate,
																		ProduceDate=@ProduceDate,
																		ItemID		=@ItemID,
																		IsCombined	=@IsCombined
																WHERE	Serial = @singleSerial	
		
																IF @@ROWCOUNT = 0
																	RETURN -901
															END
													END
												ELSE																	--*************************如果是普通单据*************************
													BEGIN
											
														IF @State IN (1,7,25)
															UPDATE	Gp_CruPTypeSerial
															SET		PTypeId = @PTypeId,
																	KTypeId = @inKTypeId,
																	BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																	BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																	State	= @State,
																	Flag	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																	CostPrice	= @CostPrice,
																	GoodsOrder = @GoodsOrder,
																	GoodsNumber = @GoodsNumber,
																	ValidDate	=@ValidDate,
																	ProduceDate=@ProduceDate,
																	ItemID		=@ItemID,
																	IsCombined	=@IsCombined
															WHERE 	Serial = @singleSerial	
														ELSE
															UPDATE	Gp_CruPTypeSerial
															SET		PTypeId = @PTypeId,
																	KTypeId = @outKTypeId,
																	BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																	BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																	State	= @State,
																	Flag	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																	CostPrice	= @CostPrice,
																	GoodsOrder = @GoodsOrder,
																	GoodsNumber = @GoodsNumber,
																	ValidDate	=@ValidDate,
																	ProduceDate=@ProduceDate,
																	ItemID		=@ItemID,
																	IsCombined	=@IsCombined
															WHERE 	Serial = @singleSerial	

														IF @@ROWCOUNT = 0
															RETURN -901
													END
											END													
									END												
							END		
					END		
				FETCH NEXT FROM DoubleSerialIn INTO @singleSerial
			END		
		--关闭游标
		CLOSE DoubleSerialIn
		--释放游标资源
		DEALLOCATE DoubleSerialIn
		SET @recBillNumberId = 0
		--********************************************************************************************处理拆装、销售换货单、维修单、上门维修单的【出库】********************************************************************************************
		DECLARE DoubleSerialOut CURSOR FOR
			SELECT Serial,State FROM Gp_InOutPTypeSerial WHERE BillNumberId = @BillNumberId AND BillType = @intBillType AND State NOT IN (1,7,25) AND BillType NOT IN (71,72,87,88,203)
		--打开游标
		OPEN DoubleSerialOut
		--循环结果集
		FETCH NEXT FROM DoubleSerialOut INTO @singleSerial,@NowState
		WHILE @@FETCH_STATUS = 0
			BEGIN	--001002002
				--获取最近的单据
				SET @recBillNumberId = 0
				SET @OldSerial=''
				--查询红冲前的最近一张单据
			
				SELECT TOP 1 @ID = MIN(ID) FROM gp_inoutPtypeSerial WHERE Serial=@singleSerial and BillNumberid=@BillNumberID
				SELECT @OldSerial = dbo.F_GetOldSerial(@singleSerial,@ID)
				IF ISNULL(@OldSerial,'')='' SET @OldSerial=@LastSerial
				
				SELECT	TOP 1
						@recBillNumberId = B.BillNumberId,
						@BillType = B.BillType,
						@LastState= B.State
				FROM	(
							SELECT  TOP 1
									ISNULL(a.BillNumberId,0) AS BillNumberId,
									a.BillType,
									a.STATE,
									a.ID
							FROM	gp_inoutPtypeSerial a,
									PosAllotApplyBillIndex Bil
							WHERE   a.BillNumberid=bil.BillNumberId
									AND a.ID<@ID
									AND A.Serial=@OldSerial 
									AND a.BillNumberid<>@BillNumberID	
									AND Bil.RedWord =0 
									AND Bil.IfCheck = 't'				
									AND a.BillType NOT IN (71,72,87,88,203) 
							ORDER BY a.ID DESC
							UNION ALL
							SELECT  TOP 1
									ISNULL(a.BillNumberId,0) AS BillNumberId,
									a.BillType,
									a.STATE,
									a.ID
							FROM	gp_inoutPtypeSerial a,
									BillIndex Bil
							WHERE   a.BillNumberid=bil.BillNumberId
									AND a.ID<@ID
									AND A.Serial=@OldSerial 
									AND a.BillNumberid<>@BillNumberID	
									AND Bil.RedWord =0 
									AND Bil.IfCheck = 't'				
									AND a.BillType NOT IN (71,72,87,88,203) 
							ORDER BY a.ID DESC
				)B	
				ORDER BY B.ID DESC
				
				--门店配送类单据
				IF @BillType IN (327,328,329)
				BEGIN
					SELECT  TOP 1 
							@recBillNumberId = ISNULL(a.BillNumberId,0),
							@BillType = a.BillType,
							@LastState=a.State
					FROM	gp_inoutPtypeSerial a,
							PosAllotApplyBillIndex Bil
					WHERE   a.BillNumberid=bil.BillNumberId
							AND a.ID<@ID
							AND A.Serial=@OldSerial 
							AND a.BillNumberid<>@BillNumberID
							AND Bil.RedWord =0 
							AND Bil.IfCheck = 't' 
							AND a.BillType NOT IN (71,72,87,88,203) 
					ORDER BY a.ID DESC					
				END
				ELSE
				BEGIN
					SELECT  TOP 1 
							@recBillNumberId = ISNULL(a.BillNumberId,0),
							@BillType = a.BillType,
							@LastState=a.State
					FROM	gp_inoutPtypeSerial a,
							BillIndex Bil
					WHERE  a.BillNumberid=bil.BillNumberId
							AND a.ID<@ID
							AND A.Serial=@OldSerial 
							AND a.BillNumberid<>@BillNumberID
							AND Bil.RedWord =0 
							AND Bil.IfCheck = 't' 
							AND a.BillType NOT IN (71,72,87,88,203) 
					ORDER BY a.ID DESC				
				END
				
				
				IF @NowState IN (2,3,4,5,8,9,10,11,13,14,15,16,18,19,21,26,27,28,29,30,31,33) AND @LastState IN (2,3,4,5,8,9,10,11,13,14,15,16,18,19,21,26,27,28,29,30,31,33)
				BEGIN
					SET @recBillNumberId=0
				END				
										
				--判断是否有单据，如果没有单据，则查询期初
				IF @recBillNumberId = 0
					BEGIN	
						--查询期初序列号
						SELECT	@PTypeId 	= PTypeId,
								@inKTypeId	= KTypeId,
								@outKTypeId	= KTypeId,
								@BTypeId1	= BTypeId1,
								@BTypeId2	= BTypeId2,
								@State		= State,
								@CostPrice	= CostPrice,
								@GoodsOrder = GoodsOrder,
								@GoodsNumber = GoodsNumber,
								@ValidDate	=ValidDate,
								@ProduceDate=ProduceDate,
								@ItemID		=ItemID,
								@IsCombined	=IsCombined
						FROM 	Gp_initPTypeSerial
						WHERE	Serial = @OldSerial

						IF @@ROWCOUNT = 0 
							BEGIN	
								DELETE FROM Gp_CruPTypeSerial WHERE Serial = @singleSerial
								IF @@ROWCOUNT = 0
									RETURN -900														
							END		
						ELSE
							BEGIN
								
								UPDATE	Gp_CruPTypeSerial
								SET		PTypeId = @PTypeId,
										KTypeId = @inKTypeId,
										BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
										BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
										State	= @State,
										Flag	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
										CostPrice	= @CostPrice,
										GoodsOrder	= @GoodsOrder,
										GoodsNumber = @GoodsNumber,
										ValidDate	=@ValidDate,
										ProduceDate=@ProduceDate,
										ItemID		=@ItemID,
										IsCombined	=@IsCombined
								WHERE 	Serial = @singleSerial

								IF @@ROWCOUNT = 0
									RETURN -901
							END		
						END		
					ELSE	
						BEGIN	
							--如果是调拨、拆装单、销售换货单、采购换货单、维修单、上门维修单、维修品调入单、维修品调出单、维修品调拨单
							IF @BillType IN (17,21,16,160,161,166,172,173,174,175)
								BEGIN	
									SELECT	TOP 1
											@PTypeId 	= PTypeId,
											@inKTypeId	= inKTypeId,
											@outKTypeId	= outKTyeId,
											@BTypeId1	= BTypeId1,
											@BTypeId2	= BTypeId2,
											@inKTypeTime= inKTypeTime,
											@outKTypeTime=outKTypeTime,
											@State		= State,
											@CostPrice	= CostPrice,
											@GoodsOrder	= GoodsOrder,
											@GoodsNumber = GoodsNumber,
											@ValidDate	=ValidDate,
											@ProduceDate=ProduceDate,
											@ItemID		=ItemID,
											@IsCombined	=IsCombined
									FROM	Gp_InOutPTypeSerial
									WHERE	State IN (1,7,25)
											AND Serial = @OldSerial
											AND BillNumberId = 	@recBillNumberId
											AND BillType	 =  @BillType
											AND BillType NOT IN (71,72,87,88,203)
											
									

									IF @@ROWCOUNT <> 0
										BEGIN	
											UPDATE	Gp_CruPTypeSerial
											SET		PTypeId 	= @PTypeId,
													KTypeId		= @inKTypeId,
													BTypeId1	= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
													BTypeId2	= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
													InKTypeTime	= CASE WHEN ISNULL(inKTypeTime,'')='' THEN inKTypeTime ELSE inKTypeTime END,
													OutKTypeTime= CASE WHEN ISNULL(@outKTypeTime,'')='' THEN OutKTypeTime ELSE outKTypeTime END,
													State		= @State,
													Flag		= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
													CostPrice	= @CostPrice,
													GoodsOrder	= @GoodsOrder,
													GoodsNumber = @GoodsNumber,
													ValidDate	=@ValidDate,
													ProduceDate=@ProduceDate,
													ItemID		=@ItemID,
													IsCombined	=@IsCombined
											WHERE	Serial = @singleSerial	

											IF @@ROWCOUNT = 0
												RETURN -901
										END		
								END
							ELSE	--一般物流单据
								BEGIN											
									SELECT	TOP 1
											@PTypeId 	= PTypeId,
											@inKTypeId	= CASE BillType WHEN 57 THEN OutKtyeID ELSE inKTypeId END,
											@outKTypeId	= outKTyeId,
											@BTypeId1	= BTypeId1,
											@BTypeId2	= BTypeId2,
											@inKTypeTime= inKTypeTime,
											@outKTypeTime=outKTypeTime,
											@State		= State,
											@CostPrice	= CostPrice,
											@GoodsOrder	= GoodsOrder,
											@GoodsNumber = GoodsNumber,
											@ValidDate	=ValidDate,
											@ProduceDate=ProduceDate,
											@ItemID		=ItemID,
											@IsCombined	=IsCombined
									FROM	Gp_InOutPTypeSerial
									WHERE	Serial = @OldSerial
											AND BillNumberId = 	@recBillNumberId
											AND BillType	 =  @BillType
											AND BillType NOT IN (71,72,87,88,203)											

									IF @@ROWCOUNT <> 0
										BEGIN											
											IF (ISNULL(@inKTypeId,'')='10000' OR ISNULL(@outKTypeId,'')='10000')				--**************************特殊处理上一张单据是代销结算单**************************
												BEGIN	
								
														SELECT  @recBillId = MIN(Id) FROM Gp_InOutPTypeSerial WHERE BillNumberId = @recBillNumberId	AND Serial=@OldSerial
														SELECT  @LastSerial=dbo.F_GetOldSerial(@OldSerial,@recBillId)
														IF ISNULL(@LastSerial,'')='' SET @LastSerial=@OldSerial
													SELECT	TOP 1
															@CruBillType   = G.BillType,
															@CruInKTypeId  = G.inKTypeId,
															@CruOutKTypeId = G.outKTyeId,
															@CostPrice	= G.CostPrice,
															@GoodsOrder = G.GoodsOrder,
															@GoodsNumber = G.GoodsNumber,
															@ValidDate	=ValidDate,
															@ProduceDate=ProduceDate,
															@ItemID		=ItemID,
															@IsCombined	=IsCombined
													FROM	Gp_InOutPTypeSerial G,
															BillIndex B
													WHERE	G.BillNumberId = B.BillNumberId
															AND g.Serial = @LastSerial 
															AND B.IfCheck = 't'
															AND B.RedWord = 0
															AND G.BillType NOT IN (71,72,87,88,203)
															AND (ISNULL(G.inKTypeId,'')<>'10000' AND ISNULL(G.outKTyeId,'')<>'10000')
															AND G.Id<@recBillId
													ORDER BY G.Id DESC

													IF @@ROWCOUNT = 0
														BEGIN
															SELECT	@PTypeId 	= PTypeId,
																	@inKTypeId	= KTypeId,
																	@outKTypeId	= KTypeId,
																	@BTypeId1	= BTypeId1,
																	@BTypeId2	= BTypeId2,
																	@State		= State,
																	@CostPrice	= CostPrice,
																	@GoodsOrder = GoodsOrder,
																	@GoodsNumber = GoodsNumber,
																	@ValidDate	=ValidDate,
																	@ProduceDate=ProduceDate,
																	@ItemID		=ItemID,
																	@IsCombined	=IsCombined
															FROM 	Gp_initPTypeSerial
															WHERE	Serial = @LastSerial

															IF @@ROWCOUNT = 0 
																BEGIN
																	DELETE FROM Gp_CruPTypeSerial WHERE Serial = @singleSerial
																	IF @@ROWCOUNT = 0
																		RETURN -900														
																END
															ELSE
																BEGIN
																	UPDATE	Gp_CruPTypeSerial
																	SET		PTypeId = @PTypeId,
																			KTypeId = @inKTypeId,
																			BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																			BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																			State	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 2 END,
																			Flag	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																			CostPrice	= @CostPrice,
																			GoodsOrder	= @GoodsOrder,
																			GoodsNumber = @GoodsNumber,
																			ValidDate	=@ValidDate,
																			ProduceDate=@ProduceDate,
																			ItemID		=@ItemID,
																			IsCombined	=@IsCombined
																	WHERE 	Serial = @singleSerial

																	IF @@ROWCOUNT = 0
																		RETURN -901
																END
														END
													ELSE
														BEGIN
															IF @State IN (1,7,25)
																SELECT	TOP 1																			
																		@CruOutKTypeId = inKTypeId,
																		@CostPrice	= G.CostPrice,
																		@GoodsOrder = G.GoodsOrder,
																		@GoodsNumber = G.GoodsNumber,
																		@ValidDate	=ValidDate,
																		@ProduceDate=ProduceDate,
																		@ItemID		=ItemID,
																		@IsCombined	=IsCombined
																FROM	Gp_InOutPTypeSerial G,
																		BillIndex B
																WHERE	G.BillNumberId = B.BillNumberId
																		AND g.Serial = @LastSerial 
																		AND B.IfCheck = 't'
																		AND B.RedWord = 0
																		AND G.BillType NOT IN (71,72,87,88,203)
																		AND (ISNULL(inKTypeId,'')<>'10000' AND ISNULL(outKTyeId,'')<>'10000')
																		AND G.Id<@recBillId
																ORDER BY G.Id DESC
															ELSE
																SELECT	TOP 1																			
																		@CruOutKTypeId = outKTyeId,
																		@CostPrice	= G.CostPrice,
																		@GoodsOrder = G.GoodsOrder,
																		@GoodsNumber = G.GoodsNumber,
																		@ValidDate	=ValidDate,
																		@ProduceDate=ProduceDate,
																		@ItemID		=ItemID,
																		@IsCombined	=IsCombined
																FROM	Gp_InOutPTypeSerial G,
																		BillIndex B
																WHERE	G.BillNumberId = B.BillNumberId
																		AND g.Serial = @LastSerial  
																		AND B.IfCheck = 't'
																		AND B.RedWord = 0
																		AND G.BillType NOT IN (71,72,87,88,203)
																		AND (ISNULL(inKTypeId,'')<>'10000' AND ISNULL(outKTyeId,'')<>'10000')
																		AND G.Id<@recBillId
																ORDER BY G.Id DESC

															UPDATE	Gp_CruPTypeSerial
															SET		PTypeId 	= @PTypeId,
																	KTypeId		= CASE
																					WHEN (ISNULL(@inKTypeId,'')='10000' OR ISNULL(@outKTypeId,'')='10000') THEN @CruOutKTypeId
																					WHEN @State IN (1,7,25) THEN @inKTypeId 
																					WHEN @State NOT IN (1,7,25) THEN @outKTypeId																			
																					ELSE KTypeId 
																				  END,
																	BTypeId1	= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																	BTypeId2	= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																	InKTypeTime	= CASE WHEN @State IN (1,7,25) THEN inKTypeTime ELSE inKTypeTime END,
																	outKTypeTime= CASE WHEN @State IN (1,7,25) THEN outKTypeTime ELSE outKTypeTime END,
																	State		= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 2 END,
																	Flag		= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																	CostPrice	= @CostPrice,
																	GoodsOrder	= @GoodsOrder,
																	GoodsNumber = @GoodsNumber,
																	ValidDate	=@ValidDate,
																	ProduceDate=@ProduceDate,
																	ItemID		=@ItemID,
																	IsCombined	=@IsCombined
															WHERE	Serial = @singleSerial		

															IF @@ROWCOUNT = 0
																RETURN -901
														END
												END
											ELSE																			--**************************特殊处理上一张单据是普通单据**************************
												BEGIN
													IF @State IN (1,7,25)
														UPDATE	Gp_CruPTypeSerial
														SET		PTypeId = @PTypeId,
																KTypeId = @inKTypeId,
																BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																State	= @State,
																Flag	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																CostPrice	= @CostPrice,
																GoodsOrder	= @GoodsOrder,
																GoodsNumber = @GoodsNumber,
																ValidDate	=@ValidDate,
																ProduceDate=@ProduceDate,
																ItemID		=@ItemID,
																IsCombined	=@IsCombined
														WHERE 	Serial = @singleSerial
													ELSE
														UPDATE	Gp_CruPTypeSerial
														SET		PTypeId = @PTypeId,
																KTypeId = @outKTypeId,
																BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																State	= @State,
																Flag	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 0 END,
																CostPrice	= @CostPrice,
																GoodsOrder	= @GoodsOrder,
																GoodsNumber = @GoodsNumber,
																ValidDate	=@ValidDate,
																ProduceDate=@ProduceDate,
																ItemID		=@ItemID,
																IsCombined	=@IsCombined
														WHERE 	Serial = @singleSerial	

													IF @@ROWCOUNT = 0
														RETURN -901
												END
										END											
								END								
						END	
				FETCH NEXT FROM DoubleSerialOut INTO @singleSerial,@NowState
			END
		
		CLOSE DoubleSerialOut
		DEALLOCATE DoubleSerialOut
	END	


--重算当前序列号库中的STypeId
--性能优化：以前没加条件判断，是更新所有库存序列号，容易造成死锁
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S
WHERE	C.KtypeID = S.typeId		
		AND C.KtypeID <> '10000'
		AND EXISTS
		(
			SELECT a.Serial 
			FROM Gp_InOutPTypeSerial a
			WHERE a.BillNumberId = @BillNumberId
			AND a.Serial=c.Serial
		)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

DECLARE
	@BillNumberId	varchar(50),	-- 单据编号
	@intBillType	int,				-- 单据类型
	@nRet			INT
	
SELECT
	@BillNumberID=2,
	@intBillType=21	

BEGIN TRAN
select CostPrice,KtypeID,CargoID,* from gp_CruPtypeSerial

EXEC @nRet=Gp_SerialRedWord_dGrid
	@BillNumberId,
	@intBillType
	
select CostPrice,KtypeID,CargoID,* from gp_CruPtypeSerial
ROLLBACK TRAN

*/





GO
/*
*		实物库存序列号红冲
*/
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_SerialRedWord_Fact',N'P'))
BEGIN
	DROP PROC GP_SerialRedWord_Fact
END
GO

CREATE PROC GP_SerialRedWord_Fact
(
	@BillNumberId	varchar(50),	-- 单据编号
	@intBillType	int				-- 单据类型
)
--@encode$--
AS
SET NOCOUNT ON	
DECLARE 
		@Serial		varchar(100),			--单个的序列号
		@PTypeId			varchar(100),	--商品的Id
		@inKTypeId			varchar(100),	--入库仓库的Id
		@outKTypeId			varchar(100),	--出库仓库的Id
		@inKTypeTime		datetime,		--入库时间
		@OutKTypeTime		datetime,		--出库时间
		@State				int,			--序列号的状态
		@Flag				int,			--判断是否在库
		@BillType			int,			--单据类型
		@recBillNumberId 	int,			 --最近的Id
		@ID					NUMERIC(10,0),
		@GoodsOrder			INT,			--批次
		@GoodsNumber		VARCHAR(100),	--批号
		@CargoID			INT,
		@ValidDate			VARCHAR(50),
		@ProduceDate		VARCHAR(50),
		@ItemID				INT,
		@IsCombined			INT,
		@LendState          INT,
		@AfterBillNumberID  INT				--本单之后的单据编号

SET @recBillNumberId = 0


--循环处理序列号
DECLARE SerialCursor CURSOR FOR
	SELECT Serial FROM Fact_InOutPTypeSerial WHERE BillNumberId = @BillNumberId AND BillType = @intBillType
OPEN SerialCursor

FETCH NEXT FROM SerialCursor INTO @Serial

WHILE @@FETCH_STATUS = 0	
BEGIN
		SET @recBillNumberId = 0
		--查询红冲前的最近一张单据
		SELECT TOP 1 @ID=MIN(ID) FROM Fact_inoutPtypeSerial WHERE Serial=@Serial and BillNumberid=@BillNumberID
		SELECT TOP 1 @recBillNumberId = ISNULL(a.BillNumberId,0),@BillType = a.BillType
		FROM Fact_inoutPtypeSerial a,dbo.FactIndex Bil WHERE a.BillNumberid=bil.BillNumberId
								AND a.ID<@ID
								AND A.Serial = @Serial
								AND Bil.RedWord =0 
								AND Bil.IfCheck = 't' 
						ORDER BY a.ID DESC
	    
	    SELECT TOP 1 @AfterBillNumberID = ISNULL(a.BillNumberId,0),@BillType = a.BillType
		FROM Fact_inoutPtypeSerial a,dbo.FactIndex Bil WHERE a.BillNumberid=bil.BillNumberId
								AND a.ID>@ID
								AND A.Serial = @Serial
								AND Bil.RedWord =0 
								AND Bil.IfCheck = 't' 
						ORDER BY a.ID DESC
						
		--序列号被之后单据引用
		IF @AfterBillNumberID<>0
		BEGIN
			RETURN -11
		END
		
		IF @recBillNumberId = 0	--之前没有单据了，判断是否有期初序列号了
		BEGIN	
			SELECT 	TOP 1 
					@PTypeId = PTypeId,
					@inKTypeId	= KTypeId,
					@State = State,
					@Flag = Flag,
					@GoodsOrder = GoodsOrder,
					@GoodsNumber = GoodsNumber,
					@CargoID=CargoID,
					@ValidDate	=ValidDate,
					@ProduceDate=ProduceDate,
					@ItemID		=ItemID,
					@IsCombined	=IsCombined
			FROM 	dbo.gp_iniFactPtypeSerial 
			WHERE 	Serial = @Serial

			--如果有期初序列号
			IF @@ROWCOUNT <> 0
			BEGIN
				UPDATE	GP_FactPTypeSerial
				SET		KTypeId	= @inKTypeId,
						PTypeId = @PTypeId,
						State	= @State,
						Flag	= @Flag,
						GoodsOrder = @GoodsOrder,
						GoodsNumber = @GoodsNumber,
						CargoID=@CargoID,
						ValidDate	=@ValidDate,
						ProduceDate=@ProduceDate,
						ItemID		=@ItemID,
						IsCombined	=@IsCombined,
						LendState   =0
				WHERE	Serial  = @Serial
				
				IF @@ROWCOUNT = 0
					RETURN -901
			END
			ELSE
			BEGIN
				DELETE FROM GP_FactPTypeSerial WHERE Serial = @Serial
				IF @@ROWCOUNT = 0
					RETURN -900
			END
		END				
		ELSE		
		/**********如果红冲单据最近的一张单据是调拨x单据 调拨单退回到入库状态**********************/
		BEGIN							
		IF @BillType=420
		BEGIN
			SELECT 	TOP 1 
					@PTypeId = PTypeId,
					@inKTypeId	= inKTypeId,
					@outKTypeId = outKTyeId,
					@State = State,
					@GoodsOrder = GoodsOrder,
					@GoodsNumber = GoodsNumber,
					@CargoID=CargoID,
					@ValidDate	=ValidDate,
					@ProduceDate=ProduceDate,
					@ItemID		=ItemID,
					@IsCombined	=IsCombined,
					@LendState=LendState
			FROM 	Fact_InOutPTypeSerial 
			WHERE 	Serial = @Serial 
					AND BillNumberId = @recBillNumberId 
					AND State=1 
			
			IF @@ROWCOUNT <> 0
			BEGIN
				UPDATE	Gp_FactPTypeSerial
				SET		PTypeId = @PTypeId,
						KTypeId = @inKTypeId,
						State	= @State,
						Flag	= 1,
						GoodsOrder	= @GoodsOrder,
						GoodsNumber = @GoodsNumber,
						CargoID=@CargoID,
						ValidDate	=@ValidDate,
						ProduceDate=@ProduceDate,
						ItemID		=@ItemID,
						IsCombined	=@IsCombined,
						LendState=@LendState
				WHERE	Serial  = @Serial
				
				IF @@ROWCOUNT = 0
					RETURN -901
			END
		END
		/********红冲最近的单据是仓库出库单，怎做出库处理*********/
		ELSE IF @BillType=419
		BEGIN
				SELECT 	TOP 1 
					@PTypeId = PTypeId,
					@inKTypeId	= inKTypeId,
					@outKTypeId = outKTyeId,
					@State = State,
					@GoodsOrder = GoodsOrder,
					@GoodsNumber = GoodsNumber,
					@CargoID=CargoID,
					@ValidDate	=ValidDate,
					@ProduceDate=ProduceDate,
					@ItemID		=ItemID,
					@IsCombined	=IsCombined,
					@LendState=LendState
			FROM 	Fact_InOutPTypeSerial 
			WHERE 	Serial = @Serial 
					AND BillNumberId = @recBillNumberId 
					AND State=2
			
			IF @@ROWCOUNT <> 0
			BEGIN
				UPDATE	Gp_FactPTypeSerial
				SET		PTypeId = @PTypeId,
						KTypeId = @inKTypeId,
						State	= @State,
						Flag	= 0,
						GoodsOrder	= @GoodsOrder,
						GoodsNumber = @GoodsNumber,
						CargoID=@CargoID,
						ValidDate	=@ValidDate,
						ProduceDate=@ProduceDate,
						ItemID		=@ItemID,
						IsCombined	=@IsCombined,
						LendState=@LendState
				WHERE	Serial  = @Serial
				
			IF @@ROWCOUNT = 0
				RETURN -901
			END
		END
		/********红冲最近的单据是仓库入库单，怎做入库处理*********/
		ELSE IF @BillType=418
		BEGIN
			SELECT 	TOP 1 
				@PTypeId = PTypeId,
				@inKTypeId	= inKTypeId,
				@outKTypeId = outKTyeId,
				@State = State,
				@GoodsOrder = GoodsOrder,
				@GoodsNumber = GoodsNumber,
				@CargoID=CargoID,
				@ValidDate	=ValidDate,
				@ProduceDate=ProduceDate,
				@ItemID		=ItemID,
				@IsCombined	=IsCombined,
				@LendState=LendState
			FROM 	Fact_InOutPTypeSerial 
			WHERE 	Serial = @Serial 
					AND BillNumberId = @recBillNumberId 
					AND State=1
			
			IF @@ROWCOUNT <> 0
			BEGIN
				UPDATE	Gp_FactPTypeSerial
				SET		PTypeId = @PTypeId,
						KTypeId = @inKTypeId,
						State	= @State,
						Flag	= 1,
						GoodsOrder	= @GoodsOrder,
						GoodsNumber = @GoodsNumber,
						CargoID=@CargoID,
						ValidDate	=@ValidDate,
						ProduceDate=@ProduceDate,
						ItemID		=@ItemID,
						IsCombined	=@IsCombined,
						LendState=@LendState
				WHERE	Serial  = @Serial
				
				IF @@ROWCOUNT = 0
					RETURN -901
			END
		END
	END	
	FETCH NEXT FROM SerialCursor INTO @Serial
END	

CLOSE SerialCursor
DEALLOCATE SerialCursor

--重算当前序列号库中的STypeId
--性能优化：以前没加条件判断，是更新所有库存序列号，容易造成死锁
UPDATE	GP_FactPTypeSerial
SET		STypeId = S.STypeID
FROM    GP_FactPTypeSerial C,
		Stock S
WHERE	C.KtypeID = S.typeId		
		AND EXISTS
		(
			SELECT a.Serial 
			FROM Fact_InOutPTypeSerial a
			WHERE a.BillNumberId = @BillNumberId
			AND a.Serial=c.Serial
		)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialRedWord_sGrid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialRedWord_sGrid]
GO



/*
	作者：谢吉康
	时间：2009-12-29 
	原因：重写序列号红冲的算法【单仓库序列号】
	
	修改: 冯波
*/
CREATE  PROCEDURE Gp_SerialRedWord_sGrid
(
	@BillNumberId	varchar(50),	-- 单据编号
	@intBillType	int				-- 单据类型
)
--@encode$--
AS
SET NOCOUNT ON	
DECLARE @IOPSBilNumID 		int,			--序列号出入库中的BillNumberID
		@BilNumID 			int,			--主索引表中的BillNumberID
		@SrcSerial			varchar(200),	--查询的序列号
		@RedSerial_SQL 		varchar(8000),	--使用游标的SQL
		--@DelID				int,			--需要删除的单据的过帐ID   BillIndex->ID
		@MaxID				int,			--需要删除最大单据的过帐ID GP_InOutPTypeSerial->BillIndex->ID
		@singleSerial		varchar(100),	--单个的序列号
		@laterSerial		varchar(100),	--Gp_InOutPTypeSerial中的序列号
		@CruOutKTypeId		varchar(100),	--当前单据的出库仓库的ID
		@CruInKTypeId		varchar(100),	--当前单据的入库仓库的ID
		@recBillId 			int,			--最近单据的物流过账真是的ID
		@CruBillType 		int,												
		@PTypeId			varchar(100),	--商品的Id
		@BTypeId1			varchar(100),	--客户
		@BTypeId2			varchar(100),	--供货商
		@inKTypeId			varchar(100),	--入库仓库的Id
		@outKTypeId			varchar(100),	--出库仓库的Id
		@inKTypeTime		datetime,		--入库时间
		@OutKTypeTime		datetime,		--出库时间
		@State				int,			--序列号的状态
		@Flag				int,			--判断是否在库
		@BillType			int,			--单据类型
		@tmpBillNumberId	int,			--临时的BillNumberId
		@recBillNumberId 	int,				--最近的Id
		@recBillNumberId1 	int,				--最近的Id billindex
		@recBillNumberId2 	int,				--最近的Id PosAllotApplyBillIndex
		@ID					NUMERIC(10,0),
		@OldSerial			VARCHAR(50),
		@LastSerial			VARCHAR(50),
		@CostPrice			 NUMERIC(24, 10) ,	--成本单价
		@GoodsOrder			INT,			--批次
		@GoodsNumber		VARCHAR(100),	--批号
		@CargoID			INT,
		@ValidDate			VARCHAR(50),
		@ProduceDate		VARCHAR(50),
		@ItemID				INT,
		@IsCombined			INT,
		@IfWx				INT,
		@NowState			TINYINT,
		@LastState			TINYINT,
		@NowKTypeId			VARCHAR(50),
		@OldKTypeId			VARCHAR(50),
		@nowFlag            INT,
		@Ktypeidout 	VARCHAR(50),
		@Ktypeidin	VARCHAR(50),
		@InoutID    INT,
		@InoutID1  INT,
		@InoutID2  INT,
		@costing INT ,
		@NowInktypeid 	varchar(100),
		@NowOutktypeid varchar(100)

--获取需要删除的单据的过帐Id
--SELECT @DelID = [ID] FROM BillIndex WHERE BillNumberID = @BillNumberID

SELECT @IfWx = [ifwx] FROM BillIndex WHERE BillNumberID = @BillNumberID

SET @recBillNumberId = 0
SET @recBillNumberId1 = 0
SET @recBillNumberId2 = 0
SELECT @costing=SubValue FROM dbo.sysdata WHERE SubName='costing'

--循环处理序列号
DECLARE SerialSingleCursor CURSOR FOR
	SELECT Serial,State,InKtypeID,OutKtyeID FROM Gp_InOutPTypeSerial WHERE BillNumberId = @BillNumberId AND BillType = @intBillType AND BillType NOT IN (71,72,87,88,203)
	

OPEN SerialSingleCursor

FETCH NEXT FROM SerialSingleCursor INTO @singleSerial,@NowState,@NowInktypeid,@NowOutktypeid
--如果结果集不为空
WHILE @@FETCH_STATUS = 0	
	BEGIN
		SET @recBillNumberId = 0
		SET @recBillNumberId1 = 0
        SET @recBillNumberId2 = 0
        SET @nowFlag =0
		
		--查询红冲前的最近一张单据		
		SELECT TOP 1 @ID=MIN(ID) FROM gp_inoutPtypeSerial WHERE Serial=@singleSerial and BillNumberid=@BillNumberID AND BillType = @intBillType
		SELECT @nowFlag=Flag FROM dbo.gp_CruPtypeSerial WHERE Serial=@singleSerial
		
		SELECT @OldSerial = dbo.F_GetOldSerial(@singleSerial,@ID) 
		IF ISNULL(@OldSerial,'')='' SET @OldSerial=@singleSerial
		
		--SELECT '最近一张单据' ,@ID,@OldSerial,@singleSerial,@nowFlag
		
		--普通单据
		IF EXISTS(
			SELECT	TOP 1 1				
			FROM	gp_inoutPtypeSerial a,
					BillIndex Bil
			WHERE	a.BillNumberid=bil.BillNumberId
					AND a.ID<@ID
					AND A.Serial = @OldSerial
					AND Bil.RedWord =0 
					AND Bil.IfCheck = 't' 
					AND a.BillType NOT IN (71,72,87,88,203,327,328,329) AND a.BillType =bil.BillType						
			ORDER BY a.ID DESC
		)
		BEGIN
		   
			SELECT	TOP 1 
			        @InoutID1=a.id,
					@recBillNumberId1 = ISNULL(a.BillNumberId,0),
					@BillType = a.BillType,
					@Ktypeidout=a.OutKtyeID,
					@Ktypeidin=a.InKtypeID,
					@LastState=a.State,
					@OldKTypeId = CASE
										WHEN ISNULL(InKtypeID,'') <> '' THEN InKtypeID
										WHEN ISNULL(OutKtyeID,'') <> '' THEN OutKtyeID
								  END
			FROM	gp_inoutPtypeSerial a,
					BillIndex Bil
			WHERE	a.BillNumberid=bil.BillNumberId
					AND a.ID<@ID
					AND A.Serial = @OldSerial
					AND Bil.RedWord =0 
					AND Bil.IfCheck = 't' 
					AND a.BillType NOT IN (71,72,87,88,203,327,328,329)AND a.BillType =bil.BillType		 				
			ORDER BY a.ID DESC	
		

             IF (@costing<>3 AND @BillType<>57)--手工指定时处理成本单价，手工指定成本，并且上一张单据为成本调价单时，不用下面的限制，因为成本调价单序列号出入库表中state=1，但是却记录的是出库仓库id敏捷4883
             BEGIN
			 IF(@nowFlag=1 AND ISNULL(@Ktypeidout,'') = '' AND @NowOutktypeid<>'10000') ---红冲在库单据，找前一张出库不为空的,，如果前一张单据出库为空，就不是
				BEGIN
				 SET @recBillNumberId1=0
				END	
			ELSE
			    IF(@nowFlag=0 AND ISNULL(@Ktypeidin,'') = '' AND @NowOutktypeid<>'10000')
			    BEGIN
			     SET @recBillNumberId1=0
			    END
			END
		END
		--SELECT '@recBillNumberId1', @recBillNumberId1,'@LastState',@LastState,'@NowState',@NowState,@OldKTypeId,@Ktypeidout,@Ktypeidin
		--门店配送类单据327 328 329
		IF EXISTS(
			SELECT	TOP 1 1				
			FROM	gp_inoutPtypeSerial a,
					dbo.PosAllotApplyBillIndex Bil
			WHERE	a.BillNumberid=bil.BillNumberId
					AND a.ID<@ID
					AND A.Serial = @OldSerial
					AND Bil.RedWord =0 
					AND Bil.IfCheck = 't' 
					AND a.BillType  IN (327,328,329)AND a.BillType =bil.BillType		 				
			ORDER BY a.ID DESC
		)
		BEGIN
		  
			SELECT	TOP 1 
			        @InoutID2=a.id,
					@recBillNumberId2 = ISNULL(a.BillNumberId,0),
					@BillType = a.BillType,
					@Ktypeidout=a.OutKtyeID,
					@Ktypeidin=a.InKtypeID,
					@LastState=a.State,
					@OldKTypeId = CASE
										WHEN ISNULL(a.InKtypeID,'') <> '' THEN a.InKtypeID
										WHEN ISNULL(a.OutKtyeID,'') <> '' THEN a.OutKtyeID
								  END
			FROM	gp_inoutPtypeSerial a,
					PosAllotApplyBillIndex Bil
			WHERE	a.BillNumberid=bil.BillNumberId
					AND a.ID<@ID
					AND A.Serial = @OldSerial
					AND Bil.RedWord =0 
					AND Bil.IfCheck = 't' 
					AND a.BillType IN (327,328,329) AND a.BillType =bil.BillType						
			ORDER BY a.ID DESC
			 IF (@costing<>3 AND @BillType<>57)--手工指定时处理成本单价，手工指定成本，并且上一张单据为成本调价单时，不用下面的限制，因为成本调价单序列号出入库表中state=1，但是却记录的是出库仓库id敏捷4883
             BEGIN
			 IF(@nowFlag=1 and ISNULL(@Ktypeidout,'') = '') ---红冲在库单据，找前一张出库不为空的
				BEGIN
				 SET @recBillNumberId2=0
				END	
			ELSE
			    IF(@nowFlag=0 AND ISNULL(@Ktypeidin,'') = '')
			    BEGIN
			     SET @recBillNumberId2=0
			    END
		     END
		END
			--SELECT '@recBillNumberId12', @recBillNumberId2,'@LastState',@LastState,'@NowState',@NowState,@OldKTypeId
		
		--991新增门店配送单，上一张单据主表可能是billindex，可能是PosAllotApplyBillIndex，可能两个查出来都只值，取id 最小的那个
		IF(@recBillNumberId1<>0 AND @recBillNumberId2<>0)
		BEGIN
		    SET @recBillNumberId=(SELECT BillNumberid FROM gp_inoutPtypeSerial WHERE id=(SELECT TOP 1 max(ID) FROM gp_inoutPtypeSerial WHERE  BillNumberid IN(@recBillNumberId1,@recBillNumberId2) AND Serial=@singleSerial))
			SET @inoutid=(SELECT TOP 1 max(ID) FROM gp_inoutPtypeSerial WHERE  BillNumberid IN(@recBillNumberId1,@recBillNumberId2) AND Serial=@singleSerial)        
		END
		ELSE IF(@recBillNumberId1<> 0 AND @recBillNumberId2=0)
		BEGIN
		SET @recBillNumberId=@recBillNumberId1
		SET @inoutid=@inoutid1
		END
		ELSE IF(@recBillNumberId2<>0 AND @recBillNumberId1=0)
		BEGIN
		SET @recBillNumberId=@recBillNumberId2
		SET @inoutid=@inoutid2
		END
		ELSE SET @recBillNumberId=0
			
	--  SELECT '@recBillNumberId', @recBillNumberId,'@LastState',@LastState,'@NowState',@NowState,@OldKTypeId,@inoutid
        
						
		--如果当前序列号状态是出库类，且最近一次的单据中该序列号也是出库类，则将@recBillNumberID设置为0
		IF @NowState IN (2,3,4,5,8,9,10,11,13,14,15,16,18,19,21,26,27,28,29,30,31,35) 
			AND @LastState IN (2,3,4,5,8,9,10,11,13,14,15,16,18,19,21,26,27,28,29,30,31,35)
		BEGIN		
			IF @NowState<>2 AND @LastState<>13
			BEGIN
				--排除特殊情况，先委托发货，然后委托代销结算这种，是不能变成0的
				SET @recBillNumberId=0
			END
			
			--跨分支机构序列号
			SELECT TOP 1 @NowKTypeId = KTypeId FROM dbo.gp_CruPtypeSerial WHERE Serial = @singleSerial
			
			IF @OldKTypeId <> @NowKTypeId and  @OldKTypeId<>'10000' and @NowKTypeId<>'10000' --敏捷bug,代销库不计入判断仓库判断
			BEGIN
				--相同状态但是仓库信息不同了，跨了分支机构，则需要回到期初去找状态
				SET @recBillNumberId=0 
			END
		END
					
		IF @LastState IN (1,7) AND EXISTS(
			SELECT Serial FROM dbo.gp_CruPtypeSerial
			WHERE Serial=@OldSerial AND State IN (1,7)
		)
		BEGIN
			--如果上一个状态是在库，目前也是在库，那么就不能红冲然后再回到在库状态
			IF @LastState=7 AND NOT EXISTS(
			SELECT Serial FROM dbo.gp_CruPtypeSerial
			WHERE Serial=@OldSerial AND State=1)
			BEGIN
				--如果上一个状态是在库，目前也是在库，那么就不能红冲然后再回到在库状态
				--排除特殊情况：当前是库存中，上一步是受托代销库存中；譬如先受托代销收货，再受托代销结算，之后红冲受托代销结算的这种情形
				RETURN -969
			END			
		END
		
	--	SELECT @NowState,@OldSerial,@LastState,@recBillNumberId,@inoutid
		
		IF @recBillNumberId = 0	--之前没有单据了，判断是否有期初序列号了
			BEGIN	
				SELECT 	TOP 1 
						@PTypeId = PTypeId,
						@inKTypeId	= KTypeId,
						@BTypeId1	= BTypeId1,
						@BTypeId2 = BTypeId2,
						@State = State,
						@Flag = Flag,
						@CostPrice = CostPrice,
						@GoodsOrder = GoodsOrder,
						@GoodsNumber = GoodsNumber,
						@CargoID=CargoID,
						@ValidDate	=ValidDate,
						@ProduceDate=ProduceDate,
						@ItemID		=ItemID,
						@IsCombined	=IsCombined							
				FROM 	Gp_initPTypeSerial 
				WHERE 	Serial = @OldSerial

				--如果有期初序列号
				IF @@ROWCOUNT <> 0
					BEGIN
						UPDATE	Gp_CruPTypeSerial
						SET		KTypeId	= @inKTypeId,
								PTypeId = @PTypeId,
								BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
								BTypeId2= CASE WHEN ISNULL(@BTypeid2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
								State	= @State,
								Flag	= @Flag,
								CommissionState = CASE 
														WHEN @intBillType = 145 THEN 0
														WHEN @intBillType = 146 THEN 0	
														WHEN ISNULL(CommissionState,'')='' THEN NULL
														ELSE ISNULL(CommissionState,'') 
												  END,
								CostPrice = @CostPrice,
								GoodsOrder = @GoodsOrder,
								GoodsNumber = @GoodsNumber,
								CargoID=@CargoID,
								ValidDate	=@ValidDate,
								ProduceDate=@ProduceDate,
								ItemID		=@ItemID,
								IsCombined	=@IsCombined
						WHERE	Serial  = @singleSerial
						
						IF @@ROWCOUNT = 0
							RETURN -901
					END
				ELSE
					BEGIN
							--SELECT 2,2
							DELETE FROM Gp_CruPTypeSerial WHERE Serial = @singleSerial
						
						IF @@ROWCOUNT = 0
								RETURN -900
					END
			END				
		ELSE		--**********************************************************************************如果红冲单据最近的一张单据是调拨等双仓库单据（特殊处理）**********************************************************************************
			BEGIN							
				IF @BillType IN (17,21,16,160,161,166,172,173,174,175)
					BEGIN
						--调拨退回到入库的状态
						IF @BillType IN (17,21,173,174,175) 
							BEGIN
								SELECT 	TOP 1 
										@PTypeId = PTypeId,
										@inKTypeId	= inKTypeId,
										@outKTypeId = outKTyeId,
										@BTypeId1 = BTypeId1,
										@BTypeId2 = BTypeId2,
										@State = State,
										@CostPrice = CostPrice,
										@GoodsOrder = GoodsOrder,
										@GoodsNumber = GoodsNumber,
										@CargoID=CargoID,
										@ValidDate	=ValidDate,
										@ProduceDate=ProduceDate,
										@ItemID		=ItemID,
										@IsCombined	=IsCombined 
								FROM 	Gp_InOutPTypeSerial 
								WHERE 	Serial = @OldSerial 
										AND BillNumberId = @recBillNumberId 
										AND State IN (1,7,25) 
										AND BillType NOT IN (71,72,87,88,203)
								
								IF @@ROWCOUNT <> 0
									BEGIN
										UPDATE	Gp_CruPTypeSerial
										SET		PTypeId = @PTypeId,
												BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
												BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
												KTypeId = @inKTypeId,
												State	= CASE
																WHEN @intBillType = 145 THEN 7
																ELSE @State
														  END,
												Flag	= 1,
												CommissionState = CASE 
																		WHEN @BillType = 144 THEN 0 
																		WHEN @intBillType = 145 THEN 0
																		WHEN @intBillType = 146 THEN 0
																		WHEN ISNULL(CommissionState,'')='' THEN NULL
																		ELSE ISNULL(CommissionState,'') 
																  END,
												CostPrice	= @CostPrice,
												GoodsOrder	= @GoodsOrder,
												GoodsNumber = @GoodsNumber,
												CargoID=@CargoID,
												ValidDate	=@ValidDate,
												ProduceDate=@ProduceDate,
												ItemID		=@ItemID,
												IsCombined	=@IsCombined
										WHERE	Serial  = @singleSerial
										
										IF @@ROWCOUNT = 0
											RETURN -901
									END
							END
						ELSE
							BEGIN
								--如果红冲的序列号在入库的仓库中,则状态为库存中
								IF EXISTS(SELECT TOP 1 Serial FROM Gp_InOutPTypeSerial WHERE Serial = @OldSerial AND BillNumberId = @recBillNumberId AND State IN (1,7,25) AND BillType NOT IN (71,72,87,88,203))
									BEGIN
										SELECT 	TOP 1
												@PTypeId 	= PTypeId,
												@inKTypeId	= CASE BillType WHEN 57 THEN OutKtyeID ELSE inKTypeId END,
												@outKTypeId = outKTyeId,
												@BTypeId1	= BTypeId1,
												@BTypeId2	= BTypeId2,
												@State		= State,
												@CostPrice = CostPrice,
												@GoodsOrder = GoodsOrder,
												@GoodsNumber = GoodsNumber,
												@CargoID=CargoID,
												@ValidDate	=ValidDate,
												@ProduceDate=ProduceDate,
												@ItemID		=ItemID,
												@IsCombined	=IsCombined
										FROM	Gp_InOutPTypeSerial
										WHERE	Serial = @OldSerial	
												AND BillNumberId = @recBillNumberId					
												AND State IN (1,7,25)
												AND BillType NOT IN (71,72,87,88,203)
										
										IF @@ROWCOUNT <> 0
											BEGIN
												UPDATE	Gp_CruPTypeSerial
												SET		PTypeId = @PTypeId,
														BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
														BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
														KTypeId = @inKTypeId,
														State	= CASE
																		WHEN @intBillType = 145 THEN 7
																		ELSE @State
																  END,
														Flag	= 1,
														CommissionState = CASE 
																		WHEN @BillType = 144 THEN 0 
																		WHEN @intBillType = 145 THEN 0
																		WHEN @intBillType = 146 THEN 0
																		WHEN ISNULL(CommissionState,'')='' THEN NULL
																		ELSE ISNULL(CommissionState,'') 
																  END,
														CostPrice	= @CostPrice,
														GoodsOrder	= @GoodsOrder,
														GoodsNumber = @GoodsNumber,
														CargoID=@CargoID,
														ValidDate	=@ValidDate,
														ProduceDate=@ProduceDate,
														ItemID		=@ItemID,
														IsCombined	=@IsCombined
												WHERE	Serial  = @singleSerial
												
												IF @@ROWCOUNT = 0
													RETURN -901
											END
									END
								ELSE
									--如果是出库的序列号
									BEGIN
										SELECT 	TOP 1
												@PTypeId 	= PTypeId,
												@inKTypeId	= CASE BillType WHEN 57 THEN OutKtyeID ELSE inKTypeId END,
												@outKTypeId = outKTyeId,
												@BTypeId1	= BTypeId1,
												@BTypeId2	= BTypeId2,
												@State		= State,
												@CargoID=CargoID,
												@ValidDate	=ValidDate,
												@ProduceDate=ProduceDate,
												@ItemID		=ItemID,
												@IsCombined	=IsCombined
										FROM	Gp_InOutPTypeSerial
										WHERE	Serial		= @OldSerial	
												AND BillNumberId = @recBillNumberId					
												AND State NOT IN (1,7,25)
												AND BillType NOT IN (71,72,87,88,203)
										
										IF @@ROWCOUNT <> 0
											BEGIN
												UPDATE	Gp_CruPTypeSerial
												SET		PTypeId = @PTypeId,
														BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
														BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
														KTypeId = @outKTypeId,
														State	= @State,
														Flag	= 0,
														CommissionState = CASE 
																			WHEN @intBillType = 146 THEN 0
																			WHEN @intBillType = 145 THEN 0
																			WHEN @intBillType = 144 THEN NULL
																			WHEN ISNULL(CommissionState,'')='' THEN NULL
																			ELSE ISNULL(CommissionState,'') 
																  		  END,
														CostPrice	= @CostPrice,
														GoodsOrder	= @GoodsOrder,
														GoodsNumber = @GoodsNumber,
														CargoID=@CargoID,
														ValidDate	=@ValidDate,
														ProduceDate=@ProduceDate,
														ItemID		=@ItemID,
														IsCombined	=@IsCombined
												WHERE	Serial  = @singleSerial
												
												IF @@ROWCOUNT = 0
													RETURN -901
											END
									END
							END
					END
				ELSE	--**********************************************************************************如果红冲单据最近的一张单据是普通单据**********************************************************************************
					BEGIN
	
						SELECT 	TOP 1
								@PTypeId 	= PTypeId,
								@inKTypeId	= CASE BillType WHEN 57 THEN OutKtyeID ELSE inKTypeId END,
								@outKTypeId	= outKTyeId,
								@BTypeId1	= BTypeId1,
								@BTypeId2	= BTypeId2,
								@State		= State,
								@CostPrice = CostPrice,
								@GoodsOrder = GoodsOrder,
								@GoodsNumber = GoodsNumber,
								@CargoID=CargoID,
								@ValidDate	=ValidDate,
								@ProduceDate=ProduceDate,
								@ItemID		=ItemID,
								@IsCombined	=IsCombined
						FROM	Gp_InOutPTypeSerial
						WHERE	Serial = @OldSerial						
								AND BillNumberId = @recBillNumberId AND ID=@Inoutid--加一个这个，不然会出现一个序列号有相同的billnumberid的两条不同状态的数据，就找不到对应的正确的state
								AND BillType NOT IN (71,72,87,88,203)
                                
						IF @@ROWCOUNT <> 0
							BEGIN								
								IF (ISNULL(@inKTypeId,'')='10000' OR ISNULL(@outKTypeId,'')='10000')	--**********************如果是代销结算的单据则特殊处理代销结算单据**********************
									BEGIN
										--SELECT  @recBillId = Id FROM BillIndex WHERE BillNumberId = @recBillNumberId
										SELECT  @recBillId = MIN(Id) FROM Gp_InOutPTypeSerial WHERE BillNumberId = @recBillNumberId	AND Serial=@OldSerial
										SELECT  @LastSerial=dbo.F_GetOldSerial(@OldSerial,@recBillId)
										IF ISNULL(@LastSerial,'')='' SET @LastSerial=@OldSerial
										
										SELECT	TOP 1
												@CruBillType   = G.BillType,
												@CruInKTypeId  = G.inKTypeId,
												@CruOutKTypeId = G.outKTyeId,
												@CargoID=CargoID,
												@ValidDate	=ValidDate,
												@ProduceDate=ProduceDate,
												@ItemID		=ItemID,
												@IsCombined	=IsCombined
										FROM	Gp_InOutPTypeSerial G,
												BillIndex B
										WHERE	G.BillNumberId = B.BillNumberId
												AND g.Serial = @LastSerial
												AND B.IfCheck = 't'
												AND B.RedWord = 0
												AND G.BillType NOT IN (71,72,87,88,203)
												AND (ISNULL(G.inKTypeId,'')<>'10000' AND ISNULL(G.outKTyeId,'')<>'10000')
												AND G.Id<@recBillId
										ORDER BY G.Id DESC

										IF @@ROWCOUNT = 0
											BEGIN
												SELECT 	TOP 1
														@PTypeId 	= PTypeId,
														@inKTypeId	= KTypeId,
														@BTypeId1	= BTypeId1,
														@BTypeId2	= BTypeId2,
														@State		= State,
														@Flag		= Flag,
														@CostPrice = CostPrice,
														@GoodsOrder = GoodsOrder,
														@GoodsNumber = GoodsNumber,
														@CargoID=CargoID,
														@ValidDate	=ValidDate,
														@ProduceDate=ProduceDate,
														@ItemID		=ItemID,
														@IsCombined	=IsCombined
												FROM	Gp_initPTypeSerial
												WHERE	Serial 		= @LastSerial

												IF @@ROWCOUNT <> 0
													BEGIN
														UPDATE	Gp_CruPTypeSerial
														SET		KTypeId	= @inKTypeId,
																PTypeId	= @PTypeId,
																BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																BTypeId2= CASE WHEN ISNULL(@BTypeid2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																State	= CASE WHEN @State IN (1,7,25) THEN 1 ELSE 2 END,
																Flag	= @Flag,
																CommissionState = CASE 
																						WHEN @intBillType = 145 THEN 0
																						WHEN @intBillType = 146 THEN 0	
																						WHEN ISNULL(CommissionState,'')='' THEN NULL
																						ELSE ISNULL(CommissionState,'') 
																				  END,
																CostPrice = @CostPrice,
																GoodsOrder = @GoodsOrder,
																GoodsNumber = @GoodsNumber,
																CargoID=@CargoID,
																ValidDate	=@ValidDate,
																ProduceDate=@ProduceDate,
																ItemID		=@ItemID,
																IsCombined	=@IsCombined
														WHERE	Serial  = @singleSerial
														
														IF @@ROWCOUNT = 0
															RETURN -901
													END
												ELSE
													BEGIN
														--SELECT 1.1
														DELETE FROM Gp_CruPTypeSerial WHERE Serial = @singleSerial
														
														IF @@ROWCOUNT = 0
															RETURN -900
													END
											END
										ELSE
											BEGIN 
												IF @CruBillType IN (17,21,16,160,161,166,172,173,174,175) 
													BEGIN
														IF @State IN (1,7,25)
															SELECT	TOP 1
																	@CruInKTypeId  = G.inKTypeId,
																	@CruOutKTypeId = G.outKTyeId,
																	@CostPrice = g.CostPrice,
																	@GoodsOrder = g.GoodsOrder,
																	@GoodsNumber = g.GoodsNumber,
																	@CargoID=CargoID,
																	@ValidDate	=ValidDate,
																	@ProduceDate=ProduceDate,
																	@ItemID		=ItemID,
																	@IsCombined	=IsCombined
															FROM	Gp_InOutPTypeSerial G,
																	BillIndex B
															WHERE	G.BillNumberId = B.BillNumberId
																	AND g.Serial = @LastSerial
																	AND B.IfCheck = 't'
																	AND B.RedWord = 0
																	AND G.BillType NOT IN (71,72,87,88,203)
																	AND (ISNULL(G.inKTypeId,'')<>'10000' AND ISNULL(G.outKTyeId,'')<>'10000')
																	AND G.Id<@recBillId
																	AND G.State IN (1,7,25)
															ORDER BY G.Id DESC
														ELSE
															SELECT	TOP 1
																	@CruBillType   = G.BillType,
																	@CruInKTypeId  = G.inKTypeId,
																	@CruOutKTypeId = G.outKTyeId,
																	@CostPrice = g.CostPrice,
																	@GoodsOrder = g.GoodsOrder,
																	@GoodsNumber = g.GoodsNumber,
																	@CargoID=CargoID,
																	@ValidDate	=ValidDate,
																	@ProduceDate=ProduceDate,
																	@ItemID		=ItemID,
																	@IsCombined	=IsCombined
															FROM	Gp_InOutPTypeSerial G,
																	BillIndex B
															WHERE	G.BillNumberId = B.BillNumberId
																	AND g.Serial = @LastSerial
																	AND B.IfCheck = 't'
																	AND B.RedWord = 0
																	AND G.BillType NOT IN (71,72,87,88,203)
																	AND (ISNULL(G.inKTypeId,'')<>'10000' AND ISNULL(G.outKTyeId,'')<>'10000')
																	AND G.Id<@recBillId
																	AND G.State NOT IN (1,7,25)
															ORDER BY G.Id DESC
													END
												ELSE
													BEGIN
														SELECT	TOP 1
																@CruBillType   = G.BillType,
																@CruInKTypeId  = G.inKTypeId,
																@CruOutKTypeId = G.outKTyeId,
																@CostPrice = g.CostPrice,
																@GoodsOrder = g.GoodsOrder,
																@GoodsNumber = g.GoodsNumber,
																@CargoID=CargoID,
																@ValidDate	=ValidDate,
																@ProduceDate=ProduceDate,
																@ItemID		=ItemID,
																@IsCombined	=IsCombined
														FROM	Gp_InOutPTypeSerial G,
																BillIndex B
														WHERE	G.BillNumberId = B.BillNumberId
																AND g.Serial = @LastSerial
																AND B.IfCheck = 't'
																AND B.RedWord = 0
																AND G.BillType NOT IN (71,72,87,88,203)
																AND (ISNULL(G.inKTypeId,'')<>'10000' AND ISNULL(G.outKTyeId,'')<>'10000')
																AND G.Id<@recBillId
														ORDER BY G.Id DESC
													END

												IF @State IN (1,7,25)
													BEGIN
														UPDATE	Gp_CruPTypeSerial
														SET		PTypeId = @PTypeId,
																BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																KTypeId = CASE 
																				WHEN (ISNULL(@inKTypeId,'')<>'' AND ISNULL(@inKTypeId,'')<>'10000') THEN @inKTypeId 
																				WHEN (ISNULL(@inKTypeId,'')='10000' OR ISNULL(@outKTypeId,'')='10000') THEN @CruInKTypeId
																				ELSE KTypeId 
																		  END,
																State	= 1,
																Flag	= 1,
																CommissionState = CASE 
																						WHEN @BillType = 144 THEN 0 
																						WHEN @intBillType = 145 THEN 0
																						WHEN @intBillType = 146 THEN 0
																						WHEN ISNULL(CommissionState,'')='' THEN NULL
																						ELSE ISNULL(CommissionState,'') 
																				  END,
																CostPrice = @CostPrice,
																GoodsOrder = @GoodsOrder,
																GoodsNumber = @GoodsNumber,
																CargoID=@CargoID,
																ValidDate	=@ValidDate,
																ProduceDate=@ProduceDate,
																ItemID		=@ItemID,
																IsCombined	=@IsCombined
														WHERE	Serial  = @singleSerial									
														
														IF @@ROWCOUNT = 0
															RETURN -901
													END
												ELSE
													BEGIN
														UPDATE	Gp_CruPTypeSerial
														SET		PTypeId = @PTypeId,
																BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
																BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
																KTypeId = CASE 
																			WHEN (ISNULL(@outKTypeId,'')<>'' AND ISNULL(@outKTypeId,'')<>'10000') THEN @outKTypeId
																			WHEN (ISNULL(@inKTypeId,'')='10000' OR ISNULL(@outKTypeId,'')='10000') THEN @CruOutKTypeId
																			ELSE KTypeId 
																		  END,
																State	= CASE  
																				WHEN @intBillType IN (145,188,141) THEN @State
																				WHEN ISNULL(CommissionState,'')='0' THEN @State 
																				ELSE 2 
																		  END,
																Flag	= 0,
																CommissionState = CASE 
																						WHEN @intBillType = 146 THEN 0
																						WHEN @intBillType = 145 THEN 0
																						WHEN @intBillType = 144 THEN NULL
																						WHEN ISNULL(CommissionState,'')='' THEN NULL
																						ELSE ISNULL(CommissionState,'') 
																				  END,
																CostPrice = @CostPrice,
																GoodsOrder = @GoodsOrder,
																GoodsNumber = @GoodsNumber,
																CargoID=@CargoID,
																ValidDate	=@ValidDate,
																ProduceDate=@ProduceDate,
																ItemID		=@ItemID,
																IsCombined	=@IsCombined
														WHERE	Serial  = @singleSerial									
														
														IF @@ROWCOUNT = 0
															RETURN -901
													END													
											END
									END
								ELSE												--**********************如果是不是结算的单据则按照状态处理**********************
									BEGIN
										IF @State IN (1,7,25)
											BEGIN
											  --SELECT @State,@inKTypeId
												--SELECT '?????'
												UPDATE	Gp_CruPTypeSerial
												SET		PTypeId = @PTypeId,
														BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
														BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
														KTypeId = CASE 
																		WHEN (ISNULL(@inKTypeId,'')<>'' AND ISNULL(@inKTypeId,'')<>'10000') THEN @inKTypeId
																		ELSE KTypeId 
																  END,
														State	= @State,
														Flag	= 1,
														CommissionState = CASE 
																				WHEN @BillType = 144 THEN 0 
																				WHEN @intBillType = 145 THEN 0
																				WHEN @intBillType = 146 THEN 0
																				WHEN ISNULL(CommissionState,'')='' THEN NULL
																				ELSE ISNULL(CommissionState,'') 
																		  END,
														CostPrice = @CostPrice,
														GoodsOrder = @GoodsOrder,
														GoodsNumber = @GoodsNumber,
														CargoID=@CargoID,
														ValidDate	=@ValidDate,
														ProduceDate=@ProduceDate,
														ItemID		=@ItemID,
														IsCombined	=@IsCombined
												WHERE	Serial  = @singleSerial									
												
												IF @@ROWCOUNT = 0
													RETURN -901
											END
										ELSE
											BEGIN
											--PRINT 2222
											--SELECT @State,@singleSerial
												UPDATE	Gp_CruPTypeSerial
												SET		PTypeId = @PTypeId,
														BTypeId1= CASE WHEN ISNULL(@BTypeId1,'')<>'' THEN @BTypeId1 ELSE BTypeId1 END,
														BTypeId2= CASE WHEN ISNULL(@BTypeId2,'')<>'' THEN @BTypeId2 ELSE BTypeId2 END,
														KTypeId = CASE 
																	WHEN (ISNULL(@outKTypeId,'')<>'' AND ISNULL(@outKTypeId,'')<>'10000') THEN @outKTypeId
																	ELSE KTypeId 
																  END,
														State	= @State,
														Flag	= 0,
														CommissionState = CASE 
																				WHEN @intBillType = 146 THEN 0
																				WHEN @intBillType = 145 THEN 0
																				WHEN @intBillType = 144 THEN NULL
																				WHEN ISNULL(CommissionState,'')='' THEN NULL
																				ELSE ISNULL(CommissionState,'') 
																		  END,
														CostPrice = @CostPrice,
														GoodsOrder = @GoodsOrder,
														GoodsNumber = @GoodsNumber,
														CargoID=@CargoID,
														ValidDate	=@ValidDate,
														ProduceDate=@ProduceDate,
														ItemID		=@ItemID,
														IsCombined	=@IsCombined
												WHERE	Serial  = @singleSerial									
													--PRINT 2222111
												IF @@ROWCOUNT = 0
													RETURN -901
											END
									END	
							END	
					END	
			END	
			
		
		--报损报溢维修类序列号，CARGOID始终为0
		IF @intBillType IN (14,9) AND @IfWx=1
		BEGIN
			UPDATE	Gp_CruPTypeSerial SET CargoID=0 WHERE	Serial  = @singleSerial	
		END
	
		FETCH NEXT FROM SerialSingleCursor INTO @singleSerial,@NowState,@NowInktypeid,@NowOutktypeid
	END	

CLOSE SerialSingleCursor
DEALLOCATE SerialSingleCursor

--重算当前序列号库中的STypeId
--性能优化：以前没加条件判断，是更新所有库存序列号，容易造成死锁
UPDATE	gp_CruPtypeSerial
SET		STypeId = S.STypeID
FROM    gp_CruPtypeSerial C,
		Stock S
WHERE	C.KtypeID = S.typeId		
		AND C.KtypeID <> '10000'
		AND EXISTS
		(
			SELECT a.Serial 
			FROM Gp_InOutPTypeSerial a
			WHERE a.BillNumberId = @BillNumberId
			AND a.Serial=c.Serial
		)
		
--SELECT * FROM gp_CruPtypeSerial		

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
DECLARE
	@BillNumberId	varchar(50),		-- 单据编号
	@intBillType	int,				-- 单据类型
	@intRet			INT
	
SELECT
	@BillNumberId=132087,
	@intBillType=11


BEGIN TRAN

SELECT state,* FROM dbo.gp_inoutPtypeSerial
WHERE Serial='862434049379132'

SELECT * FROM dbo.gp_CruPtypeSerial
WHERE Serial='862434049379132'

EXEC @intRet=Gp_SerialRedWord_sGrid
	@BillNumberId,
	@intBillType


SELECT @intRet

SELECT state,* FROM dbo.gp_inoutPtypeSerial
WHERE Serial='862434049379132'

SELECT * FROM dbo.gp_CruPtypeSerial
WHERE Serial='862434049379132'

ROLLBACK TRAN


*/



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SerialRedWordForLend]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SerialRedWordForLend]
GO










/*
	作者：谢吉康
	日期：2004-2-3
	描述：借欠序列号的红冲问题
*/
CREATE      PROCEDURE Gp_SerialRedWordForLend
(
	@BillNumberID	VARCHAR(50),	-- 单据编号
	@intBillType	VARCHAR(50)		-- 单据类型	
)
--@encode$--
AS
SET NOCOUNT ON 
--获取当前单据的ID号码
DECLARE @CurID	numeric(10,0),
		@OldID	numeric(10,0)

SELECT @CurID = ID FROM LendIndex WHERE BillNumberId = @BillNumberId
DECLARE @maxid NUMERIC(24,10)
SELECT  @maxid = ISNULL( MAX(ID),0)FROM Gp_InOutPTypeSerial WHERE BillNumberid = @BillNumberId AND BillType = @intBillType  

--SELECT @maxid AS '@maxid'
IF (@intBillType = '71' OR  @intBillType = '87') AND EXISTS(
	SELECT	TOP 1 1
	FROM Gp_InOutPTypeSerial a JOIN (
		SELECT Serial,ID FROM Gp_InOutPTypeSerial WHERE BillType  = CASE @intBillType WHEN '71' THEN 34 ELSE 11 END AND BillNumberid IN (
			SELECT BillNumberId FROM dbo.BillIndex WHERE BillType = CASE @intBillType WHEN '71' THEN 34 ELSE 11 END AND IsLend = 1 AND ifcheck = 't' AND RedWord=0
		)
	) b ON a.Serial = b.Serial
	WHERE a.BillNumberid = @BillNumberId
	AND a.BillType  = @intBillType  
	AND @maxid < b.ID
	AND @maxid <> 0
)
	BEGIN
		--RAISERROR('序列号被后续单据操作过，不允许删除单据！',16,1)
		RETURN -12
	END

IF EXISTS(
	SELECT	TOP 1 1
	FROM	LendIndex L,
			Gp_InOutPTypeSerial I
	WHERE	L.BillNumberId = I.BillNumberID
			AND CAST(L.ID as numeric(10,0))>CAST(@CurID as numeric(10,0))
			AND I.Serial IN (SELECT	Serial FROM Gp_InOutPTypeSerial WHERE BillNumberId = @BillNumberId AND BillType IN (71,72,87,88))		
			AND I.BillType IN (71,72,87,88)
)
	BEGIN
		--RAISERROR('序列号被后续单据操作过，不允许删除单据！',16,1)
		RETURN -12
	END
ELSE
	BEGIN
		--逐级分析序列号
		DECLARE @Serial 			varchar(100),
				@PreBillNumberId	numeric(18,0),
				@PreBillType		int,
				@BTypeId2			varchar(100),
				@BTypeId1			varchar(100),
				@BTypeId			varchar(100),
				@PTypeId			varchar(100),
				@KTypeId			varchar(100),
				@mngLendSerial		varchar(10),--系统采用序列号借欠出入库校验模式
				@Msg				VARCHAR(500)=''
				
		SELECT @mngLendSerial = Value FROM dbo.Userconfig WHERE ConfigName='mngLendSerial'
		DECLARE SerialCursor CURSOR FOR
			SELECT	Serial FROM Gp_InOutPTypeSerial WHERE BillNumberId = @BillNumberId AND BillType IN (71,72,87,88)

		OPEN SerialCursor

		FETCH NEXT FROM SerialCursor INTO @Serial

		WHILE @@FETCH_STATUS = 0
			BEGIN
				--如果序列号做过调整则不允许删
				--IF EXISTS(SELECT TOP 1 1 FROM SerialAdjustBill s,SerialAdjustIndex i 
				--		WHERE   I.BillNumberId=S.BillNumberId AND I.draft=0  and (s.OldSerial= 'я'+@Serial+'я'  OR s.Serial= 'я'+@Serial+'я') 
				--		)
				--BEGIN
				--	CLOSE SerialCursor
				--	DEALLOCATE SerialCursor
				--	RETURN -22
				--END
				
				--17	借进		71
				--18	借出		87
				--19	借进还出	72
				--20	借出还回	88

				IF @mngLendSerial = '1' --系统采用序列号借欠出入库校验模式
				BEGIN
					IF (@intBillType = '71'	OR 	@intBillType ='88 ') --------------------借进----借出还回-------------
						AND EXISTS( SELECT TOP 1 1 
						FROM dbo.gp_CruPtypeSerial 
						WHERE Serial= @Serial 
						AND State IN (2, 3, 4, 5, 8, 9, 10, 11, 13, 14, 15, 16, 18, 19, 21, 26, 27, 28, 29, 30, 31,34, 33))
					BEGIN
						/*
						--如果在借欠库中存在,则可以红冲回去 BUG 981 2271 这个情况比较复杂,还需要判断之前是什么状态,是否借出还回,再决定如何处理借欠库的记录,所以先延期;且以前销售出库单红冲,专门过滤掉了71,72,88这3类单据的
						IF NOT EXISTS(
							SELECT Serial
							FROM dbo.gp_LendPtypeSerial
							WHERE Serial=@Serial AND State=17
						)
						BEGIN
							
						END
						*/
						SET @Msg = '序列号【'+@Serial+'】在当前序列号库中已出库，不能红冲该单据!'
					END
					DECLARE @mid INT
					SELECT @mid= MAX(ISNULL(id,0)) FROM dbo.gp_inoutPtypeSerial WHERE Serial = @Serial AND BillNumberid = @BillNumberID
					--SELECT @mid AS '@mid'
					
					IF (@mid <> 0 AND @intBillType = '87' AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.gp_inoutPtypeSerial WHERE Serial = @Serial AND State IN (1, 6, 7, 17, 20, 25, 34) AND ID < @mid ORDER BY id DESC
					UNION ALL
					SELECT 1
					FROM dbo.gp_initPtypeSerial
					WHERE Serial = @Serial 							
					))
					
					
					OR (@mid <> 0 AND @intBillType = '72' AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.gp_inoutPtypeSerial WHERE Serial = @Serial AND State IN (1, 6, 7, 17, 25, 34) AND ID < @mid ORDER BY id DESC
					UNION ALL
					SELECT 1
					FROM dbo.gp_initPtypeSerial
					WHERE Serial = @Serial 							
					))
					BEGIN 
						IF (@intBillType = '87'		) -----------------借出---借进还出--------------
								AND EXISTS( SELECT TOP 1 1 
								FROM dbo.gp_CruPtypeSerial 
								WHERE Serial= @Serial 
								AND State IN (1, 6, 7, 17, 20, 25, 34))
						BEGIN
							SET @Msg = '序列号【'+@Serial+'】在当前序列号库存中已存在，不能红冲该单据!'
						END
						IF (@intBillType = '72'	) -----------------借出---借进还出--------------
								AND EXISTS( SELECT TOP 1 1 
								FROM dbo.gp_CruPtypeSerial 
								WHERE Serial= @Serial 
								AND State IN (1, 6, 7, 17, 25, 34))
						BEGIN
							SET @Msg = '序列号【'+@Serial+'】在当前序列号库存中已存在，不能红冲该单据!'
						END
					END 
					IF @Msg <> ''
					BEGIN
						CLOSE SerialCursor
						DEALLOCATE SerialCursor
						RAISERROR(@Msg,16,1)
						RETURN
					END 
				END
				
				--如果不存在以前的单据，则需要追到期初中判断
				/*
				IF NOT EXISTS(
					SELECT 	TOP 1 1
					FROM	LendIndex L,
							Gp_InOutPTypeSerial I
					WHERE	L.BillNumberId = I.BillNumberId
							AND L.ID < @CurID
							AND I.Serial = @Serial
							AND I.BillType IN (71,72,87,88)
				)
					BEGIN	--PRINT('处理期初')						
						IF EXISTS(SELECT TOP 1 1 FROM Gp_InitLendPTypeSerial WHERE Serial = @Serial)
							BEGIN
								SELECT 	@PTypeId	= PTypeId,
										@KTypeId 	= KTypeId,
										@BTypeId1 	= CASE WHEN Flag=0 THEN BTypeID1 ELSE NULL END,
										@BTypeId2	= CASE WHEN Flag=1 THEN BTypeId2 ELSE NULL END  
								FROM 	Gp_InitLendPTypeSerial 
								WHERE 	Serial = @Serial 
										--AND Flag = 1

								IF @@ROWCOUNT <> 0
									UPDATE	Gp_LendPTypeSerial
									SET		State 	= 17,
											Flag	= 1,
											BFlag	= 1,
											PTypeId = @PTypeId,
											KTypeId = @KTypeid,
											BTypeId2= @BTypeId2
									WHERE	Serial	= @Serial
								ELSE
									UPDATE	Gp_LendPTypeSerial
									SET		State 	= 18,
											Flag	= 0,
											BFlag	= 0,									
											BTypeId1= @BTypeId1
									WHERE	Serial	= @Serial									
							END
						ELSE							
							DELETE FROM Gp_LendPTypeSerial WHERE Serial = @Serial							
					END
					*/
				--ELSE	--PRINT('处理序列号的上张状态')
					--BEGIN						
						SELECT	TOP 1 @PreBillNumberId 	= L.BillNumberId,
								@PreBillType			= L.BillType,
								@BTypeId				= L.BTypeId,
								@KTypeId				= L.KTypeId,
								@PTypeId				= I.PTypeId
						FROM	LendIndex L,
								Gp_InOutPTypeSerial I
						WHERE	L.BillNumberId = I.BillNumberId
								AND I.BillType IN (71,72,87,88)
									AND I.Serial = @Serial
								AND L.ID<@CurId
						ORDER BY L.ID DESC
						
						IF @PTypeId IS NULL 
							SELECT	@KTypeId				= KTypeId
							FROM	LendIndex 
							WHERE BillNumberId = @BillNumberID
						IF @PTypeId IS NULL
							SELECT	@PTypeId				= PTypeId
							FROM  dbo.LendBill 
							WHERE BillNumberId = @BillNumberID AND CHARINDEX(@Serial,Serial) > 0
							
						IF @intBillType = '71'		-----------------借进-----------------
							DELETE  FROM  Gp_LendPTypeSerial WHERE Serial = @Serial
						ELSE IF @intBillType = '87'	-----------------借出-----------------
						BEGIN
						--87	借出开单   18
						--71	借进开单   17
						--88	借出还回单 20
						--72	借进还出单 19		
							IF NOT EXISTS(SELECT TOP 1 1 FROM Gp_InOutPTypeSerial WHERE BillType IN (71,88) AND Serial = @Serial)
							AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.gp_initLendPtypeSerial WHERE Serial = @Serial AND State = 17  )
							BEGIN
								DELETE  FROM  Gp_LendPTypeSerial WHERE Serial = @Serial
							END
							ELSE
							BEGIN
								
								DECLARE @bid INT = 0
								SELECT @bid = MAX(a.BillNumberid) FROM gp_inoutPtypeSerial a
								INNER JOIN dbo.BillIndex b
								ON a.BillNumberid=b.BillNumberId
								WHERE a.Serial=@Serial AND b.ifcheck='t' AND b.RedWord=0 AND b.BillType=34 AND a.State = 1 AND a.ID < @maxid 
								AND @PreBillType=b.BillType AND @PreBillNumberId=b.BillNumberId AND b.IsLend=1
								--SELECT @bid AS '@bid',@Serial AS '@Serial' ,@CurId AS '@CurId',@maxId '@maxId'
								IF @bid !=0
								BEGIN
									UPDATE T SET 
										T.PTypeId = @PTypeId,
										T.KTypeId = @KTypeid,
										T.BTypeId1= @BTypeId,
										T.STATE = 34,
										T.Flag =  1
										FROM  Gp_LendPTypeSerial T WHERE Serial = @Serial
								END
								ELSE IF 0 < (SELECT ISNULL(MAX(ID),0) FROM Gp_InOutPTypeSerial WHERE  BillType IN (71,88) AND Serial = @Serial)
								BEGIN
									UPDATE T SET 
									T.PTypeId = @PTypeId,
									T.KTypeId = @KTypeid,
									T.BTypeId1= @BTypeId,
									T.STATE = t1.STATE ,
									T.OutKtypeTime = NULL,
									T.Flag =  CASE WHEN t1.BillType  IN(71,88) THEN 1 ELSE 0 END 
									FROM  Gp_LendPTypeSerial T JOIN Gp_InOutPTypeSerial t1
									ON T.Serial = t1.Serial 
									WHERE BillType IN (71,88) AND t1.Serial = @Serial 
									AND t1.ID = (SELECT ISNULL(MAX(ID),0) FROM Gp_InOutPTypeSerial WHERE  BillType IN (71,88) AND Serial = @Serial)
								END
								ELSE
								BEGIN
									IF EXISTS(SELECT TOP 1 1 FROM dbo.gp_initLendPtypeSerial WHERE Serial = @Serial AND State = 17 )
									BEGIN
										UPDATE T SET 
										T.PTypeId = @PTypeId,
										T.KTypeId = @KTypeid,
										T.BTypeId1= @BTypeId,
										T.STATE = 17,
										T.Flag =  1
										FROM  Gp_LendPTypeSerial T WHERE Serial = @Serial
									END
								END
							END
						END
						ELSE IF @intBillType = '72'	-----------------借进还出-----------------
							UPDATE	Gp_LendPTypeSerial
							SET		PTypeId = @PTypeId,
									KTypeId = @KTypeid,
									State 	= 17,
									Flag	= 1,
									BTypeId1= @BTypeId
							WHERE	Serial	= @Serial							
						ELSE						-----------------借出还回-----------------
							UPDATE	Gp_LendPTypeSerial
							SET		PTypeId = @PTypeId,
									KTypeId = @KTypeid,
									State 	= 18,
									Flag	= 0,
									BTypeId2= @BTypeId
							WHERE	Serial	= @Serial							
					--END
				
				FETCH NEXT FROM SerialCursor INTO @Serial
			END

		CLOSE SerialCursor
		DEALLOCATE SerialCursor

		--删除出入库记录
		DELETE FROM Gp_InOutPTypeSerial WHERE BillNumberId = @BillNumberId AND BillType IN (71,72,87,88)
				
		RETURN 0
	END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
DECLARE
	@BillNumberID	VARCHAR(50),	-- 单据编号
	@intBillType	VARCHAR(50),	-- 单据类型
	@nRet			INT
	
SELECT
	@BillNumberID=12,
	@intBillType=71
	
	
			
BEGIN TRAN

EXEC	@nRet=Gp_SerialRedWordForLend
	@BillNumberID,
	@intBillType


SELECT state,* FROM dbo.gp_CruPtypeSerial
WHERE Serial='hhr-08'

SELECT state,* FROM dbo.gp_LendPtypeSerial
WHERE Serial='hhr-08'


ROLLBACK TRAN

*/



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_SetAccount_L]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_SetAccount_L]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		增加操作员会计科目多级权限
-- 最后修改作者：	彭勇
-- 最后修改时间：	2016-03-22
-- ========================================================================
CREATE PROCEDURE GP_SetAccount_L
(   
    @operatorId  VARCHAR(100),
	@etypeid	VARCHAR(100)	
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ope (TYPEID VARCHAR(50)) 
 INSERT #Ope
         ( TYPEID )
select TypeId from F_GetAllManagerBaseTypeId(@etypeid,3,@operatorId)
INSERT INTO Ac_Account_L(etypeid,stypeid,typeid,flag) 
 SELECT TYPEID,'00000','00000',1  FROM #Ope WHERE TYPEId  NOT IN (SELECT etypeid FROM Ac_Account_L) 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




GO
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_SetAuditFlow',N'P'))
BEGIN
	DROP PROC GP_SetAuditFlow
END
GO

/*
*	单据审核流程设置启用-停用
*	@HandleType=0 启用
*   @HandleType=1 停用       
*   2015-09-29
*/
CREATE PROC GP_SetAuditFlow
(
	@BillTypes VARCHAR(MAX),		--单据类型
	@HandleType INT=0,				--操作类型 0==启用，1==停用
	@OperatorUserID VARCHAR(50)='',	--操作员ID
	@STypeID    VARCHAR(50)			--分支结构ID
)
AS
BEGIN
	IF @BillTypes=''
		RETURN -1
	
	SELECT A AS BillType,ID INTO #BillType FROM dbo.f_splitAN(@BillTypes,',') WHERE A<>''
	
	--启用
	IF @HandleType=0
	BEGIN
		DECLARE @AuditingID INT,
				@StateBefore INT;
		
		--更新审核流程表		
		UPDATE AuditingFlowSet SET	   LastStartETypeID=@OperatorUserID,
									   LastStartTime=GETDATE(),
									   Stoped=0,
									   AuditingReason='0'+SUBSTRING(AuditingReason,2,LEN(AuditingReason)-1)
		WHERE BillType IN (SELECT BillType FROM #BillType) AND Stypeid=@STypeID
		--销售订单
		IF EXISTS(SELECT 1 FROM #BillType WHERE BillType=300)
		BEGIN
			SELECT @AuditingID=AuditingID FROM dbo.AuditingFlowSet WHERE BillType=300 AND Stypeid=@STypeID
			EXEC dbo.Gp_UpdateSaleOrderState @AuditingID = @AuditingID, 
											 @StateBefore = 0,
											 @deleteBill = 0 
		END
		--采购订单
		ELSE IF EXISTS(SELECT 1 FROM #BillType WHERE BillType=301)
		BEGIN
			SELECT @AuditingID=AuditingID FROM dbo.AuditingFlowSet WHERE BillType=301 AND Stypeid=@STypeID
			EXEC dbo.Gp_UpdateBuyOrderState  @AuditingID = @AuditingID, 
											 @StateBefore = 0,
											 @deleteBill = 0 
		END
	    DROP TABLE #BillType
	    RETURN 0
	END
	
	--停用
	ELSE IF @HandleType=1
	BEGIN
		DECLARE @RowIndex INT=1,
				@RowCount INT,
				@BillType INT,
				@AuditID  INT;            
		
		--更新审核流程表		
		UPDATE AuditingFlowSet SET LastStopETypeID=@OperatorUserID,
								   LastStopTime=GETDATE(),
								   Stoped=1,
								   AuditingReason='1'+SUBSTRING(AuditingReason,2,LEN(AuditingReason)-1)
	    WHERE BillType IN  (SELECT BillType FROM #BillType) AND Stypeid=@STypeID
	    
	    --无审核中记录，退出
	    --删除审核流程
	    --设置单据审核状态为无需审核
	    SELECT @RowCount=COUNT(1) FROM #BillType
	    WHILE(@RowIndex<=@RowCount)
	    BEGIN
			SELECT @BillType=BillType FROM #BillType WHERE ID=@RowIndex
			SELECT @AuditID=AuditingID FROM dbo.AuditingFlowSet WHERE BillType=@BillType AND STypeID=@STypeID
			
			--IF NOT EXISTS(SELECT 1 FROM dbo.AuditingBill WHERE AuditingID=@AuditID AND IfAudit='0')
			--BEGIN
			--	SET @RowIndex+=1;
			--	CONTINUE;
			--END
			
			--设置未完成审核单据未无需审核状态
			--订单
			IF @BillType IN(300,301)
			BEGIN
				UPDATE dbo.OrderIndex SET IfAudit='' WHERE BillNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE --IfAudit='0' AND
					 AuditingID=@AuditID)
					 
				
				
				UPDATE dbo.OrderIndex SET IfAudit=1 WHERE BillType=@BillType AND STypeID=@STypeID --AND IfAudit='0'
				
				
				
			END
			--请购单
			ELSE IF @BillType =204
			BEGIN
				UPDATE dbo.RequestIndex SET IfAudit='' WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE -- IfAudit='0' AND
					 AuditingID=@AuditID)
					 
				UPDATE dbo.RequestIndex SET IfAudit=1 WHERE BillType=@BillType AND STypeID=@STypeID AND IfAudit='0'
			END
			--借欠单据
			ELSE IF @BIllType IN(87,71,88,72)
			BEGIN
				UPDATE dbo.LendIndex SET IfAudit='' WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE  --IfAudit='0' AND
					 AuditingID=@AuditID)
					 
				UPDATE dbo.LendIndex SET IfAudit=1 WHERE BillType=@BillType AND STypeID=@STypeID AND IfAudit='0'
			END
			--提成单
			ELSE IF @BillType =311
			BEGIN
				UPDATE dbo.CommissionBillNew SET BillState=1 WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE --IfAudit='0' AND
					 AuditingID=@AuditID)
					 
				UPDATE dbo.CommissionBillNew SET BillState=1 WHERE BillType=@BillType AND STypeID=@STypeID AND BillState=0
			END
			--开票单据
			ELSE IF @BillType IN(404,405)
			BEGIN
				UPDATE dbo.ReceiptBillIndex SET IfAudit='' WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE --IfAudit='0' AND
					 AuditingID=@AuditID)
					 
				UPDATE dbo.ReceiptBillIndex SET IfAudit=1 WHERE BillType=@BillType AND STypeID=@STypeID AND IfAudit='0'
			END
			--普通单据
			ELSE
			BEGIN
				UPDATE dbo.BillIndex SET IfAudit='' WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE --IfAudit='0' AND
					 AuditingID=@AuditID)
					 
				UPDATE dbo.BillIndex SET IfAudit=1 WHERE BillType=@BillType AND STypeID=@STypeID AND IfAudit='0'
			END
			
			--删除未完成审核流程
			DELETE A FROM dbo.AuditingBillDetail A,dbo.AuditingBill B WHERE A.BillNumberID=B.BillNumberID AND 
																			A.BillIndexType=B.BillIndexType AND
																			B.AuditingID=@AuditID-- AND B.IfAudit='0'   --审核通过...
																				
			DELETE FROM dbo.AuditingBill WHERE AuditingID=@AuditID-- AND IfAudit='0'		--审核通过... 半成品不要，成品也不要
			
			SET @RowIndex+=1;			
	    END
	    DROP TABLE #BillType
	END
END

GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SetCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SetCode]
GO





-- ========================================================================
-- 功能说明：得到单据大类的自定义字符及样式预览
-- 作者：陈启华  2004-12-15
-- ========================================================================
CREATE         PROCEDURE [Gp_SetCode] 
(
	@chvOperatorID		varchar(50),	-- 11、操作员 ID（作权限范围检查用）
	@strBilltypes		char(100)
)
--@encode$--
AS 
SET NOCOUNT ON
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe
DECLARE @SQL Varchar(2000)
DECLARE @chvBilltype numeric(4,0)
DECLARE @chvBilltypes varchar(200)
DECLARE @chvBillName varchar(200)
DECLARE @chvBillNames varchar(200)
SET @chvBilltype ='0'
SET @chvBilltypes =''
SET @chvBillName =''
SET @chvBillNames =''
DECLARE @EuserCode varchar(200)
DECLARE @KuserCode varchar(200)
DECLARE @DuserCode varchar(200)
DECLARE @CEuserCode varchar(200)
SET @EuserCode =''
SET @KuserCode =''
SET @DuserCode=''
SET @CEuserCode=''
SELECT @EuserCode =UserCode FROM Employee where typeid=@chvOperatorID 
SELECT top 1 @KuserCode= UserCode FROM Stock where  Sonnum =0
SELECT top 1 @DuserCode= UserCode FROM dbo.Department where  Sonnum =0
SELECT top 1 @CEuserCode= UserCode FROM dbo.Employee where  Sonnum =0
SET @EuserCode=Rtrim(ltrim(@EuserCode))
SET @KuserCode=Rtrim(ltrim(@KuserCode))
SET @DuserCode=RTRIM(LTRIM(@DuserCode))
SET @CEuserCode=RTRIM(LTRIM(@CEuserCode))
DECLARE @CODE1 varchar(100)
DECLARE @CODE2 varchar(100)
DECLARE @CODE3 varchar(100)
DECLARE @CODE4 varchar(100)
DECLARE @CODE5 varchar(100)
DECLARE @CODE6 varchar(100)
DECLARE @CODE7 varchar(100)
DECLARE @CODE8 varchar(100)
DECLARE @CODE9 varchar(100)
DECLARE @CODE10 varchar(100)
DECLARE @CODE11 varchar(100)
DECLARE @CODE12 varchar(100)
DECLARE @CODE13 varchar(100)
SET @CODE1 =''
SET @CODE2 =''
SET @CODE3 =''
SET @CODE4 =''
SET @CODE5 =''
SET @CODE6 =''
SET @CODE7 =''
SET @CODE8 =''
SET @CODE9 =''
SET @CODE10 =''
SET @CODE11 =''
SET @CODE12 =''
SET @CODE13 =''

DECLARE
	@intZeroLen		INT,
	@IsUseAcSystem  int 

SELECT @intZeroLen=Value FROM UserConfig WHERE ConfigName='flowlen'
SELECT @IsUseAcSystem=SubValue FROM sysdata WHERE LOWER(SubName)='IsUseAcSystem'
DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
DECLARE @whereSQL varchar(800)

IF @proinfo='3' --汽配版本
	BEGIN
		SET @whereSQL=' Billtypes=' +char(39)+@strBilltypes+char(39) +' AND Billtype NOT IN (155,149,151,204)'
		IF EXISTS(SELECT * FROM SYSDATA WHERE SubName = 'QPEdition' AND (SubValue = '1' OR SubValue = '2' OR SubValue = '3'))
			SET @whereSQL = @whereSQL + ' AND BillType NOT IN (195,192,196,200,198,197,191)'		
	END
ELSE
	BEGIN
		IF @strBilltypes<>'7'
			SET @whereSQL=' Billtypes=' +char(39)+@strBilltypes+char(39) +' AND Billtype NOT IN (155)'
		ELSE	-- 会员类	
		   BEGIN
				IF @proinfo <> '2'
				BEGIN
					IF @IsUseAcSystem=1
						SET @whereSQL=' (Billtypes=' +char(39)+@strBilltypes+char(39) +' AND Billtype NOT IN (155,428,429)) OR BillType IN(181,183,310)'
					ELSE
						SET @whereSQL=' (Billtypes=' +char(39)+@strBilltypes+char(39) +' AND Billtype NOT IN (155,428,429)) OR BillType IN(181,183)'				
				END
				ELSE
				BEGIN
					IF @IsUseAcSystem=1
						SET @whereSQL=' (Billtypes=' +char(39)+@strBilltypes+char(39) +' AND Billtype NOT IN (155)) OR BillType IN(181,183,310)'
					ELSE
						SET @whereSQL=' (Billtypes=' +char(39)+@strBilltypes+char(39) +' AND Billtype NOT IN (155)) OR BillType IN(181,183)'
				END		
			END	
	END

IF @strBilltypes='10' 
BEGIN
	SET @whereSQL =' Billtypes= 6' 
END

IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = '1') 
 OR EXISTS(SELECT * FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = '3')
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (187,188)'
END

DECLARE @qpedition VARCHAR(5),@Edition VARCHAR(5)
SELECT @qpedition=SubValue FROM sysdata WHERE LOWER(SubName)='qpedition'

SELECT @Edition=SubValue FROM sysdata WHERE LOWER(SubName)='edition'

IF @strBilltypes<>9 OR @proinfo<>3 OR @qpedition<>4
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (193,194)'
END

IF @strBilltypes=3 AND (@proinfo=3 OR (@proinfo<>3 AND @Edition IN (1,6)))
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (203)'
END

DECLARE
		@nCostingMethod		INT,
		@AVERAGE			smallint

SET @AVERAGE	= 0		-- 移动加权平均算法
		
EXEC Gp_GetSubValue 'costing', '',@nCostingMethod OUT

IF @strBilltypes=6 AND @nCostingMethod<>@AVERAGE
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (205,206)'
END

IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'useonshelves' AND SubValue = '1')	--启用上架
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (412)'
END

IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usepickgoods' AND SubValue = '1')	--启用拣货
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (413)'
END

IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'usetransport' AND SubValue = '1')	--启用运输配送
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (414)'
END

--实物库存
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'isphysicalsstock' AND SubValue = '1')	
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (418,419,420,421,422)'
END

--组合品
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'combinationproduct' AND SubValue = '1')	
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (12,46,313)'
END

--运输费用分摊单
SET @whereSQL = @whereSQL + ' AND BillType NOT IN (415)'

CREATE TABLE  #BillCode
(
	Billtype numeric(4,0),
	Billtypes varchar(200),
	BillName varchar(200),
	BillNames varchar(200),
	BillCode varchar(800),
	PreBillCode varchar(800)
)
DECLARE @chvBillCode varchar(800)
DECLARE @chvPreBillCode varchar(800)
DECLARE @assets VARCHAR(1)
SELECT @assets=SubValue FROM dbo.sysdata WHERE SubName='assets'
SET @chvBillCode =''
SET @chvPreBillCode =''
IF @strBilltypes='10'
BEGIN
	SET @whereSQL=@whereSQL+' AND BillType  IN (212,213,214,307) '
END
IF @strBilltypes='6'
BEGIN
	IF @assets='1'
	  BEGIN 
	    SET @whereSQL = @whereSQL + ' AND BillType NOT IN (212,213,214,84,85,78)'
	  END
	ELSE
	  BEGIN
	   SET @whereSQL = @whereSQL + ' AND BillType NOT IN (212,213,214)'
	  END
END
--这版本排除卡片变更和固定资产拆分单 排除固定资产盘点单 与固定资产类重复
IF @strBilltypes = '6'
BEGIN
SET @whereSQL = @whereSQL + ' AND BillType NOT IN (410,411,307)'
END
--v3没有资金调拨单
IF @proinfo = '1'	
BEGIN
	SET @whereSQL = @whereSQL + ' AND BillType NOT IN (310)'
END
--v1版本没有提成单,赠送单,获赠单,序列号调整单,分支机构调拨出入库单,获利丶返利单,价保类单
IF @proinfo = '4'
BEGIN
    SET @whereSql = @whereSQL + ' AND BillType NOT IN(148,150,149,151,139,126,165,166,167,168,169,170,171,172,173,174,175,307,311,209,400,401,402,403,404,405,187,188,203,428,429,326,327,328,329)';
END

--关闭 期初未实物出库单、期初未实物入库单
SET @whereSQL = @whereSQL + ' AND BillType NOT IN (421,422)'

SET @SQL='DECLARE Rows_Cursor CURSOR FOR 
				SELECT  BillType,BillName,BillTypes,BillNames FROM 
				(
					SELECT BillType,BillName,BillTypes,BillNames,SortId
					FROM BillName
					UNION ALL
					SELECT 193,''工具入库台帐'',9,''汽配维修类'',10001
					UNION ALL
					SELECT 194,''工具出库台帐'',9,''汽配维修类'',10002
				) a 
				WHERE '+@whereSQL + ' ORDER BY Sortid '

--PRINT @SQL
EXEC(@SQL)

--单据编号配置
DECLARE @BillcodeDateSeparator varchar(5),@monthSeparator varchar(5),@daySeparator varchar(5),@yearSeparator varchar(5)
SELECT @BillcodeDateSeparator=Value FROM Userconfig WHERE ConfigName='BillcodeDateSeparator' 

IF @BillcodeDateSeparator='0'
	SELECT @monthSeparator='-',@daySeparator='',@yearSeparator='-'
ELSE IF @BillcodeDateSeparator='1'
	SELECT @monthSeparator='.',@daySeparator='',@yearSeparator='.'
ELSE IF @BillcodeDateSeparator='2'
	SELECT @monthSeparator='月',@daySeparator='日',@yearSeparator='年'
ELSE IF @BillcodeDateSeparator='3'
	SELECT @monthSeparator='',@daySeparator='',@yearSeparator=''
ELSE IF @BillcodeDateSeparator='4'
	SELECT @monthSeparator=' ',@daySeparator='',@yearSeparator=' '
DECLARE @BillDate VARCHAR(10)
SELECT @BillDate=CAST(YEAR(GETDATE()) AS VARCHAR(4))+'-'+CAST(MONTH(GETDATE()) AS VARCHAR(2))+'-'+CAST(DAY(GETDATE()) AS VARCHAR(2))

-- 返回结果不受影响
SET NOCOUNT ON
-- 打开游标
OPEN Rows_Cursor
FETCH NEXT FROM Rows_Cursor INTO  @chvBilltype,@chvBillName,@chvBilltypes,@chvBillNames
WHILE ( @@FETCH_STATUS = 0 ) 
BEGIN  
	SET @chvPreBillCode =''
	SET @chvBillCode =''
	SET @CODE1 =''
	SET @CODE2 =''
	SET @CODE3 =''
	SET @CODE4 =''
	SET @CODE5 =''
	SET @CODE6 =''
	SET @CODE7 =''
	SET @CODE8 =''
	SET @CODE9 =''
	SET @CODE10 =''
	SET @CODE11 =''
	SET @CODE12 =''
		SET @CODE13 =''
	
	SELECT 	
	@Code1=code1,
	@Code2=code2,
	@Code3=code3,
	@Code4=code4,
	@Code5=code5,
	@Code6=code6,
	@Code7=code7,
	@Code8=code8,
	@Code9=code9,
	@Code10=code10,
	@Code11=code11,
	@Code12=code12,
	@CODE13=code13  FROM CodeConfig  WHERE Billtype =@chvBilltype
	SET @chvPreBillCode = 
	@chvPreBillCode + 
	dbo.F_Get_YMD_NEW(@code1,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code2,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code3,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code4,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code5,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code6,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code7,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code8,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code9,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code10,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code11,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code12,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)+
	dbo.F_Get_YMD_NEW(@code13,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)
	
	SET @chvPreBillCode =Replace(@chvPreBillCode,'#KK#',@KuserCode)
	SET @chvPreBillCode =Replace(@chvPreBillCode,'#EE#',@EuserCode)
	SET @chvPreBillCode =Replace(@chvPreBillCode,'#BM#',@DuserCode)
	SET @chvPreBillCode =Replace(@chvPreBillCode,'#ZDR#',@CEuserCode)
	IF LEN(@chvPreBillCode) =0
		SET @chvPreBillCode =''

	IF @chvPreBillCode<>''
	BEGIN
		SET @chvPreBillCode =Rtrim(ltrim(@chvPreBillCode))+'-'+REPLICATE('0',@intZeroLen+3-1)+'1'
	END
	
	SET @chvBillCode = @chvBillCode + @CODE1+@CODE2+@CODE3+@CODE4+@CODE5+@CODE6+@CODE7+@CODE8+@CODE9+@CODE10+@CODE11+@CODE12+@code13
	INSERT #BillCode VALUES (@chvBilltype,@chvBilltypes,@chvBillName,@chvBillNames,@chvBillCode,@chvPreBillCode)
	FETCH NEXT FROM Rows_Cursor INTO  @chvBilltype,@chvBillName,@chvBilltypes,@chvBillNames
END
CLOSE Rows_Cursor	-- 关闭游标
DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源
--特殊处理维修接待登记单,工具出入库

/*
IF @strBilltypes=9 and @proinfo=3 and @qpedition=4
BEGIN
	INSERT INTO #BillCode(Billtype,Billtypes,BillName,BillNames, BillCode,PreBillCode)VALUES(193,9,'工具入库台帐','汽配维修类','','')
	INSERT INTO #BillCode(Billtype,Billtypes,BillName,BillNames, BillCode,PreBillCode)VALUES(194,9,'工具出库台帐','汽配维修类','','')
END
*/


UPDATE #BillCode SET BillName='接待登记单' WHERE Billtype=195

DECLARE @isinvoice VARCHAR(10) 

SELECT @isinvoice=SubValue FROM dbo.sysdata WHERE SubName='isinvoice'

IF(@isinvoice!='1')
	SELECT * FROM #BillCode WHERE billtype NOT IN (400,401,402,403,404,405,427)
ELSE
	SELECT * FROM #BillCode  WHERE billtype NOT IN (427)
	
DROP TABLE #BillCode





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SetCodeSave]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SetCodeSave]
GO










-- ========================================================================
-- 功能说明：存储单据自定义字符
-- 作者：陈启华  2004-12-15


-- ========================================================================


CREATE      PROCEDURE [Gp_SetCodeSave] 
(
	@chvOperatorID		  varchar(50),	-- 11、操作员 ID（作权限范围检查用）
	@chvBilltype 		  char(100),
	@chvCode1             varchar(100),
	@chvCode2             varchar(100),
	@chvCode3             varchar(100),
	@chvCode4             varchar(100),
	@chvCode5             varchar(100),
	@chvCode6             varchar(100),
	@chvCode7             varchar(100),
	@chvCode8             varchar(100),
	@chvCode9             varchar(100),
	@chvCode10            varchar(100),
	@chvCode11            varchar(100),
	@chvCode12            varchar(100),
	@chvCode13            VARCHAR(100),
	@FlowSet			  VARCHAR(50)
)
--@encode$--
AS 
SET NOCOUNT ON

IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe

Delete FROM CodeConfig WHERE Billtype=@chvBilltype

INSERT INTO CodeConfig Values (@chvBilltype,@chvCode1,@chvCode2,@chvCode3,@chvCode4,@chvCode5,@chvCode6,@chvCode7,@chvCode8,@chvCode9,@chvCode10,@chvCode11,@chvCode12,@chvOperatorID,@chvCode13,@FlowSet)



IF @@Rowcount>0
	RETURN 1
ELSE
	RETURN 0










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_SetDefaulHaveLimit]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_SetDefaulHaveLimit]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		设置操作员默认拥有权限
-- 最后修改作者：	黄清
-- 最后修改时间：	2013-06-17
-- ========================================================================
CREATE PROCEDURE GP_SetDefaulHaveLimit
(
	@Operator	VARCHAR(MAX),	-- 操作员id
	@limits		VARCHAR(MAX),	-- 权限位字符串
	@flag		VARCHAR(1)		--标志 0.处理全部操作员，1.处理@Operator里的操作员
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ope (TYPEID VARCHAR(50)) 
IF @flag=1
	INSERT INTO #Ope (TYPEID) SELECT l.etypeid FROM f_split(@Operator,',') a INNER JOIN loginuser l ON l.etypeid LIKE a.a+'%'
ELSE
	INSERT INTO #Ope (TYPEID) SELECT etypeid FROM LoginUser

CREATE TABLE #lim (lim VARCHAR(10))
INSERT INTO #lim (lim) SELECT *FROM f_split(@limits,',')

DECLARE @opecount INT
DECLARE @limcount INT
DECLARE @operatorid VARCHAR(50)
DECLARE @limposition VARCHAR(10)
DECLARE @limit VARCHAR(MAX)
DECLARE @limitleft VARCHAR(MAX)
DECLARE @limitright VARCHAR(MAX)

DELETE FROM #OPE WHERE TYPEID='00001' --超级管理员不处理

SELECT @opecount=COUNT(1) FROM #OPE



WHILE(@opecount>0)
BEGIN
	SELECT TOP (@opecount) @operatorid=TYPEID FROM #OPE 
	SELECT @limcount=COUNT(1) FROM #lim
	WHILE (@limcount>0)
	BEGIN
		SELECT TOP (@limcount) @limposition=lim FROM #lim
		SELECT @limit=lim FROM LoginUser WHERE etypeid=@operatorid
		SET @limitleft=LEFT(@limit,CAST(@limposition AS INT)-1)
		SET @limitright=RIGHT(@limit,LEN(@limit)-CAST(@limposition AS INT))
		SET @limit=@limitleft+'1'+@limitright
		UPDATE LoginUser SET lim=@limit WHERE etypeid=@operatorid
		SET @limcount=@limcount-1
		
	END
	IF NOT EXISTS (SELECT *FROM LoginUserCol WHERE ETypeID=@operatorid AND BillType='215')
	BEGIN
		INSERT INTO LoginUserCol VALUES (@operatorid, '215', 'posfullname', 0)
		INSERT INTO LoginUserCol VALUES (@operatorid, '215', 'posusercode', 0)
	END
	
	--添加默认不允许修改单据列的“原币税额”
	IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUserCol WHERE etypeid = @operatorid AND ColDataField = 'ntaxmoney')
	BEGIN		
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'160In','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'184','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'11','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'6','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'45','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'301','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'145','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'161Out','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'161In','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'160Out','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'142','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'141','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'140','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'34','ntaxmoney','1')		
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'300','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'146','ntaxmoney','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'144','ntaxmoney','1')
	END
	
	--虚拟库存默认不允许修改
	IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUserCol WHERE etypeid = @operatorid AND ColDataField = 'virtualstockqty')
	BEGIN
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'305','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'402','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'11','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'21','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'17','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'300','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'204','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'12down','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'187','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'16Out','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'313down','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'301','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'160Out','virtualstockqty','1')
		INSERT INTO dbo.LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@operatorid,'140','virtualstockqty','1')
	END	
	
	SET @opecount=@opecount-1
END
EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'

DROP TABLE #Ope,#lim

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_SetDefaultAcAuditingTemplate]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_SetDefaultAcAuditingTemplate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--=================================================
--by:glj
--date:2016-04-25
--description:凭证模板设置默认模板
--=================================================
CREATE PROCEDURE Gp_SetDefaultAcAuditingTemplate
(
	@AtId		INT --凭证模板ID
)
----@encode$--
AS
SET NOCOUNT ON
DECLARE
	@STypeId		VARCHAR(50),--分支机构
	@BillType		INT,		--模版类型 
	@InOutType		INT,		--资金调拨单，调入调出类型 1.调入 -1.调出
	@ChargeOffType	INT			--往来核销单 0=应收冲应付,1=预收冲预付,2=应收转应收,3=应付转应付,4=预收转应付,5=预付转应收
SELECT @STypeId=STypeId,@inouttype=InOutType,@BillType=BillType,@ChargeOffType=ChargeOffType FROM Ac_Auditing_Template WHERE AtId=@AtId
IF(@BillType IN(310,57))
	BEGIN
		UPDATE Ac_Auditing_Template SET IsDefault = 1 WHERE AtId = @AtId AND BillType = @BillType AND STypeId = @STypeId AND InOutType=@inouttype
		UPDATE Ac_Auditing_Template SET IsDefault = 0 WHERE AtId <> @AtId AND BillType = @BillType AND STypeId = @STypeId AND InOutType=@inouttype	
	END
--往来核销单增加核销类型后  根据核销类型设置默认模板
ELSE IF (@BillType=450)
	BEGIN
		UPDATE Ac_Auditing_Template SET IsDefault = 1 WHERE AtId = @AtId AND BillType = @BillType AND STypeId = @STypeId AND ChargeOffType=@ChargeOffType
		UPDATE Ac_Auditing_Template SET IsDefault = 0 WHERE AtId <> @AtId AND BillType = @BillType AND STypeId = @STypeId AND ChargeOffType=@ChargeOffType
	END
ELSE IF (@BillType IN(212,213))
	BEGIN
		DECLARE @AuditType INT
		SELECT @AuditType=AuditType FROM Ac_Auditing_Template WHERE AtId = @AtId AND BillType = @BillType AND STypeId = @stypeid
		UPDATE dbo.Ac_Auditing_Template SET IsDefault = 1 WHERE AtId = @AtId AND BillType = @BillType AND STypeId = @stypeid AND AuditType = @AuditType 
		UPDATE dbo.Ac_Auditing_Template SET IsDefault = 0 WHERE AtId <> @AtId AND BillType = @BillType AND STypeId = @stypeid AND AuditType = @AuditType 
	END 
ELSE --,214,-1,-2,410 除了212，213外的固定资产凭证模板应该都是没有audittype类型的或者audittype只有一个类型，不需要区分auditype的，跟兵哥确认过
	BEGIN
		UPDATE Ac_Auditing_Template SET IsDefault = 1 WHERE AtId = @AtId AND BillType = @BillType AND STypeId = @STypeId 
		UPDATE Ac_Auditing_Template SET IsDefault = 0 WHERE AtId <> @AtId AND BillType = @BillType AND STypeId = @STypeId 
	END

RETURN @AtId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_SetLendGoods]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[gp_SetLendGoods]
GO

/****** Object:  Stored Procedure dbo.gp_SetLendGoods    Script Date: 2002-6-20 10:14:58 ******/


CREATE  PROCEDURE gp_SetLendGoods 
(
	@nBillID				NUMERIC(10,0)				-- 单据 ID 号
)
--@encode$--
AS
SET NOCOUNT ON 

	DECLARE @KtypeID VARCHAR(50), @BtypeID VARCHAR(50),@BillType INT
	SELECT  @KtypeID = ktypeid ,@BtypeID =  btypeid ,@BillType = BillType FROM dbo.LendIndex  WHERE BillNumberId = @nBillID

	SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber,
	SUM(BorrowQty) BorrowQty,SUM(NBorrowQty) NBorrowQty,SUM(LendQty) LendQty,SUM(NLendQty) NLendQty
	INTO #goodslendtemp 
	FROM (
		SELECT t1.pTypeID,t1.ktypeid,t1.btypeid,t1.ItemID,t1.IsCombined , t1.GoodsNumber,
			SUM(t1.Borrow+t1.BorrowBack) BorrowQty,SUM(t1.NBorrow + t1.NBorrowBack ) NBorrowQty,
			SUM(t1.Lend+t1.LendBack) LendQty,SUM(t1.NLend+t1.NLendBack) NLendQty
		FROM (
		
			SELECT		
				lb.PtypeId AS pTypeID, 	
				@KtypeID AS kTypeID,--li.kTypeID, 	
				@BtypeID AS bTypeID,--li.bTypeID,
				lb.ItemID,
				lb.IsCombined,
				lb.GoodsNumber,
				CASE @BillType WHEN 71 THEN  Qty   ELSE 0 END AS Borrow,
				CASE @BillType WHEN 71 THEN  NQty  ELSE 0 END AS NBorrow,
				CASE @BillType WHEN 72 THEN  Qty   ELSE 0 END AS BorrowBack,
				CASE @BillType WHEN 72 THEN  NQty  ELSE 0 END AS NBorrowBack,
				CASE @BillType WHEN 87 THEN  Qty   ELSE 0 END AS Lend,
				CASE @BillType WHEN 87 THEN  NQty  ELSE 0 END AS NLend,
				CASE @BillType WHEN 88 THEN  Qty   ELSE 0 END AS LendBack,
				CASE @BillType WHEN 88 THEN  NQty  ELSE 0 END AS NLendBack
			FROM dbo.LendBill lb WHERE lb.BillNumberId = @nBillID
			--INNER JOIN dbo.LendIndex li ON li.BillNumberId = lb.BillNumberId 
			--WHERE li.ifcheck='t' AND li.RedWord=0 AND li.draft = 0 
		) t1 GROUP BY t1.pTypeID,t1.ktypeid,t1.btypeid,t1.ItemID,t1.IsCombined , t1.GoodsNumber
		
		UNION ALL
		
		SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,-LendQty,-NLendQty 
		FROM dbo.GoodsLend WHERE KtypeId = @KtypeID AND BtypeId = @BtypeID
		AND ptypeid IN (
			SELECT PtypeId FROM dbo.LendBill WHERE BillNumberId = @nBillID
		)
		
	)AS t2 GROUP BY PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber

	DELETE b FROM #goodslendtemp a JOIN GoodsLend b 
	ON b.PtypeId = a.PtypeId 
	AND b.KtypeId = a.KtypeId
	AND b.BtypeId = a.BtypeId
	AND b.ItemID = a.ItemID
	AND b.Iscombined = a.Iscombined
	AND b.GoodsNumber = a.GoodsNumber

	INSERT INTO dbo.GoodsLend( PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,LendQty,NLendQty,Qty,NQty)
	SELECT PtypeId,KtypeId,BtypeId,ItemID,Iscombined,GoodsNumber, BorrowQty,NBorrowQty,-LendQty,-NLendQty, 
	(BorrowQty + LendQty) AS Qty, (NBorrowQty + NLendQty) AS NQty FROM #goodslendtemp

	DROP TABLE #goodslendtemp

	--DELETE GoodsLend WHERE Qty = 0 AND NQty = 0
	--SELECT * from GoodsLend

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_SetLimitExChange]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_SetLimitExChange]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		两个权限交换
-- 最后修改作者：	黄清
-- 最后修改时间：	2014-02-08
-- ========================================================================
CREATE PROCEDURE GP_SetLimitExChange
(
	@Operator	VARCHAR(MAX),	-- 操作员id
	@limit1		VARCHAR(50),	--操作员原拥有的权限位
	@limit2		VARCHAR(MAX),	--操作员拥有的新增权限
	@flag		VARCHAR(1)		--标志 0.处理全部操作员，1.处理@Operator里的操作员
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ope (TYPEID VARCHAR(50)) 
IF @flag=1
	INSERT INTO #Ope (TYPEID) SELECT *FROM f_split(@Operator,',')
ELSE
	INSERT INTO #Ope (TYPEID) SELECT etypeid FROM LoginUser


DECLARE @Limit1Value VARCHAR(2)
DECLARE @Limit2Value VARCHAR(2)


DECLARE @opecount INT

DECLARE @operatorid VARCHAR(50)

DECLARE @lim VARCHAR(MAX)
DECLARE @limitleft VARCHAR(MAX)
DECLARE @limitright VARCHAR(MAX)

DELETE FROM #OPE WHERE TYPEID='00001' --超级管理员不处理

SELECT @opecount=COUNT(1) FROM #OPE

WHILE(@opecount>0)
BEGIN
	SELECT TOP (@opecount) @operatorid=TYPEID FROM #OPE 

	SELECT @lim=lim FROM LoginUser WHERE etypeid=@operatorid
	--取权限位的值
	SET @Limit1Value=SUBSTRING(@lim,CAST(@limit1 AS INT),1)
	SET @Limit2Value=SUBSTRING(@lim,CAST(@limit2 AS INT),1)

	--limit1放到limit2位置
	SET @limitleft=LEFT(@lim,CAST(@limit2 AS INT)-1)
	SET @limitright=RIGHT(@lim,LEN(@lim)-CAST(@limit2 AS INT))
	SET @lim=@limitleft+@Limit1Value+@limitright
	
	--limit1放到limit2位置
	SET @limitleft=LEFT(@lim,CAST(@limit1 AS INT)-1)
	SET @limitright=RIGHT(@lim,LEN(@lim)-CAST(@limit1 AS INT))
	SET @lim=@limitleft+@Limit2Value+@limitright
	
	UPDATE LoginUser SET lim=@lim WHERE etypeid=@operatorid

	SET @opecount=@opecount-1
END

DROP TABLE #Ope

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_SetOperatorSimple]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_SetOperatorSimple];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：谢吉康
	日期：2019-08-02
	描述：设置操作员的极简操作模式
*/

CREATE PROCEDURE Gp_SetOperatorSimple
(
	@etypeid		VARCHAR(50)
)
AS 
SET NOCOUNT ON

--单据表头配置
TRUNCATE TABLE BillHeadControlField
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','184','priceResponseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','184','priceResponseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','184','priceResponseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','184','priceResponseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','184','priceResponseBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','184','priceResponseBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','305','retailBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','305','retailBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','305','retailBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','305','retailBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','305','retailBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','305','retailBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','215','retailBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','215','retailBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','215','retailBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','215','retailBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','215','retailBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','215','retailBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','300','saleOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','300','saleOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','300','saleOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','300','saleOrderBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','交货时间','5','300','saleOrderBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','6','300','saleOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','300','saleOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','300','saleOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','9','300','saleOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','10','300','saleOrderBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','11','300','saleOrderBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','12','300','saleOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','18','300','saleOrderBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','11','saleOutStockBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','11','saleOutStockBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','13','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','14','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','15','11','saleOutStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','45','saleBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','45','saleBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','45','saleBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','45','saleBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','45','saleBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','45','saleBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','45','saleBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','45','saleBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','45','saleBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','10','45','saleBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','160','saleGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','160','saleGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','160','saleGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','160','saleGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','160','saleGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','160','saleGoodsExchangeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','160','saleGoodsExchangeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','160','saleGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','160','saleGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','10','160','saleGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','139','giveBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','139','giveBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','139','giveBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','139','giveBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','139','giveBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','139','giveBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','139','giveBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','140','wtSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','140','wtSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','140','wtSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','140','wtSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','140','wtSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','140','wtSendBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','140','wtSendBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','142','wtBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','142','wtBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','142','wtBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','142','wtBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','142','wtBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','142','wtBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','142','wtBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','143','wtChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','143','wtChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','143','wtChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','143','wtChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','143','wtChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','143','wtChangePriceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','143','wtChangePriceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','141','wtGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','141','wtGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','141','wtGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','141','wtGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','141','wtGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','141','wtGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','141','wtGatherBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','141','wtGatherBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','9','141','wtGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','5','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','6','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','7','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','8','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','9','313','combinationSaleOrderHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','10','313','combinationSaleOrderHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','11','313','combinationSaleOrderHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','12','313','combinationSaleOrderHead','1')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','交货时间','13','313','combinationSaleOrderHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','12','combinationSaleHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','12','combinationSaleHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','14','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','15','12','combinationSaleHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','16','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','17','12','combinationSaleHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','46','combinationSaleBackHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','46','combinationSaleBackHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','46','combinationSaleBackHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','46','combinationSaleBackHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','46','combinationSaleBackHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','46','combinationSaleBackHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','46','combinationSaleBackHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','46','combinationSaleBackHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('StockInDeadline','入库期限','9','46','combinationSaleBackHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','46','combinationSaleBackHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','11','46','combinationSaleBackHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','6','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','7','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','8','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','9','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('edAddress','送货地址','10','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','11','402','sendPtypeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','12','402','sendPtypeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','13','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','14','402','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','403','sendBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','403','sendBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','403','sendBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','403','sendBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','403','sendBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','403','sendBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','7','403','sendBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','204','buyRequestBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','204','buyRequestBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','204','buyRequestBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','204','buyRequestBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','204','buyRequestBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','185','priceQueryBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','185','priceQueryBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','185','priceQueryBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','185','priceQueryBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','185','priceQueryBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','185','priceQueryBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','301','buyOrderBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','301','buyOrderBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ReachDate','到货时间','3','301','buyOrderBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('WayBillcode','运单号','4','301','buyOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Tel','承运单位','4','301','buyOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('GoodsNumber','物件数量','5','301','buyOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','301','buyOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('PackWay','包装方式','7','301','buyOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','8','301','buyOrderBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','9','301','buyOrderBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('preTotal','订金','10','301','buyOrderBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','11','301','buyOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','12','301','buyOrderBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','34','buyInStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','34','buyInStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','34','buyInStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','34','buyInStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','34','buyInStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','34','buyInStockBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','34','buyInStockBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','34','buyInStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','34','buyInStockBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','34','buyInStockBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','11','34','buyInStockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','6','buyBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','6','buyBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','6','buyBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','6','buyBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','6','buyBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','6','buyBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','6','buyBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','6','buyBackBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','9','6','buyBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','10','6','buyBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','11','6','buyBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','161','buyGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','161','buyGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','161','buyGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','161','buyGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','161','buyGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','161','buyGoodsExchangeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','161','buyGoodsExchangeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','161','buyGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','161','buyGoodsExchangeBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AfterPreference','抹零后金额','10','161','buyGoodsExchangeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','11','161','buyGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','12','161','buyGoodsExchangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','126','giveMeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','126','giveMeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','126','giveMeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','126','giveMeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','126','giveMeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','126','giveMeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','126','giveMeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','144','stSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','144','stSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','144','stSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','144','stSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','144','stSendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','144','stSendBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','144','stSendBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','146','stBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','146','stBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','146','stBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','146','stBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','146','stBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','146','stBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','146','stBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','147','stChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','147','stChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','147','stChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','147','stChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','147','stChangePriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','147','stChangePriceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','147','stChangePriceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','145','stGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','145','stGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','145','stGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','145','stGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','145','stGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','145','stGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','7','145','stGatherBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','8','145','stGatherBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','9','145','stGatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','400','appraisalInstockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','400','appraisalInstockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','400','appraisalInstockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','400','appraisalInstockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','400','appraisalInstockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','400','appraisalInstockBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','400','appraisalInstockBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Contrast','条码对货','8','400','appraisalInstockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','9','400','appraisalInstockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','10','400','appraisalInstockBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','401','appraisalBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','401','appraisalBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','401','appraisalBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','401','appraisalBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','401','appraisalBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','401','appraisalBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','7','401','sendPtypeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','17','allotBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','17','allotBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','17','allotBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','17','allotBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','17','allotBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','17','allotBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','21','allotPriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','21','allotPriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','21','allotPriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','21','allotPriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','21','allotPriceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','21','allotPriceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','187','innerStockTranBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','187','innerStockTranBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','187','innerStockTranBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','187','innerStockTranBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','187','innerStockTranBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','187','innerStockTranBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','188','innerInStockTranBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','188','innerInStockTranBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','188','innerInStockTranBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','188','innerInStockTranBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','188','innerInStockTranBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','188','innerInStockTranBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','201','otherInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','201','otherInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','201','otherInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','201','otherInBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('OtherOperationSort','业务类别','5','201','otherInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','201','otherInBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','201','otherInBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','201','otherInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','202','otherOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','202','otherOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','202','otherOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','202','otherOutBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('OtherOperationSort','业务类别','5','202','otherOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','202','otherOutBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','202','otherOutBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','8','202','otherOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','1','306','doStockCheckBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','2','306','doStockCheckBillHead','0')
--INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('StockQtyEndDate','账面数截止时间','3','306','doStockCheckBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','9','loseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','9','loseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','9','loseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','9','loseBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','9','loseBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','9','loseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','14','overFlowBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','14','overFlowBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','14','overFlowBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','14','overFlowBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','14','overFlowBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','6','14','overFlowBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','87','lendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','87','lendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','87','lendBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','87','lendBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','87','lendBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','71','borrowBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','71','borrowBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','71','borrowBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','71','borrowBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','71','borrowBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','88','lendBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','88','lendBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','88','lendBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','88','lendBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','88','lendBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','72','BorrowBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','72','BorrowBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','72','BorrowBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','72','BorrowBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','72','BorrowBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','16','disassembleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','16','disassembleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','16','disassembleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','16','disassembleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','16','disassembleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','6','16','disassembleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','7','16','disassembleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','203','serialEdiBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','203','serialEdiBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','203','serialEdiBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','203','serialEdiBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','203','serialEdiBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','申请部门','1','22','posAllotApplyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','22','posAllotApplyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','22','posAllotApplyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','22','posAllotApplyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','412','stockUpShelvesBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','412','stockUpShelvesBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','413','stockPickBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','413','stockPickBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('freightperson','司机','2','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('freighttel','联系电话','3','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shipperfullname','托运方','4','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shipperperson','托运联系人','5','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('shippertel','托运联系电话','6','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('totalfreight','合计运费','7','414','stockTransportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('tax','税率','8','414','stockTransportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atype','付款账户','9','414','stockTransportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('TotalInmoney','付款金额','10','414','stockTransportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('transportno','承运商运单号','11','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','12','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','13','414','stockTransportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','14','414','stockTransportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','418','stockImportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','418','stockImportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','418','stockImportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','418','stockImportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','419','stockExmportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','419','stockExmportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','419','stockExmportBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','419','stockExmportBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','420','stockAllotBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','2','420','stockAllotBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','3','420','stockAllotBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','4','420','stockAllotBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','165','RepairReceiveBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','165','RepairReceiveBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','165','RepairReceiveBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','165','RepairReceiveBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','165','RepairReceiveBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','165','RepairReceiveBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','165','RepairReceiveBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','166','RepairSelfBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','166','RepairSelfBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','166','RepairSelfBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','166','RepairSelfBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','5','166','RepairSelfBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','6','166','RepairSelfBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','167','RepairGetBackBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','167','RepairGetBackBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','167','RepairGetBackBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','167','RepairGetBackBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','167','RepairGetBackBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','167','RepairGetBackBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','167','RepairGetBackBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','168','RepairChangeBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','168','RepairChangeBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','168','RepairChangeBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','168','RepairChangeBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','168','RepairChangeBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','168','RepairChangeBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','168','RepairChangeBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','169','RepairSendBil','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','169','RepairSendBil','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','169','RepairSendBil','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','169','RepairSendBil','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','169','RepairSendBil','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','170','RepairSendBackBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','170','RepairSendBackBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','170','RepairSendBackBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','170','RepairSendBackBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','171','RepairCallBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','171','RepairCallBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','171','RepairCallBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','171','RepairCallBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','171','RepairCallBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','171','RepairCallBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','171','RepairCallBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','172','RepairGoToBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','172','RepairGoToBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkMan','联系人','3','172','RepairGoToBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkTel','联系电话','4','172','RepairGoToBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('LinkAddr','联系地址','5','172','RepairGoToBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','172','RepairGoToBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','172','RepairGoToBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeOut','出库条码','8','172','RepairGoToBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCodeIn','入库条码','9','172','RepairGoToBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','173','RepairAllotInBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','173','RepairAllotInBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','173','RepairAllotInBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','173','RepairAllotInBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','173','RepairAllotInBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','174','RepairAllotOutBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','174','RepairAllotOutBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','174','RepairAllotOutBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','174','RepairAllotOutBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','174','RepairAllotOutBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','1','175','RepairAllotBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','2','175','RepairAllotBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','175','RepairAllotBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','175','RepairAllotBill','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('entryCode','条形码录入','5','175','RepairAllotBill','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','116','gatheraddBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','116','gatheraddBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','116','gatheraddBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','116','gatheraddBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','116','gatheraddBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','115','gatherReduceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','115','gatherReduceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','115','gatherReduceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','115','gatherReduceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','115','gatherReduceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','128','payAddBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','128','payAddBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','128','payAddBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','128','payAddBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','128','payAddBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','129','payReduceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','129','payReduceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','129','payReduceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','129','payReduceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','129','payReduceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','4','gatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','4','gatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','4','gatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','4','gatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','4','gatherBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','4','gatherBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','7','4','gatherBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','189','preSettleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','189','preSettleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','189','preSettleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','189','preSettleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','189','preSettleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','189','preSettleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','7','189','preSettleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','66','payBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','66','payBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','66','payBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','66','payBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','66','payBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','66','payBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','7','66','payBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','190','preSettlePayBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','190','preSettlePayBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','190','preSettlePayBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','190','preSettlePayBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','190','preSettlePayBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','190','preSettlePayBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','7','190','preSettlePayBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','148','advantageBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','148','advantageBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','148','advantageBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','148','advantageBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','148','advantageBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','148','advantageBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','148','advantageBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','148','advantageBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','150','advantageGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','150','advantageGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','150','advantageGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','150','advantageGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','150','advantageGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','150','advantageGetBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','150','advantageGetBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','150','advantageGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','149','priceProtectBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','149','priceProtectBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','149','priceProtectBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','149','priceProtectBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','149','priceProtectBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','149','priceProtectBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','149','priceProtectBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','149','priceProtectBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','151','priceProtectGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','151','priceProtectGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','151','priceProtectGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','151','priceProtectGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','151','priceProtectGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','151','priceProtectGetBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','151','priceProtectGetBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','151','priceProtectGetBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','450','wLCancelAfterVerificationBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','450','wLCancelAfterVerificationBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','3','450','wLCancelAfterVerificationBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Alertday','收付款期限','4','450','wLCancelAfterVerificationBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','450','wLCancelAfterVerificationBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('TotalMoney','本单核销金额','6','450','wLCancelAfterVerificationBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','162','saleInvoiceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','162','saleInvoiceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','162','saleInvoiceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','162','saleInvoiceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','162','saleInvoiceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','162','saleInvoiceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','162','saleInvoiceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','163','buyInvoiceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','163','buyInvoiceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','163','buyInvoiceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','163','buyInvoiceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','163','buyInvoiceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','163','buyInvoiceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','163','buyInvoiceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','404','receiptForBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','404','receiptForBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','404','receiptForBuyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','404','receiptForBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','404','receiptForBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','404','receiptForBuyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','404','receiptForBuyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目（借）','8','404','receiptForBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid2CanSelect','往来科目（贷）','9','404','receiptForBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','10','404','receiptForBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','405','receiptForSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','405','receiptForSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('FaPiaoCode','发票编号','3','405','receiptForSaleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','4','405','receiptForSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','5','405','receiptForSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','405','receiptForSaleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','405','receiptForSaleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','9','405','receiptForSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','10','405','receiptForSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','36','expenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','36','expenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','36','expenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','36','expenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收付款期限','5','36','expenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','36','expenseBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','36','expenseBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','36','expenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','158','cachExpenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','158','cachExpenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','158','cachExpenseBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','158','cachExpenseBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','158','cachExpenseBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','77','moneyChangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','77','moneyChangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','77','moneyChangeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','77','moneyChangeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','77','moneyChangeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','93','inComeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','93','inComeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','93','inComeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','93','inComeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','93','inComeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','93','inComeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','93','inComeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','93','inComeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','5','ExpenseHappenBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','5','ExpenseHappenBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','5','ExpenseHappenBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','5','ExpenseHappenBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','5','ExpenseHappenBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','10','expenseAllocateBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','10','expenseAllocateBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','10','expenseAllocateBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','10','expenseAllocateBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','10','expenseAllocateBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','84','fixedBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','84','fixedBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','84','fixedBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','84','fixedBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','付款期限','5','84','fixedBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','84','fixedBuyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','84','fixedBuyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','84','fixedBuyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','85','fixedSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','85','fixedSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','85','fixedSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','85','fixedSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','85','fixedSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','85','fixedSaleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','85','fixedSaleBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','85','fixedSaleBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','78','depBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','78','depBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','78','depBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','78','depBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','78','depBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','57','adpriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','57','adpriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','57','adpriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('warehouseoutday','出库期限','4','57','adpriceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','57','adpriceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','6','57','adpriceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','159','accountCredenceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','159','accountCredenceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','159','accountCredenceBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','159','accountCredenceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','159','accountCredenceBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','205','buyExpenseAmortizeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','205','buyExpenseAmortizeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','205','buyExpenseAmortizeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','205','buyExpenseAmortizeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','205','buyExpenseAmortizeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','206','saleExpenseAmortizeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','206','saleExpenseAmortizeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','206','saleExpenseAmortizeBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','4','206','saleExpenseAmortizeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','206','saleExpenseAmortizeBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','312','vipPlAddMoneyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','312','vipPlAddMoneyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','312','vipPlAddMoneyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','312','vipPlAddMoneyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('AlertDay','收款期限','5','312','vipPlAddMoneyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','6','312','vipPlAddMoneyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','7','312','vipPlAddMoneyBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','8','312','vipPlAddMoneyBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','423','CouponInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','423','CouponInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','423','CouponInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','423','CouponInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','423','CouponInBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','5','423','CouponInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','424','CouponOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','424','CouponOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','424','CouponOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','424','CouponOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','424','CouponOutBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','6','424','CouponOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','425','CouponAllotBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','2','425','CouponAllotBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','426','CouponBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','426','CouponBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','426','CouponBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','426','CouponBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','426','CouponBackBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Atypeid1CanSelect','往来科目','6','426','CouponBackBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Denominated','结算单位','1','183','qp_CentChange_BillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','2','183','qp_CentChange_BillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','3','183','qp_CentChange_BillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','4','183','qp_CentChange_BillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','5','183','qp_CentChange_BillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','428','CouponStypeInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','428','CouponStypeInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','428','CouponStypeInBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','428','CouponStypeInBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','428','CouponStypeInBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Department','部门','1','429','CouponStypeOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Currency','币种','2','429','CouponStypeOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('ExchangeRate','汇率','3','429','CouponStypeOutBillHead','0')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Comment','摘要','4','429','CouponStypeOutBillHead','1')
INSERT INTO BillHeadControlField(NameField,FullName,num,BillType,tabtype,isShow)VALUES('Explain','说明','5','429','CouponStypeOutBillHead','1')

--单据表体字段
TRUNCATE TABLE LoginUserCol
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','nsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','virtualstockqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','stockunitqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16Out','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','sourcebillname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','billcode','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','ncompletetotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','completetotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','unncompletetotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','uncompletetotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','ktypeid','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'404','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','sourcebillname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','billcode','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','ncompletetotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','completetotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','unncompletetotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','ktypeid','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','sourcebillname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'405','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','nocompleteqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','pricesource','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','costprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'402','costtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','nocompleteqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','costprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'403','costtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'201','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'201','stockunitqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'201','munit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'201','mqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'201','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'201','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'201','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'201','curmsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'202','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'202','stockunitqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'202','munit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'202','mqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'202','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'202','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'202','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','state','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','requestdate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','orderdate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','btypeid','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','nsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','total','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','discounttotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','taxmoney','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'204','taxtotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','jiejiancode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','jiejianusercode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','jiejianfullname','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','jiejianbuydate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','jiejianerrdes','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','errdes1','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','jiejianrepairmode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'169','jiejianstate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','jiejianusercode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','jiejianfullname','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','jiejianbuydate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','jiejianerrdes','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','jiejianrepairmode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','jiejianstate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','jiejiancode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'168','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'126','referprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','nsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','total','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','taxmoney','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'163','taxtotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','nsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','taxtotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','taxmoney','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'162','total','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','base','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'142','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','jiejiancode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','jiejianusercode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','jiejianfullname','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','jiejianbuydate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','jiejianerrdes','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','jiejianrepairmode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'167','jiejianstate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'165','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'165','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'165','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','mqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','stockunitqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','munit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'9','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'87','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'87','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'87','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','nsaletotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','base','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46up','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'57','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'57','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'57','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'57','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'57','adrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'57','nprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'57','ntotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'6','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','mqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','virtualstockqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','stockunitqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','munit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'17','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','nsaletotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'141','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'140','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','nsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','total','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'147','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'146','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'145','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'144','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'buyOrder','pricetotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'buyOrder','advantagetotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'buyOrder','zeropriceqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16In','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16In','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16In','nsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16In','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16In','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16In','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16In','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'16In','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'166Out','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'166Out','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'166Out','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','mqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','msaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','virtualstockqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','stockunitqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','munit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'21','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','munit','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','base','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','nocompleteqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','eusercode','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','efullname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','pricesource','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','promos','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'11','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'71','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'71','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'71','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','eusercode','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','efullname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160Out','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','eusercode','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','efullname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'45','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','nocompleteqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','invoiceqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','ninvoicemoneyex','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','invoicemoneyex','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','ninvoicemoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','invoicemoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','invoicenqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'401','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','factqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','frombillcode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'418','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'419','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'419','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'419','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'419','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'419','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'419','frombillcode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'419','factqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','eusercode','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','efullname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'160In','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'46down','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'414','weight','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'414','volume','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'412','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'412','billqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'412','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'412','billname','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'412','billcode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'413','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'413','behooveqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'413','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'413','billname','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'413','billcode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'413','rqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','accountqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','referprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'139','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','eusercode','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','efullname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','posusercode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','posfullname','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','munit','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'215','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','base','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161Out','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'88','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'88','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'88','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'173','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'173','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'173','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'171','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'171','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'171','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'170','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'170','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'170','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'170','sendcode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'170','sendusercode','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'170','sendfullname','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'170','sendbilldate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'170','senderrdes','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'175','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'175','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'175','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'174','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'174','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'174','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','nsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','total','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','referprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'143','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'161In','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','nsaletotal','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','reachqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','pricesource','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313up','stopreason','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'172Out','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'172Out','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'172Out','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','nsaletotal','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','reachqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','factqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','locknumber','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','pricesource','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','stopreason','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'313down','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','ntaxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','nocompleteqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','pricesource','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12down','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','base','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','nocompleteqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','pricesource','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','promos','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'12up','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'saleOrder','salecount','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'saleOrder','salebackcount','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'saleOrder','pricetotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'saleOrder','advantagetotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'saleOrder','zeropriceqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'saleOrder','qty_qz','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'saleOrder','total_qz','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'saleOrder','maoli_qz','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'72','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'72','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'72','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'172In','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'172In','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'172In','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','stockqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','stocknqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','stockcauqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','cauqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','countqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','countnqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'306','countcauqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','reachqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','base','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'301','stopreason','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','reachqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','base','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','factqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','locknumber','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','pricesource','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','stopreason','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'300','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'188','mqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'188','curmsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'188','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'188','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'188','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'188','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'188','munit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'188','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','base','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','eusercode','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','efullname','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','pricesource','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','promos','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'305','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','nocompleteqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'34','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','ntaxmoney','1')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','nocompleteqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','invoiceqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','ninvoicemoneyex','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','invoicemoneyex','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','ninvoicemoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','invoicemoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','invoicenqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'400','isgift','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'14','mqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'14','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'14','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'14','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'14','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'14','munit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'14','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'14','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','conversionrelationship','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','factqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'420','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','mqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','msaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','accountqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','virtualstockqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','munit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','stockunitqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','costprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'187','costtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','unit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','qty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','nsaleprice','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','assistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','customassistantunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','unitrate','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','nunit','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','nqty','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','total','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','discounttotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','taxmoney','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'185','taxtotal','0')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','unit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','qty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','nsaleprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','conversionrelationship','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','nqty','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','total','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','discounttotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','taxmoney','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','taxtotal','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','expectedinterestrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','expectedinterest','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','referprice','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','assistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'184','customassistantunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'183','unitrate','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'183','nunit','2')
INSERT INTO LoginUserCol(ETypeID,BillType,ColDataField,Display)VALUES(@etypeid,'183','nqty','2')



RETURN 0


GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_SetSomeLimitByOneLimit]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[GP_SetSomeLimitByOneLimit]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		处理升级，若操作员本来有某个权限，则拥有某些权限
-- 最后修改作者：	黄清
-- 最后修改时间：	2014-02-08
-- ========================================================================
CREATE PROCEDURE GP_SetSomeLimitByOneLimit
(
	@Operator	VARCHAR(MAX),	-- 操作员id
	@limit		VARCHAR(50),	--操作员原拥有的权限位
	@limits		VARCHAR(MAX),	--操作员拥有的新增权限
	@flag		VARCHAR(1)		--标志 0.处理全部操作员，1.处理@Operator里的操作员
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ope (TYPEID VARCHAR(50)) 
IF @flag=1
	INSERT INTO #Ope (TYPEID) SELECT *FROM f_split(@Operator,',')
ELSE
	INSERT INTO #Ope (TYPEID) SELECT etypeid FROM LoginUser


CREATE TABLE #lim (lim VARCHAR(10))
INSERT INTO #lim (lim) SELECT *FROM f_split(@limits,',')
DELETE FROM #lim WHERE lim='' OR lim IS NULL

DECLARE @OldLimitValue VARCHAR(2)


DECLARE @opecount INT
DECLARE @limcount INT
DECLARE @operatorid VARCHAR(50)
DECLARE @limposition VARCHAR(10)
DECLARE @lim VARCHAR(MAX)
DECLARE @limitleft VARCHAR(MAX)
DECLARE @limitright VARCHAR(MAX)

DELETE FROM #OPE WHERE TYPEID='00001' --超级管理员不处理

SELECT @opecount=COUNT(1) FROM #OPE

WHILE(@opecount>0)
BEGIN
	SELECT TOP (@opecount) @operatorid=TYPEID FROM #OPE 

	SELECT @lim=lim FROM LoginUser WHERE etypeid=@operatorid
	--取原权限位的值
	SET @OldLimitValue=SUBSTRING(@lim,CAST(@limit AS INT),1)

	IF @OldLimitValue='1'
	BEGIN
		SELECT @limcount=COUNT(1) FROM #lim
		WHILE (@limcount>0)
		BEGIN
			SELECT TOP (@limcount) @limposition=lim FROM #lim
			SET @limitleft=LEFT(@lim,CAST(@limposition AS INT)-1)
			SET @limitright=RIGHT(@lim,LEN(@lim)-CAST(@limposition AS INT))
			SET @lim=@limitleft+'1'+@limitright
			UPDATE LoginUser SET lim=@lim WHERE etypeid=@operatorid
			SET @limcount=@limcount-1
		END
	END
	SET @opecount=@opecount-1
END

DROP TABLE #Ope,#lim

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SetSubValue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SetSubValue]
GO














/****** Object:  Stored Procedure dbo.Gp_SetSubValue    Script Date: 2002-6-20 10:14:51 ******/

CREATE  PROCEDURE Gp_SetSubValue
(
	@szName		varchar(30),
	@szValue	varchar(50),
	@stypeid	varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 

--新的按分支机构开账方式
IF EXISTS(SELECT TOP 1 1 FROM SType_Config C,SType_UserConfig U WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND ISNULL(U.STypeID,'') = @stypeid)
	BEGIN
		UPDATE	SType_UserConfig
		SET		Value = '1'
		FROM	SType_Config C,
				SType_UserConfig U
		WHERE	C.ConfigNo = U.ConfigNo 
				AND C.ConfigName = 'stypeinicanmodify' 
				AND ISNULL(U.STypeID,'') = @stypeid
	END
ELSE
	BEGIN
		INSERT INTO SType_UserConfig
		(
			ConfigNo,
			Value,
			EtypeId,
			STypeID
		)
		SELECT	ConfigNo,
				'1' AS Value,
				'00001' AS ETypeId,
				@stypeid AS STypeId
		FROM	SType_Config
		WHERE	ConfigName = 'stypeinicanmodify' 
	END

--有一个总的开账标识
UPDATE	sysdata 
SET		SubValue=@szValue 
WHERE	SubName=@szName














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_ShareDocFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_ShareDocFile
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-12-19
	描述：文档管理系统文档共享
*/
CREATE PROCEDURE Gp_ShareDocFile
(
	@id					int,				--文档id
	@etypeid			varchar(50),		--上传者id
	@uploaddate			datetime,			--上传时间
	@pathid				varchar(50),		--路径id
	@filesize			int,				--文件大小
	@filename			varchar(200),		--文件名称
	@filetype			varchar(50)			--文件类型
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT * FROM DocFile WHERE etypeid=@etypeid AND pathId=@pathid AND FullName=@filename)
BEGIN
	RAISERROR('你已经共享了相同文件名的文档！请重命名文档后重试！',16,1)
	RETURN
END

INSERT INTO DocFile
(
	etypeid,
	UploadDate,
	pathId,
	FileSize,
	FileType,
	FullName,
	Binarydata
)
VALUES
(
	@etypeid,
	@uploaddate,
	@pathid,
	@filesize,
	@filetype,
	@filename,
	(SELECT Binarydata FROM DocFile WHERE ID=@id)
)

IF @@ERROR<>0
	RAISERROR('共享文件失败！',16,1)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Showsubname]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Showsubname]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE Gp_Showsubname
--@encode$--
AS
SET NOCOUNT ON

 IF (
		EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'Edition' AND SubValue = '1')
			AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '2'))
	)
	OR EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'ProInfo' AND SubValue = '3')
BEGIN
RETURN 1
END
ELSE
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SortAllVoucherIdentifier]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SortAllVoucherIdentifier]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.06。27
	描述：将指定分支机构的所有凭证进行凭证号重排
*/
CREATE PROCEDURE GP_SortAllVoucherIdentifier
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@Stypeid			VARCHAR(50)			--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Fyear INT,@SFperiod INT,@EFperiod	INT

SELECT DISTINCT FYear INTO #TmpYear FROM dbo.Ac_Period

DECLARE Fyearcur CURSOR READ_ONLY FOR
	SELECT FYear
	FROM #TmpYear
OPEN Fyearcur

FETCH NEXT FROM Fyearcur INTO @Fyear

WHILE @@FETCH_STATUS = 0
BEGIN
	
	SELECT @SFperiod = MIN(FPeriod) FROM dbo.Ac_Period WHERE FYear = @Fyear
	SELECT @EFperiod = MAX(FPeriod) FROM dbo.Ac_Period WHERE FYear = @Fyear
	
	EXEC dbo.GP_SortVoucherIdentifier @OperatorId,@Stypeid,@Fyear,@SFperiod,@EFperiod,''
	
	FETCH NEXT FROM Fyearcur INTO @Fyear
END

CLOSE Fyearcur
DEALLOCATE Fyearcur

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SortVoucherIdentifier]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SortVoucherIdentifier]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013-06-26
	描述：重排会计期间内凭证的凭证号
*/
CREATE PROCEDURE GP_SortVoucherIdentifier
(
	@OperatorId		VARCHAR(50),		--当前操作员ID
	@Stypeid		VARCHAR(50),		--分支机构
	@Fyear			INT,				--年度
	@SFperiod		INT,				--起始期间
	@EFperiod		INT,				--截止期间
	@Vgid			VARCHAR(1000) = ''	--凭证字
)
--@encode$--
AS
SET NOCOUNT ON


CREATE TABLE #Tmp_VoucherFlowNo
(
	billnumberid	INT,
	newflowno		INT IDENTITY(1,1)
)

CREATE TABLE #Tmp_Vgid
(
	vgid	INT
)

IF @Vgid <> ''
	INSERT INTO #Tmp_Vgid( vgid )
	SELECT a AS vgid
	FROM dbo.f_split(@Vgid,',')
ELSE
	INSERT INTO #Tmp_Vgid( vgid )
	SELECT vgid FROM dbo.Ac_Voucher_Group

DECLARE @Index INT,@currentVgid INT
SET @Index = @SFperiod

WHILE @Index <= @EFperiod
BEGIN
	
	DECLARE FlowCur CURSOR READ_ONLY FOR
		SELECT vgid
		FROM #Tmp_Vgid
	OPEN FlowCur
	FETCH NEXT FROM FlowCur INTO @currentVgid
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO #Tmp_VoucherFlowNo
		        ( billnumberid)
		SELECT billnumberid
		FROM dbo.Ac_Voucher
		WHERE STypeId = @Stypeid AND FYear = @Fyear AND FPeriod = @Index AND VgId = @currentVgid
		ORDER BY BillDate ASC,BillNumberId ASC
		
		UPDATE dbo.Ac_Voucher SET FlowNo = T1.newflowno FROM #Tmp_VoucherFlowNo T1 INNER JOIN dbo.Ac_Voucher T2 ON T1.billnumberid = T2.BillNumberId
		
		TRUNCATE TABLE #Tmp_VoucherFlowNo
		
		FETCH NEXT FROM FlowCur INTO @currentVgid
	END
	
	CLOSE FlowCur
	DEALLOCATE FlowCur
	
	SET @Index += 1
END

DROP TABLE #Tmp_Vgid,#Tmp_VoucherFlowNo

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GP_StartAcTable]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_StartAcTable]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	glj
	Date	:	2019-05-16
	Description	:	v3启用科目模板设置
*/

CREATE PROCEDURE GP_StartAcTable
(
	@SubID	INT  --科目表模板ID
)
--@encode$--
AS 
SET NOCOUNT ON

UPDATE Ac_Account_Set_List SET IsUse = 1 WHERE SubId = @SubID;
UPDATE Ac_Account_Set_List SET IsUse = 0 WHERE SubId <> @SubID
 
--删除原模板公式   
TRUNCATE TABLE ThreeFinancialItemParent_Stype
TRUNCATE TABLE ThreeFinancialItem_SType
TRUNCATE TABLE ThreeFinancialFormula_Stype                             
 
 --导入科目模板时直接引入三大报表公式

--具体分支机构 项目
INSERT INTO ThreeFinancialItem_SType(
	ReportType,
	STypeID,
	ItemID,
	ItemFullName,
	Formula1IsPar, 
	Formula2IsPar
)
SELECT 
	F.ReportType,
	S.TypeId STypeID,
	F.ItemID,
	F.ItemFullName,
	F.Formula1IsPar, 
	F.Formula2IsPar
FROM SType S,ThreeFinancialItem F
WHERE 
	F.AccountSubId=@SubID
	AND S.sonnum=0
GROUP BY 
	F.ReportType,
	S.TypeId,
	F.ItemID,
	F.ItemFullName,
	F.Formula1IsPar, 
	F.Formula2IsPar 

--项目子级公式表
INSERT INTO ThreeFinancialFormula_Stype(
	ReportType,
	STypeID,
	ItemID,
	[SIGN],
	Formula,
	RowId,
	FormulaType,
	IsEditAll
)
SELECT 
	ReportType,
	S.TypeId STypeID,
	ItemID,
	[SIGN],
	Formula,
	RowId,
	FormulaType,
	0 IsEditAll
FROM SType S,ThreeFinancialFormula F
WHERE 
	F.AccountSubId=@SubID
	AND S.sonnum=0
GROUP BY 
	ReportType,
	S.TypeId,
	ItemID,
	[SIGN],
	Formula,
	RowId,
	FormulaType

--项目父级公式表
INSERT INTO ThreeFinancialItemParent_Stype(
	ReportType,				--1:利润表 2：现金流量表 3：资产负债表
	STypeID,		--分支机构ID 
	ParItemID,--父类项目ID
	[Sign],--公式符号 1：正 -1负
	SonItemID,--自己项目ID
	FormulaType--公式类型比如利润表1：本期金额 2本年累计金额
)
SELECT 
	ReportType,
	S.TypeId STypeID,
	F.ParItemID,
	F.[Sign],
	F.SonItemID,
	F.FormulaType
FROM SType S,ThreeFinancialItemParent F
WHERE 
	F.AccountSubId=@SubID
	AND S.sonnum=0
GROUP BY 
	ReportType,
	S.TypeId,
	F.ParItemID,
	F.[Sign],
	F.SonItemID,
	F.FormulaType

 
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_StockAlarmAutoSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_StockAlarmAutoSet]
GO


-- 时间：2007-03-21 
-- 作者：徐辉
-- 功能：批量设置库存上下限报警
CREATE                      PROCEDURE GP_StockAlarmAutoSet
(
	@OperatorID	varchar(100),
	@PUserCode	varchar(200),	--过滤商品标号
	@PFullName	varchar(200),	--过滤商品名称
	@KTypeId	varchar(MAX), 	--仓库Id
	@UpFormula	int,			--上限公式
	@UpCalculate	int,		--上限算法
	@UpFactor	 NUMERIC(24, 10) ,	--上限因子
	@DownFormula	int,		--下限公式
	@DownCalculate	int,		--下限算法
	@DownFactor	 NUMERIC(24, 10) ,	--下限因子
	@OrderFormula	int,		--库存限公式
	@OrderCalculate	int,		--库存限算法
	@OrderFactor	 NUMERIC(24, 10) ,	--库存限因子,
	@ptypeids         VARCHAR(max),--商品id
	@querytype       VARCHAR(15), --是选择商品	还是筛选商品 mutiplequery为选择商品
	@LeftFullName	varchar(800)='' OUTPUT,	--返回有负数的商品名称
	@RightFullName	varchar(800)='' OUTPUT	--返回下限大于等于上限的商品名称
)
--@encode$--
As
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId('',11,@OperatorID)
DECLARE @stid VARCHAR(100)
SELECT TOP  1 @stid=stypeid FROM stock WHERE typeId=@KTypeId
 
DECLARE @SQL varchar(6000)

CREATE TABLE #Ptype(
	typeId		varchar(100),
	UserCode	varchar(200),
	FullName	varchar(200)
)
CREATE CLUSTERED INDEX #ptype_p_k ON #Ptype(typeid)

--生成更新商品临时表
IF @querytype!='mutiplequery'
BEGIN
	INSERT INTO #Ptype 
	SELECT 	P.typeId,
			P.UserCode,
			P.FullName 
	FROM 	PType P
	INNER JOIN (SELECT * FROM F_GetManDetailPType(@OperatorID)) M ON M.TypeId = P.typeId
	WHERE 	P.SonNum=0
			AND P.UserCode LIKE '%'+@PUserCode+'%'
			AND P.FullName LIKE '%'+@PFullName+'%'
			AND P.IsService=0
	END
ELSE
BEGIN
	INSERT INTO #Ptype 
	SELECT 	a.typeId,
			a.UserCode,
			a.FullName 
	FROM 	PType a
	INNER JOIN (select typeid from dbo.F_GetAllManagerBaseTypeId(@ptypeids,1,@operatorid)) M ON M.TypeId = a.typeId
	WHERE 	a.SonNum=0
			AND a.IsService=0			
END

--已经有的记录
CREATE TABLE #ExistPtype(
	PtypeId		varchar(100),
	KtypeId		varchar(100),
	UPLimitQty	 NUMERIC(24, 10) ,
	DownLimitQty	 NUMERIC(24, 10) ,
	OrderQty	 NUMERIC(24, 10) 
)

--没有的记录
CREATE TABLE #NoExistPtype(
	PtypeId		varchar(100),
	KtypeId		varchar(100),
	UPLimitQty	 NUMERIC(24, 10) ,
	DownLimitQty	 NUMERIC(24, 10) ,
	OrderQty	 NUMERIC(24, 10) 	
)

--stockAlarm中有的记录
INSERT INTO #ExistPtype
SELECT	s.PTypeId,
		s.KtypeId,
		s.UPLimitQty,
		s.DownLimitQty,
		s.OrderQty
FROM	StockAlarm As S,#Ptype AS p
WHERE	s.PtypeId=p.typeId
		AND s.KtypeId=@KTypeId

--stockAlarm中没有的记录
INSERT INTO #NoExistPtype
SELECT	TypeId AS PTypeId,
		@KTypeId AS KtypeId,
		0 AS UPLimitQty,
		0 AS DownLimitQty,
		0 AS OrderQty
FROM	#Ptype
WHERE	typeId NOT IN (SELECT PTypeID FROM #ExistPtype)

--计算开帐到现在的天数
DECLARE @DayCount int
SELECT @DayCount=DATEDIFF(DAY, (SELECT distinct StartDate FROM MonthProc WHERE period=(SELECT MAX(period) FROM MonthProc)), getdate()) 

IF @DayCount<0
	SET @DayCount=1
ELSE
	SET @DayCount=@DayCount+1


--处理公式
DECLARE @UpFormulaStr varchar(8000)
DECLARE @strUpCalculate varchar(8000)
DECLARE @DownFormulaStr varchar(8000)
DECLARE @strDownCalculate varchar(8000)
DECLARE @OrderFormulaStr varchar(8000)
DECLARE @strOrderCalculate varchar(8000)

--无公式
IF @UpFormula=1
	SET @UpFormulaStr='e.UPLimitQty'
--日平均销售量
IF @UpFormula=2
BEGIN
	IF @KTypeId='00000'
		SET @UpFormulaStr='ISNULL((SELECT -1*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @UpFormulaStr='ISNULL((SELECT -1*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END
--周平均销售量
IF @UpFormula=3
BEGIN
	IF @KTypeId='00000'
		SET @UpFormulaStr='ISNULL((SELECT -7*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @UpFormulaStr='ISNULL((SELECT -7*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END
--月平均销售量
IF @UpFormula=4
BEGIN
	IF @KTypeId='00000'
		SET @UpFormulaStr='ISNULL((SELECT -30*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @UpFormulaStr='ISNULL((SELECT -30*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END

--处理计算
IF @UpCalculate=1
	SET @strUpCalculate=@UpFormulaStr+'+'+CAST(@UpFactor AS varchar(20))
IF @UpCalculate=2
	SET @strUpCalculate=@UpFormulaStr+'-'+CAST(@UpFactor AS varchar(20))
IF @UpCalculate=3
	SET @strUpCalculate=@UpFormulaStr+'*'+CAST(@UpFactor AS varchar(20))
IF @UpCalculate=4
	SET @strUpCalculate=@UpFormulaStr+'/'+CAST(@UpFactor AS varchar(20))

--无公式
IF @DownFormula=1
	SET @DownFormulaStr='E.DownLimitQty'
--日平均销售量
IF @DownFormula=2
BEGIN
	IF @KTypeId='00000'
		SET @DownFormulaStr='ISNULL((SELECT -1*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @DownFormulaStr='ISNULL((SELECT -1*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END
IF @DownFormula=3
BEGIN
	IF @KTypeId='00000'
		SET @DownFormulaStr='ISNULL((SELECT -7*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @DownFormulaStr='ISNULL((SELECT -7*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END
IF @DownFormula=4
BEGIN
	IF @KTypeId='00000'
		SET @DownFormulaStr='ISNULL((SELECT -30*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @DownFormulaStr='ISNULL((SELECT -30*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END

--处理计算
IF @DownCalculate=1
	SET @strDownCalculate=@DownFormulaStr+'+'+CAST(@DownFactor AS varchar(20))
IF @DownCalculate=2
	SET @strDownCalculate=@DownFormulaStr+'-'+CAST(@DownFactor AS varchar(20))
IF @DownCalculate=3
	SET @strDownCalculate=@DownFormulaStr+'*'+CAST(@DownFactor AS varchar(20))
IF @DownCalculate=4
	SET @strDownCalculate=@DownFormulaStr+'/'+CAST(@DownFactor AS varchar(20))
	
--无公式
IF @OrderFormula=1
	SET @OrderFormulaStr='E.OrderQty'
--日平均销售量
IF @OrderFormula=2
BEGIN
	IF @KTypeId='00000'
		SET @OrderFormulaStr='ISNULL((SELECT -1*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @OrderFormulaStr='ISNULL((SELECT -1*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END
IF @OrderFormula=3
BEGIN
	IF @KTypeId='00000'
		SET @OrderFormulaStr='ISNULL((SELECT -7*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @OrderFormulaStr='ISNULL((SELECT -7*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END
IF @OrderFormula=4
BEGIN
	IF @KTypeId='00000'
		SET @OrderFormulaStr='ISNULL((SELECT -30*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND PtypeId=E.PtypeId),0)'
	ELSE
		SET @OrderFormulaStr='ISNULL((SELECT -30*SUM(Qty)/'+CAST(@DayCount AS varchar(20))+' FROM InOutStockTable WHERE BillType In(305,11,45,160,141) AND KtypeId='''+@KTypeId+''' AND PtypeId=E.PtypeId),0)'
END

--处理计算
IF @OrderCalculate=1
	SET @strOrderCalculate=@OrderFormulaStr+'+'+CAST(@OrderFactor AS varchar(20))
IF @OrderCalculate=2
	SET @strOrderCalculate=@OrderFormulaStr+'-'+CAST(@OrderFactor AS varchar(20))
IF @OrderCalculate=3
	SET @strOrderCalculate=@OrderFormulaStr+'*'+CAST(@OrderFactor AS varchar(20))
IF @OrderCalculate=4
	SET @strOrderCalculate=@OrderFormulaStr+'/'+CAST(@OrderFactor AS varchar(20))	

--处理本来有的记录
SET @SQL='UPDATE #ExistPtype 
		SET 	UPLimitQty='+@strUpCalculate+', DownLimitQty='+@strDownCalculate+',OrderQty='+@strOrderCalculate+'
		FROM 	#ExistPtype E'


EXECUTE(@SQL)

--处理没有的记录
SET @SQL='UPDATE #NoExistPtype 
		SET UPLimitQty='+@strUpCalculate+', DownLimitQty='+@strDownCalculate+',OrderQty = '+@strOrderCalculate+'
		FROM 	#NoExistPtype E'

--PRINT(@SQL)
EXECUTE(@SQL)

--还要过滤1、负数 2、下限大于上限
DECLARE @PtypeId varchar(100),@FullName varchar(200),@UserCode varchar(200)
DECLARE @Count int

SET @Count=1
SET @LeftFullName=''
SET @RightFullName=''


--小于0的提示
DECLARE CountCursor CURSOR FOR
	SELECT P.FullName FROM (SELECT * FROM #NOExistPtype UNION SELECT * FROM #ExistPtype) N LEFT JOIN #Ptype P ON P.typeId = N.PtypeId WHERE N.UPLimitQty<0 OR N.DownLimitQty<0 OR N.OrderQty < 0

OPEN CountCursor
FETCH NEXT FROM CountCursor INTO @FullName
WHILE @@FETCH_STATUS = 0 AND @Count<6
BEGIN
	IF @LeftFullName=''
		SET @LeftFullName=@FullName
	ELSE
		SET @LeftFullName=@LeftFullName+','+@FullName
	SET @Count=@Count+1
	FETCH NEXT FROM CountCursor INTO @FullName
END

CLOSE CountCursor
DEALLOCATE CountCursor


--上限小于等于下限的提示
DECLARE CountCursor CURSOR FOR
	SELECT P.FullName FROM (SELECT * FROM #NOExistPtype UNION SELECT * FROM #ExistPtype) N LEFT JOIN #Ptype P ON P.typeId = N.PtypeId WHERE  N.UPLimitQty<>0 AND N.UPLimitQty<=N.DownLimitQty

SET @Count=1

OPEN CountCursor
FETCH NEXT FROM CountCursor INTO @FullName
WHILE @@FETCH_STATUS = 0 AND @Count<6
BEGIN
	IF @RightFullName=''
		SET @RightFullName=@FullName
	ELSE
		SET @RightFullName=@RightFullName+','+@FullName
	SET @Count=@Count+1
	FETCH NEXT FROM CountCursor INTO @FullName
END

CLOSE CountCursor
DEALLOCATE CountCursor

DROP TABLE #Ptype

--将大于等于0的符合条件的数据写入数据库
INSERT INTO StockAlarm 
SELECT 	* 
FROM 	#NOExistPtype 
WHERE 	UPLimitQty>=0 
		AND DownLimitQty>=0 
		AND OrderQty>=0 
		AND (UPLimitQty>DownLimitQty OR UPLimitQty=0)

UPDATE 	StockAlarm  
SET 	UPLimitQty=E.UPLimitQty, 
		DownLimitQty=E.DownLimitQty,
		OrderQty = E.OrderQty
FROM 	#ExistPtype E,
		StockAlarm S
WHERE	E.PtypeId=S.PtypeId 
		AND E.KtypeId=S.KtypeId
		AND E.UPLimitQty>=0 
		AND E.DownLimitQty>=0 
		AND E.OrderQty>=0
		AND (E.UPLimitQty>E.DownLimitQty OR E.UPLimitQty=0)

DROP TABLE #ExistPtype,#NOExistPtype,#GetSelectSTypeId



IF @RightFullName = '' AND @LeftFullName = ''
BEGIN
	--修改9.3BUG 1478 删除为0数据
	DELETE FROM StockAlarm WHERE UpLimitQty=0 AND DownLimitQty=0 AND OrderQty=0
	RETURN 0
END
IF  @LeftFullName = '' AND @RightFullName <> '' --有下限大于等于上限
BEGIN
	--修改9.3BUG 1478 删除为0数据
	DELETE FROM StockAlarm WHERE UpLimitQty=0 AND DownLimitQty=0 AND OrderQty=0
	RETURN -1
END
IF  @LeftFullName <> '' AND @RightFullName = '' --有负数
BEGIN
	--修改9.3BUG 1478 删除为0数据
	DELETE FROM StockAlarm WHERE UpLimitQty=0 AND DownLimitQty=0 AND OrderQty=0
	RETURN -2
END
IF @LeftFullName <> '' AND @RightFullName <> '' --都有
BEGIN
	--修改9.3BUG 1478 删除为0数据
	DELETE FROM StockAlarm WHERE UpLimitQty=0 AND DownLimitQty=0 AND OrderQty=0
	RETURN -3
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StockAlermUpOrDownDataAutoCaoGao]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StockAlermUpOrDownDataAutoCaoGao]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2009-06-03
	描述：库存上下限报警查询数据
	exec Gp_StockAlermUpOrDownDataAutoCaoGao @OperatorId='00001',@KTypeId='00000',@UserCode='',@FullName='',@Flag='3',@bFlag='5',@rtype='3',@chk='0',@numvalue='0',@etypeid='',@ptypeid='',@bcode=NULL output,@Parameter1=NULL
*/
CREATE   PROCEDURE Gp_StockAlermUpOrDownDataAutoCaoGao
(
	@OperatorId		varchar(200),
	@KTypeId		varchar(8000),
	@UserCode		varchar(300),
	@FullName		varchar(300),
	@Flag			int,
	@bFlag			int,--1：销售出库单 2：采购退货单 3：报损单 4：销售订单
	@rType			VARCHAR(10),	--1.按库存上限 2.指定库存数量【上限】 3.按库存下限 4.订货库存 5.指定库存数量【下限】
	@Chk			VARCHAR(10),
	@NumValue		VARCHAR(100),
	@ETypeId		VARCHAR(100),
	@PTypeId		VARCHAR(8000),
	@bcode			varchar(8000) OUTPUT,
	@ktypeid1		VARCHAR(100),	--单据所生成的仓库
	@virtualStock	CHAR(1),		--是否用虚拟库存数量 1.表示用 0表示没用
	@VirtualQtySQL	VARCHAR(MAX),	--虚拟库存数量计算公式
	@UnitType		INT				--生成单位选择 1：基本计量单位 2：销售默认单位 3:采购默认单位 4:存货默认单位
)
--@encode$--
AS
SET NOCOUNT ON
-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

DECLARE
	@NowDate	DATETIME
SELECT @NowDate=GETDATE()

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -5
	END
END  

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @cargoid INT

IF @ktypeid1 = ''
SET @cargoid=0
ELSE 
SELECT  @cargoid=CargoID FROM dbo.CargoType WHERE IsDefault=1 AND KtypeID=@ktypeid1 AND deleted=0


DECLARE @stid  VARCHAR(100) --查询分支机构
SELECT TOp 1 @stid = stypeid FROM stock WHERE typeId = @ktypeid1

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX GetManPTypeId_IX ON #GetManPTypeId(TypeId)

INSERT INTO #GetManPTypeId(TypeId) 
SELECT	a.TypeId 
FROM	F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID) a
INNER JOIN dbo.ptype b ON a.TypeId=b.typeId
WHERE	b.IsService=0 
		AND B.iscombinationproduct = 0


DECLARE @SQL VARCHAR(MAX),
		@UnitsStr VARCHAR(50)--单位选择
--根据客户选择设定生成单据默认单位
IF(@UnitType=1)--基本
	SET @UnitsStr='baseUnitId'
IF(@UnitType=2)--销售
	SET @UnitsStr='SaleUnitId'
IF(@UnitType=3)--采购
	SET @UnitsStr='BuyUnitId'
IF(@UnitType=4)--存货
	SET @UnitsStr='StockUnitId'
	
--商品汇率表	
CREATE TABLE #GetManPTypeId1
(
	TypeId		varchar(100),	--商品ID
	rate		 NUMERIC(24, 10) ,	--辅助默认单位id汇率
	aunitid		VARCHAR(200),	--辅助默认单位id
	CRate		 NUMERIC(24, 10) ,	--客户选择单位换算单位汇率
	CUnitId		VARCHAR(200),	--客户选择单位换算单位ID
)
SET @SQL='
INSERT INTO #GetManPTypeId1(TypeId,rate,aunitid,CRate,CUnitId) 
SELECT	c.TypeId,
		ISNULL(b.Rate,0)AS rate,
		ISNULL(b.UnitsId,0)AS aunitid,
		ISNULL(b1.Rate,0)AS CRate,
		ISNULL(b1.UnitsId,0)AS UnitsId
FROM	#GetManPTypeId c 
INNER  JOIN  dbo.ptype  a ON c.TypeId = a.typeId 
LEFT JOIN dbo.PType_Units_Ext b ON a.typeId=b.PtypeID AND a.AssistantUnitId=b.UnitsId
INNER JOIN dbo.PType_Units_Ext b1 ON a.typeId=b1.PtypeID AND a.'+@UnitsStr+'=b1.UnitsId'
EXEC(@SQL)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)

IF @KTypeId = '00000'
	INSERT INTO #GetManKTypeId(TypeId)VALUES('00000')

CREATE TABLE #GoodsStocks
(
	PTypeId			varchar(200),
	KTypeId			VARCHAR(200),
	Qty				 NUMERIC(24, 10) ,
	Total			 NUMERIC(24, 10) 
)
DECLARE @GSQL VARCHAR(MAX)
   
DECLARE @virtualstock_1 VARCHAR(10)
SET @virtualstock_1 =CASE WHEN @virtualstock = '1' THEN 'true' ELSE 'false' END

CREATE TABLE #QueryBjData
(
	typeid			VARCHAR(50),
	unit1			VARCHAR(50),
	usercode		VARCHAR(500),
	fullname		VARCHAR(500),
	qty				NUMERIC(24,10),
	price			NUMERIC(24,10),
	total			NUMERIC(24,10),
	upqty			NUMERIC(24,10),
	ccqty			NUMERIC(24,10),
	cctotal			NUMERIC(24,10),
	downqty			NUMERIC(24,10),
	syqty			NUMERIC(24,10),
	sytotal			NUMERIC(24,10),
	orderqty		NUMERIC(24,10),
	syorderqty		NUMERIC(24,10),
	syordertotal	NUMERIC(24,10),
	zdqty			NUMERIC(24,10),
	cczdqty			NUMERIC(24,10),
	cczdtotal		NUMERIC(24,10),
	syzdqty			NUMERIC(24,10),
	syzdtotal		NUMERIC(24,10),
	salecanqty		NUMERIC(24,10),
	salezdtotal		NUMERIC(24,10)
)
INSERT INTO #QueryBjData
(
	typeid,
	unit1,
	usercode,
	fullname,
	qty,
	price,
	total,
	upqty,
	ccqty,
	cctotal,
	downqty,
	syqty,
	sytotal,
	orderqty,
	syorderqty,
	syordertotal,
	zdqty,
	cczdqty,
	cczdtotal,
	syzdqty,
	syzdtotal,
	salecanqty,
	salezdtotal
)
EXEC Web_QueryStockAlermUpOrDownData	@OperatorId=@OperatorId,
										@ETypeId=@etypeid,
										@KTypeId=@KTypeId,
										@PTypeId=@PTypeId,
										@UserCode=@UserCode,
										@FullName=@FullName,
										@Flag=@Flag,
										@rType=@rtype,
										@numValue=@numvalue,
										@virtualstock=@virtualstock_1,
										@isLoginHit=0,
										@virtualqtysql=@virtualqtysql

CREATE TABLE #Result
(
	PTypeId			varchar(200),
	Qty		   		 NUMERIC(24, 10) ,
	Price	   		 NUMERIC(24, 10) ,
	Total			 NUMERIC(24, 10) ,
	UpQty			 NUMERIC(24, 10) ,
	DownQty	   		 NUMERIC(24, 10) ,
	OrderQty		 NUMERIC(24, 10) ,
	ZdQty			 NUMERIC(24, 10) ,
	CcQty			 NUMERIC(24, 10) ,
	CcTotal			 NUMERIC(24, 10) ,
	SyQty			 NUMERIC(24, 10) ,
	SyTotal			 NUMERIC(24, 10) ,
	SyOrderQty		 NUMERIC(24, 10) ,
	SyOrderTotal	 NUMERIC(24, 10) ,
	CcZdQty			 NUMERIC(24, 10) ,
	CcZdTotal 		 NUMERIC(24, 10) ,
	SyZdQty			 NUMERIC(24, 10) ,
	SyZdTotal		 NUMERIC(24, 10) 
)

CREATE TABLE #MxBillold
(
	nid			int identity(1,1),
	PTypeId		varchar(200),
	BTypeId		VARCHAR(200),
	Qty			 NUMERIC(24, 10) ,
	recPrice	 NUMERIC(24, 10) ,
	prePrice1	 NUMERIC(24, 10) ,
	unitid      INT 
)

--计算主要数据
INSERT INTO #Result
SELECT	X.PTypeId,
		SUM(X.Qty) AS Qty,
		CAST(CASE WHEN SUM(Qty)=0 THEN 0 ELSE SUM(Total)/SUM(Qty) END as  NUMERIC(24, 10) ) AS Price,
		SUM(X.Total) AS Total,
		SUM(X.UpQty) AS UpQty,
		SUM(X.DownQty) AS DownQty,
		SUM(X.OrderQty) AS OrderQty,
		@numvalue AS ZdQty,
		SUM(X.CcQty) AS CcQty,
		CAST(SUM(X.CcQty)*CAST(CASE WHEN SUM(Qty)=0 THEN 0 ELSE SUM(Total)/SUM(Qty) END as  NUMERIC(24, 10) ) as  NUMERIC(24, 10) ) AS CcTotal,
		SUM(X.SyQty) AS SyQty,
		CAST(SUM(X.SyQty)*CAST(CASE WHEN SUM(Qty)=0 THEN 0 ELSE SUM(Total)/SUM(Qty) END as  NUMERIC(24, 10) ) as  NUMERIC(24, 10) ) AS SyTotal,
		SUM(X.SyOrderQty) AS SyOrderQty,
		CAST(SUM(X.SyOrderQty)*CAST(CASE WHEN SUM(Qty)=0 THEN 0 ELSE SUM(Total)/SUM(Qty) END as  NUMERIC(24, 10) ) as  NUMERIC(24, 10) ) AS SyOrderTotal,
		SUM(X.Qty)-@numvalue AS CcZdQty,
		CAST((SUM(X.Qty)-@numvalue)*CAST(CASE WHEN SUM(Qty)=0 THEN 0 ELSE SUM(Total)/SUM(Qty) END as  NUMERIC(24, 10) ) as  NUMERIC(24, 10) ) AS CcZdTotal,
		SUM(X.Qty)-@numvalue AS SyZdQty,
		CAST((SUM(X.Qty)-@numvalue)*CAST(CASE WHEN SUM(Qty)=0 THEN 0 ELSE SUM(Total)/SUM(Qty) END as  NUMERIC(24, 10) ) as  NUMERIC(24, 10) ) AS SyZdTotal			
FROM	(
			SELECT	B.TypeId AS PTypeId,
					B.Qty,					
					B.Total,
					B.UpQty,
					B.DownQty,
					B.OrderQty,						
					B.CcQty,
					B.SyQty,
					B.SyOrderQty
			FROM	#QueryBjData B
)X GROUP BY X.PTypeId


--查询最终结果
SET @SQL = 'INSERT INTO #MxBillold(PTypeId,BTypeId,Qty,recPrice,prePrice1,unitid)
			SELECT	P.TypeId,
					 '''' AS BTypeId,'
			
IF @Flag = 2	--上限
	BEGIN
		IF @rType = 1
			SET @SQL = @SQL + '	ABS(R.CcQty) AS CcQty, '
		ELSE
			SET @SQL = @SQL + '	ABS(R.CcZdQty) AS CcZdQty, '
	END
ELSE			--下限
	BEGIN
		IF @rType = 3
			SET @SQL = @SQL + ' ABS(R.SyQty) AS SyQty, '
		ELSE IF @rType = 4
			SET @SQL = @SQL + ' ABS(R.SyOrderQty) AS SyOrderQty, '
		ELSE
			SET @SQL = @SQL + '	ABS(R.SyZdQty) AS SyZdQty, '
	END	
	
SET @SQL = @SQL + '	P.recPrice,
					P.prePrice1,
					p.baseUnitId				
			FROM	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') P,
					#Result R
			WHERE	P.TypeId = R.PTypeId
					AND ISNULL(P.UserCode,'''') LIKE ' + CHAR(39) + '%' + @UserCode + '%' + CHAR(39) + '
					AND ISNULL(P.FullName,'''') LIKE ' + CHAR(39) + '%' + @FullName + '%' + CHAR(39)

IF @Flag = 2	--上限
	BEGIN
		IF @rType = 1
			SET @SQL = @SQL + '	AND R.CcQty<>0 AND R.UpQty<>0 '
		ELSE
			SET @SQL = @SQL + '	AND R.CcZdQty<>0 '
	END
ELSE			--下限
	BEGIN
		IF @Flag=3 			
			SET @SQL =@SQL+CHAR(13)+'  AND P.StopBuy = 0'
		IF @rType = 3
			SET @SQL = @SQL + ' AND R.SyQty<>0 AND R.DownQty<>0 '
		ELSE IF @rType = 4
			SET @SQL = @SQL + ' AND R.SyOrderQty<>0 AND R.OrderQty<>0 '
		ELSE
			SET @SQL = @SQL + '	AND R.SyZdQty<>0 '
	END			
					
SET @SQL = @SQL + ' ORDER BY P.UserCode'					

--PRINT(@SQL)
EXEC(@SQL)
	

--如果是按照往来单位生成，则需要修改往来单位信息
IF @chk = 1
	BEGIN
		UPDATE	#MxBillold
		SET		BTypeId = ISNULL(Q.BTypeId,'')
		FROM	#MxBillold M
		LEFT JOIN (
			SELECT	PTypeId,
					ISNULL(BTypeId,'') AS BTypeId
			FROM 	QP_PType_Ext QP
					INNER JOIN btype b ON QP.BTypeID=b.typeId
			WHERE b.deleted=0			
		)Q ON Q.PTypeId = M.PTypeId
	END


--更改预设售价1
UPDATE	#MxBillold
SET		PrePrice1 = ISNULL(Q.PreSalePrice1,0)
FROM	#MxBillold M
LEFT JOIN (
	SELECT	PTypeId,
			ISNULL(PreSalePrice1,0) AS PreSalePrice1
	FROM 	PType_Price
)Q ON Q.PTypeId = M.PTypeId	

--开始生成草稿
DECLARE @costing int  --当前系统的成本算法
DECLARE @TmpBillCode	varchar(8000)

SET @TmpBillCode = ''

SELECT @costing=subvalue FROM sysdata WHERE subname='costing'

-- ********	判断是否试用版 - END	********
DECLARE @MONTH 				varchar(50),
		@DAY 				varchar(50),
		@BillCodeConfig		varchar(10),
		@BillCode			varchar(300),
		@Rex				int,
		@Tax				 NUMERIC(24, 10) ,
		@period				int,
		@DTypeId			varchar(200),
		@nBillId			numeric(18,0),
		@recPrice			 NUMERIC(24, 10) ,
		@preprice			 NUMERIC(24, 10) ,
		@Explain			varchar(400),
		@TotalQty			 NUMERIC(24, 10) ,
		@TotalMoney			 NUMERIC(24, 10) ,
		@bCount				int,
		@BillCount			int,
		@i					int,
		@bCodeList			varchar(8000),
		@VchType			int,
		@VchHead			varchar(20),
		@Discount			 NUMERIC(24, 10) ,
		@GridType			int,
		@cid               int,
		@atypeid1           varchar(200),
		@stypeid            varchar(200),
		@dfullname			varchar(200),
		@cefullname			varchar(200)=''
		

set @cid=(SELECT cid FROM dbo.Ac_Currency WHERE Sysrow=1 AND Deleted=0)
SET @Tax = 0
SET @Discount = 0
SET @recPrice = 0
SET @preprice = 0
--IF @ETypeId = ''	--如果客户没有选择职业，则使用当前操作员做经手人,并且使用当前操作员所在部门作为部门名称
--	SET @ETypeId = @OperatorID
	
SET @i = 1
SET @bCodeList = ''
SET @DTypeId = ''

IF @KTypeId = '' OR LEN(REPLACE(@KTypeId,',',''))<>LEN(@KTypeId)
	SET @KTypeId = '00000'

SET @Explain = '库存报警生成的草稿'

IF @bFlag = 1
	BEGIN
		SET @VchType = 11
		SET @VchHead = 'XK'
	END
ELSE IF @bFlag = 2
	BEGIN
		SET @VchType = 6
		SET @VchHead = 'JT'
	END
ELSE IF @bFlag = 3
	BEGIN
		SET @VchType = 9
		SET @VchHead = 'BS'
	END
ELSE IF @bFlag = 4
	BEGIN
		SET @VchType = 300
		SET @VchHead = 'XD'
	END
ELSE IF @bFlag = 5
	BEGIN
		SET @VchType = 34
		SET @VchHead = 'JK'
	END
ELSE IF @bFlag = 6
	BEGIN
		SET @VchType = 45	
		SET @VchHead = 'XT'
	END
ELSE IF @bFlag = 7
	BEGIN
		SET @VchType = 14
		SET @VchHead = 'BY'
	END
ELSE IF @bFlag = 8
	BEGIN
		SET @VchType = 301
		SET @VchHead = 'JD'
	END
ELSE IF @bFlag = 9
	BEGIN
		SET @VchType = 402
		SET @VchHead = 'FC'
	END
ELSE IF @bFlag = 10
	BEGIN
		SET @VchType = 400
		SET @VchHead = 'GR'
	END
ELSE IF @bFlag = 11
	BEGIN
		SET @VchType = 17
		SET @VchHead = 'TD'
	END
ELSE IF @bFlag = 12
	BEGIN
		SET @VchType = 21
		SET @VchHead = 'BD'
	END	
ELSE IF @bFlag =13
	BEGIN
		SET @VchType = 187
		SET @VchHead = 'SCD'
	END	
CREATE TABLE #temtable(atypeid1 VARCHAR(200),atypeid1name VARCHAR(200),flag VARCHAR(50))



SET  @stypeid=(SELECT STypeID FROM dbo.Stock WHERE typeId=@KTypeId)
INSERT INTO #temtable(atypeid1,atypeid1name,flag)  EXEC dbo.Web_GetAtype 
    @billtypeid=@VchType, 
    @stypeid=@stypeid,
    @OperatorId=@OperatorId

set @atypeid1=(SELECT atypeid1 from #temtable)

SELECT @GridType = Value FROM userconfig WHERE configname = 'Gridtype'

IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '1')
	BEGIN
		SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'
		SET @Discount = 1
	END
ELSE IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '2')
	BEGIN
		SELECT @Discount=Value from userconfig where configname = 'ZekouValue'
		SET @Tax = 0
	END
ELSE IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '3')
	BEGIN
		SET @Tax = 0
		SET @Discount = 1
	END
ELSE 
	BEGIN
		SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'
		SELECT @Discount=Value from userconfig where configname = 'ZekouValue'
	END

SELECT @DTypeId = D.TypeId FROM Department D,Employee E WHERE E.DtypeID = D.typeid AND E.TypeId = @ETypeId

SELECT TOP 1  @period = period FROM MonthProc WHERE MonthNo = '本期'

SET @month = MONTH(GetDate())
SET @day = DAY(GetDate())

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

DECLARE @BeginDate 	datetime,
		@szItem 	varchar(30),
		@szVchCode 	varchar(30),
		@szPeriod	varchar(20),
		@MxBTypeId	VARCHAR(100)

EXEC Gp_GetSubValue 'period',@stid,@szPeriod out

SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod 
IF GetDate()<@BeginDate 
	BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
		RETURN -33
	END
	
DECLARE
	@datBillDate	DATETIME
	
SELECT
	@datBillDate=CONVERT(varchar(10),GetDate(),120)		

--按照往来单位为标准生成单据
DECLARE BilCursor CURSOR FOR 
	SELECT DISTINCT BTypeId FROM #MxBillold ORDER BY BTypeId

OPEN BilCursor

FETCH NEXT FROM BilCursor INTO @MxBTypeId
WHILE @@FETCH_STATUS = 0
	BEGIN	
		SELECT IDENTITY(INT,1,1) nid,PTypeId,BTypeId,Qty,recPrice,prePrice1,unitid INTO #MxBill FROM #MxBillold WHERE BTypeId=@MxBTypeId

		SELECT @bCount = COUNT(*) FROM #MxBill
				
		DECLARE @dealbtypeid VARCHAR(200)
		SET @dealbtypeid=(SELECT denominatedid FROM dbo.btype WHERE  typeId=@MxBTypeId)
		
		CREATE TABLE #MxBilloneBtype
		(
			nid			int identity(1,1),
			PTypeId		varchar(200),
			BTypeId		VARCHAR(200),
			Qty			 NUMERIC(24, 10) ,
			recPrice	 NUMERIC(24, 10) ,
			prePrice1	 NUMERIC(24, 10) ,
			unitid		int
		)
		INSERT INTO #MxBilloneBtype (PTypeId,BTypeId,Qty,recPrice,prePrice1,unitid)
		SELECT	PTypeId,BTypeId,Qty,m.recPrice,m.prePrice1,p.baseUnitId  
		FROM	#MxBill m 
		LEFT JOIN ptype p ON m.PTypeId=p.typeId 
		WHERE	BTypeId = @MxBTypeId
				
		IF @bCount % 150 = 0
			SET @BillCount = @bCount / 150
		ELSE
			SET @BillCount = @bCount / 150 + 1
		
		SET @i =  1	
		
		WHILE @i<=@BillCount
			BEGIN
			IF  EXISTS( SELECT 1 FROM #MxBill a WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId)
			BEGIN
				--生成单据编号
				IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @VchType) AND @BillCodeConfig = '1'
					BEGIN
						SELECT @MONTH = typeid FROM Employee WHERE TypeID = @ETypeId
						SELECT @DAY = FullName FROM Stock WHERE TypeID = @ktypeid1
						SELECT @dfullname=FullName FROM dbo.Department WHERE typeid=( select DtypeID from dbo.employee WHERE typeId=@ETypeId)
						SELECT @cefullname=TypeId FROM dbo.employee WHERE typeid=@OperatorId
					END
		
				EXEC @Re=Gp_GetBillCode @VchType, @MONTH,@DAY,@VchHead,@NowDate,@stid,@BillCode OUTPUT,@dfullname,@cefullname,-999
				
				IF @Re <> 0
				BEGIN
					CLOSE BilCursor
					DEALLOCATE BilCursor
					RETURN -2	
				END
				
				IF @VchType IN (300,301)
					INSERT INTO OrderIndex (BillDate,BillCode,BillType,btypeid,etypeid,ktypeid,checke,totalmoney,Ntotalmoney,totalqty,tax,period,RedWord,waybillcode,packway,TEL,IfAudit,DTypeId,Explain,OrderState,etypeid2,waymode,goodsnumber,STypeID,CID,Rate,DealBTypeID)
					VALUES(@datBillDate,@BillCode,@VchType,ISNULL(@dealbtypeid,''),ISNULL(@ETypeId,''),@ktypeid1,@OperatorId,0,0,0,@Tax,@period,0,'','','','1',ISNULL(@DTypeId,''),@Explain,0,'','','',@stid,@cid,1,ISNULL(@MxBTypeId,''))
				ELSE IF @VchType IN (17,21,187)
				  INSERT INTO BillIndex (CheckTime,AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,NTotalMoney,totalinmoney,NTotalInMoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,Stypeid,CID,Rate,ATypeID1,DealBTypeID)
					VALUES(GETDATE(),9999,@datBillDate,@BillCode,@VchType,'','',ISNULL(@dealbtypeid,''),ISNULL(@ETypeId,''),'',@ktypeid1,'f',@OperatorId,0,0,0,0,0,@Tax,@period,0,1,0,'','','','3',0,ISNULL(@DTypeId,''),@Explain,@stid,@cid,1,@atypeid1,ISNULL(@MxBTypeId,''))
				ELSE
					INSERT INTO BillIndex (CheckTime,AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,NTotalMoney,totalinmoney,NTotalInMoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,Stypeid,CID,Rate,ATypeID1,DealBTypeID)
					VALUES(GETDATE(),9999,@datBillDate,@BillCode,@VchType,'','',ISNULL(@dealbtypeid,''),ISNULL(@ETypeId,''),@ktypeid1,'','f',@OperatorId,0,0,0,0,0,@Tax,@period,0,1,0,'','','','3',0,ISNULL(@DTypeId,''),@Explain,@stid,@cid,1,@atypeid1,ISNULL(@MxBTypeId,''))
				
				IF @@ROWCOUNT = 0  OR @@ERROR<>0
				BEGIN
					CLOSE BilCursor
					DEALLOCATE BilCursor
					RETURN -3
				END
				ELSE
					SET @nBillId = @@identity
					
				--插入明细表				
				IF @VchType = 11
					BEGIN
                        INSERT  INTO SaleBill
                                (BillNumberId,
                                 PTypeId,
                                 Qty,
                                 nqty,
                                 MQty,
                                 SalePrice,
                                 NSalePrice,
                                 MSalePrice,
                                 CurMSalePrice,
                                 Total,
                                 NTotal,
                                 Discount,
                                 DiscountPrice,
                                 NDiscountPrice,
                                 MDiscountPrice,
                                 CurMDiscountPrice,
                                 TaxPrice,
                                 NTaxPrice,
                                 MTaxPrice,
                                 CurMTaxPrice,
                                 TaxTotal,
                                 NTaxTotal,
                                 SaleTotal,
                                 NSaleTotal,
                                 tax,
                                 ktypeid,
                                 STypeID,
                                 UnitID,
                                 NUnitID,
                                 UnitRate,
                                 MUnitID,
                                 MUnitRate,
                                 CargoID,TaxMoney,NTaxMoney,IsCombined,ItemID)
                                SELECT
                                    @nBillId,
                                    PTypeId,
                                    Qty,
                                    CASE WHEN b.rate=0 THEN 0
                                         ELSE qty/b.rate
                                    END,
                                    qty/b.CRate,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    @Discount,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    @Tax,
                                    @ktypeid1,
                                    @stid,
                                    unitid,
                                    b.aunitid,
                                    b.rate,
                                    b.CUnitId,
                                    b.CRate,
                                    @cargoid,0,0,0,0
                                FROM #MxBill a
                                INNER JOIN #GetManPTypeId1 b ON a.ptypeid=b.typeid
                                WHERE
                                    nid>(@i-1)*150 AND
                                    nid<=@i*150 AND
                                    BTypeId=@MxBTypeId
		
						--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(TaxTotal) FROM SaleBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney WHERE BillNumberId = @nBillId

                        UPDATE SaleBill SET ShowOrder=ID,CargoID=ISNULL(b.CargoID,'') FROM SaleBill a LEFT JOIN  dbo.CargoType b ON  a.KTypeId = b.KTypeId AND b.IsDefault=1
                        WHERE a.BillNumberId=@nBillId 
						
					END
				ELSE IF @VchType = 6
					BEGIN
						IF @GridType = 1 --采购/销售单采用税率格式
                                INSERT  INTO BuyBackBill
                                        (BillNumberId,
                                         PTypeId,
                                         Qty,
                                         nqty,
                                         MQty,
                                         SalePrice,
                                         NSalePrice,
                                         MSalePrice,
                                         CurMSalePrice,
                                         Total,
                                         NTotal,
                                         Discount,
                                         DiscountPrice,
                                         NDiscountPrice,
                                         MDiscountPrice,
                                         CurMDiscountPrice,
                                         TaxPrice,
                                         NTaxPrice,
                                         MTaxPrice,
                                         CurMTaxPrice,
                                         TaxTotal,
                                         NTaxTotal,
                                         SaleTotal,
                                         NSaleTotal,
                                         tax,
                                         ktypeid,
                                         STypeID,
                                         UnitID,
                                         NUnitID,
                                         UnitRate,
                                         MUnitID,
                                         MUnitRate,
                                         CargoID,TaxMoney,NTaxMoney,IsCombined,ItemID)
                                        SELECT
                                            @nBillId,
                                            PTypeId,
                                            Qty,
                                            CASE WHEN b.rate=0 THEN 0
                                                 ELSE qty/b.rate
                                            END,
                                            qty/b.CRate,
                                            recPrice,
                                            recPrice,
                                            recPrice,
                                            recPrice,
                                            CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                            CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                            1,
                                            recPrice,
                                            recPrice,
                                            recPrice,
                                            recPrice,
                                            CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                            CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                            CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                            CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                            CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                            CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                            CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                            CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                            @Tax,
                                            @ktypeid1,
                                            @stid,
                                            unitid,
                                            b.aunitid,
                                            b.rate,
                                            b.CUnitId,
                                            b.CRate,
                                            @cargoid, 
                                            CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                            CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ) ,0,0                
								FROM #MxBill a 
								INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId
						ELSE IF @GridType = 2 --采购/销售单采用折扣格式(recPrice=最近进价
                            INSERT  INTO BuyBackBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     mqty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,TaxMoney,NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) )  ,0,0                    
							FROM #MxBill a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE IF @GridType = 3	--采购/销售单采用普通格式
                            INSERT  INTO BuyBackBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     mqty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        1,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                         CAST(recPrice*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) )	,
                                         CAST(recPrice*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ) ,0,0
							FROM #MxBill a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE --全格式
                            INSERT  INTO BuyBackBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     mqty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                          CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-	CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-	CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ) ,0,0                 
							FROM #MxBill a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
		
						--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(TaxTotal) FROM BuyBackBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney,NTotalMoney=@TotalMoney WHERE BillNumberId = @nBillId
                        
                        UPDATE BuyBackBill SET ShowOrder=ID,CargoID=ISNULL(b.CargoID,'') FROM BuyBackBill a LEFT JOIN  dbo.CargoType b ON  a.KTypeId = b.KTypeId AND IsDefault=1  WHERE a.BillNumberId=@nBillId 
                        /*UPDATE 	BuyBackBill 
						SET 	CargoSpace=(
												SELECT 	ISNULL(b.FullName,'') 
												FROM 	BuyBackBill a LEFT JOIN  CargoSpace b ON a.PTypeID=b.PTypeID AND a.KTypeId = b.KTypeId 
												WHERE	a.BillNumberId=@nBillId
											)*/
					END
				ELSE IF @VchType = 9
					BEGIN
						INSERT INTO LoseBill(BillNumberId,PTypeId,Qty,nqty,MQty,STypeID,UnitID,NUnitID,UnitRate,MUnitID,MUnitRate,CargoID,IsCombined,ItemID,KTypeId)
						SELECT @nBillId,PTypeId,Qty,CASE WHEN b.rate=0 THEN 0 ELSE qty/b.rate END ,qty/b.CRate,@stid,unitid,b.aunitid,b.rate,b.CUnitId,b.CRate,@cargoid,0,0,@ktypeid1 FROM #MxBill a INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId
						
						--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty) FROM LoseBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty WHERE BillNumberId = @nBillId
---
                        UPDATE LoseBill SET ShowOrder=A.ID,CargoID=ISNULL(b.CargoID,'') FROM LoseBill a INNER JOIN dbo.BillIndex c ON a.BillNumberId=c.BillNumberId LEFT JOIN  dbo.CargoType b ON c.ktypeid=b.KtypeID AND IsDefault=1
                        WHERE c.KTypeID=@KTypeID  AND  a.BillNumberId=@nBillId
---                 
					END
				ELSE IF @VchType = 34
					BEGIN
						IF @GridType = 1
                            INSERT  INTO BuyBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        1,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),	
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),0,0                     	
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE IF @GridType = 2
                            INSERT  INTO BuyBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     Stypeid,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                         CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-cAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-cAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) )   ,0,0                   	
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE IF @GridType = 3
                            INSERT  INTO BuyBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     Stypeid,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        1,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),0,0
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE --全格式
                            INSERT  INTO BuyBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     mqty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     Stypeid,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                         CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),                      
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-	CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-	CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ) ,0,0                     
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
		
						--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(TaxTotal) FROM BuyBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney ,NTotalMoney=@TotalMoney WHERE BillNumberId = @nBillId

                        UPDATE BuyBill SET ShowOrder=ID,CargoID=ISNULL(b.CargoID,'') FROM BuyBill a LEFT JOIN  dbo.CargoType b ON  a.KTypeId = b.KTypeId  AND IsDefault=1
                        WHERE a.BillNumberId=@nBillId 
					END
				ELSE IF @VchType = 45
					BEGIN
						IF @GridType = 1
                            INSERT  INTO SaleBackBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     KTypeID,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,TaxMoney,NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        qty/b.CRate,
                                        prePrice1,
                                        prePrice1,
                                        prePrice1*b.CRate,
                                        prePrice1*b.CRate,
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        1,
                                        prePrice1,
                                        prePrice1,
                                        prePrice1*b.CRate,
                                        prePrice1*b.CRate,
                                        CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                        CAST(CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(prePrice1*Qty AS  NUMERIC(24, 10) )  ,0,0                    
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE IF @GridType = 2
                            INSERT  INTO SaleBackBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     NQty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     KTypeID,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        qty/b.CRate,
                                        prePrice1,
                                        prePrice1,
                                        prePrice1*b.CRate,
                                        prePrice1*b.CRate,
                                        CAST(prePrice1*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(prePrice1*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(CAST(prePrice1*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(prePrice1*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                        CAST(CAST(prePrice1*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(prePrice1*Qty*@Discount AS  NUMERIC(24, 10) ),
                                         CAST(CAST(prePrice1*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(prePrice1*Qty*@Discount AS  NUMERIC(24, 10) )   ,0,0                  
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE IF @GridType = 3
                            INSERT  INTO SaleBackBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     KTypeID,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        qty/b.CRate,
                                        prePrice1,
                                        prePrice1,
                                        prePrice1*b.CRate,
                                        prePrice1*b.CRate,
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        1,
                                        prePrice1,
                                        prePrice1,
                                        prePrice1*b.CRate,
                                        prePrice1*b.CRate,
                                        prePrice1,
                                        prePrice1,
                                        prePrice1*b.CRate,
                                        prePrice1*b.CRate,
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                         CAST(prePrice1*Qty AS  NUMERIC(24, 10) )-CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) )-CAST(prePrice1*Qty AS  NUMERIC(24, 10) ) ,0,0
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId
						ELSE --全格式
                            INSERT  INTO SaleBackBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     NQty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     KTypeID,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        qty/b.CRate,
                                        prePrice1,
                                        prePrice1,
                                        prePrice1*b.CRate,
                                        prePrice1*b.CRate,
                                        CAST(prePrice1*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(prePrice1*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*b.CRate*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        CAST(prePrice1*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                        CAST(CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(prePrice1*@Discount*Qty AS  NUMERIC(24, 10) ),
                                         CAST(CAST(prePrice1*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(prePrice1*@Discount*Qty AS  NUMERIC(24, 10) ),0,0                      
							FROM #MxBill a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
		
						--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(TaxTotal) FROM SaleBackBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney,NTotalMoney=@TotalMoney WHERE BillNumberId = @nBillId

                        UPDATE SaleBackBill SET ShowOrder=ID,CargoID=ISNULL(b.CargoID,'') FROM SaleBackBill a LEFT JOIN  dbo.CargoType b ON a.KTypeId = b.KTypeId AND IsDefault=1 WHERE a.BillNumberId=@nBillId 
                       
					END
				ELSE IF @VchType = 14
					BEGIN
						INSERT INTO OverFlowBill(BillNumberId,PTypeId,Qty,NQty,MQty,STypeID,UnitID,NUnitID,UnitRate,MUnitID,MUnitRate,CargoID,IsCombined,ItemID,KTypeId)
						SELECT @nBillId,PTypeId,Qty,CASE WHEN b.rate=0 THEN 0 ELSE qty/b.rate END,qty/b.CRate, @stid,unitid,b.aunitid,b.rate,b.CUnitId,b.CRate,@cargoid,0,0,@ktypeid1 FROM #MxBill  a INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId
						--修改BillIndex的TotalMoney
		
						SELECT @TotalQty = SUM(Qty) FROM OverFlowBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty WHERE BillNumberId = @nBillId
   
                        UPDATE OverFlowBill SET ShowOrder=A.ID,CargoID=ISNULL(b.CargoID,'') FROM OverFlowBill a INNER JOIN dbo.BillIndex c ON a.BillNumberId = c.BillNumberId LEFT JOIN  dbo.CargoType b ON c.ktypeid=b.KtypeID AND IsDefault=1
                        WHERE b.KTypeID=@KTypeID AND a.BillNumberId = @nBillId
					END
				ELSE IF @VchType IN (300,301)
					BEGIN						
						IF @VchType = 301
							BEGIN								
								IF @GridType = 1
								BEGIN								
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             NQty,
                                             MQty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeID,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             UnitRate,
                                             MUnitID,
                                             MUnitRate,
                                             CargoID,
                                             TaxMoney,
                                             NTaxMoney,IsCombined,ItemID)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                Qty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE qty/b.rate
                                                END,
                                                Qty/b.CRate,
                                                recPrice,
                                                recPrice,
                                                recPrice,
                                                recPrice,
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                1,
                                                recPrice,
                                                recPrice,
                                                recPrice,
                                                recPrice,
                                                CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(CAST(recPrice*(1+@Tax/
                                                          100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                CAST(CAST(recPrice*(1+@Tax/
                                                          100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                @Tax,
                                                @ktypeid1,
                                                @stid,
                                                unitid,
                                                b.aunitid,
                                                b.rate,
                                                b.CUnitId,
                                                b.CRate,
                                                @cargoid,
                                                 CAST(CAST(recPrice*(1+@Tax/
                                                          100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-	 CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                 CAST(CAST(recPrice*(1+@Tax/
                                                          100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-	 CAST(recPrice*Qty AS  NUMERIC(24, 10) ),0,0	         				
										FROM #MxBill a 
										INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   
										WHERE	BTypeId = @MxBTypeId	
												AND nid > (@i-1)*150 
												AND nid <=@i*150
                                    END
									ELSE IF @GridType = 2
									BEGIN
                                        INSERT  INTO OrderBill
                                                (BillNumberId,
                                                 PTypeId,
                                                 Qty,
                                                 nqty,
                                                 MQty,
                                                 Price,
                                                 NSalePrice,
                                                 MSalePrice,
                                                 CurMSalePrice,
                                                 Total,
                                                 NTotal,
                                                 Discount,
                                                 DiscountPrice,
                                                 NDiscountPrice,
                                                 MDiscountPrice,
                                                 CurMDiscountPrice,
                                                 TaxPrice,
                                                 NTaxPrice,
                                                 MTaxPrice,
                                                 CurMTaxPrice,
                                                 TaxTotal,
                                                 NTaxTotal,
                                                 SaleTotal,
                                                 NSaleTotal,
                                                 tax,
                                                 KTypeID,
                                                 STypeID,
                                                 UnitID,
                                                 NUnitID,
                                                 UnitRate,
                                                 MUnitID,
                                                 MUnitRate,
                                                 CargoID,
                                                 TaxMoney,
                                                 NTaxMoney,IsCombined,ItemID)
                                                SELECT
                                                    @nBillId,
                                                    PTypeId,
                                                    Qty,
                                                    CASE WHEN b.rate=0 THEN 0
                                                         ELSE qty/b.rate
                                                    END,
                                                    qty/b.CRate,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    @Discount,
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(recPrice*
                                                    @Discount AS  NUMERIC(24, 10) )*
                                                    Qty AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(recPrice*
                                                    @Discount AS  NUMERIC(24, 10) )*
                                                    Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    @Tax,
                                                    @ktypeid1,
                                                    @stid,
                                                    unitid,
                                                    b.aunitid,
                                                    b.rate,
                                                    b.CUnitId,
                                                    b.CRate,
                                                    @cargoid,
                                                    CAST(CAST(recPrice*
                                                    @Discount AS  NUMERIC(24, 10) )*
                                                    Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                     CAST(CAST(recPrice*
                                                    @Discount AS  NUMERIC(24, 10) )*
                                                    Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) )   ,0,0       	
										FROM #MxBill a 
										INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   
										WHERE	nid > (@i-1)*150 
												AND nid <=@i*150 
												AND BTypeId = @MxBTypeId	
									END																
									ELSE  IF @GridType = 3
                                        BEGIN
										INSERT  INTO OrderBill
                                                (BillNumberId,
                                                 PTypeId,
                                                 Qty,
                                                 nqty,
                                                 MQty,
                                                 Price,
                                                 NSalePrice,
                                                 MSalePrice,
                                                 CurMSalePrice,
                                                 Total,
                                                 NTotal,
                                                 Discount,
                                                 DiscountPrice,
                                                 NDiscountPrice,
                                                 MDiscountPrice,
                                                 CurMDiscountPrice,
                                                 TaxPrice,
                                                 NTaxPrice,
                                                 MTaxPrice,
                                                 CurMTaxPrice,
                                                 TaxTotal,
                                                 NTaxTotal,
                                                 SaleTotal,
                                                 NSaleTotal,
                                                 tax,
                                                 KTypeID,
                                                 STypeID,
                                                 UnitID,
                                                 NUnitID,
                                                 UnitRate,
                                                 MUnitID,
                                                 MUnitRate,
                                                 CargoID,
                                                 TaxMoney,
                                                 NTaxMoney,IsCombined,ItemID)
                                                SELECT
                                                    @nBillId,
                                                    PTypeId,
                                                    Qty,
                                                    CASE WHEN b.rate=0 THEN 0
                                                         ELSE qty/b.rate
                                                    END,
                                                    Qty/b.CRate,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    1,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    @Tax,
                                                    @ktypeid1,
                                                    @stid,
                                                    unitid,
                                                    b.aunitid,
                                                    b.rate,
                                                    b.CUnitId,
                                                    b.CRate,
                                                    @cargoid,
                                                     CAST(recPrice*Qty AS  NUMERIC(24, 10) )-	CAST(recPrice*Qty AS  NUMERIC(24, 10) ), 
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) )-	CAST(recPrice*Qty AS  NUMERIC(24, 10) )  ,0,0        
											FROM #MxBill a 
											INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   
											WHERE	BTypeId = @MxBTypeId	 
													AND nid > (@i-1)*150 
													AND nid <=@i*150 									
										END
									ELSE --全格式
                                        INSERT  INTO OrderBill
                                                (BillNumberId,
                                                 PTypeId,
                                                 Qty,
                                                 NQty,
                                                 MQty,
                                                 Price,
                                                 NSalePrice,
                                                 MSalePrice,
                                                 CurMSalePrice,
                                                 Total,
                                                 NTotal,
                                                 Discount,
                                                 DiscountPrice,
                                                 NDiscountPrice,
                                                 MDiscountPrice,
                                                 CurMDiscountPrice,
                                                 TaxPrice,
                                                 NTaxPrice,
                                                 MTaxPrice,
                                                 CurMTaxPrice,
                                                 TaxTotal,
                                                 NTaxTotal,
                                                 SaleTotal,
                                                 NSaleTotal,
                                                 tax,
                                                 KTypeID,
                                                 STypeID,
                                                 UnitID,
                                                 NUnitID,
                                                 UnitRate,
                                                 MUnitID,
                                                 MUnitRate,
                                                 CargoID,
                                                 TaxMoney,NTaxMoney,IsCombined,ItemID)
                                                SELECT
                                                    @nBillId,
                                                    PTypeId,
                                                    Qty,
                                                    CASE WHEN b.rate=0 THEN 0
                                                         ELSE qty/b.rate
                                                    END,
                                                    Qty/b.CRate,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    recPrice,
                                                    CAST(recPrice*@Discount*
                                                    Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount*
                                                    Qty AS  NUMERIC(24, 10) ),
                                                    @Discount,
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                     CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(recPrice*(1+@Tax/
                                                              100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(recPrice*(1+@Tax/
                                                              100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                    @Tax,
                                                    @ktypeid1,
                                                    @stid,
                                                    unitid,
                                                    b.aunitid,
                                                    b.rate,
                                                    b.CUnitId,
                                                    b.CRate,
                                                    @cargoid, CAST(CAST(recPrice*(1+@Tax/
                                                              100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*@Discount*
                                                    Qty AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(recPrice*(1+@Tax/
                                                              100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*@Discount*
                                                    Qty AS  NUMERIC(24, 10) ),0,0
										FROM #MxBill a 
										INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   
										WHERE	nid > (@i-1)*150 
												AND nid <=@i*150 
												AND BTypeId = @MxBTypeId	
							END
						ELSE
							BEGIN
								IF @GridType = 1
                                        INSERT  INTO OrderBill
                                                (BillNumberId,
                                                 PTypeId,
                                                 Qty,
                                                 NQty,
                                                 MQty,
                                                 Price,
                                                 NSalePrice,
                                                 MSalePrice,
                                                 CurMSalePrice,
                                                 Total,
                                                 NTotal,
                                                 Discount,
                                                 DiscountPrice,
                                                 NDiscountPrice,
                                                 MDiscountPrice,
                                                 CurMDiscountPrice,
                                                 TaxPrice,
                                                 NTaxPrice,
                                                 MTaxPrice,
                                                 CurMTaxPrice,
                                                 TaxTotal,
                                                 NTaxTotal,
                                                 SaleTotal,
                                                 NSaleTotal,
                                                 tax,
                                                 KTypeID,
                                                 STypeID,
                                                 UnitID,
                                                 NUnitID,
                                                 UnitRate,
                                                 MUnitID,
                                                 MUnitRate,
                                                 CargoID,
                                                 TaxMoney,
                                                 NTaxMoney,IsCombined,ItemID)
                                                SELECT
                                                    @nBillId,
                                                    PTypeId,
                                                    Qty,
                                                    CASE WHEN b.rate=0 THEN 0
                                                         ELSE qty/b.rate
                                                    END,
                                                    Qty/b.CRate,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    1,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                    CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                    CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                    CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                    0,
                                                    0,
                                                    @Tax,
                                                    @ktypeid1,
                                                    @stid,
                                                    unitid,
                                                    b.aunitid,
                                                    b.rate,
                                                    b.CUnitId,
                                                    b.CRate,
                                                    @cargoid,
                                                    CAST(CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                      CAST(CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(0*Qty AS  NUMERIC(24, 10) ) ,0,0        	
										FROM #MxBill a 
										INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
									ELSE IF @GridType = 2
                                        INSERT  INTO OrderBill
                                                (BillNumberId,
                                                 PTypeId,
                                                 Qty,
                                                 NQty,
                                                 MQty,
                                                 Price,
                                                 NSalePrice,
                                                 MSalePrice,
                                                 CurMSalePrice,
                                                 Total,
                                                 NTotal,
                                                 Discount,
                                                 DiscountPrice,
                                                 NDiscountPrice,
                                                 MDiscountPrice,
                                                 CurMDiscountPrice,
                                                 TaxPrice,
                                                 NTaxPrice,
                                                 MTaxPrice,
                                                 CurMTaxPrice,
                                                 TaxTotal,
                                                 NTaxTotal,
                                                 SaleTotal,
                                                 NSaleTotal,
                                                 tax,
                                                 KTypeID,
                                                 STypeID,
                                                 UnitID,
                                                 NUnitID,
                                                 UnitRate,
                                                 MUnitID,
                                                 MUnitRate,
                                                 CargoID,TaxMoney,
                                                 NTaxMoney,IsCombined,ItemID)
                                                SELECT
                                                    @nBillId,
                                                    PTypeId,
                                                    Qty,
                                                    CASE WHEN b.rate=0 THEN 0
                                                         ELSE qty/b.rate
                                                    END,
                                                    Qty/b.CRate,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    @Discount,
                                                    CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(0*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(CAST(0*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                    0,
                                                    0,
                                                    @Tax,
                                                    @ktypeid1,
                                                    @stid,
                                                    unitid,
                                                    b.aunitid,
                                                    b.rate,
                                                    b.CUnitId,
                                                    b.CRate,
                                                    @cargoid,
                                                     CAST(CAST(0*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(0*Qty AS  NUMERIC(24, 10) ),	
                                                    CAST(CAST(0*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(0*Qty AS  NUMERIC(24, 10) ) ,0,0         
										FROM #MxBill a 
										INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
									ELSE IF @GridType = 3
                                        INSERT  INTO OrderBill
                                                (BillNumberId,
                                                 PTypeId,
                                                 Qty,
                                                 nqty,
                                                 MQty,
                                                 Price,
                                                 NSalePrice,
                                                 MSalePrice,
                                                 CurMSalePrice,
                                                 Total,
                                                 NTotal,
                                                 Discount,
                                                 DiscountPrice,
                                                 NDiscountPrice,
                                                 MDiscountPrice,
                                                 CurMDiscountPrice,
                                                 TaxPrice,
                                                 NTaxPrice,
                                                 MTaxPrice,
                                                 CurMTaxPrice,
                                                 TaxTotal,
                                                 NTaxTotal,
                                                 SaleTotal,
                                                 NSaleTotal,
                                                 tax,
                                                 KTypeID,
                                                 STypeID,
                                                 UnitID,
                                                 NUnitID,
                                                 UnitRate,
                                                 MUnitID,
                                                 MUnitRate,
                                                 CargoID,
                                                 TaxMoney,
                                                 NTaxMoney,IsCombined,ItemID)
                                                SELECT
                                                    @nBillId,
                                                    PTypeId,
                                                    Qty,
                                                    CASE WHEN b.rate=0 THEN 0
                                                         ELSE qty/b.rate
                                                    END,
                                                    Qty/b.CRate,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    1,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    @Tax,
                                                    @ktypeid1,
                                                    @stid,
                                                    unitid,
                                                    b.aunitid,
                                                    b.rate,
                                                    b.CUnitId,
                                                    b.CRate,
                                                    @cargoid,CAST(0*Qty AS  NUMERIC(24, 10) )- CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) )- CAST(0*Qty AS  NUMERIC(24, 10) ),0,0
										FROM #MxBill a 
										INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
									ELSE
                                        INSERT  INTO OrderBill
                                                (BillNumberId,
                                                 PTypeId,
                                                 Qty,
                                                 NQty,
                                                 MQty,
                                                 Price,
                                                 NSalePrice,
                                                 MSalePrice,
                                                 CurMSalePrice,
                                                 Total,
                                                 NTotal,
                                                 Discount,
                                                 DiscountPrice,
                                                 NDiscountPrice,
                                                 MDiscountPrice,
                                                 CurMDiscountPrice,
                                                 TaxPrice,
                                                 NTaxPrice,
                                                 MTaxPrice,
                                                 CurMTaxPrice,
                                                 TaxTotal,
                                                 NTaxTotal,
                                                 SaleTotal,
                                                 NSaleTotal,
                                                 tax,
                                                 KTypeID,
                                                 STypeID,
                                                 UnitID,
                                                 NUnitID,
                                                 UnitRate,
                                                 MUnitID,
                                                 MUnitRate,
                                                 CargoID,
                                                 TaxMoney,
                                                 NTaxMoney,IsCombined,ItemID)
                                                SELECT
                                                    @nBillId,
                                                    PTypeId,
                                                    Qty,
                                                    CASE WHEN b.rate=0 THEN 0
                                                         ELSE qty/b.rate
                                                    END,
                                                    Qty/b.CRate,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    @Discount,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    0,
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                    @Tax,
                                                    @ktypeid1,
                                                    @stid,
                                                    unitid,
                                                    b.aunitid,
                                                    b.rate,
                                                    b.CUnitId,
                                                    b.CRate,
                                                    @cargoid,
                                                     CAST(0*Qty AS  NUMERIC(24, 10) )-	 CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                     CAST(0*Qty AS  NUMERIC(24, 10) )-	 CAST(0*Qty AS  NUMERIC(24, 10) ),0,0
										FROM #MxBill a 
										INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid   WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
							END
						
						UPDATE dbo.OrderBill SET ShowOrder=ID WHERE billNumberID=@nBillId
						--修改OrderIndex的TotalMoney，TotalQty
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(TaxTotal) FROM OrderBill WHERE BillNumberId = @nBillId
						UPDATE OrderIndex SET TotalQty = ISNULL(@TotalQty,0),TotalMoney = ISNULL(@TotalMoney,0) WHERE BillNumberId = @nBillId
					END
				ELSE IF @VchType = 402
				BEGIN
                        INSERT  INTO SendBill
                                (BillNumberId,
                                 PTypeId,
                                 Qty,
                                 nqty,
                                 MQty,
                                 SalePrice,
                                 NSalePrice,
                                 MSalePrice,
                                 CurMSalePrice,
                                 Total,
                                 NTotal,
                                 Discount,
                                 DiscountPrice,
                                 NDiscountPrice,
                                 MDiscountPrice,
                                 CurMDiscountPrice,
                                 TaxPrice,
                                 NTaxPrice,
                                 MTaxPrice,
                                 CurMTaxPrice,
                                 TaxTotal,
                                 NTaxTotal,
                                 SaleTotal,
                                 NSaleTotal,
                                 tax,
                                 ktypeid,
                                 STypeID,
                                 UnitID,
                                 NUnitID,
                                 UnitRate,
                                 MUnitID,
                                 MUnitRate,
                                 CargoID,TaxMoney,NTaxMoney,IsCombined,ItemID)
                                SELECT
                                    @nBillId,
                                    PTypeId,
                                    Qty,
                                    CASE WHEN b.rate=0 THEN 0
                                         ELSE qty/b.rate
                                    END,
                                    qty/b.CRate,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    @Discount,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    0,
                                    @Tax,
                                    @ktypeid1,
                                    @stid,
                                    unitid,
                                    b.aunitid,
                                    b.rate,
                                    b.CUnitId,
                                    b.CRate,
                                    @cargoid,0,0,0,0
                                FROM
                                    #MxBill a
                                INNER JOIN #GetManPTypeId1 b
                                    ON a.ptypeid=b.typeid
                                WHERE
                                    nid>(@i-1)*150 AND
                                    nid<=@i*150 AND
                                    BTypeId=@MxBTypeId
		
						--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(TaxTotal) FROM SendBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney WHERE BillNumberId = @nBillId

                        UPDATE SendBill SET ShowOrder=ID,CargoID=ISNULL(b.CargoID,'') FROM SendBill a LEFT JOIN  dbo.CargoType b ON  a.KTypeId = b.KTypeId AND b.IsDefault=1
                        WHERE a.BillNumberId=@nBillId 
						
					END
				ELSE IF @VchType = 400
					BEGIN
						IF @GridType = 1
                            INSERT  INTO AppraisalBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        1,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),	
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),0,0                     	
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE IF @GridType = 2
                            INSERT  INTO AppraisalBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     Stypeid,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                         CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-cAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-cAST(recPrice*Qty*@Discount AS  NUMERIC(24, 10) )   ,0,0                   	
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE IF @GridType = 3
                            INSERT  INTO AppraisalBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     Stypeid,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        1,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),0,0
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
						ELSE --全格式
                            INSERT  INTO AppraisalBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     mqty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     ktypeid,
                                     Stypeid,
                                     UnitID,
                                     NUnitID,
                                     UnitRate,
                                     MUnitID,
                                     MUnitRate,
                                     CargoID,
                                     TaxMoney,
                                     NTaxMoney,IsCombined,ItemID)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE qty/b.rate
                                        END,
                                        Qty/b.CRate,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                         CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) ),                      
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @ktypeid1,
                                        @stid,
                                        unitid,
                                        b.aunitid,
                                        b.rate,
                                        b.CUnitId,
                                        b.CRate,
                                        @cargoid,
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-	CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ),
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-	CAST(recPrice*@Discount*Qty AS  NUMERIC(24, 10) ) ,0,0                     
							FROM #MxBill  a 
							INNER JOIN  #GetManPTypeId1 b ON a.ptypeid=b.typeid  WHERE nid > (@i-1)*150 AND nid <=@i*150 AND BTypeId = @MxBTypeId	
		
						--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(TaxTotal) FROM AppraisalBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney ,NTotalMoney=@TotalMoney WHERE BillNumberId = @nBillId

                        UPDATE AppraisalBill SET ShowOrder=ID,CargoID=ISNULL(b.CargoID,'') FROM AppraisalBill a LEFT JOIN  dbo.CargoType b ON  a.KTypeId = b.KTypeId  AND IsDefault=1
                        WHERE a.BillNumberId=@nBillId 
					END
				ELSE IF @VchType = 17
				BEGIN
                        INSERT  INTO MoveBill
                                ( BillNumberId ,
                                  PTypeId ,
                                  Qty ,
                                  nqty ,
                                  MQty ,
                                  KTypeID ,
                                  KTypeId2,
                                  STypeID ,
                                  UnitID ,
                                  NUnitID ,
                                  UnitRate ,
                                  MUnitID ,
                                  MUnitRate ,
                                  InCargoID ,
                                  OutCargoID ,
                                  IsCombined ,
                                  ItemID 
					            )
                                SELECT  @nBillId ,
                                        PTypeId ,
                                        Qty ,
                                        CASE WHEN b.rate = 0 THEN 0
                                             ELSE qty / b.rate
                                        END ,
                                        Qty / b.CRate ,
                                      '',
                                        @ktypeid1 ,
                                        @stid ,
                                        unitid ,
                                        b.aunitid ,
                                        b.rate ,
                                        b.CUnitId ,
                                        b.CRate ,
                                        @cargoid ,
                                        '',
                                        0 ,
                                        0
                                FROM    #MxBill a
                                        INNER JOIN #GetManPTypeId1 b ON a.ptypeid = b.typeid
                                WHERE   nid > ( @i - 1 ) * 150
                                        AND nid <= @i * 150
                                        AND BTypeId = @MxBTypeId	
                                        
                            	--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(Total) FROM MoveBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney WHERE BillNumberId = @nBillId
				END
					ELSE IF @VchType = 21
				BEGIN
                        INSERT  INTO MoveBjBill
                                ( BillNumberId ,
                                  PTypeId ,
                                  Qty ,
                                  nqty ,
                                  MQty ,
                                  KTypeID ,
                                  KTypeId2,
                                  STypeID ,
                                  UnitID ,
                                  NUnitID ,
                                  UnitRate ,
                                  MUnitID ,
                                  MUnitRate ,
                                  InCargoID ,
                                  OutCargoID ,
                                  IsCombined ,
                                  ItemID 
					            )
                                SELECT  @nBillId ,
                                        PTypeId ,
                                        Qty ,
                                        CASE WHEN b.rate = 0 THEN 0
                                             ELSE qty / b.rate
                                        END ,
                                        Qty / b.CRate ,
                                        '',
                                        @ktypeid1 ,
                                        @stid ,
                                        unitid ,
                                        b.aunitid ,
                                        b.rate ,
                                        b.CUnitId ,
                                        b.CRate ,
                                        @cargoid ,
                                        '',
                                        0 ,
                                        0
                                FROM    #MxBill a
                                        INNER JOIN #GetManPTypeId1 b ON a.ptypeid = b.typeid
                                WHERE   nid > ( @i - 1 ) * 150
                                        AND nid <= @i * 150
                                        AND BTypeId = @MxBTypeId	
                                        
                            	--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(Total) FROM MoveBjBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney WHERE BillNumberId = @nBillId
				END	
				
				ELSE IF @VchType = 187
				BEGIN
                        INSERT  INTO STypeMoveBill
                                ( BillNumberId ,
                                BillType,
                                  PTypeId ,
                                  Qty ,
                                  nqty ,
                                  MQty ,
                                  Total ,
                                  KTypeID ,
                                  KTypeId2,
                                  STypeID ,
                                  UnitID ,
                                  NUnitID ,
                                  UnitRate ,
                                  MUnitID ,
                                  MUnitRate ,
                                  InCargoID ,
                                  OutCargoID ,
                                  IsCombined ,
                                  ItemID 
					            )
                                SELECT  @nBillId ,
                                       @VchType,
                                        PTypeId ,
                                        Qty ,
                                        CASE WHEN b.rate = 0 THEN 0
                                             ELSE qty / b.rate
                                        END ,
                                        Qty / b.CRate ,
                                    CASE WHEN  @GridType = 2 OR @GridType = 3 THEN   CAST(recPrice * Qty AS NUMERIC(24, 10)) ELSE   CAST(recPrice * Qty*@Discount AS NUMERIC(24, 10)) END ,
                                      '',
                                        @ktypeid1 ,
                                        @stid ,
                                        unitid ,
                                        b.aunitid ,
                                        b.rate ,
                                        b.CUnitId ,
                                        b.CRate ,
                                        @cargoid ,
                                        '',
                                        0 ,
                                        0
                                FROM    #MxBill a
                                        INNER JOIN #GetManPTypeId1 b ON a.ptypeid = b.typeid
                                WHERE   nid > ( @i - 1 ) * 150
                                        AND nid <= @i * 150
                                        AND BTypeId = @MxBTypeId	
                                        
                            	--修改BillIndex的TotalMoney
						SELECT @TotalQty = SUM(Qty),@TotalMoney = SUM(Total) FROM STypeMoveBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney WHERE BillNumberId = @nBillId
				END	
		IF @costing=3--手工指定算法把成本价格设为-1
		 BEGIN
		 UPDATE dbo.SaleBill SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
		 update dbo.saleBackBill SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
		 update dbo.LoseBill SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
		 update dbo.BuyBill SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
		 update  BuyBackBill SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
		 update OverFlowBill SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
		 update dbo.OrderBill  SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
		 END
		 
		IF @VchType NOT IN (300,301)
		BEGIN
			-- 自动生成的单据会影响草稿库存
			EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,@VchType
		END
		
		IF @VchType IN (300,301)
		BEGIN
			-- 自动生成的单据会影响订单库存
			EXECUTE GP_Deal_OrderQTY @nBillId,@VchType,'+'
		END

				--返回单据编号
				IF @VchType IN (300,301)
					BEGIN
						SELECT @TmpBillCode = BillCode FROM OrderIndex WHERE BillNumberId = @nBillId	
						--如果订单有审核，特殊处理
						IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @VchType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)
							BEGIN
								UPDATE OrderIndex SET IfAudit = 0 WHERE BillNumberId = @nBillId	
							END
					END
				ELSE
					SELECT @TmpBillCode = BillCode FROM BillIndex WHERE BillNumberId = @nBillId	
			
				SET @bCodeList = @bCodeList + ' ' + @TmpBillCode
				
				
				IF @VchType IN(300,301)
				BEGIN
					EXEC GP_SaveBillCode_Seed @nBillId,@NowDate,@VchType,@TmpBillCode
				END  
				ELSE
				BEGIN
					IF NOT EXISTS(
						SELECT ConfigNo
						FROM Userconfig
						WHERE ConfigName='BillcodeCreateTime'
						AND Value=2
					)
					BEGIN
						EXEC GP_SaveBillCode_Seed @nBillId,@NowDate,@VchType,@TmpBillCode
					END	
				END
				
				
				IF @@error<>0 
					BEGIN
						CLOSE BilCursor
						DEALLOCATE BilCursor
						RETURN -2						
					END 
		  END
				SET @i = @i + 1
			END
			DROP TABLE #MxBilloneBtype
			DROP TABLE #MxBill
			FETCH NEXT FROM BilCursor INTO @MxBTypeId
	END			
CLOSE BilCursor
DEALLOCATE BilCursor

--修改BillIndex的值
UPDATE BillIndex SET TotalMoney = 0 WHERE TotalMoney IS NULL
UPDATE BillIndex SET NTotalMoney = 0 WHERE NTotalMoney IS NULL
UPDATE BillIndex SET TotalQty = 0 WHERE TotalQty IS NULL

SET @bcode = @bCodeList
RETURN 0

DROP TABLE #Result,#MxBillold,#StockAlarm,#GetManPTypeId,#temtable,#DraftGoodsStocks,#GetManKTypeId,#GetManPTypeId1,#GoodsStocks,#QueryBjData

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StockCheckHzBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StockCheckHzBill]
GO







/*
	作者：谢吉康
	日期：2009-06-02
	描述：盘点历史库存
-----------------------------------------------------
	Author:		Wang Wei 
	Datetiem:	2010-7-30
	Description:	优化
	库存金额取的是当前仓库+商品的总成本，然后平均
*/
CREATE    PROCEDURE Gp_StockCheckHzBill   --------从StockCheckIndex表得到StockCheck的所有内容(应用在库存盘点)
(
	@OperatorID 	varchar(100),       		-- 操作员id
	@KtypeId 		varchar(100)='',         	-- 仓库ID
	@EndDatePoint	datetime='',				-- 盘点日期		
	@UserCode 		varchar(100)='',			-- 商品编号
	@FullName 		varchar(100)='',			-- 商品名称
	@Flag			int,						-- 1.全部商品  2.盘盈商品  3.盘亏商品
	@ifwx			int=0,							-- 0.正常商品盘点  1.维修商品盘点
	@StypeId		VARCHAR(MAX),
	@SerialCheck	INT=0--序列号盘点汇总
	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM dbo.F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorID)



--商品
CREATE TABLE #GetManPTypeAll
(
	TypeId		VARCHAR(100),
	UserCode 	VARCHAR(100),
	fullname 	VARCHAR(100),
	SonNum		NUMERIC(9,0),
	Deleted		INT
)
INSERT INTO #GetManPTypeAll SELECT TypeId,UserCode,fullname,SonNum,Deleted FROM  PType
/**/

DECLARE @costing int  --当前系统的成本算法

SELECT @costing=subvalue FROM sysdata WHERE subname='costing'

/*BEGIN
取未处理的盘点单中的盘点数据，
根据批次不同分开盘点
*/

CREATE TABLE #stockDetail(
	KtypeID			VARCHAR(100),
	PTypeID			VARCHAR(100),
	GoodsCostPrice	 NUMERIC(24, 10) ,
	GoodsNumber		VARCHAR(100),
	ProduceDate		VARCHAR(100),
	ValidDate		VARCHAR(100),
	SQty			 NUMERIC(24, 10) ,
	StockCheckID	INT,
	qty				 NUMERIC(24, 10) ,
	newNO			VARCHAR(3000),
	CargoID			INT,
	ItemID			INT,
	IsCombined		INT,
	nqty			 NUMERIC(24, 10) ,
	snqty			 NUMERIC(24, 10) 
)
DECLARE @SQL VARCHAR(MAX)
SET @SQL='
	INSERT INTO #stockDetail
	SELECT	D.KTypeID,B.PTypeId,B.GoodsCostPrice,B.GoodsNumber,B.ProduceDate,B.ValidDate,MAX(StockQty) as sqty,D.StockCheckID, 
			sum(B.qty),'
IF	@costing=0 
	SET @SQL=@SQL+'(D.KTypeID+B.PTypeID+CAST(ISNULL(B.CargoID,0) as VARCHAR)+cast(ISNULL(B.IsCombined,0) as varchar)+cAST(b.ItemID as varchar)+CONVERT(VARCHAR(MAX),B.GoodsNumber)+CONVERT(VARCHAR(MAX),B.ProduceDate)+CONVERT(VARCHAR(MAX),B.ValidDate)) as newNo, '	
ELSE
	SET @SQL=@SQL+'(D.KTypeID+B.PTypeID+CAST(ISNULL(B.CargoID,0) as VARCHAR)+cast(ISNULL(B.IsCombined,0) as varchar)+cAST(b.ItemID as varchar)+CONVERT(VARCHAR(MAX),B.goodscostprice)+CONVERT(VARCHAR(MAX),B.GoodsNumber)+CONVERT(VARCHAR(MAX),B.ProduceDate)+CONVERT(VARCHAR(MAX),B.ValidDate)) as newNo, '	

SET @SQL=@SQL+'b.CargoID,b.ItemID,b.IsCombined,sum(B.nqty),MAX(StocknQty) as snqty'
SET @SQL=@SQL+'
	FROM	StockCheckIndex D
			INNER JOIN 	StockCheck B	ON B.StockCheckID=D.StockCheckID 
			inner join #GetManKTypeId k1 on k1.typeid=d.ktypeid
			
			'  
	
SET @SQL=@SQL+' 
	WHERE	B.Qty IS NOT NULL AND D.Pass <> 1 AND D.SerialCheck='+CAST(@SerialCheck As VARCHAR(10))+' AND D.IfWx ='+CAST(@ifWx As VARCHAR(10)) 	
--IF @KtypeId<> '' OR  @KtypeId<>'00000'
--	SET @SQL=@SQL+' AND D.KTypeId LIKE '+CHAR(39)+@KtypeId+CHAR(39)
	
SET @SQL=@SQL+'	GROUP BY D.KTypeID,B.PTypeId,B.GoodsCostPrice,B.GoodsNumber,B.ProduceDate,B.ValidDate,D.StockCheckID,b.CargoID,b.ItemID,b.IsCombined '

print @SQL
EXEC(@SQL)
--SELECT * FROM #stockDetail
---	return 

/*End*/

CREATE TABLE #GoodsStocks
(
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) ,
	CostPrice	 NUMERIC(24, 10) ,
	--cargoid		INT,
	--IsCombined	INT,
	--ItemID		INT,
	--GoodsNumber	 varchar(300)
)
DECLARE @stockSql NVARCHAR(MAX)
SEt @stockSql='	
INSERT INTO #GoodsStocks
	(
		PTypeId,
		Qty,
		CostTotal,
		CostPrice
			
	)
SELECT	ptypeid,
		ISNULL(SUM(G.Qty),0) AS Qty,
		ISNULL(SUM(G.CostTotal),0) AS CostTotal,
		CASE ISNULL(SUM(G.Qty),0) 
			WHEN 0 THEN 0 
			ELSE ROUND(CAST(ISNULL(SUM(G.CostTotal),0) AS  NUMERIC(24, 10) )/CAST(ISNULL(SUM(G.Qty),0) AS  NUMERIC(24, 10) ),4) 
		END Price
FROM	(
		SELECT	ptypeid,
				SUM(qty) as qty,
				SUM(Total) as CostTotal
		FROM	'+
				CASE  @ifwx WHEN 1  THEN 'wx_GoodsStocks'
							ELSE'GoodsStocks  ' END 
				+' a 
				inner  join #GetManKTypeId  b on a.ktypeid=b.typeid 
		WHERE	KTypeId <> ''10000''
				
		Group by PtypeId
		UNION ALL  
		SELECT typeid,0 as qty,0 as CostTotal FROM ptype  WHERE sonnum=0
		)G
group by G.ptypeid		'


PRINT @stockSql
EXEC  sp_executesql @stockSql


Create TABLE  #Result(
	typeid		varchar(500),
	StockCheckId	NUMERIC(18,0),
	qty				 NUMERIC(24, 10) ,
	QtyMoney	 NUMERIC(24, 10) ,
	countmoney	 NUMERIC(24, 10) ,
	checkqty	 NUMERIC(24, 10) ,
	BillCode	varchar(200),
	CountQty	 NUMERIC(24, 10) ,
	nQty		 NUMERIC(24, 10) ,
	checkNqty	 NUMERIC(24, 10) ,
	CountnQty	 NUMERIC(24, 10) ,
	ItemID		int,
	IsCombined	int,
	cargoid		int,
	GoodsNumber	VARCHAR(500),
	nid			INT identity(1,1)
)

DECLARE @selectSql NVARCHAR(MAX)


--正式查询数据
SET @selectSql=' INSERT INTO #Result( typeid,
										StockCheckId,		
									  	qty	,		
									  	QtyMoney	,
									  	countmoney,	
									  	checkqty,	
									  	BillCode,	
									  	CountQty,	
									  	nQty	,	
									  	checkNqty,	
									  	CountnQty,	
									  	ItemID	,	
									  	IsCombined	,
									  	cargoid,		
									  	GoodsNumber)'	
SET @selectSql+='
				SELECT 	A.TypeId,
      					B.StockCheckId,
						ISNULL(B.Qty,0) AS Qty,
						--ISNULL(B.Total,0) AS QtyMoney,
						ISNULL(ISNULL(B.Qty,0)*B.CostPrice,0) AS QtyMoney,
						--ISNULL(B.CheckTotal,0)-ISNULL(B.Total,0) AS CountMoney,
						(ISNULL(ISNULL(B.CheckQty,0)*B.CostPrice,0) - ISNULL(ISNULL(B.Qty,0)*B.CostPrice,0)) as  CountMoney,
						ISNULL(B.CheckQty,0) AS CheckQty,
						(SELECT BillCode FROM StockCheckIndex WHERE StockCheckId=b.StockCheckId AND pass=0) AS BillCode,
						ISNULL((ISNULL(b.CheckQty,0)-
							CASE B.Qty 
								WHEN NULL THEN 0 
								ELSE B.Qty END),0
							) AS CountQty,
						ISNULL(B.nQty,0) AS nQty,
						ISNULL(B.checkNqty,0) AS checkNqty,
						ISNULL((ISNULL(b.checkNqty,0)-
							CASE B.Qty 
								WHEN NULL THEN 0 
								ELSE B.nQty END),0
							) AS CountnQty,
							
							B.ItemID,
							B.IsCombined,
							B.cargoid,
							B.GoodsNumber
				FROM 	Ptype A 
				INNER  JOIN ('
						SET @selectSql+='				
								SELECT	sd.PTypeID, 
								MAX(sd.StockCheckID) as StockCheckId,
								MAX(sd.SQty) as Qty,
								sum(sd.qty)   as CheckQty,
								newNo,
								SUM(sd.nqty) as checkNqty,
								MAX(sd.snqty) as nQty,
								sd.CargoID,
								sd.ItemID,
								sd.IsCombined,
								sd.GoodsNumber,
								MAX(gs.CostPrice) as costprice
						FROM	#stockDetail sd
								INNER JOIN #GoodsStocks gs ON sd.PTypeID=gs.PTypeId
						group by sd.newNO,sd.KtypeID,sd.PTypeID,sd.CargoID,sd.ItemID,sd.IsCombined,sd.GoodsNumber	'			
				
	
SET @selectSql+='
				)B ON A.TypeId = B.PTypeId
				WHERE  	A.SonNum=0 
						AND A.UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
						AND A.FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+' 
				ORDER BY A.UserCode'

PRINT(@selectSql)
exec (@selectSql)

DECLARE @tb table(
	fullname varchar(500),
	nid			INT
)


INSERT INTO @tb(fullname,nid)
SELECT xs.FullName,r.nid 
FROM #Result  r INNER JOIN xw_SelfData xs ON r.ItemID=xs._Id
WHERE IsCombined=0 
UNION ALL 
SELECT REPLACE(xs.FullName,'я','/') as fullname,r.nid 
FROM #Result  r INNER JOIN CustomReferenceValue xs ON r.ItemID=xs.id
WHERE IsCombined=1 

IF @Flag = 1
		SELECT a.*,cs.fullname as itemname,ct.FullName as cargospace,pu.unit,pu.nunit, pu.stockunitname as munit,
			   (a.Qty/pu.stockmunitrate)  as mqty,	
			   (a.CheckQty/pu.stockmunitrate)  as checkmqty,
			   (a.CheckQty/pu.stockmunitrate)-(a.Qty/pu.stockmunitrate) as countmqty,
				ISNULL(aux1.fullname,'') AS auxfullname1, 
				ISNULL(aux2.fullname,'') AS auxfullname2, 
				ISNULL(aux3.fullname,'') AS auxfullname3,
				ISNULL(aux.SaleUnitRate1,0) AS auxrate1,
				ISNULL(aux.SaleUnitRate2,0) AS auxrate2,
				ISNULL(aux.SaleUnitRate3,0) AS auxrate3,
				CAST('' AS VARCHAR(100))  AS stockcauqty,
				CAST('' AS VARCHAR(100))  AS cauqty,
				CAST('' AS VARCHAR(100))  AS countcauqty  
		FROM #Result a	
			INNER JOIN F_GetPtypeUnitInfo() pu ON pu.typeid=a.TypeId
			LEFT JOIN @tb cs ON a.nid=cs.nid
			LEFT JOIN  CargoType ct ON a.CargoID=ct.CargoID
			LEFT JOIN dbo.PType_AuxiliaryUnits_Ext aux ON aux.ptypeid = a.typeid
			LEFT JOIN dbo.PType_Units aux1 ON aux1.UnitsId = aux.SaleUnitID1
			LEFT JOIN dbo.PType_Units aux2 ON aux2.UnitsId = aux.SaleUnitID2
			LEFT JOIN dbo.PType_Units aux3 ON aux3.UnitsId = aux.SaleUnitID3
ELSE IF @Flag = 2
		SELECT a.*,cs.fullname as itemname,ct.FullName as cargospace,pu.unit,pu.nunit, pu.stockunitname as munit,
			   (a.Qty/pu.stockmunitrate)  as mqty,
			   (a.CheckQty/pu.stockmunitrate)  as checkmqty	 ,
			   (a.CheckQty/pu.stockmunitrate)-(a.Qty/pu.stockmunitrate) as countmqty,
				ISNULL(aux1.fullname,'') AS auxfullname1, 
				ISNULL(aux2.fullname,'') AS auxfullname2, 
				ISNULL(aux3.fullname,'') AS auxfullname3,
				ISNULL(aux.SaleUnitRate1,0) AS auxrate1,
				ISNULL(aux.SaleUnitRate2,0) AS auxrate2,
				ISNULL(aux.SaleUnitRate3,0) AS auxrate3,
				CAST('' AS VARCHAR(100))  AS stockcauqty,
				CAST('' AS VARCHAR(100))  AS cauqty,
				CAST('' AS VARCHAR(100))  AS countcauqty    
		FROM #Result a 
		LEFT JOIN @tb cs ON a.nid=cs.nid
		LEFT JOIN  CargoType ct ON a.CargoID=ct.CargoID
		INNER JOIN F_GetPtypeUnitInfo() pu ON pu.typeid=a.TypeId
		LEFT JOIN dbo.PType_AuxiliaryUnits_Ext aux ON aux.ptypeid = a.typeid
		LEFT JOIN dbo.PType_Units aux1 ON aux1.UnitsId = aux.SaleUnitID1
		LEFT JOIN dbo.PType_Units aux2 ON aux2.UnitsId = aux.SaleUnitID2
		LEFT JOIN dbo.PType_Units aux3 ON aux3.UnitsId = aux.SaleUnitID3
		WHERE CountQty > 0

ELSE IF @Flag = 3
		SELECT a.* ,cs.fullname as itemname ,ct.FullName as cargospace,pu.unit,pu.nunit, pu.stockunitname as munit ,
			   (a.Qty/pu.stockmunitrate)  as mqty,
			   (a.CheckQty/pu.stockmunitrate)  as checkmqty	,
			   (a.CheckQty/pu.stockmunitrate)-(a.Qty/pu.stockmunitrate)  as countmqty,
				ISNULL(aux1.fullname,'') AS auxfullname1, 
				ISNULL(aux2.fullname,'') AS auxfullname2, 
				ISNULL(aux3.fullname,'') AS auxfullname3,
				ISNULL(aux.SaleUnitRate1,0) AS auxrate1,
				ISNULL(aux.SaleUnitRate2,0) AS auxrate2,
				ISNULL(aux.SaleUnitRate3,0) AS auxrate3,
				CAST('' AS VARCHAR(100)) AS stockcauqty,
				CAST('' AS VARCHAR(100)) AS cauqty,
				CAST('' AS VARCHAR(100)) AS countcauqty    
		FROM #Result a  
		LEFT JOIN @tb cs ON a.nid=cs.nid
		LEFT JOIN  CargoType ct ON a.CargoID=ct.CargoID
		INNER JOIN F_GetPtypeUnitInfo() pu ON pu.typeid=a.TypeId
		LEFT JOIN dbo.PType_AuxiliaryUnits_Ext aux ON aux.ptypeid = a.typeid
		LEFT JOIN dbo.PType_Units aux1 ON aux1.UnitsId = aux.SaleUnitID1
		LEFT JOIN dbo.PType_Units aux2 ON aux2.UnitsId = aux.SaleUnitID2
		LEFT JOIN dbo.PType_Units aux3 ON aux3.UnitsId = aux.SaleUnitID3
		WHERE CountQty < 0

--删除临时表
DROP TABLE #GoodsStocks,#Result,#GetManKTypeId, #stockDetail

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StockCheckHzBillAutoCaoGao]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StockCheckHzBillAutoCaoGao]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：谢吉康
	日期：2009-06-02
	描述：盘点历史库存
*/
CREATE     PROCEDURE Gp_StockCheckHzBillAutoCaoGao   --------从StockCheckIndex表得到StockCheck的所有内容(应用在库存盘点)
(
	@OperatorID 	varchar(100),       	-- 操作员id
	@chrKtypeId 		varchar(100)='',        -- 可选的商品ID
	@EndDatePoint	datetime='',			-- 盘点日期		
	@UserCode 		varchar(100)='',		-- 商品编号
	@FullName 		varchar(66)='',			-- 商品名称
	@Flag			int,					-- 1.全部商品  2.盘盈商品  3.盘亏商品
	@IfWx			int,					-- 1.维修盘点  0.正常盘点
	@bcode			varchar(8000) OUTPUT,	-- 返回单据编号列表
	@autocount 	INT output
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -5
	END
END  

-- ********	判断是否试用版 - END	********
-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1


DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------
DECLARE @saveKtypeid VARCHAR(100)
SET @saveKtypeid=@chrKtypeId
--权限范围临时表
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)

DECLARE @costing int  --当前系统的成本算法
DECLARE @TmpBillCode	varchar(8000)
DECLARE @SKTypeId		varchar(1000)	--客户选的仓库
SET @SKTypeId = @chrKtypeId

SET @TmpBillCode = ''

SELECT @costing=subvalue FROM sysdata WHERE subname='costing'

-------------------------------------------------------------读表的内容-----------------------------------------------------

IF @UserCode='' SELECT @UserCode='%' ELSE SELECT @UserCode='%'+@UserCode+'%'
IF @FullName='' SELECT @FullName='%' ELSE SELECT @FullName='%'+@FullName+'%'

DECLARE @cid INT
DECLARE @rate  NUMERIC(24, 10)   
SELECT @cid= CID,@rate=Rate FROM Ac_Currency WHERe Sysrow=1

/*BEGIN
取未处理的盘点单中的盘点数据，
根据批次不同分开盘点
*/

CREATE TABLE #stockDetail(
	KtypeID			VARCHAR(100),
	PTypeID			VARCHAR(100),
	GoodsCostPrice	 NUMERIC(24, 10) ,
	GoodsNumber		VARCHAR(100),
	ProduceDate		VARCHAR(100),
	ValidDate		VARCHAR(100),
	SQty			 NUMERIC(24, 10) ,
	StockCheckID	INT,
	qty				 NUMERIC(24, 10) ,
	newNO			VARCHAR(3000),
	CargoID			INT,
	ItemID			INT,
	IsCombined		INT,
	nqty			 NUMERIC(24, 10) ,
	snqty			 NUMERIC(24, 10) 
)
DECLARE @SQL VARCHAR(MAX)
SET @SQL='
	INSERT INTO #stockDetail
	SELECT	D.KTypeID,B.PTypeId,B.GoodsCostPrice,B.GoodsNumber,B.ProduceDate,B.ValidDate,MAX(StockQty) as sqty,D.StockCheckID, sum(B.qty),'

IF	@costing=0 
	SET @SQL=@SQL+'(D.KTypeID+B.PTypeID+CAST(ISNULL(B.CargoID,0) as VARCHAR)+cast(ISNULL(B.IsCombined,0) as varchar)+cAST(b.ItemID as varchar)+CONVERT(VARCHAR(MAX),B.GoodsNumber)+CONVERT(VARCHAR(MAX),B.ProduceDate)+CONVERT(VARCHAR(MAX),B.ValidDate)) as newNo, '	
ELSE
	SET @SQL=@SQL+'(D.KTypeID+B.PTypeID+CAST(ISNULL(B.CargoID,0) as VARCHAR)+cast(ISNULL(B.IsCombined,0) as varchar)+cAST(b.ItemID as varchar)+CONVERT(VARCHAR(MAX),B.goodscostprice)+CONVERT(VARCHAR(MAX),B.GoodsNumber)+CONVERT(VARCHAR(MAX),B.ProduceDate)+CONVERT(VARCHAR(MAX),B.ValidDate)) as newNo, '	


SET @SQL=@SQL+'b.CargoID,b.ItemID,b.IsCombined,sum(B.nqty),MAX(StocknQty) as snqty'
SET @SQL=@SQL+'
	FROM	StockCheckIndex D
			INNER JOIN 	StockCheck B	ON B.StockCheckID=D.StockCheckID '  
IF @MKtypeid='-99999'
	SET @SQL=@SQL+' INNER JOIN #GetManKTypeId k ON D.KTypeId=k.typeid '
	
SET @SQL=@SQL+' 
	WHERE	B.Qty IS NOT NULL AND D.Pass <> 1	AND D.IfWx ='+CAST(@ifWx As VARCHAR(10))	
IF @chrKtypeId<> '' AND  @chrKtypeId<>'00000'
	SET @SQL=@SQL+' AND D.KTypeId LIKE '+CHAR(39)+@chrKtypeId+CHAR(39)
	
SET @SQL=@SQL+'	GROUP BY D.KTypeID,B.PTypeId,B.GoodsCostPrice,B.GoodsNumber,B.ProduceDate,B.ValidDate,D.StockCheckID,b.CargoID,b.ItemID,b.IsCombined '

EXEC(@SQL)

/*End*/
DECLARE @STypeID VARCHAR(100)
IF @chrKtypeId='' OR @chrKtypeId='00000' SELECT @chrKtypeId='%'

SELECT TOP 1 @STypeID=stypeid FROM stock WHERE typeId=@chrKtypeId
--取当前库存的数量，期初+出入库记录

CREATE TABLE #GoodsStocks
(
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) ,
	CostPrice	 NUMERIC(24, 10) ,
	Nqty		 NUMERIC(24, 10) ,
	cargoid		INT,
	IsCombined	INT,
	ItemID		INT,
	GoodsNumber	 varchar(300)
)
IF @IfWx = 0
	INSERT INTO	#GoodsStocks
	(
		PTypeId,
		Qty,
		CostTotal,
		CostPrice,
		Nqty,
		cargoid,
		IsCombined,
		ItemID,
		GoodsNumber
	)
	SELECT	G.PTypeId,
			ISNULL(SUM(G.Qty),0) AS Qty,
			ISNULL(SUM(G.CostTotal),0) AS CostTotal,
			CASE ISNULL(SUM(G.Qty),0) 
					WHEN 0 THEN 0 
					ELSE ROUND(CAST(ISNULL(SUM(G.CostTotal),0) AS  NUMERIC(24, 10) )/CAST(ISNULL(SUM(G.Qty),0) AS  NUMERIC(24, 10) ),4) 
			END Price,
			ISNULL(SUM(G.NQty),0) AS NQty,
			G.CargoID,
			G.IsCombined,
			G.ItemID,
			G.GoodsNumber
	FROM (
			SELECT	PTypeId,
					ISNULL(SUM(Qty),0) AS Qty,
					ISNULL(SUM(CostTotal),0) AS CostTotal,
					ISNULL(SUM(NQty),0) AS NQty,
					ItemID ,
					IsCombined,
					CargoID,
					GoodsNumber
			FROM	InOutStockTable
			WHERE	Audited = 1
					AND KTypeId <> '10000'
					AND KTypeId LIKE @chrKtypeId + '%'
					AND KTypeId IN (SELECT TypeId FROM #GetManKTypeId)
			GROUP BY PTypeId,ItemID,IsCombined,CargoID,GoodsNumber
			UNION ALL
			SELECT	i.PtypeId,
					ISNULL(SUM(gq.Qty),0) AS Qty,
					(CASE ISNULL(SUM(i.Price),0) 
						WHEN 0 THEN 0
						ELSE ISNULL(SUM(gq.Qty),0)* ISNULL(SUM(i.Price),0) 
					END) as CostTotal,
					ISNULL(SUM(gq.NQty),0) AS NQty,
					gq.ItemID,
					gq.Iscombined,
					gq.CargoID,
					gq.GoodsNumber
			FROM	iniGoodsStocks i
					INNER JOIN F_GetAllManagerBaseTypeId(@chrKtypeId,4,@OperatorID) mk ON i.KtypeId=mk.TypeId
					INNER JOIN Ini_GOODSSTOCKS_QTY gq ON i.PtypeId=gq.PTypeID 
													  AND i.ktypeid=gq.ktypeid
													  AND i.ProduceDate=gq.ProduceDate 
													  AND i.ValidDate=gq.ValidDate 
													  AND i.GoodsNumber=gq.GoodsNumber
			GROUP BY i.PTypeId,gq.ItemID,gq.IsCombined,gq.CargoID,gq.GoodsNumber
			UNION ALL
			SELECT	TypeId,
					0 AS Qty,
					0 AS CostTotal,
					0 AS Nqty,
					0 as CargoID,
					0 as IsCombined,
					0 as ItemID,
					'' as GoodsNumber
			FROM	F_GetManPTypeAll(@OperatorID)
			WHERE	SonNum = 0
					AND Deleted = 0
	)G GROUP BY G.PTypeId,G.CargoID,G.IsCombined,G.ItemID,G.GoodsNumber
ELSE
BEGIN
	INSERT INTO	#GoodsStocks
	(
		PTypeId,
		Qty,
		CostTotal,
		Nqty,
		cargoid,		
		IsCombined,	
		ItemID,
		GoodsNumber	
	)
	SELECT	G.PTypeId,
			ISNULL(SUM(G.Qty),0) AS Qty,
			ISNULL(SUM(G.CostTotal),0) AS CostTotal,
			ISNULL(SUM(G.NQty),0) AS nQty,
			0 as cargoid,
			g.IsCombined,
			g.ItemID,
			g.GoodsNumber
	FROM (
			SELECT	PTypeId,
					ISNULL(SUM(Qty),0) AS Qty,
					ISNULL(SUM(CostTotal),0) AS CostTotal,
					ISNULL(SUM(NQty),0) AS NQty,
					IsCombined,
					ItemID,
					GoodsNumber
			FROM	Wx_InOutStockTable
			WHERE	Audited = 1
					AND KTypeId <> '10000'
					AND KTypeId LIKE @chrKtypeId + '%'
					AND KTypeId IN (SELECT * FROM #GetManKTypeId)
			GROUP BY PTypeId,CargoID,IsCombined,ItemID,GoodsNumber
			UNION ALL
			SELECT	PTypeId,
					ISNULL(SUM(Qty),0) AS Qty,
					ISNULL(SUM(Total),0) AS CostTotal,
					ISNULL(SUM(NQty),0) AS NQty,
					IsCombined,
					ItemID,
					GoodsNumber
			FROM	Wx_iniGoodsStocks
			WHERE	KTypeId LIKE @chrKtypeId + '%'
					AND KTypeId IN (SELECT * FROM #GetManKTypeId)
			GROUP BY PTypeId,Iscombined,ItemID,GoodsNumber
			UNION ALL
			SELECT	TypeId,
					0 AS Qty,
					0 AS CostTotal,
					0 AS Nqty,
					0 as IsCombined,
					0 as ItemID,
					'' as GoodsNumber
			FROM	F_GetManPTypeAll(@OperatorID)
			WHERE	SonNum = 0
					AND Deleted = 0
	)G GROUP BY G.PTypeId,g.IsCombined,g.ItemID,g.GoodsNumber
END	

--正式查询数据
SELECT 	A.TypeId,
		A.usercode,
		A.fullname,
		A.unit1,
      	B.StockCheckId,
		(SELECT BillCode FROM StockCheckIndex WHERE StockCheckId=b.StockCheckId AND pass=0) AS BillCode,
		ISNULL(B.Qty,0) AS Qty,
		ISNULL(B.Total,0) AS QtyMoney,
		ISNULL(B.CheckQty,0) AS CheckQty,
		ISNULL((ISNULL(b.CheckQty,0)-
			CASE B.Qty 
				WHEN NULL THEN 0 
				ELSE B.Qty END),0
			) AS CountQty,
			
		B.GoodsCostPrice,
		B.GoodsNumber,
		B.ProduceDate,
		B.ValidDate,
		ISNULL(B.NQty,0) AS NQty,
		ISNULL(B.CheckNQty,0) AS CheckNQty,
		
		ISNULL((ISNULL(b.CheckNQty,0)-
			CASE B.NQty 
				WHEN NULL THEN 0 
				ELSE B.NQty END),0
			) AS CountNQty,
		B.CargoID,
		B.ItemID,
		B.IsCombined,
		A.StockUnitId AS MunitID,
		A.baseUnitId AS UnitID,
		A.AssistantUnitId AS NUnitID,
		e1.Rate AS MUnitrate,
		e2.Rate AS Unitrate
INTO	#Result
FROM 	PType A 
INNER JOIN (
				SELECT	PTypeID, 
						MAX(StockCheckID) as StockCheckId,
						0 AS Total,
						MAX(SQty) as Qty,
						sum(qty)   as CheckQty,
						newNo,
						Max(GoodsCostPrice) as GoodsCostPrice	,
						GoodsNumber,		
						ProduceDate	,	
						ValidDate,
						SUM(nqty) as checkNqty,
						MAX(snqty) as nQty,
						CargoID,
						ItemID,
						IsCombined
				FROM #stockDetail
				GROUP BY newNO,KtypeID,PTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID,ItemID,IsCombined	
							
)B ON A.TypeId = B.PTypeId
LEFT JOIN PType_Units_Ext e1 On (A.StockUnitId=e1.UnitsId AND A.typeId=e1.PtypeID)
LEFT JOIN PType_Units_Ext e2 On (A.AssistantUnitId=e2.UnitsId AND A.typeId=e2.PtypeID)
WHERE  	A.SonNum=0 
		AND A.Deleted=0 
		--AND A.TypeId IN (SELECT * FROM #GetManPTypeId)
		AND A.UserCode LIKE '%'+@UserCode+'%'
		AND A.FullName LIKE '%'+@FullName+'%'
ORDER BY A.UserCode


DECLARE @MONTH 				varchar(50),
		@DAY 				varchar(50),
		@BillCodeConfig		varchar(10),
		@BillCode			varchar(300),
		@Rex				int,
		@Tax				 NUMERIC(24, 10) ,
		@period				int,
		@DTypeId			varchar(200),
		@nBillId			numeric(18,0),
		@recPrice			 NUMERIC(24, 10) ,
		@preprice			 NUMERIC(24, 10) ,
		@Explain			varchar(400),
		@KTypeId			varchar(200),
		@TotalQty			 NUMERIC(24, 10) ,
		@ETypeId			varchar(200),
		@bCount				int,
		@BillCount			int,
		@i					int,
		@bCodeList			varchar(8000),
		@cdfullname			VARCHAR(256)=''

SET @Tax = 0
SET @recPrice = 0
SET @preprice = 0
SET @ETypeId = @OperatorID
SET @i = 1
SET @bCodeList = ''

IF @IfWx = 0
	SET @Explain = '库存盘点单草稿'
ELSE
	SET @Explain = '维修商品库存盘点单草稿'

DECLARE @stid varchar(100)	

IF isnull(@saveKtypeid,'')='' SELECT TOP 1 @stid=stypeid FROM stock WHERE typeId='00000'
ELSE  SELECT TOP 1 @stid=stypeid FROM stock WHERE typeId=@saveKtypeid

IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '1')
	SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'

SELECT @period = period FROM MonthProc WHERE MonthNo = '本期' 
SELECT @DTypeId = D.TypeId FROM Department D,Employee E WHERE E.Department = D.FullName AND E.TypeId = @ETypeId

SET @MONTH = month(getdate())
SET @DAY = day(getdate())

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

SET @KTypeId = '00000'

IF @chrKtypeId <> ''
	BEGIN
		IF @chrKtypeId = '00000' OR @chrKtypeId = '%'
			SET @KTypeId = ''
		ELSE
			SET @KTypeId = @chrKtypeId
	END


CREATE TABLE #BillMx
(
	nid			int identity(1,1),
	TypeId		varchar(200),
	CountQty	 NUMERIC(24, 10) ,
	GoodsCostPrice		 NUMERIC(24, 10) ,
	GoodsNumber			VARCHAR(100),
	ProduceDate			VARCHAR(100),
	ValidDate			VARCHAR(100),
	CountNQty		 NUMERIC(24, 10) ,
	cargoid				INT,
	IsCombined			INT,
	ItemID				INT,
	MunitID				INT,
	UnitID				INT,
	NUnitID				INT,
	MUnitrate		 NUMERIC(24, 10) ,	
	Unitrate		 NUMERIC(24, 10) ,	
)

DECLARE @BeginDate 	datetime,
		@szItem 	varchar(30),
		@szVchCode 	varchar(30),
		@szPeriod	varchar(20),
		@cefullname	VARCHAR(500)

EXEC Gp_GetSubValue 'period',@stid,@szPeriod out
SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod 
IF GetDate()<@BeginDate 
	BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
		RETURN -33
	END

DECLARE
	@NowDate	DATETIME

SELECT @NowDate=GETDATE()

--生成报溢单
IF EXISTS(SELECT TOP 1 1 FROM #Result WHERE CountQty > 0)
	BEGIN
		TRUNCATE TABLE #BillMx

		INSERT INTO #BillMx(TypeId,CountQty,GoodsCostPrice,GoodsNumber,ProduceDate,ValidDate,CountNQty,cargoid,IsCombined,ItemID,MunitID,NUnitID,UnitID,MUnitrate,Unitrate) 
		SELECT TypeId,CountQty,GoodsCostPrice,GoodsNumber,ProduceDate,ValidDate,CountNQty ,cargoid,IsCombined,ItemID,MunitID,NUnitID,UnitID,MUnitrate,CountQty/Unitrate
		FROM #Result WHERE CountQty > 0

		SELECT @bCount = COUNT(*) FROM #BillMx

		IF @bCount % 150 = 0
			SET @BillCount = @bCount / 150
		ELSE
			SET @BillCount = @bCount / 150 + 1

		SET @i =  1
		WHILE @i<=@BillCount
			BEGIN		
				--生成单据编号
				IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 14) AND @BillCodeConfig = '1'
					BEGIN
						SELECT @MONTH=''
						SELECT @DAY = FullName,@stid=STypeID FROM Stock WHERE TypeID = @KTypeId
						SELECT @cefullname = E.typeid FROM Employee E WHERE E.TypeId = @OperatorID
						SELECT @cdfullname=fullname FROM dbo.Department WHERE typeid=@DTypeId
					END
				
				EXEC @Re=Gp_GetBillCode 14, @MONTH,@DAY,'BY',@NowDate,@stid,@BillCode output,@cdfullname,@cefullname
				
				IF @Re <> 0
					RETURN -2	
					
				SELECT @STypeID=STypeID
				FROM STOCK
				WHERE typeId=@KTypeId									
		
				--写入单据主表
				INSERT INTO BillIndex (AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,
										etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,
										period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,
										DTypeId,Explain,Stypeid,CID,Rate,NTotalInMoney,NTotalMoney,NPreferenceMoney,NVIPCZMoney)
				VALUES(9999,CONVERT(varchar(10),GetDate(),120),@BillCode,14,'','','','',@ktypeid,'','f',@ETypeId,0,0,0,@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@STypeID,@cid,@rate,0,0,0,0)
				
				IF @@ROWCOUNT = 0
					RETURN -3
				ELSE
					SET @nBillId = SCOPE_IDENTITY();
				
				--插入明细表
				INSERT INTO OverFlowBill(BillNumberId,PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
				STypeID,NQty,ItemID,IsCombined,CargoID,MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,KTypeId,IfWx)
				SELECT	@nBillId AS BillNumberId,TypeId,abs(CountQty),GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
						@STypeID,abs(CountNQty),ItemID,IsCombined,cargoid,MunitID,NUnitID,UnitID,MUnitrate,
						CASE when a.CountNQty=0  THEN 0 else (abs(CountQty)/abs(a.CountNQty)) END,--p.unitrate,
						abs(CountQty)/MUnitrate ,@ktypeid,@IfWx
				FROM #BillMx a
				WHERE  nid > (@i-1)*150 AND nid <=@i*150
				
				UPDATE dbo.overflowBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
				--修改BillIndex的TotalMoney
				SELECT @TotalQty = SUM(Qty) FROM OverFlowBill WHERE BillNumberId = @nBillId
				UPDATE BillIndex SET TotalQty = @TotalQty,IfWx = @IfWx WHERE BillNumberId = @nBillId
		
				--返回单据编号
				SELECT @TmpBillCode = ISNULL(BillCode,' ') FROM BillIndex WHERE BillNumberId = @nBillId	

				SET @bCodeList = @bCodeList + 'я' + @TmpBillCode
				
				IF NOT EXISTS(
					SELECT ConfigNo
					FROM Userconfig
					WHERE ConfigName='BillcodeCreateTime'
					AND Value=2
				)
				BEGIN
					EXEC GP_SaveBillCode_Seed	@nBillId,@NowDate,14,@BillCode
				END

				IF @@error<>0 
					BEGIN
						RETURN -2
					END 

				SET @i = @i + 1
				
				-- 自动生成的单据会影响草稿库存
				EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,14
			END
	END

SET @MONTH = month(getdate())
SET @DAY = day(getdate())

--生成报损单
IF EXISTS(SELECT TOP 1 1 FROM #Result WHERE CountQty < 0)
	BEGIN
	
		
		TRUNCATE TABLE #BillMx

		INSERT INTO #BillMx(TypeId,CountQty,GoodsCostPrice,GoodsNumber,ProduceDate,ValidDate,CountNQty,cargoid,IsCombined,ItemID,MunitID,NUnitID,UnitID,MUnitrate,Unitrate) 
		SELECT TypeId,CountQty,GoodsCostPrice,GoodsNumber,ProduceDate,ValidDate,CountNQty ,cargoid,IsCombined,ItemID,MunitID,NUnitID,UnitID,MUnitrate,Unitrate
		FROM #Result WHERE CountQty < 0

		SELECT @bCount = COUNT(*) FROM #BillMx

		IF @bCount % 150 = 0
			SET @BillCount = @bCount / 150
		ELSE
			SET @BillCount = @bCount / 150 + 1

		SET @i =  1

		WHILE @i<=@BillCount
			BEGIN
				--生成单据编号
				IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 9) AND @BillCodeConfig = '1'
					BEGIN
						SELECT @MONTH =''
						SELECT @DAY = FullName,@stid=STypeID FROM Stock WHERE TypeID = @KTypeId
						SELECT @cefullname = E.typeid FROM Employee E WHERE E.TypeId = @OperatorID
						SELECT @cdfullname=fullname FROM dbo.Department WHERE typeid=@DTypeId
					END
				
				SET @BillCode = ''
				EXEC @Re=Gp_GetBillCode 9, @MONTH,@DAY,'BS',@NowDate,@stid,@BillCode output,@cdfullname,@cefullname	
				IF @Re <> 0
					RETURN -2
					
				--写入单据主表
				INSERT INTO BillIndex (AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,STypeId,CID,Rate,NTotalInMoney,NTotalMoney,NPreferenceMoney,NVIPCZMoney)
				VALUES(9999,CONVERT(varchar(10),GetDate(),120),@BillCode,9,'','','','',@ktypeid,'','f',@ETypeId,0,0,0,@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@STypeID,@cid,@rate,0,0,0,0)
				
				IF @@ROWCOUNT = 0
					RETURN -3
				ELSE
					SET @nBillId = SCOPE_IDENTITY();
		
				--插入明细表
				INSERT INTO LoseBill(BillNumberId,PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
									STypeId,NQty,ItemID,IsCombined,CargoID,MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,KTypeId,IfWx)
				SELECT	@nBillId AS BillNumberId,TypeId,abs(CountQty),GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
						@STypeID,abs(CountNQty),ItemID,IsCombined,cargoid,MUnitID,NUnitID,UnitID,MUnitRate,
						CASE when a.CountNQty=0  THEN 0 else (abs(CountQty)/abs(a.CountNQty)) END,--p.unitrate,
						abs(CountQty)/MUnitrate,@ktypeid,@IfWx
				FROM #BillMx a
				WHERE  nid > (@i-1)*150 AND nid <=@i*150
				
				UPDATE dbo.LoseBill SET ShowOrder=ID WHERE BillNumberId=@nBillID
				--修改BillIndex的TotalMoney
				SELECT @TotalQty = SUM(Qty) FROM LoseBill WHERE BillNumberId = @nBillId
				UPDATE BillIndex SET TotalQty = @TotalQty,IfWx = @IfWx WHERE BillNumberId = @nBillId
		
				--返回单据编号
				SELECT @TmpBillCode = ISNULL(BillCode,' ') FROM BillIndex WHERE BillNumberId = @nBillId	

				SET @bCodeList = @bCodeList + 'я' + @TmpBillCode

				IF NOT EXISTS(
					SELECT ConfigNo
					FROM Userconfig
					WHERE ConfigName='BillcodeCreateTime'
					AND Value=2
				)
				BEGIN
					EXEC GP_SaveBillCode_Seed	@nBillId,@NowDate,9,@BillCode
				END

				IF @@error<>0 
					BEGIN
						RETURN -2
					END 

				SET @i = @i + 1
				
				-- 自动生成的单据会影响草稿库存
				EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,9
			END
	END

IF @SKTypeId = ''
	UPDATE StockCheckIndex SET Pass = 1 WHERE IfWx = @IfWx
ELSE
	UPDATE StockCheckIndex SET Pass = 1 WHERE Pass = 0 AND KTypeId = @SKTypeId AND IfWx = @IfWx

SET @bcode = @bCodeList

SELECT @autocount=COUNT(*)
FROM #BillMx

RETURN 0

--删除临时表
DROP TABLE #GoodsStocks,#Result,#GetManPTypeId,#GetManKTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_StockCheckMachineFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_StockCheckMachineFile]
GO





















/*
	作者：徐辉
	日期：2007-03-29
	描述：盘点机生成盘点文件导入数据库生成盘点单草稿
	GP_StockCheckMachineFile '00001','a~tiaoma~3|a~TMab~3|d~aaa~3|f~fjig~3|a~123~3|c~456321~1|a~changhong~5|a~dfd~5|a~chang4354hong~5|a~changddfshong~5','','',''
	
*/

CREATE           PROCEDURE GP_StockCheckMachineFile(
	@OperateId	varchar(100),
	@FileStr	Ntext,		--盘点文件字符串
	@NotExit	varchar(1000) OUTPUT,
	@TooMuch	varchar(1000) OUTPUT,
	@ReturnBillCode	varchar(1000) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF


--生成临时表保存text字段
CREATE TABLE #TmpFileStrTable (	
	FileStr 	NTEXT
)
INSERT INTO #TmpFileStrTable VALUES(@FileStr)


--第一次拆分后的保存临时表
CREATE TABLE  #TmpBill(
	CId		int,
	KUserCode 	varchar(200),
	PEntryCode	varchar(200),
	PQty		 NUMERIC(24, 10) 
)
	
DECLARE @i int
DECLARE @k int
DECLARE @j int
DECLARE @StrLen int
DECLARE @Row int
DECLARE @KUserCode varchar(200)
DECLARE @PEntryCode varchar(200)
DECLARE @PQty  NUMERIC(24, 10) 
DECLARE @tempRowstr varchar(1000)

SET @k=1
SET @j=1 --"|"定位标志

--字符串长度（text字段）
SELECT @StrLen=DATALENGTH(FileStr) FROM #TmpFileStrTable
SELECT @i=PATINDEX('%|%',SUBSTRING(FileStr,@j,DATALENGTH(FileStr))) FROM #TmpFileStrTable

WHIlE @j<@StrLen AND @i>0
BEGIN
	SELECT @tempRowstr=SUBSTRING(FileStr,@j,PATINDEX('%|%',SUBSTRING(FileStr,@j,DATALENGTH(FileStr)))-1) FROM #TmpFileStrTable
	
	SET @j = @j + LEN(@tempRowstr)+1
	
	--仓库编号 
	SET @KUserCode=SUBSTRING(@tempRowstr,0,CHARINDEX('~',@tempRowstr))
	
	SET @tempRowstr=SUBSTRING(@tempRowstr,CHARINDEX('~',@tempRowstr)+1,DATALENGTH(@tempRowstr))
	
	--商品条码
	SET @PEntryCode=SUBSTRING(@tempRowstr,0,CHARINDEX('~',@tempRowstr))
	
	--商品数量
	SELECT @PQty=CAST(SUBSTRING(@tempRowstr,CHARINDEX('~',@tempRowstr)+1,DATALENGTH(@tempRowstr)) AS  NUMERIC(24, 10) )
	
	INSERT INTO #TmpBill VALUES(@k,@KUserCode,@PEntryCode,@PQty)

	SELECT @i=PATINDEX('%|%',SUBSTRING(FileStr,@j,DATALENGTH(FileStr))) FROM #TmpFileStrTable

	SET @k=@k+1
END


--最后一条记录
SELECT @tempRowstr=SUBSTRING(FileStr,@j,@StrLen-@j+1) FROM #TmpFileStrTable

--仓库编号 
SET @KUserCode=SUBSTRING(@tempRowstr,0,CHARINDEX('~',@tempRowstr))

	
SET @tempRowstr=SUBSTRING(@tempRowstr,CHARINDEX('~',@tempRowstr)+1,DATALENGTH(@tempRowstr))

--商品条码
SET @PEntryCode=SUBSTRING(@tempRowstr,0,CHARINDEX('~',@tempRowstr))

--商品数量
SELECT @PQty=CAST(SUBSTRING(@tempRowstr,CHARINDEX('~',@tempRowstr)+1,DATALENGTH(@tempRowstr)) AS  NUMERIC(24, 10) )	

	
--写入最后一条记录
INSERT INTO #TmpBill VALUES(@k,@KUserCode,@PEntryCode,@PQty)

SELECT DISTINCT a.KUserCode,a.PEntryCode  INTO #TempRow  FROM #TmpBill a

SELECT @Row=COUNT(*) FROM #TempRow

--有相同的商品数据行，不处理，返回
IF @Row<>@k
	RETURN -1

DROP TABLE #TempRow

SELECT a.*,p.deleted,p.sonnum,CountRow=(SELECT COUNT(EntryCode) FROM Ptype WHERE EntryCode=a.PEntryCode) INTO #TempTableNew FROM #TmpBill a 
	LEFT JOIN Ptype p
	ON a.PEntryCode=p.EntryCode
	WHERE p.isservice=0

--删除临时表
DROP TABLE #TmpBill


--得到非叶子节点，停用数据
SELECT 
	T.KUserCode,T.PEntryCode,T.PQty,2 AS Flag
INTO
	#TempNotValid
FROM 
	#TempTableNew T
WHERE
	T.Deleted<>0 OR T.SonNum <> 0

--过滤停用，非叶子节点商品
SELECT T.* INTO #TempTable FROM #TempTableNew T WHERE (T.Deleted=0 AND T.SonNum = 0) OR (T.Deleted is null AND T.SonNum is null)

DROP TABLE #TempTableNew

--得到有效的数据
SELECT 
	P.TypeId,T.KUserCode,T.PQty
INTO
	#TempValid
FROM 
	#TempTable T
LEFT JOIN 
	Ptype p
ON 
	T.PEntryCode=p.EntryCode
WHERE
	T.CountRow=1 AND p.isservice=0

--得到没有这个条码的商品
SELECT 
	T.KUserCode,T.PEntryCode,T.PQty,0 AS Flag
INTO
	#TempNotExist
FROM 
	#TempTable T
LEFT JOIN 
	Ptype p
ON 
	T.PEntryCode=p.EntryCode
WHERE
	T.CountRow=0

--得到该条码有对应两个或者以上的商品
SELECT 
	T.KUserCode,T.PEntryCode,T.PQty,2 AS Flag
INTO
	#TempTooMuch
FROM 
	#TempTable T
LEFT JOIN 
	Ptype p
ON 
	T.PEntryCode=p.EntryCode
WHERE
	T.CountRow>=2

--删除临时表
DROP TABLE #TempTable

--得到盘点仓库
SELECT
	DISTINCT T.KUserCode,S.TypeId AS KTypeId
INTO
	#TempStock
FROM
	#TempValid T
LEFT JOIN
	Stock S
ON
	T.KUserCode=S.UserCode

DECLARE
	@NowDate DATETIME

SELECT @NowDate=GETDATE()

--声明仓库游标
DECLARE KTypeIDCursor CURSOR FOR SELECT KTypeId,KUserCode FROM #TempStock

DECLARE @BillCodeConfig varchar(1)
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置

DECLARE @KtypeId varchar(100)
DECLARE @StockUserCode varchar(300)
DECLARE @PTypeIDCursorCount int, @BillNum int,@BillCode varchar(300),@StockCheckID int,
	@Day varchar(50),@Month varchar(50),@Year varchar(50)
DECLARE @PtypeId varchar(100),@CargoSpace varchar(200)

DECLARE @stockqty  NUMERIC(24, 10) 

--生成盘点单草稿单据编号
--DECLARE @ReturnBillCode	varchar(1000)
SELECT @ReturnBillCode = ''

DECLARE
	@STypeid VARCHAR(100)
	

DECLARE @TypeID varchar(100),@Qty  NUMERIC(24, 10) 
SET NOCOUNT ON	-- 返回结果不受影响
OPEN KTypeIDCursor	-- 打开游标
--循环游标到指定位置
FETCH NEXT FROM KTypeIDCursor INTO @KtypeId,@StockUserCode
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
	--计数器
	SELECT @PTypeIDCursorCount = 1
	
	SELECT @STypeid=STypeID
	FROM Stock
	WHERE typeId=@KTypeID
	DECLARE @defaultCargoId INT
	SET @defaultCargoId=null
	
	IF EXISTS(SELECT  TOP 1 1 FROM Userconfig  Where ConfigName='mngcargospace' AND Value=0)
	 SELECT  @defaultCargoId=CargoID FROM CargoType WHERE KtypeID=@KTypeID
	
	--声明商品游标
	DECLARE PTypeIDCursor CURSOR FOR SELECT P.TypeId,P.PQty FROM #TempValid P WHERE P.KUserCode=@StockUserCode
	OPEN PTypeIDCursor
	FETCH NEXT FROM PTypeIDCursor INTO @PtypeId,@PQty
	WHILE ( @@FETCH_STATUS = 0 )
	BEGIN
		
	
		IF @PTypeIDCursorCount=1 OR (@PTypeIDCursorCount%150) = 1
		BEGIN
			SELECT @StockCheckID=ISNULL(MAX(StockCheckID),0)  FROM StockCheckIndex
			SELECT @StockCheckID=@StockCheckID+1
			IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =306 ) AND @BillCodeConfig='1' --单据编号自定义
			BEGIN
				SELECT @Month = ''
				SELECT @Day = FullName FROM stock WHERE TypeId = @KtypeId
				SELECT @Year=YEAR(GETDATE())
			END
			ELSE
			BEGIN
				SELECT @Month=Month(GETDATE())
				SELECT @Day=DAY(GETDATE())
				SELECT @Year=YEAR(GETDATE())
			END
			--需要调整，盘点单自定义单据编号
			EXEC Gp_GetBillCode 306,@Month,@Day,'PM', @NowDate,@STypeid,@BillCode OutPut

			

			SELECT @Month=Month(GETDATE())
			SELECT @Day=DAY(GETDATE())
			IF @ReturnBillCode=''
				SELECT @ReturnBillCode = @BillCode
			ELSE
				SELECT @ReturnBillCode = @ReturnBillCode + '||'+ @BillCode
			INSERT INTO StockCheckIndex(StockCheckID,BillDate,BillCode,ETypeID,KTypeID,Comment) 
			VALUES(@StockCheckID,@Year+'-'+@Month+'-'+@Day,@BillCode,'',@KtypeId,'盘点机数据导入生成')

			IF NOT EXISTS(
				SELECT ConfigNo
				FROM Userconfig
				WHERE ConfigName='BillcodeCreateTime'
				AND Value=2
			)
			BEGIN
				EXEC GP_SaveBillCode_Seed	@StockCheckID,@NowDate,306,@BillCode
			END

		END

		IF @KtypeId<>'' AND @PTypeID<>''
		BEGIN
			SELECT @stockQty=SUM(qty)
			FROM goodsstocks
			WHERE PTypeID=@PTypeID AND KTypeID=@KTypeID
		END
        --SELECT @CargoSpace=ISNULL(FullName,'') FROM CargoSpace WHERE PTypeID=@PtypeId AND ktypeid=@KtypeId
		SELECT @stockQty=ISNULL(@stockQty,0)
           
		INSERT INTO StockCheck (StockCheckID,PtypeID,Qty,goodscostprice,StockQty,CargoID,ItemID,IsCombined) 
		values (@StockCheckID,@PtypeId,ISNULL(@PQty,0),-1,@stockqty,@defaultCargoId,0,0)
		SELECT @PTypeIDCursorCount = @PTypeIDCursorCount + 1
		
		UPDATE dbo.StockCheck SET ShowOrder=ID WHERE StockCheckID=@StockCheckID
		FETCH NEXT FROM PTypeIDCursor INTO @PtypeId,@PQty
	END
	CLOSE PTypeIDCursor		-- 关闭游标
	DEALLOCATE PTypeIDCursor	-- 释放游标所使用的资源
	FETCH NEXT FROM KTypeIDCursor INTO @KtypeId,@StockUserCode
END
CLOSE KTypeIDCursor		-- 关闭游标
DEALLOCATE KTypeIDCursor	-- 释放游标所使用的资源

--释放临时表
DROP TABLE #TempValid
DROP TABLE #TempStock

--返回标志
DECLARE @ExistAndMuch int
SET @ExistAndMuch=0
SELECT @ExistAndMuch=COUNT(*) FROM #TempNotValid
SELECT @ExistAndMuch=COUNT(*)+@ExistAndMuch FROM #TempNotExist
SELECT @ExistAndMuch=COUNT(*)+@ExistAndMuch FROM #TempTooMuch


SELECT * FROM #TempNotValid
UNION
SELECT * FROM #TempNotExist
UNION
SELECT * FROM #TempTooMuch


DROP TABLE #TempNotValid
DROP TABLE #TempNotExist
DROP TABLE #TempTooMuch





		




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StockCheckSerialHzBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StockCheckSerialHzBill]
GO







/*
	作者：谢吉康
	日期：2009-06-02
	描述：盘点历史库存
-----------------------------------------------------
	Author:		Wang Wei 
	Datetiem:	2010-7-30
	Description:	优化
	库存金额取的是当前仓库+商品的总成本，然后平均
*/
CREATE    PROCEDURE Gp_StockCheckSerialHzBill   --------从StockCheckIndex表得到StockCheck的所有内容(应用在库存盘点)
(
	@OperatorID 	varchar(100),       		-- 操作员id
	@KtypeId 		varchar(100)='',         	-- 仓库ID
	@EndDatePoint	datetime='',				-- 盘点日期		
	@UserCode 		varchar(100)='',			-- 商品编号
	@FullName 		varchar(100)='',			-- 商品名称
	@Flag			int,						-- 1.全部商品  2.盘盈商品  3.盘亏商品
	@StypeId		VARCHAR(MAX),
	@SerialCheck	INT=1						--序列号盘点汇总
	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM dbo.F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorID)



--商品
CREATE TABLE #GetManPTypeAll
(
	TypeId		VARCHAR(100),
	UserCode 	VARCHAR(100),
	fullname 	VARCHAR(100),
	SonNum		NUMERIC(9,0),
	Deleted		INT
)
INSERT INTO #GetManPTypeAll SELECT TypeId,UserCode,fullname,SonNum,Deleted FROM  PType
/**/

DECLARE @costing int  --当前系统的成本算法

SELECT @costing=subvalue FROM sysdata WHERE subname='costing'

/*BEGIN
取未处理的盘点单中的盘点数据，
根据批次不同分开盘点
*/

CREATE TABLE #stockDetail(
	Serial			VARCHAR(max),
	StockCheckSerial VARCHAR(max),
	KtypeID			VARCHAR(100),
	PTypeID			VARCHAR(100),
	GoodsCostPrice	 NUMERIC(24, 10) ,
	GoodsNumber		VARCHAR(100) DEFAULT(''),
	ProduceDate		VARCHAR(100),
	ValidDate		VARCHAR(100),
	SQty			 NUMERIC(24, 10) ,
	StockCheckID	INT,
	qty				 NUMERIC(24, 10) ,
	newNO			VARCHAR(3000),
	CargoID			INT,
	ItemID			INT,
	IsCombined		INT,
	nqty			 NUMERIC(24, 10) ,
	snqty			 NUMERIC(24, 10) 
)
DECLARE @SQL VARCHAR(MAX)
SET @SQL='
	INSERT INTO #stockDetail
	SELECT	B.Serial,B.StockCheckSerial,D.KTypeID,B.PTypeId,B.GoodsCostPrice,B.GoodsNumber,B.ProduceDate,B.ValidDate,StockQty as sqty,D.StockCheckID, 
			B.qty,'
IF	@costing=0 
	SET @SQL=@SQL+'(D.KTypeID+B.PTypeID+CAST(ISNULL(B.CargoID,0) as VARCHAR)+cast(ISNULL(B.IsCombined,0) as varchar)+cAST(b.ItemID as varchar)+CONVERT(VARCHAR(MAX),B.GoodsNumber)+CONVERT(VARCHAR(MAX),B.ProduceDate)+CONVERT(VARCHAR(MAX),B.ValidDate)) as newNo, '	
ELSE
	SET @SQL=@SQL+'(D.KTypeID+B.PTypeID+CAST(ISNULL(B.CargoID,0) as VARCHAR)+cast(ISNULL(B.IsCombined,0) as varchar)+cAST(b.ItemID as varchar)+CONVERT(VARCHAR(MAX),B.goodscostprice)+CONVERT(VARCHAR(MAX),B.GoodsNumber)+CONVERT(VARCHAR(MAX),B.ProduceDate)+CONVERT(VARCHAR(MAX),B.ValidDate)) as newNo, '	

SET @SQL=@SQL+'b.CargoID,b.ItemID,b.IsCombined,B.nqty,StocknQty as snqty'
SET @SQL=@SQL+'
	FROM	StockCheckIndex D
			INNER JOIN 	StockCheck B	ON B.StockCheckID=D.StockCheckID 
			inner join (SELECT DISTINCT typeid FROM #GetManKTypeId) k1 on k1.typeid=d.ktypeid
			'  
	
SET @SQL=@SQL+' 
	WHERE	B.Qty IS NOT NULL AND D.Pass <> 1 AND D.SerialCheck='+CAST(@SerialCheck As VARCHAR(10))	

print @SQL
EXEC(@SQL)
--SELECT * FROM #stockDetail
---	return 

/*End*/

CREATE TABLE #GoodsStocks
(
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) ,
	CostPrice	 NUMERIC(24, 10) ,
	--cargoid		INT,
	--IsCombined	INT,
	--ItemID		INT,
	--GoodsNumber	 varchar(300)
)
DECLARE @stockSql NVARCHAR(MAX)
SEt @stockSql='	
INSERT INTO #GoodsStocks
	(
		PTypeId,
		Qty,
		CostTotal,
		CostPrice
			
	)
SELECT	ptypeid,
		ISNULL(SUM(G.Qty),0) AS Qty,
		ISNULL(SUM(G.CostTotal),0) AS CostTotal,
		CASE ISNULL(SUM(G.Qty),0) 
			WHEN 0 THEN 0 
			ELSE ROUND(CAST(ISNULL(SUM(G.CostTotal),0) AS  NUMERIC(24, 10) )/CAST(ISNULL(SUM(G.Qty),0) AS  NUMERIC(24, 10) ),4) 
		END Price
FROM	(
		SELECT	ptypeid,
				SUM(qty) as qty,
				SUM(Total) as CostTotal
		FROM	GoodsStocks a 
				inner  join #GetManKTypeId  b on a.ktypeid=b.typeid 
		WHERE	KTypeId <> ''10000''
				
		Group by PtypeId
		UNION ALL  
		SELECT typeid,0 as qty,0 as CostTotal FROM ptype  WHERE sonnum=0
		)G
group by G.ptypeid'


PRINT @stockSql
EXEC  sp_executesql @stockSql


Create TABLE  #Result(
	Serial		VARCHAR(max),
	StockCheckSerial VARCHAR(max),
	typeid		varchar(500),
	CostPrice	NUMERIC(24,10),
	StockCheckId	NUMERIC(18,0),
	qty				 NUMERIC(24, 10) ,
	QtyMoney	 NUMERIC(24, 10) ,
	countmoney	 NUMERIC(24, 10) ,
	checkqty	 NUMERIC(24, 10) ,
	BillCode	varchar(200),
	CountQty	 NUMERIC(24, 10) ,
	nQty		 NUMERIC(24, 10) ,
	checkNqty	 NUMERIC(24, 10) ,
	CountnQty	 NUMERIC(24, 10) ,
	ItemID		int,
	IsCombined	int,
	cargoid		int,
	GoodsNumber	VARCHAR(500) DEFAULT(''),
	ProduceDate varchar(50) DEFAULT (''),
	ValidDate varchar(50) DEFAULT (''),
	nid			INT identity(1,1)
)

DECLARE @selectSql NVARCHAR(MAX)


--正式查询数据
SET @selectSql=' INSERT INTO #Result( Serial,StockCheckSerial,typeid,CostPrice,
										StockCheckId,		
									  	qty	,		
									  	QtyMoney	,
									  	countmoney,	
									  	checkqty,	
									  	BillCode,	
									  	CountQty,	
									  	nQty	,	
									  	checkNqty,	
									  	CountnQty,	
									  	ItemID	,	
									  	IsCombined	,
									  	cargoid,		
									  	GoodsNumber,ProduceDate,ValidDate)'	
SET @selectSql+='
				SELECT 	B.Serial,B.StockCheckSerial,A.TypeId,B.CostPrice,
      					B.StockCheckId,
						ISNULL(B.Qty,0) AS Qty,
						--ISNULL(B.Total,0) AS QtyMoney,
						ISNULL(ISNULL(B.Qty,0)*B.CostPrice,0) AS QtyMoney,
						--ISNULL(B.CheckTotal,0)-ISNULL(B.Total,0) AS CountMoney,
						(ISNULL(ISNULL(B.CheckQty,0)*B.CostPrice,0) - ISNULL(ISNULL(B.Qty,0)*B.CostPrice,0)) as  CountMoney,
						ISNULL(B.CheckQty,0) AS CheckQty,
						(SELECT BillCode FROM StockCheckIndex WHERE StockCheckId=b.StockCheckId AND pass=0) AS BillCode,
						ISNULL((ISNULL(b.CheckQty,0)-
							CASE B.Qty 
								WHEN NULL THEN 0 
								ELSE B.Qty END),0
							) AS CountQty,
						ISNULL(B.nQty,0) AS nQty,
						ISNULL(B.checkNqty,0) AS checkNqty,
						ISNULL((ISNULL(b.checkNqty,0)-
							CASE B.Qty 
								WHEN NULL THEN 0 
								ELSE B.nQty END),0
							) AS CountnQty,
							
							B.ItemID,
							B.IsCombined,
							B.cargoid,
							B.GoodsNumber,
							B.ProduceDate,
							B.ValidDate
				FROM 	Ptype A 
				INNER  JOIN ('
						SET @selectSql+='				
								SELECT	sd.Serial,sd.StockCheckSerial,sd.PTypeID, 
								sd.StockCheckID as StockCheckId,
								sd.SQty as Qty,
								sd.qty   as CheckQty,
								newNo,
								sd.nqty as checkNqty,
								sd.snqty as nQty,
								sd.CargoID,
								sd.ItemID,
								sd.IsCombined,
								sd.GoodsNumber,
								gs.CostPrice as costprice,
								sd.ProduceDate,
								sd.ValidDate
						FROM	#stockDetail sd
								INNER JOIN #GoodsStocks gs ON sd.PTypeID=gs.PTypeId'			
				
	
SET @selectSql+='
				)B ON A.TypeId = B.PTypeId
				WHERE  	A.SonNum=0 
						AND A.UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
						AND A.FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+' 
				ORDER BY A.UserCode'

PRINT(@selectSql)
exec (@selectSql)


DECLARE @tb table(
	fullname varchar(500),
	nid			INT
)


INSERT INTO @tb(fullname,nid)
SELECT xs.FullName,r.nid 
FROM #Result  r INNER JOIN xw_SelfData xs ON r.ItemID=xs._Id
WHERE IsCombined=0 
UNION ALL 
SELECT REPLACE(xs.FullName,'я','/') as fullname,r.nid 
FROM #Result  r INNER JOIN CustomReferenceValue xs ON r.ItemID=xs.id
WHERE IsCombined=1 

IF @Flag = 1
		SELECT a.*,cs.fullname as itemname,ct.FullName as cargospace,pu.unit,pu.nunit, pu.stockunitname as munit,
			   (a.Qty/pu.stockmunitrate)  as mqty,	
			   (a.CheckQty/pu.stockmunitrate)  as checkmqty,
			   (a.CheckQty/pu.stockmunitrate)-(a.Qty/pu.stockmunitrate) as countmqty ,
				ISNULL(aux1.fullname,'') AS auxfullname1, 
				ISNULL(aux2.fullname,'') AS auxfullname2, 
				ISNULL(aux3.fullname,'') AS auxfullname3,
				ISNULL(aux.SaleUnitRate1,0) AS auxrate1,
				ISNULL(aux.SaleUnitRate2,0) AS auxrate2,
				ISNULL(aux.SaleUnitRate3,0) AS auxrate3,
				CAST('' AS VARCHAR(100))  AS stockcauqty,
				CAST('' AS VARCHAR(100))  AS cauqty,
				CAST('' AS VARCHAR(100))  AS countcauqty 
		FROM #Result a	
			INNER JOIN F_GetPtypeUnitInfo() pu ON pu.typeid=a.TypeId
			LEFT JOIN @tb cs ON a.nid=cs.nid
			LEFT JOIN  CargoType ct ON a.CargoID=ct.CargoID
			LEFT JOIN dbo.PType_AuxiliaryUnits_Ext aux ON aux.ptypeid = a.typeid
			LEFT JOIN dbo.PType_Units aux1 ON aux1.UnitsId = aux.SaleUnitID1
			LEFT JOIN dbo.PType_Units aux2 ON aux2.UnitsId = aux.SaleUnitID2
			LEFT JOIN dbo.PType_Units aux3 ON aux3.UnitsId = aux.SaleUnitID3
ELSE IF @Flag = 2
		SELECT a.*,cs.fullname as itemname,ct.FullName as cargospace,pu.unit,pu.nunit, pu.stockunitname as munit,
			   (a.Qty/pu.stockmunitrate)  as mqty,
			   (a.CheckQty/pu.stockmunitrate)  as checkmqty	 ,
			   (a.CheckQty/pu.stockmunitrate)-(a.Qty/pu.stockmunitrate) as countmqty,
				ISNULL(aux1.fullname,'') AS auxfullname1, 
				ISNULL(aux2.fullname,'') AS auxfullname2, 
				ISNULL(aux3.fullname,'') AS auxfullname3,
				ISNULL(aux.SaleUnitRate1,0) AS auxrate1,
				ISNULL(aux.SaleUnitRate2,0) AS auxrate2,
				ISNULL(aux.SaleUnitRate3,0) AS auxrate3,
				CAST('' AS VARCHAR(100))  AS stockcauqty,
				CAST('' AS VARCHAR(100))  AS cauqty,
				CAST('' AS VARCHAR(100))  AS countcauqty 
		FROM #Result a LEFT JOIN @tb cs ON a.nid=cs.nid
						LEFT JOIN  CargoType ct ON a.CargoID=ct.CargoID
						INNER JOIN F_GetPtypeUnitInfo() pu ON pu.typeid=a.TypeId
			LEFT JOIN dbo.PType_AuxiliaryUnits_Ext aux ON aux.ptypeid = a.typeid
			LEFT JOIN dbo.PType_Units aux1 ON aux1.UnitsId = aux.SaleUnitID1
			LEFT JOIN dbo.PType_Units aux2 ON aux2.UnitsId = aux.SaleUnitID2
			LEFT JOIN dbo.PType_Units aux3 ON aux3.UnitsId = aux.SaleUnitID3
		WHERE CountQty > 0

ELSE IF @Flag = 3
		SELECT a.* ,cs.fullname as itemname ,ct.FullName as cargospace,pu.unit,pu.nunit, pu.stockunitname as munit ,
			   (a.Qty/pu.stockmunitrate)  as mqty,
			   (a.CheckQty/pu.stockmunitrate)  as checkmqty	,
			   (a.CheckQty/pu.stockmunitrate)-(a.Qty/pu.stockmunitrate)  as countmqty,
				ISNULL(aux1.fullname,'') AS auxfullname1, 
				ISNULL(aux2.fullname,'') AS auxfullname2, 
				ISNULL(aux3.fullname,'') AS auxfullname3,
				ISNULL(aux.SaleUnitRate1,0) AS auxrate1,
				ISNULL(aux.SaleUnitRate2,0) AS auxrate2,
				ISNULL(aux.SaleUnitRate3,0) AS auxrate3,
				CAST('' AS VARCHAR(100))  AS stockcauqty,
				CAST('' AS VARCHAR(100))  AS cauqty,
				CAST('' AS VARCHAR(100))  AS countcauqty 
		FROM #Result a  LEFT JOIN @tb cs ON a.nid=cs.nid
						LEFT JOIN  CargoType ct ON a.CargoID=ct.CargoID
						INNER JOIN F_GetPtypeUnitInfo() pu ON pu.typeid=a.TypeId
			LEFT JOIN dbo.PType_AuxiliaryUnits_Ext aux ON aux.ptypeid = a.typeid
			LEFT JOIN dbo.PType_Units aux1 ON aux1.UnitsId = aux.SaleUnitID1
			LEFT JOIN dbo.PType_Units aux2 ON aux2.UnitsId = aux.SaleUnitID2
			LEFT JOIN dbo.PType_Units aux3 ON aux3.UnitsId = aux.SaleUnitID3
		WHERE CountQty < 0

--删除临时表
DROP TABLE #GoodsStocks,#Result,#GetManKTypeId, #stockDetail

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_StockDisByP23]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_StockDisByP23]
GO








/*
	作者：谢吉康
	日期：2003-11-25
	描述：历史库存状况的分布数据不正确
	结果：本地测试正确
*/


CREATE     PROCEDURE GP_StockDisByP23
(
	@OperatorID 	VARCHAR(100) ,		--操作员ID
	@ntype 			INT=1,				--库存分布类别1:期初2:其他
	@parid 			VARCHAR(100),		--商品的父节点
	@EndDatePoint 	VARCHAR(10)=''		--时间点
)
--@encode$--
 AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
-------------------------------------------------------------------------------
 IF @ntype=1 --查起初库存分布
 BEGIN
	SELECT	S.Fullname AS SFullName, 
			P.FullName AS PFullName, 
			C.PTypeid, 
			C.Ktypeid, 
			C.Qty, 
			C.Total, 
			C.Price
	 FROM (
				SELECT	LEFT(g.PtypeId,len(@parid)) AS PTypeid,
						g.KtypeId, 
						SUM(g.Qty) AS Qty,
						SUM(g.Total) AS Total, 
						CAST(
							(CASE WHEN SUM(g.qty) = 0 
							THEN NULL 
							ELSE SUM(g.Total) / SUM(g.Qty) 
							END) AS Money
						) AS Price
				FROM 	dbo.iniGoodsStocks AS g,dbo.Ptype AS p
				WHERE 	LEFT(g.PtypeId,len(@parid))=@parid
						AND g.PtypeId LIKE @MPtypeid+'%'
						AND g.PtypeID=p.TypeID
						AND p.deleted=0
				GROUP BY LEFT(g.PtypeId,len(@parid)), g.KtypeId
	) C INNER JOIN dbo.PType P ON (C.PTypeid = P.Typeid) 
		INNER JOIN dbo.Stock S ON (C.KTypeid = S.typeid) 
	WHERE S.typeid LIKE @MKtypeid+'%'
 END
-------------------------------------------------------------------------------
 ELSE IF @ntype=2 --查当前库存分布
	BEGIN
		IF isdate(@EndDatePoint )=1 
	 		BEGIN
				SELECT	S.Fullname AS SFullName, 
						P.FullName AS PFullName, 
						C.PTypeid, C.Ktypeid,
						C.Qty, 
						C.Total, 
						C.Price
				FROM (
						SELECT 
							LEFT(t.PtypeId,len(@parid)) AS PTypeid, 
							t.KtypeId, 
							SUM(t.Qty) AS Qty, 
							SUM(t.Total) AS Total,
							CAST((CASE WHEN SUM(t.qty) = 0 THEN NULL ELSE SUM(t.Total) / SUM(t.Qty) END)  AS Money) AS Price
				        FROM (
								SELECT 	ptypeid,
										ktypeid,
										SUM(qty) AS qty,
										SUM(total) AS total 
								FROM 	inigoodsstocks
								WHERE 	PTypeID LIKE @parID + '%'
								GROUP BY
										PTypeID,
										KTypeID
								UNION ALL
								SELECT 	ptypeid,
										ktypeid,
										SUM(qty) AS qty,
										SUM(total) AS total 
								FROM 	iniCommissionStock
								WHERE 	PTypeID LIKE @parID + '%'
										AND Type = 144
								GROUP BY
										PTypeID,
										KTypeID
	             				UNION ALL
	     						SELECT 	ptypeid,
										ktypeid,
										SUM(qty) AS qty,
										SUM(CostTotal) AS Total 
								FROM 	inoutstocktable 
								WHERE 	KTypeID<>'10000' 
										AND Billdate<=@EndDatePoint
										AND PTypeID LIKE @parID + '%'
								GROUP BY 	ptypeid,
											ktypeid
							) t 
						WHERE 	LEFT(t.PtypeId,len(@parid))=@parid  
								AND t.PtypeId LIKE @MPtypeid+'%'  
						GROUP BY LEFT(t.PtypeId,len(@parid)), t.KtypeId
					) C 
				INNER JOIN		dbo.PType P ON (C.PTypeid = P.Typeid AND p.Deleted=0) 
				INNER JOIN		dbo.Stock S ON (C.KTypeid = S.typeid)  
				WHERE S.typeid LIKE @MKtypeid+'%'
			END
		ELSE--------------------------------------------------
			BEGIN
				SELECT	S.Fullname AS SFullName, 
						P.FullName AS PFullName, 
						C.PTypeid, 
						C.Ktypeid, 
						C.Qty, 
						C.Total, 
						C.Price
			     FROM (
						SELECT	LEFT(g.PtypeId,len(@parid)) AS PTypeid, 
								g.KtypeId, 
								SUM(g.Qty) AS Qty, 
								SUM(g.Total) AS Total, 
								CAST((CASE WHEN SUM(g.qty) = 0 THEN NULL ELSE SUM(g.Total) / SUM(g.Qty) END)   AS Money) AS Price
			        	FROM 	dbo.GoodsStocks AS g,dbo.Ptype AS p
						WHERE 	LEFT(g.PtypeId,len(@parid))=@parid  
								AND g.PtypeId LIKE @MPtypeid+'%'
								AND g.PtypeID=p.TypeID
								AND p.deleted=0
			        	GROUP BY LEFT(g.PtypeId,len(@parid)), g.KtypeId
				) C 
				INNER JOIN	dbo.PType P ON (C.PTypeid = P.Typeid AND p.deleted=0) 
				INNER JOIN	dbo.Stock S ON (C.KTypeid = S.typeid)  
				WHERE S.typeid LIKE @MKtypeid+'%'
			END
 END















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_StockDisByP23_Ini]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_StockDisByP23_Ini]
GO















/*
	-- 维修品库存期初、库存期初的分布 cqhua 2009-11-04
*/


CREATE      PROCEDURE GP_StockDisByP23_Ini
(
 @OperatorID 	VARCHAR(100) ,		--操作员ID
 @ntype 		INT=1,				--库存分布类别1:维修期初2:
 @parid 		VARCHAR(100),		--商品的父节点
 @EndDatePoint 	VARCHAR(10)='',		--时间点
 @stypeid		VARCHAR(MAX)
)
--@encode$--
 AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	
	
CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))


INSERT INTO #Ptype(typeid) select P.typeid from ptype P, F_GetManDetailPType(@OperatorID) W WHERE P.typeid=W.typeid
INSERT INTO #Ktype(typeid) 
select K.typeid 
FROM Stock K, 
	 F_GetManDetailKTypeSType(@OperatorID) W
WHERE K.typeid=W.typeid 

DECLARE @SQL NVARCHAR(4000)
-------------------------------------------------------------------------------
 IF @ntype=1 --查起初库存分布
 BEGIN

SET @SQL='  SELECT  LEFT(g.PtypeId,len('''+@parid+''')) AS PTypeid,
					g.KtypeId, 
					SUM(g.Qty) AS Qty,
					SUM(g.Total) AS Total, 
					CAST((CASE WHEN SUM(g.qty) = 0 
						THEN NULL 
						ELSE SUM(g.Total) / SUM(g.Qty) 
						END) AS Money
					) AS Price
					FROM dbo.iniGoodsStocks AS g
			             INNER JOIN dbo.Ptype AS p ON LEFT(g.PtypeId,len('''+@parid+'''))='''+@parid+''' '

         IF NOT (@parid ='00000' AND @MPtypeid = '00000')
         SET @SQL=@SQL+' INNER JOIN #Ptype P1 ON g.PtypeId=P1.typeid '
         IF NOT (@MKtypeid = '00000')
         SET @SQL=@SQL+' INNER JOIN #Ktype K  ON g.KTypeid = K.typeid '

		 SET @SQL=@SQL+' WHERE g.PtypeID=p.TypeID
							   GROUP BY LEFT(g.PtypeId,len('''+@parid+''')), g.KtypeId '
      EXEC(@SQL)
END
ELSE IF @ntype=2 --查维修品库存期初分布
 BEGIN
   SET @SQL='  SELECT   LEFT(g.PtypeId,len('''+@parid+''')) AS PTypeid,
						g.KtypeId, 
						SUM(g.Qty) AS Qty,
						SUM(g.Total) AS Total, 
						CAST(
							(CASE WHEN SUM(g.qty) = 0 
							THEN NULL 
							ELSE SUM(g.Total) / SUM(g.Qty) 
							END) AS Money
						) AS Price
					FROM Wx_iniGoodsStocks AS g 
                      	INNER JOIN dbo.Ptype AS p  ON LEFT(g.PtypeId,len('''+@parid+'''))='''+@parid +''''

        IF NOT (@parid ='00000' AND @MPtypeid = '00000')
		SET @SQL=@SQL+' INNER JOIN #Ptype P1 ON g.PtypeId=P1.typeid '

        IF NOT (@MKtypeid = '00000')
        SET @SQL=@SQL+' INNER JOIN #Ktype K  ON g.KTypeid = k.typeid '

		SET @SQL=@SQL+' WHERE g.PtypeID=p.TypeID
						      GROUP BY LEFT(g.PtypeId,len('''+@parid+''')), g.KtypeId '
        EXEC(@SQL)
END
ELSE IF @ntype=3 --实物库存期初分布
BEGIN
SET @SQL='  SELECT   LEFT(g.PtypeId,len('''+@parid+''')) AS PTypeid,
						g.KtypeId, 
						SUM(g.Qty) AS Qty						
					FROM IniFactStocks AS g 
                      	INNER JOIN dbo.Ptype AS p  ON LEFT(g.PtypeId,len('''+@parid+'''))='''+@parid +''''

        IF NOT (@parid ='00000' AND @MPtypeid = '00000')
		SET @SQL=@SQL+' INNER JOIN #Ptype P1 ON g.PtypeId=P1.typeid '

        IF NOT (@MKtypeid = '00000')
        SET @SQL=@SQL+' INNER JOIN #Ktype K  ON g.KTypeid = k.typeid '

		SET @SQL=@SQL+' WHERE g.PtypeID=p.TypeID
						      GROUP BY LEFT(g.PtypeId,len('''+@parid+''')), g.KtypeId '
        EXEC(@SQL)
END

DROP TABLE #Ptype,#Ktype,#GetSelectSTypeId











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StockGoodsOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StockGoodsOrder]
GO





/*
	作者：谢吉康
	日期：2007-04-26
	描述：增加效期等
*/
CREATE  PROCEDURE Gp_StockGoodsOrder
(
	@OperatorID        		varchar(100) ,                 --------------------------操作员ID
	@Ktypeid              	varchar(8000),                  --------------------------仓库ID号
	@parid                  varchar(8000),                   ---------------------------商品的父节点
	@stypeid				VARCHAR(MAX)
)
--@encode$--
 AS
set nocount on
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DECLARE @costing int 

SELECT @costing=SubValue  FROM dbo.sysdata WHERE SubName='costing'

IF @costing = 1 OR @costing = 2 OR @costing = 3--先进先出，后进先出 手工指定
    BEGIN
		SELECT  
			S.Fullname AS SFullName ,
			P.FullName AS PFullName ,
			LEFT(a.PtypeId, LEN(@parid)) AS PTypeid ,
			a.KtypeId ,
			a.Qty ,
			a.qty * Price AS total ,
			Price ,
			GoodsOrder ,
			a.GoodsNumber ,
			a.ProduceDate ,
			a.ValidDate,
			B.LockNumber
		FROM GoodsStocks a
		LEFT JOIN (SELECT PtypeId,KtypeId,SUM(LockNumber) LockNumber,GoodsNumber FROM dbo.GOODSSTOCKS_QTY GROUP BY PtypeId,KtypeId,GoodsNumber) B ON B.PtypeId=A.PtypeId AND B.KtypeId=A.KtypeId AND B.GoodsNumber=A.GoodsNumber
		INNER JOIN F_GetManDetailPType(@OperatorID) FP ON FP.TypeId=A.PtypeId
		INNER JOIN F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) FK ON FK.TypeId=A.KtypeId
		INNER JOIN PType P ON a.PTypeid = P.Typeid
		INNER JOIN Stock S ON a.KTypeid = S.typeid
		INNER JOIN #GetSelectSTypeId ss ON ss.TypeId = s.STypeID
		WHERE   
			LEFT(a.PtypeId,LEN(@parid)) = @parid

    END
ELSE---移动加权
    BEGIN
		SELECT  
			S.Fullname AS SFullName ,
			P.FullName AS PFullName ,
			C.PTypeid ,
			C.Ktypeid ,
			C.Qty ,
			C.Total ,
			C.Price ,
			C.GoodsOrder ,
			C.GoodsNumber ,
			C.ProduceDate ,
			C.ValidDate,
			c.LockNumber
		FROM ( 
			SELECT 
				LEFT(a.PtypeId, LEN(@parid)) AS PTypeid ,
				a.KtypeId ,
				a.Qty ,
				a.qty * Price AS total ,
				Price ,
				GoodsOrder ,
				a.GoodsNumber ,
				a.ProduceDate ,
				a.ValidDate,
				a.LockNumber
			FROM  GOODSSTOCKS_QTY a
			INNER JOIN F_GetManDetailPType(@OperatorID) FP ON FP.TypeId=A.PtypeId
			INNER JOIN GoodsStocks b ON a.KTypeID = b.KtypeId AND a.PTypeID = b.PtypeId
			INNER JOIN F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) FK ON FK.TypeId=A.KtypeId
			WHERE     
				LEFT(a.PtypeId, LEN(@parid)) = @parid
		) C
		INNER JOIN PType P ON ( C.PTypeid = P.Typeid )
		INNER JOIN Stock S ON ( C.KTypeid = S.typeid )
		INNER JOIN #GetSelectSTypeId ss ON ss.TypeId = s.STypeID
		ORDER BY GoodsOrder
    END

DROP TABLE #GetSelectSTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_StockInOroutSaveIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_StockInOroutSaveIndex]
GO


/*
实物库存期初入出/库单保存
2016-07-16
*/
CREATE   PROCEDURE GP_StockInOroutSaveIndex
(
	@billnumberid	NUMERIC(18,0),	
	@billtype		varchar(20),
	@billdate		varchar(20),
	@billcode		varchar(50),
	@stypeid		varchar(50),
	@etypeid		VARCHAR(50),
	@dtypeid		VARCHAR(50),
	@ktypeid		VARCHAR(50),
	@ktypeid2		VARCHAR(50),
	@comment		varchar(256),
	@explain		varchar(50),
	@isini			INT,
	@entryCode		varchar(500),
	@draft			INT,
	@updateE		VARCHAR(500),
	@checke			VARCHAR(500),
	@frombilltype	INT,
	@totalqty       NUMERIC(24,10),
	@ifcargo int
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @intReturn		BIGINT

DECLARE @BeginDate DATETIME 

SELECT TOP 1
        @BeginDate = startdate
FROM    monthproc
WHERE   MonthNo='本期' AND STypeID=@STypeID
IF @BillDate < @BeginDate
    AND @isini = 0 AND @BillType<>310 
    BEGIN 
        RETURN -2
    END

--如果没有billcode就插入
IF @billnumberid = -1
BEGIN
	insert into FactIndex
	(
		BillDate,
		BillCode,
		OtherType,
		billtype,
		Stypeid,
		dtypeId,
		etypeid,
		ktypeid,
		ktypeid2,	
		ifcheck,
		checke,
		checkTime,
		RedWord,
		RedReason,
		draft,
		totalqty,
		IsIni,
		EntryCode,
		Comment,
		explain,
		updateE,
		DealBTypeID,
		LastUpdateTime,
		Poster,
		PostTime,
		frombilltype,
		ifcargo
	)
	VALUES
	(
		@billdate,
		@billcode,
		@billtype,
		@billtype,
		@stypeid,
		@dtypeid,
		@etypeid,
		@ktypeid,
		@ktypeid2,
		'f',
		@checke,
		GETDATE(),
		0,
		NULL,
		@draft,
		@totalqty,
		@isini,
		NULL,
		@comment,
		@explain,
		NULL,
		NULL,
		NULL,
		NULL,
		NULL,
		@frombilltype,
		@ifcargo
	)

	SET @intReturn = SCOPE_IDENTITY();
	
	RETURN @intReturn;
END 
ELSE
--更新操作
BEGIN
	UPDATE	FactIndex 
	SET		BillDate	=	@billdate,
	        BillCode    =   @billcode,
			Stypeid		=	@stypeid,
			dtypeId		=	@dtypeid,
			etypeid		=	@etypeid,
			ktypeid		=	@ktypeid,
			ktypeid2	=	@ktypeid2,
			EntryCode	=	@entryCode,
			Comment		=	@comment,
			explain		=	@explain,
			updatee		=	@checke,
			LastUpdateTime=GETDATE(),
			totalqty	=   @totalqty,
			frombilltype=@frombilltype,
			ifcargo=@ifcargo 
	WHERE	BillNumberId = @billNumberId
	
	--删除自定义表头列
DELETE FROM CustomBillColumns	WHERE billnumberid=@BillNumberId AND BillType=@BillType
--删除自定义明细列
DELETE FROM CustomBillDetailColumns WHERE billnumberid=@BillNumberId AND BillType=@BillType
DELETE FROM dbo.Custom_BillDetails WHERE BillId=@BillNumberID AND BillType=@BillType
DELETE FROM dbo.Custom_BillIndex WHERE BillId=@BillNumberID AND BillType=@BillType
	
	IF @BillType IN(418,419)
	BEGIN
		DECLARE		@GoodsBillNumberID INT,					/*出库单单据编号*/
					@GoodsBillType     INT,					/*出库单单据类型*/
					@RowIndex          INT,					
					@RowCount          INT					/*运输单明细行数*/
		DECLARE	    @Tmp			   TABLE
		(
			GoodsBillNumberID INT,
			GoodsBillType     INT,
			RowIndex          INT
		)
		
		INSERT INTO @Tmp(GoodsBillNumberID,GoodsBillType,RowIndex)
		SELECT 
			   FromBillNumberID,
			   FromBillType,
			   ROW_NUMBER() OVER(ORDER BY GETDATE())
		FROM dbo.FactDepotInOut 
		WHERE billNumberID=@BillNumberID	AND FromBillNumberID>0 AND FromBillType>0
		--删除明细数据
		DELETE FROM FactDepotInOut WHERE BillNumberID = @billnumberid
		
		SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
		/*仓库入库单*/
		IF @BillType=418
		BEGIN
			WHILE(@RowIndex<=@RowCount)
			BEGIN
				SELECT @GoodsBillNumberID=GoodsBillNumberID,
					   @GoodsBillType=GoodsBillType
				FROM @Tmp WHERE @RowIndex=RowIndex
				
				IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId AND b.RedWord=0 
					WHERE A.FromBillNumberID=@GoodsBillNumberID AND A.FromBillType=@GoodsBillType)
				BEGIN
					IF @GoodsBillType IN(71,72,87,88)
					BEGIN
						UPDATE dbo.LendIndex 
						SET 
							InFactRefState=0
						WHERE BillNumberId=@GoodsBillNumberID
						
					END
					ELSE
					BEGIN
						UPDATE dbo.BillIndex 
						SET 
							InFactRefState=0
						WHERE BillNumberId=@GoodsBillNumberID
					END
				END
				SET @RowIndex=@RowIndex+1
			END
			RETURN
		END
		/*仓库出库单*/
		IF @BillType=419
		BEGIN
			WHILE(@RowIndex<=@RowCount)
			BEGIN
				SELECT @GoodsBillNumberID=GoodsBillNumberID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
				
				IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId AND b.RedWord=0 
				WHERE A.FromBillNumberID=@GoodsBillNumberID AND A.FromBillType=@GoodsBillType)		
				BEGIN
					IF @GoodsBillType IN(71,72,87,88)
					BEGIN
						UPDATE dbo.LendIndex 
						SET 
							OutFactRefState=0
						WHERE BillNumberId=@GoodsBillNumberID
					END
					ELSE
					BEGIN
						UPDATE dbo.BillIndex 
						SET 
							OutFactRefState=0
						WHERE BillNumberId=@GoodsBillNumberID
					END
				END
				SET @RowIndex=@RowIndex+1
			END
			RETURN 0
		END
	END

	IF @billtype = '420'
	DELETE FROM FactDepotAllot WHERE BillNumberID = @billnumberid
	
	RETURN 0
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--select * from FactIndex order by billdate asc

--SELECT * FROM dbo.FactDepotInOut

--SELECT * FROM dbo.BillName






IF EXISTS ( SELECT TOP 1
                    1
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_StockPtypeInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROC [dbo].Gp_StockPtypeInfo;
GO
SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者:颜熙
	日期:2016-11-20
	描述:库存查询
*/
CREATE PROCEDURE Gp_StockPtypeInfo 
( 
	@ktypeid VARCHAR(50),   --仓库id
	@OperatorID	VARCHAR(100) = '' 	-- 操作员ID
)
    --@encode$--
AS
    SET NOCOUNT ON;
    BEGIN
   ----开启了货位
        --DECLARE @SQL VARCHAR(MAX);
        --IF EXISTS ( SELECT  1
        --            FROM    dbo.Userconfig
        --            WHERE   ConfigName = 'mngcargospace'
        --                    AND Value = 1 )
        --    BEGIN
        IF NOT EXISTS ( SELECT  *
                        FROM    dbo.GOODSSTOCKS_QTY
                        WHERE   KTypeID = @ktypeid )
            BEGIN
                DECLARE @Message VARCHAR(50);
                DECLARE @StockName VARCHAR(100)
                SELECT @StockName = FullName FROM stock WHERE typeId = @ktypeid
                SET @Message = '所选仓库【' + @StockName + '】无库存！';
                RAISERROR(@Message,16,1);
                RETURN;
            END;
        
        WITH    NOInventory
              AS ( SELECT   *
                   FROM     dbo.InOutstocktable
                   WHERE    PtypeId + '\' + KtypeId + '\'
                            + CAST(CargoID AS VARCHAR(50)) NOT IN (
                            SELECT  ISNULL(PTypeID + '\' + KTypeID + '\'
                                           + CAST(CargoID AS VARCHAR(50)),
                                           '')
                            FROM    dbo.GOODSSTOCKS_QTY )
                 )
            SELECT  CAST(p.Pid AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    p.Pid AS goods_erpid ,
                    qty.CargoID AS position_erpid ,
                    0 AS validqty ,
                    CT.FullName AS cargofullname ,
                    '' AS itemid ,
                    qty.CargoID AS cargoid ,
                    p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    0 AS qty ,
                    '' AS freeitem
            FROM    ptype AS p
                    INNER JOIN NOInventory AS qty ON p.typeId = qty.PtypeId
                    INNER JOIN CargoType CT ON CT.CargoID = qty.CargoID
                    INNER JOIN Stock S ON S.typeId = qty.KtypeId
                    INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = p.typeId
            WHERE   p.customitemfrom IS NULL
                    AND qty.KtypeId = @ktypeid
                    AND p.WdSyncFlag = 1
            GROUP BY p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    qty.CargoID ,
                    CT.FullName ,
                    p.Pid ,
                    S.Kid ,
                    p.baseUnitId
            UNION ALL
            SELECT  CAST(p.Pid AS VARCHAR) + '_1_' + CAST(c.id AS VARCHAR)
                    + '_' + CAST(p.baseUnitId AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    p.Pid AS goods_erpid ,
                    qty.CargoID AS position_erpid ,
                    0 AS validqty ,
                    CT.FullName AS cargofullname ,
                    c.id AS itemid ,
                    qty.CargoID AS cargoid ,
                    p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    0 AS qty ,
                    c.Fullname AS freeitem
            FROM    ptype AS p
                    INNER JOIN NOInventory AS qty ON p.typeId = qty.PtypeId
                    INNER JOIN CustomReferenceValue c ON qty.ItemID = c.id
                    INNER JOIN CargoType CT ON CT.CargoID = qty.CargoID
                    INNER JOIN Stock S ON S.typeId = qty.KtypeId
                    INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = P.typeId
            WHERE   p.customitemfrom = 1
                    AND qty.KtypeId = @ktypeid
                    AND p.WdSyncFlag = 1
            GROUP BY p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    c.Fullname ,
                    qty.CargoID ,
                    c.id ,
                    CT.FullName ,
                    p.Pid ,
                    S.Kid ,
                    p.baseUnitId
            UNION ALL
            SELECT  CAST(p.Pid AS VARCHAR) + '_0_' + CAST(_Id AS VARCHAR)
                    + '_' + CAST(p.baseUnitId AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    p.Pid AS goods_erpid ,
                    qty.CargoID AS position_erpid ,
                    0 AS validqty ,
                    CT.FullName AS cargofullname ,
                    x._Id AS itemid ,
                    qty.CargoID AS cargoid ,
                    p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    0 AS qty ,
                    x.FullName AS freeitem
            FROM    ptype AS p
                    INNER JOIN NOInventory AS qty ON p.typeId = qty.PtypeId
                    INNER JOIN xw_SelfData x ON qty.ItemID = x._Id
                    INNER JOIN CargoType CT ON CT.CargoID = qty.CargoID
                    INNER JOIN Stock S ON S.typeId = qty.KtypeId
                    INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = P.typeId
            WHERE   p.customitemfrom = 0
                    AND qty.KtypeId = @ktypeid
                    AND p.WdSyncFlag = 1
            GROUP BY p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    x.FullName ,
                    qty.CargoID ,
                    x._Id ,
                    CT.FullName ,
                    p.Pid ,
                    S.Kid ,
                    p.baseUnitId
            UNION ALL
            SELECT  CAST(p.Pid AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    p.Pid AS goods_erpid ,
                    qty.CargoID AS position_erpid ,
                    SUM(qty.Qty) AS validqty ,
                    CT.FullName AS cargofullname ,
                    '' AS itemid ,
                    qty.CargoID AS cargoid ,
                    p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    SUM(qty.Qty) AS qty ,
                    '' AS freeitem
            FROM    ptype AS p
                    INNER JOIN GOODSSTOCKS_QTY AS qty ON p.typeId = qty.PTypeID
                    INNER JOIN CargoType CT ON CT.CargoID = qty.CargoID
                    INNER JOIN Stock S ON S.typeId = qty.KTypeID
                    INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = P.typeId
            WHERE   p.customitemfrom IS NULL
                    AND qty.KTypeID = @ktypeid
                    AND p.WdSyncFlag = 1
            GROUP BY p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    qty.CargoID ,
                    CT.FullName ,
                    p.Pid ,
                    S.Kid ,
                    p.baseUnitId
            UNION ALL
            SELECT  CAST(p.Pid AS VARCHAR) + '_1_' + CAST(c.id AS VARCHAR)
                    + '_' + CAST(p.baseUnitId AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    p.Pid AS goods_erpid ,
                    qty.CargoID AS position_erpid ,
                    SUM(qty.Qty) AS validqty ,
                    CT.FullName AS cargofullname ,
                    c.id AS itemid ,
                    qty.CargoID AS cargoid ,
                    p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    SUM(qty.Qty) AS qty ,
                    c.Fullname AS freeitem
            FROM    ptype AS p
                    INNER JOIN GOODSSTOCKS_QTY AS qty ON p.typeId = qty.PTypeID
                    INNER JOIN CustomReferenceValue c ON qty.ItemID = c.id
                    INNER JOIN CargoType CT ON CT.CargoID = qty.CargoID
                    INNER JOIN Stock S ON S.typeId = qty.KTypeID
                    INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = P.typeId
            WHERE   p.customitemfrom = 1
                    AND qty.KTypeID = @ktypeid
                    AND p.WdSyncFlag = 1
            GROUP BY p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    c.Fullname ,
                    qty.CargoID ,
                    c.id ,
                    CT.FullName ,
                    p.Pid ,
                    S.Kid ,
                    p.baseUnitId
            UNION ALL
            SELECT  CAST(p.Pid AS VARCHAR) + '_0_' + CAST(_Id AS VARCHAR)
                    + '_' + CAST(p.baseUnitId AS VARCHAR) AS sku_erpid ,
                    S.Kid AS whs_erpid ,
                    p.Pid AS goods_erpid ,
                    qty.CargoID AS position_erpid ,
                    SUM(qty.Qty) AS validqty ,
                    CT.FullName AS cargofullname ,
                    x._Id AS itemid ,
                    qty.CargoID AS cargoid ,
                    p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    SUM(qty.Qty) AS qty ,
                    x.FullName AS freeitem
            FROM    ptype AS p
                    INNER JOIN GOODSSTOCKS_QTY AS qty ON p.typeId = qty.PTypeID
                    INNER JOIN xw_SelfData x ON qty.ItemID = x._Id
                    INNER JOIN CargoType CT ON CT.CargoID = qty.CargoID
                    INNER JOIN Stock S ON S.typeId = qty.KTypeID
                    INNER JOIN F_GetAllManagerBaseTypeId('',1,@OperatorID) ON F_GetAllManagerBaseTypeId.TypeId = P.typeId
            WHERE   p.customitemfrom = 0
                    AND qty.KTypeID = @ktypeid
                    AND p.WdSyncFlag = 1
            GROUP BY p.deleted ,
                    p.typeId ,
                    p.FullName ,
                    p.UserCode ,
                    x.FullName ,
                    qty.CargoID ,
                    x._Id ,
                    CT.FullName ,
                    p.Pid ,
                    S.Kid ,
                    p.baseUnitId;
    END; 
GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StockSerialCheckHzBillAutoCaoGao]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StockSerialCheckHzBillAutoCaoGao]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	描述：序列号盘点
*/               
CREATE PROCEDURE Gp_StockSerialCheckHzBillAutoCaoGao 
(
	@OperatorID 	varchar(100),       	-- 操作员id
	@chrKtypeId 		varchar(100)='',        -- 可选的商品ID
	@EndDatePoint	datetime='',			-- 盘点日期		
	@UserCode 		varchar(100)='',		-- 商品编号
	@FullName 		varchar(66)='',			-- 商品名称
	@Flag			int,					-- 1.全部商品  2.盘盈商品  3.盘亏商品
	@IfWx			int,					-- 1.维修盘点  0.正常盘点
	@bcode			varchar(8000) OUTPUT,	-- 返回单据编号列表
	@autocount 	INT OUTPUT,
	@isserialcheck	INT=1,--是否为序列号盘点0：否1：是
	@stockDetail Tb_SerialStockCheckBill READONLY
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -5
	END
END  

-- ********	判断是否试用版 - END	********
-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1


DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------
DECLARE @saveKtypeid VARCHAR(100)
SET @saveKtypeid=@chrKtypeId
--权限范围临时表
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)

DECLARE @costing int  --当前系统的成本算法
DECLARE @TmpBillCode	varchar(8000)
DECLARE @SKTypeId		varchar(1000)	--客户选的仓库
SET @SKTypeId = @chrKtypeId

SET @TmpBillCode = ''

SELECT @costing=subvalue FROM sysdata WHERE subname='costing'

-------------------------------------------------------------读表的内容-----------------------------------------------------

IF @UserCode='' SELECT @UserCode='%' ELSE SELECT @UserCode='%'+@UserCode+'%'
IF @FullName='' SELECT @FullName='%' ELSE SELECT @FullName='%'+@FullName+'%'

DECLARE @cid INT
DECLARE @rate  NUMERIC(24, 10)   
SELECT @cid= CID,@rate=Rate FROM Ac_Currency WHERe Sysrow=1

/*End*/
DECLARE @STypeID VARCHAR(100)
IF @chrKtypeId='' OR @chrKtypeId='00000' SELECT @chrKtypeId='%'

SELECT TOP 1 @STypeID=stypeid FROM stock WHERE typeId=@chrKtypeId

--正式查询数据
SELECT 	A.TypeId,
		A.usercode,
		A.fullname,
		A.unit1,
      	B.StockCheckId,
		(SELECT BillCode FROM StockCheckIndex WHERE StockCheckId=b.StockCheckId AND pass=0) AS BillCode,
		ISNULL(B.Qty,0) AS Qty,
		ISNULL(B.Total,0) AS QtyMoney,
		ISNULL(B.CheckQty,0) AS CheckQty,
		ISNULL((ISNULL(b.CheckQty,0)-
			CASE B.Qty 
				WHEN NULL THEN 0 
				ELSE B.Qty END),0
			) AS CountQty,
			
		B.GoodsCostPrice,
		B.GoodsNumber,
		B.ProduceDate,
		B.ValidDate,
		ISNULL(B.NQty,0) AS NQty,
		ISNULL(B.CheckNQty,0) AS CheckNQty,
		
		ISNULL((ISNULL(b.CheckNQty,0)-
			CASE B.NQty 
				WHEN NULL THEN 0 
				ELSE B.NQty END),0
			) AS CountNQty,
		B.CargoID,
		B.ItemID,
		B.IsCombined,
		A.StockUnitId AS MunitID,
		A.baseUnitId AS UnitID,
		A.AssistantUnitId AS NUnitID,
		e1.Rate AS MUnitrate,
		e2.Rate AS Unitrate,
		B.Serial,
		B.StockCheckSerial
INTO	#Result
FROM 	PType A 
INNER JOIN (
				SELECT	
						Serial,
						StockCheckSerial,
						PTypeID, 
						StockCheckID as StockCheckId,
						0 AS Total,
						SQty as Qty,
						qty as CheckQty,
						newNo,
						GoodsCostPrice as GoodsCostPrice,
						GoodsNumber,		
						ProduceDate	,	
						ValidDate,
						nqty as checkNqty,
						snqty as nQty,
						CargoID,
						ItemID,
						IsCombined
				FROM @stockDetail
							
)B ON A.TypeId = B.PTypeId
LEFT JOIN PType_Units_Ext e1 On (A.StockUnitId=e1.UnitsId AND A.typeId=e1.PtypeID)
LEFT JOIN PType_Units_Ext e2 On (A.AssistantUnitId=e2.UnitsId AND A.typeId=e2.PtypeID)
WHERE  	A.SonNum=0 
		AND A.Deleted=0 
		--AND A.TypeId IN (SELECT * FROM #GetManPTypeId)
		AND A.UserCode LIKE '%'+@UserCode+'%'
		AND A.FullName LIKE '%'+@FullName+'%'
ORDER BY A.UserCode

DECLARE @MONTH 				varchar(50),
		@DAY 				varchar(50),
		@BillCodeConfig		varchar(10),
		@BillCode			varchar(300),
		@Rex				int,
		@Tax				 NUMERIC(24, 10) ,
		@period				int,
		@DTypeId			varchar(200),
		@nBillId			numeric(18,0),
		@recPrice			 NUMERIC(24, 10) ,
		@preprice			 NUMERIC(24, 10) ,
		@Explain			varchar(400),
		@KTypeId			varchar(200),
		@TotalQty			 NUMERIC(24, 10) ,
		@ETypeId			varchar(200),
		@bCount				int,
		@BillCount			int,
		@i					int,
		@bCodeList			varchar(8000)

SET @Tax = 0
SET @recPrice = 0
SET @preprice = 0
SET @ETypeId = @OperatorID
SET @i = 1
SET @bCodeList = ''

IF @isserialcheck=1
	SET @Explain = '序列号库存盘点单草稿'
ELSE IF @IfWx = 0
	SET @Explain = '库存盘点单草稿'
ELSE
	SET @Explain = '维修商品库存盘点单草稿'

DECLARE @stid varchar(100)	

IF isnull(@saveKtypeid,'')='' SELECT TOP 1 @stid=stypeid FROM stock WHERE typeId='00000'
ELSE  SELECT TOP 1 @stid=stypeid FROM stock WHERE typeId=@saveKtypeid

IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '1')
	SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'

SELECT @period = period FROM MonthProc WHERE MonthNo = '本期' 
SELECT @DTypeId = D.TypeId FROM Department D,Employee E WHERE E.Department = D.FullName AND E.TypeId = @ETypeId

SET @MONTH = month(getdate())
SET @DAY = day(getdate())

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

SET @KTypeId = '00000'

IF @chrKtypeId <> ''
	BEGIN
		IF @chrKtypeId = '00000' OR @chrKtypeId = '%'
			SET @KTypeId = ''
		ELSE
			SET @KTypeId = @chrKtypeId
	END


CREATE TABLE #BillMx
(
	nid			int identity(1,1),
	TypeId		varchar(200),
	CountQty	 NUMERIC(24, 10) ,
	GoodsCostPrice		 NUMERIC(24, 10) ,
	GoodsNumber			VARCHAR(100),
	ProduceDate			VARCHAR(100),
	ValidDate			VARCHAR(100),
	CountNQty		 NUMERIC(24, 10) ,
	cargoid				INT,
	IsCombined			INT,
	ItemID				INT,
	MunitID				INT,
	UnitID				INT,
	NUnitID				INT,
	MUnitrate		 NUMERIC(24, 10) ,	
	Unitrate		 NUMERIC(24, 10) ,	
	Serial			TEXT NULL,
	StockCheckSerial TEXT NULL
)

DECLARE @BeginDate 	datetime,
		@szItem 	varchar(30),
		@szVchCode 	varchar(30),
		@szPeriod	varchar(20)

EXEC Gp_GetSubValue 'period',@stid,@szPeriod out
SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod 
IF GetDate()<@BeginDate 
	BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
		RETURN -33
	END

DECLARE
	@NowDate	DATETIME

SELECT @NowDate=GETDATE()

DECLARE @SERIAL VARCHAR(max),@STOCKCHECKSERIAL VARCHAR(max),@SerialResultBy VARCHAR(max)='',@SerialResultBs VARCHAR(max)=''


INSERT INTO #BillMx(TypeId,CountQty,GoodsCostPrice,GoodsNumber,ProduceDate,ValidDate,CountNQty,cargoid,IsCombined,ItemID,MunitID,NUnitID,UnitID,MUnitrate,Unitrate,Serial,StockCheckSerial) 
SELECT TypeId,CountQty,GoodsCostPrice,GoodsNumber,ProduceDate,ValidDate,CountNQty ,cargoid,IsCombined,ItemID,MunitID,NUnitID,UnitID,MUnitrate,CountQty/Unitrate,Serial,StockCheckSerial
FROM #Result


SELECT @bCount = COUNT(*) FROM #BillMx

IF @bCount % 150 = 0
	SET @BillCount = @bCount / 150
ELSE
	SET @BillCount = @bCount / 150 + 1

SET @MONTH = month(getdate())
SET @DAY = day(getdate())
SET @i =  1
WHILE @i<=@BillCount
	BEGIN
	   
	   
	
		SELECT @SERIAL=Serial,@STOCKCHECKSERIAL=StockCheckSerial FROM #BillMx a WHERE 
			    a.nid > (@i-1)*150 
				AND a.nid <=@i*150
			
		--筛选合并序列号
		SELECT DISTINCT @SerialResultBy=stuff((select 'я' + a from 
		(SELECT a FROM dbo.f_split(@STOCKCHECKSERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(@SERIAL,'я'))) b
		where a = a for xml path('')),1,1,'')
		FROM (SELECT a FROM dbo.f_split(@STOCKCHECKSERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(@SERIAL,'я'))) c
		
		--筛选合并序列号
		SELECT DISTINCT @SerialResultBs=stuff((select 'я' + a from 
		(SELECT a FROM dbo.f_split(@SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(@STOCKCHECKSERIAL,'я'))) b
		where a = a for xml path('')),1,1,'')
		FROM (SELECT a FROM dbo.f_split(@SERIAL,'я') WHERE a NOT IN (SELECT a FROM dbo.f_split(@STOCKCHECKSERIAL,'я'))) c
			
			
		IF(@SerialResultBy!='')--报溢单
		BEGIN
			--生成单据编号
			IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 14) AND @BillCodeConfig = '1'
				BEGIN
					SELECT @MONTH=''
					SELECT @DAY = FullName,@stid=STypeID FROM Stock WHERE TypeID = @KTypeId
				END
			
			EXEC @Re=Gp_GetBillCode 14, @MONTH,@DAY,'BY',@NowDate,@stid,@BillCode output
			
			IF @Re <> 0
				RETURN -2	
				
			SELECT @STypeID=STypeID
			FROM STOCK
			WHERE typeId=@KTypeId									
	
			--写入单据主表
			INSERT INTO BillIndex (AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,
									etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,
									period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,
									DTypeId,Explain,Stypeid,CID,Rate,NTotalInMoney,NTotalMoney,NPreferenceMoney,NVIPCZMoney)
			VALUES(9999,CONVERT(varchar(10),GetDate(),120),@BillCode,14,'','','','',@ktypeid,'','f',@ETypeId,0,0,0,@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@STypeID,@cid,@rate,0,0,0,0)
			
			IF @@ROWCOUNT = 0
				RETURN -3
			ELSE
				SET @nBillId = SCOPE_IDENTITY();
			
			--插入明细表
			INSERT INTO OverFlowBill(BillNumberId,PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
			STypeID,NQty,ItemID,IsCombined,CargoID,MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,Serial)
			SELECT	@nBillId AS BillNumberId,TypeId,(SELECT COUNT(*) FROM dbo.f_split(@SerialResultBy,'я') c WHERE c.a<>''),GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
					@STypeID,abs(CountNQty),ItemID,IsCombined,cargoid,MunitID,NUnitID,UnitID,MUnitrate,
					CASE when a.CountNQty=0  THEN 0 else (abs(CountQty)/abs(a.CountNQty)) END,--p.unitrate,
					ABS((SELECT COUNT(*) FROM dbo.f_split(@SerialResultBy,'я') c WHERE c.a<>''))/MUnitRate,@SerialResultBy
			FROM #BillMx a
			
			WHERE  nid > (@i-1)*150 AND nid <=@i*150
			
			UPDATE dbo.overflowBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
			--修改BillIndex的TotalMoney
			SELECT @TotalQty = SUM(Qty) FROM OverFlowBill WHERE BillNumberId = @nBillId
			UPDATE BillIndex SET TotalQty = @TotalQty,IfWx = @IfWx WHERE BillNumberId = @nBillId
	
			--返回单据编号
			SELECT @TmpBillCode = ISNULL(BillCode,' ') FROM BillIndex WHERE BillNumberId = @nBillId	

			SET @bCodeList = @bCodeList + 'я' + @TmpBillCode
			
			IF NOT EXISTS(
				SELECT ConfigNo
				FROM Userconfig
				WHERE ConfigName='BillcodeCreateTime'
				AND Value=2
			)
			BEGIN
				EXEC GP_SaveBillCode_Seed	@nBillId,@NowDate,14,@BillCode
			END

			IF @@error<>0 
				BEGIN
					RETURN -2
				END 

			SET @i = @i + 1
			
		-- 自动生成的单据会影响草稿库存
		EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,14
		END
		
	
		
		IF(@SerialResultBs!='')
		BEGIN
		
			TRUNCATE TABLE #BillMx

			INSERT INTO #BillMx(TypeId,CountQty,GoodsCostPrice,GoodsNumber,ProduceDate,ValidDate,CountNQty,cargoid,IsCombined,ItemID,MunitID,NUnitID,UnitID,MUnitrate,Unitrate,Serial,StockCheckSerial) 
			SELECT TypeId,CountQty,GoodsCostPrice,GoodsNumber,ProduceDate,ValidDate,CountNQty ,cargoid,IsCombined,ItemID,MunitID,NUnitID,UnitID,MUnitrate,Unitrate,Serial,StockCheckSerial
			FROM #Result
			
			

			SELECT @bCount = COUNT(*) FROM #BillMx

			IF @bCount % 150 = 0
				SET @BillCount = @bCount / 150
			ELSE
				SET @BillCount = @bCount / 150 + 1

			SET @i =  1

			WHILE @i<=@BillCount
			BEGIN
				--生成单据编号
				IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 9) AND @BillCodeConfig = '1'
					BEGIN
						SELECT @MONTH =''
						SELECT @DAY = FullName,@stid=STypeID FROM Stock WHERE TypeID = @KTypeId
					END
				
				SET @BillCode = ''
				EXEC @Re=Gp_GetBillCode 9, @MONTH,@DAY,'BS',@NowDate,@stid,@BillCode output	
				IF @Re <> 0
					RETURN -2
					
				--写入单据主表
				INSERT INTO BillIndex (AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,STypeId,CID,Rate,NTotalInMoney,NTotalMoney,NPreferenceMoney,NVIPCZMoney)
				VALUES(9999,CONVERT(varchar(10),GetDate(),120),@BillCode,9,'','','','',@ktypeid,'','f',@ETypeId,0,0,0,@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@STypeID,@cid,@rate,0,0,0,0)
				
				IF @@ROWCOUNT = 0
					RETURN -3
				ELSE
					SET @nBillId = SCOPE_IDENTITY();
		
				--插入明细表
				INSERT INTO LoseBill(BillNumberId,PTypeId,Qty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
									STypeId,NQty,ItemID,IsCombined,CargoID,MUnitID,NUnitID,UnitID,MUnitRate,UnitRate,MQty,Serial)
				SELECT	@nBillId AS BillNumberId,TypeId,abs((SELECT COUNT(*) FROM dbo.f_split(@SerialResultBs,'я') c WHERE c.a<>'')),GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,
						@STypeID,abs(CountNQty),ItemID,IsCombined,cargoid,MUnitID,NUnitID,UnitID,MUnitRate,
						CASE when a.CountNQty=0  THEN 0 else (abs(CountQty)/abs(a.CountNQty)) END,--p.unitrate,
						abs((SELECT COUNT(*) FROM dbo.f_split(@SerialResultBs,'я') c WHERE c.a<>''))/MUnitRate,@SerialResultBs
				FROM #BillMx a
				
				WHERE  nid > (@i-1)*150 AND nid <=@i*150
				
				UPDATE dbo.LoseBill SET ShowOrder=ID WHERE BillNumberId=@nBillID
				--修改BillIndex的TotalMoney
				SELECT @TotalQty = SUM(Qty) FROM LoseBill WHERE BillNumberId = @nBillId
				UPDATE BillIndex SET TotalQty = @TotalQty,IfWx = @IfWx WHERE BillNumberId = @nBillId
		
				--返回单据编号
				SELECT @TmpBillCode = ISNULL(BillCode,' ') FROM BillIndex WHERE BillNumberId = @nBillId	

				SET @bCodeList = @bCodeList + 'я' + @TmpBillCode

				IF NOT EXISTS(
					SELECT ConfigNo
					FROM Userconfig
					WHERE ConfigName='BillcodeCreateTime'
					AND Value=2
				)
				BEGIN
					EXEC GP_SaveBillCode_Seed	@nBillId,@NowDate,9,@BillCode
				END

				IF @@error<>0 
					BEGIN
						RETURN -2
					END 

				SET @i = @i + 1
				
				EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,9
			END
		END
		
	END

IF @SKTypeId = ''
	UPDATE StockCheckIndex SET Pass = 1 WHERE IfWx = @IfWx
ELSE
	UPDATE StockCheckIndex SET Pass = 1 WHERE Pass = 0 AND KTypeId = @SKTypeId AND IfWx = @IfWx

SET @bcode = @bCodeList

SELECT @autocount=COUNT(*)
FROM #BillMx

RETURN 0

--删除临时表
DROP TABLE #GoodsStocks,#Result,#GetManPTypeId,#GetManKTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StopBaseInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StopBaseInfo]
GO

/****** Object:  StoredProcedure [dbo].[Gp_StopBaseInfo]    Script Date: 05/25/2011 15:52:10 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*
	作者：谢吉康
	日期：2011-02-23
	描述：基本信息的停用
*/

CREATE PROCEDURE [dbo].[Gp_StopBaseInfo]
(
	@typeid		varchar(max),	--基本信息Id
	@dbname		varchar(max),	--基本信息表名称
	@deltype	int				--操作方式
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)

IF @dbname = 'stype'
	BEGIN
		declare @FullName varchar(128)
		IF (SELECT COUNT(*) FROM SType WHERE VerifyID=@typeid AND deleted=0)>1
			BEGIN
				RAISERROR('您所要停用的分支机构为独立核算分支机构，且该分支机构有被未停用的非独立核算分支机构所调用，不能停用，请核对后再试！',16,1) return
			END
			
		IF EXISTS(SELECT TOP 1 1 FROM Stock WHERE STypeID=@typeid AND deleted=0 AND SonNum = 0)
			BEGIN
				RAISERROR('您所需要停用的分支机构有未停用的所属仓库，不能停用，请确认后再试！',16,1) return
			END
		IF EXISTS(SELECT TOP 1 1 FROM employee WHERE STypeID=@typeid AND deleted=0)
			BEGIN
				RAISERROR('您所需要停用的分支机构有未停用的所属职员，不能停用，请确认后再试！',16,1) return
			END
			/*
		--if exists(select * from SType_InnerARTotal where STypeID2=@TypeId)
		--begin
		--	 select @FullName=FullName from SType where TypeId=@TypeId
		--	 RAISERROR('该分支机构【%s】已经使用过不允许停用！',16,1,@FullName) return
		--end

		--declare @TableName varchar(128)		
		--declare stype_cursor cursor for 
		--	select o.[name] as tablename from syscolumns c inner join sysobjects o on(c.[id]=o.[id]) where c.[name]='stypeid' and o.type='u' and O.[name] not in ('monthproc','stype_userconfig')
		--for read only
		--open stype_cursor
		--fetch next from stype_cursor into  @TableName
		--while @@fetch_status=0
		--begin
		--	 select @sql= 'select TOP 1 * from  '+ @TableName +' where stypeid='''+@TypeId+''''
		--	 exec(@sql)
		--	 if @@rowcount>0
		--	 begin
		--		 select @FullName=FullName from SType where TypeId=@TypeId
		--		 RAISERROR('该分支机构【%s】已经使用过不允许停用！',16,1,@FullName) return
		--	 end
		--	 fetch next from stype_cursor into  @TableName
		--end
		--close stype_cursor
		--deallocate stype_cursor
		*/
		
	END
IF @dbname='Employee'
	BEGIN
		IF @deltype=0
			BEGIN
				--
				IF EXISTS(SELECT TOP 1 1 FROM dbo.Employee WHERE typeId=@typeid AND deleted=1)
				BEGIN
					RAISERROR('该职员已经停用过,不能再停用',16,1) 
					RETURN
				END
				--判断有木有作为操作员使用
				IF EXISTS(SELECT TOP 1 1 FROM dbo.loginuser WHERE etypeid=@typeid)
				BEGIN
					DECLARE @eFullName VARCHAR(255)
					SELECT @eFullName=FullName FROM dbo.employee WHERE typeId=@typeid
					RAISERROR('该职员【%s】已被设置为操作员，不能做停用操作，请删除操作员后再试！',16,1,@eFullName) 
					RETURN
				END
				 
                UPDATE  employee   SET  deleted = 1  WHERE   typeId = @typeid;
				EXEC Gp_DataSaveForPosDown '-99999','employee','0'
				RETURN 0
			END
			
	END
IF @dbname='Atype'
	BEGIN
		IF @deltype=0
			--判断至少有一个基本信息不能停用
		declare @num int
		IF EXISTS(SELECT TypeID FROM atype WHERE TypeID=@TypeId AND deleted=0 and leveal=3)
		begin
		  declare @aparid varchar(100)
		  set @aparid=LEFT(@TypeId,10)
		  if(@aparid='0000100002' or @aparid='0000100004') --固定资产和银行合计
		    begin
				select @num=COUNT(*) from atype where parid=@aparid and deleted=0
				if(@num=1)				
				BEGIN
					 RAISERROR('停用至少要保留一个启用的基本信息，请重新操作',16,1)RETURN--RETURN-8
			    END		     
		    end
		end
	END
	
	---2012-04-20 by 彭勇  发布到Om的商品是不能停用的。
IF @dbname='Ptype'
   BEGIN
    IF EXISTS(SELECT TOP 1 1 from Om_ptype WHERE PtypeID=@typeid)
     BEGIN
	  RAISERROR('该商品已发布到Om不能停用',16,1)RETURN
     END
   END
	
	--仓库关联POS，不允许停用
IF @dbname='Stock'
   BEGIN
    IF EXISTS(SELECT TOP 1 1 from PosInfo WHERE ktypeID=@typeid)
     BEGIN
	  RAISERROR('该仓库已关联POS,不允许停用',16,1)RETURN
     END
   END
	--客户关联POS，不允许停用
IF @dbname='Btype'
BEGIN
	IF EXISTS(SELECT TOP 1 1 from PosInfo WHERE BtypeID=@typeid)
    BEGIN
		RAISERROR('该客户已关联POS,不允许停用',16,1)RETURN
    END
    IF EXISTS(SELECT TOP 1 1 FROM PosInfo WHERE dealbtypeid=@typeid)
    BEGIN
		RAISERROR('该客户已关联POS往来账户,不允许停用',16,1)RETURN
    END
END		
	
SET @SQL = 'UPDATE ' + @dbname + ' 
			SET		Deleted = 1 
			WHERE TypeId = '+CHAR(39)+@typeid+CHAR(39)
			
IF lower(@dbname)='btype'
SET @SQL = 'UPDATE ' + @dbname + ' 
			SET		Deleted = 1 ,
					stopdate=getdate()
			WHERE TypeId = '+CHAR(39)+@typeid+CHAR(39)

EXEC(@SQL)

/* --9.7.1 新增分支机构允许停用 --停用分支机构时同时删除Ac_Items_Detail表相应关联
--IF @dbname = 'stype'
--	BEGIN
--		DELETE Ac_Items_Detail WHERE STypeId=@TypeId
--	END
*/
	
--商品停用启用POS下载处理
IF @dbname = 'Ptype'
BEGIN
	--修改XiWa的XiWaMaxNumber
	DECLARE @XiWaMaxNumber numeric(18,0)
	SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM PType
	UPDATE PType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId

	--POS下载处理
	EXEC Gp_DataSaveForPosDown '-99999','Ptype','0'
	EXEC Gp_DataSaveForPosDown '-99999','PType_Price','0'
	EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext','0'
END

RETURN 0



GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StopOrderBillDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StopOrderBillDetails]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE      PROCEDURE Gp_StopOrderBillDetails 
(
   @OrderBillNumberID numeric(10,0),    --订单BillNumberid号   
   @OrderID			  int,				--明细ID
   @OrderBilltype   VARCHAR(4),			--订单类型
   @chvExcType		varchar(20),			--操作类型
   @stopreason		VARCHAR(max)		--中止原因
)
--@encode$--
AS
SET NOCOUNT ON

Declare @orderState char(1),@chvBillType int

DECLARE @chvBillOver varchar(1)
IF @chvExcType = 'Stop'
BEGIN
	SELECT	@chvBillOver = BillOver
	FROM	OrderIndex
	WHERE	BillNumberID = @OrderBillNumberID

	IF @chvBillOver <> 0	-- 已是中止订单，不用再中止
		RETURN 1
		
	SELECT @orderState=orderState,@chvBillType=BillType FROM orderIndex WHERE BillNumberid =@OrderBillNumberID
	IF @orderState='1' --已完成订单
		RETURN 2
	IF @OrderBilltype = '313'
	BEGIN
		SELECT	@chvBillOver = BillOver
		FROM	PT_Combin_OrderBill
		WHERE	BillNumberID = @OrderBillNumberID AND OrderID = @OrderID
	END
	ELSE
	BEGIN
		SELECT	@chvBillOver = BillOver
		FROM	OrderBill
		WHERE	BillNumberID = @OrderBillNumberID AND OrderID = @OrderID
	END
	IF @chvBillOver <> 0 --已中止明细
		RETURN 3
	IF @OrderBilltype = '313'
	BEGIN
		IF exists(SELECT 1 FROM PT_Combin_OrderBill WHERE billNumberID=@OrderBillNumberID AND OrderID =@OrderID AND qty <= ReachQty)--到货，明细已完成
			RETURN 6
	END
	ELSE
	BEGIN
		IF exists(SELECT 1 FROM OrderBill WHERE billNumberID=@OrderBillNumberID AND OrderID =@OrderID AND qty <= ReachQty)--到货，明细已完成
			RETURN 6
	END
--------------------------------------------------------订单删除或终止执行解锁 start---------------------------------------------------------
	DECLARE @ClearDetail TbType_ClearDetail
	DECLARE @lockDetail TbType_LockDetail
	
	INSERT INTO @ClearDetail (BillNumberId,OrderID) 
	SELECT @OrderBillNumberID,@OrderID
	
	EXEC dbo.GP_DoLock 0,0,@ClearDetail,@lockDetail
--------------------------------------------------------订单删除或终止执行解锁	 end---------------------------------------------------------
	--处理订单库存
	IF @OrderBilltype IN (300,301,313)
	BEGIN
		EXEC GP_Deal_OrderQTY_Stop @OrderBillNumberID,@OrderBilltype,@OrderID,'-'
	END

	--将订单引用的报价单数量修正
	UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)-ISNULL(o.Qty,0)
	FROM QuotePriceBill q INNER JOIN dbo.OrderBill o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.askbillid
	WHERE o.billNumberID=@OrderBillNumberID AND o.OrderID=@OrderID AND o.askbillnumberid<>0 AND o.askbillid<>0
	
	--将订单引用的询价单数量修正
	UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)-ISNULL(o.Qty,0)
	FROM AskPriceBill q INNER JOIN dbo.OrderBill o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.askbillid
	WHERE o.billNumberID=@OrderBillNumberID AND o.OrderID=@OrderID AND o.askbillnumberid<>0 AND o.askbillid<>0
	
	--将订单引用的请购单数量修正
	UPDATE dbo.RequestBill  SET RequestQty=ISNULL(RequestQty,0)-ISNULL(o.Qty,0)
	FROM RequestBill q INNER JOIN dbo.OrderBill o ON q.BillNumberID=o.RequestBillNumberID AND q.ID=o.RequestBillID
	WHERE o.billNumberID=@OrderBillNumberID AND o.OrderID=@OrderID AND o.RequestBillNumberID<>0 AND o.RequestBillID<>0
	
	--中止采购订单明细行 修正销售订单的已采购数量 - 关联关系不处理
	IF @OrderBilltype = 301 
	begin
		UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID=@OrderBillNumberID and OrderID=@OrderID  GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId
	
	 --中止采购订单 修正组合品销售订单的已采购数量 - 关联关系不处理
	           UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		       FROM PT_Combin_OrderBillDetail A JOIN (select SUM(Qty) AS Qty,PTCombinOrderBillDetailID FROM dbo.OrderBill
		       WHERE billNumberID=@OrderBillNumberID and OrderID=@OrderID GROUP BY PTCombinOrderBillDetailID) B on A.ORDERID=B.PTCombinOrderBillDetailID			
	end
	
			
	DECLARE @customerTotal NUMERIC(24,10)
	DECLARE @detialTotal NUMERIC(24,10)
	--SELECT @customerTotal=ISNULL(CustomerTotal,0) FROM dbo.OrderIndex WHERE billNumberID=@OrderBillNumberID--定金金额
	--IF @OrderBilltype = '313'
	--BEGIN
	--	SELECT @detialTotal=ISNULL(SUM(TaxTotal),0) FROM dbo.PT_Combin_OrderBill WHERE billNumberID=@OrderBillNumberID AND BillOver=0 AND OrderID<>@OrderID
	--END
	--ELSE
	--BEGIN
	--	SELECT @detialTotal=ISNULL(SUM(TaxTotal),0) FROM dbo.OrderBill WHERE billNumberID=@OrderBillNumberID AND BillOver=0 AND OrderID<>@OrderID
	--END
	--IF @customerTotal>@detialTotal
	--	RETURN 7
			
	--中止明细
	IF @OrderBilltype = '313'
	BEGIN
		UPDATE	PT_Combin_OrderBill
		SET	BillOver = '1',stopreason=@stopreason
		WHERE BillNumberID = @OrderBillNumberID AND OrderID = @OrderID
		
		
		DECLARE @INDEX1 varchar(300)
		SELECT @INDEX1=pindexid FROM PT_Combin_OrderBill WHERE BillNumberID = @OrderBillNumberID AND OrderID = @OrderID
		
		UPDATE	PT_Combin_OrderBillDetail
		SET	BillOver = '1',stopreason=@stopreason
		WHERE BillNumberID = @OrderBillNumberID 
		AND pindexid=@INDEX1
	END
	ELSE
	BEGIN
		UPDATE	OrderBill
		SET	BillOver = '1',stopreason=@stopreason
		WHERE	BillNumberID = @OrderBillNumberID AND OrderID = @OrderID
	END
	
	
	--判断是否所有明细都被中止,所有都终止的话，将单据中止
	DECLARE @AllDetails int,@StopDetails int
	IF @OrderBilltype = '313'
	BEGIN
		SELECT @AllDetails = COUNT(*) FROM PT_Combin_OrderBill WHERE BillNumberID = @OrderBillNumberID
		SELECT @StopDetails = COUNT(*) FROM PT_Combin_OrderBill WHERE  BillNumberID = @OrderBillNumberID AND BillOver = '1'
	END
	ELSE
	BEGIN
		SELECT @AllDetails = COUNT(*) FROM OrderBill WHERE BillNumberID = @OrderBillNumberID
		SELECT @StopDetails = COUNT(*) FROM OrderBill WHERE  BillNumberID = @OrderBillNumberID AND BillOver = '1'
	END
	IF @StopDetails = @AllDetails
		UPDATE	OrderIndex
		SET	BillOver = '1', OrderState='1'
		WHERE	BillNumberID = @OrderBillNumberID
	--判断中止后，是否所有明细都是中止或调用状态，如果是，单据完成
	IF @OrderBilltype = '313'
	BEGIN
		IF NOT EXISTS(
				SELECT	*
				FROM	PT_Combin_OrderBill
				WHERE	BillNumberID = @OrderBillNumberID
						AND ReachQty < Qty AND BillOver='0')
		BEGIN
			UPDATE	OrderIndex
			SET		OrderState = '1'	-- 已完成
			WHERE	BillNumberID = @OrderBillNumberID
		END		
	END
	ELSE
	BEGIN
		IF NOT EXISTS(
				SELECT	*
				FROM	OrderBill
				WHERE	BillNumberID = @OrderBillNumberID
						AND ReachQty < Qty AND BillOver='0')
		BEGIN
			UPDATE	OrderIndex
			SET		OrderState = '1'	-- 已完成
			WHERE	BillNumberID = @OrderBillNumberID
		END				
	END	
END

IF @chvExcType = 'Free'
BEGIN
	SELECT	@chvBillOver = BillOver
	FROM	OrderBill
	WHERE	BillNumberID = @OrderBillNumberID AND OrderID = @OrderID

	IF @chvBillOver <> 1 	-- 非中止的明细，无法解除中止
		RETURN 4	
		
	DECLARE @qtyOver INT =0;
	;WITH CurORDERQTY AS (
	SELECT c.RequestBillNumberID, c.RequestBillID,ISNULL((c.qty+isnull(o.qty,0)),0) AS qty
	FROM
	(
	SELECT  billNumberID, RequestBillNumberID,RequestBillID,SUM(ISNULL(qty,0)) AS QTY
	FROM orderbill 
	WHERE billNumberID=@OrderBillNumberID AND OrderID = @OrderID AND RequestBillNumberID<>0 AND BillOver=1
	GROUP BY  billNumberID,RequestBillNumberID,RequestBillID
	)c
	left JOIN 
	(
	SELECT  b.billNumberID,b.RequestBillNumberID,b.RequestBillID,SUM(ISNULL(b.qty,0)) AS QTY
	FROM  orderbill b 
	INNER JOIN dbo.OrderIndex c ON b.billNumberID = c.billNumberId
	WHERE b.RequestBillNumberID<>0 AND b.RequestBillID<>0 AND b.BillOver = 0 AND c.IfAudit = 1
	GROUP BY b.billNumberID,b.RequestBillNumberID,b.RequestBillID
	)o  ON c.RequestBillNumberID=o.RequestBillNumberID AND c.RequestBillID=o.RequestBillID

	)

	SELECT  @qtyOver=COUNT(*)
	FROM  RequestBill b 
	INNER JOIN CurORDERQTY c ON b.BillNumberId=c.RequestBillNumberID AND b.ID=c.RequestBillID AND ISNULL(c.qty,0) > ISNULL(b.Qty,0)

	IF ISNULL(@qtyOver,0)>0 AND EXISTS (SELECT TOP 1 1 FROM userconfig WHERE ConfigName='notorderqtybiggerrequest' AND Value= '1')
		RETURN 9; 
		
	SELECT @customerTotal=ISNULL(CustomerTotal,0) FROM dbo.OrderIndex WHERE billNumberID=@OrderBillNumberID--定金金额
	IF @OrderBilltype = '313'
	BEGIN
		SELECT @detialTotal=ISNULL(SUM(TaxTotal),0) FROM dbo.PT_Combin_OrderBill WHERE (billNumberID=@OrderBillNumberID AND BillOver=0) OR (OrderID=@OrderID AND BillOver=1)
	END
	ELSE
	BEGIN
		SELECT @detialTotal=ISNULL(SUM(TaxTotal),0) FROM dbo.OrderBill WHERE (billNumberID=@OrderBillNumberID AND BillOver=0) OR (OrderID=@OrderID AND BillOver=1)
	END
		
	--IF @customerTotal>@detialTotal
	--	RETURN 8
		
		--处理订单库存
	IF @OrderBilltype IN (300,301,313)
	BEGIN
		EXEC GP_Deal_OrderQTY_Stop @OrderBillNumberID,@OrderBilltype,@OrderID,'+'
	END
		
	--将订单引用的报价单数量修正
	UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)+ISNULL(o.Qty,0)
	FROM QuotePriceBill q INNER JOIN dbo.OrderBill o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.askbillid
	WHERE o.billNumberID=@OrderBillNumberID AND o.OrderID=@OrderID  AND o.askbillnumberid<>0 AND o.askbillid<>0
	
	--将订单引用的询价单数量修正
	UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)+ISNULL(o.Qty,0)
	FROM AskPriceBill q INNER JOIN dbo.OrderBill o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.askbillid
	WHERE o.billNumberID=@OrderBillNumberID AND o.OrderID=@OrderID  AND o.askbillnumberid<>0 AND o.askbillid<>0
	
	--将订单引用的请购单数量修正
	UPDATE dbo.RequestBill SET RequestQty=ISNULL(RequestQty,0)+ISNULL(o.Qty,0)
	FROM RequestBill q INNER JOIN dbo.OrderBill o ON q.BillNumberID=o.RequestBillNumberID AND q.ID=o.RequestBillID
	WHERE o.billNumberID=@OrderBillNumberID AND o.OrderID=@OrderID  AND o.RequestBillNumberID<>0 AND o.RequestBillID<>0
	
	--解除中止采购订单 修正销售订单的已采购数量 + 关联关系不处理
	IF @OrderBilltype = 301 
	begin
		UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)+ISNULL( B.qty,0)
		FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID=@OrderBillNumberID   AND OrderID=@OrderID  GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId	
		
		--解除中止采购订单 修正组合品销售订单的已采购数量 + 关联关系不处理
		 UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)+ISNULL( B.qty,0)
		 FROM PT_Combin_OrderBillDetail A JOIN (select SUM(Qty) AS Qty,PTCombinOrderBillDetailID FROM dbo.OrderBill
		 WHERE billNumberID=@OrderBillNumberID AND OrderID=@OrderID  GROUP BY PTCombinOrderBillDetailID) B on A.ORDERID=B.PTCombinOrderBillDetailID	
	end
	
	--明细解除中止
	IF @OrderBilltype = '313'
	BEGIN
		UPDATE	PT_Combin_OrderBill
		SET	BillOver = '0',stopreason=@stopreason
		WHERE	BillNumberID = @OrderBillNumberID
		AND OrderID = @OrderID
		
		DECLARE @INDEX varchar(300)
		SELECT @INDEX=pindexid FROM PT_Combin_OrderBill WHERE	BillNumberID = @OrderBillNumberID AND OrderID = @OrderID
		
		UPDATE	PT_Combin_OrderBillDetail
		SET	BillOver = '0',stopreason=@stopreason
		WHERE	BillNumberID = @OrderBillNumberID
		AND pindexid=@INDEX
	END
	ELSE
	BEGIN
		UPDATE	OrderBill
		SET	BillOver = '0',stopreason=@stopreason
		WHERE	BillNumberID = @OrderBillNumberID
		AND OrderID = @OrderID
	END
	--单据解除中止
	SELECT	@chvBillOver = BillOver
	FROM	OrderIndex
	WHERE	BillNumberID = @OrderBillNumberID
	IF @chvBillOver = '1'
	BEGIN
		IF exists(SELECT 1 FROM OrderBill WHERE billNumberID=@OrderBillNumberID AND ReachQty<qty) --存在发货数量小于订货数量，既未完成
		BEGIN
			UPDATE	OrderIndex
			SET	BillOver = '0',OrderState='0'
			WHERE	BillNumberID = @OrderBillNumberID
		END
		ELSE
		BEGIN
			UPDATE	OrderIndex
			SET	BillOver = '0',OrderState='1'
			WHERE	BillNumberID = @OrderBillNumberID
		END
	END
	--判断中止后，是否所有明细都是中止或调用状态，如果是，单据完成
	IF @OrderBilltype = '313'
	BEGIN
		IF  EXISTS(
			SELECT	*
			FROM	PT_Combin_OrderBill
			WHERE	BillNumberID = @OrderBillNumberID
					AND ReachQty < Qty AND BillOver='0')
		BEGIN
			UPDATE	OrderIndex
			SET		OrderState = '0'	-- 已完成
			WHERE	BillNumberID = @OrderBillNumberID
		END	
	END
	ELSE
	BEGIN
		IF  EXISTS(
				SELECT	*
				FROM	OrderBill
				WHERE	BillNumberID = @OrderBillNumberID
						AND ReachQty < Qty AND BillOver='0')
		BEGIN
			UPDATE	OrderIndex
			SET		OrderState = '0'	-- 已完成
			WHERE	BillNumberID = @OrderBillNumberID
		END	
	END
	
	RETURN 5
	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_StopOrReUseBillStopMoney]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_StopOrReUseBillStopMoney]
GO







/*
	作者：谢吉康
	日期：2004-12-08
	描述：停止（启用）单据的收付款
*/
CREATE PROCEDURE GP_StopOrReUseBillStopMoney
(
	@BillNumberId	int,	--单据ID
	@nType			int,		--操作类型	0.启用  1.停止
	@billtype int,  --单据类型
	@Btypeid        varchar(50),
	@did             int
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

IF @nType = 0
	BEGIN
		
		IF @billtype=404 or @billtype=405
			UPDATE ReceiptBillIndex SET IfStopMoney=0 WHERE BillNumberId = @BillNumberId and BillType=@billtype
		ELSE IF @billtype=115 or @billtype=116 or @billtype=128 or @billtype=129
		    UPDATE addebtbill SET IfStopMoney=0 WHERE BillNumberId = @BillNumberId and Btypeid=@Btypeid and id=@did
		ELSE
			UPDATE	BillIndex SET IfStopMoney = 0 WHERE BillNumberId = @BillNumberId and BillType=@billtype
		
		IF @@ROWCOUNT = 0
			BEGIN
				--RAISERROR('启用单据收（付）款失败，请确认后重试！',16,1)
				RETURN -1
			END
		ELSE
			BEGIN
				--RAISERROR('启用单据收（付）款成功！',16,1)
				RETURN 0			
			END
	END
ELSE
	BEGIN
	
		IF @billtype=404 or @billtype=405
			UPDATE ReceiptBillIndex SET IfStopMoney=1 WHERE BillNumberId = @BillNumberId and BillType=@billtype
		ELSE IF @billtype=115 or @billtype=116 or @billtype=128 or @billtype=129
		    UPDATE addebtbill SET IfStopMoney=1 WHERE BillNumberId = @BillNumberId and Btypeid=@Btypeid and id=@did
		ELSE
			UPDATE	BillIndex SET IfStopMoney = 1 WHERE BillNumberId = @BillNumberId and BillType=@billtype
	
		IF @@ROWCOUNT = 0
			BEGIN
				--RAISERROR('停止单据收（付）款失败，请确认后重试！',16,1)
				RETURN -1
			END
		ELSE
			BEGIN
				--RAISERROR('停止单据收（付）款成功！',16,1)
				RETURN 0			
			END
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_STypeGatherPayBill_CreateDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_STypeGatherPayBill_CreateDraft]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.02.02
	描述：根据分支机构对应 客户/供货商 的 付款单 生成相应 供货商/客户 的 收款单 草稿
*/
CREATE PROCEDURE GP_STypeGatherPayBill_CreateDraft
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@intBillType			int,					--单据类型
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@chvBTypeID				varchar(100),
	@chvSTypeID				varchar(100),
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--
AS
SET NOCOUNT ON



DECLARE 
	@sourcestype	VARCHAR(50) = '',----源分支机构
	@stype			varchar(50) = '',----目标分支机构
	@billPBtypeid	varchar(50),	 ----往来单位分类值
	@bTypeID1		varchar(50),	 ----目标客户
	@bTypeID2		varchar(50),	 ----目标供货商
	@tmpBtypeid		varchar(50) = '', ----目标往来单位
	@ceCheckId			VARCHAR(100),
	@ceDtypeid			VARCHAR(100),
	@cefullname			VARCHAR(500)='',		--制单人
	@cdfullname			VARCHAR(500)=''			--部门

---获取源分支机构
SELECT @sourcestype = Stypeid,@ceCheckId=checke,@ceDtypeid=DTypeId FROM dbo.BillIndex WHERE BillNumberId = @nBillID

---获取目标分支机构
/*
SELECT @stype = b.TypeId
FROM  BillIndex a INNER JOIN dbo.SType b ON (a.btypeid = b.BTypeID1 OR a.btypeid = b.BTypeID2) 
WHERE BillNumberId = @nBillID
*/

SELECT @stype = TypeId
FROM  dbo.SType
WHERE (BTypeID1=@chvBTypeID OR BTypeID2=@chvBTypeID) 



---如果是同一分支机构内，不用生成单据
IF @sourcestype = @stype
	SET @stype = ''
	


---获取目标往来单位

---对应客户、供货商
/*
SELECT @bTypeID1 = A.BTypeID1, @bTypeID2 = A.BTYPEID2 
FROM SType AS A INNER JOIN dbo.BillIndex b ON (a.TypeId = b.Stypeid)
WHERE b.BillNumberId = @nBillID
*/

SELECT @bTypeID1 = BTypeID1, @bTypeID2 = BTYPEID2 
FROM SType 
WHERE TypeID=@chvSTypeID


---判定目标往来单位应该是客户还是供货商
SELECT @billPBtypeid = LEFT(btypeid,5) FROM BillIndex WHERE BillNumberId = @nBillID

IF @billPBtypeid = '00001' 
BEGIN
	SET @tmpBtypeid = @bTypeID2
END
ELSE IF @billPBtypeid = '00002'
BEGIN
	SET @tmpBtypeid = @bTypeID1
END

DECLARE
	@strdenominatedid VARCHAR(50)
	
SELECT 	@strdenominatedid=denominatedid
FROM BType
WHERE typeId=@tmpBtypeid

DECLARE
	@strTempATypeID		VARCHAR(100)
	
SELECT
	@strTempATypeID=ATypeID
FROM BillAtype
WHERE BillTypeId='4'
AND StypeId=@stype

SELECT @strTempATypeID=ISNULL(@strTempATypeID,'')

DECLARE
	@billtype int,				---单据类型
	@strcomment varchar(1000)	---单据备注
	
DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@ETypeID			VARCHAR(100),
	@KTypeID			VARCHAR(100),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@datBillDate		DATETIME,
	@strBillCode        VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID	INT 			 --返回新生成的流水号
	


DECLARE 
	@strFromBillCode varchar(100) --源单据编号
	
SELECT @strFromBillCode = BillCode  FROM BillIndex WHERE BillNumberId = @nBillID

------------生成对应草稿-------

--生成单据类型、备注
IF @tmpBtypeid <> '' AND @stype <> ''
BEGIN
	IF @intBillType = 4
	BEGIN
		SET @billtype = 66
		SET @strComment='该付款单是从收款单'+@strFromBillCode+'生成而来'
		SET	@VchHead='JF'
	END
	
	ELSE
	BEGIN
		SET @billtype = 4
		SET @strComment='该收款单是从付款单'+@strFromBillCode+'生成而来'
		SET @VchHead='XS'
	END
	
--生成单据编号
	SELECT 
		@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
	--单据日期
	SELECT @datBillDate = BillDate FROM BillIndex WHERE BillNumberId = @nBillID	
	
	SELECT
		@ETypeID='',
		@KTypeID=@stype

	IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @billtype) AND @BillCodeConfig = '1'
	BEGIN
		SELECT @MONTH = typeid FROM Employee WHERE TypeID = @ETypeId
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @chvOpID
		SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid
	END

	SELECT 
		@MONTH=ISNULL(@MONTH,''),
		@DAY=ISNULL(@DAY,'')
	
	EXEC @Re=Gp_GetBillCode @billtype, @MONTH,@DAY,@VchHead,@datBillDate,@stype,@strBillCode OUTPUT,@cdfullname,@cefullname
	
-----生成表头
	INSERT BillIndex(BillDate,BillCode,BillType,STypeID,ETypeID,
		ATypeID,DealBTypeID,btypeid,ptypeid,Comment,totalmoney,totalqty,tax,period,explain,
		waybillcode,goodsnumber,packway,TEL,AlertDay,DTypeId,CostSale,FromBillNumberID,
		ifcheck,IfAudit,draft,OrderId,checke,ktypeid,ktypeid2,KTypeID3,NTotalMoney,CID,Rate,ATypeID1,billtime)	
	SELECT BillDate,@strBillCode,@billtype,@stype,
		'','',@tmpBtypeid,@strdenominatedid,ptypeid,@strComment,totalmoney,totalqty,tax,period,explain,
		waybillcode,goodsnumber,packway,TEL,AlertDay,'',CostSale,BillNumberId,
		'f',0,1,0,'','','','',NTotalMoney,CID,Rate,@strTempATypeID,CONVERT(VARCHAR(20), GETDATE(), 24)
	FROM BillIndex
	WHERE BillNumberId=@nBillID

	SELECT @intReturnID=SCOPE_IDENTITY();

---生成表体
	IF @billtype = 4 --收款单
	BEGIN
		--预付对应预收
		INSERT gatheringBill(BillNumberId,AtypeId,total,Comment,Stypeid,VipCardID,ntotal,ShowOrder)
		SELECT @intReturnID,CASE WHEN AtypeId = '0000100009' THEN '0000200006' ELSE Atypeid END,total,Comment,Stypeid,VipCardID,ntotal,ShowOrder
		FROM PayBill
		WHERE BillNumberId = @nBillID 

	END
	ELSE IF @billtype = 66--生成付款单
	BEGIN
		--预收对应预付，排除付款单没有的“会员储值”
		INSERT PayBill(BillNumberId,AtypeId,total,Comment,Stypeid,VipCardID,ntotal,ShowOrder)
		SELECT @intReturnID,CASE WHEN AtypeId = '0000200006' THEN '0000100009' ELSE AtypeId END,total,Comment,Stypeid,VipCardID,ntotal,ShowOrder
		FROM gatheringBill
		WHERE BillNumberId = @nBillID AND AtypeId <> '0000200005'
		
		IF EXISTS(SELECT * FROM dbo.PayBill WHERE BillNumberId = @intReturnID)--如果存在明细，更新总额
		BEGIN
			DECLARE @total  NUMERIC(24, 10) ,@ntotal  NUMERIC(24, 10) 
			SELECT @total=SUM(total),@ntotal=SUM(ntotal) FROM dbo.gatheringBill WHERE BillNumberId = @intReturnID
			UPDATE dbo.BillIndex SET totalmoney = @total,NTotalMoney=@ntotal WHERE BillNumberId = @intReturnID
		END
		ELSE--不存在明细，删除生成的表头，不生成单据
		BEGIN
			DELETE FROM dbo.BillIndex WHERE BillNumberId = @intReturnID
			RETURN
		END
	END
--写入种子数
	IF NOT EXISTS(SELECT ConfigNo FROM Userconfig WHERE ConfigName='BillcodeCreateTime' AND Value=2)
	BEGIN
		EXEC GP_SaveBillCode_Seed @intReturnID,@datBillDate,@billtype,@strBillCode
	END    

	IF ISNULL(@strErrMsg,'')=''
	BEGIN
		SET @strReturnBillCode=@strBillCode
	END
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StypeIfTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StypeIfTotal]
GO
/****** Object:  StoredProcedure [dbo].[Gp_StypeIsUsed]    Script Date: 05/20/2011 17:31:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO



/*******************************
--时间：2013-07-10
--描述：判断分支机构是否有科余额和项余额
--作者：黄 清
*******************************/
CREATE PROCEDURE [dbo].[Gp_StypeIfTotal]
(
@TypeId VARCHAR(100)
)
--@encode$--
AS 
SET QUOTED_IDENTIFIER ON 
IF EXISTS (SELECT *FROM AType_Total WHERE STypeID=@TypeId AND (Total00<>0 OR Total<>0 OR Ntotal00<>0 OR Ntotal<>0))
	RETURN 1
IF EXISTS (SELECT *FROM Ac_Balance WHERE STypeId=@TypeId AND (FBeginBalance<>0 OR FBeginBalanceFor<>0 OR FEndBalance<>0 OR FEndBalanceFor<>0))
	RETURN 1
IF EXISTS( SELECT *FROM SType_InnerARTotal WHERE (STypeID=@TypeId OR STypeID2=@TypeId) AND (InnerARTotal<>0 OR InnerARTotal00<>0))
	RETURN 1
RETURN 0
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_StypeIndependentOpenConfig]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].GP_StypeIndependentOpenConfig
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*
	作者：	毛欣蓉
	时间：	2016-7-11
	描述：获取分支机构月经相同的记录(所选分支必须期间、年度一样一样，开始时间和结束时间都一致)
*/

CREATE  PROCEDURE [dbo].GP_StypeIndependentOpenConfig
(
	@ischeck	INT,		--1勾选 0取消
	@flag		INT  --1表是检测 2 表示修改数据
)
--@encode$--
AS
set nocount on
	
	IF @flag=1     --检测
	BEGIN
		IF @ischeck=1
		BEGIN
			IF  EXISTS(SELECT TOP 1 1 FROM MonthProc WHERE MonthNo<>'本期')
				RETURN -1
			ELSE
				RETURN 1
		END
		ELSE   --取消勾选
		BEGIN
			--DECLARE @ystart
			IF (SELECT  COUNT(1) FROM (SELECT DISTINCT SFPeriod,SFYear FROM SType_UserConfig)a)<>1
			   RETURN -1
			 
			IF (SELECT  COUNT(1) FROM (SELECT DISTINCT SFPeriod,SFYear FROM Ac_AccountsPeroid_Stype)a)<>1
			   RETURN -1
			 
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype a,SType_UserConfig b WHERE a.SFPeriod<>b.SFPeriod OR a.SFYear<>b.SFYear)
				RETURN -1
				
			IF EXISTS(SELECT TOP 1 1 FROM dbo.MonthProc a,MonthProc b WHERE a.MonthNo='本期' AND b.MonthNo='本期' AND (a.period<>b.period OR a.Year<>b.Year))
			   RETURN -1
			   
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype a,SType_UserConfig b WHERE a.Stypeid=b.StypeId AND a.IsUse<>b.Value)
				RETURN -2
			   
			 RETURN 1
		END
	END
	ELSE
	BEGIN
		IF @ischeck	= 1 --勾选
		BEGIN
			
			IF  EXISTS(SELECT TOP 1 1 FROM MonthProc WHERE MonthNo<>'本期')
				RETURN -1
			
			/*SELECT * INTO #MonthProc FROM MonthProc
			
			DELETE MonthProc
			
			INSERT INTO dbo.MonthProc( MonthNo ,StartDate ,EndDate ,period ,comment ,STypeID ,Year)
			SELECT     a.MonthNo,a.StartDate,a.EndDate,a.period, a.comment,b.TypeId,a.Year
			FROM  #MonthProc a,
			dbo.SType b	 */
			
			UPDATE A SET A.YEAR=ISNULL(B.SFYear,A.Year),
						 A.Period=ISNULL(B.SFPeriod,A.period),
						 A.StartDate=ISNULL(C.FBegin,A.StartDate)
			FROM dbo.MonthProc A ,dbo.SType_UserConfig B,dbo.Ac_Period C
			WHERE A.STypeID=B.StypeId 
				 AND B.SFYear=C.FYear 
				 AND B.SFPeriod=C.FPeriod
				 AND b.Value = 0
				 
			UPDATE dbo.sysdata SET SubValue=1 WHERE SubName='stypeindependentopen'
			
			--DROP TABLE #MonthProc 
			
			RETURN 1
		END
		ELSE
		BEGIN

			IF (SELECT  COUNT(1) FROM (SELECT DISTINCT SFPeriod,SFYear FROM SType_UserConfig)a)<>1
			   RETURN -1
			 
			IF (SELECT  COUNT(1) FROM (SELECT DISTINCT SFPeriod,SFYear FROM Ac_AccountsPeroid_Stype)a)<>1
			    RETURN -1
			 
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype a,SType_UserConfig b WHERE a.SFPeriod<>b.SFPeriod OR a.SFYear<>b.SFYear)
				RETURN -1
				
			IF EXISTS(SELECT TOP 1 1 FROM dbo.MonthProc a inner join MonthProc b on b.STypeID=a.STypeID and a.MonthNo='本期' AND b.MonthNo='本期' AND (a.period<>b.period OR a.Year<>b.Year))
			    RETURN -1
			
			IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype a,SType_UserConfig b WHERE a.Stypeid=b.StypeId AND a.IsUse<>b.Value)
				RETURN -2
			/*SELECT * INTO #MonthProc1 FROM MonthProc
			
			DELETE MonthProc
			
			INSERT INTO dbo.MonthProc( MonthNo ,StartDate ,EndDate ,period ,comment ,STypeID ,Year)
			SELECT  DISTINCT  a.MonthNo,a.StartDate,a.EndDate,a.period, a.comment,'00000',a.Year
			FROM  #MonthProc1 a	*/
				
			UPDATE dbo.sysdata SET SubValue=0 WHERE SubName='stypeindependentopen'
			--修改总账期间表
			DECLARE @Fyear	INT,@FPeriod INT
			SELECT TOP 1 @Fyear=SFYear,@FPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype
			UPDATE SysData SET SubValue=@Fyear WHERE SubName='fyear'
			UPDATE SysData SET SubValue=@FPeriod WHERE SubName IN('fmonth','FPeriod')
			UPDATE Ac_Period SET FMonth=@FPeriod WHERE FYear=@Fyear
			--DROP TABLE #MonthProc1 
			RETURN 1
		END
	END
									   

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StypeIsUsed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StypeIsUsed]
GO
/****** Object:  StoredProcedure [dbo].[Gp_StypeIsUsed]    Script Date: 05/20/2011 17:31:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO




 
--作    用：判断分支机构是否被其他地方使用过


CREATE PROCEDURE [dbo].[Gp_StypeIsUsed]
(
@TypeId VARCHAR(100)
)
--@encode$--
AS 
BEGIN 
	DECLARE @TableName VARCHAR(1000) 
	,@sql VARCHAR(1000)

	DECLARE  stype_cursor CURSOR 
	for select o.[name] as tablename from syscolumns c inner join sysobjects o on(c.[id]=o.[id]) where c.[name]='stypeid' and o.type='u' and o.[name] 
	not in('atype_total','inicommissionStock','BType_ARAPTotal','Ac_AssetBusinessType','Ac_Account_L','Te_StartPeriod')--排除的表
	for read only
	open stype_cursor
	FETCH  NEXT  FROM  stype_cursor into  @TableName
	WHILE  @@fetch_status=0
		BEGIN
			 IF (isnull(@TableName,'')<>'btype_credit' AND isnull(@TableName,'')<>'BillAtype' ) --AND isnull(@TableName,'')<>'Ac_Items_Detail'
				 BEGIN 
					IF @TableName='listtable' 
					BEGIN
						SET  @sql= 'select * from  '+ @TableName +' where stypeid='''+@TypeId+''' OR stypeid2='''+@TypeId+''''
					END
					ELSE
						IF @TableName='Ac_Items_Detail' 
						BEGIN
							SET @sql='SELECT *FROM '+@TableName+' WHERE Stypeid='''+@TypeId+''' AND (ATypeId<>'''' OR DepATypeId<>'''' OR DisATypeId<>'''') '
						END
					ELSE
						BEGIN
							SET  @sql= 'select * from  '+ @TableName +' where stypeid='''+@TypeId+''''
						END
				EXEC (@sql)
				IF  @@rowcount>0
					BEGIN
						IF @TableName = 'SType_UserConfig' OR @TableName = 'Base_InventoryTypeDetails' OR @TableName = 'Base_FixedReasonForChangeDetails'
							OR @TableName = 'Ac_AccountsPeroid_Stype' OR @TableName = 'MonthProc' OR @TableName='PTYPE_InventoryType'
						   FETCH  NEXT  FROM  stype_cursor INTO   @TableName 
						ELSE
						BEGIN
							PRINT @TableName
							RETURN 1
						END
					END 
			END 
		 
		 FETCH  NEXT  FROM  stype_cursor INTO   @TableName
	END 
	CLOSE  stype_cursor
	DEALLOCATE  stype_cursor
	RETURN 0
END


SET QUOTED_IDENTIFIER ON 




GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_STypeMoveOutBill_CreateBill]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_STypeMoveOutBill_CreateBill]
GO




/*

功能说明：		分支机构调拨出库单生成分支机构调拨入库单的草稿

作    者：       冯波


返回结果：       

*/

CREATE PROCEDURE [GP_STypeMoveOutBill_CreateBill]
(
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0) OUT,		--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100) OUT,
	@strErrMsg				VARCHAR(100) OUT		--出错信息
)
--@encode$--        
AS

/*
DECLARE
	@intMoneyDot	INT,		--金额的小数位数
	@intPriceDot	INT			--单价的小数位数

SELECT
	@intMoneyDot=2,
	@intPriceDot=4

--加上对扣率，税率的小数归整
DECLARE
	@intDiscountDot		INT,		--扣率的小数位数
	@intTaxDot			INT			--税率的小数位数
*/
	DECLARE
		@intQtyDot			INT,
		@intPriceDot		INT,
		@intMoneyDot		INT,
		@intDiscountDot		INT,
		@intTaxDot			INT,
		@intCRateDot		INT,	
		@intTRateDot		INT	
		
	EXEC	GP_Post_Dot
		@intQtyDot	OUT,
		@intPriceDot	OUT,
		@intMoneyDot	OUT,
		@intDiscountDot	OUT,
		@intTaxDot	OUT,
		@intCRateDot OUT,
		@intTRateDot	OUT


SELECT @intReturnID=0

DECLARE 	
	@strTempKTypeID					VARCHAR(50),
	@strOutSTypeID					VARCHAR(50),		--出库对应的分支机构
	@strInSTypeID					VARCHAR(50),
	@decTax							 NUMERIC(24, 10) ,
	@strFromBillCode 				VARCHAR(100),
	@intBillType					INT,
	@datBillDate					DATETIME,
	@KTypeID						VARCHAR(100),
	@ceDtypeid						VARCHAR(100),
	@cdfullname			VARCHAR(500)=''			--部门

SELECT 
	@strOutSTypeID=a.sTypeId,@KTypeID=a.ktypeid2,@ceDtypeid=DTypeId,
	@decTax=a.tax,@strFromBillCode=a.BillCode,@datBillDate=a.BillDate
FROM BillIndex a
WHERE a.BillNumberId=@nBillID

SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

SELECT @intBillType=188

SELECT @strTempKTypeID=KTypeID2
FROM
(
	SELECT TOP 1 KTypeID2 
	FROM STypeMoveBill
	WHERE BillNumberId=@nBillID
) a

SELECT @strInSTypeID=STypeID
FROM Stock
WHERE typeId=@strTempKTypeID


--判断是否属于分支机构间的采购，销售

IF EXISTS(SELECT BillNumberId FROM BillIndex WHERE FromBillNumberID=@nBillID AND BillType=188)
BEGIN
	SET @strErrMsg='该分支机构调拨出库单已生成有相应分支机构调拨入库单草稿！'	
	RETURN
END


DECLARE
	@strBillCode        		VARCHAR(100) ,   --返回新生成的单据编号
	@intReturnFlowID			INT 			--返回新生成的流水号

/*

生成新的单据编号

DECLARE
	@strTempSID			VARCHAR(100),
	@strTempDID			VARCHAR(100),
	@strTempEID			VARCHAR(100)

SELECT @strTempSID=@strOutSTypeID

SELECT @strTempEID=''

SELECT @strTempDID='',@strTempEID=''

DECLARE
	@intNewSeed		BigInt



EXEC GP_CreateBillCode
	'',
	@strTempSID,
	@datBillDate,
	@intBillType,
	1,
    @strBillCode OUT,
    @intNewSeed OUT,
    @strErrMsg OUT
*/

DECLARE 
	@BillCodeConfig		VARCHAR(100),
	@MONTH				VARCHAR(200),
	@DAY				VARCHAR(200),
	@ETypeID			VARCHAR(100),
	@VchHead			VARCHAR(100),
	@Re					INT,
	@cefullname			VARCHAR(500)=''

SELECT 
	@BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'
	
SELECT
	@ETypeID='',
	@VchHead='SRD'

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @intBillType) AND @BillCodeConfig = '1'
BEGIN
	SELECT @MONTH = typeid FROM Employee WHERE TypeID = @ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
	SELECT @cefullname = E.FUllname FROM Employee E WHERE E.TypeId = @chvOpID
END

SELECT 
	@MONTH=ISNULL(@MONTH,''),
	@DAY=ISNULL(@DAY,'')


EXEC @Re=Gp_GetBillCode @intBillType, @MONTH,@DAY,@VchHead,@datBillDate,@strInSTypeID,@strBillCode OUTPUT,@cdfullname,@cefullname




IF @Re <> 0
RETURN -2	

--SELECT @strBillCode='tmpfzjgrkd'  --因为单据编号要调整，暂时屏蔽生成单据编号那段代码

DECLARE
	@strSql			VARCHAR(8000),
	@strComment		VARCHAR(1000)
	
	
SELECT 
	@strComment='该分支机构调拨入库是从分支机构调拨出库单'+@strFromBillCode+'生成而来的！',
	@intBillType=188
	
	



--生成分支机构入库单的草稿
--生成表头





INSERT BillIndex(BillDate,BillCode,BillType,STypeID,ETypeID,
ATypeID,KTypeID,KTypeID2,Comment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,AlertDay,DTypeId,CostSale,FromBillNumberID,
ifcheck,IfAudit,draft,OrderId,checke,btypeid,NTotalMoney,CID,Rate)
SELECT BillDate,@strBillCode,@intBillType,@strInSTypeID,
'','',KTypeID,KTypeID2,@strComment,totalmoney,totalqty,tax,period,explain,
waybillcode,goodsnumber,packway,TEL,AlertDay,'',CostSale,BillNumberId,
'f',0,1,0,'','',NTotalMoney,CID,Rate
FROM BillIndex
WHERE BillNumberId=@nBillID

SELECT @intReturnID=SCOPE_IDENTITY();

--生成表体

INSERT STypeMoveBill(BillNumberId,BillType,Comment,PtypeId,Qty,
Price,Total,Jobnumber,GoodsNo,OutFactoryDate,IsUnit2,Serial,
GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,
GoodsCostTotal,HandZeroCost,InCargoID,OutCargoID,Stypeid,
Ktypeid2,Ktypeid,FromBillNumberID,FromBillID,
UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,ItemID,IsCombined,
MPrice,ShowOrder)
SELECT @intReturnID,@intBillType,Comment,PtypeId,Qty,
Price,Total,Jobnumber,GoodsNo,OutFactoryDate,IsUnit2,Serial,
GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,
GoodsCostTotal,HandZeroCost,InCargoID,OutCargoID,@strInSTypeID,
Ktypeid2,Ktypeid,@nBillID,ID,
UnitID,NUnitID,NQty,UnitRate,NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,ItemID,IsCombined,
MPrice,ShowOrder
FROM STypeMoveBill
WHERE BillNumberId=@nBillID


--写入种子数
IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@intReturnID,
		@datBillDate,
		@intBillType,
		@strBillCode
END    

IF ISNULL(@strErrMsg,'')=''
BEGIN
	SET @strReturnBillCode=@strBillCode
END

-- Costing Method
DECLARE @AVERAGE			smallint,
		@FIFO				smallint,
		@LIFO				smallint,
		@HAND				smallint,
		@nCostingMethod		smallint

SET @AVERAGE	= 0		-- 移动加权平均
SET @FIFO		= 1		-- 先进先出
SET @LIFO		= 2		-- 后进先出
SET @HAND		= 3		-- 手工指定

EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output



IF @nCostingMethod<>@HAND
BEGIN
	--修改价格
	UPDATE STypeMoveBill
	SET GoodsCostPrice=a.CostPrice,GoodsCostTotal=a.CostTotal
	FROM
	(
		SELECT ID,SUM(CostTotal)*(-1) AS CostTotal,CASE SUM(Qty) WHEN 0 THEN 0 ELSE ROUND(CAST(SUM(CostTotal) AS  NUMERIC(24, 10) )/CAST(SUM(Qty) AS  NUMERIC(24, 10) ),4) END AS CostPrice
		FROM InOutstocktable
		WHERE BillNumberId=@nBillID
		GROUP BY ID
	) a
	WHERE STypeMoveBill.BillNumberId=@nBillID AND STypeMoveBill.ID=a.ID
END

-- 自动生成的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @intReturnID,@intBillType

GO


/*

DECLARE
	@chvOpID				varchar(50) = '',		-- 当前操作员 ID 值
	@nBillID				numeric(10,0),			-- 单据 ID 号
	@intReturnID			numeric(10,0),			--新生成的单据的ID
	@strReturnBillCode		VARCHAR(100),
	@strErrMsg				VARCHAR(100)			--出错信息
	
SELECT
	@chvOpID=1,
	@nBillID=6
	
	

EXEC	GP_STypeMoveOutBill_CreateBill
	@chvOpID,
	@nBillID,
	@intReturnID OUT,
	@strReturnBillCode OUT,
	@strErrMsg OUT

SELECT @strReturnBillCode,@strErrMsg


SELECT * FROM BillIndex WHERE BillType=187

*/




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_StypePriceXWMaxNumber]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_StypePriceXWMaxNumber]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：胡小科
	日期：2013-7-22
	描述：posxwmaxnumber
*/

 
CREATE PROCEDURE Gp_StypePriceXWMaxNumber
(
	@mflag			int,            --更具该标识做出相应的处理（增1删2改3）
	@stypeid		VARCHAR(MAX),	--分支机构
	@ptypeid		VARCHAR(MAX)	--商品ID
 
)
--@encode$--
AS
SET NOCOUNT ON

if @mflag=1
begin
	delete from PosReDataGlobal where stypeid=@stypeid 
	insert into  PosReDataGlobal values(1,@stypeid)
	 
	delete  PosIsUpdateData where stypeid=@stypeid and tbType='PType_StypePrice'
	insert into  PosIsUpdateData values('PType_StypePrice',0,1,@stypeid)	
		
		
		   
	update PType_STypePrice set XiWaMaxNumber=(select MAX(XiWaMaxNumber) from PType_STypePrice )+1 WHERE PTypeID = @PTypeId AND STypeID = @STypeId
		   
		   --PosIsUpdateData，PosReDataGlobal
end


if @mflag=2
begin
	delete   PosReDataGlobal where stypeid=@stypeid 
	insert into  PosReDataGlobal values(1,@stypeid)
		   
    delete  PosIsUpdateData where stypeid=@stypeid and tbType='PType_StypePrice'
    insert into  PosIsUpdateData values('PType_StypePrice',-1,1,@stypeid)
end



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Switch_DeleteInitData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Switch_DeleteInitData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.09.13
	描述：项目与卡片模式期初切换时的数据清理
*/
CREATE PROCEDURE GP_Switch_DeleteInitData
(
	@Flag	INT --0.项目期初 1.卡片数据
)
--@encode$--
AS
SET NOCOUNT ON

IF @Flag = 0--有未开账的分支机构时，切换到卡片模式，清除未开账分支机构的项目期初
BEGIN
	DELETE FROM dbo.AType_Total 
	WHERE ATypeID IN (SELECT nId FROM dbo.Ac_Items WHERE TypeName = 'F')
		AND STypeID NOT IN (SELECT T1.TypeId FROM dbo.SType T1 INNER JOIN dbo.SType_UserConfig T2 ON T1.TypeId = T2.StypeId AND T2.Value = 1)
END
ELSE
BEGIN
	TRUNCATE TABLE dbo.Ac_AssetsCards
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Sys_DataBaseClean]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Sys_DataBaseClean]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO








/*

功能说明：       数据整理，包括收缩事务日志，重建数据索引

作    者：       田浩

创建日期：       2006-12-20

返回结果：       @strErrMsg返回出错原因

*/



CREATE PROCEDURE [GP_Sys_DataBaseClean]
(
 @strErrMsg         VARCHAR(255)='' OUT     --出错原因，默认为空
)
--@encode$-- 
AS
DECLARE @strSQL VARCHAR(4000),
		@strDataBaseName VARCHAR(100)

SET @strDataBaseName = DB_NAME();

----设置单用户模式并回滚所有未完成的事务
--SET @strSQL = 'ALTER DATABASE [' + @strDataBaseName + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;';
--EXEC(@strSQL);



/****************************************************************/
/*****1、重建索引**********************************************/
/****************************************************************/


/*******************************删除索引***********************************************/
CREATE TABLE #TableName(name VARCHAR(200))

INSERT INTO #TableName
	SELECT name 
		FROM SYSOBJECTS 
			WHERE xtype = 'U';



DECLARE @strTableName VARCHAR(200);
DECLARE cursor_TableName cursor FOR SELECT name FROM #TableName;

OPEN cursor_TableName

WHILE 1=1 
BEGIN
     FETCH NEXT FROM cursor_TableName INTO @strTableName;
	 
     IF @@FETCH_STATUS < 0 BREAK;
	 
     SET @strSql = 'DBCC DBREINDEX([' + @strTableName + ']) WITH NO_INFOMSGS';
     EXEC(@strSql);
END

CLOSE cursor_TableName
DEALLOCATE cursor_TableName


DROP TABLE #TableName

/****************************************************************/
/*****2、收缩数据库***********************************************/
/****************************************************************/

----修改数据库日志模式为简单

SET @strSQL = 'alter database [' + @strDataBaseName + '] set recovery simple with no_wait;';
EXEC(@strSQL);

SET @strSQL = 'alter database [' + @strDataBaseName + '] set recovery simple ;';
EXEC(@strSQL);


-----收缩文件
SELECT @strSQL='DBCC SHRINKDATABASE(N''' + @strDataBaseName + ''',  TRUNCATEONLY );'
EXEC(@strSQL);


----修改数据库日志模式为完整
SET @strSQL = 'alter database [' + @strDataBaseName + '] set recovery full with no_wait;';
EXEC(@strSQL);

SET @strSQL = 'alter database [' + @strDataBaseName + '] set recovery full ;';
EXEC(@strSQL);


-----更新统计信息
EXEC sp_updatestats


----还原多用户模式
SET @strSQL = 'ALTER DATABASE [' + @strDataBaseName + '] SET MULTI_USER;';
EXEC(@strSQL);


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SysGetBaseInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SysGetBaseInfo]
GO









/*
	作者：谢吉康
	日期：2004-11-24
	描述：基本信息的选择
*/
CREATE PROCEDURE GP_SysGetBaseInfo
(
	@OperatorID		varchar(50),		--操作员ID
	@TableName		varchar(50),		--基本信息表名称
	@TypeId			varchar(50)			--基本信息的Id
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SonNum int			--当前ID的节点数
		
IF @TableName = 'BType'
	BEGIN
		SELECT @SonNum = SonNum FROM BType WHERE TypeId = @TypeId AND Deleted = 0
		
		IF @SonNum>=1 
			SELECT	TypeId,
					SonNum,
					UserCode,
					FullName
			FROM	BType
			WHERE	ParId = @TypeId
					AND Deleted = 0
					AND (TypeId LIKE @MBTypeId+'%' OR TypeId LIKE @MBTypeId2+'%')
			ORDER BY
					UserCode
		ELSE
			SELECT	TypeId,
					SonNum,
					UserCode,
					FullName
			FROM	BType
			WHERE	TypeId = @TypeId
					AND Deleted = 0					
					AND (TypeId LIKE @MBTypeId+'%' OR TypeId LIKE @MBTypeId2+'%')
			ORDER BY
					UserCode
	END
ELSE
	IF @TableName = 'Employee'
		BEGIN
			SELECT @SonNum = SonNum FROM Employee WHERE TypeId = @TypeId AND Deleted = 0

			IF @SonNum>=1 
				SELECT	TypeId,
						SonNum,
						UserCode,
						FullName
				FROM	Employee
				WHERE	ParId = @TypeId
						AND Deleted = 0
						AND TypeId LIKE @METypeId+'%'
				ORDER BY
						UserCode
			ELSE
				SELECT	TypeId,
						SonNum,
						UserCode,
						FullName
				FROM	Employee
				WHERE	TypeId = @TypeId
						AND Deleted = 0		
						AND TypeId LIKE @METypeId+'%'
				ORDER BY
						UserCode
		END
	ELSE
		IF @TableName = 'STock'
			BEGIN
				SELECT @SonNum = SonNum FROM Stock WHERE TypeId = @TypeId AND Deleted = 0

				IF @SonNum>=1 
					SELECT	TypeId,
							SonNum,
							UserCode,
							FullName
					FROM	STock
					WHERE	ParId = @TypeId
							AND Deleted = 0
							AND TypeId LIKE @MKTypeId+'%'
					ORDER BY
							UserCode
				ELSE
					SELECT	TypeId,
							SonNum,
							UserCode,
							FullName
					FROM	STock
					WHERE	TypeId = @TypeId
							AND Deleted = 0		
							AND TypeId LIKE @MKTypeId+'%'
					ORDER BY
							UserCode
			END
		ELSE
			IF @TableName = 'AType'
				BEGIN
					SELECT @SonNum = SonNum FROM AType WHERE TypeId = @TypeId AND Deleted = 0
		
					IF @SonNum>=1 
						SELECT	TypeId,
								SonNum,
								UserCode,
								FullName
						FROM	AType
						WHERE	ParId = @TypeId
								AND Deleted = 0
								AND TypeId LIKE @MATypeId+'%'
						ORDER BY
								UserCode
					ELSE
						SELECT	TypeId,
								SonNum,
								UserCode,
								FullName
						FROM	AType
						WHERE	TypeId = @TypeId
								AND Deleted = 0		
								AND TypeId LIKE @MATypeId+'%'
						ORDER BY
								UserCode
				END
			ELSE
				IF @TableName = 'PType'
					BEGIN
						SELECT @SonNum = SonNum FROM PType WHERE TypeId = @TypeId AND Deleted = 0

						IF @SonNum>=1 
							SELECT	TypeId,
									SonNum,
									UserCode,
									FullName
							FROM	PType
							WHERE	ParId = @TypeId
									AND Deleted = 0
									AND TypeId LIKE @MPTypeId+'%'
							ORDER BY
									UserCode
						ELSE
							SELECT	TypeId,
									SonNum,
									UserCode,
									FullName
							FROM	PType
							WHERE	TypeId = @TypeId
									AND Deleted = 0		
									AND TypeId LIKE @MPTypeId+'%'
							ORDER BY

									UserCode
					END
				ELSE
					IF @TableName = 'Department'
						BEGIN
							SELECT @SonNum = SonNum FROM Department WHERE TypeId = @TypeId AND Deleted = 0
	
							IF @SonNum>=1 
								SELECT	TypeId,
										SonNum,
										UserCode,
										FullName
								FROM	Department
								WHERE	ParId = @TypeId
										AND Deleted = 0
										AND TypeId LIKE @MPTypeId+'%'
								ORDER BY
										UserCode
							ELSE
								SELECT	TypeId,
										SonNum,
										UserCode,
										FullName
								FROM	Department
								WHERE	TypeId = @TypeId
										AND Deleted = 0		
										AND TypeId LIKE @MPTypeId+'%'
								ORDER BY
										UserCode
						END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SysReportConditionDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SysReportConditionDeal]
GO








/*
	作者：谢吉康
	日期：2004-11-04
	描述：处理系统报表条件
	SELECT * FROM sp_sysReportCondition
	SELECT * FROM sp_sysReportCondition_Item
*/
CREATE  PROCEDURE GP_SysReportConditionDeal
(
	@sysReportId			int,		--系统报表的ID
	@sysReportContionId		int,		--系统报表的条件Id
	@Action					char(10)	--操作类型 A.新增   M.修改  D删除
)
--@encode$--
AS

DECLARE @paramValue	int,			--参数的个数
		@funName    varchar(256),	--函数名称
		@maxOrderId	int,			--排序的最大Id
		@maxSortId	int,			--顺序ID
		@whileI		int				--计数器

SET @maxOrderId = 1
SET @maxSortId  = 1
SET @whileI = 1

SELECT  @paramValue = paramCount,@funName = funName FROM sp_SysReportConditionList WHERE [ID] = @sysReportContionId

IF @Action = 'A'		--新增
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 * FROM sp_SysProce WHERE sp_ReportId = @sysReportId)
			BEGIN
				--RAISERROR('系统报表中不存在该报表，请确认后重试！',16,1)
				RETURN -1
			END
		ELSE
			BEGIN
				SELECT @maxOrderId = ISNULL(Max(OrderId),0),@maxSortId=ISNULL(Max(SortId),0) FROM sp_sysReportCondition WHERE sp_Id = @sysReportId

				IF @maxOrderId = 0
					SET @maxOrderId = 1
				ELSE
					SET @maxOrderId = @maxOrderId + 1

				IF @maxSortId = 0
					SET @maxSortId = 1
				ELSE
					SET @maxSortId = @maxOrderId + 1

				INSERT INTO sp_sysReportCondition(sp_Id,funName,orderId,sortId)VALUES(@sysReportId,@funName,@maxOrderId,@maxSortId)

				IF @@ROWCOUNT = 0
					BEGIN
						--RAISERROR('写系统报表条件主表失败，请确认后重试！',16,1)
						RETURN -2
					END
				
				WHILE @whileI<=@paramValue
					BEGIN
						INSERT INTO sp_sysReportCondition_Item(sp_Id,orderId,paramValue)VALUES(@sysReportId,@maxOrderId,null)
						
						IF @@ROWCOUNT = 0
							BEGIN
								--RAISERROR('写系统报表条件主表失败，请确认后重试！',16,1)
								RETURN -3
								BREAK
							END

						SET @whileI = @whileI + 1
					END

				--RAISERROR('写系统报表条件成功！',16,1)
				RETURN 0				
			END
	END
ELSE IF @Action = 'M'	--修改
		BEGIN
			RETURN 0
		END
ELSE					--删除
	BEGIN
		RETURN 0
	END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SysReportConditionSort]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SysReportConditionSort]
GO







/*
	作者：谢吉康
	日期：2004-10-11
	描述：系统报表条件排序调整	
*/
CREATE PROCEDURE GP_SysReportConditionSort
(
	@SysReportId				int,				--系统报表的ID
	@SysReportItemId			int,				--报表子项的ID
	@SysReportSortId			int					--排序的ID
)
--@encode$--
AS
SET NOCOUNT ON

-- 开始事务
BEGIN TRAN
UPDATE	sp_sysReportCondition
SET		SortId = @SysReportSortId
WHERE	sp_Id = @SysReportId 
		AND [ID]=@SysReportItemId

IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		--RAISERROR('更新记录失败，请确认后重试！',16,1)
		RETURN -1
	END
ELSE
	BEGIN
		COMMIT TRAN
		--RAISERROR('更新记录成功，请确认后重试！',16,1)
		RETURN 0
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SysReportDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SysReportDeal]
GO








/*
	作者：谢吉康
	日期：2004-10-18
	描述：系统报表的新增、修改
*/
CREATE PROCEDURE GP_SysReportDeal
(
	@repId		int,				--报表ID
	@Action		varchar(10),		--操作类型  A.新增    M.修改
	@SysCode	int,				--报表编号
	@SysName	varchar(256),		--报表名称
	@SysProc	varchar(256),		--存储过程
	@isTree		int,				--是否是树型表   1.是    0.否
	@Height		varchar(50),		--报表条件页的高度
	@Width		varchar(50)			--报表条件页的宽度
)	
--@encode$--
AS
SET NOCOUNT ON
BEGIN	
	IF @Action='A'		--新增系统报表
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 * FROM sp_SysProce WHERE sp_ReportId = @SysCode)
				BEGIN
					INSERT INTO sp_SysProce
					(
						sp_ReportId,
						sp_ReportName,
						sp_ProcName,
						is_Tree,
						Height,
						Width
					)
					VALUES
					(
						@SysCode,
						@SysName,
						@SysProc,
						@isTree,
						@Height,
						@Width
					)
				
					IF @@ROWCOUNT = 0
						BEGIN
							--RAISERROR('录入报表失败，请确定后重试！',16,1)
							RETURN -2
						END
					ELSE
						BEGIN
							--RAISERROR('录入报表成功，请确定后重试！',16,1)
							RETURN 0
						END
				END
			ELSE
				BEGIN
					--RAISERROR('相同编号的报表已存在，请确定后重试！',16,1)
					RETURN -1
				END
		END
	ELSE				--修改系统报表
		BEGIN
			IF EXISTS(SELECT TOP 1 * FROM sp_SysProce WHERE sp_ReportId = @repId)
				BEGIN
					UPDATE	sp_SysProce
					SET		sp_ReportName = @SysName,
							sp_ProcName	  = @SysProc,
							is_Tree       = @isTree,
							Height		  = @Height,
							Width		  = @Width
					WHERE	sp_ReportId   = @repId

					IF @@ROWCOUNT = 0
						BEGIN
							--RAISERROR('修改报表失败，请确定后重试！',16,1)
							RETURN -2
						END
					ELSE
						BEGIN
							--RAISERROR('修改报表成功，请确定后重试！',16,1)
							RETURN 0
						END
				END
			ELSE
				BEGIN
					--RAISERROR('需要修改的报表不存在，请确定后重试！',16,1)
					RETURN -1
				END
		END
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SysReportDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SysReportDelete]
GO










/*
	作者：谢吉康
	日期：2004-10-18
	描述：系统报表的删除
*/
CREATE PROCEDURE GP_SysReportDelete
(
	@SysReportId	int	--系统报表ID
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 * FROM sp_SysProce WHERE sp_ReportId = @SysReportId)
	BEGIN

		DELETE FROM sp_SysTableName WHERE sp_Id = @SysReportId

		DELETE FROM sp_SysTEnItem WHERE sp_Id = @SysReportId

		DELETE FROM sp_SysProce WHERE sp_ReportId = @SysReportId

		DELETE FROM sp_sysReportCondition WHERE sp_Id = @SysReportId

		DELETE FROM sp_sysReportCondition_Item WHERE sp_Id = @SysReportId

		IF @@ROWCOUNT = 0
			BEGIN
				--RAISERROR('删除报表失败，请确认后重试！')
				RETURN -2
			END
		ELSE
			BEGIN
				--RAISERROR('删除报表成功，请确认后重试！')
				RETURN 0
			END
	END
ELSE
	BEGIN
		--RAISERROR('系统中没有需要删除的报表，请确认后重试！')
		RETURN -1
	END










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SysReportGenScript]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SysReportGenScript]
GO











/*
	作者：谢吉康
	日期：2005-02-20
	描述：生成系统报表的SQL脚本
*/
CREATE PROCEDURE Gp_SysReportGenScript
(
	@ReportId		varchar(8000),				--报表的ID
	@Sp_SysProce 	varchar(8000) OUTPUT,		--输出的脚本字符串Sp_SysProce
	@Sp_SysCondi 	varchar(8000) OUTPUT,		--输出的脚本字符串sp_sysReportCondition
	@Sp_SysConIt 	varchar(8000) OUTPUT,		--输出的脚本字符串sp_sysReportCondition_Item
	@Sp_SysTabN 	varchar(8000) OUTPUT,		--输出的脚本字符串sp_SysTableName
	@Sp_SysTabI 	varchar(8000) OUTPUT		--输出的脚本字符串sp_SysTEnItem
)
--@encode$--
AS
DECLARE @MySQL	varchar(8000)

SET	@ReportId = 1

--处理Sp_SysProce SELECT * FROM Sp_SysProce
DECLARE @Sp_ReportName	varchar(100),
		@Sp_ProcName	varchar(200),
		@is_Tree		char(10),
		@hidd_Value		varchar(100),
		@Height			varchar(50),
		@Width			varchar(50)

SELECT	@Sp_ReportName = Sp_ReportName,
		@Sp_ProcName   = Sp_ProcName,
		@is_Tree	   = is_Tree,
		@hidd_Value	   = hidd_Value,
		@Height		   = Height,
		@Width         = Width
FROM	Sp_SysProce
WHERE	Sp_ReportId = @ReportId

IF @@ROWCOUNT <> 0
	BEGIN
		SET	@MySQL = '--处理Sp_SysProce
IF EXISTS(SELECT * FROM Sp_SysProce WHERE Sp_ReportId = '+@ReportId+')
	UPDATE	Sp_SysProce
	SET 	Sp_ReportName = '''+@Sp_ReportName+''',
		Sp_ProcName   = '''+@Sp_ProcName+''',
		is_Tree	     = '+@is_Tree+',
		hidd_Value    = '''+@hidd_Value+''',
		Height 	     = '+@Height+',
		Width         = '+@Width+'
	WHERE	Sp_ReportId = '+@ReportId+'
ELSE 
	INSERT INTO Sp_SysProce
	(
		Sp_ReportId,
		Sp_ReportName,
		Sp_ProcName,
		is_Tree,
		hidd_Value,
		Height,
		Width
	)
	VALUES
	(
		'+@ReportId+',
		'''+@Sp_ReportName+''',
		'''+@Sp_ProcName+''',
		'+@is_Tree+',
		'''+@hidd_Value+''',
		'+@Height+',
		'+@Width+'
	)'
	END
SET @MySQL = @MySQL + '
GO'+'
--处理sp_sysReportCondition'

--处理sp_sysReportCondition SELECT * FROM sp_sysReportCondition
DECLARE @funName varchar(1000),
		@OrderId varchar(100),
		@SortId  varchar(100),
		@ConSQL  varchar(8000)

SET @ConSQL = ''

DECLARE Tmp_ConCursor CURSOR FOR
	SELECT	funName,OrderId,SortId FROM sp_sysReportCondition

	OPEN Tmp_ConCursor

	FETCH NEXT FROM Tmp_ConCursor INTO @FunName,@OrderId,@SortId

	WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @ConSQL = @ConSQL+' 
IF EXISTS(SELECT * FROM sp_sysReportCondition WHERE Sp_Id = '+@ReportId+' AND FunName = '''+@FunName+''' AND OrderId = '+@OrderId+' AND SortId = '+@SortId+')
	UPDATE	sp_sysReportCondition
	SET	funName = '''+@FunName+''',
		OrderId = '''+@OrderId+''',
		SortId  = '''+@SortId+'''
	WHERE	Sp_Id = '+@ReportId+'
			AND funName = '''+@FunName+'''
			AND OrderId = '''+@OrderId+'''
			AND SortId  = '''+@SortId+'''
ELSE
	INSERT INTO sp_sysReportCondition
	(
		Sp_Id,
		FunName,
		OrderId,
		SortId
	)
	VALUES
	(
		'+@ReportId+',
		'''+@FunName+''',
		'''+@OrderId+''',
		'''+@SortId+'''
	)
GO '
			FETCH NEXT FROM Tmp_ConCursor INTO @FunName,@OrderId,@SortId
		END

	CLOSE Tmp_ConCursor
	DEALLOCATE Tmp_ConCursor

--处理sp_sysReportCondition_Item  SELECT * FROM sp_sysReportCondition_Item
DECLARE @IOrderId	varchar(100),
		@paramValue	varchar(1000),
		@Con_Item	varchar(8000)

SET @Con_Item = '
--处理sp_sysReportCondition_Item'

DECLARE ITmp_ConCursor CURSOR FOR
	SELECT	OrderId,paramValue FROM sp_sysReportCondition_Item

	OPEN ITmp_ConCursor

	FETCH NEXT FROM ITmp_ConCursor INTO @IOrderId,@paramValue

	WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @Con_Item = @Con_Item+' 
IF EXISTS(SELECT * FROM sp_sysReportCondition_Item WHERE Sp_Id = '+@ReportId+' AND OrderId = '+@IOrderId+' AND paramValue='''+@paramValue+''')
	UPDATE	sp_sysReportCondition_Item
	SET	OrderId = '''+@IOrderId+''',
		paramValue  = '''+@paramValue+'''
	WHERE	Sp_Id = '+@ReportId+'			
			AND OrderId = '''+@IOrderId+'''
			AND paramValue  = '''+@paramValue+'''
ELSE
	INSERT INTO sp_sysReportCondition_Item
	(
		Sp_Id,
		OrderId,
		paramValue
	)
	VALUES
	(
		'+@ReportId+',
		'''+@IOrderId+''',
		'''+@paramValue+'''
	)
GO '
			FETCH NEXT FROM ITmp_ConCursor INTO @IOrderId,@paramValue
		END

	CLOSE ITmp_ConCursor
	DEALLOCATE ITmp_ConCursor

--处理sp_SysTableName  SELECT * FROM sp_SysTableName
DECLARE @NMaxId			varchar(100),
		@NOrderId		varchar(100),
		@Sp_TableName	varchar(1000),
		@TableName		varchar(8000)

SET @TableName = '
--处理sp_SysTableName'

DECLARE NTmp_ConCursor CURSOR FOR
	SELECT	[Id],OrderId,Sp_TableName FROM sp_SysTableName

	OPEN NTmp_ConCursor

	FETCH NEXT FROM NTmp_ConCursor INTO @NMaxId,@NOrderId,@Sp_TableName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @TableName = @TableName+' 
IF EXISTS(SELECT * FROM sp_SysTableName WHERE [Id] = '+@NMaxId+' AND Sp_Id = '+@ReportId+' AND OrderId = '+@NOrderId+' AND Sp_TableName='''+@Sp_TableName+''')
	UPDATE	sp_SysTableName
	SET	OrderId = '''+@NOrderId+''',
		Sp_TableName  = '''+@Sp_TableName+'''
	WHERE	[Id] = '+@NMaxId+'
			AND Sp_Id = '+@ReportId+'			
			AND OrderId = '''+@NOrderId+'''
			AND Sp_TableName  = '''+@Sp_TableName+'''
ELSE
	INSERT INTO sp_SysTableName
	(
		[Id],
		Sp_Id,
		OrderId,
		Sp_TableName
	)
	VALUES
	(
		'+@NMaxId+',
		'+@ReportId+',
		'''+@NOrderId+''',
		'''+@Sp_TableName+'''
	)
GO '
			FETCH NEXT FROM NTmp_ConCursor INTO @NMaxId,@NOrderId,@Sp_TableName
		END

	CLOSE NTmp_ConCursor
	DEALLOCATE NTmp_ConCursor		

--处理sp_SysTEnItem SELECT * FROM sp_SysTEnItem
DECLARE @IMaxId					varchar(100),
		@TableIName 			varchar(8000),
		@sp_SysTableName_Id		varchar(100),
		@En_Item				varchar(200),
		@Align					varchar(50),
		@Format					varchar(2),
		@Format_Num				varchar(2),
		@is_Sum					varchar(2),
		@TiOrderId				varchar(2),
		@is_Hidden				varchar(2)

SET @TableIName = '
--处理sp_SysTEnItem
'
DECLARE NTmp_ItemCursor CURSOR FOR
	SELECT	[Id],sp_SysTableName_Id,En_Item,Align,Format,Format_Num,is_Sum,OrderId,is_Hidden FROM sp_SysTEnItem

	OPEN NTmp_ItemCursor

	FETCH NEXT FROM NTmp_ItemCursor INTO @IMaxId,@sp_SysTableName_Id,@En_Item,@Align,@Format,@Format_Num,@is_Sum,@TiOrderId,@is_Hidden

	WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @TableIName = @TableIName+' 
IF EXISTS(SELECT * FROM sp_SysTEnItem WHERE Sp_Id = '+@ReportId+' AND En_Item = '''+@En_Item+''')
	UPDATE	sp_SysTEnItem
	SET	[Id] = '+@IMaxId+',
		sp_SysTableName_Id = '''+@sp_SysTableName_Id+''',
		En_Item  = '''+@En_Item+''',
		Align    ='''+@Align+''',
		Format   ='''+@Format+''',
		Format_Num = '''+@Format_Num+''',
		is_Sum = '''+@is_Sum+''',
		OrderId='''+@TiOrderId+''',
		is_Hidden='''+@is_Hidden+'''
	WHERE	[Id] = '+@IMaxId+'
			AND Sp_Id = '+@ReportId+'			
			AND sp_SysTableName_Id = '''+@sp_SysTableName_Id+'''
ELSE
	INSERT INTO sp_SysTEnItem
	(
		[Id],
		Sp_Id,
		sp_SysTableName_Id,
		En_Item,
		Align,
		Format,
		Format_Num,
		is_Sum,
		OrderId,
		is_Hidden
	)
	VALUES
	(
		'+@IMaxId+',
		'+@ReportId+',
		'''+@sp_SysTableName_Id+''',
		'''+@En_Item+''',
		'''+@Align+''',
		'''+@Format+''',
		'''+@Format_Num+''',
		'''+@is_Sum+''',
		'''+@TiOrderId+''',
		'''+@is_Hidden+'''
	)
GO '
			FETCH NEXT FROM NTmp_ItemCursor INTO @IMaxId,@sp_SysTableName_Id,@En_Item,@Align,@Format,@Format_Num,@is_Sum,@TiOrderId,@is_Hidden
		END

	CLOSE NTmp_ItemCursor
	DEALLOCATE NTmp_ItemCursor	

SET	@Sp_SysProce = @MySQL
SET @Sp_SysCondi = @ConSQL
SET @Sp_SysConIt = @Con_Item
SET @Sp_SysTabN  = @TableName
SET @Sp_SysTabI  = @TableIName









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SysReportItemDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SysReportItemDeal]
GO









/*
	作者：谢吉康
	日期：2004-10-15
	描述：对相关的系统报表【表头和表体数据】进行维护
*/
CREATE PROCEDURE GP_SysReportItemDeal
(
	@reportId		int,				--报表ID
	@Action			varchar(20),		--操作类型   A：新增       M：修改        D：删除
	@ATarget		varchar(20),		--操作标识   H：表头信息   B：表体信息
	@ATargetValue	int,				--操作的具体ID值
	@ATargetCon		varchar(256),		--操作的具体值
	@Align			varchar(20)='',		--对齐方式
	@IsFormat		int='0',			--是否格式化
	@FormatNum		varchar(20)='0',	--格式化位数
	@IsSum			int='0',			--是否需要合计
	@IsHidden		int='0'				--是否是隐藏列
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @SysTableName_Id		int,	--表头字段的自动增长的ID值
		@MaxOrderId				int,	--字段排序的最大值OrderId
		@RecordCount			int,	--记录数目
		@MaxId					int		--计算ID的最大值

--计算Id的最大值
IF @ATarget = 'H'	
	SELECT @MaxId = ISNULL((MAX(Id)+1),'') FROM sp_SysTableName WHERE sp_Id = @reportId
ELSE
	SELECT @MaxId = ISNULL((MAX(Id)+1),'') FROM sp_SysTEnItem   WHERE sp_Id = @reportId

IF @MaxId = 0 
	SET @MaxId = 1

--计算OrderId的最大值
IF @ATarget = 'H'	
	SELECT @MaxOrderId = ISNULL((MAX(OrderId)+1),'') FROM sp_SysTableName WHERE sp_Id = @reportId
ELSE
	SELECT @MaxOrderId = ISNULL((MAX(OrderId)+1),'') FROM sp_SysTEnItem   WHERE sp_Id = @reportId

IF @MaxOrderId = 0
	SET @MaxOrderId = 1

IF @ATarget = 'H'				--处理表头信息
	BEGIN
		IF @Action = 'A'		--新增表头字段
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM sp_SysProce WHERE sp_ReportId = @reportId)
					BEGIN
						BEGIN TRAN
							INSERT INTO sp_SysTableName([Id],sp_Id,sp_TableName,OrderId)VALUES(@MaxId,@reportId,@ATargetCon,@MaxOrderId)
							
							IF @@ROWCOUNT<>0
								SET @SysTableName_Id = @MaxId
							ELSE
								BEGIN
									--RAISERROR('录入报表表头信息失败，请确认后重试！',16,1)
									RETURN -2
								END								
							INSERT INTO sp_SysTEnItem([Id],sp_Id,sp_SysTableName_Id,En_Item,OrderId)VALUES(@MaxId,@reportId,@SysTableName_Id,@ATargetCon,@MaxOrderId)
						
						IF @@ROWCOUNT <> 0
							BEGIN
								COMMIT TRAN
								--RAISERROR('录入报表表头信息成功！',16,1)
								RETURN 0
							END
						ELSE
							BEGIN
								--RAISERROR('录入报表表头信息失败，请确认后重试！',16,1)
								RETURN -3
							END
					END
				ELSE
					BEGIN
						--RAISERROR('系统报表主表中不存在该报表，请确认后重试！',16,1)
						RETURN -1
					END
			END
		ELSE IF @Action = 'M'	--修改表头字段内容
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM sp_SysTableName WHERE sp_Id = @reportId AND [ID] = @ATargetValue)
					BEGIN
						UPDATE sp_SysTableName SET sp_TableName = @ATargetCon WHERE sp_Id = @reportId AND [ID] = @ATargetValue
						
						IF @@ROWCOUNT <> 0
							BEGIN
								--RAISERROR('修改报表表头信息成功！',16,1)
								RETURN 0
							END
						ELSE
							BEGIN
								--RAISERROR('修改报表表头信息失败，请确认后重试！',16,1)
								RETURN -2
							END
					END
				ELSE
					BEGIN
						--RAISERROR('系统报表主表中不存在该报表，请确认后重试！',16,1)
						RETURN -1
					END					
			END
		ELSE					--删除表头字段内容
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM sp_SysTableName WHERE sp_Id = @reportId AND [ID] = @ATargetValue)
					BEGIN
						BEGIN TRAN
							--清除隐藏字段
							SELECT @RecordCount = COUNT(sp_Id) FROM sp_SysTableName WHERE sp_Id = @reportId
							IF @RecordCount = 1
								UPDATE sp_SysProce SET Hidd_Value = '' WHERE sp_reportId = @reportId

							DELETE FROM sp_SysTableName WHERE sp_Id = @reportId AND [ID] = @ATargetValue
							DELETE FROM sp_SysTEnItem   WHERE sp_Id = @reportId AND sp_SysTableName_Id = @ATargetValue						

						IF @@ROWCOUNT <> 0
							BEGIN
								COMMIT TRAN
								--RAISERROR('删除报表表头信息成功！',16,1)
								RETURN 0
							END
						ELSE
							BEGIN
								--RAISERROR('删除报表表头信息失败，请确认后重试！',16,1)
								RETURN -2
							END
					END
				ELSE
					BEGIN
						--RAISERROR('系统报表主表中不存在该报表，请确认后重试！',16,1)
						RETURN -1
					END									
			END
	END
ELSE		--操作表体字段内容
	BEGIN
		IF @Action = 'A'		--新增表体字段
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM sp_SysProce WHERE sp_ReportId = @reportId)
					BEGIN
						BEGIN TRAN

							IF @IsHidden = 1
								UPDATE	sp_SysProce SET hidd_Value = @ATargetCon WHERE sp_reportId = @reportId

							INSERT INTO sp_SysTableName([Id],sp_Id,sp_TableName,OrderId)VALUES(@MaxId,@reportId,@ATargetCon,@MaxOrderId)

							IF @@ROWCOUNT <> 0
								SET @SysTableName_Id = @MaxId
							ELSE
								BEGIN
									--RAISERROR('录入报表表体信息失败，请确认后重试！',16,1)
									RETURN -2
								END
					
							INSERT INTO sp_SysTEnItem([Id],sp_Id,sp_SysTableName_Id,En_Item,Align,[Format],Format_Num,is_Sum,is_Hidden,OrderId)
										VALUES(@MaxId,@reportId,@SysTableName_Id,@ATargetCon,@Align,@IsFormat,@FormatNum,@IsSum,@IsHidden,@MaxOrderId)
						

						IF @@ROWCOUNT <> 0
							BEGIN
								COMMIT TRAN
								--RAISERROR('录入报表表体信息成功！',16,1)
								RETURN 0
							END
						ELSE
							BEGIN
								--RAISERROR('录入报表表体信息失败，请确认后重试！',16,1)
								RETURN -3
							END
					END
				ELSE
					BEGIN
						--RAISERROR('系统报表主表中不存在该报表，请确认后重试！',16,1)
						RETURN -1
					END				
			END
		ELSE IF @Action = 'M'	--修改表体字段内容
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM sp_SysTableName WHERE sp_Id = @reportId AND [ID] = @ATargetValue)
					BEGIN
						IF @IsHidden = 1
							UPDATE	sp_SysProce SET hidd_Value = @ATargetCon WHERE sp_reportId = @reportId

						UPDATE 	sp_SysTEnItem 
						SET 	En_Item 	= 	@ATargetCon,
								Align   	= 	@Align,
								[Format]	= 	@IsFormat,
								Format_Num	=	@FormatNum,
								is_Sum		=   @IsSum,
								is_Hidden	= 	@isHidden
						WHERE 	sp_Id = @reportId 
								AND sp_SysTableName_Id = @ATargetValue

						IF @@ROWCOUNT <> 0
							BEGIN
								--RAISERROR('修改报表表体信息成功！',16,1)
								RETURN 0
							END
						ELSE
							BEGIN
								--RAISERROR('修改报表表体信息失败，请确认后重试！',16,1)
								RETURN -2
							END
					END
				ELSE
					BEGIN
						--RAISERROR('系统报表主表中不存在该报表，请确认后重试！',16,1)
						RETURN -1
					END										
			END
		ELSE					--删除表体字段
			BEGIN
				IF EXISTS(SELECT TOP 1 * FROM sp_SysTableName WHERE sp_Id = @reportId AND [ID] = @ATargetValue)
					BEGIN
						BEGIN TRAN
							--清除隐藏字段
							SELECT @RecordCount = COUNT(sp_Id) FROM sp_SysTableName WHERE sp_Id = @reportId
							IF @RecordCount = 1
								UPDATE sp_SysProce SET Hidd_Value = '' WHERE sp_reportId = @reportId

							DELETE FROM sp_SysTableName WHERE sp_Id = @reportId AND [ID] = @ATargetValue
							DELETE FROM sp_SysTEnItem   WHERE sp_Id = @reportId AND sp_SysTableName_Id = @ATargetValue						
						
						IF @@ROWCOUNT <> 0
							BEGIN
								COMMIT TRAN
								--RAISERROR('删除报表表头信息成功！',16,1)
								RETURN 0
							END
						ELSE
							BEGIN
								--RAISERROR('删除报表表头信息失败，请确认后重试！',16,1)
								RETURN -2
							END
					END
				ELSE
					BEGIN
						--RAISERROR('系统报表主表中不存在该报表，请确认后重试！',16,1)
						RETURN -1
					END													
			END
		END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SysReportItemSort]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SysReportItemSort]
GO







/*
	作者：谢吉康
	日期：2004-10-11
	描述：系统报表条件排序调整	
*/
CREATE PROCEDURE GP_SysReportItemSort
(
	@SysReportId				int,				--系统报表的ID
	@SysReportHeadOrBody		varchar(10),		--表头或表尾       H:表头   B:表尾
	@SysReportItemId			int,				--报表子项的ID
	@SysReportOrderId			int					--排序的ID
)
--@encode$--
AS
SET NOCOUNT ON

-- 开始事务
BEGIN TRAN
UPDATE	sp_SysTableName
SET		OrderId = @SysReportOrderId
WHERE	sp_Id = @SysReportId 
		AND [ID]=@SysReportItemId

IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		--RAISERROR('更新记录失败，请确认后重试！',16,1)
		RETURN -1
	END

UPDATE	sp_SysTEnItem
SET		OrderId = @SysReportOrderId
WHERE	sp_Id = @SysReportId 
		AND sp_SysTableName_Id=@SysReportItemId

IF @@ROWCOUNT = 0
	BEGIN
		ROLLBACK TRAN
		--RAISERROR('更新记录失败，请确认后重试！',16,1)
		RETURN -2
	END
ELSE
	BEGIN
		COMMIT TRAN
		--RAISERROR('更新记录成功，请确认后重试！',16,1)
		RETURN 0
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_SystemLogOut]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_SystemLogOut]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GO
/*
	作者：谢吉康
	日期：2019-03-08
	描述：系统退出删除操作员
*/

CREATE  PROCEDURE [dbo].Gp_SystemLogOut
(
	@etypeid			VARCHAR(50)		--操作员ID	
)
AS
SET NOCOUNT ON

DECLARE @currentTime	VARCHAR(50),
		@dbName			VARCHAR(500),
		@dogNo			VARCHAR(100)

SET @currentTime = GETDATE()
SET @dbName = db_name()

SET @dogNo = ''
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubName = 'ZCFlag' AND SubValue = '1')
BEGIN
	SELECT @dogNo = SubValue FROM dbo.sysdata1 WHERE SubName = 'DogNo'
END

--删除记录
DELETE FROM dbo.OA_OnlineUser WHERE ETypeId_UserTypeId =@etypeid
DELETE FROM [SysdataDb].dbo.Fx_OnlineUser WHERE ETypeID_UserTypeID = @etypeid AND dbName = @dbName


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SystemRebuild]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SystemRebuild]
GO


/*
	作者：谢吉康
	日期：2003-02-09
	描述：系统重建
	
	修改：2013-05-16 周华 开放内部应收期初
	
	exec GP_SystemRebuild @etypeID=N'00001',@bRebulidIni=0,@bRebulidDraft=1,@bitRecPrice=1,@bitEventLog=1,@bitPriceTrack=1,@bitRecSalePrice=1,@bitMessage=1,@bitPosdata=0,@bitRecSTypeBuyPrice=1,@bitRecSTypeSalePrice=1,@bitSTypePriceTrack=1,@clearauditflow=1,@clearStopOrder=1,@clearCompleteOrder=1,@clearAllOrder=1,@clearCompleteAllotApply=1,@clearnocompleteallotapply=1,@clearcompletegetbillapply=1,@clearnocompletegetbillapply=1,@logid=N'416'
*/
CREATE       PROCEDURE GP_SystemRebuild
(
    @etypeID				VARCHAR(50), 
	@bRebulidIni			bit,	-- 是否清除期初；0 - 不清除，1 - 清除
	@bRebulidDraft			bit,	-- 是否清除草稿；0 - 不清除，1 - 清除
	@bitRecPrice			bit,	-- 是否清除最近进价；0 - 不清除，1 - 清除
	@bitEventLog			bit,	-- 是否清除操作日志
	@bitPriceTrack			bit,	-- 是否清除价格跟踪信息；0 - 不清除，1 - 清除
	@bitRecSalePrice		BIT,	-- 是否清除商品最近售价 0 - 不清除，1 - 清除
	@bitMessage				BIT,	-- 是否清除聊天记录；0 - 不清除，1 - 清除
	@bitPosdata				BIT,	-- 是否清除小票数据
	@bitRecSTypeBuyPrice	BIT,	-- 是否清除分支机构间最近进价 0 - 不清除， 1 - 清除
	@bitRecSTypeSalePrice	BIT,	-- 是否清除分支机构间最近售价 0 - 不清除， 1 - 清除
	@bitSTypePriceTrack		BIT,	-- 是否清除分支机构间价格跟踪信息 0 - 不清除， 1 - 清除
	@clearauditflow			BIT,	-- 是否除审核流程	0 - 不清除， 1 - 清除
	@clearStopOrder			BIT,	-- 是否清除已中止订单	0 - 不清除， 1 - 清除
	@clearCompleteOrder		BIT,	-- 是否清除已完成订单	0 - 不清除， 1 - 清除
	@clearAllOrder			BIT,	-- 是否清除所有订单	0 - 不清除， 1 - 清除
	@clearCompleteAllotApply BIT,--是否清除已完成的调货申请单 0-不清除 1-清除
	@clearNoCompleteAllotApply BIT,--是否清除未完成的调货申请单 0-不清除 1-清除
	@clearcompletegetbillapply BIT,--是否清除已完成的要货申请单 0-不清除 1-清除
	@clearnocompletegetbillapply BIT,--是否清除未完成的要货申请单 0-不清除 1-清除
	@logid					INT 	--当前操作日志ID
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN TRAN Rebulid
	IF EXISTS  (SELECT  * FROM dbo.SysObjects WHERE ID = object_id(N'[Cost_NoRelog]') AND OBJECTPROPERTY(ID, 'IsTable') = 1) 
	BEGIN
		TRUNCATE TABLE Cost_NoRelog    -- 不知道什么表
	END	
	delete from sysdata where SubNo=999
	insert into sysdata select 999,'sysbuild by',TypeID,CAST(FullName AS varchar(30)) from Employee where TypeId = @etypeID
	-----------------------------------------构建操作明细信息 start-------------------------------------------------------------
	IF @logid>0
	BEGIN
		DECLARE @logdata VARCHAR(2000)
		SET @logdata='cInit='+CAST(@bRebulidIni AS varchar(30))+';cDraft='+CAST(@bRebulidDraft AS varchar(30))+';chkRecPrice='+CAST(@bRebulidDraft AS varchar(30))
		+';chkEventLog='+CAST(@bitEventLog AS varchar(30))+';chkPriceTrack='+CAST(@bRebulidDraft AS varchar(30))+';chkRecSalePrice='+CAST(@bitRecSalePrice AS varchar(30))
		+';chkclearmessage='+CAST(@bitMessage AS varchar(30))+';chkclearposdata='+CAST(@bitPosdata AS varchar(30))+';chkstyperecbuyprice='+CAST(@bitRecSTypeBuyPrice AS varchar(30))
		+';chkstyperecsaleprice='+CAST(@bitRecSTypeSalePrice AS varchar(30))+';chkstypepricetrack='+CAST(@bitSTypePriceTrack AS varchar(30))+';clearauditflow='+CAST(@clearauditflow AS varchar(30))
		+';clearstoporder='+CAST(@clearStopOrder AS varchar(30))+';clearcompleteorder='+CAST(@clearCompleteOrder AS varchar(30))+';clearallorder='+CAST(@clearAllOrder AS varchar(30))
		+';clearCompleteAllotApply=' + CAST(@clearCompleteAllotApply AS varchar(30)) + ';clearNoCompleteAllotApply=' + CAST(@clearNoCompleteAllotApply AS varchar(30))
		+';clearcompletegetbillapply=' + CAST(@clearcompletegetbillapply AS varchar(30)) + ';clearnocompletegetbillapply=' + CAST(@clearnocompletegetbillapply AS varchar(30))
		UPDATE dbo.EventLog SET LogData=@logdata WHERE id=@logid
	END
	-----------------------------------------构建操作明细信息   end-------------------------------------------------------------	
	
	--系统重建所有锁库数据进行解锁
	TRUNCATE TABLE PT_SaleOrderLockDetail		 		--清除订单锁库信息
	UPDATE Ini_GOODSSTOCKS_QTY SET LockNumber=0 --清楚期初锁库信息
	UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
	UPDATE OrderBill SET LockNumber=0 --清除订单锁库信息
	UPDATE PT_Combin_OrderBillDetail SET LockNumber=0 --清除组合品订单锁库信息	
	
	TRUNCATE TABLE Ac_DeliveryBill_VoucherBill
	-------------------------- 专门对 BillIndex、以及主表在billindex中的期初单据进行处理 start---------------------------------
	DECLARE @columns VARCHAR(max)=''	--表的列名
	IF @bRebulidDraft = 1 AND @bRebulidIni = 1
		BEGIN
			TRUNCATE TABLE BillIndex
			TRUNCATE TABLE BillOperateLog --操作日志
			---------------------主表在billindex中的期初单据-------------
			TRUNCATE TABLE	SaleBill
			TRUNCATE TABLE  PT_Combin_SaleBill
			TRUNCATE TABLE  PT_Combin_SaleBillDetail
			TRUNCATE TABLE	SaleBackBill
			TRUNCATE TABLE  PT_Combin_SaleBackBill
			TRUNCATE TABLE  PT_Combin_SaleBackBillDetail
			TRUNCATE TABLE	buybill
			TRUNCATE TABLE	buybackbill
			TRUNCATE TABLE	SaleGoodsExchangeBill
			TRUNCATE TABLE	BuyGoodsExchangeBill
			TRUNCATE TABLE	CommissionBill
			TRUNCATE TABLE	retailbill
			TRUNCATE TABLE	PreBill				--预收预付
			TRUNCATE TABLE	AdDebtBill			--调账单
			TRUNCATE TABLE	wx_Bill_GetBack		--维修取件单
			TRUNCATE TABLE	wx_Bill_Replace		--整机更换单
			TRUNCATE TABLE	wx_Bill_SendBack	--送修返回单
			TRUNCATE TABLE	wx_bill_goto		--上门维修单
			TRUNCATE TABLE  MoneyBill			--其他收入、费用单、固定资产购买及变卖、费用单
			TRUNCATE TABLE	PriceProtectBill	-- 价保单
			TRUNCATE TABLE	Advantage			--返利、获利单
			TRUNCATE TABLE  BillIndex_CarRepair
			TRUNCATE TABLE  AssetIncDecBill		--固定资产增加减少单
			TRUNCATE TABLE  DepBill;
			--9.7 自定义
			TRUNCATE TABLE dbo.Custom_BillIndex
			TRUNCATE TABLE dbo.Custom_BillDetails
			--<9.7自定义
			TRUNCATE TABLE  CustomBillColumns 
			TRUNCATE TABLE  CustomBillDetailColumns 
			
			TRUNCATE TABLE CommissionBillNew;
			TRUNCATE TABLE CommissionBillNewDetail;
			
			TRUNCATE TABLE CapitalTransfer_Bill --资金调拨单
			TRUNCATE TABLE dbo.VipAddMoneyBatchBill; --会员批量充值
			TRUNCATE TABLE dbo.VipCentToMoneyBill; --会员积分转储值单

			TRUNCATE TABLE AppraisalBill--暂估入库
			TRUNCATE TABLE AppraisalBackBill--暂估退货
			TRUNCATE TABLE SendBill--发出商品出库
			TRUNCATE TABLE SendBackBill--发出商品退货
			TRUNCATE TABLE ReceiptBillIndex --发票主表
			TRUNCATE TABLE ReceiptBill		--发票明细
			TRUNCATE TABLE ChargeOffBill	--往来核销单明细
			
			---------------实物库存 Start---------------
			TRUNCATE TABLE dbo.IniFactStocks	
			TRUNCATE TABLE dbo.IniFactStocks_Qty
			TRUNCATE TABLE dbo.FactStocks
			TRUNCATE TABLE dbo.FactStocks_Qty
			TRUNCATE TABLE dbo.gp_FactPtypeSerial
			TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
			TRUNCATE TABLE dbo.Fact_InOutstocktable
			TRUNCATE TABLE dbo.gp_iniFactPtypeSerial
			TRUNCATE TABLE dbo.FactIndex
			TRUNCATE TABLE dbo.FactInOut
			TRUNCATE TABLE dbo.FactDepotInOut
			TRUNCATE TABLE dbo.FactDepotAllot
			---------------实物库存 End---------------
			
			----------------优惠券 BEGIN---------------
			TRUNCATE TABLE dbo.Coupon_InBill
			TRUNCATE TABLE dbo.Coupon_OutBill
			TRUNCATE TABLE dbo.Coupon_OutBill_Ptype
			TRUNCATE TABLE dbo.Coupon_BackBill
			TRUNCATE TABLE dbo.Coupon_AllotBill
			TRUNCATE TABLE dbo.Coupon_AllotBillStype
			TRUNCATE TABLE dbo.Coupon_CodeInfo
			TRUNCATE TABLE dbo.Coupon_BillUsed	
			TRUNCATE TABLE dbo.Coupon_CodeInOut
			TRUNCATE TABLE dbo.Coupon_BillIndex
			TRUNCATE TABLE dbo.BillMulBrand	
			----------------优惠券 END  --------------
			
			--------------品牌 begin--------------------
			TRUNCATE TABLE dbo.CompleteBrandarTotal
			--------------品牌 end ---------------------
			TRUNCATE TABLE CompleteTotal		--DELETE FROM CompleteTotal  --清掉按单结算表
	
		END
	ELSE
		BEGIN
			IF EXISTS (SELECT NAME FROM sysobjects WHERE type='tr' AND NAME ='DeleteBill')
				DROP TRIGGER DeleteBill
			--------------------------不清理期初单据要对已结算和已开票的数据进行回写-----------------	
			IF @bRebulidIni=0
			BEGIN
				EXEC WriteBackInvoiveAndCompleteData				
			END
			--------------------------对已结算和已开票的数据进行回写 end -----------------	
						
			DELETE FROM wx_Bill_GetBack WHERE NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId= wx_Bill_GetBack.BillNumberId AND BillType ='167' AND (Draft=1 OR IsIni=1))	-- 新维修 - 维修取件单
			DELETE FROM wx_Bill_Replace WHERE NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId= wx_Bill_Replace.BillNumberId AND BillType ='168' AND (Draft=1 OR IsIni=1))	-- 新维修 - 整机更换单
			DELETE FROM wx_Bill_SendBack WHERE NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId= wx_Bill_SendBack.BillNumberId AND BillType ='170' AND (Draft=1 OR IsIni=1))-- 新维修 - 送修返回单
			DELETE FROM wx_Bill_Goto WHERE NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId= wx_Bill_Goto.BillNumberId AND BillType ='172' AND (Draft=1 OR IsIni=1))		-- 新维修 - 上门维修单
			
			IF @bRebulidDraft = 0	--不清除草稿
			BEGIN
				SELECT * INTO #BillIndexd FROM dbo.BillIndex WHERE draft=1 AND ifcheck='f' AND IsIni = 0	AND BillType NOT IN (205,206,414,450)			--billindex
				SELECT * INTO #CommissionBillNewd FROM CommissionBillNew WHERE draft=1 AND ifcheck='f'--未审核的留下
				SELECT  * INTO #CouponIndexd FROM Coupon_BillIndex WHERE draft=1 AND ifcheck='f' AND IsIni = 0					
			END
			IF @bRebulidIni = 0		--不清除期初单据
			BEGIN
				SELECT * INTO #BillIndexi  FROM dbo.BillIndex WHERE IsIni=1;
				SELECT * INTO #ReceiptBillIndexIni FROM dbo.ReceiptBillIndex WHERE IsIni=1;
				SELECT * INTO #CouponIndexi FROM Coupon_BillIndex WHERE  IsIni=1;
				-- 清除按品牌结算明细表 --期初单据 都结算了 期初未结算代销单等的按品牌结算过程要保留下来
				SELECT  * INTO #CompleteTotald FROM dbo.CompleteTotal WHERE MoneyBillID=-1;
				SELECT * INTO #CompleteBrandarTotald FROM dbo.CompleteBrandarTotal WHERE IsIni=1;
			END
				
			TRUNCATE TABLE  BillIndex
			TRUNCATE TABLE CommissionBillNew;
			TRUNCATE TABLE ReceiptBillIndex;
			TRUNCATE TABLE Coupon_BillIndex;
			TRUNCATE TABLE CompleteBrandarTotal
			TRUNCATE TABLE dbo.CompleteTotal
			
			IF @bRebulidDraft = 0	--不清除草稿
			BEGIN
				SET IDENTITY_INSERT BillIndex ON
				SET @columns=dbo.f_getallcolumns('billindex')
				EXEC('INSERT INTO BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #BillIndexd')
				SET IDENTITY_INSERT BillIndex OFF
				
				SET IDENTITY_INSERT CommissionBillNew ON 
				SET @columns=dbo.f_getallcolumns('CommissionBillNew')
				EXEC('INSERT INTO CommissionBillNew ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBillNewd')
				SET IDENTITY_INSERT CommissionBillNew OFF
				
				SET IDENTITY_INSERT Coupon_BillIndex ON 
				SET @columns=dbo.f_getallcolumns('Coupon_BillIndex')
				EXEC('INSERT INTO Coupon_BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #CouponIndexd')
				SET IDENTITY_INSERT Coupon_BillIndex OFF
				
				DROP TABLE #BillIndexd
				DROP TABLE #CommissionBillNewd
				DROP TABLE #CouponIndexd
				
			END
			ELSE
			BEGIN 
				DELETE FROM wx_Bill_GetBack WHERE DraftFlag=1 AND IsIniFlag=0	-- 新维修 - 维修取件单
				DELETE FROM wx_Bill_Replace WHERE DraftFlag=1 AND IsIniFlag=0	-- 新维修 - 整机更换单
				DELETE FROM wx_Bill_SendBack WHERE DraftFlag=1 AND IsIniFlag=0	-- 新维修 - 送修返回单
				DELETE FROM wx_Bill_Goto WHERE DraftFlag=1 AND IsIniFlag=0		-- 新维修 - 上门维修单
			END 
			
			IF @bRebulidIni=0
			BEGIN		
				SET IDENTITY_INSERT BillIndex ON
				SET @columns=dbo.f_getallcolumns('billindex')
				EXEC('INSERT INTO BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #BillIndexi')
				SET IDENTITY_INSERT BillIndex OFF
				
				SET IDENTITY_INSERT ReceiptBillIndex ON
				SET @columns=dbo.f_getallcolumns('ReceiptBillIndex')
				EXEC('INSERT INTO ReceiptBillIndex ('+@columns+') SELECT '+@columns+ ' FROM #ReceiptBillIndexIni')
				SET IDENTITY_INSERT ReceiptBillIndex OFF
				
				SET IDENTITY_INSERT Coupon_BillIndex ON
				SET @columns=dbo.f_getallcolumns('Coupon_BillIndex')
				EXEC('INSERT INTO Coupon_BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #CouponIndexi')
				SET IDENTITY_INSERT Coupon_BillIndex OFF
				
				SET IDENTITY_INSERT CompleteBrandarTotal ON
				SET @columns=dbo.f_getallcolumns('CompleteBrandarTotal')
				EXEC('INSERT INTO CompleteBrandarTotal ('+@columns+') SELECT '+@columns+ ' FROM #CompleteBrandarTotald')
				SET IDENTITY_INSERT CompleteBrandarTotal OFF
				
				SET IDENTITY_INSERT dbo.CompleteTotal ON
				SET @columns=dbo.f_getallcolumns('CompleteTotal')
				EXEC('INSERT INTO CompleteTotal ('+@columns+') SELECT '+@columns+ ' FROM #CompleteTotald ')
				SET IDENTITY_INSERT CompleteTotal OFF
					
				DROP TABLE #ReceiptBillIndexIni
				DROP TABLE #BillIndexi
				DROP TABLE #CouponIndexi
				DROP TABLE #CompleteTotald,#CompleteBrandarTotald
			END
			ELSE
			BEGIN
				DELETE FROM wx_Bill_GetBack WHERE DraftFlag=0 AND IsIniFlag=1	-- 新维修 - 维修取件单
				DELETE FROM wx_Bill_Replace WHERE DraftFlag=0 AND IsIniFlag=1		-- 新维修 - 整机更换单
				DELETE FROM wx_Bill_SendBack WHERE DraftFlag=0 AND IsIniFlag=1		-- 新维修 - 送修返回单
				DELETE FROM wx_Bill_Goto WHERE DraftFlag=0 AND IsIniFlag=1			-- 新维修 - 上门维修单
			END
			
			SELECT a.* INTO #salebilld  FROM  SaleBill a INNER JOIN billindex b ON a.BillNumberId = b.BillNumberId WHERE b.BillType='11' --销售出库单
			SELECT a.* INTO #BuyBilld FROM buybill a INNER JOIN billindex b ON a.billnumberid=b.billnumberid WHERE b.Billtype='34' --采购入库单色了
			SELECT a.* INTO #PT_Combin_SaleBill  FROM  PT_Combin_SaleBill a INNER JOIN billindex b ON a.BillNumberId = b.BillNumberId WHERE b.BillType='12' --组合品销售出库单
			SELECT a.* INTO #PT_Combin_SaleBillDetail  FROM  dbo.PT_Combin_SaleBillDetail a INNER JOIN billindex b ON a.BillNumberId = b.BillNumberId WHERE b.BillType='12' --组合品销售出库单明细
			
	
					
			SELECT a.* INTO #SaleBackBilld FROM SaleBackBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='45'   -- 销售退货单 
			SELECT a.* INTO #PT_Combin_SaleBackBill FROM dbo.PT_Combin_SaleBackBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='46'   -- 组合品销售退货单 
			SELECT a.* INTO #PT_Combin_SaleBackBillDetail FROM dbo.PT_Combin_SaleBackBillDetail a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='46'   -- 组合品销售退货单 
			SELECT a.* INTO #BuyBackBilld FROM BuyBackBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype ='6'  -- 采购退货单
			SELECT a.* INTO #CommissionBilld FROM dbo.CommissionBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid -- 代销单据
			SELECT a.* INTO #SaleGoodsExchangeBilld FROM dbo.SaleGoodsExchangeBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.BillType ='160' -- 销售换货单
			SELECT a.* INTO #BuyGoodsExchangeBilld  FROM dbo.BuyGoodsExchangeBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.BillType ='161' -- 采购换货单
			SELECT a.* INTO #PreBilld	FROM dbo.PreBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN (189,190) -- 预收款单，预付款单				
			SELECT a.* INTO #adDebtbilld FROM dbo.AdDebtBill	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN ('115','116','128','129') -- 调账单
			SELECT a.* INTO #MoneyBilld FROM dbo.MoneyBill	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  -- 其他收入、费用单、固定资产购买及变卖
			SELECT a.* INTO #PriceProtectBilld FROM dbo.PriceProtectBill	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN ('149','151') -- 价保
			SELECT a.* INTO #Advantaged FROM dbo.Advantage	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN ('148','150') -- 返利、获利
			SELECT a.* INTO #AssetIncDecBilld FROM dbo.AssetIncDecBill	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN ('212','213') -- 固定资产增加减少单
			SELECT a.* INTO #DepBilld FROM DepBill a INNER JOIN BillIndex b ON a.BillNumberId=b.BillNumberId WHERE b.BillType=214 --折旧单
			SELECT a.* INTO #FixedAssetsDetailsd FROM FixedAssetsDetails a INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberId WHERE b.billtype=307
			
			SELECT a.* INTO #CommissionBillNewDetaild FROM CommissionBillNewDetail a INNER JOIN CommissionBillNew b ON a.billnumberid=b.billnumberid --提成单 
			SELECT a.* INTO #CapitalTransfer_Billd FROM CapitalTransfer_Bill a INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberId WHERE b.billtype=310
			SELECT a.* INTO #VipAddMoneyBatchBilld FROM dbo.VipAddMoneyBatchBill a JOIN dbo.BillIndex b ON a.BillNumberId=b.BillNumberId WHERE b.billtype=312 --会员批量储值充值单
			
			SELECT a.* INTO #VipCentToMoneyBill FROM dbo.VipCentToMoneyBill a JOIN dbo.BillIndex b ON a.BillNumberId=b.BillNumberId WHERE b.billtype=427 --会员积分转储值单
			
			SELECT a.* INTO #AppraisalBill FROM dbo.AppraisalBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND b.BillType=400 --暂估入库单
			SELECT a.* INTO #AppraisalBackBill FROM dbo.AppraisalBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberID=B.BillNumberId AND b.BillType=401 --暂估退货单
			SELECT a.* INTO #SendBill FROM dbo.SendBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=402  --发出商品出库单
			SELECT a.* INTO #SendBackBill FROM dbo.SendBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=403 --发出商品退货单
			SELECT a.* INTO #ReceiptBill FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID               --发票明细
			SELECT a.* INTO #ChargeOffBill FROM dbo.ChargeOffBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=450 --往来核销单
			
			SELECT a.* into #Coupon_InBill FROM dbo.Coupon_InBill A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=423 --优惠券入库单
			SELECT a.* into #Coupon_OutBill FROM dbo.Coupon_OutBill A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=424 --优惠券出库单
			SELECT a.* into #Coupon_OutBill_Ptype FROM dbo.Coupon_OutBill_Ptype A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=424 --优惠券出库下表体
			SELECT a.* into #Coupon_BackBill FROM dbo.Coupon_BackBill A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=426 --优惠券退货单
			SELECT a.* into #Coupon_AllotBill FROM dbo.Coupon_AllotBill A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=425 --优惠券调拨单
			SELECT a.* into #Coupon_AllotBillStype FROM dbo.Coupon_AllotBillStype A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType IN (428,429) --优惠券调分支机构拨单			
			SELECT a.* into #BillMulBrand FROM dbo.BillMulBrand A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND a.BillType=B.BillType
			
			--重置OldBillNumberID,OldID 为-1
			UPDATE #AppraisalBill SET OldBillNumberID=-1,OldID=-1,BackQty=0
			UPDATE #SendBill SET OldBillNumberID=-1,OldID=-1,BackQty=0
			UPDATE #AppraisalBackBill SET OldBillNumberID=-1,OldID=-1
			UPDATE #SendBackBill SET OldBillNumberID=-1,OldID=-1
			UPDATE #BuyBackBilld SET OldBillNumberID=-1,OldID=-1
			UPDATE #SaleBackBilld SET OldBillNumberID=-1,OldID=-1
			UPDATE #PT_Combin_SaleBill SET BackQty=0
			UPDATE #PT_Combin_SaleBillDetail SET BackQty=0
			UPDATE #PT_Combin_SaleBackBill SET OldBillNumberID=-1,OldID=-1
			UPDATE #PT_Combin_SaleBackBillDetail SET OldBillNumberID=-1,OldID=-1
						
			TRUNCATE TABLE	SaleBill
			TRUNCATE TABLE	SaleBackBill
			TRUNCATE TABLE	buybill
			TRUNCATE TABLE	buybackbill
			TRUNCATE TABLE	SaleGoodsExchangeBill
			TRUNCATE TABLE	BuyGoodsExchangeBill
			TRUNCATE TABLE	CommissionBill
			TRUNCATE TABLE	PreBill--预收预付
			TRUNCATE TABLE	AdDebtBill--调账单
			TRUNCATE TABLE dbo.PriceProtectBill
			TRUNCATE TABLE dbo.Advantage
			TRUNCATE TABLE dbo.MoneyBill
			TRUNCATE TABLE AssetIncDecBill --固定资产增加减少单
			TRUNCATE TABLE DepBill;
			TRUNCATE TABLE CommissionBillNewDetail;
			TRUNCATE TABLE CapitalTransfer_Bill --资金调拨单
			TRUNCATE TABLE VipAddMoneyBatchBill--会员储值单
			TRUNCATE TABLE VipCentToMoneyBill	--会员积分转储值单
			TRUNCATE TABLE AppraisalBill		--暂估入库
			TRUNCATE TABLE AppraisalBackBill	--暂估退货
			TRUNCATE TABLE SendBill				--发出商品出库
			TRUNCATE TABLE SendBackBill			--发出商品退货
			TRUNCATE TABLE ReceiptBill			--发票表明细
			TRUNCATE TABLE ChargeOffBill		--往来核销单
			TRUNCATE TABLE dbo.PT_Combin_SaleBill
			TRUNCATE TABLE dbo.PT_Combin_SaleBillDetail
			TRUNCATE TABLE dbo.PT_Combin_SaleBackBill
			TRUNCATE TABLE dbo.PT_Combin_SaleBackBillDetail
			--优惠券
			TRUNCATE TABLE dbo.Coupon_InBill
			TRUNCATE TABLE dbo.Coupon_OutBill
			TRUNCATE TABLE dbo.Coupon_OutBill_Ptype
			TRUNCATE TABLE dbo.Coupon_BackBill
			TRUNCATE TABLE dbo.Coupon_AllotBill
			TRUNCATE TABLE dbo.Coupon_AllotBillStype
			TRUNCATE TABLE dbo.BillMulBrand
			
			SET IDENTITY_INSERT dbo.SaleBill ON
			SET @columns=dbo.f_getallcolumns('SaleBill')
			EXEC('INSERT INTO SaleBill('+@columns+') SELECT '+@columns+ ' FROM #SaleBilld')
			SET IDENTITY_INSERT SaleBill OFF
			
			SET IDENTITY_INSERT BuyBill ON
			SET @columns=dbo.f_getallcolumns('BuyBill')
			EXEC('INSERT INTO BuyBill ('+@columns+') SELECT '+@columns+ ' FROM #BuyBilld')
			SET IDENTITY_INSERT BuyBill OFF
			
			SET IDENTITY_INSERT dbo.saleBackBill ON
			SET @columns=dbo.f_getallcolumns('saleBackBill')
			EXEC('INSERT INTO saleBackBill ('+@columns+') SELECT '+@columns+ ' FROM #saleBackBilld')
			SET IDENTITY_INSERT saleBackBill OFF
			
			SET IDENTITY_INSERT dbo.BuyBackBill ON
			SET @columns=dbo.f_getallcolumns('BuyBackBill')
			EXEC('INSERT INTO BuyBackBill ('+@columns+') SELECT '+@columns+ ' FROM #BuyBackBilld')
			SET IDENTITY_INSERT BuyBackBill OFF
			
			SET IDENTITY_INSERT dbo.CommissionBill ON
			SET @columns=dbo.f_getallcolumns('CommissionBill')
			EXEC('INSERT INTO CommissionBill ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBilld')
			SET IDENTITY_INSERT CommissionBill OFF
			
			SET IDENTITY_INSERT dbo.BuyGoodsExchangeBill ON
			SET @columns=dbo.f_getallcolumns('BuyGoodsExchangeBill')
			EXEC('INSERT INTO BuyGoodsExchangeBill ('+@columns+') SELECT '+@columns+ ' FROM #BuyGoodsExchangeBilld')
			SET IDENTITY_INSERT BuyGoodsExchangeBill OFF
			
			SET IDENTITY_INSERT dbo.SaleGoodsExchangeBill ON
			SET @columns=dbo.f_getallcolumns('SaleGoodsExchangeBill')
			EXEC('INSERT INTO SaleGoodsExchangeBill ('+@columns+') SELECT '+@columns+ ' FROM #SaleGoodsExchangeBilld')
			SET IDENTITY_INSERT SaleGoodsExchangeBill OFF
			
			SET IDENTITY_INSERT dbo.PreBill ON
			SET @columns=dbo.f_getallcolumns('PreBill')
			EXEC('INSERT INTO PreBill ('+@columns+') SELECT '+@columns+ ' FROM #PreBilld')
			SET IDENTITY_INSERT PreBill OFF
			
			SET IDENTITY_INSERT dbo.AdDebtBill ON
			SET @columns=dbo.f_getallcolumns('AdDebtBill')
			EXEC('INSERT INTO AdDebtBill ('+@columns+') SELECT '+@columns+ ' FROM #AdDebtBilld')
			SET IDENTITY_INSERT AdDebtBill OFF
			
			SET IDENTITY_INSERT dbo.MoneyBill ON
			SET @columns=dbo.f_getallcolumns('MoneyBill')
			EXEC('INSERT INTO MoneyBill ('+@columns+') SELECT '+@columns+ ' FROM #MoneyBilld')
			SET IDENTITY_INSERT MoneyBill OFF
			
			SET IDENTITY_INSERT dbo.PriceProtectBill ON
			SET @columns=dbo.f_getallcolumns('PriceProtectBill')
			EXEC('INSERT INTO PriceProtectBill ('+@columns+') SELECT '+@columns+ ' FROM #PriceProtectBilld')
			SET IDENTITY_INSERT PriceProtectBill OFF
			
			SET IDENTITY_INSERT dbo.Advantage ON
			SET @columns=dbo.f_getallcolumns('Advantage')
			EXEC('INSERT INTO Advantage ('+@columns+') SELECT '+@columns+ ' FROM #Advantaged')
			SET IDENTITY_INSERT Advantage OFF
			
			SET IDENTITY_INSERT dbo.AssetIncDecBill ON
			SET @columns=dbo.f_getallcolumns('AssetIncDecBill')
			EXEC('INSERT INTO AssetIncDecBill ('+@columns+') SELECT '+@columns+ ' FROM #AssetIncDecBilld')
			SET IDENTITY_INSERT AssetIncDecBill OFF
			
			SET IDENTITY_INSERT dbo.DepBill ON
			SET @columns=dbo.f_getallcolumns('DepBill')
			EXEC('INSERT INTO DepBill ('+@columns+') SELECT '+@columns+ ' FROM #DepBilld')
			SET IDENTITY_INSERT DepBill OFF
			
			SET IDENTITY_INSERT dbo.FixedAssetsDetails ON
			SET @columns=dbo.f_getallcolumns('FixedAssetsDetails')
			EXEC('INSERT INTO FixedAssetsDetails ('+@columns+') SELECT '+@columns+ ' FROM #FixedAssetsDetailsd')
			SET IDENTITY_INSERT FixedAssetsDetails OFF
			
			SET IDENTITY_INSERT dbo.CommissionBillNewDetail ON
			SET @columns=dbo.f_getallcolumns('CommissionBillNewDetail')
			EXEC('INSERT INTO CommissionBillNewDetail ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBillNewDetaild')
			SET IDENTITY_INSERT CommissionBillNewDetail OFF
			
			SET IDENTITY_INSERT dbo.CapitalTransfer_Bill ON
			SET @columns=dbo.f_getallcolumns('CapitalTransfer_Bill')
			EXEC('INSERT INTO CapitalTransfer_Bill ('+@columns+') SELECT '+@columns+ ' FROM #CapitalTransfer_Billd')
			SET IDENTITY_INSERT CapitalTransfer_Bill OFF
			
			--会员储值单
			SET IDENTITY_INSERT dbo.VipAddMoneyBatchBill ON
			SET @columns=dbo.f_getallcolumns('VipAddMoneyBatchBill')
			EXEC('INSERT INTO VipAddMoneyBatchBill ('+@columns+') SELECT '+@columns+ ' FROM #VipAddMoneyBatchBilld')
			SET IDENTITY_INSERT VipAddMoneyBatchBill OFF
			
			--会员积分转储值单
			SET IDENTITY_INSERT dbo.VipCentToMoneyBill ON
			SET @columns=dbo.f_getallcolumns('VipCentToMoneyBill')
			EXEC('INSERT INTO VipCentToMoneyBill ('+@columns+') SELECT '+@columns+ ' FROM #VipCentToMoneyBill')
			SET IDENTITY_INSERT VipCentToMoneyBill OFF
			
			SET IDENTITY_INSERT dbo.AppraisalBill ON
			SET @columns=dbo.f_getallcolumns('AppraisalBill')
			EXEC ('INSERT INTO AppraisalBill ('+@columns+') SELECT '+@columns +' FROM #AppraisalBill')
			SET IDENTITY_INSERT dbo.AppraisalBill OFF
			
			SET IDENTITY_INSERT dbo.AppraisalBackBill ON
			SET @columns=dbo.f_getallcolumns('AppraisalBackBill')
			EXEC ('INSERT INTO AppraisalBackBill ('+@columns+') SELECT '+@columns +' FROM #AppraisalBackBill')
			SET IDENTITY_INSERT dbo.AppraisalBackBill OFF
			
			SET IDENTITY_INSERT dbo.SendBill ON
			SET @columns=dbo.f_getallcolumns('SendBill')
			EXEC ('INSERT INTO SendBill ('+@columns+') SELECT '+@columns +' FROM #SendBill')
			SET IDENTITY_INSERT dbo.SendBill OFF
			
			SET IDENTITY_INSERT dbo.SendBackBill ON
			SET @columns=dbo.f_getallcolumns('SendBackBill')
			EXEC ('INSERT INTO SendBackBill ('+@columns+') SELECT '+@columns +' FROM #SendBackBill')
			SET IDENTITY_INSERT dbo.SendBackBill OFF
			
			SET IDENTITY_INSERT dbo.ReceiptBill ON
			SET @columns=dbo.f_getallcolumns('ReceiptBill')
			EXEC ('INSERT INTO ReceiptBill ('+@columns+') SELECT '+@columns +' FROM #ReceiptBill')
			SET IDENTITY_INSERT dbo.ReceiptBill OFF
			
			SET IDENTITY_INSERT dbo.ChargeOffBill ON
			SET @columns=dbo.f_getallcolumns('ChargeOffBill')
			EXEC ('INSERT INTO ChargeOffBill ('+@columns+') SELECT '+@columns +' FROM #ChargeOffBill')
			SET IDENTITY_INSERT dbo.ChargeOffBill OFF
			
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBill ON
			SET @columns=dbo.f_getallcolumns('PT_Combin_SaleBill')
			EXEC ('INSERT INTO PT_Combin_SaleBill ('+@columns+') SELECT '+@columns +' FROM #PT_Combin_SaleBill')
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBill OFF
			
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBillDetail ON
			SET @columns=dbo.f_getallcolumns('PT_Combin_SaleBillDetail')
			EXEC ('INSERT INTO PT_Combin_SaleBillDetail ('+@columns+') SELECT '+@columns +' FROM #PT_Combin_SaleBillDetail')
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBillDetail OFF
			
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBackBill ON
			SET @columns=dbo.f_getallcolumns('PT_Combin_SaleBackBill')
			EXEC ('INSERT INTO PT_Combin_SaleBackBill ('+@columns+') SELECT '+@columns +' FROM #PT_Combin_SaleBackBill')
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBackBill OFF
			
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBackBillDetail ON
			SET @columns=dbo.f_getallcolumns('PT_Combin_SaleBackBillDetail')
			EXEC ('INSERT INTO PT_Combin_SaleBackBillDetail ('+@columns+') SELECT '+@columns +' FROM #PT_Combin_SaleBackBillDetail')
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBackBillDetail OFF
			
			--优惠券
			SET IDENTITY_INSERT dbo.Coupon_InBill ON
			SET @columns=dbo.f_getallcolumns('Coupon_InBill')
			EXEC ('INSERT INTO Coupon_InBill ('+@columns+') SELECT '+@columns +' FROM #Coupon_InBill')
			SET IDENTITY_INSERT dbo.Coupon_InBill OFF
			
			SET IDENTITY_INSERT dbo.Coupon_OutBill ON
			SET @columns=dbo.f_getallcolumns('Coupon_OutBill')
			EXEC ('INSERT INTO Coupon_OutBill ('+@columns+') SELECT '+@columns +' FROM #Coupon_OutBill')
			SET IDENTITY_INSERT dbo.Coupon_OutBill OFF
			
			
			SET @columns=dbo.f_getallcolumns('Coupon_OutBill_Ptype')
			EXEC ('INSERT INTO Coupon_OutBill_Ptype ('+@columns+') SELECT '+@columns +' FROM #Coupon_OutBill_Ptype')
	
			
			SET IDENTITY_INSERT dbo.Coupon_AllotBill ON
			SET @columns=dbo.f_getallcolumns('Coupon_AllotBill')
			EXEC ('INSERT INTO Coupon_AllotBill ('+@columns+') SELECT '+@columns +' FROM #Coupon_AllotBill')
			SET IDENTITY_INSERT dbo.Coupon_AllotBill OFF
			
			SET IDENTITY_INSERT dbo.Coupon_AllotBillStype ON
			SET @columns=dbo.f_getallcolumns('Coupon_AllotBillStype')
			EXEC ('INSERT INTO Coupon_AllotBillStype ('+@columns+') SELECT '+@columns +' FROM #Coupon_AllotBillStype')
			SET IDENTITY_INSERT dbo.Coupon_AllotBillStype OFF			
			
			SET IDENTITY_INSERT dbo.Coupon_BackBill ON
			SET @columns=dbo.f_getallcolumns('Coupon_BackBill')
			EXEC ('INSERT INTO Coupon_BackBill ('+@columns+') SELECT '+@columns +' FROM #Coupon_BackBill')
			SET IDENTITY_INSERT dbo.Coupon_BackBill OFF
			
			SET IDENTITY_INSERT dbo.BillMulBrand ON
			SET @columns=dbo.f_getallcolumns('BillMulBrand')
			EXEC ('INSERT INTO BillMulBrand ('+@columns+') SELECT '+@columns +' FROM #BillMulBrand')
			SET IDENTITY_INSERT dbo.BillMulBrand OFF


			
			DROP TABLE #SaleBilld,#BuyBilld,#saleBackBilld,#BuyBackBilld,#adDebtbilld,#BuyGoodsExchangeBilld,#CommissionBilld,#PreBilld,#SaleGoodsExchangeBilld,#MoneyBilld,#PriceProtectBilld,#Advantaged,#AssetIncDecBilld,#CommissionBillNewDetaild,#CapitalTransfer_Billd,#AppraisalBill,#AppraisalBackBill,#SendBill,#SendBackBill,#ReceiptBill
			,#PT_Combin_SaleBill,#PT_Combin_SaleBillDetail,#PT_Combin_SaleBackBill,#PT_Combin_SaleBackBillDetail,#Coupon_InBill,#Coupon_OutBill,#Coupon_OutBill_Ptype,#Coupon_AllotBill,#Coupon_AllotBillStype,#Coupon_BackBill,#VipCentToMoneyBill,#VipAddMoneyBatchBilld,#BillMulBrand,#ChargeOffBill,#DepBilld,#FixedAssetsDetailsd
			CREATE TABLE #BillOperateLog(		
							[BillnumberID] INT,				
							[OperateType] VARCHAR(50) NULL DEFAULT(''),
							[EtypeID] VARCHAR(50) NULL DEFAULT(''),
							[OperateTime] DATETIME NULL DEFAULT(GETDATE()),
							[IP] VARCHAR(50) NULL,
							[BillCode] VARCHAR(200) NOT NULL DEFAULT(''),
							[BillDate] DATETIME ,
							[ifcheck] CHAR(1) NOT NULL DEFAULT(''),
							[btypeid] VARCHAR(50) NOT NULL DEFAULT(''),
							[NTotalMoney] NUMERIC(22,10) DEFAULT(0),
							[billtype] INT  NOT NULL DEFAULT(0)
						)
			------------------------操作日志BillOperateLog---------------
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM BillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='billindex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM ReceiptBillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='ReceiptBillIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM FaPiaoBillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='FaPiaoBillIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM LendIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='LendIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM factindex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='factindex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='OrderIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM RequestIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='RequestIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM onShelvespickIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='onShelvespickIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM PosAllotApplyBillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='PosAllotApplyBillIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM SerialAdjustIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='SerialAdjustIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM StockCheckIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='StockCheckIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM Coupon_BillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='Coupon_BillIndex')
			
			TRUNCATE TABLE BillOperateLog --操作日志
			INSERT INTO dbo.BillOperateLog
			        ( BillnumberID ,
			          OperateType ,
			          EtypeID ,
			          OperateTime ,
			          IP ,
			          BillCode ,
			          BillDate ,
			          ifcheck ,
			          btypeid ,
			          NTotalMoney ,
			          billtype
			        )
			SELECT  BillnumberID ,
			          OperateType ,
			          EtypeID ,
			          OperateTime ,
			          IP ,
			          BillCode ,
			          BillDate ,
			          ifcheck ,
			          btypeid ,
			          NTotalMoney ,
			          billtype
			 FROM #BillOperateLog					
			DROP TABLE #BillOperateLog
			DELETE FROM BeforePromoteIndex WHERE NOT EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BeforePromoBillNumberId=dbo.BeforePromoteIndex.BillNumberId AND draft=1)	--零售零售促销方案主表
			DELETE FROM BeforePromoteRetailBill WHERE NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.BeforePromoteRetailBill.BillNumberId)	--零售零食促销方案明细
			DELETE FROM BeforePromoteSaleBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BeforePromoteIndex WHERE BillNumberId=BeforePromoteSaleBill.BillNumberId)
			
			DELETE FROM  BillIndex_CarRepair WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.Billindex_CarRepair.BillNumberId)
				
			
			IF @bRebulidIni = 1	--清除期初
			BEGIN
				TRUNCATE TABLE Coupon_CodeInfo 
			END
			ELSE
			BEGIN
			
				
				--回写状态,重建 将inistate 赋值给 state
				UPDATE  a 
				SET		[state]=inistate,	
						outprice=CASE WHEN a.inistate=2 THEN a.outprice  ELSE 0 END ,				
						ktypeid=IniKtypeId,
						CargoId=IniCargoId
				FROM  dbo.Coupon_CodeInfo a
			END
			DELETE FROM Coupon_CodeInfo WHERE IsIni=0 --不是期初的，则通过过账来，需要清理
			
				
			--处理优惠券信息表 和 出入库优惠券使用表
			DELETE FROM  Coupon_BillUsed WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.Coupon_BillUsed.BillNumberId)
			TRUNCATE TABLE dbo.Coupon_CodeInOut 	
			
		END
	-------------------------- 专门对 BillIndex、以及主表在billindex中的期初单据进行处理 end---------------------------------
	
	IF @clearStopOrder=1 --清除已中止的订单
	BEGIN
		--更新期初订单库存
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.BillOver=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.BillOver=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
		--删除已中止的采购订单 回写销售订单的已采购订货数量 (注释掉---中止订单的时候已经回写一次，所以重建删除是不再回写2019-08-05)	
		--UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		--FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 and billtype =301) GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId
		
		--删除已中止的采购订单 回写组合品销售订单的已采购订货数量	(注释掉---中止订单的时候已经回写一次，所以重建删除是不再回写)	
		--UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		--FROM PT_Combin_OrderBillDetail A JOIN (select SUM(Qty) AS Qty,PTCombinOrderBillDetailID FROM dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 and billtype =301) GROUP BY PTCombinOrderBillDetailID) B on A.ORDERID=B.PTCombinOrderBillDetailID

		
		--删除已中止的销售订单 去除关联关系
		UPDATE OrderBill SET SaleOrderId =-1
		WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 and billtype =300)  )
		
		--删除已中止的组合品销售订单 去除关联关系
		UPDATE OrderBill SET PTCombinOrderBillDetailID =-1
		WHERE PTCombinOrderBillDetailID IN (SELECT ORDERID FROM PT_Combin_OrderBillDetail WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 and billtype =313)  )
		
		DELETE dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1)
		DELETE dbo.PT_Combin_OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1)
		DELETE dbo.PT_Combin_OrderBillDetail WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1)
		DELETE dbo.OrderIndex WHERE BillOver=1		
	END
	
	IF @clearCompleteOrder=1 --清除已完成的订单
	BEGIN
			--更新期初订单库存
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.OrderState=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.OrderState=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
		--删除已完成的采购订单 回写销售订单的已采购订货数量
		UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1 and billtype =301) GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId
		
	   --删除已完成的采购订单 回写组合品销售订单的已采购订货数量		
		UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		FROM PT_Combin_OrderBillDetail A JOIN (select SUM(Qty) AS Qty,PTCombinOrderBillDetailID FROM dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE  OrderState=1 AND billtype =301) GROUP BY PTCombinOrderBillDetailID) B on A.ORDERID=B.PTCombinOrderBillDetailID
		
		--删除已中止的销售订单 去除关联关系
		UPDATE OrderBill SET SaleOrderId =-1
		WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1 and billtype =300)  )
		
		--删除已完成的组合品销售订单 去除关联关系
		UPDATE OrderBill SET PTCombinOrderBillDetailID =-1
		WHERE PTCombinOrderBillDetailID IN (SELECT ORDERID FROM PT_Combin_OrderBillDetail WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1 and billtype =313)  )
		
		----打断销售 采购有订金产生的 预收\付款  收付款单关联关系
		--UPDATE prebill set RelevanceBillId=-1 
		--WHERE RelevanceBillId IN (SELECT ORDERID FROM ORDERBILL  WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1  ))
		--UPDATE gatheringbill set RelevanceBillId=-1 
		--WHERE RelevanceBillId IN (SELECT ORDERID FROM ORDERBILL   WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1 ))
		--UPDATE paybill set RelevanceBillId=-1 
		--WHERE RelevanceBillId IN (SELECT ORDERID FROM ORDERBILL   WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1  ))

		DELETE dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1)
		DELETE dbo.PT_Combin_OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1)
		DELETE dbo.PT_Combin_OrderBillDetail WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1)
		DELETE dbo.OrderIndex WHERE OrderState=1
	END 
	
	IF @clearAllOrder=1	--清除所有订单\修改所有掉订单OrderID为-1
	BEGIN
		TRUNCATE TABLE OrderBill			-- 销售、采购订单
		TRUNCATE TABLE OrderIndex			-- 清除订单索引表
		DELETE dbo.OrderIndex WHERE BillType=313		--清除所有组合品订单
		TRUNCATE TABLE PT_Combin_OrderBill				--清除所有组合品订单信息
		TRUNCATE TABLE PT_Combin_OrderBillDetail			--清除所有组合品订单明细信息
		TRUNCATE TABLE Ini_GoodsStocks_Order
		
		UPDATE AppraisalBill SET OrderID=-1
		UPDATE SendBill SET OrderID=-1
		UPDATE SaleBill SET OrderID=-1
		UPDATE Buybill SET OrderID=-1
		UPDATE PT_Combin_SaleBill SET OrderID=-1
		UPDATE PT_Combin_SaleBillDetail SET OrderID=-1
		UPDATE CommissionBill SET OrderID=-1 WHERE Type IN (140,144)
		
		UPDATE prebill SET RelevanceBillId=-1
		UPDATE gatheringbill SET RelevanceBillId=-1 
		UPDATE paybill SET RelevanceBillId=-1 
	END
	ELSE	--修改所有被删除订单的调用ID，OrderID为-1
	BEGIN
		UPDATE SendBill SET OrderID=-1 FROM SendBill LEFT JOIN OrderBill 
			ON dbo.SendBill.OrderID = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE SaleBill SET OrderID=-1 FROM SaleBill LEFT JOIN OrderBill 
			ON dbo.SaleBill.OrderID = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE PT_Combin_SaleBill SET OrderID=-1 FROM PT_Combin_SaleBill LEFT JOIN PT_Combin_OrderBill 
			ON dbo.PT_Combin_SaleBill.OrderID = dbo.PT_Combin_OrderBill.OrderID WHERE dbo.PT_Combin_OrderBill.OrderID IS NULL;
		UPDATE PT_Combin_SaleBillDetail SET OrderID=-1 FROM PT_Combin_SaleBillDetail LEFT JOIN PT_Combin_OrderBillDetail 
			ON dbo.PT_Combin_SaleBillDetail.OrderID = dbo.PT_Combin_OrderBillDetail.OrderID WHERE dbo.PT_Combin_OrderBillDetail.OrderID IS NULL;
		UPDATE AppraisalBill SET OrderID=-1 FROM AppraisalBill LEFT JOIN OrderBill 
			ON dbo.AppraisalBill.OrderID = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE Buybill SET OrderID=-1 FROM Buybill LEFT JOIN OrderBill 
			ON dbo.Buybill.OrderID = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE CommissionBill SET OrderID=-1 FROM CommissionBill LEFT JOIN OrderBill 
			ON dbo.CommissionBill.OrderID = dbo.OrderBill.OrderID AND Type IN (140,144) WHERE dbo.OrderBill.OrderID IS NULL;
		--打断销售 采购有订金产生的 预收\付款  收付款单关联关系	
		UPDATE prebill SET RelevanceBillId=-1 FROM prebill LEFT JOIN OrderBill 
			ON dbo.prebill.RelevanceBillId = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE gatheringbill SET RelevanceBillId=-1 FROM gatheringbill LEFT JOIN OrderBill 
			ON dbo.gatheringbill.RelevanceBillId = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE paybill SET RelevanceBillId=-1 FROM paybill LEFT JOIN OrderBill 
			ON dbo.paybill.RelevanceBillId = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
	END
	
	---------------------------------------------------------------------------门店配送类单据系统重建 开始---------------------------------------------------------------------------

--年结存后的门配单据，做了验收/退货过账，此时做重建只保留期初数据，其余的全部勾选清掉，此时的数量没有回写。
	IF EXISTS ( SELECT b.BillNumberId,b.ID FROM dbo.PosAllotApplyBillIndex  a
	            INNER JOIN  dbo.DeliveryBill b ON a.BillNumberId=b.BillNumberId AND a.IsIni=1	)
	BEGIN	     
        SELECT  db.Qty,db.BillNumberId,db.DeliveryID,db.PtypeId INTO #table FROM dbo.DeliveryBackBill db
		INNER JOIN (
		SELECT ID,de.BillNumberId FROM dbo.DeliveryBill de
		INNER JOIN  PosAllotApplyBillIndex po ON po.BillNumberId=de.BillNumberId
		WHERE po.IsIni=1
		) de ON de.ID=db.DeliveryID
		INNER JOIN PosAllotApplyBillIndex pa ON pa.BillNumberId=db.BillNumberId AND pa.ifcheck='t' AND pa.draft=0 AND pa.RedWord=0
		
		 SELECT  db.Qty,db.BillNumberId,db.DeliveryID,db.PtypeId INTO #table2 FROM dbo.DeliveryCheckBill db
		INNER JOIN (
		SELECT ID,de.BillNumberId FROM dbo.DeliveryBill de
		INNER JOIN  PosAllotApplyBillIndex po ON po.BillNumberId=de.BillNumberId
		WHERE po.IsIni=1
		) de ON de.ID=db.DeliveryID
		INNER JOIN PosAllotApplyBillIndex pa ON pa.BillNumberId=db.BillNumberId AND pa.ifcheck='t' AND pa.draft=0 AND pa.RedWord=0
		
      UPDATE dbo.DeliveryBill SET  CheckQty-=b.qty FROM #table2 b WHERE b.DeliveryID=dbo.DeliveryBill.ID
      UPDATE dbo.DeliveryBill SET  backqty-=b.qty FROM #table b WHERE b.DeliveryID=dbo.DeliveryBill.ID
      
	END		
	
	IF @clearCompleteAllotApply = 1 --清除已完成的调货申请单 BillState=4 作废  IsDone=1 已完成
	BEGIN
	     DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE (BillState = 4 OR Isdone = 1) and BillType=22)
	     DELETE PosAllotApplyBillIndex WHERE (BillState = 4 OR Isdone = 1) and BillType=22;
	END
	
	IF @clearNoCompleteAllotApply = 1 --清除未完成的调货申请单
	BEGIN
	     DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone <> 1 and BillType=22)
	     DELETE PosAllotApplyBillIndex WHERE Isdone <> 1 and BillType=22;
	END
		
	IF @clearcompletegetbillapply = 1 --清除已完成的要货申请单 BillState=4 作废  IsDone=1 已完成
	BEGIN
	     DELETE DeliveryApplyBill WHERE BillNumberId IN (SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE (BillState = 4 OR Isdone = 1) and BillType=326)
	     DELETE PosAllotApplyBillIndex WHERE (BillState = 4 OR Isdone = 1) and BillType=326;
	END
	IF @clearnocompletegetbillapply = 1 --清除未完成的要货申请单
	BEGIN
	     DELETE DeliveryApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone <> 1 and BillType=326)
	     DELETE PosAllotApplyBillIndex WHERE Isdone <> 1 and BillType=326;
	END
	
	--清期初数据
	IF @bRebulidIni = 1
	BEGIN
		DELETE FROM PosAllotApplyBillIndex WHERE IsIni = 1
		DELETE FROM PosAllotApplyBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)
		DELETE FROM DeliveryApplyBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)
		DELETE FROM DeliveryBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)
		DELETE FROM DeliveryBackBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)
		DELETE FROM DeliveryCheckBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)
	END
	
	--清除草稿
	IF @bRebulidDraft = 1
	BEGIN
		DELETE FROM dbo.DeliveryBill WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE ifcheck='f' AND draft=1 AND BillType IN (327)) --门店配送单
		DELETE FROM dbo.DeliveryBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE ifcheck='f' AND draft=1 AND BillType IN (328)) --门店配送退货单
		DELETE FROM dbo.DeliveryCheckBill WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE ifcheck='f' AND draft=1 AND BillType IN (329)) --门店验收单
		DELETE FROM PosAllotApplyBillIndex WHERE ifcheck='f' AND IsIni=0 AND BillType IN (327,328,329) --主表		
	END
	
	--清除过账单据
	DELETE FROM dbo.DeliveryBill WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE ifcheck='t' AND IsIni=0 AND BillType IN (327))
	 --门店配送单	
	     	            	         	            
	DELETE FROM dbo.DeliveryBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE ifcheck='t' AND IsIni=0 AND BillType IN (328)) --门店配送退货单
	DELETE FROM dbo.DeliveryCheckBill WHERE BillNumberId IN (SELECT BillNumberId FROM dbo.PosAllotApplyBillIndex WHERE ifcheck='t' AND IsIni=0 AND BillType IN (329)) --门店验收单
	DELETE FROM PosAllotApplyBillIndex WHERE ifcheck='t' AND IsIni=0 AND BillType IN (327,328,329) --主表
	
	---------------------------------------------------------------------------门店配送类单据系统重建 结束---------------------------------------------------------------------------
		
	--重建清除所有物流单据，包括草稿
	TRUNCATE TABLE Transportbill
	TRUNCATE TABLE PickBill
	TRUNCATE TABLE onShelvesbill
	TRUNCATE TABLE onShelvespickIndex
	TRUNCATE TABLE Transportcontrastbill
	
	TRUNCATE TABLE FixedAssetsIndex
	TRUNCATE TABLE FixedAssetsDetails;
	
	TRUNCATE TABLE RequestBill			--请购单明细
	TRUNCATE TABLE RequestIndex			--请购单主表
	TRUNCATE TABLE dbo.FactStocks
	TRUNCATE TABLE dbo.FactStocks_Qty
	TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
	TRUNCATE TABLE dbo.Fact_InOutstocktable
	TRUNCATE TABLE GOODSSTOCKS_QTY
	TRUNCATE TABLE GoodsStocks			--DELETE FROM GoodsStocks
	TRUNCATE TABLE wx_GoodsStocks
	TRUNCATE TABLE CommissionStock		--DELETE FROM CommissionStock --清掉代销库存
	TRUNCATE TABLE dbo.CommissionStock_Qty
	TRUNCATE TABLE InOutStockTable		--DELETE FROM InOutStockTable
	TRUNCATE TABLE wx_InOutStockTable	-- 维修出入库明细表
	TRUNCATE TABLE ListTable			--DELETE FROM ListTable
	TRUNCATE TABLE dbo.Fact_InOutstocktable
	TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
	TRUNCATE TABLE GP_InOutPTypeSerial	--DELETE FROM GP_InOutPTypeSerial
	TRUNCATE TABLE GP_CruPTypeSerial	--DELETE FROM GP_CruPTypeSerial
	TRUNCATE TABLE GP_LendPTypeSerial	--DELETE FROM GP_LendPTypeSerial	--清掉借欠的序列号 谢吉康  2004-02-24
	TRUNCATE TABLE VipCardConsume		--DELETE FROM VipCardConsume		--清掉VIP卡消费记录表  谢吉康  2004-7-21
	TRUNCATE TABLE StockCheck			--DELETE FROM StockCheck     --清掉库存盘点
	TRUNCATE TABLE StockCheckIndex		--DELETE FROM StockCheckIndex  --清掉库存盘点
	--TRUNCATE TABLE StockAlarm			--DELETE FROM StockAlarm  --清掉上下限报警

	TRUNCATE TABLE DiyIndex   --装机配置单
	TRUNCATE TABLE DiyBill		--装机配置单
	TRUNCATE TABLE DiyBillTypePSaleTypeID
	TRUNCATE TABLE Ac_Balance							--科目余额表
	TRUNCATE TABLE Ac_Balance_Assist_CheckItems			--科目余额表(辅助核算）
	TRUNCATE TABLE Ac_Balance_Assist_CheckItems_Detail  --科目余额表(辅助核算明细)
	TRUNCATE TABLE Ac_ProfitAndLoss						--损益表
	TRUNCATE TABLE Ac_ProfitAndLoss_Detail				--损益表明细
	TRUNCATE TABLE Ac_GoodsBill_VoucherBill				--业务和财务关联表
	TRUNCATE TABLE Ac_CommissionBill_VoucherBill
	TRUNCATE TABLE Ac_ReceiptBill_VoucherBill
	TRUNCATE TABLE Ac_Provision_Voucher
	TRUNCATE TABLE Ac_CouponBill_VoucherBill--删除凭证关联关系
	TRUNCATE TABLE Ac_DeliveryBill_VoucherBill--删除凭证关联关系
	--删除单据修改记录
	TRUNCATE TABLE dbo.FrozeBusiness
	TRUNCATE TABLE ModifyLog_BillIndex
	TRUNCATE TABLE ModifyLog_SaleBill
	TRUNCATE TABLE ModifyLog_BuyBill
	TRUNCATE TABLE ModifyLog_SaleBackBill
	TRUNCATE TABLE ModifyLog_BuyBackBill
	TRUNCATE TABLE ModifyLog_PayBill
	TRUNCATE TABLE ModifyLog_GatheringBill
	TRUNCATE TABLE ModifyLog_CompleteTotal
	TRUNCATE TABLE ModifyLog_CompleteGoodTotal
	TRUNCATE TABLE ModifyLog_PreBill
	TRUNCATE TABLE ModifyLog_ReceiptBillIndex
	TRUNCATE TABLE ModifyLog_ReceiptBill
	TRUNCATE TABLE ModifyLog_SendBill
	TRUNCATE TABLE ModifyLog_SendBackBill
	TRUNCATE TABLE ModifyLog_AppraisalBill
	TRUNCATE TABLE ModifyLog_AppraisalBackBill
	TRUNCATE TABLE ModifyLog_PT_Combin_SaleBill
	TRUNCATE TABLE ModifyLog_PT_Combin_SaleBillDetail
	TRUNCATE TABLE ModifyLog_PT_Combin_SaleBackBill
	TRUNCATE TABLE ModifyLog_PT_Combin_SaleBackBillDetail
	TRUNCATE TABLE CostRe_Bill
	TRUNCATE TABLE CostReLog
 	--设置提成方案状
	UPDATE CommissionScheme SET UseState=1 WHERE BillNumberId NOT IN (SELECT CommissionSchemeID FROM CommissionBillNew)
	
	--清除订单的RequestBillNumberID,RequestBillID字段 增加ReachQty,ReachTotal,ReachTaxTotal
	UPDATE orderbill SET RequestBillNumberID = 0,RequestBillID = 0,ReachQty=0,ReachTotal=0,ReachTaxTotal=0
	
	IF @bitPriceTrack = 1
	BEGIN
		TRUNCATE TABLE PriceTrack			--DELETE FROM PriceTrack  --清掉价格跟踪表
		--9.4价格跟踪变化后的清除
		TRUNCATE TABLE PriceTrack_AskPrice
		TRUNCATE TABLE PriceTrack_Buy
		TRUNCATE TABLE PriceTrack_BuyOrder
		TRUNCATE TABLE PriceTrack_Quote
		TRUNCATE TABLE PriceTrack_Sale
		TRUNCATE TABLE PriceTrack_SaleOrder
		TRUNCATE TABLE PriceTrack_Appraisal
		TRUNCATE TABLE PriceTrack_Send
		TRUNCATE TABLE PriceTrack_STypeMove
	END
	ELSE
	BEGIN
		DELETE FROM dbo.PriceTrack WHERE BuyOrderPrice=NULL AND SaleOrderPrice=NULL AND CostPrice=NULL AND QueryPrice=NULL AND SalePrice=NULL AND ResponsePrice = NULL AND Discount=NULL 
	END
	
	--分支机构间最近进价
	IF @bitRecSTypeBuyPrice=1
	BEGIN
		UPDATE PType_Price SET RecAmgSTypeBuyPrice=0
	END
	--分支机构间最近售价
	IF @bitRecSTypeSalePrice=1
	BEGIN
		UPDATE PType_Price SET RecAmgSTypeSalePrice=0
	END
	--分支机构间价格跟踪
	IF @bitSTypePriceTrack=1
	BEGIN
		TRUNCATE TABLE PriceTrack_SType_Appraisal	 --暂估入库分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_AskPrice	 --询价单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Buy	 --采购入库单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_BuyOrder	 --采购订单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Quote	 --报价单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Sale	 --销售出库分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_SaleOrder	 --销售订单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Send	 --发出商品分支机构间价格跟踪表
	END

	IF @bitEventLog = 1
	BEGIN
		DELETE FROM dbo.EventLog WHERE Id<>@logid --DELETE FROM EventLog --清掉操作日志表
	END
	TRUNCATE TABLE PriceProtectList		--DELETE FROM PriceProtectList --清掉价保记录
	TRUNCATE TABLE OA_Message			--DELETE FROM OA_Message --清除在线传讯 
	DELETE FROM GiveFromSaleOrBuy		--清掉销售、采购关联赠送、获赠数据表
	TRUNCATE TABLE TCBillindex			-- 清掉提成单据索引表
	TRUNCATE TABLE TCBill				-- 清掉提成单据明细表
	TRUNCATE TABLE FaPiaoBillindex		-- 清掉新发票单据索引表
	TRUNCATE TABLE FaPiaoBill			-- 清掉新发票单据明细表
	
	--IF @bRebulidDraft = 1
	--BEGIN
	--    TRUNCATE TABLE Advantage_Standard	--DELETE FROM Advantage_standard
	--END
	TRUNCATE TABLE PromotePrice			--DELETE FROM PromotePrice	-- 促销价格表
	TRUNCATE TABLE InvoiceBill			--DELETE FROM InvoiceBill	-- 发票记录表	
	TRUNCATE TABLE LocalIndex			--DELETE FROM LocalIndex	-- 货位单据索引表
	TRUNCATE TABLE LocalDetail			--DELETE FROM LocalDetail	-- 货位单据明细表
	-- 借欠
	--TRUNCATE TABLE LendIndex			--DELETE FROM LendIndex
	--TRUNCATE TABLE LendBill				--DELETE FROM LendBill	
	TRUNCATE TABLE GoodsLend			

	-- 清除财务历史状况表
	TRUNCATE TABLE MonthATypeHistory
	-- 清除按商品结算明细表
	TRUNCATE TABLE CompleteGoodTotal
				
	TRUNCATE TABLE nVipAdjust			-- 清除消费金额调整单、积分调整单
	-- 清空VIP卡储值明细表
	TRUNCATE TABLE nVipAddMoney
	TRUNCATE TABLE wx_GoodsStocks		-- 清除维修库存
	TRUNCATE TABLE visit				-- 服务回访表
	TRUNCATE TABLE visitfj				-- 服务回访附件表
	
	DELETE  FROM commonpossaleindex WHERE Draft<>0								--收银小票
	DELETE  FROM commonpossalelist WHERE NOT EXISTS(SELECT 1 FROM CommonPosSaleIndex WHERE PosVchCode=commonpossalelist.PosVchCode)
	DELETE  FROM CommonPosPtypeCheckNdx WHERE PDVchCode<>0						--POS盘点单据
	DELETE  FROM CommonPosPtypeCheckList WHERE NOT EXISTS(SELECT 1 FROM CommonPosPtypeCheckNdx WHERE CheckCode=CommonPosPtypeCheckList.CheckCode)
	
	/*清除网店相关信息*/
	DELETE FROM dbo.WdOrder 
	DELETE FROM dbo.WdOrderBody  
	DELETE FROM dbo.WdItemsDetail
	DELETE FROM dbo.WdCargoDetail
	DELETE FROM dbo.WdAccountDetail
	DELETE BillIndex FROM dbo.BillIndex B INNER JOIN dbo.WdShopBillRelation W ON W.Billnumberid = B.BillNumberId  WHERE draft = 1
	DELETE FROM dbo.WdSaleBillTemp
	DELETE FROM dbo.WdBillIndexTemp
	DELETE FROM dbo.WdShopBillRelationTemp
	DELETE FROM dbo.WdShopBillRelation 
	DELETE FROM dbo.WDGOODSSTOCKS_QTY
	DELETE FROM dbo.WdSerialsDetail
	
	
	UPDATE dbo.ptype SET WdSyncFlag = 0
	UPDATE dbo.employee SET WdSyncFlag = 0
	UPDATE dbo.Stock SET WdSyncFlag = 0
	UPDATE dbo.CargoType SET WdSyncFlag = 0
	UPDATE dbo.loginuser SET WdSyncFlag = 0
	UPDATE dbo.Ac_Items SET WdSyncFlag = 0
	UPDATE dbo.Department SET WdSyncFlag = 0
	
	TRUNCATE TABLE Ac_Voucher
	TRUNCATE TABLE Ac_Voucher_Bill
	TRUNCATE TABLE Ac_Voucher_Bill_Assist_CheckItems
	TRUNCATE TABLE Ac_Voucher_Bill_CashMoneyItems		--现金流量项目
	
	--9.4 出纳模块处理
	UPDATE dbo.Te_StartPeriod SET IsUse = 0,IsConnect = 0,CFYear = 0,CFPeriod = 0
	TRUNCATE TABLE dbo.Te_AccountInTransit_Detail
	TRUNCATE TABLE dbo.Te_AccountInTransit_Index

	TRUNCATE TABLE dbo.Te_CheckRelevance
	TRUNCATE TABLE dbo.Te_Period
	TRUNCATE TABLE dbo.Te_Journal_Detail
	TRUNCATE TABLE dbo.Te_Journal
	TRUNCATE TABLE dbo.Te_BankStatementDetail
	TRUNCATE TABLE dbo.Te_BankStatement
	TRUNCATE TABLE dbo.Te_Balance
	
	TRUNCATE TABLE IniBType_ARAPTotal;
	--
	
	---------------------------------------------处理期初数据-------------------------------------------------
	IF @bRebulidIni = 1
	BEGIN
		UPDATE BType SET arapExplain = '' , initComment = ''
		TRUNCATE TABLE iniGoodsStocks			--DELETE FROM iniGoodsStocks
		--删除库龄数据
		TRUNCATE TABLE dbo.IniStockAgeGroup
		TRUNCATE TABLE dbo.IniStockAgeStock
		TRUNCATE TABLE dbo.IniStockAgeStype
		
		TRUNCATE TABLE ini_goodsstocks_qty
		TRUNCATE TABLE GP_initPTypeSerial		--DELETE FROM GP_initPTypeSerial
		TRUNCATE TABLE GP_initLendPtypeSerial	--DELETE FROM GP_initLendPtypeSerial	--清掉借欠期初的序列号 谢吉康  2004-02-24
		TRUNCATE TABLE AType_Total
		TRUNCATE TABLE BType_ARAPTotal
		TRUNCATE TABLE dbo.Brandar_ArApTotal
		TRUNCATE TABLE SType_InnerARTotal
		TRUNCATE TABLE GP_initPTypeSerial		--DELETE FROM GP_initPTypeSerial 
		TRUNCATE TABLE IniGoodsLend				--DELETE FROM IniGoodsLend
		TRUNCATE TABLE IniCommissionStock		--DELETE FROM IniCommissionStock
		TRUNCATE TABLE IniCommissionStock_qty
		TRUNCATE TABLE GoodsLocal				--DELETE FROM GoodsLocal		-- 期初货位  Roamer Wu 2004-03-01
	
		
		-- 清空初始及累计金额、积分
		-- 清空期初储值金额、累计储值金额、消费储值金额、储值余额
		-- 清空可洗车次数,累计可洗车次数和期初可洗车次数 毛欣蓉 2010-08-18
		-- 清除分支机构会员卡储值信息
		TRUNCATE TABLE nVipCardSignStype 
		
		UPDATE nVipCardSign 
		SET 
			TotalMoney = 0,
			TotalCent = 0,
			qCczMoney = 0,
			lJczMoney = 0,
			xFczMoney = 0,
			cZyeMoney = 0,
			CanWashTimes= 0 ,
			CanWashTimes00 = 0,
			CanWashTimesTotal = 0
		
		TRUNCATE TABLE wx_IniGoodsStocks	-- 清空维修期初库存
		TRUNCATE TABLE Ac_IniAccount							-- 清空财务期初
		TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems			-- 清空财务期初的辅助核算		
		TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems_Detail	-- 清空财务期初的辅助核算对照表		
		TRUNCATE TABLE RetailCombinationBill
		TRUNCATE TABLE dbo.Te_InitDataIndex
		TRUNCATE TABLE dbo.Te_InitDataDetail
		
		----------------期初实物库存----------------
		TRUNCATE TABLE dbo.IniFactStocks
		TRUNCATE TABLE dbo.IniFactStocks_Qty
		TRUNCATE TABLE dbo.gp_iniFactPtypeSerial
		DELETE FROM dbo.FactIndex WHERE isini=1 
		DELETE FROM dbo.FactDepotAllot WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
		DELETE FROM dbo.FactDepotInOut WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
		TRUNCATE TABLE dbo.FactInOut
		--------------------------------------------
	END
	ELSE
	BEGIN
		DECLARE  @costing INT=0
		SELECT @costing=SubValue FROM sysdata WHERE SubName='costing'
		DELETE FROM iniGoodsStocks WHERE Qty = 0 AND Total=0
		--删除库龄数据
		DELETE dbo.IniStockAgeGroup WHERE Qty = 0 AND Total=0
		DELETE dbo.IniStockAgeStock	WHERE Qty = 0 AND Total=0
		DELETE dbo.IniStockAgeStype	WHERE Qty = 0 AND Total=0
		
		DELETE FROM dbo.Ini_GOODSSTOCKS_QTY WHERE Qty=0 AND NQty=0 
		DELETE AType_Total WHERE Total00=0 OR Ntotal00=0
		DELETE dbo.SType_InnerARTotal WHERE InnerARTotal00=0;
		UPDATE SType_InnerARTotal SET InnerARTotal=0 -- 内部应收期初 
		UPDATE AType_Total SET Total=0,Ntotal=0
		DELETE BType_ARAPTotal WHERE ISNULL(YSTotal00,0)=0 AND ISNULL(YFTotal00,0)=0 AND ISNULL(ARTotal00,0)=0 AND ISNULL(APTotal00,0)=0 
			   AND ISNULL(nYSTotal00,0)=0 AND ISNULL(nYFTotal00,0)=0 AND ISNULL(nARTotal00,0)=0 AND ISNULL(nAPTotal00,0)=0 
			   AND ISNULL(NGRIRTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0 AND ISNULL(FCTotal00,0)=0 AND ISNULL(GRIRTotal00,0)=0 
		UPDATE BType_ARAPTotal SET ARTotal=0,APTotal=0,YSTotal=0,YFTotal=0,nARTotal=0,nAPTotal=0,nYSTotal=0,nYFTotal=0,GRIRTotal=0,NGRIRTotal=0,FCTotal=0,NFCTotal=0
		
		DELETE dbo.Brandar_ArApTotal WHERE ISNULL(YSTotal00,0)=0 AND ISNULL(ARTotal00,0)=0 
			   AND ISNULL(nYSTotal00,0)=0 AND ISNULL(nARTotal00,0)=0 
			   
		UPDATE Brandar_ArApTotal SET ARTotal=0,YSTotal=0,nARTotal=0,nYSTotal=0
		
		IF @costing<>3
		BEGIN
			UPDATE	iniGoodsStocks SET Total = CAST(Total AS  NUMERIC(24, 10) )
			UPDATE	iniGoodsStocks SET Price = dbo.F_RoundPrice(Total/Qty) WHERE	Qty <> 0
		END
		--9.7数量为零，金额不为零的数据不删
		DELETE FROM iniCommissionStock WHERE Qty = 0 AND Total=0 AND CostTotal=0
		DELETE FROM dbo.IniCommissionStock_Qty WHERE Qty=0 AND NQty=0
		UPDATE	iniCommissionStock SET Total = CAST(Total AS  NUMERIC(24, 10) ),CostTotal = CAST(CostTotal AS  NUMERIC(24, 10) )
		
		-- 清空累计金额、积分，保留初始金额、积分
		-- 清空累计储值金额、消费储值金额、储值余额
		-- 清空可洗车次数,累计可洗车次数 毛欣蓉 2010-08-18
		-- A8清除会员卡信息期初数据,V3 V1 需要显示,A8不显示
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName='ProInfo' AND SubValue=2)
		BEGIN
			UPDATE nVipCardSign 
			SET 
				TotalMoney = 0,
				TotalCent = 0,
				qCczMoney = 0,
				lJczMoney = 0,
				xFczMoney = 0,
				cZyeMoney = 0,
				CanWashTimes= 0 ,
				CanWashTimes00 = 0,
				CanWashTimesTotal = 0
		END
		ELSE
		BEGIN
			UPDATE nVipCardSign 
			SET 
				TotalMoney = 0,
				TotalCent = 0,
				lJczMoney = 0,
				xFczMoney = 0,
				cZyeMoney=qCczMoney,
				CanWashTimes= CanWashTimes00 ,
				CanWashTimesTotal = 0
		END	
		/* 
		** 累计已消费储值金额=累计已消费储值金额-本年消费储值金额
		** 累计储值金额=累计储值金额-本年储值金额
		** 累计消费金额=累计消费金额-本年消费金额
		** 储值余额=累积储值余额-累计已消费储值余额
		** 本年储值金额清零
		** 本年消费储值金额清零
		** 本年消费金额清零
		*/
		UPDATE nVipCardSignStype
		SET 
			lJxFczMoney=lJxFczMoney-BnXFCzMoney,	
			LjCzMoney=LjCzMoney-BnCzMoney,			
			LjXfMoney=LjXfMoney-BnXFMoney,			
			BnCzMoney=0,							
			BnXFCzMoney=0,							
			BnXFMoney=0								
		
		UPDATE dbo.nVipCardSignStype
		SET 
			CzYeMoney=LjCzMoney-lJxFczMoney,
			qCczMoney=LjCzMoney-lJxFczMoney
		
		DELETE FROM wx_IniGoodsStocks WHERE Qty = 0 AND Nqty=0 AND Total=0
		DELETE FROM dbo.IniGoodsLend WHERE LendQty=0 AND BorrowQty=0 AND Qty=0
		
		--出纳
		UPDATE Te_InitDataIndex SET Finish=0;
	END
	
	----------------------------------------------处理不包含期初单据的单据的草稿-------------------------------
	IF @clearauditflow = 1
	BEGIN
		UPDATE dbo.BillIndex SET IfAudit=''	 WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=2) 
		UPDATE dbo.ReceiptBillIndex SET IfAudit=''	WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=5) 
		UPDATE dbo.OrderIndex SET IfAudit='' WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=0) 
		UPDATE dbo.LendIndex SET IfAudit='' WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=1) 
		UPDATE dbo.RequestIndex SET IfAudit=''  WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=3) 
		UPDATE dbo.CommissionBillNew SET BillState=1  WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=4) 
		
		--审核清除外键约束
		------------------------------------------删除外键开始-----------------------------------------------
		IF OBJECT_ID(N'[dbo].[FK_AuditingReason_AuditingFlowSet]', 'F') IS NOT NULL
		BEGIN
			ALTER TABLE [dbo].[AuditingReason] DROP CONSTRAINT [FK_AuditingReason_AuditingFlowSet];
		END
		IF OBJECT_ID(N'[dbo].[FK_AuditingFlowDetail_AuditingFlowSet]', 'F') IS NOT NULL
		BEGIN
			ALTER TABLE [dbo].[AuditingFlowDetail] DROP CONSTRAINT [FK_AuditingFlowDetail_AuditingFlowSet];
		END
		------------------------------------------删除外键结束-----------------------------------------------
		
		TRUNCATE TABLE dbo.AuditingBillDetail
		TRUNCATE TABLE dbo.AuditingBill
		TRUNCATE TABLE AuditingReason		--DELETE FROM AuditingReason
		TRUNCATE TABLE AuditingStepReason
		TRUNCATE TABLE AuditingFlowDetail	--DELETE FROM AuditingFlowDetail	--清掉审核的相关表 谢吉康  2004-02-26
		TRUNCATE TABLE AuditingFlowSet		--DELETE FROM AuditingFlowSet
	END
	
	IF @bRebulidDraft = 1     
	BEGIN		
		TRUNCATE TABLE retailBill		--零售单
		TRUNCATE TABLE retailBackBill		--零售退货
		TRUNCATE TABLE BeforePromoteIndex	--零售零售促销方案主表
		TRUNCATE TABLE BeforePromoteRetailBill	--零售零食促销方案明细
		TRUNCATE TABLE BeforePromoteSaleBill	--销售出库促销方案
		TRUNCATE TABLE DepBill				-- 固定资产折旧
		TRUNCATE TABLE GatheringBill		-- 收款单
		TRUNCATE TABLE PayBill				-- 付款单
		TRUNCATE TABLE LoseBill				-- 报损单
		TRUNCATE TABLE OverFlowBill			-- 报溢单
		TRUNCATE TABLE MoveMoneyBill		-- 转款单
		TRUNCATE TABLE adPriceBill			-- 成本调价单
		TRUNCATE TABLE MoveBill				-- 同价调拨单
		TRUNCATE TABLE MoveBjBill			-- 变价调拨单
		
		TRUNCATE TABLE PerformanceDistribution  --业绩分配

		TRUNCATE TABLE DisassembleBill		-- 生产拆装单
		TRUNCATE TABLE GiveMeBill			-- 获赠单
		TRUNCATE TABLE GiveBill				-- 赠送单
		TRUNCATE TABLE InvoiceBill			-- 发票表
		TRUNCATE TABLE STypeMoveBill		--分支机构调拨出库单，分支机构调拨入库单

		-- #01 begin
		TRUNCATE TABLE RepairDeal			--DELETE RepairDeal
		TRUNCATE TABLE RepairDealDetail		--DELETE RepairDealDetail
		TRUNCATE TABLE RepairEngage			--DELETE RepairEngage
		-- #01 end
		TRUNCATE TABLE AuditingBillDetail	--DELETE FROM AuditingBillDetail
		TRUNCATE TABLE AuditingBill			--DELETE FROM AuditingBill


		TRUNCATE TABLE GoodsExchangeBill	-- 换货单
		TRUNCATE TABLE AccountCredence		-- 会计凭证

		TRUNCATE TABLE	wx_bill_jiejian--维修接件单
		TRUNCATE TABLE	wx_bill_self--维修单
		TRUNCATE TABLE	wx_Bill_Send--送修单
		TRUNCATE TABLE	wx_bill_call--报修单
		TRUNCATE TABLE wx_Bill_In			-- 新维修 - 维修品调入单
		TRUNCATE TABLE wx_Bill_Out			-- 新维修 - 维修品调出单
		TRUNCATE TABLE wx_Bill_Move			-- 新维修 - 维修品调拨单
		TRUNCATE TABLE PrintRecord			--打印记录表
		TRUNCATE TABLE AddPrintCountRecord	--增加的打印次数记录
		TRUNCATE TABLE QuotePriceBill 			--(报价单) 
		TRUNCATE TABLE AskPriceBill 			--(询价单)
		
		TRUNCATE TABLE IntegralExchangeBill					--(积分兑换单明细表)		

		TRUNCATE TABLE ShareSourceBill						--费用分摊采购销售明细
		TRUNCATE TABLE ShareFeeBill							--费用分摊费用明细
		TRUNCATE TABLE OtherInOutBill						--其他出入库单明细
		TRUNCATE TABLE SerialAdjustIndex					--序列号调整单主表
		TRUNCATE TABLE SerialAdjustBill						--序列号调整单明细
		TRUNCATE TABLE CM_CarUseIndex  --（车辆使用登记单主表
		TRUNCATE TABLE CM_CarUseBill  --（车辆使用登记单明细表）
		TRUNCATE TABLE CM_FeeIndex --（车辆费用单主表） 
		TRUNCATE TABLE CM_FeeBill --（车辆费用单明细表）
		
		TRUNCATE TABLE LendIndex    --借欠
		TRUNCATE TABLE LendBill		--借欠
		TRUNCATE TABLE dbo.LendCheck--借欠 
		
		---------------实物库存 Start---------------
		DELETE FROM dbo.FactIndex WHERE isini=0 
		TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
		TRUNCATE TABLE dbo.Fact_InOutstocktable
		TRUNCATE TABLE dbo.gp_FactPtypeSerial
		TRUNCATE TABLE dbo.FactStocks
		TRUNCATE TABLE dbo.FactStocks_Qty
		TRUNCATE TABLE dbo.FactDepotInOut
		TRUNCATE TABLE dbo.FactDepotAllot
		---------------实物库存 End---------------
		
		
	END
	ELSE
	BEGIN
		--- 收款单 ---
		SELECT a.* INTO #GatheringBill FROM GatheringBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='4' AND b.Draft=1
		TRUNCATE TABLE GatheringBill
		SET IDENTITY_INSERT dbo.GatheringBill ON
		SET @columns=dbo.f_getallcolumns('GatheringBill')
		EXEC('INSERT INTO GatheringBill ('+@columns+') SELECT '+@columns+ ' FROM #GatheringBill')
		SET IDENTITY_INSERT GatheringBill OFF
		DROP TABLE #GatheringBill		
		
		--清除业绩分配明细
		SELECT a.* INTO #PerformanceDistribution FROM PerformanceDistribution a INNER JOIN billindex b ON a.billnumberid=b.billnumberid
		TRUNCATE TABLE PerformanceDistribution
		SET IDENTITY_INSERT dbo.PerformanceDistribution ON
		SET @columns=dbo.f_getallcolumns('PerformanceDistribution')
		EXEC('INSERT INTO PerformanceDistribution ('+@columns+') SELECT '+@columns+ ' FROM #PerformanceDistribution')
		SET IDENTITY_INSERT PerformanceDistribution OFF
		DROP TABLE #PerformanceDistribution
		--DELETE FROM PerformanceDistribution WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)--清除业绩分配明细
		DELETE FROM PayBill			 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=PayBill.BillNumberId AND billtype ='66' AND Draft=1)	-- 付款单
		DELETE FROM LoseBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=LoseBill.BillNumberId AND  billtype ='9'  AND Draft=1)	-- 报损单
		DELETE FROM OverFlowBill	 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=OverFlowBill.BillNumberId AND  billtype ='14' AND Draft=1)	-- 报溢单
		DELETE FROM MoveMoneyBill	 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=MoveMoneyBill.BillNumberId AND  billtype ='77' AND Draft=1)	-- 转款单
		DELETE FROM adPriceBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=adPriceBill.BillNumberId AND  billtype ='57' AND Draft=1)	-- 成本调价单
		DELETE FROM RetailBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailBill.BillNumberId)			-- 零售单
		DELETE FROM RetailBackBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailBackBill.BillNumberId)			-- 零售退货
		DELETE FROM DepBill WHERE NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=DepBill.BillNumberId)	--固定资产折旧
		--- 同价调拨单 ---
		SELECT a.* INTO #MoveBill FROM MoveBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='17' AND b.Draft=1
		TRUNCATE TABLE MoveBill
		SET IDENTITY_INSERT MoveBill ON
		SET @columns=dbo.f_getallcolumns('MoveBill')
		EXEC('INSERT INTO MoveBill ('+@columns+') SELECT '+@columns+ ' FROM #MoveBill')
		SET IDENTITY_INSERT MoveBill OFF
		DROP TABLE #MoveBill
		
		DELETE FROM MoveBjBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=MoveBjBill.BillNumberId AND  billtype ='21' AND Draft=1)	-- 变价调拨单
		DELETE FROM RetailCombinationBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailCombinationBill.BillNumberId)			-- 零售单
		
		DELETE FROM DisassembleBill	 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=DisassembleBill.BillNumberId AND  billtype ='16' AND Draft=1)	-- 生产拆装单
		DELETE FROM GiveMeBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=GiveMeBill.BillNumberId AND  billtype ='126' AND Draft=1)	-- 获赠单
		DELETE FROM GiveBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=GiveBill.BillNumberId AND  billtype ='139' AND Draft=1)	-- 赠送单
		DELETE FROM InvoiceBill		 --WHERE BillNumberID NOT IN (SELECT * FROM BillIndex WHERE AND billtype ='11' AND Draft=1)	-- 发票表
		
        --- 分支机构调拨出库单，分支机构调拨入库单 ---
		SELECT a.* INTO #STypeMoveBill FROM STypeMoveBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype IN (187,188) AND b.Draft=1
		TRUNCATE TABLE STypeMoveBill
		SET IDENTITY_INSERT STypeMoveBill ON
		SET @columns=dbo.f_getallcolumns('STypeMoveBill')
		EXEC('INSERT INTO STypeMoveBill ('+@columns+') SELECT '+@columns+ ' FROM #STypeMoveBill')
		SET IDENTITY_INSERT STypeMoveBill OFF
		DROP TABLE #STypeMoveBill
        
		DELETE RepairDeal WHERE NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=RepairDeal.BillNumberID)
		DELETE RepairDealDetail WHERE NOT EXISTS (SELECT 1 FROM RepairDeal WHERE BillNumberId=RepairDealDetail.BillNumberID)
		DELETE RepairEngage WHERE NOT EXISTS(SELECT 1 FROM RepairDeal WHERE EngageBillID=RepairEngage.BillNumberID) AND Draft <> 0

		--清掉审核的相关表 谢吉康  2004-02-26
		DELETE FROM AuditingBillDetail WHERE BillNumberID NOT IN (SELECT BillNumberID FROM BillIndex)
		DELETE FROM AuditingBill WHERE BillNumberID NOT IN (SELECT BillNumberID FROM BillIndex)

		DELETE FROM GoodsExchangeBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=GoodsExchangeBill.BillNumberId AND  BillType ='155' AND Draft=1)	-- 换货单
		DELETE FROM AccountCredence	 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AccountCredence.BillNumberId AND  billtype ='159' AND Draft=1)	-- 会计凭证
		
		DELETE FROM	wx_bill_jiejian WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_bill_jiejian.BillNumberId  AND Draft=1)--维修接件单
		DELETE FROM	wx_bill_self WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_bill_self.BillNumberId  AND Draft=1)--维修单
		DELETE FROM	wx_Bill_Send WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_Bill_Send.BillNumberId  AND Draft=1)--送修单
		DELETE FROM	wx_bill_call WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_bill_call.BillNumberId  AND Draft=1)--报修单
		DELETE FROM wx_Bill_In WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_Bill_In.BillNumberId AND  BillType ='173' AND Draft=1)			-- 新维修 - 维修品调入单
		DELETE FROM wx_Bill_Out WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_Bill_Out.BillNumberId AND  BillType ='174' AND Draft=1)		-- 新维修 - 维修品调出单
		DELETE FROM wx_Bill_Move WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_Bill_Move.BillNumberId AND  BillType ='175' AND Draft=1)		-- 新维修 - 维修品调拨单
		DELETE FROM QuotePriceBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=QuotePriceBill.BillNumberId AND  BillType ='184' AND Draft=1)
		DELETE FROM AskPriceBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AskPriceBill.BillNumberId AND  BillType ='185' AND Draft=1)
		
		DELETE FROM IntegralExchangeBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=IntegralExchangeBill.BillNumberId AND  BillType ='183' AND Draft=1)
		DELETE FROM BillIndex WHERE BillType IN (191,197) AND ISNULL(BTypeId,'') <> ''
		TRUNCATE TABLE ShareSourceBill	--费用分摊出入库单明细
		TRUNCATE TABLE ShareFeeBill		--费用分摊费用明细
		DELETE FROM OtherInOutBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=OtherInOutBill.BillNumberId AND  draft = 1)
		DELETE FROM SerialAdjustIndex WHERE   draft = 0
		DELETE FROM SerialAdjustBill WHERE NOT EXISTS(SELECT 1 FROM SerialAdjustIndex WHERE draft = 1 AND BillNumberId=SerialAdjustBill.BillNumberId)
		
		DELETE FROM LendBill WHERE BillNumberId IN(SELECT BillNumberId FROM dbo.LendIndex WHERE ifcheck='t') --借欠
		DELETE FROM LendIndex WHERE  draft = 0 
		TRUNCATE TABLE dbo.LendCheck  --借欠 
		
		DELETE FROM ReceiptBill WHERE Not EXISTS (SELECT 1 FROM dbo.ReceiptBillIndex WHERE Draft=1 AND BillNumberID=ReceiptBill.BillNumberID)
		DELETE FROM ReceiptBillIndex WHERE Draft=0  AND IsIni=0
		
		DELETE FROM dbo.FactIndex WHERE ifcheck='t' AND IsIni=0
		DELETE FROM dbo.FactDepotAllot WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
		DELETE FROM dbo.FactDepotInOut WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
		TRUNCATE TABLE dbo.FactStocks
		TRUNCATE TABLE dbo.FactStocks_Qty
		TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
		TRUNCATE TABLE dbo.Fact_InOutstocktable
		TRUNCATE TABLE dbo.gp_FactPtypeSerial
	END		
	
	TRUNCATE TABLE dbo.tmpGain
	
    ------------------------------------------------处理其他----------------------------------------------------------------------
    --自定义删除
	;WITH CustomExists
	 AS
	 (
		SELECT BillType,BillNumberID FROM dbo.BillIndex
		UNION ALL
		SELECT BillType,BillNumberID FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillType,BillNumberID FROM dbo.OrderIndex
		UNION ALL 
		SELECT BillType,BillNumberID FROM dbo.LendIndex
		UNION ALL
		SELECT 204 AS BillType,BillNumberID FROM dbo.RequestIndex
		UNION ALL 
		SELECT 311 AS BillType,BillNumberId FROM dbo.CommissionBillNew
		UNION ALL 
		SELECT BillType,BillNumberID FROM dbo.FaPiaoBillIndex
		UNION ALL
		SELECT BillType,BillNumberid FROM dbo.FactIndex
	 )
	SELECT BillType,BillNumberID INTO #CustomExists FROM CustomExists
	--9.7自定义
	DELETE A FROM dbo.Custom_BillIndex A WHERE NOT EXISTS(SELECT 1 FROM #CustomExists WHERE BillType=A.BillType AND BillNumberID=A.BillId)
	DELETE A FROM dbo.Custom_BillDetails A WHERE NOT EXISTS(SELECT 1 FROM #CustomExists WHERE BillType=A.BillType AND BillNumberID=A.BillId)
	--<9.7自定义
	DELETE FROM  CustomBillColumns WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.CustomBillColumns.BillNumberId)
	DELETE FROM  CustomBillDetailColumns WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.CustomBillDetailColumns.BillNumberId AND BillType=dbo.CustomBillDetailColumns.billtype)
														AND NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.CustomBillDetailColumns.billnumberid AND dbo.CustomBillDetailColumns.billtype=9999)
	DROP TABLE #CustomExists
			
    --清除多账户
	DELETE FROM BillMulAccount WHERE NOT EXISTS(SELECT 1 FROM BillIndex b WHERE b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype=BillMulAccount.billtype
												UNION 
												SELECT  1 FROM dbo.Coupon_BillIndex b WHERE b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype=BillMulAccount.billtype)	
	--清除品牌多账户
	DELETE FROM BillMulBrand WHERE NOT EXISTS(SELECT 1 FROM BillIndex b WHERE b.BillNumberId=BillMulBrand.BillNumberId AND b.billtype=BillMulBrand.billtype
												UNION 
												SELECT  1 FROM dbo.Coupon_BillIndex b WHERE b.BillNumberId=BillMulBrand.BillNumberId AND b.billtype=BillMulBrand.billtype)				
		
	IF @bitRecPrice = 1
	BEGIN
		UPDATE PType SET recPrice=0
		UPDATE dbo.PType_Price SET RecAmgSTypeBuyPrice=0
		UPDATE PType_STypePrice SET RecPrice=0
	END

	--清除打印记录
	SELECT billnumberid,billtype INTO #PrintTmp 
	FROM 
		(SELECT BillNumberId,BillType FROM  BillIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  OrderIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  requestindex
		UNION ALL
		SELECT BillNumberId,BillType FROM FaPiaoBillIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  serialadjustindex
		UNION ALL
		SELECT BillNumberId,164 FROM  TCBillindex
		UNION ALL
		SELECT BillNumberId,BillType FROM  V_LendFace
		UNION ALL
		SELECT ProduceModelID,127 FROM  producemodelindex
		UNION ALL
		SELECT stockCheckID,306 FROM  StockCheckIndex
		UNION ALL 
		SELECT BillNumberId,BillType FROM CM_CarUseIndex
		UNION ALL 
		SELECT BillNumberId,BillType FROM CM_FeeIndex ) A 
		
        --- 打印记录 ---
	SELECT a.* INTO #printrecord FROM printrecord a INNER JOIN #PrintTmp b ON a.billnumberid=b.billnumberid WHERE a.billtype=b.BillType
	TRUNCATE TABLE printrecord
	INSERT INTO dbo.PrintRecord select * FROM #printrecord	
	    --- 增加打印次数记录 ---
	SELECT a.* INTO #AddPrintCountRecord FROM AddPrintCountRecord a INNER JOIN #PrintTmp b ON a.billnumberid=b.billnumberid  WHERE a.billtype=b.BillType
	TRUNCATE TABLE AddPrintCountRecord
	INSERT INTO AddPrintCountRecord (billtype,BillNumberId,etypeid,addprintcount) select billtype,BillNumberId,etypeid,addprintcount from #AddPrintCountRecord
	
	--------------------清除附件和附件log start-------------------------------
	SELECT * INTO #BillAttachFiles FROM BillAttachFiles WHERE EXISTS (SELECT 1 FROM #PrintTmp WHERE BillNumberId=BillAttachFiles.BillNumberId AND BillType=BillAttachFiles.BillType)
	TRUNCATE TABLE dbo.BillAttachFiles
	SET IDENTITY_INSERT dbo.BillAttachFiles ON
	SET @columns=dbo.f_getallcolumns('BillAttachFiles')
	EXEC('INSERT INTO BillAttachFiles ('+@columns+') SELECT '+@columns+ ' FROM #BillAttachFiles')
	SET IDENTITY_INSERT BillAttachFiles OFF
	
	SELECT * INTO #BillAttachFileslog FROM BillAttachFileslog WHERE EXISTS (SELECT 1 FROM #PrintTmp WHERE BillNumberId=BillAttachFileslog.BillNumberId AND BillType=BillAttachFileslog.BillType)
	TRUNCATE TABLE dbo.BillAttachFileslog
	SET IDENTITY_INSERT dbo.BillAttachFileslog ON
	SET @columns=dbo.f_getallcolumns('BillAttachFileslog')
	EXEC('INSERT INTO BillAttachFileslog ('+@columns+') SELECT '+@columns+ ' FROM #BillAttachFileslog')
	SET IDENTITY_INSERT BillAttachFileslog OFF
	--------------------清除附件和附件log end-------------------------------
	
	DROP TABLE #PrintTmp,#AddPrintCountRecord,#printrecord,#BillAttachFiles,#BillAttachFileslog
	
	IF @bitMessage='1'
	BEGIN
		--TRUNCATE TABLE IM_Message
		TRUNCATE TABLE IM_Message_NoSocket
		TRUNCATE TABLE IM_Message_NoSocket_Bak
	END
	
	--
	--处理IM消息，把有编号的清空
	UPDATE dbo.IM_Message_NoSocket SET BillNumberId=0
	--
	IF @bitPosdata='1'
	BEGIN
		TRUNCATE TABLE dbo.PosSaleBill
		TRUNCATE TABLE dbo.PosSaleBillIndex
		TRUNCATE TABLE dbo.PosMulAccount
		TRUNCATE TABLE dbo.PosSaleBillAll
		TRUNCATE TABLE dbo.PosSaleBillIndexAll
		TRUNCATE TABLE dbo.PosMulAccountAll
		TRUNCATE TABLE dbo.PosSaleMergeFailed
		TRUNCATE TABLE dbo.PosRetailRecord
	END
	ELSE
	BEGIN
		DELETE FROM dbo.PosRetailRecord 
		WHERE RetailBillNumberId NOT IN(SELECT BillNumberID FROM dbo.BillIndex WHERE BillType IN(215,305)) AND 
			  PosBillNumberId NOT IN (SELECT BillNumberID FROM dbo.PosSaleBillIndexAll WHERE Billtype IN (215,305))
	END

	UPDATE AType SET Total = 0
	UPDATE BType SET arTotal = 0,apTotal = 0
	--DELETE FROM dbo.Ac_Period WHERE FYear<>(SELECT MIN(FYear) FROM Ac_Period)
	DELETE FROM Monthproc WHERE MonthNo <> '本期'
	DECLARE @period INT=1,@fyear INT,@startdate DATETIME
	SELECT @fyear=subvalue FROM dbo.sysdata WHERE SubName='fyear'
	SELECT @period=FMonth,@startdate=FBegin FROM dbo.Ac_Period WHERE FPeriod=FMonth AND fyear=@fyear
	
	UPDATE	A 
	SET		StartDate=ISNULL(FBegin,@StartDate),
			period=ISNULL(B.SFPeriod,1),
			Year=ISNULL(B.SFYear,YEAR(@StartDate))
	FROM	dbo.MonthProc A,
			dbo.SType_UserConfig B,dbo.Ac_Period C
	WHERE	A.STypeID=B.StypeId 
			AND B.SFPeriod=C.FPeriod 
			AND B.SFYear=C.FYear AND A.MonthNo='本期'
	
	UPDATE SysData SET SubValue = '0000000000' WHERE SubName LIKE '%Code' and SubName NOT IN('bwbcode','hyyunsms_usercode')--排除短信账号
	UPDATE SysData SET SubValue='1' WHERE SubName = 'period'
	
	UPDATE SysData SET SubValue=@period WHERE SubName = 'FPeriod'
	UPDATE SysData SET SubValue='1' WHERE SubName = 'CanAuditing'

	UPDATE UserConfig SET Value = '0' WHERE ConfigName = 'AverageCostPrice'

	UPDATE SysData SET SubValue='T' WHERE SubName = 'inicanmodify' 
	
	UPDATE	SType_UserConfig
	SET		Value=0
	FROM	SType_Config b
	WHERE	SType_UserConfig.ConfigNo=b.ConfigNo  
			AND b.ConfigName='stypeinicanmodify'
	
	--父节点没有存在的必要了
	DELETE FROM dbo.SType_UserConfig
	WHERE StypeId IN (SELECT typeid FROM dbo.SType WHERE sonnum>0)
	
	---add by dongzhan  version9.2
	--TRUNCATE TABLE Ac_AccountsPeroid_Stype
	UPDATE Ac_AccountsPeroid_Stype SET FYear = SFYear,FPeriod = SFPeriod,IsUse =0
	
	--修改期初序列号的入库时间
	UPDATE GP_InitPTypeSerial SET InKtypeTime = NULL
	
	
	--判断创建删除单据的触发器
	EXEC GP_SystemRebuild_CreateTrigger
	
	--是否清除商品最近售价 0 - 不清除，1 - 清除
	IF @bitRecSalePrice = '1'
	BEGIN
		UPDATE PType_STypePrice SET RecSalePrice = 0 , RecAppraisalPrice = 0 ,RecSendPrice =0
		
		UPDATE dbo.PType_Price SET RecAmgSTypeSalePrice=0
	END
	--系统重建，单据编号种子数处理
	EXEC GP_BillCode_Seed_ReBuild
	
	EXEC GP_OldBill_Clone_Del
	
    EXEC GP_FixedAssets_ReBuild @bRebulidIni,@bRebulidDraft	
    
    --重建更新已完成订单状态
    UPDATE OrderIndex SET OrderState=0 WHERE OrderState=1 and billNumberId not in (SELECT BillNumberID FROM Ini_GoodsStocks_Order)
    
    --系统重建，重算草稿库存
    exec QP_Recount_DraftQty
    
     --系统重建，重算订单库存
    exec QP_Recount_OrderQty
    
    --系统重建，清除部分pos相关的数据
    exec QP_Clear_PosData
    
    --店账通单据的处理
    DELETE FROM EshopBillRelation WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
    
    --删除电子面单
    DELETE FROM BillExpressage WHERE VchCode NOT IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 11)
    
    ----删除WMS对应数据    
    --DELETE FROM WMS_ERPBillRelation WHERE ERP_BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
    
	COMMIT TRAN Rebulid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SystemRebuild_CreateTrigger]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SystemRebuild_CreateTrigger]
GO


/*
	作者：谢吉康
	日期：2020-02-17
	描述：系统重建创建触发器
*/
CREATE       PROCEDURE GP_SystemRebuild_CreateTrigger
AS
SET NOCOUNT ON

DECLARE @TRG VARCHAR(MAX)
IF NOT EXISTS (SELECT NAME FROM sysobjects WHERE   type='tr' AND NAME ='DeleteBill')
BEGIN
	SET @TRG ='	
		CREATE TRIGGER [DeleteBill] ON dbo.BillIndex 
		FOR  DELETE 
		AS
		------------------------------------------------------------处理单据删除影响草稿库存 start------------------------------------------------------------------------------------------
		CREATE TABLE #BillInfo
		(
			BillType 		INT,	--单据类型
			BillnumberID	INT	
		)
		
		DECLARE @BillNumberID	INT,
				@BillType		INT
		
		INSERT INTO #BillInfo SELECT BillType,BillnumberID FROM deleted WHERE draft=1 AND isini=0
		WHILE(EXISTS(SELECT 1 FROM #BillInfo))
		BEGIN
			SELECT TOP 1 @BillType=BillType,@BillnumberID=BillnumberID FROM #BillInfo
			EXEC GP_AuditingORDel_DraftQTY @BillnumberID,@BillType
			IF @BillType IN (11,12,34,140,144,400,402)
			BEGIN
				--处理明细waitqty
				DECLARE @qty NUMERIC(24, 10) ,@orderid int
				IF @billtype=12
				BEGIN
					UPDATE PT_Combin_OrderBillDetail 
					SET 
						WaitQty = ISNULL(PT_Combin_OrderBillDetail.WaitQty,0) - b.Qty
					FROM 
					(
						SELECT BillNumberId,OrderID,SUM(Qty) Qty
						FROM dbo.PT_Combin_SaleBillDetail
						WHERE BillNumberId=@billnumberid
						GROUP BY BillNumberId,OrderID
					) b
					WHERE PT_Combin_OrderBillDetail.OrderID=b.OrderID						  
					
					UPDATE PT_Combin_OrderBill 
					SET 
						WaitQty = ISNULL(PT_Combin_OrderBill.WaitQty,0) - b.Qty
					FROM 
					(
						SELECT BillNumberId,OrderID,SUM(Qty) Qty
						FROM dbo.PT_Combin_SaleBill
						WHERE BillNumberId=@billnumberid
						GROUP BY BillNumberId,OrderID
					) b
					WHERE PT_Combin_OrderBill.OrderID=b.OrderID	
			END
			ELSE
			BEGIN
				IF @billtype=11
					DECLARE cr_insertbill CURSOR FOR
					SELECT orderid,qty FROM salebill WHERE billnumberid=@billnumberid
				ELSE IF @billtype=12
					DECLARE cr_insertbill CURSOR FOR
					SELECT orderid,qty FROM PT_Combin_SaleBillDetail where billnumberid=@billnumberid
				ELSE IF @billtype=140
					DECLARE cr_insertbill CURSOR FOR
					SELECT orderid,qty FROM commissionbill WHERE billnumberid=@billnumberid
				ELSE IF @BillType=400
					DECLARE cr_insertbill CURSOR FOR
					SELECT orderid,qty FROM AppraisalBill WHERE billnumberid=@billnumberid
				ELSE IF @BillType=402
					DECLARE cr_insertbill CURSOR FOR
					SELECT orderid,qty FROM SENDBill WHERE billnumberid=@billnumberid
				ELSE IF @billtype=34
				DECLARE cr_insertbill CURSOR FOR
				SELECT orderid,qty FROM buybill WHERE billnumberid=@billnumberid
				ELSE IF @billtype=144
					DECLARE cr_insertbill CURSOR FOR
					SELECT orderid,qty FROM commissionbill WHERE billnumberid=@billnumberid
				 OPEN cr_Insertbill

				 FETCH NEXT FROM cr_insertbill INTO @orderid,@qty
				 WHILE @@FETCH_status<>-1
				 BEGIN
				  
				  UPDATE orderbill 
				  SET 
					WaitQty = ISNULL(WaitQty,0) - @qty
				  WHERE orderid=@orderid
				  
				  IF @@error<>0 
				  BEGIN
					  CLOSE cr_insertbill
					  DEALLOCATE cr_insertbill 
					  ROLLBACK TRAN
					  RETURN  
				  END
				  FETCH NEXT FROM cr_insertbill INTO @orderid,@qty
				 END

				 CLOSE cr_insertbill
				 DEALLOCATE cr_insertbill 
				END
			-- 处理订单库存,--先减去引用未过账数量
			EXEC GP_Deal_OrderReferQty @BillnumberID,@BillType,''-'',1
			END
			
			DELETE #BillInfo WHERE BillnumberID=@BillnumberID
		END
		------------------------------------------------------------处理单据删除影响草稿库存 start------------------------------------------------------------------------------------------
		BEGIN tran DelBill
		DELETE FROM salebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=11)
		DELETE FROM salebackbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=45)
		DELETE FROM gatheringbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=4)
		 
		DELETE FROM buybill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=34)
		DELETE FROM buybackbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=6)
		DELETE FROM paybill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=66)
		DELETE FROM losebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=9)
		DELETE FROM overflowbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=14)
		DELETE FROM disassemblebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=16)
		DELETE FROM movemoneybill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=77)
		DELETE FROM adDebtbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype IN(115,116,128,129))
		DELETE FROM adpricebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=57)
		DELETE FROM movebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=17)
		DELETE FROM movebjbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=21)
		DELETE FROM Commissionbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype IN(201,202))
		DELETE FROM moneybill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype IN(35,36,84,85,78,5,10,93,158))-- 加入费用单和一般收入单
		DELETE FROM Retailbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=305)
		--固定资产
		DELETE FROM AssetIncDecBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE billtype=212)
		DELETE FROM AssetIncDecBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE billtype=213)
		DELETE FROM DepBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE billtype=214)
		DELETE FROM FixedAssetsDetails WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE billtype=307)
		-- 加入商品换货单
		DELETE FROM GoodsExchangeBill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=155)
		--加入获利、返利
		DELETE FROM Advantage WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype IN (148,150))
		--加入价保执行、获得价保
		DELETE FROM PriceProtectBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype IN (149,151))
		-- 加入会计凭证
		DELETE FROM AccountCredence WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=159)
		-- 加入销售换货单
		DELETE FROM SaleGoodsExchangeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=160)
		-- 加入采购换货单
		DELETE FROM BuyGoodsExchangeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=161)
		-- 新维修 - 接件单
		DELETE FROM wx_Bill_JieJian WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=165)
		-- 新维修 - 维修单
		DELETE FROM wx_Bill_Self WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=166)
		-- 新维修 - 维修取件单
		DELETE FROM wx_Bill_GetBack WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=167)
		-- 新维修 - 整机更换单
		DELETE FROM wx_Bill_Replace WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=168)
		-- 新维修 - 送修单
		DELETE FROM wx_Bill_Send WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=169)
		-- 新维修 - 送修返回单
		DELETE FROM wx_Bill_SendBack WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=170)
		-- 新维修 - 报修单
		DELETE FROM wx_Bill_Call WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=171)
		-- 新维修 - 上门维修单
		DELETE FROM wx_Bill_Goto WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=172)
		-- 新维修 - 维修品调入单
		DELETE FROM wx_Bill_In WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=173)
		-- 新维修 - 维修品调出单
		DELETE FROM wx_Bill_Out WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=174)
		-- 新维修 - 维修品调拨单
		DELETE FROM wx_Bill_Move WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=175)
		-- 赠送单
		DELETE FROM GiveBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=139)
		-- 获赠单
		DELETE FROM GiveMeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=126)
		--维修估价单
		DELETE FROM QP_EvaluationBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=177)
		DELETE FROM QP_EvaluationBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=177)
		--快修单
		DELETE FROM QP_QuickRepairBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=178)
		DELETE FROM QP_QuickRepairBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=178)
		--洗车结算单
		DELETE FROM QP_WashCarBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=179)	
		--旧件回收单
		DELETE FROM QP_RecycleBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=180)
		--积分兑换单
		DELETE FROM IntegralExchangeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=183)	
		--报价单
		DELETE FROM QuotePriceBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=184)		
		--询价单
		DELETE FROM AskPriceBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=185)		
		--保险理赔单
		DELETE FROM QP_InsuranceBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=186)
		DELETE FROM QP_InsuranceBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=186)		
		--分支机构调拨出库单，分支机构调拨入库单
		DELETE FROM STypeMoveBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype IN (187,188))	
		--预收款单，预付款单
		DELETE FROM PreBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype IN (189,190))	
		--领料出库单
		DELETE FROM Qp_PickingBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=191)	
		--返修单
		DELETE FROM Qp_BackingOut_Bill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=192)	
		--接待登记
		DELETE FROM Qp_ReceptionBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)
		DELETE FROM Qp_ReceptionBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)	
		DELETE FROM Qp_ReceptionBill_Pic WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)	
		DELETE FROM Qp_ReceptionBill_Accessory WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)	
		DELETE FROM Qp_ReceptionBill_Insurance WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)	
		DELETE FROM Qp_AttemperBill_RepairItemsPerson WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)
		--救援单
		DELETE FROM Qp_SuccorBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单,是BillIndex_CarRepair的衍生表
		DELETE FROM Qp_SuccorBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单_维修项目明细表
		DELETE FROM Qp_SuccorBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单_配件明细表
		DELETE FROM Qp_SuccorBill_SuccorItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单_救援项目明细表
		DELETE FROM Qp_SuccorBill_ErrDescription WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单_故障描述	
		--领料退回单
		DELETE FROM Qp_PickingBackBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=197)
		--维修回访单
		DELETE FROM Qp_IntendingTalkBack_Bill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=198)
		--三包索赔单
		DELETE FROM Qp_ThreePacketsBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=200)--三包索赔单_维修项目明细表
		DELETE FROM Qp_ThreePacketsBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=200)--三包索赔单_维修配件明细表
	    --序列号调整单
		DELETE FROM SerialAdjustBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=203)
		--其他出、入库单
		DELETE FROM OtherInOutBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype in(201,202))
		--采购、销售费用分摊
		DELETE FROM ShareSourceBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype in(205,206))--费用分摊出入库单明细
		DELETE FROM ShareFeeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype in(205,206))--费用分摊费用明细		
	
		DELETE FROM AppraisalBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE BillType=400)--暂估入库
		DELETE FROM AppraisalBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE BillType=401)-- 暂估退货
		DELETE FROM SendBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE BillType=402)--发出商品
		DELETE FROM SendBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE BillType=403)--发出商品退货
		--单据自定义
		DELETE FROM CustomBillColumns FROM deleted WHERE CustomBillColumns.billnumberid = deleted.BillNumberId AND 	CustomBillColumns.billtype = deleted.BillType
		DELETE FROM CustomBillDetailColumns FROM deleted WHERE CustomBillDetailColumns.billnumberid = deleted.BillNumberId AND 	CustomBillDetailColumns.billtype = deleted.BillType	
		DELETE FROM RetailCombinationBill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=305)
		DELETE FROM dbo.Transportbill WHERE billNumberID IN(SELECT billNumberID FROM deleted WHERE billtype=414)
		DELETE FROM dbo.Transportcontrastbill WHERE billNumberID IN(SELECT billNumberID FROM Deleted WHERE billtype=414)
		DELETE FROM dbo.PT_Combin_SaleBackBill FROM deleted WHERE PT_Combin_SaleBackBill.billnumberid = deleted.BillNumberId AND 	billtype=46
		DELETE FROM dbo.PT_Combin_SaleBackBillDetail FROM deleted WHERE PT_Combin_SaleBackBillDetail.billnumberid = deleted.BillNumberId AND 	billtype=46	
		DELETE FROM dbo.PT_Combin_SaleBill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=12)
		DELETE FROM dbo.PT_Combin_SaleBillDetail WHERE billNumberID IN(SELECT billNumberID FROM deleted WHERE billtype=12)
		
		DELETE FROM Custom_BillIndex  FROM deleted b WHERE BillId=b.BillNumberId AND b.BillType=Custom_BillIndex.BillType
		DELETE FROM Custom_BillDetails  FROM deleted b WHERE BillId=b.BillNumberId AND b.BillType=Custom_BillDetails.BillType
		
		--积分转储值单
		DELETE FROM dbo.VipCentToMoneyBill WHERE billNumberID IN (SELECT billNumberID FROM deleted WHERE billtype=427)		 
		
		/*
			作者：谢吉康
			日期：2004-2-6
			描述：如果有审核，则删除单据审核里面的数据
		*/
		DECLARE @AuditCount INT
		SELECT @AuditCount=COUNT(AuditingBill.BillNumberID) FROM AuditingBill INNER JOIN deleted ON AuditingBill.BillNumberID=deleted.billnumberid WHERE AuditingBill.BillIndexType=2
		
		IF ISNULL(@AuditCount,0) <> 0
		BEGIN
			DELETE FROM AuditingBillDetail WHERE BillNumberID IN(SELECT billnumberid FROM deleted) AND BillIndexType=2
			DELETE FROM AuditingBill WHERE BillNumberID IN(SELECT billnumberid FROM deleted) AND BillIndexType=2
		END

		-- 加入代销单据
		DELETE FROM CommissionBill WHERE BillNumberID IN (SELECT billnumberid FROM deleted WHERE billtype in(140,141,142,143,144,145,147))
		
		 DELETE FROM inoutstocktable WHERE BillType NOT IN (404,405) AND billnumberid IN (SELECT billnumberid FROM deleted)
		 DELETE FROM Listtable WHERE BillType NOT IN (404,405,423,424,425,426) AND billnumberid IN(SELECT billnumberid FROM deleted)
		 
		 DELETE FROM dbo.BillMulAccount WHERE EXISTS (SELECT billnumberid FROM deleted WHERE Deleted.billtype=dbo.BillMulAccount.BillType AND Deleted.BillNumberId=dbo.BillMulAccount.BillNumberId)
		 DELETE FROM dbo.BillMulBrand WHERE EXISTS (SELECT billnumberid FROM deleted WHERE Deleted.billtype=dbo.BillMulBrand.BillType AND Deleted.BillNumberId=dbo.BillMulBrand.BillNumberId)
		 DELETE FROM dbo.Coupon_BillUsed WHERE EXISTS (SELECT billnumberid FROM deleted WHERE Deleted.billtype=dbo.Coupon_BillUsed.BillType AND Deleted.BillNumberId=dbo.Coupon_BillUsed.BillNumberId)
		
		COMMIT tran DelBill '
		
	--PRINT @TRG
	EXEC (@TRG)	
END
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SystemRebuild_Stype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SystemRebuild_Stype]
GO


/*
	作者：谢吉康
	日期：2010-10-09
	描述：系统重建 - 按分支机构
*/
CREATE       PROCEDURE GP_SystemRebuild_Stype
(
    @etypeID					VARCHAR(50), 
	@bRebulidIni				bit,				-- 是否清除期初；0 - 不清除，1 - 清除
	@bRebulidDraft				bit,				-- 是否清除草稿；0 - 不清除，1 - 清除
	@bitRecPrice				bit,				-- 是否清除最近进价；0 - 不清除，1 - 清除
	@bitEventLog				bit,				-- 是否清除操作日志
	@bitPriceTrack				bit,				-- 是否清除价格跟踪信息；0 - 不清除，1 - 清除
	@bitRecSalePrice			BIT,				-- 是否清除商品最近售价 0 - 不清除，1 - 清除
	@bitMessage					BIT,				-- 是否清除聊天记录；0 - 不清除，1 - 清除
	@bitPosdata					BIT,				-- 是否清除小票数据
	@bitRecSTypeBuyPrice		BIT,				-- 是否清除分支机构间最近进价 0 - 不清除， 1 - 清除
	@bitRecSTypeSalePrice		BIT,				-- 是否清除分支机构间最近售价 0 - 不清除， 1 - 清除
	@bitSTypePriceTrack			BIT,				-- 是否清除分支机构间价格跟踪信息 0 - 不清除， 1 - 清除
	@clearauditflow				BIT,				-- 是否除审核流程	0 - 不清除， 1 - 清除
	@clearStopOrder				BIT,				-- 是否清除已中止订单	0 - 不清除， 1 - 清除
	@clearCompleteOrder			BIT,				-- 是否清除已完成订单	0 - 不清除， 1 - 清除
	@clearAllOrder				BIT,				-- 是否清除所有订单	0 - 不清除， 1 - 清除
	@clearCompleteAllotApply	BIT,				--是否清除已完成的调货申请单 0-不清除 1-清除
	@clearNoCompleteAllotApply	BIT,				--是否清除未完成的调货申请单 0-不清除 1-清除
	@clearcompletegetbillapply BIT,--是否清除已完成的要货申请单 0-不清除 1-清除
	@clearnocompletegetbillapply BIT,--是否清除未完成的要货申请单 0-不清除 1-清除
	@logid						INT, 				--当前操作日志ID
	@stypeid					VARCHAR(MAX) = ''	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN TRAN Rebulid
	IF EXISTS  (SELECT  * FROM dbo.SysObjects WHERE ID = object_id(N'[Cost_NoRelog]') AND OBJECTPROPERTY(ID, 'IsTable') = 1) 
	BEGIN
		TRUNCATE TABLE Cost_NoRelog    -- 不知道什么表
	END	
	
	--delete from sysdata where SubNo=999
	--insert into sysdata select 999,'sysbuild by',TypeID,CAST(FullName AS varchar(30)) from Employee where TypeId = @etypeID
	-----------------------------------------构建操作明细信息 start-------------------------------------------------------------
	IF @logid>0
	BEGIN
		DECLARE @logdata VARCHAR(2000)
		SET @logdata='cInit='+CAST(@bRebulidIni AS varchar(30))+';cDraft='+CAST(@bRebulidDraft AS varchar(30))+';chkRecPrice='+CAST(@bRebulidDraft AS varchar(30))
		+';chkEventLog='+CAST(@bitEventLog AS varchar(30))+';chkPriceTrack='+CAST(@bRebulidDraft AS varchar(30))+';chkRecSalePrice='+CAST(@bitRecSalePrice AS varchar(30))
		+';chkclearmessage='+CAST(@bitMessage AS varchar(30))+';chkclearposdata='+CAST(@bitPosdata AS varchar(30))+';chkstyperecbuyprice='+CAST(@bitRecSTypeBuyPrice AS varchar(30))
		+';chkstyperecsaleprice='+CAST(@bitRecSTypeSalePrice AS varchar(30))+';chkstypepricetrack='+CAST(@bitSTypePriceTrack AS varchar(30))+';clearauditflow='+CAST(@clearauditflow AS varchar(30))
		+';clearstoporder='+CAST(@clearStopOrder AS varchar(30))+';clearcompleteorder='+CAST(@clearCompleteOrder AS varchar(30))+';clearallorder='+CAST(@clearAllOrder AS varchar(30))
		+';clearCompleteAllotApply=' + CAST(@clearCompleteAllotApply AS varchar(30)) + ';clearNoCompleteAllotApply=' + CAST(@clearNoCompleteAllotApply AS varchar(30))
		+';stypeid='+CAST(@stypeid AS VARCHAR(50))
		
		UPDATE dbo.EventLog SET LogData=@logdata WHERE id=@logid
	END
	-----------------------------------------构建操作明细信息   end-------------------------------------------------------------	
	
	--系统重建所有锁库数据进行解锁
	DELETE FROM PT_SaleOrderLockDetail WHERE KTypeId IN (SELECT Typeid FROM Stock WHERE STypeID = @stypeid)	
	UPDATE Ini_GOODSSTOCKS_QTY SET LockNumber=0 WHERE KTypeId IN (SELECT Typeid FROM Stock WHERE STypeID = @stypeid)			--清楚期初锁库信息
	UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber=0 WHERE KTypeId IN (SELECT Typeid FROM Stock WHERE STypeID = @stypeid)			--清除订单锁库信息
	UPDATE OrderBill SET LockNumber=0 WHERE KTypeId IN (SELECT Typeid FROM Stock WHERE STypeID = @stypeid)						--清除订单锁库信息
	UPDATE PT_Combin_OrderBillDetail SET LockNumber=0 WHERE KTypeId IN (SELECT Typeid FROM Stock WHERE STypeID = @stypeid)		--清除组合品订单锁库信息	
	-------------------------- 专门对 BillIndex、以及主表在billindex中的期初单据进行处理 start---------------------------------
	
	DECLARE @columns VARCHAR(max)=''	--表的列名
	
	--收集需要删除的主表单据
	CREATE TABLE #DelBillIndex
	(
		BillNumberId	NUMERIC(18,0)
	)	
	INSERT INTO #DelBillIndex(BillNumberId) SELECT BillNumberId FROM dbo.BillIndex WHERE stypeid = @stypeid
	
	IF @bRebulidDraft = 1 AND @bRebulidIni = 1
		BEGIN
			DELETE FROM dbo.BillIndex WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM dbo.BillOperateLog WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			---------------------主表在billindex中的期初单据-------------
			DELETE FROM	SaleBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM PT_Combin_SaleBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM PT_Combin_SaleBillDetail WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM	SaleBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM PT_Combin_SaleBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM PT_Combin_SaleBackBillDetail WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM	buybill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM	buybackbill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM	SaleGoodsExchangeBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM	BuyGoodsExchangeBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM	CommissionBill
			DELETE FROM	retailbill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM	PreBill	WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)			--预收预付
			DELETE FROM	AdDebtBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)			--调账单
			DELETE FROM	wx_Bill_GetBack WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)		--维修取件单
			DELETE FROM	wx_Bill_Replace	WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)	--整机更换单
			DELETE FROM	wx_Bill_SendBack WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)	--送修返回单
			DELETE FROM	wx_bill_goto WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)		--上门维修单
			DELETE FROM MoneyBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)			--其他收入、费用单、固定资产购买及变卖、费用单
			DELETE FROM	PriceProtectBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)	-- 价保单
			DELETE FROM	Advantage WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)			--返利、获利单
			DELETE FROM BillIndex_CarRepair WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM AssetIncDecBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)		--固定资产增加减少单
			DELETE FROM DepBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			--9.7 自定义
			DELETE FROM dbo.Custom_BillIndex WHERE BillId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM dbo.Custom_BillDetails WHERE BillId IN (SELECT BillNumberId FROM #DelBillIndex)
			--<9.7自定义
			DELETE FROM CustomBillColumns WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM CustomBillDetailColumns WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			
			DELETE FROM CommissionBillNew WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			DELETE FROM CommissionBillNewDetail WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)
			
			DELETE FROM CapitalTransfer_Bill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex) --资金调拨单
			DELETE FROM dbo.VipAddMoneyBatchBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex) --会员批量充值
			DELETE FROM dbo.VipCentToMoneyBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex) --会员积分转储值单
			DELETE FROM ChargeOffBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)	--往来核销单明细

			DELETE FROM AppraisalBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)--暂估入库
			DELETE FROM AppraisalBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)--暂估退货
			DELETE FROM SendBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)--发出商品出库
			DELETE FROM SendBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM #DelBillIndex)--发出商品退货
			
			DELETE FROM ReceiptBillIndex WHERE stypeid = @stypeid  --发票主表
			DELETE FROM ReceiptBill WHERE BillNumberID NOT IN (SELECT BillNumberID FROM ReceiptBillIndex)		--发票明细			
			---------------实物库存 Start---------------
			DELETE FROM dbo.IniFactStocks WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.IniFactStocks_Qty WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.FactStocks WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.FactStocks_Qty WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.gp_FactPtypeSerial WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.Fact_InoutPtypeSerial WHERE InKTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.Fact_InoutPtypeSerial WHERE OutKtyeID IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.Fact_InOutstocktable WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.gp_iniFactPtypeSerial WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			
			DELETE FROM dbo.FactIndex WHERE stypeid = @stypeid
			DELETE FROM dbo.FactInOut WHERE billNumberID NOT IN (SELECT BillNumberId FROM FactIndex)
			DELETE FROM dbo.FactDepotInOut WHERE billNumberID NOT IN (SELECT BillNumberId FROM FactIndex)
			DELETE FROM dbo.FactDepotAllot WHERE billNumberID NOT IN (SELECT BillNumberId FROM FactIndex)
			---------------实物库存 End---------------
			
			----------------优惠券 BEGIN---------------
			DELETE FROM dbo.Coupon_BillIndex WHERE STypeId = @stypeid
			DELETE FROM dbo.Coupon_InBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_OutBill  WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_OutBill_Ptype  WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_BackBill  WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_AllotBill  WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_CodeInfo  WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
			DELETE FROM dbo.Coupon_BillUsed	 WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_CodeInOut  WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.BillMulBrand	
			----------------优惠券 END  --------------
			
			--------------品牌 begin--------------------
			DELETE FROM dbo.CompleteBrandarTotal WHERE stypeid = @stypeid
			--------------品牌 end ---------------------
			DELETE FROM CompleteTotal WHERE GoodsBillID NOT IN (SELECT BillNumberID FROM #DelBillIndex)		--DELETE FROM CompleteTotal  --清掉按单结算表
	
		END
	ELSE
		BEGIN
			--------------------------不清理期初单据要对已结算和已开票的数据进行回写-----------------	
			IF @bRebulidIni=0
			BEGIN
				EXEC WriteBackInvoiveAndCompleteData				
			END
			--------------------------对已结算和已开票的数据进行回写 end -----------------	
			DELETE FROM BillIndex WHERE stypeid = @stypeid AND IfCheck = 't'
						
			DELETE FROM wx_Bill_GetBack WHERE NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId= wx_Bill_GetBack.BillNumberId AND BillType ='167' AND (Draft=1 OR IsIni=1))	-- 新维修 - 维修取件单
			DELETE FROM wx_Bill_Replace WHERE NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId= wx_Bill_Replace.BillNumberId AND BillType ='168' AND (Draft=1 OR IsIni=1))	-- 新维修 - 整机更换单
			DELETE FROM wx_Bill_SendBack WHERE NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId= wx_Bill_SendBack.BillNumberId AND BillType ='170' AND (Draft=1 OR IsIni=1))-- 新维修 - 送修返回单
			DELETE FROM wx_Bill_Goto WHERE NOT EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillNumberId= wx_Bill_Goto.BillNumberId AND BillType ='172' AND (Draft=1 OR IsIni=1))		-- 新维修 - 上门维修单
			
			IF @bRebulidDraft = 0	--不清除草稿
			BEGIN
				SELECT * INTO #BillIndexd FROM dbo.BillIndex WHERE draft=1 AND ifcheck='f' AND IsIni = 0	AND BillType NOT IN (205,206,414,450)			--billindex
				SELECT * INTO #CommissionBillNewd FROM CommissionBillNew WHERE draft=1 AND ifcheck='f'--未审核的留下
				SELECT  * INTO #CouponIndexd FROM Coupon_BillIndex WHERE draft=1 AND ifcheck='f' AND IsIni = 0	
				
			END
			IF @bRebulidIni = 0		--不清除期初单据
			BEGIN
				SELECT * INTO #BillIndexi  FROM dbo.BillIndex WHERE IsIni=1;
				SELECT * INTO #ReceiptBillIndexIni FROM dbo.ReceiptBillIndex WHERE IsIni=1;
				SELECT * INTO #CouponIndexi FROM Coupon_BillIndex WHERE  IsIni=1;
				-- 清除按品牌结算明细表 --期初单据 都结算了 期初未结算代销单等的按品牌结算过程要保留下来
				SELECT  * INTO #CompleteTotald FROM dbo.CompleteTotal WHERE MoneyBillID=-1;
				SELECT * INTO #CompleteBrandarTotald FROM dbo.CompleteBrandarTotal WHERE IsIni=1;
			END
				
			DELETE FROM BillIndex WHERE stypeid = @stypeid
			DELETE FROM CommissionBillNew WHERE stypeid = @stypeid
			DELETE FROM ReceiptBillIndex WHERE stypeid = @stypeid
			DELETE FROM Coupon_BillIndex WHERE stypeid = @stypeid
			DELETE FROM CompleteBrandarTotal  WHERE GoodsBillID NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM dbo.CompleteTotal  WHERE GoodsBillID NOT IN (SELECT BillNumberId FROM BillIndex)
			
			IF @bRebulidDraft = 0	--不清除草稿
			BEGIN
				SET IDENTITY_INSERT BillIndex ON
				SET @columns=dbo.f_getallcolumns('billindex')
				EXEC('INSERT INTO BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #BillIndexd')
				SET IDENTITY_INSERT BillIndex OFF
				
				SET IDENTITY_INSERT CommissionBillNew ON 
				SET @columns=dbo.f_getallcolumns('CommissionBillNew')
				EXEC('INSERT INTO CommissionBillNew ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBillNewd')
				SET IDENTITY_INSERT CommissionBillNew OFF
				
				SET IDENTITY_INSERT Coupon_BillIndex ON 
				SET @columns=dbo.f_getallcolumns('Coupon_BillIndex')
				EXEC('INSERT INTO Coupon_BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #CouponIndexd')
				SET IDENTITY_INSERT Coupon_BillIndex OFF
				
				DROP TABLE #BillIndexd
				DROP TABLE #CommissionBillNewd
				DROP TABLE #CouponIndexd
				
			END
			ELSE
			BEGIN 
				DELETE FROM wx_Bill_GetBack WHERE DraftFlag=1 AND IsIniFlag=0	-- 新维修 - 维修取件单
				DELETE FROM wx_Bill_Replace WHERE DraftFlag=1 AND IsIniFlag=0	-- 新维修 - 整机更换单
				DELETE FROM wx_Bill_SendBack WHERE DraftFlag=1 AND IsIniFlag=0	-- 新维修 - 送修返回单
				DELETE FROM wx_Bill_Goto WHERE DraftFlag=1 AND IsIniFlag=0		-- 新维修 - 上门维修单
			END 
			
			IF @bRebulidIni=0
			BEGIN		
				SET IDENTITY_INSERT BillIndex ON
				SET @columns=dbo.f_getallcolumns('billindex')
				EXEC('INSERT INTO BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #BillIndexi')
				SET IDENTITY_INSERT BillIndex OFF
				
				SET IDENTITY_INSERT ReceiptBillIndex ON
				SET @columns=dbo.f_getallcolumns('ReceiptBillIndex')
				EXEC('INSERT INTO ReceiptBillIndex ('+@columns+') SELECT '+@columns+ ' FROM #ReceiptBillIndexIni')
				SET IDENTITY_INSERT ReceiptBillIndex OFF
				
				SET IDENTITY_INSERT Coupon_BillIndex ON
				SET @columns=dbo.f_getallcolumns('Coupon_BillIndex')
				EXEC('INSERT INTO Coupon_BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #CouponIndexi')
				SET IDENTITY_INSERT Coupon_BillIndex OFF
				
				SET IDENTITY_INSERT CompleteBrandarTotal ON
				SET @columns=dbo.f_getallcolumns('CompleteBrandarTotal')
				EXEC('INSERT INTO CompleteBrandarTotal ('+@columns+') SELECT '+@columns+ ' FROM #CompleteBrandarTotald')
				SET IDENTITY_INSERT CompleteBrandarTotal OFF
				
				SET IDENTITY_INSERT dbo.CompleteTotal ON
				SET @columns=dbo.f_getallcolumns('CompleteTotal')
				EXEC('INSERT INTO CompleteTotal ('+@columns+') SELECT '+@columns+ ' FROM #CompleteTotald ')
				SET IDENTITY_INSERT CompleteTotal OFF
					
				DROP TABLE #ReceiptBillIndexIni
				DROP TABLE #BillIndexi
				DROP TABLE #CouponIndexi
				DROP TABLE #CompleteTotald,#CompleteBrandarTotald
			END
			ELSE
			BEGIN
				DELETE FROM wx_Bill_GetBack WHERE DraftFlag=0 AND IsIniFlag=1	-- 新维修 - 维修取件单
				DELETE FROM wx_Bill_Replace WHERE DraftFlag=0 AND IsIniFlag=1		-- 新维修 - 整机更换单
				DELETE FROM wx_Bill_SendBack WHERE DraftFlag=0 AND IsIniFlag=1		-- 新维修 - 送修返回单
				DELETE FROM wx_Bill_Goto WHERE DraftFlag=0 AND IsIniFlag=1			-- 新维修 - 上门维修单
			END
			
			SELECT a.* INTO #salebilld  FROM  SaleBill a INNER JOIN billindex b ON a.BillNumberId = b.BillNumberId WHERE b.BillType='11' --销售出库单
			SELECT a.* INTO #BuyBilld FROM buybill a INNER JOIN billindex b ON a.billnumberid=b.billnumberid WHERE b.Billtype='34' --采购入库单色了
			SELECT a.* INTO #PT_Combin_SaleBill  FROM  PT_Combin_SaleBill a INNER JOIN billindex b ON a.BillNumberId = b.BillNumberId WHERE b.BillType='12' --组合品销售出库单
			SELECT a.* INTO #PT_Combin_SaleBillDetail  FROM  dbo.PT_Combin_SaleBillDetail a INNER JOIN billindex b ON a.BillNumberId = b.BillNumberId WHERE b.BillType='12' --组合品销售出库单明细
			
	
					
			SELECT a.* INTO #SaleBackBilld FROM SaleBackBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='45'   -- 销售退货单 
			SELECT a.* INTO #PT_Combin_SaleBackBill FROM dbo.PT_Combin_SaleBackBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='46'   -- 组合品销售退货单 
			SELECT a.* INTO #PT_Combin_SaleBackBillDetail FROM dbo.PT_Combin_SaleBackBillDetail a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='46'   -- 组合品销售退货单 
			SELECT a.* INTO #BuyBackBilld FROM BuyBackBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype ='6'  -- 采购退货单
			SELECT a.* INTO #CommissionBilld FROM dbo.CommissionBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid -- 代销单据
			SELECT a.* INTO #SaleGoodsExchangeBilld FROM dbo.SaleGoodsExchangeBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.BillType ='160' -- 销售换货单
			SELECT a.* INTO #BuyGoodsExchangeBilld  FROM dbo.BuyGoodsExchangeBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.BillType ='161' -- 采购换货单
			SELECT a.* INTO #PreBilld	FROM dbo.PreBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN (189,190) -- 预收款单，预付款单				
			SELECT a.* INTO #adDebtbilld FROM dbo.AdDebtBill	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN ('115','116','128','129') -- 调账单
			SELECT a.* INTO #MoneyBilld FROM dbo.MoneyBill	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  -- 其他收入、费用单、固定资产购买及变卖
			SELECT a.* INTO #PriceProtectBilld FROM dbo.PriceProtectBill	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN ('149','151') -- 价保
			SELECT a.* INTO #Advantaged FROM dbo.Advantage	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN ('148','150') -- 返利、获利
			SELECT a.* INTO #AssetIncDecBilld FROM dbo.AssetIncDecBill	a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid  WHERE b.billtype IN ('212','213') -- 固定资产增加减少单
			SELECT a.* INTO #DepBilld FROM DepBill a INNER JOIN BillIndex b ON a.BillNumberId=b.BillNumberId WHERE b.BillType=214 --折旧单
			SELECT a.* INTO #FixedAssetsDetailsd FROM FixedAssetsDetails a INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberId WHERE b.billtype=307
			
			SELECT a.* INTO #CommissionBillNewDetaild FROM CommissionBillNewDetail a INNER JOIN CommissionBillNew b ON a.billnumberid=b.billnumberid --提成单 
			SELECT a.* INTO #CapitalTransfer_Billd FROM CapitalTransfer_Bill a INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberId WHERE b.billtype=310
			SELECT a.* INTO #VipAddMoneyBatchBilld FROM dbo.VipAddMoneyBatchBill a JOIN dbo.BillIndex b ON a.BillNumberId=b.BillNumberId WHERE b.billtype=312 --会员批量储值充值单
			
			SELECT a.* INTO #VipCentToMoneyBill FROM dbo.VipCentToMoneyBill a JOIN dbo.BillIndex b ON a.BillNumberId=b.BillNumberId WHERE b.billtype=427 --会员积分转储值单
			
			SELECT a.* INTO #AppraisalBill FROM dbo.AppraisalBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND b.BillType=400 --暂估入库单
			SELECT a.* INTO #AppraisalBackBill FROM dbo.AppraisalBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberID=B.BillNumberId AND b.BillType=401 --暂估退货单
			SELECT a.* INTO #SendBill FROM dbo.SendBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=402  --发出商品出库单
			SELECT a.* INTO #SendBackBill FROM dbo.SendBackBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=403 --发出商品退货单
			SELECT a.* INTO #ReceiptBill FROM dbo.ReceiptBill A INNER JOIN dbo.ReceiptBillIndex B ON A.BillNumberID=B.BillNumberID               --发票明细
			SELECT a.* INTO #ChargeOffBill FROM dbo.ChargeOffBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=450 --往来核销单
			
			SELECT a.* into #Coupon_InBill FROM dbo.Coupon_InBill A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=423 --优惠券入库单
			SELECT a.* into #Coupon_OutBill FROM dbo.Coupon_OutBill A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=424 --优惠券出库单
			SELECT a.* into #Coupon_OutBill_Ptype FROM dbo.Coupon_OutBill_Ptype A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=424 --优惠券出库下表体
			SELECT a.* into #Coupon_BackBill FROM dbo.Coupon_BackBill A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=426 --优惠券退货单
			SELECT a.* into #Coupon_AllotBill FROM dbo.Coupon_AllotBill A INNER JOIN dbo.Coupon_BillIndex B ON A.BillNumberId=B.BillNumberId AND B.BillType=425 --优惠券调拨单
			SELECT a.* into #BillMulBrand FROM dbo.BillMulBrand A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND a.BillType=B.BillType
			SELECT a.* FROM dbo.BillMulBrand A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND a.BillType=B.BillType

			--重置OldBillNumberID,OldID 为-1
			UPDATE #AppraisalBill SET OldBillNumberID=-1,OldID=-1,BackQty=0
			UPDATE #SendBill SET OldBillNumberID=-1,OldID=-1,BackQty=0
			UPDATE #AppraisalBackBill SET OldBillNumberID=-1,OldID=-1
			UPDATE #SendBackBill SET OldBillNumberID=-1,OldID=-1
			UPDATE #BuyBackBilld SET OldBillNumberID=-1,OldID=-1
			UPDATE #SaleBackBilld SET OldBillNumberID=-1,OldID=-1
			UPDATE #PT_Combin_SaleBill SET BackQty=0
			UPDATE #PT_Combin_SaleBillDetail SET BackQty=0
			UPDATE #PT_Combin_SaleBackBill SET OldBillNumberID=-1,OldID=-1
			UPDATE #PT_Combin_SaleBackBillDetail SET OldBillNumberID=-1,OldID=-1
						
			DELETE FROM	SaleBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM	SaleBackBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM	buybill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM	buybackbill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM	SaleGoodsExchangeBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM	BuyGoodsExchangeBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM	CommissionBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM	PreBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)--预收预付
			DELETE FROM	AdDebtBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)--调账单
			DELETE FROM dbo.PriceProtectBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM dbo.Advantage WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM dbo.MoneyBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM AssetIncDecBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)--固定资产增加减少单
			DELETE FROM DepBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM CommissionBillNewDetail WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM CapitalTransfer_Bill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex) --资金调拨单
			DELETE FROM VipAddMoneyBatchBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)--会员储值单
			DELETE FROM VipCentToMoneyBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)	--会员积分转储值单
			DELETE FROM AppraisalBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)		--暂估入库
			DELETE FROM AppraisalBackBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)	--暂估退货
			DELETE FROM SendBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)				--发出商品出库
			DELETE FROM SendBackBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)			--发出商品退货
			DELETE FROM ReceiptBill	 WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)		--发票表明细
			DELETE FROM ChargeOffBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)		--往来核销单
			DELETE FROM dbo.PT_Combin_SaleBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM dbo.PT_Combin_SaleBillDetail WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM dbo.PT_Combin_SaleBackBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			DELETE FROM dbo.PT_Combin_SaleBackBillDetail WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
			--优惠券
			DELETE FROM Coupon_BillIndex WHERE stypeid = @stypeid
			DELETE FROM dbo.Coupon_InBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_OutBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_OutBill_Ptype WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_BackBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.Coupon_AllotBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)
			DELETE FROM dbo.BillMulBrand WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Coupon_BillIndex)			
			
			SET IDENTITY_INSERT dbo.SaleBill ON
			SET @columns=dbo.f_getallcolumns('SaleBill')
			EXEC('INSERT INTO SaleBill('+@columns+') SELECT '+@columns+ ' FROM #SaleBilld')
			SET IDENTITY_INSERT SaleBill OFF
			
			SET IDENTITY_INSERT BuyBill ON
			SET @columns=dbo.f_getallcolumns('BuyBill')
			EXEC('INSERT INTO BuyBill ('+@columns+') SELECT '+@columns+ ' FROM #BuyBilld')
			SET IDENTITY_INSERT BuyBill OFF
			
			SET IDENTITY_INSERT dbo.saleBackBill ON
			SET @columns=dbo.f_getallcolumns('saleBackBill')
			EXEC('INSERT INTO saleBackBill ('+@columns+') SELECT '+@columns+ ' FROM #saleBackBilld')
			SET IDENTITY_INSERT saleBackBill OFF
			
			SET IDENTITY_INSERT dbo.BuyBackBill ON
			SET @columns=dbo.f_getallcolumns('BuyBackBill')
			EXEC('INSERT INTO BuyBackBill ('+@columns+') SELECT '+@columns+ ' FROM #BuyBackBilld')
			SET IDENTITY_INSERT BuyBackBill OFF
			
			SET IDENTITY_INSERT dbo.CommissionBill ON
			SET @columns=dbo.f_getallcolumns('CommissionBill')
			EXEC('INSERT INTO CommissionBill ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBilld')
			SET IDENTITY_INSERT CommissionBill OFF
			
			SET IDENTITY_INSERT dbo.BuyGoodsExchangeBill ON
			SET @columns=dbo.f_getallcolumns('BuyGoodsExchangeBill')
			EXEC('INSERT INTO BuyGoodsExchangeBill ('+@columns+') SELECT '+@columns+ ' FROM #BuyGoodsExchangeBilld')
			SET IDENTITY_INSERT BuyGoodsExchangeBill OFF
			
			SET IDENTITY_INSERT dbo.SaleGoodsExchangeBill ON
			SET @columns=dbo.f_getallcolumns('SaleGoodsExchangeBill')
			EXEC('INSERT INTO SaleGoodsExchangeBill ('+@columns+') SELECT '+@columns+ ' FROM #SaleGoodsExchangeBilld')
			SET IDENTITY_INSERT SaleGoodsExchangeBill OFF
			
			SET IDENTITY_INSERT dbo.PreBill ON
			SET @columns=dbo.f_getallcolumns('PreBill')
			EXEC('INSERT INTO PreBill ('+@columns+') SELECT '+@columns+ ' FROM #PreBilld')
			SET IDENTITY_INSERT PreBill OFF
			
			SET IDENTITY_INSERT dbo.AdDebtBill ON
			SET @columns=dbo.f_getallcolumns('AdDebtBill')
			EXEC('INSERT INTO AdDebtBill ('+@columns+') SELECT '+@columns+ ' FROM #AdDebtBilld')
			SET IDENTITY_INSERT AdDebtBill OFF
			
			SET IDENTITY_INSERT dbo.MoneyBill ON
			SET @columns=dbo.f_getallcolumns('MoneyBill')
			EXEC('INSERT INTO MoneyBill ('+@columns+') SELECT '+@columns+ ' FROM #MoneyBilld')
			SET IDENTITY_INSERT MoneyBill OFF
			
			SET IDENTITY_INSERT dbo.PriceProtectBill ON
			SET @columns=dbo.f_getallcolumns('PriceProtectBill')
			EXEC('INSERT INTO PriceProtectBill ('+@columns+') SELECT '+@columns+ ' FROM #PriceProtectBilld')
			SET IDENTITY_INSERT PriceProtectBill OFF
			
			SET IDENTITY_INSERT dbo.Advantage ON
			SET @columns=dbo.f_getallcolumns('Advantage')
			EXEC('INSERT INTO Advantage ('+@columns+') SELECT '+@columns+ ' FROM #Advantaged')
			SET IDENTITY_INSERT Advantage OFF
			
			SET IDENTITY_INSERT dbo.AssetIncDecBill ON
			SET @columns=dbo.f_getallcolumns('AssetIncDecBill')
			EXEC('INSERT INTO AssetIncDecBill ('+@columns+') SELECT '+@columns+ ' FROM #AssetIncDecBilld')
			SET IDENTITY_INSERT AssetIncDecBill OFF
			
			SET IDENTITY_INSERT dbo.DepBill ON
			SET @columns=dbo.f_getallcolumns('DepBill')
			EXEC('INSERT INTO DepBill ('+@columns+') SELECT '+@columns+ ' FROM #DepBilld')
			SET IDENTITY_INSERT DepBill OFF
			
			SET IDENTITY_INSERT dbo.FixedAssetsDetails ON
			SET @columns=dbo.f_getallcolumns('FixedAssetsDetails')
			EXEC('INSERT INTO FixedAssetsDetails ('+@columns+') SELECT '+@columns+ ' FROM #FixedAssetsDetailsd')
			SET IDENTITY_INSERT FixedAssetsDetails OFF
			
			SET IDENTITY_INSERT dbo.CommissionBillNewDetail ON
			SET @columns=dbo.f_getallcolumns('CommissionBillNewDetail')
			EXEC('INSERT INTO CommissionBillNewDetail ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBillNewDetaild')
			SET IDENTITY_INSERT CommissionBillNewDetail OFF
			
			SET IDENTITY_INSERT dbo.CapitalTransfer_Bill ON
			SET @columns=dbo.f_getallcolumns('CapitalTransfer_Bill')
			EXEC('INSERT INTO CapitalTransfer_Bill ('+@columns+') SELECT '+@columns+ ' FROM #CapitalTransfer_Billd')
			SET IDENTITY_INSERT CapitalTransfer_Bill OFF
			
			--会员储值单
			SET IDENTITY_INSERT dbo.VipAddMoneyBatchBill ON
			SET @columns=dbo.f_getallcolumns('VipAddMoneyBatchBill')
			EXEC('INSERT INTO VipAddMoneyBatchBill ('+@columns+') SELECT '+@columns+ ' FROM #VipAddMoneyBatchBilld')
			SET IDENTITY_INSERT VipAddMoneyBatchBill OFF
			
			--会员积分转储值单
			SET IDENTITY_INSERT dbo.VipCentToMoneyBill ON
			SET @columns=dbo.f_getallcolumns('VipCentToMoneyBill')
			EXEC('INSERT INTO VipCentToMoneyBill ('+@columns+') SELECT '+@columns+ ' FROM #VipCentToMoneyBill')
			SET IDENTITY_INSERT VipCentToMoneyBill OFF
			
			SET IDENTITY_INSERT dbo.AppraisalBill ON
			SET @columns=dbo.f_getallcolumns('AppraisalBill')
			EXEC ('INSERT INTO AppraisalBill ('+@columns+') SELECT '+@columns +' FROM #AppraisalBill')
			SET IDENTITY_INSERT dbo.AppraisalBill OFF
			
			SET IDENTITY_INSERT dbo.AppraisalBackBill ON
			SET @columns=dbo.f_getallcolumns('AppraisalBackBill')
			EXEC ('INSERT INTO AppraisalBackBill ('+@columns+') SELECT '+@columns +' FROM #AppraisalBackBill')
			SET IDENTITY_INSERT dbo.AppraisalBackBill OFF
			
			SET IDENTITY_INSERT dbo.SendBill ON
			SET @columns=dbo.f_getallcolumns('SendBill')
			EXEC ('INSERT INTO SendBill ('+@columns+') SELECT '+@columns +' FROM #SendBill')
			SET IDENTITY_INSERT dbo.SendBill OFF
			
			SET IDENTITY_INSERT dbo.SendBackBill ON
			SET @columns=dbo.f_getallcolumns('SendBackBill')
			EXEC ('INSERT INTO SendBackBill ('+@columns+') SELECT '+@columns +' FROM #SendBackBill')
			SET IDENTITY_INSERT dbo.SendBackBill OFF
			
			SET IDENTITY_INSERT dbo.ReceiptBill ON
			SET @columns=dbo.f_getallcolumns('ReceiptBill')
			EXEC ('INSERT INTO ReceiptBill ('+@columns+') SELECT '+@columns +' FROM #ReceiptBill')
			SET IDENTITY_INSERT dbo.ReceiptBill OFF
			
			SET IDENTITY_INSERT dbo.ChargeOffBill ON
			SET @columns=dbo.f_getallcolumns('ChargeOffBill')
			EXEC ('INSERT INTO ChargeOffBill ('+@columns+') SELECT '+@columns +' FROM #ChargeOffBill')
			SET IDENTITY_INSERT dbo.ChargeOffBill OFF
			
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBill ON
			SET @columns=dbo.f_getallcolumns('PT_Combin_SaleBill')
			EXEC ('INSERT INTO PT_Combin_SaleBill ('+@columns+') SELECT '+@columns +' FROM #PT_Combin_SaleBill')
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBill OFF
			
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBillDetail ON
			SET @columns=dbo.f_getallcolumns('PT_Combin_SaleBillDetail')
			EXEC ('INSERT INTO PT_Combin_SaleBillDetail ('+@columns+') SELECT '+@columns +' FROM #PT_Combin_SaleBillDetail')
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBillDetail OFF
			
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBackBill ON
			SET @columns=dbo.f_getallcolumns('PT_Combin_SaleBackBill')
			EXEC ('INSERT INTO PT_Combin_SaleBackBill ('+@columns+') SELECT '+@columns +' FROM #PT_Combin_SaleBackBill')
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBackBill OFF
			
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBackBillDetail ON
			SET @columns=dbo.f_getallcolumns('PT_Combin_SaleBackBillDetail')
			EXEC ('INSERT INTO PT_Combin_SaleBackBillDetail ('+@columns+') SELECT '+@columns +' FROM #PT_Combin_SaleBackBillDetail')
			SET IDENTITY_INSERT dbo.PT_Combin_SaleBackBillDetail OFF
			
			--优惠券
			SET IDENTITY_INSERT dbo.Coupon_InBill ON
			SET @columns=dbo.f_getallcolumns('Coupon_InBill')
			EXEC ('INSERT INTO Coupon_InBill ('+@columns+') SELECT '+@columns +' FROM #Coupon_InBill')
			SET IDENTITY_INSERT dbo.Coupon_InBill OFF
			
			SET IDENTITY_INSERT dbo.Coupon_OutBill ON
			SET @columns=dbo.f_getallcolumns('Coupon_OutBill')
			EXEC ('INSERT INTO Coupon_OutBill ('+@columns+') SELECT '+@columns +' FROM #Coupon_OutBill')
			SET IDENTITY_INSERT dbo.Coupon_OutBill OFF
			
			
			SET @columns=dbo.f_getallcolumns('Coupon_OutBill_Ptype')
			EXEC ('INSERT INTO Coupon_OutBill_Ptype ('+@columns+') SELECT '+@columns +' FROM #Coupon_OutBill_Ptype')
	
			
			SET IDENTITY_INSERT dbo.Coupon_AllotBill ON
			SET @columns=dbo.f_getallcolumns('Coupon_AllotBill')
			EXEC ('INSERT INTO Coupon_AllotBill ('+@columns+') SELECT '+@columns +' FROM #Coupon_AllotBill')
			SET IDENTITY_INSERT dbo.Coupon_AllotBill OFF
			
			SET IDENTITY_INSERT dbo.Coupon_BackBill ON
			SET @columns=dbo.f_getallcolumns('Coupon_BackBill')
			EXEC ('INSERT INTO Coupon_BackBill ('+@columns+') SELECT '+@columns +' FROM #Coupon_BackBill')
			SET IDENTITY_INSERT dbo.Coupon_BackBill OFF
			
			SET IDENTITY_INSERT dbo.BillMulBrand ON
			SET @columns=dbo.f_getallcolumns('BillMulBrand')
			EXEC ('INSERT INTO BillMulBrand ('+@columns+') SELECT '+@columns +' FROM #BillMulBrand')
			SET IDENTITY_INSERT dbo.BillMulBrand OFF
			
			DROP TABLE #SaleBilld,#BuyBilld,#saleBackBilld,#BuyBackBilld,#adDebtbilld,#BuyGoodsExchangeBilld,#CommissionBilld,#PreBilld,#SaleGoodsExchangeBilld,#MoneyBilld,#PriceProtectBilld,#Advantaged,#AssetIncDecBilld,#CommissionBillNewDetaild,#CapitalTransfer_Billd,#AppraisalBill,#AppraisalBackBill,#SendBill,#SendBackBill,#ReceiptBill
			,#PT_Combin_SaleBill,#PT_Combin_SaleBillDetail,#PT_Combin_SaleBackBill,#PT_Combin_SaleBackBillDetail,#Coupon_InBill,#Coupon_OutBill,#Coupon_OutBill_Ptype,#Coupon_AllotBill,#Coupon_BackBill,#VipCentToMoneyBill,#VipAddMoneyBatchBilld,#BillMulBrand,#ChargeOffBill,#DepBilld,#FixedAssetsDetailsd
			
			CREATE TABLE #BillOperateLog(		
							[BillnumberID] INT,				
							[OperateType] VARCHAR(50) NULL DEFAULT(''),
							[EtypeID] VARCHAR(50) NULL DEFAULT(''),
							[OperateTime] DATETIME NULL DEFAULT(GETDATE()),
							[IP] VARCHAR(50) NULL,
							[BillCode] VARCHAR(200) NOT NULL DEFAULT(''),
							[BillDate] DATETIME ,
							[ifcheck] CHAR(1) NOT NULL DEFAULT(''),
							[btypeid] VARCHAR(50) NOT NULL DEFAULT(''),
							[NTotalMoney] NUMERIC(22,10) DEFAULT(0),
							[billtype] INT  NOT NULL DEFAULT(0)
						)
			------------------------操作日志BillOperateLog---------------
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM BillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='billindex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM ReceiptBillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='ReceiptBillIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM FaPiaoBillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='FaPiaoBillIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM LendIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='LendIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM factindex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='factindex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='OrderIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM RequestIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='RequestIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM onShelvespickIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='onShelvespickIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM PosAllotApplyBillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='PosAllotApplyBillIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM SerialAdjustIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='SerialAdjustIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM StockCheckIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='StockCheckIndex')
			INSERT INTO #BillOperateLog( BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,billtype)
				SELECT BillnumberID ,OperateType ,EtypeID ,OperateTime ,IP ,BillCode ,BillDate ,ifcheck ,btypeid ,NTotalMoney ,Billtype 
				FROM BillOperateLog WHERE BillNumberID IN (SELECT BillNumberID FROM Coupon_BillIndex) AND billtype IN (SELECT Billtype FROM dbo.BillName WHERE IndexTable='Coupon_BillIndex')
			
			TRUNCATE TABLE BillOperateLog --操作日志
			INSERT INTO dbo.BillOperateLog
			        ( BillnumberID ,
			          OperateType ,
			          EtypeID ,
			          OperateTime ,
			          IP ,
			          BillCode ,
			          BillDate ,
			          ifcheck ,
			          btypeid ,
			          NTotalMoney ,
			          billtype
			        )
			SELECT  BillnumberID ,
			          OperateType ,
			          EtypeID ,
			          OperateTime ,
			          IP ,
			          BillCode ,
			          BillDate ,
			          ifcheck ,
			          btypeid ,
			          NTotalMoney ,
			          billtype
			FROM #BillOperateLog			
			 		
			DROP TABLE #BillOperateLog
			
			DELETE FROM BeforePromoteIndex WHERE NOT EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BeforePromoBillNumberId=dbo.BeforePromoteIndex.BillNumberId AND draft=1)	--零售零售促销方案主表
			DELETE FROM BeforePromoteRetailBill WHERE NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.BeforePromoteRetailBill.BillNumberId)	--零售零食促销方案明细
			DELETE FROM BeforePromoteSaleBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BeforePromoteIndex WHERE BillNumberId=BeforePromoteSaleBill.BillNumberId)
			
			DELETE FROM  BillIndex_CarRepair WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.Billindex_CarRepair.BillNumberId)				
			
			IF @bRebulidIni = 1	--清除期初
			BEGIN
				TRUNCATE TABLE Coupon_CodeInfo 
			END
			ELSE
			BEGIN				
				--回写状态,重建 将inistate 赋值给 state
				UPDATE  a 
				SET		[state]=inistate,	
						outprice=CASE WHEN a.inistate=2 THEN a.outprice  ELSE 0 END ,				
						ktypeid=IniKtypeId,
						CargoId=IniCargoId
				FROM  dbo.Coupon_CodeInfo a
			END
			
			DELETE FROM Coupon_CodeInfo WHERE IsIni=0 --不是期初的，则通过过账来，需要清理			
				
			--处理优惠券信息表 和 出入库优惠券使用表
			DELETE FROM  Coupon_BillUsed WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.Coupon_BillUsed.BillNumberId)
			TRUNCATE TABLE dbo.Coupon_CodeInOut 				
		END
	-------------------------- 专门对 BillIndex、以及主表在billindex中的期初单据进行处理 end---------------------------------
	
	IF @clearStopOrder=1 --清除已中止的订单
	BEGIN
		--更新期初订单库存
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.BillOver=1 AND A.billNumberID=B.billNumberId AND b.Stypeid = @STypeId) AND BILLTYPE<>313
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.BillOver=1 AND A.billNumberID=B.billNumberId AND B.STypeId = @STypeId) AND BILLTYPE=313
		
		--删除已中止的销售订单 去除关联关系
		UPDATE	OrderBill 
		SET		SaleOrderId =-1
		WHERE	SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 and billtype =300 AND stypeid = @stypeid))
		
		--删除已中止的组合品销售订单 去除关联关系
		UPDATE	OrderBill 
		SET		PTCombinOrderBillDetailID =-1
		WHERE	PTCombinOrderBillDetailID IN (SELECT ORDERID FROM PT_Combin_OrderBillDetail WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 and billtype =313 AND stypeid = @stypeid))
		
		DELETE dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 AND stypeid = @stypeid)
		DELETE dbo.PT_Combin_OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 AND stypeid = @stypeid)
		DELETE dbo.PT_Combin_OrderBillDetail WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE BillOver=1 AND stypeid = @stypeid)
		DELETE dbo.OrderIndex WHERE BillOver=1 AND stypeid = @stypeid		
	END
	
	IF @clearCompleteOrder=1 --清除已完成的订单
	BEGIN		
		--更新期初订单库存
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.OrderState=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.OrderState=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
		--删除已完成的采购订单 回写销售订单的已采购订货数量
		UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1 and billtype =301) GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId
		
	   --删除已完成的采购订单 回写组合品销售订单的已采购订货数量		
		UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
		FROM PT_Combin_OrderBillDetail A JOIN (select SUM(Qty) AS Qty,PTCombinOrderBillDetailID FROM dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE  OrderState=1 AND billtype =301) GROUP BY PTCombinOrderBillDetailID) B on A.ORDERID=B.PTCombinOrderBillDetailID
		
		--删除已中止的销售订单 去除关联关系
		UPDATE OrderBill SET SaleOrderId =-1
		WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1 and billtype =300)  )
		
		--删除已完成的组合品销售订单 去除关联关系
		UPDATE OrderBill SET PTCombinOrderBillDetailID =-1
		WHERE PTCombinOrderBillDetailID IN (SELECT ORDERID FROM PT_Combin_OrderBillDetail WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1 and billtype =313)  )

		DELETE dbo.OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1)
		DELETE dbo.PT_Combin_OrderBill WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1)
		DELETE dbo.PT_Combin_OrderBillDetail WHERE billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState=1)
		DELETE dbo.OrderIndex WHERE OrderState=1
	END 
	
	IF @clearAllOrder=1	--清除所有订单\修改所有掉订单OrderID为-1
	BEGIN
		DELETE FROM OrderIndex WHERE stypeid = @stypeid
		DELETE FROM OrderBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.OrderIndex)			-- 销售、采购订单		
		DELETE FROM dbo.OrderIndex WHERE BillType=313 AND Stypeid = @stypeid		--清除所有组合品订单
		DELETE FROM PT_Combin_OrderBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.OrderIndex)				--清除所有组合品订单信息
		DELETE FROM PT_Combin_OrderBillDetail WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.OrderIndex)			--清除所有组合品订单明细信息
		DELETE FROM Ini_GoodsStocks_Order WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.OrderIndex)
				
		UPDATE AppraisalBill SET OrderID=-1 WHERE OrderID NOT IN (SELECT orderid FROM OrderBill)
		UPDATE SendBill SET OrderID=-1 WHERE OrderID NOT IN (SELECT orderid FROM OrderBill)
		UPDATE SaleBill SET OrderID=-1 WHERE OrderID NOT IN (SELECT orderid FROM OrderBill)
		UPDATE Buybill SET OrderID=-1 WHERE OrderID NOT IN (SELECT orderid FROM OrderBill)
		UPDATE PT_Combin_SaleBill SET OrderID=-1 WHERE OrderID NOT IN (SELECT orderid FROM OrderBill)
		UPDATE PT_Combin_SaleBillDetail SET OrderID=-1 WHERE OrderID NOT IN (SELECT orderid FROM OrderBill)
		UPDATE CommissionBill SET OrderID=-1 WHERE Type IN (140,144) AND OrderID NOT IN (SELECT orderid FROM OrderBill)
		
		UPDATE prebill SET RelevanceBillId=-1 WHERE RelevanceBillId NOT IN (SELECT orderid FROM OrderBill)
		UPDATE gatheringbill SET RelevanceBillId=-1  WHERE RelevanceBillId NOT IN (SELECT orderid FROM OrderBill)
		UPDATE paybill SET RelevanceBillId=-1  WHERE RelevanceBillId NOT IN (SELECT orderid FROM OrderBill)		
	END
	ELSE	--修改所有被删除订单的调用ID，OrderID为-1
	BEGIN
		UPDATE SendBill SET OrderID=-1 FROM SendBill LEFT JOIN OrderBill 
			ON dbo.SendBill.OrderID = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE SaleBill SET OrderID=-1 FROM SaleBill LEFT JOIN OrderBill 
			ON dbo.SaleBill.OrderID = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE PT_Combin_SaleBill SET OrderID=-1 FROM PT_Combin_SaleBill LEFT JOIN PT_Combin_OrderBill 
			ON dbo.PT_Combin_SaleBill.OrderID = dbo.PT_Combin_OrderBill.OrderID WHERE dbo.PT_Combin_OrderBill.OrderID IS NULL;
		UPDATE PT_Combin_SaleBillDetail SET OrderID=-1 FROM PT_Combin_SaleBillDetail LEFT JOIN PT_Combin_OrderBillDetail 
			ON dbo.PT_Combin_SaleBillDetail.OrderID = dbo.PT_Combin_OrderBillDetail.OrderID WHERE dbo.PT_Combin_OrderBillDetail.OrderID IS NULL;
		UPDATE AppraisalBill SET OrderID=-1 FROM AppraisalBill LEFT JOIN OrderBill 
			ON dbo.AppraisalBill.OrderID = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE Buybill SET OrderID=-1 FROM Buybill LEFT JOIN OrderBill 
			ON dbo.Buybill.OrderID = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE CommissionBill SET OrderID=-1 FROM CommissionBill LEFT JOIN OrderBill 
			ON dbo.CommissionBill.OrderID = dbo.OrderBill.OrderID AND Type IN (140,144) WHERE dbo.OrderBill.OrderID IS NULL;
		--打断销售 采购有订金产生的 预收\付款  收付款单关联关系	
		UPDATE prebill SET RelevanceBillId=-1 FROM prebill LEFT JOIN OrderBill 
			ON dbo.prebill.RelevanceBillId = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE gatheringbill SET RelevanceBillId=-1 FROM gatheringbill LEFT JOIN OrderBill 
			ON dbo.gatheringbill.RelevanceBillId = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
		UPDATE paybill SET RelevanceBillId=-1 FROM paybill LEFT JOIN OrderBill 
			ON dbo.paybill.RelevanceBillId = dbo.OrderBill.OrderID WHERE dbo.OrderBill.OrderID IS NULL;
	END
	
	IF @clearCompleteAllotApply = 1 --清除已完成的调货申请单
	BEGIN
	     DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 1)
	     DELETE PosAllotApplyBillIndex WHERE Isdone = 1;
	END
	
	IF @clearNoCompleteAllotApply = 1 --清除未完成的调货申请单
	BEGIN
	     DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 0)
	     DELETE PosAllotApplyBillIndex WHERE Isdone = 0;
	END	
	--bug2853,调货申请单，状态是作废的，年结存的时候直接清除掉，不管选项。祝伟已确认
	DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE BillState = 4);
	DELETE PosAllotApplyBillIndex WHERE BillState = 4;
	
	--重建清除所有物流单据，包括草稿
	TRUNCATE TABLE Transportbill
	TRUNCATE TABLE PickBill
	TRUNCATE TABLE onShelvesbill
	TRUNCATE TABLE onShelvespickIndex
	TRUNCATE TABLE Transportcontrastbill
	
	TRUNCATE TABLE FixedAssetsIndex
	TRUNCATE TABLE FixedAssetsDetails;
	
	TRUNCATE TABLE RequestBill			--请购单明细
	TRUNCATE TABLE RequestIndex			--请购单主表
	TRUNCATE TABLE dbo.FactStocks
	TRUNCATE TABLE dbo.FactStocks_Qty
	TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
	TRUNCATE TABLE dbo.Fact_InOutstocktable
	TRUNCATE TABLE GOODSSTOCKS_QTY
	TRUNCATE TABLE GoodsStocks			--DELETE FROM GoodsStocks
	TRUNCATE TABLE wx_GoodsStocks
	TRUNCATE TABLE CommissionStock		--DELETE FROM CommissionStock --清掉代销库存
	TRUNCATE TABLE dbo.CommissionStock_Qty
	TRUNCATE TABLE InOutStockTable		--DELETE FROM InOutStockTable
	TRUNCATE TABLE wx_InOutStockTable	-- 维修出入库明细表
	TRUNCATE TABLE ListTable			--DELETE FROM ListTable
	TRUNCATE TABLE dbo.Fact_InOutstocktable
	TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
	TRUNCATE TABLE GP_InOutPTypeSerial	--DELETE FROM GP_InOutPTypeSerial
	TRUNCATE TABLE GP_CruPTypeSerial	--DELETE FROM GP_CruPTypeSerial
	TRUNCATE TABLE GP_LendPTypeSerial	--DELETE FROM GP_LendPTypeSerial	--清掉借欠的序列号 谢吉康  2004-02-24
	TRUNCATE TABLE VipCardConsume		--DELETE FROM VipCardConsume		--清掉VIP卡消费记录表  谢吉康  2004-7-21
	TRUNCATE TABLE StockCheck			--DELETE FROM StockCheck     --清掉库存盘点
	TRUNCATE TABLE StockCheckIndex		--DELETE FROM StockCheckIndex  --清掉库存盘点

	TRUNCATE TABLE DiyIndex   --装机配置单
	TRUNCATE TABLE DiyBill		--装机配置单
	TRUNCATE TABLE DiyBillTypePSaleTypeID
	TRUNCATE TABLE Ac_Balance							--科目余额表
	TRUNCATE TABLE Ac_Balance_Assist_CheckItems			--科目余额表(辅助核算）
	TRUNCATE TABLE Ac_Balance_Assist_CheckItems_Detail  --科目余额表(辅助核算明细)
	TRUNCATE TABLE Ac_ProfitAndLoss						--损益表
	TRUNCATE TABLE Ac_ProfitAndLoss_Detail				--损益表明细
	TRUNCATE TABLE Ac_GoodsBill_VoucherBill				--业务和财务关联表
	TRUNCATE TABLE Ac_CommissionBill_VoucherBill
	TRUNCATE TABLE Ac_ReceiptBill_VoucherBill
	TRUNCATE TABLE Ac_Provision_Voucher
	TRUNCATE TABLE Ac_CouponBill_VoucherBill--删除凭证关联关系
	TRUNCATE TABLE Ac_DeliveryBill_VoucherBill--删除凭证关联关系
	--删除单据修改记录
	TRUNCATE TABLE dbo.FrozeBusiness
	TRUNCATE TABLE ModifyLog_BillIndex
	TRUNCATE TABLE ModifyLog_SaleBill
	TRUNCATE TABLE ModifyLog_BuyBill
	TRUNCATE TABLE ModifyLog_SaleBackBill
	TRUNCATE TABLE ModifyLog_BuyBackBill
	TRUNCATE TABLE ModifyLog_PayBill
	TRUNCATE TABLE ModifyLog_GatheringBill
	TRUNCATE TABLE ModifyLog_CompleteTotal
	TRUNCATE TABLE ModifyLog_CompleteGoodTotal
	TRUNCATE TABLE ModifyLog_PreBill
	TRUNCATE TABLE ModifyLog_ReceiptBillIndex
	TRUNCATE TABLE ModifyLog_ReceiptBill
	TRUNCATE TABLE ModifyLog_SendBill
	TRUNCATE TABLE ModifyLog_SendBackBill
	TRUNCATE TABLE ModifyLog_AppraisalBill
	TRUNCATE TABLE ModifyLog_AppraisalBackBill
	TRUNCATE TABLE ModifyLog_PT_Combin_SaleBill
	TRUNCATE TABLE ModifyLog_PT_Combin_SaleBillDetail
	TRUNCATE TABLE ModifyLog_PT_Combin_SaleBackBill
	TRUNCATE TABLE ModifyLog_PT_Combin_SaleBackBillDetail
	TRUNCATE TABLE CostRe_Bill
	TRUNCATE TABLE CostReLog
	
 	--设置提成方案状
	UPDATE CommissionScheme SET UseState=1 WHERE BillNumberId NOT IN (SELECT CommissionSchemeID FROM CommissionBillNew)
	
	--清除订单的RequestBillNumberID,RequestBillID字段 增加ReachQty,ReachTotal,ReachTaxTotal
	UPDATE orderbill SET RequestBillNumberID = 0,RequestBillID = 0,ReachQty=0,ReachTotal=0,ReachTaxTotal=0
	
	IF @bitPriceTrack = 1
	BEGIN
		TRUNCATE TABLE PriceTrack			--DELETE FROM PriceTrack  --清掉价格跟踪表
		--9.4价格跟踪变化后的清除
		TRUNCATE TABLE PriceTrack_AskPrice
		TRUNCATE TABLE PriceTrack_Buy
		TRUNCATE TABLE PriceTrack_BuyOrder
		TRUNCATE TABLE PriceTrack_Quote
		TRUNCATE TABLE PriceTrack_Sale
		TRUNCATE TABLE PriceTrack_SaleOrder
		TRUNCATE TABLE PriceTrack_Appraisal
		TRUNCATE TABLE PriceTrack_Send
		TRUNCATE TABLE PriceTrack_STypeMove
	END
	ELSE
	BEGIN
		DELETE FROM dbo.PriceTrack WHERE BuyOrderPrice=NULL AND SaleOrderPrice=NULL AND CostPrice=NULL AND QueryPrice=NULL AND SalePrice=NULL AND ResponsePrice = NULL AND Discount=NULL 
	END
	
	--分支机构间最近进价
	IF @bitRecSTypeBuyPrice=1
	BEGIN
		UPDATE PType_Price SET RecAmgSTypeBuyPrice=0
	END
	
	--分支机构间最近售价
	IF @bitRecSTypeSalePrice=1
	BEGIN
		UPDATE PType_Price SET RecAmgSTypeSalePrice=0
	END
	
	--分支机构间价格跟踪
	IF @bitSTypePriceTrack=1
	BEGIN
		TRUNCATE TABLE PriceTrack_SType_Appraisal	 --暂估入库分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_AskPrice	 --询价单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Buy	 --采购入库单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_BuyOrder	 --采购订单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Quote	 --报价单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Sale	 --销售出库分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_SaleOrder	 --销售订单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Send	 --发出商品分支机构间价格跟踪表
	END

	IF @bitEventLog = 1
	BEGIN
		DELETE FROM dbo.EventLog WHERE Id<>@logid --DELETE FROM EventLog --清掉操作日志表
	END
	
	DELETE FROM PriceProtectList WHERE stypeid = @stypeid		--DELETE FROM PriceProtectList --清掉价保记录
	TRUNCATE TABLE OA_Message			--DELETE FROM OA_Message --清除在线传讯 
	DELETE FROM GiveFromSaleOrBuy WHERE SourceBillNumberId NOT IN (SELECT BillNumberId FROM dbo.BillIndex)		--清掉销售、采购关联赠送、获赠数据表
	
	/*
	TRUNCATE TABLE TCBillindex			-- 清掉提成单据索引表
	TRUNCATE TABLE TCBill				-- 清掉提成单据明细表	
	*/
	
	DELETE FROM FaPiaoBillindex WHERE stypeid = @stypeid		-- 清掉新发票单据索引表
	DELETE FROM FaPiaoBill WHERE BillNumberID NOT IN (SELECT BillNumberId FROM FaPiaoBillindex)			-- 清掉新发票单据明细表

	/*
	TRUNCATE TABLE PromotePrice			--DELETE FROM PromotePrice	-- 促销价格表
	TRUNCATE TABLE InvoiceBill			--DELETE FROM InvoiceBill	-- 发票记录表	
	TRUNCATE TABLE LocalIndex			--DELETE FROM LocalIndex	-- 货位单据索引表
	TRUNCATE TABLE LocalDetail			--DELETE FROM LocalDetail	-- 货位单据明细表
	*/
	
	-- 借欠
	DELETE FROM GoodsLend WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)			

	-- 清除财务历史状况表
	DELETE FROM MonthATypeHistory WHERE STypeId = @stypeid
	
	-- 清除按商品结算明细表
	DELETE FROM CompleteGoodTotal WHERE GoodsBillID NOT IN (SELECT BillNumberId FROM BillIndex)				
	DELETE FROM nVipAdjust WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			-- 清除消费金额调整单、积分调整单
	
	-- 清空VIP卡储值明细表
	TRUNCATE TABLE nVipAddMoney
	DELETE FROM wx_GoodsStocks WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)		-- 清除维修库存
	DELETE FROM visit WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)				-- 服务回访表
	DELETE FROM visitfj WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)				-- 服务回访附件表
	
	DELETE FROM commonpossaleindex WHERE Draft<>0								--收银小票
	DELETE FROM commonpossalelist WHERE NOT EXISTS(SELECT 1 FROM CommonPosSaleIndex WHERE PosVchCode=commonpossalelist.PosVchCode)
	DELETE FROM CommonPosPtypeCheckNdx WHERE PDVchCode<>0						--POS盘点单据
	DELETE FROM CommonPosPtypeCheckList WHERE NOT EXISTS(SELECT 1 FROM CommonPosPtypeCheckNdx WHERE CheckCode=CommonPosPtypeCheckList.CheckCode)
	
	/*清除网店相关信息*/
	DELETE FROM dbo.WdOrder 
	DELETE FROM dbo.WdOrderBody  
	DELETE FROM dbo.WdItemsDetail
	DELETE FROM dbo.WdCargoDetail
	DELETE FROM dbo.WdAccountDetail
	DELETE BillIndex FROM dbo.BillIndex B INNER JOIN dbo.WdShopBillRelation W ON W.Billnumberid = B.BillNumberId  WHERE draft = 1
	DELETE FROM dbo.WdSaleBillTemp
	DELETE FROM dbo.WdBillIndexTemp
	DELETE FROM dbo.WdShopBillRelationTemp
	DELETE FROM dbo.WdShopBillRelation 
	DELETE FROM dbo.WDGOODSSTOCKS_QTY
	DELETE FROM dbo.WdSerialsDetail	
	
	UPDATE dbo.ptype SET WdSyncFlag = 0
	UPDATE dbo.employee SET WdSyncFlag = 0
	UPDATE dbo.Stock SET WdSyncFlag = 0
	UPDATE dbo.CargoType SET WdSyncFlag = 0
	UPDATE dbo.loginuser SET WdSyncFlag = 0
	UPDATE dbo.Ac_Items SET WdSyncFlag = 0
	UPDATE dbo.Department SET WdSyncFlag = 0
	
	DELETE FROM Ac_Voucher WHERE stypeid = @stypeid
	DELETE FROM Ac_Voucher_Bill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Ac_Voucher)
	DELETE FROM Ac_Voucher_Bill_Assist_CheckItems  WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Ac_Voucher)
	DELETE FROM Ac_Voucher_Bill_CashMoneyItems  WHERE BillNumberId NOT IN (SELECT BillNumberId FROM Ac_Voucher)
	
	--9.4 出纳模块处理
	UPDATE dbo.Te_StartPeriod SET IsUse = 0,IsConnect = 0,CFYear = 0,CFPeriod = 0 WHERE stypeid = @stypeid
	/*	
	TRUNCATE TABLE dbo.Te_AccountInTransit_Detail
	TRUNCATE TABLE dbo.Te_AccountInTransit_Index
	
	TRUNCATE TABLE dbo.Te_CheckRelevance
	TRUNCATE TABLE dbo.Te_Period
	TRUNCATE TABLE dbo.Te_Journal_Detail
	TRUNCATE TABLE dbo.Te_Journal
	TRUNCATE TABLE dbo.Te_BankStatementDetail
	TRUNCATE TABLE dbo.Te_BankStatement
	*/
	DELETE FROM dbo.Te_Balance WHERE stypeid = @stypeid
	
	DELETE FROM IniBType_ARAPTotal WHERE stypeid = @stypeid
	---------------------------------------------处理期初数据-------------------------------------------------
	IF @bRebulidIni = 1
	BEGIN
		UPDATE BType SET arapExplain = '' , initComment = ''
		DELETE FROM iniGoodsStocks WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		
		--删除库龄数据
		DELETE FROM dbo.IniStockAgeGroup WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM dbo.IniStockAgeStock WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM dbo.IniStockAgeStype WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)		
		DELETE FROM ini_goodsstocks_qty WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM GP_initPTypeSerial WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM GP_initLendPtypeSerial WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM AType_Total WHERE stypeid = @stypeid
		DELETE FROM BType_ARAPTotal WHERE stypeid = @stypeid
		DELETE FROM dbo.Brandar_ArApTotal WHERE stypeid = @stypeid
		DELETE FROM SType_InnerARTotal WHERE stypeid = @stypeid
		DELETE FROM GP_initPTypeSerial WHERE stypeid = @stypeid
		DELETE FROM IniGoodsLend WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM IniCommissionStock WHERE stypeid = @stypeid
		DELETE FROM IniCommissionStock_qty WHERE stypeid = @stypeid
		DELETE FROM GoodsLocal WHERE LTypeID NOT IN (SELECT LTypeId FROM dbo.GoodsStocks)	
		
		-- 清空初始及累计金额、积分
		-- 清空期初储值金额、累计储值金额、消费储值金额、储值余额
		-- 清空可洗车次数,累计可洗车次数和期初可洗车次数 毛欣蓉 2010-08-18
		-- 清除分支机构会员卡储值信息
		TRUNCATE TABLE nVipCardSignStype 
		
		UPDATE  nVipCardSign 
		SET		TotalMoney = 0,
				TotalCent = 0,
				qCczMoney = 0,
				lJczMoney = 0,
				xFczMoney = 0,
				cZyeMoney = 0,
				CanWashTimes= 0 ,
				CanWashTimes00 = 0,
				CanWashTimesTotal = 0
		WHERE	jkStypeId = @stypeid		
		
		TRUNCATE TABLE wx_IniGoodsStocks	-- 清空维修期初库存
		TRUNCATE TABLE Ac_IniAccount							-- 清空财务期初
		TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems			-- 清空财务期初的辅助核算		
		TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems_Detail	-- 清空财务期初的辅助核算对照表		
		TRUNCATE TABLE RetailCombinationBill
		TRUNCATE TABLE dbo.Te_InitDataIndex
		TRUNCATE TABLE dbo.Te_InitDataDetail
		
		----------------期初实物库存----------------
		TRUNCATE TABLE dbo.IniFactStocks
		TRUNCATE TABLE dbo.IniFactStocks_Qty
		TRUNCATE TABLE dbo.gp_iniFactPtypeSerial
		DELETE FROM dbo.FactIndex WHERE isini=1 
		DELETE FROM dbo.FactDepotAllot WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
		DELETE FROM dbo.FactDepotInOut WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
		TRUNCATE TABLE dbo.FactInOut
		--------------------------------------------
	END
	ELSE
	BEGIN
		DECLARE  @costing INT=0
		SELECT @costing=SubValue FROM sysdata WHERE SubName='costing'
		DELETE FROM iniGoodsStocks WHERE Qty = 0 AND Total=0
		--删除库龄数据
		DELETE dbo.IniStockAgeGroup WHERE Qty = 0 AND Total=0
		DELETE dbo.IniStockAgeStock	WHERE Qty = 0 AND Total=0
		DELETE dbo.IniStockAgeStype	WHERE Qty = 0 AND Total=0
		
		DELETE FROM dbo.Ini_GOODSSTOCKS_QTY WHERE Qty=0 AND NQty=0 
		DELETE AType_Total WHERE Total00=0 OR Ntotal00=0
		DELETE dbo.SType_InnerARTotal WHERE InnerARTotal00=0;
		UPDATE SType_InnerARTotal SET InnerARTotal=0 -- 内部应收期初 
		UPDATE AType_Total SET Total=0,Ntotal=0
		DELETE BType_ARAPTotal WHERE ISNULL(YSTotal00,0)=0 AND ISNULL(YFTotal00,0)=0 AND ISNULL(ARTotal00,0)=0 AND ISNULL(APTotal00,0)=0 
			   AND ISNULL(nYSTotal00,0)=0 AND ISNULL(nYFTotal00,0)=0 AND ISNULL(nARTotal00,0)=0 AND ISNULL(nAPTotal00,0)=0 
			   AND ISNULL(NGRIRTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0 AND ISNULL(FCTotal00,0)=0 AND ISNULL(GRIRTotal00,0)=0 
		UPDATE BType_ARAPTotal SET ARTotal=0,APTotal=0,YSTotal=0,YFTotal=0,nARTotal=0,nAPTotal=0,nYSTotal=0,nYFTotal=0,GRIRTotal=0,NGRIRTotal=0,FCTotal=0,NFCTotal=0
		
		DELETE dbo.Brandar_ArApTotal WHERE ISNULL(YSTotal00,0)=0 AND ISNULL(ARTotal00,0)=0 
			   AND ISNULL(nYSTotal00,0)=0 AND ISNULL(nARTotal00,0)=0 
			   
		UPDATE Brandar_ArApTotal SET ARTotal=0,YSTotal=0,nARTotal=0,nYSTotal=0
		
		IF @costing<>3
		BEGIN
			UPDATE	iniGoodsStocks SET Total = CAST(Total AS  NUMERIC(24, 10) )
			UPDATE	iniGoodsStocks SET Price = dbo.F_RoundPrice(Total/Qty) WHERE	Qty <> 0
		END
		--9.7数量为零，金额不为零的数据不删
		DELETE FROM iniCommissionStock WHERE Qty = 0 AND Total=0 AND CostTotal=0
		DELETE FROM dbo.IniCommissionStock_Qty WHERE Qty=0 AND NQty=0
		UPDATE	iniCommissionStock SET Total = CAST(Total AS  NUMERIC(24, 10) ),CostTotal = CAST(CostTotal AS  NUMERIC(24, 10) )
		
		-- 清空累计金额、积分，保留初始金额、积分
		-- 清空累计储值金额、消费储值金额、储值余额
		-- 清空可洗车次数,累计可洗车次数 毛欣蓉 2010-08-18
		-- A8清除会员卡信息期初数据,V3 V1 需要显示,A8不显示
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName='ProInfo' AND SubValue=2)
		BEGIN
			UPDATE	nVipCardSign 
			SET		TotalMoney = 0,
					TotalCent = 0,
					qCczMoney = 0,
					lJczMoney = 0,
					xFczMoney = 0,
					cZyeMoney = 0,
					CanWashTimes= 0 ,
					CanWashTimes00 = 0,
					CanWashTimesTotal = 0
			WHERE	jkStypeId = @stypeid
		END
		ELSE
		BEGIN
			UPDATE  nVipCardSign 
			SET		TotalMoney = 0,
					TotalCent = 0,
					lJczMoney = 0,
					xFczMoney = 0,
					cZyeMoney=qCczMoney,
					CanWashTimes= CanWashTimes00 ,
					CanWashTimesTotal = 0
			WHERE	jkStypeId = @stypeid
		END	
		/* 
		** 累计已消费储值金额=累计已消费储值金额-本年消费储值金额
		** 累计储值金额=累计储值金额-本年储值金额
		** 累计消费金额=累计消费金额-本年消费金额
		** 储值余额=累积储值余额-累计已消费储值余额
		** 本年储值金额清零
		** 本年消费储值金额清零
		** 本年消费金额清零
		*/
		UPDATE	nVipCardSignStype
		SET		lJxFczMoney=lJxFczMoney-BnXFCzMoney,	
				LjCzMoney=LjCzMoney-BnCzMoney,			
				LjXfMoney=LjXfMoney-BnXFMoney,			
				BnCzMoney=0,							
				BnXFCzMoney=0,							
				BnXFMoney=0	
		WHERE	StypeId = @stypeid							
		
		UPDATE  dbo.nVipCardSignStype
		SET		CzYeMoney=LjCzMoney-lJxFczMoney,
				qCczMoney=LjCzMoney-lJxFczMoney
		WHERE	StypeId = @stypeid
		
		DELETE FROM wx_IniGoodsStocks WHERE Qty = 0 AND Nqty=0 AND Total=0
		DELETE FROM dbo.IniGoodsLend WHERE LendQty=0 AND BorrowQty=0 AND Qty=0
		
		--出纳
		UPDATE Te_InitDataIndex SET Finish=0 WHERE stypeid = @stypeid
	END
	
	----------------------------------------------处理不包含期初单据的单据的草稿-------------------------------
	IF @clearauditflow = 1
	BEGIN
		UPDATE dbo.BillIndex SET IfAudit=''	 WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=2) 
		UPDATE dbo.ReceiptBillIndex SET IfAudit=''	WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=5) 
		UPDATE dbo.OrderIndex SET IfAudit='' WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=0) 
		UPDATE dbo.LendIndex SET IfAudit='' WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=1) 
		UPDATE dbo.RequestIndex SET IfAudit=''  WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=3) 
		UPDATE dbo.CommissionBillNew SET BillState=1  WHERE billNumberId IN (SELECT billNumberId FROM dbo.AuditingBill WHERE BillIndexType=4) 
		
		--审核清除外键约束
		------------------------------------------删除外键开始-----------------------------------------------
		IF OBJECT_ID(N'[dbo].[FK_AuditingReason_AuditingFlowSet]', 'F') IS NOT NULL
		BEGIN
			ALTER TABLE [dbo].[AuditingReason] DROP CONSTRAINT [FK_AuditingReason_AuditingFlowSet];
		END
		IF OBJECT_ID(N'[dbo].[FK_AuditingFlowDetail_AuditingFlowSet]', 'F') IS NOT NULL
		BEGIN
			ALTER TABLE [dbo].[AuditingFlowDetail] DROP CONSTRAINT [FK_AuditingFlowDetail_AuditingFlowSet];
		END
		------------------------------------------删除外键结束-----------------------------------------------
		
		DELETE FROM dbo.AuditingBillDetail WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)
		DELETE FROM dbo.AuditingBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)
		TRUNCATE TABLE AuditingReason
		TRUNCATE TABLE AuditingStepReason
		TRUNCATE TABLE AuditingFlowDetail
		TRUNCATE TABLE AuditingFlowSet
	END
	
	IF @bRebulidDraft = 1     
	BEGIN		
		DELETE FROM retailBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		--零售单
		DELETE FROM retailBackBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		--零售退货
		DELETE FROM BeforePromoteIndex WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)	--零售零售促销方案主表
		DELETE FROM BeforePromoteRetailBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)	--零售零食促销方案明细
		DELETE FROM BeforePromoteSaleBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)	--销售出库促销方案
		DELETE FROM DepBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)				-- 固定资产折旧
		DELETE FROM GatheringBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		-- 收款单
		DELETE FROM PayBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)				-- 付款单
		DELETE FROM LoseBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)				-- 报损单
		DELETE FROM OverFlowBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			-- 报溢单
		DELETE FROM MoveMoneyBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		-- 转款单
		DELETE FROM adPriceBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			-- 成本调价单
		DELETE FROM MoveBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)				-- 同价调拨单
		DELETE FROM MoveBjBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			-- 变价调拨单
		
		DELETE FROM PerformanceDistribution WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)  --业绩分配

		DELETE FROM DisassembleBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		-- 生产拆装单
		DELETE FROM GiveMeBill	 WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		-- 获赠单
		DELETE FROM GiveBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)				-- 赠送单
		DELETE FROM InvoiceBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			-- 发票表
		DELETE FROM STypeMoveBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		--分支机构调拨出库单，分支机构调拨入库单
		DELETE FROM RepairDeal WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			--DELETE RepairDeal
		DELETE FROM RepairDealDetail WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		--DELETE RepairDealDetail
		DELETE FROM RepairEngage WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			--DELETE RepairEngage
		DELETE FROM AuditingBillDetail WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)
		DELETE FROM AuditingBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)

		DELETE FROM GoodsExchangeBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)	-- 换货单
		DELETE FROM AccountCredence WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		-- 会计凭证

		DELETE FROM	wx_bill_jiejian WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)--维修接件单
		DELETE FROM	wx_bill_self WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)--维修单
		DELETE FROM	wx_Bill_Send WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)--送修单
		DELETE FROM	wx_bill_call WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)--报修单
		DELETE FROM wx_Bill_In WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			-- 新维修 - 维修品调入单
		DELETE FROM wx_Bill_Out WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			-- 新维修 - 维修品调出单
		DELETE FROM wx_Bill_Move WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			-- 新维修 - 维修品调拨单
		DELETE FROM PrintRecord	 WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)		--打印记录表
		DELETE FROM AddPrintCountRecord WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)	--增加的打印次数记录
		DELETE FROM QuotePriceBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex) 			--(报价单) 
		DELETE FROM AskPriceBill  WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)			--(询价单)
		
		DELETE FROM IntegralExchangeBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)					--(积分兑换单明细表)		

		DELETE FROM ShareSourceBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)						--费用分摊采购销售明细
		DELETE FROM ShareFeeBill WHERE FromBillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)							--费用分摊费用明细
		DELETE FROM OtherInOutBill	 WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)					--其他出入库单明细
		DELETE FROM SerialAdjustIndex WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)					--序列号调整单主表
		DELETE FROM SerialAdjustBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)						--序列号调整单明细
		DELETE FROM CM_CarUseIndex WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)  --（车辆使用登记单主表
		DELETE FROM CM_CarUseBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex)  --（车辆使用登记单明细表）
		DELETE FROM CM_FeeIndex WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex) --（车辆费用单主表） 
		DELETE FROM CM_FeeBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM BillIndex) --（车辆费用单明细表）
		
		DELETE FROM LendIndex WHERE STypeid = @stypeid    --借欠
		DELETE FROM LendBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM LendIndex)	--借欠
		DELETE FROM dbo.LendCheck WHERE BillNumberid NOT IN (SELECT BillNumberId FROM LendIndex) --借欠 
		
		---------------实物库存 Start---------------
		DELETE FROM dbo.FactIndex WHERE isini=0 
		DELETE FROM dbo.Fact_InoutPtypeSerial WHERE BillNumberid NOT IN (SELECT BillNumberId FROM FactIndex)
		DELETE FROM dbo.Fact_InOutstocktable WHERE BillNumberid NOT IN (SELECT BillNumberId FROM FactIndex)
		DELETE FROM dbo.gp_FactPtypeSerial  WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM dbo.FactStocks  WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM dbo.FactStocks_Qty  WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)
		DELETE FROM dbo.FactDepotInOut WHERE BillNumberid NOT IN (SELECT BillNumberId FROM FactIndex)
		DELETE FROM dbo.FactDepotAllot WHERE BillNumberid NOT IN (SELECT BillNumberId FROM FactIndex)
		---------------实物库存 End---------------		
	END
	ELSE
	BEGIN
		--- 收款单 ---
		SELECT a.* INTO #GatheringBill FROM GatheringBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='4' AND b.Draft=1
		TRUNCATE TABLE GatheringBill
		SET IDENTITY_INSERT dbo.GatheringBill ON
		SET @columns=dbo.f_getallcolumns('GatheringBill')
		EXEC('INSERT INTO GatheringBill ('+@columns+') SELECT '+@columns+ ' FROM #GatheringBill')
		SET IDENTITY_INSERT GatheringBill OFF
		DROP TABLE #GatheringBill		
		
		--清除业绩分配明细
		SELECT a.* INTO #PerformanceDistribution FROM PerformanceDistribution a INNER JOIN billindex b ON a.billnumberid=b.billnumberid
		TRUNCATE TABLE PerformanceDistribution
		SET IDENTITY_INSERT dbo.PerformanceDistribution ON
		SET @columns=dbo.f_getallcolumns('PerformanceDistribution')
		EXEC('INSERT INTO PerformanceDistribution ('+@columns+') SELECT '+@columns+ ' FROM #PerformanceDistribution')
		SET IDENTITY_INSERT PerformanceDistribution OFF
		DROP TABLE #PerformanceDistribution
		--DELETE FROM PerformanceDistribution WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)--清除业绩分配明细
		DELETE FROM PayBill			 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=PayBill.BillNumberId AND billtype ='66' AND Draft=1)	-- 付款单
		DELETE FROM LoseBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=LoseBill.BillNumberId AND  billtype ='9'  AND Draft=1)	-- 报损单
		DELETE FROM OverFlowBill	 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=OverFlowBill.BillNumberId AND  billtype ='14' AND Draft=1)	-- 报溢单
		DELETE FROM MoveMoneyBill	 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=MoveMoneyBill.BillNumberId AND  billtype ='77' AND Draft=1)	-- 转款单
		DELETE FROM adPriceBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=adPriceBill.BillNumberId AND  billtype ='57' AND Draft=1)	-- 成本调价单
		DELETE FROM RetailBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailBill.BillNumberId)			-- 零售单
		DELETE FROM RetailBackBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailBackBill.BillNumberId)			-- 零售退货
		DELETE FROM DepBill WHERE NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=DepBill.BillNumberId)	--固定资产折旧
		--- 同价调拨单 ---
		SELECT a.* INTO #MoveBill FROM MoveBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype ='17' AND b.Draft=1
		TRUNCATE TABLE MoveBill
		SET IDENTITY_INSERT MoveBill ON
		SET @columns=dbo.f_getallcolumns('MoveBill')
		EXEC('INSERT INTO MoveBill ('+@columns+') SELECT '+@columns+ ' FROM #MoveBill')
		SET IDENTITY_INSERT MoveBill OFF
		DROP TABLE #MoveBill
		
		DELETE FROM MoveBjBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=MoveBjBill.BillNumberId AND  billtype ='21' AND Draft=1)	-- 变价调拨单
		DELETE FROM RetailCombinationBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailCombinationBill.BillNumberId)			-- 零售单
		
		DELETE FROM DisassembleBill	 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=DisassembleBill.BillNumberId AND  billtype ='16' AND Draft=1)	-- 生产拆装单
		DELETE FROM GiveMeBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=GiveMeBill.BillNumberId AND  billtype ='126' AND Draft=1)	-- 获赠单
		DELETE FROM GiveBill		 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=GiveBill.BillNumberId AND  billtype ='139' AND Draft=1)	-- 赠送单
		DELETE FROM InvoiceBill		 --WHERE BillNumberID NOT IN (SELECT * FROM BillIndex WHERE AND billtype ='11' AND Draft=1)	-- 发票表
		
        --- 分支机构调拨出库单，分支机构调拨入库单 ---
		SELECT a.* INTO #STypeMoveBill FROM STypeMoveBill a INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid WHERE b.billtype IN (187,188) AND b.Draft=1
		TRUNCATE TABLE STypeMoveBill
		SET IDENTITY_INSERT STypeMoveBill ON
		SET @columns=dbo.f_getallcolumns('STypeMoveBill')
		EXEC('INSERT INTO STypeMoveBill ('+@columns+') SELECT '+@columns+ ' FROM #STypeMoveBill')
		SET IDENTITY_INSERT STypeMoveBill OFF
		DROP TABLE #STypeMoveBill
        
		DELETE RepairDeal WHERE NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=RepairDeal.BillNumberID)
		DELETE RepairDealDetail WHERE NOT EXISTS (SELECT 1 FROM RepairDeal WHERE BillNumberId=RepairDealDetail.BillNumberID)
		DELETE RepairEngage WHERE NOT EXISTS(SELECT 1 FROM RepairDeal WHERE EngageBillID=RepairEngage.BillNumberID) AND Draft <> 0

		--清掉审核的相关表 谢吉康  2004-02-26
		DELETE FROM AuditingBillDetail WHERE BillNumberID NOT IN (SELECT BillNumberID FROM BillIndex)
		DELETE FROM AuditingBill WHERE BillNumberID NOT IN (SELECT BillNumberID FROM BillIndex)

		DELETE FROM GoodsExchangeBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=GoodsExchangeBill.BillNumberId AND  BillType ='155' AND Draft=1)	-- 换货单
		DELETE FROM AccountCredence	 WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AccountCredence.BillNumberId AND  billtype ='159' AND Draft=1)	-- 会计凭证
		
		DELETE FROM	wx_bill_jiejian WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_bill_jiejian.BillNumberId  AND Draft=1)--维修接件单
		DELETE FROM	wx_bill_self WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_bill_self.BillNumberId  AND Draft=1)--维修单
		DELETE FROM	wx_Bill_Send WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_Bill_Send.BillNumberId  AND Draft=1)--送修单
		DELETE FROM	wx_bill_call WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_bill_call.BillNumberId  AND Draft=1)--报修单
		DELETE FROM wx_Bill_In WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_Bill_In.BillNumberId AND  BillType ='173' AND Draft=1)			-- 新维修 - 维修品调入单
		DELETE FROM wx_Bill_Out WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_Bill_Out.BillNumberId AND  BillType ='174' AND Draft=1)		-- 新维修 - 维修品调出单
		DELETE FROM wx_Bill_Move WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=wx_Bill_Move.BillNumberId AND  BillType ='175' AND Draft=1)		-- 新维修 - 维修品调拨单
		DELETE FROM QuotePriceBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=QuotePriceBill.BillNumberId AND  BillType ='184' AND Draft=1)
		DELETE FROM AskPriceBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AskPriceBill.BillNumberId AND  BillType ='185' AND Draft=1)
		
		DELETE FROM IntegralExchangeBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=IntegralExchangeBill.BillNumberId AND  BillType ='183' AND Draft=1)
		DELETE FROM BillIndex WHERE BillType IN (191,197) AND ISNULL(BTypeId,'') <> ''
		TRUNCATE TABLE ShareSourceBill	--费用分摊出入库单明细
		TRUNCATE TABLE ShareFeeBill		--费用分摊费用明细
		DELETE FROM OtherInOutBill WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=OtherInOutBill.BillNumberId AND  draft = 1)
		DELETE FROM SerialAdjustIndex WHERE   draft = 0
		DELETE FROM SerialAdjustBill WHERE NOT EXISTS(SELECT 1 FROM SerialAdjustIndex WHERE draft = 1 AND BillNumberId=SerialAdjustBill.BillNumberId)
		
		DELETE FROM LendBill WHERE BillNumberId IN(SELECT BillNumberId FROM dbo.LendIndex WHERE ifcheck='t') --借欠
		DELETE FROM LendIndex WHERE  draft = 0 
		TRUNCATE TABLE dbo.LendCheck  --借欠 
		
		DELETE FROM ReceiptBill WHERE Not EXISTS (SELECT 1 FROM dbo.ReceiptBillIndex WHERE Draft=1 AND BillNumberID=ReceiptBill.BillNumberID)
		DELETE FROM ReceiptBillIndex WHERE Draft=0  AND IsIni=0
		
		DELETE FROM dbo.FactIndex WHERE ifcheck='t' AND IsIni=0
		DELETE FROM dbo.FactDepotAllot WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
		DELETE FROM dbo.FactDepotInOut WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
		TRUNCATE TABLE dbo.FactStocks
		TRUNCATE TABLE dbo.FactStocks_Qty
		TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
		TRUNCATE TABLE dbo.Fact_InOutstocktable
		TRUNCATE TABLE dbo.gp_FactPtypeSerial
	END
	
	TRUNCATE TABLE dbo.tmpGain
	
    ------------------------------------------------处理其他----------------------------------------------------------------------
    --自定义删除
	;WITH CustomExists
	 AS
	 (
		SELECT BillType,BillNumberID FROM dbo.BillIndex
		UNION ALL
		SELECT BillType,BillNumberID FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillType,BillNumberID FROM dbo.OrderIndex
		UNION ALL 
		SELECT BillType,BillNumberID FROM dbo.LendIndex
		UNION ALL
		SELECT 204 AS BillType,BillNumberID FROM dbo.RequestIndex
		UNION ALL 
		SELECT 311 AS BillType,BillNumberId FROM dbo.CommissionBillNew
		UNION ALL 
		SELECT BillType,BillNumberID FROM dbo.FaPiaoBillIndex
		UNION ALL
		SELECT BillType,BillNumberid FROM dbo.FactIndex
	 )
	SELECT BillType,BillNumberID INTO #CustomExists FROM CustomExists
	--9.7自定义
	DELETE A FROM dbo.Custom_BillIndex A WHERE NOT EXISTS(SELECT 1 FROM #CustomExists WHERE BillType=A.BillType AND BillNumberID=A.BillId)
	DELETE A FROM dbo.Custom_BillDetails A WHERE NOT EXISTS(SELECT 1 FROM #CustomExists WHERE BillType=A.BillType AND BillNumberID=A.BillId)
	--<9.7自定义
	DELETE FROM  CustomBillColumns WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.CustomBillColumns.BillNumberId)
	DELETE FROM  CustomBillDetailColumns WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.CustomBillDetailColumns.BillNumberId AND BillType=dbo.CustomBillDetailColumns.billtype)
														AND NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.CustomBillDetailColumns.billnumberid AND dbo.CustomBillDetailColumns.billtype=9999)
	DROP TABLE #CustomExists
			
    --清除多账户
	DELETE FROM BillMulAccount WHERE NOT EXISTS(SELECT 1 FROM BillIndex b WHERE b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype=BillMulAccount.billtype
												UNION 
												SELECT  1 FROM dbo.Coupon_BillIndex b WHERE b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype=BillMulAccount.billtype)	
	--清除品牌多账户
	DELETE FROM BillMulBrand WHERE NOT EXISTS(SELECT 1 FROM BillIndex b WHERE b.BillNumberId=BillMulBrand.BillNumberId AND b.billtype=BillMulBrand.billtype
												UNION 
												SELECT  1 FROM dbo.Coupon_BillIndex b WHERE b.BillNumberId=BillMulBrand.BillNumberId AND b.billtype=BillMulBrand.billtype)				
		
	IF @bitRecPrice = 1
	BEGIN
		UPDATE PType SET recPrice=0
		UPDATE dbo.PType_Price SET RecAmgSTypeBuyPrice=0
		UPDATE PType_STypePrice SET RecPrice=0
	END

	--清除打印记录
	SELECT billnumberid,billtype INTO #PrintTmp 
	FROM 
		(SELECT BillNumberId,BillType FROM  BillIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  OrderIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  requestindex
		UNION ALL
		SELECT BillNumberId,BillType FROM FaPiaoBillIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  serialadjustindex
		UNION ALL
		SELECT BillNumberId,164 FROM  TCBillindex
		UNION ALL
		SELECT BillNumberId,BillType FROM  V_LendFace
		UNION ALL
		SELECT ProduceModelID,127 FROM  producemodelindex
		UNION ALL
		SELECT stockCheckID,306 FROM  StockCheckIndex
		UNION ALL 
		SELECT BillNumberId,BillType FROM CM_CarUseIndex
		UNION ALL 
		SELECT BillNumberId,BillType FROM CM_FeeIndex ) A 
		
        --- 打印记录 ---
	SELECT a.* INTO #printrecord FROM printrecord a INNER JOIN #PrintTmp b ON a.billnumberid=b.billnumberid WHERE a.billtype=b.BillType
	TRUNCATE TABLE printrecord
	INSERT INTO dbo.PrintRecord select * FROM #printrecord	
	    --- 增加打印次数记录 ---
	SELECT a.* INTO #AddPrintCountRecord FROM AddPrintCountRecord a INNER JOIN #PrintTmp b ON a.billnumberid=b.billnumberid  WHERE a.billtype=b.BillType
	TRUNCATE TABLE AddPrintCountRecord
	INSERT INTO AddPrintCountRecord (billtype,BillNumberId,etypeid,addprintcount) select billtype,BillNumberId,etypeid,addprintcount from #AddPrintCountRecord
	
	--------------------清除附件和附件log start-------------------------------
	SELECT * INTO #BillAttachFiles FROM BillAttachFiles WHERE EXISTS (SELECT 1 FROM #PrintTmp WHERE BillNumberId=BillAttachFiles.BillNumberId AND BillType=BillAttachFiles.BillType)
	TRUNCATE TABLE dbo.BillAttachFiles
	SET IDENTITY_INSERT dbo.BillAttachFiles ON
	SET @columns=dbo.f_getallcolumns('BillAttachFiles')
	EXEC('INSERT INTO BillAttachFiles ('+@columns+') SELECT '+@columns+ ' FROM #BillAttachFiles')
	SET IDENTITY_INSERT BillAttachFiles OFF
	
	SELECT * INTO #BillAttachFileslog FROM BillAttachFileslog WHERE EXISTS (SELECT 1 FROM #PrintTmp WHERE BillNumberId=BillAttachFileslog.BillNumberId AND BillType=BillAttachFileslog.BillType)
	TRUNCATE TABLE dbo.BillAttachFileslog
	SET IDENTITY_INSERT dbo.BillAttachFileslog ON
	SET @columns=dbo.f_getallcolumns('BillAttachFileslog')
	EXEC('INSERT INTO BillAttachFileslog ('+@columns+') SELECT '+@columns+ ' FROM #BillAttachFileslog')
	SET IDENTITY_INSERT BillAttachFileslog OFF
	--------------------清除附件和附件log end-------------------------------
	
	DROP TABLE #PrintTmp,#AddPrintCountRecord,#printrecord,#BillAttachFiles,#BillAttachFileslog
	
	IF @bitMessage='1'
	BEGIN
		TRUNCATE TABLE IM_Message_NoSocket
		TRUNCATE TABLE IM_Message_NoSocket_Bak
	END
	
	--
	--处理IM消息，把有编号的清空
	UPDATE dbo.IM_Message_NoSocket SET BillNumberId=0
	--
	IF @bitPosdata='1'
	BEGIN
		TRUNCATE TABLE dbo.PosSaleBill
		TRUNCATE TABLE dbo.PosSaleBillIndex
		TRUNCATE TABLE dbo.PosMulAccount
		TRUNCATE TABLE dbo.PosSaleBillAll
		TRUNCATE TABLE dbo.PosSaleBillIndexAll
		TRUNCATE TABLE dbo.PosMulAccountAll
		TRUNCATE TABLE dbo.PosSaleMergeFailed
		TRUNCATE TABLE dbo.PosRetailRecord
	END
	ELSE
	BEGIN
		DELETE FROM dbo.PosRetailRecord 
		WHERE RetailBillNumberId NOT IN(SELECT BillNumberID FROM dbo.BillIndex WHERE BillType IN(215,305)) AND 
			  PosBillNumberId NOT IN (SELECT BillNumberID FROM dbo.PosSaleBillIndexAll WHERE Billtype IN (215,305))
	END

	UPDATE AType SET Total = 0
	UPDATE BType SET arTotal = 0,apTotal = 0
	
	DELETE 
	FROM	Monthproc 
	WHERE	MonthNo <> '本期' 
			AND stypeid = @stypeid
	
	DECLARE @period INT=1,
			@fyear INT,
			@startdate DATETIME
			
	SELECT @fyear=subvalue FROM dbo.sysdata WHERE SubName='fyear'
	SELECT @period=FMonth,@startdate=FBegin FROM dbo.Ac_Period WHERE FPeriod=FMonth AND fyear=@fyear
	
	UPDATE	A 
	SET		StartDate=ISNULL(FBegin,@StartDate),
			period=ISNULL(B.SFPeriod,1),
			Year=ISNULL(B.SFYear,YEAR(@StartDate))
	FROM	dbo.MonthProc A,
			dbo.SType_UserConfig B,
			dbo.Ac_Period C
	WHERE	A.STypeID=B.StypeId 
			AND B.SFPeriod=C.FPeriod 
			AND B.SFYear=C.FYear 
			AND A.MonthNo='本期'
			AND B.stypeid = @stypeid
	
	UPDATE SysData SET SubValue = '0000000000' WHERE SubName LIKE '%Code' and SubName NOT IN('bwbcode','hyyunsms_usercode')--排除短信账号
	
	/*
	UPDATE SysData SET SubValue='1' WHERE SubName = 'period'	
	UPDATE SysData SET SubValue=@period WHERE SubName = 'FPeriod'
	UPDATE SysData SET SubValue='1' WHERE SubName = 'CanAuditing'
	UPDATE UserConfig SET Value = '0' WHERE ConfigName = 'AverageCostPrice'
	UPDATE SysData SET SubValue='T' WHERE SubName = 'inicanmodify' 
	*/	
	
	UPDATE	SType_UserConfig
	SET		Value=0
	FROM	SType_Config b
	WHERE	SType_UserConfig.ConfigNo=b.ConfigNo  
			AND b.ConfigName='stypeinicanmodify'
			AND stypeid = @stypeid
	
	--父节点没有存在的必要了
	DELETE FROM dbo.SType_UserConfig WHERE StypeId IN (SELECT typeid FROM dbo.SType WHERE sonnum>0)
		
	UPDATE Ac_AccountsPeroid_Stype SET FYear = SFYear,FPeriod = SFPeriod,IsUse =0 WHERE Stypeid = @stypeid
	
	--修改期初序列号的入库时间
	UPDATE GP_InitPTypeSerial SET InKtypeTime = NULL WHERE KTypeId IN (SELECT TypeId FROM Stock WHERE stypeid = @stypeid)	
	
	--是否清除商品最近售价 0 - 不清除，1 - 清除
	IF @bitRecSalePrice = '1'
	BEGIN
		UPDATE PType_STypePrice SET RecSalePrice = 0 , RecAppraisalPrice = 0 ,RecSendPrice =0
		
		UPDATE dbo.PType_Price SET RecAmgSTypeSalePrice=0
	END
	--系统重建，单据编号种子数处理
	EXEC GP_BillCode_Seed_ReBuild
	
	EXEC GP_OldBill_Clone_Del
	
    EXEC GP_FixedAssets_ReBuild @bRebulidIni,@bRebulidDraft	
    
    --重建更新已完成订单状态
    UPDATE OrderIndex SET OrderState=0 WHERE OrderState=1 and billNumberId not in (SELECT BillNumberID FROM Ini_GoodsStocks_Order)
    
    --系统重建，重算草稿库存
    exec QP_Recount_DraftQty
    
     --系统重建，重算订单库存
    exec QP_Recount_OrderQty
    
    --系统重建，清除部分pos相关的数据
    DELETE FROM dbo.DepositBillIndex WHERE SID IN (SELECT TypeId FROM STock WHERE stypeid = @stypeid)
	DELETE FROM dbo.DepositBillDetail WHERE BillnumberID NOT IN (SELECT BillNumberID FROM DepositBillDetail)
    
    --店账通单据的处理
    DELETE FROM EshopBillRelation WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
    
    --删除电子面单
    DELETE FROM BillExpressage WHERE VchCode NOT IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 11)
    
    DROP TABLE #DelBillIndex
    
	COMMIT TRAN Rebulid
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_SystemRebuild_Stype_All]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_SystemRebuild_Stype_All]
GO


/*
	作者：谢吉康
	日期：2010-10-09
	描述：系统重建 - 按分支机构
*/
CREATE       PROCEDURE GP_SystemRebuild_Stype_All
(
    @etypeID					VARCHAR(50), 
	@bRebulidIni				bit,				-- 是否清除期初；0 - 不清除，1 - 清除
	@bRebulidDraft				bit,				-- 是否清除草稿；0 - 不清除，1 - 清除
	@bitRecPrice				bit,				-- 是否清除最近进价；0 - 不清除，1 - 清除
	@bitEventLog				bit,				-- 是否清除操作日志
	@bitPriceTrack				bit,				-- 是否清除价格跟踪信息；0 - 不清除，1 - 清除
	@bitRecSalePrice			BIT,				-- 是否清除商品最近售价 0 - 不清除，1 - 清除
	@bitMessage					BIT,				-- 是否清除聊天记录；0 - 不清除，1 - 清除
	@bitPosdata					BIT,				-- 是否清除小票数据
	@bitRecSTypeBuyPrice		BIT,				-- 是否清除分支机构间最近进价 0 - 不清除， 1 - 清除
	@bitRecSTypeSalePrice		BIT,				-- 是否清除分支机构间最近售价 0 - 不清除， 1 - 清除
	@bitSTypePriceTrack			BIT,				-- 是否清除分支机构间价格跟踪信息 0 - 不清除， 1 - 清除
	@clearauditflow				BIT,				-- 是否除审核流程	0 - 不清除， 1 - 清除
	@clearStopOrder				BIT,				-- 是否清除已中止订单	0 - 不清除， 1 - 清除
	@clearCompleteOrder			BIT,				-- 是否清除已完成订单	0 - 不清除， 1 - 清除
	@clearAllOrder				BIT,				-- 是否清除所有订单	0 - 不清除， 1 - 清除
	@clearCompleteAllotApply	BIT,				--是否清除已完成的调货申请单 0-不清除 1-清除
	@clearNoCompleteAllotApply	BIT,				--是否清除未完成的调货申请单 0-不清除 1-清除
	@clearcompletegetbillapply BIT,--是否清除已完成的要货申请单 0-不清除 1-清除
	@clearnocompletegetbillapply BIT,--是否清除未完成的要货申请单 0-不清除 1-清除
	@logid						INT, 				--当前操作日志ID
	@stypeid					VARCHAR(MAX) = ''	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @I			INT,
		@nCount		INT
		
CREATE TABLE #SType
(
	nid		INT IDENTITY(1,1),
	stypeid	VARCHAR(50)
)	

INSERT INTO #SType(stypeid) SELECT a FROM dbo.f_split(@stypeid,',')	

SET @nCount = @@ROWCOUNT

SET @I = 1

WHILE @I <= @nCount
BEGIN
	EXEC GP_SystemRebuild_Stype	@etypeID,
								@bRebulidIni,
								@bRebulidDraft,
								@bitRecPrice,
								@bitEventLog,
								@bitPriceTrack,
								@bitRecSalePrice,
								@bitMessage,
								@bitPosdata,
								@bitRecSTypeBuyPrice,
								@bitRecSTypeSalePrice,
								@bitSTypePriceTrack,
								@clearauditflow,
								@clearStopOrder,
								@clearCompleteOrder,
								@clearAllOrder,
								@clearCompleteAllotApply,
								@clearNoCompleteAllotApply,
								@logid,
								@stypeid
								
	SET @I = @I + 1								
END

DROP TABLE #SType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_TEBankStatementAddOrModify]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_TEBankStatementAddOrModify]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：李灏龙	
	日期：2014年6月26日 14:10:50
	描述：银行对账单的新增、修改
*/
CREATE PROCEDURE GP_TEBankStatementAddOrModify
(
	@Id				INT,
	@BusinessDate	DATE,
	@BusinessId		VARCHAR(50),
	@ETypeId		VARCHAR(50),
	@TellerName		VARCHAR(50),
	@Summary		VARCHAR(1000),
	@FDebit			 NUMERIC(24, 10) ,
	@FCredit		 NUMERIC(24, 10) ,
	@Cid			INT,
	@AccountId		INT,
	@FSettleId		INT,
	@FSettleNo		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@RATE			 NUMERIC(24, 10) ,
		@BILLNUMBERID	INT,
		@szPId	NVARCHAR(500),
		@stypeid			VARCHAR(50),
		@LASTJOURNALDATE	DATE,
		@RES	INT
		
IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND deleted=1)
	BEGIN
		RAISERROR('该分支机构已被停用，不能进行操作！',16,1) RETURN -2
	END	
		
SELECT @Rate = Rate FROM Ac_Currency WHERE CId = @Cid
SET @RES = 0

SET @FDebit = ISNULL(@FDebit,0)
SET @FCredit = ISNULL(@FCredit,0)
SELECT @stypeid = STypeId	FROM Te_BankAccount WHERE Id = @AccountId

IF EXISTS (SELECT TOP 1 1 FROM Te_BankStatement WHERE AccountId IN (SELECT ID FROM Te_BankAccount WHERE STypeId = @stypeid ))
	SELECT TOP 1 @LASTJOURNALDATE=DATEADD(DAY,1,Businessdate) FROM Te_BankStatement WHERE AccountId IN (SELECT ID FROM Te_BankAccount WHERE STypeId = @stypeid ) ORDER BY Businessdate DESC
ELSE
	SELECT TOP 1 @LASTJOURNALDATE=FBegin	FROM  Ac_Period ap INNER JOIN Te_Period tp ON tp.FYear = ap.FYear AND tp.FPeriod = ap.FPeriod AND tp.STypeId = @Stypeid 



IF NOT EXISTS(SELECT TOP 1 1 FROM Te_StartPeriod tsp WHERE TSP.STypeId = @stypeid AND IsUse = 1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE subname='proinfo' AND SubValue = 2)
		RAISERROR('当前对账单所属的分支机构的出纳系统没有结束初始化，不能进行操作！',16,0)
	ELSE
		RAISERROR('出纳系统没有结束初始化，不能进行操作！',16,0)
		
	RETURN -2
END 

IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period ap INNER JOIN Te_Period tp ON tp.FYear = ap.FYear AND tp.FPeriod = ap.FPeriod AND tp.STypeId = @Stypeid WHERE ap.FBegin <=@BusinessDate  AND ap.FEnd >=@BusinessDate)
BEGIN
	RAISERROR('只能做当前期间的对账单！',16,0)
	RETURN -2
END

IF EXISTS (SELECT TOP 1 1 FROM Te_BankStatement WHERE Businessdate = @BusinessDate AND AccountId = @AccountId)
BEGIN
	RAISERROR('该业务日期已经日结，不能做对账单！',16,0)
	RETURN -2
END


IF EXISTS (SELECT TOP 1 1 FROM Te_BankStatement tbs INNER JOIN Te_BankStatementDetail tbsd ON tbsd.BusinessDate = tbs.Businessdate AND TBSD.AccountId = TBS.AccountId WHERE tbsd.Id=@Id)
BEGIN
	RAISERROR('该对账单已经日结，不能修改！',16,0)
	RETURN -2
END

IF @LASTJOURNALDATE <> @BusinessDate AND EXISTS(select TOP 1 1 from sysdata where subname='tejournal' and subvalue=1)
BEGIN
	RAISERROR('所选业务日期的前一天没有做日结,不能做对账单！',16,0)
	RETURN -2
END

IF EXISTS(SELECT TOP 1 1 FROM Te_BankAccount WHERE Id=@AccountId AND IsDestroy=1)
BEGIN
	RAISERROR('所选银行账户已经销户,不能做对账单！',16,0)
	RETURN -2
END

IF @Id = -1  --新增
BEGIN
	INSERT INTO Te_BankStatementDetail(
			BusinessDate
			,SourceId
			,BusinessId
			,TellerName
			,ETypeId
			,Summary
			,FDebit
			,FCredit
			,Cid
			,Rate
			,AccountId
			,FSettleId
			,FSettleNo)
	VALUES( @BusinessDate
			,1
			,@BusinessId
			,@TellerName
			,@ETypeId
			,@Summary
			,@FDebit
			,@FCredit
			,@Cid
			,@RATE
			,@AccountId
			,@FSettleId
			,@FSettleNo
		)

	SELECT @BILLNUMBERID = @@IDENTITY

	EXEC @RES = GP_TeDetailToBalance @BUID=3,@Id=@BILLNUMBERID,@Flag=1,@szPId = @szPId OUT
	IF @RES = -1
	BEGIN
		RAISERROR(@szPId,16,0)
		RETURN @RES
	END
END
ELSE --修改
BEGIN
	IF  EXISTS (SELECT TOP 1 StatementId FROM Te_CheckRelevance  WHERE StatementId = @Id)
	BEGIN
		RAISERROR('该对账单已经勾对，不能修改！',16,0)
		RETURN -2
	END
		
	EXEC @RES = GP_TeDetailToBalance @BUID=3,@Id=@Id,@Flag=-1,@szPId = @szPId OUT
	IF @RES = -1
	BEGIN
		RAISERROR(@szPId,16,0)
		RETURN @RES
	END
	UPDATE Te_BankStatementDetail SET BusinessDate=@BusinessDate
								,BusinessId = @BusinessId
								,TellerName = @TellerName
								,ETypeId = @ETypeId
								,Summary = @Summary
								,FDebit = @FDebit
								,FCredit = @FCredit
								,Cid = @Cid
								,Rate = @RATE
								,AccountId = @AccountId
								,FSettleId = @FSettleId
								,FSettleNo = @FSettleNo
	WHERE Id = @Id
	EXEC @RES = GP_TeDetailToBalance @BUID=3,@Id=@Id,@Flag=1,@szPId = @szPId OUT
	IF @RES = -1
	BEGIN
		RAISERROR(@szPId,16,0)
		RETURN @RES
	END
END	


PRINT @szPId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_TeCheckForImport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_TeCheckForImport]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
-------------------------------------------*/
CREATE PROCEDURE Gp_TeCheckForImport 
(
       @Stypeid 		VARCHAR(50),	
	   @cid				INT,		--币种
	   @type			INT,			--类型  1：现金  2：银行存款 3：银行对账单
	   @chvOperatorID	VARCHAR(50)		---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON

IF EXISTS (select * from stype where deleted=1 AND TypeId=@Stypeid)
BEGIN
	SELECT 1 AS FLAG,'该分支机构已经停用，不能引入数据！' AS MSG
	RETURN
END

IF EXISTS(SELECT * FROM dbo.Te_StartPeriod WHERE STypeId = @Stypeid AND IsUse = 1)
BEGIN
	SELECT 1 AS FLAG,'该分支机构出纳系统已经初始化，不能引入数据！' AS MSG
	RETURN
END

DECLARE @SQL	NVARCHAR(MAX),
		@_StartFYear	INT,
		@_StartFPeriod	INT,
		@_FYear	INT,
		@_FPeriod	INT

SELECT @_FYear = SubValue,@_StartFYear = SubValue FROM sysdata WHERE SubName = 'fyear'
SELECT @_FPeriod = SubValue,@_StartFPeriod = SubValue FROM sysdata WHERE SubName = 'fperiod'

IF @type <> 3 AND NOT EXISTS(SELECT TOP 1 1 from Te_StartPeriod where Stypeid =@Stypeid and (SFYear > @_StartFYear OR (SFYear = @_StartFYear AND SFPeriod >= @_StartFPeriod)))
BEGIN
	SELECT 1 AS FLAG,'总账系统的启用期间＞出纳系统的启用期间，无法从总账系统引入数据！' AS MSG
	RETURN
END 

IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE STypeId = @Stypeid)
BEGIN
	SELECT @_FYear=	FYear,@_FPeriod=FPeriod	FROM Ac_AccountsPeroid_Stype WHERE STypeId = @Stypeid
END

IF @type <> 3 AND NOT EXISTS(SELECT TOP 1 1 from Te_StartPeriod where Stypeid =@Stypeid and (SFYear < @_FYear OR (SFYear = @_FYear AND SFPeriod <= @_FPeriod)))
BEGIN
	SELECT 1 AS FLAG,'总账系统的当前期间＜出纳系统的启用期间，无法从总账系统引入数据！' AS MSG
	RETURN
END 

IF EXISTS(SELECT TOP 1 1 FROM Te_InitDataIndex WHERE Stypeid =@Stypeid AND BUId = @type AND Cid=@cid)
BEGIN
	SELECT 2 AS FLAG,CASE @type WHEN 1 THEN '出纳系统已有现金的期初余额数据，请确认是否用总账数据覆盖？' WHEN 2 THEN '出纳系统已有银行存款的期初余额数据，请确认是否用总账数据覆盖？' ELSE '出纳系统已有银行对账单数据，请确认是否用银行存款数据覆盖？' END AS MSG
	RETURN
END

SELECT 0 AS FLAG,'ok' AS MSG
	 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_TeDetailToBalance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_TeDetailToBalance]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.06.26
	描述：将指定日记账、对账单数据写入/清除余额表
*/
CREATE PROCEDURE GP_TeDetailToBalance
(
	@BUID	INT,				-- 业务类型
	@Id		INT,				-- 数据ID
	@Flag	INT=1,				-- 1.写入 -1.清除
	@szPId	VARCHAR(500) OUTPUT --异常信息
)
--@encode$--
AS
SET NOCOUNT ON

SET @szPId = ''

DECLARE @STypeId	VARCHAR(50),--分支机构
		@AccountId	INT,		--银行账户ID
		@ATypeId	VARCHAR(50),--会计科目
		@FYear		INT,		--年度
		@FPeriod	INT,		--期间
		@cid		INT			--币种
		
--临时数据表
CREATE TABLE #TmpData
(
	AccountId		INT,				
	BUId			INT,				
	ATypeId			VARCHAR(50),		
	STypeId			VARCHAR(50),		
	Cid				INT,				
	FYear			INT,				
	FPeriod			INT,				
	FDebit			 NUMERIC(24, 10) ,		
	FDebitFor		 NUMERIC(24, 10) ,		
	FCredit			 NUMERIC(24, 10) ,		
	FCreditFor		 NUMERIC(24, 10) ,
	FDC				INT			
)

IF @BUID IN (1,2)--现金、银行存款
BEGIN
	SELECT  @STypeId = T1.STypeId,
			@ATypeId = T1.ATypeId,
			@FYear = T2.FYear,
			@FPeriod = T2.FPeriod,
			@cid = T1.Cid,
			@AccountId=T1.AccountId
	FROM dbo.Te_Journal_Detail T1
		LEFT JOIN dbo.Te_Period T2 ON T1.STypeId = T2.STypeId
	WHERE T1.Id = @Id
	
	--未结束初始化
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period WHERE STypeId = @STypeId)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @szPId = '相应分支机构'
		SET @szPId += '出纳管理未结束初始化'
		RETURN -1
	END
	
	--准备数据，原币和综合本位币
	INSERT INTO #TmpData
	        ( AccountId ,
	          BUId ,
	          ATypeId ,
	          STypeId ,
	          Cid ,
	          FYear ,
	          FPeriod ,
	          FDebit ,
	          FDebitFor ,
	          FCredit ,
	          FCreditFor,
	          FDC
	        )
	SELECT	ISNULL(AccountId,0),
			@BUID,
			ATypeId,
			T1.STypeId,
			T1.Cid,
			T2.FYear,
			T2.FPeriod,
			T1.FDebitOri,
			T1.FDebit,
			T1.FCreditOri,
			T1.FCredit,
			T4.Fdc
	FROM dbo.Te_Journal_Detail T1
		INNER JOIN dbo.Te_Period T2 ON T1.STypeId = T2.STypeId
		INNER JOIN dbo.Ac_Currency T3 ON T1.Cid = T3.CId
		INNER JOIN dbo.Ac_Account T4 ON T1.STypeId = T4.StypeId AND T1.ATypeId = T4.TypeId
	WHERE T1.Id = @Id
	
	UNION ALL
	
	SELECT	ISNULL(AccountId,0),
			@BUID,
			ATypeId,
			T1.STypeId,
			0,
			T2.FYear,
			T2.FPeriod,
			T1.FDebitOri,
			T1.FDebitOri,
			T1.FCreditOri,
			T1.FCreditOri,
			T4.Fdc
	FROM dbo.Te_Journal_Detail T1
		INNER JOIN dbo.Te_Period T2 ON T1.STypeId = T2.STypeId
		INNER JOIN dbo.Ac_Account T4 ON T1.STypeId = T4.StypeId AND T1.ATypeId = T4.TypeId
	WHERE T1.Id = @Id
END
ELSE IF @BUID = 3--银行对账单
BEGIN
	SELECT  @STypeId = T2.STypeId,
			@ATypeId = T2.ATypeId,
			@FYear = T3.FYear,
			@FPeriod = T3.FPeriod,
			@cid = T1.Cid,
			@AccountId=T1.AccountId
	FROM dbo.Te_BankStatementDetail T1
		INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
		LEFT JOIN dbo.Te_Period T3 ON T2.STypeId = T3.STypeId
	WHERE T1.Id = @Id
	
	--未结束初始化
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period WHERE STypeId = @STypeId)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @szPId = '相应分支机构'
		SET @szPId += '出纳管理未结束初始化'
		RETURN -1
	END
	
	--准备数据，原币和综合本位币
	INSERT INTO #TmpData
	        ( AccountId ,
	          BUId ,
	          ATypeId ,
	          STypeId ,
	          Cid ,
	          FYear ,
	          FPeriod ,
	          FDebit ,
	          FDebitFor ,
	          FCredit ,
	          FCreditFor,
	          FDC
	        )
	SELECT	ISNULL(AccountId,0),
			@BUID,
			ATypeId,
			T2.STypeId,
			T1.Cid,
			T3.FYear,
			T3.FPeriod,
			dbo.f_roundtotal(CASE WHEN T4.BasisType = 0 THEN FDebit * T1.Rate
				ELSE FDebit / T1.Rate
			END),
			FDebit,
			dbo.f_roundtotal(CASE WHEN BasisType = 0 THEN FCredit * T1.Rate
				ELSE FCredit / T1.Rate
			END),
			FCredit,
			T5.Fdc
	FROM dbo.Te_BankStatementDetail T1
		INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
		INNER JOIN dbo.Te_Period T3 ON T2.STypeId = T3.STypeId
		INNER JOIN dbo.Ac_Currency T4 ON T1.Cid = T4.CId
		INNER JOIN dbo.Ac_Account T5 ON T2.STypeId = T5.StypeId AND T2.ATypeId = T5.TypeId

	WHERE T1.Id = @Id
	
	UNION ALL
	
	SELECT	ISNULL(AccountId,0),
			@BUID,
			ATypeId,
			T2.STypeId,
			0,
			T3.FYear,
			T3.FPeriod,
			dbo.f_roundtotal(CASE WHEN T4.BasisType = 0 THEN FDebit * T1.Rate
				ELSE FDebit / T1.Rate
			END),
			dbo.f_roundtotal(CASE WHEN T4.BasisType = 0 THEN FDebit * T1.Rate
				ELSE FDebit / T1.Rate
			END),
			dbo.f_roundtotal(CASE WHEN BasisType = 0 THEN FCredit * T1.Rate
				ELSE FCredit / T1.Rate
			END),
			dbo.f_roundtotal(CASE WHEN BasisType = 0 THEN FCredit * T1.Rate
				ELSE FCredit / T1.Rate
			END),
			T5.Fdc
	FROM dbo.Te_BankStatementDetail T1
		INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
		INNER JOIN dbo.Te_Period T3 ON T2.STypeId = T3.STypeId
		INNER JOIN dbo.Ac_Currency T4 ON T1.Cid = T4.CId
		INNER JOIN dbo.Ac_Account T5 ON T2.STypeId = T5.StypeId AND T2.ATypeId = T5.TypeId
	WHERE T1.Id = @Id
END

--写入数据
IF @Flag = 1
BEGIN
	--1.无记录的，新增记录
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Balance WHERE BUId = @BUID AND ATypeId = @ATypeId AND STypeId = @STypeId AND FYear = @FYear AND FPeriod = @FPeriod AND cid = @cid AND AccountId=@AccountId)
	BEGIN
		INSERT INTO dbo.Te_Balance
				( AccountId ,
				  BUId ,
				  ATypeId ,
				  STypeId ,
				  InitBalance ,
				  InitBalanceFor ,
				  InitYearBalance ,
				  InitYearBalanceFor ,
				  Cid ,
				  FYear ,
				  FPeriod ,
				  FDebit ,
				  FDebitFor ,
				  FCredit ,
				  FCreditFor ,
				  FEndBalance ,
				  FEndBalanceFor ,
				  FYtdDebit ,
				  FYtdDebitFor ,
				  FYtdCredit ,
				  FYtdCreditFor
				)
		SELECT  AccountId,
				BUId,
				ATypeId,
				STypeId,
				0,
				0,
				0,
				0,
				Cid,
				FYear,
				FPeriod,
				FDebit,
				FDebitFor,
				FCredit,
				FCreditFor,
				CASE WHEN (BUID = 1 AND FDC = 1) OR BUId = 2 THEN FDebit - FCredit ELSE FCredit - FDebit END,
				CASE WHEN (BUID = 1 AND FDC = 1) OR BUId = 2 THEN FDebitFor - FCreditFor ELSE FCreditFor - FDebitFor END,
				FDebit,
				FDebitFor,
				FCredit,
				FCreditFor
		FROM #TmpData
		WHERE Cid = @cid
	END
	ELSE
	BEGIN--2.有记录的更新值
		UPDATE T1
				SET T1.FDebit = T1.FDebit + T2.FDebit,
					T1.FDebitFor = T1.FDebitFor + T2.FDebitFor,
					T1.FCredit = T1.FCredit + T2.FCredit,
					T1.FCreditFor = T1.FCreditFor + T2.FCreditFor,
					T1.FEndBalance = CASE WHEN (T2.BUID = 1 AND FDC = 1) OR T2.BUID = 2 THEN T1.FEndBalance + T2.FDebit - T2.FCredit
											ELSE T1.FEndBalance + T2.FCredit - T2.FDebit
									 END,
					T1.FEndBalanceFor = CASE WHEN (T2.BUID = 1 AND FDC = 1) OR T2.BUID = 2 THEN T1.FEndBalanceFor + T2.FDebitFor - T2.FCreditFor
											ELSE T1.FEndBalanceFor + T2.FCreditFor - T2.FDebitFor
									 END,
					T1.FYtdDebit = T1.FYtdDebit + T2.FDebit,
					T1.FYtdDebitFor = T1.FYtdDebitFor + T2.FDebitFor,
					T1.FYtdCredit = T1.FYtdCredit + T2.FCredit,
					T1.FYtdCreditFor = T1.FYtdCreditFor + T2.FCreditFor
			FROM dbo.Te_Balance T1
				INNER JOIN #TmpData T2 ON T1.STypeId = T2.STypeId 
										AND ISNULL(T1.AccountId,0) = T2.AccountId
										AND T1.ATypeId = T2.ATypeId
										AND T1.BUId = T2.BUId
										AND T1.Cid = T2.Cid
										AND T1.FYear = T2.FYear
										AND T1.FPeriod = T2.FPeriod
			WHERE T1.Cid = @cid
	END
	--没有记录，新增记录 综合本位币
	IF NOT EXISTS (SELECT TOP 1 1 FROM dbo.Te_Balance WHERE BUId = @BUID AND ATypeId = @ATypeId AND STypeId = @STypeId AND FYear = @FYear AND FPeriod = @FPeriod AND cid = 0 AND AccountId=@AccountId)
	BEGIN
		INSERT INTO dbo.Te_Balance
				( AccountId ,
				  BUId ,
				  ATypeId ,
				  STypeId ,
				  InitBalance ,
				  InitBalanceFor ,
				  InitYearBalance ,
				  InitYearBalanceFor ,
				  Cid ,
				  FYear ,
				  FPeriod ,
				  FDebit ,
				  FDebitFor ,
				  FCredit ,
				  FCreditFor ,
				  FEndBalance ,
				  FEndBalanceFor ,
				  FYtdDebit ,
				  FYtdDebitFor ,
				  FYtdCredit ,
				  FYtdCreditFor
				)
		SELECT  AccountId,
				BUId,
				ATypeId,
				STypeId,
				0,
				0,
				0,
				0,
				Cid,
				FYear,
				FPeriod,
				FDebit,
				FDebitFor,
				FCredit,
				FCreditFor,
				CASE WHEN (BUID = 1 AND FDC = 1) OR BUId = 2 THEN FDebit - FCredit ELSE FCredit - FDebit END,
				CASE WHEN (BUID = 1 AND FDC = 1) OR BUId = 2 THEN FDebitFor - FCreditFor ELSE FCreditFor - FDebitFor END,
				FDebit,
				FDebitFor,
				FCredit,
				FCreditFor
		FROM #TmpData
		WHERE Cid = 0
	END
	ELSE--有记录的，更新记录 综合本位币
	BEGIN
		UPDATE T1
			SET T1.FDebit = T1.FDebit + T2.FDebit,
				T1.FDebitFor = T1.FDebitFor + T2.FDebitFor,
				T1.FCredit = T1.FCredit + T2.FCredit,
				T1.FCreditFor = T1.FCreditFor + T2.FCreditFor,
				T1.FEndBalance = CASE WHEN (T2.BUID = 1 AND FDC = 1) OR T2.BUID = 2 THEN T1.FEndBalance + T2.FDebit - T2.FCredit
										ELSE T1.FEndBalance + T2.FCredit - T2.FDebit
								 END,
				T1.FEndBalanceFor = CASE WHEN (T2.BUID = 1 AND FDC = 1) OR T2.BUID = 2 THEN T1.FEndBalanceFor + T2.FDebitFor - T2.FCreditFor
										ELSE T1.FEndBalanceFor + T2.FCreditFor - T2.FDebitFor
								 END,
				T1.FYtdDebit = T1.FYtdDebit + T2.FDebit,
				T1.FYtdDebitFor = T1.FYtdDebitFor + T2.FDebitFor,
				T1.FYtdCredit = T1.FYtdCredit + T2.FCredit,
				T1.FYtdCreditFor = T1.FYtdCreditFor + T2.FCreditFor
		FROM dbo.Te_Balance T1
			INNER JOIN #TmpData T2 ON T1.STypeId = T2.STypeId 
									AND ISNULL(T1.AccountId,0) = T2.AccountId
									AND T1.ATypeId = T2.ATypeId
									AND T1.BUId = T2.BUId
									AND T1.Cid = T2.Cid
									AND T1.FYear = T2.FYear
									AND T1.FPeriod = T2.FPeriod
		WHERE T1.Cid = 0
	END
END
ELSE --删除数据
BEGIN
	UPDATE T1
			SET T1.FDebit = T1.FDebit - T2.FDebit,
				T1.FDebitFor = T1.FDebitFor - T2.FDebitFor,
				T1.FCredit = T1.FCredit - T2.FCredit,
				T1.FCreditFor = T1.FCreditFor - T2.FCreditFor,
				T1.FEndBalance = CASE WHEN (T2.BUID = 1 AND FDC = 1) OR T2.BUID = 2 THEN T1.FEndBalance - T2.FDebit + T2.FCredit
										ELSE T1.FEndBalance - T2.FCredit + T2.FDebit
								 END,
				T1.FEndBalanceFor = CASE WHEN (T2.BUID = 1 AND FDC = 1) OR T2.BUID = 2 THEN T1.FEndBalanceFor - T2.FDebitFor + T2.FCreditFor
										ELSE T1.FEndBalanceFor - T2.FCreditFor + T2.FDebitFor
								 END,
				T1.FYtdDebit = T1.FYtdDebit - T2.FDebit,
				T1.FYtdDebitFor = T1.FYtdDebitFor - T2.FDebitFor,
				T1.FYtdCredit = T1.FYtdCredit - T2.FCredit,
				T1.FYtdCreditFor = T1.FYtdCreditFor - T2.FCreditFor
	FROM dbo.Te_Balance T1
		INNER JOIN #TmpData T2 ON T1.STypeId = T2.STypeId 
								AND ISNULL(T1.AccountId,0) = T2.AccountId
								AND T1.ATypeId = T2.ATypeId
								AND T1.BUId = T2.BUId
								AND T1.Cid = T2.Cid
								AND T1.FYear = T2.FYear
								AND T1.FPeriod = T2.FPeriod
END


DROP TABLE #TmpData

RETURN 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_TeFinishInit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_TeFinishInit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.05.21
	描述：出纳系统结束初始化
*/
CREATE PROCEDURE GP_TeFinishInit
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@STypeId			VARCHAR(MAX),		-- 分支机构
	@Finish				INT = 1				-- 结束初始化 -1.反初始化 1.结束初始化
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN

--分支机构
CREATE TABLE #GetManSTypeId
(
	Id	INT IDENTITY(1,1),
	TypeId	VARCHAR(50),
	sfullname	VARCHAR(100),
	FYear	INT,
	FPeriod	INT,
	StartDate	DATETIME
)

INSERT INTO #GetManSTypeId(TypeId,sfullname,FYear,FPeriod,StartDate)
SELECT T1.TypeId,T2.FullName,T3.SFYear,T3.SFPeriod,DATEADD(day,-1,T4.FBegin)
FROM  F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorId) T1 
	INNER JOIN dbo.SType T2 ON T1.TypeId = T2.TypeId
	LEFT JOIN dbo.Te_StartPeriod T3 ON T1.TypeId = T3.STypeId
	LEFT JOIN dbo.Ac_Period T4 ON T3.SFYear = T4.FYear AND T3.SFPeriod = T4.FPeriod

--异常消息
DECLARE @Msg VARCHAR(MAX)
SET @Msg = ''

IF NOT EXISTS(SELECT TOP 1 1 FROM #GetManSTypeId)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
				SET @msg = '所选分支机构'	
	SET @Msg += '不在权限范围内，无法进行初始化'
	RAISERROR(@Msg,16,1)
	RETURN -1
END


DECLARE @TypeId		VARCHAR(50),
		@SFullName  VARCHAR(100),
		@FYear		INT,
		@FPeriod	INT,
		@StartDate	DATETIME

DECLARE @NowFYear INT,
		@NowFPerid INT

--结束初始化
IF @Finish = 1
BEGIN
	DECLARE STypeCur CURSOR FOR
		SELECT  TypeId,
				sfullname,
				FYear,
				FPeriod
		FROM #GetManSTypeId
	OPEN STypeCur
	FETCH NEXT FROM STypeCur INTO @TypeId,@SFullName,@FYear,@FPeriod
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--判断期间
		IF ISNULL(@FYear,0) = 0 OR ISNULL(@FPeriod,0) = 0
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
				SET @msg = '分支机构['+@sfullname+']'
			
			SET @Msg += '未设置启用期间，无法完成初始化！'
			RAISERROR(@Msg,16,1)
			
			CLOSE STypeCur
			DEALLOCATE STypeCur
			ROLLBACK TRAN
			RETURN
		END
		ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @TypeId AND IsUse = 1)
		BEGIN
			DELETE FROM #GetManSTypeId WHERE  TypeId = @TypeId
		END
		
		FETCH NEXT FROM STypeCur INTO @TypeId,@SFullName,@FYear,@FPeriod
	END
	
	CLOSE STypeCur
	DEALLOCATE STypeCur

	IF NOT EXISTS(SELECT TOP 1 1 FROM #GetManSTypeId)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '所选分支机构全部'
			
		SET @Msg += '已完成初始化，不能重复初始化！'
		RAISERROR(@Msg,16,1)
		
		ROLLBACK TRAN
		RETURN
	END

	--期初数据写临时表
	SELECT  ISNULL(AccountId,0) AS AccountId,
			ISNULL(InitBalanceOri,0) AS InitBalance,
			CASE WHEN BUID = 3 THEN (ISNULL(InitBalanceOri,0) + ISNULL(FDebitOri,0) - ISNULL(FCreditOri,0))
				ELSE
				(ISNULL(InitBalanceOri,0) + ISNULL(FCreditOri,0) - ISNULL(FDebitOri,0)) 
			END AS InitYearBalance,
			T1.Cid,
			FYear,
			FPeriod,
			ISNULL(FDebitOri,0) AS FDebitOri,
			ISNULL(FCreditOri,0) AS FCreditOri,
			ISNULL(InitBalanceOri,0) AS FEndBalance,
			0 AS FYtdDebit,
			0 AS FYtdCredit,
			BUId,
			AtypeId,
			STypeId,
			ISNULL(T2.InitBalance,0) AS InitBalanceFor,
			CASE WHEN BUID = 3 THEN (ISNULL(InitBalance,0) + ISNULL(FDebit,0) - ISNULL(FCredit,0))
				ELSE (ISNULL(InitBalance,0) + ISNULL(FCredit,0) - ISNULL(FDebit,0)) 
			END AS  InitYearBalanceFor,
			ISNULL(FDebit,0) AS FDebitFor,
			ISNULL(FCredit,0) AS FCreditFor,
			ISNULL(T2.InitBalance,0) AS FEndBalanceFor,
			0 AS FYtdDebitFor,
			0 AS FYtdCreditFor,
			StartDate,
			T1.Rate
	INTO #TmpInitData
	FROM dbo.Te_InitDataIndex T1
		INNER JOIN dbo.Te_InitDataDetail T2 ON T1.Id = T2.IndexId
		INNER JOIN #GetManSTypeId T3 ON T1.STypeId = T3.TypeId
		INNER JOIN dbo.Ac_Currency T4 ON T1.Cid = T4.CId
	WHERE T2.FDebit <> 0 OR T2.FCredit <> 0 OR T2.InitBalance <> 0
	
	--0.写日记账、银行对账单
	--①日记账
	INSERT INTO dbo.Te_Journal_Detail
	        ( BusinessDate ,
	          SourceId ,
	          VoucherId ,
	          ETypeId ,
	          Summary ,
	          FDebit ,
	          FCredit ,
	          FEndBalance ,
	          AccountId ,
	          IsCash ,
	          FDC ,
	          STypeId ,
	          ATypeId ,
	          FSettleId ,
	          FSettleNo ,
	          Cid ,
	          Rate,
	          IsInit,
	          FDebitOri,
	          FCreditOri,
	          FEndBalanceOri
	        )
	SELECT  StartDate,
			0,
			0,
			@OperatorId,
			'期初数据',
			0,
			0,
			InitBalanceFor,
			AccountId,
			CASE WHEN BUId = 1 THEN 1 ELSE 0 END AS IsCash,
			T2.FDC,
			T1.STypeId,
			AtypeId,
			0,
			'',
			T1.Cid,
			T1.Rate,
			1,
			0,
			0,
			FEndBalance
	FROM #TmpInitData T1
		INNER JOIN dbo.Ac_Account T2 ON T1.STypeId = T2.StypeId AND T1.AtypeId = T2.TypeId
	WHERE T1.BUId IN (1,2)
	
	--②对账单
	INSERT INTO dbo.Te_BankStatementDetail
	        ( Businessdate ,
	          BusinessId ,
	          TellerName ,
	          FSettleId ,
	          FSettleNo ,
	          ETypeId ,
	          Summary ,
	          FDebit ,
	          FCredit ,
	          FEndBalance ,
	          SourceId ,
	          AccountId ,
	          FDC ,
	          Cid ,
	          Rate,
	          IsInit
	        )
	SELECT  StartDate,
			'',
			'',
			0,
			'',
			@OperatorId,
			'期初数据',
			0,
			0,
			InitBalanceFor,
			0,
			AccountId,
			T2.FDC,
			T1.Cid,
			T1.Rate,
			1
	FROM #TmpInitData T1
		INNER JOIN dbo.Ac_Account T2 ON T1.STypeId = T2.StypeId AND T1.AtypeId = T2.TypeId
	WHERE T1.BUId = 3
	
	
	INSERT INTO dbo.Te_Journal
	        ( Businessdate ,
	          YesterdayFBalance ,
	          FDebitTotal ,
	          FCreditTotal ,
	          FBalance ,
	          AccountId ,
	          IsCash ,
	          STypeId ,
	          ATypeId ,
	          FDC ,
	          Cid
	        )
	SELECT  BusinessDate,
			0 AS YesterdayFBalance,
			0 AS FDebitTotal,
			0 AS FCreditTotal,
			FEndBalance,
			AccountId,
			IsCash,
			STypeId,
			ATypeId,
			FDC,
			Cid
	FROM dbo.Te_Journal_Detail T1
		INNER JOIN #GetManSTypeId T2 ON T1.STypeId = T2.typeid
	WHERE IsInit = 1
	
	UNION ALL
	
	SELECT  BusinessDate,
			0 AS YesterdayFBalance,
			0 AS FDebitTotal,
			0 AS FCreditTotal,
			FEndBalanceOri,
			AccountId,
			IsCash,
			STypeId,
			ATypeId,
			FDC,
			0
	FROM dbo.Te_Journal_Detail T1
		INNER JOIN #GetManSTypeId T2 ON T1.STypeId = T2.typeid
	WHERE IsInit = 1
	
	INSERT INTO dbo.Te_BankStatement
	        ( Businessdate ,
	          YesterdayFBalance ,
	          FDebitTotal ,
	          FCreditTotal ,
	          FBalance ,
	          AccountId ,
	          Cid ,
	          FDC
	        )
	SELECT  Businessdate,
			0 AS YesterdayFBalance,
			0 AS FDebitTotal,
			0 AS FCreditTotal,
			FEndBalance,
			AccountId,
			T1.Cid,
			FDC
	FROM dbo.Te_BankStatementDetail T1
		INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
		INNER JOIN #GetManSTypeId T3 ON T2.STypeId = T3.typeid
	WHERE IsInit = 1
	
	UNION ALL
	
	SELECT  Businessdate,
			0 AS YesterdayFBalance,
			0 AS FDebitTotal,
			0 AS FCreditTotal,
			dbo.f_roundtotal(CASE WHEN T2.BasisType = 0 THEN FEndBalance * T1.rate
				ELSE FEndBalance / T1.rate
			END) AS FEndBalance,
			AccountId,
			0 AS cid,
			FDC
	FROM dbo.Te_BankStatementDetail T1
		INNER JOIN dbo.Ac_Currency T2 ON T1.Cid = T2.CId
		INNER JOIN dbo.Te_BankAccount T3 ON T1.AccountId = T3.Id
		INNER JOIN #GetManSTypeId T4 ON T3.STypeId = T4.typeid
	WHERE IsInit = 1
	
	--1.数据结转
	DECLARE STypeCur2 CURSOR FOR
	SELECT  TypeId,
			sfullname,
			FYear,
			FPeriod
	FROM #GetManSTypeId
	OPEN STypeCur2
	FETCH NEXT FROM STypeCur2 INTO @TypeId,@SFullName,@FYear,@FPeriod
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC dbo.Gp_CalculateTeBalance @TypeId,@FYear,@FPeriod
		
		FETCH NEXT FROM STypeCur2 INTO @TypeId,@SFullName,@FYear,@FPeriod
	END
	
	CLOSE STypeCur2
	DEALLOCATE STypeCur2
	
	
	--2.标识初始数据不可变更
	UPDATE dbo.Te_InitDataIndex SET Finish = 1
		WHERE STypeId IN (SELECT TypeId FROM #GetManSTypeId) 
		
	--3.写出纳期间表为启用期间
	INSERT INTO dbo.Te_Period
	        ( STypeId, FYear, FPeriod )
	SELECT STypeId,SFYear,SFPeriod
	FROM dbo.Te_StartPeriod T1
		INNER JOIN #GetManSTypeId T2 ON T1.STypeId = T2.TypeId
	--4.启用分支出纳系统
	UPDATE dbo.Te_StartPeriod SET IsUse = 1
		WHERE STypeId IN (SELECT TypeId FROM #GetManSTypeId)
	
	DROP TABLE #TmpInitData
END
ELSE--反初始化
BEGIN
	DECLARE @FBegin DATETIME,
			@FEnd	DATETIME

	DECLARE STypeCur CURSOR FOR
		SELECT  TypeId,
				sfullname,
				FYear,
				FPeriod,
				Startdate
		FROM #GetManSTypeId
	OPEN STypeCur
	FETCH NEXT FROM STypeCur INTO @TypeId,@SFullName,@FYear,@FPeriod,@StartDate
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--期间时间范围
		SELECT @FBegin = FBegin,@FEnd = FEnd FROM dbo.Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod
	
		--判断是否未初始化
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @TypeId AND IsUse = 0)
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
				SET @msg = '分支机构['+@sfullname+']'
			
			SET @Msg += '未初始化，无需反初始化'
			RAISERROR(@Msg,16,1)
			
			CLOSE STypeCur
			DEALLOCATE STypeCur
			ROLLBACK TRAN
			RETURN
		END
		ELSE
		BEGIN
			--当前期间
			SELECT @NowFYear = FYear,@NowFPerid = FPeriod FROM dbo.Te_Period WHERE STypeId = @TypeId
			--当前期间为启用期间时才能反初始化
			IF @NowFYear <> @FYear OR @NowFPerid <> @FPeriod
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
					SET @msg = '分支机构['+@sfullname+']'
				
				SET @Msg += '当前不是启用期间，无法反初始化'
				RAISERROR(@Msg,16,1)
				
				CLOSE STypeCur
				DEALLOCATE STypeCur
				ROLLBACK TRAN
				RETURN
			END
			ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @TypeId AND IsConnect = 1)
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
					SET @msg = '分支机构['+@sfullname+']'
				
				SET @Msg += '无法反初始化，请先取消与总账联用'
				RAISERROR(@Msg,16,1)
				
				CLOSE STypeCur
				DEALLOCATE STypeCur
				ROLLBACK TRAN
				RETURN
			END
			ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal_Detail WHERE BusinessDate >=@FBegin AND BusinessDate <=@FEnd AND STypeId = @typeid)
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
					SET @msg = '分支机构['+@sfullname+']'
				
				SET @Msg += '无法反初始化，请先删除当期日记账数据'
				RAISERROR(@Msg,16,1)
				
				CLOSE STypeCur
				DEALLOCATE STypeCur
				ROLLBACK TRAN
				RETURN
			END
			ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_BankStatementDetail WHERE BusinessDate >= @FBegin AND BusinessDate <= @FEnd 
							AND AccountId IN (SELECT Id FROM dbo.Te_BankAccount WHERE STypeId = @Typeid AND IsDestroy = 0))
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
					SET @msg = '分支机构['+@sfullname+']'
				
				SET @Msg += '无法反初始化，请先删除当期银行对账单数据'
				RAISERROR(@Msg,16,1)
				
				CLOSE STypeCur
				DEALLOCATE STypeCur
				ROLLBACK TRAN
				RETURN
			END
			ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_AccountInTransit_Detail T1
							INNER JOIN dbo.Te_AccountInTransit_Index T2 ON T1.Id = T2.Id
							INNER JOIN dbo.Te_BankAccount T3 ON T2.AccountId = T3.Id AND T3.IsDestroy = 0
						WHERE T2.IsInit =0 AND T3.STypeId = @Typeid)
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
					SET @msg = '分支机构['+@sfullname+']'
				
				SET @Msg += '无法反初始化，请先删除未达账数据'
				RAISERROR(@Msg,16,1)
				
				CLOSE STypeCur
				DEALLOCATE STypeCur
				ROLLBACK TRAN
				RETURN
			END
			ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillType = 310 AND ifcheck='t' AND RedWord = 0 AND (Stypeid = @Typeid OR StypeID2 = @Typeid)
				AND BillDate >= @FBegin AND BillDate <= @FEnd)
			BEGIN
				RAISERROR('当期存在已过账资金调拨单数据，无法反月结',16,1)
				CLOSE STypeCur
				DEALLOCATE STypeCur
				ROLLBACK TRAN
				RETURN
			END
	
			ELSE--反初始化
			BEGIN
				--1.删除数据
				DELETE FROM dbo.Te_Journal_Detail WHERE STypeId=@TypeId
				DELETE FROM dbo.Te_BankStatementDetail WHERE AccountId IN (SELECT Id FROM dbo.Te_BankAccount WHERE STypeId = @Typeid)
				DELETE FROM dbo.Te_Journal WHERE STypeId = @Typeid
				DELETE FROM dbo.Te_BankStatement WHERE AccountId IN (SELECT Id FROM dbo.Te_BankAccount WHERE STypeId = @Typeid)
				DELETE FROM dbo.Te_Balance WHERE STypeId = @Typeid
				
				--2.调整标识
				UPDATE dbo.Te_InitDataIndex SET Finish = 0 WHERE STypeId = @TypeId
				--3.删除期间标识
				DELETE FROM dbo.Te_Period WHERE STypeId = @TypeId
				--4.停用分支出纳系统
				UPDATE dbo.Te_StartPeriod SET IsUse = 0 WHERE STypeId = @TypeId
			END
		END
		
		FETCH NEXT FROM STypeCur INTO @TypeId,@SFullName,@FYear,@FPeriod,@StartDate
	END
	
	CLOSE STypeCur
	DEALLOCATE STypeCur
END

DROP TABLE #GetManSTypeId

COMMIT TRAN

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_TeIniImportData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_TeIniImportData]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
-------------------------------------------*/
CREATE PROCEDURE Gp_TeIniImportData 
(
       @Stypeid 		VARCHAR(50),	
	   @cid				INT,		--币种
	   @type			INT,			--类型  1：现金  2：银行存款 3：银行对账单
	   @chvOperatorID	VARCHAR(50)		---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON

IF EXISTS (select * from stype where deleted=1 AND TypeId=@Stypeid)
BEGIN
	RETURN -3 --该分支机构已经停用，不能引入数据！
END

IF EXISTS(SELECT * FROM dbo.Te_StartPeriod WHERE STypeId = @Stypeid AND IsUse = 1)
BEGIN
	RETURN -2   --该分支机构出纳系统已经初始化，不能引入数据！
END

CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200),UserCode VARCHAR(200),CID INT,IsCash INT)
INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName,UserCode,CID,IsCash) 
SELECT	L.Typeid,L.Stypeid,A.FullName,A.UserCode,A.Cid,A.IsCash 
FROM	F_LineAccount(@chvOperatorID,'') L
INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
WHERE L.Stypeid=@stypeid AND A.Deleted<>'1' 

--写入空数据
INSERT INTO #Ac_Account_L(TypeId,StypeId,FullName,UserCode)VALUES
('',@stypeid,'','')


DECLARE @rate  NUMERIC(24, 10) 
SELECT @rate=Rate FROM AC_CURRENCY WHERE CId=@cid

DECLARE @INDEXID INT,
		@_FYear	INT,
		@_FPeriod	INT

SELECT @_FYear=	SFYear,@_FPeriod=SFPeriod	FROM Te_StartPeriod WHERE STypeId = @Stypeid

--总账科目数据
CREATE TABLE #Ac_Balance
(
	STypeId		VARCHAR(50),
	ATypeId		VARCHAR(50),
	Cid			INT,
	FYear		INT,
	FPeriod		INT,
	FDebit		NUMERIC(24,10) DEFAULT(0),
	FDebitFor	NUMERIC(24,10) DEFAULT(0),
	FCredit		NUMERIC(24,10) DEFAULT(0),
	FCreditFor	NUMERIC(24,10) DEFAULT(0),
	FYtdDebit	NUMERIC(24,10) DEFAULT(0),
	FYtdDebitFor NUMERIC(24,10) DEFAULT(0),
	FYtdCredit	NUMERIC(24,10) DEFAULT(0),
	FYtdCreditFor NUMERIC(24,10) DEFAULT(0),
	FBeginBalance NUMERIC(24,10) DEFAULT(0),
	FBeginBalanceFor NUMERIC(24,10) DEFAULT(0),
)	
IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE STypeId = @Stypeid)
	BEGIN
		INSERT INTO #Ac_Balance
		(
			STypeId
			,ATypeId
			,Cid
			,FYear
			,FPeriod
			,FYtdDebit
			,FYtdDebitFor
			,FYtdCredit
			,FYtdCreditFor
			,FBeginBalance
			,FBeginBalanceFor
		)
		SELECT
			STypeId
			,ATypeId
			,Cid
			,FYear
			,FPeriod
			,FYtdDebit
			,FYtdDebitFor
			,FYtdCredit
			,FYtdCreditFor
			,FBeginBalance
			,FBeginBalanceFor
		FROM Ac_Balance
		WHERE STypeId=@Stypeid
	END
ELSE
	BEGIN
		INSERT #Ac_Balance
		(
			STypeId
			,ATypeId
			,Cid
			,FYear
			,FPeriod
			,FYtdDebit
			,FYtdDebitFor
			,FYtdCredit
			,FYtdCreditFor
			,FBeginBalance
			,FBeginBalanceFor
		)
		SELECT	
			STypeId
			,ATypeId
			,Cid
			,FYear
			,FPeriod
			,FDebit
			,FDebitFor
			,FCredit
			,FCreditFor
			,iniTotal
			,iniTotalFor
		FROM Ac_IniAccount
		WHERE STypeId=@Stypeid
	END

IF EXISTS(SELECT * FROM Te_InitDataIndex WHERE STypeId=@stypeid AND BUId=@type AND Cid=@cid)
	BEGIN
		SELECT @INDEXID=ID FROM Te_InitDataIndex WHERE STypeId=@stypeid AND BUId=@type AND Cid=@cid

		UPDATE Te_InitDataIndex
		SET Rate=@rate
		WHERE ID=@INDEXID
		
		DELETE FROM Te_InitDataDetail WHERE IndexId = @INDEXID
	END
ELSE
	BEGIN
		INSERT INTO Te_InitDataIndex
		(
			STypeId,
			BUId,
			Cid,
			Finish,
			Rate
		)
		VALUES
		(
			@stypeid,
			@type,
			@cid,
			'0',
			@rate
		)

		IF @@ROWCOUNT=0
			RETURN -1
		ELSE 
			SET @INDEXID = @@IDENTITY
	END	
--备注一个，出纳期初表中，带Ori的是本位币，不带Ori的才是原币
IF @type = 1
BEGIN	
	INSERT INTO Te_InitDataDetail(IndexId,AtypeId,FDebitOri,FCreditOri,InitBalanceOri,FDebit,FCredit,InitBalance)
	SELECT	
		@INDEXID
		,B.ATypeId
		,ISNULL(B.FYtdDebit,0)-ISNULL(B.FDebit,0)
		,ISNULL(B.FYtdCredit,0)-ISNULL(B.FCredit,0)
		,ISNULL(B.FBeginBalance,0)
		,ISNULL(B.FYtdDebitFor,0)-ISNULL(B.FDebitFor,0)
		,ISNULL(B.FYtdCreditFor,0)-ISNULL(B.FCreditFor,0)
		,ISNULL(B.FBeginBalanceFor,0)
	FROM #Ac_Account_L A
	INNER JOIN F_GetStandard_Ac_Account(@chvOperatorID) L ON A.TypeId=L.TypeId AND L.STypeId=@stypeid
	LEFT JOIN #Ac_Balance B ON B.STypeId = A.StypeId AND B.ATypeId = A.TypeId AND B.Cid = @cid AND B.FYear = @_FYear AND B.FPeriod = @_FPeriod
	WHERE	
		A.IsCash=1 
		AND A.StypeId=@stypeid 
END
ELSE IF @type = 2
	BEGIN
		INSERT INTO Te_InitDataDetail(IndexId,AtypeId,FDebitOri,FCreditOri,InitBalanceOri,AccountId,FDebit,FCredit,InitBalance)
		SELECT	
			@INDEXID
			,B.ATypeId
			,ISNULL(B.FYtdDebit,0)-ISNULL(B.FDebit,0)
			,ISNULL(B.FYtdCredit,0)-ISNULL(B.FCredit,0)
			,ISNULL(B.FBeginBalance,0)
			,tb.Id
			,ISNULL(B.FYtdDebitFor,0)-ISNULL(B.FDebitFor,0)
			,ISNULL(B.FYtdCreditFor,0)-ISNULL(B.FCreditFor,0)
			,ISNULL(B.FBeginBalanceFor,0)
		FROM Te_BankAccount TB
		INNER JOIN F_LineBank(@chvOperatorID) LB ON LB.TypeId=TB.Id
		LEFT JOIN #Ac_Account_L A ON TB.ATypeId=A.TypeId AND A.StypeId=@stypeid AND A.IsCash=0 
		LEFT JOIN #Ac_Balance B ON B.STypeId = A.StypeId AND B.ATypeId = A.TypeId AND B.Cid = @cid AND B.FYear = @_FYear AND B.FPeriod = @_FPeriod
		WHERE 
			TB.STypeId=@stypeid  
			AND TB.IsDestroy=0 --AND a.SonNum=0
	END
ELSE
	BEGIN
		INSERT INTO Te_InitDataDetail(IndexId,AtypeId,FDebitOri,FCreditOri,InitBalanceOri,AccountId,FDebit,FCredit,InitBalance)
		SELECT	
			@INDEXID
			,A.ATypeId
			,ISNULL(A.FCreditOri,0)
			,ISNULL(A.FDebitOri,0)
			,ISNULL(A.InitBalanceOri,0)
			,A.AccountId
			,ISNULL(A.FCredit,0)
			,ISNULL(A.FDebit,0)
			,ISNULL(A.InitBalance,0)
		FROM Te_InitDataDetail A
		INNER JOIN	Te_InitDataIndex B ON B.Id = A.IndexId
		WHERE	
			B.BUId = 2 
			AND B.Cid = @cid
			AND B.StypeId=@stypeid 
	END

DELETE FROM Te_InitDataDetail WHERE FCredit=0 AND FDebit=0 AND InitBalance=0

IF NOT EXISTS(SELECT *FROM Te_InitDataDetail WHERE IndexId=@indexid)
	DELETE Te_InitDataIndex WHERE Id=@indexid

DROP TABLE #Ac_Account_L,#Ac_Balance

RETURN @_FPeriod
	 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_TEJournalAddOrModify]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_TEJournalAddOrModify]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：李灏龙	
	日期：2014年6月26日 10:58:15
	描述：日记账的新增、修改
*/
CREATE PROCEDURE GP_TEJournalAddOrModify
(
	@Id				INT,
	@BusinessDate	DATE,
	@VoucherId		INT,
	@ETypeId		VARCHAR(50),
	@Summary		VARCHAR(1000),
	@FDebit			 NUMERIC(24, 10) ,
	@FCredit		 NUMERIC(24, 10) ,
	@IsCash			INT,
	@STypeId		VARCHAR(50),
	@Cid			INT,
	@ATypeId		VARCHAR(50),
	@AccountId		INT,
	@FSettleId		INT,
	@FSettleNo		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@RATE			 NUMERIC(24, 10) ,
		@BasisType		INT,
		@BILLNUMBERID	INT,
		@szPId	NVARCHAR(500),
		@FDebitOri			 NUMERIC(24, 10) ,
		@FCreditOri		 NUMERIC(24, 10) ,
		@RES	INT,
		@FDC	INT,
		@LASTJOURNALDATE	DATE,
		@BILLDATE		DATE,
		@BILLTYPE		INT,
		@TPeriod INT,
		@VoucherPeriod INT

IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND deleted=1)
	BEGIN
		RAISERROR('分支机构已被停用，不能进行操作！',16,0)
		RETURN -2
	END
IF EXISTS (SELECT TOP 1 1 FROM Te_Journal WHERE STypeId=@STypeId)
	SELECT TOP 1 @LASTJOURNALDATE=DATEADD(DAY,1,Businessdate) FROM Te_Journal WHERE STypeId = @STypeId ORDER BY Businessdate DESC
ELSE
	SELECT TOP 1 @LASTJOURNALDATE=FBegin	FROM  Ac_Period ap INNER JOIN Te_Period tp ON tp.FYear = ap.FYear AND tp.FPeriod = ap.FPeriod AND tp.STypeId = @Stypeid 

IF NOT EXISTS(SELECT TOP 1 1 FROM Te_StartPeriod tsp WHERE TSP.STypeId = @stypeid AND IsUse = 1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE subname='proinfo' AND SubValue = 2)
		RAISERROR('当前日记账所属的分支机构的出纳系统没有结束初始化，不能进行操作！',16,0)
	ELSE
		RAISERROR('出纳系统没有结束初始化，不能进行操作！',16,0)
		
	RETURN -2
END 

		
SELECT @Rate = Rate,@BasisType = BasisType FROM Ac_Currency WHERE CId = @Cid
SET @RES = 0

SELECT TOP 1 @FDC = Fdc  FROM Ac_Account WHERE TypeId = @ATypeId AND StypeId = @STypeId

SET @FDebit = ISNULL(@FDebit,0)
SET @FCredit = ISNULL(@FCredit,0)

IF ISNULL(@VoucherId,0) > 0
BEGIN
	SELECT @FDebitOri = FDebitTotal,@FCreditOri=FCreditTotal   FROM Ac_Voucher_Bill WHERE ID=@VoucherId
	SELECT	@BILLDATE = B.BillDate,@BILLTYPE=B.BillType	FROM Ac_GoodsBill_VoucherBill AGV
	INNER JOIN Ac_Voucher_Bill AVB ON AVB.BillNumberId = AGV.VourchBillId AND AVB.ID = @VoucherId
	INNER JOIN BillIndex B ON B.BillNumberId = AGV.GoodsBillId
	
	SET @BILLTYPE = ISNULL(@BILLTYPE,0)
END
ELSE IF @BasisType=1
BEGIN
	SET @FDebitOri =dbo.f_roundtotal(@FDebit/@RATE)
	SET @FCreditOri = dbo.f_roundtotal(@FCredit/@RATE)
END
ELSE
BEGIN
	SET @FDebitOri = dbo.f_roundtotal(@FDebit*@RATE)
	SET @FCreditOri = dbo.f_roundtotal(@FCredit*@RATE)
END


SELECT @TPeriod=ISNULL(FPeriod,0)   FROM Te_Period WHERE STypeId = @STypeId
SELECT @VoucherPeriod=ISNULL(AV.FPeriod,0)   FROM Ac_Voucher AV INNER JOIN Ac_Voucher_Bill AVB ON AVB.BillNumberId = AV.BillNumberId AND AVB.ID = @VoucherId


IF @BILLTYPE = 310
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period ap INNER JOIN Te_Period tp ON tp.FYear = ap.FYear AND tp.FPeriod = ap.FPeriod AND tp.STypeId = @Stypeid WHERE ap.FBegin <=@BILLDATE  AND ap.FEnd >=@BILLDATE)
	BEGIN
		RAISERROR('只能做当前期间的日记账！',16,0)
		RETURN -2
	END 
END
ELSE 
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period ap INNER JOIN Te_Period tp ON tp.FYear = ap.FYear AND tp.FPeriod = ap.FPeriod AND tp.STypeId = @Stypeid WHERE ap.FBegin <=@BusinessDate  AND ap.FEnd >=@BusinessDate)
	BEGIN
		RAISERROR('只能做当前期间的日记账！',16,0)
		RETURN -2
	END
	
	IF @TPeriod <> @VoucherPeriod
	BEGIN
		RAISERROR('只能选择期间与出纳系统同一期间的凭证！',16,0)
		RETURN -2
	END 
END


IF EXISTS (SELECT TOP 1 1 FROM Te_Journal WHERE Businessdate = @BusinessDate AND STypeId = @STypeId)
BEGIN
	RAISERROR('该业务日期已经日结，不能做日记账！',16,0)
	RETURN -2
END


IF EXISTS (SELECT TOP 1 1 FROM Te_Journal tj INNER JOIN Te_Journal_Detail tjd ON tjd.BusinessDate = tj.Businessdate AND TJD.STypeId = TJ.STypeId AND TJD.ATypeId = TJ.ATypeId AND TJD.AccountId = TJ.AccountId WHERE tjd.Id=@Id)
BEGIN
	RAISERROR('该日记账已经日结，不能修改！',16,0)
	RETURN -2
END

IF @LASTJOURNALDATE <> @BusinessDate AND EXISTS(select TOP 1 1 from sysdata where subname='tejournal' and subvalue=1)
BEGIN
	RAISERROR('所选业务日期的前一天没有做日结,不能做日记账！',16,0)
	RETURN -2
END

IF @IsCash = 0   --银行日记账
BEGIN

	IF EXISTS(SELECT TOP 1 1 FROM Te_BankAccount WHERE Id=@AccountId AND IsDestroy=1)
	BEGIN
		RAISERROR('所选银行账户已经销户,不能做日记账！',16,0)
		RETURN -2
	END
	
	IF @Id = -1  --新增
	BEGIN
	
		IF ISNULL(@VoucherId,0) > 0 AND 
			(
				NOT EXISTS (SELECT TOP 1 1 FROM Ac_Voucher av INNER JOIN Ac_Voucher_Bill avb ON avb.BillNumberId = av.BillNumberId WHERE avb.ID = @VoucherId AND av.IfCheck = 't')
				OR EXISTS (SELECT TOP 1 1 FROM Te_Journal_Detail WHERE VoucherId = @VoucherId)
			)
		BEGIN
			RAISERROR('所选择的凭证未记账或是已被使用，请重新选择！',16,0)
			RETURN -2
		END
		
		INSERT INTO Te_Journal_Detail(
				BusinessDate
				,SourceId
				,VoucherId
				,ETypeId
				,Summary
				,FDebit
				,FCredit
				,FDebitOri
				,FCreditOri
				,IsCash
				,STypeId
				,Cid
				,Rate
				,ATypeId
				,AccountId
				,FSettleId
				,FSettleNo
				,FDC
				)
		VALUES( @BusinessDate
				,CASE WHEN ISNULL(@VoucherId,0) > 0 THEN 2 ELSE 1 END
				,@VoucherId
				,@ETypeId
				,@Summary
				,@FDebit
				,@FCredit
				,@FDebitOri
				,@FCreditOri
				,@IsCash
				,@STypeId
				,@Cid
				,@RATE
				,@ATypeId
				,@AccountId
				,@FSettleId
				,@FSettleNo
				,@FDC
			)

		SELECT @BILLNUMBERID = @@IDENTITY

		EXEC @RES = GP_TeDetailToBalance @BUID=2,@Id=@BILLNUMBERID,@Flag=1,@szPId = @szPId OUT
		IF @RES = -1
		BEGIN
			RAISERROR(@szPId,16,0)
			RETURN @RES
		END
	END
	ELSE --修改
	BEGIN
		IF EXISTS (SELECT TOP 1 JournalId FROM Te_CheckRelevance WHERE JournalId = @Id)
		BEGIN
			RAISERROR('该银行日记账已经勾对，不能修改！',16,0)
			RETURN -2
		END
	
		IF ISNULL(@VoucherId,0) > 0 AND 
			(
				NOT EXISTS (SELECT TOP 1 1 FROM Ac_Voucher av INNER JOIN Ac_Voucher_Bill avb ON avb.BillNumberId = av.BillNumberId WHERE avb.ID = @VoucherId AND av.IfCheck = 't')
				OR EXISTS (SELECT TOP 1 1 FROM Te_Journal_Detail WHERE VoucherId = @VoucherId AND Id!=@Id)
			)
		BEGIN
			RAISERROR('所选择的凭证未记账或是已被使用，请重新选择！',16,0)
			RETURN -2
		END
	
		EXEC @RES = GP_TeDetailToBalance @BUID=2,@Id=@Id,@Flag=-1,@szPId = @szPId OUT
		IF @RES = -1
		BEGIN
			RAISERROR(@szPId,16,0)
			RETURN @RES
		END
		UPDATE Te_Journal_Detail SET BusinessDate=@BusinessDate
									,VoucherId = @VoucherId
									,SourceId = CASE WHEN ISNULL(@VoucherId,0) > 0 THEN 2 ELSE 1 END
									,ETypeId = @ETypeId
									,Summary = @Summary
									,FDebit = @FDebit
									,FCredit = @FCredit
									,FDebitOri = @FDebitOri
									,FCreditOri =@FCreditOri
									,Cid = @Cid
									,Rate = @RATE
									,ATypeId = @ATypeId
									,AccountId = @AccountId
									,FSettleId = @FSettleId
									,FSettleNo = @FSettleNo
									,FDC=@FDC
		WHERE Id = @Id
		EXEC @RES = GP_TeDetailToBalance @BUID=2,@Id=@Id,@Flag=1,@szPId = @szPId OUT
		IF @RES = -1
		BEGIN
			RAISERROR(@szPId,16,0)
			RETURN @RES
		END
	END	
END
ELSE --现金日记账
BEGIN
	IF @Id = -1  --新增
	BEGIN
	
		IF ISNULL(@VoucherId,0) > 0 AND 
			(
				NOT EXISTS (SELECT TOP 1 1 FROM Ac_Voucher av INNER JOIN Ac_Voucher_Bill avb ON avb.BillNumberId = av.BillNumberId WHERE avb.ID = @VoucherId AND av.IfCheck = 't')
				OR EXISTS (SELECT TOP 1 1 FROM Te_Journal_Detail WHERE VoucherId = @VoucherId)
			)
		BEGIN
			RAISERROR('所选择的凭证未记账或是已被使用，请重新选择！',16,0)
			RETURN -2
		END
	
		INSERT INTO Te_Journal_Detail(
				BusinessDate
				,SourceId
				,VoucherId
				,ETypeId
				,Summary
				,FDebit
				,FCredit
				,FDebitOri
				,FCreditOri
				,IsCash
				,STypeId
				,Cid
				,Rate
				,ATypeId
				,FDC
				,AccountId
				)
		VALUES( 
				@BusinessDate
				,CASE WHEN ISNULL(@VoucherId,0) > 0 THEN 2 ELSE 1 END
				,@VoucherId
				,@ETypeId
				,@Summary
				,@FDebit
				,@FCredit
				,@FDebitOri
				,@FCreditOri
				,@IsCash
				,@STypeId
				,@Cid
				,@RATE
				,@ATypeId
				,@FDC
				,0
			)

		SELECT @BILLNUMBERID = @@IDENTITY

		EXEC @RES = GP_TeDetailToBalance @BUID=1,@Id=@BILLNUMBERID,@Flag=1,@szPId = @szPId OUT
		IF @RES = -1
		BEGIN
			RAISERROR(@szPId,16,0)
			RETURN @RES
		END
	END
	ELSE --修改
	BEGIN
	
		IF ISNULL(@VoucherId,0) > 0 AND 
			(
				NOT EXISTS (SELECT TOP 1 1 FROM Ac_Voucher av INNER JOIN Ac_Voucher_Bill avb ON avb.BillNumberId = av.BillNumberId WHERE avb.ID = @VoucherId AND av.IfCheck = 't')
				OR EXISTS (SELECT TOP 1 1 FROM Te_Journal_Detail WHERE VoucherId = @VoucherId AND Id!=@Id)
			)
		BEGIN
			RAISERROR('所选择的凭证未记账或是已被使用，请重新选择！',16,0)
			RETURN -2
		END
		
		EXEC @RES = GP_TeDetailToBalance @BUID=1,@Id=@Id,@Flag=-1,@szPId = @szPId OUT
		IF @RES = -1
		BEGIN
			RAISERROR(@szPId,16,0)
			RETURN @RES
		END
		UPDATE Te_Journal_Detail SET BusinessDate=@BusinessDate
									,VoucherId = @VoucherId
									,SourceId = CASE WHEN ISNULL(@VoucherId,0) > 0 THEN 2 ELSE 1 END
									,ETypeId = @ETypeId
									,Summary = @Summary
									,FDebit = @FDebit
									,FCredit = @FCredit
									,FDebitOri=@FDebitOri
									,FCreditOri=@FCreditOri
									,Cid = @Cid
									,Rate = @RATE
									,ATypeId = @ATypeId
									,FDC = @FDC
									,AccountId = 0
		WHERE Id = @Id
		EXEC @RES = GP_TeDetailToBalance @BUID=1,@Id=@Id,@Flag=1,@szPId = @szPId OUT
		IF @RES = -1
		BEGIN
			RAISERROR(@szPId,16,0)
			RETURN @RES
		END
	END	
END

PRINT @szPId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_TellerDailySettlement]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_TellerDailySettlement]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.04.25
	描述：出纳日结、反日结
*/
CREATE PROCEDURE Gp_TellerDailySettlement
(
	@OperatorId			VARCHAR(50),	-- 当前操作员ID
	@SettlementDay		DATETIME,		-- 日结日期
	@Flag				INT,			-- 0.反日结 1.日结
	@STypeId			VARCHAR(MAX),	-- 分支机构
	@NoTip				INT=0			-- 是否给出异常提示
)
--@encode$--
AS
SET NOCOUNT ON
-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId
(
	Id	INT IDENTITY(1,1),
	TypeId	VARCHAR(100),
	sfullname	VARCHAR(100)
)

INSERT INTO #GetManSTypeId(TypeId,sfullname)
SELECT T1.TypeId,T2.FullName FROM  F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID) T1 INNER JOIN dbo.SType T2 ON T1.TypeId = T2.TypeId


--获取出纳当前期间、当期起始日期、结束日期
DECLARE @FYear INT,@FPeriod INT,@FBeginDate DATE,@FEndDate DATE

--本位币
DECLARE @StandMoney INT
SELECT @StandMoney = CId FROM dbo.Ac_Currency WHERE Sysrow = 1

--循环变量
DECLARE @Index INT,@Total INT,@TypeId VARCHAR(50),@sfullname VARCHAR(100)
SET @Index = 1
SELECT @Total = COUNT(*) FROM #GetManSTypeId

--联用期间
DECLARE @ConnectFYear INT,@ConnectFPeriod INT

--日结日期/反日结日期
DECLARE @Day DATE
SET @Day = CONVERT(VARCHAR(100),@SettlementDay,23)

CREATE TABLE #Temp
(
	CONTENT		VARCHAR(1000)
)

--消息
DECLARE @Msg VARCHAR(1000)
SET @Msg = ''

DECLARE @MaxDay DATETIME,@MiniDay DATETIME,@CurrentDay DATETIME

WHILE @Index <= @Total
BEGIN
	--分支机构
	SELECT @TypeId = TypeId,@sfullname = sfullname FROM #GetManSTypeId WHERE Id = @Index
	
	IF EXISTS (SELECT TOP 1 1 FROM dbo.Te_Period WHERE STypeId = @TypeId)
	BEGIN
		IF @NoTip = 1 AND @Flag = 0
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period WHERE STypeId = @TypeId AND FPeriod > 1)
				SELECT @FYear = T1.FYear,@FPeriod = T1.FPeriod,@FBeginDate = T2.FBegin,@FEndDate = FEnd
				FROM dbo.Te_Period T1
					INNER JOIN dbo.Ac_Period T2 ON (T1.FPeriod - 1) = T2.FPeriod AND T1.FYear = T2.FYear
				WHERE T1.STypeId = @TypeId
			ELSE
				SELECT @FYear = T1.FYear,@FPeriod = T1.FPeriod,@FBeginDate = T2.FBegin,@FEndDate = FEnd
				FROM dbo.Te_Period T1
					INNER JOIN dbo.Ac_Period T2 ON 12 = T2.FPeriod AND (T1.FYear - 1) = T2.FYear
				WHERE T1.STypeId = @TypeId
		END
		ELSE IF (@NoTip = 1 AND @Flag = 1) OR @NoTip = 0
		BEGIN
			SELECT @FYear = T1.FYear,@FPeriod = T1.FPeriod,@FBeginDate = T2.FBegin,@FEndDate = FEnd
			FROM dbo.Te_Period T1
				INNER JOIN dbo.Ac_Period T2 ON T1.FPeriod = T2.FPeriod AND T1.FYear = T2.FYear
			WHERE T1.STypeId = @TypeId
		END
	END
	ELSE
	BEGIN
		IF @NoTip = 0
			RAISERROR('初始化未完成，操作无法继续',16,1)
		RETURN
	END
		
	--反日结
	IF @Flag = 0
	BEGIN
		IF @Day < @FBeginDate
		BEGIN
			IF @NoTip = 0
				RAISERROR('所选日期超出当前期间，请调整日期',16,1)
			RETURN
		END
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal WHERE CONVERT(VARCHAR(100),Businessdate,23) = @Day AND STypeId = @TypeId)
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
				SET @Msg = '分支机构['+@sfullname+']'
			SET @Msg += '未日结到此日期，无需反日结'
			
			IF @NoTip = 0
				RAISERROR(@Msg,16,1)
			RETURN
		END
		
		--如果日结记录中有数据，得到当期日结最晚一天
		--SET @MaxDay = @FEndDate
		SELECT TOP 1 @MaxDay = Businessdate FROM dbo.Te_Journal WHERE STypeId = @STypeId ORDER BY Businessdate DESC
		
		--无可日结的日期
		IF ISNULL(@MaxDay,'') = ''
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
				SET @Msg = '分支机构['+@sfullname+']'
			SET @Msg += '无日结数据，无法反日结'
			
			IF @NoTip = 0	
				RAISERROR(@Msg,16,1)
			RETURN
		END
		
		SET @CurrentDay = @MaxDay
		
		
		WHILE @CurrentDay >= @Day
		BEGIN
			--删除日结数据
			DELETE FROM dbo.Te_Journal 
			WHERE CONVERT(VARCHAR(100),Businessdate,23) = @CurrentDay 
				AND STypeId = @TypeId
			
			DELETE FROM dbo.Te_BankStatement 
			WHERE CONVERT(VARCHAR(100),Businessdate,23) = @CurrentDay 
					AND AccountId IN (SELECT Id FROM dbo.Te_BankAccount WHERE STypeId = @TypeId)
			
			SET @CurrentDay = DATEADD(DAY,-1,@CurrentDay)
		END
	END
	ELSE--日结
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal WHERE CONVERT(VARCHAR(100),Businessdate,23) = @Day AND STypeId = @TypeId)
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
				SET @Msg = '分支机构['+@sfullname+']'
			SET @Msg += '已日结，无法日结'
			
			IF @NoTip = 0
				RAISERROR(@Msg,16,1)
			RETURN
		END
		
		--如果日结记录中有数据，得到当期日结最后一天
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal WHERE STypeId = @TypeId AND Businessdate >= @FBeginDate AND Businessdate <= @FEndDate)
		BEGIN
			SELECT TOP 1 @MiniDay = DATEADD(day,1,Businessdate) FROM dbo.Te_Journal 
			WHERE STypeId = @TypeId 
			ORDER BY Businessdate DESC
		END
		ELSE
		BEGIN
			SET @MiniDay = @FBeginDate
		END
		
		
		--无可日结的日期
		IF ISNULL(@MiniDay,'') = ''
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
				SET @Msg = '分支机构['+@sfullname+']'
			SET @Msg += '无可日结数据，无法日结'
			
			IF @NoTip = 0
				RAISERROR(@Msg,16,1)
			RETURN
		END
		
		SET @CurrentDay = @MiniDay
		
		IF @Day > @FEndDate
		BEGIN
			IF @NoTip = 0
				RAISERROR('所选日期超出当前期间,请调整日期',16,1)
			RETURN
		END
		
		--已结日期超出选择日期	
		IF @CurrentDay > @Day
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
				SET @Msg = '分支机构['+@sfullname+']'
			SET @Msg += '所选日期前都已日结或无数据，请调整日期'
			
			IF @NoTip = 0
				RAISERROR(@Msg,16,1)
			RETURN 
		END
		
		WHILE @CurrentDay <= @Day
		BEGIN
			--联用时，判断是否有凭证未生成日记账
			IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @stypeid AND IsConnect = 1)
				AND EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'tejournal' AND SubValue = 1)
			BEGIN
				SELECT @ConnectFYear = CFYear,@ConnectFPeriod = CFPeriod FROM dbo.Te_StartPeriod WHERE STypeId = @stypeid
				INSERT INTO #Temp( CONTENT )
				SELECT DISTINCT T4.FullName + '----------' + T5.FullName + '-' + CAST(T1.FlowNo AS VARCHAR(100)) AS content
				FROM dbo.Ac_Voucher T1
					INNER JOIN dbo.Ac_Voucher_Bill T2 ON T1.BillNumberId = T2.BillNumberId
					INNER JOIN dbo.Ac_Account T3 ON T2.ATypeId = T3.TypeId AND T1.STypeId = T3.StypeId
					INNER JOIN dbo.SType T4 ON T1.STypeId = T4.TypeId
					INNER JOIN Ac_Voucher_Group T5 ON T1.VgId = T5.VgId
				WHERE (T3.IsBank = 1 OR T3.IsCash = 1)
					AND T2.ID NOT IN (SELECT VoucherId FROM dbo.Te_Journal_Detail WHERE STypeId = @stypeid AND BusinessDate = @CurrentDay)
					AND T1.BillDate = @CurrentDay
					AND T4.TypeId = @TypeId
					AND (T1.FYear = @ConnectFYear AND T1.FPeriod = @ConnectFPeriod OR T1.FYear > @ConnectFYear)
				
				IF EXISTS(SELECT TOP 1 1 FROM #Temp)
				BEGIN
					SELECT '未生成日记账的会计凭证' AS CONTENT
					UNION ALL
					SELECT * FROM #Temp
					BREAK;
				END
			END
		
			------日结 Start ------
			
			----日记账日结----
			--①日记账 所有币种
			INSERT INTO dbo.Te_Journal
				( Businessdate ,
				  YesterdayFBalance ,
				  FDebitTotal ,
				  FCreditTotal ,
				  FBalance ,
				  AccountId ,
				  IsCash ,
				  STypeId ,
				  ATypeId,
				  FDC,
				  Cid
				)
			SELECT	Businessdate,
				SUM(YesterdayBalance) AS YesterdayFBalance,
				SUM(FDebit),
				SUM(FCredit),
				CASE WHEN FDC = 1 THEN
					SUM(YesterdayBalance) + SUM(FDebit) - SUM(FCredit)
				ELSE 
					SUM(YesterdayBalance) + SUM(FCredit) - SUM(FDebit)
				END,
				AccountId,
				CASE WHEN ISNULL(AccountId,'') = '' THEN 1 ELSE 0 END AS IsCash,
				STypeId,
				ATypeId,
				FDC,
				Cid
			FROM
			(
				SELECT @CurrentDay AS BusinessDate,
						0 AS YesterdayBalance,
						FDebit,
						FCredit,
						0 AS FBalance,
						AccountId,
						IsCash,
						STypeId,
						ATypeId,
						FDC,
						Cid
				FROM dbo.Te_Journal_Detail
				WHERE CONVERT(VARCHAR(100),Businessdate,23) = @CurrentDay
					AND STypeId = @TypeId
				
				UNION ALL
				
				SELECT	@CurrentDay AS BusinessDate,
						FBalance AS YesterdayBalance,
						0 AS FDebit,
						0 AS FCredit,
						0 AS FBalance,
						AccountId,
						IsCash,
						STypeId,
						ATypeId,
						FDC,
						Cid
				FROM dbo.Te_Journal T2
				WHERE CONVERT(VARCHAR(100),Businessdate,23) = DATEADD(day,-1,@CurrentDay)
					AND STypeId = @TypeId
					AND Cid <> 0
			)T
			GROUP BY T.BusinessDate,AccountId,STypeId,ATypeId,FDC,T.Cid
			
			--②日记账 综合本位币
			INSERT INTO dbo.Te_Journal
				( Businessdate ,
				  YesterdayFBalance ,
				  FDebitTotal ,
				  FCreditTotal ,
				  FBalance ,
				  AccountId ,
				  IsCash ,
				  STypeId ,
				  ATypeId,
				  FDC,
				  Cid
				)
			SELECT	Businessdate,
				SUM(YesterdayBalance) AS YesterdayFBalance,
				SUM(FDebit),
				SUM(FCredit),
				CASE WHEN FDC = 1 THEN
					SUM(YesterdayBalance) + SUM(FDebit) - SUM(FCredit)
				ELSE 
					SUM(YesterdayBalance) + SUM(FCredit) - SUM(FDebit)
				END,
				AccountId,
				CASE WHEN ISNULL(AccountId,'') = '' THEN 1 ELSE 0 END AS IsCash,
				STypeId,
				ATypeId,
				FDC,
				Cid
			FROM
			(
				SELECT @CurrentDay AS BusinessDate,
						0 AS YesterdayBalance,
						dbo.f_roundtotal(CASE WHEN T2.BasisType = 0 
								THEN FDebit * T1.Rate
							ELSE FDebit / T1.Rate
						END) AS FDebit,
						dbo.f_roundtotal(CASE WHEN T2.BasisType = 0
								THEN FCredit * T1.Rate
							ELSE FCredit / T1.Rate
						END) AS FCredit,
						0 AS FBalance,
						AccountId,
						IsCash,
						STypeId,
						ATypeId,
						FDC,
						0 AS Cid
				FROM dbo.Te_Journal_Detail T1
					INNER JOIN dbo.Ac_Currency T2 ON T1.Cid = T2.CId
				WHERE CONVERT(VARCHAR(100),Businessdate,23) = @CurrentDay
					AND STypeId = @TypeId
				
				UNION ALL
				
				SELECT	@CurrentDay AS BusinessDate,
						FBalance AS YesterdayBalance,
						0 AS FDebit,
						0 AS FCredit,
						0 AS FBalance,
						AccountId,
						IsCash,
						STypeId,
						ATypeId,
						FDC,
						0 AS Cid
				FROM dbo.Te_Journal T2
				WHERE CONVERT(VARCHAR(100),Businessdate,23) = DATEADD(day,-1,@CurrentDay)
					AND STypeId = @TypeId
					AND Cid = 0
			)T
			GROUP BY T.BusinessDate,AccountId,STypeId,ATypeId,FDC,T.Cid
			
			--日记账数据日结后，还是没有数据，写一条现金0值记录用于标识
			IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal WHERE Businessdate = @CurrentDay AND STypeId = @Typeid)
			BEGIN
				INSERT INTO dbo.Te_Journal
				( Businessdate ,
				  YesterdayFBalance ,
				  FDebitTotal ,
				  FCreditTotal ,
				  FBalance ,
				  AccountId ,
				  IsCash ,
				  STypeId ,
				  ATypeId,
				  FDC,
				  Cid
				)
				SELECT	TOP 1 @CurrentDay,
					0 AS YesterdayFBalance,
					0 AS FDebit,
					0 AS FCredit,
					0 AS FEndBalance,
					0 AS AccountId,
					1 AS IsCash,
					STypeId,
					TypeId,
					FDC,
					0
				FROM dbo.Ac_Account
				WHERE StypeId = @TypeId AND TypeId LIKE '0000100001%' AND SonNum = 0
			END
			
			----对账单日结----
			--①对账单 所有币种
			INSERT INTO dbo.Te_BankStatement
			        ( Businessdate ,
			          YesterdayFBalance ,
			          FDebitTotal ,
			          FCreditTotal ,
			          FBalance ,
			          AccountId ,
			          Cid,
			          FDC
			        )
			SELECT  Businessdate,
					SUM(YesterdayFBalance) AS YesterdayFBalance,
					SUM(FDebit) AS FDEbit,
					SUM(FCredit) AS FCredit,
					CASE WHEN FDC = 1 THEN 
							SUM(YesterdayFBalance) + SUM(FDebit) - SUM(FCredit)
						 ELSE
							SUM(YesterdayFBalance) + SUM(FCredit) - SUM(FDebit)
					END AS FBalance,
					AccountId,
					Cid,
					FDC
			FROM
			(
			SELECT	Businessdate,
					0 AS YesterdayFBalance,
					FDebit,
					FCredit,
					0 AS FBalance,
					AccountId,
					T1.Cid,
					FDC
			FROM dbo.Te_BankStatementDetail T1
				INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id AND T2.STypeId = @STypeId
			WHERE CONVERT(VARCHAR(100),Businessdate,23) = @CurrentDay
			
			UNION ALL
			
			SELECT  @CurrentDay AS BusinessDate,
					FBalance AS YesterdayFBalance,
					0,
					0,
					0 AS FBalance,
					AccountId,
					T1.Cid,
					FDC
			FROM dbo.Te_BankStatement T1
				INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id AND T2.STypeId = @STypeId
			WHERE CONVERT(VARCHAR(100),Businessdate,23) = DATEADD(day,-1,@CurrentDay)
				AND T1.Cid <> 0
			)T
			GROUP BY T.Businessdate,T.AccountId,T.Cid,T.FDC
			
			--②对账单 综合本位币
			INSERT INTO dbo.Te_BankStatement
			        ( Businessdate ,
			          YesterdayFBalance ,
			          FDebitTotal ,
			          FCreditTotal ,
			          FBalance ,
			          AccountId ,
			          Cid,
			          FDC
			        )
			SELECT  Businessdate,
					SUM(YesterdayFBalance) AS YesterdayFBalance,
					SUM(FDebit) AS FDEbit,
					SUM(FCredit) AS FCredit,
					CASE WHEN FDC = 1 THEN 
							SUM(YesterdayFBalance) + SUM(FDebit) - SUM(FCredit)
						 ELSE
							SUM(YesterdayFBalance) + SUM(FCredit) - SUM(FDebit)
					END AS FBalance,
					AccountId,
					Cid,
					FDC
			FROM
			(
			SELECT	Businessdate,
					0 AS YesterdayFBalance,
					dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN 
							FDebit * T1.Rate
						 ELSE
							FDebit / T1.Rate
					END) AS FDebit,
					dbo.f_roundtotal(CASE WHEN T3.BasisType = 0 THEN 
							FCredit * T1.Rate
						ELSE
							FCredit / T1.Rate
					END) AS FCredit,
					0 AS FBalance,
					AccountId,
					0 AS Cid,
					FDC
			FROM dbo.Te_BankStatementDetail T1
				INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id AND T2.STypeId = @STypeId
				INNER JOIN dbo.Ac_Currency T3 ON T1.Cid = T3.CId
			WHERE CONVERT(VARCHAR(100),Businessdate,23) = @CurrentDay
			
			UNION ALL
			
			SELECT  @CurrentDay AS BusinessDate,
					FBalance AS YesterdayFBalance,
					0,
					0,
					0 AS FBalance,
					AccountId,
					0 AS Cid,
					FDC
			FROM dbo.Te_BankStatement T1
				INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id AND T2.STypeId = @STypeId
			WHERE CONVERT(VARCHAR(100),Businessdate,23) = DATEADD(day,-1,@CurrentDay)
					AND T1.Cid = 0
			)T
			GROUP BY T.Businessdate,T.AccountId,T.Cid,T.FDC
			
			
			--对账单数据日结后，还是没有数据，写一条0值记录用于标识
			IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_BankStatement T1 INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
							WHERE Businessdate = @CurrentDay AND T2.STypeId = @TypeId)
			BEGIN
				INSERT INTO dbo.Te_BankStatement
				        ( Businessdate ,
				          YesterdayFBalance ,
				          FDebitTotal ,
				          FCreditTotal ,
				          FBalance ,
				          AccountId ,
				          Cid ,
				          FDC
				        )
				SELECT	TOP 1 @CurrentDay,
					0 AS YesterdayFBalance,
					0 AS FDebit,
					0 AS FCredit,
					0 AS FEndBalance,
					T1.Id AS AccountId,
					0 Cid,
					T2.Fdc
				FROM dbo.Te_BankAccount T1
					INNER JOIN dbo.Ac_Account T2 ON T1.STypeId = T2.StypeId AND T1.ATypeId = T2.TypeId
				WHERE T1.StypeId = @TypeId AND T1.IsDestroy = 0
			END
			
			------日结 END ------
						
			SET @CurrentDay = DATEADD(DAY,1,@CurrentDay)
		END

	END

	SET @MiniDay = ''
	SET @Index += 1
END

SELECT 1 AS finish

DROP TABLE #GetManSTypeId,#temp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_TellerSignOpreation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_TellerSignOpreation]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.04.16
	描述：出纳签字、取消签字
*/
CREATE PROCEDURE GP_TellerSignOpreation
(
	@OperatorId			VARCHAR(50),	-- 当前操作员ID
	@StypeId			VARCHAR(50),	-- 分支机构
	@BillIds			VARCHAR(MAX),	-- 凭证ID
	@IfBatch			INT=0,			-- 0.无 1.按匹配条件批量签字（无批量取消）
	@Flag				INT=1,			-- 0.取消签字 1.签字
	@Jump				INT=0			-- 联用时，当日日结时生成次日日记账明细 0.提示 1.生成
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN

--存储可以生成日记账的凭证明细
CREATE TABLE #TmpVoucherBill
(
	Id INT IDENTITY(1,1),
	BillDate		DATETIME,
	VoucherId		INT,
	BillDetailId	INT,
	ETypeId			VARCHAR(50),
	Summary			VARCHAR(1000),
	FDebit			 NUMERIC(24, 10) ,
	FCredit			 NUMERIC(24, 10) ,
	AccountId		INT,
	IsCash			INT,
	FDC				INT,
	STypeId			VARCHAR(50),
	ATypeId			VARCHAR(50),
	FSettleId		INT,
	FSettleNo		VARCHAR(50),
	Cid				INT,
	Rate			 NUMERIC(24, 10) ,
	FDebitOri		 NUMERIC(24, 10) ,
	FCreditOri		 NUMERIC(24, 10) ,
	Teller			VARCHAR(50),
	FYear			INT,
	FPeriod			INT
)

DECLARE @DetailID	INT,--日记账明细ID
		@BUID		INT, --业务类型ID
		@szPid		VARCHAR(500)

--配置，每日日结
DECLARE @DayConfig INT
SELECT @DayConfig = SubValue FROM dbo.sysdata WHERE SubName = 'tejournal'

--配置，签字是否生成日记账
DECLARE @JournalConfig INT
SELECT @JournalConfig = SubValue FROM sysdata WHERE SubName = 'tevouchertojournal'

--出纳、总账是否联用
DECLARE @IsConnect INT
SELECT @IsConnect = IsConnect FROM dbo.Te_StartPeriod WHERE STypeId = @StypeId

DECLARE @FYear INT,@FPeriod	INT

--如果出纳启用了并联用了总账，以出纳期间为准进行签字
IF @IsConnect = 1
BEGIN
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Te_Period WHERE STypeId = @StypeId
END
ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @StypeId)
BEGIN
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @StypeId
END
ELSE
BEGIN
	SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName = 'fyear'
	SELECT @FPeriod = SubValue FROM dbo.sysdata WHERE SubName = 'FPeriod'
END

--手工
IF @IfBatch = 0
BEGIN
	INSERT INTO #TmpVoucherBill
				( BillDate ,
				  VoucherId,
				  BillDetailId ,
				  ETypeId ,
				  Summary ,
				  FDebit ,
				  FCredit ,
				  AccountId ,
				  IsCash ,
				  FDC ,
				  STypeId ,
				  ATypeId ,
				  FSettleId ,
				  FSettleNo ,
				  Cid ,
				  Rate,
				  FDebitOri,
				  FCreditOri,
				  Teller,
				  FYear,
				  FPeriod
				)
		SELECT  T2.BillDate,
				T2.BillNumberId,
				T1.ID,
				T2.ETypeId,
				Summary,
				FDebitTotalFor,
				FCreditTotalFor,
				ISNULL(T4.Id,''),
				T3.IsCash,
				T1.Fdc,
				T1.STypeId,
				T1.ATypeId,
				FSettleTypeID,
				FSettleNo,
				T1.Cid,
				T1.Rate,
				T1.FDebitTotal,
				T1.FCreditTotal,
				T2.Teller,
				T2.FYear,
				T2.FPeriod
		FROM dbo.Ac_Voucher_Bill T1
			INNER JOIN dbo.Ac_Voucher T2 ON T1.BillNumberId = T2.BillNumberId
			INNER JOIN dbo.Ac_Account T3 ON T1.STypeId = T3.StypeId AND T1.ATypeId = T3.TypeId
			LEFT JOIN dbo.Te_BankAccount T4 ON T1.ATypeId = T4.ATypeId AND T1.STypeId = T4.STypeId AND T4.IsDestroy=0
			LEFT JOIN dbo.Ac_GoodsBill_VoucherBill T5 ON T1.BillNumberId = T5.VourchBillId
		LEFT JOIN dbo.BillIndex T6 ON t5.GoodsBillId = T6.BillNumberId
		WHERE T2.BillNumberId IN (SELECT a FROM dbo.f_split(@BillIds,',') WHERE ISNULL(a,'')<>'')
			AND (T3.IsCash = 1 OR T3.IsBank = 1)
			AND T2.IfCheck = 't'
			AND ISNULL(T2.MarkError,'') = ''
END
ELSE
BEGIN--批量
	INSERT INTO #TmpVoucherBill
				( BillDate ,
				  VoucherId,
				  BillDetailId ,
				  ETypeId ,
				  Summary ,
				  FDebit ,
				  FCredit ,
				  AccountId ,
				  IsCash ,
				  FDC ,
				  STypeId ,
				  ATypeId ,
				  FSettleId ,
				  FSettleNo ,
				  Cid ,
				  Rate,
				  FDebitOri,
				  FCreditOri
				)
	SELECT  T2.BillDate,
			T2.BillNumberId,
			T1.ID,
			T2.ETypeId,
			Summary,
			FDebitTotalFor,
			FCreditTotalFor,
			ISNULL(T4.Id,''),
			T3.IsCash,
			T1.Fdc,
			T1.STypeId,
			T1.ATypeId,
			FSettleTypeID,
			FSettleNo,
			T1.Cid,
			T1.Rate,
			T1.FDebitTotal,
			T1.FCreditTotal
	FROM dbo.Ac_Voucher_Bill T1
		INNER JOIN dbo.Ac_Voucher T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN dbo.Ac_Account T3 ON T1.STypeId = T3.StypeId AND T1.ATypeId = T3.TypeId
		LEFT JOIN dbo.Te_BankAccount T4 ON T1.ATypeId = T4.ATypeId AND T1.STypeId = T4.STypeId AND T4.IsDestroy=0
		LEFT JOIN dbo.Ac_GoodsBill_VoucherBill T5 ON T1.BillNumberId = T5.VourchBillId
		LEFT JOIN dbo.BillIndex T6 ON t5.GoodsBillId = T6.BillNumberId
	WHERE T1.FYear = @FYear AND T1.FPeriod = @FPeriod
		AND (T3.IsCash = 1 OR T3.IsBank = 1)
		AND ISNULL(T2.MarkError,'') = ''
		AND T2.IfCheck = 't'
		AND ISNULL(T2.Teller,'') = ''
END

--最后日结日期
DECLARE @JournalEndDate DATETIME
SELECT TOP 1 @JournalEndDate = Businessdate FROM dbo.Te_Journal WHERE STypeId = @StypeId ORDER BY Businessdate DESC


--已月结期间的凭证不能操作
IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherBill
	WHERE ((FYear = @FYear AND FPeriod < @FPeriod) OR (FYear < @FYear) ) )
BEGIN
	COMMIT TRANSACTION
	RETURN -11
END

--签字
IF @Flag = 1
BEGIN
	--存在已签字凭证
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherBill WHERE ISNULL(Teller,'') <> '' ) AND @jump = 0
	BEGIN
		COMMIT TRANSACTION
		RETURN -12
	END

	--配置每日日结
	--并且要生成日记账时
	--如果凭证日期大于当天，不签字也不生成日记账
	IF  @DayConfig = 1 
		AND @JournalConfig = 1
		AND EXISTS(SELECT TOP 1 1 FROM #TmpVoucherBill 
				WHERE BillDate <=@JournalEndDate)
		AND @jump = 0
	BEGIN
		COMMIT TRAN
		RETURN -13
	END

	--签字
	UPDATE T1
	SET T1.Teller = @OperatorId
	FROM dbo.Ac_Voucher T1
		INNER JOIN #TmpVoucherBill T2 ON T1.BillNumberId = T2.VoucherId
	
	UPDATE #TmpVoucherBill SET Teller = @OperatorId
END
ELSE --取消签字
BEGIN
	--存在未签字凭证
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherBill WHERE ISNULL(Teller,'') = '' )
	BEGIN
		COMMIT TRANSACTION
		RETURN -14
	END
	--相应日期已做日结
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherBill T1 INNER JOIN dbo.Te_Journal T2 ON T1.billdate = T2.Businessdate AND T1.stypeid = T2.STypeId
				INNER JOIN dbo.Te_Journal_Detail T3 ON T1.BillDetailId = T3.VoucherId)
	BEGIN
		COMMIT TRAN
		RETURN -15
	END
	
	--如果银行日记账已勾对，不能反签字
	IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherBill T1
				INNER JOIN dbo.Te_Journal_Detail T2 ON T1.BillDetailId = T2.VoucherId
				INNER JOIN dbo.Te_CheckRelevance T3 ON T2.Id = T3.JournalId)
	BEGIN
		COMMIT TRAN
		RETURN -16
	END
	
	--反签字
	UPDATE T1
	SET T1.Teller = ''
	FROM dbo.Ac_Voucher T1
		INNER JOIN #TmpVoucherBill T2 ON T1.BillNumberId = T2.VoucherId
END


--异常值
DECLARE @ErrorFlag INT
SET @ErrorFlag = 0

--联用且配置要登入日记账，生成日记账
IF @IsConnect = 1 AND @JournalConfig = 1
BEGIN
	DECLARE @TotalRow INT,@Index INT,
		@BusinessDate	DATETIME,--日期
		@BillId		INT,		--凭证明细ID
		@BillIndexId	INT,	--凭证id
		@BillFDebit	 NUMERIC(24, 10) ,--明细的借方发生
		@BillFCredit	 NUMERIC(24, 10) ,--明细的贷方发生
		@BillFDC		INT,--借贷方向
		@BillCid		INT,--明细币种
		@BillATypeId	VARCHAR(50),--明细科目
		@NowBalance	 NUMERIC(24, 10) ,--日记账相应科目当前累计余额
		@EndDate		DATETIME  --所在期间最后一天
	SET @Index = 1
	SELECT @TotalRow = COUNT(*) FROM #TmpVoucherBill

		
	WHILE @Index <= @TotalRow
	BEGIN
		SELECT  @BusinessDate = BillDate,
				@BillId = BillDetailId,
				@BillIndexId = VoucherId,
				@BillFDebit = FDebit,
				@BillFCredit = FCredit,
				@BillFDC = FDC,
				@BillCid = Cid,
				@BillATypeId = ATypeId
		FROM #TmpVoucherBill WHERE Id = @Index
		
		--期间一致性检查
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE STypeId = @StypeId AND FYear = @FYear AND FPeriod = @FPeriod)
			AND @Flag = 1
		BEGIN
			IF @Jump = 0
			BEGIN
				--RAISERROR('出纳期间与总账期间不一致，无法出纳签字，确认后继续',16,1)
				SET @ErrorFlag = -1
				UPDATE dbo.Ac_Voucher SET Teller = '' WHERE BillNumberId = @BillIndexId
				BREAK
			END
			ELSE
			BEGIN
				SET @Index += 1
				CONTINUE
			END
		END
		
		--日期所在期间最后一天
		SELECT @EndDate = FEnd FROM dbo.Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod
		
		--计算当前写入日记账明细余额
		SELECT TOP 1 @NowBalance = (CASE WHEN @BillFDC = 1 THEN FEndBalance + @BillFDebit - @BillFCredit
							ELSE FEndBalance + @BillFCredit - @BillFDC
					  END) 
		FROM dbo.Te_Journal_Detail 
		WHERE ATypeId = @BillATypeId 
			ORDER BY Id DESC
		
		--签字，按配置生成日记账
		IF @Flag = 1
		BEGIN		
			IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal WHERE Businessdate = @BusinessDate AND STypeId = @StypeId)
			BEGIN
				IF @Jump = 0
				BEGIN
					IF DATEADD(day,1,@BusinessDate) <= @EndDate
					BEGIN
						--RAISERROR('出纳系统已经完成相应日期的日结，继续将登入次日的日记账，请确认是否继续？',16,1)
						SET @ErrorFlag = -2
						UPDATE dbo.Ac_Voucher SET Teller = '' WHERE BillNumberId = @BillIndexId
						BREAK
					END
					ELSE 
					BEGIN
						--RAISERROR('不能登入日记账，反日结后才能登入，确认后操作继续',16,1)
						SET @ErrorFlag = -3
						UPDATE dbo.Ac_Voucher SET Teller = '' WHERE BillNumberId = @BillIndexId
						BREAK
					END
				END
				ELSE
				BEGIN
					--IF DATEADD(day,1,@BusinessDate) <= @EndDate
					--BEGIN
					--	SET @BusinessDate = DATEADD(day,1,@BusinessDate)
					--	GOTO InsertData;
					--END
					--ELSE
					--BEGIN
						SET @Index += 1
						CONTINUE
					--END
				END
			END
			
			--生成日记账
			InsertData:
				SET @DetailId = 0
				
				IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpVoucherBill
							WHERE ID = @Index 
								AND BillDetailId IN (SELECT VoucherId FROM dbo.Te_Journal_Detail)
						)		
				BEGIN
				INSERT INTO dbo.Te_Journal_Detail
						( BusinessDate ,
						  SourceId ,
						  VoucherId ,
						  ETypeId ,
						  Summary ,
						  FDebit ,
						  FCredit ,
						  FEndBalance ,
						  AccountId ,
						  IsCash ,
						  FDC ,
						  STypeId ,
						  ATypeId ,
						  FSettleId ,
						  FSettleNo ,
						  Cid ,
						  Rate ,
						  FDebitOri ,
						  FCreditOri
						)
				SELECT  BillDate,
						2,
						BillDetailId,
						Teller,
						Summary,
						FDebit,
						FCredit,
						@NowBalance,
						AccountId,
						IsCash,
						fdc,
						STypeId,
						ATypeId,
						FSettleId,
						FSettleNo,
						Cid,
						Rate,
						FDebitOri,
						FCreditOri
				FROM #TmpVoucherBill
				WHERE ID = @Index 
					AND (IsCash = 1 OR (IsCash = 0 AND ISNULL(AccountId,'') <> ''))
					AND BillDetailId NOT IN (SELECT VoucherId FROM dbo.Te_Journal_Detail)
				
				
				--写余额表
				SET @DetailId = @@IDENTITY
				
				END

				
				SELECT @BUID = CASE WHEN ISNULL(AccountId,0) = 0 THEN 1 ELSE 2 END 
					FROM #TmpVoucherBill WHERE ID = @Index
				
				IF ISNULL(@DetailId,0) <> 0
					AND EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal_Detail WHERE Id = @DetailId) 
					AND @BUID IN (1,2)
				BEGIN
					
					EXEC @ErrorFlag = dbo.GP_TeDetailToBalance @BUID,@DetailId,1,@szPid OUTPUT
					IF @ErrorFlag = -1
					BEGIN
						SET @ErrorFlag = -4
						BREAK
					END
				END
				
			IF @@ERROR <> 0
			BEGIN
				RAISERROR('发生异常，操作无法完成',16,1)
				ROLLBACK TRANSACTION
			END
		END
		ELSE--取消签字，删除日记账
		BEGIN
			SELECT  @DetailId = Id,
					@BUID = CASE WHEN ISNULL(AccountId,0) = 0 THEN 1 ELSE 2 END 
			FROM dbo.Te_Journal_Detail
			WHERE BusinessDate = @BusinessDate 
				AND ATypeId = @BillATypeId 
				AND FDebit = @BillFDebit 
				AND FCredit = @BillFCredit
				AND STypeId = @STypeId
				AND SourceId = 2
				AND VoucherId = @BillId
			
			--已勾对
			IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_CheckRelevance WHERE JournalId = @DetailId)
			BEGIN
				RAISERROR('凭证对应日记账已勾对，无法反签字！',16,1)
				ROLLBACK TRAN
				RETURN
			END
									
			--删除余额表相应数据
			EXEC dbo.GP_TeDetailToBalance @BUID,@DetailId,-1,@szPid OUTPUT
			
			--删除日记账数据
			DELETE FROM dbo.Te_Journal_Detail WHERE Id = @DetailID
			
			IF @@ERROR <> 0
			BEGIN
				RAISERROR('发生异常，操作无法完成',16,1)
				ROLLBACK TRANSACTION
				RETURN
			END
		END
		
		SET @DetailId = 0
		SET @Index += 1
	END
END	



DROP TABLE #TmpVoucherBill

COMMIT TRAN

RETURN @ErrorFlag


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_TeMonthProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_TeMonthProc]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.05.08
	描述：出纳系统月结
*/
CREATE PROCEDURE Gp_TeMonthProc
(
	@OperatorId	VARCHAR(50),-- 操作员ID
	@type		INT,		-- 操作标识   -1.反结账  1.结账
	@Stypeid	VARCHAR(50) -- 结账分支机构
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM dbo.loginuser WHERE etypeid = @OperatorId AND MangerSTypeID = '-99999')
	AND NOT EXISTS(SELECT TOP 1 1 FROM F_GetAllManagerBaseTypeId('',11,@OperatorId) WHERE typeid = @Stypeid)
BEGIN
	RAISERROR('当前操作员不具有此分支机构权限',16,1)
	RETURN -1
END

--分支机构未启用，无法操作
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @Stypeid AND IsUse = 1)
BEGIN
	RAISERROR('出纳系统启用期间尚未启用，无法执行操作',16,1)
	RETURN 
END

--此分支是否联用总账
DECLARE @isConnect INT
SELECT @isConnect = IsConnect FROM dbo.Te_StartPeriod WHERE STypeId = @Stypeid

--是否要求每日日结
DECLARE @mustJournal INT
SET @mustJournal = 0
SELECT @mustJournal = SubValue FROM dbo.sysdata WHERE SubName ='tejournal'

--日结/反日结操作结果
CREATE TABLE #TmpDaily(finish INT)

--启用年度、期间
DECLARE @StartFYear INT,@StartFPeriod INT
--联用年度、期间
DECLARE @ConnectFYear INT,@ConnectFperiod INT
SELECT @StartFYear = SFYear,@StartFPeriod = SFPeriod,
		@ConnectFYear = CFYear,@ConnectFperiod = CFPeriod
FROM dbo.Te_StartPeriod WHERE STypeId = @Stypeid

--年度、期间
DECLARE @FYear INT,@FPeriod INT
SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Te_Period WHERE STypeId = @STypeId
--期间开始日期
DECLARE @PeriodOPDate DATETIME


--期间总数
DECLARE @AcPeriodCount INT

--当期开始日期、结束日期
DECLARE @FBegin DATETIME,
		@FEnd	DATETIME


SELECT @FBegin = FBegin,@FEnd = FEnd FROM dbo.Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod

--标识是否要生成下一年度期间
DECLARE @returnValue INT
SET @returnValue = 0

--反月结
IF @type = -1
BEGIN
	IF @FYear = @StartFYear AND @FPeriod = @StartFPeriod
	BEGIN
		RAISERROR('当前为出纳系统启用期间，没有历史结账记录，无需反结账',16,1)
		RETURN 
	END
	
	--要求业务数据清空才能反月结
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal_Detail WHERE BusinessDate >= @FBegin AND BusinessDate <= @FEnd AND STypeId = @Stypeid)
	BEGIN
		RAISERROR('当期存在日记账数据，无法反月结',16,1)
		RETURN
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_BankStatementDetail WHERE BusinessDate >= @FBegin AND BusinessDate <= @FEnd
			AND AccountId IN (SELECT Id FROM dbo.Te_BankAccount WHERE STypeId = @Stypeid AND IsDestroy = 0))
	BEGIN
		RAISERROR('当期存在银行对账单数据，无法反月结',16,1)
		RETURN
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_AccountInTransit_Detail T1
				INNER JOIN dbo.Te_AccountInTransit_Index T2 ON T1.Id = T2.Id
				INNER JOIN dbo.Te_BankAccount T3 ON T2.AccountId = T3.Id AND T3.IsDestroy = 0
			WHERE T1.CreateDate >= @FBegin AND T1.CreateDate <= @FEnd AND T3.STypeId = @Stypeid)
	BEGIN
		RAISERROR('当期存在未达账数据，无法反月结',16,1)
		RETURN
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillType = 310 AND ifcheck='t' AND RedWord = 0 AND Stypeid = @Stypeid
				AND BillDate >= @FBegin AND BillDate <= @FEnd)
	BEGIN
		RAISERROR('当期存在已过账资金调拨单数据，无法反月结',16,1)
		RETURN
	END
	
	--调整赋值位置，因为月结和反月结查询的年度条件其实是不一样的，反月结的时候应查询上一年度的数据
	SELECT @AcPeriodCount = COUNT(FPeriod) FROM dbo.Ac_Period WHERE FYear = @FYear-1
	--未要求每日日结，反月结将当月数据全部反日结
	IF @mustJournal = 0
	BEGIN
		IF @FPeriod > 1
			SELECT @PeriodOPDate = FBegin FROM dbo.Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod -1
		ELSE
			SELECT @PeriodOPDate = FBegin FROM dbo.Ac_Period WHERE FYear = @FYear - 1 AND FPeriod = @AcPeriodCount
		
		--反日结到指定期间开始日期
		INSERT INTO #TmpDaily(finish)
		EXEC dbo.Gp_TellerDailySettlement @OperatorId,@PeriodOPDate,0,@Stypeid,1
	END
	
	--如果当期没有业务数据，反月结清空当期余额表记录
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal_Detail WHERE BusinessDate >= @FBegin AND BusinessDate <= @FEnd AND STypeId = @Stypeid)
		AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_BankStatementDetail T1
							INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
						WHERE Businessdate >= @FBegin AND Businessdate <= @FEnd AND STypeId = @Stypeid)
	BEGIN
		DELETE FROM dbo.Te_Balance WHERE FYear = @FYear AND FPeriod = @FPeriod AND STypeId = @Stypeid
	END
	
	--更新期间
	IF @FPeriod > 1
		UPDATE dbo.Te_Period SET FPeriod = @FPeriod - 1 WHERE STypeId = @Stypeid
	ELSE
		UPDATE dbo.Te_Period 
			SET FPeriod = @AcPeriodCount,
				FYear -= 1
		WHERE STypeId = @Stypeid
	
	SELECT @returnValue AS finish
END
ELSE
BEGIN
	--未初始化完成，无期间，无法月结
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period WHERE STypeId = @Stypeid)
	BEGIN
		RAISERROR('未初始化完成，无法结账',16,1)
		RETURN
	END
	
	
	DECLARE @startDate  DATETIME,
			@endDate	DATETIME
			
	SELECT  @startDate = FBegin,
			@endDate = FEnd 
	FROM dbo.Ac_Period T1
		INNER JOIN dbo.Te_Period T2 ON T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod
	WHERE T2.STypeId = @Stypeid
	
	--判断是否有未入账的资金调拨单
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillType = 310 AND IfConfirm = 0 AND BillDate >= @startDate AND BillDate <= @endDate AND StypeID2 = @Stypeid AND RedWord = 0)
	BEGIN
		RAISERROR('本期内存在未入账的资金调拨单，无法结账',16,1)
		RETURN
	END
	
	--判断调出/调入未生成凭证
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillType = 310 AND RedWord = 0 AND ifcheck = 't'
				AND BillDate >= @startDate AND BillDate <= @endDate AND Stypeid = @Stypeid
				AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = -1))
		OR EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillType = 310 AND RedWord = 0 AND ifcheck = 't'
					AND BillDate >= @startDate AND BillDate <= @endDate AND Stypeid2 = @Stypeid
					AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = 1))
	BEGIN
		RAISERROR('本期存在资金调拨单未生成凭证，无法结账',16,1)
		RETURN
	END
	
	--联用时，判断凭证是否已生成相应日记账
	IF @isConnect = 1 AND (@FYear = @ConnectFYear AND @FPeriod>=@ConnectFperiod OR @FYear > @ConnectFYear)
	BEGIN
		SELECT DISTINCT content
		INTO #Temp
		FROM
		(
		SELECT T4.FullName + '----------' + T5.FullName + '-' + CAST(T1.FlowNo AS VARCHAR(100)) AS content
		FROM dbo.Ac_Voucher T1
			INNER JOIN dbo.Ac_Voucher_Bill T2 ON T1.BillNumberId = T2.BillNumberId
			INNER JOIN dbo.Ac_Account T3 ON T2.ATypeId = T3.TypeId AND T1.STypeId = T3.StypeId
			INNER JOIN dbo.SType T4 ON T1.STypeId = T4.TypeId
			INNER JOIN Ac_Voucher_Group T5 ON T1.VgId = T5.VgId
		WHERE (T3.IsBank = 1 OR T3.IsCash = 1)
			AND T2.ID NOT IN (SELECT VoucherId FROM dbo.Te_Journal_Detail WHERE STypeId = @stypeid)
			AND T1.FYear = @FYear AND T1.FPeriod = @FPeriod
			AND T1.stypeid = @Stypeid
			AND T1.FChecked <> -1
			AND ISNULL(T1.MarkError,'') = ''
		
		UNION ALL
		SELECT T4.FullName + '----------' + T5.FullName + '-' + CAST(T1.FlowNo AS VARCHAR(100)) AS content
		FROM dbo.Ac_Voucher T1
			INNER JOIN dbo.Ac_Voucher_Bill T2 ON T1.BillNumberId = T2.BillNumberId
			INNER JOIN dbo.Ac_Account T3 ON T2.ATypeId = T3.TypeId AND T1.STypeId = T3.StypeId
			INNER JOIN dbo.SType T4 ON T1.STypeId = T4.TypeId
			INNER JOIN Ac_Voucher_Group T5 ON T1.VgId = T5.VgId
			INNER JOIN dbo.Ac_GoodsBill_VoucherBill T6 ON T1.BillNumberId = T6.VourchBillId
			INNER JOIN dbo.BillIndex T7 ON T6.GoodsBillId = T7.BillNumberId
		WHERE (T3.IsBank = 1 OR T3.IsCash = 1)
			AND T2.ID NOT IN (SELECT VoucherId FROM dbo.Te_Journal_Detail WHERE STypeId = @stypeid)
			AND T7.BillDate >= @startDate AND T7.BillDate <= @endDate
			AND T1.VoucherType = 7
			AND T1.STypeId = @stypeid
			AND T1.FChecked <> -1
			AND ISNULL(T1.MarkError,'') = ''
		)T	
		
		IF EXISTS(SELECT TOP 1 1 FROM #Temp)
		BEGIN
			SELECT '未生成日记账的会计凭证' AS CONTENT
			UNION ALL
			SELECT * FROM #Temp
			
			RETURN
		END

		--联用下判断余额要一致
		IF EXISTS(
			SELECT TOP 1 1
			FROM
				(
				SELECT ISNULL(T1.FEndBalance,0)AS Ac_Balance,
						ISNULL(T2.FEndBalance,0) AS Te_Balance 
					FROM dbo.Ac_Balance T1
					LEFT JOIN dbo.Te_Balance T2 ON T1.FYear = T2.FYear 
								AND T1.FPeriod = T2.FPeriod 
								AND T1.Cid = T2.Cid
								AND T1.ATypeId = T2.ATypeId
								AND T1.STypeId = T2.STypeId
					INNER JOIN dbo.Ac_Account T3 ON T1.STypeId = T3.StypeId AND T1.ATypeId = T3.TypeId
				WHERE T1.FYear = @FYear 
					AND T1.FPeriod = @FPeriod 
					AND T1.Cid = 0 
					AND T1.STypeId = @STypeId
					AND (T3.IsCash = 1 OR T3.IsBank = 1)
					AND ISNULL(T2.BUId,1) <> 3
				)T WHERE Ac_Balance <> Te_Balance
			)
		OR EXISTS(
			SELECT TOP 1 1
			FROM
				(
				SELECT ISNULL(T1.FEndBalance,0)AS Te_Balance,
						ISNULL(T2.FEndBalance,0) AS Ac_Balance 
				FROM dbo.Te_Balance T1
					LEFT JOIN dbo.Ac_Balance T2 ON T1.FYear = T2.FYear 
								AND T1.FPeriod = T2.FPeriod 
								AND T1.Cid = T2.Cid
								AND T1.ATypeId = T2.ATypeId
								AND T1.STypeId = T2.STypeId
				WHERE T1.FYear = @FYear 
					AND T1.FPeriod = @FPeriod 
					AND T1.Cid = 0 
					AND T1.STypeId = @STypeId
					AND ISNULL(T1.BUId,1) <> 3
				)T WHERE Ac_Balance <> Te_Balance
			)
		BEGIN
			RAISERROR('出纳系统与总账系统对应科目余额不一致，无法月结！',16,1)
			RETURN
		END
	END
	ELSE--未联用时，资金调拨单的凭证要生成日记账
	BEGIN
		SELECT DISTINCT T4.FullName + '----------' + T5.FullName + '-' + CAST(T1.FlowNo AS VARCHAR(100)) AS content
		INTO #Temp2
		FROM dbo.Ac_Voucher T1
			INNER JOIN dbo.Ac_Voucher_Bill T2 ON T1.BillNumberId = T2.BillNumberId
			INNER JOIN dbo.Ac_Account T3 ON T2.ATypeId = T3.TypeId AND T1.STypeId = T3.StypeId
			INNER JOIN dbo.SType T4 ON T1.STypeId = T4.TypeId
			INNER JOIN Ac_Voucher_Group T5 ON T1.VgId = T5.VgId
			INNER JOIN dbo.Ac_GoodsBill_VoucherBill T6 ON T1.BillNumberId = T6.VourchBillId
			INNER JOIN dbo.BillIndex T7 ON T6.GoodsBillId = T7.BillNumberId
		WHERE (T3.IsBank = 1 OR T3.IsCash = 1)
			AND T2.ID NOT IN (SELECT VoucherId FROM dbo.Te_Journal_Detail WHERE STypeId = @stypeid)
			AND T7.BillDate >= @startDate AND T7.BillDate <= @endDate
			AND T1.VoucherType = 7
			AND T1.STypeId = @stypeid
			AND T1.FChecked <> -1
			AND ISNULL(T1.MarkError,'') = ''
		
		IF EXISTS(SELECT TOP 1 1 FROM #Temp2)
		BEGIN
			SELECT '未生成日记账的资金调拨单对应会计凭证' AS CONTENT
			UNION ALL
			SELECT * FROM #Temp2
			
			RETURN
		END
	END
	
	--配置每日日结，判断是否全部做了日结
	IF NOT EXISTS(SELECT Businessdate FROM dbo.Te_Journal WHERE STypeId = @Stypeid
				AND Businessdate = @endDate AND Stypeid = @Stypeid)
		AND @mustJournal = 1
	BEGIN
		RAISERROR('本期日记账未全部日结，无法结账',16,1)
		RETURN
	END
	
	--配置要求对账单和日记账余额一致
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'testatement' AND SubValue = 1)
		AND (EXISTS(
					SELECT TOP 1 1
					FROM dbo.Te_Balance T1
						LEFT JOIN dbo.Te_Balance T2 ON T1.AccountId = T2.AccountId 
										AND T1.FYear = T2.FYear 
										AND T1.FPeriod = T2.FPeriod
										AND T1.Cid = T2.Cid
					WHERE T1.BUId = 2 AND T2.BUId = 3 AND T1.FYear = @FYear AND T1.FPeriod = @FPeriod AND T1.Cid = 0
							AND T1.FEndBalance <> T2.FEndBalance
							AND T1.STypeId = @Stypeid
					)
			OR EXISTS(SELECT TOP 1 1
					FROM dbo.Te_Balance T1
					WHERE T1.BUId = 2 AND T1.FYear = @FYear AND T1.FPeriod = @FPeriod AND T1.STypeId = @Stypeid
						AND NOT EXISTS(SELECT AccountId FROM dbo.Te_Balance T2 
										WHERE BUId = 3 
											AND T1.FYear = T2.FYear 
											AND T1.FPeriod = T2.FPeriod))
			OR EXISTS(SELECT TOP 1 1
					FROM dbo.Te_Balance T1
					WHERE T1.BUId = 3 AND T1.FYear = @FYear AND T1.FPeriod = @FPeriod AND T1.STypeId = @Stypeid
						AND NOT EXISTS(SELECT AccountId FROM dbo.Te_Balance T2 
										WHERE BUId = 2 
											AND T1.FYear = T2.FYear 
											AND T1.FPeriod = T2.FPeriod))
			)
	BEGIN
		RAISERROR('日记账与对账单余额不一致，无法结账',16,1)
		RETURN 
	END
	
	
	--配置非每日日结，系统自动将相应期间内数据标记为日结
	IF @mustJournal = 0
	BEGIN
		SELECT @PeriodOPDate = FEnd FROM dbo.Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod
				
		--日结
		INSERT INTO #TmpDaily(finish)
		EXEC dbo.Gp_TellerDailySettlement @OperatorId,@PeriodOPDate,1,@Stypeid,1
	END
	
	----月结时，重算当期余额（因为日记账一直在改余额）
	----如果有其他期间的数据，相应改写
	--BEGIN TRANSACTION
	
	--DECLARE @minPeriod	INT,
	--		@maxPeriod	INT,
	--		@minYear INT,
	--		@maxYear INT
	
	----当前期间
	--SELECT @minPeriod = FPeriod FROM dbo.Te_Period WHERE STypeId = @Stypeid
	----存在的最大期间
	--SELECT TOP 1 @maxPeriod = FPeriod FROM dbo.Te_Balance WHERE STypeId = @Stypeid ORDER BY FPeriod DESC
	
	----当前年度
	--SELECT @minYear = FYear FROM dbo.Te_Period WHERE STypeId = @Stypeid
	----存在的最大年度
	--SELECT TOP 1 @maxYear = FYear FROM dbo.Te_Balance WHERE STypeId = @Stypeid ORDER BY FYear DESC
	
	
	--DECLARE @currentPeriod INT,@currentFyear INT
	
	--SET @currentPeriod = @minPeriod
	--SET @currentFyear = @minYear
	
	--WHILE @currentFyear <= @maxYear
	--BEGIN
	--	WHILE @currentPeriod <= @maxPeriod
	--	BEGIN
	--		--如果是结账期，且没有下期余额数据，直接将本期余额写入下期期初
	--		IF @currentFyear = @minYear
	--			AND @currentPeriod = @minPeriod
	--			AND
	--			(
	--				(
	--				@currentPeriod < @AcPeriodCount
	--				AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Balance 
	--						WHERE FPeriod = @currentPeriod + 1 AND STypeId = @Stypeid)
	--				)
	--				OR
	--				(
	--				@currentPeriod = @AcPeriodCount
	--				AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Balance 
	--						WHERE FPeriod = 1 AND FYear = @currentFyear + 1 AND STypeId = @Stypeid)
	--				)
	--			)
				
	--		BEGIN
	--			INSERT INTO dbo.Te_Balance
	--					( AccountId ,
	--					  InitBalance ,
	--					  InitYearBalance ,
	--					  Cid ,
	--					  FYear ,
	--					  FPeriod ,
	--					  FDebit ,
	--					  FCredit ,
	--					  FEndBalance ,
	--					  FYtdDebit ,
	--					  FYtdCredit ,
	--					  BUId ,
	--					  ATypeId ,
	--					  STypeid ,
	--					  InitBalanceFor ,
	--					  InitYearBalanceFor ,
	--					  FDebitFor ,
	--					  FCreditFor ,
	--					  FEndBalanceFor ,
	--					  FYtdDebitFor ,
	--					  FYtdCreditFor
	--					)
	--			SELECT  AccountId,
	--					FEndBalance,
	--					InitYearBalance,
	--					Cid,
	--					FYear,
	--					@FPeriod + 1,
	--					0,
	--					0,
	--					FEndBalance,
	--					FYtdDebit,
	--					FYtdCredit,
	--					BUId,
	--					ATypeId,
	--					STypeid,
	--					FEndBalanceFor,
	--					InitYearBalanceFor,
	--					0,
	--					0,
	--					FEndBalanceFor,
	--					FYtdDebitFor,
	--					FYtdCreditFor
	--			FROM dbo.Te_Balance
	--			WHERE FYear = @FYear AND FPeriod = @FPeriod
	--		END
	--		ELSE--如果不是结账期且存在下期数据，以此期间继续重算下期数据
	--		BEGIN
	--			IF @currentPeriod < @AcPeriodCount
	--			UPDATE T1
	--					SET InitBalance = T2.FEndBalance,
	--						InitBalanceFor = T2.FEndBalanceFor,
	--						FEndBalance = CASE WHEN T3.Fdc = 1 THEN T2.FEndBalance + T1.FCredit - T1.FDebit
	--											ELSE T2.FEndBalance + T1.FDebit - T1.FCredit
	--										END,
	--						FEndBalanceFor = CASE WHEN T3.Fdc = 1 THEN T2.FEndBalanceFor + T1.FCreditFor - T1.FDebitFor
	--											ELSE T2.FEndBalanceFor + T1.FDebitFor - T1.FCreditFor
	--										END
	--			FROM dbo.Te_Balance T1
	--				INNER JOIN dbo.Te_Balance T2 
	--					ON T1.BUId = T2.BUId 
	--						AND ISNULL(T1.AccountId,0) = ISNULL(T2.AccountId,0) 
	--						AND T1.ATypeId = T2.ATypeId
	--						AND T1.Cid = T2.Cid
	--						AND T1.FYear = T2.FYear
	--						AND T1.FPeriod = T2.FPeriod + 1
	--						AND T1.STypeId = T2.STypeId
	--				INNER JOIN dbo.Ac_Account T3 ON T1.ATypeId = T3.TypeId AND T1.STypeId = T3.StypeId
	--			WHERE T1.STypeId = @stypeid AND T2.FPeriod = @currentPeriod
	--			ELSE
	--				UPDATE T1
	--					SET InitBalance = T2.FEndBalance,
	--						InitBalanceFor = T2.FEndBalanceFor,
	--						InitYearBalance = T2.FEndBalance,
	--						InitYearBalanceFor = T2.FEndBalanceFor,
	--						FEndBalance = CASE WHEN T3.Fdc = 1 THEN T2.FEndBalance + T1.FCredit - T1.FDebit
	--											ELSE T2.FEndBalance + T1.FDebit - T1.FCredit
	--										END,
	--						FEndBalanceFor = CASE WHEN T3.Fdc = 1 THEN T2.FEndBalanceFor + T1.FCreditFor - T1.FDebitFor
	--											ELSE T2.FEndBalanceFor + T1.FDebitFor - T1.FCreditFor
	--										END
	--				FROM dbo.Te_Balance T1
	--					INNER JOIN dbo.Te_Balance T2 
	--						ON T1.BUId = T2.BUId 
	--							AND ISNULL(T1.AccountId,0) = ISNULL(T2.AccountId,0) 
	--							AND T1.ATypeId = T2.ATypeId
	--							AND T1.Cid = T2.Cid
	--							AND T1.FYear = T2.FYear + 1
	--							AND T2.FPeriod = @AcPeriodCount
	--							AND T1.STypeId = T2.STypeId
	--					INNER JOIN dbo.Ac_Account T3 ON T1.ATypeId = T3.TypeId AND T1.STypeId = T3.StypeId
	--				WHERE T1.STypeId = @stypeid AND T1.FPeriod = @currentPeriod
	--		END
	--		SET @currentPeriod += 1
	--	END
		
	--	SET @currentFyear += 1
	--	SET @currentPeriod = 1
	--	SELECT @maxPeriod = FPeriod FROM dbo.Te_Balance WHERE FYear = @currentFyear ORDER BY FPeriod DESC
	--END
	
	
	----更新期间
	--IF @minPeriod < @AcPeriodCount
	--	UPDATE dbo.Te_Period SET FPeriod += 1 WHERE STypeId = @Stypeid
	--ELSE
	--BEGIN
	--	UPDATE dbo.Te_Period SET FPeriod = 1,FYear += 1 WHERE STypeId = @StypeId
		
	--	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FYear = @minYear + 1)
	--		SET @returnValue = 1
	--END
	
	--IF @@ERROR <> 0
	--BEGIN
	--	RAISERROR('发生异常，操作无法完成',16,1)
	--	ROLLBACK TRANSACTION
	--END
	
	--COMMIT TRANSACTION
	
	--2014.09.04 调整为反月结要删除业务数据，所以不再需要重算后期数据，仅重算当期，确认数据正确
	DECLARE @minPeriod INT,
			@minFYear	INT
	SELECT @minPeriod = FPeriod,@minFYear = FYear FROM dbo.Te_Period WHERE STypeId = @Stypeid
	
	--调整赋值位置，因为月结和反月结查询的年度条件其实是不一样的，反月结的时候应查询上一年度的数据
	SELECT @AcPeriodCount = COUNT(FPeriod) FROM dbo.Ac_Period WHERE FYear = @FYear

	--重算当期 2014.09.26暂时屏蔽
	--UPDATE A
	--SET 
	--	A.FDebit = B.FDebit,
	--	A.FDebitFor = B.FDebitFor,
	--	A.FCredit = B.FCredit,
	--	A.FCreditFor = B.FCreditFor,
	--	A.FEndBalance = A.InitBalance + B.FEndBalance,
	--	A.FEndBalanceFor = A.InitBalanceFor + B.FEndBalanceFor,
	--	A.FYtdDebit = B.FYtdDebit,
	--	A.FYtdDebitFor = B.FYtdDebitFor,
	--	A.FYtdCredit = B.FYtdCredit,
	--	A.FYtdCreditFor = B.FYtdCreditFor
	--FROM Te_Balance A
	--INNER JOIN
	--(
	--SELECT  AccountId,
	--		BUId,
	--		ATypeId,
	--		STypeId,
	--		SUM(InitBalance) AS InitBalance,
	--		SUM(InitBalanceFor) AS InitBalanceFor,
	--		SUM(InitYearBalance) AS InitYearBalance,
	--		SUM(InitYearBalanceFor) AS InitYearBalanceFor,
	--		Cid,
	--		FYear,
	--		FPeriod,
	--		SUM(FDebit) AS FDebit,
	--		SUM(FDebitFor) AS FDebitFor,
	--		SUM(FCredit) AS FCredit,
	--		SUM(FCreditFor) AS FCreditFor,
	--		SUM(FEndBalance) AS FEndBalance,
	--		SUM(FEndBalanceFor) AS FEndBalanceFor,
	--		SUM(FYtdDebit) AS FYtdDebit,
	--		SUM(FYtdDebitFor) AS FYtdDebitFor,
	--		SUM(FYtdCredit) AS FYtdCredit,
	--		SUM(FYtdCreditFor) AS FYtdCreditFor
	--FROM
	--(
	----日记账
	--SELECT  ISNULL(T1.AccountId,0) AS AccountId,
	--		CASE WHEN T1.IsCash = 1 THEN 1 ELSE 2 END AS BUID,
	--		T1.ATypeId,
	--		T1.STypeId,
	--		0 AS InitBalance,
	--		0 AS InitBalanceFor,
	--		0 AS InitYearBalance,
	--		0 AS InitYearBalanceFor, 
	--		T1.Cid,
	--		@minFYear AS FYear,
	--		@minPeriod AS FPeriod,
	--		SUM(T1.FDebitOri) AS FDebit,
	--		SUM(T1.FDebit) AS FDebitFor,
	--		SUM(T1.FCreditOri) AS FCredit,
	--		SUM(T1.FCredit) AS FCreditFor,
	--		SUM(T1.FDebitOri - T1.FCreditOri) AS FEndBalance,
	--		SUM(T1.FDebit - T1.FCredit) AS FEndBalanceFor,
	--		SUM(T1.FDebitOri) AS FYtdDebit,
	--		SUM(T1.FDebit) AS FYtdDebitFor,
	--		SUM(T1.FCreditOri) AS FYtdCredit,
	--		SUM(T1.FCredit) AS FYtdCreditFor
	--FROM dbo.Te_Journal_Detail T1
	--WHERE T1.IsInit = 0 AND BusinessDate >= @FBegin AND BusinessDate <= @FEnd AND T1.STypeId = @STypeId
	--GROUP BY AccountId,T1.IsCash,T1.ATypeId,T1.STypeId,T1.Cid

	--UNION ALL
	----日记账,综合本位币
	--SELECT  ISNULL(T1.AccountId,0) AS AccountId,
	--		CASE WHEN T1.IsCash = 1 THEN 1 ELSE 2 END AS BUID,
	--		T1.ATypeId,
	--		T1.STypeId,
	--		0 AS InitBalance,
	--		0 AS InitBalanceFor,
	--		0 AS InitYearBalance,
	--		0 AS InitYearBalanceFor, 
	--		0 AS Cid,
	--		@minFYear AS FYear,
	--		@minPeriod AS FPeriod,
	--		SUM(T1.FDebitOri) AS FDebit,
	--		SUM(T1.FDebitOri) AS FDebitFor,
	--		SUM(T1.FCreditOri) AS FCredit,
	--		SUM(T1.FCreditOri) AS FCreditFor,
	--		SUM(T1.FDebitOri - T1.FCreditOri) AS FEndBalance,
	--		SUM(T1.FDebitOri - T1.FCreditOri) AS FEndBalanceFor,
	--		SUM(T1.FDebitOri) AS FYtdDebit,
	--		SUM(T1.FDebitOri) AS FYtdDebitFor,
	--		SUM(T1.FCreditOri) AS FYtdCredit,
	--		SUM(T1.FCreditOri) AS FYtdCreditFor
	--FROM dbo.Te_Journal_Detail T1
	--WHERE T1.IsInit = 0 AND BusinessDate >= @FBegin AND BusinessDate <= @FEnd AND T1.STypeId = @STypeId
	--GROUP BY AccountId,T1.IsCash,T1.ATypeId,T1.STypeId
	
	--UNION ALL
	----对账单
	--SELECT  ISNULL(T1.AccountId,0) AS AccountId,
	--		3 AS BUID,
	--		T2.ATypeId,
	--		T2.STypeId,
	--		0 AS InitBalance,
	--		0 AS InitBalanceFor,
	--		0 AS InitYearBalance,
	--		0 AS InitYearBalanceFor, 
	--		T1.Cid,
	--		@minFYear AS FYear,
	--		@minPeriod AS FPeriod,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FDebit) / T1.Rate
	--		END AS FDebit,
	--		SUM(T1.FDebit) AS FDebitFor,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit) * T1.rate
	--			ELSE SUM(T1.FCredit) / T1.Rate
	--		END AS FCredit,
	--		SUM(T1.FCredit) AS FCreditFor,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit - T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FCredit - T1.FDebit) / T1.Rate
	--		END AS FEndBalance,
	--		SUM(T1.FCredit - T1.FDebit) AS FEndBalanceFor,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FDebit) / T1.Rate
	--		END  AS FYtdDebit,
	--		SUM(T1.FDebit) AS FYtdDebitFor,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit) * T1.rate
	--			ELSE SUM(T1.FCredit) / T1.Rate
	--		END AS FYtdCredit,
	--		SUM(T1.FCredit) AS FYtdCreditFor
	--FROM dbo.Te_BankStatementDetail T1
	--	INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
	--	INNER JOIN dbo.Ac_Currency T3 ON T1.Cid = T3.CId
	--WHERE T1.IsInit = 0 AND BusinessDate >= @FBegin AND BusinessDate <= @FEnd AND T2.STypeId = @STypeId
	--GROUP BY AccountId,T2.ATypeId,T2.STypeId,T1.Cid,T3.BasisType,T1.Rate
	
	--UNION ALL
	----对账单,综合本位币
	--SELECT  ISNULL(T1.AccountId,0) AS AccountId,
	--		3 AS BUID,
	--		T2.ATypeId,
	--		T2.STypeId,
	--		0 AS InitBalance,
	--		0 AS InitBalanceFor,
	--		0 AS InitYearBalance,
	--		0 AS InitYearBalanceFor, 
	--		0 AS cid,
	--		@minFYear AS FYear,
	--		@minPeriod AS FPeriod,			
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FDebit) / T1.Rate
	--		END AS FDebit,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FDebit) / T1.Rate
	--		END AS FDebitFor,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit) * T1.rate
	--			ELSE SUM(T1.FCredit) / T1.Rate
	--		END AS FCredit,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit) * T1.rate
	--			ELSE SUM(T1.FCredit) / T1.Rate
	--		END AS FCreditFor,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit - T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FCredit - T1.FDebit) / T1.Rate
	--		END AS FEndBalance,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit - T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FCredit - T1.FDebit) / T1.Rate
	--		END AS FEndBalanceFor,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FDebit) / T1.Rate
	--		END  AS FYtdDebit,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FDebit) * T1.rate
	--			ELSE SUM(T1.FDebit) / T1.Rate
	--		END AS FYtdDebitFor,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit) * T1.rate
	--			ELSE SUM(T1.FCredit) / T1.Rate
	--		END AS FYtdCredit,
	--		CASE WHEN T3.BasisType = 0 THEN SUM(T1.FCredit) * T1.rate
	--			ELSE SUM(T1.FCredit) / T1.Rate
	--		END AS FYtdCreditFor
	--FROM dbo.Te_BankStatementDetail T1
	--	INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
	--	INNER JOIN dbo.Ac_Currency T3 ON T1.Cid = T3.CId
	--WHERE T1.IsInit = 0 AND BusinessDate >= @FBegin AND BusinessDate <= @FEnd AND T2.STypeId = @STypeId
	--GROUP BY AccountId,T2.ATypeId,T2.STypeId,T1.Cid,T3.BasisType,T1.Rate
	--)T
	--GROUP BY AccountId,BUId,ATypeId,STypeId,Cid,FYear,FPeriod
	--)B 
	--	ON A.AccountId = B.AccountId
	--		AND A.BUId = B.BUID
	--		AND A.ATypeId = B.ATypeId
	--		AND A.FYear = B.FYear
	--		AND A.FPeriod = B.FPeriod
	--		AND A.cid = B.cid
	--WHERE A.FYear = @minFYear AND A.FPeriod = @minPeriod AND A.StypeId = @STypeId
	
	
	----调整本期的本年累计借、贷
	--IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Balance WHERE FYear = @minFYear - 1)
	--	OR @minPeriod > 1
	--BEGIN	
	--	UPDATE T1
	--	SET T1.FYtdCredit = T1.FCredit + T2.FYtdCredit,
	--		T1.FYtdCreditFor = T1.FCreditFor + T2.FYtdCredit,
	--		T1.FYtdDebit = T1.FDebit + T2.FYtdDebit,
	--		T1.FYtdDebitFor = T1.FDebitFor + T2.FYtdDebit
	--	FROM dbo.Te_Balance T1
	--		INNER JOIN dbo.Te_Balance T2 ON T1.AccountId = T2.AccountId 
	--					AND T1.STypeId = T2.STypeId 
	--					AND T1.Cid = T2.Cid
	--					AND T1.FYear = T2.FYear AND T1.FPeriod - 1 = T2.FPeriod
	--	WHERE T1.FYear = @minFYear AND T1.FPeriod = @minPeriod AND T1.STypeId = @STypeId
	--END
	
	--写下期STypeId,数据
	INSERT INTO dbo.Te_Balance
		( AccountId ,
		  InitBalance ,
		  InitYearBalance ,
		  Cid ,
		  FYear ,
		  FPeriod ,
		  FDebit ,
		  FCredit ,
		  FEndBalance ,
		  FYtdDebit ,
		  FYtdCredit ,
		  BUId ,
		  ATypeId ,
		  STypeid ,
		  InitBalanceFor ,
		  InitYearBalanceFor ,
		  FDebitFor ,
		  FCreditFor ,
		  FEndBalanceFor ,
		  FYtdDebitFor ,
		  FYtdCreditFor
		)
	SELECT  AccountId,
			FEndBalance,
			CASE WHEN @FPeriod = @AcPeriodCount THEN FEndBalance ELSE InitYearBalance END,
			Cid,
			CASE WHEN @FPeriod = @AcPeriodCount THEN FYear + 1 ELSE FYear END,
			CASE WHEN @FPeriod = @AcPeriodCount THEN 1 ELSE @FPeriod + 1 END,
			0,
			0,
			FEndBalance,
			CASE WHEN @FPeriod = @AcPeriodCount THEN 0 ELSE FYtdDebit END,
			CASE WHEN @FPeriod = @AcPeriodCount THEN 0 ELSE FYtdCredit END,
			BUId,
			ATypeId,
			STypeid,
			FEndBalanceFor,
			CASE WHEN @FPeriod = @AcPeriodCount THEN FEndBalanceFor ELSE InitYearBalanceFor END,
			0,
			0,
			FEndBalanceFor,
			CASE WHEN @FPeriod = @AcPeriodCount THEN 0 ELSE FYtdDebitFor END,
			CASE WHEN @FPeriod = @AcPeriodCount THEN 0 ELSE FYtdCreditFor END
	FROM dbo.Te_Balance
	WHERE FYear = @FYear AND FPeriod = @FPeriod AND STypeId = @STypeId
	
	--更新期间
	IF @minPeriod < @AcPeriodCount
		UPDATE dbo.Te_Period SET FPeriod += 1 WHERE STypeId = @Stypeid
	ELSE
	BEGIN
		UPDATE dbo.Te_Period SET FPeriod = 1,FYear += 1 WHERE STypeId = @StypeId
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FYear = @minFYear + 1)
			SET @returnValue = 1
	END
	
	SELECT @returnvalue AS finish
	
END

DROP TABLE #TmpDaily

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_TemplateCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_TemplateCheck]
GO















/****** Object:  Stored Procedure dbo.Gp_TemplateCheck    Script Date: 2002-6-20 10:14:51 ******/

CREATE  PROCEDURE Gp_TemplateCheck 
( @TemplateId int,
 @KtypeId varchar(100),
 @Num   NUMERIC(24, 10) 
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql  varchar (1000)
select @sql='select a.*,(select isnull(sum(c.total)/sum(c.qty),0) from goodsstocks c where
     left(c.ptypeid,len(a.ptypeid))=a.ptypeid and c.ktypeid='
     +char(39)+@ktypeid+char(39)+') as price,
   (select isnull(sum(c.total),0) from goodsstocks c where
     left(c.ptypeid,len(a.ptypeid))=a.ptypeid and c.ktypeid='
     +char(39)+@ktypeid+char(39)+') as Stocktotal,
   (select isnull(sum(c.qty),0) from goodsstocks c where
     left(c.ptypeid,len(a.ptypeid))=a.ptypeid and c.ktypeid='
     +char(39)+@ktypeid+char(39)+') as Stockqty,
   b.fullname,b.usercode,a.qty*'+Cast(@num as char)+' as pQty from templatelisttable a 
   INNER JOIN ptype b ON b.typeId = a.PtypeId where templateid='+cast(@templateid as varchar)
--print @sql
exec(@sql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_TemplateCopy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_TemplateCopy]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--=========================================================
--	create date：2016-07-07
--	by：glj	
--	description：当前分支机构下模板复制
--=========================================================
CREATE PROCEDURE Gp_TemplateCopy
(
	@STypeID	VARCHAR(50),	--分支机构ID
	@Atid		INT,			--凭证明细id
	@OperatorID	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN

DECLARE 
	@AtidNew	INT,--新凭证模板ID
	@Error		INT=0
INSERT INTO Ac_Auditing_Template
(
	UserCode,
	FullName,
	BillType,
	ETypeId,
	IsDefault,
	CreateDateTime,
	PyCode,
	Comment,
	FromAtid,
	AuditType,
	ChargeOffType,
	InOutType,
	VgId,
	STypeId,
	Sysrow,
	Explaintext,
	ExplainAuditType,
	IsCombineRow
)
SELECT	
	UserCode+'Copy',
	FullName+'Copy',
	BillType,
	ETypeId,
	0 IsDefault,
	CreateDateTime,
	PyCode,
	Comment,
	AtId,
	AuditType,
	ChargeOffType,
	InOutType,
	VgId,
	STypeId,
	Sysrow,
	Explaintext,
	ExplainAuditType,
	IsCombineRow
FROM Ac_Auditing_Template
WHERE 
	AtId=@Atid
	AND STypeId=@STypeID

SELECT @AtidNew=@@IDENTITY
SET @Error+=@@ERROR

INSERT INTO Ac_Auditing_Template_Detail
(
	Atid,
	Summary,
	AcFrom,
	ATypeId,
	Fdc,
	BillMoneyId,
	Express,
	AssistCheckItmes,
	AssistCheckItmesIds,
	SummaryType,
	FromAtdId,
	isCost,
	OrderID
)
SELECT	
	@AtidNew,
	Summary,
	AcFrom,
	ATypeId,
	Fdc,
	BillMoneyId,
	Express,
	AssistCheckItmes,
	AssistCheckItmesIds,
	SummaryType,
	Atid,
	isCost,
	OrderID
FROM Ac_Auditing_Template_Detail
WHERE 
	Atid=@Atid
SET @Error+=@@ERROR

IF(@Error=0)
	BEGIN
		COMMIT TRAN
		RETURN 1
	END
ELSE
	BEGIN 
		ROLLBACK TRAN
		RETURN 0
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_TemplateCopyCheckAtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_TemplateCopyCheckAtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：黄清	
	日期：2013-05-09
	描述：凭证模板复制验证科目
*/
CREATE PROCEDURE Gp_TemplateCopyCheckAtype
(
    @mstypeid			VARCHAR(MAX),	--分支机构ID
	@atidlist			VARCHAR(MAX)	--凭证明细id	
)
--@encode$--
AS
SET NOCOUNT ON

--IF EXISTS(SELECT *FROM STYPE WHERE TypeId =@mstypeid AND IfAssetsIni=0) 
--AND EXISTS(SELECT *FROM Ac_Auditing_Template WHERE BillType IN (212,213,214,-1,-2) AND Atid IN (SELECT *FROM f_split(@atidlist,',')))
--BEGIN
--	RAISERROR('目标分支机构尚未进行固定资产初始化，不能对相关凭证模板进行复制',16,1)
--END

SELECT DISTINCT A.ATypeId,AC.UserCode,AC.FullName 
FROM Ac_Auditing_Template_Detail A
INNER JOIN Ac_Account AC ON A.ATypeId=AC.TypeId 
WHERE Atid IN (SELECT *FROM f_split(@atidlist,','))
AND A.ATypeId NOT IN (SELECT TypeId FROM Ac_Account WHERE StypeId=@mstypeid AND SonNum=0)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_TemplateMulStypeCopy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_TemplateMulStypeCopy]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：黄清	
	日期：2013-05-09
	描述：凭证模板复制验证科目
*/
CREATE PROCEDURE Gp_TemplateMulStypeCopy
(
    @mstypeid			VARCHAR(MAX),	--分支机构ID
	@atidlist			VARCHAR(MAX)	--凭证明细id	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @maxAtId INT
SELECT @maxAtId=MAX(AtId) FROM Ac_Auditing_Template

INSERT INTO Ac_Auditing_Template
(
	UserCode,
	FullName,
	BillType,
	ETypeId,
	IsDefault,
	CreateDateTime,
	PyCode,
	Comment,
	VgId,
	STypeId,
	Sysrow,
	FromAtid,
	Explaintext,
	ExplainAuditType,
	IsCombineRow,
	InOutType,
	ChargeOffType,
	AuditType
)
SELECT	S.UserCode+'_'+AC.UserCode,
		AC.FullName,
		BillType,
		ETypeId,
		CASE
			WHEN AC.BillType IN (212,213,214,-1,-2) AND EXISTS (SELECT TOP 1 1 FROM Ac_Auditing_Template WHERE STypeId=S.TypeId AND BillType=AC.BillType AND AuditType =AC.AuditType) THEN 0		
			WHEN AC.BillType NOT IN (212,213,214,-1,-2) AND EXISTS (SELECT TOP 1 1 FROM Ac_Auditing_Template WHERE STypeId=S.TypeId AND BillType=AC.BillType) THEN 0
			ELSE IsDefault END,
		GETDATE(),
		AC.PyCode,
		AC.Comment,
		VgId,
		S.TypeId,
		0,
		AtId,
		AC.Explaintext,
		AC.ExplainAuditType,
		AC.IsCombineRow,
		AC.InOutType,
		AC.ChargeOffType,
		AC.AuditType
FROM Ac_Auditing_Template AC
INNER JOIN SType S ON S.TypeId IN (SELECT *FROM f_split(@mstypeid,','))
WHERE AtId IN (SELECT *FROM f_split(@atidlist,','))

UPDATE Ac_Auditing_Template
SET UserCode=UserCode+'@'+CAST(AtId AS  VARCHAR(50)),FullName=FullName++'@'+CAST(AtId AS  VARCHAR(50))
WHERE AtId>@maxAtId

INSERT INTO Ac_Auditing_Template_Detail
(
	Atid,
	Summary,
	AcFrom,
	ATypeId,
	Fdc,
	BillMoneyId,
	Express,
	AssistCheckItmes,
	AssistCheckItmesIds,
	SummaryType,
	FromAtdId,
	isCost,
	OrderID
)
SELECT	AC.AtId AS Atid,
		ACD.Summary,
		ACD.AcFrom,
		ACD.ATypeId,
		ACD.Fdc,
		ACD.BillMoneyId,
		ACD.Express,
		ACD.AssistCheckItmes,
		ACD.AssistCheckItmesIds,
		ACD.SummaryType,
		ACD.AtdId,
		acd.isCost,
		acd.OrderID
FROM Ac_Auditing_Template_Detail ACD
INNER JOIN Ac_Auditing_Template AC ON ACD.Atid=AC.FromAtid AND AC.AtId NOT IN (SELECT ATID FROM Ac_Auditing_Template_Detail)
WHERE 
ACD.Atid IN (SELECT *FROM f_split(@atidlist,','))


INSERT INTO Ac_Auditing_Template_Detail_Assist_CheckItems
(
	AtdId,
	Atid,
	AssistCheckItmes,
	AssistCheckItmesIds,
	Express,
	AscIds,
	AscIdsDetailId
)
SELECT	TD.AtdId,
		T.AtId,
		A.AssistCheckItmes,
		A.AssistCheckItmesIds,
		A.Express,
		A.AscIds,
		A.AscIdsDetailId
FROM Ac_Auditing_Template_Detail_Assist_CheckItems A
INNER JOIN Ac_Auditing_Template_Detail TD ON TD.FromAtdId=A.AtdId AND TD.AtId>@maxAtId
INNER JOIN Ac_Auditing_Template T ON T.FromAtid=A.Atid AND T.AtId>@maxAtId
WHERE	A.Atid IN (SELECT *FROM f_split(@atidlist,','))

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_TerminalAdjustRate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_TerminalAdjustRate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.05.21
	描述：期末调汇
*/
CREATE PROCEDURE GP_TerminalAdjustRate
(
	@OperatorId					VARCHAR(50),			-- 当前操作员ID
	@stypeid					VARCHAR(50),			-- 分支机构
	@billdate					DATETIME,				-- 凭证日期
	@vgid						INT,					-- 凭证字
	@summary					VARCHAR(400),			-- 凭证摘要
	@choice						INT,					-- 1收益、2损失、3损益
	@ratetable TbType_Currency	READONLY, 				-- 调整的汇率
	@checkdate					INT = 1					-- 0.按分支机构期间来 1.按指定日期来
)
--@encode$--
AS
SET NOCOUNT ON



DECLARE @msg VARCHAR(1000),@sfullname VARCHAR(66)
SET @msg = ''
SELECT @sfullname = fullname FROM dbo.SType WHERE TypeId = @stypeid

--判断是否为独立分支
IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId = @stypeid AND IsSelfVerify = 0)
BEGIN
	SET @msg = '分支机构['+@sfullname+']为非独立核算分支机构，请勿选择！'
	RAISERROR(@msg,16,1)
	RETURN -1
END

--未开账
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE StypeId = @stypeid AND IsUse = 1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '未开账，操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

--取当前会计期间
DECLARE @fyear		INT,
		@fperiod	INT,
		@InitFyear	INT
SELECT @InitFyear = SubValue FROM sysdata WHERE SubName = 'FYear'
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @stypeid)
BEGIN
	SELECT @fperiod = SubValue FROM sysdata WHERE SubName = 'FPeriod'
	SELECT @fyear = SubValue FROM sysdata WHERE SubName = 'Fyear'
END
ELSE
	SELECT @fyear = fyear,@fperiod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @stypeid

IF @checkdate = 0
	SELECT @billdate = T1.FEnd FROM dbo.Ac_Period T1 INNER JOIN dbo.Ac_AccountsPeroid_Stype T2 ON T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod
	WHERE T2.Stypeid = @stypeid


--取分支汇总损益科目
DECLARE	@atypeid VARCHAR(50)-- 损益会计科目
SET @atypeid = ''
SELECT @atypeid = ATypeID3 FROM dbo.SType WHERE TypeId = @stypeid

--不存在汇兑损益科目，不能调
IF @atypeid = ''
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '未设置汇兑损益科目，调汇操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @stypeid AND TypeId = @atypeid AND Deleted = 0)
BEGIN
	RAISERROR('汇总损益科目已被停用，调汇操作中止',16,1)
	RETURN -1
END


--本期已调汇，不能调
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE FYear = @fyear AND FPeriod = @fperiod AND STypeId = @stypeid AND VoucherType = 1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '本期已进行调汇，重新调汇请先删除该凭证'
	RAISERROR(@msg,16,1)
	RETURN -1
END



--存在未过账并且没作废的凭证
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE STypeId = @stypeid AND Audited = 0 AND FChecked <> -1 AND FYear = @fyear AND FPeriod = @fperiod)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '本期凭证未全部记账，调汇操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

----不存在需要调汇的科目
--IF NOT EXISTS(	SELECT TOP 1 1
--				FROM dbo.Ac_Voucher_Bill a
--					INNER JOIN dbo.Ac_Voucher b ON a.BillNumberId = b.BillNumberId
--					INNER JOIN dbo.Ac_Account c ON (a.ATypeId = c.TypeId AND b.STypeId = c.StypeId)
--					INNER JOIN dbo.Ac_Currency d ON a.Cid = d.CId
--				WHERE 
--					a.FYear = @fyear AND a.FPeriod = @fperiod AND 
--					b.Audited = 1 AND b.FChecked <> -1 AND b.STypeId = @stypeid AND --过账的凭证才用于统计
--					c.FAdjustRate = 1)
--BEGIN
--	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
--			SET @msg = '分支机构['+@sfullname+']'
--	SET @msg = '期末调汇科目，本期未发生数据，调汇操作中止'
--	RAISERROR(@msg,16,1)
--	RETURN -1
--END

--------取期初------
SELECT DISTINCT a.ATypeId,a.cid,ISNULL(d.ascids,'') AS ascids,
				CASE WHEN b.FAcnt <> 1 THEN a.IniTotal ELSE ISNULL(c.iniTotal,0) END AS IniTotal,
				CASE WHEN b.FAcnt <> 1 THEN a.IniTotalFor ELSE ISNULL(c.iniTotalFor,0) END AS IniTotalFor,
				b.Fdc
INTO #tmpIni
FROM	Ac_IniAccount a
INNER JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND a.STypeId = b.StypeId  AND b.StypeId = @stypeid AND b.FAdjustRate = 1
LEFT JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail c ON a.ATypeId = c.ATypeId AND a.Cid = c.Cid AND c.STypeId = a.STypeId
LEFT JOIN 
(
SELECT STypeId,ATypeId,cid,dbo.F_Get_IniAccountAscids(ATypeId,groupid,cid,STypeId) ascids,GroupId 
FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail
WHERE STypeId = @stypeid
GROUP BY GroupId,STypeId,ATypeId,cid
)d ON a.stypeid = d.stypeid AND a.atypeid = d.atypeid AND a.cid = d.cid AND c.groupid = d.groupid

/*
IF @fyear > @InitFyear
BEGIN
	DELETE FROM #tmpIni
	
	INSERT INTO #tmpIni (ATypeId,
	Cid,
	ascids,
	IniTotal,
	IniTotalFor,
	Fdc)
	SELECT DISTINCT a.ATypeId,a.cid,ISNULL(c.ascids,'') AS ascids,
				CASE WHEN ISNULL(c.IniTotal,0) = 0 THEN a.FBeginBalance ELSE c.IniTotal END AS   IniTotal,
				CASE WHEN ISNULL(c.IniTotalFor,0) = 0 THEN a.FBeginBalanceFor ELSE c.IniTotalFor END AS IniTotalFor,
				b.Fdc
	FROM	dbo.Ac_Balance a
	INNER JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND a.STypeId = b.StypeId  AND b.StypeId = @stypeid AND b.FAdjustRate = 1
	LEFT JOIN 
	(
		SELECT DISTINCT IniTotal,IniTotalFor,STypeId,ATypeId,cid,dbo.F_Get_BalanceAccountAscids(ATypeId,cid,FYear,FPeriod,IniTotal) ascids,FYear,FPeriod 
		FROM dbo.Ac_Balance_Assist_CheckItems_Detail
		WHERE STypeId = @stypeid AND FYear = @fyear AND FPeriod = @fperiod
	)c ON a.STypeId = c.STypeId AND a.ATypeId = c.ATypeId AND a.Cid = c.cid AND a.FYear = c.FYear AND a.FPeriod = c.FPeriod
	WHERE a.FPeriod = @fperiod AND a.FYear = @fyear
END
*/
--------取期初和所有发生金额---
SELECT	T.atypeid,
		T.cid,
		T.Fdc,
		T.ascids,
		SUM(ISNULL(initotal,0)) AS inibenbi,
		SUM(ISNULL(initotalfor,0)) AS iniyuanbi,
		SUM(FDebittotalFor) AS jieyuanbi,
		SUM(fcredittotalfor) AS daiyuanbi,
		SUM(fdebittotal) AS jiebenbi,
		SUM(fcredittotal) AS daibenbi
INTO	#tmpData
FROM 
(
	SELECT	a.atypeid,
			a.cid,
			a.Fdc,
			dbo.f_Get_VoucherAscids(a.id,1) AS ascids,
			0 AS initotal,
			0 AS initotalfor,
			SUM(a.fdebittotalfor) AS fdebittotalfor,
			SUM(a.fcredittotalfor) AS fcredittotalfor,
			SUM(a.fdebittotal) AS fdebittotal,
			SUM(a.fcredittotal) AS fcredittotal
	FROM dbo.Ac_Voucher_Bill a
	INNER JOIN dbo.Ac_Voucher b ON a.BillNumberId = b.BillNumberId
	INNER JOIN dbo.Ac_Account c ON (a.ATypeId = c.TypeId AND b.STypeId = c.StypeId)
	INNER JOIN dbo.Ac_Currency d ON a.Cid = d.CId
	WHERE 
		(a.FYear = @fyear AND a.FPeriod <= @fperiod OR a.FYear < @fyear) AND --到当前期间的所有发生额
		b.Audited = 1 AND b.FChecked <> -1 AND b.STypeId = @stypeid AND --过账的凭证才用于统计
		c.FAdjustRate = 1 --标记调汇的科目才需要调
	GROUP BY ATypeId,a.Cid,dbo.f_Get_VoucherAscids(a.id,1),a.Fdc,FAdc
	UNION ALL
	SELECT ATypeId,Cid,Fdc,ascids,IniTotal,IniTotalFor,0,0,0,0
	FROM #tmpIni
) T
GROUP BY T.atypeid,T.cid,T.Fdc,T.ascids


-- 算原币、本币余额
SELECT CASE fdc 
			WHEN 1 THEN (iniyuanbi + jieyuanbi - daiyuanbi)
			ELSE (iniyuanbi + daiyuanbi - jieyuanbi)
		END AS yuanbiBalance,
		CASE fdc 
			WHEN 1 THEN (inibenbi + jiebenbi - daibenbi)
			ELSE (inibenbi + daibenbi - jiebenbi)
		END AS benbiBalance,
		cid,
		ATypeId,
		AscIds,
		fdc
INTO	#tmpBalance
FROM	#tmpData


--去除为0的数据
DELETE FROM #tmpBalance WHERE yuanbiBalance = 0 AND benbiBalance = 0


-- 计算损益，判断科目金额方向，余额为0的排除
SELECT  CASE WHEN a.yuanbiBalance > 0 THEN a.fdc ELSE -a.fdc END AS fdc,
		yuanbiBalance AS yuanbi,
		CONVERT( NUMERIC(24, 10) ,(dbo.f_roundtotal(CASE 
									WHEN c.basistype = 0 THEN b.newrate * ABS(yuanbiBalance)
									ELSE ABS(yuanbiBalance)/b.newrate
								END )
									- ABS(benbiBalance))) AS sunyi,
		ATypeId,
		AscIds,
		a.cid
INTO	#tmpSunyi
FROM	#tmpBalance a 
INNER JOIN @ratetable b ON a.cid = b.cid
INNER JOIN dbo.Ac_Currency c ON a.cid = c.cid
WHERE yuanbiBalance <> 0


--去除损益为0的
DELETE FROM #tmpSunyi WHERE sunyi = 0

-- 如果木有数据要调整，直接返回
IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpSunyi)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '无可调汇数据，调汇操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpSunyi WHERE sunyi <> 0)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
			SET @msg = '分支机构['+@sfullname+']'
	SET @msg += '损益为0，调汇操作中止'
	RAISERROR(@msg,16,1)
	RETURN -1
END

--生成调汇科目凭证明细部分数据（借贷金额）1.只算收益，2.只算损失，3.损益同算 
--TODO:本版本暂时默认损益同算
SELECT  ATypeId,
		SUM(yuanbi) AS totalyuanbi,
		SUM(sunyi) AS totalsunyi,
		fdc,
		AscIds,
		cid 
INTO	#tmpBill  
FROM	#tmpSunyi  
GROUP BY ATypeId,AscIds,fdc,cid


--没有数据，不生成
IF @@ROWCOUNT = 0
	RETURN -1
	
--计算损益科目（财务费用）借方金额
DECLARE @feetotal  NUMERIC(24, 10) 
SELECT	TOP 1 @feetotal = SUM(CASE WHEN fdc = -1 THEN sunyi ELSE 0 END ) - SUM(CASE WHEN fdc = 1 THEN sunyi ELSE 0 END)  FROM #tmpSunyi

--借贷总额
DECLARE @total  NUMERIC(24, 10) 
SELECT TOP 1 @total = SUM(CASE WHEN fdc = -1 THEN sunyi ELSE 0 END ) FROM #tmpSunyi

--计算分录数
DECLARE @fentrycount INT
SELECT TOP 1 @fentrycount = COUNT(*) + 1 FROM #tmpBill

--插入凭证表头
DECLARE @VoucherId INT --凭证编号

EXEC @VoucherId =	dbo.GP_SaveAc_VoucherIndex 
						@stypeid = @stypeid, -- varchar(50)
						@vgid = @vgid, -- int
						@billdate = @billdate, -- datetime
						@flowno = 1, -- int
						@attachfilecount = 0, -- int
						@etypeid = @operatorid, -- varchar(50)
						@fcredittotal = @total, -- numeric  借方总额
						@fdebittotal = @total, -- numeric   贷方总额
						@fentrycount = @fentrycount, -- int  分录数
						@type = 1	--凭证类型
DECLARE @countRow INT							 
SET @countRow = @@ROWCOUNT	

IF @VoucherId = -1
BEGIN
	RAISERROR('您使用的是试用版，凭证数量不能大于200！',16,1)
	RETURN -2
END

IF  @countRow = 0
BEGIN
	DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherId
	RAISERROR('写入主表信息错误！',16,1)
	RETURN -2
END


--取本位币ID
DECLARE @currency INT 
SELECT @currency = cid FROM dbo.Ac_Currency WHERE Sysrow = 1


--插入损益明细
CREATE TABLE #tmpVoucherBill
(
	BillNumberId         NUMERIC(18,0),
	Summary              VARCHAR(400),
	ATypeId              VARCHAR(50),
	Fdc                  INT,  
	F_ExchId	         INT,	   
	FDebitTotal           NUMERIC(24, 10) ,
	FDebitTotalFor        NUMERIC(24, 10) ,
	FCreditTotal          NUMERIC(24, 10) ,
	FCreditTotalFor       NUMERIC(24, 10) ,	   
	rowno                INT IDENTITY(1,1),
	rate				  NUMERIC(24, 10) ,
	cid					 INT,
	fadc				 INT,
	AscIds               VARCHAR(4000),
	stypeid				 VARCHAR(50),
	FYear				 INT,
	FPeriod				 INT
)	


--凭证明细临时表
INSERT INTO #tmpVoucherBill
(
	BillNumberId ,
	Summary ,
	ATypeId ,
	Fdc ,
	F_ExchId ,
	FDebitTotal ,
	FCreditTotal ,
	FDebitTotalFor ,
	FCreditTotalFor ,
	rate ,
	cid ,
	fadc,
	AscIds ,
	stypeid ,
	FYear ,
	FPeriod
)
SELECT billnumberid,summary,atypeid,fromadc,f_exchid,SUM(FDebitTotal),SUM(FCreditTotal),SUM(FDebitTotalfor),SUM(FCreditTotalfor),
		T2.Rate,T2.cid,fadc,Ascids,stypeid,fyear,fperiod
FROM
(
SELECT	@VoucherId AS billnumberid,
		@summary AS summary,
		@ATypeId AS atypeid,
		b.Fdc AS fromadc,
		@currency AS f_exchid,
		CASE WHEN a.fdc=-1 THEN dbo.F_RoundTotal(totalsunyi) ELSE 0 END AS FDebitTotal,
		CASE WHEN a.fdc=1 THEN dbo.F_RoundTotal(totalsunyi) ELSE 0 END AS FCreditTotal,
		CASE WHEN a.fdc=-1 THEN dbo.F_RoundTotal(totalsunyi) ELSE 0 END AS FDebitTotalfor,
		CASE WHEN a.fdc=1 THEN dbo.F_RoundTotal(totalsunyi) ELSE 0 END AS FCreditTotalfor,
		c.rate,
		@currency AS Cid,
		-a.fdc AS fadc,
		a.ascids,
		@StypeId AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod
FROM	#tmpBill a
INNER JOIN dbo.Ac_Account b  ON b.TypeId = @ATypeId
INNER JOIN dbo.Ac_Currency c ON a.cid = c.cid
WHERE b.StypeId = @stypeid
)T
INNER JOIN dbo.Ac_Currency T2 ON T.Cid = T2.CId
GROUP BY billnumberid,summary,atypeid,fromadc,f_exchid,T2.Rate,T2.cid,fadc,Ascids,stypeid,fyear,fperiod
UNION ALL 
--明细，添加上主表id，摘要
SELECT	@VoucherId AS billnumberid,
		@summary AS summary,
		ATypeId,
		b.Fdc AS fromadc,
		@currency AS f_exchid,
		CASE WHEN a.fdc=1 THEN totalsunyi ELSE 0 END AS FDebitTotal,
		CASE WHEN a.fdc=-1 THEN totalsunyi ELSE 0 END AS FCreditTotal,
		0 AS FDebitTotalfor,
		0 AS FCreditTotalfor,
		c.rate,
		a.cid,
		a.fdc AS fadc,
		a.ascids,
		@StypeId AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod
FROM	#tmpBill a
INNER JOIN dbo.Ac_Account b  ON a.atypeid = b.TypeId
INNER JOIN dbo.Ac_Currency c ON a.cid = c.cid
WHERE b.StypeId = @stypeid

INSERT INTO dbo.Ac_Voucher_Bill
    ( BillNumberId ,
      Summary ,
      ATypeId ,
      ATypeId2,
      Fdc ,
      F_ExchId,
      F_ExchIdFor,
      FDebitTotal,
      FCreditTotal ,
      FDebitTotalFor,
      FCreditTotalFor,
      RowNo,
      Rate,
      FAdc,
      cid,
      AscIds,
      STypeId,
      FYear,
      FPeriod
    )
SELECT billnumberid,summary,ATypeId,'',Fdc,f_exchid,cid,FDebitTotal,FCreditTotal,FDebitTotalfor,
	   FCreditTotalfor,rowno,rate,fadc,cid,ascids,STypeId,FYear,FPeriod
FROM #tmpVoucherBill


--调整并插入辅助核算
EXEC dbo.Gp_InsertAscidsAsDetails @VoucherID


--合并相同明细
DECLARE @newVoucherId INT --临时BillNumberId
SELECT @newVoucherId = -CAST(FLOOR(RAND()*100) AS INT)

SELECT  @newVoucherId AS billnumberid,
		Summary ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		SUM(FDebitTotal) AS FDebitTotal,
		SUM(FCreditTotal) AS FCreditTotal,
		SUM(FDebitTotalFor) AS FDebitTotalFor,
		SUM(FCreditTotalFor) AS FCreditTotalFor,
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		Comment ,
		Cid ,
		IDENTITY(INT,1,1) AS rowno,
		Rate ,
		FAdc ,
		STypeId ,
		FYear ,
		FPeriod
INTO #tmpNewVoucherBill
FROM dbo.Ac_Voucher_Bill
WHERE BillNumberId = @VoucherID
GROUP BY Summary,ATypeId,ATypeId2,fdc,F_ExchId,F_ExchIdFor,FCashFlowItem,AscIds,FSettleNo,FSettleTypeID,Comment,cid,Rate,FAdc,STypeId,FYear,FPeriod


DELETE #tmpNewVoucherBill WHERE FDebitTotal = 0 AND FCreditTotal = 0

--用于记录明细ID，插入辅助核算使用
CREATE TABLE #tmpId
(
	id INT,
	ascids VARCHAR(500)
)

INSERT INTO dbo.Ac_Voucher_Bill
        ( BillNumberId ,
          Summary ,
          STypeId ,
          ATypeId ,
          ATypeId2 ,
          Fdc ,
          F_ExchId ,
          F_ExchIdFor ,
          FDebitTotal ,
          FDebitTotalFor ,
          FCreditTotal ,
          FCreditTotalFor ,
          FCashFlowItem ,
          AscIds ,
          FSettleNo ,
          FSettleTypeID ,
          FYear ,
          FPeriod ,
          Comment ,
          Cid ,
          RowNo ,
          Rate ,
          FAdc
        )
OUTPUT INSERTED.ID,INSERTED.AscIds INTO #tmpId
SELECT  billnumberid,
		Summary ,
		STypeId ,
		ATypeId ,
		ATypeId2 ,
		Fdc ,
		F_ExchId ,
		F_ExchIdFor ,
		dbo.F_RoundTotal(FDebitTotal),
		dbo.F_RoundTotal(FDebitTotalFor),
		dbo.F_RoundTotal(FCreditTotal),
		dbo.F_RoundTotal(FCreditTotalFor),
		FCashFlowItem ,
		AscIds ,
		FSettleNo ,
		FSettleTypeID ,
		FYear ,
		FPeriod,
		Comment ,
		Cid ,
		rowno,
		Rate ,
		FAdc
FROM #tmpNewVoucherBill


--辅助核算
INSERT INTO dbo.Ac_Voucher_Bill_Assist_CheckItems
			( BillNumberId ,
			  vBId ,
			  typeName ,
			  TypeId
			)
SELECT DISTINCT	@newVoucherId,
		c.id,
		typeName,
		TypeId  
FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
INNER  JOIN dbo.Ac_Voucher_Bill b ON a.vBId = b.ID
INNER JOIN #tmpId c ON b.AscIds = c.ascids
WHERE a.BillNumberId = @VoucherID

DROP TABLE #tmpId,#tmpNewVoucherBill

--更新表头分录数
UPDATE dbo.Ac_Voucher SET FEntryCount = (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID) WHERE BillNumberId=@VoucherID

--删除旧分录数据
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherID

--替换临时BillNumberId为真实的
UPDATE dbo.Ac_Voucher_Bill SET BillNumberId = @VoucherID WHERE BillNumberId = @newVoucherId
UPDATE dbo.Ac_Voucher_Bill_Assist_CheckItems SET BillNumberId = @VoucherID WHERE BillNumberId = @newVoucherId

--------合并完成---------


--调整表头借贷总额、分录总数
DECLARE @DebitTotal  NUMERIC(24, 10) ,@CreditTotal  NUMERIC(24, 10) ,@TotolRow INT
SELECT @DebitTotal = SUM(FDebitTotal),@CreditTotal = SUM(FCreditTotal),@TotolRow = COUNT(*) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID
UPDATE dbo.Ac_Voucher SET FDebitTotal = @DebitTotal,FCreditTotal = @CreditTotal  WHERE BillNumberId=@VoucherID

--检测辅助核算是否完全
DECLARE @Flag INT
SET @Flag = 0

--汇总损益辅助核算类别组合值
DECLARE @typeid VARCHAR(50),@ascids INT
SET @typeid = dbo.F_Get_AscidsItem(@stypeid,@ATypeId)

DECLARE @countAssit INT
SELECT @countAssit =  COUNT(*) FROM dbo.f_split(@typeid,',')

DECLARE @rowid	INT
DECLARE AssitCur CURSOR READ_ONLY FOR 
	SELECT ID FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID AND ATypeId = @atypeid
OPEN AssitCur
FETCH NEXT FROM AssitCur INTO @rowid
WHILE (@@FETCH_STATUS = 0)
BEGIN
	IF (SELECT COUNT(*) FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a 
			INNER JOIN dbo.Ac_Voucher_Bill b ON a.vBId = b.ID AND b.ATypeId = @atypeid AND b.BillNumberId = @VoucherID AND b.ID = @rowid) < @countAssit
	BEGIN
		SET @flag = 1
	END

	FETCH NEXT FROM AssitCur INTO @rowid
END
CLOSE AssitCur
DEALLOCATE AssitCur

--检测是否要填写现金流量
IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'acpitdataflow' AND SubValue = 1)--必填现金流量
BEGIN
	DECLARE @countJie  NUMERIC(24, 10) ,@countDai  NUMERIC(24, 10) 

	SELECT @countJie = SUM(FDebitTotal),@countDai = SUM(FCreditTotal)
	FROM dbo.Ac_Voucher_Bill a
	INNER JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND a.STypeId = b.StypeId
	WHERE BillNumberId = @VoucherID AND (b.IsBank = 1 OR b.IsCash = 1 OR b.IsOther = 1)
	
	IF @countJie <> @countJie
		SET @flag = 2
END

IF @DebitTotal <> @CreditTotal
BEGIN
	SET @Flag = 3
END

--无异常，返回空数据
IF @Flag = 0
SET @VoucherID = 0

SELECT	BillDate,
		VgId,
		STypeId,
		FlowNo,
		FComment
FROM dbo.Ac_Voucher	
WHERE BillNumberId = @VoucherID

SELECT	a.Summary AS explain,
		b.UserCode,
		b.FullName,
		a.ATypeId AS typeid,
		c.Sysrow,
		a.cid,
		a.cid AS moneytype,
		c.BasisType,
		ISNULL(a.Rate,1) AS rate,
		CASE a.FAdc
			 WHEN 1		THEN a.FDebitTotalFor
			 WHEN -1	THEN a.FCreditTotalFor
		END AS balanceprice,
		CASE WHEN a.FDebitTotal = 0 THEN NULL ELSE FDebitTotal END AS lendprice,
		CASE WHEN a.FCreditTotal = 0 THEN NULL ELSE FCreditTotal END AS loanprice,
		a.FSettleNo,
		a.FSettleTypeID,
		a.Comment,
		a.STypeId,
		a.Fdc,
		a.FAdc,
		b.FAcnt,
		a.FCashFlowItem,
		a.RowNo,
		a.id,
		b.MainItems,
		b.AdditionItems,
		b.KeyId,
		b.IsCash,
		b.IsBank,
		b.IsDiary,
		b.TypeId,
		ISNULL(b.Cid,-1) AS mcid,
		b.mainitems AS mainitemsid,--主表项目id
		b.additionitems AS additionitemsid, --附表项目id
		d.fullname AS mainitemsname,--主表项目名称
		e.fullname AS additionitemsname,--附表项目名称
		dbo.F_GetAc_Assist_CheckItems_Str(a.BillNumberId,a.RowNo,'00001',1) AS assist,
		null AS asslist,
		a.FSettleNo AS balancenum,
		a.FSettleTypeID AS balancetype,
		c.UserCode,
		c.FullName
FROM dbo.Ac_Voucher_Bill a
	LEFT JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND b.StypeId = @stypeid
	LEFT JOIN dbo.Ac_Currency c ON a.Cid = c.CId
	LEFT JOIN dbo.Ac_CashMoneyItems d ON b.MainItems = d.TypeId
	LEFT JOIN dbo.Ac_CashMoneyItems e ON b.AdditionItems = e.TypeId
WHERE BillNumberId = @VoucherID

SELECT	DISTINCT a.nid,
		a.BillNumberId,
		a.vBId,
		a.typeName AS usercode,
		a.TypeId,
		CASE a.typeName
		WHEN '01' THEN (SELECT FullName FROM SType WHERE TypeId = a.TypeId)
		WHEN '02' THEN (SELECT FullName FROM Department WHERE TypeId = a.TypeId)
		WHEN '03' THEN (SELECT FullName FROM employee WHERE TypeId = a.TypeId)
		WHEN '04' THEN (SELECT FullName FROM BType WHERE TypeId = a.TypeId)
		END AS fullname,
		CASE a.typeName
		WHEN '01' THEN 'sfullname'
		WHEN '02' THEN 'dfullname'
		WHEN '03' THEN 'efullname'
		WHEN '04' THEN 'bfullname'
		END AS displayfield,
		CASE a.typeName
		WHEN '01' THEN 'stypeid'
		WHEN '02' THEN 'dtypeid'
		WHEN '03' THEN 'etypeid'
		WHEN '04' THEN 'btypeid'
		END AS datafield,
		b.AscIds AS value
FROM dbo.Ac_Voucher_Bill_Assist_CheckItems a
INNER JOIN dbo.Ac_Assist_CheckItems b ON a.typeName = b.UserCode
WHERE a.BillNumberId = @VoucherID

DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherID
DELETE FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @VoucherID
DELETE FROM dbo.Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @VoucherID

--成功，调整汇率
UPDATE dbo.Ac_Currency SET rate = newrate FROM @ratetable b WHERE dbo.Ac_Currency.cid = b.cid

DROP TABLE #tmpBill,#tmpVoucherBill
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UgLimitAddOper]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UgLimitAddOper]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-11-11
	描述：角色中添加新用户,同时复制多久权限
-------------------------------------------*/
CREATE PROCEDURE Gp_UgLimitAddOper
(
	@UgID			INT,
	@UserID			VARCHAR(MAX), --用户字符串
	@operatorID		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

--5000个0
DECLARE @Lim VARCHAR(8000)= ' '

SELECT TOP 1 @Lim = Lim FROM UserGroup WHERE UgId = @UgID

CREATE TABLE #Etype(typeid VARCHAR(50))

INSERT #Etype SELECT * FROM f_split(@UserID,',')


UPDATE loginuser SET	belongToGroup = @UgID,
						lim = ISNULL(@Lim,@Lim),
						MangerBTypeID = ISNULL(G.MangerBTypeID,'-99999') ,
						MangerBTypeID2 = ISNULL(G.MangerBTypeID2,'-99999') ,
						MangerPTypeID = ISNULL(G.MangerPTypeID,'-99999'),
						MangerKTypeID = ISNULL(G.MangerKTypeID,'-99999'),
						MangerETypeID = ISNULL(G.MangerETypeID,'-99999'),
						MangerDTypeID = ISNULL(G.MangerDTypeID,'-99999'),
						MangerSTypeID = ISNULL(G.MangerSTypeID,'-99999'),
						MangerATypeID = ISNULL(G.MangerATypeID,'-99999'),
						MangerExpense = ISNULL(G.MangerExpense,'-99999'),
						MangerIncome = ISNULL(G.MangerIncome,'-99999'),
						MangerCpaital = ISNULL(G.MangerCpaital,'-99999'),
						MangerOtherCpaital = ISNULL(G.MangerOtherCpaital,'-99999'),
						MangerLiabilities = ISNULL(G.MangerLiabilities,'-99999'),
						MangerRevenue = ISNULL(G.MangerRevenue,'-99999'),
						MangerPay = ISNULL(G.MangerPay,'-99999'),
						MangerOwnerEquity = ISNULL(G.MangerOwnerEquity,'-99999'),
						MangerBankID = ISNULL(G.MangerBankID,'-99999')
FROM loginuser L
INNER JOIN #Etype E ON E.typeid = L.etypeid
LEFT JOIN UserGroupLimit G ON G.EtypeID = @UgID

BEGIN --写入操作员权限变更日志
	SELECT etypeid,lim 
	INTO #oldloginuser 
	FROM loginuser 
	WHERE etypeid IN (SELECT typeid FROM #Etype)
	INSERT INTO LimitLog
	(
		Operator,
		Etypeid,
		oldlim,
		newlim,
		ChangeDatetime,
		ChangeEvent
	)
	SELECT	@operatorID,
			l.etypeid,
			O.lim,
			L.lim,
			GETDATE(),
			'角色管理-添加操作员'
	FROM #oldloginuser o
	INNER JOIN loginuser l ON L.etypeid=o.etypeid
END;
--BType_L
DELETE BType_L WHERE EXISTS(SELECT TOP 1 1 FROM #Etype e WHERE e.typeid = etypeid)
INSERT BType_L(etypeid,typeid,flag)
SELECT E.typeid,U.typeid,U.flag FROM UgBtype_l U,#Etype E WHERE U.etypeid = @UgID 

--PType_L
DELETE PType_L WHERE EXISTS(SELECT TOP 1 1 FROM #Etype e WHERE e.typeid = etypeid)
INSERT PType_L(etypeid,typeid,flag)
SELECT E.typeid,U.typeid,U.flag FROM UgPType_L U,#Etype E WHERE U.etypeid = @UgID 

--KType_L
DELETE KType_L WHERE EXISTS(SELECT TOP 1 1 FROM #Etype e WHERE e.typeid = etypeid)
INSERT KType_L(etypeid,typeid,flag)
SELECT E.typeid,U.typeid,U.flag FROM UgKType_L U,#Etype E WHERE U.etypeid = @UgID 

--EType
DELETE EType_L WHERE EXISTS(SELECT TOP 1 1 FROM #Etype e WHERE e.typeid = etypeid)
INSERT EType_L(etypeid,typeid,flag)
SELECT E.typeid,U.typeid,U.flag FROM UgEType_L U,#Etype E WHERE U.etypeid = @UgID 

--DType_L
DELETE DType_L WHERE EXISTS(SELECT TOP 1 1 FROM #Etype e WHERE e.typeid = etypeid)
INSERT DType_L(etypeid,typeid,flag)
SELECT E.typeid,U.typeid,U.flag FROM UgDType_L U,#Etype E WHERE U.etypeid = @UgID 

--SType_L
DELETE SType_L WHERE EXISTS(SELECT TOP 1 1 FROM #Etype e WHERE e.typeid = etypeid)
INSERT SType_L(etypeid,typeid,flag)
SELECT E.typeid,U.typeid,U.flag FROM UgSType_L U,#Etype E WHERE U.etypeid = @UgID 

--AType_L
DELETE AType_L WHERE EXISTS(SELECT TOP 1 1 FROM #Etype e WHERE e.typeid = etypeid)
INSERT AType_L(etypeid,typeid,flag,type)
SELECT E.typeid,U.typeid,U.flag,U.type FROM UgAType_L U,#Etype E WHERE U.etypeid = @UgID 

--Bank_l
DELETE Bank_l WHERE EXISTS(SELECT TOP 1 1 FROM #Etype e WHERE e.typeid = etypeid)
INSERT Bank_l(etypeid,typeid,flag)
SELECT E.typeid,U.typeid,U.flag FROM UgBank_l U,#Etype E WHERE U.etypeid = @UgID 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UgLimitCopyToLoginUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UgLimitCopyToLoginUser]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-11-10
	描述：把用户角色的权限复制到操着员的权限中
-------------------------------------------*/
CREATE PROCEDURE Gp_UgLimitCopyToLoginUser
(
	@UgID			INT,
	@Type			INT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE 
		@ManTypeIDName VARCHAR(50), 
		@TableName VARCHAR(50)			-- 对应的_l表, 每个type对应一个type_l表

-- 分类选择权限表
--BType
IF @Type IN (0,1)
BEGIN
	SET @TableName = 'BType_L'
	IF @Type = 0
		SET @ManTypeIDName = 'MangerBTypeID'
	ELSE
		SET @ManTypeIDName = 'MangerBTypeID2'
END
-- PType
ELSE IF @Type = 2
BEGIN
	SET @TableName = 'PType_L'
	SET @ManTypeIDName = 'MangerPTypeID'
END
-- KType
ELSE IF @Type = 3
BEGIN
	SET @TableName = 'KType_L'
	SET @ManTypeIDName = 'MangerKTypeID'
END
-- EType
ELSE IF @Type = 4
BEGIN
	SET @TableName = 'EType_L'
	SET @ManTypeIDName = 'MangerETypeID'
END
-- DType
ELSE IF @Type = 9
	BEGIN
		SET @TableName = 'DType_L'
		SET @ManTypeIDName = 'MangerDTypeID'
	END
--SType
ELSE IF @Type = 10
BEGIN
	SET @TableName = 'SType_L'
	SET @ManTypeIDName = 'MangerSTypeID'
END
--Bank_L
ELSE IF @Type = 16
BEGIN
	SET @TableName = 'Bank_L'
	SET @ManTypeIDName = 'MangerBankID'
END
-- others
ELSE
BEGIN
	SET @TableName = 'AType_L'
	IF @Type = 5
	BEGIN
		SET @ManTypeIDName = 'MangerATypeID' --银行账户
	END
	ELSE IF @Type = 6
	BEGIN
		SET @ManTypeIDName = 'MangerExpense' --费用
	END
	ELSE IF @Type = 7
	BEGIN
		SET @ManTypeIDName = 'MangerIncome'  --收入
	END
	ELSE IF @Type=8
	BEGIN
		SET @ManTypeIDName = 'MangerCpaital' --固定资产
	END
	ELSE IF(@Type=11)
	BEGIN
		SET @ManTypeIDName = 'MangerOtherCpaital'  --其他资产
	END
	ELSE IF(@Type=12)
	BEGIN
		SET @ManTypeIDName = 'MangerLiabilities'  --负债
	END
	ELSE IF(@Type=13)
	BEGIN
		SET @ManTypeIDName = 'MangerRevenue'  --全部收入
	END
	ELSE IF(@Type=14)
	BEGIN
		SET @ManTypeIDName = 'MangerPay'  --支出
	END
	ELSE IF(@Type=15)
	BEGIN
		SET @ManTypeIDName = 'MangerOwnerEquity'  --所有者权益
	END
END

DECLARE @SQL VARCHAR(MAX)=''
--操着员权限
CREATE TABLE #Etype(typeid VARCHAR(50),ugid INT)
INSERT #Etype(typeid,ugid)
SELECT L.etypeid,@UgID
FROM loginuser L
INNER JOIN UserGroupLimit U ON U.EtypeID = L.belongToGroup
WHERE U.EtypeID = @UgID

SET @SQL = 
	'
		UPDATE loginuser SET '+@ManTypeIDName+' = u.'+@ManTypeIDName+'
		FROM loginuser L
		INNER JOIN UserGroupLimit U ON U.EtypeID = L.belongToGroup 
		INNER JOIN #Etype e ON e.ugid = u.etypeid   '
EXEC(@SQL)


IF @TableName = 'AType_L'
BEGIN
	DELETE AType_L WHERE EXISTS(SELECT TOP 1 1 FROM #Etype E WHERE E.typeid = etypeid)
	INSERT AType_L(etypeid,typeid,flag,type)
	SELECT e.typeid,a.typeid,a.flag,a.type
	FROM UgAType_L a
	INNER JOIN #Etype e ON e.ugid = a.etypeid
END
ELSE
BEGIN
	SET @SQL = 
	'
		DELETE '+@TableName+' WHERE EXISTS(SELECT TOP 1 1 FROM #Etype E WHERE E.typeid = etypeid)
		INSERT '+@TableName+' (etypeid,typeid,flag)
		SELECT e.typeid,a.typeid,a.flag
		FROM Ug'+@TableName+' a
		INNER JOIN #Etype e ON e.ugid = a.etypeid '
END

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Etype

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UgModify]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UgModify]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-11-11
	描述：角色中修改用户组
-------------------------------------------*/
CREATE PROCEDURE Gp_UgModify
(
	@UgID			INT,
	@UgName			VARCHAR(500),
	@UgComment		VARCHAR(500),
	@ListStr		VARCHAR(MAX),--在分组的用户
	@ListUnStr		VARCHAR(MAX),--没在分组的用户
	@operatorID		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Etype(typeid VARCHAR(50))
	INSERT #Etype SELECT * FROM f_split(@ListStr,',')

CREATE TABLE #UnEtype(typeid VARCHAR(50))
	INSERT #UnEtype SELECT * FROM f_split(@ListUnStr,',')

IF EXISTS(SELECT TOP 1 1 FROM UserGroup WHERE ugname=@UgName AND UgId<>@UgID)
	RETURN 3  --角色名称已存在,请重新输入！

--修改角色名称
UPDATE UserGroup SET ugname = @UgName, Comment = @UgComment WHERE UgId = @UgID


--筛选本次新添加的角色职员
--组成字符串
DECLARE @UserID VARCHAR(MAX) = ''

SELECT @UserID = @UserID + E.typeid + ','
FROM #Etype E
WHERE NOT EXISTS(SELECT top 1 1 FROM loginuser l WHERE l.etypeid=e.typeid AND L.belongToGroup=@UgID)

--更新新添加的职员权限
IF ISNULL(@UserID,'') <> ''
	EXEC Gp_UgLimitAddOper @UgID=@UgID, @UserID=@UserID	,@operatorID=@operatorID


--本次角色职员中去掉的职员
UPDATE loginuser SET belongToGroup = 0
FROM #UnEtype A,loginuser
WHERE A.typeid = loginuser.etypeid AND loginuser.belongToGroup = @UgID


RETURN 1 --角色修改成功

DROP TABLE #Etype,#UnEtype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UnCheckBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UnCheckBill]
GO



/*
	作者：谢吉康
	日期：2007-3-6
	描述：反审核单据
*/
CREATE PROCEDURE Gp_UnCheckBill
(
	@OperatorId		varchar(100),
	@BillNumberId	varchar(100),
	@BillType		varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON
--判断单据是否有审核流程
IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)
	RETURN -6

--判断单据是否提交审核
IF @BillType IN (300,301,313)
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 0)
			RETURN -7
	END
ELSE IF @BillType IN (71,72,87,88)
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 1)
			RETURN -7
	END
ELSE IF @BillType IN (311)
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 4)
			RETURN -7
	END
ELSE IF @BillType IN(404,405)
	BEGIN
		IF NOT EXISTS (SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberID=@BillNumberId AND BillIndexType=5)
			RETURN -7
	END
ELSE IF @BillType IN(418,419,420)
	BEGIN
		IF NOT EXISTS (SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberID=@BillNumberId AND BillIndexType=7)
			RETURN -7
	END
ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 2 AND @billType<>204 or BillIndexType = 3 AND @BillType=204)
			RETURN -7
	END
--判断是否在审核人的列表中
IF @OperatorId<>'00001'
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail WHERE BillType = @BillType)
			RETURN -2
	END

--根据不同的单据进行判断
IF @BillType IN (300,301,313)
	BEGIN
		--判断是否是审核不通过的草稿
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType = 0 AND IfAudit = -1 AND BillNumberId = @BillNumberId)
			RETURN -1

		--判断订单是否已经被调用过
		IF @BillType = 300
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM SaleBill S 
							INNER JOIN BillIndex BI ON S.BillNumberId=BI.BillNumberId
							WHERE S.OrderID IN (SELECT OrderId FROM OrderBill WHERE BillNumberId =  @BillNumberId) 
							AND BI.RedWord='0')
					RETURN -4				
			END
		ELSE
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM BuyBill B
							INNER JOIN BillIndex BI ON B.BillNumberId=BI.BillNumberId 
							WHERE B.orderid IN (SELECT OrderId FROM OrderBill WHERE BillNumberId =  @BillNumberId)
							AND BI.RedWord='0')
					RETURN -4
			END
	END
ELSE IF @BillType IN (71,72,87,88)
	BEGIN
		--判断是否是审核不通过的草稿
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType = 1 AND IfAudit = -1 AND BillNumberId = @BillNumberId)
			RETURN -1
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType = 1 AND IfAudit =  0 AND BillNumberId = @BillNumberId)
			RETURN -9
		IF EXISTS(SELECT TOP 1 1 FROM dbo.LendIndex WHERE BillNumberId=@BillNumberId AND IfCheck='t')
			RETURN -3
	END
ELSE IF @BillType IN (204)
	BEGIN
		IF EXISTS(SELECT 1 FROM AuditingBill WHERE BillIndexType = 3 AND IfAudit = -1 AND BillNumberId = @BillNumberId)
			RETURN -1
		--已处理
		IF EXISTS(SELECT 1 FROM  RequestBill WHERE BillNumberId=@BillNumberId AND State<>1)
			RETURN -8
	END
ELSE IF @BillType IN (311)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType = 4 AND IfAudit = -1 AND BillNumberId = @BillNumberId)
			RETURN -1
		IF EXISTS(SELECT TOP 1 1 FROM  CommissionBillNew WHERE BillNumberId=@BillNumberId AND IfCheck='t')
			RETURN -3
	END
ELSE IF @BillType IN (404,405)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType=5 AND IfAudit=-1 AND BillNumberID=@BillNumberId)
			RETURN -1
		IF EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberID=@BillNumberId AND ifcheck='t')
			RETURN -3
	END
ELSE IF @BillType IN (418,419,420)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType=7 AND IfAudit=-1 AND BillNumberID=@BillNumberId)
			RETURN -1
		IF EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberID=@BillNumberId AND ifcheck='t')
			RETURN -3
	END
ELSE
	BEGIN
		--判断是否是审核不通过的草稿
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = -1 AND BillNumberId = @BillNumberId)
			RETURN -1

		--判断单据是否已经过帐
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE IfCheck='t' AND BillNumberId = @BillNumberId)
			RETURN -3
	END

--删除审核历史
BEGIN TRAN DEL
IF @BillType IN (300,301,313)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType = 0 AND BillNumberId = @BillNumberId)
			BEGIN
				UPDATE	OrderIndex SET IfAudit = 0 WHERE BillNumberId = @BillNumberId
				DELETE FROM AuditingBillDetail WHERE BillNumberID=@BillNumberId AND BillIndexType=0
				DELETE FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 0
			END
	END
ELSE IF @BillType IN (71,72,87,88)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType = 1 AND BillNumberId = @BillNumberId)
			BEGIN
				UPDATE LendIndex SET IfAudit = 0 WHERE BillNumberId = @BillNumberId
				DELETE FROM AuditingBillDetail WHERE BillNumberID=@BillNumberId AND BillIndexType=1
				DELETE FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 1
			END
	END
ELSE IF @billType IN (204)
	BEGIN --请购单特殊
		DELETE FROM AuditingBillDetail WHERE BillNumberID=@BillNumberId AND BillIndexType=3
		DELETE FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 3
	END
ELSE IF @billType IN (311)
	BEGIN --提成单
		DELETE FROM AuditingBillDetail WHERE BillNumberID=@BillNumberId AND BillIndexType=4
		DELETE FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 4
		UPDATE CommissionBillNew SET Checker = '', CheckerTime=NULL , BillState = 1 ,FChecker = @OperatorId , FCheckerTime=GETDATE() WHERE BillNumberId = @BillNumberId
	END
ELSE IF @BillType IN(404,405)
	BEGIN
		DELETE FROM AuditingBillDetail WHERE BillNumberID=@BillNumberId AND BillIndexType=5
		DELETE FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 5
		UPDATE ReceiptBillIndex SET IfAudit=0,Assessor='' WHERE BillNumberID=@BillNumberID
	END
ELSE IF @BillType IN(418,419,420)
	BEGIN
		DELETE FROM AuditingBillDetail WHERE BillNumberID=@BillNumberId AND BillIndexType=7
		DELETE FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 7		
	END	
ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AuditingBill WHERE BillIndexType = 2 AND BillNumberId = @BillNumberId)
			BEGIN
				DELETE FROM AuditingBillDetail WHERE BillNumberID=@BillNumberId AND BillIndexType=2
				DELETE FROM AuditingBill WHERE BillNumberId = @BillNumberId AND BillIndexType = 2
				/*
				--特殊处理调价全部仓库
				IF @BillType = 57
					UPDATE	adPriceBill SET ChangeAllStock = 0 WHERE BillNumberId = @BillNumberId
				*/
			END
	END
	
IF @@error <> 0
BEGIN
	ROLLBACK TRAN del
	RETURN -5
END
COMMIT TRAN del
RETURN 0












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_UnitIsUsed]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UnitIsUsed]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
--判断商品单位是否使用过
--By HQing
--Data: 2013年11月12日
CREATE    PROCEDURE [dbo].[GP_UnitIsUsed]
( 
	@UnitId		VARCHAR(50),
	@PTYPEID	VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

--OR c.[name]='UnitID'
DECLARE @TableName VARCHAR(128)
DECLARE @fname VARCHAR(400)
DECLARE @FullName VARCHAR(400)
DECLARE @existRecORd INT;
DECLARE @sqlQuery NVARCHAR(2000)

SELECT @FullName=FullName FROM PType_Units WHERE UnitsId=@UnitId


IF EXISTS(SELECT *FROM PriceTrack WHERE PtypeID=@PTYPEID AND UID=@UnitId)
BEGIN
	RAISERROR('该商品的该单位【%s】已价格跟踪中使用过不允许修改或删除',16,1,@FullName) 
END 
DECLARE Unit_CURSOR CURSOR
FOR SELECT o.[name] AS tablename FROM syscolumns c 
	INNER JOIN sysobjects o ON(c.[id]=o.[id]) 
	WHERE c.[name]='MUnitID' AND o.type='u'
	AND O.[name] IN (SELECT o1.[name]  FROM syscolumns C1 INNER JOIN sysobjects o1 ON(c1.[id]=o1.[id]) WHERE C1.name='ptypeid' AND O1.type='u')
FOR READ ONly
OPEN Unit_CURSOR
FETCH NEXT FROM Unit_CURSOR INTO  @TableName

WHILE @@FETCH_status=0
	BEGIN
		
	SET @existRecORd = 0;
	SET @sqlQuery = 'set @existRecORd = cASe when exists (SELECT top 1 1 FROM  '+ @TableName +' WHERE MUnitID='''+@UnitId+''' AND ptypeid='''+@PTYPEID+''') then 1 else 0 end;';
	EXEC sp_executesql @sqlQuery,N'@existRecORd int OUTPUT',@existRecORd OUTPUT;
	IF @existRecORd  = 1
		BEGIN
			--采购订单 和 销售订单 都是orderbill		
			IF @TableName='orderbill'
				SET @fname=(SELECT TOP 1 BN.BILLNAME FROM ORDERINDEX IX 
					INNER JOIN OrderBill OB ON IX.BILLNUMBERID=OB.BILLNUMBERID 
					LEFT JOIN BILLNAME BN ON BN.BILLTYPE=IX.BILLTYPE
					WHERE OB.PTYPEID=@PTYPEID)
	
			ELSE 
				SET @fname=(SELECT TOP 1 BillName FROM BillName WHERE detailTable=@TableName)
			IF @fname IS NULL OR @fname=''
			BEGIN
				SET @fname='被'
			END
			ELSE
			BEGIN
				SET @fname='在'+@fname+'中'
			END
			RAISERROR('该商品的该单位【%s】已%s使用过不允许修改或删除',16,1,@FullName, @fname) 
			return
		end 
	FETCH NEXT FROM Unit_CURSOR INTO  @TableName
	end
Close Unit_CURSOR
Deallocate Unit_CURSOR

--基本单位判断
DECLARE Unit_CURSOR1 CURSOR
FOR SELECT o.[name] AS tablename FROM syscolumns c 
	INNER JOIN sysobjects o ON(c.[id]=o.[id]) 
	WHERE c.[name]='UnitID' AND o.type='u'
	AND O.[name] IN (SELECT o1.[name]  FROM syscolumns C1 INNER JOIN sysobjects o1 ON(c1.[id]=o1.[id]) WHERE C1.name='ptypeid' AND O1.type='u')
FOR READ ONly
OPEN Unit_CURSOR1
FETCH NEXT FROM Unit_CURSOR1 INTO  @TableName
WHILE @@FETCH_status=0
	BEGIN
		
	SET @existRecORd = 0;
	IF(@TableName<>'PType_Price' and @TableName<>'PType_STypePrice' and  @TableName<>'PType_TranslateRates')
	SET @sqlQuery = 'set @existRecORd = cASe when exists (SELECT top 1 1 FROM  '+ @TableName +' WHERE UnitID='''+@UnitId+''' AND ptypeid='''+@PTYPEID+''') then 1 else 0 end;';
	EXEC sp_executesql @sqlQuery,N'@existRecORd int OUTPUT',@existRecORd OUTPUT;
	IF @existRecORd  = 1
		BEGIN	 
	        --PRINT @existRecORd 	
			SELECT @FullName=FullName FROM PType_Units WHERE UnitsId=@UnitId
			SET @fname=(SELECT TOP 1 BillName FROM BillName WHERE detailTable=@TableName)
			IF @fname IS NULL OR @fname=''
			BEGIN
				SET @fname='被'
			END
			ELSE
			BEGIN
				SET @fname='在'+@fname+'中'
			END
			RAISERROR('该商品的该单位【%s】已%s使用过不允许修改或删除',16,1,@FullName, @fname) 
			return
		end
		
	FETCH NEXT FROM Unit_CURSOR1 INTO  @TableName
	end
Close Unit_CURSOR1
Deallocate Unit_CURSOR1

--浮动单位判断
DECLARE Unit_CURSOR2 CURSOR
FOR SELECT o.[name] AS tablename FROM syscolumns c 
	INNER JOIN sysobjects o ON(c.[id]=o.[id]) 
	WHERE c.[name]='NUnitID' AND o.type='u'
	AND O.[name] IN (SELECT o1.[name]  FROM syscolumns C1 INNER JOIN sysobjects o1 ON(c1.[id]=o1.[id]) WHERE C1.name='ptypeid' AND O1.type='u')
FOR READ ONly
OPEN Unit_CURSOR2
FETCH NEXT FROM Unit_CURSOR2 INTO  @TableName
WHILE @@FETCH_status=0
	BEGIN
			
	SET @existRecORd = 0;
	SET @sqlQuery = 'set @existRecORd = cASe when exists (SELECT top 1 1 FROM  '+ @TableName +' WHERE NUnitID='''+@UnitId+''' AND ptypeid='''+@PTYPEID+''') then 1 else 0 end;';
	EXEC sp_executesql @sqlQuery,N'@existRecORd int OUTPUT',@existRecORd OUTPUT;

	IF @existRecORd  = 1
		BEGIN	
			--PRINT @TableName	
			SELECT @FullName=FullName FROM PType_Units WHERE UnitsId=@UnitId
			SET @fname=(SELECT TOP 1 BillName FROM BillName WHERE detailTable=@TableName)
			IF @fname IS NULL OR @fname=''
			BEGIN
				SET @fname='被'
			END
			ELSE
			BEGIN
				SET @fname='在'+@fname+'中'
			END
			RAISERROR('该商品的该单位【%s】已%s使用过不允许修改或删除',16,1,@FullName, @fname) 
			return
		end
		
	FETCH NEXT FROM Unit_CURSOR2 INTO  @TableName
	end
Close Unit_CURSOR2
Deallocate Unit_CURSOR2
 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO



IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_UnitIsUsedRtInt]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UnitIsUsedRtInt]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
--判断商品单位是否使用过
--By HQing
--Data: 2013年11月12日
CREATE    PROCEDURE [dbo].[GP_UnitIsUsedRtInt]
( 
	@UnitId		VARCHAR(50),
	@PTYPEID	VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

--OR c.[name]='UnitID'
DECLARE @TableName VARCHAR(128)
DECLARE @fname VARCHAR(400)
DECLARE @FullName VARCHAR(400)
DECLARE @existRecORd INT;
DECLARE @sqlQuery NVARCHAR(2000)
DECLARE @rtvalue INT
SELECT @FullName=FullName FROM PType_Units WHERE UnitsId=@UnitId

SET @rtvalue=0
IF EXISTS(SELECT *FROM PriceTrack WHERE PtypeID=@PTYPEID AND UID=@UnitId)
BEGIN
	RETURN 0
END 
DECLARE Unit_CURSOR CURSOR
FOR SELECT o.[name] AS tablename FROM syscolumns c 
	INNER JOIN sysobjects o ON(c.[id]=o.[id]) 
	WHERE c.[name]='MUnitID' AND o.type='u'
	AND O.[name] IN (SELECT o1.[name]  FROM syscolumns C1 INNER JOIN sysobjects o1 ON(c1.[id]=o1.[id]) WHERE C1.name='ptypeid' AND O1.type='u')
FOR READ ONly
OPEN Unit_CURSOR
FETCH NEXT FROM Unit_CURSOR INTO  @TableName

WHILE @@FETCH_status=0
	BEGIN
		
	SET @existRecORd = 0;
	SET @sqlQuery = 'set @existRecORd = cASe when exists (SELECT top 1 1 FROM  '+ @TableName +' WHERE MUnitID='''+@UnitId+''' AND ptypeid='''+@PTYPEID+''') then 1 else 0 end;';
	EXEC sp_executesql @sqlQuery,N'@existRecORd int OUTPUT',@existRecORd OUTPUT;

	IF @existRecORd  = 1
		BEGIN	 
			SET @rtvalue=1
		end
		
	FETCH NEXT FROM Unit_CURSOR INTO  @TableName
	end
Close Unit_CURSOR
Deallocate Unit_CURSOR

--基本单位判断
DECLARE Unit_CURSOR1 CURSOR
FOR SELECT o.[name] AS tablename FROM syscolumns c 
	INNER JOIN sysobjects o ON(c.[id]=o.[id] AND o.name<>'PType_Price' AND o.name<>'PType_TranslateRates' and  o.name<>'PType_stypePrice') 
	WHERE c.[name]='UnitID' AND o.type='u'
	AND O.[name] IN (SELECT o1.[name]  FROM syscolumns C1 INNER JOIN sysobjects o1 ON(c1.[id]=o1.[id]) WHERE C1.name='ptypeid' AND O1.type='u')
FOR READ ONly
OPEN Unit_CURSOR1
FETCH NEXT FROM Unit_CURSOR1 INTO  @TableName
WHILE @@FETCH_status=0
	BEGIN 
	SET @existRecORd = 0;
	 
	 
	SET @sqlQuery = 'set @existRecORd = cASe when exists (SELECT top 1 1 FROM  '+ @TableName +' WHERE UnitID='''+@UnitId+''' AND ptypeid='''+@PTYPEID+''') then 1 else 0 end;';
	EXEC sp_executesql @sqlQuery,N'@existRecORd int OUTPUT',@existRecORd OUTPUT;

	IF @existRecORd  = 1
		BEGIN	  
		 PRINT @TableName
			SET @rtvalue=1
		end
		
	FETCH NEXT FROM Unit_CURSOR1 INTO  @TableName
	 
	end
Close Unit_CURSOR1
Deallocate Unit_CURSOR1

--浮动单位判断
DECLARE Unit_CURSOR2 CURSOR
FOR SELECT o.[name] AS tablename FROM syscolumns c 
	INNER JOIN sysobjects o ON(c.[id]=o.[id]) 
	WHERE c.[name]='NUnitID' AND o.type='u'
	AND O.[name] IN (SELECT o1.[name]  FROM syscolumns C1 INNER JOIN sysobjects o1 ON(c1.[id]=o1.[id]) WHERE C1.name='ptypeid' AND O1.type='u')
FOR READ ONly
OPEN Unit_CURSOR2
FETCH NEXT FROM Unit_CURSOR2 INTO  @TableName
WHILE @@FETCH_status=0
	BEGIN
			
	SET @existRecORd = 0;
	SET @sqlQuery = 'set @existRecORd = cASe when exists (SELECT top 1 1 FROM  '+ @TableName +' WHERE NUnitID='''+@UnitId+''' AND ptypeid='''+@PTYPEID+''') then 1 else 0 end;';
	EXEC sp_executesql @sqlQuery,N'@existRecORd int OUTPUT',@existRecORd OUTPUT;

	IF @existRecORd  = 1
		BEGIN	 
		SET @rtvalue=1 
		end
		
	FETCH NEXT FROM Unit_CURSOR2 INTO  @TableName
	end
Close Unit_CURSOR2
Deallocate Unit_CURSOR2
	--PRINT @existRecORd
	SELECT  @rtvalue
RETURN  @rtvalue
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UnStockCheck_AutoCreate]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[GP_UnStockCheck_AutoCreate]
GO





/*

功能说明：		生成盘点单

作    者：       冯波

修改日期：       2008-10-07

返回结果：       

*/

CREATE PROCEDURE [dbo].[GP_UnStockCheck_AutoCreate]
(
	@chvOperatorID				VARCHAR(100),			--登陆员ID
	@chvPTypeID					VARCHAR(1550),			--商品类别查询范围父节点 ID
	@chvKTypeID					VARCHAR(50),			--仓库
	@chvStartDate				VARCHAR(30),			--查询起始时间
	@chvENDDate					VARCHAR(30),			--查询结束时间
	@intRange					TINYINT,				--统计范围:0包含账面数量不为0的商品,1包含账面数量为0，且本仓库有历史库存的商品,2包含账面数量为0，且含本仓库没有历史库存的商品
	@strReturnBillCode			VARCHAR(8000) OUT,
	@type						INT=1,					--盘点维修品库(0=正常，1=维修)
	@chkPf                      INT 
	
)
--@encode$--
AS

SET @strReturnBillCode=''

IF @chvOperatorID IS NULL RETURN 1
IF (@chvKTypeID='') OR (CHARINDEX(',',@chvKTypeID)>0) RETURN 1


DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT



DECLARE @stid VARCHAR(100)
SELECT TOP 1 @stid=stypeid FROM stock WHERE typeId=@chvKTypeID

IF @Re<>0 RETURN @Re

CREATE TABLE #Ptype (TypeID varchar(50),SonNum INT ,UserCode VARCHAR(300),IsService INT)

IF @chvPTypeID =''
	INSERT INTO #Ptype(typeid,SonNum,UserCode,IsService) select p.typeid,p.sonnum,p.UserCode,p.IsService from F_GetManDetailPType(@chvOperatorID) mp INNER JOIN ptype p ON mp.TypeId=p.typeId WHERE ((@chkPf=0 AND deleted=0) OR @chkPf=1 ) AND p.iscombinationproduct = 0
ELSE
	INSERT INTO #Ptype(typeid,SonNum,UserCode,IsService)
	SELECT p.typeId,p.sonnum,p.UserCode,p.IsService FROM F_GetAllManagerBaseTypeId(@chvPtypeID,1,@chvOperatorID) mp INNER JOIN  ptype p ON mp.TypeId=p.typeId  WHERE ((@chkPf=0 AND deleted=0) OR @chkPf=1)  AND p.iscombinationproduct = 0
	 --select a.typeid from F_GetManDetailPType(@chvOperatorID) a, (select * from  dbo.f_split(@chvPtypeID,',')) b where left(a.typeid,len(b.a))=b.a

CREATE TABLE #table_StockCheck(
								PTypeID	VARCHAR(50),
								Qty  NUMERIC(24, 10) ,
								[GoodsNumber] [varchar](100) ,
								[ProduceDate] [varchar](50),
								[ValidDate] [varchar](50) ,
								[GoodsBTypeID] [varchar](50) ,
								cargoid INT,
								ItemID INT,
								Iscombined	INT,
								Nqty  NUMERIC(24, 10) , 
								Price  NUMERIC(24, 10) , 
								AutoID INT IDENTITY (1, 1) NOT NULL)

DECLARE
	@strSql				VARCHAR(MAX),
	@costing			INT,
	@ColumnList			VARCHAR(MAX),
	@defaultCargoId		INT
SELECT TOP 1 @costing=SubValue  FROM  sysdata WHERE SubName='costing'
SET @ColumnList=''
IF @costing=3   SET @ColumnList=',Price'
/*取成本算法*/---------------------------------------------------------------------------------------------------

SET @defaultCargoId=0
IF (SELECT TOP 1 Value FROM Userconfig  where ConfigName='mngcargospace')=0
	SELECT @defaultCargoId=CargoID FROM CargoType where IsDefault=1 AND KtypeID=@chvKTypeID
/*取默认的货位*/---------------------------------------------------------------------------------------------

SELECT TOP 1 @costing=SubValue  FROM sysdata  where SubName='costing'




--不包括停用商品
SELECT @strSql='	
	INSERT #table_StockCheck(PTypeID,Qty,[GoodsNumber],[ProduceDate],[ValidDate],[GoodsBTypeID],cargoid,ItemID,Iscombined,Nqty '+@ColumnList+')
	SELECT a.TypeID,ISNULL(c.Qty ,0) AS Qty,
			ISNULL(GoodsNumber,'''') as GoodsNumber ,
			ISNULL(ProduceDate,'''') as ProduceDate,
			ISNULL(ValidDate,'''') as ValidDate,
			''''  as GoodsBTypeID,'
IF @type=1
	SELECT @strSql+=' 0 as cargoid,'
else 
BEGIN			
	IF (SELECT TOP 1 Value FROM Userconfig  where ConfigName='mngcargospace')=0		
		SELECT @strSql+=' 
				(CASE WHEN ISNULL(cargoid,0)=0 THEN '+CAST(@defaultCargoId as VARCHAR)+' ELSE cargoid END ) as cargoid,'
	else 
		SELECT @strSql+='	cargoid,'
END	
				
SELECT @strSql+='
			ItemID,
			Iscombined,
			Nqty 
			'+@ColumnList+'
	
	'+CHAR(10)

	SET @strSql = @strSql + '	FROM  #Ptype a '+CHAR(10)


--关联库存状况表
SELECT @strSql=@strSql+'	LEFT JOIN	
	(
		SELECT	gq.PTypeID,
				ISNULL(gq.GoodsNumber,'''') as GoodsNumber ,
				ISNULL(gq.ProduceDate,'''') as ProduceDate,
				ISNULL(gq.ValidDate,'''') as ValidDate, '
		IF @type=1 
		BEGIN		
			IF @costing=3 	SET @strSql+='gq.Price as Price,'	
			SET @strSql+=' gq.ItemID,gq.Iscombined, SUM(gq.Qty) AS Qty,SUM(gq.Nqty) as nqty '	
			SET @strSql+=CHAR(10)+' FROM   Wx_GoodsStocks gq '	
		END	
		ELSE
		BEGIN
			IF @costing=3 	SET @strSql+='gq.GoodsCostPrice as Price,'	
			SET @strSql+='gq.CargoID,gq.ItemID,gq.Iscombined,SUM(gq.Qty) AS Qty,SUM(gq.Nqty) as nqty ' 
			SET @strSql+=CHAR(10)+'	FROM  GOODSSTOCKS_QTY gq '	
		END	

		SET @strSql=@strSql+'
			WHERE gq.KTypeID='+CHAR(39)+@chvKTypeID+CHAR(39)+' and (gq.qty<>0 or gq.nqty<>0)
			GROUP BY gq.PTypeID,gq.GoodsNumber,gq.ProduceDate,gq.ValidDate'
		IF @type=1 
  			SET @strSql+=',gq.Price'
		eLSE 
  			SET @strSql+=',gq.GoodsCostPrice,gq.CargoID'

		SET @strSql+=',gq.ItemID,gq.Iscombined'

SET @strSql+=CHAR(10)+'	) c 	ON a.TypeID=c.PTypeID '+CHAR(10)



SELECT @strSql=@strSql+'	WHERE a.SonNum=0 AND a.isservice=0 AND a.TypeID NOT IN
		(
			SELECT DISTINCT PTypeID
			FROM StockCheck a
			INNER JOIN StockCheckIndex b
			ON a.StockCheckID=b.StockCheckID
			AND	b.KTypeID='+CHAR(39)+@chvKTypeID+CHAR(39)+'
			AND b.ifWX='+CHAR(39)+CONVERT(VARCHAR(10),@type)+CHAR(39)+''
SELECT @strSql=@strSql+'				
			AND b.BillDate BETWEEN '+CHAR(39)+@chvStartDate+CHAR(39)+'	AND '+CHAR(39)+@chvEndDate+CHAR(39)+'
		)	'+CHAR(10)

IF @intRange<>2
BEGIN
	SELECT @strSql=@strSql+'
		AND a.TypeID IN
			(
				SELECT a.PTypeID
				FROM
				(
					SELECT PTypeID,SUM(Qty) AS Qty
					FROM  '
				IF @type=1 
					SET @strSql=@strSql+' Wx_InOutStockTable '	
				ELSE
					SET @strSql=@strSql+' InOutStockTable '			
	SET @strSql=@strSql+'
				WHERE KTypeID='+CHAR(39)+@chvKTypeID+CHAR(39)+'
				GROUP BY PTypeID
				UNION
				SELECT PTypeID,SUM(Qty) AS Qty
				FROM '
		IF @type=1 
			SET @strSql=@strSql+' Wx_IniGoodsStocks '	
		ELSE
			SET @strSql=@strSql+' IniGoodsStocks '			
	SET @strSql=@strSql+'
				WHERE KTypeID='+CHAR(39)+@chvKTypeID+CHAR(39)+'
				GROUP BY PTypeID	'+CHAR(10)+'
			) a 
			GROUP BY a.PTypeID
			'


	--统计范围
	IF @intRange=0
	BEGIN
		SELECT @strSql=@strSql+'	HAVING SUM(a.Qty)<>0	'+CHAR(10)
	END

	SELECT @strSql=@strSql+'
		)
	
	'+CHAR(10)

END

SELECT @strSql=@strSql+'	ORDER BY a.UserCode '+CHAR(10)
--SET @strSql+=' SELECT * FROM #table_StockCheck DROP TABLE #table_StockCheck'
EXEC(@strSql)
--print @strSql
--return 
DECLARE
	@intPeriodID	INT,
	@datBeginDate	DATETIME

EXEC Gp_GetSubValue 'period',@stid,@intPeriodID OUT

SELECT TOP 1 @datBeginDate=startdate FROM monthproc WHERE period=@intPeriodID 
IF GetDate()<@datBeginDate 
BEGIN 
	RETURN -33
END

-----------生成单据

DECLARE	@intTotalCount		BigInt		--生成的所有商品数量,也就是盘点单表体的行数
SET	@intTotalCount=0
SELECT	@intTotalCount=COUNT(*) FROM #table_StockCheck


DECLARE	@NowDate	DATETIME
SET @NowDate=GETDATE()
IF @intTotalCount=0	RETURN -1


DECLARE 
	@intRemain 			INT,			--表示余数部分,
	@intTotalPages		INT,			--总的需要生成的单据,也是循环的次数
	@intPageRows		INT				--自动生成盘点单中允许的表体行数

SET 	@intPageRows=150
SET @intTotalPages = @intTotalCount / @intPageRows
SET @intRemain = @intTotalCount % @intPageRows
IF @intRemain>0 		--如果有余数，则页数加1
BEGIN
	SET @intTotalPages=@intTotalPages+1
END


DECLARE
	
	@strBillCode					VARCHAR(200),				--单据编号
	@intBillType					INT,						--单据类型
	@intReturnFlowID				INT,						--流水号
	@intIniID						INT,
	@datBillDate					DATETIME,
	@strETypeID						VARCHAR(50),
	@strComment						VARCHAR(256),
	@strKFullName					VARCHAR(100),
	@strLoginUserName				VARCHAR(100),
	@Month							VARCHAR(100),
	@Day							VARCHAR(100),
	@BillCodeConfig					VARCHAR(10),
	@cefullname						VARCHAR(500)=''

SELECT @datBillDate=CAST(CAST(YEAR(GETDATE()) AS VARCHAR(4))+'-'+CAST(MONTH(GETDATE()) AS VARCHAR(4))+'-'+CAST(DAY(GETDATE()) AS VARCHAR(4))+' 00:00:00' AS DATETIME)

SELECT
	@strBillCode='',
	@intBillType=306,
	@Month='',
	@Day=''

SELECT 
	@Month=MONTH(GETDATE()),
	@Day=DAY(GETDATE())

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

SELECT @strKFullName=FullName
FROM Stock
WHERE TypeID=@chvKTypeID

SELECT @strLoginUserName=FullName
FROM LoginUser a
INNER JOIN Employee b
ON a.ETypeID=b.TypeID
WHERE ETypeID=@chvOperatorID

DECLARE @wxtitle VARCHAR(300),
		@ifwx	INT 
SET @wxtitle=''
SET @ifwx=0
IF @type=1
BEGIN
	SET @wxtitle='维修品库'
	SET @ifwx=1
END

SELECT @strComment=@strLoginUserName+'对'+@wxtitle+'『'+@strKFullName+'』未盘点商品进行自动盘点。'

--生成多张库存盘点单,从M到N

DECLARE
	@intPageNo		INT,		--当前的循环次数,从1开始
	@m 				INT,
	@n 				INT,
	@intRe			INT
	

SELECT
	@intPageNo=1

BEGIN TRY  
BEGIN TRAN
		WHILE @intPageNo<=@intTotalPages
		BEGIN

			SET @m=(@intPageNo-1)*@intPageRows
			SET @n=@intPageNo*@intPageRows

			--生成单据编号
			IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 306) AND @BillCodeConfig = '1'
				BEGIN
					SELECT @MONTH = ''
					SELECT @DAY = FullName FROM Stock WHERE TypeID = @chvKTypeID
					SELECT @cefullname = E.Fullname FROM Employee E WHERE E.TypeId = @chvOperatorID
				END
			SET @strBillCode=''
			EXEC @intRe=Gp_GetBillCode @intBillType, @MONTH,@DAY,'PM',@NowDate,@stid,@strBillCode OUT,'',@cefullname
			IF @Re <> 0	
			BEGIN
				ROLLBACK TRAN
				RETURN -2		
			END

			--库存盘点单
			SELECT @intIniID=MAX(StockCheckID)
			FROM StockCheckIndex

			IF @intIniID IS NULL SET @intIniID=0

			--生成表头
			SELECT	@intIniID=@intIniID+1

			INSERT INTO StockCheckIndex(StockCheckID,BillDate,BillCode,ETypeID,KTypeID,Comment,ifWX)
			SELECT @intIniID,@datBillDate,@strBillCode,'',@chvKTypeID,@strComment,@ifwx

			IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN
				RETURN -3
			END

			INSERT INTO StockCheck(StockCheckID,PTypeID,Qty,StockQty,GoodsNumber,ProduceDate,ValidDate,GoodsCostPrice,CargoID,ItemID,IsCombined,nqty,StockNqty)
			SELECT @intIniID,a.PTypeID,ISNULL(a.Qty,0),ISNULL(a.Qty,0),ISNULL(a.GoodsNumber,''),ISNULL(a.ProduceDate,''),ISNULL(a.ValidDate,''), ISNULL(a.Price,-1),ISNULL(a.cargoid,0),ISNULL(a.ItemID,0),ISNULL(a.Iscombined,0),ISNULL(a.Nqty,0),ISNULL(a.Nqty,0)
			FROM #table_StockCheck	a
			WHERE AutoID>@m AND AutoID<=@n
			ORDER BY a.AutoID
			
			UPDATE StockCheck SET ShowOrder=ID WHERE StockCheckID=@intIniID

			SET @strReturnBillCode = @strReturnBillCode + ' ' + @strBillCode

			IF NOT EXISTS(
				SELECT ConfigNo
				FROM Userconfig
				WHERE ConfigName='BillcodeCreateTime'
				AND Value=2
			)
			BEGIN
				EXEC GP_SaveBillCode_Seed	@intIniID,@NowDate,306,@strBillCode
			END

			IF @@error<>0 
				BEGIN
					ROLLBACK TRAN
					RETURN -2
				END 

		
			SELECT @intPageNo=@intPageNo+1


		END
	DROP TABLE #table_StockCheck
IF @@ERROR=0 COMMIT TRAN
END TRY
BEGIN CATCH
    ROLLBACK TRAN
END CATCH;


GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpColorSizeBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpColorSizeBill]
GO















/****** Object:  Stored Procedure dbo.Gp_UpColorSizeBill    Script Date: 2002-6-20 10:14:51 ******/




/*
   服装版2002－6－11  王浩
   过帐前，更据新生成的单据编号替换临时的单据编号，并做一些检查工作
   参数： @BillNumberID    单据的新单据编号

*/
CREATE   PROCEDURE Gp_UpColorSizeBill
( 
 @BillNumberID [numeric](18, 0),
 @BillCode varchar(200)
)
--@encode$--
AS
 Set NoCount On

 -- 替换单据编号
 Update [FZ_InOutColorSize]
 Set [BillNumberid]=@BillNumberID,[IfCheck]=0
 Where [BillNumberid]=@BillCode

 -- 根据不同的单据类型做动作
-- Declare @BillType   int
 --Declare @K          varchar(25)
 --Declare @K2         varchar(25)
 --Select @BillType=BillType,@K=KtypeID,@K2=KtypeID2 From BillIndex Where BillNumberId=@BillNumberID

 -- 同价调拨
-- if @BillType=17
  --  Update [FZ_InOutColorSize]
   -- Set [KtypeID]=@K2,
     --   [KtypeID]=@K
   -- Where [BillNumberid]=CAST(@BillNumberID AS varchar(50))
 -- 变价调拨
 --if @BillType=21    
   -- Update [FZ_InOutColorSize]
    --Set [KtypeID]=@K2,
      --  [KtypeID]=@K
    --Where [BillNumberid]=CAST(@BillNumberID AS varchar(50))
 -- 商品拆装单
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_Update_ShareOrNot_Templet]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_Update_ShareOrNot_Templet
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	模板 分享或者取消分享
-- 时间：	2013-06-26
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_Update_ShareOrNot_Templet
(
	@IsShare		INT,				--1:分享  0：取消分享
	--@OperatorID		VARCHAR(50),		--操作人ID
	@Id				INT					--模板ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@ShareName		VARCHAR(50)='取消分享',
	@TempletName	VARCHAR(200),			--模板名称	
	@ErrorCount		INT						--执行时出错
	
IF @IsShare=1
	SET @ShareName='分享'

IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_Temple WHERE ID=@Id)
	BEGIN
		RAISERROR('模板已被删除或不存在，不能%s',16,1,@ShareName)
		RETURN 
	END
SELECT @TempletName=TempleName  FROM UFO_Temple  WHERE ID=@Id

--修改模板是否共享
UPDATE UFO_Temple SET IsShare=@IsShare WHERE ID=@Id
SET @ErrorCount+=@@ERROR

--修改菜单是否共享
UPDATE UFO_ReportCategory SET IsShares=@IsShare WHERE Name=@TempletName
SET @ErrorCount+=@@ERROR

IF(@ErrorCount<>0)
	BEGIN
		RAISERROR('模板%s过程中出错，请稍后再试！',16,1,@ShareName)
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Gp_Update_ShareOrNot_TempletReport]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_Update_ShareOrNot_TempletReport
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	模板 分享或者取消分享
-- 时间：	2013-06-26
-- 作者：	glj
-- ========================================================================
CREATE PROC Gp_Update_ShareOrNot_TempletReport
(
	@IsShare		INT,				--1:分享  0：取消分享
	@Id				INT					--模板ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@ShareName			VARCHAR(50)='取消分享',
	@TempleCategoryID	VARCHAR(50),			--模板名称	
	@ErrorCount			INT=0						--执行时出错
	
IF @IsShare=1
	SET @ShareName='分享'

IF NOT EXISTS(SELECT TOP 1 1 FROM UFO_Temple WHERE ID=@Id)
	BEGIN
		RAISERROR('报表已被删除或不存在，不能%s',16,1,@ShareName)
		RETURN 
	END

SELECT @TempleCategoryID=TempleCategoryID  FROM UFO_Temple  WHERE ID=@Id AND ClassId=3

--修改节点
IF (SELECT COUNT(*) FROM UFO_Temple WHERE TempleCategoryID=@TempleCategoryID AND ClassId=3)=1
	BEGIN
		UPDATE UFO_ReportCategory SET IsShares=@IsShare WHERE TypeId=@TempleCategoryID AND SysType=1
		SET @ErrorCount+=@@ERROR
	END

--修改模板是否共享
UPDATE UFO_Temple SET IsShare=@IsShare WHERE ID=@Id
SET @ErrorCount+=@@ERROR

IF(@ErrorCount<>0)
	BEGIN
		RAISERROR('模板%s过程中出错，请稍后再试！',16,1,@ShareName)
	END
RETURN @ErrorCount
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateA]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateA]
GO


--费用合计等更新数据 
--修改者：黄飞佳  修改时间：2012-4-16



CREATE    PROCEDURE [Gp_UpdateA]
(
 @TypeId  [varchar](50),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @Name   [varchar](30),
 @Total00   NUMERIC(24, 10) ,
 @Comment  [varchar](256),
 @PyCode   varchar(200)
)
--@encode$--
AS 
SET NOCOUNT ON 
if exists(select usercode from atype where (usercode=@usercode or fullname=@fullname) and  deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -3
end
if exists(select usercode from atype where (usercode=@fullname or fullname=@usercode) and  deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -10
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode


UPDATE [dbo].[atype] 
--UPDATE [dbo].[Ac_Expenses]
SET      [FullName]  = @FullName,
  [Name]    = @Name,
  [UserCode]  = @UserCode,
  [Comment]  = @Comment,
  [PyCode] =@returnPym,
  [Total00]  = dbo.F_RoundTotal(@Total00) 
WHERE 
 ( [typeId]  = @typeId )
 
 --修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AType
UPDATE AType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAc_AssetsCards]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[Gp_UpdateAc_AssetsCards]
GO


/****** Object:  StoredPROCEDURE [dbo].[Gp_InsertAc_AssetsCards]    Script Date: 05/17/2011 20:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

----========================
----修改者：黄清
----日期：2013-05-20
----描述：固定资产卡片修改
----========================
CREATE    PROCEDURE [dbo].[Gp_UpdateAc_AssetsCards]
(
	@cardid			[VARCHAR](50),
	@UserCode		[VARCHAR](200),
	@FullName		[VARCHAR](200),
	@stypeid		[VARCHAR](50),
	@dtypeid		[VARCHAR](50),
	@size			[VARCHAR](50),
	@categoryid		[VARCHAR](50),
	@locationid		[VARCHAR](50),
	@conditionid	[VARCHAR](50),
	@inaccountdate	DATETIME,
	@businesstypeid	[VARCHAR](50),
	@total			 NUMERIC(24, 10) ,
	@cid			[VARCHAR](50),
	@rate			 NUMERIC(24, 10) ,
	@ftotal			 NUMERIC(24, 10) ,
	@deptotal		 NUMERIC(24, 10) ,
	@devalueready	 NUMERIC(24, 10) ,
	@netvalue		 NUMERIC(24, 10) ,
	@netsalvage		 NUMERIC(24, 10) ,
	@netsalvagerate	 NUMERIC(24, 10) ,
	@depreciationmean	[VARCHAR](50),
	@duryear			INT,
	@durmonth			INT,
	@depreciationmonth	INT,
	@assertatypeid	[VARCHAR](50),
	@depatypeid		[VARCHAR](50),
	@disatypeid		[VARCHAR](50),
	@devalueatypeid	[VARCHAR](50),
	@etypeid		[VARCHAR](50),
	@Comment  [VARCHAR](256),
	@units		[VARCHAR](200),
	@barcode	VARCHAR(256),
	@Qty        NUMERIC(24, 10) ,
	@expectwork	 NUMERIC(24, 10) ,
	@finishwork  NUMERIC(24, 10) ,
	@workunit	VARCHAR(256)
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND deleted=1)
	BEGIN
		RAISERROR('该分支机构已被停用，不能进行操作！',16,1) RETURN
	END	
IF @barcode IS NOT NULL AND @barcode<>'' AND EXISTS (SELECT *FROM AC_AssetsCards WHERE BarCode=@barcode AND id<>@cardid)
BEGIN
	RAISERROR('固定资产条码【%s】已存在，请更换条码',16,1,@barcode)RETURN
END

IF EXISTS(SELECT 1 FROM AC_AssetsCards WHERE usercode=@usercode AND id<>@cardid)
BEGIN
	RAISERROR('该【%s】的编号已经使用，请更换编号',16,1,@usercode)RETURN--return -31
END


--IF EXISTS(SELECT 1 FROM AC_AssetsCards WHERE fullname=@fullname AND id<>@cardid)
--BEGIN
--	RAISERROR('该【%s】的名称已经使用，请更换名称',16,1,@FullName)return--return -31
--END
DECLARE @ini INT
DECLARE @AssetsState INT
DECLARE @IsA8 INT	
IF EXISTS(SELECT *FROM sysdata WHERE SubName='ProInfo' AND SubValue=2)
	SET @IsA8=1
ELSE
	SET @IsA8=0

--获取开账期间
DECLARE 
	@SFyear			 INT,	--分支机构启用年度
	@SFPeriod		 INT,	--分支机构启用期间
	@Fyear			 INT,	--分支机构当前年度
	@FPeriod		 INT,	--分支机构当前期间		
	@VerifyID VARCHAR(50)

SELECT @VerifyID=VerifyID FROM SType WHERE TypeId =@stypeid
--获取指定分支机构当前财务期间		

SELECT	
	@SFyear=SFYear,
	@SFPeriod=SFPeriod,
	@Fyear=FYear,
	@FPeriod=FPeriod
FROM dbo.Ac_AccountsPeroid_Stype 
WHERE Stypeid=@VerifyID

SET @ini=0
SELECT @ini=CASE WHEN AssetsState=1 THEN 1
			WHEN AssetsState=2 THEN 0
			ELSE  2 END,
	   @AssetsState=AssetsState
 FROM Ac_AssetsCards WHERE Id=@cardid

---初始数据录入
IF @ini='1' 
BEGIN
	IF EXISTS (SELECT 1 FROM Stype WHERE TypeId=@stypeid AND IfAssetsIni=1) AND @IsA8=1
	BEGIN
		RAISERROR('所选分支机构已初始化，请重新选择',16,1,@usercode)return--return -31
	END
	IF EXISTS (SELECT 1 FROM Stype WHERE TypeId=@VerifyID AND IfAssetsIni=1) AND @IsA8=0
	BEGIN
		RAISERROR('初始化已完成，不能录入初始数据，请确认',16,1,@usercode)return--return -31
	END
	--初始数据录入，未开账，入账时间<起始会计期间开始日期
	IF EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@VerifyID AND IsUse=0) AND EXISTS(SELECT 1 FROM Ac_Period WHERE FPeriod=@SFPeriod AND FYear=@SFyear AND IsCurrent=1 AND FBegin<=@inaccountdate)
	BEGIN
		RAISERROR('初始数据录入，未开账时,入账日期必须小于系统起始会计期间日期,请确认',16,1,@usercode)return--return -31
	END
	
	--初始数据录入，已开账，入账时间<当前会计期间开始日期
	IF EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@VerifyID AND IsUse=1) AND EXISTS(SELECT 1 FROM Ac_Period WHERE FPeriod=@FPeriod AND FYear=@Fyear AND IsCurrent=1 AND FBegin<=@inaccountdate)
	BEGIN
		RAISERROR('初始数据录入，已开账，入账时间必须小于当前会计期间开始日期,请确认',16,1,@usercode)return--return -31
	END

END

--正常卡片录入
IF @ini='0'
BEGIN
	
	IF EXISTS(SELECT 1 FROM Stype WHERE TypeId=@stypeid AND IfAssetsIni=0) AND @IsA8=1
	BEGIN
		RAISERROR('所选分支机构未初始化，请重新选择',16,1,@usercode)return--return -31
	END
	
	IF NOT EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@VerifyID AND IsUse=1) AND @IsA8=1
	BEGIN
		RAISERROR('所选分支机构已初始化但未开账，请重新选择',16,1,@usercode)return--return -31
	END
	
	IF( NOT EXISTS(SELECT 1 FROM Ac_AccountsPeroid_Stype WHERE StypeId=@VerifyID AND IsUse=1) OR EXISTS(SELECT 1 FROM Stype WHERE TypeId=@stypeid AND IfAssetsIni=0))  AND @IsA8=1
	BEGIN
		RAISERROR('未完成初始化或未开账，不能录入卡片数据，请确认',16,1,@usercode)return--return -31
	END

	IF EXISTS(SELECT 1 FROM Ac_Period WHERE FPeriod=@FPeriod AND FYear=@Fyear AND IsCurrent=1 AND FBegin>@inaccountdate)
	BEGIN
		RAISERROR('正常卡片录入，入账时间必须大于当前会计期间开始日期,请确认',16,1,@usercode)return--return -31
	END
END

DECLARE @AudtiType VARCHAR(50)
SELECT @AudtiType=AuditType FROM Ac_AssetBusinessType WHERE Id=@businesstypeid
IF @ini='0' AND (@AudtiType=1 OR @AudtiType=2 OR @AudtiType=3) AND @deptotal<>0 AND @AssetsState<4
BEGIN
	RAISERROR('正常卡片，增加方式为【购入(原值含税)】、【购入(原值不含税)】、【自建工程】的资产卡片累计折旧值应该为0',16,1)return--return -31
END

--非工作量法，工作量相关字段统一处理为null
IF @depreciationmean<>'5'
BEGIN
	SET @expectwork=NULL
	SET @finishwork=NULL
	SET @workunit=NULL
END


UPDATE AC_AssetsCards
SET
	UserCode=@UserCode,         
	FullName=@FullName,
	stypeid=@stypeid,
	dtypeid=@dtypeid,
	size=@size,
	categoryid=@categoryid,
	locationid=@locationid,
	conditionid=@conditionid,
	inaccountdate=@inaccountdate,
	businesstypeid=@businesstypeid,
	total=dbo.F_RoundTotal(@total),
	cid=@cid,
	rate=dbo.F_RoundExchangeRate(@rate),
	F_Total=dbo.F_RoundTotal(@ftotal),
	deptotal=dbo.F_RoundTotal(@deptotal),
	devalueready=@devalueready,
	netvalue=dbo.F_RoundTotal(@netvalue),
	netsalvage=dbo.F_RoundTotal(@netsalvage),
	netsalvagerate=dbo.F_RoundPercentage(@netsalvagerate),
	depreciationmean=@depreciationmean,
	duryear=@duryear,
	durmonth=@durmonth,
	depreciationmonth=@depreciationmonth,
	assertatypeid=@assertatypeid,
	depatypeid=@depatypeid,
	disatypeid=@disatypeid,
	devalueatypeid=@devalueatypeid,
	Comment=@Comment,
	Units=@units,
	BarCode=@barcode,
	Qty=@Qty,
	ExpectWork=@expectwork,
	FinishWork=@finishwork,
	WorkUnit=@workunit
WHERE id=@cardid

IF @@rowcount=0 
BEGIN
 RETURN -1
END
ELSE
BEGIN
	--修改XiWa的XiWaMaxNumber
	DECLARE @XiWaMaxNumber numeric(18,0)
	SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AC_AssetsCards
	UPDATE AC_AssetsCards SET XiWaMaxNumber = @XiWaMaxNumber WHERE id = @CARDID
	RETURN @CARDID
END

GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateAc_Assist_CheckItems_BillType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_UpdateAc_Assist_CheckItems_BillType]

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

--作    者：胡小科 
--日    期：2012-06-01 
--作    用：更新单据表头自定义信息 


CREATE     PROCEDURE [dbo].[Gp_UpdateAc_Assist_CheckItems_BillType]
(
	@AscIds			int,--自定义类型
	@BillType		int,--单据类型id
	@FullName		varchar(200),--自定义字段全名
	@FieldValue		varchar(100)--自定义字段detafield
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN TRY
 
IF EXISTS(SELECT * FROM Ac_Assist_CheckItems_BillType WHERE BillType= @BillType and FieldValue= @FieldValue)
	BEGIN 
		UPDATE Ac_Assist_CheckItems_BillType  SET AscIds=@AscIds ,FullName=@FieldValue WHERE  BillType=@BillType AND  FieldValue=@FullName
	END
ELSE
	BEGIN
		INSERT INTO Ac_Assist_CheckItems_BillType ( AscIds ,BillType ,FullName ,FieldValue)
		VALUES(@AscIds,@BillType,@FullName,@FieldValue)
	END

	RETURN 1
END TRY
BEGIN CATCH

	RETURN 0

END CATCH

GO






IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAc_CashMoney]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_UpdateAc_CashMoney
GO 

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROC [Gp_UpdateAc_CashMoney]
(
	@TypeId		[varchar](50),
	@UserCode	[varchar](100),
	@FullName	[varchar](100)
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @Name VARCHAR(200)=''

SELECT @Name=FullName FROM Ac_CashMoneyItems WHERE usercode=@usercode and typeid<>@typeid and typeid<>'00000'
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1)
		RETURN
	END

UPDATE [dbo].[Ac_CashMoneyItems] 
SET  
	[FullName]  = @FullName,
	[UserCode]  = @UserCode
WHERE 
	[typeId]  = @typeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAc_Items]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateAc_Items]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	Ac_items 新增、编辑
-- 时间：	2012-06-14
-- 作者：	古丽娟

-- ========================================================================
CREATE PROC Gp_UpdateAc_Items
(
	@nid			INT,				--Id
	@UserCode		VARCHAR(200),		--编码
	@FullName		VARCHAR(400),		--名称
	@Comment		VARCHAR(500),		--描述
	@TypeName		VARCHAR(2),			--信息类型
	@type			INT					--update类型  1:新增 2：修改
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Name VARCHAR(200),@NIDS INT,@ErrorCount INT =0
--判断编号是否重复
IF(ISNULL(@nid,0)>0)
	SELECT @Name=FullName FROM Ac_Items WHERE  UserCode=@usercode AND nId<>@nid
ELSE
	SELECT @Name=FullName FROM Ac_Items WHERE UserCode=@usercode
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1)RETURN
	END
--判断名称是否重复
IF(ISNULL(@nid,0)>0)
	SELECT @Name=FullName FROM Ac_Items WHERE  FullName=@fullname AND nId<>@nid
ELSE
	SELECT @Name=FullName FROM Ac_Items WHERE  FullName=@fullname
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG1 VARCHAR(100)='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END	
DECLARE @PyCode VARCHAR(50)=(SELECT dbo.fun_getPY(@FullName)),@XiWaMaxNumber INT=0
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items
IF(@type=1)
	BEGIN
		INSERT INTO Ac_Items
			(
				[UserCode],
				[FullName],
				[Comment],
				[Deleted],
				[TypeName],
				[Sysrow],
				IsModify,
				[TypeId],
				[ParId],
				[Leveal],
				[SonNum],
				[SonCount],
				[Name],
				[CreateBank],
				[BankType],
				[IsBank],
				[PyCode],
				[XiWaMaxNumber]
			)
		VALUES
			(
				@usercode,
				@fullname,
				@comment,
				0,
				@TypeName,
				0,
				1,
				'',
				'',
				1,
				0,
				0,
				'',
				'',
				'',
				0,
				@PyCode,
				@XiWaMaxNumber
				)
		SET @NIDS=SCOPE_IDENTITY();
		SET @ErrorCount+=@@ERROR
	END
ELSE IF(@type=2)
	BEGIN
		UPDATE	Ac_Items 
		SET		UserCode=@UserCode,
				FullName=@FullName,
				PyCode = @PyCode,
				Comment=@Comment,
				XiWaMaxNumber=@XiWaMaxNumber
		WHERE	nId=@nid
		
		SET @ErrorCount+=@@ERROR
	END	

DELETE FROM Ac_Items_Detail WHERE nId=@NIDS OR nId=@nid
SET @ErrorCount+=@@ERROR


IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='信息添加失败！'
		IF(@type=2)
			SET @MSG2='信息修改失败'
		RAISERROR(@MSG2,16,1)	
	END
ELSE 
	BEGIN
		IF(@type=2)
			SET @NIDS=@nid
		RETURN @NIDS
	END
	
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAc_Items_Details]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateAc_Items_Details]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	新增Ac_Items_Detail
-- 时间：	2012-04-19
-- 作者：	古丽娟

-- ========================================================================
CREATE PROC Gp_UpdateAc_Items_Details
(
	@Did			INT,				--自增长列
	@nid			INT,				--项目ID
	@stypeid		VARCHAR(50)='',		--分支机构
	@atypeid		VARCHAR(50)='',		--科目
	@depatypeid		VARCHAR(50)='',		--累计折旧科目
	@disatypeid		VARCHAR(50)=''		--折旧分配科目
)
--@encode$--

AS
SET NOCOUNT ON 

--缓存字段
DECLARE @XiWaMaxNumber INT=0,@oldNid INT=0
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items_Detail 
IF(ISNULL(@Did,0)<>0)
	BEGIN
		SELECT @oldNid=nId FROM Ac_Items_Detail WHERE DId=@Did
	END
IF(ISNULL(@Did,0)=0 OR @oldNid<>@nid)
	BEGIN
		DECLARE @delete INT 
		SELECT @delete = deleted FROM dbo.SType WHERE TypeId = @stypeid
		IF @delete = 1
		BEGIN
			UPDATE Ac_Items_Detail SET ATypeId = @atypeid WHERE STypeId = @stypeid AND nId = @nid
		END 
		ELSE
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Items_Detail WHERE STypeId=@stypeid AND nId=@nid)
			BEGIN
				RAISERROR('分支机构不能重复！',16,1)
				RETURN 	
			END
			INSERT INTO Ac_Items_Detail
				(
					[nId],
					[STypeId],
					[ATypeId],
					[DepATypeId],
					[DisATypeId],
					[XiWaMaxNumber]
				)
			VALUES
				(
					@nid,
					@stypeid,
					@atypeid,
					@depatypeid,
					@disatypeid,
					@XiWaMaxNumber
				)
		END 
	END
ELSE 
	BEGIN
		UPDATE Ac_Items_Detail 
		SET 
			STypeId=@stypeid,
			ATypeId=@atypeid,
			DepATypeId=@depatypeid,
			DisATypeId=@disatypeid,
			XiWaMaxNumber=@XiWaMaxNumber
		WHERE DId=@Did
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_UpdateAcAccountAssist]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[GP_UpdateAcAccountAssist]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	修改科目辅助核算类型及明细
-- 时间：	2015-10-12
-- 作者：	GLJ
-- ========================================================================
CREATE PROC GP_UpdateAcAccountAssist
(
	@STypeID		VARCHAR(50),	--分支机构ID
	@ATypeID		VARCHAR(50),	--科目ID
	@AscIds			VARCHAR(MAX),	--辅助核算类别ID Str
	@AscDetailIds	VARCHAR(MAX),	--辅助核算类别ID 明细Str
	@OperatorID		VARCHAR(50),	--操作员ID
	@Type			INT				--0科目表 1:会计科目
)

--@encode$--
AS
SET NOCOUNT ON

--如果该科目被使用，详细处理逻辑，如果没有使用只需处理科目辅助核算关联表
DECLARE 
	@IsUsed		INT=0,
	@STypeID1	VARCHAR(50)=@STypeID,
	@AcId		INT		--科目表ID
	
SELECT @AcId=AcId FROM Ac_Account WHERE StypeId=@STypeID AND TypeId=@ATypeID
	
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeID AND TypeId=@ATypeID AND FContact=1) AND ISNULL(@AscIds,'')=''
	BEGIN
        RAISERROR ( '该科目为核算往来科目，必须选择至少一项辅助核算！', 16, 1 )RETURN
	END
--EXEC @IsUsed=GP_CheckAccountUsage @STypeID,@ATypeID	
SELECT @IsUsed=DBO.F_GetAcacountIsUsed(@STypeID,@ATypeID)

IF(@Type=0)
	SET @STypeID1='00000'
--类别
CREATE TABLE #Assist(NID INT,AscIds INT)
INSERT #Assist(NID,AscIds)
SELECT 
	SUBSTRING(a,1,CHARINDEX('=',a,1)-1) NID,
	SUBSTRING(a,CHARINDEX('=',a,1)+1,LEN(a)) 
FROM f_split(@AscIds,',')
IF EXISTS(SELECT AscIds FROM #Assist GROUP BY AscIds HAVING COUNT(AscIds)>1)
	BEGIN
        RAISERROR ( '列表中有相同的辅助核算项目！', 16, 1 )RETURN
	END
IF EXISTS(SELECT TOP 1 1 FROM #Assist WHERE AscIds IN(SELECT AscIds FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeID AND ATypeId=@ATypeID GROUP BY AscIds)) AND @IsUsed>0
	BEGIN
        RAISERROR ( '新选择的核算项目及与原有的核算项目不能出现重复！', 16, 1 )RETURN
	END

--默认值
CREATE TABLE #Detail(NID INT,TypeID VARCHAR(50))
INSERT #Detail(NID,TypeID)
SELECT 
	SUBSTRING(a,1,CHARINDEX('=',a,1)-1) NID,
	SUBSTRING(a,CHARINDEX('=',a,1)+1,LEN(a)) 
FROM f_split(@AscDetailIds,',')

--处理数据
DECLARE 
	@I			INT=1,
	@J			INT=1,
	@AssistID	INT,				--类别ID
	@AssistUserCode	VARCHAR(200),	--类别编号
	@AssistType	VARCHAR(50),		--核算明细
	@Error		INT=0				--出错标志
--辅助核算明细数据
CREATE TABLE #AssistDetail(ID INT IDENTITY(1,1),NID INT,AscIds INT,UserCode VARCHAR(200),DTypeID VARCHAR(50))
INSERT INTO #AssistDetail(NID,AscIds,UserCode,DTypeID)
SELECT
	A.NID,
	A.AscIds,
	C.UserCode,
	D.TypeID
FROM #Assist A 
INNER JOIN #Detail D ON D.NID=A.NID
INNER JOIN Ac_Assist_CheckItems C ON C.AscIds=A.AscIds

SELECT @J=@@ROWCOUNT
--科目币种
DECLARE @CID INT
SELECT @CID=Cid FROM Ac_Account WHERE StypeId=@STypeID AND TypeId=@ATypeID
--币种
CREATE TABLE #Currency(CId INT)
INSERT INTO #Currency(CId)
SELECT CId FROM Ac_Currency WHERE (@CID<>0 AND CId=@CID) OR (@CID=0 AND 1=1)
BEGIN TRAN
IF(@IsUsed>0)
	BEGIN
		WHILE(@I<=@J)
			BEGIN
				--以前就已经保存的核算类别
				DECLARE 
					@usedAscids	INT,
					@usedUserCode VARCHAR(200)
				SELECT TOP 1 @usedAscids=C.Ascids,@usedUserCode=D.UserCode FROM Ac_Account_Assist_CheckItems C INNER JOIN Ac_Assist_CheckItems D ON D.AscIds=C.Ascids WHERE C.STypeId=@STypeID AND C.ATypeId=@ATypeID ORDER BY C.Ascids	
				
				SELECT @AssistID=AscIds,@AssistType=DTypeID,@AssistUserCode=UserCode FROM #AssistDetail WHERE ID=@I 
				--科目辅助核算表
				INSERT INTO Ac_Account_Assist_CheckItems (STypeId,ATypeId,Cid,Ascids,DTypeID,AcId)
				SELECT @STypeID,@ATypeID,cid,@AssistID,@AssistType,@AcId FROM #Currency 
				SET @Error+=@@ERROR	
				--期初科目余额表辅助核算项目对照表
				IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount WHERE STypeId=@STypeID AND ATypeId=@ATypeID AND(iniTotal<>0 OR FDebit<>0 OR FCredit<>0 OR FYTotal<>0  OR iniYTotal<>0 OR iniTotalFor<>0 OR FDebitFor<>0 OR FCreditFor<>0 OR FYTotalFor<>0 OR iniYTotalFor<>0 OR iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0 OR FYTotalDebit<>0 OR FYTotalCredit<>0 OR FYTotalDebitFor<>0 OR FYTotalCreditFor<>0)) OR EXISTS (SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId = @STypeID AND ATypeId = @ATypeID ) 
					BEGIN
						IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId=@STypeID AND ATypeId=@ATypeID)
							BEGIN
								INSERT INTO Ac_IniAccount_Assist_CheckItems(STypeId,ATypeId,Cid,FYear,FPeriod,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,FYTotal,FYTotalFor,IniYqty,FDebitqty,FCreditqty,Iniqty)
SELECT STypeId,ATypeId,Cid,FYear,FPeriod,iniYTotal,iniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,iniTotal,iniTotalFor,FYTotal,FYTotalFor,IniYqty,FDebitqty,FCreditqty,Iniqty FROM Ac_IniAccount WHERE STypeId=@STypeID AND ATypeId=@ATypeID
								SET @Error+=@@ERROR	
									
								INSERT INTO Ac_IniAccount_Assist_CheckItems_Detail(STypeId,ATypeId,Cid,Ascids,FieldValue,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,GroupId,FYear,FPeriod,FYTotal,FYTotalFor,IniYqty,FDebitqty,FCreditqty,Iniqty)
								SELECT STypeId,ATypeId,Cid,@AssistID,@AssistType,iniYTotal,iniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,iniTotal,iniTotalFor,1,FYear,FPeriod,FYTotal,FYTotalFor,IniYqty,FDebitqty,FCreditqty,Iniqty FROM Ac_IniAccount WHERE STypeId=@STypeID AND ATypeId=@ATypeID
								SET @Error+=@@ERROR			
							END
						ELSE
							BEGIN
								SELECT STypeId,ATypeId,Cid,Ascids,FieldValue,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,GroupId,FYear,FPeriod,FYTotal,FYTotalFor,IniYqty,FDebitqty,FCreditqty,Iniqty INTO #Temp FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId=@STypeID AND ATypeId=@ATypeID AND Ascids=@usedAscids
								SET @Error+=@@ERROR
											
								INSERT INTO Ac_IniAccount_Assist_CheckItems_Detail(STypeId,ATypeId,Cid,Ascids,FieldValue,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,GroupId,FYear,FPeriod,FYTotal,FYTotalFor,IniYqty,FDebitqty,FCreditqty,Iniqty)
								SELECT STypeId,ATypeId,Cid,@AssistID,@AssistType,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,GroupId,FYear,FPeriod,FYTotal,FYTotalFor,IniYqty,FDebitqty,FCreditqty,Iniqty FROM #Temp	
								SET @Error+=@@ERROR
								
								DROP TABLE 	#Temp	
								SET @Error+=@@ERROR															
							END	
					END
					
				--凭证辅助核算
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill WHERE STypeId=@STypeID AND ATypeId=@ATypeID)
					BEGIN
						UPDATE Ac_Voucher_Bill SET AscIds+=CAST(@AssistID AS VARCHAR(5))+':'+@AssistType+',' WHERE STypeId=@STypeID AND ATypeId=@ATypeID
						SET @Error+=@@ERROR	
						
						INSERT INTO Ac_Voucher_Bill_Assist_CheckItems(BillNumberId,vBId,typeName,TypeId)
						SELECT BillNumberId,ID,@AssistUserCode,@AssistType FROM Ac_Voucher_Bill WHERE STypeId=@STypeID AND ATypeId=@ATypeID
						SET @Error+=@@ERROR		
					END
					
				--科目余额辅助核算表
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE STypeId=@STypeID AND ATypeId=@ATypeID)
					BEGIN
						--保存的核算类别ascids的相关数据
						SELECT	STypeId,ATypeId,Cid,FYear,FPeriod,FDebit,FDebitFor,FCredit,FCreditFor
								,FBeginBalance AS IniTotal,FBeginBalanceFor AS IniTotalFor,FEndBalance,FEndBalanceFor
								,FBeginqty AS Iniqty,FDebitqty,FCreditqty,FEndqty 
						INTO #BalanceDetails 
						FROM Ac_Balance 
						WHERE STypeId=@STypeID AND ATypeId=@ATypeID
												
						--插入数据值相同但是类别不同的数据					
						INSERT INTO Ac_Balance_Assist_CheckItems_Detail
								(STypeId,ATypeId,Cid,Ascids,FieldValue,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor
								,FEndBalance,FEndBalanceFor,FYear,FPeriod,Iniqty,FDebitqty,FCreditqty,FEndqty)
						SELECT	STypeId,ATypeId,Cid,@AssistID,@AssistType,SUM(FDebit),SUM(FDebitFor),SUM(FCredit),SUM(FCreditFor)
								,SUM(IniTotal),SUM(IniTotalFor),SUM(FEndBalance),SUM(FEndBalanceFor),FYear,FPeriod,SUM(Iniqty)
								,SUM(FDebitqty),SUM(FCreditqty),SUM(FEndqty) 
						FROM #BalanceDetails GROUP BY STypeId,ATypeId,Cid,FYear,FPeriod
						SET @Error+=@@ERROR		
						
						IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Balance_Assist_CheckItems WHERE STypeId = @STypeID AND ATypeId = @ATypeID)
						BEGIN
							SELECT	i.STypeId,i.ATypeId,i.Cid,i.iniYTotal,i.iniYTotalFor,i.IniYqty,b.FYear,b.FPeriod
							INTO #iniYTotal 
							FROM dbo.Ac_IniAccount i
							INNER JOIN dbo.Ac_Balance b ON b.STypeId = i.STypeId AND b.ATypeId = i.ATypeId AND b.Cid = i.Cid
							WHERE i.STypeId=@STypeID AND i.ATypeId=@ATypeID
							
							INSERT INTO #iniYTotal
									( STypeId ,
									  ATypeId ,
									  Cid ,
									  iniYTotal ,
									  iniYTotalFor ,
									  IniYqty ,
									  FYear ,
									  FPeriod
									)
							SELECT STypeId ,
								   ATypeId ,
								   0 ,
								   SUM(iniYTotalFor) ,
								   SUM(iniYTotalFor) ,
								   SUM(IniYqty) ,
								   FYear ,
								   FPeriod 
							FROM #iniYTotal
							GROUP BY stypeid,atypeid,FYear,FPeriod
							
							INSERT INTO dbo.Ac_Balance_Assist_CheckItems
									( STypeId ,
									  ATypeId ,
									  Cid ,
									  IniYTotal ,
									  IniYTotalFor ,
									  FDebit ,
									  FDebitFor ,
									  FCredit ,
									  FCreditFor ,
									  IniTotal ,
									  IniTotalFor ,
									  IniYqty ,
									  FDebitqty ,
									  FCreditqty ,
									  Iniqty ,
									  FYear ,
									  FPeriod ,
									  FEndBalance ,
									  FEndBalanceFor ,
									  FEndqty
									)
							SELECT	b.STypeId ,
									b.ATypeId ,
									b.Cid ,
									ISNULL(i.iniYTotal,0),
									ISNULL(i.iniYTotalFor,0),
									FDebit ,
									FDebitFor ,
									FCredit ,
									FCreditFor ,
									IniTotal ,
									IniTotalFor ,
									ISNULL(i.IniYqty,0),
									FDebitqty ,
									FCreditqty ,
									Iniqty ,
									b.FYear ,
									b.FPeriod ,
									FEndBalance ,
									FEndBalanceFor ,
									FEndqty 
							FROM #BalanceDetails b
							LEFT JOIN #iniYTotal i ON i.STypeId = b.STypeId AND i.ATypeId = b.ATypeId AND i.Cid = b.Cid 
														AND i.FYear = b.FYear AND i.FPeriod = b.FPeriod
							
							SET @Error+=@@ERROR	
							DROP TABLE #iniYTotal
						END 
						
						
						DROP TABLE #BalanceDetails	
					END
				--损益类科目实际发生额明细表
				IF EXISTS(SELECT TOP 1 1 FROM Ac_ProfitAndLoss WHERE STypeId=@STypeID AND ATypeId=@ATypeID)
					BEGIN
						INSERT INTO Ac_ProfitAndLoss_Detail(STypeId,ATypeId,Cid,Ascids,FieldValue,FFTotal,FFTotalFor,FYTotal,FYTotalFor,FYear,FPeriod)
						SELECT STypeId,ATypeId,Cid,@AssistID,@AssistType,FFTotal,FFTotalFor,FYTotal,FYTotalFor,FYear,FPeriod FROM Ac_ProfitAndLoss WHERE STypeId=@STypeID AND ATypeId=@ATypeID
						SET @Error+=@@ERROR		
					END

			SET @I+=1
			END
	END
ELSE 
	BEGIN
		-- 先清除设置的辅助核算项目
		DELETE Ac_Account_Assist_CheckItems WHERE STypeID IN(@STypeID,@STypeID1) AND ATypeId = @ATypeID 
		SET @Error+=@@ERROR	
		
		-- 重新填写辅助核算项目
		IF(@Type=0)
			BEGIN
				INSERT  INTO Ac_Account_Assist_CheckItems 
				(
					STypeId,
					ATypeId,
					Cid,
					Ascids,
					DTypeID,
					AcId
				)
				SELECT  
					@stypeid, 
					@ATypeID, 
					cid, 
					AscIds,
					DTypeID,
					@AcId
				FROM #Currency,#AssistDetail
				UNION ALL
				SELECT  
					@STypeID1, 
					@ATypeID, 
					cid, 
					AscIds,
					DTypeID,
					@AcId
				FROM #Currency,#AssistDetail
				SET @Error+=@@ERROR
			END	
		ELSE 
			BEGIN
				INSERT  INTO Ac_Account_Assist_CheckItems 
				(
					STypeId,
					ATypeId,
					Cid,
					Ascids,
					DTypeID,
					AcId
				)
				SELECT  
					@stypeid, 
					@ATypeID, 
					cid, 
					AscIds,
					DTypeID,
					@AcId
				FROM #Currency,#AssistDetail
				SET @Error+=@@ERROR
			END
			
		--凭证模板信息
		IF EXISTS(SELECT * FROM Ac_Auditing_Template T INNER JOIN Ac_Auditing_Template_Detail D ON D.Atid=T.AtId AND T.STypeId=@STypeID AND D.ATypeId=@ATypeID)
		BEGIN	
			INSERT INTO Ac_Auditing_Template_Detail_Assist_CheckItems(AtdId,Atid,AscIds,AscIdsDetailId)
			SELECT
				TD.Atid,
				TD.Atid,
				AD.AscIds,
				B.nId 
			FROM Ac_Auditing_Template T
			INNER JOIN Ac_Auditing_Template_Detail TD ON TD.Atid=T.AtId AND T.STypeId=@STypeID AND TD.ATypeId=@ATypeID
			INNER JOIN Ac_Assist_CheckItems_BillType B ON B.BillType=T.BillType
			INNER JOIN #AssistDetail AD ON AD.AscIds=B.AscIds
			WHERE AD.AscIds NOT IN(SELECT
				AD.AscIds
			FROM Ac_Auditing_Template T
			INNER JOIN Ac_Auditing_Template_Detail TD ON TD.Atid=T.AtId AND T.STypeId=@STypeID AND TD.ATypeId=@ATypeID
			INNER JOIN Ac_Assist_CheckItems_BillType B ON B.BillType=T.BillType)
		END
	END
--修改科目FAcnt标志为有辅助核算
DECLARE @XiWaMaxNumber INT
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Account 
UPDATE Ac_Account SET FAcnt=1,XiWaMaxNumber=@XiWaMaxNumber,@XiWaMaxNumber+=1 WHERE StypeId IN(@STypeID,@STypeID1) AND TypeId=@ATypeID
SET @Error+=@@ERROR	
	
IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN

RETURN @Error

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAcBank]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateAcBank]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	银行账户 新增、编辑
-- 时间：	2012-04-19
-- 作者：	古丽娟

-- ========================================================================
CREATE PROCEDURE Gp_UpdateAcBank
(
	@nid			INT,				--Id
	@UserCode		VARCHAR(200),		--编码
	@FullName		VARCHAR(400),		--名称
	@CreateBank		VARCHAR(400),		--开户银行
	@BankType		VARCHAR(200),		--银行类型
	@IsBank			INT,				--是否是银行
	@Comment		VARCHAR(500),		--描述
	@type			INT					--update类型  1:新增 2：修改
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Name VARCHAR(200),@NIDS INT,@ErrorCount INT =0
--判断编号是否重复
IF(ISNULL(@nid,0)>0)
	SELECT @Name=FullName FROM Ac_Items WHERE  UserCode=@usercode AND nId<>@nid
ELSE
	SELECT @Name=FullName FROM Ac_Items WHERE  UserCode=@usercode
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同 ，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1)RETURN
	END
--判断名称是否重复
IF(ISNULL(@nid,0)>0)
	SELECT @Name=FullName FROM Ac_Items WHERE  FullName=@fullname AND nId<>@nid
ELSE
	SELECT @Name=FullName FROM Ac_Items WHERE  FullName=@fullname
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG1 VARCHAR(100)='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END	
	
DECLARE @PyCode VARCHAR(50)=(SELECT dbo.fun_getPY(@FullName)),@XiWaMaxNumber INT=0
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items
IF(@type=1)
	BEGIN
		INSERT INTO Ac_Items
			(
				[UserCode],
				[FullName],
				[Comment],
				[CreateBank],
				[BankType],
				[IsBank],
				[Deleted],
				[TypeName],
				[Sysrow],
				IsModify,
				[TypeId],
				[ParId],
				[Leveal],
				[SonNum],
				[SonCount],
				[Name],
				[PyCode],
				[XiWaMaxNumber]
			)
		VALUES
			(
				@usercode,
				@fullname,
				@comment,
				@CreateBank,
				@BankType,
				1,
				0,
				'B',
				0,
				1,
				'',
				'',
				1,
				0,
				0,
				'',
				@PyCode,
				@XiWaMaxNumber
				)
		SET @NIDS=SCOPE_IDENTITY();
		SET @ErrorCount+=@@ERROR
	END
ELSE IF(@type=2)
	BEGIN
		UPDATE Ac_Items 
		SET 
			UserCode=@UserCode,
			FullName=@FullName,
			CreateBank=@CreateBank,
			BankType=@BankType,
			IsBank=@IsBank,
			Comment=@Comment,
			XiWaMaxNumber=@XiWaMaxNumber
		WHERE
			nId=@nid
		SET @ErrorCount+=@@ERROR
	END	

DELETE FROM Ac_Items_Detail WHERE nId=@NIDS OR nId=@nid
SET @ErrorCount+=@@ERROR


IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='信息添加失败！'
		IF(@type=2)
			SET @MSG2='信息修改失败'
		RAISERROR(@MSG2,16,1)	
	END
ELSE 
	BEGIN
		IF(@type=2)
			SET @NIDS=@nid
		RETURN @NIDS
	END
	
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAccountInitialData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_UpdateAccountInitialData
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	glj	
	Date	:	2015-03-25
	Description	: 保存
			【账务期初】中【往来/库存/固定资产期初余额转入】时，对于无期初单据或卡片数据为0允许引入成功；
*/

CREATE PROCEDURE Gp_UpdateAccountInitialData
(
	@STypeId	VARCHAR(50),    --分支机构id
	@ATypeId	VARCHAR(50),	--科目id
	@Cid		INT,			--币别id
	@Fyear		INT,			--年度
	@FPeriod	INT				--期间
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN TRAN


DECLARE @Error INT=0
IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount WHERE STypeId=@STypeId AND Cid=@Cid AND ATypeId=@ATypeId AND FYear=@Fyear AND FPeriod=@FPeriod)
	UPDATE Ac_IniAccount 
	SET 
		iniYTotal=0,
		iniYTotalFor=0,
		FDebit=0,
		FDebitFor=0,
		FCredit=0,
		FCreditFor=0,
		iniTotal=0,
		iniTotalFor=0,
		FYTotal=0,
		FYTotalFor=0,
		FYTotalDebit=0,
		FYTotalDebitFor=0,
		FYTotalCredit=0,
		FYTotalCreditFor=0,
		IniYqty=0,
		FDebitqty=0,
		FCreditqty=0,
		iniqty=0
	WHERE 
		STypeId=@STypeId
		AND ATypeId=@ATypeId
		AND Cid=@Cid
		AND FYear=@Fyear
		AND FPeriod=@FPeriod

SELECT @Error+=@@ERROR

DELETE Ac_IniAccount_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND FYear=@Fyear AND FPeriod=@FPeriod
SELECT @Error+=@@ERROR
DELETE Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId=@STypeId AND ATypeId=@ATypeId AND FYear=@Fyear AND FPeriod=@FPeriod
SELECT @Error+=@@ERROR

IF(@Error=0)
	BEGIN
		COMMIT TRAN
		RETURN 1
	END
ELSE 
	BEGIN
		ROLLBACK TRAN
		RETURN 0
	END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAcFixedAssets]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateAcFixedAssets]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产 新增、编辑
-- 时间：2012-05-21	
-- 作者：古丽娟	
-- ========================================================================
CREATE PROCEDURE Gp_UpdateAcFixedAssets
(
	@nid		int,					--Id
	@usercode	VARCHAR(200),			--编码
	@fullname	VARCHAR(400),			--名称
	@comment	VARCHAR(500),			--备注
	@type		INT						--update类型  1:新增 2：修改
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @Name VARCHAR(200),@NIDS INT,@ErrorCount INT =0

--判断编号是否重复
IF(ISNULL(@nid,0)>0)
	SELECT @Name=FullName FROM Ac_Items WHERE  UserCode=@usercode AND nId<>@nid
ELSE
	SELECT @Name=FullName FROM Ac_Items WHERE  UserCode=@usercode
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1)RETURN
	END
--判断名称是否重复
IF(ISNULL(@nid,0)>0)
	SELECT @Name=FullName FROM Ac_Items WHERE FullName=@fullname AND nId<>@nid
ELSE
	SELECT @Name=FullName FROM Ac_Items WHERE  FullName=@fullname
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG1 VARCHAR(100)='与【'+@Name+'】的名称相同，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END	
	
--缓存字段
	
DECLARE @PyCode VARCHAR(50)=(SELECT dbo.fun_getPY(@FullName)),@XiWaMaxNumber INT=0
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_Items
IF(@type=1)
	BEGIN
		INSERT INTO Ac_Items
			(
				[UserCode],
				[FullName],
				[Comment],
				[Deleted],
				[TypeName],
				[Sysrow],
				IsModify,
				[TypeId],
				[ParId],
				[Leveal],
				[SonNum],
				[SonCount],
				[Name],
				[CreateBank],
				[BankType],
				[IsBank],
				[PyCode],
				[XiWaMaxNumber]
			)
		VALUES
			(
				@usercode,
				@fullname,
				@comment,
				0,
				'F',
				0,
				1,
				'',
				'',
				1,
				0,
				0,
				'',
				'',
				'',
				0,
				@PyCode,
				@XiWaMaxNumber
				)
		SET @NIDS=SCOPE_IDENTITY();
		SET @ErrorCount+=@@ERROR
	END
ELSE IF(@type=2)--修改
	BEGIN
		UPDATE Ac_Items 
		SET 
			UserCode=@usercode,
			FullName=@fullname,
			Comment=@comment,
			XiWaMaxNumber=@XiWaMaxNumber
		WHERE 
			nId=@nid
		SET @ErrorCount+=@@ERROR
	END

DELETE FROM Ac_Items_Detail WHERE nId=@NIDS OR nId=@nid
SET @ErrorCount+=@@ERROR

IF(@ErrorCount<>0)
	BEGIN
		DECLARE @MSG2 VARCHAR(10)='信息添加失败！'
		IF(@type=2)
			SET @MSG2='信息修改失败！'
		RAISERROR(@MSG2,16,1)
	END
ELSE 
	BEGIN
		IF(@type=2)
			SET @NIDS=@nid
		RETURN @NIDS
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAcItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateAcItems]
GO          

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_items 1:启用 2：停用 3:删除
-- 时间：	2013-01-30
-- 作者：	glj
--TypeName	B:现金银行 G：其他收入 E：费用类型 F：固定资产 C：资产项 L:负债项
-- ========================================================================
CREATE PROC Gp_UpdateAcItems
(
	@nid			VARCHAR(50)='',		--操作ID
	@TypeName		VARCHAR(2)='',		--信息类型 B:现金银行G：其他收入E：费用类型F：固定资产C：资产项 L:负债项
	@OperatorID		VARCHAR(50),		-- 操作员
	@Type			INT=0				--操作类型  1：启用 2：停用 3：删除
)

--@encode$--
AS
SET NOCOUNT ON

DECLARE @ERROR INT=0

IF(@Type<=0)
	BEGIN
		RAISERROR('执行异常',16,1) RETURN
	END
ELSE 
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE nId=@nid)
			BEGIN
				RAISERROR('该信息已经删除！不能执行该操作',16,1)RETURN
			END
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE Sysrow=1 AND nId=@nid)
			BEGIN
				RAISERROR('系统默认数据，不执行该操作！',16,1)RETURN
			END
		IF(@Type=1)--启用
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE nId=@nid AND Deleted=0)
					BEGIN
						RAISERROR('该信息已经启用，不需要重复启用！',16,1)RETURN
					END
				UPDATE Ac_Items SET Deleted=0 WHERE nId=@nid
				SET @ERROR+=@@ERROR
			END
		IF(@Type=2)--停用
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE nParId=(SELECT nTypeId FROM Ac_Items WHERE nId=@nid))
					BEGIN
						RAISERROR('该信息为父级节点，不允许停用！',16,1)RETURN
					END
				IF EXISTS(SELECT *FROM PosInfo WHERE BankCardID =@nid)
					BEGIN
						RAISERROR('该信息已关联POS，不允许停用！',16,1)RETURN
					END	
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE nId=@nid AND Deleted=1)
					BEGIN
						RAISERROR('该信息已经停用，不需要重复停用！',16,1)RETURN
					END
				IF(@TypeName='B')--现金银行
				BEGIN	
					IF EXISTS(SELECT *FROM PosInfo WHERE BankCardID =@nid OR wxpayid=@nid OR alipayid=@nid)
					BEGIN
						RAISERROR('该信息已关联POS，不能停用！',16,1)RETURN
					END	
				END
				UPDATE Ac_Items SET Deleted=1 WHERE nId=@nid
				SET @ERROR+=@@ERROR
			END
		IF(@Type=3)--删除
			BEGIN
				DECLARE @RET INT=0
				SET @RET=(SELECT dbo.Fn_GetIsUse_Items(@nid,0))
				IF @RET>0
					BEGIN
						RAISERROR('该信息已经使用，不能删除！',16,1)RETURN
					END	
					BEGIN	
					IF EXISTS(SELECT *FROM PosInfo WHERE BankCardID =@nid OR wxpayid=@nid OR alipayid=@nid)
					BEGIN
						RAISERROR('该信息已关联POS，不能删除！',16,1)RETURN
					END	
					IF EXISTS(SELECT * FROM dbo.WdShopConfig WHERE PayitemId= @nid)
					BEGIN
						RAISERROR('该项目已在网店配置中使用，不能删除！',16,1)RETURN
					END	
					IF EXISTS(SELECT * FROM dbo.PayConfigInfo WHERE BankCardID=@nid)
					BEGIN
						RAISERROR('该项目已在支付宝或微信结算设置中使用，不能删除！',16,1)RETURN
					END 
				END
					
				DECLARE @nTypeId VARCHAR(50)
				SELECT @nTypeId=nTypeId  FROM Ac_Items WHERE nId=@nid
				
				--判断是否是父级
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE nParId=@nTypeId)
					BEGIN
							RAISERROR('该信息下已有子级,请先删除子级在进行删除！',16,1)RETURN
					END	
				--删除零售单默认账户
				DELETE FROM RetailConfig WHERE ATypeID=CONVERT(VARCHAR(50),@nid)
				set @ERROR+=@@ERROR
				--修改父级sonCount/sonNum值
				DECLARE @ParTypeID	VARCHAR(50)=(SELECT nParId FROM Ac_Items WHERE nId=@nid)
				
				UPDATE Ac_Items SET SonNum-=1 WHERE nTypeId=@ParTypeID
				SET @ERROR+=@@ERROR
				
				DELETE FROM Ac_Items_Detail WHERE nId=@nid--删除关联分支机构信息
				SET @ERROR+=@@ERROR
				DELETE FROM Ac_Items WHERE nId=@nid--删除项目主表
				SET @ERROR+=@@ERROR
				----更新父级缓存
				--EXEC Gp_UpdateAcItemNParidXiWaMaxNumber @nid
				
				--删除权限关联
				EXEC GP_DeleteBaseL 'A',@nTypeId
			END
	END
IF(@ERROR<>0)
	BEGIN
		RAISERROR('执行异常！',16,1)
	END
	
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateAcPeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateAcPeriod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/03
	Description	: 保存账务期初数据
*/
CREATE PROCEDURE Gp_UpdateAcPeriod
(
	@STypeId								VARCHAR(50),   --分支机构id	
	@Cid									INT,           --当前币别id  
	@AccountingPeriod Type_AcPeriod			Readonly	   --账务期初数据	
)
--@encode$--
AS
SET NOCOUNT ON
 
DECLARE 
	@FullName VARCHAR(MAX)=''--数据错误科目名称
	
--判断账务期初分支机构是否被删除	
SELECT @FullName=FullName FROM SType WHERE TypeId=@STypeId
IF ISNULL(@FullName,'')=''
	BEGIN
		RAISERROR('当前选中分支机构【%s】已不存在,请重新打开页面后重试！',16,1,@FullName) RETURN 
	END
	
--判断账务期初币种是否被删除
SET @FullName=''
SELECT @FullName=FullName FROM dbo.Ac_Currency WHERE CId = @Cid
IF ISNULL(@FullName,'')=''
	BEGIN
		RAISERROR('当前选中币种【%s】已不存在,请重新打开页面后重试！',16,1,@FullName) RETURN 
	END
	
--判断分支机构是否已经开账
SET @FullName=''
IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE IsUse=1 AND Stypeid=@STypeId)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='ProInfo' AND SubValue='2')
			SET @FullName='分支机构'
			
		RAISERROR('%s 已经开账，不执行此操作！',16,1,@FullName) RETURN	
	END	
	
--科目是否停用
SET @FullName=''
SELECT @FullName+=A.FullName+';' FROM Ac_Account A INNER JOIN @AccountingPeriod P ON P.STypeId=A.StypeId AND P.ATypeId=A.TypeId AND A.Deleted=1
IF(@FullName<>'')
	BEGIN
		SET @FullName=SUBSTRING(@FullName,1,LEN(@FullName)-1)
		RAISERROR('科目【%s】已停用，请刷新页面后重试！',16,1,@FullName) RETURN	
	END	
	
--数量核算变更科目
SET @FullName=''
SELECT @FullName+=A.FullName+';' FROM Ac_Account A INNER JOIN @AccountingPeriod P ON P.STypeId=A.StypeId AND P.ATypeId=A.TypeId AND A.AdjustAccounts=0 AND (P.IniYqty<>0 OR P.FDebitqty<>0 OR P.FCreditqty<>0 OR P.iniqty<>0)
IF(@FullName<>'')
	BEGIN
		SET @FullName=SUBSTRING(@FullName,1,LEN(@FullName)-1)
		RAISERROR('科目【%s】已取消【数量核算】，请刷新页面后重试！',16,1,@FullName) RETURN	
	END	
--币种变更科目
SET @FullName=''
SELECT @FullName+=A.FullName+';' FROM Ac_Account A WHERE Cid<>0 AND EXISTS(SELECT * FROM @AccountingPeriod P WHERE P.STypeId=A.StypeId AND P.ATypeId=A.TypeId AND P.Cid<>A.Cid)
IF(@FullName<>'')
	BEGIN
		SET @FullName=SUBSTRING(@FullName,1,LEN(@FullName)-1)
		RAISERROR('【%s】科目币种已经发生变更，请刷新页面后重试！',16,1,@FullName) RETURN	
	END	
	
--辅助核算变更科目
SET @FullName=''
SELECT @FullName+=a.FullName+';' 
FROM Ac_Account_Assist_CheckItems C
INNER JOIN Ac_Account A ON A.StypeId=C.STypeId AND A.TypeId=C.ATypeId AND C.Cid=@Cid --AND C.STypeId=@STypeId 
INNER JOIN @AccountingPeriod P ON P.STypeId=A.STypeId AND P.ATypeId=A.TypeId AND P.Cid=@Cid AND (P.iniYTotal<>0 OR P.iniYTotalFor<>0 OR P.FDebit<>0 OR P.FDebitFor<>0 OR P.FCredit<>0 OR P.FCreditFor<>0 OR P.iniTotal<>0 OR P.iniTotalFor<>0 OR P.FYTOTAL<>0 OR P.FYTOTALFOR<>0 OR P.IniYqty<>0 OR P.FDebitqty<>0 OR P.FCreditqty<>0 OR P.iniqty<>0)
WHERE NOT EXISTS(SELECT * FROM Ac_IniAccount_Assist_CheckItems_Detail D WHERE D.STypeId=C.STypeId AND D.ATypeId=C.ATypeId AND D.Ascids=C.Ascids)
	
IF(ISNULL(@FullName,'')<>'')
	BEGIN
		SET @FullName=SUBSTRING(@FullName,1,LEN(@FullName)-1)
		RAISERROR('科目【 %s 】已启用辅助核算项，请刷新页面后重试！',16,1,@FullName) RETURN 
	END

BEGIN TRANSACTION

DECLARE 
	@errorSum	INT=0,
	@FYear		VARCHAR(10),--当前分支机构年度
	@FPeriod	INT			--当前分支机构期间
SELECT @FYear=SFYear,@FPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId

--删除当前修改已含数据
DELETE FROM Ac_IniAccount 
FROM Ac_IniAccount A 
INNER JOIN @AccountingPeriod P ON P.STypeId=a.STypeId AND P.ATypeId=A.ATypeId AND A.Cid=@Cid
Set @errorSum+=@@error	

------------插入数据
INSERT INTO Ac_IniAccount
(
	STypeId,
	ATypeId,
	iniYTotal,
	iniYTotalFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	iniTotal,
	iniTotalFor,
	FYTotal,
	FYTotalFor,
	Cid,
	FYear,
	FPeriod,
	IniYqty,
	FDebitqty,
	FCreditqty,
	iniqty
)
SELECT 
	P.STypeId,
	P.ATypeId,
	dbo.F_RoundTotal(P.INIYTOTAL),
	dbo.F_RoundTotal(P.INIYTOTALFOR),
	dbo.F_RoundTotal(P.FDEBIT),
	dbo.F_RoundTotal(P.FDEBITFOR),
	dbo.F_RoundTotal(P.FCREDIT),
	dbo.F_RoundTotal(P.FCREDITFOR),
	dbo.F_RoundTotal(P.INITOTAL),
	dbo.F_RoundTotal(P.INITOTALFOR),
	dbo.F_RoundTotal(P.FYTOTAL),
	dbo.F_RoundTotal(P.FYTOTALFOR),
	@Cid Cid,
	@FYear,
	@FPeriod,
	IniYqty,
	FDebitqty,
	FCreditqty,
	iniqty
FROM @AccountingPeriod P
INNER JOIN Ac_Account A ON A.StypeId=P.STypeId AND A.TypeId=P.ATypeId AND A.SonNum=0
SET @errorSum+=@@error

--删除期初辅助核算表不在期初主表里面的科目数据
--主表
--SELECT * FROM dbo.Ac_Account

SELECT a.ATypeId INTO #TmepDataNoDelete FROM (SELECT AC.ATypeId FROM Ac_IniAccount_Assist_CheckItems AS AC GROUP BY AC.STypeId,Cid,ATypeId HAVING SUM(AC.IniYTotal)= 0) AS A

DELETE FROM Ac_IniAccount_Assist_CheckItems 
FROM Ac_IniAccount_Assist_CheckItems C
WHERE NOT EXISTS(SELECT * FROM Ac_IniAccount I WHERE I.STypeId=C.STypeId AND I.ATypeId=C.ATypeId AND I.Cid=C.Cid) 
AND C.ATypeId NOT IN(SELECT ATypeId FROM #TmepDataNoDelete)
SET @errorSum+=@@error

DELETE FROM Ac_IniAccount_Assist_CheckItems
FROM Ac_IniAccount_Assist_CheckItems C
INNER JOIN Ac_IniAccount I ON I.STypeId=C.STypeId AND I.ATypeId=C.ATypeId AND I.Cid=C.Cid AND I.iniYTotal=0 AND I.iniYTotalFor=0 AND I.FDebit=0 AND I.FDebitFor=0 AND I.FCredit=0 AND I.FCreditFor=0 AND I.iniTotal=0 AND I.iniTotalFor=0 AND I.IniYqty=0 AND I.FDebitqty=0  AND I.FCreditqty=0 AND I.iniqty=0
WHERE C.ATypeId NOT IN(SELECT ATypeId FROM #TmepDataNoDelete)
SET @errorSum+=@@error

----明细表
DELETE FROM Ac_IniAccount_Assist_CheckItems_Detail
FROM  Ac_IniAccount_Assist_CheckItems_Detail D
WHERE NOT EXISTS(SELECT * FROM Ac_IniAccount I WHERE I.STypeId=D.STypeId AND I.ATypeId=D.ATypeId AND I.Cid=D.Cid)
AND D.ATypeId NOT IN(SELECT ATypeId FROM #TmepDataNoDelete)
SET @errorSum+=@@error

DELETE FROM Ac_IniAccount_Assist_CheckItems_Detail
FROM Ac_IniAccount_Assist_CheckItems_Detail D
INNER JOIN Ac_IniAccount I ON I.STypeId=D.STypeId AND I.ATypeId=D.ATypeId AND I.Cid=D.Cid AND I.iniYTotal=0 AND I.iniYTotalFor=0 AND I.FDebit=0 AND I.FDebitFor=0 AND I.FCredit=0 AND I.FCreditFor=0 AND I.iniTotal=0 AND I.iniTotalFor=0 AND I.IniYqty=0 AND I.FDebitqty=0  AND I.FCreditqty=0 AND I.iniqty=0 
WHERE  D.ATypeId NOT IN(SELECT ATypeId FROM #TmepDataNoDelete)
SET @errorSum+=@@error

IF @errorSum<>0  --如果有错误
	BEGIN
		ROLLBACK TRANSACTION 
		RETURN 0
	END
ELSE
	BEGIN
		COMMIT TRANSACTION
		RETURN 1
	END

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateArApIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_UpdateArApIni
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-02-21
-- Description: 应收、应付期初修改
-- =============================================
CREATE PROCEDURE Gp_UpdateArApIni
(
	@stypeid	VARCHAR(1000)='',
	@typeid		varchar(1000)='',
	@total		 NUMERIC(24, 10) ,
	@pretotal	 NUMERIC(24, 10) ,
	@comment	varchar(1000),
	@flag		varchar(10)
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON;
	IF 	@flag='AR'
	begin
		/*If @pretotal<>0
			UPDATE BType_ARAPTotal SET YFTotal00=0
					WHERE BTypeID = @typeid AND STypeID=@stypeid
		IF @total<>0
			UPDATE BType_ARAPTotal SET APTotal00=0
					WHERE BTypeID = @typeid AND STypeID=@stypeid*/
		IF NOT EXISTS(
					SELECT BTypeID
					FROM BType_ARAPTotal
					WHERE BTypeID=@typeid AND STypeID=@stypeid
				)
				BEGIN
					INSERT BType_ARAPTotal(BTypeID,STypeID,ARTotal00,YSTotal00)
					SELECT @typeid,@stypeid,dbo.F_RoundTotal(@Total),dbo.F_RoundTotal(@pretotal)
				END
				ELSE
				BEGIN
					UPDATE BType_ARAPTotal SET ARTotal00 = dbo.F_RoundTotal(@Total),YSTotal00=dbo.F_RoundTotal(@pretotal)
					WHERE BTypeID = @typeid AND STypeID=@stypeid
					IF @Total=0
					BEGIN
						UPDATE BType_ARAPTotal SET ARTotal = dbo.F_RoundTotal(@Total)
						WHERE BTypeID = @typeid AND STypeID=@stypeid
					END
					IF @pretotal=0
					BEGIN
						UPDATE BType_ARAPTotal SET YSTotal=dbo.F_RoundTotal(@pretotal)
						WHERE BTypeID = @typeid AND STypeID=@stypeid
					END
				END
		if not exists(select 1 from AType_Total where ATypeID='0000200006' and STypeID=@stypeid)
			insert into AType_Total(STypeID,ATypeID,Total,Total00) values(@stypeid,'0000200006',0,0)
		update AType_Total set Total00=dbo.F_RoundTotal((select SUM(ystotal00) from BType_ARAPTotal where STypeID=@stypeid))  where ATypeID='0000200006' and STypeID=@stypeid
				
	end
	else
	begin
		/*If @pretotal<>0
			UPDATE BType_ARAPTotal SET YSTotal00=0
					WHERE BTypeID = @typeid AND STypeID=@stypeid
		IF @total<>0
			UPDATE BType_ARAPTotal SET ARTotal00=0
					WHERE BTypeID = @typeid AND STypeID=@stypeid*/
		IF NOT EXISTS(
					SELECT BTypeID
					FROM BType_ARAPTotal
					WHERE BTypeID=@typeid AND STypeID=@stypeid
				)
				BEGIN
					INSERT BType_ARAPTotal(BTypeID,STypeID,APTotal00,YFTotal00)
					SELECT @typeid,@stypeid,dbo.F_RoundTotal(@Total),dbo.F_RoundTotal(@pretotal)
				END
				ELSE
				BEGIN
					UPDATE BType_ARAPTotal SET APTotal00 = dbo.F_RoundTotal(@Total),YFTotal00=dbo.F_RoundTotal(@pretotal)
					WHERE BTypeID = @typeid AND STypeID=@stypeid
					IF @Total=0
					BEGIN
						UPDATE BType_ARAPTotal SET APTotal = dbo.F_RoundTotal(@Total)
						WHERE BTypeID = @typeid AND STypeID=@stypeid
					END
					IF @pretotal=0
					BEGIN
						UPDATE BType_ARAPTotal SET YFTotal=dbo.F_RoundTotal(@pretotal)
						WHERE BTypeID = @typeid AND STypeID=@stypeid
					END
				END
		if not exists(select 1 from AType_Total where ATypeID='0000100009' and STypeID=@stypeid)
			insert into AType_Total(STypeID,ATypeID,Total,Total00) values(@stypeid,'0000100009',0,0)
		update AType_Total set Total00=dbo.F_RoundTotal((select SUM(YFTotal00) from BType_ARAPTotal where STypeID=@stypeid))  where ATypeID='0000100009' and STypeID=@stypeid
	end
	update btype set initcomment=@comment where typeId=@typeid
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateArea]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateArea]
GO




CREATE       PROCEDURE [Gp_UpdateArea]
(
 @TypeId  [varchar](50),
 @UserCode  [varchar](256),
 @FullName  [varchar](256),
 @Name   [varchar](256),
 @Tel   [varchar](256),
 @LinkMan   [varchar](256),
 @PyCode   varchar(200),
 @Comment  [varchar](256)

)
--@encode$--
AS
SET NOCOUNT ON 
if exists(select usercode from AreaType where (usercode=@usercode  or fullname=@fullname) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -3
end
if exists(select usercode from AreaType where (usercode=@fullname  or fullname=@usercode) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -10
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

UPDATE [dbo].[AreaType] 
SET  [FullName]  = @FullName,
  [Name]     = @Name,
  [UserCode] = @UserCode,
  [Comment]  = @Comment,
  [Tel]      = @Tel,
  [LinkMan]  = @LinkMan,
  [PyCode] = @returnPym

WHERE 
 ( [typeId]  = @typeId )

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM AreaType
UPDATE AreaType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateAreaDept]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateAreaDept]
GO
















/****** Object:  Stored Procedure dbo.Gp_UpdateAreaDept    Script Date: 2002-6-20 10:14:51 ******/

CREATE   PROCEDURE [Gp_UpdateAreaDept]
(
 @DbName  [varchar](20),
 @Typeid  [varchar](50),
 @UserCode  [varchar](10),
 @FullName  [varchar](50),
 @Comment  [varchar](50)
)
--@encode$--
AS 
SET NOCOUNT ON 
declare @Sql [varchar](500)
select @Sql='UPDATE '+@dbname++' SET  usercode = '+char(39)+@usercode+char(39)+',
  Fullname = '+char(39)+@Fullname+char(39)+',
  Comment = '+char(39)+@Comment+char(39)+
 ' WHERE typeid = '+char(39)+@typeid+char(39)
exec(@Sql)

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAssetBusinessType]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_UpdateAssetBusinessType
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-业务类型 修改信息
-- 时间：2013-05-23
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Gp_UpdateAssetBusinessType
(
	@Id			INT,				--业务类型
	@Atid		VARCHAR(10),			--模板
	@Deleted	BIT					--时候启用
)
--@encode$--

AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetBusinessType WHERE Id=@Id)
	BEGIN
		RAISERROR('该信息不存在，请确认！',16,1) RETURN 
	END
	 
IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=(SELECT STypeId FROM Ac_AssetBusinessType WHERE Id=@Id) AND deleted=1)
	BEGIN
		RAISERROR('该分支机构已被停用，不能进行操作！',16,1) RETURN
	END	
	
UPDATE Ac_AssetBusinessType SET Atid=@Atid,Deleted=@Deleted WHERE Id=@Id
RETURN 1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAssetsCategory]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_UpdateAssetsCategory
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-资产类别 基本操作
-- 时间：2013-05-15
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Gp_UpdateAssetsCategory
(
	@OperatorId			VARCHAR(50),		--操作人
	@Type				INT,				--操作类型 1 2：新增 3：编辑
	@ID					INT,				--ID
	@StypeId			VARCHAR(50),		--分支机构
	@UserCode			VARCHAR(26),		--编号
	@FullName			VARCHAR(66),		--名称
	@UnitsFullName		VARCHAR(200),		--计量单位
	@DepreciationMean	VARCHAR(50),		--折旧方法
	@RemainsRate		 NUMERIC(24, 10) ,		--残值率
	@DurYear			INT,				--预计使用期限
	@DepATypeId			VARCHAR(50),		--累计折旧科目
	@ExpenseATypeId		VARCHAR(50),		--费用科目
	@AssertATypeId		VARCHAR(50),		--固定资产科目	
	@Comment			VARCHAR(256)		--备注

	
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @Error		INT=0,
		@TypeName	VARCHAR(5)='',
		@Name		VARCHAR(66)=''
		
IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND deleted=1)
	BEGIN
		RAISERROR('该分支机构已被停用，不能进行操作！',16,1) RETURN
	END	
	
--判断编号是否重复
IF(@Type=3)
	SELECT @Name=FullName FROM Ac_AssetsCategory WHERE  UserCode=@usercode AND Id<>@ID
ELSE
	SELECT @Name=FullName FROM Ac_AssetsCategory WHERE  UserCode=@usercode
	
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG VARCHAR(100)='与【'+@Name+'】的编号相同 ，请重新进行编号！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG,16,1) RETURN
	END
	
--判断名称是否重复
IF(@Type=3)
	SELECT @Name=FullName FROM Ac_AssetsCategory WHERE  FullName=@fullname AND Id<>@ID AND StypeId=@StypeId
ELSE
	SELECT @Name=FullName FROM Ac_AssetsCategory WHERE  FullName=@fullname AND StypeId=@StypeId
IF(ISNULL(@Name,'')<>'')
	BEGIN
		DECLARE @MSG1 VARCHAR(100)='该分支机构已存在名为【'+@Name+'】的资产类别，请另取一个名称！'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
		RAISERROR(@MSG1,16,1)RETURN
	END	
	
SET @DepreciationMean=ISNULL(@DepreciationMean,-1)

IF @Type=1--新增
	BEGIN
		INSERT INTO Ac_AssetsCategory
		(
			StypeId,
			UserCode,
			FullName,
			Units,
			DepreciationMean,
			RemainsRate,
			DurYear,
			DepATypeId,
			ExpenseATypeId,
			AssertATypeId,
			Comment
		)
		VALUES
		(
			@StypeId,
			@UserCode,
			@FullName,
			@UnitsFullName,
			@DepreciationMean,
			dbo.F_RoundPercentage(@RemainsRate),
			@DurYear,
			@DepATypeId,
			@ExpenseATypeId,
			@AssertATypeId,
			@Comment
		)
		SET @Error+=@@ERROR
	END
ELSE IF @Type=3--修改
	BEGIN
		UPDATE Ac_AssetsCategory
		SET 
			StypeId=@StypeId,
			FullName=@FullName,
			Units=@UnitsFullName,
			DepreciationMean=@DepreciationMean,
			RemainsRate=dbo.F_RoundPercentage(@RemainsRate),
			DurYear=@DurYear,
			DepATypeId=@DepATypeId,
			ExpenseATypeId=@ExpenseATypeId,
			AssertATypeId=@AssertATypeId,
			Comment=@Comment
		WHERE Id=@ID
		SET @Error+=@@ERROR
			
	END
IF(@Error<>0)
	BEGIN
		IF(@Type=1)
			SET @TypeName='新增'
		ELSE
			SET @TypeName='修改'
		
		RAISERROR('信息%s失败！',16,1,@TypeName) RETURN -1
	END
ELSE 
	RETURN 1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAssetsDepartmentChange]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_UpdateAssetsDepartmentChange
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-部门转移
-- 时间：2013-05-23
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Gp_UpdateAssetsDepartmentChange
(
	@StypeID		VARCHAR(50),	--分支机构
	@CardId			INT,			--固定资产卡片ID
	--@UserCode		VARCHAR(26)='',	--固定资产卡片编号
	@OldDTypeId		VARCHAR(50),	--原部门ID
	@DTypeId		VARCHAR(50),	--部门ID
	@OldLocationId	VARCHAR(50),	--原存放地点
	@LocationId		VARCHAR(50),	--存放地点
	@OldDisATypeId	VARCHAR(50),	--原折旧分配科目
	@DisATypeId		VARCHAR(50),	--折旧分配科目
	@OperatorID		VARCHAR(50),	--操作员ID
	@BusinessDate	DATETIME		--业务日期
)
--@encode$--

AS
SET NOCOUNT ON 
--声明变量
DECLARE 
	@Error INT=0,
	@BillNumberID	INT,
	@BusinessTypeID	INT=0,			-- 指定分支机构部门转移 业务类型ID
	@UserCode		VARCHAR(26)=''	--固定资产卡片编号
	
IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND deleted=1)
	BEGIN
		RAISERROR('该分支机构已被停用，不能进行操作！',16,1) RETURN
	END		
IF(@OldDTypeId=@DTypeId)
	BEGIN
		RAISERROR('新部门与原部门相同，请重新选择!',16,1,@UserCode)
		RETURN
	END

--判断是否存在业务日期大于本单据日期的记录
IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards_History WHERE BusinessDate>@BusinessDate AND AssertsCardId=@CardId AND BillType<>-3)
	BEGIN
		SELECT @UserCode=UserCode FROM Ac_AssetsCards WHERE Id=@CardId
		RAISERROR('资产编号 %s 在本单据日期之后已有操作记录，不能进行部门转移！',16,1,@UserCode)
		RETURN
	END
IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsModifyRecords WHERE CardId=@CardId AND Id NOT IN(SELECT SourceId FROM Ac_Provision_Voucher WHERE SourceType=2))
	AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue=1)
	BEGIN
		RAISERROR('该固定资产尚存在未生成凭证的部门转移单，请先将该固定资产之前的部门转移单删除或生成凭证后，再重新做新的部门转移单',16,1)
		RETURN 
	END
--添加部门转移记录
INSERT INTO Ac_AssetsModifyRecords
(
	CardId,
	OldDTypeId,
	DTypeId,
	OldLocationId,
	LocationId,
	OldDisATypeId,
	DisATypeId,
	OperationDate,
	ETypeId,
	BusinessDate
)
VALUES
(
	@CardId,
	@OldDTypeId,
	@DTypeId,
	@OldLocationId,
	@LocationId,
	@OldDisATypeId,
	@DisATypeId,
	GETDATE(),
	@OperatorID,
	@BusinessDate
)
SELECT @BillNumberID=SCOPE_IDENTITY();
SET @Error+=@@ERROR

--取最大缓存值，以便更新缓存
DECLARE @XiWaMaxNumber INT
SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM Ac_AssetsCards
--卡片信息立即更新
UPDATE Ac_AssetsCards 
SET 
	DTypeid=@DTypeId,
	LocationId=@LocationId,
	DisATypeId=@DisATypeId,
	XiWaMaxNumber=@XiWaMaxNumber
WHERE Id=@CardId
SET @Error+=@@ERROR

SELECT @BusinessTypeID=Id FROM Ac_AssetBusinessType WHERE STypeId=@StypeID AND FullName='部门转移'
--历史数据
EXEC Gp_SaveAssetsCardHistory @StypeID,@CardId,@OperatorID,@BusinessDate,-2,@BillNumberID,@BusinessTypeID,''

--折旧表的影响
UPDATE Ac_DepreciationPlan 
SET 
	DTypeid=@DTypeId,
	LocationId=@LocationId,
	DisATypeId=@DisATypeId 
WHERE 
	AssetCardId=@CardId 
	AND PlanState=0 
	AND PlanType IN(0,1)
SET @Error+=@@ERROR

IF @@ERROR>0 
	RAISERROR('部门转移失败！',16,1)
RETURN @BillNumberID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAssetStorageLocation]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_UpdateAssetStorageLocation
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-存放地点 基本操作
-- 时间：2013-05-15
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Gp_UpdateAssetStorageLocation
(
	@OperatorId	VARCHAR(50),		--操作人
	@Type		INT,				--操作类型 1：新增 2：编辑 3：删除
	@ID			INT,				--ID
	@Location	VARCHAR(256)		--使用状况
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @Error		INT=0,
		@TypeName	VARCHAR(5)=''
IF @Type=1 OR @Type=2
	BEGIN
		IF (EXISTS(SELECT TOP 1 1 FROM Ac_AssetStorageLocation WHERE Location=@Location) AND @Type=1) OR (EXISTS(SELECT TOP 1 1 FROM Ac_AssetStorageLocation WHERE Location=@Location AND Id<>@ID) AND @Type=2)
			BEGIN
				DECLARE @MSG VARCHAR(100)='已存在相同名称信息，请重新输入'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
				RAISERROR(@MSG,16,1) RETURN
			END
		IF @Type=1
			BEGIN
				INSERT INTO Ac_AssetStorageLocation(Location)VALUES(@Location)
				SET @Error+=@@ERROR
			END
		ELSE IF @Type=2
			BEGIN
				UPDATE Ac_AssetStorageLocation SET Location=@Location WHERE id=@ID
				SET @Error+=@@ERROR
			END
	END
ELSE IF @Type=3
	BEGIN
		DECLARE @RET INT=0
		SET @RET=(SELECT dbo.Fn_GetIsUse_Assets(@ID,2))
		IF @RET>0
			BEGIN
				RAISERROR('该信息已经使用，不允许删除！',16,1)RETURN
			END	
		DELETE Ac_AssetStorageLocation WHERE Id=@ID
		SET @Error+=@@ERROR
	END
IF(@Error<>0)
	BEGIN
		IF(@Type=1)
			SET @TypeName='添加'
		ELSE IF(@Type=2)
			SET @TypeName='修改'
		ELSE IF(@Type=3)
			SET @TypeName='删除'
		
		RAISERROR('信息%s失败！',16,1,@TypeName) RETURN -1
	END
ELSE 
	RETURN 1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAssetWorkingCondition]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_UpdateAssetWorkingCondition
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-使用状况 基本操作
-- 时间：2013-05-15
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Gp_UpdateAssetWorkingCondition
(
	@OperatorId	VARCHAR(50),		--操作人
	@Type		INT,				--操作类型 1：新增 2：编辑 3：删除
	@ID			INT,				--ID
	@Comment	VARCHAR(256)		--使用状况
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @Error		INT=0,
		@TypeName	VARCHAR(5)=''
IF @Type=1 OR @Type=2
	BEGIN
		IF (EXISTS(SELECT TOP 1 1 FROM Ac_AssetWorkingCondition WHERE Comment=@Comment) AND @Type=1 )
			OR 
			(EXISTS(SELECT TOP 1 1 FROM Ac_AssetWorkingCondition WHERE Comment=@Comment AND Id<>@ID) AND @Type=2 )
			BEGIN
				DECLARE @MSG VARCHAR(100)='已存在相同信息，请重新输入'+char(10)+'要放弃编辑，按【Esc】键可关闭窗口退出!'
				RAISERROR(@MSG,16,1) RETURN
			END
		IF @Type=1
			BEGIN
				INSERT INTO Ac_AssetWorkingCondition(Comment)VALUES(@Comment)
				SET @Error+=@@ERROR
			END
		ELSE IF @Type=2
			BEGIN
				UPDATE Ac_AssetWorkingCondition SET Comment=@Comment WHERE id=@ID
				SET @Error+=@@ERROR
			END
	END
ELSE IF @Type=3
	BEGIN
		DECLARE @RET INT=0
		SET @RET=(SELECT dbo.Fn_GetIsUse_Assets(@ID,3))
		IF @RET>0
			BEGIN
				RAISERROR('该信息已经使用，不允许删除！',16,1)RETURN
			END	
		DELETE Ac_AssetWorkingCondition WHERE Id=@ID
		SET @Error+=@@ERROR
	END
IF(@Error<>0)
	BEGIN
		IF(@Type=1)
			SET @TypeName='添加'
		ELSE IF(@Type=2)
			SET @TypeName='修改'
		ELSE IF(@Type=3)
			SET @TypeName='删除'
		
		RAISERROR('信息%s失败！',16,1,@TypeName) RETURN -1
	END
ELSE 
	RETURN 1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM sys.types t JOIN sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_AssistInfor' AND ss.name=N'dbo')
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAssistInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Gp_UpdateAssistInfo]--删除此存储过程的引用
	DROP TYPE [dbo].Type_AssistInfor 
END
GO
CREATE TYPE Type_AssistInfor AS TABLE             --该表列同表Ac_IniAccount_Assist_CheckItems_Detail
(
	STypeId			VARCHAR(50),
	ATypeId			VARCHAR(50),
	Cid				INT, 
	Ascids			INT, 
	FieldValue		VARCHAR(50),
	IniYTotal		NUMERIC(24, 10) ,
	IniYTotalfor	NUMERIC(24, 10) ,
	IniYqty			NUMERIC(24, 10) ,--年初数量
	FDebit			NUMERIC(24, 10) ,
	FDebitfor		NUMERIC(24, 10) ,
	FDebitqty		NUMERIC(24, 10) ,--借方数量
	FCredit			NUMERIC(24, 10) ,
	FCreditfor		NUMERIC(24, 10) ,
	FCreditqty		NUMERIC(24, 10) ,--贷方数量
	IniTotal		NUMERIC(24, 10) ,
	IniTotalfor		NUMERIC(24, 10) ,
	iniqty			NUMERIC(24, 10), --期初数量
	FYTOTAL			NUMERIC(24, 10) ,
	FYTOTALFOR		NUMERIC(24, 10) ,
	Groupid			INT
)
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateAssistInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateAssistInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/04/27
	Description	: 保存账务期初下挂核算项数据
*/

CREATE PROCEDURE Gp_UpdateAssistInfo
(
	@STypeId								VARCHAR(50),    --分支机构id
	@TypeId									VARCHAR(50),	--科目id
	@Cid									INT,			--币别id	
	@AllData  Type_AssistInfor  			READONLY		--辅助核算项目数据
)
--@encode$--
AS
SET NOCOUNT ON 

--判断分支机构是否已经开账
IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=1)
	BEGIN
		DECLARE @ProStr VARCHAR(10)=''
		IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='ProInfo' AND SubValue='2')
			SET @ProStr='分支机构'
		
		SET @ProStr+='已经开账，不执行此操作！'	
		RAISERROR(@ProStr,16,1) RETURN	
	END
--判断科目是否存在
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND TypeId=@TypeId)
	BEGIN
		RAISERROR('科目已不存在，请确认！',16,1) RETURN
	END
--判断科目是否数量核算
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND TypeId=@TypeId AND AdjustAccounts=0) AND EXISTS(SELECT * FROM @AllData WHERE iniqty<>0 OR FDebitqty<>0 OR FCreditqty<>0 OR IniYqty<>0)
	BEGIN
		RAISERROR('此科目辅助核算类型异常，请确认后重试！',16,1) RETURN
	END
	
--判断科目是否存在
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND TypeId=@TypeId AND Cid<>0 AND Cid<>@Cid)
	BEGIN
		RAISERROR('科目外币核算类型已发生更改，请确认后重试！',16,1) RETURN
	END

--辅助核算科目保存是是否发生变更	
IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE Ascids NOT IN(SELECT Ascids FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid)) 
	OR EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids NOT IN(SELECT Ascids FROM @AllData))
	BEGIN
		RAISERROR('科目辅助核算已发生变更，请确认后重试！',16,1) RETURN
	END	

DECLARE 
	@Error			INT,
	@SFYear			VARCHAR(10),--分支机构启用年度
	@SFPeriod		VARCHAR(10),--分支机构启用期间
	@SQL			NVARCHAR(MAX)
		
SELECT @SFYear=SFYear,@SFPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId

BEGIN TRANSACTION
DELETE FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
SET @Error+=@@ERROR
DELETE FROM Ac_IniAccount_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
SET @Error+=@@ERROR
DELETE FROM Ac_IniAccount WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
SET @Error+=@@ERROR
--辅助核算明细表
INSERT INTO Ac_IniAccount_Assist_CheckItems_Detail
(
	STypeId,
	ATypeId,
	Cid,
	Ascids,
	FieldValue,
	IniYTotal,
	IniYTotalFor,
	IniYqty,
	FDebit,
	FDebitFor,
	FDebitqty,
	FCredit,
	FCreditFor,
	FCreditqty,
	IniTotal,
	IniTotalFor,
	iniqty,
	GroupId,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor
)
SELECT 
	STypeId,
	ATypeId,
	@Cid,
	Ascids,
	FieldValue,
	dbo.F_RoundTotal(SUM(IniYTotal)) IniYTotal,
	dbo.F_RoundTotal(SUM(IniYTotalFor)) IniYTotalFor,
	SUM(IniYqty) IniYqty,
	dbo.F_RoundTotal(SUM(FDebit)) FDebit,
	dbo.F_RoundTotal(SUM(FDebitFor)) FDebitFor,
	SUM(FDebitqty) FDebitqty,
	dbo.F_RoundTotal(SUM(FCredit)) FCredit,
	dbo.F_RoundTotal(SUM(FCreditFor)) FCreditFor,
	SUM(FCreditqty) FCreditqty,
	dbo.F_RoundTotal(SUM(IniTotal)) IniTotal,
	dbo.F_RoundTotal(SUM(IniTotalFor)) IniTotalFor,
	SUM(Iniqty) Iniqty,
	MIN(GroupId) GroupId,
	@SFYear FYear,
	@SFPeriod FPeriod,
	dbo.F_RoundTotal(SUM(FYTotal)) FYTotal,
	dbo.F_RoundTotal(SUM(FYTotalFor)) FYTotalFor 
FROM @AllData
GROUP BY STypeId,ATypeId,Ascids,FieldValue,GroupId
SET @Error+=@@ERROR

--损益类科目  跳过了验证的情况，损益类自动默认借方
IF(SUBSTRING(@TypeId,1,5)='00003')
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE (FDebit=FCredit AND FDebit<>0 AND FYTOTAL=0)) 
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYTotal=FDebit WHERE FDebit=FCredit AND FDebit<>0 AND FYTOTAL=0 AND STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
			
		IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE (FDebitfor=FCreditfor AND FDebitfor<>0 AND FYTOTALFOR=0))
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYTotalFor=FDebitfor WHERE FDebitfor=FCreditfor AND FDebitfor<>0 AND FYTOTALFOR=0 AND STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
			
		IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE FYTOTAL>FDebit AND FDebit>FCredit)
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYTOTAL=FDebit WHERE FYTOTAL>FDebit AND FDebit>FCredit AND STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
			
		IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE FYTOTAL>FCredit AND FCredit>FDebit)
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYTOTAL=FCredit WHERE FYTOTAL>FCredit AND FCredit>FDebit AND STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
	
		IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE FYTOTALFOR>FDebitfor AND FDebitfor>FCreditfor)
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYTotalFor=FDebitFor WHERE FYTOTALFOR>FDebitfor AND FDebitfor>FCreditfor AND STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
			
		IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE FYTOTALFOR>FCreditfor AND FCreditfor>FDebitfor)
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYTotalFor=FCreditFor WHERE FYTOTALFOR>FCreditfor AND FCreditfor>FDebitfor AND STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod
		
		IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE FYTOTAL>FDebit AND FDebit=FCredit)
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYTotal=FDebit WHERE  FYTotal>FDebit AND FDebit=FCredit AND STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod	
				
		IF EXISTS(SELECT TOP 1 1 FROM @AllData WHERE FYTOTALFOR>FDebitfor AND FDebitfor=FCreditfor)
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYTotalFor=FDebitfor WHERE FYTotalFor>FDebitfor AND FDebitfor=FCreditfor AND STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND FYear=@SFYear AND FPeriod=@SFPeriod						
				
	END
	
--辅助核算主表
INSERT INTO Ac_IniAccount_Assist_CheckItems
(
	STypeId,
	ATypeId,
	Cid,
	IniYTotal,
	IniYTotalFor,
	IniYqty,
	FDebit,
	FDebitFor,
	FDebitqty,
	FCredit,
	FCreditFor,
	FCreditqty,
	IniTotal,
	IniTotalFor,
	Iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor
)
SELECT 
	D.STypeId,
	D.ATypeId,
	D.Cid,
	IniYTotal,
	IniYTotalFor,
	IniYqty,
	FDebit,
	FDebitFor,
	FDebitqty,
	FCredit,
	FCreditFor,
	FCreditqty,
	IniTotal,
	IniTotalFor,
	Iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor
FROM Ac_IniAccount_Assist_CheckItems_Detail D
INNER JOIN  (
	SELECT
		STypeId,
		ATypeId,
		Cid,
		MAX(Ascids) Ascids,
		Groupid
	FROM Ac_IniAccount_Assist_CheckItems_Detail 
	WHERE 
		STypeId=@STypeId 
		AND ATypeId=@TypeId 
		AND Cid=@Cid
	GROUP BY 
		STypeId,
		ATypeId,
		Cid,
		GroupId
) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Cid=D.Cid AND F.Groupid=D.GroupId AND F.Ascids=D.Ascids
SET @Error+=@@ERROR	
--账务期初主表
INSERT INTO Ac_IniAccount
(
	STypeId,
	ATypeId,
	Cid,
	IniYTotal,
	IniYTotalFor,
	IniYqty,
	FDebit,
	FDebitFor,
	FDebitqty,
	FCredit,
	FCreditFor,
	FCreditqty,
	IniTotal,
	IniTotalFor,
	Iniqty,
	FYear,
	FPeriod,
	FYTotal,
	FYTotalFor
)
SELECT
	STypeId,
	ATypeId,
	Cid,
	dbo.F_RoundTotal(SUM(IniYTotal)),
	dbo.F_RoundTotal(SUM(IniYTotalFor)),
	SUM(IniYqty),
	dbo.F_RoundTotal(SUM(FDebit)),
	dbo.F_RoundTotal(SUM(FDebitFor)),
	SUM(FDebitqty),
	dbo.F_RoundTotal(SUM(FCredit)),
	dbo.F_RoundTotal(SUM(FCreditFor)),
	SUM(FCreditqty),
	dbo.F_RoundTotal(SUM(IniTotal)),
	dbo.F_RoundTotal(SUM(IniTotalFor)),
	SUM(Iniqty),
	FYear,
	FPeriod,
	dbo.F_RoundTotal(SUM(FYTotal)),
	dbo.F_RoundTotal(SUM(FYTotalFor))
FROM Ac_IniAccount_Assist_CheckItems
WHERE 
	STypeId=@STypeId 
	AND ATypeId=@TypeId 
	AND Cid=@Cid
GROUP BY STypeId,ATypeId,Cid,FYear,FPeriod
SET @Error+=@@ERROR

IF @Error<>0  --如果有错误
	BEGIN
		 ROLLBACK TRANSACTION 
		 RETURN 0
	END  
ELSE
	BEGIN
		COMMIT TRANSACTION   
		RETURN 1
	END

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateATypeTotall00]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateATypeTotall00]
GO





/*
	作者：谢吉康
	日期：2005-8-25
	描述：修改会计科目期初

	case "0000100001":
		alert('【系统提示】\n\n『库存商品总值合计』不允许录入账务期初！');				
	case "0000100002":
		alert('【系统提示】\n\n『固定资产合计』不允许录入账务期初！');				
	case "0000100004":
		alert('【系统提示】\n\n『全部银行存款合计』不允许录入账务期初！');				
	case "0000100005":
		alert('【系统提示】\n\n『应收款合计』不允许录入账务期初！');				
	case "0000100008":
		alert('【系统提示】\n\n『委托代销商品』不允许录入账务期初！');				
	case "0000200001":
		alert('【系统提示】\n\n『应付帐款合计』不允许录入账务期初！');				
	case "0000200003":
		alert('【系统提示】\n\n『代销商品款』不允许录入账务期初！');								
*/
CREATE PROCEDURE Gp_UpdateATypeTotall00
(
	@ATypeId		varchar(100),	--会计科目Id
	@Total00		 NUMERIC(24, 10) ,	--期初金额
	@stypeid		varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

IF @ATypeId IN ('0000100001','0000100002','0000100004','0000100005','0000100008','0000200001','0000200003')
	RETURN -1
ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AType_Total WHERE ATypeID = @ATypeId and STypeID=@stypeid)
			UPDATE	AType_Total
			SET		Total00 = @Total00
			WHERE	ATypeID = @ATypeId and STypeID=@stypeid
		ELSE
			INSERT INTO AType_Total(ATypeID,STypeID,Total,Total00)VALUES(@ATypeId,@stypeid,0,@Total00)

		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('修改期初信息失败！',16,1)
				RETURN -1
			END
		ELSE
			BEGIN
				--RAISERROR('修改期初信息成功！',16,1)
				RETURN 0
			END
	END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateB]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateB]
GO

/*最后修改版  作者：董湛   日期：2012-4-17  描述：添加字段及参数BackPercent BackLimitDay*/
/*最后修改版  作者：黄飞佳   日期：2012-3-28  描述：是否准许修改单据中价格，添加相关字段及参数*/
/*
	作者：廖晨羽
	日期：2011-08-17
	描述：修改@TelANDAddress参数的长度为256，添加etypeid字段，关联职员功能
*/


/*
	作者：吕文祺
	日期：2012-04-18
	描述：增加字段@denominatedid 为修改结算单位字段
*/




CREATE              PROCEDURE [Gp_UpdateB]
(
	@typeId  [varchar](50),
	@usercode       [varchar](200),
	@FullName  [varchar](200),
	@Name    [varchar](30),
	@Area  [Varchar](30),
	@TelANDAddress  [varchar](256),
	@PostCode  varchar(200),
	@Person  varchar(20),
	@TaxNumber  varchar(20),
	@bankANDacount    varchar(66),
	@ARTotal00   NUMERIC(24, 10) ,
	@APTotal00   NUMERIC(24, 10) ,
	@Comment  [varchar](256),
	@Client [Bit]=1,
	@ARLimit  NUMERIC(24, 10) ,
	@ARLimitTime  NUMERIC(24, 10)  = 99999,
	@PaymentLTime  NUMERIC(24, 10)  = 99999,
	@Tel1 varchar(50),
	@Tel2 varchar(50),
	@Tel3 varchar(50),
	@WWW varchar(50),
	@Email varchar(50),
	@Fax varchar(50),
	@Bank varchar(50),
	@BankName varchar(50),
	@LinkMan1 varchar(50),
	@LinkSex1 bit,
	@LinkBirthDay1 datetime,
	@LinkJob1 varchar(50),
	@LinkCall1 Varchar(50),
	@LinkTel1 varchar(50),
	@LinkMobile1 varchar(50),
	@LinkEMail1 varchar(50),
	@LinkPost1 varchar(50),
	@LinkAddress1 varchar(256),
	@LinkComment1 varchar(256),
	@LinkMan2 varchar(50),
	@LinkSex2 bit,
	@LinkBirthDay2 datetime,
	@LinkJob2 varchar(50),
	@LinkCall2 Varchar(50),
	@LinkTel2 varchar(50),
	@LinkMobile2 varchar(50),
	@LinkEMail2 varchar(50),
	@LinkPost2 varchar(50),
	@LinkAddress2 varchar(256),
	@LinkComment2 varchar(256),
	@CreateDate datetime,
	@SaleZeKou  NUMERIC(24, 10) ,
	@BuyZeKou  NUMERIC(24, 10) ,
	@PyCode   varchar(200),
	@Price    varchar(50),
	@AreaTypeID varchar(50),
	@IFStype int=0,
	@etypeid varchar(50),		--职员
	@buyprice VARCHAR(50),		--适用价格
	@consignee VARCHAR(100),	    --收货人
	@consigneetel VARCHAR(100),     --收货人电话
	@consigneeaddress VARCHAR(1000),   --收货人地址
	@valeditprice BIT, --是否准许修改单据中价格  添加人：黄飞佳   添加说明：添加对标记是否可以修改单价参数   添加日期：2012-3-27
    @denominatedid VARCHAR(100),
    @backlimitday	INT,				--退换货期限(天)
	@backpercent	INT,				--换货比例(%)
	@cid			INT,				--关联币种
	@pricetrackenable INT,				--1.启用价格跟踪 0.不启用
	@cqdays INT, --超期提前预警
	@chkskmonthday INT , --启用收款月结日 checkbox
	@skmonthday INT, --启用收款月结日  
	@chkfkmonthday INT, --启用付款月结日 checkbox
	@fkmonthday INT, --启用付款月结日  
	@dzdays INT, --每月对账日期  
	@dzwarningdays INT, --对账日提前预警天数  
	@ckarlimittime int=NULL, --收款期限
	@ckpaymentltime INT= NULL, --付款期限
	@fkcqdays        INT =NULL, --付款超期提前预警
	@fkdzdays  INT=NULL,--付款每月对账日期
	@fkdzwarningdays int=NULL,  --付款对账日提前预警
	@iscarrier BIT = 0,
	@sheng				VARCHAR(100) = '',		--省
	@shi				VARCHAR(100) = '',		--市
	@xian				VARCHAR(100) = '',		--县
	@blevel				VARCHAR(100) = '',		--单位等级
	@isusebrandartype	BIT=0,					--是否启用品牌应收
	@skmonth			VARCHAR(10) = NULL,		--收款第几月
	@skday				VARCHAR(10) = NULL,		--收款第几日 
	@skdzdayflag		VARCHAR(10) = '0',		--按对账日期计算收款期限
	@fkmonth			VARCHAR(10) = NULL,		--付款第几月
	@fkday				VARCHAR(10) = NULL,		--付款第几日
	@fkdzdayflag		VARCHAR(10) = '0',		--按对账日期计算付款期限
	@skcyjartime		VARCHAR(10) = '0',		--收款次月结
	@fkcyjaptime		VARCHAR(10) = '0'		--付款次月结
)
--@encode$--
AS 
SET NOCOUNT ON 
IF EXISTS(SELECT usercode FROM btype WHERE (usercode=@usercode )AND deleted<>1 AND typeid<>@typeid AND typeid<>'00000')
BEGIN
	RAISERROR('往来单位编号不能与已有的编号重复',16,1)--RETURN -3
	RETURN -3
END
IF EXISTS(SELECT usercode FROM btype WHERE (FullName=@usercode )AND deleted<>1 AND typeid<>@typeid AND typeid<>'00000')
BEGIN
	RAISERROR('往来单位编号不能与已有的名称重复',16,1)--RETURN -3
	RETURN -3
END
IF EXISTS(SELECT usercode FROM btype WHERE (usercode=@fullname)AND deleted<>1 AND typeid<>@typeid AND typeid<>'00000')
BEGIN
	RAISERROR('往来单位名称不能与已有的编号重复',16,1)--RETURN -3
	RETURN -10
END

-----判断供货商和客户名称不能相同
DECLARE @typename VARCHAR(50)
DECLARE @otypename VARCHAR(50)
IF LEFT(@typeid,5)='00001'
BEGIN
	SET @typename='客户'
	SET @otypename='供货商'
END
ELSE
BEGIN
	SET @typename='供货商'
	SET @otypename='客户'
END
IF EXISTS(SELECT TypeID FROM [btype] WHERE FullName=@FullName AND deleted<>1 AND LEFT(typeId,5)<>LEFT(@typeid,5) )
	BEGIN
		RAISERROR('%s的名称不能与已有%s的名称重复',16,1,@typeName,@otypename)RETURN--RETURN -3
	END

IF EXISTS(SELECT usercode FROM btype WHERE (usercode=@usercode )AND deleted=1 AND typeid<>@typeid AND typeid<>'00000')
BEGIN
	RAISERROR('该编号【%s】已被停用的往来单位使用！',16,1,@usercode)--RETURN -3
	RETURN -3
END
IF EXISTS(SELECT usercode FROM btype WHERE (FullName=@usercode )AND deleted=1 AND typeid<>@typeid AND typeid<>'00000')
BEGIN
	RAISERROR('该编号【%s】与往来单位名称重复！',16,1,@usercode)--RETURN -3
	RETURN -3
END
IF EXISTS(SELECT usercode FROM btype WHERE (usercode=@fullname)AND deleted=1 AND typeid<>@typeid AND typeid<>'00000')
BEGIN
	RAISERROR('往来单位名称不能与已停用的往来单位的编号重复',16,1)--RETURN -3
	RETURN -10
END
IF EXISTS(SELECT TypeID FROM [btype] WHERE FullName=@FullName AND deleted=1 AND LEFT(typeId,5)<>LEFT(@typeid,5) )
	BEGIN
		RAISERROR('%s的名称不能与已停用的%s名称重复',16,1,@typeName,@otypename)RETURN--RETURN -3
	END

DECLARE @RETURNPym varchar(1000)
EXEC @RETURNPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @RETURNPym=@PyCode

DECLARE @Ar00Temp  NUMERIC(24, 10) 
DECLARE @Ap00Temp  NUMERIC(24, 10) 
SET @Ar00Temp =0
SET @Ap00Temp =0

IF @Artotal00<>0 AND @Aptotal00<>0 AND (@ArTotal00 <> -9123456789.0000 AND @ApTotal00 <> -9123456789.0000)  -- 期初不应者都有
	RETURN 201

IF LEFT(@typeId,5) ='00001' -- 客户
BEGIN
	IF @Artotal00 >0 
	BEGIN
		SET @Ar00Temp = @Artotal00
		SET @Ap00Temp = 0
	END
	IF @Artotal00 <0 
	BEGIN
		SET @Ar00Temp = 0
		SET @Ap00Temp = abs(@Artotal00)
	END		
END 
ELSE  -- 供货商
BEGIN
	IF @Aptotal00 >0 
	BEGIN
		SET @Ar00Temp = 0
		SET @Ap00Temp = @Aptotal00
	END
	IF @Aptotal00 <0 
	BEGIN
		SET @Ar00Temp = abs(@Aptotal00)
		SET @Ap00Temp = 0
	END	
END

IF EXISTS (SELECT * FROM sysdata WHERE subName='inicanmodIFy' AND subValue='T')  AND @Artotal00<>-9123456789 AND @Aptotal00<>-9123456789  -- 未开帐
	UPDATE	[dbo].[btype] 
	SET     [usercode]  =@usercode,
			[FullName]  = @FullName,
			[Name]  = @Name,
			[Area]  =@Area, 
			[TelANDAddress]  = @TelANDAddress,
			[PostCode]  = @PostCode,
			[Person]  = @Person,
			[TaxNumber]  = @TaxNumber,
			[BankANDAcount] = @bankANDacount,
			[Comment]  = @Comment,
			[ARTotal00]  = dbo.F_RoundTotal(@Ar00Temp),
			[APTotal00]  = dbo.F_RoundTotal(@Ap00Temp),
			[Client]  = @Client,
			[ARLimitTime] = @ARLimitTime,
			[PaymentLTime]= @PaymentLTime,
			[Tel1]=@Tel1,
			[Tel2]=@Tel2,
			[Tel3]=@Tel3,
			[WWW]=@WWW,
			[Email]= @Email,
			[Fax]= @Fax,
			[Bank]= @Bank,
			[BankName]= @BankName,
			[LinkMan1]=@LinkMan1,
			[LinkSex1]=@LinkSex1,
			[LinkBirthDay1]=@LinkBirthDay1,
			[LinkJob1]=@LinkJob1,
			[LinkCall1]=@LinkCall1,
			[LinkTel1]=@LinkTel1,
			[LinkMobile1]=@LinkMobile1,
			[LinkEMail1]=@LinkEMail1,
			[LinkPost1]=@LinkPost1,
			[LinkAddress1]=@LinkAddress1,
			[LinkComment1]=@LinkComment1,
			[LinkMan2]=@LinkMan2,
			[LinkSex2]=@LinkSex2,
			[LinkBirthDay2]=@LinkBirthDay2,
			[LinkJob2]=@LinkJob2 ,
			[LinkCall2]=@LinkCall2,
			[LinkTel2]=@LinkTel2,
			[LinkMobile2]=@LinkMobile2,
			[LinkEMail2]=@LinkEMail2,
			[LinkPost2]=@LinkPost2,
			[LinkAddress2]=@LinkAddress2,
			[LinkComment2]=@LinkComment2,
			[CreateDate]=@CreateDate,
			[SaleZeKou] =dbo.F_RoundDiscount(@SaleZeKou),
			[BuyZeKou]=dbo.F_RoundDiscount(@BuyZeKou),
			[PyCode] =@RETURNPym,
			[Price] = @Price,
			[AreaTypeID] =@AreaTypeID,
			[etypeid] = @etypeid,
			[buyprice]=@buyprice,
			[consignee]=@consignee, 
			[consigneetel]=@consigneetel,
			[consigneeaddress]=@consigneeaddress,
			[cannotmodIFyprice] = @valeditprice,  --是否准许修改单据中价格  添加人：黄飞佳   添加说明：添加对标记是否可以修改单价字段修改   添加日期：2012-3-27
			[denominatedid]=@denominatedid,
			[backlimitday]=@backlimitday,
			[backpercent]=@backpercent,
			[Cid]=@cid,
			[PriceTrackEnable] =@pricetrackenable,
			cqdays=@cqdays,
			chkskmonthday=@chkskmonthday ,
			skmonthday=@skmonthday ,
			chkfkmonthday=@chkfkmonthday ,
			fkmonthday=@fkmonthday ,
			dzdays=@dzdays ,
			dzwarningdays=@dzwarningdays ,
			ckarlimittime =@ckarlimittime,
			ckpaymentltime =@ckpaymentltime,
			fkcqdays=@fkcqdays,
			fkdzdays =@fkdzdays,
			fkdzwarningdays =@fkdzwarningdays,
			iscarrier=@iscarrier,
			sheng = @sheng,
			shi = @shi,
			xian = @xian,
			[blevel] = @blevel,
			isusebrandartype=@isusebrandartype,
			skmonth = @skmonth,
			skday = @skday,
			skdzdayflag = @skdzdayflag,
			fkmonth = @fkmonth,
			fkday = @fkday,
			fkdzdayflag = @fkdzdayflag,
			skcyjartime = @skcyjartime,
			fkcyjaptime = @fkcyjaptime
	WHERE	( [typeId]  = @typeId)
ELSE                             -- 已开帐
	UPDATE	[dbo].[btype] 
	SET     [usercode]  =@usercode,
			[FullName]  = @FullName,
			[Name]  = @Name,
			[Area]  =@Area, 
			[TelANDAddress]  = @TelANDAddress,
			[PostCode]  = @PostCode,
			[Person]  = @Person,
			[TaxNumber]  = @TaxNumber,
			[BankANDAcount] = @bankANDacount,
			[Comment]  = @Comment,
			--  [ARTotal00]  = @ARTotal00,
			--  [APTotal00]  = @APTotal00,
			[Client]  = @Client,
			[ARLimitTime] = @ARLimitTime,
			[PaymentLTime]= @PaymentLTime,
			[Tel1]=@Tel1,
			[Tel2]=@Tel2,
			[Tel3]=@Tel3,
			[WWW]=@WWW,
			[Email]= @Email,
			[Fax]= @Fax,
			[Bank]= @Bank,
			[BankName]= @BankName,
			[LinkMan1]=@LinkMan1,
			[LinkSex1]=@LinkSex1,
			[LinkBirthDay1]=@LinkBirthDay1,
			[LinkJob1]=@LinkJob1,
			[LinkCall1]=@LinkCall1,
			[LinkTel1]=@LinkTel1,
			[LinkMobile1]=@LinkMobile1,
			[LinkEMail1]=@LinkEMail1,
			[LinkPost1]=@LinkPost1,
			[LinkAddress1]=@LinkAddress1,
			[LinkComment1]=@LinkComment1,
			[LinkMan2]=@LinkMan2,
			[LinkSex2]=@LinkSex2,
			[LinkBirthDay2]=@LinkBirthDay2,
			[LinkJob2]=@LinkJob2 ,
			[LinkCall2]=@LinkCall2,
			[LinkTel2]=@LinkTel2,
			[LinkMobile2]=@LinkMobile2,
			[LinkEMail2]=@LinkEMail2,
			[LinkPost2]=@LinkPost2,
			[LinkAddress2]=@LinkAddress2,
			[LinkComment2]=@LinkComment2,
			[CreateDate]=@CreateDate,
			[SaleZeKou] =dbo.F_RoundDiscount(@SaleZeKou),
			[BuyZeKou]=dbo.F_RoundDiscount(@BuyZeKou),
			[PyCode] =@RETURNPym,
			[Price] = @Price,
			[AreaTypeID] =@AreaTypeID,
			[etypeid] = @etypeid,
			[buyprice]=@buyprice,
			[consignee]=@consignee, 
			[consigneetel]=@consigneetel,
			[consigneeaddress]=@consigneeaddress,
			[cannotmodIFyprice] = @valeditprice,  --是否准许修改单据中价格  添加人：黄飞佳   添加说明：添加对标记是否可以修改单价字段修改   添加日期：2012-3-27
			[denominatedid]=@denominatedid,
			[backlimitday]=@backlimitday,
			[backpercent]=@backpercent,
			[Cid]=@cid,
			[PriceTrackEnable] =@pricetrackenable,
			cqdays=@cqdays,
			chkskmonthday=@chkskmonthday ,
			skmonthday=@skmonthday ,
			chkfkmonthday=@chkfkmonthday ,
			fkmonthday=@fkmonthday ,
			dzdays=@dzdays ,
			dzwarningdays=@dzwarningdays ,
			ckarlimittime =@ckarlimittime,
			ckpaymentltime =@ckpaymentltime,
			fkcqdays=@fkcqdays,
			fkdzdays =@fkdzdays,
			fkdzwarningdays =@fkdzwarningdays,
			iscarrier=@iscarrier,
			sheng = @sheng,
			shi = @shi,
			xian = @xian,
			[blevel] = @blevel,
			isusebrandartype=@isusebrandartype,
			skmonth = @skmonth,
			skday = @skday,
			skdzdayflag = @skdzdayflag,
			fkmonth = @fkmonth,
			fkday = @fkday,
			fkdzdayflag = @fkdzdayflag,
			skcyjartime = @skcyjartime,
			fkcyjaptime = @fkcyjaptime
	WHERE	( [typeId]  = @typeId)


--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM BType
UPDATE BType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateB_CORP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateB_CORP]
GO












/****** Object:  Stored Procedure dbo.Gp_UpdateB    Script Date: 2002-6-20 10:14:51 

******/



CREATE   PROCEDURE [Gp_UpdateB_CORP]
(
	@typeId			varchar(50),
	@usercode       varchar(26),
	@FullName		varchar(66),
	@Name			varchar(30),
	@Area			Varchar(30),
	@TelAndAddress  varchar(66),
	@Tel1			varchar(50),
	@PostCode		char(10),
	@Person			char(20),
	@TaxNumber		char(20),
	@Bank			varchar(50),
	@Account		char(66),
	@ARTotal00		 NUMERIC(24, 10) ,
	@APTotal00		 NUMERIC(24, 10) ,
	@Comment		varchar(256),
	@Client			Bit=1,
	@ARLimit		 NUMERIC(24, 10) =0,
	@bwbcode		VARCHAR(400) = '',	-- 本币代码
	@bwfullname		VARCHAR(400) = ''	-- 本币名称
)
--@encode$--
AS 
SET NOCOUNT ON 
IF EXISTS(select usercode from btype where (usercode=@usercode OR fullname=@fullname)and deleted<>1 and typeid<>@typeid and typeid<>'00000')
BEGIN
	--PRINT '商品已存在'+@etypeid_1
	RETURN -3
END

UPDATE	[dbo].[btype] 
SET     [usercode]  =@usercode,
		[FullName]  = @FullName,
		[Name]  = @Name,
		[Area]  =@Area, 
		[TelAndAddress]  = @TelAndAddress,
		[Tel1]=@Tel1,
		[PostCode]  = @PostCode,
		[Person]  = @Person,
		[TaxNumber]  = @TaxNumber,
		[Bank]=@Bank,
		[BankAndAcount] = @Account,
		[Comment]  = @Comment,		
		[Client]  = @Client,
		[ARLimit]  = dbo.F_RoundTotal(@ARLimit)
WHERE	typeId  = @typeId


--先将以前的默认本币修改成外币
UPDATE Ac_Currency SET Sysrow = 0 WHERE Sysrow = 1
	
--修改本位币
IF EXISTS(SELECT TOP 1 * FROM Ac_Currency WHERE UserCode = @bwbcode)
BEGIN
	UPDATE	Ac_Currency 
	SET		FullName = @bwfullname,
			Sysrow = 1 
	WHERE	UserCode = @bwbcode
END	
ELSE
BEGIN
	INSERT INTO Ac_Currency
	(
		UserCode,
		FullName,
		Rate,
		BasisType,
		PyCode,
		Deleted,
		Sysrow
	)VALUES(
		@bwbcode,
		@bwfullname,
		1,
		0,
		DBO.fun_getPY(@bwfullname),
		0,
		1
	)
END	






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateBackQTY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateBackQTY]
GO



/*
功能说明：		'haiquan 草稿批量过帐调原单按单结算处理2008-1-22
最后修改时间：	2008-1-22

修改:冯波  2015-05-20
*/
CREATE            PROCEDURE Gp_UpdateBackQTY
(
	@BillNumberID	numeric(10,0)	-- 单据 ID 值
)
--@encode$--
AS
	DECLARE @BillType int
	DECLARE @Nnum int

	SELECT @BillType=Isnull(Billtype,-1) FROM BillIndex WHERE BillNumberID=@BillNumberID --获得单据类型

	if(@BillType=-1)
	  RETURN 1  --单据或者单据类型不存在

	IF(@BillType=142 OR @BillType=146 OR @BillType=141 OR @BillType=145)
	  CREATE TABLE #CommissionBill
	  (
		BillNumberID NUMERIC(10,0),
		OldBillNumberID NUMERIC(10,0),
		Type INT,
		QTY  NUMERIC(24, 10) ,
		OldID VARCHAR(50),
		[ID] VARCHAR(10),
		BackQTY NUMERIC(24,10),
		BQTY NUMERIC(24,10),
		OldBillID VARCHAR(10)
	  )

	IF(@BillType=142 OR @BillType=146)
	  BEGIN
		INSERT  INTO #CommissionBill  
				SELECT BillNumberID,OldBillNumberID,Type,QTY,OldID,ID,BackQTY,BQTY,OldBillID  
				FROM CommissionBill 
				WHERE Type in (142,146)

		UPDATE  CommissionBill 
		SET     BQty=dbo.F_RoundQty(isnull(A.BQty,0)+isnull(B.QTY,0)) 
		FROM    CommissionBill A,#CommissionBill B 
		WHERE   A.BillNumberID= B.OldBillID
			AND A.[ID]=B.OldID 
			AND (isnull(A.Qty,0)-isnull(A.Bqty,0)-isnull(A.Backqty,0))>=isnull(B.Qty,0) 
			AND B.BillNumberID=@BillNumberID
	  END

	IF(@BillType=141 OR @BillType=145)
	  BEGIN
		INSERT  INTO #CommissionBill 
				SELECT BillNumberID,OldBillNumberID,Type,QTY,OldID,ID,BackQTY,BQTY,OldBillID 
				FROM CommissionBill 
				WHERE Type in (141,145)
		UPDATE  CommissionBill 
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    CommissionBill A,#CommissionBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID
			AND A.[ID]=B.OldID 
			AND (isnull(A.Qty,0)-isnull(A.Backqty,0)-isnull(A.Bqty,0))>=isnull(B.Qty,0) 
			AND B.BillNumberID=@BillNumberID
	  END

	IF(@BillType=6) 	--采购退货单
	  BEGIN		
		UPDATE BuyBill 
		SET    BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM   BuyBill A,BuyBackBill B 
		WHERE  A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID

		SELECT @Nnum=COUNT(A.ID) 
		FROM BuyBill A,BuyBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID

		IF(@Nnum>0)
		  RETURN 2

	  END
	  
	 IF(@BillType=161) 	--采购换货单
	  BEGIN		
		UPDATE BuyBill 
		SET    BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0))
		FROM   BuyBill A,BuyGoodsExchangeBill B 
		WHERE  A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID
			AND B.InOrOut='o'

		SELECT @Nnum=COUNT(A.ID) 
		FROM BuyBill A,BuyGoodsExchangeBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID
		        AND B.InOrOut='o'

		IF(@Nnum>0)
		  RETURN 2

	  END
	  
	  
	IF(@BillType=401) 	--暂估退货单
	  BEGIN
		
		
		
		UPDATE AppraisalBill 
		SET    BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM   AppraisalBill A,AppraisalBackBill B 
		WHERE  A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID

		SELECT @Nnum=COUNT(A.ID) 
		FROM AppraisalBill A,AppraisalBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID

		IF(@Nnum>0)
		  RETURN 2

	  END
	
	
	IF(@BillType=45)   --销售退货单
	  BEGIN
		
	
		UPDATE  SaleBill --对销售出库单处理
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    SaleBill A,SaleBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID

		SELECT @Nnum=COUNT(A.ID) 
		FROM SaleBill A,SaleBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID

		IF(@Nnum>0)
		  RETURN 2
		

		UPDATE  RetailBill --对零售单处理
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    RetailBill A,SaleBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID

		SELECT @Nnum=COUNT(A.ID) 
		FROM RetailBill A,SaleBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID

		IF(@Nnum>0)
		  RETURN 2
	  END
	  
	 IF(@BillType=160)   --销售换货单
	  BEGIN
		
	
		UPDATE  SaleBill --对销售出库单处理
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    SaleBill A,SaleGoodsExchangeBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID
			AND B.InOrOut='i'

		SELECT @Nnum=COUNT(A.ID) 
		FROM SaleBill A,SaleGoodsExchangeBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID
		        AND B.InOrOut='i'

		IF(@Nnum>0)
		  RETURN 2
		

		UPDATE  RetailBill --对零售单处理
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    RetailBill A,SaleGoodsExchangeBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID
			AND B.InOrOut='i'

		SELECT @Nnum=COUNT(A.ID) 
		FROM RetailBill A,SaleGoodsExchangeBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID
		        AND B.InOrOut='i'

		IF(@Nnum>0)
		  RETURN 2
	  END
	  
	  
	 IF(@BillType=403)   --发出商品退货单
	  BEGIN
	
		UPDATE  SendBill --对发出商品出库单处理
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    SendBill A,SendBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID

		SELECT @Nnum=COUNT(A.ID) 
		FROM SendBill A,SendBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID

		IF(@Nnum>0)
		  RETURN 2
		

		
	  END
	  
	 IF(@BillType=215)   --零售退货单
	  BEGIN
		

		UPDATE  RetailBill --对零售单处理
		SET     BackQty=dbo.F_RoundQty(isnull(A.BackQty,0)+isnull(B.QTY,0)) 
		FROM    RetailBill A,RetailBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
			AND A.[ID]=B.OldID 
			AND B.Billnumberid=@BillNumberID

		SELECT @Nnum=COUNT(A.ID) 
		FROM RetailBill A,RetailBackBill B 
		WHERE   A.BillNumberID=B.OldBillNumberID 
		        AND A.[ID]=B.OldID 
			AND isnull(A.Backqty,0) > isnull(A.Qty,0) 
		        AND B.Billnumberid=@BillNumberID

		IF(@Nnum>0)
		  RETURN 2
	  END

	IF(@BillType=142 OR @BillType=146 OR @BillType=141 OR @BillType=145)
	  DROP TABLE #CommissionBill
	
	RETURN 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_UpdateBaseSyncInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Gp_UpdateBaseSyncInfo]
GO

/*
	作者：谢吉康
	日期：2018-10-15
	描述：修改同步信息
*/
CREATE PROCEDURE Gp_UpdateBaseSyncInfo
(
	@typeid			VARCHAR(50),			--基本信息ID
	@usercode		VARCHAR(500),			--编号
	@flag			VARCHAR(10),			--修改标识
	@wmsid			VARCHAR(100),			--WMS标识
	@wmsfullname	VARCHAR(500),			--WMS名称
	@wmsusercode	VARCHAR(500),			--WMS编号
	@skuid			VARCHAR(100) = '',		--商品SKUID
	@tablename		VARCHAR(100)			--基本信息类型
)
AS
SET NOCOUNT ON

IF @tablename = 'ptype'
BEGIN
	SELECT @wmsusercode = usercode,@wmsfullname = fullname FROM ptype WHERE typeid = @typeid
	
	IF EXISTS(SELECT TOP 1 1 FROM WmsErpPtypeContrastSetting WHERE ERP_TypeId = @typeid)
	BEGIN
		UPDATE	dbo.WmsErpPtypeContrastSetting
		SET		WMS_UserCode = @wmsusercode,
				WMS_FullName = @wmsfullname,				
				nType = 1
		WHERE	ERP_TypeId = @typeid
	END	
END
ELSE IF @tablename = 'btype'
BEGIN	
	SELECT @wmsusercode = usercode,@wmsfullname = fullname FROM btype WHERE typeid = @typeid
	
	IF EXISTS(SELECT TOP 1 1 FROM WmsErpBTypeContrastSetting WHERE ERP_TypeId = @typeid)
	BEGIN
		UPDATE	dbo.WmsErpBTypeContrastSetting
		SET		WMS_UserCode = @wmsusercode,
				WMS_FullName = @wmsfullname
		WHERE	ERP_TypeId = @typeid
	END	
END
ELSE IF @tablename = 'employee'
BEGIN	
	SELECT @wmsusercode = usercode,@wmsfullname = fullname FROM employee WHERE typeid = @typeid
	
	IF EXISTS(SELECT TOP 1 1 FROM WmsErpEmployeeContrastSetting WHERE ERP_TypeId = @typeid)
	BEGIN
		UPDATE	dbo.WmsErpEmployeeContrastSetting
		SET		WMS_UserCode = @wmsusercode,
				WMS_FullName = @wmsfullname
		WHERE	ERP_TypeId = @typeid
	END	
END
ELSE IF @tablename = 'stock'
BEGIN	
	SELECT @wmsusercode = usercode,@wmsfullname = fullname FROM stock WHERE typeid = @typeid
	
	IF EXISTS(SELECT TOP 1 1 FROM WmsErpStockContrastSetting WHERE ERP_TypeId = @typeid)
	BEGIN
		UPDATE	dbo.WmsErpStockContrastSetting
		SET		WMS_UserCode = @wmsusercode,
				WMS_FullName = @wmsfullname
		WHERE	ERP_TypeId = @typeid
	END	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateBillAtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_UpdateBillAtype]

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

--作    者：胡小科 
--日    期：2012-05-29  
--作    用：插入单据往来科目 


CREATE     PROCEDURE [dbo].[Gp_UpdateBillAtype]
(
	@billtypeid			[varchar](50),
	@atypeid			[varchar](50),
	@stypeid			[varchar](50)
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN TRY
 
	IF EXISTS(SELECT [BillTypeId] FROM [BillAtype] WHERE [BillTypeId]=@billtypeid AND [StypeId]=@stypeid)
		BEGIN
			UPDATE [BillAtype] SET [AtypeId]=@atypeid WHERE [BillTypeId]=@billtypeid AND [StypeId]=@stypeid
		END
	ELSE
		BEGIN
			INSERT INTO [BillAtype]([BillTypeId] ,[AtypeId] ,[StypeId])VALUES (@billtypeid,@atypeid,@stypeid)
		END
	RETURN 1
END TRY
BEGIN CATCH

	RETURN 0

END CATCH

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateBillCargoByConfig]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateBillCargoByConfig]
GO          

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 时间：	2017-09-11
-- 作者：	glj
-- 功能：	{系统配置}-{启用货位}当把启用货位的选项取消后，发现订单库存的货位信息没有变，这是需要重新计算订单库存
-- ========================================================================
CREATE PROC Gp_UpdateBillCargoByConfig

AS
SET NOCOUNT ON

--【启用货位管理】ischecked 则不进行单据修改
IF EXISTS(SELECT * FROM SysData WHERE SubName='mngcargospace' AND SubValue=1)
	RETURN 

DECLARE 
	@iniRowId	INT=1,
	@endRowId	INT=0,
	@SQL		VARCHAR(MAX)='',
	@TableName	VARCHAR(100)
	
--单据明细中有生产日期/效期至的表
CREATE TABLE #UpdateTable(NId INT IDENTITY(1,1),TableName VARCHAR(100)) 
INSERT INTO #UpdateTable(TableName)
SELECT name 
FROM sysobjects O
WHERE 
	EXISTS(SELECT TOP 1 1 FROM syscolumns c WHERE c.name = 'CargoID' AND c.id=o.id ) 
	AND o.xtype = 'u' 
	AND EXISTS(SELECT TOP 1 1 FROM BillName b WHERE b.detailTable=o.name)
	AND name NOT IN('StockCheck','FaPiaoBill','ReceiptBill','Coupon_BackBill','Coupon_InBill','Coupon_OutBill','Coupon_AllotBill')

SELECT @endRowId=@@ROWCOUNT

WHILE(@iniRowId<=@endRowId)
	BEGIN
		SELECT @TableName=TableName FROM #UpdateTable WHERE NId=@iniRowId
		SET @SQL+='UPDATE '+@TableName+' SET cargoID=C.CargoID From '+@TableName+' B INNER JOIN '+(SELECT TOP 1 IndexTable FROM BillName WHERE detailTable=@TableName)+' I ON I.billNumberId=B.billNumberID
INNER JOIN CargoType C ON C.KtypeID=I.ktypeid AND B.cargoID<>C.cargoID AND C.IsDefault=1'+CHAR(13)

		SET @iniRowId=@iniRowId+1
	END
	--PRINT @SQL
EXEC(@SQL)
	
--库存盘点明细
UPDATE StockCheck SET cargoID=C.CargoID 
From StockCheck B 
INNER JOIN StockCheckIndex I ON I.StockCheckID=B.StockCheckID 
INNER JOIN CargoType C ON C.KtypeID=I.ktypeid AND B.cargoID<>C.cargoID AND C.IsDefault=1

--发票明细表
UPDATE FaPiaoBill SET cargoID=C.CargoID 
From FaPiaoBill B 
INNER JOIN CargoType C ON C.KtypeID=B.ktypeid AND B.cargoID<>C.cargoID AND C.IsDefault=1

--暂估发票明细
UPDATE ReceiptBill SET cargoID=C.CargoID 
From ReceiptBill B 
INNER JOIN CargoType C ON C.KtypeID=B.ktypeid AND B.cargoID<>C.cargoID AND C.IsDefault=1

--期初库存状况数量核算表
UPDATE Ini_GOODSSTOCKS_QTY SET cargoID=C.CargoID 
From Ini_GOODSSTOCKS_QTY B 
INNER JOIN CargoType C ON C.KtypeID=B.ktypeid AND B.cargoID<>C.cargoID AND C.IsDefault=1

--优惠券入库
UPDATE Coupon_InBill SET cargoID=C.CargoID From Coupon_InBill B INNER JOIN Coupon_BillIndex I ON I.billNumberId=B.billNumberID
INNER JOIN CargoType C ON C.KtypeID=I.InKTypeId AND B.cargoID<>C.cargoID AND C.IsDefault=1
--优惠券出库
UPDATE Coupon_OutBill SET cargoID=C.CargoID From Coupon_OutBill B INNER JOIN Coupon_BillIndex I ON I.billNumberId=B.billNumberID
INNER JOIN CargoType C ON C.KtypeID=I.OutKTypeId AND B.cargoID<>C.cargoID AND C.IsDefault=1
--优惠券退货
UPDATE Coupon_BackBill SET cargoID=C.CargoID From Coupon_BackBill B INNER JOIN Coupon_BillIndex I ON I.billNumberId=B.billNumberID
INNER JOIN CargoType C ON C.KtypeID=I.InKTypeId AND B.cargoID<>C.cargoID AND C.IsDefault=1
--优惠券调拨
UPDATE Coupon_AllotBill SET InCargoId=C.CargoID From Coupon_AllotBill B INNER JOIN Coupon_BillIndex I ON I.billNumberId=B.billNumberID
INNER JOIN CargoType C ON C.KtypeID=I.InKTypeId AND B.InCargoId<>C.cargoID AND C.IsDefault=1
UPDATE Coupon_AllotBill SET OutCargoId=C.CargoID From Coupon_AllotBill B INNER JOIN Coupon_BillIndex I ON I.billNumberId=B.billNumberID
INNER JOIN CargoType C ON C.KtypeID=I.OutKTypeId AND B.OutCargoId<>C.cargoID AND C.IsDefault=1

--重算期初库存状况数量核算表
EXEC QP_Recount_IniGoodsStocksQty

--重算草稿库存的
EXEC QP_Recount_DraftQty

--BUG2160 切换成本需要重新调用订单库存重算
EXEC QP_Recount_OrderQty

--删除临时表
DROP TABLE #UpdateTable


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateBillIndex]
GO

--**********************************************
--存储过程修改记录
--1.修改原因:a.增加过帐时根据配置判断是否允许过帐日期与当前日期不一致的问题   b.增加ID字段,用于物理顺序
--2.修改方法:增加
--3.结果:成功
--4.修改人:肖伟
--5.LAST修改时间:2002-10-22
--修改:    梁晰 日期:   2017-03-30  判断本次支付是微信支付宝支付时  不删除原多账户金额
--**********************************************
CREATE                                         PROCEDURE [Gp_UpdateBillIndex]
(
	@BillNumberId  		[numeric](10,0),
	@BillDate  			[datetime],
	@BillCode  			[varchar](200),
	@BillType  			[numeric](4,0),
	@AtypeId  			[varchar](50),
	@PtypeId  			[varchar](50),
	@BtypeId 			[varchar](50),
	@EtypeId  			[varchar](50),
	@KtypeId  			[varchar](50),
	@KtypeId2  			[varchar](50),
	@IfCheck  			[char](1),
	@CheckE  			[varchar](50),
	@TotalMoney  		 NUMERIC(24, 10) ,
	@TotalInMoney  		 NUMERIC(24, 10) ,
	@TotalQty  			 NUMERIC(24, 10) ,
	@tax   				 NUMERIC(24, 10) ,
	@Period  			[SMALLINT],
	@Explain  			[varchar](2000),
	@RedWord  			[bit],
	@Draft   			[bit],
	@OrderId 			[numeric](10,0),
	@Comment  			[varchar](2000),
	--添加新的参数
	@WayBillCode 		varchar(50)=NULL,
	@Goodsnumber 		varchar(20)=NULL,
	@PackWay 			varchar(20)=NULL,
	@Tel 				varchar(100)=NULL,     --100字符 【司华山 2015-04-03】
	@preferencemoney  	 NUMERIC(24, 10) =0,			--优惠金额【谢吉康 2004-07-16】,
	@AlertDay 			int=9999,					--收款期限
	@Assessor 			varchar(50)=NULL,
	@IfAudit 			char(1)='3',
	@Audit_explain 		varchar(256)=NULL,
	@DtypeId 			varchar(50),				--分支机构ID
	@VipCardID			int = -1,					--VIP卡的唯一ID值
	@KTypeID3			varchar(50) = '',	-- 表头第三个仓库，目前用于新维修的自行维修单
	@LinkMan			varchar(256) = '',	-- 新维修(接件单) - 联系人
	@LinkTel			varchar(256) = '',	-- 新维修(接件单) - 联系电话
	@LinkAddr			varchar(256) = '',	-- 新维修(接件单) - 联系地址
	@wxManID			varchar(50) = '',	-- 新维修(维修单、上门维修单) - 维修人ID
	@JieJianBillNumberID varchar(200) = '',	-- 新维修 - 接件单的BillNumberID
	@JieJianID 			varchar(200) = '',	-- 新维修 - 接件单对应商品明细行的物理顺序ID
	@BaoXiuBillNumberID	varchar(200) = '',	-- 新维修 - 报修单的BillNumberID
	@BaoXiuID			varchar(200) = '',	-- 新维修 - 报修单对应商品明细行的物理顺序ID
	@BuyDate			varchar(50) = '',	-- 新维修(接件单) - 购买日期
	@Serial				varchar(200) = '',	-- 新维修 - 序列号
	@wxTotal			 NUMERIC(24, 10)  = 0,	-- 新维修(表尾) - 维修费用、换机费用
	@ErrDes				varchar(3000) = '',	-- 新维修 - 故障描述
	@ifHideJieJian		int = 0,			-- 新维修 - 是否隐藏接件详情，0：不隐藏；1：隐藏
	@ifWX				int = 0,			-- 是否针对维修库存进行盘点、报损、报溢；0：正常库，1：维修库
	--@RATypeID			varchar(50) = '',	--车辆信息ID
	--@OperationSort		varchar(200) = '',	--业务类别
	--@RepairMode			varchar(200) = '',	--维修方式
	--@Oil				varchar(200) = '',	--存油
	--@Mileage			varchar(200) = '',	--行驶里程
	--@EpibolyItem		varchar(200) = '',	--外加工项
	--@OtherItem			varchar(200) = '',	--其他项目
	--@Status				int	= 0,			--维修状态
	--@ManHourTotal		 NUMERIC(24, 10)  = 0,	--工时费
	--@ManHourTax			 NUMERIC(24, 10)  = 0,	--工时费税率
	--@ManHourTaxTotal	 NUMERIC(24, 10)  = 0,	--工时费合计
	--@PTypeTotal			 NUMERIC(24, 10)  = 0,	--材料费
	--@PTypeTax			 NUMERIC(24, 10)  = 0,	--材料费税率
	--@PTypeTaxTotal		 NUMERIC(24, 10)  = 0,	--材料费合计
	--@EpibolyTotal		 NUMERIC(24, 10)  = 0,	--外加工费
	--@OtherTotal			 NUMERIC(24, 10)  = 0,	--其他费用
	--@InPriceType		varchar(50)='',		--收费标准
	@IfBargainOn		int=0,				--询价单、报价单成交标志 0：未成交  1：成交
	--@BTypeID1			varchar(50)='',
	--@QuickRepairBillID	int=0,
	--@ManHourInsuranceTotal	 NUMERIC(24, 10) =0,
	--@PTypeInsuranceTotal	 NUMERIC(24, 10) =0,
	--@InvoiceMode			int=0,
	--@InvoiceCode			varchar(200)='',
	--@InsuranceStatus		int=0,
	@STypeID			varchar(50)='',
	@FromBillNumberID	numeric(10,0)=0,
	@CostSale			bit=0,
	--@repairtype			int,				--维修类型
	--@bespokedate		datetime,			--预约时间
	--@receptiondate		datetime,			--接待时间
	@completedate		datetime,			--预计完成
	--@infactorydate		datetime,			--进场时间
	--@factcompletedate	datetime,			--实际完工时间
	--@receptionid		varchar(50)='',		--接车人
	--@unitsatrap			varchar(50)='',		--单位主管
	--@sendperson			varchar(50)='',		--送车人
	--@ErrDescription		varchar(2000)='',	--故障描述
	--@epibolycosttotal	 NUMERIC(24, 10)  = 0,	--外加工成本
	--@preferencereason	varchar(250)='',	--优惠原因
	--@balancedate		datetime,			--结算时间
	--@itemprincipal		varchar(50)='',		--项目负责人
	--@monitorprincipal	varchar(50)='',		--监理负责人
	@billstate			int,				--单据状态
	--@intendingkickback	varchar(20)='',		--预计回扣
	--@settlementkickback varchar(20)='',		--已计算回扣
	--@BackTypeId			int,				--返修类型
	--@intendingtalkbackdate datetime,		--预计回访日期
	--@istalkbackover		INT,				--回访完成标志
	@ifmulaccount		INT,				--是否多账户收款
	@otherinouttype		int,					--其他出入库单业务类别
	@czbeforetimes		 NUMERIC(24, 10) ,		  --会员卡充值前次数
	@PosBillType		int,
	@updateE			VARCHAR(50),			--修改人
	@ShareMode			TINYINT,
	@TransportId		int,
	@IsFreightMoney		int,
	@FreightAddr		varchar(300),
	@FreightPerson		varchar(100),
	@FreightTel			varchar(100),
	--@wctypeid			varchar(50)='',		--维修车型
	@ModifyAuditBill	INT,					--是否为修改过账后单据 
	@uf1				VARCHAR(200)='',		--自定义表头字段
	@uf2				VARCHAR(200)='',
	@uf3				VARCHAR(200)='',
	@uf4				VARCHAR(200)='',
	@uf5				VARCHAR(200)='',
	--9.0新字段
	@DEALBTYPEID		VARCHAR(50),		--结算单位
	@cid				INT,				--外币币种ID
	@rate			 NUMERIC(24, 10) ,		--汇率
	@ntotalmoney		MONEY,				--原币总金额
	@ntotalinmoney		MONEY,				--原币收现金额
	@npreferencemoney	MONEY,				--原币优惠金额
	@nvipczmoney		MONEY,				--原币会员卡充值金额
	@ATYPEID1			VARCHAR(50),
	@billproperty		INT,					--单据属性	
	@ncompletetotal	 NUMERIC(24, 10) ,		--原币结算金额		
	@isini	BIT,
	@ATID INT,
	@completetotal	 NUMERIC(24, 10) ,
	@IfCargo		BIT,
	@IfInvoice		INT,
	@invoicemoney  NUMERIC(24, 10)  = 0,
    @ninvoicemoney  NUMERIC(24, 10)  = 0,
    
	@AssetBusinessTypeId int=0,
	@promoruleid	int,
	@beforepromobillnumberid int,
	@promotionmsg nvarchar(500)='',
	@STypeID2 VARCHAR(50)='',	
	@ifconfirm int=0,
	@FeeDeductType int=0,
	@TransferType int =1,
	@DeliveryAddress VARCHAR(256),
	@Discount  NUMERIC(24, 10) =1,
	@AdpriceType INT=0,
	@checkSave varchar(128)='',
	@chargeofftotal NUMERIC(24, 10),
	@nchargeofftotal NUMERIC(24, 10),	
	@ChargeOffType int=0,
	@ChargeOffBtypeid varchar(50),
	@IsLend		BIT=0,
	@WarehouseOutDay INT = 9999,--出库期限 
	@StockInDeadline INT = 9999,--入库期限 
	@IsNeedTransport BIT=0,--是否需要运输配送
	@iscombinationstyle INT = 0,
	@transporterid VARCHAR(50)='0',
	@transporterfullname varchar(200)	='',
	@shipperfullname varchar(100)	='',
	@shipperperson varchar(100)='',
	@shippertel varchar(100)='',
	@transportno VARCHAR(200)='',
	@totalfreight NUMERIC(24,10)=0,
	@ntotalfreight NUMERIC(24,10)=0,
	@paytag int = 0,
	@PromonIds VARCHAR(1000),
	@isByBrandarType int,
	@NewPosBill INT, --pos上传单据标志
    @PayOnTheSpot	INT --当面付
)
--@encode$--
AS 
SET NOCOUNT ON 

	--********判断是否被完全破解**********
	--IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'PassVchCheck' AND SubValue = CONVERT(varchar(100), GETDATE(), 112))
		--RETURN -99

DECLARE @ID		INT,
		@ReCv	INT
		
SET @ID=0
IF @ModifyAuditBill<>1 AND @isini<>1
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM billindex WHERE  draft=0 AND ifcheck='t' AND [BillNumberId]  = @BillNumberId
			  UNION ALL
			  SELECT TOP 1 1 FROM dbo.ListTable WHERE BillNumberId=@BillNumberId AND BillType=@BillType
			  UNION ALL
			  SELECT TOP 1 1 FROM dbo.InOutstocktable WHERE BillNumberId=@BillNumberId AND BillType=@BillType)

		RETURN -1 
END
ELSE
BEGIN
	SELECT TOP 1 @ID=ID FROM billindex WHERE [BillNumberId]  = @BillNumberId
END

IF NOT EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberID = @BillNumberID AND BillType = @BillType)
	RETURN -7

-- 谢吉康 2019-09-26 屏蔽
--EXEC @ReCv = Gp_ChkSdAllType
--IF (@ReCv = 0) RETURN -7

DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
--EXEC Gp_GetSubValue 'period',@STypeID,@Period out
SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE STypeID=@STypeID AND MonthNo='本期'


DECLARE
	@intNeed TINYINT

IF @BillType=195 AND @billstate=3
BEGIN
	SELECT @intNeed=1
END
ELSE
BEGIN
	SELECT @intNeed=0
END
/*
DECLARE @ProInfoname VARCHAR(6)
SELECT @ProInfoname = CASE SubValue WHEN  '1' THEN 'V3' WHEN '2' THEN 'A8' WHEN '4' THEN 'V1' ELSE '' END FROM dbo.sysdata WHERE SubName = 'ProInfo'
IF EXISTS(SELECT TOP 1 1 FROM  sysdatadb..rwxsysadmin WHERE [Version] = @ProInfoname AND rgday <> 99999)
BEGIN	
	--验证数据是否已经被控制
	--此处不做数据清理，放在C++中进行数据清理
	DECLARE @isControl varchar(10)
	SET @isControl=''
	SELECT @isControl=subvalue FROM SYSDATA WHERE subname='ControlFlag'
	IF @isControl = 'ssct'
	BEGIN
		RETURN -100
	END
	--验证数据是否允许执行保存   
	IF @checkSave='check_account_num_err'
	BEGIN
		RETURN -102
	END
	IF @checkSave<>'bill_allow_save' AND @BillType IN (4,11)
	BEGIN
		RETURN -101
	END
	ELSE
	BEGIN
		--bill_unsave
		UPDATE sysdata1 SET subvalue=N'`ljk_vlvgqe' WHERE subname='BillSaveCheck'
	END
END 
*/
IF @BillType NOT IN (184,185) AND @intNeed=0
BEGIN
	IF @isini=1
	BEGIN
		DECLARE @iniBegindate DATETIME  --取会计期间开始时间
		--SELECT @iniBegindate=FBegin FROM sysdata s INNER JOIN Ac_Period a ON s.SubValue=a.FPeriod  WHERE SubName = 'fmonth'
        SELECT @iniBegindate=fBegin FROM dbo.Ac_Period 
        WHERE FYear IN (SELECT subvalue FROM dbo.sysdata WHERE subname ='fyear' )
			AND FPeriod IN (SELECT subvalue FROM dbo.sysdata WHERE SubName='fmonth')
		IF @billdate > @iniBegindate
		RETURN -8
	END
	IF @BillDate<@BeginDate AND @isini=0 AND @BillType<>310
	BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1) 
		RETURN -2
	END
	
	---根据配置检查过帐日期是否当前日期  开始 如果单据没有审核流程才判断,如果有审核流程,则在审核流程中判断 谢吉康 2004-06-14
	IF(@isini=0)
		BEGIN		
		IF @ModifyAuditBill<>1
		BEGIN
			DECLARE @CurDate datetime,@chvIfAudit varchar(10)
			DECLARE @IsOrNotPassOneDay bit
			IF NOT EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType=@BillType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)	--检查单据是否有审核流程
			BEGIN
				SELECT @CurDate=GETDATE()
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
				BEGIN 
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -3
				END
			END
			ELSE
			BEGIN
				SET @chvIfAudit = ''
				SET @CurDate=@billdate
				SELECT @chvIfAudit=ISNULL(IfAudit,'') FROM AuditingBill Where BillNumberId = @BillNumberId AND BillIndexType<>0
				IF @chvIfAudit = '' OR @chvIfAudit = '-1'
				BEGIN
					SELECT @CurDate=GETDATE()
				END
				SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
				IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
				BEGIN
			
					--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
					RETURN -3
				END
			
			END
		END
	END
END
---根据配置检查过帐日期是否当前日期  完毕

--对于审核未通过的，或更改了分支机构的之前提交过审核的单据，都把审核历程删掉
IF EXISTS(
	SELECT BillNumberID
	FROM AuditingBill
	WHERE BillNumberID=@BillNumberId AND IfAudit=-1
)
BEGIN
	DELETE AuditingBillDetail WHERE BillNumberID =@BillNumberId AND BillIndexType<>0
	DELETE AuditingBill
	WHERE BillNumberID=@BillNumberId AND BillIndexType<>0
END

IF @BillType=195
BEGIN
	IF EXISTS(
		SELECT BillNumberID
		FROM Billindex_CarRepair
		WHERE BillNumberId=@BillNumberId AND BillState=2
	)
	BEGIN
		RETURN -10
	END
END

IF(@isini=1)  --期初单据计算completetotal
BEGIN
	DECLARE @currate  NUMERIC(24, 10) ,
			@curbasistype INT,
			@curCompleteTotal  NUMERIC(24, 10) ,
            @curChargeOffTotal NUMERIC(24, 10) 
	SELECT @currate = rate,@curbasistype = basistype FROM Ac_Currency WHERE CId=@cid
	IF(@curbasistype = 1)
	BEGIN
          SET @curCompleteTotal = @ncompletetotal / @currate
          SET @curChargeOffTotal= @nchargeofftotal/ @currate
    END
	ELSE
    BEGIN
          SET @curCompleteTotal = @ncompletetotal * @currate
          SET @curChargeOffTotal= @nchargeofftotal* @currate
    END	
END

UPDATE [dbo].[BillIndex] 
SET     [BillDate]  = @BillDate,
		[BillCode]  = @BillCode,
		[BillType]  = @BillType,
		[Comment]  = @Comment,
		[atypeid]  = @atypeid,
		[ptypeid]  = @ptypeid,
		[btypeid]  = @btypeid,
		[etypeid]  = @etypeid,
		[ktypeid]  = @ktypeid,
		[ktypeid2]  = @ktypeid2,
		[ifcheck]  = @ifcheck,
		[checke]  = @checke,
		[totalmoney]  = dbo.F_RoundTotal(@totalmoney),
		[totalinmoney]  = dbo.F_RoundTotal(@totalinmoney),
		[totalqty]  = dbo.F_RoundQty(@totalqty),
		[tax]    = dbo.F_RoundTax(@tax),
		[period]  = @period,
		[explain]  = @explain,
		[RedWord]  = @RedWord,
		[draft]  = @draft ,
		[orderid]       = @orderid,
		[waybillcode] = @waybillcode,
		[goodsnumber] = @goodsnumber,
		[packway] = @packway,
		[tel] = @tel,
		[preferencemoney]= dbo.F_RoundTotal(@preferencemoney),
		[AlertDay] = @AlertDay,
		[ID]=@ID,
		[Assessor]=@Assessor,
		[IfAudit]=@IfAudit,
		[Audit_explain]=@Audit_explain,
		[DtypeId]=@DtypeId,
		[VipCardID]=@VipCardID,
		[KTypeID3] = @KTypeID3,
		[LinkMan] = @LinkMan,
		[LinkTel] = @LinkTel,
		[LinkAddr] = @LinkAddr,
		[wxManID] = @wxManID,
		[JieJianBillNumberID] = @JieJianBillNumberID,
		[JieJianID] = @JieJianID,
		[BaoXiuBillNumberID] = @BaoXiuBillNumberID,
		[BaoXiuID] = @BaoXiuID,
		[BuyDate] = @BuyDate,
		[Serial] = @Serial,
		[wxTotal] = @wxTotal,
		[ErrDes] = @ErrDes,
		[ifHideJieJian] = @ifHideJieJian,
		[ifWX] = @ifWX,
		[IfBargainOn]=@IfBargainOn,
		[LastUpdateTime]=GETDATE(),
		[updateE]=@updateE,
		[StypeId]=@StypeId,
		[FromBillNumberID]=@FromBillNumberID,
		[CostSale]=@CostSale,
		[ifmulaccount]=@ifmulaccount,
		otherinouttype=@otherinouttype,
		PosBillType=@PosBillType,
		sharemode=@ShareMode,
		TransportId=@TransportId,
		IsFreightMoney=@IsFreightMoney,
		FreightAddr=@FreightAddr,
		FreightPerson=@FreightPerson,
		FreightTel=@FreightTel,
		uf1=@uf1,
		uf2=@uf2,
		uf3=@uf3,
		uf4=@uf4,
		uf5=@uf5,
		DEALBTYPEID = @DEALBTYPEID,	
		cid = @cid,
		rate = dbo.F_RoundExchangeRate(@rate),
		ntotalmoney = dbo.F_RoundTotal(@ntotalmoney),
		ntotalinmoney= dbo.F_RoundTotal(@ntotalinmoney),
		npreferencemoney= dbo.F_RoundTotal(@npreferencemoney),
		nvipczmoney= dbo.F_RoundTotal(@nvipczmoney),
		atypeid1=@ATYPEID1,
		billproperty=@billproperty,
		ncompletetotal= dbo.F_RoundTotal(@ncompletetotal),
		isini = @isini,
		ATID = @ATID,
		IfCargo=@IfCargo,
		IfInvoice=@IfInvoice,
		
		InvoiceMoney= dbo.F_RoundTotal(@invoicemoney),
		NInvoiceMoney= dbo.F_RoundTotal(@ninvoicemoney),
		
		AssetBusinessTypeId=@AssetBusinessTypeId,
		PromoRuleId = @PromoRuleId,
		BeforePromoBillNumberId= @beforepromobillnumberid,
		PromotionMsg=@promotionmsg,
		Stypeid2=@STypeId2,
		IfConfirm=@ifconfirm,
		FeeDeductType=@FeeDeductType,
		TransferType=@TransferType,
		checkTime=ISNULL(checkTime,GETDATE()),
		DeliveryAddress=@DeliveryAddress,
		Discount=@Discount,
		AdPriceType=@AdpriceType,
        NChargeOffTotal=@nchargeofftotal,
        ChargeOffType=@ChargeOffType,
        ChargeOffBtypeid=@ChargeOffBtypeid,
		IsLend=@IsLend,
		WarehouseOutDay=@WarehouseOutDay,
		StockInDeadline =@StockInDeadline,
		IsNeedTransport=@IsNeedTransport,
		iscombinationstyle = @iscombinationstyle,
		transportno= @transportno,
		transporterid= @transporterid ,
		transporterfullname=@transporterfullname,
		shipperfullname=@shipperfullname,
		shipperperson=@shipperperson,
		shippertel=@shippertel,
		totalfreight=@totalfreight,
		ntotalfreight=@ntotalfreight,
		CompleteTotal = (CASE WHEN @isini=1 THEN dbo.F_RoundTotal(@curCompleteTotal) ELSE dbo.F_RoundTotal(@completetotal) END),
		ChargeOffTotal=(CASE WHEN @isini=1 THEN dbo.F_RoundTotal(@curChargeOffTotal) ELSE @chargeofftotal END) ,		
		BillTime=(CASE WHEN BillTime IS NULL THEN CONVERT(VARCHAR(20), GETDATE(), 24) ELSE BillTime END),
		PromonIds=ISNULL(@PromonIds,''),
		isByBrandarType=ISNULL(@isByBrandarType,0),
		PayOnTheSpot = @PayOnTheSpot
	WHERE [BillNumberId]  = @BillNumberId

--PRINT @@rowCount
IF @@rowcount =0  OR @@error<>0
--RAISERROR('更新数据表发生错误！',16,1)
	RETURN -5

IF @BillType = 181--IN (177,178,186,191,192,195,196,197,198,200)
BEGIN
	UPDATE Billindex_CarRepair
	SET		[BillDate]=@BillDate,
			[RATypeID]='',
			[OperationSort]='',
			[RepairMode]='',
			[Oil]='',
			[Mileage]='',
			[EpibolyItem]='',
			[OtherItem]='',
			[Status]=0,
			[ManHourTotal]=0,
			[ManHourTax]=0,
			[ManHourTaxTotal]=0,
			[PTypeTotal]=0,
			[PTypeTax]=0,
			[PTypeTaxTotal]=0,
			[EpibolyTotal]=0,
			[OtherTotal]=0,
			[InPriceType]='',
			BTypeID1=0,
			QuickRepairBillID=0,
			ManHourInsuranceTotal=0,
			PTypeInsuranceTotal=0,
			InvoiceMode=0,
			InvoiceCode='',
			InsuranceStatus=0,
			repairtype=0,
			bespokedate='9999-12-31 23:59:59',
			receptiondate='9999-12-31 23:59:59',
			completedate=@completedate,
			infactorydate='9999-12-31 23:59:59',
			factcompletedate='9999-12-31 23:59:59',
			receptionid='',
			unitsatrap='',
			sendperson='',
			ErrDescription='',
			epibolycosttotal=0,
			preferencereason='',
			balancedate='9999-12-31 23:59:59',
			itemprincipal='',
			monitorprincipal='',
			billstate=@billstate,
			intendingkickback=0,
			settlementkickback=0,
			BackTypeId=0,
			intendingtalkbackdate='9999-12-31 23:59:59',
			istalkbackover=0,
			RepairAutoTypeId='',
			czbeforetimes=@czbeforetimes
	WHERE BillNumberID=@BillNumberId
END

IF @BillType IN (11,12,34,140,144,400,402) AND @ModifyAuditBill<>1
BEGIN
	DECLARE @billTableName VARCHAR(50);
	DECLARE @tempSQL VARCHAR(500);
	CREATE TABLE #TEMP
	(
		BillNumberID NUMERIC(10,0),
		OrderID INT,
		Qty  NUMERIC(24, 10) 
	)
	IF @BillType=11
	BEGIN
		SET @billTableName='SaleBill'
	END
	IF @BillType=34
	BEGIN
		SET @billTableName='BuyBill'
	END
	IF @BillType=12
	BEGIN
		SET @billTableName='PT_Combin_SaleBillDetail'
	END
	IF @BillType=140
	BEGIN
		SET @billTableName='commissionbill'
	END
	IF @BillType=144
	BEGIN
		SET @billTableName='commissionbill'
	END
	IF @BillType=400
	BEGIN
		SET @billTableName='AppraisalBill'
	END
	IF @BillType=402
	BEGIN
		SET @billTableName='SENDBill'
	END
	
	SET @tempSQL='INSERT INTO #TEMP(BillNumberID,OrderID,Qty)
	SELECT BillNumberId,OrderID,ISNULL(SUM(Qty),0) AS Qty
	FROM '+ @billTableName +'
	WHERE BillNumberId = '+CONVERT(varchar(15),@BillNumberID)+'
	GROUP BY BillNumberId,OrderID'

	EXEC (@tempSQL);
	IF @BillType=12
	BEGIN
		UPDATE PT_Combin_OrderBillDetail 
		SET WaitQty = S.WaitQty - T.Qty
		FROM PT_Combin_OrderBillDetail S
		INNER JOIN #TEMP T ON T.OrderID = S.OrderID AND S.BillOver<>1
		
		UPDATE PT_Combin_OrderBill
		SET WaitQty = S.WaitQty - T.Qty
		FROM PT_Combin_OrderBill S
		INNER JOIN #TEMP T ON T.OrderID = S.OrderID AND S.BillOver<>1
	END
	ELSE
	BEGIN
		UPDATE OrderBill 
		SET WaitQty = S.WaitQty - T.Qty
		FROM OrderBill S
		INNER JOIN #TEMP T ON T.OrderID = S.OrderID AND S.BillOver<>1
	END
END

IF @BillType IN (11,12,34,140,144,400,402) AND @ModifyAuditBill<>1
BEGIN
	DROP TABLE #TEMP	
END

--删除自定义表头列
DELETE FROM CustomBillColumns	WHERE billnumberid=@BillNumberId AND BillType=@BillType
--删除自定义明细列
DELETE FROM CustomBillDetailColumns WHERE billnumberid=@BillNumberId AND BillType=@BillType
DELETE FROM dbo.Custom_BillDetails WHERE BillId=@BillNumberID AND BillType=@BillType
DELETE FROM dbo.Custom_BillIndex WHERE BillId=@BillNumberID AND BillType=@BillType

--@@ROWCOUNT万恶
IF @BillType IN(6,11,12,34,45,46,400,401,402,403,414) 
BEGIN
    
    --IF  @paytag <> 0
    --BEGIN
    --   RETURN;
    --END  

	DELETE BillMulAccount WHERE BillNumberId=@BillNumberId AND (PayType IS NULL OR PayType = 0)  AND billtype=@billtype
	DELETE BillMulBrand WHERE BillNumberId=@BillNumberId AND billtype=@billtype
	
	-- 处理订单库存(全面修改单据)
	IF @BillType IN (11,12,34,144,140,400,402,45)
	BEGIN
		IF @ModifyAuditBill =1
		BEGIN
		
			--先加被引用的，全面修改单据在Gp_InsertSaleBillDT时无法判断是否过账
			EXEC GP_CopyOrCreateBill_DraftQTY @BillnumberID,@BillType
			--需要更改订单明细行的waitqty
			
		IF @BillType IN (11,12,34,144,140,400,402)
		BEGIN	
			--先减去过账数量
			EXEC GP_Deal_OrderReachQTY @BillnumberID,@BillType,'-',1
		END
		END
	END

	RETURN 
END
------------------------------------------------------------
IF @BillType IN (305,11,12,45,46,34,6,140,141,142,143,144,145,146,147,4,66,17,21,9,14,57,16,155,157,
	115,116,128,129,5,10,36,77,78,84,85,93,158,139,126,148,150,149,151,159,160,161,
	165,166,167,168,169,170,171,172,173,174,175,180,177,178,183,184,185,186,187,188,189,190,191,192,195,196,197,200,198,201,202,205,206,212,213,214,215,415,310,181,312,400,401,402,403)
BEGIN
	--期初单据不影响草稿库存
	IF @isini <> 1
	BEGIN
		IF @ModifyAuditBill <>1 
		BEGIN
			--删除单据明细影响草稿库存
			EXEC GP_AuditingORDel_DraftQTY @BillnumberID,@BillType
		END

		-- 处理订单库存
		IF @BillType IN (11,12,34,144,140,400,402)
		BEGIN
			IF @ModifyAuditBill <>1
			BEGIN
				--先减去引用未过账数量
				EXEC GP_Deal_OrderReferQty @BillnumberID,@BillType,'-'
			END
			ELSE
			BEGIN
				--先加被引用的，全面修改单据在Gp_InsertSaleBillDT时无法判断是否过账
				EXEC GP_Deal_OrderReferQty @BillnumberID,@BillType,'+'
				--先减去过账数量
				EXEC GP_Deal_OrderReachQTY @BillnumberID,@BillType,'-'
			END
		END
	END
	-- 删除单据明细
	DECLARE 
		@strSQL		varchar(500),
		@strDBName	varchar(100)
	IF @BillType=305
	BEGIN
		DELETE FROM RetailCombinationBill WHERE BILLNUMBERID=CONVERT(varchar(15),@BillNumberID)
	END
	ELSE IF @BillType=12
	BEGIN
		DELETE FROM PT_Combin_SaleBill WHERE BILLNUMBERID=CONVERT(varchar(15),@BillNumberID)
		DELETE FROM PT_Combin_SaleBillDetail WHERE BILLNUMBERID=CONVERT(varchar(15),@BillNumberID)
	END
	ELSE IF @BillType=46
	BEGIN
		DELETE FROM PT_Combin_SaleBackBill WHERE BILLNUMBERID=CONVERT(varchar(15),@BillNumberID)
		DELETE FROM PT_Combin_SaleBackBillDetail WHERE BILLNUMBERID=CONVERT(varchar(15),@BillNumberID)
	END
	SET @strDBName = CASE
						WHEN @BillType = 305	THEN 'RetailBill'			-- 零售单
						WHEN @BillType = 11		THEN 'SaleBill'				-- 销售出库单
						WHEN @BillType = 45		THEN 'SaleBackBill'			-- 销售退货单
						WHEN @BillType = 34		THEN 'BuyBill'				-- 采购入库单
						WHEN @BillType = 6		THEN 'BuyBackBill'			-- 采购退货单
						WHEN @BillType IN (140,141,142,143,144,145,146,147)
												THEN 'CommissionBill'		-- 委托/受托代销单据(7种)
						WHEN @BillType = 4		THEN 'GatheringBill'		-- 收款单
						WHEN @BillType = 66		THEN 'PayBill'				-- 付款单
						WHEN @BillType = 17		THEN 'MoveBill'				-- 同价调拨单
						WHEN @BillType = 21		THEN 'MoveBjBill'			-- 变价调拨单
						WHEN @BillType = 9		THEN 'LoseBill'				-- 报损单
						WHEN @BillType = 14		THEN 'OverFlowBill'			-- 报溢单
						WHEN @BillType = 57		THEN 'AdPriceBill'			-- 成本调价单
						WHEN @BillType = 16		THEN 'DisassembleBill'		-- 生产拆装单
						WHEN @BillType = 155	THEN 'GoodsExchangeBill'	-- 换货单
						WHEN @BillType = 157	THEN 'RepairDeal'			-- 维修受理单
						WHEN @BillType IN (115,116,128,129)
												THEN 'AdDebtBill'			-- 往来调账单(4种)
						WHEN @BillType IN (5,10,36,78,84,85,93,158)
												THEN 'MoneyBill'			-- 待摊费用类单据(2种)
																			-- 费用单
																			-- 固定资产类单据(3种)
																			-- 其他收入单
																			-- 现金费用单
						WHEN @BillType = 77		THEN 'MoveMoneyBill'		-- 转款单
						WHEN @BillType = 139	THEN 'GiveBill'				-- 赠送单
						WHEN @BillType = 126	THEN 'GiveMeBill'			-- 获赠单
						WHEN @BillType IN (148,150)
												THEN 'Advantage'			-- 返利/获利核算执行单据
						WHEN @BillType IN (149,151)
												THEN 'PriceProtectBill'		-- 价保执行单/获得价保
						WHEN @BillType = 159	THEN 'AccountCredence'		-- 会计凭证
						WHEN @BillType = 160	THEN 'SaleGoodsExchangeBill'-- 销售换货单
						WHEN @BillType = 161	THEN 'BuyGoodsExchangeBill'	-- 采购换货单
						WHEN @BillType = 165	THEN 'wx_Bill_JieJian'		-- 新维修 - 接件单
						WHEN @BillType = 166	THEN 'wx_Bill_Self'			-- 新维修 - 自行维修单
						WHEN @BillType = 167	THEN 'wx_Bill_GetBack'		-- 新维修 - 维修取件单
						WHEN @BillType = 168	THEN 'wx_Bill_Replace'		-- 新维修 - 整机更换单
						WHEN @BillType = 169	THEN 'wx_Bill_Send'			-- 新维修 - 送修单
						WHEN @BillType = 170	THEN 'wx_Bill_SendBack'		-- 新维修 - 送修返回单
						WHEN @BillType = 171	THEN 'wx_Bill_Call'			-- 新维修 - 报修单
						WHEN @BillType = 172	THEN 'wx_Bill_Goto'			-- 新维修 - 上门维修单
						WHEN @BillType = 173	THEN 'wx_Bill_In'			-- 新维修 - 维修品调入单
						WHEN @BillType = 174	THEN 'wx_Bill_Out'			-- 新维修 - 维修品调出单
						WHEN @BillType = 175	THEN 'wx_Bill_Move'			-- 新维修 - 维修品调拨单
						WHEN @BillType = 180	THEN 'QP_RecycleBill'		-- 旧件回收单
						WHEN @BillType = 177    THEN 'QP_EvaluationBill_RepairItems'	--维修估价单
						WHEN @BillType = 178    THEN 'QP_QuickRepairBill_RepairItems'
						WHEN @BillType = 183    THEN 'IntegralExchangeBill'	--积分兑换单
						WHEN @BillType = 184    THEN 'QuotePriceBill'		--报价单
						WHEN @BillType = 185    THEN 'AskPriceBill'			--询价单
						WHEN @BillType = 186    THEN 'QP_InsuranceBill_RepairItems' --保险理赔单_维修项目明细表
						WHEN @BillType = 187    THEN 'STypeMoveBill'		--分支机构调拨出库单
						WHEN @BillType = 188    THEN 'STypeMoveBill'		--分支机构调拨入库单
						WHEN @BillType = 189	THEN 'PreBill'				--预收款单
						WHEN @BillType = 190	THEN 'PreBill'				--预付款单
						WHEN @BillType = 191	THEN 'Qp_PickingBill'		--领料出库单
						WHEN @BillType = 192	THEN 'Qp_BackingOut_Bill'	--返修单
						WHEN @BillType = 195	THEN 'Qp_ReceptionBill_RepairItems'	--接待登记单,维修结算单
						WHEN @BillType = 196	THEN 'Qp_SuccorBill_RepairItems'	--救援单
						WHEN @BillType = 197    THEN 'Qp_PickingBackBill'	--领料退回单
						WHEN @BillType = 200    THEN 'Qp_ThreePacketsBill_RepairItems' --三包索赔单
						WHEN @BillType = 198    THEN 'Qp_IntendingTalkBack_Bill' --回访单
						WHEN @BillType = 179    THEN 'QP_WashCarBill' --洗车结算
						WHEN @BillType = 201    THEN 'OtherInOutBill' --其他入库单
						WHEN @BillType = 202    THEN 'OtherInOutBill' --其他出库单
						WHEN @BillType = 205    THEN 'ShareFeeBill' --采购费用分摊
						WHEN @BillType = 206    THEN 'ShareFeeBill' --销售费用分摊
						WHEN @BillType = 415    THEN 'ShareFeeBill' --销售费用分摊
						WHEN @BillType IN (212,213) THEN 'AssetIncDecBill' --固定资产增加减少
						WHEN @billType=214 THEN 'DepBill' --固定资产折旧单
						WHEN @billType=215 THEN 'RetailBackBill' --零售退货单
						WHEN @billType=310 THEN 'CapitalTransfer_Bill' --资金调拨单
						WHEN @billType=312 THEN 'VipAddMoneyBatchBill' --会员批量储值充值
						WHEN @BillType=400 THEN 'AppraisalBill' --暂估入库单
						WHEN @BillType=401 THEN 'AppraisalBackBill' --暂估退货单
						WHEN @BillType=402 THEN 'SendBill' --发出商品出库单
						WHEN @billType=403 THEN 'SendBackBill'  --发出商品退货单
					END 
	
	DECLARE
		@intNoDelete INT
		
	SELECT @intNoDelete=0
	
	IF @BillType=195
	BEGIN
		IF EXISTS(SELECT BillNumberID FROM Billindex_CarRepair WHERE BillNumberId=@BillNumberId AND BillState=3)
		BEGIN
			SELECT @intNoDelete=1
		END
	END
	
	IF @intNoDelete=0
	BEGIN
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		
		EXEC(@strSQL)
	END
	ELSE IF @BillType=195
	BEGIN
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)+' AND Virtual=1 '
		
		EXEC(@strSQL)
	END


	IF (@@ROWCOUNT = 0 OR @@ERROR <> 0) AND @BillType NOT IN (177,178,186,199,200,195,196)
	BEGIN
		IF @BillType IN (166,172) AND @@ROWCOUNT = 0
		BEGIN
			SET @strSQL = 'SELECT TOP 1 1 FROM ' + @strDBName + ' WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
			EXEC(@strSQL)
			IF @@ROWCOUNT = 0 
			BEGIN
			DELETE BillMulAccount WHERE BillNumberId=@BillNumberId  AND billtype=@billtype
			RETURN 0
			END
			
		END
		--RAISERROR('删除单据发生错误',16,1)
		RETURN -6
	END
	
	IF @BillType = 157
	BEGIN
		SET @strDBName = 'RepairDealDetail'
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END
	END

	IF @BillType = 177
	BEGIN
		SET @strDBName = 'QP_EvaluationBill_PType'
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)

		/*
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END
		*/
	END

	IF @BillType = 178
	BEGIN
		SET @strDBName = 'QP_QuickRepairBill_PType'
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)

		/*
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END
		*/
	END

	IF @BillType = 186
	BEGIN
		SET @strDBName = 'QP_InsuranceBill_PType'
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)

		/*
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END
		*/
	END
	IF @BillType = 195 
	BEGIN
		DECLARE
			@intBillState	INT
			
		SELECT @intBillState=BillState
		FROM Billindex_CarRepair
		WHERE BillNumberId=@BillNumberId
		
		IF @intBillState=1
		BEGIN
			DELETE FROM Qp_ReceptionBill_PType WHERE BillNumberId = @BillNumberId
			DELETE FROM Qp_ReceptionBill_RepairItems WHERE BillNumberId = @BillNumberId
			
			DELETE FROM Qp_ReceptionBill_Pic WHERE BillNumberId = @BillNumberId
			DELETE FROM Qp_ReceptionBill_Accessory WHERE BillNumberId = @BillNumberId
			DELETE FROM Qp_ReceptionBill_Insurance WHERE BillNumberId = @BillNumberId
		END
		ELSE
		BEGIN
			DELETE FROM Qp_ReceptionBill_PType WHERE BillNumberId = @BillNumberId AND Virtual=1
			DELETE FROM Qp_ReceptionBill_RepairItems WHERE BillNumberId = @BillNumberId AND Virtual=1
			DELETE FROM Qp_ReceptionBill_FactUsePType WHERE ReceptionBillnumberId = @BillNumberId AND Virtual=1
		END
	END
	IF @BillType = 196
	BEGIN
		SET @strDBName = 'Qp_SuccorBill_PType'
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		SET @strDBName = 'Qp_SuccorBill_SuccorItems'
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		
		
		SET @strDBName = 'Qp_SuccorBill'
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		
		
		SET @strDBName = 'Qp_SuccorBill_ErrDescription'
		SET @strSQL = '
			DELETE FROM ' + @strDBName + '
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)


		/*
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END
		*/
	END
	
	
	IF @BillType=200
	BEGIN
		DELETE Qp_ThreePacketsBill_PType WHERE BillNumberId=@BillNumberId 
	END
	/*
	IF @BillType in ('305','11','141','167','172','178','195','179','182','196','181','34','145')--删除多账户信息
	BEGIN
		DELETE BillMulAccount WHERE BillNumberId=@BillNumberId 
	END*/
	
	IF @BillType in(205,206,415)
	BEGIN
		DELETE ShareSourceBill WHERE BillNumberId=@BillNumberId 
	END
	
	--IF @BillType=11
	--BEGIN
	--	DELETE DiyBillTypePSaleTypeID WHERE  SalebillNumberId=@BillNumberId 
	--END
	
	--IF  @paytag <> 0
 --   BEGIN
 --      RETURN;
 --   END 
	
	DELETE BillMulAccount WHERE BillNumberId=@BillNumberId AND BILLTYPE =@BillType AND (PayType IS NULL OR PayType = 0)  --单账户也会写这张表
	
	DELETE dbo.BillMulBrand WHERE  BillNumberId=@BillNumberId AND BILLTYPE =@BillType
	
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateBuyOrderState]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateBuyOrderState]
GO




--20090812
--李明洋

--20131125 周华 修改审核流程修改问题 参考9.1 sp2
CREATE    PROCEDURE Gp_UpdateBuyOrderState	--在单据审核发生变化后修改采购订单的状态
(
	@AuditingID			int,		--审核流程编号
	@StateBefore		int,		--销售订单之间的状态
	@deleteBill			int			--是否需要清除待审核
)
--@encode$--
AS

SET NOCOUNT ON


DECLARE @IfHaveBuy1 int
SET @IfHaveBuy1 = 0

IF EXISTS(SELECT * FROM AuditingFlowSet where Billtype =301 AND AuditingType<>0 AND LEFT(AuditingReason,1)<>'1')
	SET @IfHaveBuy1 = 1

CREATE TABLE #BillnumberID (BillnumberID INT)
CREATE TABLE #BillnumberID1 (BillnumberID INT)
CREATE TABLE #BillnumberID2 (BillnumberID INT)



		IF @StateBefore = 0
		BEGIN
			IF @IfHaveBuy1 = 1 -- 订单审核从无到有
			BEGIN
				-- 没被调用的订单IfAudit置0，清除AuditingBill
				INSERT INTO #BillnumberID 
					select  BillnumberID   FROM OrderBill where OrderID IN (SELECT orderid From BuyBill)
				UNION
					select  BillnumberID   FROM OrderIndex WHERE Billtype =301 AND orderState ='1'
	
				Update orderindex set ifAudit=0 WHERE OrderState ='0' AND billtype =301 AND BillnumberID NOT IN (SELECT BillnumberID FROM #BillnumberID)
				AND Stypeid=(select TOP 1 stypeid FROM AuditingFlowSet WHERE AuditingID = @AuditingID AND Billtype =301)
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex WHERE OrderState='0' AND billtype=301 And IfAudit=0) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID IN (SELECT BillnumberID FROM Orderindex WHERE OrderState ='0' AND billtype =301 AND ifAudit =0) AND AuditingID=@AuditingID
			END
		END
		ELSE
		BEGIN
			IF @IfHaveBuy1 = 1 -- 订单审核从有到有 审核改变
			BEGIN
				-- 审核没通过或待审单据 
				INSERT INTO #BillnumberID SELECT BillnumberID FROM AuditingBill WHERE IfAudit ='0' AND AuditingID =@AuditingID 
				-- 被调用过的订单或订单状态为已完成
				INSERT INTO #BillnumberID1 
					select  BillnumberID   FROM OrderBill where OrderID IN (SELECT orderid From BuyBill) 
				UNION			
					select  BillnumberID   FROM OrderIndex WHERE Billtype =301 AND orderState ='1'
				-- 审核通过单据
				INSERT INTO #BillnumberID2 SELECT BillnumberID FROM AuditingBill WHERE IfAudit ='1' AND AuditingID =@AuditingID 
	
				--没有审核通过，待审核的订单IfAudit置0
				Update Orderindex SET IfAudit =0 WHERE orderState='0' AND Billtype=301 AND  BillnumberID  IN (SELECT BillnumberID FROM #BillnumberID)
				-- 不在审核通过，且不在被调用过的单据之中，IfAudit置0
				UPDATE Orderindex SET IfAudit =0 WHERE orderState='0' AND Billtype=301 AND  
				(BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID1)) AND 
				(BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID2))
				 AND Stypeid=(SELECT TOP 1 stypeid FROM AuditingFlowSet WHERE AuditingID = @AuditingID AND Billtype =301)
				if @deleteBill = 1
				begin
					--没有审核通过，待审核的订单,清除AuditingBill
					DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM #BillnumberID) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
					DELETE FROM AuditingBill WHERE BillnumberID  IN (SELECT BillnumberID FROM #BillnumberID) AND AuditingID =@AuditingID
					-- 不在审核通过，且不在被调用过的单据之中，清除AuditingBill
--					DELETE FROM AuditingBill WHERE BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID1) AND AuditingID =@AuditingID AND BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID2)
				end
	
			END
			ELSE	-- 订单审核从有到无
			BEGIN
				-- 所有订单的IfAudit 置 1，清除订单的 AuditingBill
				Update orderindex set ifAudit=1 WHERE  billtype =301
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex WHERE billtype=301) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID IN (SELECT BillnumberID FROM Orderindex WHERE billtype =301 ) AND AuditingID =@AuditingID
			END
		END


DROP TABLE #BillnumberID
DROP TABLE #BillnumberID1
DROP TABLE #BillnumberID2


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpDateBuyRequestBillState]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpDateBuyRequestBillState
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-18
	描述：更改请购单计划状态
*/
CREATE PROCEDURE Gp_UpDateBuyRequestBillState
(
	@idlist	VARCHAR(MAX),		--单据ID集合
	@billstate	int,			--要变为的状态
	@feedback varchar(max)		--反馈信息
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT * FROM RequestBill WHERE	ID IN (SELECT * FROM DBO.f_split(@idlist,',')) AND State>6)
	RETURN 2

BEGIN TRANSACTION  DEL
IF @billstate<>6
	BEGIN
		UPDATE	RequestBill 
		SET		State = @billstate,feedback=@feedback,Etypeid='' 
		WHERE	ID IN (SELECT * FROM DBO.f_split(@idlist,',')) 
	END
ELSE
	BEGIN
		UPDATE	RequestBill 
		SET		State = @billstate,etypeid=@feedback 
		WHERE	ID IN (SELECT * FROM DBO.f_split(@idlist,',')) 
	END

IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RETURN 0
	
END

COMMIT TRANSACTION  DEL
RETURN 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateBxPerson]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateBxPerson]
GO
















-- ========================================================================
-- 功能说明：	报修修改维修人
-- 作    者：	cqhua
-- 2009-11-09
-- ========================================================================
CREATE                 PROCEDURE GP_UpdateBxPerson
(
	@billnumberid   varchar(6000), -- 单据ID
	@idstr          varchar(6000), -- 表wx_Bill_call 字段ID
	@EtypeID 		varchar(50)		-- 职员ID
)	

--@encode$--
AS
CREATE TABLE #Billnumberid 
(
[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
billnumberid numeric(18,0)
)

CREATE TABLE #idstr 
(
[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
idstr numeric(18,0)
)

INSERT INTO #Billnumberid(Billnumberid) select * from dbo.f_split(@billnumberid,',')
INSERT INTO #idstr(idstr) select * from dbo.f_split(@idstr,',')
--报修单的状态不为 【待上门维修】，不能修改维修人
IF EXISTS(select top 1 1 from wx_Bill_call a,#Billnumberid b,#idstr c where a.state<>0 AND  a.billnumberid=b.billnumberid and a.id=c.idstr)
	RETURN -1

UPDATE wx_Bill_call set  etypeid=@Etypeid
FROM wx_Bill_call a
INNER JOIN #billnumberID b on a.billnumberid=b.billnumberid
INNER JOIN #idstr c on a.ID=c.idstr
WHERE b.ID=c.ID


DROP TABLE #Billnumberid
DROP TABLE #idstr


SET NOCOUNT ON
SET ANSI_WARNINGS OFF











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateCarInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateCarInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-16
	描述：车辆信息更新
*/

CREATE PROCEDURE GP_UpdateCarInfo
(
	@platenumber    varchar(50),
	@cartype		varchar(50),
	@receptiondate  datetime,
	@etypeid		varchar(50),
	@typeid			varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON

	if exists (select fullname from employee where typeId=@etypeid and deleted=1)
	begin
		RAISERROR('选择的驾驶员已停用，请重新选择驾驶员!',16,1)return--return -511
	end

update CM_CarInfo 
set 
	platenumber=@platenumber,
	Cartype=@cartype,
	Receptiondate=@receptiondate,
	Driver=@etypeid
where
	TypeId=@typeid
	

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateCombinationOrderBillDetailsDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_UpdateCombinationOrderBillDetailsDT;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-07 11:13:50.777
	描述：采购订单，销售订单 明细查入 DT版
*/
CREATE PROCEDURE Gp_UpdateCombinationOrderBillDetailsDT
	@intFlag INT
	,@billNumberId INT
	,@billType INT
	,@tb TbType_CombinationOrder READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	IF @intFlag = 0 --插入操作
	BEGIN
		INSERT INTO PT_Combin_OrderBillDetail(
			BillNumberID,
			PTypeID,
			Qty,
			Price,
			Total,
			ReachQty,
			Comment,
			IsUnit2,
			Discount,
			DiscountPrice,
			TaxPrice,
			TaxTotal,
			SaleTotal,
			Tax,
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID,
			RequestBillNumberID,
			RequestBillID,
			AskBillNumberID,
			AskBillID
			
			-- 新增字段
			,TaxMoney
			,NSalePrice
			,NSaleTotal
			,NDiscountPrice
			,NTotal
			,NTaxPrice
			,NTaxTotal
			,NTaxMoney
			--,CargoId
			,UnitId
			,NUnitId
			,NQty
			,UnitRate
			,NUnitMsg
			,MUnitId
			,MQty
			,MUnitRate
			,MUnitMsg
			,MSalePrice
			,MDiscountPrice
			,MTaxPrice
			,CurMSalePrice
			,CurMDiscountPrice
			,CurMTaxPrice
			,ItemId
			,IsCombined
			,goodsnumber
			,CargoID
			,GoodsCostPrice
			,GoodsOrder 
			,ProduceDate 
			,ValidDate 
			,entrycode
			,IsGift
			,YapiID
			,PriceSource
			,Id
			,PromoType
			,ShowOrder
			,pindexid
			,combinationptypeid
		) SELECT 
			@billNumberId,
			chvPTypeID,
			dbo.F_RoundQty(numQty),
			dbo.F_RoundPrice(numPrice),
			dbo.F_RoundTotal(numTotal),
			dbo.F_RoundQty(numReachQty),
			chvComment,
			intIsUnitTow,
			dbo.F_RoundDiscount(numDiscount),
			dbo.F_RoundPrice(numDiscountPrice),
			dbo.F_RoundPrice(numTaxPrice),
			dbo.F_RoundTotal(numTaxTotal),
			dbo.F_RoundTotal(numSaleTotal),
			dbo.F_RoundTax(numTax),
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID,
			requestbillnumberid,
			requestbillid,
			askbillnumberid,
			askbillid
			
			-- 新增字段
			,dbo.F_RoundTotal(TaxMoney)
			,dbo.F_RoundPrice(NSalePrice)
			,dbo.F_RoundTotal(NSaleTotal)
			,dbo.F_RoundPrice(NDiscountPrice)
			,dbo.F_RoundTotal(NTotal)
			,dbo.F_RoundPrice(NTaxPrice)
			,dbo.F_RoundTotal(NTaxTotal)
			,dbo.F_RoundTotal(NTaxMoney)
			--,CargoId
			,UnitId
			,NUnitId
			,dbo.F_RoundQty(NQty)
			,dbo.F_RoundTranslateRate(UnitRate)
			,NUnitMsg
			,MUnitId
			,dbo.F_RoundQty(MQty)
			,dbo.F_RoundTranslateRate(MUnitRate)
			,MUnitMsg
			,dbo.F_RoundPrice(MSalePrice)
			,dbo.F_RoundPrice(MDiscountPrice)
			,dbo.F_RoundPrice(MTaxPrice)
			,dbo.F_RoundPrice(CurMSalePrice)
			,dbo.F_RoundPrice(CurMDiscountPrice)
			,dbo.F_RoundPrice(CurMTaxPrice)
			,ItemId
			,IsCombined
			,goodsnumber
			,CargoID
			,dbo.F_RoundPrice(GoodsCostPrice)
			,GoodsOrder 
			,ProduceDate 
			,ValidDate 
			,entrycode
			,IsGift
			,YapiID
			,PriceSource
			,Id
			,PromoType
			,ShowOrder
			,pindexid
			,combinationptypeid
		FROM @tb;
		/*
		说明：组合品销售订单不能调用报价单，因此此处不需要回写数量
		*/
	END
	-- 更新处理
	ELSE 
	BEGIN
		IF (SELECT IsIni FROM OrderIndex WHERE billNumberId = @billNumberId) <> 1
		BEGIN
			--删除订单明细影响订单库存
			EXEC GP_Deal_OrderQTY @billNumberId,@billType,'-'
		END
	SELECT * FROM orderbill 
		CREATE TABLE #t(id int);
		BEGIN
			INSERT #t SELECT orderid FROM dbo.PT_Combin_OrderBillDetail a WHERE billNumberID=@billNumberId
			AND (EXISTS(SELECT 1 FROM dbo.PT_Combin_SaleBillDetail b JOIN billindex w ON b.BillNumberId=w.BillNumberId WHERE a.OrderID=b.OrderID AND w.RedWord=0) 
				OR EXISTS (SELECT 1 FROM dbo.OrderBill b  WHERE a.OrderID=b.PTCombinOrderBillDetailID )
				OR BillOver<>0) --被引用或被中止的明细
		END
		--1.清除没有的
		DELETE FROM dbo.PT_Combin_OrderBillDetail WHERE billNumberID=@billNumberId AND OrderID NOT IN (SELECT id FROM #t) 
		
		--2.插入新增的
		INSERT INTO PT_Combin_OrderBillDetail(
				BillNumberID,
				PTypeID,
				Qty,
				Price,
				Total,
				ReachQty,
				Comment,
				IsUnit2,
				Discount,
				DiscountPrice,
				TaxPrice,
				TaxTotal,
				SaleTotal,
				Tax,
				KTypeID,
				STypeID,
				FromBillNumberID,
				FromBillID,
				RequestBillNumberID,
				RequestBillID,
				AskBillNumberID,
				AskBillID
				
				-- 新增字段
				,TaxMoney
				,NSalePrice
				,NSaleTotal
				,NDiscountPrice
				,NTotal
				,NTaxPrice
				,NTaxTotal
				,NTaxMoney
				--,CargoId
				,UnitId
				,NUnitId
				,NQty
				,UnitRate
				,NUnitMsg
				,MUnitId
				,MQty
				,MUnitRate
				,MUnitMsg
				,MSalePrice
				,MDiscountPrice
				,MTaxPrice
				,CurMSalePrice
				,CurMDiscountPrice
				,CurMTaxPrice
				,ItemId
				,IsCombined
				,goodsnumber
				,CargoID
				,GoodsCostPrice
				,GoodsOrder 
				,ProduceDate 
				,ValidDate 
				,entrycode
				,IsGift
				,YapiID
				,PriceSource
				,Id
				,PromoType
				,ShowOrder
				,pindexid
				,combinationptypeid
		) SELECT 
				@billNumberId,
				chvPTypeID,
				numQty,
				numPrice,
				numTotal,
				numReachQty,
				chvComment,
				intIsUnitTow,
				numDiscount,
				numDiscountPrice,
				numTaxPrice,
				numTaxTotal,
				numSaleTotal,
				numTax,
				KTypeID,
				STypeID,
				FromBillNumberID,
				FromBillID,
				requestbillnumberid,
				requestbillid,
				askbillnumberid,
				askbillid
				
				-- 新增字段
				,TaxMoney
				,NSalePrice
				,NSaleTotal
				,NDiscountPrice
				,NTotal
				,NTaxPrice
				,NTaxTotal
				,NTaxMoney
				--,CargoId
				,UnitId
				,NUnitId
				,NQty
				,UnitRate
				,NUnitMsg
				,MUnitId
				,MQty
				,MUnitRate
				,MUnitMsg
				,MSalePrice
				,MDiscountPrice
				,MTaxPrice
				,CurMSalePrice
				,CurMDiscountPrice
				,CurMTaxPrice
				,ItemId
				,IsCombined
				,goodsnumber
				,CargoID
				,GoodsCostPrice
				,GoodsOrder 
				,ProduceDate 
				,ValidDate 
				,entrycode
				,IsGift
				,YapiID
				,PriceSource
				,Id
				,PromoType
				,ShowOrder
				,pindexid
				,combinationptypeid
		FROM @tb WHERE OrderID NOT IN (SELECT id FROM #t)
		
		--3.更新要更新的
		UPDATE a SET id=b.id,ShowOrder=b.ShowOrder
		FROM dbo.PT_Combin_OrderBillDetail a JOIN @tb b ON a.OrderID=b.OrderId 
		AND a.billNumberID=@billNumberId AND a.Id<>b.Id
		DROP TABLE #t;
	END
		
	IF @@ERROR <> 0
		RAISERROR('写入组合品销售订单明细数据时发生错误！',16,1);
	
	-- 判断并处理订单的完成状态
	--EXEC GP_AuditingCheckOrderState @billNumberId,0
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateCombinationOrderBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_UpdateCombinationOrderBillDT;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：罗淮文
	时间：2016-07-11
	描述：组合品销售订单 明细保存/修改 DT版
*/
CREATE PROCEDURE Gp_UpdateCombinationOrderBillDT
	@intFlag INT
	,@billNumberId INT
	,@billType INT
	,@tb TbType_CombinationOrder READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	IF @intFlag = 0 --插入操作
	BEGIN
		INSERT INTO PT_Combin_OrderBill(
			BillNumberID,
			PTypeID,
			Qty,
			Price,
			Total,
			ReachQty,
			Comment,
			IsUnit2,
			Discount,
			DiscountPrice,
			TaxPrice,
			TaxTotal,
			SaleTotal,
			Tax,
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID,
			RequestBillNumberID,
			RequestBillID,
			AskBillNumberID,
			AskBillID
			,TaxMoney
			,NSalePrice
			,NSaleTotal
			,NDiscountPrice
			,NTotal
			,NTaxPrice
			,NTaxTotal
			,NTaxMoney
			--,CargoId
			,UnitId
			,NUnitId
			,NQty
			,UnitRate
			,NUnitMsg
			,MUnitId
			,MQty
			,MUnitRate
			,MUnitMsg
			,MSalePrice
			,MDiscountPrice
			,MTaxPrice
			,CurMSalePrice
			,CurMDiscountPrice
			,CurMTaxPrice
			,ItemId
			,IsCombined
			,CargoID
			,GoodsCostPrice
			,GoodsOrder 
			,entrycode
			,IsGift
			,YapiID
			,PriceSource
			,Id
			,PromoType
			,ShowOrder
			,pindexid
		) SELECT 
			@billNumberId,
			chvPTypeID,
			dbo.F_RoundQty(numQty),
			dbo.F_RoundPrice(numPrice),
			dbo.F_RoundTotal(numTotal),
			dbo.F_RoundQty(numReachQty),
			chvComment,
			intIsUnitTow,
			dbo.F_RoundDiscount(numDiscount),
			dbo.F_RoundPrice(numDiscountPrice),
			dbo.F_RoundPrice(numTaxPrice),
			dbo.F_RoundTotal(numTaxTotal),
			dbo.F_RoundTotal(numSaleTotal),
			dbo.F_RoundTax(numTax),
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID,
			requestbillnumberid,
			requestbillid,
			askbillnumberid,
			askbillid
			
			-- 新增字段
			,dbo.F_RoundTotal(TaxMoney)
			,dbo.F_RoundPrice(NSalePrice)
			,dbo.F_RoundTotal(NSaleTotal)
			,dbo.F_RoundPrice(NDiscountPrice)
			,dbo.F_RoundTotal(NTotal)
			,dbo.F_RoundPrice(NTaxPrice)
			,dbo.F_RoundTotal(NTaxTotal)
			,dbo.F_RoundTotal(NTaxMoney)
			--,CargoId
			,UnitId
			,NUnitId
			,dbo.F_RoundQty(NQty)
			,dbo.F_RoundTranslateRate(UnitRate)
			,NUnitMsg
			,MUnitId
			,dbo.F_RoundQty(MQty)
			,dbo.F_RoundTranslateRate(MUnitRate)
			,MUnitMsg
			,dbo.F_RoundPrice(MSalePrice)
			,dbo.F_RoundPrice(MDiscountPrice)
			,dbo.F_RoundPrice(MTaxPrice)
			,dbo.F_RoundPrice(CurMSalePrice)
			,dbo.F_RoundPrice(CurMDiscountPrice)
			,dbo.F_RoundPrice(CurMTaxPrice)
			,ItemId
			,IsCombined
			,CargoID
			,dbo.F_RoundPrice(GoodsCostPrice)
			,GoodsOrder 
			,entrycode
			,IsGift
			,YapiID
			,PriceSource
			,Id
			,PromoType
			,ShowOrder
			,pindexid
		FROM @tb;
		/*****************************************************************************
			说明：组合品表不需要回写，只回写明细配料表
		*****************************************************************************/
	END
	ELSE -- 更新处理
	BEGIN
		CREATE TABLE #t(id int);
		INSERT #t SELECT orderid FROM dbo.PT_Combin_OrderBill a WHERE billNumberID=@billNumberId
		AND (EXISTS(SELECT 1 FROM dbo.PT_Combin_SaleBill b JOIN billindex w ON b.BillNumberId=w.BillNumberId WHERE a.OrderID=b.OrderID AND w.RedWord=0) OR BillOver<>0) --被引用或被中止的明细
		--组合品可以从下表体推上表体 所以上表体是可以改的
		--INSERT #t --被采购订单引用了下表体 那上表体也不能动了
		--SELECT a.orderid 
		--FROM dbo.PT_Combin_OrderBill a
		--INNER JOIN dbo.PT_Combin_OrderBillDetail b ON a.billNumberID=b.billNumberID AND b.pindexid = a.pindexid 
		-- WHERE a.billNumberID=@billNumberId
		--	AND (  EXISTS (SELECT 1 FROM dbo.OrderBill c  WHERE b.OrderID=c.PTCombinOrderBillDetailID )
		--		) --被引用或被中止的明细
		--1.清除没有的
		DELETE FROM dbo.PT_Combin_OrderBill WHERE billNumberID=@billNumberId AND OrderID NOT IN (SELECT id FROM #t) 
		
		--2.插入新增的
		INSERT INTO PT_Combin_OrderBill(
				BillNumberID,
				PTypeID,
				Qty,
				Price,
				Total,
				ReachQty,
				Comment,
				IsUnit2,
				Discount,
				DiscountPrice,
				TaxPrice,
				TaxTotal,
				SaleTotal,
				Tax,
				KTypeID,
				STypeID,
				FromBillNumberID,
				FromBillID,
				RequestBillNumberID,
				RequestBillID,
				AskBillNumberID,
				AskBillID
				
				-- 新增字段
				,TaxMoney
				,NSalePrice
				,NSaleTotal
				,NDiscountPrice
				,NTotal
				,NTaxPrice
				,NTaxTotal
				,NTaxMoney
				--,CargoId
				,UnitId
				,NUnitId
				,NQty
				,UnitRate
				,NUnitMsg
				,MUnitId
				,MQty
				,MUnitRate
				,MUnitMsg
				,MSalePrice
				,MDiscountPrice
				,MTaxPrice
				,CurMSalePrice
				,CurMDiscountPrice
				,CurMTaxPrice
				,ItemId
				,IsCombined
				,CargoID
				,GoodsCostPrice
				,GoodsOrder 
				,entrycode
				,IsGift
				,YapiID
				,PriceSource
				,Id
				,PromoType
				,ShowOrder
				,pindexid
		) SELECT 
				@billNumberId,
				chvPTypeID,
				numQty,
				numPrice,
				numTotal,
				numReachQty,
				chvComment,
				intIsUnitTow,
				numDiscount,
				numDiscountPrice,
				numTaxPrice,
				numTaxTotal,
				numSaleTotal,
				numTax,
				KTypeID,
				STypeID,
				FromBillNumberID,
				FromBillID,
				requestbillnumberid,
				requestbillid,
				askbillnumberid,
				askbillid
				
				-- 新增字段
				,TaxMoney
				,NSalePrice
				,NSaleTotal
				,NDiscountPrice
				,NTotal
				,NTaxPrice
				,NTaxTotal
				,NTaxMoney
				--,CargoId
				,UnitId
				,NUnitId
				,NQty
				,UnitRate
				,NUnitMsg
				,MUnitId
				,MQty
				,MUnitRate
				,MUnitMsg
				,MSalePrice
				,MDiscountPrice
				,MTaxPrice
				,CurMSalePrice
				,CurMDiscountPrice
				,CurMTaxPrice
				,ItemId
				,IsCombined
				,CargoID
				,GoodsCostPrice
				,GoodsOrder 
				,entrycode
				,IsGift
				,YapiID
				,PriceSource
				,Id
				,PromoType
				,ShowOrder
				,pindexid
		FROM @tb WHERE OrderID NOT IN (SELECT id FROM #t)
	END
		
	IF @@ERROR <> 0
		RAISERROR('写入组合品销售单明细数据时发生错误！',16,1);
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateCommission]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateCommission]
GO

CREATE     PROCEDURE [Gp_UpdateCommission]
(
@BillNumberId  		[numeric](10,0),
@BillCode				VARCHAR(200),   --单据编号
	@FullName				VARCHAR(200)='',   --单据名称
	@BillDate				DATETIME  ,		 --单据日期 
	@PlanStart				DATETIME  ,
	@PlanEnd					DATETIME  ,
	@CommissionStandard		INT  ,			 --提成基准  1=销售额 2=价税合计
	--@Checke					VARCHAR(50)  ,				--制单人
	@Comment					VARCHAR(256) ='',	--摘要
	@BillState				INT ,						--单据状态  1=未审核  2=审核  3=禁用
	@UseState				INT =0,			--使用状态  1=未引用  2=引用  3=部分完成 4=全部完成
	@IsStop					INT =0,				--是否禁用  0=正常  1/2当禁用时写入单据状态 启用时写到单据状态列 起保存禁用时的状态
	@Checker				VARCHAR(50),   --审核人
	@CheckerTime			DATETIME ,		 --审核时间
	@SalePlanId				NUMERIC(18,0),   --关联计划ID
	@SalesFlag	INT ,			 --是否使用促销商品销售额不参与提成 1=勾选
	@BelowCostFlag 	INT		 --是否使用低于成本销售额不参与提成 1=勾选
)
--@encode$--
AS 
SET NOCOUNT ON 

IF NOT EXISTS(SELECT TOP 1 1 FROM ReferencePlanCommission WHERE BillNumberID = @BillNumberID)
	RETURN -7
	
IF @CheckerTime = ''
BEGIN
	SET @CheckerTime = NULL
END
	
UPDATE [dbo].[ReferencePlanCommission] 
SET     
BillCode=	@BillCode,				
FullName=	@FullName,				
BillDate=	@BillDate,				
PlanStart=	@PlanStart,				
PlanEnd=	@PlanEnd,				
CommissionStandard=	@CommissionStandard		,
--Checke=	@Checke	,
Comment	=	@Comment		,
BillState=	@BillState				,
UseState	=	@UseState				,
IsStop	=		@IsStop		,			
Checker = 	@Checker	,
CheckerTime = @CheckerTime,
SalePlanId=	@SalePlanId,
SalesFlag=	@SalesFlag,
BelowCostFlag=@BelowCostFlag
WHERE 	BillNumberID  = @BillNumberId

--PRINT @@rowCount
IF @@rowcount =0  OR @@error<>0
--RAISERROR('更新数据表发生错误！',16,1)
	RETURN -5
	
	------------------------------------------------------------
		declare @strSQL varchar(500)
		SET @strSQL = '
			DELETE FROM ReferencePlanCommissionEtype
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END	
		
		SET @strSQL = '
			DELETE FROM ReferencePlanCommissionPlan
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GP_UpdateCommissionDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC GP_UpdateCommissionDT;
	
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：周华
	时间：2012-05-09 16:11:05.483
	描述：更新委托/受托代销结算单的按单数量
*/
CREATE PROCEDURE GP_UpdateCommissionDT 
(
	@billType INT
	,@tb TbType_CommissionUpdate READONLY
)
--@encode$--	
AS
BEGIN
    IF @billType IN (142,146) --委托，受托代销退货
		UPDATE CommissionBill SET BQty=dbo.F_RoundQty(ISNULL(BQty,0)+v.Qty)
		FROM CommissionBill w JOIN @tb v ON w.BillNumberId=v.OldBillNumberId AND w.Id=v.OldId
		WHERE v.OldBillNumberId<>0 AND ISNULL(w.Qty,0)-ISNULL(w.BQty,0)-ISNULL(w.BackQty,0)>=v.Qty;
    ELSE
		UPDATE CommissionBill SET BackQty=dbo.F_RoundQty(ISNULL(BackQty,0)+v.Qty)
		FROM CommissionBill w JOIN @tb v ON w.BillNumberId=v.OldBillNumberId AND w.Id=v.OldId
		WHERE v.OldBillNumberId<>0 AND ISNULL(w.Qty,0)-ISNULL(w.BQty,0)-ISNULL(w.BackQty,0)>=v.Qty;
END

GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateCompleteBrandarTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateCompleteBrandarTotal]
GO


-- ========================================================================
-- 功能说明：		按品牌结算,写如单据明细

-- ========================================================================
CREATE                              PROCEDURE [GP_UpdateCompleteBrandarTotal]
(
	@MoneyBillNumberID int,--收/付款单据id
	@IfRe int = 0
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @Billtype INT    -- 单据类型
DECLARE @GoodsBillNumberId INT
DECLARE @GoodsDetailId INT

DECLARE @Billdate datetime 

select @Billdate=getDate()

IF EXISTS (SELECT etypeid FROM Billindex   WHERE BillnumberID =@MoneyBillNumberId)
	SELECT @Billdate =billdate FROM Billindex  WHERE BillnumberID =@MoneyBillNumberId

UPDATE dbo.CompleteBrandarTotal SET isdraft=0,BillDate=@Billdate WHERE MoneyBillID=@MoneyBillNumberId AND isDraft=1    --处理按商品结算记录表

IF @@error<>0
RETURN 2

IF @IfRe = 1
BEGIN
	DELETE FROM dbo.CompleteBrandarTotal WHERE MoneyBillID=@MoneyBillNumberId
	AND GoodsBillID NOT IN (
		SELECT GoodsBillID FROM CompleteTotal
		WHERE MoneyBillID=@MoneyBillNumberId AND Draft = 0 GROUP BY GoodsBillID)
	AND isDraft = 0
END

	
DECLARE Bills CURSOR FOR
	SELECT DISTINCT Goodsbillid,b.Billtype,A.DetailId
	FROM dbo.CompleteBrandarTotal A,BillIndex B
	WHERE A.GoodsBillid=B.BillNumberID AND A.BillType=B.BillType
	AND A.MoneyBillId=@MoneyBillNumberID
	AND A.IsDraft=0
	UNION ALL
	SELECT DISTINCT Goodsbillid,b.Billtype ,A.DetailId
	FROM CompleteBrandarTotal A,ReceiptBillIndex B
	WHERE A.GoodsBillid=B.BillNumberID	AND A.BillType=B.BillType						
	AND A.MoneyBillId=@MoneyBillNumberID                      
	AND A.IsDraft=0
	
OPEN Bills
FETCH NEXT FROM Bills INTO @GoodsBillNumberId,@Billtype,@GoodsDetailId
WHILE ( @@FETCH_STATUS = 0 )
BEGIN

	
	-- *** 处理九种单据的结算状态 - Start ***
	DECLARE @intBillType int,
			@TotalMoney  NUMERIC(24, 10) ,
			@TotalInMoney  NUMERIC(24, 10),
			@preferencemoney  NUMERIC(24, 10) ,
			@CompleteTotal  NUMERIC(24, 10) ,
			@NTotalMoney  NUMERIC(24, 10) ,
			@NTotalInMoney  NUMERIC(24, 10),
			@Npreferencemoney  NUMERIC(24, 10) ,
			@NCompleteTotal  NUMERIC(24, 10) ,
			@NChargeOffTotal	NUMERIC(24,10)

	IF @Billtype IN (404,405)
	BEGIN
		SELECT @intBillType=BillType,@TotalMoney=TaxTotalMoney,@TotalInMoney=0,
		@preferencemoney=0,@CompleteTotal=CompleteTotal,
		@NTotalMoney=NTaxTotalMoney,
		@NTotalInMoney=0,
		@Npreferencemoney=0,
		@NCompleteTotal=NCompleteTotal,
		@NChargeOffTotal=NChargeOffTotal
		FROM ReceiptBillIndex WHERE BillnumberID=@GoodsBillNumberId
	END
	ELSE IF @Billtype IN (115,116,128,129)
	BEGIN 
		SELECT @intBillType=bil.BillType,@TotalMoney=adb.total,@TotalInMoney=0,
		@preferencemoney=0,@CompleteTotal=adb.CompleteTotal,
		@NTotalMoney=adb.NTotal,
		@NTotalInMoney=0,
		@Npreferencemoney=0,
		@NCompleteTotal=adb.NCompleteTotal,
		@NChargeOffTotal=adb.NChargeOffTotal
		FROM dbo.AdDebtBill adb
		INNER JOIN billindex bil ON bil.BillNumberId = adb.BillNumberId
		WHERE  adb.BillnumberID=@GoodsBillNumberId AND adb.ID=@GoodsDetailId AND bil.BillType= @Billtype
	END  
	ELSE
		SELECT @intBillType=BillType,@TotalMoney=TotalMoney,@TotalInMoney=TotalInMoney,
		@preferencemoney=preferencemoney,@CompleteTotal=CompleteTotal,
		@NTotalMoney=NTotalMoney,
		@NTotalInMoney=NTotalInMoney,
		@Npreferencemoney=Npreferencemoney,
		@NCompleteTotal=NCompleteTotal,
		@NChargeOffTotal=NChargeOffTotal
		FROM BillIndex WHERE BillnumberID=@GoodsBillNumberId  AND BillType=@Billtype
		
	IF ( (@NTotalMoney>=0 AND (@NTotalMoney-@NPreferencemoney) <= @NCompleteTotal+@NTotalInMoney+@NChargeOffTotal)
		OR (@NTotalMoney<0 AND (@NTotalMoney-@NPreferencemoney) >= @NCompleteTotal+@NTotalInMoney+@NChargeOffTotal) ) AND @intBillType NOT IN (115,116,128,129) 
	BEGIN
		IF @intBillType IN (404,405)
		BEGIN
			UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@GoodsBillNumberId
		END
		ELSE
		BEGIN
			UPDATE BillIndex SET jsStyle = '3',jsState = '2' WHERE BillNumberID=@GoodsBillNumberId
		END
	END
	ELSE IF @intBillType IN (115,116,128,129) 
	BEGIN	
		UPDATE dbo.AdDebtBill 
		SET  
			JsStyle='3',
			jsState=CASE WHEN @intBillType IN(115,116) THEN CASE WHEN NTotal>NCompleteTotal+NChargeOffTotal THEN '1' ELSE '2' END
						ELSE '2' END				
		WHERE BillNumberID=@GoodsBillNumberId AND id=@GoodsDetailId
	
		UPDATE BillIndex 
		SET jsStyle = '3',jsState = '2' 
		WHERE BillNumberID=@GoodsBillNumberId AND
		NOT EXISTS (
			SELECT 1 
			FROM  AdDebtBill 
			WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
			AND	(JsStyle<>3 or jsState<>2)
		 )
		 
		UPDATE BillIndex 
		SET jsStyle = '4',jsState = '1' 
		WHERE BillNumberID=@GoodsBillNumberId AND
		 EXISTS (
			SELECT 1 
			FROM  AdDebtBill 
			WHERE AdDebtBill.BillNumberId=BillIndex.BillNumberId
			AND	JsStyle=1 AND jsState=1 
		 )AND BillType in(115,116)
		 
		 IF NOT  EXISTS (SELECT  1 FROM (SELECT CASE WHEN (JsStyle=0 or jsState=0) THEN 0
								WHEN JsStyle=1 AND jsState=1 THEN 0
								WHEN JsStyle=1 AND jsState=2 THEN 1
								WHEN JsStyle=3 AND jsState=1 THEN 0
								WHEN JsStyle=3 AND jsState=2 THEN 0
								END as flag FROM  AdDebtBill WHERE BillNumberId=@GoodsBillNumberId) a WHERE a.flag=0)
		BEGIN 	 
			UPDATE BillIndex 
			SET jsStyle = '4',jsState = '2' 
			WHERE  BillNumberId=@GoodsBillNumberId AND BillType in(115,116)
		END 
				 
	END
	ELSE
	BEGIN
		IF @intBillType IN (404,405)
		BEGIN
			UPDATE ReceiptBillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@GoodsBillNumberId
		END
		ELSE
		BEGIN
			UPDATE BillIndex SET jsStyle = '3',jsState = '1' WHERE BillNumberID=@GoodsBillNumberId
		END
	END

	FETCH NEXT FROM Bills INTO @GoodsBillNumberId,@Billtype,@GoodsDetailId

END

IF @@error<>0 RETURN 2 ------------发生错误

CLOSE Bills	-- 关闭游标
DEALLOCATE Bills	-- 释放游标所使用的资源

DELETE A FROM CompleteTotal A 
INNER JOIN 
CompleteBrandartotal B ON A.MoneyBillId=B.MoneyBillID AND A.GoodsBillID=B.GoodsBillID AND A.BillType=B.BillType
WHERE A.CompleteTotal=0

IF not @@error<>0
RETURN 0 ------------正确返回
else
RETURN 2 ------------发生错误


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateCompleteGoodTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateCompleteGoodTotal]
GO


-- ========================================================================
-- 功能说明：		按商品结算,写如单据明细
-- 最后修改作者：	haiquan
-- 最后修改时间：	2007-04-11
-- ========================================================================
CREATE                              PROCEDURE [GP_UpdateCompleteGoodTotal]
(
	@MoneyBillNumberID int,--收/付款单据id
	@IfRe int = 0
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @Billtype INT    -- 单据类型
DECLARE @GoodsBillNumberId INT
DECLARE @Billdate datetime 

select @Billdate=getDate()

IF EXISTS (SELECT etypeid FROM Billindex   WHERE BillnumberID =@MoneyBillNumberId)
	SELECT @Billdate =billdate FROM Billindex  WHERE BillnumberID =@MoneyBillNumberId

UPDATE CompleteGoodTotal SET draft=0,BillDate=@Billdate WHERE MoneyBillID=@MoneyBillNumberId AND Draft=1    --处理按商品结算记录表

IF @@error<>0
RETURN 2

IF @IfRe = 1
BEGIN
	DELETE FROM CompleteGoodTotal WHERE MoneyBillID=@MoneyBillNumberId
	AND GoodsBillID NOT IN (
		SELECT GoodsBillID FROM CompleteTotal
		WHERE MoneyBillID=@MoneyBillNumberId AND Draft = 0 GROUP BY GoodsBillID)
	AND Draft = 0
END

DECLARE @SQL VARCHAR(1000)
DECLARE @BillTable varchar(200)
DECLARE @ReturnValue int
DECLARE @MoneyBillNumberID1 varchar(20)
SELECT @MoneyBillNumberID1=@MoneyBillNumberID

DECLARE Bills CURSOR FOR
	SELECT DISTINCT Goodsbillid,b.Billtype
	FROM CompleteGoodTotal A,BillIndex B
	WHERE A.GoodsBillid=B.BillNumberID AND A.BillType=B.BillType
	AND A.MoneyBillId=@MoneyBillNumberID
	AND A.Draft=0
	UNION ALL
	SELECT DISTINCT Goodsbillid,b.Billtype 
	FROM CompleteGoodTotal A,ReceiptBillIndex B
	WHERE A.GoodsBillid=B.BillNumberID	AND A.BillType=B.BillType						
	AND A.MoneyBillId=@MoneyBillNumberID                      
	AND A.Draft=0
	
OPEN Bills
FETCH NEXT FROM Bills INTO @GoodsBillNumberId,@Billtype

WHILE ( @@FETCH_STATUS = 0 )

BEGIN


	EXEC @ReturnValue =GP_CheckCompleteGoodTotal @GoodsBillNumberId,@Billtype

	if @ReturnValue<>0

		Return @ReturnValue


	SELECT @BillTable=
		CASE @BillType
		         WHEN 34
		         	THEN 'buybill' --采购单
		         WHEN 6 
					THEN 'BuyBackBill' --采购退货单
		         WHEN 161 
					THEN 'BuyGoodsExchangeBill'--采购换货单
		         WHEN 145 
					THEN 'CommissionBill'--受托代销结算单，代销单还要特殊处理
--以下是销售类单据
		         WHEN 11 
					THEN 'saleBill' --销售出库单
				 WHEN 12
					THEN 'PT_Combin_SaleBill'
				 WHEN 45
					THEN 'saleBackBill' --销售退货单
				 WHEN 46
					THEN 'PT_Combin_SaleBackBill'
				 WHEN 160
					THEN 'SaleGoodsExchangeBill' --销售换货单	
				 WHEN 141
					THEN 'CommissionBill' --委托代销结算单
				 WHEN 167
					THEN 'wx_Bill_GetBack'	-- 新维修 - 取件单
				 WHEN 168
					THEN 'wx_Bill_Replace'	-- 新维修 - 整机更换单
				 WHEN 170
					THEN 'wx_Bill_SendBack'	-- 新维修 - 送修返回单
					
				 WHEN 404
					THEN 'receiptbill'	--采购暂估开票
					
				 WHEN 405
					THEN 'receiptbill'  --销售暂估开票
				 ELSE '0'
		END

	IF @BillTable='0'
			RETURN 2
	
    DECLARE @exDeleted BIT= 0,		--存在删除明细
			@exSQL     NVARCHAR(MAX)=''
    SET @exSQL = N'IF Exists(SELECT 1 FROM CompleteGoodTotal A LEFT JOIN '
        + @BillTable + ' B ON A.BillId=B.ID WHERE A.MoneyBillID='
        + CAST(@MoneyBillNumberID AS VARCHAR(50)) +'AND A.BillType='+CAST(@BillType AS VARCHAR(50))+ ' AND B.ID IS NULL )
				SET @exDeleted=1'
    EXEC sp_executesql @exSQL, N'@exDeleted BIT OUT', @exDeleted OUT
    IF @exDeleted = 1
        RETURN 11

	IF @Billtype IN (404,405)
	BEGIN
		UPDATE ReceiptBill
					SET CompleteQTY=B.CompleteQTY+C.QTY,
						CompleteTotal=B.CompleteTotal+C.CompleteTotal,
						NCompleteTotal=B.NCompleteTotal+C.NCompleteTotal
					FROM ReceiptBill B,
						(SELECT SUM(A.CompleteGoodQTY) AS QTY,
							SUM(A.CompleteGoodTotal) AS CompleteTotal,
							SUM(A.NCompleteGoodTotal) AS NCompleteTotal,
							MoneyBillid,
							A.Billid from ReceiptBill  D,
							CompleteGoodTotal A
					  	 WHERE D.[id]=A.Billid
						   AND D.BillNumberid=A.Goodsbillid 
						   AND A.draft=0
						   AND D.BillNumberID=@GoodsBillNumberId
						   AND A.BillType=@BillType
						   GROUP BY A.Billid,MoneyBillid,A.BillType) C 
					WHERE B.[id]=C.Billid 
						  AND C.MoneyBillID=@MoneyBillNumberID1
	END	
	ELSE
	BEGIN
		SELECT @SQL='UPDATE '+@BillTable+' 
					SET CompleteQTY=B.CompleteQTY+ABS(C.QTY) ,
						CompleteTotal=B.CompleteTotal+ABS(C.CompleteTotal) ,
						NCompleteTotal=B.NCompleteTotal+ABS(C.NCompleteTotal) 
					FROM '+@BillTable+' B,
						(SELECT SUM(A.CompleteGoodQTY) AS QTY,
							SUM(A.CompleteGoodTotal) AS CompleteTotal,
							SUM(A.NCompleteGoodTotal) AS NCompleteTotal,
							MoneyBillid,
							A.Billid from '+@BillTable+' D,
							CompleteGoodTotal A
					  	 WHERE D.[id]=A.Billid
						   AND D.BillNumberid=A.Goodsbillid 
						   AND A.draft=0
						   AND A.BillType='+ CAST(@BillType AS VARCHAR(10))+'
						   AND D.BillNumberID='+CAST(@GoodsBillNumberId AS VARCHAR(50))+'  
						   GROUP BY A.Billid,MoneyBillid) C 
					WHERE B.[id]=C.Billid 
						  AND C.MoneyBillID='+@MoneyBillNumberID1+' '
						  
  					
	--PRINT(@sql)
	EXEC(@SQL)
	END
	-- *** 处理九种单据的结算状态 - Start ***
	DECLARE @intBillType int,
			@TotalMoney  NUMERIC(24, 10) ,
			@TotalInMoney  NUMERIC(24, 10),
			@preferencemoney  NUMERIC(24, 10) ,
			@CompleteTotal  NUMERIC(24, 10) ,
			@NTotalMoney  NUMERIC(24, 10) ,
			@NTotalInMoney  NUMERIC(24, 10),
			@Npreferencemoney  NUMERIC(24, 10) ,
			@NCompleteTotal  NUMERIC(24, 10) ,
			@NChargeOffTotal	NUMERIC(24,10)
	
	IF @Billtype IN (404,405)
	BEGIN
		SELECT @intBillType=BillType,@TotalMoney=TaxTotalMoney,@TotalInMoney=0,
		@preferencemoney=0,@CompleteTotal=CompleteTotal,
		@NTotalMoney=NTaxTotalMoney,
		@NTotalInMoney=0,
		@Npreferencemoney=0,
		@NCompleteTotal=NCompleteTotal,
		@NChargeOffTotal=NChargeOffTotal
		FROM ReceiptBillIndex WHERE BillnumberID=@GoodsBillNumberId
	END
    ELSE
    	SELECT @intBillType=BillType,@TotalMoney=TotalMoney,@TotalInMoney=TotalInMoney,
		@preferencemoney=preferencemoney,@CompleteTotal=CompleteTotal,
		@NTotalMoney=NTotalMoney,
		@NTotalInMoney=NTotalInMoney,
		@Npreferencemoney=Npreferencemoney,
		@NCompleteTotal=NCompleteTotal,
		@NChargeOffTotal=NChargeOffTotal
		FROM BillIndex WHERE BillnumberID=@GoodsBillNumberId
	
	IF @intBillType NOT IN (160,161)
	BEGIN
		
		IF(@NTotalMoney-@NPreferencemoney)=(@NCompleteTotal+@NTotalInMoney+@NChargeOffTotal)
		BEGIN
			IF @intBillType IN (404,405)
				UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@GoodsBillNumberId
			ELSE
				UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@GoodsBillNumberId
		END
		ELSE
			IF @intBillType IN (404,405)
				UPDATE ReceiptBillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@GoodsBillNumberId
			ELSE
				UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@GoodsBillNumberId
				
	END
	ELSE
	BEGIN
		DECLARE @sumComGoodQtyOut  NUMERIC(24, 10) ,@sumBillGoodQtyOut  NUMERIC(24, 10) 
		DECLARE @sumComGoodQtyIn  NUMERIC(24, 10) ,@sumBillGoodQtyIn  NUMERIC(24, 10) 
		SELECT @sumComGoodQtyOut=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
		WHERE GoodsBillID=@GoodsBillNumberId AND InOrOut = 'O' AND Draft = 0
		SELECT @sumComGoodQtyIn=ABS(ISNULL(SUM(CompleteGoodQty),0)) FROM CompleteGoodTotal
		WHERE GoodsBillID=@GoodsBillNumberId AND InOrOut = 'I' AND Draft = 0
		IF @intBillType = 160
		BEGIN
			SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
			WHERE BillNumberID=@GoodsBillNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
			SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM SaleGoodsExchangeBill
			WHERE BillNumberID=@GoodsBillNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
		END
		IF @intBillType = 161
		BEGIN
			SELECT @sumBillGoodQtyOut=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
			WHERE BillNumberID=@GoodsBillNumberId AND InOrOut = 'O' AND Qty <> 0 AND Total <> 0
			SELECT @sumBillGoodQtyIn=ISNULL(SUM(Qty),0) FROM BuyGoodsExchangeBill
			WHERE BillNumberID=@GoodsBillNumberId AND InOrOut = 'I' AND Qty <> 0 AND Total <> 0
		END
		IF (@NTotalMoney-@NPreferencemoney)=(@NCompleteTotal+@NTotalInMoney+@NChargeOffTotal) AND
			(@sumComGoodQtyOut+@sumComGoodQtyIn)=(@sumBillGoodQtyOut+@sumBillGoodQtyIn)
			UPDATE BillIndex SET jsStyle = '2',jsState = '2' WHERE BillNumberID=@GoodsBillNumberId
		ELSE
			UPDATE BillIndex SET jsStyle = '2',jsState = '1' WHERE BillNumberID=@GoodsBillNumberId
	END
	-- *** 处理九种单据的结算状态 - End ***

	FETCH NEXT FROM Bills INTO @GoodsBillNumberId,@Billtype

END

IF @@error<>0 RETURN 2 ------------发生错误

CLOSE Bills	-- 关闭游标
DEALLOCATE Bills	-- 释放游标所使用的资源

--DELETE FROM CompleteGoodTotal WHERE MoneyBillId=@MoneyBillNumberId AND GoodsBillID NOT IN (select GoodsBillID from Completetotal WHERE MoneyBillID=@MoneyBillNumberId) and draft=0

DELETE A FROM CompleteTotal A 
INNER JOIN 
CompleteGoodtotal B ON A.MoneyBillId=B.MoneyBillID AND A.GoodsBillID=B.GoodsBillID AND A.BillType=B.BillType
WHERE A.CompleteTotal=0 AND B.CompleteGoodQTY=0

IF not @@error<>0
  RETURN 0 ------------正确返回
else
 RETURN 2 ------------发生错误


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateCouponBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateCouponBillIndex]
GO

--**********************************************

--**********************************************
CREATE  PROCEDURE [Gp_UpdateCouponBillIndex]
(
	@BillNumberId  			[numeric](10,0),   
	@BillDate				DATETIME,
	@BillCode				varchar(200),
	@BillType				INT,
	@FromType				INT,
	@STypeID				varchar(50),
	@DTypeID				varchar(50),
	@ETypeID				varchar(50),
	@OutKTypeID				varchar(50),
	@InKTypeId				varchar(50),
	@CID					INT,
	@Rate					numeric(24,10),
	@TotalQty				numeric(24,10),
	@TotalMoney				numeric(24,10),
	@NTotalMoney			numeric(24,10),
	@CompleteTotal			numeric(24,10),
	@NCompleteTotal			numeric(24,10),
	@TotalInMoney			numeric(24,10),
	@NTotalInMoney			numeric(24,10),
	@PosID					INT,
	@PosBillCode			VARCHAR(200)	,	
	@IfMulAccount			INT,
	@ATypeID				varchar(50),
	@BTypeID				varchar(50),
	@DealBTypeID			varchar(50),
	@Comment				varchar(255),
	@Explain				varchar(255),
	--@Poster				varchar(50),
	--@PostTime				DATETIME,
	--@MakeTime				DATETIME,
	@Maker					varchar(50),
	@Checker				varchar(50),
	@CheckeTime				DATETIME,
	@IfAudit				INT,
	@Draft					INT,
	@IfCheck				VARCHAR(1),
	@RedWord				INT,
	@IsIni					INT,
	--@IfYearBill			INT,
	@RedReason				varchar(255),
	@ATypeID1				varchar(50),
	@ATID					int,
	@TallyId				varchar(50),
	@ChargeOffTotal			numeric(24,10),
	@NChargeOffTotal		numeric(24,10),
	@checke					varchar(50),
	--@JsState				numeric(24,10)
	@updateE				VARCHAR(50)	,		--修改人
	@PreferenceMoney	NUMERIC(24, 10),  --抹零金额
	@NPreferenceMoney	NUMERIC(24, 10)  --抹零金额

	
)
--@encode$--
AS 
SET NOCOUNT ON 

DECLARE @ID		INT,
		@ReCv	INT
		

IF  @isini<>1
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Coupon_BillIndex WHERE  draft=0 AND ifcheck='t' AND [BillNumberId]  = @BillNumberId
			  UNION ALL
			  SELECT TOP 1 1 FROM dbo.ListTable WHERE BillNumberId=@BillNumberId AND BillType=@BillType
			  UNION ALL
			  SELECT TOP 1 1 FROM dbo.Coupon_CodeInOut WHERE BillNumberId=@BillNumberId AND BillType=@BillType)

		RETURN -1 
END

IF NOT EXISTS(SELECT TOP 1 1 FROM Coupon_BillIndex WHERE BillNumberID = @BillNumberID AND BillType = @BillType)
	RETURN -7

EXEC @ReCv = Gp_ChkSdAllType
IF (@ReCv = 0) RETURN -7

DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE STypeID=@STypeID AND MonthNo='本期'


IF @isini=1
BEGIN
	DECLARE @iniBegindate DATETIME  --取会计期间开始时间

    SELECT @iniBegindate=fBegin FROM dbo.Ac_Period 
    WHERE FYear IN (SELECT subvalue FROM dbo.sysdata WHERE subname ='fyear' )
		AND FPeriod IN (SELECT subvalue FROM dbo.sysdata WHERE SubName='fmonth')
	IF @billdate > @iniBegindate
	RETURN -8
END
IF @BillDate<@BeginDate AND @isini=0 AND @BillType<>310
BEGIN  
	RETURN -2
END

DECLARE @CurDate DATETIME,@IsOrNotPassOneDay int
---根据配置检查过帐日期是否当前日期  
IF(@isini=0)
BEGIN		
	SELECT @CurDate=GETDATE()
	SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
	IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
	BEGIN
		
		RETURN -3
	END

	
END
---根据配置检查过帐日期是否当前日期  完毕

IF(@isini=1)  --期初单据计算completetotal
BEGIN
	DECLARE @currate  NUMERIC(24, 10) ,
			@curbasistype INT,
			@curCompleteTotal  NUMERIC(24, 10) ,
            @curChargeOffTotal NUMERIC(24, 10) 
	SELECT @currate = rate,@curbasistype = basistype FROM Ac_Currency WHERE CId=@cid
	IF(@curbasistype = 1)
	BEGIN
          SET @curCompleteTotal = @ncompletetotal / @currate
          SET @curChargeOffTotal= @nchargeofftotal/ @currate
    END
	ELSE
    BEGIN
          SET @curCompleteTotal = @ncompletetotal * @currate
          SET @curChargeOffTotal= @nchargeofftotal* @currate
    END	
END

UPDATE [dbo].Coupon_BillIndex 
SET		BillDate=@BillDate,
		BillCode=@BillCode,
		BillType=@BillType,
		FromType= CASE WHEN @BillType IN (425,426) THEN  -1 ELSE  @FromType END,
		STypeID=@STypeID,
		DTypeID=@DTypeID,
		ETypeID=@ETypeID,
		OutKTypeID=@OutKTypeID,
		InKTypeId=@InKTypeId,
		CID=@CID,
		Rate=dbo.F_RoundExchangeRate(@Rate),
		TotalQty=dbo.F_RoundQty(ISNULL(@TotalQty,0)),
		TotalMoney=dbo.F_RoundTotal(ISNULL(@TotalMoney,0)),
		NTotalMoney=dbo.F_RoundTotal(ISNULL(@NTotalMoney,0)),
		CompleteTotal=(CASE WHEN @isini=1 THEN dbo.F_RoundTotal(ISNULL(@curCompleteTotal,0)) ELSE dbo.F_RoundTotal(ISNULL(@completetotal,0)) END),
		NCompleteTotal=dbo.F_RoundTotal(ISNULL(@NCompleteTotal,0)),
		TotalInMoney=dbo.F_RoundTotal(ISNULL(@TotalInMoney,0)),
		NTotalInMoney=dbo.F_RoundTotal(ISNULL(@NTotalInMoney,0)),
		IfMulAccount=@IfMulAccount,
		ATypeID=@ATypeID,
		BTypeID=@BTypeID,
		DealBTypeID=@DealBTypeID,
		Comment=@Comment,
		Explain=@Explain,
		--Poster=@Poster,
		--PostTime=@PostTime,
		--MakeTime=@MakeTime,
		--Maker=@Maker,
		Checker='',
		CheckeTime=@CheckeTime,
		IfAudit=@IfAudit,
		Draft=@Draft,
		IfCheck=@IfCheck,
		RedWord=@RedWord,
		IsIni=@IsIni,
		--IfYearBill=@IfYearBill,
		RedReason=@RedReason,
		ATypeID1=@ATypeID1,
		ATID=@ATID,
		TallyId=@TallyId,
		ChargeOffTotal=(CASE WHEN @isini=1 THEN dbo.F_RoundTotal(ISNULL(@curChargeOffTotal,0) )ELSE dbo.F_RoundTotal(ISNULL(@chargeofftotal,0)) END) ,
		NChargeOffTotal=ISNULL(@NChargeOffTotal,0),
		--JsState=@JsState
		--Checke=@checke,
		[LastUpdateTime]=GETDATE(),
		updateE = @updateE,
		PreferenceMoney=dbo.F_RoundTotal(ISNULL(@NPreferenceMoney,0)),
		NPreferenceMoney=dbo.F_RoundTotal(ISNULL(@NPreferenceMoney,0))
WHERE	[BillNumberId]  = @BillNumberId

--PRINT @@rowCount
IF @@rowcount =0  OR @@error<>0
--RAISERROR('更新数据表发生错误！',16,1)
	RETURN -5
---- 删除单据明细
--IF @BillType=423
--	BEGIN
--		DELETE FROM Coupon_InBill WHERE BILLNUMBERID=@BillNumberID
--	END
--ELSE IF @BillType=424
--	BEGIN
--		DELETE FROM Coupon_OutBill WHERE BILLNUMBERID=@BillNumberID
--		DELETE FROM Coupon_OutBill_Ptype WHERE BILLNUMBERID=@BillNumberID
--	END
--ELSE IF @BillType=425
--	BEGIN
--		DELETE FROM Coupon_AllotBill WHERE BILLNUMBERID=@BillNumberID
--	END 
--IF @BillType=426
--	BEGIN
--		DELETE FROM Coupon_BackBill WHERE BILLNUMBERID=@BillNumberID
--	END 		
DELETE BillMulAccount WHERE BillNumberId=@BillNumberId AND BILLTYPE =@BillType AND (PayType IS NULL OR PayType = 0)  --单账户也会写这张表

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateCouponPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateCouponPtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	杨鑫
	Date	:	2017/11/13
	Description	: 更新优惠券适用分支机构信息
*/
CREATE PROCEDURE Gp_UpdateCouponPtype
(
	@ptypetable Type_CouponPtypeInfo	READONLY,
	@couponid       INT,
	@isexchange		INT  
)
--@encode$--
AS
SET NOCOUNT ON 

--清除优惠券商品数据
DELETE FROM  coupon_ApplyPtype WHERE CouponId=@couponid
------------插入数据
INSERT INTO dbo.coupon_ApplyPtype(CouponId, PtypeId,IsExchangePtype,Price,Qty,Total)
SELECT  @couponid,typeid,@isexchange,Price,Qty,Total FROM @ptypetable 
----------更新数据
UPDATE  dbo.coupon_ApplyPtype
SET     dbo.coupon_ApplyPtype.PtypeId=dbo.ptype.TypeId
FROM    dbo.coupon_ApplyPtype 
        INNER JOIN dbo.ptype  ON coupon_ApplyPtype.PtypeId = ptype.TypeId
WHERE	CouponId=@couponid


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateCouponStype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateCouponStype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	杨鑫
	Date	:	2017/11/13
	Description	: 更新优惠券适用分支机构信息
*/
CREATE PROCEDURE Gp_UpdateCouponStype
(
	@stypetable Type_CouponStypeInfo	READONLY,
	@couponid       INT 
)
--@encode$--
AS
SET NOCOUNT ON 

--清除优惠券适用分支机构数据
DELETE FROM  coupon_ApplyStype WHERE CouponId=@couponid
------------插入数据
INSERT INTO dbo.coupon_ApplyStype(CouponId, StypeId)
SELECT  @couponid,typeid FROM @stypetable 
UPDATE  dbo.coupon_ApplyStype
SET     dbo.Coupon_ApplyStype.StypeId=dbo.SType.TypeId
FROM    dbo.coupon_ApplyStype 
        INNER JOIN dbo.SType  ON coupon_ApplyStype.StypeId = SType.TypeId
WHERE   CouponId=@couponid


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateCRMB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateCRMB]
GO










CREATE               PROCEDURE [Gp_UpdateCRMB]
(
 @typeId  [varchar](50),
 @usercode       [varchar](26),
  @FullName  [varchar](66),
 @Name    [varchar](30),
 @Area  [Varchar](30),
 @TelAndAddress  [varchar](66),
 @PostCode  [char](10),
 @Person  [char](20),
 @TaxNumber  [char](20),
 @Account  [char](66),
 @ARTotal00   NUMERIC(24, 10) ,
 @APTotal00   NUMERIC(24, 10) ,
 @Comment  [varchar](256),
 @Client [Bit]=1,
 @ARLimit  NUMERIC(24, 10) ,
 @ARLimitTime  NUMERIC(24, 10)  = 99999,
 @PaymentLTime  NUMERIC(24, 10)  = 99999,
 @Tel1 varchar(50),
 @Tel2 varchar(50),
 @Tel3 varchar(50),
 @WWW varchar(50),
 @Email varchar(50),
 @Fax varchar(50),
 @Bank varchar(50),
 @BankName varchar(50),
@LinkManId1 varchar(50),
@LinkMan1 varchar(50),
@LinkSex1 bit,
@LinkBirthDay1 datetime,
@LinkJob1 varchar(50),
@LinkCall1 Varchar(50),
@LinkTel1 varchar(50),
@LinkMobile1 varchar(50),
@LinkEMail1 varchar(50),
@LinkPost1 varchar(50),
@LinkAddress1 varchar(50),
@LinkComment1 varchar(50),
@LinkManId2 varchar(50),
@LinkMan2 varchar(50),
@LinkSex2 bit,
@LinkBirthDay2 datetime,
@LinkJob2 varchar(50),
@LinkCall2 Varchar(50),
@LinkTel2 varchar(50),
@LinkMobile2 varchar(50),
@LinkEMail2 varchar(50),
@LinkPost2 varchar(50),
@LinkAddress2 varchar(50),
@LinkComment2 varchar(50),
@CreateDate varchar(10),
@SaleZeKou  NUMERIC(24, 10) ,
@BuyZeKou  NUMERIC(24, 10) ,
@PyCode   varchar(200),
@Price    varchar(50),
@AreaTypeID varchar(50)

)
--@encode$--
AS 
SET NOCOUNT ON 

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName
SELECT  @PyCode,@returnPym

if(@PyCode='')
	SET @PyCode=@returnPym

DECLARE @Ar00Temp  NUMERIC(24, 10) 
DECLARE @Ap00Temp  NUMERIC(24, 10) 
SET @Ar00Temp =0
SET @Ap00Temp =0

    -- 已开帐
 UPDATE [dbo].[CRM_btype] 
 SET      [usercode]  =@usercode,
   [FullName]  = @FullName,
   [Name]  = @Name,
   [Area]  =@Area, 
   [TelAndAddress]  = @TelAndAddress,
   [PostCode]  = @PostCode,
   [Person]  = @Person,
   [TaxNumber]  = @TaxNumber,
   [BankAndAcount] = @Account,
   [Comment]  = @Comment,
 --  [ARTotal00]  = @ARTotal00,
 --  [APTotal00]  = @APTotal00,
   [Client]  = @Client,
   [ARLimit]  = dbo.F_RoundTotal(@ARLimit),
   [ARLimitTime] = @ARLimitTime,
   [PaymentLTime]= @PaymentLTime,
   [Tel1]=@Tel1,
   [Tel2]=@Tel2,
   [Tel3]=@Tel3,
   [WWW]=@WWW,
   [Email]= @Email,
   [Fax]= @Fax,
   [Bank]= @Bank,
   [BankName]= @BankName,
 [LinkManId1]=@LinkManId1,
 [LinkMan1]=@LinkMan1,
 [LinkSex1]=@LinkSex1,
 [LinkBirthDay1]=@LinkBirthDay1,
 [LinkJob1]=@LinkJob1,
 [LinkCall1]=@LinkCall1,
 [LinkTel1]=@LinkTel1,
 [LinkMobile1]=@LinkMobile1,
 [LinkEMail1]=@LinkEMail1,
 [LinkPost1]=@LinkPost1,
 [LinkAddress1]=@LinkAddress1,
 [LinkComment1]=@LinkComment1,
 [LinkManId2]=@LinkManId2,
 [LinkMan2]=@LinkMan2,
 [LinkSex2]=@LinkSex2,
 [LinkBirthDay2]=@LinkBirthDay2,
 [LinkJob2 ]=@LinkJob2 ,
 [LinkCall2]=@LinkCall2,
 [LinkTel2]=@LinkTel2,
 [LinkMobile2]=@LinkMobile2,
 [LinkEMail2]=@LinkEMail2,
 [LinkPost2]=@LinkPost2,
 [LinkAddress2]=@LinkAddress2,
 [LinkComment2]=@LinkComment2,
 [CreateDate]=@CreateDate,
 [SaleZeKou] =dbo.F_RoundDiscount(@SaleZeKou),
 [BuyZeKou]=dbo.F_RoundDiscount(@BuyZeKou),
 [PyCode] =@PyCode,
 [Price] = dbo.F_RoundPrice(@Price),
 [AreaTypeID] =@AreaTypeID
 WHERE 
  ( [id]  = @typeId)
 
 UPDATE CRM_LinkMan SET Crm_BtypeId = null WHERE Crm_BtypeId = @typeId

 UPDATE CRM_LinkMan SET Crm_BtypeId = @typeId WHERE [id] = @LinkManId1
 UPDATE CRM_LinkMan SET Crm_BtypeId = @typeId WHERE [id] = @LinkManId2

 









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateCX_SaleByHand]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateCX_SaleByHand]
GO
/****** Object:  StoredProcedure [dbo].[GP_UpdateCX_SaleByHand]    Script Date: 07/19/2011 14:47:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


--**********************************************
--功能：保存手工促销单据表体数据（新增ADD／修改EDIT/审核AUDIT）
--作者：罗锐
--日期：2010-03-08
--**********************************************
create procedure [dbo].[GP_UpdateCX_SaleByHand]
(
	@OperateMode varchar(40),
	@BillNumberId decimal(9),
	@SaleType varchar(1),
	@MoneyTicket varchar(1),
	@GoodsPro varchar(1),
	@ChoosePro varchar(100),
	@TotalMoney varchar(20),
	@TotalQty varchar(20),
	@Discount varchar(10),
	@RebateMoney varchar(20),
	@MoneyAdd varchar(1)
)
--@encode$--
AS
--如果选择了属性但没有选择属性值，那么将属性值默认设置为0
IF(@GoodsPro<>'' AND @ChoosePro = '') SELECT @ChoosePro = '0'

--新增表体数据Start--------------------------------
if @OperateMode='ADD'
begin
insert into CX_SaleByHand 
(
	CX_SaleByHand.BillNumberId,
	CX_SaleByHand.SaleType,
	CX_SaleByHand.MoneyTicket,
	CX_SaleByHand.GoodsPro,	
	CX_SaleByHand.ChoosePro,
	CX_SaleByHand.TotalMoney,
	CX_SaleByHand.TotalQty,
	CX_SaleByHand.Discount,
	CX_SaleByHand.RebateMoney,
	CX_SaleByHand.MoneyAdd
)
values
(
	@BillNumberId,
	@SaleType,
	@MoneyTicket,
	@GoodsPro,
	@ChoosePro,
	@TotalMoney,
	@TotalQty,
	@Discount,
	@RebateMoney,
	@MoneyAdd
)
if @@rowcount =0  or @@error<>0
	begin
		return -1
	end
else
	begin
		--返回单据ID
		return @BillNumberId
	end
end
--新增表体数据End----------------------------------
--修改/审核表体数据Start--------------------------------
if @OperateMode='EDIT' or @OperateMode='AUDIT'
begin
update CX_SaleByHand
set 
	CX_SaleByHand.SaleType = @SaleType, 
	CX_SaleByHand.MoneyTicket = @MoneyTicket, 
	CX_SaleByHand.GoodsPro = @GoodsPro, 
	CX_SaleByHand.ChoosePro = @ChoosePro, 
	CX_SaleByHand.TotalMoney = @TotalMoney, 
	CX_SaleByHand.TotalQty = @TotalQty, 
	CX_SaleByHand.Discount = @Discount, 
	CX_SaleByHand.RebateMoney = @RebateMoney, 
	CX_SaleByHand.MoneyAdd = @MoneyAdd
where 
	CX_SaleByHand.BillNumberId = @BillNumberId
if @@rowcount =0  or @@error<>0
	begin
		return -1
	end
else
	begin
		--返回单据ID
		return @BillNumberId
	end
end
--修改/审核表体数据End----------------------------------


GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateCX_SalePlanIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateCX_SalePlanIndex]
GO

/****** Object:  StoredProcedure [dbo].[GP_UpdateCX_SalePlanIndex]    Script Date: 07/19/2011 14:49:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


--**********************************************
--功能：保存促销单据表头（新增ADD／修改EDIT/审核AUDIT）
--作者：罗锐
--日期：2010-03-01
--**********************************************

create procedure [dbo].[GP_UpdateCX_SalePlanIndex]
(
	@OperateMode varchar(40),
	@BillNumberId numeric(9),
	@BillType varchar(1),
	@BillName varchar(40),
	@BillCode VARCHAR(50),
	@BillDateTime datetime,
	@StartDate datetime,
	@EndDate datetime,
	@EtypeId VARCHAR(50),
	@JTypeID VARCHAR(50),
	@BillStatus varchar(1),
	@DateTimeType varchar(1),
	@MonthDay varchar(2),
	@MonthWeek varchar(1),
	@MonthWeekDay varchar(1),
	@WeekDays varchar(7),
	@StartTime varchar(8),
	@EndTime varchar(8),
	@SalePrice VARCHAR(50),
	@SaleType varchar(1),
	@TotalMoney varchar(18),
	@Remark varchar(100),
	@Checke VARCHAR(50),
	@Breake VARCHAR(50),
	@CheckeDateTime varchar(20),
	@BreakeDateTime varchar(20),
	@PermitsStockID varchar(8000)
)
--@encode$--
as

Declare @IsHQ varchar(1)	
Declare @P VARCHAR(50)
SET @IsHQ='0'
SET @P=''

if left(@EtypeId,5)='00003'
begin
	set @IsHQ='1'
end

--新增表头数据Start--------------------------------
if @OperateMode='ADD'
begin
--检查是否有相同促销名称
if exists(select * from CX_SalePlanIndex where BillName=@BillName)
	return -2
--检查是否有相同单据编号
if exists(select * from CX_SalePlanIndex where BillCode=@BillCode)
	return -3
insert into CX_SalePlanIndex 
(
	CX_SalePlanIndex.BillType,
	CX_SalePlanIndex.BillName,
	CX_SalePlanIndex.BillCode,
	CX_SalePlanIndex.BillDateTime,
	CX_SalePlanIndex.StartDate,
	CX_SalePlanIndex.EndDate,
	CX_SalePlanIndex.EtypeId,
	CX_SalePlanIndex.JTypeID,
	CX_SalePlanIndex.BillStatus,
	CX_SalePlanIndex.DateTimeType,
	CX_SalePlanIndex.MonthDay,
	CX_SalePlanIndex.MonthWeek,
	CX_SalePlanIndex.MonthWeekDay,
	CX_SalePlanIndex.WeekDays,
	CX_SalePlanIndex.StartTime,
	CX_SalePlanIndex.EndTime,
	CX_SalePlanIndex.SalePrice,
	CX_SalePlanIndex.SaleType,
	CX_SalePlanIndex.TotalMoney,
	CX_SalePlanIndex.Remark,
	CX_SalePlanIndex.Checke,
	CX_SalePlanIndex.Breake,
	CX_SalePlanIndex.CheckeDateTime,
	CX_SalePlanIndex.BreakeDateTime
)
values
(
	@BillType,
	@BillName,
	@BillCode,
	@BillDateTime,
	@StartDate,
	@EndDate,
	@EtypeId,
	CASE @JTypeID WHEN '00000' THEN Null ELSE @JTypeID END,
	@BillStatus,
	@DateTimeType,
	@MonthDay,
	@MonthWeek,
	@MonthWeekDay,
	@WeekDays,
	@StartTime,
	@EndTime,
	@SalePrice,
	@SaleType,
	@TotalMoney,
	@Remark,
	@Checke,
	@Breake,
	@CheckeDateTime,
	@BreakeDateTime
)
if @@rowcount =0  or @@error<>0
	begin
		return -1
	end
else
	begin
		SET @BillNumberId=SCOPE_IDENTITY()
		SET @P=''

		--先删除促销适用仓库表中的相关信息
		exec('Delete from CX_SaleStocksArea where BillNumberId ='  + @BillNumberId)
		if @@error<>0
		Begin
			return -1
		End		

		--拆分仓库ID集并添加到促销适用仓库表中
		WHILE	CHARINDEX(',',@PermitsStockID)>0
		BEGIN
		 	
		 	SET @P=LEFT(@PermitsStockID,CHARINDEX(',',@PermitsStockID)-1)
		 	SET @P=''+@P+''
		  	INSERT INTO CX_SaleStocksArea values(@BillNumberId,@P,@IsHQ)
		 	IF @@error!=0 	
			Begin
				return -1
			End			
		 	SET @PermitsStockID=SUBSTRING(@PermitsStockID,CHARINDEX(',',@PermitsStockID)+1,LEN(@PermitsStockID))
		END
		
		--返回单据ID
		return @BillNumberId
	end
end
--新增表头数据End----------------------------------

--修改/审核表头数据Start--------------------------------
if @OperateMode='EDIT' or @OperateMode='AUDIT'
begin
--检查是否有其他ID号相同促销名称
if exists(select * from CX_SalePlanIndex where BillNumberId<>@BillNumberId and BillName=@BillName)
	return -2
--检查是否有其他ID号相同单据编号
if exists(select * from CX_SalePlanIndex where BillNumberId<>@BillNumberId and BillCode=@BillCode)
	return -3
update CX_SalePlanIndex
set 
	CX_SalePlanIndex.BillType = @BillType, 
	CX_SalePlanIndex.BillName = @BillName, 
	CX_SalePlanIndex.BillCode = @BillCode, 
	CX_SalePlanIndex.BillDateTime = @BillDateTime, 
	CX_SalePlanIndex.StartDate = @StartDate, 
	CX_SalePlanIndex.EndDate = @EndDate, 
	CX_SalePlanIndex.EtypeId = @EtypeId,
	CX_SalePlanIndex.JTypeID = CASE @JTypeID WHEN '' THEN Null ELSE @JTypeID END,
	CX_SalePlanIndex.BillStatus = @BillStatus, 
	CX_SalePlanIndex.DateTimeType = @DateTimeType, 
	CX_SalePlanIndex.MonthDay = @MonthDay, 
	CX_SalePlanIndex.MonthWeek = @MonthWeek, 
	CX_SalePlanIndex.MonthWeekDay = @MonthWeekDay, 
	CX_SalePlanIndex.WeekDays = @WeekDays, 
	CX_SalePlanIndex.StartTime = @StartTime,
	CX_SalePlanIndex.EndTime = @EndTime, 
	CX_SalePlanIndex.SalePrice = @SalePrice, 
	CX_SalePlanIndex.SaleType = @SaleType, 
	CX_SalePlanIndex.TotalMoney = @TotalMoney, 
	CX_SalePlanIndex.Remark = @Remark, 
	CX_SalePlanIndex.Checke = @Checke, 
	CX_SalePlanIndex.Breake = @Breake,
	CX_SalePlanIndex.CheckeDateTime = @CheckeDateTime,	
	CX_SalePlanIndex.BreakeDateTime = @BreakeDateTime
where 
	CX_SalePlanIndex.BillNumberId = @BillNumberId
if @@error<>0
	begin
		return -1
	end
else
	begin
		SET @P=''

		--先删除促销适用仓库表中的相关信息
		exec('Delete from CX_SaleStocksArea where BillNumberId ='  + @BillNumberId)
		if @@error<>0
		Begin
			return -1
		End		

		--拆分仓库ID集并添加到促销适用仓库表中
		WHILE	CHARINDEX(',',@PermitsStockID)>0
		BEGIN
		 	
		 	SET @P=LEFT(@PermitsStockID,CHARINDEX(',',@PermitsStockID)-1)
		 	SET @P=''+@P+''
		  	INSERT INTO CX_SaleStocksArea values(@BillNumberId,@P,@IsHQ)
		 	IF @@error<>0
			Begin
				return -1
			End			
		 	SET @PermitsStockID=SUBSTRING(@PermitsStockID,CHARINDEX(',',@PermitsStockID)+1,LEN(@PermitsStockID))
		END
		
		--返回单据ID
		return @BillNumberId
	end
end
--修改/审核表头数据End----------------------------------

GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateD]
GO







CREATE        PROCEDURE [Gp_UpdateD]
(
 @TypeId  [varchar](50),
 @UserCode  [varchar](100),
 @FullName  [varchar](100),
 @Name   [varchar](100),
 @Comment  [varchar](100),
@LinkMan varchar(50),
@Tel varchar(50),
@FAX varchar(50),
@PyCode varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON 
if exists(select usercode from DEPARTMENT where (usercode=@usercode  or fullname=@fullname) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '分支机构已存在'+@etypeid_1
 return -307
end
if exists(select usercode from DEPARTMENT where (usercode=@fullname  or fullname=@usercode) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '分支机构已存在'+@etypeid_1
 return -307
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName
IF @PyCode <>'' 
SET @returnPym=@PyCode

UPDATE [dbo].[DEPARTMENT] 
SET  [FullName]  = @FullName,
  [Name]  = @name,
  [UserCode]  = @UserCode,
  [Comment]  = @Comment ,
[LinkMan]=@LinkMan,
[Tel]=@Tel,
[Fax]=@FAX,
[PyCode] =@returnPym
WHERE 
 ( [typeId]  = @typeId )

UPDATE Employee SET DepartMent=@FullName where DtypeID=@typeId


--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Department
UPDATE Department SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateDetailsBillReconciliation]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_UpdateDetailsBillReconciliation]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：修改明细表对账标志	
--			销售类统计表：零售单、零售退货单、销售出库单、销售退货单、销售换货单、委托代销结算单、销售发货开票、组合品销售出库单、组合品销售退货单；
--			采购类统计表：采购入库单、采购退货单、采购换货单、受托代销结算单、采购暂估开票、
-- 时间：	2013-01-30
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [Gp_UpdateDetailsBillReconciliation]
(
	@BillType		INT,--单据类型
	@BillnumberId	INT,--单据ID
	@Id				INT,--明细ID,
	@Flag			INT=0--具体单据明细对账  1：整张单据对账
)
AS
SET NOCOUNT ON

IF(@Id<1)
	SET @Flag=1
	
DECLARE @Reconciliation VARCHAR(2)='T'--对账标志
IF(@Flag=0)
	BEGIN
		--305	零售单	1         	销售类	102	retailbill	Billindex
		IF(@BillType=305)
			BEGIN
			
				UPDATE retailBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM retailBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'	
			END
		--215	零售退货单	1         	销售类	103	RetailBackBill	Billindex
		ELSE IF(@BillType=215)
			BEGIN
			
				UPDATE RetailBackBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM RetailBackBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'	
			END
		--11	销售出库单	1         	销售类	105	salebill	BillIndex
		ELSE IF(@BillType=11)
			BEGIN
			
				UPDATE SaleBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM SaleBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--45	销售退货单	1         	销售类	106	salebackbill	BillIndex
		ELSE IF(@BillType=45)
			BEGIN
			
				UPDATE saleBackBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM saleBackBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--160	销售换货单	1         	销售类	107	salegoodsexchangebill	BillIndex
		ELSE IF(@BillType=160)
			BEGIN
			
				UPDATE SaleGoodsExchangeBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM SaleGoodsExchangeBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--141	委托代销结算单	1         	销售类	112	commissionbill	BillIndex
		ELSE IF(@BillType=141)
			BEGIN
			
				UPDATE CommissionBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM CommissionBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--12	组合品销售出库单	1         	销售类	114	PT_Combin_SaleBill	BillIndex
		ELSE IF(@BillType=12)
			BEGIN
			
				UPDATE PT_Combin_SaleBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM PT_Combin_SaleBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--46	组合品销售退货单	1         	销售类	115	PT_Combin_SaleBackBill	BillIndex
		ELSE IF(@BillType=46)
			BEGIN
			
				UPDATE PT_Combin_SaleBackBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM PT_Combin_SaleBackBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--34	采购入库单	2         	采购类	204	buybill	BillIndex
		ELSE IF(@BillType=34)
			BEGIN
			
				UPDATE BuyBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM BuyBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--6	采购退货单	2         	采购类	205	buybackbill	BillIndex
		ELSE IF(@BillType=6)
			BEGIN
			
				UPDATE BuyBackBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM BuyBackBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--161	采购换货单	2         	采购类	206	buygoodsexchangebill	BillIndex
		ELSE IF(@BillType=161)
			BEGIN
			
				UPDATE BuyGoodsExchangeBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM BuyGoodsExchangeBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--145	受托代销结算单	2         	采购类	211	commissionbill	BillIndex
		ELSE IF(@BillType=145)
			BEGIN
			
				UPDATE CommissionBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM CommissionBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--404	采购暂估开票	5         	暂估类	954	ReceiptBill	ReceiptBillIndex
		ELSE IF(@BillType=404)
			BEGIN
			
				UPDATE ReceiptBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM ReceiptBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--400	暂估入库单	2         	暂估类	950	AppraisalBill	BillIndex
		ELSE IF(@BillType=400)
			BEGIN
			
				UPDATE AppraisalBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM AppraisalBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END	
		--401	暂估退货单	2         	暂估类	951	AppraisalBackBill	BillIndex
		ELSE IF(@BillType=401)
			BEGIN
			
				UPDATE AppraisalBackBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM AppraisalBackBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END	
		--405	销售发货开票	5         	暂估类	955	ReceiptBill	ReceiptBillIndex
		ELSE IF(@BillType=405)
			BEGIN
			
				UPDATE ReceiptBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM ReceiptBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--139	赠送单	1         	销售类	108	givebill	BillIndex
		ELSE IF(@BillType=139)
			BEGIN
			
				UPDATE GiveBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM GiveBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		--126	获赠单	2         	采购类	207	givemebill	BillIndex
		ELSE IF(@BillType=126)
			BEGIN
			
				UPDATE GivemeBill SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id
				
				SELECT TOP 1 @Reconciliation=Reconciliation FROM GivemeBill WHERE BillNumberId=@BillnumberId AND Reconciliation='F'
			END
		ELSE
			BEGIN
				UPDATE BillIndex SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId
			END
			
		--修改主表明细
		IF(@BillType IN(305,215,11,45,160,141,12,46,34,6,161,145,139,126,400,401))
			BEGIN
				--修改出入库表明细	
				UPDATE InOutstocktable SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId AND ID=@Id AND BillType=@BillType

				UPDATE BillIndex SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId AND BillType=@BillType
			END
		ELSE IF(@BillType IN(404,405))
			BEGIN
			
				UPDATE ReceiptBillIndex SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId AND BillType=@BillType
			END			
	END
ELSE 
	BEGIN
		--修改主表明细
		IF(@BillType IN(305,215,11,45,160,141,12,46,34,6,161,145,139,126,400,401))
			BEGIN

				UPDATE BillIndex 
				SET 
					Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END,
					@Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END 
				WHERE 
					BillNumberId=@BillnumberId 
					AND BillType=@BillType
				
				--修改出入库表明细	
				UPDATE InOutstocktable SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId AND BillType=@BillType
				
			END
		ELSE IF(@BillType IN(404,405))
			BEGIN
			
				UPDATE ReceiptBillIndex 
				SET 
					Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END,
					@Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END 
				WHERE BillNumberId=@BillnumberId AND BillType=@BillType
			END	
		ELSE 
			BEGIN
			
				UPDATE BillIndex SET Reconciliation=CASE WHEN Reconciliation='T' THEN 'F' ELSE 'T' END WHERE BillNumberId=@BillnumberId
				
			END		
	
		--305	零售单	1         	销售类	102	retailbill	Billindex
		IF(@BillType=305)
			BEGIN
				UPDATE retailBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--215	零售退货单	1         	销售类	103	RetailBackBill	Billindex
		ELSE IF(@BillType=215)
			BEGIN
				UPDATE RetailBackBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--11	销售出库单	1         	销售类	105	salebill	BillIndex
		ELSE IF(@BillType=11)
			BEGIN
				UPDATE SaleBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId	
			END
		--45	销售退货单	1         	销售类	106	salebackbill	BillIndex
		ELSE IF(@BillType=45)
			BEGIN
				UPDATE saleBackBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId	
			END
		--160	销售换货单	1         	销售类	107	salegoodsexchangebill	BillIndex
		ELSE IF(@BillType=160)
			BEGIN
				UPDATE SaleGoodsExchangeBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--141	委托代销结算单	1         	销售类	112	commissionbill	BillIndex
		ELSE IF(@BillType=141)
			BEGIN
				UPDATE CommissionBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--12	组合品销售出库单	1         	销售类	114	PT_Combin_SaleBill	BillIndex
		ELSE IF(@BillType=12)
			BEGIN
				UPDATE PT_Combin_SaleBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--46	组合品销售退货单	1         	销售类	115	PT_Combin_SaleBackBill	BillIndex
		ELSE IF(@BillType=46)
			BEGIN
				UPDATE PT_Combin_SaleBackBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--34	采购入库单	2         	采购类	204	buybill	BillIndex
		ELSE IF(@BillType=34)
			BEGIN
				UPDATE BuyBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--6	采购退货单	2         	采购类	205	buybackbill	BillIndex
		ELSE IF(@BillType=6)
			BEGIN
				UPDATE BuyBackBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--161	采购换货单	2         	采购类	206	buygoodsexchangebill	BillIndex
		ELSE IF(@BillType=161)
			BEGIN
				UPDATE BuyGoodsExchangeBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--145	受托代销结算单	2         	采购类	211	commissionbill	BillIndex
		ELSE IF(@BillType=145)
			BEGIN
				UPDATE CommissionBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--404	采购暂估开票	5         	暂估类	954	ReceiptBill	ReceiptBillIndex
		ELSE IF(@BillType=404)
			BEGIN
				UPDATE ReceiptBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
			
		--400	暂估入库单	2         	暂估类	950	AppraisalBill	BillIndex
		ELSE IF(@BillType=400)
			BEGIN
				UPDATE AppraisalBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END	
		--401	暂估退货单	2         	暂估类	951	AppraisalBackBill	BillIndex
		ELSE IF(@BillType=401)
			BEGIN
				UPDATE AppraisalBackBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END	
		--405	销售发货开票	5         	暂估类	955	ReceiptBill	ReceiptBillIndex
		ELSE IF(@BillType=405)
			BEGIN
				UPDATE ReceiptBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--139	赠送单	1         	销售类	108	givebill	BillIndex
		ELSE IF(@BillType=139)
			BEGIN
				UPDATE GiveBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
		--126	获赠单	2         	采购类	207	givemebill	BillIndex
		ELSE IF(@BillType=126)
			BEGIN
				UPDATE GivemeBill SET Reconciliation=@Reconciliation WHERE BillNumberId=@BillnumberId
			END
			
	
	END
RETURN 1
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateE]
GO


CREATE  PROCEDURE [Gp_UpdateE]
(
 @Typeid  [varchar](50),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @Department  [varchar](100),
 @Tel   [varchar](20),
 @Address  [varchar](66),
 @Comment  [varchar](256),
 @BTypeId  [varchar](50),
@Sex bit,
@Nation varchar(20),
@Knowledge varchar(20),
@Blood varchar(20),
@Health varchar(256),
@IDCard varchar(50),
@BirthDay datetime,
@Marriage int,
@Job varchar (50),
@Job2 varchar (50),
@Jobtime datetime,
@Mob varchar (50),
@Mail varchar (50),
@Political varchar (20),
@Nat_place varchar (20),
@Tel2 varchar (50),
@College varchar (50),
@For_language varchar (20),
@Reg_place varchar (50),
@Com_level varchar (20),
@Weight  NUMERIC(24, 10) ,
@Stature  NUMERIC(24, 10) ,
@Fam_status varchar (50),
@Informer varchar (20),
@Speciality varchar (50),
@For_lan_level varchar (20),
@PostCode varchar (10),
@DtypeID  varchar(50),
@PyCode   varchar(200),
@MaxPre    NUMERIC(24, 10) ,
@tichengRate  NUMERIC(24, 10) ,
@STypeID varchar(50),
@QQ varchar(50),
@MSN varchar(50),
@Blog varchar(200),
@mBlog varchar(200),
@Team varchar(200),
@Buyerminvalue NUMERIC(24, 10) ,
@Saleminvalue NUMERIC(24, 10) 
)
--@encode$--
AS 
SET NOCOUNT ON 

--系统启用了允许同名
DECLARE @eroFlag int
SELECT @eroFlag=value from Userconfig where ConfigName='equaleroname'

if (@eroFlag=0)--不允许重复
BEGIN
if exists(select usercode from employee where (usercode=@usercode  or fullname=@fullname) and deleted<>1 and typeid<>@typeid and btypeid=@btypeid)
begin
-- print '商品已存在'+@etypeid_1
 return -3
end
if exists(select usercode from employee where (usercode=@fullname  or fullname=@usercode) and deleted<>1 and typeid<>@typeid  and btypeid=@btypeid)
begin
-- print '商品已存在'+@etypeid_1
 return -10
end
END

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

UPDATE [employee] 
SET    [FullName]  = @FullName,
  [UserCode]  = @UserCode,
  [Department]  = @Department,
  [Tel]   = @Tel,
  [Address]  = @Address,
  [Comment]  = @Comment,
  [BTypeId]  = @BTypeId,
[Sex]=@Sex,
[Nation]=@Nation,
[Knowledge]=@Knowledge,
[Blood]=@Blood,
[Health]=@Health,
[IDCard]=@IDCard,
[BirthDay]=@BirthDay,
[Marriage]=@Marriage,
[Job]=@Job,
[Job2]=@Job2,
[Jobtime]=@Jobtime,
[Mob]=@Mob,
[Mail]=@Mail,
[Political]=@Political,
[Nat_place]=@Nat_place,
[Tel2]=@Tel2,
[College]=@College,
[For_language]=@For_language,
[Reg_place]=@Reg_place,
[Com_level]=@Com_level,
[Weight]=@Weight,
[Stature]=@Stature,
[Fam_status]=@Fam_status,
[Informer]=@Informer,
[Speciality]=@Speciality,
[For_lan_level]=@For_lan_level,
[PostCode]=@PostCode,
[PyCode] = @returnPym,
[DtypeID] =@DtypeID,
[MaxPre]  =dbo.F_RoundTotal(@MaxPre),
[tichengRate] =dbo.F_RoundPercentage(@tichengRate),
[STypeID]=@STypeID,
[QQ]=@QQ,
[MSN]=@MSN,
[Blog]=@Blog,
[mBlog]=@mBlog,
[Team]=@Team,
[Buyerminvalue]=@Buyerminvalue,
[Saleminvalue]=@Saleminvalue
WHERE 
 ([Typeid]  = @Typeid)

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Employee
UPDATE Employee SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId
UPDATE PrintRecord SET eFullName =  @FullName WHERE etypeid = @TypeId

--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','loginuser','0'

EXEC Gp_DataSaveForPosDown '-99999','employee','0'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateErrDes]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateErrDes]
GO










-- ========================================================================
-- 功能说明：	维修故障查询
-- 作    者：	cqhua
-- 2009-11-09
-- ========================================================================
CREATE    PROCEDURE GP_UpdateErrDes
(
	@ErrCode        varchar(100)='',	
	@ErrName        varchar(100)='',
	@ErrPycode      varchar(100)='',
	@ErrDes         varchar(100)='',
	@ErrDeal        varchar(256)='',
	@ErrComment     varchar(256)='',
	@Total           NUMERIC(24, 10) =0,
	@ID             numeric(18,0)
	
)	

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

IF EXISTS(select * from  wx_ErrDescription where [ID]<>@ID AND (errcode =@errcode or errcode=@errname or errname=@errcode or errname=@errname ))
	RETURN -2
ELSE	
	UPDATE wx_ErrDescription
	SET ErrCode=@ErrCode,
		ErrName = @ErrName,
		ErrPyCode =@ErrPyCode,
		ErrDes =@ErrDes,
		ErrDeal =@ErrDeal,
		ErrComment=@ErrComment,
		Total =dbo.F_RoundTotal(@Total)
	WHERE [ID] =@ID

IF @@rowcount =0
	RETURN -1
ELSE
	RETURN 0





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateFaPiaoBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateFaPiaoBillIndex]
GO



/*
功能：修改发票索引
作者：卢春  2009-01
*/
CREATE    PROCEDURE [Gp_UpdateFaPiaoBillIndex]
(
	@BillNumberId  		[numeric](10,0),
	@BillDate  			[datetime],
	@BillCode  			[varchar](200),
	@BillType  			[numeric](4,0),
	@FaPiaoType			[char](1),
	@FaPiaoCode			[varchar](256),
	@Comment  			[varchar](256),
	@Explain 			[varchar](256),
	@BtypeId  			[varchar](100),
	@dealBtypeId  		[varchar](100),
	@EtypeId  			[varchar](100),
	@DtypeId 			[varchar](100) = '',		--分支机构ID
	@CheckE  			[varchar](100) = '',
	@Assessor			[varchar](100) = '',
	@Tax   				 NUMERIC(24, 10) ,
	@TotalQty 			 NUMERIC(24, 10) ,
	@TotalMoney  		 NUMERIC(24, 10) ,
	@TaxTotalMoney 		 NUMERIC(24, 10) ,
	@STypeID			varchar(50)='',
	@othertotal			 NUMERIC(24, 10) ,
	@CID				INT,
	@RATE				 NUMERIC(24, 10) ,
	@NTOTALMONEY		DECIMAL(22,10),
	@NTAXTOTALMONEY		DECIMAL(22,10)
)
--@encode$--
AS 
SET NOCOUNT ON 

IF NOT EXISTS(SELECT TOP 1 1 FROM FaPiaoBillIndex WHERE BillNumberID = @BillNumberID AND BillType = @BillType)
	RETURN -7

DECLARE @szPeriod [SMALLINT]
DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
EXEC Gp_GetSubValue 'period',@STypeID,@szPeriod out
SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
IF @BillDate<@BeginDate  AND @BillType NOT IN(162,163)
BEGIN 
	--RAISERROR('录单日期小于本期开始日期 ！',16,1) 
	RETURN -2
END
---根据配置检查过帐日期是否当前日期
DECLARE @CurDate datetime
DECLARE @IsOrNotPassOneDay bit
SELECT @CurDate=GETDATE()
SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
BEGIN 
	--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
	RETURN -3
END

IF NOT EXISTS (
	SELECT	TOP 1 1
	FROM	SType_UserConfig
	WHERE	ConfigNo = 1
			AND Value = '1'
			AND STypeID=@STypeID
)
	RETURN -33	-- 没有开帐不允许过帐


UPDATE [dbo].[FaPiaoBillIndex] 
SET     [BillDate]  = @BillDate,
		[BillCode]  = @BillCode,
		[BillType]  = @BillType,
		[FaPiaoType]= @FaPiaoType,
		[FaPiaoCode]= @FaPiaoCode,
		[Comment]  = @Comment,
		[explain]  = @explain,
		[btypeid]  = @btypeid,
		dealBtypeId = @dealBtypeId,
		[etypeid]  = @etypeid,
		[DtypeId]=@DtypeId,
		[checke]  = @checke,
		[Assessor]=@Assessor,
		[tax]    =dbo.F_RoundTax( @tax),
		[totalqty]  = dbo.F_RoundQty(@totalqty),
		[totalmoney]  = dbo.F_RoundTotal(@totalmoney),
		[taxtotalmoney]  = dbo.F_RoundTotal(@taxtotalmoney),
		STypeID	=@STypeID,
		otherTotal=dbo.F_RoundTotal(@othertotal),
		CID=@CID,
		RATE=dbo.F_RoundExchangeRate(@RATE),
		NTOTALMONEY=dbo.F_RoundTotal(@NTOTALMONEY),
		NTAXTOTALMONEY=dbo.F_RoundTotal(@NTAXTOTALMONEY)
WHERE 	[BillNumberId]  = @BillNumberId
--PRINT @@rowCount
IF @@rowcount =0  OR @@error<>0
--RAISERROR('更新数据表发生错误！',16,1)
	RETURN -5


--删除自定义表头列
DELETE FROM CustomBillColumns	WHERE billnumberid=@BillNumberId AND BillType=@BillType
--删除自定义明细列
DELETE FROM CustomBillDetailColumns WHERE billnumberid=@BillNumberId AND BillType=@BillType
DELETE FROM dbo.Custom_BillIndex WHERE BillId=@BillNumberId AND BillType=@BillType
DELETE FROM dbo.Custom_BillDetails WHERE BillId=@BillNumberId AND BillType=@BillType
DECLARE @sql VARCHAR(max)=''
CREATE TABLE #listid( billnumberid VARCHAR(50) )

---------------回写单据的开票金额,状态-----------------
SET @SQL = ' INSERT INTO #listid(billnumberid) SELECT DISTINCT MainBillNumberID FROM FaPiaoBill WHERE BillNumberId ='+CAST(@BillNumberId AS VARCHAR(10))+' and MainBillNumberID > = 0 '
EXEC (@SQL)

IF(@@ERROR=0)
BEGIN
--------更新状态
DECLARE @NumBerID VARCHAR(50)
DECLARE CursorName CURSOR  ------查询游标
	LOCAL SCROLL STATIC 
	FOR SELECT billnumberid FROM #listid
	OPEN CursorName
	FETCH NEXT FROM CursorName
	INTO @NumBerID

	WHILE @@FETCH_STATUS=0
	BEGIN	
		EXEC Gp_UpdateInvoiceState @billnumberid = @NumBerID,@fapiaobillnumberid=@BillNumberId,@otype=0	
		FETCH NEXT FROM CursorName
		INTO @NumBerID
	END
	CLOSE CursorName
	DEALLOCATE CursorName
END

DROP TABLE #listid
---------------回写单据的开票金额,状态 end-----------------


DELETE FROM QP_InvoiceRepairItems
WHERE BillNumberID = @BillNumberId

DELETE FROM QP_InvoiceOtherTotalDetails
WHERE BillNumberID = @BillNumberId

DELETE FROM FaPiaoBill
WHERE BillNumberID = @BillNumberId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateFeeType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateFeeType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-17
	描述：费用信息更新
*/

CREATE PROCEDURE GP_UpdateFeeType
(
	@feetypeid  int,		  --唯一标识
	@usercode   varchar(50),  --费用编号
	@fullname	varchar(100), --费用名称
	@comment    varchar(256)  --备注
)
--@encode$--
AS
SET NOCOUNT ON

update CM_FeeType
set 
	Usercode=@usercode,
	Fullname=@fullname,
	Comment=@comment
where
	FeeTypeId=@feetypeid
	

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_UpdateFixedAssetsIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_UpdateFixedAssetsIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROC Gp_UpdateFixedAssetsIndex
	@billnumberid int,
	@createdate DATE,
	@billcode varchar(100),
	@stypeid VARCHAR(50),
	@dtypeid VARCHAR(50),
	@etypeid VARchar(50),
	@state INT,
	@memo VARCHAR(200),
	@comment VARCHAR(200)
--@encode$--
AS 
BEGIN
	DECLARE @ret INT=0
	
	UPDATE FixedAssetsIndex SET createdate=@createdate,
	billcode=@billcode,
	stypeid=@stypeid,
	dtypeid=@dtypeid,
	etypeid=@etypeid,
	[state]=@state,
	memo=@memo,
	comment=@comment
	WHERE billnumberid=@billnumberid
	
	--删除单据明细
	DELETE FROM FixedAssetsDetails WHERE BillNumberID=@billnumberid;
	
	RETURN @ret;
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TbType_FPeriodStartSet' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateFPeriodStartSet]') AND TYPE in (N'P', N'PC'))
		DROP PROC Gp_UpdateFPeriodStartSet;
	DROP TYPE TbType_FPeriodStartSet;
END
GO

CREATE TYPE TbType_FPeriodStartSet AS TABLE
(
	NId			INT,
	STypeId		VARCHAR(50),			--分支机构
	ASFyear		INT,					--总账启用年度
	ASFperiod	INT,					--总账启用期间
	AIsUse		INT,					--总账分支机构当前是否开账
	AIsEdit		INT,					--总账是否更改
	BSFyear		INT,					--业务启用年度
	BSFperiod	INT,					--业务启用期间
	BIsUse		INT,					--业务分支机构当前是否开账
	BIsEdit		INT						--业务是否更改
)
GO


IF EXISTS (SELECT TOP 1  1FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateFPeriodStartSet]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateFPeriodStartSet]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：lxl
	时间：2016.06.20
	描述：系统设置-启用期间设置
*/
CREATE PROCEDURE Gp_UpdateFPeriodStartSet
(
	@OperatorId		VARCHAR(50),		-- 当前操作员ID
	@GridData		TbType_FPeriodStartSet	READONLY	-- 出纳启用期间数据
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE 
	@I			INT=1,
	@RowCount	INT,
	@Error		INT=0,
	@STypeId	VARCHAR(50),			--分支机构
	@SFullName	VARCHAR(200),			--分支机构名称
	@ASFyear	INT,					--总账启用年度
	@ASFperiod	INT,					--总账启用期间
	@BSFyear	INT,					--业务启用年度
	@BSFperiod	INT,					--业务启用期间
	@BillDate	DATETIME,				--当前期间开始时间
	@AIsEdit	INT,					--总账是否修改
	@BIsEdit	INT,					--业务是否修改
	@ResultTemp VARCHAR(MAX)='',		--错误消息列表
	@AResultTemp VARCHAR(MAX)='',		--总账错误消息列表
	@BResultTemp VARCHAR(MAX)='',		--业务错误消息列表
	@IsUseA		BIT=0,					--使用总账期间
	@IsV3		INT						--是否V3版本 
	
BEGIN TRAN
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='IsUseAcSystem' AND SubValue='1') OR  EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='assets' AND SubValue='1')
	SET @IsUseA=1

IF EXISTS(SELECT * FROM SysData WHERE SubName='ProInfo' AND SubValue=1)
	SET @IsV3=1

SELECT @RowCount=COUNT(*) FROM @GridData
WHILE(@I<=@RowCount)
BEGIN
	SET @AResultTemp=''
	SET @BResultTemp=''
	SELECT 
		@STypeId=STypeId,
		@SFullName='分支机构【'+S.FullName+'】',
		@ASFyear=ISNULl(D.ASFyear,0),
		@ASFperiod=ISNULL(D.ASFperiod,0),
		@BSFyear=ISNULL(D.BSFyear,0),
		@BSFperiod=ISNULL(D.BSFperiod,0),
		@AIsEdit=D.AIsEdit,
		@BIsEdit=D.BIsEdit
	FROM @GridData D 
	INNER JOIN SType S ON S.TypeId=D.STypeId WHERE NId=@I
	
	IF @IsV3=1
		SET @SFullName=''
	
	IF @IsUseA=1 AND EXISTS(SELECT TOP 1 1 FROM SType S INNER JOIN @GridData G ON G.STypeId=S.TypeId AND (S.VerifyID=@STypeId OR S.TypeId=@STypeId) AND (BSFyear>ASFyear OR (BSFyear=ASFyear AND BSFperiod>ASFperiod)))
		BEGIN
			IF (SELECT COUNT(*) FROM SType WHERE VerifyID=@STypeId)>1
				SET @AResultTemp+=@SFullName+'或其非独立分支机构【总账系统】启用期间必须大于【业务系统】启用期间!'+CHAR(13)
			ELSE
				SET @AResultTemp+=@SFullName+'【总账系统】启用期间必须大于【业务系统】启用期间!'+CHAR(13)
		END
	ELSE 
		BEGIN
			IF @AIsEdit=1
				BEGIN
					IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE STypeId=@STypeId AND IsUse=1 AND (SFYear<>@ASFyear OR SFPeriod<>@ASFperiod) )
						SET @AResultTemp+=@SFullName+'总账开账状态已发生更改!'+CHAR(13)
						
					--出纳，不需要判断分支机构
					IF EXISTS(SELECT TOP 1 1 FROM Te_StartPeriod WHERE (ISNULL(SFYear,0)<>@ASFyear) AND (ISNULL(SFYear,0)<>0 OR ISNULL(SFPeriod,0)<>0))
						SET @AResultTemp+=@SFullName+'调整后的会计年度或期间与出纳系统设置有冲突！'+CHAR(13)
						
					--固定资产相关判断
					IF EXISTS(SELECT * FROM SysData WHERE SubName='assets' AND SubValue=1) 
						BEGIN
							IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId=@STypeId AND IfAssetsIni=1 AND deleted=0  )
								SET @AResultTemp+=@SFullName+'固定资产已经初始化,请先反初始化固定资产!'+CHAR(13)
							
							IF EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards WHERE AssetsState=1 AND InAccountDate>=(SELECT FBegin FROM Ac_Period WHERE FYear=@ASFyear AND FPeriod=@ASFperiod) AND STypeId IN(SELECT TypeId FROM SType WHERE VerifyID = @STypeId))
								SET @AResultTemp+=@SFullName+'当前启用日期后存在初始固定资产卡片,请调整启用期间或初始固定资产卡片入账日期!'+CHAR(13)
								
							IF EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FYear<>@ASFyear OR FMonth<>@ASFperiod) AND EXISTS(SELECT TOP 1 1 FROM Ac_DepreciationPlan WHERE STypeId=@STypeId)
								SET @AResultTemp+=@SFullName+'修改后的启用期间与固定资产卡片折旧计划表冲突!'+CHAR(13)	
						END
					--总账相关判断
					IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='IsUseAcSystem' AND SubValue=1)
						BEGIN						
							IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount WHERE STypeId=@STypeId AND (FDebit<>0 OR FDebitFor<>0 OR FCredit<>0 OR FCreditFor<>0 OR FDebitqty<>0 AND FCreditqty<>0) AND (FYear<>@ASFyear OR (FYear=@ASFyear AND @ASFperiod=1)))
								SET @AResultTemp+=@SFullName+'账务期初中存在本年累计发生额，请修改后再进行期间调整！'+CHAR(13)
							
							IF EXISTS(SELECT * FROM Te_StartPeriod WHERE STypeId=@STypeId AND IsConnect=1 AND (SFYear<>@ASFyear OR SFPeriod<>@ASFperiod))	
								SET @AResultTemp+=@SFullName+'修改后期间与出纳系统启用期间设置中有冲突！'+CHAR(13)
							
							IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher V INNER JOIN (SELECT MIN(BillDate) BillDate,BillNumberId FROM Ac_Voucher WHERE STypeId=@STypeId AND IfCheck='F' GROUP BY BillNumberId) F ON F.BillNumberId=V.BillNumberId AND (FYear<@ASFyear OR (FYear=@ASFyear AND FPeriod<@ASFperiod )))
								SET @AResultTemp+=@SFullName+'调整后的年度及期间必须小于等于系统内未记账会计凭证最小日期的年度和期间值'+CHAR(13)
						END
				END
				
			IF(@BIsEdit=1)
				BEGIN
					--业务相关配置
					IF EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeId=@STypeId AND Value=1 AND(SFYear<>@BSFyear OR SFPeriod<>@BSFperiod))
						SET @BResultTemp+=@SFullName+'业务开账状态已发生更改!'+CHAR(13)
						
					SELECT @BillDate=FBegin FROM Ac_Period WHERE FYear=@BSFyear AND FPeriod=@BSFperiod	
					IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE StypeID=@STypeId AND IsIni=1 AND BillDate>=@BillDate)
						SET @BResultTemp+=@SFullName+'当前启用日期后存在期初单据，请调整启用期间或期初单据的日期！'+CHAR(13)
				END
			
			IF(@AIsEdit=1 AND @BIsEdit=1 AND @AResultTemp='' AND @BResultTemp='')
				BEGIN
					--更改总账启用期间、当前期间
					UPDATE Ac_AccountsPeroid_Stype 
					SET 
						SFYear=@ASFyear,
						SFPeriod=@ASFperiod,
						FYear=@ASFyear,
						FPeriod=@ASFperiod
					FROM Ac_AccountsPeroid_Stype
					WHERE Stypeid=@STypeId
					SET @Error+=@@ERROR

					--原逻辑添加期初数据期间更改
					UPDATE Ac_IniAccount SET FYear=@ASFyear,FPeriod=@ASFperiod WHERE STypeId=@STypeId
					SET @Error+=@@ERROR
					
					UPDATE Ac_IniAccount_Assist_CheckItems SET FYear=@ASFyear,FPeriod=@ASFperiod WHERE STypeId=@STypeId
					SET @Error+=@@ERROR
					
					UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYear=@ASFyear,FPeriod=@ASFperiod  WHERE STypeId=@STypeId
					SET @Error+=@@ERROR
					
					--更改业务启用期间、当前期间
					UPDATE SType_UserConfig SET SFYear=@BSFyear,SFPeriod=@BSFperiod WHERE StypeId=@STypeId
					SET @Error+=@@ERROR

					UPDATE MonthProc SET [Year]=@BSFyear,period=@BSFperiod,StartDate=@BillDate WHERE MonthNo='本期' AND STypeID=@STypeId
					SET @Error+=@@ERROR
				END
			ELSE IF(@AIsEdit=1 AND @AResultTemp='' AND @BIsEdit=0  AND @BResultTemp='')
				BEGIN
					UPDATE Ac_AccountsPeroid_Stype 
					SET 
						SFYear=@ASFyear,
						SFPeriod=@ASFperiod,
						FYear=@ASFyear,
						FPeriod=@ASFperiod
					FROM Ac_AccountsPeroid_Stype
					WHERE Stypeid=@STypeId
					SET @Error+=@@ERROR

					--原逻辑添加期初数据期间更改
					UPDATE Ac_IniAccount SET FYear=@ASFyear,FPeriod=@ASFperiod WHERE STypeId=@STypeId
					SET @Error+=@@ERROR
					
					UPDATE Ac_IniAccount_Assist_CheckItems SET FYear=@ASFyear,FPeriod=@ASFperiod WHERE STypeId=@STypeId
					SET @Error+=@@ERROR
					
					UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYear=@ASFyear,FPeriod=@ASFperiod  WHERE STypeId=@STypeId
					SET @Error+=@@ERROR
				END
			ELSE IF(@BIsEdit=1  AND @BResultTemp='' AND @AIsEdit=0 AND @AResultTemp='' )
				BEGIN
					--更改业务启用期间、当前期间
					UPDATE SType_UserConfig SET SFYear=@BSFyear,SFPeriod=@BSFperiod WHERE StypeId=@STypeId
					SET @Error+=@@ERROR

					UPDATE MonthProc SET [Year]=@BSFyear,period=@BSFperiod,StartDate=@BillDate WHERE MonthNo='本期' AND STypeID=@STypeId
					SET @Error+=@@ERROR
				END
		END
	SET @ResultTemp+=@AResultTemp+@BResultTemp
	SET @I+=1
END

/*
UPDATE I SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0,iniYTotal = iniTotal,iniYTotalFor = iniTotalFor,IniYqty=iniqty
FROM Ac_IniAccount I
INNER JOIN Ac_AccountsPeroid_Stype S ON S.Stypeid = I.STypeId
WHERE	S.SFPeriod = 1 AND S.IsUse = 0

UPDATE I SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0,iniYTotal = iniTotal,iniYTotalFor = iniTotalFor,IniYqty=iniqty
FROM Ac_IniAccount_Assist_CheckItems I
INNER JOIN Ac_AccountsPeroid_Stype S ON S.Stypeid = I.STypeId
WHERE	S.SFPeriod = 1 AND S.IsUse = 0

UPDATE I SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0,iniYTotal = iniTotal,iniYTotalFor = iniTotalFor,IniYqty=iniqty
FROM Ac_IniAccount_Assist_CheckItems_Detail I
INNER JOIN Ac_AccountsPeroid_Stype S ON S.Stypeid = I.STypeId
WHERE	S.SFPeriod = 1 AND S.IsUse = 0
*/

IF(@Error=0)
	COMMIT TRAN
ELSE 
	ROLLBACK TRAN
	
SELECT @ResultTemp
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateGiveFromSaleOrBuy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateGiveFromSaleOrBuy]
GO








/*
	作者：谢吉康
	日期：2003-12-9
	描述：将采购、销售中发生的赠送、获赠的关联关系记入下面的表中
*/
CREATE PROCEDURE Gp_UpdateGiveFromSaleOrBuy
(
	@SourceBillNumberId		INT,
	@DestBillNumberId		INT,
	@IfCheck 				CHAR(1),
	@ETypeID				VARCHAR(50),
	@BTypeID				VARCHAR(50),
	@KTypeID				VARCHAR(50),
	@Explain				VARCHAR(256),
	@Comment				VARCHAR(256),
	@OutPutID				INT 	OUTPUT
)
--@encode$--
AS
BEGIN
	UPDATE 	GiveFromSaleOrBuy
	SET 	IfCheck=@IfCheck,
			ETypeID=@ETypeID,
			BTypeID=@BTypeID,
			KTypeID=@KTypeID,
			Explain=@Explain,
			Comment=@Comment
	WHERE	SourceBillNumberId=@SourceBillNumberId
			AND	DestBillNumberId=@DestBillNumberId

	SELECT @OutPutID = [ID] FROM GiveFromSaleOrBuy WHERE SourceBillNumberId = @SourceBillNumberId AND DestBillNumberId = @DestBillNumberId

	IF @@ROWCOUNT=0
		RETURN -1
	ELSE
		RETURN 0
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateGiveFromSaleOrBuyBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateGiveFromSaleOrBuyBill]
GO








/*
	作者：谢吉康
	日期：2003-12-9
	描述：将采购、销售中发生的赠送、获赠的关联关系明细记入下面的表中
*/
CREATE PROCEDURE Gp_UpdateGiveFromSaleOrBuyBill
(
	@ID						INT,
	@PTypeID				VARCHAR(50),
	@Qty					 NUMERIC(24, 10) 
)
--@encode$--
AS
BEGIN
	IF Exists(SELECT Qty FROM GiveFromSaleOrBuyBill WHERE [ID]=@ID AND PTypeID=@PTypeID)	
		UPDATE	GiveFromSaleOrBuyBill
		SET		Qty		= @Qty
		WHERE	[ID]	= @ID
	ELSE
		INSERT INTO GiveFromSaleOrBuyBill
			(
				[ID],
				PTypeID,
				Qty
			)
			VALUES
			(
				@ID,
				@PTypeID,
				dbo.F_RoundQty(@Qty)
			)
	
		IF @@ROWCOUNT=0
			RETURN -1
		ELSE
			RETURN 0
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateGuestGetIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateGuestGetIndex]
GO
















/****** Object:  Stored Procedure dbo.Gp_UpdateGuestGetIndex    Script Date: 2002-6-20 10:14:51 ******/

CREATE    PROCEDURE [Gp_UpdateGuestGetIndex]
(
  @BillNumberID [numeric](10,0),
  @BillDate  [datetime],
  @BillCode  [varchar](200),
  @BillType  [numeric](4,0),
  @Comment  [varchar](256),
  @AtypeId  [varchar](50),
  @PtypeId  [varchar](50),
  @BtypeId  [varchar](50),
  @EtypeId  [varchar](50),
  @KtypeId  [varchar](50),
  @KtypeId2 [varchar](50),
  @IfCheck  [char](1),
  @CheckE  [varchar](50),
  @TotalMoney   NUMERIC(24, 10) ,
  @TotalQty  NUMERIC(24, 10) ,
  @TotalInMoney   NUMERIC(24, 10) ,
  @Tax   [numeric],
  @szPeriod [smallint],
  @Explain [varchar](256),
  @Draft  [bit],
  @RedWord [bit],
  @OrderId [numeric]=0 
)
--@encode$--
AS 
SET NOCOUNT ON 
update [dbo].[GuestGetIndex] set
  [BillDate]=@BillDate,
  [BillCode]=@BillCode,
  [BillType]=@BillType,
  [Comment]=@Comment,
  [atypeid]=@atypeid,
  [ptypeid]=@ptypeid,
  [btypeid]=@btypeid,
  [etypeid]=@etypeid,
  [ktypeid]=@ktypeid,
  [ktypeid2]=@ktypeid2,
  [ifcheck]=@ifcheck,
  [checke]=@checke,
  [totalqty]=dbo.F_RoundQty(@totalqty),
  [totalmoney]=dbo.F_RoundTotal(@totalmoney),
  [totalinmoney]=dbo.F_RoundTotal(@totalinmoney),
  [tax]=dbo.F_RoundTax(@tax),
  [period]=@szPeriod,
  [explain]=@explain, 
  [draft]=@draft,
  [RedWord]=@redword,
  [orderid]=@orderID
where [billnumberid]=@billnumberid
if @@rowcount =0  or @@error<>0
  RAISERROR('更新单据发生错误！',16,1)

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateInvoiceState]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateInvoiceState
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：MaoXinrong
	日期：2011-11-25
	描述：保存发票后修改原来的开票状态,回写开票数量和金额
	
	修改：hanlin
	修改: 周华 2013-08-14 添加零售退货单类型
*/

CREATE PROCEDURE [dbo].[Gp_UpdateInvoiceState]
(
	@billnumberid		INT,
	@fapiaobillnumberid VARCHAR(500),
	@otype				INT		--1=保存发票，0=删除发票
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(
				SELECT TOP 1 1 FROM --从未开过票
				(  
					 SELECT PTypeID 
					 FROM	FaPiaoBill 
					 WHERE MainBillNumberID=@billnumberid
				)a
			)
BEGIN
	UPDATE BillIndex SET IfInvoice=0  WHERE BillNumberId=@billnumberid --未开票
END


DECLARE @type INT=0
DECLARE @sql NVARCHAR(MAX)=''
DECLARE @sel NVARCHAR(1000)=''
DECLARE @qty INT=0
DECLARE @operator VARCHAR(1)='+'

SET @operator=CASE @otype WHEN 1 THEN '+' ELSE '-' END

SELECT @type=BillType FROM BillIndex WHERE BillNumberId=@BillNumberId;
IF @type=0 OR @type IS NULL 
	RETURN

DECLARE @dbname VARCHAR(50)=''
IF @type=11				SET @dbname=' SaleBill'				--销售出库
IF @type=305			SET @dbname=' retailBill';				--零售
IF @type IN (141,145)	SET @dbname=' CommissionBill'			--受托，委托结算
IF @type=160			SET @dbname=' SaleGoodsExchangeBill'	--销售换货
IF @type=161			SET @dbname=' BuyGoodsExchangeBill'	--采购换货
IF @type=45				SET @dbname= ' saleBackBill'			--销售退货
IF @type=34				SET @dbname= ' BuyBill';				--采购入库
IF @type=6				SET @dbname= ' BuyBackBill'			--采购退货
IF @type=215			SET @dbname=' RetailBackBill' -- 零售退货单

--组合品
IF @type=12			SET @dbname=' PT_Combin_SaleBill'
IF @type=46			SET @dbname=' PT_Combin_SaleBackBill'

--将开票的金额回写到billindex 和明细表
DECLARE @TOTAL VARCHAR(max)='',@NTOTAL VARCHAR(max)='',@iqty  VARCHAR(max)=''
IF @type NOT IN (160,161)
BEGIN
	SET @TOTAL=CASE WHEN @type IN (45,46,6,215) THEN '-F.TaxTotal' ELSE 'F.TaxTotal' END 
	SET @NTOTAL= CASE WHEN @type IN (45,46,6,215) THEN '-F.NTaxTotal' ELSE 'F.NTaxTotal' END 
	SET @iqty=CASE WHEN @type IN (45,46,6,215) THEN '-F.Qty' ELSE 'F.Qty' END 
	SET @sql= '
		UPDATE Billindex
		SET InvoiceMoney=InvoiceMoney'+@operator+'C.Total,
			NInvoiceMoney=NInvoiceMoney'+@operator+'C.NTotal
		FROM 
		(
			SELECT	SUM('+@TOTAL+') AS Total,
					SUM('+@nTOTAL+') AS NTotal,
					MainBillNumberID
			FROM	dbo.FaPiaoBill F
			where	billnumberid in('+@fapiaobillnumberid+')
			GROUP BY MainBillNumberID
		)C
		WHERE C.MainBillNumberID=Billindex.BillNumberId
		AND	C.MainBillNumberID='+CAST(@BillNumberId AS VARCHAR(10))
				
	SET @sql =@SQL +'
		UPDATE '+@dbname+'
		SET	InvoiceQty=InvoiceQty'+@operator+'C.QTY,
			InvoiceMoney=InvoiceMoney'+@operator+'C.Total,
			NInvoiceMoney=NInvoiceMoney'+@operator+'C.NTotal
		FROM 
		(
			SELECT	SUM('+@iqty+') AS QTY,
					SUM('+@TOTAL+') AS Total,
					SUM('+@nTOTAL+') AS NTotal,
					RecordedItemId,
					MainBillNumberID
			FROM	dbo.FaPiaoBill F
			where	billnumberid in('+@fapiaobillnumberid+')
			GROUP BY F.RecordedItemId,MainBillNumberID
		)C
		WHERE C.MainBillNumberID='+@dbname+'.BillNumberId
		AND	C.RecordedItemId='+@dbname+'.ID
		AND	C.MainBillNumberID='+CAST(@BillNumberId AS VARCHAR(10))
END
ELSE
BEGIN
	SET @TOTAL=CASE @type WHEN 160 THEN '-F.TaxTotal' ELSE 'F.TaxTotal' END 
	SET @NTOTAL= CASE @type WHEN 160 THEN '-F.NTaxTotal' ELSE 'F.NTaxTotal' END 
	SET @iqty= CASE @type WHEN 160 THEN '-F.qty' ELSE 'F.qty' END 
	SET @sql= '	
		UPDATE Billindex
		SET InvoiceMoney=InvoiceMoney'+@operator+'C.Total,
			NInvoiceMoney=NInvoiceMoney'+@operator+'C.NTotal
		FROM 
		(
			SELECT	SUM(F.TaxTotal) AS Total,
					SUM(F.nTaxTotal) AS NTotal,
					MainBillNumberID
			FROM	dbo.FaPiaoBill F
			where	billnumberid in('+@fapiaobillnumberid+')
			GROUP BY MainBillNumberID
		)C
		WHERE C.MainBillNumberID=Billindex.BillNumberId
		AND	C.MainBillNumberID='+CAST(@BillNumberId AS VARCHAR(10))	
				
	SET @sql =@SQL +'
		UPDATE '+@dbname+'
		SET	InvoiceQty=InvoiceQty'+@operator+'C.QTY,
			InvoiceMoney=InvoiceMoney'+@operator+'C.Total,
			NInvoiceMoney=NInvoiceMoney'+@operator+'C.NTotal
		FROM 
		(
			SELECT	SUM(CASE WHEN A.InOrOut = ''I'' THEN '+@iqty+' ELSE -('+@iqty+') END) AS QTY,
					SUM(CASE WHEN A.InOrOut = ''I'' THEN '+@TOTAL+' ELSE -('+@TOTAL+') END) AS Total,
					SUM(CASE WHEN A.InOrOut = ''I'' THEN '+@nTOTAL+' ELSE -('+@nTOTAL+') END) AS NTotal,
					RecordedItemId,
					MainBillNumberID
			FROM	dbo.FaPiaoBill F
			INNER JOIN '+@dbname+' A ON A.ID=F.RecordedItemId
			where	f.billnumberid in('+@fapiaobillnumberid+')
			GROUP BY F.RecordedItemId,MainBillNumberID
		)C
		WHERE C.MainBillNumberID='+@dbname+'.BillNumberId
		AND	C.RecordedItemId='+@dbname+'.ID
		AND	C.MainBillNumberID='+CAST(@BillNumberId AS VARCHAR(10))	
END	

EXEC (@SQL)

DECLARE @IfInvoice int=2
SET @SQL ='
IF EXISTS(SELECT 1 FROM '+@dbname+ ' WHERE billnumberid=@billNumberId AND QTY>InvoiceQty)
	SET @IfInvoice=1'
PRINT @sql	
EXEC SP_EXECUTESQL @sql,N'@IfInvoice INT OUTPUT,@billNumberId INT',@IfInvoice OUTPUT,@billNumberId;

UPDATE BillIndex SET IfInvoice=@IfInvoice  WHERE BillNumberId=@billnumberid 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateInvoiceStateAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateInvoiceStateAll
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：Hanlin	
	日期：2013-05-31
	描述：保存发票后修改原来的开票状态,回写开票数量和金额
*/

CREATE PROCEDURE [dbo].[Gp_UpdateInvoiceStateAll]

--@encode$--
AS
SET NOCOUNT ON

UPDATE Billindex
SET InvoiceMoney=InvoiceMoney + C.Total,
	NInvoiceMoney=NInvoiceMoney + C.NTotal
FROM 
(
	SELECT	SUM(CASE WHEN b.billtype IN (45,6) THEN -f.Taxtotal ELSE f.TaxTotal END) AS Total,
			SUM(CASE WHEN b.billtype IN (45,6) THEN -f.nTaxtotal ELSE f.nTaxTotal END) AS NTotal,
			MainBillNumberID
	FROM	FaPiaoBill F
	INNER JOIN dbo.BillIndex B ON B.BillNumberId=f.MainBillNumberID
	GROUP BY MainBillNumberID
)C
WHERE C.MainBillNumberID=Billindex.BillNumberId



DECLARE @type INT=0
DECLARE @sql NVARCHAR(MAX)=''

CREATE TABLE #billtype(billtype int)
INSERT INTO #billtype
SELECT DISTINCT(BillType) FROM BillIndex WHERE BillNumberId IN (SELECT MainBillNumberID from dbo.FaPiaoBill)

DECLARE CursorName CURSOR  ------查询游标
FOR SELECT billtype FROM #billtype
OPEN CursorName
FETCH NEXT FROM CursorName INTO @type

WHILE @@FETCH_STATUS=0
BEGIN	
	DECLARE @dbname VARCHAR(50)=''
	IF @type=11				SET @dbname=' SaleBill'				--销售出库
	IF @type=305			SET @dbname=' retailBill';				--零售
	IF @type IN (141,145)	SET @dbname=' CommissionBill'			--受托，委托结算
	IF @type=160			SET @dbname=' SaleGoodsExchangeBill'	--销售换货
	IF @type=161			SET @dbname=' BuyGoodsExchangeBill'	--采购换货
	IF @type=45				SET @dbname= ' saleBackBill'			--销售退货
	IF @type=34				SET @dbname= ' BuyBill';				--采购入库
	IF @type=6				SET @dbname= ' BuyBackBill'			--采购退货
	
	--将开票的金额回写到billindex 和明细表
	DECLARE @TOTAL VARCHAR(max)='',@NTOTAL VARCHAR(max)='',@iqty  VARCHAR(max)=''
	IF @type NOT IN (160,161)
	BEGIN
		SET @TOTAL=CASE WHEN @type IN (45,6) THEN '-F.TaxTotal' ELSE 'F.TaxTotal' END 
		SET @NTOTAL= CASE WHEN @type IN (45,6) THEN '-F.NTaxTotal' ELSE 'F.NTaxTotal' END 
		SET @iqty=CASE WHEN @type IN (45,6) THEN '-F.Qty' ELSE 'F.Qty' END 
					
		SET @sql =@SQL +'
			UPDATE '+@dbname+'
			SET	InvoiceQty=InvoiceQty + C.QTY,
				InvoiceMoney=InvoiceMoney + C.Total,
				NInvoiceMoney=NInvoiceMoney + C.NTotal
			FROM 
			(
				SELECT	SUM('+@iqty+') AS QTY,
						SUM('+@TOTAL+') AS Total,
						SUM('+@nTOTAL+') AS NTotal,
						RecordedItemId,
						MainBillNumberID
				FROM	dbo.FaPiaoBill F
				GROUP BY F.RecordedItemId,MainBillNumberID
			)C
			WHERE C.MainBillNumberID='+@dbname+'.BillNumberId
			AND	C.RecordedItemId='+@dbname+'.ID
			AND	C.MainBillNumberID in (SELECT BillNumberid from billindex where billtype ='+CAST(@type AS VARCHAR)+')'
	END
	ELSE
	BEGIN
		SET @TOTAL=CASE @type WHEN 160 THEN '-F.TaxTotal' ELSE 'F.TaxTotal' END 
		SET @NTOTAL= CASE @type WHEN 160 THEN '-F.NTaxTotal' ELSE 'F.NTaxTotal' END 
		SET @iqty= CASE @type WHEN 160 THEN '-F.qty' ELSE 'F.qty' END 

		SET @sql =@SQL +'
			UPDATE '+@dbname+'
			SET	InvoiceQty=InvoiceQty + C.QTY,
				InvoiceMoney=InvoiceMoney + C.Total,
				NInvoiceMoney=NInvoiceMoney + C.NTotal
			FROM 
			(
				SELECT	SUM(CASE WHEN A.InOrOut = ''I'' THEN '+@iqty+' ELSE -('+@iqty+') END) AS QTY,
						SUM(CASE WHEN A.InOrOut = ''I'' THEN '+@TOTAL+' ELSE -('+@TOTAL+') END) AS Total,
						SUM(CASE WHEN A.InOrOut = ''I'' THEN '+@nTOTAL+' ELSE -('+@nTOTAL+') END) AS NTotal,
						RecordedItemId,
						MainBillNumberID
				FROM	dbo.FaPiaoBill F
				INNER JOIN '+@dbname+' A ON A.ID=F.RecordedItemId
				GROUP BY F.RecordedItemId,MainBillNumberID
			)C
			WHERE C.MainBillNumberID='+@dbname+'.BillNumberId
			AND	C.RecordedItemId='+@dbname+'.ID
			AND	C.MainBillNumberID in (SELECT BillNumberid from billindex where billtype ='+CAST(@type AS VARCHAR)+')'
	END	
	--PRINT @sql
	EXEC (@SQL)
	
	FETCH NEXT FROM CursorName
	INTO @TYPE
END
CLOSE CursorName
DEALLOCATE CursorName

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateK]
GO


/****** Object:  StoredProcedure [dbo].[Gp_UpdateK]    Script Date: 05/25/2011 12:25:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*
修改人：李小虎
日  期：2011.4
原  因：仓库关联了分支机构，且其期初中有数据，则禁止修改其父节点的分支机构
*/



CREATE  PROCEDURE [dbo].[Gp_UpdateK]
(
	@TypeId			[varchar](50),
	@UserCode		[varchar](26),
	@FullName		[varchar](66),
	@Name			[varchar](30),
	@Comment		[varchar](256),
	@LinkMan		varchar(20),
	@Tel			varchar(50),
	@Address		varchar(50),
	@PyCode			varchar(200),
	@STypeID		varchar(50),
	@job			VARCHAR(100) = '',	--职位
	@mobile			VARCHAR(100) = '',	--手机
	@sheng			VARCHAR(100) = '',	--省
	@shi			VARCHAR(100) = '',	--市
	@xian			VARCHAR(100) = '',	--县
	@postcode		VARCHAR(100) = ''	--邮编
)
--@encode$--
AS
SET NOCOUNT ON 
if exists(select usercode from stock where (usercode=@usercode  or fullname=@fullname) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -3
end
if exists(select usercode from stock where (usercode=@fullname  or fullname=@usercode) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -10
end
----判断：凡是单据(BillIndex,OrderIndex,LendIndex)中已经关联了仓库，则该禁止修改该仓库的分支机构
IF EXISTS(select ktypeid FROM Coupon_CodeInfo WHERE ktypeid = @TypeId)
	AND EXISTS(SELECT TOP 1 1 FROM Stock K,Stype S WHERE K.STypeId = S.TypeId AND K.TypeId = @TypeId AND K.STypeId <> @STypeID)
	BEGIN
		RAISERROR('该仓库已经被优惠券使用，禁止修改该仓库的分支机构',16,1) 
		RETURN
	END
--IF EXISTS(select ktypeid from OrderIndex,Stock where OrderIndex.ktypeid=Stock.typeId AND @TypeId=Stock.typeId AND @STypeID<>Stock.STypeID)
--	BEGIN
--		RAISERROR('该仓库已经被单据使用，禁止修改该仓库的分支机构',16,1) 
--		RETURN
--	END
--IF EXISTS(select ktypeid,ktypeid2 from LendIndex,Stock where(Stock.typeId=LendIndex.ktypeid OR Stock.typeId=LendIndex.ktypeid2) AND @TypeId=Stock.typeId AND @STypeID<>Stock.STypeID )
--BEGIN
--	RAISERROR('该仓库已经被单据使用，禁止修改该仓库的分支机构',16,1) 
--	RETURN
--END

--修改仓库的分支机构必须满足的条件有2：1、该仓库及其子结点在任何的单据中都没有被使用 2、该仓库期初库存为0
DECLARE @ID VARCHAR(200)		--子结点的id
DECLARE @SStypeID VARCHAR(100)	--商品序列号所属分支机构id
DECLARE @Count int				--使用1个分支机构的仓库个数
SET @ID=@TypeId+'%'
CREATE TABLE #StockSon(TypeID VARCHAR(50))
IF EXISTS(SELECT * FROM Stock WHERE typeId=@TypeId AND STypeID<>@STypeID)
	BEGIN
		--IF EXISTS(SELECT * FROM Stock,SType_UserConfig WHERE typeId=@TypeId AND Stock.STypeID=SType_UserConfig.StypeId AND Value=1)
			--BEGIN
			--	RAISERROR('该仓库的分支机构已经开账，禁止修改其分支机构',16,1)
			--	RETURN
			--END		
		INSERT INTO #StockSon SELECT typeId FROM Stock WHERE typeId LIKE @ID AND sonnum=0 
		--期初序列号
		IF EXISTS(SELECT * FROM gp_initPtypeSerial,#StockSon WHERE KtypeID<>'10000' AND (KtypeID=TypeID OR KtypeID=@TypeId))
			BEGIN
				--判断1
				RAISERROR('该仓库的分支机构已经被期初关联，禁止修改该仓库的分支机构',16,1)
				RETURN
				--判断2
				SELECT TOP 1 STypeId=@SStypeID FROM gp_initPtypeSerial WHERE KtypeID=@TypeId
				SET @Count=(SELECT  COUNT (DISTINCT KtypeID) FROM gp_initPtypeSerial WHERE STypeId=@SStypeID)
				IF @Count=1
					BEGIN
						RAISERROR('期初序列号管理：该仓库所属的分支机构只有一个下属仓库，禁止修改其分支机构',16,1)
					END
			END
		
		--期初库存
		IF EXISTS(SELECT TypeID FROM IniGoodsStocks,#StockSon WHERE (KtypeId=TypeID OR @TypeId=KtypeId) AND Qty>0)
			BEGIN
				RAISERROR('该仓库或其子结点期初库存不为0，禁止修改其分支机构',16,1)
				RETURN
			END
		--期初判断
		IF EXISTS(SELECT * FROM Wx_iniGoodsStocks,#StockSon WHERE KTypeId=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已经关联维修品库存期初，禁止修改其分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM IniGoodsLend,#StockSon WHERE KtypeId=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已经关联借欠期初，禁止修改其分支机构',16,1)
				RETURN
			END
		--单据表头
		IF EXISTS(SELECT * FROM BillIndex,#StockSon WHERE TypeID=ktypeid OR TypeID=ktypeid2 OR TypeID=KTypeID3)
			BEGIN
				RAISERROR('该仓库或其子结点已经被单据使用，禁止修改该仓库的分支机构',16,1) 
				RETURN
			END
		IF EXISTS(SELECT ktypeid FROM OrderIndex,#StockSon WHERE ktypeid=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已经被单据使用，禁止修改该仓库的分支机构',16,1) 
				RETURN
			END
		IF EXISTS(SELECT ktypeid,ktypeid2 FROM LendIndex,#StockSon WHERE #StockSon.TypeID=ktypeid OR #StockSon.TypeID=ktypeid2)
			BEGIN
				RAISERROR('该仓库或其子结点已经被单据使用，禁止修改该仓库的分支机构',16,1) 
				RETURN
			END
		--单据表体(销售类)
		IF EXISTS(SELECT * FROM OrderBill,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联销售订单或采购订单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM SaleBill,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联销售出库单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM SaleGoodsExchangeBill,#StockSon WHERE KTypeID=TypeID OR KTypeID2=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联销售换货单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM SaleBackBill,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联销售退货单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM CommissionBill,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联委托代销单据，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		--单据表体(采购类)
		IF EXISTS(SELECT * FROM BuyBill,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联采购入库单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM BuybackBill,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联采购退货单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM BuyGoodsExchangeBill,#StockSon WHERE KTypeID=TypeID OR KTypeID2=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联采购换货单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		--单据表体(库存类)
		IF EXISTS(SELECT * FROM StypeMoveBill,#StockSon WHERE KTypeID=TypeID OR KTypeID2=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联分支机构调拨出库单或分支机构调拨入库单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM DisassembleBill,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联生产拆装单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		IF EXISTS(SELECT * FROM StockCheckIndex,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已经关联库存盘点单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		--IF EXISTS(SELECT * FROM OverFlowBill,#StockSon,Stock WHERE OverFlowBill.Stypeid=Stock.STypeID AND #StockSon.TypeID=Stock.typeId)
		--	BEGIN
		--		RAISERROR('该仓库或其子结点已关联报溢单，禁止修改该仓库的分支机构',16,1)
		--		RETURN
		--	END
		--单据表体(会员类)
		IF EXISTS(SELECT * FROM IntegralExchangeBill,#StockSon WHERE KTypeID=TypeID)
			BEGIN
				RAISERROR('该仓库或其子结点已关联积分兑换单，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
	    --库存期初
		IF EXISTS(select Ktypeid from IniGoodsStocks where Ktypeid=@TypeId and (qty<>0  or total<>0))
			BEGIN
				RAISERROR('该仓库已有库存期初，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		--关联POS
		IF EXISTS(select Ktypeid from PosInfo where Ktypeid LIKE @TypeId+'%')
			BEGIN
				RAISERROR('该仓库或其子节点关联POS，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
		--关联POS
		IF EXISTS(select Ktypeid from PriceRule_Detail_KConfig where Ktypeid=@TypeId)
			BEGIN
				RAISERROR('该仓库已在取价规则设置中使用，禁止修改该仓库的分支机构',16,1)
				RETURN
			END
	END
--判断结束
DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

UPDATE	[dbo].[Stock] 
SET 	[FullName]  = @FullName,
		[Name]  = @name,
		[UserCode]  = @UserCode,
		[Comment]  = @Comment ,
		[LinkMan]=@LinkMan,
		[Tel]=@Tel,
		[Add]=@Address,
		[PyCode] =@returnPym,
		[STypeID]=@STypeID,
		[job] = @job,
		[mobile] = @mobile,
		[sheng] = @sheng,
		[shi] = @shi,
		[xian] = @xian,
		[postcode] = @postcode
WHERE 	([typeId]  = @typeId)

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM Stock

DECLARE @sonnum VARCHAR(200)
SELECT @sonnum=sonnum FROM stock  WHERE typeId=@TypeId
IF(@sonnum>0)UPDATE Stock SET STypeID = @STypeID,XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId like @TypeId+'%'

UPDATE Stock SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId

PRINT(@sonnum)
DROP TABLE #StockSon


GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateL]
GO






















/****** Object:  Stored Procedure dbo.Gp_UpdateK    Script Date: 2002-6-20 10:14:51 ******/



CREATE       PROCEDURE [Gp_UpdateL]
(
 @TypeId  [varchar](50),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @SimpleName   [varchar](30),
 @Comment  [varchar](256),
 @PyCode   varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON 
if exists(select usercode from LType where (usercode=@usercode  or fullname=@fullname) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -3
end
if exists(select usercode from LType where (usercode=@fullname  or fullname=@usercode) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -10
end

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

UPDATE [dbo].[LType] 
SET  [FullName]  = @FullName,
  [Name]  = @simplename,
  [UserCode]  = @UserCode,
  [Comment]  = @Comment,
  [PyCode] = @returnPym

WHERE 
 ( [typeId]  = @typeId )
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_updateLd]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_updateLd]
GO














CREATE   PROCEDURE [Gp_updateLd] 

--@encode$--
AS

set nocount on

declare @typeid varchar(50)
declare @Ntypeid varchar(50)
declare @SQL varchar(500)
declare @len int
SET @typeid = ''
SET @Ntypeid = ''
SET @SQL = ''


-- ========================== 仓库分类时，删掉默认的货位
SET @SQL ='declare  updateDL cursor for
		select typeid from stock where typeid  in 
			(select ktypeid as typeid 
				from ltype where sysFlag =1  and typeid<>'+char(39)+'00000'+char(39)+') 
			and sonnum<>0'

EXEC(@SQL)

open updateDL
fetch next from updateDL into @typeid
while @@fetch_status =0
	BEGIN
		DElETE from Ltype where Ktypeid =@typeid and sysFlag =1
		IF @@ROWCOUNT =1
			begin
				update Ltype set sonnum =sonnum -1 where typeid ='00000'
			end
		fetch next from updateDL into @typeid
	END
	CLOSE updateDL	-- 关闭游标
	DEALLOCATE updateDL


SET @typeid =''
SET @SQL =''




declare @j int
set @j =0

-- ========================== 插入一个仓库结点时，随即插入一个默认的货位
SET @SQL ='declare  InsertDL cursor for
		select typeid from stock where typeid not in 
			(select ktypeid as typeid 
				from ltype where sysFlag =1  and typeid<>'+char(39)+'00000'+char(39)+') 
			and sonnum=0'
EXEC(@SQL)

open InsertDL
fetch next from InsertDL into @typeid
while @@fetch_status = 0
	BEGIN
		if @j = 0 
			begin
				SELECT @Ntypeid = convert(varchar(50),convert(int,soncount)+1) from ltype where typeid ='00000'
			end 
		else
			begin
				SELECT @Ntypeid = convert(varchar(50),Convert(int,@Ntypeid)+1)
			end
		
		--print 'begin'+@Ntypeid
		SET @len = len(@Ntypeid)
		SELECT @Ntypeid =
			case  @len
				when 1  then '0000'+@Ntypeid
				when 2  then '000' +@Ntypeid
				when 3  then '00'  +@Ntypeid
				when 4  then '0'   +@Ntypeid
				else @Ntypeid
			End  
		--print 'end'+@Ntypeid
		insert into ltype values (@Ntypeid,'00000',1,0,0,@typeid,'dftLocal','默认货位','默认货位',1,0,'系统保留','MRHW')
		IF @@ROWCOUNT =1
			begin
				update Ltype set sonnum =sonnum +1,soncount = soncount +1 where typeid ='00000'
			end
		SET @j =@j + 1
		fetch next from InsertDL into @typeid
	END
	CLOSE InsertDL	-- 关闭游标
	DEALLOCATE InsertDL	



return 0
--FETCH NEXT FROM Rows_Cursor INTO















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateLim]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateLim]
GO













/****** Object:  Stored Procedure dbo.Gp_UpdateLim    Script Date: 2002-6-20 10:14:51 ******/

/*
   按照职员的特性筛选登陆用户
   成都任我行软件公司Copy Right --刘畅
   20001-12-25 圣诞节
   参数：
     @ETypeID  操作员ID 及其管辖的职员(用于分级管理暂封)
     @BTypeID(@BTypeCode), @BTypeName 职员所在单位 
     @UserCode 职员的编号
     @FullName 职员的全名
     @FiltVal  其他过滤条件
     @OrderBy  排序字段
*/
-- 返回 -1 往来单位名称不正确
CREATE        PROCEDURE Gp_UpdateLim 
(
	@ETypeID	VARCHAR(50)='',
	@Lim		VARCHAR(MAX)='',
	@BTypeCode	VARCHAR(26)='',
	@BTypeName	VARCHAR(66)='',
	@UserCode	VARCHAR(26)='',
	@FullName	VARCHAR(66)='',
	@FiltVal	VARCHAR(512)='',
	@operator	VARCHAR(50),
	@optype		VARCHAR(50)=''
)
--@encode$--
AS
SET NOCOUNT ON
IF @Lim='' RETURN -1
DECLARE 
	@SQLText	VARCHAR(MAX)='',
	@SQLFrom	VARCHAR(4000)='',
	@SQLWhere	VARCHAR(2000)='AND e.[TypeID]<>''00000''',
	@BTYPEID_U	VARCHAR(50)


SELECT etypeid,lim INTO #OldLoginUser FROM LoginUser


SELECT
	@BTypeCode=LTRIM(RTRIM(ISNULL(@BTypeCode,''))),
	@BTypeName=LTRIM(RTRIM(ISNULL(@BTypeName,''))),
	@UserCode=LTRIM(RTRIM(ISNULL(@UserCode,''))),
	@FullName=LTRIM(RTRIM(ISNULL(@FullName,''))),
	@FiltVal=LTRIM(RTRIM(ISNULL(@FiltVal,'')))

IF (@ETypeID<>'00000') AND (@ETypeID<>'00001')
	SELECT @SQLWhere = ' AND e.[TypeID] LIKE ''' + @ETypeID + '%'' '
	
IF LTRIM(@BTypeCode) <> ''
	SELECT @SQLWhere = ' AND (b.[UserCode] LIKE ''' + @BTypeCode + '%'' OR b.[TypeID] = ''' + @BTypeCode + ''') '
	
IF LTRIM(@BTypeName) <> ''
	SELECT @SQLWhere = ' AND b.[FullName] LIKE ''' + @BTypeName + '%'' '
	
IF LTRIM(@UserCode) <> ''
	SELECT @SQLWhere = ' AND (e.[UserCode] LIKE ''%' + @UserCode + '%'' OR e.[TypeID] = ''' + @UserCode + ''') '
	
IF LTRIM(@FullName) <> ''
	SELECT @SQLWhere = ' AND e.[FullName] LIKE ''%' + @FullName + '%'' '
	
-- 过滤
IF RTRIM(@FiltVal)<>''
	BEGIN
		-- 符号变换
		SELECT @FiltVal = REPLACE(@FiltVal,'~','''')
		SELECT @FiltVal = REPLACE(@FiltVal,'$','%')
		SELECT @FiltVal = REPLACE(@FiltVal,'{','>')
		SELECT @FiltVal = REPLACE(@FiltVal,'}','<')
		
		IF CHARINDEX('AND',LTRIM(UPPER(@FiltVal))) = 1
			SELECT @SQLWhere = @SQLWhere + ' ' + @FiltVal
		ELSE
			SELECT @SQLWhere = @SQLWhere + ' AND ' + @FiltVal
	END
	
SELECT @SQLWhere+=' AND e.[TypeID]<>''00001'' '

IF @optype='ispos'
	SET @SQLWhere+=' AND l.ispos=1 AND l.iserp<>1 '
	
IF @optype='iserp'
	SET @SQLWhere+=' AND l.iserp=1 '

-- 去掉多余的 AND
IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + Right(@SQLWhere,LEN(@SQLWhere)-4)
	
-- 建立结果集From
SELECT @SQLFrom = ' FROM [employee] e JOIN [btype] b ON (e.[BTypeID]=b.[TypeID]) '
		+ ' JOIN [Loginuser] l ON (e.[TypeID]=l.[ETypeID]) '
-- 
SELECT @SQLText = 'UPDATE [Loginuser] SET [Lim]= ''' + @Lim +''' '
		+ @SQLFrom
		+ @SQLWhere
Exec(@SQLText)

IF @ETypeID <> '' AND @ETypeID <> '00001'
BEGIN
	IF SUBSTRING(@Lim,480,1) <> '1'
	BEGIN
		UPDATE	LoginUser
		SET		InfoFixUp = ''
		WHERE	ETypeID = @ETypeID
	END
END
--print @SQLText

--判断安全钥匙级别
DECLARE @UserRank1 Bit		--系统重建
DECLARE @UserRank2 Bit		--系统配置
DECLARE @UserRank3 Bit		--年结存



IF @ETypeID <> ''	--个人
BEGIN
	Exec @UserRank1 = GP_CheckLimit @ETypeID,107
	Exec @UserRank2 = GP_CheckLimit @ETypeID,121
	Exec @UserRank3 = GP_CheckLimit @ETypeID,105

	IF @UserRank1=1 And @UserRank2=1 And @UserRank3=1 
	BEGIN
		UPDATE LoginUser
		SET UserRank = 0		--普通锁
		WHERE ETypeID = @ETypeID  
	END
	ELSE
	BEGIN
		UPDATE LoginUser
		SET UserRank = 1		--高级锁
		WHERE ETypeID = @ETypeID 
	END
END
ELSE		--批量
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL=''
	SELECT Top 1 @ETypeID=ETypeID From LoginUser Where ETypeID <> '00001' And ETypeID <> '00000'

	Exec @UserRank1 = GP_CheckLimit @ETypeID,107
	Exec @UserRank2 = GP_CheckLimit @ETypeID,121
	Exec @UserRank3 = GP_CheckLimit @ETypeID,105

	IF @UserRank1=1 And @UserRank2=1 And @UserRank3=1 
	BEGIN
		SET @SQL='
		UPDATE LoginUser
			SET UserRank = 0		--普通锁
			WHERE  ETypeID <> ''00001'' And ETypeID <> ''00000''
			'
		IF @optype='ispos'
			SET @SQL=@SQL+' AND isPos=''1'' AND isErp<>''1'' '
		ELSE
			SET @SQL=@SQL+'AND isErp=''1'' '
	END
	ELSE
	BEGIN
		SET @SQL='
		UPDATE LoginUser
			SET UserRank = 1		--普通锁
			WHERE  ETypeID <> ''00001'' And ETypeID <> ''00000''
			'
		IF @optype='ispos'
			SET @SQL=@SQL+' AND isPos=''1'' AND isErp<>''1'' '
		ELSE
			SET @SQL=@SQL+'AND isErp=''1'' '
	END
END

BEGIN --写入权限变更日志
	INSERT INTO LimitLog
	(
		Operator,
		Etypeid,
		oldlim,
		newlim,
		ChangeDatetime,
		ChangeEvent
	)
	SELECT	@operator,
			l.etypeid,
			O.lim,
			L.lim,
			GETDATE(),
			'权限修改'
	FROM #OldLoginUser o
	INNER JOIN loginuser l ON L.etypeid=o.etypeid AND L.lim<>O.lim
END;

--更新pos下载数据
EXEC Gp_DataSaveForPosDown '-99999','loginuser','0'






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateLocalIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateLocalIndex]
GO












/****** Object:  Stored Procedure dbo.GP_UpdateLocalIndex    Script Date: 2003-12-26 16:47:40 ******/

/****** Object:  Stored Procedure dbo.GP_UpdateLocalIndex    Script Date: 2003-12-23 12:04:41 ******/

/****** Object:  Stored Procedure dbo.GP_UpdateLocalIndex    Script Date: 2003-12-19 13:41:37 ******/
/*
	--编程：Roamer Wu
	--时间：2003-12-29
	--功能：修改货位单据的索引
*/
CREATE       PROCEDURE GP_UpdateLocalIndex
(
	@BillNumberID		numeric(18, 0),
	@BillType		 numeric(4, 0),
	@BillCode		 varchar (200),
	@BillDate		 datetime,
	@ETypeID		 varchar (50),
	@KTypeID		 varchar (50),
	@IfCheck		 varchar (50),
	@TotalQty		  NUMERIC(24, 10) ,
	@BID			  NUMERIC(24, 10) ,
	@BCode			 varchar (50),
	@Period			 smallint,
	@Comment		 varchar (256),
	@Explain		 varchar (256),
	@RedWord		 int,
	@Draft			 bit,
--	@ETypeID1		 varchar (50),	--原始制单人
	@EtypeID2		 varchar (50)	  
)
--@encode$--
AS
SET NOCOUNT ON

Update	LocalIndex
Set 
	BillType	 = @BillType,
	BillCode	 = @BillCode,
	BillDate	 = @BillDate,
	ETypeID		 = @ETypeID,
	KTypeID		 = @KTypeID,
	IfCheck		 = @IfCheck,
	TotalQty	 = dbo.F_RoundQty(@TotalQty),
	BID		 = @BID,
	BCode		 = @BCode,
	Period		 = @Period,
	Comment		 = @Comment,
	Explain		 = @Explain,
	RedWord		 = @RedWord,
	Draft		 = @Draft,
--	@ETypeID1		 varchar (50),	--原始制单人
	EtypeID2	 = @EtypeID2
Where	BillNumberID	 = @BillNumberID










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateMange]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateMange]
GO

CREATE     PROCEDURE Gp_UpdateMange
(
	@szETypeID	VARCHAR(50),
	@sztypeId	VARCHAR(50) ,
	@szMode		VARCHAR(1)
)
--@encode$--
AS
SET NOCOUNT ON 
IF @szMode = 'B' 
	UPDATE loginuser SET mangerbtypeid=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'G' 
	UPDATE loginuser SET mangerbtypeid2=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'P' 
	UPDATE loginuser SET mangerptypeid=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'E' 
	UPDATE loginuser SET mangeretypeid=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'K' 
	UPDATE loginuser SET mangerktypeid=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'A' 
	UPDATE loginuser SET mangeratypeid=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'F' 
	UPDATE loginuser SET MangerExpense=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'S' 
	UPDATE loginuser SET MangerIncome=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'C' 
	UPDATE loginuser SET MangerCpaital=@sztypeId WHERE etypeid=@szETypeID
IF @szMode = 'D'
	UPDATE loginuser SET MangerDTypeId=@sztypeId WHERE etypeid=@szETypeID
/*	
IF @szMode = 'S'
	UPDATE loginuser SET MangerSTypeId=@sztypeId WHERE etypeid=@szETypeID
*/	
--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_MenuTemplateConfig' AND ss.name=N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateMenuTemplateConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)	
		DROP PROC [dbo].[Gp_UpdateMenuTemplateConfig]--删除此存储过程的引用
	
	DROP TYPE [dbo].Type_MenuTemplateConfig 
END
GO

CREATE TYPE Type_MenuTemplateConfig AS TABLE					
(
	MenuID		INT			NOT NULL,
	Caption		VARCHAR(50)	NOT NULL,
	Name		VARCHAR(50) NOT NULL,
	IsChecked	INT			DEFAULT(0)
)
GO


IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateMenuTemplateConfig]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_UpdateMenuTemplateConfig]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	修改模板设置数据 
-- 时间：	2016-01-25
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_UpdateMenuTemplateConfig
(
	@ConfigTable Type_MenuTemplateConfig READONLY
)
--@encode$--

AS
SET NOCOUNT ON

UPDATE MenuTemplateConfig  SET IsChecked=C.IsChecked
FROM MenuTemplateConfig T
INNER JOIN @ConfigTable C ON C.MenuID=T.MenuID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateModflyAccount]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROC [dbo].Gp_UpdateModflyAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	增加本位币信息
-- 时间：	2012-04-24
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_UpdateModflyAccount
(
	@bwbcode			VARCHAR(200),		--本位币编号
	@bwbcodefullname	VARCHAR(200),		--本位币名称
	@aloneusebsys		INT					--独立使用业务系统
	
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN TRANSACTION
DECLARE @error int=0
IF EXISTS(SELECT TOP 1 1 FROM Ac_Currency WHERE Sysrow=1 AND Deleted=0)
	BEGIN
		UPDATE Ac_Currency 
		SET 
			UserCode=@bwbcode,
			FullName=@bwbcodefullname
		WHERE Sysrow=1
	END
ELSE
	BEGIN
		INSERT INTO Ac_Currency
		(
			UserCode,
			FullName,
			Rate,
			BasisType,
			Deleted,
			Sysrow
		)
		VALUES
		(
			@bwbcode,
			@bwbcodefullname,
			1
			,
			0
			,
			0,
			1
		)
	END
set @error+=@@ERROR
IF(@aloneusebsys=1)
	UPDATE sysdata SET SubValue='1' WHERE SubName='postingparameter'--凭证生成方式 业务单据财务过账
set @error+=@@ERROR
IF(@error<>0)
	BEGIN
		ROLLBACK TRAN
		RAISERROR('信息保存发生错误!请确认后重试!',16,1)
	END
ELSE COMMIT TRAN

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateMulColAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateMulColAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/23
	Description	: 保存多栏账设计方案
*/

CREATE PROCEDURE Gp_UpdateMulColAccount
(
	@STypeId								VARCHAR(50),    --分支机构id
	@ATypeId								VARCHAR(50),	--科目id
	@Accountname							VARCHAR(200),	--方案名称
	@Ascid									VARCHAR(50),	--辅助核算项id
	@Cids									VARCHAR(50),	--币别id	
	@Comment								VARCHAR(500),	--备注
	@Assistid								BIGINT,			--设计方案id,新增0，修改时本身的id
	@Flag                                   INT,			--0是明细科目,1是非明细科目
	@Creator								VARCHAR(50),
	@CreatorStypeId							VARCHAR(50),
	@IsPublic								BIT,
	@AllData	Type_MulColInfor  			READONLY		--辅助核算项目数据
)
--@encode$--
AS
SET NOCOUNT ON 
IF EXISTS(SELECT TOP 1 1 FROM SType WHERE TypeId=@STypeId AND deleted=1)
	BEGIN
		RAISERROR('分支机构已被停用，不能进行操作！',16,0)
		RETURN
	END

DECLARE @errorSum		INT,
		@NewId			BIGINT

BEGIN TRANSACTION
	IF @Assistid>0    --修改
		BEGIN
			UPDATE AC_MULCOLUMNACCOUNT SET STYPEID=@STypeId,
										   ATYPEID=@ATypeId,
										   ACCOUNTNAME=@Accountname,
										   Ascid=@Ascid,
										   Cids=@Cids,
										   COMMENT=@Comment,
										   Flag=@Flag,
										   IsPublic=@IsPublic
			WHERE ASSISTID=@Assistid
			Set @errorSum=@errorSum+@@error
										   
			DELETE FROM AC_MULCOLUMNACCOUNT_ASSIST WHERE ASSISTID=@Assistid
			Set @errorSum=@errorSum+@@error	  
			
			INSERT INTO AC_MULCOLUMNACCOUNT_ASSIST 
			(
			  ASSISTID,
			  FDC,
			  FVALUE
			)
			SELECT @Assistid,
				   FDC,
				   FVALUE
			FROM @AllData
			Set @errorSum=@errorSum+@@error	  
		END
	ELSE
		BEGIN	
			--新增
			INSERT INTO AC_MULCOLUMNACCOUNT 
			(
				STYPEID,
				ATYPEID,
				ACCOUNTNAME,
				ASCID,
				CIDS,
				COMMENT,
				FLAG,
				CREATOR,
				CREATORSTYPEID,
				ISPUBLIC
			)
			VALUES
			(
				@STypeId,
				@ATypeId,
				@Accountname,
				@Ascid,
				@Cids,
				@Comment,
				@Flag,
				@Creator,
				@CreatorStypeId,
				@IsPublic
			)
			Set @errorSum=@errorSum+@@error	  
			SELECT @NewId=SCOPE_IDENTITY() FROM AC_MULCOLUMNACCOUNT
			
			INSERT INTO AC_MULCOLUMNACCOUNT_ASSIST 
			(
			  ASSISTID,
			  FDC,
			  FVALUE
			)
			SELECT @NewId,
				   FDC,
				   FVALUE
			FROM @AllData
			Set @errorSum=@errorSum+@@error	  
		END
		
	IF @errorSum<>0  --如果有错误
		BEGIN
			 ROLLBACK TRANSACTION 
			 RETURN 0
		END  
	ELSE
		BEGIN
			COMMIT TRANSACTION 
			RETURN 1
		END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateNewTCDataIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateNewTCDataIndex]
GO

CREATE     PROCEDURE [Gp_UpdateNewTCDataIndex]
(
	@BillNumberId  		[numeric](10,0),
	@BillCode [varchar](200) ,  
    @BillDate [datetime] ,
    @CommissionStart	DATETIME =NULL,			 --提成开始
	@CommissionEnd	DATETIME =NULL,			 --提成结束
	@CommissionSchemeID	NUMERIC(18,0),
    --@Checke VARCHAR(50) ,				--制单人
	--@Checker					VARCHAR(50) = '',	--审核人
	--@CheckerTime				DATETIME ,		    --审核时间
	@Explain					VARCHAR(256)='' ,	--说明
	@Comment					VARCHAR(256)='' ,	--摘要
	@IsAuto					INT,	 						--自动生成  0=手动 1=自动
	@stypeid				varchar(50),
	@ifcheck				CHAR(1),
	@commissiontotal	 NUMERIC(24, 10) ,
	@total  NUMERIC(24, 10) ,
	@qty  NUMERIC(24, 10) 
)
--@encode$--
AS 
SET NOCOUNT ON 

IF @BillNumberId > 0
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM CommissionBillNew WHERE  ifcheck='t' AND [BillNumberId]  = @BillNumberId
			  UNION ALL 
			  SELECT TOP 1 1 FROM dbo.ListTable WHERE BillNumberId=@BillNumberId AND BillType=311
			  UNION ALL 
			  SELECT TOP 1 1 FROM dbo.InOutstocktable WHERE BillNumberId=@BillNumberId AND BillType=311)
		RETURN -1 
END


IF NOT EXISTS(SELECT TOP 1 1 FROM CommissionBillNew WHERE BillNumberID = @BillNumberID)
	RETURN -7
	
DECLARE @BeginDate DATETIME ,
        @szItem VARCHAR(30) ,
        @szVchCode VARCHAR(30),
        @szPeriod SMALLINT
    EXEC Gp_GetSubValue 'period', @STypeID, @szPeriod OUT
    SELECT TOP 1
            @BeginDate = startdate
    FROM    monthproc
    WHERE   period = @szPeriod

IF @BillDate < @BeginDate
                BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
                    RETURN -2
                END

IF NOT EXISTS ( SELECT TOP 1
                                            1
                                    FROM    AuditingFlowSet
                                    WHERE   BillType = 311
                                            AND IfUse = 1
                                            AND LEFT(AuditingReason, 1) <> 1 )	--检查单据是否有审核流程
                        BEGIN
                            DECLARE @CurDate DATETIME
                            DECLARE @IsOrNotPassOneDay BIT
                            SELECT  @CurDate = GETDATE()
                            SELECT TOP 1
                                    @IsOrNotPassOneDay = value
                            FROM    UserConfig
                            WHERE   ConfigName = 'PassOneDay'
                            IF ( CONVERT(DATETIME, @BillDate) <> CONVERT(DATETIME, CONVERT(VARCHAR, YEAR(@CurDate))
                                 + '-' + CONVERT(VARCHAR, MONTH(@CurDate))
                                 + '-' + CONVERT(VARCHAR, DAY(@CurDate))) )
                                AND ( @IsOrNotPassOneDay = 1 ) 
                                BEGIN 
				--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
                                    RETURN -3
                                END
                        END
		--有审核流程单据，第一次录单时需要和当前日期一致
                    ELSE 
                        BEGIN
                            SELECT  @CurDate = GETDATE()
                            SELECT TOP 1
                                    @IsOrNotPassOneDay = value
                            FROM    UserConfig
                            WHERE   ConfigName = 'PassOneDay'
                            IF ( CONVERT(DATETIME, @BillDate) <> CONVERT(DATETIME, CONVERT(VARCHAR, YEAR(@CurDate))
                                 + '-' + CONVERT(VARCHAR, MONTH(@CurDate))
                                 + '-' + CONVERT(VARCHAR, DAY(@CurDate))) )
                                AND ( @IsOrNotPassOneDay = 1 ) 
                                BEGIN 
				--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
                                    RETURN -3
                                END
                        END


DELETE FROM dbo.Custom_BillDetails WHERE BillId=@BillNumberId AND BillType=311
DELETE FROM dbo.Custom_BillIndex WHERE BillId=@BillNumberId AND BillType=311
UPDATE [dbo].[CommissionBillNew] 
SET     
		[BillCode]  = @BillCode,
		[BillDate]  = @BillDate,
		CommissionStart = @CommissionStart	,	
		CommissionEnd = @CommissionEnd,			
		CommissionSchemeID = @CommissionSchemeID,
		--[checke]  = @checke,
		Explain=@Explain,
		[Comment]  = @Comment,
		IsAuto=@IsAuto,
		stypeid = @stypeid,
		[ifcheck]  = @ifcheck,
		commissiontotal=dbo.F_RoundTotal(@commissiontotal),
		Total=dbo.F_RoundTotal(@total),
		qty=dbo.F_RoundQty(@qty),
		draft=1
WHERE 	[BillNumberId]  = @BillNumberId

--PRINT @@rowCount
IF @@rowcount =0  OR @@error<>0
--RAISERROR('更新数据表发生错误！',16,1)
	RETURN -5



------------------------------------------------------------
		declare @strSQL varchar(500)
		SET @strSQL = '
			DELETE FROM CommissionBillNewDetail
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END	
		
		--SET @strSQL = '
		--	DELETE FROM CommissionBillNewStype
		--	WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateNewTCIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateNewTCIndex]
GO

CREATE     PROCEDURE [Gp_UpdateNewTCIndex]
(
@BillNumberId  		[numeric](10,0),
@BillCode				VARCHAR(200) ,   --单据编号
@FullName				VARCHAR(200) ,   --单据名称
@BillDate				DATETIME=null ,		 --单据日期 
@RuleStart				DATETIME=null ,		 --规则开始
@RuleEnd					DATETIME=null ,		 --规则结束
@CommissionStandard		INT ,			 --提成基准  0=折后金额 1=价税合计 2=销售数量 3=销售
@SalesFlag							INT,             --促销商品标识
@BelowCostFlag					INT,			 --是否低于成本
@IsUseEtypeCommission	INT ,			 --是否使用职员提成比例 1=勾选
@ECommissionType			INT ,			 --提成人类型  0=业务员   1=上级参与提成
@CommissionStyle			INT ,			 --提成方式    0=单一提成 1=区间提成
--@Checke					VARCHAR(50) ,				--制单人
@Comment					VARCHAR(256),	--摘要
@BillState				INT ,						--单据状态  1=未审核  2=审核  3=禁用
@UseState				INT ,			--使用状态  1=未引用  2=引用  3=部分完成
@IsStop					INT ,			--是否禁用  0=正常  1/2当禁用时写入单据
@Checker				VARCHAR(50) ,	--审核人
@CheckerTime			DATETIME 		 --审核时间
)
--@encode$--
AS 
SET NOCOUNT ON 

IF NOT EXISTS(SELECT TOP 1 1 FROM CommissionRule WHERE BillNumberID = @BillNumberID)
	RETURN -7
	
IF @CheckerTime = ''
BEGIN
	SET @CheckerTime = NULL
END
	
UPDATE [dbo].[CommissionRule] 
SET     
BillCode=	@BillCode,				
FullName=	@FullName,				
BillDate=	@BillDate,				
RuleStart=	@RuleStart,				
RuleEnd=	@RuleEnd,				
CommissionStandard=	@CommissionStandard		,
SalesFlag=@SalesFlag,
BelowCostFlag=@BelowCostFlag,
IsUseEtypeCommission=	@IsUseEtypeCommission	,
ECommissionType	=	@ECommissionType		,
CommissionStyle	=	@CommissionStyle		,
--Checke	=	@Checke					,
--CheckeTime=	@CheckeTime				,
Comment	=	@Comment				,
BillState=	@BillState				,
UseState	=	@UseState				,
IsStop	=		@IsStop					,
Checker = @Checker,
CheckerTime = @CheckerTime
		
WHERE 	BillNumberID  = @BillNumberId

--PRINT @@rowCount
IF @@rowcount =0  OR @@error<>0
--RAISERROR('更新数据表发生错误！',16,1)
	RETURN -5
	
	------------------------------------------------------------
		declare @strSQL varchar(500)
		SET @strSQL = '
			DELETE FROM CommissionRuleEtype
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END	
		
		SET @strSQL = '
			DELETE FROM CommissionRulePtype
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END	
		
		SET @strSQL = '
			DELETE FROM CommissionRuleRegion
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END	
		
		SET @strSQL = '
			DELETE FROM CommissionRuleLeader
			WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
		EXEC(@strSQL)
		IF @@ERROR <> 0
		BEGIN
			--RAISERROR('删除单据发生错误',16,1)
			RETURN -6
		END	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateOM_LoginUsers]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_UpdateOM_LoginUsers]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：鲁大林
	日期：2012-4-16
	描述：更新OM系统操作员
*/
CREATE PROCEDURE Gp_UpdateOM_LoginUsers
(
	@typeid VARCHAR(50),				--操作员id
	@btypeid VARCHAR(50)=NULL,			--往来单位
	@usercode VARCHAR(50)=NULL,			--操作员账号
	@username VARCHAR(50)=NULL,			--姓名
	@date VARCHAR(50)=NULL,				--注册时间
	@level INT,							--等级
	@telephone VARCHAR(50)=NULL,		--联系座机
	@qq VARCHAR(50)=NULL,				--QQ
	@email VARCHAR(50)=NULL,			--电子邮件
	@mobilephone VARCHAR(50)=NULL,		--联系手机
	@lim VARCHAR(5000)=NULL,			--权限
	@password VARCHAR(10)=NULL			--密码
)
--@encode$--
AS
-----------------------------------判断是否存在当前的用户(如果不存在，返回-1)------------------
IF NOT EXISTS(SELECT * FROM OM_LoginUsers WHERE TypeID=@typeid)
BEGIN
	RETURN -1
END
------------------------------------判断是否存在账号(如果存在，返回-2)----------------------------
IF EXISTS(SELECT * FROM OM_LoginUsers WHERE UserCode=@usercode AND TypeID<>@typeid)
BEGIN
	RETURN -2
END
SET NOCOUNT ON
------------------------------------执行修改的操作-----------------------------------
UPDATE OM_LoginUsers
SET
	BtypeID=@btypeid,
	UserCode=@usercode,
	UserName=@username,
	[Date]=@date,
	[Level]=@level,
	TelePhone=@telephone,
	QQ=@qq,
	Email=@email,
	MobilePhone=@mobilephone,
	Lim=@lim,
	[Password]=@password
WHERE TypeID=@typeid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateOMBackBillQty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_UpdateOMBackBillQty]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


/*	
		hanlin
		OM商品退货回写
*/



CREATE  PROCEDURE [dbo].[Gp_UpdateOMBackBillQty]
(
	@billnumberid int
)
--@encode$--
AS
SET NOCOUNT ON

	IF NOT EXISTS(SELECT 1 FROM dbo.saleBackBill WHERE BillNumberId=@billnumberid AND OMBillID<>0)
		RETURN

	IF EXISTS(
			SELECT 1 FROM dbo.OM_BackOrderDetail a
			INNER JOIN dbo.saleBackBill b
			ON a.ID=b.OMBillID
			WHERE b.BillNumberId=@billnumberid
			AND a.[STATUS] IN(1,2) 
		)
	BEGIN
		RAISERROR('单据所引用的OM单据有明细已中止或者已完成，请刷新OM单据列表后重新生成退货单！',16,1)
		RETURN
	END


	
	
	--审核通过的退货单数量大于或等于前台退货单数量为完成状态2 否则为状态'已开单未完成' 3
    UPDATE dbo.OM_BackOrderDetail SET ReachQty=(ReachQty+s.mqty),
							[STATUS]=(CASE WHEN ReachQty+s.mqty >= OM_BackOrderDetail.qty THEN 2 ELSE 3 END) FROM dbo.saleBackBill  s
    WHERE s.OMBillID=OM_BackOrderDetail.ID and s.billnumberid=@billnumberid
    
 
	IF @@ERROR <>0
		RAISERROR('回写OM退货数量失败！',16,1)
		
	


GO






/****** Object:  StoredProcedure [dbo].[Gp_UpdateOMBillQty]    Script Date: 08/21/2014 14:47:37 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateOMBillQty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_UpdateOMBillQty]
GO


/****** Object:  StoredProcedure [dbo].[Gp_UpdateOMBillQty]    Script Date: 08/21/2014 14:47:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*	
		hanlin
		OM商品发货回写
*/



CREATE  PROCEDURE [dbo].[Gp_UpdateOMBillQty]
(
	@billnumberid int
)
--@encode$--
AS
SET NOCOUNT ON

	IF NOT EXISTS(SELECT 1 FROM dbo.SaleBill WHERE BillNumberId=@billnumberid AND OMBillID<>0)
		RETURN

	IF EXISTS(
			SELECT 1 FROM dbo.OM_OrderDetail a
			INNER JOIN SaleBill b
			ON a.ID=b.OMBillID
			WHERE b.BillNumberId=@billnumberid
			AND a.STATUS IN(4,5) 
		)
	BEGIN
		RAISERROR('单据所引用的OM单据有明细已中止或者已完成，请刷新OM单据列表后重新生成出库单！',16,1)
		RETURN
	END


	
	--IF EXISTS(SELECT 1 FROM dbo.OMBill o INNER JOIN dbo.SaleBill s ON s.OMBillID=o.ID WHERE o.qty<o.ReachQty+s.MQty AND s.BillNumberId=@billnumberid)
	--BEGIN
	--	RAISERROR('单据过账后将造成OM发货数量超过购买数量，请修改后重试',16,1)
	--	RETURN
	--END
	
	INSERT INTO dbo.OM_Shipments
	( 
		OMBillID , 
		GoodsBillID ,
		ReachQty 
	)
	SELECT	OMBillID,
			id,
			mqty 
	FROM dbo.SaleBill 
	WHERE BillNumberId=@billnumberid
	
	
	
    UPDATE dbo.OM_OrderDetail SET ReachQty=(ReachQty+SaleBill.mqty) ,STATUS=2 FROM dbo.SaleBill 
    WHERE SaleBill.OMBillID=OM_OrderDetail.ID and SaleBill.billnumberid=@billnumberid
    
    
    --更改订单发货状态
    IF not EXISTS(
			SELECT 1 FROM dbo.OM_OrderDetail 
			WHERE [STATUS]=0 and billNumberId IN
			(
				SELECT a.billNumberID FROM dbo.OM_OrderDetail a
				INNER JOIN SaleBill b
				ON a.ID=b.OMBillID
				WHERE b.BillNumberId=@billnumberid
			)
		)
    BEGIN
         UPDATE dbo.OM_Order SET [status]=2 
         WHERE id IN
         (
				SELECT a.billNumberID FROM dbo.OM_OrderDetail a
				INNER JOIN SaleBill b
				ON a.ID=b.OMBillID
				WHERE b.BillNumberId=@billnumberid
		  )
    END
	
	IF @@ERROR <>0
		RAISERROR('回写OM发货数量失败！',16,1)
		
	

GO





/****** Object:  StoredProcedure [dbo].[Gp_UpdateSAtype]    Script Date: 06/06/2012 09:56:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateORAddDefaultStock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateORAddDefaultStock
GO

--作    者：蒋奎
--日    期：2014-12-15  
--作    用：修改或添加默认仓库




CREATE     PROCEDURE [dbo].Gp_UpdateORAddDefaultStock
(
	@Ptypeid		VARCHAR(50),		--商品id
	@stypeid		VARCHAR(50),		--分支机构id
	@ktypeid 		VARCHAR(50),		--仓库id
	@CargoId 		VARCHAR(50) = ''	--货位id
	
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN 
	IF @ktypeid <>''
	BEGIN	
		IF NOT EXISTS(SELECT * FROM STOCK WHERE typeId=@KtypeID ) 
            BEGIN
                RAISERROR('仓库无效,请重新选择！',16,1)
                RETURN
            END
                
        IF ISNULL(@CargoID,0)<>0 AND ISNULL(@CargoID,'')<>''  AND NOT EXISTS(SELECT * FROM CargoType WHERE CargoID=@CargoID ) 
            BEGIN
                RAISERROR('货位无效,请重新选择！',16,1)
                RETURN
            END
            
        DECLARE @ErrorMsg VARCHAR(200)=''
        
        IF EXISTS(SELECT * FROM STOCK WHERE typeId=@KtypeID AND deleted=1 ) 
            BEGIN
				SELECT @ErrorMsg=FullName FROM STOCK WHERE typeId=@KtypeID AND deleted=1
				SET @ErrorMsg='【'+@ErrorMsg+'】仓库已停用，请重新选择！'
                RAISERROR(@ErrorMsg,16,1)
                RETURN
            END
        
        IF EXISTS(SELECT * FROM CargoType WHERE CargoID=@CargoID AND deleted=1 ) 
            BEGIN
				SELECT @ErrorMsg=FullName FROM CargoType WHERE CargoID=@CargoID AND deleted=1
				SET @ErrorMsg='【'+@ErrorMsg+'】货位已停用，请重新选择！'
                RAISERROR(@ErrorMsg,16,1)
                RETURN
            END
	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.DefaultStock WHERE Ptypeid=@Ptypeid AND Stypeid=@stypeid)
			BEGIN
				UPDATE DefaultStock SET ktypeid=@ktypeid,CargoId=@CargoId WHERE Ptypeid=@Ptypeid AND Stypeid=@stypeid
			END
		ELSE
			BEGIN
				INSERT DefaultStock (Ptypeid,Stypeid,ktypeid,CargoId) VALUES (@Ptypeid,@stypeid,@ktypeid,@CargoId)
			END
	END
	ELSE IF @ktypeid=''
	BEGIN
			DELETE FROM DefaultStock WHERE Ptypeid=@Ptypeid AND Stypeid=@stypeid
	END	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







/****** Object:  StoredProcedure [dbo].[Gp_UpdateSAtype]    Script Date: 06/06/2012 09:56:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateORAddInventoryType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateORAddInventoryType
GO

--作    者：魏伟
--日    期：2016-06-08  
--作    用：修改或添加默认仓库




CREATE     PROCEDURE [dbo].Gp_UpdateORAddInventoryType
(
	@Ptypeid		[varchar](50),--商品id
	@stypeid		[varchar](50),--分支机构id
	@InventoryTypeid 		[varchar](50) --存货类型id
	
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN 
	IF @InventoryTypeid <>'0' AND @InventoryTypeid<>''
	BEGIN	
		IF EXISTS(SELECT TOP 1 1 FROM dbo.PType_InventoryType WHERE Ptypeid=@Ptypeid AND Stypeid=@stypeid)
			BEGIN
				UPDATE PType_InventoryType SET InventoryTypeid=@InventoryTypeid WHERE Ptypeid=@Ptypeid AND Stypeid=@stypeid
				 
			END
		ELSE
			BEGIN
				INSERT PType_InventoryType (Ptypeid,Stypeid,InventoryTypeid) VALUES (@Ptypeid,@stypeid,@InventoryTypeid) 
			END
	END
	ELSE IF @InventoryTypeid='0' OR @InventoryTypeid=''
	BEGIN
			DELETE FROM PType_InventoryType WHERE Ptypeid=@Ptypeid AND Stypeid=@stypeid
	END	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateOrderBill]
GO




IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateOrderBillDT]') AND TYPE in (N'P', N'PC'))
	DROP PROC Gp_UpdateOrderBillDT;
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：周华
	时间：2012-05-07 11:13:50.777
	描述：采购订单，销售订单 明细查入 DT版
*/
CREATE PROCEDURE Gp_UpdateOrderBillDT
	@intFlag INT
	,@billNumberId INT
	,@billType INT
	,@tb TbType_Order READONLY
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
	IF @intFlag = 0 --插入操作
	BEGIN
		INSERT INTO OrderBill(
			BillNumberID,
			PTypeID,
			Qty,
			Price,
			Total,
			ReachQty,
			Comment,
			IsUnit2,
			Discount,
			DiscountPrice,
			TaxPrice,
			TaxTotal,
			SaleTotal,
			Tax,
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID,
			RequestBillNumberID,
			RequestBillID,
			AskBillNumberID,
			AskBillID
			
			-- 新增字段
			,TaxMoney
			,NSalePrice
			,NSaleTotal
			,NDiscountPrice
			,NTotal
			,NTaxPrice
			,NTaxTotal
			,NTaxMoney
			--,CargoId
			,UnitId
			,NUnitId
			,NQty
			,UnitRate
			,NUnitMsg
			,MUnitId
			,MQty
			,MUnitRate
			,MUnitMsg
			,MSalePrice
			,MDiscountPrice
			,MTaxPrice
			,CurMSalePrice
			,CurMDiscountPrice
			,CurMTaxPrice
			,ItemId
			,IsCombined
			,goodsnumber
			,CargoID
			,GoodsCostPrice
			,GoodsOrder 
			,ProduceDate 
			,ValidDate 
			,isrequest
			,oldcurmtaxprice
	        ,oldqty
			,entrycode
			,IsGift
			,YapiID
			,PriceSource
			,Id
			,PromoType
			,ShowOrder
			,SaleOrderId --销售订单明细行ID
			,PTCombinOrderBillDetailID  --组合品订单明细id
		) SELECT 
			@billNumberId,
			chvPTypeID,
			dbo.F_RoundQty(numQty),
			dbo.F_RoundPrice(numPrice),
			dbo.F_RoundTotal(numTotal),
			dbo.F_RoundQty(numReachQty),
			chvComment,
			intIsUnitTow,
			dbo.F_RoundDiscount(numDiscount),
			dbo.F_RoundPrice(numDiscountPrice),
			dbo.F_RoundPrice(numTaxPrice),
			dbo.F_RoundTotal(numTaxTotal),
			dbo.F_RoundTotal(numSaleTotal),
			dbo.F_RoundTax(numTax),
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID,
			requestbillnumberid,
			requestbillid,
			askbillnumberid,
			askbillid
			
			-- 新增字段
			,dbo.F_RoundTotal(TaxMoney)
			,dbo.F_RoundPrice(NSalePrice)
			,dbo.F_RoundTotal(NSaleTotal)
			,dbo.F_RoundPrice(NDiscountPrice)
			,dbo.F_RoundTotal(NTotal)
			,dbo.F_RoundPrice(NTaxPrice)
			,dbo.F_RoundTotal(NTaxTotal)
			,dbo.F_RoundTotal(NTaxMoney)
			--,CargoId
			,UnitId
			,NUnitId
			,dbo.F_RoundQty(NQty)
			,dbo.F_RoundTranslateRate(UnitRate)
			,NUnitMsg
			,MUnitId
			,dbo.F_RoundQty(MQty)
			,dbo.F_RoundTranslateRate(MUnitRate)
			,MUnitMsg
			,dbo.F_RoundPrice(MSalePrice)
			,dbo.F_RoundPrice(MDiscountPrice)
			,dbo.F_RoundPrice(MTaxPrice)
			,dbo.F_RoundPrice(CurMSalePrice)
			,dbo.F_RoundPrice(CurMDiscountPrice)
			,dbo.F_RoundPrice(CurMTaxPrice)
			,ItemId
			,IsCombined
			,goodsnumber
			,CargoID
			,dbo.F_RoundPrice(GoodsCostPrice)
			,GoodsOrder 
			,ProduceDate 
			,ValidDate 
			,isrequest
			,oldcurmtaxprice
	        ,oldqty
			,entrycode
			,IsGift
			,YapiID
			,PriceSource
			,Id
			,PromoType
			,ShowOrder
			,case when @billType=300 then -1 else SaleOrderId end as SaleOrderId
			,PTCombinOrderBillDetailID  --组合品订单明细id
		FROM @tb;
		-----------------------回写报价单的已引用数量 begin---------------------------
		IF @billType IN (300) 
		BEGIN
			UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)+dbo.F_RoundQty(t.numQty)
			FROM QuotePriceBill q INNER JOIN (SELECT SUM(numQty) AS numQty,askbillnumberid,askbillid from @tb GROUP BY askbillnumberid,askbillid) t ON q.BillNumberID=t.askbillnumberid AND q.ID=t.askbillid
			WHERE t.askbillnumberid<>0 AND t.askbillid<>0
			----引用数量最大不能超过报价单数量
			--UPDATE QuotePriceBill SET UseQty=Qty
			--WHERE BillNumberID IN (SELECT askbillnumberid FROM dbo.OrderBill WHERE billNumberID=@billNumberId ) AND UseQty>Qty
			--已被引用的报价单状态改为成交(2019-05-29主表的报价状态变为改明细表的报价状态)
			UPDATE dbo.QuotePriceBill SET IfBargainOn=1 
			WHERE ID IN (SELECT askbillid from @tb WHERE askbillnumberid<>0 AND askbillid<>0) 
			
		END
		ELSE IF @BillType IN(301)
		BEGIN
			UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)+dbo.F_RoundQty(t.numQty)
			FROM AskPriceBill q INNER JOIN (SELECT SUM(numQty) AS numQty,askbillnumberid,askbillid from @tb GROUP BY askbillnumberid,askbillid) t ON q.BillNumberID=t.askbillnumberid AND q.ID=t.askbillid
			WHERE t.askbillnumberid<>0 AND t.askbillid<>0
			--引用数量最大不能超过报价单数量
			--UPDATE AskPriceBill SET UseQty=Qty
			--WHERE BillNumberID IN (SELECT askbillnumberid FROM dbo.OrderBill WHERE billNumberID=@billNumberId ) AND UseQty>Qty
			--已被引用的询价单状态改为成交(2019-05-29主表的报价状态变为改明细表的报价状态)
			UPDATE dbo.AskPriceBill SET IfBargainOn=1 
			WHERE ID IN (SELECT askbillid from @tb WHERE askbillnumberid<>0 AND askbillid<>0) 
			
			--采购单调销售订单，回写在销售订单明细行
			UPDATE OrderBill SET SaleOrderReachQty=ISNULL(SaleOrderReachQty,0)+dbo.F_RoundQty(t.numQty)
			FROM OrderBill o INNER JOIN (SELECT SUM(isnull(numQty,0)) AS numQty,SaleOrderId from @tb GROUP BY SaleOrderId) t  ON o.ORDERID=t.saleorderid
	
	        --采购单调组合品销售订单，回写在组合品销售订单明细行2019-06-11
	        UPDATE  PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(SaleOrderReachQty,0)+dbo.F_RoundQty(t.numQty)
	        FROM PT_Combin_OrderBillDetail o
	        INNER JOIN (SELECT SUM(isnull(numQty,0)) AS numQty,PTCombinOrderBillDetailID from @tb GROUP BY PTCombinOrderBillDetailID) t 
	        ON o.ORDERID=t.PTCombinOrderBillDetailID
	        
		END
		-----------------------回写报价单的已引用数量   end---------------------------
		
		IF (SELECT IsIni FROM OrderIndex WHERE billNumberId = @BillnumberID) <> 1
		BEGIN
			--影响订单库存
			EXEC GP_Deal_OrderQTY @BillnumberID,@BillType,'+'
		END

	END
	ELSE -- 更新处理
	BEGIN
		IF (SELECT IsIni FROM OrderIndex WHERE billNumberId = @BillnumberID) <> 1
		BEGIN
			--删除订单明细影响订单库存
			EXEC GP_Deal_OrderQTY @BillnumberID,@BillType,'-'
		END
		
		---------------------------将待更新的数据引用数量减去 start-------------------------------------
		IF @billType IN (300)
		BEGIN
			UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)-ISNULL(o.Qty,0)
			FROM QuotePriceBill q INNER JOIN (select SUM(Qty) AS Qty,askbillnumberid,askbillid FROM dbo.OrderBill WHERE billNumberID=@billNumberId GROUP BY askbillnumberid,askbillid) o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.askbillid
			WHERE o.askbillnumberid<>0 AND o.askbillid<>0
		    --删除销售单引用的报价单商品明细行，只要useqty=0就回写报价单的成交状态为未成交
			UPDATE QuotePriceBill SET IfBargainOn=0 WHERE UseQty=0	
			
		END
		ELSE IF @BillType IN(301)
		BEGIN
			UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)-ISNULL(o.Qty,0)
			FROM AskPriceBill q INNER JOIN (select SUM(Qty) AS Qty,askbillnumberid,askbillid FROM dbo.OrderBill WHERE billNumberID=@billNumberId GROUP BY askbillnumberid,askbillid) o ON q.BillNumberID=o.askbillnumberid AND q.ID=o.askbillid
			WHERE o.askbillnumberid<>0 AND o.askbillid<>0	
			
			--更新销售行明细的采购数量
			UPDATE OrderBill SET SaleOrderReachQtY=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
			FROM OrderBill A JOIN (select SUM(Qty) AS Qty,SaleOrderId FROM dbo.OrderBill WHERE billNumberID=@billNumberId GROUP BY SaleOrderId) B on A.ORDERID=B.SaleOrderId
				
			--更新组合品销售订单明细行的采购数量2019-06-11
	        UPDATE  PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(A.SaleOrderReachQty,0)-ISNULL( B.qty,0)
	        FROM PT_Combin_OrderBillDetail A
	        INNER JOIN (Select SUM(Qty) AS Qty,PTCombinOrderBillDetailID from dbo.OrderBill WHERE billNumberID=@billNumberId GROUP BY PTCombinOrderBillDetailID) B
	        ON A.ORDERID=B.PTCombinOrderBillDetailID
	        
			--删除采购单引用的询价单商品明细行，只要useqty=0就回写报价单的成交状态为未成交
			UPDATE AskPriceBill SET IfBargainOn=0 WHERE UseQty=0				
		END
		---------------------------将待更新的数据引用数量减去   end-------------------------------------
		CREATE TABLE #t(id int);
		
		IF @billType=300
			BEGIN
				INSERT #t SELECT orderid FROM dbo.OrderBill a WHERE billNumberID=@billNumberId
				AND (EXISTS(SELECT 1 FROM dbo.SaleBill b JOIN billindex w ON b.BillNumberId=w.BillNumberId WHERE a.OrderID=b.OrderID AND w.RedWord=0) OR BillOver<>0 OR ReachQty > 0 OR WaitQty > 0) --被引用或被中止的明细
				INSERT #t SELECT OrderID FROM OrderBill A WHERE BillNumberID=@BillNumberID
				AND EXISTS (SELECT 1 FROM dbo.SendBill B JOIN BillIndex W ON B.BillNumberID=W.BillNumberID WHERE a.OrderID=b.orderid AND W.RedWord=0  )OR BillOver<>0 
				INSERT #t SELECT OrderID FROM OrderBill A WHERE BillNumberID=@billNumberId
			    AND EXISTS (SELECT 1 FROM dbo.CommissionBill B JOIN BillIndex W ON B.BillNumberID=W.BillNumberID WHERE a.OrderID=b.orderid AND W.RedWord=0  AND b.[Type] = 140 )OR BillOver<>0 
				INSERT #t SELECT distinct orderid FROM dbo.OrderBill a WHERE billNumberID=@billNumberId
				AND (EXISTS(SELECT 1 FROM dbo.OrderBill b where a.orderid=b.saleorderid  )
						--OR isnull(saleorderreachqty,0)<>0
					) --被采购订单调用,年结存删了单的
				
				
				
			END
		ELSE 
		BEGIN
			INSERT #t SELECT orderid FROM dbo.OrderBill a WHERE billNumberID=@billNumberId
			AND (EXISTS(SELECT 1 FROM dbo.BuyBill b JOIN billindex w ON b.BillNumberId=w.BillNumberId WHERE a.OrderID=b.OrderID AND w.RedWord=0) OR BillOver<>0 OR ReachQty > 0 OR WaitQty > 0)
			INSERT #t SELECT OrderID FROM OrderBill A WHERE BillNumberID=@BillNumberID
			AND EXISTS (SELECT 1 FROM dbo.AppraisalBill B JOIN BillIndex W ON B.BillNumberID=W.BillNumberID WHERE a.OrderID=b.orderid AND W.RedWord=0  )OR BillOver<>0 
			INSERT #t SELECT OrderID FROM OrderBill A WHERE BillNumberID=@billNumberId
			    AND EXISTS (SELECT 1 FROM dbo.CommissionBill B JOIN BillIndex W ON B.BillNumberID=W.BillNumberID WHERE a.OrderID=b.orderid AND W.RedWord=0  AND b.[Type] = 144 )OR BillOver<>0 
		
		END
		
		UPDATE A SET A.RequestQty = ISNULL( A.RequestQty ,0) - ISNULL( B.qty,0),
					 A.orderqty=ISNULL(A.orderqty,0)-ISNULL(B.Qty,0)
		FROM RequestBill A JOIN OrderBill B ON A.ID=B.RequestBillId
		WHERE @billType=301 AND b.billNumberID = @billNumberId AND B.RequestBillId<>0
		
		
		
		--1.清除没有的
		DELETE FROM dbo.OrderBill WHERE billNumberID=@billNumberId AND OrderID NOT IN (SELECT id FROM #t) 

		
		--2.插入新增的
		INSERT INTO OrderBill(
				BillNumberID,
				PTypeID,
				Qty,
				Price,
				Total,
				ReachQty,
				Comment,
				IsUnit2,
				Discount,
				DiscountPrice,
				TaxPrice,
				TaxTotal,
				SaleTotal,
				Tax,
				KTypeID,
				STypeID,
				FromBillNumberID,
				FromBillID,
				RequestBillNumberID,
				RequestBillID,
				AskBillNumberID,
				AskBillID
				
				-- 新增字段
				,TaxMoney
				,NSalePrice
				,NSaleTotal
				,NDiscountPrice
				,NTotal
				,NTaxPrice
				,NTaxTotal
				,NTaxMoney
				--,CargoId
				,UnitId
				,NUnitId
				,NQty
				,UnitRate
				,NUnitMsg
				,MUnitId
				,MQty
				,MUnitRate
				,MUnitMsg
				,MSalePrice
				,MDiscountPrice
				,MTaxPrice
				,CurMSalePrice
				,CurMDiscountPrice
				,CurMTaxPrice
				,ItemId
				,IsCombined
				,goodsnumber
				,CargoID
				,GoodsCostPrice
				,GoodsOrder 
				,ProduceDate 
				,ValidDate 
				,isrequest
				,oldcurmtaxprice
	            ,oldqty
				,entrycode
				,IsGift
				,YapiID
				,PriceSource
				,Id
				,PromoType
				,ShowOrder
				,SaleOrderId
				,saleorderreachqty
				,PTCombinOrderBillDetailID
				--,ReachTotal
				--,ReachTaxTotal
		) SELECT 
				@billNumberId,
				chvPTypeID,
				numQty,
				numPrice,
				numTotal,
				numReachQty,
				chvComment,
				intIsUnitTow,
				numDiscount,
				numDiscountPrice,
				numTaxPrice,
				numTaxTotal,
				numSaleTotal,
				numTax,
				KTypeID,
				STypeID,
				FromBillNumberID,
				FromBillID,
				requestbillnumberid,
				requestbillid,
				askbillnumberid,
				askbillid
				
				-- 新增字段
				,TaxMoney
				,NSalePrice
				,NSaleTotal
				,NDiscountPrice
				,NTotal
				,NTaxPrice
				,NTaxTotal
				,NTaxMoney
				--,CargoId
				,UnitId
				,NUnitId
				,NQty
				,UnitRate
				,NUnitMsg
				,MUnitId
				,MQty
				,MUnitRate
				,MUnitMsg
				,MSalePrice
				,MDiscountPrice
				,MTaxPrice
				,CurMSalePrice
				,CurMDiscountPrice
				,CurMTaxPrice
				,ItemId
				,IsCombined
				,goodsnumber
				,CargoID
				,GoodsCostPrice
				,GoodsOrder 
				,ProduceDate 
				,ValidDate 
				,isrequest
				,oldcurmtaxprice
	            ,oldqty
				,entrycode
				,IsGift
				,YapiID
				,PriceSource
				,Id
				,PromoType
				,ShowOrder
				,case when @billType=300 then -1 else SaleOrderId end as SaleOrderId --销售订单的saleorderid 为0
				,saleorderreachqty
				,PTCombinOrderBillDetailID
				--,numTotal
				--,numTaxTotal
		FROM @tb WHERE OrderID NOT IN (SELECT id FROM #t)
		
		--3.更新要更新的
		UPDATE a SET 
			id=b.id,
			ShowOrder=b.ShowOrder
		FROM dbo.OrderBill a JOIN @tb b ON a.OrderID=b.OrderId AND a.billNumberID=@billNumberId
		AND a.Id<>b.Id
		
		DROP TABLE #t;
		
		---------------------------用最新的数据去更新引用数量 start-------------------------------------
		IF @billType IN (300)
		BEGIN
			UPDATE dbo.QuotePriceBill SET UseQty=ISNULL(UseQty,0)+dbo.F_RoundQty(t.numQty)
			FROM QuotePriceBill q INNER JOIN (SELECT SUM(numQty) AS numQty,askbillnumberid,askbillid from @tb GROUP BY askbillnumberid,askbillid) t ON q.BillNumberID=t.askbillnumberid AND q.ID=t.askbillid
			WHERE t.askbillnumberid<>0 AND t.askbillid<>0
			----引用数量最大不能超过报价单数量
			--UPDATE QuotePriceBill SET UseQty=Qty
			--WHERE BillNumberID IN (SELECT askbillnumberid FROM dbo.OrderBill WHERE billNumberID=@billNumberId ) AND UseQty>Qty
			--已被引用的报价单状态改为成交(2019-05-29主表的报价状态变为改明细表的报价状态)
			UPDATE dbo.QuotePriceBill SET IfBargainOn=1 
			WHERE ID IN (SELECT askbillid from @tb WHERE askbillnumberid<>0 AND askbillid<>0) 
			
			
		END
		ELSE IF @billType IN (301)
		BEGIN
			UPDATE dbo.AskPriceBill SET UseQty=ISNULL(UseQty,0)+dbo.F_RoundQty(t.numQty)
			FROM AskPriceBill q INNER JOIN (SELECT SUM(numQty) AS numQty,askbillnumberid,askbillid from @tb GROUP BY askbillnumberid,askbillid) t ON q.BillNumberID=t.askbillnumberid AND q.ID=t.askbillid
			WHERE t.askbillnumberid<>0 AND t.askbillid<>0
			--引用数量最大不能超过报价单数量
			--UPDATE AskPriceBill SET UseQty=Qty
			--WHERE BillNumberID IN (SELECT askbillnumberid FROM dbo.OrderBill WHERE billNumberID=@billNumberId ) AND UseQty>Qty
			--已被引用的询价单状态改为成交(2019-05-29主表的报价状态变为改明细表的报价状态)
			UPDATE dbo.AskPriceBill SET IfBargainOn=1 
			WHERE ID IN (SELECT askbillid from @tb WHERE askbillnumberid<>0 AND askbillid<>0) 
			
			--修改采购单调销售订单，回写在销售订单明细行
			UPDATE ORDERBILL SET SaleOrderReachQty=ISNULL(SaleOrderReachQty,0)+dbo.F_RoundQty(t.numQty)
			FROM ORDERBILL o INNER JOIN (SELECT SUM(isnull(numQty,0)) AS numQty,SaleOrderId from @tb GROUP BY SaleOrderId) t  ON o.ORDERID=t.saleorderid
			where t.saleorderid<>0 
			
			--修改采购单调组合品销售订单，回写在组合品销售订单明细行
			UPDATE PT_Combin_OrderBillDetail SET SaleOrderReachQty=ISNULL(SaleOrderReachQty,0)+dbo.F_RoundQty(t.numQty)
			FROM PT_Combin_OrderBillDetail o INNER JOIN (SELECT SUM(isnull(numQty,0)) AS numQty,PTCombinOrderBillDetailID from @tb GROUP BY PTCombinOrderBillDetailID) t  ON o.ORDERID=t.PTCombinOrderBillDetailID
			where t.PTCombinOrderBillDetailID<>0 
		END
		---------------------------用最新的数据去更新引用数量   end-------------------------------------
	END
		
	IF @@ERROR <> 0
		RAISERROR('写入销售、采购订单明细数据时发生错误！',16,1);
	
	UPDATE A SET A.RequestQty = ISNULL( A.RequestQty ,0)+ISNULL( B.numQty,0),A.orderqty=ISNULL(A.orderqty,0)+ISNULL(b.numQty,0)
	FROM RequestBill A JOIN @tb B ON A.ID=B.RequestBillId
	WHERE @billType=301 AND B.RequestBillId<>0
	
	-- 如果订单有调请购单的数据，更新请购单中的状态
	UPDATE A SET A.[State]=8
	FROM RequestBill A JOIN @tb B ON A.ID=B.RequestBillId
	WHERE @billType=301 AND B.RequestBillId<>0 and sendqty=0
	
	UPDATE dbo.RequestBill SET [State]=1 WHERE State=8 AND NOT EXISTS(SELECT 1 FROM dbo.OrderBill WHERE RequestBillID=RequestBill.Id) AND orderqty=0
	
	-- 判断并处理订单的完成状态
	EXEC GP_AuditingCheckOrderState @billNumberId,0
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateOrderIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateOrderIndex]
GO


-- ========================================================================
-- 功能说明：		销售、采购订单数据修改
-- 作    者：		卢  春
-- 最后修改时间：	2003-07-17
-- ========================================================================
CREATE        PROCEDURE Gp_UpdateOrderIndex
(
	@intBillNumberID	numeric(10,0),			--  1、单据 ID 值 ( 唯一 )
	@chvBillDate		varchar(50),			--  2、单据日期
	@chvReachDate		varchar(50)		= '',	--  3、交货 ( 销售 )、到货 ( 采购 ) 日期
	@chvBillCode		varchar(200),			--  4、单据编号
	@intBillType		int,					--  5、单据类型，300 - 销售订单；301 - 采购订单
	@chvBTypeID			varchar(50),			--  6、往来单位 ID 值
	@chvETypeID			varchar(50),			--  7、经手人 ID 值
	@chvKTypeID			varchar(50),			--  8、仓库 ID 值
	@numTotalMoney		 NUMERIC(24, 10) ,			--  9、订单合计金额
	@numTotalQty		 NUMERIC(24, 10) ,			-- 10、订单合计数量
	@intPeriod			smallint,				-- 11、期号 ( 预留字段 )
	@bitChecked			bit,					-- 12、完成标志 ( 预留字段，默认置假 )
	@bitRedWord			bit,					-- 13、红字标志 ( 预留字段，默认置假 )
	@chvComment			varchar(256), 			-- 14、摘要
	@chvExplain			varchar(256),			-- 15、说明
	@chvCheckeID		varchar(50),			-- 16、制单人 ID 值
	@numTax				 NUMERIC(24, 10) 	= 17 ,	-- 17、税率 ( 预留字段，默认置 0 )
	@chvETypeID2		varchar(50),			-- 18、发货人 （预留字段 )
	@chvWayMode			varchar(50),			-- 19、发货方式 ( 预留字段，置空 )
	@chvWayBillCode		varchar(50),			-- 20、运单号
	@chvGoodsNumber		varchar(20),			-- 21、物件数量
	@chvPackWay			varchar(20),			-- 22、包装方式
	@chvTEL				varchar(100),			-- 23、电话
	@Dtypeid			varchar(50),				-- 24、分支机构Id
	@STypeID			varchar(50)='',
	@CustomerTotal		 NUMERIC(24, 10) =0,
	@NCustomerTotal		 NUMERIC(24, 10) =0,
	@frombillnumberid	INT,
	@NTotalMoney  NUMERIC(24, 10) ,
	@CId INT,
	@Rate  NUMERIC(24, 10) ,
	@BillProperty INT,
	@dealbtypeid VARCHAR(50),
	@Discount   NUMERIC(24, 10) =1,
	@ATypeID	VARCHAR(50),					--账户ID
	@TotalInMoney		NUMERIC(24,10)=0,		--实收本币金额
	@NTotalInMoney		NUMERIC(24,10)=0,		--实收原币金额
	@VipCardID			INT						--会员卡号
)
--@encode$--
AS
	-- 返回结果不受影响
	SET NOCOUNT ON

	IF NOT EXISTS(SELECT TOP 1 1 FROM OrderIndex WHERE BillNumberID = @intBillNumberID AND BillType = @intBillType)
	BEGIN
		RETURN -7
	END

	--对于审核未通过的，或更改了分支机构的之前提交过审核的单据，都把审核历程删掉
	IF EXISTS(
		SELECT BillNumberID
		FROM AuditingBill
		WHERE BillNumberID=@intBillNumberID AND IfAudit=-1
	)
	BEGIN
		DELETE AuditingBillDetail WHERE BillNumberID=@intBillNumberID AND BillIndexType=0
		DELETE AuditingBill
		WHERE BillNumberID=@intBillNumberID AND BillIndexType=0
	END
	
--删除自定义表头列
DELETE FROM CustomBillColumns	WHERE billnumberid=@intBillNumberID AND BillType=@intBillType
--删除自定义明细列
DELETE FROM CustomBillDetailColumns WHERE billnumberid=@intBillNumberID AND BillType=@intBillType
DELETE FROM dbo.Custom_BillDetails WHERE BillId=@intBillNumberID AND BillType=@intBillType	
DELETE FROM dbo.Custom_BillIndex WHERE BillId=@intBillNumberID AND BillType=@intBillType
DELETE BillMulAccount WHERE BillNumberId=@intBillNumberID  AND billtype=@intBillType

	UPDATE	OrderIndex
	SET		BTypeID		= @chvBTypeID,
			ETypeID		= @chvETypeID,
			KTypeID		= @chvKTypeID,
			BillDate	= @chvBillDate,
			ReachDate	= @chvReachDate,
			BillCode	= @chvBillCode,
			BillType	= @intBillType,
			TotalMoney	= dbo.F_RoundTotal(@numTotalMoney),
			TotalQty	= dbo.F_RoundQty(@numTotalQty),  
			Period		= @intPeriod,
			Checked		= @bitChecked,
			RedWord		= @bitRedWord,
			Comment		= @chvComment,
			Explain		= @chvExplain,
			Checke		= @chvCheckeID,
			Tax			= dbo.F_RoundTax(@numTax),
			ETypeID2	= @chvETypeID2,
			WayMode		= @chvWayMode,
			WayBillCode	= @chvWayBillCode,
			GoodsNumber	= @chvGoodsNumber,
			PackWay		= @chvPackWay,
			TEL			= @chvTEL,
			Dtypeid		= @DtypeId,
			STypeID     = @STypeID,
			frombillnumberid=@frombillnumberid,
			CustomerTotal=dbo.F_RoundTotal(@CustomerTotal),
			NCustomerTotal=dbo.F_RoundTotal(@NCustomerTotal),
			NTotalMoney = dbo.F_RoundTotal(@NTotalMoney),
			CId = @CId ,
			Rate = dbo.F_RoundExchangeRate(@Rate) ,
			BillProperty = @BillProperty,
			dealbtypeid=@dealbtypeid,
			Discount=dbo.F_RoundDiscount(@Discount),
			ATypeID=@ATypeID,
			VipCardID=ISNULL(@VipCardID,-1)
			--TotalInMoney=dbo.F_RoundTotal(@TotalInMoney),  实付金额不能通过界面传回值修改(该值由收付款单过账回写)
			--NTotalInMoney=dbo.F_RoundTotal(@NTotalInMoney)	实付金额不能通过界面传回值修改(该值由收付款单过账回写)
	WHERE	BillNumberID = @intBillNumberID

	IF @@ERROR <> 0 OR @@ROWCOUNT = 0
		RAISERROR('更新销售、采购订单发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateOrderIndexFinished]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateOrderIndexFinished]
GO







/*
	作者：谢吉康
	日期：2005-5-24
	描述：修改订单的状态
*/

CREATE PROCEDURE Gp_UpdateOrderIndexFinished
(
	@BillNumberId int
)
--@encode$--
AS

IF EXISTS(SELECT BillNumberId FROM OrderBill WHERE ISNULL(Qty,0)>ISNULL(ReachQty,0) AND BillNumberId = @BillNumberId)
	UPDATE	OrderIndex SET IsFinished = 0 WHERE BillNumberId = @BillNumberId
ELSE
	UPDATE	OrderIndex SET IsFinished = 1 WHERE BillNumberId = @BillNumberId








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateOrderIndexFinishedFromOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateOrderIndexFinishedFromOrderBill]
GO







/*
	作者：谢吉康
	日期：2005-5-24
	描述：修改订单的状态[根据订单的明细，用在采购入库单、销售出库单]
*/

CREATE PROCEDURE Gp_UpdateOrderIndexFinishedFromOrderBill
(
	@BillNumberId int
)
--@encode$--
AS

DECLARE @intOrderId int

SELECT @intOrderId = BillNumberId FROM OrderBill WHERE OrderId = @BillNumberId

IF EXISTS(SELECT BillNumberId FROM OrderBill WHERE ISNULL(Qty,0)>ISNULL(ReachQty,0) AND BillNumberId = @intOrderId)
	UPDATE	OrderIndex SET IsFinished = 0 WHERE BillNumberId = @intOrderId
ELSE
	UPDATE	OrderIndex SET IsFinished = 1 WHERE BillNumberId = @intOrderId








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateOrInsertCRMLinkMan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateOrInsertCRMLinkMan]
GO









CREATE                 PROCEDURE Gp_UpdateOrInsertCRMLinkMan
(
 @Mode   [varchar](25),
 @TypeId     int,
 @LinkMan varchar(50),
 @LinkSex bit,
 @LinkBirthDay datetime,
 @LinkJob varchar(50),
 @LinkCall Varchar(50),
 @LinkTel varchar(50),
 @LinkMobile varchar(50),
 @LinkEMail varchar(50),
 @LinkPost varchar(50),
 @LinkAddress varchar(50),
 @LinkComment varchar(50),
 @CreateDate datetime,
 @OperateId varchar(50),
 @OperateName varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON

declare @nReturntype int

IF @Mode = 'add'
BEGIN
 begin tran insertproc
 
 INSERT INTO [CRM_LinkMan] 
 (
 [LinkMan],
 [LinkSex],
 [LinkBirthDay],
 [LinkJob],
 [LinkCall],
 [LinkTel],
 [LinkMobile],
 [LinkEMail],
 [LinkPost],
 [LinkAddress],
 [LinkComment],
 [CreateDate],
 [deleted],
 [Createor],
 [CreateorName]
 ) 
  
 VALUES 
  ( 
 @LinkMan,
 @LinkSex,
 @LinkBirthDay,
 @LinkJob,
 @LinkCall,
 @LinkTel,
 @LinkMobile,
 @LinkEMail,
 @LinkPost,
 @LinkAddress,
 @LinkComment,
 @CreateDate,
 0,
 @OperateId,
 @OperateName
 )
 
 if @@rowcount=0 
 begin
  rollback tran insertproc 
  return -1
 end 
 
 -- 建立Employee数据 .超级用户的节点 --
 --select @UserCode=@UserCode+'_超级用户'
 --exec @nReturnType=Gp_InsertE '00000','employee',@UserCode,'超级用户','','','','',@EtypeId_1
 if (@nReturnType <> 0)
 begin 
  rollback tran insertproc 
  return @nReturnType 
 end
 commit tran insertproc
END
ELSE
BEGIN
 UPDATE [dbo].[CRM_LinkMan] 
 SET
 [LinkMan]=@LinkMan,
 [LinkSex]=@LinkSex,
 [LinkBirthDay]=@LinkBirthDay,
 [LinkJob]=@LinkJob,
 [LinkCall]=@LinkCall,
 [LinkTel]=@LinkTel,
 [LinkMobile]=@LinkMobile,
 [LinkEMail]=@LinkEMail,
 [LinkPost]=@LinkPost,
 [LinkAddress]=@LinkAddress,
 [LinkComment]=@LinkComment
 WHERE 
  ( [id]  = @typeId )

 IF EXISTS( SELECT * FROM CRM_Btype WHERE LinkManId1 = @typeId )
 BEGIN
 UPDATE CRM_Btype
  SET
  [LinkMan1]=@LinkMan,
  [LinkSex1]=@LinkSex,
  [LinkBirthDay1]=@LinkBirthDay,
  [LinkJob1]=@LinkJob,
  [LinkCall1]=@LinkCall,
  [LinkTel1]=@LinkTel,
  [LinkMobile1]=@LinkMobile,
  [LinkEMail1]=@LinkEMail,
  [LinkPost1]=@LinkPost,
  [LinkAddress1]=@LinkAddress,
  [LinkComment1]=@LinkComment
  WHERE
   LinkManId1 = @typeId
 END
 IF EXISTS( SELECT * FROM CRM_Btype WHERE LinkManId2 = @typeId )
 BEGIN
  UPDATE CRM_Btype
  SET
  [LinkMan2]=@LinkMan,
  [LinkSex2]=@LinkSex,
  [LinkBirthDay2]=@LinkBirthDay,
  [LinkJob2]=@LinkJob,
  [LinkCall2]=@LinkCall,
  [LinkTel2]=@LinkTel,
  [LinkMobile2]=@LinkMobile,
  [LinkEMail2]=@LinkEMail,
  [LinkPost2]=@LinkPost,
  [LinkAddress2]=@LinkAddress,
  [LinkComment2]=@LinkComment
  WHERE
   LinkManId2 = @typeId
 END
END

 







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateP]
GO








----========================
----修改者：吴德水
----日期：2003-05-26
----描述：增加序列号强制管理
----========================
CREATE              PROCEDURE [Gp_UpdateP]
(
 @TypeId  [varchar](50),
 @UserCode  [varchar](26),
 @FullName  [varchar](66),
 @Name    [varchar](30),
 @Standard  [varchar](40),
 @Type   [varchar](20),
 @Area    [varchar](30),
 @Unit1   [varchar](8),
 @Unit2   [varchar](8),
 @UnitRate1   NUMERIC(24, 10) ,
 @UnitRate2   NUMERIC(24, 10) ,
 @Preprice1   NUMERIC(24, 10) ,
 @Preprice2   NUMERIC(24, 10) ,
 @Preprice3   NUMERIC(24, 10) ,
 @Preprice4   NUMERIC(24, 10) ,
 @Preprice5   NUMERIC(24, 10) ,
 @usefulLifeMonth  [smallint],
 @usefulLifeDay  [smallint],
 @Comment  [varchar](250),
 @ColorGroupID int,    -----肖伟2002-6-5 Add For 服装版
 @SizeGroupID int,      -----肖伟2002-6-5 Add For 服装版
 @EntryCode [varchar](50),   -----条形码
 @IfSerial varchar(5),   ------序列号强制管理
 @serialcount int,   ------序列号强制管理商品序列号位数
 @PyCode   varchar(200),
 @ValidDays int
)
--@encode$--
AS 
SET NOCOUNT ON 
declare @Count int   -----肖伟2002-6-5 Add For 服装版
if exists(select usercode from ptype where (usercode=@usercode) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
begin
-- print '商品已存在'+@etypeid_1
 return -3
end
--if exists(select usercode from ptype where ((usercode=@fullname) or (fullname=@usercode)) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
--begin
-- print '商品已存在'+@etypeid_1
-- return -10
--end
DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName
IF @PyCode <>'' 
SET @returnPym=@PyCode


UPDATE [dbo].[ptype] 
SET  [UserCode]  = @UserCode,
  [FullName]  = @FullName,
  [Name]  = @Name,
  [Standard]  = @Standard,
  [Type]  = @Type,
  [Area]  = @Area,
  [Unit1] = @Unit1,
  [Unit2]  = @Unit2,
  [UnitRate1]  = dbo.F_RoundTranslateRate(@UnitRate1),
  [UnitRate2]  = dbo.F_RoundTranslateRate(@UnitRate2),
  [preprice1]    =dbo.F_RoundPrice(@preprice1),
  [preprice2]    =dbo.F_RoundPrice(@preprice2),
  [preprice3]    =dbo.F_RoundPrice(@preprice3),
  [preprice4]    =dbo.F_RoundPrice(@preprice4),
  [preprice5]    =dbo.F_RoundPrice(@preprice5),
  [UsefulLifeMonth]  = @usefulLifeMonth,
  [UsefulLifeDay]  = @usefulLifeDay,
  [Comment]  = @Comment, 
  [ColorGroupID]=@ColorGroupID,       -----肖伟2002-6-5 Add For 服装版
  [SizeGroupID]=@SizeGroupID,           -----肖伟2002-6-5 Add For 服装版
  [EntryCode]=@EntryCode,
  [IfSerial]=@IfSerial,
  [serialcount]=@serialcount,
  [PyCode] = @returnPym,
  [ValidDays] = @ValidDays
WHERE 
 ( [typeId]  = @typeId)

--保存单位
IF @Unit1<>''
BEGIN
	IF NOT EXISTS(SELECT * FROM UniteName WHERE UniteName = @Unit1)
	BEGIN
		INSERT UniteName (UniteName) VALUES (@Unit1)
	END
END
IF @Unit2<>''
BEGIN
	IF NOT EXISTS(SELECT * FROM UniteName WHERE UniteName = @Unit2)
	BEGIN
		INSERT UniteName (UniteName) VALUES (@Unit2)
	END
END
   select @Count=Sonnum from ptype where typeid=@typeId   -----肖伟2002-6-5 Add For 服装版
   if @Count<>0
      update ptype set ColorGroupID=@ColorGroupID,SizeGroupID=@SizeGroupID where left(typeid,len(@typeId))=@typeId and deleted<>1
--判断系统是否是序列号强制管理
DECLARE	@SysMngSerial varchar(1)
SELECT @SysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial'
IF @SysMngSerial = '1' AND @IfSerial = '1'
BEGIN
	UPDATE BuyBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE OrderBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE BuyBackBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE BuyGoodsExchangeBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE SaleBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE SaleBackBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE SaleGoodsExchangeBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE RetailBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE CommissionBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE MoveBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE MoveBjBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE LoseBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE OverFlowBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE GiveBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
	UPDATE GiveMeBill SET IsUnit2 = 0 WHERE PTypeID = @typeId AND IsUnit2 = 1
END


--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM PType
UPDATE PType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdatePass]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdatePass]
GO















/****** Object:  Stored Procedure dbo.Gp_UpdatePass    Script Date: 2002-6-20 10:14:52 ******/

CREATE   PROCEDURE Gp_UpdatePass 
(
 @szEtypeid varchar(50),
 @Pass    varchar(32) 
)
--@encode$--
AS
SET NOCOUNT ON 
IF @szEtypeid = '' 
    BEGIN
        UPDATE  loginuser
        SET     password = CAST(@pass AS VARBINARY(32)) WHERE etypeid!='00001'
    END
ELSE 
    BEGIN
        UPDATE  loginuser
        SET     password = CAST(@pass AS VARBINARY(32))
        WHERE   etypeid = @szEtypeid
    END
    PRINT @@error
if @@error = 0
begin
--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'
return 0
end
else return -1
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdatePeriod]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROC [dbo].[Gp_UpdatePeriod]
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	账套保存修改相应期间值
-- 时间：	2012-06-20
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_UpdatePeriod
(
	@Fyear	VARCHAR(10),--启用年度
	@Fmonth VARCHAR(10)--启用期间
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@year			VARCHAR(10)='',--会计期间启用年度
	@month			VARCHAR(10)='',--会计期间启用期间
	@IsDynamic	INT=0,			--是否动态	
	@error INT=0
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period)
	BEGIN
		RAISERROR('会计期间未设置,请确认！',16,1) 
		RETURN 
	END
IF EXISTS(SELECT TOP 1 1 FROM Ac_Period)
	BEGIN
		SELECT TOP 1 @year=FYear,@month=FMonth,@IsDynamic=IsDynamic FROM Ac_Period 
		IF((ISNULL(@Fyear,0)>ISNULL(@year,0) OR ISNULL(@Fmonth,0)>ISNULL(@month,0)) AND @IsDynamic=1)
			BEGIN
				RAISERROR('启用期间年度/期间与会计期间启用年度/期间不一致!',16,1) 
				RETURN 
			END	
	END

BEGIN TRAN
UPDATE Ac_Period SET FYear=@Fyear,FMonth=@Fmonth --修改会计期间设置表
SET @error+=@@ERROR
DECLARE @SubValue VARCHAR(1)=''
SELECT @SubValue=SubValue FROM sysdata WHERE SubName='IsInvocation'
IF(@SubValue='' OR @SubValue!='1')
	BEGIN
		UPDATE sysdata SET SubValue=@Fmonth WHERE SubName IN('FPeriod','fmonth')--修改sysdata表
		SET @error+=@@ERROR
		END
IF(@error<>0)
	BEGIN
		ROLLBACK TRAN
		RAISERROR('期间设置失败',16,1)
	END
ELSE COMMIT TRAN
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdatePerson]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdatePerson]
GO














-- ========================================================================
-- 功能说明：	派工
-- 作    者：	cqhua
-- 2009-11-09
-- ========================================================================
CREATE                PROCEDURE GP_UpdatePerson
(
	@billnumberid   varchar(6000), -- 单据ID
	@idstr          varchar(6000), -- 表wx_Bill_JieJian 字段ID
	@EtypeID 		varchar(50)		-- 职员ID
)	

--@encode$--
AS
CREATE TABLE #Billnumberid 
(
[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
billnumberid numeric(18,0)
)

CREATE TABLE #idstr 
(
[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
idstr numeric(18,0)
)




INSERT INTO #Billnumberid(Billnumberid) select * from dbo.f_split(@billnumberid,',')
INSERT INTO #idstr(idstr) select * from dbo.f_split(@idstr,',')
-- 接件单的状态不为 【待修理】，不能修改维修人
IF EXISTS(select top 1 1 from wx_bill_jiejian a,#Billnumberid b,#idstr c where a.state<>0 AND  a.billnumberid=b.billnumberid and a.id=c.idstr)
	RETURN -1
UPDATE wx_Bill_JieJian set  etypeid=@Etypeid
FROM wx_Bill_JieJian a
INNER JOIN #billnumberID b on a.billnumberid=b.billnumberid
INNER JOIN #idstr c on a.ID=c.idstr
WHERE b.ID=c.ID


DROP TABLE #Billnumberid
DROP TABLE #idstr


SET NOCOUNT ON
SET ANSI_WARNINGS OFF









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdatePosAdminitorInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdatePosAdminitorInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	颜熙
	Date	:	2017/10/26
	Description	: 插入Pos终端管辖相关信息
*/
CREATE PROCEDURE Gp_UpdatePosAdminitorInfo
(
	@PosEmployee Type_PosEmployee	READONLY,   --	pos职员
	@PosPtype	 Type_PosPtype		READONLY,
	@PosAccount	 Type_PosAccount	READONLY,
	@PosBtype	 Type_PosBtype		READONLY,
	@PosOperator Type_PosOperator	READONLY,
	@posid       INT ,
	@isEall      BIT,
	@isOperator  BIT ,
	@isAccountAll BIT,
	@isPtypeAll BIT,
	@isBtypeAl  BIT ,
	@operator VARCHAR(100) --操作员
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @tips VARCHAR(1000)
--权限验证
--职员
SELECT TOP 1 @tips =  e.FullName FROM @PosEmployee p INNER JOIN dbo.employee e ON p.Eid = e.Eid WHERE e.typeId NOT IN (SELECT typeId FROM dbo.F_GetManETypeAll(@operator))
IF(@tips<>'' AND @tips IS NOT NULL)
BEGIN
SELECT @tips = ISNULL(@tips,'') + '资料不是一个有效的基本信息或者不在您权限范围内，不允许保存！'
RAISERROR(@tips,16,1)
RETURN
END 
--商品
SELECT TOP 1 @tips =  e.FullName FROM @PosPtype p INNER JOIN dbo.ptype e ON p.Pid = e.Pid WHERE e.typeId NOT IN (SELECT typeId FROM dbo.F_GetManPTypeAll(@operator))
IF(@tips<>'' AND @tips IS NOT NULL)
BEGIN
SELECT @tips = ISNULL(@tips,'') + '资料不是一个有效的基本信息或者不在您权限范围内，不允许保存！'
RAISERROR(@tips,16,1)
RETURN
END 
--账户
SELECT TOP 1 @tips =  e.FullName FROM @PosAccount p INNER JOIN dbo.Ac_Items e ON p.nid = e.nId WHERE e.nTypeId NOT IN (SELECT nTypeId FROM dbo.F_GetManATypeAll(@operator))
IF(@tips<>'' AND @tips IS NOT NULL)
BEGIN
SELECT @tips = ISNULL(@tips,'') + '资料不是一个有效的基本信息或者不在您权限范围内，不允许保存！'
RAISERROR(@tips,16,1)
RETURN
END 
--往来单位
SELECT TOP 1 @tips =  e.FullName FROM @PosBtype p INNER JOIN dbo.btype e ON p.Bid= e.Bid WHERE e.typeId NOT IN (SELECT typeId FROM dbo.F_GetManBType(@operator))
IF(@tips<>'' AND @tips IS NOT NULL)
BEGIN
SELECT @tips = ISNULL(@tips,'') + '资料不是一个有效的基本信息或者不在您权限范围内，不允许保存！'
RAISERROR(@tips,16,1)
RETURN
END 
--操作员
SELECT TOP 1 @tips =  e.FullName FROM @PosEmployee p INNER JOIN dbo.employee e ON p.Eid = e.Eid WHERE e.typeId NOT IN (SELECT typeId FROM dbo.F_GetManETypeAll(@operator))
IF(@tips<>'' AND @tips IS NOT NULL)
BEGIN
SELECT @tips = ISNULL(@tips,'') + '资料不是一个有效的基本信息或者不在您权限范围内，不允许保存！'
RAISERROR(@tips,16,1)
RETURN
END 

--清除Pos终端数据
DELETE FROM POSEmployee WHERE posid=@posid
DELETE FROM POSBtype WHERE posid=@posid
DELETE FROM POSPtype WHERE posid=@posid
DELETE FROM PosAccount WHERE posid=@posid
DELETE FROM POSOperator WHERE posid=@posid
------------插入数据
INSERT INTO dbo.POSEmployee(posid, Eid)
SELECT @posid, Eid FROM @POSEmployee 
UPDATE  dbo.POSEmployee
SET     dbo.POSEmployee.Etypeid = dbo.employee.typeId 
		--,
  --      dbo.POSEmployee.Efullname = dbo.employee.FullName ,
  --      dbo.POSEmployee.Eusercode = dbo.employee.UserCode ,
  --      dbo.POSEmployee.Comment = dbo.employee.Comment
FROM    dbo.POSEmployee
        INNER JOIN dbo.employee ON employee.Eid = POSEmployee.Eid;


INSERT INTO dbo.PosPtype(posid, pid)
SELECT @posid, pid FROM @PosPtype 
UPDATE  dbo.POSPtype
SET     dbo.POSPtype.ptypeid = ptype.typeId 
		--,
  --      dbo.POSPtype.Fullname = ptype.FullName ,
  --      dbo.POSPtype.Usercode = ptype.UserCode ,
  --      dbo.POSPtype.Comment = ptype.Comment ,
  --      dbo.POSPtype.Standard = ptype.Standard ,
  --      dbo.POSPtype.Type = ptype.typeId ,
  --      dbo.POSPtype.Entrycode = ptype.MultEntryCode
FROM    dbo.POSPtype
        INNER JOIN dbo.ptype ON ptype.Pid = POSPtype.pid
        WHERE Posid=@posid;

INSERT  INTO dbo.POSAccount
        ( Posid ,
          nid
        )
        SELECT  @posid ,
                nid
        FROM    @PosAccount;
UPDATE  dbo.POSAccount
SET     dbo.POSAccount.ntypeid = dbo.Ac_Items.nTypeId 
		--,
  --      dbo.POSAccount.Fullname = dbo.Ac_Items.FullName ,
  --      dbo.POSAccount.Comment = dbo.Ac_Items.Comment,
  --      dbo.POSAccount.Usercode = dbo.Ac_Items.UserCode
FROM    dbo.POSAccount
        INNER JOIN dbo.Ac_Items ON dbo.POSAccount.nid = dbo.Ac_Items.nId
        WHERE Posid=@posid;


INSERT INTO dbo.PosBtype(posid, bid)
SELECT @posid, bid FROM @PosBtype 
UPDATE dbo.POSBtype SET 
--dbo.POSBtype.Fullname = dbo.btype.FullName,
--dbo.POSBtype.Usercode = btype.UserCode,
--dbo.POSBtype.Comment = dbo.btype.Comment,
--dbo.POSBtype.Address = btype.TelAndAddress,
dbo.POSBtype.typeid = btype.typeId 
FROM dbo.POSBtype  INNER JOIN dbo.btype  ON btype.Bid = POSBtype.bid
WHERE Posid=@posid;

INSERT INTO dbo.PosOperator(posid, Eid)
SELECT @posid, operatorid FROM @PosOperator
UPDATE  dbo.POSOperator
SET     dbo.POSOperator.Etypeid = dbo.employee.typeId 
		--,
  --      dbo.POSOperator.Efullname = dbo.employee.FullName ,
  --      dbo.POSOperator.Eusercode = dbo.employee.UserCode ,
  --      dbo.POSOperator.Comment = dbo.employee.Comment ,
  --      dbo.POSOperator.Dfullname = Department.FullName ,
  --      PositionName = dbo.employee.Job,
  --      dbo.POSOperator.Dtypeid = Department.typeid
FROM    dbo.POSOperator
        INNER JOIN dbo.employee ON employee.Eid = POSOperator.Eid
        INNER JOIN dbo.Department ON Department.typeid = dbo.employee.DtypeID
        WHERE Posid=@posid;

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_UpdatePosAllotApplyBillState]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_UpdatePosAllotApplyBillState]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：glj
	日期：2018-08-13
	描述：调货申请单状态改变
*/
CREATE  PROCEDURE Gp_UpdatePosAllotApplyBillState
(
	@BillIds	VARCHAR(MAX),--单据ID字符串
	@BillState	INT,--单据操作类型 2-已接受 3-已拒绝 4-已作废 41-反作废
	@OperatorId	VARCHAR(50),--当前操作员ID
	@IP			VARCHAR(50)--当前操作员ID
)
AS
SET NOCOUNT ON 

CREATE TABLE #Bill
(
	BillNumberId	NUMERIC(24,0),--单据ID
	BillCode		VARCHAR(200),--单据编号
	BillState		INT,--单据状态
	ExecState		INT,--单据执行状态
)
INSERT INTO #Bill
(
	BillNumberId,
	BillCode,
	BillState,
	ExecState
)  
SELECT  
	B.billnumberid,
	B.BillCode,
	B.BillState,
	CASE WHEN B.Isdone = 1 THEN 7 --已完成
		WHEN M.qty>0 and B.isdone=0 THEN 6 --已引用未完成
		ELSE 8 END ExecState --未引用
FROM f_split(@BillIds,',') FB
INNER JOIN PosAllotApplyBillIndex B ON B.BillNumberId=FB.a
LEFT JOIN 
	(	
		SELECT 
			ISNULL(SUM(F.Qty),0) as Qty,
			pb.BillNumberId
		FROM (
			SELECT Qty,AllotID FROM dbo.MoveBill m 
			INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
			WHERE bi.RedWord=0 ----引用要算草稿
			UNION ALL 
			SELECT Qty,AllotID FROM dbo.MoveBjBill m
			INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
			WHERE bi.RedWord=0 ----引用要算草稿 
			UNION ALL 
			SELECT s.Qty,s.AllotID FROM dbo.STypeMoveBill s 
			INNER JOIN dbo.BillIndex bi ON s.BillNumberId=bi.BillNumberId
			WHERE bi.RedWord=0 ----引用要算草稿 
		) F
		INNER JOIN dbo.PosAllotApplyBill pb ON pb.ID=F.AllotID 
		GROUP BY pb.BillNumberId		
	)M on B.BillNumberId=M.BillNumberId
	

--//单据状态 0-原始草稿 2-已接受 3-已拒绝 4-已作废
--//单据执行状态 1-已完成 2-已引用未完成 3-未引用 
IF(@BillState=2)--2-接受
	BEGIN
		UPDATE B SET B.BillState=2
		FROM PosAllotApplyBillIndex B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(0,3) AND F.ExecState=8
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(0,3) OR F.ExecState<>8
	END
ELSE IF(@BillState=3)--3-拒绝
	BEGIN
		UPDATE B SET B.BillState=3
		FROM PosAllotApplyBillIndex B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(0,2) AND F.ExecState=8
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(0,2) OR F.ExecState<>8
		
	END
ELSE IF(@BillState=4)--4-作废
	BEGIN
		UPDATE B SET B.BillState=4
		FROM PosAllotApplyBillIndex B
				INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(0,2,3) AND F.ExecState in(6,8)
		
				--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(0,2,3) OR F.ExecState not in(6,8)
		
	END
ELSE IF(@BillState=41)--41-反作废
	BEGIN
		UPDATE B SET B.BillState=0
		FROM PosAllotApplyBillIndex B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(4) AND F.ExecState=8
		UPDATE B SET B.BillState=2
		FROM PosAllotApplyBillIndex B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(4) AND F.ExecState=6
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(4) OR F.ExecState not in (6,8)
		
		
	END
ELSE IF(@BillState=-1)-- -1-删除
	BEGIN
		--删除主表
		DELETE FROM T
		FROM PosAllotApplyBillIndex T
		INNER JOIN #Bill B ON B.BillNumberId=T.BillNumberId AND B.BillState IN(0,2,3,4) AND B.ExecState=8
		--删除明细表
		DELETE FROM T
		FROM PosAllotApplyBill T
		INNER JOIN #Bill B ON B.BillNumberId=T.BillNumberId AND B.BillState IN(0,2,3,4) AND B.ExecState=8
		
		--插入删除日志
		INSERT INTO BillDeleteLog
		(
			BillNumberID
			,BillType
			,BillCode
			,BillDate
			,StypeID
			,BtypeID
			,DealBTypeID
			,Checke
			,DelDate
			,DelEtypeID
			,DelIP
		)
		SELECT 
			B.BillNumberId,
			B.BillType,
			B.BillCode,
			B.BillDate,
			B.StypeId,
			'' BTypeId,
			'' DealBTypeId,
			B.checkE,
			GETDATE(),
			@OperatorId,
			@IP
		FROM PosAllotApplyBillIndex  B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(0,2,3,4) AND F.ExecState=8
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(0,2,3,4) OR F.ExecState<>8
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdatePosBankRateInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdatePosBankRateInfo
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE	PROCEDURE	Gp_UpdatePosBankRateInfo
(
		@rateid			INT  ,
		@UserCode		VARCHAR(200) ,
		@FullName		VARCHAR(200) ,
		@bankitemid		varchar(50),
		@payitemid		varchar (50),
		@payrate		NUMERIC(24,4) ,
		@limittotal		NUMERIC(24,2) ,
		@retaildefault	bit ,
		@comment		varchar (500)	
)
--@encode$--
AS
SET NOCOUNT ON

IF @rateid=0 AND  EXISTS( SELECT TOP 1 1 FROM POSBankRateInfo WHERE usercode =@usercode )
begin
	SELECT -1
	RETURN 
END

IF EXISTS( 
SELECT TOP 1 1 FROM POSBankRateInfo 
WHERE @retaildefault=1 AND retaildefault=1 
	  AND ratestate=1 
	  AND bankitemid=@bankitemid
 )
begin
	SELECT -2
	RETURN 
END

IF @rateid=0 AND EXISTS( SELECT TOP 1 1 FROM POSBankRateInfo WHERE bankitemid=@bankitemid AND payrate=@payrate AND limittotal=@limittotal )
begin
	SELECT -3
	RETURN 
END



IF @rateid=0
BEGIN
	INSERT INTO dbo.POSBankRateInfo
        ( UserCode ,
          FullName ,
          bankitemid ,
          payitemid ,
          payrate ,
          limittotal ,
          retaildefault ,
          comment,
          ratestate
        )
VALUES  ( @UserCode ,
          @FullName ,
          @bankitemid ,
          @payitemid ,
          @payrate ,
          @limittotal ,
          @retaildefault ,
          @comment,
          0
        )
        
	SELECT @@identity	 		
END					
ELSE
BEGIN	
    UPDATE dbo.POSBankRateInfo
    SET UserCode=@UserCode,FullName=@FullName,bankitemid=@bankitemid,
		payitemid=@payitemid,payrate=@payrate,limittotal=@limittotal,
		retaildefault=@retaildefault,comment=@comment
	WHERE rateid=@rateid
	
	SELECT @rateid
END

EXEC Gp_DataSaveForPosDown '-99999','POSBankRateInfo','0'

GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdatePosInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdatePosInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：王珏
	日期：2013-02-25
	描述：更新门店档案信息
*/
CREATE	PROCEDURE	Gp_UpdatePosInfo
(
	@posid			INT,
	@usercode		VARCHAR(200),
	@fullname		VARCHAR(200),
	@ktypeid		VARCHAR(50),
	@btypeid		VARCHAR(50),
	@stypeid		VARCHAR(50),
	@bankcardid		INT,
	@pycode			VARCHAR(100),
	@comment		VARCHAR(500),
	@flag			INT, --0：新增，1：复制新增 2：修改	
	@KID			INT,
	@cashid			INT,
	@passtype		INT,
	@permitsaleemployee INT, --0不允许录入业务员 1允许录入业务员
	@canclezeroway INT,	  
	@canclezerotype INT,
	@lowlowestsaleprice INT,
	@lowlastbuyprice INT,
	@highhighestsaleprice INT,
	@codesearchway INT,
	@stockqueryrange INT,
	@permitmakevipcard INT,
	@permitvipcardrecharge INT,
	@permitshowbatchno INT,
	@permitshowbatchtime INT,
	@permitsavenonnumber INT,
	@frequencysecond INT,
	@displayptypepic int,
	@displayadvpic INT,
	@autoshowpromote INT,
	@rememberemployee int ,
	@samegoodsumqty INT ,
	@PriceBillIndexID NUMERIC(18,0)	,
	@rateid INT ,
	@startbankrate INT,
	@autopromotions INT,
	@posnotposting 		INT,
	@enablemultipleaccounts INT,
	@alipayid	INT,
	@wxpayid    INT,
	@allinpayid	INT,
	@JFPayId    INT,--jfpayid//积分收款项目
	@enablebtype INT,
	@dealbtypeid   VARCHAR(200) ,
	@enablemonthend BIT,
	@AllowTransferGoods INT=0,
	@autozeroui int=0,
	@ForeFroegroundStock INT=0,
	@barcodetype INT,
	@autogenerate INT=0,
	@prepricenum INT,   --适用预设价格
	@isEall BIT, --是否职员全选
	@isOperatorAll BIT ,--是否操作员全选
	@isAccountAll BIT ,--是否账户全选
	@isPtypeAll BIT ,--是否商品全选
	@isBtypeAll BIT ,--是否客户全选
	@permitshowbtype INT,
	@serialptypejs	INT = 0			--严密序列号管理商品必须录入序列号后方可结算
)
--@encode$--
AS
SET NOCOUNT ON

--验证仓库的有效性
IF @flag<>2
	BEGIN
		IF NOT EXISTS ( SELECT  *
						FROM    STOCK
						WHERE   typeId = @ktypeid ) 
			BEGIN
				RAISERROR('仓库无效,请重新选择！',16,1)
				RETURN
			END
	END

--验证客户的有效性
IF NOT EXISTS ( SELECT  *
			FROM    Btype
			WHERE   typeId = @btypeid ) 
BEGIN
	RAISERROR('客户无效,请重新选择！',16,1)
	RETURN
END
--验证客户的有效性
--IF @enablebtype=1 AND  NOT EXISTS ( SELECT  *
--			FROM    Btype
--			WHERE   typeId = @dealbtypeid ) 
--BEGIN
--	RAISERROR('往来账户无效,请重新选择！',16,1)
--	RETURN
--END
--验证银行卡的有效性
IF NOT EXISTS ( SELECT  *
			FROM    Ac_Items
			WHERE   nid = @bankcardid ) 
BEGIN
	RAISERROR('银行卡无效,请重新选择！',16,1)
	RETURN
END

--验证现金项目的有效性
IF NOT EXISTS ( SELECT  *
			FROM    Ac_Items
			WHERE   nid = @cashid ) 
BEGIN
	RAISERROR('现金项目无效,请重新选择！',16,1)
	RETURN
END

IF NOT EXISTS ( SELECT  1
                FROM    dbo.Ac_Items
                WHERE   nId = @alipayid )
BEGIN
    RAISERROR('支付宝项目无效,请重新选择！',16,1)
    RETURN
END

IF NOT EXISTS ( SELECT  1
                FROM    dbo.Ac_Items
                WHERE   nId = @allinpayid )
BEGIN
    RAISERROR('易支付项目无效,请重新选择！',16,1)
    RETURN
END

--有微信配置才进入
IF NOT EXISTS ( SELECT  1
                FROM    dbo.Ac_Items
                WHERE   nId = @wxpayid )
BEGIN
    RAISERROR('微信项目无效,请重新选择！',16,1)
    RETURN
END
	
IF NOT EXISTS ( SELECT  1
                FROM    dbo.Ac_Items
                WHERE   nId = @JFPayId )
BEGIN
    RAISERROR('积分收款项目,请重新选择！',16,1)
    RETURN
END

DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

SELECT @KID = KID FROM dbo.Stock WHERE typeId = @ktypeid

DECLARE @ItemId INT
SELECT @ItemId=nid FROM dbo.Ac_Items WHERE UserCode='2191'	AND FullName='『优惠券』'


IF @flag <>2
BEGIN
	INSERT INTO PosInfo (	UserCode,
							FullName,
							ktypeid,
							btypeid,
							stypeid,
							bankcardid,
							cashid,
							vipmoneyid,
							couponmoneyid,							
							PyCode,
							STATE,
							Comment,
							KID,
							passtype,
							permitsaleemployee,
							canclezeroway ,	  
							canclezerotype ,
							lowlowestsaleprice ,
							lowlastbuyprice ,
							highhighestsaleprice ,
							codesearchway ,
							stockqueryrange ,
							permitmakevipcard ,
							permitvipcardrecharge ,
							permitshowbatchno,
							permitshowbatchtime,
							permitsavenonnumber,
							frequencysecond ,
							displayptypepic ,
							displayadvpic ,
							autoshowpromote,
							rememberemployee,
							samegoodsumqty,
							PriceBillIndexID,
							rateid,
							startbankrate,
							autopromotions,
							posnotposting,
							enablemultipleaccounts,
							alipayid,
							wxpayid,
							allinpayid,
							JFPayId,
							enablebtype,
							enablemonthend,
							AllowTransferGoods,
							ForeFroegroundStock,
							dealbtypeid,
							autozeroui,
							barcodetype,
							autogenerate,
							prepricenum,
							isEall ,
							isOperatorAll,
							isAccountAll,
							isPtypeAll,
							isBtypeAll,
							permitshowbtype,
							serialptypejs
					)VALUES( 
							@usercode,
							@fullname,
							@ktypeid,
							@btypeid,
							@stypeid,
							@bankcardid,
							@cashid,--预制ac_items nid=1 现金
							'34',--预制ac_items nid=34 会员储值	
							@ItemId,--预制ac_items nid=78 优惠券，预制78是错误的，应该是查询出来才对				
							@returnPym,
							1,							
							@comment,
							@KID,
							@passtype,
							1,
							@canclezeroway ,	  
							@canclezerotype ,
							@lowlowestsaleprice ,
							@lowlastbuyprice ,
							@highhighestsaleprice ,
							1 ,
							@stockqueryrange ,
							@permitmakevipcard ,
							@permitvipcardrecharge,
							@permitshowbatchno,
							@permitshowbatchtime,
							@permitsavenonnumber,
							@frequencysecond ,
							@displayptypepic ,
							@displayadvpic ,
							@autoshowpromote,
							1,
							@samegoodsumqty,
							@PriceBillIndexID,
							@rateid,
							@startbankrate,
							@autopromotions,
							@posnotposting,
							1 ,
							@alipayid,
							@wxpayid,
							@allinpayid,
							@JFPayId,
							@enablebtype,
							@enablemonthend,
							@AllowTransferGoods,
							@ForeFroegroundStock,
							@dealbtypeid,
							@autozeroui,
							@barcodetype,
							@autogenerate,
							@prepricenum,
							@isEall,
							@isOperatorAll,
							@isAccountAll,
							@isPtypeAll,
							@isBtypeAll,
							@permitshowbtype,
							@serialptypejs
					)	
	SELECT @@IDENTITY	 			
END					
ELSE
BEGIN
	UPDATE PosInfo SET UserCode=@usercode,FullName=@fullname,ktypeid=@ktypeid,btypeid=@btypeid,stypeid=@stypeid,bankcardid=@bankcardid,PyCode=@returnPym,Comment=@comment,KID=@KID,CashID=@cashid,passtype=@passtype,
					permitsaleemployee=1,
					canclezeroway=@canclezeroway ,	  
					canclezerotype=@canclezerotype ,
					lowlowestsaleprice=@lowlowestsaleprice ,
					lowlastbuyprice =@lowlastbuyprice ,
					highhighestsaleprice =@highhighestsaleprice ,
					codesearchway =1 ,
					stockqueryrange =@stockqueryrange ,
					permitmakevipcard =@permitmakevipcard ,
					permitvipcardrecharge =@permitvipcardrecharge,
					permitshowbatchno=@permitshowbatchno,
					permitshowbatchtime =@permitshowbatchtime,
					permitsavenonnumber=@permitsavenonnumber,
					frequencysecond=@frequencysecond,
					displayptypepic=@displayptypepic,
					displayadvpic=@displayadvpic,
					autoshowpromote=@autoshowpromote,
					rememberemployee=1,
					samegoodsumqty=@samegoodsumqty,
					PriceBillIndexID=@PriceBillIndexID,
					startbankrate=@startbankrate,
					rateid=@rateid,
					autopromotions=@autopromotions,
					posnotposting=@posnotposting,
					enablemultipleaccounts=1 ,
					alipayid=@alipayid,
					wxpayid=@wxpayid,
					allinpayid=@allinpayid,
					JFPayId=@JFPayId,
					enablebtype=@enablebtype,
					enablemonthend=@enablemonthend,
					AllowTransferGoods=@AllowTransferGoods,
					ForeFroegroundStock=@ForeFroegroundStock,
					dealbtypeid=@dealbtypeid
					,
					autozeroui = @autozeroui,
					barcodetype=@barcodetype,
					autogenerate=@autogenerate,
					prepricenum=@prepricenum,
					isEall = @isEall,
					isOperatorAll = @isOperatorAll,
					isAccountAll = @isAccountAll,
					isPtypeAll = @isPtypeAll,
					isBtypeAll = @isBtypeAll,
					permitshowbtype=@permitshowbtype,
					serialptypejs	 = @serialptypejs
	WHERE  PosID=@posid
	
	SELECT @posid
	
END

IF @permitsaleemployee=0
BEGIN
	UPDATE PosInfo SET rememberemployee=0
	WHERE  PosID=@posid
END

GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdatePosLowNo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdatePosLowNo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇	
	日期：2016-03-03
	描述：自定义单据编号规则
*/
CREATE PROCEDURE Gp_UpdatePosLowNo
(
	@posid				INT,
	@IsDiy				INT,
	@FlowNoLen			INT, 
	@FlowNoStartVal		INT,
	@SplitSign			VARCHAR(3),

	@PrefixType1		INT, 
	@PrefixVal1			VARCHAR(200),	  
	@IsEnabled1			INT,
	
	@PrefixType2		INT, 
	@PrefixVal2			VARCHAR(200),	  
	@IsEnabled2			INT,

	@PrefixType3		INT, 
	@PrefixVal3			VARCHAR(200),	  
	@IsEnabled3			INT

	
)
--@encode$--
AS
SET NOCOUNT ON
   DECLARE @posusercode VARCHAR(200)
   SELECT @posusercode=usercode FROM dbo.PosInfo WHERE PosID=@posid
   DECLARE @FlowNoConfigID int 
   DECLARE @id int
   SELECT  @FlowNoConfigID=id FROM PosFlowNoConfig WHERE PosCode=@posusercode
    
   DELETE PosFlowNoConfig WHERE PosCode=@posusercode
   
   DELETE  PosFlowNoPrefix WHERE FlowNoConfigID=@FlowNoConfigID

     INSERT INTO PosFlowNoConfig (PosCode,IsDiy,FlowNoLen,FlowNoStartVal,SplitSign) VALUES(@posusercode,@IsDiy,@FlowNoLen,@FlowNoStartVal,@SplitSign)
     SELECT @id= @@IDENTITY
     INSERT	INTO PosFlowNoPrefix(FlowNoConfigID,PrefixCode,PrefixType,PrefixVal,IsEnabled) VALUES(@id,1,@PrefixType1,@PrefixVal1,@IsEnabled1)
     INSERT	INTO PosFlowNoPrefix(FlowNoConfigID,PrefixCode,PrefixType,PrefixVal,IsEnabled) VALUES(@id,2,@PrefixType2,@PrefixVal2,@IsEnabled2)
     INSERT	INTO PosFlowNoPrefix(FlowNoConfigID,PrefixCode,PrefixType,PrefixVal,IsEnabled) VALUES(@id,3,@PrefixType3,@PrefixVal3,@IsEnabled3)

    UPDATE PosReDataGlobal  SET  IfReData=1 WHERE stypeid='-99999'
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdatePriceBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdatePriceBillIndex]
GO

CREATE PROC [Gp_UpdatePriceBillIndex]
(
   @BillNumberID           INT
  ,@UserCode             VARCHAR(200)                     --价格表编号
  ,@FullName             VARCHAR(200)                     --价格表名称
  ,@CID                  INT                              --币种ID
  ,@IsFreePrice          TINYINT                          --按自由项报价
  ,@IsUnitPrice          TINYINT                          --按计量单位报价
  ,@IsDiscount           TINYINT                          --指定扣率
  ,@IsRate               TINYINT                          --指定税率
  ,@Explain              VARCHAR(255)                     --说明
  ,@Comment              VARCHAR(255)                     --摘要
  ,@BillType             INT                              --单据类型
  ,@State                INT                              --单据状态
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE PriceBillIndex SET UserCode=@UserCode
                         ,FullName=@FullName
                         ,CID=@CID
                         ,IsFreePrice=@IsFreePrice
                         ,IsUnitPrice=@IsUnitPrice
                         ,IsDiscount=@IsDiscount
                         ,IsRate=@IsRate
                         ,Explain=@Explain
                         ,Comment=@Comment
                         ,BillType=@BillType
                         ,State=@State
                         ,XiWaMaxNumber=ISNULL(XiWaMaxNumber,0)+1
                    WHERE id=@BillNumberID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdatePriceProtect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdatePriceProtect]
GO


--==========================
--作者：谢吉康
--日期：2003-03-21
--描述：修改信息到价格保护表
--==========================
CREATE    PROCEDURE [Gp_UpdatePriceProtect] 
(
	@OperatorId	VARCHAR(50),
	@PtypeID 	VARCHAR(50),	--商品ID
	@BtypeID 	VARCHAR(50),	--客户ID
	@OldPrice 	 NUMERIC(24, 10) ,	--原发货价
	@NewPrice 	 NUMERIC(24, 10) ,	--新价格
	@Date 		VARCHAR(25),		--截止日期	
	@WriteDate 	VARCHAR(25),		--登记日期
	@WriteID 	VARCHAR(50),	--登记人ID
	@State		VARCHAR(25),	--状态
	@CurID  	VARCHAR(10),	--当前修改的记录
	@StartDate 	VARCHAR(25),
	@EndDate  	VARCHAR(25),
	@BillType   VARCHAR(20),
	@stypeid	VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON 

--------	权限检查 - Start	--------
IF @OperatorId IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorId, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------
IF @chvMStypeid='-99999' AND @STypeId=''
	RETURN -2
	
UPDATE	PriceProtect
SET     PtypeID=@PtypeID,
		BtypeID=@BtypeID,
		OldPrice=dbo.F_RoundPrice(@OldPrice),
		NewPrice=dbo.F_RoundPrice(@NewPrice),
		[Date]=@Date,
		WriteDate=@WriteDate,
		WriteID=@WriteID,
		State=@State,
		StartDate=@StartDate,
		EndDate=@EndDate,
		BillType=@BillType,
		stypeid=@stypeid
WHERE 	PriceId=@CurID


IF @@ROWCOUNT = 0
	RETURN -1
ELSE
	RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_UpdatePriceRuleIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_UpdatePriceRuleIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
--**********************************************
--编写人:覃雨翔
--用  途:取价规则，主表信息修改
--时  间:2013-06-09
--**********************************************
CREATE PROCEDURE Gp_UpdatePriceRuleIndex
(
     @BillNumberID                   INT
    ,@UserCode                       VARCHAR(200)
    ,@FullName                       VARCHAR(200)
    ,@PriceBillIndexID               INT
    ,@VipConfig                      INT
    ,@KConfig                        INT
    ,@EConfig                        INT
    ,@StartDate                      DATETIME
    ,@EndDate                        DATETIME
    ,@StartTime                      VARCHAR(10)
    ,@EndTime                        VARCHAR(10)
    ,@PriceDay                       VARCHAR(7)
    ,@Comment                        VARCHAR(255)
    ,@State                          INT
    ,@Checke                         VARCHAR(50)
    ,@Checker                        VARCHAR(50)
    ,@VaildDate                      DATETIME
    ,@DeletedR                       VARCHAR(50)
    ,@DeletedDate                    DATETIME
    ,@CreateDate                     DATETIME
    ,@BConfig                        INT
    ,@VipEnable                      INT
    ,@BtypeEnable                    INT
    ,@VBEnable                       INT
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE PriceRule
   SET UserCode=@UserCode
      ,FullName=@FullName
      ,PriceBillIndexID=@PriceBillindexID
      ,VipConfig=@VipConfig
      ,KConfig=@KConfig
      ,EConfig=@EConfig
      ,StartDate=@StartDate
      ,EndDate=@EndDate
      ,StartTime=@StartTime
      ,EndTime=@EndTime
      ,PriceDay=@PriceDay
      ,Comment=@Comment
      ,State=@State
      ,Checke=@Checke
      ,Checker=@Checker
      ,VaildDate=@VaildDate
      ,DeletedR=@DeletedR
      ,DeletedDate=@DeletedDate
      ,CreateDate=@CreateDate
      ,XiWaMaxNumber=XiWaMaxNumber+1
      ,BConfig =@BConfig
      ,VipEnable = @VipEnable
      ,BtypeEnable = @BtypeEnable
      ,VBEnable = @VBEnable
WHERE ID=@BillNumberID


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateProduceAndValidDateByConfig]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_UpdateProduceAndValidDateByConfig]
GO          

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 时间：	2017-09-11
-- 作者：	glj
-- 功能：	升级处理时当发现成本算法是 先进先出/后进先出 两种成本算法，如果单据明细中生产日期或效期至有数据，则应该处理为空
-- ========================================================================
CREATE PROC Gp_UpdateProduceAndValidDateByConfig

AS
SET NOCOUNT ON

DECLARE 
	@iniRowId	INT=1,
	@endRowId	INT=0,
	@SQL		VARCHAR(MAX)='',
	@TableName	VARCHAR(100)
	
--单据明细中有生产日期/效期至/批号的表
CREATE TABLE #UpdateTable(NId INT IDENTITY(1,1),TableName VARCHAR(100)) 
INSERT INTO #UpdateTable(TableName)
SELECT name 
FROM sysobjects O
WHERE 
	EXISTS(SELECT TOP 1 1 FROM syscolumns c WHERE c.name = 'ProduceDate' AND c.id=o.id ) 
	AND o.xtype = 'u' 
	AND EXISTS(SELECT TOP 1 1 FROM BillName b WHERE b.detailTable=o.name)
	AND EXISTS(SELECT TOP 1 1 
				FROM sysobjects F
				WHERE 
					EXISTS(SELECT TOP 1 1 FROM syscolumns c WHERE c.name = 'ValidDate' AND c.id=F.id ) 
					AND F.xtype = 'u' 
					AND EXISTS(SELECT TOP 1 1 FROM BillName b WHERE b.detailTable=F.name)
					AND F.name=O.name)
	AND EXISTS(SELECT TOP 1 1 
					FROM sysobjects G
					WHERE 
						EXISTS(SELECT TOP 1 1 FROM syscolumns c WHERE c.name = 'GoodsNumber' AND c.id=G.id ) 
						AND G.xtype = 'u' 
						AND EXISTS(SELECT TOP 1 1 FROM BillName b WHERE b.detailTable=G.name)
						AND G.name=O.name)
SELECT @endRowId=@@ROWCOUNT

WHILE(@iniRowId<=@endRowId)
	BEGIN
		SELECT @TableName=TableName FROM #UpdateTable WHERE NId=@iniRowId
		
		SET @SQL+='UPDATE '+@TableName+' SET ProduceDate='''',ValidDate='''',GoodsNumber='''' WHERE ISNULL(ProduceDate,'''')<>'''' OR ISNULL(ValidDate,'''')<>'''' OR ISNULL(GoodsNumber,'''')<>'''''+CHAR(13)
		
		SET @iniRowId=@iniRowId+1
	END
EXEC(@SQL)

--单据明细中有只有生产日期没有效期至的表
DECLARE @ProduceDate TABLE(NId INT IDENTITY(1,1),TableName VARCHAR(100)) 
INSERT INTO @ProduceDate(TableName)
SELECT name 
FROM sysobjects O
WHERE 
	EXISTS(SELECT TOP 1 1 FROM syscolumns c WHERE c.name = 'ProduceDate' AND c.id=o.id ) 
	AND o.xtype = 'u' 
	AND EXISTS(SELECT TOP 1 1 FROM BillName b WHERE b.detailTable=o.name)
	AND Not EXISTS(SELECT TOP 1 1 FROM #UpdateTable WHERE TableName=O.name)
SELECT @endRowId=@@ROWCOUNT

SET @iniRowId=1
SET @SQL=''
WHILE(@iniRowId<=@endRowId)
	BEGIN
		SELECT @TableName=TableName FROM @ProduceDate WHERE NId=@iniRowId
		
		SET @SQL+='UPDATE '+@TableName+' SET ProduceDate='''' WHERE ISNULL(ProduceDate,'''')<>'''''+CHAR(13)
		
		SET @iniRowId=@iniRowId+1
	END
EXEC(@SQL)


--单据明细中有只有效期至没有生产日期的表
DECLARE @ValidDate TABLE(NId INT IDENTITY(1,1),TableName VARCHAR(100)) 
INSERT INTO @ValidDate(TableName)
SELECT name 
FROM sysobjects O
WHERE 
	EXISTS(SELECT TOP 1 1 FROM syscolumns c WHERE c.name = 'ValidDate' AND c.id=o.id ) 
	AND o.xtype = 'u' 
	AND EXISTS(SELECT TOP 1 1 FROM BillName b WHERE b.detailTable=o.name)
	AND Not EXISTS(SELECT TOP 1 1 FROM #UpdateTable WHERE TableName=O.name)
SELECT @endRowId=@@ROWCOUNT

SET @iniRowId=1
SET @SQL=''
WHILE(@iniRowId<=@endRowId)
	BEGIN
		SELECT @TableName=TableName FROM @ValidDate WHERE NId=@iniRowId
		
		SET @SQL+='UPDATE '+@TableName+' SET ValidDate='''' WHERE ISNULL(ValidDate,'''')<>'''''+CHAR(13)
		
		SET @iniRowId=@iniRowId+1
	END
EXEC(@SQL)


--单据明细中有只有效期至没有生产日期的表
DECLARE @GoodsNumber TABLE(NId INT IDENTITY(1,1),TableName VARCHAR(100)) 
INSERT INTO @GoodsNumber(TableName)
SELECT name 
FROM sysobjects O
WHERE 
	EXISTS(SELECT TOP 1 1 FROM syscolumns c WHERE c.name = 'GoodsNumber' AND c.id=o.id ) 
	AND o.xtype = 'u' 
	AND EXISTS(SELECT TOP 1 1 FROM BillName b WHERE b.detailTable=o.name)
	AND Not EXISTS(SELECT TOP 1 1 FROM #UpdateTable WHERE TableName=O.name)
SELECT @endRowId=@@ROWCOUNT

SET @iniRowId=1
SET @SQL=''
WHILE(@iniRowId<=@endRowId)
	BEGIN
		SELECT @TableName=TableName FROM @GoodsNumber WHERE NId=@iniRowId
		
		SET @SQL+='UPDATE '+@TableName+' SET GoodsNumber='''' WHERE ISNULL(GoodsNumber,'''')<>'''''+CHAR(13)
		
		SET @iniRowId=@iniRowId+1
	END
EXEC(@SQL)

--删除临时表
DROP TABLE #UpdateTable


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




GO
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_UpdatePromoRuleBillIndex]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_UpdatePromoRuleBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
--**********************************************
--编写人:覃雨翔
--用  途:促销规则档案，主表信息修改
--时  间:2013-05-28
--**********************************************
CREATE PROCEDURE Gp_UpdatePromoRuleBillIndex
(
     @BillNumberID              INT
    ,@BillCode                  VARCHAR(200) --单据编号
    ,@FullName                  VARCHAR(200) --活动名称
    ,@PromoStylePtype           INT          --促销模式值商品0=买满金额，1=买够商品
    ,@PromoStyleDiscount        INT          --促销模式之折扣0=减免金额  1=送点券 2=送赠品 3=打折 4=特价
    ,@VIPConfig                 INT          --会员卡设定
    ,@KConfig                   INT          --仓库设定
    ,@EConfig                   INT          --业务员设定
    ,@PConfig                   INT          --商品设定
    ,@CalculateStyle            INT          --计算方式
    ,@BindType                  INT          --捆绑方式
    ,@ReachCondition            INT          --达到条件
    ,@AccumulatedProfits        INT          --累计让利
    ,@DoubleDiscount            INT          --折上有效
    ,@BillState                 INT          --单据状态
    ,@Checke                    VARCHAR(50)  --制单人
    ,@Checker                   VARCHAR(50)  --审核人
    ,@VaildDate                 DATETIME     --审核时间
    ,@CreateDate                DATETIME     --创建时间
    ,@DeletedR                  VARCHAR(50)  --作废人
    ,@DeletedDate               DATETIME     --作废时间
    ,@StartDate                 DATETIME     --生效日期
    ,@EndDate                   DATETIME     --失效时期
    ,@StartTime                 VARCHAR(10)  --起始阶段
    ,@EndTime                   VARCHAR(10)  --结束阶段
    ,@PriceDay                  VARCHAR(7)   --取价日设定
    ,@Comment                   VARCHAR(255) --备注
    ,@GiftsType                 INT          --赠品类别
    ,@BtypeConfig               INT          --往来单位类别 0=适用全部往来单位,1=适用部分往来单位,2=适用部分结算单位
    ,@promotype					INT			 --0表示每天，1表示每周，2表示每月第几天选项，3表示每月第几周周几选项；当PromoType为2或者3时，前台每月这个选项才生效。
	,@pricemonthday				INT			 --此时PromoType=2，表示每月的第几天，取整值1-31<每月不同>
	,@pricemonthweek			VARCHAR(10)	 --此时PromoType=3，表示每月的第几周的周几，第一个字符表示第几周，第二个字符表示周几，比如“11”，表示当月的第一个周一，第一个字符取值范围1-6，第二个字符取值范围1-7
	,@pricemonthweektype		INT			 --1.第一个选项   2.第二个选项    
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE	PromoRule 
SET		BillCode=@BillCode
        ,FullName=@FullName
        ,PromoStylePtype=@PromoStylePtype
        ,PromoStyleDiscount=@PromoStyleDiscount
        ,VIPConfig=@VIPConfig
        ,KConfig=@KConfig
        ,EConfig=@EConfig
        ,PConfig=@PConfig
        ,CalculateStyle=@CalculateStyle
        ,BindType=@BindType
        ,ReachCondition=@ReachCondition
        ,AccumulatedProfits=@AccumulatedProfits
        ,DoubleDiscount=@DoubleDiscount
        ,BillState=@BillState
        ,Checke=@Checke
        ,Checker=@Checker
        ,VaildDate=@VaildDate
        ,CreateDate=@CreateDate
        ,DeletedR=@DeletedR
        ,DeletedDate=@DeletedDate
        ,StartDate=@StartDate
        ,EndDate=@EndDate
        ,StartTime=@StartTime
        ,EndTime=@EndTime
        ,PriceDay=@PriceDay
        ,Comment=@Comment
        ,GiftsType=@GiftsType
        ,XiWaMaxNumber=ISNULL(XiWaMaxNumber,0)+1
        ,BtypeConfig = @BtypeConfig                    
        ,promotype = @promotype
        ,pricemonthday = @pricemonthday
        ,pricemonthweek = @pricemonthweek
        ,pricemonthweektype = @pricemonthweektype
WHERE	ID=@BillNumberID  
               
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_UpdatePtypeIDInCoupon]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
	DROP PROCEDURE [dbo].[GP_UpdatePtypeIDInCoupon]
END
GO

/*
	功能：商品搬移后，如果该新节点和其父节点被同一个优惠券名称引用，则删除该节点在优惠券中的引用
	创建人：李德强
	创建时间：2018-01-16
*/
CREATE PROCEDURE GP_UpdatePtypeIDInCoupon
(
@TypeID VARCHAR(100),
@ParID VARCHAR(100) 
)
--@encode$--
AS
BEGIN
	
	DECLARE @tempIndex INT
	DECLARE @tempCount INT
	DECLARE @tempCouponID VARCHAR(100)
	 
	--存储引用了该商品的优惠券id
	CREATE TABLE #tempCouponID(id INT IDENTITY(1,1), couponid INT)
	
	IF @ParID <> '00000'
	BEGIN
		--查找引用了目标节点父节点的优惠券
		INSERT INTO #tempCouponID ( couponid ) 
		SELECT CTI.CouponId FROM dbo.Coupon_TypeInfo CTI
		INNER JOIN dbo.Coupon_ApplyPtype CAP2 ON CTI.CouponId = CAP2.CouponId AND CAP2.IsExchangePtype = 0 AND CAP2.PtypeId = @ParID 
		
		SET @tempIndex = 1
		SELECT @tempCount = COUNT(1) FROM #tempCouponID
		
		WHILE @tempIndex <= @tempCount
		BEGIN
			SELECT @tempCouponID = couponid FROM #tempCouponID WHERE id = @tempIndex
			DELETE FROM dbo.Coupon_ApplyPtype WHERE CouponId = @tempCouponID AND IsExchangePtype = 0 AND PtypeId <> @ParID AND PtypeId LIKE @ParID + '%'
			SET @tempIndex += 1 
		END
		
	END
	
	DROP TABLE #tempCouponID
 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
 




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_UpdatePullSignalBillState]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_UpdatePullSignalBillState]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：武智均
	日期：2019-11-25
	描述：要货申请单状态改变
*/
CREATE  PROCEDURE Gp_UpdatePullSignalBillState
(
	@BillIds	VARCHAR(MAX),--单据ID字符串
	@BillState	INT,--单据操作类型 要修改到类型 0原始，2接受，3拒绝，4作废
	@OperatorId	VARCHAR(50),--当前操作员ID
	@IP			VARCHAR(50)--当前操作员ID
)
AS
SET NOCOUNT ON 

CREATE TABLE #Bill
(
	BillNumberId	NUMERIC(24,0),--单据ID
	BillCode		VARCHAR(200),--单据编号
	BillState		INT,--单据状态
	ExecState		INT,--单据执行状态
)

INSERT INTO #Bill(ExecState,BillNumberId,BillCode,BillState)
SELECT CASE WHEN pb.isdone = 1 THEN 7
			WHEN T.Qty > 1 THEN 6
			ELSE 0 END AS execstate,
			pb.billnumberid,
			pb.BillCode,
			pb.BillState
FROM f_split(@BillIds,',') FB
INNER JOIN PosAllotApplyBillIndex pb ON pb.BillNumberId = FB.a
LEFT JOIN(
        SELECT ISNULL(SUM(db.Qty),0) Qty,da.BillNumberId FROM dbo.DeliveryBill db 
        INNER JOIN dbo.DeliveryApplyBill da ON da.ID = db.DeliveryApplyBillId
        INNER JOIN PosAllotApplyBillIndex pab ON db.BillNumberId = pab.BillNumberId
        WHERE pab.BillType = 327 AND pab.ifcheck = 't' AND pab.RedWord=0
        GROUP BY da.BillNumberId
)T ON T.BillNumberId = pb.BillNumberId
WHERE pb.BillType = 326
    
       
--//单据状态 0原始，2接受，3拒绝，4作废
--//单据执行状态 6-已完成 7-已引用未完成
IF(@BillState=2)--2-接受
	BEGIN
		UPDATE B SET B.BillState=@BillState,B.Checker = @OperatorId,B.CheckerTime = GETDATE()
		FROM PosAllotApplyBillIndex B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(0,3) AND ExecState NOT IN (6,7)
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(0,3) OR ExecState IN (6,7)
	END
ELSE IF(@BillState=3)--4-拒绝
	BEGIN
		UPDATE B SET B.BillState=@BillState,B.Checker = @OperatorId,B.CheckerTime = GETDATE()
		FROM PosAllotApplyBillIndex B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(0,2) AND ExecState NOT IN (6,7)
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(0,2) OR ExecState IN (6,7)
		
	END
ELSE IF(@BillState=4)--4-作废
	BEGIN
		UPDATE B SET B.BillState=@BillState,B.Updater = @OperatorId,B.UpdaterTime = GETDATE()
		FROM PosAllotApplyBillIndex B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(0,2,3) AND ExecState NOT IN (6,7)
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(0,2,3) OR ExecState IN (6,7)
		
	END
ELSE IF(@BillState=0)--反作废
	BEGIN
		UPDATE B SET B.BillState=@BillState,B.Updater = @OperatorId,B.UpdaterTime = GETDATE()
		FROM PosAllotApplyBillIndex B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(4)
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(4)
		
	END
ELSE IF(@BillState=-1)-- -1-删除 【原始，已拒绝，已作废】
	BEGIN
		--插入删除日志
		INSERT INTO BillDeleteLog
		(
			BillNumberID
			,BillType
			,BillCode
			,BillDate
			,StypeID
			,BtypeID
			,DealBTypeID
			,Checke
			,DelDate
			,DelEtypeID
			,DelIP
		)
		SELECT 
			B.BillNumberId,
			B.BillType,
			B.BillCode,
			B.BillDate,
			B.StypeId,
			'' BTypeId,
			'' DealBTypeId,
			B.checkE,
			GETDATE(),
			@OperatorId,
			@IP
		FROM PosAllotApplyBillIndex  B
		INNER JOIN #Bill F ON F.BillNumberId=B.BillNumberId AND F.BillState IN(0,3,4) AND ExecState NOT IN (6,7)
			
		--删除明细表
		DELETE FROM T
		FROM DeliveryApplyBill T
		INNER JOIN #Bill B ON B.BillNumberId=T.BillNumberId AND B.BillState IN(0,3,4) AND ExecState NOT IN (6,7)
			
		--删除主表
		DELETE FROM T
		FROM PosAllotApplyBillIndex T
		INNER JOIN #Bill B ON B.BillNumberId=T.BillNumberId AND B.BillState IN(0,3,4) AND ExecState NOT IN (6,7)
		
		--返回不满足操作条件单据
		SELECT BillNumberId,BillCode ErrCode FROM #Bill F WHERE F.BillState NOT IN(0,3,4) OR ExecState IN (6,7)
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO

IF EXISTS (SELECT Name FROM SysObjects WHERE ID=OBJECT_ID(N'dbo.Gp_UpdateReceiptBillIndex',N'P'))
BEGIN
	DROP PROC dbo.Gp_UpdateReceiptBillIndex;
END
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

/*
			作者：司华山
			日期：2015-05-14
			描述：修改发票主表记录
*/

CREATE PROC dbo.Gp_UpdateReceiptBillIndex
(
	@BillNumberId		    INT,
	@BillDate				DATETIME,
	@BillCode				VARCHAR(200),
	@BillType				NUMERIC(4,0),
	@FaPiaoType				CHAR(1),
	@FaPiaoCode				VARCHAR(256),
	@Comment				VARCHAR(256),
	@Explain				VARCHAR(256),
	@BTypeID				VARCHAR(100),
	@ETypeID			    VARCHAR(100),
	@DTypeID				VARCHAR(100),
	@checke					VARCHAR(100),
	@Tax					 NUMERIC(24, 10) ,
	@TotalQty				 NUMERIC(24, 10) ,
	@TotalMoney				 NUMERIC(24, 10) ,
	@TaxTotalMoney			 NUMERIC(24, 10) ,
	@Stypeid				VARCHAR(50),
	@OtherTotal				 NUMERIC(24, 10) ,
	@ifYearBill				INT,
	@IsIni					BIT,
	@CID					INT,
	@Rate					 NUMERIC(24, 10) ,
	@NTotalMoney			 NUMERIC(24, 10) ,
	@NTaxTotalMoney			 NUMERIC(24, 10) ,
	@DealBTypeID			VARCHAR(50),
	@TaskType				TINYINT,
	@AlertDay				INT,
	@RedWord				INT,
	@ifcheck				CHAR(1), 
	@IfStopMoney			INT, 
	@CompleteTotal			 NUMERIC(24, 10)  ,
	@NCompleteTotal			 NUMERIC(24, 10)  ,
	@Draft					BIT,
	@JSState				CHAR(1),
	@JSStyle				CHAR(1),
	@Poster					VARCHAR(100)  ,
	@UpdateE				VARCHAR(100),
	@IfAudit				CHAR(1),
	@ATypeID1				VARCHAR(50),
	@ATypeID2				VARCHAR(50),
	@ATID					INT,
	@Reconciliation			CHAR(1),
	@ModifyAuditBill		INT=-1,
	@ChargeOffTotal			NUMERIC(24, 10) ,
	@NChargeOffTotal		NUMERIC(24, 10) 
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	--不存在
	IF NOT EXISTS(SELECT TOP 1 1 FROM ReceiptBillIndex WHERE BillNumberID = @BillNumberId AND BillType = @BillType)
	BEGIN
		RETURN -7
	END
		--对于审核未通过的，或更改了分支机构的之前提交过审核的单据，都把审核历程删掉
	IF EXISTS(
		SELECT BillNumberID
		FROM AuditingBill
		WHERE BillNumberID=@BillNumberId AND IfAudit=-1
	)
	BEGIN
		DELETE AuditingBillDetail WHERE BillNumberID=@BillNumberId AND BillIndexType=5
		DELETE AuditingBill
		WHERE BillNumberID=@BillNumberId AND BillIndexType=5
	END
	
	IF @ModifyAuditBill<>1 AND EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBillIndex WHERE ifcheck='t' AND Draft=0 AND BillNumberID=@BillNumberId AND BillType=@BillType
			  UNION ALL
			  SELECT TOP 1 1 FROM dbo.ListTable WHERE BillNumberId=@BillNumberId AND BillType=@BillType
			  UNION ALL
			  SELECT TOP 1 1 FROM dbo.InOutstocktable WHERE BillNumberId=@BillNumberId AND BillType=@BillType
			  )
		RETURN -1
	
	DELETE FROM dbo.Custom_BillDetails WHERE BillId=@BillNumberId AND BillType=@BillType
	DELETE FROM dbo.Custom_BillIndex WHERE BillId=@BillNumberId AND BillType=@BillType
		
	UPDATE	ReceiptBillIndex	SET							
								  BillDate=@BillDate				
								 ,BillCode=@BillCode			
								 ,BillType=@BillType			
								 ,FaPiaoType=@FaPiaoType		
								 ,FaPiaoCode=@FaPiaoCode	
								 ,Comment=@Comment
								 ,Explain=@Explain		
								 ,BTypeID=@BTypeID		
								 ,ETypeID=@ETypeID	  
								 ,DTypeID=@DTypeID
								 ,checke=@checke			
								 ,Tax=dbo.F_RoundTax(@Tax)	
								 ,TotalQty=dbo.F_RoundQty(@TotalQty)				
								 ,TotalMoney=dbo.F_RoundTotal(@TotalMoney)		
								 ,TaxTotalMoney=dbo.F_RoundTotal(@TaxTotalMoney)
								 ,Stypeid=@Stypeid
								 ,OtherTotal=dbo.F_RoundTotal(@OtherTotal)
								 ,ifYearBill=@ifYearBill	
								 ,IsIni=@IsIni
								 ,CID=@CID			
								 ,Rate=dbo.F_RoundExchangeRate(@Rate)				
								 ,NTotalMoney=dbo.F_RoundTotal(@NTotalMoney)			
								 ,NTaxTotalMoney=dbo.F_RoundTotal(@NTaxTotalMoney)	
								 ,DealBTypeID=@DealBTypeID
								 ,TaskType=@TaskType
								 ,AlertDay=@AlertDay	
								 ,RedWord=@RedWord	
								 ,ifcheck=@ifcheck		
								 ,IfStopMoney=@IfStopMoney		
								 ,CompleteTotal=dbo.F_RoundTotal(@CompleteTotal)
								 ,NCompleteTotal=dbo.F_RoundTotal(@NCompleteTotal)
								 ,Draft=@Draft
								 ,JSState=@JSState			
								 ,JSStyle=@JSStyle		
								 ,Poster=@Poster			
								 ,LastUpdateTime=GETDATE()			
								 ,checkTime=ISNULL(checkTime,GETDATE())
								 ,UpdateE=@UpdateE				
								 ,IfAudit=@IfAudit		
								 ,ATypeID1=@ATypeID1		
								 ,ATypeID2=@ATypeID2
								 ,ATID=@ATID
								 ,Reconciliation=@Reconciliation
								 ,ChargeOffTotal=@ChargeOffTotal
								 ,NChargeOffTotal=@ChargeOffTotal
	  WHERE BillNumberID=@BillNumberId
	  SET NOCOUNT OFF
END
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateReceiptState]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_UpdateReceiptState
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2015-05-27
	描述：暂估发票过账后修改原来的开票状态,回写开票数量和金额
	
*/

CREATE PROCEDURE [dbo].[GP_UpdateReceiptState]
(
	@strGoodsBillNumberID		VARCHAR(50),
	@intBillType				INT,
	@strReceiptBillNumberID		VARCHAR(50),
	@intRedWord					INT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @strSql NVARCHAR(MAX)=''

DECLARE @Operator VARCHAR(1)='+'

SET @Operator=CASE @intRedWord WHEN 0 THEN '+' ELSE '-' END

DECLARE @dbname VARCHAR(50)=''

SELECT @dbname=detailTable
FROM BillName
WHERE Billtype=@intBillType

--将开票的金额回写到billindex 和明细表
DECLARE @TOTAL VARCHAR(MAX)='',@NTOTAL VARCHAR(MAX)='',@iQty  VARCHAR(MAX)='',@iNQty  VARCHAR(MAX)='',
		@SALETOTAL VARCHAR(MAX)='',@NSALETOTAL VARCHAR(MAX)='',@TAXTOTAL VARCHAR(MAX)='',@NTAXTOTAL VARCHAR(MAX)='',
		@CostTotal VARCHAR(MAX)=''


	SET @SALETOTAL=CASE WHEN @intBillType IN (401,403) THEN '-F.SaleTotal' ELSE 'F.SaleTotal' END 
	SET @NSALETOTAL= CASE WHEN @intBillType IN (401,403) THEN '-F.NSaleTotal' ELSE 'F.NSaleTotal' END 
	SET @TOTAL=CASE WHEN @intBillType IN (401,403) THEN '-F.Total' ELSE 'F.Total' END 
	SET @NTOTAL= CASE WHEN @intBillType IN (401,403) THEN '-F.NTotal' ELSE 'F.NTotal' END 
	SET @TAXTOTAL=CASE WHEN @intBillType IN (401,403) THEN '-F.TaxTotal' ELSE 'F.TaxTotal' END 
	SET @NTAXTOTAL= CASE WHEN @intBillType IN (401,403) THEN '-F.NTaxTotal' ELSE 'F.NTaxTotal' END 
	SET @iQty=CASE WHEN @intBillType IN (401,403) THEN '-F.Qty' ELSE 'F.Qty' END 
	SET @iNQty=CASE WHEN @intBillType IN (401,403) THEN '-F.NQty' ELSE 'F.NQty' END 
	SET @CostTotal=CASE WHEN @intBillType IN (401,403) THEN '-F.InvoiceCostTotal' ELSE 'F.InvoiceCostTotal' END 
	
	SET @strSql= '
		UPDATE Billindex
		SET InvoiceMoney=InvoiceMoney'+@Operator+'C.Total,
			NInvoiceMoney=NInvoiceMoney'+@Operator+'C.NTotal
		FROM 
		(
			SELECT	SUM('+@TAXTOTAL+') AS Total,
					SUM('+@nTAXTOTAL+') AS NTotal,
					MainBillNumberID
			FROM	dbo.ReceiptBill F
			WHERE BillNumberID ='+@strReceiptBillNumberID+'
			GROUP BY MainBillNumberID
		)C
		WHERE C.MainBillNumberID=Billindex.BillNumberId
		AND	C.MainBillNumberID='+@strGoodsBillNumberID
				
	SET @strSql =@strSql +'
		UPDATE '+@dbname+'
		SET	InvoiceQty=InvoiceQty'+@Operator+'C.QTY,
			InvoiceNQty=InvoiceNQty'+@Operator+'C.NQTY,
			InvoiceSaleMoney=InvoiceSaleMoney'+@Operator+'C.SALETotal,
			NInvoiceSaleMoney=NInvoiceSaleMoney'+@Operator+'C.NSALETotal,
			InvoiceMoney=InvoiceMoney'+@Operator+'C.TaxTotal,
			NInvoiceMoney=NInvoiceMoney'+@Operator+'C.NTaxTotal,
			InvoiceMoneyEX=InvoiceMoneyEX'+@Operator+'C.Total,
			NInvoiceMoneyEX=NInvoiceMoneyEX'+@Operator+'C.NTotal,
			InvoiceCostTotal=InvoiceCostTotal'+@Operator+'C.CostTotal
			
		FROM 
		(
			SELECT	SUM('+@iqty+') AS QTY,
					SUM('+@iNQty+') AS NQTY,
					SUM('+@SALETOTAL+') AS SALETotal,
					SUM('+@NSALETOTAL+') AS NSALETotal,
					SUM('+@TOTAL+') AS Total,
					SUM('+@NTOTAL+') AS NTotal,
					SUM('+@TAXTOTAL+') AS TAXTotal,
					SUM('+@NTAXTOTAL+') AS NTAXTotal,
					SUM('+@CostTotal+') AS CostTotal,
					RecordedItemId,
					MainBillNumberID
			FROM	dbo.ReceiptBill F
			WHERE BillNumberID ='+@strReceiptBillNumberID+'
			GROUP BY F.RecordedItemId,MainBillNumberID
		)C
		WHERE C.MainBillNumberID='+@dbname+'.BillNumberId
		AND	C.RecordedItemId='+@dbname+'.ID
		AND	C.MainBillNumberID='+@strGoodsBillNumberID


--PRINT(@strSql)
EXEC (@strSql)

DECLARE @IfInvoice int=2
SET @strSql ='
IF EXISTS(SELECT 1 FROM '+@dbname+ ' WHERE Billnumberid=@BillNumberID AND QTY>InvoiceQty)
	SET @IfInvoice=1'
--PRINT @strSql	
EXEC SP_EXECUTESQL @strSql,N'@IfInvoice INT OUTPUT,@BillNumberID INT',@IfInvoice OUTPUT,@strGoodsBillNumberID;

UPDATE BillIndex SET IfInvoice=@IfInvoice  WHERE BillNumberId=@strGoodsBillNumberID 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateRecPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateRecPrice]
GO















/****** Object:  Stored Procedure dbo.Gp_UpdateRecPrice    Script Date: 2002-6-20 10:14:52 ******/

CREATE  PROCEDURE Gp_UpdateRecPrice 
(
 @szPtypeid varchar(100),
 @RecPrice  NUMERIC(24, 10) 
)
--@encode$--
AS
SET NOCOUNT ON 
set nocount on
update ptype set recprice=dbo.F_RoundPrice(@RecPrice) where typeid=@szPtypeid
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateReduceVipCardCent]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_UpdateReduceVipCardCent]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：glj
	日期：2018-08-03
	描述：pos付款生成积分调整单
*/
CREATE PROCEDURE Gp_UpdateReduceVipCardCent
(
	@VipCardID	INT,
	@BillDate	VARCHAR(20),
	@JFPayTotal	NUMERIC(24,10),
	@OperatorId	VARCHAR(50),
	@ErrorMsg	VARCHAR(200) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

SET @BillDate=CONVERT(VARCHAR(100),GETDATE(), 23)

IF NOT EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardID=@VipCardID)
	BEGIN
		SET @ErrorMsg='请录入正确的卡号' 
		RETURN
	END
IF NOT EXISTS(SELECT TOP 1 1 FROM Employee WHERE typeId = @OperatorId AND sonnum=0 AND deleted=0)
	BEGIN
		SET @ErrorMsg='经手人不正确' 
		RETURN
	END
	
IF NOT EXISTS(SELECT VipCardID FROM nVipCardSign WHERE VipCardID=@VipCardID AND Deleted=0 AND EndDate>=@BillDate)
	BEGIN
		SET @ErrorMsg='单据日期不能大于会员卡的有效期' 
		RETURN
	END
	
--开账前不能过账
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'inicanmodify' AND SubValue = 'T') 
	BEGIN
		SET @ErrorMsg='系统没有开账，不能开单！' 
		RETURN
	END

--录单日期不能小于开帐日期
IF EXISTS(SELECT TOP 1 1 FROM MonthProc WHERE Period =(select subvalue from sysdata where subname='period') AND StartDate>@BillDate)
	BEGIN
		SET @ErrorMsg='录单日期不能小于本期开始日期' 
		RETURN
	END

--当前积分小于能扣款金额的积分
IF EXISTS(SELECT * FROM nVipCardSign N INNER JOIN NVipCardSet S ON S.VipCardTypeID=N.VipCardTypeID AND N.VipCardID=@VipCardID AND (N.totalCent+N.BeginCent)<S.CentToMoney*@JFPayTotal )
	BEGIN
		SET @ErrorMsg='当前会员卡积分小于抵扣金额积分，请确认！' 
		RETURN
	END

DECLARE 
	@nBillId NUMERIC(18,0),--单据ID
	@BillCode	VARCHAR(200)='',
	@DownScore	INT--扣减积分
SELECT @DownScore=S.CentToMoney*@JFPayTotal FROM nVipCardSign N INNER JOIN NVipCardSet S ON S.VipCardTypeID=N.VipCardTypeID AND N.VipCardID=@VipCardID 
--单据编号
EXEC Gp_GetAdjustCode 'JFC',@BillDate,@BillCode OUTPUT

IF NOT EXISTS(SELECT TOP 1 1 FROM nVipAdjust)
	SET @nBillID = 1
ELSE
	SELECT @nBillId = ISNULL(MAX(BillNumberId),0) + 1 FROM nVipAdjust


INSERT INTO nVipAdjust
(
	BillNumberId,
	BillDate,
	BillCode,
	ETypeId,
	Checke,
	VipNo,
	UpCost,
	DownCost,
	SumCost,
	Reason,
	IsSend,
	nType
)
VALUES
(
	@nBillId,
	@BillDate,
	@BillCode,
	@OperatorId,
	@OperatorId,
	@VipCardID,
	0,
	@DownScore,
	-@DownScore,
	'POS积分收款',
	0,
	2 
)
	
UPDATE nVipCardSign SET totalCent-=@DownScore WHERE VipCardID = @VipCardID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateRepairCarAndBtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateRepairCarAndBtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




/*
	作者：WANG WEI
	日期：2010-06-24
	描述：更改车辆信息
*/

CREATE  PROCEDURE GP_UpdateRepairCarAndBtype
(
	@OperatorID			VARCHAR(100),
	@ratypeid			VARCHAR(200),
	@billnumberid		DECIMAL(18,0),
	@Btypeid			VARCHAR(200)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
IF NOT  EXISTS( SELECT  Top 1 1 FROM F_BaseGetAllManagerBaseTypeId(@Btypeid,2,@OperatorID))
BEGIN
	RAISERROR('当前车辆对应的往来单位不在权限范围内，请确认！',16,1)  
	return 
END

DECLARE @billID VARCHAR(MAX)
SET @billID=''
select @billID=@billID+','+CAST( BillNumberId AS VARCHAR(100)) from Billindex_CarRepair where QuickRepairBillID=@billnumberid

DECLARE @BillBackId	VARCHAR(MAX)--查询领料退回的billnumerid
SET @BillBackId=''
SELECT @BillBackId=@BillBackId+','+CAST(billnumberid  AS VARCHAR(100)) FROM Billindex_CarRepair  WHERE QuickRepairBillID IN (SELECT a FROM   f_split(@billID,',') WHERE a<>'')

/*更新接待登记*/

Update BillIndex SET btypeid=@Btypeid WHERE BillNumberId=@billnumberid --更新接待登记的往来单位
Update Billindex_CarRepair SET RATypeID=@ratypeid WHERE BillNumberId=@billnumberid  --更新接待登记的车辆信息
/*更新领料出库*/
Update Billindex_CarRepair SET RATypeID=@ratypeid WHERE BillNumberId IN (SELECT a FROM   f_split(@billID,',') WHERE a<>'')  --更新领料出库的的车辆信息
Update BillIndex SET btypeid=@Btypeid  WHERE BillNumberId IN (SELECT a FROM   f_split(@billID,',') WHERE a<>'')    --更新领料出库的往来单位
UPdate InOutstocktable set BtypeId=@Btypeid WHERE BillNumberId IN (SELECT a FROM   f_split(@billID,',') WHERE a<>'')
Update ListTable Set BtypeId=@Btypeid WHERE BillNumberId IN (SELECT a FROM   f_split(@billID,',') WHERE a<>'')
/*更新领料退回*/
Update Billindex_CarRepair SET RATypeID=@ratypeid WHERE BillNumberId   IN (SELECT a FROM   f_split(@BillBackId,',') WHERE a<>'')  --=@BillBackId--更新领料退回的车辆信息	
Update BillIndex SET btypeid=@Btypeid  WHERE BillNumberId  IN (SELECT a FROM   f_split(@BillBackId,',') WHERE a<>'')    --更新领料退回的往来单位
UPdate InOutstocktable set BtypeId=@Btypeid WHERE BillNumberId   IN (SELECT a FROM   f_split(@BillBackId,',') WHERE a<>'') 
Update ListTable Set BtypeId=@Btypeid WHERE BillNumberId   IN (SELECT a FROM   f_split(@BillBackId,',') WHERE a<>'') 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpDateRepairEngage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpDateRepairEngage]
GO



/*
	作者：谢吉康
	日期：2003-12-30
	描述：修改数据到维修表中
*/
CREATE    PROCEDURE GP_UpDateRepairEngage
(
	@OperatorID		VARCHAR(50),	
	@BillDate		VARCHAR(20),
	@BillCode		VARCHAR(200),
	@BillType		VARCHAR(10),
	@PTypeID		VARCHAR(50),
	@Serial			VARCHAR(256),
	@ETypeID		VARCHAR(50),
	@IfCheck		VARCHAR(10),
	@Checke			VARCHAR(50),
	@RedWord		VARCHAR(10),
	@Draft			INT,
	@Stat			INT,
	@ETypeID1		VARCHAR(50),
	@RepairDate		VARCHAR(20),
	@ETypeName1		VARCHAR(50),
	@Tel			VARCHAR(100),
	@BuyDate		VARCHAR(20),
	@SaleBTypeName	VARCHAR(200),
	@Buyer			VARCHAR(100),
	@Address		VARCHAR(8000),
	@Brief			VARCHAR(256),	
	@Config			VARCHAR(800),
	@RepairType		INT,
	@Attach			VARCHAR(800),
	@Fault			VARCHAR(8000),
	@Comment		VARCHAR(8000),
	@SaleBillID		VARCHAR(66),
	@BillNumberID	INT
)
--@encode$--
AS
BEGIN
	--判断序列号
	SELECT TOP 1 * FROM GP_CruPTypeSerial WHERE Serial = @Serial AND State IN (1,7) AND Flag = 1
	
	IF @@ROWCOUNT <> 0 
		BEGIN
			--RAISERROR('序列号在当前库中，没有出库记录，不允许维修！',16,1)
			RETURN -1
		END
	
	UPDATE 	RepairEngage
	SET		BillDate = @BillDate,
			BillCode = @BillCode,
			BillType = @BillType,
			PTypeID = @PTypeID,
			Serial = @Serial,
			ETypeID = @ETypeID,
			IfCheck = @IfCheck,
			Checke = @Checke,
			RedWord = @RedWord,
			Draft = @Draft,
			Stat = @Stat,
			ETypeID1 = @ETypeID1,
			RepairDate = @RepairDate,
			ETypeName1 = @ETypeName1,
			Tel = @Tel,
			BuyDate = @BuyDate,		
			SaleBTypeName = @SaleBTypeName,
			Buyer = @Buyer,
			Address = @Address,
			Brief = @Brief,
			Config = @Config,
			RepairType = @RepairType,
			Attach = @Attach,
			Fault = @Fault,
			Comment = @Comment,
			SaleBillID = @SaleBillID	
	WHERE BillNumberID = @BillNumberID


	IF @@ROWCOUNT = 0 
		BEGIN
			--RAISERROR('修改维修库失败，请确认后重试！',16,1)
			RETURN -2
		END
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateRepairMode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateRepairMode]
GO













-- ========================================================================
-- 功能说明：	修改维修方式
-- 作    者：	cqhua
-- 2009-11-09
-- ========================================================================
CREATE                PROCEDURE GP_UpdateRepairMode
(
	@billnumberid   varchar(6000), -- 单据ID
	@idstr          varchar(6000), -- 表wx_Bill_JieJian 字段ID
	@repairMode		int 
)	

--@encode$--
AS
CREATE TABLE #Billnumberid 
(
[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
billnumberid numeric(18,0)
)

CREATE TABLE #idstr 
(
[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
idstr numeric(18,0)
)

INSERT INTO #Billnumberid(Billnumberid) select * from dbo.f_split(@billnumberid,',')
INSERT INTO #idstr(idstr) select * from dbo.f_split(@idstr,',')

UPDATE wx_Bill_JieJian set  repairMode =@repairMode
FROM wx_Bill_JieJian a
INNER JOIN #billnumberID b on a.billnumberid=b.billnumberid
INNER JOIN #idstr c on a.ID=c.idstr
WHERE b.ID=c.ID


DROP TABLE #Billnumberid
DROP TABLE #idstr


SET NOCOUNT ON
SET ANSI_WARNINGS OFF








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** 对象:  StoredProcedure [dbo].[Gp_UpdateS]    脚本日期: 05/07/2010 12:33:18 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_UpdateS]

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

--作    者：林军 
--日    期：2010-05-07  
--作    用：更新机构基本信息 




CREATE     PROCEDURE [dbo].[Gp_UpdateS]
(
	@TypeId		[varchar](50),
	@UserCode	[varchar](26),
	@FullName	[varchar](66),
	@SimpleName [varchar](30),
	@Comment	[varchar](256),
	@LinkMan	varchar(20),
	@Tel		varchar(50),
	@Address	varchar(50),
	@PyCode		varchar(200),
	@PostCode	varchar(100),
	@TaxNo		varchar(100),
	@Bank		varchar(100),
	@Account	varchar(100),
	@BTypeId1	varchar(50),
	@BTypeId2	varchar(50),
	@PriceType	varchar(10) = '0',
	@atypeid	varchar(50),
	@atypeid2	varchar(50),
	@atypeid3   VARCHAR(50),
	@atypeid4   VARCHAR(50),
	@isselfverify   INT,
	@verifyid   VARCHAR(50),
	@calcFullName   VARCHAR(100),
	@EtypeId VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON 

-----对应客户和对应供货商
if(isnull(@BTypeID1,'')<>'')
begin
	if  exists(select * from [SType] where BTypeID1=@BTypeID1 and TypeId<>@TypeId)
	begin
		--print '['+@usercode+']机构已存在'
		RAISERROR('该对应客户已经被其它分支机构使用',16,1,@FullName)return--return -101
	end
end

if(isnull(@BTypeID2,'')<>'')
begin
	if  exists(select * from [SType] where BTypeID2=@BTypeID2 and TypeId<>@TypeId)
	begin
		--print '['+@usercode+']机构已存在'
		RAISERROR('该对应供货商已经被其它分支机构使用',16,1,@FullName)return--return -101
	end
end
IF @BTypeID1<>''
	BEGIN
		IF NOT EXISTS(select * from btype where typeId=@BTypeID1)
			BEGIN
				RAISERROR('对应的客户已经不存在，请检查！',16,1)
				RETURN
			END
		IF EXISTS(select * from btype where typeId=@BTypeID1 and sonnum<>0)
			BEGIN
				RAISERROR('对应的客户不是子结点，请检查！',16,1)
				RETURN
			END
	END
IF @BTypeID2<>''
	BEGIN
		IF NOT EXISTS(select * from btype where typeId=@BTypeID2)
			BEGIN
				RAISERROR('对应的供货商已经不存在，请检查！',16,1)
				RETURN
			END
		IF EXISTS(select * from btype where typeId=@BTypeID2 and sonnum<>0)
			BEGIN
				RAISERROR('对应的供货商不是子结点，请检查！',16,1)
				RETURN
			END
	END
if exists(select usercode from SType where (usercode=@usercode  or fullname=@fullname) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
BEGIN
RAISERROR('当前信息名称或编号不能与已有的名称或编号重复',16,1) return
-- print '机构已存在'+@etypeid_1
 --return -3
end
if exists(select usercode from SType where (usercode=@fullname  or fullname=@usercode) and deleted<>1 and typeid<>@typeid and typeid<>'00000')
BEGIN
RAISERROR('当前信息名称或编号不能与已有的名称或编号重复',16,1) return
-- print '机构已存在'+@etypeid_1
 --return -10
END



IF @verifyid <> ''
AND NOT @verifyid is NULL
AND  NOT EXISTS (SELECT 1 FROM SType WHERE TypeId = @verifyid)
BEGIN
    RAISERROR('选择的记账单位不存在。',16,1)
    RETURN
END


IF @isselfverify = 1 AND @verifyid <> @TypeId
BEGIN
	RAISERROR('独立核算时，记账单位只能是其自己.',16,1)
	RETURN
END

-- 核算单位为自己的时候，修改为独立核算
IF @isselfverify = 0 AND @verifyid = @TypeId
BEGIN
	SET @isselfverify = 1;
	RETURN
END

/*

IF @atypeid IS NOT NULL AND NOT EXISTS (SELECT 1 FROM Ac_Account WHERE StypeId = @verifyid AND TypeId = @atypeid)
BEGIN
	RAISERROR('选择的利润科目不存在.',16,1)
	RETURN
END

IF @atypeid2 IS NOT NULL AND NOT EXISTS (SELECT 1 FROM Ac_Account WHERE StypeId = @verifyid AND TypeId = @atypeid2)
BEGIN
	RAISERROR('利润分配科目不存在.',16,1)
	RETURN
END

IF @atypeid3 IS NOT NULL AND NOT EXISTS (SELECT 1 FROM Ac_Account WHERE StypeId = @verifyid AND TypeId = @atypeid3)
BEGIN
	RAISERROR('汇兑损益科目不存在.',16,1)
	RETURN
END
IF @atypeid4 IS NOT NULL AND NOT EXISTS (SELECT 1 FROM Ac_Account WHERE StypeId = @verifyid AND TypeId = @atypeid4)
BEGIN
	RAISERROR('存货科目不存在.',16,1)
	RETURN
END
*/
DECLARE @returnPym varchar(1000)
EXEC @returnPym = fun_getPy @FullName

IF @PyCode <>'' 
SET @returnPym=@PyCode

UPDATE	[dbo].[SType] 
SET 	[FullName]  = @FullName,
		[Name]  = @simplename,
		[UserCode]  = @UserCode,
		[Comment]  = @Comment ,
		[LinkMan]=@LinkMan,
		[Tel]=@Tel,
		[Address]=@Address,
		[PyCode] =@returnPym,
		[PostCode]=@PostCode,
		[TaxNo]=@TaxNo,
		[Bank]=@Bank,
		[Account] =@Account,
		[BTypeId1]=@BTypeId1,
		[BTypeId2]=@BTypeId2,
		[PriceType] = @PriceType,
		[atypeid] = @atypeid,
		[atypeid2] = @atypeid2,
		[atypeid3] = @atypeid3,
		[atypeid4] = @atypeid4,
		[isselfverify] = @isselfverify,
		[verifyid] = @verifyid,
		[calcFullName]=@calcFullName
WHERE 	([typeId]  = @TypeId)

--记账单位已初始化
IF EXISTS(SELECT *FROM SType WHERE TypeId=@verifyid AND IfAssetsIni=1)
BEGIN
	UPDATE SType SET IfAssetsIni=1 WHERE TypeId=@TypeId
END

--9.8独立分支机构开账，分支机构表数据添加
	DECLARE 
		@SFyear		INT,--启用年度
		@SFPeriod	INT--启用期间
		
		SELECT @SFyear=SubValue FROM SysData WHERE SubName='fyear'
		SELECT @SFPeriod=SubValue FROM SysData WHERE SubName='fmonth'
		
IF @isselfverify = 1
BEGIN
--没有就添加
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE STypeId=@TypeId )
 INSERT INTO Ac_AccountsPeroid_Stype
			(
				
				STypeId,
				SFYear,
				SFPeriod,
				FYear,
				FPeriod,
				IsUse
			)VALUES
			(
				
				@TypeId,
				@SFyear,
				@SFPeriod,
				@SFyear,
				@SFPeriod,
				0
			)

END
ELSE
BEGIN
--删除
DELETE FROM Ac_AccountsPeroid_Stype WHERE STypeId=@TypeId
END


--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber numeric(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM SType
UPDATE SType SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @TypeId
IF(EXISTS( SELECT * FROM dbo.SType_UserConfig WHERE StypeId=@verifyid AND Value=1))
	BEGIN
		IF  NOT EXISTS(SELECT * FROM SType_UserConfig WHERE StypeId=@TypeId)
		BEGIN
			INSERT INTO SType_UserConfig( ConfigNo, StypeId, Value, EtypeId )VALUES  ( 1,@TypeId,'1',@EtypeId)
		END
		ELSE
		BEGIN
			UPDATE SType_UserConfig SET Value=1 WHERE StypeId=@TypeId
		END
	END


GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateSaleAllPlan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateSaleAllPlan]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-09-19
--	描述：销售计划修改
---------------------------------------------
CREATE PROCEDURE GP_UpdateSaleAllPlan
(	
	@fullname		VARCHAR(MAX),
	@ifstype		VARCHAR(MAX)=1,
	@year			VARCHAR(MAX)='',
	@moneyunit		varchar(max),
	@planid			VARCHAR(MAX),
	@idtype			VARCHAR(MAX),
	@alltotalindex	VARCHAR(MAX),
	@alltotalplan	VARCHAR(MAX),
	@timeid			VARCHAR(MAX)='',
	@comment		VARCHAR(MAX)

)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @intReturnValue INT
SET @intReturnValue=0
EXEC @intReturnValue=QP_SalePlanIfUsed @planid,@idtype,@fullname
IF(@intReturnValue=-1)
	RETURN -1
--PRINT (@intReturnValue)
IF @idtype='timeid'
	BEGIN
		IF EXISTS(SELECT *FROM SaleTimeTotal WHERE ID!=@planid AND FullName=@fullname)
		BEGIN
		RAISERROR('该时段组名称【%s】已经使用，保存失败！',16,1,@fullname)RETURN -1
		END
		UPDATE	SaleTimeTotal
		SET		FullName=@fullname,
				Years=@year,
				Comment=@comment
		WHERE	ID=@planid
	END
IF @idtype='splanid'
	BEGIN
		IF EXISTS (SELECT * FROM StypeSaleAllPlan WHERE ID!=@planid AND FullName=@fullname)
		BEGIN
			RAISERROR('该分支机构销售计划名称【%s】已经使用，保存失败！',16,1,@fullname)RETURN -1
		END
		UPDATE	StypeSaleAllPlan
		SET		FullName=@fullname,
				AllPlanValue=@alltotalplan,
				AllRatingValue=@alltotalindex,
				Comment=@comment,
				MoneyUnit=@moneyunit,
				TotalID=@timeid
		WHERE	ID=@planid
	END
IF @idtype='dplanid'
	BEGIN
		IF EXISTS (SELECT * FROM DtypeSaleAllPlan WHERE ID!=@planid AND FullName=@fullname AND @ifstype='0')
		BEGIN
			RAISERROR('该部门销售计划名称【%s】已经使用，保存失败！',16,1,@fullname) RETURN -1
		END
		UPDATE	DtypeSaleAllPlan
		SET		FullName=@fullname,
				AllPlanValue=@alltotalplan,
				AllRatingValue=@alltotalindex,
				Comment=@comment,
				MoneyUnit=@moneyunit,
				TotalID=@timeid
		WHERE	ID=@planid
	END
IF @idtype='eplanid'
	BEGIN
		IF EXISTS (SELECT TOP 1 1  FROM ReferencePlanCommission WHERE SalePlanID = @planid)
		BEGIN
			RAISERROR('该职员销售计划【%s】被参照计划引用，不能修改！',16,1,@fullname)RETURN -1
		END
		UPDATE	EtypeSaleAllPlan
		SET		FullName=@fullname,
				AllPlanValue=@alltotalplan,
				AllRatingValue=@alltotalindex,
				Comment=@comment,
				MoneyUnit=@moneyunit
		WHERE	ID=@planid
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateSaleOrderState]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateSaleOrderState]
GO




--20090812
--李明洋
--20131123 周华 修改审核流程问题 参考9.1sp2
CREATE    PROCEDURE Gp_UpdateSaleOrderState	--在单据审核发生变化后修改销售单据的状态
(
	@AuditingID			int,		--审核流程编号
	@StateBefore		int,		--销售订单之间的状态
	@deleteBill			int			--是否需要清除待审核
)
--@encode$--
AS

SET NOCOUNT ON

DECLARE @IfHaveSale1 int -- 判断之后是否有审核
DECLARE @IfHaveBuy1 int
SET @IfHaveSale1 = 0
SET @IfHaveBuy1 = 0

		IF EXISTS(SELECT * FROM AuditingFlowSet where Billtype =300 AND AuditingType<>0 AND LEFT(AuditingReason,1)<>'1')
			SET @IfHaveSale1 = 1



CREATE TABLE #BillnumberID (BillnumberID INT)
CREATE TABLE #BillnumberID1 (BillnumberID INT)
CREATE TABLE #BillnumberID2 (BillnumberID INT)


		IF @StateBefore = 0
		BEGIN
			IF @IfHaveSale1 = 1 -- 订单审核从无到有
			BEGIN
				-- 被调用过的订单或订单状态为已完成
				INSERT INTO #BillnumberID 
					select  BillnumberID   FROM OrderBill where OrderID IN (SELECT orderid From SaleBill) 
				UNION			
					select  BillnumberID   FROM OrderIndex WHERE Billtype =300 AND orderState ='1'
	
				
				-- 没被调用的订单IfAudit置0，清除AuditingBill
				Update orderindex set ifAudit=0 WHERE OrderState ='0' AND billtype =300 AND BillnumberID NOT IN (SELECT BillnumberID FROM #BillnumberID) 
				AND Stypeid=(select TOP 1 stypeid FROM AuditingFlowSet WHERE AuditingID = @AuditingID AND Billtype =300)
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex WHERE OrderState='0' AND billtype=300 AND IfAudit=0) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID IN (SELECT BillnumberID FROM Orderindex WHERE OrderState ='0' AND billtype =300 AND ifAudit =0) AND AuditingID =@AuditingID
			END
		END
		ELSE
		BEGIN
			IF @IfHaveSale1 = 1 -- 订单审核从有到有 审核改变
			BEGIN
				-- 审核没通过或待审单据 
				INSERT INTO #BillnumberID SELECT BillnumberID FROM AuditingBill WHERE IfAudit ='0' AND AuditingID =@AuditingID 
				-- 被调用过的订单或订单状态为已完成
				INSERT INTO #BillnumberID1 
					select  BillnumberID   FROM OrderBill where OrderID IN (SELECT orderid From SaleBill) 
				UNION			
					select  BillnumberID   FROM OrderIndex WHERE Billtype =300 AND orderState ='1'
				-- 审核通过单据
				INSERT INTO #BillnumberID2 SELECT BillnumberID FROM AuditingBill WHERE IfAudit ='1' AND AuditingID =@AuditingID 
	
				--没有审核通过，待审核的订单IfAudit置0
				Update Orderindex SET IfAudit =0 WHERE orderState='0' AND Billtype=300 AND  BillnumberID  IN (SELECT BillnumberID FROM #BillnumberID)
				-- 不在审核通过，且不在被调用过的单据之中，IfAudit置0
				UPDATE Orderindex SET IfAudit =0 WHERE orderState='0' AND Billtype=300 AND 
				 (BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID1)) AND 
				 (BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID2)) AND Stypeid=(SELECT TOP 1 stypeid FROM AuditingFlowSet WHERE AuditingID = @AuditingID AND Billtype =300)

				--没有审核通过，待审核的订单,清除AuditingBill
				if @deleteBill = 1
				begin
					DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM #BillnumberID) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
					DELETE FROM AuditingBill WHERE BillnumberID  IN (SELECT BillnumberID FROM #BillnumberID) AND AuditingID =@AuditingID
					-- 不在审核通过，且不在被调用过的单据之中，清除AuditingBill
					-- DELETE FROM AuditingBill WHERE BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID1) AND AuditingID =@AuditingID AND BillnumberID  NOT IN (SELECT BillnumberID FROM #BillnumberID2)
				end
	
			END
			ELSE	-- 订单审核从有到无 
			BEGIN
				-- 所有订单的IfAudit 置 1，清除订单的 AuditingBill
				Update orderindex set ifAudit=1 WHERE  billtype =300
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN (SELECT BillNumberID FROM OrderIndex WHERE billtype=300) AND BillNumberID IN (SELECT BillNumberID FROM AuditingBill WHERE AuditingID=@AuditingID)
				DELETE FROM AuditingBill WHERE BillnumberID IN (SELECT BillnumberID FROM Orderindex WHERE billtype =300 ) AND AuditingID =@AuditingID
			END
		END


DROP TABLE #BillnumberID
DROP TABLE #BillnumberID1
DROP TABLE #BillnumberID2




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateSalePlanIfUsed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateSalePlanIfUsed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-09-20
--	描述：销售计划启用状态更改
---------------------------------------------
CREATE PROCEDURE GP_UpdateSalePlanIfUsed
( 
	@id			VARCHAR(MAX),
	@idtype		VARCHAR(MAX),
	@ifuse		VARCHAR(MAX),
	@fullname	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

IF @idtype='timeid'
	BEGIN
		IF EXISTS(SELECT *FROM StypeSaleAllPlan WHERE TotalID=@id) AND @ifuse='0'
			BEGIN
				RAISERROR('该销售计划【%s】已经被分支机构销售计划引用，不能停用！',16,1,@fullname)RETURN -1
			END
		IF EXISTS(SELECT *FROM DtypeSaleAllPlan WHERE TotalID=@id) AND @ifuse='0'
			BEGIN
				RAISERROR('该销售计划【%s】被部门销售计划中引用，不能停用！',16,1,@fullname)RETURN -1
			END
		UPDATE SaleTimeTotal SET IfUse=@ifuse WHERE ID=@id
		UPDATE StypeSaleAllPlan SET IfUse=@ifuse WHERE TotalID=@id
		UPDATE DtypeSaleAllPlan SET IfUse=@ifuse WHERE TotalID=@id
		UPDATE EtypeSaleAllPlan SET IfUse=@ifuse WHERE TotalID=@id
		RETURN 0
	END
DECLARE @DETIALID VARCHAR(MAX)

IF @idtype='splanid'
	BEGIN
		IF @ifuse='1' AND EXISTS (SELECT FullName FROM SaleTimeTotal WHERE IfUse='0' AND ID IN (SELECT TotalID FROM StypeSaleAllPlan WHERE ID=@id))
			BEGIN
				RAISERROR('该销售计划【%s】所引用的时段组已经被停用，启用失败！',16,1,@fullname)RETURN -1
			END
		
		
		IF @ifuse = '0' AND  EXISTS(	SELECT TOP 1 1 FROM ReferencePlanCommission R 
					INNER JOIN EtypeSaleAllPlan E ON E.ID = R.SalePlanID
					INNER JOIN DtypeSaleAllPlan D ON D.ID = E.DTypePlanID
					INNER JOIN StypeSaleAllPlan S ON S.ID = D.STypePlanID
					WHERE S.ID = @id
				)
		BEGIN
			RAISERROR('该销售计划【%s】间接被参照计划引用，停用失败！',16,1,@fullname)RETURN -1
		END
		
		UPDATE StypeSaleAllPlan 
		SET IfUse=@ifuse 
		WHERE ID=@id
		
		UPDATE DtypeSaleAllPlan 
		SET IfUse=@ifuse 
		WHERE STypePlanID IN (SELECT ID FROM StypeSaleplan WHERE SplanID=@id)
					
		UPDATE EtypeSaleAllPlan 
		SET IfUse=@ifuse 
		WHERE DTypePlanID IN (
								SELECT	ID 
								FROM	DtypeSaleplan 
								WHERE DplanID IN 
								(
									SELECT	ID 
									FROM DtypeSaleAllPlan 
									WHERE STypePlanID IN (SELECT ID FROM StypeSaleplan WHERE SplanID=@id)
								)
							 )
	    RETURN 0
	END

IF @idtype='dplanid'
	BEGIN
		IF @ifuse='1' AND EXISTS (SELECT FullName FROM SaleTimeTotal WHERE IfUse='0' AND ID IN (SELECT TotalID FROM DtypeSaleAllPlan WHERE ID=@id))
			BEGIN
				RAISERROR('该销售计划【%s】所引用的时段组已经被停用，启用失败！',16,1,@fullname)RETURN -1
			END
		IF @ifuse='1' AND EXISTS (	SELECT * FROM StypeSalePlan SP 
									INNER JOIN StypeSaleAllPlan SA ON SA.ID=SP.SplanID 
									WHERE SA.IfUse='0' AND SP.ID IN (SELECT STypePlanID FROM DtypeSaleAllPlan WHERE ID=@id))
			BEGIN
				RAISERROR('该销售计划【%s】所引用的分支机构计划已经被停用，启用失败！',16,1,@fullname)RETURN -1
			END
			
		IF @ifuse = '0' AND EXISTS(	SELECT TOP 1 1 FROM ReferencePlanCommission R 
					INNER JOIN EtypeSaleAllPlan E ON E.ID = R.SalePlanID
					INNER JOIN DtypeSaleAllPlan D ON D.ID = E.DTypePlanID
					WHERE D.ID = @id
				)
		BEGIN
			RAISERROR('该销售计划【%s】间接被参照计划引用，停用失败！',16,1,@fullname)RETURN -1
		END	
		
		UPDATE DtypeSaleAllPlan SET IfUse=@ifuse WHERE ID=@id
		UPDATE EtypeSaleAllPlan SET IfUse=@ifuse WHERE DTypePlanID IN ( SELECT ID FROM DtypeSaleplan WHERE DplanID=@id)
		RETURN 0
	END
IF @idtype='eplanid'
	BEGIN
		IF @ifuse='1' AND EXISTS (SELECT FullName FROM SaleTimeTotal WHERE IfUse='0' AND ID IN (SELECT TotalID FROM EtypeSaleAllPlan WHERE ID=@id))
			BEGIN
				RAISERROR('该销售计划【%s】所引用的时段组已经被停用，启用失败！',16,1,@fullname)RETURN -1
			END
		IF @ifuse='1' AND EXISTS (	SELECT *FROM DtypeSalePlan DP 
									INNER JOIN DtypeSaleAllPlan DA ON DA.ID=DP.DplanID 
									WHERE DA.IfUse='0' AND DP.ID IN (SELECT DTypePlanID FROM EtypeSaleAllPlan WHERE ID=@id))
			BEGIN
				RAISERROR('该销售计划【%s】所引用的部门计划已经被停用，启用失败！',16,1,@fullname)RETURN -1
			END
		
		IF @ifuse = '0' AND EXISTS(SELECT TOP 1 1 FROM ReferencePlanCommission WHERE SalePlanID = @id)
		BEGIN
			RAISERROR('该销售计划【%s】被参照计划引用，停用失败！',16,1,@fullname)RETURN -1
		END
			
		UPDATE EtypeSaleAllPlan SET IfUse=@ifuse WHERE ID=@id
		RETURN 0
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_UpdateSAtype]    Script Date: 06/06/2012 09:56:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateSAtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateSAtype]
GO

--作    者：胡小科 
--日    期：2012-05-29  
--作    用：更新机构基本信息 




CREATE     PROCEDURE [dbo].[Gp_UpdateSAtype]
(
	@billtypeid			[varchar](50),
	@atypeid			[varchar](50),
	@stypeid			[varchar](50)
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN TRY
 
	IF EXISTS(SELECT [BillTypeId] FROM [BillAtype] WHERE [BillTypeId]=@billtypeid AND [StypeId]=@stypeid)
		BEGIN
			UPDATE [BillAtype] SET [AtypeId]=@atypeid WHERE [BillTypeId]=@billtypeid AND [StypeId]=@stypeid
		END
	ELSE
		BEGIN
			INSERT INTO [BillAtype]([BillTypeId] ,[AtypeId] ,[StypeId])VALUES (@billtypeid,@atypeid,@stypeid)
			UPDATE BillIndex
			SET ATypeID1=@atypeid
			WHERE Stypeid=@stypeid AND BillType=@billtypeid AND (ATypeID1 IS NULL OR ATypeID1 ='')
		END
	RETURN 1
END TRY
BEGIN CATCH

	RETURN 0

END CATCH


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_UpdateSmsTemplateContent]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Gp_UpdateSmsTemplateContent]
GO

/*
	作者：谢吉康
	日期：2018-11-06
	描述：写入模版内容
*/
CREATE PROCEDURE Gp_UpdateSmsTemplateContent
(
	@smstemplatecode	VARCHAR(500),			--编号 
	@smstemplatename	VARCHAR(500),			--名称
	@smstemplatecontent	VARCHAR(MAX),			--内容	
	@smsbeizhu			VARCHAR(MAX),			--备注
	@templatetype		VARCHAR(10),			--模版类型
	@smsbilltype		VARCHAR(10),			--单价类型
	@id					VARCHAR(100),			--模版ID
	@retcontent			VARCHAR(MAX) OUTPUT,	--返回数据
	@rettemplateid		VARCHAR(100) OUTPUT		--返回ID
)
AS
SET NOCOUNT ON

--翻译模版
DECLARE @returncontent VARCHAR(MAX)

EXEC Web_ConvertBillTypeOldSmsContentToHyyun @smsbilltype,@smstemplatecontent,@returncontent OUTPUT

--修改数据
UPDATE	SMSTemplate 
SET 	smstemplatecode=@smstemplatecode,
		smstemplatename=@smstemplatename,
		smstemplatecontent=@smstemplatecontent,
		smsbeizhu=@smsbeizhu,
		templatetype=@templatetype,
		smsbilltype=@smsbilltype,
		HyyunSmsTemplateContent = @returncontent
WHERE	id=@id 
             
UPDATE  SMSBillType 
SET		smstemplatecode=@smstemplatecode,
		smstemplatename=@smstemplatename,
		smstemplatecontent=@smstemplatecontent,
		smsbeizhu=@smsbeizhu,
		HyyunSmsTemplateContent = @returncontent
WHERE   templateid=@id 

--返回串
SET @retcontent = @returncontent
SELECT @rettemplateid = hyyunsmstemplateid FROM SMSTemplate WHERE id=@id 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS(SELECT 1 FROM dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateStyleAdminUsingSet]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_UpdateStyleAdminUsingSet
GO
--===================================================
--CreatedBy:glj
--Date:2012-11-16
--年终启用总账 分支机构核算设置
--===================================================
CREATE   PROCEDURE Gp_UpdateStyleAdminUsingSet
(
	@IsSelfVerify	INT,
	@VerifyID		VARCHAR(50),
	@calcFullName	VARCHAR(200),
	@TypeId			VARCHAR(500)
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN TRAN
DECLARE	@RET INT=0
	IF @IsSelfVerify=1
		BEGIN
			SET @VerifyID=@TypeId
		END
	UPDATE stype SET 
					IsSelfVerify=@IsSelfVerify,
					VerifyID=@VerifyID,
					calcFullName=@calcFullName 
	WHERE TypeId=@TypeId
	SET @RET+=@@ERROR
	IF(@IsSelfVerify=0)
		BEGIN
			DELETE dbo.BillAtype WHERE StypeId=@TypeId
			SET @RET+=@@ERROR
		END
IF @RET<>0
	ROLLBACK TRAN 
ELSE 
	COMMIT TRAN
RETURN @RET
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateStypePriceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateStypePriceInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-
	描述：
*/
/*
修改：增加商品单位查询条件
日期：2016-04-29
修改人:魏伟
*/
CREATE PROCEDURE Gp_UpdateStypePriceInfo
(
	@STypeId		VARCHAR(50),	--分支机构
	@PTypeId		VARCHAR(50),	--商品ID
	@PreBuyPrice1	numeric(24,10), 
	@PreBuyPrice2	numeric(24,10), 
	@PreBuyPrice3	numeric(24,10), 
	@PreBuyPrice4	numeric(24,10), 
	@PreBuyPrice5	numeric(24,10), 
	@PreSalePrice1	numeric(24,10), 
	@PreSalePrice2	numeric(24,10), 
	@PreSalePrice3	numeric(24,10), 
	@PreSalePrice4	numeric(24,10), 
	@PreSalePrice5	numeric(24,10), 
	@PreSalePrice6	numeric(24,10), 
	@PreSalePrice7	numeric(24,10), 
	@PreSalePrice8	numeric(24,10), 
	@PreSalePrice9	numeric(24,10), 
	@PreSalePrice10	numeric(24,10), 
	@RetailPrice	numeric(24,10), 
	@TopSalePrice	numeric(24,10), 
	@LowSalePrice	numeric(24,10),
	@recPrice		numeric(24,10),
	@TopBuyPrice	numeric(24,10),
	@referprice		numeric(24,10),
	@unittypeid     VARCHAR(50),
	@unittypename   VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @ifdefaultunit bit,
		@ErrorCNT		   INT=0
		
select @ifdefaultunit=ext.IsDefaultUnit
	from ptype_units_ext ext 
	inner join PType_Units u on ext.unitsid=u.unitsid
	where ext.ptypeid=@PTypeId and ext.UnitsId=@unittypeid
--------------有就更新 没有新增 
IF EXISTS(SELECT TOP 1 1 FROM PType_STypePrice WHERE PTypeID = @PTypeId AND STypeID = @STypeId AND UnitID=@unittypeid)
	BEGIN
		UPDATE	PType_STypePrice
		SET		PreBuyPrice1 = @PreBuyPrice1,
				PreBuyPrice2 = @PreBuyPrice2,
				PreBuyPrice3 = @PreBuyPrice3,
				PreBuyPrice4 = @PreBuyPrice4,
				PreBuyPrice5 = @PreBuyPrice5,
				PreSalePrice1 = @PreSalePrice1,
				PreSalePrice2 = @PreSalePrice2,
				PreSalePrice3 = @PreSalePrice3,
				PreSalePrice4 = @PreSalePrice4,
				PreSalePrice5 = @PreSalePrice5,
				PreSalePrice6 = @PreSalePrice6,
				PreSalePrice7 = @PreSalePrice7,
				PreSalePrice8 = @PreSalePrice8,
				PreSalePrice9 = @PreSalePrice9,
				PreSalePrice10 = @PreSalePrice10,
				RetailPrice =  @RetailPrice,
				TopSalePrice = @TopSalePrice,
				LowSalePrice = @LowSalePrice,
				RecPrice	 = @recPrice,
				TopBuyPrice	 = @TopBuyPrice,
				referprice = case when @ifdefaultunit=0 then 0 else @referprice end
		WHERE	PTypeID = @PTypeId 
				AND STypeID = @STypeId 
				AND UnitID=@unittypeid
		SET @ErrorCNT+= @@ERROR 
	END
ELSE
	BEGIN
		INSERT INTO PType_STypePrice
		(
			STypeID,
			PTypeID,
			PreBuyPrice1, 
			PreBuyPrice2, 
			PreBuyPrice3, 
			PreBuyPrice4, 
			PreBuyPrice5, 
			PreSalePrice1, 
			PreSalePrice2, 
			PreSalePrice3, 
			PreSalePrice4, 
			PreSalePrice5, 
			PreSalePrice6, 
			PreSalePrice7, 
			PreSalePrice8, 
			PreSalePrice9, 
			PreSalePrice10, 
			RetailPrice, 
			TopSalePrice, 
			LowSalePrice,
			RecPrice,
			TopBuyPrice,
			referprice,
			unitid,
			IsDefaultUnit
		)VALUES(
			@STypeID,
			@PTypeID,
			@PreBuyPrice1, 
			@PreBuyPrice2, 
			@PreBuyPrice3, 
			@PreBuyPrice4, 
			@PreBuyPrice5, 
			@PreSalePrice1, 
			@PreSalePrice2, 
			@PreSalePrice3, 
			@PreSalePrice4, 
			@PreSalePrice5, 
			@PreSalePrice6, 
			@PreSalePrice7, 
			@PreSalePrice8, 
			@PreSalePrice9, 
			@PreSalePrice10, 
			@RetailPrice, 
			@TopSalePrice, 
			@LowSalePrice,
			@recPrice,
			@TopBuyPrice,
			case when @ifdefaultunit=0 then 0 else @referprice end,
			@unittypeid,
			@ifdefaultunit
		)
		
		SET @ErrorCNT+= @@ERROR
	END	

--修改商品档案的缓存最大值
DECLARE @XiWaMaxNumber INT

SELECT @XiWaMaxNumber=MAX(XiWaMaxNumber)+1 FROM PType

UPDATE PType SET XiWaMaxNumber=@XiWaMaxNumber WHERE typeId=@ptypeid

DELETE  FROM  PType_STypePrice 
WHERE PTYPEID=@PTypeID
AND STYPEID=@STypeID
AND IsDefaultUnit=0
AND ISNULL(PreBuyPrice1,0)=0 
AND	ISNULL(PreBuyPrice2,0)=0
AND ISNULL(PreBuyPrice3,0)=0
AND	ISNULL(PreBuyPrice4,0)=0 
AND	ISNULL(PreBuyPrice5,0)=0
AND	ISNULL(PreSalePrice1,0)=0
AND	ISNULL(PreSalePrice2,0)=0 
AND	ISNULL(PreSalePrice3,0)=0 
AND	ISNULL(PreSalePrice4,0)=0 
AND	ISNULL(PreSalePrice5,0)=0 
AND	ISNULL(PreSalePrice6,0)=0 
AND	ISNULL(PreSalePrice7,0)=0 
AND	ISNULL(PreSalePrice8,0)=0 
AND	ISNULL(PreSalePrice9,0)=0 
AND	ISNULL(PreSalePrice10, 0)=0
AND	ISNULL(RetailPrice,0)=0 
AND	ISNULL(TopSalePrice,0)=0 
AND	ISNULL(LowSalePrice,0)=0
AND	ISNULL(RecPrice,0)=0
AND	ISNULL(TopBuyPrice,0)=0
AND	ISNULL(referprice,0)=0
AND ISNULL(RECSALEPRICE,0)=0
AND ISNULL(RECAPPRAISALPRICE,0)=0
AND ISNULL(RECSENDPRICE,0)=0

RETURN @ErrorCNT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateSysdataFyearAndMonth]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROC [dbo].Gp_UpdateSysdataFyearAndMonth
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO 
-- ========================================================================
-- 描述：	会计期间保存修改sysdata fyear fmonth 
--			确保会计期间设置页面的启用时间跟账套管理的启用时间相同。防止用户在保存会计期间设置界面后没有保存帐套页面
-- 时间：	2012-04-21
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Gp_UpdateSysdataFyearAndMonth
(
  @Fyear            VARCHAR(10),  --启用年度
  @Fmonth           VARCHAR(10),  --启用月度
  @TypeID			INT				--进口
)

--@encode$--
AS
SET NOCOUNT ON 
DECLARE @year INT=0,@month INT=0,@Ret INT=0

SELECT @year=SubValue FROM sysdata WHERE SubName='fyear'
SELECT @month=SubValue FROM sysdata WHERE SubName='fmonth'

IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='fyear')
	BEGIN
		UPDATE sysdata SET SubValue=@Fyear WHERE SubName='fyear' 
		SET @Ret+=@@ERROR
	END
ELSE 
	BEGIN
		DECLARE @id INT
		SELECT @id = max(subno) + 1 from sysdata;		
		INSERT sysdata(subno, SubValue,SubName) VALUES(@id, @Fyear,'fyear')--fyear
		SET @Ret+=@@ERROR
	END
	
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='fmonth')
	BEGIN
		UPDATE sysdata SET SubValue=@Fmonth WHERE SubName='fmonth'
		SET @Ret+=@@ERROR
	END
ELSE 
	BEGIN
			SELECT @id = max(subno) + 1 from sysdata;	
			INSERT sysdata(subno, SubValue,SubName) VALUES(@id, @Fmonth,'fmonth')--fmonth
		SET @Ret+=@@ERROR
	END
UPDATE sysdata SET SubValue=@Fmonth WHERE SubName IN('FPeriod','fmonth')--修改sysdata表
		SET @Ret+=@@ERROR
--ELSE IF(@TypeID=0)
--	BEGIN
--SELECT @Fyear,@Fmonth,@year,@month;RETURN;
		UPDATE Ac_IniAccount SET FYear=@Fyear, FPeriod=@Fmonth WHERE FYear=@year AND FPeriod=@month
		SET @Ret+=@@ERROR
		UPDATE Ac_IniAccount_Assist_CheckItems SET FYear=@Fyear, FPeriod=@Fmonth WHERE FYear=@year AND FPeriod=@month
		SET @Ret+=@@ERROR
		UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FYear=@Fyear, FPeriod=@Fmonth WHERE FYear=@year AND FPeriod=@month
		SET @Ret+=@@ERROR
--  END

--Awu:期间数小于12，只能使用固定资产项目管理
IF (SELECT COUNT(*) FROM dbo.Ac_Period T1 WHERE FYear = (SELECT SubValue FROM dbo.sysdata WHERE SubName='fyear')) < 12
	UPDATE dbo.sysdata SET SubValue = 0 WHERE SubName = 'assets'
 	
IF(@Ret<>0)
	RETURN 1
RETURN 0
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateSysdataWsd]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_UpdateSysdataWsd]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2015-5-26
	描述：批量修改预制数据	
	EXEC Gp_UpdateSysdataWsd '120.26.200.120'
*/

CREATE PROCEDURE Gp_UpdateSysdataWsd
(
	@newId			VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @dbI		INT,
		@dbCount	INT,		
		@dbBase		VARCHAR(MAX),
		@dbSql		VARCHAR(MAX)
		
CREATE TABLE #DataBase
(
	nid		INT IDENTITY(1,1),
	dbName	VARCHAR(MAX)
)				
INSERT INTO #DataBase(dbName ) SELECT name FROM [master].dbo.sysdatabases WHERE name NOT IN ('master','tempdb','model','msdb')

SET @dbCount = @@ROWCOUNT

SET @dbI = 1

WHILE @dbI <= @dbCount
BEGIN
	SELECT @dbBase = dbName FROM #DataBase WHERE nid = @dbI
	
	BEGIN TRY	
		--刷新新的数据
		SET @dbSql = 'IF NOT EXISTS(SELECT TOP 1 1 FROM '+@dbBase+'.dbo.sysdata WHERE LEFT(Subvalue,3) IN (''9.0'') OR LEFT(Subvalue,4) IN (''8.22''))
						BEGIN
							UPDATE '+@dbBase+'.dbo.sysdata SET SubValue = '''+@newId+''' WHERE SubName = ''wsd''
							EXEC '+@dbBase+'.dbo.Gp_Fz_Base '''+@newId+''',''1''							
						END'
		
		--PRINT(@dbSql)
		EXEC(@dbSql)	
		
		--修改IM消息备份周期
		SET @dbSql = '  IF EXISTS(SELECT TOP 1 1 FROM '+@dbBase+'.dbo.sysdata WHERE SubName = ''moveimmesagedays'' AND SubValue = ''0'')
						BEGIN
							UPDATE '+@dbBase+'.dbo.sysdata SET SubValue = ''1'' WHERE SubName = ''moveimmesagedays''
						END'
						
		--PRINT(@dbSql)
		EXEC(@dbSql)		
	END TRY
	BEGIN CATCH
		
	END CATCH
	
	SET @dbI = @dbI + 1
END

DROP TABLE #DataBase

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateTCBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateTCBillIndex]
GO


--**********************************************
--销售提成公式设置
--**********************************************
CREATE                                PROCEDURE [Gp_UpdateTCBillIndex]
(
	@BillNumberId  		[numeric](10,0),
	@BillDate  			[datetime],
	@StarDate			[datetime],
	@EndDate			[datetime],
	@BillCode  			[varchar](200),
	@EtypeId  			[varchar](50),--审核人
	@checke  			[varchar](50), --制单人
	@Comment  			[varchar](256)
)
--@encode$--
AS 
SET NOCOUNT ON 

DECLARE @szPeriod [SMALLINT]
DECLARE @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
EXEC Gp_GetSubValue 'period','',@szPeriod out
SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
IF @BillDate<@BeginDate 
BEGIN 
	RETURN -2
END

---根据配置检查过帐日期是否当前日期
DECLARE @CurDate datetime
DECLARE @IsOrNotPassOneDay bit
SELECT @CurDate=GETDATE()
SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
BEGIN 
	--RAISERROR('录单日期必须与当前日期一致 ！',16,1) 
	RETURN -4
END
--判断是否已经有审核人
DECLARE @existEtypeId varchar(50)
SELECT @existEtypeId=EtypeId FROM TcBillIndex WHERE billNumberId=@BillNumberId
IF @existEtypeId<>''
BEGIN
	RETURN -3
END


UPDATE [dbo].[TCBillIndex] 
SET	[BillDate] 	= @BillDate,
	[BillCode]	= @BillCode,
	[Comment]	= @Comment,
	[StartDate] 	= @StarDate,
	[EndDate] 	= @EndDate,
	[checke]	=@checke,
	[EtypeID]	=@EtypeId,
	[unChecke]    = '',
	[unCheckTime] = ''
	
WHERE 	[BillNumberId]  = @BillNumberId
--PRINT @@rowCount
IF @@rowcount =0  OR @@error<>0
--RAISERROR('更新数据表发生错误！',16,1)
	RETURN -5

-- 删除单据明细
DECLARE @strSQL		varchar(500),
	@strDBName	varchar(100)
	
	
	
SET @strDBName = 'TCBill'
SET @strSQL = '
	DELETE FROM ' + @strDBName + '
	WHERE BillNumberID = ' + CONVERT(varchar(15),@BillNumberID)
EXEC(@strSQL)
IF @@ERROR <> 0
BEGIN
	--RAISERROR('删除单据发生错误',16,1)
	RETURN -6
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateTe_BankAccount_Closed]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Gp_UpdateTe_BankAccount_Closed
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Te_BankAccount 出纳管理-银行账户销户
-- 时间：	2014-05-13
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_UpdateTe_BankAccount_Closed
(
	@Id				INT,				--银行账户ID
	@DestroyDate	DATETIME,			--销户时间
	@DestroyReson	VARCHAR(1000)		--销户原因
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 1 FROM Te_BankAccount WHERE Id=@Id)
BEGIN
	RAISERROR('该信息已删除或不存在,请确定！',16,1) RETURN
END

DECLARE @RET INT=0
SELECT @RET=dbo.F_GetIsUse_Te(@Id,3)
IF @RET=1
	BEGIN
		RAISERROR('此账户在出纳系统/总账系统还存有余额，请将此账户余额转至其它账户后，再进行销户操作！',16,1)RETURN
	END
ELSE IF @RET=2
	BEGIN
		RAISERROR('此账户还存在资金调拨单未生成凭证，请先处理后再进行销户操作！',16,1)RETURN
	END
ELSE IF @RET=3
	BEGIN
		RAISERROR('此账户还存在凭证未生成日记账，请先处理后再进行销户操作！',16,1)RETURN
	END
	
UPDATE Te_BankAccount SET IsDestroy=1,DestroyDate=@DestroyDate,DestroyReson=@DestroyReson WHERE Id=@Id

IF(@@ERROR<>0)
BEGIN
	RAISERROR('销户出现异常,请稍后再试！',16,1)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateTemplateListTable]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateTemplateListTable]
GO




CREATE  PROCEDURE [Gp_UpdateTemplateListTable]
(
 @TemplateID  [int],
 @Ptypeid  [varchar](100),
 @Qty    NUMERIC(24, 10) ,
 @comment  [varchar](50)
)
--@encode$--
AS 
SET NOCOUNT ON 
UPDATE [TemplateListTable] 
SET  [Ptypeid]  = @Ptypeid,
  [Qty]  = dbo.F_RoundQty(@Qty),
  [comment]  = @comment 
WHERE 
 ( [templateID]  = @templateID AND
  [Ptypeid]  = @Ptypeid)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateTemplateTable]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateTemplateTable]
GO















/****** Object:  Stored Procedure dbo.Gp_UpdateTemplateTable    Script Date: 2002-6-20 10:14:52 ******/

CREATE   PROCEDURE [Gp_UpdateTemplateTable]
(
 @Templateid  [int],
 @TemplateName  [varchar](20),
 @PtypeId  [varchar](50),
 @Comment  [varchar](50)
)
--@encode$--
AS 
SET NOCOUNT ON 
UPDATE [TemplateTable] 
SET  [TemplateName]  = @TemplateName,
  [ptypeid]  = @ptypeid,
  [comment]  = @comment 
WHERE 
 ( [Templateid]  = @Templateid)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateTeStartPeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateTeStartPeriod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.04.24
	描述：更新出纳管理 启用期间信息
*/
CREATE PROCEDURE Gp_UpdateTeStartPeriod
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@starttable TbType_TeStartPeriod	READONLY	-- 出纳启用期间数据
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #SType
(
	stypeid		VARCHAR(50),
	fullname	VARCHAR(200)
)

DECLARE @before INT
SET @before = 0

--启用期间前
INSERT INTO #SType
        ( stypeid, fullname )
SELECT DISTINCT *
FROM
(
SELECT T2.stypeid,T4.fullname
FROM dbo.Te_Journal_Detail T1 
	INNER JOIN @starttable T2 ON T1.STypeId = T2.stypeid
	INNER JOIN dbo.Ac_Period T3 ON T2.sfyear = T3.FYear AND T2.sfperiod = T3.FPeriod AND T1.BusinessDate < T3.FBegin
	INNER JOIN dbo.SType T4 ON T2.stypeid = T4.typeid
	INNER JOIN dbo.Te_StartPeriod T5 ON T2.stypeid = T5.STypeId AND T5.IsUse = 0
UNION ALL
SELECT T3.stypeid,T5.FullName 
FROM dbo.Te_BankStatementDetail T1 
	INNER JOIN dbo.Te_BankAccount T2 ON T1.AccountId = T2.Id
	INNER JOIN @starttable T3 ON T2.STypeId = T3.stypeid
	INNER JOIN dbo.Ac_Period T4 ON T3.sfyear = T4.FYear AND T3.sfperiod = T4.FPeriod AND T1.BusinessDate < T4.FBegin
	INNER JOIN dbo.SType T5 ON T3.stypeid = T5.TypeId
	INNER JOIN dbo.Te_StartPeriod T6 ON T3.stypeid = T6.STypeId AND T6.IsUse = 0
UNION ALL	
SELECT T2.stypeid,T4.FullName 
FROM dbo.BillIndex T1 
	INNER JOIN @starttable T2 ON T1.STypeId = T2.stypeid
	INNER JOIN dbo.Ac_Period T3 ON T2.sfyear = T3.FYear AND T2.sfperiod = T3.FPeriod AND T1.BillDate < T3.FBegin
	INNER JOIN dbo.SType T4 ON T2.stypeid = T4.TypeId
	INNER JOIN dbo.Te_StartPeriod T5 ON T2.stypeid = T5.STypeId AND T5.IsUse = 0
WHERE T1.BillType = 310
)T

IF EXISTS(SELECT TOP 1 1 FROM #SType)
	SET @before = 1
ELSE
BEGIN
	--启用期间之后
	INSERT INTO #SType
			( stypeid, fullname )
	SELECT DISTINCT T4.stypeid,T6.FullName
	FROM dbo.Te_AccountInTransit_Index T1
		INNER JOIN dbo.Te_AccountInTransit_Detail T2 ON T1.Id = T2.IndexId
		INNER JOIN dbo.Te_BankAccount T3 ON T1.AccountId = T3.Id
		INNER JOIN @starttable T4 ON T3.STypeId = T4.stypeid
		INNER JOIN dbo.Ac_Period T5 ON T4.SFYear = T5.FYear AND T4.SFPeriod = T5.FPeriod
		INNER JOIN dbo.SType T6 ON T4.stypeid = T6.TypeId
		INNER JOIN dbo.Te_StartPeriod T7 ON T4.stypeid = T7.STypeId AND T7.IsUse = 0
	WHERE T2.CreateDate >= T5.FBegin

	IF EXISTS(SELECT TOP 1 1 FROM #SType)
		SET @before = 2
END

--生成分支机构名字集合
DECLARE @msg VARCHAR(MAX)
SET @msg = ''

DECLARE @sfullname VARCHAR(200),@stypename VARCHAR(MAX)
SET @stypename = ''

DECLARE Stype_Cur CURSOR READ_ONLY FOR
	SELECT fullname
	FROM #SType
OPEN Stype_Cur

FETCH NEXT FROM Stype_Cur INTO @sfullname

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @stypename += @sfullname + '、'
	FETCH NEXT FROM Stype_Cur INTO @sfullname
END

CLOSE Stype_Cur
DEALLOCATE Stype_Cur

IF LEN(@stypename) > 1
BEGIN
	SET @stypename = SUBSTRING(@stypename,0,LEN(@stypename))
END

--启用期间前不能有出纳相关数据
IF @before = 1
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		SET @msg = '分支机构['+@stypename+']'
	SET @msg += '启用期间前存在出纳数据，无法设置启用期间，请确认！'
	RAISERROR(@msg,16,1)
	RETURN
END


--启用期间之后不能存在未达账数据
IF @before = 2
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		SET @msg = '分支机构['+@stypename+']'
	SET @msg += '启用期间后存在未达账数据，无法设置启用期间，请确认！'
	RAISERROR(@msg,16,1)
	RETURN
END

SET @stypename=''
--已启用不能修改启用期间
IF EXISTS(	SELECT TOP 1 1 FROM Te_StartPeriod T1 
			INNER JOIN @starttable T2 ON T1.STypeId = T2.stypeid
			WHERE T1.IsUse='1' AND (T1.SFYear<>T2.SFYear OR T1.SFPeriod<>T2.SFPeriod ))
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
	BEGIN
		INSERT INTO #SType (stypeid,fullname)
		SELECT TypeId,FullName  FROM SType WHERE TypeId IN (SELECT T1.STypeId FROM Te_StartPeriod T1 INNER JOIN @starttable T2 ON T1.STypeId = T2.stypeid WHERE T1.IsUse='1' AND (T1.SFYear<>T2.SFYear OR T1.SFPeriod<>T2.SFPeriod ))
		SELECT  @stypename+='['+fullname+']' FROM #SType
		SET @msg='分支机构'+@stypename
	END
		
	SET @msg += '已结束初始化，无法设置启用期间，请确认！'
	RAISERROR(@msg,16,1)
	RETURN
END




UPDATE dbo.Te_StartPeriod 
	SET SFYear = T2.sfyear,
	SFPeriod = T2.sfperiod,
	IsConnect = T2.isconnect,
	CFYear = T2.cfyear,
	CFPeriod = T2.cfperiod
FROM dbo.Te_StartPeriod T1 
	INNER JOIN @starttable T2 ON T1.STypeId = T2.stypeid

DROP TABLE #SType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateToolndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateToolndex
GO

/*
	作者：韩林		
	日期：2011-4-26
	描述：保存工具出入库台帐
*/

CREATE       PROCEDURE Gp_UpdateToolndex
(
  @BillNumberID [varchar](20),
  @BillDate  [datetime],
  @BillCode  [varchar](200), 
  @BillType  [numeric](4,0),
  @Comment   [varchar](256),
  @EtypeId   [varchar](50),
  @DtypeId   [varchar](50),
  @StypeId   [varchar](50),
  @Checke	 [varchar](50),
  @Explain   [varchar](256),
  @InOutType [varchar](50),
  @szPeriod [smallint]
)
--@encode$--
AS 
SET NOCOUNT ON
--根据配置检查录单日期是否小于本期日期
DECLARE @Re int, @Flag int
declare @BeginDate datetime,@szItem varchar(30),@szVchCode varchar(30)
EXEC Gp_GetSubValue 'period',@STypeID,@szPeriod out
select @BeginDate=startdate from monthproc where period=@szPeriod
if @BillDate<@BeginDate 
	RAISERROR('录单日期小于本期开始日期 ！',16,1) 
---根据配置检查录单日期是否当前日期
DECLARE @CurDate datetime
DECLARE @IsOrNotPassOneDay bit
SELECT @CurDate=GETDATE()
SELECT TOP 1 @IsOrNotPassOneDay=value FROM UserConfig WHERE ConfigName='PassOneDay'
IF (CONVERT(datetime,@BillDate)<>CONVERT(datetime,CONVERT(varchar,YEAR(@CurDate))+'-'+CONVERT(varchar,MONTH(@CurDate))+'-'+CONVERT(varchar,DAY(@CurDate)))) AND (@IsOrNotPassOneDay=1)
	RAISERROR('录单日期必须与当前日期一致 ！',16,1) 

IF @BillNumberID ='' 
BEGIN
	INSERT INTO ToolIndex
	(
		BillDate,
	    BillCode,
	    BillType,
	    Comment,
	    ETypeID,
	    DTypeID ,
	    Stypeid,
	    Checke,
	    Explain, 
		InOutType
	) 
	VALUES 
	(
		@BillDate,
	    @BillCode,
	    @BillType,
	    @Comment,
	    @EtypeId,
	    @DtypeId,
	    @StypeId,
	    @Checke,
	    @Explain,
	    @InOutType
	)
	IF @@rowcount =0  or @@error<>0
		RAISERROR('保存单据发生错误！',16,1)
	RETURN SCOPE_IDENTITY();
END 
ELSE
BEGIN
	UPDATE	ToolIndex 
	SET		BillDate	= @BillDate,
			BillCode	= @BillCode,
			BillType	= @BillType,
			Comment		= @Comment,
			ETypeID		= @Etypeid,
			Dtypeid		= @Dtypeid,
			Stypeid		= @Stypeid,
			Checke		= @Checke,
			Explain		= @Explain,
			InOutType	= @InOutType
	WHERE	BillNumberId= @BillNumberId
	IF @@rowcount =0  or @@error<>0
		RAISERROR('更新单据发生错误！',16,1)
	RETURN @BillNumberId
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateUFOOpenFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateUFOOpenFile
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--==================================================
--createby:glj	
--date:2013-06-17
--functiondescription:UFO_OpenFile新增数据
--=================================================
CREATE PROCEDURE Gp_UpdateUFOOpenFile
(
	@StypeID		VARCHAR(max),			--分支机构ID
	@FunctionName	VARCHAR(20),			--公式名称
	@UserCode		VARCHAR(200),			--项目/科目编号
	@BeginDate		VARCHAR(50),			--开始时间
	@EndDate		VARCHAR(50),			--结束时间
	@Fyear			INT,					--年份
	@FPeriod		INT,					--期间
	@ShowNotPost	INT,					--包含未记账凭证
	@CreatedBy		VARCHAR(50),			--创建人
	@Type			INT						--类型, 1：总账 2业务
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE 
	@AtypeID VARCHAR(50)='',
	@Assets INT =0
IF(@Type=1)
	BEGIN
		SELECT @AtypeID=TypeId FROM Ac_Account WHERE UserCode=@UserCode AND StypeId=@StypeID
		INSERT INTO UFO_OpenFile(StypeID,AtypeID,Fyear,FPeriod,ShowNotPost,CreatedBy,[TYPE],FunctionName)
VALUES(@StypeID,@AtypeID,@Fyear,@FPeriod,@ShowNotPost,@CreatedBy,1,@FunctionName)
	END
ELSE IF @Type=2
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='assets' AND SubValue=1)
			SET @Assets=1
		SELECT TOP 1 @AtypeID=nTypeId FROM Ac_Items WHERE UserCode=@UserCode
		INSERT INTO UFO_OpenFile
		(
			StypeID,
			AtypeID,
			BeginDate,
			EndDate,
			CreatedBy,
			[TYPE],
			FunctionName,
			Assets
		)
		VALUES
		(
			@StypeID,
			@AtypeID,
			CAST(@BeginDate AS DATETIME),
			CAST(@EndDate AS DATETIME),
			@CreatedBy,
			2,
			@FunctionName,
			@Assets
		)
	END
RETURN 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateUnitAndTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateUnitAndTotal
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：毛欣蓉
	日期：2012-04-26
	描述：处理多单位、货币等的升级
*/
CREATE PROCEDURE Gp_UpdateUnitAndTotal
--@encode$--
AS
SET NOCOUNT ON

---------------本位币升级---------------------

--INSERT INTO Ac_Currency(UserCode,FullName,Rate,BasisType,Deleted,Sysrow) VALUES('RMB','人民币',1,0,0,1)
DECLARE @SYSCID INT,--本位币
		@costing INT--成本算法

SELECT @SYSCID=CID FROM Ac_Currency WHERE Sysrow=1
SELECT @costing=SubValue FROM sysdata WHERE SubName='costing'

DECLARE @XIWANUM	INT = 1

--------------仓库默认货位升级-----------------
INSERT INTO CargoType(UserCode,FullName,KtypeID,Comment,deleted,IsDefault,XiWaMaxNumber) 
SELECT FullName+'默认货位', FullName+'默认货位',typeId, FullName+'默认货位',0,1,XiWaMaxNumber=(SELECT MAX(XiWaMaxNumber)+1 FROM CargoType)
FROM STOCK S

UPDATE CargoType SET XiWaMaxNumber = @XIWANUM,@XIWANUM=@XIWANUM+1
---------------多单位升级-------------------------
INSERT INTO PType_Units(UserCode,FullName,Comment) 
	SELECT DISTINCT Unit1,Unit1,'' 
	FROM ptype
	WHERE Not EXISTS(SELECT UserCode FROM PType_Units WHERE UserCode=Unit1)
		AND ISNULL(Unit1,'')<>''
INSERT INTO PType_Units(UserCode,FullName,Comment) 
	SELECT DISTINCT Unit2,Unit2,''
	FROM ptype
	WHERE Not EXISTS(SELECT UserCode FROM PType_Units WHERE UserCode=Unit2)
		AND ISNULL(Unit2,'')<>''
		
UPDATE ptype 
SET Unit1='PCS' 
WHERE ISNULL(Unit1,'')='' 

DECLARE @UnitsType INT = 0

--将商品现有的小单位写入单位关系表
INSERT INTO PType_Units_Ext(PtypeID,UnitsId,RateType,Rate,IsDefaultUnit)
	SELECT P.typeId,u.UnitsId,0,1,1  
	FROM PTYPE P,PType_Units u 
	WHERE  U.FullName=P.Unit1 
--将默认基本单位id写入商品
UPDATE ptype 
SET UnitsType=1,baseUnitId=E.UnitsId 
FROM PType_Units_Ext E 
WHERE  E.PTYPEID=TYPEID AND E.IsDefaultUnit=1
--处理双单位
INSERT INTO PType_Units_Ext(PtypeID,UnitsId,RateType,Rate,IsDefaultUnit)
	SELECT P.typeId,u.UnitsId,0,p.UnitRate1,0  
	FROM PTYPE P,PType_Units u 
	WHERE ISNULL(P.UnitRate1,0)<>0 AND U.FullName=P.Unit2

IF @@ROWCOUNT>0
	SET @UnitsType = 1 
	
UPDATE ptype 
SET UnitsType=1,BuyUnitId=e.UnitsId,SaleUnitId=e.UnitsId,ProduceUnitId=e.UnitsId,JobUnitId=e.UnitsId,StockUnitId=E.UnitsId
FROM PType_Units_Ext E 
WHERE ISNULL(UnitRate1,0)<>0 AND E.PtypeID=typeId AND E.IsDefaultUnit=0

UPDATE ptype 
SET UnitsType=@UnitsType,BuyUnitId=e.UnitsId,SaleUnitId=e.UnitsId,ProduceUnitId=e.UnitsId,JobUnitId=e.UnitsId,StockUnitId=E.UnitsId
FROM PType_Units_Ext E 
WHERE ISNULL(UnitRate1,0)=0 AND E.PtypeID=typeId AND E.IsDefaultUnit=1


UPDATE Userconfig SET Value=@UnitsType WHERE ConfigName='doubleunit'

--处理商品的条码
UPDATE ptype
SET IfUseEntryCode = 1
WHERE ISNULL(EntryCode,'')<>''


UPDATE ptype
SET IfUseGoodsNum = 0
WHERE IfUseGoodsNum IS NULL
  
IF @costing=3
BEGIN
	UPDATE PType SET IfUseGoodsNum=1
END
UPDATE PTYPE SET UnitRate1=0

-----------------------单据多单位、外币升级------------------------------------
CREATE TABLE #Ptype
(
	TypeID		VARCHAR(50),	--商品id
	UnitID		INT,			--基本单位id
	unitName	VARCHAR(50),	--基本单位名称
	MUnitID		INT,			--大单位id
	MunitName	VARCHAR(50),	--大单位名称
	UnitRate	 NUMERIC(24, 10) 	--换算关系
)
INSERT INTO #Ptype
	SELECT	P.typeId,
			P.baseUnitId,
			U.FullName,
			CASE WHEN ISNULL(P.SaleUnitId,0)=0 THEN P.baseUnitId ELSE P.SaleUnitId END AS  SaleUnitId,
			CASE WHEN  ISNULL(P.SaleUnitId,0)=0 THEN U.FullName ELSE U1.FullName END AS MunitName,
			CASE WHEN ISNULL(UnitRate1,0)=0 THEN 1 ELSE UnitRate1 END AS UnitRate
	FROM ptype p,PType_Units u,PType_Units U1
	WHERE P.baseUnitId=U.UnitsId AND (u1.UnitsId = p.SaleUnitId OR ISNULL(P.SaleUnitId,0)=0)
--询价单	
UPDATE AskPriceBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = Price,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0 
FROM #Ptype P
WHERE PTypeID=P.TypeID
--请购
UPDATE RequestBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = P.UnitID,
	MQty =  Qty,
	MUnitRate= 1,
	MUnitMsg =  CAST(Qty AS VARCHAR)+P.unitName,
	MSalePrice = SalePrice,
	MDiscountPrice = DiscountPrice,
	MTaxPrice = TaxPrice,
	CurMSalePrice = SalePrice,
	CurMDiscountPrice = DiscountPrice,
	CurMTaxPrice = TaxPrice,
	ItemID = 0,
	IsCombined = 0 
FROM #Ptype P
WHERE PTypeID=P.TypeID
--订单
UPDATE OrderBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = price,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0),
	BillOver = 0
FROM #Ptype P
INNER JOIN OrderBill O ON P.TypeID = O.ptypeid
LEFT JOIN CargoType c ON O.KTypeID=C.KtypeID AND  C.IsDefault=1


--采购单
UPDATE BuyBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(c.CargoID,0)
FROM #Ptype P
INNER JOIN BuyBill O ON P.TypeID = O.ptypeid
LEFT JOIN CargoType c ON O.KTypeID=C.KtypeID AND  C.IsDefault=1

--采购退货单
UPDATE BuyBackBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(c.CargoID,0)
FROM #Ptype P
INNER JOIN BuyBackBill O ON P.TypeID = O.ptypeid
LEFT JOIN CargoType c ON O.KTypeID=C.KtypeID AND  C.IsDefault=1
--采购换货单
UPDATE BuyGoodsExchangeBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(c.CargoID,0)
FROM #Ptype P
INNER JOIN BuyGoodsExchangeBill O ON P.TypeID = O.ptypeid
LEFT JOIN CargoType c ON O.KTypeID=C.KtypeID AND  C.IsDefault=1
--委托类单据
UPDATE CommissionBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(c.CargoID,0)
FROM #Ptype P
INNER JOIN CommissionBill B ON P.TypeID = B.PtypeId
LEFT JOIN  CargoType c  ON B.KTypeID=C.KtypeID AND C.IsDefault=1 

--报价单
UPDATE QuotePriceBill 
SET
	CurRate = 1,
	TaxMoney = TaxTotal-Total,
	NSalePrice = Price,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10)) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0
FROM #Ptype P
WHERE PTypeID=P.TypeID
--零售单
UPDATE retailbill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = c.CargoID
FROM #Ptype P,CargoType c ,BillIndex b
WHERE  retailbill.PTypeID=P.TypeID AND retailbill.BillNumberId=B.BillNumberId AND B.KTypeID=C.KtypeID AND C.IsDefault=1
--销售出库单
UPDATE SaleBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(c.CargoID,0)
FROM #Ptype P
INNER JOIN SaleBill O ON P.TypeID = O.ptypeid
LEFT JOIN CargoType c ON O.KTypeID=C.KtypeID AND  C.IsDefault=1
--销售退货
UPDATE SaleBackBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice =dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(c.CargoID,0)
FROM #Ptype P
INNER JOIN SaleBackBill O ON P.TypeID = O.ptypeid
LEFT JOIN CargoType c ON O.KTypeID=C.KtypeID AND  C.IsDefault=1
--销售换货单
UPDATE SaleGoodsExchangeBill 
SET
	TaxMoney = TaxTotal-Total,
	NSalePrice = SalePrice,
	NSaleTotal = SaleTotal,
	NDiscountPrice = DiscountPrice,
	NTotal = Total,
	NTaxPrice = TaxPrice,
	NTaxTotal = TaxTotal,
	NTaxMoney = TaxTotal-Total,
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	MDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	MTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	CurMSalePrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN SalePrice*p.UnitRate ELSE SalePrice END),
	CurMDiscountPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN DiscountPrice*P.UnitRate ELSE DiscountPrice END),
	CurMTaxPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN TaxPrice*P.UnitRate ELSE TaxPrice END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(c.CargoID,0)
FROM #Ptype P
INNER JOIN SaleGoodsExchangeBill O ON P.TypeID = O.ptypeid
LEFT JOIN CargoType c ON O.KTypeID=C.KtypeID AND  C.IsDefault=1
--赠送单
UPDATE GiveBill 
SET
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	ItemID = 0,
	IsCombined = 0,
	CargoID = c.CargoID
FROM #Ptype P,CargoType c,BillIndex b 
WHERE GiveBill.PTypeID=P.TypeID AND B.BillNumberId=GiveBill.BillNumberId AND b.KTypeID=C.KtypeID AND C.IsDefault=1
--获赠单
UPDATE GivemeBill 
SET
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	ItemID = 0,
	IsCombined = 0,
	CargoID = c.CargoID
FROM #Ptype P,CargoType c,BillIndex b 
WHERE GivemeBill.PTypeID=P.TypeID AND B.BillNumberId=GivemeBill.BillNumberId AND b.KTypeID=C.KtypeID AND C.IsDefault=1
--同价调拨单
UPDATE MoveBill 
SET
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	ItemID = 0,
	IsCombined = 0,
	OutCargoID = c.CargoID,
	InCargoID = c1.CargoID
FROM #Ptype P,CargoType c,CargoType c1 
WHERE PTypeID=P.TypeID 
	AND MoveBill.KTypeID=C.KtypeID 
	AND C.IsDefault=1 
	AND MoveBill.KTypeId2 = C1.KtypeID 
	AND C1.IsDefault=1
--变价价调拨单
UPDATE MoveBjBill 
SET
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	ItemID = 0,
	IsCombined = 0,
	OutCargoID = c.CargoID,
	InCargoID = c1.CargoID
FROM #Ptype P,CargoType c,CargoType c1 
WHERE PTypeID=P.TypeID 
	AND MoveBjBill.KTypeID=C.KtypeID 
	AND C.IsDefault=1 
	AND MoveBjBill.KTypeId2 = C1.KtypeID 
	AND C1.IsDefault=1
--分支机构调拨单
UPDATE STypeMoveBill 
SET
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	ItemID = 0,
	IsCombined = 0,
	OutCargoID = c.CargoID,
	InCargoID = c1.CargoID
FROM #Ptype P,CargoType c,CargoType c1 
WHERE PTypeID=P.TypeID 
	AND STypeMoveBill.KTypeID=C.KtypeID 
	AND C.IsDefault=1 
	AND STypeMoveBill.KTypeId2 = C1.KtypeID 
	AND C1.IsDefault=1
--其他出入库单
UPDATE OtherInOutBill 
SET
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = C.CargoID
FROM #Ptype P,CargoType c
WHERE PTypeID=P.TypeID AND OtherInOutBill.KtypeId = C.KtypeID AND C.IsDefault=1
--报损单
UPDATE LoseBill 
SET
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MPrice = dbo.F_RoundPrice(CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END),
	ItemID = 0,
	IsCombined = 0,
	CargoID = C.CargoID
FROM #Ptype P,CargoType c,BillIndex b
WHERE LoseBill.PTypeID=P.TypeID AND B.BillNumberId = LoseBill.BillNumberId  AND b.ktypeid = C.KtypeID AND C.IsDefault=1
--报溢单
UPDATE overflowBill 
SET
	UnitID = P.UnitID,
	MUnitID = CASE WHEN IsUnit2 = 1 THEN P.MUnitID ELSE P.UnitID END,
	MQty = dbo.F_RoundQty(CASE WHEN IsUnit2=1 THEN CAST(Qty/P.UnitRate AS  NUMERIC(24, 10) ) ELSE Qty END),
	MUnitRate= dbo.F_RoundTranslateRate(CASE WHEN IsUnit2=1 THEN p.UnitRate ELSE 1 END),
	MUnitMsg = CASE WHEN IsUnit2=1 THEN CAST(CAST(Qty/P.UnitRate AS INT) AS VARCHAR)+P.MunitName+CAST((Qty-CAST(Qty/P.UnitRate AS INT)* p.UnitRate) AS VARCHAR)+P.unitName
					ELSE CAST(Qty AS VARCHAR)+P.unitName END,
	MPrice = CASE WHEN IsUnit2=1 THEN Price*p.UnitRate ELSE Price END,
	ItemID = 0,
	IsCombined = 0,
	CargoID = C.CargoID
FROM #Ptype P,CargoType c,BillIndex b
WHERE overflowBill.PTypeID=P.TypeID AND B.BillNumberId = overflowBill.BillNumberId  AND b.ktypeid = C.KtypeID AND C.IsDefault=1

--库存盘点单
UPDATE stockcheck 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = C.CargoID
FROM CargoType C,stockcheckindex b
WHERE stockcheck.StockCheckID = B.StockCheckID AND B.KTypeID = C.KtypeID AND C.IsDefault = 1

--生产拆装单
UPDATE DisassembleBill 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = C.CargoID
FROM CargoType C ,billindex b
WHERE DisassembleBill.BillNumberId=b.BillNumberId AND DisassembleBill.ktypeid = c.KtypeID AND C.IsDefault = 1

--积分兑换单
UPDATE IntegralExchangeBill 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = C.CargoID
FROM CargoType C ,billindex b
WHERE IntegralExchangeBill.BillNumberId=b.BillNumberId AND B.ktypeid = c.KtypeID AND C.IsDefault = 1
	
--发票
/*UPDATE FaPiaoBill 
SET
	CargoID = 0*/
--借还单
UPDATE LendBill 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = C.CargoID
FROM CargoType C ,LendIndex b
WHERE LendBill.BillNumberId=b.BillNumberId AND B.ktypeid = c.KtypeID AND C.IsDefault = 1
--报修单
UPDATE wx_Bill_Call 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_Call  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID

--维修取件
UPDATE wx_Bill_GetBack 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_GetBack  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--上门维修
UPDATE wx_Bill_Goto 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_Goto  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID

--维修品调入
UPDATE wx_Bill_In 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_In  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID

--维修借件
UPDATE wx_Bill_JieJian 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_JieJian  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--维修品调出
UPDATE wx_Bill_Out 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_Out  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--整机更换
UPDATE wx_Bill_Replace 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_Replace  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--维修单
UPDATE wx_Bill_Self 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_Self  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--送修单
UPDATE wx_Bill_Send 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_Send  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--维修品调拨
UPDATE wx_Bill_Move 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_Move  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--送修返回
UPDATE wx_Bill_SendBack 
SET
	ItemID = 0,
	IsCombined = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM wx_Bill_SendBack  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--价保
UPDATE  priceprotectbill
SET
	ItemID = 0,
	IsCombined = 0
--返利
UPDATE Advantage 
SET
	ItemID = 0,
	IsCombined = 0	
--应收增加、减少，应付增加、减少
UPDATE addebtbill
SET 
	NTotal = total,
	NCompleteTotal = CompleteTotal
--收款单
UPDATE gatheringbill
SET ntotal = total,
	ATYPEID = AC.NID
FROM ac_items ac
WHERE AC.TypeId = AtypeId
--付款单
UPDATE paybill
SET ntotal = total,
	ATYPEID = AC.NID
FROM ac_items ac
WHERE AC.TypeId = AtypeId
--预收、预付款单
UPDATE PreBill
SET ntotal = total,
	ATYPEID = AC.NID
FROM ac_items ac
WHERE AC.TypeId = AtypeId
--钱流类单据
UPDATE moneybill
SET ntotal = total,
	ATYPEID = AC.NID
FROM ac_items ac
WHERE AC.TypeId = AtypeId
--转款单
UPDATE movemoneybill
SET ntotal = total,
	ATYPEID = AC.NID
FROM ac_items ac
WHERE AC.TypeId = AtypeId
--成本调价单
UPDATE ADPRICEBILL
SET 
	IsCombined = 0,
	ItemID = 0,
	CargoID = ISNULL(C.CargoID,0)
FROM ADPRICEBILL  A
INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
LEFT JOIN CargoType C ON C.KtypeID = B.KTYPEID
--价保
--业务凭证
UPDATE accountcredence
SET ND_Total = dbo.F_RoundTotal(D_Total),
	NJ_Total = dbo.F_RoundTotal(J_Total),
	CID = @SYSCID,
	Rate = 1,
	TypeATypeID = AC.nId
FROM AC_items AC
WHERE TypeATypeID = AC.TypeId

UPDATE accountcredence
SET  ATypeID = AC.nId
FROM AC_items AC
WHERE ATypeID = AC.TypeId
	AND TypeATypeID NOT IN (27,33,35,39,28)


UPDATE  FaPiaoBill
SET	   Nprice = Price,
	   NTotal = Total,
	   NTaxPrice = TaxPrice,
	   NTaxTotal= TaxTotal,
	   NTaxMoney = TaxTotal-Total,
	   CargoID = ISNULL(c.CargoID,0),
	   UnitID = P.UNITID,
	   MUnitID=P.UnitID,
	   MQty = Qty,
	   MUnitRate =1,
	   MUnitMsg =CAST(Qty AS VARCHAR)+P.unitName ,
	   MPrice = Price,
	   MTaxPrice = TaxPrice,
	   CurMPrice = Price,
	   CurMTaxPrice = TaxPrice,
	   ItemID = 0,
	   IsCombined = 0,
	   Nbeforeprice = BeforePrice,
	   Nberoretotal   = BeforeTotal,
	   saleprice = Price,
	   saletotal = Total,
	   nsaleprice = Price,
	   nsaletotal = Total,
	   curmsaleprice = Price,
	   curmsaletotal= Total,
	   taxmoney	= TaxTotal - Total
FROM #Ptype P
INNER JOIN FaPiaoBill O ON P.TypeID = O.ptypeid
LEFT JOIN CargoType c ON O.KTypeID=C.KtypeID AND  C.IsDefault=1

--DROP TABLE #Ptype
----------------------------多单位和单据明细升级 END-------------------------------
--------------------------- 升级处理开票金额回写 START-----------------------------
EXEC Gp_UpdateInvoiceStateAll
---------------------------- 升级处理开票金额回写 END-----------------------------


-------------------------billindex、inoutstocktable、listtable、Atype_total、btype_araptotal 升级  START ------------------------
UPDATE ListTable SET AtypeId=AC.nId,Ntotal=ListTable.Total,CID=@SYSCID
FROM Ac_Items AC 
WHERE  ListTable.AtypeId = AC.TypeId


UPDATE Atype_total SET AtypeId=AC.nId,Ntotal=Atype_total.Total, Ntotal00 = AType_Total.Total00,CID=@SYSCID
FROM Ac_Items AC 
WHERE  Atype_total.AtypeId = AC.TypeId

UPDATE OtherInOutType SET AtypeId=AC.nId
FROM Ac_Items AC 
WHERE  OtherInOutType.AtypeId = AC.TypeId


UPDATE btype_araptotal 
SET CID=@SYSCID,nARTotal=ARTotal,nARTotal00=ARTotal00,nAPTotal=APTotal,nAPTotal00=ApTotal00,
	nYSTotal=YSTotal,nYSTotal00=YSTotal00,nYFTotal=YFTotal,nYFTotal00=YFTotal00	

DECLARE @SQL	VARCHAR(MAX)='',
		@ifusegoodsnumber	INT

SELECT @ifusegoodsnumber = Value FROM Userconfig WHERE ConfigName='ifusegoodsnumber'

IF @costing=3 AND @ifusegoodsnumber = 1
BEGIN
	SELECT   @SQL=@SQL+'
			 UPDATE '+detailTable +' 
			 SET GoodsNumber=''默认批号''
			 WHERE GoodsNumber='''' OR GoodsNumber IS NULL 
			 '
	FROM BillName
	WHERE Billtype IN(305,11,45,139,140,142,34,6,126,144,201,9,14,160,161,17,21,187,170,169,166,168,174,175,165,173,172,167,171,57,183,16)
	EXEC(@SQL)
END
SET @SQL=''

---inoutstocktable
SELECT @SQL=@SQL + 'UPDATE InOutstocktable
					SET		CargoID=bill.CargoID,
							NPrice=i.Price,
							NTotal=i.total,
							NSalePrice=i.SalePrice,
							NSaleTotal = i.SaleTotal,
							NTaxPrice=i.TaxPrice,
							NTaxTotal=i.TaxTotal,
							MUNITID=bill.MUnitID,
							ItemID = 0,
							IsCombined = 0,
							GoodsNumber = bill.GoodsNumber
					FROM InOutstocktable i,'+detailTable+' bill
					WHERE i.BillNumberId = bill.BillNumberId AND i.ID=bill.ID 
					'
FROM BillName
WHERE Billtype IN(305,11,45,139,140,142,143,141,34,6,126,144,145,147,201,9,14,160,161)--(305,11,45,139,140,142,143,141,34,6,126,144,146,147,145,187,188,201,202,9,14,57,205,206,165,166,167,168,169,170,171,172,173,174,175,183)
--处理明细双货位
SELECT @SQL=@SQL + 'UPDATE InOutstocktable
					SET		
							CargoID=(CASE WHEN i.qty<0 THEN bill.OutCargoID ELSE bill.InCargoID END),
							NPrice=i.Price,
							NTotal=i.total,
							NSalePrice=i.SalePrice,
							NSaleTotal = i.SaleTotal,
							NTaxPrice=i.TaxPrice,
							NTaxTotal=i.TaxTotal,
							MUNITID=bill.MUnitID,
							ItemID = 0,
							IsCombined = 0,
							GoodsNumber = bill.GoodsNumber
					FROM InOutstocktable i,'+detailTable+' bill
					WHERE i.BillNumberId = bill.BillNumberId AND i.ID=bill.ID '
FROM BillName
WHERE Billtype IN(17,21,187)

--处理不使用多单位的单据
SELECT @SQL=@SQL + 'UPDATE InOutstocktable
					SET		
							CargoID=c.CargoID,
							NPrice=i.Price,
							NTotal=i.total,
							NSalePrice=i.SalePrice,
							NSaleTotal = i.SaleTotal,
							NTaxPrice=i.TaxPrice,
							NTaxTotal=i.TaxTotal,
							MUNITID=P.UnitID,
							ItemID = 0,
							IsCombined = 0,
							GoodsNumber= (CASE WHEN ISNULL(GoodsNumber,'''')<>'''' AND '+CAST(@costing AS VARCHAR)+'=3 THEN ''默认批号'' ELSE GoodsNumber END)
					FROM InOutstocktable i,cargoType c,#Ptype p
					WHERE i.ktypeid = c.ktypeid AND p.typeid=i.ptypeid AND C.IsDefault=1
						  AND billType IN(170,169,166,168,174,175,165,173,172,167,171,205,206,57,183) '
	EXEC(@SQL)

UPDATE InOutstocktable SET MUNITID = 0 WHERE BillType=16

UPDATE InOutstocktable 
SET AtypeId = AC.nId
FROM AC_ITEMS AC
WHERE AtypeId=AC.TypeId
AND AtypeId='0000100001'

--print @SQL
UPDATE BillIndex 
SET CID=@SYSCID,
	Rate = 1,
	NTotalMoney = totalmoney,
	NTotalInMoney = totalinmoney,
	NPreferenceMoney = preferencemoney,
	NVIPCZMoney = vipCZMoney,
	NCompleteTotal = CompleteTotal,
	DealBTypeID = btypeid,
	IsIni = 0,
	ATID = 0,
	IfCargo = 0,
	billproperty = -1
	
UPDATE BillIndex 
SET ATypeID= AC.nId
FROM Ac_Items  AC
WHERE BillIndex.ATYPEID = AC.TypeId
	AND ATypeID<>'' AND ATypeID<>'-99999'


UPDATE BillMulAccount SET AtypeId=AC.nId,NTotalMoney=BillMulAccount.Total
FROM Ac_Items AC,AType a 
WHERE A.UserCode=AC.UserCode 

UPDATE OrderIndex
SET --CID=@SYSCID,
	Rate = 1,
	Ntotalmoney = totalmoney,
	DealBTypeID = btypeid
	

UPDATE FaPiaoBillIndex
SET CID = @SYSCID,
	Rate = 1,
	NTaxTotalMoney = TaxTotalMoney,
	NTotalMoney = TotalMoney,
	DealBTypeID = BTypeID
	
UPDATE RequestIndex
SET CID = @SYSCID,
	Rate = 1,
	NTotalMoney = totalmoney
	
----------------------------billindex、inoutstocktable、listtable、Atype_total、btype_araptotal 升级  END   ------------------------
----------------------------库表升级 START -----------------------
/*
COMMISSIONSTOCK_QTY
GOODSLEND
GOODSSTOCKS_QTY
WX_GOODSSTOCKS
WX_INOUTSTOCKTABLE

SELECT * FROM COMMISSIONSTOCK_QTY
SELECT ProduceDate,ValidDate,GoodsNumber,* FROM InOutstocktable
*/
IF @costing<>3
BEGIN
	INSERT INTO COMMISSIONSTOCK_QTY
			(Ptypeid,Btypeid,Stypeid,type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty)
	SELECT  Ptypeid,Btypeid,Stypeid,type,0,0,'','','',Qty,0 FROM CommissionStock
END
ELSE
BEGIN

	DECLARE @nPtypeid VARCHAR(50),@nBtypeid VARCHAR(50),@nStypeid VARCHAR(50),
			@nqty  NUMERIC(24, 10) ,@nid BIGINT,@TMPID BIGINT,@tmpQty  NUMERIC(24, 10) ,
			@tmpDecQty	 NUMERIC(24, 10)  

	CREATE TABLE #CommissionStock_Qty(
			[Ptypeid]					VARCHAR(50)		DEFAULT (''),
			[Btypeid]					VARCHAR(50)		DEFAULT (''),
			[Stypeid]					VARCHAR(50)		DEFAULT (''),
			[Type]						INT				DEFAULT(0),
			ItemID						INT				DEFAULT(0),
			Iscombined					BIT				DEFAULT(0),
			GoodsNumber					VARCHAR(100)	DEFAULT(''),
			ProduceDate					VARCHAR(50)		DEFAULT (''),
			ValidDate					VARCHAR(50)		DEFAULT (''),
			Qty							 NUMERIC(24, 10) 	DEFAULT(0),
			NQty						 NUMERIC(24, 10) 	DEFAULT(0),
			GoodsCostPrice				 NUMERIC(24, 10)   DEFAULT(0),
			ID							INT IDENTITY(1,1)		
		) 
	INSERT INTO #CommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
		SELECT  A.Ptypeid,a.Btypeid,A.stypeid,A.type,0 as ItemID,0 as Iscombined,
					A.GoodsNumber,a.ProduceDate,a.ValidDate,
					SUM(A.Qty)-SUM(ISNULL(B.QTY,0)) as qty,0 as NQty,A.CostPrice FROM 
			(
				SELECT Ptypeid,Btypeid,stypeid,144 as type,0 as ItemID,0 as Iscombined,GoodsNumber,ProduceDate,ValidDate,SUM(Qty) as qty,0 as NQty,CostPrice 
				FROM InOutstocktable 
				WHERE BillType IN(144) AND KtypeId<>'10000'
				GROUP BY Ptypeid,Btypeid,stypeid,GoodsNumber,ProduceDate,ValidDate,CostPrice,billtype
			)A
			LEFT JOIN 
			(
				SELECT c.ptypeid,b.Btypeid,B.STYPEID,c1.GoodsNumber,c1.ProduceDate,c1.ValidDate,SUM(C.Qty) AS Qty,0 AS NQty 
				FROM CommissionBill c
				INNER JOIN BillIndex b ON C.BillNumberId = B.BillNumberId 
				INNER JOIN CommissionBill c1 ON C1.ID=C.OldID
				WHERE B.draft = 0 AND B.RedWord = 0 AND B.ifcheck='T' AND B.BillType IN(145,146) AND C.OldID IS NOT NULL
				GROUP BY c.Ptypeid,b.Btypeid,B.STYPEID,c.stypeid,c1.GoodsNumber,c1.ProduceDate,c1.ValidDate
			)b on a.PtypeId =b.PtypeId AND A.BtypeId = B.btypeid AND A.STypeID=B.Stypeid AND A.GoodsNumber = B.GoodsNumber AND A.ProduceDate = B.ProduceDate AND A.ValidDate = B.ValidDate	
		 GROUP BY A.Ptypeid,A.Btypeid,A.stypeid,A.GoodsNumber,A.ProduceDate,A.ValidDate,A.CostPrice,A.type	


	DECLARE CommissionStock_CURSOR CURSOR FOR
		SELECT	c.Ptypeid,b.Btypeid,B.stypeid,c.qty,C.ID
		FROM	CommissionBill c
		INNER JOIN  billindex b ON C.billnumberid=b.billnumberid
		WHERE  B.draft = 0 AND B.RedWord = 0 AND B.ifcheck='T' AND B.BillType IN(145,141) AND C.OldID IS NULL
		ORDER BY b.posttime 
		OPEN CommissionStock_CURSOR
		FETCH NEXT FROM CommissionStock_CURSOR INTO	@nPtypeid,@nBtypeid,@nStypeid,@nqty,@nid
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT TOP 1 @TMPID=ID,@tmpQty=Qty 
			FROM  #CommissionStock_Qty  
			WHERE  Ptypeid=@nPtypeid AND Btypeid=@nBtypeid  AND Stypeid= @nStypeid AND qty <> 0 
			ORDER BY ID 
			
			WHILE @tmpQty<=@nqty
			BEGIN 
				SET @nqty = @nqty - @tmpQty
				DELETE #CommissionStock_Qty WHERE ID=@TMPID
				SELECT TOP 1 @TMPID=ID,@tmpQty=Qty 
				FROM  #CommissionStock_Qty  
				WHERE  Ptypeid=@nPtypeid AND Btypeid=@nBtypeid  AND Stypeid= @nStypeid AND qty <> 0 
				ORDER BY ID 
			END
			IF @tmpQty>@nqty
			BEGIN
					UPDATE #CommissionStock_Qty SET Qty=Qty-@nqty WHERE ID=@TMPID
			END
			FETCH NEXT FROM CommissionStock_CURSOR INTO	@nPtypeid,@nBtypeid,@nStypeid,@nqty,@nid
		END
	CLOSE CommissionStock_CURSOR
	DEALLOCATE CommissionStock_CURSOR

	CREATE TABLE #CommissionStock_Qtywt(
			[Ptypeid]					VARCHAR(50)		DEFAULT (''),
			[Btypeid]					VARCHAR(50)		DEFAULT (''),
			[Stypeid]					VARCHAR(50)		DEFAULT (''),
			[Type]						INT				DEFAULT(0),
			ItemID						INT				DEFAULT(0),
			Iscombined					BIT				DEFAULT(0),
			GoodsNumber					VARCHAR(100)	DEFAULT(''),
			ProduceDate					VARCHAR(50)		DEFAULT (''),
			ValidDate					VARCHAR(50)		DEFAULT (''),
			Qty							 NUMERIC(24, 10) 	DEFAULT(0),
			NQty						 NUMERIC(24, 10) 	DEFAULT(0),
			GoodsCostPrice				 NUMERIC(24, 10)   DEFAULT(0),
			ID							INT IDENTITY(1,1)		
		) 
	INSERT INTO #CommissionStock_Qtywt(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
		SELECT  A.Ptypeid,a.Btypeid,A.stypeid,A.type,0 as ItemID,0 as Iscombined,
					A.GoodsNumber,a.ProduceDate,a.ValidDate,
					SUM(A.Qty)-SUM(ISNULL(B.QTY,0)) as qty,0 as NQty,A.CostPrice FROM 
			(
				SELECT Ptypeid,Btypeid,stypeid, 140  as type,0 as ItemID,0 as Iscombined,GoodsNumber,ProduceDate,ValidDate,SUM(-Qty) as qty,0 as NQty,CostPrice 
				FROM InOutstocktable 
				WHERE BillType IN(140) AND KtypeId<>'10000'
				GROUP BY Ptypeid,Btypeid,stypeid,GoodsNumber,ProduceDate,ValidDate,CostPrice,billtype
			)A
			LEFT JOIN 
			(
				SELECT c.ptypeid,b.Btypeid,B.STYPEID,c1.GoodsNumber,c1.ProduceDate,c1.ValidDate,SUM(C.Qty) AS Qty,0 AS NQty 
				FROM CommissionBill c
				INNER JOIN BillIndex b ON C.BillNumberId = B.BillNumberId 
				INNER JOIN CommissionBill c1 ON C1.ID=C.OldID
				WHERE B.draft = 0 AND B.RedWord = 0 AND B.ifcheck='T' AND B.BillType IN(141,142) AND C.OldID IS NOT NULL
				GROUP BY c.Ptypeid,b.Btypeid,B.STYPEID,c.stypeid,c1.GoodsNumber,c1.ProduceDate,c1.ValidDate
			)b on a.PtypeId =b.PtypeId AND A.BtypeId = B.btypeid AND A.STypeID=B.Stypeid AND A.GoodsNumber = B.GoodsNumber AND A.ProduceDate = B.ProduceDate AND A.ValidDate = B.ValidDate
			GROUP BY A.Ptypeid,A.Btypeid,A.stypeid,A.GoodsNumber,A.ProduceDate,A.ValidDate,A.CostPrice,A.type	

	DECLARE CommissionStock_CURSOR1 CURSOR FOR
		SELECT	c.Ptypeid,b.Btypeid,B.stypeid,c.qty,C.ID
		FROM	CommissionBill c
		INNER JOIN  billindex b ON C.billnumberid=b.billnumberid
		WHERE  B.draft = 0 AND B.RedWord = 0 AND B.ifcheck='T' AND B.BillType IN(141,142) AND C.OldID IS NULL
		ORDER BY b.posttime 
		OPEN CommissionStock_CURSOR1
		FETCH NEXT FROM CommissionStock_CURSOR1 INTO	@nPtypeid,@nBtypeid,@nStypeid,@nqty,@nid
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT TOP 1 @TMPID=ID,@tmpQty=Qty 
			FROM  #CommissionStock_Qtywt  
			WHERE  Ptypeid=@nPtypeid AND Btypeid=@nBtypeid  AND Stypeid= @nStypeid AND qty <> 0 
			ORDER BY ID 
			
			WHILE @tmpQty<=@nqty
			BEGIN 
				SET @nqty = @nqty - @tmpQty
				DELETE #CommissionStock_Qtywt WHERE ID=@TMPID
				SELECT TOP 1 @TMPID=ID,@tmpQty=Qty 
				FROM  #CommissionStock_Qtywt  
				WHERE  Ptypeid=@nPtypeid AND Btypeid=@nBtypeid  AND Stypeid= @nStypeid AND qty <> 0 
				ORDER BY ID 
			END
			IF @tmpQty>@nqty
			BEGIN
					UPDATE #CommissionStock_Qtywt SET Qty=Qty-@nqty WHERE ID=@TMPID
			END
			FETCH NEXT FROM CommissionStock_CURSOR1 INTO	@nPtypeid,@nBtypeid,@nStypeid,@nqty,@nid
		END
	CLOSE CommissionStock_CURSOR1
	DEALLOCATE CommissionStock_CURSOR1
	
	INSERT INTO COMMISSIONSTOCK_QTY
			(Ptypeid,Btypeid,Stypeid,type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
	SELECT  Ptypeid,Btypeid,Stypeid,type,0,0,GoodsNumber,ProduceDate,ValidDate,dbo.F_RoundQty(Qty),0,GoodsCostPrice 
	FROM #CommissionStock_Qty
	WHERE Qty<>0
	INSERT INTO COMMISSIONSTOCK_QTY
			(Ptypeid,Btypeid,Stypeid,type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice)
	SELECT  Ptypeid,Btypeid,Stypeid,type,0,0,GoodsNumber,ProduceDate,ValidDate,dbo.F_RoundQty(Qty),0,GoodsCostPrice 
	FROM #CommissionStock_Qtywt
	WHERE Qty<>0
END

INSERT INTO GOODSSTOCKS_QTY(PTypeID,KTypeID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,CargoID)
SELECT PtypeId,s.KtypeId,0,0,GoodsNumber,ProduceDate,ValidDate,Qty,NULL,c.CargoID
FROM GOODSSTOCKS s,CargoType c
where c.KtypeID=s.KtypeId

UPDATE GoodsLend SET ItemID=0,Iscombined=0 
UPDATE WX_GOODSSTOCKS SET ItemID=0,Iscombined=0,CargoID = 0
UPDATE WX_INOUTSTOCKTABLE SET ItemID=0,Iscombined=0,CargoID = c.CargoID FROM CargoType C

UPDATE WX_INOUTSTOCKTABLE
SET		
	CargoID=c.CargoID,
	NPrice=i.Price,
	NTotal=i.total,
	NSalePrice=i.SalePrice,
	NSaleTotal = i.SaleTotal,
	NTaxPrice=i.TaxPrice,
	NTaxTotal=i.TaxTotal,
	MUNITID=P.UnitID,
	ItemID = 0,
	IsCombined = 0
FROM WX_INOUTSTOCKTABLE i,cargoType c,#Ptype p
WHERE i.ktypeid = c.ktypeid AND p.typeid=i.ptypeid AND C.IsDefault=1


----------------------------库表升级 END   -----------------------
DROP TABLE #CommissionStock_Qty,#Ptype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateUserGroupLim]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateUserGroupLim]
GO



/*
	作者：陈守川
	日期：2012-02-09
	描述：保存用户组权限
*/
CREATE        PROCEDURE Gp_UpdateUserGroupLim 
(
  @ugid	    [varchar](10),
  @Lim		[varchar](8000)='',
  @operator		[varchar](50)
)
--@encode$--
AS
SET NOCOUNT ON
IF @Lim='' return -1
ELSE
	BEGIN
		--取操作员旧权限
		SELECT	etypeid,
				lim
		INTO #oldloginuser
		FROM LoginUser WHERE belongToGroup=@ugid
		
		--保存用户组权限
		UPDATE UserGroup SET lim=@Lim WHERE UGId=@ugid
		--保存该用户组下所有操作员的权限
		UPDATE loginuser 
		SET lim=@Lim 
		WHERE etypeid IN 
		(
			SELECT etypeid FROM loginuser WHERE belongToGroup=@ugid
		)
		
		BEGIN --写入权限变更日志
			INSERT INTO LimitLog
			(
				Operator,
				Etypeid,
				oldlim,
				newlim,
				ChangeDatetime,
				ChangeEvent
			)
			SELECT	@operator,
					l.etypeid,
					O.lim,
					L.lim,
					GETDATE(),
					'角色权限修改'
			FROM #oldloginuser o
			INNER JOIN loginuser l ON L.etypeid=o.etypeid AND l.belongToGroup=@ugid
		END;

		
		EXEC Gp_DataSaveForPosDown '-99999','loginuser','0'
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateVipCardCent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_UpdateVipCardCent
GO

-- =============================================
-- Author:		韩林
-- Create date: 2013-05-13
-- Description: Pos使用会员储值后修改会员积分信息
-- =============================================

CREATE   PROCEDURE Gp_UpdateVipCardCent
(
	@VipCardID		INT,
	@ptypeinfo		TBType_VipCardPtype READONLY
)
--@encode$--
AS

	DECLARE @intVipJF INT =0,@Multiple	DECIMAL(7,2)=0,@datBillDate DATETIME=GETDATE()
	SELECT	@intVipJF = ISNULL(SUM(a.GridJF),0) 
	FROM(
		SELECT	CAST((SUM(ISNULL(a.Total,0))/c.Total) AS int)*ISNULL(c.JF,0) AS GridJF
		FROM	@ptypeinfo a,
				(	SELECT CASE WHEN JFid=0 THEN(SELECT jfgz FROM nVipCardSet ns1,NVipCardSign ns2  WHERE ns1.VipCardTypeID= ns2.VipCardTypeID AND ns2.VipCardID=@VipCardID) ELSE JFid END AS RealJFid,* FROM dbo.nVipGoodsSign) b,
				nVipJfSet c,
				ptype p
		WHERE	a.pid=p.Pid
				AND p.TypeID = b.PTypeID
				AND b.RealJFid = c.[ID]
				AND c.Total <> 0
				AND c.JF <> 0
				AND a.UnitId = b.UnitId   --积分翻倍问题解决
		GROUP BY c.[ID],c.Total,c.[JF]
	)a
	PRINT @intVipJF 
	
	IF EXISTS(SELECT 1 FROM dbo.nVipCardSet WHERE VipCardTypeID=(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@VipCardID AND MONTH(Bbirthday)=MONTH(@datBillDate) AND DAY(Bbirthday)=DAY(@datbilldate)) AND IfBirthDay='0' AND ifJF='1')
		SELECT @Multiple=BirthDayMultiple FROM dbo.nVipCardSet WHERE VipCardTypeID=(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@VipCardID )
	IF EXISTS(SELECT 1 FROM dbo.nVipCardSet WHERE VipCardTypeID=(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@VipCardID) AND IfDate='0' AND ifJF='1' AND StartDate<=@datBillDate AND EndDate>=CONVERT (DATE,@datBillDate,120) AND CAST(DateMultiple AS  NUMERIC(24, 10) )>@Multiple)
		SELECT @Multiple=DateMultiple FROM dbo.nVipCardSet WHERE VipCardTypeID=(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@VipCardID )
	IF @Multiple=0
		SET @Multiple=1
	SET @intVipJF=@intVipJF*@Multiple
	
	IF @intVipJF <> 0
	UPDATE nVipCardSign SET TotalCent = TotalCent + @intVipJF
	WHERE VipCardID = @VipCardID
	
	--自动升级会员卡	
	DECLARE @UpgradePoint INT=0,@oldtypelevel INT =0,@nBillId INT,@billdate VARCHAR(20),@billcode VARCHAR(50),@etypeid VARCHAR(50),
			@validday INT,@validtype INT		
	SELECT @UpgradePoint = Value FROM dbo.Userconfig WHERE ConfigName='UpgradePointToVip'
	SELECT @oldtypelevel =TypeLevel FROM dbo.nVipCardSet WHERE  VipCardTypeID =(SELECT VipCardTypeID FROM dbo.nVipCardSign WHERE VipCardID=@VipCardID)
	IF @UpgradePoint=1 AND @oldtypelevel>0 AND @oldtypelevel<5 AND @intVipJF>=0
	BEGIN
		DECLARE @typelevel INT=0,@standardcent DECIMAL(10,0)=0,@deductcent DECIMAL(10,0) =0,
				@AllTotalCent  NUMERIC(24, 10) ,@oldCardtype INT =0,@newCardType INT =0
		
		SELECT	@AllTotalCent=ISNULL(TotalCent,0)+ISNULL(BeginCent,0)
		FROM	nVipCardSign a
		WHERE	a.VipCardID = @VipCardID

		SELECT *
		INTO #VipCardSet 
		FROM dbo.nVipCardSet
		WHERE TypeLevel>@oldtypelevel
		
		UPDATE #VipCardSet 
		SET StandardCent+=n2.DeductCent,
			deductcent +=n2.deductcent
		FROM 
		(
			SELECT n.TypeLevel,SUM(a.DeductCent) AS DeductCent
			FROM #VipCardSet n
			INNER JOIN #VipCardSet a ON a.TypeLevel<n.TypeLevel
			GROUP BY n.TypeLevel
		)n2
		WHERE n2.TypeLevel=#VipCardSet.TypeLevel
							
		SELECT @oldCardtype = VipCardTypeID,@etypeid=etypeid FROM dbo.nVipCardSign WHERE VipCardID=@VipCardID
		SELECT TOP 1 @typelevel= TypeLevel,@standardcent=StandardCent,@deductcent=DeductCent FROM #VipCardSet WHERE TypeLevel>@oldtypelevel AND StandardCent<=@AllTotalCent ORDER BY TypeLevel DESC
		IF  @typelevel>1
		BEGIN
			SELECT @newCardType=VipCardTypeID,@validday=ValidDate,@validtype=ValidType FROM dbo.nVipCardSet WHERE TypeLevel=@typelevel
			UPDATE dbo.nVipCardSign SET totalCent=totalCent-@deductcent,VipCardTypeID=@newCardType WHERE VipCardID=@VipCardID
			DECLARE @sql NVARCHAR(max)
			SET @sql='UPDATE dbo.nVipCardSign SET EndDate=DATEADD('+CASE WHEN @validtype=0 THEN 'YEAR' WHEN @validtype=1 THEN 'MONTH' ELSE 'DAY' END+',@validday,CAST(GETDATE() AS DATE)) WHERE VipCardID=@VipCardID'
			EXEC sp_executesql @sql, N'@validday int,@VipCardID int',@validday,@VipCardID
			INSERT INTO dbo.nVipCardTypeChange
	        ( 
				VipCardID ,
				OldVipCardTypeID ,
				NewVipCardTypeID ,
				etypeid ,
				ChangeDate ,
				OperatStyle ,
				Comment
	        )
			VALUES  
			( 
				@VipCardID,
				@oldCardType,
				@newCardType,
				'',
				convert(varchar(10),getdate(),120) ,
				1,
				'系统自动升级会员级别'
			)
			
			IF NOT EXISTS(SELECT TOP 1 1 FROM nVipAdjust)
				SET @nBillID = 1
			ELSE
				SELECT @nBillId = ISNULL(MAX(BillNumberId),0) + 1 FROM nVipAdjust
			SET @billdate=CONVERT(varchar(10),GetDate(),120)	
			EXEC dbo.Gp_GetAdjustCode  'JFC', @billdate,  @BillCode output 
			
			IF @deductcent>0
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM nVipAdjust)
					SET @nBillID = 1
				ELSE
					SELECT @nBillId = ISNULL(MAX(BillNumberId),0) + 1 FROM nVipAdjust
				SET @billdate=CONVERT(varchar(10),GetDate(),120)	
				EXEC dbo.Gp_GetAdjustCode  'JFC', @billdate,  @BillCode output 
				INSERT INTO nVipAdjust
				(
					BillNumberId,
					BillDate,
					BillCode,
					ETypeId,
					Checke,
					VipNo,
					UpCost,
					DownCost,
					SumCost,
					Reason,
					IsSend,
					nType
				)VALUES(
					@nBillId,
					@BillDate,
					@BillCode,
					@etypeid,
					@etypeid,
					@VipCardID,
					0,
					@deductcent,
					-@deductcent,
					'会员级别升级扣减',
					0,
					2
				)
			END
		END
	END

RETURN @intVipJF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateVipCardInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateVipCardInfo]
GO

-- =============================================
-- Author:		韩林
-- Create date: 2013-05-13
-- Description: Pos使用会员储值后修改会员卡信息
-- =============================================

CREATE   PROCEDURE Gp_UpdateVipCardInfo
(
	@VipCardCode	VARCHAR(50),
	@VipMoney		NUMERIC(24, 10) ,
	@TotalMoney     NUMERIC(24, 10) ,
	@billdate		DATETIME,
	@pid			INT
)
--@encode$--
AS

DECLARE   
@chvVipIsCz			CHAR(1),	--是否储值
@numVipcZyeMoney		 NUMERIC(24, 10)   --储值余额


SELECT	@chvVipIsCz = a.IsCz,
		@numVipcZyeMoney = a.cZyeMoney
FROM	nVipCardSign a,
		nVipCardSet b
WHERE	a.VipCardCode = @VipCardCode
		AND a.VipCardTypeID = b.VipCardTypeID
		AND a.Deleted = '0'
		AND b.Deleted = '0'
		AND a.EndDate >= @BillDate

-- 1)无此VIP卡 2)过了有效期 3)VIP卡是未启用状态 4)VIP卡类型不存在或已删除
IF @@ROWCOUNT = 0 OR @@ERROR <> 0 
BEGIN
	RAISERROR('获取会员卡信息失败！',16,1)
	RETURN
END

IF @numVipcZyeMoney < @VipMoney
BEGIN
	RAISERROR('会员卡余额不足！',16,1)
	RETURN
END

BEGIN TRAN updatevip

DECLARE @intVipJF	INT = 0,	 --单据总积分
		@tableName	VARCHAR(50)  --单据明细表
		
UPDATE	nVipCardSign
SET		TotalMoney = dbo.F_RoundTotal(TotalMoney + @TotalMoney),  --加单据金额
		cZyeMoney = dbo.F_RoundTotal(cZyeMoney -@VipMoney)
WHERE	VipCardCode = @VipCardCode

DECLARE @stypeid VARCHAR(100) 
DECLARE @intVipCardID INT

SELECT @stypeid = stypeid FROM dbo.PosInfo WHERE PosID = @pid
SELECT @intVipCardID = VipCardID FROM dbo.nVipCardSign WHERE VipCardCode=@VipCardCode
	
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSignStype WHERE VipCardID=@intVipCardID AND StypeId=@StypeID)
BEGIN
	INSERT INTO dbo.nVipCardSignStype
	( 
		VipCardID ,
		StypeId ,
		qCczMoney ,
		lJczMoney ,
		lJxFczMoney ,
		bNczMoney ,
		bNxFczMoney ,
		cZyeMoney ,
		lJxFMoney ,
		bNxFMoney
	)VALUES( 
		@intVipCardID , -- VipCardID - int
		@STypeID , -- StypeId - varchar(50)
		0 , -- qCczMoney - numeric
		0 , -- lJczMoney - numeric
		0 ,--@TotalMoney , -- lJxFczMoney - numeric
		0 , -- bNczMoney - numeric
		0 , -- bNxFczMoney - numeric
		-@VipMoney , -- cZyeMoney - numeric
		@TotalMoney , -- lJxFMoney - numeric
		@TotalMoney  -- bNxFMoney - numeric
	)
END
ELSE
BEGIN
	UPDATE	dbo.nVipCardSignStype
	SET		lJxFczMoney=lJxFczMoney+@VipMoney,
			bNxFczMoney = bNxFczMoney+@VipMoney,
			cZyeMoney = cZyeMoney-@VipMoney,
			lJxFMoney = lJxFMoney+@TotalMoney,
			bNxFMoney = bNxFMoney+@TotalMoney
	WHERE	VipCardID=@intVipCardID 
			AND StypeId=@STypeID
END

IF EXISTS(SELECT * FROM dbo.nVipCardSign WHERE VipCardCode = @VipCardCode AND cZyeMoney < 0)
	ROLLBACK TRAN updatevip
ELSE
	COMMIT TRAN updatevip
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateVipSMSTemplate]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Gp_UpdateVipSMSTemplate
GO

-- ========================================================================
-- 描述：	修改指定会员短信模板信息
-- 时间：	2017-10-17
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_UpdateVipSMSTemplate
(
	@smsId						INT,					--模板ID
	@tempCode				VARCHAR(500),			--短信群发模板编号
	@tempName				VARCHAR(500),			--短信群发模板名称
	@tempTypeId			INT,					--模板类型
	@vipCardTypeID		VARCHAR(MAX),			--发送对象(卡类型)
	@tempContent			VARCHAR(MAX),			--群发内容
	@comment				VARCHAR(MAX),			--备注
	@isPostSend				BIT,					--过账时自动发送(不包含自动过账)
	@OpertiorId				VARCHAR(50)='00000',	--操作人
	@Birth_IsAutoSend	BIT=0,--（@Birth_IsAutoSend）会员生日短信提前（@SendDay）天（@SendTime）时间
	@SendDay					INT=0,
	@SendTime				TIME='00:00:00',
	@retcontent				VARCHAR(MAX) OUTPUT,	--返回数据
	@rettemplateid			VARCHAR(100) OUTPUT,	--返回ID
	@retsmsid					VARCHAR(100) OUTPUT		--返回SMSID
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE smsId=@smsId)
	BEGIN
		RAISERROR('该模板信息已不存在，请确认！',16,1) RETURN
	END
	
IF ISNULL(@tempCode,'')=''
	BEGIN
		RAISERROR('模板编号不能为空，请确认！',16,1) RETURN
	END
	
IF ISNULL(@tempName,'')=''
	BEGIN
		RAISERROR('模板名称不能为空，请确认！',16,1) RETURN
	END
			
IF ISNULL(@tempContent,'')=''
	BEGIN
		RAISERROR('短信内容不能为空，请确认！',16,1) RETURN
	END		
				
IF EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE tempCode=@tempCode AND smsId<>@smsId)
	BEGIN
		RAISERROR('系统中已经存在该模板编号，请确认！',16,1) RETURN
	END
	
IF EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE tempName=@tempName AND smsId<>@smsId)
	BEGIN
		RAISERROR('系统中已经存在该模板名称，请确认！',16,1) RETURN
	END
	
	
DECLARE @Error INT=0

BEGIN TRAN

--翻译模版
DECLARE @returncontent VARCHAR(MAX)

EXEC Web_ConvertBillTypeOldSmsContentToHyyun '-1',@tempContent,@returncontent OUTPUT

UPDATE	SMSInfo_Template 
SET		tempCode=@tempCode,
		tempName=@tempName,
		tempTypeId=@tempTypeId,
		tempContent=@tempContent,
		comment=@comment,
		isPostSend=CASE WHEN @smsId=6 THEN CASE WHEN @Birth_IsAutoSend=1 THEN 1 ELSE 0 END ELSE @isPostSend END ,
		HyyunSmsTemplateContent = @returncontent,
		Birth_IsAutoSend=CASE WHEN @smsId=6 THEN @Birth_IsAutoSend ELSE 0  END,
		SendDay=CASE WHEN @smsId=6 THEN @SendDay ELSE 0  END ,
		SendTime=CASE WHEN @smsId=6 THEN @SendTime ELSE  '00:00:00'  END
WHERE	smsId=@smsId
SET @Error+=@@ERROR

--删除发送对象关联关系
DELETE FROM SMSInfo_Template_CardType WHERE smsId=@smsId
SET @Error+=@@ERROR

--重新插入关联关系
IF(@vipCardTypeID<>'0')
	BEGIN
		INSERT INTO SMSInfo_Template_CardType(smsId,vipCardTypeID) SELECT DISTINCT @smsId,a FROM f_split(@vipCardTypeID,',')
		SET @Error+=@@ERROR
	END
	
--返回模版内容和ID	
SET @retcontent = @returncontent
SET @retsmsid = @smsId
SELECT 	@rettemplateid = hyyunsmstemplateid FROM SMSInfo_Template WHERE smsId=@smsId

IF(@@ERROR=0)--保存成功
	BEGIN
		COMMIT TRAN
		RETURN 1
	END
ELSE
	BEGIN
		ROLLBACK TRAN
		RETURN 0
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateVipSMSTemplateDefault]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Gp_UpdateVipSMSTemplateDefault
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	恢复指定会员短信模板信息
-- 时间：	2017-10-17
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Gp_UpdateVipSMSTemplateDefault
(
	@smsId		INT,	--模板ID
	@OpertiorId	VARCHAR(50)='00000'	--操作人
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE smsId=@smsId)
	BEGIN
		RAISERROR('该模板信息已不存在，请确认！',16,1) RETURN
	END
IF EXISTS(SELECT TOP 1 1 FROM SMSInfo_Template WHERE isSysRow=0)
	BEGIN
		RAISERROR('该模板信息不属于系统预制数据不支持恢复功能，请确认！',16,1) RETURN
	END
IF(@smsId=1)
	BEGIN
		UPDATE SMSInfo_Template
		SET 
			tempCode='001',
			tempName='会员储值',
			tempTypeId=1,
			tempContent='尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】充值【@本次储值金额】元，当前储值余额为【@储值余额】元。',
			comment='',
			isPostSend=0
		WHERE smsId=@smsId
			
	END
ELSE IF(@smsId=2)
	BEGIN
		UPDATE SMSInfo_Template
		SET 
			tempCode='002',
			tempName='会员消费（积分）',
			tempTypeId=2,
			tempContent='尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】发生【@本次消费金额】元消费，（本次积分【@本次积分】，当前积分余额为【@积分余额】），感谢您的惠顾！',
			comment='',
			isPostSend=0
		WHERE smsId=@smsId
	END
ELSE IF(@smsId=3)
	BEGIN
		UPDATE SMSInfo_Template
		SET 
			tempCode='003',
			tempName='会员消费（储值）',
			tempTypeId=3,
			tempContent='尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】发生【@本次消费金额】元消费，其中储值消费【@本次储值结算金额】，当前储值余额为【@储值余额】元，如非本人操作，请及时核查。感谢您的惠顾！',
			comment='',
			isPostSend=0
		WHERE smsId=@smsId
	END
ELSE IF(@smsId=4)
	BEGIN
		UPDATE SMSInfo_Template
		SET 
			tempCode='004',
			tempName='会员消费（储值+积分）',
			tempTypeId=4,
			tempContent='尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】发生【@本次消费金额】元消费，（本次积分【@本次积分】，当前积分余额为【@积分余额】），储值消费【@本次储值结算金额】，当前储值余额为【@储值余额】元，如非本人操作，请及时核查。感谢您的惠顾！',
			comment='',
			isPostSend=0
		WHERE smsId=@smsId
	END
ELSE IF(@smsId=5)
	BEGIN
		UPDATE SMSInfo_Template
		SET 
			tempCode='005',
			tempName='会员积分转储值',
			tempTypeId=5,
			tempContent='尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】发生积分转储值业务，本次兑换积分【@兑换积分】，转储值金额为【@转储值金额】，当前积分余额为【@积分余额】，当前储值余额为【@储值余额】元，如非本人操作，请及时核查。感谢您的惠顾！',
			comment='',
			isPostSend=0
		WHERE smsId=@smsId
	END	
ELSE IF(@smsId=6)
	BEGIN
		UPDATE SMSInfo_Template
		SET 
			tempCode='006',
			tempName='会员生日',
			tempTypeId=6,
			tempContent='尊敬的【@持卡人】会员，您好！今天是您的生日，衷心祝福您生日快乐！',
			comment='',
			isPostSend=0,
			Birth_IsAutoSend=0,
			SendDay=0,
			SendTime='09:00:00'
		WHERE smsId=@smsId
	END	
--删除发送对象关联关系
DELETE FROM SMSInfo_Template_CardType WHERE smsId=@smsId
	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_UpdateVisit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_UpdateVisit]
GO







/*
-- 维修品库存期初、库存期初的分布 cqhua 2009-11-04
*/


CREATE      PROCEDURE GP_UpdateVisit
(
 @Billnumberid  numeric(18,0),
 @billdate      Datetime,
 @billcode      varchar(200),
 @etypeid       varchar(50),--操作员ID
 @jbbillnumberid numeric(18,0),
 @btypeid       varchar(50),
 @fullname      varchar(256),
 @linkman      varchar(256),
 @linktel      varchar(256),
 @linkaddr      varchar(256),
 @manyidu      varchar(256),
 @jianyi      varchar(256),
 @inbilldate  datetime,
 @inbillcode  varchar(200)
)
--@encode$--
 AS
SET NOCOUNT ON

if exists(select * from visit where billcode=@Billcode and billnumberid<>@Billnumberid)
	RETURN -1

UPDATE Visit 
SET 
	billdate =@billdate,
	billcode=@billcode,
	etypeid=@etypeid,
	jbbillnumberid=@jbbillnumberid,
	btypeid=@btypeid,
	fullname=@fullname,
	linkman=@linkman,
	linktel=@linktel,
	linkaddr=@linkaddr,
	manyidu=@manyidu,
	jianyi=@jianyi,
	inbilldate=@inbilldate,
	inbillcode=@inbillcode  
WHERE Billnumberid=@Billnumberid

IF @@rowcount =0  OR @@error<>0
	RETURN -2
ELSE
 	RETURN 0







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_UpdateVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_UpdateVoucher]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：鲁大林
	日期：2012-4-6
	描述：凭证字修改
*/

CREATE PROCEDURE [Gp_UpdateVoucher]
(
	
	----------------------------AC_VOUCHER_GROUP(凭证字表)------------------------------------
	@fullname			VARCHAR(8000),				--凭证字名称
	@ismulvoulimit		INT	=0,					--限制多借多贷
	@vgid               VARCHAR(8000),				--凭证字id
	----------------------------AC_VOUCHER_GROUP_DETAIL(凭证字明细表)-------------------------
	@isdebit			VARCHAR(MAX)=NULL,			--借方必有
	@iscredit			VARCHAR(MAX)=NULL,			--贷方必有
	@isdebitorcredit	VARCHAR(MAX)=NULL,			--借或贷必有
	@isnodebit			VARCHAR(MAX)=NULL,			--借方必无
	@isnocredit			VARCHAR(MAX)=NULL,			--贷方必无
	@isnodebitandcredit	VARCHAR(MAX)=NULL			--借或贷必无
)
--@encode$--
AS
SET NOCOUNT ON

--IF NOT EXISTS(SELECT * FROM Ac_Voucher_Group_Detail WHERE Ac_Voucher_Group_Detail.VgId=@vgid)
--BEGIN
--	--------PRINT '不存在记录'+@atypeid
--	RETURN -1
--END
---------------------------------------判断修改的凭证字名称是否为其他的凭证字----------------
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Group WHERE FullName=@fullname AND VgId<>@vgid)
BEGIN
	RETURN -2
END
-----------------------------------修改凭证字表----------------
UPDATE Ac_Voucher_Group
SET 
	FullName=@fullname,
	IsMulVourchLimit=@ismulvoulimit,
	PyCode=NULL
WHERE VgId=@vgid
-------------------------------------修改凭明细表----------------
--DELETE FROM Ac_Voucher_Group_Detail WHERE Ac_Voucher_Group_Detail.VgId=@vgid			--删除记录

--DECLARE  @Tem_Table_isDebit				TABLE(Debit_id VARCHAR(MAX))							--用于接收借方必有id
--DECLARE  @Tem_Table_isCrebit			TABLE(Crebit_id VARCHAR(MAX))							--用于接收贷方必有id
--DECLARE  @Tem_Table_isDebitorCrebit		TABLE(DebitorCrebit_id VARCHAR(MAX))					--用于接收借或贷必有id	
--DECLARE  @Tem_Table_isNoDebit			TABLE(NoDebit_id VARCHAR(MAX))							--用于接收借方必无id
--DECLARE  @Tem_Table_isNOCrebit			TABLE(NoCrebit_id VARCHAR(MAX))						--用于接收贷方必无id
--DECLARE  @Tem_Table_isNoDebitAndCrebit	TABLE(NoDebitAndCrebit_id VARCHAR(MAX))				--用于接收借或贷必无id
	
--INSERT INTO @Tem_Table_isDebit				SELECT * FROM	dbo.f_split(@isdebit,',')			
--INSERT INTO @Tem_Table_isCrebit				SELECT * FROM	dbo.f_split(@iscredit,',')	
--INSERT INTO @Tem_Table_isDebitorCrebit		SELECT * FROM	dbo.f_split(@isdebitorcredit,',')	
--INSERT INTO @Tem_Table_isNoDebit			SELECT * FROM	dbo.f_split(@isnodebit,',')	
--INSERT INTO @Tem_Table_isNOCrebit			SELECT * FROM	dbo.f_split(@isnocredit,',')	
--INSERT INTO @Tem_Table_isNoDebitAndCrebit	SELECT * FROM	dbo.f_split(@isnodebitandcredit,',')	
						
--INSERT INTO [Ac_Voucher_Group_Detail]
--		(
--			[VgId],
--			[ATypeId],
--			[IsDebit],
--			[IsCredit],
--			[IsDebitOrCredit],
--			[IsNoDebit],
--			[IsNoCredit],
--			[IsNoDebitAndCredit]
--		)
--SELECT @vgid,Debit_id,0,1,0,0,0,0  FROM @Tem_Table_isDebit	
	
--INSERT INTO [Ac_Voucher_Group_Detail]
--		(
--			[VgId],
--			[ATypeId],
--			[IsDebit],
--			[IsCredit],
--			[IsDebitOrCredit],
--			[IsNoDebit],
--			[IsNoCredit],
--			[IsNoDebitAndCredit]
--		)
--SELECT @vgid,Crebit_id,1,0,0,0,0,0  FROM @Tem_Table_isCrebit
--INSERT INTO [Ac_Voucher_Group_Detail] 
--		(
--			[VgId],
--			[ATypeId],
--			[IsDebit],
--			[IsCredit],
--			[IsDebitOrCredit],
--			[IsNoDebit],
--			[IsNoCredit],
--			[IsNoDebitAndCredit]
--		)
--SELECT @vgid,DebitorCrebit_id,0,0,1,0,0,0  FROM @Tem_Table_isDebitorCrebit
--INSERT INTO [Ac_Voucher_Group_Detail] 
--		(
--			[VgId],
--			[ATypeId],
--			[IsDebit],
--			[IsCredit],
--			[IsDebitOrCredit],
--			[IsNoDebit],
--			[IsNoCredit],
--			[IsNoDebitAndCredit]
--		)
--SELECT @vgid,NoDebit_id,0,0,0,1,0,0  FROM @Tem_Table_isNoDebit
--INSERT INTO [Ac_Voucher_Group_Detail] 
--		(
--			[VgId],
--			[ATypeId],
--			[IsDebit],
--			[IsCredit],
--			[IsDebitOrCredit],
--			[IsNoDebit],
--			[IsNoCredit],
--			[IsNoDebitAndCredit]
--		)
--SELECT @vgid,NoCrebit_id,0,0,0,0,1,0  FROM @Tem_Table_isNOCrebit
--INSERT INTO [Ac_Voucher_Group_Detail] 
--		(
--			[VgId],
--			[ATypeId],
--			[IsDebit],
--			[IsCredit],
--			[IsDebitOrCredit],
--			[IsNoDebit],
--			[IsNoCredit],
--			[IsNoDebitAndCredit]
--		)
--SELECT @vgid,NoDebitAndCrebit_id,0,0,0,0,0,1  FROM @Tem_Table_isNoDebitAndCrebit


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpdateWdGoodsStocks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpdateWdGoodsStocks]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	颜熙
	Date	:	2017/05/19
	Description	: 插入网店库存数据
*/
CREATE PROCEDURE Gp_UpdateWdGoodsStocks
(
	@WdGoodsStockQty Type_WdGoodsStocks	Readonly	   --网店库存数据	
)
--@encode$--
AS
SET NOCOUNT ON 

--清除网店库存表数据 
TRUNCATE TABLE WDGOODSSTOCKS_QTY
------------插入数据
INSERT INTO dbo.WDGOODSSTOCKS_QTY
        ( KTypeID ,
          CargoID ,
          PTypeID ,
          IsCombinedItem ,
          ItemID ,
          Qty ,
          EnableNum
        )
SELECT KTypeID,CargoID,PTypeID,IsCombinedItem,ItemID,Qty,EnableNum FROM @WdGoodsStockQty W

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_UpdateWdOrderTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_UpdateWdOrderTotal];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO

/*
	作者：颜熙
	日期：2017-02-09
	描述：更改网店单据总价
*/
CREATE PROCEDURE Gp_UpdateWdOrderTotal
	(
      @billnumberid VARCHAR(200) --billnumberid
    )

--@encode$--
AS
    SET NOCOUNT ON;

    BEGIN
      DECLARE @total NUMERIC(24,10)
      SELECT @total = SUM(NTotal) FROM dbo.SaleBill WHERE BillNumberId = @billnumberid
      UPDATE dbo.BillIndex SET totalmoney =@total,NTotalMoney = @total
    END;
GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpGradeV60MonthProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpGradeV60MonthProc]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-05-19
	描述：升级V6.0的历史月结数据
*/
CREATE PROCEDURE Gp_UpGradeV60MonthProc
--@encode$--
AS
SET NOCOUNT ON

DECLARE @StartDate	DATETIME,
		@EndDate	DATETIME,
		@intPeriod	INT
		
--先删除MonthATypeHistory
DELETE FROM MonthATypeHistory		

--月结次数分次写入数据
DECLARE MontProcCursor CURSOR FOR
	SELECT StartDate,EndDate,Period FROM MonthProc WHERE MonthNo <> '本期' ORDER BY Period

OPEN MontProcCursor

FETCH NEXT FROM MontProcCursor INTO @StartDate,@EndDate,@intPeriod

WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE @ATypeId VARCHAR(50),
				@SonNum	 INT	
		
		DECLARE MonthCursor CURSOR FOR
			SELECT TypeId,SonNum FROM AType WHERE Deleted = 0
			
		OPEN MonthCursor
		
		FETCH NEXT FROM MonthCursor INTO @ATypeId,@SonNum
		
		WHILE @@FETCH_STATUS = 0
			BEGIN
				IF @ATypeId = '0000100005'
					INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,BqTotal)
					SELECT	@intPeriod,
							@ATypeId,
							B.STypeId,
							ISNULL(SUM(b.Total),0),
							0
					FROM	ListTable b
					WHERE	b.BillDate <= @EndDate
							AND b.ATypeID IN ('0000100005')
							AND b.Audited = 1
					GROUP BY B.STypeID
				ELSE IF @ATypeId = '0000200001'
						INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,BqTotal)
						SELECT	@intPeriod,
								@ATypeId,
								B.STypeId,
								ISNULL(SUM(b.Total),0),
								0
						FROM	ListTable b
						WHERE	b.BillDate <= @EndDate
								AND b.ATypeID IN ('0000200001')
								AND b.Audited = 1
						GROUP BY B.STypeID					
				ELSE IF @SonNum = 0				
					INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,BqTotal)	
					SELECT	@intPeriod,
							@ATypeId,
							B.STypeId,
							ISNULL(SUM(b.Total),0),
							0						
					FROM	ListTable b
					WHERE	b.BillDate <= @EndDate							
							AND B.AtypeId = @ATypeId
							AND b.Audited = 1
					GROUP BY B.STypeID
						
				IF @ATypeId = '0000100005' OR @ATypeId = '0000200001'
				BEGIN
					IF @ATypeId = '0000100005'
					INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,BqTotal)
					SELECT	@intPeriod,
							@ATypeId,
							B.STypeId,
							ISNULL(SUM(b.ARTotal00),0),
							0
					FROM	BType_ARAPTotal b
					GROUP BY B.STypeID
					
					IF @ATypeId = '0000200001'
					INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,BqTotal)
					SELECT	@intPeriod,
							@ATypeId,
							B.STypeId,
							ISNULL(SUM(b.APTotal00),0),
							0
					FROM	BType_ARAPTotal b
					GROUP BY B.STypeID			
				END	ELSE IF @SonNum = 0
					INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,BqTotal)
					SELECT	@intPeriod,
							@ATypeId,
							C.STypeID,
							ISNULL(SUM(c.Total00),0),
							0
					FROM	AType_Total c					
					WHERE	C.ATypeID = @ATypeId
					GROUP BY C.STypeID
				
				--本期数据
				IF @SonNum = 0
				INSERT INTO MonthATypeHistory(period,ATypeID,STypeID,Total,BqTotal)
				SELECT	@intPeriod,
						@ATypeID,
						b.STypeID,
						0,
						ISNULL(SUM(b.Total),0)
				FROM	ListTable b
				WHERE	b.BillDate >= @StartDate
						AND b.BillDate <= @EndDate						
						AND B.AtypeId = @ATypeId
						AND b.Audited = 1
				GROUP BY B.STypeID								
				
				FETCH NEXT FROM MonthCursor INTO @ATypeId,@SonNum
			END
			
		CLOSE MonthCursor
		DEALLOCATE MonthCursor
		
		FETCH NEXT FROM MontProcCursor INTO @StartDate,@EndDate,@intPeriod
	END
	
CLOSE MontProcCursor
DEALLOCATE MontProcCursor	

-- 删除都为0的数据
DELETE FROM MonthATypeHistory WHERE Total = 0 AND BqTotal = 0 AND period = @intPeriod

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_UpSerialBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_UpSerialBill]
GO














/****** Object:  Stored Procedure dbo.Gp_UpSerialBill    Script Date: 2002-6-20 10:14:51 ******/

/*
   过帐前，更据新生成的单据编号替换临时的单据编号，并做一些检查工作
   参数： @BillNumberID    单据的新单据编号
         @nBillID         序列号的临时编号
*/
CREATE  PROCEDURE Gp_UpSerialBill
( 
 @BillNumberID [numeric](18, 0),
 @nBillID varchar(50)
)
--@encode$--
AS
 Set NoCount On
 
 -- 替换单据编号
 Update [gp_inoutPtypeSerial]
 Set [BillNumberid]=@BillNumberID
 Where [BillNumberid]=@nBillID

--严格检查序列号与仓库、商品的一一对应情况Start
--   Select 

--严格检查序列号与仓库、商品的一一对应情况End

 -- 根据不同的单据类型做动作
 Declare @BillType   int
 Declare @K          varchar(25)
 Declare @K2         varchar(25)
 Select @BillType=BillType,@K=KtypeID,@K2=KtypeID2 From BillIndex Where BillNumberId=@BillNumberID

 -- 同价调拨
 if @BillType=17
    Update [gp_inoutPtypeSerial]
    Set [InKtypeID]=@K2,
        [OutKtyeID]=@K
    Where [BillNumberid]=CAST(@BillNumberID AS varchar(50))
 -- 变价调拨
 if @BillType=21    
    Update [gp_inoutPtypeSerial]
    Set [InKtypeID]=@K2,
        [OutKtyeID]=@K
    Where [BillNumberid]=CAST(@BillNumberID AS varchar(50))
 -- 商品拆装单









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO
	
IF EXISTS ( SELECT  1
            FROM    SysObjects
            WHERE   ID = OBJECT_ID(N'GP_UptPayKey', N'P') )
    BEGIN
        DROP PROC GP_UptPayKey
    END
GO
CREATE PROC GP_UptPayKey
(
	@KeyWord		VARCHAR(MAx)
)
AS

		UPDATE PayConfigInfo SET KeyWord=@KeyWord WHERE PayType = 1
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (
	SELECT * 
	FROM dbo.sysobjects 
	WHERE id = OBJECT_ID(N'[dbo].[GP_UserRange_DataUpdate_nIdToNTypeid]') 
		AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
	DROP PROCEDURE [dbo].[GP_UserRange_DataUpdate_nIdToNTypeid]
GO
/*
多级权限Atype_l升级处理, nid转换为ntypeid
*/
CREATE PROCEDURE [GP_UserRange_DataUpdate_nIdToNTypeid]
--@encode$--
AS 
BEGIN

	CREATE TABLE #Atype_l(
		etypeid varchar(100) ,
		typeid varchar(200) ,
		flag char(1) ,
		type char(1) ,
	) 
	--原始数据放入临时表
	INSERT INTO #Atype_l SELECT * FROM atype_l

	--删除atype_l中的所有nid有关列
	DELETE FROM atype_l WHERE typeid <> '0000'


	-- 更新nid到ntypeid
	declare @userid varchar(50), @nid int, @type int
	DECLARE UserRange_Update_Cursor CURSOR FOR
		SELECT etypeid,typeid , type FROM #Atype_l where flag = 1 and typeid <> '0000'
		
	OPEN UserRange_Update_Cursor
	FETCH NEXT FROM UserRange_Update_Cursor 
	INTO @userid, @nid, @type
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @type = @type + 5
		EXEC GP_UserRange_Insert @UserID=@userid,@Type=@type,@TypeIDs=@nid 
		FETCH NEXT FROM UserRange_Update_Cursor INTO @userid, @nid, @type
	END
	CLOSE UserRange_Update_Cursor
	DEALLOCATE UserRange_Update_Cursor
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_UserRange_DefaultSetting]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_UserRange_DefaultSetting]
GO
/*
新增操作员后给所有操作员添加默认权限
add by 李海洋
date: 2012.04.06
*/
CREATE PROCEDURE GP_UserRange_DefaultSetting
--@encode$--
AS -- aTypt_l
    INSERT  INTO AType_l
            SELECT  *
            FROM    ( SELECT    etypeid ,
                                MangerATypeID ,
                                1 AS flag ,
                                '0' AS atype
                      FROM      dbo.loginuser
                      WHERE     MangerATypeID <> -99999
                      UNION ALL
                      SELECT    etypeid ,
                                MangerExpense ,
                                1 AS flag ,
                                '1' AS atype
                      FROM      dbo.loginuser L
                      WHERE     MangerExpense <> -99999
                      UNION ALL
                      SELECT    etypeid ,
                                MangerIncome ,
                                1 AS flag ,
                                '2' AS atype
                      FROM      dbo.loginuser L
                      WHERE     MangerIncome <> -99999
                      UNION ALL
                      SELECT    etypeid ,
                                MangerCpaital ,
                                1 AS flag ,
                                '3' AS atype
                      FROM      dbo.loginuser L
                      WHERE     MangerCpaital <> -99999
                      UNION ALL
                      SELECT    etypeid ,
                                MangerCpaital ,
                                1 AS flag ,
                                '4' AS atype
                      FROM      dbo.loginuser L
                      WHERE     MangerOtherCpaital <> -99999
                      UNION ALL
                      SELECT    etypeid ,
                                MangerCpaital ,
                                1 AS flag ,
                                '5' AS atype
                      FROM      dbo.loginuser L
                      WHERE     MangerLiabilities <> -99999
                      UNION ALL
                      SELECT    etypeid ,
                                MangerCpaital ,
                                1 AS flag ,
                                '6' AS atype
                      FROM      dbo.loginuser L
                      WHERE     MangerRevenue <> -99999
                      UNION ALL
                      SELECT    etypeid ,
                                MangerCpaital ,
                                1 AS flag ,
                                '7' AS atype
                      FROM      dbo.loginuser L
                      WHERE     MangerPay <> -99999
                      UNION ALL
                      SELECT    etypeid ,
                                MangerCpaital ,
                                1 AS flag ,
                                '8' AS atype
                      FROM      dbo.loginuser L
                      WHERE     MangerOwnerEquity <> -99999
                      
                    ) L
            WHERE   NOT EXISTS ( SELECT *
                                 FROM   AType_l A
                                 WHERE  A.etypeid = L.etypeid
                                        AND A.type = L.atype )
-- btype_l

    INSERT  INTO btype_l
            SELECT  L.etypeid ,
                    L.MangerBTypeID ,
                    1
            FROM    dbo.loginuser L
            WHERE   L.MangerBTypeID <> -99999
                    AND NOT EXISTS ( SELECT 1
                                     FROM   btype_l B
                                     WHERE  B.etypeid = L.etypeid
                                            AND B.typeid = L.MangerBTypeID )
    INSERT  INTO btype_l
            SELECT  L.etypeid ,
                    L.MangerBTypeID2 ,
                    1
            FROM    dbo.loginuser L
            WHERE   L.MangerBTypeID <> -99999
                    AND NOT EXISTS ( SELECT 1
                                     FROM   btype_l B
                                     WHERE  B.etypeid = L.etypeid
                                            AND B.typeid = L.MangerBTypeID2 )

-- PType_L
    INSERT  INTO PType_L
            SELECT  L.etypeid ,
                    L.MangerPTypeID ,
                    1 AS flag
            FROM    dbo.loginuser L
            WHERE   L.MangerPTypeID <> -99999
                    AND NOT EXISTS ( SELECT 1
                                     FROM   PType_L P
                                     WHERE  P.etypeid = L.etypeid
                                            AND P.typeid = L.MangerPTypeID )

-- ktype_l
    INSERT  INTO ktype_l
            SELECT  L.etypeid ,
                    L.MangerKTypeID ,
                    1 AS flag
            FROM    dbo.loginuser L
            WHERE   L.MangerKTypeID <> -99999
                    AND NOT EXISTS ( SELECT 1
                                     FROM   ktype_l K
                                     WHERE  K.etypeid = L.etypeid
                                            AND K.typeid = L.MangerKTypeID )
				
--EType_l
    INSERT  INTO EType_l
            SELECT  L.etypeid ,
                    L.MangerETypeID ,
                    1 AS flag
            FROM    dbo.loginuser L
            WHERE   L.MangerETypeID <> -99999
                    AND NOT EXISTS ( SELECT 1
                                     FROM   EType_l E
                                     WHERE  E.etypeid = L.etypeid
                                            AND E.typeid = L.MangerETypeID )
				
--DType_l
    INSERT  INTO DType_L
            SELECT  L.etypeid ,
                    L.MangerDTypeID ,
                    1 AS flag
            FROM    dbo.loginuser L
            WHERE   L.MangerDTypeID <> -99999
                    AND NOT EXISTS ( SELECT 1
                                     FROM   DType_L D
                                     WHERE  D.etypeid = L.etypeid
                                            AND D.typeid = L.MangerDTypeID )
--SType_L
    INSERT  INTO SType_L
            SELECT  L.etypeid ,
                    L.MangerSTypeID ,
                    1 AS flag
            FROM    dbo.loginuser L
            WHERE   L.MangerSTypeID <> -99999
                    AND NOT EXISTS ( SELECT 1
                                     FROM   SType_L S
                                     WHERE  S.etypeid = L.etypeid
                                            AND S.typeid = L.MangerSTypeID )

    RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_UserRange_Del]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_UserRange_Del]
GO


/*
操作员多级权限范围设置 - 删除
*/


/*
	--
	--modify by 李海洋, 
	--date: 2012-04-05
	--description: @TypeID 为'00000'(当前type所有权限), 添加清理相应的[x]type_l表
*/
CREATE    PROCEDURE GP_UserRange_Del
    (
      @UserID VARCHAR(50) ,
      @Type INT ,
      @TypeID VARCHAR(200),
      @IsUserGroupLimit INT
    )
--@encode$--
AS 
    SET NOCOUNT ON 

    DECLARE @ManTypeIDName VARCHAR(50) ,
        @TableName VARCHAR(50) ,
        @AllManID VARCHAR(50) ,
        @SQL VARCHAR(2000) ,
        @atypeType CHAR(1) ,
        @SchemeType VARCHAR(20)		--基本信息样式名称，如rmetype则赋值是etype
		
    IF @Type = 0
        OR @Type = 1 
        BEGIN
            SET @TableName = 'BType_L'
            IF @Type = 0 
                BEGIN
                    SET @ManTypeIDName = 'MangerBTypeID'
                    SET @AllManID = '00001'
                END
            ELSE 
                BEGIN
                    SET @ManTypeIDName = 'MangerBTypeID2'
                    SET @AllManID = '00002'
                END
            SET @SchemeType = 'btype'
        END
    ELSE 
        IF @Type = 2 
            BEGIN
                SET @TableName = 'PType_L'
                SET @ManTypeIDName = 'MangerPTypeID'
                SET @AllManID = '00000'
                SET @SchemeType = 'ptype'
            END
        ELSE 
            IF @Type = 3 
                BEGIN
                    SET @TableName = 'KType_L'
                    SET @ManTypeIDName = 'MangerKTypeID'
                    SET @AllManID = '00000'
                    SET @SchemeType = 'ktype'
                END
            ELSE 
                IF @Type = 4 
                    BEGIN
                        SET @TableName = 'EType_L'
                        SET @ManTypeIDName = 'MangerETypeID'
                        SET @AllManID = '00001'
                        SET @SchemeType = 'etype'
                    END
                ELSE 
                    IF @Type = 9 
                        BEGIN
                            SET @TableName = 'DType_L'
                            SET @ManTypeIDName = 'MangerDTypeID'
                            SET @AllManID = '00000'
                            SET @SchemeType = 'dtype'
                        END
                    ELSE 
                        IF @Type = 10 
                            BEGIN
                                SET @TableName = 'SType_L'
                                SET @ManTypeIDName = 'MangerSTypeID'
                                SET @AllManID = '00000'
                                SET @SchemeType = 'stype'
                            END
                        ELSE 
                            BEGIN
                                SET @TableName = 'AType_L'
                                IF @Type = 5 
                                    BEGIN
                                        SET @ManTypeIDName = 'MangerATypeID'
                                        SET @atypeType = '0'
                                        SET @SchemeType = 'atype'
                                    END
                                ELSE 
                                    IF @Type = 6 
                                        BEGIN
                                            SET @ManTypeIDName = 'MangerExpense'
                                            SET @atypeType = '1'
                                            SET @SchemeType = 'fytype'
                                        END
                                    ELSE 
                                        IF @Type = 7 
                                            BEGIN
                                                SET @ManTypeIDName = 'MangerIncome'
                                                SET @atypeType = '2'
                                                SET @SchemeType = 'srtype'
                                            END
                                        ELSE IF @Type=8
                                            BEGIN
                                                SET @ManTypeIDName = 'MangerCpaital'
                                                SET @atypeType = '3'
                                                SET @SchemeType = 'gdzctype'
                                            END
                                        ELSE IF(@Type=11)
											BEGIN
                                                SET @ManTypeIDName = 'MangerOtherCpaital'
                                                SET @atypeType = '4'
                                                SET @SchemeType = 'OtherCpaitalType'
											END
										ELSE IF(@Type=12)
											BEGIN
                                                SET @ManTypeIDName = 'MangerLiabilities'
                                                SET @atypeType = '5'
                                                SET @SchemeType = 'LiabilitiesType'
											END
										ELSE IF(@Type=13)
											BEGIN
                                                SET @ManTypeIDName = 'MangerRevenue'
                                                SET @atypeType = '6'
                                                SET @SchemeType = 'RevenueType'
											END
										ELSE IF(@Type=14)
											BEGIN
                                                SET @ManTypeIDName = 'MangerPay'
                                                SET @atypeType = '7'
                                                SET @SchemeType = 'PayType'
											END
										ELSE IF(@Type=15)
											BEGIN
                                                SET @ManTypeIDName = 'MangerOwnerEquity'
                                                SET @atypeType = '8'
                                                SET @SchemeType = 'OwnerEquityType'
											END
                                     
                                SET @AllManID = '0000'	
                            END

--------
	
	DECLARE @LimitTable VARCHAR(100) = 'LoginUser'
	--角色设置时，表前面添加了Ug
	IF @IsUserGroupLimit = 1
	BEGIN
		SET @TableName = 'Ug' + @TableName
		SET @LimitTable = 'UserGroupLimit'
	END

    IF @TypeID = '00000' 
        BEGIN
	--清理LoginUser
            SET @SQL = '
		IF EXISTS(SELECT TOP 1 1 FROM '+@LimitTable+' WHERE ETypeID=''' + @UserID
                + ''' AND ' + @ManTypeIDName + '=''' + @AllManID + ''')
			UPDATE '+@LimitTable+' SET ' + @ManTypeIDName
                + ' = ''-99999'' WHERE ETypeID = ''' + @UserID + ''''
	--清理相应的type_l
	--add by 李海洋, 
	--date: 2012-04-05
            IF @TableName = 'AType_L' OR  @TableName = 'UgAType_L'  
                SET @SQL = @SQL + '
		DELETE FROM ' + @TableName + '
		WHERE ETypeID = ''' + @UserID + '''
		AND TypeId = ''' + @AllManID + '''
		AND type = ' + @atypeType
            ELSE 
                SET @SQL = @SQL + '
		DELETE FROM ' + @TableName + '
		WHERE ETypeID = ''' + @UserID + '''
		AND TypeId = ''' + @AllManID + ''''

            EXEC(@SQL)
        END
--删除叶子节点
    ELSE 
        BEGIN
            SET @SQL = 'DELETE FROM ' + @TableName + ' 
							WHERE ETypeID = ''' + @UserID + ''' 
							AND TypeID = ''' + @TypeID + ''' 
							AND Flag = ''1'''
            EXEC(@SQL)
        END


-- 清理相应父节点
    DECLARE @i INT ,
        @tempTypeID VARCHAR(50)
    SET @i = 1
    WHILE @i < LEN(@TypeID) / 5 
        BEGIN
            SET @tempTypeID = LEFT(@TypeID, @i * 5)
            IF @Type IN ( 5, 6, 7, 8,11,12,13,14,15 ) 
            BEGIN
				IF @IsUserGroupLimit = 1
				BEGIN
					 SET @SQL = '
						IF NOT EXISTS(SELECT TOP 1 1 FROM UgAType_L WHERE ETypeID=''' + @UserID
									+ ''' AND TypeID LIKE ''' + @tempTypeID
									+ '%'' AND Flag=''1'' AND Type=''' + @atypeType + ''')
							DELETE FROM UgAType_L WHERE ETypeID=''' + @UserID + ''' AND TypeID='''
									+ @tempTypeID + ''' AND Flag=''0'' AND Type='''
									+ @atypeType + ''''
				END
			
            END
            ELSE  
                SET @SQL = '
		IF NOT EXISTS(SELECT TOP 1 1 FROM ' + @TableName + ' WHERE ETypeID='''
                    + @UserID + ''' AND TypeID LIKE ''' + @tempTypeID
                    + '%'' AND Flag=''1'')
			DELETE FROM ' + @TableName + ' WHERE ETypeID=''' + @UserID
                    + ''' AND TypeID=''' + @tempTypeID + ''' AND Flag=''0'''
            EXEC(@SQL)
            SET @i = @i + 1
        END

--处理用户查询解决方案
    IF @SchemeType = 'btype' 
        BEGIN
            SET @SQL = 'EXEC Gp_ReplaceSchemeDetailValue ''' + @TypeID
                + ''',''AND SchemeId IN (SELECT D.SchemeId FROM SchemeDetail D INNER JOIN Scheme S ON D.SchemeId = S.SchemeId WHERE s.ETypeID = '''''
                + @UserID + '''''' + ') AND (BaseType LIKE ''''%'
                + @SchemeType
                + ''''' OR BaseType LIKE ''''%jtype'''' OR BaseType LIKE ''''%gtype'''')'''
        END
    ELSE 
        BEGIN
            SET @SQL = 'EXEC Gp_ReplaceSchemeDetailValue ''' + @TypeID
                + ''',''AND SchemeId IN (SELECT D.SchemeId FROM SchemeDetail D INNER JOIN Scheme S ON D.SchemeId = S.SchemeId WHERE s.ETypeID = '''''
                + @UserID + '''''' + ') AND BaseType LIKE ''''%' + @SchemeType
                + ''''''''
        END

----用户查询解决方案全部权限到部分权限的时候把该内容清除
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @UserID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT

    IF ( @MBtypeid = '-99999'
         OR @MBtypeid2 = '-99999'
         OR @MPtypeid = '-99999'
         OR @MKtypeid = '-99999'
         OR @MEtypeid = '-99999'
         OR @MAtypeid = '-99999'
         OR @MExpense = '-99999'
         OR @MIncome = '-99999'
         OR @MCapital = '-99999'
         OR @MDtypeid = '-99999'
         OR @MStypeid = '-99999'
       ) 
        BEGIN
            DECLARE @sql1 VARCHAR(MAX)
            SET @sql1 = 'EXEC Gp_ReplaceSchemeDetailValue '''', ''AND DataField=''''etypeid'''' AND (SELECT	CHARINDEX('''''
                + @UserID + ''''',DataValue)) <> 0'','''','''''
            EXEC(@sql1)
	--SELECT nId,DataValue FROM	SchemeDetail WHERE	DataField=''etypeid'' AND ControlType = ''XWSelectorEdit'' AND ISNULL(DataValue,'''')<>'''' AND (SELECT	CHARINDEX('''+ @UserID +''',''DataValue'')) = 1	
        END

--PRINT(@SQL)
    EXEC(@SQL)

--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'
    RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
	SELECT * 
	FROM dbo.sysobjects 
	WHERE id = OBJECT_ID(N'[dbo].[GP_UserRange_Insert]') 
		AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
	DROP PROCEDURE [dbo].[GP_UserRange_Insert]
GO
/*
操作员多级权限范围设置 - 新添
*/
CREATE PROCEDURE GP_UserRange_Insert (
	 @UserID	VARCHAR(50)
	,@Type		INT
	,@TypeIDs	VARCHAR(MAX)
	,@IsUserGroupLimit INT
)
--@encode$--
AS 
SET NOCOUNT ON 

DECLARE 
	 @ManTypeIDName VARCHAR(50) -- loginUser 中的ManagerTypeID字段 为非-99999时表示拥有该type的所有权限
	,@TableName VARCHAR(50)			-- 对应的_l表, 每个type对应一个type_l表
	,@AllManID VARCHAR(50)			-- loginUser 中的ManagerTypeID字段为非-99999时的值
	,@Typeflag VARCHAR(50)			-- Atype_l子类型
	,@SQL VARCHAR(2000)					
	,@atypeType CHAR(1)
	
-- 分类选择权限表
-- BType
IF @Type IN (0,1)
BEGIN
	SET @TableName = 'BType_L'
	IF @Type = 0
	BEGIN
		SET @ManTypeIDName = 'MangerBTypeID'
		SET @AllManID = '00001'
		SET @Typeflag = '00001'
	END
	ELSE
	BEGIN
		SET @ManTypeIDName = 'MangerBTypeID2'
		SET @AllManID = '00002'
		SET @Typeflag = '00002'
	END
END
-- PType
ELSE IF @Type = 2
BEGIN
	SET @TableName = 'PType_L'
	SET @ManTypeIDName = 'MangerPTypeID'
	SET @AllManID = '00000'
	SET @Typeflag = '00000'
END
-- KType
ELSE IF @Type = 3
BEGIN
	SET @TableName = 'KType_L'
	SET @ManTypeIDName = 'MangerKTypeID'
	SET @AllManID = '00000'
	SET @Typeflag = '00000'
END
-- EType
ELSE IF @Type = 4
BEGIN
	SET @TableName = 'EType_L'
	SET @ManTypeIDName = 'MangerETypeID'
	SET @AllManID = '00001'
	SET @Typeflag = '00000'
END
-- DType
ELSE IF @Type = 9
	BEGIN
		SET @TableName = 'DType_L'
		SET @ManTypeIDName = 'MangerDTypeID'
		SET @AllManID = '00000'
	SET @Typeflag = '00000'
	END
--SType
ELSE IF @Type = 10
BEGIN
	SET @TableName = 'SType_L'
	SET @ManTypeIDName = 'MangerSTypeID'
	SET @AllManID = '00000'
	SET @Typeflag = '00000'
END
-- others
ELSE
BEGIN
	SET @TableName = 'AType_L'
	IF @Type = 5
	BEGIN
		SET @ManTypeIDName = 'MangerATypeID' --银行账户
		SET @atypeType = '0'
	END
	ELSE IF @Type = 6
	BEGIN
		SET @ManTypeIDName = 'MangerExpense' --费用
		SET @atypeType = '1'
	END
	ELSE IF @Type = 7
	BEGIN
		SET @ManTypeIDName = 'MangerIncome'  --收入
		SET @atypeType = '2'
	END
	ELSE IF @Type=8
	BEGIN
		SET @ManTypeIDName = 'MangerCpaital' --固定资产
		SET @atypeType = '3'
	END
	ELSE IF(@Type=11)
		BEGIN
		SET @ManTypeIDName = 'MangerOtherCpaital'  --其他资产
		SET @atypeType = '4'
		END
	ELSE IF(@Type=12)
		BEGIN
		SET @ManTypeIDName = 'MangerLiabilities'  --负债
		SET @atypeType = '5'
		END
	ELSE IF(@Type=13)
		BEGIN
		SET @ManTypeIDName = 'MangerRevenue'  --全部收入
		SET @atypeType = '6'
		END
	ELSE IF(@Type=14)
		BEGIN
		SET @ManTypeIDName = 'MangerPay'  --支出
		SET @atypeType = '7'
		END
	ELSE IF(@Type=15)
		BEGIN
		SET @ManTypeIDName = 'MangerOwnerEquity'  --所有者权益
		SET @atypeType = '8'
		END
	
	SET @AllManID = '0000'
	SET @Typeflag = '0000'
END


DECLARE @LimitTable VARCHAR(100) = 'LoginUser'
	--角色设置时，表前面添加了Ug
IF @IsUserGroupLimit = 1
BEGIN
	SET @TableName = 'Ug' + @TableName
	SET @LimitTable = 'UserGroupLimit'
END

-- 修改LoginUser表
--@TypeIDs 为00000表示所有当前type的权限
--'-99999'表示并非拥有所有权限
IF @TypeIDs <> '00000' 
	SET @AllManID = '-99999'

IF @IsUserGroupLimit = 1
BEGIN
	IF NOT EXISTS(SELECT * FROM UserGroupLimit WHERE EtypeID = @UserID)
		INSERT UserGroupLimit(EtypeID) VALUES(@UserID)
	
	SET @SQL = 'UPDATE UserGroupLimit
				SET ' + @ManTypeIDName + ' = ''' + @AllManID + '''
				WHERE ETypeID = ''' + @UserID + ''''
END
ELSE
BEGIN
	SET @SQL = 'UPDATE LoginUser
				SET ' + @ManTypeIDName + ' = ''' + @AllManID + '''
				WHERE ETypeID = ''' + @UserID + ''''
END

--PRINT(@SQL)
EXEC(@SQL)


-- 拥有当前类型所有权限时, 清空表中所有用户相关项
-- LoginUser的相应Manger[x]type字段维护当前是否拥有当前类型的所有权限
-- [x]type_l表维护子权限


--由于去掉了多级权限细分, 故不需要在在_l表添加为全部权限时的4个值
IF @TypeIDs = '00000'
BEGIN
	SET @SQL = 'DELETE FROM ' + @TableName + ' WHERE ETypeID = ''' + @UserID + ''''
	IF @Type = 0 
		SET @SQL = @SQL + ' AND TypeID LIKE ''00001%'''
	ELSE IF @Type = 1 
		SET @SQL = @SQL + ' AND TypeID LIKE ''00002%'''
	ELSE IF @Type = 5 
		SET @SQL = @SQL + ' AND ((TypeID LIKE ''00001%'' OR TypeID = 0000) AND Type=''0'' OR  (TypeID=''0000200006'' AND Type=''0''))' 
	ELSE IF @Type = 6 
		SET @SQL = @SQL + ' AND (TypeID LIKE ''00004%'' OR TypeID = 0000) AND Type=''1'''
	ELSE IF @Type = 7 
		SET @SQL = @SQL + ' AND (TypeID LIKE ''00003%'' OR TypeID = 0000) AND Type=''2'''
	ELSE IF @Type = 8 
		SET @SQL = @SQL + ' AND (TypeID LIKE ''00001%'' OR TypeID = 0000) AND Type=''3'''		
	ELSE IF @Type = 11 --其他资产 不包括'固定资产'     '银行账户,现金' '预收预付资金'
		SET @SQL = @SQL + ' AND ((TypeID LIKE ''00001%'' AND TypeID NOT LIKE ''0000100002%'' AND TypeID NOT LIKE ''0000100004%'' AND TypeID<>''0000100003'' ) OR TypeID = 0000) AND Type=''4'''
	ELSE IF @Type = 12 --负债 '预收预付资金'
		SET @SQL = @SQL + ' AND (TypeID LIKE ''00002%'' OR TypeID = 0000)  AND Type=''5'''
	ELSE IF @Type = 13 --收入不包括'其他收入'
		SET @SQL = @SQL + ' AND ((TypeID LIKE ''00003%'' AND TypeID NOT LIKE ''0000300003%'') OR TypeID = 0000) AND Type=''6'''
	ELSE IF @Type = 14 --支出 不包括'费用合计'
		SET @SQL = @SQL + ' AND ((TypeID LIKE ''00004%'' AND TypeID NOT LIKE ''0000400003%'') OR TypeID = 0000) AND Type=''7'''
	ELSE IF @Type = 15 --所有者权益
		SET @SQL = @SQL + ' AND (TypeID LIKE ''00005%''  OR TypeID = 0000) AND Type=''8'''
	
	
	--PRINT(@SQL)
	EXEC(@SQL)
	--由于去掉了多级权限细分, 故不需要在在_l表添加为全部权限时的4个值
	--2012-09-12但由于9.0中已经有人在用_l表的字段, 故还是加回来
	IF @TableName = 'AType_L' OR @TableName = 'UgAType_L'
		SET @SQL = 'INSERT INTO ' + @TableName + '
								VALUES (''' + @UserID + '''
								, ''' + @AllManID + '''
								, ''1''
								, ''' + @atypeType	 + ''')'
	ELSE
		SET @SQL = 'INSERT INTO ' + @TableName + '
								VALUES (''' + @UserID + '''
								, ''' + @AllManID + '''
								, ''1'')'
	--PRINT(@SQL)
	EXEC(@SQL)
	RETURN 0
END
--删除为全部的节点
ELSE
BEGIN
	SET @SQL = 'DELETE FROM ' + @TableName + ' WHERE ETypeID = ''' + @UserID + ''''
	IF @Type = 5 
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''0'''
	ELSE IF @Type = 6 
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''1'''
	ELSE IF @Type = 7 
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''2'''
	ELSE IF @Type = 8 
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''3'''
	ELSE IF @Type = 11--其他资产 
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''4'''
	ELSE IF @Type = 12 --负债
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''5'''
	ELSE IF @Type = 13 --收入不包括'其他收入
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''6'''
	ELSE IF @Type = 14 --支出 不包括'费用合计'
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''7'''
	ELSE IF @Type = 15 --所有者权益'
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''' AND Type=''8'''
	ELSE 
		SET @SQL = @SQL + ' AND TypeID = ''' + @Typeflag + ''''
	--PRINT(@SQL)
	EXEC(@SQL)
END

-- 临时处理 清理atype_l中的某类的所有数据(去掉)
	-- 删除所有的child, Atype_L单独处理
--IF @TableName = 'AType_L'
--BEGIN
	--SET @SQL = 'DELETE FROM ' + @TableName + ' 
	--						WHERE ETypeID = ''' + @UserID  + '''' +   (' AND Type = ''' + @atypeType + '''' )
--	EXEC(@SQL)
--END
--------

CREATE TABLE #TYPEIDS
(
	typeid VARCHAR(50)
)
--项目分类在9.0 Sp6中做特殊处理
	IF @TableName = 'AType_L' OR @TableName = 'UgAType_L'
	INSERT INTO #Typeids SELECT Ac.nTypeId a FROM f_split(@TypeIDs, ',') A 
		INNER JOIN Ac_Items Ac on ac.nId = A.a
	ELSE
	INSERT INTO #Typeids SELECT a FROM f_split(@TypeIDs, ',')

DECLARE 
	 @TypeID VARCHAR(200)
	,@tempTypeID VARCHAR(200)
	,@i INT
	,@Flag CHAR(1)
	
DECLARE @NCHECKSQL		NVARCHAR(MAX),
		@Return			INT
	
DECLARE UserRange_Cursor CURSOR FOR
	SELECT * FROM #Typeids
	
OPEN UserRange_Cursor

FETCH NEXT FROM UserRange_Cursor INTO @TypeID

WHILE @@FETCH_STATUS = 0
BEGIN
	IF	( @Type IN (0, 1, 4)			AND LEN(@TypeID) < 10)
		OR( @Type IN (2, 3, 9, 10)	AND LEN(@TypeID) < 5 )
		OR( @Type IN (6, 7, 8)			AND LEN(@TypeID) < 15)
		OR( @Type = 5								AND LEN(@TypeID) < 10)
		OR (@Type IN (11,12,13,14,15) AND LEN(@TypeID) < 10)
	BEGIN
		CLOSE UserRange_Cursor
		DEALLOCATE UserRange_Cursor
		RETURN -3
	END
	--判断TypeID是否 已经在表中, 或者他的直接父辈是否在表中	
	SET @NCHECKSQL = ''
	SET @NCHECKSQL = '
				IF EXISTS(	SELECT TOP 1 1 
							FROM ' + @TableName+'
							WHERE ETypeID = ''' + @UserID + ''' AND ((TypeID = ''' + @TypeID + ''' AND Flag = ''1'') 
								OR (TypeID LIKE '''
													+ CASE WHEN @TableName = 'BType_L' 
																	OR @TableName='UgBType_L'
																	OR @TableName = 'EType_L' 
																	OR @TableName = 'UgEType_L' THEN LEFT(@TypeID, 10)
															WHEN @TableName = 'PType_L' 
																	OR @TableName = 'UgPType_L'
																	OR @TableName = 'KType_L' 
																	OR @TableName = 'UgKType_L' 
																    OR @TableName = 'SType_L' 
																    OR @TableName = 'UgSType_L' 
																    OR @TableName = 'DType_L' 
																    OR @TableName = 'UgDType_L' THEN LEFT(@TypeID,5)
														END + '%'' 
									AND LEN(TypeID) < LEN(''' + @TypeID + ''') ' + --排除同辈
								 'AND LEFT(''' + @TypeID + ''', LEN(TypeID)) = TypeID ' + --排除间接父辈
								 'AND Flag=''1''))
				)
					SET @Return = 1
				ELSE
					SET @Return = 0 ' --父辈为之前的选择节点
	
	EXEC sp_executesql @NCHECKSQL,N'@Return INT OUT',@Return OUT
		
	IF @Return = 1 
	BEGIN
		CLOSE UserRange_Cursor
		DEALLOCATE UserRange_Cursor
		RETURN -2
	END
	-- 删除所有的child
	SET @SQL = 'DELETE FROM '+ @TableName+ ' 
							WHERE ETypeID = ''' + @UserID + ''' AND TypeID LIKE ''' + @TypeID + '%'''
	EXEC(@SQL)

	SET @i = 1
	SET @Flag = '0'
	-- 层次循环
	WHILE @i <= LEN(@TypeID) / 5
	BEGIN
		IF @i = LEN(@TypeID) / 5 
			SET @Flag = '1'
		-- 当前层次typeID
		SET @tempTypeID = LEFT(@TypeID, @i * 5)
		
		-- AType_l
		IF @Type IN (5, 6, 7, 8,11,12,13,14,15)
			BEGIN
					IF @IsUserGroupLimit = 1
					BEGIN
						IF NOT EXISTS( SELECT TOP 1 1 FROM UgAType_L WHERE ETypeID= @UserID AND TypeID =  @tempTypeID AND Type =  @atypeType) 
							INSERT INTO UgAType_L (ETypeID, TypeID, Flag, Type) VALUES ( @UserID,@tempTypeID  ,@Flag ,@atypeType )
						ELSE
							UPDATE UgAType_L SET flag = '0' WHERE ETypeID = @UserID AND TypeID = @tempTypeID AND Type =@atypeType 
					END
					ELSE
					BEGIN
						IF NOT EXISTS( SELECT TOP 1 1 FROM AType_L WHERE ETypeID= @UserID AND TypeID =  @tempTypeID AND Type =  @atypeType) 
							INSERT INTO AType_L (ETypeID, TypeID, Flag, Type) VALUES ( @UserID,@tempTypeID  ,@Flag ,@atypeType )
						ELSE
							UPDATE AType_L SET flag = '0' WHERE ETypeID = @UserID AND TypeID = @tempTypeID AND Type =@atypeType 
					END
			END
		ELSE
			BEGIN
					SET @SQL = 
					'IF NOT EXISTS( SELECT TOP 1 1 FROM ' + @TableName + ' WHERE ETypeID=''' + @UserID + ''' 
							AND TypeID=''' + @tempTypeID + '''
					)
						INSERT INTO ' + @TableName + ' (ETypeID, TypeID, Flag) 
						VALUES (''' + @UserID + ''',''' + @tempTypeID + ''',''' + @Flag + ''')
					ELSE
						UPDATE '+ @TableName + ' SET flag = ''0''
						WHERE ETypeID = ''' + @UserID + ''' AND TypeID = ''' + @tempTypeID + ''''
			EXEC(@SQL)
			END
		--PRINT(@SQL)
		
		SET @i = @i + 1
		SET @Flag = '0'
	END

	FETCH NEXT FROM UserRange_Cursor INTO @TypeID
END
CLOSE UserRange_Cursor
DEALLOCATE UserRange_Cursor

-- 超过500条设置记录，不允许
DECLARE 
	@numCount INT
	,@nSQL NVARCHAR(1000)
SET @nSQL = N'SELECT @numCount = COUNT(1) 
							FROM ' + @TableName + ' 
							WHERE ETypeID = ''' + @UserID + ''' 
								AND Flag=''1'''
								
IF @Type = 0 
	SET @nSQL = @nSQL + ' AND TypeID LIKE ''00001%'''
ELSE IF @Type = 1 
	SET @nSQL = @nSQL + ' AND TypeID LIKE ''00002%'''
ELSE IF @Type = 5 
	SET @nSQL = @nSQL + ' AND (TypeID LIKE ''0000100003%'' OR TypeID LIKE ''0000100004%'') AND Type=''0'''
ELSE IF @Type = 6 
	SET @nSQL = @nSQL + ' AND TypeID LIKE ''0000400003%'' AND Type=''1'''
ELSE IF @Type = 7 
	SET @nSQL = @nSQL + ' AND TypeID LIKE ''0000300003%'' AND Type=''2'''
ELSE IF @Type = 8 
	SET @nSQL = @nSQL + ' AND TypeID LIKE ''0000100002%'' AND Type=''3'''
ELSE IF @Type = 11 --其他资产 不包括'固定资产'     '银行账户'
	SET @SQL = @SQL + ' AND (TypeID LIKE ''00001%'' AND TypeID NOT LIKE ''0000100002%'' AND TypeID NOT LIKE ''0000100004%'' AND TypeID<>''0000100003''  and typeid <>''0000100009'' and typeid <>''0000200006'') AND Type=''4'''
ELSE IF @Type = 12 --负债
	SET @SQL = @SQL + ' AND (TypeID LIKE ''00002%'' OR TypeID = 0000) AND (  typeid <>''0000100009'' and typeid <>''0000200006'') AND Type=''5'''
ELSE IF @Type = 13 --收入不包括'其他收入'
	SET @SQL = @SQL + ' AND (TypeID LIKE ''00003%'' AND TypeID NOT LIKE ''0000300003%'') AND Type=''6'''
ELSE IF @Type = 14 --支出 不包括'费用合计'
	SET @SQL = @SQL + ' AND (TypeID LIKE ''00004%'' AND TypeID NOT LIKE ''0000400003%'') AND Type=''7'''
ELSE IF @Type = 15 --所有者权益'
	SET @SQL = @SQL + ' AND TypeID LIKE ''00006%'' AND Type=''8'''
	
EXEC sp_executesql @nSQL, N'@numCount INT OUTPUT', @numCount OUTPUT

DECLARE @MaxNum INT ,@charMaxNum VARCHAR(30)
SELECT @MaxNum=SubValue FROM dbo.sysdata WHERE SubName='OperatorBaseRange'

SET @charMaxNum=@MaxNum
IF @numCount > 5000
BEGIN
	RETURN -4
END
 
--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','LoginUser','0'
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
	SELECT * 
	FROM dbo.sysobjects 
	WHERE id = OBJECT_ID(N'[dbo].[GP_UserRange_ModifySub]') 
		AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
	DROP PROCEDURE [dbo].[GP_UserRange_ModifySub]
GO
/*
add by 李海洋
date: 2012-04-05
description: 操作员多级权限范围, 子权限设置 - 新添
*/
CREATE PROCEDURE GP_UserRange_ModifySub (
	 @UserID			VARCHAR(50)
	,@Type				INT
	,@TypeID			VARCHAR(200)
	,@modifyflag	VARCHAR(1)
	,@assortflag	VARCHAR(1)
	,@disableflag	VARCHAR(1)
	,@delflag			VARCHAR(1)
)
--@encode$--
AS 
SET NOCOUNT ON 

DECLARE 
	-- @ManTypeIDName varchar(50) 
	@TableName varchar(50)
	,@AllManID varchar(50)
	,@SQL varchar(2000)
	,@atypeType char(1)
	
-- 分类选择权限表
-- BType
IF @Type IN (0,1)
BEGIN
	SET @TableName = 'BType_L'
	IF @Type = 0
	BEGIN
		--SET @ManTypeIDName = 'MangerBTypeID'
		SET @AllManID = '00001'
	END
	ELSE
	BEGIN
		--SET @ManTypeIDName = 'MangerBTypeID2'
		SET @AllManID = '00002'
	END
END
-- PType
ELSE IF @Type = 2
BEGIN
	SET @TableName = 'PType_L'
	--SET @ManTypeIDName = 'MangerPTypeID'
	SET @AllManID = '00000'
END
-- KType
ELSE IF @Type = 3
BEGIN
	SET @TableName = 'KType_L'
	--SET @ManTypeIDName = 'MangerKTypeID'
	SET @AllManID = '00000'
END
-- EType
ELSE IF @Type = 4
BEGIN
	SET @TableName = 'EType_L'
	--SET @ManTypeIDName = 'MangerETypeID'
	SET @AllManID = '00001'
END
-- DType
ELSE IF @Type = 9
	BEGIN
		SET @TableName = 'DType_L'
		--SET @ManTypeIDName = 'MangerDTypeID'
		SET @AllManID = '00000'
	END
--SType
ELSE IF @Type = 10
BEGIN
	SET @TableName = 'SType_L'
	--SET @ManTypeIDName = 'MangerSTypeID'
	SET @AllManID = '00000'
END
-- others
ELSE
BEGIN
	SET @TableName = 'AType_L'
	IF @Type = 5
	BEGIN
		--SET @ManTypeIDName = 'MangerATypeID'
		SET @atypeType = '0'
	END
	ELSE IF @Type = 6
	BEGIN
		--SET @ManTypeIDName = 'MangerExpense'
		SET @atypeType = '1'
	END
	ELSE IF @Type = 7
	BEGIN
		--SET @ManTypeIDName = 'MangerIncome'
		SET @atypeType = '2'
	END
	ELSE
	BEGIN
		--SET @ManTypeIDName = 'MangerCpaital'
		SET @atypeType = '3'
	END
	SET @AllManID = '0000'
END



SET @SQL = 'UPDATE ' + @TableName + ' 
						SET modifyflag	 = ''' + @modifyflag	+ '''
								,assortflag	 = ''' + @assortflag	+ '''
								,disableflag = ''' + @disableflag	+ '''
								,delflag		 = ''' + @delflag			+ '''	
						WHERE ETypeID = ''' + @UserID + '''
							AND typeid = '

--@TypeID 为00000表示所有当前type的权限
IF @TypeID = '00000'
BEGIN
	IF @Type NOT IN (5, 6, 7, 8)
		SET @SQL = @SQL + '''' + @AllManID + ''''
	ELSE 
	BEGIN
		IF @Type = 5 
			SET @SQL = @SQL + '''' + @AllManID + '''
							AND type = ''0'''
		ELSE IF @Type = 6 
			SET @SQL = @SQL + '''' + @AllManID + '''
							AND type = ''1'''
		ELSE IF @Type = 7 
			SET @SQL = @SQL + '''' + @AllManID + '''
							AND type = ''2'''
		ELSE IF @Type = 8 
			SET @SQL = @SQL + '''' + @AllManID + '''
							AND type = ''3'''
	END
END
ELSE
	SET @SQL = @SQL + '''' + @TypeID + ''''

PRINT(@SQL)
EXEC(@SQL)

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_UserRange_Query]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_UserRange_Query]
GO
/*
操作员多级权限范围设置 - 查询

*/

/*
modify by 李海洋
date: 2012.06.21
添加多级权限子权限
*/
CREATE     PROCEDURE GP_UserRange_Query
    (
      @UserID VARCHAR(50) ,
      @Type INT,
      @IsUserGroupLimit BIT  --是否设置角色权限
    )
--@encode$--
AS 
    SET NOCOUNT ON 

    DECLARE @ManTypeIDName VARCHAR(50) ,
        @TableName VARCHAR(50) ,
        @BaseTableName VARCHAR(50) ,
        @AllWord VARCHAR(50) ,
        @SQL VARCHAR(MAX)
    IF @Type = 0 OR @Type = 1 
    BEGIN
        SET @TableName = 'BType_L'
        SET @BaseTableName = 'BType'
        IF @Type = 0 
            BEGIN
                SET @ManTypeIDName = 'MangerBTypeID'
                SET @AllWord = '全部客户'
            END
        ELSE 
            BEGIN
                SET @ManTypeIDName = 'MangerBTypeID2'
                SET @AllWord = '全部供货商'
            END
    END
    ELSE IF @Type = 2 
    BEGIN
        SET @TableName = 'PType_L'
        SET @BaseTableName = 'PType'
        SET @ManTypeIDName = 'MangerPTypeID'
        SET @AllWord = '全部商品'
    END
    ELSE IF @Type = 3 
    BEGIN
        SET @TableName = 'KType_L'
        SET @BaseTableName = 'Stock'
        SET @ManTypeIDName = 'MangerKTypeID'
        SET @AllWord = '全部仓库'
    END
    ELSE IF @Type = 4 
    BEGIN
        SET @TableName = 'EType_L'
        SET @BaseTableName = 'Employee'
        SET @ManTypeIDName = 'MangerETypeID'
        SET @AllWord = '全部职员'
    END
    ELSE IF @Type = 9  --去掉分支机构
    BEGIN
        SET @TableName = 'SType_L'
        SET @BaseTableName = 'SType'
        SET @ManTypeIDName = 'MangerSTypeID'
        SET @AllWord = '全部分支机构'
    END
    ELSE IF @Type = 10 
    BEGIN
        SET @TableName = 'DType_L'
        SET @BaseTableName = 'Department'
        SET @ManTypeIDName = 'MangerDTypeID'
        SET @AllWord = '全部部门'
    END
    ELSE 
    BEGIN
        SET @TableName = 'AType_L'
        SET @BaseTableName = 'Ac_Items'
        IF @Type = 5 
        BEGIN
            SET @ManTypeIDName = 'MangerATypeID'
            SET @AllWord = '全部账户'
        END
        ELSE IF @Type = 6 
        BEGIN
            SET @ManTypeIDName = 'MangerExpense'
            SET @AllWord = '全部费用'
        END
        ELSE  IF @Type = 7 
        BEGIN
            SET @ManTypeIDName = 'MangerIncome'
            SET @AllWord = '全部其他收入'
        END
        ELSE IF @Type = 8 
        BEGIN
            SET @ManTypeIDName = 'MangerCpaital'
            SET @AllWord = '全部固定资产'
        END
        ELSE IF @Type=11
		BEGIN
            SET @ManTypeIDName = 'MangerOtherCpaital'
            SET @AllWord = '全部其他资产'
		END
         ELSE IF @Type=12
		BEGIN
            SET @ManTypeIDName = 'MangerLiabilities'
            SET @AllWord = '全部负债'
		END
         ELSE IF @Type=13
		BEGIN
            SET @ManTypeIDName = 'MangerRevenue'
            SET @AllWord = '全部收入'
			END
        ELSE IF @Type=14 
        BEGIN
                SET @ManTypeIDName = 'MangerPay'
                SET @AllWord = '全部支出'
		END
		ELSE IF @Type=15
		BEGIN
            SET @ManTypeIDName = 'MangerOwnerEquity'
            SET @AllWord = '全部所有者权益'
		END
  END
  
  
	DECLARE @LimitTable VARCHAR(100) = 'LoginUser'
	--角色设置时，表前面添加了Ug
  
	IF @IsUserGroupLimit = 1
	BEGIN
		SET @TableName = 'Ug' + @TableName
		SET @LimitTable = 'UserGroupLimit'
	END

	CREATE TABLE #temp
	(
	  UserCode VARCHAR(200) ,
	  FullName VARCHAR(200) ,
	  TypeID VARCHAR(200) ,
	  URL VARCHAR(3000) ,
	  SonNum INT
	)

--查询loginUser, 是否拥有所有权限
    SET @SQL = '
	IF EXISTS(
		SELECT TOP 1 1 
		FROM '+@LimitTable+' 
		WHERE ETypeID = ''' + @UserID + ''' 
			AND ' + @ManTypeIDName + '<>''-99999''
	)
		INSERT INTO #temp VALUES(''''
				,N''' + @AllWord + '''
				,''00000''
				,''' + @AllWord + '''
				,1)'

    EXEC(@SQL)

-- 如果loginUser没有取到数据, 查询type_l表获取数据,
-- 只筛选叶子节点(flag为'1')

    IF NOT EXISTS ( SELECT TOP 1
                            1
                    FROM    #temp ) 
        BEGIN
            SET @SQL = '
	INSERT INTO #temp(
		 UserCode
		,FullName
		,TypeID
		,SonNum
	) 
		SELECT 
			 b.UserCode
			,b.FullName
			,a.TypeID
			,b.SonNum 
		FROM ' + @TableName + ' a,' + @BaseTableName + ' b
		WHERE a.ETypeID = ''' + @UserID + ''' 
			AND a.Flag = ''1'''
                + CASE WHEN @TableName = 'AType_L' OR @TableName = 'UgAType_L'
                       THEN ' AND a.TypeID = b.nTypeId '
                       ELSE ' AND a.TypeID = b.TypeID '
                  END
                + CASE WHEN @Type = 0 THEN ' AND a.TypeID LIKE ''00001%'''
                       WHEN @Type = 1 THEN ' AND a.TypeID LIKE ''00002%'''
                       ELSE ''
                  END + CASE WHEN @Type = 5 THEN 'AND a.type = ''0'''
                             WHEN @Type = 6 THEN 'AND a.type = ''1'''
                             WHEN @Type = 7 THEN 'AND a.type = ''2'''
                             WHEN @Type = 8 THEN 'AND a.type = ''3'''
							 WHEN @Type=11 THEN 'AND a.type=''4'''
							 WHEN @Type=12 THEN 'AND a.type=''5'''
							 WHEN @Type=13 THEN 'AND a.type=''6'''
							 WHEN @Type=14 THEN 'AND a.type=''7'''
							 WHEN @Type=15 THEN 'AND a.type=''8'''
                       ELSE ''
                        END
												
           
            --PRINT ( @SQL )
            EXEC(@SQL)
        END



-- 如果不存在UserCode为空字符的
-- 处理'路径'信息

    IF NOT EXISTS ( SELECT TOP 1
                            1
                    FROM    #temp
                    WHERE   UserCode = '' ) 
        BEGIN
           IF @TableName = 'AType_L' OR @TableName = 'UgAType_L' 
               BEGIN
					 	-- 9.0Sp6 项目路劲单独处理
                  SELECT  UserCode ,
                          FullName ,
                          TypeID ,
                          DBO.F_GetItemsPath(TypeID) AS URL ,
                          SonNum
                  FROM    #temp 
								 RETURN 0
               END
           ELSE 
                BEGIN
                    DECLARE @URL VARCHAR(3000) ,
                        @FullName VARCHAR(200) ,
                        @TypeID VARCHAR(200) ,
                        @i INT ,
                        @nSQL NVARCHAR(1000) ,
                        @urlFlag INT ,
                        @SonNum INT
                    DECLARE Range_Cursor CURSOR
                    FOR
                        SELECT  TypeID ,
                                SonNum
                        FROM    #temp
                    OPEN Range_Cursor
                    FETCH NEXT FROM Range_Cursor INTO @TypeID, @SonNum
                    WHILE @@FETCH_STATUS = 0 
                        BEGIN
                            SET @i = 1
                            SET @FullName = ''
                            SET @URL = ''
                            SET @urlFlag = CASE WHEN @Type = 0
                                                     OR @Type = 1 THEN 2
                                                WHEN @Type = 2 THEN 4
                                                WHEN @Type = 3 THEN 5
                                                WHEN @Type = 4 THEN 3
                                                WHEN @Type = 9 THEN 13
                                                WHEN @Type = 10 THEN 10
                                                ELSE 6
                                           END
                            EXEC Web_GetParentPath1 @TypeID, @urlFlag,
                                @URL OUTPUT

                            IF @SonNum = 0
                                AND RIGHT(@URL, 1) = '\' 
                                SET @URL = LEFT(@URL, LEN(@URL) - 1)
                            UPDATE  #temp
                            SET     URL = @URL
                            WHERE   TypeID = @TypeID
                            FETCH NEXT FROM Range_Cursor INTO @TypeID, @SonNum
                        END
                    CLOSE Range_Cursor
                    DEALLOCATE Range_Cursor
                END
        END
        
    SELECT * FROM #temp ORDER BY UserCode ,URL
        
    DROP TABLE #temp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
	SELECT * 
	FROM dbo.sysobjects 
	WHERE id = OBJECT_ID(N'[dbo].[GP_UserRangeSubLevel_Check]') 
		AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
	DROP PROCEDURE [dbo].[GP_UserRangeSubLevel_Check]
GO
/*
操作员多级权限子权限验证, 
add by 李海洋
date: 2012.04.05
*/
CREATE PROCEDURE GP_UserRangeSubLevel_Check (
	 @UserID	VARCHAR(50)
	,@Type		INT
	,@TypeID	VARCHAR(200)
	,@SubLevelType INT
)
--@encode$--
AS 
SET NOCOUNT ON 

DECLARE 
	@TableName varchar(50)
	,@AllManID varchar(50)
	,@SQL NVARCHAR(2000)
	,@atypeType char(1)
	
-- 分类选择权限表
-- BType
IF @Type = 2
BEGIN
	SET @TableName = 'BType_L'
END
-- EType
ELSE IF @Type = 3
BEGIN
	SET @TableName = 'EType_L'
	SET @AllManID = '00001'
END
-- PType
ELSE IF @Type = 4
BEGIN
	SET @TableName = 'PType_L'
	SET @AllManID = '00000'
END
-- KType
ELSE IF @Type = 5
BEGIN
	SET @TableName = 'KType_L'
	SET @AllManID = '00000'
END
-- DType
ELSE IF @Type = 7
	BEGIN
		SET @TableName = 'DType_L'
		SET @AllManID = '00000'
	END
--SType
ELSE IF @Type = 9
BEGIN
	SET @TableName = 'SType_L'
	SET @AllManID = '00000'
END
-- others
ELSE
BEGIN
	SET @TableName = 'AType_L'
	IF @Type = 15
	BEGIN
		SET @atypeType = '0'
	END
	ELSE IF @Type = 16
	BEGIN
		SET @atypeType = '1'
	END
	ELSE IF @Type = 17
	BEGIN
		SET @atypeType = '2'
	END
	ELSE IF @Type = 18
	BEGIN
		SET @atypeType = '3'
	END
	SET @AllManID = '0000'
END
-- 结果
DECLARE @RE VARCHAR(10)


--要check的权限类型
SET @SQL = 'SELECT TOP 1 @RE = '
IF @SubLevelType = -1
	SET @SQL = @SQL + 'delflag'
ELSE IF @SubLevelType = 0
	SET @SQL = @SQL + 'disableflag'
ELSE IF @SubLevelType = 1
	SET @SQL = @SQL + 'assortflag'
ELSE IF @SubLevelType = 2
	SET @SQL = @SQL + 'modifyflag'



SET @SQL = @SQL + '
	FROM ' + @TableName + '
	WHERE etypeid = ''' + @UserID + '''' + '
	AND flag = 1
	AND (''' + @TypeID + ''' LIKE typeid + ''%'''
	
--Atype, Btype单独处理
IF @TableName = 'AType_L'
	SET @SQL = @SQL + '
		AND type = ''' + @atypeType +''' )'
ELSE IF @TableName = 'BType_L'
	SET @SQL = @SQL + ')'
ELSE 
	SET @SQL = @SQL + '
		OR typeid = ''' + @AllManID + ''')'
SET @SQL = @SQL + ' ORDER BY flag DESC'
--PRINT(@SQL)
EXEC sp_executesql @SQL, N'@RE VARCHAR(10) output',@RE OUTPUT;

--SELECT @RE;

IF @RE = '0'
	RETURN 0;
ELSE IF @RE = '1'
	RETURN 1;
ELSE 
	RETURN 0;

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



--
--			 单据自定义验证
--			 老老实实拼接字符串
--			 Custom_Column_Index|Detail中 CustomColumnID与Custom_BillIndex|Details表中字段名字中的数字对应
--
GO
	IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_Valid_CostomRequired',N'P'))
	BEGIN
		DROP PROC GP_Valid_CostomRequired
	END
GO
	CREATE PROC GP_Valid_CostomRequired
	(
		@BillNumberID INT,
		@BillType INT
	)
	AS
	BEGIN
		DECLARE @RowCount INT,
				@RowIndex INT,
				@CustomColumnId INT,
				@Label NVARCHAR(100)='',
				@SQL NVARCHAR(MAX),
				@Error BIT,
				@Result NVARCHAR(100)
		
		--表头自定义字段必填
        SELECT  CustomColumnId ,
                Label ,
                IsRequired ,
                ROW_NUMBER() OVER ( ORDER BY CustomColumnId ) AS RowIndex
        INTO    #Custom_Index_Define
        FROM    dbo.Custom_Column_BillIndex
        WHERE   BillType = @BillType AND IsRequired=1 AND IsVisible=1
		--表体自定义字段必填
		SELECT  CustomColumnId ,
                Label ,
                IsRequired ,
                ROW_NUMBER() OVER ( ORDER BY CustomColumnId ) AS RowIndex
        INTO    #Custom_Detail_Define
        FROM    dbo.Custom_Column_BillDetail
        WHERE   BillType = @BillType AND IsRequired=1 AND IsVisible=1
        
        --表头验证
        --不存在对应自定义字段，异常
		IF EXISTS(SELECT TOP 1 1 FROM #Custom_Index_Define)
		BEGIN
			SELECT @RowCount=COUNT(1) FROM #Custom_Index_Define
			SET @RowIndex=1
			WHILE(@RowIndex<=@RowCount)
			BEGIN
				SELECT @CustomColumnId=CustomColumnId,@Label=Label FROM #Custom_Index_Define WHERE RowIndex=@RowIndex
				SET @Error=0
				SET @SQL='IF NOT EXISTS(SELECT TOP 1 1 FROM Custom_BillIndex WHERE BillID=@BillNumberID 
						                AND BillType=@BillType AND SysDiy'+CAST(@CustomColumnId AS VARCHAR(10))+'_head IS NOT NULL)
						  SET @Error=1'
				EXEC sp_executesql @SQL,N'@BillNumberID INT,@BillType INT,@Error BIT OUT',@BillNumberID,@BillType,@Error OUT
				
				IF @Error=1
				BEGIN
					SET @Result='表头自定义字段['+@Label+']为必填项，不能为空！'
					DROP TABLE #Custom_Detail_Define,#Custom_Index_Define
					RAISERROR(@Result,16,1);
					RETURN
				END
				SET @RowIndex=@RowIndex+1
			END
		END
		
		--表体自定义验证
		IF EXISTS(SELECT TOP 1 1 FROM #Custom_Detail_Define)
		BEGIN
			CREATE TABLE #Detail
			(
				ID INT,
				BillNumberID INT,
				RowIndex INT
			)
			DECLARE @Table VARCHAR(50);
			SELECT @Table=detailTable FROM dbo.BillName WHERE Billtype=@BillType
			
			--提示信息要对应每一行
			--所以把明细ID导入临时表
			IF ISNULL(@Table,'')<>''
			BEGIN
				SET @SQL=N'SELECT ID,BillNumberID,ROW_NUMBER() OVER ( ORDER BY BillNumberID ) AS RowIndex FROM '+@Table +' WITH(NOLOCK) WHERE BillNumberID=@BillNumberID'
				INSERT INTO #Detail EXEC sp_executesql @SQL,N'@BillNumberID INT',@BillNumberID
				
				IF EXISTS(SELECT TOP 1 1 FROM #Detail)
				BEGIN
					DECLARE @ErrorRowIndex INT
					SELECT @RowCount=COUNT(1) FROM #Custom_Detail_Define
					SELECT @RowIndex=1
					
					WHILE(@RowIndex<=@RowCount)
					BEGIN
						SELECT @CustomColumnId=CustomColumnId,@Label=Label FROM #Custom_Detail_Define WHERE RowIndex=@RowIndex
						SET @ErrorRowIndex=0
						
						SET @SQL=N'SELECT TOP 1 @ErrorRowIndex=RowIndex FROM #Detail A LEFT JOIN  Custom_BillDetails B ON B.BillID=A.BillNumberID
										  AND B.DetailID=A.ID
						                  AND B.BillType=@BillType 
						           WHERE B.SysDiy'+CAST(@CustomColumnId AS VARCHAR(10))+' IS NULL
								  '
						EXEC sp_executesql @SQL,N'@ErrorRowIndex INT OUT,@BillNumberID INT,@BillType INT',@ErrorRowIndex OUT,@BillNumberID,@BillType
						IF @ErrorRowIndex<>0
						BEGIN
							SET @Result='明细第['+CAST(@ErrorRowIndex AS VARCHAR(10))+']行，表体自定义字段['+@Label+']为必填项，不能为空！'
							DROP TABLE #Detail,#Custom_Detail_Define,#Custom_Index_Define
							RAISERROR(@Result,16,1)
							RETURN
						END
						SET @RowIndex=@RowIndex+1
					END 
				END
				DROP TABLE #Detail
			END
		END
		DROP TABLE #Custom_Detail_Define,#Custom_Index_Define
	END
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Validate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Validate]
GO




CREATE   PROCEDURE Gp_Validate
(
	@SubNo int,
	@Flag int output
)
--@encode$--
AS
SET NOCOUNT ON 
 declare @N int
select TOP 1 @N=Cast(SubValue as int) from SYSDATA1 where SubNo=@SubNo --检查程序的版本
 if @N is null return 1

if @SubNo=1
	select @Flag=@N
else if @SubNo=2 
begin
	 DECLARE @BIT INT,@MASK INT
 
	 SELECT @BIT=@N & 15
	 SELECT @MASK=POWER(2,@BIT)^POWER(2,@BIT+1) ^ POWER(2,@BIT+2) ^ POWER(2,@BIT+3) ^ POWER(2,@BIT+4) ^ POWER(2,@BIT+5)
	 SELECT @Flag=(@MASK & @N)/POWER(2,@BIT)
end 
else if @SubNo=3
begin
	 select @Flag=((POWER(2,18)-1) & @N) /4
	 if (3 & @N<>3) return 1
end

return @@Error




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_VIEWACCOUNT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_VIEWACCOUNT]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		过帐单据查看会计科目明细
-- 最后修改作者：	徐辉
-- 最后修改时间：	2005-08-19
-- ========================================================================
CREATE    PROCEDURE GP_VIEWACCOUNT
( 
	@billNumber int,
	@billType int
)
--@encode$--
AS
SET NOCOUNT ON

IF @billType in (17,57,21) --同价调拨，变价调拨，成本调价单特殊处理
BEGIN
	SELECT a.* 
	FROM (
			SELECT	l.CostTotal AS Total,
					a.typeid as atypeid
			FROM 	InOutStockTable l
			LEFT JOIN Ac_Items a ON a.nid = l.AtypeId
			WHERE l.billnumberId = @billNumber
			UNION ALL
			SELECT 	L.total,
					a.typeid AS atypeid
			FROM 	Listtable l
			LEFT JOIN Ac_Items a ON a.nid = l.AtypeId
			WHERE l.billnumberId = @billNumber
					AND l.atypeid <> '30'
	) a ORDER BY a.Total
	
END
ELSE
BEGIN
	SELECT 	ATypeID,
			Total 
	FROM 	ListTable 
	WHERE 	BillNumberID=@billNumber
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_VIEWACCOUNTEX]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_VIEWACCOUNTEX]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		过帐单据查看会计科目明细
-- 最后修改作者：	张腾
-- 最后修改时间：	2011-04-28
-- ========================================================================
CREATE PROCEDURE GP_VIEWACCOUNTEX
( 
	@billNumber int,
	@billType int
)
--@encode$--
AS
SET NOCOUNT ON

IF @billType in (17,57,21) --同价调拨，变价调拨，成本调价单特殊处理
BEGIN
	SELECT ATypeID,afullname,
	CASE 
		WHEN  TypeName IN('B','C','E','F') THEN  
			CASE  WHEN Total>=0 THEN ABS(Total) ELSE 0 END
		WHEN TypeName IN('L','G','A') THEN  
			CASE  WHEN Total>=0 THEN 0 ELSE ABS(Total) END
	END AS [JTotal],
	CASE 
		WHEN TypeName IN('B','F','C','E') THEN 
			CASE  WHEN Total>=0 THEN 0 ELSE ABS(Total) END
		WHEN TypeName IN('L','G','A') THEN  
			CASE  WHEN Total>=0 THEN ABS(Total) ELSE 0 END
	END AS [DTotal]			
 FROM(
	SELECT a.* 
	FROM (
			SELECT	l.CostTotal AS Total,
					a.typeid as atypeid,
					a.FullName AS afullname,
					a.TypeName
			FROM 	InOutStockTable l
			LEFT JOIN Ac_Items a ON a.nid = l.AtypeId
			WHERE l.billnumberId = @billNumber
			AND L.CostTotal<>0 AND L.CostTotal IS NOT NULL
			UNION ALL
			SELECT 	L.total,
					a.typeid AS atypeid,
					a.FullName AS afullname,
					a.TypeName
			FROM 	Listtable l
			LEFT JOIN Ac_Items a ON a.nid = l.AtypeId
			WHERE l.billnumberId = @billNumber
					AND l.atypeid <> '30'
	) a --ORDER BY a.Total
	)t ORDER BY JTotal,DTotal
END
ELSE
BEGIN	
SELECT ATypeID,afullname,
	CASE 
		WHEN TypeName IN('B','C','E','F') THEN 
			CASE  WHEN Total>=0 THEN ABS(Total) ELSE 0 END
		WHEN TypeName IN('L','G','A') THEN 
			CASE  WHEN Total>=0 THEN 0 ELSE ABS(Total) END
	END AS [JTotal],
	CASE 
		WHEN TypeName IN('B','C','E','F') THEN 
			CASE  WHEN Total>=0 THEN 0 ELSE ABS(Total) END
		WHEN TypeName IN('L','G','A') THEN  
			CASE  WHEN Total>=0 THEN ABS(Total) ELSE 0 END
	END AS [DTotal]			
 FROM(SELECT 	l.ATypeID,
			l.Total,
			a.FullName AS afullname,
			a.TypeName
	FROM 	ListTable l
	LEFT JOIN Ac_Items a ON a.nid = l.AtypeId 
	WHERE 	BillNumberID=@billNumber and billtype=@billType
)t ORDER BY JTotal,DTotal

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_VipCardDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_VipCardDeal]
GO










/*
	描述:Vip卡的处理,包括启用,停用,挂起,清除数据
	作者:谢吉康
	日期:2004-06-10
*/
CREATE   PROCEDURE GP_VipCardDeal(
	@Action 			varchar(20),	--动作
	@chvOperatorId		varchar(50),	--操作员ID
	@intVipCardSignId	int				--Vip卡的ID
)
--@encode$--
AS
SET NOCOUNT ON 

--=======================================删除VIP卡
IF @Action = 'Deleted'
BEGIN
	IF EXISTS(SELECT TOP 1 * FROM VipCardConsume A,VipCardSign B WHERE A.VipCardNo = B.VipCardNo AND B.VipCardSignId = @intVipCardSignId)
	BEGIN
		--RAISERROR('Vip卡已经使用过,不能删除!',16,1)
		RETURN -1
	END
	ELSE
	BEGIN
		DELETE FROM VipCardSign WHERE VipCardSignId = @intVipCardSignId
		
		IF @@ROWCOUNT = 0
		BEGIN
			--RAISERROR('删除数据失败!',16,1)
			RETURN -2
		END
		ELSE
		BEGIN
			--RAISERROR('删除数据成功!',16,1)
			RETURN 0
		END
	END
END

--=======================================启用VIP卡
IF @Action = 'ReUse'
BEGIN
	IF EXISTS(SELECT TOP 1 * FROM VipCardSign WHERE VipCardSignId = @intVipCardSignId AND VipCardState = 0)
	BEGIN
		--RAISERROR('正常的Vip卡,无需启用!',16,1)
		RETURN -1
	END
	ELSE
	BEGIN
		UPDATE VipCardSign SET VipCardState = 0 WHERE VipCardSignId = @intVipCardSignId

		IF @@ROWCOUNT = 0
		BEGIN
			--RAISERROR('启用Vip卡失败!',16,1)
			RETURN -2
		END
		ELSE
		BEGIN
			--RAISERROR('启用Vip卡成功!',16,1)
			RETURN 0
		END
	END
END

--=======================================停用VIP卡
IF @Action = 'Stop'
BEGIN
	--IF EXISTS(SELECT TOP 1 * FROM VipCardConsume A,VipCardSign B WHERE A.VipCardNo = B.VipCardNo AND B.VipCardSignId = @intVipCardSignId)
	--BEGIN
		--RAISERROR('Vip卡已经使用过,不能停用!',16,1)
	--	RETURN -1
	--END
	--ELSE
	--BEGIN
		UPDATE VipCardSign SET VipCardState = 1 WHERE VipCardSignId = @intVipCardSignId

		IF @@ROWCOUNT = 0
		BEGIN
			--RAISERROR('停用Vip卡失败!',16,1)
			RETURN -2
		END
		ELSE
		BEGIN
			--RAISERROR('停用Vip卡成功!',16,1)
			RETURN 0
		END
	--END
END

--=======================================挂失VIP卡
IF @Action = 'HangUp'
BEGIN
	--IF EXISTS(SELECT TOP 1 * FROM VipCardConsume A,VipCardSign B WHERE A.VipCardNo = B.VipCardNo AND B.VipCardSignId = @intVipCardSignId)
	--BEGIN
		--RAISERROR('Vip卡已经使用过,不能执行挂起操作!',16,1)
	--	RETURN -1
	--END
	--ELSE
	--BEGIN
		UPDATE VipCardSign SET VipCardState = 2 WHERE VipCardSignId = @intVipCardSignId

		IF @@ROWCOUNT = 0
		BEGIN
			--RAISERROR('挂起Vip卡失败!',16,1)
			RETURN -2
		END
		ELSE
		BEGIN
			--RAISERROR('挂起Vip卡成功!',16,1)
			RETURN 0
		END
	--END
END

--=======================================清除VIP卡数据
IF @Action = 'Clear'
BEGIN
	DECLARE @chvVipCardNo	varchar(100)	--Vip卡卡号
	
	SELECT TOP 1 @chvVipCardNo = VipCardNo FROM VipCardSign WHERE VipCardSignId = @intVipCardSignId

	IF @@ROWCOUNT = 0
	BEGIN
		--RAISERROR('没有符合条件的Vip卡记录!',16,1)
		RETURN -1
	END
	ELSE
	BEGIN
		UPDATE	VipCardConsume SET BillNumberID = '' WHERE VipCardNo = @chvVipCardNo

		IF @@ROWCOUNT = 0
		BEGIN
			--RAISERROR('挂起Vip卡失败!',16,1)
			RETURN -2
		END
		ELSE
		BEGIN
			--RAISERROR('挂起Vip卡成功!',16,1)
			RETURN 0
		END
	END
END









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_VipIniCzEdit]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Gp_VipIniCzEdit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===================================
--李灏龙
--会员初期储值维护修改
--======================================
CREATE PROCEDURE Gp_VipIniCzEdit
(
	@VipCardid		INT,			--会员卡id
	@stypeid		VARCHAR(50),	--分支机构id
	@OperatorId		VARCHAR(50),	--操作员ID
	@qcczmoney		NUMERIC(24,10)	--期初储值金额
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM dbo.SType_UserConfig WHERE StypeId = @stypeid AND Value = 1)
BEGIN
	SELECT	-1 AS code
			,'您所选分支机构已经开账，不允许修改期初储值余额，请确认后再试！' AS msg
	RETURN
END 

IF EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSign WHERE VipCardID = @VipCardid AND deleted = 1)
BEGIN
	SELECT	-1 AS code
			,'您本次所修改的会员卡已经停用，请确认后再试！' AS msg
	RETURN
END 

--985新增判断适用机构
IF EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSign V WHERE V.VipCardID=@VipCardid AND V.isApplyAllStype=0 AND NOT EXISTS(SELECT * FROM VipCard_ApplyStype WHERE VipCardID=V.VipCardID AND STypeID=@stypeid))
BEGIN
	SELECT	-1 AS code
			,'当前会员卡【'+(SELECT VipCardCode FROM nVipCardSign WHERE VipCardID=@VipCardid)+'】不适用于分支机构【'+(SELECT FullName FROM SType WHERE TypeId=@stypeid)+'】，不能保存，请确认后再试！' AS msg
	RETURN
END 

SET @qcczmoney = ISNULL(@qcczmoney,0)

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSignStype WHERE VipCardID = @VipCardid AND StypeId = @stypeid)
BEGIN
	INSERT INTO dbo.nVipCardSignStype
	        ( VipCardID ,
	          StypeId ,
	          qCczMoney ,
	          lJczMoney ,
	          lJxFczMoney ,
	          bNczMoney ,
	          bNxFczMoney ,
	          cZyeMoney ,
	          lJxFMoney ,
	          bNxFMoney
	        )
	SELECT	c.VipCardID ,
			@stypeid,
			@qcczmoney,--c.qCczMoney ,
			@qcczmoney,--c.qCczMoney+c.lJczMoney ,
			0,--c.qCczMoney+c.lJczMoney -c.cZyeMoney,
			0,--c.lJczMoney ,
			0,--c.qCczMoney+c.lJczMoney -c.cZyeMoney ,
			@qcczmoney,--c.cZyeMoney ,
			0,--c.BeginMoney+c.totalMoney ,
			0--c.totalMoney 
	FROM dbo.nVipCardSign c
	WHERE c.VipCardID = @VipCardid
END 
ELSE
BEGIN
	UPDATE nVipCardSignStype 
	SET	qCczMoney = @qcczmoney
		,cZyeMoney=@qcczmoney
		,lJczMoney = @qcczmoney+lJxFczMoney
	WHERE	VipCardID = @VipCardid AND StypeId = @stypeid
END

IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'inicanmodify' AND SubValue = 'T')
BEGIN
	--更新其他业务期初中【会员储值】的期初值
	DECLARE @numQcTotal  NUMERIC(24, 10) 
			,@sys_cid	INT
	SELECT	@sys_cid = CId FROM dbo.Ac_Currency WHERE Sysrow = 1
	SELECT  @numQcTotal = ISNULL(SUM(qCczMoney),0) FROM nVipCardSignStype WHERE StypeId = @stypeid
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.AType_Total WHERE ATypeID = '34' AND STypeID = @stypeid AND CID = @sys_cid )
		UPDATE  dbo.AType_Total SET Total00 = ISNULL(@numQcTotal,0),Ntotal00=ISNULL(@numQcTotal,0) WHERE ATypeID = '34' AND STypeID = @stypeid AND CID = @sys_cid
	ELSE
		INSERT dbo.AType_Total
		        ( ATypeID ,
		          STypeID ,
		          Total00 ,
		          Total ,
		          CID ,
		          Ntotal00 ,
		          Ntotal
		        )
		VALUES  ( '34' , -- ATypeID - varchar(50)
		          @stypeid , -- STypeID - varchar(50)
		          ISNULL(@numQcTotal,0) , -- Total00 - numeric
		          0 , -- Total - numeric
		          @sys_cid , -- CID - int
		          ISNULL(@numQcTotal,0) , -- Ntotal00 - numeric
		          0  -- Ntotal - numeric
		        )
END

SELECT	0 AS code
		,'修改成功！' AS msg
		
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_VirtualStockStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_VirtualStockStatus]
GO



/*
	作者：谢吉康
	日期：2004-11-24
	描述：重新调整了可销售订货数量
	
	修改标识 #01============================================
	修改:Wang Wei 
 	时间:2010-8-31
    描述:单据选择多仓库之后,从billindex表换成相关的明细表(qp1.0)
	
	修改标识 #02============================================
	修改:Wang Wei 
 	时间:2010-8-31
    描述:去除维修单据统计 01,添加单据（快修单）统计 02
*/

/*
	修改：赵斌
	时间：2011-07-06
	描述：为汽配3S添加领料出库单、领料退回单、救援单统计
	
	修改：徐辉
	时间：2011-08-17
	描述：添加虚拟库存列，动态计算
*/

/*
	修改：黄飞佳
	时间：2012-06-08
	描述：多单位换算动态加载单位列
*/

CREATE  PROCEDURE [dbo].[Gp_VirtualStockStatus]
( 
	@OperatorID 		VARCHAR(100),--操作员ID号 
	@Parid   			VARCHAR(100)='00000',--商品的父节点号
	@szKtypeId  		VARCHAR(8000)='',--仓库id号
	@sortfield 			VARCHAR(20),--按何种方式排序
	@EntryCode			VARCHAR(200),--商品条码
	@Standard			VARCHAR(200),--商品规格
	@Type				VARCHAR(200),--商品型号
	@Area				VARCHAR(200),--商品产地
	@stypeid			VARCHAR(8000),
	@virtualqtysql		VARCHAR(MAX)='isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)',--虚拟库存列计算sql
	@unitconvert        VARCHAR(10),--多单位标示,
	@billtype			VARCHAR(50),
	@startdate			VARCHAR(50) ,
	@enddate			VARCHAR(50),
	@showstockstop      INT =0,--是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid	VARCHAR(max)='',				
	@showzeroqty		INT=1--是否显示库存为零  1.显示  0.不显示
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
DECLARE @SQL varchar(MAX)  

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId VARCHAR(50))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
		
--仓库
CREATE TABLE #GetManKTypeId(TypeId VARCHAR(50))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT sk.TypeId FROM F_BaseGetAllManagerBaseTypeId(@szKTypeId,4,@OperatorID) sk
INNER JOIN stock S ON S.typeId=SK.TypeId AND (@showstockstop=0 OR (@showstockstop=1 AND S.deleted=0))
INNER JOIN #GetSelectSTypeId ST ON ST.TypeId=S.STypeID
-----------------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
        @Lendqty NVARCHAR(2000),
        @Borrowqty NVARCHAR(2000),
		@RQty NVARCHAR(2000),
		@CQty NVARCHAR(2000),
		@BuyOrderQty NVARCHAR(2000),
		@BuyReachQty NVARCHAR(2000),
		@SaleOrderQty NVARCHAR(2000),
		@SaleReachQty NVARCHAR(2000),
		@UnitRate NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
		@BaseUnitName NVARCHAR(2000),
        @temptable  NVARCHAR(2000),
		@drafBuyQty NVARCHAR(2000),
		@saleDrafQty NVARCHAR(2000),
		@LimitBuyQty NVARCHAR(2000),
		@LimitSaleQty NVARCHAR(2000)
      
IF @unitconvert=0
BEGIN
SELECT  @Qty='o.Qty/isnull(r3.rate,1)',
		@Lendqty='SUM((o.Lend-o.LendBack-o.saleqty)/isnull(r3.rate,1))',
		@Borrowqty='SUM((o.Borrow-o.BorrowBack-o.buyqty)/isnull(r3.rate,1))',   
	    @BuyReachQty='o.BuyReachQty/isnull(r3.rate,1)', 
		@RQty='o.RQty/isnull(r3.rate,1)',        
		@CQty='o.CQty/isnull(r3.rate,1)',        
		@BuyOrderQty='o.BuyOrderQty/isnull(r3.rate,1)', 
		@BuyReachQty='o.BuyReachQty/isnull(r3.rate,1)', 
		@SaleOrderQty='o.SaleOrderQty/isnull(r3.rate,1)',
		@SaleReachQty='o.SaleReachQty/isnull(r3.rate,1)',
        @UnitRate = 'isnull(r3.rate,1)',
		@UnitName = 'u3.fullname',
		@BaseUnitName = 'u1.fullname',
        @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,3','3'),
		@drafBuyQty='o.BuyReferQty/isnull(r3.rate,1)', 
		@saleDrafQty='o.SaleReferQty/isnull(r3.rate,1)',
		@LimitBuyQty='o.LimitBuyQty/isnull(r3.rate,1)', 
		@LimitSaleQty='o.LimitSaleQty/isnull(r3.rate,1)'
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='o.Qty/isnull(r2.rate,1)',
		@Lendqty='SUM((o.Lend-o.LendBack-o.saleqty)/isnull(r2.rate,1))',
		@Borrowqty='SUM((o.Borrow-o.BorrowBack-o.buyqty)/isnull(r2.rate,1))',   
		@BuyReachQty='o.BuyReachQty/isnull(r2.rate,1)', 
		@RQty='o.RQty/isnull(r2.rate,1)',        
		@CQty='o.CQty/isnull(r2.rate,1)',        
		@BuyOrderQty='o.BuyOrderQty/isnull(r2.rate,1)', 
		@BuyReachQty='o.BuyReachQty/isnull(r2.rate,1)', 
		@SaleOrderQty='o.SaleOrderQty/isnull(r2.rate,1)',
		@SaleReachQty='o.SaleReachQty/isnull(r2.rate,1)',
        @UnitRate = 'isnull(r2.rate,1)',
		@UnitName = 'u2.fullname',
		@BaseUnitName = 'u1.fullname',
        @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,2','2'),
		@drafBuyQty='o.BuyReferQty/isnull(r2.rate,1)', 
		@saleDrafQty='o.SaleReferQty/isnull(r2.rate,1)',
		@LimitBuyQty='o.LimitBuyQty/isnull(r2.rate,1)', 
		@LimitSaleQty='o.LimitSaleQty/isnull(r2.rate,1)'
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='o.Qty/isnull(r4.rate,1)',
		@Lendqty='SUM((o.Lend-o.LendBack-o.saleqty)/isnull(r4.rate,1))',
		@Borrowqty='SUM((o.Borrow-o.BorrowBack-o.buyqty)/isnull(r4.rate,1))',   
		@BuyReachQty='o.BuyReachQty/isnull(r4.rate,1)', 
		@RQty='o.RQty/isnull(r4.rate,1)',        
		@CQty='o.CQty/isnull(r4.rate,1)',        
		@BuyOrderQty='o.BuyOrderQty/isnull(r4.rate,1)', 
		@BuyReachQty='o.BuyReachQty/isnull(r4.rate,1)', 
		@SaleOrderQty='o.SaleOrderQty/isnull(r4.rate,1)',
		@SaleReachQty='o.SaleReachQty/isnull(r4.rate,1)',
		@UnitRate = 'c.stockunitrate',
		@UnitName = 'c.stockunitfullname',
		@BaseUnitName = 'c.baseunitfullname',
	    @UnitRate = 'isnull(r4.rate,1)',
		@UnitName = 'u4.fullname',
		@BaseUnitName = 'u1.fullname',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,4','4'),
		@drafBuyQty='o.BuyReferQty/isnull(r4.rate,1)', 
		@saleDrafQty='o.SaleReferQty/isnull(r4.rate,1)',
		@LimitBuyQty='o.LimitBuyQty/isnull(r4.rate,1)', 
		@LimitSaleQty='o.LimitSaleQty/isnull(r4.rate,1)'
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='o.Qty',
		@Lendqty='SUM(o.Lend-o.LendBack-o.saleqty)',
		@Borrowqty='SUM(o.Borrow-o.BorrowBack-o.buyqty)',   
		@RQty='o.RQty',        
		@CQty='o.CQty',     
		@BuyOrderQty='o.BuyOrderQty', 
		@BuyReachQty='o.BuyReachQty', 
		@SaleOrderQty='o.SaleOrderQty',
		@SaleReachQty='o.SaleReachQty',
		@UnitRate = '1',
		@UnitName = 'u1.fullname',
		@BaseUnitName = 'u1.fullname',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1','1'),
		@drafBuyQty='o.BuyReferQty', 
		@saleDrafQty='o.SaleReferQty',
		@LimitBuyQty='o.LimitBuyQty', 
		@LimitSaleQty='o.LimitSaleQty'
END
--------多单位计算End---------
-----------------------------------------------------------------------------------------------------------------------------

--非服务类、非组合品 商品
CREATE TABLE #GetManPTypeID(TypeId VARCHAR(50))
CREATE UNIQUE CLUSTERED INDEX [Ptypeidx] ON [dbo].[#GetManPTypeID] ([typeId])

SELECT @SQL='
	INSERT INTO #GetManPTypeID(TypeId) 
	SELECT P.typeId 
	FROM ptype P 
	INNER JOIN dbo.F_ManPTypeInCategoryID('''+@OperatorID+''','''+@Parid+''','''+@ptypeCategoryid+''') mp ON mp.TypeId=p.typeId 
	WHERE 
		P.isservice=0
		AND P.iscombinationproduct=0
	'
IF ISNULL(@EntryCode,'')<>''
	SET @SQL+=' AND P.MultEntryCode LIKE ''%'+@EntryCode+'%'''
	
IF ISNULL(@Standard,'')<>''
	SET @SQL+=' AND P.[Standard] LIKE ''%'+@Standard+'%'''
	
IF ISNULL(@Type,'')<>''
	SET @SQL+=' AND P.[Type] LIKE ''%'+@Type+'%'''
	
IF ISNULL(@Area,'')<>''
	SET @SQL+=' AND P.Area LIKE ''%'+@Area+'%'''
EXEC(@SQL)		

CREATE TABLE #GetManPTypeAll
(
	TypeId			varchar(100),
	FullName        varchar(200),
	UserCode        varchar(100),
	EntryCode		varchar(100),
	[Standard]		varchar(100),
	[Type]			varchar(20),
	Area			varchar(30),
	Sonnum          int,
	Leveal          int,
	Parid           varchar(200),
	unit1           varchar(100),
	unit2           varchar(100),
	unitrate1       varchar(100),
	unitname       NVARCHAR(2000),
	baseunitname    NVARCHAR(2000),
	unitrate        NVARCHAR(2000),
	sortid        int
)

CREATE UNIQUE CLUSTERED INDEX [PtypeAllidx] ON [dbo].[#GetManPTypeAll] 
(
	[typeId]
)

SET @SQL='INSERT INTO #GetManPTypeAll 
			 SELECT DISTINCT P.TypeId,P.FullName,P.UserCode,P.EntryCode,P.Standard,P.Type,P.Area,P.Sonnum,P.Leveal,
			 P.Parid,P.unit1,P.unit2,P.unitrate1,'
         
     SET @sql+=@UnitName+','+@BaseUnitName+','+@UnitRate
     
    SET @sql+=' ,p.sortid 
		FROM F_GetManPTypeAll('''+@OperatorID+''') P 
		inner join ptype p1 on p.typeid=p1.typeid '+@temptable

IF ISNULL(@ptypeCategoryid,'')<>''
	SET @sql=@sql+' inner join #GetManPTypeId pc on pc.typeid like p.typeid +''%'' '    
    set @sql+=' WHERE P.Parid='''+@Parid+'''
						AND p.isservice=0 
						AND p.iscombinationproduct = 0  
    '

EXEC(@SQL)

---------------数据统计---------------------------------------------------------------
CREATE TABLE #LeftJoinTable
(
	TypeId			 VARCHAR(50),
	RQty			 NUMERIC(24, 10) NOT NULL DEFAULT(0) ,
	CQty			 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	Qty				 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	Lendqty			 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	Borrowqty		 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	SaleOrderQty	 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	BuyOrderQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	SaleReachQty	 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	BuyReachQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	baseqty          NUMERIC(24, 10) NOT NULL DEFAULT(0),
	total			 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	drafBuyQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0), 
	saleDrafQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	LimitBuyQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0), 
	LimitSaleQty	 NUMERIC(24, 10) NOT NULL DEFAULT(0)
)

CREATE TABLE #ResultLeftTable
(
	pTypeId			 VARCHAR(50),
	saleQty			 NUMERIC(24, 10) 
)
 SET @SQL='
	INSERT INTO #ResultLeftTable (
		pTypeId,
		saleqty
	)
	SELECT 
		p1.typeid pTypeId,
		SUM(CASE WHEN o.billtype in (305,11,140,141,12,215,45,142,46,160,402,403) THEN -ISNULL('+@qty+',0)
				 ELSE ISNULL('+@qty+',0) END) saleQty 
	FROM  InOutstocktable o
	INNER JOIN f_split('''+@billtype+''','','') F ON F.a=O.BillType
	INNER JOIN #GetManPTypeId pp ON o.ptypeid = pp.typeid
	INNER JOIN #GetManKTypeId K ON o.KTypeId = K.TypeId
	INNER JOIN ptype p1 ON o.ptypeid=p1.typeid
	'+@temptable+'
	WHERE 
		BillDate BETWEEN '''+@startdate+''' AND '''+@enddate+'''   
	GROUP BY p1.typeid'
exec(@SQL)	   

SELECT @SQL='
	INSERT INTO #LeftJoinTable 
	(
		TypeId,
		RQty,
		CQty
	)
	SELECT	
		O.PTypeId TypeId,
		ISNULL(SUM('+@RQty+'),0) AS RQty,
		ISNULL(SUM('+@CQty+'),0) AS CQty
	FROM GoodsStocks_Draft O
	INNER JOIN #GetManKTypeId K ON K.typeid=O.ktypeid
	INNER JOIN #GetManPTypeId P ON P.TypeId=O.PtypeId
	INNER JOIN ptype p1 ON p1.typeid=O.PTypeId '+ @temptable+'
	GROUP BY 
		O.PTypeId'
EXEC(@SQL)

SELECT @sql ='
INSERT INTO #LeftJoinTable 
(
	TypeId,
	Qty,
	baseqty,
	total
)
SELECT 	
	p.typeid,
	ISNULL(SUM('+@qty+'),0) qty,
	ISNULL(sum(o.qty),0) baseqty,
	ISNULL(sum(o.total),0) total
FROM goodsstocks o 
INNER JOIN #GetManPTypeID p on p.typeid=o.ptypeid
INNER JOIN #GetManKTypeId k on o.KTypeId=k.TypeId
INNER JOIN ptype p1 ON p1.typeid=O.PTypeId '+ @temptable+'
GROUP BY 
	p.typeid'
EXEC(@SQL)	

SELECT @sql ='		
INSERT INTO #LeftJoinTable
(
	TypeId,
	Lendqty,
	Borrowqty
)					
SELECT 	
	a.typeid,
	ISNULL('+@Lendqty+',0) AS Lendqty,
	ISNULL('+@Borrowqty+',0) AS  Borrowqty
FROM V_LendStatus o 
INNER JOIN #GetManPTypeID a on a.typeid=o.ptypeid
INNER JOIN #GetManKTypeId k on o.ktypeid=k.typeid
INNER JOIN ptype p1  on o.ptypeid=p1.typeid ' + @temptable+'
GROUP BY 
	a.typeid'
EXEC(@SQL)		
	
SELECT @sql ='
INSERT INTO #LeftJoinTable 
(
	TypeId,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	saleDrafQty,
	drafBuyQty,
	LimitSaleQty,
	LimitBuyQty
)	
SELECT 	
	a.typeid,
	ISNULL(SUM('+@SaleOrderQty+'),0) SaleOrderQty,
	ISNULL(SUM('+@BuyOrderQty+'),0) BuyOrderQty,
	
	ISNULL(SUM('+@SaleReachQty+'),0) SaleReachQty,
	ISNULL(SUM('+@BuyReachQty+'),0) BuyReachQty,
	
	ISNULL(SUM('+@saleDrafQty+'),0) saleDrafQty,
	ISNULL(SUM('+@drafBuyQty+'),0) drafBuyQty,
	
	ISNULL(SUM('+@LimitSaleQty+'),0) LimitSaleQty,
	ISNULL(SUM('+@LimitBuyQty+'),0) LimitBuyQty
FROM GoodsStocks_Order o
inner join #GetManPTypeID a on a.typeid=o.ptypeid 
INNER JOIN #GetManKTypeId K ON o.ktypeid=K.TypeId 
INNer join ptype p1 on o.ptypeid=p1.typeid'+@temptable+'
GROUP BY 
	a.typeid'
EXEC(@SQL)

SET @SQL='
SELECT	
	a.typeid,
	a.sortid,
	a.fullname,
	a.usercode,
	a.EntryCode,
	a.Standard,
	a.Type,
	a.Area,
	a.sONnum,
	a.leveal,
	a.parid,
	a.unit1,
	a.unit2,
	a.unitrate1,
	ISNULL(SUM(f.qty),0) AS qty,
	ISNULL(SUM(f.Lendqty),0) AS Lendqty,
	ISNULL(SUM(f.Borrowqty),0) AS Borrowqty,
	ISNULL(SUM(f.FactQty),0) AS FactQty,
	ISNULL(SUM(f.RQty),0) AS RQty,
	ISNULL(SUM(f.CQty),0) AS CQty,
	ISNULL(SUM(f.KFHQty),0) KFHQty,
	ISNULL(SUM(f.buyreferqty),0) AS buyreferqty,
	ISNULL(SUM(f.salereferqty),0) AS salereferqty,
	ISNULL(SUM(f.BuyOrderQty),0) BuyOrderQty,
	ISNULL(SUM(f.SaleOrderQty),0) SaleOrderQty,
	ISNULL(SUM(f.SaleCanQty),0) SaleCanQty,
	case when a.Sonnum>0 then null else  a.unitname end AS unitname,
	case when a.Sonnum>0 then null else   a.baseunitname end AS baseunitname,
	case when a.Sonnum>0 then null else a.unitrate end AS unitrate,
	ISNULL(SUM(f.BuyReachQty),0) BuyReachQty,
	ISNULL(SUM(f.SaleReachQty),0) SaleReachQty,
	ISNULL(SUM(f.baseqty),0) AS baseqty,
	case when ISNULL(SUM(f.virtualqty),0)=0 THEN 0 ELSE CAST(ISNULL(SUM(f.costtotal),0) AS NUMERIC(24,10))/CAST(ISNULL(SUM(f.virtualqty),0)AS NUMERIC(24,10)) END  AS price,
	ISNULL(SUM(f.virtualqty),0) AS virtualqty,
	ISNULL(SUM(f.costtotal),0) costtotal
INTO #result			
FROM #GetManPTypeAll a 
LEFT JOIN 
(
	SELECT 
		a.*,
		('+@virtualqtysql+') virtualqty,
		('+@virtualqtysql+')*A.price costtotal 
	FROM (
		select 
			o.typeid,
			ISNULL(SUM(o.qty),0) AS qty,
			ISNULL(SUM(o.Lendqty),0) AS Lendqty,
			ISNULL(SUM(o.borrowqty),0) AS Borrowqty,
			ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.borrowqty),0)-ISNULL(SUM(o.lendqty),0) AS FactQty,
			ISNULL(SUM(o.rqty),0) AS RQty,
			ISNULL(SUM(o.cqty),0) AS CQty,
			ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.rqty),0)-ISNULL(SUM(o.cqty),0) AS KFHQty,
			ISNULL(SUM(o.drafBuyQty),0) AS buyreferqty,
			ISNULL(SUM(o.saleDrafQty),0) AS salereferqty,
			CASE WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.LimitBuyQty),0)>0 THEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.LimitBuyQty),0) ELSE 0 END  BuyOrderQty,
			
			CASE WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.LimitSaleQty),0)>0 THEN ISNULL(SUM(o.SaleOrderQty),0) - ISNULL(SUM(o.LimitSaleQty),0) ELSE 0 END SaleOrderQty,
			ISNULL(SUM(o.qty),0)+(CASE WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.LimitBuyQty),0)<=0 THEN 0 ELSE ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.LimitBuyQty),0) END)-ISNULL(SUM(saleDrafQty),0)+ISNULL(SUM(drafBuyQty),0)-(CASE WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.LimitSaleQty),0)<=0 THEN 0 ELSE ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.LimitSaleQty),0) END)
			SaleCanQty,
			
			ISNULL(SUM(o.BuyReachQty),0) BuyReachQty,
			ISNULL(SUM(o.SaleReachQty),0) SaleReachQty,
			ISNULL(SUM(o.baseqty),0) AS baseqty,
			case when ISNULL(SUM(o.qty),0)=0 THEN 0 ELSE CAST(ISNULL(SUM(o.total),0) AS NUMERIC(24,10))/CAST(ISNULL(SUM(o.qty),0)AS NUMERIC(24,10)) END  AS price
		from #LeftJoinTable o
		group by o.typeid
	)  A
) f ON LEFT(f.typeid,LEN(a.typeid))=a.typeid 
GROUP BY	
	a.typeid,
	a.fullname,
	a.usercode,
	a.EntryCode,
	a.Standard,
	a.Type,
	a.Area,
	a.sONnum,
	a.leveal,
	a.parid,
	a.unit1,
	a.unitrate1,
	a.unit2,	
	a.sortid,
	case when a.Sonnum>0 then null else a.unitname end,
	case when a.Sonnum>0 then null else	 a.baseunitname END,
	case when a.Sonnum>0 then null else a.unitrate END
	'
	
	
SET @SQL+='
SELECT	A.*
FROM	(
			SELECT	a.*,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.typeid)) as auxfullname1,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.typeid)) as auxfullname2,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.typeid)) as auxfullname3,
					(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.typeid) as auxrate1,
					(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.typeid) as auxrate2,
					(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.typeid) as auxrate3,
					 pp.RecAmgSTypeBuyPrice as recprice,
					ISNULL(o.saleqty,0)	 saleqty,
					customassistantunit=dbo.F_GetCustomAssist(a.typeid,a.baseqty)
			FROM #result a
			INNER JOIN Ptype p on a.typeid=p.typeid
			LEFT join (
						select	a.typeid, 
								sum(saleqty)as saleqty 
						from   #resultlefttable  TT
						INNER JOIN #result a ON tt.ptypeid like A.typeid+''%''
						group by a.typeid
			) o ON o.typeid=a.typeid
			left join ptype_price pp on pp.ptypeid=p.typeid and p.baseunitid=pp.unitid
)A '

--是否显示数量为0
IF @showzeroqty = 0
	SET @SQL = @SQL + ' WHERE A.virtualqty <> 0 '

SET @SQL = @SQL + ' ORDER BY a.sortid	
					drop table #result '	
					
--PRINT(@SQL)					
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#GetManPTypeId,#LeftJoinTable,#GetSelectSTypeId,#ResultLeftTable,#GetManPTypeAll

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_VirtualStockStatus_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_VirtualStockStatus_Details]
GO


/*
李灏龙
明细虚拟库存
*/


CREATE        PROCEDURE Gp_VirtualStockStatus_Details
( 
	@OperatorID 		VARCHAR(100),  	    		--操作员ID号
	@szKtypeId 			VARCHAR(8000)='',           --仓库id号
	@showzeroqty   		VARCHAR(5),               	--是否显示库存为0的记录   1--显示   0--不显示
	@stypeid			VARCHAR(8000),
	@virtualqtysql		VARCHAR(max)='isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)',
	@unitconvert        VARCHAR(10)  ,               --多单位标示	
	@billtype			VARCHAR(50),
	@startdate			VARCHAR(50) ,
	@enddate			VARCHAR(50),
	@showstockstop		INT =0, --是否显示停用仓库数据 1为不显示 0为显示
	@ptypeid			VARCHAR(50)=''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
			
DECLARE @SQLALL VARCHAR(MAX)	 
IF @stypeid='' 
BEGIN
	SET @stypeid='00000'
END

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	VARCHAR(50))
INSERT INTO #GetSelectSTypeId(TypeId) 
SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--商品
CREATE TABLE #GetManPTypeId(TypeId	VARCHAR(50))
INSERT INTO #GetManPTypeId(TypeId) 
SELECT	F.TypeId 
FROM	dbo.F_LineP(@OperatorID) F,
		PType P
WHERE	F.TypeId = @ptypeid
		AND P.typeid = F.TypeId
		AND P.isservice = 0
		AND p.iscombinationproduct = 0
		
	

--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(50))
IF  @showstockstop=0
BEGIN
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT sk.TypeId FROM F_BaseGetAllManagerBaseTypeId(@szKTypeId,4,@OperatorID) sk
	INNER JOIN stock S ON sk.Typeid=S.Typeid
	INNER JOIN #GetSelectSTypeId ST ON S.STYPEID=ST.TYPEID	
END
ELSE
BEGIN
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT sk.TypeId FROM F_BaseGetAllManagerBaseTypeId(@szKTypeId,4,@OperatorID) sk
	INNER JOIN stock S ON sk.Typeid=S.Typeid
	INNER JOIN #GetSelectSTypeId ST ON S.STYPEID=ST.TYPEID	 WHERE s.deleted=0
END

CREATE CLUSTERED INDEX CIX_BID ON #GetManKTypeId(typeid)

IF @szKtypeId='' OR @szKtypeId='00000'   
	SELECT @szKtypeId='%'	-- 全部仓库
	
-----------------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
        @Lendqty NVARCHAR(2000),
        @Borrowqty NVARCHAR(2000),
		@RQty NVARCHAR(2000),
		@CQty NVARCHAR(2000),
		@BuyOrderQty NVARCHAR(2000),
		@BuyReachQty NVARCHAR(2000),
		@SaleOrderQty NVARCHAR(2000),
		@SaleReachQty NVARCHAR(2000),
		@UnitRate NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
		@BaseUnitName NVARCHAR(2000),
        @temptable  NVARCHAR(2000)

SELECT  @Qty='o.Qty/r.unitrate',
		@Lendqty='o.Lendqty/r.unitrate',
		@Borrowqty='o.Borrowqty/r.unitrate',   
		@BuyReachQty='o.BuyReachQty/r.unitrate', 
		@RQty='o.RQty/r.unitrate',        
		@CQty='o.CQty/r.unitrate',        
		@BuyOrderQty='o.BuyOrderQty/r.unitrate', 
		@BuyReachQty='o.BuyReachQty/r.unitrate', 
		@SaleOrderQty='o.SaleOrderQty/r.unitrate',
		@SaleReachQty='o.SaleReachQty/r.unitrate'
IF @unitconvert=0
BEGIN
SELECT  @UnitRate = 'isnull(r3.rate,1)',
		@UnitName = 'u3.fullname',
		@BaseUnitName = 'u1.fullname'
SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('o','1,3','3')

  
END
IF @unitconvert=1
BEGIN
SELECT  @UnitRate = 'isnull(r2.rate,1)',
		@UnitName = 'u2.fullname',
		@BaseUnitName = 'u1.fullname'
SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('o','1,2','2')

END
IF @unitconvert=2
BEGIN
SELECT  @UnitRate = 'isnull(r4.rate,1)',
		@UnitName = 'u4.fullname',
		@BaseUnitName = 'u1.fullname'
SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('o','1,4','4')

END
IF @unitconvert=3
BEGIN
SELECT  @UnitRate = '1',
		@UnitName = 'u1.fullname',
		@BaseUnitName = 'u1.fullname'
SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('o','1','1')

END
--------多单位计算End---------
-----------------------------------------------------------------------------------------------------------------------------

-- ==== 修改 ===

-- ==== 修改 ====

CREATE TABLE #Result1(
	TypeId			VARCHAR(50),
	Qty				NUMERIC(24, 10) NOT NULL DEFAULT(0),
	Factqty			NUMERIC(24, 10) NOT NULL DEFAULT(0),
	LendQty			NUMERIC(24, 10) NOT NULL DEFAULT(0),
	BorrowQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),	
	BuyOrderQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),
	SaleOrderQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),
	SaleCanQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),
	RQty			NUMERIC(24, 10) NOT NULL DEFAULT(0),
	CQty			NUMERIC(24, 10) NOT NULL DEFAULT(0),
	KFHQty			NUMERIC(24, 10) NOT NULL DEFAULT(0),
	saleqty         NUMERIC(24, 10) NOT NULL DEFAULT(0),
	GoodsCostPrice  NUMERIC(24, 10) NOT NULL DEFAULT(0),
	KtypeID			VARCHAR(50),
	CargoID			INT,
	ItemID			INT,
	IsCombined		INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100)
)

CREATE TABLE #Result(
	TypeId			VARCHAR(50),
	UserCode		VARCHAR(256),
	FullName  	  	VARCHAR(256),
	EntryCode		VARCHAR(256),
	[Standard]		VARCHAR(256),
	[Type]			VARCHAR(256),
	Area			VARCHAR(256),
	Unit1			VARCHAR(256),
	Unit2			VARCHAR(256),
	UnitRate1		VARCHAR(256),
	SonNum			INT,
	Leveal			INT,
	Parid			VARCHAR(50),
	unitname        NVARCHAR(2000),
	baseunitname    NVARCHAR(2000),
	unitrate        NVARCHAR(2000)
)

SET @SQLALL= '
INSERT INTO  #Result
	(
		TypeId,
		UserCode,
		FullName,
		EntryCode,
		Standard,
		Type,
		Area,
		Unit1,
		Unit2,
		UnitRate1,
		SonNum,
		Leveal,
		Parid,
		unitname,
		baseunitname,
		unitrate
	)
SELECT 
		o.TypeId,
		o.UserCode,
		o.FullName,
		o.EntryCode,
		o.Standard,
		o.Type,
		o.Area,
		isnull(o.Unit1,''''),
		isnull(o.Unit2,''''),
		o.UnitRate1,
		o.SonNum,
		o.Leveal,
		o.Parid,
		'+@UnitName+' AS unitname,
		'+@BaseUnitName+' AS baseunitname,
		'+@UnitRate+' AS unitrate
FROM 	ptype o'
+@temptable+
'
INNER JOIN #GetManPTypeId P ON P.TypeId=o.typeId  
WHERE	o.SonNum = 0
		and o.isservice=0
		and o.iscombinationproduct = 0  '
		
		
--PRINT(@SQLALL)
EXEC(@SQLALL)

--==============================================当前数量
CREATE TABLE #CurrStocksQty
(
	PTypeID		VARCHAR(50),
	QTY			NUMERIC(24,10),
	GoodsCostPrice NUMERIC(24,10),
	KtypeID		VARCHAR(50),
	CargoID		INT,
	ItemID		INT,
	IsCombined	INT,
	ProduceDate	VARCHAR(50),
	ValidDate	VARCHAR(50),
	GoodsNumber	VARCHAR(100)
) 
INSERT INTO #CurrStocksQty
SELECT	s.PTypeID,
		s.Qty,
		s.GoodsCostPrice,
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber
FROM 	GOODSSTOCKS_QTY s 
INNER JOIN #Result P ON s.pTypeId=p.typeId  
INNER JOIN #GetManKTypeId K ON s.ktypeid=K.TypeId 

SET @SQLALL =
'INSERT INTO #Result1
	(	TypeId ,
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber,	
		Qty ,
		Factqty,
		GoodsCostPrice
        )
SELECT	PTypeid,
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		ISNULL('+@qty+',0),
		ISNULL('+@qty+',0),
		GoodsCostPrice
FROM	#CurrStocksQty o
INNER JOIN #Result r ON r.typeid = o.ptypeid '

EXEC(@SQLALL)

--==============================================借欠数量	
CREATE TABLE #LEND
(
	PTypeID VARCHAR(50),
	LendQty  NUMERIC(24, 10) ,
	BorrowQty  NUMERIC(24, 10),
	KtypeID		VARCHAR(50),
	CargoID		INT,
	ItemID		INT,
	IsCombined	INT,
	ProduceDate	VARCHAR(50),
	ValidDate	VARCHAR(50),
	GoodsNumber	VARCHAR(100) 
) 	
INSERT INTO  #LEND
SELECT 	S.PTypeID,
		LendQty   =  ISNULL(SUM(S.Lend-S.LendBack-saleqty),0),
		BorrowQty =  ISNULL(SUM(Borrow-BorrowBack-buyqty),0),
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber	
FROM 	V_LENDStatus S 
INNER JOIN #Result P ON s.pTypeId=p.typeId  
INNER JOIN #GetManKTypeId K ON s.ktypeid=K.TypeId 
GROUP BY
		S.PTypeID,
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber	

SET @SQLALL =	
'INSERT INTO #Result1
	(	TypeId ,
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		LendQty ,
		BorrowQty
        )
SELECT	PTypeid,
		o.KtypeID,
		o.CargoID,
		o.ItemID,
		o.IsCombined,
		o.ProduceDate,
		o.ValidDate,
		o.GoodsNumber,
		LendQty   = ISNULL('+@Lendqty+',0),
		BorrowQty = ISNULL('+@Borrowqty+',0)
FROM	#LEND o 
INNER JOIN #Result r ON r.typeid = o.ptypeid 
'

EXEC(@SQLALL)

--==============================================修改订单数量
CREATE TABLE #VirtualStockOrder
(
	PTYPEID			VARCHAR(50),
	SaleOrderQty	NUMERIC(24, 10) ,
	BuyOrderQty		NUMERIC(24, 10),
	KtypeID			VARCHAR(50),
	CargoID			INT,
	ItemID			INT,
	IsCombined		INT,
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	GoodsNumber		VARCHAR(100),
	GoodsCostPrice	NUMERIC(24,10) 
)
INSERT INTO #VirtualStockOrder 
SELECT 	A.PTypeID,
		--A.SaleOrderQty - A.SaleReachQty - a.SaleReferQty AS SaleOrderQty, 
		A.SaleOrderQty - A.LimitSaleQty AS SaleOrderQty, 
		A.BuyOrderQty - A.LimitBuyQty AS BuyOrderQty,
		--A.BuyOrderQty - A.BuyReachQty - a.BuyReferQty AS BuyOrderQty,
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		GoodsCostPrice
FROM 	dbo.GoodsStocks_Order A 
INNER JOIN #Result P ON a.pTypeId=p.typeId  
INNER JOIN #GetManKTypeId K ON A.ktypeid=K.TypeId 

--SELECT * FROM dbo.GoodsStocks_Order WHERE ptypeid = '00011'

SET @SQLALL =
'INSERT INTO #Result1
	(	TypeId ,
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		SaleOrderQty ,
		BuyOrderQty,
		GoodsCostPrice
        )
SELECT	PTypeid,
		o.KtypeID,
		o.CargoID,
		o.ItemID,
		o.IsCombined,
		o.ProduceDate,
		o.ValidDate,
		o.GoodsNumber,					
		SaleOrderQty   = CASE WHEN ISNULL('+@SaleOrderQty+',0)>=0 THEN ISNULL('+@SaleOrderQty+',0) ELSE 0 END,
		BuyOrderQty    = CASE WHEN ISNULL('+@BuyOrderQty+',0)>=0 THEN ISNULL('+@BuyOrderQty+',0) ELSE 0 END,
		GoodsCostPrice
FROM	#VirtualStockOrder o
INNER JOIN #Result R ON (R.TypeID = o.PTypeID) '

--PRINT(@SQLALL)
EXEC(@SQLALL)


--==============================================修改草稿数量
--计算普通单据草稿库存
CREATE TABLE #DGS
(
	PTypeId		varchar(100),
	RQty		 NUMERIC(24, 10) ,
	CQty		 NUMERIC(24, 10) ,
	KtypeID		VARCHAR(50),
	CargoID		INT,
	ItemID		INT,
	IsCombined	INT,
	ProduceDate	VARCHAR(50),
	ValidDate	VARCHAR(50),
	GoodsNumber	VARCHAR(100),
	goodscostprice NUMERIC(24,10)
)
INSERT INTO #DGS(PTypeId,RQty,CQty,KtypeID,CargoID,ItemID,IsCombined,ProduceDate,ValidDate,GoodsNumber,goodscostprice)
SELECT	B.PTypeId,
		ISNULL(SUM(B.RQty),0) AS RQty,
		ISNULL(SUM(B.CQty),0) AS CQty,
		b.KtypeID,
		B.CargoID,
		B.ItemID,
		B.IsCombined,
		B.ProduceDate,
		B.ValidDate,
		B.GoodsNumber,
		b.GoodsCostPrice
FROM GoodsStocks_Draft B 
INNER JOIN #GetManKTypeId K ON b.ktypeid=k.typeid
INNER JOIN #GetManPTypeId p ON p.TypeId = b.PtypeId
GROUP BY b.PtypeId,KtypeID,CargoID,ItemID,IsCombined,ProduceDate,ValidDate,GoodsNumber,b.GoodsCostPrice

SET @SQLALL ='
INSERT INTO #Result1
	(	TypeId ,
		KtypeID,
		CargoID,
		ItemID,
		IsCombined,
		ProduceDate,
		ValidDate,
		GoodsNumber,
		RQty ,
		CQty ,
		goodscostprice
        )
SELECT	PTypeid,
		o.KtypeID,
		o.CargoID,
		o.ItemID,
		o.IsCombined,
		o.ProduceDate,
		o.ValidDate,
		o.GoodsNumber,
		RQty = ISNULL('+@RQty+',0),
		CQty = ISNULL('+@CQty+',0),
		goodscostprice
FROM	#DGS o
INNER JOIN #Result R ON R.TypeId = o.PTypeId '

EXEC(@SQLALL)
-- ==== 修改 ====

--如果不是手工指定法，则没有成本纬度，所以将成本全部置为0，以便后面合并数据
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'costing' AND SubValue = '3')
	UPDATE #Result1 SET GoodsCostPrice = 0
	
SELECT @SQLALL = ' select * from (
SELECT	R1.TypeId ,
		R1.KtypeID,
		R1.CargoID,
		R1.ItemID,
		R1.IsCombined,
		R1.ProduceDate,
		R1.ValidDate,
		R1.GoodsNumber,
		R1.Qty ,
		R1.Qty + R1.BorrowQty - R1.LendQty AS Factqty ,
		R1.LendQty ,
		R1.BorrowQty ,
		R1.Qty + CASE WHEN R1.BuyOrderQty >=0 THEN R1.BuyOrderQty ELSE 0 END - CASE WHEN R1.SaleOrderQty>=0 THEN R1.SaleOrderQty ELSE 0 END 
			AS SaleCanQty ,
		R1.SaleOrderQty ,
		R1.BuyOrderQty ,
		R1.RQty ,
		R1.CQty ,
		R1.Qty + R1.RQty - R1.CQty AS KFHQty ,
		R1.saleqty ,
		R1.GoodsCostPrice
		,
		R.UserCode,
		R.FullName,
		R.EntryCode,
		R.Standard,
		R.Type,
		R.Area,
		R.Unit1,
		R.Unit2,
		R.UnitRate1,
		R.SonNum,
		R.Leveal,
		R.Parid,
		R.unitname,
		R.baseunitname,
		R.unitrate
		,items.fullname AS itemfullname
		,k.fullname AS kfullname
		,cargo.fullname AS cargofullname
		,'+@virtualqtysql+' as virtualqty 
FROM (	SELECT  TypeId ,
				KtypeID,
				CargoID,
				ItemID,
				IsCombined,
				ProduceDate,
				ValidDate,
				GoodsNumber,	
				SUM(Qty) AS Qty ,
				SUM(Factqty) AS Factqty ,
				SUM(LendQty) AS LendQty ,
				SUM(BorrowQty) AS BorrowQty ,
				SUM(SaleCanQty) AS SaleCanQty ,
				SUM(SaleOrderQty) AS SaleOrderQty ,
				SUM(BuyOrderQty) AS BuyOrderQty ,
				SUM(RQty) AS RQty ,
				SUM(CQty) AS CQty ,
				SUM(KFHQty) AS KFHQty ,
				SUM(saleqty) AS saleqty,
				GoodsCostPrice 
		FROM #Result1 
		GROUP BY	TypeId ,
					KtypeID,
					CargoID,
					ItemID,
					IsCombined,
					ProduceDate,
					ValidDate,
					GoodsNumber,
					GoodsCostPrice
	) R1 
LEFT JOIN #Result R ON R.typeid = R1.typeid 
LEFT JOIN vWeb_ItemIDByIsCombined items ON items.id = R1.itemID AND items.IsCombined = R1.IsCombined 
LEFT JOIN Stock k ON k.typeid = R1.ktypeid  
LEFT JOIN CargoType cargo ON cargo.CargoID = R1.CargoID 
) a 
where a.Qty <> 0 or a.FactQty <> 0 or a.LendQty <> 0 or a.BorrowQty <> 0 or a.SaleCanQty  <> 0 or a.SaleOrderQty  <> 0 
	or a.BuyOrderQty  <> 0 or a.RQty  <> 0 or a.CQty  <> 0 or a.KFHQty  <> 0 or a.saleqty  <> 0 or a.virtualqty <> 0 '

--PRINT(@SQLALL)
EXEC(@SQLALL)

DROP TABLE #Result,#DGS,#VirtualStockOrder,#LEND,#GetManKTypeId,#GetManPTypeId,#GetSelectSTypeId,#CurrStocksQty

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Gp_VirtualStockStatus_Line]    Script Date: 10/19/2017 19:06:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_VirtualStockStatus_Line]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_VirtualStockStatus_Line]
GO

/****** Object:  StoredProcedure [dbo].[Gp_VirtualStockStatus_Line]    Script Date: 10/19/2017 19:06:35 ******/
SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO



/*
	作者：谢吉康
	日期：2004-11-24
	描述：重新调整了可销售订货数量
	修改标识 ##01============================================
	修改:Wang Wei 
 	时间:2010-8-31
    描述:单据选择多仓库之后,从billindex表换成相关的明细表(qp1.0)
	
	修改标识 ##02============================================
	修改:Wang Wei 
 	时间:2010-8-31
    描述:去除维修单据统计 01,添加单据（快修单）统计 02
*/

/*
	修改：赵斌
	时间：2011-08-04
	描述：为汽配3S添加领料出库单、领料退回单、救援单统计
	
	修改：徐辉
	时间：2011-08-17
	描述：添加虚拟库存列，动态计算
*/

/*
	修改：黄飞佳
	时间：2012-06-08
	描述：多单位换算动态加载单位列
*/
/*
	修改：周华
	时间：2012-12-10 09:33:58.363
	描述：目前用的优化M3.1,测试过M4更慢，而且也有其它的bug.
*/
/*
	修改：lbz
	时间：2017-10-19
	描述：定义了@DecimalDigit 取金额的小数位数
*/

CREATE PROCEDURE [dbo].[Gp_VirtualStockStatus_Line]
( 
	@OperatorID 		VARCHAR(100),  	    		--操作员ID号
	@Parid   			VARCHAR(100)='00000',       --商品的父节点号
	@szKtypeId 			VARCHAR(8000)='',           --仓库id号
	@szPeriod  			CHAR(2)='' ,                --期号
	@usercode 			VARCHAR(200)='',             --商品编号
	@fullname  			VARCHAR(200)='',             --商品名称
	@sortfield  		VARCHAR(20),                --排序字段
	@sorttype 			VARCHAR(20),                --按何种方式排序
	@showzeroqty   		VARCHAR(5),               	--是否显示库存为0的记录   1--显示   0--不显示
	@EntryCode			VARCHAR(200),				--商品条码
	@Standard			VARCHAR(200),				--商品规格
	@Type				VARCHAR(200),				--商品型号
	@Area				VARCHAR(200),				--商品产地
	@stypeid			VARCHAR(8000),
	@virtualqtysql		VARCHAR(MAX)='isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)',
	@unitconvert        VARCHAR(10)  ,               --多单位标示	
	@billtype			VARCHAR(50),
	@startdate			VARCHAR(50) ,
	@enddate			VARCHAR(50),
	@showstockstop INT =0, --是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid VARCHAR(MAX)=''
)
--@encode$--
AS
SET NOCOUNT ON

IF @Parid='00000' SET @Parid=''

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
---------------取金额小数位数---------------------------------------------------------------
DECLARE @DecimalDigit VARCHAR(1)
EXEC @DecimalDigit = Gp_GetDigit 3
---------------取金额小数位数---------------------------------------------------------------			
DECLARE @SQL VARCHAR(MAX)	 
IF @stypeid='' 
BEGIN
	SET @stypeid='00000'
END

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId VARCHAR(50))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId)
SELECT P.typeId FROM ptype P 
INNER JOIN dbo.F_ManPTypeInCategoryID(@OperatorID,@Parid,@ptypeCategoryid) F ON F.TypeId=P.typeId AND P.iscombinationproduct=0 AND P.IsService=0

CREATE CLUSTERED INDEX CIX_BID ON #GetManPTypeId(typeid)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId)
SELECT S.typeId 
FROM F_GetAllManagerBaseTypeId(@szKTypeId,4,@OperatorId) F
INNER JOIN Stock S ON F.TypeId=S.typeId AND ((@showstockstop=1 AND S.deleted=0) OR @showstockstop=0)
INNER JOIN #GetSelectSTypeId ST ON ST.TypeId=S.STypeID

CREATE CLUSTERED INDEX CIX_BID ON #GetManKTypeId(typeid)
-----------------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE 
	@Qty		VARCHAR(2000),
	@Lendqty	VARCHAR(2000),
	@Borrowqty	VARCHAR(2000),
	@RQty		VARCHAR(2000),
	@CQty		VARCHAR(2000),
	@BuyOrderQty VARCHAR(2000),
	@BuyReachQty VARCHAR(2000),
	@SaleOrderQty VARCHAR(2000),
	@SaleReachQty VARCHAR(2000),
	@UnitRate	VARCHAR(2000),
	@UnitName	VARCHAR(2000),
	@BaseUnitName VARCHAR(2000),
	@temptable  VARCHAR(2000),
	@drafBuyQty VARCHAR(2000),
	@saleDrafQty VARCHAR(2000),
	@LimitBuyQty NVARCHAR(2000),
	@LimitSaleQty NVARCHAR(2000)

SELECT  
	@Qty='o.Qty/r.unitrate',
	@Lendqty='o.Lendqty/r.unitrate',
	@Borrowqty='o.Borrowqty/r.unitrate',   
	@BuyReachQty='o.BuyReachQty/r.unitrate', 
	@RQty='o.RQty/r.unitrate',        
	@CQty='o.CQty/r.unitrate',        
	@BuyOrderQty='o.BuyOrderQty/r.unitrate', 
	@BuyReachQty='o.BuyReachQty/r.unitrate', 
	@SaleOrderQty='o.SaleOrderQty/r.unitrate',
	@SaleReachQty='o.SaleReachQty/r.unitrate',
	@drafBuyQty='o.drafBuyQty/r.unitrate', 
	@saleDrafQty='o.saleDrafQty/r.unitrate',
	@LimitBuyQty='o.LimitBuyQty/r.unitrate', 
	@LimitSaleQty='o.LimitSaleQty/r.unitrate'
	
IF @unitconvert=0--销售单位
	BEGIN
		SELECT  
			@UnitRate = 'isnull(r3.rate,1)',
			@UnitName = 'u3.fullname',
			@BaseUnitName = 'u1.fullname'
		SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('o','1,3','3')
	END
IF @unitconvert=1--采购单位
	BEGIN
		SELECT  
			@UnitRate = 'isnull(r2.rate,1)',
			@UnitName = 'u2.fullname',
			@BaseUnitName = 'u1.fullname'
		SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('o','1,2','2')
	END
IF @unitconvert=2--存货单位
	BEGIN
		SELECT
			@UnitRate = 'isnull(r4.rate,1)',
			@UnitName = 'u4.fullname',
			@BaseUnitName = 'u1.fullname'
		SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('o','1,4','4')
	END
	
IF @unitconvert=3--基本单位
	BEGIN
		SELECT
			@UnitRate = '1',
			@UnitName = 'u1.fullname',
			@BaseUnitName = 'u1.fullname'
		SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('o','1','1')
	END
--------多单位计算End---------
-----------------------------------------------------------------------------------------------------------------------------

--查询结果集
CREATE TABLE #Result(
	TypeId			varchar(50),
	UserCode		varchar(256),
	FullName  	  	varchar(256),
	EntryCode		varchar(256),
	Standard		varchar(256),
	Type			varchar(256),
	Area			varchar(256),
	Unit1			varchar(256),
	Unit2			varchar(256),
	UnitRate1		varchar(256),
	SonNum			int,
	Leveal			int,
	Parid			varchar(50),
	Qty				 NUMERIC(24, 10) ,
	Factqty			 NUMERIC(24, 10) ,
	LendQty			 NUMERIC(24, 10) ,
	BorrowQty		 NUMERIC(24, 10) ,	
	BuyOrderQty		 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	SaleCanQty		 NUMERIC(24, 10) ,
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	KFHQty			 NUMERIC(24, 10) ,
	saleqty          NUMERIC(24, 10) ,
	unitname		NVARCHAR(2000),
	baseunitname    NVARCHAR(2000),
	unitrate        NVARCHAR(2000),
	price1			NUMERIC(24, 10),
	BuyReferQty		NUMERIC(24, 10),
	SaleReferQty	NUMERIC(24, 10), 
	LimitBuyQty		NUMERIC(24, 10),
	LimitSaleQty	NUMERIC(24, 10),
	Recprice	NUMERIC(24, 10)
)
SET @SQL='
INSERT INTO #Result
(
	TypeId,
	UserCode,
	FullName,
	EntryCode,
	[Standard],
	[Type],
	Area,
	Unit1,
	Unit2,
	UnitRate1,
	SonNum,
	Leveal,
	Parid,
	Qty,
	Factqty,
	LendQty,
	BorrowQty,		
	BuyOrderQty,
	SaleOrderQty,
	SaleCanQty,
	RQty,
	CQty,
	KFHQty,
	saleqty,
	unitname,
	baseunitname,
	unitrate,
	price1,
	BuyReferQty,
	SaleReferQty,
	LimitBuyQty,
	LimitSaleQty,
	recprice
)
SELECT 
	o.TypeId,
	o.UserCode,
	o.FullName,
	o.EntryCode,
	o.Standard,
	o.Type,
	o.Area,
	isnull(o.Unit1,''''),
	isnull(o.Unit2,''''),
	o.UnitRate1,
	o.SonNum,
	o.Leveal,
	o.Parid,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	'+@UnitName+' AS unitname,
	'+@BaseUnitName+' AS baseunitname,
	'+@UnitRate+' AS unitrate,
	0,
	0,
	0,
	0,
	0,
	pp.RecAmgSTypeBuyPrice as recprice
FROM ptype o
INNER JOIN #GetManPTypeId P ON P.TypeId=o.typeId
LEFT JOIN ptype_price pp on pp.ptypeid=O.typeid AND O.baseunitid=pp.unitid'
+@temptable
	
SET @SQL+='
WHERE	
	o.SonNum=0
	and o.isservice=0
	and o.iscombinationproduct=0
	AND o.TypeID <> ''00000''
	AND o.TypeID LIKE '''+ @ParID + '%'''
		
IF(ISNULL(@usercode,'')<>'')
	SET @SQL+='AND o.UserCode LIKE ''%' + @UserCode + '%'''
	
IF(ISNULL(@FullName,'')<>'')
	SET @SQL+='AND o.FullName LIKE ''%' + @FullName + '%'''
	
IF(ISNULL(@EntryCode,'')<>'')
	SET @SQL+=' AND O.MultEntryCode LIKE ''%'+@EntryCode+'%'''
	
IF(ISNULL(@Standard,'')<>'')
	SET @SQL+='AND o.Standard LIKE ''%' + @Standard + '%'''
	
IF(ISNULL(@Type,'')<>'')
	SET @SQL+='AND o.[Type] LIKE ''%' + @Type + '%'''
		
IF(ISNULL(@Area,'')<>'')
	SET @SQL+='AND o.Area LIKE ''%' + @Area + '%'''
			
SET @SQL+='
ORDER BY
	o.UserCode'
EXEC(@SQL)

--草稿库存
CREATE TABLE #DGS
(
	PTypeId		varchar(100),
	RQty		 NUMERIC(24, 10) ,
	CQty		 NUMERIC(24, 10) 
)
INSERT INTO #DGS(PTypeId,RQty,CQty)
SELECT 
	B.PTypeId,
	ISNULL(SUM(B.RQty),0) AS RQty,
	ISNULL(SUM(B.CQty),0) AS CQty
FROM GoodsStocks_Draft B 
INNER JOIN #GetManKTypeId K on b.KtypeId=k.TypeId
INNER JOIN #GetManPTypeId P ON P.TypeId=B.PtypeId
GROUP BY B.PtypeId

--出入库
CREATE TABLE #ResultLeftTable
(
	pTypeId	VARCHAR(50),
	qty		NUMERIC(24, 10)
)
IF @billtype='' 
	BEGIN
		SET @SQL='
		INSERT INTO #ResultLeftTable(pTypeId,qty)
		SELECT 
			o.PtypeId,
			0 qty 
		FROM inoutstocktable o
		INNER JOIN #GetManPTypeId g on g.typeid=o.ptypeid
		INNER JOIN #GetManKTypeId K ON o.ktypeid=K.TypeId
		WHERE 
			BillDate BETWEEN '''+@startdate+''' AND '''+@enddate+'''  
		GROUP BY
				o.ptypeid '
	END
ELSE 
	BEGIN 
		SET @SQL='
		INSERT INTO #ResultLeftTable(pTypeId,qty)
		SELECT 
			o.PtypeId,
			SUM(CASE WHEN o.billtype in (305,11,140,141,12,215,45,142,46,160,402,403) THEN ISNULL(-o.qty,0)
				 ELSE ISNULL(o.qty,0)
				END )  
		FROM inoutstocktable o
		INNER JOIN f_split('''+@billtype+''','','') F ON F.a=O.BillType
		INNER JOIN #GetManKTypeId K ON o.ktypeid=K.TypeId 
		INNER JOIN #GetManPTypeId g on g.typeid=o.ptypeid
		WHERE 
			BillDate BETWEEN '''+@startdate+''' AND '''+@enddate+'''  
		GROUP BY
				o.ptypeid ' 
     END
 EXEC (@SQL)
 
--==============================================修改当前数量
--账面库存
CREATE TABLE #CurrStocksQty
(
	PTypeID VARCHAR(50),
	QTY  NUMERIC(24, 10) ,
	total NUMERIC(24,10)
) 
SET @SQL='
INSERT INTO #CurrStocksQty(PTypeID,QTY,total)
SELECT	
	s.PTypeID,
	ISNULL(SUM(s.Qty),0) AS Qty,
	ISNULL(SUM(s.total),0) AS total		
FROM GoodsStocks s 
INNER JOIN #GetManPTypeId P ON s.pTypeId=p.typeId
INNER JOIN #GetManKTypeId K ON s.ktypeid=K.TypeId 
WHERE
	s.PTypeID LIKE '''+ @ParID + '%''
GROUP BY
	s.PTypeID' 
EXEC(@SQL)

--修改账面库存、实际存在库存 、成本金额
SET @SQL =
'UPDATE	#Result
SET
	Qty = ISNULL('+@qty+',0),
	FactQty = ISNULL('+@qty+',0),
	price1= case when ISNULL('+@qty+',0)=0 then 0 else CAST(ISNULL(total,0) AS NUMERIC(24,10))/CAST(ISNULL('+@qty+',0) AS NUMERIC(24,10)) end 
FROM #Result R
LEFT JOIN #CurrStocksQty o ON o.PTypeID=R.TypeId'
EXEC(@SQL)

--==============================================修改借欠数量	
CREATE TABLE #LEND
(
	PTypeID VARCHAR(50),
	LendQty  NUMERIC(24, 10) ,
	BorrowQty  NUMERIC(24, 10)
) 	
SET @SQL='
INSERT INTO #LEND(PTypeID,LendQty,BorrowQty)
SELECT 	
	S.PTypeID,
	ISNULL(SUM(S.Lend-S.LendBack-saleqty),0) LendQty,
	ISNULL(SUM(Borrow-BorrowBack-buyqty),0) BorrowQty
FROM V_LENDStatus S
INNER JOIN #GetManPTypeId P ON P.TypeId=s.ptypeId  
INNER JOIN #GetManKTypeId K ON s.ktypeid=K.TypeId 
WHERE
	S.PTypeID LIKE '''+ @ParID + '%''
GROUP BY
	S.PTypeID'
EXEC(@SQL)

--FactQty=实际存在库存+借进-借出 --借进-BorrowQty 借出-LendQty
SET @SQL=	
'UPDATE	#Result
SET
	FactQty=ISNULL((ISNULL(R.Qty,0)+ISNULL('+@Borrowqty+',0)-ISNULL('+@Lendqty+',0)),0),		
	LendQty=ISNULL('+@Lendqty+',0),
	BorrowQty=ISNULL('+@Borrowqty+',0)
FROM #Result R
LEFT JOIN #LEND o ON (R.TypeID = o.PTypeID)'
EXEC(@SQL)

--已销售数量
SET @SQL='
UPDATE	#Result
SET saleqty=ISNULL(o.qty,0) 
FROM #Result R
LEFT JOIN (
	SELECT 
		ptypeid ,
		sum(CONVERT(DECIMAL(21,10),ISNULL('+@qty+',0) )) qty 
	FROM #Result r 
	LEFT JOIN #ResultLeftTable o on  R.TypeID = o.PTypeID 
	GROUP BY ptypeid
) o ON (R.TypeID = o.PTypeID)'
EXEC(@SQL)

--==============================================修改订单数量
CREATE TABLE #VirtualStockOrder
(
	PTYPEID VARCHAR(50),
	SaleOrderQty NUMERIC(24, 10),
	BuyOrderQty	 NUMERIC(24, 10),
	drafBuyQty	 NUMERIC(24, 10),
	saleDrafQty	 NUMERIC(24, 10),
	LimitBuyQty	 NUMERIC(24, 10),
	LimitSaleQty NUMERIC(24, 10)
)
SET @SQL='
INSERT INTO #VirtualStockOrder(PTypeID,SaleOrderQty,BuyOrderQty,drafBuyQty,saleDrafQty,LimitBuyQty,LimitSaleQty)
SELECT 	
	A.PTypeID,
	ISNULL(SUM(A.SaleOrderQty),0) SaleOrderQty,
	ISNULL(SUM(A.BuyOrderQty),0) BuyOrderQty,
	ISNULL(SUM(A.BuyReferQty),0) drafBuyQty,
	ISNULL(SUM(A.SaleReferQty),0) saleDrafQty,
	ISNULL(SUM(A.LimitBuyQty),0) LimitBuyQty,
	ISNULL(SUM(A.LimitSaleQty),0) LimitSaleQty
FROM GoodsStocks_Order A
INNER JOIN #GetManPTypeId P ON P.TypeId=a.PtypeId
INNER JOIN #GetManKTypeId K ON A.ktypeid=K.TypeId   
WHERE
	PTypeID LIKE '''+@ParID + '%''
GROUP BY
	PTypeID	'
EXEC(@SQL)

--SaleCanQty-可销售订货数量/SaleOrderQty-已销售订货数量/ BuyOrderQty-已采购订货数量
SET @SQL =
'UPDATE	#Result
SET	
	SaleCanQty=(ISNULL(R.qty,0)+(CASE WHEN ISNULL('+@BuyOrderQty+',0)-ISNULL('+@LimitBuyQty+',0)>0 THEN ISNULL('+@BuyOrderQty+',0)-ISNULL('+@LimitBuyQty+',0) ELSE 0 END)-ISNULL('+@saleDrafQty+',0)+ISNULL('+@drafBuyQty+',0)-(CASE WHEN ISNULL('+@SaleOrderQty+',0)-ISNULL('+@LimitSaleQty+',0)>0 THEN ISNULL('+@SaleOrderQty+',0)-ISNULL('+@LimitSaleQty+',0) ELSE 0 END)), 			 
	SaleOrderQty=CASE WHEN ISNULL('+@SaleOrderQty+',0)-ISNULL('+@LimitSaleQty+',0)>0 THEN ISNULL('+@SaleOrderQty+',0)-ISNULL('+@LimitSaleQty+',0) ELSE 0 END,
	BuyOrderQty=CASE WHEN ISNULL('+@BuyOrderQty+',0)-ISNULL('+@LimitBuyQty+',0)>0 THEN ISNULL('+@BuyOrderQty+',0)-ISNULL('+@LimitBuyQty+',0) ELSE 0 END,
	BuyReferQty=ISNULL('+@drafBuyQty+',0),
	SaleReferQty=ISNULL('+@saleDrafQty+',0)
FROM #Result R
LEFT JOIN #VirtualStockOrder o ON o.PTypeID=R.TypeID'
EXEC(@SQL)

--==============================================修改草稿数量
--RQty-草稿入库 CQty-草稿出库 KFHQty-可发货数量
SET @SQL ='
UPDATE #Result
SET	
	RQty = ISNULL('+@RQty+',0),
	CQty = ISNULL('+@CQty+',0),
	KFHQty = ISNULL(R.Qty,0)+ISNULL('+@RQty+',0)-ISNULL('+@CQty+',0)
FROM #Result R
LEFT JOIN #DGS o ON R.TypeId = o.PTypeId'
EXEC(@SQL)


-- ==== 查询结果集 ====
SET @SQL = '
	SELECT	A.*,case when ISNULL(A.virtualqty,0)=0 THEN 0 ELSE CAST(ISNULL(A.costtotal,0) AS NUMERIC(24,10))/CAST(ISNULL(A.virtualqty,0)AS NUMERIC(24,10)) END  AS price
	FROM	(
				SELECT	*,
						'+@virtualqtysql+' as virtualqty,
						round(('+@virtualqtysql+')*price1,
						'+@DecimalDigit+') costtotal
				FROM	#Result 
	) A '
	
	
--是否显示为0	
IF @showzeroqty = 0 
BEGIN
	SET @SQL = @SQL + ' WHERE A.virtualqty <> 0'							  
END

IF @sortfield = ''
	SET @SQL = @SQL + ' ORDER BY A.UserCode' +' '+@sorttype;
ELSE
	SET @SQL = @SQL + ' ORDER BY A.'+@sortfield +' '+@sorttype;

--PRINT @SQL
EXEC(@SQL)

DROP TABLE #Result,#DGS,#VirtualStockOrder,#LEND,#GetManKTypeId,#GetManPTypeId,#GetSelectSTypeId,#CurrStocksQty,#ResultLeftTable


GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_VirtualStockStatusDetail]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_VirtualStockStatusDetail]
GO


/*	
	作者：张陈仁
	时间：2011-08-18
	描述：虚拟库明细帐本
*/
------------------------------------------------------------------------------
	--修改: 李海洋
	--日期：2012-08-10
	--描述：添加经手人筛选, 
------------------------------------------------------------------------------
CREATE PROCEDURE Gp_VirtualStockStatusDetail
    (
      @OperatorID VARCHAR(100) ,  	     	--操作员ID号 
      @Parid VARCHAR(100) = '00000' ,   --商品的父节点号
      @szKtypeId VARCHAR(8000) = '' ,       --仓库id号
      @sortfield VARCHAR(20) ,            --按何种方式排序
      @EntryCode VARCHAR(200) ,			--商品条码
      @Standard VARCHAR(200) ,			--商品规格
      @Ptypeid VARCHAR(200) ,			--商品型号
      @Area VARCHAR(200) ,			--商品产地
      @BillType VARCHAR(50) ,            --单据类型
      @stypeid VARCHAR(8000) ,		    --分支机构id
      @Order VARCHAR(200) = 'ORDER BY P.UserCode,p.FullName' ,           --排序
      @SelectType VARCHAR(50) ,            --明细报表类型
      @startdate VARCHAR(30) ,            --起始时间
      @enddate VARCHAR(30) ,              --结束时间
      @eTypeId VARCHAR(8000) ,			--经手人
      @isEtypeRightEnable BIT,		--库存明细表经手人限制是否启用
      @showstockstop INT =0, --是否显示停用仓库数据 1为不显示 0为显示
      @ptypeCategoryid VARCHAR(max)=''
    )
--@encode$--
AS 
    SET NOCOUNT ON
    SET ANSI_WARNINGS OFF
    DECLARE @SQL VARCHAR(8000)  

--------------------------------------------------------------权限检查-------------------------------------------------------
    IF @OperatorID IS NULL 
        RETURN 1
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT
    IF @Re <> 0 
        RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


--选择分支机构
    CREATE TABLE #GetSelectSTypeId ( TypeId VARCHAR(100) )
    INSERT  INTO #GetSelectSTypeId
            ( TypeId
            )
            SELECT  typeid
            FROM    F_GetAllManagerBaseTypeId(@stypeid, 11, @OperatorID)
	
-- 经手人条件筛选表 Add by Haiyang, Li 2012-08-10
--****************
    --CREATE TABLE #GetSelETypeId ( TypeId VARCHAR(100) )
    --INSERT  INTO #GetSelETypeId
    --        ( TypeId
    --        )
    --        SELECT  typeid
    --        FROM    F_GetAllManagerBaseTypeId(@eTypeId, 3, @OperatorID)
    
    CREATE TABLE #etypelist(typeid VARCHAR(50))
	INSERT INTO #etypelist
	        ( typeid )
	SELECT a AS typeid FROM dbo.f_split(@eTypeId, ',') ORDER BY typeid
	
	CREATE TABLE #GetSelETypeId ( TypeId VARCHAR(100) )
	
	DECLARE @totalcount INT=(SELECT COUNT(typeid) FROM #etypelist)
	DECLARE @rownum INT=1
	DECLARE @tempEtype VARCHAR(50)
	
	WHILE @rownum<=@totalcount
	BEGIN
		SET @tempEtype=(SELECT TOP 1 typeid FROM #etypelist)
		
		INSERT INTO #GetSelETypeId(TypeId)
		SELECT  f.TypeId
		FROM F_GetAllManagerBaseTypeId(@tempEtype, 3, @OperatorID) f
		where not exists (select 1 from #GetSelETypeId g where g.typeid=f.typeid )
		
		DELETE TOP(1) FROM #etypelist
		SET @rownum=@rownum + 1
	END
--****************

--商品
  /*  CREATE TABLE #GetManPTypeId
        (
          TypeId VARCHAR(100) ,
          EntryCode VARCHAR(100) ,
          [Standard] VARCHAR(100) ,
          [Type] VARCHAR(20) ,
          Area VARCHAR(30)
        )
    INSERT  INTO #GetManPTypeId
            ( TypeId ,
              EntryCode ,
              [Standard] ,
              [Type] ,
              Area
            )
            SELECT  p.typeId ,
                    p.EntryCode ,
                    p.Standard ,
                    p.Type ,
                    p.Area
            FROM    ptype p
                    INNER JOIN F_GetManDetailPType(@OperatorID) mp ON mp.TypeId = p.typeId	 */

--往来单位
    CREATE TABLE #GetManBTypeId ( TypeId VARCHAR(100) )
    INSERT  INTO #GetManBTypeId
            ( TypeId
            )
            SELECT  *
            FROM    F_GetManDetailBType(@OperatorID)

--职员
    CREATE TABLE #GetManETypeId ( TypeId VARCHAR(100) )
    INSERT  INTO #GetManETypeId
            ( TypeId
            )
            SELECT  *
            FROM    F_GetManDetailEType(@OperatorID)

--仓库
    CREATE TABLE #GetManSelKTypeId ( TypeId VARCHAR(100) )
    	IF  @showstockstop=0
    INSERT  INTO #GetManSelKTypeId
            ( TypeId
            )
            SELECT  sk.TypeId
            FROM    F_BaseGetAllManagerBaseTypeId(@szKTypeId, 4, @OperatorID) sk
                    INNER JOIN ( SELECT Typeid
                                 FROM   stock
                                 WHERE  STypeID IN ( SELECT TYPEID
                                                     FROM   #GetSelectSTypeId )
                               ) s ON sk.TypeId = s.TypeId
ELSE
    INSERT  INTO #GetManSelKTypeId
            ( TypeId
            )
            SELECT  sk.TypeId
            FROM    F_BaseGetAllManagerBaseTypeId(@szKTypeId, 4, @OperatorID) sk
                    INNER JOIN ( SELECT Typeid
                                 FROM   stock
                                 WHERE  STypeID IN ( SELECT TYPEID
                                                     FROM   #GetSelectSTypeId ) AND deleted=0
                               ) s ON sk.TypeId = s.TypeId

   
   
   CREATE TABLE #GetManPTypeAll
   (
		typeid VARCHAR(50),
		usercode VARCHAR(200),
		fullname VARCHAR(200),
		baseUnitId INT
   )
    INSERT INTO #GetManPTypeAll
    SELECT  b.TypeId,b.UserCode,b.FullName,b.baseUnitId
    FROM    dbo.F_ManPTypeInCategoryID(@OperatorID,@Ptypeid,@ptypeCategoryid) a,
			ptype  b
    WHERE a.TypeId=b.typeId
 
    IF @szKtypeId = ''
        OR @szKtypeId = '00000' 
        SELECT  @szKtypeId = '%'	-- 全部仓库

--草稿入库、出库明细
    IF @SelectType = 'rkqty'
        OR @SelectType = 'ckqty' 
        OR @SelectType='crkqty'
        BEGIN
	--计算普通单据草稿库存
            SELECT  BillNumberId ,
                    BillType ,
                    KTypeId ,
                    EtypeId ,
                   DealBTypeID AS  BtypeId ,
                    StypeId ,
                    BillCode ,
                    BillDate ,
                    Comment ,
                    KTypeId2
            INTO    #BillIndex
            FROM    BillIndex
            WHERE   BillType IN ( 34, 6, 161, 11, 45, 160, 17, 21, 16, 9, 14,
                                  144, 146, 140, 142, 305, 126, 139, 183, 187,
                                  188, 201, 202 ,215,400,401,402,403,12,46)
                    AND Draft = 1
                    AND IfWx = 0
                    AND AdPriceType=0

	--维修单据草稿库存
            SELECT  BillNumberId ,
                    BillType ,
                    KTypeId ,
                    EtypeId ,
                  DealBTypeID as   BtypeId ,
                    StypeId ,
                    BillCode ,
                    BillDate ,
                    Comment ,
                    KTypeId2
            INTO    #WxBillIndex
            FROM    BillIndex
            WHERE   BillType IN ( 166, 168, 172, 173, 174, 178, 191, 196, 197 )
                    AND Draft = 1
                    
	--计算门店单据草稿库存
            SELECT  BillNumberId ,
                    BillType ,
                    KTypeId ,
                    ApplyEtypeId AS etypeid ,
                    StypeId ,
                    BillCode ,
                    BillDate ,
                    Comment ,
                    inKTypeId 
            INTO    #PosAllotApplyBillIndex
            FROM    dbo.PosAllotApplyBillIndex
            WHERE   BillType IN (327,328)
                    AND Draft = 1
                    
	--草稿库存
            CREATE TABLE #DraftGoodsStocks
                (
                  PTypeId VARCHAR(100) ,
                  rKTypeId VARCHAR(100) ,
                  cktypeid	VARCHAR(200),
                  EtypeId VARCHAR(100) ,
                  BtypeId VARCHAR(100) ,
                  StypeId VARCHAR(100) ,
                  BillNumberId VARCHAR(200) ,
                  BillCode VARCHAR(100) ,
                  BillType VARCHAR(50) ,
                  BillDate DATETIME ,
                  RQty  NUMERIC(24, 10)  ,
                  CQty  NUMERIC(24, 10)  ,
                  Comment VARCHAR(256) ,
                  Type_t INT ,         ---出入库标示 0入库、1出库 
                  customid INT 
	              )
            INSERT  INTO #DraftGoodsStocks
                    ( PTypeId ,
                      rKTypeId ,
                      cktypeid,
                      EtypeId ,
                      BtypeId ,
                      StypeId ,
                      BillNumberId ,
                      BillCode ,
                      BillType ,
                      BillDate ,
                      RQty ,
                      CQty ,
                      Comment ,
                      Type_t,
                      customid
                    ) --Qty,TotalMoney,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty,
                    SELECT  B.PTypeId ,
                            B.rKTypeId ,
                            b.cktypeid,
                            B.EtypeId ,
                            B.BtypeId ,
                            B.StypeId ,
                            B.BillNumberId ,
                            B.BillCode ,
                            B.BillType ,
                            B.BillDate ,
                            B.RQty ,
                            B.CQty ,
                            B.Comment ,
                            B.Type_t,customid
                    FROM    (	
			    ---入库
                              SELECT    S.PTypeId ,
                                        S.KTypeId AS rKTypeId,
                                        '' AS cktypeid ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                        s.id AS customid
                              FROM      BuyBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        s.KTypeID,
                                        S.KTypeID2 ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      BuyGoodsExchangeBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.InOrOut = 'I'
                              UNION ALL
                              SELECT    S.PTypeId ,
										s.KTypeID,
                                        S.KTypeID2 ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      SaleGoodsExchangeBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.InOrOut = 'I'
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId2 ,
                                        s.KTypeId,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      MoveBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeId2
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId2 ,
                                        s.KTypeId,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      MoveBjBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeId2
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      DisassembleBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.InOrOut = 'I'
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        B.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      OverflowBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = B.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      CommissionBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND B.BillType = 144
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      CommissionBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND B.BillType = 142
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        s.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      GiveMeBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = s.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        B.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      Wx_Bill_OUT S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = B.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      Qp_PickingBackBill S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.Ktypeid2 ,
                                        s.Ktypeid,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      STypeMoveBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.Ktypeid2
                                        AND S.BillType = 188
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      OtherInOutBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.BillType = 201
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      SaleBackBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                               UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      dbo.PT_Combin_SaleBackBillDetail S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        i.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      dbo.RetailBackBill S ,
                                        #BillIndex B ,
                                        dbo.BillIndex i,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = i.KTypeID
                                        AND s.BillNumberId=i.BillNumberId  
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        i.KTypeId ,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        S.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      AppraisalBill S ,
                                        #BillIndex B ,
                                        dbo.BillIndex i,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = i.KTypeID
                                        AND s.BillNumberId=i.BillNumberId         
							UNION ALL
                              SELECT    S.PTypeId ,
                                        S.KTypeId,
                                        '',
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        s.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                           s.id AS customid
                              FROM      SendBackBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID  
							UNION ALL
                              SELECT    S.PTypeId ,
                                        S.inktypeid,
                                        '', 
                                        B.EtypeId ,
                                        ''  , --btypeid
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        s.Qty AS RQty ,
                                        0 AS CQty ,
                                        B.Comment ,
                                        0 AS Type_t,
                                        s.id AS customid
                              FROM      dbo.DeliveryBackBill S ,
                                        #PosAllotApplyBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.inktypeid
				--出库部分
                              UNION ALL
                                   SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      integralexchangebill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                
                              UNION ALL
                              SELECT    S.PTypeId ,
										'',	
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      SaleBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                               UNION ALL
                              SELECT    S.PTypeId ,
										'',	
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      dbo.PT_Combin_SaleBillDetail S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        s.KTypeID2,
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      BuyGoodsExchangeBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.InOrOut = 'O'
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        s.KTypeID2,
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      SaleGoodsExchangeBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.InOrOut = 'O'
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        s.KTypeId2,
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      MoveBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeId
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        s.KTypeId2,
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      MoveBjBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeId
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      DisassembleBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.InOrOut = 'O'
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        B.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      LoseBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = B.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      CommissionBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND B.BillType = 146
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      CommissionBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND B.BillType = 140
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        B.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      RetailBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = B.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        s.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      GiveBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = s.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        B.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      Wx_Bill_SELF S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = B.KTypeID
                                        AND S.InOrOut = 'O'
                                        AND S.WxProperty = 0
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        B.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      Wx_Bill_REPLACE S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = B.KTypeID
                                        AND S.WxProperty = 0
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        B.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      Wx_Bill_GoTo S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = B.KTypeID
                                        AND S.InOrOut = 'O'
                                        AND S.WxProperty = 0
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        B.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      Wx_Bill_IN S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = B.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      QP_QuickRepairBill_PType S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      Qp_SuccorBill_PType S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      Qp_PickingBill S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      IntegralExchangeBill S ,
                                        #WxBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        s.Ktypeid2,
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      STypeMoveBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.BillType = 187
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        S.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      OtherInOutBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
                                        AND S.BillType = 202
                              UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        s.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      BuyBackBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
							UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        s.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                           s.id AS customid
                              FROM      AppraisalBackBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
							UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        S.KTypeId ,
                                        B.EtypeId ,
                                        B.BtypeId ,
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        s.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                        s.id AS customid
                              FROM      SendBill S ,
                                        #BillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.KTypeID
							UNION ALL
                              SELECT    S.PTypeId ,
                                        '',
                                        s.ktypeidout, 
                                        B.EtypeId ,
                                        ''  , --btypeid
                                        B.StypeId ,
                                        B.BillNumberId ,
                                        B.BillCode ,
                                        B.BillType ,
                                        B.BillDate ,
                                        0 AS RQty ,
                                        s.Qty AS CQty ,
                                        B.Comment ,
                                        1 AS Type_t,
                                        s.id AS customid
                              FROM      dbo.DeliveryBill S ,
                                        #PosAllotApplyBillIndex B ,
                                        #GetManSelKTypeId K
                              WHERE     B.BillNumberId = S.BillNumberId
                                        AND K.TypeId = S.ktypeidout
                            ) B
                    WHERE   B.BillDate >= '' + @startdate + ''
                            AND B.BillDate <= '' + @enddate + ''
            SET @SQL = '
            SELECT B.PTypeId,
	                 B.rKTypeId,
	                 b.cktypeid,
	                 B.EtypeId,
	                 B.BtypeId,
	                 B.StypeId,
	                 B.BillNumberId,
	                 B.BillCode,
	                 B.BillType,
	                 B.BillDate,
	                 B.Comment, 
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head, 
					SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,
					SysDiy24_head,SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,
					SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
					SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,              
                     b.rqty AS rqty,
                     b.cqty AS cqty,
					ISNULL(pr.RecAmgSTypeBuyPrice,0) as recprice 
			 FROM #DraftGoodsStocks b
			 INNER JOIN #GetManPTypeAll P ON p.typeid=b.ptypeid
			 INNER JOIN #GetSelectSTypeId s  ON  B.stypeID=s.typeid 
			 LEFT JOIN dbo.PType_Price pr ON p.typeid=pr.PTypeID AND pr.UnitID=p.baseUnitId'
		     IF @EtypeID <> '00001' AND @isEtypeRightEnable = 1	    --经手人权限
					SET @SQL = @SQL+ ' INNER JOIN #GetSelETypeId ET ON ET.TypeId = B.EtypeId'
			SET @SQL = @SQL+ '						
			 left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
			 left join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND b.customid=csdetail.Detailid
			 where 1=1 '
		    IF ( @SelectType = 'rkqty' ) 
                SET @SQL += ' AND B.Type_t=0 '--草稿入库
            IF ( @SelectType = 'ckqty' ) 
                SET @SQL += ' AND B.Type_t=1 '--草稿出库
                  
            SET @SQL += ' ' + @Order + ''	
            
			--PRINT(@SQL)						 
            EXEC(@SQL)
            
           
            DROP TABLE #BillIndex,#WxBillIndex,#DraftGoodsStocks,#PosAllotApplyBillIndex
        END
		
		
/******************************************************************************************************************/

--借出、借进科目
    IF @SelectType = 'jj'
        OR @SelectType = 'jc' 
        OR @selecttype='jjjc'
        BEGIN
            CREATE TABLE #LendTable
                (
                  BillNumberId VARCHAR(50) ,   --单据ID
                  BillCode VARCHAR(100) ,  --单据编号
                  BillDate DATETIME ,      --单据日期
                  BillType VARCHAR(50) ,   --单据类型
                  EtypeId VARCHAR(50) ,   --职员ID
                  BtypeId VARCHAR(50) ,   --往来单位ID
                  PtypeId VARCHAR(50) ,   --商品ID
                  StypeId VARCHAR(50) ,   --分支机构ID
                  KtypeId VARCHAR(50) ,   --仓库ID
                  Qty  NUMERIC(24, 10)  , --数量
                  Comment VARCHAR(256),   --摘要
                  customid int
	              )
	
            DECLARE @tempSql VARCHAR(MAX)
	
            SET @tempSql = '
			   INSERT INTO #LendTable
					(
					   BillNumberId,
					   BillCode,
					   BillDate,
					   BillType,
					   EtypeId,
					   BtypeId,
					   PtypeId,
					   StypeId,
					   Ktypeid,
					   Qty,
					   Comment,
					   customid
					)
			   SELECT  B.BillNumberId,
					   I.BillCode,
					   I.BillDate,
					   I.BillType,
					   I.etypeid,
					   I.btypeid,
					   B.PtypeId,
					   B.StypeId,
					   I.ktypeid,
					   B.Qty,
					   I.Comment ,
					   b.id AS customid
			   FROM  dbo.LendBill B 
			   INNER JOIN dbo.LendIndex I ON B.BillNumberId=I.BillNumberId AND I.RedWord=0 '
 SET @tempSql = @tempSql + ' 
            WHERE I.BillType IN (' + @BillType+ ') 
				AND I.BillDate>=''' + @startdate + ''' 
                AND I.BillDate<=''' + @enddate + ''' '
     --PRINT(@tempSql)
            EXEC (@tempSql)	
	 
       SET @SQL = 'SELECT P.typeId,
					  P.UserCode,
					  P.FullName,
					  B.BillNumberId,
					  B.BillCode,
					  B.BillType,
					  B.BillDate,
					  B.EtypeId,
					  B.BtypeId,
					  B.PtypeId,
					  B.StypeId,
					   '
            IF @SelectType = 'jc' 
                SET @SQL = @SQL + 'B.ktypeid as cktypeid,'''' as rktypeid,ISNULL(-B.Qty,0) AS cQty,0 as rqty, '
            IF @SelectType = 'jj' 
                SET @SQL = @SQL + ' '''' as cktypeid ,b.ktypeid as rktypeid, 0 as cqty,ISNULL(B.Qty,0) AS rQty, '
             IF @selecttype='jjjc'
                 SET @SQL = @SQL + ' CASE WHEN b.billtype=87 OR b.billtype=72 THEN B.ktypeid  ELSE '''' END  as cktypeid, CASE WHEN b.billtype=71 OR b.billtype=88 THEN b.ktypeid  ELSE '''' END as rktypeid,CASE WHEN b.billtype=87  OR b.billtype=72 THEN ISNULL(-B.Qty,0)  ELSE 0 END AS cQty ,
					  CASE WHEN b.billtype=71 OR b.billtype=88 THEN ISNULL(B.Qty,0)  else 0 end AS rQty,'  
            SET @SQL = @SQL + 'B.Comment, 
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head, 
					SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,
					SysDiy24_head,SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,
					SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
					SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
					ISNULL(pr.RecAmgSTypeBuyPrice,0) as recprice  
			   FROM #GetManPTypeAll P 
			   inner JOIN #LendTable B ON P.typeId=B.PtypeId
			   left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
			   left join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND b.customid=csdetail.Detailid
			   left	JOIN dbo.PType_Price pr ON p.typeid=pr.PTypeID AND pr.UnitID=p.baseUnitId
				
			   '
            
            IF @szKtypeId <> ''
                OR @MKTypeID = -99999 
                SET @SQL = @SQL
                    + ' INNER JOIN #GetManSelKTypeId k ON B.ktypeid=k.TypeId '
                    + CHAR(13)
            IF NOT ( @stypeid = ''
                     AND @MStypeid = '00000'
                   ) 
                SET @SQL = @SQL
                    + ' INNER JOIN #GetSelectSTypeId s  ON  B.stypeID=s.typeid '
                    + CHAR(13)
            IF @EtypeID <> '00001' --经手人权限
                AND @isEtypeRightEnable = 1 
                SET @SQL = @SQL
                    + ' INNER JOIN #GetSelETypeId ET ON ET.TypeId = B.EtypeId '
                    + CHAR(13)
            SET @SQL = @SQL + @Order + ' '               
	PRINT(@SQL)
            EXEC(@SQL)
            DROP TABLE #LendTable
        END
/******************************************************************************************************************/
---已采购订货数量,已销售订货数量
    IF ( @SelectType = 'ycgdhqty'
         OR @SelectType = 'yxsdhqty'
       ) 
        BEGIN
            CREATE TABLE #VirtualStockOrderStatus
                (
                  BillNumberId VARCHAR(50) ,   --单据ID
                  BillCode VARCHAR(100) ,  --单据编号
                  BillDate DATETIME ,      --单据日期
                  BillType INT ,           --单据类型
                  EtypeId VARCHAR(50) ,   --职员ID
                  BtypeId VARCHAR(50) ,   --往来单位ID
                  PtypeId VARCHAR(50) ,   --商品ID
                  StypeId VARCHAR(50) ,   --分支机构ID
                  KtypeId VARCHAR(50) ,   --仓库ID
                  buyorderqty  NUMERIC(24, 10)  , --已采购订货数量
                  saleorderqty  NUMERIC(24, 10)  , --已销售订货数量
                  TaxPrice  NUMERIC(24, 10)  , --含税单价
                  TaxTotal  NUMERIC(24, 10)  , --含税金额
                  ReachQty  NUMERIC(24, 10)  , --已完成订单数量
                  ReachTaxTotal  NUMERIC(24, 10)  ,
                  Comment VARCHAR(256),   --摘要	
                  customid int,
                  drafBuyQty  NUMERIC(24, 10),	
                  drafBuyTaxTotal  NUMERIC(24, 10),
                  saleDrafQty  NUMERIC(24, 10),	
                  saleDrafTaxTotal  NUMERIC(24, 10)	
                )
   
            INSERT  INTO #VirtualStockOrderStatus
                    ( BillNumberId ,
                      BillCode ,
                      BillDate ,
                      BillType ,
                      EtypeId ,
                      BtypeId ,
                      PtypeId ,
                      StypeId ,
                      KtypeId ,
                      saleorderqty ,
                      buyorderqty ,
                      TaxPrice ,
                      TaxTotal ,
                      ReachQty ,
                      ReachTaxTotal ,
                      Comment,
                      drafBuyQty,
                      drafBuyTaxTotal,
                      saleDrafQty,
                      saleDrafTaxTotal
                    )
                    SELECT  b.*
                    FROM    ( SELECT    c.BillNumberId ,
                                        c.BillCode ,
                                        c.BillDate ,
                                        c.BillType ,
                                        c.EtypeId ,
                                        c.BtypeId ,
                                        c.PtypeId ,
                                        c.StypeId ,
                                        c.KtypeId ,
                                        CASE c.billtype
                                          WHEN 300 THEN c.qty
                                           WHEN 313 THEN c.qty
                                          ELSE NULL
                                        END AS SaleOrderQty ,
                                        CASE c.billtype
                                          WHEN 301 THEN c.qty
                                          ELSE NULL
                                        END AS BuyOrderQty ,
                                        c.TaxPrice ,
                                        c.TaxTotal ,
                                        c.ReachQty ,
                                        c.ReachTaxTotal ,
                                        c.Comment,
                                        c.drafBuyQty,
                                        c.drafBuyTaxTotal,
                                        c.saleDrafQty,
                                        c.saleDrafTaxTotal
                                  
                              FROM      ( SELECT    a.BillNumberId ,
                                                    a.BillCode ,
                                                    a.BillDate ,
                                                    a.BillType ,
                                                    a.EtypeId ,
                                                    a.dealBtypeId as btypeid,
                                                    b.PtypeId ,
                                                    b.StypeId ,
                                                    b.KtypeId ,
                                                    SUM(b.qty)qty ,
                                                   SUM(b.ReachQty ) ReachQty ,
                                                   SUM(b.ReachTaxTotal) ReachTaxTotal ,
                                                    b.TaxPrice ,
                                                    SUM(b.TaxTotal ) TaxTotal ,
                                                    a.Comment,
													SUM(ISNULL(buy.Qty,0))	drafBuyQty,
													SUM(ISNULL(buy.Qty,0)*b.TaxPrice) drafBuyTaxTotal,
													SUM(ISNULL(sale.Qty,0))	saleDrafQty,
													SUM(ISNULL(sale.Qty,0)*b.TaxPrice) saleDrafTaxTotal
                                                    
                                          FROM      orderindex a
                                          INNER JOIN orderbill b ON a.billnumberid = b.billnumberid
                                          LEFT JOIN (SELECT OrderID,ISNULL(SUM(Qty),0) Qty FROM (
													SELECT B.OrderID,B.Qty
													FROM BuyBill B 
													WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=B.BillNumberId)
													UNION ALL
													SELECT B.OrderID,B.Qty
													FROM dbo.AppraisalBill b 
													WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=B.BillNumberId)
													UNION ALL
													SELECT B.OrderID,b.Qty
													FROM dbo.commissionbill b 
													WHERE 
														b.[type]=144
														AND NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=b.BillNumberId)
													) Bi GROUP BY Bi.OrderID
											) buy ON buy.OrderID=B.OrderID
										LEFT JOIN (SELECT OrderID,ISNULL(SUM(Qty),0) Qty FROM (
													SELECT BB.OrderID,BB.Qty
													FROM SaleBill BB 
													WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=BB.BillNumberId)
													UNION ALL
													SELECT BB.OrderID,BB.Qty
													FROM SendBill BB 
													WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=BB.BillNumberId)
													UNION ALL
													SELECT BB.OrderID,BB.Qty
													FROM commissionbill BB 
													WHERE 
														BB.[type]=140
														AND NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=BB.BillNumberId)
													 ) S GROUP BY S.OrderID
												) sale ON sale.OrderID=B.OrderID
                                          WHERE     
                                                    A.BillOver = 0
                                                    AND b.BillOver = 0
                                                    AND A.OrderState <> 1
                                          GROUP BY  b.ptypeid ,
                                                    b.ktypeid ,
                                                    a.billtype ,
                                                    a.dealBtypeId ,
                                                    a.BillNumberId ,
                                                    a.BillCode ,
                                                    a.BillDate ,
                                                    a.BillType ,
                                                    a.EtypeId ,
                                                    b.StypeId ,    
                                                    b.TaxPrice ,
                                                    a.Comment
                                           UNION ALL
                                           SELECT    a.BillNumberId ,
                                                    a.BillCode ,
                                                    a.BillDate ,
                                                    a.BillType ,
                                                    a.EtypeId ,
                                                    a.dealBtypeId as btypeid,
                                                    b.PtypeId ,
                                                    b.StypeId ,
                                                    b.KtypeId ,
                                                    SUM(b.qty)qty ,
                                                   SUM(b.ReachQty ) ReachQty ,
                                                   SUM(b.ReachTaxTotal) ReachTaxTotal ,
                                                    b.TaxPrice ,
                                                    SUM(b.TaxTotal ) TaxTotal ,
                                                    a.Comment,
													0 drafBuyQty,
													0 drafBuyTaxTotal,
													SUM(ISNULL(CS.Qty,0)) saleDrafQty,
													SUM(ISNULL(CS.Qty,0)*b.TaxPrice) saleDrafTaxTotal
                                          FROM      orderindex a
                                          INNER JOIN dbo.PT_Combin_OrderBillDetail b ON a.billnumberid = b.billnumberid
                                          LEFT JOIN (
													SELECT CS.OrderID,ISNULL(SUM(Qty),0) Qty
													FROM PT_Combin_SaleBillDetail CS 
													WHERE NOT EXISTS(SELECT TOP 1 1 FROM InOutstocktable WHERE BillNumberId=CS.BillNumberId)
													GROUP BY CS.OrderID) CS ON CS.OrderID=B.OrderID
                                          WHERE    
                                                    A.BillOver = 0
                                                    AND b.BillOver = 0
                                                    AND A.OrderState <> 1
                                          GROUP BY  b.ptypeid ,
                                                    b.ktypeid ,
                                                    a.billtype ,
                                                    a.dealBtypeId ,
                                                    a.BillNumberId ,
                                                    a.BillCode ,
                                                    a.BillDate ,
                                                    a.BillType ,
                                                    a.EtypeId ,
                                                    b.StypeId ,    
                                                    b.TaxPrice ,
                                                    a.Comment
                                        ) c
                              WHERE     c.BillDate >= '' + @startdate + ''
                                        AND c.BillDate <= '' + @enddate + ''
                            ) b                       
            IF ( @SelectType = 'ycgdhqty' )--采购订单
                SET @BillType = '301'
            IF ( @SelectType = 'yxsdhqty' )--销售订单
                SET @BillType = '300,313' 
                
            SET @SQL = 'SELECT P.typeId,
					P.UserCode,
					P.FullName,
					B.BillNumberId,
					B.BillCode,
					B.BillType,
					B.BillDate,
					B.EtypeId,
					B.BtypeId,
				    B.PtypeId,
					B.StypeId,
					B.ktypeid,
					B.Comment,
					B.TaxPrice,
					b.ReachQty as cgxsqty,'
					
			IF @BillType = '301' 
				SET @SQL+='CASE WHEN ISNULL(B.TaxTotal,0)-ISNULL(B.ReachTaxTotal,0)-ISNULL(B.drafBuyTaxTotal,0)>0 THEN ISNULL(B.TaxTotal,0)-ISNULL(B.ReachTaxTotal,0)-ISNULL(B.drafBuyTaxTotal,0) ELSE 0 END AS TaxTotal,'
			ELSE IF @BillType='300,313'
				SET @SQL+='CASE WHEN ISNULL(B.TaxTotal,0)-ISNULL(B.ReachTaxTotal,0)-ISNULL(B.saleDrafTaxTotal,0)>0 THEN ISNULL(B.TaxTotal,0)-ISNULL(B.ReachTaxTotal,0)-ISNULL(B.saleDrafTaxTotal,0) ELSE 0 END AS TaxTotal,'
			ELSE 
				SET @SQL+='ISNULL(B.TaxTotal,0)-ISNULL(B.ReachTaxTotal,0) AS TaxTotal,'
			
			SET @SQL+='
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head, 
					SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,
					SysDiy24_head,SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,
					SysDiy31_head,SysDiy32_head'
            IF @BillType = '300,313' 
                SET @SQL += ' ,CASE WHEN ISNULL(B.SaleOrderQty,0)-ISNULL(B.ReachQty,0)-ISNULL(B.saleDrafQty,0)>0 THEN ISNULL(B.SaleOrderQty,0)-ISNULL(B.ReachQty,0)-ISNULL(B.saleDrafQty,0) ELSE 0 END as qty ,b.SaleOrderQty as orderqty'
            IF @BillType='301'
                SET @SQL += ' ,CASE WHEN ISNULL(B.BuyOrderQty,0)-ISNULL(B.ReachQty,0)-ISNULL(B.drafBuyQty,0)>0 THEN ISNULL(B.BuyOrderQty,0)-ISNULL(B.ReachQty,0)-ISNULL(B.drafBuyQty,0) ELSE 0 END as qty ,b.BuyOrderQty as orderqty'
            SET @SQL += ' ,ISNULL(pr.RecAmgSTypeBuyPrice,0) as recprice  
				FROM #GetManPTypeAll P 
              inner JOIN #VirtualStockOrderStatus B ON P.typeId=b.ptypeId
              left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
			  left JOIN dbo.PType_Price pr ON p.typeid=pr.PTypeID AND pr.UnitID=p.baseUnitId
              '
         
            IF @szKtypeId <> ''
                OR @MKTypeID = -99999 
                SET @SQL = @SQL
                    + ' INNER JOIN #GetManSelKTypeId k ON B.ktypeid=k.TypeId '
                    + CHAR(13)
            IF NOT ( @stypeid = ''
                     AND @MStypeid = '00000'
                   ) 
                SET @SQL = @SQL
                    + ' INNER JOIN #GetSelectSTypeId s  ON  B.stypeID=s.typeid '
                    + CHAR(13)
            IF @EtypeID <> '00001' --经手人权限
                AND @isEtypeRightEnable = 1 
                SET @SQL = @SQL
                    + ' INNER JOIN #GetSelETypeId ET ON ET.TypeId = B.EtypeId '
                    + CHAR(13)
            SET @SQL = @SQL + '    WHERE  B.BillType in(' + @billtype + ') 
									   ' + @Order + ' '
									   
            EXEC(@SQL)
            DROP TABLE #VirtualStockOrderStatus
        END

    DROP TABLE #GetSelectSTypeId,#GetManBTypeId,#GetManETypeId,#GetManSelKTypeId,#GetManPTypeAll,#GetSelETypeId,#etypelist
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-05
	描述：凭证记账
	DECLARE @rValue VARCHAR(400) 
	EXEC Gp_Voucher_Auditing 1,'00001',@rValue
	PRINT(@rValue)
*/
CREATE PROCEDURE Gp_Voucher_Auditing
(
	@BillNumberId	NUMERIC(18,0),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值	
	@szPID			VARCHAR(1000) OUTPUT	-- 返回出错信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @STypeId	VARCHAR(50),
		@FPeriod	INT,
		@FYear		VARCHAR(10),
		@Re			INT,
		@BillPeriod	INT,
		@BillFYear	VARCHAR(10)

--判断单据是否存在
SELECT	TOP 1
		@STypeId    = STypeId,
		@BillPeriod = FPeriod,
		@BillFYear	= FYear
FROM	Ac_Voucher
WHERE	BillNumberId = @BillNumberId

IF @@ROWCOUNT = 0
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN -1
END		

--获取当前分支机构年度、会计期间
SELECT @FYear=FYear,@FPeriod=FPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID

--判断单据是否记账
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE BillNumberId = @BillNumberId AND IfCheck = 't')
BEGIN
	RAISERROR('凭证已经记账，请确认！',16,1)
	RETURN -2
END

--检查会计科目是否已经被停用
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill b INNER JOIN dbo.Ac_Account A ON B.ATypeId = A.TypeId AND B.STypeId=A.StypeId WHERE B.BillNumberId = @BillNumberId AND A.Deleted = 1)
BEGIN
	RAISERROR('凭证明细中存在被停用的科目，请确认！',16,1)
	RETURN -2
END

--检查辅助核算信息
DECLARE @i			INT,
		@vbid		VARCHAR(100),
		@typeName	VARCHAR(100),
		@billCount	INT,
		@rAscids	VARCHAR(2000),
		@rMscids	VARCHAR(2000)
		
CREATE TABLE #VoucherBillAssist
(
	nId			INT IDENTITY(1,1),
	AscIds		VARCHAR(1000),
	vBid		VARCHAR(100),
	typeName	VARCHAR(100)
)
INSERT INTO #VoucherBillAssist(AscIds,vBid,typeName)
SELECT	DISTINCT ISNULL(B.AscIds,'') AS AscIds,B.ID AS vBId,I.UserCode AS typeName 
FROM	Ac_Voucher_Bill B,
		Ac_Account_Assist_CheckItems C,
		Ac_Assist_CheckItems I 
WHERE	B.STypeId = C.STypeId 
		AND B.ATypeId = C.ATypeId 
		AND I.AscIds = C.Ascids 
		AND B.BillNumberId = @BillNumberId
		
SET @billCount = @@ROWCOUNT		
SET @i = 1
WHILE @i<=@billCount
BEGIN
	SELECT @typeName = TypeName,@vbid = vBid,@rAscids = AscIds FROM #VoucherBillAssist WHERE nId = @i
	
	SELECT	@rMscids = CAST(A.AscIds AS VARCHAR(100)) + ':'+b.TypeId
	FROM	Ac_Voucher_Bill_Assist_CheckItems B,
			Ac_Assist_CheckItems A 
	WHERE	B.typeName = A.UserCode 
			AND B.vBId = @vbId 
			AND B.typeName = @typeName 
			AND ISNULL(B.TypeId,'')<>''
			
	IF @@ROWCOUNT = 0 OR CHARINDEX(@rMscids,@rAscids) <= 0
	BEGIN
		RAISERROR('辅助核算信息不完整！',16,1)
		RETURN -1
	END
	
	SET @i = @i + 1	
END
DROP TABLE #VoucherBillAssist

--判断是否开账
IF EXISTS(SELECT TOP 1 * FROM Ac_AccountsPeroid_Stype WHERE StypeId = @STypeId AND IsUse=0)
BEGIN
	RAISERROR('系统没有开账，不允许记账，请确认！',16,1)
	RETURN -1
END

--非本期的会计凭证不允许记账
IF @BillPeriod <> @FPeriod OR @BillFYear <> @FYear
BEGIN
	DECLARE @x VARCHAR(MAX)
	SET @x = @BillNumberId
	RAISERROR('会计年度或者期间不一致，不允许记账，请确认！',16,1)
	RETURN -1
END

--凭证已经作废
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE BillNumberId = @BillNumberId AND FChecked = -1)
BEGIN
	RAISERROR('凭证已经作废，不允许记账，请确认！',16,1)
	RETURN -1
END

--凭证被标记有错误
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE BillNumberId = @BillNumberId AND ISNULL(markerror,'') <> '')
BEGIN
	RAISERROR('凭证被标记有错误，不允许记账，请确认！',16,1)
	RETURN -1
END

--凭证过账前必须审核
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'acvhrchk' AND SubValue = '1')
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher WHERE BillNumberId = @BillNumberId AND FChecked = 1)
BEGIN
	RAISERROR('凭证未审核，不允许记账，请确认！',16,1)
	RETURN -1
END

--凭证过账前必须复核
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'actellerchk' AND SubValue = '1')
	AND EXISTS(SELECT TOP 1 1 FROM Ac_Voucher V,Ac_Voucher_Bill B,Ac_Account A 
				WHERE	V.BillNumberId = B.BillNumberId 
						AND B.ATypeId = A.TypeId
						AND V.BillNumberId = @BillNumberId 
						AND ISNULL(V.ReCheckId,'') = '' 						
			  )
BEGIN
	RAISERROR('凭证未经复核，不允许记账，请确认！',16,1)
	RETURN -1
END


--每条凭证分录必须要有摘要
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'acsummary' AND SubValue = '1')
	AND EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill WHERE BillNumberId = @BillNumberId AND ISNULL(Summary,'') = '')
BEGIN
	RAISERROR('凭证分录存在摘要为空，不允许记账，请确认！',16,1)
	RETURN -1
END

--检测凭证的借方和贷方金额是否平衡
DECLARE @FDebitTotal	 NUMERIC(24, 10) ,
		@FCreditTotal	 NUMERIC(24, 10) 
		
SELECT	@FDebitTotal	= ISNULL(SUM(FDebitTotal),0),
		@FCreditTotal	= ISNULL(SUM(FCreditTotal),0)
FROM	Ac_Voucher_Bill
WHERE	BillNumberId = @BillNumberId

IF @FDebitTotal <> @FCreditTotal
BEGIN
	RAISERROR('借贷不平，请确认！',16,1)
	RETURN -3
END

--获取本币的Cid
DECLARE @Cid INT
SELECT TOP 1 @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1

IF @@ROWCOUNT = 0
BEGIN
	RAISERROR('获取本币失败，请确认！',16,1)
	RETURN -3
END

------------------------------------------------------------过账前检查数据------------------------------------------------------------
DECLARE @CheckDataMsg VARCHAR(MAX)

EXEC @Re = Gp_Voucher_Auditing_CheckData @BillNumberId,@FYear,@FPeriod,@CheckDataMsg OUTPUT
IF @Re <> 0
BEGIN
	RAISERROR(@CheckDataMsg,16,1)
	RETURN -1
END

------------------------------------------------------------处理科目余额表------------------------------------------------------------
EXEC @Re = Gp_Voucher_Auditing_Ac_Balance @BillNumberId,@Cid,@FPeriod,@FYear,@STypeId

IF @Re <> 0
BEGIN
	RAISERROR('处理科目余额表发生错误，请确认！',16,1)
	RETURN -3
END

------------------------------------------------------------处理科目余额表辅助核算----------------------------------------------------
EXEC @Re = Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems @BillNumberId,@Cid,@FPeriod,@FYear,@STypeId

IF @Re <> 0
BEGIN
	RAISERROR('处理科目余额表辅助核算发生错误，请确认！',16,1)
	RETURN -3
END

EXEC @Re = Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems_Cid0 @BillNumberId,@Cid,@FPeriod,@FYear,@STypeId

IF @Re <> 0
BEGIN
	RAISERROR('处理科目余额表辅助核算发生错误，请确认！',16,1)
	RETURN -3
END
------------------------------------------------------------重算科目余额---------------------------------------------------------------
EXEC @Re = Gp_Voucher_Check_Balance_Assit_Total @BillNumberId,@FPeriod,@FYear

IF @Re <> 0
BEGIN
	RAISERROR('处理科目余额表余额发生错误，请确认！',16,1)
	RETURN -3
END

------------------------------------------------------------过账后检查数据------------------------------------------------------------
EXEC @Re = Gp_Voucher_Auditing_CheckData @BillNumberId,@FYear,@FPeriod,@CheckDataMsg OUTPUT
IF @Re <> 0
BEGIN
	RAISERROR(@CheckDataMsg,16,1)
	RETURN -1
END

------------------------------------------------------------修改单据状态---------------------------------------------------------------
UPDATE	Ac_Voucher
SET		IfCheck = 't',
		Audited = 1,
		posttime = GetDate(),
		TallyId = @szCheckMan
WHERE	BillNumberId = @BillNumberId		


IF @@ERROR <> 0
BEGIN
	RAISERROR('修改单据记账状态错误，请确认！',16,1)
	RETURN -8
END	

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Ac_Balance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Ac_Balance]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-05
	描述：凭证记账-处理科目余额表
	DECLARE @rValue VARCHAR(400) 
	EXEC Gp_Voucher_Auditing_Ac_Balance 1,'00001',@rValue
	PRINT(@rValue)
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Ac_Balance
(
	@BillNumberId	NUMERIC(18,0),	-- 单据编号
	@Cid			INT,			-- 币别ID
	@FPeriod		INT,			-- 会计期间
	@FYear			INT,			-- 会计年度
	@STypeId		VARCHAR(50)		-- 分支机构ID	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Re INT

SELECT @STypeId = STypeId,@FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_Voucher WHERE BillNumberId = @BillNumberId

------------------------------------------------------------修改原币科目余额表------------------------------------------------------------
UPDATE	Ac_Balance
SET		FDebit			= FDebit + ISNULL(V.FDebitTotal,0),
		FDebitFor		= FDebitFor + ISNULL(V.FDebitTotalFor,0),
		FCredit			= FCredit + ISNULL(V.FCreditTotal,0),
		FCreditFor		= FCreditFor + ISNULL(V.FCreditTotalFor,0),
		FYtdDebit		= FYtdDebit + ISNULL(V.FDebitTotal,0),
		FYtdDebitFor	= FYtdDebitFor + ISNULL(V.FDebitTotalFor,0),
		FYtdCredit		= FYtdCredit + ISNULL(V.FCreditTotal,0),
		FYtdCreditFor	= FYtdCreditFor + ISNULL(V.FCreditTotalFor,0),
		FDebitqty		= FDebitqty + ISNULL(V.FDebitQtytotal,0),
		FCreditqty		= FCreditqty + ISNULL(V.FCreditQtytotal,0),
		FYtdDebitqty	= FYtdDebitqty + ISNULL(V.FDebitQtytotal,0),
		FYtdCreditqty	= FYtdCreditqty + ISNULL(V.FCreditQtytotal,0)
FROM	Ac_Balance B
INNER JOIN (		
				SELECT	Ab.ATypeId,
						Ab.STypeId,
						Ab.Cid,						
						ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotal,
						ISNULL(SUM(Ab.FDebitTotalFor),0) AS FDebitTotalFor,
						ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotal,
						ISNULL(SUM(Ab.FCreditTotalFor),0) AS FCreditTotalFor,	
						ISNULL(SUM(Ab.FDebitQty),0) AS FDebitQtytotal,
						ISNULL(SUM(Ab.FCreditQty),0) AS FCreditQtytotal		
				FROM	Ac_Voucher_Bill Ab
				WHERE	Ab.BillNumberId = @BillNumberId
				GROUP BY Ab.ATypeId,
						 Ab.STypeId,
						 Ab.Cid
)V ON B.Cid = V.Cid
WHERE	V.ATypeId = B.ATypeId
		AND B.STypeId = V.STypeId
		AND B.STypeId = @STypeId		
		AND B.FPeriod = @FPeriod
		AND B.Cid = V.Cid
		AND B.FYear = @FYear
		AND B.FPeriod = @FPeriod	
		
---------更新反月结的数据
UPDATE	Ac_Balance
SET		FBeginBalance = CASE WHEN A.Fdc = 1 THEN FBeginBalance + V.FDebitTotal - V.FCreditTotal ELSE FBeginBalance - V.FDebitTotal + V.FCreditTotal END,
		FBeginBalanceFor = CASE WHEN A.Fdc = 1 THEN FBeginBalanceFor + V.FDebitTotalFor - V.FCreditTotalFor ELSE FBeginBalanceFor - V.FDebitTotalFor + V.FCreditTotalFor END,
		FEndBalance = CASE WHEN A.Fdc = 1 THEN FEndBalance + V.FDebitTotal - V.FCreditTotal ELSE FEndBalance - V.FDebitTotal + V.FCreditTotal END,
		FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN FEndBalanceFor + V.FDebitTotalFor - V.FCreditTotalFor ELSE FEndBalanceFor - V.FDebitTotalFor + V.FCreditTotalFor END,
		FYtdDebit		= FYtdDebit + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotal,0) ELSE 0 END,
		FYtdDebitFor	= FYtdDebitFor + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotalFor,0) ELSE 0 END,
		FYtdCredit		= FYtdCredit + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotal,0) ELSE 0 END,
		FYtdCreditFor	= FYtdCreditFor + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotalFor,0) ELSE 0 END,
		FBeginqty = CASE WHEN A.Fdc = 1 THEN FBeginqty + V.FDebitQtytotal - V.FCreditQtytotal ELSE FBeginqty - V.FDebitQtytotal + V.FCreditQtytotal END,
		FEndqty = CASE WHEN A.Fdc = 1 THEN FEndqty + V.FDebitQtytotal - V.FCreditQtytotal ELSE FEndqty - V.FDebitQtytotal + V.FCreditQtytotal END,
		FYtdDebitqty	= FYtdDebitqty + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitQtytotal,0) ELSE 0 END,
		FYtdCreditqty		= FYtdCreditqty + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditQtytotal,0) ELSE 0 END
FROM	Ac_Balance B
INNER JOIN (		
				SELECT	Ab.ATypeId,
						Ab.STypeId,
						Ab.Cid,						
						ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotal,
						ISNULL(SUM(Ab.FDebitTotalFor),0) AS FDebitTotalFor,
						ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotal,
						ISNULL(SUM(Ab.FCreditTotalFor),0) AS FCreditTotalFor,	
						ISNULL(SUM(Ab.FDebitQty),0) AS FDebitQtytotal,
						ISNULL(SUM(Ab.FCreditQty),0) AS FCreditQtytotal		
				FROM	Ac_Voucher_Bill Ab
				WHERE	Ab.BillNumberId = @BillNumberId
				GROUP BY Ab.ATypeId,
						 Ab.STypeId,
						 Ab.Cid
)V ON B.Cid = V.Cid
INNER JOIN Ac_Account A ON A.TypeId = B.ATypeId AND A.StypeId = B.STypeId
WHERE	V.ATypeId = B.ATypeId
		AND B.STypeId = V.STypeId
		AND B.STypeId = @STypeId	
		AND B.Cid = V.Cid
		AND ((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
		
IF @@ERROR <> 0
BEGIN
	RAISERROR('修改原币余额平衡表数据错误，请确认！',16,1)
	RETURN -5
END		
----------------------------------------------------------------写原币科目余额表----------------------------------------------------------
INSERT INTO Ac_Balance
(
	STypeId,
	ATypeId,
	FBeginBalance,
	FBeginBalanceFor,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,		
	FYtdDebit,
	FYtdDebitFor,
	FYtdCredit,
	FYtdCreditFor,
	FYear,
	FPeriod,
	Cid,
	FBeginqty,
	FDebitqty,
	FCreditqty,
	FYtdDebitqty,
	FYtdCreditqty
)
SELECT	V.STypeId,
		V.ATypeId,		
		0 AS FBeginBalance,
		0 AS FBeginBalanceFor,
		FDebit = ISNULL(SUM(V.FDebitTotal),0),
		FDebitFor = ISNULL(SUM(V.FDebitTotalFor),0),
		FCredit = ISNULL(SUM(V.FCreditTotal),0),
		FCreditFor = ISNULL(SUM(V.FCreditTotalFor),0),
		FYtdDebit = ISNULL(SUM(V.FDebitTotal),0),
		FYtdDebitFor = ISNULL(SUM(V.FDebitTotalFor),0),
		FYtdCredit = ISNULL(SUM(V.FCreditTotal),0),		
		FYtdCreditFor = ISNULL(SUM(V.FCreditTotalFor),0),
		@FYear AS FYear,
		@FPeriod AS Period,
		V.Cid,
		0 AS FBeginqty,
		FDebitQty = ISNULL(SUM(V.FDebitQty),0),
		FCreditQty = ISNULL(SUM(V.FCreditQty),0),
		FYtdDebitqty = ISNULL(SUM(V.FDebitQty),0),
		FYtdCreditqty = ISNULL(SUM(V.FCreditQty),0)
FROM	Ac_Voucher_Bill V
WHERE	V.BillNumberId = @BillNumberId	
		AND NOT EXISTS(
						SELECT	1 
						FROM	Ac_Balance B 
						WHERE	B.STypeId = V.STypeId 
								AND B.ATypeId = V.ATypeId 
								AND B.Cid = V.Cid 
								AND B.FPeriod = V.FPeriod 
								AND B.FYear = V.FYear
								AND B.FYear = @FYear
								AND B.FPeriod = @FPeriod
					  )
GROUP BY V.STypeId,
		 V.ATypeId,
		 V.Fdc,
		 V.Cid

----------往反月结插入数据	
DECLARE	@LOOP	INT
		,@COUNT	INT
		,@NEXTFPERIOD INT
		,@NEXTFYEAR	INT
		
SELECT @COUNT = COUNT(*)
FROM	(
			SELECT DISTINCT FYear,FPeriod
			FROM	Ac_Balance
			WHERE	STypeId = @STypeId
			AND ((FYear = @FYear AND FPeriod > @FPeriod) OR FYear > @FYear)
		) T	
		
SET @LOOP = 0
SET @NEXTFPERIOD = @FPeriod
SET @NEXTFYEAR = @FYear

WHILE @LOOP < @COUNT
BEGIN		
	SET @LOOP += 1
	SET @NEXTFPERIOD += 1
	IF @NEXTFPERIOD > 12
	BEGIN
		SET @NEXTFPERIOD = 1
		SET @NEXTFYEAR += 1
	END
	
	INSERT INTO Ac_Balance
	(
		STypeId,
		ATypeId,
		FBeginBalance,
		FBeginBalanceFor,
		FEndBalance,
		FEndBalanceFor,
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		FYtdDebit,
		FYtdDebitFor,
		FYtdCredit,
		FYtdCreditFor,
		FPeriod,
		FYear,
		Cid,
		FBeginqty,
		FDebitqty,
		FCreditqty,
		FYtdDebitqty,
		FYtdCreditqty
	)
	SELECT	V.STypeId,
			V.ATypeId,
			FBeginBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			FBeginBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			FEndBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE  - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			0,--FDebit = ISNULL(SUM(V.FDebitTotal),0),		
			0,--FDebitFor = ISNULL(SUM(V.FDebitTotalFor),0),
			0,--FCredit = ISNULL(SUM(V.FCreditTotal),0),
			0,--FCreditFor =  ISNULL(SUM(V.FCreditTotalFor),0),
			FYtdDebit = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitTotal),0) ELSE 0 END,
			FYtdDebitFor = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitTotalFor),0) ELSE 0 END,
			FYtdCredit = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FCreditTotal),0) ELSE 0 END,
			FYtdCreditFor = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FCreditTotalFor),0) ELSE 0 END,
			@NEXTFPERIOD AS Period,
			@NEXTFYEAR AS FYear,
			V.Cid AS Cid,
			CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitQty),0) - ISNULL(SUM(V.FCreditQty),0) ELSE  - ISNULL(SUM(V.FDebitQty),0) + ISNULL(SUM(V.FCreditQty),0) END AS FBeginqty,
			0,--FDebitQty = ISNULL(SUM(V.FDebitQty),0),
			0,--FCreditQty = ISNULL(SUM(V.FCreditQty),0),
			FYtdDebitqty = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitQty),0) ELSE 0 END,
			FYtdCreditqty = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitQty),0) ELSE 0 END
	FROM	Ac_Voucher_Bill V
	INNER JOIN Ac_Account A ON A.TypeId = V.ATypeId AND A.StypeId = V.STypeId
	WHERE	V.BillNumberId = @BillNumberId
			AND NOT EXISTS(
							SELECT	1 
							FROM	Ac_Balance B 
							WHERE	B.STypeId = V.STypeId 
									AND B.ATypeId = V.ATypeId 
									AND B.Cid = V.Cid 
									AND B.FYear = @NEXTFYEAR
									AND B.FPeriod = @NEXTFPERIOD
						  )
	GROUP BY V.ATypeId,
			 V.STypeId,
			 V.Fdc,
			 V.Cid,
			 A.Fdc			 
END
		
		
IF @@ERROR <> 0
BEGIN
	RAISERROR('新增原币余额平衡表数据错误，请确认！',16,1)
	RETURN -4
END	

------------------------------------------------------------修改原币科目余额表------------------------------------------------------------

UPDATE	Ac_Balance
SET		FDebit = B.FDebit + ISNULL(M.FDebitTotal,0),
		FDebitFor = B.FDebitFor + ISNULL(M.FDebitTotal,0),
		FCredit = B.FCredit + ISNULL(FCreditTotal,0),
		FCreditFor = B.FCreditFor + ISNULL(M.FCreditTotal,0),
		FYtdDebit = B.FYtdDebit + ISNULL(M.FDebitTotal,0),
		FYtdDebitFor = B.FYtdDebitFor + ISNULL(M.FDebitTotal,0),
		FYtdCredit = B.FYtdCredit + ISNULL(FCreditTotal,0),
		FYtdCreditFor = B.FYtdCreditFor + ISNULL(M.FCreditTotal,0),
		
		FDebitqty = B.FDebitqty + ISNULL(M.FDebitQtytotal,0),
		FCreditqty = B.FCreditqty + ISNULL(FCreditQtytotal,0),
		FYtdDebitqty = B.FYtdDebitqty + ISNULL(M.FDebitQtytotal,0),
		FYtdCreditqty = B.FYtdCreditqty + ISNULL(FCreditQtytotal,0)
FROM	Ac_Balance B
INNER JOIN (
				SELECT  B.STypeId,
						B.ATypeId,
						FDebitTotal = ISNULL(SUM(B.FDebitTotal),0),
						FDebitTotalFor = ISNULL(SUM(B.FDebitTotal),0),
						FCreditTotal = ISNULL(SUM(B.FCreditTotal),0),
						FCreditTotalFor = ISNULL(SUM(B.FCreditTotal),0),
						FDebitQtytotal = ISNULL(SUM(B.FDebitQty),0),
						FCreditQtytotal= ISNULL(SUM(B.FCreditQty),0)
				FROM	Ac_Voucher_Bill B				
				WHERE	B.BillNumberId = @BillNumberId
				GROUP BY B.STypeId,
						 B.ATypeId
				
)M ON B.STypeId = M.STypeId AND B.ATypeId = M.ATypeId
WHERE	B.Cid = 0
		AND B.FYear = @FYear
		AND B.FPeriod = @FPeriod

---------更新反月结的数据
UPDATE	Ac_Balance
SET		FBeginBalance = CASE WHEN A.Fdc = 1 THEN FBeginBalance + V.FDebitTotal - V.FCreditTotal ELSE FBeginBalance - V.FDebitTotal + V.FCreditTotal END,
		FBeginBalanceFor = CASE WHEN A.Fdc = 1 THEN FBeginBalanceFor + V.FDebitTotalFor - V.FCreditTotalFor ELSE FBeginBalanceFor - V.FDebitTotalFor + V.FCreditTotalFor END,
		FEndBalance = CASE WHEN A.Fdc = 1 THEN FEndBalance + V.FDebitTotal - V.FCreditTotal ELSE FEndBalance - V.FDebitTotal + V.FCreditTotal END,
		FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN FEndBalanceFor + V.FDebitTotalFor - V.FCreditTotalFor ELSE FEndBalanceFor - V.FDebitTotalFor + V.FCreditTotalFor END,
		FYtdDebit		= FYtdDebit + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotal,0) ELSE 0 END,
		FYtdDebitFor	= FYtdDebitFor + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotalFor,0) ELSE 0 END,
		FYtdCredit		= FYtdCredit + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotal,0) ELSE 0 END,
		FYtdCreditFor	= FYtdCreditFor + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotalFor,0) ELSE 0 END,
		FBeginqty = CASE WHEN A.Fdc = 1 THEN FBeginqty + V.FDebitQtytotal - V.FCreditQtytotal ELSE FBeginqty - V.FDebitQtytotal + V.FCreditQtytotal END,
		FEndqty = CASE WHEN A.Fdc = 1 THEN FEndqty + V.FDebitQtytotal - V.FCreditQtytotal ELSE FEndqty - V.FDebitQtytotal + V.FCreditQtytotal END,
		FYtdDebitqty	= FYtdDebitqty + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitQtytotal,0) ELSE 0 END,
		FYtdCreditqty		= FYtdCreditqty + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditQtytotal,0) ELSE 0 END
FROM	Ac_Balance B
INNER JOIN (		
				SELECT	Ab.ATypeId,
						Ab.STypeId,
						ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotal,							
						ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotalFor,
						ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotal,
						ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotalFor,	
						ISNULL(SUM(Ab.FDebitQty),0) AS FDebitQtytotal,
						ISNULL(SUM(Ab.FCreditQty),0) AS FCreditQtytotal								
				FROM	Ac_Voucher_Bill Ab
				WHERE	Ab.BillNumberId = @BillNumberId
				GROUP BY Ab.ATypeId,
						 Ab.STypeId
)V ON B.STypeId = V.STypeId AND B.ATypeId = V.ATypeId
INNER JOIN Ac_Account A ON A.TypeId = B.ATypeId AND A.StypeId = B.STypeId
WHERE	((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
		AND B.Cid = 0


IF @@ERROR <> 0
BEGIN
	RAISERROR('修改科目余额表综合本位币信息错误，请确认！',16,1)
	RETURN -1
END

INSERT INTO Ac_Balance 
(
	STypeId, 
	ATypeId, 
	FBeginBalance, 
	FBeginBalanceFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	Cid, 
	FYtdDebit, 
	FYtdDebitFor, 
	FYtdCredit, 
	FYtdCreditFor, 
	FYear, 
	FPeriod,
	FBeginqty,
	FDebitqty,
	FCreditqty,
	FYtdDebitqty,
	FYtdCreditqty
)
SELECT  B.STypeId,
		B.ATypeId,
		FBeginBalance = 0,
		FBeginBalanceFor = 0,
		FDebit = ISNULL(SUM(B.FDebitTotal),0),
		FDebitFor = ISNULL(SUM(B.FDebitTotal),0),
		FCreditTotal = ISNULL(SUM(B.FCreditTotal),0),
		FDebitFor = ISNULL(SUM(B.FCreditTotal),0),
		0 AS Cid,			
		FYtdDebit = ISNULL(SUM(B.FDebitTotal),0),
		FYtdDebitFor = ISNULL(SUM(B.FDebitTotal),0),	
		FYtdCredit = ISNULL(SUM(B.FCreditTotal),0),
		FYtdCreditFor = ISNULL(SUM(B.FCreditTotal),0),
		@FYear,
		@FPeriod,
		0 AS FBeginqty,
		FDebitQty = ISNULL(SUM(B.FDebitQty),0),
		FCreditQty = ISNULL(SUM(B.FCreditQty),0),
		FYtdDebitqty = ISNULL(SUM(B.FDebitQty),0),
		FYtdCreditqty = ISNULL(SUM(B.FCreditQty),0)					
FROM	Ac_Voucher_Bill B
WHERE	B.BillNumberId = @BillNumberId
		AND NOT EXISTS(
						SELECT  1
						FROM	Ac_Balance V
						WHERE	V.Cid = 0
								AND B.STypeId = V.STypeId
								AND B.ATypeId = V.ATypeId
								AND V.FYear = @FYear
								AND V.FPeriod = @FPeriod
						
		)		
GROUP BY B.STypeId,
		 B.ATypeId	

---------往反月结期间插入数据
SET @LOOP = 0
SET @NEXTFPERIOD = @FPeriod
SET @NEXTFYEAR = @FYear

WHILE @LOOP < @COUNT
BEGIN		
	SET @LOOP += 1
	SET @NEXTFPERIOD += 1
	IF @NEXTFPERIOD > 12
	BEGIN
		SET @NEXTFPERIOD = 1
		SET @NEXTFYEAR += 1
	END
	
	INSERT INTO Ac_Balance
	(
		STypeId,
		ATypeId,
		FBeginBalance,
		FBeginBalanceFor,
		FEndBalance,
		FEndBalanceFor,
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		FYtdDebit,
		FYtdDebitFor,
		FYtdCredit,
		FYtdCreditFor,
		FPeriod,
		FYear,
		Cid,
		FBeginqty,
		FDebitqty,
		FCreditqty,
		FYtdDebitqty,
		FYtdCreditqty
	)
	SELECT	V.STypeId,
			V.ATypeId,
			FBeginBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			FBeginBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			FEndBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE  - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			0,--FDebit = ISNULL(SUM(V.FDebitTotal),0),		
			0,--FDebitFor = ISNULL(SUM(V.FDebitTotalFor),0),
			0,--FCredit = ISNULL(SUM(V.FCreditTotal),0),
			0,--FCreditFor =  ISNULL(SUM(V.FCreditTotalFor),0),
			FYtdDebit = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitTotal),0) ELSE 0 END,
			FYtdDebitFor = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitTotalFor),0) ELSE 0 END,
			FYtdCredit = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FCreditTotal),0) ELSE 0 END,
			FYtdCreditFor = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FCreditTotalFor),0) ELSE 0 END,
			@NEXTFPERIOD AS Period,
			@NEXTFYEAR AS FYear,
			0 AS Cid,
			CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitQty),0) - ISNULL(SUM(V.FCreditQty),0) ELSE  - ISNULL(SUM(V.FDebitQty),0) + ISNULL(SUM(V.FCreditQty),0) END AS FBeginqty,
			0,--FDebitQty = ISNULL(SUM(V.FDebitQty),0),
			0,--FCreditQty = ISNULL(SUM(V.FCreditQty),0),
			FYtdDebitqty = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitQty),0) ELSE 0 END,
			FYtdCreditqty = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitQty),0) ELSE 0 END
	FROM	Ac_Voucher_Bill V
	INNER JOIN Ac_Account A ON A.TypeId = V.ATypeId AND A.StypeId = V.STypeId
	WHERE	V.BillNumberId = @BillNumberId
			AND NOT EXISTS(
							SELECT  1
							FROM	Ac_Balance B
							WHERE	B.Cid = 0
									AND B.STypeId = V.STypeId
									AND B.ATypeId = V.ATypeId
									AND B.FYear = @NEXTFYEAR
									AND B.FPeriod = @NEXTFPERIOD
						  )
	GROUP BY V.ATypeId,
			 V.STypeId,
			 A.Fdc	
			 
END
		 
IF @@ERROR <> 0
BEGIN
	RAISERROR('写入科目余额表综合本位币信息错误，请确认！',16,1)
	RETURN -1
END			 

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-05
	描述：凭证记账-处理科目余额表辅助核算
	DECLARE @rValue VARCHAR(400) 
	EXEC Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems 1,'00001',@rValue
	PRINT(@rValue)
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems
(
	@BillNumberId	NUMERIC(18,0),			-- 单据编号
	@Cid			INT,					-- 币别ID
	@FPeriod		INT,			-- 会计期间
	@FYear			INT,			-- 会计年度
	@STypeId		VARCHAR(50)				-- 分支机构ID	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Re INT

--无辅助核算数据需要处理，直接返回
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @BillNumberId)
BEGIN
	RETURN 0
END


--------------------------------------------------------写本币辅助核算数据--------------------------------------------------------
		 


--------------------------------------------------------写原币辅助核算数据--------------------------------------------------------
UPDATE	Ac_Balance_Assist_CheckItems
SET		FDebit = FDebit + ISNULL(FDebitTotal,0),
		FDebitFor = FDebitFor +  ISNULL(FDebitTotalFor,0),
		FCredit = FCredit + ISNULL(FCreditTotal,0),
		FCreditFor = FCreditFor + ISNULL(FCreditTotalFor,0)
		,FDebitqty = FDebitqty + ISNULL(FDebitQtytotal,0)
		,FCreditqty = FCreditqty + ISNULL(FCreditQtytotal,0)
FROM	Ac_Balance_Assist_CheckItems Abc
INNER JOIN (
			SELECT	B.ATypeId,
					B.STypeId,
					B.Cid,
					B.FYear,
					B.FPeriod,										
					ISNULL(SUM(B.FDebitTotal),0) AS FDebitTotal, 
					ISNULL(SUM(B.FDebitTotalFor),0) AS FDebitTotalFor, 
					ISNULL(SUM(B.FCreditTotal),0) AS FCreditTotal,
					ISNULL(SUM(B.FCreditTotalFor),0) AS FCreditTotalFor,	
					ISNULL(SUM(b.FDebitQty),0) AS FDebitQtytotal,
					ISNULL(SUM(b.FCreditQty),0) AS FCreditQtytotal		
			FROM	Ac_Voucher_Bill B						
			WHERE	B.BillNumberId = @BillNumberId
					AND ISNULL(B.AscIds,'') <> ''
			GROUP BY B.ATypeId,
					 B.STypeId,
					 B.Cid,
					 B.FYear,
					 B.FPeriod
)B ON Abc.ATypeId = B.ATypeId AND B.STypeId = Abc.STypeId AND B.Cid = Abc.Cid
		AND Abc.FYear = B.FYear 
		AND Abc.FPeriod = B.FPeriod 
		
		
----------更新反月结数据
UPDATE	Abc
SET		IniTotal = CASE WHEN A.Fdc = 1 THEN IniTotal + B.FDebitTotal - B.FCreditTotal ELSE IniTotal - B.FDebitTotal + B.FCreditTotal END,
		IniTotalFor = CASE WHEN A.Fdc = 1 THEN IniTotalFor + B.FDebitTotalFor - B.FCreditTotalFor ELSE IniTotalFor - B.FDebitTotalFor + B.FCreditTotalFor END,
		FEndBalance = CASE WHEN A.Fdc = 1 THEN FEndBalance + B.FDebitTotal - B.FCreditTotal ELSE FEndBalance - B.FDebitTotal + B.FCreditTotal END,
		FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN FEndBalanceFor + B.FDebitTotalFor - B.FCreditTotalFor ELSE FEndBalanceFor - B.FDebitTotalFor + B.FCreditTotalFor END
		,Iniqty = CASE WHEN A.Fdc = 1 THEN Iniqty + B.FDebitQtytotal - B.FCreditQtytotal ELSE Iniqty - B.FDebitQtytotal + B.FCreditQtytotal END,
		FEndqty = CASE WHEN A.Fdc = 1 THEN FEndqty + B.FDebitQtytotal - B.FCreditQtytotal ELSE FEndqty - B.FDebitQtytotal + B.FCreditQtytotal END
		
FROM	Ac_Balance_Assist_CheckItems Abc
INNER JOIN Ac_Account A ON A.TypeId = ABC.ATypeId AND A.StypeId = ABC.STypeId
INNER JOIN (
			SELECT	B.ATypeId,
					B.STypeId,
					B.Cid,						
					B.FYear,
					B.FPeriod,				
					ISNULL(SUM(B.FDebitTotal),0) AS FDebitTotal, 
					ISNULL(SUM(B.FDebitTotalFor),0) AS FDebitTotalFor, 
					ISNULL(SUM(B.FCreditTotal),0) AS FCreditTotal,
					ISNULL(SUM(B.FCreditTotalFor),0) AS FCreditTotalFor,	
					ISNULL(SUM(b.FDebitQty),0) AS FDebitQtytotal,
					ISNULL(SUM(b.FCreditQty),0) AS FCreditQtytotal	
			FROM	Ac_Voucher_Bill B
			WHERE	B.BillNumberId = @BillNumberId
					AND ISNULL(B.AscIds,'') <> ''
			GROUP BY B.ATypeId,
					 B.STypeId,
					 B.Cid,
					 B.FYear,
					 B.FPeriod
)B ON Abc.ATypeId = B.ATypeId AND Abc.STypeId = B.STypeId AND B.Cid = Abc.Cid
WHERE	((Abc.FYear = @FYear AND Abc.FPeriod > @FPeriod) OR Abc.FYear > @FYear)
			
IF @@ERROR <> 0
BEGIN
	RAISERROR('修改科目余额辅助核算原币信息错误，请确认！',16,1)
	RETURN -6	
END			

INSERT INTO Ac_Balance_Assist_CheckItems 
(
	STypeId, 
	ATypeId, 
	Cid, 		
	IniYTotal, 
	IniYTotalFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	IniTotal, 
	IniTotalFor, 
	FYear, 
	FPeriod
	,IniYqty
	,FDebitqty
	,FCreditqty
	,Iniqty
)
SELECT	B.STypeId,
		B.ATypeId,
		B.Cid,						
		0 AS IniYTotal,
		0 AS IniYTotalFor,
		FFDebit = ISNULL(SUM(B.FDebitTotal),0),
		FDebitFor = ISNULL(SUM(B.FDebitTotalFor),0),
		FCredit = ISNULL(SUM(B.FCreditTotal),0),
		FCreditFor = ISNULL(SUM(B.FCreditTotalFor),0),
		0 AS IniTotal,
		0 AS IniTotalFor,			
		@FYear AS FYear,
		@FPeriod AS FPeriod
		,0
		,ISNULL(SUM(B.FDebitQty),0)
		,ISNULL(SUM(B.FCreditQty),0)
		,0
FROM	Ac_Voucher_Bill B
WHERE	B.BillNumberId = @BillNumberId
		AND ISNULL(B.AscIds,'')<>''
		AND NOT EXISTS(
						SELECT  1
						FROM	Ac_Balance_Assist_CheckItems V
						WHERE	B.STypeId = V.STypeId
								AND B.ATypeId = V.ATypeId
								AND B.Cid = V.Cid
								AND V.FYear = @FYear
								AND V.FPeriod = @FPeriod
		)		
GROUP BY B.STypeId,
		 B.ATypeId,
		 B.Cid,			 
		 B.Fdc
		 
--------往反月结期间插入数据
DECLARE @COUNT INT
		,@LOOP	INT
		,@NEXTFYEAR	INT
		,@NEXTFPERIOD	INT
		
SELECT @COUNT = COUNT(*)
FROM	(
			SELECT DISTINCT FYear,FPeriod
			FROM	Ac_Balance
			WHERE	STypeId = @STypeId
			AND ((FYear = @FYear AND FPeriod > @FPeriod) OR FYear > @FYear)
		) T
			
SET @LOOP = 0
SET @NEXTFPERIOD = @FPeriod
SET @NEXTFYEAR = @FYear

WHILE @LOOP < @COUNT
BEGIN		
	SET @LOOP += 1
	SET @NEXTFPERIOD += 1
	IF @NEXTFPERIOD > 12
	BEGIN
		SET @NEXTFPERIOD = 1
		SET @NEXTFYEAR += 1
	END
	
	INSERT INTO Ac_Balance_Assist_CheckItems
	(
		STypeId, 
		ATypeId, 
		IniYTotal, 
		IniYTotalFor, 
		IniTotal, 
		IniTotalFor, 
		FEndBalance,
		FEndBalanceFor,
		FDebit, 
		FDebitFor, 
		FCredit, 
		FCreditFor, 
		FYear, 
		FPeriod,
		Cid
		,IniYqty
		,Iniqty
		,FEndqty
		,FDebitqty
		,FCreditqty
	)
	SELECT	V.STypeId,
			V.ATypeId,
			0,
			0,
			IniTotal = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			IniTotalFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			FEndBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE  - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			0,--FDebit = ISNULL(SUM(V.FDebitTotal),0),		
			0,--FDebitFor = ISNULL(SUM(V.FDebitTotalFor),0),
			0,--FCredit = ISNULL(SUM(V.FCreditTotal),0),
			0,--FCreditFor =  ISNULL(SUM(V.FCreditTotalFor),0),
			@NEXTFYEAR AS FYear,
			@NEXTFPERIOD AS Period,
			V.Cid AS Cid
			,0
			,iniqty = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitQty),0) - ISNULL(SUM(V.FCreditQty),0) ELSE  - ISNULL(SUM(V.FDebitQty),0) + ISNULL(SUM(V.FCreditQty),0) END,
			FEndqty = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitQty),0) - ISNULL(SUM(V.FCreditQty),0) ELSE  - ISNULL(SUM(V.FDebitQty),0) + ISNULL(SUM(V.FCreditQty),0) END,
			0
			,0
	FROM	Ac_Voucher_Bill V
	INNER JOIN Ac_Account A ON A.TypeId = V.ATypeId AND A.StypeId = V.STypeId
	WHERE	V.BillNumberId = @BillNumberId	
			AND ISNULL(V.AscIds,'')<>''
			AND NOT EXISTS(
							SELECT  1
							FROM	Ac_Balance_Assist_CheckItems B
							WHERE	B.STypeId = V.STypeId
									AND B.ATypeId = V.ATypeId
									AND B.Cid = V.Cid
									AND B.FYear = @NEXTFYEAR
									AND B.FPeriod = @NEXTFPERIOD
			)
	GROUP BY V.STypeId,
			 V.ATypeId,
			 V.Cid,
			 V.Fdc,
			 A.Fdc			 
END		 
		 
		 
		
IF @@ERROR <> 0
BEGIN
	RAISERROR('写入科目余额辅助核算信息错误，请确认！',16,1)
	RETURN -6	
END

--------------------------------------------------------产生综合本位币------------------------------------------------------------

--------------------------------------------------------处理科目余额辅助核算【综合本位币】的累加余额--------------------------------------------------------
UPDATE	Ac_Balance_Assist_CheckItems
SET		FDebit = A.FDebit + ISNULL(B.Debit,0),
		FDebitFor = A.FDebitFor + ISNULL(B.Debit,0),
		FCredit = A.FCredit + ISNULL(B.Credit,0),
		FCreditFor = A.FCreditFor + ISNULL(B.Credit,0)
		,FDebitqty	= a.FDebitqty + ISNULL(b.Debitqty,0)
		,FCreditqty	= a.FCreditqty	+ ISNULL(b.Creditqty,0)
FROM    Ac_Balance_Assist_CheckItems A
INNER JOIN 
(
	SELECT  Ab.STypeId,
			Ab.ATypeId,
			Ab.FYear,
			Ab.FPeriod,			
			Debit = ISNULL(SUM(Ab.FDebitTotal),0), 
			DebitFor = ISNULL(SUM(Ab.FDebitTotal),0), 
			Credit = ISNULL(SUM(Ab.FCreditTotal),0), 
			CreditFor = ISNULL(SUM(Ab.FCreditTotal),0)
			,Debitqty = ISNULL(SUM(ab.FDebitQty),0)
			,Creditqty = ISNULL(sum(ab.FCreditQty),0)
	FROM	Ac_Voucher_Bill Ab	
	WHERE	Ab.BillNumberId = @BillNumberId
			AND ISNULL(Ab.AscIds,'') <> ''
	GROUP BY Ab.STypeId,
			 Ab.ATypeId,
			 Ab.FYear,
			 Ab.FPeriod	 
)B ON A.STypeId = B.STypeId AND A.ATypeId = B.ATypeId AND A.FYear = B.FYear AND A.FPeriod = B.FPeriod					
WHERE	A.Cid = 0
		AND A.STypeId = @STypeId
		AND A.FYear = @FYear
		AND A.FPeriod = @FPeriod

----------更新反月结数据
UPDATE	ABC
SET		IniTotal = CASE WHEN A.Fdc = 1 THEN IniTotal + B.FDebitTotal - B.FCreditTotal ELSE IniTotal - B.FDebitTotal + B.FCreditTotal END,
		IniTotalFor = CASE WHEN A.Fdc = 1 THEN IniTotalFor + B.FDebitTotalFor - B.FCreditTotalFor ELSE IniTotalFor - B.FDebitTotalFor + B.FCreditTotalFor END,
		FEndBalance = CASE WHEN A.Fdc = 1 THEN FEndBalance + B.FDebitTotal - B.FCreditTotal ELSE FEndBalance - B.FDebitTotal + B.FCreditTotal END,
		FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN FEndBalanceFor + B.FDebitTotalFor - B.FCreditTotalFor ELSE FEndBalanceFor - B.FDebitTotalFor + B.FCreditTotalFor END
		,Iniqty = CASE WHEN A.Fdc = 1 THEN Iniqty + B.FDebitqtyTotal - B.FCreditqtyTotal ELSE Iniqty - B.FDebitqtyTotal + B.FCreditqtyTotal END,
		FEndqty = CASE WHEN A.Fdc = 1 THEN FEndqty + B.FDebitqtyTotal - B.FCreditqtyTotal ELSE FEndqty - B.FDebitqtyTotal + B.FCreditqtyTotal END
		
FROM    Ac_Balance_Assist_CheckItems ABC
INNER JOIN Ac_Account A ON A.TypeId = ABC.ATypeId AND A.StypeId = ABC.STypeId
INNER JOIN 
(
	SELECT  Ab.STypeId,
			Ab.ATypeId,
			Ab.FYear,
			Ab.FPeriod,			
			FDebitTotal = ISNULL(SUM(Ab.FDebitTotal),0), 
			FDebitTotalFor = ISNULL(SUM(Ab.FDebitTotal),0), 
			FCreditTotal = ISNULL(SUM(Ab.FCreditTotal),0), 
			FCreditTotalFor = ISNULL(SUM(Ab.FCreditTotal),0)
			,FDebitqtyTotal = ISNULL(SUM(Ab.FDebitQty),0)
			,FCreditqtyTotal = ISNULL(SUM(Ab.FCreditQty),0)
			
	FROM	Ac_Voucher_Bill Ab	
	WHERE	Ab.BillNumberId = @BillNumberId
			AND ISNULL(Ab.AscIds,'') <> ''
	GROUP BY Ab.STypeId,
			 Ab.ATypeId,
			 Ab.FYear,
			 Ab.FPeriod	 
)B ON ABC.STypeId = B.STypeId AND ABC.ATypeId = B.ATypeId 					
WHERE	ABC.Cid = 0
		AND ABC.STypeId = @STypeId
		AND ((ABC.FYear = @FYear AND ABC.FPeriod > @FPeriod) OR ABC.FYear > @FYear)
		
--------------------------------------------------------写入科目余额辅助核算【综合本位币】信息------------------------------------------------------------	
INSERT INTO Ac_Balance_Assist_CheckItems 
(
	STypeId, 
	ATypeId, 
	Cid, 		
	IniYTotal, 
	IniYTotalFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	IniTotal, 
	IniTotalFor, 
	FYear, 
	FPeriod
	,IniYqty
	,FDebitqty
	,FCreditqty
	,Iniqty
)
SELECT	B.STypeId,
		B.ATypeId,
		0 AS Cid,			
		0 AS IniYTotal,
		0 AS IniYTotalFor,
		FDebitTotal = ISNULL(SUM(B.FDebitTotal),0),
		FDebitTotalFor = ISNULL(SUM(B.FDebitTotal),0),
		FCreditTotal = ISNULL(SUM(B.FCreditTotal),0),
		FCreditTotalFor = ISNULL(SUM(B.FCreditTotal),0),
		0 AS IniTotal,
		0 AS IniTotalFor,			
		@FYear AS FYear,
		@FPeriod AS FPeriod
		,0
		,ISNULL(SUM(b.FDebitQty),0)
		,ISNULL(SUM(b.FCreditQty),0)
		,0
FROM	Ac_Voucher_Bill B
WHERE	B.BillNumberId = @BillNumberId	
		AND ISNULL(B.AscIds,'')<>''
		AND NOT EXISTS(
						SELECT  1
						FROM	Ac_Balance_Assist_CheckItems V
						WHERE	V.Cid = 0
								AND B.STypeId = V.STypeId
								AND B.ATypeId = V.ATypeId 
								AND B.FYear = V.FYear
								AND B.FPeriod = V.FPeriod
								AND V.FYear = @FYear
								AND V.FPeriod = @FPeriod
		)	
GROUP BY B.STypeId,
		 B.ATypeId

		 
----------往反月结插入数据	
			
SET @LOOP = 0
SET @NEXTFPERIOD = @FPeriod
SET @NEXTFYEAR = @FYear

WHILE @LOOP < @COUNT
BEGIN		
	SET @LOOP += 1
	SET @NEXTFPERIOD += 1
	IF @NEXTFPERIOD > 12
	BEGIN
		SET @NEXTFPERIOD = 1
		SET @NEXTFYEAR += 1
	END
	
	INSERT INTO Ac_Balance_Assist_CheckItems
	(
		STypeId, 
		ATypeId, 
		IniYTotal, 
		IniYTotalFor, 
		IniTotal, 
		IniTotalFor, 
		FEndBalance,
		FEndBalanceFor,
		FDebit, 
		FDebitFor, 
		FCredit, 
		FCreditFor, 
		FYear, 
		FPeriod,
		Cid
		,IniYqty
		,Iniqty
		,FEndqty
		,FDebitqty
		,FCreditqty
	)
	SELECT	V.STypeId,
			V.ATypeId,
			0,
			0,
			IniTotal = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			IniTotalFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			FEndBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE  - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			0,--FDebit = ISNULL(SUM(V.FDebitTotal),0),		
			0,--FDebitFor = ISNULL(SUM(V.FDebitTotalFor),0),
			0,--FCredit = ISNULL(SUM(V.FCreditTotal),0),
			0,--FCreditFor =  ISNULL(SUM(V.FCreditTotalFor),0),
			@NEXTFYEAR AS FYear,
			@NEXTFPERIOD AS Period,
			0 AS Cid
			,0
			,iniqty = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitQty),0) - ISNULL(SUM(V.FCreditQty),0) ELSE - ISNULL(SUM(V.FDebitQty),0) + ISNULL(SUM(V.FCreditQty),0) END
			,FEndqty = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitQty),0) - ISNULL(SUM(V.FCreditQty),0) ELSE  - ISNULL(SUM(V.FDebitQty),0) + ISNULL(SUM(V.FCreditQty),0) END
			,0
			,0
			
	FROM	Ac_Voucher_Bill V
	INNER JOIN Ac_Account A ON A.TypeId = V.ATypeId AND A.StypeId = V.STypeId
	WHERE	V.BillNumberId = @BillNumberId	
		AND ISNULL(V.AscIds,'')<>''
		AND NOT EXISTS(
						SELECT  1
						FROM	Ac_Balance_Assist_CheckItems B
						WHERE	B.Cid = 0
								AND B.STypeId = V.STypeId
								AND B.ATypeId = V.ATypeId 
								AND B.FYear = @NEXTFYEAR
								AND B.FPeriod = @NEXTFPERIOD
		)	
	GROUP BY V.STypeId,
			 V.ATypeId,
			 A.Fdc		 
END
			 
		
IF @@ERROR <> 0
BEGIN
	RAISERROR('写入科目余额辅助核算信息错误，请确认！',16,1)
	RETURN -6	
END		

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems_Cid0]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems_Cid0]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-05
	描述：凭证记账-处理科目余额表辅助核算的综合本位币
	DECLARE @rValue VARCHAR(400) 
	EXEC Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems_Cid0 1,'00001',@rValue
	PRINT(@rValue)
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Ac_Balance_Assist_CheckItems_Cid0
(
	@BillNumberId	NUMERIC(18,0),			-- 单据编号
	@Cid			INT,					-- 币别ID
	@FPeriod		INT,			-- 会计期间
	@FYear			INT,			-- 会计年度
	@STypeId		VARCHAR(50)				-- 分支机构ID	
)
--@encode$--
AS
SET NOCOUNT ON

---------------------------------------------------------修改科目余额表辅助核算项目对照表【非综合本位币】信息---------------------------------------------------------
UPDATE	Ac_Balance_Assist_CheckItems_Detail
SET		FDebit = D.FDebit + ISNULL(A.FDebit,0),
		FDebitFor = D.FDebitFor + ISNULL(A.FDebitFor,0),
		FCredit = D.FCredit + ISNULL(A.FCredit,0),
		FCreditFor = D.FCreditFor + ISNULL(A.FCreditFor,0)
		,FDebitqty	= d.FDebitqty + ISNULL(a.Debitqty,0)
		,FCreditqty	= d.FCreditqty	+ ISNULL(a.Creditqty,0)
FROM	Ac_Balance_Assist_CheckItems_Detail D
INNER JOIN (
			SELECT	Ab.STypeId,
					Ab.ATypeId,
					Ab.Cid,
					Ac.AscIds,
					Abc.TypeId AS FieldValue,
					Ab.FYear,
					Ab.FPeriod,
					FDebit = ISNULL(SUM(Ab.FDebitTotal),0),
					FDebitFor =ISNULL(SUM(Ab.FDebitTotalFor),0),
					FCredit = ISNULL(SUM(Ab.FCreditTotal),0),
					FCreditFor = ISNULL(SUM(Ab.FCreditTotalFor),0),
					Debitqty =ISNULL(SUM(Ab.FDebitqty),0),
					Creditqty = ISNULL(SUM(Ab.FCreditqty),0)
			FROM    Ac_Voucher_Bill Ab			
			INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
			INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
			WHERE	Abc.BillNumberId = @BillNumberId		
			GROUP BY Ab.STypeId,
					 Ab.ATypeId,
					 Ab.Cid,
					 Ac.AscIds,
					 Abc.TypeId,
					 Ab.FYear,
					 Ab.FPeriod		
)A ON D.STypeId = A.STypeId AND D.ATypeId = A.ATypeId AND D.Cid = A.Cid AND D.Ascids = A.AscIds AND D.FieldValue = A.FieldValue
WHERE	D.STypeId = @STypeId
		AND D.FYear = @FYear
		AND D.FPeriod = @FPeriod
		
----------更新反月结数据
UPDATE	Ac_Balance_Assist_CheckItems_Detail
SET		IniTotal = CASE WHEN B.Fdc = 1 THEN IniTotal + A.FDebitTotal - A.FCreditTotal ELSE IniTotal - A.FDebitTotal + A.FCreditTotal END,
		IniTotalFor = CASE WHEN B.Fdc = 1 THEN IniTotalFor + A.FDebitTotalFor - A.FCreditTotalFor ELSE IniTotalFor - A.FDebitTotalFor + A.FCreditTotalFor END,
		FEndBalance = CASE WHEN B.Fdc = 1 THEN FEndBalance + A.FDebitTotal - A.FCreditTotal ELSE FEndBalance - A.FDebitTotal + A.FCreditTotal END,
		FEndBalanceFor = CASE WHEN B.Fdc = 1 THEN FEndBalanceFor + A.FDebitTotalFor - A.FCreditTotalFor ELSE FEndBalanceFor - A.FDebitTotalFor + A.FCreditTotalFor END,
		Iniqty = CASE WHEN B.Fdc = 1 THEN Iniqty + A.FDebitqtytotal - A.FCreditqtytotal ELSE Iniqty - A.FDebitqtytotal + A.FCreditqtytotal END,
		FEndqty = CASE WHEN B.Fdc = 1 THEN FEndqty + A.FDebitqtytotal - A.FCreditqtytotal ELSE FEndqty - A.FDebitqtytotal + A.FCreditqtytotal END
		
FROM	Ac_Balance_Assist_CheckItems_Detail D
INNER JOIN Ac_Account B ON B.TypeId = D.ATypeId AND B.StypeId = D.STypeId
INNER JOIN (
			SELECT	Ab.STypeId,
					Ab.ATypeId,
					Ab.Cid,
					Ac.AscIds,
					Abc.TypeId AS FieldValue,
					Ab.FYear,
					Ab.FPeriod,
					FDebitTotal = ISNULL(SUM(Ab.FDebitTotal),0),
					FDebitTotalFor =ISNULL(SUM(Ab.FDebitTotalFor),0),
					FCreditTotal = ISNULL(SUM(Ab.FCreditTotal),0),
					FCreditTotalFor = ISNULL(SUM(Ab.FCreditTotalFor),0),
					FDebitqtytotal =ISNULL(SUM(Ab.FDebitQty),0),
					FCreditqtytotal = ISNULL(SUM(Ab.FCreditQty),0)
			FROM    Ac_Voucher_Bill Ab			
			INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
			INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
			WHERE	Abc.BillNumberId = @BillNumberId		
			GROUP BY Ab.STypeId,
					 Ab.ATypeId,
					 Ab.Cid,
					 Ac.AscIds,
					 Abc.TypeId,
					 Ab.FYear,
					 Ab.FPeriod		
)A ON D.STypeId = A.STypeId AND D.ATypeId = A.ATypeId AND D.Cid = A.Cid AND D.Ascids = A.AscIds AND D.FieldValue = A.FieldValue
WHERE	D.STypeId = @STypeId
		AND ((D.FYear = @FYear AND CAST(D.FPeriod AS INT) > @FPeriod) OR D.FYear > @FYear)


IF @@ERROR <> 0
BEGIN
	RAISERROR('修改科目余额辅助核算信息错误，请确认！',16,1)
	RETURN -6	
END

---------------------------------------------------------写入科目余额表辅助核算项目对照表【非综合本位币】信息---------------------------------------------------------
INSERT INTO Ac_Balance_Assist_CheckItems_Detail
(
	STypeId,
	ATypeId,
	Cid,
	Ascids,
	FieldValue,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	IniTotal,
	IniTotalFor,
	FYear,
	FPeriod
	,FDebitqty
	,FCreditqty
	,Iniqty
)
SELECT	Ab.STypeId,
		Ab.ATypeId,
		Ab.Cid,
		Ac.AscIds,
		Abc.TypeId,
		FDebit = ISNULL(SUM(Ab.FDebitTotal),0),
		FDebitFor = ISNULL(SUM(Ab.FDebitTotalFor),0),
		FCredit = ISNULL(SUM(Ab.FCreditTotal),0),
		FCreditFor = ISNULL(SUM(Ab.FCreditTotalFor),0),
		0 AS IniTotal,
		0 AS IniTotalFor,
		@FYear,
		@FPeriod
		,ISNULL(SUM(FDebitQty),0)
		,ISNULL(SUM(FCreditQty),0)
		,0
FROM    Ac_Voucher_Bill Ab
INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
WHERE	Abc.BillNumberId = @BillNumberId
		AND NOT EXISTS(
						SELECT  1
						FROM	Ac_Balance_Assist_CheckItems_Detail D
						WHERE	Ab.STypeId = D.STypeId
								AND Ab.ATypeId = D.ATypeId
								AND Ab.Cid = D.Cid
								AND Ac.AscIds = D.Ascids
								AND Abc.TypeId = D.FieldValue
								AND Ab.FYear = D.FYear
								AND Ab.FPeriod = D.FPeriod
								AND D.FYear = @FYear
								AND D.FPeriod = @FPeriod
		)		
GROUP BY Ab.ATypeId,
		 Ab.STypeId,
		 Ab.Cid,
		 Ac.AscIds,
		 Abc.TypeId			

------------往反月结期间插入数据
DECLARE @COUNT INT
		,@LOOP	INT
		,@NEXTFYEAR	INT
		,@NEXTFPERIOD	INT
SELECT @COUNT = COUNT(*)
FROM	(
			SELECT DISTINCT FYear,FPeriod
			FROM	Ac_Balance
			WHERE	STypeId = @STypeId
			AND ((FYear = @FYear AND FPeriod > @FPeriod) OR FYear > @FYear)
		) T
		
SET @LOOP = 0
SET @NEXTFPERIOD = @FPeriod
SET @NEXTFYEAR = @FYear

WHILE @LOOP < @COUNT
BEGIN		
	SET @LOOP += 1
	SET @NEXTFPERIOD += 1
	IF @NEXTFPERIOD > 12
	BEGIN
		SET @NEXTFPERIOD = 1
		SET @NEXTFYEAR += 1
	END
	
	INSERT INTO Ac_Balance_Assist_CheckItems_Detail
	(
		STypeId,
		ATypeId,
		Cid,
		Ascids,
		FieldValue,
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		IniTotal,
		IniTotalFor,
		FEndBalance,
		FEndBalanceFor,
		FYear,
		FPeriod
		,FDebitqty
		,FCreditqty
		,Iniqty
		,FEndqty
	)
	SELECT	Ab.STypeId,
			Ab.ATypeId,
			Ab.Cid,
			Ac.AscIds,
			Abc.TypeId,
			0,--FDebit = ISNULL(SUM(Ab.FDebitTotal),0),
			0,--FDebitFor = ISNULL(SUM(Ab.FDebitTotalFor),0),
			0,--FCredit = ISNULL(SUM(Ab.FCreditTotal),0),
			0,--FCreditFor = ISNULL(SUM(Ab.FCreditTotalFor),0),
			IniTotal = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitTotal),0) - ISNULL(SUM(AB.FCreditTotal),0) ELSE  - ISNULL(SUM(AB.FDebitTotal),0) + ISNULL(SUM(AB.FCreditTotal),0) END,
			IniTotalFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitTotalFor),0) - ISNULL(SUM(AB.FCreditTotalFor),0) ELSE - ISNULL(SUM(AB.FDebitTotalFor),0) + ISNULL(SUM(AB.FCreditTotalFor),0) END,
			FEndBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitTotal),0) - ISNULL(SUM(AB.FCreditTotal),0) ELSE  - ISNULL(SUM(AB.FDebitTotal),0) + ISNULL(SUM(AB.FCreditTotal),0) END,
			FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitTotalFor),0) - ISNULL(SUM(AB.FCreditTotalFor),0) ELSE  - ISNULL(SUM(AB.FDebitTotalFor),0) + ISNULL(SUM(AB.FCreditTotalFor),0) END,
			@NEXTFYEAR,
			@NEXTFPERIOD
			,0
			,0
			,Iniqty = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitQty),0) - ISNULL(SUM(AB.FCreditQty),0) ELSE - ISNULL(SUM(AB.FDebitQty),0) + ISNULL(SUM(AB.FCreditQty),0) END,
			FEndqty = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitQty),0) - ISNULL(SUM(AB.FCreditQty),0) ELSE  - ISNULL(SUM(AB.FDebitQty),0) + ISNULL(SUM(AB.FCreditQty),0) END
			FROM    Ac_Voucher_Bill Ab
	INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
	INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
	INNER JOIN Ac_Account A ON A.TypeId = AB.ATypeId AND A.StypeId = AB.STypeId
	WHERE	Abc.BillNumberId = @BillNumberId
			AND NOT EXISTS(
							SELECT  1
							FROM	Ac_Balance_Assist_CheckItems_Detail D
							WHERE	Ab.STypeId = D.STypeId
									AND Ab.ATypeId = D.ATypeId
									AND Ab.Cid = D.Cid
									AND Ac.AscIds = D.Ascids
									AND Abc.TypeId = D.FieldValue
									AND D.FYear = @NEXTFYEAR
									AND D.FPeriod = @NEXTFPERIOD
			)		
	GROUP BY Ab.ATypeId,
			 Ab.STypeId,
			 Ab.Cid,
			 Ac.AscIds,
			 Abc.TypeId,
			 A.Fdc	 
END



IF @@ERROR <> 0
BEGIN
	RAISERROR('写入科目余额辅助核算信息错误，请确认！',16,1)
	RETURN -6	
END


---------------------------------------------------------修改科目余额表辅助核算项目对照表【综合本位币】信息---------------------------------------------------------
UPDATE	Ac_Balance_Assist_CheckItems_Detail
SET		FDebit = D.FDebit + ISNULL(A.FDebit,0),
		FDebitFor = D.FDebitFor + ISNULL(A.FDebit,0),
		FCredit = D.FCredit + ISNULL(A.FCredit,0),
		FCreditFor = D.FCreditFor + ISNULL(A.FCredit,0)
		,FDebitqty = d.FDebitqty + ISNULL(a.FDebitQty,0)
		,FCreditqty = d.FCreditqty + ISNULL(a.FCreditQty,0)
FROM	Ac_Balance_Assist_CheckItems_Detail D
INNER JOIN (
			SELECT	Ab.STypeId,
					Ab.ATypeId,
					0 AS Cid,
					Ac.AscIds,
					Abc.TypeId AS FieldValue,
					Ab.FYear,
					Ab.FPeriod,
					FDebit = ISNULL(SUM(Ab.FDebitTotal),0),
					FDebitFor = ISNULL(SUM(Ab.FDebitTotal),0),
					FCredit = ISNULL(SUM(Ab.FCreditTotal),0),
					FCreditFor = ISNULL(SUM(Ab.FCreditTotal),0)
					,FDebitQty = ISNULL(SUM(ab.FDebitQty),0)
					,FCreditQty = ISNULL(SUM(ab.FCreditQty),0)
			FROM    Ac_Voucher_Bill Ab			
			INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
			INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
			WHERE	Abc.BillNumberId = @BillNumberId		
			GROUP BY Ab.STypeId,
					 Ab.ATypeId,					 
					 Ac.AscIds,
					 Abc.TypeId,
					 Ab.FYear,
					 Ab.FPeriod		
)A ON D.STypeId = A.STypeId AND D.ATypeId = A.ATypeId AND D.Cid = A.Cid AND D.Ascids = A.AscIds AND D.FieldValue = A.FieldValue
WHERE	D.Cid = 0
		AND D.FYear = @FYear
		AND D.FPeriod = @FPeriod
		

----------更新反月结数据
UPDATE	Ac_Balance_Assist_CheckItems_Detail
SET		IniTotal = CASE WHEN B.Fdc = 1 THEN IniTotal + A.FDebitTotal - A.FCreditTotal ELSE IniTotal - A.FDebitTotal + A.FCreditTotal END,
		IniTotalFor = CASE WHEN B.Fdc = 1 THEN IniTotalFor + A.FDebitTotalFor - A.FCreditTotalFor ELSE IniTotalFor - A.FDebitTotalFor + A.FCreditTotalFor END,
		FEndBalance = CASE WHEN B.Fdc = 1 THEN FEndBalance + A.FDebitTotal - A.FCreditTotal ELSE FEndBalance - A.FDebitTotal + A.FCreditTotal END,
		FEndBalanceFor = CASE WHEN B.Fdc = 1 THEN FEndBalanceFor + A.FDebitTotalFor - A.FCreditTotalFor ELSE FEndBalanceFor - A.FDebitTotalFor + A.FCreditTotalFor END
		,Iniqty = CASE WHEN B.Fdc = 1 THEN Iniqty + A.FDebitqtytotal - A.FCreditqtytotal ELSE Iniqty - A.FDebitqtytotal + A.FCreditqtytotal END,
		FEndqty = CASE WHEN B.Fdc = 1 THEN FEndqty + A.FDebitqtytotal - A.FCreditqtytotal ELSE FEndqty - A.FDebitqtytotal + A.FCreditqtytotal END
		FROM	Ac_Balance_Assist_CheckItems_Detail D
INNER JOIN Ac_Account B ON B.TypeId = D.ATypeId AND B.StypeId = D.STypeId
INNER JOIN (
			SELECT	Ab.STypeId,
					Ab.ATypeId,
					0 AS Cid,
					Ac.AscIds,
					Abc.TypeId AS FieldValue,
					Ab.FYear,
					Ab.FPeriod,
					FDebitTotal = ISNULL(SUM(Ab.FDebitTotal),0),
					FDebitTotalFor =ISNULL(SUM(Ab.FDebitTotalFor),0),
					FCreditTotal = ISNULL(SUM(Ab.FCreditTotal),0),
					FCreditTotalFor = ISNULL(SUM(Ab.FCreditTotalFor),0),
					FDebitqtytotal =ISNULL(SUM(Ab.FDebitQty),0),
					FCreditqtytotal = ISNULL(SUM(Ab.FCreditQty),0)
			FROM    Ac_Voucher_Bill Ab			
			INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
			INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
			WHERE	Abc.BillNumberId = @BillNumberId		
			GROUP BY Ab.STypeId,
					 Ab.ATypeId,
					 Ab.Cid,
					 Ac.AscIds,
					 Abc.TypeId,
					 Ab.FYear,
					 Ab.FPeriod		
)A ON D.STypeId = A.STypeId AND D.ATypeId = A.ATypeId AND D.Cid = A.Cid AND D.Ascids = A.AscIds AND D.FieldValue = A.FieldValue
WHERE	D.Cid = 0
		AND ((D.FYear = @FYear AND CAST(D.FPeriod AS INT) > @FPeriod) OR D.FYear > @FYear)

IF @@ERROR <> 0
BEGIN
	RAISERROR('修改科目余额辅助核算综合本位币信息错误，请确认！',16,1)
	RETURN -6	
END

---------------------------------------------------------写入科目余额表辅助核算项目对照表【综合本位币】信息---------------------------------------------------------
INSERT INTO Ac_Balance_Assist_CheckItems_Detail
(
	STypeId,
	ATypeId,
	Cid,
	Ascids,
	FieldValue,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	IniTotal,
	IniTotalFor,
	FYear,
	FPeriod
	,FDebitqty
	,FCreditqty
	,Iniqty
)
SELECT	Ab.STypeId,
		Ab.ATypeId,
		0 AS Cid,
		Ac.AscIds,
		Abc.TypeId,
		FDebit = ISNULL(SUM(Ab.FDebitTotal),0),
		FDebitFor = ISNULL(SUM(Ab.FDebitTotal),0),
		FCredit = ISNULL(SUM(Ab.FCreditTotal),0),
		FCreditFor = ISNULL(SUM(Ab.FCreditTotal),0),
		0 AS IniTotal,
		0 AS IniTotalFor,
		@FYear AS FYear,
		@FPeriod AS FPeriod
		,FDebitQty = ISNULL(SUM(ab.FDebitQty),0)
		,FCreditQty = ISNULL(SUM(ab.FCreditQty),0)
		,0
FROM    Ac_Voucher_Bill Ab
INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
WHERE	Abc.BillNumberId = @BillNumberId
		AND NOT EXISTS(
						SELECT  1
						FROM	Ac_Balance_Assist_CheckItems_Detail D
						WHERE	D.Cid = 0
								AND Ab.STypeId = D.STypeId
								AND Ab.ATypeId = D.ATypeId								
								AND Ac.AscIds = D.Ascids
								AND Abc.TypeId = D.FieldValue
								AND Ab.FYear = D.FYear
								AND Ab.FPeriod = D.FPeriod
								AND D.FYear = @FYear
								AND D.FPeriod = @FPeriod
		)	
GROUP BY Ab.STypeId,
		 Ab.ATypeId,		 
		 Ac.AscIds,
		 Abc.TypeId	
		 
------------往反月结期间插入数据
SET @LOOP = 0
SET @NEXTFPERIOD = @FPeriod
SET @NEXTFYEAR = @FYear

WHILE @LOOP < @COUNT
BEGIN		
	SET @LOOP += 1
	SET @NEXTFPERIOD += 1
	IF @NEXTFPERIOD > 12
	BEGIN
		SET @NEXTFPERIOD = 1
		SET @NEXTFYEAR += 1
	END
	
	INSERT INTO Ac_Balance_Assist_CheckItems_Detail
	(
		STypeId,
		ATypeId,
		Cid,
		Ascids,
		FieldValue,
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		IniTotal,
		IniTotalFor,
		FEndBalance,
		FEndBalanceFor,
		FYear,
		FPeriod
		,FDebitqty
		,FCreditqty
		,Iniqty
		,FEndqty
	)
	SELECT	Ab.STypeId,
			Ab.ATypeId,
			0 AS Cid,
			Ac.AscIds,
			Abc.TypeId,
			0,--FDebit = ISNULL(SUM(Ab.FDebitTotal),0),
			0,--FDebitFor = ISNULL(SUM(Ab.FDebitTotalFor),0),
			0,--FCredit = ISNULL(SUM(Ab.FCreditTotal),0),
			0,--FCreditFor = ISNULL(SUM(Ab.FCreditTotalFor),0),
			IniTotal = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitTotal),0) - ISNULL(SUM(AB.FCreditTotal),0) ELSE  - ISNULL(SUM(AB.FDebitTotal),0) + ISNULL(SUM(AB.FCreditTotal),0) END,
			IniTotalFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitTotalFor),0) - ISNULL(SUM(AB.FCreditTotalFor),0) ELSE - ISNULL(SUM(AB.FDebitTotalFor),0) + ISNULL(SUM(AB.FCreditTotalFor),0) END,
			FEndBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitTotal),0) - ISNULL(SUM(AB.FCreditTotal),0) ELSE  - ISNULL(SUM(AB.FDebitTotal),0) + ISNULL(SUM(AB.FCreditTotal),0) END,
			FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitTotalFor),0) - ISNULL(SUM(AB.FCreditTotalFor),0) ELSE  - ISNULL(SUM(AB.FDebitTotalFor),0) + ISNULL(SUM(AB.FCreditTotalFor),0) END,
			@NEXTFYEAR,
			@NEXTFPERIOD
			,0
			,0
			,iniqty = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitQty),0) - ISNULL(SUM(AB.FCreditQty),0) ELSE - ISNULL(SUM(AB.FDebitQty),0) + ISNULL(SUM(AB.FCreditQty),0) END,
			FEndqty = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(AB.FDebitQty),0) - ISNULL(SUM(AB.FCreditQty),0) ELSE  - ISNULL(SUM(AB.FDebitQty),0) + ISNULL(SUM(AB.FCreditQty),0) END
			
	FROM    Ac_Voucher_Bill Ab
	INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
	INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
	INNER JOIN Ac_Account A ON A.TypeId = AB.ATypeId AND A.StypeId = AB.STypeId
	WHERE	Abc.BillNumberId = @BillNumberId
		AND NOT EXISTS(
						SELECT  1
						FROM	Ac_Balance_Assist_CheckItems_Detail D
						WHERE	D.Cid = 0
								AND Ab.STypeId = D.STypeId
								AND Ab.ATypeId = D.ATypeId								
								AND Ac.AscIds = D.Ascids
								AND Abc.TypeId = D.FieldValue
								AND D.FYear = @NEXTFYEAR
								AND D.FPeriod = @NEXTFPERIOD
		)	
	GROUP BY Ab.STypeId,
			 Ab.ATypeId,		 
			 Ac.AscIds,
			 Abc.TypeId	,
			 A.Fdc	 
END		 
		

IF @@ERROR <> 0
BEGIN
	RAISERROR('写入科目余额辅助核算综合本位币信息错误，请确认！',16,1)
	RETURN -6	
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Ac_Balance_Cid0]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Ac_Balance_Cid0]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-05
	描述：凭证记账-处理科目余额表综合本位币
	DECLARE @rValue VARCHAR(400) 
	EXEC Gp_Voucher_Auditing_Ac_Balance_Cid0 2,5,'1','2021','00001'
	PRINT(@rValue)
	SELECT * FROM Ac_Balance
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Ac_Balance_Cid0
(
	@BillNumberId	NUMERIC(18,0),	-- 单据编号
	@Cid			INT,			-- 币别ID
	@FPeriod		INT,			-- 会计期间
	@FYear			INT,			-- 会计年度
	@STypeId		VARCHAR(50)		-- 分支机构ID	
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------------------修改科目余额表【综合本位币】信息--------------------------------------------------------------------------
UPDATE	Ac_Balance
SET		FDebit = B.FDebit + ISNULL(M.FDebitTotal,0),
		FDebitFor = B.FDebitFor + ISNULL(M.FDebitTotal,0),
		FCredit = B.FCredit + ISNULL(FCreditTotal,0),
		FCreditFor = B.FCreditFor + ISNULL(M.FCreditTotal,0),
		FYtdDebit = B.FYtdDebit + ISNULL(M.FDebitTotal,0),
		FYtdDebitFor = B.FYtdDebitFor + ISNULL(M.FDebitTotal,0),
		FYtdCredit = B.FYtdCredit + ISNULL(FCreditTotal,0),
		FYtdCreditFor = B.FYtdCreditFor + ISNULL(M.FCreditTotal,0),
		
		FDebitqty = B.FDebitqty + ISNULL(M.FDebitQtytotal,0),
		FCreditqty = B.FCreditqty + ISNULL(FCreditQtytotal,0),
		FYtdDebitqty = B.FYtdDebitqty + ISNULL(M.FDebitQtytotal,0),
		FYtdCreditqty = B.FYtdCreditqty + ISNULL(FCreditQtytotal,0)
FROM	Ac_Balance B
INNER JOIN (
				SELECT  B.STypeId,
						B.ATypeId,
						FDebitTotal = ISNULL(SUM(B.FDebitTotal),0),
						FDebitTotalFor = ISNULL(SUM(B.FDebitTotal),0),
						FCreditTotal = ISNULL(SUM(B.FCreditTotal),0),
						FCreditTotalFor = ISNULL(SUM(B.FCreditTotal),0),
						FDebitQtytotal = ISNULL(SUM(B.FDebitQty),0),
						FCreditQtytotal= ISNULL(SUM(B.FCreditQty),0)
				FROM	Ac_Voucher_Bill B				
				WHERE	B.BillNumberId = @BillNumberId
				GROUP BY B.STypeId,
						 B.ATypeId
				
)M ON B.STypeId = M.STypeId AND B.ATypeId = M.ATypeId
WHERE	B.Cid = 0
		AND B.FYear = @FYear
		AND B.FPeriod = @FPeriod

---------更新反月结的数据
UPDATE	Ac_Balance
SET		FBeginBalance = CASE WHEN A.Fdc = 1 THEN FBeginBalance + V.FDebitTotal - V.FCreditTotal ELSE FBeginBalance - V.FDebitTotal + V.FCreditTotal END,
		FBeginBalanceFor = CASE WHEN A.Fdc = 1 THEN FBeginBalanceFor + V.FDebitTotalFor - V.FCreditTotalFor ELSE FBeginBalanceFor - V.FDebitTotalFor + V.FCreditTotalFor END,
		FEndBalance = CASE WHEN A.Fdc = 1 THEN FEndBalance + V.FDebitTotal - V.FCreditTotal ELSE FEndBalance - V.FDebitTotal + V.FCreditTotal END,
		FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN FEndBalanceFor + V.FDebitTotalFor - V.FCreditTotalFor ELSE FEndBalanceFor - V.FDebitTotalFor + V.FCreditTotalFor END,
		FYtdDebit		= FYtdDebit + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotal,0) ELSE 0 END,
		FYtdDebitFor	= FYtdDebitFor + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotalFor,0) ELSE 0 END,
		FYtdCredit		= FYtdCredit + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotal,0) ELSE 0 END,
		FYtdCreditFor	= FYtdCreditFor + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotalFor,0) ELSE 0 END,
		FBeginqty = CASE WHEN A.Fdc = 1 THEN FBeginqty + V.FDebitQtytotal - V.FCreditQtytotal ELSE FBeginqty - V.FDebitQtytotal + V.FCreditQtytotal END,
		FEndqty = CASE WHEN A.Fdc = 1 THEN FEndqty + V.FDebitQtytotal - V.FCreditQtytotal ELSE FEndqty - V.FDebitQtytotal + V.FCreditQtytotal END,
		FYtdDebitqty	= FYtdDebitqty + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitQtytotal,0) ELSE 0 END,
		FYtdCreditqty		= FYtdCreditqty + CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditQtytotal,0) ELSE 0 END
FROM	Ac_Balance B
INNER JOIN (		
				SELECT	Ab.ATypeId,
						Ab.STypeId,
						ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotal,							
						ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotalFor,
						ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotal,
						ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotalFor,	
						ISNULL(SUM(Ab.FDebitQty),0) AS FDebitQtytotal,
						ISNULL(SUM(Ab.FCreditQty),0) AS FCreditQtytotal								
				FROM	Ac_Voucher_Bill Ab
				WHERE	Ab.BillNumberId = @BillNumberId
				GROUP BY Ab.ATypeId,
						 Ab.STypeId
)V ON B.STypeId = V.STypeId AND B.ATypeId = V.ATypeId
INNER JOIN Ac_Account A ON A.TypeId = B.ATypeId AND A.StypeId = B.STypeId
WHERE	((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
		AND B.Cid = 0


IF @@ERROR <> 0
BEGIN
	RAISERROR('修改科目余额表综合本位币信息错误，请确认！',16,1)
	RETURN -1
END

INSERT INTO Ac_Balance 
(
	STypeId, 
	ATypeId, 
	FBeginBalance, 
	FBeginBalanceFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	Cid, 
	FYtdDebit, 
	FYtdDebitFor, 
	FYtdCredit, 
	FYtdCreditFor, 
	FYear, 
	FPeriod,
	FBeginqty,
	FDebitqty,
	FCreditqty,
	FYtdDebitqty,
	FYtdCreditqty
)
SELECT  B.STypeId,
		B.ATypeId,
		FBeginBalance = 0,
		FBeginBalanceFor = 0,
		FDebit = ISNULL(SUM(B.FDebitTotal),0),
		FDebitFor = ISNULL(SUM(B.FDebitTotal),0),
		FCreditTotal = ISNULL(SUM(B.FCreditTotal),0),
		FDebitFor = ISNULL(SUM(B.FCreditTotal),0),
		0 AS Cid,			
		FYtdDebit = ISNULL(SUM(B.FDebitTotal),0),
		FYtdDebitFor = ISNULL(SUM(B.FDebitTotal),0),	
		FYtdCredit = ISNULL(SUM(B.FCreditTotal),0),
		FYtdCreditFor = ISNULL(SUM(B.FCreditTotal),0),
		@FYear,
		@FPeriod,
		0 AS FBeginqty,
		FDebitQty = ISNULL(SUM(B.FDebitQty),0),
		FCreditQty = ISNULL(SUM(B.FCreditQty),0),
		FYtdDebitqty = ISNULL(SUM(B.FDebitQty),0),
		FYtdCreditqty = ISNULL(SUM(B.FCreditQty),0)					
FROM	Ac_Voucher_Bill B
WHERE	B.BillNumberId = @BillNumberId
		AND NOT EXISTS(
						SELECT  1
						FROM	Ac_Balance V
						WHERE	V.Cid = 0
								AND B.STypeId = V.STypeId
								AND B.ATypeId = V.ATypeId
								AND V.FYear = @FYear
								AND V.FPeriod = @FPeriod
						
		)		
GROUP BY B.STypeId,
		 B.ATypeId	

---------往反月结期间插入数据
DECLARE @COUNT INT
		,@LOOP	INT
		,@NEXTFYEAR	INT
		,@NEXTFPERIOD	INT
SELECT @COUNT = COUNT(*)
FROM	(
			SELECT DISTINCT FYear,FPeriod
			FROM	Ac_Balance
			WHERE	STypeId = @STypeId
			AND ((CAST(FYear AS INT) = CAST(@FYear AS INT) AND CAST(FPeriod AS INT) > CAST(@FPeriod AS INT)) OR CAST(FYear AS INT) > CAST(@FYear AS INT))
		) T

SET @LOOP = 0
SET @NEXTFPERIOD = @FPeriod
SET @NEXTFYEAR = @FYear

WHILE @LOOP < @COUNT
BEGIN		
	SET @LOOP += 1
	SET @NEXTFPERIOD += 1
	IF @NEXTFPERIOD > 12
	BEGIN
		SET @NEXTFPERIOD = 1
		SET @NEXTFYEAR += 1
	END
	
	INSERT INTO Ac_Balance
	(
		STypeId,
		ATypeId,
		FBeginBalance,
		FBeginBalanceFor,
		FEndBalance,
		FEndBalanceFor,
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		FYtdDebit,
		FYtdDebitFor,
		FYtdCredit,
		FYtdCreditFor,
		FPeriod,
		FYear,
		Cid,
		FBeginqty,
		FDebitqty,
		FCreditqty,
		FYtdDebitqty,
		FYtdCreditqty
	)
	SELECT	V.STypeId,
			V.ATypeId,
			FBeginBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			FBeginBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			FEndBalance = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotal),0) - ISNULL(SUM(V.FCreditTotal),0) ELSE  - ISNULL(SUM(V.FDebitTotal),0) + ISNULL(SUM(V.FCreditTotal),0) END,
			FEndBalanceFor = CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitTotalFor),0) - ISNULL(SUM(V.FCreditTotalFor),0) ELSE  - ISNULL(SUM(V.FDebitTotalFor),0) + ISNULL(SUM(V.FCreditTotalFor),0) END,
			0,--FDebit = ISNULL(SUM(V.FDebitTotal),0),		
			0,--FDebitFor = ISNULL(SUM(V.FDebitTotalFor),0),
			0,--FCredit = ISNULL(SUM(V.FCreditTotal),0),
			0,--FCreditFor =  ISNULL(SUM(V.FCreditTotalFor),0),
			FYtdDebit = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitTotal),0) ELSE 0 END,
			FYtdDebitFor = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitTotalFor),0) ELSE 0 END,
			FYtdCredit = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FCreditTotal),0) ELSE 0 END,
			FYtdCreditFor = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FCreditTotalFor),0) ELSE 0 END,
			@NEXTFPERIOD AS Period,
			@NEXTFYEAR AS FYear,
			0 AS Cid,
			CASE WHEN A.Fdc = 1 THEN ISNULL(SUM(V.FDebitQty),0) - ISNULL(SUM(V.FCreditQty),0) ELSE  - ISNULL(SUM(V.FDebitQty),0) + ISNULL(SUM(V.FCreditQty),0) END AS FBeginqty,
			0,--FDebitQty = ISNULL(SUM(V.FDebitQty),0),
			0,--FCreditQty = ISNULL(SUM(V.FCreditQty),0),
			FYtdDebitqty = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitQty),0) ELSE 0 END,
			FYtdCreditqty = CASE WHEN @NEXTFYEAR = @FYear THEN ISNULL(SUM(V.FDebitQty),0) ELSE 0 END
	FROM	Ac_Voucher_Bill V
	INNER JOIN Ac_Account A ON A.TypeId = V.ATypeId AND A.StypeId = V.STypeId
	WHERE	V.BillNumberId = @BillNumberId
			AND NOT EXISTS(
							SELECT  1
							FROM	Ac_Balance B
							WHERE	B.Cid = 0
									AND B.STypeId = V.STypeId
									AND B.ATypeId = V.ATypeId
									AND B.FYear = @NEXTFYEAR
									AND B.FPeriod = @NEXTFPERIOD
						  )
	GROUP BY V.ATypeId,
			 V.STypeId,
			 A.Fdc	
			 
END
		 
IF @@ERROR <> 0
BEGIN
	RAISERROR('写入科目余额表综合本位币信息错误，请确认！',16,1)
	RETURN -1
END			 

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Batch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Batch]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2013-05-29
	描述：凭证批量记账
	DECLARE @rValue VARCHAR(400) 
	EXEC Gp_Voucher_Auditing_Batch '00001','00001'
	PRINT(@rValue)
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Batch
(
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@stypeid		VARCHAR(50)				-- 分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
		
--采取新思路，直接修改未记账凭证的记账状态，然后计算该分支机构当期数据
DECLARE @FPeriod		INT,
		@FYear			INT,
		@PassCount		INT,
		@FailtCount		INT,
		@acvhrchk		INT,	--必须审核
		@actellerchk	INT,	--必须复核
		@newSTypeId		VARCHAR(50),
		@acsummary		INT		--每行必须有摘要
		

SELECT	@newSTypeId = VerifyID
FROM	SType S 
WHERE	TypeId = @stypeid

--获取当前分支机构当前年度、会计期间	
SELECT @FYear=FYear,@FPeriod=FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE STypeId = @newSTypeId
SELECT @acvhrchk = SubValue FROM SysData WHERE subname ='acvhrchk'
SELECT @actellerchk = SubValue FROM SysData WHERE subname ='actellerchk'
SELECT @acsummary = SubValue FROM sysdata WHERE SubName='acsummary'

CREATE TABLE  #ResultTable
(
	OrderId	INT 
	,BillCode	VARCHAR(500)
	,Msg	VARCHAR(500)
	,billnumberid DECIMAL(24,0)
)
--统计不能记账的凭证
--3:必须审核的
INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
	,billnumberid
)
SELECT	DISTINCT 3
		,'【'+G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))+'】'
		,' 未审核，系统配置必须审核，请先审核凭证！'
		,v.BillNumberId
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE	IfCheck = 'f'
		AND STypeId = @stypeid
		AND FPeriod = @FPeriod
		AND FYear   = @FYear
		AND @acvhrchk = 1 
		AND FChecked = 0
		AND MarkError = ''

SET @FailtCount = @@ROWCOUNT

--4:必须复核的
INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
	,billnumberid
)
SELECT	DISTINCT 4
		,'【'+G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))+'】'
		,' 未复核，系统配置必须复核，请先复核凭证！'
		,v.BillNumberId
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE	IfCheck = 'f'
		AND STypeId = @stypeid
		AND FPeriod = @FPeriod
		AND FYear   = @FYear
		AND @actellerchk = 1 
		AND ISNULL(ReCheckId,'') = ''
		AND FChecked <> -1
		AND MarkError = ''
		
SET @FailtCount += @@ROWCOUNT

--5:必须每行都有摘要
INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
	,billnumberid
)
SELECT	DISTINCT 5
		,'【'+G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))+'】'
		,' 分录摘要不全，系统配置每条分录必须要有摘要，请调整凭证！'
		,v.BillNumberId
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId = V.BillNumberId
WHERE	IfCheck = 'f'
		AND V.STypeId = @stypeid
		AND V.FPeriod = @FPeriod
		AND V.FYear   = @FYear
		AND @acsummary = 1 
		AND FChecked <> -1
		AND MarkError = ''
		AND B.Summary = ''
		
SET @FailtCount += @@ROWCOUNT

INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
	,billnumberid
)
SELECT	2
		,'未能记账凭证总数：'
		,CAST(@FailtCount AS VARCHAR)
		,0
		
--统计能记账的凭证
CREATE TABLE #Result
(
	nId				INT IDENTITY(1,1),
	BillNumberId	NUMERIC(18,0),
	FPeriod			INT,
	FYear			VARCHAR(10),	
	STypeId			VARCHAR(100)
	
)
INSERT INTO #Result(BillNumberId,FPeriod,FYear,STypeId) 
SELECT	BillNumberId,FPeriod,FYear,STypeId 
FROM	Ac_Voucher V
WHERE	IfCheck = 'f'
		AND STypeId = @newSTypeId
		AND FPeriod = @FPeriod
		AND FYear   = @FYear
		AND MarkError = ''	--标错
		AND FChecked <> -1	--作废
		AND NOT EXISTS(SELECT TOP 1 1 FROM #ResultTable t WHERE t.billnumberid = v.BillNumberId)
ORDER BY BillNumberId ASC	

SET @PassCount = @@ROWCOUNT

UPDATE Ac_Voucher 
SET	IfCheck = 't'
	,Audited = 1
	,TallyId = @szCheckMan
	,posttime = GETDATE()
FROM	#Result R
WHERE	R.BillNumberId = Ac_Voucher.BillNumberId

INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
)
SELECT	1
		,'成功记账凭证总数：'
		,CAST(@PassCount AS VARCHAR)

SELECT *
INTO #VOUCHERDATA
FROM
(
	SELECT	B.STypeId
			,B.ATypeId
			,B.Cid
			,B.FYear
			,B.FPeriod
			,SUM(B.FDebitTotal) AS FDebitTotal
			,SUM(B.FDebitTotalFor) AS FDebitTotalFor
			,SUM(B.FCreditTotal) AS FCreditTotal
			,SUM(B.FCreditTotalFor) AS FCreditTotalFor
			,SUM(B.FDebitQty) AS FDebitQty
			,SUM(B.FCreditQty) AS FCreditQty
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotalFor-B.FCreditTotalFor) ELSE (-B.FDebitTotalFor+B.FCreditTotalFor) END) AS balancefor
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
	FROM	Ac_Voucher_Bill B
	INNER JOIN #Result R ON R.BillNumberId = B.BillNumberId
	GROUP BY B.STypeId,B.ATypeId,B.Cid,B.FYear,B.FPeriod
	UNION ALL
	SELECT	B.STypeId
			,B.ATypeId
			,0
			,B.FYear
			,B.FPeriod
			,SUM(B.FDebitTotal) AS FDebitTotal
			,SUM(B.FDebitTotal) AS FDebitTotalFor
			,SUM(B.FCreditTotal) AS FCreditTotal
			,SUM(B.FCreditTotal) AS FCreditTotalFor
			,SUM(B.FDebitQty) AS FDebitQty
			,SUM(B.FCreditQty) AS FCreditQty
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END ) AS balancefor
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
	FROM	Ac_Voucher_Bill B
	INNER JOIN #Result R ON R.BillNumberId = B.BillNumberId
	GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod
) X
--修改当期数据
MERGE INTO Ac_Balance AS T
USING #VOUCHERDATA AS S
ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod
WHEN MATCHED
THEN UPDATE SET T.FDebit += S.FDebitTotal,T.FDebitFor += S.FDebitTotalFor,T.FCredit+=S.FCreditTotal,T.FCreditFor+=S.FCreditTotalFor
				,T.FYtdDebit+=s.FDebitTotal,T.FYtdDebitFor+= S.FDebitTotalFor,T.FYtdCredit+=S.FCreditTotal,T.FYtdCreditFor+=S.FCreditTotalFor
				,T.FEndBalance+=S.balance,T.FEndBalanceFor+=S.balancefor
				,T.FDebitqty += S.FDebitQty,T.FCreditqty += S.FCreditQty
				,T.FYtdDebitqty += S.FDebitQty,T.FYtdCreditqty += S.FCreditQty
				,T.FEndqty += S.balanceqty
WHEN NOT MATCHED BY TARGET
THEN INSERT(STypeId,ATypeId,FBeginBalance,FBeginBalanceFor,FDebit,FDebitFor,FCredit,FCreditFor,Cid,FEndBalance,FEndBalanceFor
			,FYtdDebit,FYtdDebitFor,FYtdCredit,FYtdCreditFor,FYear,FPeriod
			,FDebitqty,FCreditqty,FYtdDebitqty,FYtdCreditqty,FEndqty,FBeginqty)
	 VALUES(S.stypeid,s.atypeid,0,0,s.fdebittotal,s.fdebittotalfor,s.fcredittotal,s.fcredittotalfor,s.cid,s.balance,s.balancefor
			,s.fdebittotal,s.fdebittotalfor,s.fcredittotal,s.fcredittotalfor,s.fyear,s.fperiod
			,S.FDebitqty,S.FCreditqty,S.FDebitqty,S.FCreditqty,S.balanceqty,0);

--修改后期数据
UPDATE T SET T.FYtdDebit+=CASE WHEN T.FYear=S.FYear THEN s.FDebitTotal ELSE 0 END
			,T.FYtdDebitFor+= CASE WHEN T.FYear=S.FYear THEN S.FDebitTotalFor ELSE 0 END
			,T.FYtdCredit+=CASE WHEN T.FYear=S.FYear THEN S.FCreditTotal ELSE 0 END
			,T.FYtdCreditFor+=CASE WHEN T.FYear=S.FYear THEN S.FCreditTotalFor ELSE 0 END
			,T.FBeginBalance+=S.balance,T.FBeginBalanceFor+=S.balancefor
			,T.FEndBalance+=S.balance,T.FEndBalanceFor+=S.balancefor
			,T.FYtdDebitqty += S.FDebitQty,T.FYtdCreditqty += S.FCreditQty
			,T.FBeginqty += S.balanceqty
			,T.FEndqty += S.balanceqty
FROM Ac_Balance T
INNER JOIN #VOUCHERDATA S ON S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND ((S.FYear = T.FYear AND S.FPeriod < T.FPeriod) OR S.FYear < T.FYear)

SELECT T.FYear,T.FPeriod 
INTO #PERIODS
FROM Ac_Balance T 
WHERE ((T.FYear = @FYear AND T.FPeriod > @FPeriod) OR T.FYear > @FYear) 
GROUP BY T.FYear,T.FPeriod

INSERT INTO Ac_Balance
(
		STypeId,
		ATypeId,
		FBeginBalance,
		FBeginBalanceFor,
		FEndBalance,
		FEndBalanceFor,
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		FYtdDebit,
		FYtdDebitFor,
		FYtdCredit,
		FYtdCreditFor,
		FPeriod,
		FYear,
		Cid,
		FBeginqty,
		FDebitqty,
		FCreditqty,
		FYtdDebitqty,
		FYtdCreditqty
)
SELECT C.STypeId,
		C.ATypeId,
		C.balance,
		C.balancefor ,
		C.balance,
		C.balancefor ,
		0,--FDebit = ISNULL(SUM(V.FDebitTotal),0),		
		0,--FDebitFor = ISNULL(SUM(V.FDebitTotalFor),0),
		0,--FCredit = ISNULL(SUM(V.FCreditTotal),0),
		0,--FCreditFor =  ISNULL(SUM(V.FCreditTotalFor),0),
		FYtdDebit = CASE WHEN V.FYear = @FYear THEN ISNULL(C.FDebitTotal,0) ELSE 0 END,
		FYtdDebitFor = CASE WHEN V.FYear = @FYear THEN ISNULL(C.FDebitTotalFor,0) ELSE 0 END,
		FYtdCredit = CASE WHEN V.FYear = @FYear THEN ISNULL(C.FCreditTotal,0) ELSE 0 END,
		FYtdCreditFor = CASE WHEN V.FYear = @FYear THEN ISNULL(C.FCreditTotalFor,0) ELSE 0 END,
		V.FPeriod  AS Period,
		V.FYear AS FYear,
		C.Cid AS Cid,
		C.balanceqty,
		0,--FDebitQty = ISNULL(SUM(V.FDebitQty),0),
		0,--FCreditQty = ISNULL(SUM(V.FCreditQty),0),
		FYtdDebitqty = CASE WHEN V.FYear = @FYear THEN ISNULL(C.FDebitQty,0) ELSE 0 END,
		FYtdCreditqty = CASE WHEN V.FYear = @FYear THEN ISNULL(C.FDebitQty,0) ELSE 0 END
FROM #VOUCHERDATA C
INNER JOIN #PERIODS V ON 1=1
WHERE NOT EXISTS(
					SELECT	TOP 1 1 
					FROM	Ac_Balance B 
					WHERE	B.STypeId = c.STypeId 
						AND B.ATypeId = c.ATypeId 
						AND B.Cid = c.Cid 
						AND (B.FYear = V.FYear AND B.FPeriod = V.FPeriod) 
				)
				
;WITH AccountWithAssistCheckItems AS
(
	SELECT	B.STypeId
			,B.ATypeId
			,B.Cid
			,B.FYear
			,B.FPeriod
			,B.FBeginBalance
			,B.FBeginBalanceFor
			,B.FBeginqty
			,B.FDebit
			,B.FDebitFor
			,B.FDebitqty
			,B.FCredit
			,B.FCreditFor
			,B.FCreditqty
			,B.FEndBalance
			,B.FEndBalanceFor
			,B.FEndqty
			,B.FYtdDebit
			,B.FYtdDebitFor
			,B.FYtdDebitqty
			,B.FYtdCredit
			,B.FYtdCreditFor
			,B.FYtdCreditqty
	FROM	Ac_Balance B
	INNER JOIN (SELECT ATYPEID FROM Ac_Account_Assist_CheckItems WHERE STypeId = @newSTypeId GROUP BY ATypeId) A ON A.ATypeId = B.ATypeId
	WHERE	B.STypeId = @newSTypeId
		AND	((B.FYear = @FYear AND	B.FPeriod >= @FPeriod) OR B.FYear > @FYear)
)
MERGE INTO Ac_Balance_Assist_CheckItems AS T
USING AccountWithAssistCheckItems AS S
ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod
WHEN MATCHED
THEN UPDATE SET T.FDebit = S.FDebit,T.FDebitFor = S.FDebitFor,T.FCredit=S.FCredit,T.FCreditFor=S.FCreditFor
				,T.FEndBalance=S.FEndBalance,T.FEndBalanceFor=S.FEndBalanceFor
				,T.IniTotal=s.FBeginBalance,T.IniTotalFor= S.FBeginBalanceFor
				,T.FDebitqty = S.FDebitqty,T.FCreditqty = S.FCreditqty
				,T.FEndqty = S.FEndqty
				,T.Iniqty = S.FBeginqty
WHEN NOT MATCHED BY TARGET
THEN INSERT(STypeId,ATypeId,IniTotal,IniTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,Cid,FEndBalance,FEndBalanceFor,FYear,FPeriod
			,FDebitqty,FCreditqty,FEndqty,Iniqty)
	 VALUES(S.stypeid,s.atypeid,s.FBeginBalance,S.FBeginBalanceFor,s.fdebit,s.fdebitfor,s.fcredit,s.fcreditfor,s.cid,s.FEndBalance,s.FEndBalancefor
			,s.fyear,s.fperiod
			,S.FDebitqty,S.FCreditqty,S.FEndqty,S.FBeginqty);
	
--;WITH VoucherDataWithAssistCheckItems AS
SELECT *
INTO #VoucherDataWithAssistCheckItems
FROM
(
	SELECT	B.STypeId
			,B.ATypeId
			,B.Cid
			,B.FYear
			,B.FPeriod
			,Ac.AscIds
			,Abc.TypeId AS FieldValue
			,SUM(B.FDebitTotal) AS FDebit
			,SUM(B.FDebitTotalFor) AS FDebitFor
			,SUM(B.FCreditTotal) AS FCredit
			,SUM(B.FCreditTotalFor) AS FCreditFor
			,SUM(B.FDebitQty) AS FDebitQty
			,SUM(B.FCreditQty) AS FCreditQty
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotalFor-B.FCreditTotalFor) ELSE (-B.FDebitTotalFor+B.FCreditTotalFor) END) AS balancefor
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
	FROM	Ac_Voucher_Bill B
	INNER JOIN #Result R ON R.BillNumberId = B.BillNumberId
	INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = b.ID
	INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
	GROUP BY B.STypeId,B.ATypeId,B.Cid,B.FYear,B.FPeriod,ac.AscIds,abc.TypeId
	UNION ALL
	SELECT	B.STypeId
			,B.ATypeId
			,0
			,B.FYear
			,B.FPeriod
			,Ac.AscIds
			,Abc.TypeId AS FieldValue
			,SUM(B.FDebitTotal) AS FDebit
			,SUM(B.FDebitTotal) AS FDebitFor
			,SUM(B.FCreditTotal) AS FCredit
			,SUM(B.FCreditTotal) AS FCreditFor
			,SUM(B.FDebitQty) AS FDebitQty
			,SUM(B.FCreditQty) AS FCreditQty
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END ) AS balancefor
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
	FROM	Ac_Voucher_Bill B
	INNER JOIN #Result R ON R.BillNumberId = B.BillNumberId
	INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = b.ID
	INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
	GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod,ac.AscIds,abc.TypeId
) X
--修改当期数据
MERGE INTO Ac_Balance_Assist_CheckItems_Detail AS T
USING #VoucherDataWithAssistCheckItems AS S
ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND S.AscIds=T.AscIds AND S.FieldValue=T.FieldValue AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod
WHEN MATCHED
THEN UPDATE SET T.FDebit += S.FDebit,T.FDebitFor += S.FDebitFor,T.FCredit+=S.FCredit,T.FCreditFor+=S.FCreditFor
				,T.FEndBalance+=S.balance,T.FEndBalanceFor+=S.balanceFor
				,T.FDebitqty += S.FDebitQty,T.FCreditqty += S.FCreditQty
				,T.FEndqty += S.balanceqty
WHEN NOT MATCHED BY TARGET
THEN INSERT(STypeId,ATypeId,AscIds,FieldValue,IniTotal,IniTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,Cid,FEndBalance,FEndBalanceFor,FYear,FPeriod
			,FDebitqty,FCreditqty,FEndqty,Iniqty)
	 VALUES(S.stypeid,s.atypeid,S.AscIds,S.FieldValue,0,0,s.fdebit,s.fdebitfor,s.fcredit,s.fcreditfor,s.cid,s.Balance,s.Balancefor
			,s.fyear,s.fperiod
			,S.FDebitqty,S.FCreditqty,S.balanceqty,0);
			
--修改后期数据
UPDATE T SET T.IniTotal+=S.balance,T.IniTotalFor+=S.balancefor
			,T.FEndBalance+=S.balance,T.FEndBalanceFor+=S.balancefor
			,T.Iniqty += S.balanceqty
			,T.FEndqty += S.balanceqty
FROM Ac_Balance_Assist_CheckItems_Detail T
INNER JOIN #VoucherDataWithAssistCheckItems S ON S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid 
												AND S.AscIds = T.Ascids AND S.FieldValue = T.FieldValue
												AND ((S.FYear = T.FYear AND S.FPeriod < T.FPeriod) OR S.FYear < T.FYear)
												
INSERT INTO Ac_Balance_Assist_CheckItems_Detail
(
	STypeId,
	ATypeId,
	Cid,
	Ascids,
	FieldValue,
	FDebit,
	FDebitFor,
	FCredit,
	FCreditFor,
	IniTotal,
	IniTotalFor,
	FEndBalance,
	FEndBalanceFor,
	FYear,
	FPeriod
	,FDebitqty
	,FCreditqty
	,Iniqty
	,FEndqty
)
SELECT	Ab.STypeId,
		Ab.ATypeId,
		Ab.Cid,
		Ab.AscIds,
		Ab.FieldValue,
		0,--FDebit = ISNULL(SUM(Ab.FDebitTotal),0),
		0,--FDebitFor = ISNULL(SUM(Ab.FDebitTotalFor),0),
		0,--FCredit = ISNULL(SUM(Ab.FCreditTotal),0),
		0,--FCreditFor = ISNULL(SUM(Ab.FCreditTotalFor),0),
		IniTotal = ab.balance,
		IniTotalFor = ab.balancefor,
		FEndBalance = ab.balance,
		FEndBalanceFor = ab.balancefor,
		V.FYear,
		V.FPeriod
		,0
		,0
		,Iniqty = Ab.balanceqty,
		FEndqty = ab.balanceqty
FROM    #VoucherDataWithAssistCheckItems Ab
INNER JOIN #PERIODS V ON 1=1
WHERE NOT EXISTS(
					SELECT  TOP 1 1
					FROM	Ac_Balance_Assist_CheckItems_Detail D
					WHERE	Ab.STypeId = D.STypeId
							AND Ab.ATypeId = D.ATypeId
							AND Ab.Cid = D.Cid
							AND AB.AscIds = D.Ascids
							AND Ab.FieldValue = D.FieldValue
							AND D.FYear = V.FYear
							AND D.FPeriod = V.FPeriod
			)											

--整理最后展示的结果
TRUNCATE TABLE Ac_Batch_Bills_Result
INSERT INTO Ac_Batch_Bills_Result(BillCode,Msg)
SELECT	BillCode,Msg
FROM	#ResultTable
ORDER BY OrderId ASC

DROP TABLE #VOUCHERDATA,#VoucherDataWithAssistCheckItems,#PERIODS,#Result
--将值置为0，表示处理完成
UPDATE Ac_Batch_Bills SET BillNumberId = 0	

SELECT * FROM Ac_Batch_Bills_Result

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Batch_Convert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Batch_Convert]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2013-07-19
	描述：凭证批量反记账
	DECLARE @rValue VARCHAR(400) 
	EXEC Gp_Voucher_Auditing_Batch_Convert '00001','00001'
	PRINT(@rValue)
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Batch_Convert
(
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@stypeid		VARCHAR(50)				-- 分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

DECLARE @BillCount		INT,
		@PassCount		INT,
		@FailtCount		INT,
		@FPeriod		INT,
		@FYear			VARCHAR(MAX)

--获取当前分支机构当前年度、会计期间	
SELECT @FYear=FYear,@FPeriod=FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE STypeId = @STypeId

CREATE TABLE  #ResultTable
(
	OrderId	INT 
	,BillCode	VARCHAR(500)
	,Msg	VARCHAR(500)
	,billnumerid	DECIMAL(18,0)
)

--统计不能反记账的凭证
--3:已经出纳签字的
INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
	,billnumerid
)
SELECT	DISTINCT 3
		,G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))
		,' 凭证已出纳签字，请先反签字再反记账凭证！'
		,v.BillNumberId
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE	IfCheck = 't'
		AND STypeId = @stypeid
		AND FPeriod = @FPeriod
		AND FYear   = @FYear
		AND Teller <> ''

SET @FailtCount = @@ROWCOUNT
SET @BillCount = @FailtCount

--4:凭证存在分录被日记账引用
INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
	,billnumerid
)
SELECT	DISTINCT 4
		,G.FullName + '-' + CAST(V.FlowNo AS VARCHAR(200))
		,' 凭证存在分录被日记账引用，请先删除相应日记账再反记账凭证！'
		,v.BillNumberId
FROM	Ac_Voucher V
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
INNER JOIN Ac_Voucher_Bill VB ON VB.BillNumberId = V.BillNumberId
INNER JOIN Te_Journal_Detail TD ON TD.VoucherId = VB.ID
WHERE	V.IfCheck = 't'
		AND V.STypeId = @stypeid
		AND V.FPeriod = @FPeriod
		AND V.FYear   = @FYear

SET @FailtCount += @@ROWCOUNT
SET @BillCount += @FailtCount

INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
	,billnumerid
)
SELECT	2
		,'未能反记账凭证总数：'
		,CAST(@FailtCount AS VARCHAR)
		,0
		
--统计能反记账的凭证
CREATE TABLE #VouherBill
(
	BillNumberId	NUMERIC(18,0)
)

INSERT INTO #VouherBill(BillNumberId)
SELECT	V.BillNumberId
FROM	Ac_Voucher V
WHERE	V.IfCheck = 't'
		AND V.STypeId = @stypeid
		AND V.FPeriod = @FPeriod
		AND V.FYear   = @FYear
		AND NOT EXISTS(SELECT TOP 1 1 FROM #ResultTable r WHERE r.billnumerid = v.BillNumberId)
GROUP BY V.BillNumberId

SET @PassCount = @@ROWCOUNT
SET @BillCount += @PassCount

INSERT INTO #ResultTable
(
	OrderId
	,BillCode
	,Msg
)
SELECT	1
		,'成功反记账凭证总数：'
		,CAST(@PassCount AS VARCHAR)

SELECT *
INTO #VOUCHERDATA
FROM
(
	SELECT	B.STypeId
			,B.ATypeId
			,B.Cid
			,B.FYear
			,B.FPeriod
			,SUM(B.FDebitTotal) AS FDebitTotal
			,SUM(B.FDebitTotalFor) AS FDebitTotalFor
			,SUM(B.FCreditTotal) AS FCreditTotal
			,SUM(B.FCreditTotalFor) AS FCreditTotalFor
			,SUM(B.FDebitQty) AS FDebitQty
			,SUM(B.FCreditQty) AS FCreditQty
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotalFor-B.FCreditTotalFor) ELSE (-B.FDebitTotalFor+B.FCreditTotalFor) END) AS balancefor
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
	FROM	Ac_Voucher_Bill B
	INNER JOIN #VouherBill R ON R.BillNumberId = B.BillNumberId
	GROUP BY B.STypeId,B.ATypeId,B.Cid,B.FYear,B.FPeriod
	UNION ALL
	SELECT	B.STypeId
			,B.ATypeId
			,0
			,B.FYear
			,B.FPeriod
			,SUM(B.FDebitTotal) AS FDebitTotal
			,SUM(B.FDebitTotal) AS FDebitTotalFor
			,SUM(B.FCreditTotal) AS FCreditTotal
			,SUM(B.FCreditTotal) AS FCreditTotalFor
			,SUM(B.FDebitQty) AS FDebitQty
			,SUM(B.FCreditQty) AS FCreditQty
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END ) AS balancefor
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
	FROM	Ac_Voucher_Bill B
	INNER JOIN #VouherBill R ON R.BillNumberId = B.BillNumberId
	GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod
) X

--修改当期数据
UPDATE T SET T.FDebit -= S.FDebitTotal,T.FDebitFor -= S.FDebitTotalFor,T.FCredit-=S.FCreditTotal,T.FCreditFor-=S.FCreditTotalFor
				,T.FYtdDebit-=s.FDebitTotal,T.FYtdDebitFor-= S.FDebitTotalFor,T.FYtdCredit-=S.FCreditTotal,T.FYtdCreditFor-=S.FCreditTotalFor
				,T.FEndBalance-=S.balance,T.FEndBalanceFor-=S.balancefor
				,T.FDebitqty -= S.FDebitQty,T.FCreditqty -= S.FCreditQty
				,T.FYtdDebitqty -= S.FDebitQty,T.FYtdCreditqty -= S.FCreditQty
				,T.FEndqty -= S.balanceqty
FROM Ac_Balance T
INNER JOIN #VOUCHERDATA S ON S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod

--修改后期数据
UPDATE T SET T.FYtdDebit-=CASE WHEN T.FYear=S.FYear THEN s.FDebitTotal ELSE 0 END
			,T.FYtdDebitFor-= CASE WHEN T.FYear=S.FYear THEN S.FDebitTotalFor ELSE 0 END
			,T.FYtdCredit-=CASE WHEN T.FYear=S.FYear THEN S.FCreditTotal ELSE 0 END
			,T.FYtdCreditFor-=CASE WHEN T.FYear=S.FYear THEN S.FCreditTotalFor ELSE 0 END
			,T.FBeginBalance-=S.balance,T.FBeginBalanceFor-=S.balancefor
			,T.FEndBalance-=S.balance,T.FEndBalanceFor-=S.balancefor
			,T.FYtdDebitqty -= CASE WHEN T.FYear=S.FYear THEN S.FDebitQty ELSE 0 END
			,T.FYtdCreditqty -= CASE WHEN T.FYear=S.FYear THEN S.FCreditQty ELSE 0 END
			,T.FBeginqty -= S.balanceqty
			,T.FEndqty -= S.balanceqty
FROM Ac_Balance T
INNER JOIN #VOUCHERDATA S ON S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND ((S.FYear = T.FYear AND S.FPeriod < T.FPeriod) OR s.FYear < t.FYear)

;WITH AccountWithAssistCheckItems AS
(
	SELECT	B.STypeId
			,B.ATypeId
			,B.Cid
			,B.FYear
			,B.FPeriod
			,B.FBeginBalance
			,B.FBeginBalanceFor
			,B.FBeginqty
			,B.FDebit
			,B.FDebitFor
			,B.FDebitqty
			,B.FCredit
			,B.FCreditFor
			,B.FCreditqty
			,B.FEndBalance
			,B.FEndBalanceFor
			,B.FEndqty
			,B.FYtdDebit
			,B.FYtdDebitFor
			,B.FYtdCredit
			,B.FYtdCreditFor
	FROM	Ac_Balance B
	INNER JOIN (SELECT ATYPEID FROM Ac_Account_Assist_CheckItems WHERE STypeId = @STypeId GROUP BY ATypeId) A ON A.ATypeId = B.ATypeId
	WHERE	B.STypeId = @STypeId
		AND	((B.FYear = @FYear AND	B.FPeriod >= @FPeriod) OR B.FYear > @FYear)
)
UPDATE T SET T.FDebit = S.FDebit,T.FDebitFor = S.FDebitFor,T.FCredit=S.FCredit,T.FCreditFor=S.FCreditFor
			,T.FEndBalance=S.FEndBalance,T.FEndBalanceFor=S.FEndBalanceFor
			,T.IniTotal=s.FBeginBalance,T.IniTotalFor= S.FBeginBalanceFor
			,T.FDebitqty = S.FDebitqty,T.FCreditqty = S.FCreditqty
			,T.FEndqty = S.FEndqty
			,T.Iniqty = S.FBeginqty
FROM Ac_Balance_Assist_CheckItems T
INNER JOIN AccountWithAssistCheckItems S ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod

SELECT *
INTO #VoucherDataWithAssistCheckItems 
FROM
(
	SELECT	B.STypeId
			,B.ATypeId
			,B.Cid
			,B.FYear
			,B.FPeriod
			,Ac.AscIds
			,Abc.TypeId AS FieldValue
			,SUM(B.FDebitTotal) AS FDebit
			,SUM(B.FDebitTotalFor) AS FDebitFor
			,SUM(B.FCreditTotal) AS FCredit
			,SUM(B.FCreditTotalFor) AS FCreditFor
			,SUM(B.FDebitQty) AS FDebitQty
			,SUM(B.FCreditQty) AS FCreditQty
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotalFor-B.FCreditTotalFor) ELSE (-B.FDebitTotalFor+B.FCreditTotalFor) END) AS balancefor
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
	FROM	Ac_Voucher_Bill B
	INNER JOIN #VouherBill R ON R.BillNumberId = B.BillNumberId
	INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = b.ID
	INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
	GROUP BY B.STypeId,B.ATypeId,B.Cid,B.FYear,B.FPeriod,ac.AscIds,abc.TypeId
	UNION ALL
	SELECT	B.STypeId
			,B.ATypeId
			,0
			,B.FYear
			,B.FPeriod
			,Ac.AscIds
			,Abc.TypeId AS FieldValue
			,SUM(B.FDebitTotal) AS FDebit
			,SUM(B.FDebitTotal) AS FDebitFor
			,SUM(B.FCreditTotal) AS FCredit
			,SUM(B.FCreditTotal) AS FCreditFor
			,SUM(B.FDebitQty) AS FDebitQty
			,SUM(B.FCreditQty) AS FCreditQty
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END ) AS balancefor
			,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
	FROM	Ac_Voucher_Bill B
	INNER JOIN #VouherBill R ON R.BillNumberId = B.BillNumberId
	INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = b.ID
	INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
	GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod,ac.AscIds,abc.TypeId
)x

--修改当期数据
UPDATE T SET T.FDebit -= S.FDebit,T.FDebitFor -= S.FDebitFor,T.FCredit-=S.FCredit,T.FCreditFor-=S.FCreditFor
			,T.FEndBalance-=S.balance,T.FEndBalanceFor-=S.balanceFor
			,T.FDebitqty -= S.FDebitQty,T.FCreditqty -= S.FCreditQty
			,T.FEndqty -= S.balanceqty
FROM Ac_Balance_Assist_CheckItems_Detail T 
INNER JOIN #VoucherDataWithAssistCheckItems S ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid 
												AND S.AscIds=T.AscIds AND S.FieldValue=T.FieldValue AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod

--修改后期数据
UPDATE T SET t.IniTotal -= s.balance,t.IniTotalFor-=s.balancefor
			,T.FEndBalance-=S.balance,T.FEndBalanceFor-=S.balanceFor
			,t.Iniqty -= s.balanceqty
			,T.FEndqty -= S.balanceqty
FROM Ac_Balance_Assist_CheckItems_Detail T 
INNER JOIN #VoucherDataWithAssistCheckItems S ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid 
												AND S.AscIds=T.AscIds AND S.FieldValue=T.FieldValue 
												AND ((S.FYear = T.FYear AND S.FPeriod < T.FPeriod) OR s.FYear < t.FYear)

--整理最后展示的结果
TRUNCATE TABLE Ac_Batch_Bills_Result
INSERT INTO Ac_Batch_Bills_Result(BillCode,Msg)
SELECT	BillCode,Msg
FROM	#ResultTable
ORDER BY OrderId ASC

UPDATE V SET IfCheck = 'f' 
			 ,Audited = 0
			 ,TallyId = ''
FROM Ac_Voucher V
INNER JOIN #VouherBill TV ON TV.BillNumberId = V.BillNumberId

--将值置为0，表示处理完成
UPDATE Ac_Batch_Bills SET BillNumberId = 0	

SELECT * FROM Ac_Batch_Bills_Result

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Batch_Hint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Batch_Hint]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2013-05-29
	描述：凭证批量记账
	DECLARE @rValue NUMERIC(18,0)
	EXEC Gp_Voucher_Auditing_Batch_Hint '00001','1',@rValue OUTPUT
	SELECT(@rValue)
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Batch_Hint
(	
	@stypeid		VARCHAR(50),			-- 分支机构
	@flag			INT,					--标识   1.记账   0.反记账 
	@firtin			INT,
	@rCount			NUMERIC(18,0) OUTPUT	--返回单据张数
)
--@encode$--
AS
SET NOCOUNT ON


DECLARE @FPeriod INT,
		@FYear	 VARCHAR(MAX)

IF @firtin = '1'
BEGIN
	--获取当前分支机构当前年度、会计期间	
	SELECT @FYear=FYear,@FPeriod=FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE STypeId = @STypeId

	IF @flag = 1
	BEGIN
		SELECT	@rCount = ISNULL(COUNT(*),0)
		FROM	Ac_Voucher V
		INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
		WHERE	V.IfCheck = 'f'
				AND V.STypeId = @stypeid
				AND V.FPeriod = @FPeriod
				AND V.FYear   = @FYear
				AND MarkError = ''	--标错
				AND FChecked <> -1	--作废
	END
	ELSE
	BEGIN
		SELECT	@rCount = ISNULL(COUNT(*),0)
		FROM	Ac_Voucher V
		INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
		WHERE	V.IfCheck = 't'
				AND V.STypeId = @stypeid
				AND V.FPeriod = @FPeriod
				AND V.FYear   = @FYear
	END
	
	--写入数据
	TRUNCATE TABLE Ac_Batch_Bills
	INSERT INTO Ac_Batch_Bills(BillNumberId)VALUES(@rCount)
	SELECT * FROM dbo.Ac_Batch_Bills
END
ELSE
BEGIN
	SELECT	@rCount = BillNumberId FROM Ac_Batch_Bills WITH (NOLOCK)
END

--为0的时候则返回处理结果
IF @rCount = 0
	SELECT * FROM Ac_Batch_Bills_Result ORDER BY Nid ASC
ELSE
	SELECT TOP 1 * FROM dbo.Ac_Batch_Bills


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Batch_Repair]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Batch_Repair]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2015-6-2
	描述：批量修复总账数据
	EXEC Gp_Voucher_Auditing_Batch_Repair '%'
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Batch_Repair
(
	@curStypeID			VARCHAR(MAX), 	--分支机构信息
	@flag				INT
)
--@encode$--
AS
SET NOCOUNT ON

--开始前清除数据
TRUNCATE TABLE Ac_Voucher_Repair_Msg
INSERT INTO Ac_Voucher_Repair_Msg(Msg) VALUES('数据准备中……')

DECLARE @stypeAllCount INT,
		@stypeIniCount INT,
		@IniFPeriod		INT,	
		@MaxFPeriod		INT,
		@TotalFPeriod	INT,
		@nBillId		NUMERIC(18,0),
		@FPeriod		INT,
		@IniFYear		VARCHAR(10),
		@MaxFYear		INT,
		@FYear			VARCHAR(10),
		@STypeId		VARCHAR(50),	
		@newSTypeId		VARCHAR(50),
		@nweSfullname	VARCHAR(100),
		@lastFPeriod	INT,
		@lastFYear		INT		
		
SET @stypeIniCount = 1		

--由于分支机构的期间可以不同，于是需要分开计算会计期间
CREATE TABLE #SType_UserConfig
(
	nId		INT IDENTITY(1,1),
	STypeId VARCHAR(50),
	sfullname	VARCHAR(100),
	SFYear	INT,
	SFPeriod	INT
)

INSERT INTO #SType_UserConfig (STypeId,sfullname,SFYear,SFPeriod ) 
SELECT	u.StypeId 
		,S.FullName
		,U.SFYear
		,U.SFPeriod
FROM dbo.Ac_AccountsPeroid_Stype U
INNER JOIN SType S ON S.TypeId = U.StypeId
WHERE u.IsUse = 1 AND u.Stypeid LIKE @curStypeID + '%' 
ORDER BY StypeId ASC

SET @stypeAllCount = @@ROWCOUNT

--中间表
CREATE TABLE #Result
(
	nId				INT IDENTITY(1,1),
	BillNumberId	NUMERIC(18,0),
	FPeriod			INT,
	FYear			VARCHAR(10),	
	STypeId			VARCHAR(100)
	
)

WHILE @stypeIniCount <= @stypeAllCount
BEGIN		
	SELECT	@newSTypeId = STypeId,@nweSfullname=sfullname
			,@IniFPeriod = SFPeriod,@IniFYear = SFYear
			,@FPeriod=SFPeriod,@FYear=SFYear 
	FROM	#SType_UserConfig 
	WHERE	nid = @stypeIniCount
	
	SELECT TOP 1 @TotalFPeriod = NatureCount FROM dbo.Ac_Period WHERE FYear = @FYear
	
	SELECT	@MaxFYear = MAX(FYear) 
	FROM	(
				SELECT MAX(FYear) AS FYear FROM Ac_Voucher WHERE STypeId = @newSTypeId AND IfCheck = 't'
				UNION ALL
				SELECT MAX(FYear) AS FYear FROM Ac_Balance WHERE STypeId = @newSTypeId 
				UNION ALL
				SELECT FYear FROM Ac_AccountsPeroid_Stype WHERE STypeId = @newSTypeId 
			) X
			
	SELECT @MaxFPeriod = MAX(FPeriod) 
	FROM	(
				SELECT ISNULL(MAX(FPeriod),0) AS FPeriod  FROM Ac_Voucher WHERE STypeId = @newSTypeId AND FYear = @MaxFYear AND IfCheck = 't'
				UNION ALL
				SELECT ISNULL(MAX(FPeriod),0) AS FPeriod	FROM Ac_Balance WHERE STypeId = @newSTypeId AND FYear = @MaxFYear 
				UNION ALL
				SELECT ISNULL(FPeriod,0) FROM Ac_AccountsPeroid_Stype WHERE STypeId = @newSTypeId AND FYear = @MaxFYear 
			) X
	
	----如果是重算当前期间，则可以假设前面的期间已经重算过，直接从当前期间开始即可
	IF @flag = 1
	BEGIN
		SELECT @FPeriod=FPeriod,@FYear=FYear FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @newSTypeId	
	END

	WHILE @FYear <= @MaxFYear
	BEGIN
		IF @FYear = @MaxFYear AND @FPeriod > @MaxFPeriod
			BREAK
		IF @FPeriod > @TotalFPeriod
			BREAK
		
		INSERT INTO Ac_Voucher_Repair_Msg(Msg)VALUES('【'+@nweSfullname+'】 '+CAST(@FYear AS VARCHAR(100))+'年度,第' + CAST(@FPeriod AS VARCHAR(100)) + '期处理中.....')
		
		------------------从期初表或是余额表上一期数据转入当期的期初字段数据----------------------------
		--如果重算是从开帐期间开始，则从期初表转入期初数据
		IF @IniFPeriod = @FPeriod AND @IniFYear = @FYear
		BEGIN
			BEGIN TRY
				--Gp_OkIni_Account_Normal里会清除余额表里所有数据
				EXEC Gp_OkIni_Account_Normal @newSTypeId,@IniFYear,@IniFPeriod,''
			END TRY
			BEGIN CATCH
				--PRINT(ERROR_MESSAGE())
			END CATCH
		END		
		--否则，需要清除表中当前期间数据，并从余额表上一期数据转入期初数据
		ELSE
		BEGIN
			DELETE FROM dbo.Ac_Balance WHERE STypeId = @newSTypeId AND FPeriod= @FPeriod AND FYear = @FYear
			DELETE FROM dbo.Ac_Balance_Assist_CheckItems WHERE STypeId = @newSTypeId AND FPeriod = @FPeriod AND FYear = @FYear
			DELETE FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE STypeId = @newSTypeId AND FPeriod = @FPeriod AND FYear = @FYear
			
			--获取上一期的期间年度和期间
			IF @FPeriod = 1
			BEGIN
				SET @lastFYear = @FYear - 1
				SELECT @lastFPeriod = ISNULL(MAX(FPeriod),13) FROM Ac_Balance WHERE STypeId = @newSTypeId AND FYear = @lastFYear
			END
			ELSE
			BEGIN
				SELECT @lastFYear = @FYear,@lastFPeriod = @FPeriod -1
			END
			
			--写入余额表
			INSERT INTO Ac_Balance(STypeId,ATypeId,FBeginBalance,FBeginBalanceFor,FDebit,FDebitFor,FCredit,FCreditFor
									,Cid,FEndBalance,FEndBalanceFor,FYtdDebit,FYtdDebitFor,FYtdCredit,FYtdCreditFor,FYear,FPeriod
									,FBeginqty,FDebitqty,FCreditqty,FEndqty,FYtdDebitqty,FYtdCreditqty)
			SELECT	STypeId,ATypeId,FEndBalance AS FBeginBalance,FEndBalanceFor AS FBeginBalanceFor
					,0 AS FDebit,0 AS FDebitFor,0 AS FCredit,0 AS FCreditFor
					,Cid,FEndBalance,FEndBalanceFor,
					CASE WHEN @lastFYear=@FYear THEN FYtdDebit ELSE 0 END
					,CASE WHEN @lastFYear=@FYear THEN FYtdDebitFor ELSE 0 END
					,CASE WHEN @lastFYear=@FYear THEN FYtdCredit ELSE 0 END
					,CASE WHEN @lastFYear=@FYear THEN FYtdCreditFor ELSE 0 END
					,@FYear AS FYear,@FPeriod AS FPeriod
					,FEndqty,0,0,FEndqty
					,CASE WHEN @lastFYear=@FYear THEN FYtdDebitqty ELSE 0 END
					,CASE WHEN @lastFYear=@FYear THEN FYtdCreditqty ELSE 0 END
			FROM	Ac_Balance
			WHERE	FPeriod = @lastFPeriod
					AND FYear = @lastFYear
					AND STypeId = @newSTypeId
							
			--写入辅助核算余额表
			INSERT INTO Ac_Balance_Assist_CheckItems(STypeId,ATypeId,Cid,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor
													,IniTotal,IniTotalFor,FYear,FPeriod,FEndBalance,FEndBalanceFor
													,IniYqty,Iniqty,FDebitqty,FCreditqty,FEndqty)
			SELECT	STypeId,ATypeId,Cid,IniYTotal,IniYTotalFor
					,0 AS FDebit,0 AS FDebitFor,0 AS FCredit,0 AS FCreditFor, 
					FEndBalance AS IniTotal,FEndBalanceFor AS IniTotalFor,@FYear AS FYear,@FPeriod AS FPeriod,FEndBalance,FEndBalanceFor
					,IniYqty,FEndqty,0,0,FEndqty
			FROM	Ac_Balance_Assist_CheckItems
			WHERE	FPeriod = @lastFPeriod
					AND FYear = @lastFYear
					AND STypeId = @newSTypeId
			
				
			--写入辅助核算余额表明细
			INSERT INTO Ac_Balance_Assist_CheckItems_Detail(STypeId,ATypeId,Cid,Ascids,FieldValue,FYear,FPeriod,IniTotal,IniTotalFor,FEndBalance,FEndBalanceFor
															,FDebit,FDebitFor,FCredit,FCreditFor,Iniqty,FDebitqty,FCreditqty,FEndqty)
			SELECT 	STypeId,ATypeId,Cid,Ascids,FieldValue,@FYear AS FYear,@FPeriod AS FPeriod,FEndBalance AS IniTotal,FEndBalanceFor AS IniTotalFor,
					FEndBalance,FEndBalanceFor
					,0,0,0,0,FEndqty,0,0,FEndqty
			FROM	Ac_Balance_Assist_CheckItems_Detail
			WHERE	FPeriod = @lastFPeriod
					AND FYear = @lastFYear
					AND STypeId = @newSTypeId
		END
		
		---------------计算当期发生额字段数据，即凭证上的数据---------------------
		TRUNCATE TABLE #Result	
		
		--统计当期所有已记账的凭证
		INSERT INTO #Result(BillNumberId,FPeriod,FYear,STypeId) 
		SELECT	BillNumberId,FPeriod,FYear,STypeId 
		FROM	Ac_Voucher 
		WHERE	IfCheck = 't' 
				AND FPeriod = @FPeriod
				AND FYear = @FYear
				AND STypeId = @newSTypeId 
		ORDER BY BillNumberId ASC	
		
		;WITH VOUCHERDATA AS
		(
			SELECT	B.STypeId
					,B.ATypeId
					,B.Cid
					,B.FYear
					,B.FPeriod
					,SUM(B.FDebitTotal) AS FDebitTotal
					,SUM(B.FDebitTotalFor) AS FDebitTotalFor
					,SUM(B.FCreditTotal) AS FCreditTotal
					,SUM(B.FCreditTotalFor) AS FCreditTotalFor
					,SUM(B.FDebitQty) AS FDebitQty
					,SUM(B.FCreditQty) AS FCreditQty
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotalFor-B.FCreditTotalFor) ELSE (-B.FDebitTotalFor+B.FCreditTotalFor) END) AS balancefor
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
			FROM	Ac_Voucher_Bill B
			INNER JOIN #Result R ON R.BillNumberId = B.BillNumberId
			GROUP BY B.STypeId,B.ATypeId,B.Cid,B.FYear,B.FPeriod
			UNION ALL
			SELECT	B.STypeId
					,B.ATypeId
					,0
					,B.FYear
					,B.FPeriod
					,SUM(B.FDebitTotal) AS FDebitTotal
					,SUM(B.FDebitTotal) AS FDebitTotalFor
					,SUM(B.FCreditTotal) AS FCreditTotal
					,SUM(B.FCreditTotal) AS FCreditTotalFor
					,SUM(B.FDebitQty) AS FDebitQty
					,SUM(B.FCreditQty) AS FCreditQty
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END ) AS balancefor
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
			FROM	Ac_Voucher_Bill B
			INNER JOIN #Result R ON R.BillNumberId = B.BillNumberId
			GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod
		)
		MERGE INTO Ac_Balance AS T
		USING VOUCHERDATA AS S
		ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod
		WHEN MATCHED
		THEN UPDATE SET T.FDebit += S.FDebitTotal,T.FDebitFor += S.FDebitTotalFor,T.FCredit+=S.FCreditTotal,T.FCreditFor+=S.FCreditTotalFor
						,T.FEndBalance+=S.balance,T.FEndBalanceFor+=S.balancefor,T.FYtdDebit+=s.FDebitTotal,T.FYtdDebitFor+= S.FDebitTotalFor
						,T.FYtdCredit+=S.FCreditTotal,T.FYtdCreditFor+=S.FCreditTotalFor
						,T.FDebitqty += S.FDebitQty,T.FCreditqty += S.FCreditQty
						,T.FYtdDebitqty += S.FDebitQty,T.FYtdCreditqty += S.FCreditQty
						,T.FEndqty += S.balanceqty
		WHEN NOT MATCHED BY TARGET
		THEN INSERT(STypeId,ATypeId,FBeginBalance,FBeginBalanceFor,FDebit,FDebitFor,FCredit,FCreditFor,Cid,FEndBalance,FEndBalanceFor
					,FYtdDebit,FYtdDebitFor,FYtdCredit,FYtdCreditFor,FYear,FPeriod
					,FDebitqty,FCreditqty,FYtdDebitqty,FYtdCreditqty,FEndqty,FBeginqty)
			 VALUES(S.stypeid,s.atypeid,0,0,s.fdebittotal,s.fdebittotalfor,s.fcredittotal,s.fcredittotalfor,s.cid,s.balance,s.balancefor
					,s.fdebittotal,s.fdebittotalfor,s.fcredittotal,s.fcredittotalfor,s.fyear,s.fperiod
					,S.FDebitqty,S.FCreditqty,S.FDebitqty,S.FCreditqty,S.balanceqty,0);
		
		
		;WITH AccountWithAssistCheckItems AS
		(
			SELECT	B.STypeId
					,B.ATypeId
					,B.Cid
					,B.FYear
					,B.FPeriod
					,B.FBeginBalance
					,B.FBeginBalanceFor
					,B.FBeginqty
					,B.FDebit
					,B.FDebitFor
					,B.FDebitqty
					,B.FCredit
					,B.FCreditFor
					,B.FCreditqty
					,B.FEndBalance
					,B.FEndBalanceFor
					,B.FEndqty
					,B.FYtdDebit
					,B.FYtdDebitFor
					,B.FYtdDebitqty
					,B.FYtdCredit
					,B.FYtdCreditFor
					,B.FYtdCreditqty
			FROM	Ac_Balance B
			INNER JOIN (SELECT ATYPEID FROM Ac_Account_Assist_CheckItems WHERE STypeId = @newSTypeId GROUP BY ATypeId) A ON A.ATypeId = B.ATypeId
			WHERE	B.STypeId = @newSTypeId
				AND	B.FYear = @FYear
				AND	B.FPeriod = @FPeriod
		)
		MERGE INTO Ac_Balance_Assist_CheckItems AS T
		USING AccountWithAssistCheckItems AS S
		ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod
		WHEN MATCHED
		THEN UPDATE SET T.FDebit = S.FDebit,T.FDebitFor = S.FDebitFor,T.FCredit=S.FCredit,T.FCreditFor=S.FCreditFor
						,T.FEndBalance=S.FEndBalance,T.FEndBalanceFor=S.FEndBalanceFor
						,T.IniTotal=s.FBeginBalance,T.IniTotalFor= S.FBeginBalanceFor
						,T.FDebitqty = S.FDebitqty,T.FCreditqty = S.FCreditqty
						,T.FEndqty = S.FEndqty
						,T.Iniqty = S.FBeginqty
		WHEN NOT MATCHED BY TARGET
		THEN INSERT(STypeId,ATypeId,IniTotal,IniTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,Cid,FEndBalance,FEndBalanceFor,FYear,FPeriod
					,FDebitqty,FCreditqty,FEndqty,Iniqty)
			 VALUES(S.stypeid,s.atypeid,s.FBeginBalance,S.FBeginBalanceFor,s.fdebit,s.fdebitfor,s.fcredit,s.fcreditfor,s.cid,s.FEndBalance,s.FEndBalancefor
					,s.fyear,s.fperiod
					,S.FDebitqty,S.FCreditqty,S.FEndqty,S.FBeginqty);
			
		
		;WITH VoucherDataWithAssistCheckItems AS
		(
			SELECT	B.STypeId
					,B.ATypeId
					,B.Cid
					,B.FYear
					,B.FPeriod
					,Ac.AscIds
					,Abc.TypeId AS FieldValue
					,SUM(B.FDebitTotal) AS FDebit
					,SUM(B.FDebitTotalFor) AS FDebitFor
					,SUM(B.FCreditTotal) AS FCredit
					,SUM(B.FCreditTotalFor) AS FCreditFor
					,SUM(B.FDebitQty) AS FDebitQty
					,SUM(B.FCreditQty) AS FCreditQty
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotalFor-B.FCreditTotalFor) ELSE (-B.FDebitTotalFor+B.FCreditTotalFor) END) AS balancefor
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
			FROM	Ac_Voucher_Bill B
			INNER JOIN #Result R ON R.BillNumberId = B.BillNumberId
			INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = b.ID
			INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
			GROUP BY B.STypeId,B.ATypeId,B.Cid,B.FYear,B.FPeriod,ac.AscIds,abc.TypeId
			UNION ALL
			SELECT	B.STypeId
					,B.ATypeId
					,0
					,B.FYear
					,B.FPeriod
					,Ac.AscIds
					,Abc.TypeId AS FieldValue
					,SUM(B.FDebitTotal) AS FDebit
					,SUM(B.FDebitTotal) AS FDebitFor
					,SUM(B.FCreditTotal) AS FCredit
					,SUM(B.FCreditTotal) AS FCreditFor
					,SUM(B.FDebitQty) AS FDebitQty
					,SUM(B.FCreditQty) AS FCreditQty
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END) AS balance
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitTotal-B.FCreditTotal) ELSE (-B.FDebitTotal+B.FCreditTotal) END ) AS balancefor
					,SUM(CASE WHEN B.Fdc = 1 THEN (B.FDebitQty-B.FCreditQty) ELSE (-B.FDebitQty+B.FCreditQty) END) AS balanceqty
			FROM	Ac_Voucher_Bill B
			INNER JOIN #Result R ON R.BillNumberId = B.BillNumberId
			INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = b.ID
			INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
			GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod,ac.AscIds,abc.TypeId
		)
		MERGE INTO Ac_Balance_Assist_CheckItems_Detail AS T
		USING VoucherDataWithAssistCheckItems AS S
		ON	S.STypeId = T.STypeId AND S.ATypeId = T.ATypeId AND S.Cid = T.Cid AND S.AscIds=T.AscIds AND S.FieldValue=T.FieldValue AND S.FYear = T.FYear AND S.FPeriod = T.FPeriod
		WHEN MATCHED
		THEN UPDATE SET T.FDebit += S.FDebit,T.FDebitFor += S.FDebitFor,T.FCredit+=S.FCredit,T.FCreditFor+=S.FCreditFor
						,T.FEndBalance+=S.balance,T.FEndBalanceFor+=S.balanceFor
						,T.FDebitqty += S.FDebitQty,T.FCreditqty += S.FCreditQty
						,T.FEndqty += S.balanceqty
		WHEN NOT MATCHED BY TARGET
		THEN INSERT(STypeId,ATypeId,AscIds,FieldValue,IniTotal,IniTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,Cid,FEndBalance,FEndBalanceFor,FYear,FPeriod
					,FDebitqty,FCreditqty,FEndqty,Iniqty)
			 VALUES(S.stypeid,s.atypeid,S.AscIds,S.FieldValue,0,0,s.fdebit,s.fdebitfor,s.fcredit,s.fcreditfor,s.cid,s.Balance,s.Balancefor
					,s.fyear,s.fperiod
					,S.FDebitqty,S.FCreditqty,S.balanceqty,0);
		
		IF @FPeriod = @TotalFPeriod AND @FYear < @MaxFYear
		BEGIN	
			SET @FYear += 1
			SET @FPeriod = 1
		END
		ELSE 
			SET @FPeriod = @FPeriod + 1
	END

	SET @stypeIniCount = @stypeIniCount + 1	
END

DROP TABLE #SType_UserConfig,#Result

--清除表数据表示数据处理完毕.
TRUNCATE TABLE Ac_Voucher_Repair_Msg

SELECT * FROM Ac_Voucher_Repair_Msg

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_Batch_Repair_BeforeCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_Batch_Repair_BeforeCheck]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2015-7-13
	描述：批量修复总账数据前检查
	--余额表和辅助核算余额表数据对比检查-所有期间
	--主要检查：
	--1.余额表、辅助核算余额表与对应期间凭证发生的借贷不一致
	--2.余额表、辅助核算余额表开账期间期初与期初表数据一致
	--3.余额表与辅助核算余额表数据一致
	--4.余额表当期期初与上期期末


	--LOG：
	--2013.11.07 添加分支机构条件
	--LOG：
	--2014.05.05 所有期间对比版
	--LOG：
	--2015.01.08 修正跨年比对BUG，增加当期期初和上期期末对比
	--2015.01.12 修正bug

	EXEC Gp_Voucher_Auditing_Batch_Repair_BeforeCheck '%'
*/
CREATE PROCEDURE Gp_Voucher_Auditing_Batch_Repair_BeforeCheck
(
	@curStypeID			VARCHAR(MAX) 	--分支机构信息
)
--@encode$--
AS
SET NOCOUNT ON

SELECT '强制重算' AS msg

/*
DECLARE @FYear INT,@FPeriod INT,@STypeId VARCHAR(50)
DECLARE @MaxFperiod INT
DECLARE @TotalPeriod INT
--获取当前分支机构年度、会计期间
SELECT @FYear=FYear,@FPeriod=FPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID

--获取分支机构启用年度、会计期间
DECLARE @FYearInit INT,@FPeriodInit INT
SELECT @FYearInit=SFYear,@FPeriodInit=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID
--总期间数
SELECT @TotalPeriod = MAX(FPeriod)
FROM dbo.Ac_Period

--由于分支机构的期间可以不同，于是需要分开计算会计期间
CREATE TABLE #SType_UserConfig
(
	nId		INT IDENTITY(1,1),
	STypeId VARCHAR(50)
)

INSERT INTO #SType_UserConfig (STypeId ) SELECT StypeId FROM dbo.SType_UserConfig WHERE Value = 1 AND StypeId LIKE @curStypeID + '%' ORDER BY StypeId ASC

DECLARE @stypeMAXCount INT
		,@stypeMINCount INT
		
SELECT @stypeMINCount = MIN(nId) FROM #SType_UserConfig
SELECT @stypeMAXCount = MAX(nId) FROM #SType_UserConfig

CREATE TABLE #TMPBILL
(
	Id		INT IDENTITY(1,1)
	,ATypeId		VARCHAR(50)
	,FBeginBalance	 NUMERIC(24, 10) 
	,FDebit	 NUMERIC(24, 10) 
	,FCredit	 NUMERIC(24, 10) 
	,FEndBalance	 NUMERIC(24, 10) 
	,Cid	INT
	,UserCode	VARCHAR(200)
	,AFullName	VARCHAR(200)
	,SFullName	VARCHAR(200)
	,FPeriod	INT
	,FYear	INT
)

CREATE TABLE #Result
(
	nid INT IDENTITY(1,1),
	msg	VARCHAR(MAX)
)

WHILE @stypeMINCount <= @stypeMAXCount
BEGIN
		
	TRUNCATE TABLE #TMPBILL
	
	SELECT @STypeId =STypeId  FROM #SType_UserConfig WHERE nId = @stypeMINCount

	SELECT *
	INTO #TmpBalance 
	FROM dbo.Ac_Balance WHERE STypeId = @STypeId

	--最大期间
	SELECT @MaxFperiod = MAX(FPeriod)
	FROM dbo.Ac_Balance WHERE STypeId = @STypeId


	


	--余额表综合本位币合计值
	DECLARE @bTotal1  NUMERIC(24, 10) 
	
	INSERT INTO #TMPBILL
	SELECT T1.ATypeId,T1.FBeginBalance,FDebit,FCredit,FEndBalance,T1.Cid,T2.UserCode,T2.FullName,T3.FullName AS SFullName,T1.FPeriod,T1.FYear
	FROM #TmpBalance T1
		INNER JOIN dbo.Ac_Account T2 ON T1.STypeId = T2.StypeId AND T1.ATypeId = T2.TypeId
		INNER JOIN dbo.SType T3 ON T1.STypeId = T3.TypeId
	WHERE T1.Cid <> 0
	ORDER BY FPeriod ASC

	DROP TABLE #TmpBalance
	
	DECLARE 
			@ATypeId		VARCHAR(50),
			@FBeginBalance	 NUMERIC(24, 10) ,
			@FDebit			 NUMERIC(24, 10) ,
			@FCredit		 NUMERIC(24, 10) ,
			@FEndBalance	 NUMERIC(24, 10) ,
			@Cid			INT,
			@UserCode		VARCHAR(100),
			@AFullName		VARCHAR(100),
			@SFullName		VARCHAR(100),
			@BalanceFPeriod		INT,
			@BalanceFYear		INT,
			
			@FInit			 NUMERIC(24, 10) ,
			@FBDebit		 NUMERIC(24, 10) ,
			@FBCredit		 NUMERIC(24, 10) ,
			@FAcnt			INT,
			@Msg			VARCHAR(MAX)
			,@MaxId		INT
			,@MinId		INT
	
	SELECT @MinId = MIN(Id) FROM #TMPBILL
	SELECT @MaxId = MAX(Id) FROM #TMPBILL

	SET @Msg = ''

	WHILE @MinId <= @MaxId
	BEGIN
		
		SELECT	@ATypeId = ATypeId
				,@FBeginBalance = FBeginBalance
				,@FDebit = FDebit
				,@FCredit = FCredit
				,@FEndBalance = FEndBalance
				,@Cid = Cid
				,@Usercode = UserCode
				,@AFullName = AFullName
				,@SFullName = SFullName
				,@BalanceFPeriod = FPeriod
				,@BalanceFYear = FYear
		FROM	#TMPBILL
		WHERE	Id = @MinId
		
		SET @Msg = ''
		SET @FBCredit = 0
		SET @FBDebit = 0
		SET @FInit = 0
		SET @FAcnt = 0
		
		SELECT @FAcnt = FAcnt FROM dbo.Ac_Account WHERE TypeId = @ATypeId AND StypeId = @StypeId
		
		--查开账第1期和期初
		IF @FYearInit = @FYear AND @FPeriodInit = @BalanceFPeriod
		BEGIN
			SELECT @FInit = SUM(ISNULL(iniTotal,0)) FROM dbo.Ac_IniAccount WHERE ATypeId = @ATypeId AND STypeId = @StypeId AND FYear = @BalanceFYear AND FPeriod = @BalanceFPeriod AND Cid = @Cid
			
			IF @FBeginBalance <> @FInit
				SET @Msg += '【'+@SFullName+'】【' + CAST(@BalanceFYear AS VARCHAR(10)) + '-'+CAST(@BalanceFPeriod AS VARCHAR(10))+'期】【'+@UserCode+'-'+@AFullName+'】'+ '余额表开账期初与期初表不一致'+CHAR(10)
			
		END
		
		--查开账第1期和余额表期初
		IF @FYearInit = @BalanceFYear AND @FPeriodInit = @BalanceFPeriod AND @FAcnt > 0
		BEGIN
			SELECT @FInit = SUM(ISNULL(iniTotal,0)) FROM dbo.Ac_IniAccount_Assist_CheckItems WHERE ATypeId = @ATypeId AND STypeId = @StypeId AND FYear = @BalanceFYear AND FPeriod = @BalanceFPeriod AND Cid = @Cid
			IF @FBeginBalance <> @FInit
				SET @Msg += '【'+@SFullName+'】【' + CAST(@BalanceFYear AS VARCHAR(10)) + '-'+CAST(@BalanceFPeriod AS VARCHAR(10))+'期】【'+@UserCode+'-'+@AFullName+'】'+ '辅助核算余额表开账期初与期初不一致'+CHAR(10)
		END
		ELSE
		
		--查余额表当期期初和上期余额是否一致
		IF (@BalanceFYear = @FYear OR @BalanceFYear > @FYear )
			AND @BalanceFPeriod > @FPeriod
		BEGIN
			SELECT @FInit = ISNULL(FEndBalance,0) FROM dbo.Ac_Balance 
				WHERE FYear = @BalanceFYear AND FPeriod = @BalanceFPeriod - 1 AND Cid = @Cid
					AND ATypeId = @ATypeId AND STypeId = @STypeId
			SELECT @FBeginBalance = ISNULL(FBeginBalance,0) FROM dbo.Ac_Balance WHERE FYear = @BalanceFYear AND FPeriod = @BalanceFPeriod
				AND ATypeId = @ATypeId AND STypeId = @STypeId AND Cid = @Cid
				
			IF @FInit <> @FBeginBalance
				SET @Msg += '【'+@SFullName+'】【' + CAST(@BalanceFYear AS VARCHAR(10)) + '-'+CAST(@BalanceFPeriod AS VARCHAR(10))+'期】【'+@UserCode+'-'+@AFullName+'】'+ '余额表当期期初与上期期末不一致'+CHAR(10)
		END
		ELSE IF @BalanceFYear > @FYear AND @BalanceFPeriod = @FPeriod
		BEGIN
			SELECT @FInit = ISNULL(FEndBalance,0) FROM dbo.Ac_Balance WHERE FYear = @BalanceFYear - 1 AND FPeriod = @TotalPeriod AND Cid = @Cid
				AND ATypeId = @ATypeId AND STypeId = @STypeId
			SELECT @FBeginBalance = ISNULL(FBeginBalance,0) FROM dbo.Ac_Balance WHERE FYear = @BalanceFYear AND FPeriod = @BalanceFPeriod
				AND ATypeId = @ATypeId AND STypeId = @STypeId AND Cid = @Cid
			IF @FInit <> @FBeginBalance
				SET @Msg += '【'+@SFullName+'】【' + CAST(@BalanceFYear AS VARCHAR(10)) + '-'+CAST(@BalanceFPeriod AS VARCHAR(10))+'期】【'+@UserCode+'-'+@AFullName+'】'+ '余额表当期期初与上期期末不一致'+CHAR(10)
		END
		
		
		--查每期余额表发生额与凭证合计发生
		SELECT @FBDebit = SUM(ISNULL(FDebitTotal,0)),@FBCredit = SUM(ISNULL(FCreditTotal,0))
		FROM
		(
			SELECT T2.FDebitTotal,T2.FCreditTotal FROM dbo.Ac_Voucher T1
				INNER JOIN dbo.Ac_Voucher_Bill T2 ON T1.BillNumberId = T2.BillNumberId
			WHERE T1.IfCheck = 't' AND T1.STypeId = @StypeId AND T2.ATypeId = @ATypeId AND T2.Cid = @cid AND T1.FYear = @BalanceFYear AND T1.FPeriod = @BalanceFPeriod 
		)T
		
		
		IF @FDebit <> @FBDebit OR @FCredit <> @FBCredit
		BEGIN
			SET @Msg += '【'+@SFullName+'】【' + CAST(@BalanceFYear AS VARCHAR(10)) + '-'+CAST(@BalanceFPeriod AS VARCHAR(10))+'期】【'+@UserCode+'-'+@AFullName+'】'+ '余额表与凭证明细，借贷方有差值'+CHAR(10)
		END
		
		IF (@FDebit <> @FBDebit OR @FCredit <> @FBCredit) AND @Facnt > 0
			SET @Msg += '【'+@SFullName+'】【' + CAST(@BalanceFYear AS VARCHAR(10)) + '-'+CAST(@BalanceFPeriod AS VARCHAR(10))+'期】【'+@UserCode+'-'+@AFullName+'】'+ '辅助核算余额表与凭证明细，借贷方有差值'+CHAR(10)

		
		--查每期辅助核算余额表与对应辅助核算余额表不一致
		IF @FEndBalance <> 0 AND @FAcnt > 1
			AND EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Balance_Assist_CheckItems WHERE ATypeId = @ATypeId AND STypeId = @StypeId AND Cid = @cid AND FYear = @BalanceFYear AND FPeriod = @BalanceFPeriod AND FEndBalance <> @FEndBalance)
		BEGIN
			SET @Msg += '【'+@SFullName+'】【' + CAST(@BalanceFYear AS VARCHAR(10)) + '-'+CAST(@BalanceFPeriod AS VARCHAR(10))+'期】【'+@UserCode+'-'+@AFullName+'】'+ '余额表与辅助核算余额表不一致'+CHAR(10)
		END
		
		--查余额表自身
		SET @bTotal1= 0
		SELECT @bTotal1= ISNULL(SUM(FEndBalance),0) FROM Ac_Balance WHERE FYear = @BalanceFYear AND FPeriod = @BalanceFPeriod AND STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = 0
		IF @FEndBalance <> @bTotal1
		BEGIN
			SET @Msg += '【'+@SFullName+'】【' + CAST(@BalanceFYear AS VARCHAR(10)) + '-'+CAST(@BalanceFPeriod AS VARCHAR(10))+'期】【'+@UserCode+'-'+@AFullName+'】'+  '余额表数据异常【综合本位币<>原币对应本位币合计】'
		END
		
		
		IF ISNULL(@Msg,'') <> ''
		BEGIN
			INSERT INTO #Result(msg)VALUES(@Msg)
		END
		
		SET @MinId = @MinId + 1
	END
	
	SET @stypeMINCount = @stypeMINCount + 1

END

SELECT * FROM #Result

DROP TABLE #Result,#SType_UserConfig,#TMPBILL
*/

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_CheckData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_CheckData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2013-01-07
	描述：凭证记账前和记账后的检查	
	DECLARE @Re INT
	EXEC @Re = Gp_Voucher_Auditing_CheckData 3,'2012',2
	SELECT @Re
*/
CREATE PROCEDURE Gp_Voucher_Auditing_CheckData
(
	@BillNumberId	NUMERIC(18,0),			-- 单据编号	
	@FYear			VARCHAR(10),			-- 会计年度
	@FPeriod		INT,					-- 会计期间
	@Rmsg			VARCHAR(MAX) OUTPUT		-- 错误信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @RowCount	INT,
		@I			INT,
		@mRowCount	INT,
		@cRowCount	INT,
		@STypeId	VARCHAR(50),
		@ATypeId	VARCHAR(50),
		@Cid		INT,
		@bTotal		 NUMERIC(24, 10) ,
		@bTotal1	 NUMERIC(24, 10) ,
		@bATotal	 NUMERIC(24, 10) ,
		@bATotal1	 NUMERIC(24, 10) ,
		@bAdtotal	 NUMERIC(24, 10) ,
		@bAdtotal1	 NUMERIC(24, 10) ,
		@Fdc		INT,
		@nRet		INT
		
EXEC @nRet = Gp_Fz_Base '',2
IF @nRet <> 0 RETURN -1		
		
SET @I = 1		

CREATE TABLE #CheckData
(
	nId		INT IDENTITY(1,1),
	STypeId	VARCHAR(50),
	ATypeId	VARCHAR(50),
	Fdc		INT
)

INSERT INTO #CheckData(STypeId,ATypeId,Fdc) SELECT STypeId,ATypeId,Fdc FROM Ac_Voucher_Bill WHERE BillNumberId = @BillNumberId

SET @RowCount = @@ROWCOUNT

WHILE @I <= @RowCount
BEGIN	
	SELECT @STypeId = STypeId,@ATypeId = ATypeId,@Fdc = Fdc FROM #CheckData WHERE nId = @I
	
	--检查科目的最终余额方向是否和会计科目表一致
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId = @STypeId AND TypeId = @ATypeId AND Fdc <> @Fdc)
	BEGIN
		SET @Rmsg = '凭证明细科目余额表方向异常，不能记账，请确认！'
		RETURN -1
	END
	
	--检查科目余额表
	SET @bTotal = 0
	SET @bTotal1= 0
	SELECT @bTotal = ISNULL(SUM(FEndBalance),0) FROM Ac_Balance WHERE FYear = @FYear AND FPeriod = @FPeriod AND STypeId = @STypeId AND ATypeId = @ATypeId AND Cid <> 0
	SELECT @bTotal1= ISNULL(SUM(FEndBalance),0) FROM Ac_Balance WHERE FYear = @FYear AND FPeriod = @FPeriod AND STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = 0
	IF @bTotal <> @bTotal1
	BEGIN
		SET @Rmsg = '科目余额表数据异常，不能记账，请确认！'
		RETURN -1
	END
	
	--检查辅助核算余额表
	SET @bATotal = 0
	SET @bATotal1= 0
	SELECT @bATotal = ISNULL(SUM(FEndBalance),0) FROM Ac_Balance_Assist_CheckItems WHERE FYear = @FYear AND FPeriod = @FPeriod AND STypeId = @STypeId AND ATypeId = @ATypeId AND Cid <> 0
	SELECT @bATotal1= ISNULL(SUM(FEndBalance),0) FROM Ac_Balance_Assist_CheckItems WHERE FYear = @FYear AND FPeriod = @FPeriod AND STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = 0
		
	IF @bATotal <> @bATotal1
	BEGIN		
		SET @Rmsg = '辅助核算余额表数据异常，不能记账，请确认！'
		RETURN -2
	END
	
	--检查辅助核算明细表
	SET @bAdTotal = 0
	SET @bAdTotal1= 0
	SELECT @bAdTotal = ISNULL(SUM(FEndBalance),0) FROM Ac_Balance_Assist_CheckItems_Detail WHERE FYear = @FYear AND FPeriod = @FPeriod AND STypeId = @STypeId AND ATypeId = @ATypeId AND Cid <> 0
	SELECT @bAdTotal1= ISNULL(SUM(FEndBalance),0) FROM Ac_Balance_Assist_CheckItems_Detail WHERE FYear = @FYear AND FPeriod = @FPeriod AND STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = 0
		
	IF @bAdTotal <> @bAdTotal1
	BEGIN		
		SET @Rmsg = '辅助核算明细表数据异常，不能记账，请确认！'
		RETURN -2
	END
	
	SET @I = @I + 1
END

DECLARE @No6Value	INT,
		@No10Value	VARCHAR(MAX),
		@No9Value	VARCHAR(MAX),
		@No11Value	VARCHAR(MAX),
		@No13Value	VARCHAR(MAX)
		
SELECT TOP 1 @No6Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 6
SELECT TOP 1 @No10Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 10
SELECT TOP 1 @No9Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 9
SELECT TOP 1 @No11Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 11
SELECT TOP 1 @No13Value = SubValue FROM dbo.sysdata1 WHERE SubNo = 13

IF @No6Value = 1 AND (ISNULL(@No10Value,'')='' OR ISNULL(@No9Value,'')='' OR ISNULL(@No11Value,'')='' OR ISNULL(@No13Value,'')='')
	RETURN -2

DROP TABLE #CheckData

SET @Rmsg = ''

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_RedWord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_RedWord]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-05
	描述：凭证反记账、冲销
	DECLARE @rValue VARCHAR(400) 
	EXEC Gp_Voucher_Auditing_RedWord 6,'00001',0,@rValue
	PRINT(@rValue)
*/
CREATE PROCEDURE Gp_Voucher_Auditing_RedWord
(
	@BillNumberId	NUMERIC(18,0),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@RedWord		INT,					-- 记账标识 0.反记账 1.冲销
	@szPID			VARCHAR(1000) OUTPUT	-- 返回出错信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @STypeId	VARCHAR(50),
		@FPeriod	INT,
		@Re			INT,
		@FYear		VARCHAR(10),
		@BillYear	VARCHAR(10),
		@BillPeriod	INT

--检测凭证的借方和贷方金额是否平衡
DECLARE @FDebitTotal	 NUMERIC(24, 10) ,
		@FCreditTotal	 NUMERIC(24, 10) ,
		@FlowNo			VARCHAR(10),
		@VgName			VARCHAR(200),
		@VgId			INT,
		@RedValue		INT,
		@IfCheck		VARCHAR(10),
		@Teller			VARCHAR(50)
		
SELECT	@VgId			= V.VgId,
		@FlowNo			= V.FlowNo,
		@BillYear		= V.FYear,	
		@BillPeriod		= V.FPeriod,	
		@VgName			= G.FullName,
		@STypeId		= V.STypeId,		
		@RedValue		= V.RedWord,
		@IfCheck		= V.IfCheck,
		@Teller			= V.Teller
FROM	Ac_Voucher_Bill B
INNER JOIN Ac_Voucher V ON V.BillNumberId = B.BillNumberId
INNER JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE	V.BillNumberId = @BillNumberId
GROUP BY V.VgId,
		 V.FlowNo,
		 V.FYear,
		 V.FPeriod,
		 G.FullName,
		 V.STypeId,
		 V.ReCheckId,
		 V.IfCheck,
		 V.RedWord,
		 V.Teller

--判断单据是否存在		 
IF @@ROWCOUNT = 0
BEGIN
	RAISERROR('凭证不存在，请确认！',16,1)
	RETURN -1
END

--获取当前分支机构年度、会计期间
SELECT @FYear=FYear,@FPeriod=FPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID

--您选择的凭证中有部份没有记账或者已经被反记账！
IF @IfCheck = 'f'
BEGIN
	RAISERROR('您选择的凭证中有部份没有记账或者已经被反记账，请确认！',16,1)
	RETURN -2
END	

--判断单据是否记账
IF @IfCheck = 't' AND @RedValue IN (1,2)
BEGIN
	RAISERROR('单据已经被冲销，请确认！',16,1)
	RETURN -2
END	 

--非本期的会计凭证不允许反记账、冲销
IF @BillPeriod <> @FPeriod OR @BillYear <> @FYear
BEGIN
	RAISERROR('凭证所在会计年度或者期间与当前会计年度或者期间不一致，不允许凭证反记账或者冲销，请确认！',16,1)
	RETURN -1
END

IF ISNULL(@Teller,'') <> ''
BEGIN
	RAISERROR('凭证已出纳签字，请先反签字再反记账凭证，请确认！',16,1)
	RETURN -2
END

IF @RedWord = 0 
	AND EXISTS(SELECT TOP 1 1  FROM dbo.Ac_Voucher_Bill WHERE ID IN(SELECT VoucherId FROM dbo.Te_Journal_Detail) AND BillNumberId = @BillNumberId)
BEGIN
	RAISERROR('凭证存在分录被日记账引用，请先删除相应日记账再反记账凭证，请确认！',16,1)
	RETURN -2
END

-----------------------------------------------------------------------------------开始反记账-------------------------------------------------------------------------------------------
IF @RedWord = 0
BEGIN
	----------------------------------------------------------------------------修改科目余额表【综合本位币】----------------------------------------------------------------------------
	UPDATE	Ac_Balance
	SET		FDebit			= FDebit - ISNULL(V.FDebitTotal,0),
			FDebitFor		= FDebitFor - ISNULL(V.FDebitTotal,0),
			FCredit			= FCredit - ISNULL(V.FCreditTotal,0),
			FCreditFor		= FCreditFor - ISNULL(V.FCreditTotal,0),
			FYtdDebit		= FYtdDebit - ISNULL(V.FDebitTotal,0),
			FYtdDebitFor	= FYtdDebitFor - ISNULL(V.FDebitTotal,0),
			FYtdCredit		= FYtdCredit - ISNULL(V.FCreditTotal,0),
			FYtdCreditFor	= FYtdCreditFor - ISNULL(V.FCreditTotal,0),
			FDebitqty		= FDebitQty - ISNULL(V.vFDebitQty,0),
			FCreditqty		= FCreditqty - ISNULL(V.vFCreditQty,0),
			FYtdDebitqty	= FYtdDebitqty - ISNULL(V.vFDebitQty,0),
			FYtdCreditqty	= FYtdCreditqty - ISNULL(V.vFCreditQty,0)
	FROM	Ac_Balance B
	INNER JOIN (
					SELECT	ATypeId,
							STypeId,							
							ISNULL(SUM(FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill
					WHERE	BillNumberId = @BillNumberId
					GROUP BY ATypeId,STypeId
	)V ON B.ATypeId = V.ATypeId AND B.STypeId = V.STypeId
	WHERE	B.STypeId = @STypeId
			AND B.FPeriod = @FPeriod
			AND B.FYear = @FYear
			AND B.Cid = 0
	
	--反记账反月结数据
	UPDATE	B
	SET		FBeginBalance = CASE WHEN A.Fdc = 1 THEN FBeginBalance - V.FDebitTotal + V.FCreditTotal ELSE FBeginBalance + V.FDebitTotal - V.FCreditTotal END,
			FBeginBalanceFor = CASE WHEN A.Fdc = 1 THEN FBeginBalanceFor - V.FDebitTotal + V.FCreditTotal ELSE FBeginBalanceFor + V.FDebitTotal - V.FCreditTotal END,
			FYtdDebit		= FYtdDebit - CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotal,0) ELSE 0 END,
			FYtdDebitFor	= FYtdDebitFor - CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotal,0) ELSE 0 END,
			FYtdCredit		= FYtdCredit - CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotal,0) ELSE 0 END,
			FYtdCreditFor	= FYtdCreditFor - CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotal,0) ELSE 0 END,
			FBeginqty		= CASE WHEN A.Fdc = 1 THEN FBeginqty - V.vFDebitQty + V.vFCreditQty ELSE FBeginqty + V.vFDebitQty - V.vFCreditQty END,
			FDebitqty		= FDebitQty - CASE WHEN B.FYear = @FYear THEN ISNULL(V.vFDebitQty,0) ELSE 0 END,
			FCreditqty		= FCreditqty - CASE WHEN B.FYear = @FYear THEN ISNULL(V.vFCreditQty,0) ELSE 0 END,
			FYtdDebitqty	= FYtdDebitqty - CASE WHEN B.FYear = @FYear THEN ISNULL(V.vFDebitQty,0) ELSE 0 END,
			FYtdCreditqty	= FYtdCreditqty - CASE WHEN B.FYear = @FYear THEN ISNULL(V.vFCreditQty,0) ELSE 0 END
	FROM	Ac_Balance B
	INNER JOIN (
					SELECT	ATypeId,
							STypeId,							
							ISNULL(SUM(FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill
					WHERE	BillNumberId = @BillNumberId
					GROUP BY ATypeId,STypeId
	)V ON B.ATypeId = V.ATypeId AND B.STypeId = V.STypeId
	INNER JOIN Ac_Account A ON A.StypeId = B.STypeId AND A.TypeId = B.ATypeId
	WHERE	B.STypeId = @STypeId
			AND B.Cid = 0
			AND ((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
					
	IF @@ERROR <> 0
	BEGIN	
		RAISERROR('修改余额平衡表综合本位币数据错误，请确认！',16,1)
		RETURN -4
	END	
	
	----------------------------------------------------------------------------修改科目余额表【非综合本位币】----------------------------------------------------------------------------
	UPDATE	Ac_Balance
	SET		FDebit			= FDebit - ISNULL(V.FDebitTotal,0),
			FDebitFor		= FDebitFor - ISNULL(V.FDebitTotalFor,0),
			FCredit			= FCredit - ISNULL(V.FCreditTotal,0),
			FCreditFor		= FCreditFor - ISNULL(V.FCreditTotalFor,0),
			FYtdDebit		= FYtdDebit - ISNULL(V.FDebitTotal,0),
			FYtdDebitFor	= FYtdDebitFor - ISNULL(V.FDebitTotalFor,0),
			FYtdCredit		= FYtdCredit - ISNULL(V.FCreditTotal,0),
			FYtdCreditFor	= FYtdCreditFor - ISNULL(V.FCreditTotalFor,0),
			FDebitqty		= FDebitQty - ISNULL(V.vFDebitQty,0),
			FCreditqty		= FCreditqty - ISNULL(V.vFCreditQty,0),
			FYtdDebitqty	= FYtdDebitqty - ISNULL(V.vFDebitQty,0),
			FYtdCreditqty	= FYtdCreditqty - ISNULL(V.vFCreditQty,0)
	FROM	Ac_Balance B
	INNER JOIN (
					SELECT	ATypeId,							
							Cid,	
							STypeId,					
							ISNULL(SUM(FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(FDebitTotalFor),0) AS FDebitTotalFor,
							ISNULL(SUM(FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(FCreditTotalFor),0) AS FCreditTotalFor,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill
					WHERE	BillNumberId = @BillNumberId
					GROUP BY ATypeId,							
							 Cid,
							 STypeId
	)V ON B.ATypeId = V.ATypeId AND B.Cid = V.Cid AND B.STypeId = V.STypeId
	WHERE	B.STypeId = @STypeId
			AND B.FPeriod = @FPeriod
			AND B.FYear = @FYear
			AND B.Cid <> 0
	
	--反记账反月结数据		
	UPDATE	B
	SET		FBeginBalance = CASE WHEN A.Fdc = 1 THEN FBeginBalance - V.FDebitTotal + V.FCreditTotal ELSE FBeginBalance + V.FDebitTotal - V.FCreditTotal END 
			,FBeginBalanceFor = CASE WHEN A.Fdc = 1 THEN FBeginBalanceFor - V.FDebitTotalFor + V.FCreditTotalFor ELSE FBeginBalanceFor + V.FDebitTotalFor - V.FCreditTotalFor END 
			,FYtdDebit		= FYtdDebit -CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotal,0) ELSE 0 END,
			FYtdDebitFor	= FYtdDebitFor -CASE WHEN B.FYear = @FYear THEN ISNULL(V.FDebitTotalFor,0) ELSE 0 END,
			FYtdCredit		= FYtdCredit -CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotal,0) ELSE 0 END,
			FYtdCreditFor	= FYtdCreditFor -CASE WHEN B.FYear = @FYear THEN ISNULL(V.FCreditTotalFor,0) ELSE 0 END,
			FBeginqty		= CASE WHEN A.Fdc = 1 THEN FBeginqty - V.vFDebitQty + V.vFCreditQty ELSE FBeginqty + V.vFDebitQty - V.vFCreditQty END,
			FDebitqty		= FDebitQty - CASE WHEN B.FYear = @FYear THEN ISNULL(V.vFDebitQty,0) ELSE 0 END,
			FCreditqty		= FCreditqty - CASE WHEN B.FYear = @FYear THEN ISNULL(V.vFCreditQty,0) ELSE 0 END,
			FYtdDebitqty	= FYtdDebitqty - CASE WHEN B.FYear = @FYear THEN ISNULL(V.vFDebitQty,0) ELSE 0 END,
			FYtdCreditqty	= FYtdCreditqty - CASE WHEN B.FYear = @FYear THEN ISNULL(V.vFCreditQty,0) ELSE 0 END
	FROM	Ac_Balance B
	INNER JOIN (
					SELECT	ATypeId,							
							Cid,	
							STypeId,					
							ISNULL(SUM(FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(FDebitTotalFor),0) AS FDebitTotalFor,
							ISNULL(SUM(FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(FCreditTotalFor),0) AS FCreditTotalFor,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill
					WHERE	BillNumberId = @BillNumberId
					GROUP BY ATypeId,							
							 Cid,
							 STypeId
	)V ON B.ATypeId = V.ATypeId AND B.Cid = V.Cid AND B.STypeId = V.STypeId
	INNER JOIN Ac_Account A ON A.StypeId = B.STypeId AND A.TypeId = B.ATypeId
	WHERE	B.STypeId = @STypeId
			AND B.Cid <> 0
			AND ((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
			
	IF @@ERROR <> 0
	BEGIN	
		RAISERROR('修改余额平衡表非综合本位币数据错误，请确认！',16,1)
		RETURN -4
	END

	----------------------------------------------------------------------------修改辅助核算余额表【综合本位币】----------------------------------------------------------------------------
	UPDATE	Ac_Balance_Assist_CheckItems
	SET		FDebit			= B.FDebit - ISNULL(V.FDebitTotal,0),
			FDebitFor		= B.FDebitFor - ISNULL(V.FDebitTotal,0),
			FCredit			= B.FCredit - ISNULL(V.FCreditTotal,0),
			FCreditFor		= B.FCreditFor - ISNULL(V.FCreditTotal,0),
			FDebitqty		= FDebitQty - ISNULL(V.vFDebitQty,0),
			FCreditqty		= FCreditqty - ISNULL(V.vFCreditQty,0)
	FROM	Ac_Balance_Assist_CheckItems B
	INNER JOIN (
					SELECT	B.ATypeId,
							B.STypeId,							
							ISNULL(SUM(B.FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(B.FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill B							
					WHERE	B.BillNumberId = @BillNumberId
							AND ISNULL(B.AscIds,'') <> ''					
					GROUP BY B.ATypeId,B.STypeId
	)V ON B.ATypeId = V.ATypeId AND B.STypeId = V.STypeId
	WHERE	B.STypeId = @STypeId
			AND B.FPeriod = @FPeriod
			AND B.FYear = @FYear
			AND B.Cid = 0
			
	--反记账反月结数据
	UPDATE	B
	SET		IniTotal = CASE WHEN A.Fdc = 1 THEN IniTotal - V.FDebitTotal + V.FCreditTotal ELSE IniTotal + V.FDebitTotal - V.FCreditTotal END ,
			IniTotalFor = CASE WHEN A.Fdc = 1 THEN IniTotalFor - V.FDebitTotal + V.FCreditTotal ELSE IniTotalFor + V.FDebitTotal - V.FCreditTotal END ,
			Iniqty		= CASE WHEN A.Fdc = 1 THEN Iniqty - V.vFDebitQty + V.vFCreditQty ELSE Iniqty + V.vFDebitQty - V.vFCreditQty END
	FROM	Ac_Balance_Assist_CheckItems B
	INNER JOIN (
					SELECT	B.ATypeId,
							B.STypeId,							
							ISNULL(SUM(B.FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(B.FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill B							
					WHERE	B.BillNumberId = @BillNumberId
							AND ISNULL(B.AscIds,'') <> ''					
					GROUP BY B.ATypeId,B.STypeId
	)V ON B.ATypeId = V.ATypeId AND B.STypeId = V.STypeId
	INNER JOIN Ac_Account A ON A.StypeId = B.STypeId AND A.TypeId = B.ATypeId
	WHERE	B.STypeId = @STypeId
			AND B.Cid = 0
			AND ((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
			
	IF @@ERROR <> 0
	BEGIN	
		RAISERROR('修改辅助核算余额平衡表综合本位币数据错误，请确认！',16,1)
		RETURN -4
	END
	
	----------------------------------------------------------------------------修改辅助核算余额表【非综合本位币】----------------------------------------------------------------------------
	UPDATE	Ac_Balance_Assist_CheckItems
	SET		FDebit			= B.FDebit - ISNULL(V.FDebitTotal,0),
			FDebitFor		= B.FDebitFor - ISNULL(V.FDebitTotalFor,0),
			FCredit			= B.FCredit - ISNULL(V.FCreditTotal,0),
			FCreditFor		= B.FCreditFor - ISNULL(V.FCreditTotalFor,0),
			FDebitqty		= FDebitQty - ISNULL(V.vFDebitQty,0),
			FCreditqty		= FCreditqty - ISNULL(V.vFCreditQty,0) 
	FROM	Ac_Balance_Assist_CheckItems B
	INNER JOIN (
					SELECT	B.ATypeId,							
							B.Cid,
							B.STypeId,
							ISNULL(SUM(B.FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(B.FDebitTotalFor),0) AS FDebitTotalFor,
							ISNULL(SUM(B.FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(B.FCreditTotalFor),0) AS FCreditTotalFor,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill B												
					WHERE	BillNumberId = @BillNumberId
							AND ISNULL(B.Ascids,'') <> ''							
					GROUP BY B.ATypeId,							
							 B.Cid,
							 B.STypeId
	)V ON B.ATypeId = V.ATypeId AND B.Cid = V.Cid AND B.STypeId = V.STypeId
	WHERE	B.STypeId = @STypeId
			AND B.FPeriod = @FPeriod
			AND B.FYear = @FYear
			AND B.Cid <> 0
			
	--反记账反月结数据
	UPDATE	B
	SET		IniTotal = CASE WHEN A.Fdc = 1 THEN IniTotal - V.FDebitTotal + V.FCreditTotal ELSE IniTotal + V.FDebitTotal - V.FCreditTotal END ,
			IniTotalFor = CASE WHEN A.Fdc = 1 THEN IniTotalFor - V.FDebitTotalFor + V.FCreditTotalFor ELSE IniTotalFor + V.FDebitTotalFor - V.FCreditTotalFor END,
			Iniqty		= CASE WHEN A.Fdc = 1 THEN Iniqty - V.vFDebitQty + V.vFCreditQty ELSE Iniqty + V.vFDebitQty - V.vFCreditQty END
	FROM	Ac_Balance_Assist_CheckItems B
	INNER JOIN (
					SELECT	B.ATypeId,							
							B.Cid,
							B.STypeId,
							ISNULL(SUM(B.FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(B.FDebitTotalFor),0) AS FDebitTotalFor,
							ISNULL(SUM(B.FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(B.FCreditTotalFor),0) AS FCreditTotalFor,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill B												
					WHERE	BillNumberId = @BillNumberId
							AND ISNULL(B.Ascids,'') <> ''							
					GROUP BY B.ATypeId,							
							 B.Cid,
							 B.STypeId
	)V ON B.ATypeId = V.ATypeId AND B.Cid = V.Cid AND B.STypeId = V.STypeId
	INNER JOIN Ac_Account A ON A.StypeId = B.STypeId AND A.TypeId = B.ATypeId
	WHERE	B.STypeId = @STypeId
			AND B.Cid <> 0			
			AND ((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
			
	IF @@ERROR <> 0
	BEGIN	
		RAISERROR('修改辅助核算余额平衡表非综合本位币数据错误，请确认！',16,1)
		RETURN -4
	END		
	
	----------------------------------------------------------------------------修改辅助核算余额表对照表【综合本位币】----------------------------------------------------------------------------
	UPDATE	Ac_Balance_Assist_CheckItems_Detail
	SET		FDebit			= B.FDebit - ISNULL(V.FDebitTotal,0),
			FDebitFor		= B.FDebitFor - ISNULL(V.FDebitTotal,0),
			FCredit			= B.FCredit - ISNULL(V.FCreditTotal,0),
			FCreditFor		= B.FCreditFor - ISNULL(V.FCreditTotal,0),
			FDebitqty		= FDebitQty - ISNULL(V.vFDebitQty,0) ,
			FCreditqty		= FCreditqty - ISNULL(V.vFCreditQty,0)
	FROM	Ac_Balance_Assist_CheckItems_Detail B
	INNER JOIN (
					SELECT	Ab.ATypeId,
							Ab.STypeId,						
							Ac.AscIds,
							Abc.TypeId AS FieldValue,
							ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill Ab
					INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
					INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
					WHERE	Ab.BillNumberId = @BillNumberId
					GROUP BY Ab.ATypeId,
							 Ab.STypeId,							
							 Ac.AscIds,
							 Abc.TypeId
	)V ON B.ATypeId = V.ATypeId AND B.STypeId = V.STypeId AND B.Ascids = V.AscIds AND B.FieldValue = V.FieldValue
	WHERE	B.STypeId = @STypeId
			AND B.FPeriod = @FPeriod
			AND B.FYear = @FYear
			AND B.Cid = 0
			
	--反记账反月结数据
	UPDATE	B
	SET		IniTotal = CASE WHEN A.Fdc = 1 THEN IniTotal - V.FDebitTotal + V.FCreditTotal ELSE IniTotal + V.FDebitTotal - V.FCreditTotal END ,
			IniTotalFor = CASE WHEN A.Fdc = 1 THEN IniTotalFor - V.FDebitTotal + V.FCreditTotal ELSE IniTotalFor + V.FDebitTotal - V.FCreditTotal END ,
			Iniqty		= CASE WHEN A.Fdc = 1 THEN Iniqty - V.vFDebitQty + V.vFCreditQty ELSE Iniqty + V.vFDebitQty - V.vFCreditQty END
	FROM	Ac_Balance_Assist_CheckItems_Detail B
	INNER JOIN (
					SELECT	Ab.ATypeId,
							Ab.STypeId,						
							Ac.AscIds,
							Abc.TypeId AS FieldValue,
							ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill Ab
					INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
					INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
					WHERE	Ab.BillNumberId = @BillNumberId
					GROUP BY Ab.ATypeId,
							 Ab.STypeId,							
							 Ac.AscIds,
							 Abc.TypeId
	)V ON B.ATypeId = V.ATypeId AND B.STypeId = V.STypeId AND B.Ascids = V.AscIds AND B.FieldValue = V.FieldValue
	INNER JOIN Ac_Account A ON A.StypeId = B.STypeId AND A.TypeId = B.ATypeId
	WHERE	B.STypeId = @STypeId
			AND B.Cid = 0
			AND ((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
			
			
	IF @@ERROR <> 0
	BEGIN	
		RAISERROR('修改辅助核算余额对照表综合本位币数据错误，请确认！',16,1)
		RETURN -4
	END	
	
	----------------------------------------------------------------------------修改辅助核算余额表对照表【非综合本位币】----------------------------------------------------------------------------
	UPDATE	Ac_Balance_Assist_CheckItems_Detail
	SET		FDebit			= B.FDebit - ISNULL(V.FDebitTotal,0),
			FDebitFor		= B.FDebitFor - ISNULL(V.FDebitTotalFor,0),
			FCredit			= B.FCredit - ISNULL(V.FCreditTotal,0),
			FCreditFor		= B.FCreditFor - ISNULL(V.FCreditTotalFor,0),
			FDebitqty		= FDebitQty - ISNULL(V.vFDebitQty,0),
			FCreditqty		= FCreditqty - ISNULL(V.vFCreditQty,0)
	FROM	Ac_Balance_Assist_CheckItems_Detail B
	INNER JOIN (
					SELECT	Ab.ATypeId,
							Ab.STypeId,
							Ab.Cid,							
							Ac.AscIds,
							Abc.TypeId AS FieldValue,
							ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(Ab.FDebitTotalFor),0) AS FDebitTotalFor,
							ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(Ab.FCreditTotalFor),0) AS FCreditTotalFor,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill Ab
					INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
					INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
					WHERE	Ab.BillNumberId = @BillNumberId
					GROUP BY Ab.ATypeId,
							 Ab.STypeId,	
							 Ab.Cid,						
							 Ac.AscIds,
							 Abc.TypeId
	)V ON B.ATypeId = V.ATypeId AND B.STypeId = V.STypeId AND B.Ascids = V.AscIds AND B.FieldValue = V.FieldValue AND B.Cid = V.Cid
	WHERE	B.STypeId = @STypeId
			AND B.FPeriod = @FPeriod
			AND B.FYear = @FYear
			AND B.Cid <> 0
			
	--反记账反月结数据
	UPDATE	B
	SET		IniTotal = CASE WHEN A.Fdc = 1 THEN IniTotal - V.FDebitTotal + V.FCreditTotal ELSE IniTotal + V.FDebitTotal - V.FCreditTotal END ,
			IniTotalFor = CASE WHEN A.Fdc = 1 THEN IniTotalFor - V.FDebitTotalFor + V.FCreditTotalFor ELSE IniTotalFor + V.FDebitTotalFor - V.FCreditTotalFor END ,
			Iniqty		= CASE WHEN A.Fdc = 1 THEN Iniqty - V.vFDebitQty + V.vFCreditQty ELSE Iniqty + V.vFDebitQty - V.vFCreditQty END
	FROM	Ac_Balance_Assist_CheckItems_Detail B
	INNER JOIN (
					SELECT	Ab.ATypeId,
							Ab.STypeId,
							Ab.Cid,							
							Ac.AscIds,
							Abc.TypeId AS FieldValue,
							ISNULL(SUM(Ab.FDebitTotal),0) AS FDebitTotal,
							ISNULL(SUM(Ab.FDebitTotalFor),0) AS FDebitTotalFor,
							ISNULL(SUM(Ab.FCreditTotal),0) AS FCreditTotal,
							ISNULL(SUM(Ab.FCreditTotalFor),0) AS FCreditTotalFor,
							ISNULL(SUM(FDebitQty),0) AS vFDebitQty,
							ISNULL(SUM(FCreditQty),0) AS vFCreditQty
					FROM	Ac_Voucher_Bill Ab
					INNER JOIN Ac_Voucher_Bill_Assist_CheckItems Abc ON Abc.vBId = Ab.ID
					INNER JOIN Ac_Assist_CheckItems Ac ON Ac.UserCode = Abc.typeName
					WHERE	Ab.BillNumberId = @BillNumberId
					GROUP BY Ab.ATypeId,
							 Ab.STypeId,	
							 Ab.Cid,						
							 Ac.AscIds,
							 Abc.TypeId
	)V ON B.ATypeId = V.ATypeId AND B.STypeId = V.STypeId AND B.Ascids = V.AscIds AND B.FieldValue = V.FieldValue AND B.Cid = V.Cid
	INNER JOIN Ac_Account A ON A.StypeId = B.STypeId AND A.TypeId = B.ATypeId
	WHERE	B.STypeId = @STypeId
			AND B.Cid <> 0
			AND ((B.FYear = @FYear AND B.FPeriod > @FPeriod) OR B.FYear > @FYear)
			
	IF @@ERROR <> 0
	BEGIN	
		RAISERROR('修改辅助核算余额对照表非综合本位币数据错误，请确认！',16,1)
		RETURN -4
	END			

	--修改单据反记账状态
	UPDATE	Ac_Voucher
	SET		PostTime = NULL,
			TallyId = '',
			IfCheck = 'f',
			Audited = 0
	WHERE	BillNumberId = @BillNumberId		


	IF @@ERROR <> 0
	BEGIN
		RAISERROR('修改单据记账状态错误，请确认！',16,1)
		RETURN -5
	END	
END
ELSE ------------------------------------------------------------------------------开始红冲----------------------------------------------------------------------------------
BEGIN
	DECLARE @newBillNumberId  NUMERIC(18,0),
			@newFlowNo		  VARCHAR(100),
			@CurFYear		  VARCHAR(10),
			@CurFPeriod		  INT,
			@CurFDate		  VARCHAR(10),
			@BillDate		  VARCHAR(10)
	
	SET @CurFYear = @FYear
	SET @CurFPeriod = @FPeriod
	SET @CurFDate = CONVERT(VARCHAR(10),GETDATE(),120)
	SELECT @BillDate = BillDate FROM Ac_Voucher WHERE BillNumberId = @BillNumberId
	
	--如果单据日期大于等于本期开始日期
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod AND @BillDate >= FBegin)	
	BEGIN
		--获取当前日期的期间，如果当前期间没有取到，则去本年度的最后一天,若最后所取日期超出当年会计期内，则取当前会计年度最后一天	
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FBegin <= @CurFDate AND FEnd >= @CurFDate)
		BEGIN			
			SELECT @CurFDate = @BillDate, @CurFYear = FYear,@CurFPeriod = FPeriod FROM Ac_Period WHERE FBegin <= @BillDate AND FEnd >= @BillDate			
		END
		ELSE
		BEGIN
			SELECT TOP 1 @CurFDate = FEnd, @CurFYear = FYear,@CurFPeriod = FPeriod FROM Ac_Period ORDER BY FPeriod DESC
		END	
	END
	ELSE	--若单据日期小于当前会计期间起始日期，则取当前系统日期，若当前系统日期也小于当前会计期间起始日期，则取当前会计期间起始日期。
	BEGIN
		SET @CurFDate = CONVERT(VARCHAR(10),GETDATE(),120)
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod AND @CurFDate < FBegin)
			SELECT @CurFDate = FBegin FROM Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod
		ELSE
			SELECT @CurFYear = FYear,@CurFPeriod = FPeriod FROM Ac_Period WHERE FBegin <= @CurFDate AND FEnd >= @CurFDate
	END	

	--判断异常期间数据
	IF @CurFYear < @FYear OR @CurFPeriod < @FPeriod
	BEGIN
		RAISERROR('冲销生成的新凭证期间错误，请确认！',16,1)
		RETURN -1
	END
			
	--生成凭证号
	IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'Acvhflowno' AND SubValue = '1')
		SELECT @newFlowNo = ISNULL(MAX(flowno),0)+1 FROM Ac_Voucher WHERE FYear = @CurFYear AND FPeriod = @CurFPeriod AND VgId = @VgId AND STypeId = @STypeId
	ELSE		
		SELECT @newFlowNo = ISNULL(MIN(flowno+1),1) FROM Ac_Voucher WHERE ( NOT ((flowno+1) IN (SELECT flowno FROM Ac_Voucher WHERE FYear = @CurFYear AND FPeriod = @CurFPeriod AND VgId = @VgId AND STypeId = @STypeId))) AND FYear = @CurFYear AND FPeriod = @CurFPeriod AND VgId = @VgId AND STypeId = @STypeId
	
	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('生成新凭证号错误，请确认！',16,1)
		RETURN -1
	END
	
	--写入红单
	INSERT INTO Ac_Voucher 
	(
		VgId, 
		BillDate, 
		BillCode, 
		FlowNo, 
		AttachFileCount, 
		TallyId, 
		FChecked, 
		AuditId, 
		ETypeId, 
		FYear, 
		FPeriod, 
		MarkError, 
		FCreditTotal, 
		FDebitTotal, 
		FEntryCount, 
		FModifyTime, 
		FComment, 
		FFootNote, 
		Audited, 
		FSerialNum, 
		STypeId, 
		ReCheckId, 
		IfCheck, 
		posttime, 
		RedWord
	)
	SELECT	VgId, 
			@CurFDate,
			BillCode, 
			@newFlowNo AS FlowNo, 
			AttachFileCount, 
			'' AS TallyId, 
			0 AS FChecked, 
			'' AS AuditId, 
			@szCheckMan AS ETypeId, 
			@CurFYear AS FYear, 
			@CurFPeriod AS FPeriod, 
			MarkError, 
			FCreditTotal, 
			FDebitTotal, 
			FEntryCount, 
			FModifyTime, 
			FComment, 
			FFootNote, 
			0 AS Audited, 
			FSerialNum, 
			STypeId, 
			'' AS ReCheckId, 
			'f' AS IfCheck, 
			NULL AS posttime, 
			0 AS RedWord
	FROM	Ac_Voucher
	WHERE	BillNumberId = @BillNumberId	
	
	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('写入红冲单据出错，请确认！',16,1)
		RETURN -5
	END
	
	--新的单据ID
	SET @newBillNumberId = SCOPE_IDENTITY();

	--写入凭证明细	
	EXEC @Re = Gp_Voucher_Auditing_RedWord_Detail @BillNumberId,@newBillNumberId,@FPeriod,@FlowNo,@VgName,@CurFYear,@CurFPeriod
	IF @Re <> 0
	BEGIN
		RAISERROR('写入凭证明细和辅助核算数据错误，请确认！',16,1)
		RETURN -6
	END
	
	--修改红冲状态
	UPDATE	Ac_Voucher
	SET		RedWord = 0
	WHERE	BillNumberId = @BillNumberId
	
	
	--得到红冲生成凭证ID
	SET @szPID = @newBillNumberId		
END

-----------------------------------------------------------------------------------整理会计科目------------------------------------------------------------------------------
EXEC @Re = Gp_Voucher_Check_Balance_Assit_Total @BillNumberId,@FPeriod,@FYear
IF @Re <> 0
BEGIN
	RAISERROR('处理科目余额信息错误，请确认！',16,1)
	RETURN -8	
END


RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Auditing_RedWord_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Auditing_RedWord_Detail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-05
	描述：凭证记账冲销	
*/
CREATE PROCEDURE Gp_Voucher_Auditing_RedWord_Detail
(
	@BillNumberId		NUMERIC(18,0),			-- 单据编号
	@NewBillNumberId	NUMERIC(18,0),			-- 新单据编号
	@FPeriod			INT,					-- 期间
	@FlowNo				VARCHAR(200),			-- 凭证号
	@VgName				VARCHAR(200),			-- 凭证字
	@CurFYear			VARCHAR(10),			-- 新的会计年度
	@CurFPeriod			INT						-- 新的会计期间	
)
--@encode$--
AS
SET NOCOUNT ON
		
DECLARE @TempId TABLE
(
	vBId		INT,
	newVbId		INT
)		
		
------------------------------------------------------------------------------------------------------写凭证明细------------------------------------------------------------------------------------------------------
INSERT INTO Ac_Voucher_Bill 
(
	BillNumberId, 
	Summary, 
	ATypeId, 
	ATypeId2, 
	Fdc, 
	F_ExchId, 
	F_ExchIdFor, 
	FDebitTotal, 
	FDebitTotalFor,
	FCreditTotal, 
	FCreditTotalFor,
	FCashFlowItem, 
	AscIds, 
	FSettleNo, 
	FSettleTypeID,
	FSettleDate, 
	Comment, 
	Cid,
	FAdc,
	Rate,
	RowNo,
	STypeId,
	FYear,
	FPeriod,
	OldID
	,FDebitQty
	,FCreditQty
)
SELECT	@NewBillNumberId AS BillNumberId, 
		CASE
			WHEN Summary = '' THEN '红冲第' + CAST(@FPeriod AS VARCHAR(10)) + '期'+ @VgName + '-' + CAST(@FlowNo AS VARCHAR(200)) + '凭证'
			ELSE '红冲第' + CAST(@FPeriod AS VARCHAR(10)) + '期'+ @VgName + '-' + CAST(@FlowNo AS VARCHAR(200)) + '凭证-' + Summary
		END,  
		ATypeId, 
		ATypeId2, 
		Fdc, 
		F_ExchId, 
		F_ExchIdFor, 
		-1*FDebitTotal, 
		-1*FDebitTotalFor,
		-1*FCreditTotal, 
		-1*FCreditTotalFor,
		FCashFlowItem, 
		AscIds, 
		FSettleNo, 
		FSettleTypeID,
		FSettleDate, 
		Comment, 
		Cid,
		FAdc,
		Rate,
		RowNo,
		STypeId,
		@CurFYear AS FYear,
		@CurFPeriod AS FPeriod,
		ID
		,-1*FDebitQty
		,-1*FCreditQty
FROM	Ac_Voucher_Bill
WHERE	BillNumberId = @BillNumberId

IF @@ROWCOUNT = 0
BEGIN
	RAISERROR('写入凭证明细表数据失败，请确认！',16,1)
	RETURN -1
END

------------------------------------------------------------------------------------------------------有辅助核算才处理------------------------------------------------------------------------------------------------------
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @BillNumberId)
BEGIN
	--写入对照关系
	INSERT INTO @TempId
	(
		vBId,
		newVbId
	) 
	SELECT	OldId,
			ID
	FROM	Ac_Voucher_Bill 
	WHERE	BillNumberId = @NewBillNumberId

	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('写入凭证明细表对应信息失败，请确认！',16,1)
		RETURN -1
	END

	--写入辅助核算的对照表	
	INSERT INTO Ac_Voucher_Bill_Assist_CheckItems 
	(
		vBId, 
		typeName, 
		TypeId, 
		BillNumberId
	)
	SELECT	T.newVbId AS vBId, 
			C.typeName, 
			C.TypeId, 
			@NewBillNumberId AS BillNumberId
	FROM	Ac_Voucher_Bill_Assist_CheckItems C
	INNER JOIN @TempId T ON C.vBId = T.vBId
	WHERE	BillNumberId = @BillNumberId

	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('写入凭证明细对照表数据失败，请确认！',16,1)
		RETURN -1
	END
END

------------------------------------------------------------------------------------------------------写入现金流量明细------------------------------------------------------------------------------------------------------
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_CashMoneyItems WHERE BillNumberId = @BillNumberId)
BEGIN
	INSERT INTO Ac_Voucher_Bill_CashMoneyItems
	(
		BillNumberId, 
		STypeId, 
		MATypeId, 
		DATypeId, 
		FDc, 
		FAdc, 
		RowNo, 
		Cid, 
		Total, 
		TotalFor, 
		FYear, 
		FPeriod
	)
	SELECT	@newBillNumberId AS BillNumberId, 
			STypeId, 
			MATypeId, 
			DATypeId, 
			FDc, 
			FAdc, 
			RowNo, 
			Cid, 
			-1*Total, 
			-1*TotalFor, 
			@CurFYear AS FYear,
			@CurFPeriod AS FPeriod
	FROM	Ac_Voucher_Bill_CashMoneyItems
	WHERE	BillNumberid = @BillNumberId
	
	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('写入现金流量明细数据失败，请确认！',16,1)
		RETURN -1
	END	
END	

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_Check_Balance_Assit_Total]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_Check_Balance_Assit_Total]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-05
	描述：重算科目余额	
*/
CREATE PROCEDURE Gp_Voucher_Check_Balance_Assit_Total
(
	@BillNumberId	NUMERIC(18,0),			-- 单据编号	
	@FPeriod		INT,			-- 会计期间
	@FYear			INT				-- 会计年度	
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------处理科目余额表------------------------------------------------------------------------
UPDATE	Ac_Balance
SET		FEndBalance = CASE WHEN M.Fdc = 1 THEN B.FBeginBalance + B.FDebit - B.FCredit ELSE B.FBeginBalance - B.FDebit + B.FCredit END,
		FEndBalanceFor = CASE WHEN M.Fdc = 1 THEN B.FBeginBalanceFor + B.FDebitFor - B.FCreditFor ELSE B.FBeginBalanceFor - B.FDebitFor + B.FCreditFor END
		,FEndqty = CASE WHEN M.Fdc = 1 THEN B.FBeginqty + B.FDebitqty - B.FCreditqty ELSE B.FBeginqty - B.FDebitqty + B.FCreditqty END
FROM	Ac_Balance B
INNER JOIN (
				SELECT  B.STypeId,
						B.ATypeId,
						B.Fdc
				FROM	Ac_Voucher_Bill B
				WHERE	B.BillNumberId = @BillNumberId
)M ON B.STypeId = M.STypeId AND B.ATypeId = M.ATypeId
WHERE	(B.FYear = @FYear
		AND B.FPeriod >= @FPeriod)
		OR B.FYear > @FYear
		
IF @@ERROR <> 0
BEGIN
	RAISERROR('更新科目余额表错误，请确认！',16,1)
	RETURN -1
END		


--整理科目余额表数据
--DELETE  
--FROM	Ac_Balance 
--WHERE	FBeginBalance = 0
--		AND FBeginBalanceFor =0
--		AND FDebit = 0
--		AND FDebitFor = 0
--		AND FCredit = 0
--		AND FCreditFor = 0
--		AND FEndBalance = 0
--		AND FEndBalanceFor = 0
--		AND FYear = @FYear
--		AND FPeriod = @FPeriod

------------------------------------------------------------------------科目余额表的辅助核算------------------------------------------------------------------------
UPDATE	Ac_Balance_Assist_CheckItems
SET		FEndBalance = CASE WHEN M.Fdc = 1 THEN B.IniTotal + B.FDebit - B.FCredit ELSE B.IniTotal - B.FDebit + B.FCredit END,
		FEndBalanceFor = CASE WHEN M.Fdc = 1 THEN B.IniTotalFor + B.FDebitFor - B.FCreditFor ELSE B.IniTotalFor - B.FDebitFor + B.FCreditFor END
		,FEndqty= CASE WHEN M.Fdc = 1 THEN B.Iniqty + B.FDebitqty - B.FCreditqty ELSE B.Iniqty - B.FDebitqty + B.FCreditqty END
FROM	Ac_Balance_Assist_CheckItems B
INNER JOIN (
				SELECT  B.STypeId,
						B.ATypeId,
						B.Fdc
				FROM	Ac_Voucher_Bill B
				WHERE	B.BillNumberId = @BillNumberId
)M ON B.STypeId = M.STypeId AND B.ATypeId = M.ATypeId
WHERE	(B.FYear = @FYear
		AND B.FPeriod >= @FPeriod)
		OR B.FYear > @FYear

IF @@ERROR <> 0
BEGIN
	RAISERROR('更新科目余额辅助核算表错误，请确认！',16,1)
	RETURN -1
END

--整理科目余额表的辅助核算
--DELETE 
--FROM	Ac_Balance_Assist_CheckItems
--WHERE	IniYTotal = 0
--		AND IniYTotalFor = 0
--		AND FDebit = 0
--		AND FDebitFor = 0
--		AND FCredit = 0
--		AND FCreditFor = 0
--		AND IniTotal = 0
--		AND IniTotalFor = 0
--		AND FEndBalance = 0
--		AND FEndBalanceFor = 0
--		AND FYear = @FYear
--		AND FPeriod = @FPeriod
		
------------------------------------------------------------------------科目余额表的辅助核算明细表------------------------------------------------------------------------
UPDATE	Ac_Balance_Assist_CheckItems_Detail
SET		FEndBalance = CASE WHEN M.Fdc = 1 THEN B.IniTotal + B.FDebit - B.FCredit ELSE B.IniTotal - B.FDebit + B.FCredit END,
		FEndBalanceFor = CASE WHEN M.Fdc = 1 THEN B.IniTotalFor + B.FDebitFor - B.FCreditFor ELSE B.IniTotalFor - B.FDebitFor + B.FCreditFor END
		,FEndqty = CASE WHEN M.Fdc = 1 THEN B.Iniqty + B.FDebitqty - B.FCreditqty ELSE B.Iniqty - B.FDebitqty + B.FCreditqty END
FROM	Ac_Balance_Assist_CheckItems_Detail B
INNER JOIN (
				SELECT  B.STypeId,
						B.ATypeId,
						B.Fdc
				FROM	Ac_Voucher_Bill B
				WHERE	B.BillNumberId = @BillNumberId
)M ON B.STypeId = M.STypeId AND B.ATypeId = M.ATypeId
WHERE	(B.FYear = @FYear
		AND B.FPeriod >= @FPeriod)
		OR B.FYear > @FYear

IF @@ERROR <> 0
BEGIN
	RAISERROR('更新科目余额辅助核算明细表错误，请确认！',16,1)
	RETURN -1
END		
		
--整理科目余额表辅助核算明细表
--DELETE 
--FROM	Ac_Balance_Assist_CheckItems_Detail
--WHERE	FDebit = 0
--		AND FDebitFor = 0
--		AND FCredit = 0
--		AND FCreditFor = 0
--		AND IniTotal = 0
--		AND IniTotalFor = 0
--		AND FEndBalance = 0
--		AND FEndBalanceFor = 0

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Voucher_MonthProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Voucher_MonthProc]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-04-09	
	描述：结账存的时候处理科目余额表
	EXEC Gp_Voucher_MonthProc 1
	
	Modify: awu 2014.04.10
	Description:非总账下支持固定资产卡片模式，增加固定资产的期末过账处理
*/
CREATE PROCEDURE Gp_Voucher_MonthProc
(
	@OperatorId	VARCHAR(50),-- 操作员ID
	@flag		INT,		-- 操作标识   0.反结账  1.结账
	@Stypeid	VARCHAR(50),-- 结账分支机构
	@ignore		INT = 0,		-- 0.检查业务账务对账 1.不检查
	@ignore1    INT = 0,		-- 0.固定资产对账 1.忽略
	@ignoreDep	INT = 0			-- 0.检测“工作量法”的固定资产未折旧 1.忽略“工作量法”的固定资产未折旧
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM dbo.loginuser WHERE etypeid = @OperatorId AND MangerSTypeID = '-99999')
	AND NOT EXISTS(SELECT TOP 1 1 FROM F_GetAllManagerBaseTypeId('',11,@OperatorId) WHERE typeid = @Stypeid)
BEGIN
	RAISERROR('当前操作员不具有此分支机构权限',16,1)
	RETURN -1
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.HR_Person WHERE Name = '00003' AND password = '1')
BEGIN
	RAISERROR('当前操作员不具有此分支机构权限',16,1)
	RETURN -1
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId = @Stypeid AND IsSelfVerify = 1)
BEGIN
	RAISERROR('当前分支机构非独立核算，不能结账',16,1)
	RETURN -1
END

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE IsUse = 1 AND StypeId = @Stypeid)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		RAISERROR('当前分支机构未开账，不能结账',16,1)
	ELSE
		RAISERROR('未开账，不能结账',16,1)
	RETURN -1
END

DECLARE @InitFYear		INT,			--开账年度
		@InitFPeriod	INT,			--开账期间
		@FPeriod		INT,			--当前期间
		@FYear			VARCHAR(20),	--当前年度
		@Cid			INT,			--本币ID
		@TotalPeriod	INT,			--期间总数
		@AssetStart		DATE,
		@AssetEnd		DATE,
		@IsAc			INT,			--是否总账
		@sys_assets		INT,			--是否卡片模式
		@FBeginDate		DATETIME,		--当期开始日期
		@FEndDate		DATETIME		--当期结束日期

--总账标识
SELECT @IsAc = SubValue FROM dbo.sysdata WHERE SubName = 'IsUseAcSystem'
SELECT @sys_assets = SubValue FROM dbo.sysdata WHERE SubName='assets'
		
--获取开账年度、期间
SELECT	@FPeriod = FPeriod,@FYear = FYear
		,@InitFPeriod = SFPeriod,@InitFYear = SFYear
FROM	dbo.Ac_AccountsPeroid_Stype
WHERE	Stypeid = @stypeid

--获取期间总数
SELECT @TotalPeriod = NatureCount FROM dbo.Ac_Period WHERE FYear = @InitFYear AND FPeriod = @InitFPeriod

SELECT	@FBeginDate = FBegin,@FEndDate = FEnd 
		,@AssetStart = FBegin,@AssetEnd = FEnd
FROM dbo.Ac_Period WHERE FYear = @FYear AND FPeriod = @FPeriod

--获取本币ID
SELECT TOP 1
		@Cid = CId
FROM	Ac_Currency
WHERE	Sysrow = 1

--消息列表
CREATE TABLE #TmpInfo
(
	ContentText	VARCHAR(200),--消息内容
	Detail		INT	--是否具体信息
)

--------------------------------------------------------------------------------反结账---------------------------------------------------------------------
IF @flag = 0
BEGIN
	IF @FPeriod = @InitFPeriod AND @FYear = @InitFYear
	BEGIN
		RAISERROR('当前为第一个会计启用期间，没有历史结账记录，无需反结账！',16,1)
		RETURN -1
	END
	
	IF @FPeriod = 1 AND @FYear = @InitFYear
	BEGIN
		RAISERROR('当前在第一个会计期间，无需反结账！',16,1)
		RETURN -1
	END
	
	IF @sys_assets = 1 --1是卡片模式
	BEGIN
		---取期间
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_FixedAssetsInit_Stype WHERE stypeid=@stypeid)
		BEGIN
			DECLARE @iniFperiod INT,@iniFyear INT
			SELECT @iniFperiod=fperiod,@iniFyear = fyear FROM Ac_FixedAssetsInit_Stype WHERE stypeid=@stypeid
			
			IF @iniFperiod=@FPeriod AND @iniFyear = @FYear
			BEGIN
			    DECLARE @ErrorMsg NVARCHAR(200)
			    SET @ErrorMsg='固定资产卡片管理启用期间与当前财务期间同为第'
								+CONVERT(varchar(2),@iniFperiod)+
							  '期，要进行反结账，请先对固定资产卡片管理进行反初始化操作'
				RAISERROR(@ErrorMsg,16,1)
				RETURN -1
			END
		END
	END
	
	IF @IsAc = 1
	BEGIN
		DECLARE @ConnectFYear INT, @ConnectFPeriod INT,@IsConnect INT
		SELECT @ConnectFYear = CFYear,@ConnectFPeriod = CFPeriod,@IsConnect = IsConnect FROM dbo.Te_StartPeriod WHERE STypeId = @Stypeid
		
		--如果出纳与总账联用，不能反月结到联用期间之前
		IF @IsConnect = 1 AND @ConnectFPeriod=@FPeriod AND @ConnectFYear = @FYear
		BEGIN
			RAISERROR('出纳与总账处于联用状态，不能反月结到联用期间之前,如果确定需要反月结，请先取消出纳系统与总账联用',16,1)
			RETURN -1
		END
	END
				
	--修改当前的会计期间
	IF @FPeriod = 1
		UPDATE dbo.Ac_AccountsPeroid_Stype SET FPeriod = @TotalPeriod,FYear = @FYear-1 WHERE Stypeid = @Stypeid
	ELSE
		UPDATE dbo.Ac_AccountsPeroid_Stype SET FPeriod = FPeriod - 1 WHERE Stypeid = @Stypeid
	
	IF @@ERROR <> 0
	BEGIN
		RAISERROR('修改当前会计期间失败，请确认！',16,1)
		RETURN -1		
	END				
END
ELSE----------------------------------------------------------------------------结账------------------------------------------------------------------------
BEGIN
	--结账的分支机构及挂靠它的机构
	DECLARE @tempStype TABLE
	(
		typeid VARCHAR(50)
	)
	INSERT INTO @tempStype(typeid)
	SELECT typeid FROM stype WHERE VerifyID=@Stypeid
	
	---------------------------抛出信息并返回的判断处理----------------------------------------------------------
	--卡片模式
	IF @sys_assets = 1   
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE IfAssetsIni = 1 AND TypeId = @Stypeid)
		BEGIN
			RAISERROR('固定资产未完成初始化，不能进行结帐操作！',16,1)
			RETURN -1
		END
		
		----固定资产2 未入账的卡片
		IF EXISTS(SELECT TOP 1 1 FROM dbo.AC_AssetsCards aa
				  JOIN @tempStype s ON aa.stypeid=s.typeid 
				  WHERE InAccountDate>=@AssetStart AND InAccountDate<=@AssetEnd AND AssetsState<3)
		BEGIN
			RAISERROR('有入账日期为当前会计期的卡片未入账，不能结账！',16,1)
			RETURN -1
		END
		
		----固定资产3 是否都有了资产折旧表 
		IF EXISTS(SELECT TOP 1 1 FROM (SELECT aa.id FROM AC_AssetsCards aa JOIN @tempStype s ON aa.stypeid=s.typeid  
									   WHERE InAccountDate>=@AssetStart AND InAccountDate<=@AssetEnd 
										AND (aa.DepreciationMean=2 OR aa.DepreciationMean=3 OR aa.DepreciationMean = 4)
									  ) ac
								 LEFT JOIN Ac_DepreciationPlan t ON ac.Id=t.AssetCardId WHERE t.AssetCardId IS NULL)
		BEGIN
			RAISERROR('有入账日期为当前会计期的卡片未生成折旧计划表，不能结账！',16,1)
			RETURN -1
		END	
			 
		----固定资产4 本期是否已经计提 
		IF EXISTS(SELECT TOP 1 1 FROM 
					(	SELECT aa.id FROM AC_AssetsCards  aa JOIN @tempStype s ON aa.stypeid=s.typeid 
						WHERE aa.DepreciationMean=2 OR aa.DepreciationMean=3 OR aa.DepreciationMean = 4
					) ac
					JOIN Ac_DepreciationPlan t ON ac.Id=t.AssetCardId WHERE t.FYEAR=@FYear AND t.FPeriod=@FPeriod AND PlanType=1 AND PlanState=0
		   )
		BEGIN
			RAISERROR('有卡片本期还未进行计提，不能结账！',16,1)
			RETURN -1
		END			
		
		----固定资产6 折旧方式为“工作量法”的本期内是否进行了折旧(生成折旧单)
		IF @ignoreDep = 0 AND 
			EXISTS(
				SELECT TOP 1 1 FROM dbo.Ac_AssetsCards T1
					INNER JOIN @tempStype T4 ON T1.Stypeid = T4.typeid
					INNER JOIN dbo.Ac_FixedAssetsInit_Stype T2 ON T1.STypeId = t2.StypeId
				WHERE T1.DepreciationMean = 5 
					AND T1.InAccountDate < @AssetStart
					AND T1.AssetsState NOT IN (2,5)
					AND T1.FinishWork < T1.ExpectWork
					AND NOT EXISTS
					(
						SELECT TT3.AssetCardId FROM dbo.BillIndex TT1
							INNER JOIN @tempStype s ON TT1.Stypeid=s.typeid 
							INNER JOIN dbo.DepBill TT3 ON TT1.BillNumberId = TT3.BillNumberId
						WHERE	TT1.BillDate >= @AssetStart AND TT1.BillDate <= @AssetEnd  
							AND TT1.BillType = 214 AND TT1.RedWord=0 AND TT1.ifcheck = 't' 
							AND TT3.AssetCardId = T1.ID
					)
				)
		BEGIN
			SELECT 1 AS nodep
			RETURN -1
		END
				
	END		
	
	--使用总账
	IF @IsAc = 1
	BEGIN
		--判断出纳系统联用时，需要检查出纳已结到下期，且所有相应凭证生成了日记账
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @Stypeid AND IsConnect = 1)
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period WHERE (FYear <@FYear OR (FYear = @FYear AND FPeriod <= @Fperiod)) AND STypeId = @Stypeid)
			BEGIN
				RAISERROR('出纳系统与总账联用，请先将出纳系统结账到下期',16,1)
				RETURN -1
			END
			ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill T1
						INNER JOIN dbo.Ac_Voucher T2 ON T1.BillNumberId = T2.BillNumberId
						INNER JOIN dbo.Ac_Account T3 ON T1.STypeId = T3.StypeId AND T1.ATypeId = T3.TypeId
						WHERE T2.STypeId = @stypeid AND T2.BillDate >= @FBeginDate AND T2.BillDate <= @FEndDate
								AND (T3.IsBank = 1 OR T3.IsCash = 1)
								AND T2.FChecked <> -1 AND ISNULL(T2.MarkError ,'') = ''
								AND NOT EXISTS (SELECT VoucherId FROM dbo.Te_Journal_Detail WHERE VoucherId = T1.ID))
			BEGIN
				RAISERROR('存在未生成日记账的出纳相关凭证，请先将其生成日记账',16,1)
				RETURN -1				
			END
			
			--联用下判断余额要一致
			IF EXISTS(
				SELECT TOP 1 1
				FROM
					(
					SELECT ISNULL(T1.FEndBalance,0)AS Ac_Balance,
							ISNULL(T2.FEndBalance,0) AS Te_Balance 
					FROM dbo.Ac_Balance T1
					LEFT JOIN dbo.Te_Balance T2 ON T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod 
													AND T1.Cid = T2.Cid AND T1.ATypeId = T2.ATypeId 
													AND T1.STypeId = T2.STypeId
					WHERE T2.FYear = @FYear 
						AND T2.FPeriod = @FPeriod 
						AND T2.Cid = 0 
						AND T2.STypeId = @STypeId
						AND T2.BUId <> 3
					)T WHERE Ac_Balance <> Te_Balance
				)
			OR EXISTS(
				SELECT TOP 1 1
				FROM
					(
					SELECT ISNULL(T1.FEndBalance,0)AS Te_Balance,
							ISNULL(T2.FEndBalance,0) AS Ac_Balance 
					FROM dbo.Te_Balance T1
						LEFT JOIN dbo.Ac_Balance T2 ON T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod 
														AND T1.Cid = T2.Cid AND T1.ATypeId = T2.ATypeId
														AND T1.STypeId = T2.STypeId
					WHERE T2.FYear = @FYear 
						AND T2.FPeriod = @FPeriod 
						AND T2.Cid = 0 
						AND T2.STypeId = @STypeId
						AND T1.BUId <> 3
					)T WHERE Ac_Balance <> Te_Balance
				)
			BEGIN
				RAISERROR('出纳系统与总账系统对应科目余额不一致，无法月结！',16,1)
				RETURN -1
			END
		END
		ELSE --未联用
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill T1
						INNER JOIN dbo.Ac_Voucher T2 ON T1.BillNumberId = T2.BillNumberId
						INNER JOIN dbo.Ac_Account T3 ON T1.STypeId = T3.StypeId AND T1.ATypeId = T3.TypeId
						WHERE T2.STypeId = @stypeid AND T2.BillDate >= @FBeginDate AND T2.BillDate <= @FEndDate
								AND (T3.IsBank = 1 OR T3.IsCash = 1)
								AND NOT EXISTS (SELECT VoucherId FROM dbo.Te_Journal_Detail WHERE VoucherId = T1.ID)
								AND T2.vouchertype = 7
					)
			BEGIN
				RAISERROR('存在未生成日记账的资金调拨单对应凭证，请先将其生成日记账',16,1)
				RETURN -1
			END
		END
		
	END
	---------------------------抛出信息并返回的判断处理end----------------------------------------------------------

	---------------------------以报告形式展现信息的判断处理----------------------------------------------------------
	IF @sys_assets = 1
	BEGIN		
		INSERT INTO #TmpInfo( ContentText, Detail )
		SELECT BillCode,2
		FROM dbo.BillIndex T1
		JOIN @tempStype s ON T1.Stypeid=s.typeid 
		WHERE BillDate >= @AssetStart AND BillDate <= @AssetEnd   AND BillType IN (212,213,214) AND T1.draft=1
		
		INSERT INTO #TmpInfo(ContentText, Detail)
		SELECT TOP 1 '存在固定资产业务单据未过账',1
		FROM	#TmpInfo
		WHERE	Detail = 2
				
		IF @IsAc = 1
		BEGIN
			INSERT INTO #TmpInfo( ContentText, Detail )
			SELECT BillCode,4
			FROM dbo.BillIndex T1
			JOIN @tempStype s ON T1.Stypeid=s.typeid 
			WHERE BillDate >= @AssetStart AND BillDate <= @AssetEnd   AND BillType IN (212,213,214) AND Isini = 0
				AND NOT EXISTS (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId = T1.BillNumberId) 
				AND BillType IN (212,213,214) AND RedWord=0   --减少单,增加单，折旧单,排除红蓝单
			UNION ALL
			SELECT aa.FullName+'【减值准备】',4																				  --减值准备
			FROM Ac_ProvisionForImpairment ap 
			JOIN Ac_AssetsCards aa ON ap.cardid=aa.Id 
			JOIN @tempStype s ON aa.stypeid=s.typeid 
			WHERE ap.BusinessDate>= @AssetStart AND ap.BusinessDate <= @AssetEnd   
				  AND ap.id NOT IN (SELECT SourceId FROM Ac_Provision_Voucher WHERE SourceType=1)
			UNION ALL 
			SELECT aa.FullName+'【部门变更】',4																				  --部门变更
			FROM Ac_Assetsmodifyrecords ap 
			JOIN Ac_AssetsCards aa ON ap.cardid=aa.Id    
			JOIN @tempStype s ON aa.stypeid=s.typeid 
			WHERE ap.BusinessDate>= @AssetStart AND ap.BusinessDate <= @AssetEnd   
				  AND ap.id NOT IN (SELECT SourceId FROM Ac_Provision_Voucher WHERE SourceType=2)
				  
			INSERT INTO #TmpInfo(ContentText, Detail)
			SELECT TOP 1 '存在固定资产业务单据未生成凭证',3
			FROM	#TmpInfo
			WHERE	Detail = 4	
		END 
	END
	
	IF @IsAc = 1
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'aloneusebsys' AND SubValue = 0) --校验时间段内业务单据
		BEGIN
			DECLARE @independentoutprice INT
			SELECT @independentoutprice = Value FROM userconfig WHERE ConfigName = 'independentoutprice'
			
			INSERT INTO #TmpInfo( ContentText, Detail )
			SELECT BillCode,6
			FROM dbo.BillIndex T1
			INNER JOIN @tempStype S ON S.typeid = T1.Stypeid
			WHERE BillDate >= @FBeginDate AND BillDate <= @FEndDate
				AND (BillType IN (11,45,160,305,139,140,142,141,34,6,161,126,144,146,145,21,187,188,201,202,9,14,16,116,115,128,129,4,189,66,190,148,
								150,149,151,36,84,85,78,158,77,93,5,10,57,205,181,427,183,166,167,168,170,172,159,173,174,215,147,312,400,401,402,403,12,46)
					OR	(BillType = 414 AND IsFreightMoney = 1))
				AND draft = 0 AND IsIni = 0 AND T1.ifYearBill = 0 AND RedWord = 0
				AND NOT EXISTS (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE GoodsBillId = T1.BillNumberId)
				AND NOT EXISTS (SELECT BillnumberId FROM Ac_ProvisionForImpairment WHERE BillNumberId = T1.BillNumberId)
				AND (@independentoutprice = 0 OR (@independentoutprice = 1 AND T1.BillType NOT IN(305,215,11,45,160,139,140,142,141,402,403,405,12,46)))
			UNION ALL
			SELECT BillCode,6
			FROM dbo.CommissionBillNew T1
			INNER JOIN @tempStype S ON S.typeid = T1.Stypeid
			WHERE BillDate >= @FBeginDate AND BillDate <= @FEndDate
				AND draft = 0 AND RedWord = 0
				AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_CommissionBill_VoucherBill)
			UNION ALL
			SELECT BillCode,6
			FROM dbo.ReceiptBillIndex T1
			INNER JOIN @tempStype S ON S.typeid = T1.Stypeid
			WHERE BillDate >= @FBeginDate AND BillDate <= @FEndDate
				AND draft = 0 AND IsIni = 0 AND T1.ifYearBill =0 AND RedWord = 0
				AND BillNumberId NOT IN(SELECT GoodsBillId FROM Ac_ReceiptBill_VoucherBill)
				AND (@independentoutprice = 0 OR (@independentoutprice = 1 AND T1.BillType NOT IN(305,215,11,45,160,139,140,142,141,402,403,405,12,46)))
			UNION ALL
			SELECT BillCode,6
			FROM dbo.BillIndex
			WHERE BillType = 310 AND draft = 0 AND RedWord = 0 AND ifYearBill = 0
				AND (Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) 
						AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = -1)
					OR
					Stypeid2 IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) 
						AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = 1)
					)
				AND BillDate >= @FBeginDate AND BillDate <= @FEndDate
			UNION ALL
			SELECT B.BillCode,6
			FROM dbo.Coupon_BillIndex B
			INNER JOIN dbo.SType S ON S.TypeId=B.STypeId AND S.VerifyID=@Stypeid
			WHERE 
				BillType IN(423,424,426,428,429)
				AND BillDate >= @FBeginDate AND BillDate <= @FEndDate
				AND draft = 0 
				AND RedWord = 0 
				AND B.FromType<>3
				AND ifYearBill = 0
				AND B.TotalMoney>0
				AND B.BillNumberId NOT IN (SELECT CouponBillId FROM dbo.Ac_CouponBill_VoucherBill)
			UNION ALL
			SELECT B.BillCode,6
			FROM dbo.PosAllotApplyBillIndex B
			INNER JOIN dbo.SType S ON S.TypeId=B.STypeId AND S.VerifyID=@Stypeid
			WHERE 
				BillType IN(327,328,329)
				AND BillDate >= @FBeginDate AND BillDate <= @FEndDate
				AND draft = 0 
				AND RedWord = 0 
				AND ifYearBill = 0
				AND B.Total>0
				AND B.BillNumberId NOT IN (SELECT DeliveryBillId FROM dbo.Ac_DeliveryBill_VoucherBill)
				
					
			INSERT INTO #TmpInfo( ContentText, Detail )
			SELECT TOP 1 '存在业务单据未生成凭证',5
			FROM #TmpInfo
			WHERE Detail = 6
			
			IF EXISTS(SELECT * FROM userconfig WHERE ConfigName = 'independentoutprice' AND Value = 1)
			BEGIN
				INSERT INTO #TmpInfo( ContentText, Detail )
				SELECT BillCode,8
				FROM billindex b 
				INNER JOIN @tempStype S ON S.typeid = B.Stypeid
				WHERE  draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill =0 AND BillDate >= @FBeginDate AND BillDate <= @FEndDate 
				AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) 
				AND BillType IN (305,215,11,45,160,141,405,12,46)
				UNION ALL
				SELECT BillCode,8
				FROM ReceiptBillIndex b 
				INNER JOIN @tempStype S ON S.typeid = B.Stypeid
				WHERE draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill =0 AND BillDate >= @FBeginDate AND BillDate <= @FEndDate 
				AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) 
				AND BillType IN (305,215,11,45,160,141,405,12,46)
				
				INSERT INTO #TmpInfo( ContentText, Detail )
				SELECT TOP 1 '存在出库类单据未生成基本凭证',7
				FROM #TmpInfo
				WHERE Detail = 8
				
				INSERT INTO #TmpInfo( ContentText, Detail )
				SELECT BillCode,10
				FROM billindex b 
				INNER JOIN @tempStype S ON S.typeid = B.Stypeid
				WHERE  draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill = 0 AND BillDate >= @FBeginDate AND BillDate <= @FEndDate 
				AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) 
				AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46)
				UNION ALL
				SELECT BillCode,10
				FROM ReceiptBillIndex b 
				INNER JOIN @tempStype S ON S.typeid = B.Stypeid
				WHERE draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill =0 AND BillDate >= @FBeginDate AND BillDate <= @FEndDate 
				AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) 
				AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46) 
				
				INSERT INTO #TmpInfo( ContentText, Detail )
				SELECT TOP 1 '存在出库类单据未生成成本凭证',9
				FROM #TmpInfo
				WHERE Detail = 10
			END
		END
		
		--判断本期是否有凭证未记账
		INSERT INTO #TmpInfo( ContentText, Detail )
		SELECT T2.FullName + '-' + CAST(T1.FlowNo AS VARCHAR(100)),12
		FROM Ac_Voucher T1
		INNER JOIN dbo.Ac_Voucher_Group T2 ON T1.VgId = T2.VgId
		WHERE FYear = @FYear AND FPeriod = @FPeriod AND IfCheck = 'f' AND FChecked <> -1 AND MarkError = '' AND STypeId = @Stypeid
		
		INSERT INTO #TmpInfo( ContentText, Detail )
		SELECT TOP 1 '本期有未记账的凭证存在，不能结账！',11
		FROM #TmpInfo
		WHERE Detail = 12
	END
	
	--判断是否有未签字的凭证
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'actellersign' AND SubValue = 1)
	BEGIN
		INSERT INTO #TmpInfo( ContentText, Detail )
		SELECT DISTINCT T3.FullName + '-' + CAST(T1.FlowNo AS VARCHAR(100)),14
		FROM dbo.Ac_Voucher T1
			INNER JOIN dbo.Ac_Voucher_Bill T2 ON T1.BillNumberId = T2.BillNumberId
			INNER JOIN dbo.Ac_Voucher_Group T3 ON T1.VgId = T3.VgId
			INNER JOIN dbo.Ac_Account T4 ON T2.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		WHERE T1.FYear = @FYear AND T1.FPeriod = @FPeriod
			AND ISNULL(T1.Teller,'') = ''
			AND (T4.IsBank = 1 OR T4.IsCash = 1)
			AND T1.STypeId = @STypeid
			AND T1.FChecked <> -1 
			AND ISNULL(T1.MarkError ,'') = ''
		
		INSERT INTO #TmpInfo(ContentText,Detail)
		SELECT TOP 1 '本期有未签字的凭证存在，不能结账！',13
		FROM #TmpInfo
		WHERE Detail = 14
	END
			
	IF EXISTS(SELECT TOP 1 1 FROM #TmpInfo)
	BEGIN
		SELECT * FROM #TmpInfo ORDER BY Detail
		DROP TABLE #TmpInfo
		RETURN -1
	END

	---------------------------以报告形式展现信息的判断处理end----------------------------------------------------------
	---------------------------最后验证数据是否平衡----------------------------------------------------------------
	IF @sys_assets = 1
	BEGIN		
		----固定资产5 检测数据
		DECLARE @A  NUMERIC(24, 10) --固定资产科目之和
		DECLARE @B  NUMERIC(24, 10) --累计折旧科目之和
		DECLARE @C  NUMERIC(24, 10) --减值准备科目之和
		DECLARE @NetValueTotal  NUMERIC(24, 10)  --净值之和
	
		---取出净值之和
		IF @ignore1=0
		BEGIN
		SELECT DISTINCT A.*INTO #s 
        FROM dbo.Ac_AssetsCards_History a 
        INNER JOIN dbo.AC_AssetsCards ac ON AC.Id=A.AssertsCardId AND AC.AssetsState IN(3,4) 
        INNER JOIN dbo.Ac_AssetsCategory aac ON aac.StypeId=@STypeId AND AAC.Id = AC.CategoryId
        INNER JOIN SType S ON S.TypeId = A.STypeId AND S.VerifyID = aac.STYPEID
        WHERE 
        a.BusinessDate<=@AssetEnd 
        AND A.AuditType !=-4  ------这里要排除掉-4的情况，-4是业务月结存的时候写入的数据，月结存的时候净值取的是结存期间的值，而不是财务系统中卡片最新折旧后的净值
        AND NOT EXISTS (SELECT 1 FROM Ac_AssetsCards_History b WHERE b.AssertsCardId= a.AssertsCardId AND b.DepreciationMonth>a.DepreciationMonth  AND b.BusinessDate<=@AssetEnd  AND AuditType !=-4) 
          

        SELECT @NetValueTotal=ISNULL(SUM(a.NetValue),0) FROM #s a
        INNER JOIN (              
           SELECT AssertsCardId,DepreciationMonth,MIN(id)id  FROM #s GROUP BY AssertsCardId,DepreciationMonth HAVING COUNT(*)>1
           UNION ALL
           SELECT AssertsCardId,DepreciationMonth,MIN(id)id  FROM #s GROUP BY AssertsCardId,DepreciationMonth HAVING COUNT(*)=1)b
        ON a.AssertsCardId=b.AssertsCardId AND a.DepreciationMonth=b.DepreciationMonth AND a.id=b.id

        DROP TABLE #s
        
        
			--SELECT @NetValueTotal=ISNULL(SUM(a.NetValue),0) 
			--FROM dbo.Ac_AssetsCards_History a 
			--INNER JOIN dbo.AC_AssetsCards ac ON AC.Id=A.AssertsCardId AND AC.AssetsState IN(3,4) 
			--INNER JOIN dbo.Ac_AssetsCategory aac ON aac.StypeId=@STypeId AND ac.CategoryId=aac.Id -- AND aac.StypeId=A.STypeId
			--INNER JOIN SType S ON S.TypeId = A.STypeId AND S.VerifyID = aac.STYPEID
			--WHERE 
			--	a.BusinessDate<=@AssetEnd 
			--	AND A.AuditType !=-4  --排除-4的情况，-4是业务月结存的时候写入的数据，月结存的时候净值取的是结存期间的值，而不是财务系统中卡片最新折旧后的净值
			--	AND NOT EXISTS (SELECT 1 FROM Ac_AssetsCards_History 
			--					WHERE	AssertsCardId= a.AssertsCardId AND Id>a.Id 
			--						AND BusinessDate<=@AssetEnd AND AuditType !=-4)
			
			---取出固定资产科目之和
			SELECT @A=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
			FROM dbo.Ac_Balance ab 
			JOIN ( 
					SELECT distinct a.AssertATypeId typeid
					FROM dbo.Ac_AssetsCards_History a 
					INNER JOIN @tempStype S ON S.typeid = A.STypeId
					WHERE a.BusinessDate<=@AssetEnd 
						AND A.AuditType !=-4  --排除-4的情况，-4是业务月结存的时候写入的数据
						AND A.AssetsState IN(3,4)
						AND NOT EXISTS (SELECT 1 FROM Ac_AssetsCards_History 
										WHERE	AssertsCardId= a.AssertsCardId AND Id>a.Id 
											AND BusinessDate<=@AssetEnd AND AuditType !=-4)
				 ) ac  ON ab.ATypeId=ac.typeid
			 WHERE ab.STypeId=@Stypeid AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
		    
			---取出累计折旧科目之和
			SELECT @B=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
			FROM dbo.Ac_Balance ab 
			JOIN (  
					SELECT distinct a.DepATypeId typeid
					FROM dbo.Ac_AssetsCards_History a 
					INNER JOIN @tempStype S ON S.typeid = A.STypeId
					WHERE 
						a.BusinessDate<=@AssetEnd 
						AND A.AuditType !=-4  --排除-4的情况，-4是业务月结存的时候写入的数据
						AND A.AssetsState IN(3,4)
						AND NOT EXISTS (SELECT 1 FROM Ac_AssetsCards_History 
										WHERE	AssertsCardId= a.AssertsCardId AND Id>a.Id 
											AND BusinessDate<=@AssetEnd AND AuditType !=-4)
				 ) ac  ON ab.ATypeId=ac.typeid
			 WHERE ab.STypeId=@Stypeid AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
			 
			---取出减值准备科目之和
			SELECT @C=ISNULL(SUM(ISNULL(FEndBalance,0)),0)
			FROM dbo.Ac_Balance ab 
			JOIN (  
					SELECT distinct a.DevalueATypeId typeid
					FROM dbo.Ac_AssetsCards_History a 
					INNER JOIN @tempStype S ON S.typeid = A.STypeId
					WHERE 
						a.BusinessDate<=@AssetEnd 
						AND A.AuditType !=-4  --排除-4的情况，-4是业务月结存的时候写入的数据
						AND A.AssetsState IN(3,4)
						AND NOT EXISTS (SELECT 1 FROM Ac_AssetsCards_History 
										WHERE	AssertsCardId= a.AssertsCardId AND Id>a.Id 
											AND BusinessDate<=@AssetEnd AND AuditType !=-4)
				 ) ac  ON ab.ATypeId=ac.typeid
			 WHERE ab.STypeId=@Stypeid AND FPeriod=@FPeriod  AND ab.Cid=@Cid AND FYear=@FYear
			 
 			IF @NetValueTotal!=@A-@B-@C 
			BEGIN
				SELECT @stypeid AS stypeid
				RETURN -1
			END
		END	
	END
	IF @IsAc = 1
	BEGIN

		--判断余额表中记录的借贷发生额合计和当期凭证明细里记录的借贷发生额合计是否一致
		DECLARE @FDebitTotal_B		 NUMERIC(24, 10),
				@FCreditTotal_B		 NUMERIC(24, 10),
				@FDebitTotal_V		 NUMERIC(24, 10),
				@FCreditTotal_V		 NUMERIC(24, 10),
				@FDebitqty_B         NUMERIC(24, 10),
				@FCreditqty_B        NUMERIC(24, 10),
				@FDebitqty_V         NUMERIC(24, 10),
				@FCreditqty_V        NUMERIC(24, 10) 
		
		SET @FDebitTotal_B = 0
		SET @FCreditTotal_B = 0
		SET @FDebitTotal_V = 0
		SET @FCreditTotal_V = 0
		SET @FDebitqty_B = 0
		SET @FCreditqty_B = 0
		SET @FDebitqty_V = 0
		SET @FCreditqty_V = 0
		
		SELECT	@FDebitTotal_B= ISNULL(SUM(FDebit),0)
				,@FCreditTotal_B= ISNULL(SUM(FCredit),0)
				,@FDebitqty_B= ISNULL(SUM(FDebitqty),0)
				,@FCreditqty_B= ISNULL(SUM(FCreditqty),0)
		FROM	Ac_Balance
		WHERE	Cid = 0
				AND FYear = @FYear
				AND FPeriod = @FPeriod
				AND STypeId = @Stypeid		
				
		SELECT	@FDebitTotal_V = ISNULL(SUM(B.FDebitTotal),0)
				,@FCreditTotal_V = ISNULL(SUM(B.FCreditTotal),0)
				,@FDebitqty_V = ISNULL(SUM(B.FDebitQty),0)
				,@FCreditqty_V = ISNULL(SUM(B.FCreditQty),0)
		FROM	Ac_Voucher V
		INNER JOIN Ac_Voucher_Bill B ON V.BillNumberId = B.BillNumberId
		WHERE	V.IfCheck = 't' AND V.STypeId = @Stypeid AND v.FPeriod=@FPeriod AND v.FYear=@fyear				
							
		IF @FDebitTotal_B <> @FDebitTotal_V
		BEGIN
			RAISERROR('科目余额表借方发生额本位币数据和凭证明细数据不平衡，不能结账！',16,1)
			RETURN -1
		END
		IF @FCreditTotal_B <> @FCreditTotal_V
		BEGIN
			RAISERROR('科目余额表贷方发生额本位币数据和凭证明细数据不平衡，不能结账！',16,1)
			RETURN -1
		END
		--IF @FDebitqty_B <> @FDebitqty_V
		--BEGIN
		--	RAISERROR('科目余额表借方数量数据和凭证明细数据不平衡，不能结账！',16,1)
		--	RETURN -1
		--END
		--IF @FCreditqty_B <> @FCreditqty_V
		--BEGIN
		--	RAISERROR('科目余额表贷方数量数据和凭证明细数据不平衡，不能结账！',16,1)
		--	RETURN -1
		--END
			
		--判断辅助核算余额表和辅助核算明细表是否平衡
		DECLARE @FEndBalance		 NUMERIC(24, 10),
				@FBEndBalance		 NUMERIC(24, 10)
				
		SET @FEndBalance = 0
		SET @FBEndBalance = 0
		
		--SELECT @FYear,@FPeriod,@Stypeid
		
		SELECT	@FEndBalance = ISNULl(SUM(FEndBalance),0)
		FROM	Ac_Balance_Assist_CheckItems
		WHERE	Cid = 0	
				AND FYear = @FYear
				AND FPeriod = @FPeriod
				AND STypeId = @Stypeid		
		
		SELECT	@FBEndBalance = ISNULL(SUM(CASE WHEN B.Fdc = 1 THEN B.FDebitTotal - B.FCreditTotal ELSE B.FCreditTotal - B.FDebitTotal END),0)			
		FROM	(			
					SELECT	A.Fdc,
							FDebitTotal  = ISNULL(B.FDebitTotal,0),			
							FCreditTotal = ISNULL(B.FCreditTotal,0)
					FROM	Ac_Voucher V
					INNER JOIN Ac_Voucher_Bill B ON V.BillNumberId = B.BillNumberId				
					INNER JOIN Ac_Account A ON B.STypeId = A.StypeId AND B.ATypeId = A.TypeId								
					WHERE	V.IfCheck = 't'				
							AND ISNULL(B.AscIds,'') <> ''
							AND V.STypeId = @Stypeid AND (v.FPeriod<=@FPeriod AND v.FYear=@fyear OR v.FYear<@fyear)
					UNION ALL
					SELECT	A.FDc,
							FDebitTotal  = CASE WHEN A.Fdc = 1  THEN ISNULL(iniTotal,0) ELSE 0 END,
							FCreditTotal = CASE WHEN A.Fdc = -1 THEN ISNULL(iniTotal,0) ELSE 0 END
					FROM	Ac_IniAccount_Assist_CheckItems I
					INNER JOIN Ac_Account A ON I.STypeId = A.StypeId AND I.ATypeId = A.TypeId
					INNER JOIN Ac_AccountsPeroid_Stype U ON I.STypeId = U.StypeId
					WHERE	U.IsUse = 1 AND i.STypeId = @Stypeid 														
				)B
		IF @FEndBalance <> @FBEndBalance
		BEGIN
			RAISERROR('本币科目辅助余额表和凭证明细数据不平衡，不能结账！',16,1)		
			RETURN -1
		END
		
		--结账时要求损益类科目余额为0
		--本年度最后一期结账前要求必须进行一次结转损益 awu 2013.8.7
		IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'acbalanceiszero' AND SubValue = '1') OR @FPeriod = @TotalPeriod		
		BEGIN
			DECLARE @FSDebit	 NUMERIC(24, 10) ,
					@FSCredit	 NUMERIC(24, 10) ,
					@FSDebitqty  NUMERIC(24, 10) ,
					@FSCreditqty NUMERIC(24, 10)

			SELECT	ISNULL(SUM(FEndBalance),0) AS Balance,
					ISNULL(SUM(FEndBalanceFor),0) AS BalanceFor,
					ISNULL(SUM(FEndqty),0) AS qty,
					Cid
			INTO	#TmpBalance
			FROM	dbo.Ac_Balance
			WHERE	ATypeId LIKE '00003%'
					AND FYear = @FYear 
					AND FPeriod = @FPeriod 
					AND STypeId = @Stypeid
			GROUP BY ATypeId,Cid
			
			IF EXISTS(SELECT TOP 1 1 FROM #TmpBalance WHERE Balance <> 0 OR qty <> 0)
			BEGIN
				RAISERROR('科目余额表损益类余额不为0，不能结账！',16,1)
				RETURN -1
			END
		END
	END
	---------------------------最后验证数据是否平衡END----------------------------------------------------------------
	
	---------------------------开始月结，调整数据--------------------------------------------
	
	--总账下才判断
	IF @IsAc = 1
	BEGIN
		DECLARE @isfanyuejie INT 
		SET @isfanyuejie=(SELECT COUNT(1) FROM Ac_Balance
					   WHERE FPeriod=(CASE WHEN @FPeriod = @TotalPeriod THEN 1 ELSE @FPeriod + 1 END)
							AND stypeid= @Stypeid
							AND fyear=(CASE WHEN @FPeriod = @TotalPeriod THEN @FYear + 1 ELSE @FYear END ) ) 
							
		--因为增加了反月结不反记账凭证功能，所以改变结转数据思路，如果下期存在匹配的数据，则更新其期初、期末、本年累计数据，否则插入新数据
		--这样就可以不用去判断是否有做反月结了，统一处理方式
		;WITH result1 AS 
		(
			SELECT	STypeId,
			ATypeId,
			FEndBalance AS FBeginBalance,
			FEndBalanceFor AS FBeginBalanceFor,
			0 AS FDebit,
			0 AS FDebitFor,
			0 AS FCredit,
			0 AS FCreditFor,
			Cid,
			FEndBalance,
			FEndBalanceFor,
			CASE WHEN @FPeriod = @TotalPeriod THEN 0 ELSE FYtdDebit END AS FYtdDebit,
			CASE WHEN @FPeriod = @TotalPeriod THEN 0 ELSE FYtdDebitFor END AS FYtdDebitFor,
			CASE WHEN @FPeriod = @TotalPeriod THEN 0 ELSE FYtdCredit END AS FYtdCredit,
			CASE WHEN @FPeriod = @TotalPeriod THEN 0 ELSE FYtdCreditFor END AS FYtdCreditFor,
			CASE WHEN @FPeriod = @TotalPeriod THEN @FYear + 1 ELSE @FYear END AS FYear,
			CASE WHEN @FPeriod = @TotalPeriod THEN 1 ELSE @FPeriod + 1 END AS FPeriod,
			FEndqty AS FBeginqty,
			0 AS FDebitqty,
			0 AS FCreditqty,
			CASE WHEN @FPeriod = @TotalPeriod THEN 0 ELSE FYtdDebitqty END AS FYtdDebitqty,
			CASE WHEN @FPeriod = @TotalPeriod THEN 0 ELSE FYtdCreditqty END AS FYtdCreditqty,
			FEndqty
			FROM	Ac_Balance
			WHERE	FPeriod = @FPeriod
					AND FYear = @FYear
					AND STypeId = @Stypeid
		)	
		MERGE INTO dbo.Ac_Balance pp 
		USING result1 AS r   
		ON r.fyear=pp.FYear AND r.stypeid=pp.STypeId AND r.fperiod =pp.FPeriod  AND r.atypeid=pp.ATypeId AND r.cid=pp.cid
		WHEN MATCHED  
		THEN UPDATE SET pp.FEndBalance += r.FBeginBalance-pp.FBeginBalance,
						pp.FEndBalanceFor += r.FBeginBalanceFor-pp.FBeginBalanceFor,
						pp.FYtdDebit = pp.FDebit+r.FYtdDebit,
						pp.FYtdDebitFor = pp.FDebitFor+r.FYtdDebitFor,
						pp.FYtdCredit = pp.FCredit+r.FYtdCredit,
						pp.FYtdCreditFor = pp.FCreditFor+r.FYtdCreditFor,
						pp.FBeginqty = r.FBeginqty,
						pp.FEndqty += r.FEndqty-pp.FBeginqty,
						pp.FYtdDebitqty = pp.FDebitqty+r.FYtdDebitqty,
						pp.FYtdCreditqty = pp.FCreditqty+r.FYtdCreditqty,
						pp.FBeginBalance = r.FBeginBalance,
						pp.FBeginBalanceFor = r.FBeginBalanceFor
		WHEN NOT MATCHED BY TARGET 
		THEN INSERT ( 	STypeId,ATypeId,FBeginBalance,FBeginBalanceFor,FDebit,FDebitFor,FCredit,
					FCreditFor,Cid,	FEndBalance,FEndBalanceFor,FYtdDebit,FYtdDebitFor,FYtdCredit,FYtdCreditFor,FYear,FPeriod,
					FBeginqty,FEndqty,FDebitqty,FCreditqty,FYtdDebitqty,FYtdCreditqty)  
		VALUES	(r.STypeId,r.ATypeId,r.FBeginBalance,r.FBeginBalanceFor,r.FDebit,r.FDebitFor,r.FCredit,r.
					FCreditFor,r.Cid,r.	FEndBalance,r.FEndBalanceFor,r.FYtdDebit,r.FYtdDebitFor,r.FYtdCredit,r.FYtdCreditFor,r.FYear,r.FPeriod,
					r.FBeginqty,r.FEndqty,r.FDebitqty,r.FCreditqty,r.FYtdDebitqty,r.FYtdCreditqty );			

		IF @@ERROR <> 0
		BEGIN
			RAISERROR('处理科目余额表错误，请确认！',16,1)
			RETURN -1		
		END
		
		;WITH result1 AS 
		(
			SELECT	STypeId, 
					ATypeId, 
					Cid, 
					CASE WHEN @FPeriod = @TotalPeriod THEN 0 ELSE IniYTotal END AS IniYTotal, 
					CASE WHEN @FPeriod = @TotalPeriod THEN 0 ELSE IniYTotalFor END AS IniYTotalFor, 
					0 AS FDebit, 
					0 AS FDebitFor, 
					0 AS FCredit, 
					0 AS FCreditFor, 
					FEndBalance AS IniTotal, 
					FEndBalanceFor AS IniTotalFor, 
					CASE WHEN @FPeriod = @TotalPeriod THEN @FYear + 1 ELSE @FYear END AS FYear,
					CASE WHEN @FPeriod = @TotalPeriod THEN 1 ELSE @FPeriod + 1 END AS FPeriod,
					FEndBalance, 
					FEndBalanceFor
			FROM	Ac_Balance_Assist_CheckItems
			WHERE	FYear = @FYear
					AND FPeriod = @FPeriod	
					AND STypeId = @Stypeid
		)	
		MERGE INTO dbo.Ac_Balance_Assist_CheckItems pp 
		USING result1 AS r   
		ON r.fyear=pp.FYear AND r.stypeid=pp.STypeId AND r.fperiod =pp.FPeriod  AND r.atypeid=pp.ATypeId AND r.cid=pp.cid
		WHEN MATCHED  
		THEN UPDATE SET pp.FEndBalance += r.IniTotal-pp.IniTotal,
						pp.FEndBalanceFor += r.IniTotalFor-pp.IniTotalFor,
						pp.IniYTotal = r.IniYTotal,
						pp.IniYTotalFor = r.IniYTotalFor,
						pp.IniTotal = r.IniTotal,
						pp.IniTotalFor = r.IniTotalFor
		WHEN NOT MATCHED BY TARGET 
		THEN INSERT ( STypeId, ATypeId, Cid, IniYTotal, IniYTotalFor, FDebit, FDebitFor, FCredit, FCreditFor, 
					IniTotal, IniTotalFor, FYear, FPeriod, FEndBalance, FEndBalanceFor)
		VALUES	(r.STypeId,r.ATypeId,r.Cid,r.IniYTotal,r.IniYTotalFor,r.FDebit,r.FDebitFor,r.FCredit,r.FCreditFor,r.
				IniTotal,r.IniTotalFor,r.FYear,r.FPeriod,r.FEndBalance,r.FEndBalanceFor);			
				
		IF @@ERROR <> 0
		BEGIN
			RAISERROR('处理科目余额辅助核算表错误，请确认！',16,1)
			RETURN -1		
		END		
		
		;WITH result1 AS 
		(
			SELECT 	STypeId, 
					ATypeId, 
					Cid, 
					Ascids, 
					FieldValue, 
					CASE WHEN @FPeriod = @TotalPeriod THEN @FYear + 1 ELSE @FYear END AS FYear,
					CASE WHEN @FPeriod = @TotalPeriod THEN 1 ELSE @FPeriod + 1 END AS FPeriod,
					FEndBalance AS IniTotal,
					FEndBalanceFor AS IniTotalFor,
					FEndBalance,
					FEndBalanceFor,
					FEndqty AS Iniqty,
					FEndqty
			FROM	Ac_Balance_Assist_CheckItems_Detail
			WHERE	FYear = @FYear
					AND FPeriod = @FPeriod
					AND STypeId = @Stypeid
		)	
		MERGE INTO dbo.Ac_Balance_Assist_CheckItems_Detail pp 
		USING result1 AS r   
		ON r.fyear=pp.FYear AND r.stypeid=pp.STypeId AND r.fperiod =pp.FPeriod  AND r.atypeid=pp.ATypeId AND r.cid=pp.cid
		AND  pp.Ascids=r.Ascids AND pp.FieldValue=r.FieldValue
		WHEN MATCHED  
		THEN UPDATE SET	pp.FEndBalance += r.IniTotal-pp.IniTotal,
						pp.FEndBalanceFor += r.IniTotalFor-pp.IniTotalFor,
						pp.FEndqty += r.Iniqty-pp.Iniqty,	
						pp.IniTotal = r.IniTotal,
						pp.IniTotalFor = r.IniTotalFor,
						pp.Iniqty = r.Iniqty			  
		WHEN NOT MATCHED BY TARGET 	
		THEN INSERT (STypeId, ATypeId, Cid, Ascids, FieldValue, FYear, FPeriod,IniTotal,IniTotalFor,FEndBalance,FEndBalanceFor,Iniqty,FEndqty)
		VALUES(r.STypeId,r.ATypeId,r.Cid,r.Ascids,r.FieldValue,r. FYear,r. FPeriod,r.IniTotal,r.IniTotalFor,r.FEndBalance,r.FEndBalanceFor,r.Iniqty,r.FEndqty);
				
		IF @@ERROR <> 0
		BEGIN
			RAISERROR('处理科目余额辅助核算明细表错误，请确认！',16,1)
			RETURN -1		
		END		
	END
	
	--修改当前的会计期间
	IF @FPeriod = @TotalPeriod
		UPDATE dbo.Ac_AccountsPeroid_Stype SET FYear = @FYear + 1,FPeriod = 1 WHERE Stypeid = @STypeid
	ELSE
		UPDATE dbo.Ac_AccountsPeroid_Stype SET FPeriod = @FPeriod + 1 WHERE Stypeid = @Stypeid
	
	IF @@ERROR <> 0
	BEGIN
		RAISERROR('修改当前会计期间失败，请确认！',16,1)
		RETURN -1		
	END		
END

SELECT * FROM #TmpInfo
DROP TABLE #TmpInfo
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS OFF; 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_WdErpOrderCompare]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].[Gp_WdErpOrderCompare];
GO

/*
	作者:颜熙
	日期:2016-11-28
	描述:网店订单及ERP单据核对
*/
CREATE  PROCEDURE Gp_WdErpOrderCompare
    (
      @billtype INT , --单据类型 0：销售出库单 1：销售退货单 2：费用单
      @startdate VARCHAR(50) ,--开始日期
      @enddate VARCHAR(50) ,--截止日期
      @IsDif BIT
    )
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
		IF @startdate = '' OR @startdate IS NULL SET @startdate = '1990-01-01'
		IF @enddate = '' OR @enddate IS NULL SET @enddate = '2999-12-12'
        CREATE TABLE #tempSaletable
            (
              wiordercode VARCHAR(50) ,
              BillCode VARCHAR(50) ,
              BillNumberId NUMERIC(24, 10) ,
              goodsfullname VARCHAR(500) ,
              erpgoodsfullname VARCHAR(500) ,
              freeitemname VARCHAR(500) ,
              cargofullname VARCHAR(500) ,
              wdtotal NUMERIC(24, 10) ,
              erptotal NUMERIC(24, 10) ,
              wdprice NUMERIC(24, 10) ,
              erpprice NUMERIC(24, 10) ,
              wdqty NUMERIC(24, 10) ,
              erpqty NUMERIC(24, 10),
            );  
						
        IF @billtype = 0
            BEGIN
                SELECT  dbo.SaleBill.BillNumberId ,
                        PtypeId ,
                        ItemID ,
                        CargoID ,
                        KTypeID ,
                        NTaxPrice ,
                        SUM(NTaxTotal) AS NTaxTotal ,
                        SUM(Qty) AS Qty ,
                        IsCombined,
                        IsGift 
                INTO    #tempSale
                FROM    dbo.SaleBill WHERE BillNumberId IN (SELECT Billnumberid FROM dbo.WdShopBillRelation)
                GROUP BY SaleBill.BillNumberId ,
                        PtypeId ,
                        ItemID ,
                        CargoID ,
                        KTypeID ,
                        NTaxPrice ,
                        IsCombined,
                        IsGift;
                        --select * from #tempSale;
                        --drop table #tempSale
            
                WITH    tempT
                          AS ( SELECT   wb.Billnumberid ,
                                        p.FullName AS goodsfullname ,
                                        p.typeId AS ptypeid ,
                                        wi.goodscode AS wipid ,
                                        SUM(wi.qty) AS wiqty ,
                                        AVG(wi.price) AS wiprice ,
                                        SUM(wi.total) AS witotal ,
                                        wi.sku_erpid AS wisku_erpid ,
                                        wc.goodscode AS wcpid ,
                                        SUM(wc.qty) AS wcqty ,
                                        wc.sku_erpid AS wcsku_erpid ,
                                        wc.whstpt_erpid AS wcwhstpt_erpid,
                                        wi.isgift
                               FROM     WdItemsDetail wi
                                        INNER JOIN ptype p ON p.Pid = wi.goodscode
                                        INNER JOIN WdCargoDetail wc ON wi.mid = wc.mid
                                                              AND wi.ordercode = wc.ordercode 
                                        INNER JOIN WdShopBillRelation wb ON wi.ordercode = wb.WdShopBillID
                               GROUP BY p.typeId ,
                                        wi.sku_erpid ,
                                        wi.goodscode ,
                                        --wi.price ,
                                        wc.goodscode ,
                                        wc.sku_erpid ,
                                        wc.whstpt_erpid ,
                                        wb.Billnumberid ,
                                        p.FullName,
                                        wi.isgift
                             )
                             
                             
                    INSERT  INTO #tempSaletable
                            SELECT  '' wiordercode,  
									bi.BillCode ,
                                    sb.BillNumberId ,
                                    tempWd.goodsfullname ,
                                    p.FullName AS erpgoodsfullname ,
                                    REPLACE(c.Fullname, 'я', '/') AS freeitemname ,
                                    ct.FullName AS cargofullname ,
                                    tempWd.witotal * tempWd.wcqty
                                    / tempWd.wiqty AS wdtotal ,
                                    sb.NTaxTotal AS erptotal ,
                                    dbo.F_RoundTotal((tempWd.witotal * tempWd.wcqty
                                    / tempWd.wiqty))/dbo.F_RoundQty(tempWd.wcqty)  AS wdprice ,
                                    sb.NTaxPrice AS erpprice ,
                                    tempWd.wcqty AS wdqty ,
                                    sb.Qty AS erpqty
                            FROM    tempT AS tempWd
                                    FULL JOIN #tempSale sb ON sb.PtypeId = tempWd.ptypeid
                                                              AND sb.ItemID = dbo.Get_StrArrayStrOfIndex(tempWd.wisku_erpid,
                                                              '_', 3)
                                                              AND tempWd.Billnumberid = sb.BillNumberId AND tempWd.wcwhstpt_erpid = sb.CargoID AND tempWd.isgift = sb.IsGift
                                    INNER JOIN CustomReferenceValue c ON sb.ItemID = c.id
                                    LEFT JOIN CargoType ct ON ct.CargoID = sb.CargoID
                                    INNER JOIN BillIndex bi ON bi.BillNumberId = tempWd.billnumberid
                                    INNER JOIN ptype p ON p.typeId = sb.PtypeId
                            WHERE   sb.ItemID <> 0 
                                    AND sb.IsCombined = 1
                                    AND bi.BillDate >= @startdate
                                    AND bi.BillDate <= @enddate
                            UNION ALL
                            SELECT  '' wiordercode,
									bi.BillCode ,
                                    sb.BillNumberId ,
                                    tempWd.goodsfullname ,
                                    p.FullName AS erpgoodsfullname ,
                                    REPLACE(x.FullName, 'я', '/') AS freeitemname ,
                                    ct.FullName AS cargofullname ,
                                    tempWd.witotal * tempWd.wcqty
                                    / tempWd.wiqty AS wdtotal ,
                                    sb.NTaxTotal AS erptotal ,
                                    dbo.F_RoundTotal((tempWd.witotal * tempWd.wcqty
                                    / tempWd.wiqty))/dbo.F_RoundQty(tempWd.wcqty) AS wdprice ,
                                    sb.NTaxPrice AS erpprice ,
                                    tempWd.wcqty AS wdqty ,
                                    sb.Qty AS erpqty
                            FROM    tempT AS tempWd
                                    FULL JOIN #tempSale sb ON sb.PtypeId = tempWd.ptypeid
                                                             AND sb.ItemID = dbo.Get_StrArrayStrOfIndex(tempWd.wisku_erpid,
                                                              '_', 3)
                                                             AND tempWd.Billnumberid = sb.BillNumberId AND tempWd.wcwhstpt_erpid = sb.CargoID AND tempWd.isgift = sb.IsGift
                                    INNER JOIN xw_SelfData x ON sb.ItemID = x._Id
                                    LEFT JOIN CargoType ct ON ct.CargoID = sb.CargoID
                                    INNER JOIN BillIndex bi ON bi.BillNumberId = sb.Billnumberid
                                    INNER JOIN ptype p ON p.typeId = sb.PtypeId
                            WHERE   sb.ItemID <> 0
                                    AND sb.IsCombined = 0
                                    AND bi.BillDate >= @startdate
                                    AND bi.BillDate <= @enddate
                            UNION ALL
                            SELECT  '' wiordercode,
									bi.BillCode ,
                                    sb.BillNumberId ,
                                    tempWd.goodsfullname ,
                                    p.FullName AS erpgoodsfullname ,
                                    '' AS freeitemname ,
                                    ct.FullName AS cargofullname ,
                                    tempWd.witotal * tempWd.wcqty
                                    / tempWd.wiqty AS wdtotal ,
                                    sb.NTaxTotal AS erptotal ,
                                    dbo.F_RoundTotal((tempWd.witotal * tempWd.wcqty
                                    / tempWd.wiqty))/dbo.F_RoundQty(tempWd.wcqty) AS wdprice ,
                                    sb.NTaxPrice AS erpprice ,
                                    tempWd.wcqty AS wdqty ,
                                    sb.Qty AS erpqty
                            FROM    tempT AS tempWd
                                    FULL JOIN #tempSale sb ON sb.PtypeId = tempWd.ptypeid
                                                             AND tempWd.Billnumberid = sb.BillNumberId AND tempWd.wcwhstpt_erpid = sb.CargoID AND tempWd.isgift = sb.IsGift
                                    LEFT JOIN CargoType ct ON ct.CargoID = sb.CargoID
                                    INNER JOIN BillIndex bi ON bi.BillNumberId = sb.Billnumberid
                                    INNER JOIN ptype p ON p.typeId = sb.PtypeId
                            WHERE   sb.ItemID = 0
                                    AND sb.IsCombined = 0
                                    AND bi.BillDate >= @startdate
                                    AND bi.BillDate <= @enddate;
                IF @IsDif = 1
                    SELECT  *
                    FROM    #tempSaletable   
                    WHERE  (#tempSaletable.goodsfullname IS NOT NULL ) AND ( ISNULL(goodsfullname, '') <> ISNULL(erpgoodsfullname,
                                                              '')
                            OR ISNULL(wdtotal, 0) <> ISNULL(erptotal, 0)
                            OR ISNULL(wdprice, 0) <> ISNULL(erpprice, 0)
                            OR ISNULL(wdqty, 0) <> ISNULL(erpqty, 0))
                    ORDER BY wiordercode ,
                            BillNumberId; 
                ELSE
                    SELECT  *
                    FROM    #tempSaletable WHERE #tempSaletable.goodsfullname IS NOT NULL 
                    ORDER BY wiordercode ,
                            BillNumberId; 
						--drop table #tempSaletable	
					DROP TABLE #tempSale
            END;
        IF @billtype = 1
            BEGIN
                INSERT  INTO #tempSaletable
                        SELECT  tempWd.wiordercode ,
                                bi.BillCode ,
                                sb.BillNumberId ,
                                tempWd.goodsfullname ,
                                p.FullName AS erpgoodsfullname ,
                                REPLACE(c.Fullname, 'я', '/') AS freeitemname ,
                                ct.FullName AS cargofullname ,
                                tempWd.witotal AS wdtotal ,
                                sb.NTaxTotal AS erptotal ,
                                tempWd.wiprice AS wdprice ,
                                sb.NTaxPrice AS erpprice ,
                                tempWd.wiqty AS wdqty ,
                                sb.Qty AS erpqty
                        FROM    ( SELECT    wb.Billnumberid ,
                                            p.FullName AS goodsfullname ,
                                            p.typeId AS ptypeid ,
                                            wi.ordercode AS wiordercode ,
                                            wi.goodscode AS wipid ,
                                            wi.qty AS wiqty ,
                                            wi.price AS wiprice ,
                                            wi.total AS witotal ,
                                            wi.sku_erpid AS wisku_erpid ,
                                            wi.mid
                                  FROM      WdItemsDetail wi
                                            INNER JOIN ptype p ON p.Pid = wi.goodscode
                                            INNER JOIN WdShopBillRelation wb ON wi.ordercode = wb.WdShopBillID
                                ) AS tempWd
                                FULL JOIN saleBackBill sb ON sb.mid = tempWd.mid
                                                             AND tempWd.Billnumberid = sb.BillNumberId
                                INNER JOIN CustomReferenceValue c ON sb.ItemID = c.id
                                INNER JOIN CargoType ct ON ct.CargoID = sb.CargoID
                                INNER JOIN WdShopBillRelation wb ON wb.Billnumberid = sb.BillNumberId
                                INNER JOIN BillIndex bi ON bi.BillNumberId = wb.Billnumberid
                                INNER JOIN ptype p ON p.typeId = sb.PtypeId
                        WHERE   sb.ItemID <> 0
                                AND sb.IsCombined = 1
                                AND wb.Flag = 5
                                AND bi.BillDate >= @startdate
                                AND bi.BillDate <= @enddate
                        UNION ALL
                        SELECT  tempWd.wiordercode ,
                                bi.BillCode ,
                                sb.BillNumberId ,
                                tempWd.goodsfullname ,
                                p.FullName AS erpgoodsfullname ,
                                REPLACE(x.FullName, 'я', '/') AS freeitemname ,
                                ct.FullName AS cargofullname ,
                                tempWd.witotal AS wdtotal ,
                                sb.NTaxTotal AS erptotal ,
                                tempWd.wiprice AS wdprice ,
                                sb.NTaxPrice AS erpprice ,
                                tempWd.wiqty AS wdqty ,
                                sb.Qty AS erpqty
                        FROM    ( SELECT    wb.Billnumberid ,
                                            p.FullName AS goodsfullname ,
                                            p.typeId AS ptypeid ,
                                            wi.ordercode AS wiordercode ,
                                            wi.goodscode AS wipid ,
                                            wi.qty AS wiqty ,
                                            wi.price AS wiprice ,
                                            wi.total AS witotal ,
                                            wi.sku_erpid AS wisku_erpid ,
                                            wi.mid
                                  FROM      WdItemsDetail wi
                                            INNER JOIN ptype p ON p.Pid = wi.goodscode
                                            INNER JOIN WdShopBillRelation wb ON wi.ordercode = wb.WdShopBillID
                                ) AS tempWd
                                FULL JOIN saleBackBill sb ON sb.mid = tempWd.mid
                                                             AND tempWd.Billnumberid = sb.BillNumberId
                                INNER JOIN xw_SelfData x ON sb.ItemID = x._Id
                                INNER JOIN CargoType ct ON ct.CargoID = sb.CargoID
                                INNER JOIN WdShopBillRelation wb ON wb.Billnumberid = tempWd.Billnumberid
                                INNER JOIN BillIndex bi ON bi.BillNumberId = sb.BillNumberId
                                INNER JOIN ptype p ON p.typeId = sb.PtypeId
                        WHERE   sb.ItemID <> 0
                                AND sb.IsCombined = 0
                                AND wb.Flag = 5
                                AND bi.BillDate >= @startdate
                                AND bi.BillDate <= @enddate
                        UNION ALL
                        SELECT  tempWd.wiordercode ,
                                bi.BillCode ,
                                sb.BillNumberId ,
                                tempWd.goodsfullname ,
                                p.FullName AS erpgoodsfullname ,
                                '' AS freeitemname ,
                                ct.FullName AS cargofullname ,
                                tempWd.witotal AS wdtotal ,
                                sb.NTaxTotal AS erptotal ,
                                tempWd.wiprice AS wdprice ,
                                sb.NTaxPrice AS erpprice ,
                                tempWd.wiqty AS wdqty ,
                                sb.Qty AS erpqty
                        FROM    ( SELECT    wb.Billnumberid ,
                                            p.FullName AS goodsfullname ,
                                            p.typeId AS ptypeid ,
                                            wi.ordercode AS wiordercode ,
                                            wi.goodscode AS wipid ,
                                            wi.qty AS wiqty ,
                                            wi.price AS wiprice ,
                                            wi.total AS witotal ,
                                            wi.sku_erpid AS wisku_erpid ,
                                            wi.mid
                                  FROM      WdItemsDetail wi
                                            INNER JOIN ptype p ON p.Pid = wi.goodscode
                                            INNER JOIN WdShopBillRelation wb ON wi.ordercode = wb.WdShopBillID
                                ) AS tempWd
                                FULL JOIN saleBackBill sb ON sb.mid = tempWd.mid
                                                             AND tempWd.Billnumberid = sb.BillNumberId
                                INNER JOIN CargoType ct ON ct.CargoID = sb.CargoID
                                INNER JOIN WdShopBillRelation wb ON wb.Billnumberid = sb.BillNumberId
                                                              OR wb.Billnumberid = sb.BillNumberId
                                INNER JOIN BillIndex bi ON bi.BillNumberId = wb.Billnumberid
                                INNER JOIN ptype p ON p.typeId = sb.PtypeId
                        WHERE   sb.ItemID = 0
                                AND sb.IsCombined = 0
                                AND wb.Flag = 5
                                AND bi.BillDate >= @startdate
                                AND bi.BillDate <= @enddate;
                IF @IsDif = 1
                    SELECT  *
                    FROM    #tempSaletable
                    WHERE   ISNULL(goodsfullname, '') <> ISNULL(erpgoodsfullname,
                                                              '')
                            OR ISNULL(wdtotal, 0) <> ISNULL(erptotal, 0)
                            OR ISNULL(wdprice, 0) <> ISNULL(erpprice, 0)
                            OR ISNULL(wdqty, 0) <> ISNULL(erpqty, 0)
                    ORDER BY wiordercode ,
                            BillNumberId; 
                ELSE
                    SELECT  *
                    FROM    #tempSaletable
                    ORDER BY wiordercode ,
                            BillNumberId; 
            END;
        DROP TABLE #tempSaletable;
        
          
        IF @billtype = 2
            BEGIN
                CREATE TABLE #tempMoneytable
                    (
                      wiordercode VARCHAR(50) ,
                      BillCode VARCHAR(50) ,
                      BillNumberId NUMERIC(24, 10) ,
                      goodsfullname VARCHAR(500) ,
                      atypeid VARCHAR(50) ,
                      wdtotal NUMERIC(24, 10) ,
                      erptotal NUMERIC(24, 10)
                    );
                INSERT  INTO #tempMoneytable
                        SELECT  wi.ordercode AS wiordercode ,
                                bi.BillCode ,
                                sb.BillNumberId ,
                                p.FullName AS goodsfullname ,
                                ai.FullName AS atypeid ,
                                wi.total AS wdtotal ,
                                sb.NTotal AS erptotal
                        FROM    WdItemsDetail wi
                                INNER JOIN WdShopBillRelation wb ON wi.ordercode = wb.WdShopBillID
                                FULL JOIN MoneyBill sb ON wi.mid = sb.mid
                                                          AND wb.Billnumberid = sb.BillNumberId
                                INNER JOIN BillIndex bi ON sb.BillNumberId = bi.BillNumberId
                                INNER JOIN ptype p ON p.Pid = wi.goodscode
                                INNER JOIN Ac_Items ai ON ai.nId = sb.AtypeId
                        WHERE   wb.Flag = 0
                                AND bi.BillDate >= @startdate
                                AND bi.BillDate <= @enddate;
				--select * from #tempMoneytable order by wiordercode , billnumberid
                IF @IsDif = 1
                    SELECT  *
                    FROM    #tempMoneytable
                    WHERE   ISNULL(wdtotal, 0) <> ISNULL(erptotal, 0); 
                ELSE
                    SELECT  *
                    FROM    #tempMoneytable
                    ORDER BY wiordercode ,
                            BillNumberId; 
                DROP TABLE #tempMoneytable;
				
            END;
    END;

GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO






IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_WdshopBillDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Gp_WdshopBillDeal
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE Gp_WdshopBillDeal
(
       @BillDate	DATETIME ,			---录单日期
       @BillCode	VARCHAR(50),		---单据编号  
       @FreightNo   VARCHAR(50),		---销售出库单运单号
       @VchCode		VARCHAR(50),		---网店单据ID   
       @BtypeId		VARCHAR(500),		---往来单位 
	   @BillType	NUMERIC(4,0),		---单据类型       
	   @Comment		NVARCHAR(1000),		---摘要
	   @Explain	    NVARCHAR(500),	    ---说明（传入的是网店单据号）		
       @PtypeId		VARCHAR(200)='',	---商品ID
       @FullName    VARCHAR(100),     --商品名称 
       @ETypeId		VARCHAR(200)='',	---经手人ID
       @KTypeId		VARCHAR(200)='',	---仓库ID
       @TotalMoney	 NUMERIC(24, 10) =0,	---总金额
       @TotalNMoney	 NUMERIC(24, 10) =0,	---实收金额
       @Qty			 NUMERIC(24, 10) =0,	---总数量
       @Checke		VARCHAR(50),		---制单人
       --@EshopId		VARCHAR(200),
       --@TradeId     VARCHAR(100),   --网店只有一个网店单据号,还有一个订单号是选填
       @Havecargo	BIT,				---货位
       @Flag	    INT		,			---区分单据(数字同说明里的数字)
       @TEL         VARCHAR(200)='',  --承运单位
       @AtypeId	    VARCHAR(500)='', --收款账户
       @NPreferenceMoney NUMERIC(24, 10)=0, --优惠金额
       @TotalStr    VARCHAR(MAX)   --多账户收款金额字符串
)
WITH ENCRYPTION
AS 
SET NOCOUNT ON
BEGIN
   ----数据库存在这张单，不再生成
	IF EXISTS(SELECT TOP 1 1 FROM  dbo.BillIndex b JOIN dbo.WdShopBillRelation e ON b.BillNumberId=e.billnumberid AND e.WdShopBillID =@VchCode AND flag=@Flag
	)
		BEGIN
			SELECT -1 AS id
			RETURN
		END 


    --删除半个小时以上还没有汇总成功的网店单据，避免再次汇总失败
	DELETE dbo.WdShopBillRelationTemp FROM WdBillIndexTemp wbt INNER JOIN dbo.WdShopBillRelationTemp brt ON brt.Billnumberid = wbt.BillNumberId
	WHERE  -DATEDIFF(HOUR,GETDATE(),checkTime)>0.5 AND brt.WdShopBillID = @VchCode
	
	IF EXISTS(SELECT TOP 1 1 FROM  dbo.WdBillIndexTemp b JOIN dbo.WdShopBillRelationTemp e ON b.BillNumberId=e.billnumberid AND e.WdShopBillID =@VchCode)
	BEGIN
		DECLARE @tip VARCHAR(200)
		SELECT @tip = ISNULL(@VchCode,'该')+'订单正在汇总生成单据中，请勿重复生成！'
		RAISERROR(@tip,16,1)
		--SELECT -1 AS id
		RETURN
	END 
	
		
	IF (@Flag=1 OR @Flag=5 OR @Flag=6) AND EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName='mngcargospace' AND Value=1) AND @Havecargo=0
		BEGIN
			SET @Explain='系统启用了货位，网店单据【'+@Explain+'】有商品未设置货位，请配置完成后再进行此操作。'
			RAISERROR(@Explain,16,1)
			RETURN
		END
		
	DECLARE @DTypeId VARCHAR(200)																										--经手人部门
	IF @ETypeid='00001'																									               
		 BEGIN
			SET @Explain='网店单据【'+@Explain+'】经手人为管理员，请重新做单后再进行此操作。'
			RAISERROR(@Explain,16,1)
			RETURN
		END 
	ELSE IF @ETypeId='' or @ETypeId Is NULL
		BEGIN
			SET @Explain='网店单据【'+@Explain+'】经手人为空，请新增经手人再进行此操作。'
			RAISERROR(@Explain,16,1)
			RETURN
		END
	ELSE 
		BEGIN
			 SET @DTypeId=(SELECT B.typeid  FROM employee A JOIN Department B ON A.Department = B.FullName WHERE A.typeId=@ETypeid)	
			 IF @DTypeId='' OR @DTypeId IS NULL
				BEGIN
					SET @Explain='网店单据【'+@Explain+'】经手人不存在，请先到操作员里面新增该操作员。'
					RAISERROR(@Explain,16,1)
					RETURN
				END  
		END
	IF @KTypeId = '' OR @KTypeId Is NULL
		BEGIN
			SET @Explain='网店单据【'+@Explain+'】不存在该仓库,请重新做单后再进行此操作!'
			RAISERROR(@Explain,16,1)
			RETURN
		END
		
	DECLARE @AccountCount INT =0,@tempAccountStr VARCHAR(200),@tempTotalStr VARCHAR(200)
	IF @AtypeId<>''
		BEGIN
			CREATE TABLE #tempAccount
			(
				id INT IDENTITY(1,1),
				accountStr VARCHAR(200),
			)
			INSERT INTO #tempAccount
			SELECT a FROM dbo.f_split(@AtypeId,';')	
			--select * from #tempAccount
			CREATE TABLE #tempTotal
			(
				id INT IDENTITY(1,1),
				totalStr VARCHAR(200)
			)
			INSERT INTO #tempTotal
			SELECT a FROM dbo.f_split(@TotalStr,';')
			SELECT @AccountCount=COUNT(*) FROM #tempAccount	
		END
	
	DECLARE @sql NVARCHAR(MAX)
	DECLARE @BillNumberId NUMERIC(18,0)	
	
	DECLARE @ATYPEID1	VARCHAR(50)=''  --往来科目
	DECLARE @cid        INT
	
	SELECT @cid=CId FROM dbo.Ac_Currency WHERE Sysrow=1																							 
	DECLARE @StypeId VARCHAR(200)   
	-- SET @StypeId='00001'     						--分支机构 V3为00001
	--IF @StypeId=''
	--	BEGIN
	--		RAISERROR('请配置分支机构',16,1)
	--		RETURN
	--	END 
	SELECT @StypeId = STypeID FROM dbo.Stock WHERE typeId = @KTypeId		
		
	DECLARE @Period INT				
	SET @Period = (SELECT SubValue  FROM sysdata WHERE SubName='period' )								--业务期间

	SET @Comment = '【网店】'+@Comment
	
	--替换单引号
    SET @Comment= REPLACE(@Comment,'''','''''')
	
	---以防摘要太长，截取字符串
	DECLARE @Comment1 VARCHAR(256)=@Comment
	 
	SET @Explain='网店单据【'+@Explain+'】'
	

	IF @Flag=1  --销售出库单
		BEGIN
			DECLARE @VerifyID VARCHAR(50)
			SELECT @VerifyID = VerifyID FROM dbo.SType WHERE TypeId=@StypeId
			IF EXISTS(SELECT TOP 1 1 FROM BillAtype WHERE BillTypeId='11' AND StypeId=@VerifyID AND AtypeId<>'')
				SET @ATYPEID1=(SELECT ISNULL(atypeid,' ') FROM BillAtype WHERE BillTypeId='11' AND StypeId=@VerifyID  )
		END	
	ELSE IF @Flag=5 --退货单 
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM BillAtype WHERE BillTypeId='45' AND StypeId=@StypeId AND AtypeId<>'')
				SET @ATYPEID1=(SELECT ISNULL(atypeid,' ') FROM BillAtype WHERE BillTypeId='45' AND StypeId=@StypeId)
		END
	ELSE IF @Flag=0 --费用单 
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM BillAtype WHERE BillTypeId='36_client' AND StypeId=@StypeId AND AtypeId<>'')
				SET @ATYPEID1=(SELECT ISNULL(atypeid,' ') FROM BillAtype WHERE BillTypeId='36_client' AND StypeId=@StypeId)
		END
		
	BEGIN TRANSACTION
	DECLARE @errorSum INT SET @errorSum=0  
	
	IF @AtypeId<>''
		BEGIN
			SELECT @AtypeId = accountStr FROM #tempAccount WHERE id=1
		END
	DECLARE @CollectBill INT  =0
	IF EXISTS (SELECT * FROM dbo.WdShopBaseInfo WHERE Field = 'collectBill' AND Value='True')
	SET @CollectBill = 1
	
	DECLARE @BTypeID1 VARCHAR(50)
	SELECT @BTypeID1 =ISNULL(denominatedid,@BtypeId) FROM dbo.btype WHERE typeId = @BtypeId
	
	IF @CollectBill = 1 AND @BillType =11
	BEGIN
		SET @sql='
		INSERT INTO	WdBillIndexTemp 
		( 
		  BillDate ,	--录单日期
		  BillCode ,	--单据编号
		  BillType ,	--单据类型
		  Comment ,		--摘要
		  atypeid,		--收款项目ID 现金（1）
		  atypeid1,		--往来科目
		  ptypeid ,		--商品ID
		  btypeid ,		--结算单位
		  DealBTypeID,  --往来单位
		  etypeid ,		--职员ID
		  ktypeid ,		--仓库ID
		  ifcheck ,		--是否过账 f：未过账,t：过账
		  checke ,		--制单人
		  cid,
		  rate,
		  totalmoney ,	--总金额
		  totalinmoney,	--收款金额
		  ntotalmoney ,	--总金额
		  ntotalinmoney,	--收款金额
		  totalqty ,	--数量
		  RedWord ,		--红冲 0
		  draft ,		--草稿标志 1
		  DTypeId ,		--经手人部门
		  Stypeid ,		--分支机构()
		  checkTime ,	--制单时间
		  explain,		--说明
		  period ,
		  Audit_explain,	--用于存储VchCode
		  tax,
		  Assessor,
		  waybillcode,    --运单号
		  TEL,              --承运单位
		  NPreferenceMoney,   --优惠金额
		  preferencemoney,
		  ktypeid2,
		  ktypeid3,  
		  vipCZMoney,
		  AssetBusinessTypeId ,
		  BillTime     
		) VALUES 
		(
		  '''+CAST(@BillDate AS VARCHAR(50))+''',
		  '''+@BillCode+''',
		  '+CAST(@BillType AS VARCHAR(50))+',
		  '''+@Comment1+''',
		  @Atype,
		   '''+@ATYPEID1+''',
		  @Ptypeid,
		  @Btypeid1,
		  @Btypeid,
		  @ETypeid,
		  @Ktypeid,
		  ''f'',
		  '''+@Checke+''',
		  '''+CAST(@cid  AS VARCHAR(50))+''',
		  1,
		  @TotalMoney,
		  CASE WHEN @Atype IS NULL OR @Atype='''' THEN 0 ELSE  @TotalNMoney END,
		  @TotalMoney,
		  CASE WHEN @Atype IS NULL OR @Atype='''' THEN 0 ELSE  @TotalNMoney END,
		  @Qty,
		  0,
		  1,
		  '''+@DTypeId+''',
		  '''+@StypeId+''',
		  '''+CONVERT(VARCHAR(100), GETDATE(), 25)+''' ,
		  '''+@Explain+''',
		  '+CAST(@Period AS VARCHAR(50))+',
		  '''+@VchCode+''',
		  0,
		  ''wdshop'',
		  @FreightNo,
		  @TEL,
		  @NPreferenceMoney,
		  @NPreferenceMoney,
		  '''',
		  '''',
		  0,
		  0,
		  '''+CONVERT(varchar(100), GETDATE(), 8)+''' 
		)
		SELECT @BillNumberId=SCOPE_IDENTITY();	'
	END
	ELSE 
		BEGIN 
			SET @sql='
			INSERT INTO	BillIndex 
			( 
			  BillDate ,	--录单日期
			  BillCode ,	--单据编号
			  BillType ,	--单据类型
			  Comment ,		--摘要
			  atypeid,		--收款项目ID 现金（1）
			  atypeid1,		--往来科目
			  ptypeid ,		--商品ID
			  btypeid ,		--结算单位
			  DealBTypeID,  --往来单位
			  etypeid ,		--职员ID
			  ktypeid ,		--仓库ID
			  ifcheck ,		--是否过账 f：未过账,t：过账
			  checke ,		--制单人
			  cid,
			  rate,
			  totalmoney ,	--总金额
			  totalinmoney,	--收款金额
			  ntotalmoney ,	--总金额
			  ntotalinmoney,	--收款金额
			  totalqty ,	--数量
			  RedWord ,		--红冲 0
			  draft ,		--草稿标志 1
			  DTypeId ,		--经手人部门
			  Stypeid ,		--分支机构()
			  checkTime ,	--制单时间
			  explain,		--说明
			  period ,
			  Audit_explain,	--用于存储VchCode
			  tax,
			  Assessor,
			  waybillcode,    --运单号
			  TEL,              --承运单位
			  NPreferenceMoney,   --优惠金额
			  PreferenceMoney,
			  ktypeid2,
			  ktypeid3,  
			  vipCZMoney,
			  AssetBusinessTypeId ,
			  BillTime    
			) VALUES 
			(
			  '''+CAST(@BillDate AS VARCHAR(50))+''',
			  '''+@BillCode+''',
			  '+CAST(@BillType AS VARCHAR(50))+',
			  '''+@Comment1+''',
			  @Atype,
			   '''+@ATYPEID1+''',
			  @Ptypeid,
			  @Btypeid1,
			  @Btypeid,
			  @ETypeid,
			  @Ktypeid,
			  ''f'',
			  '''+@Checke+''',
			  '''+CAST(@cid  AS VARCHAR(50))+''',
			  1,
			  @TotalMoney,
			  CASE WHEN @Atype IS NULL OR @Atype='''' THEN 0 ELSE  @TotalNMoney END,
			  @TotalMoney,
			  CASE WHEN @Atype IS NULL OR @Atype='''' THEN 0 ELSE  @TotalNMoney END,
			  @Qty,
			  0,
			  1,
			  '''+@DTypeId+''',
			  '''+@StypeId+''',
			  '''+CONVERT(VARCHAR(100), GETDATE(), 25)+''' ,
			  '''+@Explain+''',
			  '+CAST(@Period AS VARCHAR(50))+',
			  '''+@VchCode+''',
			  0,
			  ''wdshop'',
			  @FreightNo,
			  @TEL,
			  @NPreferenceMoney,
			  @NPreferenceMoney,
			  '''',
			  '''',
			  0,
			  0,
			  '''+CONVERT(varchar(100), GETDATE(), 8)+''' 
			)
			SELECT @BillNumberId=SCOPE_IDENTITY();	'
		END 
	--SELECT @sql
	--Double Check
	IF EXISTS(SELECT TOP 1 1 FROM  dbo.BillIndex b JOIN WdShopBillRelation e ON b.BillNumberId=e.billnumberid AND e.WdShopBillID=@VchCode AND flag=@Flag)
	BEGIN
			SELECT -1 AS id
			RETURN
	END 
	
	--SELECT @TotalMoney=dbo.F_RoundTotal(@TotalMoney),@TotalNMoney=dbo.F_RoundTotal(@TotalNMoney),@NPreferenceMoney=dbo.F_RoundPrice(@NPreferenceMoney),@Qty=dbo.F_RoundQty(@Qty)
	
	IF  @BillType=11 ---销售出库单 
		BEGIN 
			EXEC sp_executesql @sql,N'@Atype VARCHAR(50),@Ptypeid VARCHAR(50),@Btypeid VARCHAR(50),@Btypeid1 VARCHAR(50),@ETypeid VARCHAR(50),
								   @Ktypeid VARCHAR(50),@TotalMoney  NUMERIC(24, 10) ,@TotalNMoney  NUMERIC(24, 10) ,@Qty  NUMERIC(24, 10) ,@FreightNo VARCHAR(50),@TEL VARCHAR(200),@NPreferenceMoney NUMERIC(24, 10), @BillNumberId NUMERIC(18,0) out',
								   @AtypeId,'',@BtypeID,@BTypeID1,@ETypeid,@KTypeId,@TotalMoney,@TotalNMoney,@Qty,@FreightNo,@TEL,@NPreferenceMoney, @BillNumberId OUT
		END 
	ELSE IF @BillType=36  ---一般费用单
		BEGIN	
			 --SET @AtypeId=''
			 
			 PRINT @TotalMoney
			 PRINT @TotalNMoney
			 EXEC sp_executesql @sql,N'@Atype VARCHAR(50),@Ptypeid VARCHAR(50),@Btypeid VARCHAR(50),@Btypeid1 VARCHAR(50),@ETypeid VARCHAR(50),
								   @Ktypeid VARCHAR(50),@TotalMoney  NUMERIC(24, 10) ,@TotalNMoney  NUMERIC(24, 10) ,@Qty  NUMERIC(24, 10) ,@FreightNo VARCHAR(50),@TEL VARCHAR(200),@NPreferenceMoney NUMERIC(24, 10), @BillNumberId NUMERIC(18,0) out',
								   @AtypeId,'',@BtypeId,@BTypeID1,@ETypeId,'',@TotalMoney,@TotalNMoney,0,'',@TEL,@NPreferenceMoney, @BillNumberId out
		END
	ELSE IF @BillType=45  ---退货单
		BEGIN
			--SET @AtypeId=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='FeeItem')	
			--SET @BtypeID=(SELECT Value FROM dbo.EshopBaseInfo WHERE EshopID=@EshopId AND Field='InOutBtype')
			EXEC sp_executesql @sql,N'@Atype VARCHAR(50),@Ptypeid VARCHAR(50),@Btypeid VARCHAR(50),@Btypeid1 VARCHAR(50),@ETypeid VARCHAR(50),
								   @Ktypeid VARCHAR(50),@TotalMoney  NUMERIC(24, 10) ,@TotalNMoney  NUMERIC(24, 10) ,@Qty  NUMERIC(24, 10) ,@FreightNo VARCHAR(50),@TEL VARCHAR(200),@NPreferenceMoney NUMERIC(24, 10), @BillNumberId NUMERIC(18,0) out',
								   @AtypeId,'',@BtypeID,@BTypeID1,@ETypeid,@KTypeid,@TotalMoney,@TotalNMoney,@Qty,'',@TEL,@NPreferenceMoney, @BillNumberId  out
		END 

	   
	SET @errorSum=@errorSum+@@error			
	--将billnumberid的获取调整到@sql里面去了				   
	--SELECT @BillNumberId=SCOPE_IDENTITY();																----获取生成的id
	
	IF(@CollectBill = 0 ) --不是汇总生成的billnumberid时才保存编号种子数
	BEGIN
		EXEC GP_SaveBillCode_Seed @BillNumberId,@BillDate,@BillType,@BillCode						----更新编号种子数
		SET @errorSum=@errorSum+@@error
	END 
	ELSE IF (@CollectBill = 1 AND  @BillType <> 11) 
	BEGIN 
		EXEC GP_SaveBillCode_Seed @BillNumberId,@BillDate,@BillType,@BillCode						----更新编号种子数
		SET @errorSum=@errorSum+@@error
	END 
	
	DECLARE @WdSyncFlag bit =0
	IF @CollectBill = 1 AND @BillType=11
	BEGIN 
		IF EXISTS(SELECT 1 FROM WdShopBillRelationTemp a inner join WdbillindexTemp b on a.billnumberid=b.billnumberid where WdShopBillID=@VchCode AND a.flag=@Flag )
		BEGIN
			SET @errorSum=-1
		END	
		Delete WdShopBillRelationTemp WHERE  WdShopBillID=@VchCode AND flag=@Flag                          ----删除关系对应
		SET @errorSum=@errorSum+@@error		
		INSERT INTO  WdShopBillRelationTemp SELECT  @VchCode,@BillNumberId,@Flag,@WdSyncFlag                           ----重新建立关系
	END 
	ELSE
	BEGIN
		IF EXISTS(SELECT 1 FROM WdShopBillRelation a inner join billindex b on a.billnumberid=b.billnumberid where WdShopBillID=@VchCode AND flag=@Flag )
		BEGIN
			SET @errorSum=-1
		END	
		Delete WdShopBillRelation WHERE  WdShopBillID=@VchCode AND flag=@Flag                          ----删除关系对应
		SET @errorSum=@errorSum+@@error
		INSERT INTO WdShopBillRelation SELECT  @VchCode,@BillNumberId,@Flag,@WdSyncFlag                           ----重新建立关系
	END 
	SET @errorSum=@errorSum+@@error
	-------------------------多账户收款插入（现金）------------
	IF @TotalNMoney <>0 AND @AtypeId IS NOT NULL AND @AtypeId<>''
	BEGIN
		IF @BillType=11           --出库单
			BEGIN
				IF @AccountCount=1
					BEGIN
						IF @CollectBill = 0
						INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
						VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【网店销售出库单】商品收款',-1,@TotalNMoney,@BillType)
						ELSE
						INSERT INTO WdBillMulAccountTemp(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
						VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【网店销售出库单】商品收款',-1,@TotalNMoney,@BillType)
					END
				ELSE 
					BEGIN
						DECLARE @index INT =1
						WHILE @index <= @AccountCount
							BEGIN
								SELECT @tempAccountStr = accountStr FROM #tempAccount WHERE id=@index
								SELECT @tempTotalStr = totalStr FROM #tempTotal WHERE id=@index
								IF @CollectBill = 0
								BEGIN 
									INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
									VALUES(@BillNumberId,@tempAccountStr,@tempTotalStr,'【网店销售出库单】商品收款',-1,@tempTotalStr,@BillType)
								END 
								ELSE
								BEGIN
									INSERT INTO WdBillMulAccountTemp(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
									VALUES(@BillNumberId,@tempAccountStr,@tempTotalStr,'【网店销售出库单】商品收款',-1,@tempTotalStr,@BillType)
								END 
								SET @index = @index+1
							END
					END
			END
		ELSE IF @BillType=45	  --退货单
			BEGIN
					IF @AccountCount=1
						BEGIN
							INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
							VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【网店销售退货单】商品退货',-1,@TotalNMoney,@BillType)
						END
					ELSE 
						BEGIN
							DECLARE @index2 INT =1
							WHILE @index2 <= @AccountCount
								BEGIN
									SELECT @tempAccountStr = accountStr FROM #tempAccount WHERE id=@index2
									SELECT @tempTotalStr = totalStr FROM #tempTotal WHERE id=@index2
									INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
									VALUES(@BillNumberId,@tempAccountStr,@tempTotalStr,'【网店销售退货单】商品退货',-1,@tempTotalStr,@BillType)
									SET @index2 = @index2+1
								END
						END
				END
		ELSE IF @BillType=36       --一般费用单
			BEGIN
					IF @AccountCount=1
						BEGIN
							INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
							VALUES(@BillNumberId,@AtypeId,@TotalNMoney,'【网店一般费用单】仅退款',-1,@TotalNMoney,@BillType)
						END 
					ELSE 
						BEGIN
							DECLARE @index3 INT =1
							WHILE @index3 <= @AccountCount
								BEGIN
									SELECT @tempAccountStr = accountStr FROM #tempAccount WHERE id=@index3
									SELECT @tempTotalStr = totalStr FROM #tempTotal WHERE id=@index3
									INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,VipCardID,NTotalMoney,BillType)
									VALUES(@BillNumberId,@tempAccountStr,@tempTotalStr,'【网店销售退货单】商品退货',-1,@tempTotalStr,@BillType)
									SET @index3 = @index3+1
								END
						END
				END
			
	END
	-------------------------------------------------------------------
	SET @errorSum=@errorSum+@@error
	
	SET @errorSum=@errorSum+@@error
	IF @errorSum<>0  --如果有错误
	  BEGIN
		DECLARE @ErrorInfo Nvarchar(200) 
		declare @BillName NVarchar(200)
		IF @Flag=1
			SET @BillName='生成本地销售出库单'
		ELSE IF @Flag=5
			SET @BillName='生成本地销售退货单'
		ELSE IF @Flag=0
			SET @BillName='生成本地一般费用单'
		SET @ErrorInfo=@Explain+@BillName+'失败，请检查订单信息后再试'
		RAISERROR(@ErrorInfo,16,1)
		ROLLBACK TRANSACTION 
		SELECT -1 AS id
	  END  
	ELSE
	  BEGIN
		COMMIT TRANSACTION   --返回结果
		IF(@CollectBill = 1 AND @BillType=11)
		BEGIN
			SELECT 'R'+CAST(@BillNumberId AS VARCHAR) AS id 
		END 
		ELSE
		BEGIN 
			SELECT @BillNumberId AS id     
		END  
	  END
	
END 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT TOP 1
                    1
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_WdShopBillDealDetail]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROC [dbo].[Gp_WdShopBillDealDetail];
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO
CREATE PROCEDURE Gp_WdShopBillDealDetail
    (
      @BillDate DATETIME ,			---单据日期
      @BillType NUMERIC(4, 0) ,		---单据类型  
      @BillNumberId NUMERIC(10, 0) ,		---单据ID
      @PtypeId VARCHAR(50) = '' ,		---商品ID     
      @Qty NUMERIC(24, 10) = 0 ,	---数量 
      @KTypeId VARCHAR(50) = '00001' ,---仓库ID 
      @ETypeId VARCHAR(200) = '' ,	---业务员ID   
      @Total NUMERIC(24, 10) = 0 ,	---总价/实付金额
      @Price NUMERIC(24, 10) = 0 ,	---单价
      @FreightFee NUMERIC(24, 10) = 0 ,	---运费
      @Cargo VARCHAR(MAX) ,		---货位
      @ItemID INT ,				---自由项
      @Comment VARCHAR(100) = '' ,	---摘要     
      @EshopId VARCHAR(200) ,		---网店id
      @feeatypeid VARCHAR(100) ,    --费用项
      @Flag INT ,
      @IsGift BIT ,        --赠品项
      @Stypeid VARCHAR(50) = '00001' ,--分支机构
      @CargoID VARCHAR(100) = '' , --货位id
      @Itemqty VARCHAR(100) = '' , --每个货位对应数量字符串  
      @id INT,         --每条明细对应的id
      @WdBillComment VARCHAR(100) = ''---带网店编号的摘要     
    )
    WITH ENCRYPTION
AS
    SET NOCOUNT ON;
    BEGIN
		DECLARE @customPirce VARCHAR(50)='0' --0=网店商品单价,1=预设售价1,2=预设售价2,3=预设售价3,4=预设售价4,5=预设售价5,6=预设售价6,7=预设售价7,8=预设售价8,9=预设售价9,10=预设售价10,11=零售价,12=最低售价,13=最高售价
		DECLARE @YunFei VARCHAR(50) ,@PriceSource VARCHAR(200)='网店生成'--价格来源
		SELECT @YunFei =typeId,@customPirce=pricetype FROM dbo.WdShopConfig INNER JOIN PTYPE ON dbo.WdShopConfig.PtypeId = PTYPE.UserCode WHERE eshopid = @EshopId
		IF (@BillType = 11 AND @PtypeId != ISNULL(@YunFei,'') AND @IsGift = 0)
		BEGIN 
			IF(@customPirce = '1')
			BEGIN
				SELECT @Price =  PreSalePrice1 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total =  dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价1'
			END 
			ELSE IF(@customPirce = '2')
			BEGIN
				SELECT @Price = PreSalePrice2 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价2'
			END
			ELSE IF(@customPirce = '3')
			BEGIN
				SELECT @Price = PreSalePrice3 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价3'
			END 
			ELSE IF(@customPirce = '4')
			BEGIN
				SELECT @Price = PreSalePrice4 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价4'
			END 
			ELSE IF(@customPirce = '5')
			BEGIN
				SELECT @Price = PreSalePrice5 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价5'
			END 
			ELSE IF(@customPirce = '6')
			BEGIN
				SELECT @Price = PreSalePrice6 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价6'
			END 
			ELSE IF(@customPirce = '7')
			BEGIN
				SELECT @Price = PreSalePrice7 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价7'
			END 
			ELSE IF(@customPirce = '8')
			BEGIN
				SELECT @Price = PreSalePrice8 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价8'
			END 
			ELSE IF(@customPirce = '9')
			BEGIN
				SELECT @Price = PreSalePrice9 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价9'
			END 
			ELSE IF(@customPirce = '10')
			BEGIN
				SELECT @Price = PreSalePrice10 FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '预设售价10'
			END 
			ELSE IF(@customPirce = '11')
			BEGIN
				SELECT @Price = RetailPrice FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '零售价'
			END 
			ELSE IF(@customPirce = '12')
			BEGIN
				SELECT @Price = LowSalePrice FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '最低售价'
			END 
			ELSE IF(@customPirce = '13')
			BEGIN
				SELECT @Price = TopSalePrice FROM PType_Price WHERE PTypeID = @PtypeId AND IsDefaultUnit = 1
				SELECT @Total = dbo.F_RoundTotal(@Price * @Qty),@PriceSource = '最高售价'
			END 
		END 
        
        DECLARE @CargoCount INT= 0 ,
            @tempCargoStr VARCHAR(MAX) ,
            @tempCargoIDQty NUMERIC(24, 10) = 0;
	  --先默认一个货位id
        IF @CargoID = ''
            OR @CargoID IS NULL
            BEGIN  
                SELECT  @CargoID = CargoID
                FROM    dbo.CargoType
                WHERE   KtypeID = @KTypeId
                        AND IsDefault = 1;
            END;
    --货位
        IF @CargoID <> ''
            BEGIN
                CREATE TABLE #tempCargo
                    (
                      id INT IDENTITY(1, 1) ,
                      cargostr VARCHAR(100)
                    );
                INSERT  INTO #tempCargo
                        SELECT  a
                        FROM    dbo.f_split(@CargoID, ',');	

                SELECT  @CargoCount = COUNT(*)
                FROM    #tempCargo;
			
                CREATE TABLE #tempCargoQty
                    (
                      id INT IDENTITY(1, 1) ,
                      CargoQty VARCHAR(100)
                    );
                INSERT  INTO #tempCargoQty
                        SELECT  a
                        FROM    dbo.f_split(@Itemqty, ',');
            END;
    
    --是否有自由项或组合项
        DECLARE @iscombined INT= 0; 
        IF EXISTS ( SELECT TOP 1
                            1
                    FROM    dbo.ptype
                    WHERE   typeId = @PtypeId
                            AND ( customitemfrom = 0
                                  OR customitemfrom = 1
                                ) )
            SELECT  @iscombined = customitemfrom
            FROM    dbo.ptype
            WHERE   typeId = @PtypeId;   
        IF @ItemID = NULL
            SET @ItemID = 0;
		
		DECLARE @skuid VARCHAR(100)
		IF(@ItemID <>0)
		BEGIN
			IF(@iscombined=0)
				BEGIN
					SELECT @skuid =  CAST(Pid AS VARCHAR)+'_0_'+CAST(@ItemID AS VARCHAR)+ '_'+ CAST(baseUnitId AS VARCHAR) FROM dbo.ptype WHERE typeId = @PtypeId
				END 
			ELSE
				SELECT @skuid =  CAST(Pid AS VARCHAR)+'_1_'+CAST(@ItemID AS VARCHAR)+ '_'+ CAST(baseUnitId AS VARCHAR) FROM dbo.ptype WHERE typeId = @PtypeId
		END 
		ELSE
			SELECT @skuid = Pid  FROM dbo.ptype WHERE typeId = @PtypeId
		
	---商品信息
        DECLARE @entrycode VARCHAR(200)= '' ,
				@UnitID INT =0,
				@MUnitID INT ,
				@NUnitID INT = 0,
				@MQty NUMERIC(24, 10) ,
				@Mrate NUMERIC(24, 10) ,
				@MSale NUMERIC(24, 10) ,
				@Nrate NUMERIC(24, 10); 
        SELECT  @entrycode = EntryCode ,
                @UnitID = baseUnitId ,
                @MUnitID = SaleUnitId ,
                @NUnitID = AssistantUnitId
        FROM    dbo.ptype
        WHERE   typeId = @PtypeId;
		---销售换算率，数量,销售单价
        SELECT  @Mrate = Rate
        FROM    PType_Units_Ext
        WHERE   PtypeID = @PtypeId
                AND UnitsId = @MUnitID;
        SET @MQty = @Qty / @Mrate;
        SET @MSale = @Price * @Mrate;
		---浮动换算率
        SELECT  @Nrate = ISNULL(Rate,0)
        FROM    PType_Units_Ext
        WHERE   PtypeID = @PtypeId
                AND UnitsId = @NUnitID;
		
		
		DECLARE @CollectBill INT  =0
		IF EXISTS (SELECT * FROM dbo.WdShopBaseInfo WHERE Field = 'collectBill' AND Value='True')
		SET @CollectBill = 1                
 
        DECLARE @GoodsNumber VARCHAR(100)='',--批号
				@ProduceDate VARCHAR(50)='',--生产日期
				@ValidDate VARCHAR(50)='',--效期至
				@GoodsCostPrice NUMERIC(24,10)=0,--商品成本价
				@batchNumberDeal INT, --批次处理
				@batchQty NUMERIC(24,10), --批次里的数量
				@serial VARCHAR(MAX),--序列号
				@serialRelation BIT, --序列号关联货位、自由项、批次批号	
				@salebillcount INT,	--明细行数	
				@serialid INT,	
				@serialA varchar(50),
				@CostPrice NUMERIC(24,10) --序列号表中的成本价
		SELECT @batchNumberDeal=Value FROM dbo.WdShopBaseInfo WHERE Field = 'BatchNumberDeal'
        SELECT @serialRelation = Value FROM dbo.Userconfig WHERE ConfigName = 'serialRelation'
        
        --临时表放外面创建
		CREATE TABLE #serial
		(
			serial	VARCHAR(50),
			id		INT IDENTITY(1,1)
		)
		--未启用序列号关联货位时，使用的序列号表，记录该张单据的所有序列号，按数量取序列号
		CREATE TABLE #serialTable
		(
			serial	VARCHAR(50),
			id		INT 
		)
	
		DECLARE @serialStr VARCHAR(MAX),@rowNumber INT =0
		DECLARE @serialCount INT 			        
    ----单价、总价、数量的小数位数
   -- SELECT @Price=dbo.F_RoundPrice(@Price),@Total=dbo.F_RoundTotal(@Price),@Qty=dbo.F_RoundQty(@Qty),@MSale=dbo.F_RoundPrice(@MSale),@MQty=dbo.F_RoundQty(@MQty)
        IF @BillType = 11				----销售出库单明细
            BEGIN
				DECLARE @n INT = 1
                IF @Cargo = @CargoID OR @CargoCount = 0 OR @CargoCount = 1
                    BEGIN
                        IF @CargoCount = 1
                            BEGIN
                                SELECT  @tempCargoStr = cargostr,@serialid=id
                                FROM    #tempCargo;
                                SELECT  @CargoID = c.CargoID
                                FROM    ( SELECT TOP 1
                                                    a
                                          FROM      dbo.f_split(@tempCargoStr,
                                                              'я')
                                        ) f
                                        JOIN CargoType c ON f.a = c.CargoID;
                                ------------------------------------------------------批次批号拆分处理屏蔽----------------------------------------------------------------
								-------------------------------------------------序列号处理------------------------------------------
								IF(@serialRelation=0)----未使用序列号关联货位自由项
								BEGIN
									SELECT @serialStr = STUFF((SELECT LEFT(serial,LEN(serial)-1) FROM dbo.WdSerialsDetail w 
									WHERE Serial<>'' AND  Serial IS NOT NULL AND w.ordercode = ws.ordercode AND w.mid = ws.mid
									FOR XML PATH('')),1,0,'') FROM WdSerialsDetail ws WHERE ws.ordercode = SUBSTRING(@WdBillComment,6,17) AND mid = @id
																		
									INSERT INTO #serialTable (serial, id )
							        SELECT * FROM dbo.F_SplitSerial(@serialStr,'я')
							       
									IF @CollectBill = 0
							        SELECT @rowNumber =	ISNULL(SUM(Qty),0) FROM dbo.SaleBill WHERE BillNumberId = @BillNumberId AND mid = @id
							        ELSE
							        SELECT @rowNumber =	ISNULL(SUM(Qty),0) FROM dbo.WdSaleBillTemp WHERE BillNumberId = @BillNumberId AND mid = @id
							        SELECT @serial = STUFF((SELECT s.serial+'я' FROM #serialTable s 
									--WHERE  s.id = st.id
								    FOR XML PATH('')),1,0,'') FROM #serialTable st WHERE id>@rowNumber AND id<=@rowNumber+CAST(@Qty AS int)
									
									SET @serial = ISNULL(@serial,'')
								END 
								ELSE ----使用序列号关联货位自由项批次
								BEGIN 
									IF(@CollectBill=1)
									BEGIN
										SELECT @salebillcount =COUNT(*) FROM dbo.WdSaleBillTemp WHERE BillNumberId = @BillNumberId		
									END 
									ELSE	
										SELECT @salebillcount =COUNT(*) FROM dbo.SaleBill WHERE BillNumberId = @BillNumberId											
										SELECT @serial= ISNULL(serial,'') FROM [WdSerialsDetail] WHERE sku_erpid = @skuid AND whstpt_erpid = @Cargoid AND ordercode = SUBSTRING(@WdBillComment,6,17) AND  serialrelationid IN(SELECT serialRelationId FROM dbo.WdSerialsDetail WHERE ordercode = SUBSTRING(@WdBillComment,6,17) AND mid =@id)
									--修改每行明细数量，将商品数量和序列号数量保持一致，总价=序列号数量*单价								
										SELECT @serialCount = COUNT(*) FROM dbo.f_split(@serial,'я') WHERE a<>''
									IF(@serialCount<>@Qty AND @serialCount<>0)
									BEGIN						
										SELECT @Qty = @serialCount, @Total = dbo.F_RoundTotal(@serialCount*@Price)
										SET @MQty = @Qty / @Mrate;SET @MSale = @Price * @Mrate;
									END 
								END 
								IF(@serialRelation=1 AND @serial <>'')
								BEGIN
									SET @serialA = ''
									TRUNCATE TABLE #serial
									INSERT INTO #serial
									SELECT a FROM dbo.f_split(@serial,'я') 
									SELECT @serialA = serial FROM #serial WHERE id = 2
                                    SELECT  @GoodsNumber = ISNULL(GoodsNumber,0),
                                            @ProduceDate = ISNULL(ProduceDate,''),
                                            @ValidDate = ISNULL(ValidDate,''),
                                            @CostPrice = ISNULL(CostPrice,0)
                                    FROM    gp_CruPtypeSerial
                                    WHERE   Serial = @serialA
                                            AND PtypeID = @PtypeId
                                            AND ItemID = @ItemID;
									SELECT @GoodsCostPrice=GoodsCostPrice,@batchQty = Qty  FROM dbo.GOODSSTOCKS_QTY WHERE GoodsNumber = @GoodsNumber AND PTypeID = @PtypeId AND CargoID=@CargoID AND @ProduceDate = @ProduceDate AND GoodsCostPrice = @CostPrice
								END
								ELSE
								BEGIN 
									IF(@batchNumberDeal = 0)	--自动读取最早入库的批号/批次信息			
										BEGIN
											SELECT @GoodsNumber=GoodsNumber,@ProduceDate=ProduceDate,@ValidDate=ValidDate,@GoodsCostPrice=GoodsCostPrice,@batchQty = Qty FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID) FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID AND Qty>0)
										END
									ELSE IF (@batchNumberDeal = 1) --自动读取最最大数量的批号/批次信息
										BEGIN 
									
											SELECT  @GoodsNumber = GoodsNumber ,
													@ProduceDate = ProduceDate ,
													@ValidDate = ValidDate ,
													@GoodsCostPrice = GoodsCostPrice ,
													@batchQty = Qty
											FROM    dbo.GOODSSTOCKS_QTY
											WHERE   ID = ( SELECT TOP 1 id
														   FROM   dbo.GOODSSTOCKS_QTY
														   WHERE  PTypeID = @PtypeId
																  AND CargoID = @tempCargoStr
																  AND KTypeID = @KTypeId
																  AND ItemID = @ItemID
																  ORDER BY Qty desc
														 );
										END 
								END 

								--	IF (@batchNumberDeal = 1 AND  @batchQty < @Qty)
								--	BEGIN
								--		WHILE(@batchQty<@Qty)
								--		BEGIN
								--			SELECT @ActuallyQty = @batchQty,@Total=dbo.F_RoundTotal(@Price*@ActuallyQty)
								--			IF @CollectBill = 0
								--				INSERT  INTO SaleBill
								--				(BillNumberId,/*从表头获取*/ OutFactoryDate,/*--单据日期*/  Stypeid ,/*分支机构*/ KTypeID ,/*--仓库ID*/ CargoID ,/*--货位*/
								--				PtypeId,/*--商品ID*/ entryCode,/*--条形码*/Qty ,/*--基本数量*/SalePrice ,/*--基本单价*/UnitID ,/*--基本单位*/MQty,/*--销售数量*/MSalePrice ,/*--销售单价*/
								--				MUnitID ,/*--销售单位*/MUnitRate,/*	--销售换算率*/NQty,/*--浮动数量*/NUnitID,/*--浮动单位*/UnitRate,/*--浮动换算率*/discount,/*--折扣率*/Tax,/*--税率*/
								--				TaxMoney,/*--税额*/DiscountPrice,/*--折后单价，按基本单价算折后*/MDiscountPrice,/*--折后单价，按销售单价算折后*/TaxPrice,/*--含税价，按基本单价算*/
								--				MTaxPrice,/*--含税价，按销售单价算*/saleTotal,/*--总金额*/total,/*--折后总金额*/TaxTotal,/*--价税合计*/NSalePrice,/*--原币基本单价*/CurMSalePrice,/*--原币销售单价*/
								--				NTaxMoney,/*--原币税额*/NDiscountPrice,/*--原币折后单价*/CurMDiscountPrice ,/*--原币折后单价*/NTaxPrice,/*--原币含税价*/CurMTaxPrice,/*--原币含税价*/
								--				NSaleTotal,NTotal,NTaxTotal,comment,IsCombined,ItemID,PriceSource,ETypeID,/*--业务员ID*/IsGift,/*--赠品项*/NUnitMsg,MUnitMsg,ClearQty,GoodsNumber,/*--批号*/
								--				GoodsCostPrice,/*--商品成本价*/ProduceDate,/*--生产日期*/ValidDate,/*--效期至*/mid,nid)
								--				VALUES(@BillNumberId,@BillDate,/*--单据日期*/@Stypeid,/*--分支机构*/@KTypeId,/*--仓库*/@CargoID,/*--货位*/@PtypeId,@entrycode,/*--条形码*/@ActuallyQty,/*--基本数量*/
								--					   @Price,/*--基本单价*/@UnitID,/*--基本单位*/@ActuallyQty,/*--销售数量*/@MSale,/*--销售单价*/@MUnitID,@Mrate,/*--销售换算率*/dbo.F_RoundQty(@ActuallyQty/@Nrate),--浮动数量*/
								--					   @NUnitID,/*	--浮动单位*/@Nrate,/*--浮动换算率@Nrate*/1,/*--折扣率*/0,/*--税率*/0,/*--税额*/@Price,/*--折后单价，按基本单价算*/@MSale,/*--折后单价，按销售单价算*/
								--					   @Price,/*--含税价，按基本单价算*/@MSale,/*--含税价，按销售单价算*/@Total,/*--总金额*/@Total,/*--折后总金额*/@Total,/*--含税总金额*/@Price,/*--原币基本单价*/
								--					   @MSale,/*--原币销售单价*/ 0,/*--原币税额*/@Price,/*--原币折后单价，按基本单价算折后*/@MSale,/*--原币折后单价，按销售单价算折后*/@Price,/*--原币含税价，按基本单价算*/
								--					   @MSale,/*--原币含税价，按销售单价算*/@Total,/*--原币总金额*/@Total,/*--原币折后总金额*/@Total,/*--原币含税总金额*/@Comment,@iscombined ,@ItemID ,'网店生成' ,
								--					   @ETypeId,@IsGift,'','',0,@GoodsNumber,@GoodsCostPrice,@ProduceDate,@ValidDate,@id ,0);
								--			ELSE/*汇总生成单据插入临时表*/
								--				INSERT  INTO WdSaleBillTemp 
								--				(BillNumberId,/*从表头获取*/ OutFactoryDate,/*--单据日期*/  Stypeid ,/*分支机构*/ KTypeID ,/*--仓库ID*/ CargoID ,/*--货位*/
								--				PtypeId,/*--商品ID*/ entryCode,/*--条形码*/Qty ,/*--基本数量*/SalePrice ,/*--基本单价*/UnitID ,/*--基本单位*/MQty,/*--销售数量*/MSalePrice ,/*--销售单价*/
								--				MUnitID ,/*--销售单位*/MUnitRate,/*	--销售换算率*/NQty,/*--浮动数量*/NUnitID,/*--浮动单位*/UnitRate,/*--浮动换算率*/discount,/*--折扣率*/Tax,/*--税率*/
								--				TaxMoney,/*--税额*/DiscountPrice,/*--折后单价，按基本单价算折后*/MDiscountPrice,/*--折后单价，按销售单价算折后*/TaxPrice,/*--含税价，按基本单价算*/
								--				MTaxPrice,/*--含税价，按销售单价算*/saleTotal,/*--总金额*/total,/*--折后总金额*/TaxTotal,/*--价税合计*/NSalePrice,/*--原币基本单价*/CurMSalePrice,/*--原币销售单价*/
								--				NTaxMoney,/*--原币税额*/NDiscountPrice,/*--原币折后单价*/CurMDiscountPrice ,/*--原币折后单价*/NTaxPrice,/*--原币含税价*/CurMTaxPrice,/*--原币含税价*/
								--				NSaleTotal,NTotal,NTaxTotal,comment,IsCombined,ItemID,PriceSource,ETypeID,/*--业务员ID*/IsGift,/*--赠品项*/NUnitMsg,MUnitMsg,ClearQty,GoodsNumber,/*--批号*/
								--				GoodsCostPrice,/*--商品成本价*/ProduceDate,/*--生产日期*/ValidDate,/*--效期至*/mid,nid)
								--				VALUES(@BillNumberId,@BillDate,/*--单据日期*/@Stypeid,/*--分支机构*/@KTypeId,/*--仓库*/@CargoID,/*--货位*/@PtypeId,@entrycode,/*--条形码*/@ActuallyQty,/*--基本数量*/
								--					   @Price,/*--基本单价*/@UnitID,/*--基本单位*/@ActuallyQty,/*--销售数量*/@MSale,/*--销售单价*/@MUnitID,@Mrate,/*--销售换算率*/dbo.F_RoundQty(@ActuallyQty/@Nrate),--浮动数量*/
								--					   @NUnitID,/*	--浮动单位*/@Nrate,/*--浮动换算率@Nrate*/1,/*--折扣率*/0,/*--税率*/0,/*--税额*/@Price,/*--折后单价，按基本单价算*/@MSale,/*--折后单价，按销售单价算*/
								--					   @Price,/*--含税价，按基本单价算*/@MSale,/*--含税价，按销售单价算*/@Total,/*--总金额*/@Total,/*--折后总金额*/@Total,/*--含税总金额*/@Price,/*--原币基本单价*/
								--					   @MSale,/*--原币销售单价*/ 0,/*--原币税额*/@Price,/*--原币折后单价，按基本单价算折后*/@MSale,/*--原币折后单价，按销售单价算折后*/@Price,/*--原币含税价，按基本单价算*/
								--					   @MSale,/*--原币含税价，按销售单价算*/@Total,/*--原币总金额*/@Total,/*--原币折后总金额*/@Total,/*--原币含税总金额*/@Comment,@iscombined ,@ItemID ,'网店生成' ,
								--					   @ETypeId,@IsGift,'','',0,@GoodsNumber,@GoodsCostPrice,@ProduceDate,@ValidDate,@id ,0);
								--			SELECT @n=@n+1,@Qty = @Qty-@ActuallyQty,@AllTotal = @AllTotal-@Total
								--			IF EXISTS (SELECT 1 FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID)+@n FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID))
								--			BEGIN 
								--			SELECT @GoodsNumber=GoodsNumber,@ProduceDate=ProduceDate,@ValidDate=ValidDate,@GoodsCostPrice=GoodsCostPrice,@batchQty = Qty FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID)+@n FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID)
								--			END 
								--			ELSE
								--			BEGIN
								--				SELECT @GoodsNumber = '',--批号
								--					   @ProduceDate ='',--生产日期
								--					   @ValidDate ='',--效期至
								--					   @GoodsCostPrice =0--商品成本价
								--				BREAK
								--			END 
								--		END 
								--		SELECT @Total=@AllTotal
								--	END 
                              -- END  
                               ------------------------------------------------------批次批号拆分处理----------------------------------------------------------------
                            END;
						IF @CollectBill = 0           
							BEGIN
								INSERT  INTO SaleBill
										( BillNumberId ,	--从表头获取
										  OutFactoryDate ,	--单据日期  
										  Stypeid ,			--分支机构
										  KTypeID ,			--仓库ID
										  CargoID ,			--货位
								  --序列号Serial
								  --GoodsOrder,--批次
								  --成本单价costprice
										  PtypeId ,			--商品ID
										  entryCode ,		--条形码
										  Qty ,				--基本数量
										  SalePrice ,		--基本单价
										  UnitID ,		--基本单位
										  MQty ,             --销售数量
										  MSalePrice ,		--销售单价
										  MUnitID ,		--销售单位
										  MUnitRate ,		--销售换算率
										  NQty ,			--浮动数量
										  NUnitID ,		--浮动单位
										  UnitRate ,		--浮动换算率
										  discount ,			--折扣率
										  Tax ,			--税率
										  TaxMoney ,			--税额
										  DiscountPrice ,	--折后单价，按基本单价算折后
										  MDiscountPrice ,	--折后单价，按销售单价算折后
										  TaxPrice ,			--含税价，按基本单价算
										  MTaxPrice ,		--含税价，按销售单价算
										  SaleTotal ,		--总金额
										  total ,			--折后总金额
										  TaxTotal ,			--价税合计
										  NSalePrice ,       --原币基本单价
										  CurMSalePrice ,	--原币销售单价
										  NTaxMoney ,		--原币税额
										  NDiscountPrice ,	--原币折后单价
										  CurMDiscountPrice ,--原币折后单价
										  NTaxPrice ,        --原币含税价
										  CurMTaxPrice ,		--原币含税价
										  NSaleTotal ,
										  NTotal ,
										  NTaxTotal ,
										  comment ,
										  IsCombined ,
										  ItemID ,
										  PriceSource ,
										  ETypeID ,        --业务员ID
										  IsGift ,          --赠品项
										  NUnitMsg ,
										  MUnitMsg ,
										  ClearQty ,
										  GoodsNumber,--批号
										  GoodsCostPrice,--商品成本价
										  ProduceDate,--生产日期
										  ValidDate,--效期至
										  Serial,
										  mid ,
										  nid 
										)
								VALUES  ( @BillNumberId ,
										  @BillDate ,        --单据日期
										  @Stypeid ,         --分支机构
										  @KTypeId ,			--仓库
										  @CargoID ,			--货位
										  @PtypeId ,			--商品
										  @entrycode ,		--条形码
										  @Qty ,             --基本数量
										  @Price ,           --基本单价
										  @UnitID ,			--基本单位
										  ISNULL(dbo.F_RoundQty(@MQty),0) ,			--销售数量
										  @MSale ,           --销售单价
										  @MUnitID ,			--销售单位
										  @Mrate ,			--销售换算率
										  ISNULL(dbo.F_RoundQty(@Qty/@Nrate),0),--浮动数量
										  ISNULL(@NUnitID,0),			--浮动单位
										  ISNULL(@Nrate,0),			--浮动换算率@Nrate
										  1 ,				--折扣率
										  0 ,				--税率
										  0 ,				--税额
										  @Price ,			--折后单价，按基本单价算
										  @MSale ,			--折后单价，按销售单价算
										  @Price ,			--含税价，按基本单价算
										  @MSale ,			--含税价，按销售单价算
										  @Total ,			--总金额
										  @Total ,			--折后总金额
										  @Total ,			--含税总金额
										  @Price ,			--原币基本单价
										  @MSale ,			--原币销售单价
										  0 ,				--原币税额
										  @Price ,			--原币折后单价，按基本单价算折后
										  @MSale ,			--原币折后单价，按销售单价算折后
										  @Price ,			--原币含税价，按基本单价算
										  @MSale ,			--原币含税价，按销售单价算
										  @Total ,			--原币总金额
										  @Total ,			--原币折后总金额
										  @Total ,			--原币含税总金额
										  @Comment ,
										  @iscombined ,
										  @ItemID ,
										  @PriceSource ,
										  @ETypeId ,
										  @IsGift ,
										  '' ,
										  '' ,
										  0 ,
										  @GoodsNumber,
										  @GoodsCostPrice,
										  @ProduceDate,
										  @ValidDate,   
										  @serial,                               
										  @id ,
										  0
										);
									IF(@serialRelation=1)
									BEGIN 
										EXEC Gp_MakeSerialDetail @BillDate,
											@BillType, @BillNumberId, @PtypeId,
											@Qty, @KTypeId, @ETypeId, @Total,
											@Price, @FreightFee, @Cargo, @ItemID,
											@WdBillComment, @EshopId, @feeatypeid, @Flag,
											@IsGift, @Stypeid, @CargoID, @Itemqty,
											@id, @entrycode, @UnitID, @MQty,
											@MSale, @MUnitID, @Mrate, @NUnitID,
											@Nrate, @iscombined, @serial,
											@GoodsNumber, @ProduceDate, @ValidDate,
											@GoodsCostPrice, @batchNumberDeal,
											@batchQty,@CollectBill,@PriceSource; 		
									END 				
								END
					        ELSE
								BEGIN
									 INSERT  INTO WdSaleBillTemp
									( BillNumberId ,	--从表头获取
									  OutFactoryDate ,	--单据日期  
									  Stypeid ,			--分支机构
									  KTypeID ,			--仓库ID
									  CargoID ,			--货位
						  --序列号Serial
						  --批次GoodsOrder
						  --成本单价costprice
									  PtypeId ,			--商品ID
									  entryCode ,		--条形码
									  Qty ,				--基本数量
									  SalePrice ,		--基本单价
									  UnitID ,		--基本单位
									  MQty,             --销售数量
									  MSalePrice ,		--销售单价
									  MUnitID ,		--销售单位
									  MUnitRate ,		--销售换算率
									  NQty ,			--浮动数量
									  NUnitID ,		--浮动单位
									  UnitRate ,		--浮动换算率
									  discount ,			--折扣率
									  Tax ,			--税率
									  TaxMoney ,			--税额
									  DiscountPrice ,	--折后单价，按基本单价算折后
									  MDiscountPrice ,	--折后单价，按销售单价算折后
									  TaxPrice ,			--含税价，按基本单价算
									  MTaxPrice ,		--含税价，按销售单价算
									  SaleTotal ,		--总金额
									  total ,			--折后总金额
									  TaxTotal ,			--价税合计
									  NSalePrice ,       --原币基本单价
									  CurMSalePrice ,	--原币销售单价
									  NTaxMoney ,		--原币税额
									  NDiscountPrice ,	--原币折后单价
									  CurMDiscountPrice ,--原币折后单价
									  NTaxPrice ,        --原币含税价
									  CurMTaxPrice ,		--原币含税价
									  NSaleTotal ,
									  NTotal ,
									  NTaxTotal ,
									  comment ,
									  IsCombined ,
									  ItemID ,
									  PriceSource ,
									  ETypeID ,        --业务员ID
									  IsGift ,          --赠品项
									  NUnitMsg ,
									  MUnitMsg ,
									  ClearQty ,
									  GoodsNumber,--批号
									  GoodsCostPrice,--商品成本价
									  ProduceDate,--生产日期
									  ValidDate,--效期至
									  Serial,
									  mid ,
									  nid 
									)
							VALUES  ( @BillNumberId ,
									  @BillDate ,        --单据日期
									  @Stypeid ,         --分支机构
									  @KTypeId ,			--仓库
									  @CargoID ,			--货位
									  @PtypeId ,			--商品
									  @entrycode ,		--条形码
									  @Qty ,             --基本数量
									  @Price ,           --基本单价
									  @UnitID ,			--基本单位
									  ISNULL(dbo.F_RoundQty(@MQty),0) ,			--销售数量
									  @MSale ,           --销售单价
									  @MUnitID ,			--销售单位
									  @Mrate ,			--销售换算率     
									  ISNULL(dbo.F_RoundQty(@Qty/@Nrate),0),--浮动数量
									  ISNULL(@NUnitID,0),			--浮动单位
									  ISNULL(@Nrate,0),			--浮动换算率@Nrate
									  1 ,				--折扣率
									  0 ,				--税率
									  0 ,				--税额
									  @Price ,			--折后单价，按基本单价算
									  @MSale ,			--折后单价，按销售单价算
									  @Price ,			--含税价，按基本单价算
									  @MSale ,			--含税价，按销售单价算
									  @Total ,			--总金额
									  @Total ,			--折后总金额
									  @Total ,			--含税总金额
									  @Price ,			--原币基本单价
									  @MSale ,			--原币销售单价
									  0 ,				--原币税额
									  @Price ,			--原币折后单价，按基本单价算折后
									  @MSale ,			--原币折后单价，按销售单价算折后
									  @Price ,			--原币含税价，按基本单价算
									  @MSale ,			--原币含税价，按销售单价算
									  @Total ,			--原币总金额
									  @Total ,			--原币折后总金额
									  @Total ,			--原币含税总金额
									  @WdBillComment ,
									  @iscombined ,
									  @ItemID ,
									  @PriceSource ,
									  @ETypeId ,
									  @IsGift ,
									  '' ,
									  '' ,
									  0 ,
									  @GoodsNumber,
									  @GoodsCostPrice,
									  @ProduceDate,
									  @ValidDate,
									  @serial,           
									  @id ,
									  0
									);
								IF(@serialRelation=1)
								BEGIN 
								   EXEC Gp_MakeSerialDetail @BillDate,
                                        @BillType, @BillNumberId, @PtypeId,
                                        @Qty, @KTypeId, @ETypeId, @Total,
                                        @Price, @FreightFee, @Cargo, @ItemID,
                                        @WdBillComment, @EshopId, @feeatypeid, @Flag,
                                        @IsGift, @Stypeid, @CargoID, @Itemqty,
                                        @id, @entrycode, @UnitID, @MQty,
                                        @MSale, @MUnitID, @Mrate, @NUnitID,
                                        @Nrate, @iscombined, @serial,
                                        @GoodsNumber, @ProduceDate, @ValidDate,
                                        @GoodsCostPrice, @batchNumberDeal,
                                        @batchQty,@CollectBill,@PriceSource; 	
                                END 			
							END 
                    END;
					
                ELSE         ---遍历每个货位，分拆他们
                    BEGIN
                        DECLARE @index INT= 1,@tempTotal NUMERIC(24, 10); 
                        WHILE @index <= @CargoCount
                            BEGIN
                                SELECT  @tempCargoStr = cargostr,@serialid=id FROM #tempCargo WHERE id = @index;
                                SELECT  @tempCargoIDQty = CAST(CargoQty AS NUMERIC(24,10)) FROM #tempCargoQty WHERE   id = @index;
                                SET @MQty = @tempCargoIDQty / @Mrate;
                                SELECT @tempTotal = dbo.F_RoundTotal(@Total * @tempCargoIDQty/ @Qty); 
                                
								IF(@serialRelation=0)----未使用序列号关联货位自由项
								BEGIN
									SELECT @serialStr = STUFF((SELECT LEFT(serial,LEN(serial)-1) FROM dbo.WdSerialsDetail w 
									WHERE Serial<>'' AND  Serial IS NOT NULL AND w.ordercode = ws.ordercode AND w.mid = ws.mid
									FOR XML PATH('')),1,0,'') FROM WdSerialsDetail ws WHERE ws.ordercode = SUBSTRING(@WdBillComment,6,17) AND mid = @id

									INSERT INTO #serialTable (serial, id )
							        SELECT * FROM dbo.F_SplitSerial(@serialStr,'я')
							       
							        IF @CollectBill = 0
							        SELECT @rowNumber =ISNULL(SUM(Qty),0) FROM dbo.SaleBill WHERE BillNumberId = @BillNumberId AND mid = @id
							        ELSE
							        SELECT @rowNumber =ISNULL(SUM(Qty),0) FROM dbo.WdSaleBillTemp WHERE BillNumberId = @BillNumberId AND mid = @id
							        
							        SELECT @serial = STUFF((SELECT s.serial+'я' FROM #serialTable s 
									--WHERE  s.id = st.id 
									FOR XML PATH('')),1,0,'') FROM #serialTable st WHERE id>@rowNumber AND id<=@rowNumber+@tempCargoIDQty
								END 
								ELSE ----使用序列号关联货位自由项
								BEGIN 
									IF(@CollectBill=1)
									BEGIN
										SELECT @salebillcount =COUNT(*) FROM dbo.WdSaleBillTemp WHERE BillNumberId = @BillNumberId		
									END 
									ELSE	
										SELECT @salebillcount =COUNT(*) FROM dbo.SaleBill WHERE BillNumberId = @BillNumberId	
																			
									SELECT @serial= serial FROM [WdSerialsDetail] WHERE sku_erpid = @skuid AND whstpt_erpid = @tempCargoStr AND ordercode = SUBSTRING(@WdBillComment,6,17) AND serialrelationid IN(SELECT serialRelationId FROM dbo.WdSerialsDetail WHERE ordercode = SUBSTRING(@WdBillComment,6,17) AND mid =@id)
									--修改每行明细数量，将商品数量和序列号数量保持一致，总价=序列号数量*单价								
									SELECT @serialCount = COUNT(*) FROM dbo.f_split(@serial,'я') WHERE a<>''
									
									IF(@serialCount<>@Qty AND @serialCount<>0)
									BEGIN						
										SELECT @tempCargoIDQty = @serialCount, @tempTotal = dbo.F_RoundTotal(@serialCount*@Price)
										SET @MQty = @tempCargoIDQty / @Mrate;SET @MSale = @Price * @Mrate;
									END 
								END 
                                
                                IF(@serialRelation=1 AND @serial <>'')--有序列号并且序列号关联了批次批号
								BEGIN
									SET @serialA = ''
									TRUNCATE TABLE #serial
									INSERT INTO #serial
									SELECT a FROM dbo.f_split(@serial,'я') 
									SELECT @serialA = serial FROM #serial WHERE id = 2
									SELECT  @GoodsNumber = ISNULL(GoodsNumber,0),
											@ProduceDate = ISNULL(ProduceDate,''),
											@ValidDate = ISNULL(ValidDate,''),
											@CostPrice = ISNULL(CostPrice,0)
									FROM    gp_CruPtypeSerial
									WHERE   Serial = @serialA
											AND PtypeID = @PtypeId
											AND ItemID = @ItemID;
									SELECT @GoodsCostPrice=GoodsCostPrice,@batchQty = Qty  FROM dbo.GOODSSTOCKS_QTY WHERE GoodsNumber = @GoodsNumber AND PTypeID = @PtypeId AND CargoID=@tempCargoStr AND @ProduceDate = @ProduceDate AND GoodsCostPrice = @CostPrice
								END
                                ELSE
                                BEGIN
									IF(@batchNumberDeal = 0)	--自动读取最早入库的批号/批次信息			
										BEGIN
											SELECT @GoodsNumber=GoodsNumber,@ProduceDate=ProduceDate,@ValidDate=ValidDate,@GoodsCostPrice=GoodsCostPrice,@batchQty = Qty FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID) FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID AND Qty>0)
										END
									ELSE IF (@batchNumberDeal = 1) --自动读取最最大数量的批号/批次信息
										BEGIN 
											 SELECT  @GoodsNumber = GoodsNumber ,
													@ProduceDate = ProduceDate ,
													@ValidDate = ValidDate ,
													@GoodsCostPrice = GoodsCostPrice ,
													@batchQty = Qty
											FROM    dbo.GOODSSTOCKS_QTY
											WHERE   ID = ( SELECT TOP 1 id
														   FROM   dbo.GOODSSTOCKS_QTY
														   WHERE  PTypeID = @PtypeId
																  AND CargoID = @tempCargoStr
																  AND KTypeID = @KTypeId
																  AND ItemID = @ItemID
																  ORDER BY Qty desc
														 );
										END 
								END 
							
        --                        ------------------批次批号拆分处理暂时屏蔽--------------------------------
        --                        IF(@batchNumberDeal <> 2)	--批次号处理			
								--BEGIN
								--	SELECT @GoodsNumber=GoodsNumber,@ProduceDate=ProduceDate,@ValidDate=ValidDate,@GoodsCostPrice=GoodsCostPrice,@batchQty = Qty FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID) FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID)
								--	IF (@batchNumberDeal = 1 AND  @batchQty < @Qty)
								--	BEGIN
								--		SELECT @n = 1
								--		WHILE(@batchQty<@tempCargoIDQty)
								--		BEGIN
								--			SELECT @ActuallyQty = @batchQty,@Total=dbo.F_RoundTotal(@Price*@ActuallyQty)
								--			IF @CollectBill = 0
								--				INSERT  INTO SaleBill
								--				(BillNumberId,/*从表头获取*/ OutFactoryDate,/*--单据日期*/  Stypeid ,/*分支机构*/ KTypeID ,/*--仓库ID*/ CargoID ,/*--货位*/
								--				PtypeId,/*--商品ID*/ entryCode,/*--条形码*/Qty ,/*--基本数量*/SalePrice ,/*--基本单价*/UnitID ,/*--基本单位*/MQty,/*--销售数量*/MSalePrice ,/*--销售单价*/
								--				MUnitID ,/*--销售单位*/MUnitRate,/*	--销售换算率*/NQty,/*--浮动数量*/NUnitID,/*--浮动单位*/UnitRate,/*--浮动换算率*/discount,/*--折扣率*/Tax,/*--税率*/
								--				TaxMoney,/*--税额*/DiscountPrice,/*--折后单价，按基本单价算折后*/MDiscountPrice,/*--折后单价，按销售单价算折后*/TaxPrice,/*--含税价，按基本单价算*/
								--				MTaxPrice,/*--含税价，按销售单价算*/saleTotal,/*--总金额*/total,/*--折后总金额*/TaxTotal,/*--价税合计*/NSalePrice,/*--原币基本单价*/CurMSalePrice,/*--原币销售单价*/
								--				NTaxMoney,/*--原币税额*/NDiscountPrice,/*--原币折后单价*/CurMDiscountPrice ,/*--原币折后单价*/NTaxPrice,/*--原币含税价*/CurMTaxPrice,/*--原币含税价*/
								--				NSaleTotal,NTotal,NTaxTotal,comment,IsCombined,ItemID,PriceSource,ETypeID,/*--业务员ID*/IsGift,/*--赠品项*/NUnitMsg,MUnitMsg,ClearQty,GoodsNumber,/*--批号*/
								--				GoodsCostPrice,/*--商品成本价*/ProduceDate,/*--生产日期*/ValidDate,/*--效期至*/mid,nid)
								--				VALUES(@BillNumberId,@BillDate,/*--单据日期*/@Stypeid,/*--分支机构*/@KTypeId,/*--仓库*/@tempCargoStr,/*--货位*/@PtypeId,@entrycode,/*--条形码*/@ActuallyQty,/*--基本数量*/
								--					   @Price,/*--基本单价*/@UnitID,/*--基本单位*/@ActuallyQty,/*--销售数量*/@MSale,/*--销售单价*/@MUnitID,@Mrate,/*--销售换算率*/dbo.F_RoundQty(@ActuallyQty/@Nrate),--浮动数量*/
								--					   @NUnitID,/*	--浮动单位*/@Nrate,/*--浮动换算率@Nrate*/1,/*--折扣率*/0,/*--税率*/0,/*--税额*/@Price,/*--折后单价，按基本单价算*/@MSale,/*--折后单价，按销售单价算*/
								--					   @Price,/*--含税价，按基本单价算*/@MSale,/*--含税价，按销售单价算*/@Total,/*--总金额*/@Total,/*--折后总金额*/@Total,/*--含税总金额*/@Price,/*--原币基本单价*/
								--					   @MSale,/*--原币销售单价*/ 0,/*--原币税额*/@Price,/*--原币折后单价，按基本单价算折后*/@MSale,/*--原币折后单价，按销售单价算折后*/@Price,/*--原币含税价，按基本单价算*/
								--					   @MSale,/*--原币含税价，按销售单价算*/@Total,/*--原币总金额*/@Total,/*--原币折后总金额*/@Total,/*--原币含税总金额*/@Comment,@iscombined ,@ItemID ,'网店生成' ,
								--					   @ETypeId,@IsGift,'','',0,@GoodsNumber,@GoodsCostPrice,@ProduceDate,@ValidDate,@id ,0);
								--			ELSE/*汇总生成单据插入临时表*/
								--				INSERT  INTO WdSaleBillTemp 
								--				(BillNumberId,/*从表头获取*/ OutFactoryDate,/*--单据日期*/  Stypeid ,/*分支机构*/ KTypeID ,/*--仓库ID*/ CargoID ,/*--货位*/
								--				PtypeId,/*--商品ID*/ entryCode,/*--条形码*/Qty ,/*--基本数量*/SalePrice ,/*--基本单价*/UnitID ,/*--基本单位*/MQty,/*--销售数量*/MSalePrice ,/*--销售单价*/
								--				MUnitID ,/*--销售单位*/MUnitRate,/*	--销售换算率*/NQty,/*--浮动数量*/NUnitID,/*--浮动单位*/UnitRate,/*--浮动换算率*/discount,/*--折扣率*/Tax,/*--税率*/
								--				TaxMoney,/*--税额*/DiscountPrice,/*--折后单价，按基本单价算折后*/MDiscountPrice,/*--折后单价，按销售单价算折后*/TaxPrice,/*--含税价，按基本单价算*/
								--				MTaxPrice,/*--含税价，按销售单价算*/saleTotal,/*--总金额*/total,/*--折后总金额*/TaxTotal,/*--价税合计*/NSalePrice,/*--原币基本单价*/CurMSalePrice,/*--原币销售单价*/
								--				NTaxMoney,/*--原币税额*/NDiscountPrice,/*--原币折后单价*/CurMDiscountPrice ,/*--原币折后单价*/NTaxPrice,/*--原币含税价*/CurMTaxPrice,/*--原币含税价*/
								--				NSaleTotal,NTotal,NTaxTotal,comment,IsCombined,ItemID,PriceSource,ETypeID,/*--业务员ID*/IsGift,/*--赠品项*/NUnitMsg,MUnitMsg,ClearQty,GoodsNumber,/*--批号*/
								--				GoodsCostPrice,/*--商品成本价*/ProduceDate,/*--生产日期*/ValidDate,/*--效期至*/mid,nid)
								--				VALUES(@BillNumberId,@BillDate,/*--单据日期*/@Stypeid,/*--分支机构*/@KTypeId,/*--仓库*/@CargoID,/*--货位*/@PtypeId,@entrycode,/*--条形码*/@ActuallyQty,/*--基本数量*/
								--					   @Price,/*--基本单价*/@UnitID,/*--基本单位*/@ActuallyQty,/*--销售数量*/@MSale,/*--销售单价*/@MUnitID,@Mrate,/*--销售换算率*/dbo.F_RoundQty(@ActuallyQty/@Nrate),--浮动数量*/
								--					   @NUnitID,/*	--浮动单位*/@Nrate,/*--浮动换算率@Nrate*/1,/*--折扣率*/0,/*--税率*/0,/*--税额*/@Price,/*--折后单价，按基本单价算*/@MSale,/*--折后单价，按销售单价算*/
								--					   @Price,/*--含税价，按基本单价算*/@MSale,/*--含税价，按销售单价算*/@Total,/*--总金额*/@Total,/*--折后总金额*/@Total,/*--含税总金额*/@Price,/*--原币基本单价*/
								--					   @MSale,/*--原币销售单价*/ 0,/*--原币税额*/@Price,/*--原币折后单价，按基本单价算折后*/@MSale,/*--原币折后单价，按销售单价算折后*/@Price,/*--原币含税价，按基本单价算*/
								--					   @MSale,/*--原币含税价，按销售单价算*/@Total,/*--原币总金额*/@Total,/*--原币折后总金额*/@Total,/*--原币含税总金额*/@Comment,@iscombined ,@ItemID ,'网店生成' ,
								--					   @ETypeId,@IsGift,'','',0,@GoodsNumber,@GoodsCostPrice,@ProduceDate,@ValidDate,@id ,0);
								--			SELECT @n=@n+1,@Qty = @Qty-@ActuallyQty,@AllTotal = @AllTotal-@Total
								--			IF EXISTS (SELECT 1 FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID)+@n FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID))
								--			BEGIN 
								--			SELECT @GoodsNumber=GoodsNumber,@ProduceDate=ProduceDate,@ValidDate=ValidDate,@GoodsCostPrice=GoodsCostPrice,@batchQty = Qty FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID)+@n FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID)
								--			END 
								--			ELSE
								--			BEGIN
								--				SELECT @GoodsNumber = '',--批号
								--					   @ProduceDate ='',--生产日期
								--					   @ValidDate ='',--效期至
								--					   @GoodsCostPrice =0--商品成本价
								--				BREAK
								--			END 
								--		END 
								--		SELECT @Total=@AllTotal
								--	END 
        --                        END  
        --                       ----------------------------------------------批次批号拆分处理结束----------------------------------------------------------------
                                IF @CollectBill = 0
                                BEGIN 
                                INSERT  INTO SaleBill
                                        ( BillNumberId ,	--从表头获取
                                          OutFactoryDate ,	--单据日期  
                                          Stypeid ,			--分支机构
                                          KTypeID ,			--仓库ID
                                          CargoID ,			--货位
							  --序列号Serial
							  --批次GoodsOrder
							  --成本单价costprice
                                          PtypeId ,			--商品ID
                                          entryCode ,		--条形码
                                          Qty ,				--基本数量
                                          SalePrice ,		--基本单价
                                          UnitID ,		--基本单位
                                          MQty ,             --销售数量
                                          MSalePrice ,		--销售单价
                                          MUnitID ,		--销售单位
                                          MUnitRate ,		--销售换算率
                                          NQty ,			--浮动数量
                                          NUnitID ,		--浮动单位
                                          UnitRate ,		--浮动换算率
                                          discount ,			--折扣率
                                          Tax ,			--税率
                                          TaxMoney ,			--税额
                                          DiscountPrice ,	--折后单价，按基本单价算折后
                                          MDiscountPrice ,	--折后单价，按销售单价算折后
                                          TaxPrice ,			--含税价，按基本单价算
                                          MTaxPrice ,		--含税价，按销售单价算
                                          SaleTotal ,		--总金额
                                          total ,			--折后总金额
                                          TaxTotal ,			--价税合计
                                          NSalePrice ,       --原币基本单价
                                          CurMSalePrice ,	--原币销售单价
                                          NTaxMoney ,		--原币税额
                                          NDiscountPrice ,	--原币折后单价
                                          CurMDiscountPrice ,--原币折后单价
                                          NTaxPrice ,        --原币含税价
                                          CurMTaxPrice ,		--原币含税价
                                          NSaleTotal ,
                                          NTotal ,
                                          NTaxTotal ,
                                          comment ,
                                          IsCombined ,
                                          ItemID ,
                                          PriceSource ,
                                          ETypeID ,     --业务员ID
                                          IsGift ,       --赠品项
                                          NUnitMsg ,
                                          MUnitMsg ,
                                          ClearQty ,
                                          GoodsNumber,--批号
										  GoodsCostPrice,--商品成本价
										  ProduceDate,--生产日期
										  ValidDate,--效期至
										  Serial,
                                          mid ,
                                          nid
							            )
                                VALUES  ( @BillNumberId ,
                                          @BillDate ,        --单据日期
                                          @Stypeid ,         --分支机构
                                          @KTypeId ,			--仓库
                                          CAST(@tempCargoStr AS INT) ,			--货位
                                          @PtypeId ,			--商品
                                          @entrycode ,		--条形码
                                          @tempCargoIDQty ,  --基本数量
                                          @Price ,           --基本单价
                                          @UnitID ,			--基本单位
                                          ISNULL(dbo.F_RoundQty(@MQty),0) ,			--销售数量
                                          @MSale ,           --销售单价
                                          @MUnitID ,			--销售单位
                                          @Mrate ,			--销售换算率
                                          ISNULL(dbo.F_RoundQty(@tempCargoIDQty/@Nrate),0) ,				--浮动数量
                                          ISNULL(@NUnitID,0),			--浮动单位
										  ISNULL(@Nrate,0),			--浮动换算率@Nrate
                                          1 ,				--折扣率
                                          0 ,				--税率
                                          0 ,				--税额
                                          @Price ,			--折后单价，按基本单价算
                                          @MSale ,			--折后单价，按销售单价算
                                          @Price ,			--含税价，按基本单价算
                                          @MSale ,			--含税价，按销售单价算
                                          @tempTotal ,			--总金额
                                          @tempTotal ,			--折后总金额
                                          @tempTotal ,			--含税总金额
                                          @Price ,			--原币基本单价
                                          @MSale ,			--原币销售单价
                                          0 ,				--原币税额
                                          @Price ,			--原币折后单价，按基本单价算折后
                                          @MSale ,			--原币折后单价，按销售单价算折后
                                          @Price ,			--原币含税价，按基本单价算
                                          @MSale ,			--原币含税价，按销售单价算
                                          @tempTotal ,			--原币总金额
                                          @tempTotal ,			--原币折后总金额
                                          @tempTotal ,			--原币含税总金额
                                          @Comment ,
                                          @iscombined ,
                                          @ItemID ,
                                          @PriceSource ,
                                          @ETypeId ,
                                          @IsGift ,
                                          '' ,
                                          '' ,
                                          0 ,
										  @GoodsNumber,
										  @GoodsCostPrice,
										  @ProduceDate,
										  @ValidDate,   
										  @serial,     
                                          @id ,
                                          @index - 1
					                    );
					                END 
					                ELSE
					                BEGIN
										INSERT  INTO WdSaleBillTemp
                                        ( BillNumberId ,	--从表头获取
                                          OutFactoryDate ,	--单据日期  
                                          Stypeid ,			--分支机构
                                          KTypeID ,			--仓库ID
                                          CargoID ,			--货位
							  --序列号Serial
							  --批次GoodsOrder
							  --成本单价costprice
                                          PtypeId ,			--商品ID
                                          entryCode ,		--条形码
                                          Qty ,				--基本数量
                                          SalePrice ,		--基本单价
                                          UnitID ,		--基本单位
                                          MQty ,             --销售数量
                                          MSalePrice ,		--销售单价
                                          MUnitID ,		--销售单位
                                          MUnitRate ,		--销售换算率
                                          NQty ,			--浮动数量
                                          NUnitID ,		--浮动单位
                                          UnitRate ,		--浮动换算率
                                          discount ,			--折扣率
                                          Tax ,			--税率
                                          TaxMoney ,			--税额
                                          DiscountPrice ,	--折后单价，按基本单价算折后
                                          MDiscountPrice ,	--折后单价，按销售单价算折后
                                          TaxPrice ,			--含税价，按基本单价算
                                          MTaxPrice ,		--含税价，按销售单价算
                                          SaleTotal ,		--总金额
                                          total ,			--折后总金额
                                          TaxTotal ,			--价税合计
                                          NSalePrice ,       --原币基本单价
                                          CurMSalePrice ,	--原币销售单价
                                          NTaxMoney ,		--原币税额
                                          NDiscountPrice ,	--原币折后单价
                                          CurMDiscountPrice ,--原币折后单价
                                          NTaxPrice ,        --原币含税价
                                          CurMTaxPrice ,		--原币含税价
                                          NSaleTotal ,
                                          NTotal ,
                                          NTaxTotal ,
                                          comment ,
                                          IsCombined ,
                                          ItemID ,
                                          PriceSource ,
                                          ETypeID ,     --业务员ID
                                          IsGift ,       --赠品项
                                          NUnitMsg ,
                                          MUnitMsg ,
                                          ClearQty ,
                                          GoodsNumber,--批号
										  GoodsCostPrice,--商品成本价
										  ProduceDate,--生产日期
										  ValidDate,--效期至
										  Serial,
                                          mid ,
                                          nid
							            )
                                VALUES  ( @BillNumberId ,
                                          @BillDate ,        --单据日期
                                          @Stypeid ,         --分支机构
                                          @KTypeId ,			--仓库
                                          CAST(@tempCargoStr AS INT) ,			--货位
                                          @PtypeId ,			--商品
                                          @entrycode ,		--条形码
                                          @tempCargoIDQty ,  --基本数量
                                          @Price ,           --基本单价
                                          @UnitID ,			--基本单位
                                          ISNULL(dbo.F_RoundQty(@MQty),0) ,			--销售数量
                                          @MSale ,           --销售单价
                                          @MUnitID ,			--销售单位
                                          @Mrate ,			--销售换算率
                                          ISNULL(dbo.F_RoundQty(@tempCargoIDQty/@Nrate),0) ,				--浮动数量
                                          ISNULL(@NUnitID,0),			--浮动单位
										  ISNULL(@Nrate,0),			--浮动换算率@Nrate
                                          1 ,				--折扣率
                                          0 ,				--税率
                                          0 ,				--税额
                                          @Price ,			--折后单价，按基本单价算
                                          @MSale ,			--折后单价，按销售单价算
                                          @Price ,			--含税价，按基本单价算
                                          @MSale ,			--含税价，按销售单价算
                                          @tempTotal ,			--总金额
                                          @tempTotal ,			--折后总金额
                                          @tempTotal ,			--含税总金额
                                          @Price ,			--原币基本单价
                                          @MSale ,			--原币销售单价
                                          0 ,				--原币税额
                                          @Price ,			--原币折后单价，按基本单价算折后
                                          @MSale ,			--原币折后单价，按销售单价算折后
                                          @Price ,			--原币含税价，按基本单价算
                                          @MSale ,			--原币含税价，按销售单价算
                                          @tempTotal ,			--原币总金额
                                          @tempTotal ,			--原币折后总金额
                                          @tempTotal ,			--原币含税总金额
                                          @Comment ,
                                          @iscombined ,
                                          @ItemID ,
                                          @PriceSource ,
                                          @ETypeId ,
                                          @IsGift ,
                                          '' ,
                                          '' ,
                                          0 ,
                                          @GoodsNumber,
										  @GoodsCostPrice,
										  @ProduceDate,
										  @ValidDate,        
										  @serial,
                                          @id ,
                                          @index - 1
					                    );
					                END 
                                SET @index = @index + 1;
                            END;
                            IF(@serialRelation=1)
								BEGIN 
									 EXEC Gp_MakeSerialDetail @BillDate,
												@BillType, @BillNumberId, @PtypeId,
												@Qty, @KTypeId, @ETypeId, @Total,
												@Price, @FreightFee, @Cargo, @ItemID,
												@WdBillComment, @EshopId, @feeatypeid, @Flag,
												@IsGift, @Stypeid,@tempCargoStr, @Itemqty,
												@id, @entrycode, @UnitID, @MQty,
												@MSale, @MUnitID, @Mrate, @NUnitID,
												@Nrate, @iscombined, @serial,
												@GoodsNumber, @ProduceDate, @ValidDate,
												@GoodsCostPrice, @batchNumberDeal,
												@batchQty,@CollectBill,@PriceSource; 			
								END                     
                    END;
            END;
        ELSE
            IF @BillType = 45		----销售退货单
                BEGIN
                    IF @Cargo = ''
                        OR @CargoCount = 0
                        OR @CargoCount = 1
                        BEGIN
                            IF @CargoCount = 1
                                BEGIN
                                    SELECT  @tempCargoStr = cargostr,@serialid=id
                                    FROM    #tempCargo;
                                    SELECT  @CargoID = c.CargoID
                                    FROM    ( SELECT TOP 1
                                                        a
                                              FROM      dbo.f_split(@tempCargoStr,
                                                              'я')
                                            ) f
                                            JOIN CargoType c ON f.a = c.CargoID;
                     			IF(@serialRelation=0)----未使用序列号关联货位自由项
								BEGIN
									SELECT @serialStr = STUFF((SELECT LEFT(serial,LEN(serial)-1) FROM dbo.WdSerialsDetail w 
									WHERE Serial<>'' AND  Serial IS NOT NULL AND w.ordercode = ws.ordercode AND w.mid = ws.mid
									FOR XML PATH('')),1,0,'') FROM WdSerialsDetail ws WHERE ws.ordercode = SUBSTRING(@WdBillComment,6,17) AND mid = @id

									INSERT INTO #serialTable (serial, id )
							        SELECT * FROM dbo.F_SplitSerial(@serialStr,'я')
							       
							        SELECT @rowNumber =ISNULL(SUM(Qty),0) FROM dbo.saleBackBill WHERE BillNumberId = @BillNumberId AND mid = @id
							        
							        SELECT @serial = STUFF((SELECT s.serial+'я' FROM #serialTable s 
									--WHERE  s.id = st.id 
									FOR XML PATH('')),1,0,'') FROM #serialTable st WHERE id>@rowNumber AND id<=@rowNumber+@Qty
								END 
								ELSE ----使用序列号关联货位自由项
								BEGIN 
									SELECT @salebillcount =COUNT(*) FROM dbo.saleBackBill WHERE BillNumberId = @BillNumberId
									SELECT  @serial = serial FROM    [WdSerialsDetail] WHERE   sku_erpid = @skuid AND whstpt_erpid = @CargoID
											AND ordercode = SUBSTRING(@WdBillComment, 6,17) AND serialrelationid IN(SELECT serialRelationId FROM dbo.WdSerialsDetail WHERE ordercode = SUBSTRING(@WdBillComment,6,17) AND mid =@id);
									--修改每行明细数量，将商品数量和序列号数量保持一致，总价=序列号数量*单价								
									SELECT @serialCount = COUNT(*) FROM dbo.f_split(@serial,'я') WHERE a<>''
									IF(@serialCount<>@Qty AND @serialCount<>0)
									BEGIN						
										SELECT @Qty = @serialCount, @Total = dbo.F_RoundTotal(@serialCount*@Price)
										SET @MQty = @Qty / @Mrate;SET @MSale = @Price * @Mrate;
									END 
								END       
 

								IF(@serialRelation=1 AND @serial <>'')
								BEGIN
									SET @serialA =''
									TRUNCATE TABLE #serial
									INSERT INTO #serial
									SELECT a FROM dbo.f_split(@serial,'я') 
									SELECT @serialA = serial FROM #serial WHERE id = 2
                                    SELECT  @GoodsNumber = ISNULL(GoodsNumber,0),
                                            @ProduceDate = ISNULL(ProduceDate,''),
                                            @ValidDate = ISNULL(ValidDate,''),
                                            @CostPrice = ISNULL(CostPrice,0)
                                    FROM    gp_CruPtypeSerial
                                    WHERE   Serial = @serialA
                                            AND PtypeID = @PtypeId
                                            AND ItemID = @ItemID;
									SELECT @GoodsCostPrice=GoodsCostPrice,@batchQty = Qty  FROM dbo.GOODSSTOCKS_QTY WHERE GoodsNumber = @GoodsNumber AND PTypeID = @PtypeId AND CargoID=@CargoID AND @ProduceDate = @ProduceDate AND GoodsCostPrice = @CostPrice
								END
								ELSE
									BEGIN 
										IF(@batchNumberDeal = 0)	--自动读取最早入库的批号/批次信息			
											BEGIN
												SELECT @GoodsNumber=GoodsNumber,@ProduceDate=ProduceDate,@ValidDate=ValidDate,@GoodsCostPrice=GoodsCostPrice,@batchQty = Qty FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID) FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID AND Qty>0)
											END
										ELSE IF (@batchNumberDeal = 1) --自动读取最最大数量的批号/批次信息
											BEGIN 
												SELECT  @GoodsNumber = GoodsNumber ,
														@ProduceDate = ProduceDate ,
														@ValidDate = ValidDate ,
														@GoodsCostPrice = GoodsCostPrice ,
														@batchQty = Qty
												FROM    dbo.GOODSSTOCKS_QTY
												WHERE   ID = ( SELECT TOP 1 id
															   FROM   dbo.GOODSSTOCKS_QTY
															   WHERE  PTypeID = @PtypeId
																	  AND CargoID = @tempCargoStr
																	  AND KTypeID = @KTypeId
																	  AND ItemID = @ItemID
																	  ORDER BY Qty desc
															 );
											END 
									END 
                                END;
                            INSERT  INTO saleBackBill
                                    ( BillNumberId ,
                                      OutFactoryDate ,	--date
                                      Stypeid ,			--分支机构
                                      KTypeID ,			--仓库ID
                                      CargoID ,
                                      PtypeId ,
                                      Qty ,				--基本数量
                                      SalePrice ,		--基本单价
                                      UnitID ,		--基本单位
                                      MQty ,             --销售数量
                                      MSalePrice ,		--销售单价
                                      MUnitID ,		--销售单位
                                      MUnitRate ,		--销售换算率
                                      NQty ,			--浮动数量
                                      NUnitID ,		--浮动单位
                                      UnitRate ,		--浮动换算率
                                      discount ,			--折扣率
                                      Tax ,			--税率
                                      TaxMoney ,			--税额
                                      DiscountPrice ,	--折后单价，按基本单价算折后
                                      MDiscountPrice ,	--折后单价，按销售单价算折后
                                      TaxPrice ,			--含税价，按基本单价算
                                      MTaxPrice ,		--含税价，按销售单价算
                                      SaleTotal ,		--总金额
                                      total ,			--折后总金额
                                      TaxTotal ,			--价税合计
                                      NSalePrice ,       --原币基本单价
                                      CurMSalePrice ,	--原币销售单价
                                      NTaxMoney ,		--原币税额
                                      NDiscountPrice ,	--原币折后单价
                                      CurMDiscountPrice ,--原币折后单价
                                      NTaxPrice ,        --原币含税价
                                      CurMTaxPrice ,		--原币含税价
                                      NSaleTotal ,
                                      NTotal ,
                                      NTaxTotal ,
                                      IsCombined ,
                                      ItemID ,
                                      ETypeID ,       --业务员ID
                                      GoodsNumber,
                                      GoodsCostPrice,
                                      ProduceDate,
                                      mid,
                                      comment ,
                                      Serial
					                )
                            VALUES  ( @BillNumberId ,
                                      @BillDate ,
                                      @Stypeid ,         --分支机构
                                      @KTypeId ,			--仓库
                                      @CargoID ,			--货位
                                      @PtypeId ,			--商品
                                      @Qty ,             --基本数量
                                      @Price ,           --基本单价
                                      @UnitID ,			--基本单位
                                      ISNULL(dbo.F_RoundQty(@MQty),0) ,			--销售数量
                                      @MSale ,           --销售单价
                                      @MUnitID ,			--销售单位
                                      @Mrate ,			--销售换算率
                                      ISNULL(dbo.F_RoundQty(@Qty/@Nrate),0),				--浮动数量
                                      ISNULL(@NUnitID,0),			--浮动单位
								      ISNULL(@Nrate,0),			--浮动换算率@Nrate
                                      1 ,				--折扣率
                                      0 ,				--税率
                                      0 ,				--税额
                                      @Price ,			--折后单价，按基本单价算
                                      @MSale ,			--折后单价，按销售单价算
                                      @Price ,			--含税价，按基本单价算
                                      @MSale ,			--含税价，按销售单价算
                                      @Total ,			--总金额
                                      @Total ,			--折后总金额
                                      @Total ,			--含税总金额
                                      @Price ,			--原币基本单价
                                      @MSale ,			--原币销售单价
                                      0 ,				--原币税额
                                      @Price ,			--原币折后单价，按基本单价算折后
                                      @MSale ,			--原币折后单价，按销售单价算折后
                                      @Price ,			--原币含税价，按基本单价算
                                      @MSale ,			--原币含税价，按销售单价算
                                      @Total ,			--原币总金额
                                      @Total ,			--原币折后总金额
                                      @Total ,			--原币含税总金额
                                      @iscombined ,
                                      @ItemID ,
                                      @ETypeId ,
                                      @GoodsNumber,
                                      @GoodsCostPrice,
                                      '',
                                      @id,
                                      @Comment,
                                      ISNULL(@serial,'')
                                    );	
                             IF(@serialRelation=1)
								BEGIN 
									 EXEC Gp_MakeSerialDetail @BillDate,
											@BillType, @BillNumberId, @PtypeId,
											@Qty, @KTypeId, @ETypeId, @Total,
											@Price, @FreightFee, @Cargo, @ItemID,
											@WdBillComment, @EshopId, @feeatypeid, @Flag,
											@IsGift, @Stypeid,@tempCargoStr, @Itemqty,
											@id, @entrycode, @UnitID, @MQty,
											@MSale, @MUnitID, @Mrate, @NUnitID,
											@Nrate, @iscombined, @serial,
											@GoodsNumber, @ProduceDate, @ValidDate,
											@GoodsCostPrice, @batchNumberDeal,
											@batchQty,@CollectBill,@PriceSource; 
								END 
                        END;
                    ELSE
                        BEGIN
                            DECLARE @index1 INT= 1 ,
                                @tempTotal1 NUMERIC(24, 10); 
                            WHILE @index1 <= @CargoCount
                                BEGIN
                                    SELECT  @tempCargoStr = cargostr,@serialid=id
                                    FROM    #tempCargo
                                    WHERE   id = @index1;
                                    SELECT  @CargoID = c.CargoID
                                    FROM    ( SELECT TOP 1
                                                        a
                                              FROM      dbo.f_split(@tempCargoStr,
                                                              'я')
                                            ) f
                                            JOIN CargoType c ON f.a = c.CargoID;
                                    SELECT  @tempCargoIDQty = CAST(a AS NUMERIC(24,
                                                              10))
                                    FROM    dbo.f_split(@tempCargoStr, 'я')
                                    WHERE   a NOT IN (
                                            SELECT TOP 1
                                                    a
                                            FROM    dbo.f_split(@tempCargoStr,
                                                              'я') );
                                    SET @MQty = @tempCargoIDQty / @Mrate;
                                    SET @tempTotal1 = @Total * @tempCargoIDQty
                                        / @Qty; 
									IF(@serialRelation=0)----未使用序列号关联货位自由项
									BEGIN
										SELECT @serialStr = STUFF((SELECT LEFT(serial,LEN(serial)-1) FROM dbo.WdSerialsDetail w 
										WHERE Serial<>'' AND  Serial IS NOT NULL AND w.ordercode = ws.ordercode AND w.mid = ws.mid
										FOR XML PATH('')),1,0,'') FROM WdSerialsDetail ws WHERE ws.ordercode = SUBSTRING(@WdBillComment,6,17) AND mid = @id

										INSERT INTO #serialTable (serial, id )
										SELECT * FROM dbo.F_SplitSerial(@serialStr,'я')
								       
										SELECT @rowNumber =ISNULL(SUM(Qty),0) FROM dbo.saleBackBill WHERE BillNumberId = @BillNumberId AND mid = @id
								        
										SELECT @serial = STUFF((SELECT s.serial+'я' FROM #serialTable s 
										--WHERE  s.id = st.id 
										FOR XML PATH('')),1,0,'') FROM #serialTable st WHERE id>@rowNumber AND id<=@rowNumber+@tempCargoIDQty
									END 
									ELSE ----使用序列号关联货位自由项
									BEGIN 
										SELECT @salebillcount =COUNT(*) FROM dbo.saleBackBill WHERE BillNumberId = @BillNumberId
										SELECT  @serial = serial FROM    [WdSerialsDetail] WHERE   sku_erpid = @skuid AND whstpt_erpid = @tempCargoStr
												AND ordercode = SUBSTRING(@WdBillComment, 6,17) AND serialrelationid IN(SELECT serialRelationId FROM dbo.WdSerialsDetail WHERE ordercode = SUBSTRING(@WdBillComment,6,17) AND mid =@id);
										--修改每行明细数量，将商品数量和序列号数量保持一致，总价=序列号数量*单价								
										SELECT @serialCount = COUNT(*) FROM dbo.f_split(@serial,'я') WHERE a<>''
										IF(@serialCount<>@Qty AND @serialCount<>0)
										BEGIN						
											SELECT @tempCargoIDQty = @serialCount, @Total = dbo.F_RoundTotal(@serialCount*@Price)
											SET @MQty = @tempCargoIDQty / @Mrate;SET @MSale = @Price * @Mrate;
										END 
									END    
									IF(@serialRelation=1 AND @serial <>'')
									BEGIN
										SET @serialA =''
										TRUNCATE TABLE #serial
										INSERT INTO #serial
										SELECT a FROM dbo.f_split(@serial,'я') 
										SELECT @serialA = serial FROM #serial WHERE id = 2
										SELECT  @GoodsNumber = ISNULL(GoodsNumber,0),
                                            @ProduceDate = ISNULL(ProduceDate,''),
                                            @ValidDate = ISNULL(ValidDate,''),
                                            @CostPrice = ISNULL(CostPrice,0)
										FROM    gp_CruPtypeSerial
										WHERE   Serial = @serialA
												AND PtypeID = @PtypeId
												AND ItemID = @ItemID;
										SELECT @GoodsCostPrice=GoodsCostPrice,@batchQty = Qty  FROM dbo.GOODSSTOCKS_QTY WHERE GoodsNumber = @GoodsNumber AND PTypeID = @PtypeId AND CargoID=@tempCargoStr AND @ProduceDate = @ProduceDate AND GoodsCostPrice = @CostPrice
									END
									ELSE
									BEGIN 
										IF(@batchNumberDeal = 0)	--自动读取最早入库的批号/批次信息			
											BEGIN
												SELECT @GoodsNumber=GoodsNumber,@ProduceDate=ProduceDate,@ValidDate=ValidDate,@GoodsCostPrice=GoodsCostPrice,@batchQty = Qty FROM dbo.GOODSSTOCKS_QTY WHERE ID = (SELECT MIN(ID) FROM dbo.GOODSSTOCKS_QTY WHERE PTypeID=@PtypeId AND CargoID=@tempCargoStr AND KTypeID=@KTypeId AND ItemID=@ItemID AND Qty>0)
											END
										ELSE IF (@batchNumberDeal = 1) --自动读取最最大数量的批号/批次信息
											BEGIN 
												SELECT  @GoodsNumber = GoodsNumber ,
														@ProduceDate = ProduceDate ,
														@ValidDate = ValidDate ,
														@GoodsCostPrice = GoodsCostPrice ,
														@batchQty = Qty
												FROM    dbo.GOODSSTOCKS_QTY
												WHERE   ID = ( SELECT TOP 1 id
															   FROM   dbo.GOODSSTOCKS_QTY
															   WHERE  PTypeID = @PtypeId
																	  AND CargoID = @tempCargoStr
																	  AND KTypeID = @KTypeId
																	  AND ItemID = @ItemID
																	  ORDER BY Qty desc
															 );
											END 
									END 
                                    INSERT  INTO saleBackBill
                                            ( BillNumberId ,
                                              OutFactoryDate ,	--date
                                              Stypeid ,			--分支机构
                                              KTypeID ,			--仓库ID
                                              CargoID ,
                                              PtypeId ,
                                              Qty ,				--基本数量
                                              SalePrice ,		--基本单价
                                              UnitID ,		--基本单位
                                              MQty ,             --销售数量
                                              MSalePrice ,		--销售单价
                                              MUnitID ,		--销售单位
                                              MUnitRate ,		--销售换算率
                                              NQty ,			--浮动数量
                                              NUnitID ,		--浮动单位
                                              UnitRate ,		--浮动换算率
                                              discount ,			--折扣率
                                              Tax ,			--税率
                                              TaxMoney ,			--税额
                                              DiscountPrice ,	--折后单价，按基本单价算折后
                                              MDiscountPrice ,	--折后单价，按销售单价算折后
                                              TaxPrice ,			--含税价，按基本单价算
                                              MTaxPrice ,		--含税价，按销售单价算
                                              SaleTotal ,		--总金额
                                              total ,			--折后总金额
                                              TaxTotal ,			--价税合计
                                              NSalePrice ,       --原币基本单价
                                              CurMSalePrice ,	--原币销售单价
                                              NTaxMoney ,		--原币税额
                                              NDiscountPrice ,	--原币折后单价
                                              CurMDiscountPrice ,--原币折后单价
                                              NTaxPrice ,        --原币含税价
                                              CurMTaxPrice ,		--原币含税价
                                              NSaleTotal ,
                                              NTotal ,
                                              NTaxTotal ,
                                              IsCombined ,
                                              ItemID ,
                                              ETypeID,
                                              GoodsNumber,
											  GoodsCostPrice,
											  ProduceDate,
                                              mid,
                                              comment,
                                              Serial
							                )
                                    VALUES  ( @BillNumberId ,
                                              @BillDate ,
                                              @Stypeid ,         --分支机构
                                              @KTypeId ,			--仓库
                                              @CargoID ,			--货位
                                              @PtypeId ,			--商品
                                              @tempCargoIDQty ,  --基本数量
                                              @Price ,           --基本单价
                                              @UnitID ,			--基本单位
                                              ISNULL(dbo.F_RoundQty(@MQty),0) ,			--销售数量
                                              @MSale ,           --销售单价
                                              @MUnitID ,			--销售单位
                                              @Mrate ,			--销售换算率
                                              dbo.F_RoundQty(@tempCargoIDQty/@Nrate) ,--浮动数量
                                              ISNULL(@NUnitID,0),			--浮动单位
										      ISNULL(@Nrate,0),			--浮动换算率@Nrate
                                              1 ,				--折扣率
                                              0 ,				--税率
                                              0 ,				--税额
                                              @Price ,			--折后单价，按基本单价算
                                              @MSale ,			--折后单价，按销售单价算
                                              @Price ,			--含税价，按基本单价算
                                              @MSale ,			--含税价，按销售单价算
                                              @tempTotal1 ,			--总金额
                                              @tempTotal1 ,			--折后总金额
                                              @tempTotal1 ,			--含税总金额
                                              @Price ,			--原币基本单价
                                              @MSale ,			--原币销售单价
                                              0 ,				--原币税额
                                              @Price ,			--原币折后单价，按基本单价算折后
                                              @MSale ,			--原币折后单价，按销售单价算折后
                                              @Price ,			--原币含税价，按基本单价算
                                              @MSale ,			--原币含税价，按销售单价算
                                              @tempTotal1 ,			--原币总金额
                                              @tempTotal1 ,			--原币折后总金额
                                              @tempTotal1 ,			--原币含税总金额
                                              @iscombined ,
                                              @ItemID ,
                                              @ETypeId,
                                              @GoodsNumber,
                                              @GoodsCostPrice,
                                              '',
                                              @id,
                                              @Comment,
                                              ISNULL(@serial,'')
							                );	
                                    SET @index1 = @index1 + 1;
                                END;
                                IF(@serialRelation=1)
								BEGIN 
									EXEC Gp_MakeSerialDetail @BillDate,
										@BillType, @BillNumberId, @PtypeId,
										@Qty, @KTypeId, @ETypeId, @Total,
										@Price, @FreightFee, @Cargo, @ItemID,
										@WdBillComment, @EshopId, @feeatypeid, @Flag,
										@IsGift, @Stypeid, @tempCargoStr, @Itemqty,
										@id, @entrycode, @UnitID, @MQty,
										@MSale, @MUnitID, @Mrate, @NUnitID,
										@Nrate, @iscombined, @serial,
										@GoodsNumber, '', @ValidDate,
										@GoodsCostPrice, @batchNumberDeal,
										@batchQty,@CollectBill,@PriceSource; 		
								END 	
                        END;	
                END;
            ELSE
                BEGIN 
                    DECLARE @sql NVARCHAR(MAX);
                    SET @sql = 'INSERT INTO MoneyBill
						 ( 
						  BillNumberId ,
						  AtypeId , 
						  total ,
						  ntotal ,
						  mid ,
						  Comment,
						  Stypeid
						 )
						VALUES(' + CAST(@BillNumberId AS VARCHAR(50))
                        + ',@atypeid,@Total,@Total,@mid,''' + @Comment
                        + ''',''' + @Stypeid + ''' )';
                    IF @BillType = 36		----费用单		
                        BEGIN
						--SELECT @sql
                            EXEC sp_executesql @sql,
                                N'@atypeid VARCHAR(50),@Total  NUMERIC(24, 10),@mid INT',
                                @feeatypeid, @Total, @id;
                        END; 
                END; 
    END; 
    
DROP TABLE #serial    
    
GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO

 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Web_DeleteDiybill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Web_DeleteDiybill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2010-07-28
	描述：删除电脑装机配置单
*/
CREATE PROCEDURE Gp_Web_DeleteDiybill
(
	@Billnumberid  	VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON

		IF EXISTS(SELECT TOP 1 1 FROM DiyBillTypePSaleTypeID 
		          INNER JOIN dbo.BillIndex  b ON b.BillNumberId =  DiyBillTypePSaleTypeID.SalebillNumberId
		          WHERE DiyBillTypeId = @Billnumberid
		          AND b.RedWord=0)
			RETURN -1
		DELETE FROM DiyIndex WHERE BillNumberId = @Billnumberid
		DELETE FROM DiyBill WHERE BillNumberId = @Billnumberid
RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Web_DiyHistorybill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Web_DiyHistorybill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：郑红霞
	日期：2011-9-20
	描述：查询装机配置单历史调用情况
	
-------------------------------------------*/
CREATE PROCEDURE Gp_Web_DiyHistorybill
(
	@BillNumberId	 VARCHAR(MAX)	---单据编号
)
--@encode$--
AS
SET NOCOUNT ON
        SELECT  DISTINCT a.BillCode,
							a.BillNumberId,
							a.Stypeid,
							a.etypeid,
							a.DealBTypeID AS btypeid
				FROM  BillIndex a
				INNER JOIN DiyBillTypePSaleTypeID b ON b.SalebillNumberId = a.BillNumberId
				INNER JOIN dbo.DiyIndex d ON d.billnumberid = b.DiyBillTypeId
				WHERE d.BillNumberId = @BillNumberId
				AND a.draft=0
				AND a.RedWord=0
				AND a.ifcheck='t'
				ORDER BY a.BillCode DESC
		
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




		if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_web_Ptype_Buy_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		drop procedure [dbo].[Gp_web_Ptype_Buy_Analysis]
		GO

		SET QUOTED_IDENTIFIER ON 
		GO
		SET ANSI_NULLS ON 
		GO

		/*
		功能：单品进货分析
		作者：赵和平
		时间：2011-12-12
		*/
		CREATE         PROCEDURE Gp_web_Ptype_Buy_Analysis
		(
			@chvPTypeID			varchar(8000),  --当前查询商品
			@chvOperatorID		varchar(50),
			@STypeId			varchar(max),	--分支机构
			@billtype           varchar(100),    --表单类型
			@pttypeid           varchar(8000)   --商品类
		)
		--@encode$--
		AS
		SET NOCOUNT ON

		-- 权限范围检查
		IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数

		DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
					@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
		EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

		CREATE TABLE #Ptype(typeid varchar(50)) -- 当前查询商品
		INSERT INTO #Ptype(typeid) select a.typeid from F_GetManDetailPType(@chvOperatorID) a, (select * from  dbo.f_split(@chvPtypeID,',')) b where left(a.typeid,len(b.a))=b.a

		CREATE TABLE #Ptype1(typeid varchar(50)) -- 本类商品
		IF NOT Charindex(',',@chvPtypeID)>0
		BEGIN
			SET @chvPtypeID =@pttypeid
			SET @chvPtypeID=@chvPtypeID+'%'
			INSERT INTO #Ptype1(typeid) select a.typeid from F_GetManDetailPType(@chvOperatorID) a where a.typeid like @chvPtypeID
		END
		CREATE TABLE #Ptype2(typeid varchar(50)) -- 全部商品
		INSERT INTO #Ptype2(typeid) select a.typeid from F_GetManDetailPType(@chvOperatorID) a

		--分支机构
		CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperatorID)

		--职员
		CREATE TABLE #GetManETypeId(TypeId	varchar(100))
		INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID)	

		--仓库
		CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
		INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@chvOperatorID)

		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))	
		INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

		--部门
		CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
		INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)	

		--往来单位
		CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
		INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID)	


		/* 取全年相关进货数据 - Start */

		-- 【当前查询商品】全年相关进货数据
		DECLARE @numQty			 NUMERIC(24, 10) ,	-- 当前查询商品的全年进货数量
				@numTotal		 NUMERIC(24, 10) 	-- 当前查询商品的全年进货金额

		SELECT	@numQty = CAST(ISNULL(SUM(a.Qty),0) AS  NUMERIC(24, 10) ),
				@numTotal = CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))

		-- 【本类商品】全年相关进货数据
		DECLARE @numParentQty			 NUMERIC(24, 10) ,	-- 本类商品的全年进货数量
				@numParentTotal			 NUMERIC(24, 10) 	-- 本类商品的全年进货金额

		SELECT	@numParentQty = CAST(ISNULL(SUM(a.Qty),0) AS  NUMERIC(24, 10) ),
				@numParentTotal = CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype1 p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))

		-- 【全部商品】全年相关进货数据
		DECLARE @numAllQty			 NUMERIC(24, 10) ,	-- 全部商品的全年进货数量
				@numAllTotal		 NUMERIC(24, 10) 	-- 全部商品的全年进货金额

		SELECT	@numAllQty = CAST(ISNULL(SUM(a.Qty),0) AS  NUMERIC(24, 10) ),
				@numAllTotal = CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype2 p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId	
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))



		/* 取全年相关进货数据 - End */


		-- 创建临时报表
		CREATE TABLE #TempAnalyse (
			Line_No		int,
			Item		varchar(200),
			YearData	 NUMERIC(24, 10) 
		)

		/* 先期导入全年数据 - Start */
		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(1,'进货数量',@numQty)
		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(2,'进货金额',@numTotal)

		IF EXISTS(SELECT * FROM #Ptype1)
		BEGIN
			INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(3,'进货数量占本类商品的百分比（%）',CASE WHEN @numParentQty = 0 THEN 0 ELSE ABS(CAST((@numQty/@numParentQty)*100 AS  NUMERIC(24, 10) )) END )
			INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(4,'进货金额占本类商品的百分比（%）',CASE WHEN @numParentTotal = 0 THEN 0 ELSE ABS(CAST((@numTotal/@numParentTotal)*100 AS  NUMERIC(24, 10) )) END )
		END
		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(5,'进货数量占全部商品的百分比（%）',CASE WHEN @numAllQty = 0 THEN 0 ELSE ABS(CAST((@numQty/@numAllQty)*100 AS  NUMERIC(24, 10) )) END )
		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(6,'进货金额占全部商品的百分比（%）',CASE WHEN @numAllTotal = 0 THEN 0 ELSE ABS(CAST((@numTotal/@numAllTotal)*100 AS  NUMERIC(24, 10) )) END )

		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(7,'当月进货量占全年进货量的百分比（%）',CASE WHEN @numQty = 0 THEN 0 ELSE 100 END)
		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(8,'当月进货额占全年进货额的百分比（%）',CASE WHEN @numQty = 0 THEN 0 ELSE 100 END)
		/* 先期导入全年数据 - End */

		-- 循环查询每个会计期间相关数据
		DECLARE @MonthNo	varchar(50),
				@StartDate	varchar(20),
				@EndDate	varchar(20),
				@period		int
				
		DECLARE @chvSQL varchar(100)
		DECLARE MONTH_CURSOR CURSOR FOR
			SELECT	MonthNo,StartDate,EndDate,period FROM MonthProc ORDER BY period

		OPEN MONTH_CURSOR
		FETCH NEXT FROM MONTH_CURSOR INTO	@MonthNo,
											@StartDate,
											@EndDate,
											@period
		WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 增加对应的会计期间列
		SET @chvSQL = 'ALTER TABLE #TempAnalyse ADD [' + @MonthNo + ']  NUMERIC(24, 10)  NULL'
		EXEC(@chvSQL)

		-- 对本期结束时间进行放开
		SET @EndDate = ISNULL(@EndDate,'2518-01-01')

		-- 【当前查询商品】会计期间相关进货数据
		DECLARE @numPeriodQty			 NUMERIC(24, 10) ,	-- 当前查询商品的会计期间进货数量
				@numPeriodTotal			 NUMERIC(24, 10) 	-- 当前查询商品的会计期间进货金额

		SELECT	@numPeriodQty = ISNULL(SUM(a.Qty),0),
				@numPeriodTotal = CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))
				AND BillDate >= @StartDate
				AND BillDate <= @EndDate

		-- 【本类商品】会计期间相关进货数据
		DECLARE @numPeriodParentQty			 NUMERIC(24, 10) ,	-- 本类商品的会计期间进货数量
				@numPeriodParentTotal		 NUMERIC(24, 10) 	-- 本类商品的会计期间进货金额

		SELECT	@numPeriodParentQty = ISNULL(SUM(a.Qty),0),
				@numPeriodParentTotal = CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype1 p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))
				AND BillDate >= @StartDate
				AND BillDate <= @EndDate

		-- 【全部商品】会计期间相关进货数据
		DECLARE @numPeriodAllQty		 NUMERIC(24, 10) ,	-- 全部商品的会计期间进货数量
				@numPeriodAllTotal		 NUMERIC(24, 10) 	-- 全部商品的会计期间进货金额

		SELECT	@numPeriodAllQty = ISNULL(SUM(a.Qty),0),
				@numPeriodAllTotal = CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype2 p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))
				AND BillDate >= @StartDate
				AND BillDate <= @EndDate


		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(@numPeriodQty AS varchar(50)) + ' WHERE Line_No = 1'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(@numPeriodTotal AS varchar(50)) + ' WHERE Line_No = 2'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodParentQty = 0 THEN 0 ELSE ABS(CAST((@numPeriodQty/@numPeriodParentQty)*100 AS  NUMERIC(24, 10) )) END AS varchar(50)) + ' WHERE Line_No = 3'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodParentTotal = 0 THEN 0 ELSE ABS(CAST((@numPeriodTotal/@numPeriodParentTotal)*100 AS  NUMERIC(24, 10) )) END AS varchar(50)) + ' WHERE Line_No = 4'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodAllQty = 0 THEN 0 ELSE ABS(CAST((@numPeriodQty/@numPeriodAllQty)*100 AS  NUMERIC(24, 10) )) END AS varchar(50)) + ' WHERE Line_No = 5'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodAllTotal = 0 THEN 0 ELSE ABS(CAST((@numPeriodTotal/@numPeriodAllTotal)*100 AS  NUMERIC(24, 10) )) END AS varchar(50)) + ' WHERE Line_No = 6'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numQty = 0 THEN 0 ELSE ABS(CAST((@numPeriodQty/@numQty)*100 AS  NUMERIC(24, 10) )) END AS varchar(50)) + ' WHERE Line_No = 7'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numTotal = 0 THEN 0 ELSE ABS(CAST((@numPeriodTotal/@numTotal)*100 AS  NUMERIC(24, 10) )) END AS varchar(50)) + ' WHERE Line_No = 8'
		EXEC(@chvSQL)

		FETCH NEXT FROM MONTH_CURSOR INTO	@MonthNo,
											@StartDate,
											@EndDate,
											@period
	END
	CLOSE MONTH_CURSOR
	DEALLOCATE MONTH_CURSOR

	-- 查询结果
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'IfQP' AND SubValue = '1')
	BEGIN
		UPDATE #TempAnalyse SET Item = REPLACE(Item,'商品','配件')
	END

	SELECT * FROM #TempAnalyse ORDER BY Line_No

	DROP TABLE #TempAnalyse,#Ptype,#Ptype1,#ptype2,#GetManSTypeId,#GetManETypeId,#GetManKTypeId,#GetManDTypeId,#GetManBTypeId

	GO
	SET QUOTED_IDENTIFIER OFF 
	GO
	SET ANSI_NULLS ON 
	GO




	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_web_Ptype_Sale_Analysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].[Gp_web_Ptype_Sale_Analysis]
	GO

	SET QUOTED_IDENTIFIER ON 
	GO
	SET ANSI_NULLS ON 
	GO

	/*
	功能：单品销售分析
	作者：赵和平
	时间：2011-12-12
	*/
	CREATE         PROCEDURE Gp_web_Ptype_Sale_Analysis
	(
		@chvPTypeID			varchar(8000),  --商品
		@chvOperatorID		varchar(50),
		@STypeId			varchar(max),	--分支机构
		@billtype           varchar(100),    --单据类
		@chvPtTypeID        varchar(8000)   --商品类
	)
	--@encode$--
	AS
	SET NOCOUNT ON

	-- 权限范围检查
	IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数

	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
				@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

	CREATE TABLE #Ptype(typeid varchar(50)) -- 当前查询商品
	INSERT INTO #Ptype(typeid) select a.typeid from F_GetManDetailPType(@chvOperatorID) a, (select * from  dbo.f_split(@chvPtypeID,',')) b where left(a.typeid,len(b.a))=b.a

	CREATE TABLE #Ptype1(typeid varchar(50)) -- 本类商品
	IF NOT Charindex(',',@chvPtypeID)>0
	BEGIN
		SET @chvPtypeID =@chvPtTypeID
		SET @chvPtypeID=@chvPtypeID+'%'
		INSERT INTO #Ptype1(typeid) select a.typeid from F_GetManDetailPType(@chvOperatorID) a where a.typeid like @chvPtypeID
	END
	CREATE TABLE #Ptype2(typeid varchar(50)) -- 全部商品
	INSERT INTO #Ptype2(typeid) select a.typeid from F_GetManDetailPType(@chvOperatorID) a

	--分支机构
	CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperatorID)

	--职员
	CREATE TABLE #GetManETypeId(TypeId	varchar(100))
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID)	

	--仓库
	CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@chvOperatorID)

	--删除仓库中的对于STypeId
	DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))	
	INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

	--部门
	CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)	

	--往来单位
	CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
	INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID)	

	/* 取全年相关销售数据 - Start */

	-- 【当前查询商品】全年相关销售数据
	DECLARE @numQty			 NUMERIC(24, 10) ,	-- 当前查询商品的全年销售数量
			@numTotal		 NUMERIC(24, 10) ,	-- 当前查询商品的全年销售金额
			@numCostTotal	 NUMERIC(24, 10) 	-- 当前查询商品的全年成本金额

	SELECT	@numQty = -CAST(ISNULL(SUM(a.Qty),0) AS  NUMERIC(24, 10) ),
			@numTotal = -CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) ),
			@numCostTotal = -CAST(ISNULL(SUM(a.CostTotal),0) AS  NUMERIC(24, 10) )
	FROM	InOutStockTable a
	INNER JOIN #Ptype p ON a.ptypeid=p.typeid
	INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
	INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
	INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
	INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
	INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
	WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))

	-- 【本类商品】全年相关销售数据
	DECLARE @numParentQty			 NUMERIC(24, 10) ,	-- 本类商品的全年销售数量
			@numParentTotal			 NUMERIC(24, 10) ,	-- 本类商品的全年销售金额
			@numParentCostTotal		 NUMERIC(24, 10) 	-- 本类商品的全年成本金额

	SELECT	@numParentQty = -CAST(ISNULL(SUM(a.Qty),0) AS  NUMERIC(24, 10) ),
			@numParentTotal = -CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) ),
			@numParentCostTotal = -CAST(ISNULL(SUM(a.CostTotal),0) AS  NUMERIC(24, 10) )
	FROM	InOutStockTable a
	INNER JOIN #Ptype1 p ON a.ptypeid=p.typeid
	INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
	INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
	INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
	INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
	INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
	WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))


	-- 【全部商品】全年相关销售数据
	DECLARE @numAllQty			 NUMERIC(24, 10) ,	-- 全部商品的全年销售数量
			@numAllTotal		 NUMERIC(24, 10) ,	-- 全部商品的全年销售金额
			@numAllCostTotal	 NUMERIC(24, 10) 	-- 全部商品的全年成本金额

	SELECT	@numAllQty = -CAST(ISNULL(SUM(a.Qty),0) AS  NUMERIC(24, 10) ),
			@numAllTotal = -CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) ),
			@numAllCostTotal = -CAST(ISNULL(SUM(a.CostTotal),0) AS  NUMERIC(24, 10) )
	FROM	InOutStockTable a
	INNER JOIN #Ptype2 p ON a.ptypeid=p.typeid
	INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId	
	INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
	INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
	INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
	INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
	WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))


	/* 取全年相关销售数据 - End */


	-- 创建临时报表
	CREATE TABLE #TempAnalyse (
		Line_No		int,
		Item		varchar(200),
		YearData	 NUMERIC(24, 10) 
	)

	/* 先期导入全年数据 - Start */
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(1,'销售数量',@numQty)
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(2,'销售金额',@numTotal)
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(3,'销售利润',@numTotal-@numCostTotal)
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(4,'销售毛利率（%）',CASE WHEN @numTotal = 0 THEN 0 ELSE CAST(((@numTotal-@numCostTotal)/@numTotal)*100 AS  NUMERIC(24, 10) ) END )

	IF EXISTS(SELECT * FROM #Ptype1)
	BEGIN
		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(5,'销售数量占本类商品的百分比（%）',CASE WHEN @numParentQty = 0 THEN 0 ELSE CAST((@numQty/@numParentQty)*100 AS  NUMERIC(24, 10) ) END )
		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(6,'销售金额占本类商品的百分比（%）',CASE WHEN @numParentTotal = 0 THEN 0 ELSE CAST((@numTotal/@numParentTotal)*100 AS  NUMERIC(24, 10) ) END )
		INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(7,'销售利润占本类商品的百分比（%）',CASE WHEN @numParentTotal-@numParentCostTotal = 0 THEN 0 ELSE CAST(((@numTotal-@numCostTotal)/(@numParentTotal-@numParentCostTotal))*100 AS  NUMERIC(24, 10) ) END )
	END
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(8,'销售数量占全部商品的百分比（%）',CASE WHEN @numAllQty = 0 THEN 0 ELSE CAST((@numQty/@numAllQty)*100 AS  NUMERIC(24, 10) ) END )
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(9,'销售金额占全部商品的百分比（%）',CASE WHEN @numAllTotal = 0 THEN 0 ELSE CAST((@numTotal/@numAllTotal)*100 AS  NUMERIC(24, 10) ) END )
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(10,'销售毛利占全部商品的百分比（%）',CASE WHEN @numAllTotal-@numAllCostTotal = 0 THEN 0 ELSE CAST(((@numTotal-@numCostTotal)/(@numAllTotal-@numAllCostTotal))*100 AS  NUMERIC(24, 10) ) END )

	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(11,'当月销售量占全年销售量的百分比（%）',CASE WHEN @numQty = 0 THEN 0 ELSE 100 END)
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(12,'当月销售额占全年销售额的百分比（%）',CASE WHEN @numQty = 0 THEN 0 ELSE 100 END)
	INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(13,'当月销售毛利占全年销售毛利的百分比（%）',CASE WHEN @numQty = 0 THEN 0 ELSE 100 END)
	/* 先期导入全年数据 - End */

	-- 循环查询每个会计期间相关数据
	DECLARE @MonthNo	varchar(50),
			@StartDate	varchar(20),
			@EndDate	varchar(20),
			@period		int
			
	DECLARE @chvSQL varchar(100)
	DECLARE MONTH_CURSOR CURSOR FOR
		SELECT	MonthNo,StartDate,EndDate,period FROM MonthProc ORDER BY period

	OPEN MONTH_CURSOR
	FETCH NEXT FROM MONTH_CURSOR INTO	@MonthNo,
										@StartDate,
										@EndDate,
										@period
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 增加对应的会计期间列
		SET @chvSQL = 'ALTER TABLE #TempAnalyse ADD [' + @MonthNo + ']  NUMERIC(24, 10)  NULL'
		EXEC(@chvSQL)

		-- 对本期结束时间进行放开
		SET @EndDate = ISNULL(@EndDate,'2518-01-01')

		-- 【当前查询商品】会计期间相关销售数据
		DECLARE @numPeriodQty			 NUMERIC(24, 10) ,	-- 当前查询商品的会计期间销售数量
				@numPeriodTotal			 NUMERIC(24, 10) ,	-- 当前查询商品的会计期间销售金额
				@numPeriodCostTotal		 NUMERIC(24, 10) 	-- 当前查询商品的会计期间成本金额

		SELECT	@numPeriodQty = -ISNULL(SUM(a.Qty),0),
				@numPeriodTotal = -CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) ),
				@numPeriodCostTotal = -CAST(ISNULL(SUM(a.CostTotal),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))
				AND BillDate >= @StartDate
				AND BillDate <= @EndDate

		-- 【本类商品】会计期间相关销售数据
		DECLARE @numPeriodParentQty			 NUMERIC(24, 10) ,	-- 本类商品的会计期间销售数量
				@numPeriodParentTotal		 NUMERIC(24, 10) ,	-- 本类商品的会计期间销售金额
				@numPeriodParentCostTotal	 NUMERIC(24, 10) 	-- 本类商品的会计期间成本金额

		SELECT	@numPeriodParentQty = -ISNULL(SUM(a.Qty),0),
				@numPeriodParentTotal = -CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) ),
				@numPeriodParentCostTotal = -CAST(ISNULL(SUM(a.CostTotal),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype1 p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))
				AND BillDate >= @StartDate
				AND BillDate <= @EndDate

		-- 【全部商品】会计期间相关销售数据
		DECLARE @numPeriodAllQty		 NUMERIC(24, 10) ,	-- 全部商品的会计期间销售数量
				@numPeriodAllTotal		 NUMERIC(24, 10) ,	-- 全部商品的会计期间销售金额
				@numPeriodAllCostTotal	 NUMERIC(24, 10) 	-- 全部商品的会计期间成本金额

		SELECT	@numPeriodAllQty = -ISNULL(SUM(a.Qty),0),
				@numPeriodAllTotal = -CAST(ISNULL(SUM(a.Total),0) AS  NUMERIC(24, 10) ),
				@numPeriodAllCostTotal = -CAST(ISNULL(SUM(a.CostTotal),0) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #Ptype2 p ON a.ptypeid=p.typeid
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))
				AND BillDate >= @StartDate
				AND BillDate <= @EndDate


		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(@numPeriodQty AS varchar(50)) + ' WHERE Line_No = 1'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(@numPeriodTotal AS varchar(50)) + ' WHERE Line_No = 2'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(@numPeriodTotal-@numPeriodCostTotal AS varchar(50)) + ' WHERE Line_No = 3'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodTotal = 0 THEN 0 ELSE CAST(((@numPeriodTotal-@numPeriodCostTotal)/@numPeriodTotal)*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 4'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodParentQty = 0 THEN 0 ELSE CAST((@numPeriodQty/@numPeriodParentQty)*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 5'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodParentTotal = 0 THEN 0 ELSE CAST((@numPeriodTotal/@numPeriodParentTotal)*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 6'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodParentTotal-@numPeriodParentCostTotal = 0 THEN 0 ELSE CAST(((@numPeriodTotal-@numPeriodCostTotal)/(@numPeriodParentTotal-@numPeriodParentCostTotal))*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 7'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodAllQty = 0 THEN 0 ELSE CAST((@numPeriodQty/@numPeriodAllQty)*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 8'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodAllTotal = 0 THEN 0 ELSE CAST((@numPeriodTotal/@numPeriodAllTotal)*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 9'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numPeriodAllTotal-@numPeriodAllCostTotal = 0 THEN 0 ELSE CAST(((@numPeriodTotal-@numPeriodCostTotal)/(@numPeriodAllTotal-@numPeriodAllCostTotal))*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 10'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numQty = 0 THEN 0 ELSE CAST((@numPeriodQty/@numQty)*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 11'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numTotal = 0 THEN 0 ELSE CAST((@numPeriodTotal/@numTotal)*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 12'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numTotal-@numCostTotal = 0 THEN 0 ELSE CAST(((@numPeriodTotal-@numPeriodCostTotal)/(@numTotal-@numCostTotal))*100 AS  NUMERIC(24, 10) ) END AS varchar(50)) + ' WHERE Line_No = 13'
		EXEC(@chvSQL)

		FETCH NEXT FROM MONTH_CURSOR INTO	@MonthNo,
											@StartDate,
											@EndDate,
											@period
	END
	CLOSE MONTH_CURSOR
	DEALLOCATE MONTH_CURSOR

	-- 查询结果
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'IfQP' AND SubValue = '1')
	BEGIN
		UPDATE #TempAnalyse SET Item = REPLACE(Item,'商品','配件')
	END

	SELECT * FROM #TempAnalyse ORDER BY Line_No

	DROP TABLE #TempAnalyse,#Ptype,#Ptype1,#ptype2,#GetManSTypeId,#GetManETypeId,#GetManKTypeId,#GetManDTypeId,#GetManBTypeId

	GO
	SET QUOTED_IDENTIFIER OFF 
	GO
	SET ANSI_NULLS ON 
	GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Web_QueryOtherinOutline]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Web_QueryOtherinOutline]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2011-07-12
	描述：其他出入库线性表
*/
CREATE PROCEDURE Gp_Web_QueryOtherinOutline
(
    @OperatorId			VARCHAR(MAX),	--操作员ID
	@StartDate			VARCHAR(MAX),	--开始日期
	@EndDate			VARCHAR(MAX),	--截止日期
	@STypeId			VARCHAR(MAX),	--分支机构
	@dealBTypeId		VARCHAR(MAX),	--往来单位
	@DTypeId			VARCHAR(MAX),	--部门ID
	@KTypeId			VARCHAR(MAX),	--仓库
	@PTypeId			VARCHAR(MAX),
	@EtypeId            VARCHAR(MAX),
	@businessid         VARCHAR(max)         --业务类别
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealBTypeId,2,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID)	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)	


CREATE TABLE #Otherouttable  -----其他出库临时表
   (
     PTypeId varchar(100),
     BillNumberId varchar(max),
     Qty  NUMERIC(24, 10) ,
     Price  NUMERIC(24, 10) ,
     Total  NUMERIC(24, 10) ,
     stypeid varchar(max),
     ktypeid varchar(max)
   )
INSERT INTO  #Otherouttable 
(   PTypeId,
	BillNumberId,
	Qty,
	Price,
	Total,
	stypeid,
	ktypeid
) 
SELECT  o.PtypeId,
		o.BillNumberId,
		o.Qty ,
		o.Price,
		o.Total,
		o.Stypeid,
		o.KtypeId
FROM  OtherInOutBill o
			  INNER JOIN BillIndex b       ON b.BillNumberId = o.BillNumberId
			  INNER JOIN #GetManSTypeId S  ON S.TypeId = o.Stypeid
			  INNER JOIN #GetManKTypeId K  ON K.TypeId = o.KtypeId
			  INNER JOIN #GetManDTypeId D  ON D.TypeId = b.DTypeId
			  INNER JOIN #GetManBTypeId bi ON bi.TypeId = b.DealBTypeID
			  INNER JOIN #GetManETypeId e  ON e.TypeId =b.etypeid
			  INNER JOIN #GetManPTypeId p ON p.TypeId = o.PtypeId
    WHERE	B.BillDate>=@StartDate
			  AND B.BillDate<=@EndDate							
			  AND B.RedWord = 0
			  AND b.draft=0
			  AND b.ifcheck='t'
			  AND o.BillTYpe=202
			  AND b.ifYearBill=0
			  AND (b.OtherInOutType IN (SELECT * FROM dbo.f_split(@businessid,',')) OR @businessid='')
			  	 --年节存标志
			 -- AND P.TypeId LIKE '''+@PTypeId+'%'' 
--SELECT * FROM  #Otherouttable
CREATE TABLE  #OtherIntable  ----其他入库临时表
(
	 PTypeId varchar(100),
	 BillNumberId numeric(10, 0) ,
	 Qty  NUMERIC(24, 10) ,
	 Price  NUMERIC(24, 10) ,
	 Total  NUMERIC(24, 10) ,
	 stypeid varchar(max),
	 ktypeid varchar(max)
  )	
INSERT INTO #OtherIntable 
(	PTypeId,
	BillNumberId,
	Qty,
	Price,
	Total,
	stypeid,
	ktypeid
)
SELECT  o.PtypeId,
		o.BillNumberId,
		o.Qty,
		o.Price,
		o.Total,
		o.Stypeid,
		o.KtypeId 
FROM  OtherInOutBill o 
		  INNER JOIN BillIndex b       ON b.BillNumberId = o.BillNumberId
		  INNER JOIN #GetManSTypeId S  ON S.TypeId = o.Stypeid
		  INNER JOIN #GetManKTypeId K  ON K.TypeId = o.KtypeId
		  INNER JOIN #GetManDTypeId D  ON D.TypeId = b.DTypeId
		  INNER JOIN #GetManBTypeId bi ON bi.TypeId = b.DealBTypeID
		  INNER JOIN #GetManETypeId e  ON e.TypeId =b.etypeid
		  INNER JOIN #GetManPTypeId p ON p.TypeId = o.PtypeId
		  
	WHERE	B.BillDate>=@StartDate
		  AND B.BillDate<=@EndDate						
		  AND B.RedWord = 0
		  AND b.draft=0
		  AND b.ifcheck='t'
		  AND o.BillTYpe=201
		  AND b.ifYearBill=0	 --年节存标志
		 AND (b.OtherInOutType IN (SELECT * FROM dbo.f_split(@businessid,',')) OR @businessid='')
    --  SELECT * FROM  #OtherIntable
CREATE TABLE  #OtherInOuttable  ----其他入库临时表
(
     PTypeId		    varchar(max),
     outqty				 NUMERIC(24, 10) ,
     outprice			 NUMERIC(24, 10) ,
     outtotal			 NUMERIC(24, 10) ,
     inqty				 NUMERIC(24, 10) ,
     inprice			 NUMERIC(24, 10) ,
     intotal			 NUMERIC(24, 10) ,
     differentialqty     NUMERIC(24, 10) ,
     differentialtotal   NUMERIC(24, 10)  
)	
INSERT INTO #OtherInOuttable 
(   PTypeId,
	outqty,
	outprice,
	outtotal,
	inqty,
	inprice,
	intotal,
	differentialqty,
	differentialtotal
)
SELECT  i.PTypeId,0,0,0,i.Qty as inqty,i.Price as inprice,i.Total as intotal,0,0 from #OtherIntable i
  UNION ALL
SELECT o.PTypeId,o.Qty as outqty,o.Price as outprice,o.Total as outtotal,0,0,0,0,0 from #Otherouttable o


DECLARE @SQL		VARCHAR(MAX)
SET @SQL = ' SELECT	P.TypeId, 
					P.SonNum,  
					P.usercode, 
                    --ISNULL((SUM(o.inprice)),0) AS inprice,
                    ISNULL((SUM(o.inqty)),0) AS inqty,
                    ISNULL((SUM(o.intotal)),0) AS intotal,
                    CASE WHEN SUM(o.inqty) = 0  THEN SUM(o.intotal)
					  ELSE ISNULL(SUM(o.intotal),0)/SUM(o.inqty) END AS inprice,
                    --ISNULL((SUM(o.outprice)),0) AS outprice,
                    CASE WHEN SUM(o.outqty) = 0  THEN SUM(o.outtotal)
					   ELSE ISNULL(SUM(o.outtotal),0)/SUM(o.outqty) END AS outprice,
					ISNULL((SUM(o.outqty)),0) AS outqty,
					ISNULL((SUM(o.outtotal)),0) AS outtotal,
					ISNULL((SUM(o.differentialqty)),0) AS differentialqty,
					ISNULL((SUM(o.differentialtotal)),0) AS differentialtotal,
					u1.fullname AS basename
			FROM	PType P '+dbo.F_GetPtypeUnitsAndRates('p','1','1')
		SET @SQL+='	
			LEFT JOIN (
						select  inout.ptypeid,
								SUM(inout.outqty) AS outqty,
								SUM(inout.outprice) AS outprice,
								SUM(inout.outtotal) AS outtotal,
								SUM(inout.inqty) AS inqty,
								SUM(inout.inprice) AS inprice,
								SUM(inout.intotal) AS intotal,
								sum(isnull(inout.outqty,0))-sum(isnull(inout.inqty,0)) as differentialqty,
								sum(isnull(inout.outtotal,0)) - sum(isnull(inout.intotal,0)) as differentialtotal
						from #OtherInOuttable inout
						'
SET @SQL = @SQL + ' GROUP BY inout.PtypeId )o ON LEFT(o.PtypeId,LEN(P.TypeId)) = P.TypeId
                      WHERE	P.TypeId LIKE '''+@PTypeId+'%'' 
							AND P.SonNum = 0
							AND	(inqty + outqty)<> 0
					GROUP By P.TypeId,
							 P.SonNum,
							 P.usercode,
							 u1.fullname
					ORDER BY P.usercode ASC '
--SET @SQL=@SQL+ 'group by o.PtypeId,o.BillNumberId'
--print @sql
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Web_QueryOtherOutOrOutline]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Web_QueryOtherOutOrOutline]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2011-07-12
	描述：其他出库或入库线性表
*/
CREATE PROCEDURE Gp_Web_QueryOtherOutOrOutline
(
    @OperatorId			VARCHAR(MAX),	--操作员ID
	@StartDate			VARCHAR(MAX),	--开始日期
	@EndDate			VARCHAR(MAX),	--截止日期
	@STypeId			VARCHAR(MAX),	--分支机构
	@dealBTypeId			VARCHAR(MAX),	--往来单位
	@DTypeId			VARCHAR(MAX),	--部门ID
	@KTypeId			VARCHAR(MAX),	--仓库
	@BillType			VARCHAR(MAX),	--单据类型
	@PTypeId			VARCHAR(MAX),
	@EtypeId            VARCHAR(MAX)='',
    @businessid         VARCHAR(max)         --业务类别
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealBTypeId,2,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)	


--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID)	

DECLARE @SQL		VARCHAR(MAX)

SET @SQL = 'SELECT	P.TypeId, 
					P.SonNum,  
					P.usercode, 
                    ISNULL((SUM(o.Qty)),0) AS Qty,
                    CASE WHEN SUM(o.Qty) = 0  THEN 0
					  ELSE ISNULL(SUM(o.Total),0)/SUM(o.Qty) END AS Price,
					--ISNULL((SUM(o.Price)),0) AS Price,
					ISNULL((SUM(o.Total)),0) AS Total,
					u1.fullname AS basename,
					dbo.F_GetCustomAssist(P.TypeId,ISNULL((SUM(o.Qty)),0)) AS customassistantunit
			FROM	PType P '+dbo.F_GetPtypeUnitsAndRates('p','1','1')
		SET @SQL+='	
			LEFT JOIN (
					   SELECT	inout.PtypeId,
								SUM(inout.Price) AS Price,
								SUM(inout.Qty) AS Qty,
								SUM(inout.Total) AS Total
						FROM OtherInOutBill inout
						INNER JOIN BillIndex b ON b.BillNumberId = inout.BillNumberId
						INNER JOIN #GetManSTypeId S ON S.TypeId = inout.Stypeid
						INNER JOIN #GetManKTypeId K ON K.TypeId = inout.KtypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = b.DTypeId
						INNER JOIN #GetManBTypeId bi ON bi.TypeId = b.dealBTypeId
						INNER JOIN #GetManETypeId e  ON e.TypeId =b.etypeid
						INNER JOIN #GetManPTypeId p ON p.TypeId = inout.PtypeId'
						IF @businessid!=''
						 BEGIN
							SET @SQL+='	inner join  dbo.f_split('''+@businessid+''', '','') JJ on b.OtherInOutType= JJ.a'
					     END
					SET @SQL+='	WHERE	B.BillDate>='''+@StartDate+'''
						AND B.BillDate<='''+@EndDate+'''							
						AND B.RedWord = 0
						AND b.draft=0
				        AND b.ifcheck=''t''
						AND b.ifYearBill=0'	 --年节存标志		
IF @BillType = 'OUTTYPE'
	SET @SQL = @SQL + 'AND B.BillType = 202'

IF @BillType = 'INTYPE'
	SET @SQL = @SQL + 'AND B.BillType = 201'
	
--IF @BillType = 'INOUTTYPE'
--	SET @SQL = @SQL + 'AND B.BillType in (201,202)'
	
SET @SQL = @SQL + ' GROUP BY inout.PtypeId )o ON LEFT(o.PTypeId,LEN(P.TypeId)) = P.TypeId 
                    WHERE	P.TypeId LIKE '''+@PTypeId+'%'' 
							AND P.SonNum = 0
							AND	Qty <> 0
					GROUP By P.TypeId,
							 P.SonNum,
							 P.usercode,
							 u1.fullname
					ORDER BY P.usercode ASC'

--SET @SQL=@SQL+ 'group by o.PtypeId,o.BillNumberId'
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Wldz323]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Wldz323]
GO

--=================================================================
--作者：谢吉康
--日期：2004-10-10
--原因：增加是否显示红冲单据的选项
--作者：毛欣蓉
--日期：2011-02-23
--原因：因功能调整，重新编写

--2012-02-20
--郑红霞查询条件中增加经手人

--作者：覃雨翔
--日期：2012-06-04
--原因：9.0版本修改

--日期:2013-06-05
--作者:鲁大林
--描述:应收查询统计零售退货单、业务类型为变卖的固定资产减少单
--		应付查询统计业务类型为购买的固定资产增加单
--*****固定资产类的新单据只有在系统配置固定资产管理模式为卡片时统计*****

--修改：舒珊
--日期：2016年2月26日
--描述：增添表头自定义显示字段


--修改：陈强
--日期：2019年10月17日
--描述：敏捷4681 应收查询-->明细账本 很慢 更改了很多，具体看SVN日志吧
--=================================================================	
CREATE PROCEDURE Gp_Wldz323
(
	@OperatorID 	VARCHAR(100), --操作员ID号
	@nTYpe        	INT=1,      --往来单位类型,1:代表客户 2:代表供应商 3:账龄分析
	@BtypeID      	VARCHAR(MAX),--往来单位typeid
	@DTypeId		VARCHAR(MAX),--部门
	@DtypeIsVisible	INT,--1=使用部门 0=不使用部门
	@StartDate   	VARCHAR(20),--起始日期
	@EndDate    	VARCHAR(20),--截至日期
	@showRedWord	INT=1,--是否显示红冲单据  1.显示   0.不显示
	@STypeId		VARCHAR(MAX),--分支机构
	@ETypeId		VARCHAR(MAX),--职员
	@IncludePre		INT=0,--包含预收
	@CID            INT=0--币种
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--分支机构
CREATE TABLE #SType(TypeId VARCHAR(50))
CREATE NONCLUSTERED INDEX CIX_SType_TypeId ON #SType(TypeId)

INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--结算单位
CREATE TABLE #BType(TypeId VARCHAR(50))
CREATE NONCLUSTERED INDEX CIX_BType_TypeId ON #BType(TypeId)

INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BtypeID,2,@OperatorID)

--账龄分析，和应收应付查询的明细存储过程是一个 部门是公用的
CREATE TABLE #DType(TypeId VARCHAR(50))
CREATE NONCLUSTERED INDEX CIX_DType_TypeId ON #DType(TypeId)

IF @DtypeIsVisible = 1 AND @dtypeid <> '' AND @nTYpe <> 3
	INSERT #DType(typeid) SELECT TypeId FROM F_GetAllBaseTypeId(@DTypeId,9)
ELSE
	INSERT INTO #DType SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--固定资产管理模式。0：项目；1：卡片
DECLARE @Assets VARCHAR(2)
SELECT @Assets= SubValue FROM sysdata WHERE SubNo=732

DECLARE @SQLS VARCHAR(max)
	
--统计开票
CREATE TABLE #invoiceQty
(
	id	INT,
	ptypeid VARCHAR(50),
	billnumberid NUMERIC(24,0),
	billtype INT,
	uninvoiceqty NUMERIC(24,10),
	uninvoicemoney NUMERIC(24,10),
	nuninvoicemoney NUMERIC(24,10) --原币
)
CREATE NONCLUSTERED INDEX CIX_invoiceQty_TypeId ON #invoiceQty(ptypeid,billnumberid)

DECLARE 
	@SQL VARCHAR(max),
	@preSql1	VARCHAR(MAX)='', --应收增加条件
	@npreSql1   VARCHAR(MAX)='',
	@preSql2	VARCHAR(MAX)='', --应收减少条件
	@npreSql2   VARCHAR(MAX)='',
	@AtypeType	VARCHAR(MAX)='',  --要查询的科目
	@CIDWhere	VARCHAR(MAX)='',--币种
	@GroupBy	VARCHAR(2000)=''--分组条件
	
IF @CID<>0
	SET @CIDWhere='	AND L.CID='+CONVERT(VARCHAR,@CID)

----group 条件----------
IF @showRedWord = 0
BEGIN
	SET @GroupBy='
		AND L.Audited = 1  
		AND bi.RedWord = 0
	GROUP BY 
		bi.billnumberid,
		bi.billdate,
		L.stypeid,
		L.dtypeid,
		bi.billcode,
		bi.billtype,
		bi.comment,
		L.atypeid,
		bi.redword,
		bi.rate,
		acc.rate,
		acc.fullname,
		L.BillType  '
END
ELSE
BEGIN
	SET @GroupBy='
	GROUP BY 
		bi.billnumberid,
		bi.billdate,
		L.stypeid,
		L.dtypeid,
		bi.billcode,
		bi.billtype,
		bi.comment ,
		L.atypeid,
		bi.redword,
		bi.rate,
		ACC.Rate,
		acc.fullname,
		L.BillType '
END

IF @nType=1 OR @nTYpe=3 --应收
BEGIN
	IF @IncludePre=1--包含预收
	BEGIN
		SET @AtypeType='''987'',''2131'''
		SET @preSql1='	WHEN AC.UserCode=''2131'' AND l.Total<0  AND bi.redword IN(0,1) AND L.BILLTYPE<>213 THEN ABS(l.Total) 
						WHEN AC.UserCode=''2131'' AND l.Total>0  AND bi.redword=2 AND L.BILLTYPE<>213 THEN -l.Total'
		IF @assets=1
			SET @preSql1+='	WHEN AC.UserCode=''2131'' AND l.Total<0  AND bi.redword IN(0,1) AND L.BILLTYPE=213 AND at.AuditType=7 THEN ABS(l.Total) 
							WHEN AC.UserCode=''2131'' AND l.Total>0  AND bi.redword=2 AND L.BILLTYPE=213 AND at.AuditType=7 THEN -l.Total
		'

		SET @npreSql1='	WHEN AC.UserCode=''2131'' AND l.NTotal<0  AND bi.redword IN(0,1) AND L.BILLTYPE<>213 THEN ABS(l.NTotal) 
						WHEN AC.UserCode=''2131'' AND l.NTotal>0  AND bi.redword=2 AND L.BILLTYPE<>213 THEN -l.NTotal'
		
		IF @assets=1
			SET @npreSql1+=' WHEN AC.UserCode=''2131'' AND l.NTotal<0  AND bi.redword IN(0,1) AND L.BILLTYPE=213 AND at.AuditType=7 THEN ABS(l.NTotal) 
							WHEN AC.UserCode=''2131'' AND l.NTotal>0  AND bi.redword=2 AND L.BILLTYPE=213 AND at.AuditType=7 THEN -l.NTotal '

		SET @preSql2='	WHEN AC.UserCode=''2131'' AND l.Total>0 AND bi.redword IN(0,1) AND L.BILLTYPE<>213 THEN l.Total 
						WHEN AC.UserCode=''2131'' AND l.Total<0  AND bi.redword=2 AND L.BILLTYPE<>213 THEN l.Total'		
		IF @assets=1
			SET @preSql2+='	WHEN AC.UserCode=''2131'' AND l.Total>0 AND bi.redword IN(0,1) AND L.BILLTYPE=213 AND at.AuditType=7 THEN l.Total 
							WHEN AC.UserCode=''2131'' AND l.Total<0  AND bi.redword=2 AND L.BILLTYPE=213 AND at.AuditType=7 THEN l.Total'
					
					
		SET @npreSql2='	WHEN AC.UserCode=''2131'' AND l.NTotal>0 AND bi.redword IN(0,1) AND L.BILLTYPE<>213 THEN l.NTotal 
						WHEN AC.UserCode=''2131'' AND l.NTotal<0  AND bi.redword=2 AND L.BILLTYPE<>213 THEN l.NTotal'
		
		IF @assets=1
			SET @npreSql2+=' WHEN AC.UserCode=''2131'' AND l.NTotal>0 AND bi.redword IN(0,1) AND L.BILLTYPE=213 AND at.AuditType=7 THEN l.NTotal 
							WHEN AC.UserCode=''2131'' AND l.NTotal<0  AND bi.redword=2 AND L.BILLTYPE=213 AND at.AuditType=7 THEN l.NTotal '
	END
	ELSE
	BEGIN
	   SET @AtypeType='''987'''
	END
	
	SET @SQL='
	SELECT	
		bi.billnumberid,
		bi.billdate,
		L.stypeid,
		L.dtypeid,
		bi.billcode,
		bi.billtype,
		bi.comment,
		SUM(CASE  
			WHEN l.billtype IN(45,215,11,160,405,12,46,424,426)  AND AC.UserCode=''987'' THEN l.Total
			WHEN AC.UserCode=''987'' AND l.Total>0 AND l.BillType NOT IN(45,11,215,213,160,405,12,46,424,426,4) AND bi.RedWord IN(0,1) THEN l.Total 
			WHEN AC.UserCode=''987'' AND l.Total<0 AND l.BillType NOT IN(45,11,215,213,160,405,12,46,424,426,4) AND bi.RedWord=2 THEN l.Total 
		'
		IF @assets=1
		SET @SQL+='	WHEN  AC.UserCode=''987'' AND l.Total>0 AND l.BillType=213 AND at.AuditType=7 AND bi.RedWord IN(0,1) THEN l.Total
					WHEN  AC.UserCode=''987'' AND l.Total<0 AND l.BillType=213 AND at.AuditType=7 AND bi.RedWord=2 THEN l.Total'
		SET @SQL+=@preSql1+'
				ELSE 0 END) AS addtotal,
		SUM(CASE  
				WHEN l.billtype IN (45,215,11,160,405,12,46,424,426) AND AC.UserCode=''987'' THEN ISNULL(l.NTotal,0)
				WHEN AC.UserCode=''987'' AND l.NTotal>0 AND l.BillType NOT IN(45,11,215,160,213,405,12,46,424,426,4) AND bi.RedWord IN(0,1) THEN ISNULL(l.NTotal,0) 
				WHEN  AC.UserCode=''987'' AND l.NTotal<0 AND l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.RedWord=2 THEN ISNULL(l.NTotal,0) 
		'
		
		IF @assets=1
		SET @SQL+='	WHEN AC.UserCode=''987'' AND l.NTotal>0 AND l.BillType=213 AND at.AuditType=7 AND bi.RedWord IN(0,1) THEN ISNULL(l.NTotal,0)
					WHEN AC.UserCode=''987'' AND l.NTotal<0 AND l.BillType=213 AND at.AuditType=7 AND bi.RedWord=2 THEN ISNULL(l.NTotal,0)'
		SET @SQL+=@npreSql1+'
				ELSE 0 END) AS naddtotal,
		SUM(CASE WHEN l.BillType=4 AND AC.UserCode=''987'' AND bi.redword IN(0,1) THEN (CASE WHEN l.Total<0 THEN abs(l.Total) ELSE -l.Total END)
				 WHEN l.BillType=4 AND AC.UserCode=''987'' AND bi.redword IN(2)   THEN (CASE WHEN l.Total<0 THEN abs(l.Total) ELSE -l.Total END)
				WHEN AC.UserCode=''987'' AND l.Total<0 AND  l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.redword IN(0,1) THEN abs(l.Total)
				WHEN AC.UserCode=''987'' AND l.Total>0 AND  l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.redword IN(2) THEN -l.Total 
		'
		
		IF @assets=1
			SET @SQL+='	WHEN AC.UserCode=''987'' AND l.Total<0 AND  l.BillType=213 AND at.AuditType=7 AND bi.redword IN(0,1) THEN abs(l.Total)
						WHEN  AC.UserCode=''987'' AND l.Total>0 AND  l.BillType=213 AND at.AuditType=7 AND bi.redword IN(2) THEN -l.Total'
		SET @SQL+=@preSql2+'
				ELSE 0 END) AS rectotal,
		SUM(CASE WHEN l.BillType=4 AND AC.UserCode=''987'' AND bi.redword IN(0,1) THEN (CASE WHEN l.NTotal<0 THEN abs(l.NTotal) ELSE -l.NTotal END)
				 WHEN l.BillType=4 AND AC.UserCode=''987'' AND bi.redword IN(2)   THEN (CASE WHEN l.NTotal<0 THEN abs(l.NTotal) ELSE -l.NTotal END)
				WHEN AC.UserCode=''987'' AND l.NTotal<0 AND  l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.redword IN(0,1) THEN abs(l.NTotal)
				WHEN AC.UserCode=''987'' AND l.NTotal>0 AND  l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.redword IN(2) THEN -l.NTotal 
		'
		
		IF @assets=1
		SET @SQL+='	WHEN AC.UserCode=''987'' AND l.NTotal<0 AND  l.BillType=213 AND at.AuditType=7 AND bi.redword IN(0,1) THEN abs(l.NTotal)
					WHEN AC.UserCode=''987'' AND l.NTotal>0 AND  l.BillType=213 AND at.AuditType=7 AND bi.redword IN(2) THEN -l.NTotal '
		SET @SQL+=@npreSql2+'
				ELSE 0 END) AS nrectotal,
		bi.redword,
		CASE WHEN L.BillType=159 THEN ACC.rate ELSE bi.rate END rate,
		ACC.fullname AS cfullname,
		sum( isnull(bi.totalqty ,0)  ) as qty
	FROM(
		SELECT    
			AssetBusinessTypeId,
			ifYearBill ,
			Rate ,
			Comment ,
			BillNumberId ,
			BillDate ,
			BillCode ,
			BillType ,
			atypeid ,
			btypeid ,
			etypeid ,
			ktypeid ,
			ifcheck ,
			totalmoney ,
			totalinmoney ,
			RedWord ,
			draft ,
			preferencemoney ,
			DTypeId,
			case when redword in (0,1) then isnull(totalqty ,0) else -isnull(totalqty ,0) end  as totalqty
		FROM dbo.BillIndex
		WHERE
			BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			AND ifYearBill= 0
		UNION ALL
		SELECT    
			0 AssetBusinessTypeId ,
			IfYearBill ,
			Rate ,
			Comment ,
			BillNumberID ,
			BillDate ,
			BillCode ,
			BillType ,
			ATypeID ,
			BTypeID ,
			ETypeID ,
			InKTypeId ,
			IfCheck,
			TotalMoney ,
			TotalInMoney ,
			RedWord ,
			Draft ,
			0 preferencemoney ,
			DTypeID,
			case when redword in (0,1) then isnull(totalqty ,0) else -isnull(totalqty ,0) end  as totalqty
		FROM dbo.Coupon_BillIndex
		WHERE
			BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			AND ifYearBill= 0
	) BI 	
	INNER JOIN ListTable L ON L.billnumberid=bi.billnumberid and l.billtype=bi.billtype
	INNER JOIN AC_Items AC ON L.AtypeId=AC.nid
	INNER JOIN AC_Currency ACC ON ACC.CID=L.CID
	INNER JOIN #stype s on L.StypeId=s.typeid
	INNER JOIN #dtype d ON d.typeid = L.DTypeID 
	INNER JOIN #btype b ON b.typeid=L.btypeid 
	LEFT JOIN Ac_AssetBusinessType at on at.id=bi.AssetBusinessTypeId
	WHERE L.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' AND
		AC.UserCode IN ('+@AtypeType+') '
	
	SET @SQL+=@CIDWhere+@GroupBy
	
	------------------------------------------------普通单据end--------------------------------------
	------发票
	IF @IncludePre=1--包含预收
		BEGIN
		  SET @preSql1='	WHEN  AC.UserCode=''2131'' AND l.Total<0  AND bi.redword IN(0,1) AND L.BILLTYPE<>213 THEN ABS(l.Total) 
							WHEN  AC.UserCode=''2131'' AND l.Total>0  AND bi.redword=2 AND L.BILLTYPE<>213 THEN -l.Total'

		  SET @npreSql1='	WHEN  AC.UserCode=''2131'' AND l.NTotal<0  AND bi.redword IN(0,1) AND L.BILLTYPE<>213 THEN ABS(l.NTotal) 
							WHEN  AC.UserCode=''2131'' AND l.NTotal>0  AND bi.redword=2 AND L.BILLTYPE<>213 THEN -l.NTotal'

		   SET @preSql2='	WHEN  AC.UserCode=''2131'' AND l.Total>0 AND bi.redword IN(0,1) AND L.BILLTYPE<>213 THEN l.Total 
							WHEN  AC.UserCode=''2131'' AND l.Total<0  AND bi.redword=2 AND L.BILLTYPE<>213 THEN l.Total'
					
		   SET @npreSql2='	WHEN  AC.UserCode=''2131'' AND l.NTotal>0 AND bi.redword IN(0,1) AND L.BILLTYPE<>213 THEN l.NTotal 
							WHEN  AC.UserCode=''2131'' AND l.NTotal<0  AND bi.redword=2 AND L.BILLTYPE<>213 THEN l.NTotal'
		END
			
	SET @SQL+='
	UNION ALL
	SELECT	
		bi.billnumberid,
		bi.billdate,
		L.stypeid,
		L.dtypeid,
		bi.billcode,
		bi.billtype,
		bi.comment,
		SUM(CASE  
				WHEN l.billtype IN(45,215,11,160,405,12,46)  AND AC.UserCode=''987'' THEN l.Total
				WHEN AC.UserCode=''987'' AND l.Total>0 AND l.BillType NOT IN(45,215,213,11,160,405,12,46,424,426,4) AND bi.RedWord IN(0,1) THEN l.Total 
				WHEN AC.UserCode=''987'' AND l.Total<0 AND l.BillType NOT IN(45,11,215,213,160,405,12,46,424,426,4) AND bi.RedWord=2 THEN l.Total 
		'
		SET @SQL+=@preSql1+'
				ELSE 0 END) AS addtotal,
		SUM(CASE  
				WHEN l.billtype IN (45,215,11,160,405) AND AC.UserCode=''987'' THEN ISNULL(l.NTotal,0)
				WHEN AC.UserCode=''987'' AND l.NTotal>0 AND l.BillType NOT IN(45,11,215,160,213,405,12,46,424,426,4) AND bi.RedWord IN(0,1) THEN ISNULL(l.NTotal,0) 
				WHEN  AC.UserCode=''987'' AND l.NTotal<0 AND l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.RedWord=2 THEN ISNULL(l.NTotal,0) 
		'
		SET @SQL+=@npreSql1+'
				ELSE 0 END) AS naddtotal,
		SUM(CASE WHEN l.BillType=4 AND AC.UserCode=''987'' AND bi.redword IN(0,1) THEN (CASE WHEN l.Total<0 THEN abs(l.Total) ELSE -l.Total END)
				 WHEN l.BillType=4 AND AC.UserCode=''987'' AND bi.redword IN(2)   THEN (CASE WHEN l.Total<0 THEN abs(l.Total) ELSE -l.Total END)
				 WHEN AC.UserCode=''987'' AND l.Total<0 AND  l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.redword IN(0,1) THEN abs(l.Total)
				 WHEN AC.UserCode=''987'' AND l.Total>0 AND  l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.redword IN(2) THEN -l.Total 
		 '
		 SET @SQL+=@preSql2+'
				ELSE 0 END) AS rectotal,
		SUM(CASE WHEN l.BillType=4 AND AC.UserCode=''987'' AND bi.redword IN(0,1) THEN (CASE WHEN l.NTotal<0 THEN abs(l.NTotal) ELSE -l.NTotal END)
				 WHEN l.BillType=4 AND AC.UserCode=''987'' AND bi.redword IN(2)   THEN (CASE WHEN l.NTotal<0 THEN abs(l.NTotal) ELSE -l.NTotal END)
				 WHEN AC.UserCode=''987'' AND l.NTotal<0 AND  l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.redword IN(0,1) THEN abs(l.NTotal)
				 WHEN AC.UserCode=''987'' AND l.NTotal>0 AND  l.BillType NOT IN(45,11,160,215,213,405,12,46,424,426,4) AND bi.redword IN(2) THEN -l.NTotal 
		 '
		 SET @SQL+=@npreSql2+'
				ELSE 0 END) AS nrectotal,
		bi.redword,
		CASE WHEN L.BillType=159 THEN ACC.rate ELSE bi.rate END rate,
		ACC.fullname AS cfullname,
		sum( case when bi.redword in (0,1) then isnull(bi.totalqty ,0) else -isnull(bi.totalqty ,0) end ) as qty
	FROM ReceiptBillIndex bi
	INNER JOIN ListTable L on L.billnumberid=bi.billnumberid and L.billtype=bi.billtype
	INNER JOIN AC_Items AC ON L.AtypeId=AC.nid AND AC.UserCode IN ('+@AtypeType+') 
	INNER JOIN #stype s on L.StypeId=s.typeid
	INNER JOIN #dtype d ON d.typeid = L.DTypeID 
	INNER JOIN AC_Currency ACC ON ACC.CID=L.CID
	INNER JOIN #btype b ON b.typeid=L.btypeid
	WHERE
		L.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
		AND bi.ifYearBill= 0 '    --年节存标志
		
	SET @SQL+=@CIDWhere+@GroupBy
-----------------------------------------------------发票end-----------------------------------------	
END
ELSE--应付
BEGIN
	IF @IncludePre=1--包含预付
	BEGIN
		SET @AtypeType='''2121'',''1151'''

		SET @preSql1='	WHEN  AC.UserCode=''1151'' AND l.Total<0  AND bi.redword IN(0,1) AND L.BILLTYPE<>212 THEN ABS(l.Total) 
						WHEN  AC.UserCode=''1151'' AND l.Total>0  AND bi.redword=2 AND L.BILLTYPE<>212 THEN -l.Total'
		IF @assets=1
			SET @preSql1+='	WHEN  AC.UserCode=''1151'' AND l.Total<0  AND bi.redword IN(0,1) AND L.BILLTYPE=212 AND at.AuditType IN (1,2) THEN ABS(l.Total) 
							WHEN  AC.UserCode=''1151'' AND l.Total>0  AND bi.redword=2 AND L.BILLTYPE=212 AND at.AuditType IN (1,2) THEN -l.Total'
		
		SET @npreSql1='	WHEN  AC.UserCode=''1151'' AND l.NTotal<0  AND bi.redword IN(0,1) AND L.BILLTYPE<>212 THEN ABS(l.NTotal) 
						WHEN  AC.UserCode=''1151'' AND l.NTotal>0  AND bi.redword=2 AND L.BILLTYPE<>212 THEN -l.NTotal'   
		IF @assets=1
			SET @npreSql1+=' WHEN  AC.UserCode=''1151'' AND l.NTotal<0  AND bi.redword IN(0,1) AND L.BILLTYPE=212 AND at.AuditType IN (1,2) THEN ABS(l.NTotal) 
							 WHEN  AC.UserCode=''1151'' AND l.NTotal>0  AND bi.redword=2 AND L.BILLTYPE=212 AND at.AuditType IN (1,2) THEN -l.NTotal '


		SET @preSql2='	WHEN  AC.UserCode=''1151'' AND l.Total>0 AND bi.redword IN(0,1) AND L.BILLTYPE<>212 THEN l.Total 
						WHEN  AC.UserCode=''1151'' AND l.Total<0  AND bi.redword=2 AND L.BILLTYPE<>212 THEN l.Total'
		
		IF @assets=1
			SET @preSql2+=' WHEN  AC.UserCode=''1151'' AND l.Total>0 AND bi.redword IN(0,1) AND L.BILLTYPE=212 AND at.AuditType IN (1,2) THEN l.Total 
							WHEN  AC.UserCode=''1151'' AND l.Total<0  AND bi.redword=2 AND L.BILLTYPE=212 AND at.AuditType IN (1,2) THEN l.Total'
				
		
		SET @npreSql2='	WHEN  AC.UserCode=''1151'' AND l.NTotal>0 AND bi.redword IN(0,1) AND L.BILLTYPE<>212 THEN l.NTotal 
						WHEN  AC.UserCode=''1151'' AND l.NTotal<0  AND bi.redword=2 AND L.BILLTYPE<>212 THEN l.NTotal'
		
		IF @assets=1
			SET @npreSql2+=' WHEN  AC.UserCode=''1151'' AND l.NTotal>0 AND bi.redword IN(0,1) AND L.BILLTYPE=212 AND at.AuditType IN (1,2) THEN l.NTotal 
							 WHEN  AC.UserCode=''1151'' AND l.NTotal<0  AND bi.redword=2 AND L.BILLTYPE=212 AND at.AuditType IN (1,2) THEN l.NTotal '

	END
	ELSE
	BEGIN
		SET @AtypeType='''2121'''
	END
	
	SET  @SQL='
	SELECT	
		bi.billnumberid,
		bi.billdate,
		L.stypeid,
		L.dtypeid,
		bi.billcode,
		bi.billtype,
		bi.comment,
		SUM(CASE  
				WHEN l.billtype IN (6,34,161,404,423) AND AC.UserCode=''2121'' THEN l.Total
				WHEN AC.UserCode=''2121'' AND l.Total>0 AND l.BillType NOT IN(6,212,34,161,404,423,66) AND bi.redword IN (0,1) THEN l.Total 
				WHEN AC.UserCode=''2121'' AND l.Total<0 AND l.BillType NOT IN(6,212,34,161,404,423,66) AND bi.redword=2 THEN l.Total 
		'
		IF @assets=1
			SET @SQL+='	WHEN  AC.UserCode=''2121'' AND l.Total>0 AND l.BillType=212 AND at.AuditType IN (1,2) AND bi.RedWord IN(0,1) THEN l.Total
						WHEN  AC.UserCode=''2121'' AND l.Total<0 AND l.BillType=212 AND at.AuditType IN (1,2) AND bi.RedWord=2 THEN l.Total'
		SET @SQL+=@preSql1+'
				ELSE 0 END) AS addtotal,
		SUM(CASE  
				WHEN l.billtype IN(6,34,161,404,423) AND AC.UserCode=''2121'' THEN l.NTotal
				WHEN AC.UserCode=''2121'' AND l.NTotal>0 AND l.BillType NOT IN(6,212,34,161,404,423,66) AND bi.redword IN (0,1) THEN l.NTotal 
				WHEN AC.UserCode=''2121'' AND l.NTotal<0 AND l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword=2 THEN l.NTotal 
		'
		
		IF @assets=1
			SET @SQL+='	WHEN  AC.UserCode=''2121'' AND l.NTotal>0 AND l.BillType=212 AND at.AuditType IN (1,2) AND bi.redword IN (0,1) THEN l.NTotal 
						WHEN  AC.UserCode=''2121'' AND l.NTotal<0 AND l.BillType=212 AND at.AuditType IN (1,2) AND bi.redword=2 THEN l.NTotal'
		SET @SQL+=@npreSql1+'
				ELSE 0 END) AS naddtotal,
		SUM(CASE WHEN l.BillType=66 AND AC.UserCode=''2121'' AND bi.redword IN(0,1) THEN (CASE WHEN l.Total<0 THEN abs(l.Total) ELSE -l.Total END)
				 WHEN l.BillType=66 AND AC.UserCode=''2121'' AND bi.redword IN(2)   THEN (CASE WHEN l.Total<0 THEN abs(l.Total) ELSE -l.Total END)
				 WHEN AC.UserCode=''2121'' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword IN (0,1) THEN abs(l.Total)
				 WHEN AC.UserCode=''2121'' AND l.Total>0 AND  l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword=2 THEN -l.Total 
		'
		
		IF @assets=1
		SET @SQL+='	WHEN  AC.UserCode=''2121'' AND l.Total<0 AND  l.BillType=212 AND at.AuditType IN (1,2) AND bi.redword IN (0,1) THEN abs(l.Total)
					WHEN  AC.UserCode=''2121'' AND l.Total>0 AND  l.BillType=212 AND at.AuditType IN (1,2) AND bi.redword=2 THEN -l.Total'
		SET @SQL+=@preSql2+'
				else 0 END) as rectotal,
		SUM(CASE WHEN l.BillType=66 AND AC.UserCode=''2121'' AND bi.redword IN(0,1) THEN (CASE WHEN l.NTotal<0 THEN abs(l.NTotal) ELSE -l.NTotal END)
				 WHEN l.BillType=66 AND AC.UserCode=''2121'' AND bi.redword IN(2)   THEN (CASE WHEN l.NTotal<0 THEN abs(l.NTotal) ELSE -l.NTotal END)
				 WHEN  AC.UserCode=''2121'' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword IN (0,1) THEN ABS(l.NTotal)
				 WHEN  AC.UserCode=''2121'' AND l.NTotal>0 AND  l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword=2 THEN -l.NTotal 
		'
		IF @assets=1
			SET @SQL+='	WHEN  AC.UserCode=''2121'' AND l.Total<0 AND  l.BillType=212 AND at.AuditType IN (1,2) AND bi.redword IN (0,1) THEN abs(l.NTotal)
						WHEN  AC.UserCode=''2121'' AND l.Total>0 AND  l.BillType=212 AND at.AuditType IN (1,2) AND bi.redword=2 THEN -l.NTotal'
		SET @SQL+=@npreSql2+'
			ELSE 0 END) AS nrectotal,
		bi.redword,
		CASE WHEN L.BillType=159 THEN ACC.rate WHEN L.BillType<>181 THEN bi.rate ELSE NULL END AS rate,
		CASE WHEN L.BillType<>181 THEN ACC.fullname ELSE NULL END AS cfullname	,
		sum( isnull(bi.totalqty ,0)) as qty
	FROM (
		SELECT    
			AssetBusinessTypeId,
			ifYearBill ,
			Rate ,
			Comment ,
			BillNumberId ,
			BillDate ,
			BillCode ,
			BillType ,
			atypeid ,
			btypeid ,
			etypeid ,
			ktypeid ,
			ifcheck ,
			totalmoney ,
			totalinmoney ,
			RedWord ,
			draft ,
			preferencemoney ,
			DTypeId,
			case when redword in (0,1) then isnull(totalqty ,0) else -isnull(totalqty ,0) end  as totalqty
		FROM dbo.BillIndex
		WHERE
			BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			AND ifYearBill= 0
		UNION ALL
		SELECT    
			0 AssetBusinessTypeId ,
			IfYearBill ,
			Rate ,
			Comment ,
			BillNumberID ,
			BillDate ,
			BillCode ,
			BillType ,
			ATypeID ,
			BTypeID ,
			ETypeID ,
			InKTypeId ,
			IfCheck,
			TotalMoney ,
			TotalInMoney ,
			RedWord ,
			Draft ,
			0 preferencemoney ,
			DTypeID,
			case when redword in (0,1) then isnull(totalqty ,0) else -isnull(totalqty ,0) end  as totalqty
		FROM dbo.Coupon_BillIndex
		WHERE
			BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			AND ifYearBill= 0
	) BI 
	INNER JOIN ListTable L ON L.billnumberid=bi.billnumberid and L.billtype=bi.billtype
	INNER JOIN AC_Items AC ON L.AtypeId=AC.nid 
	INNER JOIN #stype s on L.StypeId=s.typeid
	INNER JOIN #dtype d ON d.typeid = L.DTypeID
	INNER JOIN #btype b ON b.typeid=L.btypeid  
	INNER JOIN AC_Currency ACC ON ACC.CID=L.CID 
	left join Ac_AssetBusinessType at on at.id=bi.AssetBusinessTypeId
	WHERE L.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' AND
		AC.UserCode IN ('+@AtypeType+')'    --年节存标志

	SET @SQL+=@CIDWhere+@GroupBy
    -------------------------------------------普通单据end------------------------------------
    
   
    -------------------------------------------发票start---------------------------------------
	IF @IncludePre=1--包含预付
		BEGIN
			SET @AtypeType='''2121'',''1151'''

			SET @preSql1='	WHEN  AC.UserCode=''1151'' AND l.Total<0  AND bi.redword IN(0,1) AND L.BILLTYPE<>212 THEN ABS(l.Total)
							WHEN  AC.UserCode=''1151'' AND l.Total>0  AND bi.redword=2 AND L.BILLTYPE<>212 THEN -l.Total'

			SET @npreSql1='	WHEN  AC.UserCode=''1151'' AND l.NTotal<0  AND bi.redword IN(0,1) AND L.BILLTYPE<>212 THEN ABS(l.NTotal)
							WHEN  AC.UserCode=''1151'' AND l.NTotal>0  AND bi.redword=2 AND L.BILLTYPE<>212 THEN -l.NTotal'

			SET @preSql2='  WHEN  AC.UserCode=''1151'' AND l.Total>0 AND bi.redword IN(0,1) AND L.BILLTYPE<>212 THEN l.Total
							WHEN  AC.UserCode=''1151'' AND l.Total<0  AND bi.redword=2 AND L.BILLTYPE<>212 THEN l.Total'

			SET @npreSql2='	WHEN  AC.UserCode=''1151'' AND l.NTotal>0 AND bi.redword IN(0,1) AND L.BILLTYPE<>212 THEN l.NTotal
							WHEN  AC.UserCode=''1151'' AND l.NTotal<0  AND bi.redword=2 AND L.BILLTYPE<>212 THEN l.NTotal'
		END
	
	SET  @SQL=@SQL+'
	UNION ALL
	SELECT	
		bi.billnumberid,
		bi.billdate,
		L.stypeid,
		L.dtypeid,
		bi.billcode,
		bi.billtype,
		bi.comment,
		SUM(CASE  
				WHEN l.billtype IN (6,34,161,404,423) AND AC.UserCode=''2121'' THEN l.Total
				WHEN AC.UserCode=''2121'' AND l.Total>0 AND l.BillType NOT IN(6,212,34,161,404,423,66) AND bi.redword IN (0,1) THEN l.Total 
				WHEN AC.UserCode=''2121'' AND l.Total<0 AND l.BillType NOT IN(6,212,34,161,404,423,66) AND bi.redword=2 THEN l.Total 
		'
		SET @SQL+=@preSql1+'
				ELSE 0 END) AS addtotal,
		SUM(CASE  
				WHEN l.billtype IN(6,34,161,404,423) AND AC.UserCode=''2121'' THEN l.NTotal
				WHEN AC.UserCode=''2121'' AND l.NTotal>0 AND l.BillType NOT IN(6,212,34,161,404,423,66) AND bi.redword IN (0,1) THEN l.NTotal 
				WHEN AC.UserCode=''2121'' AND l.NTotal<0 AND l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword=2 THEN l.NTotal 
		'
		SET @SQL+=@npreSql1+'
				ELSE 0 END) AS naddtotal,
		SUM(CASE WHEN l.BillType=66 AND AC.UserCode=''2121'' AND bi.redword IN(0,1) THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
				 WHEN l.BillType=66 AND AC.UserCode=''2121'' AND bi.redword IN(2)   THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
				 WHEN AC.UserCode=''2121'' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword IN (0,1) THEN abs(l.Total)
				 WHEN AC.UserCode=''2121'' AND l.Total>0 AND  l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword=2 THEN -l.Total 
		'
		SET @SQL+=@preSql2+'
				else 0 END) as rectotal,
		SUM(CASE WHEN l.BillType=66 AND AC.UserCode=''2121'' AND bi.redword IN(0,1) THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
				 WHEN l.BillType=66 AND AC.UserCode=''2121'' AND bi.redword IN(2)   THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
				 WHEN AC.UserCode=''2121'' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword IN (0,1) THEN ABS(l.NTotal)
				 WHEN AC.UserCode=''2121'' AND l.NTotal>0 AND  l.BillType NOT IN(6,34,161,212,404,423,66) AND bi.redword=2 THEN -l.NTotal 
		'
		SET @SQL+=@npreSql2+'
				ELSE 0 END) AS nrectotal,
		bi.redword,
		CASE WHEN L.BillType=159 THEN ACC.rate WHEN L.BillType<>181 THEN bi.rate ELSE NULL END AS rate,
		CASE WHEN L.BillType<>181 THEN ACC.fullname ELSE NULL END AS cfullname	,
		sum( case when bi.redword in (0,1) then isnull(bi.totalqty ,0) else -isnull(bi.totalqty ,0) end ) as qty
	FROM ListTable L
	INNER JOIN ReceiptBillIndex bi on L.billnumberid=bi.billnumberid and L.billtype=bi.billtype
	INNER JOIN AC_Items AC ON L.AtypeId=AC.nid AND AC.UserCode IN ('+@AtypeType+')
	INNER JOIN #stype S on L.StypeId=S.typeid
	INNER JOIN #dtype D ON D.typeid = L.DTypeID 
	INNER JOIN #btype b ON b.typeid=L.btypeid  
	INNER JOIN AC_Currency ACC ON ACC.CID=L.CID '

	SET @SQL+=' 
	WHERE	
		L.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
		AND bi.ifYearBill= 0 '    --年节存标志

	SET @SQL+=@CIDWhere+@GroupBy
END


CREATE table #CenterTable
(
	billnumberid  NUMERIC(24,0),
	billdate datetime,
	stypeid nvarchar(256),
	dtypeid nvarchar(256),
	billcode nvarchar(100),
	billtype nvarchar(50),
	comment nvarchar(2000),
	addtotal NUMERIC(24,10),
	naddtotal NUMERIC(24,10),
	rectotal NUMERIC(24,10),
	nrectotal NUMERIC(24,10),
	redword int,
	rate NUMERIC(24,10),
	cfullname nvarchar(100),
	qty NUMERIC(24,10)
)
CREATE NONCLUSTERED INDEX CIX_CenterTable_TypeId ON #CenterTable(billnumberid)

SET @SQLS='INSERT INTO #CenterTable
(
	billnumberid,
	billdate,
	stypeid,
	dtypeid,
	billcode,
	billtype,
	comment,
	addtotal,
	naddtotal,
	rectotal,
	nrectotal,
	redword,
	rate,
	cfullname,
	qty
) select b.billnumberid,
	b.billdate,
	b.stypeid,
	b.dtypeid,
	b.billcode,
	b.billtype,
	b.comment,
	b.addtotal,
	b.naddtotal,
	b.rectotal,
	b.nrectotal,
	b.redword,
	b.rate,
	b.cfullname,
	b.qty from ('+@SQL+') b'

exec(@SQLS)

SET @SQLS='
INSERT INTO #invoiceQty
(
	id,
	ptypeid,
	billnumberid,
	billtype,
	uninvoiceqty,
	uninvoicemoney,
	nuninvoicemoney
) 
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
		400,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN AppraisalBill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    401,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b	
INNER JOIN  AppraisalBackBill a on b.billnumberId=a.billnumberId  
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    402,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN SendBill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    403,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN SendBackBill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	

UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    305,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN retailbill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    215,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN RetailBackBill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    11,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN salebill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    45,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN salebackbill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN salegoodsexchangebill a on b.billnumberId=a.billnumberId 
where a.InOrOut=''I''
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN salegoodsexchangebill a on b.billnumberId=a.billnumberId 
where a.InOrOut=''O''
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    141,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN commissionbill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    12,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN PT_Combin_SaleBillDetail a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    46,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN PT_Combin_SaleBackBillDetail a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    34,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN buybill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id		
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    6,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN buybackbill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN buygoodsexchangebill a on b.billnumberId=a.billnumberId 
where A.InOrOut=''O''
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN buygoodsexchangebill a on b.billnumberId=a.billnumberId 
where A.InOrOut=''I''
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    145,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM #CenterTable  b
INNER JOIN commissionbill a on b.billnumberId=a.billnumberId 
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	'
	
exec (@SQLS)


SET @SQL='
SELECT	R.*,
	Case when R.billtype=12 THEN
		case when  R.RedWord IN(0,1) then  isnull(R.Qty,0) else -isnull(R.Qty,0) end
		ELSE
		case when  R.RedWord IN(0,1) then  isnull(inv.uninvoiceqty,0) else -isnull(inv.uninvoiceqty,0) end 
	END as uninvoiceqty ,
    case when  R.RedWord IN(0,1) then isnull(inv.uninvoicemoney,0) else -isnull(inv.uninvoicemoney,0) end as uninvoicemoney ,
	case when  R.RedWord IN(0,1) then isnull(inv.nuninvoicemoney ,0) else -isnull(inv.nuninvoicemoney,0) end as  nuninvoicemoney,
	SysDiy1_head,
	SysDiy2_head,
	SysDiy3_head,
	SysDiy4_head, 
	SysDiy5_head,
	SysDiy6_head,
	SysDiy7_head,
	SysDiy8_head,
	SysDiy9_head,
	SysDiy10_head,
	SysDiy11_head,
	SysDiy12_head,
	SysDiy13_head,
	SysDiy14_head,
	SysDiy15_head,
	SysDiy16_head,
	SysDiy17_head,
	SysDiy18_head,
	SysDiy19_head,
	SysDiy20_head,
	SysDiy21_head,
	SysDiy22_head,
	SysDiy23_head,
	SysDiy24_head,
	SysDiy25_head,
	SysDiy26_head,
	SysDiy27_head,
	SysDiy28_head,
	SysDiy29_head,
	SysDiy30_head,
	SysDiy31_head,
	SysDiy32_head,
	SysDiy33_head,
	SysDiy34_head,
	SysDiy35_head,
	SysDiy36_head,
	SysDiy37_head,
	SysDiy38_head,
	SysDiy39_head,
	SysDiy40_head
FROM #CenterTable R 
LEFT JOIN Custom_BillIndex csindex on R.billnumberid=csindex.BillId and R.billtype=csindex.billtype
left join  (select  billnumberid, 
					billtype,
					SUM(uninvoiceqty) as uninvoiceqty,
					sum(uninvoicemoney) as uninvoicemoney ,
					sum(nuninvoicemoney) as nuninvoicemoney 
			FROM #invoiceQty 
			GROUP by billnumberid,billtype  
			) inv on R.billtype=inv.billtype and R.billnumberid=inv.billnumberid
ORDER BY billdate,billnumberid'


EXEC (@SQL)

DROP TABLE #stype,#btype,#dtype,#invoiceQty,#CenterTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/*	
*	仓库物流单据 处理引用状态
*/
IF  EXISTS (SELECT * FROM SysObjects WHERE ID = OBJECT_ID(N'[Gp_WLUpdateBillState]',N'P') )
BEGIN
	DROP PROCEDURE [dbo].[Gp_WLUpdateBillState]
END
GO

CREATE  PROCEDURE [dbo].[Gp_WLUpdateBillState]
(
	@BillNumberID INT,
	@BillType	  INT
)

AS
BEGIN
	/*拣货单、运输配送单、上架单*/
	IF @BillType NOT IN(412,413,414) RETURN 0
	DECLARE		@GoodsBillNumberID INT,					/*出库单单据编号*/
				@GoodsBillType     INT,					/*出库单单据类型*/
				@RowIndex          INT,					
				@RowCount          INT,					/*运输单明细行数*/
				@Return            INT,					/*返回值*/
				@TbName            VARCHAR(100),		/*出库单明细表	*/
				@CheckSQL          NVARCHAR(MAX)		/*验证发货数量SQL*/
	DECLARE	    @Tmp			   TABLE
	(
		GoodsBillNumberID INT,
		GoodsBillType     INT,
		RowIndex          INT
	)
	/*上架单*/
	IF @BillType=412
	BEGIN
		INSERT INTO @Tmp(GoodsBillNumberID,GoodsBillType,RowIndex)
		SELECT
			   GoodsBillNumberID,
			   GoodsBillType,
			   ROW_NUMBER() OVER (ORDER BY GETDATE()) 
		FROM onShelvesbill WHERE BillNumberID=@BillNumberID
		GROUP BY GoodsBillNUmberID,GoodsBillType
		SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
		
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @GoodsBillNumberID=GoodsBillNumberID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
			SELECT @TbName=detailTable FROM BillName WHERE Billtype=@GoodsBillType
			
			SET @CheckSQL =N'IF EXISTS(SELECT 1 FROM ' +@TbName+'  A
			INNER JOIN PType P ON A.PTypeID=P.TypeID WHERE P.IsService=0 AND A.Qty>ISNULL(A.InflowQty,0) AND BillNumberID=@GoodsBillNumberID '+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''I''' ELSE ''END+') SET @Return=0 ELSE SET @Return=1'

			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@GoodsBillType INT ,@Return INT OUT',@GoodsBillNumberID,@GoodsBillType,@Return OUT
			--PRINT(@CheckSQL)
			UPDATE dbo.BillIndex SET ShelveRefState=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@GoodsBillNumberID
			SET @RowIndex=@RowIndex+1
		END
		RETURN 0
	END
	/*拣货单*/
	IF @BillType=413
	BEGIN
		INSERT INTO @Tmp(GoodsBillNumberID,GoodsBillType,RowIndex)
		SELECT
			   GoodsBillNumberID,
			   GoodsBillType,
			   ROW_NUMBER() OVER (ORDER BY GETDATE()) 
		FROM PickBill WHERE BillNumberID=@BillNumberID
		GROUP BY GoodsBillNUmberID,GoodsBillType
		SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
		
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @GoodsBillNumberID=GoodsBillNumberID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
			SELECT @TbName=detailTable FROM BillName WHERE Billtype=@GoodsBillType
			
			SET @CheckSQL ='IF EXISTS(SELECT 1 FROM ' +@TbName+'  A
			INNER JOIN PType P ON A.PTypeID=P.TypeID WHERE P.IsService=0 AND A.Qty>ISNULL(A.PickedQty,0) AND BillNumberID=@GoodsBillNumberID '+CASE WHEN @GoodsBillType IN(16,160,161) THEN  ' AND InOrOut=''O''' ELSE ''END+') SET @Return=0 ELSE SET @Return=1'

			exec sp_executesql @CheckSQL,N'@GoodsBillNumberID INT,@GoodsBillType INT,@Return INT OUT',@GoodsBillNumberID,@GoodsBillType,@Return OUT
			UPDATE dbo.BillIndex SET citestate=CASE WHEN @Return=1 THEN 2 ELSE 1 END WHERE BillNumberId=@GoodsBillNumberID
			SET @RowIndex=@RowIndex+1
		END
		RETURN 0
	END
	/*运输配送单*/
	IF @BillType=414
	BEGIN
		INSERT INTO @Tmp(GoodsBillNumberID,GoodsBillType,RowIndex)
		SELECT
			   GoodsBillNumberID,
			   GoodsBillType,
			   ROW_NUMBER() OVER (ORDER BY GETDATE()) 
		FROM dbo.Transportbill WHERE BillNumberID=@BillNumberID
		GROUP BY GoodsBillNUmberID,GoodsBillType
		SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
		
		WHILE(@RowIndex<=@RowCount)
		BEGIN
			SELECT @GoodsBillNumberID=GoodsBillNumberID FROM @Tmp WHERE RowIndex=@RowIndex
			
			IF EXISTS(SELECT 1 FROM PickBill A LEFT JOIN 
				(
					SELECT SUM(Qty) AS Qty,GoodsBillID FROM Transportbill A INNER JOIN BillIndex B 
					ON A.BillNumberID=B.BillNumberID 
					WHERE A.GoodsBillNumberID=@GoodsBillNumberID AND B.RedWord=0 AND B.ifcheck='t'
					GROUP BY GoodsBillID 
				)B ON A.ID=B.GoodsBillID 
				INNER JOIN PType P ON A.PTypeID=P.TypeID 
				WHERE P.IsService=0 AND A.Qty<>ISNULL(B.Qty,0) AND BillNumberID=@GoodsBillNumberID
			)
			BEGIN
				UPDATE dbo.onShelvespickIndex SET citestate=1 WHERE BillNumberId=@GoodsBillNumberID
			END
			ELSE 
			BEGIN
				UPDATE dbo.onShelvespickIndex SET citestate=2 WHERE BillNumberID=@GoodsBillNumberID
			END
			
			IF EXISTS(SELECT 1 FROM PickBill A LEFT JOIN 
				(
					SELECT SUM(Qty) AS Qty,GoodsBillID FROM Transportbill A INNER JOIN BillIndex B 
					ON A.BillNumberID=B.BillNumberID 
					WHERE A.GoodsBillNumberID=@GoodsBillNumberID AND B.RedWord=0 AND B.ifcheck='t'
					GROUP BY GoodsBillID 
				)B ON A.ID=B.GoodsBillID 
				INNER JOIN PType P ON A.PTypeID=P.TypeID 
				WHERE P.IsService=0 AND A.Qty<ISNULL(B.Qty,0) AND BillNumberID=@GoodsBillNumberID
			)
			BEGIN
				RETURN -4151
			END
			SET @RowIndex=@RowIndex+1
		END
		RETURN 0
	END
END
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_WmsBillToExpenseBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_WmsBillToExpenseBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：glj
	日期：2018-10-30
	描述：wms生成ERP单据费用单
*/
CREATE PROCEDURE Gp_WmsBillToExpenseBill
( 
	@wmsBillNumberId	NUMERIC(24,0),
	@STypeId			VARCHAR(50),--分支机构
	@OperatorId			VARCHAR(50),--当前操作员
	@DefualtEtypeId		VARCHAR(50),--默认经手人
	@BillType			INT--单据类型
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN created
SAVE TRAN createbill	

DECLARE
	@ErrorCount	INT=0,
	@wms_BillCode VARCHAR(200),
	@wms_BTypeId VARCHAR(50),
	@wms_ETypeId VARCHAR(50),--经手人
	@wms_Comment	VARCHAR(1000),
	@wms_Explain	VARCHAR(1000),
	@wms_Atypeid	VARCHAR(50),
		
	@BTypeId VARCHAR(50),
	@ETypeId VARCHAR(50),
	@DTypeId VARCHAR(50),
	@ATypeId	VARCHAR(50),--往来单位
	@BillATypeId VARCHAR(50),
	@BrandTypeId	VARCHAR(50)=''--默认其他品牌
	
IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND  SubValue='1')--启用品牌
	SET @BrandTypeId='00001'
	
--判断是否存在
IF NOT EXISTS(SELECT TOP 1 1 FROM WMSOrderIndex WHERE BillNumberID=@wmsBillNumberId)
	BEGIN
		SELECT 'error' [type], CAST(@wmsBillNumberId AS VARCHAR(50))+'单据不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
SELECT 
	@wms_BillCode=BillCode,
	@wms_BTypeId=BtypeId,
	@wms_ETypeId=ETypeId,
	@wms_Comment='单据来源：WMS '+Summary,
	@wms_Explain=Comment,
	@wms_Atypeid=atypeid
FROM WMSOrderIndex
WHERE BillNumberID=@wmsBillNumberId

--判断是否已经生成ERP草稿
IF EXISTS(SELECT TOP 1 1 FROM WMS_ERPBillRelation R WHERE R.WMS_BillNumberID=@wmsBillNumberId AND R.BillType=@BillType AND R.RedWord=0)
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！已经存在生成ERP单据！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--往来单位
SELECT @BTypeId=D.typeId FROM WmsErpBTypeContrastSetting F 
INNER JOIN btype D ON F.WMS_TypeId=@wms_BTypeId AND D.typeId=F.ERP_TypeId
IF(ISNULL(@BTypeId,'')='')
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！收费单位对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--经手人
IF(@wms_ETypeId NOT IN('0',''))
	BEGIN
		SELECT @ETypeId=D.typeId,@DTypeId=D.DtypeID FROM WmsErpEmployeeContrastSetting F 
		INNER JOIN employee D ON F.WMS_TypeId=@wms_ETypeId AND D.typeId=F.ERP_TypeId
		IF(ISNULL(@ETypeId,'')='')
			BEGIN
				SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！经手人对照关系不存在！' Msg
				ROLLBACK TRAN createbill
				COMMIT TRAN created
				RETURN
			END
	END
ELSE 
	BEGIN
		SELECT @ETypeId=typeId,@DTypeId=DtypeID FROM employee WHERE typeId=@DefualtEtypeId
	END

--判断收款项目
IF @wms_Atypeid NOT IN('0','') 
	BEGIN
		SELECT @BillATypeId=D.nId FROM WmsErpItemContrastSetting F 
		INNER JOIN Ac_Items D ON F.WMS_TypeId=@wms_Atypeid AND D.nTypeId=F.ERP_TypeId
		IF(ISNULL(@BillATypeId,'')='')
			BEGIN
				SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！收款项目对照关系不存在！' Msg
				ROLLBACK TRAN createbill
				COMMIT TRAN created
				RETURN
			END
	END

--判断项目
IF EXISTS(SELECT TOP 1 1 FROM WMSExpenseBill D WHERE BillNumberID=@wmsBillNumberId AND NOT EXISTS(SELECT * FROM WmsErpItemContrastSetting F  WHERE F.WMS_TypeId=D.ATypeId AND F.ERP_TypeId<>''))
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 明细中存在项目对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END

--往来单位
CREATE TABLE #Atype(TypeId VARCHAR(50),FullName VARCHAR(200),Flag varchar(10))
INSERT INTO #Atype(TypeId,FullName,Flag)
EXEC dbo.Web_GetAtype @BillType,@STypeId
SELECT @ATypeId=TypeId FROM #Atype

DECLARE 
	@BillDate		VARCHAR(10),
	@BillCode		VARCHAR(200),
	@BillNumberId	NUMERIC(24, 10)=0 ,
	@DAY			VARCHAR(MAX),
	@MONTH			VARCHAR(MAX),
	@cefullname		VARCHAR(500)='',
	@dfullname		VARCHAR(500)=''
		
--取当前时间
SET @BillDate=CONVERT(VARCHAR(10),GETDATE(),120)
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
	
--是否自定义单据编号
IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =@BillType)
BEGIN
	SELECT @MONTH = FullName  FROM employee WHERE typeId=@ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = ''
	SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId =@OperatorId
	SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId =@DTypeId
END
--生成单据编号
EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'FY',@BillDate,@STypeId,@BillCode OUT,@dfullname,@cefullname,-999

--主表数据写入
EXEC @BillNumberId=Gp_InsertBillIndex 
		@BillDate=@BillDate,
		@BillCode=@BillCode,
		@BillType=@BillType,
		@Comment=@wms_Comment,
		@ATypeID='',
		@PTypeID='',
		@BTypeID=@BTypeId,
		@ETypeID=@ETypeId,
		@KTypeID='',
		@KTypeID2='',
		@IfCheck='f',
		@CheckE=@OperatorId,
		@TotalMoney=0,
		@TotalQty=0,
		@TotalInMoney=0,
		@Tax='0',
		@szPeriod=1,
		@Explain=@wms_Explain,
		@Draft='True',
		@RedWord='False',
		@OrderID=0,
		@WayBillCode='',
		@Goodsnumber='',
		@PackWay='',
		@Tel='',
		@preferencemoney=0,
		@AlertDay=9999,
		@Assessor='',
		@IfAudit='',
		@Audit_Explain='',
		@Dtypeid=@DTypeId,
		@VipCardID=-1,
		@KTypeID3='',
		@LinkMan='',
		@LinkTel='',
		@LinkAddr='',
		@wxManID='',
		@JieJianBillNumberID=-1,
		@JieJianID=-1,
		@BaoXiuBillNumberID=-1,
		@BaoXiuID=-1,
		@BuyDate='',
		@Serial='',
		@wxTotal=0,
		@ErrDes='',
		@ifHideJieJian=0,
		@ifWX=0,
		@IfBargainOn=0,
		@STypeID=@stypeid,
		@FromBillNumberID=0,
		@CostSale=0,
		@completedate='9999-12-31 23:59:59',
		@billstate=1,
		@ifmulaccount=0,
		@vipczmoney=0,
		@otherinouttype=-1,
		@czbeforetimes=0,
		@posbilltype=0,
		@TransportId=0,
		@IsFreightMoney=0,
		@FreightAddr=NULL,
		@freightperson=NULL,
		@freighttel=NULL,
		@ShareMode=0,
		@uf1='',
		@uf2='',
		@uf3='',
		@uf4='',
		@uf5='',
		--9.0新字段
		@dealbtypeid=@BTypeId,		--结算单位
		@cid=1,			--外币币种id
		@rate=1,			--汇率
		@ntotalmoney=0,		--原币种金额
		@ntotalinmoney=0,	--原币收现金额
		@npreferencemoney=0,	--原币优惠金额
		@nvipczmoney=0,		--原币会员卡充值金额
		@atypeid1=@ATypeId,
		@billproperty=-1,					--单据属性
		@ncompletetotal	=0,		--原币结算金额
		@isini=0,
		@ATID=0,					--过账模板
		@CompleteTotal=0,
		@IfCargo=0,
		@IfInvoice=0,
		@promoruleid=0,
		@beforepromobillnumberid=0,
		@promotionmsg='',
		@isyapi=0,
		@yapiorderid=0	,
		@DeliveryAddress='',
		@Discount=0,
		@AdpriceType=0,	
		@checkSave='bill_allow_save'
		
 IF @BillNumberId = -1 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 试用版最多录200条单据！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -2 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期小于本期开始日期！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -3 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 校验错误！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -4
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期必须与当前日期一致！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--保存单据编号的种子数
EXEC GP_SaveBillCode_Seed @BillNumberId,@BillDate,@BillType,@BillCode
SELECT @ErrorCount+=@@ERROR

--明细表数据写入
INSERT INTO MoneyBill 
(
	BillNumberId,
	AtypeId,
	total,
	Comment,
	Stypeid,
	ntotal,
	DTypeId,
	ETypeId,
	ShowOrder,
	DraftFlag,
	IsIniFlag,
	BrandarTypeId
)
SELECT
	@BillNumberId BillNumberId,
	I.nId ATypeId,
	D.Total,
	D.Comment,
	@STypeId Stypeid,
	dbo.F_RoundTotal(D.Total) ntotal,
	@DTypeId,
	@ETypeId,
	RANK()OVER(ORDER BY D.DId) ShowOrder,
	1 DraftFlag,
	0 IsIniFlag,
	@BrandTypeId BrandarTypeID
FROM WMSExpenseBill D
INNER JOIN WmsErpItemContrastSetting F ON F.WMS_TypeId=D.ATypeId
INNER JOIN Ac_Items I ON I.nTypeId=F.ERP_TypeId
WHERE D.BillNumberID=@wmsBillNumberId
ORDER BY D.DId
SELECT @ErrorCount+=@@ERROR


--=================修改billindex主表金额、数量【BEGIN】===================	
DECLARE @TotalMoney	NUMERIC(24,10)=0
	
--明细行总数量/总金额
SELECT @TotalMoney=dbo.F_RoundTotal(SUM(total)) FROM MoneyBill where BillNumberID=@BillNumberId
SELECT @ErrorCount+=@@ERROR	

--修改主表金额、数量
UPDATE BillIndex 
SET 
	TotalMoney=@TotalMoney,
	NTotalMoney=@TotalMoney,
	ATypeID=@BillATypeId,
	IsUploadWms=1,
	isbybrandartype=CASE WHEN ISNULL(@BrandTypeId,'')='' THEN 0 ELSE 1 END
WHERE BillNumberId=@BillNumberId
SELECT @ErrorCount+=@@ERROR	

--=================修改billindex主表金额、数量【END】===================	

--=================判断是否收款【BEGIN】===================
IF (@wms_Atypeid NOT IN('0',''))
	BEGIN
		UPDATE BillIndex SET totalinmoney=@TotalMoney,NTotalInMoney=@TotalMoney WHERE BillNumberId=@BillNumberId
		SELECT @ErrorCount+=@@ERROR	

		INSERT INTO BillMulAccount(BillNumberId,ATypeID,Total,Comment,BillType,TradeNo,PayType,yhType,CouponCode,VipTotal,NTotalMoney,VipCardID,paymoney)VALUES(@BillNumberId,@BillATypeId,@TotalMoney,'',@BillType,'',0,-1,'',0,@TotalMoney,-1,0)
		SELECT @ErrorCount+=@@ERROR		
	
		INSERT INTO BillMulBrand(STypeID,BTypeID,BrandarTypeID,BillNumberId,BillType,Cid,Rate,TaxTotal,NTaxTotal,PreferenceMoney,NPreferenceMoney,TotalInMoney,NTotalInMoney,YSTotalInMoney,NYSTotalInMoney,TheOrderARTotal,NTheOrderARTotal,isIni)VALUES(@STypeId,@BTypeId,@BrandTypeId,@BillNumberId,@BillType,1,1,@TotalMoney,@TotalMoney,0,0,@TotalMoney,@TotalMoney,0,0,0,0,0)		
		SELECT @ErrorCount+=@@ERROR	
	END
--=================判断是否收款【END】===================


--保存关联关系
INSERT INTO WMS_ERPBillRelation(WMS_BillNumberID,BillType,ERP_BillNumberID,ERP_BillCode,ERP_BillType)
VALUES(@wmsBillNumberId,@BillType,@BillNumberId,@BillCode,@BillType)
SELECT @ErrorCount+=@@ERROR

IF(@ErrorCount=0)
	BEGIN
		COMMIT TRAN createbill
		
		--过账处理		
		IF EXISTS(SELECT * FROM WMSBaseInfo WHERE Field='autodraftbill' AND Value=0)
			BEGIN
				DECLARE @voucherMsg VARCHAR(MAX)=''
				EXEC @ErrorCount= dbo.Gp_Auditing 
							@nBillID = @BillNumberId, -- numeric
							@szCheckMan = @OperatorId, -- varchar(50)
							@szPID = '', -- varchar(1000)
							@chvOpID = @OperatorId, -- varchar(50)
							@KTypeID = '', -- varchar(50)
							@billtype = @BillType, -- int
							@voucherMsg = @voucherMsg, -- varchar(50)
							@vipcentinfo='',
							@AssetMsg=''
							
				IF(@ErrorCount=0)
					SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode Msg
				ELSE 
					SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode++'过账失败！失败原因'+@voucherMsg Msg								
			END
		ELSE
			SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode Msg
		
		COMMIT TRAN created
	END
ELSE 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！出现异常！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
	END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_WmsBillToGatherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_WmsBillToGatherBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：glj
	日期：2018-10-230
	描述：wms生成ERP单据收款单
*/
CREATE PROCEDURE Gp_WmsBillToGatherBill
( 
	@wmsBillNumberId	NUMERIC(24,0),
	@STypeId			VARCHAR(50),--分支机构
	@OperatorId			VARCHAR(50),--当前操作员
	@DefualtEtypeId		VARCHAR(50),--默认经手人
	@BillType			INT--单据类型
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRAN created
SAVE TRAN createbill	

DECLARE
	@ErrorCount	INT=0,
	@ErrorMsg VARCHAR(MAX)='',
	@wms_BillCode VARCHAR(200),
	@wms_BTypeId VARCHAR(50),
	@wms_ETypeId VARCHAR(50),--经手人
	@wms_Comment	VARCHAR(1000),
	@wms_Explain	VARCHAR(1000),
		
	@BTypeId VARCHAR(50),
	@ETypeId VARCHAR(50),
	@DTypeId VARCHAR(50),
	@ATypeId	VARCHAR(50),--往来单位
	@BrandTypeId	VARCHAR(50)=''--默认其他品牌

IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND  SubValue='1')--启用品牌
	SET @BrandTypeId='00001'

--判断是否存在
IF NOT EXISTS(SELECT TOP 1 1 FROM WMSOrderIndex WHERE BillNumberID=@wmsBillNumberId)
	BEGIN
		SELECT 'error' [type], CAST(@wmsBillNumberId AS VARCHAR(50))+'单据不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
SELECT 
	@wms_BillCode=BillCode,
	@wms_BTypeId=BtypeId,
	@wms_ETypeId=ETypeId,
	@wms_Comment='单据来源：WMS '+Summary,
	@wms_Explain=Comment
FROM WMSOrderIndex
WHERE BillNumberID=@wmsBillNumberId

--判断是否已经生成ERP草稿
IF EXISTS(SELECT TOP 1 1 FROM WMS_ERPBillRelation R WHERE R.WMS_BillNumberID=@wmsBillNumberId AND R.BillType=@BillType AND R.RedWord=0)
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！已经存在生成ERP单据！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END

--往来单位
SELECT @BTypeId=D.typeId FROM WmsErpBTypeContrastSetting F 
INNER JOIN btype D ON F.WMS_TypeId=@wms_BTypeId AND D.typeId=F.ERP_TypeId
IF(ISNULL(@BTypeId,'')='')
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！往来单位对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--经手人
IF(@wms_ETypeId NOT IN('0','') )
	BEGIN
		SELECT @ETypeId=D.typeId,@DTypeId=D.DtypeID FROM WmsErpEmployeeContrastSetting F 
		INNER JOIN employee D ON F.WMS_TypeId=@wms_ETypeId AND D.typeId=F.ERP_TypeId
		IF(ISNULL(@ETypeId,'')='')
			BEGIN
				SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！经手人对照关系不存在！' Msg
				ROLLBACK TRAN createbill
				COMMIT TRAN created
				RETURN
			END
	END
ELSE
	BEGIN
		SELECT @ETypeId=typeId,@DTypeId=DtypeID FROM employee WHERE typeId=@DefualtEtypeId
	END

--判断项目
IF EXISTS(SELECT TOP 1 1 FROM WMSGatherBill D WHERE BillNumberID=@wmsBillNumberId AND NOT EXISTS(SELECT * FROM WmsErpItemContrastSetting F  WHERE F.WMS_TypeId=D.ATypeId AND F.ERP_TypeId<>''))
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 明细中存在项目对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END

--往来科目
CREATE TABLE #Atype(TypeId VARCHAR(50),FullName VARCHAR(200),Flag varchar(10))
INSERT INTO #Atype(TypeId,FullName,Flag)
EXEC dbo.Web_GetAtype @BillType,@STypeId
SELECT @ATypeId=TypeId FROM #Atype

DECLARE 
	@BillDate		VARCHAR(10),
	@BillCode		VARCHAR(200),
	@BillNumberId	NUMERIC(24, 10) ,
	@DAY			VARCHAR(MAX),
	@MONTH			VARCHAR(MAX),
	@cefullname		VARCHAR(500)='',
	@dfullname		VARCHAR(500)=''

--取当前时间
SET @BillDate=CONVERT(VARCHAR(10),GETDATE(),120)
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
	
--是否自定义单据编号
IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =@BillType)
BEGIN
	SELECT @MONTH = typeid  FROM employee WHERE typeId=@ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = ''
	SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId =@OperatorId
	SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId =@DTypeId
END
--生成单据编号
EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'XS',@BillDate,@STypeId,@BillCode OUT,@dfullname,@cefullname,-999

EXEC @BillNumberId=Gp_InsertBillIndex 
		@BillDate=@BillDate,
		@BillCode=@BillCode,
		@BillType=@BillType,
		@Comment=@wms_Comment,
		@ATypeID='',
		@PTypeID='',
		@BTypeID=@BTypeId,
		@ETypeID=@ETypeId,
		@KTypeID='',
		@KTypeID2='',
		@IfCheck='f',
		@CheckE=@OperatorId,
		@TotalMoney=0,
		@TotalQty=0,
		@TotalInMoney=0,
		@Tax='0',
		@szPeriod=1,
		@Explain=@wms_Explain,
		@Draft='True',
		@RedWord='False',
		@OrderID=0,
		@WayBillCode='',
		@Goodsnumber='',
		@PackWay='',
		@Tel='',
		@preferencemoney=0,
		@AlertDay=9999,
		@Assessor='',
		@IfAudit='',
		@Audit_Explain='',
		@Dtypeid=@DTypeId,
		@VipCardID=-1,
		@KTypeID3='',
		@LinkMan='',
		@LinkTel='',
		@LinkAddr='',
		@wxManID='',
		@JieJianBillNumberID=-1,
		@JieJianID=-1,
		@BaoXiuBillNumberID=-1,
		@BaoXiuID=-1,
		@BuyDate='',
		@Serial='',
		@wxTotal=0,
		@ErrDes='',
		@ifHideJieJian=0,
		@ifWX=0,
		@IfBargainOn=0,
		@STypeID=@STypeId,
		@FromBillNumberID=0,
		@CostSale=0,
		@completedate='9999-12-31 23:59:59',
		@billstate=1,
		@ifmulaccount=0,
		@vipczmoney=0,
		@otherinouttype=-1,
		@czbeforetimes=0,
		@posbilltype=0,
		@TransportId=0,
		@IsFreightMoney=0,
		@FreightAddr=NULL,
		@freightperson=NULL,
		@freighttel=NULL,
		@ShareMode=0,
		@uf1='',
		@uf2='',
		@uf3='',
		@uf4='',
		@uf5='',
		--9.0新字段
		@dealbtypeid=@BTypeId,		--结算单位
		@cid=1,			--外币币种id
		@rate=1,			--汇率
		@ntotalmoney=0,		--原币种金额
		@ntotalinmoney=0,	--原币收现金额
		@npreferencemoney=0,	--原币优惠金额
		@nvipczmoney=0,		--原币会员卡充值金额
		@atypeid1=@ATypeId,
		@billproperty=-1,					--单据属性
		@ncompletetotal	=0,		--原币结算金额
		@isini=0,
		@ATID=0,					--过账模板
		@CompleteTotal=0,
		@IfCargo=0,
		@IfInvoice=0,
		@promoruleid=0,
		@beforepromobillnumberid=0,
		@promotionmsg='',
		@isyapi=0,
		@yapiorderid=0	,
		@DeliveryAddress='',
		@Discount=0,
		@AdpriceType=0,	
		@checkSave='bill_allow_save'
		
 IF @BillNumberId = -1 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 试用版最多录200条单据！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -2 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期小于本期开始日期！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -3 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 校验错误！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -4
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期必须与当前日期一致！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END

--保存单据编号的种子数
EXEC GP_SaveBillCode_Seed @BillNumberId,@BillDate,@BillType,@BillCode
SELECT @ErrorCount+=@@ERROR
--明细表数据写入
INSERT INTO gatheringbill 
(
	BillNumberId,
	AtypeId,
	total,
	Comment,
	Stypeid,
	ntotal,
	ShowOrder,
	DraftFlag,
	IsIniFlag,
	PreferenceMoney,
	nPreferenceMoney,
	VipCardID,
	RelevanceBillId,
	BrandarTypeID
)
SELECT
	@BillNumberId BillNumberId,
	I.nId ATypeId,
	D.Total,
	D.Comment,
	@STypeId Stypeid,
	dbo.F_RoundTotal(D.Total) ntotal,
	RANK()OVER(ORDER BY D.DId) ShowOrder,
	1 DraftFlag,
	0 IsIniFlag,
	0 PreferenceMoney,
	0 nPreferenceMoney,
	-1 VipCardID,
	0 RelevanceBillId,
	@BrandTypeId BrandarTypeID
FROM WMSGatherBill D
INNER JOIN WmsErpItemContrastSetting F ON F.WMS_TypeId=D.ATypeId
INNER JOIN Ac_Items I ON I.nTypeId=F.ERP_TypeId
WHERE D.BillNumberID=@wmsBillNumberId
ORDER BY D.DId
SELECT @ErrorCount+=@@ERROR

--=================修改billindex主表金额、数量【BEGIN】===================	
DECLARE @TotalMoney	NUMERIC(24,10)=0
	
--明细行总数量/总金额
SELECT @TotalMoney=dbo.F_RoundTotal(SUM(total)) FROM gatheringBill where BillNumberID=@BillNumberId
SELECT @ErrorCount+=@@ERROR	

--修改主表金额、数量
UPDATE BillIndex 
SET 
	TotalMoney=@TotalMoney,
	NTotalMoney=@TotalMoney,
	totalinmoney=@TotalMoney,
	NTotalInMoney=@TotalMoney,
	IsUploadWms=1,
	isbybrandartype=CASE WHEN ISNULL(@BrandTypeId,'')='' THEN 0 ELSE 1 END
 WHERE BillNumberId=@BillNumberId
SELECT @ErrorCount+=@@ERROR	
--=================修改billindex主表金额、数量【END】===================	

--保存关联关系
INSERT INTO WMS_ERPBillRelation(WMS_BillNumberID,BillType,ERP_BillNumberID,ERP_BillCode,ERP_BillType)
VALUES(@wmsBillNumberId,@BillType,@BillNumberId,@BillCode,@BillType)
SELECT @ErrorCount+=@@ERROR


IF(@ErrorCount=0)
	BEGIN
		COMMIT TRAN createbill
		
		--过账处理		
		IF EXISTS(SELECT * FROM WMSBaseInfo WHERE Field='autodraftbill' AND Value=0)
			BEGIN
				DECLARE @voucherMsg VARCHAR(MAX)=''
				EXEC @ErrorCount= dbo.Gp_Auditing 
							@nBillID = @BillNumberId, -- numeric
							@szCheckMan = @OperatorId, -- varchar(50)
							@szPID = '', -- varchar(1000)
							@chvOpID = @OperatorId, -- varchar(50)
							@KTypeID = '', -- varchar(50)
							@billtype = @BillType, -- int
							@voucherMsg = @voucherMsg, -- varchar(50)
							@vipcentinfo='',
							@AssetMsg=''
							
				IF(@ErrorCount=0)
					SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode Msg
				ELSE 
					SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode++'过账失败！失败原因'+@voucherMsg Msg								
			END
		ELSE
			SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode Msg
		
		COMMIT TRAN created
	END
ELSE 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！出现异常！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_WmsBillToSaleBackBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_WmsBillToSaleBackBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：glj
	日期：2018-10-230
	描述：wms生成ERP销售退货单
*/
CREATE PROCEDURE Gp_WmsBillToSaleBackBill
( 
	@wmsBillNumberId	NUMERIC(24,0),
	@OperatorId			VARCHAR(50),--当前操作员
	@DefualtEtypeId		VARCHAR(50),--默认经手人
	@BillType			INT--单据类型
)
--@encode$--
AS
SET NOCOUNT ON
	
BEGIN TRAN created
SAVE TRAN createbill	

--判断是否存在
IF NOT EXISTS(SELECT TOP 1 1 FROM WMSOrderIndex WHERE BillNumberID=@wmsBillNumberId)
	BEGIN
		SELECT 'error' [type], CAST(@wmsBillNumberId AS VARCHAR(50))+'单据不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
DECLARE 
	@ErrorCount	INT=0,
	@wms_BillCode VARCHAR(200),
	@wms_BTypeId VARCHAR(50),
	@wms_KTypeId VARCHAR(50),
	@wms_ETypeId VARCHAR(50),--经手人
	@wms_Comment	VARCHAR(1000),
	@wms_Explain	VARCHAR(1000),
		
	@STypeId VARCHAR(50),
	@BTypeId VARCHAR(50),
	@KTypeId VARCHAR(50),
	@ETypeId VARCHAR(50),
	@DTypeId VARCHAR(50),
	@ATypeId	VARCHAR(50),--会计科目
	@CargoID	INT,
	@Costing	INT=0--成本计算
	
SELECT @Costing=SubValue FROM SysData WHERE SubName='costing'

SELECT 
	@wms_BillCode=BillCode,
	@wms_BTypeId=BtypeId,
	@wms_KTypeId=KtypeId,
	@wms_ETypeId=ETypeId,
	@wms_Comment='单据来源：WMS '+Summary,
	@wms_Explain=Comment
FROM WMSOrderIndex WHERE BillNumberID=@wmsBillNumberId

--判断是否已经生成ERP草稿
IF EXISTS(SELECT TOP 1 1 FROM WMS_ERPBillRelation R WHERE R.WMS_BillNumberID=@wmsBillNumberId AND R.BillType=@BillType AND R.RedWord=0)
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！已经存在生成ERP单据！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--往来单位
SELECT @BTypeId=D.typeId FROM WmsErpBTypeContrastSetting F 
INNER JOIN btype D ON F.WMS_TypeId=@wms_BTypeId AND D.typeId=F.ERP_TypeId
IF(ISNULL(@BTypeId,'')='')
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！往来单位对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--仓库
SELECT @KTypeId=D.typeId,@STypeId=D.STypeID,@CargoID=G.CargoID FROM WmsErpStockContrastSetting F 
INNER JOIN Stock D ON F.WMS_TypeId=@wms_KTypeId AND D.typeId=F.ERP_TypeId
INNER JOIN CargoType G ON G.KtypeID=D.typeId AND G.IsDefault=1
IF(ISNULL(@KTypeId,'')='')
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！入库仓库对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END

--经手人
IF(@wms_ETypeId NOT IN('0',''))
	BEGIN
		SELECT @ETypeId=D.typeId,@DTypeId=D.DtypeID FROM WmsErpEmployeeContrastSetting F 
		INNER JOIN employee D ON F.WMS_TypeId=@wms_ETypeId AND D.typeId=F.ERP_TypeId
		IF(ISNULL(@ETypeId,'')='')
			BEGIN
				SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！经手人对照关系不存在！' Msg
				ROLLBACK TRAN createbill
				COMMIT TRAN created
				RETURN
			END
	END
ELSE 
	BEGIN
		SELECT @ETypeId=typeId,@DTypeId=DtypeID FROM employee WHERE typeId=@DefualtEtypeId
	END
	

--判断商品
IF EXISTS(SELECT TOP 1 1 FROM WMSSaleBackBill D WHERE D.BillNumberID=@wmsBillNumberId AND NOT EXISTS( SELECT * FROM WmsErpPtypeContrastSetting F  WHERE F.WMS_TypeId=D.PTypeId AND F.WMS_SKUId=D.SKuId AND F.ERP_TypeId<>''))
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！明细中存在商品对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END


--收款科目
CREATE TABLE #Atype(TypeId VARCHAR(50),FullName VARCHAR(200),Flag varchar(10))
INSERT INTO #Atype(TypeId,FullName,Flag)
EXEC dbo.Web_GetAtype @BillType,@STypeId
SELECT @ATypeId=TypeId FROM #Atype

DECLARE 
	@BillDate		VARCHAR(10),
	@BillCode		VARCHAR(200),
	@Qty			NUMERIC(24, 10),
	@BillNumberId	NUMERIC(24, 10)=0 ,
	@DAY			VARCHAR(MAX),
	@MONTH			VARCHAR(MAX),
	@cefullname		VARCHAR(500)='',
	@dfullname		VARCHAR(500)=''

--取当前时间
SET @BillDate=GETDATE()
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
SET @billdate=(SELECT CONVERT (VARCHAR(10),@billdate,120))
	
--是否自定义单据编号
IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =@BillType)
BEGIN
	SELECT @MONTH = typeid  FROM employee WHERE typeId=@ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
	SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId =@OperatorId
	SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId =@DTypeId
END
--生成单据编号
EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'XT',@BillDate,@STypeId,@BillCode OUT,@dfullname,@cefullname,-999

--主表数据写入

EXEC @BillNumberId=Gp_InsertBillIndex 
		@BillDate=@BillDate,
		@BillCode=@BillCode,
		@BillType=@BillType,
		@Comment=@wms_Comment,
		@ATypeID='',
		@PTypeID='',
		@BTypeID=@BTypeId,
		@ETypeID=@ETypeId,
		@KTypeID=@KTypeId,
		@KTypeID2='',
		@IfCheck='f',
		@CheckE=@OperatorId,
		@TotalMoney=0,
		@TotalQty=@Qty,
		@TotalInMoney=0,
		@Tax='0',
		@szPeriod=1,
		@Explain=@wms_Explain,
		@Draft='True',
		@RedWord='False',
		@OrderID=0,
		@WayBillCode='',
		@Goodsnumber='',
		@PackWay='',
		@Tel='',
		@preferencemoney=0,
		@AlertDay=9999,
		@Assessor='',
		@IfAudit='',
		@Audit_Explain='',
		@Dtypeid=@DTypeId,
		@VipCardID=-1,
		@KTypeID3='',
		@LinkMan='',
		@LinkTel='',
		@LinkAddr='',
		@wxManID='',
		@JieJianBillNumberID=-1,
		@JieJianID=-1,
		@BaoXiuBillNumberID=-1,
		@BaoXiuID=-1,
		@BuyDate='',
		@Serial='',
		@wxTotal=0,
		@ErrDes='',
		@ifHideJieJian=0,
		@ifWX=0,
		@IfBargainOn=0,
		@STypeID=@stypeid,
		@FromBillNumberID=0,
		@CostSale=0,
		@completedate='9999-12-31 23:59:59',
		@billstate=1,
		@ifmulaccount=0,
		@vipczmoney=0,
		@otherinouttype=-1,
		@czbeforetimes=0,
		@posbilltype=0,
		@TransportId=0,
		@IsFreightMoney=0,
		@FreightAddr=NULL,
		@freightperson=NULL,
		@freighttel=NULL,
		@ShareMode=0,
		@uf1='',
		@uf2='',
		@uf3='',
		@uf4='',
		@uf5='',
		--9.0新字段
		@dealbtypeid=@BTypeId,		--结算单位
		@cid=1,			--外币币种id
		@rate=1,			--汇率
		@ntotalmoney=0,		--原币种金额
		@ntotalinmoney=0,	--原币收现金额
		@npreferencemoney=0,	--原币优惠金额
		@nvipczmoney=0,		--原币会员卡充值金额
		@atypeid1=@ATypeId,
		@billproperty=-1,					--单据属性
		@ncompletetotal	=0,		--原币结算金额
		@isini=0,
		@ATID=0,					--过账模板
		@CompleteTotal=0,
		@IfCargo=0,
		@IfInvoice=0,
		@promoruleid=0,
		@beforepromobillnumberid=0,
		@promotionmsg='',
		@isyapi=0,
		@yapiorderid=0	,
		@DeliveryAddress='',
		@Discount=1,
		@AdpriceType=0,	
		@checkSave='bill_allow_save'
	
 IF @BillNumberId = -1 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 试用版最多录200条单据！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -2 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期小于本期开始日期！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -3 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 校验错误！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -4
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期必须与当前日期一致！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--保存单据编号的种子数
EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
SELECT @ErrorCount+=@@ERROR	
	
--明细表数据写入
INSERT INTO saleBackBill 
(
	BillNumberId,
	OutFactoryDate ,	--date
	Stypeid ,			--分支机构
	KTypeID ,			--仓库ID
	CargoID,
	PtypeId ,

	Qty ,				--基本数量
	SalePrice ,		--基本单价
	UnitID	,		--基本单位

	MQty ,             --销售数量
	MSalePrice,		--销售单价
	MUnitID	,		--销售单位
	MUnitRate,		--销售换算率

	NQty ,			--浮动数量
	NUnitID	,		--浮动单位
	UnitRate ,		--浮动换算率

	discount,			--折扣率
	Tax	,			--税率
	TaxMoney,			--税额
	DiscountPrice ,	--折后单价，按基本单价算折后
	MDiscountPrice,	--折后单价，按销售单价算折后
	TaxPrice,			--含税价，按基本单价算
	MTaxPrice,		--含税价，按销售单价算

	SaleTotal,		--总金额
	total,			--折后总金额
	TaxTotal,			--价税合计

	NSalePrice,       --原币基本单价
	CurMSalePrice,	--原币销售单价
	NTaxMoney,		--原币税额
	NDiscountPrice,	--原币折后单价
	CurMDiscountPrice,--原币折后单价
	NTaxPrice,        --原币含税价
	CurMTaxPrice,		--原币含税价

	NSaleTotal,
	NTotal,
	NTaxTotal,		  
	IsCombined ,
	ItemID  ,
	PriceSource,
	ETypeID,
	ShowOrder,
	CostPrice,
	GoodsCostPrice
)
SELECT	
	@BillNumberId BillNumberId,
	@BillDate OutFactoryDate ,	--date
	@STypeId Stypeid ,			--分支机构
	@KTypeId KTypeID ,			--仓库ID
	@CargoID CargoID,
	p.typeId PtypeId ,

	dbo.F_RoundQty(d.Qty) Qty ,				--基本数量
	dbo.F_RoundPrice(D.Price) SalePrice ,		--基本单价
	PeX.UnitsId UnitID	,		--基本单位

	dbo.F_RoundQty(d.Qty) MQty ,             --销售数量
	dbo.F_RoundPrice(D.Price) MSalePrice,		--销售单价
	PeX.UnitsId MUnitID	,		--销售单位
	1 MUnitRate,		--销售换算率

	CASE WHEN ISNULL(P.AssistantUnitId,0)=0 THEN 0 ELSE dbo.F_RoundQty(d.Qty/PE.Rate) END NQty ,--浮动数量
	P.AssistantUnitId NUnitID	,		--浮动单位
	PE.Rate UnitRate ,		--浮动换算率

	D.DisCount discount,			--折扣率
	D.Tax Tax,			--税率
	0 TaxMoney,			--税额
	dbo.F_RoundPrice(D.Price) DiscountPrice ,	--折后单价，按基本单价算折后
	dbo.F_RoundPrice(D.Price) MDiscountPrice,	--折后单价，按销售单价算折后
	dbo.F_RoundTotal(D.Price) TaxPrice,			--含税价，按基本单价算
	dbo.F_RoundPrice(D.Price) MTaxPrice,		--含税价，按销售单价算

	dbo.F_RoundTotal(D.Total) SaleTotal,		--总金额
	dbo.F_RoundTotal(D.Total) total,			--折后总金额
	dbo.F_RoundTotal(D.Total) TaxTotal,			--价税合计

	dbo.F_RoundPrice(D.Price) NSalePrice,       --原币基本单价
	dbo.F_RoundPrice(D.Price) CurMSalePrice,	--原币销售单价
	0 NTaxMoney,		--原币税额
	dbo.F_RoundPrice(D.Price) NDiscountPrice,	--原币折后单价
	dbo.F_RoundPrice(D.Price) CurMDiscountPrice,--原币折后单价
	dbo.F_RoundPrice(D.Price) NTaxPrice,        --原币含税价
	dbo.F_RoundPrice(D.Price)CurMTaxPrice,		--原币含税价

	dbo.F_RoundTotal(D.Total) NSaleTotal,
	dbo.F_RoundTotal(D.Total) NTotal,
	dbo.F_RoundTotal(D.Total) NTaxTotal,		  
	ISNULL(P.customitemfrom,0) IsCombined ,
	S.ERP_SKUId ItemID  ,
	'WMS '+@wms_BillCode PriceSource,
	@ETypeId ETypeID,
	RANK()OVER(ORDER BY D.DId) ShowOrder,
	CASE WHEN @Costing=3 THEN -1 ELSE 0 END CostPrice,
	-1 GoodsCostPrice
FROM WMSSaleBackBill D
INNER JOIN WmsErpPtypeContrastSetting S ON S.WMS_TypeId=D.PTypeId AND S.WMS_SKUId=D.SKuId
INNER JOIN ptype P ON P.typeId=S.ERP_TypeId
INNER JOIN PType_Units_Ext PeX ON PeX.PtypeID=P.typeId AND PEX.UnitsId=P.baseUnitId
LEFT JOIN PType_Units_Ext PE ON PE.PtypeID=P.typeId AND  PE.UnitsId=P.AssistantUnitId
LEFT JOIN PType_EntryCode_Ext EXT ON EXT.Ptypeid=P.typeId AND EXT.IsDefaultEntryCode=1
WHERE BillNumberID=@wmsBillNumberId
ORDER BY D.DId
SELECT @ErrorCount+=@@ERROR


--=================修改billindex主表金额、数量【BEGIN】===================	
DECLARE
	@TotalQty	NUMERIC(24,10)=0,
	@TotalMoney	NUMERIC(24,10)=0
	
--明细行总数量/总金额
SELECT @TotalQty=dbo.F_RoundQty(SUM(Qty)),@TotalMoney=dbo.F_RoundTotal(SUM(total)) FROM saleBackBill where BillNumberID=@BillNumberId
SELECT @ErrorCount+=@@ERROR	

--修改主表金额、数量
UPDATE BillIndex SET totalqty=@TotalQty,TotalMoney=@TotalMoney,NTotalMoney=@TotalMoney,IsUploadWms=1 WHERE BillNumberId=@BillNumberId
SELECT @ErrorCount+=@@ERROR	
	
--=================修改billindex主表金额、数量【END】===================		
		
-- 自动生成的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,@billtype
SELECT @ErrorCount+=@@ERROR

--保存关联关系
INSERT INTO WMS_ERPBillRelation(WMS_BillNumberID,BillType,ERP_BillNumberID,ERP_BillCode,ERP_BillType)
VALUES(@wmsBillNumberId,@BillType,@BillNumberId,@BillCode,@BillType)
SELECT @ErrorCount+=@@ERROR

IF(@ErrorCount=0)
	BEGIN
		COMMIT TRAN createbill
		
		--过账处理		
		IF EXISTS(SELECT * FROM WMSBaseInfo WHERE Field='autodraftbill' AND Value=0)
			BEGIN
				DECLARE @voucherMsg VARCHAR(MAX)=''
				EXEC @ErrorCount= dbo.Gp_Auditing 
							@nBillID = @BillNumberId, -- numeric
							@szCheckMan = @OperatorId, -- varchar(50)
							@szPID = '', -- varchar(1000)
							@chvOpID = @OperatorId, -- varchar(50)
							@KTypeID = '', -- varchar(50)
							@billtype = @BillType, -- int
							@voucherMsg = @voucherMsg, -- varchar(50)
							@vipcentinfo='',
							@AssetMsg=''
							
				IF(@ErrorCount=0)
					SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode Msg
				ELSE 
					SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode++'过账失败！失败原因'+@voucherMsg Msg								
			END
		ELSE
			SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode Msg
		
		COMMIT TRAN created
	END
ELSE 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！出现异常！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_WmsBillToSaleBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_WmsBillToSaleBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：glj
	日期：2018-10-230
	描述：wms生成ERP单据
*/
CREATE PROCEDURE Gp_WmsBillToSaleBill
( 
	@wmsBillNumberId	NUMERIC(24,0),
	@OperatorId			VARCHAR(50),--当前操作员
	@DefualtEtypeId		VARCHAR(50),--默认经手人
	@BillType			INT--单据类型
)
--@encode$--
AS
SET NOCOUNT ON
	
BEGIN TRAN created
SAVE TRAN createbill	

--判断是否存在
IF NOT EXISTS(SELECT TOP 1 1 FROM WMSOrderIndex WHERE BillNumberID=@wmsBillNumberId)
	BEGIN
		SELECT 'error' [type], CAST(@wmsBillNumberId AS VARCHAR(50))+'单据不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
DECLARE 
	@ErrorCount	INT=0,
	@wms_BillCode VARCHAR(200),
	@wms_BTypeId VARCHAR(50),
	@wms_KTypeId VARCHAR(50),
	@wms_ETypeId VARCHAR(50),--经手人
	@wms_Total	NUMERIC(24,10),
	@wms_MallFee	NUMERIC(24,10),--商城扣费
	@wms_CustomerFreightFee	NUMERIC(24,10),--买家运费
	@wms_Comment	VARCHAR(1000),
	@wms_Explain	VARCHAR(1000),
		
	@STypeId VARCHAR(50),
	@BTypeId VARCHAR(50),
	@KTypeId VARCHAR(50),
	@ETypeId VARCHAR(50),
	@DTypeId VARCHAR(50),
	@ATypeId	VARCHAR(50),--会计科目
	@CargoID	INT,
	@Costing	INT=0--成本计算
	
SELECT @Costing=SubValue FROM SysData WHERE SubName='costing'

SELECT 
	@wms_BillCode=BillCode,
	@wms_BTypeId=BtypeId,
	@wms_KTypeId=KtypeId,
	@wms_ETypeId=ETypeId,
	@wms_Total=dbo.F_RoundTotal(Total),
	@wms_MallFee=MallFee,
	@wms_CustomerFreightFee=Customerfreightfee,
	@wms_Comment='单据来源：WMS '+Summary,
	@wms_Explain=Comment
FROM WMSOrderIndex WHERE BillNumberID=@wmsBillNumberId

--判断是否已经生成ERP草稿
IF EXISTS(SELECT TOP 1 1 FROM WMS_ERPBillRelation R WHERE R.WMS_BillNumberID=@wmsBillNumberId AND R.BillType=@BillType AND R.RedWord=0)
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！已经存在生成ERP单据！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--往来单位
SELECT @BTypeId=D.typeId FROM WmsErpBTypeContrastSetting F 
INNER JOIN btype D ON F.WMS_TypeId=@wms_BTypeId AND D.typeId=F.ERP_TypeId
IF(ISNULL(@BTypeId,'')='')
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！往来单位对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
	
--仓库
SELECT @KTypeId=D.typeId,@STypeId=D.STypeID,@CargoID=G.CargoID FROM WmsErpStockContrastSetting F 
INNER JOIN Stock D ON F.WMS_TypeId=@wms_KTypeId AND D.typeId=F.ERP_TypeId
INNER JOIN CargoType G ON G.KtypeID=D.typeId AND G.IsDefault=1
IF(ISNULL(@KTypeId,'')='')
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！出库仓库对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END

--经手人
IF(@wms_ETypeId NOT IN('0',''))
	BEGIN
		SELECT @ETypeId=D.typeId,@DTypeId=D.DtypeID FROM WmsErpEmployeeContrastSetting F 
		INNER JOIN employee D ON F.WMS_TypeId=@wms_ETypeId AND D.typeId=F.ERP_TypeId
		IF(ISNULL(@ETypeId,'')='')
			BEGIN
				SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！经手人对照关系不存在！' Msg
				ROLLBACK TRAN createbill
				COMMIT TRAN created
				RETURN
			END
	END
ELSE 
	BEGIN
		SELECT @ETypeId=typeId,@DTypeId=DtypeID FROM employee WHERE typeId=@DefualtEtypeId
	END
	

--判断商品
IF EXISTS(SELECT TOP 1 1 FROM WMSSaleBill D WHERE D.BillNumberID=@wmsBillNumberId AND NOT EXISTS( SELECT * FROM WmsErpPtypeContrastSetting F  WHERE F.WMS_TypeId=D.PTypeId AND F.WMS_SKUId=D.SKuId AND F.ERP_TypeId<>''))
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！明细中存在商品对照关系不存在！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END


--收款科目
CREATE TABLE #Atype(TypeId VARCHAR(50),FullName VARCHAR(200),Flag varchar(10))
INSERT INTO #Atype(TypeId,FullName,Flag)
EXEC dbo.Web_GetAtype @BillType,@STypeId
SELECT @ATypeId=TypeId FROM #Atype

DECLARE 
	@BillDate		VARCHAR(10),
	@BillCode		VARCHAR(200),
	@Qty			NUMERIC(24, 10),
	@BillNumberId	NUMERIC(24, 10)=0 ,
	@DAY			VARCHAR(MAX),
	@MONTH			VARCHAR(MAX),
	@cefullname		VARCHAR(500)='',
	@dfullname		VARCHAR(500)=''
	
--取当前时间
SET @BillDate=GETDATE()
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
SET @billdate=(SELECT CONVERT (VARCHAR(10),@billdate,120))
	
--是否自定义单据编号
IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =@BillType)
BEGIN
	SELECT @MONTH = typeid  FROM employee WHERE typeId=@ETypeId
	SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
	SELECT @cefullname = E.FUllname FROM Employee E WHERE E.TypeId =@OperatorId
	SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId =@DTypeId
END
--生成单据编号
EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'XK',@BillDate,@STypeId,@BillCode OUT,@dfullname,@cefullname,-999

--主表数据写入
EXEC @BillNumberId=Gp_InsertBillIndex 
		@BillDate=@BillDate,
		@BillCode=@BillCode,
		@BillType=@BillType,
		@Comment=@wms_Comment,
		@ATypeID='',
		@PTypeID='',
		@BTypeID=@BTypeId,
		@ETypeID=@ETypeId,
		@KTypeID=@KTypeId,
		@KTypeID2='',
		@IfCheck='f',
		@CheckE=@OperatorId,
		@TotalMoney=0,
		@TotalQty=0,
		@TotalInMoney=0,
		@Tax='0',
		@szPeriod=1,
		@Explain=@wms_Explain,
		@Draft='True',
		@RedWord='False',
		@OrderID=0,
		@WayBillCode='',
		@Goodsnumber='',
		@PackWay='',
		@Tel='',
		@preferencemoney=0,
		@AlertDay=9999,
		@Assessor='',
		@IfAudit='',
		@Audit_Explain='',
		@Dtypeid=@DTypeId,
		@VipCardID=-1,
		@KTypeID3='',
		@LinkMan='',
		@LinkTel='',
		@LinkAddr='',
		@wxManID='',
		@JieJianBillNumberID=-1,
		@JieJianID=-1,
		@BaoXiuBillNumberID=-1,
		@BaoXiuID=-1,
		@BuyDate='',
		@Serial='',
		@wxTotal=0,
		@ErrDes='',
		@ifHideJieJian=0,
		@ifWX=0,
		@IfBargainOn=0,
		@STypeID=@stypeid,
		@FromBillNumberID=0,
		@CostSale=0,
		@completedate='9999-12-31 23:59:59',
		@billstate=1,
		@ifmulaccount=0,
		@vipczmoney=0,
		@otherinouttype=-1,
		@czbeforetimes=0,
		@posbilltype=0,
		@TransportId=0,
		@IsFreightMoney=0,
		@FreightAddr=NULL,
		@freightperson=NULL,
		@freighttel=NULL,
		@ShareMode=0,
		@uf1='',
		@uf2='',
		@uf3='',
		@uf4='',
		@uf5='',
		--9.0新字段
		@dealbtypeid=@BTypeId,		--结算单位
		@cid=1,			--外币币种id
		@rate=1,			--汇率
		@ntotalmoney=0,		--原币种金额
		@ntotalinmoney=0,	--原币收现金额
		@npreferencemoney=0,	--原币优惠金额
		@nvipczmoney=0,		--原币会员卡充值金额
		@atypeid1=@ATypeId,
		@billproperty=-1,					--单据属性
		@ncompletetotal	=0,		--原币结算金额
		@isini=0,
		@ATID=0,					--过账模板
		@CompleteTotal=0,
		@IfCargo=0,
		@IfInvoice=0,
		@promoruleid=0,
		@beforepromobillnumberid=0,
		@promotionmsg='',
		@isyapi=0,
		@yapiorderid=0	,
		@DeliveryAddress='',
		@Discount=1,
		@AdpriceType=0,	
		@checkSave='bill_allow_save'
				
 IF @BillNumberId = -1 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 试用版最多录200条单据！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -2 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期小于本期开始日期！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -3 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 校验错误！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END
 IF @BillNumberId = -4
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期必须与当前日期一致！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
		RETURN
	END

	
--保存单据编号的种子数
EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
SELECT @ErrorCount+=@@ERROR			

--明细表数据写入
INSERT INTO SaleBill 
(
	BillNumberId ,	--从表头获取
	OutFactoryDate ,	--单据日期  
	Stypeid ,			--分支机构
	KTypeID ,			--仓库ID
	CargoID ,			--货位
	--序列号Serial
	--批次GoodsOrder
	--成本单价costprice
	PtypeId ,			--商品ID
	entryCode ,		--条形码

	Qty ,				--基本数量
	SalePrice ,		--基本单价
	UnitID	,		--基本单位

	MQty ,             --销售数量
	MSalePrice,		--销售单价
	MUnitID	,		--销售单位
	MUnitRate,		--销售换算率

	NQty ,			--浮动数量
	NUnitID	,		--浮动单位
	UnitRate ,		--浮动换算率

	discount,			--折扣率
	Tax	,			--税率
	TaxMoney,			--税额
	DiscountPrice ,	--折后单价，按基本单价算折后
	MDiscountPrice,	--折后单价，按销售单价算折后
	TaxPrice,			--含税价，按基本单价算
	MTaxPrice,		--含税价，按销售单价算

	SaleTotal,		--总金额
	total,			--折后总金额
	TaxTotal,			--价税合计

	NSalePrice,       --原币基本单价
	CurMSalePrice,	--原币销售单价
	NTaxMoney,		--原币税额
	NDiscountPrice,	--原币折后单价
	CurMDiscountPrice,--原币折后单价
	NTaxPrice,        --原币含税价
	CurMTaxPrice,		--原币含税价

	NSaleTotal,
	NTotal,
	NTaxTotal,		  
	comment,
	IsCombined ,
	ItemID ,
	PriceSource,
	ETypeID,
	diyid,
	IsPromotion,
	IsVipPoint,
	IsGift,
	ShowOrder,
	CostPrice,
	GoodsCostPrice
)

SELECT
	@BillNumberId BillNumberId ,	--从表头获取
	@BillDate OutFactoryDate ,	--单据日期  
	@STypeId Stypeid ,			--分支机构
	@KTypeId KTypeID ,			--仓库ID
	@CargoID CargoID ,			--货位
	
	p.typeId PtypeId ,			--商品ID
	EXT.EntryCode entryCode ,		--条形码

	dbo.F_RoundQty(d.Qty) Qty ,				--基本数量
	dbo.F_RoundPrice(D.Price) SalePrice ,		--基本单价
	PeX.UnitsId UnitID	,		--基本单位

	dbo.F_RoundQty(d.Qty)  MQty ,             --销售数量
	dbo.F_RoundPrice(D.Price)  MSalePrice,		--销售单价
	PeX.UnitsId MUnitID	,		--销售单位
	1 MUnitRate,		--销售换算率
	
	CASE WHEN ISNULL(P.AssistantUnitId,0)=0 THEN 0 ELSE dbo.F_RoundQty(d.Qty/PE.Rate) END NQty ,--浮动数量
	P.AssistantUnitId NUnitID	,		--浮动单位
	PE.Rate UnitRate ,		--浮动换算率

	d.DisCount,			--折扣率
	0 Tax	,			--税率
	0 TaxMoney,			--税额
	dbo.F_RoundPrice(D.Price)  DiscountPrice ,	--折后单价，按基本单价算折后
	dbo.F_RoundPrice(D.Price) MDiscountPrice,	--折后单价，按销售单价算折后
	dbo.F_RoundPrice(D.Price)  TaxPrice,			--含税价，按基本单价算
	dbo.F_RoundPrice(D.Price)  MTaxPrice,		--含税价，按销售单价算

	dbo.F_RoundTotal(d.Total) SaleTotal,		--总金额
	dbo.F_RoundTotal(d.Total) total,			--折后总金额
	dbo.F_RoundTotal(d.Total) TaxTotal,			--价税合计

	dbo.F_RoundPrice(D.Price) NSalePrice,       --原币基本单价
	dbo.F_RoundPrice(D.Price) CurMSalePrice,	--原币销售单价
	0 NTaxMoney,		--原币税额
	dbo.F_RoundPrice(D.Price) NDiscountPrice,	--原币折后单价
	dbo.F_RoundPrice(D.Price) CurMDiscountPrice,--原币折后单价
	dbo.F_RoundPrice(D.Price) NTaxPrice,        --原币含税价
	dbo.F_RoundPrice(D.Price)  CurMTaxPrice,		--原币含税价

	dbo.F_RoundTotal(d.Total) NSaleTotal,
	dbo.F_RoundTotal(d.Total) NTotal,
	dbo.F_RoundTotal(d.Total) NTaxTotal,		  
	d.Comment,
	ISNULL(P.customitemfrom,0) IsCombined ,
	s.ERP_SKUId ItemID ,
	'WMS '+@wms_BillCode PriceSource,
	@ETypeId ETypeID,
	0 diyid,
	0 IsPromotion,
	0 IsVipPoint,
	D.IsGift,
	RANK()OVER(ORDER BY D.DId) ShowOrder,
	CASE WHEN @Costing=3 THEN -1 ELSE 0 END CostPrice,
	-1 GoodsCostPrice
FROM WMSSaleBill D
INNER JOIN WmsErpPtypeContrastSetting S ON S.WMS_TypeId=D.PTypeId AND S.WMS_SKUId=D.SKuId
INNER JOIN ptype P ON P.typeId=S.ERP_TypeId
INNER JOIN PType_Units_Ext PeX ON PeX.PtypeID=P.typeId AND PEX.UnitsId=P.baseUnitId
LEFT JOIN PType_Units_Ext PE ON PE.PtypeID=P.typeId AND  PE.UnitsId=P.AssistantUnitId
LEFT JOIN PType_EntryCode_Ext EXT ON EXT.Ptypeid=P.typeId AND EXT.IsDefaultEntryCode=1
WHERE BillNumberID=@wmsBillNumberId
ORDER BY D.DId
SELECT @ErrorCount+=@@ERROR

--=================修改billindex主表金额、数量【BEGIN】===================	
DECLARE
	@TotalQty	NUMERIC(24,10)=0,
	@TotalMoney	NUMERIC(24,10)=0
	
--明细行总数量/总金额
SELECT @TotalQty=dbo.F_RoundQty(SUM(Qty)),@TotalMoney=dbo.F_RoundTotal(SUM(total)) FROM SaleBill where BillNumberID=@BillNumberId
SELECT @ErrorCount+=@@ERROR	

--修改主表金额、数量
UPDATE BillIndex SET totalqty=@TotalQty,TotalMoney=@TotalMoney,NTotalMoney=@TotalMoney,IsUploadWms=1 WHERE BillNumberId=@BillNumberId
SELECT @ErrorCount+=@@ERROR	
		
--=================修改billindex主表金额、数量【END】===================	

	
-- 自动生成的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,@billtype
SELECT @ErrorCount+=@@ERROR	

--保存关联关系
INSERT INTO WMS_ERPBillRelation(WMS_BillNumberID,BillType,ERP_BillNumberID,ERP_BillCode,ERP_BillType)
VALUES(@wmsBillNumberId,@BillType,@BillNumberId,@BillCode,@BillType)
SELECT @ErrorCount+=@@ERROR	



---------------------------------------------------其他收入单【BEGIN】---------------------------------------------
DECLARE 
	@New_BillCode VARCHAR(200)='',--其他收入单单据编号
	@new_BillNumberId NUMERIC(24, 10)=0,--其他收入单单据ID
	@new_BillType	INT=93,--其他收入单单据类型
	@new_Comment	VARCHAR(MAX)='【出库单编号：'+@BillCode+'】'+@wms_Comment,--收入单单据摘要
	@new_ATypeId	VARCHAR(50),--其他收入单会计科目
	@BrandTypeId	VARCHAR(50)='00001',--默认品牌,
	@new_Total		NUMERIC(24,10)=dbo.F_RoundTotal(@wms_CustomerFreightFee-@wms_MallFee),--总金额
	@new_ItemId		INT=14--其他项目

IF(@new_Total<>0)
BEGIN
	--收款科目
	CREATE TABLE #new_Atype(TypeId VARCHAR(50),FullName VARCHAR(200),Flag varchar(10))
	INSERT INTO #new_Atype(TypeId,FullName,Flag)
	EXEC dbo.Web_GetAtype @new_BillType,@STypeId
	SELECT @new_ATypeId=TypeId FROM #new_Atype
		
		
	--生成单据编号
	EXEC Gp_GetBillCode @new_BillType,@MONTH,@DAY,'QS',@BillDate,@STypeId,@New_BillCode OUT,@dfullname,@cefullname,-999

	--主表数据写入
	EXEC @new_BillNumberId=Gp_InsertBillIndex 
			@BillDate=@BillDate,
			@BillCode=@New_BillCode,
			@BillType=@new_BillType,
			@Comment=@new_Comment,
			@ATypeID='',
			@PTypeID='',
			@BTypeID=@BTypeId,
			@ETypeID=@ETypeId,
			@KTypeID=@KTypeId,
			@KTypeID2='',
			@IfCheck='f',
			@CheckE=@OperatorId,
			@TotalMoney=@new_Total,
			@TotalQty=0,
			@TotalInMoney=0,
			@Tax='0',
			@szPeriod=1,
			@Explain=@wms_Explain,
			@Draft='True',
			@RedWord='False',
			@OrderID=0,
			@WayBillCode='',
			@Goodsnumber='',
			@PackWay='',
			@Tel='',
			@preferencemoney=0,
			@AlertDay=9999,
			@Assessor='',
			@IfAudit='',
			@Audit_Explain='',
			@Dtypeid=@DTypeId,
			@VipCardID=-1,
			@KTypeID3='',
			@LinkMan='',
			@LinkTel='',
			@LinkAddr='',
			@wxManID='',
			@JieJianBillNumberID=-1,
			@JieJianID=-1,
			@BaoXiuBillNumberID=-1,
			@BaoXiuID=-1,
			@BuyDate='',
			@Serial='',
			@wxTotal=0,
			@ErrDes='',
			@ifHideJieJian=0,
			@ifWX=0,
			@IfBargainOn=0,
			@STypeID=@stypeid,
			@FromBillNumberID=0,
			@CostSale=0,
			@completedate='9999-12-31 23:59:59',
			@billstate=1,
			@ifmulaccount=0,
			@vipczmoney=0,
			@otherinouttype=-1,
			@czbeforetimes=0,
			@posbilltype=0,
			@TransportId=0,
			@IsFreightMoney=0,
			@FreightAddr=NULL,
			@freightperson=NULL,
			@freighttel=NULL,
			@ShareMode=0,
			@uf1='',
			@uf2='',
			@uf3='',
			@uf4='',
			@uf5='',
			--9.0新字段
			@dealbtypeid=@BTypeId,		--结算单位
			@cid=1,			--外币币种id
			@rate=1,			--汇率
			@ntotalmoney=@new_Total,		--原币种金额
			@ntotalinmoney=0,	--原币收现金额
			@npreferencemoney=0,	--原币优惠金额
			@nvipczmoney=0,		--原币会员卡充值金额
			@atypeid1=@new_ATypeId,
			@billproperty=-1,					--单据属性
			@ncompletetotal	=0,		--原币结算金额
			@isini=0,
			@ATID=0,					--过账模板
			@CompleteTotal=0,
			@IfCargo=0,
			@IfInvoice=0,
			@promoruleid=0,
			@beforepromobillnumberid=0,
			@promotionmsg='',
			@isyapi=0,
			@yapiorderid=0	,
			@DeliveryAddress='',
			@Discount=1,
			@AdpriceType=0,	
			@checkSave='bill_allow_save'
					
	 IF @new_BillNumberId = -1 
		BEGIN
			SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 试用版最多录200条单据！' Msg
			ROLLBACK TRAN createbill
			COMMIT TRAN created
			RETURN
		END
	 IF @new_BillNumberId = -2 
		BEGIN
			SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期小于本期开始日期！' Msg
			ROLLBACK TRAN createbill
			COMMIT TRAN created
			RETURN
		END
	 IF @new_BillNumberId = -3 
		BEGIN
			SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 校验错误！' Msg
			ROLLBACK TRAN createbill
			COMMIT TRAN created
			RETURN
		END
	 IF @new_BillNumberId = -4
		BEGIN
			SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！ 录单日期必须与当前日期一致！' Msg
			ROLLBACK TRAN createbill
			COMMIT TRAN created
			RETURN
		END

		
	--保存单据编号的种子数
	EXEC GP_SaveBillCode_Seed @new_BillNumberId,@billdate,@new_BillType,@New_BillCode
	SELECT @ErrorCount+=@@ERROR			


	--明细表数据写入
	INSERT INTO MoneyBill 
	(
		BillNumberId,
		AtypeId,
		total,
		Comment,
		Stypeid,
		ntotal,
		DTypeId,
		ETypeId,
		ShowOrder,
		DraftFlag,
		IsIniFlag,
		BrandarTypeId
	)
	VALUES(
		@new_BillNumberId,
		@new_ItemId,
		@new_Total,
		@new_Comment,
		@STypeId,
		@new_Total,
		@DTypeId,
		@ETypeId,
		1,
		1,
		0,
		@BrandTypeId)
	SELECT @ErrorCount+=@@ERROR

	--=================修改billindex是否允许再次上传WMS【BEGIN】===================	

	UPDATE BillIndex SET IsUploadWms=1,isbybrandartype=CASE WHEN ISNULL(@BrandTypeId,'')='' THEN 0 ELSE 1 END WHERE BillNumberId=@new_BillNumberId
	SELECT @ErrorCount+=@@ERROR	
			
	--=================修改billindex是否允许再次上传WMS【 END 】===================	

	--保存关联关系
	INSERT INTO WMS_ERPBillRelation(WMS_BillNumberID,BillType,ERP_BillNumberID,ERP_BillCode,ERP_BillType)
	VALUES(@wmsBillNumberId,@BillType,@new_BillNumberId,@New_BillCode,@new_BillType)
	SELECT @ErrorCount+=@@ERROR	
END

---------------------------------------------------其他收入单【 END 】---------------------------------------------

IF(@ErrorCount=0)
	BEGIN
		COMMIT TRAN createbill
		
		--过账处理		
		IF EXISTS(SELECT * FROM WMSBaseInfo WHERE Field='autodraftbill' AND Value=0)
			BEGIN
				DECLARE @voucherMsg VARCHAR(MAX)=''
				EXEC @ErrorCount= dbo.Gp_Auditing 
							@nBillID = @BillNumberId, -- numeric
							@szCheckMan = @OperatorId, -- varchar(50)
							@szPID = '', -- varchar(1000)
							@chvOpID = @OperatorId, -- varchar(50)
							@KTypeID = '', -- varchar(50)
							@billtype = @BillType, -- int
							@voucherMsg = @voucherMsg, -- varchar(50)
							@vipcentinfo='',
							@AssetMsg=''
							
				IF(@ErrorCount=0)
					SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode Msg
				ELSE 
					SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode++'过账失败！失败原因'+@voucherMsg Msg	
				
				IF(@wms_Total<>0)
					BEGIN
						EXEC @ErrorCount= dbo.Gp_Auditing 
									@nBillID = @new_BillNumberId, -- numeric
									@szCheckMan = @OperatorId, -- varchar(50)
									@szPID = '', -- varchar(1000)
									@chvOpID = @OperatorId, -- varchar(50)
									@KTypeID = '', -- varchar(50)
									@billtype = @new_BillType, -- int
									@voucherMsg = @voucherMsg, -- varchar(50)
									@vipcentinfo='',
									@AssetMsg=''
									
						IF(@ErrorCount=0)
							SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@New_BillCode Msg
						ELSE 
							SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@New_BillCode++'过账失败！失败原因'+@voucherMsg Msg	
					END				
												
			END
		ELSE
			SELECT 'ok' [type],'单据编号'+@wms_BillCode+' 生成成功！对应ERP单据编号为：'+@BillCode+';'+@New_BillCode Msg
		
		COMMIT TRAN created
	END
ELSE 
	BEGIN
		SELECT 'error' [type],'单据编号'+@wms_BillCode+'生成失败！出现异常！' Msg
		ROLLBACK TRAN createbill
		COMMIT TRAN created
	END
	
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_WmsCalVirtualStockStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_WmsCalVirtualStockStatus]
GO



/*
	作者：谢吉康
	日期：2004-11-24
	描述：WMS计算虚拟库存数量
*/

CREATE  PROCEDURE [dbo].[Gp_WmsCalVirtualStockStatus]
( 
	@OperatorID 		VARCHAR(100),--操作员ID号 
	@Parid   			VARCHAR(100)='00000',--商品的父节点号
	@szKtypeId  		VARCHAR(8000)='',--仓库id号
	@sortfield 			VARCHAR(20),--按何种方式排序
	@EntryCode			VARCHAR(200),--商品条码
	@Standard			VARCHAR(200),--商品规格
	@Type				VARCHAR(200),--商品型号
	@Area				VARCHAR(200),--商品产地
	@stypeid			VARCHAR(8000),
	@virtualqtysql		VARCHAR(MAX)='isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)',--虚拟库存列计算sql
	@unitconvert        VARCHAR(10),--多单位标示,
	@billtype			VARCHAR(50),
	@startdate			VARCHAR(50) ,
	@enddate			VARCHAR(50),
	@showstockstop      INT =0,--是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid	VARCHAR(max)='',				
	@showzeroqty		INT=1--是否显示库存为零  1.显示  0.不显示
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
DECLARE @SQL varchar(MAX)  

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId VARCHAR(50))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
		
--仓库
CREATE TABLE #GetManKTypeId(TypeId VARCHAR(50))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT sk.TypeId FROM F_BaseGetAllManagerBaseTypeId(@szKTypeId,4,@OperatorID) sk
INNER JOIN stock S ON S.typeId=SK.TypeId AND (@showstockstop=0 OR (@showstockstop=1 AND S.deleted=0))
INNER JOIN #GetSelectSTypeId ST ON ST.TypeId=S.STypeID
-----------------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
        @Lendqty NVARCHAR(2000),
        @Borrowqty NVARCHAR(2000),
		@RQty NVARCHAR(2000),
		@CQty NVARCHAR(2000),
		@BuyOrderQty NVARCHAR(2000),
		@BuyReachQty NVARCHAR(2000),
		@SaleOrderQty NVARCHAR(2000),
		@SaleReachQty NVARCHAR(2000),
		@UnitRate NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
		@BaseUnitName NVARCHAR(2000),
        @temptable  NVARCHAR(2000),
		@drafBuyQty NVARCHAR(2000),
		@saleDrafQty NVARCHAR(2000),
		@LimitBuyQty NVARCHAR(2000),
		@LimitSaleQty NVARCHAR(2000)
      
IF @unitconvert=0
BEGIN
SELECT  @Qty='o.Qty/isnull(r3.rate,1)',
		@Lendqty='SUM((o.Lend-o.LendBack-o.saleqty)/isnull(r3.rate,1))',
		@Borrowqty='SUM((o.Borrow-o.BorrowBack-o.buyqty)/isnull(r3.rate,1))',   
	    @BuyReachQty='o.BuyReachQty/isnull(r3.rate,1)', 
		@RQty='o.RQty/isnull(r3.rate,1)',        
		@CQty='o.CQty/isnull(r3.rate,1)',        
		@BuyOrderQty='o.BuyOrderQty/isnull(r3.rate,1)', 
		@BuyReachQty='o.BuyReachQty/isnull(r3.rate,1)', 
		@SaleOrderQty='o.SaleOrderQty/isnull(r3.rate,1)',
		@SaleReachQty='o.SaleReachQty/isnull(r3.rate,1)',
        @UnitRate = 'isnull(r3.rate,1)',
		@UnitName = 'u3.fullname',
		@BaseUnitName = 'u1.fullname',
        @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,3','3'),
		@drafBuyQty='o.BuyReferQty/isnull(r3.rate,1)', 
		@saleDrafQty='o.SaleReferQty/isnull(r3.rate,1)',
		@LimitBuyQty='o.LimitBuyQty/isnull(r3.rate,1)', 
		@LimitSaleQty='o.LimitSaleQty/isnull(r3.rate,1)'
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='o.Qty/isnull(r2.rate,1)',
		@Lendqty='SUM((o.Lend-o.LendBack-o.saleqty)/isnull(r2.rate,1))',
		@Borrowqty='SUM((o.Borrow-o.BorrowBack-o.buyqty)/isnull(r2.rate,1))',   
		@BuyReachQty='o.BuyReachQty/isnull(r2.rate,1)', 
		@RQty='o.RQty/isnull(r2.rate,1)',        
		@CQty='o.CQty/isnull(r2.rate,1)',        
		@BuyOrderQty='o.BuyOrderQty/isnull(r2.rate,1)', 
		@BuyReachQty='o.BuyReachQty/isnull(r2.rate,1)', 
		@SaleOrderQty='o.SaleOrderQty/isnull(r2.rate,1)',
		@SaleReachQty='o.SaleReachQty/isnull(r2.rate,1)',
        @UnitRate = 'isnull(r2.rate,1)',
		@UnitName = 'u2.fullname',
		@BaseUnitName = 'u1.fullname',
        @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,2','2'),
		@drafBuyQty='o.BuyReferQty/isnull(r2.rate,1)', 
		@saleDrafQty='o.SaleReferQty/isnull(r2.rate,1)',
		@LimitBuyQty='o.LimitBuyQty/isnull(r2.rate,1)', 
		@LimitSaleQty='o.LimitSaleQty/isnull(r2.rate,1)'
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='o.Qty/isnull(r4.rate,1)',
		@Lendqty='SUM((o.Lend-o.LendBack-o.saleqty)/isnull(r4.rate,1))',
		@Borrowqty='SUM((o.Borrow-o.BorrowBack-o.buyqty)/isnull(r4.rate,1))',   
		@BuyReachQty='o.BuyReachQty/isnull(r4.rate,1)', 
		@RQty='o.RQty/isnull(r4.rate,1)',        
		@CQty='o.CQty/isnull(r4.rate,1)',        
		@BuyOrderQty='o.BuyOrderQty/isnull(r4.rate,1)', 
		@BuyReachQty='o.BuyReachQty/isnull(r4.rate,1)', 
		@SaleOrderQty='o.SaleOrderQty/isnull(r4.rate,1)',
		@SaleReachQty='o.SaleReachQty/isnull(r4.rate,1)',
		@UnitRate = 'c.stockunitrate',
		@UnitName = 'c.stockunitfullname',
		@BaseUnitName = 'c.baseunitfullname',
	    @UnitRate = 'isnull(r4.rate,1)',
		@UnitName = 'u4.fullname',
		@BaseUnitName = 'u1.fullname',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,4','4'),
		@drafBuyQty='o.BuyReferQty/isnull(r4.rate,1)', 
		@saleDrafQty='o.SaleReferQty/isnull(r4.rate,1)',
		@LimitBuyQty='o.LimitBuyQty/isnull(r4.rate,1)', 
		@LimitSaleQty='o.LimitSaleQty/isnull(r4.rate,1)'
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='o.Qty',
		@Lendqty='SUM(o.Lend-o.LendBack-o.saleqty)',
		@Borrowqty='SUM(o.Borrow-o.BorrowBack-o.buyqty)',   
		@RQty='o.RQty',        
		@CQty='o.CQty',     
		@BuyOrderQty='o.BuyOrderQty', 
		@BuyReachQty='o.BuyReachQty', 
		@SaleOrderQty='o.SaleOrderQty',
		@SaleReachQty='o.SaleReachQty',
		@UnitRate = '1',
		@UnitName = 'u1.fullname',
		@BaseUnitName = 'u1.fullname',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1','1'),
		@drafBuyQty='o.BuyReferQty', 
		@saleDrafQty='o.SaleReferQty',
		@LimitBuyQty='o.LimitBuyQty', 
		@LimitSaleQty='o.LimitSaleQty'
END
--------多单位计算End---------
-----------------------------------------------------------------------------------------------------------------------------

--非服务类、非组合品 商品
CREATE TABLE #GetManPTypeID(TypeId VARCHAR(50))
CREATE UNIQUE CLUSTERED INDEX [Ptypeidx] ON [dbo].[#GetManPTypeID] ([typeId])

SELECT @SQL='
	INSERT INTO #GetManPTypeID(TypeId) 
	SELECT P.typeId 
	FROM ptype P 
	INNER JOIN dbo.F_ManPTypeInCategoryID('''+@OperatorID+''','''+@Parid+''','''+@ptypeCategoryid+''') mp ON mp.TypeId=p.typeId 
	WHERE 
		P.isservice=0
		AND P.iscombinationproduct=0
	'
IF ISNULL(@EntryCode,'')<>''
	SET @SQL+=' AND P.MultEntryCode LIKE ''%'+@EntryCode+'%'''
	
IF ISNULL(@Standard,'')<>''
	SET @SQL+=' AND P.[Standard] LIKE ''%'+@Standard+'%'''
	
IF ISNULL(@Type,'')<>''
	SET @SQL+=' AND P.[Type] LIKE ''%'+@Type+'%'''
	
IF ISNULL(@Area,'')<>''
	SET @SQL+=' AND P.Area LIKE ''%'+@Area+'%'''
EXEC(@SQL)		

CREATE TABLE #GetManPTypeAll
(
	TypeId			varchar(100),
	FullName        varchar(200),
	UserCode        varchar(100),
	EntryCode		varchar(100),
	[Standard]		varchar(100),
	[Type]			varchar(20),
	Area			varchar(30),
	Sonnum          int,
	Leveal          int,
	Parid           varchar(200),
	unit1           varchar(100),
	unit2           varchar(100),
	unitrate1       varchar(100),
	unitname       NVARCHAR(2000),
	baseunitname    NVARCHAR(2000),
	unitrate        NVARCHAR(2000),
	sortid        int
)

CREATE UNIQUE CLUSTERED INDEX [PtypeAllidx] ON [dbo].[#GetManPTypeAll] 
(
	[typeId]
)

SET @SQL='INSERT INTO #GetManPTypeAll 
			 SELECT DISTINCT P.TypeId,P.FullName,P.UserCode,P.EntryCode,P.Standard,P.Type,P.Area,P.Sonnum,P.Leveal,
			 P.Parid,P.unit1,P.unit2,P.unitrate1,'
         
     SET @sql+=@UnitName+','+@BaseUnitName+','+@UnitRate
     
    SET @sql+=' ,p.sortid 
		FROM F_GetManPTypeAll('''+@OperatorID+''') P 
		inner join ptype p1 on p.typeid=p1.typeid '+@temptable

IF ISNULL(@ptypeCategoryid,'')<>''
	SET @sql=@sql+' inner join #GetManPTypeId pc on pc.typeid like p.typeid +''%'' '    
    set @sql+=' WHERE P.Parid='''+@Parid+'''
						AND p.isservice=0 
						AND p.iscombinationproduct = 0  
    '

EXEC(@SQL)

---------------数据统计---------------------------------------------------------------
CREATE TABLE #LeftJoinTable
(
	TypeId			 VARCHAR(50),
	KtypeId			 VARCHAR(50),
	itemid			 INT,
	RQty			 NUMERIC(24, 10) NOT NULL DEFAULT(0) ,
	CQty			 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	Qty				 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	Lendqty			 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	Borrowqty		 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	SaleOrderQty	 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	BuyOrderQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	SaleReachQty	 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	BuyReachQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	baseqty          NUMERIC(24, 10) NOT NULL DEFAULT(0),
	total			 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	drafBuyQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0), 
	saleDrafQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0),
	LimitBuyQty		 NUMERIC(24, 10) NOT NULL DEFAULT(0), 
	LimitSaleQty	 NUMERIC(24, 10) NOT NULL DEFAULT(0)
)

CREATE TABLE #ResultLeftTable
(
	pTypeId			 VARCHAR(50),
	ktypeid			 VARCHAR(50),
	saleQty			 NUMERIC(24, 10),
	itemid			 INT
)
 SET @SQL='
	INSERT INTO #ResultLeftTable (
		pTypeId,
		ktypeid,
		itemid,
		saleqty		
	)
	SELECT	p1.typeid pTypeId,
			o.ktypeid,
			o.itemid,
			SUM(CASE WHEN o.billtype in (305,11,140,141,12,215,45,142,46,160,402,403) THEN -ISNULL('+@qty+',0)
			ELSE ISNULL('+@qty+',0) END) saleQty 
	FROM  InOutstocktable o
	INNER JOIN f_split('''+@billtype+''','','') F ON F.a=O.BillType
	INNER JOIN #GetManPTypeId pp ON o.ptypeid = pp.typeid
	INNER JOIN #GetManKTypeId K ON o.KTypeId = K.TypeId
	INNER JOIN ptype p1 ON o.ptypeid=p1.typeid
	'+@temptable+'
	WHERE	BillDate BETWEEN '''+@startdate+''' AND '''+@enddate+'''   
	GROUP BY p1.typeid,o.ktypeid,o.itemid '
	
EXEC(@SQL)	   

SELECT @SQL='
	INSERT INTO #LeftJoinTable 
	(
		TypeId,
		ktypeid,		
		itemid,
		RQty,
		CQty
	)
	SELECT	
		O.PTypeId TypeId,
		O.ktypeid,
		O.itemid,
		ISNULL(SUM('+@RQty+'),0) AS RQty,
		ISNULL(SUM('+@CQty+'),0) AS CQty
	FROM GoodsStocks_Draft O
	INNER JOIN #GetManKTypeId K ON K.typeid=O.ktypeid
	INNER JOIN #GetManPTypeId P ON P.TypeId=O.PtypeId
	INNER JOIN ptype p1 ON p1.typeid=O.PTypeId '+ @temptable+'
	GROUP BY O.PTypeId,O.Ktypeid,O.itemid'
EXEC(@SQL)

SELECT @sql ='
INSERT INTO #LeftJoinTable 
(
	TypeId,
	ktypeid,
	itemid,
	Qty,
	baseqty,
	total
)
SELECT 	
	p.typeid,
	o.ktypeid,
	o.itemid,
	SUM('+@qty+') qty,
	sum(o.qty) baseqty,
	sum(G.total) total
FROM goodsstocks_qty o 
LEFT JOIN (
			SELECT	ptypeid,
					ktypeid,
					SUM(Total) AS Total
			FROM	GoodsStocks
			GROUP BY ptypeid,ktypeid
)G ON o.ptypeid = g.ptypeid and o.ktypeid = g.ktypeid
INNER JOIN #GetManPTypeID p on p.typeid=o.ptypeid
INNER JOIN #GetManKTypeId k on o.KTypeId=k.TypeId
INNER JOIN ptype p1 ON p1.typeid=O.PTypeId '+ @temptable+'
GROUP BY p.typeid,o.ktypeid,o.itemid'

EXEC(@SQL)	

SELECT @sql ='	INSERT INTO #LeftJoinTable
				(
					TypeId,
					ktypeid,
					itemid,
					Lendqty,
					Borrowqty
				)					
				SELECT 	
					a.typeid,
					o.ktypeid,
					o.itemid,
					'+@Lendqty+' AS Lendqty,
					'+@Borrowqty+' AS  Borrowqty
				FROM V_LendStatus o 
				INNER JOIN #GetManPTypeID a on a.typeid=o.ptypeid
				INNER JOIN #GetManKTypeId k on o.ktypeid=k.typeid
				INNER JOIN ptype p1  on o.ptypeid=p1.typeid ' + @temptable+'
				GROUP BY a.typeid,o.ktypeid,o.ItemID'

EXEC(@SQL)		
	
SELECT @sql =' INSERT INTO #LeftJoinTable 
				(
					TypeId,
					ktypeid,
					itemid,
					SaleOrderQty,
					BuyOrderQty,
					SaleReachQty,
					BuyReachQty,
					saleDrafQty,
					drafBuyQty,
					LimitSaleQty,
					LimitBuyQty
				)	
				SELECT 	a.typeid,
						o.ktypeid,
						o.itemid,
						ISNULL(SUM('+@SaleOrderQty+'),0) SaleOrderQty,
						ISNULL(SUM('+@BuyOrderQty+'),0) BuyOrderQty,	
						ISNULL(SUM('+@SaleReachQty+'),0) SaleReachQty,
						ISNULL(SUM('+@BuyReachQty+'),0) BuyReachQty,	
						ISNULL(SUM('+@saleDrafQty+'),0) saleDrafQty,
						ISNULL(SUM('+@drafBuyQty+'),0) drafBuyQty,	
						ISNULL(SUM('+@LimitSaleQty+'),0) LimitSaleQty,
						ISNULL(SUM('+@LimitBuyQty+'),0) LimitBuyQty
				FROM GoodsStocks_Order o
				inner join #GetManPTypeID a on a.typeid=o.ptypeid 
				INNER JOIN #GetManKTypeId K ON o.ktypeid=K.TypeId 
				INNer join ptype p1 on o.ptypeid=p1.typeid'+@temptable+'
				GROUP BY a.typeid,o.ktypeid,o.itemid '

EXEC(@SQL)

SET @SQL='
SELECT	a.typeid,
		f.ktypeid,
		f.itemid,
		a.sortid,
		ISNULL(SUM(f.qty),0) AS qty,
		ISNULL(SUM(f.Lendqty),0) AS Lendqty,
		ISNULL(SUM(f.Borrowqty),0) AS Borrowqty,
		ISNULL(SUM(f.FactQty),0) AS FactQty,
		ISNULL(SUM(f.RQty),0) AS RQty,
		ISNULL(SUM(f.CQty),0) AS CQty,
		ISNULL(SUM(f.KFHQty),0) KFHQty,
		ISNULL(SUM(f.buyreferqty),0) AS buyreferqty,
		ISNULL(SUM(f.salereferqty),0) AS salereferqty,
		ISNULL(SUM(f.BuyOrderQty),0) BuyOrderQty,
		ISNULL(SUM(f.SaleOrderQty),0) SaleOrderQty,
		ISNULL(SUM(f.SaleCanQty),0) SaleCanQty,
		case when a.Sonnum>0 then null else  a.unitname end AS unitname,
		case when a.Sonnum>0 then null else   a.baseunitname end AS baseunitname,
		case when a.Sonnum>0 then null else a.unitrate end AS unitrate,
		ISNULL(SUM(f.BuyReachQty),0) BuyReachQty,
		ISNULL(SUM(f.SaleReachQty),0) SaleReachQty,
		ISNULL(SUM(f.baseqty),0) AS baseqty,
		case when ISNULL(SUM(f.virtualqty),0)=0 THEN 0 ELSE CAST(ISNULL(SUM(f.costtotal),0) AS NUMERIC(24,10))/CAST(ISNULL(SUM(f.virtualqty),0)AS NUMERIC(24,10)) END  AS price,
		ISNULL(SUM(f.virtualqty),0) AS virtualqty,
		ISNULL(SUM(f.costtotal),0) costtotal
INTO	#result			
FROM	#GetManPTypeAll a 
LEFT JOIN 
(
	SELECT 
		a.*,
		('+@virtualqtysql+') virtualqty,
		('+@virtualqtysql+')*A.price costtotal 
	FROM (
		select 
			o.typeid,	
			o.ktypeid,	
			o.itemid,	
			ISNULL(SUM(o.qty),0) AS qty,
			ISNULL(SUM(o.Lendqty),0) AS Lendqty,
			ISNULL(SUM(o.borrowqty),0) AS Borrowqty,
			ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.borrowqty),0)-ISNULL(SUM(o.lendqty),0) AS FactQty,
			ISNULL(SUM(o.rqty),0) AS RQty,
			ISNULL(SUM(o.cqty),0) AS CQty,
			ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.rqty),0)-ISNULL(SUM(o.cqty),0) AS KFHQty,
			ISNULL(SUM(o.drafBuyQty),0) AS buyreferqty,
			ISNULL(SUM(o.saleDrafQty),0) AS salereferqty,
			CASE WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.LimitBuyQty),0)>0 THEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.LimitBuyQty),0) ELSE 0 END  BuyOrderQty,
			CASE WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.LimitSaleQty),0)>0 THEN ISNULL(SUM(o.SaleOrderQty),0) - ISNULL(SUM(o.LimitSaleQty),0) ELSE 0 END SaleOrderQty,
			ISNULL(SUM(o.qty),0)+(CASE WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.LimitBuyQty),0)<=0 THEN 0 ELSE ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.LimitBuyQty),0) END)-ISNULL(SUM(saleDrafQty),0)+ISNULL(SUM(drafBuyQty),0)-(CASE WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.LimitSaleQty),0)<=0 THEN 0 ELSE ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.LimitSaleQty),0) END)
			SaleCanQty,
			ISNULL(SUM(o.BuyReachQty),0) BuyReachQty,
			ISNULL(SUM(o.SaleReachQty),0) SaleReachQty,
			ISNULL(SUM(o.baseqty),0) AS baseqty,
			case when ISNULL(SUM(o.qty),0)=0 THEN 0 ELSE CAST(ISNULL(SUM(o.total),0) AS NUMERIC(24,10))/CAST(ISNULL(SUM(o.qty),0)AS NUMERIC(24,10)) END  AS price
		from #LeftJoinTable o
		group by o.typeid,o.ktypeid,o.itemid
	)  A
) f ON LEFT(f.typeid,LEN(a.typeid))=a.typeid 
WHERE ISNULL(f.ktypeid,'''') <> ''''
GROUP BY a.typeid,
		f.ktypeid,
		a.fullname,
		a.usercode,
		a.EntryCode,
		a.Standard,
		a.Type,
		a.Area,
		a.sONnum,
		a.leveal,
		a.parid,
		a.unit1,
		a.unitrate1,
		a.unit2,	
		a.sortid,
		case when a.Sonnum>0 then null else a.unitname end,
		case when a.Sonnum>0 then null else	 a.baseunitname END,
		case when a.Sonnum>0 then null else a.unitrate END,
		f.itemid
		
--最终数据
SELECT	p.wms_typeid AS ptypeid,		
		k.wms_typeid as ktypeid,
		P.WMS_SKUId AS skuid,
		R.virtualqty,
		R.costtotal
FROM	(			
			SELECT	a.typeid,
					a.ktypeid,
					a.itemid,
					a.virtualqty,
					a.costtotal
			FROM	#result a
			INNER JOIN Ptype p on a.typeid=p.typeid
			LEFT join (
						select	a.typeid, 
								sum(saleqty)as saleqty 
						from   #resultlefttable  TT
						INNER JOIN #result a ON tt.ptypeid like A.typeid+''%''
						group by a.typeid
			) o ON o.typeid=a.typeid
			LEFT JOIN ptype_price pp on pp.ptypeid=p.typeid and p.baseunitid=pp.unitid
)R	
INNER JOIN dbo.WmsErpPtypeContrastSetting P ON R.typeId = P.ERP_TypeId
INNER JOIN dbo.WmsErpStockContrastSetting k ON R.KtypeId = k.ERP_TypeId
INNER JOIN ptype bp ON r.typeid = bp.typeid AND ISNULL(bp.customitemfrom,'''') = '''' AND ISNULL(bp.customitemid,'''') = ''''
WHERE	ISNULL(p.wms_typeid,'''') <> ''''
		AND ISNULL(k.wms_typeid,'''') <> ''''
UNION ALL
SELECT	p.wms_typeid AS ptypeid,		
		k.wms_typeid AS ktypeid,
		P.WMS_SKUId AS skuid,
		R.virtualqty,
		R.costtotal
FROM	(			
			SELECT	a.typeid,
					a.ktypeid,
					a.itemid,
					a.virtualqty,
					a.costtotal
			FROM	#result a
			INNER JOIN Ptype p on a.typeid=p.typeid
			LEFT join (
						select	a.typeid, 
								sum(saleqty)as saleqty 
						from   #resultlefttable  TT
						INNER JOIN #result a ON tt.ptypeid like A.typeid+''%''
						group by a.typeid
			) o ON o.typeid=a.typeid
			LEFT JOIN ptype_price pp on pp.ptypeid=p.typeid and p.baseunitid=pp.unitid
)R
LEFT JOIN (
			SELECT	p.typeid,
					v.id,
					v.fullname as itemfullname
			FROM	vWeb_ItemIDByIsCombined v
			INNER JOIN ptype p ON p.customitemid = v.DataTypeId AND p.CustomItemFrom = v.iscombined 
)M ON R.typeid = m.typeid AND r.itemid = m.id		
INNER JOIN dbo.WmsErpPtypeContrastSetting P ON R.typeId = P.ERP_TypeId AND p.wms_prop1name = m.itemfullname
INNER JOIN dbo.WmsErpStockContrastSetting k ON R.KtypeId = k.ERP_TypeId
WHERE	ISNULL(p.wms_typeid,'''') <> ''''
		AND ISNULL(k.wms_typeid,'''') <> '''' '

--PRINT(@SQL)
EXEC(@SQL)


DROP TABLE #GetManKTypeId,#GetManPTypeId,#LeftJoinTable,#GetSelectSTypeId,#ResultLeftTable,#GetManPTypeAll

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_WmsErpRebuilt]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Gp_WmsErpRebuilt]
GO

/*
	作者：谢吉康
	日期：2018-10-15
	描述：清除WMSERP中的数据
*/
CREATE PROCEDURE Gp_WmsErpRebuilt
AS
SET NOCOUNT ON

--清除同步信息
TRUNCATE TABLE dbo.WmsErpPtypeContrastSetting
TRUNCATE TABLE dbo.WmsErpBTypeContrastSetting
TRUNCATE TABLE dbo.WmsErpEmployeeContrastSetting
TRUNCATE TABLE dbo.WmsErpStockContrastSetting
TRUNCATE TABLE dbo.WmsErpItemContrastSetting
UPDATE dbo.ptype SET IsWmsSync = 0,IsWmsDownLoad = 0
UPDATE dbo.btype SET IsWmsSync = 0,IsWmsDownLoad = 0
UPDATE dbo.employee SET IsWmsSync = 0,IsWmsDownLoad = 0
UPDATE dbo.stock SET IsWmsSync = 0,IsWmsDownLoad = 0
UPDATE dbo.Ac_Items SET IsWmsSync = 0,IsWmsDownLoad = 0

--清除下载的WMS数据
TRUNCATE TABLE dbo.WMSOrderIndex
TRUNCATE TABLE dbo.WMSExpenseBill
TRUNCATE TABLE dbo.WMSGatherBill
TRUNCATE TABLE dbo.WMS_ERPBillRelation
TRUNCATE TABLE dbo.WMSSaleBill
TRUNCATE TABLE dbo.WMSSaleBackBill

--清除单据状态
UPDATE dbo.OrderIndex SET IsUploadWms = 0
UPDATE dbo.BillIndex SET IsUploadWms = 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_WmsErpSaleOrderToSaleBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_WmsErpSaleOrderToSaleBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：lhl
	日期：2018-10-25
	描述：销售订单生成销售出库单
*/
CREATE PROCEDURE Gp_WmsErpSaleOrderToSaleBill
( 
	@orderids		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @billdate		DATETIME,
		@billcode		VARCHAR(200),
		@stypeid		VARCHAR(50),
		@etypeid		VARCHAR(50),
		@btypeid		VARCHAR(50),
		@dtypeid		VARCHAR(50),
		@ktypeid		VARCHAR(50),
		@totalmoney		NUMERIC(24, 10) ,
		@totalqty		NUMERIC(24, 10) ,
		@tax			NUMERIC(24, 10) ,
		@BillNumberId	NUMERIC(24, 10) ,
		@DAY			VARCHAR(10),
		@MONTH			VARCHAR(10),
		@dealbtypeid	VARCHAR(100),--结算单位
		@cid			VARCHAR(100),
		@rate			VARCHAR(100),
		@GoodsNumber	VARCHAR(100),
		@intQtyDot		INT,
		@cefullname		VARCHAR(500)='',
		@dfullname		VARCHAR(500)='',
		@atypeid1		VARCHAR(50),
		@OperatorID		VARCHAR(50),
		@billtype		VARCHAR(10),
		@orderid		BIGINT,
		@orderbillcode	VARCHAR(200),
		@WmsVchCode		VARCHAR(50),
		@errormsg		VARCHAR(200)
		
SET @billtype='11'
SET @OperatorID = '00001'

--数量的小数位数
EXEC	@intQtyDot=Gp_GetDigit 1
--取当前时间
SET @billdate=GETDATE()
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
SET @billdate=(SELECT CONVERT (VARCHAR(10),@billdate,120))

CREATE TABLE #atypeid1(id VARCHAR(1000),NAME VARCHAR(1000),flag varchar(10))
CREATE TABLE #billnumberid(billnumberid BIGINT)
CREATE TABLE #result (msg VARCHAR(200),showid INT)

INSERT INTO #billnumberid( billnumberid )
SELECT a FROM dbo.f_split(@orderids,',')

WHILE 1=1
BEGIN	
	SELECT TOP 1 @orderid= billnumberid  FROM #billnumberid
	
	SELECT @btypeid = btypeid ,
		   @etypeid = etypeid ,
		   @ktypeid= ktypeid ,
		   @GoodsNumber = GoodsNumber ,
		   @dtypeid = DtypeId ,
		   @stypeid = Stypeid ,
		   @cid= CID ,
		   @rate= Rate ,
		   @dealbtypeid = DealBTypeID ,
		   @WmsVchCode = WmsVchCode,
		   @orderbillcode = Billcode
	FROM dbo.OrderIndex
	WHERE billNumberId = @orderid
	
	IF EXISTS(SELECT * FROM dbo.BillIndex WHERE BillType = @billtype AND WmsVchCode = @WmsVchCode AND RedWord = 0)
	BEGIN
		INSERT INTO #result(msg,showid)
		VALUES  ('订单【'+@orderbillcode+'】生成草稿失败：已经生成过相应单据了！',1)
		
		DELETE FROM #billnumberid WHERE billnumberid = @orderid
		
		IF NOT EXISTS(SELECT * FROM #billnumberid)
			BREAK
			
		CONTINUE
	END
	
	TRUNCATE TABLE #atypeid1
	
	INSERT INTO #atypeid1( id, NAME,flag )
	EXEC dbo.Web_GetAtype @billtypeid = @billtype, @stypeid = @stypeid

	SELECT @atypeid1=id FROM #atypeid1	
	
	--是否自定义单据编号
	IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =@billtype)
	BEGIN
		SELECT @MONTH = typeid  FROM employee WHERE typeId=@ETypeId
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.Fullname FROM Employee E WHERE E.TypeId = @OperatorID
		SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId = @dtypeid
	END

		--生成单据编号
		EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'XK',@billdate,@STypeId,@billcode OUT,@dfullname,@cefullname,-999

		--主表数据写入
		DECLARE @recvalue INT=0		
		SET @BillNumberId = 0
		SET @errormsg = ''
		
		EXEC @recvalue=Gp_InsertBillIndex 
					@BillDate=@billdate,
					@BillCode=@billcode,
					@BillType=@billtype,
					@Comment='未完成的销售订单生成的WMS销售出库单',
					@ATypeID='',
					@PTypeID='',
					@BTypeID=@btypeid,
					@ETypeID=@etypeid,
					@KTypeID=@ktypeid,
					@KTypeID2='',
					@IfCheck='f',
					@CheckE=@OperatorID,
					@TotalMoney=@totalmoney,
					@TotalQty=@totalqty,
					@TotalInMoney=0,
					@Tax='0',
					@szPeriod=1,
					@Explain='',
					@Draft='True',
					@RedWord='False',
					@OrderID=0,
					@WayBillCode='',
					@Goodsnumber=@GoodsNumber,
					@PackWay='',
					@Tel='',
					@preferencemoney=0,
					@AlertDay=9999,
					@Assessor='',
					@IfAudit='',
					@Audit_Explain='',
					@Dtypeid=@dtypeid,
					@VipCardID=-1,
					@KTypeID3='',
					@LinkMan='',
					@LinkTel='',
					@LinkAddr='',
					@wxManID='',
					@JieJianBillNumberID=-1,
					@JieJianID=-1,
					@BaoXiuBillNumberID=-1,
					@BaoXiuID=-1,
					@BuyDate='',
					@Serial='',
					@wxTotal=0,
					@ErrDes='',
					@ifHideJieJian=0,
					@ifWX=0,
					@IfBargainOn=0,
					@STypeID=@stypeid,
					@FromBillNumberID=0,
					@CostSale=0,
					@completedate='9999-12-31 23:59:59',
					@billstate=1,
					@ifmulaccount=0,
					@vipczmoney=0,
					@otherinouttype=-1,
					@czbeforetimes=0,
					@posbilltype=0,
					@TransportId=0,
					@IsFreightMoney=0,
					@FreightAddr=NULL,
					@freightperson=NULL,
					@freighttel=NULL,
					@ShareMode=0,
					@uf1='',
					@uf2='',
					@uf3='',
					@uf4='',
					@uf5='',
					--9.0新字段
					@dealbtypeid=@dealbtypeid,		--结算单位
					@cid=@cid,			--外币币种id
					@rate=@rate,			--汇率
					@ntotalmoney=@totalmoney,		--原币种金额
					@ntotalinmoney=0,	--原币收现金额
					@npreferencemoney=0,	--原币优惠金额
					@nvipczmoney=0,		--原币会员卡充值金额
					@atypeid1=@atypeid1,
					@billproperty=-1,					--单据属性
					@ncompletetotal	=0,		--原币结算金额
					@isini=0,
					@ATID=0,					--过账模板
					@CompleteTotal=0,
					@IfCargo=0,
					@IfInvoice=0,
					@promoruleid=0,
					@beforepromobillnumberid=0,
					@promotionmsg='',
					@isyapi=0,
					@yapiorderid=0	,
					@DeliveryAddress='',
					@Discount=1,
					@AdpriceType=0,	
					@checkSave='bill_allow_save'
				
	IF @recvalue = -1 
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：试用版最多录200条单据！'
	ELSE IF @recvalue = -2 
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：录单日期小于本期开始日期！'		
	ELSE IF @recvalue = -3 
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：校验错误 ！'		
	ELSE IF @recvalue = -4
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：录单日期必须与当前日期一致！'
	ELSE IF @recvalue = -5 
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：更新单据发生错误！'		
	ELSE IF @recvalue IS NULL
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：未知原因！'

	IF @errormsg <> ''
	BEGIN
		INSERT INTO #result(msg,showid)
		VALUES  (@errormsg,1)
		
		DELETE FROM #billnumberid WHERE billnumberid = @orderid
		
		IF NOT EXISTS(SELECT * FROM #billnumberid)
			BREAK
			
		CONTINUE
	END 
	
	SET @BillNumberId = @recvalue

	IF @BillNumberId IS NULL
		RETURN -10
		
	--保存单据编号的种子数
	EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
	
	--明细表数据写入
	INSERT INTO SaleBill 
	(
		[BillNumberId],
		[PtypeId],
		[Qty],
		[SalePrice],
		[discount],
		[DiscountPrice],
		[jobnumber],
		[total],
		[OutFactoryDate],
		[TaxPrice],
		[TaxTotal],
		[comment],
		OrderID,
		[isUnit2],
		[Serial],
		[GoodsNumber],
		[ProduceDate],
		[ValidDate],
		[GoodsBTypeID],
		Tax,
		SaleTotal,
		KTypeID,
		STypeID,--,ShareFee
		ItemID,--自由项id
		CargoID,
		CurMDiscountPrice,
		CurMSalePrice,
		CurMTaxPrice,
		UnitID,
		UnitRate,
		NTotal,
		TaxMoney,
		NDiscountPrice,
		NQty,
		NSalePrice,
		NSaleTotal,
		NTaxMoney,
		NTaxPrice,
		NTaxTotal,
		NUnitID,
		NUnitMsg,
		MDiscountPrice,
		MQty,
		MSalePrice,
		MTaxPrice,
		MUnitID,
		MUnitMsg,
		MUnitRate,
		IsCombined,
		pricesource,
		promotype,
		goodscostprice,
		ETypeID,
		IsGift
	)
	SELECT	@BillNumberId AS BillNumberId,
			a.ptypeid AS ptypeid,
			(a.qty-a.ReachQty) AS qty,
			a.price AS saleprice,
			a.Discount AS discount,
			a.DiscountPrice AS discountprice,
			'' AS jobnumber,
			CASE 
				WHEN a.reachqty = 0 THEN a.total
				ELSE ROUND((a.qty-a.ReachQty)*a.DiscountPrice,2)
			END AS total,
			@billdate AS OutFactoryDate,
			a.TaxPrice AS taxprice,
			CASE
				WHEN a.reachqty = 0 THEN a.TaxTotal
				ELSE ROUND((a.qty-a.ReachQty)*a.TaxPrice,2)
			END AS TaxTotal,
			I.Billcode AS comment,--983 540 测试提的bug
			a.OrderID AS orderid,
			a.IsUnit2 AS isunit2,
			'' AS serial,
			a.GoodsNumber,
			a.ProduceDate AS ProduceDate,
			a.ValidDate AS ValidDate,
			'' AS GoodsBTypeID,
			a.Tax AS tax,
			CASE
				WHEN a.reachqty = 0 THEN a.saletotal
				ELSE ROUND((a.qty-a.ReachQty)*a.price,2)
			END AS saletotal,
			 a.KTypeID  AS ktypeid,
			a.Stypeid AS stypeid,--,'' AS ShareFeeBill
			a.ItemID,
			a.CargoID AS cargoid,							
			a.curmdiscountprice AS curmdiscountprice,--大单位原币折后价
			a.curmsaleprice as curmsaleprice,--大单位原币单价
			a.curmtaxprice AS curmtaxprice,--大单位原币含税价
			a.UnitID,
			a.UnitRate,
			CASE
				WHEN a.reachqty = 0 THEN a.ntotal
				--ELSE a.NTotal*(1-a.ReachQty/a.qty)
				ELSE ROUND((a.qty-a.ReachQty)*a.nDiscountPrice,2)
			END AS ntotal,
			a.TaxMoney,--本币税额
			a.NDiscountPrice,--原币折后单价
			a.NQty*(1-a.ReachQty/a.qty) AS nqty,
			a.NSalePrice,--原币单价
			CASE
				WHEN a.reachqty = 0 THEN a.nsaletotal
				ELSE ROUND((a.qty-a.ReachQty)*a.NSalePrice,2)
			END AS nsaletotal,--原币金额
			a.NTaxMoney,--原币税额
			a.NTaxPrice,--原币含税单价
			CASE
				WHEN a.reachqty = 0 THEN a.ntaxtotal
				ELSE ROUND((a.qty-a.ReachQty)*NTaxPrice,2)
			END AS ntaxtotal,						--原币价税合计
			a.NUnitID,
			a.NUnitMsg,
			a.MDiscountPrice AS MDiscountPrice,--大单位折后价							
			ROUND((a.Qty-a.ReachQty)/isnull(a.MunitRate,1),@intQtyDot) AS mqty,--大单位数量
			a.MSalePrice,--大单位单价
			a.MTaxPrice,--大单位含税价
			a.munitid ,
			a.MUnitMsg,
			a.MunitRate,
			a.IsCombined,
			'来自销售订单生成：['+a.pricesource+']' AS pricesource,
			a.promotype,
			-1 as goodscostprice,
			I.etypeid,
			a.IsGift
	FROM	OrderBill a
	INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
	WHERE A.billNumberID =@orderid
	ORDER BY a.OrderID
		
	UPDATE dbo.SaleBill SET ShowOrder=ID WHERE BillNumberId=@BillNumberId
		
	UPDATE dbo.BillIndex SET totalmoney=(SELECT SUM(nTaxTotal) FROM dbo.SaleBill WHERE BillNumberId = @BillNumberId)
							,ntotalmoney=(SELECT SUM(nTaxTotal) FROM dbo.SaleBill WHERE BillNumberId = @BillNumberId)
							,totalqty =(SELECT SUM(Qty) FROM SaleBill WHERE BillNumberId = @BillNumberId)
							,IsUploadWms = 1
							--,WmsTaskId = @wmstaskid
							,WmsVchCode = @WmsVchCode
							,IsFromWms = 1
	WHERE  BillNumberId = @BillNumberId
	
		-- 自动生成的单据会影响草稿库存
	EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,@billtype	
		
	SET @errormsg = '订单【'+@orderbillcode+'】已成草稿【'+@billcode+'】，对应Wms单号【'+@WmsVchCode+'】。'
	INSERT INTO #result(msg,showid)
	VALUES  (@errormsg,2)
	
	DELETE FROM #billnumberid WHERE billnumberid = @orderid
	
	IF NOT EXISTS(SELECT * FROM #billnumberid)
		BREAK
END

--UPDATE OrderBill SET WaitQty=WaitQty+qty-ReachQty WHERE	OrderID IN (SELECT *FROM f_split(@orderid,',')) 

SELECT * FROM #result

DROP TABLE #atypeid1,#billnumberid,#result
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_WmsTaskToBuyBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Gp_WmsTaskToBuyBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：lhl
	日期：2018-10-23
	描述：wms入库任务到erp采购入库单
*/
CREATE PROCEDURE Gp_WmsTaskToBuyBill
( 
	@WmsTask		Tb_WmsTask READONLY
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #result (msg VARCHAR(200),showid INT)

SELECT * 
INTO #WmsTask
FROM @WmsTask w
WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillType = 34 AND RedWord = 0 AND WmsTaskId = w.wmstaskid)

IF NOT EXISTS(SELECT TOP 1 1 FROM #WmsTask)
BEGIN
	INSERT INTO #result(msg,showid)
	VALUES  ('所有订单对应的任务均已生成草稿。',1)	
	
	SELECT * FROM #result
	
	DROP TABLE #WmsTask,#result
	
	RETURN
END

DECLARE @billdate		DATETIME,
		@billcode		VARCHAR(200),
		@stypeid		VARCHAR(50),
		@etypeid		VARCHAR(50),
		@btypeid		VARCHAR(50),
		@dtypeid		VARCHAR(50),
		@ktypeid		VARCHAR(50),
		@totalmoney		NUMERIC(24, 10) ,
		@totalqty		NUMERIC(24, 10) ,
		@tax			NUMERIC(24, 10) ,
		@BillNumberId	NUMERIC(24, 10) ,
		@DAY			VARCHAR(10),
		@MONTH			VARCHAR(10),
		@dealbtypeid	VARCHAR(100),--结算单位
		@cid			VARCHAR(100),
		@rate			VARCHAR(100),
		@GoodsNumber	VARCHAR(100),
		@intQtyDot		INT,
		@cefullname		VARCHAR(500)='',
		@dfullname		VARCHAR(500)='',
		@wmstaskid		VARCHAR(50),
		@OperatorId		VARCHAR(50),
		@billtype		INT,
		@atypeid1		VARCHAR(50),
		@orderid		BIGINT,
		@ordertype		INT,
		@orderbillcode	VARCHAR(200),
		@errormsg		VARCHAR(200),
		@recvalue		INT
		
SET @OperatorId = '00001'
SET @billtype=34

--数量的小数位数
EXEC	@intQtyDot=Gp_GetDigit 1

--取当前时间
SET @billdate=GETDATE()
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)
SET @billdate=(SELECT CONVERT (VARCHAR(10),@billdate,120))

CREATE TABLE #atypeid1(id VARCHAR(1000),NAME VARCHAR(1000),flag varchar(10))

WHILE 1=1
BEGIN
	--数据准备	
	SET @recvalue=0	
	SET @BillNumberId = 0	
	SET @errormsg = ''
	SET @billcode = ''
	SET @atypeid1 = ''

	SELECT TOP 1 @orderid= billnumberid ,@ordertype = billtype ,@wmstaskid = wmstaskid FROM #WmsTask
	
	--IF @ordertype <> 301
	--BEGIN
	--	UPDATE dbo.BillIndex SET wmstaskid = @wmstaskid WHERE BillNumberId = @orderid
	--	DELETE FROM #WmsTask WHERE wmstaskid = @wmstaskid
	--	CONTINUE
	--END
	
	------------订单对应的任务需要生成入库单草稿-------------------
	
	SELECT @btypeid = btypeid ,
		   @etypeid = etypeid ,
		   @ktypeid= ktypeid ,
		   @GoodsNumber = GoodsNumber ,
		   @dtypeid = DtypeId ,
		   @stypeid = Stypeid ,
		   @cid= CID ,
		   @rate= Rate ,
		   @dealbtypeid = DealBTypeID ,
		   @orderbillcode = Billcode
	FROM dbo.OrderIndex
	WHERE billNumberId = @orderid
	
	TRUNCATE TABLE #atypeid1
	
	INSERT INTO #atypeid1( id, NAME,flag )
	EXEC dbo.Web_GetAtype @billtypeid = @billtype, @stypeid = @stypeid

	SELECT @atypeid1=id FROM #atypeid1	
	
	--是否自定义单据编号
	IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype =@billtype)
	BEGIN
		SELECT @MONTH = typeid  FROM employee WHERE typeId=@ETypeId
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
		SELECT @cefullname = E.Fullname FROM Employee E WHERE E.TypeId = @OperatorId
		SELECT @dfullname = d.FullName FROM dbo.Department d WHERE d.TypeId = @dtypeid
	END

	--生成单据编号
	EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'JK',@billdate,@STypeId,@billcode OUT,@dfullname,@cefullname,-999
	
	EXEC @recvalue=Gp_InsertBillIndex 
				@BillDate=@billdate,
				@BillCode=@billcode,
				@BillType=@billtype,
				@Comment='未完成的采购订单生成的WMS采购入库单',
				@ATypeID='',
				@PTypeID='',
				@BTypeID=@btypeid,
				@ETypeID=@etypeid,
				@KTypeID=@ktypeid,
				@KTypeID2='',
				@IfCheck='f',
				@CheckE=@OperatorId,
				@TotalMoney=@totalmoney,
				@TotalQty=@totalqty,
				@TotalInMoney=0,
				@Tax='0',
				@szPeriod=1,
				@Explain='',
				@Draft='True',
				@RedWord='False',
				@OrderID=0,
				@WayBillCode='',
				@Goodsnumber=@GoodsNumber,
				@PackWay='',
				@Tel='',
				@preferencemoney=0,
				@AlertDay=9999,
				@Assessor='',
				@IfAudit='',
				@Audit_Explain='',
				@Dtypeid=@dtypeid,
				@VipCardID=-1,
				@KTypeID3='',
				@LinkMan='',
				@LinkTel='',
				@LinkAddr='',
				@wxManID='',
				@JieJianBillNumberID=-1,
				@JieJianID=-1,
				@BaoXiuBillNumberID=-1,
				@BaoXiuID=-1,
				@BuyDate='',
				@Serial='',
				@wxTotal=0,
				@ErrDes='',
				@ifHideJieJian=0,
				@ifWX=0,
				@IfBargainOn=0,
				@STypeID=@stypeid,
				@FromBillNumberID=0,
				@CostSale=0,
				@completedate='9999-12-31 23:59:59',
				@billstate=1,
				@ifmulaccount=0,
				@vipczmoney=0,
				@otherinouttype=-1,
				@czbeforetimes=0,
				@posbilltype=0,
				@TransportId=0,
				@IsFreightMoney=0,
				@FreightAddr=NULL,
				@freightperson=NULL,
				@freighttel=NULL,
				@ShareMode=0,
				@uf1='',
				@uf2='',
				@uf3='',
				@uf4='',
				@uf5='',
				--9.0新字段
				@dealbtypeid=@dealbtypeid,		--结算单位
				@cid=@cid,			--外币币种id
				@rate=@rate,			--汇率
				@ntotalmoney=@totalmoney,		--原币种金额
				@ntotalinmoney=0,	--原币收现金额
				@npreferencemoney=0,	--原币优惠金额
				@nvipczmoney=0,		--原币会员卡充值金额
				@atypeid1=@atypeid1,
				@billproperty=-1,					--单据属性
				@ncompletetotal	=0,		--原币结算金额
				@isini=0,
				@ATID=0,					--过账模板
				@CompleteTotal=0,
				@IfCargo=0,
				@IfInvoice=0,
				@promoruleid=0,
				@beforepromobillnumberid=0,
				@promotionmsg='',
				@isyapi=0,
				@yapiorderid=0	,
				@DeliveryAddress='',
				@Discount=1,
				@AdpriceType=0,	
				@checkSave='bill_allow_save'
				
	IF @recvalue = -1 
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：试用版最多录200条单据！'
	ELSE IF @recvalue = -2 
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：录单日期小于本期开始日期！'		
	ELSE IF @recvalue = -3 
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：校验错误 ！'		
	ELSE IF @recvalue = -4
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：录单日期必须与当前日期一致！'
	ELSE IF @recvalue = -5 
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：更新单据发生错误！'		
	ELSE IF @recvalue IS NULL
		SET @errormsg = '订单【'+@orderbillcode+'】生成草稿失败：未知原因！'

	IF @errormsg <> ''
	BEGIN
		INSERT INTO #result(msg,showid)
		VALUES  (@errormsg,1)
		
		DELETE FROM #WmsTask WHERE wmstaskid = @wmstaskid
		
		IF NOT EXISTS(SELECT * FROM #WmsTask)
			BREAK
			
		CONTINUE
	END 
	
	SET @BillNumberId = @recvalue
				
	--明细表数据写入
	INSERT INTO BuyBill 
	(
		[BillNumberId],
		[PtypeId],
		[Qty],
		[SalePrice],
		[discount],
		[DiscountPrice],
		[jobnumber],
		[total],
		[OutFactoryDate],
		[TaxPrice],
		[TaxTotal],
		[comment],
		OrderID,
		[isUnit2],
		[Serial],
		[GoodsNumber],
		[ProduceDate],
		[ValidDate],
		[GoodsBTypeID],
		Tax,
		SaleTotal,
		KTypeID,
		STypeID,--,ShareFee
		ItemID,--自由项id
		CargoID,
		CurMDiscountPrice,
		CurMSalePrice,
		CurMTaxPrice,
		UnitID,
		UnitRate,
		NTotal,
		TaxMoney,
		NDiscountPrice,
		NQty,
		NSalePrice,
		NSaleTotal,
		NTaxMoney,
		NTaxPrice,
		NTaxTotal,
		NUnitID,
		NUnitMsg,
		MDiscountPrice,
		MQty,
		MSalePrice,
		MTaxPrice,
		MUnitID,
		MUnitMsg,
		MUnitRate,
		IsCombined,
		pricesource,			
		goodscostprice,
		IsGift
	)
	SELECT	@BillNumberId AS BillNumberId,
			a.ptypeid AS ptypeid,
			ws.qty AS qty,
			a.price AS saleprice,
			a.Discount AS discount,
			a.DiscountPrice AS discountprice,
			'' AS jobnumber,
			ROUND((ws.qty)*a.DiscountPrice,2)AS total,
			@billdate AS OutFactoryDate,
			a.TaxPrice AS taxprice,
			ROUND((ws.qty)*a.TaxPrice,2) AS TaxTotal,
			I.Billcode AS comment,--983 540 测试提的bug
			a.OrderID AS orderid,
			a.IsUnit2 AS isunit2,
			'' AS serial,
			a.GoodsNumber,
			a.ProduceDate AS ProduceDate,
			a.ValidDate AS ValidDate,
			'' AS GoodsBTypeID,
			a.Tax AS tax,
			ROUND((ws.qty)*a.price,2) AS saletotal, 
			a.KTypeID,
			a.Stypeid AS stypeid,
			a.ItemID,
			a.CargoID ,			
			a.curmdiscountprice AS curmdiscountprice,--大单位原币折后价
			a.curmsaleprice as curmsaleprice,--大单位原币单价
			a.curmtaxprice AS curmtaxprice,--大单位原币含税价
			a.UnitID,
			a.UnitRate,
			ROUND((ws.qty)*a.nDiscountPrice,2) AS ntotal,
			a.TaxMoney,--本币税额
			a.NDiscountPrice,--原币折后单价
			a.NQty*(1-a.ReachQty/ws.qty) AS nqty,
			a.NSalePrice,--原币单价
			ROUND((ws.qty)*a.NSalePrice,2) AS nsaletotal,--原币金额
			a.NTaxMoney,--原币税额
			a.NTaxPrice,--原币含税单价
			ROUND((ws.qty)*NTaxPrice,2) AS ntaxtotal,						--原币价税合计
			a.NUnitID,
			a.NUnitMsg,
			a.MDiscountPrice AS MDiscountPrice,--大单位折后价							
			ROUND((ws.qty)/isnull(a.MunitRate,1),@intQtyDot) AS mqty,--大单位数量
			a.MSalePrice,--大单位单价
			a.MTaxPrice,--大单位含税价
			a.munitid ,
			a.MUnitMsg,
			a.MunitRate,
			a.IsCombined,
			'来自采购订单生成：['+a.pricesource+']' AS pricesource,							
			-1 as goodscostprice,
			a.IsGift
	FROM	OrderBill a
	INNER JOIN OrderIndex I ON I.billNumberId=A.billNumberID
	INNER JOIN #WmsTask ws ON ws.billnumberid = a.billNumberID AND ws.detailid = a.OrderID
	WHERE	ws.wmstaskid = @wmstaskid
	ORDER BY a.OrderID
	
	IF NOT EXISTS(SELECT * FROM buybill WHERE BillNumberId = @BillNumberId)
	BEGIN
		DELETE FROM dbo.BillIndex WHERE BillNumberId = @BillNumberId
		SET @errormsg = '订单【'+@orderbillcode+'】对应的任务号【'+@wmstaskid+'】未能正常生成草稿，请确认订单是否正常后重新生成。'
		INSERT INTO #result(msg,showid)
		VALUES  (@errormsg,1)	
	END 
	ELSE
	BEGIN
		UPDATE dbo.BuyBill SET ShowOrder=ID WHERE BillNumberId=@BillNumberId
			
		UPDATE dbo.BillIndex SET totalmoney=(SELECT SUM(TaxTotal) FROM dbo.BuyBill WHERE BillNumberId = @BillNumberId)
								,ntotalmoney=(SELECT SUM(nTaxTotal) FROM dbo.BuyBill WHERE BillNumberId = @BillNumberId)
								,totalqty =(SELECT SUM(Qty) FROM buybill WHERE BillNumberId = @BillNumberId)
								,IsUploadWms = 1
								,WmsTaskId = @wmstaskid
								,IsFromWms = 1
		WHERE  BillNumberId = @BillNumberId		
			
		--保存单据编号的种子数
		EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
		-- 自动生成的单据会影响草稿库存
		EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,@billtype
		
		SET @errormsg = '订单【'+@orderbillcode+'】已成草稿【'+@billcode+'】，对应任务号【'+@wmstaskid+'】。'
		INSERT INTO #result(msg,showid)
		VALUES  (@errormsg,2)
	END 
	
	DELETE FROM #WmsTask WHERE wmstaskid = @wmstaskid
	
	IF NOT EXISTS(SELECT * FROM #WmsTask)
		BREAK
	
END

SELECT * FROM #result

DROP TABLE #atypeid1,#WmsTask,#result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_WMSToCreateErpBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Gp_WMSToCreateErpBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	WMS单据生成ERP单据
-- 时间：	2018-10-12
-- 作者：	GLJ
-- ========================================================================
CREATE PROC [Gp_WMSToCreateErpBill]
(
	@BillNumberId	NUMERIC(24,0),
	@BillType		INT--单据类型
)

AS
SET NOCOUNT ON
DECLARE @SQL VARCHAR(MAX)=''
--销售出库单
IF @BillType=11
	BEGIN
		SET @SQL=''
			
			
	END
--销售退货单
IF @BillType=45
	BEGIN
		SET @SQL=''
	END
--费用单
IF @BillType=36
	BEGIN
		SET @SQL=''
	END
--收款单
IF @BillType=4
	BEGIN
		SET @SQL=''
	END


	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_WriteAcNum_Pro]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_WriteAcNum_Pro]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE Gp_WriteAcNum_Pro
(	
	@isUseAcSystem		VARCHAR(100),
	@erpDogNo			VARCHAR(100),
	@CentificateNo		VARCHAR(100),
	@CentificateNum		VARCHAR(100),
	@IsTopDog			VARCHAR(10) = '0',
	@CorpTel			VARCHAR(200),
	@Mobil				VARCHAR(200),
	@EMail				VARCHAR(200),
	@isSstages			VARCHAR(2) = '0',
	@isSstagesEndDate	VARCHAR(20) = ''
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @chvVersion varchar(50),@chvAcSystem varchar(50)
DECLARE @N int, @intBit int, @intMask int,@Ac INT,@intAcBit int,@intAcMask int

SELECT @Ac = @isUseAcSystem
SELECT @intAcBit = @Ac & 15
SELECT @intAcMask = POWER(2,@intAcBit) ^ POWER(2,@intAcBit+1) ^ POWER(2,@intAcBit+2) ^ POWER(2,@intAcBit+3) ^ POWER(2,@intAcBit+4) ^ POWER(2,@intAcBit+5)

SELECT @chvAcSystem = CAST(( @intAcMask & @Ac ) / POWER(2,@intAcBit) AS varchar(50))

UPDATE SysData  SET SubValue = @chvAcSystem WHERE SubName = 'IsUseAcSystem'
UPDATE SysData1 SET SubValue = @isUseAcSystem WHERE SubNo = 16

IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

DECLARE @chvOffLine varchar(50)
SELECT	@chvOffLine = SubValue
FROM	SysData1
WHERE	SubNo = 1

--处理 0.业务单据即时过账，1.代表业务单据财务过账
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'OffLine' AND SubValue IN (0,1,4,6,8,10)) 
	AND @chvAcSystem = 0
BEGIN
	UPDATE sysdata SET SubValue = 1 WHERE SubName = 'postingparameter'
END

--处理证书和安全码，软件狗号码不相同的时候才修改
IF @CentificateNo <> ''
BEGIN
	UPDATE sysdata1 SET SubValue = @CentificateNo WHERE SubNo = 18
	UPDATE sysdata1 SET SubValue = @CentificateNum WHERE SubNo = 19
END
ELSE IF EXISTS(SELECT TOP 1 1 FROM sysdata1 WHERE SubNo = 10 AND SubValue <> @erpDogNo)
BEGIN
	UPDATE sysdata1 SET SubValue = @CentificateNo WHERE SubNo = 18
	UPDATE sysdata1 SET SubValue = @CentificateNum WHERE SubNo = 19
END

--是否是TOP系列软件狗
UPDATE sysdata1 SET SubValue = @IsTopDog WHERE SubNo = 20

--如果是非总账版本，分支机构调拨只能是买卖关系
--2014.04.09 9.4 非总账允许启用固定资产卡片管理
IF @chvAcSystem = 0
BEGIN
	UPDATE sysdata SET SubValue = '0' WHERE SubName = 'innerstypesaleralation'
END

--注册信息
UPDATE dbo.sysdata1 SET SubValue = @CorpTel WHERE SubName = 'CorpTel'
UPDATE dbo.sysdata1 SET SubValue = @Mobil WHERE SubName = 'Mobil'
UPDATE dbo.sysdata1 SET SubValue = @EMail WHERE SubName = 'EMail'

--分期信息
UPDATE dbo.sysdata1 SET SubValue = @isSstages WHERE SubName = 'isSstages'
UPDATE dbo.sysdata1 SET SubValue = @isSstagesEndDate WHERE SubName = 'isSstagesEndDate'
		
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[gp_WriteValdateNum_Pro]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[gp_WriteValdateNum_Pro]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE                      PROCEDURE gp_WriteValdateNum_Pro
(
	@chvValidateNum		varchar(50),
	@chvOpCounter		varchar(50),
	@chvZCInfo			varchar(100),
	@chvCompanyName		varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @chvValidateNumTemp varchar(50)
DECLARE @chvLanSign varchar(50)
DECLARE @chvAccountNum varchar(50)
DECLARE @intPOS1 int, @intPOS2 int

SET @intPOS1 = CHARINDEX('|', @chvValidateNum)
SET @intPOS2 = CHARINDEX('@', @chvValidateNum)
SET @chvValidateNumTemp = LEFT(@chvValidateNum, @intPOS1 - 1)
SET @chvLanSign = SUBSTRING(@chvValidateNum, @intPOS1 + 1, @intPOS2 - @intPOS1 - 1)
SET @chvAccountNum = RIGHT(@chvValidateNum, LEN(@chvValidateNum) - @intPOS2)

-- ZCInfo
DECLARE @chvIFNewDog varchar(50),@chvZCFlag varchar(50),@chvUseDate varchar(50)
DECLARE @chvDogNo varchar(50),@chvAreaCode varchar(50),@chvAreaName varchar(50)
DECLARE @chvSerialNo varchar(50),@chvZCDate varchar(50),   @chvPosusercount	varchar(50),@chvVerificaDate varchar(50)
DECLARE @intPOS3 int,@intPOS4 int,@intPOS5 int,@intPOS6 int,@intPOS7 int,@intPOS8 INT,@intPos9 INT,@intPos10 INT

SET @intPOS3 = CHARINDEX('|', @chvZCInfo)
SET @intPOS4 = CHARINDEX('@', @chvZCInfo)
SET @intPOS5 = CHARINDEX('#', @chvZCInfo)
SET @intPOS6 = CHARINDEX('$', @chvZCInfo)
SET @intPOS7 = CHARINDEX('^', @chvZCInfo)
SET @intPOS8 = CHARINDEX('&', @chvZCInfo)
SET @intPos9 = CHARINDEX(';', @chvZCInfo)
SET @intPos10 = CHARINDEX('*', @chvZCInfo)
SET @chvIFNewDog = LEFT(@chvZCInfo, @intPOS3 - 1)
SET @chvZCFlag = SUBSTRING(@chvZCInfo, @intPOS3 + 1,@intPOS4 - @intPOS3 - 1)
SET @chvUseDate = SUBSTRING(@chvZCInfo,@intPOS4 + 1,@intPOS5 - @intPOS4 - 1)
SET @chvDogNo = SUBSTRING(@chvZCInfo,@intPOS5 + 1,@intPOS6 - @intPOS5 - 1)
SET @chvAreaCode = SUBSTRING(@chvZCInfo,@intPOS6 + 1,@intPOS7 - @intPOS6 - 1)
SET @chvSerialNo = SUBSTRING(@chvZCInfo,@intPOS7 + 1,@intPOS8 - @intPOS7 - 1)
SET @chvZCDate = SUBSTRING(@chvZCInfo,@intPOS8 + 1,@intPos9 - @intPOS8 - 1)
SET @chvPosusercount = SUBSTRING(@chvZCInfo,@intPos9 + 1,@intPos10 - @intPOS9 - 1)
SET @chvVerificaDate = RIGHT(@chvZCInfo, LEN(@chvZCInfo) - @intPos10)

SET @chvAreaName = CASE @chvAreaCode
	WHEN '01' THEN '四川'
	WHEN '02' THEN '重庆'
	WHEN '03' THEN '广东'
	WHEN '04' THEN '广西'
	WHEN '05' THEN '海南'
	WHEN '06' THEN '福建'
	WHEN '07' THEN '湖北'
	WHEN '08' THEN '哈尔滨'
	WHEN '09' THEN '辽宁'
	WHEN '10' THEN '吉林'
	WHEN '11' THEN '黑龙江'
	WHEN '12' THEN '北京'
	WHEN '13' THEN '天津'
	WHEN '14' THEN '河北'
	WHEN '15' THEN '内蒙古'
	WHEN '16' THEN '山东'
	WHEN '17' THEN '江苏'
	WHEN '18' THEN '浙江'
	WHEN '19' THEN '上海'
	WHEN '20' THEN '安徽'
	WHEN '21' THEN '江西'
	WHEN '22' THEN '河南'
	WHEN '23' THEN '湖南'
	WHEN '24' THEN '云南'
	WHEN '25' THEN '贵州'
	WHEN '26' THEN '青海'
	WHEN '27' THEN '西藏'
	WHEN '28' THEN '新疆'
	WHEN '29' THEN '陕西'
	WHEN '30' THEN '甘肃'
	WHEN '31' THEN '宁夏'
	WHEN '32' THEN '山西'	
	WHEN '33' THEN '香港'
	WHEN '34' THEN '澳门'
	WHEN '35' THEN '台湾'
	WHEN '36' THEN '其它地区'
	ELSE ' '
	END
-- ZCInfo

DECLARE @chvVersion varchar(50)
DECLARE @N int, @intBit int, @intMask int
DECLARE @chvOffLine varchar(50)
DECLARE @chvEdition varchar(50)

SELECT @N = @chvValidateNumTemp
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @chvVersion = CAST(( @intMask & @N ) / POWER(2,@intBit) AS varchar(50))

---------------------------------修改Sysdata1数据开始---------------------------------
UPDATE SysData1 SET SubValue = @chvValidateNumTemp WHERE SubNo = 2
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

UPDATE SysData1 SET	SubValue = @chvOpCounter WHERE SubNo = 3 
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

UPDATE SysData1 SET	SubValue = @chvLanSign WHERE SubNo = 4
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

UPDATE SysData1 SET SubValue = @chvAccountNum WHERE	SubNo = 5
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

UPDATE SysData1 SET	SubValue = @chvZCFlag WHERE	SubNo = 6
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

UPDATE SysData1 SET	SubValue = @chvUseDate WHERE SubNo = 7
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

UPDATE SysData1 SET	SubValue = @chvIFNewDog WHERE SubNo = 8
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

UPDATE SysData1 SET	SubValue = @chvVerificaDate WHERE SubNo = 33
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1
---------------------------------修改Sysdata1数据结束---------------------------------

---------------------------------软件已经注册写信息开始-------------------------------
UPDATE SysData1	SET	SubValue = LTRIM(RTRIM(@chvDogNo)) WHERE SubNo = 10
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1

UPDATE SysData1	SET	SubValue = LTRIM(RTRIM(@chvPosusercount)) WHERE SubNo = 32
IF @@ROWCOUNT = 0 OR @@ERROR <> 0
	RETURN 1
		
		
IF @chvZCFlag = '1'
BEGIN
	UPDATE SysData1	SET	SubValue = @chvCompanyName WHERE SubNo = 9
	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
		RETURN 1

	UPDATE SysData1	SET	SubValue = @chvAreaName WHERE SubNo = 11
	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
		RETURN 1

	UPDATE SysData1	SET	SubValue = @chvSerialNo WHERE SubNo = 12
	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
		RETURN 1

	UPDATE SysData1	SET	SubValue = CONVERT(VARCHAR(10),@chvZCDate,120)   WHERE	SubNo = 13
	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
		RETURN 1
END
---------------------------------软件已经注册写信息结束-------------------------------
--新软件狗		
IF @chvVersion IN ('12','13','14','15')
BEGIN
	UPDATE SysData1 SET SubValue = @chvVersion WHERE SubNo = 17
	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
		RETURN 1
		
	SELECT @chvEdition = SubValue FROM SysData  WHERE SubName = 'newEdition'
	SELECT @chvOffLine = SubValue FROM SysData1 WHERE SubNo = 17	
END
ELSE
BEGIN
	UPDATE SysData1 SET SubValue = @chvVersion WHERE SubNo = 1
	IF @@ROWCOUNT = 0 OR @@ERROR <> 0
		RETURN 1
		
	SELECT @chvEdition = SubValue FROM SysData  WHERE SubName = 'Edition'
	SELECT @chvOffLine = SubValue FROM SysData1 WHERE SubNo = 1		
END

If @chvOffLine IN ( '0', '2' )	--基础
BEGIN
	IF @chvEdition <> '1'
	BEGIN
		UPDATE SysData SET SubValue = '1' WHERE	SubName = 'Edition'
	END
	IF @chvOffLine = '2'
	BEGIN
		UPDATE SysData1 SET	SubValue = '5' WHERE SubName = '3'
	END
END
ELSE IF @chvOffLine IN ( '1', '3' )	--离线
BEGIN
	IF @chvEdition <> '4'
	BEGIN
		UPDATE SysData SET SubValue = '4' WHERE SubName = 'Edition'
	END
END
ELSE IF @chvOffLine IN ( '4', '5' )	--通讯、电脑
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='ProInfo' AND (SubValue='1' OR SubValue='4'))
	BEGIN
		IF @chvEdition <> '2' AND @chvEdition <> '5'
		BEGIN
			UPDATE SysData SET SubValue = '2' WHERE SubName = 'Edition'
		END
	END
	ELSE
	BEGIN
		IF @chvEdition <> '2'
		BEGIN
			UPDATE SysData SET SubValue = '2' WHERE	SubName = 'Edition'
		END
	END
END
ELSE IF @chvOffLine IN ( '6', '7' )	--服装
BEGIN
	IF @chvEdition <> '5'
	BEGIN
		UPDATE SysData SET SubValue = '5' WHERE	SubName = 'Edition'
	END
END
ELSE IF @chvOffLine IN ( '8', '9' ) --食品
BEGIN
	IF @chvEdition <> '6'
	BEGIN
		UPDATE SysData SET SubValue = '6' WHERE	SubName = 'Edition'
	END
END
ELSE IF @chvOffLine IN ( '10', '11' ) --电脑行业版
BEGIN
	IF @chvEdition <> '8'
	BEGIN
		UPDATE SysData SET SubValue = '8' WHERE	SubName = 'Edition'
	END
END
ELSE IF @chvOffLine IN ( '12', '13' ) --非总账版
BEGIN
	IF @chvEdition <> '9'
	BEGIN
		UPDATE SysData SET SubValue = '9' WHERE	SubName = 'newEdition'
	END
END
ELSE IF @chvOffLine IN ( '14', '15' ) --总账版
BEGIN
	IF @chvEdition <> '10'
	BEGIN
		UPDATE SysData SET SubValue = '10' WHERE SubName = 'newEdition'
	END
END
ELSE
BEGIN
	UPDATE SysData1 SET	SubValue = '2' WHERE SubNo = '1'
	UPDATE SysData1 SET SubValue = '2' WHERE SubNo = '2'
	UPDATE SysData1 SET	SubValue = '5' WHERE SubNo = '3'
	UPDATE SysData1	SET	SubValue = ''  WHERE SubNo = '4'
	UPDATE SysData1	SET	SubValue = ''  WHERE SubNo = '5'
	UPDATE SysData	SET	SubValue = '1' WHERE SubNo = 'Edition'
END

--老新软件狗标识
DECLARE @chvOldEdition VARCHAR(10),
		@chvOldOffLine VARCHAR(10),
		@chvNewEdition VARCHAR(10),
		@chvNewOffLine VARCHAR(10)
		
SELECT @chvOldEdition = SubValue FROM SysData  WHERE SubName = 'Edition'
SELECT @chvOldOffLine = SubValue FROM SysData1 WHERE SubNo = 1		

SELECT @chvNewEdition = SubValue FROM SysData  WHERE SubName = 'newEdition'
SELECT @chvNewOffLine = SubValue FROM SysData1 WHERE SubNo = 17

--新狗正式版，处理老版本为正式版
IF @chvVersion IN ('12','13','14','15')
BEGIN
	IF @chvNewOffLine IN ('12','14')
	BEGIN
		IF @chvOldEdition = '1'
		BEGIN
			UPDATE sysdata1 SET SubValue = '0' WHERE SubNo = 1
		END
		IF @chvOldEdition IN ('2','5') 
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='ProInfo' AND SubValue='2') AND @chvOldEdition ='5'
				UPDATE sysdata1 SET SubValue = '6' WHERE SubNo = 1
			ELSE
				UPDATE sysdata1 SET SubValue = '4' WHERE SubNo = 1
		END
		IF @chvOldEdition = '6'
		BEGIN
			UPDATE sysdata1 SET SubValue = '8' WHERE SubNo = 1
		END
	END
	ELSE
	BEGIN
		IF @chvOldEdition = '1'
		BEGIN
			UPDATE sysdata1 SET SubValue = '2' WHERE SubNo = 1
		END
		IF @chvOldEdition IN ('2','5')
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='ProInfo' AND SubValue='2')  AND @chvOldEdition ='5'
				UPDATE sysdata1 SET SubValue = '7' WHERE SubNo = 1
			ELSE
				UPDATE sysdata1 SET SubValue = '5' WHERE SubNo = 1
		END
		IF @chvOldEdition = '6'
		BEGIN
			UPDATE sysdata1 SET SubValue = '9' WHERE SubNo = 1
		END
	END
END
ELSE	--老狗正式版，处理新狗版本为正式版，否则为试用版
BEGIN
	IF @chvOldOffLine IN ('0','1','4','6','8','10')
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 0)
		BEGIN
			UPDATE sysdata SET SubValue = '9' WHERE SubName = 'newEdition'
			UPDATE sysdata1 SET SubValue = '12' WHERE SubNo = 17
		END
		ELSE
		BEGIN
			UPDATE sysdata SET SubValue = '10' WHERE SubName = 'newEdition'
			UPDATE sysdata1 SET SubValue = '14' WHERE SubNo = 17
		END		 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'IsUseAcSystem' AND SubValue = 0)
		BEGIN
			UPDATE sysdata SET SubValue = '9' WHERE SubName = 'newEdition'
			UPDATE sysdata1 SET SubValue = '13' WHERE SubNo = 17
		END
		ELSE
		BEGIN
			UPDATE sysdata SET SubValue = '10' WHERE SubName = 'newEdition'
			UPDATE sysdata1 SET SubValue = '15' WHERE SubNo = 17
		END
	END
END

--处理数据
DECLARE @lsRe	INT,
		@vRe	INT
		
EXEC @lsRe = GP_CheckLanSing 1

IF @lsRe IN (2,3,5,9,7,11,13,15)
BEGIN
	SET @vRe = 0
END
ELSE
BEGIN
	SET @vRe = 1
END

UPDATE dbo.sysdata SET SubValue = @vRe WHERE SubName = 'fxsysflag'

--EXEC('EXEC Web_QueryTabTr')

--处理注册日期
/*IF @chvZCFlag = '1'
BEGIN
	DECLARE @strZcDate VARCHAR(200)
	SELECT @strZcDate = a FROM dbo.f_split_table(@chvZCDate,';') WHERE nID = 1
	UPDATE dbo.sysdata1 SET SubValue = CONVERT(VARCHAR(10),@strZcDate,120) WHERE SubNo = 13
END
ELSE
BEGIN
	UPDATE dbo.sysdata1 SET SubValue = '' WHERE SubNo = 13
END	*/

--处理SysdataDb里面的AccountDbList的dogno
BEGIN TRY
	DECLARE @upSQL		VARCHAR(1000)
	
	SET @upSQL = 'DECLARE @isActive	VARCHAR(10)			
	
				IF EXISTS(SELECT TOP 1 1 FROM dbo.A8ZTInfo)
					SELECT @isActive = Actived FROM dbo.A8ZTInfo
				ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.V3ZTInfo)
					SELECT @isActive = Actived FROM dbo.V3ZTInfo
				ELSE IF EXISTS(SELECT TOP 1 1 FROM dbo.V1ZTInfo)
					SELECT @isActive = Actived FROM dbo.V1ZTInfo
				
				UPDATE	SysDataDB.dbo.AccountDbList 
				SET		dogno	= LTRIM(RTRIM('''+@chvDogNo+''')),
						Actived = @isActive
				WHERE	DbName	= DB_NAME() '
	EXEC(@upSQL)				
END TRY
BEGIN CATCH
END CATCH

--维护SysdataDb中rwxsysadmin的值
UPDATE SYSDATADB.DBO.RWXsysadmin SET islimlogin = 0 WHERE ISNULL(dognumber,'') = ''


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertCallBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertCallBill]
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertCallBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertCallBillDT]
GO


/*
写报修单明细
*/
CREATE      PROCEDURE GP_Wx_InsertCallBillDT (
	@details TBType_Wx_Call READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_Call (
	BillNumberID,
	PTypeID,
	isUnit2,
	BuyDate,
	ErrDes,
	ErrDeal,
	Total,
	ETypeID,
	BaoXiu,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid 
	,ShowOrder	
)
SELECT
	BillNumberID,	
	PTypeID,		
	intIsUnit2,		
	BuyDate,		
	ErrDes,		
	ErrDeal,		
	Total,		
	ETypeID,		
	BaoXiu,		
	Comment,		
	Serial,		
	OutFactoryDate,	
	STypeID		
	-- 9.0新字段
	,ItemId 
	,IsCombined 
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid 	
	,ShowOrder
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertGetBackBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertGetBackBill]
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertGetBackBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertGetBackBillDT]
GO


/*
写取件单明细
*/
create   PROCEDURE GP_Wx_InsertGetBackBillDT (
	@details TBType_Wx_GetBack READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_GetBack (
	BillNumberID,
	PTypeID,
	isUnit2,
	JieJianBillNumberID,
	JieJianID,
	JieJianPTypeID,
	Total,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid
	,ShowOrder
)
SELECT 
	BillNumberID,
	PTypeID,
	intIsUnit2,
	JieJianBillNumberID,
	JieJianID,
	JieJianPTypeID,
	wxTotal,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid 	
	,ShowOrder
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertGotoBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertGotoBill]
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertGotoBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertGotoBillDT]
GO


/*
写上门维修单明细
*/
CREATE       PROCEDURE GP_Wx_InsertGotoBillDT (
	@details TBType_Wx_Goto READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_Goto (
	BillNumberID,
	InOrOut,
	PTypeID,
	Qty,
	isUnit2,
	Price,
	Total,
	Comment,
	Serial,
	wxProperty,
	OutFactoryDate,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,cargoid 	
	,GoodsCostTotal
	,ShowOrder
	,KTypeId
)
SELECT
	BillNumberID,
	InOrOut,
	PTypeID,
	Qty,
	intIsUnit2,
	Price,
	Total,
	Comment,
	Serial,
	wxProperty,
	OutFactoryDate,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,cargoid 	
	,GoodsCostTotal
	,ShowOrder
	,KTypeId
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertInBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertInBill]
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertInBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertInBillDT]
GO


/*
写维修品调入单明细
*/
CREATE      PROCEDURE GP_Wx_InsertInBillDT (
	@details TBType_Wx_In READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_In (
	BillNumberID,
	PTypeID,
	Qty,
	isUnit2,
	Price,
	Total,
	Comment,
	Serial,
	OutFactoryDate,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,cargoid 	
	,GoodsCostTotal
	,ShowOrder
	,KTypeID
)
SELECT
	BillNumberID,
	PTypeID,
	Qty,
	intIsUnit2,
	Price,
	Total,
	Comment,
	Serial,
	OutFactoryDate,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,cargoid 	
	,GoodsCostTotal
	,ShowOrder
	,KTypeID
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertJieJianBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertJieJianBill]
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertJieJianBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertJieJianBillDT]
GO

/*
作者：廖晨羽
描述：写入销售出库单明细表(表值)
*/
CREATE              PROCEDURE [GP_Wx_InsertJieJianBillDT]
(
	@details TBType_JieJian READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_JieJian (
	BillNumberID,
	PTypeID,
	isUnit2,
	BuyDate,
	ErrDes,
	ErrDeal,
	Total,
	RepairMode,
	ETypeID,
	BaoXiu,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID,
	--9.0新字段
	ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid	
	,ShowOrder
)
SELECT 
	BillNumberID,
	PTypeID,
	intIsUnit2,
	BuyDate,
	ErrDes,
	ErrDeal,
	Total,
	RepairMode,
	ETypeID,
	BaoXiu,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID,
	--9.0新字段
	ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid
	,ShowOrder
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertMoveBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertMoveBill]
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertMoveBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertMoveBillDT]
GO


/*
写维修品调拨单明细
*/
create     PROCEDURE GP_Wx_InsertMoveBillDT (
	@details TBType_Wx_Move READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_Move (
	BillNumberID,
	PTypeID,
	Qty,
	isUnit2,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid
	,ShowOrder
)
SELECT
	BillNumberID,
	PTypeID,
	Qty,
	intIsUnit2,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,0
	,ShowOrder
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertOutBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertOutBill]
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertOutBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertOutBillDT]
GO


/*
写维修品调出单明细
*/
CREATE       PROCEDURE GP_Wx_InsertOutBillDT (
	@details TBType_Wx_Out READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_Out (
	BillNumberID,
	PTypeID,
	Qty,
	isUnit2,
	Price,
	Total,
	Comment,
	Serial,
	OutFactoryDate,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,cargoid 
	,GoodsCostTotal
	,ShowOrder
	,InFactQty
	,KtypeID
)
SELECT 
	BillNumberID,
	PTypeID	,
	Qty,
	intIsUnit2,	
	Price,		
	Total,		
	Comment,	
	Serial,	
	OutFactoryDate,
	GoodsNumber,
	ProduceDate,	
	ValidDate,	
	GoodsBTypeID,	
	GoodsCostPrice,	
	1,
	STypeID		
	-- 9.0新字段
	,ItemId 
	,IsCombined 
	,NQty 
	,UnitRate
	,cargoid 
	,GoodsCostTotal
	,ShowOrder
	,InFactQty
	,KtypeID
FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertReplaceBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertReplaceBill]
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertReplaceBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertReplaceBillDT]
GO


/*
写整机更换单明细
*/
CREATE     PROCEDURE GP_Wx_InsertReplaceBillDT (
	@details TBType_Wx_Replace READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_Replace (
	BillNumberID,
	PTypeID,
	isUnit2,
	JieJianBillNumberID,
	JieJianID,
	JieJianPTypeID,
	Total,
	Comment,
	Serial,
	wxProperty,
	OutFactoryDate,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,cargoid 	
	,GoodsCostTotal
	,ShowOrder
	,KTypeID
)
SELECT 
	BillNumberID,
	PTypeID,
	intIsUnit2,
	JieJianBillNumberID,
	JieJianID,
	JieJianPTypeID,
	wxTotal,
	Comment,
	Serial,
	wxProperty,
	OutFactoryDate,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,cargoid 	
	,GoodsCostTotal
	,ShowOrder
	,KTypeID
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertSelfBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertSelfBill]
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertSelfBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertSelfBillDT]
GO


/*
写自行维修单明细
*/
CREATE      PROCEDURE GP_Wx_InsertSelfBillDT (
	@details TBType_Wx_Self READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_Self (
	BillNumberID,
	InOrOut,
	PTypeID,
	Qty,
	isUnit2,
	Price,
	Total,
	Comment,
	Serial,
	wxProperty,
	OutFactoryDate,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	-- 9.0新字段
	,ItemId 
	,IsCombined 
	,NQty 
	,UnitRate 
	,cargoid
	,GoodsCostTotal 
	,ShowOrder
	,KTypeID
)
SELECT 
	BillNumberID,
	InOrOut,
	PTypeID,
	Qty,
	intIsUnit2,
	Price,
	Total,
	Comment,
	Serial,
	wxProperty,
	OutFactoryDate,
	InputCostPrice,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	GoodsBTypeID,
	GoodsCostPrice,
	HandZeroCost,
	STypeID
	-- 9.0新字段
	,ItemId 
	,IsCombined 
	,NQty 
	,UnitRate 
	,cargoid 
	,GoodsCostTotal
	,ShowOrder
	,KTypeID
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertSendBackBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertSendBackBill]
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertSendBackBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertSendBackBillDT]
GO


/*
写送修返回单明细
*/
CREATE        PROCEDURE GP_Wx_InsertSendBackBillDT (
	@details TBType_Wx_SendBack READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_SendBack (
	BillNumberID,
	PTypeID,
	isUnit2,
	Qty,
	SendBillNumberID,
	SendID,
	SendPTypeID,
	Total,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID,
	--9.0新字段
	ItemId,
	IsCombined,
	NQty ,
	UnitRate,
	goodsnumber,
	cargoid,
	ShowOrder
)
SELECT
	BillNumberID,
	PTypeID,
	intIsUnit2,
	Qty,
	SendBillNumberID,
	SendID,
	SendPTypeID,
	wxTotal,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID,
	--9.0新字段
	ItemId,
	IsCombined,
	NQty ,
	UnitRate,
	goodsnumber,
	cargoid,
	ShowOrder
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertSendBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertSendBill]
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Wx_InsertSendBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_Wx_InsertSendBillDT]
GO


/*
写送修单明细
*/
CREATE       PROCEDURE GP_Wx_InsertSendBillDT (
	@details TBType_Wx_SendBill READONLY
)
--@encode$--
AS
SET NOCOUNT ON

-- 写入数据表
INSERT INTO wx_Bill_Send (
	BillNumberID,
	PTypeID,
	isUnit2,
	Qty,
	JieJianBillNumberID,
	JieJianID,
	JieJianPTypeID,
	Total,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid
	,errdes1 	
	,ShowOrder
)
SELECT
	BillNumberID,
	PTypeID,
	intIsUnit2,
	Qty,
	JieJianBillNumberID,
	JieJianID,
	JieJianPTypeID,
	wxTotal,
	Comment,
	Serial,
	OutFactoryDate,
	STypeID
	--9.0新字段
	,ItemId
	,IsCombined
	,NQty 
	,UnitRate
	,goodsnumber
	,cargoid
	,errdes1 	
	,ShowOrder
	FROM @details

-- 操作返回值
IF @@ROWCOUNT = 0 RETURN -1	-- 失败
ELSE RETURN 0	-- 成功


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[GP_WxInitInsertDetail]')
                    AND TYPE IN ( N'P', N'PC' ) ) 
    DROP PROC [dbo].[GP_WxInitInsertDetail]
	
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	By：Haiyang, Li
	Date：2012-6-9
	Description：维修期初保存明细
*/

CREATE PROCEDURE [dbo].[GP_WxInitInsertDetail]
( 
    @PTypeId VARCHAR(50) ,
    @KTypeId VARCHAR(50) ,
    @ProduceDate VARCHAR(50) ,
    @ValidDate VARCHAR(50) ,
    @Detail TBType_WxPtypeInit READONLY
)
--@encode$--    
AS 
    BEGIN
        DELETE  wx_IniGoodsStocks
        WHERE   PTypeId = @pTypeId
                AND KTypeId = @kTypeId;
        INSERT  INTO wx_IniGoodsStocks
                ( PTypeId ,
                  KTypeId ,
                  JobNumber ,
                  OutFactoryDate ,
                  GoodsOrder ,
                  Qty ,
                  Nqty ,
                  GoodsNumber ,
                  ItemID ,
                  Iscombined
	              )
                SELECT  @PTypeId ,
                        @KTypeId ,
                        '' ,
                        GETDATE() ,
                        0 ,
                        qty ,
                        nQty ,
                        goodsNumber ,
                        itemId ,
                        isCombined
                FROM    @Detail;
    END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_WxInitQueryDetails]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_WxInitQueryDetails]
GO

/*
By：Haiyang, Li
Date：2012-06-11
Description：维修期初明细查询
*/
CREATE PROCEDURE [dbo].[GP_WxInitQueryDetails]
    (
      @PTypeId VARCHAR(50) ,	--商品ID
      @KTypeId VARCHAR(50)		--仓库ID
    )
    --@encode$--
AS 
BEGIN
    SET NOCOUNT ON

    SELECT  S.PTypeId ,
            S.KTypeId ,
            S.Qty ,
            S.Nqty ,
            S.Price ,
            S.Total ,
            S.GoodsNumber ,
            V.ItemID ,
            V.Iscombined ,
            V.itemname
    FROM    ( SELECT    PTypeId ,
                        KTypeId ,
                        Qty ,
                        Nqty ,
                        Price ,
                        Total ,
                        GoodsNumber ,
                        ItemID ,
                        Iscombined
              FROM      dbo.wx_IniGoodsStocks
              WHERE     PTypeId = @PTypeId
                        AND KTypeId = @KTypeId
            ) S
            LEFT JOIN dbo.V_Item V ON S.ItemID = V.itemid
                                      AND S.Iscombined = V.iscombined
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_WxInitQueryPTypeInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_WxInitQueryPTypeInfo]
GO

/*
By：Haiyang, Li
Date：2012-06-11
Description：维修期初商品基本信息
*/
CREATE PROCEDURE [dbo].[GP_WxInitQueryPTypeInfo] 
( 
	@PTypeId VARCHAR(50)		--商品ID
)
--@encode$--                                                   
AS 
    SET NOCOUNT ON

    SELECT  P.UserCode ,
            P.FullName ,
            P.Name ,
            P.Standard ,
            P.Type ,
            P.Area , -- 基本信息
            P.customitemid ,
            P.customitemname ,
            P.customitemfrom , -- 自由项
            P.ifusegoodsnum , -- 是否启用批号
            P.usefullifeday , -- 有效期
            P.baseUnitId ,
            U.FullName AS baseunit , --基本单位
            P.AssistantUnitId ,
            U2.FullName AS assistantunit ,-- 浮动单位
            U3.rate
    FROM    ( SELECT    typeId ,
                        UserCode ,
                        FullName ,
                        Name ,
                        Standard ,
                        Type ,
                        Area , -- 基本信息
                        customitemid ,
                        customitemname ,
                        customitemfrom , -- 自由项
                        ifusegoodsnum ,		-- 是否启用批号
                        usefullifeday ,		-- 有效期
                        baseUnitId ,				-- 基本单位id
                        AssistantUnitId		-- 浮动单位id
              FROM      dbo.ptype
              WHERE     typeId = @PTypeId
            ) P
            INNER JOIN dbo.PType_Units U ON P.baseUnitId = U.UnitsId
            INNER JOIN dbo.PType_Units U2 ON P.AssistantUnitId = U2.UnitsId
            INNER JOIN dbo.PType_Units_Ext U3 ON p.AssistantUnitId = U3.UnitsId
                                                 AND P.typeId = U3.PtypeID
            
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_WXInvoiceQueryOldBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_WXInvoiceQueryOldBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：徐辉
	日期：2011-09-30
	描述：维修发票调单开票
*/
CREATE                             PROCEDURE Gp_WXInvoiceQueryOldBill
( 
	 @chvBeginDate	VARCHAR(25),
	 @chvEndDate	VARCHAR(25),
	 @chvBtype		VARCHAR(250),
	 @chvEtype		VARCHAR(250),
	 @chvKtype		VARCHAR(250),
	 @chvstype		VARCHAR(250),
	 @chvBillCode	VARCHAR(250),
	 @chvBillType	VARCHAR(100),	--查询的单据类型
	 @state			INT,			--状态 0：未全部开票 1：已全部开票 2：全部
	 @ptypeid		VARCHAR(100),	--商品（需要穿透查询）
	 @chvOperatorId VARCHAR(50)       --操作员ID
	 
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 往来单位
IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
BEGIN
	DECLARE @chvBTypeAll char(1)
	SET @chvBTypeAll = '0'
	SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'
	
	SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)
	DECLARE @SQL_ManB varchar(100)
	SET @SQL_ManB = ' INNER JOIN #F_BaseGetManDetailBType B ON a.BTypeID = B.TypeID '
	
	IF @chvBTypeAll = '0'
	BEGIN
		IF @chvBillType = '162' AND @chvMBTypeID = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00001%'' '
	
		IF @chvBillType = '163' AND @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00002%'' '
	END
	ELSE
	BEGIN
		IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB
	END
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END

CREATE TABLE #Stype	(TypeID varchar(50))
--分支机构
INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvstype,11,@chvOperatorID)

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('10000')
	INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('') --维修结算单没有仓库
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID OR a.KTypeID2 = K.TypeID '
END

--部门
IF  @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END
-- ******** 权限范围单独处理 - End ********


--明细商品穿透查询
IF @ptypeid<>''
BEGIN
	CREATE TABLE #billnumberid(billnumberid INT)
	
		INSERT #billnumberid SELECT a.billnumberid FROM
			(
			SELECT DISTINCT ReceptionBillnumberId AS billnumberid FROM dbo.Qp_ReceptionBill_FactUsePType WHERE PtypeId = @ptypeid
			UNION
			SELECT DISTINCT billnumberid FROM dbo.QP_QuickRepairBill_PType WHERE PtypeId = @ptypeid
			) a
END


DECLARE @SQL varchar(8000)

SET @SQL = '
	SELECT	DISTINCT a.BillNumberID,a.BillDate,a.BillCode,a.BillType,a.ETypeID,a.TotalMoney,ISNULL(detail.TaxTotal,0) AS TaxTotal,0.0 AS NoInvoiceTotal
	FROM	BillIndex a ' + @SQL_Man + ' INNer join #stype s on s.typeid=a.stypeid
	LEFT JOIN 
		(
			SELECT SUM(fapiaodetails.taxtotal) AS TaxTotal,fapiaodetails.MainBillNumberID AS MainBillNumberID
			FROM
			(
				SELECT MainBillNumberID,SUM(TaxTotal) AS TaxTotal
				FROM FaPiaoBill GROUP BY MainBillNumberID
				UNION ALL
				SELECT MainBillNumberID,SUM(TaxTotal) AS TaxTotal
				FROM qp_invoicerepairitems GROUP BY MainBillNumberID
				UNION ALL
				SELECT MainBillNumberID,SUM(Total) AS TaxTotal
				FROM QP_InvoiceOtherTotalDetails GROUP BY MainBillNumberID
			) fapiaodetails
			GROUP BY fapiaodetails.MainBillNumberID
		) detail 
		ON a.BillNumberID = detail.MainBillNumberID
	WHERE	a.BillDate >= ''' + @chvBeginDate + ''' AND a.BillDate <= ''' + @chvEndDate + '''
			AND a.BillType IN (' + @chvBillType + ')
			AND a.Draft = 0 AND a.RedWord = 0 AND a.IfCheck = ''t'''

IF @chvBillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @chvBillCode + '%'''
IF @chvBType <> '' SET @SQL = @SQL + ' AND a.BTypeID=''' + @chvBType + ''''
IF @chvEType <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @chvEType + ''''
IF @chvstype <> '' SET @SQL = @SQL + ' AND a.sTypeID=''' + @chvstype + ''''
IF @chvKType <> '' SET @SQL = @SQL + ' AND (a.KTypeID=''' + @chvKType + ''' OR a.KTypeID2=''' + @chvKType + ''')'
IF @ptypeid <> '' SET @SQL = @SQL + ' AND a.billnumberid IN(SELECT billnumberid FROM #billnumberid)'
IF @state=0 SET @SQL = @SQL + ' AND a.ifinvoice IN(0,1)'
IF @state=1 SET @SQL = @SQL + ' AND a.ifinvoice IN(2)'
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC,a.BillCode DESC'

EXEC (@SQL)
IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999' DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMDtypeid = '-99999' DROP TABLE #F_BaseGetManDetailDType
IF @ptypeid <> '' DROP TABLE #billnumberid

DROP TABLE #Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Gp_WxqrStockIni]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Gp_WxqrStockIni]
GO




/*
维修库存期初树形表，线性表 cqhua 2009-10-19

*/

CREATE                          PROCEDURE Gp_WxqrStockIni
    (
      @OperatorID VARCHAR(50) ,  	    	--操作员ID号
      @Parid VARCHAR(50) = '00000' ,    --商品的父节点号
      @szKtypeId VARCHAR(1550) = '' ,       --仓库id号
      @szUserCode VARCHAR(26) = '' ,			--商品编号
      @szFullName VARCHAR(66) = '' ,			--商品名称
      @ifLine CHAR(1) = '0' ,                  -- 0 代表树形表，1代表线性表
      @stypeid VARCHAR(8000)
    )
--@encode$--
AS 
    SET NOCOUNT ON
    SET ANSI_WARNINGS OFF
    DECLARE @Sql VARCHAR(8000)   ---肖伟 2002-06-27加速库存状况查询
--------------------------------------------------------------权限检查-------------------------------------------------------
    IF @OperatorID IS NULL 
        RETURN 1
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT
    IF @Re <> 0 
        RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
---------------检查是否开帐
    DECLARE @IniCanModIFy VARCHAR(10)
    SELECT  @IniCanModIFy = subValue
    FROM    sysdata
    WHERE   SubName = 'inicanmodIFy'
---------------上步结束
    IF @szUserCode = '' 
        SET @szUserCode = '%'
    ELSE 
        SET @szUserCode = '%' + @szUserCode + '%'
    IF @szFullName = '' 
        SET @szFullName = '%'
    ELSE 
        SET @szFullName = '%' + @szFullName + '%'


    CREATE TABLE #Ptype
        (
          TypeID VARCHAR(50) ,
          Usercode VARCHAR(26) ,
          fullname VARCHAR(66)
        )
    CREATE TABLE #Ktype ( TypeID VARCHAR(50) )
    CREATE TABLE #MainType
        (
          TypeID VARCHAR(50) ,
          usercode VARCHAR(26) ,
          fullname VARCHAR(100) ,
          sonnum INT ,
          deleted INT ,
          parid VARCHAR(100)
        )

    INSERT  INTO #Ptype
            ( typeid ,
              usercode ,
              fullname
            )
            SELECT  P.typeid ,
                    usercode ,
                    fullname
            FROM    ptype P ,
                    F_GetManDetailPType(@OperatorID) W
            WHERE   P.typeid = W.typeid


    DECLARE @Ksonnum INT
    SET @Ksonnum = 0

    IF @szKtypeID = '' 
        BEGIN
            INSERT  INTO #Ktype
                    SELECT  ks.typeid
                    FROM    F_GetManDetailKTypeSType(@OperatorID) ks
            SET @Ksonnum = 1
        END
    ELSE 
        BEGIN
    --仓库
            INSERT  INTO #Ktype
                    ( typeid
                    )
                    SELECT  kb.TypeId
                    FROM    F_GetAllManagerBaseTypeId(@szKtypeID, 4,
                                                      @OperatorID) kb
            IF CHARINDEX(',', @szKtypeId) > 1 
                SET @Ksonnum = 1
            ELSE 
                SELECT  @Ksonnum = sonnum
                FROM    Stock
                WHERE   typeid = @szKtypeId
        END

    DECLARE @sonnum INT
    SET @sonnum = 0
    SELECT  @sonnum = sonnum
    FROM    Ptype
    WHERE   Typeid = @Parid

/*IF @ifLine =1 -- 线性表
BEGIN
		IF @Parid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
			where typeid in (select typeid from F_GetManDetailPType(@OperatorID))
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
			where typeid in (select typeid from F_GetManDetailPType(@OperatorID) where typeid like @parid+'%')
END
ELSE
BEGIN
	IF @sonnum =0 	
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where typeid =@Parid) a where p.typeid=a.typeid
	ELSE
		IF @Parid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid=@Parid) a where p.typeid=a.typeid
END*/

--CLD
    IF @ifLine = 1 -- 线性表
        BEGIN
            IF @Parid = '00000' 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          parid
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.ParId
                        FROM    Ptype p
                        WHERE   typeid IN (
                                SELECT  typeid
                                FROM    F_GetManDetailPType(@OperatorID) )
            ELSE 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          parid
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.ParId
                        FROM    Ptype p
                        WHERE   typeid IN (
                                SELECT  typeid
                                FROM    F_GetManDetailPType(@OperatorID)
                                WHERE   typeid LIKE @parid + '%' )
        END
    ELSE 
        BEGIN
            IF @sonnum = 0 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          parid
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.ParId
                        FROM    Ptype p ,
                                ( SELECT    *
                                  FROM      F_GetManPTypeAll(@OperatorID)
                                  WHERE     typeid = @Parid
                                ) a
                        WHERE   p.typeid = a.typeid
            ELSE 
                IF @Parid = '00000' 
                    INSERT  INTO #MainType
                            ( typeid ,
                              usercode ,
                              fullname ,
                              sonnum ,
                              deleted ,
                              parid
                            )
                            SELECT  p.typeid ,
                                    p.usercode ,
                                    p.fullname ,
                                    p.sonnum ,
                                    p.deleted ,
                                    p.ParId
                            FROM    Ptype p ,
                                    ( SELECT    *
                                      FROM      F_GetManPTypeAll(@OperatorID)
                                      WHERE     parid = '00000'
                                    ) a
                            WHERE   p.typeid = a.typeid
                ELSE 
                    INSERT  INTO #MainType
                            ( typeid ,
                              usercode ,
                              fullname ,
                              sonnum ,
                              deleted ,
                              parid
                            )
                            SELECT  p.typeid ,
                                    p.usercode ,
                                    p.fullname ,
                                    p.sonnum ,
                                    p.deleted ,
                                    p.ParId
                            FROM    Ptype p ,
                                    ( SELECT    *
                                      FROM      F_GetManPTypeAll(@OperatorID)
                                      WHERE     parid = @Parid
                                    ) a
                            WHERE   p.typeid = a.typeid
        END
--CLD

---------------------------------期除

/*SELECT @Sql='
	SELECT 	a.typeid,
			a.fullname,
			a.usercode,
			a.sonnum,
			a.leveal,
			a.parid,
			a.unit1,
			a.unit2,
			a.unitrate1,
			a.EntryCode,
			a.Standard,
			a.Type,
			a.Area,
			ISNULL(SUM(Z.Gqty),0) AS qty,
			CAST(ISNULL(SUM(Z.Gtotal)/CASE WHEN SUM(Z.Gqty)=0 THEN NULL ELSE SUM(Z.Gqty) END ,0) AS  NUMERIC(24, 10) ) AS Price,			
			ISNULL(SUM(Z.Gtotal),0) AS total,
			ISNULL(SUM(Z.Zqty),0) AS dxqty,
			ISNULL(SUM(Z.Ztotal),0) AS dxtotal,
	'+Convert(varchar(10),@Ksonnum)+' as ksonnum
    FROM 	#MainType a
	LEFT JOIN	 (
					SELECT	A.TypeId,
							SUM(G.Qty) AS GQty,
							SUM(G.Total) AS GTotal,
							CAST(ISNULL(SUM(g.total)/CASE WHEN SUM(g.qty)=0 THEN NULL ELSE SUM(g.qty) END ,0) AS  NUMERIC(24, 10) ) AS GPrice,
							0 AS ZQty,
							0 AS ZTotal,
							0 AS ZPrice
					FROM	Wx_IniGoodsStocks G,
							#PType A,
							#Ktype K
					WHERE	G.PTypeId = A.TypeId
							AND G.KtypeID = K.typeid
							AND A.UserCode LIKE '+char(39)+'%'+@szUserCode+'%'+char(39)+'
							AND A.FullName LIKE '+char(39)+'%'+@szFullName+'%'+char(39)+'
					GROUP BY A.TypeId
			)Z ON LEFT(Z.TypeId,LEN(A.TypeId)) = A.TypeId
	WHERE	A.Deleted=0 '*/
-----CLD
    SELECT  @Sql = '
	SELECT 	a.typeid,
			a.parid,
			a.fullname,
			a.usercode,
			a.sonnum,
			ISNULL(SUM(Z.Gqty),0) AS qty,
			CAST(ISNULL(SUM(Z.Gtotal)/CASE WHEN SUM(Z.Gqty)=0 THEN NULL ELSE SUM(Z.Gqty) END ,0) AS  NUMERIC(24, 10) ) AS Price,			
			ISNULL(SUM(Z.Gtotal),0) AS total,
			ISNULL(SUM(Z.Zqty),0) AS dxqty,
			ISNULL(SUM(Z.Ztotal),0) AS dxtotal,
	' + CONVERT(VARCHAR(10), @Ksonnum)
            + ' as ksonnum
    FROM 	#MainType a
	LEFT JOIN	 (
					SELECT	A.TypeId,
							SUM(G.Qty) AS GQty,
							SUM(G.Total) AS GTotal,
							CAST(ISNULL(SUM(g.total)/CASE WHEN SUM(g.qty)=0 THEN NULL ELSE SUM(g.qty) END ,0) AS  NUMERIC(24, 10) ) AS GPrice,
							0 AS ZQty,
							0 AS ZTotal,
							0 AS ZPrice
					FROM	Wx_IniGoodsStocks G
                             INNER JOIN #PType A ON G.PTypeId = A.TypeId '

    IF NOT ( @szKtypeId = ''
             AND @MKTypeId = '00001'
           ) 
        SELECT  @Sql = @Sql + ' INNER JOIN #Ktype K ON G.KtypeID = K.typeid '
							
    SELECT  @Sql = @Sql + ' WHERE   A.UserCode LIKE ' + CHAR(39) + '%'
            + @szUserCode + '%' + CHAR(39) + '
							AND A.FullName LIKE ' + CHAR(39) + '%' + @szFullName + '%'
            + CHAR(39) + '
					GROUP BY A.TypeId
			)Z ON LEFT(Z.TypeId,LEN(A.TypeId)) = A.TypeId
	WHERE	1=1  '

	--如果商品编号和商品名称都为空
    IF @szUserCode = '%'
        AND @szFullName = '%' 
        IF @ifLine = '1' 
            SET @SQL = @SQL + ' AND a.sonnum = 0  AND a.typeid<>''00000'''
        ELSE 
            SET @SQL = @SQL + ' '
    ELSE 
        SET @SQL = @SQL + ' AND a.sonnum = 0'

    SET @SQL = @SQL + '
			AND A.UserCode LIKE ' + CHAR(39) + '%' + @szUserCode + '%' + CHAR(39)
        + '
			AND A.FullName LIKE ' + CHAR(39) + '%' + @szFullName + '%' + CHAR(39)
        + '
	GROUP BY
			a.typeid,
			a.parid,
			a.fullname,
			a.usercode,
			a.sonnum
	ORDER BY A.UserCode '	
-----CLD
--PRINT @SQL						
    EXEC(@SQL)
    DROP TABLE #Ktype,#Ptype,#MainType


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_WxStockInitBaseQuery]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_WxStockInitBaseQuery]
GO




/*
维修库存期初树形表，线性表 cqhua 2009-10-19

*/

CREATE PROCEDURE GP_WxStockInitBaseQuery
    (
      @OperatorID VARCHAR(50) ,  	    	--操作员ID号
      @Parid VARCHAR(50) = '00000' ,    --商品的父节点号
      @ktypeid VARCHAR(1550) = '' ,       --仓库id号
      @userCode VARCHAR(26) = '' ,			--商品编号
      @fullName VARCHAR(66) = '' ,			--商品名称
      @ifLine CHAR(1) = '0' ,                  -- 0 代表树形表，1代表线性表
      @stypeid VARCHAR(8000)
    )
--@encode$--
AS 
    SET NOCOUNT ON
    SET ANSI_WARNINGS OFF
    DECLARE @Sql VARCHAR(8000)   ---肖伟 2002-06-27加速库存状况查询
--------------------------------------------------------------权限检查-------------------------------------------------------
    IF @OperatorID IS NULL 
        RETURN 1
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT
    IF @Re <> 0 
        RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
---------------检查是否开帐
    DECLARE @IniCanModIFy VARCHAR(10)
    SELECT  @IniCanModIFy = subValue
    FROM    sysdata
    WHERE   SubName = 'inicanmodIFy'
---------------上步结束
    IF @userCode = '' 
        SET @userCode = '%'
    ELSE 
        SET @userCode = '%' + @userCode + '%'
    IF @fullName = '' 
        SET @fullName = '%'
    ELSE 
        SET @fullName = '%' + @fullName + '%'


    CREATE TABLE #Ptype
        (
          TypeID VARCHAR(50) ,
          Usercode VARCHAR(26) ,
          fullname VARCHAR(66)
        )
    CREATE TABLE #Ktype ( TypeID VARCHAR(50) )
    CREATE TABLE #MainType
        (
          TypeID VARCHAR(50) ,
          usercode VARCHAR(26) ,
          fullname VARCHAR(100) ,
          sonnum INT ,
          deleted INT ,
          parid VARCHAR(100),
          sortid INT
        )

    INSERT  INTO #Ptype
            ( typeid ,
              usercode ,
              fullname
            )
            SELECT  P.typeid ,
                    usercode ,
                    fullname
            FROM    ptype P ,
                    F_GetManDetailPType(@OperatorID) W
            WHERE   P.typeid = W.typeid
            AND p.iscombinationproduct=0


    DECLARE @Ksonnum INT
    SET @Ksonnum = 0

    IF @ktypeid = '' 
        BEGIN
            INSERT  INTO #Ktype
                    SELECT  ks.typeid
                    FROM    F_GetManDetailKTypeSType(@OperatorID) ks
            SET @Ksonnum = 1
        END
    ELSE 
        BEGIN
    --仓库
            INSERT  INTO #Ktype
                    ( typeid
                    )
                    SELECT  kb.TypeId
                    FROM    F_GetAllManagerBaseTypeId(@ktypeid, 4,
                                                      @OperatorID) kb
            IF CHARINDEX(',', @ktypeid) > 1 
                SET @Ksonnum = 1
            ELSE 
                SELECT  @Ksonnum = sonnum
                FROM    Stock
                WHERE   typeid = @ktypeid
        END

    DECLARE @sonnum INT
    SET @sonnum = 0
    SELECT  @sonnum = sonnum
    FROM    Ptype
    WHERE   Typeid = @Parid

/*IF @ifLine =1 -- 线性表
BEGIN
		IF @Parid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
			where typeid in (select typeid from F_GetManDetailPType(@OperatorID))
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
			where typeid in (select typeid from F_GetManDetailPType(@OperatorID) where typeid like @parid+'%')
END
ELSE
BEGIN
	IF @sonnum =0 	
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where typeid =@Parid) a where p.typeid=a.typeid
	ELSE
		IF @Parid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,parid,deleted,unit1,unit2,unitrate1,type,area,standard,entrycode,leveal) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.parid,p.deleted,p.unit1,p.unit2,p.unitrate1,p.type,p.area,p.standard,p.entrycode,p.leveal FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid=@Parid) a where p.typeid=a.typeid
END*/

--CLD
    IF @ifLine = 1 -- 线性表
        BEGIN
            IF @Parid = '00000' 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          parid
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.ParId
                        FROM    Ptype p
                        WHERE   typeid IN (
                                SELECT  typeid
                                FROM    F_GetManDetailPType(@OperatorID) ) AND p.IsService=0
                                AND p.iscombinationproduct=0
            ELSE 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          parid
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.ParId
                        FROM    Ptype p
                        WHERE   typeid IN (
                                SELECT  typeid
                                FROM    F_GetManDetailPType(@OperatorID)
                                WHERE   typeid LIKE @parid + '%' )AND p.IsService=0
                                AND p.iscombinationproduct=0
        END
    ELSE 
        BEGIN
            IF @sonnum = 0 
                INSERT  INTO #MainType
                        ( typeid ,
                          usercode ,
                          fullname ,
                          sonnum ,
                          deleted ,
                          parid,
                          sortid
                        )
                        SELECT  p.typeid ,
                                p.usercode ,
                                p.fullname ,
                                p.sonnum ,
                                p.deleted ,
                                p.ParId,
                                p.sortid
                        FROM    Ptype p ,
                                ( SELECT    *
                                  FROM      F_GetManPTypeAll(@OperatorID)
                                  WHERE     typeid = @Parid
                                ) a
                        WHERE   p.typeid = a.typeid AND p.IsService=0
                        AND p.iscombinationproduct=0
            ELSE 
                IF @Parid = '00000' 
                    INSERT  INTO #MainType
                            ( typeid ,
                              usercode ,
                              fullname ,
                              sonnum ,
                              deleted ,
                              parid,
                              sortid
                            )
                            SELECT  p.typeid ,
                                    p.usercode ,
                                    p.fullname ,
                                    p.sonnum ,
                                    p.deleted ,
                                    p.ParId,
                                    p.sortid
                            FROM    Ptype p ,
                                    ( SELECT    *
                                      FROM      F_GetManPTypeAll(@OperatorID)
                                      WHERE     parid = '00000'
                                    ) a
                            WHERE   p.typeid = a.typeid AND p.IsService=0
                            AND p.iscombinationproduct=0
                ELSE 
                    INSERT  INTO #MainType
                            ( typeid ,
                              usercode ,
                              fullname ,
                              sonnum ,
                              deleted ,
                              parid,
                              sortid
                            )
                            SELECT  p.typeid ,
                                    p.usercode ,
                                    p.fullname ,
                                    p.sonnum ,
                                    p.deleted ,
                                    p.ParId,
                                    p.sortid
                            FROM    Ptype p ,
                                    ( SELECT    *
                                      FROM      F_GetManPTypeAll(@OperatorID)
                                      WHERE     parid = @Parid
                                    ) a
                            WHERE   p.typeid = a.typeid AND p.IsService=0
                            AND p.iscombinationproduct=0
        END
--CLD

---------------------------------期除

/*SELECT @Sql='
	SELECT 	a.typeid,
			a.fullname,
			a.usercode,
			a.sonnum,
			a.leveal,
			a.parid,
			a.unit1,
			a.unit2,
			a.unitrate1,
			a.EntryCode,
			a.Standard,
			a.Type,
			a.Area,
			ISNULL(SUM(Z.Gqty),0) AS qty,
			CAST(ISNULL(SUM(Z.Gtotal)/CASE WHEN SUM(Z.Gqty)=0 THEN NULL ELSE SUM(Z.Gqty) END ,0) AS  NUMERIC(24, 10) ) AS Price,			
			ISNULL(SUM(Z.Gtotal),0) AS total,
			ISNULL(SUM(Z.Zqty),0) AS dxqty,
			ISNULL(SUM(Z.Ztotal),0) AS dxtotal,
	'+Convert(varchar(10),@Ksonnum)+' as ksonnum
    FROM 	#MainType a
	LEFT JOIN	 (
					SELECT	A.TypeId,
							SUM(G.Qty) AS GQty,
							SUM(G.Total) AS GTotal,
							CAST(ISNULL(SUM(g.total)/CASE WHEN SUM(g.qty)=0 THEN NULL ELSE SUM(g.qty) END ,0) AS  NUMERIC(24, 10) ) AS GPrice,
							0 AS ZQty,
							0 AS ZTotal,
							0 AS ZPrice
					FROM	Wx_IniGoodsStocks G,
							#PType A,
							#Ktype K
					WHERE	G.PTypeId = A.TypeId
							AND G.KtypeID = K.typeid
							AND A.UserCode LIKE '+char(39)+'%'+@userCode+'%'+char(39)+'
							AND A.FullName LIKE '+char(39)+'%'+@fullName+'%'+char(39)+'
					GROUP BY A.TypeId
			)Z ON LEFT(Z.TypeId,LEN(A.TypeId)) = A.TypeId
	WHERE	A.Deleted=0 '*/
-----CLD
    SELECT  @Sql = '
	SELECT 	a.typeid,
			a.parid,
			a.fullname,
			a.usercode,
			a.sonnum,
			ISNULL(SUM(Z.Gqty),0) AS qty,
			CAST(ISNULL(SUM(Z.Gtotal)/CASE WHEN SUM(Z.Gqty)=0 THEN NULL ELSE SUM(Z.Gqty) END ,0) AS  NUMERIC(24, 10) ) AS Price,			
			ISNULL(SUM(Z.Gtotal),0) AS total,
			ISNULL(SUM(Z.Zqty),0) AS dxqty,
			ISNULL(SUM(Z.Ztotal),0) AS dxtotal,
	' + CONVERT(VARCHAR(10), @Ksonnum)
            + ' as ksonnum
    FROM 	#MainType a
	LEFT JOIN	 (
					SELECT	A.TypeId,
							SUM(G.Qty) AS GQty,
							SUM(G.Total) AS GTotal,
							CAST(ISNULL(SUM(g.total)/CASE WHEN SUM(g.qty)=0 THEN NULL ELSE SUM(g.qty) END ,0) AS  NUMERIC(24, 10) ) AS GPrice,
							0 AS ZQty,
							0 AS ZTotal,
							0 AS ZPrice
					FROM	Wx_IniGoodsStocks G
                             INNER JOIN #PType A ON G.PTypeId = A.TypeId '

    IF NOT ( @ktypeid = ''
             AND @MKTypeId = '00001'
           ) 
        SELECT  @Sql = @Sql + ' INNER JOIN #Ktype K ON G.KtypeID = K.typeid '
							
    SELECT  @Sql = @Sql + ' WHERE   A.UserCode LIKE ' + CHAR(39) + '%'
            + @userCode + '%' + CHAR(39) + '
							AND A.FullName LIKE ' + CHAR(39) + '%' + @fullName + '%'
            + CHAR(39) + '
					GROUP BY A.TypeId
			)Z ON LEFT(Z.TypeId,LEN(A.TypeId)) = A.TypeId
	WHERE	1=1  '

	--如果商品编号和商品名称都为空
    IF @userCode = '%'
        AND @fullName = '%' 
        IF @ifLine = '1' 
            SET @SQL = @SQL + ' AND a.sonnum = 0  AND a.typeid<>''00000'''
        ELSE 
            SET @SQL = @SQL + ' '
    ELSE 
        SET @SQL = @SQL + ' AND a.sonnum = 0'

    SET @SQL = @SQL + '
			AND A.UserCode LIKE ' + CHAR(39) + '%' + @userCode + '%' + CHAR(39)
        + '
			AND A.FullName LIKE ' + CHAR(39) + '%' + @fullName + '%' + CHAR(39)
        + '
	GROUP BY
			a.typeid,
			a.parid,
			a.fullname,
			a.usercode,
			a.sonnum '
	 IF @ifLine = '0' 
		 SET @SQL = @SQL + ' ,a.sortid ORDER BY A.sortid asc '
	 ELSE
		 SET @SQL = @SQL + ' ORDER BY A.UserCode '
		
	
-----CLD
--PRINT @SQL						
    EXEC(@SQL)
    DROP TABLE #Ktype,#Ptype,#MainType


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[GP_WxStockInitInsertDetail]')
                    AND TYPE IN ( N'P', N'PC' ) ) 
    DROP PROC [dbo].[GP_WxStockInitInsertDetail]
	
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	By：Haiyang, Li
	Date：2012-6-9
	Description：维修期初保存明细
	Edit：2015-04-28 SiHuaShan 增加序列号插入
*/

CREATE PROCEDURE [dbo].[GP_WxStockInitInsertDetail]
(
    @PTypeId VARCHAR(50) ,
    @KTypeId VARCHAR(50) ,
    @ProduceDate VARCHAR(50) ,
    @ValidDate VARCHAR(50) ,
    @Detail TBType_WxStockInit READONLY,
    @IsDelSerial BIT-- 是否删除明细， 有表体删除，无表体不删除
)
--@encode$--    
AS 
    BEGIN
        DECLARE @STypeID VARCHAR(50);
        
        DELETE  wx_IniGoodsStocks
        WHERE   PTypeId = @pTypeId
                AND KTypeId = @kTypeId;
        
        --删除原序列号
		SELECT @STypeID=Stypeid FROM  STock WHERE typeId=@KTypeId;
		IF @IsDelSerial=1
		BEGIN
			DELETE  FROM gp_initPtypeSerial WHERE State=25 AND PtypeID=@PTypeId AND KTypeId=@KTypeId AND STypeId=@StypeId;
		END
		
        INSERT  INTO wx_IniGoodsStocks
                ( PTypeId ,
                  KTypeId ,
                  JobNumber ,
                  OutFactoryDate ,
                  GoodsOrder ,
                  Qty ,
                  Nqty ,
                  GoodsNumber ,
                  ItemID ,
                  Iscombined
	              )
                SELECT  @PTypeId ,
                        @KTypeId ,
                        '' ,
                        GETDATE() ,
                        0 ,
                        qty ,
                        nQty ,
                        goodsNumber ,
                        itemId ,
                        isCombined
                FROM    @Detail;
			
------------序列号开始-----------------

      SELECT  SUM(qty) AS qty ,
		      SUM(nqty) AS nqty ,
		      goodsNumber ,
		      itemId,
		      isCombined,
		      Serial,
		      ROW_NUMBER() OVER(ORDER BY goodsNumber,ItemId,IsCombined) AS RowIndex
	 INTO    #ImportWxStockDetails
	 FROM    @Detail
	 GROUP BY goodsNumber ,
	          itemId ,
	          isCombined,
	          Serial;
			
	DECLARE @RowCount INT,    --总函数
			@RowIndex INT,    --当前行号
			@Serial	 VARCHAR(MAX),   --序列号
			@GoodsNumber VARCHAR(100),   --批号
			@ItemId  VARCHAR(100),   --自由项
			@IsCombined INT;
	
	SELECT @RowCount=COUNT(1) FROM #ImportWxStockDetails;
	IF @RowCount=0  
	BEGIN
		DROP TABLE #ImportWxStockDetails;
		RETURN;
	END
	SET @RowIndex=1;
	
	WHILE(@RowIndex<=@RowCount)
	BEGIN
		SELECT  @Serial=Serial,
				@GoodsNumber=GoodsNumber,
				@ItemId=ItemId,
				@IsCombined=isCombined
		FROM #ImportWxStockDetails  WHERE RowIndex=@RowIndex
		
		IF @GoodsNumber IS NULL
			SET @GoodsNumber='';
		--插入新序列号
		INSERT INTO  gp_initPtypeSerial
						([Serial],
						 [KtypeID],
						 [PtypeID],
						 [state],
						 [Flag],
						 [CommissionState],
						 iniFlag,
						 STypeId,
						 GoodsNumber,
						 ItemID,
						 IsCombined
						)
		SELECT Serial,
			   @KTypeId,
			   @PTypeId,
			   25,
			   1,
			   '',
			   1,
			   @StypeId,
			   @GoodsNumber,
			   @ItemId,
			   @IsCombined FROM F_SplitSerial(@Serial,'я') WHERE Serial<>''
			   ;
			   
		SET @RowIndex+=1;
	END
    DROP TABLE #ImportWxStockDetails
    DELETE  wx_IniGoodsStocks WHERE Qty = 0
    END
    
------------序列号插入结束-----------------
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_WxStockInitQueryDetails]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_WxStockInitQueryDetails]
GO

/*
By：Haiyang, Li
Date：2012-06-11
Description：维修期初明细查询
*/
CREATE PROCEDURE [dbo].[GP_WxStockInitQueryDetails]
    (
      @PTypeId VARCHAR(50) ,	--商品ID
      @KTypeId VARCHAR(50)		--仓库ID
    )
    --@encode$--
AS 
BEGIN
    SET NOCOUNT ON

    SELECT  S.PTypeId ,
            S.KTypeId ,
            S.Qty ,
            S.Nqty ,
            S.Price ,
            S.Total ,
            S.GoodsNumber ,
            V.ItemID ,
            V.Iscombined ,
            V.itemname,
            Z.STypeID
    FROM    ( SELECT    PTypeId ,
                        KTypeId ,
                        Qty ,
                        Nqty ,
                        Price ,
                        Total ,
                        GoodsNumber ,
                        ItemID ,
                        Iscombined
              FROM      dbo.wx_IniGoodsStocks
              WHERE     PTypeId = @PTypeId
                        AND KTypeId = @KTypeId
            ) S
            LEFT JOIN dbo.V_Item V ON S.ItemID = V.itemid
                                      AND S.Iscombined = V.iscombined
            LEFT JOIN dbo.Stock  Z ON S.KTypeId=Z.typeId
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GP_WxStockInitQueryPTypeInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GP_WxStockInitQueryPTypeInfo]
GO

/*
By：Haiyang, Li
Date：2012-06-11
Description：维修期初商品基本信息
*/
CREATE PROCEDURE [dbo].[GP_WxStockInitQueryPTypeInfo] 
( 
	@PTypeId VARCHAR(50)		--商品ID
)
--@encode$--
AS 
    SET NOCOUNT ON

    SELECT  P.UserCode ,
            P.FullName ,
            P.Name ,
            P.Standard ,
            P.Type ,
            P.Area , -- 基本信息
            P.customitemid ,
            P.customitemname ,
            P.customitemfrom , -- 自由项
            P.ifusegoodsnum , -- 是否启用批号
            P.usefullifeday , -- 有效期
            P.baseUnitId ,
            U.FullName AS baseunit , --基本单位
            P.AssistantUnitId ,
            U2.FullName AS assistantunit ,-- 浮动单位
            U3.rate,
            p.IfSerial,
            P.SerialCount
    FROM    ( SELECT    typeId ,
                        UserCode ,
                        FullName ,
                        Name ,
                        SerialCount,
                        IfSerial,
                        Standard ,
                        Type ,
                        Area , -- 基本信息
                        customitemid ,
                        customitemname ,
                        customitemfrom , -- 自由项
                        ifusegoodsnum ,		-- 是否启用批号
                        usefullifeday ,		-- 有效期
                        baseUnitId ,				-- 基本单位id
                        AssistantUnitId		-- 浮动单位id
              FROM      dbo.ptype
              WHERE     typeId = @PTypeId
            ) P
            INNER JOIN dbo.PType_Units U ON P.baseUnitId = U.UnitsId
            LEFT JOIN dbo.PType_Units U2 ON P.AssistantUnitId = U2.UnitsId
            LEFT JOIN dbo.PType_Units_Ext U3 ON p.AssistantUnitId = U3.UnitsId
                                                 AND P.typeId = U3.PtypeID
            
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Yapi_CreateSaleOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_Yapi_CreateSaleOrderBill
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2013-10-27
	描述：保存云分销单据下载种子数seedid
-------------------------------------------*/
CREATE PROCEDURE [dbo].GP_Yapi_CreateSaleOrderBill
(
	@orderid VARCHAR(20)
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE @period INT=1,@cid INT =1,@billnumberid NUMERIC(10,0)=0,@tax DECIMAL=0,@gridtype INT =0,@discount  NUMERIC(24, 10) =1
SELECT @period=subvalue FROM dbo.sysdata WHERE SubName='period'
SELECT @cid=cid FROM dbo.Ac_Currency WHERE Sysrow=1
SELECT @tax=Value FROM dbo.Userconfig WHERE ConfigName ='AllTaxRate'
SELECT @discount=Value FROM dbo.Userconfig WHERE ConfigName ='zekouvalue'
SELECT @gridtype = VALUE FROM dbo.Userconfig WHERE ConfigName='gridtype'
IF @gridtype IN (2,3)
	SET @tax=0
IF @gridtype IN (1,3)	
	SET @discount=1

DECLARE @STypeId	VARCHAR(50),
		@KTypeId	VARCHAR(50),
		@CargoId	VARCHAR(50)
	
IF EXISTS(SELECT TOP 1 1 FROM Yapi_OrderBillIndex O INNER JOIN SType S ON S.Sid = O.SID WHERE orderid = @orderid)
BEGIN
	SELECT @STypeId = S.TypeId FROM Yapi_OrderBillIndex O INNER JOIN SType S ON S.Sid = O.SID WHERE orderid = @orderid
	SELECT TOP 1 @KTypeId = typeid FROM stock WHERE STypeID = @STypeId AND deleted = 0 AND sonnum = 0 ORDER BY typeid ASC
END
ELSE
BEGIN
	SELECT @STypeId = STypeId,@KTypeId = KTypeId FROM Yapi_OrderBillIndex WHERE OrderId = @orderid
END

SELECT @CargoId = CargoId FROM CargoType WHERE KTypeId = @KTypeId


INSERT INTO [dbo].[OrderIndex] 
  (
		[btypeid],
		DealBTypeID,
		stypeid,
		[BillDate],
		[Billcode],
		[billtype],
		[totalmoney],
		[totalqty],
		[period],
		[comment],
		[explain],
		[Tax],
		NTotalMoney,
		CID,
		Rate,
		isyapi,
		yapiorderid,		
		ktypeid
) 
SELECT	b.btypeid,
		b.btypeid,
		@STypeId,
		CONVERT(DATETIME,CONVERT(DATE,billdate)),
		billcode,
		300,
		TotalMoney,
		totalqty,
		@period,
		i.Comment,
		BuyerComment,
		@tax,
		TotalMoney,
		@cid,
		1,
		1,
		@orderid,		
		@KTypeId
from dbo.Yapi_OrderBillIndex i
INNER JOIN dbo.Yapi_btypeBindMerchant b ON i.buyerid=b.MerchantId
WHERE orderid=@orderid


IF @@ERROR<>0 OR @@ROWCOUNT=0
BEGIN
	RAISERROR('写入销售订单主表错误',16,1)
	RETURN
END

SELECT @billnumberid=@@IDENTITY

INSERT INTO dbo.OrderBill
        ( billNumberID ,
          ptypeid ,
          qty ,
          price ,
          total ,
          comment ,
          Discount ,
          DiscountPrice ,
          TaxPrice ,
          TaxTotal ,       
          SaleTotal ,
          Tax ,
          TaxMoney ,
          NSalePrice ,
          NSaleTotal ,
          NDiscountPrice ,
          NTotal ,
          NTaxPrice ,
          NTaxTotal ,
          NTaxMoney ,         
	      UnitID ,
          NUnitID ,
          NQty ,
          UnitRate ,
          MUnitID ,
          MQty ,
          MUnitRate ,
          MSalePrice ,
          MDiscountPrice ,
          MTaxPrice ,       
          CurMSalePrice ,
          CurMDiscountPrice ,
          CurMTaxPrice ,
          ItemID ,
          IsCombined,
          YapiID,
          stypeid,
          KtypeId,
          CargoID 
        )
SELECT	@billnumberid,
		b.typeid,
		Qty=a.qty,
		CAST(a.price/(@discount*(1+@tax/100)) AS  NUMERIC(24, 10) ),
		CAST(a.total/(1+@tax/100) AS  NUMERIC(24, 10) ) AS total,
		a.Comment,
		@discount,
		CAST(a.price/(1+@tax/100) AS  NUMERIC(24, 10) ),
		a.price,
		a.total AS taxtotal,
		
		CAST(a.total/(@discount*(1+@tax/100)) AS  NUMERIC(24, 10) ),
		@tax AS tax,
		a.Total-CAST(a.Total/(1+@tax/100) AS  NUMERIC(24, 10) ),
		CAST(a.price/(@discount*(1+@tax/100)) AS  NUMERIC(24, 10) ) AS nsaleprice,
		CAST(a.total/(@discount*(1+@tax/100)) AS  NUMERIC(24, 10) ) AS nsaletotal,
		ndiscountprice=CAST(a.price/(1+@tax/100) AS  NUMERIC(24, 10) ),
		ntotal =CAST(a.Total/(1+@tax/100) AS  NUMERIC(24, 10) ),
		a.Price AS ntaxprice,
		ntaxtotal = a.Total,
		ntaxmoney = a.Total-CAST(a.Total/(1+@tax/100) AS  NUMERIC(24, 10) ),
		unitid = b.baseUnitId,
		b.AssistantUnitId,
		CASE WHEN ISNULL(b.AssistantUnitId,0) = 0 THEN NULL
			ELSE CAST(a.qty / we.rate AS  NUMERIC(24, 10) )	END as nqty,
	    CASE WHEN ISNULL(b.AssistantUnitId,0) = 0 THEN NULL
				ELSE we.rate END AS UnitRate,
		MUnitID = b.baseUnitId,
		mqty = a.qty,
		munitrate=1,
		msaleprice=CAST(a.Price/(@discount*(1+@tax/100)) AS  NUMERIC(24, 10) ),		
		mdiscountprice=CAST(a.price/(1+@tax/100) AS  NUMERIC(24, 10) ),
		mtaxprice=a.price,					
		curmsaleprice = CAST(a.price/(@discount*(1+@tax/100)) AS  NUMERIC(24, 10) ),
		curmdiscountprice=CAST(a.price /(1+@tax/100) AS  NUMERIC(24, 10) ),
		curmtaxprice = a.price,		
		itemid=0,
		iscombined=0,
		CAST(a.id AS VARCHAR),
		@stypeid,
		@ktypeid,
		@cargoid
FROM	dbo.Yapi_OrderBill a
INNER JOIN
(
	select Ptypeid,OnLineID from Yapi_PtypeRelation
	union all
	select distinct Ptypeid,OnLineID from 
	(
	select RANK() over(partition by OnLineID order by ptypeid desc ) as sort, Ptypeid,OnLineID from Yapi_SupplierPtypeRelation p 
	where Not exists (select 1 from Yapi_PtypeRelation where OnLineID=p.OnLineID))a where sort=1
) yp ON yp.OnLineID=a.goodsid
INNER JOIN ptype b ON b.Typeid=yp.ptypeid
LEFT JOIN dbo.PType_Units_Ext we ON we.PtypeID=b.typeId AND we.UnitsId=b.AssistantUnitId		
WHERE a.Orderid=@Orderid

IF @@ERROR<>0
BEGIN
	RAISERROR('写入销售订单明细数据错误',16,1)
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Yapi_SaveOrderBillDT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_Yapi_SaveOrderBillDT
GO

/*
作者：韩林
描述：写入云分销明细表(表值)
*/
CREATE  PROCEDURE Gp_Yapi_SaveOrderBillDT
(
	@details TBType_Yapi_OrderBill READONLY
)
--@encode$--
AS 
SET NOCOUNT ON

IF EXISTS(SELECT 1 FROM @details d WHERE orderid IN(SELECT orderid FROM dbo.Yapi_OrderBillIndex WHERE  billtype=0)
		AND NOT EXISTS
		(
			SELECT 1 FROM
			(
				select Ptypeid,OnLineID from Yapi_PtypeRelation
				union all
				select distinct Ptypeid,OnLineID from 
				(
				select RANK() over(partition by OnLineID order by ptypeid desc ) as sort, Ptypeid,OnLineID from Yapi_SupplierPtypeRelation p 
				where Not exists (select 1 from Yapi_PtypeRelation where OnLineID=p.OnLineID) AND ISNULL(p.Ptypeid,'')<>'')a where sort=1
			)b WHERE b.OnLineID=d.goodsid
		 )
	 )
begin
	RAISERROR('订单商品本地不存在',16,1)
	RETURN
END

INSERT INTO dbo.Yapi_OrderBill
( 
	id ,
	Orderid ,
	goodsid ,
	Qty ,
	Price ,
	Total ,
	Comment ,
	Unitid
)
SELECT  id,
		Orderid ,
		goodsid ,
		Qty ,
		Price ,
		Total ,
		Comment ,
		Unitid
FROM	@details


if @@rowcount=0 or @@Error<>0
 RAISERROR('插入单据发生错误！',16,1)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Yapi_SaveOrderIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_Yapi_SaveOrderIndex
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2013-10-27
	描述：保存云分销销售订单主表
-------------------------------------------*/
CREATE PROCEDURE [dbo].GP_Yapi_SaveOrderIndex
(
	@billdate		VARCHAR(20),
	@billcode		VARCHAR(200),
	@orderid		DECIMAL(20,0),
	@Explain		VARCHAR(256),
	@Comment		VARCHAR(256),
	@BuyerComment	VARCHAR(256),
	@Buyerid		DECIMAL(20,0),
	@TotalMoney		NUMERIC(24, 10) ,
	@TotalQty		NUMERIC(24, 10) ,
	@billtype		INT,
	@sid			INT,
	@stypeid		VARCHAR(50),
	@ktypeid		VARCHAR(50)
)
--@encode$--
AS 
SET NOCOUNT ON

INSERT INTO dbo.Yapi_OrderBillIndex
(
	orderid ,
	billcode ,
	billdate ,
	STATUS ,
	sid,
	TotalMoney ,
	TotalQty,
	Comment ,
	BuyerComment ,
	buyerid ,
	billtype,
	STypeID,
	KtypeId
)
VALUES  
( 
	@orderid,
	@billcode,
	@billdate,
	1,
	@sid,
	@totalmoney,
	@totalqty,
	@comment,
	@BuyerComment,
	@Buyerid,
	@billtype,
	@stypeid,
	@ktypeid		
)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Yapi_SavePtypeSeedID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_Yapi_SavePtypeSeedID
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2013-10-27
	描述：保存云分销单据下载种子数seedid
-------------------------------------------*/
CREATE PROCEDURE [dbo].GP_Yapi_SavePtypeSeedID
(
	@supplierid NUMERIC(20,0),
	@seedid  NUMERIC(20,0)
)
--@encode$--
AS 
SET NOCOUNT ON
	IF NOT EXISTS(SELECT 1 FROM Yapi_SupplierPtypeSeedID WHERE supplierid=@supplierid AND seedid >=@seedid)
	BEGIN
		IF EXISTS(SELECT 1 FROM Yapi_SupplierPtypeSeedID WHERE supplierid=@supplierid)
			UPDATE Yapi_SupplierPtypeSeedID SET SEEDID=@seedid WHERE supplierid=@supplierid
		ELSE
			INSERT INTO Yapi_SupplierPtypeSeedID(supplierid,seedid) VALUES(@supplierid,@seedid)
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_Yapi_SaveSeedID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].GP_Yapi_SaveSeedID
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2013-10-27
	描述：保存云分销单据下载种子数seedid
-------------------------------------------*/
CREATE PROCEDURE [dbo].GP_Yapi_SaveSeedID
(
	@billtype INT,
	@seedid  NUMERIC(20,0)
)
--@encode$--
AS 
SET NOCOUNT ON
	IF NOT EXISTS(SELECT 1 FROM Yapi_BillSeedID WHERE billtype=@billtype AND seedid >=@seedid)
	BEGIN
		IF EXISTS(SELECT 1 FROM Yapi_BillSeedID WHERE billtype=@billtype)
			UPDATE Yapi_BillSeedID SET SEEDID=@seedid WHERE billtype=@billtype
		ELSE
			INSERT INTO Yapi_BillSeedID(billtype,seedid) VALUES(@billtype,@seedid)
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Yapi_SaveSupplierPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_Yapi_SaveSupplierPtype
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
	作者：韩林
	日期：2013-12-10
	描述：保存供货商商品信息
-------------------------------------------*/
CREATE PROCEDURE Gp_Yapi_SaveSupplierPtype
(
	@ptype TBType_Yapi_SupplierPtype READONLY
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @usercode VARCHAR(100),@fullname VARCHAR(200),@pycode VARCHAR(50),@unitname VARCHAR(100),@area VARCHAR(200),@standard VARCHAR(100),
		@type VARCHAR(100),@unitid INT,@ptypeid VARCHAR(50),@goodsid NUMERIC(20,0),@skuid NUMERIC(20,0),@xwmaxnumber DECIMAL(10,0)=0,
		@price1  NUMERIC(24, 10) ,@price2  NUMERIC(24, 10) ,@price3  NUMERIC(24, 10) ,@price4  NUMERIC(24, 10) ,@price5  NUMERIC(24, 10) ,@retailprice  NUMERIC(24, 10) ,@returnvalue INT=0

DECLARE createptype CURSOR FOR
SELECT goodsid,skuid,usercode,fullname,pycode,unitname,area,STANDARD,type,price1,price2,price3,price4,price5,retailprice
FROM @ptype p
WHERE NOT EXISTS(SELECT 1 FROM dbo.ptype WHERE UserCode=p.usercode AND FullName=p.fullname)
		AND NOT EXISTS(SELECT 1 FROM dbo.Yapi_SupplierPtypeRelation WHERE SupplierID=p.supplierid AND OnLineID=p.goodsid)
OPEN createptype	
FETCH NEXT FROM createptype
INTO @goodsid,@skuid,@usercode,@fullname,@pycode,@unitname,@area,@standard,@type,@price1,@price2,@price3,@price4,@price5,@retailprice
WHILE @@FETCH_STATUS = 0 
BEGIN
	IF NOT EXISTS(SELECT 1 FROM dbo.PType_Units WHERE FullName=@unitname)
		INSERT INTO dbo.PType_Units ( UserCode, FullName, Comment )VALUES  ( @unitname,@unitname,'')
	SELECT @unitid=UnitsId FROM dbo.PType_Units
	
	EXEC @returnvalue= Gp_createId '00000', 'ptype', @ptypeid OUT,0 ,0
	SELECT @xwmaxnumber= MAX(XiWaMaxNumber)+1 FROM ptype
	if @returnvalue=-2 
	BEGIN
		RAISERROR('无法添加基本信息',16,1)	
		return--return -2
	END
	 INSERT  INTO [ptype]
            (
              [typeId],
              [Parid],
              [leveal],
              [soncount],
              [sonnum],
              [FullName],
              [pycode],
              [Name],
              [UserCode],
              [Standard],
              [Type],
              [Area],
              [baseUnitid],
			  [StockUnitId],
			  [BuyUnitId],
              [SaleUnitId],
              StopBuy,
              isyapi,
              XiWaMaxNumber
            )    
    VALUES  (
              @ptypeid,
              '00000',
              1,
              0,
              0,
              @fullname,
              @Pycode,
              '',
              @UserCode,
              @Standard,
              @Type,
              @Area,
              @unitid,
              @unitid,
              @unitid,
              @unitid,
              0,
              1,
              @xwmaxnumber
            )  
	SELECT * FROM dbo.ptype
    INSERT  ptype_price
            (
              PTypeID,
              PreSalePrice1,
              PreSalePrice2,
              PreSalePrice3,
              PreSalePrice4,
              PreSalePrice5,            
              RetailPrice
            )
    VALUES  (
              @ptypeid,
			  @price1,
			  @price2,
			  @price3,
			  @price4,
			  @price5,
			  @retailprice
			 )
            
    UPDATE  [ptype]
    SET     sonnum = Sonnum + 1,
            soncount = Soncount + 1
    WHERE   typeid = '00000'

	INSERT INTO dbo.PType_Units_Ext
	        ( PtypeID ,
	          UnitsId ,
	          RateType ,
	          Rate ,
	          EntryCode ,
	          IsDefaultUnit
	        )
	VALUES  ( @ptypeid,
	          @unitid,
	          0,
	          1 , 
	          '' , 
	          1
	        )
	INSERT INTO dbo.Yapi_PtypeRelation
	        ( Ptypeid, OnLineID, SkuId )
	VALUES  ( @ptypeid,@goodsid,@skuid )

	FETCH NEXT FROM createptype
	INTO @goodsid,@skuid,@usercode,@fullname,@pycode,@unitname,@area,@standard,@type,@price1,@price2,@price3,@price4,@price5,@retailprice
END
CLOSE createptype
DEALLOCATE createptype

MERGE INTO Yapi_SupplierPtypeRelation AS target
USING
(
	SELECT goodsid,SupplierID,p.usercode,p.fullname,ISNULL(p1.typeid,'') AS ptypeid,SkuId 
	FROM @ptype p
	LEFT JOIN ptype p1 ON p.usercode=p1.UserCode AND p.fullname=p1.FullName
)AS source
ON target.OnLineID=source.goodsid AND target.SupplierID=source.supplierid
WHEN MATCHED 
THEN UPDATE  SET OnLineFullname = source.fullname,OnLineUserCode = source.usercode,SkuId = source.skuid
WHEN NOT MATCHED BY TARGET
THEN INSERT(SupplierID,OnLineID,OnLineFullname,OnLineUserCode,Ptypeid,SkuId)VALUES(source.supplierid,source.goodsid,source.fullname,source.usercode,source.ptypeid,source.skuid);


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：谢吉康
--日期：2011-06-03
--描述：年结存处理
-- 2013-05-16 周华 修改年结内部应收
--2015-06-02  冯波 处理暂估
--2017-01-02  冯波 处理代销库存结转
-------------------------------------------------------------------------
CREATE   PROCEDURE Gp_YearProc
(
	@yearendmode			CHAR(1) = '1',		-- 1 - 按余额转期初；0 - 按单据转期初
	@delDraft				char(1) = '1',		-- 1 - 删除草稿数据；0 - 不删除
	@delOrder				char(1) = '1',		-- 1 - 删除定单数据；0 - 不删除
	@chrRecPrice			char(1) = '0',		-- 1 - 删除商品最近进价；0 - 不删除
	@delEventLog			char(1) = '0',		-- 1 - 清除操作日志；0 - 不清除
	@delEndOrder			char(1) = '0',		-- 1 - 删除已完成订单；0 - 不删除
	@delPriceTrack			char(1) = '0',		-- 1 - 清除价格跟踪信息；0 - 不清除
	@delmessage				char(1) = '0',		-- 1 - 清除聊天记录；0 - 不清除
	@unfinishedinvoice		CHAR(1) = '1',		-- 1 - 保留未完成开票单据；0 - 不保留
	@chkcompleterequestbill CHAR(1) = '1',		-- 1 - 清除已完成请购单；0 - 清除所有请购单
	@unfinishedposbill		CHAR(1) = '1',		-- 1 - 清除所有小票数据；0 - 清除已结转小票数据
	@carefinancedata		INT	,				-- 2 - 年结存后财务数据为空；1 - 结转当前财务数据；0 - 保持原来的判断
	@chrRecSalePrice        CHAR(1) = '1',		-- 1 - 年结存清空最近售价；0 - 不清空最近售价
	@chrRecSTypeBuyPrice    CHAR(1) = '1',		-- 1 - 年结存清除商品分支机构间最近进价：0 - 不清空商品分支机构间商品最近进价
	@chrRecSTypeSalePrice   CHAR(1) = '1',		-- 1 - 年结存清除商品分支机构间最近售价：0 - 不清空商品分支机构间商品最近售价
	@chrSTypePriceTrack		CHAR(1) = '1',		-- 1 - 年结存清除分支机构间价格跟踪信息: 0 - 不清空分支机构间价格跟踪信息
	@chrStockAge			CHAR(1) = '0',		-- 1 - 关心库龄数据; 0 -不关心库龄数据
	@chrStock				CHAR(1) = '0',		-- 1 - 按照仓库结转期初库龄数据; 0 不转
	@chrStype				CHAR(1) = '0',		-- 1 - 按照分支机构结转期初库龄数据; 0 不转
	@chrGroup				CHAR(1) = '0',		-- 1 - 按照集团结转期初库龄数据; 0 不转
	@delstoporder			CHAR(1) = '0',		-- 1 - 清除中止订单;0清除中止订单
	@carryOverBillexcess	CHAR(1) = '0',		-- 1 - 业务单据超收超付及收付款单未结算完金额结转至期初应收应付减少单；0 - 不转
	--@billexdepart			CHAR(1) = '0',		-- 1 - 超收超付数据结转维度部门；0 - 不按部门维度
	--@billexstaff			CHAR(1) = '0',		-- 1 - 超收超付数据结转经手人维度；0 - 不按经手人维度
	@PhysicalComplete       CHAR(1) = '0',		-- 1 -结转未实物出入库完成的单据   0 不结转
	@clearCompleteAllotApply char,--是否清除已完成的调货申请单 0-不清除 1-清除
	@clearNoCompleteAllotApply char,--是否清除未完成的调货申请单 0-不清除 1-清除
	@clearCompleteGetBillApply char,--是否清除已完成的要货申请单 0-不清除 1-清除
	@clearNoCompleteGetBillApply char,--是否清除未完成要货申请单 0-不清除 1-清除
    @clearnocompleteonshelves CHAR(1) = '0', --是否清除未完成上架的单据 0-不清除 1-清除
    @clearnocompletepickandtransport CHAR(1) = '0',  --是否清除未完成拣货/运输的单据 0-不清除 1-清除
	@OperatorId				VARCHAR(50),		-- 操作员ID
	@logid					INT=0				-- 年结存日志记录ID
)

AS
SET NOCOUNT ON

BEGIN TRAN YearProc
SAVE TRAN YearProcPoint

IF EXISTS (SELECT * FROM SysData WHERE SubName = 'inicanmodify' and SubValue = 'T')
BEGIN
	ROLLBACK TRAN YearProcPoint
	COMMIT TRAN YearProc
	return -2
END
IF EXISTS  (SELECT  * FROM dbo.SysObjects WHERE ID = object_id(N'[Cost_NoRelog]') AND OBJECTPROPERTY(ID, 'IsTable') = 1) 
BEGIN
	TRUNCATE TABLE Cost_NoRelog    -- 不知道什么表
END	
-----------------------------------------构建操作明细信息 start-------------------------------------------------------------
IF @logid>0
BEGIN
	DECLARE @logdata VARCHAR(2000)
	DECLARE @dobill VARCHAR(4)
	DECLARE @chkallrequestbill VARCHAR(4)
	DECLARE @iscare VARCHAR(4)
	SET @dobill='0'
	SET @chkallrequestbill='0'
	SET @iscare='0'
	IF @yearendmode='0'--按单据转期初
		SET @dobill='1'
	IF @chkcompleterequestbill='0'--清除所有请购单
		SET @chkallrequestbill='1'
	IF @carefinancedata>0	--关心财务数据
		SET @iscare='1'
	SET @logdata='dobill='+@dobill+';dobalance='+@yearendmode+';clearDraft='+@delDraft
	+';clearOrder='+@delOrder+';clearCompleteOrder='+@delEndOrder+';chkRecPrice='+@chrRecPrice
	+';chkPriceTrack='+@delPriceTrack+';chkEventLog='+@delEventLog+';chkclearmessage='+@delmessage
	+';unfinishedinvoice='+@unfinishedinvoice+';chkclearrecsaleprice='+@chrRecSalePrice+';chkrecstypebuyprice='+@chrRecSTypeBuyPrice
	+';chkrecstypesaleprice='+@chrRecSTypeSalePrice+';chkstypepricetrack='+@chrSTypePriceTrack+';chkcompleterequestbill='+@chkcompleterequestbill
	+';chkallrequestbill='+@chkallrequestbill+';unfinishedposbill='+@unfinishedposbill+';stockage='+@chrStockAge
	+';stock='+@chrStock+';stype='+@chrStype+';group='+@chrGroup
	+';chkdelstoporder='+@delstoporder+';chkbillexcess='+@carryOverBillexcess
	+';iscare='+@iscare+';carefinancedata='+CAST(@carefinancedata AS varchar(4))
	+';clearCompleteAllotApply=' + @clearCompleteAllotApply + ';clearNoCompleteAllotApply=' + @clearNoCompleteAllotApply
	+';clearCompleteGetBillApply=' + @clearCompleteGetBillApply + ';clearNoCompleteGetBillApply=' + @clearNoCompleteGetBillApply;
	UPDATE dbo.EventLog SET LogData=@logdata WHERE id=@logid
END
-----------------------------------------构建操作明细信息   end-------------------------------------------------------------	

-----------------------------------------处理订单库存ReachQTY START -------------------------------------------------------------
EXEC QP_Recount_ReachQty_For_YearProc

-----------------------------------------处理订单库存ReachQTY START -------------------------------------------------------------
--重算项目余额
	

	IF EXISTS(
		SELECT a.ATypeID
		FROM dbo.AType_Total a
		LEFT JOIN
		(
			SELECT AtypeId,STypeID,CID,SUM(TOTAL) Total,SUM(NTOTAL) NTotal
			FROM dbo.ListTable
			GROUP BY AtypeId,STypeID,CID
		) b
		ON a.ATypeID=b.AtypeId
		AND a.STypeID=b.STypeID
		AND a.CID=b.CID
		AND a.Total<>a.Total00+ISNULL(b.Total,0)
	)
	BEGIN
		UPDATE dbo.AType_Total
		SET 
			Total=AType_Total.Total00+ISNULL(b.Total,0),
			NTotal=AType_Total.NTotal00+ISNULL(b.NTotal,0)
		FROM
		(
			SELECT AtypeId,STypeID,CID,SUM(TOTAL) Total,SUM(NTOTAL) NTotal
			FROM dbo.ListTable
			GROUP BY AtypeId,STypeID,CID
		) b
		WHERE AType_Total.ATypeID=b.AtypeId
		AND AType_Total.STypeID=b.STypeID
		AND AType_Total.CID=b.CID
		AND AType_Total.Total<>AType_Total.Total00+ISNULL(b.Total,0)
	END
-----------------------------------------处理数据 START--------------------------------------------------------------
	----------会计科目相关----------	
	DECLARE @lr_id INT,@cid INT --本位币
	SELECT @lr_id=nid FROM dbo.Ac_Items WHERE USERcode='3141'  --未分配利润
	
	SELECT  @cid=cid FROM dbo.Ac_Currency WHERE Sysrow=1
	
	CREATE TABLE #atypeid(stypeid VARCHAR(50),lrtotal  NUMERIC(24, 10) )
	INSERT INTO #atypeid
	        ( stypeid, lrtotal )
	SELECT DISTINCT stypeid,0
	FROM dbo.AType_Total
	
	UPDATE #atypeid
	SET	lrtotal=a.total
	FROM
	(
		SELECT stypeid,ISNULL(sum(total),0)-ISNULL(SUM(Total00),0) AS total
		FROM dbo.AType_Total WHERE ATypeID IN(SELECT nId FROM dbo.Ac_Items WHERE nTypeId like '00003%' and sonnum=0)
		GROUP BY STypeID
	) a
	
	WHERE a.stypeid=#atypeid.stypeid
	UPDATE #atypeid
	SET	lrtotal-=a.total
	FROM 
	(
		SELECT stypeid,ISNULL(sum(total),0)-ISNULL(SUM(Total00),0) AS total
		FROM dbo.AType_Total 
		WHERE ATypeID IN(SELECT nId FROM dbo.Ac_Items WHERE nTypeId like '00004%' and sonnum=0)
		GROUP BY STypeID
	)a
	WHERE a.stypeid=#atypeid.stypeid
	
	MERGE INTO dbo.AType_Total AS target
	USING #atypeid AS source
	ON source.stypeid=target.STypeID AND target.ATypeID=@lr_id AND target.CID=@cid
	WHEN MATCHED THEN UPDATE SET target.Total+=SOURCE.lrtotal,target.nTotal+=SOURCE.lrtotal
	WHEN NOT MATCHED THEN INSERT(atypeid,stypeid,total,ntotal,cid)VALUES(@lr_id,SOURCE.stypeid,SOURCE.lrtotal,SOURCE.lrtotal,@cid);
	
   DROP TABLE #atypeid
	
	UPDATE	AType_Total
	SET		Total00 = Total,
			Ntotal00 = Ntotal,
			Total   = 0,
			Ntotal	= 0
	IF @@ERROR <> 0 GOTO ERROR		
		
	--收入和支出结转余额为0
	UPDATE	AType_Total SET Total00 = 0,Ntotal00=0 
	WHERE	ATypeID IN (SELECT nid FROM dbo.Ac_Items WHERE TypeName IN ('G','E'))
	
	DELETE FROM dbo.AType_Total WHERE Total00=0 OR Ntotal00=0
	--按单结算并且选择超收超付结转为期初收付款单
	IF @yearendmode=0 AND @carryOverBillexcess=1
	BEGIN
		EXEC Gp_CarryOverToIniBill
	END
	
	--将预收预付的余额写到期初预收预付单据,将应收应付余额写到期初单据中
	IF not EXISTS (SELECT TOP 1 1 FROM  dbo.sysdata WHERE SubName='usebrandartype' AND SubValue='1')
		EXEC Gp_YsyfToInibill @yearendmode
	ELSE
	BEGIN 
		--启用品牌  只能按余额结转
		EXEC	Gp_BrandarYsyfToInibill '1' 
	

		--修改往来期初汇总值	
		UPDATE	brandar_ArApTotal 
		SET		ARTotal00 = ARTotal,
				YSTotal00 = YSTotal,
				nARTotal00 = nARTotal,
				nYSTotal00 = nYSTotal,
				ARTotal=0,
				YSTotal=0,
				nARTotal=0,
				nYSTotal=0
				
				
		DELETE FROM dbo.brandar_ArApTotal	 
		WHERE (ISNULL(YSTotal00,0)=0 OR ISNULL(nYSTotal00,0)=0)
		 AND  (ISNULL(ARTotal00,0)=0 OR ISNULL(nARTotal00,0)=0)	
	
	END 
	--修改往来期初汇总值	
	UPDATE	BType_ARAPTotal 
	SET		ARTotal00 = ARTotal,
			APTotal00 = APTotal,
			YSTotal00 = YSTotal,
			YFTotal00 = YFTotal,
			nARTotal00 = nARTotal,
			nAPTotal00 = nAPTotal,
			nYSTotal00 = nYSTotal,
			nYFTotal00 = nYFTotal,
			GRIRTotal00=GRIRTotal,
			NGRIRTotal00=NGRIRTotal,
			FCTotal00=FCTotal,
			NFCTotal00=NFCTotal,
			ARTotal=0,
			APTotal=0,
			YSTotal=0,
			YFTotal=0,
			nARTotal=0,
			nAPTotal=0,
			nYSTotal=0,
			nYFTotal=0,
			GRIRTotal=0,
			NGRIRTotal=0,
			FCTotal=0,
			NFCTotal=0
			
		
	--升级数据 FcTotal NFcTotal....为NULL 		
	DELETE FROM dbo.BType_ArApTotal	 WHERE  (ISNULL(YSTotal00,0)=0 OR ISNULL(nYSTotal00,0)=0)
									   AND  (ISNULL(YFTotal00,0)=0 OR ISNULL(nYFTotal00,0)=0)
									   AND  (ISNULL(ARTotal00,0)=0 OR ISNULL(nARTotal00,0)=0)	
									   AND  (ISNULL(APTotal00,0)=0 OR ISNULL(nAPTotal00,0)=0)
	    							   AND  (ISNULL(GRIRTotal00,0)=0 OR ISNULL(NGRIRTotal00,0)=0)
									   AND  (ISNULL(FCTotal00,0)=0 OR ISNULL(NFCTotal00,0)=0)	
	-- 分支机构调拨单(汇总数据）   
	
	-- 年结处理内部应收
	UPDATE SType_InnerARTotal SET InnerARTotal00 = InnerARTotal ,InnerARTotal=0
	DELETE FROM SType_InnerARTotal WHERE InnerARTotal=0 AND InnerARTotal00=0
	
	--删除往来期初的数据
	DELETE FROM IniBType_ArApTotal							  
	
	------------库存相关--------------------
	
	DECLARE	@AVERAGE	smallint,
				@FIFO		smallint,
				@LIFO		smallint,
				@HAND		smallint

	SET @AVERAGE	= 0		-- 移动加权平均算法
	SET @FIFO		= 1		-- 先进先出
	SET @LIFO		= 2		-- 后进先出
	SET @HAND		= 3		-- 手工指定法
	
	DECLARE	@nCostingMethod	INT
	
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output

	TRUNCATE TABLE dbo.IniStockAgeStock
	TRUNCATE TABLE dbo.IniStockAgeStype
	TRUNCATE TABLE dbo.IniStockAgeGroup
	--关心库龄数据begin
	IF @chrStockAge = '1'
	BEGIN
		DECLARE @StockDate VARCHAR(10)
		SELECT @StockDate = CONVERT(VARCHAR(10),GETDATE(),23)

		CREATE TABLE #tmpstockage(
			BillNumberId	VARCHAR(50),
			ptypeid		VARCHAR(50),
			ktypeid		VARCHAR(50),
			instockdate DATETIME,
			billcode	VARCHAR(200),
			billname	VARCHAR(200),
			billtype	int ,
			stockage	NUMERIC(24,10),
			qty			NUMERIC(24,10),
			total		NUMERIC(24,10)
		)
		IF @chrStock = '1'
		BEGIN
		INSERT INTO dbo.#tmpstockage exec Web_QueryStockAgeAnalyseDetail @OperatorId=@OperatorId,@EndDate=@StockDate,@STypeId='',@ptypeCategoryID='',@PTypeId='',@KTypeId='',@ByType=1	
			DELETE #tmpstockage WHERE qty <= 0
			INSERT INTO dbo.IniStockAgeStock ( KtypeID , PtypeID , InStockDate , StockAge , Qty , Total )
			SELECT KtypeID , PtypeID , CONVERT(VARCHAR(10),InStockDate,23) , StockAge , Qty , Total FROM #tmpstockage
			TRUNCATE TABLE #tmpstockage
		END
		IF @chrStype = '1'
		BEGIN
			INSERT INTO #tmpstockage exec Web_QueryStockAgeAnalyseDetail @OperatorId=@OperatorId,@EndDate=@StockDate,@STypeId='',@ptypeCategoryID='',@PTypeId='',@KTypeId='',@ByType=2
			DELETE #tmpstockage WHERE qty <= 0
			INSERT INTO dbo.IniStockAgeStype ( KtypeID , PtypeID , InStockDate , StockAge , Qty , Total )
			SELECT KtypeID , PtypeID , CONVERT(VARCHAR(10),InStockDate,23) , StockAge , Qty , Total FROM #tmpstockage
			TRUNCATE TABLE #tmpstockage
		END
		IF @chrGroup = '1'
		BEGIN
			INSERT INTO #tmpstockage exec Web_QueryStockAgeAnalyseDetail @OperatorId=@OperatorId,@EndDate=@StockDate,@STypeId='',@ptypeCategoryID='',@PTypeId='',@KTypeId='',@ByType=3
			DELETE #tmpstockage WHERE qty <= 0
			INSERT INTO dbo.IniStockAgeGroup ( KtypeID , PtypeID , InStockDate , StockAge , Qty , Total )
			SELECT KtypeID , PtypeID , CONVERT(VARCHAR(10),InStockDate,23) , StockAge , Qty , Total FROM #tmpstockage
			TRUNCATE TABLE #tmpstockage
		END
		DROP TABLE #tmpstockage
	END
	--关心库龄数据end
	 -- 实际库
    TRUNCATE TABLE iniGoodsStocks
    INSERT INTO dbo.IniGoodsStocks
            ( PtypeId ,
              KtypeId ,
              JobNumber ,
              OutFactoryDate ,
              Qty ,
              Price ,
              Total ,
              GoodsOrder ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              GoodsBTypeID
            )
	SELECT	  PtypeId ,
              KtypeId ,
              JobNumber ,
              OutFactoryDate ,
              SUM(Qty) ,
              Price ,
              SUM(Total) ,
              GoodsOrder ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              GoodsBTypeID
    FROM GoodsStocks 
    GROUP BY  PtypeId ,
              KtypeId ,
              JobNumber ,
              OutFactoryDate ,
              Price ,
              GoodsOrder ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              GoodsBTypeID
              
    TRUNCATE TABLE dbo.Ini_GOODSSTOCKS_QTY
    INSERT INTO dbo.Ini_GOODSSTOCKS_QTY
            ( PTypeID ,
              KTypeID ,
              CargoID ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              GOODSCOSTPRICE,
              Qty ,
              NQty,
              LockNumber
            )
    SELECT	  PTypeID ,
              KTypeID ,
              CargoID ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              GOODSCOSTPRICE,
              SUM(Qty) ,
              SUM(NQty),
              SUM(LockNumber)
    FROM dbo.GOODSSTOCKS_QTY
    GROUP BY  PTypeID ,
              KTypeID ,
              CargoID ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              GOODSCOSTPRICE

	DELETE FROM iniGoodsStocks WHERE Qty = 0 AND Total = 0
	
	IF EXISTS(
		SELECT SubNo
		FROM sysdata
		WHERE SubName='isinvoice' AND SubValue=1
	)
	BEGIN
		DELETE FROM ini_GOODSSTOCKS_QTY WHERE Qty=0 AND NQty=0 AND 
		Not EXISTS(
			SELECT a.PtypeId FROM IniGoodsStocks a
			WHERE a.PtypeId=ini_GOODSSTOCKS_QTY.PTypeID
			AND a.KtypeId=ini_GOODSSTOCKS_QTY.KTypeID
		)
	END
	ELSE
	BEGIN
		DELETE FROM ini_GOODSSTOCKS_QTY WHERE Qty=0 AND NQty=0
	END
	
	
	UPDATE iniGoodsStocks SET Price = 0 WHERE Qty = 0
	TRUNCATE TABLE GoodsStocks			-- 清除库存状况表
	TRUNCATE TABLE GOODSSTOCKS_QTY
	UPDATE	iniGoodsStocks
	SET		Total = CAST(Total AS  NUMERIC(24, 10) )

	UPDATE	iniGoodsStocks
	SET		Price = dbo.F_RoundPrice(Total/Qty)
	WHERE	Qty <> 0 AND @nCostingMethod<>@HAND

--=====================================实物库存期初开始
	TRUNCATE TABLE IniFactStocks
    INSERT INTO dbo.IniFactStocks
            ( PtypeId ,
              KtypeId ,
              Qty 
            )
	SELECT	  PtypeId ,
              KtypeId ,
              SUM(Qty)	Qty 
    FROM FactStocks 
    GROUP BY  PtypeId ,
              KtypeId 
              
              
    TRUNCATE TABLE dbo.IniFactStocks_Qty
    INSERT INTO dbo.IniFactStocks_Qty
            ( PTypeID ,
              KTypeID ,
              CargoID ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              Qty ,
              NQty
            )
    SELECT	  PTypeID ,
              KTypeID ,
              CargoID ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate ,
              SUM(Qty)  QTY,
              SUM(NQty) NQty
FROM dbo.FactStocks_Qty
    GROUP BY  PTypeID ,
              KTypeID ,
              CargoID ,
              ItemID ,
              Iscombined ,
              GoodsNumber ,
              ProduceDate ,
              ValidDate 
              
    TRUNCATE TABLE FactStocks			-- 清除库存状况表
	TRUNCATE TABLE FactStocks_Qty
--=====================================实物库存期初结束
	-- 维修库
	TRUNCATE TABLE wx_IniGoodsStocks
	INSERT INTO dbo.wx_IniGoodsStocks
	        ( PTypeId ,
	          KTypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          Qty ,
	          Price ,
	          Total ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          ItemID ,
	          Iscombined ,
	          Nqty
	        )
	SELECT	  PTypeId ,
	          KTypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          SUM(Qty) ,
	          0,
	          0 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          ItemID ,
	          Iscombined ,
	          SUM(Nqty)
	FROM wx_GoodsStocks
	GROUP BY  PTypeId ,
	          KTypeId ,
	          JobNumber ,
	          OutFactoryDate ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          ItemID ,
	          Iscombined 
	
	DELETE FROM wx_IniGoodsStocks WHERE Qty = 0 AND Nqty=0
	TRUNCATE TABLE wx_GoodsStocks		-- 清除维修库存状况表

	-- 代销库
	DECLARE
		@intserialrelation	INT--序列号关联货位、自由项、批次批号
	
	SELECT
		@intserialrelation=	Value
	FROM Userconfig
	WHERE ConfigName='serialrelation'
	
	
	DECLARE @chvMngSerial varchar(10)
		SELECT	@chvMngSerial = [Value]
		FROM	UserConfig
		WHERE	ConfigName = 'mngSerial'
	
	IF EXISTS(
		SELECT Serial
		FROM gp_CruPtypeSerial
		WHERE State IN (13,32,7,9,10,11,16,14) AND @chvMngSerial=1
	)
	BEGIN
		----先处理委托,委托分为库存委托和受托委托
		CREATE TABLE #iniCommissionStock_Before(PTypeID VARCHAR(50),BTypeID VARCHAR(50),Type TINYINT,
		Qty  NUMERIC(24, 10) ,CostTotal  NUMERIC(24, 10) ,Total  NUMERIC(24, 10) ,STypeID VARCHAR(50),DealType TINYINT,SerialType TINYINT)
		
		INSERT #iniCommissionStock_Before(PTypeID,BTypeID,Type,Qty,CostTotal,Total,STypeID)
		SELECT PTypeID,BTypeID,Type,Qty,CostTotal,Total,STypeID FROM CommissionStock
		
		
		
		TRUNCATE TABLE iniCommissionStock
		TRUNCATE TABLE iniCommissionStock_Qty
		
		--统计各类序列号状态的商品有多少个
		
		CREATE TABLE #TempCommissionSerial(
			PTypeID VARCHAR(50),BTypeID	VARCHAR(50),Type TINYINT,Qty  NUMERIC(24, 10) ,STypeID VARCHAR(50),
			DealType TINYINT,SerialType TINYINT,CostPrice  NUMERIC(24, 10) ,ItemID INT,IsCombined INT,
			CargoID INT,ProduceDate VARCHAR(100),ValidDate VARCHAR(100),GoodsNumber VARCHAR(50),Price  NUMERIC(24, 10)  DEFAULT(0),
			KTypeID	VARCHAR(50) DEFAULT('')
		)
		
		
		IF EXISTS(
			SELECT Serial
			FROM gp_CruPtypeSerial
			WHERE State=13
		)
		BEGIN
			--先委托
		
			INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
				CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
			SELECT PtypeID,BTypeID1,140,COUNT(*),STypeId,2,13,
			CostPrice,ItemID,IsCombined,0,ProduceDate,ValidDate,GoodsNumber
			FROM gp_CruPtypeSerial
			WHERE State=13
			GROUP BY PtypeID,BTypeID1,STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber	
			
			UPDATE #TempCommissionSerial
			SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
			FROM CommissionStock b
			WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
			AND b.Type=140 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
			
			
			INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
			SELECT a.Ptypeid,a.Btypeid,a.Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,a.Stypeid,a.DealType,a.SerialType
			FROM #TempCommissionSerial a
			WHERE a.SerialType=13 AND a.Type=140
			GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
			
			INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
			SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,0,DealType,'10000',0,a.SerialType,CostPrice
			FROM #TempCommissionSerial a
			WHERE a.SerialType=13 AND a.Type=140
			
			TRUNCATE TABLE #TempCommissionSerial
			
		END
		
		IF EXISTS(
			SELECT Serial
			FROM gp_CruPtypeSerial
			WHERE State=14
		)
		BEGIN
			
		
			INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
				CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
			SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),144,COUNT(*),STypeId,2,14,
			CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
			FROM gp_CruPtypeSerial
			WHERE State=14
			GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber	
			
			UPDATE #TempCommissionSerial
			SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
			FROM CommissionStock b
			WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
			AND b.Type=144 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
			
			
			INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
			SELECT a.Ptypeid,a.Btypeid,a.Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,a.Stypeid,a.DealType,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END
			FROM #TempCommissionSerial a
			WHERE a.SerialType=14 AND a.Type=144
			GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
			
			INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
			SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,0,DealType,'10000',0,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END,CostPrice
			FROM #TempCommissionSerial a
			WHERE a.SerialType=14 AND a.Type=144
			
			
			
			
			TRUNCATE TABLE #TempCommissionSerial
			
		END
		
		IF EXISTS(
			SELECT Serial
			FROM gp_CruPtypeSerial
			WHERE State=32
		)
		BEGIN
			INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
				CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
			SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,140),140,COUNT(*),STypeId,1,32,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
			FROM gp_CruPtypeSerial
			WHERE State=32
			GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,140),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
			
			
			
			UPDATE #TempCommissionSerial
			SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
			FROM CommissionStock b
			WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
			AND b.Type=140 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
			
			INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
			SELECT a.Ptypeid,a.Btypeid, a.Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,a.Stypeid,a.DealType,a.SerialType
			FROM #TempCommissionSerial a
			WHERE a.SerialType=32 AND a.Type=140
			GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
			
			INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
			SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,0,DealType,'10000',0,a.SerialType,CostPrice
			FROM #TempCommissionSerial a
			WHERE a.SerialType=32 AND a.Type=140
			
			TRUNCATE TABLE #TempCommissionSerial
		
			INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
				CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
			SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),144,COUNT(*),STypeId,1,32,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
			FROM gp_CruPtypeSerial
			
			WHERE State=32
			GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
			
			UPDATE #TempCommissionSerial
			SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
			FROM CommissionStock b
			WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
			AND b.Type=144 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
			
			
			
			INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
			SELECT a.Ptypeid,a.Btypeid,a.Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,a.Stypeid,a.DealType,a.SerialType
			FROM #TempCommissionSerial a
			WHERE a.SerialType=32 AND a.Type=144
			GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
			
			INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
			SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,0,DealType,'10000',0,a.SerialType,CostPrice
			FROM #TempCommissionSerial a
			WHERE a.SerialType=32 AND a.Type=144
			
			TRUNCATE TABLE #TempCommissionSerial
		END
		
		
		
		IF EXISTS(
			SELECT Serial
			FROM gp_CruPtypeSerial
			WHERE State=7
		)
		BEGIN
			--再受托
			
			
			INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
				CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber,KTypeID)
			SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),144,COUNT(*),STypeId,0,7,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber,KtypeID
			FROM gp_CruPtypeSerial
			WHERE State=7
			GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber,KtypeID
			
			
			
			
			
			UPDATE #TempCommissionSerial
			SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
			FROM CommissionStock b
			WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
			AND b.Type=144 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
			
			
			
			
			INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
			SELECT a.Ptypeid,a.Btypeid,Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),dbo.F_RoundTotal(SUM(Qty)*Price),0,0,Stypeid,DealType,a.SerialType
			FROM #TempCommissionSerial a
			WHERE a.SerialType=7 AND a.Type=144
			GROUP BY a.PTypeID,a.BTypeID,a.STypeID,a.DealType,a.SerialType,a.Type,a.Price
			
			INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
			SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,0,DealType,KTypeID,CargoID,a.SerialType,CostPrice
			FROM #TempCommissionSerial a
			WHERE a.SerialType=7 AND a.Type=144
			
			
			
			TRUNCATE TABLE #TempCommissionSerial
			
		
		
		END
		
		IF EXISTS(
			SELECT Serial
			FROM gp_CruPtypeSerial
			WHERE State IN (9,10,11,16)
		)
		BEGIN
			INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
				CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
			SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),144,COUNT(*),STypeId,2,State,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
			FROM gp_CruPtypeSerial
			WHERE State IN (9,10,11,16)
			GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,GoodsNumber
			
			UPDATE #TempCommissionSerial
			SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
			FROM CommissionStock b
			WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
			AND b.Type=144 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
			
			INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
			SELECT a.Ptypeid,a.Btypeid,Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,Stypeid,DealType,a.SerialType
			FROM #TempCommissionSerial a
			WHERE a.SerialType IN (9,10,11,16) AND a.Type=144
			GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
			
			INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
			SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
			Qty,0,DealType,'10000',0,a.SerialType,CostPrice
			FROM #TempCommissionSerial a
			WHERE a.SerialType IN (9,10,11,16) AND a.Type=144
			
			TRUNCATE TABLE #TempCommissionSerial	
		
		END
		
		--如果存在COSTTOTAL=0,则处理一下
		IF EXISTS(
			SELECT Ptypeid
			FROM IniCommissionStock
			WHERE Qty<>0 AND CostTotal=0
		)
		BEGIN
			UPDATE IniCommissionStock
			SET CostTotal=dbo.F_RoundTotal(IniCommissionStock.Qty *b.CostPrice)
			FROM
			(
				SELECT PTypeID,BTypeID,STypeID,TYPE,CASE SUM(Qty) WHEN 0 THEN 0 ELSE dbo.F_RoundTotal(CAST(SUM(CostTotal) AS  NUMERIC(24, 10) )/CAST((SUM(Qty)*1.0) AS  NUMERIC(24, 10) )) END AS CostPrice
				FROM #iniCommissionStock_Before
				GROUP BY PTypeID,BTypeID,STypeID,TYPE
				
			) b
			WHERE IniCommissionStock.Ptypeid=b.PTypeID
			AND IniCommissionStock.Btypeid=b.BTypeID
			AND IniCommissionStock.Stypeid=b.STypeID
			AND IniCommissionStock.Type=b.Type
			AND IniCommissionStock.CostTotal=0
			AND IniCommissionStock.Qty<>0
		END
		
		
		
		--尾差分摊
		IF EXISTS(
			SELECT a.PTypeID,a.BTypeID,a.Type,a.Total,b.Total
			FROM
			(
				SELECT PTypeID,BTypeID,Type,SUM(Total) AS Total
				FROM #iniCommissionStock_Before
				GROUP BY PTypeID,BTypeID,Type
			) a
			INNER JOIN
			(
				SELECT PTypeID,BTypeID,Type,SUM(Total) AS Total
				FROM iniCommissionStock
				GROUP BY PTypeID,BTypeID,Type
			) b
			ON a.PTypeID=b.PTypeID AND a.BTypeID=b.BTypeID AND a.Type=b.Type
			WHERE a.Total<>b.Total
		)
		BEGIN
			CREATE TABLE #tmp_Diff(PTypeID VARCHAR(50),BTypeID VARCHAR(50),Type TINYINT,Diff  NUMERIC(24, 10) ,MaxQty  NUMERIC(24, 10) ,MAXCount  NUMERIC(24, 10) ,SerialType TINYINT)
		
			INSERT #tmp_Diff(PTypeID,BTypeID,Type,Diff)
			SELECT a.PTypeID,a.BTypeID,a.Type,a.Total-b.Total
			FROM
			(
				SELECT PTypeID,BTypeID,Type,SUM(Total) AS Total
				FROM #iniCommissionStock_Before
				GROUP BY PTypeID,BTypeID,Type
			) a
			INNER JOIN
			(
				SELECT PTypeID,BTypeID,Type,SUM(Total) AS Total
				FROM iniCommissionStock
				GROUP BY PTypeID,BTypeID,Type
			) b
			ON a.PTypeID=b.PTypeID AND a.BTypeID=b.BTypeID AND a.Type=b.Type
			WHERE a.Total<>b.Total
			
		
			
			UPDATE #tmp_Diff
			SET MaxQty=b.Qty
			FROM
			(
				SELECT PTypeID,BTypeID,Type,MAX(Qty) AS Qty
				FROM iniCommissionStock
				GROUP BY PTypeID,BTypeID,Type
			) b
			WHERE #tmp_Diff.PTypeID=b.PTypeID AND #tmp_Diff.BTypeID=b.BTypeID AND #tmp_Diff.Type=b.Type
			
			
			
			
			UPDATE #tmp_Diff
			SET MAXCount=b.MaxCount
			FROM
			(
				SELECT a.PTypeID,a.BTypeID,a.Type,COUNT(*) AS MaxCount
				FROM iniCommissionStock a
				INNER JOIN #tmp_Diff b
				ON a.PTypeID=b.PTypeID AND a.BTypeID=b.BTypeID AND a.Type=b.Type AND a.Qty=b.MaxQty
				GROUP BY a.PTypeID,a.BTypeID,a.Type
			) b
			WHERE #tmp_Diff.PTypeID=b.PTypeID AND #tmp_Diff.BTypeID=b.BTypeID AND #tmp_Diff.Type=b.Type
			
			UPDATE #tmp_Diff
			SET SerialType=b.SerialType
			FROM 
			(
				SELECT a.PTypeID,a.BTypeID,a.Type,MAX(a.SerialType) AS SerialType
				FROM iniCommissionStock a
				INNER JOIN #tmp_Diff b
				ON a.PTypeID=b.PTypeID AND a.BTypeID=b.BTypeID AND a.Type=b.Type AND a.Qty=b.MaxQty
				WHERE b.MaxCount>1
				GROUP BY a.PTypeID,a.BTypeID,a.Type
			) b
			WHERE #tmp_Diff.PTypeID=b.PTypeID AND #tmp_Diff.BTypeID=b.BTypeID AND #tmp_Diff.Type=b.Type
			
			
			
			
			UPDATE iniCommissionStock
			SET Total=iniCommissionStock.Total+b.Diff
			FROM #tmp_Diff b
			WHERE iniCommissionStock.PTypeID=b.PTypeID
			AND iniCommissionStock.BTypeID=b.BTypeID
			AND iniCommissionStock.Type=b.Type
			AND b.MaxCount=1 AND iniCommissionStock.Qty=b.MaxQty
			
			UPDATE iniCommissionStock
			SET Total=iniCommissionStock.Total+b.Diff
			FROM #tmp_Diff b
			WHERE iniCommissionStock.PTypeID=b.PTypeID
			AND iniCommissionStock.BTypeID=b.BTypeID
			AND iniCommissionStock.Type=b.Type
			AND b.MaxCount<>1 AND iniCommissionStock.SerialType=b.SerialType
				
		END
		
		
		DROP TABLE #iniCommissionStock_Before
		
		--对于未启用序列号的代销数据，不能根据序列号结转，要直接转过去
		IF EXISTS(
			SELECT TypeID
			FROM dbo.ptype
			WHERE sonnum=0 AND IfSerial=0
		)
		BEGIN
			INSERT INTO iniCommissionStock (
				PTypeID,
				BTypeID,
				Type,
				Qty,
				CostTotal,
				Total,
				Explain,
				KTypeID,
				ETypeID,
				STypeID,
				DealType,
				SerialType
			)
			SELECT	a.PTypeID,
					a.BTypeID,
					a.Type,
					SUM(A.Qty) AS Qty,
					SUM(A.CostTotal) AS CostTotal,
					SUM(A.Total) AS Total,
					A = '',
					B = '',
					C = '',
					A.STypeID,
					0,
					0
			FROM	CommissionStock a
			INNER JOIN PType b
			ON a.Ptypeid=b.typeId
			WHERE b.IfSerial=0
			GROUP BY a.PTypeID, 
					 a.BTypeID, 
					 a.Type,
					 A.STypeID
			
			
					 
			INSERT INTO dbo.IniCommissionStock_Qty
					( Ptypeid ,
					  Btypeid ,
					  Stypeid ,
					  Type ,
					  ItemID ,
					  Iscombined ,
					  GoodsNumber ,
					  ProduceDate ,
					  ValidDate ,
					  Qty ,
					  NQty,
					  DealType,
					  KTypeID,
					  CargoID,
					  SerialType,
					  GoodsCostPrice
					)
			SELECT	  a.Ptypeid ,
					  a.Btypeid ,
					  a.Stypeid ,
					  a.Type ,
					  a.ItemID ,
					  a.Iscombined ,
					  a.GoodsNumber ,
					  a.ProduceDate ,
					  a.ValidDate ,
					  SUM(a.Qty) ,
					  SUM(a.NQty),
					  0,
					  '10000',
					  0,
					  0,
					  0
			FROM dbo.CommissionStock_Qty a
			INNER JOIN PType b
			ON a.Ptypeid=b.typeId
			WHERE b.IfSerial=0
			GROUP BY  a.Ptypeid ,
					  a.Btypeid ,
					  a.Stypeid ,
					  a.Type ,
					  a.ItemID ,
					  a.Iscombined ,
					  a.GoodsNumber ,
					  a.ProduceDate ,
					  a.ValidDate
					  
			

		END
		
		TRUNCATE TABLE CommissionStock
		TRUNCATE TABLE dbo.CommissionStock_Qty
		
	END
	ELSE
	BEGIN
		
	
		TRUNCATE TABLE iniCommissionStock		
		INSERT INTO iniCommissionStock (
			PTypeID,
			BTypeID,
			Type,
			Qty,
			CostTotal,
			Total,
			Explain,
			KTypeID,
			ETypeID,
			STypeID,
			DealType,
			SerialType
		)
		SELECT	a.PTypeID,
				a.BTypeID,
				a.Type,
				SUM(A.Qty) AS Qty,
				SUM(A.CostTotal) AS CostTotal,
				SUM(A.Total) AS Total,
				A = '',
				B = '',
				C = '',
				A.STypeID,
				0,
				0
		FROM	CommissionStock a
		GROUP BY a.PTypeID, 
				 a.BTypeID, 
				 a.Type,
				 A.STypeID
		
		
		
		TRUNCATE TABLE dbo.IniCommissionStock_qty
		INSERT INTO dbo.IniCommissionStock_Qty
				( Ptypeid ,
				  Btypeid ,
				  Stypeid ,
				  Type ,
				  ItemID ,
				  Iscombined ,
				  GoodsNumber ,
				  ProduceDate ,
				  ValidDate ,
				  Qty ,
				  NQty,
				  DealType,
				  KTypeID,
				  CargoID,
				  SerialType,
				  GoodsCostPrice
				)
		SELECT	  Ptypeid ,
				  Btypeid ,
				  Stypeid ,
				  Type ,
				  ItemID ,
				  Iscombined ,
				  GoodsNumber ,
				  ProduceDate ,
				  ValidDate ,
				  SUM(Qty) ,
				  SUM(NQty),
				  0,
				  '10000',
				  0,
				  0,
				  0
		FROM dbo.CommissionStock_Qty
		GROUP BY  Ptypeid ,
				  Btypeid ,
				  Stypeid ,
				  Type ,
				  ItemID ,
				  Iscombined ,
				  GoodsNumber ,
				  ProduceDate ,
				  ValidDate
		       
		          
		TRUNCATE TABLE CommissionStock
		TRUNCATE TABLE dbo.CommissionStock_Qty
	    
		DELETE FROM iniCommissionStock
		WHERE	(Qty = 0 AND Total = 0 AND CostTotal = 0 AND Type = 140)
				OR (Qty = 0 AND Total = 0 AND Type = 144)

		UPDATE	iniCommissionStock
		SET		Total = CAST(Total AS  NUMERIC(24, 10) ),
				CostTotal = CAST(CostTotal AS  NUMERIC(24, 10) )
				
		DELETE FROM iniCommissionStock_Qty WHERE qty=0 AND nqty=0
		
		--SELECT '0000',* FROM dbo.IniCommissionStock
		
		--SELECT '0001',* FROM dbo.IniCommissionStock_qty
		
		--SELECT '0002',* FROM dbo.gp_initPtypeSerial
		
		
		
	END
	-- 借欠
	TRUNCATE TABLE IniGoodsLend
	INSERT INTO dbo.IniGoodsLend 
		(BtypeId , PtypeId , KtypeId , JobNumber , OutFactoryDate , Qty , Price , Total , GoodsOrder , GoodsNumber , ItemID ,
		Iscombined , Nqty , ProduceDate , ValidDate, BorrowQty, LendQty, NBorrowQty, NLendQty )
	SELECT						  
		 BtypeId , PtypeId , KtypeId , JobNumber , OutFactoryDate , Qty , Price , Total , GoodsOrder , GoodsNumber , ItemID , 
		Iscombined , Nqty , ProduceDate , ValidDate, BorrowQty, LendQty, NBorrowQty, NLendQty 
	FROM GoodsLend
	
	--983BUG4968
	--DELETE FROM IniGoodsLend WHERE Qty = 0 AND Nqty = 0
	TRUNCATE TABLE GoodsLend
	TRUNCATE TABLE dbo.LendCheck
	-- 借欠
	DELETE FROM LoginUser
	WHERE ETypeID IN 
	(
		SELECT	TypeID
		FROM	Employee
		WHERE	Deleted = 1
				AND SonNum = 0
	)
	
	
		
	-----------------序列号 -------------------
	EXEC Gp_YearProcSerialDeal 
	
	

	---------------会员卡余额相关--------------
	-- 清空累计金额、积分，转移至初始金额、积分
	-- 清空累计储值金额、消费储值金额、储值余额，将储值余额转至期初储值金额
	--A8
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubValue=2 AND SubName='ProInfo')
	BEGIN
		UPDATE nVipCardSign 
		SET 
			BeginMoney = BeginMoney+TotalMoney,
			BeginCent = BeginCent+TotalCent,
			TotalMoney = 0,
			TotalCent = 0,
			qCczMoney = 0,
			cZyeMoney=0,
			lJczMoney = 0,
			xFczMoney = 0
	END
	ELSE
	BEGIN
		UPDATE nVipCardSign 
		SET 
			BeginMoney = BeginMoney+TotalMoney,
			BeginCent = BeginCent+TotalCent,
			qCczMoney = cZyeMoney,
			TotalMoney = 0,
			TotalCent = 0,
			lJczMoney = 0,
			xFczMoney = 0
	END
	
	--结转分支机构会员卡储值余额到期初
	UPDATE dbo.nVipCardSignStype 
	SET qCczMoney=cZyeMoney,
		bNczMoney=0,
		bNxFczMoney=0,
		bNxFMoney=0
	
	-------------LoginUser 表---------------
	DELETE FROM LoginUser
	WHERE ETypeID IN (SELECT TypeID FROM Employee WHERE Deleted = 1 AND SonNum = 0)
	TRUNCATE TABLE dbo.FrozeBusiness
	DELETE FROM dbo.PriceTrack WHERE BuyOrderPrice=NULL AND SaleOrderPrice=NULL AND CostPrice=NULL AND QueryPrice=NULL AND SalePrice=NULL AND ResponsePrice = NULL AND Discount=NULL 
-----------------------------------------处理数据  END --------------------------------------------------------------



-----------------------------------------删除单据 START -------------------------------------------------------------

	---删单据主表和明细
	
	
	EXEC Gp_YearProcDeleteBill @yearendmode,@DelDraft,@unfinishedinvoice,@chkcompleterequestbill,@unfinishedposbill,@PhysicalComplete,@carryOverBillexcess,@delOrder,@clearCompleteAllotApply,@clearNoCompleteAllotApply,@clearCompleteGetBillApply,@clearNoCompleteGetBillApply,@clearnocompleteonshelves,@clearnocompletepickandtransport,@delstoporder,@delEndOrder	


	--------删除主表后续处理  start ------------------------------	
	DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype not  IN (423,424,425,426,301,300,313) 			--多账户
	DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM dbo.Coupon_BillIndex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype IN (423,424,425,426)		--多账户
	DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM dbo.orderindex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype IN (301,300,313)		--多账户
	
	
	DELETE FROM BillMulBrand WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=BillMulBrand.BillNumberId)			--多账户

	IF @delOrder = '1'   
	BEGIN
		TRUNCATE TABLE OrderBill			-- 销售、采购订单
		TRUNCATE TABLE OrderIndex			-- 清除订单索引表
		DELETE dbo.OrderIndex WHERE BillType=313		--清除所有组合品订单
		TRUNCATE TABLE PT_Combin_OrderBill				--清除所有组合品订单信息
		TRUNCATE TABLE PT_Combin_OrderBillDetail			--清除所有组合品订单明细信息
		TRUNCATE TABLE PT_SaleOrderLockDetail		 		--清除订单锁库信息
		UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
		UPDATE dbo.Ini_GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
		TRUNCATE TABLE Ini_GoodsStocks_Order    --清除期初订单库存
	END

    	IF @clearCompleteAllotApply = 1 --清除已完成的调货申请单
	BEGIN
     DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=22)
     DELETE PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=22;
	END

	IF @clearNoCompleteAllotApply = 1 --清除未完成的调货申请单
	BEGIN
     DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=22)
     DELETE PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=22;
	END

	IF @clearcompletegetbillapply = 1 --清除已完成的要货申请单
	BEGIN
	     DELETE DeliveryApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=326)
	     DELETE PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=326;
	END
	IF @clearnocompletegetbillapply = 1 --清除未完成的要货申请单
	BEGIN
	     DELETE DeliveryApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=326)
	     DELETE PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=326;
	END
	
	--bug2853,调货申请单，状态是作废的，年结存的时候直接清除掉，不管选项。祝伟已确认
	DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE BillState = 4);
	DELETE PosAllotApplyBillIndex WHERE BillState = 4;

IF @clearnocompleteonshelves = 1
BEGIN

UPDATE dbo.RetailBackBill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 215)
UPDATE dbo.salebackbill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 45)
UPDATE dbo.salegoodsexchangebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1)AND BillType = 160)
UPDATE dbo.commissionbill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType IN(142,144))
UPDATE dbo.PT_Combin_SaleBackBillDetail SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 46)
UPDATE dbo.buybill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 34)
UPDATE dbo.buygoodsexchangebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 161)
UPDATE dbo.givemebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 126)
UPDATE dbo.movebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 17)
UPDATE dbo.movebjbill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 21)
UPDATE dbo.stypemovebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 188)
UPDATE dbo.otherinoutbill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 201)
UPDATE dbo.disassemblebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 16)
UPDATE dbo.AppraisalBill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 400)
UPDATE dbo.SendBackBill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 403) 
         
UPDATE dbo.BillIndex SET ShelveRefState = 0, ShelveState = 0 
          WHERE (ShelveState = 1 OR ShelveRefState = 1)
                
END
                    
 IF @clearnocompletepickandtransport = 1
BEGIN                   
UPDATE dbo.salebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 11) 
UPDATE dbo.salegoodsexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 160) 
UPDATE dbo.givebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 139)                                 
UPDATE dbo.commissionbill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType IN(140,146)) 
UPDATE dbo.PT_Combin_SaleBillDetail SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 12) 
UPDATE dbo.buybackbill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 6) 
UPDATE dbo.buygoodsexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 161) 
UPDATE dbo.movebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 17) 
UPDATE dbo.movebjbill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 21) 
UPDATE dbo.stypemovebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 187) 
UPDATE dbo.otherinoutbill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 202) 
UPDATE dbo.disassemblebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 16) 
UPDATE dbo.integralexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 183) 
UPDATE dbo.AppraisalBackBill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 401) 
UPDATE dbo.SendBill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 402)
                
UPDATE dbo.BillIndex SET citestate = 0, progressstate = 0 
          WHERE (citestate = 1 OR progressstate = 1)                
END

	IF @delOrder <> '1' AND @delEndOrder = '1'	-- 清除已完成订单
	BEGIN
		--更新期初订单库存
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=0 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=0 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
		
		--删除已完成的销售订单 去除关联关系
		UPDATE OrderBill SET SaleOrderId =-1
		WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState = '1' AND BillOver = 0 and billtype =300)  )
		
		DELETE FROM OrderIndex WHERE OrderState = '1' AND BillOver = 0
		DELETE FROM OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=OrderBill.billNumberID)
		DELETE FROM dbo.PT_Combin_OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBill.billNumberID)
		DELETE FROM dbo.PT_Combin_OrderBillDetail WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBillDetail.billNumberID)
	END
	--清除中止订单
	IF @delOrder<> '1' AND @delstoporder= '1'
	BEGIN
		--更新期初订单库存
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
		DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
		
		--删除已中止的销售订单 去除关联关系
		UPDATE OrderBill SET SaleOrderId =-1
		WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState='1' AND BillOver=1 and billtype =300)  )
		
		DELETE FROM dbo.OrderIndex WHERE OrderState='1' AND BillOver=1
		DELETE FROM OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=OrderBill.billNumberID)
		DELETE FROM dbo.PT_Combin_OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBill.billNumberID)
		DELETE FROM dbo.PT_Combin_OrderBillDetail WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBillDetail.billNumberID)
	END
	
	-- 删除OrderBill 中关联报价单、询价单、请购单billnumberid无效的记录
	UPDATE dbo.OrderBill SET AskBillID=0,AskBillNumberID=0 WHERE AskBillID <> 0
	UPDATE dbo.OrderBill SET RequestBillID=0,RequestBillNumberID=0 WHERE RequestBillID<>0 AND NOT EXISTS(SELECT 1 FROM Requestbill WHERE ID =OrderBill.RequestBillID)
	-- 删除销售、采购明细表中，无效关联 OrderBill 中的 OrderID 记录
	UPDATE SaleBill SET OrderID = -1 WHERE OrderID <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=SaleBill.OrderID)
	UPDATE BuyBill SET OrderID = -1 WHERE OrderID <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=BuyBill.OrderID)
	
	--打断销售 采购有订金产生的 预收\付款  收付款单关联关系
	UPDATE prebill set RelevanceBillId=-1 
	WHERE RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=prebill.RelevanceBillId)
	UPDATE gatheringbill set RelevanceBillId=-1 
	WHERE  RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=gatheringbill.RelevanceBillId)
	UPDATE paybill set RelevanceBillId=-1 
	WHERE  RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=paybill.RelevanceBillId)
	
	
	
	
	-- 如果有保留的单据，则给其赋一个年结前单据的标志
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE Draft = 0)
	BEGIN
		UPDATE BillIndex SET ifYearBill = 1 WHERE Draft = 0
		DELETE FROM visit WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE Draft = 0 AND BillNumberId=visit.JbBillNumberID)
		DELETE FROM visitfj WHERE NOT EXISTS (SELECT 1 FROM visit WHERE billnumberid=visitfj.billnumberid)
	END
	IF EXISTS(SELECT TOP 1 1 FROM dbo.LendIndex WHERE Draft = 0)
	BEGIN
		UPDATE LendIndex SET ifYearBill = 1 WHERE Draft = 0
	END

	--敏捷4210 发现是年结存时，超收超付的单据，在保留未开票完成单据，超收超付生成收付款单时，该单据的状态isini的值，应该写成0，现在是写的1，就导致该单据在计算期初时，超收超付的金额被再次计算了一次。
	UPDATE BillIndex SET IsIni=0
	WHERE 
		(
			(	
				BillType IN(6,34,145,161,84,150,151,170,128,129) 
				OR
				(BillType = 36 AND btypeid like '00002%')
			)
			AND 
			(
				(Ntotalinmoney + NCompleteTotal  + Npreferencemoney > 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney > Ntotalmoney) 
				OR 
				(Ntotalmoney < 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney < Ntotalmoney)
			)
		)
		 OR
		(
				(
					BillType IN(11,45,141,148,85,93,148,149,181,167,168,172,115,116) 
					OR
					(BillType = 36 AND btypeid like '00001%')
				)
				AND 
				(
					(Ntotalinmoney + NCompleteTotal  + Npreferencemoney > 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney > Ntotalmoney) 
					OR 
					(Ntotalmoney < 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney < Ntotalmoney)
				)
		)
		
	--单据结转时，重新算往来期初余额
	IF @yearendmode=0
		EXEC dbo.Gp_IniToArApTotal @stypeid = '%' -- varchar(50)
		

	--清除业绩分配明细
	SELECT * INTO #PerformanceDistribution FROM PerformanceDistribution  WHERE billnumberid IN(SELECT billnumberid FROM billindex )
	TRUNCATE TABLE PerformanceDistribution
	INSERT INTO PerformanceDistribution (BillNumberId,PTypeID,ETypeID,Proportion,Total,CreateDate,Checke,Comment)  SELECT BillNumberId,PTypeID,ETypeID,Proportion,Total,CreateDate,Checke,Comment FROM #PerformanceDistribution ORDER BY ID ASC
	DROP TABLE #PerformanceDistribution	
		
	--清除单据操作日志
	SELECT BO.* INTO #BillOperateLog  FROM BillOperateLog BO INNER JOIN BillIndex bi on BO.BillnumberID=BI.BillNumberId
	TRUNCATE TABLE BillOperateLog
	INSERT INTO dbo.BillOperateLog
			        ( BillnumberID ,
			          OperateType ,
			          EtypeID ,
			          OperateTime ,
			          IP ,
			          BillCode ,
			          BillDate ,
			          ifcheck ,
			          btypeid ,
			          NTotalMoney ,
			          billtype
			        )
			SELECT  BillnumberID ,
			          OperateType ,
			          EtypeID ,
			          OperateTime ,
			          IP ,
			          BillCode ,
			          BillDate ,
			          ifcheck ,
			          btypeid ,
			          NTotalMoney ,
			          billtype
			 FROM #BillOperateLog
	DROP TABLE #BillOperateLog
	
	--处理发票
	CREATE  TABLE #FaPiao( billnumberid int,MainBillNumberID int)
	INSERT INTO #FaPiao(billnumberid,MainBillNumberID) SELECT billnumberid,MainBillNumberID FROM FaPiaoBill WHERE MainBillNumberID  IN(SELECT BillNumberID FROM BillIndex WHERE IfInvoice<>2)
	IF EXISTS(SELECT TOP 1 1 FROM #FaPiao)
	BEGIN
		DELETE FaPiaoBill  WHERE NOT EXISTS(SELECT 1 FROM #FaPiao WHERE MainBillNumberID=FaPiaoBill.MainBillNumberID)
		DELETE FaPiaoBillIndex WHERE NOT EXISTS(SELECT 1 FROM #FaPiao WHERE billnumberid=FaPiaoBillIndex.BillNumberID)
		UPDATE FaPiaoBillIndex SET [ifYearBill] = 1
	END
	ELSE
	BEGIN
		TRUNCATE TABLE FaPiaoBillindex		-- 清掉新发票单据索引表
		TRUNCATE TABLE FaPiaoBill			-- 清掉新发票单据明细表
	END
	DROP TABLE #FaPiao
	
	---清除打印相关及附件相关
	SELECT billnumberid,billtype INTO #PrintTmp 
	FROM (
			SELECT BillNumberId,BillType FROM  BillIndex
			UNION ALL
			SELECT BillNumberId,BillType FROM  OrderIndex
			UNION ALL
			SELECT BillNumberId,BillType FROM  requestindex
			UNION ALL
			SELECT BillNumberId,BillType FROM FaPiaoBillIndex
			UNION ALL
			SELECT BillNumberId,BillType FROM  serialadjustindex
			UNION ALL
			SELECT BillNumberId,164 FROM  TCBillindex
			UNION ALL
			SELECT BillNumberId,BillType FROM  V_LendFace
			UNION ALL
			SELECT ProduceModelID,127 FROM  producemodelindex
			UNION ALL
			SELECT stockCheckID,306 FROM  StockCheckIndex
			UNION ALL 
			SELECT BillNumberId,BillType FROM CM_CarUseIndex
			UNION ALL 
			SELECT BillNumberId,BillType FROM CM_FeeIndex 
	) A
		
	SELECT a.* INTO #printrecord 
	FROM printrecord a 
	INNER JOIN  #PrintTmp b ON a.BillNumberId=b.BillNumberId and a.BillType=b.BillType
	TRUNCATE TABLE printrecord
	INSERT INTO printrecord SELECT * FROM #printrecord	
	
	SELECT a.* into #AddPrintCountRecord
	FROM AddPrintCountRecord a 
	INNER JOIN  #PrintTmp b ON a.BillNumberId=b.BillNumberId and a.BillType=b.BillType
	TRUNCATE TABLE AddPrintCountRecord
	INSERT INTO AddPrintCountRecord SELECT * FROM #AddPrintCountRecord
	
	DECLARE @columns VARCHAR(max)=''
	SELECT * INTO #BillAttachFiles FROM BillAttachFiles WHERE EXISTS (SELECT 1 FROM #PrintTmp WHERE BillNumberId=BillAttachFiles.BillNumberId AND BillType=BillAttachFiles.BillType)
	TRUNCATE TABLE dbo.BillAttachFiles
	SET IDENTITY_INSERT dbo.BillAttachFiles ON
	SET @columns=dbo.f_getallcolumns('BillAttachFiles')
	EXEC('INSERT INTO BillAttachFiles ('+@columns+') SELECT '+@columns+ ' FROM #BillAttachFiles')
	SET IDENTITY_INSERT BillAttachFiles OFF
	
	SELECT * INTO #BillAttachFileslog FROM BillAttachFileslog WHERE EXISTS (SELECT 1 FROM #PrintTmp WHERE BillNumberId=BillAttachFileslog.BillNumberId AND BillType=BillAttachFileslog.BillType)
	TRUNCATE TABLE dbo.BillAttachFileslog
	SET IDENTITY_INSERT dbo.BillAttachFileslog ON
	SET @columns=dbo.f_getallcolumns('BillAttachFileslog')
	EXEC('INSERT INTO BillAttachFileslog ('+@columns+') SELECT '+@columns+ ' FROM #BillAttachFileslog')
	SET IDENTITY_INSERT BillAttachFileslog OFF
	DROP TABLE #PrintTmp,#AddPrintCountRecord,#printrecord,#BillAttachFiles,#BillAttachFileslog
	
	
	--清除单据种子
	EXEC GP_BillCode_Seed_ReBuild
	
	EXEC GP_OldBill_Clone_Del
	---------------删除主表后续处理  end ------------------------

	--处理审核
	IF @delDraft = '1' AND @delOrder = '1'	-- 同时删除草稿和订单
	BEGIN
		TRUNCATE TABLE AuditingBillDetail
		TRUNCATE TABLE AuditingBill
	END
	ELSE
	BEGIN
		IF @delDraft = '1' AND @delOrder <> '1'	-- 删草稿，不删订单
		BEGIN
			DELETE FROM AuditingBillDetail WHERE BillIndexType BETWEEN 1 AND 8
			DELETE FROM AuditingBill WHERE BillIndexType BETWEEN 1 AND 8
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '0' AND NOT EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID)
			DELETE FROM AuditingBill WHERE BillIndexType = '0' AND NOT EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE BillNumberId=AuditingBill.BillNumberID)
		END
		ELSE IF @delOrder = '1' AND @delDraft <> '1'	-- 删订单，不删草稿
		BEGIN
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '0'
			DELETE FROM AuditingBill WHERE BillIndexType = '0'
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '2' AND NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '2' AND NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '1'  AND NOT EXISTS(SELECT 1 FROM LendIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '1'  AND NOT EXISTS(SELECT 1 FROM LendIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '4' AND NOT EXISTS(SELECT 1 FROM CommissionBillNew WHERE BillNumberId=AuditingBillDetail.BillNumberID)
			DELETE FROM AuditingBill WHERE BillIndexType = '4' AND NOT EXISTS(SELECT 1 FROM CommissionBillNew WHERE BillNumberId=AuditingBill.BillNumberID)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '5' AND NOT EXISTS(SELECT 1 FROM ReceiptBillIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '5' AND NOT EXISTS(SELECT 1 FROM ReceiptBillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '6' AND NOT EXISTS(SELECT 1 FROM onShelvespickIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '6' AND  NOT EXISTS(SELECT 1 FROM onShelvespickIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '7' AND NOT EXISTS(SELECT 1 FROM FactIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '7' AND NOT  EXISTS(SELECT 1 FROM FactIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '8' AND NOT EXISTS(SELECT 1 FROM Coupon_BillIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '8' AND NOT EXISTS(SELECT 1 FROM Coupon_BillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)	
		END
		ELSE
		BEGIN
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '2' AND NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '2' AND NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '0' AND NOT EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID)
			DELETE FROM AuditingBill WHERE BillIndexType = '0' AND NOT EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE BillNumberId=AuditingBill.BillNumberID)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '1'  AND NOT EXISTS(SELECT 1 FROM LendIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '1'  AND NOT EXISTS(SELECT 1 FROM LendIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '4' AND NOT EXISTS(SELECT 1 FROM CommissionBillNew WHERE BillNumberId=AuditingBillDetail.BillNumberID)
			DELETE FROM AuditingBill WHERE BillIndexType = '4' AND NOT EXISTS(SELECT 1 FROM CommissionBillNew WHERE BillNumberId=AuditingBill.BillNumberID)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '5' AND NOT EXISTS(SELECT 1 FROM ReceiptBillIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '5' AND NOT  EXISTS(SELECT 1 FROM ReceiptBillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '6' AND NOT EXISTS(SELECT 1 FROM onShelvespickIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '6' AND  NOT EXISTS(SELECT 1 FROM onShelvespickIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '7' AND NOT EXISTS(SELECT 1 FROM FactIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '7' AND NOT  EXISTS(SELECT 1 FROM FactIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
			
			DELETE FROM AuditingBillDetail WHERE BillIndexType = '8' AND NOT EXISTS(SELECT 1 FROM Coupon_BillIndex WHERE BillNumberId=AuditingBillDetail.BillNumberID AND IsIni=0)
			DELETE FROM AuditingBill WHERE BillIndexType = '8' AND NOT EXISTS(SELECT 1 FROM Coupon_BillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)		
		END
	END

	IF @chrRecPrice = '1'
	BEGIN
		UPDATE dbo.ptype SET recPrice=0
		UPDATE PType_STypePrice SET RecPrice=0,
									RecAppraisalPrice=0
	END
	
	IF @chrRecSalePrice='1'
	BEGIN
		UPDATE PType_STypePrice SET RecSalePrice=0,
									RecSendPrice=0
	END
	--商品分支机构间最近进价
	IF @chrRecSTypeBuyPrice='1'
	BEGIN
		UPDATE PType_Price SET RecAmgSTypeBuyPrice=0
	END
	--商品分支机构间最近售价
	IF @chrRecSTypeSalePrice='1'
	BEGIN
		UPDATE PType_Price SET RecAmgSTypeSalePrice=0
	END
	--分支机构间价格跟踪	
	IF @chrSTypePriceTrack='1'
	BEGIN
		TRUNCATE TABLE PriceTrack_SType_Appraisal	 --暂估入库分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_AskPrice	 --询价单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Buy	 --采购入库单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_BuyOrder	 --采购订单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Quote	 --报价单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Sale	 --销售出库分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_SaleOrder	 --销售订单分支机构间价格跟踪表
		TRUNCATE TABLE PriceTrack_SType_Send	 --发出商品分支机构间价格跟踪表
	END
	
	IF @delPriceTrack = '1'
	BEGIN
		TRUNCATE TABLE PriceTrack			-- 清除价格跟踪表
		
		--9.4价格跟踪变化后的清除
		TRUNCATE TABLE PriceTrack_AskPrice
		TRUNCATE TABLE PriceTrack_Buy
		TRUNCATE TABLE PriceTrack_BuyOrder
		TRUNCATE TABLE PriceTrack_Quote
		TRUNCATE TABLE PriceTrack_Sale
		TRUNCATE TABLE PriceTrack_SaleOrder
		TRUNCATE TABLE PriceTrack_Send
		TRUNCATE TABLE PriceTrack_Appraisal 
	END

	IF @delEventLog = '1'
	BEGIN
		DELETE FROM dbo.EventLog WHERE Id<>@logid --DELETE FROM EventLog --清掉操作日志表
	END
	
	IF @delmessage='1'
	BEGIN
		TRUNCATE TABLE IM_Message_NoSocket
		TRUNCATE TABLE IM_Message_NoSocket_Bak
	END	
	
	--调用总账的年结存
	DECLARE	@Re		INT
			,@rValue	VARCHAR(400)
	EXEC @Re = P_MF_YearProc @delDraft,@carefinancedata,@OperatorId,@rValue OUTPUT
	IF @Re <> 0
	BEGIN
		GOTO ERROR
	END	

	DELETE FROM Monthproc WHERE MonthNo <> '本期'
	
	--独立开账
	IF EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='stypeindependentopen' AND SubValue=1)
	BEGIN
		--年结前获取当前的会计年度和期间
		--未开张分支机构 直接期间，时间，年度
		--此处应该会调整
		DECLARE @newFPeriod	INT,
				@newFYear	INT,
				@BeginDate  DATETIME

		SELECT TOP 1 
			@newFPeriod=FPeriod,
			@newFYear=FYear 
		FROM Ac_AccountsPeroid_Stype 
		WHERE Stypeid IN(SELECT Stypeid FROM dbo.SType_UserConfig WHERE Value=0)
		
		SELECT @BeginDate=FBegin FROM dbo.Ac_Period WHERE FPeriod=@newFPeriod AND FYear=@newFYear
		
		UPDATE dbo.SType_UserConfig 
		SET 
			SFYear=@newFYear,
			SFPeriod=@newFPeriod
		WHERE Value=0
		
		UPDATE A
		SET 
			A.StartDate=@BeginDate,
			A.Period=@newFPeriod,
			A.YEAR=@newFYear
		FROM dbo.MonthProc A INNER JOIN dbo.SType_UserConfig B ON A.STypeID=B.StypeId
		WHERE A.MonthNo='本期' AND b.Value=0
		
		UPDATE dbo.SType_UserConfig 
		SET SfYear=B.Year,
		    sfperiod=B.Period 
		FROM dbo.SType_UserConfig A,dbo.MonthProc B 
		WHERE A.StypeId=B.STypeID AND Value=1 AND b.MonthNo='本期'
	END
	--非独立开账
	ELSE
	BEGIN
		--在总账版本下，年结存的时候，
		--将业务系统的年度和开始时间更新为当前总账的年度和期间；
		--非总账下年结存不做调整
		IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='isuseacsystem' AND SubValue=1)
		BEGIN
			DECLARE @StartDate DATETIME,
					@Year	   INT
			
			SELECT TOP 1  @StartDate=A.FBegin,@Year=A.FYear
			FROM dbo.Ac_Period A 
			INNER JOIN dbo.Ac_AccountsPeroid_Stype B 
			ON A.FPeriod=B.SFPeriod AND A.FYear=B.SFYear
			
			UPDATE	MonthProc
			SET		StartDate = @StartDate,
					Period = 1,
					[Year] = @Year
			WHERE	MonthNo = '本期'
			
			UPDATE dbo.SType_UserConfig 
			SET SfYear=C.SFYear,
				sfperiod=1
			FROM dbo.SType_UserConfig A
			INNER JOIN STYPE B ON B.TYPEID = A.STYPEID
			INNER JOIN Ac_AccountsPeroid_Stype C ON C.STYPEID = B.VerifyID
		END
		ELSE 
		BEGIN
			UPDATE	MonthProc
			SET		StartDate = CAST(YEAR(GETDATE()) AS VARCHAR) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR) + '-' + CAST(DAY(GETDATE()) AS VARCHAR),
					Period = 1,
					[Year] = YEAR(GETDATE())
			WHERE	MonthNo = '本期'
			
			UPDATE dbo.SType_UserConfig 
			SET SfYear=YEAR(GETDATE()),
				sfperiod=1
			FROM dbo.SType_UserConfig A
		END
	END
	
	IF @@ROWCOUNT = 0 GOTO ERROR
	UPDATE	SysData
	SET		SubValue = 1
	WHERE	SubName ='period'
	IF @@ERROR <> 0 GOTO ERROR
	
	UPDATE	SysData
	SET		SubValue = '0000000000'
	WHERE	SubName LIKE '%Code'
			AND SubName NOT IN('bwbcode','hyyunsms_usercode')--排除短信账号
	IF @@ROWCOUNT = 0 GOTO ERROR

	UPDATE	SysData
	SET		SubValue = '1'
	WHERE	SubName = 'CanAuditing'
	IF @@ROWCOUNT = 0 GOTO ERROR

	UPDATE	SysData
	SET		SubValue = 'T'
	WHERE	SubName = 'inicanmodify'
	IF @@ROWCOUNT = 0 GOTO ERROR

	UPDATE UserConfig SET Value = '0' WHERE ConfigName = 'AverageCostPrice'
	
	--清空开账标识
	UPDATE SType_UserConfig SET Value = '0' WHERE ConfigNo = '1' 
	
	--父节点没有存在的必要了
	DELETE FROM dbo.SType_UserConfig
	WHERE StypeId IN (SELECT typeid FROM dbo.SType WHERE sonnum>0)
	
	---------------------期初应收应付单据编号，单据日期----------------------------
	DECLARE @IniBillDate DATETIME
	SELECT @IniBillDate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth
	UPDATE A
		SET A.BillDate=CONVERT(DATE, @IniBillDate),
			A.BillCode=CASE A.billtype WHEN 189 THEN 'IniYskBill-'
									   WHEN 190 THEN 'IniYfkBill-' 
									   ELSE ''
									   END + A.STypeID +'-'+CONVERT(VARCHAR(10),@IniBillDate,120)+'-'+CAST(RowIndex AS VARCHAR(10))
	FROM dbo.BillIndex A,(
		SELECT BillNumberId,BillType,ROW_NUMBER() OVER(ORDER BY BillCode ASC) AS RowIndex
		FROM dbo.BillIndex WHERE IsIni=1 AND ifYearBill=1 AND BillType IN(189,190)
	) B
	WHERE A.BillNumberId=B.BillNumberId
	
	DECLARE @NewID VARCHAR(9)
	SET @NewID=LEFT(NEWID(),9)  
	
	UPDATE	A
	SET		A.BillDate=CONVERT(DATE, @IniBillDate),			
			A.BillCode=CASE A.billtype WHEN 115 THEN 'IniYjBill-' 
									   WHEN 116 THEN 'IniYzBill-' 
									   WHEN 128 THEN 'IniFzBill-'
									   WHEN 129 THEN 'IniFjBill-'
									   ELSE ''
									   END +@NewID+ A.STypeID +'-'+CONVERT(VARCHAR(10),@IniBillDate,120)+'-'+CAST(RowIndex AS VARCHAR(10))
	FROM dbo.BillIndex A,
	(
		SELECT	BillNumberId,
				BillType,
				ROW_NUMBER() OVER(ORDER BY BillCode ASC) AS RowIndex
		FROM	dbo.BillIndex 
		WHERE	IsIni=1 
				AND ifYearBill=1 
				AND BillType IN(115,116,128,129)
	) B
	WHERE A.BillNumberId=B.BillNumberId
	---------------------期初应收应付单据编号，单据日期----------------------------
	
	--删除单据的触发器处理
	EXEC Gp_YearProc_DeleteBill_Trigger
	
	
    --系统年结存后，重算草稿库存
    exec QP_Recount_DraftQty
    
     --系统重建，重算订单库存
     DECLARE @FLAG INT =1
    exec QP_Recount_OrderQty @FLAG
    
    --系统重建，清除部分pos相关的数据
    exec QP_Clear_PosData
    
    --店账通单据的处理
    DELETE FROM EshopBillRelation WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
    
    --删除电子面单
    DELETE FROM BillExpressage WHERE VchCode NOT IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 11)
    
    --删除WMS对应数据    
    DELETE FROM WMS_ERPBillRelation WHERE ERP_BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)
   
    COMMIT TRAN YearProc
	RETURN 0
	
	ERROR:	
		ROLLBACK TRAN YearProcPoint
		COMMIT TRAN YearProc
		RETURN -1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_Ac_Balance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_Ac_Balance]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-05-08
	描述：年结处理会计凭证余额
	EXEC Gp_YearProc_Ac_Balance '1','2020',1,'2020',1,'2019',''
*/
CREATE PROCEDURE Gp_YearProc_Ac_Balance
(
	@delDraft		CHAR(1) = '1',			-- 是否清除草稿
	@oldFYear		VARCHAR(10),			-- 年结前的会计年度
	@oldFPeriod		INT,					-- 年结前的财务期间
	@newFYear		VARCHAR(10),			-- 年结后的会计年度
	@newFPeriod		INT,					-- 年结后的财务期间
	@iniFyear		INT,
	@rValue			VARCHAR(400) OUTPUT		-- 输出信息	
)
--@encode$--
AS
SET NOCOUNT ON

--本币
DECLARE @Cid INT
SELECT	TOP 1
		@Cid = Cid
FROM	Ac_Currency
WHERE	Sysrow = 1		

DELETE FROM Ac_IniAccount WHERE FYTotal=0 AND FYTotalFor=0 AND FYTotalDebit=0 AND FYTotalDebitFor=0 AND FYTotalCredit=0 AND FYTotalCreditFor=0

CREATE TABLE #FYTotal
(
	stypeid	VARCHAR(50)
	,atypeid	VARCHAR(50)
	,cid	INT
	,FYTotal	NUMERIC(24,10)
	,FYTotalFor	NUMERIC(24,10)
	,FYTotalDebit	NUMERIC(24,10)
	,FYTotalDebitFor	NUMERIC(24,10)
	,FYTotalCredit	NUMERIC(24,10)
	,FYTotalCreditFor	NUMERIC(24,10)
)
INSERT INTO #FYTotal
(
	stypeid
	,atypeid
	,cid
	,FYTotal
	,FYTotalFor
	,FYTotalDebit
	,FYTotalDebitFor
	,FYTotalCredit
	,FYTotalCreditFor
)
SELECT	STypeId
		,ATypeId
		,Cid
		,CASE WHEN FYear = @newFYear THEN FYTotal ELSE 0 END AS FYTotal
		,CASE WHEN FYear = @newFYear THEN FYTotalFor ELSE 0 END AS FYTotalFor
		,0 AS FYTotalDebit
		,0 AS FYTotalDebitFor
		,0 AS FYTotalCredit
		,0 AS FYTotalCreditFor
FROM Ac_IniAccount
UNION ALL
SELECT	vb.STypeId
		,ATypeId
		,Cid
		,0
		,0
		,vb.FDebitTotal
		,vb.FDebitTotalFor
		,vb.FCreditTotal
		,vb.FCreditTotalFor		
FROM Ac_Voucher_Bill VB
INNER JOIN	Ac_Voucher V ON V.BillNumberId = VB.BillNumberId
--INNER JOIN	Ac_Account A ON A.StypeId = VB.STypeId AND A.TypeId = VB.ATypeId
WHERE	V.IfCheck = 't'
	AND	V.VoucherType !=2
	AND	V.RedWord = 0
	AND VB.ATypeId LIKE '00003%'
	AND V.FYear = @newFYear
	
--先清空期初数据
TRUNCATE TABLE Ac_IniAccount

--清空余额表中余额为0的科目 add by dongzhan 9.2version
IF @oldFYear<>@newFYear
BEGIN
	DELETE FROM dbo.Ac_Balance WHERE FEndBalance=0 AND FEndBalanceFor=0 AND FEndqty=0 AND FYear = @oldFYear AND FPeriod = @oldFPeriod
	DELETE FROM dbo.Ac_Balance_Assist_CheckItems WHERE FEndBalance=0 AND FEndBalanceFor=0 AND FYear = @oldFYear AND FPeriod = @oldFPeriod
	DELETE FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE FEndBalance=0 AND FEndBalanceFor=0 AND FEndqty=0 AND FYear = @oldFYear AND FPeriod = @oldFPeriod
END

--写入科目余额表
INSERT INTO Ac_IniAccount 
(
	STypeId, 
	ATypeId, 
	iniYTotal, 
	iniYTotalFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	iniTotal, 
	iniTotalFor, 
	iniqty,
	FDebitqty,
	FCreditqty,
	IniYqty,
	Cid,
	FYear,
	FPeriod
	,FYTotal
	,FYTotalFor
)
SELECT	STypeId, 
		ATypeId, 
		0,
		0,
		ISNULL(SUM(FYtdDebit),0), 
		ISNULL(SUM(FYtdDebitFor),0), 
		ISNULL(SUM(FYtdCredit),0), 
		ISNULL(SUM(FYtdCreditFor),0),
		ISNULL(SUM(FEndBalance),0) AS iniTotal, 
		ISNULL(SUM(FEndBalanceFor),0) AS iniTotalFor,
		ISNULL(SUM(FEndqty),0) AS iniqty,
		ISNULL(SUM(FYtdDebitqty),0) AS FDebitqty,
		ISNULL(SUM(FYtdCreditqty),0) AS FCreditqty,
		0,	
		Cid,
		@newFYear AS FYear,
		@newFPeriod AS FPeriod
		,SUM(FYTotal)
		,SUM(FYTotalFor)
FROM	(
	SELECT	STypeId
			,ATypeId
			,FYtdDebit
			,FYtdDebitFor
			,FYtdCredit
			,FYtdCreditFor
			,FEndBalance
			,FEndBalanceFor
			,FEndqty
			,FYtdDebitqty
			,FYtdCreditqty
			,Cid
			,0 AS FYTotal
			,0 AS FYTotalFor
	FROM	Ac_Balance
	WHERE	Cid <> 0
		AND FYear = @oldFYear
		AND FPeriod = @oldFPeriod
	UNION ALL
	SELECT	F.stypeid
			,F.atypeid
			,0
			,0
			,0
			,0
			,0
			,0
			,0
			,0
			,0
			,F.cid
			,CASE WHEN A.Fdc = 1 THEN F.FYTotal + F.FYTotalDebit - F.FYTotalCredit ELSE  F.FYTotal - F.FYTotalDebit + F.FYTotalCredit END
			,CASE WHEN A.Fdc = 1 THEN F.FYTotalFor + F.FYTotalDebitFor - F.FYTotalCreditFor ELSE  F.FYTotalFor - F.FYTotalDebitFor + F.FYTotalCreditFor END
	FROM #FYTotal F
	INNER JOIN Ac_Account A ON A.StypeId = F.stypeid AND A.TypeId = F.atypeid
	) T
GROUP BY STypeId,
		 ATypeId,
		 Cid

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -1
END

------结转辅助核算明细表数据
--备注：因为辅助核算明细表的余额表里面没有分组，而期初表是需要分组的，所以不能直接从辅助核算明细余额表取数据转入期初表，只能统计所有凭证明细

--跨年数据，清除Ac_IniAccount_Assist_CheckItems_Detail表中期初为0的数据
DELETE FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE FYear <> @newFYear AND IniTotal = 0 AND IniTotalFor = 0

DECLARE @STypeId			VARCHAR(50),
		@ATypeId			VARCHAR(50),
		@Cid_Detail				INT,
		@IniYTotal			 NUMERIC(24, 10) ,
		@IniYTotalFor		 NUMERIC(24, 10) ,
		@IniTotal			 NUMERIC(24, 10) ,
		@IniTotalFor		 NUMERIC(24, 10) ,
		@FDebitTotal		 NUMERIC(24, 10) ,
		@FDebitTotalFor		 NUMERIC(24, 10) ,
		@FCreditTotal		 NUMERIC(24, 10) ,
		@FCreditTotalFor	 NUMERIC(24, 10) ,
		@FEndBalance		 NUMERIC(24, 10) ,
		@FEndBalanceFor		 NUMERIC(24, 10) ,
		@GroupValue			VARCHAR(MAX),
		@Ascids				VARCHAR(10),
  		@FieldValue			VARCHAR(50),
  		@Fdc				INT,
  		@GroupId			INT,
  		@IniYqty             NUMERIC(24, 10) ,
		@Iniqty         NUMERIC(24, 10) ,
		@FDebitqty      NUMERIC(24, 10) ,
		@FCreditqty     NUMERIC(24, 10) ,
		@FEndBalanceqty	     NUMERIC(24, 10) ,
		@FYTotal     NUMERIC(24, 10) ,
		@FYTotalFor	     NUMERIC(24, 10),
		@FYear			INT 
		
CREATE TABLE #Ac_IniAccount_Assist_CheckItems_Detail		
(
	STypeId			VARCHAR(50),
	ATypeId			VARCHAR(50),
	Cid				INT,
	IniYTotal		 NUMERIC(24, 10)  DEFAULT(0),
	IniYTotalFor	 NUMERIC(24, 10)  DEFAULT(0),
	IniTotal		 NUMERIC(24, 10)  DEFAULT(0),
	IniTotalFor		 NUMERIC(24, 10)  DEFAULT(0),
	FDebitTotal		 NUMERIC(24, 10)  DEFAULT(0),
	FDebitTotalFor	 NUMERIC(24, 10)  DEFAULT(0),
	FCreditTotal	 NUMERIC(24, 10)  DEFAULT(0),
	FCreditTotalFor	 NUMERIC(24, 10)  DEFAULT(0),	
	FEndBalance		 NUMERIC(24, 10)  DEFAULT(0),	
	FEndBalanceFor	 NUMERIC(24, 10)  DEFAULT(0),	
	iniGroupValue	VARCHAR(MAX)  DEFAULT(''),
	--GroupId			INT,
	IniYqty          NUMERIC(24, 10)  DEFAULT(0),
	Iniqty           NUMERIC(24, 10)  DEFAULT(0),
	FDebitqty        NUMERIC(24, 10)  DEFAULT(0),
	FCreditqty       NUMERIC(24, 10)  DEFAULT(0),
	FEndBalanceqty   NUMERIC(24, 10)  DEFAULT(0),
	FYTotal        NUMERIC(24, 10)  DEFAULT(0),
	FYTotalFor       NUMERIC(24, 10)  DEFAULT(0),
	FYear			INT
)
CREATE NONCLUSTERED INDEX CIX_Ac_IniAccount_Assist_CheckItems_Detail_INDEX ON #Ac_IniAccount_Assist_CheckItems_Detail(STypeId,ATypeId,Cid)

INSERT	INTO #Ac_IniAccount_Assist_CheckItems_Detail
(
	STypeId,
	ATypeId,
	Cid,
	IniYTotal,
	IniYTotalFor,
	IniTotal,
	IniTotalFor,
	iniGroupValue,
	FDebitTotal,
	FDebitTotalFor,
	FCreditTotal,
	FCreditTotalFor,
	FEndBalance,
	FEndBalanceFor,
	IniYqty,
	Iniqty,
	FDebitqty,
	FCreditqty,
	FEndBalanceqty,
	FYTotal,
	FYTotalFor,
	FYear
)		
SELECT  DISTINCT
		stypeid,
		atypeid,
		cid,
		IniYTotal,	
		IniYTotalFor,
		IniTotal,
		IniTotalFor,			
		iniGroupValue = STUFF((
			SELECT	','+CAST(Ascids AS varchar) + ':' + fieldvalue 
			FROM	Ac_IniAccount_Assist_CheckItems_Detail
			WHERE	stypeid = a.stypeid
					AND atypeid = a.atypeid
					AND cid = a.cid
					AND groupid = a.groupid
			FOR XML PATH('')
		),1,1,''),
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		IniTotal,
		IniTotalFor,
		IniYqty,
		Iniqty,
		FDebitqty,
		FCreditqty,
		iniqty,
		FYTotal,
		FYTotalFor,
		FYear
FROM	Ac_IniAccount_Assist_CheckItems_Detail a


--统计凭证明细数据
CREATE TABLE #voucher_Assist_CheckItems_Detail
(
	stypeid	VARCHAR(50)
	,atypeid	VARCHAR(50)
	,cid	INT
	,ascids	VARCHAR(1000)
	,FDebit	NUMERIC(24,10)
	,FDebitFor	NUMERIC(24,10)
	,FCredit	NUMERIC(24,10)
	,FCreditFor	NUMERIC(24,10)
	,FDebitQty	NUMERIC(24,10)
	,FCreditQty	NUMERIC(24,10)
	,FYDebit	NUMERIC(24,10)
	,FYDebitFor	NUMERIC(24,10)
	,FYCredit	NUMERIC(24,10)
	,FYCreditFor	NUMERIC(24,10)
	,FYDebitQty	NUMERIC(24,10)
	,FYCreditQty	NUMERIC(24,10)
	,FYTotal	NUMERIC(24,10)
	,FYTotalFor	NUMERIC(24,10)
)
CREATE NONCLUSTERED INDEX CIX_voucher_Assist_CheckItems_Detail_Index ON #voucher_Assist_CheckItems_Detail(STypeId,ATypeId,Cid)


INSERT INTO #voucher_Assist_CheckItems_Detail
(
	stypeid
	,atypeid
	,cid
	,ascids
	,FDebit
	,FDebitFor
	,FCredit
	,FCreditFor
	,FDebitQty
	,FCreditQty
	,FYDebit
	,FYDebitFor
	,FYCredit
	,FYCreditFor
	,FYDebitQty
	,FYCreditQty
	,FYTotal
	,FYTotalFor
)
SELECT	b.STypeId,
		b.ATypeId,
		b.Cid,
		LEFT(ISNULL(B.AscIds,''),LEN(ISNULL(B.AscIds,''))-1) AS Ascids,
		B.FDebitTotal,
		B.FDebitTotalFor,
		B.FCreditTotal,
		B.FCreditTotalFor,
		B.FDebitQty,
		B.FCreditQty
		,CASE WHEN B.FYear = @newFYear THEN B.FDebitTotal ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FDebitTotalFor ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FCreditTotal ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FCreditTotalFor ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FDebitQty ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FCreditQty ELSE 0 END		
		,CASE WHEN B.FYear = @newFYear AND v.VoucherType <> 2 AND LEFT(B.ATYPEID,5) = '00003' THEN B.FDebitTotal - B.FCreditTotal ELSE 0 END
		,CASE WHEN B.FYear = @newFYear AND v.VoucherType <> 2 AND LEFT(B.ATYPEID,5) = '00003' THEN B.FDebitTotalFor - B.FCreditTotalFor ELSE 0 END		
FROM	Ac_Voucher_Bill B
INNER JOIN Ac_Voucher V ON B.BillNumberId = V.BillNumberId
WHERE	ISNULL(B.AscIds,'') <> ''
		AND V.FChecked <> -1
		AND V.IfCheck = 't'  

SELECT T1.*,DENSE_RANK() OVER (PARTITION BY T1.STypeId,T1.ATypeId,T1.Cid ORDER BY T1.STypeId,T1.ATypeId,T1.Cid,T1.ascids,T1.FEndBalance) as  gpid 
INTO #Ac_IniAccount_Assist_CheckItems_Detail1
FROM(
		SELECT	STypeId,
				ATypeId,
				Cid,
				ascids,
				SUM(IniYTotal) AS IniYTotal,
				SUM(IniYTotalFor) AS IniYTotalFor,
				SUM(IniTotal) AS IniTotal,
				SUM(IniTotalFor) AS IniTotalFor,
				SUM(FDebitTotal) AS FDebitTotal,
				SUM(FDebitTotalFor) AS FDebitTotalFor,
				SUM(FCreditTotal) AS FCreditTotal,
				SUM(FCreditTotalFor) AS FCreditTotalFor,
				SUM(FEndBalance) AS FEndBalance,
				SUM(FEndBalanceFor) AS FEndBalanceFor,
				SUM(IniYqty) AS IniYqty,
				SUM(Iniqty) AS Iniqty,
				SUM(FDebitqty) AS FDebitqty,
				SUM(FCreditqty) AS FCreditqty,
				SUM(FEndBalanceqty) AS FEndBalanceqty,
				SUM(FYTotal) AS FYTotal,
				SUM(FYTotalFor) AS FYTotalFor
		FROM	(
				SELECT	STypeId,
						ATypeId,
						Cid,
						iniGroupValue AS ascids,
						IniYTotal,
						IniYTotalFor,
						IniTotal,
						IniTotalFor,
						CASE WHEN FYear = @newFYear THEN FDebitTotal ELSE 0 END AS FDebitTotal,
						CASE WHEN FYear = @newFYear THEN FDebitTotalFor ELSE 0 END AS FDebitTotalFor,
						CASE WHEN FYear = @newFYear THEN FCreditTotal ELSE 0 END AS FCreditTotal,
						CASE WHEN FYear = @newFYear THEN FCreditTotalFor ELSE 0 END AS FCreditTotalFor,
						FEndBalance,
						FEndBalanceFor,
						--GroupId,
						IniYqty,
						Iniqty,
						FDebitqty,
						FCreditqty,
						FEndBalanceqty,
						CASE WHEN FYear = @newFYear THEN FYTotal ELSE 0 END AS FYTotal,
						CASE WHEN FYear = @newFYear THEN FYTotalFor ELSE 0 END AS FYTotalFor
				FROM	#Ac_IniAccount_Assist_CheckItems_Detail
				UNION ALL
				SELECT	B.stypeid,
						B.ATypeId,
						B.Cid,
						B.ascids,
						0,
						0,
						0,
						0,
						B.FYDebit,
						B.FYDebitFor,
						B.FYCredit,
						b.FYCreditFor,
						A.Fdc*(FDebit - FCredit),
						A.Fdc*(FDebitFor - FCreditFor),
						--GroupId,
						0,
						0,
						B.FYDebitQty,
						B.FYCreditQty,
						A.Fdc*(FDebitqty-FCreditqty),
						A.Fdc*FYTotal,
						A.Fdc*FYTotalFor
				FROM	#voucher_Assist_CheckItems_Detail B
				INNER JOIN	Ac_Account A ON A.StypeId =B.stypeid AND A.TypeId = B.atypeid

				) T
				GROUP BY STypeId,ATypeId,Cid,ascids
		) T1

--先清空期初数据
TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems_Detail

DECLARE @iniGroupValue	VARCHAR(MAX),
		@mxValue		VARCHAR(MAX)			

DECLARE R_CURSOR CURSOR FAST_FORWARD FOR
	SELECT	STypeId,ATypeId,Cid,ascids,FDebitTotal,FDebitTotalFor,FCreditTotal,FCreditTotalFor,
			FEndBalance,FEndBalanceFor,FDebitqty,FCreditqty,FEndBalanceqty,gpid,FYTotal,FYTotalFor
	FROM	#Ac_IniAccount_Assist_CheckItems_Detail1
	
OPEN R_CURSOR

FETCH NEXT FROM R_CURSOR INTO @STypeId,@ATypeId,@cid_detail,@iniGroupValue,@FDebitTotal,@FDebitTotalFor,@FCreditTotal,@FCreditTotalFor
								,@FEndBalance,@FEndBalanceFor,@FDebitqty,@FCreditqty,@FEndBalanceqty,@GroupId
								,@FYTotal,@FYTotalFor

WHILE @@FETCH_STATUS = 0
BEGIN
	INSERT INTO Ac_IniAccount_Assist_CheckItems_Detail
	(
		STypeId,
		ATypeId,
		Cid,
		Ascids,
		FieldValue,
		IniYTotal,
		IniYTotalFor,
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		IniTotal,
		IniTotalFor,
		GroupId,
		FYear,
		FPeriod,
		IniYqty,
		iniqty,
		FDebitqty,
		FCreditqty
		,FYTotal
		,FYTotalFor
	)
	SELECT	
			@STypeId,
			@ATypeId,
			@Cid_Detail,
			LEFT(a,1),
			RIGHT(a,LEN(a)-2),
			0,
			0,
			@FDebitTotal,
			@FDebitTotalFor,
			@FCreditTotal,
			@FCreditTotalFor,
			@FEndBalance,
			@FEndBalanceFor,
			@GroupId,
			@newFYear,
			@newFPeriod,
			0,
			@FEndBalanceqty,
			@FDebitqty,
			@FCreditqty,
			@FYTotal,
			@FYTotalFor
	FROM	dbo.f_split(@iniGroupValue,',')	
		
	FETCH NEXT FROM R_CURSOR INTO @STypeId,@ATypeId,@Cid_Detail,@iniGroupValue,@FDebitTotal,@FDebitTotalFor,@FCreditTotal,@FCreditTotalFor
									,@FEndBalance,@FEndBalanceFor,@FDebitqty,@FCreditqty,@FEndBalanceqty,@GroupId
									,@FYTotal,@FYTotalFor
END

CLOSE R_CURSOR
DEALLOCATE R_CURSOR

IF @newFPeriod = 1
BEGIN
	UPDATE Ac_IniAccount SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0
	UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0
END

--更新年初
UPDATE ai SET iniYTotal=(CASE WHEN aa.Fdc=1 THEN iniTotal-FDebit+FCredit ELSE iniTotal+FDebit-FCredit END),
			  iniYTotalFor=(CASE WHEN aa.fdc=1 THEN iniTotalFor-FDebitFor+FCreditFor ELSE iniTotalFor+FDebitFor-FCreditFor END),
			  IniYqty=(CASE WHEN aa.Fdc=1 THEN iniqty-FDebitqty+FCreditqty ELSE iniqty+FDebitqty-FCreditqty END)
FROM dbo.Ac_IniAccount ai
JOIN dbo.Ac_Account aa ON ai.STypeId=aa.StypeId AND ai.ATypeId=aa.TypeId

--更新年初
UPDATE ai SET iniYTotal=(CASE WHEN aa.Fdc=1 THEN iniTotal-FDebit+FCredit ELSE iniTotal+FDebit-FCredit END),
			  iniYTotalFor=(CASE WHEN aa.fdc=1 THEN iniTotalFor-FDebitFor+FCreditFor ELSE iniTotalFor+FDebitFor-FCreditFor END),
			  IniYqty=(CASE WHEN aa.Fdc=1 THEN iniqty-FDebitqty+FDebitqty ELSE iniqty+FDebitqty-FCreditqty END)
FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail ai
JOIN dbo.Ac_Account aa ON ai.STypeId=aa.StypeId AND ai.ATypeId=aa.TypeId 


DROP TABLE #Ac_IniAccount_Assist_CheckItems_Detail1
------结转辅助核算明细表数据end


TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems

--从主表转移辅助核算类科目
INSERT INTO Ac_IniAccount_Assist_CheckItems
(
	STypeId, 
	ATypeId, 
	Cid, 
	IniYTotal, 
	IniYTotalFor, 
	FDebit, 
	FCredit, 	
	FDebitFor, 
	FCreditFor,	
	IniTotal, 	
	IniTotalFor,
	FYear,
	FPeriod,
	IniYqty,
	Iniqty,
	FDebitqty,
	FCreditqty
	,FYTotal
	,FYTotalFor
)
SELECT  A.STypeId, 
		A.ATypeId, 
		Cid, 
		IniYTotal, 
		IniYTotalFor, 
		FDebit, 
		FCredit, 	
		FDebitFor, 
		FCreditFor,	
		IniTotal, 	
		IniTotalFor,
		FYear,
		FPeriod,
		IniYqty,
		Iniqty,
		FDebitqty,
		FCreditqty
		,FYTotal
		,FYTotalFor
FROM	Ac_IniAccount A
INNER JOIN	(SELECT STypeId,ATypeId FROM Ac_Account_Assist_CheckItems GROUP BY STypeId,ATypeId) T ON T.STypeId = A.STypeId AND T.ATypeId = A.ATypeId
WHERE A.Cid <> 0

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -1
END

--清除异常数据
--清除科目已经被删除但是年结后期初表还有数据的记录 (年结后开账遇到的bug)
DELETE A FROM Ac_IniAccount A
WHERE NOT  EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE STypeId= A.STypeId AND TypeId=A.ATypeId)

DELETE A FROM dbo.Ac_IniAccount_Assist_CheckItems A
WHERE NOT  EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE STypeId= A.STypeId AND TypeId=A.ATypeId)

DELETE A FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail A
WHERE NOT  EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE STypeId= A.STypeId AND TypeId=A.ATypeId)

--清除辅助核算明细表中已经不是辅助核算科目的记录
DELETE A FROM Ac_IniAccount_Assist_CheckItems_Detail A 
WHERE NOT EXISTS (SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems B WHERE B.STYPEID = A.STYPEID AND B.ATYPEID = A.ATYPEID)

--清除数据为0的记录，因为存在辅助核算明细数据不为0，但合计后为0的情况，所以先清除辅助核算明细表的数据，在清除其他两个表
DELETE FROM Ac_IniAccount_Assist_CheckItems_Detail  
WHERE iniYTotal=0 AND iniYTotalFor=0 AND FDebit=0 AND FDebitFor=0 AND FCredit=0 AND FCreditFor=0 AND iniTotal=0 AND iniTotalFor=0 AND FYTotal=0 AND FYTotalFor=0

DELETE I FROM Ac_IniAccount I
WHERE iniYTotal=0 AND iniYTotalFor=0 AND FDebit=0 AND FDebitFor=0 AND FCredit=0 AND FCreditFor=0 AND iniTotal=0 AND iniTotalFor=0 AND FYTotal=0 AND FYTotalFor=0
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail III WHERE III.STypeId = I.STypeId AND III.ATypeId = I.ATypeId AND III.Cid = I.Cid)

DELETE I FROM Ac_IniAccount_Assist_CheckItems  I
WHERE NOT EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail III WHERE III.STypeId = I.STypeId AND III.ATypeId = I.ATypeId AND III.Cid = I.Cid)

DROP TABLE #Ac_IniAccount_Assist_CheckItems_Detail,#voucher_Assist_CheckItems_Detail

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_Ac_Balance_Assist_CheckItems_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_Ac_Balance_Assist_CheckItems_Detail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-05-08
	描述：年结处理会计凭证余额
*/
CREATE PROCEDURE Gp_YearProc_Ac_Balance_Assist_CheckItems_Detail
(
	@oldFYear		VARCHAR(10),			-- 年结前的会计年度
	@oldFPeriod		INT,					-- 年结前的财务期间
	@newFYear		VARCHAR(10),			-- 年结后的会计年度
	@newFPeriod		INT,					-- 年结后的财务期间
	@iniFyear		INT,
	@rValue			VARCHAR(400) OUTPUT		-- 输出信息		
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @STypeId			VARCHAR(50),
		@ATypeId			VARCHAR(50),
		@Cid				INT,
		@IniYTotal			 NUMERIC(24, 10) ,
		@IniYTotalFor		 NUMERIC(24, 10) ,
		@IniTotal			 NUMERIC(24, 10) ,
		@IniTotalFor		 NUMERIC(24, 10) ,
		@FDebitTotal		 NUMERIC(24, 10) ,
		@FDebitTotalFor		 NUMERIC(24, 10) ,
		@FCreditTotal		 NUMERIC(24, 10) ,
		@FCreditTotalFor	 NUMERIC(24, 10) ,
		@FEndBalance		 NUMERIC(24, 10) ,
		@FEndBalanceFor		 NUMERIC(24, 10) ,
		@GroupValue			VARCHAR(MAX),
		@Ascids				VARCHAR(10),
  		@FieldValue			VARCHAR(50),
  		@Fdc				INT,
  		@GroupId			INT,
  		@IniYqty             NUMERIC(24, 10) ,
		@Iniqty         NUMERIC(24, 10) ,
		@FDebitqty      NUMERIC(24, 10) ,
		@FCreditqty     NUMERIC(24, 10) ,
		@FEndBalanceqty	     NUMERIC(24, 10) 
  		 

DECLARE @Ac_IniAccount_Assist_CheckItems_Detail TABLE		
(
	STypeId			VARCHAR(50),
	ATypeId			VARCHAR(50),
	Cid				INT,
	IniYTotal		 NUMERIC(24, 10)  DEFAULT(0),
	IniYTotalFor	 NUMERIC(24, 10)  DEFAULT(0),
	IniTotal		 NUMERIC(24, 10)  DEFAULT(0),
	IniTotalFor		 NUMERIC(24, 10)  DEFAULT(0),
	FDebitTotal		 NUMERIC(24, 10)  DEFAULT(0),
	FDebitTotalFor	 NUMERIC(24, 10)  DEFAULT(0),
	FCreditTotal	 NUMERIC(24, 10)  DEFAULT(0),
	FCreditTotalFor	 NUMERIC(24, 10)  DEFAULT(0),	
	FEndBalance		 NUMERIC(24, 10)  DEFAULT(0),	
	FEndBalanceFor	 NUMERIC(24, 10)  DEFAULT(0),	
	iniGroupValue	VARCHAR(MAX)  DEFAULT(''),
	GroupId			INT,
	IniYqty          NUMERIC(24, 10)  DEFAULT(0),
	Iniqty           NUMERIC(24, 10)  DEFAULT(0),
	FDebitqty        NUMERIC(24, 10)  DEFAULT(0),
	FCreditqty       NUMERIC(24, 10)  DEFAULT(0),
	FEndBalanceqty   NUMERIC(24, 10)  DEFAULT(0)
)
		
DECLARE Abc_Cursor CURSOR FOR
	SELECT 	C.STypeId,
			C.ATypeId,
			C.Cid
	FROM	Ac_Balance_Assist_CheckItems C 	
	WHERE	C.Cid <> 0
			AND FYear = @oldFYear
			AND FPeriod = @oldFPeriod	
	
OPEN Abc_Cursor

FETCH NEXT FROM Abc_Cursor INTO @STypeId,
								@ATypeId,
								@Cid

WHILE @@FETCH_STATUS = 0
BEGIN
	--****************************************************************************算期初****************************************************************************--	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = @Cid)
	BEGIN						
		DECLARE AbcMx_Cursor CURSOR FOR
			SELECT	Ascids, FieldValue,GroupId,IniYTotal,IniYTotalFor,IniTotal,IniTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,IniYqty,iniqty,FDebitqty,FCreditqty,iniqty
			FROM	Ac_IniAccount_Assist_CheckItems_Detail
			WHERE	STypeId = @STypeId 
					AND ATypeId = @ATypeId 
					AND Cid = @Cid
			ORDER BY Ascids ASC
			
		OPEN AbcMx_Cursor
		
		FETCH NEXT FROM AbcMx_Cursor INTO	@Ascids, 
											@FieldValue,
											@GroupId,
											@IniYTotal,
											@IniYTotalFor,
											@IniTotal,
											@IniTotalFor,
											@FDebitTotal,
											@FDebitTotalFor,
											@FCreditTotal,
											@FCreditTotalFor,
											@FEndBalance,
											@FEndBalanceFor,
											@IniYqty,
											@Iniqty,
											@FDebitqty,
											@FCreditqty,
											@FEndBalanceqty						
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF NOT EXISTS(SELECT TOP 1 1 FROM @Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = @Cid AND GroupId = @GroupId)
			BEGIN	--写入期初数据
				INSERT INTO @Ac_IniAccount_Assist_CheckItems_Detail
				(
					STypeId,
					ATypeId,
					Cid,
					IniYTotal,
					IniYTotalFor,
					IniTotal,
					IniTotalFor,
					iniGroupValue,
					FDebitTotal,
					FDebitTotalFor,
					FCreditTotal,
					FCreditTotalFor,
					FEndBalance,
					FEndBalanceFor,
					GroupId,
					IniYqty,
					Iniqty,
					FDebitqty,
					FCreditqty,
					FEndBalanceqty
				)VALUES(
					@STypeId,
					@ATypeId,
					@Cid,
					@IniYTotal,
					@IniYTotalFor,
					@IniTotal,
					@IniTotalFor,
					@Ascids + ':' + @FieldValue,
					@FDebitTotal,
					@FDebitTotalFor,
					@FCreditTotal,
					@FCreditTotalFor,
					@FEndBalance,
					@FEndBalanceFor,
					@GroupId,
					@IniYqty,
					@Iniqty,
					@FDebitqty,
					@FCreditqty,
					@FEndBalanceqty	
				)
			END
			ELSE	--修改数据
			BEGIN
				UPDATE	@Ac_IniAccount_Assist_CheckItems_Detail
				SET		iniGroupValue = iniGroupValue + ',' + @Ascids + ':' + @FieldValue						
				WHERE	ATypeId = @ATypeId
						AND STypeId = @STypeId
						AND Cid = @Cid
						AND GroupId = @GroupId
			END
			
			FETCH NEXT FROM AbcMx_Cursor INTO	@Ascids, 
												@FieldValue,
												@GroupId,
												@IniYTotal,
												@IniYTotalFor,
												@IniTotal,
												@IniTotalFor,
												@FDebitTotal,
												@FDebitTotalFor,
												@FCreditTotal,
												@FCreditTotalFor,
												@FEndBalance,
												@FEndBalanceFor,
												@IniYqty,
												@Iniqty,
												@FDebitqty,
												@FCreditqty,
												@FEndBalanceqty	
		END
		
		CLOSE AbcMx_Cursor
		DEALLOCATE AbcMx_Cursor
	END
									
	--****************************************************************************算单据明细****************************************************************************--
	SET @GroupValue = ''
	IF EXISTS(
				SELECT  TOP 1 1 
				FROM	Ac_Voucher_Bill B,Ac_Voucher V 
				WHERE	V.BillNumberId = B.BillNumberId 
						AND B.STypeId = @STypeId 
						AND B.ATypeId = @ATypeId 
						AND B.Cid = @Cid
						AND ISNULL(B.AscIds,'') <> ''
						AND V.FChecked <> -1
						AND V.IfCheck = 't'  
			 )
	BEGIN
		DECLARE BillMx_Cursor CURSOR FOR
			SELECT	LEFT(ISNULL(B.AscIds,''),LEN(ISNULL(B.AscIds,''))-1) AS Ascids,
					B.Fdc,
					ISNULL(SUM(B.FDebitTotal),0),
					ISNULL(SUM(B.FDebitTotalFor),0),
					ISNULL(SUM(B.FCreditTotal),0),
					ISNULL(SUM(B.FCreditTotalFor),0),
					ISNULL(SUM(B.FDebitQty),0),
					ISNULL(SUM(B.FCreditQty),0)				
			FROM	Ac_Voucher_Bill B
			INNER JOIN Ac_Voucher V ON B.BillNumberId = V.BillNumberId
			WHERE	B.STypeId = @STypeId 
					AND B.ATypeId = @ATypeId
					AND B.Cid = @Cid
					AND ISNULL(B.AscIds,'') <> ''
					AND V.FChecked <> -1
					AND V.IfCheck = 't'  
			GROUP BY B.AscIds,B.Fdc
		
		OPEN BillMx_Cursor 
		
		FETCH NEXT FROM BillMx_Cursor INTO  @GroupValue,
											@Fdc,
											@FDebitTotal,
											@FDebitTotalFor,
											@FCreditTotal,
											@FCreditTotalFor,
											@FDebitqty,
											@FCreditqty
		
		WHILE @@FETCH_STATUS = 0
		BEGIN			
			IF EXISTS(SELECT TOP 1 1 FROM @Ac_IniAccount_Assist_CheckItems_Detail WHERE iniGroupValue = @GroupValue AND Cid = @Cid AND STypeId = @STypeId AND ATypeId = @ATypeId)
			BEGIN
				UPDATE	@Ac_IniAccount_Assist_CheckItems_Detail
				SET		FDebitTotal += @FDebitTotal,
						FDebitTotalFor += @FDebitTotalFor,
						FCreditTotal += @FCreditTotal,
						FCreditTotalFor += @FCreditTotalFor,
						FEndBalance = FEndBalance + CASE WHEN @Fdc = 1 THEN @FDebitTotal - @FCreditTotal ELSE @FCreditTotal - @FDebitTotal END,
						FEndBalanceFor = FEndBalanceFor + CASE WHEN @Fdc = 1 THEN @FDebitTotalFor - @FCreditTotalFor ELSE @FCreditTotalFor - @FDebitTotalFor END,
						FDebitqty+=@FDebitqty,
						FCreditqty+=@FCreditqty,
						FEndBalanceqty=FEndBalanceqty+CASE WHEN @Fdc=1 THEN @FDebitqty-@FCreditqty ELSE @FCreditqty-@FDebitqty END
				WHERE	iniGroupValue = @GroupValue
						AND Cid = @Cid 
						AND STypeId = @STypeId 
						AND ATypeId = @ATypeId
			END
			ELSE
			BEGIN
				INSERT INTO @Ac_IniAccount_Assist_CheckItems_Detail
				(
					STypeId,
					ATypeId,
					Cid,
					IniYTotal,
					IniYTotalFor,
					IniTotal,
					IniTotalFor,
					iniGroupValue,
					FDebitTotal,
					FDebitTotalFor,
					FCreditTotal,
					FCreditTotalFor,
					FEndBalance,
					FEndBalanceFor,
					GroupId,
					IniYqty,
					Iniqty,
					FDebitqty,
					FCreditqty,
					FEndBalanceqty
				)VALUES(
					@STypeId,
					@ATypeId,
					@Cid,
					0,
					0,	
					0,
					0,
					@GroupValue,
					@FDebitTotal,
					@FDebitTotalFor,
					@FCreditTotal,
					@FCreditTotalFor,
					CASE WHEN @Fdc = 1 THEN @FDebitTotal - @FCreditTotal ELSE @FCreditTotal - @FDebitTotal END,
					CASE WHEN @Fdc = 1 THEN @FDebitTotalFor - @FCreditTotalFor ELSE @FCreditTotalFor - @FDebitTotalFor END,
					1,
					0,
					0,
					@FDebitqty,
					@FCreditqty,
					CASE WHEN @Fdc=1 THEN @FDebitqty-@FCreditqty ELSE @FCreditqty-@FDebitqty END
				)
			END

			FETCH NEXT FROM BillMx_Cursor INTO  @GroupValue,
												@Fdc,
												@FDebitTotal,
												@FDebitTotalFor,
												@FCreditTotal,
												@FCreditTotalFor,
												@FDebitqty,
											    @FCreditqty			
		END
		
		CLOSE BillMx_Cursor
		DEALLOCATE BillMx_Cursor
	END
	
		---重算本年累计
	IF @newFYear<>@iniFYear
		BEGIN
			--都先把第一期年结的本年累计设置为0
			UPDATE @Ac_IniAccount_Assist_CheckItems_Detail SET FDebitTotal=0,FDebitTotalFor=0,FCreditTotal=0,FCreditTotalFor=0 
			WHERE STypeId = @STypeId  AND ATypeId = @ATypeId  AND Cid = @Cid
			
			--如果第一期就是0，如果是后面的期数就又重算本年累计
			IF @newFperiod<>1
				BEGIN
						IF EXISTS(
						SELECT  TOP 1 1 
						FROM	Ac_Voucher_Bill B,Ac_Voucher V 
						WHERE	V.BillNumberId = B.BillNumberId 
								AND B.STypeId = @STypeId 
								AND B.ATypeId = @ATypeId 
								AND B.Cid = @Cid
								AND ISNULL(B.AscIds,'') <> ''
								AND V.FChecked <> -1
								AND V.IfCheck = 't'  
								AND B.FYear=@newFYear
				 )
					BEGIN
						DECLARE BillMx_Cursor1 CURSOR FOR
							SELECT	LEFT(ISNULL(B.AscIds,''),LEN(ISNULL(B.AscIds,''))-1) AS Ascids,
									B.Fdc,
									ISNULL(SUM(B.FDebitTotal),0),
									ISNULL(SUM(B.FDebitTotalFor),0),
									ISNULL(SUM(B.FCreditTotal),0),
									ISNULL(SUM(B.FCreditTotalFor),0),
									ISNULL(SUM(B.FDebitQty),0),
									ISNULL(SUM(B.FCreditQty),0)				
							FROM	Ac_Voucher_Bill B
							INNER JOIN Ac_Voucher V ON B.BillNumberId = V.BillNumberId
							WHERE	B.STypeId = @STypeId 
									AND B.ATypeId = @ATypeId
									AND B.Cid = @Cid
									AND V.FChecked <> -1
									AND V.IfCheck = 't'  
									AND B.FYear=@newFYear
							GROUP BY B.AscIds,B.Fdc 
						
						OPEN BillMx_Cursor1 
			
						FETCH NEXT FROM BillMx_Cursor1 INTO @GroupValue,
															@Fdc,
															@FDebitTotal,
															@FDebitTotalFor,
															@FCreditTotal,
															@FCreditTotalFor,
															@FDebitqty,
															@FCreditqty	
			
						WHILE @@FETCH_STATUS = 0
						BEGIN			
							IF EXISTS(SELECT TOP 1 1 FROM @Ac_IniAccount_Assist_CheckItems_Detail WHERE iniGroupValue = @GroupValue AND Cid = @Cid AND STypeId = @STypeId AND ATypeId = @ATypeId)
									UPDATE	@Ac_IniAccount_Assist_CheckItems_Detail
									SET		FDebitTotal += @FDebitTotal,
											FDebitTotalFor += @FDebitTotalFor,
											FCreditTotal += @FCreditTotal,
											FCreditTotalFor += @FCreditTotalFor,
											FDebitqty += @FDebitqty,
											FCreditqty += @FCreditqty
									WHERE	iniGroupValue = @GroupValue
											AND Cid = @Cid 
											AND STypeId = @STypeId 
											AND ATypeId = @ATypeId	
								
								FETCH NEXT FROM BillMx_Cursor1 INTO  @GroupValue,
													@Fdc,
													@FDebitTotal,
													@FDebitTotalFor,
													@FCreditTotal,
													@FCreditTotalFor,
													@FDebitqty,
											        @FCreditqty	
						END
													
						 CLOSE BillMx_Cursor1
						DEALLOCATE BillMx_Cursor1								
					 END 		 
					
				END
		END
	
	FETCH NEXT FROM Abc_Cursor INTO @STypeId,
									@ATypeId,
									@Cid
END

CLOSE Abc_Cursor
DEALLOCATE Abc_Cursor

--重算groupid
SELECT *,DENSE_RANK() OVER (PARTITION BY D.STypeId,D.ATypeId,D.Cid ORDER BY D.STypeId,D.ATypeId,D.Cid,iniGroupValue,FEndBalance) as  gpid 
INTO #Ac_IniAccount_Assist_CheckItems_Detail1
FROM @Ac_IniAccount_Assist_CheckItems_Detail  d  

  
--****************************************************************************清空期初数据，年结最终结果****************************************************************************--
TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems_Detail

DECLARE @iniGroupValue	VARCHAR(MAX),
		@Count			INT,
		@mxValue		VARCHAR(MAX),
		@OldSTypeId		VARCHAR(50),
		@OldATypeId		VARCHAR(50)
		
SET @OldSTypeId = ''
SET @OldATypeId = ''		
		
SET @Count = 1
		
DECLARE R_CURSOR CURSOR FOR
	SELECT STypeId,ATypeId,Cid,iniGroupValue,FDebitTotal,FDebitTotalFor,FCreditTotal,FCreditTotalFor,FEndBalance,FEndBalanceFor,FDebitqty,FCreditqty,FEndBalanceqty,gpid 
	FROM #Ac_IniAccount_Assist_CheckItems_Detail1
	
OPEN R_CURSOR

FETCH NEXT FROM R_CURSOR INTO @STypeId,@ATypeId,@Cid,@iniGroupValue,@FDebitTotal,@FDebitTotalFor,@FCreditTotal,@FCreditTotalFor,@FEndBalance,@FEndBalanceFor,@FDebitqty,@FCreditqty,@FEndBalanceqty,@GroupId

WHILE @@FETCH_STATUS = 0
BEGIN
	DECLARE RMX_CURSOR CURSOR FOR
		SELECT * FROM F_Split(@iniGroupValue,',')
		
	OPEN RMX_CURSOR
	
	FETCH NEXT FROM RMX_CURSOR INTO @mxValue
	
	WHILE @@FETCH_STATUS = 0
	BEGIN	
	
		IF EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE STypeId = @STypeId AND ATypeId = @ATypeId AND Cid = @Cid AND GroupId = @GroupId AND Ascids = LEFT(@mxValue,1) AND FieldValue = RIGHT(@mxValue,LEN(@mxValue)-2))
		BEGIN
			UPDATE Ac_IniAccount_Assist_CheckItems_Detail 
			SET	FDebit+=@FDebitTotal,
				FDebitFor+=@FDebitTotalFor,
				FCredit+=@FCreditTotal,
				FCreditFor+=@FCreditTotalFor,
				IniTotal+=@FEndBalance,
				IniTotalFor+=@FEndBalanceFor,
				FDebitqty+=@FDebitqty,
				FCreditqty+=@FCreditqty,
				iniqty+=@FEndBalanceqty
			WHERE STypeId = @STypeId 
				AND ATypeId = @ATypeId 
				AND Cid = @Cid 
				AND GroupId = @GroupId 
				AND Ascids = LEFT(@mxValue,1) 
				AND FieldValue = RIGHT(@mxValue,LEN(@mxValue)-2)
				
		END
		ELSE
		BEGIN
			INSERT INTO Ac_IniAccount_Assist_CheckItems_Detail
			(
				STypeId,
				ATypeId,
				Cid,
				Ascids,
				FieldValue,
				IniYTotal,
				IniYTotalFor,
				FDebit,
				FDebitFor,
				FCredit,
				FCreditFor,
				IniTotal,
				IniTotalFor,
				GroupId,
				FYear,
				FPeriod,
				IniYqty,
				iniqty,
				FDebitqty,
				FCreditqty
			)VALUES(
				@STypeId,
				@ATypeId,
				@Cid,
				LEFT(@mxValue,1),
				RIGHT(@mxValue,LEN(@mxValue)-2),
				0,
				0,
				@FDebitTotal,
				@FDebitTotalFor,
				@FCreditTotal,
				@FCreditTotalFor,
				@FEndBalance,
				@FEndBalanceFor,
				@GroupId,
				@newFYear,
				@newFPeriod,
				0,
				@FEndBalanceqty,
				@FDebitqty,
				@FCreditqty
			)		
		END
		
		
		FETCH NEXT FROM RMX_CURSOR INTO @mxValue
	END
	
	CLOSE RMX_CURSOR
	DEALLOCATE RMX_CURSOR
	
	SET @Count = @Count + 1
		
	FETCH NEXT FROM R_CURSOR INTO @STypeId,@ATypeId,@Cid,@iniGroupValue,@FDebitTotal,@FDebitTotalFor,@FCreditTotal,@FCreditTotalFor,@FEndBalance,@FEndBalanceFor,@FDebitqty,@FCreditqty,@FEndBalanceqty,@GroupId
END

CLOSE R_CURSOR
DEALLOCATE R_CURSOR

--更新年初
UPDATE ai SET iniYTotal=(CASE WHEN aa.Fdc=1 THEN iniTotal-FDebit+FCredit ELSE iniTotal+FDebit-FCredit END),
			  iniYTotalFor=(CASE WHEN aa.fdc=1 THEN iniTotalFor-FDebitFor+FCreditFor ELSE iniTotalFor+FDebitFor-FCreditFor END),
			  IniYqty=(CASE WHEN aa.Fdc=1 THEN iniqty-FDebitqty+FDebitqty ELSE iniqty+FDebitqty-FCreditqty END)
FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail ai
JOIN dbo.Ac_Account aa ON ai.STypeId=aa.StypeId AND ai.ATypeId=aa.TypeId 

--损益列
UPDATE ai SET FYTotal=IniTotal,FYTotalFor=IniTotalFor
	     --FDebit=(CASE WHEN Fdc=1 THEN FDebit-FCredit ELSE 0 END),
      -- FDebitFor=(CASE WHEN Fdc=1 THEN FDebitFor-FCreditFor ELSE 0 END),
      -- FCredit=(CASE WHEN Fdc=-1 THEN  FCredit-FDebit ELSE 0 END),
      -- FCreditFor=(CASE WHEN Fdc=-1 THEN FCreditFor-FDebitFor ELSE 0 END)
FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail ai
JOIN dbo.Ac_Account aa ON ai.STypeId=aa.StypeId AND ai.ATypeId=aa.TypeId AND aa.TypeId LIKE '00003%'

DROP TABLE #Ac_IniAccount_Assist_CheckItems_Detail1

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：谢吉康
--日期：2018-12-13
--描述：指定时间年结存处理
-------------------------------------------------------------------------
CREATE   PROCEDURE Gp_YearProc_DateTime
(
	@yearendmode							CHAR(1) = '1',		-- 1 - 按余额转期初；0 - 按单据转期初
	@delDraft								CHAR(1) = '1',		-- 1 - 删除草稿数据；0 - 不删除
	@delOrder								CHAR(1) = '1',		-- 1 - 删除定单数据；0 - 不删除
	@chrRecPrice							CHAR(1) = '0',		-- 1 - 删除商品最近进价；0 - 不删除
	@delEventLog							CHAR(1) = '0',		-- 1 - 清除操作日志；0 - 不清除
	@delEndOrder							CHAR(1) = '0',		-- 1 - 删除已完成订单；0 - 不删除
	@delPriceTrack							CHAR(1) = '0',		-- 1 - 清除价格跟踪信息；0 - 不清除
	@delmessage								CHAR(1) = '0',		-- 1 - 清除聊天记录；0 - 不清除
	@unfinishedinvoice						CHAR(1) = '1',		-- 1 - 保留未完成开票单据；0 - 不保留
	@chkcompleterequestbill					CHAR(1) = '1',		-- 1 - 清除已完成请购单；0 - 清除所有请购单
	@unfinishedposbill						CHAR(1) = '1',		-- 1 - 清除所有小票数据；0 - 清除已结转小票数据
	@carefinancedata						INT	,				-- 2 - 年结存后财务数据为空；1 - 结转当前财务数据；0 - 保持原来的判断
	@chrRecSalePrice					    CHAR(1) = '1',		-- 1 - 年结存清空最近售价；0 - 不清空最近售价
	@chrRecSTypeBuyPrice				    CHAR(1) = '1',		-- 1 - 年结存清除商品分支机构间最近进价：0 - 不清空商品分支机构间商品最近进价
	@chrRecSTypeSalePrice				    CHAR(1) = '1',		-- 1 - 年结存清除商品分支机构间最近售价：0 - 不清空商品分支机构间商品最近售价
	@chrSTypePriceTrack						CHAR(1) = '1',		-- 1 - 年结存清除分支机构间价格跟踪信息: 0 - 不清空分支机构间价格跟踪信息
	@chrStockAge							CHAR(1) = '0',		-- 1 - 关心库龄数据; 0 -不关心库龄数据
	@chrStock								CHAR(1) = '0',		-- 1 - 按照仓库结转期初库龄数据; 0 不转
	@chrStype								CHAR(1) = '0',		-- 1 - 按照分支机构结转期初库龄数据; 0 不转
	@chrGroup								CHAR(1) = '0',		-- 1 - 按照集团结转期初库龄数据; 0 不转
	@delstoporder							CHAR(1) = '0',		-- 1 - 清除中止订单;0清除中止订单
	@carryOverBillexcess					CHAR(1) = '0',		-- 1 - 业务单据超收超付及收付款单未结算完金额结转至期初应收应付减少单；0 - 不转
	@PhysicalComplete						CHAR(1) = '0',		-- 1 -结转未实物出入库完成的单据   0 不结转
	@clearCompleteAllotApply				CHAR,				--	 -是否清除已完成的调货申请单 0-不清除 1-清除
	@clearNoCompleteAllotApply				CHAR,				--	 -是否清除未完成的调货申请单 0-不清除 1-清除
	@clearCompleteGetBillApply              char,               --	 是否清除已完成的要货申请单 0-不清除 1-清除
	@clearNoCompleteGetBillApply            char,               --   是否清除未完成要货申请单 0-不清除 1-清除
    @clearnocompleteonshelves				CHAR(1) = '0',		--	 -是否清除未完成上架的单据 0-不清除 1-清除
    @clearnocompletepickandtransport		CHAR(1) = '0',		--   -是否清除未完成拣货/运输的单据 0-不清除 1-清除
	@OperatorId								VARCHAR(50),		--   -操作员ID
	@logid									INT=0,				--   -年结存日志记录ID
	@yearendDatetime						VARCHAR(20)			--   -年结存的日期		
)

AS
SET NOCOUNT ON

BEGIN TRAN YearProc
SAVE TRAN YearProcPoint

IF EXISTS (SELECT * FROM SysData WHERE SubName = 'inicanmodify' and SubValue = 'T')
BEGIN
	ROLLBACK TRAN YearProcPoint
	COMMIT TRAN YearProc
	RETURN -2
END
IF EXISTS  (SELECT  * FROM dbo.SysObjects WHERE ID = object_id(N'[Cost_NoRelog]') AND OBJECTPROPERTY(ID, 'IsTable') = 1) 
BEGIN
	TRUNCATE TABLE Cost_NoRelog    -- 成本计算日志
END	

--构建操作明细信息
IF @logid>0
BEGIN
	EXEC Gp_YearProc_DateTime_Log 	@yearendmode,@chkcompleterequestbill,@carefinancedata,@delDraft,@delOrder,@delEndOrder,@chrRecPrice,@delPriceTrack,@delEventLog,@delmessage,
									@unfinishedinvoice,@chrRecSalePrice,@chrRecSTypeBuyPrice,@chrRecSTypeSalePrice,@chrSTypePriceTrack,@unfinishedposbill,@chrStockAge,@chrStock,@chrStype,
									@chrGroup,@delstoporder,@carryOverBillexcess,@clearCompleteAllotApply,@clearNoCompleteAllotApply,@clearCompleteGetBillApply,@clearNoCompleteGetBillApply,@clearnocompleteonshelves,@clearnocompletepickandtransport,@logid
END

--处理订单库存ReachQTY
EXEC Gp_YearProc_DateTime_Recount_ReachQty @yearendDatetime

--重算AType_Total
EXEC Gp_YearProc_DateTime_ReCal_AType_Total @yearendDatetime

--内部应收
EXEC GP_DateTime_Stype_InnerARTotal @yearendDatetime	
	
--按单结算并且选择超收超付结转为期初收付款单
IF @yearendmode=0 AND @carryOverBillexcess=1
BEGIN
	EXEC Gp_YearProc_DateTime_CarryOverToIniBill
END
	
--重算BType_ArapTotal
EXEC Gp_YearProc_DateTime_ReCal_BType_ArApTotal @yearendmode,@yearendDatetime	

--重算往来期初的数据 最后重算 IniBType_ArApTotal
IF  @yearendmode=1
BEGIN 
	EXEC Gp_ReCalIniBtypeARAPTotal_DateTime @yearendmode, @yearendDatetime
END 	
	
--库存相关
EXEC Gp_YearProc_DateTime_ReCal_Stocks  @chrStockAge,@chrStock,@chrStype,@chrGroup,@OperatorId,@yearendDatetime

--直接绕开负库存判断 谢吉康 991 2020-01-16
IF 1 = 0
BEGIN
	--验证库存负数情况
	IF (EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'allownegativestock' AND SubValue = 0) AND EXISTS(SELECT TOP 1 1 FROM dbo.IniGoodsStocks WHERE Qty < 0))
	BEGIN
		ROLLBACK TRAN YearProcPoint
		COMMIT TRAN YearProc
		RETURN -3
	END 
	--验证实物库存负数情况
	IF (EXISTS(SELECT TOP 1 1 FROM userconfig WHERE ConfigName = 'physicalsstocknegativestock' AND Value = 0) AND EXISTS(SELECT TOP 1 1 FROM dbo.IniFactStocks WHERE qty <0))
	BEGIN
		ROLLBACK TRAN YearProcPoint
		COMMIT TRAN YearProc
		RETURN -4
	END 
	--验证维修库存负数情况
	IF EXISTS(SELECT TOP 1 1 FROM dbo.wx_IniGoodsStocks WHERE qty <0)
	BEGIN
		ROLLBACK TRAN YearProcPoint
		COMMIT TRAN YearProc
		RETURN -5
	END 
END
	
--序列号
EXEC Gp_YearProc_DateTime_YearProcSerialDeal  @yearendDatetime	

--会员卡余额相关
EXEC Gp_YearProc_DateTime_VipCard @yearendDatetime

--优惠券
EXEC Gp_YearProc_DateTime_Coupon @yearendDatetime
	
--其他信息处理
DELETE FROM dbo.PriceTrack WHERE BuyOrderPrice=NULL AND SaleOrderPrice=NULL AND CostPrice=NULL AND QueryPrice=NULL AND SalePrice=NULL AND ResponsePrice = NULL AND Discount=NULL 

--删单据主表和明细
EXEC Gp_YearProc_DateTime_YearProcDeleteBill	@yearendmode,@DelDraft,@unfinishedinvoice,@chkcompleterequestbill,@unfinishedposbill,@PhysicalComplete,@carryOverBillexcess,@delOrder,
												@clearCompleteAllotApply,@clearNoCompleteAllotApply,@clearnocompleteonshelves,@clearnocompletepickandtransport,@delstoporder,@delEndOrder,@yearendDatetime,@clearCompleteGetBillApply,@clearNoCompleteGetBillApply	

			  
--单据结转时，重新算往来期初余额 此版本不处理按单据结转的
IF @yearendmode=0
BEGIN
	EXEC dbo.Gp_YearProc_DateTime_IniToArApTotal @stypeid = '%'
END		


	
--清除业绩分配明细
EXEC Gp_YearProc_DateTime_PerformanceDistribution
		
--清除单据操作日志
EXEC Gp_YearProc_DateTime_BillOperateLog
	
--处理发票
EXEC Gp_YearProc_DateTime_FaPiao @yearendDatetime
	 
--清除打印相关及附件相关
EXEC Gp_YearProc_DateTime_PrintAndAttachFiles	
	
--清除单据种子
EXEC Gp_YearProc_DateTime_BillCode_Seed_ReBuild

--成本重算历史表	
EXEC Gp_YearProc_DateTime_OldBill_Clone_Del

--处理审核和价格跟踪信息
EXEC Gp_YearProc_DateTime_DealAuditAndPrice @delDraft,@delOrder,@chrRecPrice,@chrRecSalePrice,@chrRecSTypeBuyPrice,@chrRecSTypeSalePrice,@chrSTypePriceTrack,@delPriceTrack,@yearendDatetime
	
--调用总账的年结存
DECLARE	@Re	INT,@rValue	VARCHAR(400)
EXEC @Re = P_MF_YearProc_DateTime @delDraft,@carefinancedata,@OperatorId,@yearendDatetime,@rValue OUTPUT
IF @Re <> 0
BEGIN
	GOTO ERROR
END	

--处理业务和财务期间
EXEC Gp_YearProc_DateTime_Deal_MonthProc_SType_UserConfig @yearendDatetime
	
--期初应收应付单据编号，单据日期----------------------------
EXEC Gp_YearProc_DateTime_Deal_iniArApBillCode @yearendDatetime
	
--删除停用的操作员
TRUNCATE TABLE dbo.FrozeBusiness
DELETE FROM LoginUser WHERE ETypeID IN (SELECT	TypeID FROM	Employee WHERE	Deleted = 1 AND SonNum = 0)	

--删除单据的触发器处理
EXEC Gp_YearProc_DeleteBill_Trigger	

--系统年结存后，重算草稿库存
EXEC QP_Recount_DraftQty

 --系统重建，重算订单库存
DECLARE @FLAG INT =1
EXEC QP_Recount_OrderQty @FLAG

--系统重建，清除部分pos相关的数据
EXEC QP_Clear_PosData

--店账通单据的处理
DELETE FROM EshopBillRelation WHERE BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)

--删除电子面单
DELETE FROM BillExpressage WHERE VchCode NOT IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 11)

--删除WMS对应数据    
DELETE FROM WMS_ERPBillRelation WHERE ERP_BillNumberId NOT IN (SELECT BillNumberId FROM BillIndex)

IF @delEventLog = '1'
BEGIN
	DELETE FROM dbo.EventLog WHERE Id<>@logid --DELETE FROM EventLog --清掉操作日志表
END

IF @delmessage='1'
BEGIN
	TRUNCATE TABLE IM_Message_NoSocket
	TRUNCATE TABLE IM_Message_NoSocket_Bak
END	
--删除listtalbe数据
DELETE FROM dbo.ListTable WHERE BillDate < @yearendDatetime

COMMIT TRAN YearProc
RETURN 0

ERROR:	
	ROLLBACK TRAN YearProcPoint
	COMMIT TRAN YearProc
	RETURN -1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_Ac_Balance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_Ac_Balance]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-05-08
	描述：年结处理会计凭证余额
*/
CREATE PROCEDURE Gp_YearProc_DateTime_Ac_Balance
(
	@delDraft		CHAR(1) = '1',			-- 是否清除草稿
	@yearendDatetime		VARCHAR(20),			--   -年结存的日期	
	@rValue			VARCHAR(400) OUTPUT		-- 输出信息	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @oldFYear		VARCHAR(10),			-- 年结前的会计年度
		@oldFPeriod		INT,					-- 年结前的财务期间
		@newFYear		VARCHAR(10),			-- 年结后的会计年度
		@newFPeriod		INT						-- 年结后的财务期间

SELECT @newFPeriod = FPeriod,@newFYear = FYear FROM dbo.Ac_Period WHERE FBegin = @yearendDatetime
SELECT @oldFPeriod = FPeriod,@oldFYear = FYear FROM dbo.Ac_Period WHERE FEnd = DATEADD(DAY,-1,@yearendDatetime)

--本币
DECLARE @Cid INT
SELECT	TOP 1
		@Cid = Cid
FROM	Ac_Currency
WHERE	Sysrow = 1		

DELETE FROM Ac_IniAccount WHERE FYTotal=0 AND FYTotalFor=0 AND FYTotalDebit=0 AND FYTotalDebitFor=0 AND FYTotalCredit=0 AND FYTotalCreditFor=0

CREATE TABLE #FYTotal
(
	stypeid	VARCHAR(50)
	,atypeid	VARCHAR(50)
	,cid	INT
	,FYTotal	NUMERIC(24,10)
	,FYTotalFor	NUMERIC(24,10)
	,FYTotalDebit	NUMERIC(24,10)
	,FYTotalDebitFor	NUMERIC(24,10)
	,FYTotalCredit	NUMERIC(24,10)
	,FYTotalCreditFor	NUMERIC(24,10)
)
INSERT INTO #FYTotal
(
	stypeid
	,atypeid
	,cid
	,FYTotal
	,FYTotalFor
	,FYTotalDebit
	,FYTotalDebitFor
	,FYTotalCredit
	,FYTotalCreditFor
)
SELECT	STypeId
		,ATypeId
		,Cid
		,CASE WHEN FYear = @newFYear THEN FYTotal ELSE 0 END AS FYTotal
		,CASE WHEN FYear = @newFYear THEN FYTotalFor ELSE 0 END AS FYTotalFor
		,0 AS FYTotalDebit
		,0 AS FYTotalDebitFor
		,0 AS FYTotalCredit
		,0 AS FYTotalCreditFor
FROM Ac_IniAccount
UNION ALL
SELECT	vb.STypeId
		,ATypeId
		,Cid
		,0
		,0
		,vb.FDebitTotal
		,vb.FDebitTotalFor
		,vb.FCreditTotal
		,vb.FCreditTotalFor		
FROM Ac_Voucher_Bill VB
INNER JOIN	Ac_Voucher V ON V.BillNumberId = VB.BillNumberId
--INNER JOIN	Ac_Account A ON A.StypeId = VB.STypeId AND A.TypeId = VB.ATypeId
WHERE	V.IfCheck = 't'
	AND	V.VoucherType !=2
	AND	V.RedWord = 0
	AND VB.ATypeId LIKE '00003%'
	AND V.FYear = @newFYear
	
--先清空期初数据
TRUNCATE TABLE Ac_IniAccount

--清空余额表中余额为0的科目 add by dongzhan 9.2version
IF @oldFYear<>@newFYear
BEGIN
	DELETE FROM dbo.Ac_Balance WHERE FEndBalance=0 AND FEndBalanceFor=0 AND FEndqty=0 AND FYear = @oldFYear AND FPeriod = @oldFPeriod
	DELETE FROM dbo.Ac_Balance_Assist_CheckItems WHERE FEndBalance=0 AND FEndBalanceFor=0 AND FYear = @oldFYear AND FPeriod = @oldFPeriod
	DELETE FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE FEndBalance=0 AND FEndBalanceFor=0 AND FEndqty=0 AND FYear = @oldFYear AND FPeriod = @oldFPeriod
END

--写入科目余额表
INSERT INTO Ac_IniAccount 
(
	STypeId, 
	ATypeId, 
	iniYTotal, 
	iniYTotalFor, 
	FDebit, 
	FDebitFor, 
	FCredit, 
	FCreditFor, 
	iniTotal, 
	iniTotalFor, 
	iniqty,
	FDebitqty,
	FCreditqty,
	IniYqty,
	Cid,
	FYear,
	FPeriod
	,FYTotal
	,FYTotalFor
)
SELECT	STypeId, 
		ATypeId, 
		0,
		0,
		ISNULL(SUM(FYtdDebit),0), 
		ISNULL(SUM(FYtdDebitFor),0), 
		ISNULL(SUM(FYtdCredit),0), 
		ISNULL(SUM(FYtdCreditFor),0),
		ISNULL(SUM(FEndBalance),0) AS iniTotal, 
		ISNULL(SUM(FEndBalanceFor),0) AS iniTotalFor,
		ISNULL(SUM(FEndqty),0) AS iniqty,
		ISNULL(SUM(FYtdDebitqty),0) AS FDebitqty,
		ISNULL(SUM(FYtdCreditqty),0) AS FCreditqty,
		0,	
		Cid,
		@newFYear AS FYear,
		@newFPeriod AS FPeriod
		,SUM(FYTotal)
		,SUM(FYTotalFor)
FROM	(
	SELECT	STypeId
			,ATypeId
			,FYtdDebit
			,FYtdDebitFor
			,FYtdCredit
			,FYtdCreditFor
			,FEndBalance
			,FEndBalanceFor
			,FEndqty
			,FYtdDebitqty
			,FYtdCreditqty
			,Cid
			,0 AS FYTotal
			,0 AS FYTotalFor
	FROM	Ac_Balance
	WHERE	Cid <> 0
		AND FYear = @oldFYear
		AND FPeriod = @oldFPeriod
	UNION ALL
	SELECT	F.stypeid
			,F.atypeid
			,0
			,0
			,0
			,0
			,0
			,0
			,0
			,0
			,0
			,F.cid
			,CASE WHEN A.Fdc = 1 THEN F.FYTotal + F.FYTotalDebit - F.FYTotalCredit ELSE  F.FYTotal - F.FYTotalDebit + F.FYTotalCredit END
			,CASE WHEN A.Fdc = 1 THEN F.FYTotalFor + F.FYTotalDebitFor - F.FYTotalCreditFor ELSE  F.FYTotalFor - F.FYTotalDebitFor + F.FYTotalCreditFor END
	FROM #FYTotal F
	INNER JOIN Ac_Account A ON A.StypeId = F.stypeid AND A.TypeId = F.atypeid
	) T
GROUP BY STypeId,
		 ATypeId,
		 Cid

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -1
END

------结转辅助核算明细表数据
--备注：因为辅助核算明细表的余额表里面没有分组，而期初表是需要分组的，所以不能直接从辅助核算明细余额表取数据转入期初表，只能统计所有凭证明细

--跨年数据，清除Ac_IniAccount_Assist_CheckItems_Detail表中期初为0的数据
DELETE FROM Ac_IniAccount_Assist_CheckItems_Detail WHERE FYear <> @newFYear AND IniTotal = 0 AND IniTotalFor = 0

DECLARE @STypeId			VARCHAR(50),
		@ATypeId			VARCHAR(50),
		@Cid_Detail				INT,
		@IniYTotal			 NUMERIC(24, 10) ,
		@IniYTotalFor		 NUMERIC(24, 10) ,
		@IniTotal			 NUMERIC(24, 10) ,
		@IniTotalFor		 NUMERIC(24, 10) ,
		@FDebitTotal		 NUMERIC(24, 10) ,
		@FDebitTotalFor		 NUMERIC(24, 10) ,
		@FCreditTotal		 NUMERIC(24, 10) ,
		@FCreditTotalFor	 NUMERIC(24, 10) ,
		@FEndBalance		 NUMERIC(24, 10) ,
		@FEndBalanceFor		 NUMERIC(24, 10) ,
		@GroupValue			VARCHAR(MAX),
		@Ascids				VARCHAR(10),
  		@FieldValue			VARCHAR(50),
  		@Fdc				INT,
  		@GroupId			INT,
  		@IniYqty             NUMERIC(24, 10) ,
		@Iniqty         NUMERIC(24, 10) ,
		@FDebitqty      NUMERIC(24, 10) ,
		@FCreditqty     NUMERIC(24, 10) ,
		@FEndBalanceqty	     NUMERIC(24, 10) ,
		@FYTotal     NUMERIC(24, 10) ,
		@FYTotalFor	     NUMERIC(24, 10),
		@FYear			INT 
  		 

CREATE TABLE #Ac_IniAccount_Assist_CheckItems_Detail		
(
	STypeId			VARCHAR(50),
	ATypeId			VARCHAR(50),
	Cid				INT,
	IniYTotal		 NUMERIC(24, 10)  DEFAULT(0),
	IniYTotalFor	 NUMERIC(24, 10)  DEFAULT(0),
	IniTotal		 NUMERIC(24, 10)  DEFAULT(0),
	IniTotalFor		 NUMERIC(24, 10)  DEFAULT(0),
	FDebitTotal		 NUMERIC(24, 10)  DEFAULT(0),
	FDebitTotalFor	 NUMERIC(24, 10)  DEFAULT(0),
	FCreditTotal	 NUMERIC(24, 10)  DEFAULT(0),
	FCreditTotalFor	 NUMERIC(24, 10)  DEFAULT(0),	
	FEndBalance		 NUMERIC(24, 10)  DEFAULT(0),	
	FEndBalanceFor	 NUMERIC(24, 10)  DEFAULT(0),	
	iniGroupValue	VARCHAR(MAX)  DEFAULT(''),
	--GroupId			INT,
	IniYqty          NUMERIC(24, 10)  DEFAULT(0),
	Iniqty           NUMERIC(24, 10)  DEFAULT(0),
	FDebitqty        NUMERIC(24, 10)  DEFAULT(0),
	FCreditqty       NUMERIC(24, 10)  DEFAULT(0),
	FEndBalanceqty   NUMERIC(24, 10)  DEFAULT(0),
	FYTotal        NUMERIC(24, 10)  DEFAULT(0),
	FYTotalFor       NUMERIC(24, 10)  DEFAULT(0),
	FYear			INT
)
CREATE NONCLUSTERED INDEX CIX_Ac_IniAccount_Assist_CheckItems_Detail_INDEX ON #Ac_IniAccount_Assist_CheckItems_Detail(STypeId,ATypeId,Cid)

INSERT	INTO #Ac_IniAccount_Assist_CheckItems_Detail
(
	STypeId,
	ATypeId,
	Cid,
	IniYTotal,
	IniYTotalFor,
	IniTotal,
	IniTotalFor,
	iniGroupValue,
	FDebitTotal,
	FDebitTotalFor,
	FCreditTotal,
	FCreditTotalFor,
	FEndBalance,
	FEndBalanceFor,
	IniYqty,
	Iniqty,
	FDebitqty,
	FCreditqty,
	FEndBalanceqty,
	FYTotal,
	FYTotalFor,
	FYear
)		
SELECT  DISTINCT
		stypeid,
		atypeid,
		cid,
		IniYTotal,	
		IniYTotalFor,
		IniTotal,
		IniTotalFor,			
		iniGroupValue = STUFF((
			SELECT	','+CAST(Ascids AS varchar) + ':' + fieldvalue 
			FROM	Ac_IniAccount_Assist_CheckItems_Detail
			WHERE	stypeid = a.stypeid
					AND atypeid = a.atypeid
					AND cid = a.cid
					AND groupid = a.groupid
			FOR XML PATH('')
		),1,1,''),
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		IniTotal,
		IniTotalFor,
		IniYqty,
		Iniqty,
		FDebitqty,
		FCreditqty,
		iniqty,
		FYTotal,
		FYTotalFor,
		FYear
FROM	Ac_IniAccount_Assist_CheckItems_Detail a

--统计凭证明细数据
CREATE TABLE #voucher_Assist_CheckItems_Detail
(
	stypeid	VARCHAR(50)
	,atypeid	VARCHAR(50)
	,cid	INT
	,ascids	VARCHAR(1000)
	,FDebit	NUMERIC(24,10)
	,FDebitFor	NUMERIC(24,10)
	,FCredit	NUMERIC(24,10)
	,FCreditFor	NUMERIC(24,10)
	,FDebitQty	NUMERIC(24,10)
	,FCreditQty	NUMERIC(24,10)
	,FYDebit	NUMERIC(24,10)
	,FYDebitFor	NUMERIC(24,10)
	,FYCredit	NUMERIC(24,10)
	,FYCreditFor	NUMERIC(24,10)
	,FYDebitQty	NUMERIC(24,10)
	,FYCreditQty	NUMERIC(24,10)
	,FYTotal	NUMERIC(24,10)
	,FYTotalFor	NUMERIC(24,10)
)
INSERT INTO #voucher_Assist_CheckItems_Detail
(
	stypeid
	,atypeid
	,cid
	,ascids
	,FDebit
	,FDebitFor
	,FCredit
	,FCreditFor
	,FDebitQty
	,FCreditQty
	,FYDebit
	,FYDebitFor
	,FYCredit
	,FYCreditFor
	,FYDebitQty
	,FYCreditQty
	,FYTotal
	,FYTotalFor
)
SELECT	b.STypeId,
		b.ATypeId,
		b.Cid,
		LEFT(ISNULL(B.AscIds,''),LEN(ISNULL(B.AscIds,''))-1) AS Ascids,
		B.FDebitTotal,
		B.FDebitTotalFor,
		B.FCreditTotal,
		B.FCreditTotalFor,
		B.FDebitQty,
		B.FCreditQty
		,CASE WHEN B.FYear = @newFYear THEN B.FDebitTotal ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FDebitTotalFor ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FCreditTotal ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FCreditTotalFor ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FDebitQty ELSE 0 END
		,CASE WHEN B.FYear = @newFYear THEN B.FCreditQty ELSE 0 END		
		,CASE WHEN B.FYear = @newFYear AND v.VoucherType <> 2 AND LEFT(B.ATYPEID,5) = '00003' THEN B.FDebitTotal - B.FCreditTotal ELSE 0 END
		,CASE WHEN B.FYear = @newFYear AND v.VoucherType <> 2 AND LEFT(B.ATYPEID,5) = '00003' THEN B.FDebitTotalFor - B.FCreditTotalFor ELSE 0 END		
FROM	Ac_Voucher_Bill B
INNER JOIN Ac_Voucher V ON B.BillNumberId = V.BillNumberId
WHERE	ISNULL(B.AscIds,'') <> ''
		AND V.FChecked <> -1
		AND V.IfCheck = 't'  
		AND v.BillDate < @yearendDatetime

SELECT T1.*,DENSE_RANK() OVER (PARTITION BY T1.STypeId,T1.ATypeId,T1.Cid ORDER BY T1.STypeId,T1.ATypeId,T1.Cid,T1.ascids,T1.FEndBalance) as  gpid 
INTO #Ac_IniAccount_Assist_CheckItems_Detail1
FROM(
		SELECT	STypeId,
				ATypeId,
				Cid,
				ascids,
				SUM(IniYTotal) AS IniYTotal,
				SUM(IniYTotalFor) AS IniYTotalFor,
				SUM(IniTotal) AS IniTotal,
				SUM(IniTotalFor) AS IniTotalFor,
				SUM(FDebitTotal) AS FDebitTotal,
				SUM(FDebitTotalFor) AS FDebitTotalFor,
				SUM(FCreditTotal) AS FCreditTotal,
				SUM(FCreditTotalFor) AS FCreditTotalFor,
				SUM(FEndBalance) AS FEndBalance,
				SUM(FEndBalanceFor) AS FEndBalanceFor,
				SUM(IniYqty) AS IniYqty,
				SUM(Iniqty) AS Iniqty,
				SUM(FDebitqty) AS FDebitqty,
				SUM(FCreditqty) AS FCreditqty,
				SUM(FEndBalanceqty) AS FEndBalanceqty,
				SUM(FYTotal) AS FYTotal,
				SUM(FYTotalFor) AS FYTotalFor
		FROM	(
				SELECT	STypeId,
						ATypeId,
						Cid,
						iniGroupValue AS ascids,
						IniYTotal,
						IniYTotalFor,
						IniTotal,
						IniTotalFor,
						CASE WHEN FYear = @newFYear THEN FDebitTotal ELSE 0 END AS FDebitTotal,
						CASE WHEN FYear = @newFYear THEN FDebitTotalFor ELSE 0 END AS FDebitTotalFor,
						CASE WHEN FYear = @newFYear THEN FCreditTotal ELSE 0 END AS FCreditTotal,
						CASE WHEN FYear = @newFYear THEN FCreditTotalFor ELSE 0 END AS FCreditTotalFor,
						FEndBalance,
						FEndBalanceFor,
						--GroupId,
						IniYqty,
						Iniqty,
						FDebitqty,
						FCreditqty,
						FEndBalanceqty,
						CASE WHEN FYear = @newFYear THEN FYTotal ELSE 0 END AS FYTotal,
						CASE WHEN FYear = @newFYear THEN FYTotalFor ELSE 0 END AS FYTotalFor
				FROM	#Ac_IniAccount_Assist_CheckItems_Detail
				UNION ALL
				SELECT	B.stypeid,
						B.ATypeId,
						B.Cid,
						B.ascids,
						0,
						0,
						0,
						0,
						B.FYDebit,
						B.FYDebitFor,
						B.FYCredit,
						b.FYCreditFor,
						A.Fdc*(FDebit - FCredit),
						A.Fdc*(FDebitFor - FCreditFor),
						--GroupId,
						0,
						0,
						B.FYDebitQty,
						B.FYCreditQty,
						A.Fdc*(FDebitqty-FCreditqty),
						A.Fdc*FYTotal,
						A.Fdc*FYTotalFor
				FROM	#voucher_Assist_CheckItems_Detail B
				INNER JOIN	Ac_Account A ON A.StypeId =B.stypeid AND A.TypeId = B.atypeid

				) T
				GROUP BY STypeId,ATypeId,Cid,ascids
		) T1


--先清空期初数据
TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems_Detail

DECLARE @iniGroupValue	VARCHAR(MAX),
		@mxValue		VARCHAR(MAX)	
		
		
DECLARE R_CURSOR CURSOR FOR
	SELECT	STypeId,ATypeId,Cid,ascids,FDebitTotal,FDebitTotalFor,FCreditTotal,FCreditTotalFor
			,FEndBalance,FEndBalanceFor,FDebitqty,FCreditqty,FEndBalanceqty,gpid 
			,FYTotal,FYTotalFor
	FROM #Ac_IniAccount_Assist_CheckItems_Detail1
	
OPEN R_CURSOR

FETCH NEXT FROM R_CURSOR INTO @STypeId,@ATypeId,@cid_detail,@iniGroupValue,@FDebitTotal,@FDebitTotalFor,@FCreditTotal,@FCreditTotalFor
								,@FEndBalance,@FEndBalanceFor,@FDebitqty,@FCreditqty,@FEndBalanceqty,@GroupId
								,@FYTotal,@FYTotalFor

WHILE @@FETCH_STATUS = 0
BEGIN		
	INSERT INTO Ac_IniAccount_Assist_CheckItems_Detail
	(
		STypeId,
		ATypeId,
		Cid,
		Ascids,
		FieldValue,
		IniYTotal,
		IniYTotalFor,
		FDebit,
		FDebitFor,
		FCredit,
		FCreditFor,
		IniTotal,
		IniTotalFor,
		GroupId,
		FYear,
		FPeriod,
		IniYqty,
		iniqty,
		FDebitqty,
		FCreditqty
		,FYTotal
		,FYTotalFor
	)
	SELECT	
			@STypeId,
			@ATypeId,
			@Cid_Detail,
			LEFT(a,1),
			RIGHT(a,LEN(a)-2),
			0,
			0,
			@FDebitTotal,
			@FDebitTotalFor,
			@FCreditTotal,
			@FCreditTotalFor,
			@FEndBalance,
			@FEndBalanceFor,
			@GroupId,
			@newFYear,
			@newFPeriod,
			0,
			@FEndBalanceqty,
			@FDebitqty,
			@FCreditqty,
			@FYTotal,
			@FYTotalFor
	FROM	dbo.f_split(@iniGroupValue,',')
		
	FETCH NEXT FROM R_CURSOR INTO @STypeId,@ATypeId,@Cid_Detail,@iniGroupValue,@FDebitTotal,@FDebitTotalFor,@FCreditTotal,@FCreditTotalFor
									,@FEndBalance,@FEndBalanceFor,@FDebitqty,@FCreditqty,@FEndBalanceqty,@GroupId
									,@FYTotal,@FYTotalFor
END

CLOSE R_CURSOR
DEALLOCATE R_CURSOR


IF @newFPeriod = 1
BEGIN
	UPDATE Ac_IniAccount SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0
	UPDATE Ac_IniAccount_Assist_CheckItems_Detail SET FDebit=0,FDebitFor=0,FDebitqty=0,FCredit=0,FCreditFor=0,FCreditqty=0
END

--更新年初
UPDATE ai SET iniYTotal=(CASE WHEN aa.Fdc=1 THEN iniTotal-FDebit+FCredit ELSE iniTotal+FDebit-FCredit END),
			  iniYTotalFor=(CASE WHEN aa.fdc=1 THEN iniTotalFor-FDebitFor+FCreditFor ELSE iniTotalFor+FDebitFor-FCreditFor END),
			  IniYqty=(CASE WHEN aa.Fdc=1 THEN iniqty-FDebitqty+FCreditqty ELSE iniqty+FDebitqty-FCreditqty END)
FROM dbo.Ac_IniAccount ai
JOIN dbo.Ac_Account aa ON ai.STypeId=aa.StypeId AND ai.ATypeId=aa.TypeId

--更新年初
UPDATE ai SET iniYTotal=(CASE WHEN aa.Fdc=1 THEN iniTotal-FDebit+FCredit ELSE iniTotal+FDebit-FCredit END),
			  iniYTotalFor=(CASE WHEN aa.fdc=1 THEN iniTotalFor-FDebitFor+FCreditFor ELSE iniTotalFor+FDebitFor-FCreditFor END),
			  IniYqty=(CASE WHEN aa.Fdc=1 THEN iniqty-FDebitqty+FDebitqty ELSE iniqty+FDebitqty-FCreditqty END)
FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail ai
JOIN dbo.Ac_Account aa ON ai.STypeId=aa.StypeId AND ai.ATypeId=aa.TypeId 


DROP TABLE #Ac_IniAccount_Assist_CheckItems_Detail1,#voucher_Assist_CheckItems_Detail
------结转辅助核算明细表数据end


TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems

--从主表转移辅助核算类科目
INSERT INTO Ac_IniAccount_Assist_CheckItems
(
	STypeId, 
	ATypeId, 
	Cid, 
	IniYTotal, 
	IniYTotalFor, 
	FDebit, 
	FCredit, 	
	FDebitFor, 
	FCreditFor,	
	IniTotal, 	
	IniTotalFor,
	FYear,
	FPeriod,
	IniYqty,
	Iniqty,
	FDebitqty,
	FCreditqty
	,FYTotal
	,FYTotalFor
)
SELECT  A.STypeId, 
		A.ATypeId, 
		Cid, 
		IniYTotal, 
		IniYTotalFor, 
		FDebit, 
		FCredit, 	
		FDebitFor, 
		FCreditFor,	
		IniTotal, 	
		IniTotalFor,
		FYear,
		FPeriod,
		IniYqty,
		Iniqty,
		FDebitqty,
		FCreditqty
		,FYTotal
		,FYTotalFor
FROM	Ac_IniAccount A
INNER JOIN	(SELECT STypeId,ATypeId FROM Ac_Account_Assist_CheckItems GROUP BY STypeId,ATypeId) T ON T.STypeId = A.STypeId AND T.ATypeId = A.ATypeId
WHERE A.Cid <> 0

IF @@ERROR <> 0
BEGIN
	SET @rValue = @@ERROR
	RETURN -1
END

--清除异常数据
--清除科目已经被删除但是年结后期初表还有数据的记录 (年结后开账遇到的bug)
DELETE A FROM Ac_IniAccount A
WHERE NOT  EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE STypeId= A.STypeId AND TypeId=A.ATypeId)

DELETE A FROM dbo.Ac_IniAccount_Assist_CheckItems A
WHERE NOT  EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE STypeId= A.STypeId AND TypeId=A.ATypeId)

DELETE A FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail A
WHERE NOT  EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE STypeId= A.STypeId AND TypeId=A.ATypeId)

--清除辅助核算明细表中已经不是辅助核算科目的记录
DELETE A FROM Ac_IniAccount_Assist_CheckItems_Detail A 
WHERE NOT EXISTS (SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems B WHERE B.STYPEID = A.STYPEID AND B.ATYPEID = A.ATYPEID)

--清除数据为0的记录，因为存在辅助核算明细数据不为0，但合计后为0的情况，所以先清除辅助核算明细表的数据，在清除其他两个表
DELETE FROM Ac_IniAccount_Assist_CheckItems_Detail  
WHERE iniYTotal=0 AND iniYTotalFor=0 AND FDebit=0 AND FDebitFor=0 AND FCredit=0 AND FCreditFor=0 AND iniTotal=0 AND iniTotalFor=0 AND FYTotal=0 AND FYTotalFor=0

DELETE I FROM Ac_IniAccount I
WHERE iniYTotal=0 AND iniYTotalFor=0 AND FDebit=0 AND FDebitFor=0 AND FCredit=0 AND FCreditFor=0 AND iniTotal=0 AND iniTotalFor=0 AND FYTotal=0 AND FYTotalFor=0
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail III WHERE III.STypeId = I.STypeId AND III.ATypeId = I.ATypeId AND III.Cid = I.Cid)

DELETE I FROM Ac_IniAccount_Assist_CheckItems  I
WHERE NOT EXISTS(SELECT TOP 1 1 FROM Ac_IniAccount_Assist_CheckItems_Detail III WHERE III.STypeId = I.STypeId AND III.ATypeId = I.ATypeId AND III.Cid = I.Cid)

DROP TABLE #Ac_IniAccount_Assist_CheckItems_Detail


RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_BillCode_Seed_ReBuild]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_BillCode_Seed_ReBuild]
GO


/*
	作者：冯波
	日期：2010-04-08
	描述：系统重建或年结存时清除种子数
*/
CREATE       PROCEDURE Gp_YearProc_DateTime_BillCode_Seed_ReBuild

--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	IF NOT EXISTS(
		SELECT BillNumberID FROM BillIndex
		UNION ALL
		SELECT BillNumberID FROM OrderIndex
		UNION ALL
		SELECT StockCheckID FROM StockCheckIndex
		UNION ALL
		SELECT BillNumberId FROM LendIndex
		UNION ALL
		SELECT BillNumberID FROM FaPiaoBillIndex
		UNION ALL
		SELECT BillnumberID FROM TCBillindex
		UNION ALL
		SELECT BillNumberID FROM ToolIndex
		UNION ALL
		SELECT BillNumberID FROM RequestIndex
		UNION ALL
		SELECT BillNumberID FROM SerialAdjustIndex
		UNION ALL
		SELECT BillNumberID FROM CM_CarUseIndex
		UNION ALL
		SELECT BillNumberID FROM CM_FeeIndex
		UNION ALL 
		SELECT BillNumberId FROM CommissionBillNew
		UNION ALL 
		SELECT BillNumberId FROM ReferencePlanCommission
		UNION ALL
		SELECT BillNumberId FROM dbo.CommissionRule
		UNION ALL 
		SELECT BillNumberID FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillNumberID FROM dbo.onShelvespickIndex
		UNION ALL
		SELECT BillNumberID FROM dbo.FactIndex
		UNION ALL
		SELECT BillNumberID FROM PosAllotApplyBillIndex
		UNION ALL 
		SELECT BillNumberID FROM  dbo.Coupon_BillIndex 
	)
	BEGIN
		TRUNCATE TABLE BillCode_Seed
	END
	ELSE
	BEGIN
		DELETE BillCode_Seed
		WHERE BillType NOT IN
		(
			SELECT BillType FROM BillIndex
			UNION ALL
			SELECT BillType FROM OrderIndex
			UNION ALL
			SELECT BillType FROM LendIndex
			UNION ALL
			SELECT BillType FROM FaPiaoBillIndex
			UNION ALL
			SELECT BillType FROM ReceiptBillIndex
			UNION ALL
			SELECT BillType FROM dbo.onShelvespickIndex
			UNION ALL 
			SELECT BillType FROM dbo.FactIndex
			UNION ALL
			SELECT BillType FROM PosAllotApplyBillIndex
			UNION ALL
			SELECT 306
			UNION ALL
			SELECT 164
			UNION ALL
			SELECT 193
			UNION ALL
			SELECT 194
			UNION ALL
			SELECT 204
			UNION ALL
			SELECT 203
			UNION ALL
			SELECT 208
			UNION ALL
			SELECT 209
			UNION ALL 
			SELECT 311
			UNION ALL
			SELECT 309
			UNION ALL
			SELECT BILLTYPE FROM dbo.Coupon_BillIndex
		)
		
		IF NOT EXISTS(SELECT StockCheckID FROM StockCheckIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=306
		END
		
		IF NOT EXISTS(SELECT BillnumberID FROM CommissionRule /*TCBillindex*/)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=164
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM ToolIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType IN (193,194)
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM SerialAdjustIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=203
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM RequestIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=204
		END
		IF NOT EXISTS(SELECT BillNumberID FROM CM_CarUseIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=208
		END
		IF NOT EXISTS(SELECT BillNumberID FROM CM_FeeIndex)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=209
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM CommissionBillNew)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=311
		END
		
		IF NOT EXISTS(SELECT BillNumberID FROM ReferencePlanCommission)
		BEGIN
			DELETE BillCode_Seed
			WHERE BillType=309
		END
	END
	
	--清掉小于系统年份的种子数
	DECLARE
		@inttmpYear	INT
		
	SELECT @inttmpYear=YEAR(MIN(BillDate)) FROM dbo.BillIndex
	
	
	DELETE BillCode_Seed
	WHERE CAST(LEFT(FlowDate,4) AS INT) <@inttmpYear
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_BillOperateLog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_BillOperateLog]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_BillOperateLog
AS
SET NOCOUNT ON

SELECT BO.* INTO #BillOperateLog  FROM BillOperateLog BO INNER JOIN BillIndex bi on BO.BillnumberID=BI.BillNumberId
TRUNCATE TABLE BillOperateLog
INSERT INTO dbo.BillOperateLog
( 
	BillnumberID ,
	OperateType ,
	EtypeID ,
	OperateTime ,
	IP ,
	BillCode ,
	BillDate ,
	ifcheck ,
	btypeid ,
	NTotalMoney ,
	billtype
)
SELECT  BillnumberID ,
		OperateType ,
		EtypeID ,
		OperateTime ,
		IP ,
		BillCode ,
		BillDate ,
		ifcheck ,
		btypeid ,
		NTotalMoney ,
		billtype
FROM	#BillOperateLog
 
DROP TABLE #BillOperateLog

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_CarryOverToIniBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_CarryOverToIniBill]
GO

--====================================================================================
-----------------功能：单据超收超付金额和收付款单未结算金额结转至期初收付款单 
-----------------作者：施训果						   
-----------------日期：2016-08-17                 
--====================================================================================

CREATE	PROC Gp_YearProc_DateTime_CarryOverToIniBill

--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #gather_paybill
(	
	BTypeID varchar (50) NOT NULL,
	DealBtypeid varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	total  NUMERIC(24,10),
	ntotal NUMERIC(24,10),
	billtype VARCHAR(50),
	Comment VARCHAR(50)
)
DECLARE @startdate DATETIME
SELECT @startdate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth

TRUNCATE TABLE #gather_paybill

		--超付转入期初付款单(业务员和部门取默认值)
		INSERT INTO #gather_paybill
		( 
			BTypeID,
			DealBtypeid,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			total,
			ntotal,
			billtype,
			Comment
		)SELECT 
			BtypeId,
			DealBTypeID,
			Stypeid,
			DTypeId,
			etypeid,
			CID,
			SUM(
				CASE WHEN BillType IN (6) 
					THEN -(totalinmoney + CompleteTotal  + preferencemoney - totalmoney)
				ELSE
					(totalinmoney + CompleteTotal  + preferencemoney - totalmoney)
				END
			) AS total,
			SUM(
				CASE WHEN BillType IN (6) 
					THEN -(ntotalinmoney + nCompleteTotal  + npreferencemoney - ntotalmoney)
				ELSE
					(ntotalinmoney + nCompleteTotal  + npreferencemoney - ntotalmoney)
				END
			) AS ntotal,
			66 AS billtype,
			'数据结转时原业务单据超付金额转入'
		FROM dbo.BillIndex
		WHERE RedWord=0 
		AND draft=0 
		AND
		(	
			BillType IN(6,34,145,161,84,150,151,170,128,129) 
			OR
			(BillType = 36 AND btypeid like '00002%')
		)
		AND 
		(
			(Ntotalinmoney + NCompleteTotal  + Npreferencemoney > 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney > Ntotalmoney) 
			OR 
			(Ntotalmoney < 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney < Ntotalmoney)
		)
		AND (ifYearBill<>1 OR IsIni=1)
		GROUP BY BTypeID,STypeID,CID,DealBtypeid,etypeid,DTypeId
	
	--超收转入期初收款单
	INSERT INTO #gather_paybill
	( 
			BTypeID ,
			DealBtypeid,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			total ,
			ntotal ,
			billtype ,
			Comment 
	)SELECT BtypeId,
			DealBtypeid,
			Stypeid,
			DTypeId,
			etypeid,
			CID,
			SUM(
				CASE WHEN BillType IN (45,36) 
					THEN -(totalinmoney + CompleteTotal  + preferencemoney - totalmoney)
				ELSE
						(totalinmoney + CompleteTotal  + preferencemoney - totalmoney)
				END
			),
			SUM(
				CASE WHEN BillType IN (45,36) 
					THEN -(ntotalinmoney + nCompleteTotal  + npreferencemoney - ntotalmoney)
				ELSE
						(ntotalinmoney + nCompleteTotal  + npreferencemoney - ntotalmoney)
				END
			),
			4 ,
			'数据结转时原业务单据超收金额转入'
	FROM dbo.BillIndex
	WHERE RedWord=0 
	AND draft=0 
	AND
	(
		BillType IN(11,45,141,148,85,93,148,149,181,167,168,172,115,116) 
		OR
		(BillType = 36 AND btypeid like '00001%')
	)
	AND 
	(
		(Ntotalinmoney + NCompleteTotal  + Npreferencemoney > 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney > Ntotalmoney) 
		OR 
		(Ntotalmoney < 0 AND Ntotalinmoney + NCompleteTotal  + Npreferencemoney < Ntotalmoney)
	)
	AND (ifYearBill<>1 OR IsIni=1)
	GROUP BY BTypeID,STypeID,CID,DealBtypeid,DTypeId,etypeid
	
	--未结算完成的付款单转入期初
	INSERT INTO #gather_paybill
	( 
			BTypeID ,
			DealBtypeid,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			total ,
			ntotal ,
			billtype ,
			Comment 
	)SELECT BtypeId,
			DealBtypeid,
			Stypeid,
			DTypeId,
			etypeid,
			CID,
			SUM(z.total-z.completotal),
			SUM(z.ntotal-z.ncompletotal),
			billtype,
			'数据结转时未结算完成收付款单金额转入'
	FROM (
			SELECT SUM(ISNULL(c.CompleteTotal,0)) AS completotal,
			SUM(ISNULL(c.NCompleteTotal,0)) AS ncompletotal,
			MAX(b.totalmoney+b.preferencemoney) AS total,
			MAX(b.ntotalmoney+b.npreferencemoney) AS ntotal,
			MAX(b.BTypeID) AS btypeid, 
			MAX(b.DealBtypeid) AS DealBtypeid,
			MAX(STypeID) AS STypeID,
			MAX(DTypeId) AS DTypeId,
			MAX(b.ETypeId) AS ETypeId,
			MAX(CID) AS	CID ,
			MAX(b.billtype) AS billtype 
			FROM dbo.CompleteTotal c RIGHT JOIN dbo.BillIndex b ON c.MoneyBillID=b.BillNumberId
			WHERE b.BillType IN (4,66) AND RedWord=0 AND b.draft=0
			GROUP BY b.BillNumberId
		) z
	WHERE z.billtype IN(4,66) AND 
	z.Ntotal!=z.Ncompletotal
	GROUP BY z.BTypeID,z.STypeID,z.DTypeId,z.etypeid,z.CID,z.BillType,z.DealBtypeid

--清除合计为零的数据
IF EXISTS(SELECT 1 FROM #gather_paybill) 
BEGIN
	--重新插入了年结期初数据，把之前的年结标志先置为0
	update BillIndex set ifYearBill=0 WHERE ifYearBill=1 AND IsIni=1
	
	INSERT INTO [dbo].[BillIndex] 
	(	
		[IfYearBill],
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DEALBTYPEID,
		cid,	
		rate,	
		ntotalmoney,
		ntotalinmoney,	
		npreferencemoney,	
		nvipczmoney,	
		atypeid1,
		billproperty,
		ncompletetotal,
		IsIni
	)

	SELECT	
		1,
		0.00,
		CONVERT(DATE, @startdate),
		CASE billtype 
			WHEN '4' THEN 'XS-T-' 
			WHEN '66' THEN 'JF-'
		END + LEFT(NEWID(),9) + s.UserCode+'-'+CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
		billtype,
		b.Comment,
		'',
		'',
		btypeid,
		etypeid,
		'',
		'',
		't',
		'',
		0,
		total,
		0,
		0,
		1,
		'',
		0,
		0,
		0,
		'',
		'',
		'',
		'',
		0,
		9999,
		0,
		'',
		'',
		'',
		dtypeid,
		'',
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		STypeID,
		0,
		0,
		0,
		-1,
		'',
		@startdate,
		NULL,
		0,
		'',
		'',
		'',
		'',
		'',
		DealBTypeID,
		B.cid,	
		CASE WHEN ntotal=0 THEN AC.RATE 
			WHEN AC.BasisType=0 THEN dbo.F_RoundExchangeRate(total/ntotal) 
			ELSE dbo.F_RoundExchangeRate(ntotal/total) END,	
		ntotal,
		0,	
		0,	
		0,	
		(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
		1,
		0,
		1
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY stypeid,DTypeId,etypeid,cid) sort,
				Stypeid,
				btypeid,	
				DealBtypeid,
				DTypeId,
				etypeid,
				CID,
				BillType,
				Comment,
				SUM(total) AS total,
				SUM(ntotal) AS ntotal
		FROM #gather_paybill
		GROUP BY Stypeid,btypeid,DTypeId,etypeid,CID,BillType,Comment,DealBtypeid
	)b	INNER JOIN dbo.SType s ON b.Stypeid=s.TypeId
	INNER JOIN dbo.Ac_Currency AC ON B.CID=AC.CId
	
	DECLARE @atypeid INT=1
	SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
	INSERT INTO dbo.PayBill
        ( BillNumberId ,
          AtypeId ,
          total ,
          Comment ,
          TeamNo ,
          TeamNO1 ,
          Stypeid ,
          ntotal ,
          ShowOrder ,
          VipCardID ,
          RelevanceBillId
        ) 
	SELECT 
		B.BillNumberId,
		@atypeid,
		ba.total,
		'',
		0,
		0,
		ba.STypeID,
		ba.ntotal,
		0,
		0,
		NULL
	FROM #gather_paybill ba 
	INNER JOIN dbo.BillIndex B ON ba.stypeid=b.Stypeid AND ba.btypeid=b.btypeid  AND ba.DealBtypeid=b.DealBtypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid
	WHERE	b.BillType = 66
			AND b.IsIni=1
			AND ifYearBill=1
			AND b.Comment=ba.comment
	
	IF @@ERROR<>0
		RAISERROR('处理超收超付转期初收付款单失败！',16,1)     
	
	--SELECT * FROM #gather_paybill
	INSERT INTO dbo.gatheringBill
        ( BillNumberId ,
          AtypeId ,
          total ,
          Comment ,
          TeamNo ,
          TeamNO1 ,
          Stypeid ,
          ntotal ,
          ShowOrder ,
          VipCardID ,
          RelevanceBillId
        )
     SELECT 
		B.BillNumberId,
		@atypeid,
		ba.total,
		'',
		0,
		0,
		ba.STypeID,
		ba.ntotal,
		0,
		0,
		NULL
	FROM #gather_paybill ba 
	INNER JOIN dbo.BillIndex B ON ba.stypeid=b.Stypeid AND ba.btypeid=b.btypeid AND ba.DealBtypeid=b.DealBtypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid
	WHERE	b.BillType = 4
			AND b.IsIni=1
			AND ifYearBill=1
			AND b.Comment=ba.comment
			
	IF @@ERROR<>0
		RAISERROR('处理超收超付转期初收付款单失败！',16,1)       
END
DROP TABLE #gather_paybill
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_Coupon]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_Coupon]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------

-------------------------------------------------------------------------
CREATE   PROCEDURE Gp_YearProc_DateTime_Coupon
(
	@yearendDatetime						VARCHAR(20)			--   -年结存的日期		
)

AS
SET NOCOUNT ON

--处理期初状态：
--指定时间之前有入库记录的券，先将期初状态置为入库
UPDATE ci SET ci.IniState = 1 --CASE WHEN ci.[State] IN(2,3,4,5) THEN 2 ELSE 1 END 
			 ,ci.IsYear = 1
			 ,ci.IsIni = 1
			 ,ci.iniktypeid=ci.KtypeId
			 ,ci.Inicargoid=ci.CargoId
FROM dbo.Coupon_CodeInfo ci
WHERE EXISTS(SELECT TOP 1 CouponCode 
				FROM dbo.Coupon_CodeInOut cc 
				INNER JOIN dbo.Coupon_BillIndex cb ON cb.BillNumberId = cc.BillNumberId
				WHERE cb.RedWord = 0 AND cb.IfCheck = 't' AND cc.BillDate < @yearendDatetime AND cc.BillType = 423 AND CouponCode = ci.CouponCode)

--指定时间之前有出库记录的券，继而将期初状态置为出库
UPDATE ci SET ci.IniState = 2 --CASE WHEN ci.[State] IN(2,3,4,5) THEN 2 ELSE 1 END 
			 ,ci.IsYear = 1
			 ,ci.IsIni = 1
			 ,ci.iniktypeid=ci.KtypeId
			 ,ci.Inicargoid=ci.CargoId
FROM dbo.Coupon_CodeInfo ci
WHERE EXISTS(SELECT TOP 1 CouponCode FROM dbo.Coupon_CodeInOut cc 
				INNER JOIN dbo.Coupon_BillIndex cb ON cb.BillNumberId = cc.BillNumberId  
				WHERE cb.RedWord = 0 AND cb.IfCheck = 't' AND cc.BillDate < @yearendDatetime AND cc.BillType = 424 AND CouponCode = ci.CouponCode)

--处理当前状态：消费红冲的券，在指定时间之后没有相应状态的记录，则置为出库
UPDATE ci SET ci.[State] = 2 
FROM dbo.Coupon_CodeInfo ci
WHERE ci.[State] = 4
	AND NOT EXISTS( SELECT TOP 1 CouponCode 
					FROM dbo.Coupon_BillUsed i  
					INNER JOIN dbo.BillIndex b ON b.BillNumberId = i.BillNumberId
					WHERE b.RedWord = 1 AND b.IfCheck = 't' AND b.BillDate >= @yearendDatetime AND i.CouponCode = ci.CouponCode )
					
--处理当前状态：消费退货的券，在指定时间之后没有相应状态的记录，则置为出库					
UPDATE ci SET ci.[State] = 2 
FROM dbo.Coupon_CodeInfo ci
WHERE ci.[State] = 5
	AND NOT EXISTS( SELECT TOP 1 CouponCode 
					FROM dbo.Coupon_BillUsed i  
					INNER JOIN dbo.BillIndex b ON b.BillNumberId = i.BillNumberId
					WHERE b.RedWord = 0 AND b.IfCheck = 't' AND b.BillType IN(45,46,215) AND b.BillDate >= @yearendDatetime AND i.CouponCode = ci.CouponCode )


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_Deal_iniArApBillCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_Deal_iniArApBillCode]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-期初应收应付单据编号，单据日期
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_Deal_iniArApBillCode
(
	@yearendDatetime		VARCHAR(20)			--   -年结存的日期	
)

AS
SET NOCOUNT ON

DECLARE @newFPeriod	INT,
		@newFYear	INT,
		@BeginDate  DATETIME

SELECT TOP 1 
	@newFPeriod=FPeriod,
	@newFYear=FYear 
FROM dbo.Ac_Period 
WHERE FBegin = @yearendDatetime
DECLARE @IniBillDate DATETIME
--SELECT @IniBillDate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth
--SELECT @IniBillDate=DATEADD(day,-1,FBegin)  FROM dbo.Ac_Period WHERE FPeriod=@newFPeriod AND FYear=@newFYear
SELECT @IniBillDate=DATEADD(day,-1,@yearendDatetime) 

--SELECT @IniBillDate
UPDATE A
	SET A.BillDate=CONVERT(DATE, @IniBillDate),
		A.BillCode=CASE A.billtype WHEN 189 THEN 'IniYskBill-'
								   WHEN 190 THEN 'IniYfkBill-' 
								   ELSE ''
								   END + A.STypeID +'-'+CONVERT(VARCHAR(10),@IniBillDate,120)+'-'+CAST(RowIndex AS VARCHAR(10))
FROM dbo.BillIndex A,(
	SELECT BillNumberId,BillType,ROW_NUMBER() OVER(ORDER BY BillCode ASC) AS RowIndex
	FROM dbo.BillIndex WHERE IsIni=1 AND ifYearBill=0 AND BillType IN(189,190)
) B
WHERE A.BillNumberId=B.BillNumberId

DECLARE @NewID VARCHAR(9)
SET @NewID=LEFT(NEWID(),9)  

UPDATE	A
SET		A.BillDate=CONVERT(DATE, @IniBillDate),			
		A.BillCode=CASE A.billtype WHEN 115 THEN 'IniYjBill-' 
								   WHEN 116 THEN 'IniYzBill-' 
								   WHEN 128 THEN 'IniFzBill-'
								   WHEN 129 THEN 'IniFjBill-'
								   ELSE ''
								   END +@NewID+ A.STypeID +'-'+CONVERT(VARCHAR(10),@IniBillDate,120)+'-'+CAST(RowIndex AS VARCHAR(10))
FROM dbo.BillIndex A,
(
	SELECT	BillNumberId,
			BillType,
			ROW_NUMBER() OVER(ORDER BY BillCode ASC) AS RowIndex
	FROM	dbo.BillIndex 
	WHERE	IsIni=1 
			AND ifYearBill=0 
			AND BillType IN(115,116,128,129)
) B
WHERE A.BillNumberId=B.BillNumberId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_Deal_MonthProc_SType_UserConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_Deal_MonthProc_SType_UserConfig]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-期间和分支机构配置
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_Deal_MonthProc_SType_UserConfig
(
	@yearendDatetime		VARCHAR(20)			--   -年结存的日期	
)
AS
SET NOCOUNT ON

DELETE FROM Monthproc WHERE MonthNo <> '本期' AND StartDate < @yearendDatetime

--在总账版本下，年结存的时候，
--将业务系统的年度和开始时间更新为当前总账的年度和期间；
--非总账下年结存不做调整
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='isuseacsystem' AND SubValue=1)
BEGIN
		
	DECLARE @newFPeriod	INT,
			@newFYear	INT,
			@BeginDate  DATETIME

	SELECT TOP 1 
		@newFPeriod=FPeriod,
		@newFYear=FYear 
	FROM dbo.Ac_Period 
	WHERE FBegin = @yearendDatetime
	
	SELECT @BeginDate=FBegin FROM dbo.Ac_Period WHERE FPeriod=@newFPeriod AND FYear=@newFYear
	
	UPDATE dbo.SType_UserConfig SET SFYear=@newFYear,SFPeriod=@newFPeriod WHERE Value = 1
	
	UPDATE A
	SET 
		A.StartDate=@BeginDate,
		A.Period=@newFPeriod,
		A.YEAR=@newFYear
	FROM dbo.MonthProc A 
	WHERE A.MonthNo='本期' AND a.StartDate < @yearendDatetime
END
ELSE 
BEGIN
	UPDATE dbo.SType_UserConfig 
	SET SfYear=(SELECT TOP 1 [Year] FROM dbo.MonthProc WHERE StartDate = @yearendDatetime),
		sfperiod=(SELECT TOP 1 period FROM dbo.MonthProc WHERE StartDate = @yearendDatetime)
	FROM dbo.SType_UserConfig A
	WHERE A.Value = 1
END


--IF @@ROWCOUNT = 0 GOTO ERROR
UPDATE	SysData
SET		SubValue = 1
WHERE	SubName ='period'
--IF @@ERROR <> 0 GOTO ERROR

UPDATE	SysData
SET		SubValue = '0000000000'
WHERE	SubName LIKE '%Code'
		AND SubName NOT IN('bwbcode','hyyunsms_usercode')--排除短信账号
--IF @@ROWCOUNT = 0 GOTO ERROR

--UPDATE	SysData
--SET		SubValue = '1'
--WHERE	SubName = 'CanAuditing'
--IF @@ROWCOUNT = 0 GOTO ERROR

--UPDATE	SysData
--SET		SubValue = 'T'
--WHERE	SubName = 'inicanmodify'
--IF @@ROWCOUNT = 0 GOTO ERROR

UPDATE UserConfig SET Value = '0' WHERE ConfigName = 'AverageCostPrice'

--清空开账标识
--UPDATE SType_UserConfig SET Value = '0' WHERE ConfigNo = '1' 

--父节点没有存在的必要了
DELETE FROM dbo.SType_UserConfig
WHERE StypeId IN (SELECT typeid FROM dbo.SType WHERE sonnum>0)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_DealAuditAndPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_DealAuditAndPrice]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-审核和相关价格信息
	EXEC Gp_YearProc_DateTime_DealAuditAndPrice @delDraft,
												@delOrder,
												@chrRecPrice,
												@chrRecSalePrice,
												@chrRecSTypeBuyPrice,
												@chrRecSTypeSalePrice,
												@chrSTypePriceTrack,
												@delPriceTrack
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_DealAuditAndPrice
(
	@delDraft				CHAR(1) = '1',		-- 1 - 删除草稿数据；0 - 不删除
	@delOrder				CHAR(1) = '1',		-- 1 - 删除定单数据；0 - 不删除
	@chrRecPrice			CHAR(1) = '0',		-- 1 - 删除商品最近进价；0 - 不删除
	@chrRecSalePrice		CHAR(1) = '1',		-- 1 - 年结存清空最近售价；0 - 不清空最近售价
	@chrRecSTypeBuyPrice	CHAR(1) = '1',		-- 1 - 年结存清除商品分支机构间最近进价：0 - 不清空商品分支机构间商品最近进价
	@chrRecSTypeSalePrice	CHAR(1) = '1',		-- 1 - 年结存清除商品分支机构间最近售价：0 - 不清空商品分支机构间商品最近售价
	@chrSTypePriceTrack		CHAR(1) = '1',		-- 1 - 年结存清除分支机构间价格跟踪信息: 0 - 不清空分支机构间价格跟踪信息
	@delPriceTrack			CHAR(1) = '0',		-- 1 - 清除价格跟踪信息；0 - 不清除
	@yearendDatetime		VARCHAR(20)			--   -年结存的日期	
)
AS
SET NOCOUNT ON

IF @delDraft = '1' AND @delOrder = '1'	-- 同时删除草稿和订单
BEGIN
	DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime
END
ELSE
BEGIN
	IF @delDraft = '1' AND @delOrder <> '1'	-- 删草稿，不删订单
	BEGIN
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType BETWEEN 1 AND 8
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '0' AND NOT EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE BillNumberId=AuditingBill.BillNumberID)
	END
	ELSE IF @delOrder = '1' AND @delDraft <> '1'	-- 删订单，不删草稿
	BEGIN
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '0' 
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '2' AND NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '1'  AND NOT EXISTS(SELECT 1 FROM LendIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '4' AND NOT EXISTS(SELECT 1 FROM CommissionBillNew WHERE BillNumberId=AuditingBill.BillNumberID)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '5' AND NOT EXISTS(SELECT 1 FROM ReceiptBillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '6' AND  NOT EXISTS(SELECT 1 FROM onShelvespickIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '7' AND NOT  EXISTS(SELECT 1 FROM FactIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '8' AND NOT EXISTS(SELECT 1 FROM Coupon_BillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)	
	END
	ELSE
	BEGIN
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '2' AND NOT EXISTS(SELECT 1 FROM BillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)			
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '0' AND NOT EXISTS(SELECT 1 FROM dbo.OrderIndex WHERE BillNumberId=AuditingBill.BillNumberID)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '1'  AND NOT EXISTS(SELECT 1 FROM LendIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '4' AND NOT EXISTS(SELECT 1 FROM CommissionBillNew WHERE BillNumberId=AuditingBill.BillNumberID)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '5' AND NOT  EXISTS(SELECT 1 FROM ReceiptBillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '6' AND  NOT EXISTS(SELECT 1 FROM onShelvespickIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '7' AND NOT  EXISTS(SELECT 1 FROM FactIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)
		DELETE FROM AuditingBill WHERE BillDate < @yearendDatetime AND BillIndexType = '8' AND NOT EXISTS(SELECT 1 FROM Coupon_BillIndex WHERE BillNumberId=AuditingBill.BillNumberID AND IsIni=0)		
	END
END

DELETE FROM AuditingBillDetail WHERE NOT EXISTS(SELECT * FROM dbo.AuditingBill b WHERE b.BillNumberID = AuditingBillDetail.BillNumberID AND b.BillIndexType = AuditingBillDetail.BillIndexType)

IF @chrRecPrice = '1'
BEGIN
	UPDATE dbo.ptype SET recPrice=0
	UPDATE PType_STypePrice SET RecPrice=0,
								RecAppraisalPrice=0
END

IF @chrRecSalePrice='1'
BEGIN
	UPDATE PType_STypePrice SET RecSalePrice=0,
								RecSendPrice=0
END
--商品分支机构间最近进价
IF @chrRecSTypeBuyPrice='1'
BEGIN
	UPDATE PType_Price SET RecAmgSTypeBuyPrice=0
END
--商品分支机构间最近售价
IF @chrRecSTypeSalePrice='1'
BEGIN
	UPDATE PType_Price SET RecAmgSTypeSalePrice=0
END
--分支机构间价格跟踪	
IF @chrSTypePriceTrack='1'
BEGIN
	DELETE FROM PriceTrack_SType_Appraisal WHERE TrackTime < @yearendDatetime	 --暂估入库分支机构间价格跟踪表
	DELETE FROM PriceTrack_SType_AskPrice WHERE TrackTime < @yearendDatetime	 --询价单分支机构间价格跟踪表
	DELETE FROM PriceTrack_SType_Buy WHERE TrackTime < @yearendDatetime	 --采购入库单分支机构间价格跟踪表
	DELETE FROM PriceTrack_SType_BuyOrder WHERE TrackTime < @yearendDatetime	 --采购订单分支机构间价格跟踪表
	DELETE FROM PriceTrack_SType_Quote WHERE TrackTime < @yearendDatetime	 --报价单分支机构间价格跟踪表
	DELETE FROM PriceTrack_SType_Sale WHERE TrackTime < @yearendDatetime	 --销售出库分支机构间价格跟踪表
	DELETE FROM PriceTrack_SType_SaleOrder WHERE TrackTime < @yearendDatetime	 --销售订单分支机构间价格跟踪表
	DELETE FROM PriceTrack_SType_Send WHERE TrackTime < @yearendDatetime	 --发出商品分支机构间价格跟踪表
END

IF @delPriceTrack = '1'
BEGIN
	TRUNCATE TABLE PriceTrack			-- 清除价格跟踪表
	
	--9.4价格跟踪变化后的清除
	DELETE FROM PriceTrack_AskPrice WHERE TrackTime < @yearendDatetime
	DELETE FROM PriceTrack_Buy WHERE TrackTime < @yearendDatetime
	DELETE FROM PriceTrack_BuyOrder WHERE TrackTime < @yearendDatetime
	DELETE FROM PriceTrack_Quote WHERE TrackTime < @yearendDatetime
	DELETE FROM PriceTrack_Sale WHERE TrackTime < @yearendDatetime
	DELETE FROM PriceTrack_SaleOrder WHERE TrackTime < @yearendDatetime
	DELETE FROM PriceTrack_Send WHERE TrackTime < @yearendDatetime
	DELETE FROM PriceTrack_Appraisal  WHERE TrackTime < @yearendDatetime
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_FaPiao]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_FaPiao]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-发票信息
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_FaPiao
(
	@yearendDatetime						VARCHAR(20)			--   -年结存的日期	
)
AS
SET NOCOUNT ON

CREATE  TABLE #FaPiao( billnumberid int,MainBillNumberID int)
INSERT INTO #FaPiao(billnumberid,MainBillNumberID) SELECT billnumberid,MainBillNumberID FROM FaPiaoBill WHERE MainBillNumberID  IN(SELECT BillNumberID FROM BillIndex WHERE IfInvoice<>2 AND BillDate<=@yearendDatetime)
IF EXISTS(SELECT TOP 1 1 FROM #FaPiao)
BEGIN
	DELETE FaPiaoBillIndex WHERE NOT EXISTS(SELECT 1 FROM #FaPiao WHERE billnumberid=FaPiaoBillIndex.BillNumberID) AND BillDate<=@yearendDatetime
	DELETE FaPiaoBill  WHERE  NOT EXISTS(SELECT 1 FROM #FaPiao WHERE MainBillNumberID=FaPiaoBill.MainBillNumberID) OR NOT EXISTS (SELECT  1 FROM dbo.FaPiaoBillIndex fi WHERE fi.BillNumberID=FaPiaoBill.BillNumberID)				
	UPDATE FaPiaoBillIndex SET [ifYearBill] = 1 WHERE BillDate<=@yearendDatetime
END
ELSE
BEGIN
	DELETE FROM  FaPiaoBillindex	WHERE  BillDate<=@yearendDatetime	-- 清掉新发票单据索引表
	DELETE FROM FaPiaoBill	 WHERE NOT EXISTS (SELECT  1 FROM dbo.FaPiaoBillIndex fi WHERE fi.BillNumberID=FaPiaoBill.BillNumberID)		-- 清掉新发票单据明细表
END
DROP TABLE #FaPiao

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_HandleBalance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_HandleBalance]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结 处理结算相关 
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_HandleBalance
(
	@yearendmode	CHAR(1) = '1'	,	-- 1 - 按余额转期初；0 - 按单据转期初
	@yearendDatetime        VARCHAR(20)		
)
AS
SET NOCOUNT ON

---- 清除按单结算表
--TRUNCATE TABLE CompleteTotal		
---- 清除按商品结算明细表
--TRUNCATE TABLE CompleteGoodTotal
----清空按品牌结算明细表
--TRUNCATE TABLE dbo.CompleteBrandarTotal

--在执行删除主表之后
IF  @yearendmode=1 --按余额结转
begin
 delete from CompleteTotal where not exists (select bil.billnumberid from billindex bil where bil.billtype in (4,66) and bil.billnumberid= CompleteTotal.moneybillid AND bil.BillDate>=@yearendDatetime)
									                        
		                     					 
 delete from CompleteGoodTotal where  not exists (select bil.billnumberid from billindex bil where  bil.billnumberid= CompleteGoodTotal.moneybillid AND bil.BillDate>=@yearendDatetime)
		
								 				 
 delete from CompleteBrandarTotal where  not exists (select bil.billnumberid from billindex bil where  bil.billnumberid= CompleteBrandarTotal.moneybillid AND bil.BillDate>=@yearendDatetime)
								
								

--找不到结算过程的被结算单据

CREATE TABLE #jstemp
(
	BILLNUMBERID int ,
	billtype int
	
)
insert into #jstemp
( billnumberid,
  billtype
)
 SELECT  distinct a.billnumberid,a.billtype
 FROM BILLINDEX A
 LEFT JOIN CompleteTotal C ON A.BILLNUMBERID=C.goodsbillid AND A.BILLTYPE=C.BILLTYPE  
 WHERE C.goodsbillid IS NULL AND a.CompleteTotal<>0  AND ISNULL(c.Draft,0)=0
 UNION ALL 
 SELECT  distinct a.billnumberid,a.billtype
 FROM ReceiptBillIndex A
 LEFT JOIN CompleteTotal C ON A.BILLNUMBERID=C.goodsbillid AND A.BILLTYPE=C.BILLTYPE 
 WHERE a.billtype IN (404,405) AND C.goodsbillid IS NULL AND a.CompleteTotal<>0 AND ISNULL(c.Draft,0)=0
 UNION ALL
 SELECT  distinct a.billnumberid,a.billtype
 FROM Coupon_BillIndex A
 LEFT JOIN CompleteTotal C ON A.BILLNUMBERID=C.goodsbillid AND A.BILLTYPE=C.BILLTYPE 
 WHERE  a.billtype IN (423,424,426) AND C.goodsbillid IS NULL AND a.CompleteTotal<>0 AND ISNULL(c.Draft,0)=0


IF EXISTS (SELECT 1 FROM #jstemp)
BEGIN
	  
   UPDATE ReceiptBill
	SET CompleteQTY=0,
		CompleteTotal=0,
		NCompleteTotal=0
	FROM ReceiptBill B
	INNER JOIN #jstemp js ON js.BILLNUMBERID = B.BillNumberId AND js.billtype IN (404,405) 
		 
	--只能按单结算的单据不处理明细表 423,424,426  148,150,149,151,450,213,212,312

	DECLARE @sqldetailtable VARCHAR (max)=''
	
	SELECT   @sqldetailtable=@sqldetailtable+'  
			UPDATE  A SET COMPLETEQTY=0,COMPLETETOTAL=0,Ncompletetotal=0
			from  '+bn.detailTable+'  A
			where isnull(A.COMPLETEQTY,0)<>0
			'
    FROM  #jstemp js 
    INNER JOIN billindex bil ON js.BILLNUMBERID=bil.BILLNUMBERID AND js.billtype=bil.billtype 
    INNER JOIN billname bn ON bn.Billtype = js.billtype
    WHERE bil.billtype NOT  IN  (423,424,426,116,115,128,129,148,150,149,151,450,213,212,312)
	
	IF(ISNULL(@sqldetailtable,'')<>'')
	BEGIN
	 EXEC  (@sqldetailtable)
	END 
	
	UPDATE Ad
	SET COMPLETETOTAL=0,Ncompletetotal=0
	FROM addebtbill ad
	INNER JOIN  #jstemp js  ON js.BILLNUMBERID = ad.BillNumberId AND js.billtype IN (116,115,128,129)


	UPDATE bil SET 
	   bil.CompleteTotal=0,
	   bil.NCompleteTotal=0
	FROM billindex bil
	INNER JOIN #jstemp js ON js.BILLNUMBERID = bil.BillNumberId AND js.billtype = bil.BillType
	WHERE js.billtype NOT  IN (404,405,423,424,426) 
	AND ISNULL(bil.CompleteTotal,0)<>0 

	UPDATE bil SET 
	   bil.CompleteTotal=0,
	   bil.NCompleteTotal=0
	FROM ReceiptBillIndex bil
	INNER JOIN #jstemp js ON js.BILLNUMBERID = bil.BillNumberId AND js.billtype = bil.BillType
	WHERE js.billtype IN (404,405) 
	AND ISNULL(bil.CompleteTotal,0)<>0 

  
    UPDATE bil SET 
	   bil.CompleteTotal=0,
	   bil.NCompleteTotal=0
  FROM Coupon_BillIndex bil
  INNER JOIN #jstemp js ON js.BILLNUMBERID = bil.BillNumberId AND js.billtype = bil.BillType 
  WHERE js.billtype IN (423,424,426)    AND bil.jsState<>0
  AND ISNULL(bil.CompleteTotal,0)<>0 

END
 --TRUNCATE TABLE #jstemp
 
--找得到对应的结算过程的
--按单 按品牌

DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr= SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

CREATE TABLE #jstempbybill
(
	BILLNUMBERID int ,
	billtype INT,
	CompleteTotal numeric (24,10),
	Ncompletetotal numeric (24,10)
)


insert into #jstempbybill
( billnumberid,
  billtype,
  CompleteTotal,
  Ncompletetotal 
)
 SELECT   a.billnumberid,a.billtype,SUM(ISNULL(c.CompleteTotal,0)),SUM(ISNULL(c.NCompleteTotal,0))
 FROM BILLINDEX A
 INNER JOIN CompleteTotal C ON A.BILLNUMBERID=C.goodsbillid AND A.BILLTYPE=C.BILLTYPE AND c.Draft=0
 WHERE  a.CompleteTotal<>0 AND a.jsStyle IN (1,3)
 GROUP BY a.billnumberid,a.billtype 
 UNION ALL 
 SELECT   a.billnumberid,a.billtype,SUM(ISNULL(c.CompleteTotal,0)),SUM(ISNULL(c.NCompleteTotal,0))
 FROM ReceiptBillIndex A
 INNER JOIN CompleteTotal C ON A.BILLNUMBERID=C.goodsbillid AND A.BILLTYPE=C.BILLTYPE AND c.Draft=0
 WHERE  c.billtype IN (404,405)  AND a.CompleteTotal<>0 AND a.jsStyle IN (1,3)
 GROUP BY a.billnumberid,a.billtype 
 UNION ALL
 SELECT   a.billnumberid,a.billtype,SUM(ISNULL(c.CompleteTotal,0)),SUM(ISNULL(c.NCompleteTotal,0))
 FROM Coupon_BillIndex A
 INNER JOIN CompleteTotal C ON A.BILLNUMBERID=C.goodsbillid AND A.BILLTYPE=C.BILLTYPE AND c.Draft=0
 WHERE  c.billtype IN (423,424,426)  AND a.CompleteTotal<>0 
 GROUP BY a.billnumberid,a.billtype 
 
 --重算按单 按品牌结算金额
 IF EXISTS (SELECT 1 FROM #jstempbybill)
 BEGIN 
	UPDATE A 
		SET	A.CompleteTotal = CASE WHEN  jsb.billtype IN(45,6,148,149,150,151,115,129,46,36) THEN -1*ISNULL(jsb.CompleteTotal,0)
		 ELSE ISNULL(jsb.CompleteTotal,0) END  ,
		A.nCompleteTotal = CASE WHEN jsb.billtype IN(45,6,148,149,150,151,115,129,46,36) THEN -1*ISNULL(jsb.nCompleteTotal,0) ELSE ISNULL(jsb.nCompleteTotal,0) END
	FROM  BILLINDEX A
	INNER JOIN #jstempbybill jsb ON jsb.billnumberid=a.BillNumberId AND jsb.billtype=a.BillType
	WHERE   a.Billtype in (45,6,148,149,150,151,115,129,404,46)
			OR (a.Billtype=36 AND @ExpenseToAr=1 AND LEFT(a.btypeid,5)='00001')
			
	UPDATE A 
	   SET	A.CompleteTotal = ISNULL(jsb.CompleteTotal,0),
		A.nCompleteTotal =ISNULL(jsb.nCompleteTotal,0)

	FROM  BILLINDEX A
	INNER JOIN #jstempbybill jsb ON jsb.billnumberid=a.BillNumberId AND jsb.billtype=a.BillType
	WHERE  a.Billtype not in (45,6,148,149,150,151,115,129,36,46)
			OR (a.Billtype=36 AND (@ExpenseToAr=0 OR LEFT(a.btypeid,5)='00002'))
			
			
	UPDATE A 
	SET	A.CompleteTotal =CASE WHEN  jsb.billtype =426 THEN -1*ISNULL(jsb.CompleteTotal,0) ELSE ISNULL(jsb.CompleteTotal,0) END  ,
		A.nCompleteTotal =CASE WHEN  jsb.billtype =426 THEN -1*ISNULL(jsb.nCompleteTotal,0) ELSE ISNULL(jsb.nCompleteTotal,0) END  
	FROM  Coupon_BillIndex A
	INNER JOIN #jstempbybill jsb ON jsb.billnumberid=a.BillNumberId AND jsb.billtype=a.BillType

	UPDATE A 
	SET	A.CompleteTotal = ISNULL(jsb.CompleteTotal,0),
		A.nCompleteTotal = ISNULL(jsb.nCompleteTotal,0)

	FROM  ReceiptBillIndex A
	INNER JOIN #jstempbybill jsb ON jsb.billnumberid=a.BillNumberId AND jsb.billtype=a.BillType
	
	--应收\应付增加\减少单要回写到明细
	UPDATE A 
	SET a.CompleteTotal=c.CompleteTotal,
		a.nCompleteTotal=c.nCompleteTotal	
	FROM AdDebtBill A
	INNER JOIN  (
	SELECT c.GoodsBillID AS BillNumberId,c.BillType,c.GoodsBillID AS id,
			 CASE WHEN BillType IN (115,129) THEN  SUM(CompleteTotal) 
				 ELSE  -1*SUM(CompleteTotal) 
				 END  AS CompleteTotal , 
			 CASE WHEN BillType IN (115,129) THEN  SUM(nCompleteTotal) 
				 ELSE  -1*SUM(nCompleteTotal) 
				 END  AS nCompleteTotal 	 
				 
	FROM COMPLETETOTAL c 
	WHERE BillType IN (115,116,128,129)
	GROUP BY  c.BillType,c.GoodsBillID,c.GoodsBillDetailID
	) c ON a.BillNumberId=c.BillNumberId AND a.ID=c.id
			

 END 
CREATE TABLE #jstempbygoods
(
	BILLNUMBERID int ,
	billtype INT,
	DETAILID INT,
	CompleteQty numeric(24,10),
	CompleteTotal numeric (24,10),
	Ncompletetotal numeric (24,10),
	detailtable varchar (50)
)
INSERT INTO #jstempbygoods
(

	BILLNUMBERID  ,
	billtype ,
	CompleteQty,
	CompleteTotal ,
	Ncompletetotal ,
	DETAILID 
)
 SELECT   a.billnumberid,a.billtype,SUM(ISNULL(c.CompleteGoodQTY,0)),SUM(ISNULL(c.CompleteGoodTotal,0)),SUM(ISNULL(c.NCompleteGoodTotal,0)),C.Billid
 FROM BILLINDEX A
 INNER JOIN dbo.CompleteGoodTotal C ON A.BILLNUMBERID=C.goodsbillid AND A.BILLTYPE=C.BILLTYPE AND c.Draft=0
 WHERE  a.CompleteTotal<>0 AND a.jsStyle =2
 GROUP BY a.billnumberid,a.billtype ,C.Billid
 UNION ALL 
 SELECT   a.billnumberid,a.billtype,SUM(ISNULL(c.CompleteGoodQTY,0)),SUM(ISNULL(c.CompleteGoodTotal,0)),SUM(ISNULL(c.NCompleteGoodTotal,0)),C.Billid
 FROM ReceiptBillIndex A
 INNER JOIN CompleteGoodTotal C ON A.BILLNUMBERID=C.goodsbillid AND A.BILLTYPE=C.BILLTYPE AND c.Draft=0
 WHERE  c.billtype IN (404,405)  AND a.CompleteTotal<>0 AND a.jsStyle =2
 GROUP BY a.billnumberid,a.billtype,C.Billid
 
 IF EXISTS (SELECT 1 FROM #jstempbygoods)
 BEGIN
 UPDATE #jstempbygoods 
 SET detailtable=CASE   WHEN BILLTYPE IN (11, 203) THEN  'SaleBill'
						WHEN BILLTYPE = 12			THEN  'PT_Combin_SaleBill'
						WHEN BILLTYPE =  45			THEN  'SaleBackBill'
						WHEN BILLTYPE =  46			THEN  'PT_Combin_SaleBackBill'
						WHEN BILLTYPE = 4			THEN  'GatheringBill'
						WHEN BILLTYPE =  34			THEN  'BuyBill'
						WHEN BILLTYPE =  6			THEN  'BuyBackBill'
						WHEN BILLTYPE = 66			THEN  'PayBill'
						WHEN BILLTYPE =  77			THEN  'MoveMoneyBill'
						WHEN BILLTYPE  IN (115,116,128,129)	THEN  'adDebtBill'
						WHEN BILLTYPE =  57			THEN  'adPriceBill'
						WHEN BILLTYPE =  17			THEN  'MoveBill'
						WHEN BILLTYPE =  21			THEN  'MoveBjBill'
						WHEN BILLTYPE  IN (36,93,5,10,78,84,85,158)	THEN  'MoneyBill'
						WHEN BILLTYPE =  77			THEN  'MoveMoneyBill'
						WHEN BILLTYPE =  305		THEN  'RetailBill'
						WHEN BILLTYPE =  215		THEN  'RetailBackBill'
						WHEN BILLTYPE =  139		THEN  'GiveBill'
						WHEN BILLTYPE = 126			THEN  'GivemeBill'
						WHEN BILLTYPE =  148		THEN  'Advantage'
						WHEN BILLTYPE  IN (149,151)	THEN  'PriceProtectBill'
						WHEN BILLTYPE =  150		THEN  'Advantage'
						WHEN BILLTYPE  IN (140,141,142,143,144,145,146,147)	THEN  'CommissionBill'
						WHEN BILLTYPE =  155		THEN  'GoodsExchangeBill'
						WHEN BILLTYPE =  157		THEN  'RepairDealDetail'
						WHEN BILLTYPE =  159		THEN  'AccountCredence'	-- 会计凭证
						WHEN BILLTYPE =  160		THEN  'SaleGoodsExchangeBill'	-- 销售换货单
						WHEN BILLTYPE =  161		THEN  'BuyGoodsExchangeBill'	-- 采购换货单
						WHEN BILLTYPE =  167		THEN  'wx_Bill_GetBack'	-- 新维修 - 取件单
						WHEN BILLTYPE =  168		THEN  'wx_Bill_Replace'	-- 新维修 - 整机更换单
						WHEN BILLTYPE =  170		THEN  'wx_Bill_SendBack'	-- 新维修 - 送修返回单
						WHEN BILLTYPE  IN (404,405) THEN  'ReceiptBill'
						ELSE  ''
						END 
 
 UPDATE A 
	SET	A.CompleteTotal = ISNULL(jsb.CompleteTotal,0),
		A.nCompleteTotal = ISNULL(jsb.nCompleteTotal,0)

	FROM  BILLINDEX A
	INNER JOIN (
		SELECT A.BillNumberId ,
			   A.billtype,
			   SUM(A.CompleteTotal) AS CompleteTotal,
			   SUM(A.NCompleteTotal) AS NCompleteTotal
		FROM #jstempbygoods a
		GROUP BY A.BillNumberId ,
			   A.billtype
	 )jsb ON jsb.billnumberid=a.BillNumberId AND jsb.billtype=a.BillType
	WHERE   a.Billtype in (45,6,148,149,150,151,115,129,404,46)
			OR (a.Billtype=36 AND @ExpenseToAr=1 AND LEFT(a.btypeid,5)='00001')
			
	UPDATE A 
	SET	A.CompleteTotal = ISNULL(jsb.CompleteTotal,0),
		A.nCompleteTotal =ISNULL(jsb.nCompleteTotal,0)

	FROM  BILLINDEX A
	INNER JOIN (
		SELECT A.BillNumberId ,
			   A.billtype,
			   SUM(A.CompleteTotal) AS CompleteTotal,
			   SUM(A.NCompleteTotal) AS NCompleteTotal
		FROM #jstempbygoods a
		GROUP BY A.BillNumberId ,
			   A.billtype
	 )jsb ON jsb.billnumberid=a.BillNumberId AND jsb.billtype=a.BillType
	WHERE  a.Billtype not in (45,6,148,149,150,151,115,129,36,46)
			OR (a.Billtype=36 AND (@ExpenseToAr=0 OR LEFT(a.btypeid,5)='00002'))
			
			
	UPDATE A 
	SET	A.CompleteTotal = ISNULL(jsb.CompleteTotal,0),
		A.nCompleteTotal = ISNULL(jsb.nCompleteTotal,0)

	FROM  ReceiptBillIndex A
	INNER JOIN #jstempbybill jsb ON jsb.billnumberid=a.BillNumberId AND jsb.billtype=a.BillType
	
 
 

 
 DECLARE  @sql VARCHAR (max)=''
 
 SELECT @sql=@sql +'
	UPDATE '+detailtable+' 
	  SET		CompleteQty =  ' 
						+CASE WHEN billtype IN  (404,405) THEN  CAST((ISNULL(CompleteQty,0)) AS varchar(50))
							  ELSE  CAST(ABS(ISNULL(CompleteQty,0)) AS varchar(50))
						 END 
						+ ',
						CompleteTotal = ' 
						+CASE WHEN billtype IN  (404,405) THEN  CAST((ISNULL(CompleteTotal,0)) AS varchar(50))
							  ELSE  CAST(ABS(ISNULL(CompleteTotal,0)) AS varchar(50))
						 END 
						+ ',
						NCompleteTotal =  ' 
						+CASE WHEN billtype IN  (404,405) THEN  CAST((ISNULL(nCompleteTotal,0)) AS varchar(50))
							  ELSE  CAST(ABS(ISNULL(nCompleteTotal,0)) AS varchar(50))
						 END 
						+ '
				WHERE	BillNumberID = ' + CAST(BILLNUMBERID AS varchar(50)) + '
						AND [ID] = ' + CAST(DETAILID AS varchar(50))+'
	'
 FROM  #jstempbygoods
 WHERE  ISNULL(detailtable,'')<>''
 
 EXEC (@sql)
 
 END 
 --重算计算 结算状态
	UPDATE A 
	SET A.jsState= CASE WHEN A.totalmoney>0 AND (A.totalmoney-A.preferencemoney)<=ISNULL(A.CompleteTotal,0) +ISNULL(A.totalinmoney,0)
							OR  A.totalmoney<0 AND (A.totalmoney-A.preferencemoney)>=ISNULL(A.CompleteTotal,0) +ISNULL(A.totalinmoney,0)
						 THEN '2'
						 WHEN  A.totalmoney <>0 AND (A.totalinmoney<>0 OR ABS(ISNULL(A.CompleteTotal,0)) <>0) AND ABS( (A.totalmoney-A.preferencemoney))> ABS(ISNULL(A.CompleteTotal,0)+ISNULL(A.totalinmoney,0))
						 THEN '1'
						 ELSE  '0'
						 END 
						    
	FROM  BILLINDEX A
    WHERE A.RedWord =0 AND A.draft=0 AND A.jsState<>0
    

	UPDATE A 
	SET A.jsState= CASE WHEN A.totalmoney>0 AND (A.totalmoney-A.preferencemoney)<=ISNULL(A.CompleteTotal,0) +ISNULL(A.totalinmoney,0)
							OR A.totalmoney<0 AND (A.totalmoney-A.preferencemoney)>=ISNULL(A.CompleteTotal,0) +ISNULL(A.totalinmoney,0)
						 THEN '2'
						 WHEN  A.totalmoney <>0 AND (A.totalinmoney<>0 OR ABS(ISNULL(A.CompleteTotal,0)) <>0) AND ABS( (A.totalmoney-A.preferencemoney))> ABS(ISNULL(A.CompleteTotal,0)+ISNULL(A.totalinmoney,0))
						 THEN '1'
						 ELSE  '0'
						 END 

	FROM  Coupon_BillIndex A
    WHERE A.RedWord =0 AND A.draft=0 AND A.jsState<>0
			
			
	UPDATE A 
	SET A.jsState= CASE WHEN A.totalmoney>0 AND A.totalmoney<=ISNULL(A.CompleteTotal,0) 
							OR A.totalmoney<0 AND A.totalmoney>=ISNULL(A.CompleteTotal,0) 
						 THEN '2'
						 WHEN  A.totalmoney <>0 AND  ABS(ISNULL(A.CompleteTotal,0)) <>0 AND ABS( A.totalmoney)> ABS(ISNULL(A.CompleteTotal,0))
						 THEN '1'
						 ELSE  '0'
						 END 

	FROM  ReceiptBillIndex A
    WHERE A.RedWord =0 AND A.draft=0 AND A.jsState<>0
	
	--重新计算结算方式
	
	UPDATE A
	SET jsstyle= 0
	FROM  BILLINDEX A 
	WHERE A.jsStyle<>0 AND A.jsState=0
	
	UPDATE A
	SET jsstyle= 0
	FROM  ReceiptBillIndex A 
	WHERE A.jsStyle<>0 AND A.jsState=0
	
	IF EXISTS (SELECT 1 FROM  sysdata WHERE SubName='usebrandartype' AND SubValue='1')
	BEGIN 
		--重新处理 应收 应付增加减少单的表头 表体结算
		UPDATE adb
		SET	jsstyle=3,
			jsState=CASE WHEN ABS(adb.NTotal)<=ABS(adb.NCompleteTotal)+ABS(ADB.NChargeOffTotal) THEN 2 
			         WHEN ABS(adb.NTotal)>ABS(adb.NCompleteTotal)+ABS(ADB.NChargeOffTotal) THEN 1
			        ELSE 0
			        END 		
		FROM dbo.AdDebtBill adb
		INNER JOIN CompleteBrandarTotal c ON adb.BillNumberId=c.GoodsBillID  AND adb.id=c.DetailId
		
		UPDATE adb
		SET	jsstyle=1,
			jsState=CASE WHEN ABS(adb.NTotal)<=ABS(adb.NCompleteTotal)+ABS(ADB.NChargeOffTotal) THEN 2 
			         WHEN ABS(adb.NTotal)>ABS(adb.NCompleteTotal)+ABS(ADB.NChargeOffTotal) THEN 1
			        ELSE 0
			        END 		
		FROM dbo.AdDebtBill adb
		INNER JOIN 
		(
			SELECT  *
			FROM dbo.CompleteTotal C
			WHERE NOT EXISTS 
			(
				SELECT 1 FROM dbo.CompleteBrandarTotal CB WHERE CB.GoodsBillID=C.GoodsBillID AND CB.DetailId=C.GoodsBillDetailID
				UNION ALL
				SELECT 1 FROM  dbo.CompleteGoodTotal CG WHERE CG.GoodsBillID=C.GoodsBillID AND CG.Billid=C.GoodsBillDetailID
			)
	
		
		) c ON adb.BillNumberId=c.GoodsBillID  AND adb.id=c.GoodsBillDetailID
		
		
		
		--处理表头
		UPDATE a
		SET  jsstyle= 0
		FROM billindex a
		WHERE NOT  EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsstyle IN (1,3)
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)

		UPDATE a
		SET  jsstyle= 1
		FROM billindex a
		WHERE EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsstyle =1
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)
		AND NOT EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsstyle =3
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)
		
		UPDATE a
		SET  jsstyle= 4
		FROM billindex a
		WHERE EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsstyle =1
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)
		AND EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsstyle =3
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)
		
		UPDATE a
		SET  jsstyle= 3
		FROM billindex a
		WHERE NOT EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsstyle =1
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)
		AND EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsstyle =3
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)
	
		UPDATE a
		SET  jsState= 2
		FROM billindex a
		WHERE EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsState =2
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)
		AND NOT EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsState IN (0,1)
			AND a.BillNumberId=AdDebtBill.BillNumberId
		)
		
		UPDATE a
		SET  jsState= 1
		FROM billindex a
		WHERE EXISTS (
			SELECT  BillNumberId
			FROM AdDebtBill
			WHERE jsState IN (0,1)
			AND a.BillNumberId=AdDebtBill.BillNumberId
		) AND a.jsStyle<>0
	
		
	END 
	
	
 
 
 
 
 DROP  TABLE #jstemp,#jstempbybill,#jstempbygoods

END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_IniToArApTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Gp_YearProc_DateTime_IniToArApTotal
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2012-05-29
-- Description: 将期初单据数据转到应收应付期初
-- 备注：2013-9-29 增加当@stypeid传入"%",处理全部分支机构数据。
-- =============================================
CREATE PROCEDURE Gp_YearProc_DateTime_IniToArApTotal
(
	@stypeid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

--如果分支机构已经开账，则直接返回
IF EXISTS(SELECT TOP 1 1 FROM SType_UserConfig WHERE STypeID = @STypeId AND Value = '1' AND ConfigNo = '1')
	RETURN 0

DECLARE @ExpenseToAr INT=0
		
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'	
		
CREATE TABLE #billindexARAPTotal
(
		stypeid VARCHAR(50),
		btypeid VARCHAR(50),
		cid INT,
		ARTotal00  NUMERIC(24, 10) ,
		APTotal00  NUMERIC(24, 10) ,
		YSTotal00  NUMERIC(24, 10) ,
		YFTotal00  NUMERIC(24, 10) ,
		FCTotal00  NUMERIC(24, 10) ,
		GRIRTotal00  NUMERIC(24, 10) ,
		nARTotal00  NUMERIC(24, 10) ,
		nAPTotal00  NUMERIC(24, 10) ,
		nYSTotal00  NUMERIC(24, 10) ,
		nYFTotal00  NUMERIC(24, 10) ,
		NFCTotal00  NUMERIC(24, 10) ,
		NGRIRTotal00  NUMERIC(24, 10) 
)

INSERT INTO #billindexARAPTotal
	( 
			stypeid ,
			btypeid ,
			cid ,
			ARTotal00 ,
			APTotal00 ,
			YSTotal00 ,
			YFTotal00 ,
			FCTotal00,
			GRIRTotal00,
			nARTotal00 ,
			nAPTotal00 ,
			nYSTotal00 ,
			nYFTotal00,
			NFCTotal00,
			NGRIRTotal00
	)
	SELECT	stypeid ,
			btypeid ,
			cid ,
			SUM(ARTotal00),
			SUM(APTotal00),
			SUM(YSTotal00),
			SUM(YFTotal00),
			SUM(FCTotal00),
			SUM(GRIRTotal00),
			SUM(nARTotal00),
			SUM(nAPTotal00),
			SUM(nYSTotal00),
			SUM(nYFTotal00),
			SUM(NFCTotal00),
			SUM(NGRIRTotal00)
	FROM
	(
		SELECT	stypeid ,
				btypeid ,
				cid ,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					ELSE 0 
				END AS artotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney -ISNULL(ChargeOffTotal,0)
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)) 
					ELSE 0 
				END AS aptotal00,
				CASE WHEN billtype =189 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS ystotal00,
				CASE WHEN billtype =190 AND ISNULL(ChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney
					ELSE 0
				END AS yftotal00,
				0 AS FCTotal00,
				0 AS  GRIRTotal00,
				CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,213,312) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					 WHEN Billtype =36 and btypeid like '00001%' AND @ExpenseToAr=1
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS nartotal00,
				CASE WHEN billtype IN (34,161,145,84,170,212) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0) 
					 WHEN Billtype =36 and (btypeid like '00002%' OR @ExpenseToAr=0)
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0)) 
					ELSE 0 
				END AS naptotal00,
				CASE WHEN billtype =189 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nystotal00,
				CASE WHEN billtype =190 AND ISNULL(NChargeOffTotal,0)=0 --收付款单存在核销金额说明是期初往来核销单未结算完成保留下来的不能用于统计往来
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney
					ELSE 0
				END AS nyftotal00,
				0 AS NFCTotal00,
				0 AS  NGRIRTotal00
		FROM dbo.BillIndex
		WHERE	BillType IN(4,66,11,12,45,46,85,93,141,148,149,160,167,168,172,181,6,34,36,84,145,150,151,161,170,189,190,213,212,312)
				AND IsIni=1
				AND (Stypeid=@stypeid OR @stypeid='%')
		UNION ALL
		SELECT  b.stypeid ,
				a.btypeid ,
				b.cid ,
				CASE WHEN b.billtype = 116
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					ELSE 0
				END AS artotal00,
				CASE WHEN b.billtype = 128
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
					 ELSE 0
				END AS aptotal00,
				0 AS ystotal00,
				0 AS yftotal00,
				0 AS FCTotal00,
				0 AS GRIRTotal00,
				CASE WHEN b.billtype = 116
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 115
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					ELSE 0
				END AS nartotal00,
				CASE WHEN b.billtype = 128
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0)
					 WHEN b.billtype = 129
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.NChargeOffTotal,0))
					 ELSE 0
				END AS naptotal00,
				0 AS nystotal00,
				0 AS nyftotal00,
				0 AS NFcTotal00,
				0 AS NGRIRTotal00
		FROM	AdDebtBill a 
		INNER JOIN billindex b ON a.BillNumberId =b.BillNumberId
		WHERE	BillType IN(115,116,128,129)
				AND IsIni=1
				AND (B.Stypeid=@stypeid OR @stypeid='%')
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=402
				   THEN dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYFTotal00,
			   0 AS NYSTotal00,
			   CASE WHEN B.BillType=402
					THEN dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
				
		FROM SendBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   CASE WHEN B.BillType=403
				   THEN -dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
				   ELSE 0
			   END AS FCTotal00,
			   0 AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   CASE WHEN B.BillType=403
					THEN -dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.costprice )
					ELSE 0
				END AS NFCTotal00,
			   0 AS NGRIRTotal00
		FROM SendBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.Total
					ELSE dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.DiscountPrice)
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=400
					THEN CASE WHEN A.InvoiceQty=0
						 THEN A.NTotal
				    ELSE dbo.F_RoundTotal((A.Qty-A.InvoiceQty)*A.NDiscountPrice )
				    END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
		UNION ALL
		SELECT B.Stypeid,
			   B.BTypeID,
			   B.CID,
			   0 AS ARTotal00,
			   0 AS APTotal00,
			   0 AS YSTotal00,
			   0 AS YFTotal00,
			   0 AS FCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.Total
					ELSE dbo.F_RoundTotal(-(A.Qty-A.InvoiceQty)*A.DiscountPrice )
					END
			   ELSE 0
			   END AS GRIRTotal00,
			   0 AS nARTotal00,
			   0 AS nAPTotal00,
			   0 AS NYSTotal00,
			   0 AS NYFTotal00,
			   0 AS NFCTotal00,
			   CASE WHEN B.BillType=401
					THEN CASE WHEN A.InvoiceQty=0
						 THEN -A.NTotal
					ELSE dbo.F_RoundTotal(-(A.Qty-A.InvoiceQty)*A.NDiscountPrice )
					END
			   ELSE 0
			   END AS NGRIRTotal00
		FROM AppraisalBackBill A INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId
		WHERE B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
		
		UNION ALL
		SELECT 
			  B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.BillType=405
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS ARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.TaxTotalMoney-B.CompleteTotal-ISNULL(B.ChargeOffTotal,0)
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.BillType=405
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NARTotal00,
			  CASE WHEN B.BillType=404
				   THEN B.NTaxTotalMoney-B.NCompleteTotal-ISNULL(B.NChargeOffTotal,0)
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM ReceiptBillIndex B 
		WHERE  B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
		UNION ALL
		SELECT 
		B.Stypeid,
			  B.BTypeID,
			  B.CID,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.totalmoney
				   ELSE 0
			  END AS ARTotal00,
			  CASE 
				   WHEN B.ChargeOffType IN (3,4)
				   THEN B.totalmoney
				   ELSE 0
			  END AS APTotal00,
			  0 AS YSTotal,
			  0 AS YFTotal,
			  0 AS FCTotal00,
			  0 AS GRIRTotal00,
			  CASE WHEN B.ChargeOffType IN(2,5)
				   THEN B.NTotalMoney
				   ELSE 0
			  END AS NARTotal00,
			  CASE 
				   WHEN B.ChargeOffType IN (3,4)
				   THEN B.NTotalMoney
				   ELSE 0
			  END AS NAPTotal00,
			  0 AS NYSTotal,
			  0 AS NYFTotal,
			  0 AS NFCTotal00,
			  0 AS NGRIRTotal00
		 FROM dbo.BillIndex B 
		 WHERE B.BillType= 450 AND B.IsIni=1 AND (B.Stypeid=@stypeid OR @stypeid='%')
		
	) total
	GROUP BY stypeid,btypeid,cid

DELETE FROM #billindexARAPTotal WHERE ISNULL(YSTotal00,0)=0 AND ISNULL(YFTotal00,0)=0 AND ISNULL(ARTotal00,0)=0 AND ISNULL(APTotal00,0)=0 
			AND ISNULL(nYSTotal00,0)=0 AND ISNULL(nYFTotal00,0)=0 AND ISNULL(nARTotal00,0)=0 AND ISNULL(nAPTotal00,0)=0 
			AND ISNULL(NGRIRTotal00,0)=0 AND ISNULL(GRIRTotal00,0)=0 AND ISNULL(FCTotal00,0)=0 AND ISNULL(NFCTotal00,0)=0

DELETE FROM dbo.BType_ArApTotal WHERE (stypeid =@stypeid OR @stypeid='%')
INSERT INTO dbo.BType_ArApTotal
        ( BTypeID ,
          STypeID ,
          ARTotal ,
          APTotal ,
          YSTotal ,
          YFTotal ,
          ARTotal00 ,
          APTotal00 ,
          YSTotal00 ,
          YFTotal00 ,
          nARTotal ,
          nAPTotal ,
          nYSTotal ,
          nYFTotal ,
          nARTotal00 ,
          nAPTotal00 ,
          nYSTotal00 ,
          nYFTotal00 ,
          CID,
          GRIRTotal,
          FCTotal,
          GRIRTotal00,
          FCTotal00,
          NGRIRTotal,
          NFCTotal,
          NGRIRTotal00,
          NFCTotal00
        )
SELECT    BTypeID ,
          STypeID ,
          0 ,
          0 ,
          0 ,
          0 ,
          ARTotal00 ,
          APTotal00 ,
          YSTotal00 ,
          YFTotal00 ,
          0 ,
          0 ,
          0 ,
          0 ,
          nARTotal00 ,
          nAPTotal00 ,
          nYSTotal00 ,
          nYFTotal00 ,
          CID,
          0,
          0,
          GRIRTotal00,
          FCTotal00,
          0,
          0,
          NGRIRTotal00,
          NFCTotal00
FROM #billindexARAPTotal
IF @@ERROR<>0
	RAISERROR('录入应收应付期初失败！',16,1)

--写入atype_toatl
DECLARE	@AR_ID VARCHAR(50),		
		@AP_ID VARCHAR(50),
		@YS_ID VARCHAR(50),		
		@YF_ID VARCHAR(50),
		@APP_ID VARCHAR(50),
		@SEND_ID VARCHAR(50);
--将FullName换成UserCode,有些版本的FullName不一致会导致程序报错
SELECT @AR_ID=nid FROM dbo.Ac_Items WHERE UserCode='987'		
SELECT @AP_ID=nid FROM dbo.Ac_Items WHERE UserCode='2121'		
SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE UserCode='2131'		
SELECT @YF_ID=nid FROM dbo.Ac_Items WHERE UserCode='1151'
SELECT @APP_ID=NID FROM dbo.Ac_Items WHERE UserCode='2122'
SELECT @SEND_ID=NID FROM dbo.Ac_Items WHERE UserCode='1251'

DELETE FROM  AType_Total WHERE ATypeID IN (@AR_ID,@AP_ID,@YS_ID,@YF_ID,@APP_ID,@SEND_ID) AND	(stypeid =@stypeid OR @stypeid='%')
IF EXISTS(SELECT TOP 1 1 FROM BType_ARAPTotal WHERE	(stypeid =@stypeid OR @stypeid='%'))
BEGIN
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)	
	SELECT	@AR_ID,	
			STypeID,
			SUM(artotal00),
			SUM(nartotal00),
			CID
	FROM	BType_ARAPTotal
	WHERE		(stypeid =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING	SUM(artotal00)<>0
	
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)	
	SELECT	@AP_ID,	
			STypeID,
			SUM(aptotal00),
			SUM(naptotal00),
			CID
	FROM	BType_ARAPTotal
	WHERE		(stypeid =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING SUM(aptotal00)<>0
	
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)	
	SELECT	@YS_ID,	
			STypeID,
			SUM(YSTotal00),
			SUM(nYSTotal00),
			CID
	FROM	BType_ARAPTotal
	WHERE		(stypeid =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING	SUM(YSTotal00)<>0
	
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)	
	SELECT	@YF_ID,	
			STypeID,
			SUM(YFTotal00),
			SUM(nYFTotal00),
			CID
	FROM	BType_ARAPTotal
	WHERE		(stypeid =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING SUM(YFTotal00)<>0
	
	--暂估
	INSERT INTO AType_Total
	(
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)
	SELECT @APP_ID,
			STypeID,
			SUM(GRIRTotal00),
			SUM(NGRIRTotal00),
			CID
	FROM BType_ArApTotal
	WHERE (STypeID =@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING SUM(GRIRTotal00)<>0
	
	--发出
	INSERT INTO AType_Total
	(	
		ATypeID,
		STypeID,
		Total00,
		Ntotal00,
		CID
	)
	SELECT @SEND_ID,
			STypeID,
			SUM(FCTotal00),
			SUM(NFCTotal00),
			CID
	FROM BType_ArApTotal
	WHERE (STypeID=@stypeid OR @stypeid='%')
	GROUP BY CID,STypeID
	HAVING SUM(FCTotal00)<>0
END 	


DROP TABLE #billindexARAPTotal
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_Log]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-日志的处理
	EXEC Gp_YearProc_DateTime_Log 	@yearendmode,
									@chkcompleterequestbill,
									@carefinancedata,
									@delDraft,
									@delOrder,
									@delEndOrder,
									@chrRecPrice,
									@delPriceTrack,
									@delEventLog,
									@delmessage,
									@unfinishedinvoice,
									@chrRecSalePrice,
									@chrRecSTypeBuyPrice,
									@chrRecSTypeSalePrice,
									@chrSTypePriceTrack,
									@unfinishedposbill,
									@chrStockAge,
									@chrStock,
									@chrStype,
									@chrGroup,
									@delstoporder,
									@carryOverBillexcess,
									@clearCompleteAllotApply,
									@clearNoCompleteAllotApply,
									@clearnocompleteonshelves,
									@clearnocompletepickandtransport,
									@logid
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_Log
(
	@yearendmode							CHAR(1) = '1',		-- 1 - 按余额转期初；0 - 按单据转期初
	@chkcompleterequestbill					CHAR(1) = '1',		-- 1 - 清除已完成请购单；0 - 清除所有请购单
	@carefinancedata						INT	,				-- 2 - 年结存后财务数据为空；1 - 结转当前财务数据；0 - 保持原来的判断
	@delDraft								CHAR(1) = '1',		-- 1 - 删除草稿数据；0 - 不删除
	@delOrder								CHAR(1) = '1',		-- 1 - 删除定单数据；0 - 不删除
	@delEndOrder							CHAR(1) = '0',		-- 1 - 删除已完成订单；0 - 不删除
	@chrRecPrice							CHAR(1) = '0',		-- 1 - 删除商品最近进价；0 - 不删除
	@delPriceTrack							CHAR(1) = '0',		-- 1 - 清除价格跟踪信息；0 - 不清除
	@delEventLog							CHAR(1) = '0',		-- 1 - 清除操作日志；0 - 不清除
	@delmessage								CHAR(1) = '0',		-- 1 - 清除聊天记录；0 - 不清除
	@unfinishedinvoice						CHAR(1) = '1',		-- 1 - 保留未完成开票单据；0 - 不保留
	@chrRecSalePrice					    CHAR(1) = '1',		-- 1 - 年结存清空最近售价；0 - 不清空最近售价
	@chrRecSTypeBuyPrice				    CHAR(1) = '1',		-- 1 - 年结存清除商品分支机构间最近进价：0 - 不清空商品分支机构间商品最近进价
	@chrRecSTypeSalePrice				    CHAR(1) = '1',		-- 1 - 年结存清除商品分支机构间最近售价：0 - 不清空商品分支机构间商品最近售价
	@chrSTypePriceTrack						CHAR(1) = '1',		-- 1 - 年结存清除分支机构间价格跟踪信息: 0 - 不清空分支机构间价格跟踪信息
	@unfinishedposbill						CHAR(1) = '1',		-- 1 - 清除所有小票数据；0 - 清除已结转小票数据
	@chrStockAge							CHAR(1) = '0',		-- 1 - 关心库龄数据; 0 -不关心库龄数据
	@chrStock								CHAR(1) = '0',		-- 1 - 按照仓库结转期初库龄数据; 0 不转
	@chrStype								CHAR(1) = '0',		-- 1 - 按照分支机构结转期初库龄数据; 0 不转	
	@chrGroup								CHAR(1) = '0',		-- 1 - 按照集团结转期初库龄数据; 0 不转
	@delstoporder							CHAR(1) = '0',		-- 1 - 清除中止订单;0清除中止订单
	@carryOverBillexcess					CHAR(1) = '0',		-- 1 - 业务单据超收超付及收付款单未结算完金额结转至期初应收应付减少单；0 - 不转
	@clearCompleteAllotApply				CHAR,				--	 -是否清除已完成的调货申请单 0-不清除 1-清除
	@clearNoCompleteAllotApply				CHAR,				--	 -是否清除未完成的调货申请单 0-不清除 1-清除
    @clearCompleteGetBillApply              char,                   --是否清除已完成的要货申请单 0-不清除 1-清除
	@clearNoCompleteGetBillApply            char,               --是否清除未完成要货申请单 0-不清除 1-清除
    @clearnocompleteonshelves				CHAR(1) = '0',		--	 -是否清除未完成上架的单据 0-不清除 1-清除
    @clearnocompletepickandtransport		CHAR(1) = '0',		--   -是否清除未完成拣货/运输的单据 0-不清除 1-清除
	@logid									INT=0				--   -年结存日志记录ID
)
AS
SET NOCOUNT ON

IF @logid>0
BEGIN
	DECLARE @logdata VARCHAR(2000)
	DECLARE @dobill VARCHAR(4)
	DECLARE @chkallrequestbill VARCHAR(4)
	DECLARE @iscare VARCHAR(4)
	SET @dobill='0'
	SET @chkallrequestbill='0'
	SET @iscare='0'
	IF @yearendmode='0'--按单据转期初
		SET @dobill='1'
	IF @chkcompleterequestbill='0'--清除所有请购单
		SET @chkallrequestbill='1'
	IF @carefinancedata>0	--关心财务数据
		SET @iscare='1'
	SET @logdata='dobill='+@dobill+';dobalance='+@yearendmode+';clearDraft='+@delDraft
	+';clearOrder='+@delOrder+';clearCompleteOrder='+@delEndOrder+';chkRecPrice='+@chrRecPrice
	+';chkPriceTrack='+@delPriceTrack+';chkEventLog='+@delEventLog+';chkclearmessage='+@delmessage
	+';unfinishedinvoice='+@unfinishedinvoice+';chkclearrecsaleprice='+@chrRecSalePrice+';chkrecstypebuyprice='+@chrRecSTypeBuyPrice
	+';chkrecstypesaleprice='+@chrRecSTypeSalePrice+';chkstypepricetrack='+@chrSTypePriceTrack+';chkcompleterequestbill='+@chkcompleterequestbill
	+';chkallrequestbill='+@chkallrequestbill+';unfinishedposbill='+@unfinishedposbill+';stockage='+@chrStockAge
	+';stock='+@chrStock+';stype='+@chrStype+';group='+@chrGroup
	+';chkdelstoporder='+@delstoporder+';chkbillexcess='+@carryOverBillexcess
	+';iscare='+@iscare+';carefinancedata='+CAST(@carefinancedata AS varchar(4))
	+';clearCompleteAllotApply=' + @clearCompleteAllotApply + ';clearNoCompleteAllotApply=' + @clearNoCompleteAllotApply
	+';clearCompleteGetBillApply=' +@clearCompleteGetBillApply + ';clearNoCompleteGetBillApply=' + @clearNoCompleteGetBillApply
	UPDATE dbo.EventLog SET LogData=@logdata WHERE id=@logid
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_OldBill_Clone_Del]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_OldBill_Clone_Del]
GO


/*
	删除老单据相关数据
*/
CREATE       PROCEDURE Gp_YearProc_DateTime_OldBill_Clone_Del

--@encode$--
AS
SET NOCOUNT ON 

	TRUNCATE TABLE Old_BillMulAccount
	
	TRUNCATE TABLE Old_GatheringBill
	
	TRUNCATE TABLE Old_PayBill
	
	TRUNCATE TABLE Old_CompleteTotal
	
	TRUNCATE TABLE Old_CompleteGoodTotal
	
	TRUNCATE TABLE Old_Bill
	
	TRUNCATE TABLE Old_ListTable
	
	TRUNCATE TABLE Old_PreBill
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_PerformanceDistribution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_PerformanceDistribution]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-业绩分配
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_PerformanceDistribution
AS
SET NOCOUNT ON

SELECT * INTO #PerformanceDistribution FROM PerformanceDistribution  WHERE billnumberid IN(SELECT billnumberid FROM billindex )
TRUNCATE TABLE PerformanceDistribution
INSERT INTO PerformanceDistribution (BillNumberId,PTypeID,ETypeID,Proportion,Total,CreateDate,Checke,Comment)  SELECT BillNumberId,PTypeID,ETypeID,Proportion,Total,CreateDate,Checke,Comment FROM #PerformanceDistribution ORDER BY ID ASC
DROP TABLE #PerformanceDistribution	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_PrintAndAttachFiles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_PrintAndAttachFiles]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_PrintAndAttachFiles
AS
SET NOCOUNT ON

SELECT billnumberid,billtype INTO #PrintTmp 
FROM (
		SELECT BillNumberId,BillType FROM  BillIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  OrderIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  requestindex
		UNION ALL
		SELECT BillNumberId,BillType FROM FaPiaoBillIndex
		UNION ALL
		SELECT BillNumberId,BillType FROM  serialadjustindex
		UNION ALL
		SELECT BillNumberId,164 FROM  TCBillindex
		UNION ALL
		SELECT BillNumberId,BillType FROM  V_LendFace
		UNION ALL
		SELECT ProduceModelID,127 FROM  producemodelindex
		UNION ALL
		SELECT stockCheckID,306 FROM  StockCheckIndex
		UNION ALL 
		SELECT BillNumberId,BillType FROM CM_CarUseIndex
		UNION ALL 
		SELECT BillNumberId,BillType FROM CM_FeeIndex 
) A
		
SELECT a.* INTO #printrecord 
FROM printrecord a 
INNER JOIN  #PrintTmp b ON a.BillNumberId=b.BillNumberId and a.BillType=b.BillType
TRUNCATE TABLE printrecord
INSERT INTO printrecord SELECT * FROM #printrecord	

SELECT a.* into #AddPrintCountRecord
FROM AddPrintCountRecord a 
INNER JOIN  #PrintTmp b ON a.BillNumberId=b.BillNumberId and a.BillType=b.BillType
TRUNCATE TABLE AddPrintCountRecord
INSERT INTO AddPrintCountRecord SELECT * FROM #AddPrintCountRecord

DECLARE @columns VARCHAR(max)=''
SELECT * INTO #BillAttachFiles FROM BillAttachFiles 
WHERE EXISTS (SELECT 1 FROM #PrintTmp WHERE BillNumberId=BillAttachFiles.BillNumberId AND BillType=BillAttachFiles.BillType)
TRUNCATE TABLE dbo.BillAttachFiles
SET IDENTITY_INSERT dbo.BillAttachFiles ON
SET @columns=dbo.f_getallcolumns('BillAttachFiles')
EXEC('INSERT INTO BillAttachFiles ('+@columns+') SELECT '+@columns+ ' FROM #BillAttachFiles')
SET IDENTITY_INSERT BillAttachFiles OFF

SELECT * INTO #BillAttachFileslog FROM BillAttachFileslog 
WHERE EXISTS (SELECT 1 FROM #PrintTmp WHERE BillNumberId=BillAttachFileslog.BillNumberId AND BillType=BillAttachFileslog.BillType)
TRUNCATE TABLE dbo.BillAttachFileslog
SET IDENTITY_INSERT dbo.BillAttachFileslog ON
SET @columns=dbo.f_getallcolumns('BillAttachFileslog')
EXEC('INSERT INTO BillAttachFileslog ('+@columns+') SELECT '+@columns+ ' FROM #BillAttachFileslog')
SET IDENTITY_INSERT BillAttachFileslog OFF

DROP TABLE #PrintTmp,#AddPrintCountRecord,#printrecord,#BillAttachFiles,#BillAttachFileslog

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_ReCal_AType_Total]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_ReCal_AType_Total]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-重算AType_Total
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_ReCal_AType_Total
(
	@yearendDatetime VARCHAR(20)			--   -年结存的日期		
)
AS
SET NOCOUNT ON

--重算项目余额
IF EXISTS(
	SELECT a.ATypeID
	FROM dbo.AType_Total a
	LEFT JOIN
	(
		SELECT AtypeId,STypeID,CID,SUM(TOTAL) Total,SUM(NTOTAL) NTotal
		FROM dbo.ListTable
		GROUP BY AtypeId,STypeID,CID
	) b
	ON a.ATypeID=b.AtypeId
	AND a.STypeID=b.STypeID
	AND a.CID=b.CID
	AND a.Total<>a.Total00+ISNULL(b.Total,0)
)
BEGIN
	UPDATE dbo.AType_Total
	SET 
		Total=AType_Total.Total00+ISNULL(b.Total,0),
		NTotal=AType_Total.NTotal00+ISNULL(b.NTotal,0)
	FROM
	(
		SELECT AtypeId,STypeID,CID,SUM(TOTAL) Total,SUM(NTOTAL) NTotal
		FROM dbo.ListTable
		GROUP BY AtypeId,STypeID,CID
	) b
	WHERE AType_Total.ATypeID=b.AtypeId
	AND AType_Total.STypeID=b.STypeID
	AND AType_Total.CID=b.CID
	AND AType_Total.Total<>AType_Total.Total00+ISNULL(b.Total,0)
END
-----------------------------------------处理数据 START--------------------------------------------------------------
UPDATE	T
SET		Total00 += ISNULL(a.Total,0),
		Ntotal00 += ISNULL(a.Ntotal,0)
FROM AType_Total T
LEFT JOIN 
(
	SELECT AtypeId ,
           SUM(Total) AS total ,
           STypeID ,
           CID ,
           SUM(Ntotal) AS ntotal
	FROM dbo.ListTable
	WHERE BillDate < @yearendDatetime
	GROUP BY AtypeId,STypeID,CID
) a  ON a.ATypeID = T.ATypeID AND a.CID = T.CID AND a.STypeID = T.STypeID
----------会计科目相关----------	
DECLARE @lr_id INT,@cid INT --本位币
SELECT @lr_id=nid FROM dbo.Ac_Items WHERE USERcode='3141'  --未分配利润

SELECT  @cid=cid FROM dbo.Ac_Currency WHERE Sysrow=1

CREATE TABLE #atypeid(stypeid VARCHAR(50),lrtotal  NUMERIC(24, 10) )
INSERT INTO #atypeid
        ( stypeid, lrtotal )
SELECT DISTINCT stypeid,0
FROM dbo.AType_Total

UPDATE T
SET	lrtotal=ISNULL(a.total,0)-ISNULL(B.total,0)
FROM #atypeid T
LEFT JOIN 
(
	SELECT stypeid,ISNULL(sum(total),0) AS total
	FROM dbo.ListTable 
	WHERE ATypeID IN(SELECT nId FROM dbo.Ac_Items WHERE nTypeId like '00003%' and sonnum=0)
		AND BillDate < @yearendDatetime
	GROUP BY STypeID
) a ON a.stypeid=T.stypeid
LEFT JOIN
(
	SELECT stypeid,ISNULL(sum(total),0) AS total
	FROM dbo.ListTable 
	WHERE ATypeID IN(SELECT nId FROM dbo.Ac_Items WHERE nTypeId like '00004%' and sonnum=0)
		AND BillDate < @yearendDatetime
	GROUP BY STypeID
) b ON b.stypeid=T.stypeid

MERGE INTO dbo.AType_Total AS target
USING #atypeid AS source
ON source.stypeid=target.STypeID AND target.ATypeID=@lr_id AND target.CID=@cid
WHEN MATCHED THEN UPDATE SET target.Total00+=SOURCE.lrtotal,target.nTotal00+=SOURCE.lrtotal
WHEN NOT MATCHED THEN INSERT(atypeid,stypeid,total00,ntotal00,cid)VALUES(@lr_id,SOURCE.stypeid,SOURCE.lrtotal,SOURCE.lrtotal,@cid);

DROP TABLE #atypeid
	
--收入和支出结转余额为0
UPDATE	AType_Total SET Total00 = 0,Ntotal00=0 
WHERE	ATypeID IN (SELECT nid FROM dbo.Ac_Items WHERE TypeName IN ('G','E'))

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_ReCal_BType_ArApTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_ReCal_BType_ArApTotal]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-重算BType_Total、Brandar_ArApTotal、BType_ArApTotal
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_ReCal_BType_ArApTotal
(
	@yearendmode	CHAR(1) = '1'	,	-- 1 - 按余额转期初；0 - 按单据转期初
	@yearendDatetime        VARCHAR(20)		
)
AS
SET NOCOUNT ON

--将预收预付的余额写到期初预收预付单据,将应收应付余额写到期初单据中
IF not EXISTS (SELECT TOP 1 1 FROM  dbo.sysdata WHERE SubName='usebrandartype' AND SubValue='1')
	EXEC Gp_YsyfToInibill_DateTime @yearendmode ,@yearendDatetime
ELSE
BEGIN 
	--启用品牌  只能按余额结转 修改品牌往来期初汇总值	
	EXEC	Gp_BrandarYsyfToInibill_DateTime '1' ,@yearendDatetime

END 

--修改往来期初汇总值	
exec GP_ReCalBtypeArAp_YearProcDateTime  @yearendDatetime
 
-- 年结处理内部应收 外部已经处理了
--exec GP_DateTime_Stype_InnerARTotal @yearendDatetime

--先删除 最后重算往来期初的数据 
--DELETE FROM IniBType_ArApTotal	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Gp_YearProc_DateTime_ReCal_Stocks]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Gp_YearProc_DateTime_ReCal_Stocks]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-库存相关计算
	EXEC Gp_YearProc_DateTime_ReCal_Stocks  @chrStockAge,
											@chrStock,
											@chrStype,
											@chrGroup,
											@OperatorId,
											@yearendDatetime
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_ReCal_Stocks
(
	@chrStockAge	CHAR(1) = '0',		--1 - 关心库龄数据; 0 -不关心库龄数据
	@chrStock			CHAR(1) = '0',		--1 - 按照仓库结转期初库龄数据; 0 不转
	@chrStype			CHAR(1) = '0',		--1 - 按照分支机构结转期初库龄数据; 0 不转
	@chrGroup		CHAR(1) = '0',		--1 - 按照集团结转期初库龄数据; 0 不转
	@OperatorId		VARCHAR(50), 		-- 操作员ID
	@yearEndDateTime	DATE			--年结时间
)
AS
SET NOCOUNT ON

DECLARE	
	@Average	SMALLINT=0,--移动加权平均算法
	@Fifo			SMALLINT=1,--先进先出
	@Lifo			SMALLINT=2,--后进先出
	@Hand		SMALLINT=3,--手工指定法
	@nCostingMethod	INT--系统实际成本核算法

EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output


BEGIN--=====================================库龄期初【BEGIN】=================================

--关心库龄数据begin
IF @chrStockAge = '1'
	BEGIN
		CREATE TABLE #TmpStockAge
		(
			BillnumberId		VARCHAR(50),
			PTypeId				VARCHAR(50),
			KTypeId				VARCHAR(50),
			InStockDate			DATETIME,
			BillCode			VARCHAR(200),
			BillName			VARCHAR(200),
			BillType			INT ,
			StockAge			NUMERIC(24,10),
			Qty					NUMERIC(24,10),
			Total				NUMERIC(24,10)
			--MBillType			INT
		)
		IF @chrStock = '1'--按仓库
			BEGIN
				INSERT INTO #TmpStockAge 
				EXEC Web_QueryStockAgeAnalyseDetail @OperatorId=@OperatorId,@EndDate=@yearEndDateTime,@STypeId='',@ptypeCategoryID='',@PTypeId='',@KTypeId='',@ByType=1
				
				--删除库龄小于0天的数据
				DELETE #TmpStockAge WHERE qty <= 0

				--删除【仓库】 期初库龄相关信息
				TRUNCATE TABLE dbo.IniStockAgeStock
				
				--插入期初库龄表
				INSERT INTO dbo.IniStockAgeStock
				(
					KtypeID,
					PtypeID, 
					InStockDate, 
					StockAge, 
					Qty, 
					Total
				)
				SELECT
					 KtypeID, 
					 PtypeID, 
					 CONVERT(VARCHAR(10),InStockDate,23) , 
					 StockAge, 
					 Qty,
					 Total 
				FROM #TmpStockAge
				
				--清除临时表
				TRUNCATE TABLE #TmpStockAge
			END

		IF @chrStype = '1'--按分支机构
			BEGIN
				INSERT INTO #TmpStockAge 
				EXEC Web_QueryStockAgeAnalyseDetail @OperatorId=@OperatorId,@EndDate=@yearEndDateTime,@STypeId='',@ptypeCategoryID='',@PTypeId='',@KTypeId='',@ByType=2

				--删除库龄小于0天的数据
				DELETE #TmpStockAge WHERE qty <= 0
				
				--删除【分支机构】 期初库龄相关信息
				TRUNCATE TABLE dbo.IniStockAgeStype

				--插入分支机构期初库龄表
				INSERT INTO dbo.IniStockAgeStype
				(
					KtypeID,
					PtypeID, 
					InStockDate, 
					StockAge, 
					Qty, 
					Total
				)
				SELECT
					 KtypeID, 
					 PtypeID, 
					 CONVERT(VARCHAR(10),InStockDate,23) , 
					 StockAge, 
					 Qty,
					 Total 
				FROM #TmpStockAge

				--清除临时表
				TRUNCATE TABLE #TmpStockAge
			END

		IF @chrGroup = '1'--按集团
			BEGIN
				INSERT INTO #TmpStockAge 
				EXEC Web_QueryStockAgeAnalyseDetail @OperatorId=@OperatorId,@EndDate=@yearEndDateTime,@STypeId='',@ptypeCategoryID='',@PTypeId='',@KTypeId='',@ByType=3
				
				--删除库龄小于0天的数据
				DELETE #TmpStockAge WHERE qty <= 0

				--删除【集团】 期初库龄相关信息
				TRUNCATE TABLE dbo.IniStockAgeGroup
				
				--插入期初库龄表
				INSERT INTO dbo.IniStockAgeGroup
				(
					KtypeID,
					PtypeID, 
					InStockDate, 
					StockAge, 
					Qty, 
					Total
				)
				SELECT
					 KtypeID, 
					 PtypeID, 
					 CONVERT(VARCHAR(10),InStockDate,23) , 
					 StockAge, 
					 Qty,
					 Total 
				FROM #TmpStockAge

				--清除临时表
				TRUNCATE TABLE #TmpStockAge
			END

		DROP TABLE #TmpStockAge
	END
ELSE 
	BEGIN
		--删除【仓库/分支机构/集团】 期初库龄相关信息
		TRUNCATE TABLE dbo.IniStockAgeStock
		TRUNCATE TABLE dbo.IniStockAgeStype
		TRUNCATE TABLE dbo.IniStockAgeGroup
	END

--=====================================库龄期初【END】=================================
END;

BEGIN--=====================================实际库存期初【BEGIN】=================================

CREATE TABLE #IniGoodsStocks
  (
  PtypeId        VARCHAR (50) ,
  KtypeId        VARCHAR (50) ,
  JobNumber      VARCHAR (20) ,
  Qty            NUMERIC (24,10),
  Price          NUMERIC (24,10),
  Total          NUMERIC (24,10),
  GoodsNumber    VARCHAR (100) ,
  ProduceDate    VARCHAR (50) ,
  ValidDate      VARCHAR (50) ,
  GoodsBTypeID   VARCHAR (50) ,
  Goodsorder      VARCHAR (50)
  )

IF @nCostingMethod <> 3
BEGIN
INSERT INTO #IniGoodsStocks(PtypeId,KtypeId,JobNumber,Qty,Price,Total,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,Goodsorder )
SELECT  B.PtypeId,B.KtypeID,B.JobNumber,B.Qty,B.Price,B.Total,B.GoodsNumber,B.ProduceDate,B.ValidDate,B.GoodsBTypeID,Goodsorder 
FROM  (
		SELECT  PtypeId,
				KtypeId,
				'' AS JobNumber,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				sum(Qty)qty,
				0 as Price,
				SUM(Total)total,
				'' AS GoodsBTypeID,
				CASE WHEN @nCostingMethod = 0 THEN '' ELSE 1 END  AS Goodsorder 			
		FROM iniGoodsStocks 
		GROUP BY	 
				PtypeId,
				KtypeId,
				GoodsNumber,
				ProduceDate,
				ValidDate	
)B  --库存期初值


MERGE INTO #iniGoodsStocks I
USING (
		SELECT	a.PtypeId,
				a.KtypeId,
				SUM(a.Qty) AS QTY,
				SUM(a.CostTotal) AS CostTotal,
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate,
				CASE WHEN @nCostingMethod = 0 THEN '' ELSE 1 END  AS Goodsorder 
		FROM	dbo.InOutstocktable a,dbo.BillIndex b
		WHERE	a.BillDate<@yearEndDateTime
				AND a.KtypeId<>'10000'
				AND a.billnumberid=b.billnumberid
				AND b.RedWord=0
		GROUP BY 
				a.PtypeId,
				a.KtypeId,						
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate		
)inout ON  I.PtypeId = inout.PtypeId 
			AND i.ktypeid = inout.KtypeId 
			AND i.GoodsNumber = inout.GoodsNumber 
			AND i.ProduceDate = inout.ProduceDate 
			AND i.ValidDate = inout.ValidDate
			AND i.Goodsorder= inout.Goodsorder
WHEN MATCHED THEN 
	UPDATE SET I.qty+=inout.qty,i.Total += inout.costtotal
WHEN NOT MATCHED THEN
	INSERT (PtypeId,KtypeID,JobNumber,Qty,Price,Total,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,Goodsorder )
	VALUES(inout.PtypeId,inout.KtypeID,'',inout.Qty,0,inout.CostTotal,inout.GoodsNumber,inout.ProduceDate,inout.ValidDate,'',CASE WHEN @nCostingMethod = 0 THEN '' ELSE 1 END );
	
UPDATE #iniGoodsStocks SET price = CASE WHEN qty = 0 THEN 0 ELSE ROUND(total/qty,4) END	

END
ELSE 
BEGIN
INSERT INTO #IniGoodsStocks(PtypeId,KtypeId,JobNumber,Qty,Price,Total,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,Goodsorder)
SELECT  B.PtypeId,B.KtypeID,B.JobNumber,B.Qty,B.Price,B.Total,B.GoodsNumber,B.ProduceDate,B.ValidDate,B.GoodsBTypeID,Goodsorder
FROM  (
		SELECT  PtypeId,
				KtypeId,
				'' AS JobNumber,
				qty,
				Price,
				total,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				'' AS GoodsBTypeID,
				1 AS Goodsorder
		FROM iniGoodsStocks 		
)B  --库存期初值

MERGE INTO #iniGoodsStocks I
USING (
		SELECT	a.PtypeId,
				a.KtypeId,
				SUM(a.Qty)QTY,
				a.CostPrice  AS price,
				SUM(a.CostTotal)CostTotal,
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate,
				1 AS goodsorder
		FROM	dbo.InOutstocktable a,dbo.BillIndex b
		WHERE	a.BillDate<@yearEndDateTime
				AND a.KtypeId<>'10000'
				AND a.billnumberid=b.billnumberid
				AND b.RedWord=0
		GROUP BY 
				a.PtypeId,
				a.KtypeId,						
				a.GoodsNumber,
				a.ProduceDate,
				a.ValidDate,
				a.CostPrice
)inout ON  I.PtypeId = inout.PtypeId 
			AND i.ktypeid = inout.KtypeId 
			AND i.GoodsNumber = inout.GoodsNumber 
			AND i.ProduceDate = inout.ProduceDate 
			AND i.ValidDate = inout.ValidDate
			AND i.Price=inout.price
			AND i.Goodsorder = inout.goodsorder
WHEN MATCHED THEN 
	UPDATE SET I.qty+=inout.qty,i.Total += inout.costtotal
WHEN NOT MATCHED THEN
	INSERT (PtypeId,KtypeID,JobNumber,Qty,Price,Total,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID,Goodsorder)
	VALUES(inout.PtypeId,inout.KtypeID,'',inout.Qty,inout.price,inout.CostTotal,inout.GoodsNumber,inout.ProduceDate,inout.ValidDate,'','1');
END

TRUNCATE TABLE iniGoodsStocks
INSERT INTO iniGoodsStocks(PtypeId,KtypeID,JobNumber,OutFactoryDate,Qty,Price,Total,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID)
SELECT  PtypeId,KtypeID,'' JobNumber,@yearEndDateTime OutFactoryDate,Qty,Price,Total,GoodsOrder,GoodsNumber,ProduceDate,ValidDate,GoodsBTypeID 
FROM	#iniGoodsStocks
WHERE	Qty <> 0
		OR Total <> 0


CREATE TABLE #IniGOODSSTOCKS_QTY(
	[PTypeID] [VARCHAR](50) NULL,
	[KTypeID] [VARCHAR](50) NULL,
	[CargoID] [INT] NULL,
	[ItemID] [INT] NULL,
	[Iscombined] [BIT] NULL,
	[GoodsNumber] [VARCHAR](100) NULL,
	[ProduceDate] [VARCHAR](50) NULL,
	[ValidDate] [VARCHAR](50) NULL,
	[Qty] [NUMERIC](24, 10) NULL,
	[NQty] [NUMERIC](24, 10) NULL,
	[GoodsCostPrice] [NUMERIC](24, 10) NULL,
	[LockNumber] [NUMERIC](24, 10) NULL
) 

INSERT INTO	#iniGoodsStocks_Qty(PtypeId,KtypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,LockNumber)
SELECT	PtypeId,KtypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,LockNumber 
FROM	Ini_GOODSSTOCKS_QTY--库存期初值

--移动加权、先进先出、后进先出
IF @nCostingMethod <> 3
BEGIN
	MERGE INTO #iniGoodsStocks_Qty I
	USING (
			SELECT	O.PtypeId,
					O.KtypeId,
					O.CargoID,
					O.ItemID,
					O.IsCombined,
					O.GoodsNumber,
					O.ProduceDate,
					O.ValidDate,
					SUM(O.Qty) AS Qty,
					SUM(O.NQty) AS NQty,					
					LockNumber = SUM(CASE WHEN O.BillType=11 THEN ISNULL(S.LockNumber,0) WHEN O.BillType=12 THEN ISNULL(P.LockNumber,0) ELSE 0 END)
			FROM InOutstocktable O
			LEFT JOIN PT_SaleOrderLockDetail S ON  S.BillNumberId=O.BillNumberId AND O.BillType=11
			LEFT JOIN PT_Combin_OrderBillDetail  P ON  P.BillNumberId=O.BillNumberId AND O.BillType=12
			WHERE	O.BillDate<@yearEndDateTime
					AND O.KtypeId<>'10000'
			GROUP BY 
					O.PtypeId,
					O.KtypeId,
					O.CargoID,
					O.ItemID,
					O.IsCombined,
					O.GoodsNumber,
					O.ProduceDate,
					O.ValidDate
	)inout ON   I.PtypeId = inout.PtypeId 
				AND I.KtypeId=inout.KtypeId
				AND I.CargoID=inout.CargoID
				AND I.ItemID=inout.ItemID
				AND I.IsCombined=inout.IsCombined
				AND I.GoodsNumber=inout.GoodsNumber
				AND I.ProduceDate=inout.ProduceDate
				AND I.ValidDate=inout.ValidDate				
	WHEN MATCHED THEN
		UPDATE SET	I.Qty+=inout.Qty,I.NQty+=inout.NQty,I.LockNumber+=inout.LockNumber
	WHEN NOT MATCHED THEN
		INSERT (PtypeId,KtypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,LockNumber)
		VALUES (inout.Ptypeid,inout.ktypeid,inout.cargoid,inout.itemid,inout.iscombined,inout.goodsnumber,inout.ProduceDate,inout.ValidDate,inout.Qty,inout.NQty,0,inout.LockNumber);
END
ELSE
BEGIN
	MERGE INTO #iniGoodsStocks_Qty I
	USING (
			SELECT	B.*
			FROM	(
						SELECT	O.PtypeId,
								O.KtypeId,
								O.CargoID,
								O.ItemID,
								O.IsCombined,
								O.GoodsNumber,
								O.ProduceDate,
								O.ValidDate,
								SUM(O.Qty) AS Qty,
								SUM(O.NQty) AS NQty,
								O.CostPrice AS GoodsCostPrice,
								LockNumber = SUM(CASE WHEN O.BillType=11 THEN ISNULL(S.LockNumber,0) WHEN O.BillType=12 THEN ISNULL(P.LockNumber,0) ELSE 0 END)
						FROM InOutstocktable O
						LEFT JOIN PT_SaleOrderLockDetail S ON  S.BillNumberId=O.BillNumberId AND O.BillType=11
						LEFT JOIN PT_Combin_OrderBillDetail  P ON  P.BillNumberId=O.BillNumberId AND O.BillType=12
						WHERE	O.BillDate<@yearEndDateTime
								AND O.KtypeId<>'10000'
						GROUP BY 
								O.PtypeId,
								O.KtypeId,
								O.CargoID,
								O.ItemID,
								O.IsCombined,
								O.GoodsNumber,
								O.ProduceDate,
								O.ValidDate,
								O.CostPrice
			)B WHERE B.Qty <> 0
	)inout ON   I.PtypeId = inout.PtypeId 
				AND I.KtypeId=inout.KtypeId
				AND I.CargoID=inout.CargoID
				AND I.ItemID=inout.ItemID
				AND I.IsCombined=inout.IsCombined
				AND I.GoodsNumber=inout.GoodsNumber
				AND I.ProduceDate=inout.ProduceDate
				AND I.ValidDate=inout.ValidDate
				AND I.GoodsCostPrice = inout.GoodsCostPrice
	WHEN MATCHED THEN
		UPDATE SET	I.Qty+=inout.Qty,I.NQty+=inout.NQty,I.LockNumber+=inout.LockNumber
	WHEN NOT MATCHED THEN
		INSERT (PtypeId,KtypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,LockNumber)
		VALUES (inout.Ptypeid,inout.ktypeid,inout.cargoid,inout.itemid,inout.iscombined,inout.goodsnumber,inout.ProduceDate,inout.ValidDate,inout.Qty,inout.NQty,inout.GoodsCostPrice,inout.LockNumber);
END

TRUNCATE TABLE Ini_GOODSSTOCKS_QTY

INSERT INTO Ini_GOODSSTOCKS_QTY(PtypeId,KtypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,LockNumber)
SELECT	PtypeId,KtypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,LockNumber 
FROM	#iniGoodsStocks_Qty
WHERE	Qty <> 0

DELETE FROM iniGoodsStocks WHERE Qty = 0 AND Total = 0

---------------------------------------库存数据处理完成---------------------------------------

--启用发票立账
IF EXISTS(SELECT SubNo FROM sysdata WHERE SubName='isinvoice' AND SubValue=1)
	BEGIN
		DELETE FROM Q
		FROM Ini_GOODSSTOCKS_QTY Q
		WHERE 
			Qty=0 
			AND NQty=0 
			AND Not EXISTS(SELECT a.PtypeId FROM IniGoodsStocks a WHERE a.PtypeId=Q.PTypeID AND a.KtypeId=Q.KTypeID )
	END
ELSE
	BEGIN
		DELETE FROM ini_GOODSSTOCKS_QTY WHERE Qty=0 AND NQty=0
	END


UPDATE iniGoodsStocks SET Price = 0 WHERE Qty = 0

UPDATE	iniGoodsStocks SET Total = CAST(Total AS  NUMERIC(24, 10) )

UPDATE	iniGoodsStocks SET Price = dbo.F_RoundPrice(Total/Qty) WHERE Qty <> 0 AND @nCostingMethod<>@HAND


 DROP TABLE #iniGoodsStocks,#iniGoodsStocks_Qty
--=====================================实际库龄【END】=================================
END;


BEGIN--=====================================实物库存期初【BEGIN】=================================
SELECT * INTO #IniFactStocks FROM IniFactStocks
SELECT * INTO #IniFactStocks_Qty FROM IniFactStocks_Qty

TRUNCATE TABLE IniFactStocks
INSERT INTO dbo.IniFactStocks
( 
	PtypeId ,
	KtypeId ,
	Qty 
)
SELECT
	PTypeId,
	KTypeId,
	SUM(Qty) Qty
FROM (
	SELECT	  
		O.PTypeId ,
		O.KTypeId,
		Qty 
	FROM Fact_InOutstocktable  O
	INNER JOIN FactIndex I ON I.BillNumberId=O.billNumberID AND I.RedWord=0
	WHERE I.BillDate<@yearEndDateTime
	UNION ALL
	SELECT	  
		PTypeId ,
		KTypeId,
		Qty 
	FROM #IniFactStocks
) F
GROUP BY 
		PTypeId,
		KTypeId
            
TRUNCATE TABLE dbo.IniFactStocks_Qty
INSERT INTO dbo.IniFactStocks_Qty
( 
	PTypeID ,
	KTypeID ,
	CargoID ,
	ItemID ,
	Iscombined ,
	GoodsNumber ,
	ProduceDate ,
	ValidDate ,
	Qty ,
	NQty
)
SELECT
		ptypeid ,
		KtypeId,
		CargoID ,
		ItemID ,
		Iscombined ,
		GoodsNumber ,
		ProduceDate,
		ValidDate,
		SUM(Qty) Qty,
		SUM(NQty) Qty
FROM (
	SELECT	 
		O.ptypeid ,
		o.KtypeId,
		O.CargoID ,
		O.ItemID ,
		O.Iscombined ,
		O.GoodsNumber ,
		O.ProduceDate,
		O.ValidDate,
		Qty  QTY,
		NQty NQty
	FROM Fact_InOutstocktable  O
	INNER JOIN FactIndex I ON I.BillNumberId=O.billNumberID AND I.RedWord=0
	WHERE I.BillDate<@yearEndDateTime
	UNION ALL
	SELECT	 
		ptypeid ,
		ktypeid ,
		CargoID ,
		ItemID ,
		Iscombined ,
		GoodsNumber ,
		ProduceDate,
		ValidDate,
		Qty,
		NQty
	FROM #IniFactStocks_Qty
) F 
GROUP BY	
		ptypeid ,
		KtypeId,
		CargoID ,
		ItemID ,
		Iscombined ,
		GoodsNumber ,
		ProduceDate,
		ValidDate

--删除期初
DELETE FROM IniFactStocks_Qty WHERE Qty=0 

DROP TABLE #IniFactStocks,#IniFactStocks_Qty
--=====================================实物库存期初【END】=================================
END;


BEGIN--=====================================维修库存期初【BEGIN】=================================
SELECT * INTO #wx_IniGoodsStocks FROM wx_IniGoodsStocks

TRUNCATE TABLE wx_IniGoodsStocks
INSERT INTO dbo.wx_IniGoodsStocks
( 
	PTypeId ,
	KTypeId ,
	JobNumber ,
	OutFactoryDate ,
	Qty ,
	Price ,
	Total ,
	GoodsOrder ,
	GoodsNumber ,
	ProduceDate ,
	ValidDate ,
	GoodsBTypeID ,
	ItemID ,
	Iscombined ,
	Nqty
)
SELECT	  
	PTypeId ,
	KTypeId ,
	'' JobNumber ,
	GETDATE() OutFactoryDate ,
	SUM(Qty) Qty ,
	0,
	0 ,
	GoodsOrder ,
	GoodsNumber ,
	ProduceDate ,
	ValidDate ,
	GoodsBTypeID ,
	ItemID ,
	Iscombined ,
	SUM(Nqty) Nqty
FROM(
	SELECT	  
		PTypeId ,
		KTypeId ,
		Qty,
		GoodsNo GoodsOrder ,
		GoodsNumber ,
		ProduceDate ,
		ValidDate ,
		GoodsBTypeID ,
		ItemID ,
		Iscombined ,
		Nqty
	FROM wx_InOutStockTable
	WHERE BillDate<@yearEndDateTime
	UNION ALL
	SELECT	  
		PTypeId ,
		KTypeId ,
		Qty,
		GoodsOrder ,
		GoodsNumber ,
		ProduceDate ,
		ValidDate ,
		GoodsBTypeID ,
		ItemID ,
		Iscombined ,
		Nqty
	FROM #wx_IniGoodsStocks
) F
GROUP BY  
	PTypeId ,
	KTypeId ,
	GoodsOrder ,
	GoodsNumber ,
	ProduceDate ,
	ValidDate ,
	GoodsBTypeID ,
	ItemID ,
	Iscombined

DELETE FROM wx_IniGoodsStocks WHERE Qty = 0 AND Nqty=0	-- 清除维修库存状况表

DROP TABLE #wx_IniGoodsStocks
--=====================================维修库存期初【BEGIN】=================================
END;

 BEGIN--=====================================代销期初【BEGIN】=================================
	-- 代销库
DECLARE 
	@intserialrelation		INT,--序列号关联货位、自由项、批次批号
	@chvMngSerial			VARCHAR(10)--系统采用序列号严密管理模式

SELECT	@intserialrelation=	[Value] FROM Userconfig WHERE ConfigName='serialrelation'--序列号关联货位、自由项、批次批号
SELECT	@chvMngSerial=[Value] FROM	UserConfig WHERE	ConfigName = 'mngSerial'--系统采用序列号严密管理模式

IF EXISTS(SELECT TOP 1 1 FROM gp_CruPtypeSerial WHERE State IN (13,32,7,9,10,11,16,14) AND @chvMngSerial=1)
	BEGIN
		--先处理委托,委托分为库存委托和受托委托
		CREATE TABLE #iniCommissionStock_Before
		(
			PTypeID	VARCHAR(50),
			BTypeID	VARCHAR(50),
			[Type]		TINYINT,
			Qty			NUMERIC(24, 10) ,
			CostTotal	NUMERIC(24, 10) ,
			Total			NUMERIC(24, 10) ,
			STypeID	VARCHAR(50),
			DealType	TINYINT,
			SerialType TINYINT
		)
		INSERT #iniCommissionStock_Before(PTypeID,BTypeID,Type,Qty,CostTotal,Total,STypeID)
		SELECT PTypeID,BTypeID,CASE WHEN BillType=141 THEN 140 WHEN BillType=145 THEN 144 ELSE BillType END,Qty,CostTotal,Total,STypeID 
		FROM InOutstocktable
		WHERE BillType IN(140,141,142,144,145,146) AND BillDate<@yearEndDateTime
	
		TRUNCATE TABLE iniCommissionStock
		TRUNCATE TABLE iniCommissionStock_Qty
	
		--统计各类序列号状态的商品有多少个
		CREATE TABLE #TempCommissionSerial
		(
			PTypeID		VARCHAR(50),
			BTypeID		VARCHAR(50),
			Type				TINYINT,
			Qty				NUMERIC(24, 10) ,
			STypeID		VARCHAR(50),
			DealType		TINYINT,
			SerialType		TINYINT,
			CostPrice		 NUMERIC(24, 10) ,
			ItemID			INT,
			IsCombined	INT,
			CargoID			INT,
			ProduceDate	VARCHAR(100),
			ValidDate		VARCHAR(100),
			GoodsNumber VARCHAR(50),
			Price				NUMERIC(24, 10)  DEFAULT(0),
			KTypeID		VARCHAR(50) DEFAULT('')
		)	
	
		IF EXISTS(SELECT Serial FROM gp_CruPtypeSerial WHERE State=13 AND ((KtypeID<>'10000' AND OutKtypeTime<@yearEndDateTime) OR (KtypeID='10000' AND InKtypeTime<@yearEndDateTime)))--库存委托已发货
			BEGIN
				--先委托	
				INSERT #TempCommissionSerial
				(
					PTypeID,
					BTypeID,
					Type,
					Qty,
					STypeID,
					DealType,
					SerialType,
					CostPrice,
					ItemID,
					IsCombined,
					CargoID,
					ProduceDate,
					ValidDate,
					GoodsNumber
				)
				SELECT PtypeID,BTypeID1,140,COUNT(*),STypeId,2,13,
					CostPrice,ItemID,IsCombined,0,ProduceDate,ValidDate,GoodsNumber
				FROM gp_CruPtypeSerial
				WHERE 
					State=13
					AND ((KtypeID<>'10000' AND OutKtypeTime<@yearEndDateTime) OR (KtypeID='10000' AND InKtypeTime<@yearEndDateTime))
				GROUP BY PtypeID,BTypeID1,STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber	
		
				UPDATE #TempCommissionSerial
				SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
				FROM CommissionStock b
				WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
				AND b.Type=140 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
		
		
				INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
				SELECT a.Ptypeid,a.Btypeid,a.Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,a.Stypeid,a.DealType,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END
				FROM #TempCommissionSerial a
				WHERE a.SerialType=13 AND a.Type=140
				GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
		
				INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
				SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,0,DealType,'10000',0,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END,CostPrice
				FROM #TempCommissionSerial a
				WHERE a.SerialType=13 AND a.Type=140
		
				TRUNCATE TABLE #TempCommissionSerial		
			END
	
		IF EXISTS(SELECT Serial FROM gp_CruPtypeSerial WHERE State=14 AND OutKtypeTime<@yearEndDateTime)
			BEGIN	
				INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
					CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
				SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),144,COUNT(*),STypeId,2,14,
				CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
				FROM gp_CruPtypeSerial
				WHERE 
					State=14
					AND OutKtypeTime<@yearEndDateTime
				GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber	
		
				UPDATE #TempCommissionSerial
				SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
				FROM CommissionStock b
				WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
				AND b.Type=144 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
		
		
				INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
				SELECT a.Ptypeid,a.Btypeid,a.Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,a.Stypeid,a.DealType,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END
				FROM #TempCommissionSerial a
				WHERE a.SerialType=14 AND a.Type=144
				GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
		
				INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
				SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,0,DealType,'10000',0,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END,CostPrice
				FROM #TempCommissionSerial a
				WHERE a.SerialType=14 AND a.Type=144

				TRUNCATE TABLE #TempCommissionSerial		
			END
	
		IF EXISTS(SELECT Serial FROM gp_CruPtypeSerial WHERE State=32 AND OutKtypeTime<@yearEndDateTime)
			BEGIN
				INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
					CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
				SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,140),140,COUNT(*),STypeId,1,32,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
				FROM gp_CruPtypeSerial
				WHERE State=32 AND OutKtypeTime<@yearEndDateTime
				GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,140),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
		
				UPDATE #TempCommissionSerial
				SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
				FROM CommissionStock b
				WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
				AND b.Type=140 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
		
				INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
				SELECT a.Ptypeid,a.Btypeid, a.Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,a.Stypeid,a.DealType,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END
				FROM #TempCommissionSerial a
				WHERE a.SerialType=32 AND a.Type=140
				GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
		
				INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
				SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,0,DealType,'10000',0,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END,CostPrice
				FROM #TempCommissionSerial a
				WHERE a.SerialType=32 AND a.Type=140
		
				TRUNCATE TABLE #TempCommissionSerial
	
				INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
					CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
				SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),144,COUNT(*),STypeId,1,32,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
				FROM gp_CruPtypeSerial
		
				WHERE State=32
				GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
		
				UPDATE #TempCommissionSerial
				SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
				FROM CommissionStock b
				WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
				AND b.Type=144 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
		
				INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
				SELECT a.Ptypeid,a.Btypeid,a.Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,a.Stypeid,a.DealType,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END
				FROM #TempCommissionSerial a
				WHERE a.SerialType=32 AND a.Type=144
				GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
		
				INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
				SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,0,DealType,'10000',0,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END,CostPrice
				FROM #TempCommissionSerial a
				WHERE a.SerialType=32 AND a.Type=144
		
				TRUNCATE TABLE #TempCommissionSerial
			END
	
		IF EXISTS(SELECT Serial FROM gp_CruPtypeSerial WHERE State=7 AND InKtypeTime<@yearEndDateTime)
			BEGIN
				--再受托	
				INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
					CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber,KTypeID)
				SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),144,COUNT(*),STypeId,0,7,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber,KtypeID
				FROM gp_CruPtypeSerial
				WHERE State=7 AND InKtypeTime<@yearEndDateTime
				GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber,KtypeID
		
				UPDATE #TempCommissionSerial
				SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
				FROM CommissionStock b
				WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
				AND b.Type=144 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid

				INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
				SELECT a.Ptypeid,a.Btypeid,Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),dbo.F_RoundTotal(SUM(Qty)*Price),0,0,Stypeid,DealType,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END
				FROM #TempCommissionSerial a
				WHERE a.SerialType=7 AND a.Type=144
				GROUP BY a.PTypeID,a.BTypeID,a.STypeID,a.DealType,a.SerialType,a.Type,a.Price
		
				INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
				SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,0,DealType,KTypeID,CargoID,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END,CostPrice
				FROM #TempCommissionSerial a
				WHERE a.SerialType=7 AND a.Type=144

				TRUNCATE TABLE #TempCommissionSerial	
			END
	
		IF EXISTS(SELECT Serial FROM gp_CruPtypeSerial WHERE State IN (9,10,11,16) AND OutKtypeTime<@yearEndDateTime)
			BEGIN
				INSERT #TempCommissionSerial(PTypeID,BTypeID,Type,Qty,STypeID,DealType,SerialType,
					CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber)
				SELECT PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),144,COUNT(*),STypeId,2,State,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
				FROM gp_CruPtypeSerial
				WHERE State IN (9,10,11,16) AND OutKtypeTime<@yearEndDateTime
				GROUP BY PtypeID,DBO.F_GetCommissionBTypeID(Serial,State,144),STypeID,CostPrice,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,State,GoodsNumber
		
				UPDATE #TempCommissionSerial
				SET Price=CASE b.Qty WHEN 0 THEN 0 ELSE dbo.F_RoundPrice(CAST(b.Total AS  NUMERIC(24, 10) )/CAST(b.Qty AS  NUMERIC(24, 10) )) END
				FROM CommissionStock b
				WHERE #TempCommissionSerial.PTypeID=b.Ptypeid AND #TempCommissionSerial.BTypeID=b.Btypeid
				AND b.Type=144 AND #TempCommissionSerial.Type=b.Type AND #TempCommissionSerial.STypeID=b.Stypeid
		
				INSERT IniCommissionStock(Ptypeid,Btypeid,Type,Qty,CostTotal,Total,Tax,TaxTotal,Stypeid,DealType,SerialType)
				SELECT a.Ptypeid,a.Btypeid,Type,SUM(Qty),SUM(dbo.F_RoundTotal(Qty*CostPrice)),SUM(dbo.F_RoundTotal(Qty*Price)),0,0,Stypeid,DealType,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END
				FROM #TempCommissionSerial a
				WHERE a.SerialType IN (9,10,11,16) AND a.Type=144
				GROUP BY a.PTypeID,a.BTypeID,a.Type,a.Stypeid,a.DealType,a.SerialType
		
				INSERT IniCommissionStock_Qty(Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,NQty,DealType,KTypeID,CargoID,SerialType,GoodsCostPrice)
				SELECT Ptypeid,Btypeid,Stypeid,Type,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
				Qty,0,DealType,'10000',0,CASE WHEN @intserialrelation=1 THEN a.SerialType ELSE 0 END,CostPrice
				FROM #TempCommissionSerial a
				WHERE a.SerialType IN (9,10,11,16) AND a.Type=144
		
				TRUNCATE TABLE #TempCommissionSerial
			END
	
		--如果存在COSTTOTAL=0,则处理一下
		IF EXISTS(SELECT Ptypeid FROM IniCommissionStock WHERE Qty<>0 AND CostTotal=0)
			BEGIN
				UPDATE IniCommissionStock
				SET CostTotal=dbo.F_RoundTotal(IniCommissionStock.Qty *b.CostPrice)
				FROM
				(
					SELECT PTypeID,BTypeID,STypeID,TYPE,CASE SUM(Qty) WHEN 0 THEN 0 ELSE dbo.F_RoundTotal(CAST(SUM(CostTotal) AS  NUMERIC(24, 10) )/CAST((SUM(Qty)*1.0) AS  NUMERIC(24, 10) )) END AS CostPrice
					FROM #iniCommissionStock_Before
					GROUP BY PTypeID,BTypeID,STypeID,TYPE
			
				) b
				WHERE IniCommissionStock.Ptypeid=b.PTypeID
				AND IniCommissionStock.Btypeid=b.BTypeID
				AND IniCommissionStock.Stypeid=b.STypeID
				AND IniCommissionStock.Type=b.Type
				AND IniCommissionStock.CostTotal=0
				AND IniCommissionStock.Qty<>0
			END

		--尾差分摊
		IF EXISTS(SELECT a.PTypeID,a.BTypeID,a.Type,a.Total,b.Total 
			FROM
					(
						SELECT PTypeID,BTypeID,Type,SUM(Total) AS Total
						FROM #iniCommissionStock_Before
						GROUP BY PTypeID,BTypeID,Type
					) a
					INNER JOIN
					(
						SELECT PTypeID,BTypeID,Type,SUM(Total) AS Total
						FROM iniCommissionStock
						GROUP BY PTypeID,BTypeID,Type
					) b
					ON a.PTypeID=b.PTypeID AND a.BTypeID=b.BTypeID AND a.Type=b.Type
					WHERE a.Total<>b.Total
				)
			BEGIN
				CREATE TABLE #tmp_Diff(PTypeID VARCHAR(50),BTypeID VARCHAR(50),Type TINYINT,Diff  NUMERIC(24, 10) ,MaxQty  NUMERIC(24, 10) ,MAXCount  NUMERIC(24, 10) ,SerialType TINYINT)
	
				INSERT #tmp_Diff(PTypeID,BTypeID,Type,Diff)
				SELECT a.PTypeID,a.BTypeID,a.Type,a.Total-b.Total
				FROM
				(
					SELECT PTypeID,BTypeID,Type,SUM(Total) AS Total
					FROM #iniCommissionStock_Before
					GROUP BY PTypeID,BTypeID,Type
				) a
				INNER JOIN
				(
					SELECT PTypeID,BTypeID,Type,SUM(Total) AS Total
					FROM iniCommissionStock
					GROUP BY PTypeID,BTypeID,Type
				) b
				ON a.PTypeID=b.PTypeID AND a.BTypeID=b.BTypeID AND a.Type=b.Type
				WHERE a.Total<>b.Total
	
				UPDATE #tmp_Diff
				SET MaxQty=b.Qty
				FROM
				(
					SELECT PTypeID,BTypeID,Type,MAX(Qty) AS Qty
					FROM iniCommissionStock
					GROUP BY PTypeID,BTypeID,Type
				) b
				WHERE #tmp_Diff.PTypeID=b.PTypeID AND #tmp_Diff.BTypeID=b.BTypeID AND #tmp_Diff.Type=b.Type

				UPDATE #tmp_Diff
				SET MAXCount=b.MaxCount
				FROM
				(
					SELECT a.PTypeID,a.BTypeID,a.Type,COUNT(*) AS MaxCount
					FROM iniCommissionStock a
					INNER JOIN #tmp_Diff b
					ON a.PTypeID=b.PTypeID AND a.BTypeID=b.BTypeID AND a.Type=b.Type AND a.Qty=b.MaxQty
					GROUP BY a.PTypeID,a.BTypeID,a.Type
				) b
				WHERE #tmp_Diff.PTypeID=b.PTypeID AND #tmp_Diff.BTypeID=b.BTypeID AND #tmp_Diff.Type=b.Type
		
				UPDATE #tmp_Diff
				SET SerialType=b.SerialType
				FROM 
				(
					SELECT a.PTypeID,a.BTypeID,a.Type,MAX(a.SerialType) AS SerialType
					FROM iniCommissionStock a
					INNER JOIN #tmp_Diff b
					ON a.PTypeID=b.PTypeID AND a.BTypeID=b.BTypeID AND a.Type=b.Type AND a.Qty=b.MaxQty
					WHERE b.MaxCount>1
					GROUP BY a.PTypeID,a.BTypeID,a.Type
				) b
				WHERE #tmp_Diff.PTypeID=b.PTypeID AND #tmp_Diff.BTypeID=b.BTypeID AND #tmp_Diff.Type=b.Type

				UPDATE iniCommissionStock
				SET Total=iniCommissionStock.Total+b.Diff
				FROM #tmp_Diff b
				WHERE iniCommissionStock.PTypeID=b.PTypeID
				AND iniCommissionStock.BTypeID=b.BTypeID
				AND iniCommissionStock.Type=b.Type
				AND b.MaxCount=1 AND iniCommissionStock.Qty=b.MaxQty
		
				UPDATE iniCommissionStock
				SET Total=iniCommissionStock.Total+b.Diff
				FROM #tmp_Diff b
				WHERE iniCommissionStock.PTypeID=b.PTypeID
				AND iniCommissionStock.BTypeID=b.BTypeID
				AND iniCommissionStock.Type=b.Type
				AND b.MaxCount<>1 AND iniCommissionStock.SerialType=b.SerialType			
			END	
	
		DROP TABLE #iniCommissionStock_Before
	
		--对于未启用序列号的代销数据，不能根据序列号结转，要直接转过去
		IF EXISTS(SELECT TypeID FROM dbo.ptype WHERE sonnum=0 AND IfSerial=0 )
			BEGIN
				INSERT INTO iniCommissionStock (
					PTypeID,
					BTypeID,
					Type,
					Qty,
					CostTotal,
					Total,
					Explain,
					KTypeID,
					ETypeID,
					STypeID,
					DealType,
					SerialType
				)
				SELECT	a.PTypeID,
						a.BTypeID,
						a.BillType,
						SUM(A.Qty) AS Qty,
						SUM(A.CostTotal) AS CostTotal,
						SUM(A.Total) AS Total,
						A = '',
						B = '',
						C = '',
						A.STypeID,
						0,
						0
				FROM InOutstocktable a
				INNER JOIN PType b ON a.Ptypeid=b.typeId AND b.IfSerial=0
				WHERE A.BillDate<@yearEndDateTime
				GROUP BY 
					a.PTypeID, 
					a.BTypeID, 
					a.BillType,
					A.STypeID
		
		
				 
				INSERT INTO dbo.IniCommissionStock_Qty
						( Ptypeid ,
						  Btypeid ,
						  Stypeid ,
						  Type ,
						  ItemID ,
						  Iscombined ,
						  GoodsNumber ,
						  ProduceDate ,
						  ValidDate ,
						  Qty ,
						  NQty,
						  DealType,
						  KTypeID,
						  CargoID,
						  SerialType,
						  GoodsCostPrice
						)
				SELECT	  a.Ptypeid ,
						  a.Btypeid ,
						  a.Stypeid ,
						  a.BillType ,
						  a.ItemID ,
						  a.Iscombined ,
						  a.GoodsNumber ,
						  a.ProduceDate ,
						  a.ValidDate ,
						  SUM(a.Qty) ,
						  SUM(a.NQty),
						  0,
						  '10000',
						  0,
						  0,
						  0
				FROM dbo.InOutstocktable a
				INNER JOIN PType b ON a.Ptypeid=b.typeId and b.IfSerial=0
				where A.BillDate<@yearEndDateTime
				GROUP BY  a.Ptypeid ,
						  a.Btypeid ,
						  a.Stypeid ,
						  a.BillType ,
						  a.ItemID ,
						  a.Iscombined ,
						  a.GoodsNumber ,
						  a.ProduceDate ,
						  a.ValidDate
			END
	END
ELSE
	BEGIN
		SELECT * INTO #iniCommissionStock FROM iniCommissionStock
		SELECT * INTO #IniCommissionStock_Qty FROM IniCommissionStock_Qty

		TRUNCATE TABLE iniCommissionStock		
		INSERT INTO iniCommissionStock 
		(
			PTypeID,
			BTypeID,
			Type,
			Qty,
			CostTotal,
			Total,
			Explain,
			KTypeID,
			ETypeID,
			STypeID,
			DealType,
			SerialType
		)
		SELECT 
			PTypeID,
			BTypeID,
			BillType,
			SUM(Qty) AS Qty,
			SUM(CostTotal) AS CostTotal,
			SUM(Total) AS Total,
			'' Explain,
			'' KTypeID, 
			'' ETypeID,
			STypeID,
			0 DealType,
			0 SerialType
		FROM (
				SELECT	
					PTypeID,
					BTypeID,
					CASE WHEN BillType=141 THEN 140 WHEN BillType=145 THEN 144 ELSE BillType END BillType,
					Qty Qty,
					CostTotal CostTotal,
					Total Total,
					STypeID
				FROM InOutstocktable
				WHERE 
					BillDate<@yearEndDateTime
					AND BillType IN(140,141,142,144,145,146) 
					AND KtypeId='10000'
				UNION ALL
				SELECT	
					PTypeID,
					BTypeID,
					Type BillType,
					Qty,
					CostTotal,
					Total,
					STypeID
				FROM #iniCommissionStock
			) F
		GROUP BY
			PTypeID,
			BTypeID,
			BillType,
			STypeID

	
		TRUNCATE TABLE dbo.IniCommissionStock_qty
		INSERT INTO dbo.IniCommissionStock_Qty
		( 
			Ptypeid ,
			Btypeid ,
			Stypeid ,
			Type ,
			ItemID ,
			Iscombined ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			Qty ,
			NQty,
			DealType,
			KTypeID,
			CargoID,
			SerialType,
			GoodsCostPrice
		)
		SELECT
			Ptypeid ,
			Btypeid ,
			Stypeid ,
			BillType ,
			ItemID ,
			Iscombined ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			SUM(Qty) Qty ,
			SUM(NQty) NQty,
			0,
			'10000' KTypeID,
			0 CargoID,
			0 SerialType,
			0 GoodsCostPrice
		FROM(
			SELECT	  
				Ptypeid ,
				Btypeid ,
				Stypeid ,
				CASE WHEN BillType=141 THEN 140 WHEN BillType=145 THEN 144 ELSE a.BillType END BillType ,
				ItemID ,
				Iscombined ,
				GoodsNumber ,
				ProduceDate ,
				ValidDate ,
				Qty,
				NQty
			FROM InOutstocktable A
			WHERE 
				A.BillDate<@yearEndDateTime
				AND BillType IN(140,141,142,144,145,146) 
				AND KtypeId='10000'
			UNION ALL
			SELECT	  
				Ptypeid ,
				Btypeid ,
				Stypeid ,
				Type BillType,
				ItemID ,
				Iscombined ,
				GoodsNumber ,
				ProduceDate ,
				ValidDate ,
				Qty ,
				NQty
			FROM #IniCommissionStock_qty
		) F 
		GROUP BY 
			Ptypeid,
			Btypeid,
			Stypeid,
			BillType,
			ItemID,
			Iscombined,
			GoodsNumber,
			ProduceDate,
			ValidDate
	          
		DELETE FROM iniCommissionStock WHERE (Qty = 0 AND Total = 0 AND CostTotal = 0 AND Type = 140) OR  (Qty = 0 AND Total = 0 AND Type = 144)

		UPDATE	iniCommissionStock SET Total = CAST(Total AS  NUMERIC(24, 10) ),CostTotal = CAST(CostTotal AS  NUMERIC(24, 10) )
			
		DELETE FROM iniCommissionStock_Qty WHERE qty=0 AND nqty=0	

		DROP TABLE #iniCommissionStock,#IniCommissionStock_Qty
	END
 --=====================================代销期初【END】=================================
END;


BEGIN --=====================================借欠期初【BEGIN】=================================
--清除原借欠期初数据 不包含金额
TRUNCATE TABLE IniGoodsLend
INSERT INTO dbo.IniGoodsLend 
(
	BtypeId,
	PtypeId, 
	KtypeId, 
	JobNumber , 
	OutFactoryDate, 
	Qty, 
	GoodsNumber, 
	ItemID,
	Iscombined, 
	Nqty, 
	ProduceDate, 
	ValidDate, 
	BorrowQty, 
	LendQty, 
	NBorrowQty, 
	NLendQty 
)
SELECT 
	BtypeId,
	PtypeId, 
	KtypeId, 
	JobNumber , 
	NULL OutFactoryDate, 
	ISNULL(SUM(Qty),0) Qty, 
	GoodsNumber, 
	ItemID,
	Iscombined, 
	ISNULL(SUM(NQty),0) NQty, 
	ProduceDate, 
	ValidDate, 
	SUM(BorrowQty)  BorrowQty, 
	SUM(LendQty) LendQty, 
	SUM(NBorrowQty) NBorrowQty, 
	SUM(NLendQty) NLendQty 
FROM (
SELECT
	BtypeId,
	PtypeId, 
	KtypeId, 
	JobNumber , 
	OutFactoryDate, 
	ISNULL(SUM(CASE WHEN BillType IN(71,72) THEN Qty ELSE -1*Qty END),0) Qty, 
	GoodsNumber, 
	ItemID,
	Iscombined, 
	ISNULL(SUM(CASE WHEN BillType IN(71,72) THEN NQty ELSE -1*NQty END),0) NQty, 
	ProduceDate, 
	ValidDate, 
	SUM(CASE WHEN BillType IN(71,72) THEN Qty  WHEN BillType IN(34) THEN -1*Qty  ELSE 0 END)  BorrowQty, 
	SUM(CASE WHEN BillType IN(87,88,11) THEN -1*Qty ELSE 0 END) LendQty, 
	SUM(CASE WHEN BillType IN(71,72) THEN NQty WHEN BillType IN(34) THEN -1*NQty ELSE 0 END) NBorrowQty, 
	SUM(CASE WHEN BillType IN(87,88,11) THEN -1*NQty ELSE 0 END) NLendQty 
FROM 
(
		SELECT
			A.BillType,				  
			BtypeId, 
			B.PtypeId, 
			KtypeId, 
			JobNumber ,
			OutFactoryDate, 
			B.Qty,
			B.GoodsNumber, 
			ItemID, 
			Iscombined , 
			B.NQty , 
			ProduceDate , 
			ValidDate
		FROM LendIndex A
		INNER JOIN  LendBill B ON B.BillNumberId=A.BillNumberId 
		WHERE 
				A.BillDate<@yearEndDateTime
				AND A.draft=0
				AND A.RedWord=0
				AND A.ifcheck='t'
				AND A.ifYearBill=0

		UNION ALL--转采购

		SELECT		
			A.BillType,						  
			BtypeId, 
			B.PtypeId, 
			A.ktypeid, 
			JobNumber ,
			NULL OutFactoryDate, 
			B.Qty,
			B.GoodsNumber, 
			ItemID, 
			Iscombined , 
			B.NQty, 
			ProduceDate , 
			ValidDate
		FROM BuyBill B
		INNER JOIN  BillIndex A ON A.BillType=34 AND A.IsLend=1 AND B.BillNumberId=A.BillNumberId
		WHERE 
				A.BillDate<@yearEndDateTime
				AND A.draft=0
				AND A.RedWord=0
				AND A.ifcheck='t'
				AND A.ifYearBill=0

		UNION ALL--转销售

		SELECT		
			A.BillType,						  
			BtypeId, 
			B.PtypeId, 
			A.ktypeid, 
			JobNumber ,
			NULL OutFactoryDate, 
			B.Qty,
			B.GoodsNumber, 
			ItemID, 
			Iscombined, 
			B.NQty, 
			ProduceDate , 
			ValidDate
		FROM SaleBill B
		INNER JOIN  BillIndex A ON A.BillType=11 AND A.IsLend=1 AND B.BillNumberId=A.BillNumberId
		WHERE 
				A.BillDate<@yearEndDateTime
				AND A.draft=0
				AND A.RedWord=0
				AND A.ifcheck='t'
				AND A.ifYearBill=0
) F
GROUP BY 					  
	BtypeId, 
	PtypeId, 
	ktypeid, 
	JobNumber ,
	OutFactoryDate, 
	GoodsNumber, 
	ItemID, 
	Iscombined, 
	ProduceDate , 
	ValidDate
UNION ALL
SELECT 
	BtypeId,
	PtypeId, 
	KtypeId, 
	JobNumber , 
	NULL OutFactoryDate, 
	ISNULL(SUM(Qty),0) Qty, 
	GoodsNumber, 
	ItemID,
	Iscombined, 
	ISNULL(SUM(NQty),0) NQty, 
	ProduceDate, 
	ValidDate, 
	SUM(BorrowQty)  BorrowQty, 
	SUM(LendQty) LendQty, 
	SUM(NBorrowQty) NBorrowQty, 
	SUM(NLendQty) NLendQty 
FROM IniGoodsLend
GROUP BY 
	BtypeId, 
	PtypeId, 
	ktypeid, 
	JobNumber ,
	OutFactoryDate, 
	GoodsNumber, 
	ItemID, 
	Iscombined, 
	ProduceDate , 
	ValidDate
) F 
GROUP BY 
	BtypeId, 
	PtypeId, 
	ktypeid, 
	JobNumber ,
	OutFactoryDate, 
	GoodsNumber, 
	ItemID, 
	Iscombined, 
	ProduceDate , 
	ValidDate

 --=====================================借欠期初【END】=================================
 END;

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_Recount_ReachQty]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_Recount_ReachQty]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：重算期初订单库存-指定时间年结存 
	
*/
CREATE   PROCEDURE Gp_YearProc_DateTime_Recount_ReachQty
(
	@yearendDatetime		VARCHAR(20)		--年结存的时间
)
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--删除此前的数据 暂时不删 后面统一删
--DELETE FROM OrderIndex WHERE BillDate <= @yearendDatetime

--orderINDEX临时表
CREATE TABLE #orderINDEX
(
	BillNumberID [numeric](18, 0) NOT NULL,
	[BillType] [numeric](4, 0) NOT NULL
)
INSERT INTO #orderINDEX
(
	BillNumberID,
	[BillType]
)
SELECT A.BillNumberId,A.BillType FROM OrderIndex A WHERE BillDate <@yearendDatetime
----------------------------------------------------------重算期初订单库存 表 start------------------------------------------------------------
TRUNCATE TABLE Ini_GoodsStocks_Order
INSERT INTO Ini_GoodsStocks_Order
(
	BillNumberID,
	OrderID,
	BillType,
	ReachQty,
	ReachTotal,
	ReachTaxTotal
)
SELECT 
	A.billNumberID,
	A.OrderID,
	A.BillType,
	SUM(isnull(A.ReachQty,0)) AS ReachQty,
	SUM(isnull(A.ReachTotal,0)) AS ReachTotal,
	SUM(isnull(A.ReachTaxTotal,0)) AS ReachTaxTotal
FROM
(
--采购销售
SELECT C.billNumberID,C.OrderID,A.BillType,C.ReachQty,C.ReachTotal,C.ReachTaxTotal
FROM OrderBill C,#orderINDEX A WHERE A.BillType IN (300,301) AND C.billNumberID=A.BillNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=C.ptypeid AND IsService=0) AND C.KTypeID<>'' AND C.CargoID<>0

--组合品
UNION ALL
SELECT C.billNumberID,C.OrderID,A.BillType,C.ReachQty,C.ReachTotal,C.ReachTaxTotal
FROM PT_Combin_OrderBillDetail C,#orderINDEX A WHERE A.BillType=313 AND C.billNumberID=A.BillNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=C.ptypeid AND IsService=0) AND C.KTypeID<>'' AND C.CargoID<>0

) AS A 
GROUP BY A.billNumberID,A.OrderID,A.BillType

----------------------------------------------------------重算期初订单库存 表 END------------------------------------------------------------
DELETE FROM Ini_GoodsStocks_Order WHERE ReachQty=0 AND ReachTotal=0 AND ReachTaxTotal=0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_VipCard]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DateTime_VipCard]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2018-12-17
	描述：指定时间年结存-VipCard处理
*/

CREATE   PROCEDURE Gp_YearProc_DateTime_VipCard
(
	@yearendDatetime VARCHAR(20)			--   -年结存的日期		
)
AS
SET NOCOUNT ON

CREATE TABLE #BenNian
(
	VipCardID	INT,
	Stypeid		VARCHAR(50),
	Cz			NUMERIC(24,10),
	XfCz		NUMERIC(24,10),
	Xf			NUMERIC(24,10)
)
INSERT INTO #BenNian
( 
	VipCardID,
	Stypeid,
	Cz,
	XfCz,
	Xf 
)
SELECT	f.VipCardID,
		f.stypeid,
		ISNULL(SUM(Cz),0),
		ISNULL(SUM(f.XfCz),0),
		ISNULL(SUM(f.Xf),0) 
FROM 
(
	SELECT  VipCardID,
			Stypeid,
			0 AS Cz,0 
			AS XfCz,
			CASE WHEN b.BillType IN (45,46, 215) THEN -totalmoney ELSE b.totalmoney END AS Xf
	FROM	dbo.BillIndex b
	WHERE	b.BillDate >= @yearendDatetime 
			AND b.VipCardID > 0
			AND b.RedWord = 0 
			AND b.BillType NOT IN(181,312,427)
			AND (b.ifcheck = 't'
			OR EXISTS(SELECT TOP 1 RetailBillNumberId FROM dbo.PosRetailRecord WHERE AuditingFlag = 0 AND RetailBillNumberId = b.BillNumberId))
	UNION ALL
	SELECT	ma.VipCardID,
			b.stypeid,
			0,
			CASE WHEN b.BillType IN (45,46, 215) THEN -ma.Total ELSE ma.Total END,
			0 
	FROM	dbo.BillMulAccount ma 
	INNER JOIN dbo.BillIndex b ON b.BillNumberId = ma.BillNumberId
	WHERE	b.BillDate >= @yearendDatetime 
			AND ma.VipCardID > 0
			AND b.RedWord = 0 
			AND (b.ifcheck = 't' 
			OR EXISTS(SELECT TOP 1 RetailBillNumberId FROM dbo.PosRetailRecord WHERE AuditingFlag = 0 AND RetailBillNumberId = b.BillNumberId))
	UNION ALL
	SELECT	gb.VipCardID,
			b.Stypeid,
			0,
			total,
			0 
	FROM dbo.gatheringBill gb 
	INNER JOIN dbo.BillIndex b ON b.BillNumberId = gb.BillNumberId
	WHERE	b.BillDate >= @yearendDatetime 
			AND gb.VipCardID > 0
			AND b.RedWord = 0 AND b.ifcheck = 't'
	UNION ALL
	SELECT	VipCardID,
			Stypeid,
			totalmoney,
			0,
			0 
	FROM	dbo.BillIndex 
	WHERE	BillDate >= @yearendDatetime 
			AND BillType = 181 
			AND RedWord = 0 
			AND ifcheck = 't'
	UNION ALL
	SELECT	vb.VipCardId,
			b.Stypeid,
			vb.ChargeMoney,
			0,
			0 
	FROM	dbo.VipAddMoneyBatchBill vb 
	INNER JOIN dbo.BillIndex b ON b.BillNumberId = vb.BillNumberId
	WHERE	b.BillDate >= @yearendDatetime 
			AND b.BillType = 312 
			AND RedWord = 0 
			AND ifcheck = 't'
	UNION ALL
	SELECT	vb.VipCardId,
			b.Stypeid,
			vb.ChangeMoney,
			0,
			0 
	FROM	dbo.VipCentToMoneyBill vb 
	INNER JOIN dbo.BillIndex b ON b.BillNumberId = vb.BillNumberId	
	WHERE	b.BillDate >= @yearendDatetime 
			AND b.BillType = 427 
			AND RedWord = 0 
			AND ifcheck = 't'
) f
GROUP BY f.VipCardID,f.stypeid

--结转分支机构会员卡储值余额到期初
UPDATE	T
SET		qCczMoney=T.cZyeMoney+b.XfCz-b.Cz,		
		bNczMoney=b.Cz,
		bNxFczMoney=b.XfCz,
		bNxFMoney=b.Xf
FROM dbo.nVipCardSignStype T
LEFT JOIN #BenNian b ON b.VipCardID = T.VipCardID AND b.stypeid = T.StypeId

UPDATE	T 
SET		t.BeginCent = ISNULL(T.beginCent,0) +  ISNULL(a.jf,0),	
		t.totalCent = ISNULL(T.totalCent,0) - ISNULL(a.jf,0)		
FROM dbo.nVipCardSign T
LEFT JOIN (
	SELECT  c.VipCardID,
			SUM(c.jf) AS jf 
	FROM (
			SELECT b.VipCardID,b.JF
			FROM	dbo.BillIndex b 
			WHERE	b.BillDate < @yearendDatetime 
					AND b.VipCardID > 0
					AND b.RedWord = 0 
					AND b.ifcheck = 't'
			UNION ALL	
			SELECT v.VipNo,v.SumCost 
			FROM nVipAdjust v
			WHERE v.BillDate < @yearendDatetime 
				AND v.nType = 2
		) c
	GROUP BY c.VipCardID
		) a ON a.VipCardID = t.VipCardID

UPDATE	T	
SET		t.BeginMoney =ISNULL(t.BeginMoney,0) + ISNULL(T.totalMoney,0) - ISNULL(B.xf,0)+ISNULL(B.tzxf,0),
		t.lJczMoney = ISNULL(B.Cz,0),
		t.totalMoney = ISNULL(B.xf,0),
		t.qCczMoney = ISNULL(t.cZyeMoney,0)+ISNULL(B.Xfcz,0)-ISNULL(B.Cz,0)
FROM	nVipCardSign T
LEFT JOIN 
(
	SELECT	VipCardID,	
			Cz,
			XfCz,
			Xf,
			0 AS tzxf
	FROM	#BenNian
	UNION ALL
	SELECT  v.VipNo AS VipCardID,
			0 AS Cz,
			0 AS XfCz,
			0 AS Xf,
			SUM(v.SumCost) AS tzxf 
	FROM	nVipAdjust v
	WHERE	v.BillDate < @yearendDatetime 
			AND v.nType = 1
	GROUP BY v.VipNo
)B ON T.VipCardID = B.VipCardID

DROP TABLE #BenNian

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_YearProcDeleteBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_YearProc_DateTime_YearProcDeleteBill
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-17
-- Description: 年结存清除单据
-- 冯波 2015-06-02
/*				根据条件清除单据的主表和明细*/				
-- =============================================

CREATE PROCEDURE Gp_YearProc_DateTime_YearProcDeleteBill
(
	@yearendmode							CHAR(1) = '1',		-- 1 - 按余额转期初；0 - 按单据转期初
	@delDraft								CHAR(1) = '1',		--清除草稿数据
	@unfinishedinvoice 						CHAR(1) = '1',		-- 1 - 保留未完成开票单据；0 - 不保留
	@chkcompleterequestbill					CHAR(1) = '1',		-- 1 - 清除已完成请购单；0 - 清除所有请购单
	@unfinishedposbill						CHAR(1) = '1',		-- 0 - 清除已结转小票数据；1 - 清除所有小票数据
	@PhysicalComplete						CHAR(1) = '0',		-- 1 -结转未实物出入库完成的单据   0 不结转
	@carryOverBillexcess					CHAR(1)	= '0',		-- 1 - 业务单据超收超付及收付款单未结算完金额结转至期初应收应付减少单；0 - 不转
	@delOrder								CHAR(1) = '1',		-- 1 - 删除定单数据；0 - 不删除
	@clearCompleteAllotApply				CHAR(1),			--	 -是否清除已完成的调货申请单 0-不清除 1-清除
	@clearNoCompleteAllotApply				CHAR(1),			--	 -是否清除未完成的调货申请单 0-不清除 1-清除
	@clearnocompleteonshelves				CHAR(1) = '0',		--	 -是否清除未完成上架的单据 0-不清除 1-清除
    @clearnocompletepickandtransport		CHAR(1) = '0',		--   -是否清除未完成拣货/运输的单据 0-不清除 1-清除
    @delstoporder							CHAR(1) = '0',		-- 1 - 清除中止订单;0清除中止订单
    @delEndOrder							CHAR(1) = '0',		-- 1 - 删除已完成订单；0 - 不删除
    @yearendDatetime						VARCHAR(20),		--   -年结存的日期		
    @clearCompleteGetBillApply              CHAR(1) = '0',      --是否清除已完成的要货申请单 0-不清除 1-清除
	@clearNoCompleteGetBillApply            CHAR(1) = '0'       --是否清除未完成要货申请单 0-不清除 1-清除	
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

DECLARE @columns VARCHAR(max)=''	--存储表的字段

--系统重建所有锁库数据进行解锁
--TRUNCATE TABLE PT_SaleOrderLockDetail		 		--清除订单锁库信息
--UPDATE Ini_GOODSSTOCKS_QTY SET LockNumber=0 --清楚期初锁库信息
--UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
--UPDATE OrderBill SET LockNumber=0 --清除订单锁库信息
--UPDATE PT_Combin_OrderBillDetail SET LockNumber=0 --清除组合品订单锁库信息
---------------始终需要删除，与条件无关的部分start-------
DELETE FROM BillIndex WHERE BillType=206 AND BillDate < @yearendDatetime	
DELETE FROM ShareSourceBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BillIndex WHERE BillType IN(205,206))	--费用分摊出入库单明细
DELETE FROM ShareFeeBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex WHERE BillType IN(205,206))		--费用分摊费用明
--TRUNCATE TABLE nVipGoodsSign
DELETE FROM dbo.Fact_InOutstocktable WHERE BillDate < @yearendDatetime
DELETE FROM InOutStockTable WHERE BillDate < @yearendDatetime		-- 出入库明细表

DELETE FROM wx_InOutStockTable WHERE BillDate < @yearendDatetime	-- 维修出入库明细表
DELETE  FROM commonpossaleindex WHERE Draft<>0	AND SaleDate < @yearendDatetime	--收银小票
DELETE  FROM commonpossalelist WHERE NOT EXISTS (SELECT  1 FROM CommonPosSaleIndex WHERE CommonPosSaleIndex.PosVchCode=commonpossalelist.PosVchCode)
DELETE  FROM CommonPosPtypeCheckNdx WHERE PDVchCode<>0	AND PDDate < @yearendDatetime					--POS盘点单据
DELETE  FROM CommonPosPtypeCheckList WHERE NOT EXISTS (SELECT  1 FROM CommonPosPtypeCheckNdx WHERE CommonPosPtypeCheckNdx.CheckCode=CommonPosPtypeCheckList.CheckCode)	

--清除状态为分支机构调拨出库的优惠券
DELETE FROM dbo.Coupon_CodeInfo WHERE [State]=7

--清除固定资产盘点单已处理的
DELETE FROM FixedAssetsIndex WHERE [state]=3 AND createdate < @yearendDatetime
 
DELETE FROM StockCheckIndex WHERE BillDate < @yearendDatetime		-- 清除库存盘点单据索引表
DELETE FROM StockCheck 	WHERE StockCheckID NOT IN(SELECT StockCheckID FROM dbo.StockCheckIndex)		-- 清除库存盘点表

DELETE FROM nVipAdjust WHERE BillDate < @yearendDatetime			-- 清除消费金额调整单、积分调整单
DELETE FROM nVipAddMoney WHERE BillDate < @yearendDatetime

DELETE FROM PriceProtectList		-- 清除价保记录 
--删除单据修改记录
DELETE FROM dbo.FrozeBusiness
-- 清除财务历史状况表
DELETE FROM MonthATypeHistory

---------------始终需要删除，与条件无关的部分 end ------

---------------根据条件删除单据 start ------
DECLARE @ifKeepWXBill int --是否保留维修
SET @ifKeepWXBill = 0

CREATE TABLE #TempBillNumberID(BillNumberID int,[ID] int,BillType int)		--保存要保留的单据billnumberid
CREATE TABLE #TempCouponBillNumberID(BillNumberID int,[ID] int,BillType int)		--保存要保留的优惠券单据billnumberid
-----------------------------------------------------------------------跨年结算处理 start-----------------------------------------------------------------------
-- 保留预收预付的余额转入的期初单据
INSERT INTO #TempBillNumberID
(
	BillNumberID,
	BillType
)
SELECT	BillNumberID,
		BillType
FROM	dbo.BillIndex
WHERE	IsIni=1 
		AND BillType IN (189,190)

----------------------------------------------门店配送单保留开始327----------------------------------------------
DELETE FROM PosAllotApplyBillIndex WHERE BillType in (328,329) AND IfCheck = 't' AND draft = 0 AND BillDate < @yearendDatetime 
DELETE FROM PosAllotApplyBillIndex   WHERE IfCheck='t' AND draft=0 AND BillType=327 AND RedWord<>0  AND BillDate < @yearendDatetime --红冲了的门店配送单都要删掉
DELETE DeliveryBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.PosAllotApplyBillIndex)
DELETE DeliveryBackBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.PosAllotApplyBillIndex)
DELETE DeliveryCheckBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.PosAllotApplyBillIndex)

CREATE TABLE #DeliveryBill(BillNumberId NUMERIC(18,0))

--后续有退货单和验收单的门店配送单要留下来
INSERT INTO #DeliveryBill(BillNumberId)
SELECT	DISTINCT 
		B.BillNumberId
FROM	(
			SELECT	D.BillNumberId
			FROM	DeliveryBill D
			INNER JOIN DeliveryBackBill B ON D.ID = B.DeliveryID
			INNER JOIN PosAllotApplyBillIndex Bill ON Bill.BillNumberId = B.BillNumberId
			WHERE	Bill.BillDate >= @yearendDatetime
					AND Bill.BillType = 328
			UNION ALL
			SELECT	D.BillNumberId
			FROM	DeliveryBill D
			INNER JOIN DeliveryCheckBill C ON D.ID = C.DeliveryID
			INNER JOIN PosAllotApplyBillIndex Bill ON Bill.BillNumberId = C.BillNumberId
			WHERE	Bill.BillDate >= @yearendDatetime
					AND Bill.BillType = 329
)B

--未结算完成的过账单据要留下来
INSERT INTO #DeliveryBill(BillNumberID)
SELECT  BillNumberID
FROM  dbo.PosAllotApplyBillIndex
WHERE  Isdone = 0
    AND ifcheck='t' 
    and draft=0 
    AND RedWord = 0 
    AND BillType IN (327) 
    AND BillDate < @yearendDatetime

IF @delDraft ='0' ---不删除草稿		
BEGIN
	INSERT INTO #DeliveryBill(BillNumberID)
	SELECT	BillNumberID
	FROM	dbo.PosAllotApplyBillIndex
	WHERE	ifcheck='f' 
			and draft=1 
			AND RedWord = 0 
			AND BillType IN (327) 
			AND BillDate < @yearendDatetime
END

UPDATE	PosAllotApplyBillIndex
SET		IsIni = 1,
		ifYearBill = 1
WHERE	BillNumberid IN (SELECT BillNumberId FROM #DeliveryBill where BillDate < @yearendDatetime)
		AND BillType = 327 AND draft=0
		
DELETE FROM PosAllotApplyBillIndex WHERE BillType = 327 AND BillNumberId NOT IN (SELECT BillNumberId FROM #DeliveryBill) AND Isdone = 1			

DROP TABLE #DeliveryBill

IF @delDraft ='1' ---草稿
BEGIN
	DELETE FROM PosAllotApplyBillIndex WHERE IfCheck = 'f' AND draft = 1 AND BillDate < @yearendDatetime
	DELETE FROM dbo.DeliveryBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)
	DELETE FROM dbo.DeliveryBackBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)	
END

IF @clearCompleteAllotApply = 1 --清除已完成的调货申请单
BEGIN
     DELETE PosAllotApplyBillIndex WHERE Isdone = 1 AND BillDate < @yearendDatetime and BillType=22 ;
END

IF @clearNoCompleteAllotApply = 1 --清除未完成的调货申请单
BEGIN
     DELETE PosAllotApplyBillIndex WHERE Isdone = 0 AND BillDate < @yearendDatetime and BillType=22;
END

IF @clearcompletegetbillapply = 1 --清除已完成的要货申请单
BEGIN   
     DELETE PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=326 AND BillDate < @yearendDatetime ;
     DELETE DeliveryApplyBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=326)
END
	
IF @clearnocompletegetbillapply = 1 --清除未完成的要货申请单
BEGIN
    
     DELETE PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=326  AND BillDate < @yearendDatetime;
     DELETE DeliveryApplyBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=326)
END

--bug2853,调货申请单，状态是作废的，年结存的时候直接清除掉，不管选项。祝伟已确认
DELETE PosAllotApplyBillIndex WHERE BillState = 4 AND BillType = 22 AND BillDate < @yearendDatetime;

DELETE PosAllotApplyBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM PosAllotApplyBillIndex where BillType=22)
----------------------------------------------门店配送单保留结束327----------------------------------------------

-- 保留超收超付，未结算完成的收付款单生成的期初收付款单
IF @yearendmode=0 AND @carryOverBillexcess=1
BEGIN
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberID,BillType
	FROM dbo.BillIndex
	WHERE IsIni=1 AND draft=0 AND ifYearBill=1 AND BillType IN (4,66) 
END

-- 保留所有未完成的单据(按单据年结的时候保留)
-- 保留未结算完成的销售单、销售退货单、销售换货单、委托代销结算单、采购单、采购退货单、采购换货单、受托代销结算单、费用单、固定资产购买 、固定资产变卖、其他收入单、返利执行、
	--价保执行单、获得价保、获利核算执行单、会员储值充值单、维修取件单、整机更换单、上门维修单、送修返回单、固定资产增加、固定资产减少
IF @yearendmode='0'
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	billnumberid,
			billtype 
	FROM	BillIndex 
	WHERE	RedWord=0 
			AND jsState <> 2 
			AND draft=0
			AND (
				BillType in(12,46,6,11,34,45,141,145,148,160,161,36,84,85,93,148,149,150,151,181,427,167,168,170,172,115,116,128,129,212,213,312) 
				OR (BillType=450 AND ChargeOffType IN (2,3,4,5))
				)
			AND (
				(nTotalMoney-ISNULL(NChargeOffTotal,0)-nCompleteTotal<>0 AND nTotalInMoney=0 AND nPreferenceMoney=0)
				OR (
					(
						(nTotalMoney-ISNULL(NChargeOffTotal,0)-(nCompleteTotal+nTotalInMoney+nPreferenceMoney)<0 AND nTotalMoney<0)
						OR
						(nTotalMoney-ISNULL(NChargeOffTotal,0)-(nCompleteTotal+nTotalInMoney+nPreferenceMoney)>0 AND nTotalMoney>=0)
					)
					AND (nTotalInMoney<>0 OR nPreferenceMoney<>0)
				)
				OR (BillType IN (160,161) AND jsStyle='2' AND jsState='1')
				)
			AND BillDate < @yearendDatetime 							
ELSE--保留应收应付的余额转入的期初单据
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberID,BillType
	FROM dbo.BillIndex
	WHERE IsIni=1 AND ifYearBill=1 AND BillType IN (115,116,128,129) AND jsState<>'2'
	
--保留结算数量＋退货数量小于单据数量的委托代销发货单和受托代销收货单
INSERT INTO #TempBillNumberID(BillNumberID,BillType)
SELECT BillNumberId,type AS BillType 
FROM	CommissionBill c  
LEFT JOIN(  
			SELECT	SUM(isnull(A.qty,0)) AS qty,A.oldid 
			FROM	CommissionBill A,BillIndex B
			WHERE	[TYPe] in(145,146) 
					AND A.BillNumberId=B.BillNumberId  AND B.RedWord=0 AND B.draft=0 
					AND b.BillDate < @yearendDatetime
			GROUP BY A.OldID
) a ON c.ID=a.OldID  
WHERE	c.Type=144  
		AND isnull(a.qty,0)<c.Qty 
		AND C.BillNumberId IN(SELECT BillNumberId FROM BillIndex WHERE draft=0 AND RedWord=0 AND BillDate < @yearendDatetime)
UNION ALL
SELECT BillNumberId,type AS BillType FROM CommissionBill c
LEFT JOIN (  
			SELECT	SUM(isnull(A.qty,0)) AS qty,A.oldid 
			FROM	CommissionBill  A,BillIndex B
			WHERE	[TYPe] in(141,142) AND A.BillNumberId=B.BillNumberId  AND B.RedWord=0 AND B.draft=0 AND b.BillDate < @yearendDatetime
			GROUP BY A.OldID
) a ON c.ID=a.OldID  
WHERE	c.Type=140  
		AND isnull(a.qty,0)<c.Qty 
		AND C.BillNumberId IN(SELECT BillNumberId FROM BillIndex WHERE draft=0 AND RedWord=0 AND BillDate < @yearendDatetime)		
				
-- 非“已取件”、“已换机”的接件单，要保留下来，包括其相关单据
-- “待上门维修”的报修单，要保留下来
IF EXISTS(SELECT TOP 1 1 FROM BillIndex a,wx_Bill_JieJian b WHERE a.BillType=165 AND a.Draft=0 AND a.ifCheck='t' AND a.RedWord=0 
	AND a.BillNumberID=b.BillNumberID AND b.State NOT IN (1,5) AND a.BillDate < @yearendDatetime)
	OR EXISTS(SELECT TOP 1 1 FROM BillIndex a,wx_Bill_Call b WHERE a.BillType=171 AND a.Draft=0 AND a.ifCheck='t' AND a.RedWord=0 
	AND a.BillNumberID=b.BillNumberID AND b.State=0  AND a.BillDate < @yearendDatetime)
	OR EXISTS(SELECT TOP 1 1 FROM BillIndex a,wx_Bill_Send b WHERE a.BillType=169 AND a.Draft=0 AND a.ifCheck='t' AND a.RedWord=0 
	AND a.BillNumberID=b.BillNumberID AND b.JieJianBillNumberID=-1 AND b.Qty-b.SendBackQty>0 AND a.BillDate < @yearendDatetime)
BEGIN
	SET @ifKeepWXBill = 1
	-- 1)预存手工录入的送修单，且明细中存在未返回数量大于0的记录
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,169 AS BillType 
		FROM wx_Bill_Send a,BillIndex b
		WHERE a.JieJianBillNumberID=-1 AND a.Qty-a.SendBackQty>0 AND a.BillNumberID=b.BillNumberID
			AND b.BillType=169 AND b.Draft = 0 AND b.ifCheck = 't' AND b.RedWord = 0  AND b.BillDate < @yearendDatetime
		GROUP BY a.BillNumberID,b.[ID]
	-- 预存相关联的送修返回单
	IF @yearendmode='0'
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,170 AS BillType 
		FROM wx_Bill_SendBack a,BillIndex b
		WHERE a.SendBillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID WHERE BillType=169) 
			AND a.BillNumberID = b.BillNumberID
			AND b.BillType=170 AND b.Draft = 0 AND b.ifCheck = 't' AND b.RedWord = 0
			 AND b.BillDate < @yearendDatetime
				 --AND a.BillDate < @yearendDatetime
		GROUP BY a.BillNumberID

	-- 2)非“已取件”、“已换机”的接件单，预存起来
	INSERT INTO #TempBillNumberID(BillNumberID,[ID],BillType) 
		SELECT a.BillNumberID,b.[ID],165 AS BillType
		FROM BillIndex a,wx_Bill_JieJian b
		WHERE a.BillType=165 AND a.Draft=0 AND a.ifCheck='t' AND a.RedWord=0 
			AND a.BillNumberID=b.BillNumberID AND b.State NOT IN (1,5)
			 AND a.BillDate < @yearendDatetime
		GROUP BY a.BillNumberID,b.[ID]
	-- 预存相关联的维修单
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT BillNumberID,166 AS BillType 
		FROM BillIndex
		WHERE JieJianBillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID WHERE BillType = 165)
				AND JieJianID IN (SELECT [ID] FROM #TempBillNumberID WHERE BillType = 165)
				AND BillType=166 AND Draft = 0 AND ifCheck = 't' AND RedWord = 0 
				 AND BillDate < @yearendDatetime
		GROUP BY BillNumberID
	-- 预存相关联的送修单
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,169 AS BillType 
		FROM wx_Bill_Send a,BillIndex b
		WHERE a.JieJianBillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID WHERE BillType = 165)
			AND a.JieJianID IN (SELECT [ID] FROM #TempBillNumberID WHERE BillType = 165)
			AND a.BillNumberID = b.BillNumberID AND b.BillType=169 AND b.Draft = 0 AND b.ifCheck = 't' AND b.RedWord = 0 
			 AND b.BillDate < @yearendDatetime
		GROUP BY a.BillNumberID
	-- 预存相关联的送修返回单
	IF @yearendmode='0'
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,170 AS BillType 
		FROM wx_Bill_SendBack a,BillIndex b
		WHERE a.SendBillNumberID IN (
			SELECT BillNumberID FROM wx_Bill_Send
			WHERE JieJianBillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID WHERE BillType = 165)
				AND JieJianID IN (SELECT [ID] FROM #TempBillNumberID WHERE BillType = 165)) AND a.BillNumberID = b.BillNumberID 
				AND b.BillType=170 AND b.Draft = 0 AND b.ifCheck = 't' AND b.RedWord = 0 
				 AND b.BillDate < @yearendDatetime
				 --AND a.BillDate < @yearendDatetime
		GROUP BY a.BillNumberID

	-- 3)预存非“待上门维修”的报修单
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,171 AS BillType 
		FROM wx_Bill_Call a,BillIndex b
		WHERE a.State = 0 AND a.BillNumberID = b.BillNumberID AND b.BillType = 171 AND b.Draft = 0 AND b.ifCheck = 't' 
			AND b.RedWord = 0  AND b.BillDate < @yearendDatetime
		GROUP BY a.BillNumberID			
END

CREATE TABLE #TempReceiptBillNumberID(BillNumberID INT)

IF @yearendmode='0'  --按单据结转
BEGIN
	--未开票完成的单据一律保留
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberId,BillType 
	FROM	BillIndex 
	WHERE BillType IN (400,401,402,403) AND IfInvoice<>2
	AND ((Ifcheck='t' AND RedWord=0) OR (IsIni=1))
	
	--未结算完成的发票一律保留;所关联的物流单据未开票完成的也保留
	INSERT #TempReceiptBillNumberID
	SELECT BillNumberID
	FROM ReceiptBillIndex
	WHERE  --(nTotalMoney-nCompleteTotal<>0) AND
	JSState<>2 AND
	((Ifcheck='t' AND RedWord=0) OR (IsIni=1))
	UNION ALL
	SELECT a.BillNumberID
	FROM ReceiptBill a
	INNER JOIN ReceiptBillIndex b
	ON a.BillNumberID=b.BillNumberID
	WHERE ( (b.Ifcheck='t' AND b.RedWord=0) OR (b.IsIni=1) )
	AND a.MainBillNumberID IN
	(
		SELECT BillNumberID
		FROM #TempBillNumberID
	)
	
	--未结算完成的往来核销单关联的物流单据一律保留
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT FromBillNumberid,FromBillType FROM dbo.ChargeOffBill
	WHERE FromBillType NOT IN (404,405) AND BillNumberId IN(SELECT BillNumberID FROM #TempBillNumberID WHERE Billtype=450) 
	
	--未结算完成的往来核销单关联的物流单据一律保留
	INSERT INTO #TempReceiptBillNumberID
	SELECT FromBillNumberid from dbo.ChargeOffBill
	WHERE FromBillType IN (404,405) AND BillNumberId IN(SELECT BillNumberID FROM #TempBillNumberID WHERE Billtype=450) 
	
	--把保留的物流单据改为期初单据
	UPDATE BillIndex
	SET IsIni=1,ifYearBill=1
	WHERE BillNumberID IN
	(	
		SELECT BillNumberID
		FROM #TempBillNumberID
	) AND BillType IN (400,401,402,403,450)
	
	--把保留的优惠券单据改为期初单据
	UPDATE dbo.Coupon_BillIndex
	SET IsIni=1,IfYearBill=1
	WHERE billnumberid IN 
	(
		SELECT BillNumberID
		FROM #TempCouponBillNumberID
	)AND BILLTYPE IN(423,424,426)
	
	
	--把保留的发票改为期初发票
	UPDATE ReceiptBillIndex
	SET IsIni=1,ifYearBill=1
	WHERE BillNumberID IN
	(	
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
	)

	DELETE ReceiptBill
	WHERE BillNumberID IN
	(
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE ifYearBill=0 AND ifcheck='f'
	)
	
	
	DELETE ReceiptBillIndex
	WHERE BillNumberID IN
	(
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE ifYearBill=0 AND ifcheck='f'
	)

END
ELSE
BEGIN	
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	billnumberid,billtype 
	FROM	BillIndex 
	WHERE Isini=1 AND ifYearBill=0 AND BillType IN (115,116,128,129) AND jsState<>2
	
	--未开票完成的单据一律保留
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberId,BillType 
	FROM	BillIndex 
	WHERE  BillType IN (400,401,402,403) AND IfInvoice<>2
	AND ((Ifcheck='t' AND RedWord=0) OR (IsIni=1))

	--开票单据的日期在年结存之后，开票完成 
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT BillNumberId,BillType 
	FROM BillIndex bil
	WHERE bil.IfInvoice=2 AND bil.BillType IN (400,401,402,403) 
	AND EXISTS 
	(SELECT TOP 1 1  
	FROM dbo.ReceiptBill re
	left JOIN dbo.ReceiptBillIndex rei ON rei.BillNumberID = re.BillNumberID  AND rei.BillType = re.BillType
	WHERE re.MainBillNumberID=bil.BillNumberId AND re.MainBillType=bil.BillType
	 AND rei.BillDate>=@yearendDatetime
	 )

	--把保留的物流单据改为期初单据
	UPDATE BillIndex
	SET IsIni=1,ifYearBill=1
	WHERE BillNumberID IN
	(	
		SELECT BillNumberID
		FROM #TempBillNumberID
	) AND BillType IN (400,401,402,403,450)
END

---------------仓储运输单据 结转-------------

--清除已过账的上架单、拣货单、运输配送单

IF @delDraft ='1'
BEGIN
	DELETE FROM onShelvespickIndex WHERE BillDate < @yearendDatetime
END
ELSE
BEGIN
	DELETE  dbo.onShelvespickIndex WHERE BillDate < @yearendDatetime AND IfCheck='t' AND RedWord=0 AND draft=0
END

DELETE onShelvesbill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.onShelvespickIndex)
DELETE PickBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.onShelvespickIndex)

---------------仓储运输单据 结转-------------

---------------实物库存结转------------------

IF @delDraft='1'
BEGIN
	DELETE FROM dbo.FactIndex WHERE BillDate < @yearendDatetime
END
ELSE
BEGIN
	DELETE FROM dbo.FactIndex WHERE BillDate < @yearendDatetime AND ifcheck='t'
END

DELETE FROM dbo.FactDepotAllot WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
DELETE FROM dbo.FactDepotInOut WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
DELETE FROM FactInOut WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.FactIndex WHERE BillNumberId = dbo.FactInOut.billNumberID AND billtype=dbo.FactInOut.billtype)

IF @PhysicalComplete='1'
BEGIN
	EXEC GP_YearProcPhyStock
END
---------------实物库存结转------------------

INSERT	INTO #TempBillNumberID( BillNumberID, BillType )
SELECT BillNumberId,BillType FROM dbo.BillIndex WHERE BillDate >= @yearendDatetime

IF @unfinishedinvoice=1 --保留未开票完成的单据
BEGIN
--保留未开票完成零售单、销售单、销售退货单、销售换货单、委托代销结算单、采购单、采购退货单、采购换货单、受托代销结算单
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	billnumberid,billtype 
	FROM	BillIndex 
	WHERE	RedWord=0 
			AND IfInvoice<>2 
			AND draft=0 
			AND BillType IN(11,34,305,45,160,141,6,161,145,312)
			AND BillDate < @yearendDatetime
END

IF @chkcompleterequestbill=1 --删除已完成请购单
BEGIN
	SELECT * INTO #requestindex FROM dbo.RequestIndex 
	WHERE (isstop=0 AND BillNumberId IN (SELECT BillNumberId FROM requestbill WHERE ISNULL(sendqty,0)<qty AND isstop=0))
		OR BillDate >= @yearendDatetime
		
	SELECT b.* INTO #requestbill FROM dbo.RequestBill b INNER JOIN #requestindex a ON b.BillNumberId=a.BillNumberId
	
	TRUNCATE TABLE RequestIndex
	SET IDENTITY_INSERT RequestIndex ON
	SET @columns=dbo.f_getallcolumns('RequestIndex')
	EXEC('INSERT INTO RequestIndex ('+@columns+') SELECT '+@columns+ ' FROM #requestindex')
	SET IDENTITY_INSERT RequestIndex OFF
	
	TRUNCATE TABLE dbo.RequestBill
	SET IDENTITY_INSERT RequestBill ON
	SET @columns=dbo.f_getallcolumns('RequestBill')
	EXEC('INSERT INTO RequestBill ('+@columns+') SELECT '+@columns+ ' FROM #requestbill')
	SET IDENTITY_INSERT RequestBill OFF
	
	DROP TABLE #requestbill,#requestindex
END
ELSE
BEGIN
	DELETE FROM RequestIndex WHERE BillDate < @yearendDatetime
	DELETE FROM dbo.RequestBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.RequestIndex)
END

IF @unfinishedposbill=0 --pos小票数据处理
BEGIN
	DELETE FROM dbo.PosSaleBillIndexAll 
	WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndex WHERE BillnumberID=dbo.PosSaleBillIndexAll.BillnumberID)
		AND billdate < @yearendDatetime
END
ELSE
BEGIN
	DELETE FROM dbo.PosSaleBillIndexAll 
	WHERE billdate < @yearendDatetime
	
	DELETE FROM dbo.PosSaleBillIndex 
	WHERE billdate < @yearendDatetime
END	

DELETE FROM dbo.PosSaleBill WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndex WHERE BillnumberID=dbo.PosSaleBill.BillnumberID)
DELETE FROM dbo.PosMulAccount WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndex WHERE BillnumberID=dbo.PosMulAccount.BillnumberID)
DELETE FROM dbo.PosSaleBillAll WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndexAll WHERE BillnumberID=dbo.PosSaleBillAll.BillnumberID)
DELETE FROM dbo.PosMulAccountAll WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndexALL WHERE BillnumberID=dbo.PosMulAccountAll.BillnumberID)
DELETE FROM dbo.PosRetailRecord WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndexAll WHERE BillnumberID=dbo.PosRetailRecord.PosBillNumberId)
OR RetailBillNumberId NOT IN(SELECT BillNumberID FROM #TempBillNumberID WHERE BillType IN(215,305))
-----------------------------------------------------------------------跨年结算处理-----------------------------------------------------------------------
		
---------------删除单据主表----------
IF EXISTS (SELECT NAME FROM sysobjects WHERE type='tr' AND NAME = 'DeleteBill')
	DROP TRIGGER DeleteBill
	
IF @delDraft ='1'
BEGIN
	SELECT * INTO #BillIndexd FROM dbo.BillIndex WHERE BillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID)
	TRUNCATE TABLE dbo.BillIndex
	
	DELETE FROM CommissionBillNew WHERE BillDate < @yearendDatetime
	DELETE FROM LendIndex WHERE BillDate < @yearendDatetime
	DELETE FROM LendCheck WHERE BillDate < @yearendDatetime

	SET IDENTITY_INSERT BillIndex ON
	SET @columns=dbo.f_getallcolumns('billindex')
	EXEC('INSERT INTO BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #BillIndexd')
	SET IDENTITY_INSERT BillIndex OFF
	
	
	DELETE FROM SerialAdjustIndex WHERE BillDate < @yearendDatetime
	
	DELETE ReceiptBillIndex 
	WHERE BillNumberID NOT IN
	(
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
	)
	AND BillDate < @yearendDatetime
	
	DELETE ReceiptBill
	WHERE BillNumberID NOT IN
	(
		SELECT BillNumberID
		FROM ReceiptBillIndex
	)
	
END
ELSE
BEGIN
	-- 年结存往来核销单一律不保留
	SELECT * INTO #BillIndext 
	FROM dbo.BillIndex 
	WHERE (Draft = 1 AND ifYearBill=0 AND BillType NOT IN (450)) 
		OR BillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID)
	TRUNCATE TABLE dbo.BillIndex
	
	SET IDENTITY_INSERT BillIndex ON
	SET @columns=dbo.f_getallcolumns('billindex')
	EXEC('INSERT INTO BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #BillIndext')
	SET IDENTITY_INSERT BillIndex OFF
	
	DELETE FROM SerialAdjustIndex  WHERE Draft = 0 AND BillDate < @yearendDatetime
	
	--保留草稿
	SELECT * INTO #CommissionBillNewt FROM CommissionBillNew WHERE draft=1 OR BillDate >= @yearendDatetime;
	TRUNCATE TABLE CommissionBillNew;
	
	SET IDENTITY_INSERT CommissionBillNew ON
	SET @columns=dbo.f_getallcolumns('CommissionBillNew')
	EXEC('INSERT INTO CommissionBillNew ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBillNewt')
	SET IDENTITY_INSERT CommissionBillNew OFF
	
	
	--借欠
	SELECT * INTO #LendIndext FROM LendIndex WHERE draft=1 OR BillDate >= @yearendDatetime;
	TRUNCATE TABLE LendIndex;
	
	SET IDENTITY_INSERT LendIndex ON
	SET @columns=dbo.f_getallcolumns('LendIndex')
	EXEC('INSERT INTO LendIndex ('+@columns+') SELECT '+@columns+ ' FROM #LendIndext')
	SET IDENTITY_INSERT LendIndex OFF
	
	
	DELETE ReceiptBillIndex
	WHERE BillNumberID NOT IN
	(
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
		UNION ALL
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE ifcheck='f'
	)
	AND BillDate < @yearendDatetime
	
	DELETE ReceiptBill
	WHERE BillNumberID NOT IN
	(
		SELECT BillNumberID
		FROM ReceiptBillIndex
	)
END

--加期初单据标志
--IF @yearendmode='0'
--BEGIN
UPDATE billindex SET IsIni=1 WHERE draft=0 AND billtype NOT IN (171,169,166,165,144,140) AND BillDate < @yearendDatetime
UPDATE billindex SET CompleteTotal=CompleteTotal+totalinmoney,NCompleteTotal=NCompleteTotal+NTotalInMoney WHERE isini=1 AND billtype NOT IN (181,312)
UPDATE billindex SET totalinmoney=0,NTotalInMoney=0 WHERE isini=1 AND billtype NOT IN (181,312)
--END
---------------删除单据主表 end----------
	

IF @delDraft ='1'
BEGIN
	SELECT * INTO #salebill1 FROM salebill  WHERE billnumberid IN(SELECT billnumberid FROM #TempBillNumberID WHERE billtype ='11')
	TRUNCATE TABLE SaleBill
	SET IDENTITY_INSERT SaleBill ON
	SET @columns=dbo.f_getallcolumns('SaleBill')
	EXEC('INSERT INTO SaleBill ('+@columns+') SELECT '+@columns+ ' FROM #salebill1')
	SET IDENTITY_INSERT SaleBill OFF
	DROP TABLE #salebill1
	
	SELECT * INTO #BuyBill1 FROM buybill WHERE billnumberid IN (SELECT Billnumberid FROM #TempBillNumberID WHERE Billtype='34' )
	TRUNCATE TABLE BuyBill
	SET IDENTITY_INSERT BuyBill ON
	SET @columns=dbo.f_getallcolumns('BuyBill')
	EXEC('INSERT INTO BuyBill ('+@columns+') SELECT '+@columns+ ' FROM #BuyBill1')
	SET IDENTITY_INSERT BuyBill OFF
	DROP TABLE #BuyBill1
	
	DELETE FROM SaleBackBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillType=45 AND b.BillNumberId=SaleBackBill.BillNumberId)						--销售退货单
	DELETE FROM BuyBackBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillType=6 AND b.BillNumberId=dbo.BuyBackBill.BillNumberId )						--采购退货单
	DELETE FROM CommissionBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=CommissionBill.BillNumberId)	--代销单据		
	DELETE FROM SaleGoodsExchangeBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillType=160 AND b.BillNumberId=SaleGoodsExchangeBill.BillNumberId)	--销售换货单
	DELETE FROM BuyGoodsExchangeBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillType=161  AND b.BillNumberId=BuyGoodsExchangeBill.BillNumberId)		--采购换货单			
	DELETE FROM RetailBill WHERE  NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=RetailBill.BillNumberId AND b.BillType=305)							--零售单	
	DELETE FROM RetailCombinationBill WHERE  NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=RetailCombinationBill.BillNumberId AND b.BillType=305)		
	DELETE FROM RetailBackBill WHERE  NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=RetailBackBill.BillNumberId AND b.BillType=215)					--零售退货单	
	DELETE FROM PreBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=PreBill.BillNumberId AND b.billtype IN (189,190))						-- 预收款单，预付款单				
	DELETE FROM AdDebtBill	WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=AdDebtBill.BillNumberId AND b.billtype IN('115','116','128','129'))-- 调账单	
	DELETE FROM MoneyBill	WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=MoneyBill.BillNumberId)	--其他收入、费用单、固定资产购买及变卖、费用单	
	DELETE FROM PriceProtectBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PriceProtectBill.BillNumberId)			-- 价保单
	DELETE FROM Advantage		 WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=Advantage.BillNumberId)			-- 返利、获利单
	DELETE FROM AssetIncDecBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=AssetIncDecBill.BillNumberId AND b.BillType IN (212,213))	--固定资产增加减少
	DELETE FROM AppraisalBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=AppraisalBill.BillNumberId AND b.BillType=400) --暂估入库单
	DELETE FROM AppraisalBackBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=AppraisalBackBill.BillNumberId AND b.BillType=401) --暂估退货单
	DELETE FROM SendBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=SendBill.BillNumberId AND b.BillType=402) --发出商品出库单
	DELETE FROM SendBackBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=SendBackBill.BillNumberId AND b.BillType=403) --发出商品退货单
	DELETE FROM ChargeOffBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=ChargeOffBill.BillNumberId AND b.BillType=450) --往来核销单
	DELETE FROM GiveBill	WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=GiveBill.BillNumberId AND b.BillType=139)			-- 赠送单
	DELETE FROM MoveBill	WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=MoveBill.BillNumberId AND b.BillType=17)			-- 同价调拨单
	DELETE FROM MoveBjBill	WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=MoveBjBill.BillNumberId AND b.BillType=21)		-- 变价调拨单	
	DELETE FROM STypeMoveBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=STypeMoveBill.BillNumberId AND b.BillType=187)		-- 分支机构调拨单
	DELETE FROM OtherInOutBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=OtherInOutBill.BillNumberId AND b.BillType=202)		--其他出入库单明细		
	DELETE FROM DisassembleBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=DisassembleBill.BillNumberId AND b.BillType=16)		-- 生产拆装单	
	DELETE FROM GiveMeBill	WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=GiveMeBill.BillNumberId AND b.BillType=126)		-- 获赠单
	DELETE FROM IntegralExchangeBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=IntegralExchangeBill.BillNumberId AND b.BillType=183)	--(积分兑换单明细表)  
	DELETE FROM dbo.PT_Combin_SaleBackBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PT_Combin_SaleBackBill.BillNumberId AND b.BillType=46) --组合品销售退货单
	DELETE FROM dbo.PT_Combin_SaleBackBillDetail WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PT_Combin_SaleBackBillDetail.BillNumberId AND b.BillType=46) --组合品销售退货单
	DELETE FROM dbo.PT_Combin_SaleBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PT_Combin_SaleBill.BillNumberId AND b.BillType=12) --组合品销售出库单
	DELETE FROM dbo.PT_Combin_SaleBillDetail WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PT_Combin_SaleBillDetail.BillNumberId AND b.BillType=12) --组合品销售出库单
	DELETE FROM dbo.Transportbill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID B WHERE b.BillNumberID=dbo.Transportbill.billNumberID AND B.BillType=414)
	DELETE FROM dbo.Transportcontrastbill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID B WHERE b.BillNumberID=dbo.Transportcontrastbill.billNumberID AND B.BillType=414)
	
	DELETE FROM dbo.BeforePromoteIndex WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)	--零售零售促销方案主表
	DELETE FROM dbo.BeforePromoteSaleBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)
	DELETE FROM BeforePromoteRetailBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)
	DELETE FROM dbo.BeforePromoteRetailBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)	--零售零食促销方案明细
	DELETE FROM dbo.DepBill		 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)	--固定资产折旧
	DELETE FROM GatheringBill	 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)	--收款单
	DELETE FROM PayBill			 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)	--付款单
	DELETE FROM LoseBill		 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)		-- 报损单
	DELETE FROM OverFlowBill	 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)		-- 报溢单
	DELETE FROM MoveMoneyBill	 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)	-- 转款单
	DELETE FROM adPriceBill	 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)		-- 成本调价单
	DELETE FROM InvoiceBill	 WHERE InvoiceDate < @yearendDatetime		-- 发票表
	DELETE FROM RepairDeal	 WHERE BillDate < @yearendDatetime		-- #01 维修受理单表			
	DELETE FROM RepairDealDetail WHERE BillNumberId NOT IN(SELECT BillNumberId FROM RepairDeal)		-- #01 维修受理单明细表
	DELETE FROM RepairEngage WHERE Draft = 0 AND BillDate < @yearendDatetime
	DELETE FROM DiyBillTypePSaleTypeID WHERE SalebillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)
	DELETE FROM GoodsExchangeBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM BillIndex)	-- 换货单
	DELETE FROM AccountCredence	 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)	-- 会计凭证	
	DELETE FROM SerialAdjustBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM SerialAdjustIndex)		--序列号调整单明细
	DELETE FROM CM_CarUseIndex	 WHERE BillDate < @yearendDatetime	--车辆使用登记单主表
	DELETE FROM CM_CarUseBill	 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM CM_CarUseIndex)	--车辆使用登记单明细表）
	DELETE FROM CM_FeeIndex		 WHERE BillDate < @yearendDatetime	--车辆费用单主表） 
	DELETE FROM CM_FeeBill		 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM CM_FeeIndex)	--车辆费用单明细表）		
	DELETE FROM wx_Bill_JieJian WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_JieJian.BillNumberId)
	DELETE FROM wx_Bill_Self WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Self.BillNumberId)
	DELETE FROM wx_Bill_Send WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Send.BillNumberId)
	DELETE FROM wx_Bill_Call WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Call.BillNumberId)
	DELETE FROM wx_Bill_Replace WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Replace.BillNumberId AND b.BillType=168)		-- 新维修 - 整机更换单
	DELETE FROM wx_Bill_GetBack WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_GetBack.BillNumberId AND b.BillType=167)		-- 新维修 - 维修取件单
	DELETE FROM wx_Bill_Goto WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Goto.BillNumberId AND b. BillType=172)				-- 新维修 - 上门维修单
	DELETE FROM wx_Bill_SendBack WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_SendBack.BillNumberId AND b.BillType=170)      --送修返回
	DELETE FROM wx_Bill_In		 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)	-- 新维修 - 维修品调入单
	DELETE FROM wx_Bill_Out	 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)		-- 新维修 - 维修品调出单
	DELETE FROM wx_Bill_Move	 WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)		-- 新维修 - 维修品调拨单
	DELETE FROM CommissionBillNewDetail WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.CommissionBillNew)
	DELETE FROM LendBill		WHERE BillNumberId NOT IN(SELECT BillNumberId FROM LendIndex)		-- 借欠	
	DELETE FROM dbo.VipCentToMoneyBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=BillNumberId AND b.BillType=427) --积分转储值单
END
ELSE
BEGIN
	SELECT * INTO #salebill FROM salebill  WHERE billnumberid IN(SELECT billnumberid FROM billindex WHERE billtype ='11' )
	TRUNCATE TABLE SaleBill
	SET IDENTITY_INSERT SaleBill ON
	SET @columns=dbo.f_getallcolumns('SaleBill')
	EXEC('INSERT INTO SaleBill ('+@columns+') SELECT '+@columns+ ' FROM #salebill')
	SET IDENTITY_INSERT SaleBill OFF
	DROP TABLE #salebill
	
	SELECT * INTO #BuyBill FROM buybill WHERE billnumberid IN (SELECT Billnumberid FROM billindex WHERE Billtype='34') 
	TRUNCATE TABLE BuyBill
	SET IDENTITY_INSERT BuyBill ON
	SET @columns=dbo.f_getallcolumns('BuyBill')
	EXEC('INSERT INTO BuyBill ('+@columns+') SELECT '+@columns+ ' FROM #Buybill')
	SET IDENTITY_INSERT BuyBill OFF
	DROP TABLE #Buybill
	
	SELECT * INTO #CommissionBillNewDetail FROM CommissionBillNewDetail WHERE billnumberid in (SELECT billnumberid FROM #CommissionBillNewt)
	TRUNCATE TABLE CommissionBillNewDetail
	
	SET IDENTITY_INSERT CommissionBillNewDetail ON
	SET @columns=dbo.f_getallcolumns('CommissionBillNewDetail')
	EXEC('INSERT INTO CommissionBillNewDetail ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBillNewDetail')
	SET IDENTITY_INSERT CommissionBillNewDetail OFF
	DROP TABLE #CommissionBillNewDetail
	
	SELECT * INTO #LendBillt FROM LendBill WHERE billnumberid in (SELECT billnumberid FROM #LendIndext)
	TRUNCATE TABLE LendBill
	
	SET IDENTITY_INSERT LendBill ON
	SET @columns=dbo.f_getallcolumns('LendBill')
	EXEC('INSERT INTO LendBill ('+@columns+') SELECT '+@columns+ ' FROM #LendBillt')
	SET IDENTITY_INSERT LendBill OFF
	DROP TABLE #LendBillt

	DELETE FROM SaleBackBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE b.billtype ='45' AND b.BillNumberId=SaleBackBill.BillNumberId)	-- 销售退货单
	DELETE FROM GatheringBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE b.billtype ='4'  AND b.BillNumberId=GatheringBill.BillNumberId)	-- 收款单
	DELETE FROM DiyBillTypePSaleTypeID WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=DiyBillTypePSaleTypeID.SalebillNumberId)
	DELETE FROM BuyBackBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=BuyBackBill.BillNumberId)						-- 采购退货单
	DELETE FROM PayBill			 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=PayBill.BillNumberId)			-- 付款单
	DELETE FROM LoseBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=LoseBill.BillNumberId)		-- 报损单
	DELETE FROM OverFlowBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=OverFlowBill.BillNumberId)			-- 报溢单
	DELETE FROM MoveMoneyBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=MoveMoneyBill.BillNumberId)		-- 转款单
	DELETE FROM adDebtbill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=adDebtbill.BillNumberId)			-- 调账单
	DELETE FROM adPriceBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=adPriceBill.BillNumberId)			-- 成本调价单
	DELETE FROM MoveBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=MoveBill.BillNumberId)			-- 同价调拨单
	DELETE FROM MoveBjBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=MoveBjBill.BillNumberId)			-- 变价调拨单
	DELETE FROM MoneyBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=MoneyBill.BillNumberId)			-- 收入、费用单、、待摊费用表、现金费用	
	DELETE FROM RetailBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailBill.BillNumberId)			-- 零售单
	DELETE FROM RetailCombinationBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailCombinationBill.BillNumberId)			-- 零售单
	DELETE FROM RetailBackBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailBackBill.BillNumberId)			-- 零售退货单
	DELETE FROM BeforePromoteIndex WHERE NOT EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BeforePromoBillNumberId=dbo.BeforePromoteIndex.BillNumberId AND draft=1)	--零售零售促销方案主表
	DELETE FROM BeforePromoteRetailBill WHERE NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.BeforePromoteRetailBill.BillNumberId)	--零售零食促销方案明细	
	DELETE FROM DisassembleBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=DisassembleBill.BillNumberId)		-- 生产拆装单
	DELETE FROM CommissionBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=CommissionBill.BillNumberId)		-- 代销单据
	DELETE FROM PriceProtectBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=PriceProtectBill.BillNumberId)			-- 价保单
	DELETE FROM Advantage		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=Advantage.BillNumberId)			-- 返利、获利单
	DELETE FROM GiveMeBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=GiveMeBill.BillNumberId)		-- 获赠单
	DELETE FROM GiveBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=GiveBill.BillNumberId)		-- 赠送单
	DELETE FROM AssetIncDecBill  WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=AssetIncDecBill.BillNumberId AND b.BillType IN (212,213))	--固定资产增加减少
	DELETE FROM DepBill  WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=DepBill.BillNumberId )	--固定资产折旧
	DELETE FROM FixedAssetsDetails WHERE NOT EXISTS(SELECT 1 FROM FixedAssetsIndex b WHERE b.BillNumberId=dbo.FixedAssetsDetails.BillNumberID) --固定资产盘点单
	DELETE FROM VipAddMoneyBatchBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=VipAddMoneyBatchBill.BillNumberId AND b.BillType =312)--会员储值单
	DELETE FROM VipCentToMoneyBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=VipCentToMoneyBill.BillNumberId AND b.BillType =427)--会员积分转储值单
	
	
	DELETE FROM CapitalTransfer_Bill WHERE NOT EXISTS(SELECT 1 FROM billindex b WHERE b.BillNumberId=dbo.CapitalTransfer_Bill.BillNumberId) --资金调拨单
	
	DELETE FROM RepairDeal WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RepairDeal.BillNumberId)
	DELETE FROM RepairDealDetail WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RepairDealDetail.BillNumberId)
	DELETE FROM RepairEngage WHERE NOT EXISTS (SELECT 1 FROM RepairDeal b WHERE  b.EngageBillID=RepairEngage.BillNumberId) AND Draft=0 AND Stat=3
	DELETE FROM GoodsExchangeBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=GoodsExchangeBill.BillNumberId)		-- 换货单
	DELETE FROM AccountCredence WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=AccountCredence.BillNumberId)			-- 会计凭证
	DELETE FROM SaleGoodsExchangeBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=SaleGoodsExchangeBill.BillNumberId)	-- 销售换货单
	DELETE FROM buyGoodsExchangeBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=buyGoodsExchangeBill.BillNumberId)		-- 采购换货单

	-- 清除新维修相关表
	DELETE FROM wx_Bill_JieJian WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_JieJian.BillNumberId)			-- 新维修 - 接件单
	DELETE FROM wx_Bill_Self WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Self.BillNumberId)				-- 新维修 - 维修单		
	DELETE FROM wx_Bill_GetBack WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_GetBack.BillNumberId)			-- 新维修 - 维修取件单		
	DELETE FROM wx_Bill_Replace WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Replace.BillNumberId)			-- 新维修 - 整机更换单				
	DELETE FROM wx_Bill_Send WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Send.BillNumberId)				-- 新维修 - 送修单
	DELETE FROM wx_Bill_SendBack WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_SendBack.BillNumberId)			-- 新维修 - 送修返回单
	DELETE FROM wx_Bill_Call WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Call.BillNumberId)				-- 新维修 - 报修单
	DELETE FROM wx_Bill_Goto WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Goto.BillNumberId)				-- 新维修 - 上门维修单		
	DELETE FROM wx_Bill_In WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_In.BillNumberId)				-- 新维修 - 维修品调入单
	DELETE FROM wx_Bill_Out WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Out.BillNumberId)				-- 新维修 - 维修品调出单
	DELETE FROM wx_Bill_Move WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Move.BillNumberId)				-- 新维修 - 维修品调拨单	
	DELETE FROM PreBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=PreBill.BillNumberId)					-- 预收、预付单
	DELETE FROM STypeMoveBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=STypeMoveBill.BillNumberId)			-- 分支机构调拨单			
	DELETE FROM IntegralExchangeBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=IntegralExchangeBill.BillNumberId)		--积分兑换单			
	DELETE FROM QuotePriceBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=QuotePriceBill.BillNumberId)
	DELETE FROM AskPriceBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=AskPriceBill.BillNumberId)	
	DELETE FROM SerialAdjustBill WHERE NOT EXISTS(SELECT 1 FROM SerialAdjustIndex WHERE draft = 1 AND BillNumberId=dbo.SerialAdjustBill.BillNumberId)			--序列号调整单明细
	DELETE FROM OtherInOutBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=OtherInOutBill.BillNumberId)			--其他出入库单明细
	DELETE FROM InvoiceBill WHERE InvoiceDate < @yearendDatetime
	
	--暂估，发出商品单据处理
	DELETE FROM AppraisalBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=AppraisalBill.BillNumberId AND b.BillType=400) --暂估入库单
	DELETE FROM AppraisalBackBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=AppraisalBackBill.BillNumberId AND b.BillType=401) --暂估退货单
	DELETE FROM SendBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=SendBill.BillNumberId AND b.BillType=402) --发出商品出库单
	DELETE FROM SendBackBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=SendBackBill.BillNumberId AND b.BillType=403) --发出商品退货单
	DELETE FROM ChargeOffBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=ChargeOffBill.BillNumberId AND b.BillType=450) --往来核销单
	DELETE FROM dbo.PT_Combin_SaleBackBill WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=PT_Combin_SaleBackBill.BillNumberId AND b.BillType=46) --组合品销售退货单
	DELETE FROM dbo.PT_Combin_SaleBackBillDetail WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=PT_Combin_SaleBackBillDetail.BillNumberId AND b.BillType=46) --组合品销售退货单
	DELETE FROM dbo.PT_Combin_SaleBill WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=PT_Combin_SaleBill.BillNumberId AND b.BillType=12) --组合品销售出库单
	DELETE FROM dbo.PT_Combin_SaleBillDetail WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=PT_Combin_SaleBillDetail.BillNumberId AND b.BillType=12) --组合品销售出库单
	DELETE FROM dbo.Transportbill WHERE NOT EXISTS(SELECT 1 FROM Billindex B WHERE b.BillNumberID=dbo.Transportbill.billNumberID AND B.BillType=414)
	DELETE FROM dbo.Transportcontrastbill WHERE NOT EXISTS(SELECT 1 FROM Billindex B WHERE b.BillNumberID=dbo.Transportcontrastbill.billNumberID AND B.BillType=414)
	
	DELETE FROM BeforePromoteIndex WHERE NOT EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BeforePromoBillNumberId=dbo.BeforePromoteIndex.BillNumberId AND draft=1)	--零售零售促销方案主表
	DELETE FROM BeforePromoteRetailBill WHERE NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.BeforePromoteRetailBill.BillNumberId)	--零售零食促销方案明细
	DELETE FROM BeforePromoteSaleBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BeforePromoteIndex WHERE BillNumberId=BeforePromoteSaleBill.BillNumberId)	
	
	
END

-------------------------------------------------------------------------------------------处理优惠券 BEGIN----------------------------------------------------------------------------------------
IF @delDraft ='1'
BEGIN
	--优惠券年结 不保存未结算完成的单据，只转应收应付余额
	DELETE FROM dbo.Coupon_BillIndex WHERE BillDate < @yearendDatetime	
	DELETE FROM Coupon_BillUsed WHERE BillnumberId NOT IN (SELECT BillnumberId FROM dbo.BillIndex )
	DELETE FROM Coupon_CodeInOut WHERE BillDate < @yearendDatetime
	DELETE FROM dbo.coupon_InBill  WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.Coupon_BillIndex)
	DELETE FROM dbo.coupon_OutBill   WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.Coupon_BillIndex)
	DELETE FROM dbo.coupon_BackBill   WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.Coupon_BillIndex)
	DELETE FROM dbo.coupon_AllotBill   WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.Coupon_BillIndex)	
	
	--如果结转的是已消费的优惠券 ，券信息也被清了
	DELETE FROM dbo.Coupon_CodeInfo WHERE [State] = 3 AND CouponCode NOT IN (SELECT CouponCode FROM dbo.Coupon_BillUsed)
	DELETE FROM dbo.Coupon_CodeInfo WHERE [STATE] = 6 AND CouponCode NOT IN (SELECT CouponCode FROM dbo.Coupon_CodeInOut)
END
ELSE
BEGIN
	--保留草稿
	SELECT * INTO #CouponBillIndexd FROM dbo.Coupon_BillIndex WHERE (Draft = 1 AND ifYearBill=0 ) OR BillDate >= @yearendDatetime
	
	TRUNCATE TABLE dbo.Coupon_BillIndex
	SET IDENTITY_INSERT Coupon_BillIndex ON
	SET @columns=dbo.f_getallcolumns('Coupon_BillIndex')
	EXEC('INSERT INTO Coupon_BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #CouponBillIndexd')
	SET IDENTITY_INSERT Coupon_BillIndex OFF
								
	DELETE FROM Coupon_BillUsed WHERE BillnumberId NOT IN (SELECT BillnumberId FROM dbo.BillIndex )
	DELETE FROM Coupon_CodeInOut WHERE BillDate < @yearendDatetime
	
	DELETE FROM dbo.coupon_InBill WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_InBill.billNumberID AND b.BillType=423)
	DELETE FROM dbo.coupon_OutBill WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_OutBill.billNumberID AND b.BillType=424)
	DELETE FROM dbo.coupon_BackBill WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_BackBill.billNumberID AND b.BillType=426)
	DELETE FROM dbo.coupon_AllotBill WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_AllotBill.billNumberID AND b.BillType=425)
	
	
	--处理已消费和报损的优惠券信息
	DELETE FROM dbo.Coupon_CodeInfo WHERE [State] = 3 AND CouponCode NOT IN (SELECT CouponCode FROM dbo.Coupon_BillUsed)
	DELETE FROM dbo.Coupon_CodeInfo WHERE [STATE] = 6 AND CouponCode NOT IN (SELECT CouponCode FROM dbo.Coupon_CodeInOut)
								
	DROP TABLE #CouponBillIndexd
END

-------------------------------------------------------------------------------------------处理优惠券 END  ----------------------------------------------------------------------------------------
--自定义删除(优惠券的相关单据没自定义)
;WITH CustomExists
	AS
	(	
		SELECT BillType,BillNumberID FROM dbo.BillIndex
		UNION ALL
		SELECT BillType,BillNumberID FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillType,BillNumberID FROM dbo.OrderIndex
		UNION ALL 
		SELECT BillType,BillNumberID FROM dbo.LendIndex
		UNION ALL
		SELECT 204 AS BillType,BillNumberID FROM dbo.RequestIndex
		UNION ALL 
		SELECT 311 AS BillType,BillNumberId FROM dbo.CommissionBillNew
		UNION ALL 
		SELECT BillType,BillNumberID FROM dbo.FaPiaoBillIndex
		UNION ALL
		SELECT BillType,BillNumberId FROM dbo.FactIndex
	
	)
SELECT BillType,BillNumberID INTO #CustomExists FROM CustomExists
--9.7自定义
DELETE A FROM dbo.Custom_BillIndex A WHERE NOT EXISTS(SELECT 1 FROM #CustomExists WHERE BillType=A.BillType AND BillNumberID=A.BillId)
DELETE A FROM dbo.Custom_BillDetails A WHERE NOT EXISTS(SELECT 1 FROM #CustomExists WHERE BillType=A.BillType AND BillNumberID=A.BillId)
DROP TABLE #CustomExists
--<9.7自定义
DELETE FROM  BillIndex_CarRepair WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.Billindex_CarRepair.BillNumberId)
DELETE FROM  CustomBillColumns WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.CustomBillColumns.BillNumberId)
DELETE FROM  CustomBillDetailColumns WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.CustomBillDetailColumns.BillNumberId AND BillType=dbo.CustomBillDetailColumns.billtype)
											 AND NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.CustomBillDetailColumns.billnumberid AND dbo.CustomBillDetailColumns.billtype=9999)
DROP TABLE #TempBillNumberID
UPDATE wx_Bill_JieJian SET ifYearBillDisplay = 0 WHERE ifYearBillDisplay = 1
	-- ********	清除单据明细 - END	********

DELETE FROM ListTable	WHERE BillDate < @yearendDatetime		-- 科目变化明细表,放后面是因为前面要用到LISTTABLE
	
--把结转的期初收付款单改为年结存单据
UPDATE dbo.BillIndex SET IsIni=1,ifYearBill=1 WHERE BillType IN (4,66) AND draft=0 AND BillDate < @yearendDatetime

--后续单据处理
--------删除主表后续处理 逻辑不变 找不到billnumberID 就删掉 [shan 2019/01/28]start ------------------------------	
DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype not  IN (423,424,425,426,301,300,313) 			--多账户
DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM dbo.Coupon_BillIndex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype IN (423,424,425,426)		--多账户
DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM dbo.orderindex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype IN (301,300,313)		--多账户
DELETE FROM BillMulBrand WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=BillMulBrand.BillNumberId)			--多账户
--------删除主表后续处理 逻辑不变 找不到billnumberID 就删掉 [shan 2019/01/28]  end ------------------------------	

--------删除主表后 重算结算金额 结算方式 [shan 2019/01/28]start ------------------------------	
EXEC Gp_YearProc_DateTime_HandleBalance @yearendmode,@yearendDatetime
--------删除主表后 重算结算金额 结算方式 [shan 2019/01/28]  end ------------------------------	

IF @delOrder = '1'   
BEGIN
	DELETE FROM OrderIndex	WHERE BillDate < @yearendDatetime		-- 清除订单索引表
	DELETE FROM OrderBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.OrderIndex)			-- 销售、采购订单
	DELETE FROM PT_Combin_OrderBill	 WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.OrderIndex)			--清除所有组合品订单信息
	DELETE FROM PT_Combin_OrderBillDetail WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.OrderIndex)			--清除所有组合品订单明细信息
	--DELETE FROM PT_SaleOrderLockDetail	  		--清除订单锁库信息
	--UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
	--UPDATE dbo.Ini_GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
	--TRUNCATE TABLE Ini_GoodsStocks_Order    --清除期初订单库存
END


IF @clearnocompleteonshelves = 1
BEGIN
	UPDATE dbo.RetailBackBill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 215 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.salebackbill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 45 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.salegoodsexchangebill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1)AND BillType = 160 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.commissionbill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType IN(142,144) AND BillDate < @yearendDatetime)
					
	UPDATE dbo.PT_Combin_SaleBackBillDetail SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 46 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.buybill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 34 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.buygoodsexchangebill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 161 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.givemebill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 126 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.movebill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 17 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.movebjbill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 21 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.stypemovebill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 188 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.otherinoutbill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 201 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.disassemblebill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 16 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.AppraisalBill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 400 AND BillDate < @yearendDatetime)
					
	UPDATE dbo.SendBackBill SET InflowQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 403 AND BillDate < @yearendDatetime) 
					
	         
	UPDATE dbo.BillIndex SET ShelveRefState = 0, ShelveState = 0 
			  WHERE (ShelveState = 1 OR ShelveRefState = 1) AND BillDate < @yearendDatetime          
END
                    
IF @clearnocompletepickandtransport = 1
BEGIN                   
	UPDATE dbo.salebill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 11 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.salegoodsexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 160 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.givebill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 139 AND BillDate < @yearendDatetime) 
					                                
	UPDATE dbo.commissionbill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType IN(140,146) AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.PT_Combin_SaleBillDetail SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 12 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.buybackbill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 6 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.buygoodsexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 161 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.movebill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 17 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.movebjbill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 21 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.stypemovebill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 187 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.otherinoutbill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 202 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.disassemblebill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 16 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.integralexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 183 AND BillDate < @yearendDatetime) 
					
	UPDATE dbo.AppraisalBackBill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 401 AND BillDate < @yearendDatetime)
					 
	UPDATE dbo.SendBill SET PickedQty = 0 WHERE BillNumberId IN(
					SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 402 AND BillDate < @yearendDatetime)
					
	                
	UPDATE dbo.BillIndex SET citestate = 0, progressstate = 0 
			  WHERE (citestate = 1 OR progressstate = 1) AND BillDate < @yearendDatetime                
END

IF @delOrder <> '1' AND @delEndOrder = '1'	-- 清除已完成订单
BEGIN
	--更新期初订单库存
	--DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=0 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
	--DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=0 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
	
	--删除已完成的销售订单 去除关联关系
	UPDATE OrderBill SET SaleOrderId =-1
	WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState = '1' AND BillOver = 0 and billtype =300 AND BillDate < @yearendDatetime)  )
	
	DELETE FROM OrderIndex WHERE OrderState = '1' AND BillOver = 0 AND BillDate < @yearendDatetime
	DELETE FROM OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=OrderBill.billNumberID)
	DELETE FROM dbo.PT_Combin_OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBill.billNumberID)
	DELETE FROM dbo.PT_Combin_OrderBillDetail WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBillDetail.billNumberID)
END

--清除中止订单
IF @delOrder<> '1' AND @delstoporder= '1'
BEGIN
	--更新期初订单库存
	--DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
	--DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
	
	--删除已中止的销售订单 去除关联关系
	UPDATE OrderBill SET SaleOrderId =-1
	WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState='1' AND BillOver=1 and billtype =300)  )
	
	DELETE FROM dbo.OrderIndex WHERE OrderState='1' AND BillOver=1
	DELETE FROM OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=OrderBill.billNumberID)
	DELETE FROM dbo.PT_Combin_OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBill.billNumberID)
	DELETE FROM dbo.PT_Combin_OrderBillDetail WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBillDetail.billNumberID)
END

-- 删除OrderBill 中关联报价单、询价单、请购单billnumberid无效的记录
UPDATE dbo.OrderBill SET AskBillID=0,AskBillNumberID=0 WHERE AskBillID <> 0 AND billNumberID IN(SELECT billNumberID FROM dbo.OrderIndex WHERE BillDate < @yearendDatetime)
UPDATE dbo.OrderBill SET RequestBillID=0,RequestBillNumberID=0 
WHERE RequestBillID<>0 
	AND NOT EXISTS(SELECT 1 FROM Requestbill WHERE ID =OrderBill.RequestBillID) 
	AND billNumberID IN(SELECT billNumberID FROM dbo.OrderIndex WHERE BillDate < @yearendDatetime)
-- 删除销售、采购明细表中，无效关联 OrderBill 中的 OrderID 记录
UPDATE SaleBill SET OrderID = -1 WHERE OrderID <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=SaleBill.OrderID) AND billNumberID IN(SELECT billNumberID FROM dbo.BillIndex WHERE BillDate < @yearendDatetime)
UPDATE BuyBill SET OrderID = -1 WHERE OrderID <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=BuyBill.OrderID) AND billNumberID IN(SELECT billNumberID FROM dbo.BillIndex WHERE BillDate < @yearendDatetime)

--打断销售 采购有订金产生的 预收\付款  收付款单关联关系
UPDATE prebill set RelevanceBillId=-1 
WHERE RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=prebill.RelevanceBillId)
	AND billNumberID IN(SELECT billNumberID FROM dbo.BillIndex WHERE BillDate < @yearendDatetime)
	
UPDATE gatheringbill set RelevanceBillId=-1 
WHERE  RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=gatheringbill.RelevanceBillId)
	AND billNumberID IN(SELECT billNumberID FROM dbo.BillIndex WHERE BillDate < @yearendDatetime)
	
UPDATE paybill set RelevanceBillId=-1 
WHERE  RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=paybill.RelevanceBillId)
	AND billNumberID IN(SELECT billNumberID FROM dbo.BillIndex WHERE BillDate < @yearendDatetime)

-- 如果有保留的单据，则给其赋一个年结前单据的标志
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE Draft = 0 AND BillDate < @yearendDatetime)
BEGIN
	UPDATE BillIndex SET ifYearBill = 1 WHERE Draft = 0 AND BillDate < @yearendDatetime
	DELETE FROM visit WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE Draft = 0 AND BillNumberId=visit.JbBillNumberID AND BillDate < @yearendDatetime)
	DELETE FROM visitfj WHERE NOT EXISTS (SELECT 1 FROM visit WHERE billnumberid=visitfj.billnumberid)
END
IF EXISTS(SELECT TOP 1 1 FROM dbo.LendIndex WHERE Draft = 0 AND BillDate < @yearendDatetime)
BEGIN
	UPDATE LendIndex SET ifYearBill = 1 WHERE Draft = 0 AND BillDate < @yearendDatetime
END
	

-- 清空VIP卡储值明细表

DELETE FROM GiveFromSaleOrBuy WHERE SourceBillNumberId NOT IN(SELECT BillNumberId FROM dbo.BillIndex)	-- 清掉销售、采购关联赠送、获赠数据表
DELETE FROM VipCardConsume WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)		--清掉VIP卡消费记录表  谢吉康  2004-7-21	
DELETE FROM ModifyLog_BillIndex WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_SaleBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_BuyBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_SaleBackBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_BuyBackBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_PayBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_GatheringBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_CompleteTotal WHERE GoodsBillID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_CompleteGoodTotal WHERE GoodsBillID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_PreBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_SendBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_SendBackBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_AppraisalBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_AppraisalBackBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)

DELETE FROM ModifyLog_ReceiptBillIndex WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.ReceiptBillIndex)
DELETE FROM ModifyLog_ReceiptBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.ReceiptBillIndex)

DELETE FROM ModifyLog_PT_Combin_SaleBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_PT_Combin_SaleBillDetail WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_PT_Combin_SaleBackBill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM ModifyLog_PT_Combin_SaleBackBillDetail WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)

DELETE FROM CostRe_Bill WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
DELETE FROM CostReLog WHERE BillNumberID NOT IN(SELECT BillNumberID FROM dbo.BillIndex)
	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DateTime_YearProcSerialDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_YearProc_DateTime_YearProcSerialDeal
GO

-- =============================================
-- Author:		GLJ	
-- Create date: 2019-03-01
-- Description: 按时间年结存处理序列号
-- =============================================

CREATE PROCEDURE Gp_YearProc_DateTime_YearProcSerialDeal
(
	@yearEndDateTime DATETIME
)
AS
SET NOCOUNT ON 

DECLARE	@nCostingMethod	INT
EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output

--===========================实物库存序列号==================
-- 删除实物库存序列号数据表
SELECT * INTO #iniFactSerial FROM gp_iniFactPtypeSerial

--清除期初
TRUNCATE TABLE gp_iniFactPtypeSerial

--确保仓库分支机构正确
UPDATE dbo.gp_FactPtypeSerial SET STypeId=S.STypeID FROM dbo.gp_FactPtypeSerial C,Stock S WHERE C.KtypeID = S.typeId

INSERT INTO dbo.gp_iniFactPtypeSerial(Serial,KtypeID, PtypeID, InKtypeTime,OutKtypeTime,State,Flag,CommissionState,ETypeID,IniFlag,GoodsOrder,GoodsNumber, STypeId, Comment1,ItemID,IsCombined ,CargoID,ProduceDate,ValidDate,LendState)
SELECT Serial,KtypeID, PtypeID, InKtypeTime,OutKtypeTime,State,Flag,CommissionState,ETypeID,IniFlag,GoodsOrder,GoodsNumber, STypeId, Comment1,ItemID,IsCombined ,CargoID,ProduceDate,ValidDate,LendState
FROM  #iniFactSerial 
WHERE 
	Serial NOT IN(SELECT A.Serial FROM Fact_InoutPtypeSerial A 
						INNER JOIN FactIndex B ON B.BillNumberId=A.BillNumberid AND B.BillDate<@yearEndDateTime AND RedWord=0 AND B.ifcheck='T'
		)
UNION ALL
SELECT 
	Serial,
	KtypeID,
	PtypeID,
	InKtypeTime,
	NULL OutKtypeTime,
	1 State,
	1 Flag,
	'' CommissionState,
	etypeid,
	1 IniFlag,
	GoodsOrder,
	GoodsNumber,
	Stypeid,
	'' Comment1,
	ItemID,
	IsCombined,
	CargoID,
	ProduceDate,
	ValidDate,
	LendState
FROM (
	SELECT
		P.Serial,
		P.InKtypeID KtypeID,
		P.PtypeID,
		I.BillDate InKtypeTime,
		I.etypeid,
		P.GoodsOrder,
		P.GoodsNumber,
		I.Stypeid,
		P.ItemID,
		P.IsCombined,
		P.CargoID,
		P.ProduceDate,
		P.ValidDate,
		P.LendState,
		P.BillType,
		ROW_NUMBER() OVER(PARTITION BY P.Serial ORDER BY P.PostTime DESC) RowId
	FROM Fact_InoutPtypeSerial P
	INNER JOIN FactIndex I ON I.BillDate<@yearEndDateTime AND I.RedWord=0 AND I.ifcheck='T' AND P.BillNumberid=I.BillNumberId	
	WHERE ((P.BillType=420 AND State=1) OR P.BillType<>420)
)  T WHERE T.RowId=1 AND T.BillType IN(418,420)

-- 期初序列号库存状况表
EXEC gp_ChangeIniFlag;

DROP TABLE #iniFactSerial
--===========================账面库存序列号==================

SELECT * INTO #PTypeSerial FROM gp_initPTypeSerial

TRUNCATE TABLE gp_initPTypeSerial
--重算当前序列号库中的STypeId
UPDATE	gp_CruPtypeSerial SET STypeId = S.STypeID FROM gp_CruPtypeSerial C,Stock S WHERE	C.KtypeID = S.typeId AND C.KtypeID <> '10000'

--代销已出库的也要转过去,8,9,10,11,16,22,32
INSERT INTO gp_initPTypeSerial
(
	Serial,KtypeID,PtypeID,BTypeID1,BtypeID2,InKtypeTime,OutKTypeTime,[User],
	State,Note,Flag,CommissionState,ETypeID,LTypeID,iniFlag,CostPrice,
	GoodsOrder,GoodsNumber,STypeId,Comment1,Comment2,Comment3,ItemID,IsCombined,CargoID,ProduceDate,ValidDate
) 
SELECT Serial,KtypeID,PtypeID,BTypeID1,BtypeID2,InKtypeTime,OutKTypeTime,[User],
	State,Note,Flag,CommissionState,ETypeID,LTypeID,iniFlag,CostPrice,
	GoodsOrder,GoodsNumber,STypeId,Comment1,Comment2,Comment3,ItemID,IsCombined,CargoID,ProduceDate,ValidDate
FROM  #PTypeSerial 
WHERE 
	Serial NOT IN(SELECT A.Serial FROM gp_inoutPtypeSerial A 
						INNER JOIN BillIndex B ON B.BillNumberId=A.BillNumberid AND B.BillDate<@yearEndDateTime AND RedWord=0 AND B.ifcheck='T'
		)
UNION ALL
SELECT
		A.Serial,B.KtypeID,A.PtypeID,CASE WHEN B.State IN (13,32) THEN  DBO.F_GetCommissionBTypeID(A.Serial,B.State,140) ELSE  B.BTypeID1 END BTypeID1,CASE WHEN B.State IN (7,9,10,11,16,22,32,14) THEN DBO.F_GetCommissionBTypeID(B.Serial,B.State,144) ELSE B.BtypeID2 END BtypeID2,B.InKtypeTime,B.OutKTypeTime,A.[User],
	B.State,A.Note,A.Flag,A.CommissionState,B.ETypeID,A.LTypeID,A.iniFlag,B.CostPrice,
	B.GoodsOrder,A.GoodsNumber,B.STypeId,Comment1,Comment2,Comment3,B.ItemID,B.IsCombined,B.CargoID,B.ProduceDate,B.ValidDate
FROM gp_CruPtypeSerial A
INNER JOIN(
	SELECT * FROM (
		SELECT
			P.Serial,
			CASE WHEN P.BillType IN(17,21,16,188,160,161) THEN P.InKtypeID ELSE B.ktypeid END KtypeID,
			P.PtypeID,
			P.BTypeID1,
			P.BTypeID2,
			P.InKtypeTime,
			P.OutKtypeTime,
			P.State,
			P.ItemID,
			P.IsCombined,
			P.CargoID,
			P.ProduceDate,
			P.ValidDate,
			P.GoodsNumber,
			P.BillNumberId,
			P.BillType,
			P.CostPrice,
			P.GoodsOrder,
			B.ETypeID,
			B.STypeId,
			ROW_NUMBER() OVER(PARTITION BY P.Serial ORDER BY P.PostTime DESC) RowId
		FROM gp_inoutPtypeSerial P
		INNER JOIN  BillIndex B ON B.BillDate<@yearEndDateTime AND B.RedWord=0 AND B.ifcheck='T' AND P.BillNumberid=B.BillNumberId
		INNER JOIN dbo.gp_CruPtypeSerial c ON p.Serial=c.Serial AND c.State<>35
		WHERE ((P.BillType IN(17,21,16,160,161) AND p.State=1) OR P.BillType NOT IN (17,21,16,160,161))
		
		)  T WHERE T.RowId=1
) B ON  A.Serial=B.Serial  AND B.PtypeID=A.PtypeID AND B.State IN(1, 7, 13, 25,9,10,11,16,22,32,14)	


--修改代销的仓库属性 	
UPDATE  gp_initPTypeSerial SET 	KtypeID = '10000',InKtypeTime = NULL,CargoID=0 WHERE State IN (9,10,11,13,16,32)

--修改代销的仓库属性  state=受托委托已结算	
UPDATE  gp_initPTypeSerial SET KtypeID = '10000',CargoID=0 WHERE 	State IN (14)

--处理期初序列号标识	谢吉康  2005-7-21
UPDATE	Gp_initPTypeSerial SET iniFlag = 1			

--处理期初序列号和明细关联id
UPDATE t
SET    t.id = t1.id
FROM   gp_initPtypeSerial t
INNER JOIN dbo.Ini_GOODSSTOCKS_QTY t1 ON t.PtypeID = t1.PTypeID 
																		AND t.CargoID = t1.CargoID
																		AND t.GoodsNumber = t1.GoodsNumber
																		AND t.IsCombined = t1.Iscombined
																		AND t.ItemID = t1.ItemID
																		AND t.KtypeID = t1.KTypeID
																		AND t.ProduceDate = t1.ProduceDate
																		AND t.ValidDate = t1.ValidDate
																		AND
																		( 
																			@nCostingMethod<>3 OR (@nCostingMethod=3 AND t.CostPrice=t1.GoodsCostPrice)
																		)
WHERE  t.State = 1

DROP TABLE #PTypeSerial
--===========================借欠序列号==================
--处理借欠的序列号转期初 
SELECT * INTO #LendTemp FROM GP_InitLendPTypeSerial
TRUNCATE TABLE GP_InitLendPTypeSerial

INSERT INTO dbo.gp_initLendPtypeSerial(Serial ,KtypeID ,PtypeID ,BTypeID1 ,BtypeID2 ,InKtypeTime ,OutKTypeTime ,[User] ,State ,Note ,Flag ,CommissionState ,ETypeID ,LTypeID ,BFlag ,ItemID ,IsCombined ,CargoID ,ProduceDate ,ValidDate ,GoodsNumber)
SELECT Serial,KtypeID,PtypeID,BTypeID1,BTypeID2,InKtypeTime,OutKtypeTime,[User],State,Note,Flag,CommissionState,ETypeID,LTypeID,BFlag,ItemID,IsCombined,CargoID,ProduceDate,ValidDate,GoodsNumber
FROM #LendTemp 
WHERE Serial NOT IN(SELECT Serial FROM gp_inoutPtypeSerial P
		INNER JOIN 
		(
			SELECT BillNumberId,BillType,BillDate FROM LendIndex WHERE BillDate<@yearEndDateTime AND RedWord=0 AND ifcheck='T'
			UNION ALL
			SELECT BillNumberId,BillType,BillDate FROM BillIndex WHERE BillDate<@yearEndDateTime AND IsLend=1 AND RedWord=0 AND ifcheck='T'
		) F ON F.BillNumberId=P.BillNumberid AND F.BillType=P.BillType )
UNION ALL
SELECT
	B.Serial,
	B.KtyeID,
	B.PtypeID,
	B.BTypeID1,
	B.BTypeID2,
	B.InKtypeTime,
	B.OutKtypeTime,A.[User],
	B.State,
	A.Note,
	B.Flag,
	A.CommissionState,
	B.etypeid,
	A.LTypeID,
	B.BFlag,
	B.ItemID,
	B.IsCombined,
	B.CargoID,
	B.ProduceDate,
	B.ValidDate,
	B.GoodsNumber
FROM GP_LendPTypeSerial A
INNER JOIN(
	SELECT * FROM (
		SELECT
			F.ETypeId,
			P.Serial,
			F.ktypeid KtyeID,
			P.PtypeID,
			P.BTypeID1,
			P.BTypeID2,
			P.InKtypeTime,
			P.OutKtypeTime,
			P.State,
			CASE WHEN P.State=17 THEN 1 ELSE 0 END Flag,
			CASE WHEN P.State=17 THEN 1 ELSE 0 END BFlag,
			P.ItemID,
			P.IsCombined,
			P.CargoID,
			P.ProduceDate,
			P.ValidDate,
			P.GoodsNumber,
			P.BillNumberId,
			P.BillType,
			ROW_NUMBER() OVER(PARTITION BY P.Serial ORDER BY P.PostTime DESC) RowId
		FROM gp_inoutPtypeSerial P
		INNER JOIN 
		(
			SELECT BillNumberId,BillType,BillDate,ktypeid,etypeid FROM LendIndex WHERE BillDate<@yearEndDateTime AND RedWord=0 AND ifcheck='T'
			UNION ALL
			SELECT BillNumberId,BillType,BillDate,ktypeid,etypeid FROM BillIndex WHERE BillDate<@yearEndDateTime AND IsLend=1 AND RedWord=0 AND ifcheck='T'
		) F ON F.BillNumberId=P.BillNumberid AND F.BillType=P.BillType
		) T WHERE T.RowId=1 AND T.BillType NOT IN(34,11)
) B ON  A.Serial=B.Serial 
WHERE 
	Not EXISTS(SELECT * FROM #LendTemp WHERE Serial=B.Serial AND ((State=17 AND B.State=19) OR (State=18 AND B.State=20)))
	AND NOT EXISTS(
		SELECT * FROM(
			SELECT
				P.Serial,
				P.State,
				ROW_NUMBER() OVER(PARTITION BY P.Serial ORDER BY P.PostTime ASC) RowId
			FROM gp_inoutPtypeSerial P
			INNER JOIN LendIndex PL ON PL.BillDate<@yearEndDateTime AND PL.RedWord=0 AND PL.ifcheck='T' AND PL.BillType IN(87,71)
		) T WHERE T.RowId=1 AND T.Serial=B.Serial AND ((T.State=17 AND B.State=19) OR (T.State=18 AND B.State=20))
	)

UPDATE GP_InitLendPTypeSerial SET State = 17 WHERE Flag = 1
UPDATE GP_InitLendPTypeSerial SET State = 18 WHERE Flag = 0

--保持序列号预与期初数量的统一 谢吉康 2004-08-16
DELETE	FROM lend 
FROM GP_initLendPTypeSerial lend
WHERE
	Flag = 1
	AND NOT EXISTS (
		SELECT 	1 FROM iniGoodsLend 
		WHERE 	
			lend.BTypeID2 = BTypeID 
			AND lend.PTypeID = PTypeID 
			AND lend.KTypeID = KTypeID 
			AND BorrowQty>0 
			AND lend.Flag = 1
			AND Serial=lend.Serial
	)	
		

DELETE	FROM lend 
FROM GP_initLendPTypeSerial lend
WHERE 	
	Flag = 0	
	AND NOT EXISTS (
		SELECT 	1 FROM 	iniGoodsLend 
		WHERE 	
			lend.BTypeID1 = BTypeID 
			AND lend.PTypeID = PTypeID 						
			AND lend.KTypeID = KTypeID 
			AND LendQty>0 
			AND lend.Flag = 0
			AND Serial=lend.Serial
		)
		 
UPDATE GP_InitLendPTypeSerial SET BTypeID1 = NULL WHERE State = 17 AND Flag = 1

UPDATE GP_InitLendPTypeSerial SET BTypeID2 = NULL WHERE State = 18 AND Flag = 0

DROP TABLE #LendTemp
-----------------------------受托序列号------------------------------------------------
	-- 处理受托期初数量与受托库中序列号数目不一致的情况 - Start
DECLARE @chvEdition varchar(10)
SELECT	@chvEdition = SubValue
FROM	SysData
WHERE	SubName = 'Edition'

IF @chvEdition IN ('2','5','7')
	BEGIN
			DECLARE @chvMngSerial varchar(10)--系统采用序列号严密管理模式
			SELECT	@chvMngSerial = [Value] FROM UserConfig WHERE	ConfigName = 'mngSerial'

			IF @chvMngSerial = '1' AND EXISTS(SELECT TOP 1 a.Qty FROM iniCommissionStock a,PType b WHERE a.Type = 144 AND a.Qty <> 0 AND a.PTypeID = b.TypeID AND b.IfSerial = '1' AND b.SonNum = 0 AND b.Deleted = 0)
				BEGIN	
					SELECT	
						COUNT(Serial) AS numSerialQty,
						PTypeID,
						BTypeID2 AS BTypeID,
						STypeId,
						State,
						CASE State WHEN 7 THEN  KtypeID ELSE '' END AS KTypeID,
						CASE @nCostingMethod WHEN 3 THEN CostPrice ELSE 0 END AS CostPrice,
						GoodsNumber,
						ProduceDate,
						ValidDate,
						ItemID,
						IsCombined,
						CASE State WHEN 7 THEN  CargoID ELSE 0 END AS CargoID
					INTO	#GP_initPTypeSerial
					FROM	GP_initPTypeSerial
					WHERE	--[Flag] = 1 AND 
						State IN (13,32,7,9,10,11,16,14)
					GROUP BY	
						PTypeID,
						BTypeID2,
						STypeId,
						State,
						CASE State WHEN 7 THEN  KtypeID ELSE '' END,
						CASE @nCostingMethod WHEN 3 THEN CostPrice ELSE 0 END,
						GoodsNumber,
						ProduceDate,
						ValidDate,
						ItemID,
						IsCombined,
						CASE State WHEN 7 THEN  CargoID ELSE 0 END
					HAVING COUNT(Serial)<>0

					DELETE FROM iniCommissionStock  
					WHERE	
						Type = 144 
						AND Qty <> 0
						AND EXISTS
							(
								SELECT	p.TypeID
								FROM	ptype p
								WHERE	p.TypeID=iniCommissionStock.Ptypeid 
								AND p.IfSerial='1'
								AND p.SonNum = 0
								AND p.Deleted = 0
							)
						AND NOT EXISTS	
							(
								SELECT	b.PTypeID
								FROM	#GP_initPTypeSerial b
								WHERE	
									b.PTypeID=iniCommissionStock.Ptypeid 
									AND b.BTypeID=iniCommissionStock.Btypeid 
									AND b.STypeId=iniCommissionStock.Stypeid
									AND b.State=iniCommissionStock.SerialType
							)
					
					DELETE FROM iniCommissionStock_qty  
					WHERE	
						Type = 144 
						AND Qty <> 0
						AND EXISTS
						(
							SELECT	p.TypeID
							FROM	ptype p
							WHERE	
								p.TypeID=iniCommissionStock_qty.Ptypeid 
								AND p.IfSerial='1'
								AND p.SonNum = 0
								AND p.Deleted = 0
						)
						AND NOT EXISTS	
						(
							SELECT	b.PTypeID
							FROM	#GP_initPTypeSerial b
							WHERE	
								b.PTypeID=iniCommissionStock_qty.Ptypeid 
								AND b.BTypeID=iniCommissionStock_qty.Btypeid 
								AND b.STypeId=iniCommissionStock_qty.Stypeid
								AND b.State=iniCommissionStock_qty.SerialType
						)
		
				DECLARE @intPriceDot	INT
			
				EXEC	@intPriceDot=Gp_GetDigit 2
		
				UPDATE	iniCommissionStock_Qty
				SET Qty = b.numSerialQty
				FROM 
					iniCommissionStock_Qty a,
					#GP_initPTypeSerial b,
					ptype p
				WHERE	
					a.Type = 144
					AND a.Qty <>b.numSerialQty
					AND a.Ptypeid=p.typeId
					AND p.IfSerial='1'
					AND p.SonNum = 0
					AND p.Deleted = 0
					AND a.PTypeID = b.PTypeID
					AND a.BTypeID = b.BTypeID
					AND a.Stypeid = b.Stypeid
					AND b.State=a.SerialType
					AND a.KTypeID=b.KtypeID		
					AND a.GoodsCostPrice=b.CostPrice
					AND a.GoodsNumber=b.GoodsNumber
					AND a.ProduceDate=b.ProduceDate
					AND a.ValidDate=b.ValidDate
					AND a.CargoID=b.CargoID
					AND a.ItemID=b.ItemID
					AND a.Iscombined=b.IsCombined
				
				SELECT	
					COUNT(Serial) AS numSerialQty,
					PTypeID,
					BTypeID2 AS BTypeID,
					STypeId,
					State
				INTO	#GP_initPTypeSerialAll
				FROM	GP_initPTypeSerial
				WHERE	--[Flag] = 1 AND 
					State IN (13,32,7,9,10,11,16,14)
				GROUP BY	
					PTypeID,
					BTypeID2,
					STypeId,
					State
				HAVING COUNT(Serial)<>0	
		
				UPDATE	iniCommissionStock
				SET Qty = b.numSerialQty,
				Total=CASE a.Qty WHEN 0 THEN 0 ELSE  b.numSerialQty*(ROUND(a.Total/a.Qty,@intPriceDot)) END
				FROM 
					iniCommissionStock a,
					#GP_initPTypeSerialAll b,
					ptype p
				WHERE	
					a.Type = 144
					AND a.Qty <>b.numSerialQty
					AND a.Ptypeid=p.typeId
					AND p.IfSerial='1'
					AND p.SonNum = 0
					AND p.Deleted = 0
					AND a.PTypeID = b.PTypeID
					AND a.BTypeID = b.BTypeID
					AND a.Stypeid = b.Stypeid
					AND b.State=a.SerialType
			END
	END
	-- 处理受托期初数量与受托库中序列号数目不一致的情况 - End

IF object_id(N'tempdb..#GP_initPTypeSerial',N'U') is not null
BEGIN
--删除临时表
DROP Table #GP_initPTypeSerial
END 
IF object_id(N'tempdb..#GP_initPTypeSerialAll',N'U') is not null
BEGIN
--删除临时表
DROP Table #GP_initPTypeSerialAll
END 


--==================================--统一删除序列号【BEGIN】=========================================
--实物库存
DELETE FROM gp_FactPtypeSerial WHERE OutKtypeTime<@yearEndDateTime AND State=2

--借欠库存
DELETE FROM A
FROM GP_LendPTypeSerial A
INNER JOIN(
		SELECT
			P.Serial,
			p.State,
			P.BillType,
			ROW_NUMBER() OVER(PARTITION BY P.Serial ORDER BY P.PostTime DESC) RowId
		FROM gp_inoutPtypeSerial P
		INNER JOIN BillIndex B ON B.BillDate<@yearEndDateTime AND B.IsLend=1 AND B.RedWord=0 AND B.ifcheck='T' AND B.BillNumberId=P.BillNumberid AND B.BillType=P.BillType
	) F ON F.Serial=A.Serial AND RowId=1 AND (CASE WHEN A.State=33 THEN 2 WHEN A.State=34 THEN 1 ELSE A.State END)=F.State AND F.BillType IN(34,11) AND A.State IN(33,34)
	

DELETE FROM gp_inoutPtypeSerial 
WHERE
	PostTime<@yearEndDateTime



--账面库存
DELETE FROM gp_CruPtypeSerial 
WHERE
	OutKtypeTime<@yearEndDateTime
	 AND State IN(2,3,4,5,15,26,27,28,29,30,31,33,41,42,35)

--==================================--统一删除序列号【  END 】=========================================


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProc_DeleteBill_Trigger]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YearProc_DeleteBill_Trigger]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：谢吉康
--日期：2018-12-13
--描述：年结存处理删除单据的触发器
-------------------------------------------------------------------------
CREATE   PROCEDURE Gp_YearProc_DeleteBill_Trigger
AS
SET NOCOUNT ON 

DECLARE @TRG VARCHAR(MAX)	
IF NOT EXISTS (SELECT NAME FROM sysobjects WHERE   type='tr' AND NAME ='DeleteBill')
BEGIN			
	SET @TRG ='		
			CREATE TRIGGER [DeleteBill] ON dbo.BillIndex 
			FOR  DELETE 
			AS
			--------------------------------------------------------处理单据删除影响草稿库存 start------------------------------------------------------------------------------------------
			CREATE TABLE #BillInfo
			(
				BillType 		INT,	--单据类型
				BillnumberID	INT	
			)
			
			DECLARE @BillNumberID	INT,
					@BillType		INT
			
			INSERT INTO #BillInfo SELECT BillType,BillnumberID FROM deleted WHERE draft=1 AND isini=0
			WHILE(EXISTS(SELECT 1 FROM #BillInfo))
			BEGIN
				SELECT TOP 1 @BillType=BillType,@BillnumberID=BillnumberID FROM #BillInfo
				EXEC GP_AuditingORDel_DraftQTY @BillnumberID,@BillType
				IF @BillType IN (11,12,34,140,144,400,402)
				BEGIN
					--处理明细waitqty
					DECLARE @qty NUMERIC(24, 10) ,@orderid int 
					IF @billtype=12
					BEGIN
						UPDATE PT_Combin_OrderBillDetail 
						SET 
							WaitQty = ISNULL(PT_Combin_OrderBillDetail.WaitQty,0) - b.Qty
						FROM 
						(
							SELECT BillNumberId,OrderID,SUM(Qty) Qty
							FROM dbo.PT_Combin_SaleBillDetail
							WHERE BillNumberId=@billnumberid
							GROUP BY BillNumberId,OrderID
						) b
						WHERE PT_Combin_OrderBillDetail.OrderID=b.OrderID						  
						
						UPDATE PT_Combin_OrderBill 
						SET 
							WaitQty = ISNULL(PT_Combin_OrderBill.WaitQty,0) - b.Qty
						FROM 
						(
							SELECT BillNumberId,OrderID,SUM(Qty) Qty
							FROM dbo.PT_Combin_SaleBill
							WHERE BillNumberId=@billnumberid
							GROUP BY BillNumberId,OrderID
						) b
						WHERE PT_Combin_OrderBill.OrderID=b.OrderID	
				END
				ELSE
				BEGIN
					IF @billtype=11
						DECLARE cr_insertbill CURSOR FOR
						SELECT orderid,qty FROM salebill WHERE billnumberid=@billnumberid
					ELSE IF @billtype=12
						DECLARE cr_insertbill CURSOR FOR
						SELECT orderid,qty FROM PT_Combin_SaleBillDetail where billnumberid=@billnumberid
					ELSE IF @billtype=140
						DECLARE cr_insertbill CURSOR FOR
						SELECT orderid,qty FROM commissionbill WHERE billnumberid=@billnumberid
					ELSE IF @BillType=400
						DECLARE cr_insertbill CURSOR FOR
						SELECT orderid,qty FROM AppraisalBill WHERE billnumberid=@billnumberid
					ELSE IF @BillType=402
						DECLARE cr_insertbill CURSOR FOR
						SELECT orderid,qty FROM SENDBill WHERE billnumberid=@billnumberid
					ELSE IF @billtype=34
					DECLARE cr_insertbill CURSOR FOR
					SELECT orderid,qty FROM buybill WHERE billnumberid=@billnumberid
					ELSE IF @billtype=144
						DECLARE cr_insertbill CURSOR FOR
						SELECT orderid,qty FROM commissionbill WHERE billnumberid=@billnumberid
					 OPEN cr_Insertbill

					 FETCH NEXT FROM cr_insertbill INTO @orderid,@qty
					 WHILE @@FETCH_status<>-1
					 BEGIN
					  
					  UPDATE orderbill 
					  SET 
						WaitQty = ISNULL(WaitQty,0) - @qty
					  WHERE orderid=@orderid
					  
					  IF @@error<>0 
					  BEGIN
						  CLOSE cr_insertbill
						  DEALLOCATE cr_insertbill 
						  ROLLBACK TRAN
						  RETURN  
					  END
					  FETCH NEXT FROM cr_insertbill INTO @orderid,@qty
					 END

					 CLOSE cr_insertbill
					 DEALLOCATE cr_insertbill 
					END
				-- 处理订单库存,--先减去引用未过账数量
				EXEC GP_Deal_OrderReferQty @BillnumberID,@BillType,''-'',1
				END
				
				DELETE #BillInfo WHERE BillnumberID=@BillnumberID
			END
			--------------------------------------------------------处理单据删除影响草稿库存 start------------------------------------------------------------------------------------------

			BEGIN tran DelBill
			DELETE FROM salebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=11)
			DELETE FROM salebackbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=45)
			DELETE FROM gatheringbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=4)
			 
			DELETE FROM buybill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=34)
			DELETE FROM buybackbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=6)
			DELETE FROM paybill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=66)
			DELETE FROM losebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=9)
			DELETE FROM overflowbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=14)
			DELETE FROM disassemblebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=16)
			DELETE FROM movemoneybill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=77)
			DELETE FROM adDebtbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype IN(115,116,128,129))
			DELETE FROM adpricebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=57)
			DELETE FROM movebill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=17)
			DELETE FROM movebjbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=21)
			DELETE FROM Commissionbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype IN(201,202))
			DELETE FROM moneybill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype IN(35,36,84,85,78,5,10,93,158))-- 加入费用单和一般收入单
			DELETE FROM Retailbill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=305)
			--固定资产
			DELETE FROM AssetIncDecBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE billtype=212)
			DELETE FROM AssetIncDecBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE billtype=213)
			DELETE FROM DepBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE billtype=214)
			DELETE FROM FixedAssetsDetails WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE billtype=307)
			-- 加入商品换货单
			DELETE FROM GoodsExchangeBill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=155)
			--加入获利、返利
			DELETE FROM Advantage WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype IN (148,150))
			--加入价保执行、获得价保
			DELETE FROM PriceProtectBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype IN (149,151))
			-- 加入会计凭证
			DELETE FROM AccountCredence WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=159)
			-- 加入销售换货单
			DELETE FROM SaleGoodsExchangeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=160)
			-- 加入采购换货单
			DELETE FROM BuyGoodsExchangeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=161)
			-- 新维修 - 接件单
			DELETE FROM wx_Bill_JieJian WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=165)
			-- 新维修 - 维修单
			DELETE FROM wx_Bill_Self WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=166)
			-- 新维修 - 维修取件单
			DELETE FROM wx_Bill_GetBack WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=167)
			-- 新维修 - 整机更换单
			DELETE FROM wx_Bill_Replace WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=168)
			-- 新维修 - 送修单
			DELETE FROM wx_Bill_Send WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=169)
			-- 新维修 - 送修返回单
			DELETE FROM wx_Bill_SendBack WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=170)
			-- 新维修 - 报修单
			DELETE FROM wx_Bill_Call WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=171)
			-- 新维修 - 上门维修单
			DELETE FROM wx_Bill_Goto WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=172)
			-- 新维修 - 维修品调入单
			DELETE FROM wx_Bill_In WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=173)
			-- 新维修 - 维修品调出单
			DELETE FROM wx_Bill_Out WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=174)
			-- 新维修 - 维修品调拨单
			DELETE FROM wx_Bill_Move WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=175)
			-- 赠送单
			DELETE FROM GiveBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=139)
			-- 获赠单
			DELETE FROM GiveMeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=126)
			--维修估价单
			DELETE FROM QP_EvaluationBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=177)
			DELETE FROM QP_EvaluationBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=177)
			--快修单
			DELETE FROM QP_QuickRepairBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=178)
			DELETE FROM QP_QuickRepairBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=178)
			--洗车结算单
			DELETE FROM QP_WashCarBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=179)	
			--旧件回收单
			DELETE FROM QP_RecycleBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=180)
			--积分兑换单
			DELETE FROM IntegralExchangeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=183)	
			--报价单
			DELETE FROM QuotePriceBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=184)		
			--询价单
			DELETE FROM AskPriceBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=185)		
			--保险理赔单
			DELETE FROM QP_InsuranceBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=186)
			DELETE FROM QP_InsuranceBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=186)		
			--分支机构调拨出库单，分支机构调拨入库单
			DELETE FROM STypeMoveBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype IN (187,188))	
			--预收款单，预付款单
			DELETE FROM PreBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype IN (189,190))	
			--领料出库单
			DELETE FROM Qp_PickingBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=191)	
			--返修单
			DELETE FROM Qp_BackingOut_Bill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=192)	
			--接待登记
			DELETE FROM Qp_ReceptionBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)
			DELETE FROM Qp_ReceptionBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)	
			DELETE FROM Qp_ReceptionBill_Pic WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)	
			DELETE FROM Qp_ReceptionBill_Accessory WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)	
			DELETE FROM Qp_ReceptionBill_Insurance WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)	
			DELETE FROM Qp_AttemperBill_RepairItemsPerson WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=195)
			--救援单
			DELETE FROM Qp_SuccorBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单,是BillIndex_CarRepair的衍生表
			DELETE FROM Qp_SuccorBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单_维修项目明细表
			DELETE FROM Qp_SuccorBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单_配件明细表
			DELETE FROM Qp_SuccorBill_SuccorItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单_救援项目明细表
			DELETE FROM Qp_SuccorBill_ErrDescription WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=196)--救援单_故障描述	
			--领料退回单
			DELETE FROM Qp_PickingBackBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=197)
			--维修回访单
			DELETE FROM Qp_IntendingTalkBack_Bill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=198)
			--三包索赔单
			DELETE FROM Qp_ThreePacketsBill_RepairItems WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=200)--三包索赔单_维修项目明细表
			DELETE FROM Qp_ThreePacketsBill_PType WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=200)--三包索赔单_维修配件明细表
		    --序列号调整单
			DELETE FROM SerialAdjustBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype=203)
			--其他出、入库单
			DELETE FROM OtherInOutBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype in(201,202))
			--采购、销售费用分摊
			DELETE FROM ShareSourceBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype in(205,206))--费用分摊出入库单明细
			DELETE FROM ShareFeeBill WHERE BillNumberId IN (SELECT billnumberid FROM deleted WHERE billtype in(205,206))--费用分摊费用明细		
		
			DELETE FROM AppraisalBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE BillType=400)--暂估入库
			DELETE FROM AppraisalBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE BillType=401)-- 暂估退货
			DELETE FROM SendBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE BillType=402)--发出商品
			DELETE FROM SendBackBill WHERE BillNumberId IN (SELECT BillNumberId FROM deleted WHERE BillType=403)--发出商品退货
			--单据自定义
			DELETE FROM CustomBillColumns FROM deleted WHERE CustomBillColumns.billnumberid = deleted.BillNumberId AND 	CustomBillColumns.billtype = deleted.BillType
			DELETE FROM CustomBillDetailColumns FROM deleted WHERE CustomBillDetailColumns.billnumberid = deleted.BillNumberId AND 	CustomBillDetailColumns.billtype = deleted.BillType	
			DELETE FROM RetailCombinationBill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=305)
			DELETE FROM dbo.Transportbill WHERE billNumberID IN(SELECT billNumberID FROM deleted WHERE billtype=414)
			DELETE FROM dbo.Transportcontrastbill WHERE billNumberID IN(SELECT billNumberID FROM Deleted WHERE billtype=414)
			DELETE FROM dbo.PT_Combin_SaleBackBill FROM deleted WHERE PT_Combin_SaleBackBill.billnumberid = deleted.BillNumberId AND 	billtype=46
			DELETE FROM dbo.PT_Combin_SaleBackBillDetail FROM deleted WHERE PT_Combin_SaleBackBillDetail.billnumberid = deleted.BillNumberId AND 	billtype=46	
			DELETE FROM dbo.PT_Combin_SaleBill WHERE billnumberid IN (SELECT billnumberid FROM deleted WHERE billtype=12)
			DELETE FROM dbo.PT_Combin_SaleBillDetail WHERE billNumberID IN(SELECT billNumberID FROM deleted WHERE billtype=12)
			
			DELETE FROM Custom_BillIndex  FROM deleted b WHERE BillId=b.BillNumberId AND b.BillType=Custom_BillIndex.BillType
			DELETE FROM Custom_BillDetails  FROM deleted b WHERE BillId=b.BillNumberId AND b.BillType=Custom_BillDetails.BillType
					 
			
			/*
				作者：谢吉康
				日期：2004-2-6
				描述：如果有审核，则删除单据审核里面的数据
			*/
			DECLARE @AuditCount INT
			SELECT @AuditCount=COUNT(AuditingBill.BillNumberID) FROM AuditingBill INNER JOIN deleted ON AuditingBill.BillNumberID=deleted.billnumberid WHERE AuditingBill.BillIndexType=2
			
			IF ISNULL(@AuditCount,0) <> 0
			BEGIN
				DELETE FROM AuditingBillDetail WHERE BillNumberID IN(SELECT billnumberid FROM deleted) AND BillIndexType=2
				DELETE FROM AuditingBill WHERE BillNumberID IN(SELECT billnumberid FROM deleted) AND BillIndexType=2
			END

			-- 加入代销单据
			DELETE FROM CommissionBill WHERE BillNumberID IN (SELECT billnumberid FROM deleted WHERE billtype in(140,141,142,143,144,145,147))
			
			 DELETE FROM inoutstocktable WHERE BillType NOT IN (404,405) AND billnumberid IN (SELECT billnumberid FROM deleted)
			 DELETE FROM Listtable WHERE BillType NOT IN (404,405) AND billnumberid IN(SELECT billnumberid FROM deleted) AND billtype IN (SELECT Deleted.BillType FROM deleted)
			
			 DELETE FROM dbo.BillMulAccount WHERE EXISTS (SELECT billnumberid FROM deleted WHERE Deleted.billtype=dbo.BillMulAccount.BillType AND Deleted.BillNumberId=dbo.BillMulAccount.BillNumberId)
			 DELETE FROM dbo.BillMulBrand WHERE EXISTS (SELECT billnumberid FROM deleted WHERE Deleted.billtype=dbo.BillMulBrand.BillType AND Deleted.BillNumberId=dbo.BillMulBrand.BillNumberId)
			 DELETE FROM dbo.Coupon_BillUsed WHERE EXISTS (SELECT billnumberid FROM deleted WHERE Deleted.billtype=dbo.Coupon_BillUsed.BillType AND Deleted.BillNumberId=dbo.Coupon_BillUsed.BillNumberId)

			COMMIT tran DelBill '
			
	EXEC (@TRG)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[GP_YearProcCheckAccountCredenceBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[GP_YearProcCheckAccountCredenceBill]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	by:glj
	date:2019-01-18
	function:985新增判断 存在【预收/预付/应收/应付】原币和本位币换算后不相等的期末调汇业务凭证单据！
*/
CREATE PROC GP_YearProcCheckAccountCredenceBill
AS
	IF EXISTS(	SELECT TOP 1 1
					FROM AccountCredence a 
					INNER JOIN billindex b ON a.BillNumberID=b.BillNumberId
					WHERE	
							draft=0 
							AND RedWord=0
							AND ((J_Total=0 AND NJ_Total<>0) OR (J_Total<>0 AND NJ_Total=0) OR (D_Total=0 AND ND_Total<>0) OR (D_Total<>0 AND ND_Total=0)
							AND IsAuto=1)
					)
			RETURN -1
	RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




GO
/*
修改：	2017.08.24	LF	
当勾选了【清除未完成上架的单据】时，年结存时就不进行“未完成上架”的检测；
当勾选了【清除未完成拣货/运输的单据】时，年结存就不进行“未完成拣货和未完成运输配送”的检测。
*/
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'GP_YearProcCheckWLBill',N'P'))
BEGIN
	DROP PROC GP_YearProcCheckWLBill
END
GO
CREATE PROC GP_YearProcCheckWLBill(
	@ClearNoNompleteOnshelves			INT=0,		--清除未完成上架单
	@ClearNoCompletePickAndTransport	INT=0		--清除未完成拣货/运输配送单
)
AS
BEGIN
	DECLARE @UseOnShelves INT,		--启用上架
			@UsePickgoods INT,		--启用拣货
			@UseTransport INT		--启用运输
	
	SELECT @UseOnShelves=SubValue FROM dbo.sysdata WHERE SubName='UseOnShelves'
	SELECT @UsePickgoods=SubValue FROM dbo.sysdata WHERE SubName='UsePickgoods'
	SELECT @UseTransport=SubValue FROM dbo.sysdata WHERE SubName='UseTransport'
	
	IF @UseOnShelves=1 AND @ClearNoNompleteOnshelves=0
	BEGIN
		--期初单据不做上架,排除期初单据AND IsIni<>1
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BIlLType IN(215,45,160,142,34,161,126,144,17,21,188,201,16,400,403) AND ifcheck='t' AND RedWord=0 AND ShelveState<>2 AND IsIni<>1)
		BEGIN
			RETURN -1
		END
	END
	
	IF @UsePickgoods=1 AND @ClearNoCompletePickAndTransport=0
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BilLType IN(11,12,160,139,140,6,161,146,17,21,187,202,16,183,401,402) AND ifcheck='t' AND RedWord=0 AND progressstate<>2 AND IsIni<>1)
		BEGIN
			RETURN -2
		END
	END
	IF @UseTransport=1 AND @ClearNoCompletePickAndTransport=0
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BillIndex WHERE BillType IN(11,12,160,139,140,6,161,146,17,21,187,202,16,183,401,402) 
					AND ifcheck='t' AND RedWord=0 AND TransPortState<>2 AND IsNeedTransport=1 AND IsIni<>1)
		BEGIN
			RETURN -3
		END
	END
	RETURN 0
END
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProcDeleteBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_YearProcDeleteBill
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-17
-- Description: 年结存清除单据
-- 冯波 2015-06-02
/*				根据条件清除单据的主表和明细*/				
-- =============================================

CREATE PROCEDURE Gp_YearProcDeleteBill
(
	@yearendmode							CHAR(1) = '1',		-- 1 - 按余额转期初；0 - 按单据转期初
	@delDraft								CHAR(1) = '1',		--清除草稿数据
	@unfinishedinvoice 						CHAR(1) = '1',		-- 1 - 保留未完成开票单据；0 - 不保留
	@chkcompleterequestbill					CHAR(1) = '1',		-- 1 - 清除已完成请购单；0 - 清除所有请购单
	@unfinishedposbill						CHAR(1) = '1',		-- 0 - 清除已结转小票数据；1 - 清除所有小票数据
	@PhysicalComplete						CHAR(1) = '0',		-- 1 -结转未实物出入库完成的单据   0 不结转
	@carryOverBillexcess					CHAR(1)	= '0',		-- 1 - 业务单据超收超付及收付款单未结算完金额结转至期初应收应付减少单；0 - 不转
	@delOrder								CHAR(1) = '1',		-- 1 - 删除定单数据；0 - 不删除
	@clearCompleteAllotApply				CHAR(1),			--	 -是否清除已完成的调货申请单 0-不清除 1-清除
	@clearNoCompleteAllotApply				CHAR(1),			--	 -是否清除未完成的调货申请单 0-不清除 1-清除
	@clearCompleteGetBillApply              char(1),               --是否清除已完成的要货申请单 0-不清除 1-清除
	@clearNoCompleteGetBillApply            char(1),               --是否清除未完成要货申请单 0-不清除 1-清除
	@clearnocompleteonshelves				CHAR(1) = '0',		--	 -是否清除未完成上架的单据 0-不清除 1-清除
    @clearnocompletepickandtransport		CHAR(1) = '0',		--   -是否清除未完成拣货/运输的单据 0-不清除 1-清除
    @delstoporder							CHAR(1) = '0',		-- 1 - 清除中止订单;0清除中止订单
    @delEndOrder							CHAR(1) = '0'		-- 1 - 删除已完成订单；0 - 不删除
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

DECLARE @columns VARCHAR(max)=''	--存储表的字段

--系统重建所有锁库数据进行解锁
TRUNCATE TABLE PT_SaleOrderLockDetail		 		--清除订单锁库信息
UPDATE Ini_GOODSSTOCKS_QTY SET LockNumber=0 --清楚期初锁库信息
UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
UPDATE OrderBill SET LockNumber=0 --清除订单锁库信息
UPDATE PT_Combin_OrderBillDetail SET LockNumber=0 --清除组合品订单锁库信息
---------------始终需要删除，与条件无关的部分start-------
DELETE FROM BillIndex WHERE BillType=206	
TRUNCATE TABLE ShareSourceBill	--费用分摊出入库单明细
TRUNCATE TABLE ShareFeeBill		--费用分摊费用明细	
--TRUNCATE TABLE nVipGoodsSign
TRUNCATE TABLE dbo.Fact_InOutstocktable
TRUNCATE TABLE InOutStockTable		-- 出入库明细表
TRUNCATE TABLE VipCardConsume		--清掉VIP卡消费记录表  谢吉康  2004-7-21	

TRUNCATE TABLE wx_InOutStockTable	-- 维修出入库明细表
DELETE  FROM commonpossaleindex WHERE Draft<>0		--收银小票
DELETE  FROM commonpossalelist WHERE NOT EXISTS (SELECT  1 FROM CommonPosSaleIndex WHERE CommonPosSaleIndex.PosVchCode=commonpossalelist.PosVchCode)
DELETE  FROM CommonPosPtypeCheckNdx WHERE PDVchCode<>0						--POS盘点单据
DELETE  FROM CommonPosPtypeCheckList WHERE NOT EXISTS (SELECT  1 FROM CommonPosPtypeCheckNdx WHERE CommonPosPtypeCheckNdx.CheckCode=CommonPosPtypeCheckList.CheckCode)	


--分支机构调拨出库的优惠券
DELETE FROM dbo.Coupon_CodeInfo WHERE [STATE] =7

--清除固定资产盘点单已处理的
DELETE FROM FixedAssetsIndex WHERE [state]=3
 
TRUNCATE TABLE StockCheck			-- 清除库存盘点表
TRUNCATE TABLE StockCheckIndex		-- 清除库存盘点单据索引表
TRUNCATE TABLE CompleteTotal		-- 清除按单结算表
-- 清除按商品结算明细表
TRUNCATE TABLE CompleteGoodTotal
TRUNCATE TABLE PriceProtectList		-- 清除价保记录 
DELETE FROM GiveFromSaleOrBuy	-- 清掉销售、采购关联赠送、获赠数据表
TRUNCATE TABLE nVipAdjust			-- 清除消费金额调整单、积分调整单

--清空按品牌结算明细表
TRUNCATE TABLE dbo.CompleteBrandarTotal


-- 清空VIP卡储值明细表
TRUNCATE TABLE nVipAddMoney
--删除单据修改记录
TRUNCATE TABLE dbo.FrozeBusiness
TRUNCATE TABLE ModifyLog_BillIndex
TRUNCATE TABLE ModifyLog_SaleBill
TRUNCATE TABLE ModifyLog_BuyBill
TRUNCATE TABLE ModifyLog_SaleBackBill
TRUNCATE TABLE ModifyLog_BuyBackBill
TRUNCATE TABLE ModifyLog_PayBill
TRUNCATE TABLE ModifyLog_GatheringBill
TRUNCATE TABLE ModifyLog_CompleteTotal
TRUNCATE TABLE ModifyLog_CompleteGoodTotal
TRUNCATE TABLE ModifyLog_PreBill
TRUNCATE TABLE ModifyLog_ReceiptBillIndex
TRUNCATE TABLE ModifyLog_ReceiptBill
TRUNCATE TABLE ModifyLog_SendBill
TRUNCATE TABLE ModifyLog_SendBackBill
TRUNCATE TABLE ModifyLog_AppraisalBill
TRUNCATE TABLE ModifyLog_AppraisalBackBill
TRUNCATE TABLE ModifyLog_PT_Combin_SaleBill
TRUNCATE TABLE ModifyLog_PT_Combin_SaleBillDetail
TRUNCATE TABLE ModifyLog_PT_Combin_SaleBackBill
TRUNCATE TABLE ModifyLog_PT_Combin_SaleBackBillDetail
TRUNCATE TABLE CostRe_Bill
TRUNCATE TABLE CostReLog

-- 删除借欠相关数据表
--TRUNCATE TABLE LendIndex
--TRUNCATE TABLE LendBill
-- 清除财务历史状况表
TRUNCATE TABLE MonthATypeHistory

---------------始终需要删除，与条件无关的部分 end ------

---------------根据条件删除单据 start ------
DECLARE @ifKeepWXBill int --是否保留维修
SET @ifKeepWXBill = 0

CREATE TABLE #TempBillNumberID(BillNumberID int,[ID] int,BillType int)		--保存要保留的单据billnumberid
CREATE TABLE #TempCouponBillNumberID(BillNumberID int,[ID] int,BillType int)		--保存要保留的优惠券单据billnumberid
-----------------------------------------------------------------------跨年结算处理 start-----------------------------------------------------------------------
-- 保留预收预付的余额转入的期初单据
INSERT INTO #TempBillNumberID
(
	BillNumberID,
	BillType
)
SELECT	BillNumberID,
		BillType
FROM	dbo.BillIndex
WHERE IsIni=1 AND BillType IN (189,190)

--------------------------------------------------调货申请和门店配送单的相关处理开始--------------------------------------------------
INSERT INTO #TempBillNumberID(BillNumberID,BillType)
SELECT	BillNumberID,
		BillType
FROM	dbo.PosAllotApplyBillIndex
WHERE	Isdone=0 
		and ifcheck='t' 
		and draft=0 
		AND RedWord = 0 
		AND BillType IN (327)  
		
IF @delDraft ='0' ---不删除草稿		
BEGIN
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberID,
			BillType
	FROM	dbo.PosAllotApplyBillIndex
	WHERE	ifcheck='f' 
			and draft=1 
			AND RedWord = 0 
			AND BillType IN (327)  	
END

--把保留的过账的未完成验收的“门店配送单”单据改为期初单据
UPDATE	PosAllotApplyBillIndex 
SET		IsIni=1,
		ifYearBill=1
WHERE	BillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID) 
		AND BillType IN (327) AND draft=0  
		
DELETE FROM PosAllotApplyBillIndex WHERE BillNumberId NOT IN (SELECT BillNumberId FROM #TempBillNumberID WHERE BillType IN (327)) AND BillType = 327  AND Isdone = 1


IF @delDraft ='1' ---草稿
BEGIN
	DELETE FROM PosAllotApplyBillIndex WHERE IfCheck = 'f' AND draft = 1
	DELETE FROM PosAllotApplyBillIndex WHERE BillNumberid NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)
	DELETE FROM dbo.DeliveryBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)
	DELETE FROM dbo.DeliveryBackBill WHERE BillNumberid NOT IN (SELECT BillNumberId FROM PosAllotApplyBillIndex)	
END

DELETE dbo.PosAllotApplyBillIndex WHERE IfCheck='t' AND draft=0 AND BillType IN (328,329)
DELETE FROM PosAllotApplyBillIndex   WHERE IfCheck='t' AND draft=0 AND BillType=327 AND RedWord<>0 --红冲了的门店配送单都要删掉
DELETE DeliveryBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.PosAllotApplyBillIndex)
DELETE DeliveryBackBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.PosAllotApplyBillIndex)
DELETE DeliveryCheckBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.PosAllotApplyBillIndex)

IF @clearCompleteAllotApply = 1 --清除已完成的调货申请单
BEGIN
	DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=22)
	DELETE PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=22;
END

IF @clearNoCompleteAllotApply = 1 --清除未完成的调货申请单
BEGIN
	DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=22)
	DELETE PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=22;
END

IF @clearcompletegetbillapply = 1 --清除已完成的要货申请单
BEGIN

    DELETE PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=326;
    DELETE DeliveryApplyBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 1 and BillType=326)
END
IF @clearnocompletegetbillapply = 1 --清除未完成的要货申请单
BEGIN
    DELETE PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=326;
     DELETE DeliveryApplyBill WHERE BillNumberId NOT IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE Isdone = 0 and BillType=326)
END
	
--bug2853,调货申请单，状态是作废的，年结存的时候直接清除掉，不管选项。祝伟已确认
DELETE PosAllotApplyBill WHERE BillNumberId IN(SELECT BillNumberId FROM PosAllotApplyBillIndex WHERE BillState = 4 AND BillType = 22);
DELETE PosAllotApplyBillIndex WHERE BillState = 4 AND BillType = 22;
--------------------------------------------------调货申请和门店配送单的相关处理结束--------------------------------------------------

-- 保留超收超付，未结算完成的收付款单生成的期初收付款单
IF @yearendmode=0 AND @carryOverBillexcess=1
BEGIN
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberID,BillType
	FROM dbo.BillIndex
	WHERE IsIni=1 AND draft=0 AND ifYearBill=1 AND BillType IN (4,66)	
END

-- 保留所有未完成的单据(按单据年结的时候保留)
-- 保留未结算完成的销售单、销售退货单、销售换货单、委托代销结算单、采购单、采购退货单、采购换货单、受托代销结算单、费用单、固定资产购买 、固定资产变卖、其他收入单、返利执行、
	--价保执行单、获得价保、获利核算执行单、会员储值充值单、维修取件单、整机更换单、上门维修单、送修返回单、固定资产增加、固定资产减少
IF @yearendmode='0'
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	billnumberid,
			billtype 
	FROM	BillIndex 
	WHERE	RedWord=0 
			AND jsState <> 2 
			AND draft=0
			AND (
				BillType in(12,46,6,11,34,45,141,145,148,160,161,36,84,85,93,148,149,150,151,181,427,167,168,170,172,115,116,128,129,212,213,312) 
				OR (BillType=450 AND ChargeOffType IN (2,3,4,5))
				)
			AND (
				(nTotalMoney-ISNULL(NChargeOffTotal,0)-nCompleteTotal<>0 AND nTotalInMoney=0 AND nPreferenceMoney=0)
				OR (
					(
						(nTotalMoney-ISNULL(NChargeOffTotal,0)-(nCompleteTotal+nTotalInMoney+nPreferenceMoney)<0 AND nTotalMoney<0)
						OR
						(nTotalMoney-ISNULL(NChargeOffTotal,0)-(nCompleteTotal+nTotalInMoney+nPreferenceMoney)>0 AND nTotalMoney>=0)
					)
					AND (nTotalInMoney<>0 OR nPreferenceMoney<>0)
				)
				OR (BillType IN (160,161) AND jsStyle='2' AND jsState='1')
				) 
				
	--保留优惠券未结算完成的单据
	--INSERT INTO #TempCouponBillNumberID(BillNumberID,BillType)
	--SELECT	billnumberid,
	--		billtype 
	--FROM	dbo.Coupon_BillIndex 
	--WHERE	RedWord=0 
	--		AND jsState <> 2 
	--		AND draft=0
	--		AND (	BILLTYPE IN (423,424,426)
	--				(nTotalMoney-ISNULL(NChargeOffTotal,0)-nCompleteTotal<>0 AND nTotalInMoney=0 )
	--				OR (
	--					(
	--						(nTotalMoney-ISNULL(NChargeOffTotal,0)-(nCompleteTotal+nTotalInMoney)<0 AND nTotalMoney<0)
	--						OR
	--						(nTotalMoney-ISNULL(NChargeOffTotal,0)-(nCompleteTotal+nTotalInMoney)>0 AND nTotalMoney>=0)
	--					)
	--					AND nTotalInMoney<>0 
	--				)
	--			) 
							
ELSE--保留应收应付的余额转入的期初单据
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberID,BillType
	FROM dbo.BillIndex
	WHERE IsIni=1 AND ifYearBill=1 AND BillType IN (115,116,128,129) AND jsState<>'2'
	
--保留结算数量＋退货数量小于单据数量的委托代销发货单和受托代销收货单
INSERT INTO #TempBillNumberID(BillNumberID,BillType)
SELECT BillNumberId,type AS BillType 
FROM	CommissionBill c  
LEFT JOIN(  
			SELECT	SUM(isnull(A.qty,0)) AS qty,A.oldid 
			FROM	CommissionBill A,BillIndex B
			WHERE	[TYPe] in(145,146) 
					AND A.BillNumberId=B.BillNumberId  AND B.RedWord=0 AND B.draft=0 
			GROUP BY A.OldID
) a ON c.ID=a.OldID  
WHERE	c.Type=144  
		AND isnull(a.qty,0)<c.Qty 
		AND C.BillNumberId IN(SELECT BillNumberId FROM BillIndex WHERE draft=0 AND RedWord=0)
UNION ALL
SELECT BillNumberId,type AS BillType FROM CommissionBill c
LEFT JOIN (  
			SELECT	SUM(isnull(A.qty,0)) AS qty,A.oldid 
			FROM	CommissionBill  A,BillIndex B
			WHERE	[TYPe] in(141,142) AND A.BillNumberId=B.BillNumberId  AND B.RedWord=0 AND B.draft=0  
			GROUP BY A.OldID
) a ON c.ID=a.OldID  
WHERE	c.Type=140  
		AND isnull(a.qty,0)<c.Qty 
		AND C.BillNumberId IN(SELECT BillNumberId FROM BillIndex WHERE draft=0 AND RedWord=0)		
				
-- 非“已取件”、“已换机”的接件单，要保留下来，包括其相关单据
-- “待上门维修”的报修单，要保留下来
IF EXISTS(SELECT TOP 1 1 FROM BillIndex a,wx_Bill_JieJian b WHERE a.BillType=165 AND a.Draft=0 AND a.ifCheck='t' AND a.RedWord=0 
	AND a.BillNumberID=b.BillNumberID AND b.State NOT IN (1,5))
	OR EXISTS(SELECT TOP 1 1 FROM BillIndex a,wx_Bill_Call b WHERE a.BillType=171 AND a.Draft=0 AND a.ifCheck='t' AND a.RedWord=0 
	AND a.BillNumberID=b.BillNumberID AND b.State=0)
	OR EXISTS(SELECT TOP 1 1 FROM BillIndex a,wx_Bill_Send b WHERE a.BillType=169 AND a.Draft=0 AND a.ifCheck='t' AND a.RedWord=0 
	AND a.BillNumberID=b.BillNumberID AND b.JieJianBillNumberID=-1 AND b.Qty-b.SendBackQty>0)
BEGIN
	SET @ifKeepWXBill = 1
	-- 1)预存手工录入的送修单，且明细中存在未返回数量大于0的记录
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,169 AS BillType 
		FROM wx_Bill_Send a,BillIndex b
		WHERE a.JieJianBillNumberID=-1 AND a.Qty-a.SendBackQty>0 AND a.BillNumberID=b.BillNumberID
			AND b.BillType=169 AND b.Draft = 0 AND b.ifCheck = 't' AND b.RedWord = 0 
		GROUP BY a.BillNumberID,b.[ID]
	-- 预存相关联的送修返回单
	IF @yearendmode='0'
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,170 AS BillType 
		FROM wx_Bill_SendBack a,BillIndex b
		WHERE a.SendBillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID WHERE BillType=169) 
			AND a.BillNumberID = b.BillNumberID
			AND b.BillType=170 AND b.Draft = 0 AND b.ifCheck = 't' AND b.RedWord = 0
		GROUP BY a.BillNumberID

	-- 2)非“已取件”、“已换机”的接件单，预存起来
	INSERT INTO #TempBillNumberID(BillNumberID,[ID],BillType) 
		SELECT a.BillNumberID,b.[ID],165 AS BillType
		FROM BillIndex a,wx_Bill_JieJian b
		WHERE a.BillType=165 AND a.Draft=0 AND a.ifCheck='t' AND a.RedWord=0 
			AND a.BillNumberID=b.BillNumberID AND b.State NOT IN (1,5)
		GROUP BY a.BillNumberID,b.[ID]
	-- 预存相关联的维修单
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT BillNumberID,166 AS BillType 
		FROM BillIndex
		WHERE JieJianBillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID WHERE BillType = 165)
				AND JieJianID IN (SELECT [ID] FROM #TempBillNumberID WHERE BillType = 165)
				AND BillType=166 AND Draft = 0 AND ifCheck = 't' AND RedWord = 0 
		GROUP BY BillNumberID
	-- 预存相关联的送修单
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,169 AS BillType 
		FROM wx_Bill_Send a,BillIndex b
		WHERE a.JieJianBillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID WHERE BillType = 165)
			AND a.JieJianID IN (SELECT [ID] FROM #TempBillNumberID WHERE BillType = 165)
			AND a.BillNumberID = b.BillNumberID AND b.BillType=169 AND b.Draft = 0 AND b.ifCheck = 't' AND b.RedWord = 0 
		GROUP BY a.BillNumberID
	-- 预存相关联的送修返回单
	IF @yearendmode='0'
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,170 AS BillType 
		FROM wx_Bill_SendBack a,BillIndex b
		WHERE a.SendBillNumberID IN (
			SELECT BillNumberID FROM wx_Bill_Send
			WHERE JieJianBillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID WHERE BillType = 165)
				AND JieJianID IN (SELECT [ID] FROM #TempBillNumberID WHERE BillType = 165)) AND a.BillNumberID = b.BillNumberID 
				AND b.BillType=170 AND b.Draft = 0 AND b.ifCheck = 't' AND b.RedWord = 0 
		GROUP BY a.BillNumberID

	-- 3)预存非“待上门维修”的报修单
	INSERT INTO #TempBillNumberID(BillNumberID,BillType) 
		SELECT a.BillNumberID,171 AS BillType 
		FROM wx_Bill_Call a,BillIndex b
		WHERE a.State = 0 AND a.BillNumberID = b.BillNumberID AND b.BillType = 171 AND b.Draft = 0 AND b.ifCheck = 't' 
			AND b.RedWord = 0 
		GROUP BY a.BillNumberID			
END

CREATE TABLE #TempReceiptBillNumberID(BillNumberID INT)

IF @yearendmode='0'  --按单据结转
BEGIN
	--未开票完成的单据一律保留
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberId,BillType 
	FROM	BillIndex 
	WHERE BillType IN (400,401,402,403) AND IfInvoice<>2
	AND ((Ifcheck='t' AND RedWord=0) OR (IsIni=1))
	
	--未结算完成的发票一律保留;所关联的物流单据未开票完成的也保留
	INSERT #TempReceiptBillNumberID
	SELECT BillNumberID
	FROM ReceiptBillIndex
	WHERE  --(nTotalMoney-nCompleteTotal<>0) AND
	JSState<>2 AND
	((Ifcheck='t' AND RedWord=0) OR (IsIni=1))
	UNION ALL
	SELECT a.BillNumberID
	FROM ReceiptBill a
	INNER JOIN ReceiptBillIndex b
	ON a.BillNumberID=b.BillNumberID
	WHERE ( (b.Ifcheck='t' AND b.RedWord=0) OR (b.IsIni=1) )
	AND a.MainBillNumberID IN
	(
		SELECT BillNumberID
		FROM #TempBillNumberID
	)
	
	--未结算完成的往来核销单关联的物流单据一律保留
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT FromBillNumberid,FromBillType FROM dbo.ChargeOffBill
	WHERE FromBillType NOT IN (404,405) AND BillNumberId IN(SELECT BillNumberID FROM #TempBillNumberID WHERE Billtype=450) 
	
	--未结算完成的往来核销单关联的物流单据一律保留
	INSERT INTO #TempReceiptBillNumberID
	SELECT FromBillNumberid from dbo.ChargeOffBill
	WHERE FromBillType IN (404,405) AND BillNumberId IN(SELECT BillNumberID FROM #TempBillNumberID WHERE Billtype=450) 
	
	--把保留的物流单据改为期初单据
	UPDATE BillIndex
	SET IsIni=1,ifYearBill=1
	WHERE BillNumberID IN
	(	
		SELECT BillNumberID
		FROM #TempBillNumberID
	) AND BillType IN (400,401,402,403,450)
	
	--把保留的优惠券单据改为期初单据
	UPDATE dbo.Coupon_BillIndex
	SET IsIni=1,IfYearBill=1
	WHERE billnumberid IN 
	(
		SELECT BillNumberID
		FROM #TempCouponBillNumberID
	)AND BILLTYPE IN(423,424,426)
	
	
	--把保留的发票改为期初发票
	UPDATE ReceiptBillIndex
	SET IsIni=1,ifYearBill=1
	WHERE BillNumberID IN
	(	
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
	)

	DELETE ReceiptBill
	WHERE BillNumberID IN
	(
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE ifYearBill=0 AND ifcheck='f'
	)
	
	
	DELETE ReceiptBillIndex
	WHERE BillNumberID IN
	(
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE ifYearBill=0 AND ifcheck='f'
	)

END
ELSE
BEGIN
	--把未结算完的往来余额转成期初应收/应付单
	--EXEC Gp_RecieptToInibill
	
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	billnumberid,billtype 
	FROM	BillIndex 
	WHERE Isini=1 AND ifYearBill=0 AND BillType IN (115,116,128,129) AND jsState<>2
	
	--未开票完成的单据一律保留
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	BillNumberId,BillType 
	FROM	BillIndex 
	WHERE  BillType IN (400,401,402,403) AND IfInvoice<>2
	AND ((Ifcheck='t' AND RedWord=0) OR (IsIni=1))
	
	--把保留的物流单据改为期初单据
	UPDATE BillIndex
	SET IsIni=1,ifYearBill=1
	WHERE BillNumberID IN
	(	
		SELECT BillNumberID
		FROM #TempBillNumberID
	) AND BillType IN (400,401,402,403,450)
	

	/*
	--未结算完成的发票一律保留;所关联的物流单据未开票完成的也保留
	INSERT #TempReceiptBillNumberID
	SELECT BillNumberID
	FROM ReceiptBillIndex
	WHERE  Ifcheck='t' AND RedWord=0 AND JSState<>2
	UNION ALL
	SELECT a.BillNumberID
	FROM ReceiptBill a
	INNER JOIN ReceiptBillIndex b
	ON a.BillNumberID=b.BillNumberID
	WHERE b.Ifcheck='t' AND b.RedWord=0 AND a.MainBillNumberID IN
	(
		SELECT BillNumberID
		FROM #TempBillNumberID
	)
	
	--把保留的发票改为期初发票
	UPDATE ReceiptBillIndex
	SET IsIni=1,ifYearBill=1
	WHERE BillNumberID IN
	(	
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
	)
	*/
	
	TRUNCATE TABLE ReceiptBill
	TRUNCATE TABLE ReceiptBillIndex
END

---------------仓储运输单据 结转-------------

--清除已过账的上架单、拣货单、运输配送单

IF @delDraft ='1'
BEGIN
	TRUNCATE TABLE onShelvespickIndex
	TRUNCATE TABLE dbo.onShelvesbill
	TRUNCATE TABLE dbo.PickBill
END
ELSE
BEGIN
	DELETE  dbo.onShelvespickIndex WHERE IfCheck='t' AND RedWord=0 AND draft=0
	DELETE onShelvesbill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.onShelvespickIndex)
	DELETE PickBill WHERE billNumberID NOT IN (SELECT billNumberID FROM dbo.onShelvespickIndex)
END


---------------991门店配送结转start--------------


---------------991门店配送结转end---------------

--DECLARE		@UseOnshelves	INT,
--			@UsePickgoods	INT,
--			@UseTransport	INT
--SELECT @UseOnshelves=SubValue FROM dbo.sysdata WHERE SubName='useonshelves'
--SELECT @UsePickgoods=SubValue FROM dbo.sysdata WHERE SubName='usepickgoods'
--SELECT @UseTransport=SubValue FROM dbo.sysdata WHERE SubName='usetransport'
----上架单
----上架未完成单据
--INSERT INTO #TempBillNumberID  ( BillNumberID,BillType) 
--SELECT BillNumberID ,BillType 
--FROM  dbo.BillIndex WHERE ShelveState<>2 AND ifcheck='t' AND RedWord=0
--AND BillType IN(215,45,160,142,34,161,126,144,17,21,188,201,16,400,403) AND @UseOnshelves=1

----拣货单
----未拣货运输完成
--INSERT INTO #TempBillNumberID  ( BillNumberID,BillType ) 
--SELECT BillNumberID ,BillType
--FROM  dbo.BillIndex WHERE citestate <>2 AND ifcheck='t' AND RedWord=0
--AND BillType IN(11,12,160,139,140,6,161,146,17,21,187,202,16,183,401,402) AND @UsePickgoods=1 AND @UseTransport=1

--IF @UseTransport=1
--BEGIN
--	--未完成运输的拣货单关联的出库单保留
--	INSERT INTO #TempBillNumberID ( BillNumberID,BillType ) 
--	SELECT B.GoodsBillNumberID,b.GoodsBillType
--	FROM  dbo.onShelvespickIndex A INNER JOIN dbo.pickbill B ON A.billNumberId=B.billNumberID
--	INNER JOIN dbo.BillIndex C ON B.GoodsBillNumberID=C.BillNumberId AND B.GoodsBillType=C.BillType
--	WHERE A.citestate IN(0,1) AND A.ifcheck='t' AND A.RedWord=0
--	AND A.BillType=413 AND C.IsNeedTransport=1
--	GROUP BY B.GoodsBillNumberID,b.GoodsBillType
	
--	--运输单草稿
--	INSERT INTO #TempBillNumberID ( BillNumberID,BillType ) 
--	SELECT BillNumberId,BillType FROM BillIndex WHERE BillType=414 AND Draft=1 AND Redword=0 AND @delDraft=0
--END

----保留拣货单草稿、上架单草稿和未完成拣货单
--SELECT * INTO #onShelvespickIndex FROM dbo.onShelvespickIndex 
--WHERE  (draft=1 AND billtype=412 AND @UseOnshelves=1 AND @delDraft=0)
--	OR (draft=1 AND billtype=413 AND @UsePickGoods=1 AND @delDraft=0)
--	OR (citestate<>2 AND billtype=413 AND @UsePickGoods=1 )

--SELECT b.* INTO #PickBill FROM dbo.pickbill b INNER JOIN #onShelvespickIndex a ON b.BillNumberId=a.BillNumberId AND @UsePickgoods=1 
--SELECT b.* INTO #onShelvesbill FROM dbo.onShelvesbill b INNER JOIN #onShelvespickIndex a ON b.BillNumberId=a.BillNumberId AND @UseOnshelves=1 

--TRUNCATE TABLE onShelvespickIndex
--SET IDENTITY_INSERT onShelvespickIndex ON
--SET @columns=dbo.f_getallcolumns('onShelvespickIndex')
--EXEC('INSERT INTO onShelvespickIndex ('+@columns+') SELECT '+@columns+ ' FROM #onShelvespickIndex')
--SET IDENTITY_INSERT onShelvespickIndex OFF

--TRUNCATE TABLE dbo.PickBill
--SET IDENTITY_INSERT PickBill ON
--SET @columns=dbo.f_getallcolumns('PickBill')
--EXEC('INSERT INTO PickBill ('+@columns+') SELECT '+@columns+ ' FROM #PickBill')
--SET IDENTITY_INSERT PickBill OFF

--TRUNCATE TABLE dbo.onShelvesbill
--SET IDENTITY_INSERT onShelvesbill ON
--SET @columns=dbo.f_getallcolumns('onShelvesbill')
--EXEC('INSERT INTO onShelvesbill ('+@columns+') SELECT '+@columns+ ' FROM #onShelvesbill')
--SET IDENTITY_INSERT onShelvesbill OFF
--UPDATE dbo.onShelvespickIndex SET IsIni=1,ifYearBill=1
--DROP TABLE #onShelvesbill,#PickBill,#onShelvespickIndex
---------------仓储运输单据 结转-------------

---------------实物库存结转------------------

IF @delDraft='1'
BEGIN
	TRUNCATE TABLE dbo.FactIndex
	TRUNCATE TABLE dbo.FactDepotAllot
	TRUNCATE TABLE dbo.FactDepotInOut
	TRUNCATE TABLE dbo.FactInOut
END
ELSE
BEGIN
	TRUNCATE TABLE dbo.FactInOut
	DELETE FROM dbo.FactIndex WHERE ifcheck='t'
	DELETE FROM dbo.FactDepotAllot WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
	DELETE FROM dbo.FactDepotInOut WHERE BillNumberId NOT IN(SELECT BillNumberId FROM dbo.FactIndex)
END

IF @PhysicalComplete='1'
BEGIN
	EXEC GP_YearProcPhyStock
END
---------------实物库存结转------------------

IF @unfinishedinvoice=1 --保留未开票完成的单据
BEGIN
--保留未开票完成零售单、销售单、销售退货单、销售换货单、委托代销结算单、采购单、采购退货单、采购换货单、受托代销结算单
	INSERT INTO #TempBillNumberID(BillNumberID,BillType)
	SELECT	billnumberid,billtype 
	FROM	BillIndex 
	WHERE	RedWord=0 
			AND IfInvoice<>2 
			AND draft=0 
			AND BillType IN(11,34,305,45,160,141,6,161,145,312)
END

IF @chkcompleterequestbill=1 --删除已完成请购单
BEGIN
	SELECT * INTO #requestindex FROM dbo.RequestIndex WHERE isstop=0 AND BillNumberId IN (SELECT BillNumberId FROM requestbill WHERE ISNULL(sendqty,0)<qty AND isstop=0)
	SELECT b.* INTO #requestbill FROM dbo.RequestBill b INNER JOIN #requestindex a ON b.BillNumberId=a.BillNumberId
	
	TRUNCATE TABLE RequestIndex
	SET IDENTITY_INSERT RequestIndex ON
	SET @columns=dbo.f_getallcolumns('RequestIndex')
	EXEC('INSERT INTO RequestIndex ('+@columns+') SELECT '+@columns+ ' FROM #requestindex')
	SET IDENTITY_INSERT RequestIndex OFF
	
	TRUNCATE TABLE dbo.RequestBill
	SET IDENTITY_INSERT RequestBill ON
	SET @columns=dbo.f_getallcolumns('RequestBill')
	EXEC('INSERT INTO RequestBill ('+@columns+') SELECT '+@columns+ ' FROM #requestbill')
	SET IDENTITY_INSERT RequestBill OFF
	
	DROP TABLE #requestbill,#requestindex
END
ELSE
BEGIN
	TRUNCATE TABLE RequestIndex
	TRUNCATE TABLE dbo.RequestBill
END

IF @unfinishedposbill=0 --pos小票数据处理
BEGIN
	DELETE FROM dbo.PosSaleBillIndexAll WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndex WHERE BillnumberID=dbo.PosSaleBillIndexAll.BillnumberID)
	DELETE FROM dbo.PosSaleBillAll WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndexAll WHERE BillnumberID=dbo.PosSaleBillAll.BillnumberID)
	DELETE FROM dbo.PosMulAccountAll WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndexALL WHERE BillnumberID=dbo.PosMulAccountAll.BillnumberID)
	DELETE FROM dbo.PosRetailRecord WHERE NOT EXISTS(SELECT 1 FROM dbo.PosSaleBillIndexAll WHERE BillnumberID=dbo.PosRetailRecord.PosBillNumberId)
	OR RetailBillNumberId NOT IN(SELECT BillNumberID FROM #TempBillNumberID WHERE BillType IN(215,305))
END
ELSE
BEGIN
	TRUNCATE TABLE dbo.PosSaleBillIndex
	TRUNCATE TABLE dbo.PosSaleBillIndexAll
	TRUNCATE TABLE dbo.PosSaleBill
	TRUNCATE TABLE dbo.PosSaleBillAll
	TRUNCATE TABLE dbo.PosMulAccount
	TRUNCATE TABLE dbo.PosMulAccountAll
	TRUNCATE TABLE dbo.PosRetailRecord --清除所有小票数据时 清除小票数据和零售单关系映射
END	

-----------------------------------------------------------------------跨年结算处理-----------------------------------------------------------------------
		
---------------删除单据主表----------
IF EXISTS (SELECT NAME FROM sysobjects WHERE type='tr' AND NAME = 'DeleteBill')
	DROP TRIGGER DeleteBill
	
IF @delDraft ='1'
BEGIN
	SELECT * INTO #BillIndexd FROM dbo.BillIndex WHERE BillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID)
	TRUNCATE TABLE dbo.BillIndex
	TRUNCATE TABLE CommissionBillNew --全部清除
	TRUNCATE TABLE LendIndex
	TRUNCATE TABLE LendCheck

	SET IDENTITY_INSERT BillIndex ON
	SET @columns=dbo.f_getallcolumns('billindex')
	EXEC('INSERT INTO BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #BillIndexd')
	SET IDENTITY_INSERT BillIndex OFF
	
	
	DELETE FROM SerialAdjustIndex
	
	DELETE ReceiptBillIndex
	WHERE BillNumberID NOT IN
	(
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
	)
	
	DELETE ReceiptBill
	WHERE BillNumberID NOT IN
	(
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
	)
	
	
	
END
ELSE
BEGIN
	-- 年结存往来核销单一律不保留
	SELECT * INTO #BillIndext FROM dbo.BillIndex WHERE (Draft = 1 AND ifYearBill=0 AND BillType NOT IN (450)) OR BillNumberID IN (SELECT BillNumberID FROM #TempBillNumberID)
	TRUNCATE TABLE dbo.BillIndex
	SET IDENTITY_INSERT BillIndex ON
	SET @columns=dbo.f_getallcolumns('billindex')
	EXEC('INSERT INTO BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #BillIndext')
	SET IDENTITY_INSERT BillIndex OFF
	DELETE FROM SerialAdjustIndex  WHERE Draft = 0 
	
	--保留草稿
	SELECT * INTO #CommissionBillNewt FROM CommissionBillNew WHERE draft=1;
	TRUNCATE TABLE CommissionBillNew;
	
	SET IDENTITY_INSERT CommissionBillNew ON
	SET @columns=dbo.f_getallcolumns('CommissionBillNew')
	EXEC('INSERT INTO CommissionBillNew ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBillNewt')
	SET IDENTITY_INSERT CommissionBillNew OFF
	
	
	--借欠
	SELECT * INTO #LendIndext FROM LendIndex WHERE draft=1;
	TRUNCATE TABLE LendIndex;
	
	SET IDENTITY_INSERT LendIndex ON
	SET @columns=dbo.f_getallcolumns('LendIndex')
	EXEC('INSERT INTO LendIndex ('+@columns+') SELECT '+@columns+ ' FROM #LendIndext')
	SET IDENTITY_INSERT LendIndex OFF
	
	
	DELETE ReceiptBillIndex
	WHERE BillNumberID NOT IN
	(
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
		UNION ALL
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE ifcheck='f'
	)
	
	DELETE ReceiptBill
	WHERE BillNumberID NOT IN
	(
		SELECT BillNumberID
		FROM #TempReceiptBillNumberID
		UNION ALL
		SELECT BillNumberID
		FROM ReceiptBillIndex
		WHERE ifcheck='f'
	)
END

--加期初单据标志
--IF @yearendmode='0'
--BEGIN



UPDATE billindex 
SET IsIni=CASE WHEN billIndex.ifYearBill<>1 THEN 1  ELSE billindex.IsIni END
WHERE draft=0 AND billtype NOT IN (171,169,166,165,144,140)



UPDATE billindex SET CompleteTotal=CompleteTotal+totalinmoney,NCompleteTotal=NCompleteTotal+NTotalInMoney WHERE isini=1 AND billtype NOT IN (181,312)


UPDATE billindex SET totalinmoney=0,NTotalInMoney=0 WHERE isini=1 AND billtype NOT IN (181,312)


--END
---------------删除单据主表 end----------
	

IF @delDraft ='1'
BEGIN
	SELECT * INTO #salebill1 FROM salebill  WHERE billnumberid IN(SELECT billnumberid FROM #TempBillNumberID WHERE billtype ='11')
	TRUNCATE TABLE SaleBill
	SET IDENTITY_INSERT SaleBill ON
	SET @columns=dbo.f_getallcolumns('SaleBill')
	EXEC('INSERT INTO SaleBill ('+@columns+') SELECT '+@columns+ ' FROM #salebill1')
	SET IDENTITY_INSERT SaleBill OFF
	DROP TABLE #salebill1
	
	SELECT * INTO #BuyBill1 FROM buybill WHERE billnumberid IN (SELECT Billnumberid FROM #TempBillNumberID WHERE Billtype='34' )
	TRUNCATE TABLE BuyBill
	SET IDENTITY_INSERT BuyBill ON
	SET @columns=dbo.f_getallcolumns('BuyBill')
	EXEC('INSERT INTO BuyBill ('+@columns+') SELECT '+@columns+ ' FROM #BuyBill1')
	SET IDENTITY_INSERT BuyBill OFF
	DROP TABLE #BuyBill1
	
	DELETE FROM SaleBackBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillType=45 AND b.BillNumberId=SaleBackBill.BillNumberId)						--销售退货单
	DELETE FROM BuyBackBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillType=6 AND b.BillNumberId=dbo.BuyBackBill.BillNumberId )						--采购退货单
	DELETE FROM CommissionBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=CommissionBill.BillNumberId)	--代销单据	
		
	DELETE FROM SaleGoodsExchangeBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillType=160 AND b.BillNumberId=SaleGoodsExchangeBill.BillNumberId)	--销售换货单
	DELETE FROM BuyGoodsExchangeBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillType=161  AND b.BillNumberId=BuyGoodsExchangeBill.BillNumberId)		--采购换货单			
	DELETE FROM RetailBill WHERE  NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=RetailBill.BillNumberId AND b.BillType=305)							--零售单	
	DELETE FROM RetailCombinationBill WHERE  NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=RetailCombinationBill.BillNumberId AND b.BillType=305)		
	DELETE FROM RetailBackBill WHERE  NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=RetailBackBill.BillNumberId AND b.BillType=215)					--零售退货单	
	DELETE FROM PreBill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=PreBill.BillNumberId AND b.billtype IN (189,190))						-- 预收款单，预付款单				
	DELETE FROM AdDebtBill	WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=AdDebtBill.BillNumberId AND b.billtype IN('115','116','128','129'))-- 调账单	
	DELETE FROM MoneyBill	WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=MoneyBill.BillNumberId)	--其他收入、费用单、固定资产购买及变卖、费用单	
	DELETE FROM PriceProtectBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PriceProtectBill.BillNumberId)			-- 价保单
	DELETE FROM Advantage		 WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=Advantage.BillNumberId)			-- 返利、获利单
	DELETE FROM AssetIncDecBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=AssetIncDecBill.BillNumberId AND b.BillType IN (212,213))	--固定资产增加减少
	DELETE FROM AppraisalBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=AppraisalBill.BillNumberId AND b.BillType=400) --暂估入库单
	DELETE FROM AppraisalBackBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=AppraisalBackBill.BillNumberId AND b.BillType=401) --暂估退货单
	DELETE FROM SendBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=SendBill.BillNumberId AND b.BillType=402) --发出商品出库单
	DELETE FROM SendBackBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=SendBackBill.BillNumberId AND b.BillType=403) --发出商品退货单
	DELETE FROM ChargeOffBill  WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=ChargeOffBill.BillNumberId AND b.BillType=450) --往来核销单
	DELETE FROM GiveBill	WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=GiveBill.BillNumberId AND b.BillType=139)			-- 赠送单
	DELETE FROM MoveBill	WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=MoveBill.BillNumberId AND b.BillType=17)			-- 同价调拨单
	DELETE FROM MoveBjBill	WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=MoveBjBill.BillNumberId AND b.BillType=21)		-- 变价调拨单	
	DELETE FROM STypeMoveBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=STypeMoveBill.BillNumberId AND b.BillType=187)		-- 分支机构调拨单
	DELETE FROM OtherInOutBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=OtherInOutBill.BillNumberId AND b.BillType=202)		--其他出入库单明细		
	DELETE FROM DisassembleBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=DisassembleBill.BillNumberId AND b.BillType=16)		-- 生产拆装单	
	DELETE FROM GiveMeBill	WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=GiveMeBill.BillNumberId AND b.BillType=126)		-- 获赠单
	DELETE FROM IntegralExchangeBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=IntegralExchangeBill.BillNumberId AND b.BillType=183)	--(积分兑换单明细表)  
	DELETE FROM dbo.PT_Combin_SaleBackBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PT_Combin_SaleBackBill.BillNumberId AND b.BillType=46) --组合品销售退货单
	DELETE FROM dbo.PT_Combin_SaleBackBillDetail WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PT_Combin_SaleBackBillDetail.BillNumberId AND b.BillType=46) --组合品销售退货单
	DELETE FROM dbo.PT_Combin_SaleBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PT_Combin_SaleBill.BillNumberId AND b.BillType=12) --组合品销售出库单
	DELETE FROM dbo.PT_Combin_SaleBillDetail WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=PT_Combin_SaleBillDetail.BillNumberId AND b.BillType=12) --组合品销售出库单
	DELETE FROM dbo.Transportbill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID B WHERE b.BillNumberID=dbo.Transportbill.billNumberID AND B.BillType=414)
	DELETE FROM dbo.Transportcontrastbill WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID B WHERE b.BillNumberID=dbo.Transportcontrastbill.billNumberID AND B.BillType=414)
	
	TRUNCATE TABLE dbo.BeforePromoteIndex	--零售零售促销方案主表
	TRUNCATE TABLE dbo.BeforePromoteSaleBill
	TRUNCATE TABLE BeforePromoteRetailBill
	TRUNCATE TABLE dbo.BeforePromoteRetailBill	--零售零食促销方案明细
	TRUNCATE TABLE dbo.DepBill			--固定资产折旧
	TRUNCATE TABLE GatheringBill		--收款单
	TRUNCATE TABLE PayBill				--付款单
	TRUNCATE TABLE LoseBill				-- 报损单
	TRUNCATE TABLE OverFlowBill			-- 报溢单
	TRUNCATE TABLE MoveMoneyBill		-- 转款单
	TRUNCATE TABLE adPriceBill			-- 成本调价单
	TRUNCATE TABLE InvoiceBill			-- 发票表
	TRUNCATE TABLE RepairDealDetail		-- #01 维修受理单明细表
	TRUNCATE TABLE RepairDeal			-- #01 维修受理单表			
	DELETE FROM RepairEngage WHERE Draft = 0
	TRUNCATE TABLE DiyBillTypePSaleTypeID
	TRUNCATE TABLE GoodsExchangeBill	-- 换货单
	TRUNCATE TABLE AccountCredence		-- 会计凭证	
	TRUNCATE TABLE SerialAdjustBill		--序列号调整单明细
	TRUNCATE TABLE CM_CarUseIndex		--车辆使用登记单主表
	TRUNCATE TABLE CM_CarUseBill		--车辆使用登记单明细表）
	TRUNCATE TABLE CM_FeeIndex			--车辆费用单主表） 
	TRUNCATE TABLE CM_FeeBill			--车辆费用单明细表）		
	DELETE FROM wx_Bill_JieJian WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_JieJian.BillNumberId)
	DELETE FROM wx_Bill_Self WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Self.BillNumberId)
	DELETE FROM wx_Bill_Send WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Send.BillNumberId)
	DELETE FROM wx_Bill_Call WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Call.BillNumberId)
	DELETE FROM wx_Bill_Replace WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Replace.BillNumberId AND b.BillType=168)		-- 新维修 - 整机更换单
	DELETE FROM wx_Bill_GetBack WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_GetBack.BillNumberId AND b.BillType=167)		-- 新维修 - 维修取件单
	DELETE FROM wx_Bill_Goto WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_Goto.BillNumberId AND b. BillType=172)				-- 新维修 - 上门维修单
	DELETE FROM wx_Bill_SendBack WHERE NOT EXISTS(SELECT 1 FROM #TempBillNumberID b WHERE b.BillNumberId=wx_Bill_SendBack.BillNumberId AND b.BillType=170)      --送修返回
	TRUNCATE TABLE wx_Bill_In			-- 新维修 - 维修品调入单
	TRUNCATE TABLE wx_Bill_Out			-- 新维修 - 维修品调出单
	TRUNCATE TABLE wx_Bill_Move			-- 新维修 - 维修品调拨单
	TRUNCATE TABLE CommissionBillNewDetail
	TRUNCATE TABLE LendBill				-- 借欠	
	DELETE FROM dbo.VipCentToMoneyBill WHERE NOT EXISTS (SELECT 1 FROM #TempBillNumberID b WHERE  b.BillNumberId=BillNumberId AND b.BillType=427) --积分转储值单
	
END
ELSE
BEGIN
	SELECT * INTO #salebill FROM salebill  WHERE billnumberid IN(SELECT billnumberid FROM billindex WHERE billtype ='11' )
	TRUNCATE TABLE SaleBill
	SET IDENTITY_INSERT SaleBill ON
	SET @columns=dbo.f_getallcolumns('SaleBill')
	EXEC('INSERT INTO SaleBill ('+@columns+') SELECT '+@columns+ ' FROM #salebill')
	SET IDENTITY_INSERT SaleBill OFF
	DROP TABLE #salebill
	
	SELECT * INTO #BuyBill FROM buybill WHERE billnumberid IN (SELECT Billnumberid FROM billindex WHERE Billtype='34') 
	TRUNCATE TABLE BuyBill
	SET IDENTITY_INSERT BuyBill ON
	SET @columns=dbo.f_getallcolumns('BuyBill')
	EXEC('INSERT INTO BuyBill ('+@columns+') SELECT '+@columns+ ' FROM #Buybill')
	SET IDENTITY_INSERT BuyBill OFF
	DROP TABLE #Buybill
	
	SELECT * INTO #CommissionBillNewDetail FROM CommissionBillNewDetail WHERE billnumberid in (SELECT billnumberid FROM #CommissionBillNewt)
	TRUNCATE TABLE CommissionBillNewDetail
	
	SET IDENTITY_INSERT CommissionBillNewDetail ON
	SET @columns=dbo.f_getallcolumns('CommissionBillNewDetail')
	EXEC('INSERT INTO CommissionBillNewDetail ('+@columns+') SELECT '+@columns+ ' FROM #CommissionBillNewDetail')
	SET IDENTITY_INSERT CommissionBillNewDetail OFF
	DROP TABLE #CommissionBillNewDetail
	
	SELECT * INTO #LendBillt FROM LendBill WHERE billnumberid in (SELECT billnumberid FROM #LendIndext)
	TRUNCATE TABLE LendBill
	
	SET IDENTITY_INSERT LendBill ON
	SET @columns=dbo.f_getallcolumns('LendBill')
	EXEC('INSERT INTO LendBill ('+@columns+') SELECT '+@columns+ ' FROM #LendBillt')
	SET IDENTITY_INSERT LendBill OFF
	DROP TABLE #LendBillt

	DELETE FROM SaleBackBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE b.billtype ='45' AND b.BillNumberId=SaleBackBill.BillNumberId)	-- 销售退货单
	DELETE FROM GatheringBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE b.billtype ='4'  AND b.BillNumberId=GatheringBill.BillNumberId)	-- 收款单
	DELETE FROM DiyBillTypePSaleTypeID WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=DiyBillTypePSaleTypeID.SalebillNumberId)
	DELETE FROM BuyBackBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=BuyBackBill.BillNumberId)						-- 采购退货单
	DELETE FROM PayBill			 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=PayBill.BillNumberId)			-- 付款单
	DELETE FROM LoseBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=LoseBill.BillNumberId)		-- 报损单
	DELETE FROM OverFlowBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=OverFlowBill.BillNumberId)			-- 报溢单
	DELETE FROM MoveMoneyBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=MoveMoneyBill.BillNumberId)		-- 转款单
	DELETE FROM adDebtbill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=adDebtbill.BillNumberId)			-- 调账单
	DELETE FROM adPriceBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=adPriceBill.BillNumberId)			-- 成本调价单
	DELETE FROM MoveBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=MoveBill.BillNumberId)			-- 同价调拨单
	DELETE FROM MoveBjBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=MoveBjBill.BillNumberId)			-- 变价调拨单
	DELETE FROM MoneyBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=MoneyBill.BillNumberId)			-- 收入、费用单、、待摊费用表、现金费用	
	DELETE FROM RetailBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailBill.BillNumberId)			-- 零售单
	DELETE FROM RetailCombinationBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailCombinationBill.BillNumberId)			-- 零售单
	DELETE FROM RetailBackBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RetailBackBill.BillNumberId)			-- 零售退货单
	DELETE FROM BeforePromoteIndex WHERE NOT EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BeforePromoBillNumberId=dbo.BeforePromoteIndex.BillNumberId AND draft=1)	--零售零售促销方案主表
	DELETE FROM BeforePromoteRetailBill WHERE NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.BeforePromoteRetailBill.BillNumberId)	--零售零食促销方案明细	
	DELETE FROM DisassembleBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=DisassembleBill.BillNumberId)		-- 生产拆装单
	DELETE FROM CommissionBill	 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=CommissionBill.BillNumberId)		-- 代销单据
	DELETE FROM PriceProtectBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=PriceProtectBill.BillNumberId)			-- 价保单
	DELETE FROM Advantage		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=Advantage.BillNumberId)			-- 返利、获利单
	DELETE FROM GiveMeBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=GiveMeBill.BillNumberId)		-- 获赠单
	DELETE FROM GiveBill		 WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=GiveBill.BillNumberId)		-- 赠送单
	DELETE FROM AssetIncDecBill  WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=AssetIncDecBill.BillNumberId AND b.BillType IN (212,213))	--固定资产增加减少
	DELETE FROM DepBill  WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=DepBill.BillNumberId )	--固定资产折旧
	DELETE FROM FixedAssetsDetails WHERE NOT EXISTS(SELECT 1 FROM FixedAssetsIndex b WHERE b.BillNumberId=dbo.FixedAssetsDetails.BillNumberID) --固定资产盘点单
	DELETE FROM VipAddMoneyBatchBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=VipAddMoneyBatchBill.BillNumberId AND b.BillType =312)--会员储值单
	DELETE FROM VipCentToMoneyBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=VipCentToMoneyBill.BillNumberId AND b.BillType =427)--会员积分转储值单
	
	
	DELETE FROM CapitalTransfer_Bill WHERE NOT EXISTS(SELECT 1 FROM billindex b WHERE b.BillNumberId=dbo.CapitalTransfer_Bill.BillNumberId) --资金调拨单
	
	DELETE FROM RepairDeal WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RepairDeal.BillNumberId)
	DELETE FROM RepairDealDetail WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=RepairDealDetail.BillNumberId)
	DELETE FROM RepairEngage WHERE NOT EXISTS (SELECT 1 FROM RepairDeal b WHERE  b.EngageBillID=RepairEngage.BillNumberId) AND Draft=0 AND Stat=3
	DELETE FROM GoodsExchangeBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=GoodsExchangeBill.BillNumberId)		-- 换货单
	DELETE FROM AccountCredence WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=AccountCredence.BillNumberId)			-- 会计凭证
	DELETE FROM SaleGoodsExchangeBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=SaleGoodsExchangeBill.BillNumberId)	-- 销售换货单
	DELETE FROM buyGoodsExchangeBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=buyGoodsExchangeBill.BillNumberId)		-- 采购换货单

	-- 清除新维修相关表
	DELETE FROM wx_Bill_JieJian WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_JieJian.BillNumberId)			-- 新维修 - 接件单
	DELETE FROM wx_Bill_Self WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Self.BillNumberId)				-- 新维修 - 维修单		
	DELETE FROM wx_Bill_GetBack WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_GetBack.BillNumberId)			-- 新维修 - 维修取件单		
	DELETE FROM wx_Bill_Replace WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Replace.BillNumberId)			-- 新维修 - 整机更换单				
	DELETE FROM wx_Bill_Send WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Send.BillNumberId)				-- 新维修 - 送修单
	DELETE FROM wx_Bill_SendBack WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_SendBack.BillNumberId)			-- 新维修 - 送修返回单
	DELETE FROM wx_Bill_Call WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Call.BillNumberId)				-- 新维修 - 报修单
	DELETE FROM wx_Bill_Goto WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Goto.BillNumberId)				-- 新维修 - 上门维修单		
	DELETE FROM wx_Bill_In WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_In.BillNumberId)				-- 新维修 - 维修品调入单
	DELETE FROM wx_Bill_Out WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Out.BillNumberId)				-- 新维修 - 维修品调出单
	DELETE FROM wx_Bill_Move WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=wx_Bill_Move.BillNumberId)				-- 新维修 - 维修品调拨单	
	DELETE FROM PreBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=PreBill.BillNumberId)					-- 预收、预付单
	DELETE FROM STypeMoveBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=STypeMoveBill.BillNumberId)			-- 分支机构调拨单			
	DELETE FROM IntegralExchangeBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=IntegralExchangeBill.BillNumberId)		--积分兑换单			
	DELETE FROM QuotePriceBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=QuotePriceBill.BillNumberId)
	DELETE FROM AskPriceBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=AskPriceBill.BillNumberId)	
	DELETE FROM SerialAdjustBill WHERE NOT EXISTS(SELECT 1 FROM SerialAdjustIndex WHERE draft = 1 AND BillNumberId=dbo.SerialAdjustBill.BillNumberId)			--序列号调整单明细
	DELETE FROM OtherInOutBill WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=OtherInOutBill.BillNumberId)			--其他出入库单明细
	DELETE FROM InvoiceBill
	
	--暂估，发出商品单据处理
	DELETE FROM AppraisalBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=AppraisalBill.BillNumberId AND b.BillType=400) --暂估入库单
	DELETE FROM AppraisalBackBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=AppraisalBackBill.BillNumberId AND b.BillType=401) --暂估退货单
	DELETE FROM SendBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=SendBill.BillNumberId AND b.BillType=402) --发出商品出库单
	DELETE FROM SendBackBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=SendBackBill.BillNumberId AND b.BillType=403) --发出商品退货单
	DELETE FROM ChargeOffBill  WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=ChargeOffBill.BillNumberId AND b.BillType=450) --往来核销单
	DELETE FROM dbo.PT_Combin_SaleBackBill WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=PT_Combin_SaleBackBill.BillNumberId AND b.BillType=46) --组合品销售退货单
	DELETE FROM dbo.PT_Combin_SaleBackBillDetail WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=PT_Combin_SaleBackBillDetail.BillNumberId AND b.BillType=46) --组合品销售退货单
	DELETE FROM dbo.PT_Combin_SaleBill WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=PT_Combin_SaleBill.BillNumberId AND b.BillType=12) --组合品销售出库单
	DELETE FROM dbo.PT_Combin_SaleBillDetail WHERE NOT EXISTS (SELECT 1 FROM Billindex b WHERE  b.BillNumberId=PT_Combin_SaleBillDetail.BillNumberId AND b.BillType=12) --组合品销售出库单
	DELETE FROM dbo.Transportbill WHERE NOT EXISTS(SELECT 1 FROM Billindex B WHERE b.BillNumberID=dbo.Transportbill.billNumberID AND B.BillType=414)
	DELETE FROM dbo.Transportcontrastbill WHERE NOT EXISTS(SELECT 1 FROM Billindex B WHERE b.BillNumberID=dbo.Transportcontrastbill.billNumberID AND B.BillType=414)
	
	DELETE FROM BeforePromoteIndex WHERE NOT EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BeforePromoBillNumberId=dbo.BeforePromoteIndex.BillNumberId AND draft=1)	--零售零售促销方案主表
	DELETE FROM BeforePromoteRetailBill WHERE NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.BeforePromoteRetailBill.BillNumberId)	--零售零食促销方案明细
	DELETE FROM BeforePromoteSaleBill WHERE BillNumberId NOT IN (SELECT BillNumberId FROM dbo.BeforePromoteIndex WHERE BillNumberId=BeforePromoteSaleBill.BillNumberId)	
	
END

-------------------------------------------------------------------------------------------处理优惠券 BEGIN----------------------------------------------------------------------------------------
IF @delDraft ='1'
BEGIN
	--优惠券年结 不保存未结算完成的单据，只转应收应付余额
	TRUNCATE TABLE dbo.Coupon_BillIndex
	
	--如果结转的是已消费的优惠券 ，券信息也被清了
	DELETE FROM dbo.Coupon_CodeInfo WHERE [STATE] IN (3,6)
	UPDATE Coupon_CodeInfo  SET IsYear=1,IsIni=1,IniState=CASE WHEN [state] IN (4,5) THEN 2 ELSE [state] END ,[state]=CASE WHEN [state] IN (4,5) THEN 2 ELSE [state] END,
								IniKtypeId=KtypeId,IniCargoId=CargoId
	TRUNCATE TABLE Coupon_BillUsed 
	TRUNCATE TABLE Coupon_CodeInOut
	TRUNCATE TABLE dbo.coupon_InBill 
	TRUNCATE TABLE dbo.coupon_OutBill 
	TRUNCATE TABLE dbo.coupon_BackBill 
	TRUNCATE TABLE dbo.coupon_AllotBill 
	TRUNCATE TABLE dbo.coupon_AllotBillStype
END
ELSE
BEGIN
	--保留草稿
	SELECT * INTO #CouponBillIndexd FROM dbo.Coupon_BillIndex WHERE Draft = 1 AND ifYearBill=0 
	
	TRUNCATE TABLE dbo.Coupon_BillIndex
	SET IDENTITY_INSERT Coupon_BillIndex ON
	SET @columns=dbo.f_getallcolumns('Coupon_BillIndex')
	EXEC('INSERT INTO Coupon_BillIndex ('+@columns+') SELECT '+@columns+ ' FROM #CouponBillIndexd')
	SET IDENTITY_INSERT Coupon_BillIndex OFF
	
	--如果结转的是已消费的优惠券 ，券信息也被清了
	DELETE FROM dbo.Coupon_CodeInfo WHERE [STATE] IN (3,6)
	UPDATE Coupon_CodeInfo  SET IsYear=1,IsIni=1,
								IniState=CASE WHEN [state] IN (4,5) THEN 2 ELSE [state] END ,
								[state]=CASE WHEN [state] IN (4,5) THEN 2 ELSE [state] END ,
								iniktypeid=KtypeId,
								Inicargoid=CargoId
								
	TRUNCATE TABLE Coupon_BillUsed 
	TRUNCATE TABLE Coupon_CodeInOut
	
	DELETE FROM dbo.coupon_InBill WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_InBill.billNumberID AND b.BillType=423)
	DELETE FROM dbo.coupon_OutBill WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_OutBill.billNumberID AND b.BillType=424)
	DELETE FROM dbo.coupon_BackBill WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_BackBill.billNumberID AND b.BillType=426)
	DELETE FROM dbo.coupon_AllotBill WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_AllotBill.billNumberID AND b.BillType=425)
	DELETE FROM dbo.coupon_AllotBillStype WHERE NOT EXISTS (SELECT 1 FROM Coupon_BillIndex b WHERE b.BillNumberID=dbo.coupon_AllotBillStype.billNumberID AND b.BillType IN (428,429))
	
	DROP TABLE #CouponBillIndexd
	
END

-------------------------------------------------------------------------------------------处理优惠券 END  ----------------------------------------------------------------------------------------
--自定义删除(优惠券的相关单据没自定义)
;WITH CustomExists
	AS
	(	
		SELECT BillType,BillNumberID FROM dbo.BillIndex
		UNION ALL
		SELECT BillType,BillNumberID FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillType,BillNumberID FROM dbo.OrderIndex
		UNION ALL 
		SELECT BillType,BillNumberID FROM dbo.LendIndex
		UNION ALL
		SELECT 204 AS BillType,BillNumberID FROM dbo.RequestIndex
		UNION ALL 
		SELECT 311 AS BillType,BillNumberId FROM dbo.CommissionBillNew
		UNION ALL 
		SELECT BillType,BillNumberID FROM dbo.FaPiaoBillIndex
		UNION ALL
		SELECT BillType,BillNumberId FROM dbo.FactIndex
	
	)
SELECT BillType,BillNumberID INTO #CustomExists FROM CustomExists
--9.7自定义
DELETE A FROM dbo.Custom_BillIndex A WHERE NOT EXISTS(SELECT 1 FROM #CustomExists WHERE BillType=A.BillType AND BillNumberID=A.BillId)
DELETE A FROM dbo.Custom_BillDetails A WHERE NOT EXISTS(SELECT 1 FROM #CustomExists WHERE BillType=A.BillType AND BillNumberID=A.BillId)
DROP TABLE #CustomExists
--<9.7自定义
DELETE FROM  BillIndex_CarRepair WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.Billindex_CarRepair.BillNumberId)
DELETE FROM  CustomBillColumns WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.CustomBillColumns.BillNumberId)
DELETE FROM  CustomBillDetailColumns WHERE  NOT EXISTS (SELECT 1 FROM BillIndex WHERE BillNumberId=dbo.CustomBillDetailColumns.BillNumberId AND BillType=dbo.CustomBillDetailColumns.billtype)
											 AND NOT EXISTS(SELECT 1 FROM dbo.BeforePromoteIndex WHERE BillNumberId=dbo.CustomBillDetailColumns.billnumberid AND dbo.CustomBillDetailColumns.billtype=9999)
DROP TABLE #TempBillNumberID
UPDATE wx_Bill_JieJian SET ifYearBillDisplay = 0 WHERE ifYearBillDisplay = 1
	-- ********	清除单据明细 - END	********

TRUNCATE TABLE ListTable			-- 科目变化明细表,放后面是因为前面要用到LISTTABLE
	
--把结转的期初收付款单改为年结存单据
UPDATE dbo.BillIndex SET IsIni=1,ifYearBill=1 WHERE BillType IN (4,66) AND draft=0

--后续单据处理
--------删除主表后续处理  start ------------------------------	
DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype not  IN (423,424,425,426,301,300,313) 			--多账户
DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM dbo.Coupon_BillIndex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype IN (423,424,425,426)		--多账户
DELETE FROM BillMulAccount WHERE NOT EXISTS (SELECT 1 FROM dbo.orderindex b WHERE  b.BillNumberId=BillMulAccount.BillNumberId AND b.billtype =BillMulAccount.billtype) AND billtype IN (301,300,313)		--多账户


DELETE FROM BillMulBrand WHERE NOT EXISTS (SELECT 1 FROM BillIndex b WHERE  b.BillNumberId=BillMulBrand.BillNumberId)			--多账户

IF @delOrder = '1'   
BEGIN
	TRUNCATE TABLE OrderBill			-- 销售、采购订单
	TRUNCATE TABLE OrderIndex			-- 清除订单索引表
	DELETE dbo.OrderIndex WHERE BillType=313		--清除所有组合品订单
	TRUNCATE TABLE PT_Combin_OrderBill				--清除所有组合品订单信息
	TRUNCATE TABLE PT_Combin_OrderBillDetail			--清除所有组合品订单明细信息
	TRUNCATE TABLE PT_SaleOrderLockDetail		 		--清除订单锁库信息
	UPDATE dbo.GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
	UPDATE dbo.Ini_GOODSSTOCKS_QTY SET LockNumber=0	--清除订单锁库信息
	TRUNCATE TABLE Ini_GoodsStocks_Order    --清除期初订单库存
END

IF @clearnocompleteonshelves = 1
BEGIN

UPDATE dbo.RetailBackBill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 215)
UPDATE dbo.salebackbill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 45)
UPDATE dbo.salegoodsexchangebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1)AND BillType = 160)
UPDATE dbo.commissionbill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType IN(142,144))
UPDATE dbo.PT_Combin_SaleBackBillDetail SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 46)
UPDATE dbo.buybill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 34)
UPDATE dbo.buygoodsexchangebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 161)
UPDATE dbo.givemebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 126)
UPDATE dbo.movebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 17)
UPDATE dbo.movebjbill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 21)
UPDATE dbo.stypemovebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 188)
UPDATE dbo.otherinoutbill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 201)
UPDATE dbo.disassemblebill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 16)
UPDATE dbo.AppraisalBill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 400)
UPDATE dbo.SendBackBill SET InflowQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (ShelveState = 1 OR ShelveRefState = 1) AND BillType = 403) 
--991门店配验收,未上架完成的，把上架数量改为0
UPDATE dbo.DeliveryCheckBill SET InflowQty = 0 
                             from DeliveryBill a where a.BillNumberId=DeliveryCheckBill.DeliveryID and a.Qty>DeliveryCheckBill.InflowQty
                    
                   
UPDATE dbo.BillIndex SET ShelveRefState = 0, ShelveState = 0 
          WHERE (ShelveState = 1 OR ShelveRefState = 1)
                
END
 --------------  是否清除未完成拣货/运输的单据 0-不清除 1-清除                 
IF @clearnocompletepickandtransport = 1
BEGIN                   
UPDATE dbo.salebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 11) 
UPDATE dbo.salegoodsexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 160) 
UPDATE dbo.givebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 139)                                 
UPDATE dbo.commissionbill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType IN(140,146)) 
UPDATE dbo.PT_Combin_SaleBillDetail SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 12) 
UPDATE dbo.buybackbill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 6) 
UPDATE dbo.buygoodsexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 161) 
UPDATE dbo.movebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 17) 
UPDATE dbo.movebjbill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 21) 
UPDATE dbo.stypemovebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 187) 
UPDATE dbo.otherinoutbill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 202) 
UPDATE dbo.disassemblebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 16) 
UPDATE dbo.integralexchangebill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 183) 
UPDATE dbo.AppraisalBackBill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 401) 
UPDATE dbo.SendBill SET PickedQty = 0 WHERE BillNumberId IN(
                SELECT BillNumberId FROM dbo.BillIndex WHERE  (citestate = 1 OR progressstate = 1) AND BillType = 402)

--991新增门店验收单的拣货
UPDATE dbo.DeliveryBill SET PickedQty = 0  where Qty>PickedQty
                            

               
UPDATE dbo.BillIndex SET citestate = 0, progressstate = 0 
          WHERE (citestate = 1 OR progressstate = 1)                
END

IF @delOrder <> '1' AND @delEndOrder = '1'	-- 清除已完成订单
BEGIN
	--更新期初订单库存
	DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=0 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
	DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=0 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
	
	--删除已完成的销售订单 去除关联关系
	UPDATE OrderBill SET SaleOrderId =-1
	WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState = '1' AND BillOver = 0 and billtype =300)  )
	
	DELETE FROM OrderIndex WHERE OrderState = '1' AND BillOver = 0
	DELETE FROM OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=OrderBill.billNumberID)
	DELETE FROM dbo.PT_Combin_OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBill.billNumberID)
	DELETE FROM dbo.PT_Combin_OrderBillDetail WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBillDetail.billNumberID)
END

--清除中止订单
IF @delOrder<> '1' AND @delstoporder= '1'
BEGIN
	--更新期初订单库存
	DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM OrderBill A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE<>313
	DELETE FROM Ini_GoodsStocks_Order WHERE ORDERID IN(SELECT ORDERID FROM PT_Combin_OrderBillDetail A INNER JOIN OrderIndex B ON B.OrderState='1' AND B.BillOver=1 AND A.billNumberID=B.billNumberId) AND BILLTYPE=313
	
	--删除已中止的销售订单 去除关联关系
	UPDATE OrderBill SET SaleOrderId =-1
	WHERE SaleOrderId IN (SELECT ORDERID FROM OrderBill WHERE  billNumberID IN (SELECT billNumberID FROM dbo.OrderIndex WHERE OrderState='1' AND BillOver=1 and billtype =300)  )
	
	DELETE FROM dbo.OrderIndex WHERE OrderState='1' AND BillOver=1
	DELETE FROM OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=OrderBill.billNumberID)
	DELETE FROM dbo.PT_Combin_OrderBill WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBill.billNumberID)
	DELETE FROM dbo.PT_Combin_OrderBillDetail WHERE NOT EXISTS(SELECT 1 FROM OrderIndex WHERE billNumberId=PT_Combin_OrderBillDetail.billNumberID)
END

-- 删除OrderBill 中关联报价单、询价单、请购单billnumberid无效的记录
UPDATE dbo.OrderBill SET AskBillID=0,AskBillNumberID=0 WHERE AskBillID <> 0
UPDATE dbo.OrderBill SET RequestBillID=0,RequestBillNumberID=0 WHERE RequestBillID<>0 AND NOT EXISTS(SELECT 1 FROM Requestbill WHERE ID =OrderBill.RequestBillID)
-- 删除销售、采购明细表中，无效关联 OrderBill 中的 OrderID 记录
UPDATE SaleBill SET OrderID = -1 WHERE OrderID <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=SaleBill.OrderID)
UPDATE BuyBill SET OrderID = -1 WHERE OrderID <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=BuyBill.OrderID)

--打断销售 采购有订金产生的 预收\付款  收付款单关联关系
UPDATE prebill set RelevanceBillId=-1 
WHERE RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=prebill.RelevanceBillId)
UPDATE gatheringbill set RelevanceBillId=-1 
WHERE  RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=gatheringbill.RelevanceBillId)
UPDATE paybill set RelevanceBillId=-1 
WHERE  RelevanceBillId <> -1 AND NOT EXISTS(SELECT 1 FROM OrderBill WHERE OrderID=paybill.RelevanceBillId)

-- 如果有保留的单据，则给其赋一个年结前单据的标志
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE Draft = 0)
BEGIN
	UPDATE BillIndex SET ifYearBill = 1 WHERE Draft = 0
	DELETE FROM visit WHERE NOT EXISTS(SELECT 1 FROM BillIndex WHERE Draft = 0 AND BillNumberId=visit.JbBillNumberID)
	DELETE FROM visitfj WHERE NOT EXISTS (SELECT 1 FROM visit WHERE billnumberid=visitfj.billnumberid)
END
IF EXISTS(SELECT TOP 1 1 FROM dbo.LendIndex WHERE Draft = 0)
BEGIN
	UPDATE LendIndex SET ifYearBill = 1 WHERE Draft = 0
END
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




GO
/*年结存处理实物库存*/
IF EXISTS(SELECT 1  FROM SysObjects WHERE ID=OBJECT_ID(N'GP_YearProcPhyStock',N'P'))
BEGIN
	DROP PROC GP_YearProcPhyStock
END
GO

CREATE PROC GP_YearProcPhyStock
AS
BEGIN
	IF NOT EXISTS(SELECT  1 FROM dbo.sysdata WHERE SubName='isphysicalsstock' AND SubValue='1')
	BEGIN
		RETURN 0
	END
	
	DECLARE @StartDate DATETIME,
			@RowCount  INT,
			@RowIndex  INT,
			@STypeID   VARCHAR(100),
			@Qty	   NUMERIC(24,10),
			@BillNumberID INT
			
	SELECT @StartDate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth
	
	DECLARE @Tmp TABLE
	(
		PTypeID		VARCHAR(100),
		STypeID     VARCHAR(100),
		KTypeID		VARCHAR(100),
		CargoID		INT,
		IsCombined	INT,
		ItemID		INT,
		GoodsNumber VARCHAR(100),
		ProduceDate VARCHAR(100),
		ValidDate   VARCHAR(100),
		BillType    INT,
		Qty         NUMERIC(24,10),
		NQty        NUMERIC(24,10)
	)
	
	DECLARE @SType TABLE
	(
		STypeID		VARCHAR(100),
		RowIndex    INT,
		Qty			NUMERIC(24,10)
	)
	
	
---------------------------------仓库入库单------------------------------------------	
	--借欠单据
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.LendBill A INNER JOIN dbo.LendIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType IN(71,88)  AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN dbo.CargoType S 
	ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418  AND A.FromBillType IN(71,88) AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0
	
	--零售退货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.RetailBackBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=215 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN dbo.CargoType S ON A.CargoID=S.CargoID
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=215 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0
	
	--销售退货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.saleBackBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=45 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=45 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0
	
	
	--销售换货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.SaleGoodsExchangeBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=160 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=160 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.InOrOut='I' AND A.Qty-ISNULL(C.Qty,0)>0
	
	--委托代销退货单 受托代销收货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.CommissionBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType IN(142,144) AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType IN(142,144) AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0

	--采购入库单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.BuyBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=34 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=34 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--采购换货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.BuyGoodsExchangeBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=161 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=161 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.InOrOut='I' AND A.Qty-ISNULL(C.Qty,0)>0
	
	--获赠单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.GivemeBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=126 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=126 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--其他入库单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.otherinoutbill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=201 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=201 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--报溢单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.overflowbill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=14 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=14 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--生产拆装单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.disassemblebill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=16 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=16 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.InOrOut='I' AND A.Qty-ISNULL(C.Qty,0)>0	
	
	--维修单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.wx_bill_self A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=166 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=166 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.InOrOut='I' AND A.Qty-ISNULL(C.Qty,0)>0	
	
	--维修品调入单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.wx_bill_in A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=173 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=173 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0		
	
	--同价调拨单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID2 ,A.InCargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.MoveBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=17 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=17 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--变价调拨单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID2 ,A.InCargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.MoveBjBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=21 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=21 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--分支机构调拨入库单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID2 ,A.InCargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.STypeMoveBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=188 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=188 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	INSERT INTO @SType(
						STypeID,
						Qty,
						RowIndex
					  ) 
	SELECT				STypeID,
						SUM(Qty),
						ROW_NUMBER() OVER(ORDER BY GETDATE()) AS RowIndex
	FROM @Tmp 
	GROUP BY STypeId
	
	SELECT @RowCount=COUNT(1),@RowIndex=1 FROM @SType
	WHILE(@RowIndex<=@RowCount)
	BEGIN
		SELECT @STypeID=STypeID,@Qty=Qty FROM @SType WHERE RowIndex=@RowIndex
		INSERT INTO dbo.FactIndex
	        (  BillDate , BillCode , OtherType , BillType ,
	           Stypeid ,dtypeId ,etypeid ,ktypeid,ktypeid2,
	           ifcheck ,checke ,checkTime ,
	           draft ,
	           totalqty ,
	           IsIni ,
	           Comment ,
	           explain ,
	           FromBillType
	        )
	    SELECT @StartDate,'IniWR-MRFZJG-T'+ @STypeID +'-'+CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(@RowIndex AS VARCHAR(10)),
		   0,422,@Stypeid,'','','','','f','',GETDATE(),1,@Qty,1,'通过年结存结转而来','',0    
		SELECT @BillNumberID=@@IDENTITY
		
		INSERT INTO dbo.FactInOut
		        ( billNumberID ,billtype ,Stypeid ,ptypeid ,ktypeid ,qty ,
		          UnitID ,NQty ,NUnitID ,ItemID ,IsCombined ,GoodsOrder ,
		          ProduceDate ,ValidDate ,CargoID ,Serial ,comment ,
		          FromBillNumberID ,FromBillID ,FromBillType ,IsUnit2 ,GoodsNumber ,
				  NUnitMsg ,MUnitMsg ,entryCode ,UnitRate , MQty ,
		          MUnitRate , MUnitID , Base ,Sqty
		        )
		SELECT @BillNumberID,422,@STypeID,PTypeID,KTypeID,ISNULL(SUM(Qty),0),p.baseUnitId,
			   ISNULL(SUM(NQty),0),p.AssistantUnitId,ItemID,IsCombined,-1,ProduceDate,ValidDate,
			   CargoID,'','年结存结转而来',0,0,0,0,GoodsNumber,'','','',1,ISNULL(SUM(Qty),0),
			   1,p.baseUnitId,'年结存结转而来',0
		FROM   @Tmp A
		LEFT JOIN dbo.ptype p ON A.PTypeID=p.typeId
		WHERE Stypeid=@STypeID
		GROUP BY ktypeid,
				 ptypeid,
				 CargoID,
				 IsCombined,
				 ItemID,
				 GoodsNumber,
				 ProduceDate,
				 ValidDate,
				 baseUnitId,
				 AssistantUnitId
		SET @RowIndex=@RowIndex+1
	END
	
---------------------------------仓库入库单---------------------------------------	

DELETE FROM @Tmp
DELETE FROM @SType

---------------------------------仓库出库单---------------------------------------		
	--零售单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.RetailBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=305 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=305 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	

	--销售出库单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.SaleBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=11 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=11 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0

	--销售换货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.SaleGoodsExchangeBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=160 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=160 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.InOrOut='O' AND A.Qty-ISNULL(C.Qty,0)>0	
	
	--赠送单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.GiveBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=139 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=139 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0

	--委托代销发货单 受托代销退货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.CommissionBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType IN(140,146) AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType IN(140,146) AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--组合品销售出库单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.PT_Combin_SaleBillDetail A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType =12 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=12 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	

	--采购退货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.BuyBackBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType =6 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=6 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0		

	--采购换货单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.BuyGoodsExchangeBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=161 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=161 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.InOrOut='O' AND A.Qty-ISNULL(C.Qty,0)>0		

	--同价调拨单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.OutCargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.MoveBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=17 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=17 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--变价调拨单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.OutCargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.MoveBjBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=21 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=21 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--分支机构调拨出库单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.OutCargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.STypeMoveBill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=187 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=187 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--生产拆装单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.disassemblebill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=16 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=16 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.InOrOut='O' AND A.Qty-ISNULL(C.Qty,0)>0		

	--其他出库单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   A.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.otherinoutbill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=202 AND B.RedWord=0 AND B.ifcheck='t'
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=202 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0		
	
	--报损单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.losebill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=9 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=9 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
		
	--借欠单据
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.LendBill A INNER JOIN dbo.LendIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType IN(72,87)  AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN dbo.CargoType S 
	ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418  AND A.FromBillType IN(72,87) AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0

	--维修单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.wx_bill_self A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=166 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=166 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.InOrOut='O' AND A.Qty-ISNULL(C.Qty,0)>0	
			
	--整机更换单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.wx_bill_replace A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=168 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=168 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0		

	--上门维修单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.wx_bill_goto A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=172 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=172 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0			
	
	--上门维修单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.wx_bill_out A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=174 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=174 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0	
	
	--积分兑换单
	INSERT INTO @Tmp
	        ( 
			  PTypeID ,STypeID ,KTypeID ,CargoID ,IsCombined ,ItemID ,GoodsNumber ,
	          ProduceDate ,ValidDate ,BillType ,Qty ,NQty
	        )
	SELECT A.PTypeID ,B.Stypeid ,
		   S.KTypeID ,A.CargoID ,
		   A.IsCombined ,A.ItemID ,
		   A.GoodsNumber , A.ProduceDate ,
		   A.ValidDate ,B.BillType ,
		   A.Qty-ISNULL(C.Qty,0),A.NQty-ISNULL(C.NQty,0) 
	FROM dbo.integralexchangebill A INNER JOIN dbo.BillIndex B 
	ON A.BillNumberId=B.BillNumberId AND B.BillType=183 AND B.RedWord=0 AND B.ifcheck='t'
	INNER JOIN CargoType S ON A.CargoID=S.CargoID 
	LEFT JOIN (
		SELECT ISNULL(SUM(Qty),0) AS Qty,ISNULL(SUM(NQty),0) AS NQty,FromBillID,FromBillNumberID,A.FromBillType
		FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B 
		ON A.BillNumberID=B.BillNumberId
		WHERE B.ifcheck='t' AND RedWord=0 AND B.BillType=418 AND A.FromBillType=183 AND FromBillID>0 AND FromBillNumberID>0
		GROUP BY FromBillID,FromBillNumberID,A.FromBillType
	) C
	ON C.FromBillID=A.ID AND C.FromBillNumberID=A.BillNumberID
	WHERE A.Qty-ISNULL(C.Qty,0)>0				
	
	INSERT INTO @SType(
						STypeID,
						Qty,
						RowIndex
					  ) 
	SELECT				STypeID,
						SUM(Qty),
						ROW_NUMBER() OVER(ORDER BY GETDATE()) AS RowIndex
	FROM @Tmp 
	GROUP BY STypeId
	
	SELECT @RowCount=COUNT(1),@RowIndex=1 FROM @SType
	WHILE(@RowIndex<=@RowCount)
	BEGIN
		SELECT @STypeID=STypeID,@Qty=Qty FROM @SType WHERE RowIndex=@RowIndex
		INSERT INTO dbo.FactIndex
	        (  BillDate , BillCode , OtherType , BillType ,
	           Stypeid ,dtypeId ,etypeid ,ktypeid,KTypeID2,
	           ifcheck ,checke ,checkTime ,
	           draft ,
	           totalqty ,
	           IsIni ,
	           Comment ,
	           explain ,
	           FromBillType
	        )
	    SELECT @StartDate,'IniVC-MRFZJG-T'+ @STypeID +'-'+CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(@RowIndex AS VARCHAR(10)),
		   0,421,@Stypeid,'','','','','f','',GETDATE(),1,@Qty,1,'通过年结存结转而来','',0    
		SELECT @BillNumberID=@@IDENTITY
		
		INSERT INTO dbo.FactInOut
		        ( billNumberID ,billtype ,Stypeid ,ptypeid ,ktypeid ,qty ,
		          UnitID ,NQty ,NUnitID ,ItemID ,IsCombined ,GoodsOrder ,
		          ProduceDate ,ValidDate ,CargoID ,Serial ,comment ,
		          FromBillNumberID ,FromBillID ,FromBillType ,IsUnit2 ,GoodsNumber ,
				  NUnitMsg ,MUnitMsg ,entryCode ,UnitRate , MQty ,
		          MUnitRate , MUnitID , Base ,Sqty
		        )
		SELECT @BillNumberID,421,@STypeID,PTypeID,KTypeID,ISNULL(SUM(Qty),0),p.baseUnitId,
			   ISNULL(SUM(NQty),0),p.AssistantUnitId,ItemID,IsCombined,-1,ProduceDate,ValidDate,
			   CargoID,'','年结存结转而来',0,0,0,0,GoodsNumber,'','','',1,ISNULL(SUM(Qty),0),
			   1,p.baseUnitId,'年结存结转而来',0
		FROM   @Tmp A
		LEFT JOIN dbo.ptype p ON A.PTypeID=p.typeId
		WHERE Stypeid=@STypeID
		GROUP BY ktypeid,
				 ptypeid,
				 CargoID,
				 IsCombined,
				 ItemID,
				 GoodsNumber,
				 ProduceDate,
				 ValidDate,
				 baseUnitId,
				 AssistantUnitId
		SET @RowIndex=@RowIndex+1
	END
---------------------------------仓库出库单---------------------------------------			
END
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YearProcSerialDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_YearProcSerialDeal
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-02-17
-- Description: 年结存处理序列号

--修改人:冯波   代销序列号
-- =============================================

CREATE PROCEDURE Gp_YearProcSerialDeal



AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

	DECLARE	@nCostingMethod	INT
	
	EXEC Gp_GetSubValue 'costing', '',@nCostingMethod output

	---------------------------库存序列号------------------------------------------------
	-- 删除序列号相关数据表
	TRUNCATE TABLE dbo.gp_iniFactPtypeSerial
	TRUNCATE TABLE dbo.Fact_InoutPtypeSerial
	
	UPDATE dbo.gp_FactPtypeSerial
	SET		STypeId = S.STypeID
	FROM    dbo.gp_FactPtypeSerial C,
			Stock S
	WHERE	C.KtypeID = S.typeId

	INSERT INTO dbo.gp_iniFactPtypeSerial
	        ( 
	          Serial ,KtypeID , PtypeID , InKtypeTime ,OutKtypeTime ,
	          State ,Flag ,ETypeID ,GoodsOrder ,
	          GoodsNumber , STypeId , Comment1 ,ItemID ,IsCombined ,
	          CargoID ,ProduceDate ,ValidDate,iniFlag, LendState
	        )
	SELECT 
			  Serial , KtypeID ,PtypeID ,InKtypeTime ,OutKtypeTime ,
	          State ,Flag ,ETypeID ,GoodsOrder ,GoodsNumber ,
	          STypeId ,Comment1 ,ItemID ,IsCombined ,CargoID ,
	          ProduceDate ,ValidDate,1,LendState
	FROM dbo.gp_FactPtypeSerial WHERE State=1 AND Flag=1
	
	TRUNCATE TABLE dbo.gp_FactPtypeSerial	
	
	TRUNCATE TABLE gp_initPTypeSerial	-- 期初序列号库存状况表
	
	EXEC gp_ChangeIniFlag;
	
	--重算当前序列号库中的STypeId
	UPDATE	gp_CruPtypeSerial
	SET		STypeId = S.STypeID
	FROM    gp_CruPtypeSerial C,
			Stock S
	WHERE	C.KtypeID = S.typeId
			AND C.KtypeID <> '10000'
	
	
	--代销已出库的也要转过去,8,9,10,11,16,22,32
	
	
	INSERT INTO gp_initPTypeSerial(Serial,KtypeID,PtypeID,BTypeID1,BtypeID2,InKtypeTime,OutKTypeTime,[User],State,Note,Flag,
	CommissionState,ETypeID,LTypeID,iniFlag,CostPrice,GoodsOrder,GoodsNumber,STypeId,Comment1,Comment2,Comment3,
	ItemID,IsCombined,CargoID,ProduceDate,ValidDate) 
	SELECT	Serial,KtypeID,PtypeID,CASE WHEN State IN (13,32) THEN  DBO.F_GetCommissionBTypeID(Serial,State,140) ELSE  BTypeID1 END,
	CASE WHEN STATE IN (7,9,10,11,16,22,32,14) THEN DBO.F_GetCommissionBTypeID(Serial,State,144) ELSE BtypeID2 END,InKtypeTime,OutKTypeTime,[User],State,Note,Flag,
	CommissionState,ETypeID,LTypeID,iniFlag,CostPrice,GoodsOrder,GoodsNumber,STypeId,Comment1,Comment2,Comment3,
	ItemID,IsCombined,CargoID,ProduceDate,ValidDate 
	FROM gp_CruPTypeSerial
	WHERE	State IN (1, 7, 13, 25,9,10,11,16,22,32,14)			-- 库存中、受托代销库存中、委托代销已发货、维修库存中
	
	TRUNCATE TABLE gp_InOutPTypeSerial	-- 序列号出入库明细表
	

	UPDATE  gp_initPTypeSerial			--修改代销的仓库属性 	
	SET 	KtypeID = '10000',
			InKtypeTime = NULL,
			CargoID=0
	WHERE 	State IN (9,10,11,13,16,32)
	
	UPDATE  gp_initPTypeSerial			--修改代销的仓库属性 	
	SET 	KtypeID = '10000',
			CargoID=0
	WHERE 	State IN (14)

	--处理期初序列号标识	谢吉康  2005-7-21
	UPDATE	Gp_initPTypeSerial
	SET 	iniFlag = 1			
	
	--处理期初序列号和明细关联id
	UPDATE t
	SET    t.id = t1.id
	FROM   gp_initPtypeSerial t
		   JOIN dbo.Ini_GOODSSTOCKS_QTY t1
			 ON t.PtypeID = t1.PTypeID
				AND t.CargoID = t1.CargoID
				AND t.GoodsNumber = t1.GoodsNumber
				AND t.IsCombined = t1.Iscombined
				AND t.ItemID = t1.ItemID
				AND t.KtypeID = t1.KTypeID
				AND t.ProduceDate = t1.ProduceDate
				AND t.ValidDate = t1.ValidDate
				AND
				( 
					@nCostingMethod<>3 OR (@nCostingMethod=3 AND t.CostPrice=t1.GoodsCostPrice)
				)
	WHERE  t.State = 1
	TRUNCATE TABLE gp_CruPTypeSerial

	--------------------------借欠序列号--------------------------------------------------------
	--处理借欠的序列号转期初   谢吉康  2004-02-26
	DELETE FROM GP_InitLendPTypeSerial
	INSERT INTO dbo.gp_initLendPtypeSerial
	        ( Serial ,
	          KtypeID ,
	          PtypeID ,
	          BTypeID1 ,
	          BtypeID2 ,
	          InKtypeTime ,
	          OutKTypeTime ,
	          [User] ,
	          State ,
	          Note ,
	          Flag ,
	          CommissionState ,
	          ETypeID ,
	          LTypeID ,
	          BFlag ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsNumber
	        )
	SELECT Serial ,
	          KtypeID ,
	          PtypeID ,
	          BTypeID1 ,
	          BtypeID2 ,
	          InKtypeTime ,
	          OutKTypeTime ,
	          [User] ,
	          State ,
	          Note ,
	          Flag ,
	          CommissionState ,
	          ETypeID ,
	          LTypeID ,
	          BFlag ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsNumber FROM GP_LendPTypeSerial WHERE State IN (17,18,20)

	UPDATE GP_InitLendPTypeSerial SET State = 17 WHERE Flag = 1
	UPDATE GP_InitLendPTypeSerial SET State = 18 WHERE Flag = 0

	--保持序列号预与期初数量的统一 谢吉康 2004-08-16
	DELETE	FROM GP_initLendPTypeSerial
	WHERE	NOT EXISTS 
			(
				SELECT 	1 
				FROM 	iniGoodsLend 
				WHERE 	GP_initLendPTypeSerial.BTypeID2 = BTypeID 
						AND GP_initLendPTypeSerial.PTypeID = PTypeID 
						AND GP_initLendPTypeSerial.KTypeID = KTypeID 
						AND BorrowQty>0 
						AND GP_initLendPTypeSerial.Flag = 1
						AND Serial=GP_initLendPTypeSerial.Serial
			)	
			AND Flag = 1
	
	DELETE	FROM GP_initLendPTypeSerial 
	WHERE 	NOT EXISTS 
			(
				SELECT 	1
				FROM 	iniGoodsLend 
				WHERE 	GP_initLendPTypeSerial.BTypeID1 = BTypeID 
						AND GP_initLendPTypeSerial.PTypeID = PTypeID 						
						AND GP_initLendPTypeSerial.KTypeID = KTypeID 
						AND LendQty>0 
						AND GP_initLendPTypeSerial.Flag = 0
						AND Serial=GP_initLendPTypeSerial.Serial
			)
			AND Flag = 0	

	UPDATE GP_InitLendPTypeSerial SET BTypeID1 = NULL WHERE State = 17 AND Flag = 1

	UPDATE GP_InitLendPTypeSerial SET BTypeID2 = NULL WHERE State = 18 AND Flag = 0

	DELETE FROM GP_LendPTypeSerial
	
	-----------------------------受托序列号------------------------------------------------
		-- 处理受托期初数量与受托库中序列号数目不一致的情况 - Start
	DECLARE @chvEdition varchar(10)
	SELECT	@chvEdition = SubValue
	FROM	SysData
	WHERE	SubName = 'Edition'

	IF @chvEdition IN ('2','5','7')
	BEGIN
		DECLARE @chvMngSerial varchar(10)
		SELECT	@chvMngSerial = [Value]
		FROM	UserConfig
		WHERE	ConfigName = 'mngSerial'

		IF @chvMngSerial = '1' AND EXISTS(SELECT TOP 1 a.Qty FROM iniCommissionStock a,PType b WHERE a.Type = 144 AND a.Qty <> 0 AND a.PTypeID = b.TypeID AND b.IfSerial = '1' AND b.SonNum = 0 AND b.Deleted = 0)
		BEGIN	
		
			
						
			SELECT	COUNT(Serial) AS numSerialQty,
					PTypeID,
					BTypeID2 AS BTypeID,
					STypeId,
					State,
					CASE State WHEN 7 THEN  KtypeID ELSE '' END AS KTypeID,
					CASE @nCostingMethod WHEN 3 THEN CostPrice ELSE 0 END AS CostPrice,
					GoodsNumber,
					ProduceDate,
					ValidDate,
					ItemID,
					IsCombined,
					CASE State WHEN 7 THEN  CargoID ELSE 0 END AS CargoID
			INTO	#GP_initPTypeSerial
			FROM	GP_initPTypeSerial
			WHERE	--[Flag] = 1 AND 
					State IN (13,32,7,9,10,11,16,14)
			GROUP BY	PTypeID,
						BTypeID2,
						STypeId,
						State,
						CASE State WHEN 7 THEN  KtypeID ELSE '' END,
						CASE @nCostingMethod WHEN 3 THEN CostPrice ELSE 0 END,
						GoodsNumber,
						ProduceDate,
						ValidDate,
						ItemID,
						IsCombined,
						CASE State WHEN 7 THEN  CargoID ELSE 0 END
			HAVING COUNT(Serial)<>0
			
			
			
						
			DELETE FROM iniCommissionStock  
			WHERE	Type = 144 
					AND Qty <> 0
					AND EXISTS
					(
						SELECT	p.TypeID
						FROM	ptype p
						WHERE	p.TypeID=iniCommissionStock.Ptypeid 
								AND p.IfSerial='1'
								AND p.SonNum = 0
								AND p.Deleted = 0
					)
					AND NOT EXISTS	
					(
						SELECT	b.PTypeID
						FROM	#GP_initPTypeSerial b
						WHERE	b.PTypeID=iniCommissionStock.Ptypeid 
								AND b.BTypeID=iniCommissionStock.Btypeid 
								AND b.STypeId=iniCommissionStock.Stypeid
								AND b.State=iniCommissionStock.SerialType
					)
						
			DELETE FROM iniCommissionStock_qty  
			WHERE	Type = 144 
					AND Qty <> 0
					AND EXISTS
					(
						SELECT	p.TypeID
						FROM	ptype p
						WHERE	p.TypeID=iniCommissionStock_qty.Ptypeid 
								AND p.IfSerial='1'
								AND p.SonNum = 0
								AND p.Deleted = 0
					)
					AND NOT EXISTS	
					(
						SELECT	b.PTypeID
						FROM	#GP_initPTypeSerial b
						WHERE	b.PTypeID=iniCommissionStock_qty.Ptypeid 
								AND b.BTypeID=iniCommissionStock_qty.Btypeid 
								AND b.STypeId=iniCommissionStock_qty.Stypeid
								AND b.State=iniCommissionStock_qty.SerialType
					)
					
					
			--SELECT 'bb',*FROM iniCommissionStock	
			
			DECLARE
				@intPriceDot	INT
				
			EXEC	@intPriceDot=Gp_GetDigit 2				
			
			--SELECT '#GP_initPTypeSerial',* FROM #GP_initPTypeSerial
			
			UPDATE	iniCommissionStock_Qty
			SET		Qty = b.numSerialQty
			FROM	iniCommissionStock_Qty a,
					#GP_initPTypeSerial b,
					ptype p
			WHERE	a.Type = 144
					AND a.Qty <>b.numSerialQty
					AND a.Ptypeid=p.typeId
					AND p.IfSerial='1'
					AND p.SonNum = 0
					AND p.Deleted = 0
					AND a.PTypeID = b.PTypeID
					AND a.BTypeID = b.BTypeID
					AND a.Stypeid = b.Stypeid
					AND b.State=a.SerialType
					AND a.KTypeID=b.KtypeID		
					AND a.GoodsCostPrice=b.CostPrice
					AND a.GoodsNumber=b.GoodsNumber
					AND a.ProduceDate=b.ProduceDate
					AND a.ValidDate=b.ValidDate
					AND a.CargoID=b.CargoID
					AND a.ItemID=b.ItemID
					AND a.Iscombined=b.IsCombined
					
			SELECT	COUNT(Serial) AS numSerialQty,
					PTypeID,
					BTypeID2 AS BTypeID,
					STypeId,
					State
			INTO	#GP_initPTypeSerialAll
			FROM	GP_initPTypeSerial
			WHERE	--[Flag] = 1 AND 
					State IN (13,32,7,9,10,11,16,14)
			GROUP BY	PTypeID,
						BTypeID2,
						STypeId,
						State
			HAVING COUNT(Serial)<>0	
			
			UPDATE	iniCommissionStock
			SET		Qty = b.numSerialQty,
					Total=CASE a.Qty WHEN 0 THEN 0 ELSE  b.numSerialQty*(ROUND(a.Total/a.Qty,@intPriceDot)) END
			FROM	iniCommissionStock a,
					#GP_initPTypeSerialAll b,
					ptype p
			WHERE	a.Type = 144
					AND a.Qty <>b.numSerialQty
					AND a.Ptypeid=p.typeId
					AND p.IfSerial='1'
					AND p.SonNum = 0
					AND p.Deleted = 0
					AND a.PTypeID = b.PTypeID
					AND a.BTypeID = b.BTypeID
					AND a.Stypeid = b.Stypeid
					AND b.State=a.SerialType
		END
	END
	-- 处理受托期初数量与受托库中序列号数目不一致的情况 - End

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YsyfToInibill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YsyfToInibill]
GO

--====================================================================================
-----------------功能：将预收预付余额、业务凭证中的应收应付余额转成期初单据 
-----------------作者：韩林						   
-----------------日期：2012-06-15                 
--====================================================================================

CREATE    PROC Gp_YsyfToInibill
(
	@yearendmode			CHAR(1) = '1'	-- 1 - 按余额转期初(arap_total)；0 - 按单据转期初(AccountCredence)
)	

--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #btype_araptotal
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	YSYFTotal DECIMAL(24,10),
	NYSYFTotal DECIMAL(24,10),
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)
DECLARE @startdate DATETIME
SELECT @startdate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth

DECLARE @proinfo INT --A8=2  V3=1
SELECT @proinfo = SubValue FROM sysdata WHERE SubName = 'proinfo'

--预收预付期初单据不能结算，转余额前先删除
DELETE FROM billindex WHERE isini=1 AND BillType IN(189,190)
UPDATE dbo.BillIndex SET ifYearBill=1 WHERE BillType IN (115,116,128,129) AND IsIni=1	--将期初类单据修改年结标志，用于区分结转的期初单据

--预收预付余额转单据
IF EXISTS(SELECT TOP 1 1 FROM dbo.BType_ArApTotal WHERE (YSTotal<>0 OR nYSTotal<>0) OR (YFTotal<>0 OR nYFTotal<>0))
BEGIN	
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeID,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeID,
			EtypeId,
			CID,
			SUM(YSTotal),
			SUM(nYSTotal),
			189,
			'数据结转时预收余额转入',
			0	
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total AS YSTotal,Ntotal AS NYSTotal FROM dbo.ListTable WHERE AtypeId=39
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,YSTotal00,nYSTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				DTypeID,
				EtypeId,
				CID
	HAVING SUM(YSTotal)<>0 
		AND SUM(nYSTotal)<>0


	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			SUM(YFTotal),
			SUM(nYFTotal),
			190,
			'数据结转时预付余额转入',
			0	
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total AS YFTotal,Ntotal AS NYFTotal FROM dbo.ListTable WHERE AtypeId=27
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,YFTotal00,nYFTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				DTypeID,
				EtypeId,
				CID
	HAVING SUM(YFTotal)<>0 
		OR SUM(nYFTotal)<>0


	UPDATE #btype_araptotal
	SET sort=b.sort
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID)sort,
				STypeID,
				BTypeID,
				cid,
				billtype
		FROM	#btype_araptotal
	)b 
	WHERE	#btype_araptotal.billtype=b.billtype
			AND #btype_araptotal.STypeID=b.STypeID
			AND #btype_araptotal.BTypeID=b.BTypeID
			AND #btype_araptotal.CID=b.cid

	INSERT INTO [dbo].[BillIndex] 
	(
		ifYearBill,
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DEALBTYPEID,
		cid,	
		rate,	
		ntotalmoney,
		ntotalinmoney,	
		npreferencemoney,	
		nvipczmoney,	
		atypeid1,
		billproperty,
		ncompletetotal,
		IsIni
	)

	SELECT	
		1,
		0.00,
		CONVERT(DATE, @startdate),
		CASE billtype WHEN 189 THEN 'IniYskBill-' ELSE 'IniYfkBill-' END 
			+ CASE WHEN @proinfo=2 THEN STypeID +'-'ELSE '' END 
			+ CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
		billtype,
		Comment,
		'',
		'',
		BTypeID,
		EtypeId,
		'',
		'',
		'f',
		'',
		0,
		YSYFTotal,
		0,
		0,
		1,
		'',
		1,
		0,
		0,
		'',
		'',
		'',
		'',
		0,
		9999,
		0,
		'',
		'',
		'',
		DTypeId,
		'',
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		STypeID,
		0,
		0,
		0,
		-1,
		'',
		@startdate,
		NULL,
		0,
		'',
		'',
		'',
		'',
		'',
		BTypeID,
		cid,	
		CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nYSYFTotal WHEN 0 THEN 0 ELSE   YSYFTotal/nYSYFTotal END) ELSE dbo.F_RoundExchangeRate(CASE YSYFTotal WHEN 0 THEN 0 ELSE  NYSYFTotal/YSYFTotal END) END,		
		NYSYFTotal,
		0,	
		0,	
		0,	
		(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
		1,
		0,
		1
	FROM	#btype_araptotal b	
	
	DECLARE @atypeid INT=1
	SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
	INSERT INTO dbo.PreBill
			( BillNumberId ,
			  BillType ,
			  Comment ,
			  AtypeId ,
			  total ,
			  Stypeid ,
			  vipcardid ,
			  ntotal,
			  ShowOrder
			)
	SELECT	  BillNumberId ,
			  BillType ,
			  '' ,
			  @atypeid ,
			  totalmoney ,
			  Stypeid ,
			  -1 ,
			  NTotalMoney,
			  ROW_NUMBER() OVER(ORDER BY ID)
	FROM	dbo.BillIndex
	WHERE BillType IN(189,190) AND IsIni=1 AND ifYearBill=1
	
	IF @@ERROR<>0
		RAISERROR('处理预收预付余额失败！',16,1)            
END


TRUNCATE TABLE #btype_araptotal
DECLARE @commet VARCHAR(50)=''
DECLARE @SQL VARCHAR(MAX)=''
--按单据转期初的时候,业务凭证中的应收应付合计转成单据
IF @yearendmode='0' AND EXISTS(	SELECT TOP 1 1 
								FROM AccountCredence a 
								INNER JOIN billindex b ON a.BillNumberID=b.BillNumberId 
								INNER JOIN dbo.Ac_Items ac ON ac.nid=a.TypeATypeID 
								WHERE	ac.UserCode IN('987','2121') 
										AND b.draft=0
										AND b.RedWord=0
								GROUP BY b.Stypeid,b.CID,a.ATypeID,a.TypeATypeID	
								HAVING ISNULL(SUM(a.J_Total-a.D_Total),0)<>0 AND SUM(a.nJ_Total-a.nD_Total)<>0
							 )
BEGIN
	SET @commet='数据结转时业务凭证余额转入'
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	a.ATypeID,
			b.Stypeid,
			b.DTypeId,
			b.etypeid,
			a.CID,
			ABS(SUM(a.J_Total-a.D_Total)),
			ABS(SUM(a.NJ_Total-a.ND_Total)),
			CASE 
				WHEN ac.UserCode='987' AND SUM(a.J_Total-a.D_Total)>0 THEN 116
				WHEN ac.UserCode='987' AND SUM(a.J_Total-a.D_Total)<0 THEN 115
				WHEN ac.UserCode='2121' AND SUM(a.J_Total-a.D_Total)>0 THEN 129
				WHEN ac.UserCode='2121' AND SUM(a.J_Total-a.D_Total)<0 THEN 128
			END,
			'数据结转时业务凭证余额转入',
			0			
	FROM AccountCredence a 
	INNER JOIN billindex b ON a.BillNumberID=b.BillNumberId
	INNER JOIN dbo.Ac_Items ac ON ac.nid=a.TypeATypeID 
	WHERE	ac.UserCode IN('987','2121')
			AND draft=0 
			AND RedWord=0
	GROUP BY a.ATypeID,b.Stypeid,b.DTypeId,b.etypeid,a.CID,ac.UserCode	,CASE 
		WHEN ac.UserCode='987' AND a.J_Total-a.D_Total>0 THEN 116
		WHEN ac.UserCode='987' AND a.J_Total-a.D_Total<0 THEN 115
		WHEN ac.UserCode='2121' AND a.J_Total-a.D_Total>0 THEN 129
		WHEN ac.UserCode='2121' AND a.J_Total-a.D_Total<0 THEN 128
	END
	HAVING SUM(a.J_Total-a.D_Total)<>0 OR SUM(a.nJ_Total-a.nD_Total)<>0
END 	

--优惠券按单结转的时候 将余额转入应收应付增加，减少单
IF @yearendmode=0 AND  EXISTS(SELECT BILLNUMBERID FROM dbo.Coupon_BillIndex WHERE jsState<>2)
BEGIN
	SET @commet='数据结转时应收应付余额转入'
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DtypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			ABS(SUM(ISNULL(ARTotal,0))),
			ABS(SUM(ISNULL(nARTotal,0))),
			CASE WHEN SUM(ARTotal)>0 
					THEN 116
				 ELSE 115
			END,
			'数据结转时应收应付余额转入',
			0			
	FROM	
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,
			   CASE  WHEN BILLTYPE=426  THEN -1* (c.TotalMoney-c.TotalInMoney-c.PreferenceMoney-c.CompleteTotal)
										ELSE (c.TotalMoney-c.TotalInMoney-c.PreferenceMoney-c.CompleteTotal) END   AS ARTotal,
			   CASE  WHEN BILLTYPE=426  THEN -1*(c.NTotalMoney-c.NTotalInMoney-c.NPreferenceMoney-c.NCompleteTotal) 
										ELSE (c.NTotalMoney-c.NTotalInMoney-c.NPreferenceMoney-c.NCompleteTotal)  END  AS NARTotal 
		FROM  Coupon_BillIndex c 
		WHERE  BILLTYPE IN (424,426) AND jsState<>2 AND c.IfCheck='t' AND c.RedWord=0 AND draft=0
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(ARTotal)<>0 OR SUM(nARTotal)<>0
	
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeID,
			EtypeId,
			CID,
			ABS(SUM(APTotal)),
			ABS(SUM(nAPTotal)),
			CASE WHEN SUM(APTotal)>0 
					THEN 128
				 ELSE 129
			END,
			'数据结转时应收应付余额转入',
			0			
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,(c.TotalMoney-c.TotalInMoney-c.PreferenceMoney-c.CompleteTotal) AS APTotal,(c.NTotalMoney-c.NTotalInMoney-c.NPreferenceMoney-c.NCompleteTotal)  AS NAPTotal 
		FROM   Coupon_BillIndex c
		WHERE  BILLTYPE IN (423) AND jsState<>2 AND c.IfCheck='t' AND c.RedWord=0 AND draft=0
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(APTotal)<>0 OR SUM(nAPTotal)<>0
	
    --应付余额为0不结转
 --   DELETE  A
 --   FROM    #btype_araptotal A ,
	--(
	--	SELECT BTypeID,STypeID,CID,ISNULL(SUM(ApTotal),0) AS APTotal,ISNULL(SUM(NApTotal),0) AS NAPTotal FROM (
	--		SELECT Btypeid,stypeid,cid,Total AS APTotal,Ntotal AS NAPTotal FROM dbo.ListTable WHERE AtypeId=35  AND BILLTYPE IN (423)
	--	) C
	--	GROUP BY BTypeID,STypeID,CID
	--) B
 --   WHERE   A.BillType IN ( 128, 129 )
 --           AND A.STypeID = B.STypeID
 --           AND A.BTypeID = B.BTypeID
 --           AND A.CID=B.CID
 --           AND B.APTotal = 0
 --           AND B.nAPTotal = 0 
    
    --应付余额为0不结转
   -- DELETE  A
   -- FROM    #btype_araptotal A ,
   --         (
			--	SELECT STypeID,BTypeID,CID,ISNULL(SUM(ARTotal),0) AS ARTotal,ISNULL(SUM(NARTotal),0) AS NArTotal FROM(
			--		SELECT Btypeid,stypeid,cid,Total AS ARTotal,Ntotal AS NARTotal FROM dbo.ListTable WHERE AtypeId=33 AND BILLTYPE IN (424,426)
			--	) C GROUP BY BTypeID,STypeID,CID
			--)B
   -- WHERE   A.BillType IN ( 115, 116 )
   --         AND A.STypeID = B.STypeID
   --         AND A.BTypeID = B.BTypeID
   --         AND A.CID=B.CID
   --         AND B.ARTotal = 0
   --         AND B.NARTotal = 0 
END

--按余额转入期初，将btype_araptotal	应收应付余额转入期初单据
IF @yearendmode='1' AND EXISTS(SELECT TOP 1 1 FROM dbo.BType_ArApTotal WHERE (ARTotal<>0 AND nARTotal<>0) OR (APTotal<>0 AND nAPTotal<>0)) 
BEGIN
	DELETE FROM dbo.BillIndex WHERE IsIni=1 AND BillType NOT IN (190,189,400,401,402,403)
	SET @commet='数据结转时应收应付余额转入'
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DtypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			ABS(SUM(ARTotal)),
			ABS(SUM(nARTotal)),
			CASE WHEN SUM(ARTotal)>0 
					THEN 116
				 ELSE 115
			END,
			'数据结转时应收应付余额转入',
			0			
	FROM	--BType_ArApTotal 
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total AS ARTotal,Ntotal AS NARTotal FROM dbo.ListTable WHERE AtypeId=33
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,ARTotal00,nARTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(ARTotal)<>0 OR SUM(nARTotal)<>0
	
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeID,
			EtypeId,
			CID,
			ABS(SUM(APTotal)),
			ABS(SUM(nAPTotal)),
			CASE WHEN SUM(APTotal)>0 
					THEN 128
				 ELSE 129
			END,
			'数据结转时应收应付余额转入',
			0			
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total AS APTotal,Ntotal AS NAPTotal FROM dbo.ListTable WHERE AtypeId=35
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,APTotal00,nAPTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(APTotal)<>0 OR SUM(nAPTotal)<>0
	
    --应付余额为0不结转
    DELETE  A
    FROM    #btype_araptotal A ,
	(
		SELECT BTypeID,STypeID,CID,ISNULL(SUM(ApTotal),0) AS APTotal,ISNULL(SUM(NApTotal),0) AS NAPTotal FROM (
			SELECT Btypeid,stypeid,cid,Total AS APTotal,Ntotal AS NAPTotal FROM dbo.ListTable WHERE AtypeId=35
			UNION ALL
			SELECT Btypeid,stypeid,cid,APTotal00,nAPTotal00 FROM IniBType_ArApTotal 
		) C
		GROUP BY BTypeID,STypeID,CID
	) B
    WHERE   A.BillType IN ( 128, 129 )
            AND A.STypeID = B.STypeID
            AND A.BTypeID = B.BTypeID
            AND A.CID=B.CID
            AND B.APTotal = 0
            AND B.nAPTotal = 0 
    
    --应付余额为0不结转
    DELETE  A
    FROM    #btype_araptotal A ,
            (
				SELECT STypeID,BTypeID,CID,ISNULL(SUM(ARTotal),0) AS ARTotal,ISNULL(SUM(NARTotal),0) AS NArTotal FROM(
					SELECT Btypeid,stypeid,cid,Total AS ARTotal,Ntotal AS NARTotal FROM dbo.ListTable WHERE AtypeId=33
					UNION ALL
					SELECT Btypeid,stypeid,cid,ARTotal00,nARTotal00 FROM IniBType_ArApTotal 
				) C GROUP BY BTypeID,STypeID,CID
			)B
    WHERE   A.BillType IN ( 115, 116 )
            AND A.STypeID = B.STypeID
            AND A.BTypeID = B.BTypeID
            AND A.CID=B.CID
            AND B.ARTotal = 0
            AND B.NARTotal = 0 
END



IF EXISTS(SELECT 1 FROM #btype_araptotal) 
BEGIN
	DECLARE @newid varchar(9)
	SET @newid=LEFT(NEWID(),9)   --避免同一天连续年节产生的期初单据编号相等
	
	INSERT INTO [dbo].[BillIndex] 
	(	
		[IfYearBill],
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DEALBTYPEID,
		cid,	
		rate,	
		ntotalmoney,
		ntotalinmoney,	
		npreferencemoney,	
		nvipczmoney,	
		atypeid1,
		billproperty,
		ncompletetotal,
		IsIni
	)

	SELECT	
		1,
		0.00,
		CONVERT(DATE, @startdate),
		CASE billtype 
			WHEN '116' THEN 'IniYzBill-' 
			WHEN '115' THEN 'IniYjBill-' 
			WHEN '128' THEN 'IniFzBill-'
			WHEN '129' THEN 'IniFjBill-'
		END + @newid +
		CASE WHEN @proinfo=2 THEN STypeID + '-' ELSE '' END + CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
		billtype,
		Comment,
		'',
		'',
		'',
		etypeid,
		'',
		'',
		'f',
		'',
		0,
		YSYFTotal,
		0,
		0,
		1,
		'',
		0,
		0,
		0,
		'',
		'',
		'',
		'',
		0,
		9999,
		0,
		'',
		'',
		'',
		dtypeid,
		'',
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		STypeID,
		0,
		0,
		0,
		-1,
		'',
		@startdate,
		NULL,
		0,
		'',
		'',
		'',
		'',
		'',
		'',
		cid,	
		CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nYSYFTotal WHEN 0 THEN 0 ELSE   YSYFTotal/nYSYFTotal END) ELSE dbo.F_RoundExchangeRate(CASE YSYFTotal WHEN 0 THEN 0 ELSE  NYSYFTotal/YSYFTotal END) END,	
		NYSYFTotal,
		0,	
		0,	
		0,	
		(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
		1,
		0,
		1
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY stypeid,DTypeId,etypeid,cid) sort,
				Stypeid,	
				DTypeId,
				etypeid,
				CID,
				BillType,
				Comment,
				SUM(YSYFTotal) AS YSYFTotal,
				SUM(NYSYFTotal) AS NYSYFTotal
		FROM #btype_araptotal
		GROUP BY Stypeid,DTypeId,etypeid,CID,BillType,Comment
	)b	


	INSERT INTO dbo.AdDebtBill
	( 
			  BillNumberId ,
	          Comment ,
	          BtypeId ,
	          total ,
	          CompleteTotal ,
	          Stypeid ,
	          NTotal ,
	          NCompleteTotal,
	          ShowOrder,
	          AlertDay
	)
	SELECT	  b.BillNumberId,
			  '',
			  ba.btypeid,
			  YSYFTotal,
			  0,
			  ba.stypeid,
			  nYSYFTotal,
			  0,
			  ROW_NUMBER() OVER(ORDER BY b.ID),
			  CASE
				WHEN b.BillType IN (115,116) THEN ISNULL(bt.ARLimitTime,9999)
				WHEN b.BillType IN (128,129) THEN ISNULL(bt.paymentLTime,9999)
				ELSE 9999
			  END
	FROM	#btype_araptotal ba
	INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid
	INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
	WHERE	b.BillType IN (116,115,128,129)
			AND b.IsIni=1
			AND ifYearBill=1
			AND b.Comment=ba.comment
			
			
	IF @@ERROR<>0
		RAISERROR('处理应收应付余额失败！',16,1)       
END



DROP TABLE #btype_araptotal
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_YsyfToInibill_DateTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_YsyfToInibill_DateTime]
GO

--====================================================================================
-----------------功能：将预收预付余额、业务凭证中的应收应付余额转成期初单据 
-----------------作者：韩林						   
-----------------日期：2012-06-15                 
--====================================================================================

CREATE    PROC Gp_YsyfToInibill_DateTime
(
	@yearendmode			CHAR(1) = '1',	-- 1 - 按余额转期初(arap_total)；0 - 按单据转期初(AccountCredence)
	@yearendDatetime        VARCHAR(20)			--   -年结存的日期		
)	

--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #btype_araptotal
(
	BTypeID varchar (50) NOT NULL,
	STypeID varchar (50) NOT NULL,
	DTypeId VARCHAR(50) NOT NULL DEFAULT(''),
	EtypeId VARCHAR(50) NOT NULL DEFAULT(''),
	CID	INT null,
	YSYFTotal DECIMAL(24,10),
	NYSYFTotal DECIMAL(24,10),
	billtype VARCHAR(50),
	Comment VARCHAR(50),
	sort int
)

DECLARE @newFPeriod	INT,
		@newFYear	INT,
		@BeginDate  DATETIME

SELECT TOP 1 
	@newFPeriod=FPeriod,
	@newFYear=FYear 
FROM dbo.Ac_Period 
WHERE FBegin = @yearendDatetime

DECLARE @startdate DATETIME
SET @startdate=DATEADD(day,-1,@yearendDatetime)
--SELECT @startdate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=@newFPeriod AND FYear=@newFYear



DECLARE @proinfo INT --A8=2  V3=1
SELECT @proinfo = SubValue FROM sysdata WHERE SubName = 'proinfo'

--预收预付期初单据不能结算，转余额前先删除
DELETE FROM billindex WHERE isini=1 AND BillType IN(189,190)
UPDATE dbo.BillIndex SET ifYearBill=1 WHERE BillType IN (115,116,128,129) AND (IsIni=1 or billdate<@yearendDatetime)	--将期初类单据修改年结标志，用于区分结转的期初单据

---------------------------------------------------预收预付余额转单据 开始----------------------------------------------------------------------------------------------------

--预收 余额不为0 的数据插入临时表
INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeID,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment,
			sort
	)
SELECT	BTypeID,
	STypeID,
	DTypeID,
	EtypeId,
	CID,
	SUM(YSTotal),
	SUM(nYSTotal),
	189,
	'数据结转时预收余额转入',
	0	
FROM
 (
	SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total AS YSTotal,Ntotal AS NYSTotal FROM dbo.ListTable WHERE AtypeId=39 and billdate <@yearendDatetime
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,YSTotal00,nYSTotal00 FROM IniBType_ArApTotal 
 ) a
GROUP BY	BTypeID,
		STypeID,
		DTypeID,
		EtypeId,
		CID
HAVING SUM(YSTotal)<>0 AND SUM(nYSTotal)<>0 

--预付余额不为0的数据插入临时表 
INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeID,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment,
			sort
	)
SELECT	BTypeID,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			SUM(YFTotal),
			SUM(nYFTotal),
			190,
			'数据结转时预付余额转入',
			0	
FROM	--BType_ArApTotal
(
	SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total AS YFTotal,Ntotal AS NYFTotal FROM dbo.ListTable WHERE AtypeId=27 and billdate <@yearendDatetime
	UNION ALL
	SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,YFTotal00,nYFTotal00 FROM IniBType_ArApTotal 
) a
GROUP BY	BTypeID,
		STypeID,
		DTypeID,
		EtypeId,
		CID
HAVING SUM(YFTotal)<>0 
	OR SUM(nYFTotal)<>0

UPDATE #btype_araptotal
SET sort=b.sort
FROM
(
	SELECT	RANK() OVER
			(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID)sort,
			STypeID,
			BTypeID,
			cid,
			billtype
	FROM	#btype_araptotal
)b 
WHERE	#btype_araptotal.billtype=b.billtype
		AND #btype_araptotal.STypeID=b.STypeID
		AND #btype_araptotal.BTypeID=b.BTypeID
		AND #btype_araptotal.CID=b.cid
IF EXISTS(SELECT 1 FROM #btype_araptotal)
BEGIN	
	INSERT INTO [dbo].[BillIndex] 
	(
		ifYearBill,
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DEALBTYPEID,
		cid,	
		rate,	
		ntotalmoney,
		ntotalinmoney,	
		npreferencemoney,	
		nvipczmoney,	
		atypeid1,
		billproperty,
		ncompletetotal,
		IsIni
	)

	SELECT	
		1,
		0.00,
		CONVERT(DATE, @startdate),
		CASE billtype WHEN 189 THEN 'IniYskBill-' ELSE 'IniYfkBill-' END 
			+ CASE WHEN @proinfo=2 THEN STypeID +'-'ELSE '' END 
			+ CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
		billtype,
		Comment,
		'',
		'',
		BTypeID,
		EtypeId,
		'',
		'',
		'f',
		'',
		0,
		YSYFTotal,
		0,
		0,
		1,
		'',
		1,
		0,
		0,
		'',
		'',
		'',
		'',
		0,
		9999,
		0,
		'',
		'',
		'',
		DTypeId,
		'',
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		STypeID,
		0,
		0,
		0,
		-1,
		'',
		@startdate,
		NULL,
		0,
		'',
		'',
		'',
		'',
		'',
		BTypeID,
		cid,	
		CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nYSYFTotal WHEN 0 THEN 0 ELSE   YSYFTotal/nYSYFTotal END) ELSE dbo.F_RoundExchangeRate(CASE YSYFTotal WHEN 0 THEN 0 ELSE  NYSYFTotal/YSYFTotal END) END,		
		NYSYFTotal,
		0,	
		0,	
		0,	
		(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
		1,
		0,
		1
	FROM	#btype_araptotal b	
	
	DECLARE @atypeid INT=1
	SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
	INSERT INTO dbo.PreBill
			( BillNumberId ,
			  BillType ,
			  Comment ,
			  AtypeId ,
			  total ,
			  Stypeid ,
			  vipcardid ,
			  ntotal,
			  ShowOrder
			)
	SELECT	  BillNumberId ,
			  BillType ,
			  '' ,
			  @atypeid ,
			  totalmoney ,
			  Stypeid ,
			  -1 ,
			  NTotalMoney,
			  ROW_NUMBER() OVER(ORDER BY ID)
	FROM	dbo.BillIndex
	WHERE BillType IN(189,190) AND IsIni=1 AND ifYearBill=1
	
	IF @@ERROR<>0
		RAISERROR('处理预收预付余额失败！',16,1)            
END

TRUNCATE TABLE #btype_araptotal
---------------------------------------------------预收预付余额转单据 结束----------------------------------------------------------------------------------------------------

DECLARE @commet VARCHAR(50)=''
DECLARE @SQL VARCHAR(MAX)=''
--按单据转期初的时候,业务凭证中的应收应付合计转成单据    逻辑保留  暂时不删
IF @yearendmode='0' AND EXISTS(	SELECT TOP 1 1 
								FROM AccountCredence a 
								INNER JOIN billindex b ON a.BillNumberID=b.BillNumberId 
								INNER JOIN dbo.Ac_Items ac ON ac.nid=a.TypeATypeID 
								WHERE	ac.UserCode IN('987','2121') 
										AND b.draft=0
										AND b.RedWord=0
								GROUP BY b.Stypeid,b.CID,a.ATypeID,a.TypeATypeID	
								HAVING ISNULL(SUM(a.J_Total-a.D_Total),0)<>0 AND SUM(a.nJ_Total-a.nD_Total)<>0
							 )
BEGIN
	SET @commet='数据结转时业务凭证余额转入'
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	a.ATypeID,
			b.Stypeid,
			b.DTypeId,
			b.etypeid,
			a.CID,
			ABS(SUM(a.J_Total-a.D_Total)),
			ABS(SUM(a.NJ_Total-a.ND_Total)),
			CASE 
				WHEN ac.UserCode='987' AND SUM(a.J_Total-a.D_Total)>0 THEN 116
				WHEN ac.UserCode='987' AND SUM(a.J_Total-a.D_Total)<0 THEN 115
				WHEN ac.UserCode='2121' AND SUM(a.J_Total-a.D_Total)>0 THEN 129
				WHEN ac.UserCode='2121' AND SUM(a.J_Total-a.D_Total)<0 THEN 128
			END,
			'数据结转时业务凭证余额转入',
			0			
	FROM AccountCredence a 
	INNER JOIN billindex b ON a.BillNumberID=b.BillNumberId
	INNER JOIN dbo.Ac_Items ac ON ac.nid=a.TypeATypeID 
	WHERE	ac.UserCode IN('987','2121')
			AND draft=0 
			AND RedWord=0
	GROUP BY a.ATypeID,b.Stypeid,b.DTypeId,b.etypeid,a.CID,ac.UserCode	,CASE 
		WHEN ac.UserCode='987' AND a.J_Total-a.D_Total>0 THEN 116
		WHEN ac.UserCode='987' AND a.J_Total-a.D_Total<0 THEN 115
		WHEN ac.UserCode='2121' AND a.J_Total-a.D_Total>0 THEN 129
		WHEN ac.UserCode='2121' AND a.J_Total-a.D_Total<0 THEN 128
	END
	HAVING SUM(a.J_Total-a.D_Total)<>0 OR SUM(a.nJ_Total-a.nD_Total)<>0
END 	

--优惠券按单结转的时候 将余额转入应收应付增加，减少单 逻辑保留  暂时不删
IF @yearendmode=0 AND  EXISTS(SELECT BILLNUMBERID FROM dbo.Coupon_BillIndex WHERE jsState<>2)
BEGIN
	SET @commet='数据结转时应收应付余额转入'
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DtypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			ABS(SUM(ISNULL(ARTotal,0))),
			ABS(SUM(ISNULL(nARTotal,0))),
			CASE WHEN SUM(ARTotal)>0 
					THEN 116
				 ELSE 115
			END,
			'数据结转时应收应付余额转入',
			0			
	FROM	
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,
			   CASE  WHEN BILLTYPE=426  THEN -1* (c.TotalMoney-c.TotalInMoney-c.PreferenceMoney-c.CompleteTotal)
										ELSE (c.TotalMoney-c.TotalInMoney-c.PreferenceMoney-c.CompleteTotal) END   AS ARTotal,
			   CASE  WHEN BILLTYPE=426  THEN -1*(c.NTotalMoney-c.NTotalInMoney-c.NPreferenceMoney-c.NCompleteTotal) 
										ELSE (c.NTotalMoney-c.NTotalInMoney-c.NPreferenceMoney-c.NCompleteTotal)  END  AS NARTotal 
		FROM  Coupon_BillIndex c 
		WHERE  BILLTYPE IN (424,426) AND jsState<>2 AND c.IfCheck='t' AND c.RedWord=0 AND draft=0
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(ARTotal)<>0 OR SUM(nARTotal)<>0
	
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeID,
			EtypeId,
			CID,
			ABS(SUM(APTotal)),
			ABS(SUM(nAPTotal)),
			CASE WHEN SUM(APTotal)>0 
					THEN 128
				 ELSE 129
			END,
			'数据结转时应收应付余额转入',
			0			
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,(c.TotalMoney-c.TotalInMoney-c.PreferenceMoney-c.CompleteTotal) AS APTotal,(c.NTotalMoney-c.NTotalInMoney-c.NPreferenceMoney-c.NCompleteTotal)  AS NAPTotal 
		FROM   Coupon_BillIndex c
		WHERE  BILLTYPE IN (423) AND jsState<>2 AND c.IfCheck='t' AND c.RedWord=0 AND draft=0
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(APTotal)<>0 OR SUM(nAPTotal)<>0
	
END

-----------------------------------------------------按余额转入期初，将btype_araptotal	应收应付余额转入期初单据 开始-------------------------------------------------------------------------------
IF @yearendmode='1'
BEGIN
	SET @commet='数据结转时应收应付余额转入'
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DtypeId,
			EtypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeId,
			ETypeId,
			CID,
			ABS(SUM(ARTotal)),
			ABS(SUM(nARTotal)),
			CASE WHEN SUM(ARTotal)>0 
					THEN 116
				 ELSE 115
			END,
			'数据结转时应收应付余额转入',
			0			
	FROM	--BType_ArApTotal 
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total AS ARTotal,Ntotal AS NARTotal FROM dbo.ListTable WHERE AtypeId=33 AND billdate <@yearendDatetime
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,ARTotal00,nARTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(ARTotal)<>0 OR SUM(nARTotal)<>0
	
	INSERT INTO #btype_araptotal
	( 
			BTypeID ,
			STypeID ,
			DTypeId,
			ETypeId,
			CID ,
			YSYFTotal ,
			NYSYFTotal ,
			billtype ,
			Comment ,
			sort
	)
	SELECT	BTypeID,
			STypeID,
			DTypeID,
			EtypeId,
			CID,
			ABS(SUM(APTotal)),
			ABS(SUM(nAPTotal)),
			CASE WHEN SUM(APTotal)>0 
					THEN 128
				 ELSE 129
			END,
			'数据结转时应收应付余额转入',
			0			
	FROM	--BType_ArApTotal
	(
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,Total AS APTotal,Ntotal AS NAPTotal FROM dbo.ListTable WHERE AtypeId=35 AND billdate <@yearendDatetime
		UNION ALL
		SELECT Btypeid,stypeid,DTypeID,EtypeId,cid,APTotal00,nAPTotal00 FROM IniBType_ArApTotal 
	) a
	GROUP BY	BTypeID,
				STypeID,
				DtypeId,
				ETypeId,
				CID
	HAVING SUM(APTotal)<>0 OR SUM(nAPTotal)<>0
	
    --应付余额为0不结转
    DELETE  A
    FROM    #btype_araptotal A ,
	(
		SELECT BTypeID,STypeID,CID,ISNULL(SUM(ApTotal),0) AS APTotal,ISNULL(SUM(NApTotal),0) AS NAPTotal FROM (
			SELECT Btypeid,stypeid,cid,Total AS APTotal,Ntotal AS NAPTotal FROM dbo.ListTable WHERE AtypeId=35 AND billdate <@yearendDatetime
			UNION ALL
			SELECT Btypeid,stypeid,cid,APTotal00,nAPTotal00 FROM IniBType_ArApTotal 
		) C
		GROUP BY BTypeID,STypeID,CID
	) B
    WHERE   A.BillType IN ( 128, 129 )
            AND A.STypeID = B.STypeID
            AND A.BTypeID = B.BTypeID
            AND A.CID=B.CID
            AND B.APTotal = 0
            AND B.nAPTotal = 0 
    
    --应付余额为0不结转
    DELETE  A
    FROM    #btype_araptotal A ,
            (
				SELECT STypeID,BTypeID,CID,ISNULL(SUM(ARTotal),0) AS ARTotal,ISNULL(SUM(NARTotal),0) AS NArTotal FROM(
					SELECT Btypeid,stypeid,cid,Total AS ARTotal,Ntotal AS NARTotal FROM dbo.ListTable WHERE AtypeId=33 AND billdate <@yearendDatetime
					UNION ALL
					SELECT Btypeid,stypeid,cid,ARTotal00,nARTotal00 FROM IniBType_ArApTotal 
				) C GROUP BY BTypeID,STypeID,CID
			)B
    WHERE   A.BillType IN ( 115, 116 )
            AND A.STypeID = B.STypeID
            AND A.BTypeID = B.BTypeID
            AND A.CID=B.CID
            AND B.ARTotal = 0
            AND B.NARTotal = 0 
            
            
    IF EXISTS (SELECT 1 FROM #btype_araptotal)
    BEGIN
		DELETE FROM dbo.BillIndex WHERE IsIni=1 AND BillType NOT IN (190,189,400,401,402,403) 
    END 
END

-----------------------------------------------------按余额转入期初，将btype_araptotal	应收应付余额转入期初单据 结束-------------------------------------------------------------------------------

IF EXISTS(SELECT 1 FROM #btype_araptotal) 
BEGIN
	DECLARE @newid varchar(9)
	SET @newid=LEFT(NEWID(),9)   --避免同一天连续年节产生的期初单据编号相等
	
	INSERT INTO [dbo].[BillIndex] 
	(	
		[IfYearBill],
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DEALBTYPEID,
		cid,	
		rate,	
		ntotalmoney,
		ntotalinmoney,	
		npreferencemoney,	
		nvipczmoney,	
		atypeid1,
		billproperty,
		ncompletetotal,
		IsIni
	)

	SELECT	
		1,
		0.00,
		CONVERT(DATE, @startdate),
		CASE billtype 
			WHEN '116' THEN 'IniYzBill-' 
			WHEN '115' THEN 'IniYjBill-' 
			WHEN '128' THEN 'IniFzBill-'
			WHEN '129' THEN 'IniFjBill-'
		END + @newid +
		CASE WHEN @proinfo=2 THEN STypeID + '-' ELSE '' END + CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
		billtype,
		Comment,
		'',
		'',
		'',
		etypeid,
		'',
		'',
		'f',
		'',
		0,
		YSYFTotal,
		0,
		0,
		1,
		'',
		0,
		0,
		0,
		'',
		'',
		'',
		'',
		0,
		9999,
		0,
		'',
		'',
		'',
		dtypeid,
		'',
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		STypeID,
		0,
		0,
		0,
		-1,
		'',
		@startdate,
		NULL,
		0,
		'',
		'',
		'',
		'',
		'',
		'',
		cid,	
		CASE(SELECT BasisType from dbo.Ac_Currency WHERE CId=b.cid) WHEN 0 THEN dbo.F_RoundExchangeRate(CASE nYSYFTotal WHEN 0 THEN 0 ELSE   YSYFTotal/nYSYFTotal END) ELSE dbo.F_RoundExchangeRate(CASE YSYFTotal WHEN 0 THEN 0 ELSE  NYSYFTotal/YSYFTotal END) END,	
		NYSYFTotal,
		0,	
		0,	
		0,	
		(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
		1,
		0,
		1
	FROM
	(
		SELECT	RANK() OVER
				(PARTITION BY billtype ORDER BY stypeid,DTypeId,etypeid,cid) sort,
				Stypeid,	
				DTypeId,
				etypeid,
				CID,
				BillType,
				Comment,
				SUM(YSYFTotal) AS YSYFTotal,
				SUM(NYSYFTotal) AS NYSYFTotal
		FROM #btype_araptotal
		GROUP BY Stypeid,DTypeId,etypeid,CID,BillType,Comment
	)b	


	INSERT INTO dbo.AdDebtBill
	( 
			  BillNumberId ,
	          Comment ,
	          BtypeId ,
	          total ,
	          CompleteTotal ,
	          Stypeid ,
	          NTotal ,
	          NCompleteTotal,
	          ShowOrder,
	          AlertDay
	)
	SELECT	  b.BillNumberId,
			  '',
			  ba.btypeid,
			  YSYFTotal,
			  0,
			  ba.stypeid,
			  nYSYFTotal,
			  0,
			  ROW_NUMBER() OVER(ORDER BY b.ID),
			  CASE
				WHEN b.BillType IN (115,116) THEN ISNULL(bt.ARLimitTime,9999)
				WHEN b.BillType IN (128,129) THEN ISNULL(bt.paymentLTime,9999)
				ELSE 9999
			  END
	FROM	#btype_araptotal ba
	INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType AND ba.dtypeid=b.DTypeId AND ba.etypeid=b.etypeid
	INNER JOIN dbo.btype bt ON ba.btypeid=bt.typeId
	WHERE	b.BillType IN (116,115,128,129)
			AND b.IsIni=1
			AND ifYearBill=1
			AND b.Comment=ba.comment
			
			
	IF @@ERROR<>0
		RAISERROR('处理应收应付余额失败！',16,1)       
END



DROP TABLE #btype_araptotal
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Zc_AuditingInOut]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Zc_AuditingInOut]
GO


-- ========================================================================
-- 功能说明：	红冲单据 出入库库存相关
-- 作    者：	卢  春
-- 最后修改：	2004-01-07
-- ========================================================================
CREATE                  PROCEDURE Gp_Zc_AuditingInOut 
(
	@nBillID			numeric(10,0),			-- 1. 单据编号 ID 值
	@nBillType			INT,
	@Reverse			bit,					-- 2. 是否相反
	@strPTypeIDOutPut	varchar(50) output,		-- 3. 返回出错商品 ID 值
	@ModifyAuditBill	int=0					-- 0表示正常单据，1表示修改过账后单据
)
--@encode$--
AS
	SET NOCOUNT ON
	-- ********	Costing Method	********
	-- 定义成本核算方法变量 并 赋值
	DECLARE @AVERAGE	smallint	-- 加权移动平均
	DECLARE @FIFO		smallint	-- 先进先出
	DECLARE @LIFO		smallint	-- 后进先出
	DECLARE @HAND		smallint	-- 手工指定

	SET @AVERAGE	= 0
	SET @FIFO		= 1
	SET @LIFO		= 2
	SET @HAND		= 3
	---------------------

	DECLARE @nCostingMethod		smallint		-- 成本算法
	DECLARE @tBillDate			datetime		-- 单据日期
	DECLARE @dTotalMoney		 NUMERIC(24, 10) 	-- 单据金额
	DECLARE @dTotalInMoney		 NUMERIC(24, 10) 	-- 单据实收金额
	DECLARE @dTotalTemp			 NUMERIC(24, 10) 
	DECLARE @dCostTotalTemp		 NUMERIC(24, 10) 
	DECLARE @szATypeID			varchar(50)
	DECLARE @szPTypeID			varchar(50)
	DECLARE @szBTypeID			varchar(50)
	DECLARE @szETypeID			varchar(50)
	DECLARE @szStockID			varchar(50)
	DECLARE @szStockID2			varchar(50)
	DECLARE @szATypeIDTemp		varchar(50)
	DECLARE @szPTypeIDTemp		varchar(50)
	DECLARE @szBTypeIDTemp		varchar(50)
	DECLARE @szETypeIDTemp		varchar(50)
	DECLARE @szKTypeIDTemp		varchar(50)
	DECLARE @szSTypeIDTemp		varchar(50)
	DECLARE @szIfCheck			char(1)
	DECLARE @nPeriod			int
	DECLARE @szJobNumber		varchar(20)
	DECLARE @OutFactoryDate		datetime
	DECLARE @dPrice				 NUMERIC(24, 10) 
	DECLARE @dTotal				 NUMERIC(24, 10) 
	DECLARE @dQty				 NUMERIC(24, 10) 
	DECLARE @dCostPrice			 NUMERIC(24, 10) 
	DECLARE @dCostTotal			 NUMERIC(24, 10) 
	DECLARE @nGoodsNo			int
	DECLARE @dCostPriceOut		 NUMERIC(24, 10) 
	DECLARE @dTemp				 NUMERIC(24, 10) 
	DECLARE @dPriceTemp			 NUMERIC(24, 10) 
	DECLARE @nRet				smallint
	DECLARE @DXTaxTotalTemp		 NUMERIC(24, 10) 
	DECLARE @DXTotaltemp		 NUMERIC(24, 10) 
	DECLARE @GoodsNumber		varchar(100)
	DECLARE @ProduceDate		varchar(50)
	DECLARE @ValidDate			varchar(50)
	DECLARE @GoodsBTypeID		varchar(50)
	DECLARE @GoodsCostPrice		 NUMERIC(24, 10) 
	DECLARE @HandZeroCost		varchar(50)
	
	DECLARE
			@intItemID			INT,
			@intIsCombined		TINYINT,
			@dNQty				 NUMERIC(24, 10) ,
			@intAdPriceType		INT
	
	SELECT @intAdPriceType=0
			
	SELECT @szBTypeID=BTypeID,@intAdPriceType=CASE BillType WHEN 57 THEN AdPriceType ELSE 0 END
	FROM BillIndex
	WHERE BillNumberId=@nBillID AND BillType=@nBillType
	


	

	SET @dTotalTemp = 0
	-- 开始事务
	-- begin tran --AuditingTrans 
	-- 得到成本核算法
	EXEC Gp_GetSubValue 'costing','', @nCostingMethod output
	DECLARE Auditing_Cursor CURSOR SCROLL FOR
		SELECT	
				ATypeID,
				PTypeID,
				BTypeID,
				ETypeID,
				KTypeID,
				STypeID,
				Qty,
				Price,
				Total,
				CostPrice,
				CostTotal,
				JobNumber,
				GoodsNo,
				OutFactoryDate,
				GoodsNumber,
				ProduceDate,
				ValidDate,
				GoodsBTypeID,
				GoodsCostPrice,
				HandZeroCost
		FROM	InOutStockTable
		WHERE	BillNumberID = @nBillID AND @intAdPriceType=0  AND BillType=@nBillType
		AND IsService=0
				ORDER BY
					CASE BillType
					WHEN 57 THEN BillNumberID
					ELSE Total
					END

	OPEN Auditing_Cursor
	FETCH NEXT FROM Auditing_Cursor INTO	
											@szATypeIDTemp,
											@szPTypeIDtemp,
											@szBTypeIDTemp,
											@szETypeIDTemp,
											@szKTypeIDTemp,
											@szSTypeIDTemp,
											@dQty,
											@dPrice,
											@dTotal,
											@dCostPrice,
											@dCostTotal,
											@szJobNumber,
											@nGoodsNo,
											@OutFactoryDate,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsBTypeID,
											@GoodsCostPrice,
											@HandZeroCost
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @Reverse = 1
		BEGIN
			SET @dQty = -@dQty
			SET @dTotal = -@dTotal
			SET @dCostTotal = -@dCostTotal
		END

		IF @szKTypeIDTemp = '10000'		-- 代销单据
		BEGIN
			SET @DXTaxTotalTemp = @dTotal
			SET @DXTotalTemp = @dTotal

			EXEC @nRet = Gp_ModifyDbf_DX	@nBillType,
											@nCostingMethod,
											@szATypeIDTemp,
											@szPTypeIDTemp,
											@szBTypeID,

											@szETypeIDTemp,
											'10000',
											@szSTypeIDTemp,
											'',
											@dQty,
											@dCostTotal,
											@DXTaxTotalTemp,
											@DXTotalTemp,
											@szJobNumber,
											@nGoodsNo,
											@dCostPriceOut output,
											NULL,
											@dCostPrice
		END
		ELSE IF @nBillType=57 AND @nCostingMethod = 0
		BEGIN
				EXEC Gp_AuditingAdPriceBill     @nCostingMethod,
												@szATypeIDTemp,
												@szPTypeIDTemp,
												@szBTypeIDTemp,
												@szETypeIDTemp,
												@szKTypeIDTemp,
												@szSTypeIDTemp,
												@dQty,
												@dCostTotal,
												@nGoodsNo,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsCostPrice,
												@nBillID
		END
		ELSE
		BEGIN
			EXEC @nRet = Gp_ModifyDbf	@nBillType,				-- 单据类型
										@nCostingMethod,		-- 成本算法
										@szATypeIDTemp,			-- 会计科目 ID
										@szPTypeIDTemp,			-- 库存商品 ID
										@szBTypeIDTemp,			-- 往来单位 ID
										@szETypeIDTemp,			-- 经手人 ID
										@szKTypeIDTemp,			-- 仓库 ID
										@szSTypeIDTemp,
										'',
										@dQty,					-- 商品数量
										@dCostTotal,			-- 成本金额
										0,
										0,
										@szJobNumber,
										--@nGoodsNo,
										@nBillID,
										@GoodsNumber,
										@ProduceDate,
										@ValidDate,
										@GoodsCostPrice,
										@HandZeroCost,
										@dCostPriceOut output,
										@ModifyAuditBill,
										NULL,
										@dCostPrice
		END

		IF @nRet <> 0
		BEGIN
			GOTO ERROR1
		END

		FETCH NEXT FROM Auditing_Cursor INTO	
												@szATypeIDTemp,
												@szPTypeIDTemp,
												@szBTypeIDTemp,
												@szETypeIDTemp,
												@szKTypeIDTemp,
												@szSTypeIDTemp,
												@dQty,
												@dPrice,
												@dTotal,
												@dCostPrice,
												@dCostTotal,
												@szJobNumber,
												@nGoodsNo,
												@OutFactoryDate,
												@GoodsNumber,
												@ProduceDate,
												@ValidDate,
												@GoodsBTypeID,
												@GoodsCostPrice,
												@HandZeroCost
	END

	CLOSE Auditing_Cursor
	DEALLOCATE Auditing_Cursor
	

	
	IF @nBillType=57 AND @intAdPriceType<>0
	BEGIN
		
		/*
		UPDATE GOODSSTOCKS
		SET Total=GOODSSTOCKS.Total+b.Total,
			Price=CASE GOODSSTOCKS.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(GOODSSTOCKS.Total+b.Total AS  NUMERIC(24, 10) )/CAST(GOODSSTOCKS.Qty AS  NUMERIC(24, 10) ),4) END
		FROM InOutstocktable b
		WHERE GOODSSTOCKS.KtypeId=b.KtypeId
		AND GOODSSTOCKS.PtypeId=b.PtypeId
		AND GOODSSTOCKS.GoodsNumber=b.GoodsNumber
		AND GOODSSTOCKS.ProduceDate=b.ProduceDate
		AND GOODSSTOCKS.ValidDate=b.ValidDate
		AND b.BillNumberId=@nBillID
		AND b.BillType=@nBillType
		*/
		MERGE GoodsStocks AS t
		USING(
			SELECT PTypeID,KTypeID,SUM(Total) AS Total
			FROM InOutstocktable
			WHERE BillNumberID=@nBillID
			GROUP BY PTypeID,KTypeID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		WHEN MATCHED THEN 
			UPDATE SET t.Total=t.Total+s.Total,t.Price=CASE t.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(t.Total+s.Total AS  NUMERIC(24, 10) )/CAST(t.Qty AS  NUMERIC(24, 10) ),4) END
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,Qty,Price,Total) 
			VALUES(s.PtypeId,s.KTypeID,0,0,s.Total);
			
		MERGE GoodsStocks_Qty AS t
		USING(
			SELECT DISTINCT PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID
			FROM InOutstocktable
			WHERE BillNumberID=@nBillID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		AND t.GoodsNumber=s.GoodsNumber AND t.ProduceDate=s.ProduceDate AND t.ValidDate=s.ValidDate
		AND t.CargoID=s.CargoID
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,CargoID,ItemID,IsCombined) 
			VALUES(s.PtypeId,s.KTypeID,s.GoodsNumber,s.ProduceDate,s.ValidDate,0,0,0,s.CargoID,0,0);			
	END

	/******** 处理新维修的出入库明细 - Start ********/
	-- 同时对勾选了“处理维修品”的报损、报溢单进行处理
	
	IF @nBillType IN (165,166,167,168,169,170,172,173,174,175,9,14)
	BEGIN
		DECLARE wx_Cursor CURSOR SCROLL FOR
			SELECT	BillType,ATypeID,PTypeID,BTypeID,ETypeID,KTypeID,Qty,Price,Total,CostPrice,CostTotal,JobNumber,GoodsNo,OutFactoryDate,GoodsNumber,
					ProduceDate,ValidDate,GoodsBTypeID,GoodsCostPrice,HandZeroCost,ItemID,IsCombined,NQty
			FROM	wx_InOutStockTable
			WHERE	BillNumberID = @nBillID AND IsService=0  AND BillType=@nBillType
			ORDER BY [ID]
			--FOR UPDATE
	
		OPEN wx_Cursor
		FETCH NEXT FROM wx_Cursor INTO @nBillType,@szATypeIDTemp,@szPTypeIDTemp,@szBTypeIDTemp,@szETypeIDTemp,@szKTypeIDTemp,@dQty,@dPrice,@dTotal,
			@dCostPrice,@dCostTotal,@szJobNumber,@nGoodsNo,@OutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intItemID,@intIsCombined,@dNQty
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC @nRet = Gp_ModifyDbf_WX	@nBillType,
											@nCostingMethod,
											@szATypeIDTemp,
											@szPTypeIDTemp,
											@szBTypeIDTemp,
											@szETypeIDTemp,
											@szKTypeIDTemp,
											'',
											@dQty,
											@intItemID,
											@intIsCombined,
											@dNQty,
											@dCostTotal,
											@szJobNumber,
											--@nGoodsNo,
											@nBillID,
											@GoodsNumber,
											@ProduceDate,
											@ValidDate,
											@GoodsCostPrice,
											@HandZeroCost,
											@dCostPriceOut output,
											NULL,
											@dCostPrice
			IF @nRet <> 0 GOTO ERROR3
			FETCH NEXT FROM wx_Cursor INTO @nBillType,@szATypeIDTemp,@szPTypeIDTemp,@szBTypeIDTemp,@szETypeIDTemp,@szKTypeIDTemp,@dQty,@dPrice,@dTotal,
				@dCostPrice,@dCostTotal,@szJobNumber,@nGoodsNo,@OutFactoryDate,@GoodsNumber,@ProduceDate,@ValidDate,@GoodsBTypeID,@GoodsCostPrice,@HandZeroCost,@intItemID,@intIsCombined,@dNQty
		END
		CLOSE wx_Cursor
		DEALLOCATE wx_Cursor
	END
	/******** 处理新维修的出入库明细 - End ********/

	UPDATE	BillIndex
	SET		IfCheck = 't',
			Draft = 0
	WHERE	BillNumberID = @nBilliD   AND BillType=@nBillType

	-- if @@trancount<>0 commit tran --AuditingTrans
	RETURN 0

	ERROR1:
		CLOSE Auditing_Cursor
		DEALLOCATE Auditing_Cursor
		/*
		IF @@TRANCOUNT <> 0
		BEGIN
			ROLLBACK TRAN	-- AuditingTrans
		END
		*/
		SET @strPTypeIDOutPut = @szPTypeIDTemp
		RETURN @nRet

	ERROR3:
		CLOSE wx_Cursor
		DEALLOCATE wx_Cursor
		-- 返回商品 ID 值
		SET @strPTypeIDOutPut = @szPTypeIDTemp
		RETURN @nRet


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Zc_AuditingMx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Zc_AuditingMx]
GO


-- ========================================================================
-- 功能说明：	红冲单据 处理应收应付预收预付账务相关
-- 作    者：	卢  春
-- 最后修改：	2004-01-07
-- ========================================================================
CREATE         PROCEDURE Gp_Zc_AuditingMx 
(
	@nBillID	numeric(10, 0),		-- 1. 单据编号 ID
	@nBillType	INT,
	@Reverse	bit					-- 2. 是否相反
)
--@encode$--
AS
	SET NOCOUNT ON
	-- Some vchtype
	DECLARE	@GOODS_ID		varchar(50),
			@CASH_ID		varchar(50),
			@AR_ID			varchar(50),
			@AP_ID			varchar(50),
			@YF_ID			varchar(50),
			@YS_ID			varchar(50),
			@GOODS_LOSS_ID	varchar(50),
			@GOODS_GET_ID	varchar(50),
			@GRIR_ID		VARCHAR(50),
			@FC_ID			VARCHAR(50)

	SELECT @GOODS_ID=nid FROM dbo.Ac_Items WHERE UserCode = '1241'			-- 库存商品总值
	SELECT @CASH_ID =nid FROM dbo.Ac_Items WHERE UserCode = '1001'			-- 现金
	SELECT @AR_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '987'				-- 应收
	SELECT @AP_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '2121'			-- 应付
	SELECT @GOODS_LOSS_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '0421'	-- 商品报损支出
	SELECT @GOODS_GET_ID =nid FROM dbo.Ac_Items WHERE UserCode =  '0321'	-- 商品报溢收入
	SELECT @YF_ID=nid FROM dbo.Ac_Items WHERE UserCode =  '1151'			--预付账款
	SELECT @YS_ID=nid FROM dbo.Ac_Items WHERE UserCode = '2131'				--预收账款
	SELECT 	@FC_id					=nid FROM dbo.Ac_Items WHERE UserCode =  '1251'			--发出商品
	SELECT 	@GRIR_ID				=nid FROM dbo.Ac_Items WHERE UserCode =  '2122'			--应付暂估
	------------------
	-- Costing method --
	DECLARE	@AVERAGE	smallint,
			@FIFO		smallint,
			@LIFO		smallint,
			@HAND		smallint

	SET @AVERAGE	= 0
	SET @FIFO		= 1
	SET @LIFO		= 2
	SET @HAND		= 3
	---------------------

	DECLARE	@DBName					varchar(30),
			@nCostingMethod 		smallint,
			@tBillDate				datetime,
			@dTotalMoney			 NUMERIC(24, 10) ,
			@dTotalinMoney			 NUMERIC(24, 10) ,
			@dTotalTemp				 NUMERIC(24, 10) ,
			@dCostTotalTemp			 NUMERIC(24, 10) ,
			@szATypeID				varchar(50),
			@szPTypeID				varchar(50),
			@szBTypeID				varchar(50),
			@szETypeID				varchar(50),
			@szStockID				varchar(50),
			@szStockID2				varchar(50),
			@szATypeIDTemp			varchar(50),
			@szPTypeIDTemp			varchar(50),
			@szBTypeIDTemp			varchar(50),
			@szETypeIDTemp			varchar(50),
			@szKTypeIDTemp			varchar(50),
			@szSTypeIDTemp			varchar(50),
			@szIfCheck				char(1),
			@nPeriod				int,
			@szJobNumber			varchar(20),
			@OutFactoryDate			datetime,
			@dPrice					 NUMERIC(24, 10) ,
			@dTotal					 NUMERIC(24, 10) ,
			@dQty					 NUMERIC(24, 10) ,
			@dCostPrice				 NUMERIC(24, 10) ,
			@dCostTotal				 NUMERIC(24, 10) ,
			@nGoodsNo				int,
			@dCostPriceOut			 NUMERIC(24, 10) ,
			@dTemp					 NUMERIC(24, 10) ,
			@dPricetemp				 NUMERIC(24, 10) ,
			@cid					INT,
			@dntotal				 NUMERIC(24, 10) ,
			@nRet					smallint

	SET @dTotalTemp = 0
	-- 得到成本核算法
	EXEC Gp_GetSubValue 'costing','', @nCostingMethod output
	
	SELECT	BillType,
				ATypeID,
				PTypeID,
				BTypeID,
				ETypeID,
				KTypeID,
				STypeID,
				Qty,
				Price,
				Total,
				CostPrice,
				CostTotal,
				JobNumber,
				GoodsNo,
				OutFactoryDate,
				Ntotal,
				cid
		FROM	ListTable
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType

	-- begin tran AuditingMxTrans
	DECLARE Auditing_Cursor CURSOR SCROLL FOR
		SELECT	BillType,
				ATypeID,
				PTypeID,
				BTypeID,
				ETypeID,
				KTypeID,
				STypeID,
				Qty,
				Price,
				Total,
				CostPrice,
				CostTotal,
				JobNumber,
				GoodsNo,
				OutFactoryDate,
				Ntotal,
				cid
		FROM	ListTable
		WHERE	BillNumberID = @nBillID AND BillType=@nBillType

	OPEN Auditing_Cursor
	FETCH NEXT FROM Auditing_Cursor INTO	@nBillType,
											@szATypeIDTemp,
											@szPTypeIDTemp,
											@szBTypeIDTemp,
											@szETypeIDTemp,
											@szKTypeIDTemp,
											@szSTypeIDTemp,
											@dQty,
											@dPrice,
											@dTotal,
											@dCostPrice,
											@dCostTotal,
											@szJobNumber,
											@nGoodsNo,
											@OutFactoryDate,
											@dntotal,
											@cid
	WHILE @@FETCH_STATUS <> -1
	BEGIN
		IF @@FETCH_STATUS = -2 GOTO ERROR1
		ELSE
		BEGIN
			
			IF @Reverse = 1
			BEGIN
				SET @dQty		= -@dQty
				SET @dTotal		= -@dTotal
				SET @dCostTotal	= -@dCostTotal
				SET @dntotal	= -@dntotal
			END
			
			
			IF @nBillType IN (143)	-- 代销调价单不处理
			BEGIN
				SET @nRet = 0
			END
			ELSE
			BEGIN	
				EXEC @nRet = Gp_ModifyDbf	@nBillType,
											@nCostingMethod,
											@szATypeIDTemp,
											@szPTypeIDTemp,
											@szBTypeIDTemp,
											@szETypeIDTemp,
											@szKTypeIDTemp,
											@szSTypeIDTemp,
											'',
											@dQty,
											@dTotal,
											@dntotal,
											@cid,
											@szJobNumber,
											@nGoodsNo,
											'',
											'',
											'',
											0,
											0,
											@dCostPriceOut output
											
			END

			IF @nRet <> 0
			BEGIN
				GOTO ERROR1
			END

			IF @szATypeIDTemp = @AP_ID OR @szATypeIDTemp = @AR_ID OR @szATypeIDTemp=@YS_ID OR @szATypeIDTemp=@YF_ID OR @szATypeIDTemp =@GRIR_ID OR @szATypeIDTemp =@FC_ID
			BEGIN
				EXEC @nRet = Gp_ModifyDbf	@nBillType,
											@nCostingMethod,
											@szATypeIDTemp,

											'0',

											'0',
											'0',
											'0',
											@szSTypeIDTemp,
											'',
											@dQty,
											@dTotal,
											@dntotal,
											@cid,
											@szJobNumber,
											@nGoodsNo,
											'',
											'',
											'',
											0,
											0,
											@dCostPriceOut output
				IF @nRet <> 0
				BEGIN
					GOTO ERROR1
				END
			END

			FETCH NEXT FROM Auditing_Cursor INTO	@nBillType,
													@szATypeIDTemp,
													@szPTypeIDTemp,
													@szBTypeIDTemp,
													@szETypeIDTemp,
													@szKTypeIDTemp,
													@szSTypeIDTemp,
													@dQty,
													@dPrice,
													@dTotal,
													@dCostPrice,
													@dCostTotal,
													@szJobNumber,
													@nGoodsNo,
													@OutFactoryDate,
													@dntotal,
													@cid
		END
	END

	CLOSE Auditing_Cursor
	DEALLOCATE Auditing_Cursor
	-- commit tran AuditingMxTrans
	RETURN 0

	ERROR1:
		CLOSE Auditing_Cursor
		DEALLOCATE Auditing_Cursor
		-- if @@trancount<>0 rollback tran AuditingMxTrans
		RETURN -1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Zc_RedWord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Zc_RedWord]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
功能说明：	红冲单据 - 在单据索引表中添加新的红冲单据记录
					 - 在单据明细表中添加相同的记录
					 - 在 InOutStockTable 中添加反相出入库记录
*/
CREATE  PROCEDURE Gp_Zc_RedWord 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@EtypeID        	varchar(50) = '00001',	-- 2. 红冲单据的操作员ID
	@IsRepairBill		INT=0,
	@strPTypeIDOutPut	varchar(500) OUTPUT,	-- 3. 返回出错商品 ID 值
	@redreason			VARCHAR(256),		---红冲原因
	@billType			INT =0
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN TRAN RedWord
SAVE TRAN RedWordPoint
--------------定义变量---------------
DECLARE @Sql				varchar(256)
DECLARE @SqlItem			varchar(256)
DECLARE @szDate				varchar(12)
DECLARE @dbName				varchar(30)
DECLARE @nNewBillID			numeric(10,0)
DECLARE @tBillDate				datetime		--单据日期
DECLARE @nRet					int				--返回值
DECLARE	@nBillType				int				--单据类型
DECLARE	@bRedWord				char(1)			--红冲标志
DECLARE @szIfCheck				char(1)			--是否过账
DECLARE @szPeriod1				datetime		--本期时间
DECLARE @cwcheck				INT
DECLARE @strInfoOUT				VARCHAR(1000),
		@chvBTypeID				VARCHAR(50),
		@chvDealBTypeID			VARCHAR(50),
		@chvSTypeID				VARCHAR(50),
		@FrozeDate				DATETIME,
		@AssetBusinessTypeId	INT,
		@VerifyID				VARCHAR(50),
		@chargeOffValue			numeric(24,10)


----------------先将红冲标志置为1--------------------------------------
IF @billType IN (71,72,87,88)
BEGIN
	UPDATE dbo.LendIndex SET RedWord=1 WHERE RedWord=0 and BillNumberId=@nBillID
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -100 --已红冲或未过账
	END
	SELECT  @nBillType = BillType,
			@tBillDate=BillDate,
			@bRedWord=redword,
			@szIfCheck=ifcheck,
			@cwcheck=0,
			@chvBTypeID=btypeid,
			@chvDealBTypeID=DealBTypeID,
			@chvSTypeID=stypeid,
			@VerifyID=stypeid,
			@AssetBusinessTypeId=0
	FROM	LendIndex 
	WHERE	BillNumberId=@nBillID
	
END

ELSE IF @BillType IN (404,405)
BEGIN
	UPDATE ReceiptBillIndex SET RedWord=1 WHERE RedWord=0 and BillNumberId=@nBillID
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -100 --已红冲或未过账
	END
	SELECT  @nBillType = BillType,
			@tBillDate=BillDate,
			@bRedWord=redword,
			@szIfCheck=ifcheck,
			@cwcheck=0,
			@chvBTypeID=btypeid,
			@chvDealBTypeID=DealBTypeID,
			@chvSTypeID=stypeid,
			@VerifyID=stypeid,
			@AssetBusinessTypeId=0,
			@chargeOffValue=ChargeOffTotal
	FROM	ReceiptBillIndex 
	WHERE	BillNumberId=@nBillID
	IF @chargeOffValue <> 0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -600 --已核销
	END
END
ELSE IF @BillType IN(412,413)
BEGIN
	UPDATE onShelvespickIndex SET RedWord=1 WHERE RedWord=0 AND BillNumberID=@nBillID
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -100 --已红冲或未过账
	END
		SELECT  @nBillType = BillType,
				@tBillDate=BillDate,
				@bRedWord=redword,
				@szIfCheck=ifcheck,
				@cwcheck=0,
				@chvBTypeID='',
				@chvDealBTypeID='',
				@chvSTypeID=stypeid,
				@VerifyID=stypeid,
				@AssetBusinessTypeId='',
				@chargeOffValue=0
	FROM	onShelvespickIndex 	WHERE	BillNumberId=@nBillID
END
ELSE IF @BillType IN(418,419,420)
BEGIN
	UPDATE dbo.FactIndex SET RedWord=1 WHERE RedWord=0 AND BillNumberId=@nBillID
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -100 --已红冲或未过账
	END
	SELECT  @nBillType = BillType,
			@tBillDate=BillDate,
			@bRedWord=redword,
			@szIfCheck=ifcheck,
			@cwcheck=0,
			@chvBTypeID='',
			@chvDealBTypeID='',
			@chvSTypeID=stypeid,
			@VerifyID=stypeid,
			@AssetBusinessTypeId='',
			@chargeOffValue=0
	FROM	dbo.FactIndex 	WHERE	BillNumberId=@nBillID
END
ELSE IF @BillType IN(327,328,329)
BEGIN	
	UPDATE PosAllotApplyBillIndex SET RedWord=1 WHERE RedWord=0 and BillNumberId=@nBillID
	
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -100 --已红冲或未过账
	END
	SELECT  @nBillType = BillType,
			@tBillDate=BillDate,
			@bRedWord=redword,
			@szIfCheck=ifcheck,
			@cwcheck=0,
			@chvBTypeID='',
			@chvDealBTypeID='',
			@chvSTypeID=stypeid,
			@VerifyID=stypeid,
			@AssetBusinessTypeId='',
			@chargeOffValue=0
	FROM	dbo.PosAllotApplyBillIndex 	WHERE	BillNumberId=@nBillID
END
ELSE
BEGIN

	UPDATE BillIndex SET RedWord=1 WHERE RedWord=0 and BillNumberId=@nBillID
	IF @@ROWCOUNT=0 
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -100 --已红冲或未过账
	END
	SELECT  @nBillType = BillType,
			@tBillDate=BillDate,
			@bRedWord=redword,
			@szIfCheck=ifcheck,
			@cwcheck=CWCheck,
			@chvBTypeID=btypeid,
			@chvDealBTypeID=DealBTypeID,
			@chvSTypeID=stypeid,
			@VerifyID=stypeid,
			@AssetBusinessTypeId=AssetBusinessTypeId,
			@chargeOffValue=ChargeOffTotal
	FROM	BillIndex 
	WHERE	BillNumberId=@nBillID
	IF @chargeOffValue<>0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -600 --已核销
	END
END

IF @nBillType IN (115,116,128,129)
BEGIN
	IF EXISTS(SELECT 1 FROM AdDebtBill WHERE BillNumberId=@nBillID AND ChargeOffTotal>0)
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -600 --已核销
	END
END


IF EXISTS(
		SELECT TypeID
		FROM SType
		WHERE TypeId=@chvSTypeID AND IsSelfVerify=0
	)
BEGIN
	SELECT @VerifyID=VerifyID
	FROM SType
	WHERE TypeId=@chvSTypeID
END	
	
--------------------得到本期开始时间 start---------------
IF @nBillType=310
BEGIN
	--资金调拨单
	SELECT @szPeriod1=b.FBegin
	FROM Te_Period a
	INNER JOIN Ac_Period b
	ON a.FPeriod=b.FPeriod
	WHERE a.STypeId=@VerifyID
	AND a.FYear=YEAR(@tBillDate)
END
ELSE
BEGIN
	SELECT	@szPeriod1 = StartDate
	FROM	MonthProc
	WHERE	MonthNo = '本期' AND STypeID=@chvSTypeID
END	
--------------------得到本期开始时间 end---------------

------------------------------------------开始判断-------------------------------------------
IF @nBillType<>310
BEGIN
	IF GETDATE() < @szPeriod1 
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -8
	END
END

IF @tBillDate < @szPeriod1
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -2 --不能红冲月结前单据
END
--------------------判断冻结时间 start---------------
IF @nBillType<>310
BEGIN
	SET @FrozeDate=@tBillDate
	SELECT	@FrozeDate =FrozeDate  FROM FrozeBusiness WHERE stypeid=@chvSTypeID

	IF @tBillDate<@FrozeDate
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -705	
	END
END	
--------------------判断冻结时间 end---------------

IF @szIfCheck = 'f' 
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -100 --已红冲或未过账
END
IF @cwcheck = 1 
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -9 --已被财务审核
END
--红冲前检查关联关系
EXEC @nRet = Gp_RedWordValidate @nbillid,@nbilltype,@szPeriod1
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN @nRet
END
--select 1,@nRet

-------------------------------------------判断结束-------------------------------------------------------



/*-------------------------------------红冲序列号 start----------------------------------------------------*/
--零售单、销售出库单、销售退货单、委托发货、委托结算、委托退货、采购入库、采购退货、
--受托收货、受托结算、受托退货、同价调拨、变价调拨、报损单、报溢单、拆装单、换货单、维修受理单、赠送单、获赠单、
--销售换货单、采购换货单、维修接件单、维修单、维修取件单、整机更换单、送修单、送修返回单、上门维修单、维修品调入单、维修品调出单、维修品调拨单
--积分兑换单、分支机构调拨出库单、分支机构调拨入库单,其他入库单，其他出库单,零售退货单,门店配送单,门店配送，退货，验收单序列号红冲
IF @nBillType IN (305,11,12,6,140,141,142,34,45,46,144,145,146,17,21,9,14,16,155,157,139,126,160,161,165,166,167,168,169,170,172,173,174,175,183,187,188,201,202,215,57,400,401,402,403,327,328,329)
BEGIN
	EXEC @nRet = GP_SerialRedWord @nBillID,@nBillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN @nRet
	END
END
ELSE IF @nBillType IN (71,72,87,88)
BEGIN
	EXEC @nRet = Gp_SerialRedWordForLend @nBillID,@nBillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN @nRet
	END
END
--实物序列号
ELSE IF @nBillType IN(418,419,420)
BEGIN
	EXEC @nRet=GP_SerialRedWord_Fact @nBillID,@nBillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN @nRet
	END
END
--ELSE IF @nBillType IN(327,328,329)--门店配送，退货，验收单序列号红冲
--BEGIN
--	EXEC @nRet=GP_SerialRedWord_Delivery @nBillID,@nBillType
--	IF @nRet <> 0
--	BEGIN
--		ROLLBACK TRAN RedWordPoint
--		COMMIT TRAN RedWord
--		RETURN @nRet
--	END
--END

--借欠转采购or销售序列号红冲回去
IF @nBillType IN (11,34) AND EXISTS( SELECT TOP 1 1  FROM dbo.BillIndex WHERE BillNumberId = @nBillID AND IsLend= 1)
BEGIN
	
	DECLARE		
	@cmdSQL			NVARCHAR(MAX),
	@intDealSerial	TINYINT,
	@BillName		VARCHAR(100)
					
	SELECT @BillName=detailTable
			FROM BillName
			WHERE Billtype=@nBillType
			
	SET @cmdSQL='IF EXISTS(SELECT BillNumberID FROM '+@BillName+' WHERE BillNumberId='+CAST(@nBillID AS VARCHAR(50))+' AND CAST(Serial AS VARCHAR(MAX))<>'''') SET @intDealSerial=1 ELSE SET @intDealSerial=0'
	EXECUTE sp_executesql @cmdSQL,N'@intDealSerial TINYINT OUTPUT',@intDealSerial OUTPUT
	--SELECT @intDealSerial AS '@intDealSerial'

	IF @intDealSerial=1 
	BEGIN
		--序列号出入库操作对应状态表
		CREATE TABLE #SerialInOutState
		(
			orderid int, --序列号出入库顺序
			Serial	VARCHAR(50),	--序列号值
			SerialStata INT			--序列号状态
		)
		
		
		--需要排除蓝单,但是不能排除本单(因为本单一红冲,REDWORD就变成1了)

		
		INSERT INTO #SerialInOutState ( orderid, Serial, SerialStata )
		SELECT orderid, Serial, SerialStata
		FROM (
				SELECT ROW_NUMBER() OVER(PARTITION BY a.Serial ORDER BY a.id DESC) AS orderid,a.Serial,a.State AS SerialStata FROM gp_inoutPtypeSerial a
				WHERE a.Serial IN (SELECT Serial FROM gp_inoutPtypeSerial WHERE BillType = @nBillType AND BillNumberid = @nBillID)
				
				AND NOT EXISTS(
					SELECT b.BillNumberId
					FROM dbo.BillIndex b
					WHERE b.BillNumberId=a.BillNumberID AND b.BillType=a.BillType AND b.BillNumberID=@nBillID AND b.RedWord=1 
					UNION ALL
					SELECT b.BillNumberId
					FROM dbo.LendIndex b
					WHERE b.BillNumberId=a.BillNumberID AND b.RedWord=1 AND b.BillType=a.BillType	
				)
				
			)AS t
			
			
		--SELECT '??',* FROM #SerialInOutState
			
		--当前序列号状态为借欠转采购或借转销售时，才回写序列号状态到上一状态
		IF EXISTS (SELECT * FROM #SerialInOutState WHERE orderid=1 AND SerialStata IN (1,18,17))
		BEGIN
			UPDATE a SET a.STATE =CASE WHEN @nBillType=11 AND b.SerialStata IN(1,18) THEN 18 ELSE 17 END,a.Flag=CASE WHEN b.SerialStata IN(1,18) AND @nBillType=11 THEN 0 ELSE 1 END  FROM gp_LendPtypeSerial a JOIN (SELECT Serial,SerialStata FROM #SerialInOutState WHERE orderid=1) b ON a.Serial = b.Serial 
		END
		ELSE 
		BEGIN
			UPDATE a SET a.STATE =B.State,A.Flag=B.Flag
			FROM gp_LendPtypeSerial a 
			INNER JOIN gp_initLendPtypeSerial B ON B.Serial=A.Serial
		END
	END 
END
--select 2,@nRet	
/*----------------------------------------红冲序列号 end-----------------------------------------------------*/	


-----------------------------插入红单主表、明细、多账户 start--------------------------------
EXEC @nRet = Gp_RedWordInsertBill @nBillID,@nNewBillID output,@nBillType,@strPTypeIDOutPut OUTPUT,@tBillDate,@etypeid

--select 3,@nRet
IF ISNULL(@nRet,0)<>0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN @nRet
END
-----------------------------插入红单主表、明细、多账户 end--------------------------------




------------------------------红冲自由项 start--------------------------------------------------------
IF @billType NOT IN (71,72,87,88,404,405,450,84,85,78,212,213,214,307,310,312,203,116,115,128,129,4,189,66,190,148,150,149,151,162,163,36,158,77,93,5,10,159,205,206,181,311,412,413,414,418,419,420)
BEGIN
	EXEC GP_Auditing_DealQty
			@nBillID,
			@nBillType,
			2,
			@chvDealBTypeID,
			@chvBTypeID,
			@chvSTypeID,
			@strPTypeIDOutPut	OUT,
			@nRet	OUT
			
	IF ISNULL(@nRet,0)<>0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -18
	END
END

--select 4,@nRet
-------------------------------红冲自由项 end---------------------------------------------------------

-------------------------------插入红冲原因---------------------
IF @billType IN (404,405)
BEGIN
	UPDATE ReceiptBillIndex SET redreason = @redreason WHERE BillNumberId = @nNewBillID
END
ELSE IF @BillType IN(412,413)
BEGIN
	UPDATE onShelvespickIndex SET RedReason=@RedReason WHERE BillNumberId =@nNewBillID
END
ELSE IF @BillType IN(418,419,420)
BEGIN
	UPDATE dbo.FactIndex SET RedReason=@RedReason WHERE BillNumberId=@nNewBillID
END
ELSE IF @BillType IN(327,328,329)
BEGIN
	UPDATE dbo.PosAllotApplyBillIndex SET RedReason=@RedReason WHERE BillNumberId=@nNewBillID
END
ELSE IF @billType NOT IN (71,72,87,88)
BEGIN
	UPDATE BillIndex SET redreason = @redreason WHERE BillNumberId = @nNewBillID
END
ELSE
BEGIN
	UPDATE dbo.LendIndex SET redreason = @redreason WHERE BillNumberId = @nNewBillID
	EXEC gp_SetLendGoods @nNewBillID
END

----------------------------------------------------------------
	
	
-----------------------------处理关联的数据 start------------------------------------------
EXEC @nRet = Gp_RedWordPostmortem @nBillID,@nNewBillID,@nBillType

--select 4.5,@nRet

IF ISNULL(@nRet,0)<>0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -1
END
-----------------------------处理关联的数据 end------------------------------------------
	
------------------------------单据红冲反向插入InOutStockTable，wx_InOutStockTable,listtable明细 start---------------------
IF @nBillType NOT IN (71,72,87,88,412,413)
BEGIN
	EXEC @nRet = Gp_RedWordInsertInOutListDetail @nBillID,@nNewBillID,@nBillType
	IF ISNULL(@nRet,0)<>0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN @nRet
	END

END

--select 5,@nRet
------------------------------单据红冲反向插入InOutStockTable，wx_InOutStockTable,listtable明细 end------------------------

DECLARE		
	@intAdPriceBillNumberID		INT,
	@intAdPriceNewBillNumberID	INT,
	@strSTypeID					VARCHAR(50),
	@strBTypeID					VARCHAR(50),
	@intCID						INT

--针对暂估发票的特殊处理  start
IF @billtype IN (404,405)
BEGIN
	--对成本调价单的红冲要在调用后处理
	IF EXISTS(
		SELECT a.ID
		FROM AdPriceBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID
	)
	BEGIN

		SELECT @intAdPriceBillNumberID=a.BillNumberId,@strSTypeID=b.StypeID,@strBTypeID=b.Btypeid,@intCID=CID
		FROM AdPriceBill a
		INNER JOIN BillIndex b
		ON a.BillNumberId=b.BillNumberId
		WHERE a.FromBillNumberID=@nBillID

		
		
		
		MERGE GoodsStocks AS t
		USING(
			SELECT PTypeID,KTypeID,SUM(-Total) AS Total
			FROM AdPriceBill
			WHERE BillNumberID=@intAdPriceBillNumberID
			GROUP BY PTypeID,KTypeID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		WHEN MATCHED THEN 
			UPDATE SET t.Total=t.Total+s.Total,t.Price=CASE t.Qty WHEN 0 THEN 0 ELSE ROUND(CAST(t.Total+s.Total AS  NUMERIC(24, 10) )/CAST(t.Qty AS  NUMERIC(24, 10) ),4) END
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,Qty,Price,Total) 
			VALUES(s.PtypeId,s.KTypeID,0,0,s.Total)
		;
		
		
		MERGE GoodsStocks_Qty AS t
		USING(
			SELECT DISTINCT PTypeID,KTypeID,GoodsNumber,ProduceDate,ValidDate,CargoID
			FROM AdPriceBill
			WHERE BillNumberID=@intAdPriceBillNumberID
		) AS s ON t.PTypeID=s.PtypeId AND t.KTypeID=s.KTypeID 
		AND t.GoodsNumber=s.GoodsNumber AND t.ProduceDate=s.ProduceDate AND t.ValidDate=s.ValidDate
		AND t.CargoID=s.CargoID
		WHEN NOT MATCHED BY TARGET THEN 
			INSERT (PtypeId,KTypeID,GoodsNumber,ProduceDate,ValidDate,Qty,NQty,GoodsCostPrice,CargoID,ItemID,IsCombined) 
			VALUES(s.PtypeId,s.KTypeID,s.GoodsNumber,s.ProduceDate,s.ValidDate,0,0,0,s.CargoID,0,0)
		;

		--GOODSSTOCKS_QTY不变

		

		UPDATE ListTable
		SET Total=-Total,Ntotal=-Ntotal,CostTotal=-CostTotal
		WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57
		
		EXEC @nRet = Gp_ModifyBAndAtype_Total @intAdPriceBillNumberID,57
		

		
		DELETE ListTable WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57
		
		DELETE AdPriceBill WHERE BillNumberId=@intAdPriceBillNumberID
		
		DELETE BillIndex WHERE BillNumberId=@intAdPriceBillNumberID AND BillType=57

	END		
		
	
	
	
	--处理发票状态
	EXEC GP_Receipt_Deal @nBillID,1
END

--实物类单据直接处理实物库存
IF @nBillType IN(418,419,420)
BEGIN
	EXEC @nRet=GP_DealFactQty_Reverse @nBillID,@nBillType,@strPTypeIDOutPut output	
	IF @nRet<>0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -1
	END
END

-------------------------------inoutstocktable反算----------------------------------------
IF @nBillType NOT IN (205,206,71,72,87,88,404,405,412,413,414,418,419,420)
BEGIN
	EXEC @nRet = Gp_Zc_AuditingInOut @nNewBillID,@nBillType, 0, @strPTypeIDOutPut OUTPUT
	
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN @nRet
	END
END

-- 检查账户余额，是否过账后会 < 0
IF @nBillType NOT IN (71,72,87,88,400,401,402,403,404,405,412,413,418,419,420)
BEGIN
	EXEC @nRet = GP_AuditingATypeBalanceCheck @nNewBillID,@nBillType, @strPTypeIDOutPut output
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN 918
	END
END
-------------------------------listtable反算---------------------------------- 

--select 7,@nRet

IF @nBillType NOT IN (206,143,412,413,418,419,420) --listtable过账
BEGIN
	
	EXEC @nRet = Gp_ModifyBAndAtype_Total @nNewBillID,@nBillType
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN -1
	END
END

--select 8,@nRet
--检查是否需要平均库存成本
EXEC @nRet = Gp_CallAverageCostPrice @nNewBillID
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -1
END

IF @nbilltype IN (17,21,187)
BEGIN
     EXEC Gp_BackFillAllotBillState @nBillID,@nbilltype;
END

IF @nBillType IN (212,213,214)
BEGIN
	--处理固定资产
	EXEC Gp_Auditing_DealAssest
	@nBillID,
	'00001',
	@nBillType,
	1,
	@tBillDate,
	@AssetBusinessTypeId,
	@chvSTypeID,
	@nRet OUT,
	@strPTypeIDOutPut OUT
	
	IF @nRet<>0
	BEGIN
		ROLLBACK TRAN RedWordPoint
		COMMIT TRAN RedWord
		RETURN @nRet
	END
END
--------------------------------------------------------------------------------------------------
--销售出库单已经委托代销出库单红冲后需要重新锁定关联的订单数量
IF @BillType IN (11,12,140,402)
BEGIN
	EXEC GP_DoRedWordLock @nBillID,@nBillType
END

IF @BillType=404
BEGIN
	EXEC GP_ReceiptBill_AfterRedWord @chvOpID=@ETypeID,@nBillID=@nBillID
END
--------------------------------------------------------------------------------------------------
-- 过账最后处理订单库存
IF @BillType IN (11,12,34,140,144,400,402)
BEGIN
	EXEC GP_Deal_OrderReachQTY @nBillID,@BillType,'-',0,1
END

IF @billtype IN (305,215,11,45,12,46)
BEGIN
	IF EXISTS (SELECT  TOP 1 1 FROM  dbo.Coupon_BillUsed WHERE BillnumberId=@nBillID)
	BEGIN
		--Coupon_BillUsed
		INSERT INTO dbo.Coupon_BillUsed
				( BillnumberId ,
				  CouponCode ,
				  BillType,
				  CouponId
				)
		SELECT @nNewBillID,
				CouponCode,
				BillType,
				CouponId
		FROM  Coupon_BillUsed 
		WHERE BillnumberId=@nBillID
		--Coupon_CodeInfo
		UPDATE c 
		SET		[State]=CASE WHEN @nBillType IN(305,11,12) THEN 4 --消费红冲
							 WHEN @nBillType IN (215,45,46) THEN  3--退货红冲 为 已消费
						END 
		FROM Coupon_CodeInfo c ,
			 Coupon_BillUsed b
		WHERE c.CouponCode=b.CouponCode AND b.BillnumberId=@nBillID 
		
	END  
	
END 
--如果是WMS转过来的单据
IF(@billType IN(11,45,36,4))
	BEGIN
		UPDATE WMS_ERPBillRelation SET RedWord=1 WHERE ERP_BillNumberID=@nBillID
	END


COMMIT TRAN RedWord
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Zc_RedWord_Coupon]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Gp_Zc_RedWord_Coupon
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/****优惠券单据红冲****/

CREATE  PROCEDURE Gp_Zc_RedWord_Coupon 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@EtypeID        	varchar(50) = '00001',	-- 2. 红冲单据的操作员ID
	@strPTypeIDOutPut	varchar(500) OUTPUT,	-- 3. 返回出错券code  值
	@redreason			VARCHAR(500),		---红冲原因
	@IsRepairBill		INT =0,
	@billType			INT =0
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN TRAN RedWord
SAVE TRAN RedWordPoint
--------------定义变量---------------
DECLARE @Sql				varchar(256)
DECLARE @SqlItem			varchar(256)
DECLARE @szDate				varchar(12)
DECLARE @dbName				varchar(30)
DECLARE @nNewBillID			numeric(10,0)
DECLARE @tBillDate				datetime		--单据日期
DECLARE @nRet					int				--返回值
DECLARE	@nBillType				int				--单据类型
DECLARE	@bRedWord				char(1)			--红冲标志
DECLARE @szIfCheck				char(1)			--是否过账
DECLARE @szPeriod1				datetime		--本期时间
DECLARE @cwcheck				INT
DECLARE @strInfoOUT				VARCHAR(1000),
		@chvBTypeID				VARCHAR(50),
		@chvDealBTypeID			VARCHAR(50),
		@chvSTypeID				VARCHAR(50),
		@FrozeDate				DATETIME,
		@AssetBusinessTypeId	INT,
		@VerifyID				VARCHAR(50),
		@chargeOffValue			numeric(24,10)


----------------先将红冲标志置为1--------------------------------------
UPDATE dbo.Coupon_BillIndex SET RedWord=1 WHERE RedWord=0 and BillNumberId=@nBillID
IF @@ROWCOUNT=0 
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -100 --已红冲或未过账
END

SELECT  @nBillType = BillType,
		@tBillDate=BillDate,
		@bRedWord=redword,
		@szIfCheck=ifcheck,
		@chvBTypeID=btypeid,
		@chvDealBTypeID=DealBTypeID,
		@chvSTypeID=stypeid,
		@VerifyID=stypeid,
		@chargeOffValue=ChargeOffTotal
FROM	Coupon_BillIndex 
WHERE	BillNumberId=@nBillID


IF @chargeOffValue<>0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -600 --已核销
END

IF EXISTS(
		SELECT TypeID
		FROM SType
		WHERE TypeId=@chvSTypeID AND IsSelfVerify=0
	)
BEGIN
	SELECT @VerifyID=VerifyID
	FROM SType
	WHERE TypeId=@chvSTypeID
END	

--------------------得到本期开始时间 start---------------

SELECT	@szPeriod1 = StartDate
FROM	MonthProc
WHERE	MonthNo = '本期' AND STypeID=@chvSTypeID
	
--------------------得到本期开始时间 end---------------

------------------------------------------开始判断-------------------------------------------
IF GETDATE() < @szPeriod1 
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -8
END 

IF @tBillDate < @szPeriod1
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -2 --不能红冲月结前单据
END
--------------------判断冻结时间 start---------------
SET @FrozeDate=@tBillDate
SELECT	@FrozeDate =FrozeDate  FROM FrozeBusiness WHERE stypeid=@chvSTypeID

IF @tBillDate<@FrozeDate
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -705	
END

--------------------判断冻结时间 end---------------
IF @szIfCheck ='f' 
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -100 --已红冲或未过账
END

--校验
EXEC @nRet=GP_CheckBillRedWord  @nBillID,@billType
IF ISNULL(@nRet,0)<>0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN @nRet
END
-------------------------------------------判断结束-------------------------------------------------------

-----------------------------插入红单主表、明细、多账户 start--------------------------------
EXEC @nRet = Gp_RedWordInsertCouponBill @nBillID,@nNewBillID output,@nBillType,@strPTypeIDOutPut OUTPUT,@tBillDate,@etypeid

--select 3,@nRet
IF ISNULL(@nRet,0)<>0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN @nRet
END
-----------------------------插入红单主表、明细、多账户 end--------------------------------
-------------------------------插入红冲原因---------------------
UPDATE Coupon_BillIndex SET redreason = @redreason WHERE BillNumberId = @nNewBillID
----------------------------------------------------------------
	
	
-----------------------------处理关联的数据 start------------------------------------------
UPDATE	Coupon_BillIndex
SET		CompleteTotal = ISNULL(a.CompleteTotal,0) + ISNULL(b.CompleteTotal,0),
		nCompleteTotal = ISNULL(a.nCompleteTotal,0) + ISNULL(b.nCompleteTotal,0)
FROM	BillIndex a,
		(
			SELECT	GoodsBillID,MoneyBillID,SUM(CompleteTotal) AS CompleteTotal,SUM(NCompleteTotal) AS NCompleteTotal,BillType
			FROM	dbo.CompleteTotal c
			WHERE MoneyBillID = @nBillID 
			GROUP BY GoodsBillID,MoneyBillID,BillType
		)b
WHERE	a.BillNumberID = b.GoodsBillID
		AND b.MoneyBillID = @nBillID
		AND a.BillType=b.BillType
		AND a.Billtype =426
		
UPDATE	Coupon_BillIndex
SET		CompleteTotal = ISNULL(a.CompleteTotal,0) - ISNULL(b.CompleteTotal,0),
		nCompleteTotal = ISNULL(a.nCompleteTotal,0) - ISNULL(b.nCompleteTotal,0)
FROM	BillIndex a,
		(
			SELECT	GoodsBillID,MoneyBillID,SUM(CompleteTotal) AS CompleteTotal,SUM(NCompleteTotal) AS NCompleteTotal,BillType
			FROM	dbo.CompleteTotal c
			WHERE MoneyBillID = @nBillID
			GROUP BY GoodsBillID,MoneyBillID,BillType
		)b
WHERE	a.BillNumberID = b.GoodsBillID
		AND b.MoneyBillID = @nBillID
		AND a.BillType=b.BillType
		AND a.Billtype  in (423,424,425)
		
		
		
---------- 处理按单结算的收付款红冲返回问题----------------------
DELETE FROM CompleteTotal
WHERE	GoodsBillID = @nBillID
	AND  BILLTYPE IN (423,424,425,426)	-- 处理按单结算的问题,全部按单结算
--DELETE FROM CompleteGoodTotal
--WHERE (GoodsBillID = @nBillID OR MoneyBillID = @nBillID )AND  BILLTYPE IN (423,424,425,426)	
	
--优惠券分支机构调拨出入库红冲后回写分支机构内部应收金额
declare @tmpKtypeId varchar(50),@strSTypeID2 varchar(50)
SELECT @tmpKtypeId=case @nBillType when 428 then OutKtypeId when 429 then InKtypeId END from Coupon_BillIndex where BillNumberId=@nBillID
SELECT @strSTypeID2=STypeID FROM Stock WHERE typeId=@tmpKtypeId
IF @nBillType =429
BEGIN
	UPDATE A SET A.InnerARTotal=A.InnerARTotal-B.TotalMoney 
	FROM SType_InnerARTotal A INNER JOIN Coupon_BillIndex B ON A.STypeID=B.STypeID AND A.STypeID2=@strSTypeID2
	WHERE billnumberid=@nBillID
END
IF @nBillType =428
BEGIN
	UPDATE A SET A.InnerARTotal=A.InnerARTotal+B.TotalMoney 
	FROM SType_InnerARTotal A INNER JOIN Coupon_BillIndex B ON A.STypeID=B.STypeID AND A.STypeID2=@strSTypeID2
	WHERE billnumberid=@nBillID
END

--优惠券出库红冲删除引用此单的退货单
IF @nBillType=424
BEGIN

	CREATE TABLE #tempBackBillnumberid
	(
		billnumberid numeric(10,0)
	)

	IF EXISTS(SELECT TOP 1 1  
                            FROM COUPON_OUTBILL o 
                           INNER  JOIN  COUPON_BACKBILL b on o.id=b.outbillid 
                           INNER JOIN COUPON_BILLINDEX i on i.billnumberid=b.billnumberid 
                           WHERE   i.ifcheck='f' AND i.draft=1 AND i.redword=0 AND o.billnumberid=@nBillID)
   BEGIN  

		INSERT INTO #tempBackBillnumberid (
		 billnumberid 
		 )
	   SELECT i.billnumberid 
	   FROM COUPON_OUTBILL o 
	   INNER  JOIN  COUPON_BACKBILL b on o.id=b.outbillid 
	   INNER JOIN COUPON_BILLINDEX i on i.billnumberid=b.billnumberid 
	   WHERE   i.ifcheck='f' AND i.draft=1 AND i.redword=0 AND o.billnumberid=@nBillID
		   
	   DELETE b FROM COUPON_BACKBILL  b 
       WHERE EXISTS (SELECT 1 FROM  #tempBackBillnumberid t WHERE t.BillNumberId=b.BillNumberId )
                         
       
       DELETE b FROM dbo.BillMulAccount b
       WHERE b.BillType=426 
       AND EXISTS (SELECT 1 FROM  #tempBackBillnumberid t WHERE t.BillNumberId=b.BillNumberId )
						   
		DELETE b FROM dbo.Coupon_BillUsed b 
		WHERE  b.BillType=426 
		AND  EXISTS (SELECT 1 FROM  #tempBackBillnumberid t WHERE t.BillNumberId=b.BillNumberId )
		
		DELETE b FROM dbo.Coupon_BillIndex  b
		WHERE  b.BillType=426 
		AND  EXISTS (SELECT 1 FROM  #tempBackBillnumberid t WHERE t.BillNumberId=b.BillNumberId )
		
   END 
   
   DROP TABLE #tempBackBillnumberid
END

	
-----------------------------处理关联的数据 end------------------------------------------
	
------------------------------单据红冲反向插入Coupon_CodeInOut  Coupon_CodeInfo start---------------------
EXEC @nRet = Gp_RedWordInsertInOutListDetail @nBillID,@nNewBillID,@nBillType
IF ISNULL(@nRet,0)<>0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN @nRet
END
------------------------------单据红冲反向插入Coupon_CodeInOut Coupon_CodeInfo end------------------------

-- 检查账户余额，是否过账后会 < 0

EXEC @nRet = GP_AuditingATypeBalanceCheck @nNewBillID,@nBillType, @strPTypeIDOutPut output
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN 918
END 
-------------------------------listtable反算---------------------------------- 
EXEC @nRet = Gp_ModifyBAndAtype_Total @nNewBillID,@nBillType
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN RedWordPoint
	COMMIT TRAN RedWord
	RETURN -1
END
--------------------------------------------------------------------------------------------------



COMMIT TRAN RedWord
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Gp_Zc_RedWord_RepairBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Gp_Zc_RedWord_RepairBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
维修结算
*/
CREATE                                   PROCEDURE Gp_Zc_RedWord_RepairBill 
(
	@nBillID			numeric(10,0),		-- 1. 单据编号 ID 值
	@EtypeID        	varchar(50) = '00001',	-- 2. 红冲单据的操作员ID
	@strPTypeIDOutPut	varchar(50) OUTPUT,	-- 3. 返回出错商品 ID 值
	@redreason			VARCHAR(500)		---红冲原因
)
--@encode$--
AS

DECLARE	
	@nRet	INT
	
SELECT @nRet=0	

--如果存在保险理赔，三包索赔，或维修回访单，则不能进行红冲（如果是保险理赔或三包索赔的草稿，则提示用户系统会删除）
IF EXISTS(
	SELECT a.BillNumberId
	FROM Billindex_CarRepair a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	WHERE a.QuickRepairBillID=@nBillID
	AND (b.ifcheck='t' AND b.BillType IN (186,200)) 
	AND b.RedWord=0
	UNION ALL
	SELECT BillNumberId
	FROM Billindex_CarRepair
	WHERE BillNumberId=@nBillID  AND IsTalkBackOver=1

)
BEGIN
	RETURN -189
END

IF EXISTS(
	SELECT a.BillNumberId
	FROM Billindex_CarRepair a
	INNER JOIN BillIndex b
	ON a.BillNumberId=b.BillNumberId
	WHERE a.BillType IN (186,200) AND QuickRepairBillID=@nBillID
	AND b.ifcheck='f' AND b.RedWord=0
)
BEGIN
	--删除
	CREATE TABLE #ToDel(BillNumberID	INT)
	
	INSERT #ToDel
	SELECT BillNumberId
	FROM Billindex_CarRepair
	WHERE BillType IN (186,200,198) AND QuickRepairBillID=@nBillID
	
	DELETE Billindex_CarRepair
	WHERE BillNumberId IN (SELECT BillNumberId FROM #ToDel)
	
	DELETE Billindex
	WHERE BillNumberId IN (SELECT BillNumberId FROM #ToDel)
	
	DELETE QP_InsuranceBill_PType
	WHERE BillNumberId IN (SELECT BillNumberId FROM #ToDel)
	
	DELETE QP_InsuranceBill_RepairItems
	WHERE BillNumberId IN (SELECT BillNumberId FROM #ToDel)
	
	DELETE Qp_ThreePacketsBill_PType
	WHERE BillNumberId IN (SELECT BillNumberId FROM #ToDel)
	
	DELETE Qp_ThreePacketsBill_RepairItems
	WHERE BillNumberId IN (SELECT BillNumberId FROM #ToDel)
	
	
	DROP TABLE #ToDel
END



CREATE TABLE #PickingBillNumberID(BillNumberID INT)

/*
INSERT #PickingBillNumberID
SELECT DISTINCT a.BillNumberId 
FROM Qp_PickingBill a
INNER JOIN Qp_ReceptionBill_PType b
ON a.ReceptionBillId=b.ID
WHERE b.BillNumberId=@nBillID
*/
INSERT #PickingBillNumberID
SELECT a.BillNumberId
FROM Billindex_CarRepair a
INNER JOIN BillIndex b
ON a.BillNumberId=b.BillNumberId 
WHERE a.QuickRepairBillID=@nBillID
AND b.BillType=191
AND b.ifcheck='t' AND b.RedWord=0


CREATE TABLE #PickingBackBillNumberID(BillNumberID INT)

/*
INSERT #PickingBackBillNumberID
SELECT DISTINCT a.BillNumberId 
FROM Qp_PickingBackBill a
INNER JOIN Qp_PickingBill b
ON a.PickingId=b.ID
INNER JOIN Qp_ReceptionBill_PType c
ON b.ReceptionBillId=c.ID
WHERE c.BillNumberId=@nBillID
*/

INSERT #PickingBackBillNumberID
SELECT a.BillNumberId
FROM Billindex_CarRepair a
INNER JOIN Billindex_CarRepair b
ON a.QuickRepairBillID=b.BillNumberId
INNER JOIN Billindex_CarRepair c
ON b.QuickRepairBillID=c.BillNumberId
INNER JOIN BillIndex d
ON a.BillNumberId=d.BillNumberId
WHERE c.BillNumberId=@nBillID
AND d.BillType=197
AND d.ifcheck='t' AND d.RedWord=0


--冲领料退回		
DECLARE
	@intTempBillNumberID	INT


DECLARE PickingBackBillNumberID_CURSOR CURSOR FOR
SELECT	BillNumberID
FROM	#PickingBackBillNumberID

OPEN PickingBackBillNumberID_CURSOR
FETCH NEXT FROM PickingBackBillNumberID_CURSOR INTO	@intTempBillNumberID
WHILE @@FETCH_STATUS = 0 AND @nRet=0
BEGIN
	EXEC @nRet=Gp_Zc_RedWord @intTempBillNumberID,@ETypeID,1,@strPTypeIDOutPut OUT,@redreason

	FETCH NEXT FROM PickingBackBillNumberID_CURSOR INTO	@intTempBillNumberID
END
CLOSE PickingBackBillNumberID_CURSOR
DEALLOCATE PickingBackBillNumberID_CURSOR


DROP TABLE #PickingBackBillNumberID

IF @nRet<>0
BEGIN
	RETURN @nRet
END
--冲领料单
DECLARE PickingBilllNumberID_CURSOR CURSOR FOR
SELECT	BillNumberID
FROM	#PickingBillNumberID


OPEN PickingBilllNumberID_CURSOR
FETCH NEXT FROM PickingBilllNumberID_CURSOR INTO	@intTempBillNumberID
WHILE @@FETCH_STATUS = 0 AND @nRet=0
BEGIN
	EXEC @nRet=Gp_Zc_RedWord @intTempBillNumberID,@ETypeID,1,@strPTypeIDOutPut OUT,@redreason

	FETCH NEXT FROM PickingBilllNumberID_CURSOR INTO	@intTempBillNumberID
END
CLOSE PickingBilllNumberID_CURSOR
DEALLOCATE PickingBilllNumberID_CURSOR

DROP TABLE #PickingBillNumberID

IF @nRet<>0
BEGIN
    RETURN @nRet
END
--冲原单
EXEC @nRet=Gp_Zc_RedWord @nBillID,@ETypeID,1,@strPTypeIDOutPut OUT,@redreason

--删除实际领料信息
DELETE Qp_ReceptionBill_FactUsePType
WHERE ReceptionBillnumberId=@nBillID

RETURN @nRet
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GP_ZTSelect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_ZTSelect]
GO


CREATE           PROCEDURE GP_ZTSelect 
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF

create table #SystemTaleb([name]varchar(100)not null,[dbid] varchar(100) not null);
declare @deleted varchar(1)
declare @tablename varchar(100)
declare @dbid varchar(100)
declare @intexists tinyint

declare @strsql nvarchar(1000)

declare cursorname cursor 
 local scroll static 
  for  select [name],dbid from sysdatabases where [name] not in ('master','tempdb','model','msdb','ReportServer','ReportServerTempDB')
open cursorname
fetch next from cursorname
    into @tablename,@dbid
    
while @@FETCH_STATUS=0
begin
	
	select @strSql='use '+@tablename+CHAR(13)
	
	select @strSql=@strsql+'if exists(select * from dbo.sysobjects where id = object_id(N''[dbo].[a8ztinfo]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) set @intexists=1 else set @intexists=0 '	
	
	EXECUTE sp_executesql @strSql,N'@intexists tinyint OUTPUT',@intexists OUTPUT
	
	if @intexists=1
	begin
	
		select @strsql='select @deleted= Deleted from '+@tablename+'..a8ztinfo'
		

		EXECUTE sp_executesql @strSql,N'@deleted varchar(1) OUTPUT',@deleted OUTPUT
		
		
		if(@deleted='0')
			insert into #SystemTaleb values(@tablename,@dbid)
	end
	select * from #SystemTaleb
		
	fetch next from cursorname
	into @tablename,@dbid
	

end

select * from #SystemTaleb

drop table #SystemTaleb

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS(select * from dbo.sysobjects where ID=OBJECT_ID(N'HR_Img') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[HR_Img]
	(
	[typeID] [varchar](50) NULL,
	[parID] [varchar](50) NULL,
	[level] [int] NULL,
	[sonnum] [int] NULL,
	[soncount] [int] NULL,
	[delete] [bit] NULL,
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UrlImg] [varchar](100) NULL,
	[Person_ID] [int] NOT NULL,
	) 
END
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_QueryAllOperators]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IM_QueryAllOperators]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：覃雨翔	
	日期：2011-5-20
	描述：查询所有操作员
*/
CREATE PROC IM_QueryAllOperators
(
	@connString VARCHAR(1000)
)
--@encode$--
AS
  SELECT E.Typeid AS UserID,E.FullName AS UserName,E.UserCode,@connString AS connectionString FROM LoginUser LU INNER JOIN employee E ON LU.etypeid=E.Typeid
  
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_QueryMessageHistoryByUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IM_QueryMessageHistoryByUserID]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROC IM_QueryMessageHistoryByUserID
(	
	@senderID     varchar(50),
	@ReciverID    varchar(50)
)
--@encode$--
AS
   SELECT * FROM OA_Message WHERE 
  (ETypeID_SenderTypeID=@SenderID and ETypeID_ReceiverTypeID=@ReciverID) 
   or 
  (ETypeID_SenderTypeID=@ReciverID and ETypeID_ReceiverTypeID=@SenderID)
  
  GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_SaveInstantChatMessage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IM_SaveInstantChatMessage]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：覃雨翔
	日期：2011-9-16
	描述：保存即时聊天消息记录
-------------------------------------------*/
CREATE PROC IM_SaveInstantChatMessage
(
	@Content      VARCHAR(MAX),
	@SenderID     VARCHAR(50),
	@ReceiverID   VARCHAR(50),
	@MessageType  VARCHAR(50),
	@CreateDate   VARCHAR(50),
	@IsRead       INT,
	@SenderIP     VARCHAR(50),
	@ReceiverIP   VARCHAR(50)
)
--@encode$--
AS
  INSERT INTO IM_Message
         (
          Content,
          SenderID,
          ReceiverID,
          MessageType,
          CreateDate,
          IsRead,
          SenderIP,
          ReceiverIP     
         )
         VALUES
         (
          @Content,
          @SenderID,
          @ReceiverID,
          @MessageType,
          @CreateDate,
          @IsRead,
          @SenderIP,
          @ReceiverIP
         )  
      
           
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_SaveOffMessage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IM_SaveOffMessage]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：覃雨翔
	日期：2011-5-5
	描述：保存聊天消息记录
-------------------------------------------*/
CREATE PROC IM_SaveOffMessage
(
	@Content      VARCHAR(MAX),
	@SenderID     VARCHAR(50),
	@ReceiverID   VARCHAR(50),
	@MessageType  VARCHAR(50),
	@CreateDate   VARCHAR(50),
	@IsRead       INT
)
--@encode$--
AS
INSERT INTO IM_Message
     (
      Content,
      SenderID,
      ReceiverID,
      MessageType,
      CreateDate,
      IsRead     
     )
     VALUES
     (
      @Content,
      @SenderID,
      @ReceiverID,
      @MessageType,
      @CreateDate,
      @IsRead
     )  
      
           
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_SaveOffBillMessage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IM_SaveOffBillMessage]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*------------------------------------------
	作者：覃雨翔
	日期：2011-9-16
	描述：保存离线单据消息记录
-------------------------------------------*/
CREATE PROC IM_SaveOffBillMessage
(
	@Content        VARCHAR(MAX),
	@BillNumberID   VARCHAR(50),
	@Billtype       INT,
	@SenderID       VARCHAR(50),
	@ReceiverID     VARCHAR(50),
	@MessageType    VARCHAR(50),
	@CreateDate     VARCHAR(50),
	@IsRead         INT
)
--@encode$--	
AS
  INSERT INTO IM_Message
             (
              Content,
              BillNumberID,
              BillType,
              SenderID,
              ReceiverID,
              MessageType,
              CreateDate,
              IsRead
             )
             VALUES
             (
              @Content,
              @BillNumberID,
              @Billtype,
              @SenderID,
              @ReceiverID,
              @MessageType,
              @CreateDate,
              @IsRead
             )
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_SaveMessage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IM_SaveMessage]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：覃雨翔
	日期：2011-5-5
	描述：保存聊天消息记录
-------------------------------------------*/
CREATE PROC IM_SaveMessage
(
	@Content      VARCHAR(MAX),
	@SenderID     VARCHAR(50),
	@ReceiverID   VARCHAR(50),
	@MessageType  VARCHAR(50),
	@CreateDate   VARCHAR(50),
	@IsRead       INT
)
--@encode$--
AS
  INSERT INTO IM_Message
         (
          Content,
          SenderID,
          ReceiverID,
          MessageType,
          CreateDate,
          IsRead     
         )
         VALUES
         (
          @Content,
          @SenderID,
          @ReceiverID,
          @MessageType,
          @CreateDate,
          @IsRead
         )  
      
           
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IM_SaveScheduleMessage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IM_SaveScheduleMessage]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*------------------------------------------
	作者：覃雨翔
	日期：2011-9-16
	描述：保存日程消息记录
-------------------------------------------*/
CREATE PROC IM_SaveScheduleMessage
(
	@Title          VARCHAR(100),
	@Content        VARCHAR(MAX),
	@SenderID       VARCHAR(50),
	@ReceiverID     VARCHAR(50),
	@MessageType    VARCHAR(50),
	@CreateDate     VARCHAR(50),
	@IsRead         INT,
	@BillNumberID   INT
)
--@encode$--	
AS
  INSERT INTO IM_Message
             (
              Title,
              Content,
              SenderID,
              ReceiverID,
              MessageType,
              CreateDate,
              IsRead,
              BillNumberID
             )
             VALUES
             (
              @Title,
              @Content,
              @SenderID,
              @ReceiverID,
              @MessageType,
              @CreateDate,
              @IsRead,
              @BillNumberID
             )
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[InsertFr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[InsertFr]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年9月20日
-- Description:	维修故障档案添加修改
-- =============================================
CREATE PROCEDURE InsertFr 
(
	@typeid  VARCHAR(50),	---档案ID
	@action  VARCHAR(50),	---操作标志	
	@parid   VARCHAR(50),	---父节点ID
	@usercode	VARCHAR(200),---编号
	@faultexplain VARCHAR(1000),--故障描述
	@faultreason	VARCHAR(2000)---故障原因	
)
--@encode$--
AS
BEGIN
IF @action<>'modify'
BEGIN
DECLARE @nReturntype INT,
		@EtypeId_1 VARCHAR(50),
		@nSoncount INT,
		@nSonnum INT, 
		@leveal SMALLINT,
		@dbname VARCHAR(50)='frtype'
		
-- 获得新的ID号
EXEC @nReturntype=Gp_createId @ParId,@dbname,@EtypeId_1 OUT,@nSonnum OUT,@nSoncount OUT
IF @nReturntype=-1 
BEGIN
	RAISERROR('维修故障的分类不能超过10层',16,1)RETURN--return -1
END
IF @nReturntype=-2 
BEGIN
	RAISERROR('无法添加基本信息',16,1)RETURN--return -2
END
-- 判断重复的ID,UserCode
IF exists(SELECT TypeID FROM [frtype] WHERE typeId=@EtypeId_1 or (usercode=@usercode))
BEGIN
	--print '['+@usercode+']商品已存在'
	RAISERROR('编号为【%s】的记录已经存在',16,1,@usercode)RETURN--return -3
END

BEGIN TRAN insertproc
SELECT @leveal=leveal FROM frtype WHERE typeid=@Parid
SELECT @leveal=@leveal+1

INSERT INTO [frtype] 
(
	typeId,
	ParId,
	sonnum,
	soncount,
	leveal,
	UserCode,
	FaultExplain,
	FaultReason,
	XiWaMaxNumber 
)     
VALUES 
( 
	@EtypeId_1,
	@parid,
	0,
	0,
	@leveal,
	@usercode,
	@faultexplain,
	@faultreason,
	0	
)    
IF @@rowcount=0 
BEGIN
 ROLLBACK TRAN insertproc 
 RETURN -1
END 
ELSE 
BEGIN
	UPDATE frtype  SET sonnum=@nSonnum+1,soncount=@nSoncount+1 WHERE typeid=@Parid
END

--修改XiWa的XiWaMaxNumber
DECLARE @XiWaMaxNumber NUMERIC(18,0)
SELECT @XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM frtype
UPDATE frtype SET XiWaMaxNumber = @XiWaMaxNumber WHERE TypeId = @EtypeId_1

COMMIT TRAN insertproc
END
ELSE
BEGIN
--DECLARE @OldUserCode VARCHAR(200)
--SELECT @OldUserCode=UserCode FROM frtype WHERE typeId=@typeid
IF EXISTS (SELECT * FROM frtype WHERE UserCode=@usercode AND typeId<>@typeid) 
BEGIN
	RAISERROR('编号为【%s】的记录已经存在',16,1,@usercode)RETURN--return -3
END
DECLARE @XiWaMaxNumberupdate NUMERIC(18,0)
SELECT @XiWaMaxNumberupdate = Max(XiWaMaxNumber)+1 FROM frtype 
UPDATE [frtype]
SET UserCode=@usercode,FaultExplain=@faultexplain,FaultReason=@faultreason,XiWaMaxNumber=@XiWaMaxNumberupdate 
WHERE typeId=@typeid
 
END


END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsertFromBaseStocdk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[InsertFromBaseStocdk]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
横看成岭侧成峰


-- 代销库不引入进实物期初中
*/
CREATE       PROCEDURE InsertFromBaseStocdk
(
		@ktypeid	VARCHAR(50)	--当前获取仓库
)
--@encode$--
AS
SET NOCOUNT ON

IF @ktypeid <> ''
BEGIN
	DELETE FROM dbo.IniFactStocks  WHERE (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U 
	WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
	AND U.Value = 0
	AND U.STypeId =  (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = KtypeId)) = 0
	AND KtypeId in (SELECT a FROM dbo.f_split(@ktypeid, ','))
END
ELSE
BEGIN
	DELETE FROM dbo.IniFactStocks  WHERE (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U 
	WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
	AND U.Value = 0
	AND U.STypeId =  (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = KtypeId)) = 0
	AND KtypeId in (SELECT DISTINCT KtypeId FROM IniGoodsStocks)
END

DELETE FROM  dbo.IniFactStocks_Qty WHERE (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U 
WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
AND U.Value = 0
AND U.STypeId =   (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = KtypeId)) = 0

DELETE FROM  dbo.gp_iniFactPtypeSerial WHERE (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U 
WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
AND U.Value = 0
AND U.STypeId = STypeId) = 0

DECLARE @physicalsstocknegativestock int;
SELECT @physicalsstocknegativestock = Value FROM dbo.Userconfig WHERE ConfigName = 'physicalsstocknegativestock';

IF @physicalsstocknegativestock = 0 
BEGIN 
IF @ktypeid <> ''
BEGIN
	INSERT INTO dbo.IniFactStocks
			( PtypeId ,
			  KtypeId ,
			  Qty 
			)
	SELECT    PtypeId ,
			  KtypeId ,
			  dbo.F_RoundQty(SUM(Qty))
	 FROM dbo.IniGoodsStocks a
	WHERE  a.Qty >= 0 
	AND (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
	AND U.Value = 0
	AND U.STypeId =  (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = a.KtypeId)) = 0
	AND a.KtypeId IN (SELECT a FROM dbo.f_split(@ktypeid, ','))
	GROUP BY a.PtypeId, a.KtypeId
END
ELSE
BEGIN
	--实物库存选择所有仓库引入账面库存
	INSERT INTO dbo.IniFactStocks
			( PtypeId ,
			  KtypeId ,
			  Qty 
			)
	SELECT    PtypeId ,
			  KtypeId ,
			  dbo.F_RoundQty(SUM(Qty))
	 FROM dbo.IniGoodsStocks a
	WHERE  a.Qty >= 0 
	AND (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
	AND U.Value = 0
	AND U.STypeId =  (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = a.KtypeId)) = 0
	AND a.KtypeId IN (SELECT DISTINCT KtypeId FROM IniGoodsStocks)
	GROUP BY a.PtypeId, a.KtypeId
END
 
 INSERT INTO dbo.IniFactStocks_Qty
         ( PTypeID ,
           KTypeID ,
           CargoID ,
           ItemID ,
           Iscombined ,
           GoodsNumber ,
           ProduceDate ,
           ValidDate ,
           Qty ,
           NQty
         )
SELECT  PTypeID ,
           KTypeID ,
           CargoID ,
           ItemID ,
           Iscombined ,
           GoodsNumber ,
           ProduceDate ,
           ValidDate ,
           dbo.F_RoundQty( SUM(Qty) ),
           dbo.F_RoundQty( SUM(NQty) )
  FROM dbo.Ini_GOODSSTOCKS_QTY i
          WHERE i.Qty >= 0 
          AND (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
          AND U.Value = 0
          AND U.STypeId =  (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = i.KTypeID)) = 0
          AND i.KtypeId NOT IN('10000')
          GROUP BY PTypeID, KTypeID,CargoID, ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate
              
          
  INSERT INTO dbo.gp_iniFactPtypeSerial
          ( Serial ,
            KtypeID ,
            PtypeID ,
            InKtypeTime ,
            OutKtypeTime ,
            [State] ,
            Flag ,
            CommissionState ,
            ETypeID ,
            GoodsOrder ,
            GoodsNumber ,
            STypeId ,
            Comment1 ,
            ItemID ,
            IsCombined ,
            CargoID ,
            ProduceDate ,
            ValidDate
          )
SELECT Serial ,
            KtypeID ,
            PtypeID ,
            (select convert(varchar(10),getdate(),120)),
            OutKtypeTime ,
            CASE WHEN [State]  = 7 THEN 1 ELSE [State] END ,
            Flag ,
            CommissionState ,
            ETypeID ,
            GoodsOrder ,
            GoodsNumber ,
            STypeId ,
            Comment1 ,
            ItemID ,
            IsCombined ,
            CargoID ,
            ProduceDate ,
            ValidDate
  FROM gp_initPtypeSerial b
WHERE  ((SELECT SUM(a.Qty) FROM dbo.Ini_GOODSSTOCKS_QTY a WHERE  a.Ptypeid = b.PtypeID AND a.KTypeID = b.KtypeID) >= 0)
AND  (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U 
WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
AND U.Value = 0
AND U.STypeId = b.STypeId) = 0
AND b.KtypeId NOT IN('10000')
AND b.State IN(1)

INSERT INTO dbo.gp_iniFactPtypeSerial
          ( Serial ,
            KtypeID ,
            PtypeID ,
            InKtypeTime ,
            OutKtypeTime ,
            [State] ,
            Flag ,
            CommissionState ,
            ETypeID ,
            GoodsOrder ,
            GoodsNumber ,
            STypeId ,
            Comment1 ,
            ItemID ,
            IsCombined ,
            CargoID ,
            ProduceDate ,
            ValidDate
          )
SELECT Serial ,
            KtypeID ,
            PtypeID ,
            (select convert(varchar(10),getdate(),120)),
            OutKtypeTime ,
            CASE WHEN [State]  = 7 THEN 1 ELSE [State] END ,
            Flag ,
            CommissionState ,
            ETypeID ,
            GoodsOrder ,
            GoodsNumber ,
            STypeId ,
            Comment1 ,
            ItemID ,
            IsCombined ,
            CargoID ,
            ProduceDate ,
            ValidDate
  FROM gp_initPtypeSerial b
WHERE  ((SELECT SUM(a.Qty) FROM Ini_GOODSSTOCKS_QTY a WHERE  a.Ptypeid = b.PtypeID AND a.KTypeID = b.KtypeID) >= 0)
AND  (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U 
WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
AND U.Value = 0
AND U.STypeId = b.STypeId) = 0
AND b.KtypeId NOT IN('10000')
AND B.State IN (7)

END
ELSE BEGIN
IF @ktypeid <> ''
BEGIN
	INSERT INTO dbo.IniFactStocks
			( PtypeId ,
			  KtypeId ,
			  Qty
			)
	SELECT    PtypeId ,
			  KtypeId ,
			  dbo.F_RoundQty( SUM(Qty)) 
	 FROM dbo.IniGoodsStocks a WHERE  
	 (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
	AND U.Value = 0
	AND U.STypeId =  (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = a.KtypeId)) = 0 
	AND a.KtypeId IN (SELECT a FROM dbo.f_split(@ktypeid, ','))
	AND a.KtypeId NOT IN('10000')
	GROUP BY PtypeId,KtypeId
END
ELSE
BEGIN
	--实物库存选择所有仓库引入账面库存
	INSERT INTO dbo.IniFactStocks
			( PtypeId ,
			  KtypeId ,
			  Qty
			)
	SELECT    PtypeId ,
			  KtypeId ,
			  dbo.F_RoundQty( SUM(Qty)) 
	 FROM dbo.IniGoodsStocks a WHERE  
	 (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
	AND U.Value = 0
	AND U.STypeId =  (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = a.KtypeId)) = 0 
	AND a.KtypeId IN (SELECT DISTINCT KtypeId FROM IniGoodsStocks)
	AND a.KtypeId NOT IN('10000')
	GROUP BY PtypeId,KtypeId
END
 
 INSERT INTO dbo.IniFactStocks_Qty
         ( PTypeID ,
           KTypeID ,
           CargoID ,
           ItemID ,
           Iscombined ,
           GoodsNumber ,
           ProduceDate ,
           ValidDate ,
           Qty ,
           NQty
         )
SELECT  PTypeID ,
           KTypeID ,
           CargoID ,
           ItemID ,
           Iscombined ,
           GoodsNumber ,
           ProduceDate ,
           ValidDate ,
            dbo.F_RoundQty(SUM(Qty)),
           dbo.F_RoundQty(SUM(NQty)) 
  FROM dbo.Ini_GOODSSTOCKS_QTY i
  WHERE (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
          AND U.Value = 0
          AND U.STypeId =  (SELECT TOP 1 g.STypeId FROM dbo.Stock g WHERE g.typeID = i.KTypeID)) = 0
          AND i.KtypeId NOT IN('10000')
  GROUP BY PTypeID, KTypeID,CargoID, ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate
  
  INSERT INTO dbo.gp_iniFactPtypeSerial
          ( Serial ,
            KtypeID ,
            PtypeID ,
            InKtypeTime ,
            OutKtypeTime ,
            [State] ,
            Flag ,
            CommissionState ,
            ETypeID ,
            GoodsOrder ,
            GoodsNumber ,
            STypeId ,
            Comment1 ,
            ItemID ,
            IsCombined ,
            CargoID ,
            ProduceDate ,
            ValidDate
          )
SELECT Serial ,
            KtypeID ,
            PtypeID ,
            (select convert(varchar(10),getdate(),120)),
            OutKtypeTime ,
            [State] ,
            Flag ,
            CommissionState ,
            ETypeID ,
            GoodsOrder ,
            GoodsNumber ,
            STypeId ,
            Comment1 ,
            ItemID ,
            IsCombined ,
            CargoID ,
            ProduceDate ,
            ValidDate
  FROM gp_initPtypeSerial b
  WHERE (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U 
WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
AND U.Value = 0
AND U.STypeId = b.STypeId) = 0
AND B.State IN (1)
AND b.KtypeId NOT IN('10000')

INSERT INTO dbo.gp_iniFactPtypeSerial
          ( Serial ,
            KtypeID ,
            PtypeID ,
            InKtypeTime ,
            OutKtypeTime ,
            [State] ,
            Flag ,
            CommissionState ,
            ETypeID ,
            GoodsOrder ,
            GoodsNumber ,
            STypeId ,
            Comment1 ,
            ItemID ,
            IsCombined ,
            CargoID ,
            ProduceDate ,
            ValidDate
          )
SELECT Serial ,
            KtypeID ,
            PtypeID ,
            (select convert(varchar(10),getdate(),120)),
            OutKtypeTime ,
            CASE WHEN [State]  = 7 THEN 1 ELSE [State] END ,
            Flag ,
            CommissionState ,
            ETypeID ,
            GoodsOrder ,
            GoodsNumber ,
            STypeId ,
            Comment1 ,
            ItemID ,
            IsCombined ,
            CargoID ,
            ProduceDate ,
            ValidDate
  FROM gp_initPtypeSerial b
WHERE  ((SELECT SUM(a.Qty) FROM Ini_GOODSSTOCKS_QTY a WHERE  a.Ptypeid = b.PtypeID AND a.KTypeID = b.KtypeID) >= 0)
AND  (SELECT top 1 U.Value FROM SType_Config C,SType_UserConfig U 
WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' 
AND U.Value = 0
AND U.STypeId = b.STypeId) = 0
AND B.State IN (7)
AND b.KtypeId NOT IN('10000')
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IntToStr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IntToStr]
GO














/****** Object:  Stored Procedure dbo.IntToStr    Script Date: 2002-6-20 10:14:53 ******/

CREATE  PROCEDURE IntToStr
(
 @nInput int,
 @szId varchar(5) output
)
--@encode$--
AS
set nocount on
if @nInput>99999 
begin
 return -1
end
declare @sztemp varchar(6)
select @sztemp=str(@nInput)+100000
select @szId=right(@sztemp,5)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvalidAllPriceBaseDataById]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[InvalidAllPriceBaseDataById]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE InvalidAllPriceBaseDataById
(
	@pricebillindexid		varchar(50)     ='',
	@deletedr               varchar(50)     =''
)
--@encode$--
AS
SET NOCOUNT ON 

--先修改主表的状态
UPDATE PriceBillIndex SET [State]=3 WHERE ID=@pricebillindexid
--在将子表的信息转移至作废信息表
INSERT INTO PriceDetailDeleted([PriceBillIndexID]
      ,[State]
      ,[Ptypeid]
      ,[FreeID]
      ,[IsCombined]
      ,[UnitId]
      ,[PriceStyle]
      ,[Price]
      ,[Discount]
      ,[DiscountPrice]
      ,[TaxPrice]
      ,[Tax]
      ,[BeforeRetailPrice]
      ,[IsPriceControl]
      ,[Comment]
      ,[Checke]
      ,[Checker]
      ,[VaildDate]
      ,[CreateDate]
      ,[DeletedDate]
      ,[DeletedR]
      ,[SortID])
      SELECT [PriceBillIndexID]
      ,3
      ,[Ptypeid]
      ,[FreeID]
      ,[IsCombined]
      ,[UnitId]
      ,[PriceStyle]
      ,[Price]
      ,[Discount]
      ,[DiscountPrice]
      ,[TaxPrice]
      ,[Tax]
      ,[BeforeRetailPrice]
      ,[IsPriceControl]
      ,[Comment]
      ,[Checke]
      ,[Checker]
      ,[VaildDate]
      ,[CreateDate]
      ,[DeletedDate]
      ,[DeletedR]
      ,[SortID]
      FROM PriceDetail PD WHERE PD.PriceBillIndexID=@pricebillindexid
--在将子表信息删除
DELETE FROM  PriceDetail  WHERE PriceBillIndexID=@pricebillindexid
update PriceBillIndex set [state]=3 WHERE ID=@pricebillindexid
update PriceDetailDeleted set [DeletedR]=@deletedr,[DeletedDate]=GETDATE()  WHERE PriceBillIndexID=@pricebillindexid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IsBTypeAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[IsBTypeAll]
GO











CREATE  PROCEDURE IsBTypeAll    --是否客户供货商统一
(
    @IsBTypeAll bit output
)
--@encode$--
AS
SET NOCOUNT ON 
select @IsBTypeAll=value from UserConfig where ConfigName='BTypeAll'










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** 对象:  Table [dbo].[StockTotalConfig]    脚本日期: 05/05/2010 14:49:31 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[KinOutStockConfig]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[KinOutStockConfig](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ETypeId] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[BillTypes] [varchar](200) COLLATE Chinese_PRC_CI_AS NULL,
		[Shownqty] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[Showinstock] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[Showoutstock] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL,
		[Showstock] [varchar](10) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]


END
GO

------------------------------------------表修改区域开始-------------------------------------------------


------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------
------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
------------------------------------------创建索引区域结束-----------------------------------------------




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MainProCXCheckPower]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[MainProCXCheckPower]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE MainProCXCheckPower   
(           
	@etypeid   varchar(25),  
	@ModuleId  varchar(10),  
	@ActionId  varchar(10)  
)  
--@encode$--
AS  
   RETURN 1
    /*if exists(select 1 from PosCxEPowerView where etypeid=@etypeid and ModuleId=@ModuleId and ActionId=@ActionId)   
       return 1  
    else    
       return 0  */ 
  
  


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ManulComparePrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].ManulComparePrice
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-23
	描述：请购生单手动比价
*/

CREATE PROCEDURE ManulComparePrice 
(
	@billidlist			VARCHAR(100),	--单据ID集合
	@btypeid			VARCHAR(100),
	@tax				 NUMERIC(24, 10) ,
	@discount			 NUMERIC(24, 10) ,
	@discountprice		 NUMERIC(24, 10) 
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRANSACTION  DEL

IF @discount IS  NULL
	SET @discount=-1
UPDATE	dbo.RequestBill
SET		ComparePrice=dbo.F_RoundPrice(@discountprice/MUnitRate),
		comparetax=dbo.F_RoundTax(@tax),
		comparediscount=dbo.F_RoundDiscount(CASE @discount WHEN -1 THEN 1 ELSE @discount END),
		btypeid2=@btypeid,
		state=7
WHERE  ID IN (SELECT * FROM DBO.f_split(@billidlist,','))
					
IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('比价失败！',16,1)
END

COMMIT TRANSACTION  DEL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[NotUsePriceRule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[NotUsePriceRule]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则删除
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE NotUsePriceRule
(
	@deletestate	int	output,
	@billindex varchar(max),
	@userid varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN TRANSACTION
update PriceRule set  DeletedR=@userid ,DeletedDate=GETDATE(),[State]=3 where ID=@billindex
  delete PriceRulePriority where PriceRuleID=@billindex
IF @@error <> 0  --发生错误
   BEGIN
   set @deletestate=0
     ROLLBACK TRANSACTION
   END
ELSE
   BEGIN
     COMMIT TRANSACTION
     set   @deletestate=1
   END  
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Gp_UpdateOMBackBillQty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Gp_UpdateOMBackBillQty]
GO



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*	
		hanlin
		OM商品退货回写
*/



CREATE  PROCEDURE [dbo].Gp_UpdateOMBackBillQty
(
	@billnumberid int
)
--@encode$--
AS
SET NOCOUNT ON

	IF NOT EXISTS(SELECT 1 FROM dbo.saleBackBill WHERE BillNumberId=@billnumberid AND OMBillID<>0)
		RETURN

	IF EXISTS(
			SELECT 1 FROM dbo.OM_BackOrderDetail a
			INNER JOIN dbo.saleBackBill b
			ON a.ID=b.OMBillID
			WHERE b.BillNumberId=@billnumberid
			AND a.[STATUS] IN(1,2) 
		)
	BEGIN
		RAISERROR('单据所引用的OM单据有明细已中止或者已完成，请刷新OM单据列表后重新生成退货单！',16,1)
		RETURN
	END


	
	
	--审核通过的退货单数量大于或等于前台退货单数量为完成状态2 否则为状态'已开单未完成' 3
    UPDATE dbo.OM_BackOrderDetail SET ReachQty=(ReachQty+s.mqty),
							[STATUS]=(CASE WHEN ReachQty+s.mqty >= OM_BackOrderDetail.qty THEN 2 ELSE 3 END) FROM dbo.saleBackBill  s
    WHERE s.OMBillID=OM_BackOrderDetail.ID and s.billnumberid=@billnumberid
    
 
	IF @@ERROR <>0
		RAISERROR('回写OM退货数量失败！',16,1)
		
	

GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[OM_GetProductList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[OM_GetProductList]
GO

/****** Object:  StoredProcedure [dbo].[OM_GetProductList]    Script Date: 04/26/2012 19:11:33 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		丁超
-- Create date: 2011年12月22日
-- Description:	产品分页存储过程
-- =============================================
CREATE PROCEDURE [dbo].[OM_GetProductList]
	@PageNo        	int,  --页号,
	@PageSize       int, --每页显示数
	@Typeid         VARCHAR(5000)
--@encode$--
AS
BEGIN




DECLARE @RowCount int
DECLARE @SQL VARCHAR(MAX)
DECLARE @UserDeRowCount	int
DECLARE @PageNum int
DECLARE @PageBegin int
DECLARE @PageEnd int

SET @UserDeRowCount=@PageSize

IF @UserDeRowCount = 0
SET @UserDeRowCount = 14

IF @Typeid = '00000'
SET @Typeid = ''

-- 求总记录数的语句
SELECT @RowCount=count(*) from (select row_number() over(order by typeid) as id, * from OM_Ptype WHERE  PtypeClass_ID like ''+@Typeid+'%' )as t3
SET @PageNum =@PageNo *@UserDeRowCount
SET @PageBegin=(@PageNo-1)*@UserDeRowCount+1
SET @PageEnd=(@PageNo)*@UserDeRowCount

SET @SQL='
WITH [OM_Ptype ORDER BY typeid] AS 
(
SELECT ROW_NUMBER() OVER(ORDER BY typeid) AS id, * 
FROM OM_Ptype WHERE PtypeClass_ID LIKE '''+@Typeid+'%'' 
) 
SELECT t1.ptypeid, t3.usercode,t3.fullname,'+Convert(VARCHAR(100),@RowCount)+' AS totalNum , t2.type,pic,t2.imgurl ,t1.IsSave
FROM [OM_Ptype ORDER BY typeid] t1 
LEFT JOIN PType_Picture t2 ON t1.ptypeid = t2.ptypeid
INNER JOIN Ptype t3 ON t1.ptypeid = t3.typeid  
WHERE t1.id>='+CONVERT(VARCHAR(10),@PageBegin) +' AND t1.id<='+CONVERT(VARCHAR(10),@PageEnd)
EXEC(@SQL)
END

GO







/*
Created by zteng 2014-06-09 缓存操作员二开应用权限
*/
/****** Object:  StoredProcedure [dbo].[Ord_CahcePlugLimit]    Script Date: 06/09/2014 15:26:25 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ord_CahcePlugLimit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Ord_CahcePlugLimit]
GO


/****** Object:  StoredProcedure [dbo].[Ord_CahcePlugLimit]    Script Date: 06/09/2014 15:26:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[Ord_CahcePlugLimit]
(
	@PlugID INT
)
AS
BEGIN
	DELETE FROM Ord_CahcePlugLimitData WHERE plugid=@PlugID	

	INSERT INTO Ord_CahcePlugLimitData
		(   [PlugID]
		   ,[ETypeID]
		   ,[Lim]
		   ,[QXEnum]
		   ,[QXName]
		   ,[LimitType]
		   ,[Name]
		   ,[NameSpaceAndClass]
		   ,[NeedLoadAssembly]
		   ,[WebMenuName])           
	SELECT @PlugID
		   ,[ETypeID]
		   ,[Lim]
		   ,[QXEnum]
		   ,[QXName]
		   ,[LimitType]
		   ,[Name]
		   ,[NameSpaceAndClass]
		   ,[NeedLoadAssembly]
		   ,[webmenuname]
		  FROM (
		SELECT a.EtypeId,a.Lim,b.QXEnum,b.QXName,b.limittype,c.Name,c.NameSpaceAndClass,c.NeedLoadAssembly,c.webmenuname FROM Ord_PlugLimitFooting a
			INNER JOIN dbo.Ord_LimitList b ON a.LimitId=b.Id
			INNER JOIN Ord_PopUpPage c ON (b.plugmenuid=c.Id)
			WHERE a.EtypeId<>'00001' AND a.plugid=@PlugID
		UNION ALL	
		SELECT a.EtypeId,a.Lim,b.QXEnum,b.QXName,b.limittype,'' AS NAME,'' AS NameSpaceAndClass,'' AS NeedLoadAssembly,'' AS webmenuname FROM Ord_PlugLimitFooting a
			INNER JOIN dbo.Ord_LimitList b ON a.LimitId=b.Id 
			WHERE a.EtypeId<>'00001' AND a.plugid=@PlugID AND b.plugmenuid IS NULL
	)t	
	
END

GO






/*
Created by zteng 2014-06-09 恢复操作员二开权限
*/

/****** Object:  StoredProcedure [dbo].[Ord_ResotryPlugLimit]    Script Date: 06/09/2014 15:27:24 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ord_ResotryPlugLimit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Ord_ResotryPlugLimit]
GO


/****** Object:  StoredProcedure [dbo].[Ord_ResotryPlugLimit]    Script Date: 06/09/2014 15:27:24 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[Ord_ResotryPlugLimit]
(
	@PlugID INT
)
--@encode$--
AS
BEGIN
	DECLARE @ETypeID VARCHAR(50),
			@Lim INT,
			@QxEnum VARCHAR(200),
			@QxName VARCHAR(200),
			@LimitType INT,
			@Name VARCHAR(200),
			@NameSpaceAndClass VARCHAR(500),
			@NeedLoadAssembly VARCHAR(500),
			@WebMenuName VARCHAR(500),
			@LimitID INT
	DECLARE myCur CURSOR FOR SELECT 
					[ETypeID]
				   ,[Lim]
				   ,[QXEnum]
				   ,[QXName]
				   ,[LimitType]
				   ,[Name]
				   ,[NameSpaceAndClass]
				   ,[NeedLoadAssembly]
				   ,[WebMenuName] 
		   FROM Ord_CahcePlugLimitData WHERE plugid=@PlugID
	OPEN myCur
	FETCH NEXT FROM myCur INTO @ETypeID,@Lim,@QxEnum,@QxName,@LimitType,@Name,@NameSpaceAndClass,@NeedLoadAssembly,@WebMenuName
	WHILE(@@FETCH_STATUS=0)
	BEGIN
	
		SET @LimitID=-1
		IF(@Name='' AND @NameSpaceAndClass='' AND @NeedLoadAssembly='' AND @WebMenuName='') --表示为权限点
		BEGIN
			SELECT @LimitID=Id FROM  dbo.Ord_LimitList b 
				WHERE  b.QXName=@QxName AND b.QXEnum=@QxEnum
					AND b.limittype=@LimitType AND b.plugid=@PlugID		
		END
		ELSE
		BEGIN
			SELECT @LimitID=b.Id FROM  dbo.Ord_LimitList b 
					INNER JOIN Ord_PopUpPage c ON (b.plugmenuid=c.Id)
				WHERE  b.QXName=@QxName AND b.QXEnum=@QxEnum
					AND b.limittype=@LimitType AND b.plugid=@PlugID
					AND c.Name=@Name AND c.NameSpaceAndClass=@NameSpaceAndClass
					AND c.NeedLoadAssembly=@NeedLoadAssembly AND c.webmenuname=@WebMenuName
					
		END		
		IF(@LimitID IS NOT NULL AND @LimitID!=-1)
		BEGIN
			INSERT INTO dbo.Ord_PlugLimitFooting
				        ( plugid, LimitId, EtypeId, Lim )
				VALUES  ( @PlugID, -- plugid - int
				          @LimitID, -- LimitId - int
				          @ETypeID, -- EtypeId - varchar(50)
				          @Lim  -- Lim - int
				          )
		END
				          
		FETCH NEXT FROM myCur INTO @ETypeID,@Lim,@QxEnum,@QxName,@LimitType,@Name,@NameSpaceAndClass,@NeedLoadAssembly,@WebMenuName
	END
	CLOSE myCur
	DEALLOCATE myCur
	
	DELETE FROM Ord_CahcePlugLimitData WHERE plugid=@PlugID
END

GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_Bas_SaveGoodsType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_Bas_SaveGoodsType]
GO




/*
	功能:保存或者修改商品类别
	时间:2016-05-06
	作者:魏伟
	DROP PROC P_Bas_SaveGoodsType
	EXEC P_Bas_SaveGoodsType '00002','ss','ss','3','','a'
*/
CREATE PROCEDURE P_Bas_SaveGoodsType
(
	@typeId			    VARCHAR(50),
	@UserCode			VARCHAR(200),
	@FullName			VARCHAR(200),
	@Parid      		VARCHAR(200), 
	@Leveal             INT,
	@Comment			VARCHAR(500),
	@optype				VARCHAR(10)
)
--@encode$--
AS
SET NOCOUNT ON

declare @oldparid VARCHAR(50),
		@oldtypeid VARCHAR(50),
		@oldlevel int,
		@nReturntype INT,
		@categorytypeId_new [varchar](50),
		@nSoncount INT,
		@nSonnum INT,
		@dbname [VARCHAR](30),
		@pSoncount INT,
		@pSonnum INT,
		@newleveal INT

IF @optype = 'm' ---修改
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM PTypeCategory WHERE FullName = @FullName AND typeId <> @typeId)
	BEGIN
		RAISERROR('名称已存在，请修改后再保存。',16,1) 
		RETURN
	END
	ELSE IF EXISTS(SELECT TOP 1 1 FROM PTypeCategory WHERE UserCode = @usercode AND typeId <> @typeId)
	BEGIN
		RAISERROR('编号已存在，请修改后再保存。',16,1) 
		RETURN
	END
	ELSE
		BEGIN
							
			--获取原来父类ID,旧typeid
			select @oldparid=parid,@oldlevel=Leveal from PTypeCategory where typeId = @typeId 
			set @oldtypeid=@typeId
			
			--获取总的soncount  sonum,createid 要改动 ，等下还原
			select @pSoncount=soncount from PTypeCategory where typeId = '00000' 
			
			if @Parid=''
				set @Parid='00000'
				
			IF @Parid<>@oldparid
			BEGIN
				-- 获得新的ID号
				SET @dbname='PTypeCategory'
				
				EXEC @nReturntype= Gp_createId @Parid, @dbname, @categorytypeId_new OUT,
				@nSonnum OUT, @nSoncount OUT
				
				 IF @nReturntype=-1
				 begin 
					RAISERROR('商品类别的分类不能超过10层',16,1)return--return -1
				 end
				 
				IF @nReturntype=-2 
				begin
					RAISERROR('无法添加商品类别',16,1)return--return -2
				end
				
				--获取新父类level	
				select @newleveal=isnull(Leveal,0) from PTypeCategory where typeId = @Parid
				
				--level 变化幅度,用于更改子类leval
				declare @levelcreasement int
				set @levelcreasement=@newleveal-@oldlevel+1
				
				--更新当前typeid 到新的id
				UPDATE	PTypeCategory
				SET		FullName = @FullName,
						Comment = @Comment,
						UserCode=@UserCode,
						Leveal=@newleveal+1 ,
						parid=@Parid,
						typeId=@categorytypeId_new
				WHERE	typeId = @typeId
				
				--更新所有子类ID
				update PTypeCategory set typeid=stuff(typeid,1,len(@typeId),@categorytypeId_new),parid=stuff(parid,1,len(@typeId),@categorytypeId_new),Leveal=Leveal+@levelcreasement where typeid like @typeId+'%'
				
				--更新原父类 soncount,sonnum -1
				UPDATE PTypeCategory SET soncount=soncount-1,sonnum=sonnum-1 WHERE typeId = @oldparid and @oldparid<>'00000'
				
				--更新新父类 soncount,sonnum +1
				UPDATE PTypeCategory SET soncount=soncount+1,sonnum=sonnum+1 WHERE typeId = @Parid
				
				--更新商品档案引用的ptypecategoryid,子类ptypecategoryid
				update ptype set ptypecategoryid=stuff(ptypecategoryid,1,len(@typeId),@categorytypeId_new) where ptypecategoryid like @typeId+'%'
				
				--还原SONNUM,SONCOUNT 总数没有变
				select @pSonnum=count(*) from PTypeCategory where parid='00000'
				update PTypeCategory set soncount =@pSoncount,sonnum=@pSonnum where typeId = '00000'  
				
			END
			ELSE --未更换父类
			BEGIN
				UPDATE	PTypeCategory
				SET		FullName = @FullName,
						Comment = @Comment,
						UserCode=@UserCode	
				WHERE	typeId = @typeId
			END
		END
END 

IF @optype = 'a'---新增
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM PTypeCategory WHERE UserCode = @UserCode)
	BEGIN
		RAISERROR('编号已存在，请修改后再保存。',16,1) 
		RETURN
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM PTypeCategory WHERE FullName = @FullName)
	BEGIN
		RAISERROR('名称已存在，请修改后再保存。',16,1)
		RETURN
	END 
	
	if @Parid=''
		set @Parid='00000'
		 
	-- 获得新的ID号
	SET @dbname='PTypeCategory'
	
	EXEC @nReturntype= Gp_createId @Parid, @dbname, @categorytypeId_new OUT,
	@nSonnum OUT, @nSoncount OUT
	
	 IF @nReturntype=-1
	 begin 
		RAISERROR('商品类别的分类不能超过10层',16,1)return--return -1
	 end
	 
	IF @nReturntype=-2 
	begin
		RAISERROR('无法添加商品类别',16,1)return--return -2
	end
	
	--获取新父类level
	select @newleveal=isnull(Leveal,0) from PTypeCategory where typeId = @Parid
	
	INSERT INTO PTypeCategory(typeId,parid,soncount,sonnum,leveal,UserCode,FullName,Comment)
	VALUES(
		@categorytypeId_new,	
		@Parid,
	    0,
	    0,
		@newleveal+1,
		@UserCode,
		@FullName,
		@Comment		
	)
	
	UPDATE  PTypeCategory
	SET     sonnum = @nSonnum + 1,
			soncount = @nSoncount + 1
	WHERE   typeid = @ParId
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_MF_AC_CheckVoucher_CommonBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_MF_AC_CheckVoucher_CommonBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：李灏龙
	日期：2016年5月18日 17:08:56
	描述：用以检测凭证
*/
CREATE PROCEDURE P_MF_AC_CheckVoucher_CommonBill
(
	@verifyid		VARCHAR(50),			--独立分支机构
	@VoucherBillId	INT = 0
)
--@encode$--
AS
SET NOCOUNT ON

--存储生成结果
CREATE TABLE #Result
(
	txt			VARCHAR(1000),
	flag		INT
)

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherBillId) 
BEGIN
	INSERT #Result(txt,flag)
	VALUES('【单据生成凭证所有金额为0，无法生成或不需生成会计凭证】',-12)
	
	SELECT * FROM #Result
	RETURN
END

--有科目被停用
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill T1 INNER JOIN dbo.Ac_Account T2 ON T1.atypeid = T2.TypeId AND T2.StypeId = @Verifyid AND Deleted = 1 WHERE T1.BillNumberId = @VoucherBillId)
BEGIN
	INSERT #Result(txt,flag)
	VALUES('【生成凭证中有会计科目被停用】',-10)
END


--有空科目或借贷不平或辅助核算有空值或原币存在0值（币种不符），返回数据
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherBillId AND ATypeId = '') 
BEGIN
	INSERT #Result(txt,flag)
	VALUES('【存在凭证明细科目获取失败】',-1)
END

/*
IF @lendtotal <> @loantotal
BEGIN
	SET @szPID += '【生成的凭证借贷不平衡】'
	SET @flag = -2 
	INSERT #Result(txt,flag)
	VALUES('【生成的凭证借贷不平衡】',-2)
END
*/
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill WHERE ISNULL(atypeid,'') = '' AND BillNumberId = @voucherBillId)--项目对应的科目不全
BEGIN
	INSERT #Result(txt,flag)
	VALUES('【存在项目未设置对应科目】',-3)
END
/*
IF EXISTS(SELECT TOP 1 1 FROM #tmpAssit WHERE TypeId = '') AND @Billtype NOT IN (116,115,128,129)
BEGIN
	SET @szPID +='【辅助核算获取异常】'
	SET @flag = -4	
	INSERT #Result(txt,flag)
	VALUES('【存在凭证明细科目获取失败】',-1)
END

IF EXISTS(SELECT TOP 1 1 FROM #TmpDetailsAssit WHERE typeid = '') AND @Billtype IN (116,115,128,129)
BEGIN
	SET @szPID +='【辅助核算获取异常】'
	SET @flag = -4	
	INSERT #Result(txt,flag)
	VALUES('【存在凭证明细科目获取失败】',-1)
END
*/
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherBillId AND FDebitTotalFor = 0 AND FCreditTotalFor = 0)
BEGIN
	INSERT #Result(txt,flag)
	VALUES('【凭证模板中有会计科目外币核算与单据币种不符】',-5)
END

/*	--非手工科目有辅助核算而模板没有时，报错
IF EXISTS(
			SELECT TOP 1 1
			FROM #tmpBillID a
				INNER JOIN #tmpRow b ON a.rowno = b.rowno
				INNER JOIN dbo.Ac_Auditing_Template_Detail c ON b.atdid = c.AtdId
				INNER JOIN dbo.Ac_Account d ON a.atypeid = d.TypeId AND d.StypeId = @verifyid
				INNER JOIN dbo.Ac_Account_Assist_CheckItems e ON (d.TypeId = e.ATypeId AND d.StypeId = e.STypeId)
		)
		AND NOT EXISTS(
			SELECT TOP 1 1 
			FROM #tmpBillID a
				INNER JOIN #tmpRow b ON a.rowno = b.rowno
				INNER JOIN dbo.Ac_Auditing_Template_Detail c ON b.atdid = c.AtdId
				INNER JOIN dbo.Ac_Auditing_Template_Detail_Assist_CheckItems d ON c.AtdId = d.AtdId
		)
BEGIN
	SET @szPID +='【凭证模板中，科目来源为非手工选择的明细未设置辅助核算】'
	SET @flag = -6
	INSERT #Result(txt,flag)
	VALUES('【存在凭证明细科目获取失败】',-1)
END
*/
	--未取到辅助核算值
IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId = @voucherbillid AND ISNULL(TypeId,'') = '') 
BEGIN
	INSERT #Result(txt,flag)
	VALUES('【生成的凭证中辅助核算存在空值】',-7)
END

		
--异常的生成明细辅助核算与科目辅助核算不匹配
SELECT DISTINCT a.ATypeId,b.Ascids
INTO #tmpCheckAscids
FROM dbo.Ac_Voucher_Bill a
INNER JOIN dbo.Ac_Account_Assist_CheckItems b ON a.ATypeId = b.ATypeId AND a.STypeId = b.STypeId
WHERE a.BillNumberId = @voucherbillid

SELECT DISTINCT a.ATypeId,c.AscIds
INTO #tmpActualAscids
FROM dbo.Ac_Voucher_Bill a 
INNER JOIN dbo.Ac_Voucher_Bill_Assist_CheckItems b ON a.ID = b.vBId
INNER JOIN dbo.Ac_Assist_CheckItems c ON b.typeName = c.UserCode
WHERE a.BillNumberId = @voucherbillid

DECLARE @countC INT,@countA INT

SELECT @countC = COUNT(*)
FROM #tmpCheckAscids

SELECT @countA = COUNT(*)
FROM #tmpActualAscids a
INNER JOIN #tmpCheckAscids b ON a.ATypeId = b.ATypeId AND a.AscIds = b.Ascids


IF @countA <> @countC
BEGIN
	INSERT #Result(txt,flag)
	VALUES('【存在凭证明细辅助核算与对应科目辅助核算不匹配】',-8)
END

DROP TABLE #tmpCheckAscids,#tmpActualAscids

IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'acpitdataflow' AND SubValue = 1)--必填现金流量
BEGIN
	DECLARE @countJie  NUMERIC(24, 10) ,@countDai  NUMERIC(24, 10) 

	SELECT @countJie = SUM(FDebitTotal),@countDai = SUM(FCreditTotal)
	FROM dbo.Ac_Voucher_Bill a
	INNER JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND a.STypeId = b.StypeId
	WHERE BillNumberId = @voucherBillid AND (b.IsBank = 1 OR b.IsCash = 1 OR b.IsOther = 1)
	
	IF @countJie <> @countDai 
	BEGIN
		INSERT #Result(txt,flag)
		VALUES('【配置要求填写现金流量】',-9)
	END
END

SELECT * FROM #Result

DROP TABLE #Result




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_MF_AC_CreateVoucherDetail_CommonBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_MF_AC_CreateVoucherDetail_CommonBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：李灏龙
	日期：2016年5月16日 17:03:21
	描述：用以生成凭证明细
*/
CREATE PROCEDURE P_MF_AC_CreateVoucherDetail_CommonBill
(
	@BillNumberId	VARCHAR(MAX),			-- 单据编号
	@szCheckMan		VARCHAR(50),			-- 制单人ID值
	@verifyid		VARCHAR(50),			--独立分支机构
	@BillType		INT,					--单据类型
	@FYear			INT,
	@FPeriod		INT,
	@AtId			INT = 0,				-- 凭证模版ID
	@VoucherBillId	INT = 0,
	@IfCommission	INT = 0				-- 是否提成单311 0.不是 1.是
)
--@encode$--
AS
SET NOCOUNT ON

--因为后面多次使用到SELECT a FROM dbo.f_split(@BillNumberId,',')，所以这里创建一个临时表来存值
CREATE TABLE #BillNumberId
(
	a	NUMERIC(18,0)
)
INSERT INTO #BillNumberId(a)
SELECT a FROM dbo.f_split(@BillNumberId,',')

--存储待处理单据编号及相关数据
CREATE TABLE #TmpBillInfo
(
	RowIndex		INT IDENTITY(1,1),	--行号
	BillNumberId	INT,				--单据编号
	StypeId			VARCHAR(50),		--分支机构ID
	VerifyStypeid	VARCHAR(50),		--核算分支ID
	DTypeId			VARCHAR(50),		--部门ID
	BTypeId			VARCHAR(50),		--核算单位ID
	ETypeId			VARCHAR(50),		--职员ID
	DealBTypeId		VARCHAR(50),		--往来单位ID
	ATypeID			INT,				--收付款项目
	ATypeID1		VARCHAR(50),
	ATypeID2		VARCHAR(50),
	Cid				INT,				--币种
	Rate			 NUMERIC(24, 10) ,		--汇率
	RateType		INT,				--汇率计算方式
	balancemoney	 NUMERIC(24, 10) ,		--平衡数
	RedWord			INT			,		--红冲标识
	OtherInOutType	INT,
	outstypeid		VARCHAR(50),		--出库分支机构
	instypeid		VARCHAR(50)			--入库分支机构
	,AtId			INT					--模板号
)

IF @BillType = 405
BEGIN
	INSERT INTO #TmpBillInfo
			( BillNumberId ,
			  StypeId ,
			  VerifyStypeid ,
			  DTypeId ,
			  BTypeId ,
			  ETypeId,
			  DealBTypeId ,
			  Cid ,
			  Rate ,
			  RateType
			  ,atypeid1
			  ,atypeid2
			)
	SELECT  T1.BillNumberId,
			T1.Stypeid,
			T2.VerifyID,
			T1.DTypeId,
			T1.btypeid,
			T1.etypeid,
			T1.DealBTypeID,
			T1.CID,
			T1.Rate,
			T3.BasisType
			,T1.AtypeId1
			,T1.AtypeId2
	FROM dbo.ReceiptBillIndex T1
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
	INNER JOIN (SELECT a FROM dbo.f_split(@BillNumberId,',')) B ON B.a = T1.BillNumberID
END
ELSE
BEGIN
	INSERT INTO #TmpBillInfo
			( BillNumberId ,
			  StypeId ,
			  VerifyStypeid ,
			  DTypeId ,
			  BTypeId ,
			  ETypeId,
			  DealBTypeId ,
			  ATypeID,
			  ATypeID1,
			  Cid ,
			  Rate ,
			  RateType,
			  RedWord,
			  OtherInOutType,
			  outstypeid,
			  instypeid
			  ,AtId
			)
	SELECT  T1.BillNumberId,
			T1.Stypeid,
			T2.VerifyID,
			T1.DTypeId,
			T1.btypeid,
			T1.etypeid,
			T1.DealBTypeID,
			T1.ATypeID,
			T1.ATypeID1,
			T1.CID,
			T1.Rate,
			T3.BasisType,
			T1.RedWord,
			T1.OtherInOutType,
			ISNULL(T4.STypeID,''),
			ISNULL(T5.STypeID,'')
			,@AtId
	FROM dbo.BillIndex T1
	INNER JOIN #BillNumberId B ON B.a= T1.BillNumberId
	INNER JOIN dbo.SType T2 ON T1.Stypeid = T2.TypeId
	INNER JOIN dbo.Ac_Currency T3 ON T1.CID = T3.CId
	LEFT JOIN dbo.Stock T4 ON T1.ktypeid = T4.typeId
	LEFT JOIN dbo.Stock T5 ON T1.ktypeid2 = T5.typeId
END

--将模板明细处理到临时表中
SELECT *
INTO #TmpVoucherDetails
FROM dbo.Ac_Auditing_Template_Detail WHERE Atid = @atid 
--------------------------

DECLARE @MaxDid INT,@MinDid INT,@SqlSummary VARCHAR(MAX),@MaxNumber INT,@MinNumber INT,@Index INT,@Str VARCHAR(MAX)

SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作
SELECT @MaxDid = MAX(atdid) FROM #TmpVoucherDetails WHERE ISNULL(SummaryType,'') <> ''  --SummaryType为空的说明其是用户手动填写的摘要，故不需要再对其进行读取字段生成摘要的操作

SELECT @MinNumber = MIN(a) FROM #BillNumberId --- dbo.f_split(@billnumberid,',')
SELECT @MaxNumber = MAX(a) FROM #BillNumberId ---dbo.f_split(@Billnumberid,',')

SET @Index = @MinNumber



CREATE TABLE #TempStr
(
	SummaryStr VARCHAR(MAX),
	SummaryType	INT
)

DECLARE @flag INT--是否需要用户补足
SET @flag = 0


WHILE @MinDid <= @MaxDid
BEGIN
	SET @SqlSummary = ''
	SET @Str = ''

	WHILE @Index <= @MaxNumber
	BEGIN
	
		SET @SqlSummary = 'INSERT INTO #TempStr(SummaryStr,SummaryType) '
		
		IF @BillType=405
		BEGIN
			SELECT @SqlSummary +=  'SELECT '+
					CASE Filed
						WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
						ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
					END
				+'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
				CASE tablename 
					WHEN 'ReceiptBillIndex' THEN ' T2 '
					WHEN 'Stype' THEN ' T1 INNER JOIN ReceiptBillIndex T2 ON T1.typeid = T2.stypeid '
					WHEN 'Btype' THEN ' T1 INNER JOIN ReceiptBillIndex T2 ON T1.typeid = T2.btypeid '
					WHEN 'employee ' THEN ' T1 INNER JOIN ReceiptBillIndex T2 ON T1.typeid = T2.etypeid '
				END
				+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
				+' union all '
			FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		END
		ELSE
		BEGIN
			SELECT @SqlSummary +=  'SELECT '+
					CASE Filed
						WHEN 'BillDate' THEN 'stuff(stuff(CONVERT(varchar(max), CONVERT(VARCHAR(max),'+ filed+' ,111), 23),5,1,''年''),8,1,''月'') + ''日'''
						ELSE 'CONVERT(VARCHAR(max),'+ Filed+' ,111)'
					END
				+'AS SummaryStr,' + a + ' AS SummaryType from ' + TableName +
				CASE tablename 
					WHEN 'BillIndex' THEN ' T2 '
					WHEN 'Stype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.stypeid '
					WHEN 'Btype' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.btypeid '
					WHEN 'employee ' THEN ' T1 INNER JOIN Billindex T2 ON T1.typeid = T2.etypeid '
				END
				+' WHERE T2.BillNumberId ='+CAST(@Index AS VARCHAR(10))
				+' union all '
			FROM dbo.f_split((SELECT summarytype FROM #TmpVoucherDetails WHERE AtdId = @MinDid),',') T1
			INNER JOIN dbo.Ac_Auditing_Template_SummaryFiled T2 ON T1.a = T2.FiledID
		END
		
		IF LEN(@SqlSummary) > LEN('INSERT INTO #TempStr(SummaryStr,SummaryType) ')
		BEGIN
			SET @SqlSummary = SUBSTRING(@SqlSummary,1,LEN(@SqlSummary)-9)
			EXEC(@SqlSummary)
		END
		
		SELECT @str += summarystr + '  '
		FROM #TempStr
		
		IF @str <> ''
			SET @str += ';'
		TRUNCATE TABLE #TempStr
		
		IF @Index = @MaxNumber
			SET @Index += 1
		ELSE
			SELECT @Index = MIN(A) FROM #BillNumberId WHERE A > @Index
	END
	
	--按配置读到数据，更新摘要
	UPDATE #TmpVoucherDetails SET Summary = CASE WHEN LEN(@str) > 200 THEN LEFT(@str,197)+'...' ELSE @str END WHERE AtdId = @MinDid AND ISNULL(SummaryType,'') <> ''
	
	TRUNCATE TABLE #TempStr
	SET @Index = @MinNumber
	
	IF @MinDid = @MaxDid
		SET @MinDid += 1
	ELSE
		SELECT @MinDid = MIN(atdid) FROM #TmpVoucherDetails WHERE AtdId > @MinDid AND ISNULL(SummaryType,'') <> ''
END

--处理成本明细的摘要
SELECT @MinDid = MIN(Atid) FROM #TmpVoucherDetails WHERE isCost = 1
IF EXISTS(SELECT TOP  1 1 FROM #TmpVoucherDetails WHERE Atid = @MinDid AND Summary = '')
	UPDATE #TmpVoucherDetails SET Summary = (SELECT TOP 1 Summary  FROM #TmpVoucherDetails WHERE Summary <> '' ORDER BY OrderID) WHERE Atid = @MinDid

--删除基本明细
DELETE FROM #TmpVoucherDetails WHERE isCost = 0

----------------------


--往来科目模板行号
DECLARE @Atdid INT
SET @Atdid = 0
--获取本位币
DECLARE	 @f_exchid		VARCHAR(50)
SELECT @f_exchid = a.CId FROM dbo.Ac_Currency a WHERE Sysrow = 1

--获取往来科目模板行号
SELECT @Atdid = atdid FROM #TmpVoucherDetails WHERE Atid = @atid AND AcFrom = 3

DECLARE @BillCid	INT
		,@IsUseBillMoneyDate INT
		,@UseBillMoneyDate_BillTypes VARCHAR(200)
		,@sql VARCHAR(MAX)

SELECT TOP 1 @BillCid = Cid FROM #TmpBillInfo
SELECT @UseBillMoneyDate_BillTypes=SubValue  FROM sysdata WHERE SubName = 'usebillmoneydate'

SET @IsUseBillMoneyDate = 0
IF EXISTS (SELECT TOP 1 1 FROM F_Split(@UseBillMoneyDate_BillTypes,',') WHERE a = @BillType)
	SET @IsUseBillMoneyDate = 1


--统计单据所有金额字段
CREATE TABLE #tmpBillMoney
(
	totalmoney				 NUMERIC(24, 10) 	DEFAULT 0,
	totalinmoney			 NUMERIC(24, 10) 	DEFAULT 0,
	preferencemoney			 NUMERIC(24, 10) 	DEFAULT 0,
	total					 NUMERIC(24, 10) 	DEFAULT 0,--折后金额
	taxTotal				 NUMERIC(24, 10) 	DEFAULT 0,
	costTotal				 NUMERIC(24, 10) 	DEFAULT 0,
	inCostTotal				 NUMERIC(24, 10) 	DEFAULT 0,--入库成本（换货、拆装、调拨）
	outCostTotal			 NUMERIC(24, 10) 	DEFAULT 0,--出库成本（换货、拆装、调拨）
	rate					 NUMERIC(24, 10) 	DEFAULT 1,
	ratetype				INT				DEFAULT 0,
	instocktotal			 NUMERIC(24, 10) 	DEFAULT 0,--入库折后金额
	outstocktotal			 NUMERIC(24, 10) 	DEFAULT 0,--出库折后金额
	instocktaxtotal			 NUMERIC(24, 10) 	DEFAULT	0,--入库价税合计
	outstocktaxtotal		 NUMERIC(24, 10) 	DEFAULT 0,--出库价税合计
	GoodsCostTotal			 NUMERIC(24, 10) 	DEFAULT 0,--成本金额
	instockGoodsCostTotal	 NUMERIC(24, 10) 	DEFAULT 0,--入库成本金额
	outstockGoodsCostTotal	 NUMERIC(24, 10) 	DEFAULT 0,--出库成本金额
	beforetotal				 NUMERIC(24, 10) 	DEFAULT	0,--调前金额
	sharefee				 NUMERIC(24, 10) 	DEFAULT 0,--分摊金额
	j_total					 NUMERIC(24, 10) 	DEFAULT 0,
	d_total					 NUMERIC(24, 10) 	DEFAULT	0,
	balancemoney			 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	billnumberid			INT,
	rowindex				INT				DEFAULT 1,
	CommissionTotal			 NUMERIC(24, 10) 	DEFAULT 0,--提成单311提成金额
	
	costTotal_S				 NUMERIC(24, 10) 	DEFAULT 0,--商品成本金额（服务商品）
	inCostTotal_S			 NUMERIC(24, 10) 	DEFAULT 0,--入库成本（服务商品）换货
	outCostTotal_S			 NUMERIC(24, 10) 	DEFAULT 0,--出库成本（服务商品）换货
	total_S					 NUMERIC(24, 10) 	DEFAULT 0,--折后金额（服务商品）
	instocktotal_S			 NUMERIC(24, 10) 	DEFAULT 0,--入库折后金额(服务商品)
	outstocktotal_S			 NUMERIC(24, 10) 	DEFAULT 0, --出库折后金额（服务商品）
	
	-----9.6功能，对某些单据生成凭证时，原币金额用单据上的原币金额，而不是通过本位币反算得来
	
	totalmoneyfor				 NUMERIC(24, 10) 	DEFAULT 0,
	totalinmoneyfor			 NUMERIC(24, 10) 	DEFAULT 0,
	preferencemoneyfor		 NUMERIC(24, 10) 	DEFAULT 0,
	totalfor					 NUMERIC(24, 10) 	DEFAULT 0,--折后金额
	taxTotalfor				 NUMERIC(24, 10) 	DEFAULT 0,
	total_Sfor				 NUMERIC(24, 10) 	DEFAULT 0,
	costTotal_Sfor			 NUMERIC(24, 10) 	DEFAULT 0,
	costtotalfor			 NUMERIC(24, 10) 	DEFAULT 0,
	balancemoneyfor			 NUMERIC(24, 10) 	DEFAULT 0,--平衡数
	InvoiceCostTotal		 NUMERIC(24,10)		DEFAULT 0
)

--Awu:调整先不合并
INSERT INTO #tmpBillMoney
(
	totalmoney,
	totalinmoney,
	preferencemoney,
	billnumberid,
	rate,
	ratetype,
	totalmoneyfor,
	totalinmoneyfor,
	preferencemoneyfor
)
SELECT	CASE WHEN a.RedWord = 2 THEN -totalmoney ELSE totalmoney END AS totalmoney,
		CASE WHEN a.RedWord = 2 THEN -totalinmoney ELSE totalinmoney END AS totalinmoney,
		CASE WHEN a.RedWord = 2 THEN -preferencemoney ELSE preferencemoney END AS preferencemoney,
		a.BillNumberId,BB.Rate,BB.RateType
		,CASE WHEN a.RedWord = 2 THEN -NTotalMoney ELSE NTotalMoney END AS totalmoneyfor,
		CASE WHEN a.RedWord = 2 THEN -NTotalInMoney ELSE NTotalInMoney END AS totalinmoneyfor,
		CASE WHEN a.RedWord = 2 THEN -NPreferenceMoney ELSE NPreferenceMoney END AS preferencemoneyfor
FROM dbo.BillIndex a
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
INNER JOIN dbo.SType S ON a.Stypeid = S.TypeId
WHERE A.BillType = @BillType
UNION ALL
SELECT	CASE WHEN a.RedWord = 2 THEN -totalmoney ELSE totalmoney END AS totalmoney,
		0 AS totalinmoney,
		0 AS preferencemoney,
		a.BillNumberId,BB.Rate,BB.RateType
		,CASE WHEN a.RedWord = 2 THEN -NTotalMoney ELSE NTotalMoney END AS totalmoneyfor,
		0 AS totalinmoneyfor,
		0 AS preferencemoneyfor
FROM dbo.ReceiptBillIndex a
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId
INNER JOIN dbo.SType S ON a.Stypeid = S.TypeId
WHERE A.BillType = @BillType



--获取成本金额 换货、拆装两条记录，有入有出，其他的都是单条记录
IF @BillType IN (160)
BEGIN
	UPDATE #tmpBillMoney
	SET outCostTotal = TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN (CASE WHEN -CostTotal < 0 THEN -ABS(CostTotal) ELSE 0 END)
								ELSE (CASE WHEN CostTotal < 0 THEN ABS(CostTotal) ELSE 0 END)
						  END) AS Total,a.BillNumberId
		FROM  dbo.InOutstocktable a
			INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
			INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
		WHERE c.IsService = 0
		GROUP BY a.BillNumberId
	) TT ON T1.billnumberid = TT.billnumberid
	
	UPDATE #tmpBillMoney
	SET inCostTotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN (CASE WHEN -CostTotal > 0 THEN -ABS(CostTotal) ELSE 0 END)
								ELSE (CASE WHEN CostTotal > 0 THEN ABS(CostTotal) ELSE 0 END)
						 END) AS total,a.BillNumberId
			FROM dbo.InOutstocktable a
				INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
				INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
				INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
			WHERE c.IsService = 0
			GROUP BY a.BillNumberId
	) TT ON t1.billnumberid = tt.billnumberid
END
ELSE IF @BillType IN (140,142)--委托代销出库、委托代销退货取一个
BEGIN
	UPDATE #tmpBillMoney
	SET CostTotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN-ABS(a.CostTotal)
								ELSE ABS(a.CostTotal)
						  END) AS total,a.BillNumberId
		FROM dbo.InOutstocktable a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		WHERE a.KtypeId <> '10000'
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
END
ELSE IF @BillType IN (141)--委托代销结算，只操作代销库
BEGIN
	UPDATE #tmpBillMoney
	SET CostTotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN-ABS(a.CostTotal)
								   ELSE ABS(a.CostTotal)
							  END) AS total,a.BillNumberId
		FROM  dbo.InOutstocktable a
		INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
		INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
END
ELSE IF @BillType = 405
BEGIN
	UPDATE #tmpBillMoney
	SET InvoiceCostTotal = TT.InvoiceCostTotal
	FROM #tmpBillMoney T1
	INNER JOIN (
		SELECT	a.BillNumberID
				,SUM(a.InvoiceCostTotal) AS InvoiceCostTotal
		FROM dbo.ReceiptBill a
		INNER JOIN #TmpBillInfo B ON B.BillNumberId = A.BillNumberID
		GROUP BY A.BillNumberID
	) TT ON TT.BillNumberID = T1.billnumberid
END
ELSE
BEGIN
	UPDATE #tmpBillMoney
	SET costtotal	= TT.total
	FROM #tmpBillMoney T1
	INNER JOIN (SELECT SUM(CASE WHEN b.RedWord = 2 THEN -ABS(a.CostTotal) ELSE ABS(a.CostTotal) END) AS total,a.BillNumberId
		FROM  dbo.InOutstocktable a
			INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId
			INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = B.BillNumberId
			INNER JOIN dbo.ptype c ON a.PtypeId = c.typeId
		WHERE a.KtypeId <> '10000'
			AND c.IsService = 0
		GROUP BY a.BillNumberId
	)TT ON T1.billnumberid = TT.BillNumberId
END
	
--科目来源AcFrom
--1 手工选择
--2 单据上收付款项目对应科目
--3 单据上往来科目
--4 单据上项目对应科目
--5 单据上项目对应固定资产科目
--6 单据上借方项目对应科目
--7 单据上贷方项目对应科目
--8 单据上业务类型对应科目
CREATE TABLE #tmpExpress
(
	atdit		INT,
	lendloan	 NUMERIC(24, 10) ,
	lendloanfor	 NUMERIC(24, 10) ,
	rate		 NUMERIC(24, 10) ,
	ratetype	INT,
	billnumberid	INT,
	iscost		INT DEFAULT 0
)

--读取模板要求的金额（非项目类）
SET @sql = 'insert into #tmpExpress select distinct * from('--MARK:唉，又改回来，这个也要屏蔽，要不然有报错，无语，以后再改回去，直接取消注释吧
--SET @sql = 'insert into #tmpExpress'

SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId,('+ T2.Express +') as lendloan,'+CASE WHEN @IsUseBillMoneyDate = 1 THEN '('+dbo.F_ChangeToOriginalCurrency(T2.Express) +')' ELSE '0' END +' as lendloanfor,rate,ratetype,billnumberid,'+CASE WHEN dbo.F_ChangeToOriginalCurrency(T2.Express) = '0' THEN '1' ELSE '0' END+' as iscost
from #tmpBillMoney a 
 union all '
FROM #TmpVoucherDetails T1
INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId


IF LEN(@sql) > LEN('insert into #tmpExpress select distinct * from(')
BEGIN
	SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
	SET @sql += ')T'
	EXEC(@sql)
END

SELECT	A.*,
		CASE WHEN a.Cid = -1 THEN @f_exchid
			 ELSE a.Cid
		END AS rcid,
		CAST(ISNULL(ASS.Ascids,'0') AS VARCHAR)+',' AS Item
INTO #tmpAccount
FROM dbo.Ac_Account a
left join Ac_Account_Assist_CheckItems ass on ass.STypeId = a.StypeId and ass.ATypeId = a.TypeId and ass.Ascids = 4
WHERE a.StypeId = @Verifyid

CREATE TABLE #tmpBillMulAccount
(
	Atypeid		VARCHAR(50),
	Usercode	VARCHAR(200),
	Fullname	VARCHAR(200),
	Fdc			INT,
	Cid			INT,
	Atid		INT,
	Total		 NUMERIC(24, 10) ,
	Totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)
CREATE TABLE #tmpBillIndexAtypeid
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atid		INT,
	total		 NUMERIC(24, 10) ,
	totalfor		 NUMERIC(24, 10) ,
	billnumberid	INT
)

--获取单据上的收付款科目及金额
IF @BillType IN (305,11,45,160,141,215,402,403)
BEGIN
	INSERT INTO #tmpBillIndexAtypeid
	SELECT	c.ATypeID,
				b.UserCode,
				b.FullName,
				NULL,
				NULL,
				@atid AS atid,
				CASE WHEN BB.RedWord = 2 THEN -a.Total ELSE a.Total END AS total,
				CASE WHEN BB.RedWord = 2 THEN -a.NTotalMoney ELSE a.NTotalMoney END AS totalfor,
				BB.BillNumberId  --e.BillNumberId
	FROM	#TmpBillInfo BB
	INNER JOIN dbo.BillMulAccount a ON a.BillNumberId = BB.BillNumberId
	INNER JOIN dbo.Ac_Items b ON a.ATypeID = b.nId
	INNER JOIN dbo.Ac_Items_Detail c ON b.nId = c.nId AND c.StypeId = BB.StypeId
	

	--现金费用单只有一个科目，金额是表体总额，后面取值不会使用这个数据
	INSERT INTO #tmpBillMulAccount
	SELECT ATypeId,b.UserCode,b.FullName,b.Fdc,b.cid,atid,SUM(Total) AS total,SUM(totalfor) as totalfor,a.billnumberid
	FROM #tmpBillIndexAtypeid a
		LEFT JOIN Ac_Account b ON a.atypeid = b.typeid and b.stypeid = @verifyid
	GROUP BY atypeid,b.usercode,b.fullname,b.fdc,b.cid,atid,a.billnumberid
END

CREATE TABLE #tmpBillIndexAtypeid1
(
	atypeid		VARCHAR(50),
	usercode	VARCHAR(50),
	fullname	VARCHAR(200),
	fdc			INT,
	cid			INT,
	atid		INT,
	atdid		INT,
	item		VARCHAR(500)
	,billnumberid	INT
)
--单据上的往来科目
IF @BillType IN (11,45,160,141,402,403)
BEGIN	
	INSERT INTO #tmpBillIndexAtypeid1
	SELECT	b.typeId,
		b.UserCode,
		b.FullName,
		Fdc,
		CASE b.cid
			WHEN -1 THEN @f_exchid
			ELSE b.Cid
		END,
		@Atid AS atid,
		@Atdid as atdid,
		SUBSTRING(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1),
				LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))-1,
				LEN(dbo.F_Get_AscidsItem(@verifyid,BB.ATypeID1))) AS Item
		,BB.BillNumberId
	FROM #TmpBillInfo bb
	INNER JOIN dbo.Ac_Account b ON B.TypeId = BB.ATypeID1 AND B.StypeId = BB.VerifyStypeid
	
	--无科目，补空白
	IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBillIndexAtypeid1)
	BEGIN
		
		INSERT INTO #tmpBillIndexAtypeid1
				( atypeid ,
				  usercode ,
				  fullname ,
				  fdc ,
				  cid ,
				  atid,
				  atdid
				  ,billnumberid
				)
		SELECT  '' , -- atypeid - varchar(50)
				  '' , -- usercode - varchar(50)
				  '' , -- fullname - varchar(200)
				  0 , -- fdc - int
				  0 , -- cid - int
				  0 , -- atid - int
				  @Atdid
				,BillNumberId
		FROM #TmpBillInfo
	END
END

--凭证明细临时表
CREATE TABLE #tmpBill
(
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rowno			INT		IDENTITY(1,1),
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		addebtid		INT,
		credenceId		INT,
		billid	INT
)
	
	
--生成凭证明细数据(科目来源1~3，8)--
INSERT INTO #tmpBill
		( billnumberid ,
		  explain ,
		  atypeid ,
		  atypeid2 ,
		  Fdc ,
		  f_exchid ,
		  f_exchidfor ,
		  lendprice ,
		  loanprice ,
		  lendpricefor ,
		  loanpricefor ,
		  FCashFlowItem ,
		  ascids ,
		  FSettleNo ,
		  FSettleTypeID ,
		  comment ,
		  cid ,
		  rate ,
		  fadc ,
		  stypeid ,
		  fyear ,
		  fperiod,
		  atdid,
		  addebtid,
		  billid
		)
SELECT	DISTINCT @VoucherBillId AS billnumberid,
		Summary AS explain,
		CASE AcFrom 
			WHEN 1 THEN b.typeid
			WHEN 2 THEN c.atypeid
			WHEN 3 THEN e.atypeid
			WHEN 8 THEN (CASE WHEN @BillType = 201 THEN g4_1.typeid ELSE g4.typeid END)
		END AS atypeid,
		'' AS atypeid2,
		CASE AcFrom 
			WHEN 1 THEN b.Fdc
			WHEN 2 THEN c.Fdc
			WHEN 3 THEN e.Fdc
			WHEN 4 THEN b.Fdc
			WHEN 8 THEN (CASE WHEN @BillType = 201 THEN g4_1.Fdc ELSE g4.Fdc END)
		END AS Fdc,
		@f_exchid AS f_exchid,
		BB.Cid AS f_exchidfor,
		CASE a.Fdc 
			WHEN 1 THEN (CASE WHEN AcFrom = 2 THEN isnull(c.total,0) 
							  ELSE isnull(d.lendloan,0) END )
			ELSE 0 
		END AS lendprice,
		CASE a.Fdc 
			WHEN -1 THEN (CASE WHEN AcFrom = 2 THEN ISNULL(c.total,0)
							   ELSE isnull(d.lendloan,0) END )
			ELSE 0 
		END AS loanprice,
		CASE WHEN a.Fdc = 1 AND @IsUseBillMoneyDate = 1 AND d.iscost = 0	THEN d.lendloanfor
			 WHEN a.Fdc = 1 THEN 
					(CASE ISNULL(d.ratetype,0) 
						WHEN 0 THEN  (CASE WHEN AcFrom = 2  THEN ISNULL(c.total,0) 
										   ELSE isnull(d.lendloan,0) END ) / ISNULL(d.rate,1)
						WHEN 1 THEN (CASE WHEN AcFrom = 2  THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) * ISNULL(d.rate,1)
					END)
			ELSE 0 
		END AS lendpricefor,
		CASE WHEN a.Fdc = -1  AND @IsUseBillMoneyDate = 1 AND d.iscost = 0	THEN d.lendloanfor
			 WHEN a.Fdc = -1 THEN
					(CASE ISNULL(d.ratetype,0)                                                       
						WHEN 0 THEN (CASE WHEN AcFrom = 2  THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) / isnull(d.rate,1)
						WHEN 1 THEN (CASE WHEN AcFrom = 2  THEN ISNULL(c.total,0) 
										  ELSE isnull(d.lendloan,0) END ) * isnull(d.rate,1)
					END)
			ELSE 0 
		END AS loanpricefor,
		NULL AS FCashFlowItem,
		'' AS ascids,
		NULL AS FSettleNo,
		0 AS FSettleTypeID,
		'' AS comment,
		BB.Cid,
		d.rate,
		a.Fdc AS fadc,
		@verifyid AS stypeid,
		@fyear AS fyear,
		@fperiod AS fperiod,
		a.AtdId,
		0,
		D.billnumberid
FROM #TmpVoucherDetails a
INNER JOIN #tmpExpress d ON a.AtdId = d.atdit
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = D.billnumberid
LEFT JOIN #tmpAccount b ON a.ATypeId = b.TypeId
LEFT JOIN #tmpBillMulAccount c ON a.Atid = c.atid AND C.billnumberid = D.billnumberid
LEFT JOIN #tmpBillIndexAtypeid1 e ON a.Atid = e.atid AND E.billnumberid = D.billnumberid
LEFT JOIN dbo.OtherInOutType g1 ON  g1.ID = BB.OtherInOutType -- @OtherInOutType
LEFT JOIN dbo.Ac_Items g2 ON g1.ATypeID = g2.nId --出库
LEFT JOIN dbo.Ac_Items g2_1 ON g1.ATypeID1 = g2_1.nId--入库
LEFT JOIN dbo.Ac_Items_Detail g3 ON g2.nId = g3.nId AND g3.STypeId = BB.StypeId --- @stypeidValue
LEFT JOIN dbo.Ac_Items_Detail g3_1 ON g2_1.nId = g3_1.nId AND g3_1.STypeId =BB.StypeId  --- @stypeidValue
LEFT JOIN #tmpAccount g4 ON g3.ATypeId = g4.typeid
LEFT JOIN #tmpAccount g4_1 ON g3_1.ATypeId = g4_1.typeid
WHERE a.AcFrom IN (1,2,3,8)
ORDER BY a.AtdId


--往来科目为空
IF NOT EXISTS(SELECT TOP 1 1 FROM #tmpBillIndexAtypeid1 WHERE ISNULL(atypeid,'') <> '')
BEGIN
	IF EXISTS(	SELECT TOP 1 1
					FROM #TmpVoucherDetails T1
						LEFT JOIN #TmpExpress T2 ON T1.AtdId = T2.Atdit
						LEFT JOIN #tmpBillIndexAtypeid1 T3 ON T2.Atdit =T3.Atdid
						LEFT JOIN dbo.Ac_Account T4 ON T3.Atypeid = T4.TypeId AND T4.StypeId = @verifyid
						LEFT JOIN dbo.Ac_Currency T5 ON T4.Cid = T5.CId
					WHERE T1.Atid = @Atid AND T1.AcFrom = 3 AND T2.Lendloan <> 0)
	SET @Flag = -11
END


CREATE TABLE #tmpMoneyBill
(
	BillNumberId	INT,
	AtypeId			VARCHAR(50),
	total			 NUMERIC(24, 10) ,
	totalfor			 NUMERIC(24, 10) ,
	STypeid			VARCHAR(50),
	billid	INT	--单据编号
)

CREATE TABLE #tmpItemDetail
(
	AtdId			INT,
	Express			VARCHAR(1000),
	rate			 NUMERIC(24, 10) ,
	ratetype		INT,
	billnumberid	VARCHAR(1000),
	acfrom			INT
)

--项目对应科目生成凭证明细(4,5,9,10)
INSERT INTO #tmpItemDetail
		(AtdId,
		Express,
		rate,
		ratetype,
		billnumberid,
		acfrom)
SELECT AtdId,T2.Express,bb.Rate AS rate,bb.RateType AS ratetype,bb.BillNumberId AS billnumberid,AcFrom
FROM #TmpBillInfo BB
INNER JOIN #TmpVoucherDetails T1 ON T1.Atid = BB.AtId
INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
WHERE AcFrom IN (4,5,9,10)

INSERT INTO #tmpMoneyBill
		( BillNumberId ,
		  AtypeId ,
		  total ,
		  totalfor,
		  STypeid,
		  billid
		)
SELECT a.BillNumberId,a.AtypeId,CASE WHEN BB.RedWord = 2 THEN -total ELSE total END AS total,CASE WHEN BB.RedWord = 2 THEN -NTotal ELSE NTotal END AS totalfor,a.Stypeid,a.BillNumberId
FROM dbo.MoneyBill a
INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.BillNumberId

INSERT INTO #tmpBill
		( billnumberid ,
		  explain ,
		  atypeid ,
		  atypeid2 ,
		  Fdc ,
		  f_exchid ,
		  f_exchidfor ,
		  lendprice ,
		  loanprice ,
		  lendpricefor ,
		  loanpricefor ,
		  FCashFlowItem ,
		  ascids ,
		  FSettleNo ,
		  FSettleTypeID ,
		  comment ,
		  cid ,
		  rate ,
		  fadc ,
		  stypeid ,
		  fyear ,
		  fperiod,
		  atdid,
		  billid
		)
SELECT DISTINCT billnumberid,explain,atypeid,atypeid2,fdc,f_exchid,f_exchidfor,SUM(jie),SUM(dai),SUM(jiefor),SUM(daifor),
		FCashFlowItem,ascids,FSettleNo,FSettleTypeID,comment,cid,rate,fadc,stypeid,fyear,fperiod,AtdId,billid
FROM
(
	SELECT	@VoucherBillId AS billnumberid,c.Summary AS explain,
			e.ATypeId AS atypeid,
			'' AS atypeid2,
			f.Fdc ,@f_exchid AS f_exchid,BB.Cid AS f_exchidfor,
			CASE c.Fdc
				WHEN 1	THEN b.total
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN b.total
				WHEN 1	THEN 0
			END AS dai,
			CASE WHEN c.Fdc = 1 AND @IsUseBillMoneyDate = 1 THEN b.totalfor
				 WHEN c.Fdc = 1 THEN 
						(CASE a.ratetype 
							WHEN 0 THEN b.total / A.rate
							WHEN 1 THEN b.total * A.rate
						END)
				ELSE 0 
			END AS jiefor,
			CASE WHEN c.Fdc = -1 AND @IsUseBillMoneyDate = 1 THEN b.totalfor
				 WHEN c.Fdc = -1 THEN
						(CASE a.ratetype  
							WHEN 0 THEN b.total / A.rate
							WHEN 1 THEN b.total* A.rate
						END)
				ELSE 0 
			END AS daifor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			BB.Cid AS cid,
			a.rate,
			c.Fdc AS fadc,
			@verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId,
			BB.billnumberid AS billid
	FROM	#TmpBillInfo BB
	INNER JOIN #tmpItemDetail a ON A.billnumberid = BB.BillNumberId 
	INNER JOIN #tmpMoneyBill b ON b.BillNumberId =  BB.BillNumberId 
	INNER JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	INNER JOIN dbo.Ac_Items d ON b.AtypeId = d.nid
	INNER JOIN dbo.Ac_Items_Detail e ON d.nId = e.nId AND e.STypeId = BB.StypeId
	INNER JOIN dbo.Ac_Account f ON e.ATypeId = f.TypeId AND f.StypeId = BB.VerifyStypeid
)T
GROUP BY billnumberid,explain,atypeid,atypeid2,fdc,f_exchid,f_exchidfor,FCashFlowItem,ascids,FSettleNo,
			FSettleTypeID,comment,cid,rate,fadc,stypeid,fyear,fperiod,AtdId,billid
			
/*
处理存货类型
15-存货
16-收入
17-成本
*/
IF EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AcFrom IN(15,16,17))
BEGIN
	CREATE TABLE #InventoryTypeAccount
	(
		atdid	INT
		,atypeid	VARCHAR(50)
		,billnumberid	NUMERIC(10,0)
		,lendloan		NUMERIC(24,10)
		,lendloanfor	 NUMERIC(24, 10) ,
		rate		 NUMERIC(24, 10) ,
		ratetype	INT,
		iscost		INT DEFAULT 0
	)
	
	CREATE TABLE #BillDetailsInventoryTypeAccount
	(
		billnumberid	NUMERIC(10,0)
		,ptypeid		VARCHAR(50)
		,TID		INT
		,stypeid	VARCHAR(50)
		,CostATypeID	VARCHAR(50)
		,IncomeATypeID	VARCHAR(50)
		,StockATypeID	VARCHAR(50)
		,total		NUMERIC(24,10)
		,costtotal	NUMERIC(24,10)
		,taxtotal	NUMERIC(24,10)
		,goodscosttotal	NUMERIC(24,10)
		,incosttotal	NUMERIC(24,10)
		,outcosttotal	NUMERIC(24,10)
		,instocktotal	NUMERIC(24,10)
		,outstocktotal	NUMERIC(24,10)
		,instockgoodscosttotal	NUMERIC(24,10)
		,outstockgoodscosttotal	NUMERIC(24,10)

		,totalfor		NUMERIC(24,10)
		,costtotalfor	NUMERIC(24,10)
		,taxtotalfor	NUMERIC(24,10)
		,goodscosttotalfor	NUMERIC(24,10)
		,incosttotalfor	NUMERIC(24,10)
		,outcosttotalfor	NUMERIC(24,10)
		,instocktotalfor	NUMERIC(24,10)
		,outstocktotalfor	NUMERIC(24,10)
		,instockgoodscosttotalfor	NUMERIC(24,10)
		,outstockgoodscosttotalfor	NUMERIC(24,10)		
		
		,InvoiceCostTotal	NUMERIC(24,10)
		,InvoiceCostTotalfor	NUMERIC(24,10)
	)
	
	
	CREATE TABLE #InOutstocktableSUM
	(
		BillNumberId	NUMERIC(10,0)
		,Ptypeid		VARCHAR(50)
		,Total			NUMERIC(24,10)
		,NTotal			NUMERIC(24,10)
		,CostTotal		NUMERIC(24,10)
		,TaxTotal		NUMERIC(24,10)	
		,nTaxTotal		NUMERIC(24,10)	
		,incosttotal	NUMERIC(24,10)
		,outcosttotal	NUMERIC(24,10)
		,instocktotal	NUMERIC(24,10)
		,outstocktotal	NUMERIC(24,10)
		,sharefee		NUMERIC(24,10)	
		,instockgoodscosttotal	NUMERIC(24,10)
		,outstockgoodscosttotal	NUMERIC(24,10)
		,InvoiceCostTotal	NUMERIC(24,10)
	)
	
	IF @BillType IN(141)
	BEGIN
		INSERT INTO #InOutstocktableSUM
			(
				billnumberid
				,ptypeid
				
				,total
				,NTotal
				,costtotal
				,taxtotal
				,ntaxtotal	
										
				,incosttotal	
				,outcosttotal	
				,instockgoodscosttotal	
				,outstockgoodscosttotal	
				
				,instocktotal
				,outstocktotal		
				
				,InvoiceCostTotal		
			)
		SELECT	T.BillNumberId
				,T.ptypeid
				
				,SUM(T.Total)	--折后金额
				,SUM(T.NTotal)
				,SUM(T.CostTotal)	--成本金额
				,SUM(T.TaxTotal)	--价税合计
				,SUM(T.NTaxTotal)	--价税合计原币
				
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库商品成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库商品成本
				
				,SUM(CASE WHEN T.Total>0 THEN T.Total ELSE 0 END)	--金额 转成 入库金额
				,SUM(CASE WHEN T.Total>0 THEN 0 ELSE T.Total END)	--金额 转成 出库金额
				
				,0
		FROM InOutstocktable T
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
		INNER JOIN	PType P ON P.typeId = T.PtypeId
		WHERE	P.IsService = 0
		GROUP BY T.BillNumberId,T.PtypeId
	END
	ELSE
	BEGIN 
		INSERT INTO #InOutstocktableSUM
			(
				billnumberid
				,ptypeid
				
				,total
				,NTotal
				,costtotal
				,taxtotal
				,ntaxtotal	
										
				,incosttotal	
				,outcosttotal	
				,instockgoodscosttotal	
				,outstockgoodscosttotal	
				
				,instocktotal
				,outstocktotal		
				
				,InvoiceCostTotal		
			)
		SELECT	T.BillNumberId
				,T.ptypeid
				
				,SUM(T.Total)	--折后金额
				,SUM(T.NTotal)
				,SUM(T.CostTotal)	--成本金额
				,SUM(T.TaxTotal)	--价税合计
				,SUM(T.NTaxTotal)	--价税合计原币
				
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库成本
				,SUM(CASE WHEN T.CostTotal>0 THEN T.CostTotal ELSE 0 END)	--成本金额 转成 入库商品成本
				,SUM(CASE WHEN T.CostTotal>0 THEN 0 ELSE T.CostTotal END)	--成本金额 转成 出库商品成本
				
				,SUM(CASE WHEN T.Total>0 THEN T.Total ELSE 0 END)	--金额 转成 入库金额
				,SUM(CASE WHEN T.Total>0 THEN 0 ELSE T.Total END)	--金额 转成 出库金额
				
				,0
		FROM InOutstocktable T
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
		WHERE T.BillType <> 405
			AND T.KtypeId <> '10000'
		GROUP BY T.BillNumberId,T.PtypeId
		UNION ALL
		SELECT	T.BillNumberId
				,T.ptypeid
				
				,SUM(T.Total)	--折后金额
				,SUM(T.NTotal)
				,0	--成本金额
				,SUM(T.TaxTotal)	--价税合计
				,SUM(T.NTaxTotal)	--价税合计原币
				
				,0	--成本金额 转成 入库成本
				,0	--成本金额 转成 出库成本
				,0	--成本金额 转成 入库商品成本
				,0	--成本金额 转成 出库商品成本
				
				,SUM(CASE WHEN T.Total>0 THEN T.Total ELSE 0 END)	--金额 转成 入库金额
				,SUM(CASE WHEN T.Total>0 THEN 0 ELSE T.Total END)	--金额 转成 出库金额
				
				,SUM(InvoiceCostTotal)
		FROM ReceiptBill T
		INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
		WHERE T.BillType = 405
		GROUP BY T.BillNumberId,T.PtypeId
	END 
	
	
	INSERT INTO #BillDetailsInventoryTypeAccount
		(
			billnumberid
			,PTYPEID
			,stypeid
			,TID
			,CostATypeID
			,IncomeATypeID
			,StockATypeID
			,total
			,costtotal
			,taxtotal
			,goodscosttotal
			
			,totalfor
			,costtotalfor
			,taxtotalfor
			,goodscosttotalfor		
					
			,incosttotal	
			,outcosttotal	
			,instockgoodscosttotal	
			,outstockgoodscosttotal	
			,instocktotal
			,outstocktotal
			
			,incosttotalfor	
			,outcosttotalfor	
			,instockgoodscosttotalfor	
			,outstockgoodscosttotalfor	
			,instocktotalfor
			,outstocktotalfor
			
			,InvoiceCostTotal
			,InvoiceCostTotalfor
		)
	SELECT	T.BillNumberId
			,T.Ptypeid
			,B.Stypeid
			,PIT.InventoryTypeid
			,BITD.CostATypeID
			,BITD.IncomeATypeID
			,BITD.StockATypeID
			,ABS(CASE WHEN @BillType IN(305,215,11,45,160,140,142,141,34,6,161,144,146,147,145) THEN T.Total ELSE T.NTotal END)
			,ABS(T.CostTotal)	
			,ABS(CASE WHEN @BillType IN(305,215,11,45,160,140,142,141,34,6,161,144,146,147,145) THEN T.TaxTotal ELSE T.NTaxTotal END)
			,ABS(T.CostTotal)	
						
			,ABS(T.nTotal)	
			,ABS(T.CostTotal)	
			,ABS(T.nTaxTotal)	
			,ABS(T.CostTotal)	
			
			,ABS(T.incosttotal)	
			,ABS(T.outcosttotal)	
			,ABS(T.instockgoodscosttotal)	
			,ABS(T.outstockgoodscosttotal)
			,ABS(T.instocktotal)
			,ABS(T.outstocktotal)
			
			,ABS(T.incosttotal)	
			,ABS(T.outcosttotal)	
			,ABS(T.instockgoodscosttotal)	
			,ABS(T.outstockgoodscosttotal)
			,ABS(T.instocktotal)
			,ABS(T.outstocktotal)
			
			,T.InvoiceCostTotal
			,T.InvoiceCostTotal
			
	FROM #InOutstocktableSUM T
	INNER JOIN	#TmpBillInfo B ON B.BillNumberId = T.BillNumberId
	INNER JOIN	PType PIT ON PIT.typeid = T.PtypeId
	INNER JOIN	Base_InventoryTypeDetails BITD ON BITD.TID = PIT.InventoryTypeid AND BITD.STypeID = B.Stypeid
		
	DECLARE @AcFromLoop	INT
	SET @AcFromLoop = 14
	
	SET @sql = 'insert into #InventoryTypeAccount 
			(
				atdid
				,atypeid
				,lendloan
				,lendloanfor
				,rate
				,ratetype
				,billnumberid
				,iscost
			)
			select atdid
				,atypeid
				,lendloan
				,lendloanfor
				,rate
				,ratetype
				,billnumberid
				,iscost 
			from('
			
	WHILE @AcFromLoop <=17
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpVoucherDetails WHERE AcFrom = @AcFromLoop)
		BEGIN
			SET @AcFromLoop += 1
			CONTINUE
		END
			
		SELECT @sql += ' select ' + cast(AtdId  AS varchar(50))+ ' as AtdId
			,'+CASE @AcFromLoop WHEN 15 THEN 'StockATypeID' WHEN 16 THEN 'IncomeATypeID' ELSE 'CostATypeID' END +' as atypeid
			, sum('+ T2.Express +') as lendloan
			,'+CASE WHEN @IsUseBillMoneyDate = 1 THEN 'sum('+dbo.F_ChangeToOriginalCurrency(T2.Express) +')' ELSE '0' END+' as lendloanfor
			,b.rate
			,b.ratetype
			,a.billnumberid
			,'+CASE WHEN dbo.F_ChangeToOriginalCurrency(T2.Express) = '0' THEN '1' ELSE '0' END+' as iscost
		from #BillDetailsInventoryTypeAccount a
		inner join #TmpBillInfo b on b.billnumberid = a.billnumberid
		group by a.billnumberid,'+CASE @AcFromLoop WHEN 15 THEN 'StockATypeID' WHEN 16 THEN 'IncomeATypeID' ELSE 'CostATypeID' END +',b.rate,b.ratetype union all '
		FROM #TmpVoucherDetails T1
				INNER JOIN Ac_BillMoney_List T2 ON T1.BillMoneyId = T2.BillMoneyId
		WHERE  AcFrom = @AcFromLoop
		SET @AcFromLoop += 1
	END
	
	SET @sql = SUBSTRING(@sql,1,LEN(@sql)-9)
	SET @sql += ')T'
	EXEC(@sql)
	
	INSERT INTO #tmpBill
			( billnumberid ,
			  explain ,
			  atypeid ,
			  atypeid2 ,
			  Fdc ,
			  f_exchid ,
			  f_exchidfor ,
			  lendprice ,
			  loanprice ,
			  lendpricefor ,
			  loanpricefor ,
			  FCashFlowItem ,
			  ascids ,
			  FSettleNo ,
			  FSettleTypeID ,
			  comment ,
			  cid ,
			  rate ,
			  fadc ,
			  stypeid ,
			  fyear ,
			  fperiod,
			  atdid,
			  billid
			)
	SELECT DISTINCT * FROM
	(
	SELECT	@VoucherBillId AS billnumberid
			,c.Summary AS explain,
			a.ATypeId AS atypeid,
			'' AS atypeid2,
			Ac.Fdc 
			,@f_exchid AS f_exchid
			,BB.Cid AS f_exchidfor
			,CASE c.Fdc
				WHEN 1	THEN a.lendloan
				WHEN -1 THEN 0
			END AS jie,
			CASE c.Fdc
				WHEN -1 THEN a.lendloan
				WHEN 1	THEN 0
			END AS dai,
			CASE WHEN c.Fdc = 1 AND @IsUseBillMoneyDate = 1 THEN a.lendloanfor
				 WHEN c.Fdc = 1 THEN 
						(CASE a.ratetype 
							WHEN 0 THEN a.lendloan / A.rate
							WHEN 1 THEN a.lendloan * A.rate
						END)
				ELSE 0 
			END AS jiefor,
			CASE WHEN c.Fdc = -1 AND @IsUseBillMoneyDate = 1 THEN a.lendloanfor
				 WHEN c.Fdc = -1 THEN
						(CASE a.ratetype  
							WHEN 0 THEN a.lendloan / A.rate
							WHEN 1 THEN a.lendloan* A.rate
						END)
				ELSE 0 
			END AS daifor,
			NULL AS FCashFlowItem,
			'' AS ascids,
			NULL AS FSettleNo,
			0 AS FSettleTypeID,
			'' AS comment,
			BB.Cid AS cid,
			a.rate,
			c.Fdc AS fadc,
			@verifyid AS stypeid,
			@fyear AS fyear,
			@fperiod AS fperiod,
			a.AtdId,
			BB.billnumberid AS billid
	FROM	#InventoryTypeAccount a
	INNER JOIN #TmpBillInfo BB ON BB.BillNumberId = A.billnumberid
	INNER JOIN Ac_Account AC ON AC.StypeId = BB.VerifyStypeid AND AC.TypeId = A.atypeid
	LEFT JOIN #TmpVoucherDetails c ON a.AtdId = c.AtdId
	) T 
	WHERE jie <> 0 OR dai <> 0
	
	DROP TABLE #BillDetailsInventoryTypeAccount,#InventoryTypeAccount
END

--Awu:调整平衡数
DECLARE @BalanceBillId	INT,@balancemoney  NUMERIC(24, 10) ,@balancemoneyfor  NUMERIC(24, 10) 


DECLARE BalanceCur CURSOR FOR
SELECT billnumberid FROM #TmpBillInfo
	OPEN BalanceCur
	FETCH NEXT FROM BalanceCur INTO @BalanceBillId
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @balancemoney = 0
	SELECT	@balancemoney = SUM(CASE fadc WHEN 1 THEN lendprice ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanprice ELSE 0 END) 
			,@balancemoneyfor = SUM(CASE fadc WHEN 1 THEN lendpricefor ELSE 0 END) - SUM(CASE fadc WHEN -1 THEN loanpricefor ELSE 0 END) 
	FROM #tmpBill
	WHERE billid = @BalanceBillId
	
	
	UPDATE #tmpBill 
	SET #tmpBill.lendprice = (CASE fadc WHEN 1 THEN -@balancemoney ELSE 0 END ),
		#tmpBill.lendpricefor = (CASE WHEN fadc = 1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor 
									  WHEN fadc = 1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN -@balancemoney / T3.rate
											WHEN 1 THEN -@balancemoney * T3.rate
										END
								ELSE 0 END ),
		#tmpBill.loanprice = (CASE fadc WHEN -1 THEN @balancemoney ELSE 0 END ),
		#tmpBill.loanpricefor = (CASE WHEN fadc = -1 AND @IsUseBillMoneyDate = 1 THEN @balancemoneyfor
									  WHEN fadc = -1 THEN 
										CASE T3.BasisType
											WHEN 0 THEN @balancemoney / T3.rate
											WHEN 1 THEN @balancemoney * T3.rate
										END
								ELSE 0 END )
	FROM #tmpBill T1
		INNER JOIN #TmpVoucherDetails T2 ON T1.atdid = T2.atdid AND T2.Express = 'balancemoney' AND T2.Atid = @atid
		INNER JOIN dbo.Ac_Currency T3 ON T1.cid = T3.cid
	WHERE billid = @BalanceBillId
		
	FETCH NEXT FROM BalanceCur INTO @BalanceBillId
END
CLOSE BalanceCur
DEALLOCATE BalanceCur

--去除金额为0的
DELETE FROM #tmpBill WHERE ISNULL(lendprice,0) = 0  AND ISNULL(loanprice,0) = 0 	

--调整明细异常币种	
UPDATE #tmpbill SET f_exchidfor =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
	cid =  CASE WHEN T2.Cid = 0 THEN T1.cid ELSE T2.cid END,
	rate = CASE WHEN T2.Cid = 0 THEN T1.rate ELSE T3.rate END,
	lendpricefor =  CASE WHEN T2.Cid = 0 OR  (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid)  THEN T1.lendpricefor ELSE 
						CASE T3.BasisType WHEN 0 THEN T1.lendprice * T3.rate
										ELSE  T1.lendprice / T3.rate END
					END,
	loanpricefor =  CASE WHEN T2.Cid = 0 OR (@IsUseBillMoneyDate = 1 AND T2.Cid = @BillCid) THEN T1.loanpricefor ELSE 
						CASE T3.BasisType WHEN 0 THEN T1.loanprice * T3.rate
										ELSE  T1.loanprice / T3.rate END
					END
FROM #tmpbill T1 
	INNER JOIN dbo.Ac_Account T2 ON T1.stypeid = T2.StypeId AND T1.atypeid = T2.typeid
	LEFT JOIN dbo.Ac_Currency T3 ON T2.Cid = T3.CId

--凭证明细预处理后表（用于插入）
CREATE TABLE #tmpRow
(
		rowno			INT		IDENTITY(1,1),
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		countIndex		INT,
		addebtid		INT,
		credenceId		INT,
		billindexid		INT,
		asciditem		VARCHAR(50)
)
	
--处理分录号
INSERT INTO #tmpRow(
	billnumberid	,
	explain			,
	atypeid			,
	atypeid2		,
	Fdc				,
	f_exchid		,
	f_exchidfor		,
	lendprice		,
	loanprice		,
	lendpricefor	,
	loanpricefor	,
	FCashFlowItem	,
	ascids			,
	FSettleNo		,
	FSettleTypeID	,
	comment			,
	cid				,
	rate			,
	fadc			,
	stypeid			,
	fyear			,
	fperiod			,
	atdid			,
	countIndex		,
	addebtid		,
	credenceId		,
	billindexid
)
SELECT billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		lendprice,
		loanrice,
		lendpricefor,
		loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		atdid,
		countindex,
		addebtid,
		credenceId,
		billid
FROM
(
SELECT	billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		SUM(lendprice) AS lendprice,
		SUM(loanprice) AS loanrice,
		SUM(lendpricefor) AS lendpricefor,
		SUM(loanpricefor) AS loanpricefor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		atdid,
		@Index AS countindex,
		addebtid,
		credenceId,
		MIN(rowno) AS initrowno,
		billid
FROM	#tmpBill
GROUP BY billnumberid,
		explain,
		atypeid,
		atypeid2,
		Fdc,
		f_exchid,
		f_exchidfor,
		FCashFlowItem,
		ascids,
		FSettleNo,
		FSettleTypeID,
		comment,
		cid,
		rate,
		fadc,
		stypeid,
		fyear,
		fperiod,
		atdid,
		addebtid,
		credenceId,
		billid
) AS TT ORDER BY initrowno



--明细对应的辅助核算信息
CREATE TABLE #TmpAssit
(
	AtdId				INT,			--模板明细ID
	TypeId				VARCHAR(50),	--辅助核算对象id
	Ascids				INT,			--辅助核算类别
	fieldname			VARCHAR(100),
	BillIndexNumberId	INT				--单据ID
)	

--获取明细对应辅助核算
SET @sql = 'INSERT INTO #TmpAssit '
SELECT @sql += 'SELECT '+CAST(T1.AtdId AS VARCHAR(10))+' AS AtdId,'+
			'( '+CAST(T2.FieldValue AS VARCHAR(20))+') AS TypeId,'+CAST(T2.AscIds AS VARCHAR(10)) +' AS Ascids,
			('''+cast(case T2.FieldValue 
					WHEN 'instypeid' THEN 'stypeid'
					WHEN 'outstypeid' THEN 'stypeid'
				ELSE FieldValue END AS varchar(50))+''') as filedname ,BILLNUMBERID AS BillIndexNumberId 
			FROM #TmpBillInfo 
			
			UNION ALL '
FROM dbo.Ac_Auditing_Template_Detail_Assist_CheckItems T1
INNER JOIN #TmpVoucherDetails T3 ON T3.Atid = T1.Atid AND T3.AtdId = T1.AtdId
	LEFT JOIN dbo.Ac_Assist_CheckItems_BillType T2 ON T1.AscIdsDetailId = T2.nId

IF LEN(@sql) > LEN('INSERT INTO #TmpAssit')
BEGIN
	SET @sql = SUBSTRING(@sql,1,LEN(@sql) - 9)
	EXEC(@sql)
END

DECLARE @AssitSql VARCHAR(1000),@AssitItem VARCHAR(1000)

--更新明细ascids
DECLARE @MaxRowNum INT,@CurrentRowNo INT
SET @CurrentRowNo = 1
SELECT @MaxRowNum = COUNT(rowno) FROM #tmprow 

WHILE @CurrentRowNo <= @MaxRowNum
BEGIN
	SET @AssitSql = ''
	SET @AssitItem = ''
	SELECT @AssitSql = @AssitSql + CASE WHEN ISNULL(T1.TypeId,'') = '' THEN '' ELSE  CAST(ac.ascids AS VARCHAR(10)) + ':' + T1.typeid +',' END,@AssitItem = @AssitItem + CASE WHEN ISNULL(T1.TypeId,'') = '' THEN '' ELSE CAST(ac.ascids AS VARCHAR(10)) + ',' END
	FROM Ac_Account_Assist_CheckItems ac
	INNER JOIN #tmpRow T2 ON T2.atypeid = ac.atypeid AND T2.CID = ac.cid AND T2.stypeid = ac.stypeid
	LEFT JOIN 
	(
		SELECT A.*,R.atypeid,R.stypeid,R.cid 
		FROM #TmpAssit A 
		INNER JOIN #tmpRow R ON R.atdid = A.AtdId AND R.billindexid = A.BillIndexNumberId
		WHERE R.rowno = @CurrentRowNo 
	) T1 ON T1.atypeid = ac.atypeid AND T1.CID = ac.cid AND T1.stypeid = ac.stypeid AND T1.ascids = ac.ascids
	WHERE T2.rowno = @CurrentRowNo
	ORDER BY ac.Ascids
	
	UPDATE #tmprow SET ascids =ISNULL(@AssitSql,''),asciditem = ISNULL(@AssitItem,'') WHERE rowno = @CurrentRowNo
	
	SET @CurrentRowNo += 1
END

--返回得到的凭证明细相关信息
SELECT *,@BillType FROM #tmpRow


--排除数据全为0的单据编号
--SELECT DISTINCT BillIndexId
--INTO #TmpBillNumberId
--FROM #tmprow WHERE lendprice <> 0 OR loanprice <> 0

--SET @HasValueBillnumberids = ''
--SELECT @HasValueBillnumberids += CAST(billindexid AS VARCHAR) +','
--FROM #TmpBillNumberId

----插入明细
--INSERT INTO dbo.Ac_Voucher_Bill
--        ( BillNumberId ,
--          Summary ,
--          STypeId ,
--          ATypeId ,
--          ATypeId2 ,
--          Fdc ,
--          F_ExchId ,
--          F_ExchIdFor ,
--          FDebitTotal ,
--          FDebitTotalFor ,
--          FCreditTotal ,
--          FCreditTotalFor ,
--          FCashFlowItem ,
--          AscIds ,
--          FSettleNo ,
--          FSettleTypeID ,
--          FYear ,
--          FPeriod ,
--          Comment ,
--          Cid ,
--          RowNo ,
--          Rate ,
--          FAdc,
--          atid,
--          atdid
--        )
--OUTPUT INSERTED.ID,INSERTED.RowNo INTO #TmpDetailsRow
--SELECT	BillNumberId ,
--          explain ,
--          stypeid ,
--          ISNULL(atypeid,'') ,
--          atypeid2 ,
--          Fdc ,
--          f_exchid ,
--          f_exchidfor ,
--          dbo.F_RoundTotal(lendprice) ,
--          dbo.F_RoundTotal(lendpricefor) ,
--          dbo.F_RoundTotal(loanprice) ,
--          dbo.F_RoundTotal(loanpricefor) ,
--          FCashFlowItem ,
--          ascids ,
--          FSettleNo ,
--          FSettleTypeID ,
--          fyear ,
--          fperiod,
--          comment ,
--          cid ,
--          rowno,
--          rate ,
--          fadc ,
--          @AtId,
--          atdid
--FROM #TmpNewBill



DROP TABLE #tmpAssit,#tmpBill,#tmpRow,#TmpBillInfo,#BillNumberId

DROP TABLE #tmpExpress,#tmpBillIndexAtypeid,#tmpBillMulAccount,#tmpBillIndexAtypeid1,#tmpAccount,
		#tmpMoneyBill,#tmpItemDetail


RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_MF_AC_CreateVoucherForTransferCost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_MF_AC_CreateVoucherForTransferCost]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：李灏龙
	日期：2016年5月13日 
	描述：结转成本
*/
CREATE PROCEDURE P_MF_AC_CreateVoucherForTransferCost
(
	@szCheckMan			VARCHAR(50),		-- 操作员
	@stypeid			VARCHAR(50),		-- 分支机构单选
	@billtypes			VARCHAR(3000),		-- 单据类型多选
	@startdate			DATETIME,			-- 单据起始时间
	@enddate			DATETIME,			-- 单据截止时间
	@type				INT,				-- 结果类型 0.返回错误提示 2.凭证标错，并返回提示
	@date				DATETIME = '',		-- 手工指定日期
	@TransferType		INT
	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @szPID		VARCHAR(MAX),	--返回的信息
		@return		INT,			--返回值
		@MakeErro	VARCHAR(500),
		@flag		INT

--------------------------------------------------------------权限检查-------------------------------------------------------
if @szCheckMan is null return 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @szCheckMan,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @billtypes = ''
BEGIN
	RAISERROR('请选择单据类型！',16,1)
	RETURN 0
END

DECLARE @verifyid VARCHAR(50)

SELECT @verifyid = VerifyID FROM SType WHERE TypeId = @stypeid

--获取当前期间的起始日期，如果后面生成凭证时，凭证日期小于当前期间，则自动更新日期为当前期间的起始日期
DECLARE @FBGEIN	DATETIME
		,@SFBEGIN	DATETIME
SELECT @FBGEIN = P.FBegin,@SFBEGIN=PS.FBegin FROM dbo.Ac_AccountsPeroid_Stype AP 
INNER JOIN Ac_Period P ON AP.FYear = P.FYear AND AP.FPeriod = P.FPeriod 
INNER JOIN Ac_Period PS ON AP.SFYear = PS.FYear AND AP.SFPeriod = PS.FPeriod 
WHERE	AP.Stypeid = @verifyid

IF @enddate <@SFBEGIN
BEGIN
	/*SELECT @billTypeNames +='【'+ BillName+'】、' FROM BillName WHERE BillType IN (SELECT a  FROM f_split(@billtypes,','))
	
	INSERT #Result(txt,flag) VALUES(LEFT(@billTypeNames,LEN(@billTypeNames)-1)+ '在查询条件下没有需要结转成本的单据',-2)
	SELECT * FROM #Result*/
	SELECT '' AS txt,2 as flag
	RETURN
END

IF @startdate < @SFBEGIN
	SET @startdate = @SFBEGIN

--存储生成结果
CREATE TABLE #Result
(
	txt			VARCHAR(1000),
	flag		INT
)

--在指定的查询时间、单据类型、分支机构下，未结转过的单据id
CREATE TABLE #BillnumberidForCreateTable 
(
	billnumberid	NUMERIC(10,0)
	,billtype		INT
	,ATID			INT
)
INSERT INTO #BillnumberidForCreateTable(billnumberid,billtype,ATID)
SELECT	BillNumberId
		,BillType
		,ATID
FROM	BillIndex B
WHERE	B.BillType IN (SELECT a  FROM f_split(@billtypes,','))
	AND BillDate >= @startdate AND BillDate <= @enddate 
	AND RedWord = 0
	AND ifcheck='t'
	AND IsIni = 0
	AND StypeID =@stypeid			
	AND BillNumberId NOT IN (SELECT GoodsBillId  FROM Ac_GoodsBill_VoucherBill WHERE IsCost IN (1,2) AND VourchBillId <> -1)
UNION ALL
SELECT	BillNumberId
		,BillType
		,ATID
FROM	ReceiptBillIndex B
WHERE	B.BillType IN (SELECT a  FROM f_split(@billtypes,','))
	AND BillDate >= @startdate AND BillDate <= @enddate 
	AND RedWord = 0
	AND ifcheck='t'
	AND IsIni = 0
	AND StypeID =@stypeid			
	AND BillNumberId NOT IN (SELECT GoodsBillId  FROM Ac_ReceiptBill_VoucherBill WHERE IsCost IN (1,2) AND VourchBillId <> -1)

DECLARE @billTypeNames	VARCHAR(210)
SET @billTypeNames = ''

IF NOT EXISTS(SELECT TOP 1 1 FROM #BillnumberidForCreateTable)
BEGIN
	/*SELECT @billTypeNames +='【'+ BillName+'】、' FROM BillName WHERE BillType IN (SELECT a  FROM f_split(@billtypes,','))
	
	INSERT #Result(txt,flag) VALUES(LEFT(@billTypeNames,LEN(@billTypeNames)-1)+ '在查询条件下没有需要结转成本的单据',-2)
	SELECT * FROM #Result*/
	SELECT '' AS txt,2 as flag
	RETURN
END

--单据类型信息表变量
DECLARE @BillInfoTable TABLE
(
	id				INT IDENTITY(1,1),
	billtype		INT,
	atid			INT,
	vgid			INT
)

INSERT INTO @BillInfoTable(billtype,atid,vgid)
SELECT	B.billtype
		,B.ATID
		,T.VgId
FROM	#BillnumberidForCreateTable B
INNER JOIN Ac_Auditing_Template T ON T.BillType = B.billtype
GROUP BY B.billtype,B.ATID,T.VgId


--默认模板模式则读取凭证表中默认的atid来更新信息
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'template' AND SubValue = '0') 
BEGIN
	UPDATE B SET B.atid = ISNULL(T.AtId,0),B.vgid=ISNULL(T.VgId,0)
	FROM	@BillInfoTable B
	INNER JOIN Ac_Auditing_Template T ON T.BillType = B.billtype
	WHERE	T.STypeId = @verifyid
		AND	T.IsDefault = 1
END

IF EXISTS(SELECT TOP 1 1 FROM @BillInfoTable WHERE atid <= 0)
BEGIN
	SET @billTypeNames = ''
	SELECT @billTypeNames +='【'+ BillName+'】、' FROM BillName WHERE BillType IN (SELECT Billtype  FROM @BillInfoTable WHERE atid <= 0)
	
	INSERT #Result(txt,flag) VALUES(LEFT(@billTypeNames,LEN(@billTypeNames)-1)+ '没有可使用的凭证模板',-2)
	SELECT * FROM #Result
	RETURN
END

--凭证字表变量，用于后面循环
DECLARE @VgIdTable TABLE
(
	id				INT IDENTITY(1,1),
	vgid			INT
)
INSERT INTO @VgIdTable(vgid)
SELECT	vgid
FROM	@BillInfoTable
WHERE	vgid > 0
GROUP BY vgid

--单据类型表变量，用于后面循环
DECLARE @BillTypeTable TABLE
(
	id				INT IDENTITY(1,1),
	billtype		INT,
	ATID			INT
)

--单据日期表变量，用于后面循环
DECLARE @BillDateTable TABLE
(
	id				INT IDENTITY(1,1),
	billdate		datetime
)

--单据id表变量，用于后面循环
DECLARE @BillNumberIdTable TABLE
(
	billnumberid	NUMERIC(10,0)
)

--单据id临时表，用于存储用来生成凭证的所有单据id。
--#BillnumberidForCreateTable这个表中记录的单据可能在后面循环中被其他线程结转，
--所以再用一个表来存实际用来生成凭证的单据id，也算作一中解决并发问题的方法吧
CREATE TABLE #BillNumberIdForCreateVoucherBill
(
	billnumberid NUMERIC(10,0),
	billtype	INT
)

--单据id临时表，用以存储一个完整凭证所包含的所有单据id
CREATE TABLE #HasValueBillNumberId
(
	billnumberid NUMERIC(10,0),
	billtype	INT
)

--统计单据类型数量,凭证字数量,日期数量
DECLARE @BillTypeCount INT
		,@VgIdCount INT
		,@BillDateCount INT
		,@VgIdLoop	INT
		,@BillTypeLoop	INT
		,@BillDateLoop	INT
		,@VgId	INT
		,@BillType INT
		,@BillDate	DATETIME
		,@ATID	INT
		,@IfCommission INT
		,@BillNumberIds	VARCHAR(MAX)
		,@FYearLoop	INT
		,@FPeriodLoop	INT

SELECT	@VgIdCount = COUNT(vgid)
FROM	@VgIdTable

SET @VgIdLoop = 1
SET @IfCommission = -1 --因为混合了发票与普通单据，所以无法准确区别，赋为-1来区分


CREATE TABLE #ResultLoop
(
	txt			VARCHAR(1000),
	flag		INT
)

CREATE TABLE #checkAssit
(
	id			INT IDENTITY(1,1),
	ascids		VARCHAR(1000)
)

--生成的凭证明细信息
CREATE TABLE #tmpRow
(
		rowno			INT,
		billnumberid	INT,
		explain			VARCHAR(400),
		atypeid			VARCHAR(50),
		atypeid2		VARCHAR(50),
		Fdc				INT,
		f_exchid		INT,
		f_exchidfor		INT,
		lendprice		 NUMERIC(24, 10) ,
		loanprice		 NUMERIC(24, 10) ,
		lendpricefor	 NUMERIC(24, 10) ,
		loanpricefor	 NUMERIC(24, 10) ,
		FCashFlowItem	INT DEFAULT 0,
		ascids			VARCHAR(4000),
		FSettleNo		VARCHAR(200),
		FSettleTypeID	INT,
		comment			VARCHAR(500),
		cid				INT,
		rate			 NUMERIC(24, 10) ,
		fadc			INT,
		stypeid			VARCHAR(50),
		fyear			INT,
		fperiod			INT,
		atdid			INT,
		countIndex		INT,
		addebtid		INT,
		credenceId		INT,
		billindexid		INT,
		asciditem		VARCHAR(50),
		billtype		INT
)
		
--合并科目、币种、汇率、辅助核算相同的明细
CREATE TABLE #TmpNewBill
(
	BillNumberId	INT,
	explain			VARCHAR(400),
	atypeid			VARCHAR(50),
	atypeid2		VARCHAR(50),
	Fdc				INT,
	f_exchid		INT,
	f_exchidfor		INT,
	lendprice		 NUMERIC(24, 10) ,
	loanprice		 NUMERIC(24, 10) ,
	lendpricefor	 NUMERIC(24, 10) ,
	loanpricefor	 NUMERIC(24, 10) ,
	FCashFlowItem	INT DEFAULT 0,
	ascids			VARCHAR(4000),
	FSettleNo		VARCHAR(200),
	FSettleTypeID	INT,
	comment			VARCHAR(500),
	cid				INT,
	rowno			INT IDENTITY(1,1),
	rate			 NUMERIC(24, 10) ,
	fadc			INT,
	stypeid			VARCHAR(50),
	fyear			INT,
	fperiod			INT,
	atdid			INT,
	asciditem		VARCHAR(50)
)


--以凭证字为纬度开始循环
WHILE @VgIdLoop <= @VgIdCount
BEGIN
	SELECT @VgId = VGID FROM @VgIdTable WHERE id = @VgIdLoop
	
	DELETE FROM @BillTypeTable
	
	INSERT INTO @BillTypeTable(billtype,ATID)
	SELECT	billtype,atid
	FROM	@BillInfoTable 
	WHERE	vgid = @VgId
	GROUP BY billtype,atid
	
	DELETE FROM @BillDateTable
	
	IF @date <> ''
		INSERT @BillDateTable(billdate) VALUES(@date)
	ELSE
		INSERT INTO @BillDateTable(billdate)
		SELECT	BillDate
		FROM	BillIndex B
		INNER JOIN #BillnumberidForCreateTable BFC ON BFC.billnumberid = B.BillNumberId AND BFC.billtype = B.BillType
		INNER JOIN @BillTypeTable BT ON BT.billtype = BFC.billtype
		GROUP BY BillDate
		UNION ALL		
		SELECT	BillDate
		FROM	ReceiptBillIndex B
		INNER JOIN #BillnumberidForCreateTable BFC ON BFC.billnumberid = B.BillNumberId AND BFC.billtype = B.BillType
		INNER JOIN @BillTypeTable BT ON BT.billtype = BFC.billtype
		GROUP BY BillDate


	--单据类型数量
	SELECT	@BillTypeCount = COUNT(billtype) 
	FROM	@BillTypeTable

	--单据日期数量
	SELECT @BillDateCount = COUNT(billdate)
	FROM @BillDateTable

	SET @BillDateLoop = 1
	--SELECT * FROM @BillDateTable
	--SELECT * FROM @BillTypeTable
	--以凭日期为纬度开始循环
	WHILE @BillDateLoop <= @BillDateCount
	BEGIN
		
		SELECT @BillDate = billdate FROM @BillDateTable WHERE id = @BillDateLoop
		
		DECLARE @VoucherBillId INT
		
		--对凭证日期做调整
		DECLARE @BillDateIndex	DATETIME
		SET @BillDateIndex = @BillDate
		IF @BillDateIndex < @FBGEIN
			SET @BillDateIndex = @FBGEIN

		--以凭证字、日期为纬度，创建主表
		EXEC @VoucherBillId =   dbo.GP_SaveAc_VoucherIndex 
								@stypeid = @Verifyid, -- varchar(50)
								@vgid = @vgid, -- int
								@billdate = @BillDateIndex, -- datetime
								@billcode = '', -- varchar(400)
								@flowno = 0, -- int
								@attachfilecount = 0, -- int
								@tallyid = '', -- varchar(50)
								@fchecked = 0, -- int
								@auditid = '', -- varchar(50)
								@etypeid = @szCheckMan, -- varchar(50)
								@recheckid = '', -- varchar(50)
								@markerror = '', -- varchar(200)
								@fcredittotal = 0, -- numeric
								@fdebittotal = 0, -- numeric
								@fentrycount = 0, -- int
								@audited = 0, -- int
								@ifcheck = 'f', -- varchar(1)
								@type = 3,
								@IsCommission = @IfCommission
		DECLARE @countRow INT
		SET @countRow = @@ROWCOUNT

		IF @VoucherBillId = -1
		BEGIN
			RAISERROR('您使用的是试用版，凭证数量不能大于200！',16,1)
			SET @szpid = '您使用的是试用版，凭证数量不能大于200！'
			RETURN -2
		END
		ELSE IF @VoucherBillId = -3
		BEGIN
			RAISERROR('检查程序版本错误！',16,1)
			RETURN -2
		END

		IF  @countRow = 0
		BEGIN
			DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
			RAISERROR('写入主表信息错误！',16,1)
			RETURN -2
		END
		--创建主表完成--

		--新的凭证开始，清空上一张凭证的信息
		TRUNCATE TABLE #tmpRow
		TRUNCATE TABLE #TmpNewBill
		TRUNCATE TABLE #checkAssit
		TRUNCATE TABLE #HasValueBillNumberId
		TRUNCATE TABLE #BillNumberIdForCreateVoucherBill
		
		SELECT @FYearLoop =	FYear,@FPeriodLoop = FPeriod	FROM Ac_Voucher WHERE BillNumberId = @VoucherBillId
		SET	@BillTypeLoop = 1
		SET @billTypeNames = ''
		--以单据类型为纬度开始循环，因为单据类型不同，调用的模板不一样，所以只能分单据类型分别生成明细
		WHILE @BillTypeLoop <= @BillTypeCount
		BEGIN

			SELECT @BillType = billtype,@ATID = ATID FROM @BillTypeTable WHERE id = @BillTypeLoop
				
			DELETE FROM @BillNumberIdTable
			
			INSERT INTO @BillNumberIdTable(billnumberid)
			SELECT T1.BillNumberId
			FROM dbo.BillIndex T1
			INNER JOIN #BillnumberidForCreateTable BFC ON BFC.billnumberid = T1.BillNumberId AND BFC.billtype = T1.BillType
			WHERE BFC.billtype = @BillType
				AND ((@date = '' AND T1.BillDate = @BillDate) OR @date <> '')
				AND T1.BillNumberId NOT IN (SELECT GoodsBillId  FROM Ac_GoodsBill_VoucherBill WHERE IsCost IN (1,2) AND VourchBillId <> -1)
			UNION ALL
			SELECT T1.BillNumberId
			FROM dbo.ReceiptBillIndex T1
			INNER JOIN #BillnumberidForCreateTable BFC ON BFC.billnumberid = T1.BillNumberId AND BFC.billtype = T1.BillType
			WHERE BFC.billtype = @BillType
				AND ((@date = '' AND T1.BillDate = @BillDate) OR @date <> '')
				AND T1.BillNumberId NOT IN (SELECT GoodsBillId  FROM Ac_ReceiptBill_VoucherBill WHERE IsCost IN (1,2) AND VourchBillId <> -1)
				
			IF NOT EXISTS(SELECT TOP 1 1 FROM @BillNumberIdTable)
			BEGIN
				SET @BillTypeLoop += 1
				CONTINUE
			END
				
			IF @BillType = 405
			BEGIN
				--先删除一次，以便清除以前标为-1的记录		
				DELETE FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId IN (SELECT billnumberid FROM @BillNumberIdTable) AND IsCost = 1
				--先将筛选出来的单据全部写为已结转状态，后面再根据情况做调整	
				INSERT INTO dbo.Ac_ReceiptBill_VoucherBill(GoodsBillId,VourchBillId,IsCost)SELECT billnumberid,@VoucherBillId,1 FROM @BillNumberIdTable
			END
			ELSE
			BEGIN
				--先删除一次，以便清除以前标为-1的记录		
				DELETE FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId IN (SELECT billnumberid FROM @BillNumberIdTable) AND IsCost = 1
				--先将筛选出来的单据全部写为已结转状态，后面再根据情况做调整	
				INSERT INTO dbo.Ac_GoodsBill_VoucherBill(GoodsBillId,VourchBillId,IsCost)SELECT billnumberid,@VoucherBillId,1 FROM @BillNumberIdTable
			END
			--将实际用于了生成凭证的单据id记录下来
			INSERT INTO #BillNumberIdForCreateVoucherBill(billnumberid,billtype) SELECT billnumberid,@BillType  FROM @BillNumberIdTable
			
			--多单据类型汇总生成记录下实际参与生成的单据类型
			IF @TransferType <> 0
			BEGIN	
				SELECT @billTypeNames +=BillName+'、' FROM BillName WHERE BillType =@BillType
			END
			
			SET @BillNumberIds = ''
			SELECT @BillNumberIds += CAST(billnumberid AS VARCHAR) +',' FROM @BillNumberIdTable
			
			INSERT INTO #tmpRow 
			EXEC P_MF_AC_CreateVoucherDetail_CommonBill
										@BillNumberId=@BillNumberIds,	--VARCHAR(MAX),			-- 单据编号
										@szCheckMan=@szCheckMan,		--VARCHAR(50),			-- 制单人ID值
										@verifyid=@verifyid,	--VARCHAR(50),			--独立分支机构
										@BillType=@BillType,		--INT,					--单据类型
										@FYear=@FYearLoop,			--INT,
										@FPeriod=@FPeriodLoop,		--INT,
										@AtId=@ATID,		--INT = 0,				-- 凭证模版ID
										@VoucherBillId=@VoucherBillId,	--INT = 0,
										@IfCommission=@IfCommission	--INT = 0,				-- 是否提成单311 0.不是 1.是

			--将有数据的单据id记录到临时表#HasValueBillNumberId中，以便后面更新主表上的记账人信息,PS：金额值全为0的单据只记录生单标识，不记录记账人				
			
			SET @BillTypeLoop += 1
		END
		--PRINT 'X'
		--检查凭证
		--INSERT INTO #ResultLoop EXEC P_MF_AC_CheckVoucher_CommonBill @verifyid,@VoucherBillId
		--@BillTypeTable
			--DECLARE @billTypeNames1	VARCHAR(210)
			--SET @billTypeNames1 = ''
			--SELECT @billTypeNames1 +='【'+ BillName+'】、' FROM BillName B INNER JOIN @BillTypeTable T ON B.Billtype = T.billtype

		IF @TransferType <> 0 AND EXISTS(SELECT TOP 1 1 FROM #tmpRow)
		BEGIN
			SET @billTypeNames = '结转【'+LEFT(@billTypeNames,LEN(@billTypeNames)-1)+'】等单据类型的出库成本'
			UPDATE #tmpRow SET explain = @billTypeNames
		END
		
		--合并相同行记录，并按一定顺序生成分录号
		INSERT INTO #TmpNewBill
			( 
				BillNumberId ,
				explain ,
				atypeid ,
				atypeid2 ,
				Fdc ,
				f_exchid ,
				f_exchidfor ,
				lendprice ,
				loanprice ,
				lendpricefor ,
				loanpricefor ,
				FCashFlowItem ,
				ascids ,
				FSettleNo ,
				FSettleTypeID ,
				comment ,
				cid ,
				rate ,
				fadc ,
				stypeid ,
				fyear ,
				fperiod,
				asciditem
			)
		SELECT T.*
		FROM
		(
			SELECT BillNumberId	,
				explain			,
				atypeid			,
				atypeid2		,
				Fdc				,
				f_exchid		,
				f_exchidfor		,
				SUM(lendprice)	AS Lend,
				SUM(loanprice)	AS Loan,
				SUM(lendpricefor) AS LendFor,
				SUM(loanpricefor) AS LoanFor,
				FCashFlowItem	,
				ascids			,
				FSettleNo		,
				FSettleTypeID	,
				comment			,
				cid				,
				rate			,
				fadc			,
				stypeid			,
				fyear			,
				fperiod			,
				asciditem
			FROM #tmprow
			GROUP BY BillNumberId,
				explain			,
				atypeid			,
				atypeid2		,
				Fdc				,
				f_exchid		,
				f_exchidfor		,
				FCashFlowItem	,
				ascids			,
				FSettleNo		,
				FSettleTypeID	,
				comment			,
				cid				,
				rate			,
				fadc			,
				stypeid			,
				fyear			,
				fperiod			,
				asciditem
		)T
		INNER JOIN Ac_Account AC ON AC.TypeId = T.atypeid AND AC.StypeId = T.stypeid
		WHERE Lend <> 0 OR Loan <> 0
		ORDER BY T.fadc,AC.UserCode
		
		--必定不能生成凭证的检查------------
		IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpNewBill) 
		BEGIN			
			INSERT #ResultLoop(txt,flag)
			VALUES('【生成的凭证所有分录借贷金额为0，无法生成或不需生成会计凭证】',-12)
		END
		ELSE
		BEGIN

			--有科目被停用
			IF EXISTS(SELECT TOP 1 1 FROM #TmpNewBill T1 INNER JOIN dbo.Ac_Account T2 ON T1.atypeid = T2.TypeId AND T2.StypeId = @Verifyid AND Deleted = 1)
			BEGIN
				INSERT #ResultLoop(txt,flag)
				VALUES('【生成的凭证中有会计科目被停用】',-10)
			END
			
			DECLARE @LendTotal  NUMERIC(24, 10) ,@LoanTotal  NUMERIC(24, 10) 
			SELECT @LendTotal = SUM(lendprice),@LoanTotal = SUM(loanprice)
			FROM #TmpNewBill
			
			IF @LendTotal <> @LoanTotal
			BEGIN
				INSERT #ResultLoop(txt,flag)
				VALUES('【生成的凭证借贷不平衡】',-2)
			END	

			IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'acpitdataflow' AND SubValue = 1)--必填现金流量
			BEGIN
				DECLARE @countJie  NUMERIC(24, 10) ,@countDai  NUMERIC(24, 10) 

				SELECT @countJie = SUM(lendprice),@countDai = SUM(loanprice)
				FROM #TmpNewBill a
				INNER JOIN dbo.Ac_Account b ON a.ATypeId = b.TypeId AND a.STypeId = b.StypeId
				WHERE BillNumberId = @voucherBillid AND (b.IsBank = 1 OR b.IsCash = 1 OR b.IsOther = 1)
				
				IF @countJie <> @countDai 
				BEGIN
					INSERT #ResultLoop(txt,flag)
					VALUES('【配置要求填写现金流量】',-9)
				END
			END
			
			IF EXISTS(SELECT TOP 1 1 FROM #TmpNewBill WHERE ATypeId = '')  --这种情况可能是项目没有设置对应科目
			BEGIN
				INSERT #ResultLoop(txt,flag)
				VALUES('【生成时存在科目获取失败的分录，请检查项目对应科目】',-1)
			END
			
			IF EXISTS(SELECT TOP 1 1 FROM #TmpNewBill WHERE lendpricefor = 0 AND loanpricefor = 0) 
			BEGIN
				INSERT #ResultLoop(txt,flag)
				VALUES('【生成时存在原币值为0的分录】',-5)
			END		
			
			--异常的生成明细辅助核算与科目辅助核算不匹配
			SELECT DISTINCT a.ATypeId,DBO.F_Get_AccountAscids(A.ATypeId,A.STypeId,A.Cid) AS AscidItem
			INTO #tmpCheckAscidItem
			FROM #TmpNewBill a
			
			IF EXISTS(SELECT TOP 1 1 FROM #TmpNewBill A INNER JOIN #tmpCheckAscidItem B ON A.atypeid = B.atypeid AND A.asciditem <> B.AscidItem)
			BEGIN
				INSERT #ResultLoop(txt,flag)
				VALUES('【存在凭证分录辅助核算项与对应科目实际的辅助核算项不匹配】',-8)
			END

			DROP TABLE #tmpCheckAscidItem	
			
			INSERT INTO #checkAssit(ascids)
			SELECT ascids FROM #TmpNewBill	WHERE ascids <> ''
			DECLARE @loopid INT,@loopcount INT,@loopascids	VARCHAR(1000)
			SELECT @loopid = MIN(id) FROM #checkAssit
			SELECT @loopcount = MAX(id) FROM #checkAssit
			
			WHILE @loopid <= @loopcount
			BEGIN
				SELECT @loopascids = ascids FROM #checkAssit WHERE id = @loopid
				IF EXISTS(SELECT TOP 1 1 FROM f_split(@loopascids,',') WHERE LEN(a)<5)
				BEGIN			
					INSERT #ResultLoop(txt,flag)
					VALUES('【生成时存在辅助核算信息获取失败的分录】',-7)
					SET @loopid = @loopcount
				END
				SET @loopid +=1
			END
		END
		
		--PRINT 'Y'
		IF EXISTS(SELECT TOP 1 1 FROM #ResultLoop WHERE flag = -12)
		BEGIN
			DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
			UPDATE dbo.Ac_GoodsBill_VoucherBill SET VourchBillId = -1 WHERE VourchBillId = @VoucherBillId
			UPDATE dbo.Ac_ReceiptBill_VoucherBill SET VourchBillId = -1 WHERE VourchBillId = @VoucherBillId
			INSERT INTO #Result
			SELECT	*
			FROM	#ResultLoop
			TRUNCATE TABLE #ResultLoop	
		END
		ELSE IF (@type = 0 AND EXISTS(SELECT TOP 1 1 FROM #ResultLoop)) 
		BEGIN
			DELETE FROM dbo.Ac_Voucher WHERE BillNumberId = @VoucherBillId
			DELETE FROM dbo.Ac_GoodsBill_VoucherBill WHERE VourchBillId = @VoucherBillId AND IsCost = 1
			DELETE FROM dbo.Ac_ReceiptBill_VoucherBill WHERE VourchBillId = @VoucherBillId AND IsCost = 1
					
			INSERT INTO #Result
			SELECT	*
			FROM	#ResultLoop
			
			TRUNCATE TABLE #ResultLoop		
		END
		ELSE
		BEGIN
			INSERT INTO dbo.Ac_Voucher_Bill
				( BillNumberId ,
				  Summary ,
				  STypeId ,
				  ATypeId ,
				  ATypeId2 ,
				  Fdc ,
				  F_ExchId ,
				  F_ExchIdFor ,
				  FDebitTotal ,
				  FDebitTotalFor ,
				  FCreditTotal ,
				  FCreditTotalFor ,
				  FCashFlowItem ,
				  AscIds ,
				  FSettleNo ,
				  FSettleTypeID ,
				  FYear ,
				  FPeriod ,
				  Comment ,
				  Cid ,
				  RowNo ,
				  Rate ,
				  FAdc
				)
			SELECT	BillNumberId ,
					  explain ,
					  stypeid ,
					  ISNULL(atypeid,'') ,
					  atypeid2 ,
					  Fdc ,
					  f_exchid ,
					  f_exchidfor ,
					  dbo.F_RoundTotal(lendprice) ,
					  dbo.F_RoundTotal(lendpricefor) ,
					  dbo.F_RoundTotal(loanprice) ,
					  dbo.F_RoundTotal(loanpricefor) ,
					  FCashFlowItem ,
					  ascids ,
					  FSettleNo ,
					  FSettleTypeID ,
					  fyear ,
					  fperiod,
					  comment ,
					  cid ,
					  rowno,
					  rate ,
					  fadc 
			FROM #TmpNewBill
			
			--修正明细摘要
			IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill WHERE RowNo = 1 AND Summary <> '')--第一行没有摘要
			BEGIN	
				UPDATE Ac_Voucher_Bill SET Summary = (SELECT TOP 1 Summary  FROM Ac_Voucher_Bill WHERE Summary <> '' ORDER BY rowno) WHERE rowno = 1
			END
			
			--处理明细辅助核算信息表
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND AscIds <> '')
			BEGIN
				DECLARE @vBId	INT,@MAXvBId	INT,@vBascids	VARCHAR(1000)
				SET @vBascids = ''
				SELECT @vBId = MIN(ID) FROM Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND AscIds <> ''
				SELECT @MAXvBId = MAX(ID) FROM Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND AscIds <> ''
				WHILE @vBId <= @MAXvBId
				BEGIN
					SELECT @vBascids =AscIds  FROM Ac_Voucher_Bill WHERE ID = @vBId
					INSERT INTO Ac_Voucher_Bill_Assist_CheckItems
						(
							BillNumberId,
							vBId,
							typeName,
							TypeId
						)
					SELECT	@VoucherBillId
							,@vBId
							,'0'+LEFT(a,1)
							,RIGHT(a,LEN(a)-2) 
					FROM	f_split(@vBascids,',')
					
					IF @vBId = @MAXvBId
						SET @vBId += 1
					ELSE					
						SELECT @vBId = MIN(ID) FROM Ac_Voucher_Bill WHERE BillNumberId = @VoucherBillId AND AscIds <> '' AND ID > @vBId
				END
			END


			DECLARE @CountRowTotal INT			
			SELECT @CountRowTotal = COUNT(rowno) FROM dbo.Ac_Voucher_Bill WHERE BillNumberId = @voucherbillid
			
			--调整表头信息记录
			UPDATE dbo.Ac_Voucher SET FDebitTotal = @LendTotal,FCreditTotal = @LoanTotal,FEntryCount=@CountRowTotal WHERE BillNumberId = @voucherbillid
			
			
			INSERT INTO #HasValueBillNumberId(billnumberid,billtype)
			SELECT billindexid,billtype FROM #tmpRow WHERE lendprice<>0 OR loanprice <> 0
			
			UPDATE dbo.BillIndex SET TallyId = @szCheckMan WHERE BillNumberId IN (SELECT BillNumberId FROM #HasValueBillNumberId WHERE billtype <> 405)
			UPDATE dbo.ReceiptBillIndex SET TallyId = @szCheckMan WHERE BillNumberId IN (SELECT BillNumberId FROM #HasValueBillNumberId WHERE billtype = 405)
			
			UPDATE Ac_GoodsBill_VoucherBill SET VourchBillId = -1 
			WHERE VourchBillId = @VoucherBillId 
				AND GoodsBillId NOT IN (SELECT billnumberid FROM #HasValueBillNumberId WHERE billtype <> 405 )
				
			UPDATE Ac_ReceiptBill_VoucherBill SET VourchBillId = -1 
			WHERE VourchBillId = @VoucherBillId 
				AND GoodsBillId NOT IN (SELECT billnumberid FROM #HasValueBillNumberId WHERE billtype = 405 )
			
			SET @flag = 1
			SET @MakeErro = ''
			IF @type = 2 AND EXISTS(SELECT TOP 1 1 FROM #ResultLoop)
			BEGIN
				SELECT @MakeErro += txt  FROM #ResultLoop GROUP BY txt
				UPDATE dbo.Ac_Voucher SET MarkError = @MakeErro WHERE BillNumberId = @VoucherBillId
				SET @flag = -1
			END
			
			INSERT INTO #Result(txt,flag) --VALUES('结转成本生成凭证成功',1)			
			SELECT t4.FullName + '-'+ CAST(t3.FlowNo AS VARCHAR(100))AS txt,@flag
			FROM dbo.Ac_Voucher T3 
			INNER JOIN dbo.Ac_Voucher_Group T4 ON T3.VgId = T4.VgId
			WHERE T3.BillNumberId = @VoucherBillId
			
		END
		SET @BillDateLoop += 1
	END
	
	SET @VgIdLoop += 1
END

SELECT * FROM #Result

DROP TABLE #Result,#ResultLoop


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[P_MF_AC_DeletedVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[P_MF_AC_DeletedVoucher]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证删除
-- 备注：根据凭证的billnumberid删除凭证相关信息，不做任何判断，属于强制性删除
-- 时间：	2016年8月26日
-- ========================================================================
CREATE PROC P_MF_AC_DeletedVoucher
(
	@BillNumberIds	VARCHAR(MAX)=''			-- 单据ID
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE	@ErrorCount		INT=0

CREATE TABLE #temp
(
	billnumberid	NUMERIC(10,0)
)
INSERT INTO #temp(billnumberid)
SELECT	a
FROM	f_split(@BillNumberIds,',')

--将DELETE 更改为UPDATE
--DELETE FROM PrintRecord WHERE BillNumberId=@BillNumberId AND BillType=210--打印记录
UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId IN(SELECT BillNumberId FROM #temp) AND BillType=210
SET @ErrorCount+=@@ERROR

UPDATE BillIndex SET TallyId='' 
FROM BillIndex bi
INNER JOIN Ac_GoodsBill_VoucherBill vi ON VI.GoodsBillId=bi.BillNumberId
WHERE vi.VourchBillId IN(SELECT BillNumberId FROM #temp)--更新单据表中对应的Id记账人为空
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_GoodsBill_VoucherBill WHERE VourchBillId IN(SELECT BillNumberId FROM #temp)--物流单据和会计凭证对照表
SET @ErrorCount+=@@ERROR

UPDATE ReceiptBillIndex SET TallyId='' 
FROM ReceiptBillIndex bi
INNER JOIN Ac_ReceiptBill_VoucherBill vi ON VI.GoodsBillId=bi.BillNumberId
WHERE vi.VourchBillId IN(SELECT BillNumberId FROM #temp)--更新单据表中对应的Id记账人为空
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_ReceiptBill_VoucherBill WHERE VourchBillId  IN(SELECT BillNumberId FROM #temp)  --暂估发票单据和会计凭证对照表
SET @ErrorCount+=@@ERROR
	
DELETE FROM Ac_Voucher_Bill_CashMoneyItems WHERE BillNumberId IN(SELECT BillNumberId FROM #temp)
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher_Bill_Assist_CheckItems WHERE BillNumberId IN(SELECT BillNumberId FROM #temp)--删除凭证辅助核算表
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher_Bill WHERE BillNumberId IN(SELECT BillNumberId FROM #temp)--删除凭证明细
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Voucher WHERE BillNumberId IN(SELECT BillNumberId FROM #temp)--删除凭证主表
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_CommissionBill_VoucherBill WHERE VourchBillId IN(SELECT BillNumberId FROM #temp)
SET @ErrorCount+=@@ERROR
DELETE FROM Ac_Provision_Voucher WHERE VoucherId IN(SELECT BillNumberId FROM #temp)
SET @ErrorCount+=@@ERROR		

RETURN @ErrorCount

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_MF_AC_TransferCost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_MF_AC_TransferCost]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：李灏龙
	日期：2016-05-20 16:39:31
	描述：结转成本
*/
CREATE PROCEDURE P_MF_AC_TransferCost
(
	@szCheckMan			VARCHAR(50),		-- 操作员
	@stypeid			VARCHAR(50),		-- 分支机构单选
	@billtypes			VARCHAR(3000),		-- 单据类型多选
	@startdate			DATETIME,			-- 单据起始时间
	@enddate			DATETIME,			-- 单据截止时间
	@TransferType		INT,				-- 结转类型 0:按单据类型分别生成 1:全部汇总生成一张 2:销售成本与其它出库分开结转
	@type				INT,				-- 结果类型 0.返回错误提示 2.凭证标错，并返回提示
	@date				DATETIME = ''		-- 手工指定日期
)
--@encode$--
AS
SET NOCOUNT ON

--存储生成结果
--CREATE TABLE #Result
--(
--	txt			VARCHAR(1000),
--	flag		INT
--)

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype AP
	INNER JOIN SType S ON S.VerifyID = AP.Stypeid
	WHERE	S.TypeId = @stypeid AND IsUse = 1)
BEGIN
	SELECT  '记账分支机构没有开帐，不能结转成本。'  AS txt,-21 AS flag	
	RETURN
END

--调整按配置来决定凭证日期
--1.按单据日期生成
--2.按系统日期生成
--3.生成时手工指定
DECLARE @datetype INT
SELECT @datetype = subvalue FROM dbo.sysdata WHERE SubName = 'voucherdatetype'

IF @datetype = 2
BEGIN
	SET @date = GETDATE()
END

IF @date <> ''
BEGIN
	DECLARE @FBGEIN	DATETIME
			,@FEND	DATETIME
	SELECT @FBGEIN = FBegin FROM dbo.Ac_Period p 
	INNER JOIN Ac_AccountsPeroid_Stype AP ON AP.FYear = P.FYear AND AP.FPeriod = P.FPeriod 
	INNER JOIN SType S ON S.VerifyID = AP.Stypeid
	WHERE	S.TypeId = @stypeid
	
	SELECT @FEND = MAX(FEnd) FROM Ac_Period
	
	IF @FBGEIN > @date OR @date > @FEND
	BEGIN
		SELECT CASE WHEN @datetype=2 THEN '凭证日期指定错误。系统配置为【按系统日期生成】生成凭证，但当前系统日期不在有效的期间范围内，请确认后重试。' ELSE '凭证日期指定错误。系统配置为【生成时手工指定】生成凭证，但所选日期不在有效的期间范围内，请确认后重试。' END AS txt,-20 AS flag	
		RETURN
	END
END

DECLARE @BilltypeGroup	VARCHAR(100)
SET @BilltypeGroup = ''

IF @TransferType = 2    --销售成本与其它出库(140,142,402,403)分开结转
BEGIN
	SELECT	@BilltypeGroup += a + ',' 
	FROM	f_split(@billtypes,',')
	WHERE	a IN ('140','142','402','403')
	
	IF ISNULL(@BilltypeGroup,'') <> ''
	BEGIN
		EXEC P_MF_AC_CreateVoucherForTransferCost @szCheckMan,@stypeid,@BilltypeGroup,@startdate,@enddate,@type,@date,@TransferType
	END
	
	SET @BilltypeGroup = ''
	
	SELECT @BilltypeGroup += a +','
	FROM	f_split(@billtypes,',')
	WHERE	a NOT IN('140','142','402','403')
	
	IF ISNULL(@BilltypeGroup,'') <> ''
	BEGIN
		EXEC P_MF_AC_CreateVoucherForTransferCost @szCheckMan,@stypeid,@BilltypeGroup,@startdate,@enddate,@type,@date,@TransferType
	END
END
ELSE IF @TransferType = 1  --全部汇总生成一张
BEGIN
	EXEC P_MF_AC_CreateVoucherForTransferCost @szCheckMan,@stypeid,@billtypes,@startdate,@enddate,@type,@date,@TransferType
END
ELSE  --按单据类型分别生成
BEGIN
	DECLARE @BilltypeTable TABLE
	(
		id			INT IDENTITY(1,1),
		billtype	INT
	)
	INSERT INTO @BilltypeTable(billtype)
	SELECT	a 
	FROM	f_split(@billtypes,',')
	
	DECLARE @billtypecount INT
			,@billtypeLoop	INT
	
	SELECT @billtypecount = COUNT(billtype) FROM @BilltypeTable
	
	SET @billtypeLoop = 1
	
	WHILE @billtypeLoop <= @billtypecount
	BEGIN
		SELECT @BilltypeGroup = billtype FROM @BilltypeTable WHERE id = @billtypeLoop
		
		EXEC P_MF_AC_CreateVoucherForTransferCost @szCheckMan,@stypeid,@BilltypeGroup,@startdate,@enddate,@type,@date,@TransferType
		
		SET @billtypeLoop += 1
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_MF_BackIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_MF_BackIni]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
 总账系统单独反开帐
*/
CREATE PROCEDURE P_MF_BackIni
(
	@STypeId		VARCHAR(MAX),		--	分支机构
    @returnValue	VARCHAR(MAX) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @KTypeId		VARCHAR(MAX),
		@szCanModiIni	INT,
		@Re				INT,
		@rValue			VARCHAR(MAX),
		@MxSTypeId		VARCHAR(MAX),
		@MxSFullName	VARCHAR(MAX)
		
CREATE TABLE #stype(typeid VARCHAR(50))
IF @stypeid=''
	INSERT	INTO #stype
	SELECT	s.TypeId 
	FROM F_GetAllManagerBaseTypeId(@STypeId,11,'00001') s
	INNER JOIN SType_UserConfig u ON s.TypeId=u.StypeId 
	INNER JOIN dbo.SType B ON S.TypeId=B.TypeId
	WHERE	u.ConfigNo = '1' 
	AND B.deleted=0
ELSE
	INSERT INTO #stype
	        ( typeid )
	VALUES  ( @stypeid)
	
DECLARE @sfullname VARCHAR(max)='',@proinfo INT=1
SELECT @proinfo=subvalue FROM dbo.sysdata WHERE SubName='proinfo'

IF EXISTS(
	SELECT 1 FROM dbo.BillIndex WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype) AND BillType IN(84,85,78,213,212,214,307,410,411)
)
BEGIN
	IF @proinfo=1
		SET @rValue='存在已过账的固定资产单据，请红冲后重试！'
	ELSE
	BEGIN
		SELECT distinct(B.stypeid) AS stypeid
		INTO #stype2
		FROM (
			SELECT stypeid FROM billindex 
			WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
			UNION ALL 
			SELECT stypeid FROM ReceiptBillIndex 
			WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
			UNION ALL 
			SELECT stypeid FROM LendIndex 
			WHERE draft=0 AND RedWord=0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype)
		) AS B
		
		SELECT @sfullname=@sfullname+','+fullname FROM dbo.SType WHERE typeid IN(SELECT stypeid FROM  #stype2)
		SET @sfullname=RIGHT(@sfullname,LEN(@sfullname)-1)
		SET @rValue =@sfullname+'存在已过账的固定资产单据，请红冲后重试！'
		DROP TABLE #stype2
	END
	SET @Re=-2				
	GOTO ERROR
END	
	

DELETE FROM dbo.BillIndex			WHERE draft=0 AND RedWord<>0 AND IsIni=0 AND ifYearBill=0 AND Stypeid IN (SELECT typeid from #stype) AND BillType IN(84,85,78,213,212,214,307,410,411)
	
-----------------
--处理总账的反开账
DECLARE SType_Cursor CURSOR FOR
	SELECT TypeId FROM #stype
OPEN SType_Cursor
FETCH NEXT FROM SType_Cursor INTO @MxSTypeId
WHILE @@FETCH_STATUS = 0
BEGIN	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher V  WHERE v.STypeId = @MxSTypeId AND V.IfCheck = 't')
	BEGIN
		SELECT @rValue = '分支机构【'+FullName+'】存在已记账凭证，请删除后再试！'
		FROM	SType 
		WHERE TypeId = @MxSTypeId
		SET @Re = -2
		GOTO ERROR
		BREAK
	END
	
	EXEC @Re = Gp_BackOkIni_Account @MxSTypeId,@rValue OUTPUT	
		
	IF @Re < 0
	BEGIN						
		GOTO ERROR
		BREAK
	END		
	
	FETCH NEXT FROM SType_Cursor INTO @MxSTypeId
END
CLOSE SType_Cursor
DEALLOCATE SType_Cursor

UPDATE dbo.BillIndex		SET draft=1 WHERE IsIni=1 AND ifYearBill=0 AND Stypeid IN (SELECT  typeid FROM #stype)	AND BillType IN(84,85,78,213,212,214,307,410,411)	
	
DROP TABLE #stype	

--处理固定资产盘点单
TRUNCATE TABLE  dbo.FixedAssetsDetails
TRUNCATE TABLE  dbo.FixedAssetsIndex

IF @@ERROR <> 0
BEGIN		
	SET @Re=-1				
	GOTO ERROR
END						
ELSE
	RETURN 0
	
ERROR:
	SET @ReturnValue = @rValue
	RETURN @Re	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_MF_OkIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_MF_OkIni]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
总账系统单独开帐
*/
CREATE PROCEDURE P_MF_OkIni
(
	@STypeId		VARCHAR(MAX),		--	分支机构
    @ReturnValue	VARCHAR(MAX) out	--  输出信息
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Re				INT,
		@rValue			VARCHAR(MAX),
		@MxSTypeId		VARCHAR(MAX)

DECLARE SType_Cursor CURSOR FOR
	SELECT A.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,'00001') A INNER JOIN dbo.SType B ON A.TypeId=B.TypeId 
	WHERE B.deleted=0
	
OPEN SType_Cursor

FETCH NEXT FROM SType_Cursor INTO @MxSTypeId

WHILE @@FETCH_STATUS = 0
BEGIN		
	--处理账务期初的开账
	EXEC @Re = Gp_OkIni_Account @MxSTypeId,@rValue  OUTPUT	
	
	IF @Re < 0
	BEGIN						
		GOTO ERROR
		BREAK
	END							
	
	IF @@ERROR <> 0
	BEGIN						
		GOTO ERROR
		BREAK
	END		
					
	FETCH NEXT FROM SType_Cursor INTO @MxSTypeId
END
	
CLOSE SType_Cursor
DEALLOCATE SType_Cursor

RETURN @RE

ERROR:	
	CLOSE SType_Cursor
	DEALLOCATE SType_Cursor
	SET @ReturnValue = @rValue
	RETURN @Re	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_MF_YearProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_MF_YearProc]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：李灏龙
--日期：2016年7月28日
--描述：总账年结存处理
-------------------------------------------------------------------------
CREATE   PROCEDURE P_MF_YearProc
(
	@delDraft				char(1) = '1',		-- 1 - 删除草稿数据；0 - 不删除
	@carefinancedata		INT	,				-- 2 - 年结存后财务数据为空；1 - 结转当前财务数据；0 - 保持原来的判断
	@OperatorId				VARCHAR(50),		-- 操作员ID
	@rValue					VARCHAR(400)	OUT
)

AS
SET NOCOUNT ON

DECLARE	@Re		INT

DECLARE	@currentDate	DATE,
		@currentFYear	INT,
		@currentFPeriod	INT,
		@MAXFYear		INT,
		@FBeginYear		INT,
		@DiffFYear		INT

SET @currentDate = CONVERT(VARCHAR(10),GETDATE(),120)

--如果目前的期间表中没有当前时间所处的期间数据，则补写新的期间表数据进去
--总账版存在当前实际时间和系统中期间时间不一样的情况，所以排除掉
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FEnd > @currentDate) AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 0)
BEGIN
	SELECT @MAXFYear = MAX(FYear) FROM Ac_Period
	SELECT @FBeginYear = YEAR(MAX(FBegin)) FROM Ac_Period WHERE FYear = @MAXFYear
	SET @currentFYear = YEAR(@currentDate)
	SET	@DiffFYear = @currentFYear - @FBeginYear
	
	INSERT INTO Ac_Period(FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsDynamic)
	SELECT @currentFYear,FMonth,IsNature,NatureCount,FPeriod,DateAdd(YEAR,@DiffFYear,FBegin),DateAdd(YEAR,@DiffFYear,FEnd),Deleted,IsDynamic 
	FROM Ac_Period WHERE FYear=@MAXFYear
	
	--处理重复的期间数据
	SELECT	DISTINCT FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsCurrent,IsDynamic
	INTO	#Ac_Period		 
	FROM	Ac_Period
	ORDER BY FYear,FPeriod

	TRUNCATE TABLE Ac_Period

	INSERT INTO dbo.Ac_Period(FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsCurrent,IsDynamic)
	SELECT	FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsCurrent,IsDynamic
	FROM	#Ac_Period
	ORDER BY FYear,FPeriod

	DROP TABLE #Ac_Period	
	
	--修改如果是闰年的2月多一天的情况
	UPDATE A SET FEnd=DATEADD(DAY,-1,P.FBegin)
	FROM Ac_Period A
	INNER JOIN Ac_Period P ON RIGHT(CONVERT(VARCHAR(10),P.FBegin,120),5)='03-01' AND P.FYear=A.FYear AND P.FPeriod=A.FPeriod+1	
	
	--如果当前时间未在期间表中，默认第一期
	IF NOT EXISTS(SELECT * FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate)
		SET @currentFPeriod=1
	ELSE 
		SELECT @currentFYear = FYear,@currentFPeriod=FPeriod FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate
	
	UPDATE Ac_AccountsPeroid_Stype SET FPeriod=@currentFPeriod,FYear=@currentFYear
END

--9.7.1 判断启用了总账版但是没有使用总账，则取当前年度所在期间数据 (只判断几张主要数据表)
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Te_Balance) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Te_InitDataDetail) 
	AND ((SELECT MAX(FEnd) FROM Ac_Period)<CONVERT(VARCHAR(10),GETDATE(),120) 
		OR (EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE CONVERT(VARCHAR(10),GETDATE(),120) BETWEEN FBegin AND FEnd) 
				AND EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FMonth<(SELECT FPeriod FROM Ac_Period WHERE CONVERT(VARCHAR(10),GETDATE(),120) BETWEEN FBegin AND FEnd)))) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE SFYear <> FYear OR SFPeriod <> FPeriod)
BEGIN
	--如果目前的期间表中没有当前时间所处的期间数据，则补写新的期间表数据进去
	IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FEnd > @currentDate) 
	BEGIN
		SELECT @MAXFYear = MAX(FYear) FROM Ac_Period
		SELECT @FBeginYear = YEAR(MAX(FBegin)) FROM Ac_Period WHERE FYear = @MAXFYear
		SET @currentFYear = YEAR(@currentDate)
		SET	@DiffFYear = @currentFYear - @FBeginYear
		
		INSERT INTO Ac_Period(FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsDynamic)
		SELECT @currentFYear,FMonth,IsNature,NatureCount,FPeriod,DateAdd(YEAR,@DiffFYear,FBegin),DateAdd(YEAR,@DiffFYear,FEnd),Deleted,IsDynamic 
		FROM Ac_Period WHERE FYear=@MAXFYear
		
		--修改如果是闰年的2月多一天的情况
		UPDATE A SET FEnd=DATEADD(DAY,-1,P.FBegin)
		FROM Ac_Period A
		INNER JOIN Ac_Period P ON RIGHT(CONVERT(VARCHAR(10),P.FBegin,120),5)='03-01' AND P.FYear=A.FYear AND P.FPeriod=A.FPeriod+1	
		
		--如果当前时间未在期间表中，默认第一期
		IF NOT EXISTS(SELECT * FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate)
			SET @currentFPeriod=1
		ELSE 
			SELECT @currentFYear = FYear,@currentFPeriod=FPeriod FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate
		
		UPDATE Ac_AccountsPeroid_Stype SET FPeriod=@currentFPeriod,FYear=@currentFYear
	END
	
	IF NOT EXISTS(SELECT * FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate)
		SET @currentFPeriod=1
	ELSE 
		SELECT @currentFYear = FYear,@currentFPeriod=FPeriod FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate
	
	UPDATE Ac_AccountsPeroid_Stype SET FPeriod=@currentFPeriod,FYear=@currentFYear
END	

SELECT @currentFYear = FYear,@currentFPeriod=FPeriod FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate	
UPDATE Ac_AccountsPeroid_Stype SET SFPeriod=@currentFPeriod,SFYear=@currentFYear,FPeriod=@currentFPeriod,FYear=@currentFYear
WHERE ISNULL(SFYear,'')='' OR ISNULL(SFPeriod,'')='' OR ISNULL(FYear,'')='' OR ISNULL(FPeriod,'')=''
	
---处理固定资产卡片
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
BEGIN
	--更新卡片状态(只有已入账的改为初始)
	UPDATE dbo.Ac_AssetsCards SET AssetsState=1 WHERE AssetsState=3 
	--删除清理的卡片的历史记录和折旧表
	DELETE FROM dbo.Ac_DepreciationPlan WHERE EXISTS (SELECT ac.Id FROM dbo.Ac_AssetsCards ac WHERE ac.AssetsState=5 AND AC.Id = AssetCardId)
	DELETE FROM dbo.Ac_AssetsCards_History WHERE EXISTS (SELECT ac.Id FROM dbo.Ac_AssetsCards ac WHERE ac.AssetsState=5 AND AC.Id = AssertsCardId)
	--卡片分情况删除		
	DELETE FROM dbo.Ac_AssetsCards WHERE ID IN (SELECT ac.Id FROM dbo.Ac_AssetsCards ac LEFT JOIN AssetIncDecBill ai ON ac.Id=ai.AssetCardId WHERE ac.AssetsState=5 AND ai.AssetCardId IS NULL)
	
	--处理分支机构  
	UPDATE dbo.SType SET IfAssetsIni=0
END

DECLARE @period INT=1,@fyear INT
IF EXISTS (SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE IsUse = 1)	--SELECT TOP 1 @period=FPeriod,@fyear=FYear FROM Ac_AccountsPeroid_Stype WHERE IsUse = 1
BEGIN
	SELECT TOP 1 @period=FPeriod,@fyear=FYear FROM Ac_AccountsPeroid_Stype WHERE IsUse = 1
END
ELSE
BEGIN
	SELECT TOP 1 @period=MONTH(GETDATE()),@fyear=YEAR(GETDATE()) FROM Ac_AccountsPeroid_Stype
END

-----------相关系统数据处理-----------
-- 出纳begin

--银行账户处理
UPDATE Te_BankAccount SET YearClose=1 WHERE IsDestroy=1;

-- 转数据到期初 --
-- 期初的数据清掉,再来转数据 , 只清除已结束初始化的
DELETE FROM  Te_InitDataIndex WHERE Finish=1;
DELETE FROM  dbo.Te_InitDataDetail WHERE NOT EXISTS (SELECT Id FROM Te_InitDataIndex WHERE Id = IndexId);


DECLARE @_efullname	VARCHAR(500)
	,@_eusercode	VARCHAR(500)
	,@_subno	numeric

SELECT @_efullname = FullName,@_eusercode= UserCode FROM employee WHERE typeId = @OperatorId

UPDATE sysdata 
SET SubValue = '操作员【'+ @OperatorId + '-'+@_eusercode+'-'+@_efullname +'】于【'+CONVERT(char(25),GETDATE(),121)+'】选择【'+CASE @carefinancedata WHEN 0 THEN '严格财务判定' WHEN 1 THEN '结转当前财务数据' WHEN 2 THEN '年结存后财务数据为空' ELSE '未知' END +'】方式进行年结存'
WHERE SubName = 'YearProcRecord'

IF @carefinancedata <> 2
BEGIN
	--分类得到表头
	INSERT INTO dbo.Te_InitDataIndex
			( STypeId, BUId, Cid, Finish, Rate )
	SELECT T1.STypeId,T1.BUId,T1.Cid,0,T2.Rate
	FROM dbo.Te_Balance T1
	INNER JOIN dbo.Ac_Currency T2 ON T1.Cid = T2.CId
	WHERE T1.cid <> 0 AND T1.FYear = (SELECT TOP 1 FYear from te_period WHERE Stypeid=T1.StypeId) 
		AND T1.FPeriod =(SELECT TOP 1 FPeriod from te_period WHERE Stypeid=T1.stypeId)
	GROUP BY T1.BUId,T1.STypeId,T1.Cid,T2.Rate

	--转明细
	INSERT INTO dbo.Te_InitDataDetail
			( IndexId ,
			  AtypeId ,
			  FDebit ,
			  FCredit ,
			  InitBalance ,
			  AccountId ,
			  FDebitOri ,
			  FCreditOri ,
			  InitBalanceOri
			)
	SELECT  T1.Id,
			ATypeId,
			CASE WHEN T2.FPeriod=12 THEN 0 ELSE FYtdDebitFor END,
			CASE WHEN T2.FPeriod=12 THEN 0 ELSE FYtdCreditFor END,
			FEndBalanceFor,
			AccountId,
			CASE WHEN T2.FPeriod=12 THEN 0 ELSE FYtdDebit END ,
			CASE WHEN T2.FPeriod=12 THEN 0 ELSE FYtdCredit END ,
			FEndBalance
	FROM dbo.Te_InitDataIndex T1
	INNER JOIN dbo.Te_Balance T2 ON T1.STypeId = T2.STypeId AND T1.BUId = T2.BUId AND T1.Cid = T2.Cid
	WHERE T2.Cid <> 0 AND T2.FYear = (SELECT TOP 1 FYear FROM te_period WHERE STypeId=T1.STypeId) 
		AND T2.FPeriod = (SELECT  TOP 1 FPeriod FROM te_period WHERE StypeId=T1.StypeId)
END

----出纳未初始化，且设置了启用期间
UPDATE	A	
SET		SFPeriod = @period,SFYear = @fyear
FROM	Te_StartPeriod A 
WHERE	A.IsUse = 0
	AND	A.SFPeriod != 0
	AND A.SFYear != 0

-- 处理出纳启用期间 设置成当前期间
----出纳已初始化，且未与总账联用
UPDATE a SET SFPeriod=CASE WHEN b.fyear < @fyear THEN @period ELSE b.FPeriod END ,SFYear = CASE WHEN b.fyear < @fyear THEN @fyear ELSE b.FYear END ,IsUse=0
FROM Te_StartPeriod a 
JOIN dbo.Te_Period b ON a.STypeId=b.STypeId 
WHERE A.IsUse = 1
	AND	A.IsConnect = 0

----出纳已初始化，且与总账联用
UPDATE a SET SFPeriod=b.FPeriod,SFYear = b.FYear,CFYear=0,CFPeriod=0,IsUse=0,IsConnect=0
FROM Te_StartPeriod a 
JOIN dbo.Te_Period b ON a.STypeId=b.STypeId 
WHERE A.IsUse = 1
	AND	A.IsConnect = 1	

-- 出纳end

DELETE FROM dbo.Ac_Period WHERE FYear<@fyear 
UPDATE dbo.Ac_Period SET FMonth=@period WHERE FYear=@fyear

UPDATE	SysData
SET		SubValue = @period
WHERE	SubName IN('FPeriod','fmonth')
IF @@ERROR <> 0 RETURN -1

UPDATE	SysData
SET		SubValue = @fyear
WHERE	SubName = 'fyear'
IF @@ROWCOUNT = 0 RETURN -1

--年结前获取当前的会计年度和期间
DECLARE @oldFPeriod INT,
		@oldFYear   VARCHAR(10),
		@newFPeriod	INT,
		@newFYear	VARCHAR(10),
		@iniFyear	INT  --该值暂时没啥用2017-01-10
		
IF EXISTS (SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE IsUse = 1)
BEGIN
	SELECT TOP 1 @newFPeriod=FPeriod,@newFYear=FYear,@iniFyear=SFYear FROM Ac_AccountsPeroid_Stype WHERE IsUse = 1
	SELECT @oldFPeriod = @newFPeriod,@oldFYear=@newFYear
END
ELSE
BEGIN
	SELECT TOP 1 @newFPeriod=MONTH(GETDATE()),@newFYear=YEAR(GETDATE()),@iniFyear=YEAR(GETDATE()) FROM Ac_AccountsPeroid_Stype 
	SELECT @oldFPeriod = MONTH(GETDATE()),@oldFYear=YEAR(GETDATE())		
END
	
--SELECT TOP 1 @newFPeriod=FPeriod,@newFYear=FYear,@iniFyear=SFYear FROM Ac_AccountsPeroid_Stype WHERE IsUse = 1
--SELECT @oldFPeriod = @newFPeriod,@oldFYear=@newFYear

IF @carefinancedata <> 2
BEGIN
	EXEC @Re = Gp_YearProc_Ac_Balance @delDraft,@oldFYear,@oldFPeriod,@newFYear,@newFPeriod,@iniFyear,@rValue OUTPUT
	IF @Re <> 0
	BEGIN
		RAISERROR('结存科目余额信息失败，请确认后重试！',16,1)
		RETURN -1
	END		
END
ELSE
BEGIN
	--清空期初数据
	TRUNCATE TABLE Ac_IniAccount
	TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems
	TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems_Detail

	TRUNCATE TABLE Te_InitDataIndex
	TRUNCATE TABLE Te_InitDataDetail

	UPDATE Te_StartPeriod SET SFYear = 0,SFPeriod = 0,CFYear = 0,CFPeriod=0,IsConnect = 0,IsUse = 0
END	

UPDATE Ac_AccountsPeroid_Stype SET SFYear=@newFYear,SFPeriod=@newFPeriod,FYear=@newFYear,FPeriod=@newFPeriod,IsUse=0

--清除数据
--固定资产：删除部门，减值，变更单
TRUNCATE TABLE Ac_AssetsModifyRecords
TRUNCATE TABLE Ac_ProvisionForImpairment
TRUNCATE TABLE Ac_DepreciationAlteration
TRUNCATE TABLE Ac_FixedAssetsInit_Stype
	
--出纳
TRUNCATE TABLE Te_Balance;
TRUNCATE TABLE Te_Period;

TRUNCATE TABLE Te_Journal;
TRUNCATE TABLE Te_Journal_Detail;
TRUNCATE TABLE Te_BankStatement;
TRUNCATE TABLE Te_BankStatementDetail;

TRUNCATE TABLE Te_CheckRelevance;

--总账
TRUNCATE TABLE Ac_Balance
TRUNCATE TABLE Ac_Balance_Assist_CheckItems
TRUNCATE TABLE Ac_Balance_Assist_CheckItems_Detail

TRUNCATE TABLE Ac_Voucher
TRUNCATE TABLE Ac_Voucher_Bill
TRUNCATE TABLE Ac_Voucher_Bill_Assist_CheckItems
TRUNCATE TABLE Ac_Voucher_Bill_CashMoneyItems

TRUNCATE TABLE Ac_GoodsBill_VoucherBill
TRUNCATE TABLE Ac_ReceiptBill_VoucherBill
TRUNCATE TABLE Ac_CommissionBill_VoucherBill
TRUNCATE TABLE Ac_Provision_Voucher

TRUNCATE TABLE Ac_ProfitAndLoss
TRUNCATE TABLE Ac_ProfitAndLoss_Detail
TRUNCATE TABLE Ac_Voucher_Bill_Temp

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_MF_YearProc_DateTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_MF_YearProc_DateTime]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--作者：李灏龙
--日期：2016年7月28日
--描述：总账年结存处理
-------------------------------------------------------------------------
CREATE   PROCEDURE P_MF_YearProc_DateTime
(
	@delDraft				char(1) = '1',		-- 1 - 删除草稿数据；0 - 不删除
	@carefinancedata		INT	,				-- 2 - 年结存后财务数据为空；1 - 结转当前财务数据；0 - 保持原来的判断
	@OperatorId				VARCHAR(50),		-- 操作员ID
	@yearendDatetime		VARCHAR(20),			--   -年结存的日期	
	@rValue					VARCHAR(400)	OUT
)

AS
SET NOCOUNT ON

DECLARE	@Re		INT

DECLARE	@currentDate	DATE,
		@currentFYear	INT,
		@currentFPeriod	INT,
		@MAXFYear		INT,
		@FBeginYear		INT,
		@DiffFYear		INT,
		@MinFBeginYear  int		

SET @currentDate = CONVERT(VARCHAR(10),@yearendDatetime,120)

--如果目前的期间表中没有当前时间所处的期间数据，则补写新的期间表数据进去
--总账版存在当前实际时间和系统中期间时间不一样的情况，所以排除掉
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FEnd > @currentDate) AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 0)
BEGIN
	SELECT @MAXFYear = MAX(FYear) FROM Ac_Period
	SELECT @FBeginYear = YEAR(MAX(FBegin)) FROM Ac_Period WHERE FYear = @MAXFYear
	SET @currentFYear = YEAR(@currentDate)
	SET	@DiffFYear = @currentFYear - @FBeginYear
	SELECT @MinFBeginYear = YEAR(MIN(FBegin)) FROM Ac_Period WHERE FYear = @MAXFYear
	
	--敏捷4890特殊处理--SELECT @MAXFYear=2018,@FBeginYear=2020,@currentFYear=2020,@DiffFYear=0
	IF(@DiffFYear=0 AND  @MinFBeginYear<>@FBeginYear)
	BEGIN
		SET	@DiffFYear=@FBeginYear-@MinFBeginYear
	END
	
	INSERT INTO Ac_Period(FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsDynamic)
	SELECT @currentFYear,FMonth,IsNature,NatureCount,FPeriod,DateAdd(YEAR,@DiffFYear,FBegin),DateAdd(YEAR,@DiffFYear,FEnd),Deleted,IsDynamic 
	FROM Ac_Period WHERE FYear=@MAXFYear
	
	--处理重复的期间数据
	SELECT	DISTINCT FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsCurrent,IsDynamic
	INTO	#Ac_Period		 
	FROM	Ac_Period
	ORDER BY FYear,FPeriod

	TRUNCATE TABLE Ac_Period

	INSERT INTO dbo.Ac_Period(FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsCurrent,IsDynamic)
	SELECT	FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsCurrent,IsDynamic
	FROM	#Ac_Period
	ORDER BY FYear,FPeriod

	DROP TABLE #Ac_Period	
	
	--修改如果是闰年的2月多一天的情况
	UPDATE A SET FEnd=DATEADD(DAY,-1,P.FBegin)
	FROM Ac_Period A
	INNER JOIN Ac_Period P ON RIGHT(CONVERT(VARCHAR(10),P.FBegin,120),5)='03-01' AND P.FYear=A.FYear AND P.FPeriod=A.FPeriod+1	
	
	--如果当前时间未在期间表中，默认第一期
	IF NOT EXISTS(SELECT * FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate)
		SET @currentFPeriod=1
	ELSE 
		SELECT @currentFYear = FYear,@currentFPeriod=FPeriod FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate
	
	UPDATE Ac_AccountsPeroid_Stype SET FPeriod=@currentFPeriod,FYear=@currentFYear
END

--9.7.1 判断启用了总账版但是没有使用总账，则取当前年度所在期间数据 (只判断几张主要数据表)
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_Voucher) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_AssetsCards) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Te_Balance) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Te_InitDataDetail) 
	AND ((SELECT MAX(FEnd) FROM Ac_Period)<CONVERT(VARCHAR(10),GETDATE(),120) 
		OR (EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE CONVERT(VARCHAR(10),GETDATE(),120) BETWEEN FBegin AND FEnd) 
				AND EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FMonth<(SELECT FPeriod FROM Ac_Period WHERE CONVERT(VARCHAR(10),GETDATE(),120) BETWEEN FBegin AND FEnd)))) 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE SFYear <> FYear OR SFPeriod <> FPeriod)
BEGIN
	--如果目前的期间表中没有当前时间所处的期间数据，则补写新的期间表数据进去
	IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE FEnd > @currentDate) 
	BEGIN
		SELECT @MAXFYear = MAX(FYear) FROM Ac_Period
		SELECT @FBeginYear = YEAR(MAX(FBegin)) FROM Ac_Period WHERE FYear = @MAXFYear
		SET @currentFYear = YEAR(@currentDate)
		SET	@DiffFYear = @currentFYear - @FBeginYear
		
		INSERT INTO Ac_Period(FYear,FMonth,IsNature,NatureCount,FPeriod,FBegin,FEnd,Deleted,IsDynamic)
		SELECT @currentFYear,FMonth,IsNature,NatureCount,FPeriod,DateAdd(YEAR,@DiffFYear,FBegin),DateAdd(YEAR,@DiffFYear,FEnd),Deleted,IsDynamic 
		FROM Ac_Period WHERE FYear=@MAXFYear
		
		--修改如果是闰年的2月多一天的情况
		UPDATE A SET FEnd=DATEADD(DAY,-1,P.FBegin)
		FROM Ac_Period A
		INNER JOIN Ac_Period P ON RIGHT(CONVERT(VARCHAR(10),P.FBegin,120),5)='03-01' AND P.FYear=A.FYear AND P.FPeriod=A.FPeriod+1	
		
		--如果当前时间未在期间表中，默认第一期
		IF NOT EXISTS(SELECT * FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate)
			SET @currentFPeriod=1
		ELSE 
			SELECT @currentFYear = FYear,@currentFPeriod=FPeriod FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate
		
		UPDATE Ac_AccountsPeroid_Stype SET FPeriod=@currentFPeriod,FYear=@currentFYear
	END
	
	IF NOT EXISTS(SELECT * FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate)
		SET @currentFPeriod=1
	ELSE 
		SELECT @currentFYear = FYear,@currentFPeriod=FPeriod FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate
	
	UPDATE Ac_AccountsPeroid_Stype SET FPeriod=@currentFPeriod,FYear=@currentFYear
END	

SELECT @currentFYear = FYear,@currentFPeriod=FPeriod FROM Ac_Period WHERE FBegin <= @currentDate AND FEnd >= @currentDate	
UPDATE Ac_AccountsPeroid_Stype SET SFPeriod=@currentFPeriod,SFYear=@currentFYear,FPeriod=@currentFPeriod,FYear=@currentFYear
WHERE ISNULL(SFYear,'')='' OR ISNULL(SFPeriod,'')='' OR ISNULL(FYear,'')='' OR ISNULL(FPeriod,'')=''
	
DECLARE @period INT=1,@fyear INT
SELECT @period=FPeriod,@fyear=FYear FROM dbo.Ac_Period WHERE FBegin <= @yearendDatetime AND FEnd >= @yearendDatetime

---处理固定资产卡片
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
BEGIN
	--更新卡片状态(只有已入账的改为初始)
	UPDATE dbo.Ac_AssetsCards SET AssetsState=1 WHERE AssetsState=3 AND InAccountDate < @yearendDatetime
	--删除清理的卡片的历史记录和折旧表
	DELETE FROM dbo.Ac_DepreciationPlan WHERE EXISTS (SELECT ac.Id FROM dbo.Ac_AssetsCards ac WHERE ac.AssetsState=5 AND AC.Id = AssetCardId)
	DELETE FROM dbo.Ac_AssetsCards_History WHERE EXISTS (SELECT ac.Id FROM dbo.Ac_AssetsCards ac WHERE ac.AssetsState=5 AND AC.Id = AssertsCardId)
	--卡片分情况删除		
	DELETE FROM dbo.Ac_AssetsCards 
	WHERE ID IN (SELECT ac.Id 
				 FROM dbo.Ac_AssetsCards ac 
				 LEFT JOIN AssetIncDecBill ai ON ac.Id=ai.AssetCardId 
				 WHERE ac.AssetsState=5 AND ai.AssetCardId IS NULL)
	
	---------------------模拟初始化s--------------------------------
	--处理分支机构  
	--UPDATE dbo.SType SET IfAssetsIni=0
	UPDATE Ac_FixedAssetsInit_Stype SET fyear=@FYear,fperiod=@Period,etypeid=@OperatorId,InitDate=@yearendDatetime 
	
	--处理历史记录
	CREATE TABLE #tempCard
	(
		cardid INT,
		orderid INT,
		stypeid VARCHAR(50),
		cardstate INT
	)
	INSERT INTO #tempCard(cardid, orderid, stypeid,cardstate)
	SELECT aa.id AS cardid,ROW_NUMBER() over(ORDER BY aa.id) AS orderid,aa.STypeId,aa.AssetsState
	FROM dbo.Ac_AssetsCards aa
	JOIN dbo.Ac_AssetsCategory aac ON aa.CategoryId=aac.Id AND aac.StypeId=aa.STypeId
	WHERE AssetsState=1 OR AssetsState=4

	DECLARE @tempcardid INT,
			@state  INT,
			@index	INT,
			@count	INT
			
	SELECT @Count=COUNT(*) FROM #tempCard 			
	SET @index = 1
	
	WHILE @index <= @Count
	BEGIN
		SELECT @tempcardid=cardid,@state=cardstate FROM #tempCard WHERE orderid=@index 	 
		/*
		---生成折旧表
		IF @state=1
			EXEC Gp_CreateDepreciationPlan @tempcardid,1
        
        IF @state=4 AND @isReCreate=1
		BEGIN
			--先删除
			DELETE  dbo.Ac_DepreciationPlan WHERE AssetCardId=@tempcardid
			--后重新生成
			EXEC Gp_CreateDepreciationPlan @tempcardid,1
		END
		*/
        
		---记录卡片历史记录
		--DECLARE @tempRe VARCHAR(max)
		--EXEC Gp_SaveAssetsCardHistory  @MxSTypeId,@tempcardid,@OperatorId,@yearendDatetime,0,0,0,@tempRe OUT
		
		INSERT INTO Ac_AssetsCards_History
			(	AssertsCardId,TypeId,Parid,UserCode,FullName,STypeId,AssertATypeId,DepATypeId,DisATypeId,DevalueATypeId,CategoryId,LocationId,
			   ConditionId,Size,DTypeid,InAccountDate,BusinessTypeId,Total,Cid,F_Total,Rate,DepTotal,DevalueReady,NetValue,NetSalvage,NetSalvageRate,
			   DepreciationMean,DurYear,durmonth,DepreciationMonth,Comment,AssetsState,OperationDate,ETypeId,Businessdate,BillId,billtype,AuditType,
			   barcode,ExpectWork,FinishWork,WorkUnit
			)
		SELECT TOP 1 AssertsCardId,TypeId,Parid,UserCode,FullName,STypeId,AssertATypeId,DepATypeId,DisATypeId,DevalueATypeId,CategoryId,LocationId,
			   ConditionId,Size,DTypeid,InAccountDate,BusinessTypeId,Total,Cid,F_Total,Rate,DepTotal,DevalueReady,NetValue,NetSalvage,NetSalvageRate,
			   DepreciationMean,DurYear,durmonth,DepreciationMonth,Comment,@state,GETDATE(),ETypeId,@yearendDatetime,0,0,0,
			   barcode,ExpectWork,FinishWork,WorkUnit
		FROM dbo.Ac_AssetsCards_History
		WHERE AssertsCardId = @tempcardid AND BusinessDate < @yearendDatetime
		ORDER BY id DESC
		--SELECT @CardID,TypeId,Parid,UserCode,FullName,STypeId,AssertATypeId,DepATypeId,DisATypeId,DevalueATypeId,CategoryId,LocationId,
		--	   ConditionId,Size,DTypeid,InAccountDate,BusinessTypeId,Total,Cid,F_Total,Rate,DepTotal,DevalueReady,NetValue,NetSalvage,NetSalvageRate,
		--	   DepreciationMean,DurYear,durmonth,DepreciationMonth,Comment,AssetsState,GETDATE(),@Etypeid,@Businessdate,@billnumberid,@billtype,@AuditType,
		--	   BarCode,ExpectWork,FinishWork,WorkUnit
		--FROM dbo.Ac_AssetsCards WHERE Id=@CardID
		
		SET @index = @index + 1
	END
	
	---修改卡片状态（只处理初始状态的）
	UPDATE ac SET AssetsState=3 
	FROM dbo.Ac_AssetsCards ac 
	WHERE AssetsState=1 AND InAccountDate < @yearendDatetime
	
	DROP TABLE #tempCard
	---------------------模拟初始化e-------------------------------
END

-----------相关系统数据处理-----------
-- 出纳begin

--银行账户处理
UPDATE Te_BankAccount SET YearClose=1 WHERE IsDestroy=1;

-- 转数据到期初 --
-- 期初的数据清掉,再来转数据 , 只清除已结束初始化的
DELETE FROM  Te_InitDataIndex WHERE Finish=1;
DELETE FROM  dbo.Te_InitDataDetail WHERE NOT EXISTS (SELECT Id FROM Te_InitDataIndex WHERE Id = IndexId);


DECLARE @_efullname	VARCHAR(500)
	,@_eusercode	VARCHAR(500)
	,@_subno	numeric

SELECT @_efullname = FullName,@_eusercode= UserCode FROM employee WHERE typeId = @OperatorId

UPDATE sysdata 
SET SubValue = '操作员【'+ @OperatorId + '-'+@_eusercode+'-'+@_efullname +'】于【'+CONVERT(char(25),GETDATE(),121)+'】选择【'+CASE @carefinancedata WHEN 0 THEN '严格财务判定' WHEN 1 THEN '结转当前财务数据' WHEN 2 THEN '年结存后财务数据为空' ELSE '未知' END +'】方式进行年结存'
WHERE SubName = 'YearProcRecord'

IF @carefinancedata <> 2
BEGIN
	--分类得到表头
	INSERT INTO dbo.Te_InitDataIndex
			( STypeId, BUId, Cid, Finish, Rate )
	SELECT T1.STypeId,T1.BUId,T1.Cid,1,T2.Rate
	FROM dbo.Te_Balance T1
	INNER JOIN dbo.Ac_Currency T2 ON T1.Cid = T2.CId
	WHERE T1.cid <> 0 AND T1.FYear = @fyear 
		AND T1.FPeriod =@period
	GROUP BY T1.BUId,T1.STypeId,T1.Cid,T2.Rate

	--转明细
	INSERT INTO dbo.Te_InitDataDetail
			( IndexId ,
			  AtypeId ,
			  FDebit ,
			  FCredit ,
			  InitBalance ,
			  AccountId ,
			  FDebitOri ,
			  FCreditOri ,
			  InitBalanceOri
			)
	SELECT  T1.Id,
			ATypeId,
			CASE WHEN T2.FPeriod=1 THEN 0 ELSE FYtdDebitFor END,
			CASE WHEN T2.FPeriod=1 THEN 0 ELSE FYtdCreditFor END,
			t2.InitBalanceFor,
			AccountId,
			CASE WHEN T2.FPeriod=1 THEN 0 ELSE FYtdDebit END ,
			CASE WHEN T2.FPeriod=1 THEN 0 ELSE FYtdCredit END ,
			t2.InitBalance
	FROM dbo.Te_InitDataIndex T1
	INNER JOIN dbo.Te_Balance T2 ON T1.STypeId = T2.STypeId AND T1.BUId = T2.BUId AND T1.Cid = T2.Cid
	WHERE T2.Cid <> 0 AND T2.FYear = @fyear
		AND T2.FPeriod = @period
END

----出纳未初始化，且设置了启用期间
UPDATE	A	
SET		SFPeriod = @period,SFYear = @fyear
FROM	Te_StartPeriod A 
WHERE	A.SFPeriod != 0
	AND A.SFYear != 0

-- 出纳end


UPDATE	SysData
SET		SubValue = @period
WHERE	SubName IN('FPeriod','fmonth')
IF @@ERROR <> 0 RETURN -1

UPDATE	SysData
SET		SubValue = @fyear
WHERE	SubName = 'fyear'
IF @@ROWCOUNT = 0 RETURN -1

IF @carefinancedata <> 2
BEGIN
	EXEC @Re = Gp_YearProc_DateTime_Ac_Balance @delDraft,@yearendDatetime,@rValue OUTPUT
	IF @Re <> 0
	BEGIN
		RAISERROR('结存科目余额信息失败，请确认后重试！',16,1)
		RETURN -1
	END		
END
ELSE
BEGIN
	--清空期初数据
	TRUNCATE TABLE Ac_IniAccount
	TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems
	TRUNCATE TABLE Ac_IniAccount_Assist_CheckItems_Detail

	TRUNCATE TABLE Te_InitDataIndex
	TRUNCATE TABLE Te_InitDataDetail

	UPDATE Te_StartPeriod SET SFYear = @fyear,SFPeriod = @period --,CFYear = 0,CFPeriod=0,IsConnect = 0,IsUse = 0
	
	--获取年结前年度、期间值
	DECLARE
		@NewFYear		INT,
		@NewFPeriod		INT,
		@OldFYear		INT,
		@OldFPeriod		INT
		
	SELECT @NewFYear=FYear,@NewFPeriod=FPeriod FROM Ac_Period WHERE @yearendDatetime BETWEEN FBegin AND	FEnd
	
	IF @NewFPeriod = 1
	BEGIN
		SET @OldFYear = @NewFYear - 1
		SELECT @OldFPeriod = MAX(FPeriod) FROM dbo.Ac_Period
	END 
	ELSE
	BEGIN
		SET @OldFYear = @NewFYear
		SET @OldFPeriod = @NewFPeriod - 1
	END 
	
	
	SELECT FEndBalance,FEndBalanceFor,ATypeId,STypeId,Cid,FEndqty,FYtdDebit,FYtdDebitFor,FYtdDebitqty,FYtdCredit,FYtdCreditFor,FYtdCreditqty 
	INTO #Ac_Balance
	FROM Ac_Balance
	WHERE FPeriod = 0
	
	SELECT FEndBalance,FEndBalanceFor,FEndqty,ATypeId,STypeId,Cid,IniYTotal,IniYTotalFor,IniYqty
	INTO #Ac_Balance_Assist_CheckItems
	FROM Ac_Balance_Assist_CheckItems 
	WHERE FPeriod=0
	
	SELECT FEndBalance,FEndBalanceFor,FEndqty,STypeId,ATypeId,Cid,Ascids,FieldValue 
	INTO #Ac_Balance_Assist_CheckItems_Detail
	FROM Ac_Balance_Assist_CheckItems_Detail 
	WHERE FPeriod=0
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Balance WHERE FYear = @OldFYear AND FPeriod = @OldFPeriod)
	BEGIN
		INSERT INTO #Ac_Balance(FEndBalance,FEndBalanceFor,ATypeId,STypeId,Cid,FEndqty,FYtdDebit,FYtdDebitFor,FYtdDebitqty,FYtdCredit,FYtdCreditFor,FYtdCreditqty)
		SELECT FEndBalance,FEndBalanceFor,ATypeId,STypeId,Cid,FEndqty,FYtdDebit,FYtdDebitFor,FYtdDebitqty,FYtdCredit,FYtdCreditFor,FYtdCreditqty 
		FROM Ac_Balance
		WHERE FYear = @OldFYear AND FPeriod = @OldFPeriod
		
		INSERT INTO #Ac_Balance_Assist_CheckItems(FEndBalance,FEndBalanceFor,FEndqty,ATypeId,STypeId,Cid,IniYTotal,IniYTotalFor,IniYqty)
		SELECT FEndBalance,FEndBalanceFor,FEndqty,ATypeId,STypeId,Cid,IniYTotal,IniYTotalFor,IniYqty 
		FROM Ac_Balance_Assist_CheckItems
		WHERE FYear = @OldFYear AND FPeriod = @OldFPeriod
		
		INSERT INTO #Ac_Balance_Assist_CheckItems_Detail(FEndBalance,FEndBalanceFor,FEndqty,STypeId,ATypeId,Cid,Ascids,FieldValue)
		SELECT FEndBalance,FEndBalanceFor,FEndqty,STypeId,ATypeId,Cid,Ascids,FieldValue 
		FROM Ac_Balance_Assist_CheckItems_Detail 
		WHERE FYear = @OldFYear AND FPeriod = @OldFPeriod
	END	
	ELSE
	BEGIN
		INSERT INTO #Ac_Balance(FEndBalance,FEndBalanceFor,ATypeId,STypeId,Cid,FEndqty,FYtdDebit,FYtdDebitFor,FYtdDebitqty,FYtdCredit,FYtdCreditFor,FYtdCreditqty)
		SELECT FBeginBalance,FBeginBalanceFor,ATypeId,STypeId,Cid,FBeginqty,0,0,0,0,0,0 
		FROM Ac_Balance
		WHERE FYear = @NewFYear AND FPeriod = @NewFPeriod
		
		INSERT INTO #Ac_Balance_Assist_CheckItems(FEndBalance,FEndBalanceFor,FEndqty,ATypeId,STypeId,Cid,IniYTotal,IniYTotalFor,IniYqty)
		SELECT IniTotal,IniTotalFor,Iniqty,ATypeId,STypeId,Cid,IniYTotal,IniYTotalFor,IniYqty 
		FROM Ac_Balance_Assist_CheckItems
		WHERE FYear = @NewFYear AND FPeriod = @NewFPeriod
		
		INSERT INTO #Ac_Balance_Assist_CheckItems_Detail(FEndBalance,FEndBalanceFor,FEndqty,STypeId,ATypeId,Cid,Ascids,FieldValue)
		SELECT IniTotal,IniTotalFor,Iniqty,STypeId,ATypeId,Cid,Ascids,FieldValue 
		FROM Ac_Balance_Assist_CheckItems_Detail 
		WHERE FYear = @NewFYear AND FPeriod = @NewFPeriod
	END 
	
	--科目余额表
	UPDATE B SET 
		B.FBeginBalance-=F.FEndBalance,
		B.FBeginBalanceFor-=F.FEndBalanceFor,
		B.FBeginqty-=F.FEndqty,
		
		B.FEndBalance-=F.FEndBalance,
		B.FEndBalanceFor-=F.FEndBalanceFor,
		B.FEndqty-=F.FEndqty,
		
		B.FYtdDebit-=CASE WHEN B.FYear=@OldFYear THEN F.FYtdDebit ELSE 0 END,
		B.FYtdDebitFor-=CASE WHEN B.FYear=@OldFYear THEN F.FYtdDebitFor ELSE 0 END,
		B.FYtdDebitqty-=CASE WHEN B.FYear=@OldFYear THEN F.FYtdDebitqty ELSE 0 END,
		
		B.FYtdCredit-=CASE WHEN B.FYear=@OldFYear THEN F.FYtdCredit ELSE 0 END ,
		B.FYtdCreditFor-=CASE WHEN B.FYear=@OldFYear THEN F.FYtdCreditFor ELSE 0 END,
		B.FYtdCreditqty-=CASE WHEN B.FYear=@OldFYear THEN F.FYtdCreditqty ELSE 0 END 
	FROM Ac_Balance B
	INNER JOIN #Ac_Balance F ON F.STypeId=B.STypeId AND F.ATypeId=B.ATypeId AND F.Cid=B.Cid

	--科目余额表 辅助核算总表
	UPDATE B SET 
		B.IniTotal-=F.FEndBalance,
		B.IniTotalFor-=F.FEndBalanceFor,
		B.Iniqty-=F.FEndqty,
		
		B.FEndBalance-=F.FEndBalance,
		B.FEndBalanceFor-=F.FEndBalanceFor,
		B.FEndqty-=F.FEndqty,
		
		B.IniYTotal-=CASE WHEN B.FYear=@OldFYear THEN F.IniYTotal ELSE 0 END,
		B.IniYTotalFor-=CASE WHEN B.FYear=@OldFYear THEN F.IniYTotalFor ELSE 0 END,
		B.IniYqty-=CASE WHEN B.FYear=@OldFYear THEN F.IniYqty ELSE 0 END
		
	FROM Ac_Balance_Assist_CheckItems B
	INNER JOIN #Ac_Balance_Assist_CheckItems F ON F.STypeId=B.STypeId AND F.ATypeId=B.ATypeId AND F.Cid=B.Cid	

	--科目余额表 辅助核算明细表
	UPDATE B SET 
		B.IniTotal-=F.FEndBalance,
		B.IniTotalFor-=F.FEndBalanceFor,
		B.Iniqty-=F.FEndqty,
		
		B.FEndBalance-=F.FEndBalance,
		B.FEndBalanceFor-=F.FEndBalanceFor,
		B.FEndqty-=F.FEndqty
	FROM Ac_Balance_Assist_CheckItems_Detail B
	INNER JOIN #Ac_Balance_Assist_CheckItems_Detail F ON F.STypeId=B.STypeId AND F.ATypeId=B.ATypeId AND F.Cid=B.Cid AND F.Ascids=B.Ascids AND F.FieldValue=B.FieldValue	

	DROP TABLE #Ac_Balance,#Ac_Balance_Assist_CheckItems,#Ac_Balance_Assist_CheckItems_Detail
END	

DELETE FROM dbo.Ac_Period WHERE FYear<@fyear 
UPDATE dbo.Ac_Period SET FMonth=@period WHERE FYear=@fyear

UPDATE Ac_AccountsPeroid_Stype SET SFYear=@FYear,SFPeriod=@Period

UPDATE Ac_FixedAssetsInit_Stype SET FYear = @fyear,FPeriod = @period,InitDate = @yearendDatetime

--清除数据
--固定资产：删除部门，减值，变更单
DELETE FROM Ac_AssetsModifyRecords WHERE BusinessDate < @yearendDatetime
DELETE FROM Ac_ProvisionForImpairment WHERE BusinessDate < @yearendDatetime
DELETE FROM Ac_DepreciationAlteration WHERE BusinessDate < @yearendDatetime
	
--出纳
DELETE FROM Te_Balance WHERE FYear < @fyear OR (FYear = @fyear AND FPeriod < @period);

DELETE FROM Te_Journal WHERE Businessdate < @yearendDatetime;
DELETE FROM Te_Journal_Detail WHERE Businessdate < @yearendDatetime;
DELETE FROM Te_BankStatement WHERE Businessdate < @yearendDatetime;
DELETE FROM Te_BankStatementDetail WHERE Businessdate < @yearendDatetime;

DELETE FROM Te_CheckRelevance WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Te_Journal WHERE Id = dbo.Te_CheckRelevance.JournalId);

--删除出纳后初始化数据


--分支机构
CREATE TABLE #GetManSTypeId
(
	Id	INT IDENTITY(1,1),
	TypeId	VARCHAR(50),
	sfullname	VARCHAR(100),
	FYear	INT,
	FPeriod	INT,
	StartDate	DATETIME
)

INSERT INTO #GetManSTypeId(TypeId,sfullname,FYear,FPeriod,StartDate)
SELECT T1.TypeId,T2.FullName,T3.SFYear,T3.SFPeriod,DATEADD(day,-1,T4.FBegin)
FROM  F_GetAllManagerBaseTypeId('',11,@OperatorId) T1 
	INNER JOIN dbo.SType T2 ON T1.TypeId = T2.TypeId
	LEFT JOIN dbo.Te_StartPeriod T3 ON T1.TypeId = T3.STypeId
	LEFT JOIN dbo.Ac_Period T4 ON T3.SFYear = T4.FYear AND T3.SFPeriod = T4.FPeriod


SELECT  ISNULL(AccountId,0) AS AccountId,
			ISNULL(InitBalanceOri,0) AS InitBalance,
			CASE WHEN BUID = 3 THEN (ISNULL(InitBalanceOri,0) + ISNULL(FDebitOri,0) - ISNULL(FCreditOri,0))
				ELSE
				(ISNULL(InitBalanceOri,0) + ISNULL(FCreditOri,0) - ISNULL(FDebitOri,0)) 
			END AS InitYearBalance,
			T1.Cid,
			FYear,
			FPeriod,
			ISNULL(FDebitOri,0) AS FDebitOri,
			ISNULL(FCreditOri,0) AS FCreditOri,
			ISNULL(InitBalanceOri,0) AS FEndBalance,
			0 AS FYtdDebit,
			0 AS FYtdCredit,
			BUId,
			AtypeId,
			STypeId,
			ISNULL(T2.InitBalance,0) AS InitBalanceFor,
			CASE WHEN BUID = 3 THEN (ISNULL(InitBalance,0) + ISNULL(FDebit,0) - ISNULL(FCredit,0))
				ELSE (ISNULL(InitBalance,0) + ISNULL(FCredit,0) - ISNULL(FDebit,0)) 
			END AS  InitYearBalanceFor,
			ISNULL(FDebit,0) AS FDebitFor,
			ISNULL(FCredit,0) AS FCreditFor,
			ISNULL(T2.InitBalance,0) AS FEndBalanceFor,
			0 AS FYtdDebitFor,
			0 AS FYtdCreditFor,
			StartDate,
			T1.Rate
	INTO #TmpInitData
	FROM dbo.Te_InitDataIndex T1
		INNER JOIN dbo.Te_InitDataDetail T2 ON T1.Id = T2.IndexId
		INNER JOIN #GetManSTypeId T3 ON T1.STypeId = T3.TypeId
		INNER JOIN dbo.Ac_Currency T4 ON T1.Cid = T4.CId
	WHERE T2.FDebit <> 0 OR T2.FCredit <> 0 OR T2.InitBalance <> 0
	
	--0.写日记账、银行对账单
	--①日记账
	INSERT INTO dbo.Te_Journal_Detail
	        ( BusinessDate ,
	          SourceId ,
	          VoucherId ,
	          ETypeId ,
	          Summary ,
	          FDebit ,
	          FCredit ,
	          FEndBalance ,
	          AccountId ,
	          IsCash ,
	          FDC ,
	          STypeId ,
	          ATypeId ,
	          FSettleId ,
	          FSettleNo ,
	          Cid ,
	          Rate,
	          IsInit,
	          FDebitOri,
	          FCreditOri,
	          FEndBalanceOri
	        )
	SELECT  StartDate,
			0,
			0,
			@OperatorId,
			'期初数据',
			0,
			0,
			InitBalanceFor,
			AccountId,
			CASE WHEN BUId = 1 THEN 1 ELSE 0 END AS IsCash,
			T2.FDC,
			T1.STypeId,
			AtypeId,
			0,
			'',
			T1.Cid,
			T1.Rate,
			1,
			0,
			0,
			FEndBalance
	FROM #TmpInitData T1
		INNER JOIN dbo.Ac_Account T2 ON T1.STypeId = T2.StypeId AND T1.AtypeId = T2.TypeId
	WHERE T1.BUId IN (1,2)


	INSERT INTO dbo.Te_Journal
	        ( Businessdate ,
	          YesterdayFBalance ,
	          FDebitTotal ,
	          FCreditTotal ,
	          FBalance ,
	          AccountId ,
	          IsCash ,
	          STypeId ,
	          ATypeId ,
	          FDC ,
	          Cid
	        )
	SELECT  BusinessDate,
			0 AS YesterdayFBalance,
			0 AS FDebitTotal,
			0 AS FCreditTotal,
			FEndBalance,
			AccountId,
			IsCash,
			STypeId,
			ATypeId,
			FDC,
			Cid
	FROM dbo.Te_Journal_Detail T1
		INNER JOIN #GetManSTypeId T2 ON T1.STypeId = T2.typeid
	WHERE IsInit = 1
	
	UNION ALL
	
	SELECT  BusinessDate,
			0 AS YesterdayFBalance,
			0 AS FDebitTotal,
			0 AS FCreditTotal,
			FEndBalanceOri,
			AccountId,
			IsCash,
			STypeId,
			ATypeId,
			FDC,
			0
	FROM dbo.Te_Journal_Detail T1
		INNER JOIN #GetManSTypeId T2 ON T1.STypeId = T2.typeid
	WHERE IsInit = 1
	
	
	DECLARE @TypeId	VARCHAR(50), @SFullName  VARCHAR(100),@FPeriod	INT
	DECLARE STypeCur2 CURSOR FOR
	SELECT  TypeId,
			sfullname,
			FYear,
			FPeriod
	FROM #GetManSTypeId
	OPEN STypeCur2
	FETCH NEXT FROM STypeCur2 INTO @TypeId,@SFullName,@FYear,@FPeriod
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC dbo.Gp_CalculateTeBalance @TypeId,@FYear,@FPeriod
		
		FETCH NEXT FROM STypeCur2 INTO @TypeId,@SFullName,@FYear,@FPeriod
	END
	
	CLOSE STypeCur2
	DEALLOCATE STypeCur2


--总账
DELETE FROM Ac_Balance  WHERE FYear < @fyear OR (FYear = @fyear AND FPeriod < @period)
DELETE FROM Ac_Balance_Assist_CheckItems  WHERE FYear < @fyear OR (FYear = @fyear AND FPeriod < @period)
DELETE FROM Ac_Balance_Assist_CheckItems_Detail  WHERE FYear < @fyear OR (FYear = @fyear AND FPeriod < @period)

DELETE FROM Ac_Voucher WHERE BillDate < @yearendDatetime
DELETE FROM Ac_Voucher_Bill WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = dbo.Ac_Voucher_Bill.BillNumberId)
DELETE FROM Ac_Voucher_Bill_Assist_CheckItems WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = dbo.Ac_Voucher_Bill_Assist_CheckItems.BillNumberId)
DELETE FROM Ac_Voucher_Bill_CashMoneyItems WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = dbo.Ac_Voucher_Bill_CashMoneyItems.BillNumberId)

DELETE FROM Ac_GoodsBill_VoucherBill WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = dbo.Ac_GoodsBill_VoucherBill.VourchBillId)
DELETE FROM Ac_ReceiptBill_VoucherBill WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = dbo.Ac_ReceiptBill_VoucherBill.VourchBillId)
DELETE FROM Ac_CommissionBill_VoucherBill WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = dbo.Ac_CommissionBill_VoucherBill.VourchBillId)
DELETE FROM Ac_Provision_Voucher WHERE NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Voucher WHERE BillNumberId = dbo.Ac_Provision_Voucher.VoucherId)

DELETE FROM Ac_ProfitAndLoss WHERE  FYear < @fyear OR (FYear = @fyear AND FPeriod < @period)
DELETE FROM Ac_ProfitAndLoss_Detail WHERE  FYear < @fyear OR (FYear = @fyear AND FPeriod < @period)
TRUNCATE TABLE Ac_Voucher_Bill_Temp

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_Sys_ImportInventoryType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_Sys_ImportInventoryType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE P_Sys_ImportInventoryType
(
	@OperatorId		VARCHAR(50),		-- 当前操作员ID
	@StypeId		VARCHAR(50),
	@SubId			INT
)
--@encode$--
AS
SET NOCOUNT ON
/*
IF EXISTS(SELECT TOP 1 1 FROM dbo.SType WHERE TypeId=@stypeid AND IsSelfVerify <> 1)
BEGIN
	RAISERROR('该分支机构非独立核算，不能设置存货类型！',16,1)
	RETURN -1
END
*/
DECLARE @usercode		VARCHAR(200),
		@fullname		VARCHAR(200),
		@Stockfullname	VARCHAR(200),
		@Incomefullname	VARCHAR(200),	
		@Costfullname	VARCHAR(200),		
		@Stockatypeid	VARCHAR(50),
		@Incomeatypeid	VARCHAR(50),
		@Costatypeid	VARCHAR(50),
		@TID			INT
		

--异常信息
CREATE TABLE #ErrorMsg
(
	msg VARCHAR(MAX)
)

DECLARE @Index INT,@Version INT,@VerifyID VARCHAR(50)
SET @Index = 1

SELECT @Version = SubValue FROM dbo.sysdata WHERE SubName = 'ProInfo'
SELECT	@VerifyID=VerifyID FROM SType WHERE TypeId = @StypeId

CREATE TABLE #TEMP_DETAIL
(
	TID				INT,
	usercode		VARCHAR(200),
	Fullname		VARCHAR(200),	
	comment			VARCHAR(500),	
	STypeID			VARCHAR(50),		--分支机构ID
	StockATypeID	VARCHAR(50),		--存货核算科目
	IncomeATypeID	VARCHAR(50),		--销售收入科目
	CostATypeID		VARCHAR(50),		--销售成本科目
	Stockfullname	VARCHAR(200),		--存货核算科目
	Incomefullname	VARCHAR(200),		--销售收入科目
	Costfullname	VARCHAR(200)		--销售成本科目
)

INSERT INTO #TEMP_DETAIL
(
	TID
	,usercode
	,Fullname
	,comment
	,STypeID
	,Stockfullname
	,StockATypeID
	,Incomefullname
	,IncomeATypeID
	,Costfullname	
	,CostATypeID
)
SELECT	B.NID
		,sp.usercode
		,SP.fullname
		,sp.comment
		,@StypeId
		,SP.Stockfullname
		,ISNULL(s.TypeId,'')
		,SP.Incomefullname
		,ISNULL(i.TypeId,'')
		,SP.Costfullname
		,ISNULL(c.TypeId,'')
FROM	Sys_InventoryTypePerset SP
INNER JOIN	Base_InventoryType B ON B.SysrowId = SP.InventoryType
LEFT JOIN	Ac_Account s ON S.StypeId = @VerifyID AND S.FullName = SP.Stockfullname AND S.SonNum = 0
LEFT JOIN	Ac_Account i ON I.StypeId = @VerifyID AND I.FullName = SP.Incomefullname AND I.SonNum = 0
LEFT JOIN	Ac_Account c ON C.StypeId = @VerifyID AND C.FullName = SP.Costfullname AND C.SonNum = 0
WHERE	SP.subid = @SubId
	--AND	SP.fullname NOT IN(SELECT FullName FROM Base_InventoryType WHERE Sysrow = 0)


IF EXISTS(SELECT TOP 1 1 FROM #TEMP_DETAIL WHERE StockATypeID = '' OR IncomeATypeID = '' OR CostATypeID = '')
BEGIN
	INSERT INTO #ErrorMsg(msg)
	SELECT  '导入存货类型【'+Fullname+'】失败，科目'+ CASE WHEN StockATypeID = '' THEN '【'+Stockfullname+'】' ELSE '' END 
					+ CASE WHEN IncomeATypeID = '' THEN '【'+Incomefullname+'】' ELSE '' END 
					+ CASE WHEN CostATypeID = '' THEN '【'+Costfullname+'】' ELSE '' END 
			+'不是有效的子科目。'
	FROM	#TEMP_DETAIL
	WHERE	StockATypeID = '' OR IncomeATypeID = '' OR CostATypeID = ''
	
	DELETE FROM #TEMP_DETAIL WHERE StockATypeID = '' OR IncomeATypeID = '' OR CostATypeID = ''
END

/*
CREATE TABLE #TEMP_TID
(
	TID		INT,
	fullname	VARCHAR(200)
)

--插入主表,并获取TID,fullname
INSERT INTO Base_InventoryType
	(
		UserCode
		,FullName
		,Comment
		,Sysrow
		,XiWaMaxNumber
	)
OUTPUT INSERTED.NID,INSERTED.FullName INTO #TEMP_TID
SELECT	usercode
		,fullname
		,comment
		,1
		,1
FROM	#TEMP_DETAIL
*/

--删除明细
DELETE FROM Base_InventoryTypeDetails WHERE TID IN(SELECT TID FROM #TEMP_DETAIL) AND STypeID = @StypeId

--插入明细表
INSERT INTO Base_InventoryTypeDetails
	(
		TID
		,STypeID
		,XiWaMaxNumber
		,StockATypeID
		,IncomeATypeID
		,CostATypeID
	)
SELECT	D.TID
		,@StypeId
		,1
		,D.StockATypeID
		,D.IncomeATypeID
		,D.CostATypeID
FROM	#TEMP_DETAIL D

SELECT * FROM #ErrorMsg
DROP TABLE #ErrorMsg,#TEMP_DETAIL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[plug_createmenuitem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[plug_createmenuitem]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	功能说明：	运维平台安装插件时添加插件菜单到配置表
	作    者：	王涛
	修改时间：	2003-09-27
*/

CREATE PROCEDURE plug_createmenuitem
(
		@PlugId int ,
		@Name varchar(50),
		@parentmenuid int  ,
		@NameSpaceAndClass varchar(500) ,
		@NeedLoadAssembly varchar(500) ,
		@ismdi INT ,
		@paramlist VARCHAR(200),
		@replacemenuid VARCHAR(20),
		@menutype INT,
		@webmenuname VARCHAR(2000),
		@menuguid VARCHAR(40),
		@xapname VARCHAR(100)
)		
--@encode$--
AS 
	DECLARE @offset INT 
	IF EXISTS(SELECT 1 FROM dbo.Ord_PopUpPage)
	BEGIN
		SELECT @offset =MAX(offset)+1 FROM Ord_PopUpPage
	END
	ELSE 
	BEGIN
		SELECT @offset=3101
	END 
	INSERT INTO dbo.Ord_PopUpPage(PlugId,NAME,ParentMenuid,NameSpaceAndClass,NeedLoadAssembly,Offset,paramlist,ismdi,replacemenuid,menutype,webmenuname,[menuguid],xapname) 
	VALUES (@PlugId,@NAME,@ParentMenuid,@NameSpaceAndClass,@NeedLoadAssembly,@Offset,@paramlist,@ismdi,@replacemenuid,@menutype,@webmenuname,@menuguid,@xapname)
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[plug_createpluginfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[plug_createpluginfo]
GO
/****** Object:  StoredProcedure [dbo].[CheckCargoCount]    Script Date: 05/25/2012 10:53:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE plug_createpluginfo
(
	@PlugName VARCHAR(200),
	@AppropriateVerSion VARCHAR(4000),
	@IsInstalled INT,
	@plugversion VARCHAR(50),
	@plugfuncdescription VARCHAR(2000),
	@XmlPath VARCHAR(200)
)
--@encode$--	
AS 
	DECLARE @PlugID INT
	IF NOT  EXISTS(SELECT 1 FROM Ord_Plug WHERE PlugName=@PlugName )
	BEGIN
		INSERT INTO Ord_Plug(PlugName,AppropriateVerSion,IsInstalled,XmlPath,
							plugfuncdescription,plugversion) 
		VALUES(@PlugName,@AppropriateVerSion,@IsInstalled,@XmlPath,@plugfuncdescription,@plugversion)
		SET @PlugID=( SELECT SCOPE_IDENTITY() 	)
	END
	ELSE
	BEGIN
		UPDATE ord_plug
		SET plugname=@PlugName,
			AppropriateVerSion=@AppropriateVerSion,
			plugfuncdescription=@plugfuncdescription,
			plugversion=@plugversion,
			IsInstalled=@IsInstalled,
			XmlPath=@XmlPath
		WHERE plugname=@PlugName
		
		SELECT @PlugID=id FROM Ord_Plug WHERE PlugName=@PlugName  
		EXEC Ord_CahcePlugLimit @PlugID
	END
	SELECT @PlugID
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCX_SalePlanIndex]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetCX_SalePlanIndex]
GO

CREATE FUNCTION GetCX_SalePlanIndex (@BillDate datetime,@KtypeID varchar(50),@IsJoin int)
RETURNS @CXSalePlanIndexID TABLE (BillNumberId numeric(9),BillType varchar(1))
--@encode$--
AS
BEGIN
  declare @MonthDays int  --每月第几天
  declare @MonthWeeks int  --每月第几个星期
  declare @MonthWeekDays int --每月第几个星期几..
  declare @WeekDays int --每周哪几天
  declare @isLastDay int  --最否是最后一天
  declare @isLastWeek int  --是否是最后一个星期几
  declare @BillDateNoTime datetime --没有时间的,去掉时分秒
  declare @Time varchar(8) --时间
  set @Time = convert(varchar(8),@BillDate,108)
  set @BillDateNoTime = DATEADD(day,  DATEDIFF(day,0,@BillDate),0)
  declare @TempTable TABLE (VarName varchar(100),VarValue int)  
  insert into @TempTable
  select varname,cast(varvalue as varchar) from dbo.UFAnalyseDate(@BillDate)
  
  select @MonthDays = varvalue from @TempTable where varName = '@MonthDays'
  select @MonthWeeks = varvalue from @TempTable where varName = '@MonthWeeks'
  select @MonthWeekDays = varvalue from @TempTable where varName = '@MonthWeekDays'
  select @WeekDays = varvalue from @TempTable where varName = '@WeekDays'
  select @isLastDay = varvalue from @TempTable where varName = '@isLastDay'
  select @isLastWeek = varvalue from @TempTable where varName = '@isLastWeek'

 
--  exec AnalyseDate @BillDate,@MonthDays output,@MonthWeeks output,@MonthWeekDays output,@WeekDays output,@isLastDay output,@isLastWeek output
  insert into @CXSalePlanIndexID
  select BillNumberID,BillType from CX_SalePlanIndexView a
  where BillStatus = 1 and BreakStatus =0 
 --       and  isnull(JTypeID,'') = case when @IsJoin = 1 then @KtypeID else '' end
        and  StartDate <= @BillDateNoTime and EndDate >= @BillDateNoTime
        and  StartTime <= @Time and EndTime >= @Time
        and ((DateTimeType = 1)
	or  (DateTimeType = 3 and(monthday = cast(@MonthDays as varchar) or monthday = cast(@isLastDay -1 as varchar))) --对应每月第几天。
	or  (DateTimeType = 4 and (MonthWeek = cast(@MonthWeeks as varchar) or MonthWeek = cast(@isLastWeek - 1 as varchar)) and MonthWeekDay =@MonthWeekDays )  --对应每月第几周的周几
	or  (DateTimeType = 2 and (WeekDays & @WeekDays = @WeekDays)))  
        and exists (select 1 from CX_SaleStocksAreaView b where a.BillNumberid = b.BillNumberid and Ktypeid = @Ktypeid )--and isHQ = @isJoin)
  return   
End


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UFAnalyseDate]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[UFAnalyseDate]
GO

CREATE FUNCTION UFAnalyseDate (@BillDate datetime)
RETURNS @AnalyseDateTable TABLE (VarName varchar(100),VarValue varchar(100))
--@encode$--
AS
BEGIN

  declare @MonthDays int  --每月第几天
  declare @MonthWeeks int  --每月第几个星期
  declare @MonthWeekDays int --每月第几个星期几..
  declare @WeekDays int --每周哪几天
  declare @isLastDay int  --最否是最后一天
  declare @isLastWeek int  --是否是最后一个星期几


  declare @CurrFirstDate datetime --当前月的第一天
  declare @CurrLastDate DateTime --当前月的最后一天
  declare @MonthDayCount int --当月总天数
  declare @TempDate datetime --用于计算的临时变量
  declare @TempWeeks int 
  set @CurrFirstDate = dateadd(mm,datediff(mm,0,@BillDate),0)
  set @CurrLastDate =  dateadd(ms,-2,DATEADD(mm, DATEDIFF(m,0,@BillDate)+1, 0)) 
  set @MonthDayCount = day(@CurrLastDate)
-- 无论 @@DateFirst 等于几,无论是什么语言版本的 SQL Server 下面永远恒成立!
-- (@@Datefirst + datepart(weekday,@Date)): 2、3、4、5、6、0、1 分别代表 周一 到 周日      
  select @MonthWeekDays = (@@Datefirst + datepart(weekday,@BillDate)) % 7 - 1
  if @MonthWeekDays = -1 
     set @MonthWeekDays = 6
  if @MonthWeekDays = 0 
     set @MonthWeekDays = 7

 set @MonthDays = day(@BillDate)
 
 if  @MonthDays >= @MonthDayCount
   set @isLastDay = 1
 else
  set @isLastDay = 0
 
 set @TempDate = @BillDate
 set @TempWeeks = 0
 while @TempDate >= @CurrFirstDate
 begin
   set @TempWeeks = @TempWeeks + 1
   select @TempDate = dateadd(wk,-1,@TempDate)
 end 

 set @MonthWeeks = @TempWeeks
 set @TempDate = @BillDate
 if dateadd(wk,1,@TempDate) > @CurrLastDate 
   set @isLastWeek = 1
 else
  set @isLastWeek = 0
  set @WeekDays = power(2,@MonthWeekDays - 1)
  insert @AnalyseDateTable
  select '@MonthDays',@MonthDays union all
  select '@MonthWeeks',@MonthWeeks union all
  select '@MonthWeekDays',@MonthWeekDays union all
  select '@WeekDays',@WeekDays union all
  select '@isLastDay',@isLastDay union all
  select '@isLastWeek',@isLastWeek   
  return
end


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_CheckCanUseVipCardPay]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_CheckCanUseVipCardPay]
GO

--判断是否能用储值卡支付
CREATE PROCEDURE Pos_A8_CheckCanUseVipCardPay
    (
      @BranchId VARCHAR(50) ,
      @ReturnMsg VARCHAR(200) = '' OUTPUT ,--提示信息
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
    )
--@encode$--
AS 
    DECLARE @PosBranchType INT
    SELECT  @PosBranchType = branchtype
    FROM    PosBranchView
    WHERE   BranchID = @BranchId
    IF @PosBranchType = 3 
        BEGIN
            SET @ReturnMsg = '代销机构不能进行储值付款！'
            RETURN -2
        END
    ELSE 
        RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_CheckCommonPosVipDeport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_CheckCommonPosVipDeport]
GO
-- 检查VIP卡适用范围
CREATE procedure [dbo].[Pos_A8_CheckCommonPosVipDeport]
(
 @CardID       varchar(50),     --传入Vip卡的ID
 @DeportID     varchar(50),     --传入Vip卡所属机构的id
 @ConditionStr varchar(8000)='' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)as
   Select 1 
      From PosvipcardboundView  
         where CardTypeID = @CardID and Branchid = @DeportID  
 if @@rowcount = 0 
  return 0


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_CheckVipCardPayRange]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_CheckVipCardPayRange]
GO

CREATE PROCEDURE Pos_A8_CheckVipCardPayRange
    (
      @CardTypeID INT ,	       --卡类型ID	
      @PosId VARCHAR(50) ,     --传入POSID
      @ReturnMsg VARCHAR(200) = '' OUTPUT ,--提示信息
      @ConditionStr VARCHAR(8000) = '' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
    )
    --@encode$--
AS 
      DECLARE @CardBranchID VARCHAR(50)
    DECLARE @PosBranchID VARCHAR(50)
    DECLARE @PosBranchType INT
    DECLARE @IsAllowAdd BIT

    SELECT  @IsAllowAdd = IsCz
    FROM    nVipCardSign
    WHERE   VipCardCode = @ConditionStr
        
    --SELECT  @PosBranchID = Branchid
    --FROM    PosInfoView
    --WHERE   PosID = @PosId

    --SELECT  @PosBranchType = b.branchtype
    --FROM    PosBranchView b
    --        INNER JOIN PosInfoView p ON p.PosID = @PosId
    --                                    AND b.BranchID = p.BranchID

    --IF @PosBranchType = 4
    --    AND @CardBranchID <> @PosBranchID 
    --    BEGIN
    --        SET @ReturnMsg = '卡类型不是由本加盟机构创建，您不能使用该卡进行储值付款！'
    --        RETURN -1	
    --    END
    --ELSE 
    --    IF @PosBranchType = 3 
    --        BEGIN
    --            SET @ReturnMsg = '代销机构不能进行储值付款！'
    --            RETURN -2
    --        END
        --ELSE 
            IF @IsAllowAdd = 0 
                BEGIN
                    SET @ReturnMsg = '该卡不具储值功能！'
                    RETURN -3
                END    
            ELSE
                --SELECT @CardBranchID,@PosBranchID,@PosBranchType,@IsAllowAdd,@ReturnMsg 
                RETURN 0              
       

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_CommonPosCombination]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_CommonPosCombination]
GO

-- 组合促销
CREATE procedure Pos_A8_CommonPosCombination
(
 @Ktypeid varchar(50),--仓库ID
 @Ptypeid varchar(50),--商品Id
 @BillID int,--单据编号
 @Row int,--组合新商品行号
 @DetailRow int,--组合成份商品行号
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000)='' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as 
   select f.BillNumberID,
          f.row,
          f.ptypeid,
          f.qty,
          f.saleprice as relPrice,
	  f.discount*100 as DiscountRate,
	  f.discountprice,
	  f.MemberPrice,           
	  a.FullName,
	  a.UserCode,
	  c.colorname,
	  d.sizename,
	  c.colorid,
	  d.sizeid,
	  isnull(e.stockqty,0) as StockQty 
 
         from CX_CombinationdetailBillView f 
              inner join  PosPtypeView a on f.ptypeid = a.ptypeid 
              left join PosPtypeColorSizeView b on a.ptypeid = b.ptypeid
              left join PosColorView c on b.colorid = c.colorid 
              left join PosSizeView d on b.Sizeid = d.Sizeid 
              left join (select ptypeid,
                                Colorid,
                                Sizeid,
                                sum(qty) as StockQty 
                            from PosGoodsStocksDetailView 
                              where  Ktypeid =@Ktypeid  
                              group by Ptypeid,Colorid,sizeid) e 
                 on b.ptypeid = e.ptypeid and b.colorid = e.colorid and b.sizeid = e.sizeid 
            where f.Ptypeid = @Ptypeid 
                  and  a.deleted = 0 
                  and  a.sonnum = 0 
                  and  f.BillNumberID =  @BillID  
                  and  f.Row = @Row  
                  and  f.detailRow =@DetailRow
             order by f.ptypeid, b.colororderid, b.sizeorderid



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_CommonPosGoodsDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_CommonPosGoodsDetails]
GO

-- 商品明细
Create procedure Pos_A8_CommonPosGoodsDetails
(
 @Price  NUMERIC(24, 10) ,--价格
 @Ktypeid varchar(50),--仓库ID
 @Ptypeid varchar(50),--商品Id
 @Qty int,--数量
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000)='' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as 
   select @Qty as qty,
          a.ptypeid,
          a.FullName,
          a.UserCode,
          @Price  as relPrice, 
          c.colorname,
          d.sizename,
          c.colorid,
          d.sizeid,
          isnull(e.stockqty,0) as StockQty 
      from PosPtypeView a
        left join PosPtypeColorSizeView b on a.ptypeid = b.ptypeid 
        left join PosColorView c on b.colorid = c.colorid
        left join PosSizeView d on b.Sizeid = d.Sizeid
        left join (select ptypeid,Colorid,Sizeid,sum(qty) as StockQty 
                      from PosGoodsStocksDetailView 
                        where  Ktypeid = @Ktypeid  
                        group by Ptypeid,Colorid,sizeid) e
              on b.ptypeid  = e.ptypeid 
                 and b.colorid = e.colorid 
                 and b.sizeid = e.sizeid
         where a.Ptypeid = @Ptypeid  
               and a.deleted = 0 
               and a.sonnum = 0 
         order by a.ptypeid, b.colororderid, b.sizeorderid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_CommonPosGoodsDetailsNoColorSize]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_CommonPosGoodsDetailsNoColorSize]
GO

-- 商品明细
Create procedure Pos_A8_CommonPosGoodsDetailsNoColorSize
(
 @Price  NUMERIC(24, 10) ,--价格
 @Ktypeid varchar(50),--仓库ID
 @Ptypeid varchar(50),--商品Id
 @Qty int,--数量
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000)='' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as 
   select @Qty as qty,
          a.ptypeid,
          a.FullName,
          a.UserCode,
          @Price  as relPrice, 
          '' as colorname,
          '' as sizename,
          0 as colorid,
          0 as sizeid,
          isnull(e.stockqty,0) as StockQty 
      from PosPtypeView a
        left join (select ptypeid,Colorid,Sizeid,sum(qty) as StockQty 
                      from PosGoodsStocksDetailView 
                        where  Ktypeid = @Ktypeid  
                        group by Ptypeid,Colorid,sizeid) e
              on a.ptypeid = e.ptypeid 
         where a.Ptypeid = @Ptypeid  
               and a.deleted = 0 
               and a.sonnum = 0 
         order by a.ptypeid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_CommonPosLargess]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_CommonPosLargess]
GO

-- 赠品促销
CREATE procedure Pos_A8_CommonPosLargess
(
 @Branchid varchar(50),--机构ID
 @Ktypeid varchar(50),--仓库ID
 @Ptypeid varchar(50),--商品Id
 @BillID int,--单据编号
 @LargessTotal  NUMERIC(24, 10) ,--赠品额
 @LargessQty  NUMERIC(24, 10) ,--赠品数量
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000)='' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as 
declare @Pricetypeid varchar(50)
set @Pricetypeid = ''

      Select @Pricetypeid = isnull(PriceTypeid,'0') 
        From PosBtypeDistributeView 
          where Branchid=@Branchid   
      
   if @Pricetypeid = '' or @Pricetypeid = '0' 
    set  @Pricetypeid = 'LSSJ1'

      select @BillID as BillNumberID,
             @LargessTotal as LargessTotal,
             @LargessQty as qty,
             a.ptypeid,
	     a.FullName,
             a.UserCode,
             case when isnull(p.Price,0) = 0  
                  then isnull(q.price,0) 
                  else isnull(p.Price,0) end  
                  as relPrice,
             c.colorname,
             d.sizename,
             c.colorid,
             d.sizeid,
             isnull(e.stockqty,0) as StockQty 
       from PosPtypeView a
            left join PosPtypeColorSizeView b on a.ptypeid = b.ptypeid  
            left join PosColorView c on b.colorid = c.colorid
            left join PosSizeView d on b.Sizeid = d.Sizeid
            left join (select Ptypeid,
                              Price 
                         from PosPtypePriceView 
                            where PriceTypeid =@PriceTypeid ) p 
                              on a.ptypeid = p.ptypeid
            left join (select Ptypeid,
                              Price 
                          from PosPtypePriceView 
                            where PriceTypeid ='LSSJ1') q 
                              on a.ptypeid = q.ptypeid
            left join (select ptypeid,
                              Colorid,
                              Sizeid,sum(qty) as StockQty 
                          from PosGoodsStocksDetailView 
                           where Ktypeid =@Ktypeid  
           group by Ptypeid,Colorid,sizeid) e
              on b.ptypeid  = e.ptypeid 
                 and b.colorid = e.colorid 
                 and b.sizeid = e.sizeid
          where a.Ptypeid =@Ptypeid 
                 and a.deleted = 0 
                 and a.sonnum = 0 
          order by a.ptypeid, b.colororderid, b.sizeorderid    





 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_FZPOSGetVipPrice]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_FZPOSGetVipPrice]
GO

--  ||==========================================================================================  
-- 获取商品价格
CREATE  PROCEDURE Pos_A8_FZPOSGetVipPrice
    (
      @Ptypeid VARCHAR(50) ,  --商品ID
      @Vipid INT ,    --VIP卡ID
      @Vipdiscount  NUMERIC(24, 10)  OUTPUT ,  --参数价格
      @CXPrice  NUMERIC(24, 10)  OUTPUT , --参数价格
      @PosId VARCHAR(50) ,  --当前POSID，用于处理权限范围
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开     
    )
--@encode$--
AS 
    DECLARE @CardTypeID INT
    DECLARE @PriceTypeID VARCHAR(20)
 
    IF EXISTS ( SELECT  *
                FROM    POSVIPCardsVIEW
                WHERE   CardID = @VIpID ) 
        BEGIN
            --取得卡类型、会员价ID或折扣ID
            SELECT  @CardTypeID = b.type ,
                    @PriceTypeID = priceTypeid
            FROM    POSVipCardsView a
                    LEFT JOIN PosVIPCardTypesView b ON a.CardTypeID = b.CardTypeID
            WHERE   a.Cardid = @VipID  
            
            IF @CardTypeID = 0 --会员卡（商品折扣卡不用取会员价)
                SELECT  @Cxprice = price
                FROM    posptypepriceview
                WHERE   ptypeid = @ptypeid
                        AND priceTypeid = @priceTypeid
                                    
            IF @CardTypeID = 1 --折扣卡                     
                SELECT  @VipDiscount = Price
                FROM    posPtypePriceview
                WHERE   Ptypeid = @Ptypeid
                        AND PriceTypeid = @priceTypeid 
        END  
        
    SET @VipDiscount = ISNULL(@VipDiscount, 0)
    IF @VipDiscount = 0 
        SET @VipDiscount = 100
    SET @CXPRice = ISNULL(@CXPRice, 0)
    RETURN 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetBarInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetBarInfo]
GO
-- 获取条码信息
create procedure Pos_A8_GetBarInfo
( 
 @TempStr   varchar(50),     --传入条码ID
 @PosId    varchar(50),     --传入POSID
 @ConditionStr varchar(8000)='' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as

select DisplayBarName,BarTypeid from posbarcodetypeview where BarTypeid = @TempStr

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetBranchInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetBranchInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

Create Procedure Pos_A8_GetBranchInfo
(
 @BranchId varchar(50), --客户筛选ID
 @PosId        varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000) = ''
)
--@encode$--
as
Select * from POSBranchVIEW where BranchId = @BranchId and deleted = 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetBtypeInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetBtypeInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 根据客户ID获取客户信息
Create Procedure Pos_A8_GetBtypeInfo
(
 @BtypeId varchar(50), --客户筛选ID
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
Select * from POSBTYPEVIEW where btypeid = @BtypeId and deleted = 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetCommonPosSaleIndexORFreeInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetCommonPosSaleIndexORFreeInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 读主程序挂单或调单信息
Create procedure Pos_A8_GetCommonPosSaleIndexORFreeInfo
(
 @sTableName varchar(50), --表名字
 @BillID varchar(50), --单据ID
 @aKtypeid varchar(50),--仓库ID
 @PosId varchar(50),--POSID
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
if @sTableName = 'CommonPosSaleList'
begin
select a.Price as discountprice,a.PtypeID ,a.ColorID as ColorID,a.SizeID as Sizeid,b.Fullname ,b.UserCode,b.Unit,a.retailprice as relPrice,
a.discount,a.DiscountRate,a.Qty as Qty,isnull(e.StockQty,0) as StockQty,CXJFXS, sum as FSUM,c.ColorName,s.SizeName,a.discount,IsPresent 
From CommonPosSaleList a 
left join PosPtypeView b on a.PtypeID=b.pTypeid 
left join PosColorView c on a.ColorID=c.ColorID 
left join PosSizeView s  on a.SizeID=s.SizeID 
left join (select ptypeid,Colorid,Sizeid,sum(qty) as StockQty from PosGoodsStocksDetailView where  Ktypeid = @aKtypeid group by Ptypeid,Colorid,sizeid) e
on b.ptypeid = e.ptypeid and c.colorid = e.colorid and s.sizeid = e.sizeid
where a.PosVchcode=@BillID order by a.listid
end

if @sTableName = 'CommonPosSaleListFreeze'
begin
select a.Price as discountprice,a.PtypeID ,a.ColorID as ColorID,a.SizeID as Sizeid,b.Fullname ,b.UserCode,b.Unit,a.retailprice as relPrice,
a.discount,a.DiscountRate,a.Qty as Qty,isnull(e.StockQty,0) as StockQty,CXJFXS, sum as FSUM,c.ColorName,s.SizeName,a.discount,IsPresent 
From CommonPosSaleListFreeze a 
left join PosPtypeView b on a.PtypeID=b.pTypeid 
left join PosColorView c on a.ColorID=c.ColorID 
left join PosSizeView s  on a.SizeID=s.SizeID 
left join (select ptypeid,Colorid,Sizeid,sum(qty) as StockQty from PosGoodsStocksDetailView where  Ktypeid = @aKtypeid group by Ptypeid,Colorid,sizeid) e
 on b.ptypeid = e.ptypeid and c.colorid = e.colorid and s.sizeid = e.sizeid
where a.PosVchcode=@BillID order by a.listid
end


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_GetCommonPosVipInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_GetCommonPosVipInfo]
GO
-- 获取VIP卡信息
CREATE PROCEDURE Pos_A8_GetCommonPosVipInfo
    (
      @SearchFlag INT ,--0代表@CardNo搜索CARDID 主键，1代表搜CARDNO 卡号或根据配置匹配卡号、姓名、电话
      @CardNo VARCHAR(50) ,--@SearchFlag=0代表@CardNo传入CARDID 主键，-@SearchFlag=1代表传入CARDNO 卡号或根据配置匹配卡号、姓名、电话
      @LikeNameTel INT = 0 ,--配置标志
      @PosId VARCHAR(50) ,  --当前POSID，用于处理权限范围
      @ConditionStr VARCHAR(8000) = '' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
    )
--@encode$--
AS 
     IF OBJECT_ID('tempdb..#temp') IS NOT NULL 
        DROP TABLE #temp
    /*SELECT  CardID ,
            CardNo ,
            CardTypeID ,
            CardState ,
            HolderName ,
            NowIntegral ,
            Deposit ,
            ValidDate ,
            HandOutDate ,
            HolderAdress ,
            HolderTel ,
            HolderID ,
            cardPassWord ,
            NowDiscountTotal ,
            cBYZD1
    INTO    #temp
    FROM    PosVipCardsView
    WHERE   1 = 2*/
    
    CREATE TABLE #temp
    (
            CardID VARCHAR(50),
            CardNo VARCHAR(100),
            CardTypeID  VARCHAR(100),
            CardState  int,
            HolderName  VARCHAR(100),
            NowIntegral   NUMERIC(24, 10) ,
            Deposit   NUMERIC(24, 10) ,
            ValidDate  DATETIME,
            HandOutDate  DATETIME,
            HolderAdress  VARCHAR(500),
            HolderTel  VARCHAR(100),
            HolderID  VARCHAR(100),
            cardPassWord  VARCHAR(100),
            NowDiscountTotal   NUMERIC(24, 10) ,
            cBYZD1     VARCHAR(50)
    )
    
    BEGIN
        IF @SearchFlag = 0 
            BEGIN
                INSERT  INTO #temp
                        SELECT  CardID ,
                                CardNo ,
                                CardTypeID ,
                                CardState ,
                                HolderName ,
                                NowIntegral ,
                                Deposit ,
                                ValidDate ,
                                HandOutDate ,
                                HolderAdress ,
                                HolderTel ,
                                HolderID ,
                                cardPassWord ,
                                NowDiscountTotal ,
                                cBYZD1
                        FROM    PosVipCardsView
                        WHERE   
                        --deleted = 0 AND
                                 CardID = @CardNo
            END
        ELSE 
            BEGIN
                IF @LikeNameTel = 0 
                    BEGIN
                        INSERT  INTO #temp
                                SELECT  CardID ,
                                        CardNo ,
                                        CardTypeID ,
                                        CardState ,
                                        HolderName ,
                                        NowIntegral ,
                                        Deposit ,
                                        ValidDate ,
                                        HandOutDate ,
                                        HolderAdress ,
                                        HolderTel ,
                                        HolderID ,
                                        cardPassWord ,
                                        NowDiscountTotal ,
                                        cBYZD1
                                FROM    PosVipCardsView
                                WHERE   
                                --deleted = 0  AND
                                        CardNo = @CardNo
                                ORDER BY cardid
                    END
                ELSE 
                    BEGIN
                        INSERT  INTO #temp
                                SELECT  CardID ,
                                        CardNo ,
                                        CardTypeID ,
                                        CardState ,
                                        HolderName ,
                                        NowIntegral ,
                                        Deposit ,
                                        ValidDate ,
                                        HandOutDate ,
                                        HolderAdress ,
                                        HolderTel ,
                                        HolderID ,
                                        cardPassWord ,
                                        NowDiscountTotal ,
                                        cBYZD1
                                FROM    PosVipCardsView
                                WHERE   
                                --deleted = 0 AND
                                         CardNo = @CardNo
                                        OR HolderName = @CardNo
                                        OR HolderTel = @CardNo
                                ORDER BY cardid 
                    END
            END
            
        IF NOT EXISTS ( SELECT  1
                        FROM    #temp ) 
            BEGIN
                SELECT  *
                FROM    #temp
                WHERE   1 = 2            
                RETURN -7  --查询结果集为空所查询的会员卡不存在 
            END        
            
        DECLARE @CardState INT ,
            @HolderName VARCHAR(100) ,
            @ValidDate VARCHAR(100) ,
            @HandOutDate VARCHAR(100) ,
            @CardTypeID INT
        SELECT TOP 1
                @CardState = CardState ,
                @HolderName = HolderName ,
                @ValidDate=convert( varchar(12),ValidDate,23),
                @HandOutDate = HandOutDate ,
                @CardTypeID = CardTypeID
        FROM    #temp
        IF @CardState = 2
            BEGIN
                SELECT  *
                FROM    #temp
                WHERE   1 = 2
                RETURN -1                                               --判断会员卡是否停用CardState = 0表示会员卡已经停用
            END
        IF @CardState = 3 
            BEGIN
                SELECT  *
                FROM    #temp
                WHERE   1 = 2
                RETURN -2 
            END                                              --判断会员卡是否挂失CardState = 3表示会员卡已经挂失
        IF @CardState = 1 
            BEGIN
                SELECT  *
                FROM    #temp
                WHERE   1 = 2
                RETURN -3 
            END                                           --判断会员卡是否作废CardState = 3表示会员卡已经删除作废
--         IF @HolderName = ''
--             BEGIN
--                 SELECT  *
--                 FROM    #temp
--                 WHERE   1 = 2
--                 RETURN -4 
--             END                                              --HolderName为空表示没有发卡 （由于.NET II程序后台没有制卡阶段，发卡时可以不输入持卡人名称，所以不做此项判断）

	    IF convert( varchar(12),@ValidDate,23) < convert( varchar(12),GETDATE(),23)
            BEGIN
                SELECT  *
                FROM    #temp
                WHERE   1 = 2
                RETURN -5  
            END                                             --会员卡已经过期
        IF @HandOutDate > GETDATE()
            BEGIN
                SELECT  *
                FROM    #temp
                WHERE   1 = 2
                RETURN -6      --会员卡有效期的范围不正确
            END 
        IF NOT EXISTS ( SELECT  IsMoney ,
                                CardTypeID ,
                                LimitTotal
                        FROM    PosVipCardTypesView
                        WHERE   @CardTypeID = CardTypeID ) 
            BEGIN    
                SELECT  *
                FROM    #temp
                WHERE   1 = 2
                RETURN -8    --查询结果集为空所查询的会员卡类型不存在                                      
            END

        SELECT  CardID ,
                CardNo ,
                CardTypeID ,
                CardState ,
                HolderName ,
                NowIntegral ,
                Deposit ,
                ValidDate ,
                HandOutDate ,
                HolderAdress ,
                HolderTel ,
                HolderID ,
                cardPassWord ,
                NowDiscountTotal ,
                cBYZD1
        FROM    #temp
        IF @@rowcount = 0 
            RETURN -7    --查询结果集为空所查询的会员卡不存在 
     DECLARE @ISCZ VARCHAR(10)=''
     IF @SearchFlag = 0 
        BEGIN
            
                    SELECT  @ISCZ=IsCz
                    FROM    nVipCardSign
                    WHERE   
                    --deleted = 0 AND
                    VipCardID = @CardNo
                                     
        END
    ELSE 
    IF(@ISCZ<>''AND @ISCZ='0')
			  RETURN -11    --会员卡不是储值卡
    END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetDefaultOutStockList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetDefaultOutStockList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

create procedure Pos_A8_GetDefaultOutStockList
(
 @BranchId varchar(50),
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000) = ''
)
--@encode$--
as 
select a.ktypeid,usercode,fullname from posstockview a
  where a.deleted = 0 and a.sonnum = 0 and left(ktypeid,5) <> '99999' and branchid = @BranchId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetEmployeeInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetEmployeeInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 获取操作员信息
CREATE Procedure Pos_A8_GetEmployeeInfo
(
 @EtypeId varchar(50),--操作员ID
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
Select * from PosemployeeView where ETypeId = @EtypeId and deleted = 0 AND sonnum = 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetGoodsStock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetGoodsStock]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 查询商品库存
Create procedure Pos_A8_GetGoodsStock
(
 @Ptypeid varchar(50),  --商品ID
 @szMainPubPosID varchar(50), --POSID
 @szMainPubBranchID varchar(50),--机构ID
 @ConditionStr varchar(8000) = '' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
declare @count int
declare @sqlstr varchar(8000)

set @sqlstr = 'select v.ktypeid,[fullname] from PosGoodsStocksDetailView a, PosSTOCKView v where  a.ktypeid = v.ktypeid'
         +'  and ptypeid = ''' + @Ptypeid + ''''
         +' and exists(select 1 from PosGoodsStocksDetailView b where a.orderid = b.orderid and a.ptypeid = b.ptypeid and a.ktypeid = b.ktypeid and'
         +'         a.colorid = b.colorid and a.sizeid = b.sizeid and b.qty<>0)'
         +'          and a.ktypeid <>''99999''' 

select @count=count(1) from posinfoview where posid =  @szMainPubPosID and IsHeadquartersStock = 0

if @count = 0 
begin
	set @sqlstr = @sqlstr + ' and a.ktypeid in (select typeid from stock where branchid = ''' + @szMainPubBranchID + ''')'
end

set @sqlstr = @sqlstr +'	group by v.ktypeid,[fullname]'
         + ' Order   by v.ktypeID';

exec(@sqlstr)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_Getiskeyset]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_Getiskeyset]
GO
-- 获取会员卡号是否支持键盘输入  0是 1否 
create procedure Pos_A8_Getiskeyset
(
 @PosId    varchar(50),     --传入POSID
 @ConditionStr varchar(8000)='' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
select iskeyset from posinfoview where posid = @PosId and iskeyset = 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetPosInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetPosInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 获取POS机信息内容
Create procedure Pos_A8_GetPosInfo
(
 @PosId varchar(50),--POSID
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
if @PosId = ''
begin
  select * from posinfoview where deleted = 0
end
else
  select * from posinfoview where PosId = @PosId and deleted = 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetPosSaleIndexInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetPosSaleIndexInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 获取POS销售单据表头信息
CREATE Procedure Pos_A8_GetPosSaleIndexInfo
(
 @PosVchCode varchar(50), --单据ID
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
Select * from COMMONPOSSALEINDEX where posvchcode = cast(@PosVchCode as int)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetPosUserInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetPosUserInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 获取指定POS操作员信息
Create Procedure Pos_A8_GetPosUserInfo
(
 @EtypeId varchar(50), --操作员ID
 @ConditionStr varchar(8000) = ''  --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
Select * from posuser where EtypeId = @EtypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetPtypeInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetPtypeInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- 根据客户ID获取客户信息
Create Procedure Pos_A8_GetPtypeInfo
(
 @PtypeId varchar(50), --客户筛选ID
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
Select * from POSPtypeView where ptypeid = @PtypeId and deleted = 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetSaveAccountSumInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetSaveAccountSumInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 获取POS信息内容
Create procedure Pos_A8_GetSaveAccountSumInfo
(
 @BillID varchar(50), --单据ID
 @PosId varchar(50),--POSID
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
select * from PosVipMoneyList a left join posvipcardsview b on a.vipid = b.cardid where PosVchCode = @BillID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_GetSGCXGoods]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_GetSGCXGoods]
GO
-- 获取手工促销商品的信息
CREATE PROCEDURE Pos_A8_GetSGCXGoods
    (
      @BillDate DATETIME ,--服务器时间
      @Ktypeid VARCHAR(50) ,--仓库ID
      @isJoin INT ,--是否为加盟店 1是 0否
      @PtypeIDList VARCHAR(8000) , --商品ID串
      @PtypeQtyList VARCHAR(8000) ,--商品QTY串
      @PtypeSumList VARCHAR(8000) ,--商品SUM串
      @SGCXIDList VARCHAR(1000) , --手工促销ID串
      @PosId VARCHAR(50) ,  --当前POSID，用于处理权限范围 
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
    )
    --@encode$--
AS 
    BEGIN

        DECLARE @OldPtypeIDList VARCHAR(8000)
        SET @OldPtypeIDList = @PtypeIDList
	
        DECLARE @SGCXTemp TABLE
            (
              BillNumberId NUMERIC(9)
            )
        DECLARE @ptypeID VARCHAR(50)
        DECLARE @Qty  NUMERIC(24, 10) 
        DECLARE @Total  NUMERIC(24, 10) 
        DECLARE @QtySum  NUMERIC(24, 10) 
        DECLARE @TotalSum  NUMERIC(24, 10) 
	
        INSERT  INTO @SGCXTemp
                SELECT  BillNumberId
                FROM    dbo.GetCX_SalePlanIndex(@BillDate, @Ktypeid, @isJoin)
                WHERE   BillType = 3
                        AND CHARINDEX(',' + CAST(BillNumberID AS VARCHAR)
                                      + ',', ',' + @SGCXIDList) = 0
        IF @@rowcount = 0 
            BEGIN
                SELECT  1
                WHERE   1 = 2  ---返回空结果集
                RETURN 
            END
        IF OBJECT_ID('tempdb..#tmpPtypeList') IS NOT  NULL 
            DROP TABLE #tmpPtypeList  
        CREATE TABLE #tmpPtypeList
            (
              ptypeid VARCHAR(50) ,
              qty  NUMERIC(24, 10)  ,
              Total  NUMERIC(24, 10) 
            )
        WHILE CHARINDEX(',', @PtypeIDList) > 0 
            BEGIN
                SET @PtypeID = SUBSTRING(@PtypeIDList, 1,
                                         CHARINDEX(',', @PtypeIDList) - 1)
                SET @Qty = SUBSTRING(@PtypeQtyList, 1,
                                     CHARINDEX(',', @PtypeQtyList) - 1)
                SET @Total = SUBSTRING(@PtypeSumList, 1,
                                       CHARINDEX(',', @PtypeSumList) - 1)
                SET @PtypeIDList = SUBSTRING(@PtypeIDList,
                                             CHARINDEX(',', @PtypeIDList) + 1,
                                             LEN(@PtypeIDList))
                SET @PtypeQtyList = SUBSTRING(@PtypeQtyList,
                                              CHARINDEX(',', @PtypeQtyList)
                                              + 1, LEN(@PtypeQtyList))
                SET @PtypeSumList = SUBSTRING(@PtypeSumList,
                                              CHARINDEX(',', @PtypeSumList)
                                              + 1, LEN(@PtypeSumList))
                INSERT  INTO #tmpPtypeList
                VALUES  ( @PtypeID, @Qty, @Total ) 
            END  

	
        SELECT  @QtySum = SUM(qty) ,
                @TotalSum = SUM(total)
        FROM    #tmpPtypeList
	--SELECT * FROM @SGCXTemp
	--SELECT * FROM #tmpPtypeList

        IF OBJECT_ID('tempdb..#tmpAssistList') IS NOT  NULL 
            DROP TABLE #tmpAssistList  
        CREATE TABLE #tmpAssistList
            (
              Assistid VARCHAR(10) ,
              AssistValue VARCHAR(100) ,
              qty  NUMERIC(24, 10)  ,
              Total  NUMERIC(24, 10)  ,
              ptypeList VARCHAR(7000)
            )
	
        IF OBJECT_ID('tempdb..#tmpAssistListSum') IS NOT  NULL 
            DROP TABLE #tmpAssistListSum  
        CREATE TABLE #tmpAssistListSum
            (
              Assistid VARCHAR(10) ,
              AssistValueid VARCHAR(10) ,
              AssistValue VARCHAR(100) ,
              qty  NUMERIC(24, 10)  ,
              Total  NUMERIC(24, 10)  ,
              ptypeList VARCHAR(7000)
            )
	
	--商品属性：1:款式；2:面料；3:加工方式；4:品牌；5:季节 默认值为：空(为空时表示对所有商品有效)
        IF OBJECT_ID('tempdb..#tmpAssistType') IS NOT  NULL 
            DROP TABLE #tmpAssistType  
        CREATE TABLE #tmpAssistType
            (
              Assistid VARCHAR(10) ,
              AssistType VARCHAR(100)
            )
        


        INSERT  INTO #tmpAssistType
                SELECT  typeid ,
                        typename
                FROM    posAssisttypeview

	--SELECT * FROM #tmpAssistType
        DECLARE @AssistTypeid INT
        DECLARE @attributeid INT
        DECLARE @AssistValue VARCHAR(100)
        DECLARE @PtypeList1 VARCHAR(8000)
        DECLARE AssistPtypeCursor CURSOR FOR 
        SELECT b.attributeid,c.typeid,c.username ,SUM(qty),SUM(total) FROM #tmpPtypeList a        
        LEFT JOIN posptypeattributeview b ON a.ptypeid = b.ptypeid
        LEFT JOIN posAssistAttributeview c ON b.attributeid = c.attributeid
        GROUP BY  b.attributeid,c.typeid,c.username

        OPEN AssistPtypeCursor
	
        FETCH NEXT FROM AssistPtypeCursor 
	INTO  @attributeid,@AssistTypeid,@AssistValue,@Qty,@Total
	
        WHILE @@FETCH_STATUS = 0 
            BEGIN
                SET @PtypeList1 = ''
                SELECT  @PtypeList1 = @PtypeList1 + A.ptypeid + ','
                FROM    #tmpPtypeList a
                        LEFT JOIN posptypeattributeview b ON a.ptypeid = b.ptypeid
                        LEFT JOIN posAssistAttributeview c ON b.attributeid = c.attributeid
                WHERE   b.attributeid = @attributeid
                        AND c.typeid = @AssistTypeid
                INSERT  INTO #tmpAssistListSum
                VALUES  ( @AssistTypeid, @attributeid, @AssistValue,
                          ISNULL(@Qty, 0), ISNULL(@Total, 0), @PtypeList1 )

 
                FETCH NEXT FROM AssistPtypeCursor 
	  INTO  @attributeid,@AssistTypeid,@AssistValue,@Qty,@Total
            END

        CLOSE AssistPtypeCursor
        DEALLOCATE AssistPtypeCursor

        --处理手工促销单中没有选择商品属性及属性值的情况
        INSERT  INTO #tmpAssistListSum SELECT  '' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
        --处理手工促销单中选择了商品属性但没有选择属性值的情况(属性值ID可能为''，可能为‘0’)
-- 	INSERT  INTO #tmpAssistListSum SELECT  '1' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
-- 	INSERT  INTO #tmpAssistListSum SELECT  '2' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
-- 	INSERT  INTO #tmpAssistListSum SELECT  '3' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
-- 	INSERT  INTO #tmpAssistListSum SELECT  '4' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
-- 	INSERT  INTO #tmpAssistListSum SELECT  '5' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
-- 	INSERT  INTO #tmpAssistListSum SELECT  '6' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
-- 	INSERT  INTO #tmpAssistListSum SELECT  '7' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
-- 	INSERT  INTO #tmpAssistListSum SELECT  '8' ,'' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList	
	INSERT  INTO #tmpAssistListSum SELECT  '1' ,'0' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
	INSERT  INTO #tmpAssistListSum SELECT  '2' ,'0' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
	INSERT  INTO #tmpAssistListSum SELECT  '3' ,'0' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
	INSERT  INTO #tmpAssistListSum SELECT  '4' ,'0' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
	INSERT  INTO #tmpAssistListSum SELECT  '5' ,'0' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
	INSERT  INTO #tmpAssistListSum SELECT  '6' ,'0' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
	INSERT  INTO #tmpAssistListSum SELECT  '7' ,'0' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList
	INSERT  INTO #tmpAssistListSum SELECT  '8' ,'0' ,'' ,@QtySUM ,@TotalSum ,@OldPtypeIDList

	--SELECT * FROM #tmpAssistListSum
	
	--促销类型：1代表件数折；2代表买满折；3代表超额减  默认值为：
	--优惠类型：1代表现金；2代表券  默认值为：1
        SELECT  d.BillName ,
                d.BillCode ,
                d.StartDate ,
                d.EndDate ,
                D.BillNumberID ,
                CASE WHEN ISNULL(ast.assistType, '') = '' THEN '全部'
                     ELSE ast.assistType
                END AS assistType ,
                CASE WHEN ISNULL(a.AssistValue, '') = '' THEN '全部'
                     ELSE a.AssistValue
                END AS AssistValue ,
                a.qty ,
                a.total ,
                a.ptypelist ,
                CASE b.saletype
                  WHEN 1 THEN '件数折'
                  WHEN 2 THEN '买满折'
                  ELSE '超额减'
                END AS saletypeName ,
                b.saletype ,
                CASE b.moneyticket
                  WHEN 1 THEN '现金'
                  ELSE '返券'
                END AS MoneyTicketName ,
                MoneyTicket ,
                b.totalqty ,
                b.totalmoney ,
                CASE WHEN ISNULL(b.discount, '') = '' THEN '100'
                     ELSE CAST(b.discount AS  NUMERIC(24, 10) ) * 100
                END AS discount ,
                b.rebatemoney ,
                CASE moneyadd
                  WHEN 0 THEN '否'
                  ELSE '是'
                END AS moneyadd
        FROM    #tmpAssistListSum a
                INNER JOIN CX_SaleByHand b ON a.assistid = goodspro AND a.AssistValueid = choosepro
                LEFT JOIN #tmpAssistType AsT ON a.assistid = ast.assistid
                LEFT JOIN cx_saleplanindex d ON b.billnumberid = d.billnumberid
        WHERE   ( ( a.qty >= CASE WHEN b.totalqty = '' THEN 0
                                  ELSE CAST(b.totalqty AS  NUMERIC(24, 10) )
                             END
                    AND b.saletype = 1
                  )
                  OR ( a.total >= CASE WHEN b.totalmoney = '' THEN 0
                                       ELSE CAST(b.totalmoney AS  NUMERIC(24, 10) )
                                  END
                       AND b.saletype IN ( 2, 3 )
                     )
                )
                AND EXISTS ( SELECT 1
                             FROM   @SGCXTemp c
                             WHERE  c.billnumberid = b.billnumberid )
        DROP TABLE #tmpPtypeList  
        DROP TABLE #tmpAssistList
        DROP TABLE #tmpAssistListSum 
    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetStockInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetStockInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 获取仓库信息
Create procedure Pos_A8_GetStockInfo
(
 @KtypeId varchar(50),  --提供筛选仓库ID
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000)= ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
 select * from POSSTOCKVIEW where ktypeid = @KtypeId and deleted = 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetTJCXPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetTJCXPrice]
GO
-- 特价促销单取价
CREATE Procedure Pos_A8_GetTJCXPrice 
(@BillDate datetime, --服务器时间
 @Ktypeid varchar(50), --仓库ID
 @Ptypeid varchar(50), --商品ID
 @isJoin int, --是否为加盟店 1是 0否
 @PosId varchar(50),  --当前POSID，用于处理权限范围
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
begin
  Declare @LastCheckDateTime datetime
  Declare @CXBillID int
  declare @TJCXTemp TABLE (BillNumberId numeric(9))
  insert into  @TJCXTemp
  select BillNumberId  from dbo.GetCX_SalePlanIndex(@BillDate,@Ktypeid,@isJoin) where BillType = 1

  select @LastCheckDateTime = max(CHECKEDATETIME) from CX_SpecialOfferBillView a
  left join CX_SalePlanIndexView b on a.BillNumberid = b.BillNumberid
  where a.PTYPEID = @Ptypeid and EXISTS (select 1 from @TJCXTemp c where b.BillNumberid = c.BillNumberid)
  
  select @CXBillID = max(BillNumberid) from CX_SalePlanIndexView b
  where  CHECKEDATETIME = @LastCheckDateTime and  EXISTS (select 1 from @TJCXTemp c where b.BillNumberid = c.BillNumberid)

 select * from CX_SpecialOfferBillView a
 where a.PTYPEID = @Ptypeid and BillNumberid = @CXBillID

end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetVIPCardsInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetVIPCardsInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 获取VIP卡信息
Create Procedure Pos_A8_GetVIPCardsInfo
(
 @cardid varchar(50), --卡号筛选ID
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
Select * from posvipcardsview where cardid = @cardid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetVipCardTypeByCardId]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetVipCardTypeByCardId]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 根据卡ID获取其类型
CREATE Procedure Pos_A8_GetVipCardTypeByCardId
(
 @CardId varchar(50), --卡ID
 @PosId varchar(50),  --当前POSID，用于处理权限范围
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
Select b.type From posvipcardsview a left join POSVIPCardTypesVIEW b on a.CardTypeID=b.CardTypeID where a.Cardid=@CardId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetZHCXGoods]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetZHCXGoods]
GO
-- 获取组合促销单商品信息
CREATE Procedure Pos_A8_GetZHCXGoods 
(@BillDate datetime, --服务器时间
 @Ktypeid varchar(50), --仓库ID
 @isJoin int, --加盟店为1，其余为0
 @SearchMode int, --0模糊查找，1,条码
 @SearStr varchar(80), --条码
 @PosId varchar(50),  --当前POSID，用于处理权限范围
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
begin
  declare @ZHCXTemp TABLE (BillNumberId numeric(9))
  insert into  @ZHCXTemp
  select BillNumberId  from dbo.GetCX_SalePlanIndex(@BillDate,@Ktypeid,@isJoin) where BillType = 4

  if  @SearchMode = 1 
    select * from CX_CombinationBillView a
    left join CX_SalePlanIndexView b on a.BillNumberid = b.BillNumberid
    where a.EntryCode = @SearStr and EXISTS (select 1 from @ZHCXTemp c where b.BillNumberid = c.BillNumberid)
  else
    select a.BillNumberid,Row,UserCode,FullName,EntryCode,a.SalePrice,discount * 100 as discount,DiscountPrice,MemberPrice from CX_CombinationBillView a
    left join CX_SalePlanIndexView b on a.BillNumberid = b.BillNumberid
    where ( UserCode Like '%' +  @SearStr + '%' or fullname Like '%' +  @SearStr + '%') and EXISTS (select 1 from @ZHCXTemp c where b.BillNumberid = c.BillNumberid)


end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetZHCXGoodsDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetZHCXGoodsDetail]
GO
-- 获取组合促销单商品信息明细
CREATE Procedure Pos_A8_GetZHCXGoodsDetail 
(@BillID INT,--单据ID关联主表表头单据ID
 @Row int, --行号
 @PosId varchar(50),  --当前POSID，用于处理权限范围
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
begin
 select b.UserCode,b.FullName,a.ptypeId,b.standard,b.type,b.area,b.unit,a.saleprice as relPrice,a.BillNumberID,a.Row,a.DetailRow,a.qty,a.discountprice,a.memberprice from CX_CombinationDetailBillView a
 inner join  posptypeview b on a.ptypeid = b.ptypeid
 where BillNumberid = @BillID AND Row = @Row

end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetZPCXGoods]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetZPCXGoods]
GO
-- 获取赠品促销单商品信息
CREATE Procedure Pos_A8_GetZPCXGoods 
(@BillDate datetime,--单据日期
 @Ktypeid varchar(50),--仓库ID
 @isJoin int,--是否为加盟店，是1 否0
 @PtypeIDList varchar(8000),--商品ID串
 @PtypeQtyList varchar(8000),--商品Qty串
 @TotalSum  NUMERIC(24, 10) , --总金额
 @PosId varchar(50),  --当前POSID，用于处理权限范围
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
begin

	declare @OldPtypeIDList varchar(8000)
	set @OldPtypeIDList = @PtypeIDList
	
	declare @SGCXTemp TABLE (BillNumberId numeric(9))
	declare @ptypeID varchar(50)
	declare @Qty  NUMERIC(24, 10) 
	declare @Total  NUMERIC(24, 10) 
	declare @QtySum  NUMERIC(24, 10) 
	
	insert into  @SGCXTemp
	select BillNumberId  from dbo.GetCX_SalePlanIndex(@BillDate,@Ktypeid,@isJoin) where BillType = 2
	if @@rowcount = 0 
	begin
           print 'fff'
	  select 1  where 1=2  ---返回空结果集
	  return 
	end
	if object_id( 'tempdb..#tmpPtypeList' ) is not  null   drop table #tmpPtypeList  
	create table  #tmpPtypeList(ptypeid varchar(50),qty  NUMERIC(24, 10) ,Total  NUMERIC(24, 10) )
	while charindex(',',@PtypeIDList) > 0 
	begin
	  set @PtypeID = substring(@PtypeIDList,1,charindex(',',@PtypeIDList) -1)
	  set @Qty = substring(@PtypeQtyList,1,charindex(',',@PtypeQtyList) -1)
	  set @Total = 0

          set @PtypeIDList = substring(@PtypeIDList,charindex(',',@PtypeIDList) + 1,len(@PtypeIDList))
	  set @PtypeQtyList = substring(@PtypeQtyList,charindex(',',@PtypeQtyList) + 1,len(@PtypeQtyList))
	  insert into #tmpPtypeList
	  values(@PtypeID,@Qty,@Total) 
	end  


	if object_id( 'tempdb..#tmpPtypeListSum' ) is not  null   drop table #tmpPtypeListSum  
	create table  #tmpPtypeListSum(ptypeid varchar(50),qty  NUMERIC(24, 10) ,Total  NUMERIC(24, 10) )

        insert into #tmpPtypeListSum
        select ptypeid,sum(qty),sum(total) from #tmpPtypeList group by ptypeid
        union all
        select '',0,@TotalSum

	if object_id( 'tempdb..#tmpBillList' ) is not  null   drop table #tmpBillList  
	create table  #tmpBillList(BillNumberid int,iRow int)

      
        insert into #tmpBillList
        select ls.billnumberid,ls.row from( select distinct a.billnumberid,row,ptypeid,qty,b.saletype,case when  isnull(b.totalmoney,'') =  '' then 0 else cast(totalmoney as  NUMERIC(24, 10) ) end as totalmoney
                          from CX_LargessBill a
                          left join cx_saleplanindex b on a.billnumberid = b.billnumberid) ls
        where (exists (select 1 from #tmpPtypeListSum c where ls.ptypeid = c.ptypeid  and c.qty >= ls.qty and ls.saletype=1)
        or (@TotalSum >=ls.totalmoney  and ls.saletype =0 ))
        AND exists(select 1 from @SGCXTemp te where te.billnumberid = ls.billnumberid)  

        select cs.billname, A.billnumberid,p.usercode,p.fullname, LargessPtypeid,row,LargessRow,sum(LargessAddTotal) as LargessAddTotal,sum(LargessQty) as LargessQty,
         round(sum(LargessAddTotal)/sum(LargessQty)*1.00,2) as LargessPrice
         from  CX_LargessBill a     
        left join cx_saleplanindex cs on a.billnumberid = cs.billnumberid  
        left join posptypeview p on a.LargessPtypeid = p.ptypeid 
        where exists(select 1 from #tmpBillList b where a.Billnumberid = b.billnumberid and a.row = b.irow)
        group by cs.billname,A.billnumberid,row,LargessRow,p.usercode,p.fullname,LargessPtypeid


-- 	select * from @SGCXTemp
-- select * from #tmpPtypeList
-- select * from #tmpPtypeListSum
-- select * from #tmpBillList
	drop table #tmpPtypeList  
	drop table #tmpPtypeListSum
        drop table #tmpBillList  
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_LoadBaseInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_LoadBaseInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 查找销售人员，往来单位，STOCK仓库ID
CREATE PROCEDURE Pos_A8_LoadBaseInfo
    (
      @sType VARCHAR(20) ,--SALESMAN销售人员，BTYPE往来单位，STOCK仓库
      @search VARCHAR(100) ,--模糊查询关键字
      @IdStr VARCHAR(50) ,--查询ID号
      @BranchId VARCHAR(50) ,--机构ID号
      @PosId VARCHAR(50) ,  --当前POSID，用于处理权限范围
      @ConditionStr VARCHAR(8000) = ''
    )
    --@encode$--
AS 
    DECLARE @POSManager VARCHAR(50)
    SELECT  @POSManager = etypeid
    FROM    PosInfoView
    WHERE   PosID = @posid
    
    IF @sType = 'SALESMAN' 
        BEGIN
            SELECT  b.etypeid AS typeid ,
                    usercode ,
                    fullname
            FROM    posemployeeview b
            WHERE   b.deleted = 0
                    AND b.sonnum = 0
                    AND b.branchid = @BranchId
									--CASE LEFT(@BranchId, 5)
                                       --WHEN '00001' THEN '0000100001'
                                       --ELSE @BranchId
                                     --END
                    AND b.etypeid LIKE '%'
                    AND ( b.usercode LIKE '%' + @search + '%'
                          OR b.fullname LIKE '%' + @search + '%'
                        )
                    AND b.etypeid IN (
                    SELECT  typeid
                    FROM    FN_GetPowerRangeEList(@POSManager, '') )
            ORDER BY b.etypeid
        END
    IF @sType = 'BTYPE' 
        BEGIN
            SELECT  a.btypeid AS typeid ,
                    usercode ,
                    fullname
            FROM    posbtypeview a
            WHERE   a.deleted = 0
                    AND a.sonnum = 0
                    --AND ( ( LEFT(@BranchId, 5) = '00004'
                    --        AND LEFT(btypeid, 5) = '00006'
                    --      )
                    --      OR ( LEFT(@BranchId, 5) <> '00004'
                    --           AND LEFT(btypeid, 5) IN ( '00005', '00002' )
                    --         )
                    --    )
                    AND Btypeid LIKE @IdStr + '%'
                    AND ( a.usercode LIKE '%' + @search + '%'
                          OR a.fullname LIKE '%' + @search + '%'
                        )
                    AND a.btypeid IN (
                    SELECT  typeid
                    FROM    FN_GetPowerRangeBList(@POSManager, '00002,00006',
                                                  '2,6') )
            ORDER BY a.btypeid
        END
    IF @sType = 'STOCK' 
        BEGIN
            SELECT  a.ktypeid AS typeid ,
                    usercode ,
                    fullname
            FROM    posstockview a
            WHERE   a.deleted = 0
                    AND a.sonnum = 0
                    AND a.branchid = @BranchId
                    AND ( a.usercode LIKE '%' + @search + '%'
                          OR a.fullname LIKE '%' + @search + '%'                   
                        )     
                    AND a.Ktypeid IN(
					SELECT typeId 
					FROM F_GetManKTypeAll(@POSManager)    
					)        
            ORDER BY a.ktypeid
        END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_PosGetBasicData]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_PosGetBasicData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 根据商品货号或名称查询其信息数据
CREATE PROCEDURE [dbo].[Pos_A8_PosGetBasicData]
    (
      @Barcode VARCHAR(50) ,--商品条码
      @BaseType INT ,--基本信息对应表名
      @WithColAndSiz INT ,--是否有颜色尺码  
      @selectstring VARCHAR(100) ,--搜索串
      @PosUserId VARCHAR(50) ,--POS用户编号
      @PosId VARCHAR(50) , --POSID
      @DefaultBarCode VARCHAR(50) , --默认商品条码
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
    )
    --@encode$--
AS 
    DECLARE @MangerId VARCHAR(50)
    DECLARE @Jtypeid VARCHAR(50)
    DECLARE @Branchid VARCHAR(50)
    
    DECLARE @POSManager VARCHAR(50)
    SELECT  @POSManager = etypeid
    FROM    PosInfoView
    WHERE   PosID = @posid
    
    IF @BaseType = '1' 
        GOTO P
    IF @BaseType = '2' 
        GOTO B
    IF @BaseType = '3' 
        GOTO K
    IF @BaseType = '4' 
        GOTO A
    IF @BaseType = '5' 
        GOTO E
    IF @BaseType = '6' 
        GOTO O
        
    P:
    BEGIN
        IF @WithColAndSiz = 1 
            BEGIN
                IF @selectstring <> '▲'  --模糊查找
                    BEGIN
                        SELECT  [name] ,
                                p.Ptypeid AS Typeid ,
                                fullname ,
                                usercode ,
                                Sonnum ,
                                pcs.Colorid ,
                                pcs.ColorName ,
                                pcs.Sizeid ,
                                pcs.SizeName ,
                                p.stop
                        FROM    PosPtypeView p
                                LEFT JOIN ( SELECT  a.* ,
                                                    b.Colorname ,
                                                    c.SizeName
                                            FROM    PosPtypeColorSizeView a
                                                    LEFT JOIN PosColorView b ON a.colorid = b.colorid
                                                    LEFT JOIN PossizeView c ON a.sizeid = c.sizeid
                                          ) pcs ON p.ptypeid = pcs.ptypeid 
                        WHERE   sonnum = 0
                                AND deleted = 0
                                AND ( p.fullname LIKE '%' + @selectstring
                                      + '%'
                                      OR p.usercode LIKE '%' + @selectstring
                                      + '%'
                                    )
                                AND p.Ptypeid IN (
                                SELECT  typeid
                                FROM    FN_GetPowerRangePList(@POSManager, '') )
                        ORDER BY p.ptypeid ,
                                pcs.colorid ,
                                pcs.sizeid
                        GOTO Success    
                    END
                ELSE 
                    BEGIN
                        DECLARE @BarTypeid INT	
                        DECLARE @BarCodeDefVerLen INT
                        SET @BarTypeid = 0
                        IF @DefaultBarCode = '' 
                            SET @DefaultBarCode = '1' 
                        SELECT  @BarCodeDefVerLen = BarCheckDigit
                        FROM    posbarcodetypeview
                        WHERE   Bartypeid = @DefaultBarCode

                        DECLARE @SQL VARCHAR(8000) 
                        CREATE TABLE #BarCodetmp
                            (
                              ptypeid VARCHAR(50) ,
                              colorid INT ,
                              sizeid INT ,
                              iOrder INT IDENTITY(1, 1)
                            )
                        IF @DefaultBarCode <> '' 
                            BEGIN 
                                SET @SQL = ' insert into #BarCodetmp (ptypeid,colorid,sizeid) select  Ptypeid,isnull(Colorid,0) as Colorid,isnull(SizeID,0) as SizeID  from PosBarCodeView where Bartypeid='
                                    + @DefaultBarCode
                                    + ' and  FullBarCode= '''
                                    + CASE WHEN LEN(@BarCode) > @BarCodeDefVerLen
                                           THEN LEFT(@BarCode,
                                                     LEN(@BarCode)
                                                     - @BarCodeDefVerLen)
                                           ELSE '▲★▲'
                                      END + ''''
                                EXEC(@sql)
                            END
                        SET @SQL = ' insert into #BarCodetmp (ptypeid,colorid,sizeid)'
                            + '  select  Ptypeid,isnull(Colorid,0) as Colorid,isnull(SizeID,0) as SizeID  from PosBarCodeView b,posbarcodetypeview c '
                            + ' where b.Bartypeid = c.BarTypeid and FullBarCode = case when '
                            + CAST(LEN(@BarCode) AS VARCHAR)
                            + '>c.BarCheckDigit then  left(''' + @BarCode
                            + ''',len(''' + @BarCode
                            + ''') - c.BarCheckDigit) else ''▲★▲'' end'
                            + ' and not exists(select 1 from #BarCodetmp c where b.ptypeid = c.ptypeid and b.colorid = c.colorid and b.sizeid = c.sizeid)'
                            + ' order by b.pri' 
                        PRINT @SQL
                        EXEC(@SQL)	

                        SELECT  a.*
                        FROM    ( SELECT    [name] ,
                                            p.Ptypeid AS Typeid ,
                                            fullname ,
                                            usercode ,
                                            Sonnum ,
                                            pcs.Colorid ,
                                            pcs.ColorName ,
                                            pcs.Sizeid ,
                                            pcs.SizeName ,
                                            p.stop
                                  FROM      PosPtypeView p
                                            LEFT JOIN ( SELECT
                                                              a.* ,
                                                              b.Colorname ,
                                                              c.SizeName
                                                        FROM  PosPtypeColorSizeView a
                                                              LEFT JOIN PosColorView b ON a.colorid = b.colorid
                                                              LEFT JOIN PossizeView c ON a.sizeid = c.sizeid
                                                      ) pcs ON p.ptypeid = pcs.ptypeid 
                                  WHERE     sonnum = 0
                                            AND deleted = 0
                                            AND p.Ptypeid IN (
                                            SELECT  typeid
                                            FROM    FN_GetPowerRangePList(@POSManager,
                                                              '') )
                                ) a
                                INNER JOIN #BarCodetmp c ON a.typeid = c.ptypeid
                                                            AND a.colorid = c.colorid
                                                            AND a.sizeid = c.sizeid
                        ORDER BY c.iorder
                        GOTO Success
                    END
            END
        ELSE 
            BEGIN
                SELECT  [name] ,
                        Ptypeid AS Typeid ,
                        fullname ,
                        usercode ,
                        Sonnum ,
                        stop
                FROM    PosPtypeView
                WHERE   ( fullname LIKE '%' + @selectstring + '%'
                          OR usercode LIKE '%' + @selectstring + '%'
                        )
                        AND sonnum = 0
                        AND deleted = 0
                        AND Ptypeid IN (
                        SELECT  Ptypeid 
                        FROM    FN_GetPowerRangePList(@POSManager, '') )
                ORDER BY typeid
                GOTO Success    
            END
    END
    
    B:
    BEGIN
        SELECT  @Jtypeid = Branchid
        FROM    posinfoview
        WHERE   posid = @PosId
        IF LEFT(@jtypeid, 5) = '00004' 
            SELECT  Btypeid AS Typeid ,
                    fullname ,
                    Sonnum ,
                    [name] ,
                    usercode
            FROM    PosBtypeView
            WHERE   sonnum = 0
                    AND deleted = 0
                    AND LEFT(Btypeid, 5) LIKE '00006%'
                    AND ( fullname LIKE '%' + @SelectString + '%'
                          OR usercode LIKE '%' + @SelectString + '%'
                        )
                    AND btypeid IN (
                    SELECT  btypeid
                    FROM    FN_GetPowerRangeBList(@POSManager, '00006', '6') )
        ELSE 
            SELECT  Btypeid AS Typeid ,
                    fullname ,
                    Sonnum ,
                    [name] ,
                    usercode
            FROM    PosBtypeView
            WHERE   sonnum = 0
                    AND deleted = 0
                    AND LEFT(Btypeid, 5) LIKE '00002%'
                    AND ( fullname LIKE '%' + @SelectString + '%'
                          OR usercode LIKE '%' + @SelectString + '%'
                        )
                    AND btypeid IN (
                    SELECT  btypeid
                    FROM    FN_GetPowerRangeBList(@POSManager, '00002', '2') )
            ORDER BY typeid
        GOTO Success
    END
    
    K:
    SELECT  @Branchid = Branchid
    FROM    PosInfoView
    WHERE   Posid = @Posid
    SELECT  Ktypeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode
    FROM    PosStockView
    WHERE   ( fullname LIKE '%' + @SelectString + '%'
              OR usercode LIKE '%' + @SelectString + '%'
            )
            AND sonnum = 0
            AND deleted = 0
            AND Branchid = @Branchid
    GOTO Success

    A:
    SELECT  Atypeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode
    FROM    PosAtypeView
    WHERE   ( ( fullname LIKE '%' + @SelectString + '%'
                OR usercode LIKE '%' + @SelectString + '%'
              )
              AND sonnum = 0
              AND deleted = 0
            )
    GOTO Success
    
    E:  
    IF @PosUserId = '' 
        SELECT  @Branchid = Branchid
        FROM    PosInfoView
        WHERE   Posid = @Posid
    ELSE 
        SET @Branchid = @PosUserId
    IF LEFT(@Branchid, 5) = '00001' 
        SET @Branchid = '0000100001'		
    SELECT  Etypeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode ,
            Branchid
    FROM    PosEmployeeView
    WHERE   ( fullname LIKE '%' + @SelectString + '%'
              OR usercode LIKE '%' + @SelectString + '%'
            )
            AND sonnum = 0
            AND Etypeid <> '00000'
            AND deleted = 0
            AND Branchid = LEFT(@Branchid, LEN(Branchid))
            AND etypeid IN ( SELECT etypeid
                             FROM   FN_GetPowerRangeEList(@POSManager, '') )
    GOTO Success
    
    O:
    SELECT  a.PosId AS Typeid ,
            a.fullname ,
            a.Usercode ,
            a.fullname AS [name] ,
            0 AS sonnum ,
            a.etypeid ,
            CASE LEFT(a.Branchid, 5)
              WHEN '00001' THEN '0000100001'
              ELSE a.Branchid
            END AS branchid
    FROM    PosInfoView a
    WHERE   a.Deleted <> 1
            AND ( a.fullname LIKE '%' + @SelectString + '%'
                  OR a.usercode LIKE '%' + @SelectString + '%'
                )        

    Success:
    RETURN 0
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_PosGetGoodsStockDst]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_PosGetGoodsStockDst]
GO

-- 查询库存中的商品信息数据
create procedure Pos_A8_PosGetGoodsStockDst  
(  
@selectString varchar(8000),  --搜索串
@SearchMode int,  --0是库存分布，1是指定仓库的库存
@Ktypeid varchar(50),--仓库ID
@Jtypeid varchar(50),--加盟商ID
@edtMode int,--1是精确查找，2是模糊查找
@Custom1 varchar(50),--POSID 
@PosId varchar(50),  --当前POSID，用于处理权限范围		
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)  
--@encode$--
as  

DECLARE @OperatorID 	varchar(100) --操作员ID号
DECLARE @PriceType		int=0	--价格方式
DECLARE @stypeid		VARCHAR(8000)=''			--分支机构
DECLARE @szKtypeId  	varchar(8000)=''    --仓库id号
DECLARE @PTypeId 		varchar(100)=''
DECLARE @Flag 			int=1
DECLARE @Index 			int=1
DECLARE @Sort 			char(4)='ASC'
DECLARE @srcKTypeId		varchar(MAX)=''

--处理传入参数
Declare @TableCount INT
SELECT @TableCount=COUNT(*) FROM f_splitAN(@ConditionStr,',')
--IF(@TableCount>0)
--	SELECT @OperatorID=a FROM f_splitAN(@ConditionStr,',') WHERE ID=1
IF(@TableCount>1)
	SELECT @stypeid=a FROM f_splitAN(@ConditionStr,',') WHERE ID=2
IF(@TableCount>2)
	SELECT @PTypeId=a FROM f_splitAN(@ConditionStr,',') WHERE ID=3
--print(@PTypeId)

SELECT @OperatorID=ETypeId1 FROM CommonPosInfo WHERE PosID=@PosId  --设置权限ID为POS登记的时候的管理员ID
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0
BEGIN
	select 1 as nospqx
	RETURN @Re
END
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品树型表
SELECT * INTO #PTypeIdAll FROM F_GetManPTypeAll(@OperatorID)

--商品线性表
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
		

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) 
SELECT mk.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) mk
			INNER JOIN #GetSelectSTypeId s ON mk.STypeId=s.TypeId

--选择状况表仓库
CREATE TABLE #GetSelectKTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectKTypeId(TypeId) 
SELECT A.Typeid FROM F_GetAllBaseTypeId(@szKtypeId,4) AS A  INNER JOIN (SELECT Typeid FROM #GetManKTypeId) K	ON A.TypeId=K.TypeId
				 
DECLARE @PTypeIdMx 	varchar(100),@SonNum		int
DECLARE @ReSql varchar(8000)
DECLARE @TableName varchar(16)
DECLARE @Condition varchar(8000)			--谢吉康    2003-9-25  加大了变量的长度
DECLARE @i int,@j int
DECLARE @SQL VARCHAR(8000)
IF @SearchMode = 1   --库存状况
BEGIN
		--*********************************************************当前库存状况数据开始************************************************--
				--大数据量下首次要超时，重写算法
				CREATE TABLE #xjkang(
					PTypeId		varchar(100),
					Qty			 NUMERIC(24, 10) ,
					Total		 NUMERIC(24, 10) ,
					LendQty		 NUMERIC(24, 10) ,
					Borrowqty	 NUMERIC(24, 10) ,
					WnQty		 NUMERIC(24, 10) ,
					SnQty		 NUMERIC(24, 10) ,
					Ktypeid		varchar(100)	
				)
				INSERT INTO #xjkang
					SELECT		B.PTypeId,
								SUM(B.Qty) AS Qty,
								SUM(B.Total) AS Total,
								SUM(B.LendQty) AS LendQty,
								SUM(B.BorrowQty) AS BorrowQty,
								SUM(B.WnQty) AS WnQty,
								SUM(B.SnQty) AS SnQty,
								B.KtypeId 
					FROM	(
								SELECT	G.PTypeId,
										G.Qty,
										G.Total,
										0 AS LendQty,
										0 AS BorrowQty,
										0 AS WnQty,
										0 AS SnQty,
										G.Ktypeid
								FROM	GoodsStocks G
								INNER JOIN #GetManPTypeId P ON P.TypeId = G.PtypeId
								INNER JOIN #GetSelectKTypeId SK ON SK.TypeId = G.KtypeId
								INNER JOIN #GetManKTypeId MK ON MK.TypeId = G.KtypeId							
					)B GROUP BY B.PTypeId,B.KtypeId 
				--正式处理查询数据
				SET @SQL = '
					SELECT 	A.typeid,
							B.Ktypeid,
							A.fullname,
							A.usercode,
							ISNULL(A.EntryCode,'''') AS EntryCode,
							ISNULL(A.Standard,'''') AS Standard,
							ISNULL(A.Type,'''') AS Type,
							ISNULL(A.Area,'''') AS Area,
							A.sonnum,
							A.leveal,
							A.parid,
							ISNULL(A.unit1,'''') AS unit1,
							ISNULL(A.unit2,'''') AS unit2,
							A.unitrate1,
							ISNULL(SUM(b.qty),0) AS qty,
							CASE
								WHEN '+CAST(@PriceType AS varchar(10))+'=0  THEN CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
								WHEN '+CAST(@PriceType AS varchar(10))+'=1  THEN Pr.PreSalePrice1
								WHEN '+CAST(@PriceType AS varchar(10))+'=2  THEN Pr.PreSalePrice2
								WHEN '+CAST(@PriceType AS varchar(10))+'=3  THEN Pr.PreSalePrice3
								WHEN '+CAST(@PriceType AS varchar(10))+'=4  THEN Pr.PreSalePrice4
								WHEN '+CAST(@PriceType AS varchar(10))+'=5  THEN Pr.PreSalePrice5
								WHEN '+CAST(@PriceType AS varchar(10))+'=6  THEN Pr.PreSalePrice6
								WHEN '+CAST(@PriceType AS varchar(10))+'=7  THEN Pr.PreSalePrice7
								WHEN '+CAST(@PriceType AS varchar(10))+'=8  THEN Pr.PreSalePrice8
								WHEN '+CAST(@PriceType AS varchar(10))+'=9  THEN Pr.PreSalePrice9
								WHEN '+CAST(@PriceType AS varchar(10))+'=10 THEN Pr.PreSalePrice10
								WHEN '+CAST(@PriceType AS varchar(10))+'=11 THEN Pr.PreBuyPrice1
								WHEN '+CAST(@PriceType AS varchar(10))+'=12 THEN Pr.PreBuyPrice2
								WHEN '+CAST(@PriceType AS varchar(10))+'=13 THEN Pr.PreBuyPrice3
								WHEN '+CAST(@PriceType AS varchar(10))+'=14 THEN Pr.PreBuyPrice4
								WHEN '+CAST(@PriceType AS varchar(10))+'=15 THEN Pr.PreBuyPrice5
								WHEN '+CAST(@PriceType AS varchar(10))+'=16 THEN Pr.RetailPrice
								WHEN '+CAST(@PriceType AS varchar(10))+'=17 THEN Pr.TopSalePrice
								WHEN '+CAST(@PriceType AS varchar(10))+'=18 THEN Pr.LowSalePrice
								ELSE CAST(ISNULL(SUM(b.total)/CASE WHEN SUM(b.qty)=0 THEN NULL ELSE SUM(b.qty) END ,0) AS  NUMERIC(24, 10) ) 
							END AS price,
							CASE 
								WHEN '+CAST(@PriceType AS varchar(10))+'=0  THEN ISNULL(SUM(b.total),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=1  THEN ISNULL(Pr.PreSalePrice1,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=2  THEN ISNULL(Pr.PreSalePrice2,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=3  THEN ISNULL(Pr.PreSalePrice3,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=4  THEN ISNULL(Pr.PreSalePrice4,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=5  THEN ISNULL(Pr.PreSalePrice5,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=6  THEN ISNULL(Pr.PreSalePrice6,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=7  THEN ISNULL(Pr.PreSalePrice7,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=8  THEN ISNULL(Pr.PreSalePrice8,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=9  THEN ISNULL(Pr.PreSalePrice9,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=10 THEN ISNULL(Pr.PreSalePrice10,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=11 THEN ISNULL(Pr.PreBuyPrice1,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=12 THEN ISNULL(Pr.PreBuyPrice2,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=13 THEN ISNULL(Pr.PreBuyPrice3,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=14 THEN ISNULL(Pr.PreBuyPrice4,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=15 THEN ISNULL(Pr.PreBuyPrice5,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=16 THEN ISNULL(Pr.RetailPrice,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=17 THEN ISNULL(Pr.TopSalePrice,0)*ISNULL(SUM(b.Qty),0)
								WHEN '+CAST(@PriceType AS varchar(10))+'=18 THEN ISNULL(Pr.LowSalePrice,0)*ISNULL(SUM(b.Qty),0)
								ELSE ISNULL(SUM(b.total),0)
							END AS total '
		
						SET @SQL=@SQL+',
								0 AS LendQty,
								0 AS BorrowQty,
								0 AS WnQty,
								0 AS SnQty,
								0 AS sjczqty,
								0 AS sjyyqty '
		
						SET @SQL = @SQL + '
						FROM	#PTypeIdAll A
						INNER JOIN PType_Price Pr ON Pr.PTypeId = A.TypeId
						LEFT JOIN (
							SELECT	PTypeId,
									ISNULL(Qty,0) AS Qty,
									ISNULL(Total,0) AS Total,
									ISNULL(LendQty,0) AS LendQty,
									ISNULL(BorrowQty,0) AS BorrowQty,
									ISNULL(WnQty,0) AS WnQty,
									ISNULL(SnQty,0) AS SnQty,
									Ktypeid
							FROM	#xjkang
						)B ON LEFT(B.PTypeId,LEN(A.TypeId)) = A.TypeId
						WHERE	A.TypeId <> ''00000'' and A.sonnum=0'
					IF(@PTypeId<>'')
						SET @SQL=@SQL+ ' AND A.TypeId='''+@PTypeId+''''
					IF(@edtMode =1)
					BEGIN
						IF(@selectString<>'')
							SET   @SQL = @SQL + ' AND (A.UserCode='''+@selectString+''' OR A.FullName='''+@selectString+''')'  
					end
					IF(@edtMode =2)
					BEGIN
						IF(@selectString<>'')
							SET   @SQL = @SQL + ' AND (A.UserCode like ''%'+@selectString+'%'' OR A.FullName like ''%'+@selectString+'%'')'  
				    END
		            IF(@Ktypeid<>'')
						SET   @SQL = @SQL + ' AND  Ktypeid='''+@Ktypeid+'''' 
						 
					SET	@SQL = @SQL + '
					GROUP BY
							A.typeid,
							B.Ktypeid,
							A.fullname,
							A.usercode,
							A.EntryCode,
							A.Standard,
							A.Type,
							A.Area,
							A.sonnum,
							A.leveal,
							A.parid,
							A.unit1,
							A.unit2,
							A.unitrate1,
							Pr.PreSalePrice1,
							Pr.PreSalePrice2,
							Pr.PreSalePrice3,
							Pr.PreSalePrice4,
							Pr.PreSalePrice5,
							Pr.PreSalePrice6,
							Pr.PreSalePrice7,
							Pr.PreSalePrice8,
							Pr.PreSalePrice9,
							Pr.PreSalePrice10,
							Pr.PreBuyPrice1,
							Pr.PreBuyPrice2,
							Pr.PreBuyPrice3,
							Pr.PreBuyPrice4,
							Pr.PreBuyPrice5,
							Pr.RetailPrice,
							Pr.TopSalePrice,
							Pr.LowSalePrice
					ORDER BY A.UserCode '
		
					--PRINT(@SQL)
					EXEC(@SQL)
					--删除临时表
					DROP TABLE #xjkang
END
IF @SearchMode = 0  --库存分布  
BEGIN
--*********************************************************当前库存分布数据开始************************************************--
------------------------------------------计算出应查询的仓库-----------------------------------------------

CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)

DECLARE @SortStockCount int
DECLARE @SortStockAddRec int
DECLARE @TempKTypeID varchar(100)
DECLARE @TempKName varchar(MAX)
SELECT @SortStockCount=1
SELECT @SortStockAddRec=0

--处理仓库
DECLARE @KTypeIds 		varchar(MAX),
		@Where_KTypeId	varchar(MAX),
		@x 				int,
		@Xjkang			varchar(MAX)

/*
SET @Where_KTypeId = ''

SET @srcKTypeId = RTRIM(LTRIM(@srcKTypeId))
SET @x = charindex(',',@srcKTypeId)

WHILE @x>=1
	BEGIN
		SET @KTypeIds = LEFT(@srcKTypeId,@x-1)

		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (TypeId LIKE '+char(39)+@KTypeIds+'%'+char(39)
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR TypeId LIKE '+char(39)+@KTypeIds+'%'+char(39)

		SET @srcKTypeId=SUBSTRING(@srcKTypeId,@x+1,LEN(@srcKTypeId)-@x)
		SET @x=charindex(',',@srcKTypeId)
	END

IF @srcKTypeId<>''
	BEGIN
		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (TypeId LIKE '+char(39)+@srcKTypeId+'%'+char(39)+')'
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR TypeId LIKE '+char(39)+@srcKTypeId+'%'+char(39)+')'
	END


SET @Xjkang = 'INSERT INTO #TempStock1 SELECT TypeId,UserCode,FullName FROM Stock WHERE SonNum = 0 AND TypeID IN (SELECT * FROM #GetManKTypeId) '+@Where_KTypeId+' ORDER BY UserCode '
EXEC(@Xjkang)

SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TypeID,				
				UserCode,			
				FullName
	    FROM    #TempStock1 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '

EXEC(@xjkang)
*/
SET @Xjkang = 'INSERT INTO #TempStock1 SELECT TypeId,UserCode,FullName FROM Stock WHERE SonNum = 0 AND TypeID IN (SELECT * FROM #GetManKTypeId) ORDER BY UserCode '
EXEC(@Xjkang)
--EXEC('SELECT * FROM  #TempStock')
--RETURN
--EXEC('SELECT * FROM '+N'##'+@TableName) 
--RETURN
------------------------------------------上段程序结束-----------------------------------------------




--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@Sql='CREATE TABLE '+N'##'+@TableName+'
	(
		[typeId] 		[varchar] (100) NOT NULL,
		[parid] 		[varchar] (100) NOT NULL,
		[父节点] 		varchar(100) NOT NULL,
		[商品编号] 		[varchar] (200) NULL ,
		[商品名称] 		[varchar] (256) NOT NULL ,
		单位关系		varchar(256) NULL,
		商品条码		varchar(256) NULL,
		商品规格		varchar(256) NULL,
		商品型号		varchar(256) NULL,
		商品产地		varchar(256) NULL,
		单位			varchar(100) NULL,
		大单位			varchar(100) NULL,
		关系			varchar(100) NULL,
		[总计账面库存] 	 NUMERIC(24, 10) ,
		[总计成本均价] 	 NUMERIC(24, 10) ,
		[总计成本金额] 	 NUMERIC(24, 10) 
	)'

EXEC(@sql)

IF @@error<>0
	BEGIN
 		--RAISERROR('创建临时表发生错误！',16,1)
 		RETURN
	END
--=======================================================================谢吉康  2003-12-1 重写PType的数据
	DECLARE @TypeIDTmp		varchar(MAX),
			@SonNumTmp		varchar(100),
			@paridTmp		VARCHAR(100),
			@UserCodeTmp	varchar(MAX),
			@FullNameTmp	varchar(MAX),
			@SQLCursor 		varchar(MAX),
			@SQLTemp 		varchar(MAX),
			@CloseCursor  	varchar(MAX),
			@CruSonNum		int,
			@EntryCode		varchar(MAX),
			@Standard		varchar(MAX),
			@Type			varchar(MAX),
			@Area			varchar(MAX),
			@Unit1			varchar(MAX),
			@Unit2			varchar(MAX),
			@UnitRate1		 NUMERIC(24, 10) 

SELECT * INTO #PType FROM F_GetManPTypeAll(@OperatorID)


CREATE TABLE #GsStock
(
	PTypeId	VARCHAR(100),
	Qty	 NUMERIC(24, 10) ,
	price  NUMERIC(24, 10) ,
	total  NUMERIC(24, 10) ,
	KTypeID	VARCHAR(100)	
)

DECLARE @GsSql VARCHAR(1000)
SET @GsSql='
	INSERT INTO #GsStock
	SELECT	G.PTypeId,
			ISNULL(SUM(G.Qty),0) AS Qty,
			ISNULL(SUM(G.price),0) as price,
			ISNULL(SUM(G.total),0) as total,
			G.KTypeID
	FROM	GoodsStocks G
			INNER JOIN #GetManPTypeId p ON G.PTypeId=p.typeid
			INNER JOIN	#GetManKTypeId k  ON  k.typeid=G.KTypeId'			
	SET @GsSql = @GsSql + '	GROUP BY	G.PTypeId,G.KTypeID'
EXEC(@GsSql)

SELECT @SQLTemp='INSERT '+N'##'+@TableName+'
				(
					[typeid],
					[parid],
					[父节点],
					[商品编号],
					[商品名称],
					单位关系,
					商品条码,
					商品规格,
					商品型号,
					商品产地,
					单位,
					大单位,
					关系
				)
				
				SELECT typeid,
				       parid,
				       sonnum,
				       usercode,
				       fullname,
				       unit2,
				       entrycode,
				       standard,
				       type,
				       area,
				       unit1,
				       unit2,
				       unitrate1			
				FROM   PTYPE
				WHERE  SonNum = 0'
--print(@PTypeId)
IF(@PTypeId<>'')
	SET @SQLTemp=@SQLTemp+ ' AND TypeId='''+@PTypeId+''''

IF(@edtMode =1)
BEGIN
	IF(@selectString<>'')
		SET   @SQLTemp = @SQLTemp + ' AND (UserCode='''+@selectString+''' OR FullName='''+@selectString+''')'  
end
IF(@edtMode =2)
BEGIN
	IF(@selectString<>'')
		SET   @SQLTemp = @SQLTemp + ' AND (UserCode like ''%'+@selectString+'%'' OR FullName like ''%'+@selectString+'%'')'  
END		
--PRINT(@SQLTemp)
EXEC(@SQLTemp)	
--EXEC('SELECT * FROM '+N'##'+@TableName) 
--RETURN
	
				
SET @Sql = '
	UPDATE '+N'##'+@TableName+'
	SET	[总计账面库存]=B.Qty,
		[总计成本均价]=(CASE ISNULL(B.total,0) WHEN 0 THEN 0 ELSE ISNULL(B.total,0) / ISNULL(B.Qty,0) END),
		[总计成本金额]=B.total
	FROM '+N'##'+@TableName+' A
	INNER JOIN (
				SELECT	X.TypeId,
						ISNULL(SUM(X.Qty),0) AS Qty,
						ISNULL(SUM(X.price),0) AS price,
						ISNULL(SUM(X.total),0) AS total
				FROM (
						SELECT	A.TypeId,
								ISNULL(G.Qty,0) AS Qty,
								ISNULL(G.price,0) AS price,
								ISNULL(G.total,0) AS total
						FROM 	'+N'##'+@TableName+' A
						LEFT JOIN (
									SELECT	G.PTypeId,
											ISNULL(SUM(G.Qty),0) AS Qty,
											ISNULL(SUM(G.price),0) AS price,
											ISNULL(SUM(G.total),0) AS total
									FROM	#GsStock G
											INNER JOIN	#TempStock1 T
											ON	G.KTypeId = T.TypeId
									GROUP BY	G.PTypeId		
								)G 
						ON LEFT(G.PTypeId,LEN(A.TypeId))=A.TypeId 
					)X
				GROUP BY X.TypeId
	)B ON A.TypeId = B.TypeId'

--PRINT(@Sql)
EXEC(@Sql)

		

IF @@error<>0
	BEGIN
		--RAISERROR('更新商品总数量生错误！',16,1)
		RETURN
	END

SELECT @ReSql='SELECT [typeId],[parid],[父节点],[商品编号],[商品名称],单位关系,商品条码,商品规格,商品型号,商品产地,单位,大单位,关系,[总计账面库存],[总计成本均价],[总计成本金额]'
DECLARE @StockName varchar(MAX)


DECLARE Stock CURSOR FOR 
   SELECT TypeID,FullName FROM  #TempStock1 ORDER BY UserCode FOR READ ONLY
	
OPEN Stock
FETCH NEXT FROM Stock INTO @kTypeId,@StockName
IF @@FETCH_status<>0
	BEGIN
	   CLOSE Stock
	   DEALLOCATE Stock
	   --RAISERROR('没有可用的仓库或仓库没有商品或没有商品！',16,1)
	   SELECT * FROM #TempStock1 --当仓库没有值的时候，返回空#TempStock1
	   RETURN 
	END 

SELECT @Sql=''
WHILE @@FETCH_status=0
	BEGIN
		--检查列名是否存在
		SELECT @i=0
		SELECT @j=0
		SELECT @i=CharIndex('['+ @StockName + '账面库存]',@ReSql,@i)
		WHILE @i>0
			BEGIN

				SELECT @i=CharIndex('['+ @StockName + '账面库存]',@ReSql,@i+len('['+ @StockName + '账面库存]'))
				SELECT @j=@j+1  
 			END
		IF @j>0
			SELECT @StockName=@StockName+CONVERT(varchar(4),@j)
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @StockName + '账面库存]  NUMERIC(24, 10) '
 			EXEC(@sql)
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @StockName + '辅助数量] varchar(100)'
 			EXEC(@sql)
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @StockName + '成本均价]  NUMERIC(24, 10) '
 			EXEC(@sql)
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @StockName + '成本金额]  NUMERIC(24, 10) '
 			EXEC(@sql)
 		
		IF @@error<>0
			BEGIN
				CLOSE Stock
				DEALLOCATE Stock
				--RAISERROR('更改临时表发生错误！',16,1)
				RETURN
			END
		
		SET @Sql = '
			UPDATE '+N'##'+@TableName+'
			SET	['+@StockName+'账面库存]=B.Qty,
				['+@StockName+'辅助数量]=CASE
											WHEN A.单位关系='''' THEN ''''
											WHEN B.Qty=0 THEN ''0''+A.单位+''/''+''0''+A.大单位
											WHEN B.Qty<0 AND CAST(ABS(B.Qty)/A.关系 as  NUMERIC(24, 10) )<1	THEN CAST(CAST(B.Qty AS  NUMERIC(24, 10) ) AS varchar(100))+A.单位+''/''+CAST(CAST(CAST(B.Qty AS  NUMERIC(24, 10) )/CAST(ISNULL(A.关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+A.大单位
											WHEN B.Qty<0 AND CAST(ABS(ISNULL(B.Qty,0))/CAST(ISNULL(A.关系,0) AS  NUMERIC(24, 10) ) as  NUMERIC(24, 10) )>=1 AND CAST(CAST(B.Qty as  NUMERIC(24, 10) )-CAST(CAST(A.关系 as  NUMERIC(24, 10) )*CAST(ROUND(B.Qty/A.关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))<>''0'' THEN CAST(CAST(ROUND(B.Qty/A.关系,0,1) AS NUMERIC(18,0)) as varchar)+A.大单位+CAST(CAST(B.Qty as  NUMERIC(24, 10) )-CAST(CAST(A.关系 as  NUMERIC(24, 10) )*CAST(ROUND(B.Qty/A.关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))+A.单位+''/''+CAST(CAST(CAST(B.Qty AS  NUMERIC(24, 10) )/CAST(ISNULL(A.关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+A.大单位
											WHEN B.Qty<0 AND CAST(ABS(ISNULL(B.Qty,0))/CAST(ISNULL(A.关系,0) AS  NUMERIC(24, 10) ) as  NUMERIC(24, 10) )>=1 AND CAST(CAST(B.Qty as  NUMERIC(24, 10) )-CAST(CAST(A.关系 as  NUMERIC(24, 10) )*CAST(ROUND(B.Qty/A.关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))=''0''  THEN CAST(CAST(ROUND(B.Qty/A.关系,0,1) AS NUMERIC(18,0)) as varchar)+A.大单位+''/''+CAST(CAST(CAST(B.Qty AS  NUMERIC(24, 10) )/CAST(ISNULL(A.关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+A.大单位
											WHEN ISNULL(B.Qty,0)>0 AND B.Qty<A.关系 THEN CAST(B.Qty AS varchar(100))+A.单位+''/''+CAST(CAST(B.Qty/A.关系 as  NUMERIC(24, 10) ) AS varchar)+A.大单位	
											WHEN B.Qty/A.关系>=1 AND B.Qty/A.关系 = CAST(ROUND(B.Qty/A.关系,0,1) AS NUMERIC(18,0)) THEN CAST(CAST(B.Qty/A.关系 as  numeric(18,0)) as varchar)+A.大单位+''/''+CAST(CAST(B.Qty/A.关系 as  numeric(18,0)) as varchar)+A.大单位
											WHEN B.Qty/A.关系>=1 THEN CAST(CAST(ROUND(B.Qty/A.关系,0,1) AS NUMERIC(18,0)) as varchar)+A.大单位+CAST(CAST(B.Qty as  NUMERIC(24, 10) )-CAST(CAST(A.关系 as  NUMERIC(24, 10) )*CAST(ROUND(B.Qty/A.关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))+A.单位+''/''+CAST(CAST(B.Qty/A.关系 AS  NUMERIC(24, 10) ) AS varchar(1000))+A.大单位				
											ELSE ''0''+A.单位+''/''+CAST(CAST(CAST(B.Qty AS  NUMERIC(24, 10) )/CAST(ISNULL(A.关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+A.大单位
										 END,
										 
				['+@StockName+'成本均价]=(CASE ISNULL(B.total,0) WHEN 0 THEN 0 ELSE  ISNULL(B.total,0)/ISNULL(B.Qty,0) END ),
				['+@StockName+'成本金额]=ISNULL(B.total,0)
			FROM '+N'##'+@TableName+' A
			LEFT JOIN (
						SELECT	X.TypeId,
								ISNULL(SUM(X.Qty),0) AS Qty,
								ISNULL(SUM(X.price),0) as price,
								ISNULL(SUM(X.total),0) as total
								
						FROM (
								SELECT	A.TypeId,
										ISNULL(G.Qty,0) AS Qty,
										ISNULL(G.price,0) as price,
										ISNULL(G.total,0) as total
								FROM 	'+N'##'+@TableName+' A
								LEFT JOIN (
											SELECT	PTypeId,
													ISNULL(SUM(Qty),0) AS Qty,
													ISNULL(SUM(price),0) as price,
													ISNULL(SUM(total),0) as total
											FROM	#GsStock 
											WHERE	KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'
											GROUP BY
													PTypeId
										)G ON LEFT(G.PTypeId,LEN(A.TypeId))=A.TypeId 
							)X
						GROUP BY X.TypeId
			)B ON A.TypeId = B.TypeId '
		--print(len(@sql))
		EXEC(@sql)
		IF @@error<>0

			BEGIN
				CLOSE Stock
				DEALLOCATE Stock
				--RAISERROR('更新商品数量生错误！',16,1)
				RETURN
			END
		SELECT @ReSql=@ReSql+',['+ @StockName + '账面库存],['+ @StockName + '辅助数量],['+ @StockName + '成本均价],['+ @StockName + '成本金额]'
 
 		FETCH NEXT FROM Stock INTO @kTypeId,@StockName
	END
 	CLOSE Stock
	DEALLOCATE Stock



	DECLARE @execSql varchar(8000)
		SELECT @execSql='SELECT * '
	IF @Flag=0
		SELECT @execSql=@execSql+' FROM '+N'##'+@TableName+' ORDER BY '+CONVERT(varchar(4),@INDEX)+' '+@Sort
	ELSE IF @Flag=1
		SELECT @execSql=@execSql+' FROM '+N'##'+@TableName
	EXEC(@execSql)

	-- 删除临时表
	SELECT @ReSql='DROP TABLE '+N'##'+@TableName+',#TempStock1'
	EXEC(@ReSql)



DROP TABLE #PType,#GetManPTypeId,#GsStock ,#GetManKTypeId, #GetSelectSTypeId

END
DROP TABLE #PTypeIdAll


GO	
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_PosGetPtypeFromBarCode]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_PosGetPtypeFromBarCode]
GO
-- 根据商品条码获取商品信息数据
CREATE PROCEDURE Pos_A8_PosGetPtypeFromBarCode
    (
      @Jtypeid VARCHAR(52) , --加盟商ID
      @Ktypeid VARCHAR(52) ,--仓库ID
      @BarCode VARCHAR(50) ,--商品条码
      @PosID VARCHAR(52) ,--posID
      @DefaultBarCode VARCHAR(52) , --条码ID
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
    )
    --@encode$--
AS 
    BEGIN
        DECLARE @BarTypeid INT
        DECLARE @Ptypeid VARCHAR(52)
        DECLARE @BarCodeDefVerLen INT
        DECLARE @POSManager VARCHAR(50)
        SELECT @POSManager = etypeid FROM PosInfoView WHERE PosID = @posid
        SET @BarTypeid = 0
	
        IF @DefaultBarCode = '' 
            SET @DefaultBarCode = '1' 
        SELECT  @BarCodeDefVerLen = BarCheckDigit
        FROM    posbarcodetypeview
        WHERE   Bartypeid = @DefaultBarCode


        DECLARE @SQL VARCHAR(8000) 
        CREATE TABLE #BarCodetmp
            (
              ptypeid VARCHAR(50) ,
              colorid INT ,
              sizeid INT ,
              iOrder INT IDENTITY(1, 1)
            )
        IF @DefaultBarCode <> '' 
            BEGIN 
                SET @SQL = ' insert into #BarCodetmp (ptypeid,colorid,sizeid) select  Ptypeid,isnull(Colorid,0) as Colorid,isnull(SizeID,0) as SizeID  from PosBarCodeView where Bartypeid='
                    + @DefaultBarCode + ' and  FullBarCode= '''
                    + CASE WHEN LEN(@BarCode) > @BarCodeDefVerLen
                           THEN LEFT(@BarCode,
                                     LEN(@BarCode) - @BarCodeDefVerLen)
                           ELSE '▲★▲'
                      END + ''''
                --PRINT @SQL
                EXEC(@sql)
            END
        SET @SQL = ' insert into #BarCodetmp (ptypeid,colorid,sizeid)'
            + '  select  Ptypeid,isnull(Colorid,0) as Colorid,isnull(SizeID,0) as SizeID  from PosBarCodeView b,posbarcodetypeview c '
            + ' where b.Bartypeid = c.BarTypeid and FullBarCode = case when '
            + CAST(LEN(@BarCode) AS VARCHAR)
            + '>c.BarCheckDigit then  left(''' + @BarCode + ''',len('''
            + @BarCode + ''') - c.BarCheckDigit) else ''▲★▲'' end'
            + ' and not exists(select 1 from #BarCodetmp c where b.ptypeid = c.ptypeid and b.colorid = c.colorid and b.sizeid = c.sizeid)'
            + ' order by b.pri' 
        --PRINT @SQL
        EXEC(@SQL)
	
        SELECT  1 AS qty ,
                a.ptypeid ,
                a.colorid ,
                a.sizeid ,
                b.FullName ,
                b.UserCode ,
                b.standard ,
                b.type ,
                b.area ,
                b.unit ,
                c.colorname ,
                d.sizename ,
                ISNULL(e.qty, 0) AS Stockqty
        FROM    #BarCodetmp a
                LEFT JOIN posptypeview b ON a.ptypeid = b.ptypeid
                LEFT JOIN poscolorView c ON a.colorid = c.colorid
                LEFT JOIN posSizeView d ON a.sizeid = d.sizeid
                LEFT JOIN ( SELECT  ptypeid ,
                                    colorid ,
                                    sizeid ,
                                    SUM(qty) AS qty
                            FROM    PosGoodsStocksDetailView
                            WHERE   Ktypeid = @Ktypeid
                            GROUP BY ptypeid ,
                                    Colorid ,
                                    Sizeid
                          ) e ON a.ptypeid = e.ptypeid
                                 AND a.colorid = e.colorid
                                 AND a.sizeid = e.sizeid
        WHERE   b.Deleted = 0
                AND Sonnum = 0
                AND b.stop = 0
                AND a.ptypeid IN (SELECT typeid FROM FN_GetPowerRangePList(@POSManager,''))
        ORDER BY a.iOrder
        DROP TABLE #BarCodetmp
    END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_PosGetPtypeFromName]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_PosGetPtypeFromName]
GO
-- 根据商品名称获取商品信息数据
CREATE PROCEDURE Pos_A8_PosGetPtypeFromName
    (
      @Jtypeid VARCHAR(50) ,--加盟商ID
      @Ktypeid VARCHAR(50) , --仓库ID
      @CommandTxt VARCHAR(50) ,--查询串
      @posid VARCHAR(50) , --posid
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
    )
    --@encode$--
AS 
    BEGIN
        DECLARE @POSManager VARCHAR(50)
        SELECT @POSManager = etypeid FROM PosInfoView WHERE PosID = @posid
        SELECT  1 AS qty ,
                a.ptypeid ,
                a.FullName ,
                a.UserCode ,
                a.standard ,
                a.type ,
                a.area ,
                a.unit ,
                0 AS relPrice
        FROM    posptypeview a
        WHERE   a.Deleted = 0
                AND Sonnum = 0
                AND a.stop = 0
                AND ( UserCode LIKE '%' + @CommandTxt + '%' OR FullName LIKE '%' + @CommandTxt + '%')
                AND a.Ptypeid IN (SELECT typeid FROM FN_GetPowerRangePList(@POSManager,''))
        ORDER BY a.ptypeid
    END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_PosGetPtypePrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_PosGetPtypePrice]
GO
-- 获取商品零售价格
CREATE procedure Pos_A8_PosGetPtypePrice(  
@Branchid varchar(50),  --机构ID
@Ktypeid varchar(50),  --仓库ID
@Ptypeid varchar(50), --商品ID
@PosId varchar(50),  --当前POSID，用于处理权限范围
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)  
--@encode$--
as  
begin   
  select 0 as stockprice,  
       b.Price as relprice  
  from posptypeview a  
 left join PosPtypePriceView b on a.ptypeid = b.ptypeid  
  where a.ptypeid = @Ptypeid
    
end  
  
  
  
  
  


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_PosGetVipInFo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_PosGetVipInFo]
GO
-- 获取会员卡信息数据
CREATE PROCEDURE Pos_A8_PosGetVipInFo
(
@CardNo varchar(100),--用户编号
@WithNameTel int, --是否查找姓名电话
@PosId varchar(50),  --当前POSID，用于处理权限范围
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
	SELECT CardNo,
	   (SELECT CardTypeName FROM PosVipcardTypesView WHERE Cardtypeid = a.CardTypeid) as CardTypeName,
	   Cardtypeid,
		CASE WHEN CardState = 0 THEN '启用' WHEN CardState = 1 THEN '删除作废' WHEN CardState = 2 THEN '停用' WHEN CardState = 3 THEN '挂失' WHEN GETDATE()>ValidDate THEN '过期作废' END AS CardState,
		nowIntegral,
		nowintegral + doIntegral AS Integral,
		doIntegral AS UsedIntegral,
		 isnull(Deposit,0) AS Deposit,
		 HandOutDate,
		 ValidDate,
		 HolderName,
		 HolderSex,
		 HolderId,
		 HolderTel 
FROM PosvipcardsView a
		WHERE (CardState<>1 AND CardNo = @CardNo OR((@WithNameTel = 1) AND ((HolderName = @CardNo) OR (HolderTel = @CardNo))))




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_SaveCommonPosSaleIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_SaveCommonPosSaleIndex]
GO

-- 保存POS销售明细单据数据
CREATE  PROCEDURE Pos_A8_SaveCommonPosSaleIndex
(  
 @BillCode varchar(50),--用户编号
 @BranchID varchar(50),--机构Id
 @BtypeID varchar(50),--往来单位Id
 @KtypeID varchar(50),--仓库Id
 @Cashier varchar(50),--收银员
 @Salesman varchar(50),--营业员
 @VipCardID int,--VIP卡ID
 @Total  NUMERIC(24, 10) ,--金额
 @BillDiscount  NUMERIC(24, 10) ,--整单折让
 @Efface  NUMERIC(24, 10) ,--抹零
 @FinallyTotal  NUMERIC(24, 10) ,--最终金额
 @PosID varchar(50),--POSID
 @SaleDate varchar(10),--销售日期
 @SaleTime varchar(8),--销售时间
 @Draft int, --结存标识,未结存为0,已结存为1
 @DraftVchcode int,--结存的单据编号
 @CashSum  NUMERIC(24, 10) ,--现金
 @CreditSum  NUMERIC(24, 10) ,--银行卡
 @ReplaceCashSum  NUMERIC(24, 10) ,--代金券
 @SaveAccountSum  NUMERIC(24, 10) ,--储值卡
 @ChangeSum  NUMERIC(24, 10) ,--找零
 @VipIntegral  NUMERIC(24, 10) ,--Vip积分
 @BackGoodsVch int,--调单原单号
 @SGCXBillID int,--促销单编号
 @RetReplaceCashSum  NUMERIC(24, 10) ,--手工促销返券金额
 @IsUpSend int, --上下传的标识：0——否 1——-是对POS有效，对后台程序无效。
 @UpLoadPosVchCode int,--POS数据库单据编号
 @UNIQUEID varchar(50), --唯一标识
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
begin
  insert into CommonPosSaleIndex (BillCode,Branchid,BtypeID,KtypeID,Cashier,Salesman,VipCardID,Total,BillDiscount,Efface,FinallyTotal,PosID,SaleDate,SaleTime,Draft,DraftVchcode,CashSum,CreditSum,ReplaceCashSum,SaveAccountSum,ChangeSum,VipIntegral,BackGoodsVchCode,SGCXBillID,RetReplaceCashSum,IsUpSend,UpLoadPosVchCode,UNIQUEID)
  values(@BillCode,@BranchID,@BtypeID,@KtypeID,@Cashier,@Salesman,@VipCardID,@Total,@BillDiscount,@Efface,@FinallyTotal,@PosID,@SaleDate,@SaleTime,@Draft,@DraftVchcode,@CashSum,@CreditSum,@ReplaceCashSum,@SaveAccountSum,@ChangeSum,@VipIntegral,@BackGoodsVch,@SGCXBillID,@RetReplaceCashSum,@IsUpSend,@UpLoadPosVchCode,@UNIQUEID)

  if @@rowcount =0    
   return -1  --保存数据失败
  else  
   return @@identity 
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_SaveCommonPosSaleIndexFreeze]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_SaveCommonPosSaleIndexFreeze]
GO

-- 保存POS销售挂单明细单据数据
CREATE  PROCEDURE Pos_A8_SaveCommonPosSaleIndexFreeze  
(
 @BillCode varchar(50), --用户编号
 @Branchid varchar(50), --机构Id
 @BtypeID varchar(50),--往来单位Id
 @KtypeID varchar(50),--仓库Id
 @Cashier varchar(50),--收银员
 @Salesman varchar(50),--营业员
 @VipCardID int, --VIP卡ID
 @Total  NUMERIC(24, 10) ,--金额
 @BillDiscount  NUMERIC(24, 10) ,--整单折让
 @Efface  NUMERIC(24, 10) ,--抹零
 @FinallyTotal  NUMERIC(24, 10) ,--最终金额
 @PosID varchar(50),--POSID
 @SaleDate varchar(10),--销售日期
 @SaleTime varchar(8),--销售时间
 @Draft int, --结存标识,未结存为0,已结存为1
 @DraftVchcode int,--结存的单据编号
 @CashSum  NUMERIC(24, 10) ,--现金
 @CreditSum  NUMERIC(24, 10) ,--银行卡
 @ReplaceCashSum  NUMERIC(24, 10) ,--代金券
 @SaveAccountSum  NUMERIC(24, 10) ,--储值卡
 @ChangeSum  NUMERIC(24, 10) ,--找零
 @VipIntegral  NUMERIC(24, 10) ,--Vip积分
 @BackGoodsVch int,--调单原单号
 @SGCXBillID int,--促销单编号
 @RetReplaceCashSum  NUMERIC(24, 10) ,--手工促销返券金额
 @IsUpSend int, --上下传的标识：0——否 1——-是对POS有效，对后台程序无效。
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
begin
  insert into CommonPosSaleIndexFreeze (BillCode,Branchid,BtypeID,KtypeID,Cashier,Salesman,VipCardID,Total,BillDiscount,Efface,FinallyTotal,PosID,SaleDate,SaleTime,Draft,DraftVchcode,CashSum,CreditSum,ReplaceCashSum,SaveAccountSum,ChangeSum,VipIntegral,BackGoodsVchCode,SGCXBillID,RetReplaceCashSum,IsUpSend)
  values(@BillCode,@Branchid,@BtypeID,@KtypeID,@Cashier,@Salesman,@VipCardID,@Total,@BillDiscount,@Efface,@FinallyTotal,@PosID,@SaleDate,@SaleTime,@Draft,@DraftVchcode,@CashSum,@CreditSum,@ReplaceCashSum,@SaveAccountSum,@ChangeSum,@VipIntegral,@BackGoodsVch,@SGCXBillID,@RetReplaceCashSum,@IsUpSend)

  if @@rowcount =0    
   return -1  --保存数据失败
  else  
   return @@identity 
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_SaveOpenCashBox]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_SaveOpenCashBox]
GO
-- 记录开启钱箱次数
create Procedure Pos_A8_SaveOpenCashBox
(@Date varchar(10),--当前日期 yyyy-mm-dd
 @Etypeid varchar(50),--职员ID
 @PosID varchar(50), --POSID
@ConditionStr varchar(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
begin
  if exists (select 1 from OpenCashBoxCount where etypeid = @etypeid and [Date] = @Date and PosID =  @PosID)
  begin
    update OpenCashBoxCount set OpenCount = OpenCount  + 1,IsUpSend = 0 where etypeid = @etypeid and @Date = @Date and PosID =  @PosID
  end
  else
  begin
    insert into OpenCashBoxCount(Etypeid,Date,OpenCount,IsUpSend,PosID)
    values(@Etypeid,@Date,1,0,@PosID)
  end 
  if @@rowcount =0    
   return -1  
  else  
   return 0
end



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_CheckMainProIsInUse]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_CheckMainProIsInUse]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--是否开账
Create procedure Pos_A8_CheckMainProIsInUse
(
 @BranchId VARCHAR(50),
 @ConditionStr varchar(8000) = '' --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
--select subvalue from sysdata where subname ='iniover' 
SELECT CAST(b.Value AS BIT) AS subvalue 
FROM stype a,stype_userconfig b 
WHERE a.TypeId=b.StypeId and a.typeid = @BranchId

---无论各项目组标志是什么，此处查询结果为1表示已经开帐，其他则为没有开帐,且字段名必须为subvalue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_CommonPosCanAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_CommonPosCanAccount]
GO

create procedure  Pos_A8_CommonPosCanAccount
(
@PosVchcode int, --POS小票ID
@jcVchcode int  output,--如果能过账返回结存的单据vchcode
@vchtype  int output, --如果能过账单据返回vchtype
@ConditionStr varchar(8000)='' --默认为空，各项目组的扩展参数,如果多于一个请各项目
)
--@encode$--
AS
BEGIN 
  set @jcVchcode = 0
  set @vchtype = 0
  select @jcVchcode= draftvchcode from commonpossaleindex where posvchcode =@PosVchcode    
  if @jcVchcode = 0 
     return -1 --未找到结存草稿，不能自动过帐
  select @vchtype = BillType from BillIndex where  BillCode=@jcVchcode
  if @vchtype = 0 
     return -1 --未找到结存草稿，不能自动过帐
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Pos_A8_CommonPosCanJC]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Pos_A8_CommonPosCanJC]
GO

CREATE PROCEDURE Pos_A8_CommonPosCanJC
    (
      @BranchId VARCHAR(50) , --机构Id  
      @AtypeId VARCHAR(50) OUTPUT ,--如果能结存返回银行账户ID
      @TaxRate  NUMERIC(24, 10)  OUTPUT , --如果能结存返回税率
      @ConditionStr VARCHAR(8000) = '' --默认为空，各项目组的扩展参数,如果多于一个请各项目
    )
--@encode$--
AS 
    --BEGIN 
    --    DECLARE @branchtype INT
    --    SELECT  @branchtype = Branchtype
    --    FROM    posbranchview
    --    WHERE   Branchid = @BranchId

    --    SELECT  ACard AS AtypeId ,
    --            TaxRate
    --    FROM    RetailAtype
    --    WHERE   ACard <> ''
    --            AND Typeid = @BranchId
                
    --    IF @@rowcount = 0
    --        AND @branchtype <> 3 
    --        RETURN -1 --还没有配置默认银行帐户信息不能结存！
            
    --    SELECT  @AtypeId = ACard ,
    --            @TaxRate = TaxRate
    --    FROM    RetailAtype
    --    WHERE   ACard <> ''
    --            AND Typeid = @BranchId
    --END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetCommonPosSaleIndexInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetCommonPosSaleIndexInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- 读主程序挂单信息
Create procedure Pos_A8_GetCommonPosSaleIndexInfo
(
 @Price varchar(50), --价格
 @RetailPrice varchar(50), --零售价
 @DisCount varchar(50), --折扣
 @discountrate varchar(50),--折扣率
 @Qty varchar(50),--数量
 @CXJFXS varchar(50),--促销积分系数
 @Sum varchar(50),--商品销售金额
 @aKtypeid varchar(50),--仓库ID
 @Ptypeid varchar(50),--商品ID
 @ColorID varchar(50),--颜色ID
 @SizeID varchar(50),--尺码ID
 @PosId varchar(50),--POSID
 @ConditionStr varchar(8000) = ''--默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
)
--@encode$--
as
select @Price as discountprice,b.PtypeID ,c.ColorID as ColorID,s.SizeID as Sizeid, b.Fullname ,b.UserCode,b.Unit,@RetailPrice as relPrice,@DisCount as discount,
@discountrate as DiscountRate,@Qty as Qty,@CXJFXS as CXJFXS, @Sum as Fsum,isnull(e.StockQty,0) as StockQty, c.ColorName,s.SizeName 
From PosPtypeView b 
left join  posPtypeColorSizeView a on b.ptypeid = a.ptypeid 
left join PosColorView c on a.ColorID=c.ColorID 
left join PosSizeView s  on a.SizeID=s.SizeID 
left join (select ptypeid,Colorid,Sizeid,sum(qty) as StockQty from PosGoodsStocksDetailView where  Ktypeid = @aKtypeid group by Ptypeid,Colorid,sizeid) e
 on b.ptypeid = e.ptypeid and c.colorid = e.colorid and s.sizeid = e.sizeid
 where b.Ptypeid = @Ptypeid and a.Colorid =@ColorID and a.Sizeid = @SizeID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GetYSZKJE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_GetYSZKJE]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年10月28日
-- Description:	根据分支机构往来单位查询预收账款余额
-- =============================================
CREATE PROCEDURE Pos_A8_GetYSZKJE 
(
@BranchId varchar(50),    --机构
@BTypeID varchar(50),    --单位
@YSZKJE NUMERIC(24, 10)  out  --返回预付账款余额
)
--@encode$--
AS
BEGIN
	SELECT @YSZKJE=ISNULL(YSTotal,0) FROM BType_ArApTotal WHERE BTypeID=@BTypeID AND STypeID=@BranchId
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_GP_PoseBalanceToBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Pos_A8_GP_PoseBalanceToBill
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2012-04-18
	描述：小票结存
*/

CREATE PROCEDURE Pos_A8_GP_PoseBalanceToBill 
(
	--@stypeid	VARCHAR(max),	--分支机构编号
	@id			VARCHAR(max)	--小票编号		
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @STARTDATE DATETIME,@tax  NUMERIC(24, 10) =0,@BILLTYPE VARCHAR(3)='',@posbilltype int,@comment varchar(100)='',@flag int=0,
		@billnumberid NUMERIC(18,0),@operatorid varchar(50),@atypeid varchar(50),
		---以下为commonpossaleindex中字段
		@cashsum  NUMERIC(24, 10) ,@creditsum  NUMERIC(24, 10) ,@replacecashsum  NUMERIC(24, 10) ,@saveaccountsum  NUMERIC(24, 10) ,@changesum  NUMERIC(24, 10) ,
		@vipcardid int,@billcode varchar(30),@saledate varchar(10),@billdiscount  NUMERIC(24, 10) ,@btypeid varchar(50),@etypeid varchar(50),@dtypeid varchar(50),
		@finallytotal  NUMERIC(24, 10) ,@stypeid VARCHAR(50),@ktypeid varchar(50),
		---以下为commonpossaleList字段
		@qty  NUMERIC(24, 10) =0,@totalmoney  NUMERIC(24, 10) =0,@ispresent int,@discountrate  NUMERIC(24, 10) ,@retailprice  NUMERIC(24, 10) ,@price  NUMERIC(24, 10) ,
		@sum  NUMERIC(24, 10) ,@ptypeid varchar(50)

SELECT @STARTDATE=StartDate FROM MonthProc WHERE MonthNo='本期'

SELECT	@stypeid=branchid,
		@cashsum=CashSum,
		@creditsum=creditsum,
		@replacecashsum=ReplaceCashSum,
		@saveaccountsum=saveaccountsum,
		@changesum=changesum,
		@vipcardid=vipcardid,
		@saledate=saledate,
		@billcode=BillCode,
		@btypeid=btypeid,
		@etypeid=salesman,
		@operatorid=Cashier,
		@ktypeid=ktypeid
FROM	commonpossaleindex
WHERE   posvchcode =@ID 
		AND draft=0
		
IF NOT EXISTS(	SELECT	TOP 1 1 FROM PosRetailCash WHERE Stypeid=@stypeid)
BEGIN
	--RAISERROR('未经行零售收银设置！',16,1)
	RETURN 1
END

IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE  BillCode=@billcode)
BEGIN
	--RAISERROR('单据编号重复，结存失败！',16,1)
	RETURN 1
END

IF	CONVERT(DATETIME,@saledate)<@STARTDATE
	SET @saledate=GETDATE()
		
SELECT @tax =ISNULL(tax,0) FROM PosRetailCash WHERE stypeid=@stypeid

SELECT	@qty=@qty+QTY,
		@totalmoney=@totalmoney + [Sum]
FROM commonpossaleList WHERE posvchcode=@id

---判断是零售还是退货单
IF @qty<0	--销售退货单
BEGIN
	
	SET @BILLTYPE='45'
	SET @comment='流水号：'+ @billcode+'POS小票结存为销售退货单'
	SET @qty=-@qty
	SET @posbilltype=1
END
ELSE
BEGIN		--零售单
	SET @BILLTYPE='305'
	SET @comment='流水号：'+ @billcode+'POS小票结存为零售单'
	SET @posbilltype=2
END

BEGIN TRANSACTION SAVEDATA	

CREATE TABLE #MulAccont		--多账户临时表
(
	[ATypeID] VARCHAR(50) NULL DEFAULT(''),		
	[Total]  NUMERIC(24, 10)  NULL DEFAULT(0),
	[Comment] VARCHAR(500) NULL DEFAULT(''),
	VipCardID INT NULL DEFAULT(-1)
)

IF @cashsum<>0		--构造现金科目账户
	INSERT INTO #MulAccont
		(
			atypeid,
			total,
			comment,
			vipcardid
		)
	SELECT	cashatypeid,
			CASE @BILLTYPE WHEN '305' THEN @cashsum-@changesum ELSE ABS(@cashsum) END,
			'',
			'-1'
	FROM	PosRetailCash
	WHERE Stypeid=@stypeid

IF @creditsum<>0		--构造银行科目账户
	INSERT INTO #MulAccont
		(
			atypeid,
			total,
			comment,
			vipcardid
		)
	SELECT	bankatypeid,
			ABS(@creditsum),
			'',
			'-1'
	FROM	PosRetailCash
	WHERE Stypeid=@stypeid

IF @replacecashsum<>0		--构造预收科目账户
	INSERT INTO #MulAccont
		(
			atypeid,
			total,
			comment,
			vipcardid
		)
	SELECT	ysatypeid,
			ABS(@replacecashsum),
			'',
			'-1'
	FROM	PosRetailCash
	WHERE Stypeid=@stypeid

IF @saveaccountsum<>0		--构造储值卡科目账户
BEGIN
	DECLARE @storecardatypeid VARCHAR(50)
	SELECT @storecardatypeid=StoreCardAtypeid FROM PosRetailCash WHERE Stypeid=@stypeid
	INSERT INTO #MulAccont
		(
			atypeid,
			total,
			comment,
			vipcardid
		)
	SELECT	@storecardatypeid,
			ABS(SaveAccountSum),
			'',
			VipID
	FROM	PosVipMoneyList
	where PosVchcode=@id
END
	
DECLARE @AtypeCount int=0	
SELECT @AtypeCount=COUNT(*) FROM #MulAccont
IF @AtypeCount=0
	INSERT INTO #MulAccont
			(
				atypeid,
				total,
				comment,
				vipcardid
			)
	VALUES
			(
				'0000100003',
				0,
				'',
				'-1'
			)
SELECT @AtypeCount=COUNT(*) FROM #MulAccont	
IF @AtypeCount=1
	SELECT @atypeid=ATypeID FROM #MulAccont
ELSE
	SET @atypeid=''

IF @atypeid='0000200005'	
	SELECT @vipcardid=VipCardID FROM #MulAccont
---------保存billindex-------------------
INSERT INTO [dbo].[BillIndex] 
(
		[vipczmoney],
		[BillDate],
		[BillCode],
		[BillType],
		[Comment],
		[atypeid],
		[ptypeid],
		[btypeid],
		[etypeid],
		[ktypeid],
		[ktypeid2],
		[ifcheck],
		[checke],
		[totalqty],
		[totalmoney],
		[totalinmoney],
		[tax],
		[period],
		[explain], 
		[draft],
		[RedWord],
		[orderid],
		[waybillcode],
		[goodsnumber],
		[packway],
		[Tel],
		[preferencemoney],
		[AlertDay],
		[ID],
		[Assessor],
		[IfAudit],
		[Audit_explain],
		[DtypeId],
		[VipCardID],
		[KTypeID3],
		[LinkMan],
		[LinkTel],
		[LinkAddr],
		[wxManID],
		[JieJianBillNumberID],
		[JieJianID],
		[BaoXiuBillNumberID],
		[BaoXiuID],
		[BuyDate],
		[Serial],
		[wxTotal],
		[ErrDes],
		[ifHideJieJian],
		[ifWX],
		[IfBargainOn],
		[Stypeid],
		[FromBillNumberID],
		[CostSale],
		[ifmulaccount],
		otherinouttype,
		PosBillType,
		checkTime,
		LastUpdateTime,
		ShareMode,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5
)
SELECT	0.00,
		@saledate,
		BillCode,
		@BILLTYPE,
		@comment,
		@atypeid,
		'',
		s.BtypeID,
		Salesman,
		KtypeID,
		'',
		'f',
		Cashier,
		@qty,
		abs(@totalmoney),
		abs(FinallyTotal),
		@tax,
		1,
		'',
		1,
		0,
		0,
		'',
		'',
		abs(FinallyTotal),
		0,
		abs(@totalmoney)-abs(FinallyTotal),
		9999,
		0,
		'',
		'',
		'',
		e.DtypeID,
		case @vipcardid when 0 then -1 else @vipcardid end,
		'',
		'',
		'',
		'',
		'',
		'-1',
		'-1',
		'-1',
		'-1',
		'',
		'',
		0,
		'',
		0,
		0,
		0,
		Branchid,
		PosVchCode,
		0,
		CASE @AtypeCount WHEN 1 THEN 0 ELSE 1 END,
		-1,
		@posbilltype,
		GETDATE(),
		NULL,
		0,
		'',
		'',
		'',
		'',
		''	
FROM	commonpossaleindex s,employee e
WHERE	e.typeId=s.Salesman 
		AND s.PosVchCode=@id
 				
SET @billnumberid=SCOPE_IDENTITY();

---------保存多账户信息
INSERT INTO BillMulAccount
	(
		BillNumberID,
		atypeid,
		total,
		comment,
		vipcardid
	)
SELECT	@billnumberid,
		ATypeID,
		Total,
		Comment,
		VipCardID
FROM	#MulAccont
DROP TABLE #MulAccont

IF @BILLTYPE='305'			--零售单
BEGIN			
--------------------保存retailbill-----------------
	INSERT INTO [dbo].[RetailBill] 
	  ( 
			[BillNumberId],
			[PtypeId],
			[Qty],
			[SalePrice],
			[discount],
			[DiscountPrice],
			[jobnumber],
			[total],
			[OutFactoryDate],
			[TaxPrice],
			[TaxTotal],
			[comment],
			OrderID,
			isUnit2,
			Serial,
			[GoodsNumber],
			[ProduceDate],
			[ValidDate],
			[GoodsBTypeID],
			[GoodsCostPrice],
			[HandZeroCost],
			[InputCostPrice],
			Tax,
			SaleTotal,
			STypeID
	) 
	SELECT	@billnumberid,
			PtypeID,
			ABS(Qty),
			CASE IsPresent WHEN 1 THEN 0 ELSE RetailPrice END,
			(CASE IsPresent WHEN 1 THEN 100 ELSE DisCountRate END)/100,
			Price,
			'',
			ABS([SUM]),
			NULL,
			price*(@tax/100 + 1),
			price*(@tax/100 + 1)*Qty,
			'',
			-1,
			0,
			'',
			'',
			'',
			'',
			'',
			-1,
			0,
			0,
			@tax,
			ABS(QTY)*CASE IsPresent WHEN 1 THEN 0 ELSE RetailPrice END,
			@stypeid
	FROM	CommonPosSaleList		
	WHERE	posvchcode=@id 

	-------------------保存零售单配置信息
	exec GP_RetailBillConfig '2', @operatorid,@btypeid,@ktypeid,@atypeid,@etypeid
END	
ELSE			--销售退货单
BEGIN
	INSERT INTO [dbo].[SaleBackBill] 
	  ( 
			[BillNumberId],
			[PtypeId],
			[Qty],
			[SalePrice],
			[discount],
			[DiscountPrice],
			[jobnumber],
			[total],
			[OutFactoryDate],
			[TaxPrice],
			[TaxTotal],
			[comment],
			[isUnit2],
			[Serial],
			[OldID],
			[OldBillNumberID],
			--[CostPrice],
			[InputCostPrice],
			[GoodsNumber],
			[ProduceDate],
			[ValidDate],
			[GoodsBTypeID],
			[GoodsCostPrice],
			[HandZeroCost],
			Tax,
			SaleTotal,
			KTypeID,
			STypeID,
			FromBillNumberID,
			FromBillID
	 ) 
	SELECT	@billnumberid,
			PtypeID,
			ABS(Qty),
			CASE IsPresent WHEN 1 THEN 0 ELSE RetailPrice END,
			(CASE IsPresent WHEN 1 THEN 100 ELSE DisCountRate END)/100,
			Price,
			'',
			ABS([SUM]),
			NULL,
			price*(@tax/100+1),
			abs(price*(@tax/100+1)*Qty),
			'',
			0,
			'',
			'',
			0,
			0,
			'',
			'',
			'',
			'',
			-1,
			0,
			@tax,
			ABS(QTY)*CASE IsPresent WHEN 1 THEN 0 ELSE RetailPrice END,
			@stypeid,
			@ktypeid,
			0,
			0
	FROM	CommonPosSaleList		
	WHERE	posvchcode=@id 
END	

UPDATE CommonPosSaleIndex SET Draft=1 WHERE PosVchCode=@ID
					
IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  SAVEDATA
	--RAISERROR('pos结存保存草稿失败！',16,1)
	RETURN 1
END

COMMIT TRANSACTION  SAVEDATA

------------------------------------------过账数据判断-------------------------
IF NOT EXISTS (SELECT	TOP 1 1 FROM	SType_UserConfig WHERE	ConfigNo = 1 AND Value = 1 AND STypeID=@stypeid)   
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		-- 没有开帐不允许过帐      
	RETURN 2
END

DECLARE @vipcardrowcount int=0,@CZMoney  NUMERIC(24, 10) 
IF @vipcardid<>0
BEGIN
	SELECT @vipcardrowcount=COUNT(VipCardID) FROM nVipCardSign WHERE VipCardID=@vipcardid AND Deleted='0' AND EndDate>=@saledate 
	IF @vipcardrowcount <> 1
	BEGIN
		--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--会员卡信息错误
		RETURN 2
	END	
	IF @atypeid = '0000200005'
	BEGIN	
		SELECT @CZMoney=cZyeMoney FROM nVipCardSign WHERE VipCardID=@vipcardid AND Deleted='0' AND IsCz='1'
		IF @vipcardrowcount=0 OR @totalmoney>@CZMoney
		BEGIN
			--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--会员卡储值余额不足
			RETURN 2
		END	
	END	
END

IF NOT EXISTS(SELECT TOP 1 TypeID FROM Employee WHERE SonNum = 0 AND TypeID = @Etypeid)
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--经手人不是一个有效的职员
	RETURN 2
END	

IF NOT EXISTS(SELECT TOP 1 TypeID FROM stype WHERE SonNum = 0 AND TypeID = @stypeid)
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--分支机构不是一个有效的分支机构
	RETURN 2
END	

IF NOT EXISTS(SELECT TOP 1 TypeID FROM BTYPE WHERE SonNum = 0 AND TypeID = @btypeid)
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--不是一个有效的往来单位
	RETURN 2
END	

IF NOT EXISTS(SELECT B.typeId FROM F_GetManDetailKType(@etypeid) a INNER JOIN Stock b ON a.TypeID=b.TypeID WHERE A.TypeId=@ktypeid AND a.TypeID <> '00000' AND b.STypeID=@STypeID AND b.SonNum=0)	
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--不是一个有效的仓库或者仓库不再分支机构下
	RETURN 2
END	

IF @AtypeCount=1 AND NOT EXISTS(SELECT TOP 1 TypeID FROM ATYPE WHERE SonNum = 0 AND TypeID = @Atypeid)
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--不是一个有效的账户
	RETURN 2
END	

IF EXISTS(SELECT PtypeID FROM  CommonPosSaleList WHERE PosVchCode=@ID AND PtypeID NOT IN( SELECT TypeID FROM PType WHERE SonNum=0  AND TypeID <> '00000'))
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--有商品不是一个有效的商品
	RETURN 2
END	

IF EXISTS(SELECT qty FROM CommonPosSaleList WHERE PosVchCode=@id AND Qty=0)
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--数量为0不允许过账
	RETURN 2
END	

IF EXISTS(SELECT * FROM CommonPosSaleList WHERE PosVchCode=@id AND   ((IsPresent=1 AND (price*(@tax/100+1)*Qty<>0 OR SUM<>0)) OR (IsPresent <>1 AND ((RetailPrice =0 AND (price*(@tax/100+1)*Qty<>0 OR SUM<>0))OR(RetailPrice <>0 AND (price*(@tax/100+1)*Qty =0 OR SUM=0))))))
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--金额 或 折后金额 或 价税合计 存在零和非零同时存在的情况
	RETURN 2
END	

IF EXISTS(SELECT * FROM CommonPosSaleList WHERE (ABS(Price*QTY)> ABS(SUM*1.05) OR ABS(SUM)> 1.05*ABS(Price*QTY)) AND PosVchCode=@id)
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--（数量×折后单价）与折后金额相差大于5％
	RETURN 2
END	

IF EXISTS(SELECT * FROM CommonPosSaleList WHERE PosVchCode=@id AND IsPresent<>1 AND (DisCountRate/100<0 OR DisCountRate/100>10 OR DisCountRate=0 OR DisCountRate=1000))
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--折扣大于=10或者小于=0
	RETURN 2
END	
----------------------------单据过账---------------------
DECLARE
	@szPID					varchar(1000) ,		-- 返回出错商品 ID 值		
	@Ret					INT


BEGIN TRANSACTION AUDITING
EXEC Gp_NewAuditing @billnumberid,@operatorid,@szPID out,@operatorid,@ktypeid out,@BILLTYPE,@Ret OUT


IF @Ret<>0
BEGIN
	--RAISERROR('pos结存过账失败，保存为草稿！',16,1)		--过账失败
	ROLLBACK TRANSACTION AUDITING
	RETURN 2
END
ELSE
BEGIN
	COMMIT TRANSACTION AUDITING
	RETURN 0
END
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_PosGetBasicData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_PosGetBasicData]
GO


/****** Object:  StoredProcedure [dbo].[Pos_A8_PosGetBasicData]    Script Date: 08/04/2011 14:57:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- 根据商品货号或名称查询其信息数据
CREATE PROCEDURE [dbo].[Pos_A8_PosGetBasicData]
    (
      @Barcode VARCHAR(50) ,--商品条码
      @BaseType INT ,--基本信息对应表名
      @WithColAndSiz INT ,--是否有颜色尺码  
      @selectstring VARCHAR(100) ,--搜索串
      @PosUserId VARCHAR(50) ,--POS用户编号
      @PosId VARCHAR(50) , --POSID
      @DefaultBarCode VARCHAR(50) , --默认商品条码
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开  
    )
--@encode$--
AS 
    DECLARE @MangerId VARCHAR(50)
    DECLARE @Jtypeid VARCHAR(50)
    DECLARE @Branchid VARCHAR(50)
    
    DECLARE @POSManager VARCHAR(50)
    SELECT  @POSManager = etypeid
    FROM    PosInfoView
    WHERE   PosID = @posid
    
    IF @BaseType = '1' 
        GOTO P
    IF @BaseType = '2' 
        GOTO B
    IF @BaseType = '3' 
        GOTO K
    IF @BaseType = '4' 
        GOTO A
    IF @BaseType = '5' 
        GOTO E
    IF @BaseType = '6' 
        GOTO O
        
    P:
    BEGIN
        IF @WithColAndSiz = 1 
            BEGIN
                IF @selectstring <> '▲'  --模糊查找
                    BEGIN
                        SELECT  [name] ,
                                p.Ptypeid AS Typeid ,
                                fullname ,
                                usercode ,
                                Sonnum ,
                                pcs.Colorid ,
                                pcs.ColorName ,
                                pcs.Sizeid ,
                                pcs.SizeName ,
                                p.stop
                        FROM    PosPtypeView p
                                LEFT JOIN ( SELECT  a.* ,
                                                    b.Colorname ,
                                                    c.SizeName
                                            FROM    PosPtypeColorSizeView a
                                                    LEFT JOIN PosColorView b ON a.colorid = b.colorid
                                                    LEFT JOIN PossizeView c ON a.sizeid = c.sizeid
                                          ) pcs ON p.ptypeid = pcs.ptypeid 
                        WHERE   sonnum = 0
                                AND deleted = 0
                                AND ( p.fullname LIKE '%' + @selectstring
                                      + '%'
                                      OR p.usercode LIKE '%' + @selectstring
                                      + '%'
                                    )
                                AND p.Ptypeid IN (
                                SELECT  typeid
                                FROM    FN_GetPowerRangePList(@POSManager, '') )
                        ORDER BY p.ptypeid ,
                                pcs.colorid ,
                                pcs.sizeid
                        GOTO Success    
                    END
                ELSE 
                    BEGIN
                        DECLARE @BarTypeid INT	
                        DECLARE @BarCodeDefVerLen INT
                        SET @BarTypeid = 0
                        IF @DefaultBarCode = '' 
                            SET @DefaultBarCode = '1' 
                        SELECT  @BarCodeDefVerLen = BarCheckDigit
                        FROM    posbarcodetypeview
                        WHERE   Bartypeid = @DefaultBarCode

                        DECLARE @SQL VARCHAR(8000) 
                        CREATE TABLE #BarCodetmp
                            (
                              ptypeid VARCHAR(50) ,
                              colorid INT ,
                              sizeid INT ,
                              iOrder INT IDENTITY(1, 1)
                            )
                        IF @DefaultBarCode <> '' 
                            BEGIN 
                                SET @SQL = ' insert into #BarCodetmp (ptypeid,colorid,sizeid) select  Ptypeid,isnull(Colorid,0) as Colorid,isnull(SizeID,0) as SizeID  from PosBarCodeView where Bartypeid='
                                    + @DefaultBarCode
                                    + ' and  FullBarCode= '''
                                    + CASE WHEN LEN(@BarCode) > @BarCodeDefVerLen
                                           THEN LEFT(@BarCode,
                                                     LEN(@BarCode)
                                                     - @BarCodeDefVerLen)
                                           ELSE '▲★▲'
                                      END + ''''
                                EXEC(@sql)
                            END
                        SET @SQL = ' insert into #BarCodetmp (ptypeid,colorid,sizeid)'
                            + '  select  Ptypeid,isnull(Colorid,0) as Colorid,isnull(SizeID,0) as SizeID  from PosBarCodeView b,posbarcodetypeview c '
                            + ' where b.Bartypeid = c.BarTypeid and FullBarCode = case when '
                            + CAST(LEN(@BarCode) AS VARCHAR)
                            + '>c.BarCheckDigit then  left(''' + @BarCode
                            + ''',len(''' + @BarCode
                            + ''') - c.BarCheckDigit) else ''▲★▲'' end'
                            + ' and not exists(select 1 from #BarCodetmp c where b.ptypeid = c.ptypeid and b.colorid = c.colorid and b.sizeid = c.sizeid)'
                            + ' order by b.pri' 
                        PRINT @SQL
                        EXEC(@SQL)	

                        SELECT  a.*
                        FROM    ( SELECT    [name] ,
                                            p.Ptypeid AS Typeid ,
                                            fullname ,
                                            usercode ,
                                            Sonnum ,
                                            pcs.Colorid ,
                                            pcs.ColorName ,
                                            pcs.Sizeid ,
                                            pcs.SizeName ,
                                            p.stop
                                  FROM      PosPtypeView p
                                            LEFT JOIN ( SELECT
                                                              a.* ,
                                                              b.Colorname ,
                                                              c.SizeName
                                                        FROM  PosPtypeColorSizeView a
                                                              LEFT JOIN PosColorView b ON a.colorid = b.colorid
                                                              LEFT JOIN PossizeView c ON a.sizeid = c.sizeid
                                                      ) pcs ON p.ptypeid = pcs.ptypeid 
                                  WHERE     sonnum = 0
                                            AND deleted = 0
                                            AND p.Ptypeid IN (
                                            SELECT  typeid
                                            FROM    FN_GetPowerRangePList(@POSManager,
                                                              '') )
                                ) a
                                INNER JOIN #BarCodetmp c ON a.typeid = c.ptypeid
                                                            AND a.colorid = c.colorid
                                                            AND a.sizeid = c.sizeid
                        ORDER BY c.iorder
                        GOTO Success
                    END
            END
        ELSE 
            BEGIN
                SELECT  [name] ,
                        Ptypeid AS Typeid ,
                        fullname ,
                        usercode ,
                        Sonnum ,
                        stop
                FROM    PosPtypeView
                WHERE   ( fullname LIKE '%' + @selectstring + '%'
                          OR usercode LIKE '%' + @selectstring + '%'
                        )
                        AND sonnum = 0
                        AND deleted = 0
                        AND Ptypeid IN (
                        SELECT  Ptypeid 
                        FROM    FN_GetPowerRangePList(@POSManager, '') )
                ORDER BY typeid
                GOTO Success    
            END
    END
    
    B:
    BEGIN
        SELECT  @Jtypeid = Branchid
        FROM    posinfoview
        WHERE   posid = @PosId
        IF LEFT(@jtypeid, 5) = '00004' 
            SELECT  Btypeid AS Typeid ,
                    fullname ,
                    Sonnum ,
                    [name] ,
                    usercode
            FROM    PosBtypeView
            WHERE   sonnum = 0
                    AND deleted = 0
                    AND LEFT(Btypeid, 5) LIKE '00006%'
                    AND ( fullname LIKE '%' + @SelectString + '%'
                          OR usercode LIKE '%' + @SelectString + '%'
                        )
                    AND btypeid IN (
                    SELECT  btypeid
                    FROM    FN_GetPowerRangeBList(@POSManager, '00006', '6') )
        ELSE 
            SELECT  Btypeid AS Typeid ,
                    fullname ,
                    Sonnum ,
                    [name] ,
                    usercode
            FROM    PosBtypeView
            WHERE   sonnum = 0
                    AND deleted = 0
                    AND LEFT(Btypeid, 5) LIKE '00002%'
                    AND ( fullname LIKE '%' + @SelectString + '%'
                          OR usercode LIKE '%' + @SelectString + '%'
                        )
                    AND btypeid IN (
                    SELECT  btypeid
                    FROM    FN_GetPowerRangeBList(@POSManager, '00002', '2') )
            ORDER BY typeid
        GOTO Success
    END
    
    K:
    SELECT  @Branchid = Branchid
    FROM    PosInfoView
    WHERE   Posid = @Posid
    SELECT  Ktypeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode
    FROM    PosStockView
    WHERE   ( fullname LIKE '%' + @SelectString + '%'
              OR usercode LIKE '%' + @SelectString + '%'
            )
            AND sonnum = 0
            AND deleted = 0
            AND Branchid = @Branchid
            AND Ktypeid IN(
            SELECT typeid 
            FROM F_GetManKTypeAll(@POSManager)
            )
    ORDER BY usercode
    GOTO Success

    A:
    SELECT  Atypeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode
    FROM    PosAtypeView
    WHERE   ( ( fullname LIKE '%' + @SelectString + '%'
                OR usercode LIKE '%' + @SelectString + '%'
              )
              AND sonnum = 0
              AND deleted = 0
            )
    GOTO Success
    
    E:  
    IF @PosUserId = '' 
        SELECT  @Branchid = Branchid
        FROM    PosInfoView
        WHERE   Posid = @Posid
    ELSE 
        SET @Branchid = @PosUserId
    IF LEFT(@Branchid, 5) = '00001' 
        SET @Branchid = '0000100001'		
    SELECT  Etypeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode ,
            Branchid
    FROM    PosEmployeeView
    WHERE   ( fullname LIKE '%' + @SelectString + '%'
              OR usercode LIKE '%' + @SelectString + '%'
            )
            AND sonnum = 0
            AND Etypeid <> '00000'
            AND deleted = 0
            AND Branchid = LEFT(@Branchid, LEN(Branchid))
            AND etypeid IN ( SELECT etypeid
                             FROM   FN_GetPowerRangeEList(@POSManager, '') )
    GOTO Success
    
    O:
    SELECT  a.PosId AS Typeid ,
            a.fullname ,
            a.Usercode ,
            a.fullname AS [name] ,
            0 AS sonnum ,
            a.etypeid ,
            CASE LEFT(a.Branchid, 5)
              WHEN '00001' THEN '0000100001'
              ELSE a.Branchid
            END AS branchid
    FROM    PosInfoView a
    WHERE   a.Deleted <> 1
            AND ( a.fullname LIKE '%' + @SelectString + '%'
                  OR a.usercode LIKE '%' + @SelectString + '%'
                )        

    Success:
    RETURN 0
    

GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_PosPdtoMainProPd]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_PosPdtoMainProPd]
GO

CREATE  PROCEDURE Pos_A8_PosPdtoMainProPd
    (
      @IndexValue INT ,
      @MustDone INT = 0
    )
--@encode$--    
AS 
RETURN @IndexValue

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_A8_UpDateSystemRebuildGuid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pos_A8_UpDateSystemRebuildGuid]
GO

CREATE PROCEDURE Pos_A8_UpDateSystemRebuildGuid
--@encode$--
AS
BEGIN		
	DECLARE @newguid uniqueidentifier 
	SET @newguid = NEWID()
	if EXISTS (SELECT * FROM SystemRebuildGuid) 
	  UPDATE SystemRebuildGuid SET RebuildGuid = @newguid
	ELSE
	  INSERT INTO SystemRebuildGuid (RebuildGuid) VALUES (@newguid)
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_GetCurrentDayDogInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Pos_GetCurrentDayDogInfo
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].Pos_GetCurrentDayDogInfo 
--@encode$--	
AS
	SET NOCOUNT ON;
	
	SELECT dognumber,posname,billcount AS billcount,eid AS eid,id
	INTO #temp
	FROM dbo.Pos_UploadDogInfo
	WHERE IsUpload=0 
	
	SELECT  dognumber AS dognum,posname,SUM(billcount) AS billcount,COUNT(eid) AS posusercount
	FROM #temp
	GROUP BY posname ,dognumber
	
	SELECT id
	FROM #temp
	
				
go

		


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[POS_GetPosDownloadPicList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].POS_GetPosDownloadPicList
GO
CREATE    PROCEDURE POS_GetPosDownloadPicList 
(	
	@posid INT,
	@count INT,
	@isall INT ,
	@totalcount INT OUT
)
--@encode$--
AS

DECLARE @sql VARCHAR(MAX)

IF @isall =1
BEGIN
	INSERT INTO  dbo.Pos_PicUpdateRecord
	        ( pid, updatenumber )	
	SELECT p.Pid,1 AS updatenumber
	FROM dbo.ptype p
	INNER JOIN (SELECT PTypeID,MIN(OrderID) AS oriderid FROM dbo.PType_Picture GROUP BY PTypeID) pp ON p.typeId=pp.PTypeID	
	WHERE p.sonnum=0 AND p.deleted=0 
	AND NOT EXISTS(SELECT TOP 1 1 FROM Pos_PicUpdateRecord WHERE pid=p.Pid) 
END

SELECT ppu.pid, CASE WHEN  updatenumber >ISNULL(lastupdatenumber,-1)  THEN 1 ELSE 0 END uploadflag
INTO #uploadpic 
from Pos_PicUpdateRecord ppu
LEFT JOIN dbo.Pos_UploadPicRecord pu   ON pu.Pid = ppu.pid  and pu.posid=@posid

--SELECT @totalcount=COUNT(1) FROM #uploadpic WHERE uploadflag=1
		
-----当deleted=0 时 删除

  	;WITH porder AS   
	(  
		SELECT ptypeid,MIN(orderid) AS orderid   
		FROM dbo.PType_Picture  
		GROUP BY PTypeID  
	)
	SELECT  p.pid,p.typeId ,po.orderid   --,pic AS imgdata,isnull(filename,'''') as picname 
	into #temp
	FROM dbo.ptype p 	
	INNER JOIN #uploadpic up ON p.Pid = up.pid   AND up.uploadflag=1
	INNER JOIN porder po ON po.PTypeID= p.typeId
	WHERE p.sonnum=0 AND p.deleted=0  
	--ORDER by isnull(pic.ptypeid,'''') desc 
SET @sql='
	select TOP '+CAST(@count AS VARCHAR(30))+' t.pid,pp.pic as imgdata,isnull(pp.filename,'''') as picname from #temp t inner join PType_Picture pp on pp.PtypeId = t.typeid and pp.orderid = t.orderid order by t.pid desc
	'
SELECT @totalcount=COUNT(1) FROM #temp
EXEC (@sql)
                	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[POS_GP_QuerySerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].POS_GP_QuerySerial
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE    PROCEDURE POS_GP_QuerySerial	
(
	@serial VARCHAR(50),
	@kid INT,
	@isbackbill INT,
	@posid INT 	
)
AS
DECLARE @ktypeid VARCHAR(50)
SELECT @ktypeid=typeId FROM dbo.Stock WHERE Kid=@kid

DECLARE @isPtypeAll BIT 
SELECT @isPtypeAll = isPtypeAll FROM dbo.PosInfo WHERE PosID = @posid

DECLARE @sql VARCHAR(5000)
IF @isbackbill=1
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.gp_CruPtypeSerial WHERE Serial=@serial )
	BEGIN
		SELECT  -1 as returnvalue 
		RETURN ;
	END	
	
	SELECT @sql = 'SELECT DISTINCT a.Serial AS serial,a.ItemId AS itemid,p.[standard],CAST(1 AS int) AS discount,
				p.pid,p.baseUnitId AS unitid,pue.rate AS unitrate,pu.FullName AS unitname,ISNULL(p.customitemid,'''') AS customitemid,ISNULL(p.customitemfrom,'''') AS customitemfrom,
				 CASE WHEN a.IsCombined = 0  THEN
				(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END AS itemname,
				CAST(a.IsCombined AS INT) AS iscombined,				
				--CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
			 --   CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
				a.ProduceDate AS producedate,
				a.ValidDate AS validdate,
				a.goodsnumber as goodsnumber,
				p.FullName AS fullname,p.usercode AS usercode,p.EntryCode AS barcode,a.CostPrice,p.ifserial
		INTO #backbill
		FROM	GP_CruPTypeSerial a
		INNER JOIN ptype p ON a.PtypeID=p.typeId '
	 
	 IF(@isPtypeAll = 0)
	 BEGIN
		SELECT @sql += 'INNER JOIN dbo.POSPtype pp ON p.typeId LIKE pp.ptypeid+''%''  '
	 END 	
		
	SELECT @sql +=	'LEFT JOIN dbo.PType_Units pu ON p.baseUnitId=pu.UnitsId
		LEFT JOIN dbo.PType_Units_Ext pue ON p.baseUnitId=pue.UnitsId
		LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
		WHERE	a.Serial ='''+ @serial+'''
				AND a.KTypeID ='''+ @ktypeid+'''
				AND a.State NOT IN (1,7) 
				AND p.deleted=0
		IF NOT EXISTS(SELECT TOP 1 1 FROM #backbill)
		BEGIN
			SELECT  -2 as returnvalue 
			RETURN ;
		END	
		SELECT * FROM #backbill'
		--PRINT @sql
	EXEC(@sql)
END
ELSE
BEGIN
	
	SELECT @sql ='SELECT DISTINCT a.Serial AS serial,a.ItemId AS itemid,p.[standard],CAST(1 AS int) AS discount,
			p.pid,p.baseUnitId AS unitid,pue.rate AS unitrate,pu.FullName AS unitname,ISNULL(p.customitemid,'''') AS customitemid,ISNULL(p.customitemfrom,'''') AS customitemfrom,
			 CASE WHEN a.IsCombined = 0  THEN
			(SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END AS itemname,
			CAST(a.IsCombined AS INT) AS iscombined,				
			--CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT CargoID  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE a.CargoID END AS CargoID,
		 --   CASE WHEN a.CargoID = '''' OR a.CargoID = ''0'' OR a.CargoID = 0 OR LEN(a.CargoID) = 0 THEN (SELECT fullname  FROM CargoType WHERE KtypeID=a.Ktypeid AND IsDefault=1) ELSE ct.fullname END AS cargofullname,
			a.ProduceDate AS producedate,
			a.ValidDate AS validdate,
			a.goodsnumber as goodsnumber,
			p.FullName AS fullname,p.usercode AS usercode,p.EntryCode AS barcode,a.CostPrice,p.ifserial
			INTO #saleresult 
			FROM	GP_CruPTypeSerial a
			INNER JOIN ptype p ON a.PtypeID=p.typeId '
	
	 IF(@isPtypeAll = 0)
	 BEGIN
		SELECT @sql += ' INNER JOIN dbo.POSPtype pp ON p.typeId LIKE pp.ptypeid+''%''  '
	 END 	
	
	SELECT @sql +='
	LEFT JOIN dbo.PType_Units pu ON p.baseUnitId=pu.UnitsId
	LEFT JOIN dbo.PType_Units_Ext pue ON p.baseUnitId=pue.UnitsId
	LEFT JOIN CargoType ct ON a.CargoID = ct.CargoID
	WHERE	a.Serial = ''' + @serial + '''
		AND a.KTypeID = ''' + @ktypeid +'''
		AND a.State IN (1,7) 
		AND a.Flag = 1
		AND p.deleted=0
		AND NOT EXISTS
		(
			SELECT TOP 1 1 FROM GP_LendPTypeSerial 
			WHERE Flag = 0 AND State = 18 AND Serial=a.Serial
		)
	IF NOT EXISTS(SELECT TOP 1 1 FROM #saleresult)
	BEGIN
		SELECT -3 as returnvalue 
		RETURN ;
	END	
	SELECT * FROM #saleresult'
	--PRINT @sql
	EXEC (@sql)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pos_Web_StockGoodsNumber]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Pos_Web_StockGoodsNumber
GO

CREATE       PROCEDURE Pos_Web_StockGoodsNumber
(
 @eid        varchar(100) ,					--------------------------操作员ID
 @kid           INT,					--------------------------仓库ID号
 @pid           INT,					--------------------------商品ID号
 @isgoodsnumber		INT	,							-------------------------如果为1则是批号查询，如果为0则是批次查询
 @cargoid			INT ,---货号和自由项处理
 @itemid			INT=0,
 @filterStr varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PtypeId VARCHAR(50),@OperatorID VARCHAR(50),@ktypeid VARCHAR(50)
SELECT @ptypeid =typeid FROM ptype WHERE Pid=@pid
SELECT @OperatorID= typeid FROM dbo.employee WHERE Eid=@eid
SELECT @ktypeid =typeid FROM stock  WHERE Kid=@kid


------------------------------------------------------批次显示查询------------------------------------------------------------------------
IF @isgoodsnumber=0 
BEGIN
	SELECT
	   ROW_NUMBER() OVER (ORDER BY g.PTypeid) AS [lineno],
		g.PTypeid, 
		g.KtypeId, 
		g.Qty,
		g.GoodsCostPrice ,
		g.GoodsCostPrice*g.Qty as total,
		g.GoodsNumber,LEFT(g.ProduceDate,10) AS producedate,LEFT(g.ValidDate,10) AS validdate,
		p.UsefulLifeDay,
		p.ValidDays,
		g.NQty,
		case when g.Iscombined=0 then (select top 1 FullName from xw_SelfData where _Id=g.ItemID)
		else 
		(select top 1 REPLACE( FullName,'я','/') from CustomReferenceValue where id=g.ItemID) end as itemname ,
		c.FullName as cargofullname,
		c.CargoID as cargoid,
		g.Iscombined,
		g.ItemID
	FROM
		GOODSSTOCKS_QTY g
	LEFT JOIN Ptype p
		ON g.PtypeId = p.TypeId
	LEFT JOIN CargoType c
		ON g.CargoID=c.CargoID
	WHERE
	     g.GoodsNumber LIKE '%'+@filterStr+'%'
		AND g.PtypeId=@PtypeId 
		--AND g.KtypeId IN (SELECT TypeId FROM F_GetManDetailAllKType(@OperatorID))
		AND g.KtypeId=@Ktypeid
		AND g.Qty>0
		AND g.ItemID=@itemid
		ORDER BY g.CargoID
END

------------------------------------------------------------------批号查询-----------------------------------------------------------

create table #goodstemp
(
	GoodsNumber varchar(max),
	price  NUMERIC(24, 10)  null,
	Qty  NUMERIC(24, 10) ,
	ProduceDate varchar(800),
	ValidDate varchar(800)
)

IF @isgoodsnumber=1 
BEGIN
 insert into #goodstemp select GoodsNumber,price,Qty,ProduceDate,ValidDate from(
 	SELECT
		g.PTypeid, 
		g.KtypeId, 
		0 AS total,
		SUM(g.Qty) AS Qty,g.GoodsCostPrice AS price,
		g.GoodsNumber,LEFT(g.ProduceDate,10) AS producedate,LEFT(g.ValidDate,10) AS validdate,
		p.UsefulLifeDay,
		p.ValidDays
	FROM
		GoodsStocks_QTY g
	LEFT JOIN
		Ptype p
	ON g.PtypeId = p.TypeId
	WHERE
		g.PtypeId=@PtypeId 
		--AND g.KtypeId IN (SELECT TypeId FROM F_GetManDetailAllKType(@OperatorID))
		AND g.KtypeId=@Ktypeid
		AND  ((g.CargoID=@cargoid AND @cargoid<>-1 AND @cargoid IS NOT NULL) OR (@cargoid=-1 OR @cargoid IS NULL))
		AND ((g.ItemID=@itemid AND @itemid IS NOT NULL AND @itemid<>0)OR(@itemid IS NULL OR @itemid=0))
		AND g.qty>0
		AND g.ItemID=@itemid
	GROUP BY g.PTypeid, 
		g.KtypeId, 
		g.Qty,
		g.GoodsNumber,LEFT(g.ProduceDate,10) ,LEFT(g.ValidDate,10),g.GoodsCostPrice,
		p.UsefulLifeDay,
		p.ValidDays		
		having(COUNT(*))>0 ) a

	 if ISNULL( @filterStr,'')=''
		SELECT ROW_NUMBER() OVER (ORDER BY GoodsNumber) AS [lineno], GoodsNumber AS goodsnumber,price,Qty AS qty,
		ProduceDate AS producedate,ValidDate AS validdate from  #goodstemp
	 else
	 BEGIN
		if exists(select top 1 * from  #goodstemp where GoodsNumber =@filterStr)
			select ROW_NUMBER() OVER (ORDER BY GoodsNumber) AS [lineno], 
			GoodsNumber AS goodsnumber,
			price,
			Qty AS qty ,
			ProduceDate,ValidDate
			from  #goodstemp where GoodsNumber =@filterStr
		else
			SELECT ROW_NUMBER() OVER (ORDER BY GoodsNumber) AS [lineno],  GoodsNumber AS goodsnumber,price,Qty AS qty,
			ProduceDate,ValidDate
			from  #goodstemp where GoodsNumber like '%'+@filterStr+'%'
	 end
end

drop table #goodstemp
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PosBankInfoSelect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[PosBankInfoSelect]
GO

/****** Object:  StoredProcedure [dbo].[PosBankInfoSelect]    Script Date: 08/01/2011 10:59:48 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011年8月1日
-- Description:	选择银行基本信息节点
-- =============================================
CREATE PROCEDURE [dbo].[PosBankInfoSelect] 
(
  @OperatorId		varchar(100)	--当前操作员的ID
)
--@encode$--	
AS
CREATE TABLE #BankInfo([typeid]VARCHAR(100)not null,[fullname] VARCHAR(100) not null)
DECLARE @typeid VARCHAR(100)
DECLARE @fullname VARCHAR(100)
DECLARE @maxleveal VARCHAR(100)
DECLARE cursorname CURSOR  ------查询游标
LOCAL SCROLL STATIC 
FOR SELECT typeid,fullname FROM atype WHERE left(parid,10)='0000100004'  and sonnum=0 AND  Deleted=0 AND typeid in(select * from F_GetAllManagerBaseTypeId('',5,@OperatorId))
OPEN cursorname
FETCH NEXT FROM cursorname
INTO @typeid,@fullname
WHILE @@FETCH_STATUS=0
Begin
    IF EXISTS(SELECT * FROM atype WHERE LEFT(parid,15)=@typeid)	
    BEGIN
       SELECT @maxleveal=MAX(leveal) FROM atype WHERE LEFT(parid,15)=@typeid
	   SELECT @typeid=typeid,@fullname=fullname FROM atype WHERE LEFT(parid,15)=@typeid and leveal=@maxleveal 	  
	END
    INSERT INTO #BankInfo values(@typeid,@fullname) 
	FETCH NEXT FROM cursorname
	INTO @typeid,@fullname
END
close cursorname
deallocate cursorname
select * from #BankInfo
drop table #BankInfo

GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PosCheckSave]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[PosCheckSave]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：用于pos下载包时检测是否修改了配置
*/
CREATE PROCEDURE PosCheckSave

--@encode$--
AS
SET NOCOUNT ON


IF NOT EXISTS(SELECT 1 FROM PosReDataGlobal WHERE  stypeid='-99999')
	 BEGIN
		 INSERT INTO PosReDataGlobal VALUES(1,'-99999')
	 END
 ELSE
	BEGIN
		IF  EXISTS(SELECT 1 FROM PosReDataGlobal WHERE ifredata=0) 
			BEGIN
				 UPDATE PosReDataGlobal SET ifredata=1,stypeid='-99999'
			END
	 END
IF NOT EXISTS(SELECT 1 FROM PosIsUpdateData WHERE  tbType='sysdata' )
	 BEGIN
		 INSERT INTO PosIsUpdateData VALUES('sysdata',0,1,'-99999')
	 END
 ELSE
	BEGIN
		IF  EXISTS(SELECT 1 FROM PosIsUpdateData WHERE  tbType='sysdata' AND Tid=0 AND ifUpdate=1 AND stypeid='-99999' ) 
			BEGIN
				 UPDATE PosIsUpdateData SET ifUpdate=1,stypeid='-99999',tbType='sysdata',Tid=0
			END
	 END
	 
IF NOT EXISTS(SELECT 1 FROM sysdata where subname='costing' and subvalue='3') 
AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName IN('ifuseproducedate','ifusevaliddate','ifusegoodsnumber') AND Value='1')
BEGIN 
	UPDATE PosInfo SET permitshowbatchno=0
END

IF EXISTS(SELECT 1 FROM sysdata where subname='usebrandartype' and subvalue='1') 
BEGIN 
	UPDATE PosInfo SET permitshowbtype=0
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[PosCxGetBasicData]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[PosCxGetBasicData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE PosCxGetBasicData
    (
      @Barcode VARCHAR(50) ,
      @BaseType INT ,
      @WithColAndSiz INT ,
      @selectstring VARCHAR(100) ,
      @PosUserId VARCHAR(50) ,
      @DefaultBarCode VARCHAR(50)
    )
--@encode$--    
AS 
    DECLARE @MangerId VARCHAR(50)
    DECLARE @Jtypeid VARCHAR(50)
    DECLARE @Branchid VARCHAR(50)
    
    IF @BaseType = '1' 
        GOTO P
    IF @BaseType = '2' 
        GOTO B
    IF @BaseType = '3' 
        GOTO K
    IF @BaseType = '4' 
        GOTO A
    IF @BaseType = '5' 
        GOTO E
    IF @BaseType = '6' 
        GOTO O
        
    SELECT  *
    FROM    Ptype
    
    P:
    SELECT  [name] ,
            typeid AS Typeid ,
            fullname ,
            usercode ,
            Sonnum ,
            deleted as stop
    FROM    FN_GetPowerRangePList(@PosUserId, '')
    WHERE   ( ( fullname LIKE '%' + @selectstring + '%'
                OR usercode LIKE '%' + @selectstring + '%'
              )
              AND sonnum = 0
              AND deleted = 0
              AND typeid <> '00000'
            )
    ORDER BY typeid
    GOTO Success   
     
    B:
    SELECT  Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode
    FROM    FN_GetPowerRangeBCList(@PosUserId, '')
    WHERE   sonnum = 0
            --AND BranchType <> 0
            AND deleted = 0
            AND ( fullname LIKE '%' + @SelectString + '%'
                  OR usercode LIKE '%' + @SelectString + '%'
                )
    ORDER BY typeid
    GOTO Success
    
    K:
    SELECT  typeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode
    FROM    Stock
    WHERE   ( fullname LIKE '%' + @SelectString + '%'
              OR usercode LIKE '%' + @SelectString + '%'
            )
            AND sonnum = 0
            AND deleted = 0
            AND STypeID IN ( SELECT    typeId
                              FROM      FN_GetPowerRangeBCList(@PosUserId, '') )
    GOTO Success

    A:
    SELECT  typeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode
    FROM    Atype
    WHERE   ( fullname LIKE '%' + @SelectString + '%'
              OR usercode LIKE '%' + @SelectString + '%'
            )
            AND sonnum = 0
            AND deleted = 0
            --AND stypeid = ( SELECT CASE BranchID
            --                          WHEN '00001' THEN '0000100001'
            --                          ELSE BranchId
            --                        END AS BranchId
            --                 FROM   Employee
            --                 WHERE  typeid = @PosUserId
            --               )
    GOTO Success
    
    E:  
    SELECT  typeid AS Typeid ,
            fullname ,
            Sonnum ,
            [name] ,
            usercode ,
            CASE Branchid WHEN '00001' THEN '0000100001' ELSE Branchid END AS Branchid
    FROM    FN_GetPowerRangeEList(@PosUserId, '')
    WHERE   ( fullname LIKE '%' + @SelectString + '%'
              OR usercode LIKE '%' + @SelectString + '%'
            )
            AND sonnum = 0
            AND deleted = 0
    GOTO Success
    
    O:
    SELECT  a.PosId AS Typeid ,
            a.fullname ,
            a.Usercode ,
            a.fullname AS [name] ,
            0 AS sonnum ,
            a.etypeid ,
            a.Branchid
    FROM    CommonPosInfo a
    WHERE   a.Deleted <> 1
            AND ( a.fullname LIKE '%' + @SelectString + '%'
                  OR a.usercode LIKE '%' + @SelectString + '%'
                ) 
                
    
    Success:
    RETURN 0
    
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_ApInvoiceReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_ApInvoiceReport]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-03
	描述：付款、收票情况综合查询 
	QP_ApInvoiceReport '00001','1900-01-01','2010-08-03','','0'
*/

CREATE PROCEDURE QP_ApInvoiceReport
(
	@OperatorId			VARCHAR(100),	--操作员ID
	@StartDate			VARCHAR(20),	--开始日期
	@EndDate			VARCHAR(20),	--截止日期
	@BTypeId			VARCHAR(100),	--往来单位ID
	@Chk				VARCHAR(10)		--税率 1.查大于税率0的单据  0.所有单据
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @SonNum 	int,
		@SQL		varchar(8000),
		@BTypeIdMx	varchar(50),
		@Type 		INT
		
SET @Type = 2	--应付	   

SELECT @SonNum = SonNum FROM btype WHERE typeId = @BTypeId AND deleted = 0	

IF @BTypeId = ''
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)
			BEGIN
				IF @Type = 1
					SET @BTypeIdMx = '00001'
				ELSE
					SET @BTypeIdMx = '00002'
			END
		ELSE
			SET @BTypeIdMx = '%'
	END
ELSE
	SET @BTypeIdMx = @BTypeId	

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorID)
INSERT INTO #GetManKTypeId(TypeId)VALUES('')
INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')


CREATE TABLE #Result
(
	BTypeId		VARCHAR(100),
	BillDate	VARCHAR(20),
	IniTotal	 NUMERIC(24, 10) ,
	LeftMoney	 NUMERIC(24, 10) 
)

IF @Type = 2
	INSERT INTO #Result
	SELECT	TypeId,
			'1900-01-01' AS BillDate,
			ApTotal00 AS IniTotal,
			0 AS LeftMoney
	FROM	btype
	WHERE 	deleted = 0
			AND sonnum = 0
			
SET @SQL = 'INSERT INTO #Result
			SELECT	BTypeId, 
					BillDate,
					0 AS IniTotal,'
			IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
				BEGIN
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,85,93,141,155,157,160,167,168,172)	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (36,45,84,148,149)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (4)						THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN(66) 						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '
					ELSE			--分支机构应付查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (34,84,145,36,94,161,170)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00001%''	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)	
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00002%''	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)<0	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)	
											WHEN BillType IN (6,150,151,85,93)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (66)						THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											WHEN BillType IN (4)						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '
	
							
				END
			ELSE	
				BEGIN
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (45,148,149,34,145,36,84,94,161,170)      		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType = 4  											THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (66)										THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '		
					ELSE			--分支机构应付查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172)		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (45,148,149,34,145,36,84,94,161,170)      		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType = 4  											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											WHEN BillType IN(66)										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											ELSE 0
										END 
									) AS LeftMoney '				
				END						
SET @SQL = @SQL + ' 
			FROM 	BillIndex '

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = BillIndex.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') B ON B.TypeId = BillIndex.BTypeId '

IF @MKTypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON BillIndex.KTypeId = K.TypeId'

SET @SQL = @SQL + '
			WHERE	BTypeId LIKE '+char(39)+@BTypeIdMx+'%'+char(39)+'
					AND IfCheck = ''t''
					AND RedWord = 0				
			GROUP BY BTypeId,BillDate 
			UNION ALL
			SELECT	A.BTypeId, 
					B.BillDate,
					0 AS IniTotal,'
				IF @Type = 1	--分支机构应收查询 
					SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN B.BillType IN (116,129)   THEN ISNULL(A.Total,0)
											WHEN B.BillType IN (115,128)   THEN -1*ISNULL(A.Total,0)
											ELSE 0
										END 
									) AS LeftMoney  '
				ELSE			--分支机构应付查询
					SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN B.BillType IN (116,129)   THEN -1*ISNULL(A.Total,0)
											WHEN B.BillType IN (115,128)   THEN ISNULL(A.Total,0)
											ELSE 0
										END 
									) AS LeftMoney  '
SET @SQL = @SQL + '
			FROM 	BillIndex B
					INNER JOIN AdDebtBill A ON B.BillNumberId = B.BillNumberId'

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = B.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') MB ON MB.TypeId = A.BTypeId '

IF @MKTypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON B.KTypeId = K.TypeId'

SET @SQL = @SQL + '
			WHERE	B.BillNumberId = A.BillNumberId
					AND A.BTypeId LIKE '+char(39)+@BTypeIdMx+'%'+char(39)+'
					AND B.IfCheck = ''t''
					AND B.RedWord = 0
			GROUP BY A.BTypeId,B.BillDate
			UNION ALL
			SELECT	B.BTypeId, 
					B.BillDate,
					0 AS IniTotal,'
				IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
					ELSE
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000200001''	THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
				ELSE
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
											WHEN L.ATypeId = ''0000200001'' THEN -1*ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
					ELSE
						SET @SQL = @SQL + '
								SUM(

										CASE
											WHEN L.ATypeId = ''0000100005''	THEN -1*ISNULL(L.Total,0)
											WHEN L.ATypeId = ''0000200001'' THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '						
							
	SET @SQL = @SQL + '		
			FROM	BillIndex B
					INNER JOIN ListTable L ON (B.BillNumberId = L.BillNumberId AND L.ATypeId IN (''0000100005'',''0000200001'')) '

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = B.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') MB ON MB.TypeId = L.BTypeId '

IF @MKTypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON B.KTypeId = K.TypeId'

SET @SQL = @SQL + '
			WHERE	B.BillType = 159
			GROUP BY B.BTypeId,B.BillDate	'

--PRINT(@SQL)
EXEC(@SQL)

--运算数据
SET @SQL = '
		SELECT	B.TypeId,
				B.SonNum,
				B.UserCode,
				B.FullName,
				SUM(ISNULL(M.IniTotal,0)) AS qcye,
				SUM(ISNULL(M.IniTotal,0))+SUM(ISNULL(M.LeftMoney,0)) AS qmye		
		FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B
		LEFT JOIN (
					SELECT	BTypeId,
							SUM(IniTotal) AS IniTotal,
							SUM(LeftMoney) AS LeftMoney
					FROM	#Result
					GROUP BY BTypeId									
				)M ON LEFT(M.BTypeId,LEN(B.TypeId)) = B.TypeId
		WHERE	B.TypeId <> ''00000'''
		
IF @BTypeId = ''
	SET @SQL = @SQL + ' AND B.ParId = ''00000'''
ELSE IF @SonNum = 0
	SET @SQL = @SQL + ' AND B.TypeId = '+CHAR(39)+@BTypeId+CHAR(39)
ELSE	
	SET @SQL = @SQL + ' AND B.ParId = '+CHAR(39)+@BTypeId+CHAR(39)
		
SET @SQL = @SQL + '		
		GROUP BY
				B.TypeId,
				B.SonNum,
				B.UserCode,
				B.FullName
		ORDER BY B.UserCode'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Result,#GetManKTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_AutoProceModelCaoGao]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_AutoProceModelCaoGao]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-05
	描述：生产模板从单据生成草稿
*/
CREATE  PROCEDURE Qp_AutoProceModelCaoGao
(
	@OperatorId	varchar(200),
	@pName		varchar(1000)='',
	@ptypeid	varchar(100),	
	@ktypeid	varchar(200),
	@ktypeid1	varchar(200),
	@ptypeid1	varchar(8000),
	@strqty1	varchar(8000),
	@ptypeid2	varchar(8000),
	@strqty2	varchar(8000),
	@Qty		 NUMERIC(24, 10) ,
	@ntype		varchar(10),
	@outBcode	varchar(400) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -5
	END
END  


DECLARE
	@NowDate	DATETIME

SELECT @NowDate=GETDATE()

-- ********	判断是否试用版 - END	********


DECLARE @ProduceModelName	varchar(1000),
		@ProduceComment		varchar(400),
		@SerialSQL			varchar(8000)
		
		
if EXISTS(SELECT  TOP 1 1 FROM ptype WHERE typeId=@ptypeid AND deleted=1)
BEGIN
	RAISERROR ('生成的商品已经被停用,请重新选择!',16, 1)
	return 		
END

--先把数据分割出来
CREATE TABLE #MxBill
(
	PTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) 
)

CREATE TABLE #TmpPType
(
	nId			int identity(1,1),
	PTypeId		varchar(100)
)

CREATE TABLE #TmpQty
(
	nId			int identity(1,1),
	Qty			 NUMERIC(24, 10) 
)


INSERT INTO #TmpPType SELECT * FROM F_Split(@PTypeId1,',')
INSERT INTO #TmpQty   SELECT * FROM F_Split(@StrQty1,',')
INSERT INTO #TmpPType SELECT * FROM F_Split(@PTypeId2,',')
INSERT INTO #TmpQty   SELECT * FROM F_Split(@StrQty2,',')

DECLARE
	@STypeID	VARCHAR(50)

INSERT INTO #MxBill
(
	PTypeId,
	Qty
)
SELECT	B.PTypeId,
		B.Qty AS Qty
FROM	(
		SELECT	P.PTypeId,
				Q.Qty
		FROM	#TmpPType P,
				#TmpQty Q
		WHERE	P.nId = Q.nId
)B

--判断两个仓库是否属于同个分支机构 WANG WEI 2010-1-25 BEGIN
DECLARE @k1 VARCHAR(100)
DECLARE @k2 VARCHAR(100)

SELECT @k1=STypeID FROM stock  WHERE typeId=@ktypeid
SELECT @k2=STypeID FROM stock  WHERE typeId=@ktypeid1
IF @k1<>@k2 
BEGIN
	RAISERROR ('出库与入库必须属于同一分支机构',16, 1)
	return 
END
-- /*END*/

--生成单据编号
DECLARE @MONTH 				varchar(50),
		@DAY 				varchar(50),
		@BillCodeConfig		varchar(10),
		@bCode				varchar(300),
		@Re					int,
		@Tax				 NUMERIC(24, 10) ,
		@period				int,
		@DTypeId			varchar(200),
		@nBillId			numeric(18,0),
		@recPrice			 NUMERIC(24, 10) ,
		@preprice			 NUMERIC(24, 10) ,
		@Explain			varchar(400),
		@cefullname			VARCHAR(500)='',
		@cdfullname			VARCHAR(500)=''

SET @Tax = 0
SET @recPrice = 0
SET @preprice = 0

IF @ntype = '1'
	SET @Explain = '由生产模板【'+@pName+'】生成的组装单'
ELSE
	SET @Explain = '由生产模板【'+@pName+'】生成的拆装单'

IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '1')
	SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'

SELECT @period = period FROM MonthProc WHERE MonthNo = '本期'

SELECT @DTypeId = D.TypeId FROM Department D,Employee E WHERE E.Department = D.FullName AND E.TypeId = @OperatorId

SET @MONTH = month(getdate())
SET @DAY = day(getdate())


SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = 16) AND @BillCodeConfig = '1'
	BEGIN
		SELECT @MONTH = ''
		SELECT @DAY = FullName FROM Stock WHERE TypeID = @ktypeid
		SELECT @cefullname = E.FUllname FROM Employee E WHERE E.TypeId = @OperatorId
		SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @DTypeId
	END

EXEC @Re=Gp_GetBillCode 16, @MONTH,@DAY,'CZ',@NowDate,@k1,@bCode OUTPUT,@cdfullname,@cefullname

IF @Re <> 0
	RETURN -2
	
SELECT @STypeID=STypeID
FROM STOCK
WHERE typeId=@ktypeid	

DECLARE @cid INT --本位币ID
DECLARE @rate INT --本位币汇率
DECLARE @UnitRate  NUMERIC(24, 10)  --浮动换算率
DECLARE @UnitRate1  NUMERIC(24, 10)  --浮动换算率
DECLARE	@MunitID INT --大单位ID
DECLARE	@MunitID1 INT --大单位ID
DECLARE @MUnitrate  NUMERIC(24, 10)  --大单位换算率
DECLARE @MUnitrate1  NUMERIC(24, 10)  --大单位换算率
SELECT @cid=CId,@rate=Rate FROM Ac_Currency WHERE Sysrow=1
SELECT @UnitRate=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.AssistantUnitId =b.UnitsId WHERE a.typeID=@ptypeid
--SELECT @UnitRate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.AssistantUnitId =b.UnitsId WHERE a.typeID=@ptypeid1
SELECT @MunitID=baseUnitId FROM Ptype WHERE typeId = @ptypeid
SELECT @MUnitrate=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.baseUnitId =b.UnitsId WHERE a.typeID=@ptypeid

--写入单据主表
INSERT INTO BillIndex (AlertDay,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,Comment,Stypeid,CID,Rate)
VALUES(9999,CONVERT(varchar(10),GetDate(),120),@bCode,16,'','','','',@ktypeid,@ktypeid1,'f',@OperatorId,0,0,@Qty,@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@ProduceComment,@STypeID,@cid,@rate)

IF @@ROWCOUNT = 0
	RETURN -3
ELSE
	SET @nBillId = SCOPE_IDENTITY();

--插入明细
DECLARE @MxPTypeId		varchar(200),
		@MxQty			 NUMERIC(24, 10) ,
		@nid			 NUMERIC(24, 10) 

IF @nType = '1'	--组装单
	BEGIN
		--写入库商品明细
		IF EXISTS(SELECT TOP 1 1 FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId1)
			SELECT @recPrice = Price FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId1 ORDER BY GoodsOrder DESC
		ELSE
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM PType WHERE TypeId = @PTypeId AND recPrice=0)
					SELECT @recPrice = PreBuyPrice5 FROM PType_Price WHERE PTypeId = @PTypeId
				ELSE
					SELECT @recPrice = recPrice FROM PType WHERE TypeId = @PTypeId
			END

		INSERT INTO DisassembleBill(BillNumberId,PTypeId,Qty,CostPrice,Total,InOrOut,OutFactoryDate,JobNumber,Comment,Serial,KTypeId,STypeID,UnitRate,Nqty,MUnitId,MUnitRate,MQty,CurMSalePrice)
		VALUES(@nBillId,@PTypeId,@Qty,@recPrice,dbo.F_RoundData(@recPrice*@Qty,'total'),'I',GetDate(),'','','',@ktypeid1,@STypeID,@UnitRate,Case @UnitRate WHEN 0 THEN 0 ELSE dbo.F_RoundData(@qty/@UnitRate,'qty') END,@MunitID,@MUnitrate,@Qty,@recPrice)
		
		UPDATE dbo.DisassembleBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
		--写入出库商品
		DECLARE ZcCursor CURSOR FOR
			SELECT PTypeId,Qty FROM #MxBill

		OPEN ZcCursor

		FETCH NEXT FROM ZcCursor INTO @MxPTypeId,@MxQty
	
		WHILE @@FETCH_STATUS = 0
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM GoodsStocks WHERE PTypeId = @MxPTypeId AND KTypeId = @KTypeId)
					SELECT @PrePrice = Price FROM GoodsStocks WHERE PTypeId = @MxPTypeId AND KTypeId = @KTypeId ORDER BY GoodsOrder DESC
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 1 FROM PType WHERE TypeId = @MxPTypeId AND recprice=0)
							SELECT @PrePrice = PreBuyPrice5 FROM PType_Price WHERE PTypeId = @MxPTypeId
						ELSE
							SELECT @PrePrice = recprice FROM PType WHERE TypeId = @MxPTypeId
					END
				
				SELECT @UnitRate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.AssistantUnitId =b.UnitsId WHERE a.typeID=@MxPTypeId
				SELECT @MunitID1=baseUnitId FROM Ptype WHERE typeId = @MxPTypeId
				SELECT @MUnitrate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.baseUnitId =b.UnitsId WHERE a.typeID=@MxPTypeId
				
				INSERT INTO DisassembleBill(BillNumberId,PTypeId,Qty,CostPrice,Total,InOrOut,OutFactoryDate,JobNumber,Comment,Serial,KTypeId,STypeID,UnitRate,Nqty,MUnitId,MUnitRate,MQty,CurMSalePrice)
				VALUES(@nBillId,@MxPTypeId,dbo.F_RoundData(@Qty*@MxQty,'qty'),@PrePrice,dbo.F_RoundData(@PrePrice*@Qty*@MxQty,'total'),'O',GetDate(),'','','',@ktypeid,@STypeID,@UnitRate1,Case @UnitRate1 WHEN 0 THEN 0 ELSE dbo.F_RoundData((@Qty*@MxQty)/@UnitRate1,'qty') END,@MunitID1,@MUnitrate1,dbo.F_RoundData(@Qty*@MxQty,'qty'),@PrePrice)				
				UPDATE DisassembleBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
				FETCH NEXT FROM ZcCursor INTO @MxPTypeId,@MxQty
			END

		CLOSE ZcCursor
		DEALLOCATE ZcCursor

		IF NOT EXISTS(SELECT TOP 1 1 FROM DisassembleBill WHERE BillNumberId = @nBillId AND InOrOut='I')
			RETURN -6

		IF NOT EXISTS(SELECT TOP 1 1 FROM DisassembleBill WHERE BillNumberId = @nBillId AND InOrOut='O')
			RETURN -6
	END
ELSE
	BEGIN
		--写入库商品明细
		IF EXISTS(SELECT TOP 1 1 FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId)
			SELECT @recPrice = Price FROM GoodsStocks WHERE PTypeId = @PTypeId AND KTypeId = @KTypeId ORDER BY GoodsOrder DESC
		ELSE
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM PType WHERE TypeId = @PTypeId AND recPrice=0)
					SELECT @recPrice = PreBuyPrice5 FROM PType_Price WHERE PTypeId = @PTypeId
				ELSE
					SELECT @recPrice = recPrice FROM PType WHERE TypeId = @PTypeId
			END

		INSERT INTO DisassembleBill(BillNumberId,PTypeId,Qty,CostPrice,Total,InOrOut,OutFactoryDate,JobNumber,Comment,Serial,KTypeId,STypeID,UnitRate,Nqty,MUnitId,MUnitRate,MQty,CurMSalePrice)
		VALUES(@nBillId,@PTypeId,@Qty,@recPrice,dbo.F_RoundData(@recPrice*@Qty,'total'),'O',GetDate(),'','','',@ktypeid,@STypeID,@UnitRate,Case @UnitRate WHEN 0 THEN 0 ELSE dbo.F_RoundData(@qty/@UnitRate,'qty') END,@MunitID,@MUnitrate,@Qty,@recPrice)
		UPDATE DisassembleBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
		--写入出库商品
		DECLARE CzCursor CURSOR FOR
			SELECT PTypeId,Qty FROM #MxBill

		OPEN CzCursor

		FETCH NEXT FROM CzCursor INTO @MxPTypeId,@MxQty
	
		WHILE @@FETCH_STATUS = 0
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM GoodsStocks WHERE PTypeId = @MxPTypeId AND KTypeId = @KTypeId1)
					SELECT @PrePrice = Price FROM GoodsStocks WHERE PTypeId = @MxPTypeId AND KTypeId = @KTypeId1 ORDER BY GoodsOrder DESC
				ELSE
					BEGIN
						IF EXISTS(SELECT TOP 1 1 FROM PType WHERE TypeId = @MxPTypeId AND recprice=0)
							SELECT @PrePrice = PreBuyPrice5 FROM PType_Price WHERE PTypeId = @MxPTypeId
						ELSE
							SELECT @PrePrice = recprice FROM PType WHERE TypeId = @MxPTypeId
					END

				SELECT @UnitRate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.AssistantUnitId =b.UnitsId WHERE a.typeID=@MxPTypeId
				SELECT @MunitID1=baseUnitId FROM Ptype WHERE typeId = @MxPTypeId
				SELECT @MUnitrate1=ISNULL(b.Rate,0) FROM PType a LEFT JOIN PType_Units_Ext b ON a.typeID=b.ptypeId AND a.baseUnitId =b.UnitsId WHERE a.typeID=@MxPTypeId
				
				INSERT INTO DisassembleBill(BillNumberId,PTypeId,Qty,CostPrice,Total,InOrOut,OutFactoryDate,JobNumber,Comment,Serial,KTypeId,STypeID,UnitRate,Nqty,MUnitId,MUnitRate,MQty,CurMSalePrice)
				VALUES(@nBillId,@MxPTypeId,dbo.F_RoundData(@Qty*@MxQty,'qty'),@PrePrice,dbo.F_RoundData(@PrePrice*@Qty*@MxQty,'total'),'I',GetDate(),'','','',@ktypeid1,@STypeID,@UnitRate1,Case @UnitRate1 WHEN 0 THEN 0 ELSE dbo.F_RoundData((@Qty*@MxQty)/@UnitRate1,'qty') END,@MunitID1,@MUnitrate1,dbo.F_RoundData(@Qty*@MxQty,'qty'),@PrePrice)				
				UPDATE DisassembleBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
				FETCH NEXT FROM CzCursor INTO @MxPTypeId,@MxQty
			END

		CLOSE CzCursor
		DEALLOCATE CzCursor

		IF NOT EXISTS(SELECT TOP 1 1 FROM DisassembleBill WHERE BillNumberId = @nBillId AND InOrOut='I')
			RETURN -6

		IF NOT EXISTS(SELECT TOP 1 1 FROM DisassembleBill WHERE BillNumberId = @nBillId AND InOrOut='O')
			RETURN -6		
	END

--处理货位
UPDATE 	DisassembleBill
SET		CargoID = ISNULL((SELECT TOP 1 CargoID FROM CargoType WHERE PTypeId = DisassembleBill.PTypeId AND KTypeId = DisassembleBill.KTypeId AND CargoType.IsDefault = 1),'')
WHERE	BillNumberId = @nBillId	

DECLARE @costing INT 
SELECT @costing=SubValue FROM dbo.sysdata WHERE SubName='costing'
IF @costing=3--手工指定时处理成本单价
 BEGIN
  UPDATE DisassembleBill SET GoodsCostPrice=-1 WHERE BillNumberId=@nBillId
 
 END

SET @outBcode = @bCode	

IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed	@nBillId,@NowDate,16,@bCode
END

IF @@error<>0 
	BEGIN
		RETURN -2
	END 



-- 自动生成的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,16
RETURN 0

DROP TABLE #MxBill,#TmpPType,#TmpQty

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_BatchModifyRepairItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_BatchModifyRepairItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-14
	描述：批量修改维修项目的价格信息
*/
CREATE PROCEDURE QP_BatchModifyRepairItems
(
    @TypeId			varchar(100),
	@UserCode		varchar(300),
	@FullName		varchar(300),
	@Xmlx			varchar(200),
	@Cx				varchar(200),
	@Xz				varchar(100),
	@Yz				varchar(100),
	@Cz				varchar(100),
	@Ysz			varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Result
(
	TypeId				varchar(100)
)

DECLARE @SQL				varchar(8000),
		@Xmlx_C				varchar(20),
		@Cx_C				varchar(100),
		@Xz_Name			varchar(100),
		@Yz_Name			varchar(100),
		@Cz_Name			varchar(10)		

--新价格
IF @Xz = 1
	SET @Xz_Name = 'StandardManHour'
ELSE IF @Xz = 2
	SET @Xz_Name = 'CheckHour'
ELSE IF @Xz = 3
	SET @Xz_Name = 'StandardPrice'
ELSE IF @Xz = 4
	SET @Xz_Name = 'TopPrice'
ELSE IF @Xz = 5
	SET @Xz_Name = 'LowPrice'

--原价格
IF @Yz = 1
	SET @Yz_Name = 'StandardManHour'
ELSE IF @Yz = 2
	SET @Yz_Name = 'CheckHour'
ELSE IF @Yz = 3
	SET @Yz_Name = 'StandardPrice'
ELSE IF @Yz = 4
	SET @Yz_Name = 'TopPrice'
ELSE IF @Yz = 5
	SET @Yz_Name = 'LowPrice'

--操作类型
IF @Cz = 1
	SET @Cz_Name = '+'
ELSE IF @Cz = 2
	SET @Cz_Name = '-'
ELSE IF @Cz = 3
	SET @Cz_Name = '*'
ELSE IF @Cz = 4
	SET @Cz_Name = '/'

--项目类型
IF @Xmlx = '3'
	SET @Xmlx_C = '%'
ELSE
	SET @Xmlx_C = @Xmlx

--车型
IF @Cx = ''
	SET @Cx_C = '%'
ELSE
	SET @Cx_C = @Cx

INSERT INTO #Result
SELECT 	TypeId
FROM 	QP_RepairItems 
WHERE 	
        TypeId LIKE @TypeId + '%' 
        AND UserCode LIKE '%'+@UserCode+'%' 
		AND FullName LIKE '%'+@FullName + '%' 
		AND TypeId <> '00000' 
		AND SonNum = 0
		AND RepairAutoTypeId LIKE @Cx_C 
		AND ItemType LIKE @Xmlx_C

BEGIN TRAN UpdateProc

SET @SQL = '
	UPDATE	QP_RepairItems
	SET		'+@Xz_Name+' = CAST('+@Yz_Name+@Cz_Name+@Ysz+' AS  NUMERIC(24, 10) )
	WHERE	TypeId IN (SELECT TypeId FROM #Result)'

--PRINT(@SQL)
EXEC(@SQL)

IF @@ERROR<>0
	BEGIN
		ROLLBACK TRAN UpdateProc
		RETURN -1
	END

--只有在进行减法运算的时候才可能为负数
IF @Cz = 2
	BEGIN
		IF @Xz = 1 AND EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE StandardManHour<0)
				BEGIN
					ROLLBACK TRAN UpdateProc
					RETURN -2
				END

		IF @Xz = 2 AND EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE CheckHour<0)
				BEGIN
					ROLLBACK TRAN UpdateProc
					RETURN -3
				END

		IF @Xz = 3 AND EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE StandardPrice<0)
				BEGIN
					ROLLBACK TRAN UpdateProc
					RETURN -4
				END
		
		IF @Xz = 4 AND EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE TopPrice<0)
				BEGIN
					ROLLBACK TRAN UpdateProc
					RETURN -5
				END

		IF @Xz = 5 AND EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE LowPrice<0)
				BEGIN
					ROLLBACK TRAN UpdateProc
					RETURN -6
				END
	END

COMMIT TRAN UpdateProc

RETURN 0

DROP TABLE #Result


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_CalSaleCostInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_CalSaleCostInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




/*
	作者：谢吉康
	日期：2010-08-12
	描述：计算销售单上的库存成本
	EXEC Qp_CalSaleCostInfo '00001','00329,00332','1.5523,0'
*/

CREATE  PROCEDURE Qp_CalSaleCostInfo
(
	@OperatorId		VARCHAR(100),
	@PTypeId		VARCHAR(8000),
	@KTypeId		VARCHAR(8000),
	@strQty			VARCHAR(8000)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
CREATE TABLE #PType
(
	nId		INT IDENTITY(1,1),
	PTypeId	VARCHAR(100)
)

INSERT INTO #PType SELECT * FROM DBO.f_split(@PTypeId,',')

CREATE TABLE #KType
(
	nId		INT IDENTITY(1,1),
	KTypeId	VARCHAR(100)
)
INSERT INTO #KType SELECT * FROM DBO.f_split(@KTypeId,',')

CREATE TABLE #Qty
(
	nId		INT IDENTITY(1,1),
	Qty		 NUMERIC(24, 10) 
)

INSERT INTO #Qty SELECT * FROM dbo.F_SPLIT(@strQty,',')

CREATE TABLE #Tmp
(
	PTypeId		VARCHAR(100),
	KTypeId		VARCHAR(100),
	Qty			 NUMERIC(24, 10) 
)

INSERT INTO #Tmp
SELECT	B.PTypeId,
		B.KTypeId,
		ISNULL(SUM(B.Qty),0) AS Qty
FROM	(		
			SELECT	P.PTypeId,
					K.KTypeId,
					ISNULL(Q.Qty,0) AS Qty
			FROM	#PType P,
					#KType K,
					#Qty Q	
			WHERE	P.nId = Q.nId
					AND P.nId = K.nId 
		)B 
GROUP BY B.PTypeId,B.KTypeId

CREATE TABLE #GoodsStocks
(
	PTypeId		VARCHAR(100),
	KTypeId		VARCHAR(100),
	Price		VARCHAR(100)
)

INSERT INTO #GoodsStocks
SELECT	PTypeId,
		KTypeId,
		CAST(
			CASE
				WHEN ISNULL(SUM(Qty),0) = 0 THEN 0
				ELSE ISNULL(SUM(Total),0) / ISNULL(SUM(Qty),0)
			END
		AS VARCHAR(100)) AS Price
FROM	GoodsStocks
GROUP BY PTypeId,KTypeId

CREATE TABLE #Result
(
	PTypeId		VARCHAR(100),
	Qty			 NUMERIC(24, 10) ,
	Price		VARCHAR(100)
)

INSERT INTO #Result
SELECT	T.PTypeId,
		ISNULL(SUM(T.Qty),0) AS Qty,
		ISNULL(G.Price,0) AS Price
FROM 	#Tmp T,
		#GoodsStocks G
WHERE	G.PtypeId = T.PTypeId
		AND G.KTypeId = T.KTypeId
GROUP BY T.PTypeId,G.Price

SELECT CAST(SUM(ISNULL(R.Qty,0)*ISNULL(R.Price,0)) AS VARCHAR(100)) AS Total FROM #Result R

DROP TABLE #PType,#Qty,#Result,#Tmp,#KType,#GoodsStocks




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Clear_PosData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Clear_PosData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：清除pos中的相关信息
	返回结果：
	作    者：杨鑫
	创建时间：2017-09-06
	修改历史：
	
*/
CREATE   PROCEDURE QP_Clear_PosData 

AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

----------------------------------------------------------这里直接清除pos寄存小票主表和明细表 start------------------------------------------------------------
TRUNCATE TABLE dbo.DepositBillIndex
TRUNCATE TABLE dbo.DepositBillDetail
----------------------------------------------------------清除pos寄存小票主表和明细表   end------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_CreateBarcode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_CreateBarcode]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2012-01-05
	描述：批量全部编号生成条码
*/
CREATE PROCEDURE [dbo].[QP_CreateBarcode]
(
    @OperatorID  		varchar(50),
    @ParID              VARCHAR(50) = ''
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Result
(
	TypeId				varchar(100)
)
CREATE TABLE #Ptype (TypeID varchar(200))
--商品
INSERT INTO #Ptype select typeid from F_GetAllManagerBaseANDFatherTypeId('',1,@OperatorID,1)

DECLARE @InSQL	varchar(5000)
SET @InSQL = 'INSERT INTO #Result
				SELECT 	Ptype.TypeId
				FROM 	Ptype
				INNER JOIN  #Ptype p ON  p.typeid = Ptype.typeid
				WHERE   Ptype.IfUseEntryCode = 1
					   AND Ptype.UserCode NOT IN (SELECT ISNULL(EntryCode,'''') FROM PType_Units_Ext)
			 '
			 
IF @ParID<>'00000'
SET @InSQL = @InSQL + 'AND Ptype.typeid like '''+@ParID +'%'+''''
--PRINT(@InSQL)
EXEC(@InSQL)

DECLARE @SQL				varchar(5000)
 
BEGIN TRAN UpdateProc

--SET @SQL = '
--    UPDATE dbo.ptype SET EntryCode=UserCode
--	WHERE	TypeId IN (SELECT TypeId FROM #Result)'

	 --多条码里有与商品编码一样的条码的商品
     SELECT typeidtable.typeId
     INTO   #SameEntryCodePtype
     FROM   ( SELECT DISTINCT
                        p.typeId
              FROM      dbo.PType_EntryCode_Ext pe
                        INNER JOIN dbo.ptype p ON p.typeId = pe.Ptypeid
              WHERE     p.typeId IN ( SELECT    TypeId
                                      FROM      #Result )
                        AND p.UserCode = pe.EntryCode
            ) AS typeidtable;
	  --商品多条码里，商品存在默认条码并且商品条数小于50条
	  SELECT    Ptypeid
	  INTO      #IsExistDefaultEntryCode
	  FROM      ( SELECT    Ptypeid
				  FROM      dbo.PType_EntryCode_Ext
				  WHERE     Ptypeid IN ( SELECT TypeId
										 FROM   #Result )
							AND IsDefaultEntryCode = 1
				  GROUP BY  Ptypeid
				  HAVING    COUNT(*) >= 1
				  INTERSECT
				  SELECT    Ptypeid
				  FROM      dbo.PType_EntryCode_Ext
				  WHERE     Ptypeid IN ( SELECT TypeId
										 FROM   #Result )
				  GROUP BY  Ptypeid
				  HAVING    COUNT(*) < 50
				  EXCEPT
				  SELECT typeId FROM #SameEntryCodePtype
				) AS ptypeidTable;
		--商品多条码里不存在默认条码
		SELECT    Ptypeid
		INTO	  #NotExistDefaultEntryCode
		FROM      ( SELECT    Ptypeid
					FROM      dbo.PType_EntryCode_Ext
					WHERE     Ptypeid IN ( SELECT TypeId
											 FROM   #Result )
							  AND IsDefaultEntryCode = 1
					GROUP BY  Ptypeid
					HAVING    COUNT(*) = 0
					EXCEPT
					SELECT typeId FROM #SameEntryCodePtype
				   ) AS ptypeidTable;
		INSERT INTO dbo.PType_EntryCode_Ext
		        ( Ptypeid ,
		          EntryCode ,
		          IsDefaultEntryCode
		        )
		SELECT d.Ptypeid,UserCode,0 FROM ptype INNER JOIN #IsExistDefaultEntryCode d ON ptype.typeId = d.Ptypeid
		UNION ALL
		SELECT d.Ptypeid,UserCode,1 FROM dbo.ptype INNER JOIN #NotExistDefaultEntryCode d ON ptype.typeId = d.Ptypeid
		
		CREATE TABLE #table
		(
			id INT IDENTITY(1,1),
			ptypeid VARCHAR(50)
		)
		INSERT INTO #table(ptypeid )
		SELECT typeId  FROM dbo.ptype

		DECLARE @count INT ,@i int =1,@ptypeid VARCHAR(50)
		SELECT @count = COUNT(*) FROM dbo.ptype
		WHILE(@i<=@count)
		BEGIN
			SELECT @ptypeid = ptypeid FROM #table WHERE id = @i
			EXEC FillPtypeMultibarcode @ptypeid 
			SELECT @i=@i+1
		END 
--PRINT(@SQL)

--EXEC(@SQL)

IF @@ERROR<>0
	BEGIN
		ROLLBACK TRAN UpdateProc
		RETURN -1
	END
	
EXEC Gp_DataSaveForPosDown '-99999','ptype','0'



COMMIT TRAN UpdateProc

RETURN 0

DROP TABLE #Result




GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealCarriageUnit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].QP_DealCarriageUnit
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：蒋奎
	日期：2015-08-27
	描述：处理常用承运单位
*/
CREATE PROCEDURE QP_DealCarriageUnit
(
	@ID			varchar(100),
	@UserCode	varchar(200),
	@fullname	varchar(400),
	@opType		varchar(30)
)
--@encode$--
AS
SET NOCOUNT ON

IF @opType = 'a' 		--新增
BEGIN
		 
		IF EXISTS(SELECT TOP 1 1 FROM CarriageUnit WHERE UserCode = @UserCode)
		BEGIN
			RAISERROR('已经存在编号(%s),不能重复,请重新输入一个新编号',16,1,@UserCode)
			RETURN
		END
		
		INSERT INTO CarriageUnit
		(
			UserCode,
			fullname
		)VALUES(
			@UserCode,
			@fullname
		)

END
ELSE IF @opType = 'm' 	--修改
BEGIN
		
	IF EXISTS(SELECT TOP 1 1 FROM CarriageUnit WHERE UserCode = @UserCode AND [ID]<>@ID)
	BEGIN
			RAISERROR('已经存在编号(%s),不能重复,请重新输入一个新编号',16,1,@UserCode)
			RETURN
	END
	
	UPDATE	CarriageUnit
	SET		UserCode 	= @UserCode,
			fullname	= @fullname
	WHERE	[ID] 		= @ID
		
			
			
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealChargingStandards]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_DealChargingStandards]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-16
	描述：处理收费标准定义
*/
CREATE PROCEDURE QP_DealChargingStandards
(
	@ID			varchar(100),
	@FullName	varchar(200),
	@Gsfl		varchar(30),
	@nType		varchar(10),
	@pycode     varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

IF @nType = 'a' 		--新增
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_ChargingStandards WHERE FullName = @FullName)
			RETURN -1

		INSERT INTO QP_ChargingStandards
		(
			FullName,
			ManHourRate,
			IfDefault,
			PYCode
			
		)VALUES(
			@FullName,
			@Gsfl,
			0,
			@pycode 
		)

		IF @@ROWCOUNT = 0
			RETURN -2		
	END
ELSE IF @nType = 'm' 	--修改
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_ChargingStandards WHERE FullName = @FullName AND [ID]<>@ID)
			RETURN -1		

		UPDATE	QP_ChargingStandards
		SET		FullName 	= @FullName,
				ManHourRate = @Gsfl,
				PYCode =@pycode 
		WHERE	[ID] 		= @ID

		IF @@ROWCOUNT = 0
			RETURN -2
	END
ELSE IF @nType = 'd'	--删除
	BEGIN		
		--判断是否在维修车辆信息中使用
		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoInfo WHERE ChargingStandardsID = @ID)
			RETURN -1

		--判断是否在维修估价单、快修单中使用
		IF EXISTS(SELECT TOP 1 1 FROM Billindex_CarRepair WHERE InPriceType = @ID)
			RETURN -1 

		DELETE FROM QP_ChargingStandards WHERE [ID] = @ID

		IF @@ROWCOUNT = 0
			RETURN -2
	END
ELSE IF @nType = 's'	--设置默认收费
	BEGIN
		UPDATE 	QP_ChargingStandards
		SET		IfDefault = 1
		WHERE	[ID] = @ID

		IF @@ROWCOUNT = 0
			RETURN -1
		ELSE
			UPDATE 	QP_ChargingStandards
			SET		IfDefault = 0
			WHERE 	[ID] <> @ID								
	END

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealExpAndComment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_DealExpAndComment]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-09-20
	描述：处理常用摘要
*/
CREATE PROCEDURE QP_DealExpAndComment
(
	@ID			varchar(100),
	@UserCode	varchar(200),
	@Content	varchar(400),
	@opType		varchar(30),
	@nType		varchar(10)
)
--@encode$--
AS
SET NOCOUNT ON

IF @opType = 'a' 		--新增
	BEGIN
		IF @nType = 'exp'
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM OftenExplain WHERE UserCode = @UserCode)
					RETURN -1
		
				INSERT INTO OftenExplain
				(
					UserCode,
					Content
				)VALUES(
					@UserCode,
					@Content
				)
		
				IF @@ROWCOUNT = 0
					RETURN -2		
			END
		ELSE
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM OftenComment WHERE UserCode = @UserCode)
					RETURN -1
		
				INSERT INTO OftenComment
				(
					UserCode,
					Content
				)VALUES(
					@UserCode,
					@Content
				)
		
				IF @@ROWCOUNT = 0
					RETURN -2	
			END
	END
ELSE IF @opType = 'm' 	--修改
	BEGIN
		IF @nType = 'exp'
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM OftenExplain WHERE UserCode = @UserCode AND [ID]<>@ID)
					RETURN -1		
		
				UPDATE	OftenExplain
				SET		UserCode 	= @UserCode,
						Content		= @Content
				WHERE	[ID] 		= @ID
		
				IF @@ROWCOUNT = 0
					RETURN -2
			END
		ELSE
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM OftenComment WHERE UserCode = @UserCode AND [ID]<>@ID)
					RETURN -1		
		
				UPDATE	OftenComment
				SET		UserCode 	= @UserCode,
						Content		= @Content
				WHERE	[ID] 		= @ID
		
				IF @@ROWCOUNT = 0
					RETURN -2
			END
	END

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_DealMulStockConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_DealMulStockConfig]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-12
	描述：多仓库配置算法保存
*/

CREATE PROCEDURE Qp_DealMulStockConfig
(
	@BillTypes	VARCHAR(8000)
)
--@encode$--
AS
SET NOCOUNT ON

UPDATE 	Qp_MulStockConfig
SET		IsChecked = 1
WHERE	BillType IN (SELECT * FROM dbo.f_split(@BillTypes,','))

UPDATE 	Qp_MulStockConfig
SET		IsChecked = 0
WHERE	BillType NOT IN (SELECT * FROM dbo.f_split(@BillTypes,','))

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealOperationSort]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_DealOperationSort]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2010-07-19
	描述：处理业务类别
*/
CREATE PROCEDURE QP_DealOperationSort
(
	@ID			varchar(100),
	@FullName	varchar(200),
	@nType		varchar(10),
	@pycode     varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

IF @nType = 'a' 		--新增
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_OperationSort WHERE FullName = @FullName)
			RETURN -1

		INSERT INTO QP_OperationSort
		(
			FullName,
			pycode
		)VALUES(
			@FullName,
			@pycode 
		)

		IF @@ROWCOUNT = 0
			RETURN -2		
	END
ELSE IF @nType = 'm' 	--修改
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_OperationSort WHERE FullName = @FullName AND [ID]<>@ID)
			RETURN -1		

		UPDATE	QP_OperationSort
		SET		FullName 	= @FullName,
		        pycode      = @pycode 
		WHERE	[ID] 		= @ID

		IF @@ROWCOUNT = 0
			RETURN -2
	END
ELSE IF @nType = 'd'	--删除
	BEGIN	
		DELETE FROM QP_OperationSort WHERE [ID] = @ID

		IF @@ROWCOUNT = 0
			RETURN -2
	END
/*
ELSE IF @nType='v'
	BEGIN
		SELECT * FROM QP_OperationSort WHERE FullName LIKE '%'+@FullName+'%'
	END
*/


RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealPTypeCargoSpace]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_DealPTypeCargoSpace]
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealRepairAutoInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_DealRepairAutoInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-19
	描述：处理维修车辆信息档案
*/
CREATE PROCEDURE QP_DealRepairAutoInfo
(
	@TypeId						varchar(100),	--基本信息ID
	@PlateNumber				varchar(300),
	@EngineNumber				varchar(300),
	@RepairAutoTypeID			varchar(300),
	@FrameNumber				varchar(300),
	@TransmissionNumber			varchar(300),
	@VIN						varchar(300),
	@Color						varchar(300),
	@RecordDate					varchar(300),
	@ForceMaintainDate			varchar(300),
	@ForceMaintainMileage		varchar(300),
	@FirstMaintainDate			varchar(300),
	@FirstMaintainMileage		varchar(300),
	@Comment					varchar(300),
	@LeaveFactoryNum			varchar(300),
	@LeaveFactoryDate			varchar(300),
	@Driver						varchar(300),
	@DriverMobilePhone			varchar(300),
	@CardNumber					varchar(300),
	@ChargingStandardsID		varchar(300),
	@BTypeId					varchar(100),
	@pycode                     varchar(300),
	@BaoxianBtypeid				VARCHAR(100),
	@nType						varchar(20)		--类型 a.新增  m.修改  d.删除 c.分类
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @nReturntype 	int,
		@EtypeId_1 		varchar(100),
		@nSonCount 		int,
		@SonCount 		int,
		@nSonnum 		int,
		@SonNum			int,
		@leveal 		smallint,
		@ParId			varchar(100),
		@XiWaMaxNumber 	numeric(18,0)

--修改XiWa的XiWaMaxNumber
SELECT 	@XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM QP_RepairAutoInfo

IF @nType = 'a' OR @nType = 'c' OR @nType = 'f'
	BEGIN
		IF @nType = 'c'
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Billindex_CarRepair WHERE RATypeID = @TypeId)
					RETURN -5
		         
				IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE RATypeID = @TypeId)
					RETURN -5
				IF EXISTS(SELECT TOP 1 1 FROM Qp_InsuranceAuto WHERE RATypeID = @TypeId)
					RETURN -5
					IF EXISTS(SELECT TOP 1 1 FROM Qp_YearCheck WHERE RATypeID = @TypeId)
					RETURN -5 
			END

		-- 获得新的ID号
		EXEC @nReturntype=Gp_createId @TypeId,'QP_RepairAutoInfo',@EtypeId_1 out,@nSonnum out,@nSoncount out
		IF @nReturntype=-1 RETURN -1
		IF @nReturntype=-2 RETURN -2

		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoInfo WHERE PlateNumber = @PlateNumber)
			RETURN -3

		BEGIN TRAN InsertProc

		SELECT @leveal = Leveal FROM QP_RepairAutoInfo WHERE TypeId = @TypeId
		SET @leveal = @leveal + 1		

		INSERT INTO QP_RepairAutoInfo
		(
			TypeId,
			ParId,
			Leveal,
			SonCount,
			SonNum,
			PlateNumber,
			EngineNumber,
			RepairAutoTypeID,
			FrameNumber,
			TransmissionNumber,
			VIN,
			Color,
			RecordDate,
			ForceMaintainDate,
			ForceMaintainMileage,
			FirstMaintainDate,
			FirstMaintainMileage,
			Comment,
			LeaveFactoryNum,
			LeaveFactoryDate,
			Driver,
			DriverMobilePhone,
			CardNumber,
			ChargingStandardsID,
			BTypeId,
			PYCode,
			BaoXianBtypeid	
		)VALUES(
			@EtypeId_1,
			@TypeId,
			@leveal,
			0,
			0,
			@PlateNumber,
			@EngineNumber,
			@RepairAutoTypeID,
			@FrameNumber,
			@TransmissionNumber,
			@VIN,
			@Color,
			@RecordDate,
			@ForceMaintainDate,
			@ForceMaintainMileage,
			@FirstMaintainDate,
			@FirstMaintainMileage,
			@Comment,
			@LeaveFactoryNum,
			@LeaveFactoryDate,
			@Driver,
			@DriverMobilePhone,
			@CardNumber,
			@ChargingStandardsID,
			@BTypeId,
			@pycode,
			@BaoxianBtypeid	
		)

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN InsertProc
				RETURN -4
			END
		ELSE
			BEGIN
				UPDATE	QP_RepairAutoInfo
				SET 	sonnum=@nSonnum+1,
						soncount=@nSoncount+1
				WHERE	TypeId = @TypeId
			END

		UPDATE  QP_RepairAutoInfo 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @EtypeId_1

		COMMIT TRAN InsertProc
	END
ELSE IF @nType = 'm'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoInfo WHERE TypeId <> @TypeId AND PlateNumber = @PlateNumber)
			RETURN -3

		UPDATE	QP_RepairAutoInfo
		SET		PlateNumber			= @PlateNumber,
				EngineNumber		= @EngineNumber,
				RepairAutoTypeID	= @RepairAutoTypeID,
				FrameNumber			= @FrameNumber,
				TransmissionNumber	= @TransmissionNumber,
				VIN					= @VIN,
				Color				= @Color,
				RecordDate			= @RecordDate,
				ForceMaintainDate	= @ForceMaintainDate,
				ForceMaintainMileage= @ForceMaintainMileage,
				FirstMaintainDate	= @FirstMaintainDate,
				FirstMaintainMileage= @FirstMaintainMileage,
				Comment				= @Comment,
				LeaveFactoryNum		= @LeaveFactoryNum,
				LeaveFactoryDate	= @LeaveFactoryDate,
				Driver				= @Driver,
				DriverMobilePhone	= @DriverMobilePhone,
				CardNumber			= @CardNumber,
				ChargingStandardsID	= @ChargingStandardsID,
				BTypeId				= @BTypeId,
				PYCode              = @pycode,
				BaoxianBtypeId		=@BaoxianBtypeid
		WHERE	TypeId   = @TypeId

		IF @@ROWCOUNT = 0
			RETURN -4	

		UPDATE  QP_RepairAutoInfo 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @TypeId	
	END
ELSE IF @nType = 'd'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Billindex_CarRepair WHERE RATypeID = @TypeId)
			RETURN -1

		IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE RATypeID = @TypeId)
			RETURN -1
        IF EXISTS(SELECT TOP 1 1 FROM Qp_InsuranceAuto WHERE RATypeID = @TypeId)
			RETURN -1
		IF EXISTS(SELECT TOP 1 1 FROM Qp_YearCheck WHERE RATypeID = @TypeId)
			RETURN -1 
					
		SELECT @ParId=ParId FROM QP_RepairAutoInfo WHERE TypeId = @TypeId

		DELETE FROM QP_RepairAutoInfo WHERE TypeId = @TypeId

		IF @@ROWCOUNT = 0
			RETURN -2	
		ELSE
			BEGIN			 	
			 	SELECT @SonNum=SonNum FROM QP_RepairAutoInfo WHERE TypeId=@ParId
			 	SELECT @Sonnum=@Sonnum-1
			 	UPDATE QP_RepairAutoInfo SET Sonnum = @Sonnum WHERE TypeId =@ParId 
			END

		UPDATE  QP_RepairAutoInfo 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @TypeId
	END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealRepairAutoType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_DealRepairAutoType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-12
	描述：处理维修车型档案信息
*/
CREATE PROCEDURE QP_DealRepairAutoType
(
	@TypeId			varchar(100),	--基本信息ID
	@UserCode		varchar(200),	--编号
	@FullName		varchar(200),	--名称
	@nType			varchar(20)	,	--类型 a.新增  m.修改  d.删除 c.分类
	@pycode         varchar(100)    --拼音码
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @nReturntype 	int,
		@EtypeId_1 		varchar(100),
		@nSonCount 		int,
		@SonCount 		int,
		@nSonnum 		int,
		@SonNum			int,
		@leveal 		smallint,
		@ParId			varchar(100),
		@XiWaMaxNumber 	numeric(18,0)

--修改XiWa的XiWaMaxNumber
SELECT 	@XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM QP_RepairAutoType

IF @nType = 'a' OR @nType = 'c'
	BEGIN
		IF @nType = 'c'
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoInfo WHERE RepairAutoTypeID = @TypeId)
					RETURN -5

				IF EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE RepairAutoTypeID = @TypeId)
					RETURN -5
				IF EXISTS(SELECT TOP 1 1 FROM BillIndex_CarRepair WHERE RepairAutoTypeID = @TypeId)
					RETURN -5
				IF EXISTS(SELECT TOP 1 1 FROM QP_MiantenanceInfo WHERE RepairAutoTypeID = @TypeId)
					RETURN -5
				IF EXISTS(SELECT TOP 1 1 FROM billindex_carrepair WHERE RepairAutoTypeID = @TypeId)
					RETURN -5
			END

		-- 获得新的ID号
		EXEC @nReturntype=Gp_createId @TypeId,'QP_RepairAutoType',@EtypeId_1 out,@nSonnum out,@nSoncount out
		IF @nReturntype=-1 RETURN -1
		IF @nReturntype=-2 RETURN -2

		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoType WHERE UserCode = @UserCode OR FullName = @UserCode )
			RETURN -3

		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoType WHERE UserCode = @FullName OR FullName = @FullName )
			RETURN -6

		BEGIN TRAN InsertProc

		SELECT @leveal = Leveal FROM QP_RepairAutoType WHERE TypeId = @TypeId
		SET @leveal = @leveal + 1		

		INSERT INTO QP_RepairAutoType
		(
			TypeId,
			ParId,
			Leveal,
			SonCount,
			SonNum,
			UserCode,
			FullName,
			PYCode		
		)VALUES(
			@EtypeId_1,
			@TypeId,
			@leveal,
			0,
			0,
			@UserCode,
			@FullName,
			@PYCode
		)

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN InsertProc
				RETURN -4
			END
		ELSE
			BEGIN
				UPDATE	QP_RepairAutoType
				SET 	sonnum=@nSonnum+1,
						soncount=@nSoncount+1
				WHERE	TypeId = @TypeId
			END

		UPDATE  QP_RepairAutoType 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @EtypeId_1

		COMMIT TRAN InsertProc
	END
ELSE IF @nType = 'm'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoType WHERE TypeId <> @TypeId AND (UserCode = @UserCode OR FullName = @UserCode ))
			RETURN -3

		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoType WHERE TypeId <> @TypeId AND (UserCode = @FullName OR FullName = @FullName ))
			RETURN -6

		UPDATE	QP_RepairAutoType
		SET		UserCode = @UserCode,
				FullName = @FullName,
				PYCode   = @pycode 
		WHERE	TypeId   = @TypeId

		IF @@ROWCOUNT = 0
			RETURN -4	

		UPDATE  QP_RepairAutoType 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @TypeId	
	END
ELSE IF @nType = 'd'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairAutoInfo WHERE RepairAutoTypeID = @TypeId)
			RETURN -1

		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE RepairAutoTypeID = @TypeId)
			RETURN -1
        IF EXISTS(SELECT TOP 1 1 FROM BillIndex_CarRepair WHERE RepairAutoTypeID = @TypeId)
			RETURN -1
        IF EXISTS(SELECT TOP 1 1 FROM QP_MiantenanceInfo WHERE RepairAutoTypeID = @TypeId)
			RETURN -1
        IF EXISTS(SELECT TOP 1 1 FROM billindex_carrepair WHERE RepairAutoTypeID = @TypeId)
			RETURN -1
       
		SELECT @ParId=ParId FROM QP_RepairAutoType WHERE TypeId = @TypeId

		DELETE FROM QP_RepairAutoType WHERE TypeId = @TypeId

		IF @@ROWCOUNT = 0
			RETURN -2	
		ELSE
			BEGIN			 	
			 	SELECT @SonNum=SonNum FROM QP_RepairAutoType WHERE TypeId=@ParId
			 	SELECT @Sonnum=@Sonnum-1
			 	UPDATE QP_RepairAutoType SET Sonnum = @Sonnum WHERE TypeId =@ParId 
			END

		UPDATE  QP_RepairAutoType 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @TypeId
	END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealRepairItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_DealRepairItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-11
	描述：维修项目档案
*/
CREATE PROCEDURE QP_DealRepairItems
(
	@TypeId				varchar(100),			--基本信息ID
	@UserCode			varchar(200),		--编号
	@FullName			varchar(200),		--名称
	@ItemType			varchar(200),		--项目类型
	@StandardManHour	varchar(20),		--标准工时
	@CheckHour			varchar(20),		--考核工时
	@StandardPrice		varchar(20),		--标准价
	@TopPrice			varchar(20),		--最高价
	@LowPrice			varchar(20),		--最低价
	@ChargeMode			varchar(20),		--计费方式
	@RepairAutoTypeID	varchar(100),		--维修车型ID
	@MaintainDays		varchar(20),		--保养天数
	@Comment			varchar(MAX),		--备注
	@nType				varchar(20),		--操作类型 a.新增 m.修改 d.删除 c.分类
	@MaintainMileage	VARCHAR(MAX)='',		--保养里程
	@UserDefine1		VARCHAR(MAX)='',		--用户自定义1
	@UserDefine2		VARCHAR(MAX)='',		--用户自定义2
	@UserDefine3		VARCHAR(MAX)='',		--用户自定义3
	@UserDefine4		VARCHAR(MAX)='',		--用户自定义4
	@UserDefine5		VARCHAR(MAX)='',		--用户自定义5
	@PyCode				VARCHAR(MAX)=''		--拼音码
)
--@encode$--
AS
SET NOCOUNT ON


DECLARE @nReturntype 	int,
		@EtypeId_1 		varchar(100),
		@nSonCount 		int,
		@SonCount 		int,
		@nSonnum 		int,
		@SonNum			int,
		@leveal 		smallint,
		@ParId			varchar(100),
		@XiWaMaxNumber	numeric(18,0)

--修改XiWa的XiWaMaxNumber
SELECT 	@XiWaMaxNumber = Max(XiWaMaxNumber)+1 FROM QP_RepairItems

IF @nType = 'a' OR @nType = 'c' OR @nType = 'f'
	BEGIN
		IF @nType = 'c'
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM QP_RepairSetMeal_Items WHERE RepairItemsTypeID = @TypeId)
					RETURN -5
		
				IF EXISTS(SELECT TOP 1 1 FROM QP_EvaluationBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
					RETURN -5	
		
				IF EXISTS(SELECT TOP 1 1 FROM QP_nVipCardSet_RepairItems WHERE RepairItemsTypeID = @TypeId)
					RETURN -5		
				IF EXISTS(SELECT TOP 1 1 FROM QP_nVipCardSign_RepairItems WHERE RepairItemsTypeID = @TypeId)
					RETURN -5	
		
				IF EXISTS(SELECT TOP 1 1 FROM QP_QuickRepairBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
					RETURN -5	
        
				IF EXISTS(SELECT TOP 1 1 FROM QP_InsuranceBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
					RETURN -5	
				IF EXISTS(SELECT TOP 1 1 FROM Qp_ReceptionBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
					RETURN -5
				IF EXISTS(SELECT TOP 1 1 FROM Qp_SuccorBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
					RETURN -5	
				IF EXISTS(SELECT TOP 1 1 FROM Qp_ThreePacketsBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
					RETURN -5	
						
			END

		-- 获得新的ID号
		EXEC @nReturntype=Gp_createId @TypeId,'QP_RepairItems',@EtypeId_1 out,@nSonnum out,@nSoncount out
		IF @nReturntype=-1 RETURN -1
		IF @nReturntype=-2 RETURN -2

		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE UserCode = @UserCode OR FullName = @UserCode)
			RETURN -3

		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE UserCode = @FullName OR FullName = @FullName)
			RETURN -6

		BEGIN TRAN InsertProc

		SELECT @leveal = Leveal FROM QP_RepairItems WHERE TypeId = @TypeId
		SET @leveal = @leveal + 1		

		INSERT INTO QP_RepairItems
		(
			TypeId,
			ParId,
			Leveal,
			SonCount,
			SonNum,
			UserCode,
			FullName,
			ItemType,
			StandardManHour,
			CheckHour,
			StandardPrice,
			TopPrice,
			LowPrice,
			ChargeMode,
			RepairAutoTypeID,
			MaintainDays,
			Comment,
			MaintainMileage,
			UserDefine1,
			UserDefine2,
			UserDefine3,
			UserDefine4,
			UserDefine5,
			PyCode
		)VALUES(
			@EtypeId_1,
			@TypeId,
			@leveal,
			0,
			0,
			@UserCode,
			@FullName,
			@ItemType,
			@StandardManHour,
			@CheckHour,
			@StandardPrice,
			@TopPrice,
			@LowPrice,
			@ChargeMode,
			@RepairAutoTypeID,
			@MaintainDays,
			@Comment,
			@MaintainMileage,
			@UserDefine1,
			@UserDefine2,
			@UserDefine3,
			@UserDefine4,
			@UserDefine5,
			@PyCode
		)

		IF @@ROWCOUNT = 0
			BEGIN
				ROLLBACK TRAN InsertProc
				RETURN -4
			END
		ELSE
			BEGIN
				UPDATE	QP_RepairItems
				SET 	sonnum=@nSonnum+1,
						soncount=@nSoncount+1
				WHERE	TypeId = @TypeId
			END

		UPDATE  QP_RepairItems 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @EtypeId_1

		COMMIT TRAN InsertProc
	END
ELSE IF @nType = 'm'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE TypeId <> @TypeId AND (UserCode = @UserCode OR FullName = @UserCode))
			RETURN -3

		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairItems WHERE TypeId <> @TypeId AND (UserCode = @FullName OR FullName = @FullName))
			RETURN -6

		UPDATE 	QP_RepairItems
		SET 	UserCode 		= @UserCode,
				FullName 		= @FullName,
				ItemType 		= @ItemType,
				StandardManHour	= @StandardManHour,
				CheckHour 		= @CheckHour,
				StandardPrice	= @StandardPrice,
				TopPrice		= @TopPrice,
				LowPrice		= @LowPrice,
				ChargeMode		= @ChargeMode,
				RepairAutoTypeID= @RepairAutoTypeID,
				MaintainDays	= @MaintainDays,
				Comment			= @Comment,
				MaintainMileage	= @MaintainMileage,
				UserDefine1		= @UserDefine1,
				UserDefine2		= @UserDefine2,
				UserDefine3		= @UserDefine3,
				UserDefine4		= @UserDefine4,
				UserDefine5		= @UserDefine5,
				PyCode			= @PyCode
		WHERE	TypeId			= @TypeId

		IF @@ROWCOUNT = 0
			RETURN -4

		UPDATE  QP_RepairItems 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @TypeId	
	END
ELSE IF @nType = 'd'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairSetMeal_Items WHERE RepairItemsTypeID = @TypeId)
			RETURN -1

		IF EXISTS(SELECT TOP 1 1 FROM QP_EvaluationBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
			RETURN -1	

		IF EXISTS(SELECT TOP 1 1 FROM QP_nVipCardSet_RepairItems WHERE RepairItemsTypeID = @TypeId)
			RETURN -1		

		IF EXISTS(SELECT TOP 1 1 FROM QP_nVipCardSign_RepairItems WHERE RepairItemsTypeID = @TypeId)
			RETURN -1	
        IF EXISTS(SELECT TOP 1 1 FROM Qp_ReceptionBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
           -- print '2555'
			RETURN -1
		IF EXISTS(SELECT TOP 1 1 FROM QP_QuickRepairBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
			RETURN -1	
				
        IF EXISTS(SELECT TOP 1 1 FROM Qp_ThreePacketsBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
			-- print '2555'
			RETURN -1	
		--保险理赔单
		IF EXISTS(SELECT TOP 1 1 FROM QP_InsuranceBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
			RETURN -1
			--救援单
		IF EXISTS(SELECT TOP 1 1 FROM Qp_SuccorBill_RepairItems WHERE RepairItemsTypeID = @TypeId)
			RETURN -1		
        
		SELECT @ParId=ParId FROM QP_RepairItems WHERE TypeId = @TypeId

		DELETE FROM QP_RepairItems WHERE TypeId = @TypeId

		IF @@ROWCOUNT = 0
			RETURN -2	
		ELSE
			BEGIN			 	
			 	SELECT @SonNum=SonNum FROM QP_RepairItems WHERE TypeId=@ParId
			 	SELECT @Sonnum=@Sonnum-1
			 	UPDATE QP_RepairItems SET Sonnum = @Sonnum WHERE TypeId =@ParId 
			END

		UPDATE  QP_RepairItems 
		SET 	XiWaMaxNumber = @XiWaMaxNumber 
		WHERE 	TypeId = @TypeId	
	END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DealRepairMode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_DealRepairMode]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2010-07-19
	描述：处理维修方式
*/
CREATE PROCEDURE QP_DealRepairMode
(
	@ID			varchar(100),
	@FullName	varchar(200),
	@nType		varchar(10),
	@pycode     varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

IF @nType = 'a' 		--新增
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairMode WHERE FullName = @FullName)
			RETURN -1

		INSERT INTO QP_RepairMode
		(
			FullName,
			PYCode 
		)VALUES(
			@FullName,
			@pycode 
		)

		IF @@ROWCOUNT = 0
			RETURN -2		
	END
ELSE IF @nType = 'm' 	--修改
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_RepairMode WHERE FullName = @FullName AND [ID]<>@ID)
			RETURN -1		

		UPDATE	QP_RepairMode
		SET		FullName 	= @FullName,
		        PYCode      =@pycode 
		WHERE	[ID] 		= @ID

		IF @@ROWCOUNT = 0
			RETURN -2
	END
ELSE IF @nType = 'd'	--删除
	BEGIN	
		DELETE FROM QP_RepairMode WHERE [ID] = @ID

		IF @@ROWCOUNT = 0
			RETURN -2
	END
/*
ELSE IF @nType='v'
	BEGIN
		SELECT * FROM QP_RepairMode WHERE FullName LIKE '%'+@FullName+'%'
	END
*/


RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_DeleteScheme]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_DeleteScheme]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-12-09
	描述：删除查询方案
*/

CREATE	PROCEDURE Qp_DeleteScheme 
( 
	@schemeid		varchar(100)		--查询方案ID
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN TRANSACTION DEL
	DELETE FROM Scheme WHERE Schemeid = @schemeid
	DELETE FROM SchemeDetail WHERE Schemeid = @schemeid
	--排序字段表
	DELETE FROM OrderFiledSchemeDetail WHERE Schemeid=@schemeid

IF(@@ERROR<>0)
BEGIN
	ROLLBACK TRANSACTION  DEL
	RAISERROR('删除失败，请确认后重试！',16,1)
END

COMMIT TRANSACTION  DEL
	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_DelMiantenanceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].QP_DelMiantenanceInfo
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-09-09
	描述：处理保养档案信息
*/
CREATE PROCEDURE QP_DelMiantenanceInfo
(
	@id	varchar(100)	--维修车型ID
)
--@encode$--
AS
SET NOCOUNT ON

DELETE FROM QP_MiantenanceInfo WHERE ID=@id
IF @@ERROR<>0
	RAISERROR('删除保养档案失败！',16,1)	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[QP_DelSalePlan]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[QP_DelSalePlan]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-21
--	描述：删除销售计划
---------------------------------------------
CREATE PROCEDURE QP_DelSalePlan
( 
	@id			VARCHAR(MAX),
	@idtype		VARCHAR(MAX),
	@fullname	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

IF @idtype='timeid'
	BEGIN
		IF NOT EXISTS(SELECT *FROM SaleTimeTotal WHERE ID=@id)
			BEGIN
				RAISERROR('该销售计划时段【%s】不存在，删除失败！',16,1,@fullname)RETURN
			END
		IF @id in (select TotalID from StypeSaleAllPlan)
			BEGIN
				RAISERROR('该销售计划【%s】已经在分支机构销售计划中使用，不能删除！',16,1,@fullname)RETURN
			END
		IF @id in (select TotalID from DtypeSaleAllPlan)
			BEGIN
				RAISERROR('该销售计划【%s】已经在部门销售计划中使用，不能删除！',16,1,@fullname)RETURN
			END
		IF EXISTS (SELECT *FROM SaleTimeTotal WHERE ID=@id AND IfUse='1')
		BEGIN
			RAISERROR('该时段组【%s】已经启用，不能删除，请停用后重试！',16,1,@fullname)RETURN
		END
		--删除时间总表数据
		DELETE SaleTimeTotal WHERE ID=@id
		--删除明细表数据
		DELETE SaleTime WHERE TotalID=@id
		RETURN
	END

DECLARE @DETIALID VARCHAR(MAX)
IF @idtype='splanid'
	BEGIN
		IF NOT EXISTS (SELECT * FROM StypeSaleAllPlan WHERE ID=@id)
		BEGIN
			RAISERROR('该销售计划不存在，删除失败！',16,1,@fullname)RETURN
		END
		
		IF EXISTS (SELECT * FROM StypeSaleAllPlan WHERE ID=@id AND IfUse='1')
		BEGIN
			RAISERROR('该销售计划【%s】已经启用，不能删除，请停用后重试！',16,1,@fullname)RETURN
		END
		
		--删除分支机构销售计划
		DELETE StypeSaleAllPlan WHERE ID=@id
		DELETE DetailStypeSaleplan WHERE StypeSaleplanID IN (SELECT ID FROM StypeSaleplan  WHERE SplanID=@id)
		DELETE StypeSaleplan WHERE SplanID=@id

		
		--删除部门销售计划
		DELETE DetailDtypeSaleplan WHERE DtypeSaleplanID IN (SELECT dp.ID FROM DtypeSaleplan dp INNER JOIN DtypeSaleAllPlan da ON da.ID=dp.DplanID WHERE da.FullName=@fullname)
		DELETE DtypeSaleplan WHERE DplanID IN (SELECT ID FROM DtypeSaleAllPlan WHERE FullName=@fullname)
		DELETE DtypeSaleAllPlan WHERE FullName=@fullname
		
		--删除职员销售计划
		DELETE DetailEtypeSaleplan WHERE EtypeSaleplanID IN (SELECT ep.ID FROM EtypeSaleplan ep INNER JOIN EtypeSaleAllPlan ea ON ea.ID=ep.EplanID WHERE ea.FullName=@fullname)
		DELETE EtypeSaleplan WHERE EplanID IN (SELECT ID FROM EtypeSaleAllPlan WHERE FullName=@fullname)
		DELETE EtypeSaleAllPlan WHERE FullName=@fullname
		
	END

IF @idtype='dplanid'
	BEGIN
		IF NOT EXISTS (SELECT * FROM  DtypeSaleAllPlan WHERE ID=@id)
		BEGIN
			RAISERROR('该销售计划不存在，删除失败！',16,1,@fullname)RETURN
		END		
		IF EXISTS (SELECT * FROM  DtypeSaleAllPlan WHERE ID=@id AND IfUse='1')
		BEGIN
			RAISERROR('该销售计划【%s】已经启用，不能删除，请停用后重试！',16,1,@fullname)RETURN
		END
				
		--删除职员销售计划
		DELETE DetailEtypeSaleplan 
		WHERE	EtypeSaleplanID IN 
		(
		SELECT ID 
		FROM EtypeSaleplan 
		WHERE EplanID IN 
			(
			SELECT ID 
			FROM EtypeSaleAllPlan 
			WHERE DTypePlanID IN (SELECT ID FROM DtypeSaleplan WHERE DplanID =@id)
			)
		)
		DELETE EtypeSaleplan WHERE EplanID IN (SELECT ID FROM EtypeSaleAllPlan WHERE DTypePlanID IN (SELECT ID FROM DtypeSaleplan WHERE DplanID =@id))
		DELETE EtypeSaleAllPlan WHERE DTypePlanID IN (SELECT ID FROM DtypeSaleplan WHERE DplanID =@id)
		
		--销售计划
		DELETE DetailDtypeSaleplan WHERE DtypeSaleplanID IN (SELECT ID FROM DtypeSaleplan WHERE DplanID=@id)
		DELETE DtypeSaleplan WHERE DplanID=@id
		DELETE DtypeSaleAllPlan WHERE ID=@id	
	END
	
IF @idtype='eplanid'
	BEGIN
		IF NOT EXISTS (SELECT * FROM  EtypeSaleAllPlan WHERE ID=@id)
		BEGIN
			RAISERROR('该销售计划不存在，删除失败！',16,1,@fullname)RETURN
		END
		IF EXISTS (SELECT * FROM  EtypeSaleAllPlan WHERE ID=@id AND IfUse='1')
		BEGIN
			RAISERROR('该销售计划【%s】已经启用，不能删除，请停用后重试！',16,1,@fullname)RETURN
		END
		--删除职员销售计划总表数据
		DELETE EtypeSaleAllPlan WHERE ID=@id
		--删除职员销售计划明细
		SELECT @DETIALID=ID FROM EtypeSaleplan  WHERE EplanID=@id
		DELETE EtypeSaleplan WHERE EplanID=@id
		DELETE DetailEtypeSaleplan WHERE EtypeSaleplanID=@DETIALID
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_ETypeItemsDetail_Save]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_ETypeItemsDetail_Save]
GO


----========================
----修改者：蔡志成
----日期：2010-9-4
----描述 人员组档案
----========================
CREATE  PROCEDURE QP_ETypeItemsDetail_Save
    (
      @intid INT,
	  @strEtypeID VARCHAR(100)
    )
--@encode$--
AS 
    SET NOCOUNT ON    
    
		INSERT dbo.QP_WorkGroup_Person (
			WorkGroupID,
			ETypeID
		) VALUES ( 
			@intid,
			@strEtypeID
		)

    SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_ETypeItemsIndex_Save]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_ETypeItemsIndex_Save]
GO


----========================
----修改者：蔡志成
----日期：2010-9-4
----描述 人员组档案
----========================
CREATE  PROCEDURE QP_ETypeItemsIndex_Save
    (
      @intid INT,
      @strFullname VARCHAR(200),
      @strUserCode VARCHAR(200),
      @pycode      varchar(100)
    )
--@encode$--
AS 
    SET NOCOUNT ON    
    
    IF EXISTS ( SELECT  *
                FROM    QP_WorkGroup
                WHERE   (fullname = @strFullname
                        OR usercode = @strUserCode
                        )
                        AND ID <>@intid ) 
        BEGIN
            SELECT  @intid=-1
        END
    ELSE 
        BEGIN
            IF @intid = -1 
                BEGIN
				
                    INSERT  dbo.QP_WorkGroup ( UserCode, FullName,pycode)
                    VALUES  (
                              @strUserCode,
                              @strFullname ,
                              @pycode 
                            ) 
                    SELECT @intid= SCOPE_IDENTITY();
                END
            ELSE 
                BEGIN
                
                    UPDATE  dbo.QP_WorkGroup
                    SET     UserCode = @strUserCode,
                            FullName = @strFullname,
                            pycode   =@pycode 
                    WHERE   ID = @intid
                    
                    
                END
        END
		
    SELECT  @intid
    SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[QP_FirstMaintainInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[QP_FirstMaintainInfo]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年11月22日
-- Description:	查询首保信息
-- =============================================
CREATE PROCEDURE QP_FirstMaintainInfo 
(
	@date int,               --查询时间条件
	@OperatorId varchar(50)  --当前操作员ID
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--仓库
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT DISTINCT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)
BEGIN
SELECT a.PlateNumber,
		a.BTypeID,
		b.FullName,
		a.FirstMaintainDate,
		a.FirstMaintainMileage,
		a.Driver,
		a. DriverMobilePhone
FROM QP_RepairAutoInfo a
LEFT JOIN 
QP_RepairAutoType  b  ON a.RepairAutoTypeID=b.TypeID
WHERE DATEDIFF(day, GETDATE(),a.FirstMaintainDate)<= @date
AND a.BTypeID IN(SELECT TypeID FROM #GetManBTypeId)
ORDER BY a.FirstMaintainDate ASC,a.PlateNumber ASC
END
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBtypeCredit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetBtypeCredit
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2010-12-27
-- Description: 信用额度管理
-- =============================================
CREATE PROCEDURE Web_GetBtypeCredit
(
	@stypeid VARCHAR(100),
	@btypeid varchar(100),
	@OperatorId varchar(200)
)
AS
BEGIN
	
	SET NOCOUNT ON;

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

create table #btype(typeid varchar(100))
create table #stype(typeid varchar(100))

--往来单位    
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)

--分支机构
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)



    select b.typeid as btypeid,
			c.credit,
			c.StypeId 
	from btype b inner join btype_credit c on c.BtypeId=b.typeId where c.StypeId=@stypeid and b.typeId=@btypeid
			and b.typeId in(select typeId from #btype)
			
drop table #btype,#stype
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GetVipCardSign]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GetVipCardSign]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述:读取Vip卡发卡的信息
	作者:徐辉
	日期:2010-08-02
*/
CREATE                 PROCEDURE QP_GetVipCardSign
(	
	@VipCardId			int
)
--@encode$--
AS

SET NOCOUNT ON

SELECT 
	a.*, n.DiscountType, b.fullname as efullname, c.PlateNumber, c.autotypename, 
	c.Color, d.typeid AS btypeid, d.fullname AS bfullname,
	n.TypeName,a.VipCardTypeId,n.ifJF,n.CardTypeDiscount,
	ISNULL(a.BeginMoney,0)+ISNULL(a.TotalMoney,0) AS LjTotal
	,s.FullName AS jksfullname
FROM nVipCardSign a 
LEFT JOIN nVipCardSet n ON a.VipCardTypeId=n.VipCardTypeId
LEFT JOIN employee b ON a.etypeid=b.typeid
LEFT JOIN btype d ON a.BtypeId=d.typeid
LEFT JOIN stype s ON s.TypeId = a.jkStypeId
LEFT JOIN 
	(
	SELECT d.*, e.FullName AS autotypename FROM QP_RepairAutoInfo d 
	LEFT JOIN QP_RepairAutoType e ON d.RepairAutoTypeID=e.typeid
	) c 
	ON a.ratypeid=c.typeid 
WHERE VipCardId=@vipcardid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_CarWashBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_CarWashBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2010-08-05
	描述：洗车结算
*/
CREATE  PROCEDURE Qp_Gp_CarWashBill
(
	@BillDate  			[datetime],
	@BillCode  			[varchar](200), 
	@BillType  			[numeric](4,0),
	@EtypeId  			[varchar](50),
	@DtypeId 			varchar(50) = '',		
	@AtypeId			varchar(50)='',
	@BtypeId			varchar(50)='',
	@RAtypeId			varchar(50)='',			--车辆ID
	@VipCardID			int = -1,				-- VIP卡的唯一ID值
	@CheckE  			[varchar](50),
	@szPeriod 			[SMALLINT],
	@Comment  			[varchar](256),
	@Explain 			[varchar](256),
	@TotalInMoney		 NUMERIC(24, 10) =0,
	@STypeID			varchar(50)='',
	@TotalMoney			 NUMERIC(24, 10) =0

)
--@encode$--
AS
SET NOCOUNT ON


IF EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND deleted=2
)
BEGIN
	RETURN	-101
END

IF EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND deleted=3
)
BEGIN
	RETURN	-102
END

DECLARE
	@GetDate	DATETIME

SELECT @GetDate=CAST(CAST(YEAR(GETDATE()) AS VARCHAR(4))+'-'+CAST(MONTH(GETDATE()) AS VARCHAR(2))+'-'+CAST(DAY(GETDATE()) AS VARCHAR(2))+' 00:00:00' AS DateTime)


IF EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND @BillDate>EndDate
)
BEGIN
	RETURN -110
END

-- ********	判断是否试用版 - Start	********
DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN 1688

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

-- ********	判断是否试用版 - END	********

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********
	-- 获取数据表 LoginUser 中操作员数
	DECLARE @intLoginUserCount int
	SELECT	@intLoginUserCount = COUNT(*)
	FROM	LoginUser
	WHERE	IsErp = 1

-- 判断软件狗用户数
	DECLARE @intDogUserCount int

	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 3	-- 检查用户数

	IF @N IS NULL RETURN 1688

	IF @intVersion IN (2,3,5,7,9,11,13,15)	-- 试用版
	BEGIN
		SELECT @intDogUserCount = 5
	END
	ELSE
	BEGIN
		SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
		IF ( 3 & @N <> 3 ) RETURN 1688
	END

	-- 若实际操作员数 > 软件狗许可用户数，则不允许过账
	IF @intLoginUserCount - 1 > @intDogUserCount RETURN 1688

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - End	********




IF NOT EXISTS (
		SELECT	TOP 1 1
		FROM	SType_UserConfig
		WHERE	ConfigNo = 1
				AND Value = '1'
				AND STypeID=@STypeID
	)
		RETURN -33	-- 没有开帐不允许过帐


DECLARE @Re int,@Flag int
EXEC @Re=Gp_Validate 2, @Flag OUTPUT
IF @Re <>0 RETURN -3 --检查程序版本错误

IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
BEGIN
	--RAISERROR('校验错误 ！',16,1) 
	RETURN -3 --检查程序版本错误
END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -16
	END
END 
-- ********	判断是否试用版 - End	******** 


IF NOT EXISTS(
	SELECT TOP 1 TypeID FROM Department WHERE SonNum = 0 AND Deleted = 0 AND TypeID=@DTypeID
)
BEGIN
	RETURN -1
END

IF @ATypeID<>''
BEGIN
	IF NOT EXISTS(
		SELECT TOP 1 TypeID FROM AType WHERE TypeID=@ATypeid AND SonNum=0 AND Deleted=0
	    AND ((@ATypeID='0000100003' OR @ATypeID LIKE '0000100004%') AND @ATypeID IN (SELECT TypeID FROM F_GetManDetailAType(@CheckE)) OR @ATypeID='0000200005')
	)
	BEGIN
		RETURN -30
	END
END


IF EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='PassOneDay' AND Value='1')
BEGIN
	IF ((YEAR(GETDATE())<>YEAR(@BillDate)) OR (MONTH(GETDATE())<>MONTH(@BillDate)) OR (DAY(GETDATE())<>DAY(@BillDate)))
	BEGIN
		RETURN -11
	END
END




--如果开账日期大于当前日期，则不允许充值
IF EXISTS(SELECT TOP 1 1 FROM MonthProc WHERE (StartDate>GETDATE() OR StartDate>@BillDate) AND MonthNo = '本期' AND Period=1)
	RETURN -15

IF EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillCode=@BillCode)
	RETURN -120

DECLARE @BeginDate 	datetime,
		@szItem 	varchar(30),
		@szVchCode 	varchar(30)

--EXEC Gp_GetSubValue 'period',@szPeriod out

SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
IF @BillDate<@BeginDate 
	BEGIN 
		--RAISERROR('录单日期小于本期开始日期 ！',16,1)
		RETURN -35
	END



DECLARE
		@CardName   varchar(200)

SELECT @CardName=VipCardCode FROM nVipCardSign WHERE VipCardId = @VipCardID


IF @@ROWCOUNT = 0 AND @AtypeID='0000200005'
	RETURN -17


IF NOT EXISTS(SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND CanWashTimes>0)
BEGIN
	
	IF @TotalInMoney<0
	BEGIN
		RETURN -104
	END
	ELSE
	BEGIN
	
		IF @AtypeId='0000200005'
		BEGIN
			--需要判断会员储值金额
			/*
			IF EXISTS(SELECT typeID FROM AType WHERE TypeID='0000200005' AND Total<@TotalInMoney)
			BEGIN
				RETURN -105
			END
			ELSE
			*/
			BEGIN
				IF EXISTS(SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND cZyeMoney<@TotalInMoney)
					RETURN -106
			END
		END
	END
END

--写入主表
INSERT INTO BillIndex
(
	BillDate,
	BillCode,
	BillType,
	EtypeId,
	DtypeId,
	AtypeId,
	BtypeID,
	VipCardID,
	Checke,
	Period,
	Comment,
	Explain,
	TotalInMoney,
	TotalMoney,
	IfCheck,
	Draft,
	ptypeid,ktypeid,ktypeid2,ktypeid3,
	Stypeid
)
VALUES
(
	@BillDate,
	@BillCode,
	@BillType,
	@EtypeId,
	@DtypeId,
	@AtypeId,
	@BtypeID,
	@VipCardID,
	@Checke,
	@szPeriod,
	--@CardName+'VIP 卡充值'+CAST(@TotalInMoney as varchar(20))+'元',
	@Comment,
	@Explain,
	@TotalInMoney,
	@TotalMoney,
	't',
	0,
	'','','','',
	@STypeID
)



DECLARE	
	@nBillId		BIGINT

IF @@ROWCOUNT = 0
	BEGIN
		RETURN -13
	END
ELSE
	SET @nBillId = SCOPE_IDENTITY();

INSERT INTO Billindex_CarRepair(
			[BillNumberId],
			[BillDate],
			[BillType],
			[RATypeID]
	)
	VALUES
	(
			@nBillId,
			@BillDate,
			@BillType,
			ISNULL(@RATypeID,'')
	)

IF @@ROWCOUNT = 0
BEGIN
	RETURN -13
END

--通用的校验

--过账处理
/*



*/

IF EXISTS(SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND CanWashTimes>0)
BEGIN
	UPDATE nVipCardSign
	SET CanWashTimes=ISNULL(CanWashTimes,0)-1
	WHERE VipCardId = @VipCardID

	UPDATE BillIndex
	SET TotalMoney=0,TotalInMoney=0
	WHERE BillNumberID=@nBillId
END
ELSE
	BEGIN
	DECLARE
			@numTotal			 NUMERIC(24, 10) 
	
	SELECT @numTotal=@TotalMoney
	
	IF @numTotal<>0
	BEGIN
		IF ISNULL(@VipCardID,0)>0
		BEGIN
			UPDATE nVipCardSign 
			SET TotalMoney=ISNULL(TotalMoney,0)+@TotalInMoney
			WHERE VipCardId = @VipCardID
	
			IF EXISTS
			(
				SELECT IfJF FROM	nVipCardSign a
				INNER JOIN nVipCardSet b
				ON a.VipCardTypeID=b.VipCardTypeID
				WHERE a.VipCardID=@VipCardID AND b.ifJF=1
			)
			BEGIN
				--积分规则,同维修
				IF EXISTS(
					SELECT Value FROM UserConfig
					WHERE ConfigName='RepairItemsIntegral' AND Value<>'-1' AND Value<>''
				)
				BEGIN
					DECLARE
						@decTempValue	 NUMERIC(24, 10) ,
						@intJF			INT
	
					
						SELECT @decTempValue=CAST(ISNULL(Value,'0') AS  NUMERIC(24, 10) ) FROM UserConfig
						WHERE ConfigName='RepairItemsIntegral'
		
						SELECT @decTempValue=ISNULL(Total,0),@intJF=ISNULL(JF,0)
						FROM nVipJfSet
						WHERE ID=@decTempValue
		
						IF @decTempValue<>0 AND @intJF<>0 AND @numTotal<>0
						BEGIN
							SELECT @intJF=CAST(@numTotal/@decTempValue AS int)*@intJF
		
							UPDATE nVipCardSign
							SET	TotalCent = ISNULL(TotalCent,0) + @intJF
							WHERE VipCardID = @VipCardID
		
							UPDATE BillIndex SET JF =@intJF
							WHERE BillNumberID = @nBillId
						END		
			 					
				END		
			END
		END
		
		
		
		
		
		IF @AtypeID='0000200005'
		BEGIN
			DECLARE
				@decTemp	 NUMERIC(24, 10) 

			SELECT @decTemp=@TotalInMoney*(-1)

			EXEC GP_CreateMX_InsertList 
			@nBillId,
			@BillDate,
			@BillType,
			@ATypeID,
			@BtypeId,
			@ETypeID,
			@decTemp,
			'',
			NULL,
			@DTypeID,
			@STypeID

			UPDATE AType
			SET Total=ISNULL(Total,0)-@TotalInMoney
			WHERE typeId=@atypeid


			UPDATE nVipCardSign 
			SET 
				CZYEMoney=ISNULL(CZYEMoney,0)-@TotalInMoney
			WHERE VipCardId = @VipCardID

		END
		ELSE
		BEGIN
			EXEC GP_CreateMX_InsertList 
			@nBillId,
			@BillDate,
			@BillType,
			@ATypeID,
			@BtypeId,
			@ETypeID,
			@numTotal,
			'',
			NULL,
			@DTypeID,
			@STypeID	

			UPDATE AType
			SET Total=ISNULL(Total,0)+@TotalInMoney
			WHERE typeId=@atypeid
		END		
		
		IF EXISTS(
			SELECT ATypeID FROM AType_Total
			WHERE ATypeID=@AtypeId AND STypeID=@STypeID
		)
		BEGIN
			UPDATE AType_Total
			SET Total=ISNULL(Total,0)+@decTemp
			WHERE AtypeId=@atypeid AND STypeID=@STypeID
		END
		ELSE
		BEGIN
			INSERT AType_Total(ATypeID,STypeID,Total)
			SELECT @AtypeId,@STypeID,@decTemp
		END
	END
	
	
	
	
	
	SELECT
		@atypeid='000030000200008',
		@numTotal=@TotalMoney
	
	IF @numTotal<>0
	BEGIN
		EXEC GP_CreateMX_InsertList 
			@nBillId,
			@BillDate,
			@BillType,
			@ATypeID,
			@BtypeId,
			@ETypeID,
			@numTotal,
			'',
			NULL,
			@DTypeID,
			@STypeID	
			
		
		UPDATE AType
		SET Total=ISNULL(Total,0)+@numTotal
		WHERE typeId=@atypeid
		
		IF EXISTS(
			SELECT ATypeID FROM AType_Total
			WHERE ATypeID=@AtypeId AND STypeID=@STypeID
		)
		BEGIN
			UPDATE AType_Total
			SET Total=ISNULL(Total,0)+@numTotal
			WHERE AtypeId=@atypeid AND STypeID=@STypeID
		END
		ELSE
		BEGIN
			INSERT AType_Total(ATypeID,STypeID,Total)
			SELECT @AtypeId,@STypeID,@numTotal
		END
	END
	
	
	
	--需要挂往来
	SELECT @numTotal=@TotalMoney-@TotalInMoney
	
	DECLARE
		@intReturnCode INT
	
	IF @numTotal<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertARAP @nBillID,'AR',@BillDate,@BillType,@BTypeID,@ETypeID,
			@numTotal,'',NULL,@DTypeID,@STypeID
			
		IF EXISTS(
			SELECT ATypeID FROM AType_Total
			WHERE ATypeID=@AtypeId AND STypeID=@STypeID
		)
		BEGIN
			UPDATE AType_Total
			SET Total=ISNULL(Total,0)+@numTotal
			WHERE AtypeId=@atypeid AND STypeID=@STypeID
		END
		ELSE
		BEGIN
			INSERT AType_Total(ATypeID,STypeID,Total)
			SELECT @AtypeId,@STypeID,@numTotal
		END
		
		IF EXISTS(
			SELECT BTypeID
			FROM BType_ArApTotal
			WHERE BTypeID=@BtypeId AND STypeID=@STypeID
		)
		BEGIN
			INSERT BType_ArApTotal(BTypeID,STypeID,ARTotal)
			SELECT @BtypeId,@STypeID,@numTotal
		END
		ELSE
		BEGIN
			UPDATE BType_ArApTotal
			SET ARTotal=ARTotal+@numTotal
			WHERE BTypeID=@BtypeId AND STypeID=@STypeID
		END
	END
END

UPDATE ListTable
SET Audited=1
WHERE BillNumberID=@nBillId

-- 修改 BillIndex 的 ID 字段，写入真实的物理录单顺序
DECLARE @NewID numeric(10,0)
SELECT 	@NewID = ISNULL(MAX(ID),0) + 1
FROM	BillIndex

UPDATE	BillIndex
SET		ID = @NewID
WHERE	BillNumberID = @nBillID

RETURN @nBillId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_GP_ChangeVipcardcode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Qp_GP_ChangeVipcardcode
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-11-23
	描述：修改会员卡卡号
*/
CREATE PROCEDURE Qp_GP_ChangeVipcardcode
(
	@vipcardid				int,						--会员卡id
	@oldcardcode			varchar(MAX),				--会员卡原卡号
	@newcardcode			varchar(MAX)				--新会员卡卡号
)
--@encode$--
AS
SET NOCOUNT ON
IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardID<>@vipcardid and VipCardCode=@newcardcode)
BEGIN
	RAISERROR('该卡号已存在！',16,1)
	RETURN
END

UPDATE	nVipCardSign 
SET		VipCardCode=@newcardcode,
		Comment='由会员卡号'+@oldcardcode+'修改生成'
WHERE VipCardID=@vipcardid	
IF @@ERROR<>0
	RAISERROR('修改卡号失败！',16,1)	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Gp_ChangeVipCardType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].QP_Gp_ChangeVipCardType
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-11-23
	描述：修改会员卡类型
*/
CREATE PROCEDURE QP_Gp_ChangeVipCardType
(
	@operatorid				varchar(50),				--操作员ID
	@vipcardid				int,						--会员卡id
	@vipcardcode			varchar(MAX),				--会员卡卡号
	@btypeid				varchar(MAX),				--往来单位
	@oldvipcardtype			varchar(MAX),				--会员卡原来的类型
	@newvipcardtype			varchar(MAX),				--会员卡新的类型
	@comment				VARCHAR(200)
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRANSACTION  DEL

UPDATE	nVipCardSign 
SET		VipCardTypeID=@newvipcardtype
WHERE VipCardID=@vipcardid	

UPDATE nVipCardSet
SET vipcardnum = vipcardnum-1
WHERE vipcardtypeid = @oldvipcardtype

UPDATE nVipCardSet
SET vipcardnum = vipcardnum+1
WHERE vipcardtypeid = @newvipcardtype

--处理新会员卡的有效期--
update nVipCardSign
set EndDate= CASE B.ValidType WHEN 0 THEN DATEADD(DAY,-1,DATEADD(YEAR,VALIDDATE,GETDATE()))
							   WHEN 1 THEN DATEADD(MONTH,VALIDDATE,GETDATE())
							   WHEN 2 THEN DATEADD(DAY,VALIDDATE,GETDATE()) End
from nVipCardSign a ,
	nVipCardSet	b
where a.VipCardID=@vipcardid
	and a.VipCardTypeID=b.VipCardTypeID

INSERT INTO dbo.nVipCardTypeChange
        ( VipCardID ,
          OldVipCardTypeID ,
          NewVipCardTypeID ,
          etypeid ,
          ChangeDate,
          Comment,
          OperatStyle
        )
VALUES
(
	@vipcardid,
	@oldvipcardtype,
	@newvipcardtype,
	@operatorid,
	CONVERT (DATE,GETDATE(),120),
	@comment,
	0
)
IF @@ERROR<>0
BEGIN
	RAISERROR('变更会员卡类型失败！',16,1)
	ROLLBACK TRANSACTION  DEL
END

COMMIT TRANSACTION  DEL		
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** Object:  StoredProcedure [dbo].[Gp_HrTaskAddAndEdit]    Script Date: 03/16/2011 15:18:51 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_DelSuccorChargeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_DelSuccorChargeItems]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：赵斌
	日期：2011.4.20
	描述：删除救援收费项目
*/


CREATE PROCEDURE [dbo].[Qp_Gp_DelSuccorChargeItems]
(
	@succorchargeid int								--收费项目id号
)
--@encode$--

AS
--如果该救援收费项目被使用，则不能被删除
IF EXISTS(SELECT TOP 1 1 FROM Qp_SuccorBill_SuccorItems SS INNER JOIN Qp_SuccorChargeItems S ON SS.SuccorChargeId=S.SuccorChargeId
		 WHERE SS.SuccorChargeId=@succorchargeid)
	BEGIN
		RAISERROR('该收费项目已经被救援单使用，不能被删除！',16,1)
		RETURN
	END		
		
DELETE FROM Qp_SuccorChargeItems where SuccorChargeId = @succorchargeid

IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('基本信息删除失败！',16,1)
		RETURN
	END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_DelSuccorType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_DelSuccorType]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：韩林
	日期：2011.4.20
	描述：删除救援类型
*/


CREATE PROCEDURE [dbo].[Qp_Gp_DelSuccorType]
(
	@fullname varchar(max),							--救援类型名称
	@pycode   varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON 
--如果该救援类型被使用，则不能被删除
IF EXISTS(SELECT TOP 1 1 FROM Qp_SuccorBill WHERE SuccorId=(SELECT SuccorId FROM Qp_SuccorType WHERE FullName=@fullname))
	BEGIN 
		RAISERROR('该救援类型已经被救援单使用，不能被删除！',16,1)
		RETURN
	END		
		
DELETE FROM Qp_SuccorType where FullName = @fullname
IF @@ROWCOUNT=0	
	RAISERROR('删除失败！',16,1)		
RETURN

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Gp_DelVipCardLx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Gp_DelVipCardLx]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：徐辉
	日期：2010-07-28
	描述：删除VIP卡类型
*/
CREATE   PROCEDURE QP_Gp_DelVipCardLx
(
	@nid		numeric(18,0)
)
--@encode$--
AS
SET NOCOUNT ON

--判断是否已经使用
IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardTypeId = @nid and deleted<>'1' and VipCardID in (select A.VipCardID From BillIndex A))
	RETURN -1
	
IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardTypeId = @nid and deleted<>'1' and VipCardID in (select BA.VipCardID From BillMulAccount BA))
	RETURN -1

--判断是否已经使用
IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardTypeId = @nid and deleted<>'1' and VipCardID in (select G.vipcardid From BillIndex A Right join gatheringBill G on A.BillNumberId=G.BillNumberId))
	RETURN -1


--判断是否有初始金额
IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign WHERE VipCardTypeId = @nid and deleted<>'1' and (BeginMoney<>0 OR BeginCent<>0 OR cZyeMoney<>0 OR CanWashTimes<>0))
	RETURN -2


DELETE FROM nVipCardSign WHERE VipCardTypeId = @nid
DELETE FROM QP_nVipCardSet_RepairItems WHERE VipCardTypeID = @nid
DELETE FROM nVipCardSet WHERE VipCardTypeId = @nid

RETURN 0









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_EditSuccorChargeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_EditSuccorChargeItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-04-20
	描述：修改、添加救援收费项目信息
*/
CREATE PROCEDURE Qp_Gp_EditSuccorChargeItems
(
	@succorchargeid		int,						--id:修改时用(新增由系统自动生成)
	@fullname			varchar(MAX),				--救援类型名称
	@total				 NUMERIC(24, 10) ,				--收费金额
	@opType				varchar(MAX),				--操作类型
	@pycode             varchar(100)                --拼音码
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Msg VARCHAR(MAX)

IF @opType = 'add' 		--新增
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Qp_SuccorChargeItems WHERE FullName = @fullname)
			BEGIN
				SET @Msg = '救援项目名称重复， 请检查！' + CHAR(10) + CHAR(10)
				SET @Msg = @Msg + '要放弃编辑，按【Esc】键可关闭窗口退出！'				
				RAISERROR(@MSG,16,1)
				RETURN
			END		
		INSERT INTO Qp_SuccorChargeItems
		(
			FullName,
			Total,
			PYCode 
		)VALUES(
			@fullname,
			@total,
			@pycode 
		)	
		
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息添加失败！',16,1)
				RETURN
			END		
	END
ELSE IF @opType = 'mod' 	--修改	
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Qp_SuccorChargeItems WHERE FullName = @fullname AND SuccorChargeId <> @succorchargeid)
			BEGIN
				SET @Msg = '救援项目名称重复， 请检查！' + CHAR(10) + CHAR(10)
				SET @Msg = @Msg + '要放弃编辑，按【Esc】键可关闭窗口退出！'				
				RAISERROR(@MSG,16,1)
				RETURN
			END	
						
		UPDATE	Qp_SuccorChargeItems
		SET		FullName				= @fullname,
				Total					= @total,
				PYCode                  =@pycode 
		WHERE	SuccorChargeId	 		= @succorchargeid
		
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息添加失败！',16,1)
				RETURN
			END		
	END
	
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Gp_ImportP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Gp_ImportP]
GO

/****** Object:  StoredProcedure [dbo].[QP_Gp_ImportP]    Script Date: 05/30/2011 15:28:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO









----========================
----修改者：谢吉康
----日期：2003-03-10
----描述：增加序列号强制管理

----修 改 者：李小虎
----日    期：2011-03-25
----修改原因：促销中使用了商品信息，因此不能被分类
----修改位置：商品分类前的判断

----修 改 者：廖晨羽
----日    期：2011-08-19
----修改原因：导入商品信息
----修改位置：转换输入参数
----========================
CREATE                    PROCEDURE [dbo].[QP_Gp_ImportP]
    (
      @PUserCode [VARCHAR] (201),
      @PFullName   [varchar](201),
      @UserCode [varchar](201),
      @FullName [varchar](201),
      @Name [varchar](201),
      @Pycode	[VARCHAR](201),
      @EntryCode [varchar](201),
      @Standard [varchar](201),
      @Type [varchar](201),
      @Area [varchar](201),
      @UsefulLifeDay [varchar](200),
      @BFullName [varchar](66),
      @integral [VARCHAR] (30),
      @Unit1 [varchar](200),
      @Unit2 [varchar](200),
      @UnitRate1 [varchar](200),
      @Comment [varchar](251),
      @StrPreBuyPrice1 [VARCHAR](18),
      @StrPreBuyPrice2 [VARCHAR](18),
      @StrPreBuyPrice3 [VARCHAR](18),
      @StrPreBuyPrice4 [VARCHAR](18),
      @StrPreBuyPrice5 [VARCHAR](18),
      @StrTopBuyPrice [VARCHAR](18),
      @StrPreSalePrice1 [VARCHAR](18),
      @StrPreSalePrice2 [VARCHAR](18),
      @StrPreSalePrice3 [VARCHAR](18),
      @StrPreSalePrice4 [VARCHAR](18),
      @StrPreSalePrice5 [VARCHAR](18),
      @StrPreSalePrice6 [VARCHAR](18),
      @StrPreSalePrice7 [VARCHAR](18),
      @StrPreSalePrice8 [VARCHAR](18),
      @StrPreSalePrice9 [VARCHAR](18),
      @StrPreSalePrice10 [VARCHAR](18),
      @StrRetailPrice [VARCHAR](18),
      @StrTopSalePrice [VARCHAR](18),
      @StrLowSalePrice [VARCHAR](18),
      @ReturnID  VARCHAR(100) output,
	  @ErrMsg VARCHAR(200) OUTPUT,
	  @typeid  [varchar](500)
     )
--@encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

DECLARE @dbname		[varchar](30) = 'Ptype'
DECLARE @IfSerial [varchar](200) = '0'
DECLARE @SerialCount [varchar](200) = '0'
DECLARE @ColorGroupID [varchar](50) = '0'
DECLARE @SizeGroupID [varchar](50) = '0'
DECLARE @DwgNo [varchar](200) = ''
DECLARE @Brand [varchar](200) = ''
DECLARE @Import [varchar](200) = ''
DECLARE @GeneralType [varchar](200) = ''
DECLARE @GeneralDwgNo [varchar](250) = ''
DECLARE @Property [varchar](200) = ''
DECLARE @PackageQty [varchar](200) = ''
DECLARE @Weight [varchar](200) = '0'
DECLARE @TaxNumber [varchar](200) = ''
DECLARE @Taxrate [varchar](200) = '0'
DECLARE @FcUnit [varchar](200) = ''
DECLARE @FcPrice [varchar](200) = '0'
DECLARE @autotypepycode [VARCHAR] (max) = ''
DECLARE @UsefulLifeMonth [varchar](200) = 0
DECLARE @UnitRate2 [varchar](200) = 0
DECLARE @ValidDays [varchar](200)= 0

IF ((SELECT DATALENGTH(@PUserCode)) > 200)
BEGIN
	SET @ErrMsg = '父类编号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@PFullName)) > 200)
BEGIN
	SET @ErrMsg = '父类名称的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@UserCode)) > 200)
BEGIN
	SET @ErrMsg = '商品编号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@FullName)) > 200)
BEGIN
	SET @ErrMsg = '商品全名的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Name)) > 200)
BEGIN
	SET @ErrMsg = '商品简称的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Pycode)) > 200)
BEGIN
	SET @ErrMsg = '拼音码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@EntryCode)) > 200)
BEGIN
	SET @ErrMsg = '条码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Standard)) > 200)
BEGIN
	SET @ErrMsg = '规格的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Type)) > 200)
BEGIN
	SET @ErrMsg = '型号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Area)) > 200)
BEGIN
	SET @ErrMsg = '产地的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 250)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度250'
	RETURN -1
END

DECLARE @Parid VARCHAR(50)
IF ((@PFullName = '' AND @PUserCode = '') OR (@PFullName = '全部商品' AND @PUserCode = '0'))
BEGIN
	SET @Parid = '00000'
END
ELSE IF NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @PUserCode)
BEGIN
	SET @ErrMsg = '父类编号不存在'
	RETURN -1
END
ELSE IF NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @PFullName)
BEGIN
	SET @ErrMsg = '父类名称不存在'
	RETURN -1
END
ELSE IF(@PFullName <> (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @PUserCode))
BEGIN
	SET @ErrMsg = '父类编号与父类名称不匹配'
	RETURN -1
END
ELSE
BEGIN
	SET @Parid = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @PUserCode)
END

DECLARE @tempdeleted BIT
DECLARE @stopbuy INT
SELECT TOP 1 @tempdeleted = deleted,@stopbuy = stopbuy FROM dbo.ptype WHERE UserCode = @PUserCode
IF(@tempdeleted = 1)
BEGIN
	SET @ErrMsg = '父类商品已停用'
	RETURN -1
END
IF(@stopbuy = 1)
BEGIN
	SET @ErrMsg = '父类商品已停止采购'
	RETURN -1
END

DECLARE @isBtypeAll VARCHAR(50),@isEqualProName VARCHAR(20)  ---分解统一客户供货商和商品同名
SET @isBtypeAll = (SELECT TOP 1 A FROM f_split(@typeid,'я'))
SET @isEqualProName = (SELECT A FROM f_split(@typeid,'я') WHERE A <> @isBtypeAll)
IF (@isEqualProName = 'Enabled')
BEGIN
	IF EXISTS(SELECT TOP 1 typeid FROM dbo.ptype WHERE fullname = @FullName)
	BEGIN
		SET @ErrMsg = '商品名称重复'
		RETURN -1
	END
END

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '商品编号不能为空'
	RETURN -1
END
ELSE IF((SELECT COUNT(*) FROM dbo.ptype WHERE usercode = @UserCode) > 0)
BEGIN
	SET @ErrMsg = '商品编号已存在'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '商品名称不能为空'
	RETURN -1
END

IF(@Pycode = '')
BEGIN
	SELECT @Pycode = dbo.fun_getPY(@FullName)
END

IF (@UsefulLifeDay = '')
BEGIN
	SET @UsefulLifeDay = 0
END
ELSE IF(ISNUMERIC(@UsefulLifeDay) <> 1)
BEGIN
	SET @ErrMsg = '有效期请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('.', @UsefulLifeDay)) <> 0)
BEGIN
	SET @ErrMsg = '有效期请输入整数'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @UsefulLifeDay)) <> 0)
BEGIN
	SET @ErrMsg = '有效期不能为负数'
	RETURN -1
END

IF ((SELECT CONVERT(INT, @UsefulLifeDay)) > 9999 )
BEGIN
	SET @ErrMsg = '有效期最大值为9999'
	RETURN -1
END

DECLARE @BTypeID [varchar](200)
IF (@BFullName = '')                                                          
BEGIN
	SET @BTypeID = ''
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.BType WHERE fullname = @BFullName) OR @BFullName = 'ABC' OR @BFullName = '所有客户' OR @BFullName = '全部供货商'
		BEGIN
			SET @ErrMsg = '供货商不存在'
			RETURN -1
		END
	ELSE
		BEGIN
			DECLARE @PBtypeId VARCHAR(50)
			DECLARE @BChildCount NUMERIC(18,0)
			SET @PBtypeId = (SELECT TOP 1 typeid FROM BType WHERE fullname = @BFullName)
			SELECT @BChildCount = COUNT(*) FROM dbo.BType WHERE typeid LIKE @PBtypeId + '%' AND typeid <> @PBtypeId
			IF (@BChildCount = 0)
				BEGIN
					SET @BTypeID = @PBtypeId
				END
			ELSE
				BEGIN
					SET @ErrMsg = '该供货商为父类'
					RETURN -1
				END	
		END
END
IF(@isBtypeAll = 'False')
BEGIN
	DECLARE @tempBtypeid VARCHAR(200)
	SET @tempBtypeid = SUBSTRING(@BTypeID,1,5)
	IF(@tempBtypeid = '00001')
	BEGIN
			SET @ErrMsg = '供货商不能为客户'
			RETURN -1
	END
END

IF (@integral = '')
BEGIN
	SET @integral = 0
END
ELSE IF(ISNUMERIC(@integral) <> 1)
BEGIN
	SET @ErrMsg = '兑换积分请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @integral)) <> 0)
BEGIN
	SET @ErrMsg = '兑换积分不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SET @integral =  (SELECT ROUND(@integral,2))
END

IF ((SELECT LEN(@Unit1)) >8)
BEGIN
	SET @ErrMsg = '小单位字符长度不能超过8个'
	RETURN -1
END

IF ((SELECT LEN(@Unit2)) >8)
BEGIN
	SET @ErrMsg = '大单位字符长度不能超过8个'
	RETURN -1
END

IF (@Unit1 = @Unit2 AND @Unit1 <> '' AND @unit2 <> '')
BEGIN
	SET @ErrMsg = '大小单位不能完全相同'
	RETURN -1
END

IF (@Unit1 <> '' AND @Unit2 <> '' AND @UnitRate1 = '')
BEGIN
	SET @ErrMsg = '设置了大小单位，换算关系不能为空'
	RETURN -1
END

IF(@Unit1 = '' AND @Unit2 <> '')
BEGIN
	SET @ErrMsg = '必须设置小单位才能设置大单位'
	RETURN -1
END

IF (@UnitRate1 = '')
BEGIN
	SET @UnitRate1 = 0
END
ELSE IF (@Unit1 = '' OR @Unit2 = '')
BEGIN
	SET @ErrMsg = '大小单位不能为空'
	RETURN -1
END
ELSE IF(ISNUMERIC(@UnitRate1) <> 1)
BEGIN
	SET @ErrMsg = '换算关系请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @UnitRate1)) <> 0)
BEGIN
	SET @ErrMsg = '换算关系不能为负数'
	RETURN -1
END

DECLARE @PreBuyPrice1  NUMERIC(24, 10) 
IF (@StrPreBuyPrice1 = '')
BEGIN
	SET @PreBuyPrice1 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice1) <> 1)
BEGIN
	SET @ErrMsg = '预设进价1请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice1)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价1不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice1 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice1)
END

DECLARE @PreBuyPrice2  NUMERIC(24, 10) 
IF (@StrPreBuyPrice2 = '')
BEGIN
	SET @PreBuyPrice2 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice2) <> 1)
BEGIN
	SET @ErrMsg = '预设进价2请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice2)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价2不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice2 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice2)
END

DECLARE @PreBuyPrice3  NUMERIC(24, 10) 
IF (@StrPreBuyPrice3 = '')
BEGIN
	SET @PreBuyPrice3 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice3) <> 1)
BEGIN
	SET @ErrMsg = '预设进价3请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice3)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价3不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice3 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice3)
END

DECLARE @PreBuyPrice4  NUMERIC(24, 10) 
IF (@StrPreBuyPrice4 = '')
BEGIN
	SET @PreBuyPrice4 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice4) <> 1)
BEGIN
	SET @ErrMsg = '预设进价4请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice4)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价4不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice4 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice4)
END

DECLARE @PreBuyPrice5  NUMERIC(24, 10) 
IF (@StrPreBuyPrice5 = '')
BEGIN
	SET @PreBuyPrice5 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice5) <> 1)
BEGIN
	SET @ErrMsg = '预设进价5请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice5)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价5不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice5 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice5)
END

DECLARE @TopBuyPrice  NUMERIC(24, 10) 
IF (@StrTopBuyPrice = '')
BEGIN
	SET @TopBuyPrice = 0
END
ELSE IF(ISNUMERIC(@StrTopBuyPrice) <> 1)
BEGIN
	SET @ErrMsg = '最高进价请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrTopBuyPrice)) <> 0)
BEGIN
	SET @ErrMsg = '最高进价不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @TopBuyPrice = CONVERT( NUMERIC(24, 10) , @StrTopBuyPrice)
END

DECLARE @PreSalePrice1  NUMERIC(24, 10) 
IF (@StrPreSalePrice1 = '')
BEGIN
	SET @PreSalePrice1 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice1) <> 1)
BEGIN
	SET @ErrMsg = '预设售价1请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice1)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价1不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice1 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice1)
END

DECLARE @PreSalePrice2  NUMERIC(24, 10) 
IF (@StrPreSalePrice2 = '')
BEGIN
	SET @PreSalePrice2 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice2) <> 1)
BEGIN
	SET @ErrMsg = '预设售价2请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice2)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价2不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice2 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice2)
END

DECLARE @PreSalePrice3  NUMERIC(24, 10) 
IF (@StrPreSalePrice3 = '')
BEGIN
	SET @PreSalePrice3 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice3) <> 1)
BEGIN
	SET @ErrMsg = '预设售价3请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice3)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价3不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice3 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice3)
END

DECLARE @PreSalePrice4  NUMERIC(24, 10) 
IF (@StrPreSalePrice4 = '')
BEGIN
	SET @PreSalePrice4 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice4) <> 1)
BEGIN
	SET @ErrMsg = '预设售价4请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice4)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价4不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice4 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice4)
END

DECLARE @PreSalePrice5  NUMERIC(24, 10) 
IF (@StrPreSalePrice5 = '')
BEGIN
	SET @PreSalePrice5 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice5) <> 1)
BEGIN
	SET @ErrMsg = '预设售价5请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice5)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价5不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice5 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice5)
END

DECLARE @PreSalePrice6  NUMERIC(24, 10) 
IF (@StrPreSalePrice6 = '')
BEGIN
	SET @PreSalePrice6 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice6) <> 1)
BEGIN
	SET @ErrMsg = '预设售价6请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice6)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价6不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice6 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice6)
END

DECLARE @PreSalePrice7  NUMERIC(24, 10) 
IF (@StrPreSalePrice7 = '')
BEGIN
	SET @PreSalePrice7 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice7) <> 1)
BEGIN
	SET @ErrMsg = '预设售价7请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice7)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价7不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice7 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice7)
END

DECLARE @PreSalePrice8  NUMERIC(24, 10) 
IF (@StrPreSalePrice8 = '')
BEGIN
	SET @PreSalePrice8 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice8) <> 1)
BEGIN
	SET @ErrMsg = '预设售价8请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice8)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价8不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice8 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice8)
END

DECLARE @PreSalePrice9  NUMERIC(24, 10) 
IF (@StrPreSalePrice9 = '')
BEGIN
	SET @PreSalePrice9 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice9) <> 1)
BEGIN
	SET @ErrMsg = '预设售价9请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice9)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价9不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice9 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice9)
END

DECLARE @PreSalePrice10  NUMERIC(24, 10) 
IF (@StrPreSalePrice10 = '')
BEGIN
	SET @PreSalePrice10 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice10) <> 1)
BEGIN
	SET @ErrMsg = '预设售价10请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice10)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价10不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice10 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice10)
END

DECLARE @RetailPrice  NUMERIC(24, 10) 
IF (@StrRetailPrice = '')
BEGIN
	SET @RetailPrice = 0
END
ELSE IF(ISNUMERIC(@StrRetailPrice) <> 1)
BEGIN
	SET @ErrMsg = '零售价请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrRetailPrice)) <> 0)
BEGIN
	SET @ErrMsg = '零售价不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @RetailPrice = CONVERT( NUMERIC(24, 10) , @StrRetailPrice)
END

DECLARE @TopSalePrice  NUMERIC(24, 10) 
IF (@StrTopSalePrice = '')
BEGIN
	SET @TopSalePrice = 0
END
ELSE IF(ISNUMERIC(@StrTopSalePrice) <> 1)
BEGIN
	SET @ErrMsg = '最高售价请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrTopSalePrice)) <> 0)
BEGIN
	SET @ErrMsg = '最高售价不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @TopSalePrice = CONVERT( NUMERIC(24, 10) , @StrTopSalePrice)
END

DECLARE @LowSalePrice  NUMERIC(24, 10) 
IF (@StrLowSalePrice = '')
BEGIN
	SET @LowSalePrice = 0
END
ELSE IF(ISNUMERIC(@StrLowSalePrice) <> 1)
BEGIN
	SET @ErrMsg = '最低售价请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrLowSalePrice)) <> 0)
BEGIN
	SET @ErrMsg = '最低售价不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @LowSalePrice = CONVERT( NUMERIC(24, 10) , @StrLowSalePrice)
END

IF (@FcPrice = '')
BEGIN
	SET @FcPrice = 0
END
ELSE IF(ISNUMERIC(@FcPrice) <> 1)
BEGIN
	SET @ErrMsg = '请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrLowSalePrice)) <> 0)
BEGIN
	SET @ErrMsg = '不能为负数'
	RETURN -1
END
----------------------------------------------------------------------------------------------
    	
    DECLARE @nReturntype INT,
        @EtypeId_1 [varchar](50),
        @nSoncount INT,
        @nSonnum INT,
        @leveal SMALLINT
declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from Ptype where typeid=@parid)
if(@ParId<>'00000')
begin
--判断停用不能分类
declare @deleted INT
select @deleted=deleted from Ptype where typeId=@Parid
	if(@deleted=1)
		BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已经被停用，不能分类'
			RETURN -1	
			--RAISERROR('该商品【%s】已经被停用，不能分类',16,1,@parFullName)return ---15  
		end
-- 判断库存量（每个仓库）是否为零
    IF EXISTS ( SELECT  ptypeid
                FROM    goodsstocks
                WHERE   ptypeid = @ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	--print'44444444'
			SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
			RETURN -1	
            --RAISERROR('该商品【%s】库存余量不为零，不能分类',16,1,@parFullName)RETURN ---4
        END 
    IF EXISTS ( SELECT  ptypeid
                FROM    inigoodsstocks
                WHERE   ptypeid = @ParId
                        AND (Qty <> 0 OR Total<>0)) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	--print'3333333333'
			SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
			RETURN -1	
            --RAISERROR('该商品【%s】库存余量不为零，不能分类',16,1,@parFullName)return--RETURN -4
        END 

    IF EXISTS ( SELECT  ptypeid
                FROM    wx_goodsstocks
                WHERE   ptypeid = @ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	 --print'222222222'
			SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
			RETURN -1	
            --RAISERROR('该商品【%s】库存余量不为零，不能分类',16,1,@parFullName)return
        END 
    IF EXISTS ( SELECT  ptypeid
                FROM    wx_inigoodsstocks
                WHERE   ptypeid = @ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	       --print'111111'
		   SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
		   RETURN -1	
           --RAISERROR('该商品【%s】库存余量不为零，不能分类',16,1,@parFullName)return
        END 

-- 判断借欠余额
    IF EXISTS ( SELECT  pTypeID
                FROM    V_LendStatus
                WHERE   pTypeID = @ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品有借进借出，不能分类'
			SET @ErrMsg = '该商品【' + @parFullName + '】有借进借出，不能分类'
		    RETURN -1	
            --RAISERROR('该商品【%s】有借进借出，不能分类',16,1,@parFullName)return
        END 
-- 判断经营
    IF EXISTS ( SELECT  pTypeID
                FROM    InOutStockTable
                WHERE   pTypeID = @ParId
                        AND Qty <> 0 )
        OR EXISTS ( SELECT  pTypeID
                    FROM    LendBill
                    WHERE   pTypeID = @ParId
                            AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
			SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
		    RETURN -1	
            --RAISERROR('该商品【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
        END 

	IF EXISTS(	SELECT pTypeID 
				FROM QP_InsuranceBill_PType
				WHERE   pTypeID = @ParId)
	BEGIN
		SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
		RETURN -1	
		--RAISERROR('该商品【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
	END
	
    IF EXISTS ( SELECT  pTypeID
                FROM    Billindex
                WHERE   pTypeID = @ParId ) 
        BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
		    RETURN -1	
            --RAISERROR('该商品【%s】已经经营过，不能分类',16,1,@parFullName)return--return -6
	--print '经营过'
        END
    IF EXISTS ( SELECT  pTypeID
                FROM    OrderBill
                WHERE   pTypeID = @ParId ) 
        BEGIN
		   SET @ErrMsg = '该商品【' + @parFullName + '】已在订单中使用，不能分类'
		   RETURN -1
           --RAISERROR('该商品【%s】已在订单中使用，不能分类',16,1,@parFullName)return--return -501
	--print '订单使用'
        END
    IF EXISTS (SELECT PtypeId FROM	PromotePrice where PtypeId=@ParId )
		BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已在促销中使用，不能分类'
		    RETURN -1
			--RAISERROR('该商品【%s】已在促销中使用，不能分类',16,1,@parFullName) return 
		END
	IF EXISTS (SELECT PtypeId FROM	PriceTrack where PtypeId=@ParId )
		BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已在价格跟踪中使用，不能分类'
		    RETURN -1
			--RAISERROR('该商品【%s】已在价格跟踪中使用，不能分类',16,1,@parFullName) return 
		END
    IF EXISTS ( SELECT  pTypeID
                FROM    RepairEngage
                WHERE   pTypeID = @ParId ) 
        BEGIN
		   SET @ErrMsg = '该商品【' + @parFullName + '】已在维修中使用，不能分类'
		   RETURN -1
           --RAISERROR('该商品【%s】已在维修中使用，不能分类',16,1,@parFullName)return--return -503
	--print '维修使用'
        END
-- 判断代销
    IF EXISTS ( SELECT  pTypeID
                FROM    iniCommissionStock
                WHERE   pTypeID = @ParId
                        AND Qty <> 0 )
        OR EXISTS ( SELECT  pTypeID
                    FROM    CommissionStock
                    WHERE   pTypeID = @ParId
                            AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
			SET @ErrMsg = '该商品【' + @parFullName + '】有代销情况，不能分类'
		    RETURN -1
            --RAISERROR('该商品【%s】有代销情况，不能分类',16,1,@parFullName)return--return -13
        END 
 	IF EXISTS ( SELECT  pTypeID
                FROM    iniCommissionStock
                WHERE   pTypeID = @ParId
                        AND total <> 0 )
        OR EXISTS ( SELECT  pTypeID
                    FROM    CommissionStock
                    WHERE   pTypeID = @ParId
                            AND total <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
		   SET @ErrMsg = '该商品【' + @parFullName + '】有代销情况，不能分类'
		   RETURN -1
           --RAISERROR('该商品【%s】有代销情况，不能分类',16,1,@parFullName)return--return -13
        END 
        IF NOT EXISTS(SELECT typeid FROM dbo.btype WHERE typeid =@BTypeID AND deleted=0) AND @BTypeID<>''
        BEGIN
			SET @ErrMsg = '供应商已被删除或停用'
		    RETURN -1
			--RAISERROR('供应商已被删除或停用！',16,1)RETURN-- -800
		END
--判断序列号
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_CruPtypeSerial
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '住来有序列号，不能分类'
			SET @ErrMsg = '该商品【' + @parFullName + '】有序列号关联情况，不能分类'
		    RETURN -1
            --RAISERROR('该商品【%s】有序列号关联情况，不能分类',16,1,@parFullName)return--return -15
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_initPtypeSerial
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '往来有期初序列号，不能分类'
		   SET @ErrMsg = '该商品【' + @parFullName + '】有期初序列号关联情况，不能分类'
		   RETURN -1
           --RAISERROR('该商品【%s】有期初序列号关联情况，不能分类',16,1,@parFullName)return-- return -16
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    PuserCode
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '设置了多编码，不能分类'
		   SET @ErrMsg = '该商品【' + @parFullName + '】设置了多编码，不能分类'
		   RETURN -1
           --RAISERROR('该商品【%s】设置了多编码，不能分类',16,1,@parFullName)return-- return -17
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_LendPtypeserial
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '商品有借欠序列号，不能分类'
		   SET @ErrMsg = '该商品【' + @parFullName + '】有借欠序列号，不能分类'
		   RETURN -1
           --RAISERROR('该商品【%s】有借欠序列号，不能分类',16,1,@parFullName)return-- return -18
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    produceModel
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '商品有生产模板明细，不能分类'
		    SET @ErrMsg = '该商品【' + @parFullName + '】有生产模板，不能分类'
		    RETURN -1
            --RAISERROR('该商品【%s】有生产模板，不能分类',16,1,@parFullName)return-- return -19
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    produceModelIndex
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '商品有生产模板索引，不能分类'
			SET @ErrMsg = '该商品【' + @parFullName + '】有生产模板，不能分类'
		    RETURN -1
            --RAISERROR('该商品【%s】有生产模板，不能分类',16,1,@parFullName)return-- return -19
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    stockcheck
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '商品有盘点单，不能分类'
		   SET @ErrMsg = '该商品【' + @parFullName + '】有盘点单，不能分类'
		   RETURN -1
           --RAISERROR('该商品【%s】有盘点单，不能分类',16,1,@parFullName)return--return -20
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    dbo.QP_RecycleBill
                WHERE   PTypeID = @ParId ) 
        BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
		    RETURN -1
            --RAISERROR('该商品【%s】已被维修单据使用，不能分类',16,1,@parFullName)return
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_QuickRepairBill_PType
                WHERE   PTypeID = @ParId ) 
        BEGIN
			 SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
		     RETURN -1
             --RAISERROR('该商品【%s】已被维修单据使用，不能分类',16,1,@parFullName)return--RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_EvaluationBill_PType
                WHERE   PTypeID = @ParId ) 
        BEGIN
			 SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
		     RETURN -1
             --RAISERROR('该商品【%s】已被维修单据使用，不能分类',16,1,@parFullName)return--RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    dbo.[QP_EvaluationBill_PType]
                WHERE   PTypeID = @ParId ) 
        BEGIN
			 SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
		     RETURN -1
             --RAISERROR('该商品【%s】已被维修单据使用，不能分类',16,1,@parFullName)return--RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_QuickRepairBill_PType
                WHERE   PTypeID = @ParId ) 
        BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
		    RETURN -1
            --RAISERROR('该商品【%s】已被维修单据使用，不能分类',16,1,@parFullName)return-- RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    IntegralExchangeBill
                WHERE   PTypeID = @ParId ) 
        BEGIN
		   SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
		   RETURN -1
           --RAISERROR('该商品【%s】已被维修单据使用，不能分类',16,1,@parFullName)return--  RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QuotePriceBill
                WHERE   PTypeID = @ParId ) 
        BEGIN
			 SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
		     RETURN -1
             --RAISERROR('该商品【%s】已被维修单据使用，不能分类',16,1,@parFullName)return--RETURN -21
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    AskPriceBill
                WHERE   PTypeID = @ParId ) 
        BEGIN
			 SET @ErrMsg = '该商品【' + @parFullName + '】已被维修单据使用，不能分类'
		     RETURN -1
             --RAISERROR('该商品【%s】已被维修单据使用，不能分类',16,1,@parFullName)return--RETURN -21
        END
    IF EXISTS (SELECT TOP 1 * FROM CargoSpace WHERE PTypeID=@ParId)    
    BEGIN
		 SET @ErrMsg = '该商品【' + @parFullName + '】有货位，不能分类'
		 RETURN -1
		 --RAISERROR('该商品【%s】有货位，不能分类',16,1,@FullName)return--RETURN -22--存在货位
	END
	--判断在分支机构物价信息中使用
	IF EXISTS (SELECT  * FROM PType_STypePrice WHERE PTypeID=@ParId and (PreBuyPrice1<>0 or PreBuyPrice2<>0 or PreBuyPrice3<>0 or PreBuyPrice4<>0 or PreBuyPrice5<>0
	   or PreSalePrice1<>0 or PreSalePrice2<>0 or PreSalePrice3<>0 or PreSalePrice4<>0
	   or PreSalePrice5<>0 or PreSalePrice6<>0 or PreSalePrice7<>0 or PreSalePrice8<>0
	   or PreSalePrice9<>0 or PreSalePrice10<>0 or RetailPrice<>0 or TopSalePrice<>0
	   or LowSalePrice<>0 or RecPrice<>0
	   ))    
    BEGIN
		 SET @ErrMsg = '该商品【' + @parFullName + '】在分支机构物价信息中使用，不能分类'
		 RETURN -1
		 --RAISERROR('该商品【%s】在分支机构物价信息中使用，不能分类',16,1,@parFullName)return--RETURN -22--存在货位
	END
	--商品信息被单据关联禁止分类
DECLARE @TableName varchar(128)
DECLARE @sql nvarchar(1500)
DECLARE Ptype_cursor cursor
	FOR SELECT o.[name] AS tablename FROM syscolumns c inner join sysobjects o ON(c.[id]=o.[id]) WHERE c.[name]='ptypeid' and o.type='u' and o.[name] not in ('PType_STypePrice','PType_Picture','ptype_PicStream')
	FOR read only
OPEN Ptype_cursor
FETCH NEXT FROM Ptype_cursor INTO  @TableName
WHILE @@fetch_status=0
	BEGIN
		 DECLARE @intBeUsed int
		 SET @sql = 'IF EXISTS(SELECT * from  '+ @TableName +' where ptypeid='''+@Parid+''') SELECT @intBeUsed = 1 ELSE SELECT @intBeUsed = 0 '
		 EXECUTE sp_executesql @sql,N'@intBeUsed INT OUTPUT',@intBeUsed OUTPUT

		 IF (@intBeUsed>0 AND @TableName NOT IN('PType_Price','QP_PType_Ext','TCBill'))
			 BEGIN
				--PRINT @TableName	
				--PRINT @sql
				--SELECT @FullName=FullName from ptype where TypeId=@Parid
				--RAISERROR('该商品【%s】已经使用过不允许分类',16,1,@FullName) 
				SET @ErrMsg = '该商品已经使用过不允许分类'
				RETURN -1
				--RAISERROR('该商品已经使用过不允许分类',16,1,@TableName) 
				--RETURN
			 END
		 FETCH NEXT FROM Ptype_cursor INTO  @TableName
	END
Close Ptype_cursor
Deallocate Ptype_cursor
end

    IF EXISTS ( SELECT  PTypeID
                FROM    QP_RepairSetMeal_Fittings
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '设置了维修套餐，不能分类'
            RETURN -36
        END
-- 获得新的ID号
    EXEC @nReturntype= Gp_createId @ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
  if @nReturntype=-1 
BEGIN
	SET @ErrMsg = '商品的分类不能超过10层'
	RETURN -1
	--RAISERROR('商品的分类不能超过10层',16,1)return--return -1
end
if @nReturntype=-2 
BEGIN
	SET @ErrMsg = '无法添加基本信息'
	RETURN -1
	--RAISERROR('无法添加基本信息',16,1)return--return -2
end
-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted <> 1
                           ) ) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
			SET @ErrMsg = '该【' + @FullName + '】已经存在，职员编号或名称不能相同'
		    RETURN -1
            --RAISERROR('该【%s】已经存在，职员编号或名称不能相同',16,1,@FullName)return--return -3
        END
-- 判断已停用的重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted = 1
                           ) ) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
			SET @ErrMsg = '该【' + @FullName + '】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称'
		    RETURN -1
            --RAISERROR('该【%s】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称',16,1,@FullName)return--return -31
        END
        

    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    ptype
    WHERE   typeid = @ParId
    SELECT  @leveal = @leveal + 1
--    DECLARE @returnPym VARCHAR(1000)
--    EXEC @returnPym = ''--fun_getPy @p_fullname
--    IF @p_PyCode <> '' 
--        SET @returnPym = @p_PyCode


	IF NOT EXISTS(SELECT * FROM AutoType WHERE fullname=@Type) AND LTRIM(RTRIM(@Type))<>''
	BEGIN
		INSERT dbo.AutoType (
			fullname,
			comment,
			PYCode
		) VALUES ( @Type,'',@autotypepycode ) 
	END
	
    INSERT  INTO [ptype]
            (
              [typeId],
              [Parid],
              [leveal],
              [soncount],
              [sonnum],
              [FullName],
              [pycode],
              [Name],
              [UserCode],
              [Standard],
              [Type],
              [Area],
              [Unit1],
              [Unit2],
              [Unitrate1],
              [Unitrate2],
              [UsefulLifeMonth],
              [UsefulLifeDay],
              [Comment],
              [ColorGroupID],     -----肖伟2002-6-5 Add For 服装版
              [SizeGroupID],
              [EntryCode],
              [IfSerial],
              [SerialCount],
              [ValidDays],
              [DwgNo],
              [integral],
              [StopBuy]
            )      -----肖伟2002-6-5 Add For 服装版
    VALUES  (
              @EtypeId_1,
              @ParId,
              @leveal,
              0,
              0,
              @fullname,
              @Pycode,
              @Name,
              @UserCode,
              @Standard,
              @Type,
              @Area,
              '', --原有大单位，小单位
              '', --原有大单位，小单位
              0, --原有大单位，小单位
              0,--原有大单位，小单位
              @UsefulLifeMonth,
              @UsefulLifeDay,
              @Comment,
              @ColorGroupID,   -----肖伟2002-6-5 Add For 服装版
              @SizeGroupID,
              @EntryCode,
              @IfSerial,
              @serialcount,
              @ValidDays,
              @dwgno,
              @integral,
              0
            )    -----肖伟2002-6-5 Add For 服装版



    INSERT  ptype_price
            (
              PTypeID,
              PreBuyPrice1,
              PreBuyPrice2,
              PreBuyPrice3,
              PreBuyPrice4,
              PreBuyPrice5,
              TopBuyPrice,
              PreSalePrice1,
              PreSalePrice2,
              PreSalePrice3,
              PreSalePrice4,
              PreSalePrice5,
              PreSalePrice6,
              PreSalePrice7,
              PreSalePrice8,
              PreSalePrice9,
              PreSalePrice10,
              RetailPrice,
              TopSalePrice,
              LowSalePrice
            )
    VALUES  (
              @EtypeId_1,
              @PreBuyPrice1,
              @PreBuyPrice2,
              @PreBuyPrice3,
              @PreBuyPrice4,
              @PreBuyPrice5,
              @TopBuyPrice,
              @PreSalePrice1,
              @PreSalePrice2,
              @PreSalePrice3,
              @PreSalePrice4,
              @PreSalePrice5,
              @PreSalePrice6,
              @PreSalePrice7,
              @PreSalePrice8,
              @PreSalePrice9,
              @PreSalePrice10,
              @RetailPrice,
              @TopSalePrice,
              @LowSalePrice
            )


    INSERT  dbo.QP_PType_Ext
            (
              PTypeID,
              Brand,
              Import,
              GeneralType,
              GeneralDwgNo,
              Property,
              PackageQty,
              Weight,
              TaxNumber,
              Taxrate,
              BTypeID,
              FcUnit,
              FcPrice
            )
    VALUES  (
              @EtypeId_1,
              @Brand,
              @Import,
              @GeneralType,
              @GeneralDwgNo,
              @Property,
              @PackageQty,
              @Weight,
              @TaxNumber,
              @Taxrate,
              @BTypeID,
              @FcUnit,
              @FcPrice
            ) 
 
    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
    ELSE 
        BEGIN
            UPDATE  [ptype]
            SET     sonnum = @nSonnum + 1,
                    soncount = @nSoncount + 1
            WHERE   typeid = @ParId
            UPDATE  Ptype
            SET     preprice1 = 0,
                    preprice2 = 0,
                    preprice3 = 0,
                    preprice4 = 0,
                    preprice5 = 0,
                    SerialCount = 0,
                    recprice = 0
            WHERE   Typeid = @ParId
	--保存大小单位
            IF NOT EXISTS ( SELECT  *
                            FROM    UniteName
                            WHERE   UniteName = @Unit1 )
                AND @Unit1 <> '' 
                BEGIN
                    INSERT  UniteName ( UniteName )
                    VALUES  ( @Unit1 )
                END
            IF NOT EXISTS ( SELECT  *
                            FROM    UniteName
                            WHERE   UniteName = @Unit2 )
                AND @Unit2 <> '' 
                BEGIN
                    INSERT  UniteName ( UniteName )
                    VALUES  ( @Unit2 )
                END
        END

--修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    PType
    UPDATE  PType
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @EtypeId_1

    COMMIT TRAN insertproc


	SET @ReturnID = @@ROWCOUNT



GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Gp_ImportQPP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Gp_ImportQPP]
GO

/****** Object:  StoredProcedure [dbo].[QP_Gp_ImportP]    Script Date: 05/30/2011 15:28:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO









----========================
----修 改 者：廖晨羽
----日    期：2011-12-14
----修改原因：导入配件信息
----修改位置：转换输入参数
----========================
CREATE                    PROCEDURE [dbo].[QP_Gp_ImportQPP]
    ( 
	  @PUserCode [VARCHAR] (201),
      @PFullName   [varchar](201),
      @UserCode [varchar](201),
      @FullName [varchar](201),
      @Pycode	[VARCHAR](201),
      @DwgNo [varchar](201),
      @EntryCode [varchar](201),
      @Name [varchar](201),
      @Brand [varchar](201),
      @Import [varchar](201),
      @Area [varchar](201),
      @Type [varchar](201),
      @GeneralType [varchar](201),
      @GeneralDwgNo [varchar](251),
      @Property [varchar](201),
      @PackageQty [varchar](201),
      @Weight [varchar](201),
      @TaxNumber [varchar](201),
      @Taxrate [varchar](201),
      @BFullName [varchar](201),
      @FcUnit [varchar](201),
      @FcPrice [varchar](201),
      @integral [VARCHAR] (30),
      @Comment [varchar](251),
      @StrPreBuyPrice1 [VARCHAR](18),
      @StrPreBuyPrice2 [VARCHAR](18),
      @StrPreBuyPrice3 [VARCHAR](18),
      @StrPreBuyPrice4 [VARCHAR](18),
      @StrPreBuyPrice5 [VARCHAR](18),
      @StrTopBuyPrice [VARCHAR](18),
      @StrPreSalePrice1 [VARCHAR](18),
      @StrPreSalePrice2 [VARCHAR](18),
      @StrPreSalePrice3 [VARCHAR](18),
      @StrPreSalePrice4 [VARCHAR](18),
      @StrPreSalePrice5 [VARCHAR](18),
      @StrPreSalePrice6 [VARCHAR](18),
      @StrPreSalePrice7 [VARCHAR](18),
      @StrPreSalePrice8 [VARCHAR](18),
      @StrPreSalePrice9 [VARCHAR](18),
      @StrPreSalePrice10 [VARCHAR](18),
      @StrRetailPrice [VARCHAR](18),
      @StrTopSalePrice [VARCHAR](18),
      @StrLowSalePrice [VARCHAR](18),
      @Unit1 [varchar](200),
      @Unit2 [varchar](200),
      @UnitRate1 [varchar](200),
      @ReturnID  VARCHAR(100) output,
	  @ErrMsg VARCHAR(200) OUTPUT,
	  @typeid  [varchar](500)
     )
--@encode$--
AS 
    SET NOCOUNT ON
-------------------------------------转换输入参数---------------------------------------------

DECLARE @dbname		[varchar](30) = 'Ptype'
DECLARE @Standard [varchar](200) = NULL
DECLARE @UnitRate2 [varchar](200) = 0
DECLARE @UsefulLifeMonth [varchar](200)=0
DECLARE @UsefulLifeDay [varchar](200) =0
DECLARE @ColorGroupID [varchar](50) = '0'
DECLARE @SizeGroupID [varchar](50) = '0'
DECLARE @IfSerial [varchar](200) = '0'
DECLARE @SerialCount [varchar](200) = '0'
DECLARE @ValidDays [varchar](200)= 0
DECLARE @autotypepycode [VARCHAR] (max)

IF ((SELECT DATALENGTH(@PUserCode)) > 200)
BEGIN
	SET @ErrMsg = '父类编号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@PFullName)) > 200)
BEGIN
	SET @ErrMsg = '父类名称的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@UserCode)) > 200)
BEGIN
	SET @ErrMsg = '配件编号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@FullName)) > 200)
BEGIN
	SET @ErrMsg = '配件全名的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@DwgNo)) > 200)
BEGIN
	SET @ErrMsg = '图号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@EntryCode)) > 200)
BEGIN
	SET @ErrMsg = '条码的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Name)) > 200)
BEGIN
	SET @ErrMsg = '英文的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Brand)) > 200)
BEGIN
	SET @ErrMsg = '品牌的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Import)) > 200)
BEGIN
	SET @ErrMsg = '进口的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Area)) > 200)
BEGIN
	SET @ErrMsg = '产地的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Type)) > 200)
BEGIN
	SET @ErrMsg = '配件车型的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@GeneralType)) > 200)
BEGIN
	SET @ErrMsg = '通用车型的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@GeneralDwgNo)) > 250)
BEGIN
	SET @ErrMsg = '通用配件的长度大于最大允许长度250'
	RETURN -1
END

IF ((SELECT DATALENGTH(@PackageQty)) > 200)
BEGIN
	SET @ErrMsg = '装包数量的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Weight)) > 200)
BEGIN
	SET @ErrMsg = '重量的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@TaxNumber)) > 200)
BEGIN
	SET @ErrMsg = '关税税号的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Taxrate)) > 200)
BEGIN
	SET @ErrMsg = '关税税率的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@FcUnit)) > 200)
BEGIN
	SET @ErrMsg = '外币单位的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@FcPrice)) > 200)
BEGIN
	SET @ErrMsg = '外币价格的长度大于最大允许长度200'
	RETURN -1
END

IF ((SELECT DATALENGTH(@Comment)) > 200)
BEGIN
	SET @ErrMsg = '备注的长度大于最大允许长度250'
	RETURN -1
END


DECLARE @Parid VARCHAR(50)
IF ((@PFullName = '' AND @PUserCode = '') OR (@PFullName = '全部商品' AND @PUserCode = '0'))
BEGIN
	SET @Parid = '00000'
END
ELSE IF NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE UserCode = @PUserCode)
BEGIN
	SET @ErrMsg = '父类编号不存在'
	RETURN -1
END
ELSE IF NOT EXISTS(SELECT typeId FROM dbo.ptype WHERE FullName = @PFullName)
BEGIN
	SET @ErrMsg = '父类名称不存在'
	RETURN -1
END
ELSE IF(@PFullName <> (SELECT TOP 1 fullname FROM dbo.ptype WHERE UserCode = @PUserCode))
BEGIN
	SET @ErrMsg = '父类编号与父类名称不匹配'
	RETURN -1
END
ELSE
BEGIN
	SET @Parid = (SELECT TOP 1 typeid FROM dbo.ptype WHERE UserCode = @PUserCode)
END

DECLARE @tempdeleted BIT
DECLARE @stopbuy INT
SELECT TOP 1 @tempdeleted = deleted,@stopbuy = stopbuy FROM dbo.ptype WHERE UserCode = @PUserCode
IF(@tempdeleted = 1)
BEGIN
	SET @ErrMsg = '父类配件已停用'
	RETURN -1
END
IF(@stopbuy = 1)
BEGIN
	SET @ErrMsg = '父类配件已停止采购'
	RETURN -1
END

DECLARE @isBtypeAll VARCHAR(50),@isEqualProName VARCHAR(20)  ---分解统一客户供货商和商品同名
SET @isBtypeAll = (SELECT TOP 1 A FROM f_split(@typeid,'я'))
SET @isEqualProName = (SELECT A FROM f_split(@typeid,'я') WHERE A <> @isBtypeAll)
IF (@isEqualProName = 'Enabled')
BEGIN
	IF EXISTS(SELECT TOP 1 typeid FROM dbo.ptype WHERE fullname = @FullName)
	BEGIN
		SET @ErrMsg = '配件名称重复'
		RETURN -1
	END
END

IF(@UserCode = '')
BEGIN
	SET @ErrMsg = '配件编号不能为空'
	RETURN -1
END
ELSE IF((SELECT COUNT(*) FROM dbo.ptype WHERE usercode = @UserCode) > 0)
BEGIN
	SET @ErrMsg = '配件编号已存在'
	RETURN -1
END

IF(@FullName = '')
BEGIN
	SET @ErrMsg = '配件名称不能为空'
	RETURN -1
END

IF(@Pycode = '')
BEGIN
	SELECT @Pycode = dbo.fun_getPY(@FullName)
END

SELECT @Import = CASE @Import 
						   WHEN '' THEN ''
						   WHEN '进口' THEN '1'
						   WHEN '国产' THEN '2'
				END
	
SELECT @Property = CASE @Property 
						   WHEN '配件' THEN '0'
						   WHEN '材料' THEN '1'
						   WHEN '低值易耗品' THEN '2'
				END				

IF (@Weight = '')
BEGIN
	SET @Weight = 0
END
ELSE IF(ISNUMERIC(@Weight) <> 1)
BEGIN
	SET @ErrMsg = '重量请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @Weight)) <> 0)
BEGIN
	SET @ErrMsg = '重量不能为负数'
	RETURN -1
END
IF ((SELECT CONVERT(INT, @Weight)) > 999999999 )
BEGIN
	SET @ErrMsg = '重量最大值为999999999'
	RETURN -1
END

IF (@Taxrate = '')
BEGIN
	SET @Taxrate = 0
END
ELSE IF(ISNUMERIC(@Taxrate) <> 1)
BEGIN
	SET @ErrMsg = '关税税率请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @Taxrate)) <> 0)
BEGIN
	SET @ErrMsg = '关税税率不能为负数'
	RETURN -1
END
IF ((SELECT CONVERT(INT, @Taxrate)) > 999999999 )
BEGIN
	SET @ErrMsg = '关税税率最大值为999999999'
	RETURN -1
END

DECLARE @BTypeID [varchar](200)
IF (@BFullName = '')                                                          
BEGIN
	SET @BTypeID = ''
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 typeid FROM dbo.BType WHERE fullname = @BFullName) OR @BFullName = 'ABC' OR @BFullName = '所有客户' OR @BFullName = '全部供货商'
		BEGIN
			SET @ErrMsg = '供货商不存在'
			RETURN -1
		END
	ELSE
		BEGIN
			DECLARE @PBtypeId VARCHAR(50)
			DECLARE @BChildCount NUMERIC(18,0)
			SET @PBtypeId = (SELECT TOP 1 typeid FROM BType WHERE fullname = @BFullName)
			SELECT @BChildCount = COUNT(*) FROM dbo.BType WHERE typeid LIKE @PBtypeId + '%' AND typeid <> @PBtypeId
			IF (@BChildCount = 0)
				BEGIN
					SET @BTypeID = @PBtypeId
				END
			ELSE
				BEGIN
					SET @ErrMsg = '该供货商为父类'
					RETURN -1
				END	
		END
END
IF(@isBtypeAll = 'False')
BEGIN
	DECLARE @tempBtypeid VARCHAR(200)
	SET @tempBtypeid = SUBSTRING(@BTypeID,1,5)
	IF(@tempBtypeid = '00001')
	BEGIN
			SET @ErrMsg = '供货商不能为客户'
			RETURN -1
	END
END

IF (@FcPrice = '')
BEGIN
	SET @FcPrice = 0
END
ELSE IF(ISNUMERIC(@FcPrice) <> 1)
BEGIN
	SET @ErrMsg = '外币价格请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @FcPrice)) <> 0)
BEGIN
	SET @ErrMsg = '外币价格不能为负数'
	RETURN -1
END
IF ((SELECT CONVERT(INT, @FcPrice)) > 999999999 )
BEGIN
	SET @ErrMsg = '外币价格最大值为999999999'
	RETURN -1
END

IF (@integral = '')
BEGIN
	SET @integral = 0
END
ELSE IF(ISNUMERIC(@integral) <> 1)
BEGIN
	SET @ErrMsg = '兑换积分请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @integral)) <> 0)
BEGIN
	SET @ErrMsg = '兑换积分不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SET @integral =  (SELECT ROUND(@integral,2))
END

DECLARE @PreBuyPrice1  NUMERIC(24, 10) 
IF (@StrPreBuyPrice1 = '')
BEGIN
	SET @PreBuyPrice1 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice1) <> 1)
BEGIN
	SET @ErrMsg = '预设进价1请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice1)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价1不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice1 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice1)
END

DECLARE @PreBuyPrice2  NUMERIC(24, 10) 
IF (@StrPreBuyPrice2 = '')
BEGIN
	SET @PreBuyPrice2 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice2) <> 1)
BEGIN
	SET @ErrMsg = '预设进价2请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice2)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价2不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice2 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice2)
END

DECLARE @PreBuyPrice3  NUMERIC(24, 10) 
IF (@StrPreBuyPrice3 = '')
BEGIN
	SET @PreBuyPrice3 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice3) <> 1)
BEGIN
	SET @ErrMsg = '预设进价3请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice3)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价3不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice3 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice3)
END

DECLARE @PreBuyPrice4  NUMERIC(24, 10) 
IF (@StrPreBuyPrice4 = '')
BEGIN
	SET @PreBuyPrice4 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice4) <> 1)
BEGIN
	SET @ErrMsg = '预设进价4请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice4)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价4不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice4 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice4)
END

DECLARE @PreBuyPrice5  NUMERIC(24, 10) 
IF (@StrPreBuyPrice5 = '')
BEGIN
	SET @PreBuyPrice5 = 0
END
ELSE IF(ISNUMERIC(@StrPreBuyPrice5) <> 1)
BEGIN
	SET @ErrMsg = '预设进价5请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreBuyPrice5)) <> 0)
BEGIN
	SET @ErrMsg = '预设进价5不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreBuyPrice5 = CONVERT( NUMERIC(24, 10) , @StrPreBuyPrice5)
END

DECLARE @TopBuyPrice  NUMERIC(24, 10) 
IF (@StrTopBuyPrice = '')
BEGIN
	SET @TopBuyPrice = 0
END
ELSE IF(ISNUMERIC(@StrTopBuyPrice) <> 1)
BEGIN
	SET @ErrMsg = '最高进价请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrTopBuyPrice)) <> 0)
BEGIN
	SET @ErrMsg = '最高进价不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @TopBuyPrice = CONVERT( NUMERIC(24, 10) , @StrTopBuyPrice)
END

DECLARE @PreSalePrice1  NUMERIC(24, 10) 
IF (@StrPreSalePrice1 = '')
BEGIN
	SET @PreSalePrice1 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice1) <> 1)
BEGIN
	SET @ErrMsg = '预设售价1请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice1)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价1不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice1 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice1)
END

DECLARE @PreSalePrice2  NUMERIC(24, 10) 
IF (@StrPreSalePrice2 = '')
BEGIN
	SET @PreSalePrice2 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice2) <> 1)
BEGIN
	SET @ErrMsg = '预设售价2请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice2)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价2不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice2 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice2)
END

DECLARE @PreSalePrice3  NUMERIC(24, 10) 
IF (@StrPreSalePrice3 = '')
BEGIN
	SET @PreSalePrice3 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice3) <> 1)
BEGIN
	SET @ErrMsg = '预设售价3请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice3)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价3不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice3 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice3)
END

DECLARE @PreSalePrice4  NUMERIC(24, 10) 
IF (@StrPreSalePrice4 = '')
BEGIN
	SET @PreSalePrice4 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice4) <> 1)
BEGIN
	SET @ErrMsg = '预设售价4请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice4)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价4不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice4 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice4)
END

DECLARE @PreSalePrice5  NUMERIC(24, 10) 
IF (@StrPreSalePrice5 = '')
BEGIN
	SET @PreSalePrice5 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice5) <> 1)
BEGIN
	SET @ErrMsg = '预设售价5请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice5)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价5不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice5 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice5)
END

DECLARE @PreSalePrice6  NUMERIC(24, 10) 
IF (@StrPreSalePrice6 = '')
BEGIN
	SET @PreSalePrice6 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice6) <> 1)
BEGIN
	SET @ErrMsg = '预设售价6请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice6)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价6不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice6 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice6)
END

DECLARE @PreSalePrice7  NUMERIC(24, 10) 
IF (@StrPreSalePrice7 = '')
BEGIN
	SET @PreSalePrice7 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice7) <> 1)
BEGIN
	SET @ErrMsg = '预设售价7请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice7)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价7不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice7 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice7)
END

DECLARE @PreSalePrice8  NUMERIC(24, 10) 
IF (@StrPreSalePrice8 = '')
BEGIN
	SET @PreSalePrice8 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice8) <> 1)
BEGIN
	SET @ErrMsg = '预设售价8请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice8)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价8不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice8 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice8)
END

DECLARE @PreSalePrice9  NUMERIC(24, 10) 
IF (@StrPreSalePrice9 = '')
BEGIN
	SET @PreSalePrice9 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice9) <> 1)
BEGIN
	SET @ErrMsg = '预设售价9请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice9)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价9不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice9 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice9)
END

DECLARE @PreSalePrice10  NUMERIC(24, 10) 
IF (@StrPreSalePrice10 = '')
BEGIN
	SET @PreSalePrice10 = 0
END
ELSE IF(ISNUMERIC(@StrPreSalePrice10) <> 1)
BEGIN
	SET @ErrMsg = '预设售价10请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrPreSalePrice10)) <> 0)
BEGIN
	SET @ErrMsg = '预设售价10不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @PreSalePrice10 = CONVERT( NUMERIC(24, 10) , @StrPreSalePrice10)
END

DECLARE @RetailPrice  NUMERIC(24, 10) 
IF (@StrRetailPrice = '')
BEGIN
	SET @RetailPrice = 0
END
ELSE IF(ISNUMERIC(@StrRetailPrice) <> 1)
BEGIN
	SET @ErrMsg = '零售价请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrRetailPrice)) <> 0)
BEGIN
	SET @ErrMsg = '零售价不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @RetailPrice = CONVERT( NUMERIC(24, 10) , @StrRetailPrice)
END

DECLARE @TopSalePrice  NUMERIC(24, 10) 
IF (@StrTopSalePrice = '')
BEGIN
	SET @TopSalePrice = 0
END
ELSE IF(ISNUMERIC(@StrTopSalePrice) <> 1)
BEGIN
	SET @ErrMsg = '最高售价请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrTopSalePrice)) <> 0)
BEGIN
	SET @ErrMsg = '最高售价不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @TopSalePrice = CONVERT( NUMERIC(24, 10) , @StrTopSalePrice)
END

DECLARE @LowSalePrice  NUMERIC(24, 10) 
IF (@StrLowSalePrice = '')
BEGIN
	SET @LowSalePrice = 0
END
ELSE IF(ISNUMERIC(@StrLowSalePrice) <> 1)
BEGIN
	SET @ErrMsg = '最低售价请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @StrLowSalePrice)) <> 0)
BEGIN
	SET @ErrMsg = '最低售价不能为负数'
	RETURN -1
END
ELSE
BEGIN
	SELECT @LowSalePrice = CONVERT( NUMERIC(24, 10) , @StrLowSalePrice)
END

IF ((SELECT LEN(@Unit1)) >8)
BEGIN
	SET @ErrMsg = '小单位字符长度不能超过8个'
	RETURN -1
END

IF ((SELECT LEN(@Unit2)) >8)
BEGIN
	SET @ErrMsg = '大单位字符长度不能超过8个'
	RETURN -1
END

IF (@Unit1 = @Unit2 AND @Unit1 <> '' AND @unit2 <> '')
BEGIN
	SET @ErrMsg = '大小单位不能完全相同'
	RETURN -1
END

IF (@Unit1 <> '' AND @Unit2 <> '' AND @UnitRate1 = '')
BEGIN
	SET @ErrMsg = '设置了大小单位，换算关系不能为空'
	RETURN -1
END

IF(@Unit1 = '' AND @Unit2 <> '')
BEGIN
	SET @ErrMsg = '必须设置小单位才能设置大单位'
	RETURN -1
END

IF (@UnitRate1 = '')
BEGIN
	SET @UnitRate1 = 0
END
ELSE IF (@Unit1 = '' OR @Unit2 = '')
BEGIN
	SET @ErrMsg = '大小单位不能为空'
	RETURN -1
END
ELSE IF(ISNUMERIC(@UnitRate1) <> 1)
BEGIN
	SET @ErrMsg = '换算关系请输入数字'
	RETURN -1
END
ELSE IF((SELECT CHARINDEX('-', @UnitRate1)) <> 0)
BEGIN
	SET @ErrMsg = '换算关系不能为负数'
	RETURN -1
END

SELECT @autotypepycode = dbo.fun_getPY(@Type)
		

----------------------------------------------------------------------------------------------    
    	
    DECLARE @nReturntype INT,
        @EtypeId_1 [varchar](50),
        @nSoncount INT,
        @nSonnum INT,
        @leveal SMALLINT
declare @parFullName varchar(200)
set @parFullName=(select top 1 fullname from Ptype where typeid=@parid)
if(@ParId<>'00000')
begin
--判断停用不能分类
declare @deleted INT
select @deleted=deleted from Ptype where typeId=@Parid
	if(@deleted=1)
		begin
			SET @ErrMsg = '该商品【' + @parFullName + '】已经被停用，不能分类'
			RETURN -1
		end
-- 判断库存量（每个仓库）是否为零
    IF EXISTS ( SELECT  ptypeid
                FROM    goodsstocks
                WHERE   ptypeid = @ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	--print'44444444'
            SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
			RETURN -1	
        END 
    IF EXISTS ( SELECT  ptypeid
                FROM    inigoodsstocks
                WHERE   ptypeid = @ParId
                        AND (Qty <> 0 OR Total<>0)) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	--print'3333333333'
            SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
			RETURN -1	
        END 

    IF EXISTS ( SELECT  ptypeid
                FROM    wx_goodsstocks
                WHERE   ptypeid = @ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	 --print'222222222'
            SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
			RETURN -1	
        END 
    IF EXISTS ( SELECT  ptypeid
                FROM    wx_inigoodsstocks
                WHERE   ptypeid = @ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品库存余量不为零，不能分类'
	       --print'111111'
           SET @ErrMsg = '该商品【' + @parFullName + '】库存余量不为零，不能分类'
		   RETURN -1
        END 

-- 判断借欠余额
    IF EXISTS ( SELECT  pTypeID
                FROM    V_LendStatus
                WHERE   pTypeID = @ParId
                        AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品有借进借出，不能分类'
            SET @ErrMsg = '该商品【' + @parFullName + '】有借进借出，不能分类'
		    RETURN -1	
        END 
-- 判断经营
    IF EXISTS ( SELECT  pTypeID
                FROM    InOutStockTable
                WHERE   pTypeID = @ParId
                        AND Qty <> 0 )
        OR EXISTS ( SELECT  pTypeID
                    FROM    LendBill
                    WHERE   pTypeID = @ParId
                            AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
            SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
		    RETURN -1	
        END 

	IF EXISTS(	SELECT pTypeID 
				FROM QP_InsuranceBill_PType
				WHERE   pTypeID = @ParId)
	BEGIN
		SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
		RETURN -1	
	END
	
    IF EXISTS ( SELECT  pTypeID
                FROM    Billindex
                WHERE   pTypeID = @ParId ) 
        BEGIN
            SET @ErrMsg = '该商品【' + @parFullName + '】已经经营过，不能分类'
		    RETURN -1	
	--print '经营过'
        END
    IF EXISTS ( SELECT  pTypeID
                FROM    OrderBill
                WHERE   pTypeID = @ParId ) 
        BEGIN
           SET @ErrMsg = '该商品【' + @parFullName + '】已在订单中使用，不能分类'
		   RETURN -1
	--print '订单使用'
        END
    IF EXISTS (SELECT PtypeId FROM	PromotePrice where PtypeId=@ParId )
		BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已在促销中使用，不能分类'
		    RETURN -1
		END
	--pos
	    IF EXISTS (SELECT PtypeId FROM	CommonPosSaleList  where PtypeId=@ParId )
	    OR EXISTS (SELECT PtypeId FROM	CommonPosPtypeCheckList  where PtypeId=@ParId )
	    OR EXISTS (SELECT PtypeId FROM	CX_CombinationDetailBill  where PtypeId=@ParId )
	    OR EXISTS (SELECT PtypeId FROM	CX_LargessBill  where PtypeId=@ParId )
	    OR EXISTS (SELECT PtypeId FROM	CX_SpecialOfferBill  where PtypeId=@ParId )
		BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已在pos中使用，不能分类'
		END
	IF EXISTS (SELECT PtypeId FROM	PriceTrack where PtypeId=@ParId )
		BEGIN
			SET @ErrMsg = '该商品【' + @parFullName + '】已在价格跟踪中使用，不能分类'
		    RETURN -1
		END
    IF EXISTS ( SELECT  pTypeID
                FROM    RepairEngage
                WHERE   pTypeID = @ParId ) 
        BEGIN
           SET @ErrMsg = '该商品【' + @parFullName + '】已在维修中使用，不能分类'
		   RETURN -1
	--print '维修使用'
        END
-- 判断代销
    IF EXISTS ( SELECT  pTypeID
                FROM    iniCommissionStock
                WHERE   pTypeID = @ParId
                        AND Qty <> 0 )
        OR EXISTS ( SELECT  pTypeID
                    FROM    CommissionStock
                    WHERE   pTypeID = @ParId
                            AND Qty <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
            SET @ErrMsg = '该商品【' + @parFullName + '】有代销情况，不能分类'
		    RETURN -1
        END 
 	IF EXISTS ( SELECT  pTypeID
                FROM    iniCommissionStock
                WHERE   pTypeID = @ParId
                        AND total <> 0 )
        OR EXISTS ( SELECT  pTypeID
                    FROM    CommissionStock
                    WHERE   pTypeID = @ParId
                            AND total <> 0 ) 
        BEGIN
	--print '['+@FullName+']商品已经经营过，不能分类'
           SET @ErrMsg = '该商品【' + @parFullName + '】有代销情况，不能分类'
		   RETURN -1
        END 
        IF NOT EXISTS(SELECT typeid FROM dbo.btype WHERE typeid =@BTypeID AND deleted=0) AND @BTypeID<>''
        BEGIN
			SET @ErrMsg = '供应商已被删除或停用'
		    RETURN -1
		END
--判断序列号
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_CruPtypeSerial
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '住来有序列号，不能分类'
            SET @ErrMsg = '该商品【' + @parFullName + '】有序列号关联情况，不能分类'
		    RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_initPtypeSerial
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '往来有期初序列号，不能分类'
           SET @ErrMsg = '该商品【' + @parFullName + '】有期初序列号关联情况，不能分类'
		   RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    PuserCode
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '设置了多编码，不能分类'
           SET @ErrMsg = '该商品【' + @parFullName + '】设置了多编码，不能分类'
		   RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    gp_LendPtypeserial
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '商品有借欠序列号，不能分类'
           SET @ErrMsg = '该商品【' + @parFullName + '】有借欠序列号，不能分类'
		   RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    produceModel
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '商品有生产模板明细，不能分类'
            SET @ErrMsg = '该商品【' + @parFullName + '】有生产模板，不能分类'
		    RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    produceModelIndex
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '商品有生产模板索引，不能分类'
            SET @ErrMsg = '该商品【' + @parFullName + '】有生产模板，不能分类'
		    RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    stockcheck
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '商品有盘点单，不能分类'
           SET @ErrMsg = '该商品【' + @parFullName + '】有盘点单，不能分类'
		   RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    dbo.QP_RecycleBill
                WHERE   PTypeID = @ParId ) 
        BEGIN
            SET @ErrMsg = '该商品【'+ @parFullName+'】已被旧件回收单使用，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    dbo.[QP_EvaluationBill_PType]
                WHERE   PTypeID = @ParId ) 
        BEGIN
			 SET @ErrMsg = '该商品【'+ @parFullName+'】已被备料估价单使用，不能分类'
             RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_QuickRepairBill_PType
                WHERE   PTypeID = @ParId ) 
        BEGIN
			SET @ErrMsg = '该商品【'+ @parFullName+'】已被快修单使用，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    IntegralExchangeBill
                WHERE   PTypeID = @ParId ) 
        BEGIN
			SET @ErrMsg = '该商品【'+ @parFullName+'】已被关联积分兑换，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    QuotePriceBill
                WHERE   PTypeID = @ParId ) 
        BEGIN
			SET @ErrMsg = '该商品【'+ @parFullName+'】已被报价单使用，不能分类'
            RETURN -1
        END
    IF EXISTS ( SELECT  PTypeID
                FROM    AskPriceBill
                WHERE   PTypeID = @ParId ) 
        BEGIN
			SET @ErrMsg = '该商品【'+ @parFullName+'】已被询价单使用，不能分类'
            RETURN -1
        END
    IF EXISTS (SELECT TOP 1 * FROM CargoSpace WHERE PTypeID=@ParId)    
    BEGIN
		SET @ErrMsg = '该商品【'+ @parFullName+'】有货位，不能分类'
        RETURN -1
	END
	--判断在分支机构物价信息中使用
	IF EXISTS (SELECT  * FROM PType_STypePrice WHERE PTypeID=@ParId and (PreBuyPrice1<>0 or PreBuyPrice2<>0 or PreBuyPrice3<>0 or PreBuyPrice4<>0 or PreBuyPrice5<>0
	   or PreSalePrice1<>0 or PreSalePrice2<>0 or PreSalePrice3<>0 or PreSalePrice4<>0
	   or PreSalePrice5<>0 or PreSalePrice6<>0 or PreSalePrice7<>0 or PreSalePrice8<>0
	   or PreSalePrice9<>0 or PreSalePrice10<>0 or RetailPrice<>0 or TopSalePrice<>0
	   or LowSalePrice<>0 or RecPrice<>0
	   ))    
    BEGIN
		SET @ErrMsg = '该商品【'+ @parFullName+'】在物价信息中使用，不能分类'
        RETURN -1
	END
	--商品信息被单据关联禁止分类
DECLARE @TableName varchar(128)
DECLARE @sql nvarchar(1500)
DECLARE Ptype_cursor cursor
	FOR SELECT o.[name] AS tablename FROM syscolumns c inner join sysobjects o ON(c.[id]=o.[id]) WHERE c.[name]='ptypeid' and o.type='u' and o.[name] not in ('PType_STypePrice','PType_Picture','ptype_PicStream')
	FOR read only
OPEN Ptype_cursor
FETCH NEXT FROM Ptype_cursor INTO  @TableName
WHILE @@fetch_status=0
	BEGIN
		 DECLARE @intBeUsed int
		 SET @sql = 'IF EXISTS(SELECT * from  '+ @TableName +' where ptypeid='''+@Parid+''') SELECT @intBeUsed = 1 ELSE SELECT @intBeUsed = 0 '
		 EXECUTE sp_executesql @sql,N'@intBeUsed INT OUTPUT',@intBeUsed OUTPUT
		 
		 IF (@intBeUsed>0 AND @TableName NOT IN('PType_Price','QP_PType_Ext','TCBill'))
			 BEGIN
				--PRINT @TableName	
				--PRINT @sql
				--SELECT @FullName=FullName from ptype where TypeId=@Parid
				--RAISERROR('该商品【%s】已经使用过不允许分类',16,1,@FullName) 
				SET @ErrMsg = '该商品已经使用过不允许分类'
				RETURN -1
			 END
		 FETCH NEXT FROM Ptype_cursor INTO  @TableName
	END
Close Ptype_cursor
Deallocate Ptype_cursor
end

    IF EXISTS ( SELECT  PTypeID
                FROM    QP_RepairSetMeal_Fittings
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '设置了维修套餐，不能分类'
            RETURN -36
        END
-- 获得新的ID号
    EXEC @nReturntype= Gp_createId @ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
  if @nReturntype=-1 
BEGIN
	SET @ErrMsg = '商品的分类不能超过10层'
	RETURN -1
end
if @nReturntype=-2 
BEGIN
	SET @ErrMsg = '无法添加基本信息'
	RETURN -1
end
-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted <> 1
                           ) ) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
			SET @ErrMsg = '该【'+@FullName+'】已经存在，职员编号或名称不能相同'
			RETURN -1
        END
-- 判断已停用的重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted = 1
                           ) ) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
			SET @ErrMsg = '该【'+@FullName+'】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称'
			RETURN -1
        END
        

    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    ptype
    WHERE   typeid = @ParId
    SELECT  @leveal = @leveal + 1
--    DECLARE @returnPym VARCHAR(1000)
--    EXEC @returnPym = ''--fun_getPy @p_fullname
--    IF @p_PyCode <> '' 
--        SET @returnPym = @p_PyCode


	IF NOT EXISTS(SELECT * FROM AutoType WHERE fullname=@Type) AND LTRIM(RTRIM(@Type))<>''
	BEGIN
		INSERT dbo.AutoType (
			fullname,
			comment,
			PYCode
		) VALUES ( @Type,'',@autotypepycode ) 
	END
	
    INSERT  INTO [ptype]
            (
              [typeId],
              [Parid],
              [leveal],
              [soncount],
              [sonnum],
              [FullName],
              [pycode],
              [Name],
              [UserCode],
              [Standard],
              [Type],
              [Area],
              [Unit1],
              [Unit2],
              [Unitrate1],
              [Unitrate2],
              [UsefulLifeMonth],
              [UsefulLifeDay],
              [Comment],
              [ColorGroupID],     -----肖伟2002-6-5 Add For 服装版
              [SizeGroupID],
              [EntryCode],
              [IfSerial],
              [SerialCount],
              [ValidDays],
              [DwgNo],
              [integral],
              [StopBuy]
            )      -----肖伟2002-6-5 Add For 服装版
    VALUES  (
              @EtypeId_1,
              @ParId,
              @leveal,
              0,
              0,
              @fullname,
              @Pycode,
              @Name,
              @UserCode,
              @Standard,
              @Type,
              @Area,
              @Unit1,
              @Unit2,
              ISNULL(@UnitRate1,0),
              @UnitRate2,
              @UsefulLifeMonth,
              @UsefulLifeDay,
              @Comment,
              @ColorGroupID,   -----肖伟2002-6-5 Add For 服装版
              @SizeGroupID,
              @EntryCode,
              @IfSerial,
              @serialcount,
              @ValidDays,
              @dwgno,
              @integral,
              0
            )    -----肖伟2002-6-5 Add For 服装版



    INSERT  ptype_price
            (
              PTypeID,
              PreBuyPrice1,
              PreBuyPrice2,
              PreBuyPrice3,
              PreBuyPrice4,
              PreBuyPrice5,
              TopBuyPrice,
              PreSalePrice1,
              PreSalePrice2,
              PreSalePrice3,
              PreSalePrice4,
              PreSalePrice5,
              PreSalePrice6,
              PreSalePrice7,
              PreSalePrice8,
              PreSalePrice9,
              PreSalePrice10,
              RetailPrice,
              TopSalePrice,
              LowSalePrice
            )
    VALUES  (
              @EtypeId_1,
              @PreBuyPrice1,
              @PreBuyPrice2,
              @PreBuyPrice3,
              @PreBuyPrice4,
              @PreBuyPrice5,
              @TopBuyPrice,
              @PreSalePrice1,
              @PreSalePrice2,
              @PreSalePrice3,
              @PreSalePrice4,
              @PreSalePrice5,
              @PreSalePrice6,
              @PreSalePrice7,
              @PreSalePrice8,
              @PreSalePrice9,
              @PreSalePrice10,
              @RetailPrice,
              @TopSalePrice,
              @LowSalePrice
            )


    INSERT  dbo.QP_PType_Ext
            (
              PTypeID,
              Brand,
              Import,
              GeneralType,
              GeneralDwgNo,
              Property,
              PackageQty,
              Weight,
              TaxNumber,
              Taxrate,
              BTypeID,
              FcUnit,
              FcPrice
            )
    VALUES  (
              @EtypeId_1,
              @Brand,
              @Import,
              @GeneralType,
              @GeneralDwgNo,
              @Property,
              @PackageQty,
              @Weight,
              @TaxNumber,
              @Taxrate,
              @BTypeID,
              @FcUnit,
              @FcPrice
            ) 
 

    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
    ELSE 
        BEGIN
            UPDATE  [ptype]
            SET     sonnum = @nSonnum + 1,
                    soncount = @nSoncount + 1
            WHERE   typeid = @ParId
            UPDATE  Ptype
            SET     preprice1 = 0,
                    preprice2 = 0,
                    preprice3 = 0,
                    preprice4 = 0,
                    preprice5 = 0,
                    SerialCount = 0,
                    recprice = 0
            WHERE   Typeid = @ParId
	--保存大小单位
            IF NOT EXISTS ( SELECT  *
                            FROM    UniteName
                            WHERE   UniteName = @Unit1 )
                AND @Unit1 <> '' 
                BEGIN
                    INSERT  UniteName ( UniteName )
                    VALUES  ( @Unit1 )
                END
            IF NOT EXISTS ( SELECT  *
                            FROM    UniteName
                            WHERE   UniteName = @Unit2 )
                AND @Unit2 <> '' 
                BEGIN
                    INSERT  UniteName ( UniteName )
                    VALUES  ( @Unit2 )
                END
        END

--修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    PType
    UPDATE  PType
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @EtypeId_1

    COMMIT TRAN insertproc



	SET @ReturnID = @@ROWCOUNT



GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[QP_Gp_InsertP]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[QP_Gp_InsertP]
GO

/****** Object:  StoredProcedure [dbo].[QP_Gp_InsertP]    Script Date: 05/30/2011 15:28:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

----========================
----修改者：谢吉康
----日期：2003-03-10
----描述：增加序列号强制管理

----修 改 者：李小虎
----日    期：2011-03-25
----修改原因：促销中使用了商品信息，因此不能被分类
----修改位置：商品分类前的判断

----修 改 者：吕文祺
----日    期：2012-04-12
----修改原因：商品基本信息增加字段（自由项Id 自由项来源 自由项名称）
----修改位置：Ptype插入时


----修 改 者：舒珊
----日    期：2016-05-22
----修改原因：商品基本信息增加字段（商品类别）
----修改位置：Ptype插入时


----修 改 者：魏伟
----日    期：2016-06-12
----修改原因：商品基本信息增加字段（存货类型）
----修改位置：Ptype插入时
----========================
CREATE	PROCEDURE	[dbo].[QP_Gp_InsertP]
  (
      @customitemid [VARCHAR](20)='',
      @customitemfrom [VARCHAR](20)='',
      @customitemname [VARCHAR](max)='',
      @customitemrefid [VARCHAR](max)='',
      @dbname [VARCHAR](30),
      @ParId [varchar](50),
      @UserCode [varchar](200),
      @FullName [varchar](200),
      @Pycode	[VARCHAR](200),
      @Name [varchar](200),
      @Standard [varchar](200),
      @Type [varchar](200),
      @Area [varchar](200),
      @UnitsType INT,
      @UnitRate1 [varchar](200),
      @UnitRate2 [varchar](200),
      @UsefulLifeMonth [varchar](200),
      @UsefulLifeDay [varchar](200),
      @Comment [varchar](250),
      @ColorGroupID [varchar](50),
      @SizeGroupID [varchar](50),
      @EntryCode [varchar](200),
      @IfSerial [varchar](200),
      @SerialCount [varchar](200),
      @ValidDays [varchar](200),
      @DwgNo [varchar](200),
      @PreBuyPrice1  NUMERIC(24, 10) ,
      @PreBuyPrice2  NUMERIC(24, 10) ,
      @PreBuyPrice3  NUMERIC(24, 10) ,
      @PreBuyPrice4  NUMERIC(24, 10) ,
      @PreBuyPrice5  NUMERIC(24, 10) ,
      @TopBuyPrice  NUMERIC(24, 10) ,
      @PreSalePrice1  NUMERIC(24, 10) ,
      @PreSalePrice2  NUMERIC(24, 10) ,
      @PreSalePrice3  NUMERIC(24, 10) ,
      @PreSalePrice4  NUMERIC(24, 10) ,
      @PreSalePrice5  NUMERIC(24, 10) ,
      @PreSalePrice6  NUMERIC(24, 10) ,
      @PreSalePrice7  NUMERIC(24, 10) ,
      @PreSalePrice8  NUMERIC(24, 10) ,
      @PreSalePrice9  NUMERIC(24, 10) ,
      @PreSalePrice10  NUMERIC(24, 10) ,
      @RetailPrice  NUMERIC(24, 10) ,
      @TopSalePrice  NUMERIC(24, 10) ,
      @LowSalePrice  NUMERIC(24, 10) ,
      @Brand [varchar](200),
      @Import [varchar](200),
      @GeneralType [varchar](200),
      @GeneralDwgNo [varchar](250),
      @Property [varchar](200),
      @PackageQty [varchar](200),
      @Weight [varchar](200),
      @TaxNumber [varchar](200),
      @Taxrate [varchar](200),
      @BTypeID [varchar](200),
      @FcUnit [varchar](200),
      @FcPrice [varchar](200),
      @integral [VARCHAR] (30),
      @autotypepycode [VARCHAR] (max),
      @baseUnitid		VARCHAR(20),
      @StockUnitId		VARCHAR(20),
      @BuyUnitId		VARCHAR(20),
      @SaleUnitId		VARCHAR(20),
      @AssistantUnitId  VARCHAR(20),
      @ProduceUnitId	VARCHAR(20),
      @IfUseEntryCode	INT,
      @IfUseGoodsNum	INT,
      @isservice		INT,
      @sortid			INT,
      @Omuse			BIT,
      @omprice           NUMERIC(24, 10) ,
      @BuyDefaultRate	 NUMERIC(24, 10) ,
      @SaleDefaultRate	 NUMERIC(24, 10) ,
      @PtypeCategoryID VARCHAR(50), 
      @InventoryTypeID VARCHAR(50),
      @iscombinationproduct INT,
      @IsScaleWeight	BIT = 0,
      @ScaleWeightType	INT = 0  ,
      @Pweight			NUMERIC(24, 10)=null,--重量 前面weight 参数 区分开
      @volume			NUMERIC(24, 10)=NULL,
      @PtypeBrandarID	VARCHAR(50)='',			--商品品牌
      @othercomment1	VARCHAR(250)='',		--其他备注
      @othercomment2	VARCHAR(250)='',		--其他备注
      @othercomment3	VARCHAR(250)='',		--其他备注
      @othercomment4	VARCHAR(250)='',		--其他备注
      @othercomment5	VARCHAR(250)='',		--其他备注
      @yjkptype			VARCHAR(200)=''			--易聚客开票品名
     )
--@encode$--
AS 
    SET NOCOUNT ON
    
    	
    DECLARE @nReturntype INT,
        @EtypeId_1 [varchar](50),
        @nSoncount INT,
        @nSonnum INT,
        @leveal SMALLINT
declare @parFullName varchar(200)
set @parFullName=(SELECT top 1 fullname FROM Ptype WHERE typeid=@parid)

--能否分类判断
IF @ParId<>'00000'
BEGIN
	DECLARE @erromsg VARCHAR(MAX)
	--分类判断
	BEGIN TRY
		IF EXISTS(SELECT TOP 1 1 FROM ptype WHERE typeId=@ParId AND sonnum=0)
			EXEC Gp_BaseInfoCheck 'ptype',@parid,'0'
	END TRY
	BEGIN CATCH
		SELECT @erromsg=ERROR_MESSAGE()
		RAISERROR('%s',16,1,@erromsg)RETURN
	END CATCH
END
    IF EXISTS ( SELECT  PTypeID
                FROM    QP_RepairSetMeal_Fittings
                WHERE   PTypeID = @ParId ) 
        BEGIN
	--print '设置了维修套餐，不能分类'
            RETURN -36
        END
-- 获得新的ID号
    EXEC @nReturntype= Gp_createId @ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
        
  IF @nReturntype=-1 
begin
	RAISERROR('商品的分类不能超过10层',16,1)return--return -1
end
IF @nReturntype=-2 
BEGIN
	RAISERROR('无法添加基本信息',16,1)return--return -2
END
IF EXISTS(SELECT TOP 1 1 FROM dbo.HR_Person WHERE name = '00004' AND password = 'GJHJYRq9Rg8=')
BEGIN
	RAISERROR('无法添加基本信息',16,1)return--return -2
END
-- 判断UserCode是否重复
IF EXISTS(SELECT TypeID FROM [ptype] WHERE usercode=@usercode )
BEGIN
	--print '['+@usercode+']商品已存在'
	RAISERROR('该【%s】编号已经存在，商品编号不能重复, 请填写新的编号',16,1,@usercode)RETURN--RETURN -3
END

-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted <> 1
                           ) ) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
            RAISERROR('该【%s】已经存在，商品编号或名称不能相同',16,1,@FullName)return--return -3
        END
-- 判断已停用的重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [ptype]
                WHERE   typeId = @EtypeId_1
                        OR ( usercode = @UserCode
                             AND deleted = 1
                           ) ) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
            RAISERROR('该【%s】的编号或名称已被已停用的职员使用，请更换或删除该停用的编号或名称',16,1,@FullName)return--return -31
        END

    BEGIN TRAN insertproc
    SELECT  @leveal = leveal
    FROM    ptype
    WHERE   typeid = @ParId
    SELECT  @leveal = @leveal + 1
--    DECLARE @returnPym VARCHAR(1000)
--    EXEC @returnPym = ''--fun_getPy @p_fullname
--    IF @p_PyCode <> '' 
--        SET @returnPym = @p_PyCode


	IF NOT EXISTS(SELECT * FROM AutoType WHERE fullname=@Type) AND LTRIM(RTRIM(@Type))<>''
	BEGIN
		INSERT dbo.AutoType (
			fullname,
			comment,
			PYCode
		) VALUES ( @Type,'',@autotypepycode ) 
	END
	
	DECLARE @Temp_baseUnitid	INT,
			@Temp_StockUnitId	INT,
			@Temp_BuyUnitId		INT,
			@Temp_SaleUnitId	INT,
			@Temp_AssistantUnitId	INT,
			@Temp_ProduceUnitId		INT
			
	IF @baseUnitid = ''
		SET @Temp_baseUnitid = NULL
	ELSE
		SET @Temp_baseUnitid = CONVERT(INT, @baseUnitid)
		
	IF @StockUnitId = ''
		SET @Temp_StockUnitId = @Temp_baseUnitid
	ELSE
		SET @Temp_StockUnitId = CONVERT(INT, @StockUnitId)
		
	IF @BuyUnitId = ''
		SET @Temp_BuyUnitId = @Temp_baseUnitid
	ELSE
		SET @Temp_BuyUnitId = CONVERT(INT, @BuyUnitId)
		
	IF @SaleUnitId = ''
		SET @Temp_SaleUnitId = @Temp_baseUnitid
	ELSE
		SET @Temp_SaleUnitId = CONVERT(INT, @SaleUnitId)
		
	IF @AssistantUnitId = ''
		SET @Temp_AssistantUnitId = NULL
	ELSE
		SET @Temp_AssistantUnitId = CONVERT(INT, @AssistantUnitId)
	
	IF @ProduceUnitId = ''
		SET @Temp_ProduceUnitId = @Temp_baseUnitid
	ELSE
		SET @Temp_ProduceUnitId = CONVERT(INT, @ProduceUnitId)
	
	--并发控制 ,判断typeid是否重复
	IF EXISTS(SELECT TOP 1 1 FROM ptype WHERE typeId=@EtypeId_1)
	BEGIN
		RAISERROR('该【%s】已经存在，请重新保存',16,1,@FullName)
		RETURN
	END 
    INSERT  INTO [ptype]
            (
              [typeId],
              [Parid],
              [leveal],
              [soncount],
              [sonnum],
              [FullName],
              [pycode],
              [Name],
              [UserCode],
              [Standard],
              [Type],
              [Area],
              [UnitsType],  --基本单位类型
              [Unitrate1],
              [Unitrate2],
              [UsefulLifeMonth],
              [UsefulLifeDay],
              [Comment],
              [ColorGroupID],     -----肖伟2002-6-5 Add For 服装版
              [SizeGroupID],
              [EntryCode],
              [IfSerial],
              [SerialCount],
              [ValidDays],
              [DwgNo],
              [integral],
              [StopBuy],
              [customitemid],
              [customitemfrom],
              [customitemname],
              [customitemrefid],
              [baseUnitid],
			  [StockUnitId],
			  [BuyUnitId],
              [SaleUnitId],
              [AssistantUnitId],
              [ProduceUnitId],
              [IfUseEntryCode],
              [IfUseGoodsNum],
              [createdate],
              [IsService],
              [sortid],
               [Omuse],
			  [omprice],
			  [BuyDefaultRate],
			  [SaleDefaultRate] ,
			  [PtypeCategoryID], 
			  [InventoryTypeID],
			  iscombinationproduct,
			  isscaleweight,
			  scaleweighttype,
			  [weight],
			  [volume],
			  [BrandarTypeID],
			  [CanModify],
			  othercomment1,
			  othercomment2,
			  othercomment3,
			  othercomment4,
			  othercomment5,
			  yjkptype
            )      -----肖伟2002-6-5 Add For 服装版
    VALUES  (
              @EtypeId_1,
              @ParId,
              @leveal,
              0,
              0,
              @fullname,
              @Pycode,
              @Name,
              @UserCode,
              @Standard,
              @Type,
              @Area,
              @UnitsType,
              ISNULL(@UnitRate1,0),
              @UnitRate2,
              @UsefulLifeMonth,
              @UsefulLifeDay,
              @Comment,
              @ColorGroupID,   -----肖伟2002-6-5 Add For 服装版
              @SizeGroupID,
              @EntryCode,
              @IfSerial,
              @serialcount,
              @ValidDays,
              @dwgno,
              @integral,
              0,
              @customitemid,
              @customitemfrom ,
              @customitemname,
              @customitemrefid,
              @Temp_baseUnitid,
			  @Temp_StockUnitId,
			  @Temp_BuyUnitId,
			  @Temp_SaleUnitId,
			  @Temp_AssistantUnitId,
              @Temp_ProduceUnitId,
              @IfUseEntryCode,
              @IfUseGoodsNum,
              GETDATE(),
              @isservice,
              @sortid,
                @Omuse,
			  dbo.F_RoundPrice(@omprice),
			  dbo.F_RoundTax(@BuyDefaultRate) ,
			  dbo.F_RoundTax(@SaleDefaultRate),
			  @PtypeCategoryID, 
			  @InventoryTypeID,
			  @iscombinationproduct,
			  @IsScaleWeight,
			  @ScaleWeightType,
			  @Pweight,
			  @volume,
			  @ptypebrandarid,
			  0,
			  @othercomment1,
			  @othercomment2,
			  @othercomment3,
			  @othercomment4,
			  @othercomment5,
			  @yjkptype
            )    -----肖伟2002-6-5 Add For 服装版

    INSERT  ptype_price
            (
              PTypeID,
              PreBuyPrice1,
              PreBuyPrice2,
              PreBuyPrice3,
              PreBuyPrice4,
              PreBuyPrice5,
              TopBuyPrice,
              PreSalePrice1,
              PreSalePrice2,
              PreSalePrice3,
              PreSalePrice4,
              PreSalePrice5,
              PreSalePrice6,
              PreSalePrice7,
              PreSalePrice8,
              PreSalePrice9,
              PreSalePrice10,
              RetailPrice,
              TopSalePrice,
              LowSalePrice,
              UnitID,
              IsDefaultUnit
            )
    VALUES  (
              @EtypeId_1,
              dbo.F_RoundPrice(@PreBuyPrice1),
              dbo.F_RoundPrice(@PreBuyPrice2),
              dbo.F_RoundPrice(@PreBuyPrice3),
              dbo.F_RoundPrice(@PreBuyPrice4),
              dbo.F_RoundPrice(@PreBuyPrice5),
              dbo.F_RoundPrice(@TopBuyPrice),
              dbo.F_RoundPrice(@PreSalePrice1),
              dbo.F_RoundPrice(@PreSalePrice2),
              dbo.F_RoundPrice(@PreSalePrice3),
              dbo.F_RoundPrice(@PreSalePrice4),
              dbo.F_RoundPrice(@PreSalePrice5),
              dbo.F_RoundPrice(@PreSalePrice6),
              dbo.F_RoundPrice(@PreSalePrice7),
              dbo.F_RoundPrice(@PreSalePrice8),
              dbo.F_RoundPrice(@PreSalePrice9),
              dbo.F_RoundPrice(@PreSalePrice10),
              dbo.F_RoundPrice(@RetailPrice),
              dbo.F_RoundPrice(@TopSalePrice),
              dbo.F_RoundPrice(@LowSalePrice),
              @baseUnitid,
              1
            )


    INSERT  dbo.QP_PType_Ext
            (
              PTypeID,
              Brand,
              Import,
              GeneralType,
              GeneralDwgNo,
              Property,
              PackageQty,
              Weight,
              TaxNumber,
              Taxrate,
              BTypeID,
              FcUnit,
              FcPrice
            )
    VALUES  (
              @EtypeId_1,
              @Brand,
              @Import,
              @GeneralType,
              @GeneralDwgNo,
              @Property,
              @PackageQty,
              @Weight,
              @TaxNumber,
              @Taxrate,
              @BTypeID,
              @FcUnit,
              @FcPrice
            ) 
    IF @@rowcount = 0 
        BEGIN
            ROLLBACK TRAN insertproc 
            RETURN -1
        END
    ELSE 
        BEGIN
            UPDATE  [ptype]
            SET     sonnum = @nSonnum + 1,
                    soncount = @nSoncount + 1
            WHERE   typeid = @ParId
            UPDATE  Ptype
            SET     preprice1 = 0,
                    preprice2 = 0,
                    preprice3 = 0,
                    preprice4 = 0,
                    preprice5 = 0,
                    SerialCount = 0,
                    recprice = 0
            WHERE   Typeid = @ParId
        END

--修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    PType
    UPDATE  PType
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @EtypeId_1

--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','Ptype','0'

--建立第一个子节点，即分类，写父节点删除记录
IF EXISTS(SELECT *FROM PType WHERE typeId=@ParId AND sonnum=1)
BEGIN
	DECLARE @PID VARCHAR(50)
	SELECT @PID=Pid FROM PType WHERE typeId=@ParId
	EXEC Gp_DataSaveForPosDown '-99999','Ptype',@PID
	SELECT @PID=Pid FROM PType WHERE typeId=@ParId
	EXEC Gp_DataSaveForPosDown '-99999','PType_Price',@PID
		SELECT @PID=Pid FROM PType WHERE typeId=@ParId
	EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext',@PID
END 


EXEC Gp_DataSaveForPosDown '-99999','PType_Price','0'
EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext','0'
	SELECT @XiWaMaxNumber=MAX(xiwamaxnumber)+1 FROM PType_Price
	update PType_Price set XiWaMaxNumber=@XiWaMaxNumber WHERE PTypeID=@EtypeId_1
    COMMIT TRAN insertproc

GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_InsertRecycleBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_InsertRecycleBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：谢吉康
	日期：2010-08-06
	描述：写入旧件回收单的明细
*/

CREATE PROCEDURE Qp_Gp_InsertRecycleBill
(
	@BillNumberId		NUMERIC(18,0),
	@PTypeId			VARCHAR(100),
	@Qty				 NUMERIC(24, 10) ,
	@Price				 NUMERIC(24, 10) ,
	@Total				 NUMERIC(24, 10) ,
	@Status				INT,
	@Comment			VARCHAR(400),
	@STypeID			varchar(50)=''
)
--@encode$--
AS
SET NOCOUNT ON 

INSERT INTO QP_RecycleBill
(
	BillNumberId,
	PTypeId,
	Qty,
	Price,
	Total,
	Status,
	Comment,
	STypeID
)VALUES(
	@BillNumberId,
	@PTypeId,
	@Qty,
	@Price,
	@Total,
	@Status,
	@Comment,
	@STypeID
)

-- 操作返回值
IF @@ROWCOUNT = 0
	RETURN -1	-- 失败
ELSE
	RETURN 0	-- 成功

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_LoadRepairItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_LoadRepairItems]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-05-17
-- Description: 保险理赔单调维修单项目明细（维修单包括：接待登记、快修单、维修结算单）
-- =============================================
CREATE   PROCEDURE QP_GP_LoadRepairItems
( 
	 @BillNumberId numeric(10,0),
	 @billtype		varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(8000)
		
IF @billtype in (195)
BEGIN
	SET @SQL=' 
	SELECT  
			a.BillNumberId,
			a.StandardManHour AS standardmanhour,
			a.CheckHour AS checkmanhour,
			a.DiscountTotal AS DiscountTotal,
			b.fullname,
			b.typeid,
			b.ChargeMode,
			b.UserCode,
			a.CostTotal,
			a.Comment,
			e.FullName AS efullname,
			e.typeId AS repairmantypeid,
			a.ID AS RID,
			A.ID AS QuickOrReceptionBillId,
			a.Insurance
	FROM    Qp_ReceptionBill_RepairItems a
			LEFT JOIN QP_RepairItems b ON a.repairitemstypeid = b.TypeID
			LEFT JOIN dbo.employee e ON a.RepairMan = e.typeId
	WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))+' 
			AND  a.Insurance=1 '
END
ELSE
BEGIN
	SET @SQL=' 
	SELECT  
		a.BillNumberId,
        a.StandardManHour AS standardmanhour,
        a.CheckHour AS checkmanhour,
        a.DiscountTotal,
        b.fullname,
        b.typeid,
        b.ChargeMode,
        b.UserCode,
        a.CostTotal,
        a.Comment,
        e.FullName AS efullname,
        e.typeId AS repairmantypeid,
        a.ID AS RID,
        A.ID AS QuickOrReceptionBillId,
        a.Insurance 
	FROM    QP_QuickRepairBill_RepairItems a
			LEFT JOIN QP_RepairItems b ON a.repairitemstypeid = b.TypeID
			LEFT JOIN dbo.employee e ON a.RepairManTypeID = e.typeId
	WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))+'
	 AND  a.Insurance=1 '
END
	
EXEC(@SQL)
        
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_LoadRepairPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_LoadRepairPtype]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-05-17
-- Description: 保险理赔单调维修单配件明细（维修单包括：快修单、维修结算单）
-- =============================================
CREATE   PROCEDURE QP_GP_LoadRepairPtype
( 
	 @BillNumberId numeric(10,0),
	 @billtype		varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(8000)
	
IF @billtype in (195)
begin
	set @sql='
			SELECT  
			a.BillNumberId,
			a.Qty,
			a.discountPrice,
			a.DiscountTotal,
			p.typeId,
			p.UserCode,
			p.FullName,
			a.Comment,
			a.costtotal as goodscosttotal,
			a.ID AS AID,
			a.ID AS QuickOrReceptionBillId,
			a.Insurance
	FROM    Qp_ReceptionBill_FactUsePType a
			LEFT JOIN dbo.ptype p ON a.PTypeID = p.typeId    
	WHERE a.receptionbillnumberid='+CAST(@BillNumberId AS VARCHAR(100))+' 
			AND  a.Insurance=1 '
end
IF @billtype in(178)
BEGIN
	set @sql='
	SELECT  
			a.BillNumberId,
			a.Qty,
			a.discountPrice,
			a.DiscountTotal,
			p.typeId,
			p.UserCode,
			p.FullName,
			a.Comment,
			a.ID AS AID,
			A.ID AS QuickOrReceptionBillId,
			A.Insurance,
			a.goodsCostTotal
	FROM    QP_QuickRepairBill_PType a
			LEFT JOIN dbo.ptype p ON a.PTypeID = p.typeId    
	WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))+'
		 AND  a.Insurance=1 '
END
--print(@sql)
EXEC(@SQL)
        
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_nVipAddMoney]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_nVipAddMoney]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2010-08-05
	描述：会员储值充值
*/
CREATE  PROCEDURE Qp_Gp_nVipAddMoney
(
	@BillDate  			[datetime],
	@BillCode  			[varchar](200), 
	@BillType  			[numeric](4,0),
	@EtypeId  			[varchar](50),
	@DtypeId 			varchar(50) = '',		
	@AtypeId			varchar(50)='',
	@BtypeId			varchar(50)='',
	@RAtypeId			varchar(50)='',
	@EndDate			datetime,
	@VipCardID			int = -1,				-- VIP卡的唯一ID值
	@CheckE  			[varchar](50),
	@szPeriod 			[SMALLINT],
	@Comment  			[varchar](256),
	@Explain 			[varchar](256),
	@TotalInMoney		 NUMERIC(24, 10) =0,
	@PreferenceMoney	 NUMERIC(24, 10) =0,
	@TotalMoney			 NUMERIC(24, 10) =0,
	@vipCZMoney			 NUMERIC(24, 10) =0,
	@stypeid			varchar(50)=''


)
--@encode$--
AS
SET NOCOUNT ON

/*

1、充值金额＝实收金额＋优惠金额。
2、会员卡处于启用状态。
3、卡必须带会员储值功能。


*/




IF @TotalMoney<>@TotalInMoney+@PreferenceMoney
BEGIN
	RETURN	-100
END

IF NOT EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND deleted=0
)
BEGIN
	RETURN	-101
END

IF NOT EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND IsCZ=1
)
BEGIN
	RETURN	-102
END

-- ********	判断是否试用版 - Start	********
DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN 1688

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

-- ********	判断是否试用版 - END	********

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********
	-- 获取数据表 LoginUser 中操作员数
	DECLARE @intLoginUserCount int
	SELECT	@intLoginUserCount = COUNT(*)
	FROM	LoginUser
	WHERE	IsErp = 1

-- 判断软件狗用户数
	DECLARE @intDogUserCount int

	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 3	-- 检查用户数

	IF @N IS NULL RETURN 1688

	IF @intVersion IN (2,3,5,7,9,11,13,15)	-- 试用版
	BEGIN
		SELECT @intDogUserCount = 5
	END
	ELSE
	BEGIN
		SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
		IF ( 3 & @N <> 3 ) RETURN 1688
	END

	-- 若实际操作员数 > 软件狗许可用户数，则不允许过账
	IF @intLoginUserCount - 1 > @intDogUserCount RETURN 1688

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - End	********
IF NOT EXISTS (
	SELECT	TOP 1 1
	FROM	SType_UserConfig
	WHERE	ConfigNo = 1
			AND Value = '1'
			AND STypeID=@STypeID
)
	RETURN -33	-- 没有开帐不允许过帐


DECLARE @Re int,@Flag int
EXEC @Re=Gp_Validate 2, @Flag OUTPUT
IF @Re <>0 RETURN -3 --检查程序版本错误

IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
BEGIN
	--RAISERROR('校验错误 ！',16,1) 
	RETURN -3 --检查程序版本错误
END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -16
	END
END 
-- ********	判断是否试用版 - End	******** 


IF NOT EXISTS(
	SELECT TOP 1 TypeID FROM F_GetManDetailDType(@CheckE) WHERE TypeID=@DTypeID
)
BEGIN
	RETURN -1
END

IF NOT EXISTS(
	SELECT TOP 1 1 FROM F_GetManDetailEType(@CheckE) WHERE TypeID<>'00001' AND TypeID=@ETypeID
)
BEGIN
	RETURN -2
END

IF NOT EXISTS(
	SELECT TOP 1 1 FROM F_GetManDetailSType(@CheckE) WHERE TypeID=@STypeID
)
BEGIN
	RETURN -3
END


IF @ATypeID<>''
BEGIN
	IF NOT EXISTS(
		SELECT TOP 1 TypeID FROM AType WHERE TypeID=@ATypeid AND SonNum=0 AND Deleted=0	    AND ((@ATypeID='0000100003' OR @ATypeID LIKE '0000100004%') AND @ATypeID IN (SELECT TypeID FROM F_GetManDetailAType(@CheckE)) OR @ATypeID='0000200005')
	)
	BEGIN
		RETURN -30
	END
END



--如果开账日期大于当前日期，则不允许充值
IF EXISTS(SELECT TOP 1 1 FROM MonthProc WHERE (StartDate>GETDATE() OR StartDate>@BillDate)  AND MonthNo = '本期' AND Period=1)
	RETURN -15

IF EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='PassOneDay' AND Value='1')
BEGIN
	IF ((YEAR(GETDATE())<>YEAR(@BillDate)) OR (MONTH(GETDATE())<>MONTH(@BillDate)) OR (DAY(GETDATE())<>DAY(@BillDate)))
	BEGIN
		RETURN -11
	END
END


DECLARE @BeginDate 	datetime,
		@szItem 	varchar(30),
		@szVchCode 	varchar(30)
		

IF EXISTS(SELECT ConfigNo FROM Userconfig WHERE ConfigName='BillcodeAllowRepeat' AND Value=0)
BEGIN
	IF EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillCode=@BillCode AND BillNumberId<>@billnumberid)
		RETURN -120
END

UPDATE nVipCardSign
SET EndDate=@EndDate
WHERE VipCardId = @VipCardID

IF EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND @BillDate>EndDate
)
BEGIN
	RETURN -110
END


DECLARE
		@CardName   varchar(200)

SELECT @CardName=VipCardCode FROM nVipCardSign WHERE VipCardId = @VipCardID
IF @@ROWCOUNT = 0
	RETURN -17

DECLARE
	@intAuto	INT

SELECT @intAuto=CAST(Value AS INT) 
FROM UserConfig
WHERE ConfigName='AutoCreateResume'

DECLARE
	@intATypeBalanceCheck	INT

SELECT @intATypeBalanceCheck=CAST(Value AS INT) 
FROM UserConfig WHERE ConfigName='ATypeBalanceCheck'

IF @intATypeBalanceCheck=1
BEGIN
	--判断充值后余额是否为负
	IF EXISTS(SELECT TypeID FROM AType WHERE TypeID=@atypeid AND ISNULL(Total,0)+@TotalInMoney<0)
		RETURN -150
END


IF EXISTS(
	SELECT VipCardID FROM nVipCardSign 
	WHERE VipCardId = @VipCardID AND ISNULL(CZYEMoney,0)+@TotalMoney<0
)
RETURN -111

IF @Comment='' AND @intAuto=1
BEGIN
	IF EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='AutoCreateResume' AND Value='1')
	BEGIN
		DECLARE
			@strVipCode		VARCHAR(100),
			@strBName		VARCHAR(100),
			@strEFullName	VARCHAR(100)

		SELECT @strVipCode=VipCardCode,@strBName=BName 
		FROM NVIPCardSign
		WHERE VipCardID=@VipCardID

		SELECT @strEFullName=FullName
		FROM Employee
		WHERE TypeID=@ETypeID

		IF @strBName<>''
		BEGIN
			SELECT @Comment='【'+@strBName+'】为【'+@strVipCode+'】的会员卡充值 充值金额'+CAST(@TotalMoney AS VARCHAR(30))+' 元：'+@strEFullName
		END
		ELSE
		BEGIN
			SELECT @Comment='为【'+@strVipCode+'】的会员卡充值 充值金额'+CAST(@TotalMoney AS VARCHAR(30))+' 元：'+@strEFullName
		END
	END
END



--写入主表
INSERT INTO BillIndex
(
	BillDate,
	BillCode,
	BillType,
	EtypeId,
	DtypeId,
	AtypeId,
	BtypeId,
	VipCardID,
	Checke,
	Period,
	Comment,
	Explain,
	TotalInMoney,
	PreferenceMoney,
	TotalMoney,
	vipCZMoney,
	IfCheck,
	Draft,
	ptypeid,ktypeid,ktypeid2,ktypeid3,
	Stypeid
)
VALUES
(
	@BillDate,
	@BillCode,
	@BillType,
	@EtypeId,
	@DtypeId,
	@AtypeId,
	@BtypeId,
	@VipCardID,
	@Checke,
	@szPeriod,
	--@CardName+'VIP 卡充值'+CAST(@TotalMoney as varchar(20))+'元',
	@Comment,
	@Explain,
	@TotalInMoney,
	@PreferenceMoney,
	@TotalMoney,
	@vipCZMoney,
	't',
	0,
	'','','','',
	@stypeid
)


DECLARE	
	@nBillId		BIGINT

IF @@ROWCOUNT = 0
	BEGIN
		RETURN -13
	END
ELSE
	SET @nBillId = SCOPE_IDENTITY();

INSERT INTO Billindex_CarRepair(
			[BillNumberId],
			[BillDate],
			[BillType],
			[RATypeID]
	)
	VALUES
	(
			@nBillId,
			@BillDate,
			@BillType,
			@RATypeID
	)

IF @@ROWCOUNT = 0
BEGIN
	RETURN -13
END

UPDATE nVipCardSign
SET LJCZMoney=ISNULL(LJCZMoney,0)+@TotalMoney,CZYEMoney=ISNULL(CZYEMoney,0)+@TotalMoney,EndDate=@EndDate
WHERE	VipCardId = @VipCardID



--通用的校验

--过账处理
/*

借：收款账户科目 实收金额
    优惠金额 优惠金额
贷：会员储值 充值金额

*/

DECLARE
		@numTotal			 NUMERIC(24, 10) 

SELECT @numTotal=@TotalInMoney

IF @numTotal<>0
BEGIN
	EXEC GP_CreateMX_InsertList 
		@nBillId,
		@BillDate,
		@BillType,
		@ATypeID,
		@BTypeID,
		@ETypeID,
		@numTotal,
		'',
		NULL,
		@DtypeId,
		@stypeid
	
	UPDATE AType
	SET Total=ISNULL(Total,0)+@TotalInMoney
	WHERE typeId=@atypeid
	
	IF EXISTS(
		SELECT ATypeID FROM AType_Total
		WHERE ATypeID=@AtypeId AND STypeID=@stypeid
	)
	BEGIN
		UPDATE AType_Total
		SET Total=ISNULL(Total,0)+@TotalInMoney
		WHERE AtypeId=@atypeid AND STypeID=@stypeid
	END
	ELSE
	BEGIN
		INSERT AType_Total(ATypeID,STypeID,Total)
		SELECT @AtypeId,@stypeid,@TotalInMoney
	END
END


SELECT
	@atypeid='000040000300004',
	@numTotal=@PreferenceMoney

IF @numTotal<>0
BEGIN
	EXEC GP_CreateMX_InsertList 
		@nBillId,
		@BillDate,
		@BillType,
		@ATypeID,
		@BTypeID,
		@ETypeID,
		@numTotal,
		'',
		NULL,
		@DtypeId,
		@stypeid
	
	
	UPDATE AType
	SET Total=ISNULL(Total,0)+@numTotal
	WHERE typeId=@atypeid
	
	IF EXISTS(
		SELECT ATypeID FROM AType_Total
		WHERE ATypeID=@AtypeId AND STypeID=@stypeid
	)
	BEGIN
		UPDATE AType_Total
		SET Total=ISNULL(Total,0)+@numTotal
		WHERE AtypeId=@atypeid AND STypeID=@stypeid
	END
	ELSE
	BEGIN
		INSERT AType_Total(ATypeID,STypeID,Total)
		SELECT @AtypeId,@stypeid,@numTotal
	END
END	

SELECT
	@atypeid='0000200005',
	@numTotal=@TotalMoney


IF @numTotal<>0
BEGIN
	EXEC GP_CreateMX_InsertList 
		@nBillId,
		@BillDate,
		@BillType,
		@ATypeID,
		@BTypeID,
		@ETypeID,
		@numTotal,
		'',
		NULL,
		@DtypeId,
		@STypeID
		
	UPDATE AType
	SET Total=ISNULL(Total,0)+@numTotal
	WHERE typeId=@atypeid
	
	IF EXISTS(
		SELECT ATypeID FROM AType_Total
		WHERE ATypeID=@AtypeId AND STypeID=@stypeid
	)
	BEGIN
		UPDATE AType_Total
		SET Total=ISNULL(Total,0)+@numTotal
		WHERE AtypeId=@atypeid AND STypeID=@stypeid
	END
	ELSE
	BEGIN
		INSERT AType_Total(ATypeID,STypeID,Total)
		SELECT @AtypeId,@stypeid,@numTotal
	END
	
END

--挂往来
IF @TotalMoney-@TotalInMoney-@PreferenceMoney<>0
BEGIN
	DECLARE
		@decTemp	 NUMERIC(24, 10) 
	--需要挂往来
	SELECT @decTemp=@TotalMoney-@TotalInMoney-@PreferenceMoney
	
	DECLARE
		@intReturnCode INT
	
	IF @numTotal<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertARAP @nBillID,'AR',@BillDate,@BillType,@BTypeID,@ETypeID,
			@numTotal,'',NULL,@DTypeID,@STypeID
			
		IF EXISTS(
			SELECT ATypeID FROM AType_Total
			WHERE ATypeID=@AtypeId AND STypeID=@STypeID
		)
		BEGIN
			UPDATE AType_Total
			SET Total=ISNULL(Total,0)+@decTemp
			WHERE AtypeId=@atypeid AND STypeID=@STypeID
		END
		ELSE
		BEGIN
			INSERT AType_Total(ATypeID,STypeID,Total)
			SELECT @AtypeId,@STypeID,@decTemp
		END
		
		IF EXISTS(
			SELECT BTypeID
			FROM BType_ArApTotal
			WHERE BTypeID=@BtypeId AND STypeID=@STypeID
		)
		BEGIN
			INSERT BType_ArApTotal(BTypeID,STypeID,ARTotal)
			SELECT @BtypeId,@STypeID,@numTotal
		END
		ELSE
		BEGIN
			UPDATE BType_ArApTotal
			SET ARTotal=ARTotal+@numTotal
			WHERE BTypeID=@BtypeId AND STypeID=@STypeID
		END
	END
END

UPDATE ListTable
SET Audited=1
WHERE BillNumberID=@nBillId

-- 修改 BillIndex 的 ID 字段，写入真实的物理录单顺序
DECLARE @NewID numeric(10,0)
SELECT 	@NewID = ISNULL(MAX(ID),0) + 1
FROM	BillIndex

UPDATE	BillIndex
SET		ID = @NewID
WHERE	BillNumberID = @nBillID


RETURN @nBillId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_nVipAddTimes]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_nVipAddTimes]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：冯波
	日期：2010-08-05
	描述：洗车充值
*/
CREATE  PROCEDURE Qp_Gp_nVipAddTimes
(
	@BillDate  			[datetime],
	@BillCode  			[varchar](200), 
	@BillType  			[numeric](4,0),
	@EtypeId  			[varchar](50),
	@DtypeId 			varchar(50) = '',
	@StypeId 			varchar(50) = '',			
	@AtypeId			varchar(50)='',
	@BtypeId			varchar(50)='',
	@RAtypeId			varchar(50)='',
	@EndDate			datetime,
	@VipCardID			int = -1,				-- VIP卡的唯一ID值
	@CheckE  			[varchar](50),
	@szPeriod 			[SMALLINT],
	@Comment  			[varchar](256),
	@Explain 			[varchar](256),
	@TotalInMoney		 NUMERIC(24, 10) =0,
	@TotalMoney			 NUMERIC(24, 10) =0,
	@vipCZMoney			 NUMERIC(24, 10) =0,
	@wxTotal			 NUMERIC(24, 10) =0


)
--@encode$--
AS
SET NOCOUNT ON



IF @TotalMoney<>@TotalInMoney
BEGIN
	RETURN	-100
END

IF NOT EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND deleted=0
)
BEGIN
	RETURN	-101
END

IF NOT EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND IsWashTimes=1
)
BEGIN
	RETURN	-102
END

-- ********	判断是否试用版 - Start	********
DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN 1688

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

-- ********	判断是否试用版 - END	********

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - Start	********
	-- 获取数据表 LoginUser 中操作员数
	DECLARE @intLoginUserCount int
	SELECT	@intLoginUserCount = COUNT(*)
	FROM	LoginUser
	WHERE	IsErp = 1

-- 判断软件狗用户数
	DECLARE @intDogUserCount int

	SELECT	@N = CAST(SubValue AS int)
	FROM	SysData1
	WHERE	SubNo = 3	-- 检查用户数

	IF @N IS NULL RETURN 1688

	IF @intVersion IN (2,3,5,7,9,11,13,15)	-- 试用版
	BEGIN
		SELECT @intDogUserCount = 5
	END
	ELSE
	BEGIN
		SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
		IF ( 3 & @N <> 3 ) RETURN 1688
	END

	-- 若实际操作员数 > 软件狗许可用户数，则不允许过账
	IF @intLoginUserCount - 1 > @intDogUserCount RETURN 1688

-- ********	判断软件狗用户数 ( 试用版为 5 用户 ) - End	********



DECLARE @Re int,@Flag int
EXEC @Re=Gp_Validate 2, @Flag OUTPUT
IF @Re <>0 RETURN -3 --检查程序版本错误

IF @intVersion NOT IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
BEGIN
	--RAISERROR('校验错误 ！',16,1) 
	RETURN -3 --检查程序版本错误
END

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @billnumberid int
	SELECT @billnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @billnumberid > 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -16
	END
END 
-- ********	判断是否试用版 - End	******** 

IF NOT EXISTS (
		SELECT	TOP 1 1
		FROM	SysData
		WHERE	SubNo = 4
				AND SubName = 'inicanmodify'
				AND SubValue = 'F'
	)
		RETURN -33	-- 没有开帐不允许过帐


IF NOT EXISTS(
	SELECT TOP 1 TypeID FROM Department WHERE SonNum = 0 AND Deleted = 0 AND TypeID=@DTypeID
)
BEGIN
	RETURN -1
END

IF NOT EXISTS(
	SELECT TOP 1 1 FROM F_GetManDetailEType(@CheckE) WHERE TypeID<>'00001' AND TypeID=@ETypeID
)
BEGIN
	RETURN -2
END


IF @ATypeID<>''
BEGIN
	IF NOT EXISTS(
		SELECT TOP 1 TypeID FROM AType WHERE TypeID=@ATypeid AND SonNum=0 AND Deleted=0
	    AND ((@ATypeID='0000100003' OR @ATypeID LIKE '0000100004%') AND @ATypeID IN (SELECT TypeID FROM F_GetManDetailAType(@CheckE)) OR @ATypeID='0000200005')
	)
	BEGIN
		RETURN -30
	END
END

/*
--如果开账日期大于当前日期，则不允许充值
IF EXISTS(SELECT TOP 1 1 FROM MonthProc WHERE (StartDate>GETDATE() OR StartDate>@BillDate)  AND MonthNo = '本期' AND Period=1)
	RETURN -15

IF EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='PassOneDay' AND Value='1')
BEGIN
	IF ((YEAR(GETDATE())<>YEAR(@BillDate)) OR (MONTH(GETDATE())<>MONTH(@BillDate)) OR (DAY(GETDATE())<>DAY(@BillDate)))
	BEGIN
		RETURN -11
	END
END
*/

UPDATE nVipCardSign
SET EndDate=@EndDate
WHERE VipCardId = @VipCardID

IF EXISTS(
	SELECT VipCardID FROM nVipCardSign WHERE VipCardId = @VipCardID AND @BillDate>EndDate
)
BEGIN
	RETURN -110
END


IF EXISTS(SELECT BillNumberID FROM BillIndex WHERE BillCode=@BillCode)
	RETURN -120


DECLARE @BeginDate 	datetime,
		@szItem 	varchar(30),
		@szVchCode 	varchar(30)

DECLARE
		@CardName   varchar(200)

SELECT @CardName=VipCardCode FROM nVipCardSign WHERE VipCardId = @VipCardID
IF @@ROWCOUNT = 0
	RETURN -17


DECLARE
	@intAuto	INT

SELECT @intAuto=CAST(Value AS INT) 
FROM UserConfig
WHERE ConfigName='AutoCreateResume'

DECLARE
	@intATypeBalanceCheck	INT

SELECT @intATypeBalanceCheck=CAST(Value AS INT) 
FROM UserConfig WHERE ConfigName='ATypeBalanceCheck'

IF @intATypeBalanceCheck=1
BEGIN
	--判断充值后余额是否为负
	IF EXISTS(SELECT TypeID FROM AType WHERE TypeID=@atypeid AND ISNULL(Total,0)+@TotalInMoney<0)
		RETURN -118
END


IF EXISTS(
	SELECT VipCardID FROM nVipCardSign 
	WHERE VipCardId = @VipCardID AND ISNULL(CanWashTimes,0)+@wxTotal<0
)
RETURN -111




IF @Comment='' AND @intAuto=1
BEGIN
	IF EXISTS(SELECT Value FROM UserConfig WHERE ConfigName='AutoCreateResume' AND Value='1')
	BEGIN
		DECLARE
			@strVipCode		VARCHAR(100),
			@strBName		VARCHAR(100),
			@strEFullName	VARCHAR(100)

		SELECT @strVipCode=VipCardCode,@strBName=BName 
		FROM NVIPCardSign
		WHERE VipCardID=@VipCardID

		SELECT @strEFullName=FullName
		FROM Employee
		WHERE TypeID=@ETypeID

		SELECT @Comment='【'+@strBName+'】为【'+@strVipCode+'】的会员卡充洗车次数 充值次数'+CAST(CAST(@wxTotal AS INT) AS VARCHAR(30))+' 次：'+@strEFullName
	END
END





--写入主表
INSERT INTO BillIndex
(
	BillDate,
	BillCode,
	BillType,
	EtypeId,
	DtypeId,
	StypeId,
	AtypeId,
	BtypeId,
	VipCardID,
	Checke,
	Period,
	Comment,
	Explain,
	TotalInMoney,
	TotalMoney,
	vipCZMoney,
	wxTotal,
	IfCheck,
	Draft,
	ptypeid,ktypeid,ktypeid2,ktypeid3
)
VALUES
(
	@BillDate,
	@BillCode,
	@BillType,
	@EtypeId,
	@DtypeId,
	@StypeId,
	@AtypeId,
	@BtypeId,
	@VipCardID,
	@Checke,
	@szPeriod,
	--@CardName+'VIP 卡充值'+CAST(@TotalMoney as varchar(20))+'元',
	@Comment,
	@Explain,
	@TotalInMoney,
	@TotalMoney,
	@vipCZMoney,
	@wxTotal,
	't',
	0,
	'','','',''
)


DECLARE	
	@nBillId		BIGINT

IF @@ROWCOUNT = 0
	BEGIN
		RETURN -13
	END
ELSE
	SET @nBillId = SCOPE_IDENTITY();

INSERT INTO Billindex_CarRepair(
			[BillNumberId],
			[BillDate],
			[BillType],
			[RATypeID]
	)
	VALUES
	(
			@nBillId,
			@BillDate,
			@BillType,
			@RATypeID
	)

IF @@ROWCOUNT = 0
BEGIN
	RETURN -13
END

UPDATE nVipCardSign 
SET CanWashTimes=ISNULL(CanWashTimes,0)+@wxTotal,EndDate=@EndDate,CanWashTimesTotal=ISNULL(CanWashTimesTotal,0)+@wxTotal
WHERE VipCardId = @VipCardID


--通用的校验

--过账处理
/*

借：收款账户科目 充值金额
贷：商品维修收入 充值金额

影响对应会员卡的可洗车次数。

*/

DECLARE
		@numTotal			 NUMERIC(24, 10) 

SELECT @numTotal=@TotalInMoney

IF @numTotal<>0
BEGIN
	EXEC GP_CreateMX_InsertList 
		@nBillId,
		@BillDate,
		@BillType,
		@ATypeID,
		@BTypeID,
		@ETypeID,
		@numTotal,
		'',
		NULL,
		@DTypeID,
		@StypeId
	
	UPDATE AType
	SET Total=ISNULL(Total,0)+@TotalInMoney
	WHERE typeId=@atypeid
END



SELECT
	@atypeid='000030000200008',
	@numTotal=@TotalMoney

IF @numTotal<>0
BEGIN
	EXEC GP_CreateMX_InsertList 
		@nBillId,
		@BillDate,
		@BillType,
		@ATypeID,
		@BTypeID,
		@ETypeID,
		@numTotal,
		'',
		NULL,
		@DTypeID,
		@StypeId
	
	UPDATE AType
	SET Total=ISNULL(Total,0)+@numTotal
	WHERE typeId=@atypeid
END

--挂往来
IF @TotalMoney-@TotalInMoney<>0
BEGIN
	DECLARE
		@decTemp	 NUMERIC(24, 10) 
	--需要挂往来
	SELECT @decTemp=@TotalMoney-@TotalInMoney
	
	DECLARE
		@intReturnCode INT
	
	IF @numTotal<>0
	BEGIN
		EXEC @intReturnCode = GP_CreateMX_InsertARAP @nBillID,'AR',@BillDate,@BillType,@BTypeID,@ETypeID,
			@numTotal,'',NULL,@DTypeID,@STypeID
			
		IF EXISTS(
			SELECT ATypeID FROM AType_Total
			WHERE ATypeID=@AtypeId AND STypeID=@STypeID
		)
		BEGIN
			UPDATE AType_Total
			SET Total=ISNULL(Total,0)+@decTemp
			WHERE AtypeId=@atypeid AND STypeID=@STypeID
		END
		ELSE
		BEGIN
			INSERT AType_Total(ATypeID,STypeID,Total)
			SELECT @AtypeId,@STypeID,@decTemp
		END
		
		IF EXISTS(
			SELECT BTypeID
			FROM BType_ArApTotal
			WHERE BTypeID=@BtypeId AND STypeID=@STypeID
		)
		BEGIN
			INSERT BType_ArApTotal(BTypeID,STypeID,ARTotal)
			SELECT @BtypeId,@STypeID,@numTotal
		END
		ELSE
		BEGIN
			UPDATE BType_ArApTotal
			SET ARTotal=ARTotal+@numTotal
			WHERE BTypeID=@BtypeId AND STypeID=@STypeID
		END
	END
END

UPDATE ListTable
SET Audited=1
WHERE BillNumberID=@nBillId

-- 修改 BillIndex 的 ID 字段，写入真实的物理录单顺序
DECLARE @NewID numeric(10,0)
SELECT 	@NewID = ISNULL(MAX(ID),0) + 1
FROM	BillIndex

UPDATE	BillIndex
SET		ID = @NewID
WHERE	BillNumberID = @nBillID


RETURN @nBillId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_Priceinfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_Priceinfo]
GO 
/****
程序员:吴德水
最后修改:吴德水
最后时间:2004-01-05 10:29
修改内容：修改有效价格个数。即标准均售价
修改位置：第1行起

最后修改:徐辉
最后时间:2011-08-11 10:29
修改内容：修改价格和查询价格合并

最后修改：黄清
最后时间：2011-10-21
修改内容：去掉毛利列

修改人  ：陈强(9.91)
修改时间：2019-09-17
修改内容：商品筛选增加条件(商品简名、拼音码、状态)
***/

CREATE          PROCEDURE QP_GP_Priceinfo(
	@OperatorID 	varchar(100),
	@Units			VARCHAR(MAX),   --商品单位选择（基本，采购等）
	@PTypeId	    varchar(MAX),
	@PCategoryId	varchar(MAX),
	@ParId 			varchar(max)='',
	@usercode 		varchar(256)='',
	@fullname 		varchar(256)='',
	@entrycode 		varchar(256)='',
	@standard 		varchar(256)='',
	@type 			varchar(256)='',
	@area 			varchar(256)='',
	@unit			varchar(200)='',		--此处为基本计量单位名字
	@displayzero	INT = 1,				--是否显示为0的数据 1显示 0不显示
	--@g1 			 NUMERIC(24, 10) =0,		--去掉毛利查询相关参数
	--@g2 			 NUMERIC(24, 10) =0,
	@sortfield		varchar(50)='UserCode',
	@SortType		varchar(50)=' ASC ',	
	@queryMode 		int=1,
	@sOtherConditon	VARCHAR(max),
	@ifupdate		INT=0,					--修改价格标志
	@updateSQL		VARCHAR(max)='',		--修改价格SQL
	@updatezero		VARCHAR(max)=''	,		--更新小于0的数据sql
	@name			VARCHAR(256)='',		--商品简名
	@pycode			VARCHAR(256)='',		--商品拼音码
	@stopuse		VARCHAR(50)='stopuseno' --(状态：停用-->stopuseyes ,启用 -->stopuseno  全部 -->stopuseall)
)

--@encode$--
AS
SET NOCOUNT ON

IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT typeid FROM F_GetManDetailPType(@OperatorID)

CREATE TABLE #PTypeId(TypeId	varchar(100))
INSERT INTO #PTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@parid,1,@OperatorID)

DECLARE @SQL varchar(MAX),@strSQL varchar(MAX),@strSQL1 varchar(MAX)=''
BEGIN
SELECT @SQL=''
IF @parid<>''
	SELECT @SQL=@SQL+' 	AND p.typeid IN (SELECT TypeId FROM #PTypeId) ' 
IF @usercode <>''
	SELECT @SQL=@SQL+' AND p.usercode LIKE ''%'+@usercode+'%'''
IF @fullname<>''
	SELECT @SQL=@SQL+' AND p.fullname LIKE ''%'+@fullname+'%'''
IF @entrycode<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.entrycode,'''') LIKE ''%'+@entrycode+'%'''
IF @standard<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.standard,'''') LIKE ''%'+@standard+'%'''
IF @type<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.type,'''') LIKE ''%'+@type+'%'''
IF @area<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.area,'''')  LIKE ''%'+@area+'%'''
IF @unit<>''
	SELECT @SQL=@SQL+' AND u.fullname LIKE  ''%'+@unit+'%'''

--========================================修改内容===============================================--

---9.91版本新增查询条件---
IF @name<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.Name,'''') LIKE ''%'+@name+'%'''
IF @pycode<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.PyCode,'''') LIKE ''%'+@pycode+'%'''	
IF @stopuse<>''
BEGIN
	IF @stopuse='stopuseno'
		SELECT @SQL=@SQL+' AND p.deleted=0 '
	IF @stopuse='stopuseyes'
		SELECT @SQL=@SQL+' AND p.deleted=1 '
END

--==========================================END==================================================--

IF @queryMode = 1
	SET @SQL = @SQL+ ' AND p.deleted=0  '

SELECT @strSQL='
			SELECT 	s.ptypeid ,
					ISNULL(SUM(s.qty),0) AS qty,
					ISNULL(SUM(s.total),0) AS total
			INTO 	#gstock 
			FROM 	goodsstocks s '
IF @MPtypeid='-99999'
	SET @strSQL=@strSQL+' INNER JOIN #GetManPTypeId p ON s.PTypeId=p.typeid '
	
SET @strSQL=@strSQL+' WHERE 1=1 
						GROUP BY s.ptypeid ' --先将goodsstocks表中为零的过滤掉
						
						
						
						
 ---商品ID多选处理
CREATE TABLE #Temp (TypeId varchar(100))

IF @PTypeId = '00000' OR @PTypeId = '' OR @PTypeId = '%'
	INSERT INTO #Temp(TypeId) SELECT TypeId FROM F_GetManDetailPType(@OperatorId)
ELSE
BEGIN					
	INSERT INTO #Temp(TypeId)
	SELECT 	DISTINCT A.TypeId 
	FROM 	dbo.F_ManPTypeInCategoryID(@OperatorId,@PTypeId,@PCategoryId) A, 
			(SELECT A FROM dbo.F_Split(@PTypeId,',')) B 
	WHERE	A.TypeId LIKE B.A + '%'
END	 

--商品类别多选处理
 CREATE TABLE #TempC (TypeId varchar(100))

IF @PCategoryId = '00000' OR @PCategoryId = '' OR @PCategoryId = '%'
	INSERT INTO #TempC(TypeId) SELECT TypeId FROM dbo.PTypeCategory
ELSE
BEGIN					
	INSERT INTO #TempC(TypeId)
	SELECT 	DISTINCT A.TypeId 
	FROM 	dbo.PTypeCategory A, 
			(SELECT A FROM dbo.F_Split(@PCategoryId,',')) B 
	WHERE	A.TypeId LIKE B.A + '%'
END	 


---添加单位信息查询----
---2016-04-27----
-----魏伟----  
DECLARE @selectsql VARCHAR(max),@sqlui VARCHAR(max) ,@sqlui1 VARCHAR(max) 

CREATE TABLE #GetUnitsInfo ( unitid int,unitname VARCHAR(256),ptypeid VARCHAR(50),UserCode	VARCHAR(200),Rate NUMERIC(18,4)) 
 
IF(@Units='saleunitid')
	SET @selectsql=',p.SaleUnitId'

IF(@Units='buyunitid')
	SET @selectsql=',p.BuyUnitId'

IF(@Units='stockunitid')
	SET @selectsql=',p.StockUnitId'

IF(@Units='baseunitid')
	SET @selectsql=',p.baseUnitId'  
	
CREATE TABLE #unitsomeid (typeid varchar(256),unitid int) 

SET @sqlui1='INSERT INTO #unitsomeid  
			 SELECT	p.typeId'+@selectsql+' 
			 FROM	dbo.ptype p 
			 INNER JOIN #Temp t ON p.typeId = t.TypeId '
  
--全部单位 (辅助单位只显示前3个)
IF(@Units='')
BEGIN
  SET @sqlui1='INSERT INTO #unitsomeid  
			   SELECT	t.typeId,
						pu.UnitsId 
			   from		#Temp t,
						dbo.PType_Units pu,
						dbo.PType_Units_Ext pue 
			   WHERE	t.typeId=pue.PtypeID 
						AND pu.UnitsId=pue.UnitsId AND pue.ratetype=0 
						AND pue.IsUse = 1 AND pue.UnitsSortId <= 4'
END	
ELSE IF @Units = 'assisunit1' --辅助单位1
BEGIN
  SET @sqlui1='	INSERT INTO #unitsomeid  
			  	SELECT 	p.typeid,pue.UnitsId FROM #Temp p 
				INNER JOIN PType_Units_Ext pue ON pue.PtypeID = p.typeId 
				WHERE IsDefaultUnit = 0 AND IsUse = 1 AND UnitsSortId = 2'
END
ELSE IF @Units = 'assisunit2' --辅助单位2
BEGIN
  SET @sqlui1='	INSERT INTO #unitsomeid  
			  	SELECT 	p.typeid,pue.UnitsId FROM #Temp p 
				INNER JOIN PType_Units_Ext pue ON pue.PtypeID = p.typeId 
				WHERE IsDefaultUnit = 0 AND IsUse = 1 AND UnitsSortId = 3'
END
ELSE IF @Units = 'assisunit3' --辅助单位3
BEGIN
  SET @sqlui1='	INSERT INTO #unitsomeid  
			  	SELECT 	p.typeid,pue.UnitsId FROM #Temp p 
				INNER JOIN PType_Units_Ext pue ON pue.PtypeID = p.typeId 
				WHERE IsDefaultUnit = 0 AND IsUse = 1 AND UnitsSortId = 4'
END
					
EXEC(@sqlui1)
-- 查询辅助单位时，ptype_price商品价格表 不存在该辅助商品价格时，新增
IF @Units IN ('','assisunit1','assisunit2','assisunit3')
BEGIN
	DECLARE cursor_price SCROLL CURSOR 
	FOR SELECT typeid,unitid FROM #unitsomeid
	OPEN cursor_price
	DECLARE @typeid VARCHAR(50),
			@unitid INT
	FETCH NEXT FROM cursor_price INTO @typeid, @unitid
	WHILE @@FETCH_STATUS=0
	BEGIN
		--新增PType_Price
		EXEC Gp_InsertPriceInfo @ptypeid = @typeid,@unitsid = @unitid
		FETCH NEXT FROM cursor_price INTO @typeid, @unitid
	END
	CLOSE cursor_price
	DEALLOCATE cursor_price
END

SET @sqlui='INSERT INTO #GetUnitsInfo 
			SELECT	pu.UnitsId AS unitid,
					pu.FullName AS unitname,
					us.typeid AS ptypeid ,
					pu.UserCode,
					pue.Rate
			from	dbo.PType_Units pu  
			INNER JOIN #unitsomeid us ON pu.UnitsId=us.unitid 
			INNER JOIN dbo.PType_Units_Ext pue ON pue.PtypeID=us.typeid and pu.UnitsId=pue.UnitsId
			GROUP BY pu.UnitsId ,
					 pu.FullName,
					 us.typeid,
					 pu.UserCode,
					 pue.rate
			'  
EXEC(@sqlui)

SET @strSQL=@strSQL+'
			SELECT  p.typeid, 
					p.usercode,
					p.fullname,   
					pp.RecAmgSTypeBuyPrice  as recprice,
					pp.isdefaultunit,
					p.deleted,
					pp.PreBuyPrice1,
					pp.PreBuyPrice2,
					pp.PreBuyPrice3,
					pp.PreBuyPrice4,
					pp.TopBuyPrice,
					pp.PreBuyPrice5,
					pp.PreSalePrice1,
					pp.PreSalePrice2,
					pp.PreSalePrice3,
					pp.PreSalePrice4,
					pp.PreSalePrice5,
					pp.PreSalePrice6,
					pp.PreSalePrice7,
					pp.PreSalePrice8,
					pp.PreSalePrice9,
					pp.PreSalePrice10,
					pp.RetailPrice,
					pp.TopSalePrice,
					pp.LowSalePrice,
					pp.ReferPrice,
					gui.unitname,
					gui.unitid,
					gui.UserCode as uusercode,
					ISNULL(CASE
								WHEN p.IsService = 1 then null
								WHEN ISNULL(s.qty,0) = 0 THEN 0
									ELSE (cast( s.total as NUMERIC(24, 10))/cast(s.qty as NUMERIC(24, 10)))*gui.Rate
							END 
						,0) AS cost,
					ISNULL(s.qty,0) AS qty
			INTO #Result
			FROM ptype  p ' 
			
IF @unit <> ''
	SET @strSQL += ''		
	
SET @strSQL=@strSQL+'	
						LEFT JOIN  #gstock s ON s.Ptypeid=p.typeid 
						INNER JOIN #GetUnitsInfo gui ON P.TYPEID=gui.ptypeid
						INNER JOIN PType_Price pp ON gui.ptypeid = pp.ptypeid AND gui.unitid = pp.unitid'

IF @Units = '' 
	SET @strSQL +=' and ( pp.IsDefaultUnit = 1 or 
							pp.PreBuyPrice1<>0 or
							pp.PreBuyPrice2<>0 or
							pp.PreBuyPrice3<>0 or
							pp.PreBuyPrice4<>0 or
							pp.TopBuyPrice<>0 or
							pp.PreBuyPrice5<>0 or
							pp.PreSalePrice1<>0 or
							pp.PreSalePrice2<>0 or
							pp.PreSalePrice3<>0 or
							pp.PreSalePrice4<>0 or
							pp.PreSalePrice5<>0 or
							pp.PreSalePrice6<>0 or
							pp.PreSalePrice7<>0 or
							pp.PreSalePrice8<>0 or
							pp.PreSalePrice9<>0 or
							pp.PreSalePrice10<>0 or
							pp.RetailPrice<>0 or
							pp.TopSalePrice<>0 or
							pp.LowSalePrice<>0 or
							pp.ReferPrice<>0 ) '

IF @queryMode = 1
SET  @strSQL+=' AND p.deleted=0 '
			
IF @PCategoryId = '00000' OR @PCategoryId = '' OR @PCategoryId = '%'
	SET @strSQL1 = @strSQL1+''
ELSE
	SET @strSQL1 = @strSQL1+' INNER JOIN #TempC TC ON p.PtypeCategoryID=TC.typeid '


SET @strSQL1 = @strSQL1+'
						INNER JOIN PType_Units U ON U.UnitsId = p.baseUnitId
						WHERE 	p.sonnum=0  and parid<>''root'' AND P.IsService = 0   
					' + @SQL + ' 	 
						GROUP BY P.typeid,P.usercode,P.fullname,pp.RecAmgSTypeBuyPrice,pp.isdefaultunit,P.deleted,P.IsService,PP.PreBuyPrice1,PP.PreBuyPrice2,PP.PreBuyPrice3,
						PP.PreBuyPrice4,PP.TopBuyPrice,PP.PreBuyPrice5,PP.PreSalePrice1,PP.PreSalePrice2,PP.PreSalePrice3,
						PP.PreSalePrice4,PP.PreSalePrice5,PP.PreSalePrice6,PP.PreSalePrice7,PP.PreSalePrice8,PP.PreSalePrice9,
						PP.PreSalePrice10,PP.RetailPrice,PP.TopSalePrice,PP.LowSalePrice,PP.ReferPrice,S.qty,S.total,gui.unitname,gui.unitid ,gui.UserCode ,gui.Rate
			
			'
		

SET @strSQL+=@strSQL1
--服务类商品----------------------------------------------
SET @strSQL1 = ' 
				
					SELECT  
					p.typeid,
					p.usercode,
					p.fullname, 
					pp.RecAmgSTypeBuyPrice  as recprice,
					pp.isdefaultunit,
					p.deleted,
					pp.PreBuyPrice1,
					pp.PreBuyPrice2,
					pp.PreBuyPrice3,
					pp.PreBuyPrice4,
					pp.TopBuyPrice,
					pp.PreBuyPrice5,
					pp.PreSalePrice1,
					pp.PreSalePrice2,
					pp.PreSalePrice3,
					pp.PreSalePrice4,
					pp.PreSalePrice5,
					pp.PreSalePrice6,
					pp.PreSalePrice7,
					pp.PreSalePrice8,
					pp.PreSalePrice9,
					pp.PreSalePrice10,
					pp.RetailPrice,
					pp.TopSalePrice,
					pp.LowSalePrice,
					pp.ReferPrice, 
					gui.unitname,
					gui.unitid,
					gui.UserCode as uusercode,
					ISNULL(CAST(	CASE
								WHEN p.IsService = 1 then null
								WHEN ISNULL(s.qty,0) = 0 THEN 0
									ELSE (s.total/s.qty)*gui.Rate
							END AS  NUMERIC(24, 10) 
						),0) AS cost,
					ISNULL(s.qty,0) AS qty 
			INTO #Result1  
			FROM ptype p '
IF @unit <> ''
	SET @strSQL1 += ''		 
SET @strSQL1 = @strSQL1+'	LEFT JOIN  #gstock s ON s.Ptypeid=p.typeid 
						inner JOIN PType_Price pp ON p.typeid = pp.ptypeid '

IF @Units = '' 
	SET @strSQL1 +=' and ( pp.IsDefaultUnit = 1 or 
							pp.PreBuyPrice1<>0 or
							pp.PreBuyPrice2<>0 or
							pp.PreBuyPrice3<>0 or
							pp.PreBuyPrice4<>0 or
							pp.TopBuyPrice<>0 or
							pp.PreBuyPrice5<>0 or
							pp.PreSalePrice1<>0 or
							pp.PreSalePrice2<>0 or
							pp.PreSalePrice3<>0 or
							pp.PreSalePrice4<>0 or
							pp.PreSalePrice5<>0 or
							pp.PreSalePrice6<>0 or
							pp.PreSalePrice7<>0 or
							pp.PreSalePrice8<>0 or
							pp.PreSalePrice9<>0 or
							pp.PreSalePrice10<>0 or
							pp.RetailPrice<>0 or
							pp.TopSalePrice<>0 or
							pp.LowSalePrice<>0 or
							pp.ReferPrice<>0 ) '
SET @strSQL1+='
INNER JOIN #GetUnitsInfo gui ON P.TYPEID=gui.ptypeid and gui.unitid=pp.UnitID'
			
if @PCategoryId = '00000' OR @PCategoryId = '' OR @PCategoryId = '%'
	SET @strSQL1 = @strSQL1+''
else
	SET @strSQL1 = @strSQL1+' INNER JOIN #TempC TC ON p.PtypeCategoryID=TC.typeid '
	
SET @strSQL1 = @strSQL1+'
						INNER JOIN PType_Units U ON U.UnitsId = p.baseUnitId
						WHERE 	p.sonnum=0  and parid<>''root'' AND P.IsService = 1 
								' + @SQL + ' 
						GROUP BY P.typeid,P.usercode,P.fullname,pp.RecAmgSTypeBuyPrice,pp.isdefaultunit,P.deleted,P.IsService,PP.PreBuyPrice1,PP.PreBuyPrice2,PP.PreBuyPrice3,
									PP.PreBuyPrice4,PP.TopBuyPrice,PP.PreBuyPrice5,PP.PreSalePrice1,PP.PreSalePrice2,PP.PreSalePrice3,
									PP.PreSalePrice4,PP.PreSalePrice5,PP.PreSalePrice6,PP.PreSalePrice7,PP.PreSalePrice8,PP.PreSalePrice9,
									PP.PreSalePrice10,PP.RetailPrice,PP.TopSalePrice,PP.LowSalePrice,PP.ReferPrice,S.qty,S.total,gui.unitname,gui.unitid ,gui.UserCode,gui.Rate
		  '
----------------------------------------------------------
--into服务类商品
SET @strSQL += @strSQL1
----------------------------------------------------------
IF @ifupdate=1
	BEGIN
		--修改BUG,修改最近进价是报错
		IF EXISTS (SELECT *FROM f_split(@updateSQL,' ') WHERE A='recprice=')
			BEGIN
				SET @strSQL=@strSQL+ '
					' + @updatesql+'
					 FROM  #Result a WHERE ptype.typeid=a.typeid
					 
					 DROP TABLE #Result
					  ' 
			 END
		ELSE
			BEGIN
				SET @strSQL=@strSQL+ ' ' + @updatesql+'
						 FROM  #Result a WHERE ptype_price.ptypeid=a.typeid
						 
						 DROP TABLE #Result
						  '
			END
	END
ELSE
	SET @strSQL=@strSQL+ ' 
		SELECT * FROM #Result AS A  WHERE 1=1 AND ' + @sOtherConditon  
	
	--显示、隐藏为零的项目
	SET @strSQL += ' GROUP BY A.typeid,A.usercode,A.fullname,A.recprice,A.isdefaultunit,A.deleted,A.PreBuyPrice1,A.PreBuyPrice2,A.PreBuyPrice3,
						A.PreBuyPrice4,A.TopBuyPrice,A.PreBuyPrice5,A.PreSalePrice1,A.PreSalePrice2,A.PreSalePrice3,
						A.PreSalePrice4,A.PreSalePrice5,A.PreSalePrice6,A.PreSalePrice7,A.PreSalePrice8,A.PreSalePrice9,
						A.PreSalePrice10,A.RetailPrice,A.TopSalePrice,A.LowSalePrice,A.ReferPrice,A.qty,A.cost,A.unitname,A.unitid ,A.uusercode 
					 HAVING ' + CAST(@displayzero AS VARCHAR(1)) + ' = 1 OR ' + CAST(@displayzero AS VARCHAR(1)) + ' = 0 AND ISNULL(SUM(A.qty),0) <> 0 
					 '
	
	--合并非服务类、服务类商品
	SET @strSQL +=' UNION  
					SELECT * FROM #Result1  where 1=1 and ' + @sOtherConditon  

	SET @strSQL += ' 
					ORDER BY '+ @sortfield +' '+@SortType+' 
					
					
					DROP TABLE #Result,#Result1 '
	
	--PRINT(@strsql)
	EXEC(@strSQL)	

IF @ifupdate=1 AND @updatezero<>''
	EXEC(@updatezero)
END

DROP TABLE #GetManPTypeId
DROP TABLE #GetUnitsInfo


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_PriceinfoForGenerate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_PriceinfoForGenerate]
GO


/****
程序员:吴德水
最后修改:吴德水
最后时间:2004-01-05 10:29
修改内容：修改有效价格个数。即标准均售价
修改位置：第1行起

最后修改:徐辉
最后时间:2011-08-11 10:29
修改内容：修改价格和查询价格合并

最后修改：黄清
最后时间：2011-10-21
修改内容：去掉毛利列
***/

CREATE          PROCEDURE QP_GP_PriceinfoForGenerate(
	@OperatorID 	varchar(100),
	@ParId 			varchar(max)='',
	@usercode 		varchar(100)='',
	@fullname 		varchar(100)='',
	@entrycode 		varchar(50)='',
	@standard 		varchar(50)='',
	@type 			varchar(50)='',
	@area 			varchar(50)='',
	@unit			varchar(200)='',	--此处为基本计量单位名字
	--@g1 			 NUMERIC(24, 10) =0,	--去掉毛利查询相关参数
	--@g2 			 NUMERIC(24, 10) =0,
	@SortFild		varchar(50)='UserCode',
	@SortType		varchar(50)=' ASC ',	
	@queryMode 		int=1,
	@sOtherConditon	VARCHAR(max),
	@ifupdate		INT=0,					--修改价格标志
	@updateSQL		VARCHAR(max)='',		--修改价格SQL
	@updatezero		VARCHAR(max)=''			--更新小于0的数据sql
)

--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

CREATE TABLE #PTypeId(TypeId	varchar(100))
INSERT INTO #PTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@parid,1,@OperatorID)

DECLARE @SQL varchar(8000),@strSQL varchar(8000)
BEGIN
SELECT @SQL=''
IF @parid<>''
	SELECT @SQL=@SQL+' 	AND p.typeid IN (SELECT TypeId FROM #PTypeId) ' 

IF @usercode <>''
	SELECT @SQL=@SQL+' AND p.usercode LIKE ''%'+@usercode+'%'''
IF @fullname<>''
	SELECT @SQL=@SQL+' AND p.fullname LIKE ''%'+@fullname+'%'''
IF @entrycode<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.entrycode,'''') LIKE ''%'+@entrycode+'%'''
IF @standard<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.standard,'''') LIKE ''%'+@standard+'%'''
IF @type<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.type,'''') LIKE ''%'+@type+'%'''
IF @area<>''
	SELECT @SQL=@SQL+' AND ISNULL(p.area,'''')  LIKE ''%'+@area+'%'''
IF @unit<>''
	SELECT @SQL=@SQL+' AND u.FullName LIKE  ''%'+@unit+'%'''

IF @queryMode = 1
	SET @SQL = @SQL+ ' AND p.deleted=0  '

SELECT @strSQL='
			SELECT 	s.ptypeid ,
					ISNULL(SUM(s.qty),0) AS qty,
					ISNULL(SUM(s.total),0) AS total
			INTO 	#gstock 
			FROM 	goodsstocks s '
IF @MPtypeid='-99999'
	SET @strSQL=@strSQL+' INNER JOIN #GetManPTypeId p ON s.PTypeId=p.typeid '
	
SET @strSQL=@strSQL+' WHERE 1=1 
						GROUP BY s.ptypeid ' --先将goodsstocks表中为零的过滤掉

SET @strSQL=@strSQL+'
			SELECT 
					p.typeid,
					p.usercode,
					p.fullname,
					pp.RecAmgSTypeBuyPrice  as recprice,
					p.deleted,
					p.baseUnitId,
					p.SaleUnitId,
					p.customitemid,
					p.customitemfrom,
					p.customitemname,
					p.customitemrefid,
					pp.PreBuyPrice1,
					pp.PreBuyPrice2,
					pp.PreBuyPrice3,
					pp.PreBuyPrice4,
					pp.TopBuyPrice,
					pp.PreBuyPrice5,
					pp.PreSalePrice1,
					pp.PreSalePrice2,
					pp.PreSalePrice3,
					pp.PreSalePrice4,
					pp.PreSalePrice5,
					pp.PreSalePrice6,
					pp.PreSalePrice7,
					pp.PreSalePrice8,
					pp.PreSalePrice9,
					pp.PreSalePrice10,
					pp.RetailPrice,
					pp.TopSalePrice,
					pp.LowSalePrice,
					pp.ReferPrice,
					CAST(CASE 
						WHEN ISNULL(s.qty,0) = 0 THEN 0
						ELSE (s.total/s.qty)
						END AS  NUMERIC(24, 10) ) AS cost,
					s.qty
			INTO #Result
			FROM ptype p '
IF @unit <> ''
	SET @strSQL += 'INNER JOIN PType_Units U ON U.UnitsId = p.baseUnitId'		

IF @MPtypeid='-99999'
		SET @strSQL=@strSQL+' INNER JOIN #GetManPTypeId P1 ON P.TYPEID=P1.typeid '
SET @strSQL=@strSQL+'	LEFT JOIN  #gstock s ON s.Ptypeid=p.typeid 
						LEFT JOIN PType_Price pp ON p.typeid = pp.ptypeid and p.baseUnitId=pp.UnitID
			WHERE 	p.sonnum=0  
					' + @SQL + ' 					
			ORDER BY P.UserCode '
IF @ifupdate=1
BEGIN
	--修改BUG,修改最近进价是报错
	IF EXISTS (SELECT *FROM f_split(@updateSQL,' ') WHERE A='recprice=')
		BEGIN
			SET @strSQL=@strSQL+ '
				' + @updatesql+'
				 FROM  #Result a WHERE ptype.typeid=a.typeid
				 --DROP TABLE #newResult
				 DROP TABLE #Result
				  ' 
		 END
	ELSE
		BEGIN
	SET @strSQL=@strSQL+ '
			' + @updatesql+'
			 FROM  #Result a WHERE ptype_price.ptypeid=a.typeid and ptype_price.isdefaultunit=1
			 --DROP TABLE #newResult
			 DROP TABLE #Result
			  '
	  END
END
ELSE

SET @strSQL=@strSQL+ '
	SELECT  a.*,
			a.baseunitid as unitid,
			b.FullName AS unit,
			c.rate as unitrate,
			b1.FullName as saleunitname,
			b1.UnitsId as saleunitid,
			c1.Rate as salemunitrate  
	FROM #Result a
	LEFT JOIN PType_Units b ON b.UnitsId = a.baseUnitId
    LEFT JOIN Ptype_Units_ext c ON c.Unitsid=a.baseUnitId AND c.ptypeid=a.typeid
    left join PType_Units b1 on b1.UnitsId=a.SaleUnitId
    left join PType_Units_Ext c1 on a.SaleUnitId=c1.UnitsId AND a.typeId=c1.PtypeID					
	WHERE 1=1 AND '+@sOtherConditon+'ORDER BY '+ @SortFild +' '+@SortType+'
	DROP TABLE #Result '  
--PRINT(@strsql)
EXEC(@strSQL) 

IF @ifupdate=1 AND @updatezero<>''
	EXEC(@updatezero)
END
--print @updatezero

DROP TABLE #GetManPTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Gp_QueryBillIndexAuditing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Gp_QueryBillIndexAuditing]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：蔡志成
	日期：2010-08-16
	描述：重写了单据导入草稿的存储过程
*/
CREATE PROCEDURE QP_Gp_QueryBillIndexAuditing
( 
	@BeginDate		VARCHAR(25),
	@EndDate  		VARCHAR(25),
	@BtypeId  		VARCHAR(50),
	@EtypeId  		VARCHAR(50),
	@KtypeId  		VARCHAR(50),	
	@PtypeId  		VARCHAR(50),
	@OrderBy  		VARCHAR(50) = 'billdate DESC',
	@BillType  		VARCHAR(5) = '',
	@FilterBill 	BIT = 0 ,
	@InOut   		VARCHAR(10) = '',
	@Draft  		BIT=0,
	@ManEtype 		VARCHAR(50)='',
	@IfAudit		VARCHAR(2),	--审核的类型   -1.审核不通过  0.待审核   1.审核通过  2.没有审核  兼容以前草稿  AuditingBill 中的IfAudit
	@BillIndexType	CHAR(1), 
	-----------------------------------------------新加
	@checke 		VARCHAR(50)='',
	@BillCode 		VARCHAR(200)='', -- #&**&#
	@comment 		VARCHAR(256)='',
	@chrCheckAudit 	CHAR(1) = '',
	@RATypeId		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @checke
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)

RETURN
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid OUTPUT

IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 往来单位
CREATE TABLE #F_BaseGetManDetailBType(TypeID varchar(100))
IF (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999')
	AND @BillType IN (305,11,45,34,6,4,66,36,35,84,212,85,93,139,126,140,141,142,144,143,145,146,147,148,149,150,160,161,165,
	166,167,168,169,170,171,172,177,178,183,184,185,186,191,192,195,196,197,198,199,200)
BEGIN
	INSERT INTO #F_BaseGetManDetailBType SELECT TypeID FROM F_BaseGetManDetailBType(@chvOperatorID)
	INSERT INTO #F_BaseGetManDetailBType(TypeID) VALUES('')
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailBType B ON a.BTypeID = B.TypeID '
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
END

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)

	IF @BillType IN (305,11,45,34,6,9,14,139,126,140,142,144,146,165,167,168,169,170,171,177,178,183,191,196,197)
	BEGIN
		INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
	END

	IF @BillType IN (16,155,160,161)
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID OR a.KTypeID2 = K.TypeID '

	/*
	姜毅对维修的三种调拨单仓库权限控制备注
	请开发修改为：
	如操作员有单据入库仓库或出库仓库的任意一个的权限范围，
	a.对于单据的出入库仓库都为非空--可在调用草稿中查询出该单据。
	b.单据的出入库仓库其中一个为非空--可在调用草稿中查询出该单据。
	c.单据的出入库仓库都为空--可在调用草稿中查询出该单据。
	
	如操作员没有单据入库仓库或出库仓库的任意一个的权限范围，
	a.对于单据的出入库仓库都为非空--不能在调用草稿中查询出该单据。
	b.单据的出入库仓库其中一个为非空--不能在调用草稿中查询出该单据。
	c.单据的出入库仓库都为空--可在调用草稿中查询出该单据。
	*/
	IF @BillType IN (166,172,173,174,175)
	BEGIN
		INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K
ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID2<>'''' AND a.KTypeID2=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''') '
	END

	IF @BillType = 57
	BEGIN	
		DECLARE @KtypeLimit varchar(50)
		SELECT @KtypeLimit = MangerKtypeId FROM LoginUser WHERE ETypeID = @checke
		IF @KtypeLimit <> '00000'	-- 没有全部权限控制仓库
		BEGIN
			INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
		END
	END

	--修改人：谢吉康
	--日  期：2005-05-15
	--描  述：根据系统配置调拨当中仓库权限无效	
	IF @BillType IN (17,21)
	BEGIN
		/*
			作者：谢吉康
			日期：2005-4-15
			描述：增加调拨单中入库仓库的权限范围无效
		*/
		DECLARE @MoveInOutKLimit int
		SELECT @MoveInOutKLimit = Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit'
		IF @MoveInOutKLimit = 1 SET @MoveInOutKLimit = 0
		ELSE SET @MoveInOutKLimit = 1

		INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
		IF @MoveInOutKLimit = 1
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K
ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID2<>'''' AND a.KTypeID2=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''') '
		ELSE
			SET @SQL_Man = @SQL_Man +
' INNER JOIN #F_BaseGetManDetailKType K ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''')
INNER JOIN #F_BaseGetManDetailKType K1 ON (a.KTypeID2<>'''' AND a.KTypeID2=K1.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K1.TypeID='''') '
	END
END

-- ******** 权限范围单独处理 - End ********

DECLARE @re 			int,	-- 修改他人草稿的权限
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@ReLimitPass 	int		-- 单据过帐权限
/*
	修改人：谢吉康
	日  期：2004-04-10
	描  述：有审核权限的人不受是否修改他人草稿权限的限制[修改成修改他人草稿权限优先]
*/
DECLARE @offset INT
IF (@checke = '00001')
	SET @re = 0
ELSE
BEGIN	
	SELECT @offset = 135	-- 检查某人是否有查看管辖职员草稿得权限
	EXEC @re = GP_CheckLimit @checke,@offset
	EXEC @Re467 = GP_CheckLimit @checke,467

	IF @re = 1 AND (@IfAudit = 0 OR @IfAudit = 1)
	BEGIN
		IF @IfAudit=0
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet
				WHERE BillType = @BillType AND IfUse = 1 AND LEFT(AuditingReason,1) <> 1)	-- 检查单据是否有审核流程
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet A,AuditingFlowDetail B
					WHERE A.AuditingID = B.AuditingID AND A.BillType = @BillType AND A.IfUse = 1
					AND LEFT(A.AuditingReason,1) <> 1 AND B.ETypeID = @checke)	-- 检测具体人针对具体的单据是否有审核流程
				BEGIN
					IF @Re467 = 0
						SET @re = 0
					ELSE
						SET @re = 1
				END
				ELSE
					IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail B,AuditingFlowSet A
						WHERE A.AuditingID = B.AuditingID AND B.ETypeID = @checke
						AND B.AuditingStep = 0 AND A.BillType = @BillType)	-- 检测用户是否具有特批人权限
					BEGIN
						IF @Re467 = 0
							SET @re = 0
						ELSE
							SET @re = 1
					END
			END
		END
		ELSE 
			SET @re = 0
	END
END
IF @re = 2 RETURN @re

---------------- 判断单据是否有审核流程 谢吉康  2003-11-20
DECLARE @IsExistFlowSet int
IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType AND IfUse = 1 AND Substring(AuditingReason,1,1)<>1)
	SELECT @IsExistFlowSet = 1
ELSE
	SELECT @IsExistFlowSet = 0
-----------------------------------------------------------------------------------------------

DECLARE @SQL varchar(3000)
SET @SQL = '
	SELECT	DISTINCT
			a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.ETypeID,
			a.BTypeID,
			a.Comment,
			e.fullname AS createfullname,
			c.PlateNumber AS rafullname
			
	FROM	BillIndex a 
			INNER JOIN Billindex_CarRepair b ON a.BillNumberId = b.BillNumberId
			LEFT JOIN QP_RepairAutoInfo c ON b.RATypeID = c.TypeID 
			LEFT JOIN employee e ON a.checke=e.typeid
	
	' + @SQL_Man

IF @IsExistFlowSet = 1	-- 单据有审核流程
BEGIN
	IF @IfAudit = 2
		SET @SQL = @SQL + '
	WHERE	NOT EXISTS(
				SELECT ab.BillNumberID FROM AuditingBill ab
				WHERE a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 2
			) AND'
	ELSE
		SET @SQL = @SQL + '
	INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID AND ab.BillIndexType = 2 AND ab.IfAudit = ''' + @IfAudit + '''
	WHERE'
END
ELSE SET @SQL = @SQL + '
	WHERE '

SET @SQL = @SQL + '  a.BillDate >= ''' + @BeginDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			AND a.BillType = ' + @BillType + '
			AND a.ifCheck=''f'' AND a.Draft = 1 AND a.RedWord = 0'
IF @RATypeId<>''
BEGIN
	SELECT @SQL= @SQL +' and  b.RATypeID='''+@RATypeId+''' '
END

IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @re <> 0 SET @SQL = @SQL + ' AND a.Checke = ''' + @checke + ''''
IF @BTypeID <> '' SET @SQL = @SQL + ' AND a.BTypeID=''' + @BTypeID + ''''
IF @ETypeID <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @ETypeID + ''''
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC, a.BillCode'

EXEC (@SQL)
DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_ReceptionRegPtypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_ReceptionRegPtypeDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

查询接待登记单的维修配件
*/
CREATE          PROCEDURE Qp_Gp_ReceptionRegPtypeDetail
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(8000)

SET @SQL='
SELECT  a.BillNumberId,
		a.Qty,
		a.Price,
		a.total,
		a.ptypeId as typeid,
		p.FullName,
		p.usercode,
		a.insurance,
		a.id,
		a.comment
FROM    Qp_ReceptionBill_PType a
        LEFT JOIN dbo.ptype p ON a.PTypeID = p.typeId    
WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))   
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_ReceptionRegRIDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_ReceptionRegRIDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

查询接待登记单的维修配件

*/
CREATE          PROCEDURE QP_GP_ReceptionRegRIDetail
( 
 @BillNumberId numeric(10,0),
 @Insurance INT  =''--状态
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(8000)

SET @SQL=' 
SELECT  a.BillNumberId,
        a.StandardManHour AS standardmanhour,
        a.CheckHour AS checkmanhour,
        a.total as manhourexpense,--工时费
        a.insurance,
        a.comment,
        b.fullname,
        b.typeid,
        b.ChargeMode,
        b.UserCode,
        a.costtotal,
        a.Comment,
        a.repairman, --派工第一人+等（职员）
        a.discount,
        a.discounttotal,--CAST((a.total*a.discount) as DECIMAL(18,2))as discounttotal,
        a.id,
        a.virtual as virtual1,
        a.repairprocess,
        a.comment,
        a.ID AS QuickOrReceptionBillId
FROM    Qp_ReceptionBill_RepairItems  a
        LEFT JOIN QP_RepairItems b ON a.RepairItemsTypeID = b.TypeID
WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))+''
if ISNULL(@Insurance,'')<>'' 
	SET @SQL=@SQL+'  AND a.Insurance='+@Insurance
SET @SQL=@SQL+' order by a.ID '	
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_RepairBalanceBill_SelfPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_RepairBalanceBill_SelfPtype]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

查询维修结算单本身的维修配件

*/
CREATE          PROCEDURE Qp_Gp_RepairBalanceBill_SelfPtype
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
/*查询接待登记相关联的领料出库*/


DECLARE
	@BillType		INT
	
SELECT @BillType=BillType
FROM BillIndex
WHERE BillNumberId=@BillNumberId	

DECLARE @SQL VARCHAR(MAX)

IF @BillType=195
BEGIN
	SET @SQL=' 
	SELECT		
				pb.ID,
				SUM(pb.Qty) as qty,
				pb.Price,
				pb.Total,
				pb.Discount,
				pb.DiscountPrice,
				pb.DiscountTotal,
				pb.Insurance,
				pb.PTypeID as typeid,
				pb.ID,
				p.UserCode,
				p.FullName,
				pb.ReceptionBillPTypeID AS QuickOrReceptionBillId,
				pb.CostTotal,
				pb.Comment
	FROM	billindex b
			INNER JOIn  Qp_ReceptionBill_FactUsePType pb ON b.billnumberid=pb.ReceptionBillNumberID
			INNER JOIN  ptype p ON p.typeId=pb.PTypeID
	WHERE b.BillNumberID='+CAST(@BillNumberId AS VARCHAR(10))+' AND pb.insurance=2  AND pb.CounterClaimStatus=0 
	GROUP BY	pb.Price,
				pb.Total,
				pb.Discount,
				pb.DiscountPrice,
				pb.DiscountTotal,
				pb.Insurance,
				pb.PTypeID,
				pb.ID,
				p.UserCode,
				p.FullName,
				pb.ReceptionBillPTypeID,
				pb.CostTotal,
				pb.Comment
	HAVING SUM(pb.Qty)>0
	ORDER BY pb.ID
				'	
END
ELSE
BEGIN
	SET @SQL=' 
	SELECT		
				pb.ID,
				SUM(pb.Qty) as qty,
				pb.Price,
				pb.Total,
				pb.Discount,
				pb.DiscountPrice,
				pb.DiscountTotal,
				pb.Insurance,
				pb.PTypeID as typeid,
				pb.ID,
				p.UserCode,
				p.FullName,
				pb.ID AS QuickOrReceptionBillId,
				pb.GoodsCostTotal AS CostTotal,
				pb.Comment
	FROM	billindex b
			INNER JOIn  QP_QuickRepairBill_PType pb ON b.billnumberid=pb.BillNumberId
			INNER JOIN  ptype p ON p.typeId=pb.PTypeID
	WHERE b.BillNumberID='+CAST(@BillNumberId AS VARCHAR(10))+' AND pb.insurance=2  AND pb.CounterClaimStatus=0 
	GROUP BY	pb.Price,
				pb.Total,
				pb.Discount,
				pb.DiscountPrice,
				pb.DiscountTotal,
				pb.Insurance,
				pb.ID,
				pb.ID,
				p.UserCode,
				p.FullName,
				pb.PTypeID,
				pb.GoodsCostTotal,
				pb.Comment
	HAVING SUM(pb.Qty)>0
	ORDER BY pb.ID
				'	
END

PRINT @SQL
 
EXEC(@SQL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_RepairBalanceBill_SelfRepairItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_RepairBalanceBill_SelfRepairItems]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

三包索赔单查询维修结算单的三包维修项目

*/
CREATE          PROCEDURE Qp_Gp_RepairBalanceBill_SelfRepairItems
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE
	@BillType		INT
	
SELECT @BillType=BillType
FROM BillIndex
WHERE BillNumberId=@BillNumberId	

DECLARE @SQL VARCHAR(8000)

IF @BillType=195
BEGIN

	SET @SQL=' 
	SELECT  a.BillNumberId,
			a.StandardManHour AS standardmanhour,
			a.CheckHour AS checkmanhour,
			a.total as manhourexpense,--工时费
			a.insurance,
			a.comment,
			b.fullname,
			b.typeid,
			b.ChargeMode,
			b.UserCode,
			a.costtotal,
			a.Comment,
			a.repairman, --派工第一人+等（职员）
			a.discount,
			a.discounttotal,--CAST((a.total*a.discount) as DECIMAL(18,2))as discounttotal,
			a.id,
			a.virtual as virtual1,
			a.repairprocess,
			a.comment,
			a.ID AS QuickOrReceptionBillId
	FROM    Qp_ReceptionBill_RepairItems  a
			LEFT JOIN QP_RepairItems b ON a.RepairItemsTypeID = b.TypeID
	WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))+'
	AND a.Insurance=2 AND CounterClaimStatus=0 '

END
ELSE
BEGIN
	SET @SQL=' 
	SELECT  a.BillNumberId,
			a.StandardManHour AS standardmanhour,
			a.CheckHour AS checkmanhour,
			a.total as manhourexpense,--工时费
			a.insurance,
			a.comment,
			b.fullname,
			b.typeid,
			b.ChargeMode,
			b.UserCode,
			a.costtotal,
			a.Comment,
			c.FullName AS repairman, --派工第一人+等（职员）
			a.discount,
			a.discounttotal,--CAST((a.total*a.discount) as DECIMAL(18,2))as discounttotal,
			a.id,
			0 as virtual1,
			3 AS repairprocess,
			a.comment,
			a.ID AS QuickOrReceptionBillId
	FROM    QP_QuickRepairBill_RepairItems  a
			LEFT JOIN QP_RepairItems b ON a.RepairItemsTypeID = b.TypeID
			INNER JOIN Employee c
			ON a.RepairManTypeID=c.TypeID
	WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))+'
	AND a.Insurance=2  AND CounterClaimStatus=0 '
END

EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_Gp_RepairSetMeal_Fittings_Save]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_Gp_RepairSetMeal_Fittings_Save]
GO


----========================
----修改者：蔡志成
----日期：2010-7-22
----描述：汽配维修套餐档案配件修改或添加
----========================
CREATE  PROCEDURE QP_Gp_RepairSetMeal_Fittings_Save
    (
      @str_TypeID [varchar](50),
      @str_PTypeID [varchar](50),
      @num_Qty  NUMERIC(24, 10) ,
      @num_Price  NUMERIC(24, 10) ,
      @num_Total  NUMERIC(24, 10) ,
      @int_rowIndex INT
    )
--@encode$--
AS 
    SET NOCOUNT ON
    
    IF @int_rowIndex=0
    	DELETE dbo.QP_RepairSetMeal_Fittings WHERE TypeID=@str_TypeID
    
	IF EXISTS(SELECT 1 FROM dbo.ptype WHERE TypeID=@str_PTypeID AND sonnum>0)	
		SELECT '商品已被分类，不能添加！'
		
	INSERT dbo.QP_RepairSetMeal_Fittings (
		TypeID,
		PTypeID,
		Qty,
		Price,
		Total
	) VALUES ( 
		@str_TypeID,
		@str_PTypeID,
		@num_Qty,
		@num_Price,
		@num_Total
	) 
    
    SELECT ''
    
	SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_Gp_RepairSetMeal_Insert]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_Gp_RepairSetMeal_Insert]
GO


----========================
----修改者：蔡志成
----日期：2010-7-22
----描述：汽配维修套餐档案
----========================
CREATE  PROCEDURE QP_Gp_RepairSetMeal_Insert
    (
      @p_ParId [varchar](50),
      @p_UserCode [varchar](300),
      @p_FullName [varchar](300),
      @p_Failure [varchar](300),
      @p_DealTenet [varchar](300),
      @P_pycode   [varchar] (100),
      @p_TypeID [VARCHAR](200) OUT
    )
--@encode$--
AS 
    SET NOCOUNT ON
    DECLARE @nReturntype INT,
        @EtypeId_1 [varchar](50),
        @nSoncount INT,
        @nSonnum INT,
        @leveal SMALLINT

-- 获得新的ID号
    EXEC @nReturntype= Gp_createId @p_ParId, 'QP_RepairSetMeal', @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT
    IF @nReturntype = -1 
        RETURN -1
    IF @nReturntype = -2 
        RETURN -2
-- 判断重复的ID,UserCode
    IF EXISTS ( SELECT  TypeID
                FROM    [QP_RepairSetMeal]
                WHERE   typeId = @EtypeId_1
                        OR usercode = @p_UserCode) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
			SELECT TOP 1  @p_TypeID=FullName
            FROM    [QP_RepairSetMeal]
            WHERE   typeId = @EtypeId_1
                    OR usercode = @p_UserCode
                    
			SELECT @p_TypeID=@p_TypeID+',-3'
            RETURN -3
        END
        
    IF EXISTS ( SELECT  TypeID
                FROM    [QP_RepairSetMeal]
                WHERE   typeId = @EtypeId_1
                        OR FullName = @p_FullName) 
        BEGIN
	--print '['+@p_UserCode+']商品已存在'
			SELECT @p_TypeID=@p_FullName+',-5'
            RETURN -5
        END
        
    SELECT  @leveal = leveal
    FROM    QP_RepairSetMeal
    WHERE   typeid = @p_ParId
    SELECT  @leveal = @leveal + 1
    

    INSERT dbo.QP_RepairSetMeal (
		TypeID,
		ParID,
		Leveal,
		SonCount,
		SonNum,
		UserCode,
		FullName,
		Failure,
		DealTenet,
		pycode
	) VALUES ( 
		@EtypeId_1,
		@p_ParId,
		@leveal,
		0,
		0,
		@p_UserCode,
		@p_FullName, 
		@p_Failure,
		@p_DealTenet,
		@P_pycode
      ) 
	SELECT @p_TypeID=@EtypeId_1
	
	
    UPDATE  [QP_RepairSetMeal]
    SET     sonnum = @nSonnum + 1,
            soncount = @nSoncount + 1
    WHERE   typeid = @p_ParId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_Gp_RepairSetMeal_Items_Save]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_Gp_RepairSetMeal_Items_Save]
GO


----========================
----修改者：蔡志成
----日期：2010-7-22
----描述：汽配维修套餐档案项目修改或添加
----========================
CREATE  PROCEDURE QP_Gp_RepairSetMeal_Items_Save
    (
      @str_TypeID [varchar](50),
      @str_RepairItemsTypeID [varchar](50),
      @num_StandardManHour  NUMERIC(24, 10) ,
      @num_CheckManHour  NUMERIC(24, 10) ,
      @num_ManHourExpense  NUMERIC(24, 10) ,
      @int_rowIndex INT
    )
--@encode$--
AS 
    SET NOCOUNT ON
    
    
    IF @int_rowIndex=0
		DELETE dbo.QP_RepairSetMeal_Items WHERE TypeID=@str_TypeID
		
	IF EXISTS(SELECT 1 FROM dbo.QP_RepairItems WHERE TypeID=@str_RepairItemsTypeID AND SonNum>0)	
		SELECT '维修项目已被分类，不能添加！'
    
    INSERT dbo.QP_RepairSetMeal_Items (
		TypeID,
		RepairItemsTypeID,
		StandardManHour,
		CheckManHour,
		ManHourExpense
	) VALUES 
	( 
      @str_TypeID,
      @str_RepairItemsTypeID,
      @num_StandardManHour,
      @num_CheckManHour,
      @num_ManHourExpense		
	) 
    
    SELECT ''
    
	SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_Gp_RepairSetMeal_Update]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_Gp_RepairSetMeal_Update]
GO


----========================
----修改者：蔡志成
----日期：2010-7-22
----描述：汽配维修套餐档案
----========================
CREATE  PROCEDURE QP_Gp_RepairSetMeal_Update
    (
      @p_TypeId [varchar](50),
      @p_UserCode [varchar](200),
      @p_FullName [varchar](200),
      @p_Failure [varchar](200),
      @p_DealTenet [varchar](200),
      @P_pycode   [varchar] (100),
      @p_TypeIDOut	VARCHAR(200) OUT 
    )
--@encode$--
AS 
    IF EXISTS(SELECT * FROM QP_RepairSetMeal WHERE (UserCode=@p_UserCode) AND TypeID<>@p_TypeId)
    BEGIN
		SELECT TOP 1 @p_TypeIDOut=FullName FROM QP_RepairSetMeal WHERE UserCode=@p_UserCode AND TypeID<>@p_TypeId
		SELECT @p_TypeIDOut=@p_TypeIDOut+',-3'
		RETURN
	END
		
    IF EXISTS(SELECT * FROM QP_RepairSetMeal WHERE (FullName=@p_FullName) AND TypeID<>@p_TypeId)
    BEGIN
		
		SELECT TOP 1 @p_TypeIDOut=FullName FROM QP_RepairSetMeal WHERE FullName=@p_FullName AND TypeID<>@p_TypeId
		SELECT @p_TypeIDOut=@p_TypeIDOut+',-5'
		RETURN 
	END
		
	SELECT @p_TypeIDOut=@p_TypeId
			
	UPDATE dbo.QP_RepairSetMeal
	SET UserCode=@p_UserCode,
		FullName=@p_FullName,
		Failure=@p_Failure,
		DealTenet=@p_DealTenet,
		PYCode =@P_pycode 
	WHERE TypeID=@p_TypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_Gp_SaveNVipWashCarTimesConfig]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_Gp_SaveNVipWashCarTimesConfig]
GO
-- =============================================
-- Author:		wangwei 
-- Create date: 2011-05-30
-- Description:	汽配保存洗车次数充值单操作员快冲配置
-- =============================================
CREATE PROCEDURE QP_Gp_SaveNVipWashCarTimesConfig
(
	@OperatorId VARCHAR(50),
	@EtypeId	VARCHAR(50),
	@StypeId	VARCHAR(50),
	@DtypeId	VARCHAR(50)
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON;
	
    DELETE FROM nVipWashCarTimesConfig WHERE OperatorId=@OperatorId
    INSERT nVipWashCarTimesConfig(OperatorId,EtypeId,StypeId,DtypeId) VALUES(@OperatorId,@EtypeId,@StypeId,@DtypeId)
    RETURN 0
END
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_SaveSuccorTpe]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_SaveSuccorTpe]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：韩林
	日期：2011-04-20
	描述：修改救援类型
*/

CREATE PROCEDURE Qp_Gp_SaveSuccorTpe
(
	@otype varchar(max),    --操作类型
	@succorid int,			--救援类型ID
	@fullname varchar(max),	--救援类型名称
	@pycode  varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @Msg varchar(max)

IF @otype='add'
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM Qp_SuccorType WHERE FullName=@fullname)
		BEGIN
		SET @Msg='救援类型名称重复，请检查！'+CHAR(10)+CHAR(10)
		SET @Msg+='要放弃编辑，按【Esc】键可关闭窗口退出'
			RAISERROR(@Msg,16,1)
			RETURN
		END
	INSERT INTO Qp_SuccorType
	(
		FullName,
		PYCode 
	)
	VALUES
	(
		@fullname,
		@pycode 
	)
	IF @@ROWCOUNT=0
		RAISERROR('添加救援类型失败！',16,1)
	RETURN
END

IF EXISTS(SELECT TOP 1 1 FROM Qp_SuccorType WHERE FullName=@fullname AND SuccorId<>@succorid)
	BEGIN
	SET @Msg='救援类型名称重复，请检查！'+CHAR(10)+CHAR(10)
	SET @Msg+='要放弃编辑，按【Esc】键可关闭窗口退出'
		RAISERROR(@Msg,16,1)
		RETURN
	END
UPDATE	Qp_SuccorType
SET		FullName=@fullname,
        pycode=@pycode 
WHERE	SuccorId=@succorid

IF @@ROWCOUNT=0
	RAISERROR('修改救援类型失败！',16,1)
RETURN
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_Gp_SaveVipConfiscateConfig]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_Gp_SaveVipConfiscateConfig]
GO
-- =============================================
-- Author:		徐辉
-- Create date: 2011-05-30
-- Description:	汽配保存操作员快冲配置
-- =============================================
CREATE PROCEDURE QP_Gp_SaveVipConfiscateConfig
(
	@OperatorId VARCHAR(50),
	@EtypeId	VARCHAR(50),
	@StypeId	VARCHAR(50),
	@DtypeId	VARCHAR(50)
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON;
	
    DELETE FROM nVipConfiscateConfig WHERE OperatorId=@OperatorId
    INSERT nVipConfiscateConfig(OperatorId,EtypeId,StypeId,DtypeId) VALUES(@OperatorId,@EtypeId,@StypeId,@DtypeId)
    RETURN 0
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_SelectBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_SelectBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
修改原因：调草稿时也调出vip信息
修 改 人：蔡志成
修改标记：#01
修改时间：2010-8-16
*/
CREATE          PROCEDURE QP_GP_SelectBillIndex 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
--,车辆信息
SELECT au.*,s.FullName,s.ID as inpricetype
INTO #RepairAutoInfo
FROM QP_RepairAutoInfo au
LEFT JOIN QP_ChargingStandards s ON au.ChargingStandardsID=s.ID

declare @sql varchar (MAX)
select @sql='
SELECT a.BillNumberId,
		(SELECT c.VipCardNo
		FROM VipCardSign c,VipCardSet d,VipCardConsume e
		WHERE c.VipCardNo = e.VipCardNo AND d.VipCardId = c.VipCardId AND e.BillNumberID = '+cast(@billnumberid as char)+') AS VipCardNo,
		(SELECT d.VipCardKL  
		FROM VipCardSign c,VipCardSet d,VipCardConsume e
		WHERE c.VipCardNo = e.VipCardNo AND d.VipCardId = c.VipCardId AND e.BillNumberID = '+cast(@billnumberid as char)+') AS VipCardKL,
		a.BillDate,
		a.BillCode,
		a.BillType,
		a.Comment,
		a.atypeid,
		(CASE ISNULL(a.IfMulAccount,''0'') WHEN 1 THEN ''【多账户】''
				ELSE ISNULL(ap.fullname,'''') END 
		) as atype,
		CASE WHEN ISNULL(a.CwCheck,0) = 0 THEN ''否'' ELSE ''是'' END AS CwCheck,
		a.ptypeid,
		a.btypeid,
		a.etypeid,
		a.ktypeid,
		a.ktypeid2,
		a.ifcheck,
		a.checke,
		a.totalmoney,
		a.totalinmoney,
		a.totalqty,
		a.tax,
		a.period,
		a.explain,
		a.RedWord,
		a.draft,
		a.OrderId,
		a.waybillcode,
		a.goodsnumber,
		a.packway,
		a.TEL,
		a.Uploaded,
		a.OFF_ID,
		a.TeamNo,
		a.AlertDay,
		a.CompleteTotal,
		a.ID,
		a.Assessor,
		a.IfAudit,
		a.Audit_explain,
		a.IfStopMoney,
		a.preferencemoney,
		a.DTypeId,
		a.JF,
		a.VipCardID,
		a.vipCZMoney,
		a.jsStyle,
		a.jsState,
		a.KTypeID3,
		a.LinkMan,
		a.LinkTel,
		a.LinkAddr,
		a.wxManID,
		a.JieJianBillNumberID,
		a.JieJianID,
		a.JieJianState,
		a.BaoXiuBillNumberID,
		a.BaoXiuID,
		a.BuyDate,
		a.Serial,
		a.wxTotal,
		a.ErrDes,
		a.ifHideJieJian,
		a.ifWX,
		a.ifYearBill,
		a.stypeid,
		(CASE	WHEN   a.BillType=192 
				THEN   au.inpricetype
				ELSE b.inpricetype END) as inpricetype,
		b.RATypeID,
		b.OperationSort,
		b.RepairMode,
		b.Oil,
		b.Mileage,
		b.EpibolyItem,
		b.OtherItem,
		b.Status,
		b.ManHourTotal,
		b.ManHourTax,
		b.ManHourTaxTotal,
		b.PTypeTotal,
		b.PTypeTax,
		b.PTypeTaxTotal,
		b.EpibolyTotal,
		b.OtherTotal,
	    b.invoicemode,
	    b.invoicecode,
	    b.BillState,
	    b.repairtype,
	    b.bespokedate,
	    b.receptiondate,
	    b.completedate,
	    b.infactorydate,
	    case isnull(b.RepairAutoTypeId,'''') when '''' then au.RepairAutoTypeId else b.RepairAutoTypeId end as wctypeid,
	    --isnull(b.RepairAutoTypeId,au.RepairAutoTypeId) as wctypeid,
	    isnull(RAT.fullname,rat2.fullname) as wcfullname,
	    b.receptionId, --接车人
	    b.unitsatrap,--单位主管
	    ISNULL(b.factcompletedate,''9999-12-31'') as factcompletedate,
	    b.errdescription,
	    b.sendperson,
	    e2.fullname as receptionname,
	    e3.fullname as unitsatrapname,
		c.fullname AS bfullname,
		e.fullname AS checkman,
		e1.fullname AS efullname,
		k.fullname AS kfullname,
		k1.fullname as kfullname2,
		f.fullname AS dfullname,
		au.PlateNumber AS rafullname,
		au.baoxianbtypeid as btypeid1,
		b1.fullname as bfullname1,
		ISNULL(aa.BillDetail, '''') AS BillDetail,
		(SELECT isnull(fullname,'''') FROM Stype b WHERE a.stypeid = b.typeid) AS sfullname,
		repairbillid=(select billcode from billindex where billnumberid=b.QuickRepairBillID),
		b.quickrepairbillid,
		b.preferencereason,
		b.settlementkickback,
		b.intendingkickback,
		b.epibolycosttotal,
		b.balancedate,
		ISNULL(c.price,''-1'') as pricetype  --查询该往来单位对应的适用价格
FROM dbo.BillIndex a
INNER JOIN dbo.Billindex_CarRepair b ON a.BillNumberId=b.BillNumberId AND a.billtype=b.billtype
LEFT JOIN QP_RepairAutoType RAT ON RAT.typeid=B.RepairAutoTypeId
LEFT JOIN dbo.btype c ON a.btypeid=c.typeid
LEFT JOIN dbo.employee e ON a.checke=e.typeid
LEFT JOIN dbo.employee e1 ON a.etypeid= e1.typeid 
Left JOIN dbo.employee  e2 On b.receptionId=e2.typeid
Left JOIN dbo.employee  e3 On b.unitsatrap=e3.typeid
LEFT JOIN Stock k ON a.ktypeid= k.typeid
LEFT JOIN dbo.Stock k1 ON a.Ktypeid2=k1.typeid
LEFT JOIN dbo.Department f ON a.dtypeid = f.typeid
LEFT JOIN #RepairAutoInfo au ON b.ratypeid = au.typeid 
LEFT JOIN btype	b1 ON au.baoxianbtypeid=b1.typeid
LEFT JOIN QP_RepairAutoType rat2 ON au.RepairAutoTypeId = rat2.typeid 
LEFT JOIN ATYPE ap on a.atypeid = ap.typeid
LEFT JOIN AuditingBill aa ON (  a.billnumberid=aa.billnumberid
                                       AND aa.BillIndexType = 2
                              )
WHERE  a.billnumberid = '+cast(@billnumberid as char)
		
--print @sql
exec (@sql)

DROP TABLE #RepairAutoInfo








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_SelectIntBillPTypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_SelectIntBillPTypeDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
修改原因：调草稿项目明细
修 改 人：蔡志成
修改标记：#01
修改时间：2010-8-16
*/
CREATE          PROCEDURE QP_GP_SelectIntBillPTypeDetail
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 



SELECT  a.BillNumberId,
        a.Qty,
        a.Price,
        a.total,
        p.typeId,
        p.UserCode,
        p.FullName,
		accountqty=isnull((select sum(qty) from GoodsStocks where ktypeid=b.ktypeid and ptypeid=a.ptypeid),0),
        a.isunit2 AS unittwo,
        a.isunit2 AS isunittwo,
        CASE a.isunit2 WHEN 1 THEN p.unit2 ELSE p.unit1 END AS unit
FROM    QP_EvaluationBill_PType a
		INNER JOIN BillIndex  b ON b.BillNumberId=@BillNumberId AND a.BillNumberId=b.BillNumberId
        LEFT JOIN dbo.ptype p ON a.PTypeID = p.typeId    
WHERE a.BillNumberId=@BillNumberId        


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_SelectIntBillRIDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_SelectIntBillRIDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
修改原因：调草稿项目明细
修 改 人：蔡志成
修改标记：#01
修改时间：2010-8-16
*/
CREATE          PROCEDURE QP_GP_SelectIntBillRIDetail
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 


SELECT  a.BillNumberId,
        a.StandardManHour AS standardmanhour,
        a.CheckHour AS checkmanhour,
        a.Total AS manhourexpense,
        b.fullname,
        b.typeid,
        b.ChargeMode,
        b.UserCode
FROM    QP_EvaluationBill_RepairItems a
        LEFT JOIN QP_RepairItems b ON a.repairitemstypeid = b.TypeID
WHERE a.BillNumberId=@BillNumberId        


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_SelectQp_SuccorBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_SelectQp_SuccorBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
修改原因：调草稿时也调出vip信息
修 改 人：蔡志成
修改标记：#01
修改时间：2010-8-16
*/
CREATE          PROCEDURE QP_GP_SelectQp_SuccorBillIndex 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (MAX)
select @sql='
SELECT a.BillNumberId,
		(SELECT c.VipCardNo
		FROM VipCardSign c,VipCardSet d,VipCardConsume e
		WHERE c.VipCardNo = e.VipCardNo AND d.VipCardId = c.VipCardId AND e.BillNumberID = '+cast(@billnumberid as char)+') AS VipCardNo,
		(SELECT d.VipCardKL  
		FROM VipCardSign c,VipCardSet d,VipCardConsume e
		WHERE c.VipCardNo = e.VipCardNo AND d.VipCardId = c.VipCardId AND e.BillNumberID = '+cast(@billnumberid as char)+') AS VipCardKL,
		a.BillDate,
		a.BillCode,
		a.BillType,
		a.Comment,
		a.atypeid,
		a.ptypeid,
		a.btypeid,
		a.etypeid,
		a.ktypeid,
		a.ktypeid2,
		a.ifcheck,
		a.checke,
		a.totalmoney,
		a.totalinmoney,
		a.totalqty,
		a.tax,
		CASE WHEN ISNULL(a.CwCheck,0) = 0 THEN ''否'' ELSE ''是'' END AS CwCheck,
		a.period,
		a.explain,
		a.RedWord,
		a.draft,
		a.OrderId,
		a.waybillcode,
		a.goodsnumber,
		a.packway,
		a.TEL,
		a.Uploaded,
		a.OFF_ID,
		a.TeamNo,
		a.AlertDay,
		a.CompleteTotal,
		a.ID,
		a.Assessor,
		a.IfAudit,
		a.Audit_explain,
		a.IfStopMoney,
		a.preferencemoney,
		a.DTypeId,
		a.JF,
		a.VipCardID,
		a.vipCZMoney,
		a.jsStyle,
		a.jsState,
		a.KTypeID3,
		a.LinkMan,
		a.LinkTel,
		a.LinkAddr,
		a.wxManID,
		a.JieJianBillNumberID,
		a.JieJianID,
		a.JieJianState,
		a.BaoXiuBillNumberID,
		a.BaoXiuID,
		a.BuyDate,
		a.Serial,
		a.wxTotal,
		a.ErrDes,
		a.ifHideJieJian,
		a.ifWX,
		a.ifYearBill,
		a.stypeid,
		b.inpricetype,
		b.RATypeID,
		b.OperationSort,
		b.RepairMode,
		b.Oil,
		b.Mileage,
		b.EpibolyItem,
		b.OtherItem,
		b.Status,
		b.ManHourTotal,
		b.ManHourTax,
		b.ManHourTaxTotal,
		b.PTypeTotal,
		b.PTypeTax,
		b.PTypeTaxTotal,
		b.EpibolyTotal,
		b.OtherTotal,
	    b.invoicemode,
	    b.invoicecode,
	    b.BillState,
	    b.repairtype,
	    b.bespokedate,
	    b.receptiondate,
	    b.completedate,
	    b.infactorydate,
	    b.receptionId, --接车人
	    b.unitsatrap,--单位主管
	    ISNULL(b.factcompletedate,''9999-12-31'') as factcompletedate,
	    b.errdescription,
	    b.sendperson,
	    sb.linkperson,
	    sb.linktel,
	    sb.servicecardno,
	    sb.succoraddr,
	    sb.succorid,
	    case DATEPART(yy,sb.startdate) when 9999 then null else sb.startdate end as startdate,
	    case DATEPART(yy,sb.reachdate) when 9999 then null else sb.reachdate  end as reachdate,
	    case DATEPART(yy,sb.returndate) when 9999 then null else sb.returndate end as returndate,
	    e2.fullname as receptionname,
	    e3.fullname as unitsatrapname,
		c.fullname AS bfullname,
		e.fullname AS checkman,
		e1.fullname AS efullname,
		k.fullname AS kfullname,
		k1.fullname as kfullname2,
		f.fullname AS dfullname,
		au.PlateNumber AS rafullname,
		ISNULL(ap.fullname,'''') AS atype,
		ISNULL(aa.BillDetail, '''') AS BillDetail,
		(SELECT isnull(fullname,'''') FROM Stype b WHERE a.stypeid = b.typeid) AS sfullname,
		repairbillid=(select billcode from billindex where billnumberid=b.QuickRepairBillID),
		b.quickrepairbillid,
		b.preferencereason,
		b.settlementkickback,
		b.intendingkickback,
		b.epibolycosttotal
FROM dbo.BillIndex a
INNER JOIN dbo.Billindex_CarRepair b ON a.BillNumberId=b.BillNumberId AND a.billtype=b.billtype
INNER JOIN dbo.Qp_SuccorBill sb on a.BillNumberId=sb.BillNumberId
LEFT JOIN dbo.btype c ON a.btypeid=c.typeid
LEFT JOIN dbo.employee e ON a.checke=e.typeid
LEFT JOIN dbo.employee e1 ON a.etypeid= e1.typeid 
Left JOIN dbo.employee  e2 On b.receptionId=e2.typeid
Left JOIN dbo.employee  e3 On b.unitsatrap=e3.typeid
LEFT JOIN Stock k ON a.ktypeid= k.typeid
LEFT JOIN dbo.Stock k1 ON a.Ktypeid2=k1.typeid
LEFT JOIN dbo.Department f ON a.dtypeid = f.typeid
LEFT JOIN dbo.QP_RepairAutoInfo au ON b.ratypeid = au.typeid 
LEFT JOIN ATYPE ap on a.atypeid = ap.typeid
LEFT JOIN AuditingBill aa ON (  a.billnumberid=aa.billnumberid
                                       AND aa.BillIndexType = 2
                              )
WHERE  a.billnumberid = '+cast(@billnumberid as char)
		
--print @sql
exec (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_SelectRepairFirstBillPDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_SelectRepairFirstBillPDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
修改原因：调草稿项目明细
修 改 人：蔡志成
修改标记：#01
修改时间：2010-8-16
--------------------------------------------
修改原因：增加明细ID,是否保险标志
修 改 人：Wang Wei
修改标记：#02
修改时间：2010-9-20

*/
CREATE          PROCEDURE QP_GP_SelectRepairFirstBillPDetail
( 
 @BillNumberId numeric(10,0),
 @Insurance	 VARCHAR(10)=''
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(8000)



SET @SQL='
	SELECT  a.BillNumberId,
        a.Qty,
        a.Price,
        a.total,
        p.typeId,
        p.UserCode,
        a.CargoSpace,
        a.Discount,
        a.DiscountPrice,
        a.DiscountTotal,
        a.Insurance,
        e.typeid AS repairmantypeid,
        e.FullName AS efullname,
        p.FullName,
        a.ktypeid,
        k.fullname AS kfullname,
        a.isunit2 AS unittwo,
        a.isunit2 AS isunittwo,
        CASE a.isunit2 WHEN 1 THEN p.unit2 ELSE p.unit1 END AS unit,
        a.Comment,
        accountqty=isnull((select sum(qty) from GoodsStocks where ktypeid=a.ktypeid and ptypeid=a.ptypeid),0),
        a.ID AS AID,--#02
        a.Insurance, --#02
        a.goodscosttotal--#02
FROM    QP_QuickRepairBill_PType a
        LEFT JOIN dbo.ptype p ON a.PTypeID = p.typeId    
        LEFT JOIN dbo.Stock k ON a.ktypeid= k.typeid
        LEFT JOIN dbo.employee e ON a.RepairManTypeID = e.typeId
WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))   
     
IF @Insurance<>''
	SET @SQL=@SQL+' AND  a.Insurance='+@Insurance
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_SelectRepairFirstBillRIDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_SelectRepairFirstBillRIDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
修改原因：调草稿项目明细
修 改 人：蔡志成
修改标记：#01
修改时间：2010-8-16
--------------------------------------------
修改原因：增加明细ID,是否保险标志,工时成本
修 改 人：Wang Wei
修改标记：#02
修改时间：2010-9-20
*/
CREATE          PROCEDURE QP_GP_SelectRepairFirstBillRIDetail
( 
 @BillNumberId numeric(10,0),
 @Insurance	 VARCHAR(10)=''
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(8000)

SET @SQL=' SELECT  a.BillNumberId,
        a.StandardManHour AS standardmanhour,
        a.CheckHour AS checkmanhour,
        a.Total AS manhourexpense,
        a.Discount,
        a.DiscountTotal,
        a.Insurance,
        b.fullname,
        b.typeid,
        b.ChargeMode,
        b.UserCode,
        a.CostTotal,
        a.Comment,
        e.FullName AS efullname,
        e.typeId AS repairmantypeid,
        a.ID AS RID,--#02
        a.CostTotal,--#02
        a.Insurance --#02
        
FROM    QP_QuickRepairBill_RepairItems a
        LEFT JOIN QP_RepairItems b ON a.repairitemstypeid = b.TypeID
        LEFT JOIN dbo.employee e ON a.RepairManTypeID = e.typeId
WHERE a.BillNumberId='+CAST(@BillNumberId AS VARCHAR(100))
IF @Insurance<>''
	SET @SQL=@SQL+' AND  a.Insurance='+@Insurance
EXEC(@SQL)
        


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Gp_StopRepair]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Gp_StopRepair]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-04-21
	描述：终止维修
*/
CREATE PROCEDURE Qp_Gp_StopRepair
(
	@strBillNumberIdList	VARCHAR(MAX)	--要终止的单据编号集合
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN TRANSACTION  DEL

DECLARE @STR INT=4

CREATE TABLE #index_billnumberid (billnumberid varchar(max))
CREATE TABLE #pick_billnumberid (billnumberid varchar(max))

INSERT INTO #index_billnumberid(billnumberid) SELECT billnumberid FROM Billindex_CarRepair
WHERE BillState IN(1,2) 
AND BillNumberId IN (SELECT * FROM DBO.f_split(@strBillNumberIdList,',')) 
AND BillNumberId NOT IN (SELECT ReceptionBillnumberId FROM Qp_ReceptionBill_FactUsePType WHERE Qty>0 )

INSERT INTO #pick_billnumberid(billnumberid) SELECT bc.BillNumberId 
FROM Billindex_CarRepair bc INNER JOIN #index_billnumberid	bi ON bi.billnumberid =bc.QuickRepairBillID
INNER JOIN BillIndex B ON B.BillNumberId=BC.BillNumberId
WHERE B.draft=1

DELETE FROM Billindex_CarRepair WHERE BillNumberId IN(select * from #index_billnumberid)

DELETE FROM Billindex WHERE BillNumberId IN(select * from #index_billnumberid)

--DELETE FROM printrecord WHERE BillNumberId IN (SELECT * FROM DBO.f_split(@strBillNumberIdList,',')) AND billtype = 195 /*删除打印记录*/
UPDATE dbo.PrintRecord SET RecordState=0 WHERE BillNumberId IN (SELECT * FROM dbo.f_split(@strBillNumberIdList,',')) AND BillType=195

UPDATE Billindex_CarRepair SET QuickRepairBillID=0 WHERE QuickRepairBillID IN (select * from #index_billnumberid)

DELETE FROM Billindex WHERE	 BillNumberId IN(select * from #pick_billnumberid)

DELETE FROM Billindex_CarRepair  WHERE	 BillNumberId IN(select * from #pick_billnumberid)

IF @@ERROR<>0
BEGIN
	ROLLBACK TRANSACTION  DEL
	RETURN 0
END

COMMIT TRANSACTION  DEL

IF EXISTS(SELECT BillState FROM Billindex_CarRepair WHERE BillState NOT IN(1,2) AND BillNumberId IN (SELECT * FROM DBO.f_split(@strBillNumberIdList,',')))
	SET @STR=1
IF EXISTS(SELECT BillState FROM Billindex_CarRepair WHERE BillState IN(1,2) AND BillNumberId IN (SELECT * FROM DBO.f_split(@strBillNumberIdList,',')) AND BillNumberId IN (SELECT ReceptionBillnumberId FROM Qp_ReceptionBill_FactUsePType WHERE Qty>0))	
BEGIN
	IF	@STR=1
		SET @STR=2
	ELSE 
		SET @STR=3
END

RETURN @STR

DROP TABLE #index_billnumberid,#pick_billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_Gp_UpdateP]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_Gp_UpdateP]
GO









----========================
----修改者：吴德水
----日期：2003-05-26
----描述：增加序列号强制管理
----========================
CREATE	PROCEDURE [QP_Gp_UpdateP]
    (
      @typeid [VARCHAR](50),
      @UserCode [varchar](200),
      @FullName [varchar](200),
      @Pycode		VARCHAR(200),
      @Name [varchar](200),
      @Standard [varchar](200),
      @Type [varchar](200),
      @Area [varchar](200),
      @UnitsType INT,
      @Unit1 [varchar](200)='',
      @Unit2 [varchar](200)='',
      @UnitRate1 [varchar](200),
      @UnitRate2 [varchar](200),
      @UsefulLifeMonth [varchar](200),
      @UsefulLifeDay [varchar](200),
      @Comment [varchar](250),
      @ColorGroupID [varchar](50),
      @SizeGroupID [varchar](50),
      @EntryCode [varchar](200),
      @IfSerial [varchar](200),
     -- @PyCode [varchar](200),
      @SerialCount [varchar](200),
      @ValidDays [varchar](200),
      @DwgNo [varchar](200),
      @PreBuyPrice1  NUMERIC(24, 10) ,
      @PreBuyPrice2  NUMERIC(24, 10) ,
      @PreBuyPrice3  NUMERIC(24, 10) ,
      @PreBuyPrice4  NUMERIC(24, 10) ,
      @PreBuyPrice5  NUMERIC(24, 10) ,
      @TopBuyPrice	 NUMERIC(24, 10) ,
      @PreSalePrice1  NUMERIC(24, 10) ,
      @PreSalePrice2  NUMERIC(24, 10) ,
      @PreSalePrice3  NUMERIC(24, 10) ,
      @PreSalePrice4  NUMERIC(24, 10) ,
      @PreSalePrice5  NUMERIC(24, 10) ,
      @PreSalePrice6  NUMERIC(24, 10) ,
      @PreSalePrice7  NUMERIC(24, 10) ,
      @PreSalePrice8  NUMERIC(24, 10) ,
      @PreSalePrice9  NUMERIC(24, 10) ,
      @PreSalePrice10  NUMERIC(24, 10) ,
      @RetailPrice  NUMERIC(24, 10) ,
      @TopSalePrice  NUMERIC(24, 10) ,
      @LowSalePrice  NUMERIC(24, 10) ,
      @Brand [varchar](200),
      @Import [varchar](200),
      @GeneralType [varchar](200),
      @GeneralDwgNo [varchar](250),
      @Property [varchar](200),
      @PackageQty [varchar](200),
      @Weight [varchar](200),
      @TaxNumber [varchar](200),
      @Taxrate [varchar](200),
      @BTypeID [varchar](200),
      @FcUnit [varchar](200),
      @FcPrice [varchar](200),
      @integral [VARCHAR] (30),
      @autotypepycode [VARCHAR] (max),
      @baseUnitid		VARCHAR(20),
      @StockUnitId		VARCHAR(20),
      @BuyUnitId		VARCHAR(20),
      @SaleUnitId		VARCHAR(20),
      @AssistantUnitId  VARCHAR(20),
      @ProduceUnitId	VARCHAR(20),
      @IfUseEntryCode	INT,
      @IfUseGoodsNum	INT,
      @SonNum			INT,
      @isservice		INT,
      @Omuse			BIT,
      @omprice           NUMERIC(24, 10) ,
      @BuyDefaultRate	NUMERIC(24, 10),
      @SaleDefaultRate	NUMERIC(24, 10),
      @PtypeCategoryID VARCHAR(50),
      @InventoryTypeID VARCHAR(50),
      @iscombinationproduct INT,
      @IsScaleWeight	BIT = 0,
      @ScaleWeightType	INT = 0 ,
      @Pweight			NUMERIC(24, 10),
      @volume			NUMERIC(24, 10),
      @PtypeBrandarID	VARCHAR(50),			--商品品牌
      @othercomment1	VARCHAR(250)='',		--其他备注
      @othercomment2	VARCHAR(250)='',		--其他备注
      @othercomment3	VARCHAR(250)='',		--其他备注
      @othercomment4	VARCHAR(250)='',		--其他备注
      @othercomment5	VARCHAR(250)='',		--其他备注      
      @yjkptype			VARCHAR(200)=''			--易聚客开票品名
    )
--@encode$--
AS 
    SET NOCOUNT ON 
    
    -- 判断UserCode是否重复
	IF EXISTS(SELECT TypeID FROM [ptype] WHERE usercode=@UserCode AND typeId<>@typeid )
	BEGIN
	--print '['+@usercode+']商品已存在'
		RAISERROR('该【%s】编号已经存在，商品编号不能重复, 请填写新的编号',16,1,@usercode)RETURN--RETURN -3
	END
	
    DECLARE @Count INT   -----肖伟2002-6-5 Add For 服装版
    IF EXISTS ( SELECT  usercode
                FROM    ptype
                WHERE   ( usercode = @UserCode )
                        AND deleted <> 1
                        AND typeid <> @typeid
                        AND typeid <> '00000' ) 
        BEGIN
-- print '商品已存在'+@etypeid_1s
            RETURN -3
        END

	IF NOT EXISTS(SELECT * FROM AutoType WHERE fullname=@Type)  AND LTRIM(RTRIM(@Type))<>''
	BEGIN
		INSERT dbo.AutoType (
			fullname,
			comment,
			PYCode
		) VALUES ( @Type,'',@autotypepycode) 
	END

	DECLARE @Temp_baseUnitid	INT,
			@Temp_StockUnitId	INT,
			@Temp_BuyUnitId		INT,
			@Temp_SaleUnitId	INT,
			@Temp_AssistantUnitId	INT,
			@Temp_ProduceUnitId		INT
	
	IF @baseUnitid = ''
		SET @Temp_baseUnitid = NULL
	ELSE
		SET @Temp_baseUnitid = CONVERT(INT, @baseUnitid)
		
	IF @StockUnitId = ''
		SET @Temp_StockUnitId = @Temp_baseUnitid
	ELSE
		SET @Temp_StockUnitId = CONVERT(INT, @StockUnitId)
		
	IF @BuyUnitId = ''
		SET @Temp_BuyUnitId = @Temp_baseUnitid
	ELSE
		SET @Temp_BuyUnitId = CONVERT(INT, @BuyUnitId)
		
	IF @SaleUnitId = ''
		SET @Temp_SaleUnitId = @Temp_baseUnitid
	ELSE
		SET @Temp_SaleUnitId = CONVERT(INT, @SaleUnitId)
	
	IF @AssistantUnitId = ''
		SET @Temp_AssistantUnitId = NULL
	ELSE
		SET @Temp_AssistantUnitId = CONVERT(INT, @AssistantUnitId)
	
	IF @ProduceUnitId = ''
		SET @Temp_ProduceUnitId = @Temp_baseUnitid
	ELSE
		SET @Temp_ProduceUnitId = CONVERT(INT, @ProduceUnitId)

	IF @isservice='1'
	BEGIN
		SET @IfSerial=0
		SET @IfUseGoodsNum=0
	END
	IF DATALENGTH(@Comment) > 250
		SET @Comment = SUBSTRING(@Comment,1,125)

	
    UPDATE  [dbo].[ptype]
    SET     [UserCode] = @UserCode,
            [FullName] = @FullName,
            [pycode] = @Pycode,
            [Name] = @Name,
            [Standard] = @Standard,
            [Type] = @Type,
            [Area] = @Area,
            [UnitsType]=@UnitsType,
            [Unit1] = @Unit1,
            [Unit2] = @Unit2,
            [UnitRate1] = ISNULL(@UnitRate1,0),
            [UnitRate2] = ISNULL(@UnitRate2,0),
            [UsefulLifeMonth] = @UsefulLifeMonth,
            [UsefulLifeDay] = @UsefulLifeDay,
            [Comment] = @Comment,
            [ColorGroupID] = @ColorGroupID,       
            [SizeGroupID] = @SizeGroupID,           
            [EntryCode] = @EntryCode,
            [IfSerial] = @IfSerial,
            [serialcount] = @serialcount,
--            [PyCode] = @returnPym,
            [ValidDays] = @ValidDays,
            [DwgNo] = @DwgNo,
            [integral]=@integral,
            [baseUnitid] = @Temp_baseUnitid,
            [StockUnitId] = @Temp_StockUnitId,
            [BuyUnitId] = @Temp_BuyUnitId,
            [SaleUnitId] = @Temp_SaleUnitId,
            [AssistantUnitId] = @Temp_AssistantUnitId,
            [ProduceUnitId] = @Temp_ProduceUnitId,
            [IfUseEntryCode] = @IfUseEntryCode,
            [IfUseGoodsNum] = @IfUseGoodsNum,
            [IsService]=@isservice,
            [OMuse]=@omuse,
            [OMPrice]=@omprice,
            [BuyDefaultRate]=  dbo.F_RoundTax(@BuyDefaultRate),
            [SaleDefaultRate]=dbo.F_RoundTax(@SaleDefaultRate),
			[PtypeCategoryID]= @PtypeCategoryID,
			[InventoryTypeID]=@InventoryTypeID,
			iscombinationproduct=@iscombinationproduct,
			IsScaleWeight = @IsScaleWeight,
			ScaleWeightType = @ScaleWeightType,
			[weight]=@Pweight,
			[volume]=@volume,
			[BrandarTypeID] = @PtypeBrandarID,
			othercomment1 = @othercomment1,
			othercomment2 = @othercomment2,
			othercomment3 = @othercomment3,
			othercomment4 = @othercomment4,
			othercomment5 = @othercomment5,
			yjkptype = @yjkptype
    WHERE   ( [typeId] = @typeid )
    
    UPDATE	PType
	SET		IfUseGoodsNum = @IfUseGoodsNum
	WHERE	typeId = @typeid

	UPDATE dbo.CombinationProductIndex SET Barcode=@EntryCode,
										   CombinationProductUsercode=@UserCode,
										   CombinationProductFullName=@FullName
    WHERE CombinationProductPtypeId=@TypeID
	
	IF EXISTS(SELECT TOP 1 1 FROM QP_PType_Ext WHERE ptypeid = @typeid )
	BEGIN
		UPDATE  QP_PType_Ext
		SET     Brand = @Brand,
				Import = @Import,
				GeneralType = @GeneralType,
				GeneralDwgNo = @GeneralDwgNo,
				Property = @Property,
				PackageQty = @PackageQty,
				Weight = @Weight,
				TaxNumber = @TaxNumber,
				Taxrate = @Taxrate,
				BTypeID = @BTypeID,
				FcUnit = @FcUnit,
				FcPrice = @FcPrice
		WHERE   ptypeid = @typeid
	END
	ELSE
	BEGIN
		
		INSERT  dbo.QP_PType_Ext
				(
				  PTypeID,
				  Brand,
				  Import,
				  GeneralType,
				  GeneralDwgNo,
				  Property,
				  PackageQty,
				  Weight,
				  TaxNumber,
				  Taxrate,
				  BTypeID,
				  FcUnit,
				  FcPrice
				)
		VALUES  (
				  @typeid,
				  @Brand,
				  @Import,
				  @GeneralType,
				  @GeneralDwgNo,
				  @Property,
				  @PackageQty,
				  @Weight,
				  @TaxNumber,
				  @Taxrate,
				  @BTypeID,
				  @FcUnit,
				  @FcPrice
				) 
	END
	--如果有默认单位，则修改默认单位 ，以及价格 
	--没有，则添加新记录
	IF EXISTS(SELECT TOP 1 1 FROM PType_Price WHERE ptypeid = @typeid and isdefaultunit=1)
	BEGIN
		
		UPDATE  dbo.PType_Price
		SET     PreBuyPrice1 = @PreBuyPrice1,
				PreBuyPrice2 = @PreBuyPrice2,
				PreBuyPrice3 = @PreBuyPrice3,
				PreBuyPrice4 = @PreBuyPrice4,
				PreBuyPrice5 = @PreBuyPrice5,
				TopBuyPrice = @TopBuyPrice,
				PreSalePrice1 = @PreSalePrice1,
				PreSalePrice2 = @PreSalePrice2,
				PreSalePrice3 = @PreSalePrice3,
				PreSalePrice4 = @PreSalePrice4,
				PreSalePrice5 = @PreSalePrice5,
				PreSalePrice6 = @PreSalePrice6,
				PreSalePrice7 = @PreSalePrice7,
				PreSalePrice8 = @PreSalePrice8,
				PreSalePrice9 = @PreSalePrice9,
				PreSalePrice10 = @PreSalePrice10,
				RetailPrice = @RetailPrice,
				TopSalePrice = @TopSalePrice,
				LowSalePrice = @LowSalePrice,
				unitid=@baseUnitid
		WHERE   ptypeid = @typeid 
		and isdefaultunit=1

	END
	ELSE
	BEGIN
		
		INSERT  ptype_price
				(
				  PTypeID,
				  PreBuyPrice1,
				  PreBuyPrice2,
				  PreBuyPrice3,
				  PreBuyPrice4,
				  PreBuyPrice5,
				  TopBuyPrice,
				  PreSalePrice1,
				  PreSalePrice2,
				  PreSalePrice3,
				  PreSalePrice4,
				  PreSalePrice5,
				  PreSalePrice6,
				  PreSalePrice7,
				  PreSalePrice8,
				  PreSalePrice9,
				  PreSalePrice10,
				  RetailPrice,
				  TopSalePrice,
				  LowSalePrice,
				  unitid,
				  isdefaultunit
				)
		VALUES  (
				  @typeid,
				  @PreBuyPrice1,
				  @PreBuyPrice2,
				  @PreBuyPrice3,
				  @PreBuyPrice4,
				  @PreBuyPrice5,
				  @TopBuyPrice,
				  @PreSalePrice1,
				  @PreSalePrice2,
				  @PreSalePrice3,
				  @PreSalePrice4,
				  @PreSalePrice5,
				  @PreSalePrice6,
				  @PreSalePrice7,
				  @PreSalePrice8,
				  @PreSalePrice9,
				  @PreSalePrice10,
				  @RetailPrice,
				  @TopSalePrice,
				  @LowSalePrice,
				  @baseUnitid,
				  1
				)
	END

--保存单位
    IF @Unit1 <> '' 
        BEGIN
            IF NOT EXISTS ( SELECT  *
                            FROM    UniteName
                            WHERE   UniteName = @Unit1 ) 
                BEGIN
                    INSERT  UniteName ( UniteName )
                    VALUES  ( @Unit1 )
                END
        END
    IF @Unit2 <> '' 
        BEGIN
            IF NOT EXISTS ( SELECT  *
                            FROM    UniteName
                            WHERE   UniteName = @Unit2 ) 
                BEGIN
                    INSERT  UniteName ( UniteName )
                    VALUES  ( @Unit2 )
                END
        END
        
--未启用条码时，删除条码表的数据   
IF @IfUseEntryCode = 0
BEGIN
	DELETE FROM dbo.PType_EntryCode_Ext WHERE Ptypeid=@typeid
    DELETE FROM dbo.PType_Units_EntryCode_Ext WHERE PtypeID=@typeid
END 

--修改XiWa的XiWaMaxNumber
    DECLARE @XiWaMaxNumber NUMERIC(18, 0)
    SELECT  @XiWaMaxNumber = MAX(XiWaMaxNumber) + 1
    FROM    PType
    UPDATE  PType
    SET     XiWaMaxNumber = @XiWaMaxNumber
    WHERE   TypeId = @typeid
    
--POS下载处理
EXEC Gp_DataSaveForPosDown '-99999','Ptype','0'

EXEC Gp_DataSaveForPosDown '-99999','PType_Price','0'
EXEC Gp_DataSaveForPosDown '-99999','PType_Units_Ext','0'
select @XiWaMaxNumber=MAX(xiwamaxnumber)+1 from PType_Price
update PType_Price set XiWaMaxNumber=@XiWaMaxNumber where PTypeID=@typeid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_GP_UpdateRepairCarBack]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_GP_UpdateRepairCarBack]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




/*
	作者：WANG WEI
	日期：2010-07-26
	描述：完工后返修
*/

CREATE  PROCEDURE QP_GP_UpdateRepairCarBack
(
	@OperatorID			VARCHAR(100),
	@billnumberid		DECIMAL(18,0),
	@RepairState		INT	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
BEGIN TRANSACTION
Update Billindex_CarRepair 
SET BillState=@RepairState,
    IntendingKickback=0,
    OtherItem='',
    EpibolyItem='',
    ManHourTax=0,
    manhourtaxtotal =manhourtotal,             
    ptypetax=0,
    epibolytotal=0,
    epibolycosttotal=0,
    othertotal=0,
	preferencereason=''	
WHERE Billnumberid=@billnumberid	
Update Billindex SET preferencemoney=0,totalinmoney=0,IfMulAccount=0,VipCardID=-1,atypeid='',vipCZMoney=0 WHERE Billnumberid=@billnumberid

DELETE FROM BillMulAccount WHERE BillNumberId=@billnumberid --返修时，清空多账户

Update Qp_ReceptionBill_FactUsePType 
SET Discount=1,DiscountPrice=Price,DiscountTotal=Total
WHERE ReceptionBillnumberId=@billnumberid AND Virtual=0  --将商品返修以后，折后金额=金额 ......

Update Qp_ReceptionBill_RepairItems 
SET Discount=1,DiscountTotal=Total
WHERE Billnumberid=@billnumberid AND Virtual=0  --将维修项目返修以后，折后工时费=工时费 ......


DELETE FROM Qp_ReceptionBill_FactUsePType  WHERE ReceptionBillnumberId=@billnumberid AND Virtual=1	
DELETE FROM Qp_ReceptionBill_RepairItems  WHERE Billnumberid=@billnumberid AND Virtual=1
		
COMMIT TRAN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_HR_AddTaskDistribution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_HR_AddTaskDistribution]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：添加任务分配信息
*/
CREATE PROC [dbo].[QP_HR_AddTaskDistribution]
(
	   @Task_ID			int,					--任务id
       @BeginTime		datetime,			--开始时间
       @DeadTime		datetime,			--截止时间
       @Person_ID		int,			--员工id
       @TaskStatus_ID   int,			--任务状态
       @Remark			varchar(100)		--备注
)
--@encode$--       
AS
  INSERT INTO HR_TaskDistribution
  (
     Task_ID,
     BeginTime,
     DeadTime,
     Person_ID,
     TaskStatus_ID,
     Remark
  )
  VALUES
  (
	 @Task_ID,
	 @BeginTime,
	 @DeadTime,
	 @Person_ID,
	 @TaskStatus_ID,
	 @Remark
  )
   
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_HR_AddTaskEstimate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_HR_AddTaskEstimate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：添加任务评价
*/

/*
	修改：赵斌
	日期：2011.3.23
	描述：删除因需求变更造成的无用字段
*/

CREATE PROC [dbo].[QP_HR_AddTaskEstimate]
(
       @Content        varchar(max),
       @Task_ID        int,
       @Person_ID      int,
       @HR_ID          int,
       @DateTime       DATETIME
)
--@encode$--       
AS
  INSERT INTO HR_TaskEstimate
  (
    Content,
    Task_ID,
    Person_ID,
    HR_ID,
    DateTime
  )
  VALUES
  (
   @Content,
   @Task_ID,
   @Person_ID,
   @HR_ID,
   @DateTime
  )
  
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_HR_DeleteInterviewES]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_HR_DeleteInterviewES]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：覃雨翔
	日期：2011-3-18
	描述：删除人员评价
*/

CREATE PROC [dbo].[QP_HR_DeleteInterviewES]
(
       @ID          int
      ,@HR_ID       INT
)
--@encode$--      
AS
  DELETE FROM HR_InterviewerEstimate 
  WHERE ID=@ID and HR_ID=@HR_ID
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'QP_HR_DeleteTaskEs') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure QP_HR_DeleteTaskEs
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-19
	描述：删除任务评价
*/
CREATE PROC QP_HR_DeleteTaskEs
( 
       @ID         int,
       @HR_ID      INT
)
--@encode$--       
AS
  DELETE HR_TaskEstimate
  WHERE ID=@ID and HR_ID=@HR_ID
SET NOCOUNT ON


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'QP_HR_ModCurTaskStatus') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure QP_HR_ModCurTaskStatus
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-19
	描述：通过任务分配ID修改任务状态
*/
CREATE PROC QP_HR_ModCurTaskStatus
(
      @TaskDist_ID      int,
      @TaskStatus_ID    int,
      @EndTime          DATETIME
)
--@encode$--      
AS
  UPDATE HR_TaskDistribution
  SET  TaskStatus_ID=@TaskStatus_ID,
       EndTime=@EndTime
  WHERE ID=@TaskDist_ID
SET NOCOUNT ON


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_HR_ModPersonStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_HR_ModPersonStatus]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：覃雨翔
	日期：2011-3-18
	描述：修改人员状态
*/

CREATE PROC [dbo].[QP_HR_ModPersonStatus]
( 
        @ID          int
      ,@PersonStatus_ID   INT
)
--@encode$--      
as
  UPDATE HR_Person
  SET PersonStatus_ID=@PersonStatus_ID
  WHERE ID=@ID
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportBuyBillDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Qp_ImportBuyBillDetails
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：导入销售单据明细
	EXEC Qp_ImportDataToBillMx '00001','0','301',''
*/
CREATE PROCEDURE Qp_ImportBuyBillDetails
(
	@OperatorId		VARCHAR(50),
	@DealBtypeId    VARCHAR(50)='',
	@KTypeId        VARCHAR(50)='',
	@Sale           VARCHAR(50)='',
	@STypeId        VARCHAR(50)='',
	@bill			Tb_ImportSaleBillDetails READONLY
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------权限检查---------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------权限检查------------------------------------------------

--==========================================基础资料【BEGIN】==========================================
DECLARE @SQL VARCHAR(MAX)=''

--商品信息
CREATE TABLE #PType
(
	TypeId			VARCHAR(50),
	UserCode		VARCHAR(200),
	FullName		VARCHAR(200),
	IsService		INT,
	IfUseGoodsNum	BIT,
	IfSerial		INT,
	UnitOne			VARCHAR(200),
	UnitTwo			VARCHAR(200),
	AuxFullName1	VARCHAR(200),
	AuxFullName2	VARCHAR(200),
	AuxFullName3	VARCHAR(200),
	AuxRate1		NUMERIC(24,10),
	AuxRate2		NUMERIC(24,10),
	AuxRate3		NUMERIC(24,10),
	BuyUnitId		INT,
	SaleUnitId		INT,
	BaseUnitId		INT,
	EntryCode		VARCHAR(200)

) CREATE CLUSTERED INDEX #PType_P_K ON #PType(TypeId)
DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,'','')
SET @SQL='
	INSERT INTO #PType(
		TypeId,
		UserCode,
		FullName,
		IsService,
		IfUseGoodsNum,
		IfSerial,
		UnitOne,
		UnitTwo,
		AuxFullName1,
		AuxFullName2,
		AuxFullName3,
		AuxRate1,
		AuxRate2,
		AuxRate3,
		BuyUnitId,
		SaleUnitId,
		BaseUnitId,
		EntryCode
	)
	SELECT 
		P.TypeId,
		P.UserCode,
		P.FullName,
		P.IsService,
		P.IfUseGoodsNum,
		p.IfSerial,
		P.Unit1 UnitOne,
		P.Unit2 UnitTwo,
		PU1.FullName AuxFullName1,
		PU2.FullName AuxFullName2,
		PU3.FullName AuxFullName3,
		PE.SaleUnitRate1 AuxRate1,
		PE.SaleUnitRate2 AuxRate2,
		PE.SaleUnitRate3 AuxRate3,
		BuyUnitId,
		SaleUnitId,
		P.BaseUnitId,
		PUE.EntryCode
	'+@LinkStr+'
	LEFT JOIN PType_AuxiliaryUnits_Ext PE ON PE.PTypeID=P.TypeId
	LEFT JOIN PType_Units PU1 ON PU1.UnitsId=PE.SaleUnitID1
	LEFT JOIN PType_Units PU2 ON PU2.UnitsId=PE.SaleUnitID2
	LEFT JOIN PType_Units PU3 ON PU3.UnitsId=PE.SaleUnitID3
	LEFT JOIN PType_Units_Ext PUE ON PUE.PtypeID=P.TypeId AND PUE.UnitsId='+CASE WHEN @sale=1 THEN 'P.SaleUnitId' ELSE 'P.BuyUnitId' END+'
	WHERE 
		P.sonnum=0
		AND P.Deleted=0
		AND P.isservice=0'
EXEC(@SQL)

--库存信息
CREATE TABLE #GoodsStocks
(
	Qty		NUMERIC(24,10),
	PTypeId VARCHAR(50),
	KTypeId	VARCHAR(50)
) CREATE CLUSTERED INDEX #GoodsStocks_P_K ON #GoodsStocks(PTypeId,KTypeId)

INSERT INTO #GoodsStocks(
	Qty,
	PTypeId,
	KTypeId
)
SELECT 
	SUM(ISNULL(G.Qty,0)) Qty,
	G.PtypeId,
	G.KtypeId
FROM GoodsStocks G
INNER JOIN #PType P ON P.TypeId=G.PtypeId AND KtypeId=@KTypeId
GROUP BY 
	G.PtypeId,
	G.KtypeId
	
--主表选中的单据
CREATE TABLE #Bill
(
	BillNumberId NUMERIC(18,0),
	BillType	INT,
	BillCode	VARCHAR(200),
	BillName	VARCHAR(200)
)
CREATE CLUSTERED INDEX #Bill_P_K ON #Bill(BillNumberId)
INSERT INTO #Bill(BillNumberId,BillType,BillCode)
SELECT	DISTINCT	
		B.BillNumberId,
		B.BillType,
		B.BillCode
FROM @bill F 
INNER JOIN PosAllotApplyBillIndex B ON B.BillNumberId=F.billnumberid AND B.BillType = F.billtype
UNION ALL
SELECT DISTINCT
	B.BillNumberId,
	B.BillType,
	B.BillCode
FROM @bill F 
INNER JOIN BillIndex B ON B.BillNumberId=F.billnumberid AND B.BillType = F.billtype
	
--创建临时表，获取自定义字段
SELECT 
	cbd.BillId ,
    cbd.Detailid ,
    cbd.BillType AS Cbilltype ,
    cbd.SysDiy1 ,
    cbd.SysDiy2 ,
    cbd.SysDiy3 ,
    cbd.SysDiy4 ,
    cbd.SysDiy5 ,
    cbd.SysDiy6 ,
    cbd.SysDiy7 ,
    cbd.SysDiy8 ,
    cbd.SysDiy9 ,
    cbd.SysDiy10 ,
    cbd.SysDiy11 ,
    cbd.SysDiy12 ,
    cbd.SysDiy13 ,
    cbd.SysDiy14 ,
    cbd.SysDiy15 ,
    cbd.SysDiy16 ,
    cbd.SysDiy17 ,
    cbd.SysDiy18 ,
    cbd.SysDiy19 ,
    cbd.SysDiy20 ,
    cbd.SysDiy21 ,
    cbd.SysDiy22 ,
    cbd.SysDiy23 ,
    cbd.SysDiy24 ,
    cbd.SysDiy25 ,
    cbd.SysDiy26 ,
    cbd.SysDiy27 ,
    cbd.SysDiy28 ,
    cbd.SysDiy29 ,
    cbd.SysDiy30 ,
    cbd.SysDiy31 ,
    cbd.SysDiy32 ,
    cbd.iscombination ,
    cbd.InOrOut ,
    cbd.SysDiy33 ,
    cbd.SysDiy34 ,
    cbd.SysDiy35 ,
    cbd.SysDiy36 ,
    cbd.SysDiy37 ,
    cbd.SysDiy38 ,
    cbd.SysDiy39 ,
    cbd.SysDiy40,
	E.FullName EFullNameCustom,
	p.FullName PFullNameCustom,
	b.FullName BFullNameCustom,
	d.FullName DFullNameCustom,
	k.FullName KFullNameCustom,
	s.FullName SFullNameCustom 
INTO #Custom_T 
FROM custom_billdetails cbd 
INNER JOIN #Bill sbn ON cbd.BillId=sbn.billnumberid AND sbn.BillType=cbd.BillType
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid

DECLARE 
	@IniRow			INT=1,
	@MaxRow			INT=0,
	@NowBillType	INT,--当前billtype
	@NowBTypeName	VARCHAR(200),--当前billtype
	@Details		VARCHAR(200),--明细表表名
	
	@PriceType		VARCHAR(5)--分支机构物价信息


--分支机构物价信息
IF ISNULL(@STypeId,'')=''
	BEGIN
		SET @PriceType='0'
		SET @STypeId=''
	END
ELSE 
	SELECT @PriceType=PriceType FROM SType WHERE TypeId=@STypeId
		
	
--当前当需要查询的单据类型
CREATE TABLE #BillType(NId INT IDENTITY(1,1),BillType INT)

INSERT INTO #BillType(BillType)
SELECT BillType FROM #Bill GROUP BY BillType
SELECT @MaxRow=@@ROWCOUNT


--==========================================基础资料【END】==========================================



--==========================================业务逻辑处理【BEGIN】==========================================
SET @SQL=''

CREATE TABLE #billdetail
(
	billnumberid	NUMERIC(18),
	detailid		INT,
	billtype		INT
)
INSERT INTO #billdetail( billnumberid, detailid,billtype )
SELECT	billNumberID,detailID,billtype
FROM @bill 

WHILE(@IniRow<=@MaxRow)
BEGIN
	IF(LEN(@SQL)>0) SET @SQL+='UNION ALL'+CHAR(13)
	
	SELECT @Details=detailTable,@NowBillType=B.Billtype,@NowBTypeName=B.BillName FROM BillName B INNER JOIN #BillType T ON T.NId=@IniRow AND T.BillType=B.Billtype
	
	
	SET @SQL+='
	SELECT
		CASE DATALENGTH(ISNULL(M.Serial,''''))
						WHEN 0
							THEN ''''
						ELSE
							(SELECT TOP 1 a FROM dbo.f_splitAN(Serial,''я'') WHERE ISNULL(a,'''')<>'''')+''...'' 
					END AS Serial1,
					(''я''+(SELECT DISTINCT stuff((select ''я'' + a from 
						(
							SELECT a FROM dbo.f_split(M.Serial,''я'') 
							WHERE a NOT IN (
							SELECT ISNULL(a,'''') FROM dbo.f_split(
							(
								select [Serial] = stuff((
									select ''я'' + cast([Serial] as varchar(4000)) from pickbill t 
									inner join onShelvespickIndex o on t.billnumberid=o.billnumberid and o.ifcheck=''t'' and o.redword=0
									where  t.GoodsBillID=m.id AND m.billnumberid=t.GoodsBillNumberID AND t.GoodsBillType=B.BillType for xml path('''')) , 1 , 1 , ''''
								)  
								from pickbill p INNER JOIN dbo.onShelvespickIndex i ON p.billNumberID = i.billNumberId 
								WHERE i.IfCheck=''t'' AND i.draft=0 AND i.RedWord=0 AND p.GoodsBillID=m.id AND m.billnumberid=p.GoodsBillNumberID AND p.GoodsBillType=B.BillType
								group by ptypeid ),''я'')
							)
						) b
						where a = a for xml path('''')),1,1,'''')
						FROM (SELECT a FROM dbo.f_split(M.Serial,''я'') 
						WHERE a NOT IN (
						SELECT ISNULL(a,'''') FROM dbo.f_split(
						(
							select [Serial] = stuff(
							(
								select ''я'' + cast([Serial] as varchar(4000)) from pickbill t 
								inner join onShelvespickIndex o on t.billnumberid=o.billnumberid and o.ifcheck=''t'' and o.redword=0
								where  t.GoodsBillID=m.id AND m.billnumberid=t.GoodsBillNumberID AND t.GoodsBillType=B.BillType for xml path('''')) , 1 , 1 , ''''
							)  
							from pickbill p INNER JOIN dbo.onShelvespickIndex i ON p.billNumberID = i.billNumberId 
							WHERE i.IfCheck=''t'' AND i.draft=0 AND i.RedWord=0 AND p.GoodsBillID=m.id AND m.billnumberid=p.GoodsBillNumberID AND p.GoodsBillType=B.BillType
							group by ptypeid ),''я''))
						) c
					)+''я'') AS Serial,
		M.PTypeId,
		M.PTypeId AS TYPEID,
		P.UserCode,
		P.FullName,
		P.UnitOne,
		P.UnitTwo,
		M.Qty,
		NULL OutCargoId,
		P.AuxFullName1,
		P.AuxFullName2,
		P.AuxFullName3,
		P.AuxRate1,
		P.AuxRate2,
		P.AuxRate3,
		P.IsService,
		P.IfUseGoodsNum,
		p.IfSerial,
		PC.UserCode CustomerCode,
		P.EntryCode '+CASE WHEN @sale=1 THEN 'SaleMUnitCode,' ELSE 'BuyMUnitCode,' END+''
		+@PriceType+' PriceType,	
		M.GoodsNumber,
		M.ItemId,
		CASE WHEN M.IsCombined=0 THEN (SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
			 ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) 
		END ItemName,
		M.IsCombined,
		M.MUnitID, 	
		M.munitrate,
		PP.ReferPrice PreferPrice,
		PP.ReferPrice ReferPrice,
		ISNULL(PS.ReferPrice,0) SReferPrice,'+CHAR(13)
	--17-同价调拨单;21-变价调拨单;	
	--IF(@NowBillType IN(17,21))
	--BEGIN
	--	SET @SQL+='
	--	M.MPrice MSalePrice,
	--	M.price NSalePrice,
	--	M.price NPrice,
	--	M.Price CurmDiscountPrice,
	--	M.total NTotal,
	--	M.total NSaleTotal,
	--	'
	--END
	--126-获赠单;17-同价调拨单;21-变价调拨单;188-分支机构调拨入库单;201-其他入库单;16-生产拆装单;
	IF(@NowBillType IN(126,17,21,188,201,16,327,328,329))
	BEGIN
		SET @SQL+='
		0 MSalePrice,
		0 NSalePrice,
		0 NPrice,
		0 CurmDiscountPrice,
		0 NTotal,
		0 NSaleTotal,
		'
	END
	--215-零售退货单;45-销售退货单;160-销售换货单;142-委托代销退货单;46-组合品销售退货单;34-采购入库单;161-采购换货单;144-受托代销收货单;400-暂估入库单;403-发出商品退货单;
	IF(@NowBillType IN(34,144,142,45,46,160,161,400,403,215))
	BEGIN
		SET @SQL+='
		M.MSalePrice,
		M.NSalePrice,
		M.nsaleprice NPrice,
		M.CurmDiscountPrice,
		M.NTotal,
		M.NSaleTotal,
		'
	END
	--16-生产拆装单;
	IF(@NowBillType IN(16))
	BEGIN
		SET @SQL+='
		U.FullName AS Unit,	
		U.FullName AS Munit,	
		U.FullName AS Nunit,
		M.MUnitID as UnitId,
		M.MUnitRate as UnitRate,
		'
	END
	IF @NowBillType IN (327,328,329)--门店类
	BEGIN
		SET @SQL+='
		W.FullName AS Unit,
		U.FullName AS Munit,
		V.FullName AS Nunit,
		M.MUnitID as UnitId,
		M.MUnitRate as UnitRate,
		'
	END
	ELSE 
	BEGIN
		SET @SQL+='
		W.FullName AS Unit,
		U.FullName AS Munit,
		V.FullName AS Nunit,
		M.UnitId,
		M.UnitRate,
		'
	END

	--上架关联字段
	IF @NowBillType IN (327,328,329)
	SET @SQL += ' inktypeid KTypeID, '
	ELSE 
	SET @SQL+=' M.KTypeID, '
	
	SET @SQL+='	
		ISNULL(M.InflowQty,0) AS CQty,
		M.Qty-ISNULL(M.InflowQty,0) AS UQty,
		Ca.PathNo,
		C.FullName CFullname,
		'+CASE WHEN @NowBillType IN(17,21,188,329)/*17-同价调拨单;21-变价调拨单;188-分支机构调拨入库单; */THEN 'M.InCargoID' ELSE 'M.CargoID' END+' CargoID,
		Ca.UserCode CarGoUserCode,
		Ca.fullname CarGoFullName,
		S.FullName KFullName,
		B.BillNumberId FromBillNumberId,
		M.ID AS FromBillId,
		B.BillCode,
		B.Billtype,
		'''+@NowBTypeName+''' BillName,
		M.comment BillComment,
		M.Qty BillQty,
        M.mqty AS billmqty,
		ct.*--查询自定义字段
	FROM #Bill B
	INNER JOIN #billdetail F ON F.BillNumberId=B.BillNumberId AND F.billtype = b.billtype
	INNER JOIN '+@Details+' M ON M.BillNumberId=F.BillNumberId AND M.ID = F.detailID
	INNER JOIN #PType P ON P.TypeId=M.PtypeId'
	
	IF @NowBillType IN (327,328,329)
	SET @SQL += ' INNER JOIN stock S ON S.typeid=M.inktypeid '
	ELSE 
	SET @SQL += ' INNER JOIN stock S ON S.typeid=M.KTypeID '
	
	SET @SQL +='LEFT JOIN #Custom_T ct ON ct.BillId=M.BillNumberId AND ct.cbilltype = b.billtype'+CASE WHEN @NowBillType = 46 THEN ' and ct.InOrOut = ''I''' ELSE '' END + ' and ct.Detailid='+CASE WHEN @Details='OrderBill' THEN 'M.OrderID' ELSE 'M.id' END+'
	LEFT JOIN CargoType Ca ON Ca.CargoID='+CASE WHEN @NowBillType IN(17,21,188,329)/*17-同价调拨单;21-变价调拨单;188-分支机构调拨入库单; */ THEN 'M.InCargoID' ELSE 'M.CargoID' END+'
	LEFT JOIN CargoType C ON C.CargoID='+CASE WHEN @NowBillType IN(17,21,188,329)/*17-同价调拨单;21-变价调拨单;188-分支机构调拨入库单; */ THEN 'M.OutCargoID' ELSE 'M.CargoID' END+'
	LEFT JOIN #GoodsStocks G ON G.PTypeId=P.TypeId
	LEFT JOIN PuserCode PC ON M.PtypeId=PC.Ptypeid AND PC.btypeid='''+@DealBtypeId+'''
	LEFT JOIN PType_Units PU ON PU.UnitsId=P.BaseUnitId
	LEFT JOIN PType_Price PP ON PP.PTypeID=M.PTypeID AND PP.UnitID =M.MUnitID
	LEFT JOIN PType_StypePrice PS ON '
	
	IF @NowBillType IN (327,328,329)
	SET @SQL +=' PS.Stypeid=(select stypeid from PosAllotApplyBillIndex where billnumberid = M.billnumberid) '
	ELSE SET @SQL += ' PS.Stypeid=M.Stypeid '
	
	SET @SQL +='AND PS.PTypeID=M.PTypeID AND PS.UnitID=M.MUnitID
	LEFT JOIN dbo.PType_Units U ON U.UnitsId=M.MUnitID 
	' +CASE WHEN @NowBillType IN(16) THEN '' ELSE '
	LEFT JOIN dbo.PType_Units V ON V.UnitsId=M.NUnitID
	LEFT JOIN dbo.PType_Units W ON W.UnitsId=M.UnitID ' END +CHAR(13)

	SET @SQL+='
	WHERE
		B.billtype='+CAST(@NowBillType AS VARCHAR)+CHAR(13)
    
	--请购单
	IF(@NowBillType=204)
		SET @SQL+='	AND M.state<=8'	
			
	--160	销售换货单
	--161	采购换货单
	--16	生产拆装单	
	IF @NowBillType IN(160,161,16)
		SET @SQL+='	AND M.InOrOut=''I'''
		
	--入库仓库
	IF (ISNULL(@Ktypeid,'')<>'' AND @NowBillType<>215) 
		BEGIN
			IF @NowBillType in(17,21,188)
				SET @SQL+='	AND M.KTypeID2='''+@KTypeId+''''+CHAR(13)
			ELSE IF @NowBillType IN (327,328,329)
					SET @SQL+='	AND M.inktypeid='''+@KTypeId+''''+CHAR(13)
			ELSE
				SET @SQL+='	AND M.KTypeID='''+@KTypeId+''''+CHAR(13)
		END
	SET @IniRow+=1
END
--==========================================业务逻辑处理【END】==========================================



--==========================================执行结果并删除临时表【BEGIN】==========================================
IF(LEN(@SQL)>0)
	BEGIN
		SET @SQL='
			SELECT * FROM (
			'+@SQL+'
			) F
			ORDER BY 
				PathNo,
				FromBillNumberId,--BillNumberId
				FromBillId--ID
		'
	END
	--PRINT @SQL
EXEC(@SQL)

--删除临时表
DROP TABLE #Bill,#BillType,#Custom_T,#GoodsStocks,#PType,#billdetail

--==========================================执行结果并删除临时表【END】==========================================
				
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportBuyBillToBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Qp_ImportBuyBillToBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：导入采购类单据到 上架单
*/

CREATE PROCEDURE Qp_ImportBuyBillToBill
(
	@OperatorId		VARCHAR(100),
	
	@STypeId		VARCHAR(50)='',--分支机构
	@KTypeId		VARCHAR(50)='',--入库仓库
	@BillType		VARCHAR(100),--单据类型
	@CiteState		VARCHAR(20),--入库单状态

	@StartDate		VARCHAR(20),--开始日期
	@EndDate		VARCHAR(20),--结束日志
	@Explain		VARCHAR(1000)='',--说明
	@Comment		VARCHAR(1000)='',--摘要
	
	@DealBtypeId    VARCHAR(50)='',--往来单位
	@BtypeId		VARCHAR(50)='',--结算单位
	@Etypeid        VARCHAR(50)='',--经手人
	@Dtypeid        VARCHAR(50)=''--部门
)
--@encode$--
AS
SET NOCOUNT ON
----------------------------------------权限检查--------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
---------------------------------------权限检查------------------------------------



--==========================================基础资料【BEGIN】==========================================
--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
INSERT INTO #Stype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) F 
INNER JOIN SType D ON D.TypeId=F.TypeId

--经手人
CREATE TABLE #Etype(TypeId VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
INSERT INTO #Etype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID) F
INNER JOIN employee D ON D.typeId=F.TypeId
UNION ALL
SELECT '' TypeId,'' FullName

--部门
CREATE TABLE #Dtype(TypeId VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
INSERT INTO #Dtype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@DtypeId,9,@OperatorID) F
INNER JOIN Department D ON D.typeId=F.TypeId
UNION ALL
SELECT '' TypeId,'' FullName
	
--往来单位
CREATE TABLE #DealBtype(TypeID VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #DealBtype_P_K ON #DealBtype(TypeId)
INSERT INTO #DealBtype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId) F
INNER JOIN btype D ON D.typeId=F.TypeId
IF(ISNULL(@DealBTypeId,'')='')
	INSERT INTO #DealBtype(TypeID,FullName) VALUES( '','')
	
--结算单位
CREATE TABLE #Btype(TypeID VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
INSERT INTO #Btype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorId) F
INNER JOIN btype D ON D.typeId=F.TypeId
IF(ISNULL(@BtypeId,'')='')
	INSERT INTO #Btype(TypeID,FullName) VALUES( '','')


DECLARE 
	@SQL		VARCHAR(MAX),
	@DetailBillType	VARCHAR(50)='',
	@DetailTable	VARCHAR(500)='',
	@IniRow	INT=1,
	@MaxRow	INT=0,
	@LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,'','')--商品

--商品
CREATE TABLE #Ptype(TypeId VARCHAR(50)) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)
SET @SQL='
INSERT INTO #Ptype(TypeId)
SELECT P.typeId '+@LinkStr+' WHERE P.sonnum=0 AND P.IsService=0'
EXEC(@SQL)

CREATE TABLE #BillName(NId INT IDENTITY(1,1),BillType INT,DetailTable VARCHAR(500))
SET @SQL='
INSERT INTO #BillName(BillType,DetailTable)
SELECT BillType,DetailTable FROM BillName WHERE BillType IN('+@BillType+')'
EXEC(@SQL)
SELECT @MaxRow=@@ROWCOUNT

--明细表
CREATE TABLE #DetailBill(BillNumberId INT,BillType INT) 
CREATE CLUSTERED INDEX #DetailBill_P_K ON #DetailBill(BillNumberId)

SET @SQL=''

WHILE(@IniRow<=@MaxRow)
	BEGIN
		IF(LEN(@SQL)>1)
			SET @SQL+='UNION ALL'+CHAR(13)
			
		SELECT @DetailBillType=BillType,@DetailTable=DetailTable FROM #BillName WHERE NId=@IniRow
		
		SET @SQL+='SELECT DISTINCT '+@DetailBillType+' BillType ,B.BillNumberId
		FROM '+@DetailTable+' B 
		INNER JOIN #Ptype P ON P.TypeId=B.PTypeId '+CHAR(13)		
		
		IF ISNULL(@KTypeId,'')<>''
			BEGIN
				IF @DetailBillType IN (17,21,188)
					SET @SQL+=' AND B.ktypeid2='''+@KTypeId+''''+CHAR(13)
					
				IF @DetailBillType NOT IN (17,21,188)
					BEGIN
						-- 配送验收单特殊处理
						IF @DetailBillType IN ('329')
							SET @SQL+=' AND B.inktypeid='''+@KTypeId+''''+CHAR(13)	
						ELSE 
							SET @SQL+=' AND B.ktypeid='''+@KTypeId+''''+CHAR(13)	
					END 
			END 
			
		IF  @DetailBillType IN(160,161,16)
			SET @SQL+=' AND B.InOrOut=''I'''+CHAR(13)
			
		
		SET @IniRow+=1
	END	
	
SET @SQL='
INSERT INTO #DetailBill(BillType,BillNumberId)
SELECT BillType,BillNumberId FROM('+@SQL+') F GROUP BY BillType,BillNumberId'

--print @sql 
EXEC(@SQL)	

--门店类状态表
CREATE TABLE #DeliveryState (BillNumberId INT,ShelveRefState INT) 	
INSERT INTO #DeliveryState
SELECT	BillNumberId,
		CASE WHEN qty > pqty THEN 1 ELSE 2 END ShelveRefState
FROM	(
			SELECT pa.Qty qty,SUM(ob.qty) pqty,pa.BillNumberId  FROM PosAllotApplyBillIndex pa
			INNER JOIN  onShelvesBill ob ON GoodsBillNumberID = pa.BillNumberId
			INNER JOIN dbo.onShelvespickIndex obi ON obi.BillNumberId = ob.BillNumberId
			WHERE pa.BillType IN (SELECT * FROM dbo.f_split(@BillType,',') ) AND obi.RedWord=0
			GROUP BY pa.BillNumberId,pa.Qty
		)T
--SELECT * FROM #DeliveryState		
--==========================================基础资料【END】==========================================



--==========================================业务逻辑处理【BEGIN】==========================================
SET @SQL = '
SELECT	B.BillNumberId,
		B.BillDate,
		B.BillCode,
		B.BillType,
		CASE 
			WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
			WHEN B.IsIni=1 THEN ''期初单据''
			WHEN B.Ifcheck=''t'' THEN ''已过账'' 
			WHEN AT.IfAudit is null THEN ''原始单据''
			WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
			WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
			WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
			WHEN AT.IfAudit=''2'' THEN ''原始草稿''
		END AS BillStatus,
		BN.BillName,
		B.ETypeId,	
		B_E.Fullname EFullname,
		B.dealbtypeid BtypeId,
		B_B1.FullName BTypeName,
		B.btypeid btypeid1,
		B.DTypeId,
		B_D.Fullname DFullname,
		B.STypeId,
		B_S.Fullname SFullname,
		B.KTypeId,
		K.Fullname KFullname,
		B.TotalQty,
		B.TotalMoney,
		B.Comment,
		CASE WHEN B.CID=0 THEN (SELECT TOP 1 CId FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END Cid,
		CASE 
			WHEN B.CID=0 THEN (SELECT TOP 1 UserCode FROM Ac_Currency WHERE Sysrow=1)
			ELSE C.UserCode
		END  UserCode,
		CASE 
			WHEN B.CID=0 THEN (SELECT TOP 1 FullName FROM Ac_Currency WHERE Sysrow=1)
			ELSE C.FullName
		END FullName,
		B.rate,
		C.Sysrow,
		CASE 
			WHEN B.ShelveRefState=1 THEN ''已引用未完成'' 
			WHEN B.ShelveRefState=2 THEN ''已完成'' 
			ELSE ''未引用'' 
		END ShelveRefState,
		B.Explain			
FROM (
		SELECT	BillNumberId,
				BillDate,
				BillCode,
				BillType,
				RedWord,
				IsIni,
				IfCheck,
				ETypeId,
				dealbtypeid,
				STypeId,
				KTypeId,
				TotalQty,
				TotalInMoney,
				Comment,
				Cid,
				rate,
				ShelveRefState,
				Explain,
				IfYearBill,
				DTypeId,
				BTypeId,
				TotalMoney
		FROM	BillIndex 
		WHERE	BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
				AND BillType IN ('+@BillType+')
				AND RedWord = 0
		UNION ALL
		SELECT	PA.BillNumberId,
				BillDate,
				BillCode,
				BillType,
				RedWord,
				IsIni,
				IfCheck,
				ApplyETypeId,
				'''' AS dealbtypeid,
				STypeId,
				KTypeId,
				Qty,
				0 AS TotalInMoney,
				Comment,
				Cid,
				1 AS rate,
				ISNULL(DS.ShelveRefState,0) AS ShelveRefState,
				Explain,
				0 AS IfYearBill,
				DTypeId,
				'''' AS BTypeId,
				0 AS TotalMoney
		FROM	PosAllotApplyBillIndex PA
		LEFT	JOIN #DeliveryState DS ON PA.BillNumberId = DS.BillNumberId
		WHERE	BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
				AND BillType IN ('+@BillType+')
				AND RedWord = 0
)B
INNER JOIN #DetailBill D ON D.BillNumberId=B.BillNumberId AND D.BillType=B.BillType
INNER JOIN BillName BN ON BN.Billtype=B.BillType AND B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' AND B.IsIni!=1 AND B.RedWord=0
INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid
INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId 
INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid
INNER JOIN #DealBtype B_B1 ON B_B1.TypeID=B.DealBTypeID
INNER JOIN #Btype B_B ON B_B.TypeID=B.BTypeID
LEFT JOIN Ac_Currency C ON C.CId=B.CID
LEFT JOIN Stock K ON B.KTypeID=K.TypeId'+CHAR(13)

--144受托代销收货单 142	委托代销退货单 
IF CHARINDEX('144',@BillType)>0 OR CHARINDEX('142',@BillType)>0
	SET @SQL+='LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=4'+CHAR(13)
ELSE
	SET @SQL+='LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2'+CHAR(13)

SET @SQL+='
WHERE
	((B.IsIni=0 AND B.ifYearBill=0 AND B.ShelveRefState<>2  AND  B.ifcheck=''t'') 
		OR (B.IsIni=1 AND B.ifYearBill=1 AND B.ShelveRefState<>2  AND  B.ifcheck=''t'') 
		OR (B.IsIni=1 AND B.ifYearBill=0 AND B.ShelveRefState<>2)
	)'+CHAR(13)
	
--摘要
IF(ISNULL(@Comment,'')<>'')
	SET @SQL+=' AND B.Comment LIKE ''%'+@Comment+'%'''+CHAR(13)
	
--说明
IF(ISNULL(@Explain,'')<>'')
	SET @SQL+=' AND B.explain LIKE ''%'+@Explain+'%'''+CHAR(13)
	
--出库单状态				
IF @CiteState!=9
	SET @SQL+='	AND B.ShelveRefState='+@CiteState +CHAR(13)
	
--排序
SET @SQL+='ORDER BY B.BillDate,B.BillCode DESC'+CHAR(13)

--==========================================业务逻辑处理【END】==========================================



--==========================================执行结果并删除临时表【BEGIN】==========================================

--PRINT @SQL
EXEC(@SQL)		

	
DROP TABLE #DeliveryState,#Stype,#BillName,#Btype,#DealBtype,#DetailBill,#Dtype,#Etype,#Ptype


--==========================================执行结果并删除临时表【END】==========================================
							


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportBuyBillToBillMxNew]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Qp_ImportBuyBillToBillMxNew
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：导入销售单据明细
	EXEC Qp_ImportDataToBillMx '00001','0','301',''
*/
CREATE PROCEDURE Qp_ImportBuyBillToBillMxNew
(
	@OperatorId		VARCHAR(100),
	@IsDraft		VARCHAR(100),
	@BillType		VARCHAR(500),
	@nBillIds		VARCHAR(MAX)='',
	@DealBtypeId    VARCHAR(50)='',
	@KTypeId        VARCHAR(50)='',
	@IsService      VARCHAR(50)='',
	@IsIni			int=0,			   --1为期初单据，0为非期初单据
	@Sale           VARCHAR(50)='',
	@STypeId        VARCHAR(50)='',
	@BillCodes		VARCHAR(MAX)='' --单据编号
	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------权限检查---------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------权限检查------------------------------------------------

--==========================================基础资料【BEGIN】==========================================
DECLARE @SQL VARCHAR(MAX)=''
CREATE TABLE #Nullbilltable
(
	Serial1		VARCHAR(50),
	Serial		VARCHAR(50),
	BillNumberId		VARCHAR(50)	,
	ID		VARCHAR(50),
	Billtype	VARCHAR(50),
	BillCode	VARCHAR(50),
			BillName		VARCHAR(50),
			PTypeId		VARCHAR(50),
			UserCode		VARCHAR(50),
			FullName		VARCHAR(50),
			GoodsNumber		VARCHAR(50),
			ItemName		VARCHAR(50),
			Unit		VARCHAR(50),
			Qty		VARCHAR(50),
			CQty		VARCHAR(50),
			UQty		VARCHAR(50),
			CarGoFullName	VARCHAR(50)
)
--商品信息
CREATE TABLE #PType
(
	TypeId			VARCHAR(50),
	UserCode		VARCHAR(200),
	FullName		VARCHAR(200)

) 
CREATE CLUSTERED INDEX #PType_P_K ON #PType(TypeId)
DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,'','')
SET @SQL='
	INSERT INTO #PType(
		TypeId,
		UserCode,
		FullName
	)
	SELECT 
		P.TypeId,
		P.UserCode,
		P.FullName
	'+@LinkStr+'
	WHERE 
		P.sonnum=0
		AND P.Deleted=0
		AND P.isservice=0'
EXEC(@SQL)
	
--主表选中的单据
CREATE TABLE #Bill
(
	BillNumberId NUMERIC(18,0),
	BillType	INT,
	BillCode	VARCHAR(200)
)
CREATE CLUSTERED INDEX #Bill_P_K ON #Bill(BillNumberId)
SET @SQL='
INSERT INTO #Bill(BillNumberId,BillType,BillCode)
SELECT	DISTINCT B.BillNumberId,
		B.BillType,
		B.BillCode
FROM f_split('''+@nBillIds+''','','') F 
INNER JOIN PosAllotApplyBillIndex B ON B.BillNumberId=F.a AND B.StypeID='''+@STypeId+'''
INNER JOIN f_split('''+@BillType+''','','') BT ON B.BillType = BT.a
INNER JOIN f_split('''+@BillCodes+''','','') BC ON B.BillCode = BC.a
UNION ALL
SELECT	DISTINCT B.BillNumberId,
		B.BillType,
		B.BillCode
FROM f_split('''+@nBillIds+''','','') F 
INNER JOIN BillIndex B ON B.BillNumberId=F.a AND B.StypeID='''+@STypeId+'''
INNER JOIN f_split('''+@BillType+''','','') BT ON B.BillType = BT.a
INNER JOIN f_split('''+@BillCodes+''','','') BC ON B.BillCode = BC.a
WHERE
	(
		(B.IsIni=0 AND B.ifYearBill=0  AND  B.ifcheck=''t'') 
		OR (B.IsIni=1 AND B.ifYearBill=1  AND  B.ifcheck=''t'')  
		OR (B.IsIni=1 AND B.ifYearBill=0 )
	)'
	
IF @IsDraft = 0 
	SET @SQL+='	AND B.IfCheck=''t'' AND B.RedWord=0'+CHAR(13)
ELSE IF @IsDraft =1
	SET @SQL+='	AND B.IfCheck=''f'' AND B.Draft=1'+CHAR(13)
	
IF(@IsIni=1)
	SET @SQL+='AND B.IsIni=1'
	
EXEC(@SQL)


DECLARE 
	@IniRow			INT=1,
	@MaxRow			INT=0,
	@NowBillType	INT,--当前billtype
	@NowBTypeName	VARCHAR(200),--当前billtype
	@Details		VARCHAR(200)--明细表表名


	
--当前当需要查询的单据类型
CREATE TABLE #BillType(NId INT IDENTITY(1,1),BillType INT)

INSERT INTO #BillType(BillType)
SELECT BillType FROM #Bill GROUP BY BillType
SELECT @MaxRow=@@ROWCOUNT


--==========================================基础资料【END】==========================================



--==========================================业务逻辑处理【BEGIN】==========================================
SET @SQL=''
WHILE(@IniRow<=@MaxRow)
BEGIN
	IF(LEN(@SQL)>0) SET @SQL+='UNION ALL'+CHAR(13)
	
	SELECT @Details=detailTable,@NowBillType=B.Billtype,@NowBTypeName=B.BillName FROM BillName B INNER JOIN #BillType T ON T.NId=@IniRow AND T.BillType=B.Billtype
	
	SET @SQL+='
	SELECT
		CASE DATALENGTH(ISNULL(M.Serial,''''))
			WHEN 0
				THEN ''''
			ELSE
				(SELECT TOP 1 a FROM dbo.f_splitAN(Serial,''я'') WHERE ISNULL(a,'''')<>'''')+''...'' 
		END AS Serial1,
		(''я''+(SELECT DISTINCT stuff((select ''я'' + a from 
			(
				SELECT a FROM dbo.f_split(M.Serial,''я'') 
				WHERE a NOT IN (
				SELECT ISNULL(a,'''') FROM dbo.f_split(
				(
					select [Serial] = stuff((
						select ''я'' + cast([Serial] as varchar(4000)) from pickbill t 
						inner join onShelvespickIndex o on t.billnumberid=o.billnumberid and o.ifcheck=''t'' and o.redword=0
						where  t.GoodsBillID=m.id AND m.billnumberid=t.GoodsBillNumberID AND t.GoodsBillType=B.BillType for xml path('''')) , 1 , 1 , ''''
					)  
					from pickbill p INNER JOIN dbo.onShelvespickIndex i ON p.billNumberID = i.billNumberId 
					WHERE i.IfCheck=''t'' AND i.draft=0 AND i.RedWord=0 AND p.GoodsBillID=m.id AND m.billnumberid=p.GoodsBillNumberID AND p.GoodsBillType=B.BillType
					group by ptypeid ),''я'')
				)
			) b
			where a = a for xml path('''')),1,1,'''')
			FROM (SELECT a FROM dbo.f_split(M.Serial,''я'') 
			WHERE a NOT IN (
			SELECT ISNULL(a,'''') FROM dbo.f_split(
			(
				select [Serial] = stuff(
				(
					select ''я'' + cast([Serial] as varchar(4000)) from pickbill t 
					inner join onShelvespickIndex o on t.billnumberid=o.billnumberid and o.ifcheck=''t'' and o.redword=0
					where  t.GoodsBillID=m.id AND m.billnumberid=t.GoodsBillNumberID AND t.GoodsBillType=B.BillType for xml path('''')) , 1 , 1 , ''''
				)  
				from pickbill p INNER JOIN dbo.onShelvespickIndex i ON p.billNumberID = i.billNumberId 
				WHERE i.IfCheck=''t'' AND i.draft=0 AND i.RedWord=0 AND p.GoodsBillID=m.id AND m.billnumberid=p.GoodsBillNumberID AND p.GoodsBillType=B.BillType
				group by ptypeid ),''я''))
			) c
		)+''я'') AS Serial,
		B.BillNumberId,
		M.ID,
		B.Billtype,
		B.BillCode,
		'''+@NowBTypeName+''' BillName,
		M.PTypeId,
		P.UserCode,
		P.FullName,
		M.GoodsNumber,
		CASE WHEN M.IsCombined=0 THEN (SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
			 ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) 
		END ItemName,
		U.FullName AS Unit,
		M.Qty,
		ISNULL(M.InflowQty,0) AS CQty,		
		M.Qty-ISNULL(M.InflowQty,0) AS UQty,'
				
SET @SQL += '		
		Ca.fullname CarGoFullName
	FROM	#Bill B
	INNER JOIN '+@Details+' M ON M.BillNumberId=B.BillNumberId AND B.BillType='+CAST(@NowBillType AS VARCHAR(5))+'
	INNER JOIN #PType P ON P.TypeId=M.PtypeId
	LEFT JOIN CargoType Ca ON Ca.CargoID='+
											CASE 
												WHEN @NowBillType IN(17,21,188) THEN 'M.InCargoID' 
												WHEN @NowBillType IN(327) THEN 'M.CargoIDOut' 
												WHEN @NowBillType IN(328,329) THEN 'M.InCargoID' 
												ELSE 'M.CargoID' 
											END+' 
	LEFT JOIN dbo.PType_Units U ON U.UnitsId='+CASE WHEN @NowBillType IN(16) THEN 'M.MUnitID' ELSE 'M.UnitID' END +CHAR(13)--生产拆装单 

SET @SQL+='	WHERE	M.Qty>ISNULL(M.InflowQty,0)'+CHAR(13)
    
	--请购单
	IF(@NowBillType=204)
		SET @SQL+='	AND M.state<=8'	
			
	--160	销售换货单
	--161	采购换货单
	--16	生产拆装单	
	IF @NowBillType IN(160,161,16)
		SET @SQL+='	AND M.InOrOut=''I'''
		
	--入库仓库
	IF (ISNULL(@Ktypeid,'')<>'' AND @NowBillType<>215) 
		BEGIN
			IF @NowBillType IN (327,328,329)
			BEGIN
				IF @NowBillType IN (327)
					SET @SQL+='	AND M.KTypeIDOut='''+@KTypeId+''''+CHAR(13)
				ELSE
					SET @SQL+='	AND M.InKTypeID='''+@KTypeId+''''+CHAR(13)
			END
			ELSE
			BEGIN
				IF @NowBillType in(17,21,188)
					SET @SQL+='	AND M.KTypeID2='''+@KTypeId+''''+CHAR(13)
				ELSE
					SET @SQL+='	AND M.KTypeID='''+@KTypeId+''''+CHAR(13)
			END
		END
	SET @IniRow+=1
END
if(@MaxRow=0)
begin
select * from #Nullbilltable
end
--==========================================业务逻辑处理【END】==========================================



--==========================================执行结果并删除临时表【BEGIN】==========================================
IF(LEN(@SQL)>0)
	BEGIN
		SET @SQL='
			SELECT * FROM (
			'+@SQL+'
			) F
			ORDER BY 
				BillNumberId,
				ID
		'
	END
EXEC(@SQL)
	--PRINT (@SQL)

--删除临时表
DROP TABLE #Bill,#BillType,#PType,#Nullbilltable

--==========================================执行结果并删除临时表【END】==========================================
				
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportDataToBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_ImportDataToBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-13
	描述：导入单据
*/

CREATE PROCEDURE Qp_ImportDataToBill
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@IsDraft		VARCHAR(100),
	@BillType		VARCHAR(100),
	@BillCode		VARCHAR(400),
	@STypeId		VARCHAR(100)='',
	@DealBtypeId    VARCHAR(100)='',
	@Etypeid        VARCHAR(100)='',
	@Dtypeid        VARCHAR(100)='',
	@NotuseComplet	TINYINT=0,
	@PType			varchar(256) = '',
	@Explain		varchar(1000) = '',
	@Comment		varchar(1000) = '',
	@checkEtypeid	VARCHAR(max)='',
	@cid            VARCHAR(50) = '',
	@nBillIds		VARCHAR(8000)='',
	@BtypeId		VARCHAR(100)=''	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
--INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)
--IF @MKTypeId = '00000'
--	INSERT INTO #GetManKTypeId(TypeId)VALUES('00000')


--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_GetManBTypeId ON #GetManBTypeId(TypeId) 

INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)
INSERT INTO #GetManBTypeId(TypeId)VALUES('')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_GetManSTypeId ON #GetManSTypeId(TypeId) 
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_GetManETypeId ON #GetManETypeId(TypeId) 
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)
INSERT INTO #GetManETypeId(TypeId)VALUES('')

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_GetManDTypeId ON #GetManDTypeId(TypeId) 
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Dtypeid,9,@OperatorID)	
INSERT INTO #GetManDTypeId(TypeId)VALUES('')

CREATE TABLE #GetDetailTableBillNumberId(BillNumberId INT)
CREATE CLUSTERED INDEX CIX_GetDetailTableBillNumberId ON #GetDetailTableBillNumberId(BillNumberId) 

DECLARE @BillIndexTable VARCHAR(100),
		@SQL			VARCHAR(8000),
		@DetailBill		VARCHAR(100)	--记录明细表名
		
IF @BillType IN (301,300)
	SET @BillIndexTable = 'OrderIndex'
ELSE
	SET @BillIndexTable = 'BillIndex'	
IF 	@BillType IN (408)
	SET @BillIndexTable = 'DiyIndex'
IF 	@BillType IN (204)
	SET @BillIndexTable = 'RequestIndex'

SELECT @DetailBill=detailtable FROM BILLNAME WHERE BillType=@BillType
IF ISNULL(@DetailBill,'')<>''
BEGIN
	IF ISNULL(@PType,'')<>''
	BEGIN
	    exec('INSERT INTO #GetDetailTableBillNumberId
		SELECT DISTINCT T.BillNumberId FROM '+@DetailBill+' T 
		INNER JOIN F_GetManPTypeAll('''+@OperatorId+''') P ON T.PtypeId=P.typeid where T.PtypeId='+@PType+'')
	END
	ELSE
	BEGIN
	     exec('INSERT INTO #GetDetailTableBillNumberId
		SELECT DISTINCT T.BillNumberId FROM '+@DetailBill+' T 
		INNER JOIN F_GetManPTypeAll('''+@OperatorId+''') P ON T.PtypeId=P.typeid')
	END
END
IF  @NotuseComplet=1 --已经引用完成的报价/询价单不展示
BEGIN
	IF @BillType =184
	BEGIN
		DELETE FROM #GetDetailTableBillNumberId WHERE BillNumberId NOT IN (SELECT DISTINCT BillNumberID FROM dbo.QuotePriceBill WHERE ISNULL(qty,0)>ISNULL(useqty,0))
	END
	
	IF @BillType =185
	BEGIN
		DELETE FROM #GetDetailTableBillNumberId WHERE BillNumberId NOT IN (SELECT DISTINCT BillNumberID FROM dbo.AskPriceBill WHERE ISNULL(qty,0)>ISNULL(useqty,0))
	END
END

IF @BillType IN (301,300)
SET @SQL = 'SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,	
					B.dealbtypeid AS btypeid,
					B.btypeid AS btypeid1,
					B.DTypeId,
					B.STypeId,
					B.TotalQty,
					B.TotalMoney,
					FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  as cid,
					CASE WHEN B.CID=0 THEN
					(select usercode from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select usercode from Ac_Currency where cid=B.CID) END as usercode,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END as fullname,		
					B.rate,		
					(SELECT Sysrow FROM Ac_Currency WHERE CID=B.cid) as sysrow,	
					B.Explain
			FROM	'+@BillIndexTable+' B					
					INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
					INNER JOIN #GetManETypeId ME ON ME.TypeId = B.ETypeId
					INNER JOIN #GetManDTypeId D ON B.DTypeId = D.TypeId 
					INNER JOIN Employee E ON B.Checke=E.TypeId '
ELSE
BEGIN
	SET @SQL = 'SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.ETypeId,	
						B.dealbtypeid AS btypeid,
						B.btypeid AS btypeid1,
						B.DTypeId,
						B.STypeId,
						B.TotalQty,
						B.TotalMoney,
						FullName AS CheckeName,
						B.Comment,
						CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  as cid,
						CASE WHEN B.CID=0 THEN
						(select usercode from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
						ELSE
						(select usercode from Ac_Currency where cid=B.CID) END as usercode,
						CASE WHEN B.CID=0 THEN
						(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
						ELSE
						(select fullname from Ac_Currency where cid=B.CID) END as fullname,	'
	IF LOWER(@BillIndexTable) <> 'diyindex'				
	BEGIN
		SET @SQL = @SQL+'B.rate,
		(SELECT Sysrow FROM Ac_Currency WHERE CID=B.cid) as sysrow,'
	END
	IF @BillType = 11
	BEGIN
		SET @SQL = @SQL+'B.CostSale,'
	END
	SET @SQL = @SQL + 'B.Explain
						FROM '+@BillIndexTable+' B					
						INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
						INNER JOIN #GetManETypeId ME ON ME.TypeId = B.ETypeId
						INNER JOIN #GetManDTypeId D ON B.DTypeId = D.TypeId 
						INNER JOIN Employee E ON B.Checke=E.TypeId '
END
IF 	@BillType IN (408)
SET @SQL = 'SELECT	B.BillNumberId,
					B.BillDate,
					B.EtypeID,
					B.ToTalQty,
					B.TotalMoney,
					B.Comment as explain,
					B.IndexOrderId,
					B.IndexOrderId as BillCode,
					B.Counts,
					B.Checke,
					'''' as stypeid_fullname,
					'''' as btypeid_fullname,
					'''' as dtypeid_fullname,
					'''' as Comment,
					'''' as fullname,
					FullName AS CheckeName
			FROM	'+@BillIndexTable+' B					
					INNER JOIN #GetManETypeId ME ON ME.TypeId = B.ETypeId
					INNER JOIN Employee E ON B.Checke=E.TypeId '
IF(@BillType IN (204))
SET @SQL = 'SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.DTypeId,
					B.STypeId,
					'''' as btypeid,
					'''' as btypeid_fullname,
					B.TotalQty,
					B.TotalMoney,
					FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  as cid,
					CASE WHEN B.CID=0 THEN
					(select usercode from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select usercode from Ac_Currency where cid=B.CID) END as usercode,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END as fullname,				
					B.rate,	
					(SELECT Sysrow FROM Ac_Currency WHERE CID=B.cid) as sysrow,
					B.Explain
			FROM	'+@BillIndexTable+' B					
					INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
					INNER JOIN #GetManETypeId ME ON ME.TypeId = B.ETypeId
					INNER JOIN #GetManDTypeId D ON B.DTypeId = D.TypeId 
					INNER JOIN Employee E ON B.Checke=E.TypeId '


--同价调拨单、变价调拨单、成本调价单没有往来单位
IF @BillType NOT IN (17,21,57,408,204)
	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId MB ON MB.TypeId = ISNULL(B.dealbtypeid,'''') '
IF @BillType IN (204)
	SET @SQL = @SQL + '
			WHERE	B.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND B.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
					AND B.BillType = '+CHAR(39)+@BillType+CHAR(39)+CASE WHEN ISNULL(@BillCode,'')<>'' THEN 
					' 
					AND B.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
					ELSE 
					''
					END 
ELSE IF @BillType NOT IN (408)
SET @SQL = @SQL + '
			WHERE	B.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND B.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
					AND B.BillType = '+CHAR(39)+@BillType+CHAR(39)+
					CASE WHEN ISNULL(@BillCode,'')<>'' THEN 
					'
					AND B.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
					ELSE 
					''
					END 
					+
					CASE WHEN ISNULL(@DealBtypeId,'')<>'' THEN 
					'
					AND B.dealbtypeid LIKE'+CHAR(39)+ISNULL(@DealBtypeId,'')+'%'+CHAR(39)
					ELSE
					''
					END
					+
					CASE WHEN ISNULL(@Etypeid,'')<>'' THEN
					'
					AND B.ETypeId = '+@Etypeid+''
					ELSE
					''
					END
					+
					CASE WHEN ISNULL(@cid,'')<>'' THEN
					'
					AND B.cid='+@cid+''
					ELSE
					''
					END
					+
					CASE WHEN ISNULL(@checkEtypeid,'')<>'' THEN
					'
					AND b.checke='+@checkEtypeid+''
					ELSE
					''
					END
					+
					CASE WHEN ISNULL(@Explain,'')<>'' THEN
					'
					AND B.Explain like ''%' + @Explain + '%'''
					ELSE
					''
					END
					+
					CASE WHEN ISNULL(@Comment,'')<>'' THEN
					'
					AND B.Comment LIKE ''%' + @Comment + '%'''
					ELSE
					''
					END		
					
ELSE
SET @SQL = @SQL + '
			WHERE	B.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND B.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+
					CASE WHEN ISNULL(@BillCode,'')<>'' THEN 
					'
					AND B.IndexOrderId LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
					ELSE 
					''
					END 		
			
IF @BillType NOT IN (17,21,408,204,187,188) AND ISNULL(@BtypeId,'')<>''
	SET @SQL = @SQL	+ ' AND B.dealbtypeid = '++CHAR(39)+@BtypeId+CHAR(39)			
			
					
--报价单审核通过的才可以调出
CREATE TABLE #AuditingBill
(
	BillNumberId		NUMERIC(18,0),
	BillType			INT,
	PassFlag			INT,
	Reason				VARCHAR(MAX),
	VALUE				VARCHAR(1000),
	AuditingStep		VARCHAR(100)
)
CREATE CLUSTERED INDEX CIX_AuditingBill ON #AuditingBill(BillNumberId) 


CREATE TABLE #BillIndex
(
	nId			INT IDENTITY(1,1),
	nBillId		NUMERIC(18,0)
)
CREATE CLUSTERED INDEX CIX_BillIndex1 ON #BillIndex(nBillId) 


CREATE TABLE #AuditingPassBill
(
	BillNumberId		NUMERIC(18,0)
)
CREATE CLUSTERED INDEX CIX_AuditingPassBill ON #AuditingPassBill(BillNumberId) 
		
IF @BillType = 184 OR @BillType=185
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @BillType and stoped=0)
	BEGIN
		DECLARE @i			NUMERIC(18,0),
				@nCount		NUMERIC(18,0),
				@tmpBillId	NUMERIC(18,0)	
				
		SET @i = 1				
				
		--先写入审核通过后的单据
		INSERT INTO #AuditingPassBill(BillNumberId) 
		SELECT	a.BillNumberID 
	    FROM	dbo.AuditingBill a
	    INNER JOIN  dbo.AuditingFlowSet c ON a.AuditingID=c.AuditingID 
					AND a.IfAudit = '1'
					AND c.billtype = @BillType
					AND a.BillIndexType = 2
					
		--判断剩下的单据（有可能满足审核未提交、有可能不满足审核条件）
		INSERT INTO #BillIndex(nBillId) 
		SELECT	BillNumberId 
		FROM	BillIndex 
		WHERE	BillType = @BillType 
				AND BillNumberId NOT IN (SELECT BillNumberId FROM #AuditingPassBill)
		
		SET @nCount = @@ROWCOUNT
		
		WHILE @i<=@nCount
		BEGIN
			SELECT @tmpBillId = nBillId FROM #BillIndex WHERE nId = @i
						
			INSERT INTO #AuditingBill 
			(
				BillNumberId,
				BillType,
				PassFlag,
				Reason,
				VALUE,
				AuditingStep
			)
			EXEC GP_BillAudtingCheckReason @tmpBillId,'00001',2,'0',0,0,0
			
			IF NOT EXISTS(SELECT TOP 1 1 FROM #AuditingBill WHERE BillNumberId = @tmpBillId AND PassFlag = 0)
			BEGIN
				INSERT INTO #AuditingPassBill(BillNumberId)VALUES(@tmpBillId)
			END
		
			SET @i = @i + 1
		END		
	
		SET @SQL = @SQL + ' AND B.BillNumberId IN (SELECT BillNumberId FROM #AuditingPassBill) '		
	END				   					   
END

					--救援单配件明细
IF @BillType =196
    BEGIN
        SET @SQL=@SQL+'AND EXISTS (SELECT 1 FROM Qp_SuccorBill_PType SP WHERE SP.BillnumberID=B.BillnumberID ) '
    END
--快修单配件明细
IF @BillType =178
   BEGIN
        SET @SQL=@SQL+'AND EXISTS (SELECT 1 FROM QP_QuickRepairBill_PType QP WHERE QP.BillnumberID=B.BillnumberID ) '
   END

IF @BillType NOT IN (408,204)
BEGIN	

IF @BillType NOT IN (301,300)					
	BEGIN
		IF @IsDraft = 0 
			SET @SQL = @SQL + ' AND (B.IfYearBill = 0 AND B.IfCheck = ''t'' AND B.RedWord = 0 OR  ( B.IsIni=1  AND B.BillType = '+CHAR(39)+@BillType+CHAR(39)+' ))'
		ELSE IF @IsDraft = 1
			SET @SQL = @SQL + ' AND B.IfYearBill = 0 AND B.IfCheck = ''f'' AND B.Draft = 1'
		ELSE 
			SET @SQL = @SQL + ' AND B.IfYearBill = 0 AND B.RedWord = 0 AND 1 = 1'
	END
ELSE IF @BillType IN (301,300)
	BEGIN
		IF @IsDraft = 0
			SET @SQL = @SQL + ' AND 1 = 0  OR  ( B.IsIni=1  AND B.BillType = '+CHAR(39)+@BillType+CHAR(39)+' ) '
		ELSE
			SET @SQL = @SQL + ' AND B.BillOver = 0 '
	END
ELSE
	BEGIN
		SET @SQL = @SQL + ' AND B.IfYearBill = 0 AND B.RedWord = 0 AND 1 = 1 OR  ( B.IsIni=1  AND B.BillType = '+CHAR(39)+@BillType+CHAR(39)+' ) '
	END
	
END

IF @BillType IN (204) AND @IsDraft <> 9
BEGIN
	SET @SQL=@SQL+'AND 1=0'
END
SET @SQL = @SQL +' AND B.billnumberid IN (SELECT * FROM #GetDetailTableBillNumberId)'

IF @BillType NOT IN (408)
SET @SQL = @SQL + '					
			ORDER BY B.BillDate DESC,B.BillCode DESC'
ELSE 
SET @SQL = @SQL + '					
			ORDER BY B.BillDate DESC,B.IndexOrderId DESC'

--PRINT(@SQL)
EXEC(@SQL)	

		
DROP TABLE #GetManKTypeId,#GetManBTypeId,#GetManSTypeId,#GetManETypeId,#GetManDTypeId,#GetDetailTableBillNumberId,#AuditingBill,#BillIndex,#AuditingPassBill
							


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportDataToBillMx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_ImportDataToBillMx]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-13
	描述：导入单据明细
	EXEC Qp_ImportDataToBillMx '00001','0','301',''
*/

/*
	修改：覃雨翔
	日期：2011-08-23
	描述：询价单，报价单查询账面库存
*/

/*
	修改：李灏龙
	日期：2012年2月10日9:35:38
	描述：增添查询字段，为订单保存所需字段，具体修改处注释：zs001
*/
CREATE PROCEDURE Qp_ImportDataToBillMx
(
	@OperatorId		VARCHAR(100),
	@IsDraft		VARCHAR(100),
	@BillType		VARCHAR(100),
	@nBillIds		VARCHAR(8000)='',
	@DealBtypeId    VARCHAR(50)='',
	@Ktypeid        VARCHAR(50)='',
	@IsIni			int=0,			   --1为期初单据，0为非期初单据
	@showServicePtype		INT=1,--是否显示服务类商品：0，不显示；1，显示
	@requestdate	varchar(20)='',	--需求日期
	@btypeid		varchar(200)='',	--建议供货商
	@NotuseComplet	TINYINT=0	--已完成的不引入
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

DECLARE @BillIndexTable VARCHAR(100), 
		@MxTableName	VARCHAR(100),
		@SQL 			VARCHAR(8000)
		
CREATE TABLE #SplitBillNumberId
(
	BillNumberId		NUMERIC(18,0)
)	   
INSERT INTO #SplitBillNumberId(BillNumberId) SELECT A FROM dbo.f_split(@nBillIds,',') WHERE ISNULL(A,'')<>''

CREATE TABLE #BillIndex
(
	BillNumberId		NUMERIC(18,0),
	BillDate			VARCHAR(20),
	BillCode			VARCHAR(400),
	IsIni				bit,
	ifaudit				int
)		
CREATE CLUSTERED INDEX CIX_BillIndex ON #BillIndex(BillNumberId) 	   

CREATE TABLE #MxTable
(
	PTypeId			VARCHAR(100),
	Unit1			VARCHAR(100),
	Qty				 NUMERIC(24, 10) ,
	SalePrice		 NUMERIC(24, 10) ,
	SaleTotal		 NUMERIC(24, 10) ,
	Discount		 NUMERIC(24, 10) ,
	DiscountPrice	 NUMERIC(24, 10) ,
	DiscountTotal	 NUMERIC(24, 10) ,
	Tax				 NUMERIC(24, 10) ,
	TaxPrice		 NUMERIC(24, 10) ,
	TaxTotal		 NUMERIC(24, 10) ,	
	Comment			VARCHAR(400)
)
CREATE CLUSTERED INDEX CIX_MxTable ON #MxTable(PTypeId) 	   
		
-------------------------------------主表-------------------------------------
IF @BillType =204
	SET @BillIndexTable = 'requestindex'
ELSE IF @BillType IN (301,300)
	SET @BillIndexTable = 'OrderIndex'
ELSE
	SET @BillIndexTable = 'BillIndex'		

SET @SQL = 'INSERT INTO #BillIndex
			SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.IsIni,
					B.ifaudit
			FROM	'+@BillIndexTable+' B,
					#SplitBillNumberId S
			WHERE	B.BillNumberId = S.BillNumberId
					AND BillType = '+CHAR(39)+@BillType+CHAR(39)
					
IF @BillType NOT IN (301,300)					
	BEGIN
		IF @IsDraft = 0 
			SET @SQL = @SQL + ' AND B.IfCheck = ''t'' AND B.RedWord = 0 '
		ELSE IF @IsDraft = 1
			SET @SQL = @SQL + ' AND B.IfCheck = ''f'' AND B.Draft = 1 '
		ELSE
			SET @SQL = @SQL + ' AND 1 = 1 '
	END	
ELSE 
	BEGIN
		IF @IsDraft = 0
			SET @SQL = @SQL + ' AND 1 = 0 '
		ELSE
			SET @SQL = @SQL + ' AND B.BillOver = 0 '
	END
					
SET @SQL = @SQL + '					
			ORDER BY B.BillDate DESC,B.BillCode DESC '

--PRINT(@SQL)
EXEC(@SQL)

---------------------------------------明细表-------------------------------------
IF @BillType IN (300,301)
	SET @MxTableName = 'OrderBill'
ELSE IF @BillType = 34
	SET @MxTableName = 'BuyBill'
ELSE IF @BillType = 6
	SET @MxTableName = 'BuyBackBill'
ELSE IF @BillType IN (144,146,140,142)
	SET @MxTableName = 'CommissionBill'
ELSE IF @BillType = 305
	SET @MxTableName = 'RetailBill'
ELSE IF @BillType = 215
	SET @MxTableName = 'RetailBackBill'
ELSE IF @BillType = 11
	SET @MxTableName = 'SaleBill'
ELSE IF @BillType = 45
	SET @MxTableName = 'SaleBackBill'
ELSE IF @BillType = 17
	SET @MxTableName = 'MoveBill'
ELSE IF @BillType = 21
	SET @MxTableName = 'MoveBjBill'
ELSE IF @BillType = 57
	SET @MxTableName = 'AdPriceBill'
ELSE IF @BillType = 184
	SET @MxTableName = 'QuotePriceBill'
ELSE IF @BillType = 185
	SET @MxTableName = 'AskPriceBill'
ELSE IF @BillType IN (187,188)
	SET @MxTableName = 'STypeMoveBill'
ELSE IF @BillType = 178
	SET @MxTableName = 'QP_QuickRepairBill_PType'
ELSE IF @BillType = 191
	SET @MxTableName = 'Qp_PickingBill'
ELSE IF @BillType = 196
	SET @MxTableName = 'Qp_SuccorBill_PType'
ELSE IF @BillType = 197
	SET @MxTableName = 'Qp_PickingBackBill'
ELSE IF @BillType = 204
	SET @MxTableName = 'Requestbill'			

DECLARE @ReferPriceSql varchar(2000)
SET @ReferPriceSql = ' CASE WHEN stype.pricetype=1 THEN 
						CASE WHEN (SELECT ISNULL(REFERPRICE,0) FROM PTYPE_STYPEPRICE WHERE STYPEID=M.STYPEID AND PTYPEID=M.PTYPEID)=0
						THEN (SELECT referprice FROM PType_Price WHERE PTypeID = m.PTypeID) 
						ELSE
						(SELECT ISNULL(REFERPRICE,0) FROM PTYPE_STYPEPRICE WHERE STYPEID=M.STYPEID AND PTYPEID=M.PTYPEID) 
						END
				    ELSE
				    (SELECT referprice FROM PType_Price WHERE PTypeID = m.PTypeID) 
				    END AS referprice,'
DECLARE @Ser varchar(max)
IF @BillType NOT IN (300,301,57,184,185,178,191,196,197,204)
BEGIN
	SET @SQL = 'SELECT	CASE DATALENGTH(M.Serial)
							WHEN 0
								THEN ''''
							ELSE
								SUBSTRING(M.Serial,(charindex(''я'',M.Serial)+2),charindex(''я'',M.Serial,charindex(''я'',M.Serial)+1)-1)+''...'' 
						END AS Serial1,
						M.Serial AS Serial,
						M.PTypeId,
						P.*,
						P.Unit1 AS unitone,
						P.Unit2 As unittwo,
						M.Qty,
						(dbo.F_GetAllEntrycode(M.Ptypeid,p.SaleUnitId,2)) AS munitcode,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname1,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname2,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname3,
						(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate1,
						(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate2,
						(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate3,
						PC.UserCode AS CustomerCode,
						(select isservice from ptype where typeid = m.PTypeID) as isservice,
						(select referprice from PType_Price where PTypeID = m.PTypeID) as referprice,
						 '
END
ELSE
BEGIN 
	SET @SQL = 'SELECT	NULL AS Serial,
					M.PTypeId,
					P.*,
					P.Unit1 AS unitone,
					P.Unit2 As unittwo,
				   (dbo.F_GetAllEntrycode(M.Ptypeid,p.SaleUnitId,2)) AS munitcode,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname1,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname2,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname3,
					(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate1,
					(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate2,
					(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate3,
					PC.UserCode AS CustomerCode,
					(select isservice from ptype where typeid = m.PTypeID) as isservice,
				    (select pr.referprice from PType_Price pr where pr.PTypeID = m.PTypeID and pr.UnitId=M.UnitID) as referprice,
					 '
	IF @BillType = 204
	BEGIN
		SET @SQL = @SQL +' ISNULL(M.Qty,0)-ISNULL(M.RequestQty,0) as Qty,'
	END
	ELSE
	BEGIN
		SET @SQL = @SQL +' M.Qty,'
	END

END

					 
IF @BillType IN (17,21)
SET @SQL = @SQL + ' M.MPrice as msaleprice,
                    M.price as nsaleprice,
                    M.Price as curmdiscountprice,
                    M.total as ntotal,
                    M.total as nsaletotal,
                    '
IF @BillType IN (57)
SET @SQL = @SQL + ' M.UnitRate,
					M.beforeprice,
                    1 as munitrate,--兼容单据明细导入（含有大单位的单据）
                    '


SET @SQL = @SQL + ' pt.unitstype, '						
IF @BillType IN (305,300,11,45,140,142,301,34,6,144,146,17,21,187,188,57,215)
SET @SQL = @SQL + ' M.goodsnumber,
                     
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=M.ItemId,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					iscombined=M.IsCombined,
                  '
IF @BillType IN (184,185)
BEGIN
	SET @SQL = @SQL +' notuseqty= CASE WHEN (ISNULL(M.Qty,0)-ISNULL(M.useqty,0))<0 THEN 0 ELSE (ISNULL(M.Qty,0)-ISNULL(M.useqty,0)) END,'
	
END
IF @BillType IN (184,185)
SET @SQL = @SQL + '
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=M.ItemId,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					iscombined=M.IsCombined,
				    '''' as goodsnumber,
                  '
		
IF 	@BillType NOT IN (57)
SET @SQL = @SQL + ' M.munitrate,'


IF @BillType NOT IN (178,191,196,197,57)
SET @SQL = @SQL + ' CASE WHEN ISNULL(M.NUnitID,0) = 0 THEN NULL
					ELSE M.unitrate END AS unitrate,										
					pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=M.ItemId,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					iscombined=M.IsCombined,
					CAST(pt.ifusegoodsnum AS INT) AS ifusegoodsnum,
					 '
--ELSE
--SET @SQL = @SQL + ' P.Unitrate1 As Unitrate,'
IF @BillType IN (140)
SET @SQL = @SQL + ' M.nsaleprice as beforeprice,
					M.nsaletotal as beforetotal,					
					'



IF @BillType IN (300,301,34,6,144,146,140,142,305,11,45,184,185,204,215)
BEGIN
	SET @SQL = @SQL + ' CASE WHEN ISNULL(M.NUnitID,0) = 0 THEN NULL'
	
	IF @BillType = 204
		SET @SQL = @SQL + ' ELSE (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0))/M.unitrate END AS nqty,
							CASE WHEN ISNULL(M.RequestQty,0)=0 THEN ntaxmoney ELSE (M.ntaxprice - M.ndiscountprice )* (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0)) END AS ntaxmoney,
							CASE WHEN ISNULL(M.RequestQty,0)=0 THEN ntaxtotal ELSE M.ntaxprice * (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0)) END AS ntaxtotal,
							CASE WHEN ISNULL(M.RequestQty,0)=0 THEN taxmoney ELSE (M.taxprice - M.discountprice) * (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0)) END AS taxmoney,
							CASE WHEN ISNULL(M.RequestQty,0)=0 THEN nsaletotal ELSE M.nsaleprice * (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0)) END AS nsaletotal,
							CASE WHEN ISNULL(M.RequestQty,0)=0 THEN ntotal ELSE M.ndiscountprice * (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0)) END AS ntotal,
							(dbo.F_GetAllEntrycode(p.TypeId,m.MUnitID,2)) AS salemunitcode,
							(dbo.F_GetAllEntrycode(p.TypeId,m.MUnitID,2)) AS buymunitcode,
							(dbo.F_GetAllEntrycode(p.TypeId,m.MUnitID,2)) AS stockmunitcode,'
	ELSE
		SET @SQL = @SQL + ' ELSE M.nqty END AS nqty,
							M.ntaxmoney,
							M.ntaxtotal,
							M.taxmoney,
							M.nsaletotal,
							M.ntotal,'
					
	SET @SQL = @SQL + ' M.curmsaleprice,
						M.nsaleprice,
						M.curmdiscountprice,
						M.curmtaxprice,
						M.MUnitID, 							
						M.NUnitID,
						M.UnitID,
						W.fullname AS unit,
						U.FullName AS munit,
						V.FullName AS nunit,						      
						M.NTaxPrice,
						M.NDiscountPrice,
						M.MSalePrice,
						M.MDiscountPrice,
						M.MTaxPrice,
						'''' as serial1,					
						'	
END
IF @BillType IN (300,301,34,6,144,146,140,142,305,11,45,184,185,215)
BEGIN
	SET @SQL = @SQL + ' M.mqty,'
END
IF @BillType = 204
BEGIN
	SET @SQL = @SQL + 'cast(ISNULL(M.mqty,0) - (ISNULL(M.RequestQty,0) / unit.rate) as  NUMERIC(24, 10) ) as mqty,'
END					
IF @BillType IN (184,185)
--zs001 添加ID与BillNumberID，这样在保存单据时能在明细中添入AskBillID和AskBillNumberID
	SET @SQL = @SQL + ' M.ID AS AskBillID,
	                    '''' as serial1,
						M.BillNumberID AS AskBillNumberID,
						M.Price,
						M.Price as beforeprice,
						M.SaleTotal AS Total,
						M.Discount,
						M.DiscountPrice,
						M.Total AS DiscountTotal,
						M.Tax,
						M.TaxPrice,
						M.TaxTotal AS TaxTotal,
						M.Comment AS MxComment,		
									
						
						ISNULL(G.Qty,0) AS AccountQty,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace'
						
ELSE IF @BillType IN (300,301)
	SET @SQL = @SQL + '	M.Price,
						
						M.NSaleTotal AS Total,
						
						M.Discount,
						M.DiscountPrice,
						M.Total AS DiscountTotal,
						M.Tax,
						M.TaxPrice,
						M.TaxTotal AS TaxTotal,
						M.Comment AS MxComment,
					    M.Price,
						
						ISNULL(G.Qty,0) AS AccountQty,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace '

ELSE IF @BillType IN (34,6,144,146,140,142,305,11,45,215)
	SET @SQL = @SQL + ' M.SalePrice AS Price,
						M.SaleTotal AS Total,
						M.NSalePrice as beforeprice,
						M.NSaleTotal as beforetotal,
						M.Discount,
						M.DiscountPrice,
						M.Total AS DiscountTotal,
						M.Tax,
						M.TaxPrice,
						M.TaxTotal AS TaxTotal,
						M.Comment AS MxComment,
						
						'''' AS CargoSpace,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace '

ELSE IF @BillType IN (17,21,187,188,191,197,196)
	BEGIN
		SET @SQL = @SQL + ' M.Price,
		                    M.Price as beforeprice,
		                    M.Price as nsaleprice,
		                    M.MPrice as curmsaleprice, 
							M.Total AS Total,
							M.Total AS beforetotal,
							1 AS Discount,
							M.Price AS DiscountPrice,
							M.MPrice AS mdiscountprice,
                            M.Price AS ndiscountprice,
							M.Total AS DiscountTotal,
							0 AS Tax,
							0 as ntaxmoney,
							0 as taxmoney,
							M.Price AS TaxPrice,
							M.price as ntaxprice,
							M.MPrice AS curmtaxprice,
							M.Total AS TaxTotal,
							M.Total as ntaxtotal,
							M.Comment AS MxComment,
							M.MPrice AS curmdiscountprice,
							M.Total AS ntotal, 
							M.MQty,
							M.nqty,						
							M.NUnitID,
							M.UnitID,
							M.MUnitID,
							W.fullname AS unit,
							U.FullName AS munit,
							V.FullName AS nunit,
							
							 '
	IF @BillType IN (187,188)
			SET @SQL = @SQL + '
							M.Total AS nsaletotal,
							
							'
	
	
		IF @BillType IN (17,21,187,188)
			SET @SQL = @SQL + '
							'''' AS CargoSpace,
							'''' AS InCargoSpace,
							'''' AS OutCargoSpace '
	    ELSE IF @BillType IN (191,197,196)
			SET @SQL = @SQL + '
							M.CargoSpace,
							
							'''' AS InCargoSpace,
							'''' AS OutCargoSpace '			
		ELSE
			SET @SQL = @SQL + '
			               
							'''' AS CargoSpace,
							'''' AS InCargoSpace,
							'''' AS OutCargoSpace'
	END
ELSE IF @BillType = 178
	SET @SQL = @SQL + 'M.Price,
	                   M.Price as beforeprice,
					   M.Total,
					   M.Discount,
					   M.DiscountPrice,
					   M.DiscountTotal,
					   0 AS Tax,
					   M.DiscountPrice AS TaxPrice,
					   M.DiscountTotal AS TaxTotal,
					   M.Comment AS MxComment,
					   M.CargoSpace,
					  
					   '''' AS InCargoSpace,
					   '''' AS OutCargoSpace'
					   
ELSE IF @BillType = 204
	SET @SQL = @SQL + ' M.SalePrice AS Price,
						CASE WHEN ISNULL(M.RequestQty,0)=0 THEN SaleTotal ELSE M.SalePrice * (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0) ) END AS Total,
						M.Discount,
						M.DiscountPrice,
						CASE WHEN ISNULL(M.RequestQty,0)=0 THEN Total ELSE M.DiscountPrice * (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0) ) END AS DiscountTotal,
						M.Tax,
						M.TaxPrice,
						CASE WHEN ISNULL(M.RequestQty,0)=0 THEN TaxTotal ELSE M.TaxPrice * (ISNULL(M.qty,0) - ISNULL(M.RequestQty,0)) END AS TaxTotal,
						M.Comment AS MxComment,
						
						M.BillNumberId AS requestbillnumberid,
						M.ID AS requestbillid,
						'''' AS CargoSpace,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace,
						M.btypeid,M.requestdate,
						reqb.fullname as bfullname'
						
IF 	@BillType = 57
SET @SQL = @SQL + ' fpt.UnitsType,
					fpt.unitid,
					fpt.unit,
					fpt.nunitid,
					fpt.nunit,
					--fpt.rate,
					fpt.BuyUnitId,
					fpt.buyunitname,
					fpt.buymunitrate,
					fpt.SaleUnitId,
					fpt.saleunitname,
					fpt.salemunitrate,
					fpt.StockUnitId,
					fpt.stockunitname,
					fpt.stockmunitrate,
					fpt.ifusegoodsnum,
					M.rate,
					M.price as nsaleprice,
					M.price,
					M.total,
					fpt.unitid as munitid,
					fpt.unit as munit,
					M.qty as mqty,
					M.total as nsaletotal,
					M.price as curmsaleprice,
					1 AS Discount,
					M.Price AS DiscountPrice,
					M.Total AS DiscountTotal,
					0 AS Tax,
					0 as ntaxmoney,
					0 as taxmoney,
					M.Price AS TaxPrice,
					M.Price AS NTaxPrice,
					M.Price AS curmtaxprice,
					M.Total AS TaxTotal,
					M.Total as ntaxtotal,
					M.Price as curmdiscountprice,
					M.Price as mdiscountprice,
					M.Price as ndiscountprice,
                    M.total as ntotal,
                    M.Price as msaleprice,
                    M.nqty,
					'
					
					
IF @BillType IN (300,301,34,6,144,146,140,142,11,45) 
SET @SQL = @SQL + ' 
                    ,k.typeid as ktypeid,
					k.fullname as kfullname,
					c.cargoid as cargoid,
					c.fullname as cargofullname
					
				'	
				
				
					
--处理自定义	   
SET @SQL = @SQL +'
,cbd.*,e1.fullname as efullnamecustom,
p1.fullname as pfullnamecustom,
b1.fullname as bfullnamecustom,
d1.fullname as dfullnamecustom,
k1.fullname as kfullnamecustom,
s1.fullname as sfullnamecustom,
brandartypeid = (select top 1 typeid FROM dbo.brandar_Commodity WHERE typeid = p.brandartypeid),
brandarfullname = (select top 1 fullname FROM dbo.brandar_Commodity WHERE typeid = p.brandartypeid) '
IF @BillType IN(305,300,45,160,139,140,141,142,143,403,
				301,6,161,126,144,146,145,147,401,
				201,202,17,21,187,188,14,9,16,
				184,185,204)
BEGIN
	SET @SQL=@SQL+',(dbo.F_GetAllEntrycode(p.TypeId,m.MUnitID,2)) AS salemunitcode,
					 (dbo.F_GetAllEntrycode(p.TypeId,m.MUnitID,2)) AS buymunitcode,
					 (dbo.F_GetAllEntrycode(p.TypeId,m.MUnitID,2)) AS stockmunitcode'
END

IF @BillType IN (300,301,34,6,144,146,140,142,11,45) 
	SET @SQL += ' ,
(SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks g WHERE g.PtypeId = M.pTypeID AND g.KtypeId = M.ktypeid  ) AS showcostprice	 	
'
ELSE
	SET @SQL += ' ,
(SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks g WHERE g.PtypeId = M.pTypeID AND g.KtypeId = '''+@Ktypeid+'''  ) AS showcostprice	 	
'


SET @SQL = @SQL + '
			FROM	'+@MxTableName+'  M
			LEFT JOIN (SELECT SUM(ISNULL(QTY,0)) AS Qty,
							  PTypeid,
							  KTypeid 
					   FROM GoodsStocks
					   GROUP BY Ptypeid , Ktypeid
			) G ON M.Ptypeid=G.Ptypeid AND G.KtypeID='+char(39)+@Ktypeid+char(39)+' 
			INNER JOIN #BillIndex B ON B.BillNumberId = M.BillNumberId
			LEFT JOIN PuserCode PC ON M.PtypeId=PC.Ptypeid AND PC.btypeid='+char(39)+@DealBtypeId+char(39)+'
			LEFT JOIN stype ON M.stypeid=stype.typeid
			INNER JOIN F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') P ON M.PTypeId = P.TypeId 
			INNER JOIN PType_Units_Ext unit ON p.typeid=unit.ptypeid AND unit.unitsid=M.MUnitID ' 

IF @BillType = 204
BEGIN
	SET @SQL = @SQL + ' LEFT JOIN (SELECT q.ptypeid,q.btypeid,b.fullname as bfullname FROM QP_PType_Ext q LEFT JOIN btype b ON q.btypeid=b.typeid) qpe ON qpe.ptypeid=p.typeid'
	SET @SQL = @SQL + ' LEFT JOIN btype reqb ON reqb.typeid=M.btypeid'
	    --'LEFT JOIN OrderBill ob ON ob.RequestBillID=M.ID'
END



--IF @BillType IN (305,300,45,160,139,140,141,142,143,403,
--				301,6,161,126,144,146,145,147,401,
--				201,202,17,21,187,188,14,9,16,
--				184,185,204)
--BEGIN
--	SET @SQL=@SQL+' LEFT  JOIN  dbo.F_GetPtypeUnitInfo() f on f.typeid = p.TypeId'
--END
 
IF @BillType IN (300,301,34,6,144,146,140,142,305,11,45,184,185,204,17,21,187,188,215)
SET @SQL = @SQL + ' LEFT  JOIN  dbo.PType_Units U ON U.UnitsId=M.MUnitID 
				    LEFT  JOIN  dbo.PType_Units V ON V.UnitsId=M.NUnitID
				    LEFT  JOIN  dbo.PType_Units W ON W.UnitsId=M.UnitID '

IF @BillType IN (300,301,34,6,144,146,140,142,11,45) 
SET @SQL = @SQL + ' LEFT  JOIN  stock k ON k.typeid=m.ktypeid
				    LEFT  JOIN  cargotype c ON c.cargoid=m.cargoid
			 '

--处理自定义	   
SET @SQL = @SQL +'
LEFT JOIN custom_billdetails cbd ON m.billnumberid=cbd.billid and m.id=cbd.detailid AND cbd.BillType='+@BillType+'
LEFT JOIN employee e1 ON cbd.sysdiy11=e1.typeid
LEFT JOIN ptype p1 ON cbd.sysdiy12=p1.typeid
LEFT JOIN btype b1 ON cbd.sysdiy13=b1.typeid
LEFT JOIN department d1 ON cbd.sysdiy14=d1.typeid
LEFT JOIN stock k1 ON cbd.sysdiy15=k1.typeid
LEFT JOIN stype s1 ON cbd.sysdiy16=s1.typeid
'


IF @BillType NOT IN (178,191,196,197)
Begin
SET @SQL = @SQL + ' INNER JOIN dbo.PType pt ON M.PTypeID = pt.TypeID '
SET @SQL = @SQL + ' INNER JOIN F_GetPtypeUnitInfo() fpt ON pt.TypeID = fpt.TypeID '
END
--停止采购的不出来
--IF @BillType IN (301,34)
--	SET @SQL = @SQL + ' INNER JOIN PType BP ON (BP.TypeId = M.PTypeId AND BP.StopBuy = 0)'
					
SET @SQL = @SQL + '					
			WHERE	P.Deleted = 0  
			'+CASE @BillType WHEN 204 THEN ' AND M.state<=8' ELSE'' END+'				
			'
			
IF @IsIni = 1	   SET @SQL = @SQL + ' AND B.IsIni=1'	

--请购单审核通过的才可以调出

IF @BillType = 204 
	BEGIN
		SET @SQL = @SQL +' AND M.isstop <> 1  And ( ( b.billnumberid in
								   (
									SELECT a.BillNumberID FROM dbo.AuditingBill a
								    INNER JOIN 
								    dbo.AuditingFlowSet c
								    ON a.AuditingID=c.AuditingID 
								    )
								   AND b.billnumberid in 
								   (
								    SELECT a.BillNumberID FROM dbo.AuditingBill a
								    INNER JOIN 
								    dbo.AuditingFlowSet c
								    ON a.AuditingID=c.AuditingID 
								    AND a.IfAudit = ''1''
								    )
								 ) 
								 OR
							     ( b.BillNumberId NOT IN 
							        ( SELECT a.BillNumberID FROM dbo.AuditingBill a
									  INNER JOIN dbo.AuditingFlowSet c
									  ON a.AuditingID=c.AuditingID 
								    )
								   OR ISNULL(b.IfAudit,'''')='''' 
								 ) 
					          ) 				'	
		SET @SQL = @SQL +' AND (M.Qty - ISNULL(M.RequestQty,0) ) > 0'
		
		--if(@requestdate<>'')
		--begin
		--	SET @SQL = @SQL+' AND M.RequestDate='''+@requestdate+''''
		--end
		--if(@btypeid<>'')
		--begin
		--	SET @SQL = @SQL+' AND M.btypeid='''+@btypeid+''''
		--end
		IF @BTypeID<>''
			SET @SQL =@SQL +' AND M.BTypeID='''+@BTypeID + '''';
	END
IF @BillType=184 AND @NotuseComplet=1 SET @SQL = @SQL + ' AND M.QTY>M.UseQty '
IF @BillType IN (300,301) SET @SQL = @SQL + ' AND M.BillOver=0'	
IF @showServicePtype='0' SET @SQL = @SQL + ' AND P.isservice=0'
						
IF @BillType IN (300,301)
BEGIN
	SET @SQL=@SQL+'ORDER BY M.BillNumberId ASC,M.ORDERID '
END
ELSE
BEGIN
	SET @SQL=@SQL+'ORDER BY M.BillNumberId ASC,M.ID '
END

--PRINT(@SQL)
EXEC(@SQL)			
			

DROP TABLE #BillIndex,#MxTable,#SplitBillNumberId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportDataToBillMxNew]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_ImportDataToBillMxNew]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-13
	描述：导入单据明细
	EXEC Qp_ImportDataToBillMx '00001','0','301',''
*/

/*
	修改：覃雨翔
	日期：2011-08-23
	描述：询价单，报价单查询账面库存
*/

/*
	修改：李灏龙
	日期：2012年2月10日9:35:38
	描述：增添查询字段，为订单保存所需字段，具体修改处注释：zs001
	
	
	2017-02-20 梁晰 成本调价单没有MUnitID这个字段
*/

/*
	修改：刘飞
	日期：2017-02-21
	描述：查询速度慢优化,去掉使用函数F_GetManPTypeAll、
*/
CREATE PROCEDURE Qp_ImportDataToBillMxNew
(
	@OperatorId		VARCHAR(100),
	@IsDraft		VARCHAR(100),
	@BillType		VARCHAR(100),
	@nBillIds		VARCHAR(8000)='',
	@DealBtypeId    VARCHAR(50)='',
	@Ktypeid        VARCHAR(50)='',
	@isservice      VARCHAR(50)='',
	@IsIni			int=0,				--1为期初单据，0为非期初单据
	@sale           VARCHAR(50)='',
	@stypeid        VARCHAR(50)='',
	@issumptype		VARCHAR(10)='0',	--汇总相同商品  0.不汇总  1.汇总
	@noprice		VARCHAR(10)='0'		--导入价格信息  0.不导    1.导入
	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @BillIndexTable VARCHAR(100),
		@MxTableName	VARCHAR(100),
		@SQL 			VARCHAR(8000)
		
CREATE TABLE #SplitBillNumberId
(
	BillNumberId		NUMERIC(18,0)
)	   
INSERT INTO #SplitBillNumberId(BillNumberId) SELECT A FROM dbo.f_split(@nBillIds,',') WHERE ISNULL(A,'')<>''

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T 
FROM custom_billdetails cbd 
INNER JOIN #SplitBillNumberId sbn ON cbd.BillId=sbn.billnumberid
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.billtype=@BillType

CREATE TABLE #BillIndex
(
	BillNumberId		NUMERIC(18,0),
	billtype			INT,
	BillDate			VARCHAR(20),
	BillCode			VARCHAR(400),
	IsIni				bit,
	ifaudit				int,
	FullName			VARCHAR(200),
	CostSale			int
)		

CREATE TABLE #MxTable
(
	PTypeId			VARCHAR(100),
	Unit1			VARCHAR(100),
	Qty				 NUMERIC(24, 10) ,
	SalePrice		 NUMERIC(24, 10) ,
	SaleTotal		 NUMERIC(24, 10) ,
	Discount		 NUMERIC(24, 10) ,
	DiscountPrice	 NUMERIC(24, 10) ,
	DiscountTotal	 NUMERIC(24, 10) ,
	Tax				 NUMERIC(24, 10) ,
	TaxPrice		 NUMERIC(24, 10) ,
	TaxTotal		 NUMERIC(24, 10) ,	
	Comment			VARCHAR(400)
)
		
-------------------------------------主表-------------------------------------
IF @BillType =204
	SET @BillIndexTable = 'requestindex'
ELSE IF @BillType IN (301,300)
	SET @BillIndexTable = 'OrderIndex'
ELSE
	SET @BillIndexTable = 'BillIndex'	
IF	@BillType =408
    SET @BillIndexTable = 'DiyIndex'
	
IF @BillType IN (204)
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	B.BillNumberId,
					204,
					B.BillDate,
					B.BillCode,
					B.IsIni,
					B.ifaudit,
					'''' as FullName ,
					'''' as CostSale
			FROM	'+@BillIndexTable+' B,
					#SplitBillNumberId S
			WHERE	B.BillNumberId = S.BillNumberId
					AND BillType = '+CHAR(39)+@BillType+CHAR(39)
ELSE IF @BillType  NOT IN (408)
BEGIN
	SET @SQL = 'INSERT INTO #BillIndex
				SELECT	B.BillNumberId,
						B.billtype,
						B.BillDate,
						B.BillCode,
						B.IsIni,
						B.ifaudit,bt.FullName'
	IF @BillType NOT IN (301,300)
	BEGIN
		SET @SQL = @SQL+',B.CostSale '
	END
	ELSE
	BEGIN
		SET @SQL = @SQL+', '''' as CostSale '
	END
	
	SET @SQL = @SQL+' FROM	'+@BillIndexTable+' B INNER JOIN #SplitBillNumberId S ON B.BillNumberId = S.BillNumberId AND BillType = '+CHAR(39)+@BillType+CHAR(39)+'
						LEFT JOIN btype bt ON bt.typeid=B.btypeid'
END
ELSE 
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	B.BillNumberId,
					408,
					B.BillDate,
					B.IndexOrderId as BillCode,
					''0'' as IsIni,
					'''' as ifaudit,
					'''' as FullName,
					'''' as CostSale
			FROM	'+@BillIndexTable+' B,
					#SplitBillNumberId S
			WHERE	B.BillNumberId = S.BillNumberId
					 '
					
IF @BillType NOT IN (408,204)
 BEGIN
 
IF @BillType NOT IN (301,300)					
	BEGIN
		IF @IsDraft = 0 
			SET @SQL = @SQL + ' AND B.IfCheck = ''t'' AND B.RedWord = 0 '
		ELSE IF @IsDraft = 1
			SET @SQL = @SQL + ' AND B.IfCheck = ''f'' AND B.Draft = 1 '
		ELSE
			SET @SQL = @SQL + ' AND 1 = 1 '
	END	
ELSE 
	BEGIN
		IF @IsDraft = 0
			SET @SQL = @SQL + ' AND 1 = 0 '
		ELSE
			SET @SQL = @SQL + ' AND B.BillOver = 0 '
	END
	
 END

IF @BillType NOT IN (408)			
SET @SQL = @SQL + '					
			ORDER BY B.BillDate DESC,B.BillCode DESC '
ELSE 
SET @SQL = @SQL + '					
			ORDER BY B.BillDate DESC,B.IndexOrderId DESC '

--PRINT(@SQL)
EXEC(@SQL)

---------------------------------------明细表-------------------------------------
IF @BillType IN (300,301)
	SET @MxTableName = 'OrderBill'
ELSE IF @BillType = 34
	SET @MxTableName = 'BuyBill'
ELSE IF @BillType = 6
	SET @MxTableName = 'BuyBackBill'
ELSE IF @BillType IN (144,146,140,142)
	SET @MxTableName = 'CommissionBill'
ELSE IF @BillType = 305
	SET @MxTableName = 'RetailBill'
ELSE IF @BillType = 215
	SET @MxTableName = 'RetailBackBill'
ELSE IF @BillType = 11
	SET @MxTableName = 'SaleBill'
ELSE IF @BillType = 45
	SET @MxTableName = 'SaleBackBill'
ELSE IF @BillType = 17
	SET @MxTableName = 'MoveBill'
ELSE IF @BillType = 21
	SET @MxTableName = 'MoveBjBill'
ELSE IF @BillType = 57
	SET @MxTableName = 'AdPriceBill'
ELSE IF @BillType = 184
	SET @MxTableName = 'QuotePriceBill'
ELSE IF @BillType = 185
	SET @MxTableName = 'AskPriceBill'
ELSE IF @BillType IN (187,188)
	SET @MxTableName = 'STypeMoveBill'
ELSE IF @BillType = 178
	SET @MxTableName = 'QP_QuickRepairBill_PType'
ELSE IF @BillType = 191
	SET @MxTableName = 'Qp_PickingBill'
ELSE IF @BillType = 196
	SET @MxTableName = 'Qp_SuccorBill_PType'
ELSE IF @BillType = 197
	SET @MxTableName = 'Qp_PickingBackBill'
ELSE IF @BillType = 204
	SET @MxTableName = 'Requestbill'
ELSE IF @BillType = 408
	SET @MxTableName = 'Diybill'	
ELSE IF @BillType = 126
	SET @MxTableName = 'givemebill'
ELSE IF @BillType = 139
	SET @MxTableName = 'givebill'
ELSE IF @billtype = 403		
BEGIN
    SET @MxTableName = 'SendBackBill'
END
ELSE IF @billtype = 401
BEGIN
    SET @MxTableName = 'AppraisalBackBill'
END
	
--分支机构物价信息
DECLARE @PriceType varchar(5)
SELECT @PriceType=PriceType FROM SType WHERE TypeId=@stypeid

IF @stypeid = '' OR @stypeid = null
BEGIN

SET @PriceType='0'
SET @stypeid=''

END

--bug1560,张媛媛说序列号显示应该是第一个"序列号..."
DECLARE @Ser varchar(max)
IF @BillType NOT IN (300,301,57,184,185,178,191,196,197,204,408)
BEGIN
	SET @SQL = 'SELECT	CASE DATALENGTH(M.Serial)
							WHEN 0
								THEN ''''
							ELSE
								SUBSTRING(M.Serial,(charindex(''я'',M.Serial)+1),charindex(''я'',M.Serial,charindex(''я'',M.Serial)+1)-2)+''...'' 
						END AS Serial1,
						M.Serial AS Serial,
						P.ifSerial,
						P.TypeId,
						M.PTypeId,
						P.UserCode,
						P.FullName,
						P.Unit1 AS unitone,
						P.Unit2 As unittwo,
						M.Qty,
						R.PreBuyPrice1,
						R.PreBuyPrice2,
						R.PreBuyPrice3,
						R.PreBuyPrice4,
						R.PreBuyPrice5,
						R.PreSalePrice1,
						R.PreSalePrice2,
						R.PreSalePrice3,
						R.PreSalePrice4,
						R.PreSalePrice5,
						R.PreSalePrice6,
						R.PreSalePrice7,
						R.PreSalePrice8,
						R.PreSalePrice9,
						R.PreSalePrice10,
						R.RetailPrice,
						R.TopSalePrice,
						R.LowSalePrice,					
						R.TopBuyPrice,
						null as cargoid,
						null as outcargoid,					   
						(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname1,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname2,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname3,
						(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate1,
						(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate2,
						(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate3,
						PC.UserCode AS CustomerCode,
						(select isservice from ptype where typeid = m.PTypeID) as isservice,
						'''+@PriceType+''' as PriceType, 
						isnull((select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=m.PTypeID  and STYPEID=''' + @stypeid + ''' AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+'),0) as SReferPrice,
						(select referprice from PType_Price where PTypeID = m.PTypeID AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+') as preferprice,
						(select referprice from PType_Price where PTypeID = m.PTypeID AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+') as referprice,
						pp.ifusegoodsnum,
						 '
	END						 
ELSE IF @BillType IN (408)
	BEGIN
		SET @SQL = 'SELECT	NULL AS serial1,
							NULL AS Serial,
							P.TypeId,
							P.ifSerial,
							M.PTypeId,
							P.UserCode,
							P.FullName,
							P.Unit1 AS unitone,
							P.Unit2 As unittwo,
							M.Qty,
							R.PreBuyPrice1,
							R.PreBuyPrice2,
							R.PreBuyPrice3,
							R.PreBuyPrice4,
							R.PreBuyPrice5,
							R.PreSalePrice1,
							R.PreSalePrice2,
							R.PreSalePrice3,
							R.PreSalePrice4,
							R.PreSalePrice5,
							R.PreSalePrice6,
							R.PreSalePrice7,
							R.PreSalePrice8,
							R.PreSalePrice9,
							R.PreSalePrice10,
							R.RetailPrice,
							R.TopSalePrice,
							R.LowSalePrice,					
							R.TopBuyPrice,
							(dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS buymunitcode,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname1,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname2,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname3,
							(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate1,
							(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate2,
							(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate3,
							PC.UserCode AS CustomerCode,
							(select isservice from ptype where typeid = m.PTypeID) as isservice,
							'''+@PriceType+''' as PriceType, 
							isnull((select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=m.PTypeID  and STYPEID=''' + @stypeid + ''' AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+'),0) as SReferPrice,
							(select referprice from PType_Price where PTypeID = m.PTypeID AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+') as preferprice,
							(select referprice from PType_Price where PTypeID = m.PTypeID AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+') as referprice,
							M.Comment,
							M.Comment as mxcomment,
							pp.ifusegoodsnum,
							 '
		END
ELSE					 
	BEGIN
		SET @SQL = 'SELECT	NULL AS Serial1,
							NULL AS Serial,
							P.TypeId,
							P.ifSerial,
							M.PTypeId,	
							P.UserCode,
							P.FullName,						
							P.Unit1 AS unitone,
							P.Unit2 As unittwo,
							M.Qty,
							R.PreBuyPrice1,
							R.PreBuyPrice2,
							R.PreBuyPrice3,
							R.PreBuyPrice4,
							R.PreBuyPrice5,
							R.PreSalePrice1,
							R.PreSalePrice2,
							R.PreSalePrice3,
							R.PreSalePrice4,
							R.PreSalePrice5,
							R.PreSalePrice6,
							R.PreSalePrice7,
							R.PreSalePrice8,
							R.PreSalePrice9,
							R.PreSalePrice10,
							R.RetailPrice,
							R.TopSalePrice,
							R.LowSalePrice,					
							R.TopBuyPrice,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname1,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname2,
							(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname3,
							(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate1,
							(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate2,
							(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate3,
							PC.UserCode AS CustomerCode,
							(select isservice from ptype where typeid = m.PTypeID) as isservice,
							'''+@PriceType+''' as PriceType, 
							isnull((select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=m.PTypeID  and STYPEID=''' + @stypeid + ''' AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+'),0) as SReferPrice,
							(select referprice from PType_Price where PTypeID = m.PTypeID AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+') as preferprice,
							(select referprice from PType_Price where PTypeID = m.PTypeID AND UnitID='+Case WHEN @billtype=57 THEN 'p.BaseUnitID' ELSE 'M.MUnitID' END+') as referprice,
							pp.ifusegoodsnum,
							 '
	END
					 
--sale =1 销售 -2 库存 否则为采购

IF @BillType IN(57)
BEGIN
	IF @sale = '1'				 
		SET @SQL = @SQL + ' (dbo.F_GetAllEntrycode(M.Ptypeid,p.BaseUnitID,2)) AS salemunitcode,
							(dbo.F_GetAllEntrycode(M.Ptypeid,p.BaseUnitID,2)) AS buymunitcode,
							(dbo.F_GetAllEntrycode(M.Ptypeid,p.BaseUnitID,2)) AS stockmunitcode, '
	ELSE IF @sale = '2'
		SET @SQL = @SQL + ' (dbo.F_GetAllEntrycode(M.Ptypeid,p.BaseUnitID,2)) AS stockmunitcode,
							(dbo.F_GetAllEntrycode(M.Ptypeid,p.BaseUnitID,2)) AS buymunitcode,
							(dbo.F_GetAllEntrycode(M.Ptypeid,p.BaseUnitID,2)) AS salemunitcode, '
	ELSE 
		SET @SQL = @SQL + ' '''' AS salemunitcode,
							'''' AS buymunitcode,
							'''' AS stockmunitcode,
						  '
END
ELSE 
BEGIN
	IF @sale = '1'				 
		SET @SQL = @SQL + ' (dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS salemunitcode, 
							(dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS buymunitcode,
							(dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS stockmunitcode,'
	ELSE IF @sale = '2'
		SET @SQL = @SQL + ' (dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS stockmunitcode,
							(dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS buymunitcode,
							(dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS salemunitcode, '
	ELSE
		IF(@BillType NOT IN (57))		
		BEGIN		 
			SET @SQL = @SQL + ' (dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS salemunitcode, '    
			SET @SQL = @SQL + ' (dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS buymunitcode, '  
			SET @SQL = @SQL + ' (dbo.F_GetAllEntrycode(M.Ptypeid,M.MUnitID,2)) AS stockmunitcode, '  
		END
END

IF @BillType IN (408)
SET @SQL = @SQL + ' 
                    M.saleprice as msaleprice,
                    M.saleprice as curmdiscountprice,
                    M.saleprice as nsaleprice,
                    M.saleprice as nprice,
                    M.saleprice as curmsaleprice,
                    M.saleprice as price,
                    M.qty as mqty,
                    0 as nqty,
                    M.saletotal as ntotal,
                    M.saletotal as nsaletotal,
                    ''1'' as Discount,
                    ''0'' as tax,
                    M.saletotal as total,
                    M.saleprice as discountprice,
                    M.saletotal as discounttotal,
                    M.saleprice as taxprice,
                    M.saletotal as taxtotal,
                    '''' as itemid,
                    --'''' as serial1,
                    '''' as goodsnumber,
                    (dbo.F_GetAllEntrycode(pp.typeid,pp.buyunitid,2)) as munitcode,
                    (select rate from ptype_units_ext where ptypeid=pp.typeid and unitsid=pp.AssistantUnitId) as UnitRate,
                     (select rate from ptype_units_ext where ptypeid=pp.typeid and unitsid=pp.buyunitid) as MUnitRate,
                    
                    M.saleprice as curmtaxprice,
					M.saletotal as ntaxmoney,
					M.saletotal as ntaxtotal,
					M.saletotal as taxmoney,
					M.saleprice as NTaxPrice,
					M.saleprice as NDiscountPrice,
					M.saleprice as MDiscountPrice,
					M.saleprice as MTaxPrice,
					pp.buyunitid as MUnitID,
					pp.AssistantUnitId as NUnitID,
					pp.baseunitid as UnitID,
                    (select fullname from PType_Units where UnitsId=pp.baseunitid) AS unit,
					(select fullname from PType_Units where UnitsId=pp.buyunitid) AS munit,
					(select fullname from PType_Units where UnitsId=pp.AssistantUnitId) AS nunit,	
					
                    '
                    
IF @BillType IN (139,126)
	SET @SQL = @SQL + ' 
                    0 as msaleprice,
                    0 as curmdiscountprice,
                    0 as nsaleprice,
                    0 as nprice,
                    0 as curmsaleprice,
                    0 as price,
                    M.mqty as mqty,
                    M.nqty as nqty,
                    0 as ntotal,
                    0 as nsaletotal,
                    ''1'' as Discount,
                    ''0'' as tax,
                    0 as total,
                    0 as discountprice,
                    0 as discounttotal,
                    0 as taxprice,
                    0 as taxtotal,
                    M.munitrate as munitrate,
                    M.UnitRate as UnitRate,
                    0 as curmtaxprice,
					0 as ntaxmoney,
					0 as ntaxtotal,
					0 as taxmoney,
					0 as NTaxPrice,
					0 as NDiscountPrice,
					0 as MDiscountPrice,
					0 as MTaxPrice,
					M.MUnitID, 							
					M.NUnitID,
					M.UnitID,
					W.fullname AS unit,
					U.FullName AS munit,
					V.FullName AS nunit,
					ISNULL(G.Qty,0) AS AccountQty,
					M.KTypeId,
					(select fullname from stock where typeid=M.ktypeid) as kfullname,
					(select fullname from cargotype where cargoid=M.cargoid) as cargofullname, 
					M.Comment AS MxComment,
					'''' AS InCargoSpace,
					'''' AS OutCargoSpace, 
                    '                         

IF @BillType IN (57)
	SET @SQL = @SQL + ' M.UnitRate,
					M.beforeprice,
                    1 as munitrate,--兼容单据明细导入（含有大单位的单据）
                    fpt.UnitsType, '
ELSE
	SET	@SQL = @SQL + ' pt.unitstype, '		


IF @BillType IN (17,21)
SET @SQL = @SQL + ' M.MPrice as msaleprice,
                    M.total as nsaletotal,
                    ISNULL(G.Qty,0) AS AccountQty,
                    M.Price as MTaxPrice,
					M.goodsnumber,   
					M.KTypeId,
					(select fullname from stock where typeid=M.ktypeid) as kfullname,
					(select fullname from cargotype where cargoid=M.outcargoid) as cargofullname,                  
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=M.ItemId,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					iscombined=M.IsCombined,
                  '                  

				
IF @BillType IN (305,300,11,45,140,142,301,34,6,144,146,57,215,403,401)
SET @SQL = @SQL + ' M.goodsnumber,   
					M.KTypeId,
					(select fullname from stock where typeid=M.ktypeid) as kfullname,
					(select fullname from cargotype where cargoid=M.cargoid) as cargofullname,                  
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=M.ItemId,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					iscombined=M.IsCombined,
                  '

IF @BillType IN (187,188)
SET @SQL = @SQL + ' M.goodsnumber,   
					M.KTypeId,
					(select fullname from stock where typeid=M.ktypeid) as kfullname,
					(select fullname from cargotype where cargoid=M.outcargoid) as cargofullname,                  
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=M.ItemId,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					iscombined=M.IsCombined,
					ISNULL(G.Qty,0) AS AccountQty,
					M.Price AS MTaxPrice,
					M.Price AS MSalePrice,'
    
        
     
IF @BillType IN (139,126)
SET @SQL = @SQL + ' M.goodsnumber,                     
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=M.ItemId,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					iscombined=M.IsCombined
                  '

IF @BillType IN (408)
SET @SQL = @SQL + '                     
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid	        
					
                  '
         
IF @BillType IN (184,185)
SET @SQL = @SQL + '
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=M.ItemId,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					iscombined=M.IsCombined,
				    '''' as goodsnumber,
                  '
		
IF 	@BillType NOT IN (57,408,139,126)
	SET @SQL = @SQL + ' M.munitrate,'
				

IF @BillType IN (300,301,34,6,144,146,140,142,305,11,45,184,185,204,215,403,401)
	SET @SQL = @SQL + ' M.curmsaleprice,
					M.mqty,
					M.nsaleprice,
					M.nsaleprice as nprice,
					CASE WHEN ISNULL(M.NUnitID,0) = 0 THEN NULL
					ELSE M.nqty END AS nqty,
					M.curmdiscountprice,
					M.curmtaxprice,
					M.ntaxmoney,
					M.ntaxtotal,
					M.taxmoney,
					M.MUnitID, 							
					M.NUnitID,
					M.UnitID,
					W.fullname AS unit,
					U.FullName AS munit,
					V.FullName AS nunit,						      
					M.nsaletotal,
					M.ntotal,
					M.NTaxPrice,
					M.NDiscountPrice,
					M.MSalePrice,
					M.MDiscountPrice,
					M.MTaxPrice,
					--'''' as serial1,					
					'					
						
IF @BillType IN (184,185)	--zs001 添加ID与BillNumberID，这样在保存单据时能在明细中添入AskBillID和AskBillNumberID
	SET @SQL = @SQL + ' M.ID AS AskBillID,
	                    --'''' as serial1,
						M.BillNumberID AS AskBillNumberID,
						M.Price,
						M.Price as beforeprice,
						M.SaleTotal AS Total,
						M.Discount,
						M.DiscountPrice,
						M.Total AS DiscountTotal,
						M.Tax,
						M.TaxPrice,
						M.TaxTotal AS TaxTotal,
						M.Comment AS MxComment,		
						ISNULL(G.Qty,0) AS AccountQty,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace,
						'''' AS ktypeid,
						'''' AS cargoid, 
						'''' AS kfullname,
						'''' AS cargofullname '

ELSE IF @BillType IN (300,301)
	SET @SQL = @SQL + '	M.cargoid,
						M.Price,						
						M.NSaleTotal AS Total,						
						M.Discount,
						M.DiscountPrice,
						M.Total AS DiscountTotal,
						M.Tax,
						M.TaxPrice,
						M.TaxTotal AS TaxTotal,
						M.Comment AS MxComment,	
						ISNULL(G.Qty,0) AS AccountQty,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace '

ELSE IF @BillType IN (34,6,144,146,140,142,305,11,45,215,403,401)
	SET @SQL = @SQL + ' M.SalePrice AS Price,
						M.SaleTotal AS Total,
						M.NSalePrice as beforeprice,
						M.NSaleTotal as beforetotal,
						M.Discount,
						M.DiscountPrice,
						M.Total AS DiscountTotal,
						M.Tax,
						M.TaxPrice,
						M.TaxTotal AS TaxTotal,
						M.Comment AS MxComment,
						ISNULL(G.Qty,0) AS AccountQty,
						'''' AS CargoSpace,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace '

ELSE IF @BillType IN (17,21,187,188,191,197,196)
BEGIN
	SET @SQL = @SQL + ' M.Price,
	                    M.Price as beforeprice,
	                    M.Price as nsaleprice,
	                    M.Price as nprice,
	                    M.MPrice as curmsaleprice, 
						M.Total AS Total,
						M.Total AS beforetotal,
						1 AS Discount,
						M.Price AS DiscountPrice,
						M.MPrice AS mdiscountprice,
                        M.Price AS ndiscountprice,
						M.Total AS DiscountTotal,
						0 AS Tax,
						0 as ntaxmoney,
						0 as taxmoney,
						M.Price AS TaxPrice,
						M.price as ntaxprice,
						M.MPrice AS curmtaxprice,
						M.Total AS TaxTotal,
						M.Total as ntaxtotal,
						M.Comment AS MxComment,
						M.MPrice AS curmdiscountprice,
						M.Total AS ntotal, 
						M.MQty,
						M.nqty,						
						M.NUnitID,
						M.UnitID,
						M.MUnitID,
						W.fullname AS unit,
						U.FullName AS munit,
						V.FullName AS nunit,
						
						 '
	IF @BillType IN (187,188)
		SET @SQL = @SQL + '
						M.Total AS nsaletotal,'


	IF @BillType IN (17,21,187,188)
		SET @SQL = @SQL + '
						'''' AS CargoSpace,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace '
    ELSE IF @BillType IN (191,197,196)
		SET @SQL = @SQL + '
						M.CargoSpace,
						
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace '			
	ELSE
		SET @SQL = @SQL + '
		               
						'''' AS CargoSpace,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace'
END
ELSE IF @BillType = 178
BEGIN
	SET @SQL = @SQL + 'M.Price,
	                   M.Price as beforeprice,
					   M.Total,
					   M.Discount,
					   M.DiscountPrice,
					   M.DiscountTotal,
					   0 AS Tax,
					   M.DiscountPrice AS TaxPrice,
					   M.DiscountTotal AS TaxTotal,
					   M.Comment AS MxComment,
					   M.CargoSpace,					  
					   '''' AS InCargoSpace,
					   '''' AS OutCargoSpace'
END					   
					   
ELSE IF @BillType = 204
BEGIN
	SET @SQL = @SQL + ' M.SalePrice AS Price,
						M.SaleTotal AS Total,
						M.Discount,
						M.DiscountPrice,
						M.Total AS DiscountTotal,
						M.Tax,
						M.TaxPrice,
						M.TaxTotal AS TaxTotal,
						M.Comment AS MxComment,						
						M.ID AS requestbillid,
						'''' AS CargoSpace,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace,
						ISNULL(G.Qty,0) AS AccountQty,						
						pt.customitemid,
						pt.customitemfrom,
						pt.customitemname,
						pt.customitemrefid,		        
						itemid=M.ItemId,
						itemname= CASE WHEN M.IsCombined = 0  THEN
									(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
									ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
						iscombined=M.IsCombined,
						'''' as goodsnumber,
						'''' as KTypeId,
						'''' as CargoId,
						'''' as KFullName,
						'''' as CargoFullName
						 '
END						
						
IF 	@BillType = 57
BEGIN
	SET @SQL = @SQL + ' fpt.unitid,
						fpt.unit,
						fpt.nunitid,
						fpt.nunit,
						fpt.BuyUnitId,
						fpt.buyunitname,
						fpt.buymunitrate,
						fpt.SaleUnitId,
						fpt.saleunitname,
						fpt.salemunitrate,
						fpt.StockUnitId,
						fpt.stockunitname,
						fpt.stockmunitrate,
						M.rate,
						M.price as nsaleprice,
						M.price as nprice,
						M.price,
						M.total,
						fpt.unitid as munitid,
						fpt.unit as munit,
						M.qty as mqty,
						M.total as nsaletotal,
						M.price as curmsaleprice,
						1 AS Discount,
						M.Price AS DiscountPrice,
						M.Total AS DiscountTotal,
						0 AS Tax,
						0 as ntaxmoney,
						0 as taxmoney,
						M.Price AS TaxPrice,
						M.Price AS NTaxPrice,
						M.Price AS curmtaxprice,
						M.Total AS TaxTotal,
						M.Total as ntaxtotal,
						M.Price as curmdiscountprice,
						M.Price as mdiscountprice,
						M.Price as ndiscountprice,
						M.total as ntotal,
						M.Price as msaleprice,
						M.nqty,
						M.Comment AS MxComment,	
						ISNULL(G.Qty,0) AS AccountQty,
						M.Price AS MTaxPrice,
						M.CargoId,
						'''' AS InCargoSpace,
						'''' AS OutCargoSpace
						'
END						

IF @BillType IN(301,34,184,139,126,204,305,215,300,11,45,140,142,185,6,144,146,17,21,57,187,188)
	SET @SQL = @SQL + ',B.FullName as dealtypeName'

IF @BillType IN(11,45,215)
BEGIN
	SET @SQL=@sql +',re.typeid AS etypeid,re.fullname as efullname,re.usercode as eusercode '
END
IF @BillType IN(184,185,178,191,196,197,204,408 )
SET @SQL = @SQL + ','''' as ProduceDate
				   ,'''' as ValidDate'
ELSE 
SET @SQL = @SQL + ',M.ProduceDate as ProduceDate
				   ,M.ValidDate as ValidDate'
				   
IF @BillType = 11
BEGIN
	SET @SQL = @SQL + ',B.CostSale'
END

--查询自定义字段
SET @SQL = @SQL + '	,ct.*,
					brandartypeid = (select top 1 typeid FROM dbo.brandar_Commodity WHERE typeid = p.brandartypeid),
					brandarfullname = (select top 1 fullname FROM dbo.brandar_Commodity WHERE typeid = p.brandartypeid)'

SET @SQL = @SQL + '
			INTO	#Result
			FROM	'+@MxTableName+'  M
			LEFT JOIN (SELECT SUM(ISNULL(QTY,0)) AS Qty,
							  PTypeid,
							  KTypeid 
					   FROM GoodsStocks
					   GROUP BY Ptypeid , Ktypeid) G ON M.Ptypeid=G.Ptypeid AND G.KtypeID='+char(39)+@Ktypeid+char(39)+' 
			INNER JOIN #BillIndex B ON B.BillNumberId = M.BillNumberId
			LEFT JOIN PuserCode PC ON M.PtypeId=PC.Ptypeid AND PC.btypeid='+char(39)+@DealBtypeId+char(39)
--------------------去掉使用函数F_GetManPTypeAll------------------------------------------------------
--			INNER JOIN F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') P ON M.PTypeId = P.TypeId'
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerPTypeID = '00000')
	SET @SQL = @SQL + '
						INNER JOIN PType P ON M.PTypeId = P.TypeId
						INNER JOIN PType_Price R ON R.PTypeId = P.TypeId and p.baseunitid=R.unitid
						LEFT JOIN Qp_PType_Ext E ON E.PTypeId = P.TypeId' 
ELSE IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerPTypeID = '-99999')
	SET @SQL = @SQL + '
						INNER JOIN PType P ON M.PTypeId = P.TypeId
						INNER JOIN (SELECT	DISTINCT P.TypeId 
								FROM	PType_L L
								INNER JOIN PType  P ON (L.Flag=1 AND P.TypeId LIKE L.TypeId + ''%'')
								WHERE	L.etypeid = '+char(39)+@OperatorID+char(39)+'
								UNION
								SELECT	L.TypeID
								FROM	ptype_l L
								WHERE	L.etypeid = '+char(39)+@OperatorID+char(39)+'
										AND L.flag=0) MM ON P.TypeId = MM.TypeId
						INNER JOIN PType_Price R ON R.PTypeId = P.TypeId  and p.baseunitid=R.unitid
						LEFT JOIN Qp_PType_Ext E ON E.PTypeId = P.TypeId'
-------------------------------------------------------------------------------------------------------
SET @SQL = @SQL + '
			INNER JOIN Ptype pp ON pp.typeid=M.PTypeId
			 ' 
			 
IF @BillType IN (300,301,34,6,144,146,140,142,305,11,45,184,185,204,17,21,187,188,215,139,126,403,401)
SET @SQL = @SQL + ' LEFT  JOIN  dbo.PType_Units U ON U.UnitsId=M.MUnitID 
				    LEFT  JOIN  dbo.PType_Units V ON V.UnitsId=M.NUnitID
				    LEFT  JOIN  dbo.PType_Units W ON W.UnitsId=M.UnitID'
IF @BillType IN(11,45,215)
BEGIN
	SET @SQL = @SQL + ' LEFT JOIN EMPLOYEE re ON re.typeid=M.etypeid '
END		    				    
IF @BillType NOT IN (178,191,196,197)
Begin
SET @SQL = @SQL + ' INNER JOIN dbo.PType pt ON M.PTypeID = pt.TypeID '
SET @SQL = @SQL + ' INNER JOIN F_GetPtypeUnitInfo() fpt ON pt.TypeID = fpt.TypeID '
END
--停止采购的不出来
--IF @BillType IN (301,34)
--	SET @SQL = @SQL + ' INNER JOIN PType BP ON (BP.TypeId = M.PTypeId AND BP.StopBuy = 0)'

--处理自定义字段
IF @MxTableName='OrderBill'
BEGIN
	SET @SQL = @SQL + ' LEFT JOIN #Custom_T ct ON ct.Detailid=M.orderid '	
END
ELSE
BEGIN
	SET @SQL = @SQL + ' LEFT JOIN #Custom_T ct ON ct.Detailid=M.id '	
END

SET @SQL = @SQL + '					
			WHERE	P.Deleted = 0
			 
			'+CASE @BillType WHEN 204 THEN ' AND M.state<=8' ELSE'' END+'				
			'
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerPTypeID = '00000')
SET @SQL = @SQL + '
					AND P.TypeId <> ''00000''' 		
IF @IsIni = 1	   SET @SQL = @SQL + ' AND B.IsIni=1'	

IF @isservice <> 'true' AND @isservice <> 'True'  SET @SQL = @SQL + ' AND pp.isservice=0 '	

--请购单审核通过的才可以调出

IF @BillType = 204 
	BEGIN
		SET @SQL = @SQL +' And ( ( b.billnumberid in
								   (
									SELECT a.BillNumberID FROM dbo.AuditingBill a
								    INNER JOIN 
								    dbo.AuditingFlowSet c
								    ON a.AuditingID=c.AuditingID 
								    )
								   AND b.billnumberid in 
								   (
								    SELECT a.BillNumberID FROM dbo.AuditingBill a
								    INNER JOIN 
								    dbo.AuditingFlowSet c
								    ON a.AuditingID=c.AuditingID 
								    AND a.IfAudit = ''1''
								    )
								 ) 
								 OR
							     ( b.BillNumberId NOT IN 
							        ( SELECT a.BillNumberID FROM dbo.AuditingBill a
									  INNER JOIN dbo.AuditingFlowSet c
									  ON a.AuditingID=c.AuditingID 
								    )
								   OR ISNULL(b.IfAudit,'''')='''' 
								 ) 
					          ) 				'	
				   					   
	END
	
IF @BillType IN (300,301) SET @SQL = @SQL + ' AND M.BillOver=0'	

IF @BillType NOT IN (408)	
 BEGIN		

IF @BillType IN (300,301)
BEGIN
	SET @SQL=@SQL+'ORDER BY M.BillNumberId ASC,M.ORDERID '
END
ELSE
BEGIN
	SET @SQL=@SQL+'ORDER BY M.BillNumberId ASC,M.ID '
END

 END
ELSE 
  BEGIN
   SET @SQL=@SQL+' ORDER BY M.BillNumberId ASC '
  END   
  
--PRINT(@SQL)   
DECLARE @SqlResult VARCHAR(MAX) 

SET @SqlResult = ''

--汇总商品明细
IF @issumptype = '1' 
BEGIN
	IF @noprice = '1'
	BEGIN
		--不导入价格，清理价格才能合并
		SET @SqlResult = 'UPDATE	#Result
						  SET		total = 0,
									discount = 0,
									discountprice = 0,
									discounttotal = 0,
									tax = 0,
									taxprice = 0,
									taxtotal = 0,
									ntaxmoney = 0,
									ntaxtotal = 0,
									taxmoney = 0,
									nsaletotal = 0,
									ntotal = 0,
									curmsaleprice = 0,
									nsaleprice = 0,
									nprice = 0,
									curmdiscountprice = 0,
									curmtaxprice = 0,
									ntaxprice = 0,
									ndiscountprice = 0,
									msaleprice = 0,
									mdiscountprice = 0,
									mtaxprice = 0,
									price = 0,
									MxComment = '''',
									ktypeid = '''',
									cargoid = '''',
									kfullname = '''',
									cargofullname = ''''									
									'					  
	END
	
	SET @SqlResult = @SqlResult + '  					 
					SELECT	SUM(Qty) AS Qty,
							SUM(mqty) AS mqty,
							SUM(ntaxmoney) AS ntaxmoney,	
							SUM(ntaxtotal) AS ntaxtotal,	
							SUM(taxmoney) AS taxmoney,
							SUM(nsaletotal) AS nsaletotal,	
							SUM(ntotal) AS ntotal,
							SUM(Total) AS Total,	
							SUM(DiscountTotal) AS DiscountTotal,	
							SUM(AccountQty) AS AccountQty,	
							SUM(TaxTotal) AS TaxTotal,	
							SUM(nqty) AS nqty,'
END
ELSE
BEGIN
	SET @SqlResult = @SqlResult + '  					 
					SELECT	Qty AS Qty,
							mqty AS mqty,
							ntaxmoney AS ntaxmoney,	
							ntaxtotal AS ntaxtotal,	
							taxmoney AS taxmoney,
							nsaletotal AS nsaletotal,	
							ntotal AS ntotal,
							Total AS Total,	
							DiscountTotal AS DiscountTotal,	
							AccountQty AS AccountQty,	
							TaxTotal AS TaxTotal,	
							nqty AS nqty,'
END	
  
SET @SqlResult = @SqlResult + ' 
							TypeId, 					 				
							PTypeId,							
							Serial,							
							UserCode,
							FullName,
							unitone,
							unittwo,							
							PreBuyPrice1,
							PreBuyPrice2,
							PreBuyPrice3,
							PreBuyPrice4,
							PreBuyPrice5,
							PreSalePrice1,
							PreSalePrice2,
							PreSalePrice3,
							PreSalePrice4,
							PreSalePrice5,
							PreSalePrice6,
							PreSalePrice7,
							PreSalePrice8,
							PreSalePrice9,
							PreSalePrice10,
							RetailPrice,
							TopSalePrice,
							LowSalePrice,
							TopBuyPrice,
							auxfullname1,
							auxfullname2,
							auxfullname3,
							auxrate1,
							auxrate2,	
							auxrate3,	
							CustomerCode,	
							isservice,	
							PriceType,	
							SReferPrice,	
							preferprice,	
							referprice,	
							ifusegoodsnum,	
							salemunitcode,	
							buymunitcode,
							stockmunitcode,	
							unitstype,	
							goodsnumber,	
							customitemid,	
							customitemfrom,	
							customitemname,
							customitemrefid,	
							itemid,	
							itemname,	
							iscombined,	
							ktypeid,	
							cargoid,	
							kfullname,	
							cargofullname,	
							munitrate,	
							curmsaleprice,									
							nsaleprice,	
							nprice,
							curmdiscountprice,	
							curmtaxprice,									
							MUnitID,	
							NUnitID,	
							UnitID,	
							unit,	
							munit,	
							nunit,								
							NTaxPrice,	
							NDiscountPrice,	
							MSalePrice,	
							MDiscountPrice,	
							MTaxPrice,	
							serial1,
							ifserial,	
							Price,								
							Discount,	
							DiscountPrice,								
							Tax,
							TaxPrice,								
							MxComment,								
							InCargoSpace,	
							OutCargoSpace,	
							dealtypeName,	
							ProduceDate,	
							ValidDate,	
							BillId,	
							Detailid,	
							BillType,								
							iscombination,									
							InOrOut,	
							efullnamecustom,	
							pfullnamecustom,
							bfullnamecustom,	
							dfullnamecustom,	
							kfullnamecustom,	
							sfullnamecustom,	
							brandartypeid,	
							brandarfullname 
				'
					
IF @issumptype = '1' 	
	SET @SqlResult = @SqlResult + ' 	
					FROM	#Result  				
					GROUP BY 
							TypeId,
							PTypeId,							
							Serial,	
							ifserial,						
							UserCode,
							FullName,
							unitone,
							unittwo,							
							PreBuyPrice1,
							PreBuyPrice2,
							PreBuyPrice3,
							PreBuyPrice4,
							PreBuyPrice5,
							PreSalePrice1,
							PreSalePrice2,
							PreSalePrice3,
							PreSalePrice4,
							PreSalePrice5,
							PreSalePrice6,
							PreSalePrice7,
							PreSalePrice8,
							PreSalePrice9,
							PreSalePrice10,
							RetailPrice,
							TopSalePrice,
							LowSalePrice,
							TopBuyPrice,
							auxfullname1,
							auxfullname2,
							auxfullname3,
							auxrate1,
							auxrate2,	
							auxrate3,	
							CustomerCode,	
							isservice,	
							PriceType,	
							SReferPrice,	
							preferprice,	
							referprice,	
							ifusegoodsnum,	
							salemunitcode,	
							buymunitcode,
							stockmunitcode,	
							unitstype,	
							goodsnumber,	
							customitemid,	
							customitemfrom,	
							customitemname,
							customitemrefid,	
							itemid,	
							itemname,	
							iscombined,	
							ktypeid,	
							cargoid,	
							kfullname,	
							cargofullname,	
							munitrate,	
							curmsaleprice,									
							nsaleprice,	
							nprice,									
							curmdiscountprice,	
							curmtaxprice,									
							MUnitID,	
							NUnitID,	
							UnitID,	
							unit,	
							munit,	
							nunit,								
							NTaxPrice,	
							NDiscountPrice,	
							MSalePrice,	
							MDiscountPrice,	
							MTaxPrice,	
							serial1,	
							Price,								
							Discount,	
							DiscountPrice,								
							Tax,
							TaxPrice,								
							MxComment,								
							InCargoSpace,	
							OutCargoSpace,	
							dealtypeName,	
							ProduceDate,	
							ValidDate,	
							BillId,	
							Detailid,	
							BillType,								
							iscombination,									
							InOrOut,	
							efullnamecustom,	
							pfullnamecustom,
							bfullnamecustom,	
							dfullnamecustom,	
							kfullnamecustom,	
							sfullnamecustom,	
							brandartypeid,	
							brandarfullname
					ORDER BY UserCode 
							
					DROP TABLE #Result'  
else
	SET @sqlresult += ',SysDiy1,	
						SysDiy2,	
						SysDiy3,	
						SysDiy4,	
						SysDiy5,	
						SysDiy6,	
						SysDiy7,	
						SysDiy8,	
						SysDiy9,	
						SysDiy10,	
						SysDiy11,	
						SysDiy12,	
						SysDiy13,	
						SysDiy14,	
						SysDiy15,	
						SysDiy16,	
						SysDiy17,	
						SysDiy18,	
						SysDiy19,	
						SysDiy20,	
						SysDiy21,	
						SysDiy22,	
						SysDiy23,	
						SysDiy24,	
						SysDiy25,	
						SysDiy26,	
						SysDiy27,	
						SysDiy28,	
						SysDiy29,	
						SysDiy30,	
						SysDiy31,	
						SysDiy32,
						SysDiy33,	
						SysDiy34,	
						SysDiy35,	
						SysDiy36,	
						SysDiy37,	
						SysDiy38,	
						SysDiy39,	
						SysDiy40
					FROM	#Result'
  

--PRINT(@SQL+@SqlResult)
EXEC(@SQL+@SqlResult)			
			

DROP TABLE #BillIndex,#MxTable,#SplitBillNumberId

/*							
SysDiy1,	
SysDiy2,	
SysDiy3,	
SysDiy4,	
SysDiy5,	
SysDiy6,	
SysDiy7,	
SysDiy8,	
SysDiy9,	
SysDiy10,	
SysDiy11,	
SysDiy12,	
SysDiy13,	
SysDiy14,	
SysDiy15,	
SysDiy16,	
SysDiy17,	
SysDiy18,	
SysDiy19,	
SysDiy20,	
SysDiy21,	
SysDiy22,	
SysDiy23,	
SysDiy24,	
SysDiy25,	
SysDiy26,	
SysDiy27,	
SysDiy28,	
SysDiy29,	
SysDiy30,	
SysDiy31,	
SysDiy32,
SysDiy33,	
SysDiy34,	
SysDiy35,	
SysDiy36,	
SysDiy37,	
SysDiy38,	
SysDiy39,	
SysDiy40,
*/


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportPickBillToBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_ImportPickBillToBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：导入采购类单据到 上架单
*/

CREATE PROCEDURE Qp_ImportPickBillToBill
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@STypeId		VARCHAR(100)='',
	@Picker			VARCHAR(100)='',
	@KTypeId		VARCHAR(100)='',
	@CiteState		VARCHAR(20)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))


--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)
INSERT INTO #GetManBTypeId(TypeId)VALUES('')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)
INSERT INTO #GetManETypeId(TypeId)VALUES('')

CREATE TABLE #GetDetailTableBillNumberId(BillNumberId INT)

DECLARE @BillIndexTable VARCHAR(100),
		@SQL			VARCHAR(8000),
		@DetailBill		VARCHAR(100)	--记录明细表名
		
SET @BillIndexTable = 'onShelvespickIndex'

SELECT @DetailBill=detailtable FROM BILLNAME WHERE BillType=413
IF ISNULL(@DetailBill,'')<>''
BEGIN
	exec('INSERT INTO #GetDetailTableBillNumberId
		SELECT DISTINCT T.BillNumberId FROM '+@DetailBill+' T 
		INNER JOIN F_GetManPTypeAll('''+@OperatorId+''') P ON T.PtypeId=P.typeid')
END

SET @SQL = 'SELECT  B.BillNumberId,
					B.BillDate,
					B.BillCode,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,
					B.ETypeId,	
					ET.Fullname AS EFullname,
					B.DTypeId,
					B.STypeId,
					ST.Fullname AS SFullname,
					B.KTypeId,
					k.Fullname AS KFullname,
					B.TotalQty,
					B.Comment,
					413 as Billtype,
					CASE WHEN B.citestate=1 THEN ''已引用未完成'' WHEN B.citestate=2 THEN ''已完成'' WHEN B.citestate=0 THEN ''未引用'' END as citestate,'--0=未引用1=已引用未完成2=已完成
	SET @SQL = @SQL + 'B.Explain
					FROM '+@BillIndexTable+' B				
					LEFT JOIN Stock k ON B.KTypeID = k.typeid LEFT JOIN BillName BN on BN.Billtype = B.BillType
					INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId LEFT JOIN SType ST ON ST.Typeid= s.TypeId
					INNER JOIN #GetManETypeId ME ON ME.TypeId = B.ETypeId LEFT JOIN employee ET ON ET.Typeid= ME.TypeId
					INNER JOIN Employee E ON B.Checke=E.TypeId
				
					'
/*--会导致多张拣货单，left出来多张重复的出库单,用exists处理
SET @SQL=@SQL+' LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
				LEFT JOIN dbo.pickbill p ON B.billNumberId = p.billNumberID		
				LEFT JOIN dbo.BillIndex BI ON p.GoodsBillNumberID = BI.BillNumberId'
*/
SET @SQL=@SQL+' LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
				'


SET @SQL = @SQL + ' WHERE B.BillDate>='''+@StartDate+''' AND B.BillDate<='''+@EndDate+''' '
--需求里面没有说年结存转的单据不调用，所以去掉B.IfYearBill = 0
--SET @SQL = @SQL + ' AND B.IfYearBill = 0 AND B.RedWord = 0 AND 1 = 1'
SET @SQL = @SQL + ' AND B.RedWord = 0 AND 1 = 1'

IF @KTypeId !=''
	SET @SQL= @SQL +' AND B.ktypeid='+CHAR(39)+@KTypeId+CHAR(39)

IF @Picker!=''
	SET @SQL=@SQL+' AND B.etypeid='+CHAR(39)+@Picker+CHAR(39)

IF @CiteState !=9
	SET @SQL= @SQL +'AND B.citestate='+@CiteState

--会导致多张拣货单，left出来多张重复的出库单,用exists处理
--SET @SQL= @SQL +'AND B.citestate!=2 AND B.Draft=0 AND B.RedWord=0 AND BI.IsNeedTransport=1'

SET @SQL= @SQL +'AND B.citestate!=2 AND B.Draft=0 AND B.RedWord=0'
SET @SQL= @SQL +'AND EXISTS(
					SELECT BI.IsNeedTransport,p.GoodsBillNumberID FROM dbo.pickbill p
					LEFT JOIN dbo.BillIndex BI ON p.GoodsBillNumberID = BI.BillNumberId
					WHERE B.billNumberId = p.billNumberID AND BI.IsNeedTransport=1
					UNION ALL 
					SELECT BI.IsNeedTransport,p.GoodsBillNumberID FROM dbo.pickbill p
					INNER JOIN dbo.PosAllotApplyBillIndex BI ON p.GoodsBillNumberID = BI.BillNumberId
					WHERE B.billNumberId = p.billNumberID AND BI.IsNeedTransport=1
					)'
SET @SQL = @SQL +' AND B.billnumberid IN (SELECT * FROM #GetDetailTableBillNumberId) ORDER BY B.BillDate DESC,B.BillCode DESC'

--PRINT(@sql)
EXEC(@SQL)			
DROP TABLE #GetManKTypeId,#GetManBTypeId,#GetManSTypeId,#GetManETypeId,#GetDetailTableBillNumberId
							


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportPickBillToBillMxNew]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Qp_ImportPickBillToBillMxNew
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：导入拣货单据明细
*/
CREATE PROCEDURE Qp_ImportPickBillToBillMxNew
(
	@OperatorId		VARCHAR(100),
	@BillType		VARCHAR(100),
	@nBillIds		VARCHAR(8000)='',
	@isservice      VARCHAR(50)='',
	@IsIni			int=0,			   --1为期初单据，0为非期初单据
	@sale           VARCHAR(50)=''
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @BillIndexTable VARCHAR(100),
		@MxTableName	VARCHAR(100),
		@OutStockBill	VARCHAR(100),
		@SQL 			VARCHAR(8000)
		
CREATE TABLE #SplitBillNumberId
(
	BillNumberId		NUMERIC(18,0)
)	   
INSERT INTO #SplitBillNumberId(BillNumberId) SELECT A FROM dbo.f_split(@nBillIds,',') WHERE ISNULL(A,'')<>''

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T 
FROM custom_billdetails cbd 
INNER JOIN #SplitBillNumberId sbn ON cbd.BillId=sbn.billnumberid
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.billtype=@BillType

CREATE TABLE #BillIndex
(
	BillNumberId		NUMERIC(18,0),
	BillDate			VARCHAR(20),
	BillCode			VARCHAR(400),
	IsIni				bit,
	ifaudit				int,
	BillType			VARCHAR(20)
)		

CREATE TABLE #MxTable
(
	PTypeId			VARCHAR(100),
	Unit1			VARCHAR(100),
	Qty				 NUMERIC(24, 10) ,
	SalePrice		 NUMERIC(24, 10) ,
	SaleTotal		 NUMERIC(24, 10) ,
	Discount		 NUMERIC(24, 10) ,
	DiscountPrice	 NUMERIC(24, 10) ,
	DiscountTotal	 NUMERIC(24, 10) ,
	Tax				 NUMERIC(24, 10) ,
	TaxPrice		 NUMERIC(24, 10) ,
	TaxTotal		 NUMERIC(24, 10) ,	
	Comment			VARCHAR(400)
)
		
-------------------------------------主表-------------------------------------

SET @BillIndexTable = 'onShelvespickIndex'	

	
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.IsIni,
					B.ifaudit,B.BillType
			FROM	'+@BillIndexTable+' B INNER JOIN #SplitBillNumberId S ON B.BillNumberId = S.BillNumberId AND BillType = '+CHAR(39)+@BillType+CHAR(39)+''
SET @SQL = @SQL + ' AND B.IfCheck = ''t'' AND B.RedWord = 0 '
			
SET @SQL = @SQL + '					
			ORDER BY B.BillDate DESC,B.BillCode DESC '

--PRINT(@SQL)
EXEC(@SQL)

--（门店主表或单据主表）
CREATE TABLE #TempIndex 
(
	BillNumberId INT,
	BillCode VARCHAR(100),
	BillType VARCHAR(100),
	LinkMan VARCHAR(100),
	LinkTel VARCHAR(100),
	LinkAddr VARCHAR(100),
	IsNeedTransport INT
) 	
INSERT INTO #TempIndex
SELECT	DISTINCT A.BillNumberId ,
		A.BillCode,
		A.BillType,
		A.LinkMan,
		A.LinkTel,
		A.LinkAddr,
		A.IsNeedTransport
FROM dbo.BillIndex A 
INNER JOIN dbo.pickbill M ON A.BillNumberId = M.GoodsBillNumberID
INNER JOIN #BillIndex B ON M.billNumberID = B.BillNumberId
UNION 
SELECT  DISTINCT A.BillNumberId ,
		A.BillCode,
		A.BillType,
		A.LinkMan,
		A.LinkTel,
		A.LinkAddr,
		A.IsNeedTransport
FROM dbo.PosAllotApplyBillIndex A
INNER JOIN dbo.pickbill M ON A.BillNumberId = M.GoodsBillNumberID
INNER JOIN #BillIndex B ON M.billNumberID = B.BillNumberId


---------------------------------------明细表-------------------------------------


SET @MxTableName = 'pickbill'	
SET @SQL = 'SELECT	CASE DATALENGTH(M.Serial)
						WHEN 0
							THEN ''''
						ELSE
							SUBSTRING(M.Serial,(charindex(''я'',M.Serial)+2),charindex(''я'',M.Serial,charindex(''я'',M.Serial)+1)-1)+''...'' 
					END AS Serial1,
					M.Serial AS Serial,
					M.PTypeId,
					itemid=M.ItemId,
					M.IsCombined,
					itemname= CASE WHEN M.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) END,
					ISNULL((SELECT SUM(QTY) FROM Transportbill T INNER JOIN billindex BL ON T.billnumberid=BL.billnumberid 
						WHERE T.Goodsbillid=M.ID AND T.Ptypeid = M.Ptypeid AND ifcheck=''t'' AND redword=0),0) AS sendedqty,
					(M.Qty - ISNULL((SELECT SUM(QTY) FROM Transportbill T INNER JOIN billindex BL ON T.billnumberid=BL.billnumberid 
						WHERE T.Goodsbillid=M.ID AND T.Ptypeid = M.Ptypeid AND ifcheck=''t'' AND redword=0),0)) as uqty,
					
					(M.Qty - (SELECT sendedqty FROM F_GetBillDetails(M.Goodsbillid,m.ptypeid)))*ISNULL(PP.weight,0) as weight,
					(M.Qty - (SELECT sendedqty FROM F_GetBillDetails(M.Goodsbillid,m.ptypeid)))*ISNULL(PP.volume,0) as volume,
					P.*,
					P.Unit1 AS unitone,
					P.Unit2 As unittwo,
					M.GoodsNumber,
					M.Qty as cqty,
					I.BillCode as goodsbillcode,I.BillNumberId as saleBillnumberid,I.BillType as saleBilltype,
					I.LinkMan as LinkMan,I.LinkTel as LinkTel,I.LinkAddr as LinkAddr,
				    (select isservice from ptype where typeid = m.PTypeID) as isservice,
				    pp.ifusegoodsnum,B.Billcode as pickbillcode,B.BillNumberID as frombillnumberid,M.ID as frombillid,''413'' as frombilltype,
					 '
IF @sale = '1'				 
SET @SQL = @SQL + ' (select EntryCode from PType_Units_Ext where PtypeID=M.Ptypeid and UnitsId=p.SaleUnitId) AS salemunitcode,'
ELSE				 
SET @SQL = @SQL + ' (select EntryCode from PType_Units_Ext where PtypeID=M.Ptypeid and UnitsId=p.buyunitid) AS buymunitcode,'    

--查询自定义字段
SET @SQL = @SQL + 'ct.*'

SET @SQL = @SQL + '
			FROM	'+@MxTableName+'  M
			INNER JOIN #BillIndex B ON B.BillNumberId = M.BillNumberId
			LEFT JOIN #TempIndex I ON I.BillNumberId = M.GoodsBillNumberID
			INNER JOIN F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') P ON M.PTypeId = P.TypeId
			INNER JOIN Ptype pp ON pp.typeid=M.PTypeId
			 ' 
SET @SQL = @SQL + ' LEFT JOIN #Custom_T ct ON ct.Detailid=M.id '	

SET @SQL = @SQL + '	WHERE	P.Deleted = 0 AND I.IsNeedTransport=1 AND (M.Qty - ISNULL((SELECT SUM(QTY) FROM Transportbill T INNER JOIN billindex BL ON T.billnumberid=BL.billnumberid 
						WHERE T.Goodsbillid=M.ID AND T.Ptypeid = M.Ptypeid AND ifcheck=''t'' AND redword=0),0) > 0) '
			
IF @IsIni = 1 SET @SQL = @SQL + ' AND B.IsIni=1'	

IF @isservice <> 'true' AND @isservice <> 'True'  SET @SQL = @SQL + ' AND pp.isservice=0 '	

SET @SQL=@SQL+'ORDER BY M.BillNumberId ASC'

--PRINT(@SQL)
EXEC(@SQL)			
			

DROP TABLE #BillIndex,#MxTable,#SplitBillNumberId,#TempIndex

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportSaleBillDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Qp_ImportSaleBillDetails
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：导入销售单据明细
	EXEC Qp_ImportDataToBillMx '00001','0','301',''
*/
CREATE PROCEDURE Qp_ImportSaleBillDetails
(
	@OperatorId		VARCHAR(50),
	@DealBtypeId    VARCHAR(50)='',
	@KTypeId        VARCHAR(50)='',
	@Sale           VARCHAR(50)='',
	@STypeId        VARCHAR(50)='',
	@bill			Tb_ImportSaleBillDetails READONLY
	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------权限检查---------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------权限检查------------------------------------------------

--==========================================基础资料【BEGIN】==========================================
DECLARE @SQL VARCHAR(MAX)=''

--商品信息
CREATE TABLE #PType
(
	TypeId			VARCHAR(50),
	UserCode		VARCHAR(200),
	FullName		VARCHAR(200),
	IsService		INT,
	IfUseGoodsNum	BIT,
	IfSerial		INT,
	UnitOne			VARCHAR(200),
	UnitTwo			VARCHAR(200),
	AuxFullName1	VARCHAR(200),
	AuxFullName2	VARCHAR(200),
	AuxFullName3	VARCHAR(200),
	AuxRate1		NUMERIC(24,10),
	AuxRate2		NUMERIC(24,10),
	AuxRate3		NUMERIC(24,10),
	BuyUnitId		INT,
	SaleUnitId		INT,
	BaseUnitId		INT,
	EntryCode		VARCHAR(200)

) CREATE CLUSTERED INDEX #PType_P_K ON #PType(TypeId)
DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,'','')
SET @SQL='
	INSERT INTO #PType(
		TypeId,
		UserCode,
		FullName,
		IsService,
		IfUseGoodsNum,
		IfSerial,
		UnitOne,
		UnitTwo,
		AuxFullName1,
		AuxFullName2,
		AuxFullName3,
		AuxRate1,
		AuxRate2,
		AuxRate3,
		BuyUnitId,
		SaleUnitId,
		BaseUnitId,
		EntryCode
	)
	SELECT 
		P.TypeId,
		P.UserCode,
		P.FullName,
		P.IsService,
		P.IfUseGoodsNum,
		p.IfSerial,
		P.Unit1 UnitOne,
		P.Unit2 UnitTwo,
		PU1.FullName AuxFullName1,
		PU2.FullName AuxFullName2,
		PU3.FullName AuxFullName3,
		PE.SaleUnitRate1 AuxRate1,
		PE.SaleUnitRate2 AuxRate2,
		PE.SaleUnitRate3 AuxRate3,
		BuyUnitId,
		SaleUnitId,
		P.BaseUnitId,
		PUE.EntryCode
	'+@LinkStr+'
	LEFT JOIN PType_AuxiliaryUnits_Ext PE ON PE.PTypeID=P.TypeId
	LEFT JOIN PType_Units PU1 ON PU1.UnitsId=PE.SaleUnitID1
	LEFT JOIN PType_Units PU2 ON PU2.UnitsId=PE.SaleUnitID2
	LEFT JOIN PType_Units PU3 ON PU3.UnitsId=PE.SaleUnitID3
	LEFT JOIN PType_Units_Ext PUE ON PUE.PtypeID=P.TypeId AND PUE.UnitsId='+CASE WHEN @sale=1 THEN 'P.SaleUnitId' ELSE 'P.BuyUnitId' END+'
	WHERE 
		P.sonnum=0
		AND P.Deleted=0
		AND P.isservice=0'
EXEC(@SQL)

--库存信息
CREATE TABLE #GoodsStocks
(
	Qty		NUMERIC(24,10),
	PTypeId VARCHAR(50),
	KTypeId	VARCHAR(50)
) CREATE CLUSTERED INDEX #GoodsStocks_P_K ON #GoodsStocks(PTypeId,KTypeId)

INSERT INTO #GoodsStocks(
	Qty,
	PTypeId,
	KTypeId
)
SELECT 
	SUM(ISNULL(G.Qty,0)) Qty,
	G.PtypeId,
	G.KtypeId
FROM GoodsStocks G
INNER JOIN #PType P ON P.TypeId=G.PtypeId AND KtypeId=@KTypeId
GROUP BY 
	G.PtypeId,
	G.KtypeId
	
--主表选中的单据
CREATE TABLE #Bill
(
	BillNumberId NUMERIC(18,0),
	BillType	INT,
	BillCode	VARCHAR(200),
	BillName	VARCHAR(200)
)
CREATE CLUSTERED INDEX #Bill_P_K ON #Bill(BillNumberId)
INSERT INTO #Bill(BillNumberId,BillType,BillCode)
SELECT	DISTINCT	
		B.BillNumberId,
		B.BillType,
		B.BillCode
FROM @bill F 
INNER JOIN PosAllotApplyBillIndex B ON B.BillNumberId=F.billnumberid AND B.BillType = F.billtype
UNION ALL
SELECT DISTINCT
	B.BillNumberId,
	B.BillType,
	B.BillCode
FROM @bill F 
INNER JOIN BillIndex B ON B.BillNumberId=F.billnumberid AND B.BillType = F.billtype

--创建临时表，获取自定义字段
SELECT 
	cbd.BillId ,
    cbd.Detailid ,
    cbd.BillType AS Cbilltype,
    cbd.SysDiy1 ,
    cbd.SysDiy2 ,
    cbd.SysDiy3 ,
    cbd.SysDiy4 ,
    cbd.SysDiy5 ,
    cbd.SysDiy6 ,
    cbd.SysDiy7 ,
    cbd.SysDiy8 ,
    cbd.SysDiy9 ,
    cbd.SysDiy10 ,
    cbd.SysDiy11 ,
    cbd.SysDiy12 ,
    cbd.SysDiy13 ,
    cbd.SysDiy14 ,
    cbd.SysDiy15 ,
    cbd.SysDiy16 ,
    cbd.SysDiy17 ,
    cbd.SysDiy18 ,
    cbd.SysDiy19 ,
    cbd.SysDiy20 ,
    cbd.SysDiy21 ,
    cbd.SysDiy22 ,
    cbd.SysDiy23 ,
    cbd.SysDiy24 ,
    cbd.SysDiy25 ,
    cbd.SysDiy26 ,
    cbd.SysDiy27 ,
    cbd.SysDiy28 ,
    cbd.SysDiy29 ,
    cbd.SysDiy30 ,
    cbd.SysDiy31 ,
    cbd.SysDiy32 ,
    cbd.iscombination ,
    cbd.InOrOut ,
    cbd.SysDiy33 ,
    cbd.SysDiy34 ,
    cbd.SysDiy35 ,
    cbd.SysDiy36 ,
    cbd.SysDiy37 ,
    cbd.SysDiy38 ,
    cbd.SysDiy39 ,
    cbd.SysDiy40,
	E.FullName EFullNameCustom,
	p.FullName PFullNameCustom,
	b.FullName BFullNameCustom,
	d.FullName DFullNameCustom,
	k.FullName KFullNameCustom,
	s.FullName SFullNameCustom 
INTO #Custom_T 
FROM custom_billdetails cbd 
INNER JOIN #Bill sbn ON cbd.BillId=sbn.billnumberid AND sbn.BillType=cbd.BillType
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid

DECLARE 
	@IniRow			INT=1,
	@MaxRow			INT=0,
	@NowBillType	INT,--当前billtype
	@NowBTypeName	VARCHAR(200),--当前billtype
	@Details		VARCHAR(200),--明细表表名
	
	@PriceType		VARCHAR(5)--分支机构物价信息


--分支机构物价信息
IF ISNULL(@STypeId,'')=''
	BEGIN
		SET @PriceType='0'
		SET @STypeId=''
	END
ELSE 
	SELECT @PriceType=PriceType FROM SType WHERE TypeId=@STypeId
		
	
--当前当需要查询的单据类型
CREATE TABLE #BillType(NId INT IDENTITY(1,1),BillType INT)

INSERT INTO #BillType(BillType)
SELECT BillType FROM #Bill GROUP BY BillType
SELECT @MaxRow=@@ROWCOUNT


--==========================================基础资料【END】==========================================



--==========================================业务逻辑处理【BEGIN】==========================================
SET @SQL=''

CREATE TABLE #billdetail
(
	billnumberid	NUMERIC(18),
	detailid		INT,
	billtype		INT
)
INSERT INTO #billdetail( billnumberid, detailid,billtype )
SELECT	billNumberID,detailID,billtype
FROM @bill 

WHILE(@IniRow<=@MaxRow)
BEGIN
	IF(LEN(@SQL)>0) SET @SQL+='UNION ALL'+CHAR(13)
	
	SELECT @Details=detailTable,@NowBillType=B.Billtype,@NowBTypeName=B.BillName FROM BillName B INNER JOIN #BillType T ON T.NId=@IniRow AND T.BillType=B.Billtype
		
	SET @SQL+='
	SELECT
		CASE DATALENGTH(ISNULL(M.Serial,''''))
						WHEN 0
							THEN ''''
						ELSE
							(SELECT TOP 1 a FROM dbo.f_splitAN(Serial,''я'') WHERE ISNULL(a,'''')<>'''')+''...'' 
					END AS Serial1,
					(''я''+(SELECT DISTINCT stuff((select ''я'' + a from 
						(
							SELECT a FROM dbo.f_split(M.Serial,''я'') 
							WHERE a NOT IN (
							SELECT ISNULL(a,'''') FROM dbo.f_split(
							(
								select [Serial] = stuff((
									select ''я'' + cast([Serial] as varchar(4000)) from pickbill t 
									inner join onShelvespickIndex o on t.billnumberid=o.billnumberid and o.ifcheck=''t'' and o.redword=0
									where  t.GoodsBillID=m.id AND m.billnumberid=t.GoodsBillNumberID AND t.GoodsBillType=B.BillType for xml path('''')) , 1 , 1 , ''''
								)  
								from pickbill p INNER JOIN dbo.onShelvespickIndex i ON p.billNumberID = i.billNumberId 
								WHERE i.IfCheck=''t'' AND i.draft=0 AND i.RedWord=0 AND p.GoodsBillID=m.id AND m.billnumberid=p.GoodsBillNumberID AND p.GoodsBillType=B.BillType
								group by ptypeid ),''я'')
							)
						) b
						where a = a for xml path('''')),1,1,'''')
						FROM (SELECT a FROM dbo.f_split(M.Serial,''я'') 
						WHERE a NOT IN (
						SELECT ISNULL(a,'''') FROM dbo.f_split(
						(
							select [Serial] = stuff(
							(
								select ''я'' + cast([Serial] as varchar(4000)) from pickbill t 
								inner join onShelvespickIndex o on t.billnumberid=o.billnumberid and o.ifcheck=''t'' and o.redword=0
								where  t.GoodsBillID=m.id AND m.billnumberid=t.GoodsBillNumberID AND t.GoodsBillType=B.BillType for xml path('''')) , 1 , 1 , ''''
							)  
							from pickbill p INNER JOIN dbo.onShelvespickIndex i ON p.billNumberID = i.billNumberId 
							WHERE i.IfCheck=''t'' AND i.draft=0 AND i.RedWord=0 AND p.GoodsBillID=m.id AND m.billnumberid=p.GoodsBillNumberID AND p.GoodsBillType=B.BillType
							group by ptypeid ),''я''))
						) c
					)+''я'') AS Serial,
		M.PTypeId,
		M.PTypeId AS TYPEID,
		P.UserCode,
		P.FullName,
		P.UnitOne,
		P.UnitTwo,
		M.Qty,
		NULL OutCargoId,
		P.AuxFullName1,
		P.AuxFullName2,
		P.AuxFullName3,
		P.AuxRate1,
		P.AuxRate2,
		P.AuxRate3,
		P.IsService,
		P.IfUseGoodsNum,
		p.IfSerial,
		PC.UserCode CustomerCode,
		P.EntryCode '+CASE WHEN @sale=1 THEN 'SaleMUnitCode,' ELSE 'BuyMUnitCode,' END+''
		+@PriceType+' PriceType,	
		M.ItemId,
		CASE WHEN M.IsCombined=0 THEN (SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
			 ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) 
		END ItemName,
		M.IsCombined,'+CHAR(13)
		
--183	积分兑换单
IF(@NowBillType=183)
	BEGIN
		SET	@SQL+='
			0 PreferPrice,
			0 ReferPrice,
			0 SReferPrice,'+CHAR(13)
	END
ELSE 
	BEGIN
		SET @SQL+='
			PP.ReferPrice PreferPrice,
			PP.ReferPrice ReferPrice,
			ISNULL(PS.ReferPrice,0) SReferPrice,'+CHAR(13)
	END

IF (@NowBillType IN(11,12,160,140,6,161,146,401,402))
BEGIN
	SET @SQL+='
	M.curmsaleprice,
	M.mqty,
	M.nsaleprice,
	M.nsaleprice as nprice,
	CASE WHEN ISNULL(M.NUnitID,0) = 0 THEN NULL
	ELSE M.nqty END AS nqty,
	M.curmdiscountprice,
	M.curmtaxprice,
	M.ntaxmoney,
	M.ntaxtotal,
	M.taxmoney,
	M.MUnitID, 							
	M.NUnitID,
	M.UnitID,
    M.munitrate as munitrate,
	M.UnitRate,
	U.FullName AS munit,
	V.FullName AS nunit,						      
	M.nsaletotal,
	M.ntotal,
	M.NTaxPrice,
	M.NDiscountPrice,
	M.MSalePrice,
	M.MDiscountPrice,
	M.MTaxPrice,
	'
END
ELSE IF(@NowBillType IN(139))--139	赠送单
BEGIN
	SET @SQL+='
    0 as curmsaleprice,
    M.mqty as mqty,
    0 as nsaleprice,
    0 as nprice,
    M.nqty as nqty,
    0 as curmdiscountprice,
    0 as curmtaxprice,
	0 as ntaxmoney,
	0 as ntaxtotal,
	0 as taxmoney,
	M.MUnitID, 							
	M.NUnitID,
	M.UnitID,
    M.munitrate as munitrate,
    M.UnitRate as UnitRate,	
	U.FullName AS munit,
	V.FullName AS nunit,
    0 as nsaletotal,
    0 as ntotal,
	0 as NTaxPrice,
	0 as NDiscountPrice,
    0 as MSalePrice,
	0 as MDiscountPrice,
	0 as MTaxPrice,
	'
END
ELSE IF(@NowBillType IN(16))
BEGIN
	SET @SQL+='
    0 as curmsaleprice,
    M.mqty as mqty,
    0 as nsaleprice,
    0 as nprice,
    M.nqty as nqty,
    0 as curmdiscountprice,
    0 as curmtaxprice,
	0 as ntaxmoney,
	0 as ntaxtotal,
	0 as taxmoney,
	M.MUnitID, 							
	0 as NUnitID,
	gi.UnitID,
    M.munitrate as munitrate,
    M.UnitRate as UnitRate,	
	U.FullName AS munit,
	'''' AS nunit,
    0 as nsaletotal,
    0 as ntotal,
	0 as NTaxPrice,
	0 as NDiscountPrice,
    0 as MSalePrice,
	0 as MDiscountPrice,
	0 as MTaxPrice,
	'
END
ELSE IF(@NowBillType IN(17,21,187,202))
BEGIN
	SET @SQL+='
    0 as curmsaleprice,
    M.mqty as mqty,
    0 as nsaleprice,
    0 as nprice,
    M.nqty as nqty,
    0 as curmdiscountprice,
    0 as curmtaxprice,
	0 as ntaxmoney,
	0 as ntaxtotal,
	0 as taxmoney,
	M.MUnitID, 							
	M.NUnitID,
	M.UnitID,
    M.munitrate as munitrate,
    M.UnitRate as UnitRate,	
	U.FullName AS munit,
	V.FullName AS nunit,
    0 as nsaletotal,
    0 as ntotal,
	0 as NTaxPrice,
	0 as NDiscountPrice,
    0 as MSalePrice,
	0 as MDiscountPrice,
	0 as MTaxPrice,
	'
END 
ELSE IF (@NowBillType = 183)
BEGIN
	SET @SQL+='
    0 as curmsaleprice,
    M.qty as mqty,
    0 as nsaleprice,
    0 as nprice,
    M.nqty as nqty,
    0 as curmdiscountprice,
    0 as curmtaxprice,
	0 as ntaxmoney,
	0 as ntaxtotal,
	0 as taxmoney,
	P.BaseUnitId AS MUnitID, 							
	0 AS NUnitID,
	P.BaseUnitId AS UnitID,
    1 as munitrate,
    M.UnitRate as UnitRate,	
	U.FullName AS munit,
	'''' AS nunit,
    0 as nsaletotal,
    0 as ntotal,
	0 as NTaxPrice,
	0 as NDiscountPrice,
    0 as MSalePrice,
	0 as MDiscountPrice,
	0 as MTaxPrice,
	'
END
ELSE IF @NowBillType IN (327,328,329) --门店类
BEGIN
	SET @SQL+='
    0 as curmsaleprice,
    M.mqty as mqty,
    0 as nsaleprice,
    0 as nprice,
    M.nqty as nqty,
    0 as curmdiscountprice,
    0 as curmtaxprice,
	0 as ntaxmoney,
	0 as ntaxtotal,
	0 as taxmoney,
	M.MUnitID AS MUnitID, 							
	0 AS NUnitID,
	P.BaseUnitId AS UnitID,
    MUnitRate as munitrate,
    1 as UnitRate,	
	U.FullName AS munit,
	'''' AS nunit,
    0 as nsaletotal,
    0 as ntotal,
	0 as NTaxPrice,
	0 as NDiscountPrice,
    0 as MSalePrice,
	0 as MDiscountPrice,
	0 as MTaxPrice,
	'
END
ELSE 
BEGIN
	SET @SQL+='
    0 as curmsaleprice,
    0 as mqty,
    0 as nsaleprice,
    0 as nprice,
    0 as nqty,
    0 as curmdiscountprice,
    0 as curmtaxprice,
	0 as ntaxmoney,
	0 as ntaxtotal,
	0 as taxmoney,
	0 as MUnitID, 							
	0 as NUnitID,
	0 as UnitID,
    1 as munitrate,
    1 as UnitRate,
	'''' AS munit,
	'''' AS nunit,
    0 as nsaletotal,
    0 as ntotal,
	0 as NTaxPrice,
	0 as NDiscountPrice,
    0 as MSalePrice,
	0 as MDiscountPrice,
	0 as MTaxPrice,
	'
END

IF @NowBillType=16--生产拆装单
	SET @SQL+='GI.unit,'+CHAR(13)
ELSE IF(@NowBillType=183)
	SET @SQL+='U.FullName Unit,'+CHAR(13)
ELSE IF (@NowBillType IN(11,12,160,140,6,161,146,401,402,187,17,21,139,202))
	SET @sql+= 'W.fullname AS unit,'+CHAR(13)
ELSE
	SET @sql += ''''' AS unit,'+CHAR(13)

--拣货关联字段
IF @NowBillType IN (327,328,329)
SET @SQL += ' ktypeidout KTypeID, '
ELSE 
SET @SQL+='	M.KTypeID, '

SET @SQL+='	
	ISNULL(M.PickedQty,0) AS CQty,
	M.Qty-ISNULL(M.PickedQty,0) AS UQty,
	Ca.PathNo,
	Ca.FullName CFullname,
	Ca.CargoID,
	Ca.UserCode CarGoUserCode,
	Ca.fullname CarGoFullName,
	S.FullName KFullName,
	B.BillNumberId FromBillNumberId,
	M.ID AS FromBillId,
	B.BillCode,
	B.Billtype,
	'''+@NowBTypeName+''' BillName,
	M.comment BillComment,
	M.Qty BillQty,
	M.GoodsNumber,
	ct.*
FROM #Bill B
INNER JOIN #billdetail F ON F.BillNumberId=B.BillNumberId AND F.billtype = b.billtype
INNER JOIN '+@Details+' M ON M.BillNumberId=F.BillNumberId AND M.ID = F.detailID
INNER JOIN #PType P ON P.TypeId=M.PtypeId'

IF @NowBillType IN (327,328,329)
SET @SQL += ' INNER JOIN stock S ON S.typeid=M.ktypeidout '
ELSE 
SET @SQL += ' INNER JOIN stock S ON S.typeid=M.KTypeID '

SET @SQL +='LEFT JOIN #Custom_T ct ON ct.BillId=M.BillNumberId AND ct.cbilltype = b.billtype'+CASE WHEN @NowBillType = 12 THEN ' and ct.InOrOut = ''0''' ELSE '' END + ' and ct.Detailid='+CASE WHEN @Details='OrderBill' THEN 'm.orderid' ELSE 'M.id' END+'
LEFT JOIN CargoType Ca ON Ca.CargoID='+CASE WHEN @NowBillType IN(17,21,187) THEN 'M.OutCargoID' WHEN @NowBillType IN(327,328,329) THEN 'M.CargoIDOut' ELSE 'M.CargoID' END+'
LEFT JOIN #GoodsStocks G ON G.PTypeId=P.TypeId
LEFT JOIN PuserCode PC ON M.PtypeId=PC.Ptypeid AND PC.btypeid='''+@DealBtypeId+'''
LEFT JOIN PType_Units PU ON PU.UnitsId=P.BaseUnitId'+CHAR(13)
	
--183	积分兑换单
IF(@NowBillType<>183)
BEGIN
	SET @SQL+='
		LEFT JOIN PType_Price PP ON PP.PTypeID=M.PTypeID AND PP.UnitID =M.MUnitID
		LEFT JOIN PType_StypePrice PS ON '
	IF @NowBillType IN (327,328,329)
	SET @SQL += ' PS.Stypeid=(select stypeid from PosAllotApplyBillIndex where billnumberid = M.billnumberid) AND PS.PTypeID=M.PTypeID AND PS.UnitID=M.MUnitID'+CHAR(13)
	ELSE 
	SET @SQL += ' PS.Stypeid=M.Stypeid AND PS.PTypeID=M.PTypeID AND PS.UnitID=M.MUnitID'+CHAR(13)
END

--11销售出库单;160销售换货单;139赠送单;140委托代销发货单;12组合品销售出库单;6采购退货单;161采购换货单;146受托代销退货单;17同价调拨单;21变价调拨单;187分支机构调拨出库单;202其他出库单;401暂估退货单;402发出商品出库单;327门店配送单;
IF @NowBillType IN (11,12,160,139,140,6,161,146,17,21,187,202,401,402,327,328,329)
SET @SQL+='
LEFT JOIN dbo.PType_Units U ON U.UnitsId=M.MUnitID
LEFT JOIN dbo.PType_Units V ON V.UnitsId=M.NUnitID
LEFT JOIN dbo.PType_Units W ON W.UnitsId=M.UnitID'+CHAR(13)

--16生产拆装单
IF @NowBillType=16
	SET @SQL+='LEFT JOIN dbo.F_GetPtypeUnitInfo() GI ON GI.typeId=M.PTypeId
	LEFT JOIN dbo.PType_Units U ON U.UnitsId=M.MUnitID'+CHAR(13)
	
--183积分兑换单
IF @NowBillType=183
	SET @SQL+='LEFT JOIN PType_Units U ON U.UnitsId=P.BaseUnitId'+CHAR(13)	
	
SET @SQL+='
WHERE
	M.QTY-M.PickedQty > 0
	AND B.billtype = '+CAST(@NowBillType AS VARCHAR)+CHAR(13)
    
--请购单
IF(@NowBillType=204)
	SET @SQL+='	AND M.state<=8'	
		
--160	销售换货单
--161	采购换货单
--16	生产拆装单	
IF @NowBillType IN(160,161,16)
	SET @SQL+='	AND M.InOrOut=''O'''

	SET @IniRow+=1
END
--==========================================业务逻辑处理【END】==========================================



--==========================================执行结果并删除临时表【BEGIN】==========================================
IF(LEN(@SQL)>0)
	BEGIN
		SET @SQL='
			SELECT * FROM (
			'+@SQL+'
			) F
			ORDER BY 
				PathNo,
				FromBillNumberId,--BillNumberId
				FromBillId--ID
		'
	END
	
EXEC(@SQL)

--删除临时表
DROP TABLE #Bill,#BillType,#Custom_T,#GoodsStocks,#PType,#billdetail

--==========================================执行结果并删除临时表【END】==========================================
				
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Qp_ImportSaleBillToBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Qp_ImportSaleBillToBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：导入销售类单据到 拣货单
*/

CREATE PROCEDURE Qp_ImportSaleBillToBill
(
	@OperatorId		VARCHAR(50),
	@STypeId		VARCHAR(50)='',--分支机构
	@KTypeId		VARCHAR(50)='',--出库仓库
	@StartDate		VARCHAR(20),--单据时间从
	@EndDate		VARCHAR(20),--到
	@Explain		VARCHAR(1000)='',--说明
	@Comment		VARCHAR(1000)='',--摘要
	@BillType		VARCHAR(MAX),--出库单类型
	@CiteState		VARCHAR(20),--出库单状态
	@AreaTypeId		VARCHAR(50)='',--地区
	@IsNeedTransport VARCHAR(20)='9',--是否自提
	@DealBtypeId    VARCHAR(50)='',--往来单位
	@BtypeId		VARCHAR(50)='',--结算单位
	@EtypeId        VARCHAR(MAX)='',--经手人
	@DtypeId        VARCHAR(50)=''--部门
	
)
--@encode$--
AS
SET NOCOUNT ON
-----------------------------------------------------权限检查---------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
-----------------------------------------------------权限检查---------------------------------------------



--==========================================基础资料【BEGIN】==========================================
--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
INSERT INTO #Stype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) F 
INNER JOIN SType D ON D.TypeId=F.TypeId

--职员
CREATE TABLE #Etype(TypeId VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
INSERT INTO #Etype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID) F
INNER JOIN employee D ON D.typeId=F.TypeId
UNION ALL
SELECT '' TypeId,'' FullName

--部门
CREATE TABLE #Dtype(TypeId VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
INSERT INTO #Dtype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@DtypeId,9,@OperatorID) F
INNER JOIN Department D ON D.typeId=F.TypeId
UNION ALL
SELECT '' TypeId,'' FullName
	
--地区	
CREATE TABLE #Area(TypeId VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Area(TypeId)
IF ISNULL(@AreaTypeId,'')<>''
	BEGIN
		INSERT INTO #Area(TypeID) 
		SELECT F.TypeId FROM F_GetManDetailBType(@OperatorId) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND B.AreaTypeID=@AreaTypeId
		UNION ALL
		SELECT '' TypeId
	END
	
--往来单位
CREATE TABLE #DealBtype(TypeID VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #DealBtype_P_K ON #DealBtype(TypeId)
INSERT INTO #DealBtype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId) F
INNER JOIN btype D ON D.typeId=F.TypeId
IF(ISNULL(@DealBTypeId,'')='')
	INSERT INTO #DealBtype(TypeID,FullName) VALUES( '','')
	
--结算单位
CREATE TABLE #Btype(TypeID VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
INSERT INTO #Btype(TypeID,FullName) 
SELECT 
	F.TypeId,
	D.FullName
FROM F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorId) F
INNER JOIN btype D ON D.typeId=F.TypeId
IF(ISNULL(@BtypeId,'')='')
	INSERT INTO #Btype(TypeID,FullName) VALUES( '','')


DECLARE 
	@SQL		VARCHAR(MAX),
	@DetailBillType	VARCHAR(50)='',
	@DetailTable	VARCHAR(500)='',
	@IniRow	INT=1,
	@MaxRow	INT=0,
	@LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,'','')--商品

--商品
CREATE TABLE #Ptype(TypeId VARCHAR(50)) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)	
SET @SQL='
INSERT INTO #Ptype(TypeId)
SELECT P.typeId '+@LinkStr+' WHERE P.sonnum=0 AND P.IsService=0'
EXEC(@SQL)

--具体的单据类型
CREATE TABLE #BillName(NId INT IDENTITY(1,1),BillType INT,DetailTable VARCHAR(500))
SET @SQL='
INSERT INTO #BillName(BillType,DetailTable)
SELECT BillType,DetailTable FROM BillName WHERE BillType IN('+@BillType+')'
EXEC(@SQL)
SELECT @MaxRow=@@ROWCOUNT

--明细表
CREATE TABLE #DetailBill(BillNumberId INT,BillType INT) 
CREATE CLUSTERED INDEX #DetailBill_P_K ON #DetailBill(BillNumberId)	

SET @SQL=''
WHILE(@IniRow<=@MaxRow)
	BEGIN
		IF(LEN(@SQL)>1)
			SET @SQL+='UNION ALL'+CHAR(13)
			
		SELECT @DetailBillType=BillType,@DetailTable=DetailTable FROM #BillName WHERE NId=@IniRow
		
		SET @SQL+='SELECT DISTINCT '+@DetailBillType+' BillType ,B.BillNumberId
		FROM '+@DetailTable+' B 
		INNER JOIN #Ptype P ON P.TypeId=B.PTypeId ' +CHAR(13)
		
		IF ISNULL(@KTypeId,'')<>''
		BEGIN
			IF @DetailBillType IN ('327')
				SET @SQL+=' AND B.ktypeidout='''+@KTypeId+''''+CHAR(13)
			ELSE
				SET @SQL+=' AND B.ktypeid='''+@KTypeId+''''+CHAR(13)
		END
		
		IF  @DetailBillType IN(160,161,16)
			SET @SQL+=' AND B.InOrOut=''O'''
		SET @IniRow+=1
	END	
	
	SET @SQL='
INSERT INTO #DetailBill(BillType,BillNumberId)
SELECT BillType,BillNumberId FROM('+@SQL+') F GROUP BY BillType,BillNumberId'
--PRINT(@SQL)
EXEC(@SQL)	
	
--门店类状态表
CREATE TABLE #DeliveryState (BillNumberId INT,CiteState INT) 	
INSERT INTO #DeliveryState
SELECT	BillNumberId,
		CASE WHEN qty > pqty THEN 1 ELSE 2 END CiteState
FROM	(
			SELECT pa.Qty qty,SUM(pk.qty) pqty,pa.BillNumberId  FROM PosAllotApplyBillIndex pa
			INNER JOIN  pickbill pk ON GoodsBillNumberID = pa.BillNumberId
			INNER JOIN dbo.onShelvespickIndex obi ON obi.BillNumberId = pk.BillNumberId
			WHERE pa.BillType IN (SELECT * FROM dbo.f_split(@BillType,',') ) AND obi.RedWord=0
			GROUP BY pa.BillNumberId,pa.Qty
		)T

--==========================================基础资料【END】==========================================

--==========================================业务逻辑处理【BEGIN】==========================================
SET @SQL = '
SELECT	B.BillNumberId,
		B.BillDate,
		B.BillCode,
		B.BillType,
		CASE 
			WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
			WHEN B.IsIni=1 THEN ''期初单据''
			WHEN B.Ifcheck=''t'' THEN ''已过账'' 
			WHEN AT.IfAudit is null THEN ''原始单据''
			WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
			WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
			WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
			WHEN AT.IfAudit=''2'' THEN ''原始草稿''
		END AS BillStatus,
		BN.BillName,
		B.ETypeId,	
		B_E.Fullname EFullname,
		B.dealbtypeid BtypeId,
		B_B1.FullName BTypeName,
		B.btypeid btypeid1,
		B.DTypeId,
		B_D.Fullname DFullname,
		B.STypeId,
		B_S.Fullname SFullname,
		B.KTypeId,
		K.Fullname KFullname,
		B.TotalQty,
		B.TotalMoney,
		B.Comment,
		CASE WHEN B.CID=0 THEN (SELECT TOP 1 CId FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END Cid,
		CASE 
			WHEN B.CID=0 THEN (SELECT TOP 1 UserCode FROM Ac_Currency WHERE Sysrow=1)
			ELSE C.UserCode
		END  UserCode,
		CASE 
			WHEN B.CID=0 THEN (SELECT TOP 1 FullName FROM Ac_Currency WHERE Sysrow=1)
			ELSE C.FullName
		END FullName,
		B.rate,
		C.Sysrow,
		CASE 
			WHEN B.citestate=1 THEN ''已引用未完成'' 
			WHEN B.citestate=2 THEN ''已完成'' 
			ELSE ''未引用'' 
		END CiteState,
		B.Explain			
FROM (
		SELECT	BillNumberId,
				BillDate,
				BillCode,
				BillType,
				RedWord,
				IsIni,
				IfCheck,
				ETypeId,
				dealbtypeid,
				STypeId,
				KTypeId,
				TotalQty,
				TotalInMoney,
				Comment,
				Cid,
				rate,
				ShelveRefState,
				Explain,
				IfYearBill,
				DTypeId,
				BTypeId,
				TotalMoney,
				citestate,
				IsNeedTransport
		FROM	BillIndex 
		WHERE	BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
				AND BillType IN ('+@BillType+')
				AND RedWord = 0
		UNION ALL
		SELECT	PA.BillNumberId,
				BillDate,
				BillCode,
				BillType,
				RedWord,
				IsIni,
				IfCheck,
				ApplyETypeId,
				'''' AS dealbtypeid,
				STypeId,
				KTypeId,
				Qty,
				0 AS TotalInMoney,
				Comment,
				Cid,
				1 AS rate,
				0 AS ShelveRefState,
				Explain,
				0 AS IfYearBill,
				DTypeId,
				'''' AS BTypeId,
				0 AS TotalMoney,
				ISNULL(DS.CiteState,0) AS citestate,
				IsNeedTransport
		FROM	PosAllotApplyBillIndex PA
		LEFT	JOIN #DeliveryState DS ON PA.BillNumberId = DS.BillNumberId
		WHERE	BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
				AND BillType IN ('+@BillType+')
				AND RedWord = 0
)B
INNER JOIN #DetailBill D ON D.BillNumberId=B.BillNumberId AND D.BillType=B.BillType
INNER JOIN BillName BN ON BN.Billtype=B.BillType AND B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' AND B.IsIni!=1  AND B.RedWord=0
INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid
INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId 
INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid
INNER JOIN #DealBtype B_B1 ON B_B1.TypeID=B.DealBTypeID
INNER JOIN #Btype B_B ON B_B.TypeID=B.BTypeID
LEFT JOIN Ac_Currency C ON C.CId=B.CID
LEFT JOIN Stock K ON B.KTypeID=K.TypeId'+CHAR(13)

--地区
IF(ISNULL(@AreaTypeId,'')<>'')
	SET @SQL+='INNER JOIN #Area B_Ar ON B_Ar.TypeID=B.BTypeID'+CHAR(13)
		
--140委托代销发货单 146受托代销退货单
IF CHARINDEX('140',@BillType)>0 OR CHARINDEX('146',@BillType)>0
	SET @SQL+='LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=4'+CHAR(13)
ELSE
	SET @SQL+='LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2'+CHAR(13)

SET @SQL+='
WHERE
	((B.IsIni=0 AND B.ifYearBill=0 AND B.citestate<>2  AND  B.ifcheck=''t'') 
		OR (B.IsIni=1 AND B.ifYearBill=1 AND B.citestate<>2  AND  B.ifcheck=''t'') 
		OR (B.IsIni=1 AND B.ifYearBill=0 AND B.citestate<>2)
	) '+CHAR(13)
		
--出库单状态				
IF @CiteState!=9
	SET @SQL+='AND B.citestate='+@CiteState +CHAR(13)
	
--摘要
IF(ISNULL(@Comment,'')<>'')
	SET @SQL+=' AND B.Comment LIKE ''%'+@Comment+'%'''+CHAR(13)
	
--说明
IF(ISNULL(@Explain,'')<>'')
	SET @SQL+=' AND B.explain LIKE ''%'+@Explain+'%'''+CHAR(13)

--是否自提
IF @IsNeedTransport <>'9'
	SET @SQL+='AND B.IsNeedTransport='+@IsNeedTransport+CHAR(13)
	
--排序
SET @SQL+='ORDER BY B.BillDate,B.BillCode DESC'+CHAR(13)

--==========================================业务逻辑处理【END】==========================================



--==========================================执行结果并删除临时表【BEGIN】==========================================

--PRINT @SQL
EXEC(@SQL)		
	
DROP TABLE #DeliveryState,#Stype,#Area,#BillName,#Btype,#DealBtype,#DetailBill,#Dtype,#Etype,#Ptype


--==========================================执行结果并删除临时表【END】==========================================
							


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Qp_ImportSaleBillToBillMxNew]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Qp_ImportSaleBillToBillMxNew
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述：导入销售单据明细
	EXEC Qp_ImportDataToBillMx '00001','0','301',''
*/
CREATE PROCEDURE Qp_ImportSaleBillToBillMxNew
(
	@OperatorId		VARCHAR(100),
	@IsDraft		VARCHAR(100),
	@BillType		VARCHAR(500),
	@nBillIds		VARCHAR(MAX)='',
	@DealBtypeId    VARCHAR(50)='',
	@KTypeId        VARCHAR(50)='',
	@IsService      VARCHAR(50)='',
	@IsIni			int=0,			   --1为期初单据，0为非期初单据
	@Sale           VARCHAR(50)='',
	@STypeId        VARCHAR(50)='',
	@BillCodes		VARCHAR(MAX)='' --单据编号
	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------权限检查---------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------权限检查------------------------------------------------

--==========================================基础资料【BEGIN】==========================================
DECLARE @SQL VARCHAR(MAX)=''

--商品信息
CREATE TABLE #PType
(
	TypeId			VARCHAR(50),
	UserCode		VARCHAR(200),
	FullName		VARCHAR(200),
	BaseUnitId		INT

) CREATE CLUSTERED INDEX #PType_P_K ON #PType(TypeId)
DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,'','')
SET @SQL='
	INSERT INTO #PType(
		TypeId,
		UserCode,
		FullName,
		BaseUnitId
	)
	SELECT 
		P.TypeId,
		P.UserCode,
		P.FullName,
		P.BaseUnitId
	'+@LinkStr+'
	WHERE 
		P.sonnum=0
		AND P.Deleted=0
		AND P.isservice=0'
EXEC(@SQL)

--主表选中的单据
CREATE TABLE #Bill
(
	BillNumberId NUMERIC(18,0),
	BillType	INT,
	BillCode	VARCHAR(200),
	BillName	VARCHAR(200)
)
CREATE CLUSTERED INDEX #Bill_P_K ON #Bill(BillNumberId)
SET @SQL='
INSERT INTO #Bill(BillNumberId,BillType,BillCode)
SELECT	DISTINCT B.BillNumberId,
		B.BillType,
		B.BillCode
FROM f_split('''+@nBillIds+''','','') F 
INNER JOIN PosAllotApplyBillIndex B ON B.BillNumberId=F.a AND B.StypeID='''+@STypeId+'''
INNER JOIN f_split('''+@BillType+''','','') BT ON B.BillType = BT.a
INNER JOIN f_split('''+@BillCodes+''','','') BC ON B.BillCode = BC.a
UNION ALL
SELECT
	DISTINCT B.BillNumberId,
	B.BillType,
	B.BillCode
FROM f_split('''+@nBillIds+''','','') F 
INNER JOIN BillIndex B ON B.BillNumberId=F.a AND B.StypeID='''+@STypeId+'''
INNER JOIN f_split('''+@BillType+''','','') BT ON B.BillType = BT.a
INNER JOIN f_split('''+@BillCodes+''','','') BC ON B.BillCode = BC.a
WHERE
	(
		(B.IsIni=0 AND B.ifYearBill=0 AND B.citestate<>2 AND  B.ifcheck=''t'') 
		OR (B.IsIni=1 AND B.ifYearBill=1 AND B.citestate<>2 AND  B.ifcheck=''t'')  
		OR (B.IsIni=1 AND B.ifYearBill=0 AND B.citestate<>2)
	)'

IF @IsDraft = 0 
	SET @SQL+='	AND B.IfCheck=''t'' AND B.RedWord=0'+CHAR(13)
ELSE IF @IsDraft =1
	SET @SQL+='	AND B.IfCheck=''f'' AND B.Draft=1'+CHAR(13)
	
IF(@IsIni=1)
	SET @SQL+='AND B.IsIni=1'

EXEC(@SQL)
	
DECLARE 
	@IniRow			INT=1,
	@MaxRow			INT=0,
	@NowBillType	INT,--当前billtype
	@NowBTypeName	VARCHAR(200),--当前billtype
	@Details		VARCHAR(200)--明细表表名
	
	
--当前当需要查询的单据类型
CREATE TABLE #BillType(NId INT IDENTITY(1,1),BillType INT)

INSERT INTO #BillType(BillType)
SELECT BillType FROM #Bill GROUP BY BillType
SELECT @MaxRow=@@ROWCOUNT

--==========================================基础资料【END】==========================================



--==========================================业务逻辑处理【BEGIN】==========================================
SET @SQL=''
WHILE(@IniRow<=@MaxRow)
BEGIN
	IF(LEN(@SQL)>0) SET @SQL+='UNION ALL'+CHAR(13)
	
	SELECT @Details=detailTable,@NowBillType=B.Billtype,@NowBTypeName=B.BillName FROM BillName B INNER JOIN #BillType T ON T.NId=@IniRow AND T.BillType=B.Billtype

	SET @SQL+='
	SELECT	CASE DATALENGTH(ISNULL(M.Serial,''''))
				WHEN 0
					THEN ''''
				ELSE
					(SELECT TOP 1 a FROM dbo.f_splitAN(Serial,''я'') WHERE ISNULL(a,'''')<>'''')+''...'' 
			END AS Serial1,
			(''я''+(SELECT DISTINCT stuff((select ''я'' + a from 
				(
					SELECT a FROM dbo.f_split(M.Serial,''я'') 
					WHERE a NOT IN (
					SELECT ISNULL(a,'''') FROM dbo.f_split(
					(
						select [Serial] = stuff((
							select ''я'' + cast([Serial] as varchar(4000)) from pickbill t 
							inner join onShelvespickIndex o on t.billnumberid=o.billnumberid and o.ifcheck=''t'' and o.redword=0
							where  t.GoodsBillID=m.id AND m.billnumberid=t.GoodsBillNumberID AND t.GoodsBillType=B.BillType for xml path('''')) , 1 , 1 , ''''
						)  
						from pickbill p INNER JOIN dbo.onShelvespickIndex i ON p.billNumberID = i.billNumberId 
						WHERE i.IfCheck=''t'' AND i.draft=0 AND i.RedWord=0 AND p.GoodsBillID=m.id AND m.billnumberid=p.GoodsBillNumberID AND p.GoodsBillType=B.BillType
						group by ptypeid ),''я'')
					)
				) b
				where a = a for xml path('''')),1,1,'''')
				FROM (SELECT a FROM dbo.f_split(M.Serial,''я'') 
				WHERE a NOT IN (
				SELECT ISNULL(a,'''') FROM dbo.f_split(
				(
					select [Serial] = stuff(
					(
						select ''я'' + cast([Serial] as varchar(4000)) from pickbill t 
						inner join onShelvespickIndex o on t.billnumberid=o.billnumberid and o.ifcheck=''t'' and o.redword=0
						where  t.GoodsBillID=m.id AND m.billnumberid=t.GoodsBillNumberID AND t.GoodsBillType=B.BillType for xml path('''')) , 1 , 1 , ''''
					)  
					from pickbill p INNER JOIN dbo.onShelvespickIndex i ON p.billNumberID = i.billNumberId 
					WHERE i.IfCheck=''t'' AND i.draft=0 AND i.RedWord=0 AND p.GoodsBillID=m.id AND m.billnumberid=p.GoodsBillNumberID AND p.GoodsBillType=B.BillType
					group by ptypeid ),''я''))
				) c
			)+''я'') AS Serial,
			B.BillNumberId,
			M.ID,
			B.Billtype,
			B.BillCode,
			'''+@NowBTypeName+''' BillName,
			M.PTypeId,
			P.UserCode,
			P.FullName,
			M.GoodsNumber,
			CASE WHEN M.IsCombined=0 THEN (SELECT FullName FROM xw_SelfData WHERE _Id= M.ItemId)
				 ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= M.ItemId ) 
			END ItemName,
			'+CASE WHEN  @NowBillType=16 THEN 'U.unit' ELSE 'U.FullName' END +' AS Unit,M.Qty,
			ISNULL(M.PickedQty,0) AS CQty,
			M.Qty-ISNULL(M.PickedQty,0) AS UQty'
			
SET @SQL += '
	FROM	#Bill B
	INNER JOIN '+@Details+' M ON M.BillNumberId=B.BillNumberId AND B.BillType='+CAST(@NowBillType AS VARCHAR(5))+'
	INNER JOIN #PType P ON P.TypeId=M.PtypeId'+CHAR(13)
		
	IF @NowBillType=16--16生产拆装单
		SET @SQL+='LEFT JOIN dbo.F_GetPtypeUnitInfo() U ON U.typeId=M.PTypeId'+CHAR(13)
	ELSE IF @NowBillType=183--183积分兑换单
		SET @SQL+='LEFT JOIN PType_Units U ON U.UnitsId=P.BaseUnitId'+CHAR(13)
	ELSE 
		SET @SQL+='LEFT JOIN dbo.PType_Units U ON U.UnitsId=M.UnitID'

	SET @SQL+='
	WHERE	M.Qty>ISNULL(M.PickedQty,0)'+CHAR(13)
	    
	 IF(ISNULL(@KTypeId,'')<>'')
	 BEGIN
		IF @NowBillType IN (327,328,329)
		BEGIN
			IF @NowBillType IN (327)
				SET @SQL+='	AND M.KTypeIDOut='''+@KTypeId+''''+CHAR(13)
			ELSE
				SET @SQL+='	AND M.InKTypeID='''+@KTypeId+''''+CHAR(13)
		END	 
		ELSE
		BEGIN
			SET @SQL+='	AND M.KTypeId='''+@KTypeId+''''+CHAR(13)
		END
	 END
	  
	--请购单
	IF(@NowBillType=204)
		SET @SQL+='	AND M.state<=8'	+CHAR(13)
			
	--160	销售换货单
	--161	采购换货单
	--16	生产拆装单	
	IF @NowBillType IN(160,161,16)
		SET @SQL+='	AND M.InOrOut=''O'''+CHAR(13)

	SET @IniRow+=1
END
--==========================================业务逻辑处理【END】==========================================



--==========================================执行结果并删除临时表【BEGIN】==========================================
IF(LEN(@SQL)>0)
	BEGIN
		SET @SQL='
			SELECT * FROM (
			'+@SQL+'
			) F
			ORDER BY 
				BillNumberId,
				ID
		'
	END
	
--print @sql
EXEC(@SQL)

--删除临时表
DROP TABLE #Bill,#BillType,#PType

--==========================================执行结果并删除临时表【END】==========================================
				
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_nInsertVipCardSign]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_nInsertVipCardSign]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	描述:新增修改Vip卡发卡的信息
	作者:徐辉
	日期:2010-08-02
*/

/*
	描述:CzyeMoney的新增
	作者:覃雨翔
	日期:2011-08-18
*/
CREATE               PROCEDURE QP_nInsertVipCardSign
(
	@OperatorID		    varchar(100),	--超作员的ID
	@Action				varchar(100),	--动作	Add-新增   Modify-修改
	@VipCardId			int,
	@VipCardCode		varchar(100),	--Vip卡卡号
	@Bname				varchar(600),
	@pycode				varchar(600),
	@CreateDate			datetime,
	@EndDate			datetime,
	@EtypeId			varchar(600),
	@Cardset			int,
	@Bsex				char(1),
	@Bbirthday			datetime,
	@Btel				varchar(100),
	@Baddr				varchar(100),
	@Bpostcode			varchar(200),
	@Btrade				varchar(100),
	@BIDcard			varchar(100),
	@VipStatus			char(1),
	@Comment			varchar(500),
	@BeginMoney			 NUMERIC(24, 10) ,
	@BeginCent			numeric(18,0),
	@IsCz				varchar(10)='0',
	@qccz				 NUMERIC(24, 10) ,
	@RATypeID			varchar(100), --维修车辆TypeID
	@BTypeID			varchar(100),
	@CarType			int,
	@CarWashPrice	     NUMERIC(24, 10) ,
	@IsWashTimes		char(1),
	@CanWashTimes00	    int,
	@CanWashTimes	    int,
	@CzyeMoney           NUMERIC(24, 10) ,
	@jkStypeId			VARCHAR(50),
	@IsApplyAllStype	INT = 1,
	@IsApplyAllPOS		INT = 1,
	@cardpassword		VARCHAR(20)=''				--卡初始密码
)
--@encode$--
AS

SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
----------------------
DECLARE @totalCent NUMERIC(18,4)
--=======================================================新增发卡
IF @pycode = ''
BEGIN
	SET @pycode = DBO.fun_getPY(@Bname)
END

IF @Action = 'Add'
BEGIN
	IF EXISTS(SELECT TOP 1 * FROM nVipCardSign WHERE VipCardCode = @VipCardCode AND deleted<>'1')
		BEGIN
			--RAISERROR('该卡号的Vip卡已存在,请确定后重试!',16,1)
			RETURN -1
		END	

	INSERT INTO nVipCardSign
	(
		VipCardCode,--vip卡号
		VipCardTypeID  ,--该卡所属vip卡的类型，与nVipCardSet相关联
		Bname ,--持卡人姓名
		pycode ,--持卡人拼音码
		Bsex,--性别0表示女，1表示男
		Bbirthday ,--客户生日
		Btel,--联系电话
		Baddr  ,--联系地址
		Bpostcode ,--邮编
		Btrade  ,--行业
		BIDcard ,--证件号码
		etypeid ,--办理人id，和系统employee表关联
		CreateDate ,--发卡日期
		EndDate ,
		deleted ,  
		BeginMoney ,--初始消费金额
		BeginCent ,--初始积分
		totalMoney ,--消费总金额
		totalCent,--总积分
		Comment,
		IsCz,
		qCczMoney,
		RATypeID,
		BTypeID,
		CarType,
		CarWashPrice,
		IsWashTimes,
		CanWashTimes00,
		CanWashTimes,
		cZyeMoney,
		jkStypeId,
		isApplyAllStype,
		isApplyAllPOS,
		pWord
	)
	VALUES
	(
		@VipCardCode,
		@Cardset,
		@Bname,
		@pycode,
		@Bsex,
		@Bbirthday,
		@Btel,
		@Baddr,
		@Bpostcode,
		@Btrade,
		@BIDcard,
		@etypeid,
		@CreateDate,
		@EndDate,
		@VipStatus,  
		@BeginMoney,
		@BeginCent,
		0,
		0,
		@Comment,
		@IsCz,
		@qccz,
		@RATypeID,
		@BTypeID,
		@CarType,
		@CarWashPrice,
		@IsWashTimes,
		@CanWashTimes00,
		@CanWashTimes,
		@CzyeMoney,
		@jkStypeId,
		@IsApplyAllStype,
		@IsApplyAllPOS,
		@cardpassword
	)

	IF @@ROWCOUNT=0
		BEGIN
			--RAISERROR('录入数据失败,请确定后重试!',16,1)
			RETURN -2
		END		
		
	--积分不能为负数	
	IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign	WHERE VipCardId = @VipCardId AND (BeginCent + totalCent)<0)
	BEGIN
		--RAISERROR('最终积分不能为负数,请确定后重试!',16,1)
		RETURN -4
	END		
END

--=======================================================修改发卡
IF @Action IN( 'Modify','POSModify')
BEGIN
	IF EXISTS(SELECT * FROM nVipCardSign WHERE VipCardCode = @VipCardCode AND VipCardId <> @VipCardId AND deleted<>'1')
	BEGIN
		RETURN -1
	END
	
	IF EXISTS(SELECT * FROM nVipCardSign WHERE VipCardId=@VipCardId AND (totalCent+@BeginCent)<0)
	BEGIN
		RETURN -4
	END


	UPDATE	nVipCardSign
	SET		VipCardCode	=	@VipCardCode   ,
			VipCardTypeID  =	@CardSet,
			Bname 			=	@Bname,
			pycode 			=	@pycode,
			Bsex			=	@Bsex,
			Bbirthday 		=	@Bbirthday,
			Btel			=	@Btel,
			Baddr  		=	@Baddr,
			Bpostcode 		=	@Bpostcode,
			Btrade  		=	@Btrade,
			BIDcard 		=	@BIDcard,
			etypeid 		=	@etypeid,
			CreateDate 	=	@CreateDate,
			EndDate 		=	@EndDate,
			deleted 		=	@VipStatus,  
			BeginMoney 	=	@BeginMoney,
			BeginCent 		=	@BeginCent,
			Comment 		=	@Comment,
			IsCz			=   @IsCz,
			qCczMoney		=   @qccz,
			RATypeID	=	@RATypeID,
			BTypeID		=	@BTypeID,
			CarType		=	@CarType,
			CarWashPrice	=	@CarWashPrice,
			IsWashTimes	=	@IsWashTimes,
			CanWashTimes00	=	@CanWashTimes00,
			CanWashTimes	=	@CanWashTimes,
			jkStypeId		=	@jkStypeId,
			isApplyAllStype =	@IsApplyAllStype,
			isApplyAllPOS	=	@IsApplyAllPOS
	WHERE	VipCardId 	= @VipCardId
	
	IF @@ROWCOUNT=0
		BEGIN
			--RAISERROR('录入数据失败,请确定后重试!',16,1)
			RETURN -2
		END
		
	--积分不能为负数	
	IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign	WHERE VipCardId = @VipCardId AND (BeginCent + totalCent)<0)
	BEGIN
		--RAISERROR('最终积分不能为负数,请确定后重试!',16,1)
		RETURN -4
	END
END

--================统计各个类型vip卡发放的数量=========
DECLARE @CardTypeid int
DECLARE @num int

DECLARE Vip_Cursor CURSOR FOR
	SELECT VipCardTypeid FROM nVipCardSet Where deleted<>'1'

OPEN Vip_Cursor
	FETCH NEXT FROM Vip_Cursor INTO @CardTypeid
	WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT @num = Count(VipCardID) FROM nVipCardSign WHERE deleted<>'1' AND VipCardTypeid=@CardTypeid

			 Update nVipCardSet 
			 SET VipCardnum=@num
			 WHERE VipCardTypeID=@CardTypeid
				   
   			FETCH NEXT FROM Vip_Cursor INTO @CardTypeid
		END
CLOSE Vip_Cursor
DEALLOCATE Vip_Cursor

DECLARE @VIP_ID VARCHAR(50),
		@CID	BIGINT

SELECT @CID=CID FROM Ac_Currency WHERE Sysrow = 1
SELECT @VIP_ID=NID FROM Ac_Items WHERE UserCode='2181'

--==============期初刷新金额===========================
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'inicanmodify' AND SubValue = 'T')
	BEGIN
		--刷新储值余额
		UPDATE nVipCardSign SET cZyeMoney = qCczMoney + lJczMoney WHERE VipCardCode = @VipCardCode
		--刷新会计科目
		DECLARE @numQcTotal  NUMERIC(24, 10) 
		SELECT  @numQcTotal = ISNULL(SUM(qCczMoney),0) FROM nVipCardSign
		IF EXISTS(SELECT TOP 1 1 FROM AType_Total AT WHERE AT.ATypeID=@VIP_ID)
		   UPDATE  AType_Total SET Total00 = ISNULL(@numQcTotal,0),Ntotal00 = ISNULL(@numQcTotal,0)  WHERE ATypeID =@VIP_ID
		ELSE
		   INSERT INTO AType_Total (ATypeID,STypeID,Total00,CID,Ntotal00) VALUES(@VIP_ID,'00001',@qccz,@CID,@qccz)
	END
	
DECLARE  @returnvipcardid int
SELECT @returnvipcardid=VipCardId FROM nVipCardSign WHERE VipCardCode=@VipCardCode

--V1/V3版本写入会员卡分支机构表
IF @IsCz = '1' AND EXISTS(SELECT * FROM dbo.sysdata WHERE SubName ='proinfo' AND SubValue IN('1','4'))
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.nVipCardSignStype WHERE VipCardID = @returnvipcardid AND StypeId = '00001')
	BEGIN
		INSERT INTO dbo.nVipCardSignStype
				( VipCardID ,
				  StypeId ,
				  qCczMoney ,
				  lJczMoney ,
				  lJxFczMoney ,
				  bNczMoney ,
				  bNxFczMoney ,
				  cZyeMoney ,
				  lJxFMoney ,
				  bNxFMoney
				)
		SELECT	c.VipCardID ,
				'00001',
				@qccz ,
				@qccz ,
				0,
				0,
				0,
				@qccz,
				c.BeginMoney ,
				0 
		FROM dbo.nVipCardSign c
		WHERE c.VipCardID = @returnvipcardid
	END
	
	IF EXISTS(SELECT * FROM dbo.SType_UserConfig WHERE StypeId = '00001' AND Value = 0)
	BEGIN 
		DECLARE @temp NUMERIC(24,10)
		SELECT @temp = lJczMoney + @qccz - qCczMoney - lJxFczMoney 
		FROM dbo.nVipCardSignStype 
		WHERE	VipCardID = @returnvipcardid AND StypeId = '00001'
		
		IF @temp < 0
		BEGIN
			RETURN -3
		END 
		
		UPDATE nVipCardSignStype 
		SET	qCczMoney = @qccz
			,cZyeMoney=@qccz
			,lJczMoney = @qccz+lJxFczMoney
		WHERE	VipCardID = @returnvipcardid AND StypeId = '00001'
	END 
END

RETURN @returnvipcardid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_nInsertVipCardSignRemindEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_nInsertVipCardSignRemindEvent]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






















/*
	描述:新增修改Vip卡发卡的信息
	作者:徐辉
	日期:2010-08-02
*/
CREATE               PROCEDURE QP_nInsertVipCardSignRemindEvent
(
	@Action				varchar(100),	--动作	Add-新增   Modify-修改
	@VipCardId			int,
	@RemindContent			varchar(200),	--内容
	@RemindDate			datetime,	--日期	
	@Comment			varchar(250)
)
--@encode$--
AS

SET NOCOUNT ON

INSERT QP_nVipCardSign_RemindEvent (VipCardId,RemindContent,RemindDate,Comment)
	VALUES(@VipCardId,@RemindContent,@RemindDate,@Comment)
IF @@ROWCOUNT=0
BEGIN
	RETURN -2
END		

RETURN 0
































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_nInsertVipCardSignRepairItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_nInsertVipCardSignRepairItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO























/*
	描述:新增修改Vip卡发卡的信息
	作者:徐辉
	日期:2010-08-02
*/
CREATE                PROCEDURE QP_nInsertVipCardSignRepairItems
(
	@Action				varchar(100),	--动作	Add-新增   Modify-修改
	@VipCardId			int,
	@RepairItemsTypeID		varchar(100),	--维修项目ID
	@ManHour			 NUMERIC(24, 10) ,	--工时
	@VIPPrice			 NUMERIC(24, 10) ,	--会员价
	@AllowUsedTimes			int,
	@Comment			varchar(250)
)
--@encode$--
AS

SET NOCOUNT ON


INSERT QP_nVipCardSign_RepairItems (VipCardId,RepairItemsTypeID,ManHour,VIPPrice,AllowUsedTimes,Comment)
	VALUES(@VipCardId,@RepairItemsTypeID,@ManHour,@VIPPrice,@AllowUsedTimes,@Comment)

IF @@ROWCOUNT=0
BEGIN
	RETURN -2
END		

RETURN 0

































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_nVipcardExtend]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_nVipcardExtend]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	描述:查询Vip卡的发卡情况
	作者:徐辉
	日期:2010-08-05
*/
CREATE                   PROCEDURE QP_nVipcardExtend
(
	@chvOperatorId		varchar(100),				--操作员Id
	@VipCardCode		varchar(50),				--Vip卡号
	@Bname				varchar(50),				--Vip卡持有者
	@CreateDate			varchar(20),				--签发日期
	@EndDate			varchar(20),				--截止日期
	@EtypeID			varchar(max),				--   --发卡人
	@DtypeID			varchar(max),				--部门
	@Cardset			char(10),					--Vip卡状态
	@Comment			varchar(300),				--备注
	@OrderBy			varchar(max),				--排序字段
	@btel				varchar(20),				--会员手机
	@typename			varchar(100),				--卡类型
	@czyeV				int,						--储值余额为0不显示  1= 不显示 0= 显示
	@jfyeV				int,						--积分余额为0不显示  1= 不显示 0= 显示
	--@intPageNo 			int = 1, 					-- 当前查询的页码
	--@intPageSize 		int = 1, 					-- 每页的显示记录数,
	@intRowCount 		int = 0 output,	 			-- 返回总记录数
	@jkStypeId			VARCHAR(MAX)='00001'		--建卡机构	
	--@onlyShowSum        INT = 0						--只显示合计值
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @chvOperatorId,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Dtype(typeid VARCHAR(50))
INSERT #Dtype(typeid)
SELECT typeid FROM F_GetAllManagerBaseTypeId(@DtypeID,9,@chvOperatorId)

CREATE TABLE #Etype(typeid VARCHAR(50))
INSERT #Etype(typeid)
SELECT typeid FROM F_GetAllManagerBaseTypeId(@EtypeID,3,@chvOperatorId)

select @CreateDate=ISNULL(@CreateDate,'')
select @EndDate=ISNULL(@EndDate,'')

DECLARE @SQL		VARCHAR(8000)
DECLARE @SQL_LIST	VARCHAR(8000)


--------------------------------------------------------------开始创建临时表-------------------------------------------------------
CREATE TABLE #temp1
(
	VipCardId		numeric(10,0)	,
	BTypeId			VARCHAR(50)		,
	BUserCode       VARCHAR(50)		,
	VipCardCode		VARCHAR(100)	,
	Bname			VARCHAR(100)	,
	CreateDate		datetime		,
	EndDate			datetime		,
	deleted			char(5)			,
	zt				VARCHAR(50)		,
	Comment			VARCHAR(100)	,
	TypeName		VARCHAR(100)	,
	ifjf			VARCHAR(100)	,
	sfjf			VARCHAR(100)	,
	DiscountType	VARCHAR(10)		,
	CardTypeDiscount decimal(11, 10),
	VipCardTypeid	int				,
	Ename			VARCHAR(50)		,
	IsCz			char(5)			,
	qCczMoney		NUMERIC(24,10)	,
	lJczMoney		NUMERIC(24,10)	,
	cZyeMoney		NUMERIC(24,10)	,
	Sex				char(5)			,
	bsex			char(1)			,
	bbirthday		datetime		,
	btel			VARCHAR(50)		,
	baddr			VARCHAR(50)		,
	bpostcode		VARCHAR(50)		,
	btrade			VARCHAR(50)		,
	bidcard			VARCHAR(50)		,
	beginmoney		NUMERIC(24,10)	,
	begincent		NUMERIC(24,10)	,
	pword			char(10)		,
	canwashtimes	int				,
	iswashtimes		int				,
	RATypeID		VARCHAR(50)		,
	cartype			int				,
	bfullname		VARCHAR(50)		,
	ispword			char(5)			,
	jfyemoney		NUMERIC(24,10)	,
	LjTotal			NUMERIC(24,10)	,
	totalMoney		NUMERIC(24,10)	,
	sid numeric(10,0)  IDENTITY (1, 1) NOT NULL,
	JKSFullName		VARCHAR(200),		--建卡机构
	isApplyAllStype	VARCHAR(10),		--适用分支机构
	isApplyAllPOS	VARCHAR(10)		--适用门店
)
--------------------------------------------------------------结束创建临时表-------------------------------------------------------
--计算页码
--DECLARE @StartPageNo int
--DECLARE @EndPageNo int
--SET @StartPageNo = @intPageSize*(@intPageNo - 1) + 1;
--SET @EndPageNo = @intPageSize*@intPageNo;


SELECT @SQL_LIST  = ''

SELECT @SQL  = ''

IF 	@CreateDate = ''
	SELECT @CreateDate = '1900-01-01'
IF 	@EndDate = ''
    SET @EndDate = '9200-01-01'


	SELECT @SQL_LIST = '
		SELECT	A.VipCardId,
				A.BTypeId,
				f.usercode as BUserCode,
				A.VipCardCode As VipCardCode,
				A.Bname As Bname,
				A.CreateDate As CreateDate,
				A.EndDate AS EndDate,
				A.deleted AS deleted,
				CASE 
					WHEN A.deleted = 0 THEN ''启用''
					WHEN A.deleted = 2 THEN ''停用''
					WHEN A.deleted = 3 THEN ''挂失''
					ELSE ''启用''
				END AS zt,				
				A.Comment AS Comment,
				B.TypeName AS TypeName,
				B.ifjf,
				CASE
					WHEN B.ifJF = ''1'' THEN ''参与积分''
					ELSE ''不参与积分''
				END AS sfjf,
				B.DiscountType,
				B.CardTypeDiscount,
				B.VipCardTypeid,
				C.FullName as Ename,
				CASE
					WHEN ISNULL(IsCz,'''')=''1'' THEN ''是''
					ELSE ''否''
				END AS IsCz,
				ISNULL(A.qCczMoney,0) qCczMoney,
				ISNULL(A.lJczMoney,0) lJczMoney,
				ISNULL(A.cZyeMoney,0) cZyeMoney,
				CASE
					WHEN A.bsex=1 THEN ''男''
					WHEN A.bsex=0 THEN ''女''
					ELSE ''男''
				END AS Sex,
				CASE
					WHEN A.bsex=1 THEN 1
					WHEN A.bsex=0 THEN 0
					ELSE 0
				END AS bsex,
				A.bbirthday,
				A.btel,
				A.baddr,
				a.bpostcode,
				a.btrade,
				a.bidcard,
				ISNULL(a.beginmoney,0) beginmoney,
				ISNULL(a.begincent,0) begincent,
				a.pword,
				a.canwashtimes,
				a.iswashtimes,
				a.RATypeID,a.cartype,
				f.fullname AS bfullname,
				CASE WHEN pWord<>''''
				     THEN ''有''
				     ELSE ''''
				END AS ispword,
				ISNULL(A.BeginCent,0)+ISNULL(A.totalCent,0) AS jfyemoney,
				ISNULL(a.BeginMoney,0)+ISNULL(a.TotalMoney,0) AS LjTotal,
				ISNULL(a.totalMoney,0) totalMoney,
				JKS.FullName jksfullname,
				A.isApplyAllStype,
				A.isApplyAllPOS
		FROM 	nVipCardSign A
		INNER JOIN #Etype E ON E.typeid = A.ETypeID 
		LEFT JOIN nVipCardSet  B ON A.VipCardTypeId = B.VipCardTypeId
		INNER JOIN Employee C ON A.EtypeId = C.TypeId
		INNER JOIN SType JKS ON JKS.TypeId=A.jkStypeId'+CHAR(13)

IF @DtypeID <> ''
	SET @SQL_LIST += ' INNER JOIN #Dtype D ON D.TypeId = C.DtypeId '+CHAR(13)

--建卡机构
SET @SQL_LIST +='INNER JOIN  dbo.F_GetAllManagerBaseTypeId('''+@jkStypeId+''',11,'''+@chvOperatorId+''') F_jk ON F_jk.TypeId=A.jkStypeId'+CHAR(13)
		
SET @SQL_LIST += ' 	
		LEFT JOIN  Btype f ON A.BtypeId=f.typeid		
		WHERE	A.CreateDate >= '+CHAR(39)+@CreateDate+CHAR(39)+'
				AND A.CreateDate <= '+CHAR(39)+@EndDate+CHAR(39)+''
				
IF @VipCardCode<>''
	SET @SQL_LIST=@SQL_LIST+' AND A.VipCardCode LIKE ''%'+@VipCardCode+'%'' '
IF @Bname<>''
	SET @SQL_LIST=@SQL_LIST+' AND A.Bname LIKE ''%'+@BName+'%'' '	

IF @btel<>''
	SET @SQL_LIST=@SQL_LIST+' AND A.BTEL LIKE ''%'+@btel+'%'' '
IF @typename<>''
	SET @SQL_LIST=@SQL_LIST+' AND B.vipcardtypeid in ('+@typename+') '
IF len(LTRIM(RTRIM(@Cardset))) <> 0   				
	SET @SQL_LIST = @SQL_LIST + 'AND A.deleted = '+CHAR(39)+@Cardset+CHAR(39)+''
IF @Comment<>''
	SET @SQL_LIST = @SQL_LIST + ' AND A.Comment LIKE ''%'+@Comment+'%'''
	
--	储值余额为0不显示  1= 不显示 0= 显示
IF 	@czyeV=1 	
	SET @SQL_LIST = @SQL_LIST + ' AND ISNULL(A.cZyeMoney,0)<>0'	
--	积分余额为0不显示  1= 不显示 0= 显示		
IF	@jfyeV=1
	SET @SQL_LIST = @SQL_LIST + ' AND ISNULL(A.BeginCent+A.totalCent,0)<>0'	
			
SET @SQL_LIST = @SQL_LIST +' AND A.deleted<>''1'' '
-- 排序
IF RTRIM(@OrderBy)=''
	SET @OrderBy = ' Order By A.VipCardCode asc'
ELSE
	SET @OrderBy = ' Order By ' + @OrderBy

SET @SQL_LIST=@SQL_LIST+@OrderBy


SET @SQL =' INSERT INTO #temp1
			(
				VipCardId,
				BTypeId,
				BUserCode,
				VipCardCode,
				Bname,
				CreateDate,
				EndDate,
				deleted,
				zt,
				Comment,
				TypeName,
				ifjf,
				sfjf,
				DiscountType,
				CardTypeDiscount,
				VipCardTypeid,
				Ename,
				IsCz,
				qCczMoney,
				lJczMoney,
				cZyeMoney,
				Sex	,
				bsex,
				bbirthday,
				btel,
				baddr,
				bpostcode,
				btrade,
				bidcard	,
				beginmoney,
				begincent,
				pword,
				canwashtimes,
				iswashtimes,
				RATypeID,
				cartype	,
				bfullname,
				ispword,
				jfyemoney,
				LjTotal	,
				totalMoney,
				JKSFullName,
				isApplyAllStype,
				isApplyAllPOS
			)	'+@SQL_LIST


--print @SQL
EXEC(@SQL)

SET @intRowCount=@@ROWCOUNT--现在是这个记录数不对，应该可以用一个临时表来得到这个记录数

SET @SQL = 'select	a.*,
					'+Convert(varchar(100),@intRowCount)+' as TotalNum,
					CASE
						WHEN a.isApplyAllStype = 0 THEN ''部分''
						ELSE ''全部''
					END AS applystype,
					CASE
						WHEN isApplyAllPOS = 0 THEN ''部分''
						ELSE ''全部''
					END AS applypos
			FROM 	#temp1 a  
			ORDER BY A.sid'

--print @SQL	
EXEC (@SQL)

DROP TABLE #Dtype,#Etype,#temp1

GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_OperateTransport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_OperateTransport]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2011-11-22
	描述：处理运输方式定义
*/
CREATE PROCEDURE QP_OperateTransport
(
	@ID			VARCHAR(100),
	@FullName	VARCHAR(200),
	@Usercode   VARCHAR(200),
	@Btypeid     VARCHAR(50),
	@nType		VARCHAR(10),
	@pycode     VARCHAR(100),
	@Comment    VARCHAR(1000) 
)
--@encode$--
AS
SET NOCOUNT ON

IF @nType = 'a' 		--新增
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_Transport WHERE FullName = @FullName)
			RETURN -1
        IF EXISTS(SELECT TOP 1 1 FROM QP_Transport WHERE Usercode = @Usercode AND [ID]<>@ID)
			RETURN -3
			
		INSERT INTO QP_Transport
		(
			FullName,
			Usercode,
			Btypeid,
			PYCode,
			Comment
			
		)VALUES(
			@FullName,
			@Usercode,
			@Btypeid,
			@pycode ,
			@Comment
		)

		IF @@ROWCOUNT = 0
			RETURN -2		
	END
ELSE IF @nType = 'm' 	--修改
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM QP_Transport WHERE FullName = @FullName AND [ID]<>@ID)
			RETURN -1		
        IF EXISTS(SELECT TOP 1 1 FROM QP_Transport WHERE Usercode = @Usercode AND [ID]<>@ID)
			RETURN -3
        
		UPDATE	QP_Transport
		SET		FullName = @FullName,
				Usercode = @Usercode,
				Btypeid=@Btypeid,
				PYCode =@pycode ,
				Comment=@Comment
		WHERE	[ID] = @ID

		IF @@ROWCOUNT = 0
			RETURN -2
	END
ELSE IF @nType = 'd'	--删除
	BEGIN		
--判断是否在维修车辆信息中使用
		IF EXISTS(SELECT transportid FROM BillIndex WHERE transportid=@ID)
		OR EXISTS(SELECT transportid FROM BillIndex WHERE transportid=@ID)
			RETURN -1
        
		DELETE FROM QP_Transport WHERE [ID] = @ID

		IF @@ROWCOUNT = 0
			RETURN -2
	END

RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_PickingBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_PickingBillIndex]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-05-15
	描述：导入领料出库明细
*/

CREATE PROCEDURE Qp_PickingBillIndex
(
	@BillNumberId		VARCHAR(100),
	@OperatorId				VARCHAR(MAX)		--操作员id
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',1,@OperatorID)	

SELECT	pb.PTypeId,
		P.Unit1 AS unitone,
		P.Unit2 As unittwo,
		P.Unit1 AS Unit,
		P.Unitrate1 As Unitrate,
		pb.Qty-pb.BackQty AS Qty, 
		pb.ID,
		pb.Price,
		(pb.Qty-pb.BackQty)*pb.Price AS Total,
		pb.KTypeID,
		pb.CargoSpace,
		pb.Insurance,
		1 AS selected,
		pb.Comment
FROM	Qp_PickingBill pb
INNER JOIN ptype p ON pb.PTypeID=p.typeId
INNER JOIN #GetManDTypeId MP ON MP.TypeId=PB.PTypeID
WHERE	BillNumberId=@BillNumberId
DROP TABLE  #GetManDTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Query_BossList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Query_BossList]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	作者:冯波
	日期:2010-07-22
	描述:老板一张表
	
	作者:徐辉
	日期:2011-03-22
	描述:权限调整
*/
CREATE    PROCEDURE QP_Query_BossList
(
	@chvStartDate		varchar(30),	--  2、查询起始时间
	@chvEndDate			varchar(30),	--  3、查询结束时间
	@STypeId			varchar(MAX)='00001',	--  4、分支机构
	@OperatorID         VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON 
--DECLARE @OperatorID VARCHAR(MAX)

--SET @OperatorID = '00001'

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--ATypeID为空的，则是需要进行合计或其他运算的

CREATE TABLE #AType(
	FullName	VARCHAR(200),
	Total		 NUMERIC(24, 10) 	DEFAULT 0,
	ATypeID		VARCHAR(50)		DEFAULT '',
	SumName		VARCHAR(50)		DEFAULT '',
	typeName	VARCHAR(2),
	rowlevel	INT,
	ntypeid		VARCHAR(50),
	sonnum		INT  DEFAULT 0,
	parid		VARCHAR(50),
	ShowOrder	INT IDENTITY (1, 1)
)

--先把需要展示的项目列出来
INSERT #AType(FullName,ATypeID,SumName,rowlevel,ntypeid,sonnum) SELECT	'一、本期利润总额','','Profit',1,'00000',0

---本期收入（根据操作员配置取值）
INSERT #AType(FullName,ATypeID,rowlevel,ntypeid,sonnum) SELECT	'  本期总收入','00003',1,'00003',1
INSERT #AType(FullName,ATypeID,typeName,rowlevel,ntypeid,sonnum,parid)
SELECT	 FullName,nid,typeName,Leveal,nTypeId,SonNum,nparid 
FROM(
	SELECT	a.FullName,a.nid,a.typeName,a.Leveal AS Leveal,a.nTypeId,a.SonNum,a.nParId 
	FROM ac_items a,
	BossListConfig b
	WHERE a.nTypeId LIKE b.atypeid+'%'  AND a.nTypeId LIKE '00003%'   AND b.flag=1   AND a.TypeName='G'
	AND a.nTypeId<>'00003'	AND etypeid=@OperatorID
	UNION  ALL
	SELECT	a.FullName,a.nid,a.typeName,a.Leveal AS Leveal,a.nTypeId,a.SonNum,a.nParId  
	FROM ac_items a,
	BossListConfig b
	WHERE a.nTypeId=b.atypeid  AND a.nTypeId LIKE '00003%'   AND b.flag=0   AND a.TypeName='G'
	AND a.nTypeId<>'00003'   AND etypeid=@OperatorID
	) a
	ORDER BY a.nTypeId

--本期支出（根据操作员配置取值）
INSERT #AType(FullName,ATypeID,rowlevel,ntypeid,sonnum) SELECT	'  本期总支出','00004',1,'00004',1
INSERT #AType(FullName,ATypeID,typeName,rowlevel,ntypeid,sonnum,parid)
SELECT	 FullName,nid,typeName,Leveal,nTypeId,SonNum,nparid 
FROM(
	SELECT	a.FullName,a.nid,a.typeName,a.Leveal AS Leveal,a.nTypeId,a.SonNum,a.nParId  
	FROM ac_items a,
	BossListConfig b
	WHERE a.nTypeId LIKE b.atypeid+'%'  AND a.nTypeId LIKE '00004%'   AND b.flag=1   AND a.TypeName='E'
	AND a.nTypeId<>'00004'	AND etypeid=@OperatorID
	UNION  ALL
	SELECT	a.FullName,a.nid,a.typeName,a.Leveal AS Leveal,a.nTypeId,a.SonNum,a.nParId  
	FROM ac_items a,
	BossListConfig b
	WHERE a.nTypeId=b.atypeid  AND a.nTypeId LIKE '00004%'   AND b.flag=0   AND a.TypeName='E'
	AND a.nTypeId<>'00004'   AND etypeid=@OperatorID
	) a
	ORDER BY a.nTypeId
--其他固定项
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'二、本期实际进货总额','','InOutTotal',1,''
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'	其中:	采购入库总额','','BuyTotal',1,''
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'			   采购退货总额','','BuyBackTotal',1,''

IF EXISTS(select 1 from sysdata where SubName='ISINVOICE' and SubValue='1')
BEGIN
	INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'			   暂估入库总额','','AppraisalBill',1,''
	INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'			   暂估退货总额','','AppraisalBackBill',1,''
END
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'			   受托入库总额','','EntrustTotal',1 ,''
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'			   受托退货总额','','EntrustBackTotal',1,''
INSERT #AType(FullName,SumName,rowlevel,nTypeId) SELECT	'三、本期应收总额','ARTotal',1,''
INSERT #AType(FullName,SumName,rowlevel,nTypeId) SELECT	'四、本期应付总额','APTotal',1,''

--现金（根据操作员配置取值）
INSERT #AType(FullName,ATypeID,SumName,typeName,rowlevel,nTypeId,sonnum) 
	SELECT	'五、现金总额',NID,'Cash',typename,1,'0000100003',SonNum FROM ac_items WHERE nTypeId='0000100003'
INSERT #AType(FullName,ATypeID,typeName,rowlevel,ntypeid,sonnum,parid)
SELECT	 FullName,nid,typeName,Leveal,nTypeId,SonNum,nParId   
FROM(
	SELECT	a.FullName,a.nid,a.typeName,a.Leveal-1 AS Leveal,a.nTypeId,a.SonNum,a.nParId   
	FROM ac_items a,
	BossListConfig b
	WHERE a.nTypeId LIKE b.atypeid+'%'  AND a.nTypeId LIKE '0000100003%'   AND b.flag=1   AND a.TypeName='B'
	AND a.nTypeId<>'0000100003'	AND etypeid=@OperatorID
	UNION  ALL
	SELECT	a.FullName,a.nid,a.typeName,a.Leveal-1 AS Leveal,a.nTypeId,a.SonNum,a.nParId   
	FROM ac_items a,
	BossListConfig b
	WHERE a.nTypeId=b.atypeid  AND a.nTypeId LIKE '0000100003%'   AND b.flag=0   AND a.TypeName='B'
	AND a.nTypeId<>'0000100003'   AND etypeid=@OperatorID
	) a
	ORDER BY a.nTypeId
	
--银行账户（根据操作员配置取值）
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId,sonnum) SELECT	'六、银行存款总额',nid,'Bank',1,'0000100004' ,SonNum FROM ac_items WHERE nTypeId='0000100004'
INSERT #AType(FullName,ATypeID,typeName,rowlevel,ntypeid,sonnum,parid)
SELECT	 FullName,nid,typeName,Leveal,nTypeId,SonNum,nParId 
FROM(
	SELECT	a.FullName,a.nid,a.typeName,a.Leveal-1 AS Leveal,a.nTypeId,a.SonNum,a.nParId   
	FROM ac_items a,
	BossListConfig b
	WHERE a.nTypeId LIKE b.atypeid+'%'  AND a.nTypeId LIKE '0000100004%'   AND b.flag=1   AND a.TypeName='B'
	AND a.nTypeId<>'0000100004'	AND etypeid=@OperatorID
	UNION  ALL
	SELECT	a.FullName,a.nid,a.typeName,a.Leveal-1 AS Leveal,a.nTypeId,a.SonNum,a.nParId   
	FROM ac_items a,
	BossListConfig b
	WHERE a.nTypeId=b.atypeid  AND a.nTypeId LIKE '0000100004%'   AND b.flag=0   AND a.TypeName='B'
	AND a.nTypeId<>'0000100004'   AND etypeid=@OperatorID
	) a
	ORDER BY a.nTypeId
	
--其他
INSERT #AType(FullName,ATypeID,SumName,typeName,rowlevel,nTypeId) SELECT	'七、会员储值总额',NID,'VIP',typename,1,'' FROM ac_items WHERE usercode='2181'

INSERT #AType(FullName,SumName,rowlevel,nTypeId) SELECT	'八、本期库存金额','AllStock',1,''
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'	其中:	本期期初金额','','IniStock'	,1,''
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'			   本期入库金额','','InStock',1,''
INSERT #AType(FullName,ATypeID,SumName,rowlevel,nTypeId) SELECT	'			   本期出库金额','','OutStock',1,''
INSERT #AType(FullName,SumName,rowlevel,nTypeId) SELECT	'			   本期结存金额','AllStock',1,''

--算本期类项目的所有子节点的值
CREATE TABLE #A(atypeid VARCHAR(50),total  NUMERIC(24, 10) ,typename VARCHAR(20))
INSERT #A
SELECT A.ATypeID,SUM(a.Total) AS Total,AC.TypeName
	FROM ListTable a
	INNER JOIN dbo.Ac_Items AC ON A.AtypeId =  AC.nId
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeID
	WHERE a.BillDate BETWEEN @chvStartDate AND @chvEndDate
	AND ac.TypeName IN('G','E')
	GROUP BY A.ATypeID,AC.TypeName

--现金，银行、会员储值总额(现金银行不受时间段控制，统计总额)
INSERT #A
SELECT	a.ATypeID,SUM(a.Total) AS Total,'B'
	FROM	AType_Total a 
	INNER JOIN dbo.Ac_Items b ON a.ATypeID = b.nid
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeID
	WHERE	 (b.typename='B' OR  b.usercode='2181')
	GROUP BY a.ATypeID
	
UPDATE #AType
SET Total=b.Total
FROM #A b
WHERE #AType.ATypeID<>'' AND #AType.ATypeID=b.ATypeID
 

--递归计算所有收入、支出、现金、银行所有父节点的值
;with t  AS
(  
	select   ntypeid as rowid,ntypeid,nid,fullname   
	from    dbo.Ac_Items     
	WHERE ntypeid LIKE'00003%' OR	 ntypeid LIKE'00004%'  OR ntypeid LIKE'0000100004%' OR ntypeid LIKE'0000100003%'
	union all  
	select    rowid,  b.ntypeid,b.nid,  a.fullname  
	from   t a,Ac_Items b  
	where   
		a.ntypeid=b.nparid   AND (a.ntypeid LIKE'00003%' OR a.ntypeid LIKE'00004%' OR a.ntypeid LIKE'0000100004%' OR a.ntypeid LIKE'0000100003%' 	)
)
select  t.rowid  as ntypeid,sum(isnull(a.total,0)) as total 
INTO #tmp 
from    t  
left join  #A a  on    a.atypeid=t.nid  
	group by  t.rowid
UPDATE #atype
 SET total=t.total
 from  #tmp t
 WHERE	 #atype.ntypeid=t.ntypeid
 AND sonnum<>0


--应收，应付
DECLARE
	@strAR			VARCHAR(100),
	@strys			VARCHAR(100),
	@strAP			VARCHAR(100),
	@stryf			VARCHAR(100),
	@intBTypeAll	TINYINT		--1表示统一

		
SELECT @strys=nId FROM Ac_Items WHERE UserCode='2131'  --预收
SELECT @stryf=nId FROM Ac_Items WHERE UserCode='1151'  --预付
SELECT @strAR=nId FROM Ac_Items WHERE UserCode='987'  --应收
SELECT @strAP=nId FROM Ac_Items WHERE UserCode='2121'  --应付

SELECT	@intBTypeAll = Value 
FROM	UserConfig 
WHERE	ConfigName = 'BTypeAll'

CREATE TABLE #tmp_ARAP(
	ARTotal			 NUMERIC(24, 10) ,
	ysTotal			 NUMERIC(24, 10) ,
	APTotal			 NUMERIC(24, 10) ,
	yfTotal			 NUMERIC(24, 10) 
)


INSERT #tmp_ARAP(ARTotal,ysTotal,APTotal,yfTotal)
SELECT	
		SUM(CASE WHEN a.ATypeID=@strAR	THEN a.Total ELSE 0 END) AS ARTotal,
		SUM(CASE WHEN a.ATypeID=@strys	THEN a.Total ELSE 0 END) AS ysTotal,
		SUM(CASE WHEN a.ATypeID=@strAP	THEN a.Total ELSE 0 END) AS APTotal,
		SUM(CASE WHEN a.ATypeID=@stryf	THEN a.Total ELSE 0 END) AS yfTotal
FROM	ListTable a
--INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID		
INNER JOIN BType c ON a.BTypeID=c.TypeID
INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeID
WHERE a.ATypeID IN (@strAR,@strAP,@strys,@stryf) AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND a.Audited=1



UPDATE	#AType
SET		Total=ISNULL(b.ARTotal,0)-ISNULL(b.ysTotal,0)
FROM	#tmp_ARAP b
WHERE	#AType.SumName='ARTotal'


UPDATE	#AType
SET		Total=ISNULL(b.APTotal,0)-ISNULL(b.yfTotal,0)
FROM	#tmp_ARAP b
WHERE	#AType.SumName='APTotal'


--本期利润=收入-支出
UPDATE #AType
SET Total=ISNULL(b.Total,0)
FROM
(
	SELECT SUM(CASE typeName WHEN 'G' THEN Total ELSE -Total END) AS Total
	FROM	#A a 
	WHERE a.ATypeID<>'' and a.typeName IN ('G','E')
) b
WHERE SumName='Profit'


UPDATE #AType
SET Total=ISNULL(b.Total,0)
FROM
(
	SELECT SUM(a.CostTotal) AS Total
	FROM InOutStockTable a
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	WHERE (a.BillType=34 OR (a.BillType=161 AND a.CostTotal>0)  OR a.BillType=205) AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0
	--OR ((a.BillType=34 OR (a.BillType=161 AND a.CostTotal>0)  OR a.BillType<>205) AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0)
) b
WHERE SumName='BuyTotal'

UPDATE #AType
SET Total=ABS(ISNULL(b.Total,0))
FROM
(
	SELECT SUM(a.CostTotal) AS Total
	FROM InOutStockTable a
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	WHERE (a.BillType=6 OR (a.BillType=161 AND a.CostTotal<0)) AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0
) b
WHERE SumName='BuyBackTotal'

---暂估入库
UPDATE #AType
SET Total=ISNULL(b.Total,0)
FROM
(
	SELECT SUM(a.CostTotal) AS Total
	FROM InOutStockTable a
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	WHERE a.BillType=400  AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0
) b
WHERE SumName='AppraisalBill'
--暂估退货
UPDATE #AType
SET Total=ABS(ISNULL(b.Total,0))
FROM
(
	SELECT SUM(a.CostTotal) AS Total
	FROM InOutStockTable a
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	WHERE a.BillType=401  AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0
) b
WHERE SumName='AppraisalBackBill'



UPDATE #AType
SET Total=ISNULL(b.Total,0)
FROM
(
	SELECT SUM(a.CostTotal) AS Total
	FROM InOutStockTable a
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	WHERE a.BillType=144 AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0 AND a.KTypeID<>'10000'
) b
WHERE SumName='EntrustTotal'

UPDATE #AType
SET Total=ABS(ISNULL(b.Total,0))
FROM
(
	SELECT SUM(a.Total) AS Total
	FROM InOutStockTable a
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	WHERE a.BillType=146 AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0 AND a.KTypeID='10000'
) b
WHERE SumName='EntrustBackTotal'


UPDATE #AType
SET Total=ISNULL(b.Total,0)
FROM
(
	SELECT SUM(CASE WHEN SumName IN ('BuyTotal','EntrustTotal','AppraisalBill') THEN Total ELSE -Total END) AS Total
	FROM #AType
	WHERE SumName IN ('BuyTotal','BuyBackTotal','EntrustTotal','EntrustBackTotal','AppraisalBackBill','AppraisalBill')
) b
WHERE SumName='InOutTotal'


------库存期初
DECLARE	@strStock	VARCHAR(100),
		@Total00	 NUMERIC(24, 10) 

--SELECT @strStock='0000100001'


SELECT @strStock=nId FROM  Ac_Items WHERE UserCode='1241'

SELECT	@Total00=ISNULL(SUM(Total00),0)
FROM	AType_Total 
WHERE	ATypeID=@strStock AND AType_Total.STypeID IN(SELECT TypeId FROM #GetManSTypeId)
 
	
UPDATE	#AType
SET		Total=ISNULL(b.Total,0)+@Total00
FROM
(
	SELECT SUM(a.CostTotal) AS Total
	FROM InOutStockTable a
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	WHERE a.ATypeID=@strStock AND a.BillDate<@chvStartDate AND b.RedWord=0 AND a.KTypeID<>'10000'
	AND a.STypeID IN(SELECT typeid FROM #GetManSTypeId)
) b
WHERE SumName='IniStock'

  

UPDATE	#AType
SET		Total=ISNULL(b.Total,0)
FROM
(
	SELECT SUM(a.CostTotal) AS Total
	FROM InOutStockTable a
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	INNER JOIN #GetManSTypeId S ON S.TypeId = b.STypeId
	WHERE 
	--(a.billtype<>205 AND a.ATypeID=@strStock AND a.CostTotal>0 AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0 AND a.KTypeID<>'10000') OR 
	a.ATypeID=@strStock AND a.CostTotal>0 AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0 AND a.KTypeID<>'10000'
) b
WHERE SumName='InStock'

UPDATE	#AType
SET		Total=ABS(ISNULL(b.Total,0))
FROM
(
	SELECT SUM(a.CostTotal) AS Total
	FROM InOutStockTable a
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
	WHERE a.ATypeID=@strStock AND a.CostTotal<0 AND a.BillDate BETWEEN @chvStartDate AND @chvEndDate AND b.RedWord=0 AND a.KTypeID<>'10000'
) b
WHERE SumName='OutStock'

UPDATE	#AType
SET		Total=b.Total
FROM
(
	SELECT SUM(CASE SumName WHEN 'OutStock' THEN -Total ELSE Total END) AS Total
	FROM #AType
	WHERE SumName IN ('IniStock','InStock','OutStock')
) b
WHERE #AType.SumName='AllStock'

SELECT * FROM #AType ORDER BY ShowOrder

DROP TABLE #AType,#GetManSTypeId,#A





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryBTypeAnsi]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryBTypeAnsi]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：谢吉康
	日期：2010-08-09
	描述：供货商销售情况分析
*/

/*
    修改人：黄飞佳
    日期：  2012-06-06
    描述：  添加浮动单位列、计量单位及多单位计算
*/

/*
	修改: 魏伟
	日期: 2015-05-24
	描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
*/

/*
	修改: 舒珊
	日期: 2016-07-11
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Qp_QueryBTypeAnsi
(
	@OperatorId		    VARCHAR(100),			--操作员ID
	@StartDate			VARCHAR(20),
	@EndDate			VARCHAR(20),
	@PTypeId			VARCHAR(MAX),
	@dealBTypeId		VARCHAR(8000),
	@unitconvert        VARCHAR(10),			--换算率标示
	@ptypecategoryid    VARCHAR(MAX),			--商品类别ID
	@stypeid			VARCHAR(MAX) = '00001'	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
        @UnitName   NVARCHAR(2000),
        @temptable  NVARCHAR(2000),
        @sqltmp VARCHAR(8000)
CREATE TABLE #GetManPTypeALL
(
	typeid VARCHAR(50),
	saleunitrate  NUMERIC(24, 10) ,
	saleunitfullname VARCHAR(50),
	buyunitrate  NUMERIC(24, 10) ,
	buyunitfullname VARCHAR(50),
	stockunitrate  NUMERIC(24, 10) ,
	stockunitfullname VARCHAR(50),
	baseunitfullname VARCHAR(50),
)

SET @sqltmp='Insert into #GetManPTypeALL 
					SELECT 
							typeId,
							saleUnitRate,
							saleunitfullname,
							buyUnitRate,
							buyunitfullname,
							stockUnitRate,
							stockunitfullname,
							baseunitfullname 
					FROM F_GetManPTypeDetailALL('''+@OperatorId+''')
					'
EXEC(@sqltmp)

CREATE CLUSTERED INDEX CIX_PTYPEID ON #GetManPTypeALL(typeId)


IF @unitconvert=0
BEGIN
SELECT @temptable =dbo.F_GetPtypeUnitsAndRates('p1','1,3','3'),
	@Qty='b.qty/isnull(r3.rate,1)',
	@UnitName='u3.fullname'
END
IF @unitconvert=1
BEGIN
SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,2','2'),
	@Qty='b.qty/isnull(r2.rate,1)',
	@UnitName='u2.fullname'
END
IF @unitconvert=2
BEGIN
SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,4','4'),
	@Qty='b.qty/isnull(r4.rate,1)',
	@UnitName='u4.fullname'
END
IF @unitconvert=3
BEGIN
SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1','1'),
	@Qty='b.qty',
	@UnitName='u1.fullname'
END


--------多单位计算End---------
----------------------------------------------------------------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
CREATE NONCLUSTERED INDEX CIX_PType ON #GetManPTypeId(TypeID)

INSERT INTO #GetManPTypeId(TypeId) 
SELECT 	DISTINCT TypeId 
FROM 	F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
CREATE NONCLUSTERED INDEX CIX_SType ON #GetManSTypeId(TypeID)

INSERT INTO #GetManSTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) S


CREATE TABLE #PtypeID
(
	PtypeID VARCHAR(50)
)
SET @sqltmp='Insert into #PtypeID
			SELECT	I.PtypeID 
			FROM	InOutStockTable I 
			inner join billindex b on i.BillNumberId=b.BillNumberId
			INNER JOIN #GetManPTypeId P ON P.TypeId = I.PtypeId 
			INNER JOIN #GetManSTypeId S ON I.STypeId = S.TypeId
			WHERE	I.BillDate>='''+@StartDate+'''
					AND I.BillDate<='''+@EndDate+'''
					AND b.BillDate>='''+@StartDate+'''
					AND b.BillDate<='''+@EndDate+'''
					AND I.Audited = 1
					AND I.BillType IN (34,6,145,161)
					AND  B.dealBTypeId LIKE '+CHAR(39)+@dealBTypeId+'%''
			GROUP BY I.PtypeID'
EXEC(@sqltmp)

--中间结果
CREATE TABLE #InOutStockTable
(
	PTypeId			VARCHAR(100),
	CgQty			 NUMERIC(24, 10) ,
	XsQty			 NUMERIC(24, 10) ,
	CostTotal		 NUMERIC(24, 10) ,
	Total			 NUMERIC(24, 10) ,
	TaxTotal         NUMERIC(24, 10) ,
	cgnqty			 NUMERIC(24, 10) ,
	xsnqty			 NUMERIC(24, 10) ,
	numname			VARCHAR(100)
)		

SET @sqltmp='
INSERT INTO #InOutStockTable
  SELECT	B.PTypeId,
			SUM(
				CASE
					WHEN BillType IN (34,6,161) THEN '+@Qty+'
					WHEN BillType IN (145) THEN -1*'+@Qty+'
					ELSE 0
				END
			) AS CgQty,
			SUM(
				CASE
					WHEN BillType IN (305,11,45,141,160,215,12,46) THEN -1*'+@Qty+'
					ELSE 0
				END
			) AS XsQty,
			SUM(
				CASE
					WHEN BillType IN (305,11,45,141,160,215,12,46) THEN -1*CostTotal
					ELSE 0
				END
			) AS CostTotal,
			SUM(
				CASE
					WHEN BillType IN (305,11,45,141,160,215,12,46) THEN -1*Total
					ELSE 0
				END
			) AS Total,
			SUM(
				CASE
					WHEN BillType IN (305,11,45,141,160,215,12,46) THEN -1*TaxTotal
					ELSE 0
				END
			) AS TaxTotal,
				SUM(
				CASE
					WHEN BillType IN (34,6,161) THEN b.nqty
					WHEN BillType IN (145) THEN -1*b.nqty
					ELSE 0
				END
			) AS cgnqty,
		SUM(
				CASE
					WHEN BillType IN (305,11,45,141,160,215,12,46) THEN -1*b.nqty
					ELSE 0
				END
			) AS xsnqty,
			'+@UnitName+'
  FROM 
  (
	SELECT	I.PtypeId,
			I.BillType,
			I.Qty,
			I.CostTotal,
			I.Total,
			I.TaxTotal,
			I.nqty AS nqty
	FROM	InOutStockTable I 
	INNER JOIN #PtypeID P ON P.PtypeId = I.PtypeId 
	INNER JOIN #GetManSTypeId S ON S.TypeId = I.STypeId
	WHERE	I.BillDate>='''+@StartDate+'''
			AND I.BillDate<='''+@EndDate+'''
			AND I.Audited = 1
			AND I.BillType IN (34,6,145,161,305)
			AND I.BTypeid LIKE '+CHAR(39)+@dealBTypeId+'%''
	UNION ALL
	SELECT	I.PtypeId,
			I.BillType,
			I.Qty,
			I.CostTotal,
			I.Total,
			I.TaxTotal,
			I.nqty AS nqty
	FROM	InOutStockTable I 
	INNER JOIN #PtypeID P ON P.PtypeId = I.PtypeId 
	INNER JOIN #GetManSTypeId S ON S.TypeId = I.STypeId
	WHERE	I.BillDate>='''+@StartDate+'''
			AND I.BillDate<='''+@EndDate+'''
			AND I.Audited = 1
			AND I.BillType IN (305,11,45,141,160,215,12,46)
	) B 	
	INNER JOIN ptype p1 on b.ptypeid=  p1.typeid
	'+@temptable+'
	GROUP BY B.PtypeId,'+@UnitName+''
	
--PRINT(@sqltmp)
EXEC(@sqltmp)

CREATE TABLE #Result
(
	PTypeId		VARCHAR(100),
	CgQty		 NUMERIC(24, 10) ,
	XsQty		 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	MaoLi		 NUMERIC(24, 10) ,
	MaoLiLv		 NUMERIC(24, 10) ,
	numname     VARCHAR(2000),
	cgnqty         NUMERIC(24, 10) ,
	xsnqty         NUMERIC(24, 10) 
)

DECLARE @SQL VARCHAR(8000)

SET @SQL = 'INSERT INTO #Result
			SELECT	B.PTypeId,
					ISNULL(b.CgQty,0) AS CgQty,
					ISNULL(b.XsQty,0) AS XsQty,
					ISNULL(b.CostTotal,0) AS CostTotal,
					ISNULL(b.Total,0) AS Total,
					ISNULL(b.TaxTotal,0) AS TaxTotal,
					MaoLi 	= ISNULL(b.Total,0) - ISNULL(b.CostTotal,0),
					MaoLiLv	= CAST(
					ISNULL(
					  CASE
						WHEN ISNULL(b.Total,0) = 0 THEN 0
						ELSE (ISNULL(b.Total,0) - ISNULL(b.CostTotal,0))/ISNULL(b.Total,0)
					  END,0)*100 AS  NUMERIC(24, 10) ),
					b.numname,
					b.cgnqty,b.xsnqty
			FROM	#InOutStockTable B'
--PRINT(@SQL)
EXEC(@SQL)	




SELECT 	P.TypeId,
		ISNULL(M.CgQty,0) AS CgQty,
		ISNULL(M.XsQty,0) AS XsQty,
		ISNULL(M.CostTotal,0) AS CostTotal,
		ISNULL(M.Total,0) AS Total,
		ISNULL(M.TaxTotal,0) AS TaxTotal,
		ISNULL(M.MaoLi,0) AS MaoLi,
		ISNULL(M.MaoLiLv,0) AS MaoLiLv,
		M.numname AS numname,
		ISNULL(M.cgnqty,0) AS cgnqty,
		ISNULL(M.xsnqty,0) AS xsnqty
FROM	ptype P
INNER JOIN (
	SELECT	PTypeId,
			CgQty,
			XsQty,
			CostTotal,
			Total,
			TaxTotal,
			MaoLi,
			MaoLiLv,
			r.numname,
			r.cgnqty,
			r.xsnqty
	FROM 	#Result	r			  
)M ON P.TypeId = M.PTypeId 
WHERE	P.SonNum = 0
ORDER BY P.UserCode

DROP TABLE #Result,#GetManPTypeId,#InOutStockTable,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

       



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryHisSaleInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryHisSaleInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-10
	描述：历史销售情况
	EXEC Qp_QueryHisSaleInfo '00001','1900-01-01','2010-08-10','',''
*/
CREATE PROCEDURE Qp_QueryHisSaleInfo
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@PTypeId		VARCHAR(8000),
	@BTypeId		VARCHAR(100),
	@STypeid        VARCHAR(8000)='00001',
	@billtype		VARCHAR(10)='11'
)
--@encode$--
AS
SET NOCOUNT ON

-----------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM PType WHERE SonNum = 0 AND TypeId LIKE @PTypeId + '%' --F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeid,11,@OperatorID)

CREATE CLUSTERED INDEX CIX_GetManBTypeID ON #GetManBTypeId(TypeID)
CREATE CLUSTERED INDEX CIX_GetManKTypeID ON #GetManKTypeId(TypeID)
CREATE CLUSTERED INDEX CIX_GetManPTypeID ON #GetManPTypeId(TypeID)
CREATE CLUSTERED INDEX CIX_GetManSTypeID ON #GetManSTypeId(TypeID)

DECLARE @SaleBillTable VARCHAR(50),
		@SaleBackBillTable VARCHAR(50)

--销售单临时表
CREATE TABLE #SaleBill
(
	BillNumberID INT,
	SalePrice    NUMERIC(24,10),
	TaxPrice	 NUMERIC(24,10),
	Tax			 NUMERIC(24,10),
	Comment      VARCHAR(1000),
	Qty			 NUMERIC(24,10),
	BackQty		 NUMERIC(24,10),
	TaxTotal	 NUMERIC(24,10),
	Total		 NUMERIC(24,10),
	ItemID		 INT,
	IsCombined   INT,
	GoodsNumber  VARCHAR(100),
	PTypeID		 VARCHAR(100),
	KTypeID		 VARCHAR(100)
)

	INSERT INTO #SaleBill
			( BillNumberID ,
			  SalePrice ,
			  TaxPrice ,
			  Tax ,
			  Comment ,
			  Qty ,
			  BackQty ,
			  ItemID ,
			  IsCombined ,
			  GoodsNumber ,
			  PTypeID,
			  TaxTotal,
			  Total,
			  KTypeID
			)
	SELECT A.BillNumberId,
		   A.SalePrice,
		   A.TaxPrice,
		   A.Tax,
		   A.comment,
		   A.Qty,
		   A.BackQty,
		   A.ItemID,
		   A.IsCombined,
		   '',
		   A.PtypeId,
		   A.TaxTotal,
		   A.total,
		   A.KTypeID
	FROM dbo.PT_Combin_SaleBill A 
	INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.ifcheck='t' AND b.RedWord=0
	INNER JOIN #GetManPTypeId P ON P.TypeId = A.PTypeId
	
	INSERT INTO #SaleBill
	        ( BillNumberID ,
	          SalePrice ,
	          TaxPrice ,
	          Tax ,
	          Comment ,
	          Qty ,
	          BackQty ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          PTypeID,
	          TaxTotal,
	          Total,
	          KTypeID
	        )
	SELECT A.BillNumberId,
		   -1*A.SalePrice,
		   -1*A.TaxPrice,
		   A.Tax,
		   A.comment,
		   -1*A.Qty,
		   0,
		   A.ItemID,
		   A.IsCombined,
		   '',
		   A.PtypeId,
		   -1*A.TaxTotal,
		   -1*A.Total,
		   A.ktypeid
	FROM dbo.PT_Combin_SaleBackBill A 
	INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.ifcheck='t' AND b.RedWord=0
	INNER JOIN #GetManPTypeId P ON P.TypeId = A.PTypeId

	INSERT INTO #SaleBill
	        ( BillNumberID ,
	          SalePrice ,
	          TaxPrice ,
	          Tax ,
	          Comment ,
	          Qty ,
	          BackQty ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          PTypeID,
	          TaxTotal,
	          Total,
	          KTypeID
	        )
	SELECT A.BillNumberId,
		   A.SalePrice,
		   A.TaxPrice,
		   A.Tax,
		   A.comment,
		   A.Qty,
		   A.BackQty,
		   A.ItemID,
		   A.IsCombined,
		   A.GoodsNumber,
		   A.PtypeId,
		   A.TaxTotal,
		   A.total,
		   A.KTypeID
	FROM dbo.SaleBill A 
	INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.ifcheck='t' AND b.RedWord=0
	INNER JOIN #GetManPTypeId P ON P.TypeId = A.PTypeId
	
	INSERT INTO #SaleBill
	        ( BillNumberID ,
	          SalePrice ,
	          TaxPrice ,
	          Tax ,
	          Comment ,
	          Qty ,
	          BackQty ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          PTypeID,
	          TaxTotal,
	          Total,
	          KTypeID
	        )
	SELECT A.BillNumberId,
		   -1*A.SalePrice,
		   -1*A.TaxPrice,
		   A.Tax,
		   A.comment,
		   -1*A.Qty,
		   0,
		   A.ItemID,
		   A.IsCombined,
		   A.GoodsNumber,
		   A.PtypeId,
		   -1*A.TaxTotal,
		   -1*A.Total,
		   A.KTypeID
	FROM dbo.saleBackBill A 
	INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND B.ifcheck='t' AND b.RedWord=0
	INNER JOIN #GetManPTypeId P ON P.TypeId = A.PTypeId

DECLARE @SQL VARCHAR(8000)
SET @SQL = 'SELECT	Bi.BillNumberId,
					Bi.BillDate,
					Bi.BillCode,
					Bi.BillType,
					Bi.STypeId,
					CASE 
						WHEN Bi.BillType = 11  THEN ''销售出库单''
						WHEN Bi.BillType = 12 THEN ''组合品销售出库单''
						WHEN Bi.BillType = 45 THEN ''销售退货单''
						WHEN Bi.BillType = 46 THEN ''组合品销售退货单'' 
						ELSE ''''
					END AS BillTypeName,
					Bi.BTypeId,
					Bi.dealbtypeid,
					(select usercode from btype where typeid=Bi.dealbtypeid) as dusercode,
					(select fullname from btype where typeid=Bi.dealbtypeid) as dfullname,
					SUM(MX.Qty) AS Qty,
					ABS(MX.SalePrice) AS Price,
					ABS(MX.TaxPrice) AS TaxPrice,
					SUM(MX.Total) AS Total,
					SUM(MX.TaxTotal) AS TaxTotal,
					CAST(MX.Tax AS NUMERIC(18,0)) AS Tax,
					B.LinkMan1,
					B.LinkTel1,
					MX.Comment,
					ISNULL(SUM(Mx.BackQty),0) AS BackQty,
					Mx.GoodsNumber AS GoodsNumber ,
					pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=MX.ItemId,
					itemname= CASE WHEN MX.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= Mx.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= Mx.ItemId ) END,
					iscombined=Mx.IsCombined
			FROM 	BillIndex Bi			
			INNER JOIN #SaleBill MX ON Mx.BillNumberID=Bi.BillNumberID
			INNER JOIN dbo.PType pt ON Mx.PTypeID = pt.TypeID
			'
			
			IF @MKtypeid='-99999' OR @PTypeId<>''
				SET @SQL=@SQL+' INNER JOIN #GetManKTypeId K ON Mx.KTypeId = K.TypeId '
			SET @SQL=@SQL+' INNER JOIN BType B ON B.TypeId = Bi.dealbtypeid '
			IF @MBtypeid='-99999' OR @BTypeId<>''
				SET @SQL=@SQL+'	INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.TypeId'
			SET @SQL=@SQL+'
				INNER JOIN #GetManSTypeId S ON Bi.Stypeid = S.TypeId
				WHERE	Bi.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
						AND Bi.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
						AND Bi.IfCheck = ''t''
						AND Bi.RedWord = 0
						AND Bi.BillType IN (11,12,45,46)
				GROUP BY Bi.BillNumberId,
  						 Bi.BillDate,
						 Bi.BillCode,
						 Bi.BillType,
						 Bi.STypeId,
						 Bi.BTypeId,
						 Bi.dealbtypeid,
						 Mx.SalePrice,
						 Mx.TaxPrice,
						 Mx.Tax,
						 B.LinkMan1,
						 B.LinkTel1,
						 MX.Comment,
						 pt.customitemid,
						 pt.customitemfrom,
						 pt.customitemname,
						 pt.customitemrefid,		        
						 Mx.ItemId,
						 Mx.IsCombined,
						 Mx.GoodsNumber
				ORDER BY Bi.BillDate DESC'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManPTypeId,#GetManBTypeId,#GetManKTypeId,#SaleBill--,#MxTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryHistoryBjKcXj]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryHistoryBjKcXj]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-09-13
	描述：历史报价、虚拟库存询价
	SELECT * FROM OrderIndex
*/
CREATE PROCEDURE Qp_QueryHistoryBjKcXj
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@PTypeId		VARCHAR(8000),
	@OrderType		VARCHAR(100),	--2.全部  0.未成交  1.已成交
	@nType			VARCHAR(100), 	--Bj.历史报价 KcXj.虚拟库存询价
	@BTypeId		VARCHAR(8000),	--往来单位
	@STypeId		VARCHAR(MAX)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @BillType 	VARCHAR(10),
		@MainTable	VARCHAR(100),
		@MxTable	VARCHAR(100),
		@OrderBy	VARCHAR(100)
IF @nType = 'Bj'
	BEGIN
		SET @BillType = 184
		SET @MainTable = 'BillIndex'
		SET @MxTable = 'QuotePriceBill'
		SET @OrderBy = ' ORDER BY Bi.BillDate DESC,Bi.BillCode DESC '
	END
ELSE
	BEGIN
		SET @BillType = 185
		SET @MainTable = 'BillIndex'
		SET @MxTable = 'AskPriceBill'
		SET @OrderBy = ' ORDER BY Bi.BillDate DESC,Bi.BillCode DESC  '
	END



--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM PType WHERE SonNum = 0 AND TypeId LIKE @PTypeId + '%' --F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
--INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE SonNum = 0
INSERT INTO #GetManKTypeId(TypeId)VALUES('')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

DECLARE @SQL VARCHAR(8000)

SET @SQL = 'SELECT	Bi.BillNumberId,
					Bi.BillDate,
					Bi.BillCode,
					Bi.BillType, 
					CASE 
						WHEN Bi.IfBargainOn = 0 THEN ''未成交''
						WHEN Bi.IfBargainOn = 1 THEN ''已成交''
						ELSE ''全部''
					END AS OrderType,
					Bi.BTypeId,
					Bi.STypeId,
					SUM(I.Qty) AS Qty,
					ABS(I.DiscountPrice) AS Price,
					SUM(I.Total) AS Total,
					ABS(I.TaxPrice) AS TaxPrice,
					SUM(I.TaxTotal) AS TaxTotal,
					pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=I.ItemId,
					itemname= CASE WHEN I.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= I.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= I.ItemId ) END,
					iscombined=I.IsCombined,
					I.Comment,
					Bi.DealBTypeID,
					(select usercode from btype where typeid=Bi.DealBTypeID) as dealusercode,
					(select fullname from btype where typeid=Bi.DealBTypeID) as dealname
			FROM 	'+@MainTable+' Bi
			INNER JOIN '+@MxTable+' I ON I.BillNumberId = Bi.BillNumberId
			--INNER JOIN #GetManKTypeId K ON Bi.KTypeId = K.TypeId
			INNER JOIN BType B ON B.TypeId = Bi.DealBTypeID
			INNER JOIN #GetManPTypeId P ON P.TypeId = I.PTypeId
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.TypeId
			INNER JOIN #GetManSTypeId S ON S.TypeId = Bi.STypeId
            INNER JOIN dbo.PType pt ON I.PTypeID = pt.TypeID
			WHERE	Bi.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND Bi.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
					AND Bi.BillType IN ('+CHAR(39)+@BillType+CHAR(39)+') '


		IF @OrderType = '0'
			SET @SQL = @SQL + ' AND ISNULL(Bi.IfBargainOn,'''') = ''0'''
		ELSE IF @OrderType = '1'
			SET @SQL = @SQL + ' AND ISNULL(Bi.IfBargainOn,'''') = ''1'''
		ELSE
			SET @SQL = @SQL + ' AND 1 = 1 '

SET @SQL = @SQL + '
			GROUP BY Bi.BillNumberId,
  					 Bi.BillDate,
					 Bi.BillCode,
					 Bi.BillType,
					 Bi.IfBargainOn,
					 Bi.BTypeId,
					 Bi.STypeId,
					 Bi.DealBTypeID,
					 I.DiscountPrice,
					 I.TaxPrice,
					 I.Comment,
					 pt.customitemid,
					 pt.customitemfrom,
					 pt.customitemname,
					 pt.customitemrefid,		        
					 I.ItemId,
					 I.IsCombined
					  '

SET @SQL = @SQL + @OrderBy

PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManPTypeId,#GetManBTypeId,#GetManKTypeId,#GetManSTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryLoseBtypeAnsi]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryLoseBtypeAnsi]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢XX
	日期：2010-08-9
	描述：流失客户分析
	
	
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/

CREATE PROCEDURE Qp_QueryLoseBtypeAnsi
(
	@OperatorId		VARCHAR(100),
	@BTypeId		VARCHAR(8000),
	@Ts				NUMERIC(18,0),
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @MxBTypeId VARCHAR(100)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'BTypeAll' AND Value = '0')
	INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) WHERE TypeId LIKE '00001%'
ELSE
	INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) WHERE TypeId LIKE '00001%'
CREATE TABLE #GetManStypeId(TypeId	varchar(100))
	INSERT INTO #GetManStypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

CREATE TABLE #BillIndex
(
	dealBTypeId		VARCHAR(100),
	BillDate	DATETIME,
	LinkMan1	VARCHAR(400),
	LinkTel1	VARCHAR(400),
	WyeTs		NUMERIC(18,0),
	areatypeid  VARCHAR(200)	
)
        INSERT  INTO #BillIndex
                ( dealBTypeId ,
                  BillDate	
		        )
                SELECT  Bi.DealBTypeID ,
                        MAX(BillDate)
                FROM    BillIndex Bi ,
                        #GetManStypeId s ,
                        #GetManBTypeId bb
                WHERE   Bi.DealBTypeID = bb.TypeId
                        AND Bi.ifcheck = 't'
                        AND Bi.BillType IN ( 11, 305, 140 ,12)
                        AND Bi.RedWord = 0
                        AND Bi.ifYearBill = '0' --年节存标志
                        AND bi.Stypeid = s.TypeId
                GROUP BY Bi.DealBTypeID
                HAVING  DATEDIFF(DAY, MAX(BillDate), GETDATE()) >= @Ts
        UPDATE  #BillIndex
        SET     LinkMan1 = b.LinkMan1 ,
                LinkTel1 = b.LinkTel1 ,
                AreaTypeID = CASE WHEN b.AreaTypeID = '' THEN '99999'
                                  ELSE b.AreaTypeID
                             END ,
                WyeTs = DATEDIFF(DAY, BillDate, GETDATE())
        FROM    #BillIndex a
                INNER JOIN dbo.btype b ON a.dealBTypeId = b.typeId

        SELECT  *
        FROM    #BillIndex
        ORDER BY BillDate DESC

DROP TABLE #GetManBTypeId,#BillIndex

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryLoseBtypeAnsiChart]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryLoseBtypeAnsiChart]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：
*/


/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Qp_QueryLoseBtypeAnsiChart
(
	@OperatorId		VARCHAR(100),
	@BTypeId		VARCHAR(8000),
	@Ts				NUMERIC(18,0),
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @MxBTypeId VARCHAR(100)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'BTypeAll' AND Value = '0')
	INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) WHERE TypeId LIKE '00001%'
ELSE
	INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) WHERE TypeId LIKE '00001%'
CREATE TABLE #GetManStypeId(TypeId	varchar(100))
	INSERT INTO #GetManStypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

CREATE TABLE #BillIndex
(
	dealBTypeId		VARCHAR(100),
	BillDate	DATETIME,
	LinkMan1	VARCHAR(400),
	LinkTel1	VARCHAR(400),
	WyeTs		NUMERIC(18,0),
	areatypefullname  VARCHAR(200)	
)

        INSERT  INTO #BillIndex
                ( dealBTypeId ,
                  BillDate
			
		        )
                SELECT  Bi.DealBTypeID ,
                        MAX(BillDate)
                FROM    BillIndex Bi ,
                        #GetManStypeId s ,
                        #GetManBTypeId bb
                WHERE   Bi.DealBTypeID = bb.TypeId
                        AND Bi.ifcheck = 't'
                        AND Bi.BillType IN ( 11, 305, 140,12 )
                        AND Bi.RedWord = 0
                        AND Bi.ifYearBill = '0' --年节存标志
                        AND bi.Stypeid = s.TypeId
                GROUP BY Bi.DealBTypeID
                HAVING  DATEDIFF(DAY, MAX(BillDate), GETDATE()) >= @Ts
        UPDATE  #BillIndex
        SET     LinkMan1 = b.LinkMan1 ,
                LinkTel1 = b.LinkTel1 ,
                areatypefullname = CASE WHEN b.AreaTypeID = '' THEN '其他地区'
                                        ELSE c.fullname
                                   END ,
                WyeTs = DATEDIFF(DAY, BillDate, GETDATE())
        FROM    #BillIndex a
                INNER JOIN dbo.btype b ON a.dealBTypeId = b.typeId
                LEFT JOIN AreaType c ON b.AreaTypeID = c.typeid
	

SELECT COUNT(dealBTypeId)count,areatypefullname FROM #BillIndex GROUP BY areatypefullname

DROP TABLE #GetManBTypeId,#BillIndex

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryMiantenanceInfoList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].QP_QueryMiantenanceInfoList
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-09-09
	描述：车辆保养档案信息
*/
CREATE PROCEDURE QP_QueryMiantenanceInfoList
(
	@repairautotypeid			varchar(100)		--维修车型ID
)
--@encode$--
AS
SET NOCOUNT ON

IF @repairautotypeid='00000'
	SET @repairautotypeid='0000'				--查询所有
SELECT	r.TypeID,
		r.FullName,
		m.ID,
		m.hightMileage,
		m.lowMileage
FROM	qp_miantenanceinfo m
INNER JOIN QP_RepairAutoType R ON M.RepairAutoTypeID=R.TypeID
WHERE	r.TypeID like @repairautotypeid+'%' and r.SonNum=0
ORDER BY M.RepairAutoTypeID,m.lowMileage

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryMulStockConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryMulStockConfig]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-8-12
	描述：多仓库配置
	EXEC Qp_QueryMulStockConfig '00001','2'
	2013-05-09 周华 添加获赠单 赠送单多仓库
*/

CREATE PROCEDURE Qp_QueryMulStockConfig
(
	@OperatorId		VARCHAR(100),
	@Flag			VARCHAR(20)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @ProInfo INT=0  --版本1:V3 2:A8 4:V1
SELECT @ProInfo=SubValue FROM SysData WHERE SubName='ProInfo'

CREATE TABLE #BillType
(
	BillType 	INT
)

IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'QpEdition' AND SubValue = '1')
	BEGIN
		INSERT INTO #BillType(BillType) SELECT BillType FROM Qp_MulStockConfig WHERE BillType IN (11,12,45,46,34,6,178)
	END
ELSE IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'QpEdition' AND SubValue = '2')	
	BEGIN
		INSERT INTO #BillType(BillType) SELECT BillType FROM Qp_MulStockConfig WHERE BillType NOT IN (191,197,196)
	END
ELSE IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'QpEdition' AND SubValue = '3')
	BEGIN
		INSERT INTO #BillType(BillType) SELECT BillType FROM Qp_MulStockConfig WHERE BillType IN (11,12,45,46,34,6,178,183)
	END
ELSE 
	BEGIN
		INSERT INTO #BillType(BillType) SELECT BillType FROM Qp_MulStockConfig
	END

IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '3' OR SubValue = '4')) 
BEGIN
	DELETE FROM #BillType WHERE BillType IN (187,188)
END

IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='isinvoice' AND SubValue='1')
BEGIN
	DELETE FROM #BillType WHERE BillType IN (400,401,402,403)
END
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName='CombinAtionProduct' AND SubValue='1')
BEGIN
	DELETE FROM #BillType WHERE BillType IN (12,46,313)
END
	
--是否启用门店配送
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Userconfig WHERE ConfigName = 'usepostrans' AND Value = '1')
BEGIN
	DELETE FROM #BillType WHERE BillType IN (327)
END
	
IF @Flag = 0 --销售类
	SELECT 	B.BillName,
			B.BillType,
			M.IsChecked AS selected
	FROM    BillName B
	LEFT JOIN (
		SELECT 	BillType,
				IsChecked
		FROM	Qp_MulStockConfig
	)M ON M.BillType = B.Billtype
	WHERE 	(B.Billtype IN (300,11,12,45,46,313,160,140,142) OR (@ProInfo<>4 AND B.Billtype IN(139,402,403)))
			AND B.BillType IN (SELECT BillType FROM #BillType)
ELSE IF @Flag = 1 --采购类
	SELECT 	B.BillName,
			B.BillType,
			M.IsChecked AS selected
	FROM    BillName B
	LEFT JOIN (
		SELECT 	BillType,
				IsChecked
		FROM	Qp_MulStockConfig
	)M ON M.BillType = B.Billtype 
	WHERE (B.Billtype IN (301,34,6,161,144,146) OR (@ProInfo<>4 AND B.Billtype IN(126,400,401)))
		  AND B.BillType IN (SELECT BillType FROM #BillType)
ELSE IF @Flag = 2--库存类	
	SELECT 	B.BillName,
			B.BillType,	
			M.IsChecked AS selected
	FROM    BillName B
	LEFT JOIN (
		SELECT 	BillType,
				IsChecked
		FROM	Qp_MulStockConfig
	)M ON M.BillType = B.Billtype 
	WHERE (B.Billtype IN (16,17,21,201,202,327) OR (@ProInfo<>4 AND B.Billtype IN(187,188)))
		  AND B.BillType IN (SELECT BillType FROM #BillType)
ELSE IF @Flag = 3--维修类
	SELECT 	B.BillName,
			B.BillType,	
			M.IsChecked AS selected
	FROM    BillName B
	LEFT JOIN (
		SELECT 	BillType,
				IsChecked
		FROM	Qp_MulStockConfig
	)M ON M.BillType = B.Billtype 
	WHERE B.Billtype IN (178,191,196,197)  
		  AND B.BillType IN (SELECT BillType FROM #BillType)
ELSE IF @Flag = 4--会员类
	SELECT 	B.BillName,
			B.BillType,	
			M.IsChecked AS selected
	FROM    BillName B
	LEFT JOIN (
		SELECT 	BillType,
				IsChecked
		FROM	Qp_MulStockConfig
	)M ON M.BillType = B.Billtype 
	WHERE B.Billtype IN (183)  	
		  AND B.BillType IN (SELECT BillType FROM #BillType)
ELSE IF @Flag = 5 --成本费用管理
	SELECT 	B.BillName,
			B.BillType,	
			M.IsChecked AS selected
	FROM    BillName B
	LEFT JOIN (
		SELECT 	BillType,
				IsChecked
		FROM	Qp_MulStockConfig
	)M ON M.BillType = B.Billtype 
	WHERE B.Billtype IN (57)  	
		  AND B.BillType IN (SELECT BillType FROM #BillType)		  
ELSE 
	SELECT 	B.BillName,
			B.BillType,	
			0 AS selected
	FROM    BillName B
	WHERE Billtypes=-1
	
DROP TABLE #BillType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryPtypeCargoSpace]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryPtypeCargoSpace]
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryRecycleData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryRecycleData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:谢吉康
	日期:2010-08-09
	描述:旧件回收查询
*/

CREATE PROCEDURE Qp_QueryRecycleData
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@ETypeId		VARCHAR(8000),
	@DTypeId		VARCHAR(8000),
	@PTypeId		VARCHAR(8000),
	@nType			VARCHAR(10),
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)
IF @DTypeId = ''
	INSERT INTO #GetManDTypeId(TypeId)VALUES('')

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

DECLARE @SQL 	VARCHAR(8000),
		@State	VARCHAR(10)

IF @nType = '9'
	SET @State = '%'
ELSE
	SET @State = @nType
	

SET @SQL = 'SELECT 	Bi.BillNumberId,
					Bi.BillDate,
					Bi.BillCode,
					C.PTypeID,
					CASE
						WHEN C.Status = 0 THEN ''在库''
						WHEN C.Status = 1 THEN ''报废''
						WHEN C.Status = 2 THEN ''翻新入库''
						WHEN C.Status = 3 THEN ''废品销售''
						ELSE ''''
					END AS Status,
					c.Status as StatusNum,
					C.Qty,
					C.Price,
					C.total,
					C.Comment,
					180 AS BillType
			FROM 	BillIndex Bi
					INNER JOIN QP_RecycleBill C ON Bi.BillNumberId = C.BillNumberId
					INNER JOIN PType P ON C.PTypeID = P.TypeId '
					
IF NOT (@ETypeId = '' AND @METypeId = '00001')
	SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = Bi.ETypeId '
	
IF NOT @DTypeId = ''
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Bi.DTypeId '
	
IF NOT (@PTypeId = '' AND @MPTypeId = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManPTypeId MP ON MP.TypeId = P.TypeId '
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '		

SET @SQL = @SQL + '
			WHERE	Bi.BillType = 180
					AND Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
					AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
					AND C.Status LIKE '+CHAR(39)+@State+CHAR(39)+'
					AND bi.ifYearBill=0	 --年节存标志
			ORDER BY Bi.BillDate ASC,Bi.BillCode ASC,P.UserCode ASC '

--PRINT(@SQL)
EXEC(@SQL)			

DROP TABLE #GetManETypeId,#GetManDTypeId,#GetManPTypeId,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairAutoInfoLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairAutoInfoLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-16
	描述：维修车辆信息档案-线性表
*/
CREATE PROCEDURE QP_QueryRepairAutoInfoLine
(
	@OperatorId		varchar(100),		--操作员ID
	@typeid			varchar(100),		--基本信息ID
	@PlateNumber	varchar(300),		--车牌号
	@Cx				varchar(300),		--车型
	@BTypeId		varchar(100)		--往来单位
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SELECT * INTO #RepairAutoInfo FROM QP_RepairAutoInfo WHERE 1=0

DECLARE @SQL VARCHAR(MAX)
SET @SQL='
INSERT INTO #RepairAutoInfo
SELECT * 
FROM	QP_RepairAutoInfo
	WHERE 	TypeId <> ''00000''
			AND SonNum = 0'
IF ISNULL(@TypeId,'')=''			
	SET @SQL=@SQL+CHAR(13)+'			AND BTypeId LIKE '+CHAR(39)+@BTypeId+'%'+CHAR(39)+'
				AND PlateNumber LIKE  '+CHAR(39)+'%'+@PlateNumber+'%'+CHAR(39)+'
				AND RepairAutoTypeID LIKE '+CHAR(39)+'%'+@Cx+'%'+CHAR(39)+''
ELSE
	SET @SQL=@SQL+' AND Sonnum=0 AND TYPEID like '+CHAR(39)+@TypeId+'%'+CHAR(39)			
SET @SQL=@SQL+'	ORDER BY PlateNumber'
EXEC(@SQL)
DECLARE @chvTypeId				varchar(300),
		@SonNum					varchar(300),
		@chvPlateNumber			varchar(300),
		@RepairAutoTypeID		varchar(300),
		@chvBTypeId				varchar(300),
		@ChargingStandardsID	varchar(300),
		@Color					varchar(300),
		@RecordDate				varchar(300),
		@ForceMaintainDate		varchar(300),
		@ForceMaintainMileage	varchar(300),
		@FirstMaintainDate		varchar(300),
		@FirstMaintainMileage	varchar(300),
		@Comment				varchar(400),
		@baoxianfullname		VARCHAR(500),
		@baoxianfullname1		VARCHAR(500),
		@chvPath				varchar(2000)

CREATE TABLE #Result
(
	TypeId					varchar(300),
	SonNum					varchar(300),
	PlateNumber				varchar(300),
	RepairAutoTypeID		varchar(300),
	BTypeId					varchar(300),
	ChargingStandardsID		varchar(300),
	Color					varchar(300),
	RecordDate				datetime,
	ForceMaintainDate		datetime,
	ForceMaintainMileage	varchar(300),
	FirstMaintainDate		datetime,
	FirstMaintainMileage	varchar(300),
	Comment					varchar(400),
	baoxianfullname			VARCHAR(500),
	Path					varchar(2000)
)


DECLARE Tmp_Cursor CURSOR FOR
	SELECT	TypeId,
			SonNum,
			PlateNumber,
			RepairAutoTypeID,
			BTypeId,
			ChargingStandardsID = (SELECT FullName FROM QP_ChargingStandards WHERE [ID] = ChargingStandardsID),
			Color,
			CASE WHEN CONVERT(VARCHAR(10),RecordDate,120)='1900-01-01' THEN NULL ELSE RecordDate END AS RecordDate,
			CASE WHEN CONVERT(VARCHAR(10),ForceMaintainDate,120)='1900-01-01' THEN NULL ELSE ForceMaintainDate END AS ForceMaintainDate,
			ForceMaintainMileage,
			CASE WHEN CONVERT(VARCHAR(10),FirstMaintainDate,120)='1900-01-01' THEN NULL ELSE FirstMaintainDate END AS FirstMaintainDate,
			FirstMaintainMileage,
			Comment
	FROM	#RepairAutoInfo
	--WHERE 	TypeId <> '00000'
			--AND SonNum = 0
			--AND BTypeId LIKE @BTypeId + '%'
			--AND PlateNumber LIKE '%'+@PlateNumber+'%'
			--AND RepairAutoTypeID LIKE @Cx + '%'
	ORDER BY PlateNumber

OPEN Tmp_Cursor 

FETCH NEXT FROM Tmp_Cursor INTO @chvTypeId,
								@SonNum,
								@chvPlateNumber,
								@RepairAutoTypeID,
								@chvBTypeId,
								@ChargingStandardsID,
								@Color,
								@RecordDate,
								@ForceMaintainDate,
								@ForceMaintainMileage,
								@FirstMaintainDate,
								@FirstMaintainMileage,
								@Comment

WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC Web_GetParentPath1 @chvTypeId,17,@chvPath OUTPUT

		--SELECT @baoxianfullname=fullname FROM btype WHERE typeid=(SELECT baoxianbtypeid FROM QP_RepairAutoInfo WHERE typeid=@chvTypeId)
	    SET @baoxianfullname1 =(SELECT fullname FROM btype WHERE typeid=(SELECT baoxianbtypeid FROM QP_RepairAutoInfo WHERE typeid=@chvTypeId))
	    --SELECT fullname FROM btype WHERE typeid= (SELECT baoxianbtypeid FROM QP_RepairAutoInfo WHERE typeid=@chvTypeId)
	    SELECT @baoxianfullname = CASE WHEN @baoxianfullname1 IS NULL THEN '' ELSE @baoxianfullname1  END
	    INSERT INTO #Result
		VALUES
		(
			@chvTypeId,
			@SonNum,
			@chvPlateNumber,
			@RepairAutoTypeID,
			@chvBTypeId,
			@ChargingStandardsID,
			@Color,
			CONVERT(varchar(10),@RecordDate,120),
			CONVERT(varchar(10),@ForceMaintainDate,120),
			@ForceMaintainMileage,
			CONVERT(varchar(10),@FirstMaintainDate,120),
			@FirstMaintainMileage,
			@Comment,
			@baoxianfullname,
			REPLACE(@chvPath,'\','＼')
		)

		FETCH NEXT FROM Tmp_Cursor INTO @chvTypeId,
										@SonNum,
										@chvPlateNumber,
										@RepairAutoTypeID,
										@chvBTypeId,
										@ChargingStandardsID,
										@Color,
										@RecordDate,
										@ForceMaintainDate,
										@ForceMaintainMileage,
										@FirstMaintainDate,
										@FirstMaintainMileage,
										@Comment
	END

CLOSE Tmp_Cursor
DEALLOCATE Tmp_Cursor

SELECT * FROM #Result ORDER BY PlateNumber

DROP TABLE #Result,#RepairAutoInfo


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairAutoInfoList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairAutoInfoList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-16
	描述：维修车辆信息档案-树型表
*/
CREATE PROCEDURE QP_QueryRepairAutoInfoList
(
	@OperatorId		varchar(100),		--操作员ID
	@TypeId			varchar(100)		--基本信息ID
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SonNum int

SELECT @SonNum = SonNum FROM QP_RepairAutoInfo WHERE TypeId = @TypeId

IF @SonNum = 0 
	SELECT	a.TypeId,
			a.SonNum,
			a.PlateNumber,
			a.RepairAutoTypeID,
			a.BTypeId,
			a.BaoxianBtypeid,
			b.FullName AS baoxianfullname,
			ChargingStandardsID = (SELECT FullName FROM QP_ChargingStandards WHERE [ID] = a.ChargingStandardsID),
			a.Color,
			CASE WHEN CONVERT(VARCHAR(10),a.RecordDate,120)='1900-01-01' THEN NULL ELSE a.RecordDate END AS RecordDate,
			CASE WHEN CONVERT(VARCHAR(10),a.ForceMaintainDate,120)='1900-01-01' THEN NULL ELSE a.ForceMaintainDate END AS ForceMaintainDate,
			a.ForceMaintainMileage,
			CASE WHEN CONVERT(VARCHAR(10),a.FirstMaintainDate,120)='1900-01-01' THEN NULL ELSE a.FirstMaintainDate END AS FirstMaintainDate,
			a.FirstMaintainMileage,
			a.Comment,
			a.Pycode
	FROM	QP_RepairAutoInfo a
	LEFT JOIN btype b ON a.BaoxianBtypeid=b.typeid
	WHERE 	a.TypeId = @TypeId 
			AND a.TypeId <> '00000' 
	ORDER BY PlateNumber
ELSE
	SELECT	a.TypeId,
			a.SonNum,
			a.PlateNumber,
			a.RepairAutoTypeID,
			a.BTypeId,
			a.BaoxianBtypeid,
			b.FullName AS baoxianfullname,
			ChargingStandardsID = (SELECT FullName FROM QP_ChargingStandards WHERE [ID] = a.ChargingStandardsID),
			a.Color,
			CASE WHEN CONVERT(VARCHAR(10),a.RecordDate,120)='1900-01-01' THEN NULL ELSE a.RecordDate END AS RecordDate,
			CASE WHEN CONVERT(VARCHAR(10),a.ForceMaintainDate,120)='1900-01-01' THEN NULL ELSE a.ForceMaintainDate END AS ForceMaintainDate,
			ForceMaintainMileage,
			CASE WHEN CONVERT(VARCHAR(10),a.FirstMaintainDate,120)='1900-01-01' THEN NULL ELSE a.FirstMaintainDate END AS FirstMaintainDate,
			a.FirstMaintainMileage,
			a.Comment,
			a.Pycode
	FROM	QP_RepairAutoInfo a
	LEFT JOIN btype b ON a.BaoxianBtypeid=b.typeid
	WHERE 	a.ParId = @TypeId 
			AND a.TypeId <> '00000' 
	ORDER BY PlateNumber

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairAutoTypeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairAutoTypeLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE QP_QueryRepairAutoTypeLine
(
	@OperatorID	varchar(100),
	@TypeId		varchar(100),
	@UserCode	varchar(200),
	@FullName	varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
Create TABLE #QP_RepairAutoType
(
	TypeId VARCHAR(100),
	UserCode VARCHAR(500),
	FullName VARCHAR(500)
)
DECLARE @SQL VARCHAR(MAX)
SET @SQL='
	INSERT INTO #QP_RepairAutoType
	SELECT	TypeId,UserCode,FullName 
	FROM	QP_RepairAutoType 
	WHERE	TypeId <> ''00000'' 
			AND SonNum = 0 '
IF ISNULL(@TypeId,'')<>''
	SET @SQL=@SQL+CHAR(13)+' AND TypeId LIKE '+CHAR(39)+@TypeId+'%'+CHAR(39)
ELSE 
BEGIN
	SET @SQL=@SQL+CHAR(13)+' AND UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)
	SET @SQL=@SQL+CHAR(13)+' AND FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)
END
exec( @SQL)


CREATE TABLE #Result
(
	TypeId		varchar(100),
	UserCode	varchar(200),
	FullName	varchar(200),
	Path		varchar(2000)
)

DECLARE @chvTypeId		varchar(100),
		@chvUserCode	varchar(200),
		@chvFullName	varchar(200),
		@chvPath		varchar(2000)

DECLARE AutoCursor CURSOR FOR
	SELECT TypeId,UserCode,FullName FROM #QP_RepairAutoType ORDER BY UserCode

OPEN AutoCursor

FETCH NEXT FROM AutoCursor INTO @chvTypeId,@chvUserCode,@chvFullName

WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC Web_GetParentPath1 @chvTypeId,14,@chvPath OUTPUT

		INSERT INTO #Result(TypeId,UserCode,FullName,Path)VALUES(@chvTypeId,@chvUserCode,@chvFullName,REPLACE(@chvPath,'\','＼'))

		FETCH NEXT FROM AutoCursor INTO @chvTypeId,@chvUserCode,@chvFullName
	END

CLOSE AutoCursor
DEALLOCATE AutoCursor

SELECT * FROM #Result

DROP TABLE #Result,#QP_RepairAutoType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairAutoTypeList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairAutoTypeList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-09
	描述：维修车型档案-树型表
*/
CREATE PROCEDURE QP_QueryRepairAutoTypeList
(
	@OperatorId		varchar(100),		--操作员ID
	@TypeId			varchar(100)		--基本信息ID
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SonNum int

SELECT @SonNum = SonNum FROM QP_RepairAutoType WHERE TypeId = @TypeId

IF @SonNum = 0 
	SELECT * FROM QP_RepairAutoType WHERE TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
ELSE
	SELECT * FROM QP_RepairAutoType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairComb_Del]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairComb_Del]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：蔡志成
	日期：2010-07-19
	描述：维修套餐档案获取
*/
CREATE PROCEDURE QP_QueryRepairComb_Del
(
	@TypeId			varchar(1000),		--基本信息ID
	@OperatorId		varchar(100)		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SonNum INT ,@SonCount INT 
	
DECLARE @sql VARCHAR(6000)
SELECT @sql='
	SELECT parid,count(1) as counts INTO ##tables0 FROM QP_RepairSetMeal WHERE TypeID IN ('+@TypeId+') group by parid
	
	DELETE dbo.QP_RepairSetMeal WHERE TypeID IN ('+@TypeId+')
	DELETE dbo.QP_RepairSetMeal_Items WHERE TypeID IN ('+@TypeId+')
	DELETE dbo.QP_RepairSetMeal_Fittings WHERE TypeID IN ('+@TypeId+')
	'
EXEC(@sql)


	UPDATE QP_RepairSetMeal SET Sonnum = SonNum-r.counts--,SonCount = SonCount-r.counts 
	FROM QP_RepairSetMeal a INNER JOIN ##tables0 R ON a.TypeID = r.parid 
	
	DROP TABLE ##tables0

SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairComb_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairComb_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：蔡志成
	日期：2010-07-19
	描述：维修套餐档案获取
*/
CREATE PROCEDURE QP_QueryRepairComb_Get
(
	@TypeId			varchar(100),		--基本信息ID
	@OperatorId		varchar(100),		--操作员ID
	@flag		    INT					--需要获取的单据部分，0 单据头 1上表体 2下表体 -1 全部
)
--@encode$--
AS
SET NOCOUNT ON

	IF @flag=0 OR @flag=-1
		SELECT * FROM dbo.QP_RepairSetMeal WHERE TypeID=@TypeId
	
	
	IF @flag=1 OR @flag=-1
		SELECT a.StandardManHour,
			   a.CheckManHour,
			   a.ManHourExpense,
			   b.TypeID,
			   b.FullName,
			   b.UserCode		   
		FROM dbo.QP_RepairSetMeal_Items a LEFT JOIN dbo.QP_RepairItems b ON a.RepairItemsTypeID=b.TypeID
		WHERE a.TypeID = @TypeId
	
	
	IF @flag=2 OR @flag=-1
		SELECT a.Qty,
			   a.Price,
			   a.Total,b.FullName,b.UserCode,b.typeId  
		FROM dbo.QP_RepairSetMeal_Fittings a LEFT JOIN dbo.ptype b ON a.PTypeID=b.typeId
		WHERE a.TypeID = @TypeId
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairCombList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairCombList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：蔡志成
	日期：2010-07-19
	描述：维修套餐档案-树型表
*/
CREATE PROCEDURE QP_QueryRepairCombList
(
	@OperatorId		varchar(100),		--操作员ID
	@TypeId			varchar(100),   	--基本信息ID
	@parid          varchar(100)
) 
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
--DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
--            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
--EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
--
--IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SonNum int

SELECT @SonNum = SonNum FROM dbo.QP_RepairSetMeal WHERE TypeId = @TypeId

--IF @SonNum = 0 
--	SELECT * FROM QP_RepairSetMeal WHERE TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
--ELSE
	SELECT * FROM QP_RepairSetMeal WHERE ParId = @parid AND TypeId <> '00000' ORDER BY UserCode


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairCombQueryList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairCombQueryList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：蔡志成
	日期：2010-07-19
	描述：维修套餐档案-线性表
*/
CREATE PROCEDURE QP_QueryRepairCombQueryList
(
	@OperatorId		varchar(100),		--操作员ID
	@strFullName	VARCHAR(255),
	@strUserCode	VARCHAR(255),
	@strTypeId		VARCHAR(200)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
--DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
--            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
--EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
--
--IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @sql VARCHAR(MAX)
SET @sql='
	SELECT *,dbo.F_GetPath(TypeID,16) AS vpath FROM QP_RepairSetMeal 
	WHERE TypeId <> ''00000'' AND SonNum=0'
	
IF @strTypeId<>''	
	SET @sql=@sql+' AND Typeid like'+CHAR(39)+@strTypeId+'%'+CHAR(39)	
ELSE
BEGIN
IF @strFullName<>''	
	SET @sql=@sql+' AND FullName like '+CHAR(39)+'%'+@strFullName+'%'+CHAR(39)
IF @strUserCode<>''	
	SET @sql=@sql+' AND UserCode like '+CHAR(39)+'%'+@strUserCode+'%'+CHAR(39)
END
SET @sql=@sql+' ORDER BY UserCode '
--print (@sql)
Exec( @sql)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryRepairEmployeeAnsiDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryRepairEmployeeAnsiDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-11
	描述：维修人员业绩统计明细表
	
	作者：徐辉
	日期：2011-05-10
	描述：维修人员业绩统计明细表汽配3s相应调整(统计救援单，维修单)
*/

CREATE PROCEDURE Qp_QueryRepairEmployeeAnsiDetail
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@ETypeId		VARCHAR(100),
	@DTypeId		VARCHAR(8000),
	@Wxzt			VARCHAR(10),
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

DECLARE @SQL 	VARCHAR(8000),
		@SonNum	INT

SELECT @SonNum = SonNum FROM employee WHERE typeId = @ETypeID AND Deleted = 0


--处理明细
CREATE TABLE #Result
(
	RepairManTypeID		VARCHAR(100),
	BillNumberId		NUMERIC(18,0),
	RepairItemsTypeID	VARCHAR(100),
	PTypeId				VARCHAR(100),
	Comment				VARCHAR(400),
	StandardManHour		 NUMERIC(24, 10) ,
	CheckHour			 NUMERIC(24, 10) ,
	DiscountTotal		 NUMERIC(24, 10) ,
	CostTotal			 NUMERIC(24, 10) ,
	PDiscountTotal		 NUMERIC(24, 10) ,
	PCostTotal			 NUMERIC(24, 10) 
)

SET @SQL='
INSERT INTO 
	#Result
SELECT a.RepairManTypeID,a.BillNumberId,a.RepairItemsTypeID, a.PTypeId,a.Comment,a.StandardTotal,
		a.CheckTotal,a.DiscountHourTotal,a.CostTotal,a.DiscountTotal,a.GoodsCostTotal 
FROM
(
SELECT	a.Etypeid AS RepairManTypeID, --接待维修
		a.BillNumberId,
		b.RepairItemsTypeID AS RepairItemsTypeID,
		'''' AS PTypeId,
		'''' AS Comment,
		ISNULL(SUM(a.AllocateHour),0) AS StandardTotal,
		ISNULL(SUM(a.CheckHour),0) AS CheckTotal,
		ISNULL(SUM(a.Total),0) AS DiscountHourTotal,
		ISNULL(SUM(a.CostTotal),0) AS CostTotal,
		0 AS DiscountTotal,
		0 AS GoodsCostTotal
FROM	Qp_AttemperBill_RepairItemsPerson a
LEFT JOIN Qp_ReceptionBill_RepairItems b ON a.RepairItemsId=b.id
GROUP BY a.Etypeid,a.BillNumberID,b.RepairItemsTypeID
UNION ALL
SELECT	etypeid AS RepairManTypeID,
		receptionbillnumberid AS BillNumberId,
		'''' AS RepairItemsTypeID,
		PTypeId,
		Comment,
		0 AS StandardTotal,
		0 AS CheckTotal,
		0 AS DiscountHourTotal,
		0 AS CostTotal,
		ISNULL(SUM(DiscountTotal),0) AS DiscountTotal,
		ISNULL(SUM(CostTotal),0) AS GoodsCostTotal
FROM	Qp_ReceptionBill_FactUsePType
WHERE virtual<>1
GROUP BY etypeid,receptionbillnumberid,Comment,PTypeId
) a
INNER JOIN Billindex_CarRepair Bc ON a.BillNumberId=Bc.BillNumberId
WHERE
'

IF @Wxzt = 9
	SET @SQL = @SQL + ' 1 = 1'
ELSE
	SET @SQL = @SQL + ' Bc.BillState = '+@Wxzt
EXEC(@SQL)

SET @SQL='
INSERT INTO 
	#Result
SELECT a.RepairManTypeID,a.BillNumberId,a.RepairItemsTypeID, a.PTypeId,a.Comment,a.StandardTotal,
		a.CheckTotal,a.DiscountHourTotal,a.CostTotal,a.DiscountTotal,a.GoodsCostTotal 
FROM
(
SELECT	etypeid AS RepairManTypeID, --救援单
		BillNumberId,
		RepairItemsTypeID,
		'''' AS PTypeId,
		Comment,
		ISNULL(SUM(StandardManHour),0) AS StandardTotal,
		ISNULL(SUM(CheckHour),0) AS CheckTotal,
		ISNULL(SUM(Total),0) AS DiscountHourTotal,
		ISNULL(SUM(CostTotal),0) AS CostTotal,
		0 AS DiscountTotal,
		0 AS GoodsCostTotal
FROM	Qp_SuccorBill_RepairItems
GROUP BY etypeid,BillNumberID,RepairItemsTypeID,Comment
UNION ALL
SELECT	etypeid AS RepairManTypeID,
		BillNumberId,
		'''' AS RepairItemsTypeID,
		PTypeId,
		Comment,
		0 AS StandardTotal,
		0 AS CheckTotal,
		0 AS DiscountHourTotal,
		0 AS CostTotal,
		ISNULL(SUM(total),0) AS DiscountTotal,
		ISNULL(SUM(CostTotal),0) AS GoodsCostTotal
FROM	Qp_SuccorBill_PType
GROUP BY etypeid,BillNumberID,Comment,PTypeId
) a
'
EXEC(@SQL)

SET @SQL='
	INSERT INTO 
		#Result
	SELECT 
		a.RepairManTypeID,a.BillNumberId,a.RepairItemsTypeID, a.PTypeId,a.Comment,a.StandardTotal,
		a.CheckTotal,a.DiscountHourTotal,a.CostTotal,a.DiscountTotal,a.GoodsCostTotal 
	FROM 
		(SELECT	RepairManTypeID, --快修
				BillNumberId,
				RepairItemsTypeID,
				'''' AS PTypeId,
				Comment,
				ISNULL(SUM(StandardManHour),0) AS StandardTotal,
				ISNULL(SUM(CheckHour),0) AS CheckTotal,
				ISNULL(SUM(DiscountTotal),0) AS DiscountHourTotal,
				ISNULL(SUM(CostTotal),0) AS CostTotal,
				0 AS DiscountTotal,
				0 AS GoodsCostTotal
		FROM	QP_QuickRepairBill_RepairItems
		GROUP BY RepairManTypeID,BillNumberID,RepairItemsTypeID,Comment
		UNION ALL
		SELECT	RepairManTypeID,
				BillNumberId,
				'''' AS RepairItemsTypeID,
				PTypeId,
				Comment,
				0 AS StandardTotal,
				0 AS CheckTotal,
				0 AS DiscountHourTotal,
				0 AS CostTotal,
				ISNULL(SUM(DiscountTotal),0) AS DiscountTotal,
				ISNULL(SUM(GoodsCostTotal),0) AS GoodsCostTotal
		FROM	QP_QuickRepairBill_PType
		GROUP BY RepairManTypeID,BillNumberID,Comment,PTypeId
		) a
	INNER JOIN Billindex_CarRepair Bc ON a.BillNumberId=Bc.BillNumberId
	INNER JOIN BillIndex Bi ON a.BillNumberId=Bi.BillNumberId
	WHERE
		'

IF @Wxzt = 9
	SET @SQL = @SQL + ' 1 = 1'
ELSE IF @Wxzt=2 --在修 （对应快修单的草稿,且维修进度为“在修”）
	SET @SQL = @SQL + ' Bc.Status = 0 AND Bi.Draft=1'
ELSE IF @Wxzt=3 --完工待结算（对应快修单的草稿,且维修进度为“完工待结算”）
	SET @SQL = @SQL + ' Bc.Status = 1 AND Bi.Draft=1'
ELSE IF @Wxzt=4	--已结算（对应已过账快修单，且维修进度为“已结算”。）
	SET @SQL = @SQL + ' Bc.Status = 2 AND Bi.Draft=0'	
EXEC(@SQL)

	
SET @SQL = 'SELECT	Bi.BillNumberId,
					Bi.BillDate,
					bi.stypeid,
					Bi.BillCode,
					Bi.BillType,
					Bi.IfCheck,
					R.Comment,
					ETypeId = (SELECT FullName FROM Employee WHERE Bi.ETypeId = TypeId),
					XETypeId = E.FullName,
					Bi.DTypeId,
					Bc.RATypeID,
					Bi.BTypeId,
					R.RepairItemsTypeID,
					R.PTypeId,
					ISNULL(SUM(R.StandardManHour),0) AS StandardManHour,
					ISNULL(SUM(R.CheckHour),0) AS CheckHour,
					ISNULL(SUM(R.DiscountTotal),0) AS DiscountTotal,
					ISNULL(SUM(R.CostTotal),0) AS CostTotal,
					ISNULL(SUM(R.DiscountTotal),0) - ISNULL(SUM(R.CostTotal),0) AS ML,
					ISNULL(SUM(R.PDiscountTotal),0) AS PDiscountTotal,
					ISNULL(SUM(R.PCostTotal),0) AS PCostTotal,
					ISNULL(SUM(R.PDiscountTotal),0) - ISNULL(SUM(R.PCostTotal),0) AS PML
			FROM	BillIndex Bi					
					INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
					INNER JOIN #Result R ON Bi.BillNumberId = R.BillNumberId
					INNER JOIN Employee E ON E.TypeId = R.RepairManTypeID '
						
		IF NOT @METypeId = '00001'
			BEGIN
				SET @SQL = @SQL + ' INNER JOIN #GetManETypeId ME ON ME.TypeId = R.RepairManTypeID '
			END
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '				
		
		SET @SQL = @SQL + '
				WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND R.RepairManTypeID LIKE '+CHAR(39)+@ETypeId+'%'+CHAR(39)+'
						AND Bi.BillType IN(178,196,195)						
						AND Bi.RedWord = 0
						AND Bi.IfYearBill = 0 '

		IF NOT @DTypeId = ''
			SET @SQL = @SQL + ' AND E.DTypeId IN (SELECT TypeId FROM #GetManDTypeId) '
										
		SET @SQL = @SQL + '		
				GROUP BY
					Bi.BillNumberId,
					Bi.BillDate,
					Bi.Stypeid,
					Bi.BillCode,
					Bi.BillType,
					Bi.IfCheck,
				    R.Comment,
					Bi.ETypeId,
					E.FullName,
					Bi.DTypeId,
					Bc.RATypeID,
					Bi.BTypeId,
					R.RepairItemsTypeID,
					R.PTypeId
				ORDER BY Bi.BillDate ASC,Bi.BillCode ASC'
		
EXEC(@SQL)			

DROP TABLE #GetManETypeId,#GetManDTypeId,#Result,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryRepairEmployeeAnsiLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryRepairEmployeeAnsiLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-11
	描述：维修人员业绩统计线性表
	
	作者：徐辉
	日期：2011-05-10
	描述：维修人员业绩统计线性表汽配3s相应调整(统计救援单，维修单)
*/

CREATE PROCEDURE Qp_QueryRepairEmployeeAnsiLine
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@ETypeId		VARCHAR(100),
	@DTypeId		VARCHAR(8000),
	@Wxzt			VARCHAR(10),
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

DECLARE @SQL 	VARCHAR(8000),
		@SonNum	INT

SELECT @SonNum = SonNum FROM employee WHERE typeId = @ETypeID AND Deleted = 0


SET @SQL = 'SELECT 	B.*
			FROM	(
						SELECT	E.TypeId,
								E.UserCode,
								E.SonNum,
								E.ParId,
								E.DTypeId,
								ISNULL(SUM(M.StandardManHour),0) AS StandardManHour,
								ISNULL(SUM(M.CheckHour),0) AS CheckHour,
								ISNULL(SUM(M.DiscountTotal),0) AS DiscountTotal,
								ISNULL(SUM(M.CostTotal),0) AS CostTotal,
								ISNULL(SUM(M.DiscountTotal),0) - ISNULL(SUM(M.CostTotal),0) AS ML,
								ISNULL(SUM(M.PDiscountTotal),0) AS PDiscountTotal,
								ISNULL(SUM(M.PCostTotal),0) AS PCostTotal,
								ISNULL(SUM(M.PDiscountTotal),0) - ISNULL(SUM(M.PCostTotal),0) AS PML					
						FROM	F_GetManETypeAll('+char(39)+@OperatorID+char(39)+') E
						LEFT JOIN (
									SELECT	R.RepairManTypeID AS ETypeId,
											ISNULL(SUM(R.StandardManHour),0) AS StandardManHour,
											ISNULL(SUM(R.CheckHour),0) AS CheckHour,
											ISNULL(SUM(R.DiscountTotal),0) AS DiscountTotal,
											ISNULL(SUM(R.CostTotal),0) AS CostTotal,
											0 AS PDiscountTotal,
											0 AS PCostTotal
									FROM	BillIndex Bi
											INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
											INNER JOIN QP_QuickRepairBill_RepairItems R ON Bi.BillNumberId = R.BillNumberId '
											
							IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
								SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.RepairManTypeID '
								
							IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '									
							
							SET @SQL = @SQL + '
									WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
											AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
											AND Bi.BillType = 178
											AND Bi.RedWord = 0
											AND Bi.IfYearBill = 0 '

			
							IF @Wxzt = 9
								SET @SQL = @SQL + ' AND 1 = 1'
							ELSE IF @Wxzt=2 --在修 （对应快修单的草稿,且维修进度为“在修”）
								SET @SQL = @SQL + ' AND Bc.Status = 0 AND Bi.Draft=1'
							ELSE IF @Wxzt=3 --完工待结算（对应快修单的草稿,且维修进度为“完工待结算”）
								SET @SQL = @SQL + ' AND Bc.Status = 1 AND Bi.Draft=1'
							ELSE IF @Wxzt=4	--已结算（对应已过账快修单，且维修进度为“已结算”。）
								SET @SQL = @SQL + ' AND Bc.Status = 2 AND Bi.Draft=0'	
									
							SET @SQL = @SQL + '						
									GROUP BY 	R.RepairManTypeID
								UNION ALL
									SELECT	R.RepairManTypeID AS ETypeId,
											0 AS StandardManHour,
											0 AS CheckHour,
											0 AS DiscountTotal,
											0 AS CostTotal,
											ISNULL(SUM(R.DiscountTotal),0) AS PDiscountTotal,
											ISNULL(SUM(R.GoodsCostTotal),0) AS PCostTotal
									FROM	BillIndex Bi
											INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
											INNER JOIN QP_QuickRepairBill_PType R ON Bi.BillNumberId = R.BillNumberId '
											
							IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
								SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.RepairManTypeID '
								
							IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '									
							
							SET @SQL = @SQL + '
									WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
											AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
											AND Bi.BillType = 178
											AND Bi.RedWord = 0
											AND Bi.IfYearBill = 0 '
										
							IF @Wxzt = 9
								SET @SQL = @SQL + ' AND 1 = 1'
							ELSE IF @Wxzt=2 --在修 （对应快修单的草稿,且维修进度为“在修”）
								SET @SQL = @SQL + ' AND Bc.Status = 0 AND Bi.Draft=1'
							ELSE IF @Wxzt=3 --完工待结算（对应快修单的草稿,且维修进度为“完工待结算”）
								SET @SQL = @SQL + ' AND Bc.Status = 1 AND Bi.Draft=1'
							ELSE IF @Wxzt=4	--已结算（对应已过账快修单，且维修进度为“已结算”。）
								SET @SQL = @SQL + ' AND Bc.Status = 2 AND Bi.Draft=0'	
									
							SET @SQL = @SQL + '						
									GROUP BY 	R.RepairManTypeID
							
							--维修接待单
							UNION ALL
								SELECT	R.ETypeId,
											ISNULL(SUM(R.AllocateHour),0) AS StandardManHour,
											ISNULL(SUM(R.CheckHour),0) AS CheckHour,
											ISNULL(SUM(R.total),0) AS DiscountTotal,
											ISNULL(SUM(R.CostTotal),0) AS CostTotal,
											0 AS PDiscountTotal,
											0 AS PCostTotal
									FROM	BillIndex Bi
											INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
											INNER JOIN Qp_AttemperBill_RepairItemsPerson R ON Bi.BillNumberId = R.BillNumberId '
											
							IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
								SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.ETypeId '
								
							IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '							
								
							SET @SQL = @SQL + '
									WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
											AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
											AND Bi.BillType = 195
											AND Bi.RedWord = 0
											AND Bi.IfYearBill = 0 '

							IF @Wxzt = 9
								SET @SQL = @SQL + ' AND 1 = 1'
							ELSE
								SET @SQL = @SQL + ' AND Bc.BillState = '+@Wxzt
									
							SET @SQL = @SQL + '						
									GROUP BY 	R.ETypeId
								UNION ALL
									SELECT	R.ETypeId,
											0 AS StandardManHour,
											0 AS CheckHour,
											0 AS DiscountTotal,
											0 AS CostTotal,
											ISNULL(SUM(R.DiscountTotal),0) AS PDiscountTotal,
											ISNULL(SUM(R.CostTotal),0) AS PCostTotal
									FROM	BillIndex Bi
											INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
											INNER JOIN Qp_ReceptionBill_FactUsePType R ON Bi.BillNumberId = R.ReceptionBillnumberId '
											
							IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
								SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.ETypeId '
								
							IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '							
								
							SET @SQL = @SQL + '
									WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
											AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
											AND Bi.BillType = 195
											AND Bi.RedWord = 0
											AND Bi.IfYearBill = 0 
											AND R.Virtual<>1'
											

							IF @Wxzt = 9
								SET @SQL = @SQL + ' AND 1 = 1'
							ELSE
								SET @SQL = @SQL + ' AND Bc.BillState = '+@Wxzt
									
							SET @SQL = @SQL + '						
									GROUP BY 	R.ETypeId
									
							--救援单
							UNION ALL
							SELECT	R.ETypeId AS ETypeId,
											ISNULL(SUM(R.StandardManHour),0) AS StandardManHour,
											ISNULL(SUM(R.CheckHour),0) AS CheckHour,
											ISNULL(SUM(R.total),0) AS DiscountTotal,
											ISNULL(SUM(R.CostTotal),0) AS CostTotal,
											0 AS PDiscountTotal,
											0 AS PCostTotal
									FROM	BillIndex Bi
											INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
											INNER JOIN Qp_SuccorBill_RepairItems R ON Bi.BillNumberId = R.BillNumberId '
											
							IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
								SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.ETypeId '
								
							IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '									
							
							SET @SQL = @SQL + '
									WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
											AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
											AND Bi.BillType = 196
											AND Bi.RedWord = 0
											AND Bi.IfYearBill = 0 '

							--救援单不受状态影响
							--IF @Wxzt = 9
								--SET @SQL = @SQL + ' AND 1 = 1'
							--ELSE
								--SET @SQL = @SQL + ' AND Bc.BillState = '+@Wxzt
									
							SET @SQL = @SQL + '						
									GROUP BY 	R.ETypeId
								UNION ALL
									SELECT	R.ETypeId AS ETypeId,
											0 AS StandardManHour,
											0 AS CheckHour,
											0 AS DiscountTotal,
											0 AS CostTotal,
											ISNULL(SUM(R.total),0) AS PDiscountTotal,
											ISNULL(SUM(R.CostTotal),0) AS PCostTotal
									FROM	BillIndex Bi
											INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
											INNER JOIN Qp_SuccorBill_PType R ON Bi.BillNumberId = R.BillNumberId '
											
							IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
								SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.ETypeId '
								
							IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '									
							
							SET @SQL = @SQL + '
									WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
											AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
											AND Bi.BillType = 196
											AND Bi.RedWord = 0
											AND Bi.IfYearBill = 0 '
								
							--救援单不受状态影响		
							--IF @Wxzt = 9
								--SET @SQL = @SQL + ' AND 1 = 1'
							--ELSE
								--SET @SQL = @SQL + ' AND Bc.BillState = '+@Wxzt
									
							SET @SQL = @SQL + '						
									GROUP BY 	R.ETypeId
						)M ON M.ETypeId = E.TypeId
						WHERE 	E.TypeId <> ''00000''
								AND E.SonNum = 0
							 	AND E.TypeId LIKE '+CHAR(39)+@ETypeId+'%'+CHAR(39)
			
			IF NOT @DTypeId = ''
				SET @SQL = @SQL + ' AND E.DTypeId IN (SELECT TypeId FROM #GetManDTypeId) '
			
			SET @SQL = @SQL + '
						GROUP BY 	E.TypeId,
									E.UserCode,
									E.SonNum,
									E.ParId,  
									E.DTypeId
			)B
			WHERE	ISNULL(B.StandardManHour,0) <> 0
					OR ISNULL(B.CheckHour,0) <> 0
					OR ISNULL(B.DiscountTotal,0) <> 0
					OR ISNULL(B.CostTotal,0) <> 0
					OR ISNULL(B.ML,0) <> 0
					OR ISNULL(B.PDiscountTotal,0) <> 0
					OR ISNULL(B.PCostTotal,0) <> 0
					OR ISNULL(B.PML,0) <> 0
			ORDER BY B.UserCode'

--PRINT(@SQL)			
EXEC(@SQL)			

DROP TABLE #GetManETypeId,#GetManDTypeId,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryRepairEmployeeAnsiList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryRepairEmployeeAnsiList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-11
	描述：维修人员业绩统计树型表
	
	作者：徐辉
	日期：2011-05-10
	描述：维修人员业绩统计树型表汽配3s相应调整(统计救援单，维修单)
*/

CREATE PROCEDURE Qp_QueryRepairEmployeeAnsiList
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@ETypeId		VARCHAR(100),
	@DTypeId		VARCHAR(8000),
	@Wxzt			VARCHAR(10),
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
IF @ETypeId = ''
	SET @ETypeId = '00001'
	
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

DECLARE @SQL 	VARCHAR(Max),
		@SonNum	INT

SELECT @SonNum = SonNum FROM employee WHERE typeId = @ETypeID AND Deleted = 0

	
SET @SQL = 'SELECT	E.TypeId,
					E.UserCode,
					E.SonNum,
					E.ParId,
					E.DTypeId,
					ISNULL(SUM(M.StandardManHour),0) AS StandardManHour,
					ISNULL(SUM(M.CheckHour),0) AS CheckHour,
					ISNULL(SUM(M.DiscountTotal),0) AS DiscountTotal,
					ISNULL(SUM(M.CostTotal),0) AS CostTotal,
					ISNULL(SUM(M.DiscountTotal),0) - ISNULL(SUM(M.CostTotal),0) AS ML,
					ISNULL(SUM(M.PDiscountTotal),0) AS PDiscountTotal,
					ISNULL(SUM(M.PCostTotal),0) AS PCostTotal,
					ISNULL(SUM(M.PDiscountTotal),0) - ISNULL(SUM(M.PCostTotal),0) AS PML
			FROM	F_GetManETypeAll('+char(39)+@OperatorID+char(39)+') E
			LEFT JOIN (
						SELECT	R.RepairManTypeID AS ETypeId,
								ISNULL(SUM(R.StandardManHour),0) AS StandardManHour,
								ISNULL(SUM(R.CheckHour),0) AS CheckHour,
								ISNULL(SUM(R.DiscountTotal),0) AS DiscountTotal,
								ISNULL(SUM(R.CostTotal),0) AS CostTotal,
								0 AS PDiscountTotal,
								0 AS PCostTotal
						FROM	BillIndex Bi
								INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
								INNER JOIN QP_QuickRepairBill_RepairItems R ON Bi.BillNumberId = R.BillNumberId '
								
				IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
					SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.RepairManTypeID '
					
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '							
					
				SET @SQL = @SQL + '
						WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bi.BillType = 178
								AND Bi.RedWord = 0
								AND Bi.IfYearBill = 0 '
				
					

				IF @Wxzt = 9
					SET @SQL = @SQL + ' AND 1 = 1'
				ELSE IF @Wxzt=2 --在修 （对应快修单的草稿,且维修进度为“在修”）
					SET @SQL = @SQL + ' AND Bc.Status = 0 AND Bi.Draft=1'
				ELSE IF @Wxzt=3 --完工待结算（对应快修单的草稿,且维修进度为“完工待结算”）
					SET @SQL = @SQL + ' AND Bc.Status = 1 AND Bi.Draft=1'
				ELSE IF @Wxzt=4	--已结算（对应已过账快修单，且维修进度为“已结算”。）
					SET @SQL = @SQL + ' AND Bc.Status = 2 AND Bi.Draft=0'	
					
				SET @SQL = @SQL + '						
						GROUP BY 	R.RepairManTypeID
					UNION ALL
						SELECT	R.RepairManTypeID AS ETypeId,
								0 AS StandardManHour,
								0 AS CheckHour,
								0 AS DiscountTotal,
								0 AS CostTotal,
								ISNULL(SUM(R.DiscountTotal),0) AS PDiscountTotal,
								ISNULL(SUM(R.GoodsCostTotal),0) AS PCostTotal
						FROM	BillIndex Bi
								INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
								INNER JOIN QP_QuickRepairBill_PType R ON Bi.BillNumberId = R.BillNumberId '
								
				IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
					SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.RepairManTypeID '
					
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '							
					
				SET @SQL = @SQL + '
						WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bi.BillType = 178
								AND Bi.RedWord = 0
								AND Bi.IfYearBill = 0 '
								

				IF @Wxzt = 9
					SET @SQL = @SQL + ' AND 1 = 1'
				ELSE IF @Wxzt=2 --在修 （对应快修单的草稿,且维修进度为“在修”）
					SET @SQL = @SQL + ' AND Bc.Status = 0 AND Bi.Draft=1'
				ELSE IF @Wxzt=3 --完工待结算（对应快修单的草稿,且维修进度为“完工待结算”）
					SET @SQL = @SQL + ' AND Bc.Status = 1 AND Bi.Draft=1'
				ELSE IF @Wxzt=4	--已结算（对应已过账快修单，且维修进度为“已结算”。）
					SET @SQL = @SQL + ' AND Bc.Status = 2 AND Bi.Draft=0'	
						
				SET @SQL = @SQL + '						
						GROUP BY 	R.RepairManTypeID
				--维修接待单
				UNION ALL
					SELECT	R.ETypeId,
								ISNULL(SUM(R.AllocateHour),0) AS StandardManHour,
								ISNULL(SUM(R.CheckHour),0) AS CheckHour,
								ISNULL(SUM(R.total),0) AS DiscountTotal,
								ISNULL(SUM(R.CostTotal),0) AS CostTotal,
								0 AS PDiscountTotal,
								0 AS PCostTotal
						FROM	BillIndex Bi
								INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
								INNER JOIN Qp_AttemperBill_RepairItemsPerson R ON Bi.BillNumberId = R.BillNumberId '
								
				IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
					SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.ETypeId '
					
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '							
					
				SET @SQL = @SQL + '
						WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bi.BillType = 195
								AND Bi.RedWord = 0
								AND Bi.IfYearBill = 0 '

				IF @Wxzt = 9
					SET @SQL = @SQL + ' AND 1 = 1'
				ELSE
					SET @SQL = @SQL + ' AND Bc.BillState = '+@Wxzt
						
				SET @SQL = @SQL + '						
						GROUP BY 	R.ETypeId
					UNION ALL
						SELECT	R.ETypeId,
								0 AS StandardManHour,
								0 AS CheckHour,
								0 AS DiscountTotal,
								0 AS CostTotal,
								ISNULL(SUM(R.DiscountTotal),0) AS PDiscountTotal,
								ISNULL(SUM(R.CostTotal),0) AS PCostTotal
						FROM	BillIndex Bi
								INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
								INNER JOIN Qp_ReceptionBill_FactUsePType R ON Bi.BillNumberId = R.ReceptionBillnumberId '
								
				IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
					SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.ETypeId '
					
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '							
					
				SET @SQL = @SQL + '
						WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bi.BillType = 195
								AND Bi.RedWord = 0
								AND Bi.IfYearBill = 0 
								AND R.Virtual<>1'
								

				IF @Wxzt = 9
					SET @SQL = @SQL + ' AND 1 = 1'
				ELSE
					SET @SQL = @SQL + ' AND Bc.BillState = '+@Wxzt
						
				SET @SQL = @SQL + '						
						GROUP BY 	R.ETypeId
				--救援单
				UNION ALL
					SELECT	R.ETypeId AS ETypeId,
								ISNULL(SUM(R.StandardManHour),0) AS StandardManHour,
								ISNULL(SUM(R.CheckHour),0) AS CheckHour,
								ISNULL(SUM(R.total),0) AS DiscountTotal,
								ISNULL(SUM(R.CostTotal),0) AS CostTotal,
								0 AS PDiscountTotal,
								0 AS PCostTotal
						FROM	BillIndex Bi
								INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
								INNER JOIN Qp_SuccorBill_RepairItems R ON Bi.BillNumberId = R.BillNumberId '
								
				IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
					SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.ETypeId '
					
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '							
					
				SET @SQL = @SQL + '
						WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bi.BillType = 196
								AND Bi.RedWord = 0
								AND Bi.IfYearBill = 0 '

				--救援单不受状态影响
				--IF @Wxzt = 9
					--SET @SQL = @SQL + ' AND 1 = 1'
				--ELSE
					--SET @SQL = @SQL + ' AND Bc.BillState = '+@Wxzt
						
				SET @SQL = @SQL + '						
						GROUP BY 	R.ETypeId
					UNION ALL
						SELECT	R.ETypeId AS ETypeId,
								0 AS StandardManHour,
								0 AS CheckHour,
								0 AS DiscountTotal,
								0 AS CostTotal,
								ISNULL(SUM(R.total),0) AS PDiscountTotal,
								ISNULL(SUM(R.costtotal),0) AS PCostTotal
						FROM	BillIndex Bi
								INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
								INNER JOIN Qp_SuccorBill_PType R ON Bi.BillNumberId = R.BillNumberId '
								
				IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
					SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = R.ETypeId '
					
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '							
					
				SET @SQL = @SQL + '
						WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bi.BillType = 196
								AND Bi.RedWord = 0
								AND Bi.IfYearBill = 0 '
								
				--救援单不受状态影响
				--IF @Wxzt = 9
					---SET @SQL = @SQL + ' AND 1 = 1'
				---ELSE
					--SET @SQL = @SQL + ' AND Bc.BillState = '+@Wxzt
						
				SET @SQL = @SQL + '						
						GROUP BY 	R.ETypeId
			)M ON LEFT (M.ETypeId,LEN(E.TypeId)) = E.TypeId
			WHERE 	E.TypeId <> ''00000'''
			
IF @SonNum = 0
	SET @SQL = @SQL + ' AND E.TypeId = '+CHAR(39)+@ETypeId+CHAR(39)
ELSE
	SET @SQL = @SQL + ' AND E.ParId = '+CHAR(39)+@ETypeId+CHAR(39)

IF NOT @DTypeId = ''
	SET @SQL = @SQL + ' AND E.DTypeId IN (SELECT TypeId FROM #GetManDTypeId) '

SET @SQL = @SQL + '			
			GROUP BY 	E.TypeId,
						E.UserCode,
						E.SonNum,
						E.ParId,  
						E.DTypeId
			ORDER BY E.UserCode'

PRINT(@SQL)			
EXEC(@SQL)			

DROP TABLE #GetManETypeId,#GetManDTypeId,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryRepairItemsAnsiDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryRepairItemsAnsiDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-11
	描述：维修项目统计明细表
*/

/*
	修改者：赵斌
	日期：2011-05-10
	描述：增加单据类型，修改查询条件
*/

/*
	修改者：赵斌
	日期：2011-07-10
	描述：维修进度不影响快修单
*/

CREATE PROCEDURE Qp_QueryRepairItemsAnsiDetail
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@ETypeId		VARCHAR(8000),
	@DTypeId		VARCHAR(8000),
	@WciTypeId		VARCHAR(8000),	--维修车辆信息档案ID
	@BTypeId		VARCHAR(8000),
	@WiTypeId		VARCHAR(8000),	--维修项目档案ID
	@Xzzd			VARCHAR(10),	--虚增字段
	@Wxjd			VARCHAR(10),	--维修进度
	@Bxzt			VARCHAR(10),	--状态
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--车牌号(不用控制权限范围)
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,00001)


DECLARE @SQL 	VARCHAR(8000),
		@SQL2 	VARCHAR(8000),
		@SonNum	INT
		
--临时结果集
CREATE TABLE #RESULT(BillNumberId VARCHAR(MAX),
					 RepairManTypeID VARCHAR(MAX),
					 RITypeId VARCHAR(MAX),
					 StandardManHour  NUMERIC(24, 10) ,
					 CheckHour  NUMERIC(24, 10) ,
					 DiscountTotal  NUMERIC(24, 10) ,
					 CostTotal  NUMERIC(24, 10) ,
					 Comment [varchar] (250))

SET @SQL2 = 'INSERT #RESULT
			 SELECT RR.BillNumberId,
							   RepairMan AS RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(RR.CheckHour),0) AS CheckHour,
							   ISNULL(SUM(DiscountTotal),0) AS DiscountTotal,
							   ISNULL(SUM(RR.CostTotal),0) AS CostTotal,
							   RR.Comment
						FROM Qp_ReceptionBill_RepairItems RR
						INNER JOIN BillIndex B ON RR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON RR.BillNumberId = Bc.BillNumberId
						'
--由于虚增维修项目没有修理工，所以当非虚增的时候才连接职员表
IF @Xzzd <> 1 AND @ETypeId <> ''
	SET @SQL2 = @SQL2 + 
						'
						INNER JOIN (
							SELECT DISTINCT a.BillNumberId,a.RepairItemsID
							FROM Qp_AttemperBill_RepairItemsPerson a
							INNER JOIN #GetManETypeId b
							ON a.etypeid=b.typeid
						) ar
						ON RR.billnumberid=ar.BillNumberId
						'
SET @SQL2 = @SQL2 + '
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL2 = @SQL2 + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
											
IF @Xzzd <> 1 AND @ETypeId <> ''
	SET @SQL2 = @SQL2 + '						
						AND AR.RepairItemsID = RR.ID'
						
IF @Wxjd = 0
	SET @SQL2 = @SQL2 + ' AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL2 = @SQL2 + ' AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL2 = @SQL2 + ' AND Bc.BillState = 4'
ELSE 
	SET @SQL2 = @SQL2 + ' AND 1 = 1'
	
IF @Bxzt = 0
	SET @SQL2 = @SQL2 + ' AND RR.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL2 = @SQL2 + ' AND RR.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL2 = @SQL2 + ' AND RR.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL2 = @SQL2 + ' AND RR.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL2 = @SQL2 + ' AND RR.Insurance = 4'
ELSE 
	SET @SQL2 = @SQL2 + ' AND 1 = 1'
	
IF @Xzzd = 0
	SET @SQL2 = @SQL2 + ' AND RR.Virtual = 1'
ELSE IF @Xzzd = 1
	SET @SQL2 = @SQL2 + ' AND RR.Virtual = 0'
ELSE 
	SET @SQL2 = @SQL2 + ' AND 1 = 1'
	
SET @SQL2 = @SQL2 + '
						GROUP BY RR.BillNumberId,
								 RepairMan,
								 RepairItemsTypeId,
								 RR.Comment
						
						UNION ALL
						
						SELECT QR.BillNumberId,
							   E1.Fullname AS RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(CheckHour),0) AS CheckHour,
							   ISNULL(SUM(DiscountTotal),0) AS DiscountTotal,
							   ISNULL(SUM(CostTotal),0) AS CostTotal,
							   QR.Comment
						FROM QP_QuickRepairBill_RepairItems QR
						INNER JOIN BillIndex B ON QR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON QR.BillNumberId = Bc.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = QR.RepairManTypeID
						INNER JOIN Employee E1 on e.typeid = e1.typeid
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL2 = @SQL2 + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Wxjd = 9
	SET @SQL2 = @SQL2 + ' AND 1 = 1'
ELSE IF @Wxjd = 0
	SET @SQL2 = @SQL2+ ' AND Bc.Status = 0'
ELSE IF @Wxjd = 1
	SET @SQL2 = @SQL2 + ' AND Bc.Status = 1'
ELSE IF @Wxjd = 2
	SET @SQL2 = @SQL2 + ' AND Bc.Status = 2'
	
IF @Bxzt = 0
	SET @SQL2 = @SQL2 + ' AND QR.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL2 = @SQL2 + ' AND QR.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL2 = @SQL2 + ' AND QR.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL2 = @SQL2 + ' AND QR.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL2 = @SQL2 + ' AND QR.Insurance = 4'
ELSE 
	SET @SQL2 = @SQL2 + ' AND 1 = 1'

IF @Xzzd = 0
	SET @SQL2 = @SQL2 + ' AND 1 = 2'
ELSE 
	SET @SQL2 = @SQL2 + ' AND 1 = 1'

SET @SQL2 = @SQL2 + '
						GROUP BY QR.BillNumberId,
								 RepairManTypeID,
								 RepairItemsTypeId,
								  E1.Fullname,
								 QR.Comment
						
						UNION ALL
						
						SELECT SR.BillNumberId,
							   E1.Fullname AS RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(CheckHour),0) AS CheckHour,
							   ISNULL(SUM(Total),0) AS DiscountTotal,
							   ISNULL(SUM(CostTotal),0) AS CostTotal,
							   SR.Comment
						FROM Qp_SuccorBill_RepairItems SR
						INNER JOIN BillIndex B ON SR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON SR.BillNumberId = Bc.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = SR.ETypeId
						INNER JOIN Employee E1 on e.typeid = e1.typeid
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL2 = @SQL2 + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Xzzd = 0
	SET @SQL2 = @SQL2 + ' AND 1 = 2'
ELSE 
	SET @SQL2 = @SQL2 + ' AND 1 = 1'
	
SET @SQL2 = @SQL2 + '
						GROUP BY SR.BillNumberId,
								 SR.ETypeId,
								 RepairItemsTypeId,
								  E1.Fullname,
								 SR.Comment'
--PRINT(@SQL2)
EXEC(@SQL2)

SELECT @SonNum = SonNum FROM QP_RepairItems WHERE typeId = @WiTypeId
		
SET @SQL = 'SELECT	Bi.BillNumberId,
					Bi.BillDate,
					Bi.BillCode,
					Bi.BillType,
					Bi.IfCheck,
					Bi.stypeid,
					R.Comment,
					R.RepairManTypeID AS ETypeId,
					Bi.DTypeId,
					Bc.RATypeID,
					Bi.BTypeId,
					R.RITypeId,
					ISNULL(SUM(R.StandardManHour),0) AS StandardManHour,
					ISNULL(SUM(R.CheckHour),0) AS CheckHour,
					ISNULL(SUM(R.DisCountTotal),0) AS DisCountTotal,
					ISNULL(SUM(R.CostTotal),0) AS CostTotal,
					ISNULL(SUM(R.DiscountTotal),0) - ISNULL(SUM(R.CostTotal),0) AS ML,
					CAST(CASE WHEN ISNULL(SUM(R.DiscountTotal),0) = 0 THEN 0 ELSE (ISNULL(SUM(R.DiscountTotal),0) - ISNULL(SUM(R.CostTotal),0))/ISNULL(SUM(R.DiscountTotal),0)*100 END AS  NUMERIC(24, 10) ) AS MLL
			FROM	BillIndex Bi
					INNER JOIN #RESULT R ON Bi.BillNumberId = R.BillNumberId
					INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = Bi.BillNumberId
					'									
		SET @SQL = @SQL + '
				WHERE	Bi.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND Bi.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND Bi.RedWord = 0
						AND Bi.IfYearBill = 0
						AND R.RITypeId LIKE '+CHAR(39)+@WiTypeId+'%'+CHAR(39)
						
		SET @SQL = @SQL + '		
				GROUP BY Bi.BillNumberId,
						 Bi.BillDate,
						 Bi.BillCode,
						 Bi.BillType,
						 Bi.IfCheck,
						 R.Comment,
						 R.RepairManTypeID,
						 Bi.DTypeId,
						 Bc.RATypeID,
						 bi.stypeid,
						 Bi.BTypeId,			
						 R.RITypeId		
				ORDER BY Bi.BillDate ASC,Bi.BillCode ASC'

--PRINT(@SQL)			
EXEC(@SQL)			

DROP TABLE #GetManETypeId,#GetManDTypeId,#GetManBTypeId,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryRepairItemsAnsiLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryRepairItemsAnsiLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-11
	描述：维修项目统计线型表
*/

/*
	修改者：赵斌
	日期：2011-05-09
	描述：增加单据类型，修改查询条件
*/

/*
	修改者：赵斌
	日期：2011-07-06
	描述：维修进度不影响快修单
*/

CREATE PROCEDURE Qp_QueryRepairItemsAnsiLine
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@ETypeId		VARCHAR(8000),
	@DTypeId		VARCHAR(8000),
	@WciTypeId		VARCHAR(8000),	--维修车辆信息档案ID
	@BTypeId		VARCHAR(8000),
	@WiTypeId		VARCHAR(8000),	--维修项目档案ID
	@Xzzd			VARCHAR(10),	--虚增字段
	@Wxjd			VARCHAR(10),	--维修进度
	@Bxzt			VARCHAR(10),	--状态
	@STypeId		VARCHAR(MAX)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------	
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)


--车牌号(不用控制权限范围)
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,00001)


DECLARE @SQL 	VARCHAR(8000),
		@SQL2 	VARCHAR(8000),
		@SonNum	INT
		
SET @SQL = ''

SELECT @SonNum = SonNum FROM QP_RepairItems WHERE typeId = @WiTypeId

--IF @WiTypeId = ''
--	SET @WiTypeId = '00000'
	
SET @SQL = 'SELECT M.* FROM(
			SELECT R.TypeId,
				   R.UserCode,
				   R.SonNum,
				   R.ParId,
				   ISNULL(SUM(M.StandardManHour),0) AS StandardManHour,
				   ISNULL(SUM(M.CheckHour),0) AS CheckHour,
				   ISNULL(SUM(M.DiscountTotal),0) AS DiscountTotal,					
				   ISNULL(SUM(M.CostTotal),0) AS CostTotal,
				   ISNULL(SUM(M.DiscountTotal),0) - ISNULL(SUM(M.CostTotal),0) AS ML,
				   CAST(CASE WHEN ISNULL(SUM(M.DiscountTotal),0) = 0 THEN 0 ELSE (ISNULL(SUM(M.DiscountTotal),0) - ISNULL(SUM(M.CostTotal),0))/ISNULL(SUM(M.DiscountTotal),0)*100 END AS  NUMERIC(24, 10) ) AS MLL 
			FROM QP_RepairItems R
			LEFT JOIN(
						SELECT RR.BillNumberId,
							   RepairMan AS RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(RR.CheckHour),0) AS CheckHour,
							   ISNULL(SUM(DiscountTotal),0) AS DiscountTotal,
							   ISNULL(SUM(RR.CostTotal),0) AS CostTotal
						FROM Qp_ReceptionBill_RepairItems RR
						INNER JOIN BillIndex B ON RR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON RR.BillNumberId = Bc.BillNumberId
						'
--由于虚增维修项目没有修理工，所以当非虚增的时候才连接职员表
IF @Xzzd <> 1 AND @ETypeId <> ''
	SET @SQL = @SQL + 
						'
						INNER JOIN (
							SELECT DISTINCT a.BillNumberId,a.RepairItemsID
							FROM Qp_AttemperBill_RepairItemsPerson a
							INNER JOIN #GetManETypeId b
							ON a.etypeid=b.typeid
						) ar
						ON RR.billnumberid=ar.BillNumberId	
						'
SET @SQL = @SQL + '
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Xzzd <> 1 AND @ETypeId <> ''
	SET @SQL = @SQL + '						
						AND AR.RepairItemsID = RR.ID'
						
IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.BillState = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND RR.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND RR.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND RR.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND RR.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND RR.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
IF @Xzzd = 0
	SET @SQL = @SQL + ' AND RR.Virtual = 1'
ELSE IF @Xzzd = 1
	SET @SQL = @SQL + ' AND RR.Virtual = 0'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
SET @SQL = @SQL + '
						GROUP BY RR.BillNumberId,
								 RepairMan,
								 RepairItemsTypeId
						
						UNION ALL
						
						SELECT QR.BillNumberId,
							   RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(CheckHour),0) AS CheckHour,
							   ISNULL(SUM(DiscountTotal),0) AS DiscountTotal,
							   ISNULL(SUM(CostTotal),0) AS CostTotal 
						FROM QP_QuickRepairBill_RepairItems QR
						INNER JOIN BillIndex B ON QR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON QR.BillNumberId = Bc.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = QR.RepairManTypeID
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Wxjd = 9
	SET @SQL = @SQL + ' AND 1 = 1'
ELSE IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.Status = 0'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.Status = 1'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.Status = 2'
	
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND QR.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND QR.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND QR.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND QR.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND QR.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

IF @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

SET @SQL = @SQL + '
						GROUP BY QR.BillNumberId,
								 RepairManTypeID,
								 RepairItemsTypeId
						
						UNION ALL
						
						SELECT SR.BillNumberId,
							   SR.ETypeId AS RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(CheckHour),0) AS CheckHour,
							   ISNULL(SUM(Total),0) AS DiscountTotal,
							   ISNULL(SUM(CostTotal),0) AS CostTotal
						FROM Qp_SuccorBill_RepairItems SR
						INNER JOIN BillIndex B ON SR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON SR.BillNumberId = Bc.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = SR.ETypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
SET @SQL = @SQL + '
						GROUP BY SR.BillNumberId,
								 SR.ETypeId,
								 RepairItemsTypeId
						)M ON LEFT(M.RITypeId,LEN(R.TypeId)) = R.TypeID'
						
				
SET @SQL = @SQL + ' GROUP BY R.TypeId,
							 R.UserCode,
							 R.SonNum,
							 R.ParId
					)M
				    WHERE M.TypeId LIKE '''+@WiTypeId+'%''
						  AND M.SonNum = 0
						  AND (
								  ISNULL(M.StandardManHour,0) <> 0 OR ISNULL(M.CheckHour,0) <> 0 OR ISNULL(M.DiscountTotal,0) <> 0 OR ISNULL(M.CostTotal,0) <> 0 OR ISNULL(M.ML,0) <> 0 OR ISNULL(M.MLL,0) <> 0
							  )						
					ORDER BY M.UserCode '


--PRINT(@SQL)	
EXEC(@SQL)		

DROP TABLE #GetManETypeId,#GetManDTypeId,#GetManBTypeId,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryRepairItemsAnsiList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryRepairItemsAnsiList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-11
	描述：维修项目统计树型表
*/

/*
	修改者：赵斌
	日期：2011-05-09
	描述：增加单据类型，修改查询条件
*/

/*
	修改者：赵斌
	日期：2011-07-06
	描述：维修进度不影响快修单
*/


CREATE PROCEDURE Qp_QueryRepairItemsAnsiList
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@ETypeId		VARCHAR(8000),
	@DTypeId		VARCHAR(8000),
	@WciTypeId		VARCHAR(8000),	--维修车辆信息档案ID
	@BTypeId		VARCHAR(8000),
	@WiTypeId		VARCHAR(8000),	--维修项目档案ID
	@Xzzd			VARCHAR(10),	--虚增字段
	@Wxjd			VARCHAR(10),	--维修进度
	@Bxzt			VARCHAR(10),	--状态
	@STypeId		VARCHAR(MAX)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------	
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--车牌号(不用控制权限范围)
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,00001)



DECLARE @SQL 	VARCHAR(8000),
		@SQL2 	VARCHAR(8000),
		@SonNum	INT
		
SET @SQL = ''

SELECT @SonNum = SonNum FROM QP_RepairItems WHERE typeId = @WiTypeId

IF @WiTypeId = ''
	SET @WiTypeId = '00000'
	
SET @SQL = 'SELECT R.TypeId,
				   R.UserCode,
				   R.SonNum,
				   R.ParId,
				   ISNULL(SUM(M.StandardManHour),0) AS StandardManHour,
				   ISNULL(SUM(M.CheckHour),0) AS CheckHour,
				   ISNULL(SUM(M.DiscountTotal),0) AS DiscountTotal,					
				   ISNULL(SUM(M.CostTotal),0) AS CostTotal,
				   ISNULL(SUM(M.DiscountTotal),0) - ISNULL(SUM(M.CostTotal),0) AS ML,
				   CAST(CASE WHEN ISNULL(SUM(M.DiscountTotal),0) = 0 THEN 0 ELSE (ISNULL(SUM(M.DiscountTotal),0) - ISNULL(SUM(M.CostTotal),0))/ISNULL(SUM(M.DiscountTotal),0)*100 END AS  NUMERIC(24, 10) ) AS MLL 
			FROM QP_RepairItems R
			LEFT JOIN(
						SELECT RR.BillNumberId,
							   RepairMan AS RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(RR.CheckHour),0) AS CheckHour,
							   ISNULL(SUM(DiscountTotal),0) AS DiscountTotal,
							   ISNULL(SUM(RR.CostTotal),0) AS CostTotal
						FROM Qp_ReceptionBill_RepairItems RR
						INNER JOIN BillIndex B ON RR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON RR.BillNumberId = Bc.BillNumberId
						'
--由于虚增维修项目没有修理工，所以当非虚增的时候才连接职员表
IF @Xzzd <> 1 AND @ETypeId <> ''
	SET @SQL = @SQL + 
						'
						INNER JOIN (
							SELECT DISTINCT a.BillNumberId,a.RepairItemsID
							FROM Qp_AttemperBill_RepairItemsPerson a
							INNER JOIN #GetManETypeId b
							ON a.etypeid=b.typeid
						) ar
						ON RR.billnumberid=ar.BillNumberId	
						'
SET @SQL = @SQL + '
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
IF @Xzzd <> 1 AND @ETypeId <> ''
	SET @SQL = @SQL + '						
						AND AR.RepairItemsID = RR.ID'
IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.BillState = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND RR.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND RR.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND RR.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND RR.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND RR.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
IF @Xzzd = 0
	SET @SQL = @SQL + ' AND RR.Virtual = 1'
ELSE IF @Xzzd = 1
	SET @SQL = @SQL + ' AND RR.Virtual = 0'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
SET @SQL = @SQL + '
						GROUP BY RR.BillNumberId,
								 RepairMan,
								 RepairItemsTypeId
						
						UNION ALL
						
						SELECT QR.BillNumberId,
							   RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(CheckHour),0) AS CheckHour,
							   ISNULL(SUM(DiscountTotal),0) AS DiscountTotal,
							   ISNULL(SUM(CostTotal),0) AS CostTotal 
						FROM QP_QuickRepairBill_RepairItems QR
						INNER JOIN BillIndex B ON QR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON QR.BillNumberId = Bc.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = QR.RepairManTypeID
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Wxjd = 9
	SET @SQL = @SQL + ' AND 1 = 1'
ELSE IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.Status = 0'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.Status = 1'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.Status = 2'
	
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND QR.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND QR.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND QR.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND QR.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND QR.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

IF @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

SET @SQL = @SQL + '
						GROUP BY QR.BillNumberId,
								 RepairManTypeID,
								 RepairItemsTypeId
						
						UNION ALL
						
						SELECT SR.BillNumberId,
							   SR.ETypeId AS RepairManTypeID,
							   RepairItemsTypeId AS RITypeId,
							   ISNULL(SUM(StandardManHour),0) AS StandardManHour,
							   ISNULL(SUM(CheckHour),0) AS CheckHour,
							   ISNULL(SUM(Total),0) AS DiscountTotal,
							   ISNULL(SUM(CostTotal),0) AS CostTotal
						FROM Qp_SuccorBill_RepairItems SR
						INNER JOIN BillIndex B ON SR.BillNumberId = B.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON SR.BillNumberId = Bc.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = SR.ETypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
SET @SQL = @SQL + '
						GROUP BY SR.BillNumberId,
								 SR.ETypeId,
								 RepairItemsTypeId
						)M ON LEFT(M.RITypeId,LEN(R.TypeId)) = R.TypeID'
						
IF @SonNum = 0
	SET @SQL = @SQL + ' WHERE R.TypeId = '''+@WiTypeId+''''
ELSE
	SET @SQL = @SQL + ' WHERE R.ParId = '''+@WiTypeId+''''
				
SET @SQL = @SQL + ' GROUP BY R.TypeId,
							 R.UserCode,
							 R.SonNum,
							 R.ParId
					ORDER BY R.UserCode '


--PRINT(@SQL)	
EXEC(@SQL)		

DROP TABLE #GetManETypeId,#GetManDTypeId,#GetManBTypeId,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairItemsLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairItemsLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-07-11
	描述：维修项目档案
*/
CREATE PROCEDURE QP_QueryRepairItemsLine
(
	@OperatorID	varchar(100),
	@TypeId		varchar(100),
	@UserCode	varchar(200),
	@FullName	varchar(200),
	@Xmlx		varchar(20),
	@Cx			varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #Result
(
	TypeId				varchar(100),
	UserCode			varchar(200),
	FullName			varchar(200),
	ItemType			varchar(200),
	StandardManHour		varchar(20),
	CheckHour			varchar(20),
	StandardPrice		varchar(20),
	TopPrice			varchar(20),
	LowPrice			varchar(20),
	ChargeMode			varchar(20),
	RepairAutoTypeId	varchar(100),
	MaintainDays		varchar(20),
	Comment				varchar(400),
	Path				varchar(2000)
)

DECLARE @chvTypeId			varchar(100),
		@chvUserCode		varchar(200),
		@chvFullName		varchar(200),
		@ItemType			varchar(200),
		@StandardManHour	varchar(20),
		@CheckHour			varchar(20),
		@StandardPrice		varchar(20),
		@TopPrice			varchar(20),
		@LowPrice			varchar(20),
		@ChargeMode			varchar(20),
		@RepairAutoTypeId	varchar(100),
		@MaintainDays		varchar(20),
		@Comment			varchar(400),
		@chvPath			varchar(2000),
		@ItemTypeValue		varchar(400),
		@ChargeModeValue	varchar(400),
		@Xmlx_C				varchar(20),
		@Cx_C				varchar(100)

--项目类型
IF @Xmlx = '3'
	SET @Xmlx_C = '%'
ELSE
	SET @Xmlx_C = @Xmlx

--车型
IF @Cx = ''
	SET @Cx_C = '%'
ELSE
	SET @Cx_C = @Cx

DECLARE AutoCursor CURSOR FOR
	SELECT 	TypeId,
			UserCode,
			FullName,
			ItemType,
			StandardManHour,
			CheckHour,
			StandardPrice,
			TopPrice,
			LowPrice,
			ChargeMode,
			RepairAutoTypeId,
			MaintainDays,
			Comment 
	FROM 	QP_RepairItems 
	WHERE 	TypeId LIKE @TypeId + '%' 
			AND UserCode LIKE '%'+@UserCode+'%' 
			AND FullName LIKE '%'+@FullName + '%' 
			AND TypeId <> '00000' 
			AND SonNum = 0
			AND RepairAutoTypeId LIKE @Cx_C 
			AND ItemType LIKE @Xmlx_C
	ORDER BY UserCode

OPEN AutoCursor

FETCH NEXT FROM AutoCursor INTO @chvTypeId,@chvUserCode,@chvFullName,@ItemType,@StandardManHour,@CheckHour,@StandardPrice,@TopPrice,@LowPrice,@ChargeMode,@RepairAutoTypeId,@MaintainDays,@Comment

WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC Web_GetParentPath1 @chvTypeId,15,@chvPath OUTPUT

		INSERT INTO #Result
		(	
			TypeId,
			UserCode,
			FullName,
			ItemType,
			StandardManHour,
			CheckHour,
			StandardPrice,
			TopPrice,
			LowPrice,
			ChargeMode,
			RepairAutoTypeId,
			MaintainDays,
			Comment,
			Path
		)VALUES(
			@chvTypeId,
			@chvUserCode,
			@chvFullName,
			@ItemType,
			@StandardManHour,
			@CheckHour,
			@StandardPrice,
			@TopPrice,
			@LowPrice,
			@ChargeMode,
			@RepairAutoTypeId,
			@MaintainDays,
			@Comment,
			REPLACE(@chvPath,'\','＼')
		)

		FETCH NEXT FROM AutoCursor INTO @chvTypeId,@chvUserCode,@chvFullName,@ItemType,@StandardManHour,@CheckHour,@StandardPrice,@TopPrice,@LowPrice,@ChargeMode,@RepairAutoTypeId,@MaintainDays,@Comment
	END

CLOSE AutoCursor
DEALLOCATE AutoCursor

SELECT * FROM #Result

DROP TABLE #Result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryRepairItemsList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryRepairItemsList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：谢吉康
	日期：2010-07-09
	描述：维修项目档案-树型表
*/
CREATE PROCEDURE QP_QueryRepairItemsList
(
	@OperatorId		varchar(100),		--操作员ID
	@TypeId			varchar(100)		--基本信息ID
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SonNum int

SELECT @SonNum = SonNum FROM QP_RepairItems WHERE TypeId = @TypeId

IF @SonNum = 0 
	SELECT * FROM QP_RepairItems WHERE TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
ELSE
	SELECT * FROM QP_RepairItems WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[QP_QuerySaleANDRepair_Detail]') AND OBJECTPROPERTY(id, N'ISPROCEDURE') = 1)
DROP PROCEDURE [dbo].[QP_QuerySaleANDRepair_Detail]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：张腾
	日期：2011-5-4
	描述：配件销售、维修统计报表
*/
/*
	修改:黄清
	日期：2011-7-20
	描述：增加维修结算单统计
*/
--查询条件：单据日期、分支机构、部门、往来单位、配件名称、经手人、单据类型
CREATE PROCEDURE QP_QuerySaleANDRepair_Detail
( 
	@OperatorID		VARCHAR(100) 	,  			-- 操作员
	@BillType	 	VARCHAR(50)   	='',		-- 单据类型
	@BeginDate	 	VARCHAR(25)  	='', 		-- 开始时间
	@EndDate	 	VARCHAR(25)  	='',   		-- 结束时间
	@EtypeName	 	VARCHAR(8000)	='',    	-- 经手人名称
	@BtypeName	 	VARCHAR(8000)	='',     	-- 往来单位名称
	@PTypeName    	VARCHAR(8000)	='',  		-- 商品名称 
	@stypeid        VARCHAR(8000)	='00001',   -- 分支机构
	@Department		VARCHAR(8000)	='',		-- 部门
	@PTypeid		VARCHAR(max)
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON



--权限检查
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re


DECLARE @SQL  VARCHAR(8000),
		@SQL_LIST  VARCHAR(2000),
		@SQL_FROM  VARCHAR(8000),
		@SQL_WHERE VARCHAR(8000),
		@SQL_ORDER VARCHAR(200),
		@FiltVal  VARCHAR(250),
		@SQL_SUM VARCHAR(8000);
		
SELECT @SQL_SUM = '',@SQL_LIST  = '',@SQL_WHERE = '',@SQL_FROM  = '',@SQL_ORDER = '',@SQL  = '';


DECLARE @SQL_DEBT VARCHAR(2000); -- 输入往来单位时用来统计调帐单
SET @SQL_DEBT ='';

SET @SQL_WHERE = ' WHERE 1=1 '
IF @BeginDate<>''
	SET @SQL_WHERE = @SQL_WHERE+' AND  bi.[BillDate]>=''' + RTRIM(@BeginDate) +'''';
IF @EndDate<>''
	SET @SQL_WHERE = @SQL_WHERE+'AND bi.[BillDate]<=''' + RTRIM(@EndDate) +'''';

SET @SQL_WHERE = @SQL_WHERE+' AND bi.IFCheck = ''t''
						AND bi.IFYearBill = 0
						AND Bi.BillType IN (305,11,45,160,141,195,178,196) ';

--单据类型
IF RTRIM(@BillType)<>''
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND bi.[BillType] in  (' + RTRIM(@BillType)+')';
	


--限制条件 部门信息
CREATE TABLE #Department(TypeId	VARCHAR(100));
SET @Department = RTRIM(LTRIM(@Department));
INSERT INTO #Department(TypeId) SELECT TypeId FROM F_GetAllManagerBaSETypeId(@Department,9,@OperatorID);
SELECT @SQL_WHERE =@SQL_WHERE + ' AND Bi.DTypeId IN (SELECT * FROM #Department)';		

--限制条件 经手人
CREATE TABLE #Employee(TypeId 	VARCHAR(100))
SET @EtypeName = LTRIM(RTRIM(@EtypeName))
--IF NOT (@METypeId = '00001')
--BEGIN
	INSERT INTO #Employee(TypeId) SELECT TypeId FROM F_GetAllManagerBaSETypeId(@EtypeName,3,@OperatorID)
	SELECT @SQL_WHERE =@SQL_WHERE + ' AND Bi.ETypeId IN (SELECT * FROM #Employee)'
	IF @EtypeName = ''
		INSERT INTO #Employee(TypeId)VALUES('')
--END;
			
--限制条件 分支机构
CREATE TABLE #Stype(TypeId 	VARCHAR(100))
SET @stypeid = LTRIM(RTRIM(@stypeid))
--IF NOT (@MStypeid = '00000')
--BEGIN
	INSERT INTO #Stype(TypeId) SELECT TypeId FROM F_GetAllManagerBaSETypeId(@stypeid,11,@OperatorID)
	SELECT @SQL_WHERE =@SQL_WHERE + ' AND Bi.sTypeId IN (SELECT * FROM #Stype)'
--END;	

-- 限制条件 往来单位
CREATE TABLE #BType(TypeId VARCHAR(100));
SET @BtypeName = LTRIM(RTRIM(@BtypeName));
IF NOT (@MBTypeId = '00000')
BEGIN
	INSERT INTO #BType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaSETypeId(@BtypeName,2,@OperatorID) S
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND (bi.BTypeId IN (SELECT TypeId FROM #BType) OR ISNULL(bi.BTypeId,'''')='''')'					
END

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
BEGIN
	IF RTRIM(@BtypeName)<>''
		SELECT @SQL_WHERE = @SQL_WHERE + ' AND bi.BtypeID IN (SELECT * FROM F_GetMANDetailBType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
	ELSE
		SELECT @SQL_WHERE = @SQL_WHERE + ' AND (bi.BtypeID IN (SELECT * FROM F_GetMANDetailBType('+CHAR(39)+@OperatorID+CHAR(39)+')) OR bi.BtypeID ='+CHAR(39)+''+CHAR(39)+')'
END

IF @PTypeName IS NULL OR @PTypeName='00000'
	SET	@PTypeName=''
DECLARE @sonnum INT 
SET @sonnum =0

CREATE TABLE #MainPtype (TypeID VARCHAR(50),parid VARCHAR(50),usercode VARCHAR(200),fullname VARCHAR(200),sonnum INT,leveal INT,unit1 VARCHAR(max),unit2 VARCHAR(max),unitrate1 VARCHAR(max))

IF @PTypeName=''
	INSERT INTO #MainPtype(typeid,parid,usercode,fullname,sonnum,leveal,unit1,unit2,unitrate1) 
	SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.unit1,p.unit2,p.unitrate1
	FROM	Ptype p,
			(SELECT * FROM F_GetMANDetailPType(@OperatorID)) a 
	WHERE p.typeid=a.typeid
ELSE
	INSERT INTO #MainPtype(typeid,parid,usercode,fullname,sonnum,leveal,unit1,unit2,unitrate1) 
	SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.unit1,p.unit2,p.unitrate1
	FROM	Ptype p,
			(SELECT * FROM F_GetMANDetailPType(@OperatorID) WHERE typeid like @PTypeName+'%') a 
	WHERE	p.typeid=a.typeid



		
-- 限制条件 配件名称 
SET @PTypeName = LTRIM(RTRIM(@PTypeName))
CREATE TABLE #PType(TypeId		VARCHAR(100))
INSERT INTO #PType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaSETypeId(@PTypeName,1,@OperatorID) S
--IF(@MPtypeid<>'00000')
--BEGIN
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND (TypeID IN (SELECT * FROM #PType)) '
	--SELECT @SQL_WHERE = @SQL_WHERE + ' AND Bi.BillType IN (305,11,45,160,141,166,178)'
--END
IF @PTypeName<>''
	SET @SQL_WHERE=@SQL_WHERE+' AND t.ptypeid LIKE '+CHAR(39)+@PTypeName+'%'+CHAR(39)

--销售出库单、销售退货单、零售单、委托代销结算单、销售换货单、快修单、维修单
DECLARE @BillTypes VARCHAR(2000)
SET @BillTypes ='(9999'
DECLARE @re_re INT 
IF @OperatorID<>'00001'  -- 相关单据调阅权限
BEGIN
	EXEC @re_re=GP_CheckLimit @OperatorID,349  -- 零售单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',305'
	EXEC @re_re=GP_CheckLimit @OperatorID,350  -- 销售出库单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',11'
	EXEC @re_re=GP_CheckLimit @OperatorID,351  -- 销售退货单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',45'
	EXEC @re_re=GP_CheckLimit @OperatorID,358   -- 委托代销结算单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',141'
	EXEC @re_re=GP_CheckLimit @OperatorID,583   -- 销售换货单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',160'	
	EXEC @re_re=GP_CheckLimit @OperatorID,1533   -- 维修结算单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',195'
	EXEC @re_re=GP_CheckLimit @OperatorID,1377   -- 快修单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',178'	
	EXEC @re_re=GP_CheckLimit @OperatorID,1535   -- 救援单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',196'	
END 
SET @BillTypes = @BillTypes +' ) '

IF @OperatorID<>'00001'
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND Bi.BillType in ' +@BillTypes
	
SELECT @SQL ='SELECT 
					t.BillNumberId,
					t.BillDate AS BillDate,
					t.billtype,
					-ISNULL(SUM(t.qty),0) as qty,
					t.Price,
					-ISNULL(SUM(t.Costtotal),0) as Costtotal,
					-ISNULL(SUM(t.total),0) as total,
					-(ISNULL(SUM(t.total),0)-ISNULL(SUM(t.Costtotal),0)) as maoli,
					maoliper=
						CASE t.total
							WHEN 0 THEN NULL
							ELSE ((ISNULL(SUM(t.total),0)-ISNULL(SUM(t.Costtotal),0))/ISNULL(SUM(t.total),0))*100 
						END,
					t.CostPrice,
					bi.DTypeId as dtype,
					bi.BillCode, 
					bi.Comment,
					bi.RedWord, 
					CBillType=
						CASE bi.billtype 
							WHEN 305 THEN ''零售单''
							WHEN 11  THEN ''销售出库单''
							WHEN 45  THEN ''销售退货单''
							WHEN 141 THEN ''委托代销结算单''
							WHEN 160 THEN ''销售换货单''
							WHEN 178 THEN ''快修单''
							WHEN 196 THEN ''救援单''
						END,
					t.ptypeid AS ptype,
					bi.btypeid AS btype,
					t.ktypeid AS ktype,
					t.stypeid AS stype,
					t.etypeid AS etype	
		FROM BillIndex bi 
		INNER JOIN inoutstocktable t ON (bi.[BillNumberId] = t.[BillNumberId])' + ' LEFT Join Ptype p ON (t.[ptypeid] = p.[typeid]) '
		+@SQL_WHERE+' AND bi.RedWord=''0''  AND bi.ifYearBill=0	 --年节存标志
		GROUP BY 
					t.BillNumberId,
					t.billdate,
					t.billtype,
					bi.dtypeid,
					bi.billtype,
					t.costprice,
					t.Price,
					t.qty,
					t.total,
					bi.billcode,
					bi.comment,
					bi.redword,
					t.ptypeid,
					bi.btypeid,
					t.ktypeid,
					t.stypeid,
					t.etypeid
		UNION ALL
		SELECT	bi.BillnumberID,
				bi.BillDate,
				bi.BillType,
				ISNULL(SUM(a.Qty),0) as qty,
				a.DIScountPrice,
				ISNULL(SUM(a.Costtotal),0) as Costtotal,
				ISNULL(SUM(a.DIScountTotal),0) as total,
				(ISNULL(SUM(a .DIScountTotal),0)-ISNULL(SUM(a .Costtotal),0)) as maoli,
				maoliper=
					CASE a.DIScountTotal
						WHEN 0 THEN NULL
						ELSE ((ISNULL(SUM(a .DIScountTotal),0)-ISNULL(SUM(a .Costtotal),0)) /ISNULL(SUM(a.DIScountTotal),0))*100 
					END,
				costprice=
					CASE a.QTY
						WHEN 0 THEN NULL
						ELSE (ISNULL(SUM(a .Costtotal),0)/ISNULL(SUM(a .Qty),0)) 
					END,--as costprice,
				bi.DTypeId as dtype,
				bi.BillCode as billcode,
				bi.Comment as comment,
				bi.RedWord as redword,
				CBillType=
				CASE bi.billtype 
					WHEN 195 THEN ''维修结算单''
				END,
				a.ptypeid AS ptype,
				bi.btypeid AS btype,
				bi.ktypeid AS ktype,
				bi.stypeid AS stype,
				bi.etypeid AS etype
		FROM BillIndex bi
		inner join Qp_ReceptionBill_FactUsePType a on a.ReceptionBillnumberId=bi.BillNumberId
		--INNER JOIN InOutstocktable I ON A.BillNumberId=I.BillNumberId
		WHERE bi.BillType=''195'' AND bi.IFcheck=''t'' AND bi.RedWord=''0''
		AND bi.[BillDate]>='''+@BeginDate+'''
		AND bi.[BillDate]<='''+@EndDate+'''          
		AND bi.DTypeId IN (SELECT * FROM #Department) 
		--AND I.DTypeId IN (SELECT * FROM #Department)
		AND bi.ETypeId IN (SELECT * FROM #Employee) 
		--AND I.ETypeId IN (SELECT * FROM #Employee) 
		AND bi.sTypeId IN (SELECT * FROM #Stype) 
		AND (bi.BTypeId IN (SELECT * FROM #BType) OR ISNULL(bi.BTypeId,'''')='''') 
		AND (a.ptypeid IN (SELECT * FROM #PType))
		AND Bi.BillType in  ('+@BillType+')
		AND A.QTY<>0
		AND bi.ifYearBill=0	 --年节存标志
		group by 
			bi.BillNumberId,
			bi.RedWord,
			bi.BillDate,
			bi.BillType,
			a.PTypeID,
			bi.DTypeId,
			bi.BillCode,
			bi.Comment,
			bi.RedWord,
			bi.btypeid,
			bi.etypeid,
			bi.Stypeid,
			bi.ktypeid,
			a.PTypeID,
			a.Qty,
			a.total,
			a.DIScountPrice,
			a.DIScountTotal,
			a.CostTotal,
			a.DIScount
		ORDER BY 	BillDate,BillCode '

	--prINT(@SQL)
	EXEC(@SQL)

-- 单据明细摘要查询


-- ========================================= 删除临时表

IF RTRIM(@BtypeName)<>''
	DROP TABLE #BType
IF RTRIM(@PTypeName)<>''
	DROP TABLE #PType

--IF NOT (@stypeid='' AND @MStypeid = '00000')
	DROP TABLE #Stype	

DROP TABLE #Employee,#Department
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QuerySaleAndRepair_Line]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QuerySaleAndRepair_Line]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：张腾
	日期：2011-5-4
	描述：配件销售、维修统计报表
*/
/*
	修改:黄清
	日期:2011-7-19
	描述:增加维修结算单统计
*/

--查询条件：单据日期、分支机构、部门、往来单位、配件名称、经手人、单据类型
CREATE PROCEDURE QP_QuerySaleAndRepair_Line
( 
	@OperatorID		varchar(100) 	,  			-- 操作员
	@BillType	 	varchar(50)   	='',		-- 单据类型
	@BeginDate	 	varchar(25)  	='', 		-- 开始时间
	@EndDate	 	varchar(25)  	='',   		-- 结束时间
	@Etypeid	 	varchar(8000)	='',    	-- 经手人名称
	@Btypeid	 	varchar(8000)	='',     	-- 往来单位名称
	@PTypeid    	varchar(8000)	='',  		-- 商品名称 
	@stypeid        varchar(8000)	='00001',   -- 分支机构
	@Dtypeid		varchar(8000)	='',		-- 部门
	@ParID  		VARCHAR(50)
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------


CREATE TABLE #Ptype (TypeID varchar(200))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #MainType (
	TypeID varchar(200),
	usercode varchar(200),
	fullname varchar(200),
	sonnum int,deleted int,
	unit1 varchar(8),
	type varchar(200),
	area varchar(200),
	entrycode varchar(200),
	standard varchar(200)
)

IF @ptypeid ='00000' OR @ptypeid=''
	INSERT INTO #Ptype(typeid) select typeid from F_GetManDetailPType(@OperatorID)
ELSE
	INSERT INTO #Ptype(typeid) select a.typeid from F_GetManDetailPType(@OperatorID) a, (select * from  dbo.f_split(@ptypeid,',')) b where left(a.typeid,len(b.a))=b.a

-- 限制条件 往来单位
IF @btypeid =''
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@btypeid,',')) b where left(a.typeid,len(b.a))=b.a

--限制条件 经手人
IF @etypeid=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@etypeid,',')) b where left(a.typeid,len(b.a))=b.a

IF @dtypeid=''
BEGIN
	--INSERT INTO #Dtype select typeid from DepartMent where Sonnum =0 and deleted =0
	INSERT INTO #Dtype SELECT ''
END
--ELSE
	--INSERT INTO #Dtype select typeid from department a ,(select * from  dbo.f_split(@dtypeid,',')) b where left(a.typeid,len(b.a))=b.a
INSERT INTO #Dtype select typeid from F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)

--限制条件 分支机构
IF NOT(@stypeid='' and @MStypeid='00000')
    INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DECLARE @sonnum int 
SET @sonnum =0

DECLARE
	@strTemp	VARCHAR(8000)

CREATE TABLE [dbo].[#Billtype] (
	[Billtype] varchar(200)
)
INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@BillType,',')

CREATE TABLE #BillIndex(
	BillNumberId numeric(10, 0) ,
	RedWord  int ,
	Billdate VARCHAR(MAX),
	Billtype varchar(max),
	BtypeId  varchar (50),
	EtypeId  varchar (50),
	KtypeId  varchar (50),
	KtypeId2 varchar (50),
	preferencemoney  NUMERIC(24, 10) ,
    bflag bit,
    ifcheck varchar(max)
)
	SELECT @strTemp=' 
	INSERT INTO #BillIndex(BillnumberID,billdate,billtype,RedWord,BtypeID,EtypeID,ifcheck) 
	SELECT distinct BillnumberID,billdate,b.billtype,RedWord,BtypeID,EtypeID,ifcheck 


	FROM BillIndex b
	INNER JOIN #Billtype BILL ON b.billtype=BILL.billtype '

	IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
	SET @strTemp=@strTemp+' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '

	IF @etypeid<>'' OR @METypeID=-99999 
	SET @strTemp=@strTemp+' INNER JOIN #Etype e  ON b.etypeid=e.typeid '

	IF @dtypeid<>'' OR @MDTypeID=-99999
	SET @strTemp=@strTemp+' INNER JOIN #Dtype d  ON  b.DtypeID=d.typeid '

	IF NOT(@stypeid='' and @MStypeid='00000')
	SET @strTemp=@strTemp+' INNER JOIN #Stype s  ON  b.stypeID=s.typeid '

	SET @strTemp=@strTemp+' WHERE b.RedWord=0 AND b.Draft =0  AND b.BillDate>='+CHAR(39)+@BeginDate+CHAR(39)+' AND b.BillDate<='+CHAR(39)+@endDate+CHAR(39)+ '  AND b.ifYearBill=0'	 --年节存标志 
	EXEC(@strTemp) 

CREATE TABLE #InoutStockTable(
	BillNumberId numeric(10, 0) ,
	RedWord int ,
	BillDate datetime,
	BillType numeric(4,0),
	PtypeId varchar (50),
	BtypeId varchar (50),
	EtypeId varchar (50),
	KtypeId varchar (50),
	Qty  NUMERIC(24, 10) ,
	Price  NUMERIC(24, 10) ,
	Total  NUMERIC(24, 10) ,
	CostTotal  NUMERIC(24, 10) ,
	Tax  NUMERIC(24, 10) ,
	Discount  NUMERIC(24, 10) ,
	SaleTotal  NUMERIC(24, 10) ,
	TaxTotal  NUMERIC(24, 10) 
)

SELECT @strTemp='
INSERT INTO #InoutStockTable(BillnumberID,RedWord,BillDate,BillType,PtypeID,BtypeID,EtypeID,KtypeID,Qty,Price,Total,CostTotal,Tax,Discount,SaleTotal,TaxTotal)
SELECT a.BillnumberID,
		b.RedWord,
		a.BillDate,
		a.BillType,
		a.PtypeID,
		a.BtypeID,
		a.EtypeID,
		a.KtypeID,
		-a.Qty,
		Price,
		-Convert( NUMERIC(24, 10) ,a.Total),
		-Convert( NUMERIC(24, 10) ,a.CostTotal),
		a.Tax,a.Discount,
		-Convert( NUMERIC(24, 10) ,a.SaleTotal),
		-Convert( NUMERIC(24, 10) ,a.TaxTotal)
FROM #Billindex b
INNER JOIN InoutStockTable a
ON a.BillnumberID=b.BillnumberID
'
IF @ptypeid<>'' OR @MPTypeID=-99999 SET @strTemp=@strTemp+'	INNER JOIN #Ptype p ON a.ptypeid=p.typeid '+CHAR(13)

EXEC(@strTemp)

IF 195 IN (SELECT *FROM f_split(@BillType,','))
BEGIN
SELECT @strTemp='
INSERT INTO #InoutStockTable(BillnumberID,RedWord,BillDate,BillType,PtypeID,BtypeID,EtypeID,KtypeID,Qty,Price,Total,CostTotal,Tax,Discount,SaleTotal,TaxTotal)
select bi.BillNumberId as billnumberid,
		bi.RedWord as RedWord,
		bi.BillDate as billdate,
		bi.BillType as billtype,
		a.PTypeID as ptypeid,
		bi.btypeid as btypeid,
		bi.etypeid as etypeid,
		bi.ktypeid as ktypeid,
		SUM(a.Qty) as qty,
		SUM(a.DiscountTotal)/SUM(a.Qty) as price,
		SUM(a.DiscountTotal) as total,
		SUM(a.CostTotal) as costtotal,
		''1'' as tax,
		a.Discount as dicount,
		Convert( NUMERIC(24, 10) ,a.DiscountTotal/a.Discount) as saletotal,
		a.DiscountTotal as taxtotal
from #BillIndex bi
inner join Qp_ReceptionBill_FactUsePType a on a.ReceptionBillnumberId=bi.BillNumberId
'

IF @ptypeid<>'' OR @MPTypeID=-99999 SET @strTemp=@strTemp+'	INNER JOIN #Ptype p ON a.ptypeid=p.typeid '+CHAR(13)

SELECT @strTemp=@strTemp+'where bi.BillType=''195'' and bi.ifcheck=''t''  AND a.Qty<>0
						group by 
							bi.BillNumberId,
							bi.RedWord,
							bi.BillDate,
							bi.BillType,
							a.PTypeID,
							bi.btypeid,
							bi.etypeid,
							bi.ktypeid,
							a.DiscountPrice,
							a.DiscountTotal,
							a.CostTotal,
							a.Discount'
	EXEC(@strTemp)
END


IF @Parid IS NULL
	SET @Parid='00000'
	
SELECT @sonnum = sonnum FROM Ptype WHERE Typeid =@parid
IF @sonnum =0 
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,unit1,type,area,entrycode,standard) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.unit1,p.type,p.area,p.entrycode,p.standard FROM Ptype p
	,(select * from F_BaseGetManDetailPType(@OperatorID) where typeid =@parid) a where p.typeid=a.typeid
ELSE
	IF @ptypeid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,unit1,type,area,entrycode,standard) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.unit1,p.type,p.area,p.entrycode,p.standard FROM Ptype p
			,(select * from F_BaseGetManDetailPType(@OperatorID)) a where p.typeid=a.typeid
	ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,unit1,type,area,entrycode,standard) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.unit1,p.type,p.area,p.entrycode,p.standard FROM Ptype p
		,(select * from F_BaseGetManDetailPType(@OperatorID) where typeid LIKE @ptypeid+'%' ) a where p.typeid=a.typeid

DECLARE @SQL varchar(4000)
SET @SQL ='SELECT  
				B.ptypeid AS ptypeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				a.deleted,
				SUM(ISNULL(B.QTY,0)) as qty,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  ISNULL(SUM(ISNULL(b.total,0)),0)/SUM(ISNULL(b.qty,0)) END) as Price,
				ISNULL(SUM(ISNULL(b.total,0)),0) as Total,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  ISNULL(SUM(ISNULL(b.CostTotal,0)),0)/SUM(ISNULL(b.qty,0)) END) as CostPrice,
				ISNULL(SUM(ISNULL(b.CostTotal,0)),0) as CostTotal,
				ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0) as MaoLi,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.Total,0)),0)=0 THEN 0 ELSE (ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0) )/SUM(ISNULL(b.Total,0))*100 end) as maoliper
		   FROM #MainType a 
		   INNER JOIN #InoutStockTable b   
		   ON a.TypeID = b.ptypeid
		   GROUP BY 
				B.ptypeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				a.deleted
			ORDER BY a.UserCode '
--PRINT @SQL
EXEC(@SQL)

--删除临时表
DROP TABLE #Ptype
DROP TABLE #Btype
DROP TABLE #Etype
DROP TABLE #Ktype
DROP TABLE #Dtype
DROP TABLE #Maintype
DROP TABLE #InoutStockTable,#Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QuerySaleAndRepair_Tree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QuerySaleAndRepair_Tree]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：张腾
	日期：2011-5-4
	描述：配件销售、维修统计报表
*/
/*------------------------------------------
	作者：黄清
	日期：2011-6-27
	描述：修改
-------------------------------------------*/
--查询条件：单据日期、分支机构、部门、往来单位、配件名称、经手人、单据类型
CREATE PROCEDURE QP_QuerySaleAndRepair_Tree
( 
	@OperatorID		varchar(100) 	,  			-- 操作员
	@BillType	 	varchar(max)   	='',		-- 单据类型
	@startdate	 	varchar(25)  	='', 		-- 开始时间
	@enddate	 	varchar(25)  	='',   		-- 结束时间
	@etypeid	 	varchar(8000)	='',    	-- 经手人名称
	@btypeid	 	varchar(8000)	='',     	-- 往来单位名称
	@ptypeid    	varchar(8000)	='',  		-- 商品名称 
	@stypeid        varchar(8000)	='',   -- 分支机构
	@dtypeid		varchar(8000)	='',		-- 部门
	@Parid  		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------


CREATE TABLE #Ptype (TypeID varchar(200))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #MainType (
	TypeID varchar(200),
	usercode varchar(200),
	fullname varchar(200),
	sonnum int,deleted int,
	unit1 varchar(8),
	type varchar(200),
	area varchar(200),
	entrycode varchar(200),
	standard varchar(200)
)

IF @ptypeid =''
	INSERT INTO #Ptype(typeid) select typeid from F_GetManDetailPType(@OperatorID)
ELSE
	INSERT INTO #Ptype(typeid) select a.typeid from F_GetManDetailPType(@OperatorID) a, (select * from  dbo.f_split(@ptypeid,',')) b where left(a.typeid,len(b.a))=b.a

-- 限制条件 往来单位
IF @btypeid =''
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@btypeid,',')) b where left(a.typeid,len(b.a))=b.a

--限制条件 经手人
IF @etypeid=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@etypeid,',')) b where left(a.typeid,len(b.a))=b.a

IF @dtypeid=''
BEGIN
	--INSERT INTO #Dtype select typeid from DepartMent where Sonnum =0 and deleted =0
	INSERT INTO #Dtype SELECT ''
END
--ELSE
	--INSERT INTO #Dtype select typeid from department a ,(select * from  dbo.f_split(@dtypeid,',')) b where left(a.typeid,len(b.a))=b.a
INSERT INTO #Dtype select typeid from F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)

--限制条件 分支机构
IF NOT(@stypeid='' and @MStypeid='00000')
    INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
    
DECLARE @sonnum int 
SET @sonnum =0

DECLARE
	@strTemp	VARCHAR(8000)

CREATE TABLE [dbo].[#Billtype] (
	[Billtype] varchar(200)
)
INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@BillType,',')

CREATE TABLE #BillIndex(
	BillNumberId numeric(10, 0) ,
	RedWord  int ,
	Billdate VARCHAR(MAX),
	Billtype varchar(max),
	BtypeId  varchar (50),
	EtypeId  varchar (50),
	KtypeId  varchar (50),
	KtypeId2 varchar (50),
	preferencemoney  NUMERIC(24, 10) ,
    bflag bit,
    ifcheck varchar(max)
)
	SELECT @strTemp=' 
	INSERT INTO #BillIndex(BillnumberID,billdate,billtype,RedWord,BtypeID,EtypeID,ifcheck) 
	SELECT distinct BillnumberID,billdate,b.billtype,RedWord,BtypeID,EtypeID,ifcheck 

	FROM BillIndex b
	INNER JOIN #Billtype BILL ON b.billtype=BILL.billtype '

	IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
	SET @strTemp=@strTemp+' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '

	IF @etypeid<>'' OR @METypeID=-99999 
	SET @strTemp=@strTemp+' INNER JOIN #Etype e  ON b.etypeid=e.typeid '

	IF @dtypeid<>'' OR @MDTypeID=-99999
	SET @strTemp=@strTemp+' INNER JOIN #Dtype d  ON  b.DtypeID=d.typeid '

	IF NOT(@stypeid='' and @MStypeid='00000')
	SET @strTemp=@strTemp+' INNER JOIN #Stype s  ON  b.stypeID=s.typeid '

	SET @strTemp=@strTemp+' WHERE b.RedWord=0 AND b.Draft =0  AND b.BillDate>='+CHAR(39)+@startdate+CHAR(39)+' AND b.BillDate<='+CHAR(39)+@enddate+CHAR(39)+ '  AND b.ifYearBill=0' --年节存标志
	EXEC(@strTemp) 

CREATE TABLE #InoutStockTable(
	BillNumberId numeric(10, 0) ,
	RedWord int ,
	BillDate datetime,
	BillType numeric(4,0),
	PtypeId varchar (50),
	BtypeId varchar (50),
	EtypeId varchar (50),
	KtypeId varchar (50),
	Qty  NUMERIC(24, 10) ,
	Price  NUMERIC(24, 10) ,
	Total  NUMERIC(24, 10) ,
	CostTotal  NUMERIC(24, 10) ,
	Tax  NUMERIC(24, 10) ,
	Discount  NUMERIC(24, 10) ,
	SaleTotal  NUMERIC(24, 10) ,
	TaxTotal  NUMERIC(24, 10) 
)

SELECT @strTemp='
INSERT INTO #InoutStockTable(BillnumberID,RedWord,BillDate,BillType,PtypeID,BtypeID,EtypeID,KtypeID,Qty,Price,Total,CostTotal,Tax,Discount,SaleTotal,TaxTotal)
SELECT a.BillnumberID,
		b.RedWord,
		a.BillDate,
		a.BillType,
		a.PtypeID,
		a.BtypeID,
		a.EtypeID,
		a.KtypeID,
		-a.Qty,
		Price,
		-Convert( NUMERIC(24, 10) ,a.Total),
		-Convert( NUMERIC(24, 10) ,a.CostTotal),
		a.Tax,a.Discount,
		-Convert( NUMERIC(24, 10) ,a.SaleTotal),
		-Convert( NUMERIC(24, 10) ,a.TaxTotal)
FROM #Billindex b
INNER JOIN InoutStockTable a
ON a.BillnumberID=b.BillnumberID
'

IF @ptypeid<>'' OR @MPTypeID=-99999 SET @strTemp=@strTemp+'	INNER JOIN #Ptype p ON a.ptypeid=p.typeid '+CHAR(13)

EXEC(@strTemp)


IF 195 IN (SELECT *FROM f_split(@BillType,','))
BEGIN
SELECT @strTemp='
INSERT INTO #InoutStockTable(BillnumberID,RedWord,BillDate,BillType,PtypeID,BtypeID,EtypeID,KtypeID,Qty,Price,Total,CostTotal,Tax,Discount,SaleTotal,TaxTotal)
select bi.BillNumberId as billnumberid,
		bi.RedWord as RedWord,
		bi.BillDate as billdate,
		bi.BillType as billtype,
		a.PTypeID as ptypeid,
		bi.btypeid as btypeid,
		bi.etypeid as etypeid,
		bi.ktypeid as ktypeid,
		SUM(a.Qty) as qty,
		SUM(a.DiscountTotal)/SUM(a.Qty) as price,
		SUM(a.DiscountTotal) as total,
		SUM(a.CostTotal) as costtotal,
		''1'' as tax,
		a.Discount as dicount,
		Convert( NUMERIC(24, 10) ,a.DiscountTotal/a.Discount) as saletotal,
		a.DiscountTotal as taxtotal
from #BillIndex bi
inner join Qp_ReceptionBill_FactUsePType a on a.ReceptionBillnumberId=bi.BillNumberId
'

	IF @ptypeid<>'' OR @MPTypeID=-99999 SET @strTemp=@strTemp+'	INNER JOIN #Ptype p ON a.ptypeid=p.typeid '+CHAR(13)
	BEGIN
	SELECT @strTemp=@strTemp+'where bi.BillType=''195'' and bi.ifcheck=''t''  AND a.Qty<>0
							group by 
								bi.BillNumberId,
								bi.RedWord,
								bi.BillDate,
								bi.BillType,
								a.PTypeID,
								bi.btypeid,
								bi.etypeid,
								bi.ktypeid,
								a.Qty,
								a.DiscountPrice,
								a.DiscountTotal,
								a.CostTotal,
								a.Discount'
	END
	--PRINT(@strTemp)
	EXEC(@strTemp)
END


IF @Parid IS NULL or @Parid=''
	SET @Parid='00000'
	
DECLARE @Len int
	IF @parid = '00000'
		SET @Len = 5
	else
		SET @Len = len(@parid)+5

SELECT @sonnum = sonnum FROM Ptype WHERE Typeid =@parid
IF @sonnum =0 
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,unit1,type,area,entrycode,standard) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.unit1,p.type,p.area,p.entrycode,p.standard FROM Ptype p
	,(select * from F_BaseGetManPTypeAll(@OperatorID) where typeid =@parid) a where p.typeid=a.typeid
ELSE
	IF @ptypeid=''
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,unit1,type,area,entrycode,standard) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.unit1,p.type,p.area,p.entrycode,p.standard FROM Ptype p
			,(select * from F_BaseGetManPTypeAll(@OperatorID) where parid=case  when @parid='' then '00000' else @parid end) a where p.typeid=a.typeid
	ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,unit1,type,area,entrycode,standard) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.unit1,p.type,p.area,p.entrycode,p.standard FROM Ptype p
		,(select * from F_BaseGetManPTypeAll(@OperatorID) where parid=case  when @parid='' then '00000' else @parid end    and typeid LIKE @ptypeid+'%' ) a where p.typeid=a.typeid

DECLARE @SQL varchar(4000)

SET @SQL ='SELECT 
				a.typeid AS typeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				a.deleted,
				SUM(ISNULL(B.QTY,0)) as Qty,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  ISNULL(SUM(ISNULL(b.total,0)),0)/SUM(ISNULL(b.qty,0)) END) as Price,
				ISNULL(SUM(ISNULL(b.total,0)),0) as Total,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  ISNULL(SUM(ISNULL(b.CostTotal,0)),0)/SUM(ISNULL(b.qty,0)) END) as costprice,
				ISNULL(SUM(ISNULL(b.CostTotal,0)),0) as CostTotal,
				ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0) as MaoLi,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.Total,0)),0)=0 THEN 0 ELSE (ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0) )/SUM(ISNULL(b.Total,0))*100 end) as maoliper
		   FROM #MainType a 
		   LEFT JOIN #InoutStockTable b   
		   ON a.TypeID =  left(b.ptypeid, '+cast(@Len as varchar)+')
		   GROUP BY 
				a.typeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				a.deleted
			ORDER BY a.UserCode '
--PRINT @SQL
EXEC(@SQL)

--删除临时表
DROP TABLE #Ptype
DROP TABLE #Btype
DROP TABLE #Etype
DROP TABLE #Ktype
DROP TABLE #Dtype
DROP TABLE #Maintype
DROP TABLE #InoutStockTable,#Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QuerySaleInfoFx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QuerySaleInfoFx]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-30
	描述：销售经营情况日统计（销售经营情况月统计）
	EXEC Qp_QuerySaleInfoFx '00001','2000-08-30','2010-09-30','','d'
	
	作者：徐辉
	日期：2011-04-27
	描述：权限调整
*/

CREATE PROCEDURE Qp_QuerySaleInfoFx
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@DTypeId		VARCHAR(8000),
	@STypeId		VARCHAR(8000),
	@nType			VARCHAR(10)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

IF @nType = 'm'
	BEGIN
		IF ISDATE(@EndDate)=1
			SET @EndDate = @EndDate
		ELSE IF ISDATE(REPLACE(@EndDate,'-31','-30'))=1
			SET @EndDate = REPLACE(@EndDate,'-31','-30')
		ELSE IF ISDATE(REPLACE(@EndDate,'-31','-29'))=1
			SET @EndDate = REPLACE(@EndDate,'-31','-29')
		ELSE IF ISDATE(REPLACE(@EndDate,'-31','-28'))=1
			SET @EndDate = REPLACE(@EndDate,'-31','-28')
	END

CREATE TABLE #RQ
(
	nId		INT identity(1,1),
	nName	VARCHAR(100)
)

CREATE TABLE #Result
(
	RDay		VARCHAR(10),
	NDay		VARCHAR(20),
	Zgsr		 NUMERIC(24, 10)  DEFAULT(0),
	Xssr		 NUMERIC(24, 10)  DEFAULT(0),
	Thsr		 NUMERIC(24, 10)  DEFAULT(0),
	Srhj		 NUMERIC(24, 10)  DEFAULT(0),
	Bqsr		 NUMERIC(24, 10)  DEFAULT(0),
	zgcb		 NUMERIC(24, 10)  DEFAULT(0),
	Xscb		 NUMERIC(24, 10)  DEFAULT(0),
	Thcb		 NUMERIC(24, 10)  DEFAULT(0),
	Bqzc		 NUMERIC(24, 10)  DEFAULT(0),
	Srcb		 NUMERIC(24, 10)  DEFAULT(0),	
	Xsml		 NUMERIC(24, 10)  DEFAULT(0),
	LsThsr		 NUMERIC(24, 10)  DEFAULT(0),--零售退货收入
	LsThcb		 NUMERIC(24, 10)  DEFAULT(0)--零售退货成本
		
)
DECLARE @Date		VARCHAR(10),
		@Yd			VARCHAR(10),
		@Md			VARCHAR(10),
		@Dd			VARCHAR(10),
		@i			NUMERIC(18,0),
		@SR			VARCHAR(50),
		@CB			VARCHAR(50)

SELECT @SR=NID FROM AC_ITEMS WHERE USERCODE='5101'--销售收入，0000300001
SELECT @CB=NID FROM AC_ITEMS WHERE USERCODE='5401'--销售成本，0000400001

SET @i = 0

IF @nType = 'd'	--日分析
	BEGIN
		WHILE @i<=DATEDIFF (DAY,@StartDate,@EndDate)
			BEGIN
				IF @i = 0
					SET @Date = CONVERT(VARCHAR(10),DATEADD(Day,0,@StartDate),120)		
				ELSE
					SET @Date = CONVERT(VARCHAR(10),DATEADD(Day,1,@Date),120)		
		
				IF @Date <= @EndDate
					BEGIN
						TRUNCATE TABLE #RQ
						INSERT INTO #RQ(nName) SELECT A FROM dbo.f_split(@Date,'-')
						SELECT @Yd = nName FROM #RQ WHERE nId = 1
						SELECT @Md = nName FROM #RQ WHERE nId = 2
						SELECT @Dd = nName FROM #RQ WHERE nId = 3
						INSERT INTO #Result(RDay,NDay)VALUES(@Date,@Yd+'年'+@Md+'月'+@Dd+'日')
					END
		
				SET @i = @i + 1
			END
	END
ELSE
	BEGIN
		WHILE @i<=DATEDIFF (MONTH,@StartDate,@EndDate)
			BEGIN
				IF @i = 0
					SET @Date = CONVERT(VARCHAR(10),DATEADD(MONTH,0,@StartDate),120)		
				ELSE
					SET @Date = CONVERT(VARCHAR(10),DATEADD(MONTH,1,@Date),120)		
		
				IF @Date <= @EndDate
					BEGIN
						TRUNCATE TABLE #RQ
						INSERT INTO #RQ(nName) SELECT A FROM dbo.f_split(@Date,'-')
						SELECT @Yd = nName FROM #RQ WHERE nId = 1
						SELECT @Md = nName FROM #RQ WHERE nId = 2
						INSERT INTO #Result(RDay,NDay)VALUES(@Yd+@Md,@Yd+'年'+@Md+'月')
					END
		
				SET @i = @i + 1
			END
	END

DECLARE @SQL VARCHAR(8000)=''

CREATE TABLE #ListTable
(
	BillDate	VARCHAR(20),
	BillType	INT,
	ATypeId		VARCHAR(50),
	Total		 NUMERIC(24, 10) ,
	typeName	VARCHAR(2)
)

IF @nType = 'd'
BEGIN
	SET @SQL = 'INSERT INTO #ListTable '
	SET @SQL = @SQL + '
			SELECT	dbo.F_FormatDate(L.BillDate,''-'',''-'') AS BillDate, 
					L.BillType,
					L.ATypeId,
					ISNULL(L.Total,0) AS Total,
					A.typeName
			FROM	ListTable L 
			INNER JOIN AC_items  a ON l.atypeID = A.Nid '
	
	IF @DTypeId <> '' OR @MDtypeid = '-99999'
		SET @SQL = @SQL + '	INNER JOIN #GetManDTypeId D ON L.DTypeId = D.TypeId '
							
	IF @STypeId <> '' OR @MStypeid = '-99999'
		SET @SQL = @SQL + '	INNER JOIN #GetManSTypeId S ON L.STypeId = S.TypeId '						

	SET @SQL = @SQL + '
				WHERE	L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND L.Audited = 1
						AND (a.typeName=''G'' OR a.typeName=''E'') '
	
	EXEC(@SQL)
	
	--更新数据
	SET @SQL = 'UPDATE	#Result
			SET		Zgsr	= ISNULL(L.Zgsr,0),
					Xssr	= ISNULL(L.Xssr,0),
					Thsr	= ISNULL(L.Thsr,0),
					Srhj	= ISNULL(L.Xssr,0) + ISNULL(L.Thsr,0)+isnull(l.lsthsr,0)+isnull(l.zgsr,0),
					Bqsr	= ISNULL(L.Bqsr,0),
					zgcb	= ISNULL(L.zgcb,0),
					Xscb	= ISNULL(L.Xscb,0),
					Thcb	= ISNULL(L.Thcb,0),
					Bqzc	= ISNULL(L.Bqzc,0),
					Srcb	= ISNULL(L.Xscb,0) + ISNULL(L.Thcb,0)+ISNULL(L.lsthcb,0)+isnull(l.zgcb,0),
					Xsml 	= ISNULL(L.Xssr,0) +ISNULL(L.Zgsr,0)+ ISNULL(L.Thsr,0)+isnull(l.lsthsr,0) - ISNULL(L.Xscb,0) - ISNULL(L.Thcb,0)-isnull(l.lsthcb,0)-ISNULL(L.zgcb,0),
					lsthsr  =isnull(L.lsthsr,0),
					lsthcb  =isnull(l.lsthcb,0)
			FROM	#Result R
			LEFT JOIN (
					SELECT	BillDate,
							ISNULL(SUM(CASE WHEN ATypeId = '+@SR+' AND (BillType IN (405)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Zgsr,
							ISNULL(SUM(CASE WHEN ATypeId = '+@SR+' AND (BillType IN (305,11,141,196,195,200,12) OR (BillType = 160 AND ISNULL(Total,0)>0)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Xssr,
							ISNULL(SUM(CASE WHEN ATypeId = '+@SR+' AND (BillType IN (45,191,197,46) OR (BillType = 160 AND ISNULL(Total,0)<0)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Thsr,
							ISNULL(SUM(CASE WHEN ATypeId = '+@CB+' AND (BillType IN (405)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Zgcb,
							ISNULL(SUM(CASE WHEN ATypeId = '+@CB+' AND (BillType IN (305,11,141,196,195,200,12) OR (BillType = 160 AND ISNULL(Total,0)>0)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Xscb,
							ISNULL(SUM(CASE WHEN ATypeId = '+@CB+' AND (BillType IN (45,191,197,46) OR (BillType = 160 AND ISNULL(Total,0)<0)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Thcb,
							ISNULL(SUM(CASE WHEN typeName =''G'' THEN ISNULL(Total,0) ELSE 0 END),0) AS Bqsr,
							ISNULL(SUM(CASE WHEN typeName =''E'' THEN ISNULL(Total,0) ELSE 0 END),0) AS Bqzc,
							ISNULL(SUM(CASE WHEN ATypeId = '+@SR+' AND (BillType=215) THEN ISNULL(Total,0) ELSE 0 END),0) AS lsThsr,
		                    ISNULL(SUM(CASE WHEN ATypeId = '+@CB+' AND (BillType =215) THEN ISNULL(Total,0) ELSE 0 END),0) AS lsThcb					
					FROM	#ListTable
					GROUP BY BillDate
			)L ON R.RDay = L.BillDate '
--PRINT @SQL
	EXEC(@SQL)
END
ELSE
BEGIN
	SET @SQL = @SQL + '
			SELECT	YEAR(l.BillDate)*100+MONTH(l.BillDate) AS BillDate, 
					ISNULL(SUM(CASE WHEN ATypeId = '+@SR+' AND (BillType IN (405)) THEN ISNULL(Total,0) ELSE 0 END),0) AS zgsr,
					ISNULL(SUM(CASE WHEN ATypeId = '+@SR+' AND (BillType IN (305,11,141,196,195,200,12) OR (BillType = 160 AND ISNULL(Total,0)>0)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Xssr,
					ISNULL(SUM(CASE WHEN ATypeId = '+@SR+' AND (BillType IN (45,191,197,46) OR (BillType = 160 AND ISNULL(Total,0)<0)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Thsr,
					ISNULL(SUM(CASE WHEN ATypeId = '+@CB+' AND (BillType IN (405)) THEN ISNULL(Total,0) ELSE 0 END),0) AS zgcb,
					ISNULL(SUM(CASE WHEN ATypeId = '+@CB+' AND (BillType IN (305,11,141,196,195,200,12) OR (BillType = 160 AND ISNULL(Total,0)>0)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Xscb,
					ISNULL(SUM(CASE WHEN ATypeId = '+@CB+' AND (BillType IN (45,191,197,46) OR (BillType = 160 AND ISNULL(Total,0)<0)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Thcb,
					ISNULL(SUM(CASE WHEN typeName =''G'' THEN ISNULL(Total,0) ELSE 0 END),0) AS Bqsr,
					ISNULL(SUM(CASE WHEN typeName =''E'' THEN ISNULL(Total,0) ELSE 0 END),0) AS Bqzc,
					ISNULL(SUM(CASE WHEN ATypeId = '+@SR+' AND (BillType=215) THEN ISNULL(Total,0) ELSE 0 END),0) AS lsThsr,
		            ISNULL(SUM(CASE WHEN ATypeId = '+@CB+' AND (BillType =215) THEN ISNULL(Total,0) ELSE 0 END),0) AS lsThcb					
			FROM	ListTable L 
			INNER JOIN AC_items  a ON l.atypeID = A.Nid '
	IF @DTypeId <> '' OR @MDtypeid = '-99999'
		SET @SQL = @SQL + '	INNER JOIN #GetManDTypeId D ON L.DTypeId = D.TypeId '
							
	IF @STypeId <> '' OR @MStypeid = '-99999'
		SET @SQL = @SQL + '	INNER JOIN #GetManSTypeId S ON L.STypeId = S.TypeId '						

	SET @SQL = @SQL + '
				WHERE	L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND (a.typeName=''G'' OR a.typeName=''E'') 
						AND L.Audited = 1
						'
			
	SET @SQL = @SQL + '  GROUP BY YEAR(l.BillDate)*100+MONTH(l.BillDate)'
	
	SET @SQL = 'UPDATE	#Result
			SET		zgsr	= ISNULL(L.zgsr,0),
					Xssr	= ISNULL(L.Xssr,0),
					Thsr	= ISNULL(L.Thsr,0),
					Srhj	= ISNULL(L.Xssr,0) + ISNULL(L.Thsr,0)+isnull(l.lsthsr,0)+isnull(l.zgsr,0),
					Bqsr	= ISNULL(L.Bqsr,0),
					zgcb	= ISNULL(L.zgcb,0),
					Xscb	= ISNULL(L.Xscb,0),
					Thcb	= ISNULL(L.Thcb,0),
					Bqzc	= ISNULL(L.Bqzc,0),
					Srcb	= ISNULL(L.Xscb,0) + ISNULL(L.Thcb,0)+ISNULL(l.lsthcb,0)+isnull(l.zgcb,0),
					Xsml 	= ISNULL(L.Xssr,0)+isnull(l.zgsr,0) + ISNULL(L.Thsr,0)+isnull(l.lsthsr,0) - ISNULL(L.Xscb,0) - ISNULL(L.Thcb,0)-isnull(l.lsthcb,0)-isnull(l.zgcb,0),
					lsthsr  =isnull(l.lsthsr,0),
					lsthcb  =isnull(l.lsthcb,0) 
			FROM	#Result R
			LEFT JOIN (
					'+@SQL+' 
					
			)L ON R.RDay = L.BillDate '
			
			--print @sql
	EXEC(@SQL)

END
--PRINT(@SQL)
--EXEC(@SQL)

IF EXISTS(SELECT  1 FROM sysdata WHERE SubName='IsInvoice' AND SubValue='1')
	SELECT 	RDay,
			NDay,
			SUM(zgsr) as zgsr,
			SUM(Xssr) AS Xssr,
			SUM(Thsr) AS Thsr,
			SUM(Srhj) AS Srhj,
			SUM(Bqsr) AS Bqsr,
			SUM(zgcb) as zgcb,
			SUM(Xscb) AS Xscb,
			SUM(Thcb) AS Thcb,
			SUM(Bqzc) AS Bqzc,
			SUM(Srcb) AS Srcb,
			SUM(Xsml) AS Xsml,
			SUM(lsthsr)AS lsthsr,
			SUM (lsthcb)AS lsthcb ,
			ISNULL(SUM(Bqsr),0) - ISNULL(SUM(Bqzc),0) AS Bqlr
	FROM 	#Result
	GROUP BY RDay,NDay
ELSE
	SELECT 	RDay,
			NDay,
			SUM(Xssr) AS Xssr,
			SUM(Thsr) AS Thsr,
			SUM(Srhj) AS Srhj,
			SUM(Bqsr) AS Bqsr,
			SUM(Xscb) AS Xscb,
			SUM(Thcb) AS Thcb,
			SUM(Bqzc) AS Bqzc,
			SUM(Srcb) AS Srcb,
			SUM(Xsml) AS Xsml,
			SUM(lsthsr)AS lsthsr,
			SUM (lsthcb)AS lsthcb ,
			ISNULL(SUM(Bqsr),0) - ISNULL(SUM(Bqzc),0) AS Bqlr
	FROM 	#Result
	GROUP BY RDay,NDay


DROP TABLE #RQ,#Result,#ListTable,#GetManDTypeId,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QuerySaleInfoFxChart]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QuerySaleInfoFxChart]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-30
	描述：销售经营情况日统计（销售经营情况月统计）-图形分析
	EXEC Qp_QuerySaleInfoFxChart '00001','2010-08-30','2010-09-30','','m'
	作者：徐辉
	日期：2011-04-27
	描述：权限调整
*/

CREATE PROCEDURE Qp_QuerySaleInfoFxChart
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@DTypeId		VARCHAR(8000),
	@STypeId		VARCHAR(8000),
	@nType			VARCHAR(10)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

IF @nType = 'm'
	BEGIN
		IF ISDATE(@EndDate)=1
			SET @EndDate = @EndDate
		ELSE IF ISDATE(REPLACE(@EndDate,'-31','-30'))=1
			SET @EndDate = REPLACE(@EndDate,'-31','-30')
		ELSE IF ISDATE(REPLACE(@EndDate,'-31','-29'))=1
			SET @EndDate = REPLACE(@EndDate,'-31','-29')
		ELSE IF ISDATE(REPLACE(@EndDate,'-31','-28'))=1
			SET @EndDate = REPLACE(@EndDate,'-31','-28')
	END

CREATE TABLE #RQ
(
	nId		INT identity(1,1),
	nName	VARCHAR(100)
)

CREATE TABLE #Result
(
	RDay		VARCHAR(10),
	NDay		VARCHAR(20),
	FullName	VARCHAR(200),
	Data		 NUMERIC(24, 10) 	
)

CREATE TABLE #ListTable
(
	BillDate	VARCHAR(20),
	Xssr		 NUMERIC(24, 10) ,
	Thsr		 NUMERIC(24, 10) ,
	lsthsr       NUMERIC(24, 10) , 
	Srhj		 NUMERIC(24, 10) ,
	Xscb		 NUMERIC(24, 10) ,
	Thcb		 NUMERIC(24, 10) ,
	lsthcb       NUMERIC(24, 10) ,
	Srcb		 NUMERIC(24, 10) ,
	Xsml		 NUMERIC(24, 10) ,
	Bqsr		 NUMERIC(24, 10) ,
	Bqzc		 NUMERIC(24, 10) ,
	zgsr		 NUMERIC(24, 10)  DEFAULT(0),
	zgcb		 NUMERIC(24, 10)  DEFAULT(0)
	
)
DECLARE @SQL  VARCHAR(8000),
		@field1 VARCHAR(50),
		@field2 VARCHAR(50)
		--,
		--@Field3  NUMERIC(24, 10) ,
		--@Field4  NUMERIC(24, 10) 

		
SELECT @field1=nid FROM dbo.Ac_Items WHERE UserCode='5101'
SELECT @field2=nid FROM dbo.Ac_Items WHERE UserCode='5401'
	
	
SET @SQL = 'INSERT INTO #ListTable '
IF @nType = 'd'
	SET @SQL = @SQL + '
			SELECT	dbo.F_FormatDate(L.BillDate,''-'',''-'') AS BillDate,'
ELSE
	SET @SQL = @SQL + '
			SELECT	LEFT(dbo.F_FormatDate(L.BillDate,''-'',''-''),7) AS BillDate,'

SET @SQL = @SQL + '	ISNULL(SUM(CASE WHEN L.ATypeId = '+@field1+' AND (L.BillType IN (305,11,141) OR (L.BillType = 160 AND ISNULL(L.Total,0)>0)) THEN ISNULL(L.Total,0) ELSE 0 END),0) AS Xssr,
					ISNULL(SUM(CASE WHEN L.ATypeId = '+@field1+' AND (L.BillType IN (45) OR (L.BillType = 160 AND ISNULL(L.Total,0)<0)) THEN ISNULL(L.Total,0) ELSE 0 END),0) AS Thsr,
	
	                ISNULL(SUM(CASE WHEN L.ATypeId = '+@field1+' AND (L.BillType IN (215)) THEN ISNULL(L.Total,0) ELSE 0 END),0) AS lsThsr,				
					0 AS Srhj,
					ISNULL(SUM(CASE WHEN L.ATypeId = '+@field2+' AND (L.BillType IN (305,11,141) OR (L.BillType = 160 AND ISNULL(L.Total,0)>0)) THEN ISNULL(L.Total,0) ELSE 0 END),0) AS Xscb,
					ISNULL(SUM(CASE WHEN L.ATypeId = '+@field2+' AND (L.BillType IN (45) OR (L.BillType = 160 AND ISNULL(L.Total,0)<0)) THEN ISNULL(L.Total,0) ELSE 0 END),0) AS Thcb,
	ISNULL(SUM(CASE WHEN L.ATypeId = '+@field2+' AND (L.BillType IN (215) ) THEN ISNULL(L.Total,0) ELSE 0 END),0) AS lsThcb,				
					0 AS Srcb,
					0 AS Xsml,
					ISNULL(SUM(CASE WHEN Ac_Items.TypeName=''G'' THEN Total ELSE 0 END),0) AS Bqsr,
					ISNULL(SUM(CASE WHEN Ac_Items.TypeName=''E'' THEN Total ELSE 0 END),0) AS Bqzc,
				    ISNULL(SUM(CASE WHEN L.ATypeId = '+@field1+' AND (L.BillType IN(405)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Zgsr,
				     ISNULL(SUM(CASE WHEN L.ATypeId = '+@field2+' AND (L.BillType IN(405)) THEN ISNULL(Total,0) ELSE 0 END),0) AS Zgcb
			FROM	ListTable L 
					INNER JOIN Ac_Items ON L.AtypeId=Ac_Items.nId
			'

IF @DTypeId <> '' OR @MDtypeid = '-99999'
	SET @SQL = @SQL + '	INNER JOIN #GetManDTypeId D ON ISNULL(L.DTypeId,'''') = D.TypeId '

IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + '	INNER JOIN #GetManSTypeId S ON ISNULL(L.STypeId,'''') = S.TypeId '

SET @SQL = @SQL + '
			WHERE	L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
					AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
					AND L.Audited = 1
					AND (L.ATypeId IN (SELECT nid FROM Ac_Items WHERE (TYPENAME=  ''G'' OR TYPENAME = ''E'')))
			GROUP BY L.BillDate'
	PRINT(@SQL)
EXEC(@SQL)
		
--修改合计值
UPDATE	#ListTable
SET		Srhj	= ISNULL(Xssr,0) + ISNULL(Thsr,0)+ISNULL(lsthsr,0)+ISNULL(zgsr,0),
		Srcb	= ISNULL(Xscb,0) + ISNULL(Thcb,0)+ISNULL(lsthcb,0)+ISNULL(zgcb,0),
		Xsml 	= ISNULL(Xssr,0) + ISNULL(Thsr,0)+ISNULL(lsthsr,0)+ISNULL(zgsr,0) - ISNULL(Xscb,0) - ISNULL(Thcb,0)-ISNULL(lsthcb,0)-ISNULL(zgcb,0)

DECLARE @Date		VARCHAR(10),
		@Yd			VARCHAR(10),
		@Md			VARCHAR(10),
		@Dd			VARCHAR(10),
		@i			NUMERIC(18,0)

SET @i = 0

IF @nType = 'd'	--日分析
	BEGIN
		WHILE @i<=DATEDIFF (DAY,@StartDate,@EndDate)
			BEGIN
				IF @i = 0
					SET @Date = CONVERT(VARCHAR(10),DATEADD(Day,0,@StartDate),120)		
				ELSE
					SET @Date = CONVERT(VARCHAR(10),DATEADD(Day,1,@Date),120)		
		
				IF @Date <= @EndDate
					BEGIN
						TRUNCATE TABLE #RQ
						INSERT INTO #RQ(nName) SELECT A FROM dbo.f_split(@Date,'-')
						SELECT @Yd = nName FROM #RQ WHERE nId = 1
						SELECT @Md = nName FROM #RQ WHERE nId = 2
						SELECT @Dd = nName FROM #RQ WHERE nId = 3

						IF EXISTS(SELECT TOP 1 1 FROM #ListTable WHERE BillDate = @Date)
							BEGIN
								INSERT INTO #Result(RDay,NDay,FullName,Data)
								SELECT	@Date,
										@Yd+'年'+@Md+'月'+@Dd+'日',
										'销售收入合计' AS FullName,
										ISNULL(SUM(Srhj),0)
								FROM 	#ListTable
								WHERE	BillDate = @Date

								INSERT INTO #Result(RDay,NDay,FullName,Data)
								SELECT	@Date,
										@Yd+'年'+@Md+'月'+@Dd+'日',
										'销售成本合计' AS FullName,
										ISNULL(SUM(Srcb),0)
								FROM 	#ListTable
								WHERE	BillDate = @Date

								INSERT INTO #Result(RDay,NDay,FullName,Data)
								SELECT	@Date,
										@Yd+'年'+@Md+'月'+@Dd+'日',
										'销售毛利' AS FullName,
										ISNULL(SUM(Xsml),0)
								FROM 	#ListTable
								WHERE	BillDate = @Date
							END
						ELSE
							BEGIN
								INSERT INTO #Result(RDay,NDay,FullName,Data)VALUES(@Date,@Yd+'年'+@Md+'月'+@Dd+'日','销售收入合计',0)
								INSERT INTO #Result(RDay,NDay,FullName,Data)VALUES(@Date,@Yd+'年'+@Md+'月'+@Dd+'日','销售成本合计',0)
								INSERT INTO #Result(RDay,NDay,FullName,Data)VALUES(@Date,@Yd+'年'+@Md+'月'+@Dd+'日','销售毛利',0)
							END
					END
		
				SET @i = @i + 1
			END
	END
ELSE
	BEGIN
		WHILE @i<=DATEDIFF (MONTH,@StartDate,@EndDate)
			BEGIN
				IF @i = 0
					SET @Date = CONVERT(VARCHAR(10),DATEADD(MONTH,0,@StartDate),120)		
				ELSE
					SET @Date = CONVERT(VARCHAR(10),DATEADD(MONTH,1,@Date),120)		
		
				IF @Date <= @EndDate
					BEGIN
						TRUNCATE TABLE #RQ
						INSERT INTO #RQ(nName) SELECT A FROM dbo.f_split(@Date,'-')
						SELECT @Yd = nName FROM #RQ WHERE nId = 1
						SELECT @Md = nName FROM #RQ WHERE nId = 2

						IF EXISTS(SELECT TOP 1 1 FROM #ListTable WHERE LEFT(CONVERT(VARCHAR(10),BillDate,120),LEN(@Yd+'-'+@Md)) = @Yd+'-'+@Md)
							BEGIN								
								INSERT INTO #Result(RDay,NDay,FullName,Data)
								SELECT	@Yd+'-'+@Md,
										@Yd+'年'+@Md+'月',
										'销售收入合计' AS FullName,
										ISNULL(SUM(Srhj),0)
								FROM 	#ListTable
								WHERE	LEFT(CONVERT(VARCHAR(10),BillDate,120),LEN(@Yd+'-'+@Md)) = @Yd+'-'+@Md
						
								INSERT INTO #Result(RDay,NDay,FullName,Data)
								SELECT	@Yd+'-'+@Md,
										@Yd+'年'+@Md+'月',
										'销售成本合计' AS FullName,
										ISNULL(SUM(Srcb),0)
								FROM 	#ListTable
								WHERE	LEFT(CONVERT(VARCHAR(10),BillDate,120),LEN(@Yd+'-'+@Md)) = @Yd+'-'+@Md

								INSERT INTO #Result(RDay,NDay,FullName,Data)
								SELECT	@Yd+'-'+@Md,
										@Yd+'年'+@Md+'月',
										'销售毛利' AS FullName,
										ISNULL(SUM(Xsml),0)
								FROM 	#ListTable
								WHERE	LEFT(CONVERT(VARCHAR(10),BillDate,120),LEN(@Yd+'-'+@Md)) = @Yd+'-'+@Md
							END
						ELSE
							BEGIN
								INSERT INTO #Result(RDay,NDay,FullName,Data)VALUES(@Yd+'-'+@Md,@Yd+'年'+@Md+'月','销售收入合计',0)
								INSERT INTO #Result(RDay,NDay,FullName,Data)VALUES(@Yd+'-'+@Md,@Yd+'年'+@Md+'月','销售成本合计',0)
								INSERT INTO #Result(RDay,NDay,FullName,Data)VALUES(@Yd+'-'+@Md,@Yd+'年'+@Md+'月','销售毛利',0)
							END
					END
		
				SET @i = @i + 1
			END
	END

SELECT 	RDay,
		NDay,
		FullName,
		SUM(Data) AS Data
FROM 	#Result
GROUP BY RDay,NDay,FullName

DROP TABLE #RQ,#Result,#ListTable,#GetManDTypeId,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryStatReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryStatReport]
GO

/****** Object:  StoredProcedure [dbo].[QP_QueryStatReport]    Script Date: 08/24/2011 15:15:33 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
/*
	作者：谢吉康
	日期：2010-07-21
	描述：经营日（月，年）报表
	QP_QueryStatReport '00001','','','','','','','',''
	
	作者：徐辉
	日期：2011-03-21
	描述：权限范围调整
	出入库金额：受分支机构、仓库权限范围控制。
	收支金额：受分支机构、部门权限范围控制。
	
	【修改】：鲁大林
	日期：2012-06-26
	描述：会计科目调整（表更换后数据查询方式调整）
*/
CREATE PROCEDURE [dbo].[QP_QueryStatReport]
(
	@OperatorId			VARCHAR(100),	--操作员ID
	@SingleDate			VARCHAR(20),	--日报日期
	@MstartDate			VARCHAR(20),	--月报开始日期
	@MendDate			VARCHAR(20),	--月报截止日期
	@StartDate			VARCHAR(20),	--年报开始日期
	@EndDate			VARCHAR(20),	--年报截止日期
	@DTypeID			VARCHAR(8000),	--部门ID
	@STypeID			VARCHAR(8000),	--分支机构ID
	@KTypeID			VARCHAR(8000),	--仓库ID
	@nType				VARCHAR(10)		--标识 d.日报 m.月报 y.年报
)
--@encode$--
AS
SET NOCOUNT ON

--权限范围临时表
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--版本判断
DECLARE @proinfo varchar(5)
SELECT @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'

CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))

INSERT INTO #GetManSTypeId(TypeId) 
	SELECT TypeId 
	FROM F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID)
	
--限制分支机构内仓库
INSERT INTO #GetManKTypeId(TypeId) 
	SELECT a.TypeId
	FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) a
	INNER JOIN Stock s ON a.TypeId = s.typeId
	INNER JOIN #GetManSTypeId s1 ON s1.TypeId = s.STypeID
	
IF  @MKTypeId = '-99999'
	INSERT INTO #GetManKTypeId(TypeId)VALUES('00000')
	
	
CREATE CLUSTERED INDEX  CIX_STypeID ON #GetManSTypeId(TypeID)
CREATE CLUSTERED INDEX  CIX_KTypeID ON #GetManKTypeId(TypeID)

	
IF @DTypeID is null
	SET @DTypeID='' 
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeID,9,@OperatorID)




DECLARE @SQL 				VARCHAR(8000),
		@SendTotal			 NUMERIC(24, 10) ,
		@SendBackTotal		 NUMERIC(24, 10) ,
		@AppraisalTotal		 NUMERIC(24, 10) ,
		@AppraisalBackTotal	 NUMERIC(24, 10) ,
		@BuyTotal		 NUMERIC(24, 10) ,
		@SaleTotal		 NUMERIC(24, 10) ,
		@BuyBackTotal	 NUMERIC(24, 10) ,
		@SaleBackTotal	 NUMERIC(24, 10) ,
		@Retailback      NUMERIC(24, 10) ,
		@StshTotal		 NUMERIC(24, 10) ,
		@WtfhTotal		 NUMERIC(24, 10) ,
		@StthTotal		 NUMERIC(24, 10) ,
		@WtthTotal		 NUMERIC(24, 10) ,
		@TjdbRkTotal	 NUMERIC(24, 10) ,
		@TjdbCkTotal	 NUMERIC(24, 10) ,
		@BjdbRkTotal	 NUMERIC(24, 10) ,
		@BjdbCkTotal	 NUMERIC(24, 10) ,
		@ByRkTotal		 NUMERIC(24, 10) ,
		@BsCkTotal		 NUMERIC(24, 10) ,
		@CzRkTotal		 NUMERIC(24, 10) ,
		@CzCkTotal		 NUMERIC(24, 10) ,
		@HzRkTotal		 NUMERIC(24, 10) ,
		@ZsCkTotal		 NUMERIC(24, 10) ,
		@TjTotal		 NUMERIC(24, 10) ,
		@BqRkTotal		 NUMERIC(24, 10) ,
		@BqCkTotal		 NUMERIC(24, 10) ,
		@IniTotal		 NUMERIC(24, 10) ,
		@PreTotal		 NUMERIC(24, 10) ,
		@KxCkTotal		 NUMERIC(24, 10) ,
		@StypeDbCkTotal	 NUMERIC(24, 10) ,
		@StypeDbRkTotal	 NUMERIC(24, 10) ,
		@RepairDbRkTotal  NUMERIC(24, 10) ,
		@RepairDbCkTotal  NUMERIC(24, 10) ,
		@QtRkTotal        NUMERIC(24, 10) ,  --其他入库
		@QtCkTotal        NUMERIC(24, 10)    --其他出库

IF (@KTypeId = '' AND @MKTypeId = '00000')
	BEGIN
		--期初库存
		SELECT	@IniTotal = SUM(Total)
		FROM	IniGoodsStocks
		INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = IniGoodsStocks.KTypeId
		WHERE	KtypeId IN (SELECT TypeId FROM Stock WHERE STypeID IN (SELECT typeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)))
	
		--此前金额
		SELECT	@PreTotal= SUM(CostTotal)
		FROM	InOutStockTable
				INNER JOIN #GetManKTypeId K ON K.TypeId = InOutStockTable.KTypeId
			    INNER JOIN #GetManSTypeId S ON S.TypeId = InOutStockTable.STypeID
		WHERE	BillDate<= CASE
				WHEN @nType = 'd' THEN @SingleDate
				WHEN @nType = 'm' THEN @MendDate
				WHEN @nType = 'y' THEN @EndDate
				ELSE '1900-01-01'
			    END
				AND KTypeId <> '10000'
				AND KtypeId IN (SELECT TypeId FROM Stock WHERE STypeID IN (SELECT typeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)))	
	END
ELSE
	BEGIN
		--期初库存
		SELECT	@IniTotal = SUM(Total)
		FROM	IniGoodsStocks
				INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = IniGoodsStocks.KTypeId
		WHERE	KtypeId IN (SELECT TypeId FROM Stock WHERE STypeID IN (SELECT typeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)))
		
		--此前金额
		SELECT	@PreTotal= SUM(CostTotal)
		FROM	InOutStockTable
				INNER JOIN #GetManKTypeId K ON K.TypeId = InOutStockTable.KTypeId
			    --INNER JOIN #GetManDTypeId D ON D.TypeId = InOutStockTable.DTypeID
			    INNER JOIN #GetManSTypeId S ON S.TypeId = InOutStockTable.STypeID
		WHERE	BillDate<= CASE
				WHEN @nType = 'd' THEN @SingleDate
				WHEN @nType = 'm' THEN @MendDate
				WHEN @nType = 'y' THEN @EndDate
				ELSE '1900-01-01'
				END
				AND KTypeId <> '10000'
				AND KtypeId IN (SELECT TypeId FROM Stock WHERE STypeID IN (SELECT typeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)))
	END
----计算时间段内的数据
CREATE TABLE #InOutStockTable
(
	BillNumberId		NUMERIC(18,0) DEFAULT(0),
	BillType			INT,
	Qty					 NUMERIC(24, 10) ,
	CostTotal			 NUMERIC(24, 10) 
)


--RETURN
SET @SQL ='	INSERT INTO #InOutStockTable(BillType,Qty,CostTotal)
			SELECT	BillType,
					Qty,
					CostTotal
			FROM	InOutStockTable '

IF  @KTypeId <> '' or @MKTypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = InOutStockTable.KTypeId '

IF  @STypeID <> '' or @MStypeid = '-99999'
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId s ON s.TypeId = InOutStockTable.STypeId '

SET @SQL = @SQL + '		
			WHERE   BillDate>= CASE
					WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''d'' THEN '+CHAR(39)+@SingleDate+CHAR(39)+'
					WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''m'' THEN '+CHAR(39)+@MstartDate+CHAR(39)+'
					WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''y'' THEN '+CHAR(39)+@StartDate+CHAR(39)+'
					ELSE ''1900-01-01''
					 END
					AND BillDate<= CASE
					WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''d'' THEN '+CHAR(39)+@SingleDate+CHAR(39)+'
					WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''m'' THEN '+CHAR(39)+@MendDate+CHAR(39)+'
					WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''y'' THEN '+CHAR(39)+@EndDate+CHAR(39)+'
					ELSE ''2500-01-01''
				    END						
					AND Audited = 1			
					AND KTypeId <> ''10000''
				--	AND KtypeId IN (SELECT TypeId FROM Stock WHERE STypeID IN (SELECT typeId FROM F_GetAllManagerBaseTypeId('''+@STypeId+''',11,'''+@OperatorId+'''))) '
--PRINT(@SQL)
EXEC(@SQL)
 

SELECT	@SendTotal 		= SUM(CASE WHEN BillType=402 THEN  -1*CostTotal ELSE 0 END),
		@SendBackTotal	= SUM(CASE WHEN BillType =403 THEN -1*CostTotal ELSE 0 END),
		@AppraisalTotal	= SUM(CASE WHEN BillType = 400  THEN CostTotal ELSE 0 END),
		@AppraisalBackTotal	= SUM(CASE WHEN BillType = 401 THEN CostTotal ELSE 0 END),
		@BuyTotal 		= SUM(CASE WHEN (BillType = 34 OR (BillType=161 AND Qty>=0) OR BillType=205) THEN CostTotal ELSE 0 END),
		@SaleTotal		= SUM(CASE WHEN (BillType IN(305,11,12) OR (BillType = 160 AND Qty<=0)) THEN -1*CostTotal ELSE 0 END),
		@BuyBackTotal	= SUM(CASE WHEN (BillType = 6 OR (BillType=161 AND Qty<=0)) THEN CostTotal ELSE 0 END),
		@SaleBackTotal	= -1*SUM(CASE WHEN (BillType IN( 45,46) OR (BillType = 160 AND Qty>=0)) THEN CostTotal ELSE 0 END),
		@Retailback     =-1*SUM(CASE WHEN billtype=215 THEN CostTotal ELSE 0  END ),  
		@StshTotal		= SUM(CASE WHEN BillType = 144 THEN CostTotal ELSE 0 END),
		@WtfhTotal		= SUM(CASE WHEN BillType = 140 THEN -1*CostTotal ELSE 0 END),
		@StthTotal		= SUM(CASE WHEN BillType = 146 THEN CostTotal ELSE 0 END),
		@WtthTotal		= -1*SUM(CASE WHEN BillType = 142 THEN CostTotal ELSE 0 END),
		@TjdbRkTotal	= SUM(CASE WHEN BillType = 17 AND Qty>=0 THEN CostTotal ELSE 0 END),
		@TjdbCkTotal	= SUM(CASE WHEN BillType = 17 AND Qty<=0 THEN -1*CostTotal ELSE 0 END),
		@BjdbRkTotal	= SUM(CASE WHEN BillType = 21 AND Qty>=0 THEN CostTotal ELSE 0 END),
		@BjdbCkTotal	= SUM(CASE WHEN BillType = 21 AND Qty<=0 THEN -1*CostTotal ELSE 0 END),
		@ByRkTotal		= SUM(CASE WHEN BillType = 14 THEN CostTotal ELSE 0 END),
		@BsCkTotal		= SUM(CASE WHEN BillType = 9 THEN -1*CostTotal ELSE 0 END),
		@CzRkTotal		= SUM(CASE WHEN BillType = 16 AND Qty>=0 THEN CostTotal ELSE 0 END),
		@CzCkTotal		= SUM(CASE WHEN BillType = 16 AND Qty<=0 THEN -1*CostTotal ELSE 0 END),
		@HzRkTotal		= SUM(CASE WHEN BillType = 126 THEN CostTotal ELSE 0 END),
		@ZsCkTotal		= SUM(CASE WHEN (BillType = 139 OR BillType = 183) THEN -1*CostTotal ELSE 0 END),
		@TjTotal		= SUM(CASE WHEN BillType = 57 THEN CostTotal ELSE 0 END),
		@KxCkTotal		= SUM(CASE 
										WHEN @proinfo='3' AND BillType = 178 or BillType = 191 or BillType = 197 or BillType = 196 THEN -1*CostTotal --汽配
										WHEN @proinfo<>'3' AND (BillType = 166 OR BillType = 168 OR BillType = 172) THEN  -1*CostTotal 
										ELSE  0
							 END),
		@BqRkTotal		= SUM(CASE 
										WHEN BillType in( 45,403,46) OR (BillType = 160 AND Qty>=0) THEN 0
										WHEN BillType = 215 THEN 0
										WHEN BillType in( 6,401) OR (BillType=161 AND Qty<=0) THEN CostTotal
										WHEN BillType = 146 THEN CostTotal
										WHEN BillType = 142 THEN 0
										WHEN BillType = 57 THEN CostTotal
										WHEN BillType=197 THEN 0
										WHEN Qty>=0 THEN CostTotal 
										ELSE 0 
							  END),
		@BqCkTotal		= SUM(CASE 
										WHEN BillType in( 45,403,46) OR (BillType = 160 AND Qty>=0) THEN -1*CostTotal
										WHEN BillType = 215 THEN -1*CostTotal
										WHEN BillType in( 6,401) OR (BillType=161 AND Qty<=0) THEN 0
										WHEN BillType = 146 THEN 0
										WHEN BillType=205 THEN 0    --出库不统计费用分摊
										WHEN BillType = 142 THEN -1*CostTotal
										WHEN BillType = 57 THEN 0
										WHEN BillType=197 THEN 0
										WHEN Qty<=0 THEN -1*CostTotal 
										ELSE 0 
							  END),
		@StypeDbRkTotal		= SUM(CASE WHEN BillType = 188  THEN CostTotal ELSE 0 END),
		@StypeDbCkTotal		= SUM(CASE WHEN BillType = 187  THEN -1*CostTotal ELSE 0 END),
		@RepairDbRkTotal		= SUM(CASE WHEN BillType = 174  THEN CostTotal ELSE 0 END),
		@RepairDbCkTotal		= SUM(CASE WHEN BillType = 173  THEN -1*CostTotal ELSE 0 END),
		@QtRkTotal     =SUM(CASE WHEN BillType = 201  THEN CostTotal ELSE 0 END),  --其他入库金额
		@QtCkTotal     =SUM(CASE WHEN BillType = 202  THEN -1*CostTotal ELSE 0 END) --其他出库金额
FROM	InOutStockTable  
INNER JOIN #GetManKTypeId K ON K.TypeId = InOutStockTable.KTypeId  
INNER JOIN #GetManSTypeId s ON s.TypeId = InOutStockTable.STypeId 		
			WHERE   BillDate>= CASE
					WHEN @nType = 'd' THEN @SingleDate
					WHEN @nType = 'm' THEN @MstartDate
					WHEN @nType = 'y' THEN @StartDate
					ELSE '1900-01-01'
					 END
					AND BillDate<= CASE
					WHEN @nType  = 'd' THEN @SingleDate
					WHEN @nType  = 'm' THEN @MendDate
					WHEN @nType  = 'y' THEN @EndDate
					ELSE '2500-01-01'
				    END						
					AND Audited = 1			
					AND KTypeId <> '10000'
					
					
--如果为NULL，则处理成0
IF 	@SendTotal IS NULL SET @SendTotal = 0
IF 	@SendBackTotal IS NULL SET @SendBackTotal = 0
IF 	@AppraisalTotal IS NULL SET @AppraisalTotal = 0
IF 	@AppraisalBackTotal IS NULL SET @AppraisalBackTotal = 0
IF 	@BuyTotal IS NULL SET @BuyTotal = 0
IF 	@SaleTotal IS NULL SET @SaleTotal = 0
IF 	@BuyBackTotal IS NULL SET @BuyBackTotal = 0
IF 	@SaleBackTotal IS NULL SET @SaleBackTotal = 0
IF @Retailback IS NULL SET @Retailback=0
IF 	@StshTotal IS NULL SET @StshTotal = 0
IF 	@WtfhTotal IS NULL SET @WtfhTotal = 0
IF 	@StthTotal IS NULL SET @StthTotal = 0
IF 	@WtthTotal IS NULL SET @WtthTotal = 0
IF 	@TjdbRkTotal IS NULL SET @TjdbRkTotal = 0
IF 	@TjdbCkTotal IS NULL SET @TjdbCkTotal = 0
IF 	@BjdbRkTotal IS NULL SET @BjdbRkTotal = 0
IF 	@BjdbCkTotal IS NULL SET @BjdbCkTotal = 0
IF 	@ByRkTotal IS NULL SET @ByRkTotal = 0
IF 	@BsCkTotal IS NULL SET @BsCkTotal = 0
IF 	@CzRkTotal IS NULL SET @CzRkTotal = 0
IF 	@CzCkTotal IS NULL SET @CzCkTotal = 0
IF 	@HzRkTotal IS NULL SET @HzRkTotal = 0
IF 	@ZsCkTotal IS NULL SET @ZsCkTotal = 0
IF 	@TjTotal IS NULL SET @TjTotal = 0
IF 	@BqRkTotal IS NULL SET @BqRkTotal = 0
IF 	@BqCkTotal IS NULL SET @BqCkTotal = 0
IF  @IniTotal IS NULL SET @IniTotal = 0
IF 	@PreTotal IS NULL SET @PreTotal = 0
IF  @KxCkTotal IS NULL SET @KxCkTotal = 0
IF  @StypeDbCkTotal IS NULL SET  @StypeDbCkTotal = 0
IF  @StypeDbRkTotal IS NULL SET @StypeDbRkTotal = 0 
IF  @RepairDbRkTotal IS NULL SET @RepairDbRkTotal = 0
IF  @RepairDbCkTotal IS NULL SET @RepairDbCkTotal = 0
IF  @QtRkTotal IS NULL SET @QtRkTotal = 0
IF  @QtCkTotal IS NULL SET @QtCkTotal = 0

DECLARE	@XsSr	 NUMERIC(24, 10) ,
		@XsCb	 NUMERIC(24, 10) ,
		@WxSr	 NUMERIC(24, 10) ,
		@WxZc	 NUMERIC(24, 10) ,
		@BySr	 NUMERIC(24, 10) ,
		@BsZc	 NUMERIC(24, 10) ,
		@HzSr	 NUMERIC(24, 10) ,
		@ZsZc	 NUMERIC(24, 10) ,
		@TzSr	 NUMERIC(24, 10) ,
		@TzZc	 NUMERIC(24, 10) ,
		@CgThCj	 NUMERIC(24, 10) ,
		@YhJe	 NUMERIC(24, 10) ,
		@BjDbCj	 NUMERIC(24, 10) ,
		@GdZcZj	 NUMERIC(24, 10) ,
		@CbTjSr	 NUMERIC(24, 10) ,
		@XsZk	 NUMERIC(24, 10) ,
		@StThCj	 NUMERIC(24, 10) ,
		@QtZc	 NUMERIC(24, 10) ,
		@FdFl	 NUMERIC(24, 10) ,
		@QtSr	 NUMERIC(24, 10) ,
		@CzCj	 NUMERIC(24, 10) ,
		@BqSr	 NUMERIC(24, 10) ,
		@BqZc	 NUMERIC(24, 10) ,
		@OtherSr  NUMERIC(24, 10) ,
		@OtherZc  NUMERIC(24, 10) ,
		------------------------------会计科目---------------------------------------------------
		@saleInCome				VARCHAR(50),--销售收入0000300001
		@saleCost			    VARCHAR(50),--销售成本0000400001
		@proFixInCome			VARCHAR(50),--商品维修收入000030000200008
		@proFixExpend			VARCHAR(50),--商品维修支出000040000200003
		@ReproFlowInCome		VARCHAR(50),--商品报溢收入000030000200001
		@ReproLoss				VARCHAR(50),--商品报损000040000200001
		@ReciveInCome			VARCHAR(50),--商品获赠收入000030000200002
		@Present				VARCHAR(50),--商品赠出000040000200002
		@BindTraInCome         	VARCHAR(50),--调帐收入000030000300001
		@BindTraLoss			VARCHAR(50),--调帐亏损000040000300001
		@BuyBack				VARCHAR(50),--采购退货差价000030000200004
		@PrefMoney				VARCHAR(50),--抹零金额000040000300004
		@VariPrice				VARCHAR(50),--变价调拨差价000030000200005
		@Fasset					VARCHAR(50),--固定资产折扣000040000300002
		@CostVariPrice			VARCHAR(50),--成本调价收入000030000200003
		@SaleFasset			    VARCHAR(50),--销售折扣返利支出0000400004
		@FidureVariPrice        VARCHAR(50),--受托退货差价000030000200009
		@ReturnPInCome	        VARCHAR(50)--返点获利收入0000300004
		
	select	@saleInCome = nid FROM dbo.Ac_Items WHERE UserCode='5101'
	select	@saleCost	= nid FROM dbo.Ac_Items WHERE UserCode='5401'
	select	@proFixInCome= nid FROM dbo.Ac_Items WHERE UserCode='0328'
	select	@proFixExpend= nid FROM dbo.Ac_Items WHERE UserCode='0423'
	select	@ReproFlowInCome= nid FROM dbo.Ac_Items WHERE UserCode='0321'
	select	@ReproLoss	= nid FROM dbo.Ac_Items WHERE UserCode='0421'
	select	@ReciveInCome= nid FROM dbo.Ac_Items WHERE UserCode='0322'
	select	@Present	= nid FROM dbo.Ac_Items WHERE UserCode='0422'
	select	@BindTraInCome= nid FROM dbo.Ac_Items WHERE UserCode='03333'
	select	@BindTraLoss= nid FROM dbo.Ac_Items WHERE UserCode='0431'
	select	@BuyBack	= nid FROM dbo.Ac_Items WHERE UserCode='0324'
	select	@PrefMoney	= nid FROM dbo.Ac_Items WHERE UserCode='0456'
	select	@VariPrice	= nid FROM dbo.Ac_Items WHERE UserCode='0325'
	select	@Fasset		= nid FROM dbo.Ac_Items WHERE UserCode='0432'
	select	@CostVariPrice= nid FROM dbo.Ac_Items WHERE UserCode='0323'
	select	@SaleFasset	= nid FROM dbo.Ac_Items WHERE UserCode='0404'
	select	@FidureVariPrice= nid FROM dbo.Ac_Items WHERE UserCode='0329'
	select	@ReturnPInCome= nid FROM dbo.Ac_Items WHERE UserCode='5103'
		
--CREATE TABLE #templetable(nid varchar(50))
--INSERT INTO #templetable SELECT nid FROM Ac_Items WHERE (TYPENAME=  'G' OR TYPENAME = 'E')
CREATE TABLE #ListTable
(
	--9.6 杨俊 2015-05-13 不知道谁挖的坑，完全没用这一列，先注释，后续版本谁看见了就可以删了！
	--BillNumberId		NUMERIC(18,0) DEFAULT(0),
	ATypeId				VARCHAR(100),
	Total				 NUMERIC(24, 10) ,
	typename			VARCHAR(100)
)

--9.6 杨俊 2015-05-13 不知道谁挖的坑，完全没用这一列，先注释，后续版本谁看见了就可以删了！
--IF @DTypeId <> ''
--	SET @SQL = 'INSERT INTO #ListTable
--				SELECT	ListTable.BillNumberId,
--						ListTable.ATypeId,
--						SUM(ListTable.Total) AS Total,
--						Ac_Items.TypeName
--				FROM	ListTable
--				INNER JOIN Ac_Items ON ListTable.AtypeId=Ac_Items.nId
--			    INNER JOIN #GetManDTypeId ON #GetManDTypeId.TypeId = ListTable.DTypeID
--			    INNER JOIN #GetManSTypeId ON #GetManSTypeId.TypeId = ListTable.STypeId '
--ELSE
	SET @SQL = 'INSERT INTO #ListTable(ATypeId,Total,typename)
				SELECT	ATypeId,
						SUM(Total) AS Total,
						Ac_Items.TypeName
				FROM	ListTable 
				INNER JOIN Ac_Items ON ListTable.AtypeId=Ac_Items.nId
			    INNER JOIN #GetManDTypeId ON #GetManDTypeId.TypeId = ListTable.DTypeID
			    INNER JOIN #GetManSTypeId ON #GetManSTypeId.TypeId = ListTable.STypeId  '	
SET @SQL = @SQL + '
			WHERE	(BillType<>187 or (BillType=187 and AtypeId='+@VariPrice+')) AND
			        BillDate>= CASE
									WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''d'' THEN '+CHAR(39)+@SingleDate+CHAR(39)+'
									WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''m'' THEN '+CHAR(39)+@MstartDate+CHAR(39)+'
									WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''y'' THEN '+CHAR(39)+@StartDate+CHAR(39)+'
									ELSE ''1900-01-01''
							   END
					AND BillDate<= CASE
									WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''d'' THEN '+CHAR(39)+@SingleDate+CHAR(39)+'
									WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''m'' THEN '+CHAR(39)+@MendDate+CHAR(39)+'
									WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''y'' THEN '+CHAR(39)+@EndDate+CHAR(39)+'
									ELSE ''2500-01-01''
								   END	
					AND Audited = 1
					AND  Ac_Items.typeName in (''G'',''E'') '

--9.6 杨俊 2015-05-13 不知道谁挖的坑，完全没用这一列，先注释，后续版本谁看见了就可以删了！
--IF @DTypeId <> ''
--	SET @SQL = @SQL + ' GROUP BY ListTable.BillNumberId,ListTable.ATypeId,Ac_Items.TypeName'
--ELSE
	SET @SQL = @SQL + 'GROUP BY ATypeId,Ac_Items.TypeName'
	
--****9.6需求修改-文档遗漏导致BUG：673 杨俊2015-05-13--
SET @SQL += '
			UNION ALL 
			SELECT (SELECT TOP 1 nId FROM Ac_Items WHERE FullName = ''业务提成'') AS ATypeID,
			ISNULL(SUM(CBND.CommissionTotal),0) AS Total,
			(SELECT TOP 1 TypeName FROM Ac_Items WHERE FullName = ''业务提成'') AS TypeName 
			FROM CommissionBillNew AS CBN
			INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
			INNER JOIN #GetManDTypeId AS d ON d.TypeId = CBND.DTypeID
			INNER JOIN #GetManSTypeId AS s ON s.TypeId = CBN.STypeId 
			WHERE CBN.ifcheck = ''t'' 
				AND CBN.BillDate >= CASE
									WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''d'' THEN '+CHAR(39)+@SingleDate+CHAR(39)+'
									WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''m'' THEN '+CHAR(39)+@MstartDate+CHAR(39)+'
									WHEN '+CHAR(39)+@nType+CHAR(39)+' = ''y'' THEN '+CHAR(39)+@StartDate+CHAR(39)+'
									ELSE ''1900-01-01''
							   END
				AND CBN.BillDate <= CASE
									WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''d'' THEN '+CHAR(39)+@SingleDate+CHAR(39)+'
									WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''m'' THEN '+CHAR(39)+@MendDate+CHAR(39)+'
									WHEN '+CHAR(39)+@nType+CHAR(39)+'  = ''y'' THEN '+CHAR(39)+@EndDate+CHAR(39)+'
									ELSE ''2500-01-01''
								   END
			'
--****************************************************************************--

--PRINT(@SQL)
EXECUTE(@SQL)

DECLARE @a  NUMERIC(24, 10) 
SELECT @a=SUM(Total) FROM #ListTable WHERE typename='G'



DECLARE @b  NUMERIC(24, 10) 
SELECT @b=SUM(Total) FROM #ListTable WHERE typename='E'

SELECT	@XsSr	= SUM(CASE WHEN ATypeId = @saleInCome THEN Total ELSE 0 END),
		@XsCb	= SUM(CASE WHEN ATypeId = @saleCost THEN Total ELSE 0 END),
		@WxSr	= SUM(CASE WHEN ATypeId = @proFixInCome THEN Total ELSE 0 END),
		@WxZc	= SUM(CASE WHEN ATypeId = @proFixExpend THEN Total ELSE 0 END),
		@BySr	= SUM(CASE WHEN ATypeId = @ReproFlowInCome THEN Total ELSE 0 END),
		@BsZc	= SUM(CASE WHEN ATypeId = @ReproLoss THEN Total ELSE 0 END),
		@HzSr	= SUM(CASE WHEN ATypeId = @ReciveInCome THEN Total ELSE 0 END),
		@ZsZc	= SUM(CASE WHEN ATypeId = @Present THEN Total ELSE 0 END),
		@TzSr	= SUM(CASE WHEN ATypeId = @BindTraInCome THEN Total ELSE 0 END),
		@TzZc	= SUM(CASE WHEN ATypeId = @BindTraLoss THEN Total ELSE 0 END),
		@CgThCj = SUM(CASE WHEN ATypeId = @BuyBack THEN Total ELSE 0 END),
		@YhJe 	= SUM(CASE WHEN ATypeId = @PrefMoney THEN Total ELSE 0 END),
		@BjDbCj	= SUM(CASE WHEN ATypeId = @VariPrice THEN Total ELSE 0 END),
		@GdZcZj = SUM(CASE WHEN ATypeId = @Fasset THEN Total ELSE 0 END),
		@CbTjSr = SUM(CASE WHEN ATypeId = @CostVariPrice THEN Total ELSE 0 END),
		@XsZk	= SUM(CASE WHEN ATypeId = @SaleFasset THEN Total ELSE 0 END),
		@StThCj	= SUM(CASE WHEN ATypeId = @FidureVariPrice THEN Total ELSE 0 END),
		@QtZc	= 0,
		@FdFl	= SUM(CASE WHEN ATypeId = @ReturnPInCome THEN Total ELSE 0 END),
		@QtSr	= 0,
		@BqSr	= @a,
		@BqZc	= @b
FROM	#ListTable


--如果为NULL，则处理成0
IF @XsSr IS NULL SET @XsSr = 0
IF @XsCb IS NULL SET @XsCb = 0
IF @WxSr IS NULL SET @WxSr = 0
IF @WxZc IS NULL SET @WxZc = 0
IF @BySr IS NULL SET @BySr = 0
IF @BsZc IS NULL SET @BsZc = 0
IF @HzSr IS NULL SET @HzSr = 0
IF @ZsZc IS NULL SET @ZsZc = 0
IF @TzSr IS NULL SET @TzSr = 0
IF @TzZc IS NULL SET @TzZc = 0
IF @CgThCj IS NULL SET @CgThCj = 0
IF @YhJe IS NULL SET @YhJe = 0
IF @BjDbCj IS NULL SET @BjDbCj = 0
IF @GdZcZj IS NULL SET @GdZcZj = 0
IF @CbTjSr IS NULL SET @CbTjSr = 0
IF @XsZk IS NULL SET @XsZk = 0
IF @StThCj IS NULL SET @StThCj = 0
IF @QtZc IS NULL SET @QtZc = 0
IF @FdFl IS NULL SET @FdFl = 0
IF @QtSr IS NULL SET @QtSr = 0
IF @CzCj IS NULL SET @CzCj = 0
IF @BqSr IS NULL SET @BqSr = 0
IF @BqZc IS NULL SET @BqZc = 0

--其它支出，其它收入
SET @OtherSr=@BqSr-@XsSr-@WxSr-@BySr-@HzSr-@TzSr-@CgThCj-@BjDbCj-@CbTjSr-@StThCj-@FdFl
SET @OtherZc=@BqZc-@XsCb-@WxZc-@BsZc-@ZsZc-@TzZc-@YhJe-@GdZcZj-@XsZk

--结果放这里
CREATE TABLE #Result
(
	Item1			VARCHAR(100),
	Total1			 NUMERIC(24, 10) ,
	Item2			VARCHAR(100),
	Total2			 NUMERIC(24, 10) ,
	Item3			VARCHAR(100),
	Total3			 NUMERIC(24, 10) 	
)
DECLARE @IsInvoice INT

SELECT @IsInvoice=SubValue FROM sysdata WHERE SubName='IsInvoice'

--物流单据
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('本期入库总额',@BqRkTotal,'本期出库总额',@BqCkTotal,'本期库存余额',@IniTotal+@PreTotal)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('其中：',NULL,'其中：',NULL,'',NULL)

--发票数据
IF @IsInvoice=1
BEGIN
	INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			暂估入库',@AppraisalTotal,'		发出商品出库',@SendTotal,'		',NULL)
	INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			暂估退货（冲减）',@AppraisalBackTotal,'		发出商品退货（冲减）',@SendBackTotal,'		',NULL)
END
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			采购入库',@BuyTotal,'		销售出库',@SaleTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			采购退货入库（冲减）',@BuyBackTotal,'		销售退货出库（冲减）',@SaleBackTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			受托代销入库',@StshTotal,'		委托代销出库',@WtfhTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			受托退货入库（冲减）',@StthTotal,'		委托退货出库（冲减）',@WtthTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			同价调拨入库',@TjdbRkTotal,'		同价调拨出库',@TjdbCkTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			变价调拨入库',@BjdbRkTotal,'		变价调拨出库',@BjdbCkTotal,'		',NULL)
IF @proinfo<>'3' --不是汽配
BEGIN
	INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			维修调拨入库',@RepairDbRkTotal,'		维修调拨出库',@RepairDbCkTotal,'		',NULL)
END
IF @proinfo='2' or @proinfo='3' --A8、汽配
BEGIN
	INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			分支机构调拨入库',@StypeDbRkTotal,'		分支机构调拨出库',@StypeDbCkTotal,'		',NULL)
END
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			报溢入库',@ByRkTotal,'		报损出库',@BsCkTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			拆装入库',@CzRkTotal,'		拆装出库',@CzCkTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			获赠入库',@HzRkTotal,'		赠送出库',@ZsCkTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			调价金额',@TjTotal,'		维修出库',@KxCkTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			其他入库',@QtRkTotal,'		其他出库',@QtCkTotal,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			',null,'		零售退货出库（冲减）',@Retailback,'		',NULL)

--钱流单据
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('本期收入',@BqSr,'本期支出',@BqZc,'本期利润',@BqSr-@BqZc)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('其中：',NULL,'其中：',NULL,'',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			销售收入',@XsSr,'		销售成本',@XsCb,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			商品维修收入',@WxSr,'		商品维修支出',@WxZc,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			商品报溢收入',@BySr,'		商品报损',@BsZc,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			商品获赠收入',@HzSr,'		商品赠出',@ZsZc,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			调账收入',@TzSr,'		调账亏损',@TzZc,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			采购退货差价',@CgThCj,'		抹零金额',@YhJe,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			变价调拨差价',@BjDbCj,'		固定资产折旧',@GdZcZj,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			成本调价收入',@CbTjSr,'		销售折扣返利支出',@XsZk,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			受托退货差价',@StThCj,'		',NULL,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			返点获利收入',@FdFl,'		',NULL,'		',NULL)
INSERT INTO #Result(Item1,Total1,Item2,Total2,Item3,Total3)VALUES('			其他收入合计',@OtherSr,'		其他支出合计',@OtherZc,'		',NULL)

SELECT * FROM #Result

DROP TABLE #GetManKTypeId,#Result,#ListTable




GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryStockBuy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryStockBuy]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	 作者：谢吉康
	 日期：2010-07-27
	 描述：仓库智能补货查询
	 
	 Modify:喻堂
	 Date:2012/3/7
	 Description:优化查询速度
	 
	 修改：舒珊
	 日期：2016-04-20
	 描述：仓库智能补货查询
	 
	 修改：陈强
	 日期：2019-10-31
	 描述：敏捷4629 --->  敏捷4704
*/
CREATE PROCEDURE QP_QueryStockBuy
(
	@OperatorId		VARCHAR(100),	--操作员ID
	@StartDate		VARCHAR(20),	--开始日期
	@EndDate		VARCHAR(20),	--截止日期
	@KTypeId		VARCHAR(100),	--仓库ID
	@Jhzq			NUMERIC(18,0),	--进货周期
	@Jhbhts			NUMERIC(18,0),	--计划补货天数
	@Xsts			NUMERIC(18,0),	--销售天数
	@ptypeid		VARCHAR(max)	--	商品id
	
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------



DECLARE @SQLText NVARCHAR(max);

--商品

SELECT	M.TypeId, P.UserCode, P.StopBuy, P.deleted
INTO #GetManPTypeId
FROM	F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID) M
INNER JOIN PType P ON M.TypeId = P.typeId 
WHERE P.SONNUM = 0 AND p.isservice=0;


--仓库
CREATE  TABLE #GetManKTypeId(typeid VARCHAR(200))
IF @KTypeId <> '' OR @MKtypeid <> '00000'
	BEGIN
	INSERT INTO #GetManKTypeId	SELECT bk.TypeId
	
		FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) bk  
		--INSERT INTO #GetManKTypeId(TypeId) 
		--SELECT k.TypeId FROM Stock k	WHERE  k.SonNum = 0
	
	END
	
	IF @KTypeId = ''
			INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')	--要包含委托代销库	

--销售数据

CREATE TABLE #XsData
(
	PTypeId		VARCHAR(100),
	Qty			 NUMERIC(24, 10) ,
	RjQty		 NUMERIC(24, 10) ,
	JhzqQty		 NUMERIC(24, 10) ,
	JhbhQty		 NUMERIC(24, 10) ,
);

EXEC sp_executesql @SQLText;

SET @SQLText = '
	INSERT INTO #XsData
	SELECT i.PTypeId,
		SUM(-1*Qty) AS Qty, 
		CAST(SUM(-1*Qty)/'+CAST(@Xsts AS VARCHAR(22))+' AS  NUMERIC(24, 10) ) AS RjQty,
		CAST(CAST(SUM(-1*Qty)/'+CAST(@Xsts AS VARCHAR(22))+' AS  NUMERIC(24, 10) )*'+CAST(@Jhzq AS VARCHAR(22))+' AS NUMERIC(18,0)) AS JhzqQty, 
		CAST(CAST(SUM(-1*Qty)/'+CAST(@Xsts AS VARCHAR(22))+' AS  NUMERIC(24, 10) )*'+CAST(@Jhbhts AS VARCHAR(22))+' AS NUMERIC(18,0)) AS JhbhQty 
	FROM InOutstocktable i
	inner join billindex  bi on i.billnumberid=bi.billnumberid
   ' + 
CASE WHEN @KTypeId <> '' OR @MKtypeid <> '00000' THEN
	'INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = i.KTypeId'
ELSE '' END 
+ '
	WHERE	i.BillDate >= '''+@StartDate+'''
			AND i.BillDate <= '''+@EndDate+'''
			AND i.BillType IN (305,11,45,141,160,215,12,46,402,403)
			and bi.redword=0
			--AND Audited = 1
			GROUP BY i.PTypeId;
';

EXEC sp_executesql @SQLText;

CREATE TABLE #KcData
(
	PTypeId nvarchar(200),
	Qty  NUMERIC(24, 10) 
);


SET @SQLText = '
	INSERT INTO #KCData
	SELECT	PTypeId,
			SUM(Qty) AS Qty
	FROM 	GoodsStocks
' + 
CASE WHEN @KTypeId <> '' OR @MKtypeid <> '00000' THEN
	'INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = GoodsStocks.KTypeId'
ELSE '' END
+ ' 
	GROUP BY PTypeId
';

EXEC sp_executesql @SQLText;

CREATE TABLE #VirtualStock
(
	PTypeId				VARCHAR(100),
	ktypeid				VARCHAR(100),
	ProduceDate			DATETIME,
	ValidDate			DATETIME,	
	qty					 NUMERIC(24, 10) ,
	rqty				 NUMERIC(24, 10) ,
	cqty				 NUMERIC(24, 10) ,
	saleorderqty		 NUMERIC(24, 10) ,
	buyorderqty			 NUMERIC(24, 10) ,
	salereachqty		 NUMERIC(24, 10) ,
	buyreachqty			 NUMERIC(24, 10) ,
	BuyReferQty  NUMERIC(24, 10) ,
	SaleReferQty  NUMERIC(24, 10) 
);

INSERT INTO #VirtualStock EXEC  Web_QueryVirtualStock_ZhiNengBuHuo @OperatorID=@OperatorID,@PTypeId=@ptypeid,@KTypeId=@KTypeId

------------敏捷4629 虚拟 库存数量有问题(陈强2019-09-16，参考虚拟库存状况表，添加此字段计算buyorderqty)-------- 
if not exists (select name from syscolumns where id = object_id(N'[dbo].[#VirtualStock]') and name = 'LimitBuyQty' )
BEGIN
	ALTER TABLE dbo.#VirtualStock ADD
		LimitBuyQty  NUMERIC(24, 10)  NULL DEFAULT(0)
END

IF NOT EXISTS (select name from syscolumns where id = object_id(N'[dbo].[#VirtualStock]') and name = 'LimitSaleQty' )
BEGIN
	ALTER TABLE dbo.#VirtualStock ADD
		LimitSaleQty  NUMERIC(24, 10)  NULL DEFAULT(0)
END

UPDATE #VirtualStock SET LimitBuyQty = o.LimitBuyQty,LimitSaleQty=o.LimitSaleQty 
FROM #VirtualStock s 
INNER JOIN (select ptypeId,ktypeId, sum(LimitBuyQty) LimitBuyQty ,sum(LimitSaleQty) LimitSaleQty,ProduceDate,ValidDate from GoodsStocks_Order group by PtypeId,KtypeId,ProduceDate,ValidDate) o on o.PtypeId=s.PTypeId AND o.KtypeId=s.ktypeid AND s.ProduceDate=o.ProduceDate AND s.ValidDate=o.ValidDate

------------------------------------------------END--------------------------------------------------------------

------加借欠两列
if not exists (select name from syscolumns where id = object_id(N'[dbo].[#VirtualStock]') and name = 'borrowqty' )
BEGIN
	ALTER TABLE dbo.#VirtualStock ADD
		borrowqty  NUMERIC(24, 10)  NULL DEFAULT(0)
END

IF NOT EXISTS(SELECT name FROM syscolumns where id = object_id(N'[dbo].[#VirtualStock]') and name = 'lendqty')
BEGIN
	ALTER TABLE dbo.#VirtualStock ADD
		lendqty  NUMERIC(24, 10)  NULL DEFAULT(0)
END
SET @SQLText ='
INSERT INTO #VirtualStock
        ( PTypeId ,
          borrowqty,
          lendqty
        )
 SELECT 	    a.typeid,
				SUM(o.Borrow-o.BorrowBack) AS  Borrowqty,
				SUM(o.Lend-o.LendBack) AS Lendqty
			
		FROM 	V_LendStatus o 
		       INNer join ptype p1  on o.ptypeid=p1.typeid 
		       inner join #GetManPTypeId a on a.typeid=o.ptypeid '+
		       CASE WHEN @KTypeId <> '' OR @MKtypeid <> '00000' THEN
	         'INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = o.KTypeId'
ELSE '' END
+ ' 
	GROUP BY a.typeid
'
EXEC sp_executesql @SQLText;

--------加借欠两列
---这里不再用黑夜公式直接取虚拟库存状况表设置的公式
DECLARE @virtualqtysql NVARCHAR(max),
		@sjbhl NVARCHAR(100)

SELECT @virtualqtysql= Value FROM dbo.Userconfig WHERE ConfigName='virtualqtysql'
SELECT @sjbhl= Value FROM dbo.Userconfig WHERE ConfigName='sjbhlsql'

--最后结果
CREATE TABLE #Result
(
	PTypeId		VARCHAR(100),
	Qty			 NUMERIC(24, 10) ,
	RjQty		 NUMERIC(24, 10) ,
	JhzqQty		 NUMERIC(24, 10) ,
	JhbhQty		 NUMERIC(24, 10) ,
	Jhbhl		 NUMERIC(24, 10) ,
	KcQty		 NUMERIC(24, 10) 
);
 

SET @SQLText ='
--INSERT INTO #Result
with tempResult as (
SELECT	R.PTypeId,
			CAST(SUM(R.Qty) AS  NUMERIC(24, 10) ) AS Qty,
			CAST(SUM(R.RjQty) AS  NUMERIC(24, 10) ) AS RjQty,
			CAST(SUM(R.JhzqQty) AS  NUMERIC(24, 10) ) AS JhzqQty,
			CAST(SUM(R.JhbhQty) AS  NUMERIC(24, 10) ) AS JhbhQty,
			--CAST(SUM(R.JhbhQty - R.KcQty + R.JhzqQty) AS NUMERIC(18,0)) AS Jhbhl,
			CAST(SUM(R.KcQty) AS  NUMERIC(24, 10) ) AS KcQty
	FROM	(
				SELECT	PTypeId,
						Qty,
						RjQty,
						JhzqQty,
						JhbhQty,
						0 AS KcQty
				FROM 	#XsData
				UNION ALL
				SELECT	PTypeId,
						0 AS Qty,
						0 AS RjQty,
						0 AS JhzqQty,
						0 AS JhbhQty,
						Qty AS KcQty
				FROM 	#KcData
	) R 
INNER JOIN #GetManPTypeId M ON M.TypeId = R.PTypeId AND M.StopBuy = 0 AND M.deleted = 0
	GROUP BY R.PTypeId)';


SET @SQLText += '
	SELECT *,'+@sjbhl+' AS Jhbhl from (
	SELECT	P.TypeId,
			ISNULL(M.Qty1,0) AS Qty,
			ISNULL(M.RjQty,0) AS RjQty,
			ISNULL(M.JhzqQty,0) AS JhzqQty,
			ISNULL(JhbhQty,0) AS JhbhQty,
			ISNULL(KcQty,0) AS KcQty,
			'+@virtualqtysql+' as virtualqty,
			ROW_NUMBER() OVER(ORDER BY UserCode )rank
	FROM	#GetManPTypeId P
	LEFT JOIN (
		SELECT	R.PTypeId,
				SUM(R.Qty) AS Qty1,
				SUM(R.RjQty) AS RjQty,
				SUM(R.JhzqQty) AS JhzqQty,
				SUM(R.JhbhQty) AS JhbhQty,
				--SUM(R.Jhbhl) AS Jhbhl,
				SUM(R.KcQty) AS KcQty
		FROM 	tempresult	R
		GROUP BY R.PTypeId
	)M ON P.typeId = M.PTypeId 
	left join (
	        SELECT  ptypeid ,
					SUM(qty) qty ,
					SUM(rqty) AS rqty ,
					SUM(cqty) AS cqty ,
				    CASE WHEN ISNULL(SUM(saleorderqty),0)-ISNULL(SUM(LimitSaleQty),0) > 0 THEN ISNULL(SUM(saleorderqty),0)-ISNULL(SUM(limitsaleqty),0) ELSE 0 END AS SaleOrderQty,
				    CASE WHEN ISNULL(SUM(BuyOrderQty),0)-ISNULL(SUM(LimitBuyQty),0)>0 THEN ISNULL(SUM(BuyOrderQty),0)-ISNULL(SUM(LimitBuyQty),0) ELSE 0 END  BuyOrderQty,
					SUM(ISNULL(borrowqty, 0)) AS borrowqty ,
					SUM(ISNULL(lendqty, 0)) AS lendqty
			FROM    #VirtualStock
				    GROUP BY ptypeid
	) k on p.typeid=k.ptypeid )	 A	
	WHERE	'+@sjbhl+'>0
	;';
	
--2019-12-05客户数据仍有问题，cqiang， 这里saleorder 取值 同 [Gp_VirtualStockStatus_Line] 里的取值一致
--CASE WHEN ISNULL(SUM(saleorderqty),0)-ISNULL(SUM(salereachqty),0)-ISNULL(SUM(SaleReferQty),0) > 0 THEN I
--SNULL(SUM(saleorderqty),0)-ISNULL(SUM(salereachqty),0)-ISNULL(SUM(SaleReferQty),0) ELSE 0 END AS SaleOrderQty,

-- CASE WHEN ISNULL(SUM(buyorderqty),0)-ISNULL(SUM(buyreachqty),0)-ISNULL(SUM(BuyReferQty),0) > 0 THEN 
-- ISNULL(SUM(buyorderqty),0)-ISNULL(SUM(buyreachqty),0)-ISNULL(SUM(BuyReferQty),0) ELSE 0 END AS BuyOrderQty, 
--ps：原来计算的bugorderqty好像有问题，这里修改为 虚拟库存状况表的 取法

--PRINT @SQLText

EXEC sp_executesql @SQLText;

TRUNCATE TABLE #XsData;
TRUNCATE TABLE #KcData;
TRUNCATE TABLE #Result;
DROP TABLE #GetManKTypeId;

DROP TABLE #XsData,#KcData,#Result,#GetManPTypeId
--IF @KTypeId <> '' OR @MKtypeid <> '00000'
--BEGIN
--	TRUNCATE TABLE #GetManKTypeId;
--	DROP TABLE #GetManKTypeId;
--END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF NOT EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TBType_QueryStockBuyAutoCaoGao' AND ss.name = N'dbo')
BEGIN
	CREATE TYPE [dbo].[TBType_QueryStockBuyAutoCaoGao] AS TABLE(
	ptypeid VARCHAR(50) ,
	jhbhl  NUMERIC(24, 10) 
)
END
GO 
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryStockBuyAutoCaoGao]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryStockBuyAutoCaoGao]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	 作者：谢吉康
	 日期：2010-07-27
	 描述：仓库智能补货查询生成单据
*/
CREATE PROCEDURE QP_QueryStockBuyAutoCaoGao
(
	@OperatorId		VARCHAR(100),	--操作员ID
	@StartDate		VARCHAR(20),	--开始日期
	@EndDate		VARCHAR(20),	--截止日期
	@KTypeId		VARCHAR(100),	--仓库ID
	@Jhzq			NUMERIC(18,0),	--进货周期
	@Jhbhts			NUMERIC(18,0),	--计划补货天数
	@Xsts			NUMERIC(18,0),	--销售天数
	@PTypeId		VARCHAR(8000),	--商品ID列表
	@BillType		INT,			--单据类型 301.采购订单  34.采购入库单
	@Chk			VARCHAR(10),	--按照商品对应的供货商生成单据
	@rbcode			VARCHAR(8000) OUTPUT,
	@stypeid		VARCHAR(50),	--看代码逻辑和页面，这里应该是单选，所以将长度由max改为50
	@details TBType_QueryStockBuyAutoCaoGao READONLY,  --商品实际补货量 
	@chj			int             --按商品对应采购单位生成
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) 
SELECT	M.TypeId 
FROM	F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID) M
INNER JOIN PType P ON M.TypeId = P.typeId 
WHERE	P.StopBuy = 0

CREATE TABLE #GetManPTypeId1(TypeId	varchar(100),rate  NUMERIC(24, 10) ,aunitid VARCHAR(200))
INSERT INTO #GetManPTypeId1(TypeId,rate,aunitid) SELECT c.TypeId,ISNULL(b.Rate,0)AS rate,ISNULL(b.UnitsId,0)AS UnitsId FROM #GetManPTypeId c INNER  JOIN  dbo.ptype  a
ON c.TypeId = a.typeId LEFT JOIN dbo.PType_Units_Ext b ON a.typeId=b.PtypeID AND a.AssistantUnitId=b.UnitsId



DECLARE @cargoid int


--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @KTypeId = ''
	BEGIN
		INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE Deleted = 0 AND SonNum = 0
		INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')
		
		SET @cargoid=0
	END
ELSE
BEGIN
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)
	SELECT  @cargoid=CargoID FROM dbo.CargoType WHERE IsDefault=1 AND KtypeID=@KTypeId AND deleted=0
END
	

IF NOT (@KTypeId='' OR @KTypeId='00000')
BEGIN
	IF NOT EXISTS(
		SELECT  TOP 1 1
		FROM (SELECT STypeID  FROM  stock WHERE typeid= @ktypeid) b 
				INNER JOIN  (SELECT TOP 1 typeId  FROM  stype WHERE typeid= @stypeid) s  ON b.STypeID=s.TypeId
	)
	BEGIN 
		DECLARE @stockName VARCHAR(MAX)
		SELECT @stockName=fullname FROM stock  WHERE typeId= @KTypeId
		
		SET @stockName='【'+@stockName+'】不属于所选分支机构！'
		RAISERROR (@stockName,16, 1)
		return 
	END 	
END

----销售数据
--CREATE TABLE #XsData
--(
--	PTypeId		VARCHAR(100),
--	Qty			 NUMERIC(24, 10) ,
--	RjQty		 NUMERIC(24, 10) ,
--	JhzqQty		 NUMERIC(24, 10) ,
--	JhbhQty		 NUMERIC(24, 10) ,
--	Jhbhl		 NUMERIC(24, 10) 
--)

--INSERT INTO #XsData
--SELECT	PTypeId,
--		SUM(-1*Qty) AS Qty,
--		CAST(SUM(-1*Qty)/@Xsts AS  NUMERIC(24, 10) ) AS RjQty,
--		CAST(CAST(SUM(-1*Qty)/@Xsts AS  NUMERIC(24, 10) )*@Jhzq AS NUMERIC(18,0)) AS JhzqQty,
--		CAST(CAST(SUM(-1*Qty)/@Xsts AS  NUMERIC(24, 10) )*@Jhbhts AS NUMERIC(18,0)) AS JhbhQty,
--		0 AS Jhbhl
--FROM	InOutstocktable
--INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = InOutStockTable.KTypeId
--WHERE	BillDate >= @StartDate
--		AND BillDate <= @EndDate
--		AND BillType IN (305,11,45,141,160)
--		AND Audited = 1
--GROUP BY PTypeId		
		
--库存数量		
--CREATE TABLE #KcData
--(
--	PTypeId		VARCHAR(100),
--	Qty			 NUMERIC(24, 10) 
--)			

--INSERT INTO #KCData
--SELECT	PTypeId,
--		SUM(Qty) AS Qty
--FROM 	GoodsStocks
--INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = GoodsStocks.KTypeId
--GROUP BY PTypeId


DECLARE
	@NowDate	DATETIME

SELECT @NowDate=GETDATE()

----最后结果
--CREATE TABLE #Result
--(
--	PTypeId		VARCHAR(100),
--	Qty			 NUMERIC(24, 10) ,
--	RjQty		 NUMERIC(24, 10) ,
--	JhzqQty		 NUMERIC(24, 10) ,
--	JhbhQty		 NUMERIC(24, 10) ,
--	Jhbhl		 NUMERIC(24, 10) ,
--	KcQty		 NUMERIC(24, 10) 
--)
--INSERT INTO #Result
--SELECT	R.PTypeId,
--		SUM(R.Qty) AS Qty,
--		SUM(R.RjQty) AS RjQty,
--		SUM(R.JhzqQty) AS JhzqQty,
--		SUM(R.JhbhQty) AS JhbhQty,
--		CAST(SUM(R.JhbhQty - R.KcQty + R.JhzqQty) AS NUMERIC(18,0)) AS Jhbhl,
--		SUM(R.KcQty) AS KcQty
--FROM	(
--			SELECT	PTypeId,
--					Qty,
--					RjQty,
--					JhzqQty,
--					JhbhQty,
--					Jhbhl,
--					0 AS KcQty
--			FROM 	#XsData
--			UNION ALL
--			SELECT	PTypeId,
--					0 AS Qty,
--					0 AS RjQty,
--					0 AS JhzqQty,
--					0 AS JhbhQty,
--					0 AS Jhbhl,
--					Qty AS KcQty
--			FROM 	#KcData
--) R INNER JOIN #GetManPTypeId M ON M.TypeId = R.PTypeId
--GROUP BY R.PTypeId

--IF NOT EXISTS(SELECT TOP 1 1 FROM #Result WHERE ISNULL(Jhbhl,0)>0)
--	RETURN -1
IF NOT EXISTS(SELECT TOP 1 1 FROM @details WHERE ISNULL(Jhbhl,0)>0)
	RETURN -1

--生成单据
DECLARE @MONTH 				VARCHAR(50),
		@DAY 				VARCHAR(50),
		@BillCodeConfig		VARCHAR(10),
		@BillCode			VARCHAR(300),
		@Rex				INT,
		@Tax				 NUMERIC(24, 10) ,
		@period				INT,
		@DTypeId			VARCHAR(200),
		@nBillId			NUMERIC(18,0),
		@recPrice			 NUMERIC(24, 10) ,
		@preprice			 NUMERIC(24, 10) ,
		@Explain			VARCHAR(400),
		@TotalQty			 NUMERIC(24, 10) ,
		@TotalMoney			 NUMERIC(24, 10) ,
		@ETypeId			VARCHAR(200),
		@bCount				INT,
		@BillCount			INT,
		@i					INT,
		@bCodeList			VARCHAR(8000),
		@VchType			INT,
		@VchHead			VARCHAR(20),
		@Discount			 NUMERIC(24, 10) ,		
		@GridType			INT,		
		@bcode				VARCHAR(400),
		@TmpBillCode		VARCHAR(8000),
		@MxBTypeId			VARCHAR(100),
		@cid               int,
		@atypeid1           varchar(200),
		@cefullname			VARCHAR(500)='',
		@cdfullname			VARCHAR(500)=''
		
set @cid=(SELECT cid FROM dbo.Ac_Currency WHERE Sysrow=1 AND Deleted=0)
SET @Tax = 0
SET @Discount = 0
SET @recPrice = 0
SET @preprice = 0
SET @ETypeId = @OperatorID
SET @i = 1
SET @bCodeList = ''
SET @DTypeId = ''

CREATE TABLE #temtable(atypeid1 VARCHAR(200),atypeid1name VARCHAR(200),flag VARCHAR(200))

INSERT INTO #temtable(atypeid1,atypeid1name,flag)  EXEC dbo.Web_GetAtype 
    @billtypeid=@BillType, 
    @stypeid=@stypeid
SET @atypeid1= (select atypeid1 FROM #temtable )

IF EXISTS (SELECT * FROM sysdata WHERE SubName = 'ifQP' AND SubValue = 1)
	SET @Explain = '库存配件智能补货生成的草稿'
ELSE
	SET @Explain = '库存商品智能补货生成的草稿'

IF @BillType = 34
	BEGIN
		SET @VchType = 34
		SET @VchHead = 'JK'
	END
ELSE
	BEGIN
		SET @VchType = 301
		SET @VchHead = 'JD'
	END

SELECT @GridType = Value FROM userconfig WHERE configname = 'Gridtype'

IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '1')
	BEGIN
		SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'
		SELECT @Discount = 1
	END
ELSE IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '2')	
	BEGIN
		SELECT @Discount=Value from userconfig where configname = 'ZekouValue'
		SELECT @Tax=0
	END
ELSE IF EXISTS(select * from userconfig where configname = 'Gridtype' and value = '3')	
	BEGIN
		SET @Tax = 0
		SET @Discount = 1
	END
ELSE
	BEGIN
		SELECT @Tax = Value FROM UserConfig WHERE ConfigName = 'Alltaxrate'
		SELECT @Discount=Value from userconfig where configname = 'ZekouValue'
	END

SELECT @period = period FROM MonthProc WHERE MonthNo = '本期'
SELECT @DTypeId = D.TypeId FROM Department D,Employee E WHERE E.DTypeId = D.TypeId AND E.TypeId = @ETypeId

SET @MONTH = month(getdate())
SET @DAY = day(getdate())

SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig'

CREATE TABLE #MxBill
(
	nid			int identity(1,1),
	PTypeId		varchar(200),
	BTypeId		VARCHAR(200),
	Qty			 NUMERIC(24, 10) ,--采购单位数量
	baseqty		 NUMERIC(24, 10) ,--基本单位数量 
	recPrice	 NUMERIC(24, 10) ,--采购单位
	baserecprice	 NUMERIC(24, 10) ,--基本单位
    unitid      INT ,		  --采购单位	
    baseunitid     INT,			  --基本单位
    rate			 NUMERIC(24, 10) 			--换算率	
)

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'ProInfo' AND SubValue = 2)
BEGIN
	INSERT INTO #MxBill(PTypeId,BTypeId,Qty,baseqty,recPrice,baserecprice,unitid,baseunitid,rate)
	SELECT	P.TypeId,
			'' AS BTypeId,
			R.Jhbhl,
			R.Jhbhl,
			ISNULL(sP.recPrice,0),
			ISNULL(sP.recPrice,0),
			p.baseUnitId,
			p.baseUnitId,1
	FROM	PType P
	INNER JOIN @details R ON P.TypeId = R.PTypeId
	LEFT JOIN dbo.PType_STypePrice sp ON sp.PTypeID = p.typeId AND sp.UnitID = p.baseUnitId AND sp.STypeID = @stypeid
	WHERE	ISNULL(R.Jhbhl,0)>0
	ORDER BY P.UserCode
END
ELSE
BEGIN
	INSERT INTO #MxBill(PTypeId,BTypeId,Qty,baseqty,recPrice,baserecprice,unitid,baseunitid,rate)
	SELECT	P.TypeId,
			'' AS BTypeId,
			R.Jhbhl,
			R.Jhbhl,
			ISNULL(pri.RecAmgSTypeBuyPrice,0),
			ISNULL(pri.RecAmgSTypeBuyPrice,0),
			p.baseUnitId,
			p.baseUnitId,1
	FROM	PType P
	INNER JOIN @details R ON P.TypeId = R.PTypeId
	LEFT JOIN dbo.PType_Price pri ON pri.PTypeID = p.typeId AND pri.UnitID = p.baseUnitId
	WHERE	ISNULL(R.Jhbhl,0)>0
	ORDER BY P.UserCode
END

--如果是按照往来单位生成，则需要修改往来单位信息
IF @chk = 1
	BEGIN
		UPDATE	#MxBill
		SET		BTypeId = ISNULL(Q.BTypeId,'')
		FROM	#MxBill M
		LEFT JOIN (
			SELECT	PTypeId,
					ISNULL(BTypeId,'') AS BTypeId
			FROM 	QP_PType_Ext
		)Q ON Q.PTypeId = M.PTypeId
	END
	
IF @chj=1
BEGIN		
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'ProInfo' AND SubValue = 2)
	BEGIN			
		UPDATE	#MxBill
		SET		Qty=qty/isnull(q.rate,1),
				unitid= q.BuyUnitId ,
				recPrice=ISNULL(sp.RecPrice,0),
				baserecprice=ISNULL(sp.RecPrice,0)/ISNULL(q.Rate,1) ,
				rate=ISNULL(q.Rate,1)
		FROM	#MxBill M
		LEFT JOIN (			
				SELECT b.ptypeID,BuyUnitId,b.Rate
				FROM dbo.ptype a 
				INNER JOIN dbo.PType_Units_Ext b ON a.typeId=b.PtypeID AND BuyUnitId= b.UnitsId
				)Q ON Q.PTypeId = M.PTypeId
		LEFT JOIN dbo.PType_STypePrice sp ON sp.PTypeID = m.PTypeId AND sp.UnitID = q.BuyUnitId AND sp.STypeID = @stypeid
	END
	ELSE
	BEGIN			
		UPDATE	#MxBill
		SET		Qty=qty/isnull(q.rate,1),
				unitid=q.BuyUnitId,
				recPrice= ISNULL(pri.RecAmgSTypeBuyPrice,0),
				baserecprice=ISNULL(pri.RecAmgSTypeBuyPrice,0)/ISNULL(q.Rate,1) ,
				rate=ISNULL(q.Rate,1)
		FROM	#MxBill M
		LEFT JOIN (			
				SELECT b.ptypeID,BuyUnitId,b.Rate 
				FROM dbo.ptype a 
				INNER JOIN dbo.PType_Units_Ext b ON a.typeId=b.PtypeID AND BuyUnitId= b.UnitsId
				)Q ON Q.PTypeId = M.PTypeId
		LEFT JOIN dbo.PType_Price pri ON pri.PTypeID = m.PTypeId AND pri.UnitID = q.BuyUnitId
		LEFT JOIN dbo.ptype p ON p.typeId = m.PTypeId
	END
	
END
	
DECLARE @BeginDate 	datetime,
		@szItem 	varchar(30),
		@szVchCode 	varchar(30),
		@szPeriod	varchar(20)

--按照往来单位为标准生成单据
DECLARE BilCursor CURSOR FOR 
	SELECT DISTINCT BTypeId FROM #MxBill ORDER BY BTypeId

OPEN BilCursor

FETCH NEXT FROM BilCursor INTO @MxBTypeId

WHILE @@FETCH_STATUS = 0
	BEGIN	
		SELECT @bCount = COUNT(*) FROM #MxBill WHERE BTypeId = @MxBTypeId
		DECLARE @dealbtypeid VARCHAR(200)
		SET @dealbtypeid=(SELECT denominatedid FROM dbo.btype WHERE  typeId=@MxBTypeId)
		IF @dealbtypeid IS NULL 
		 BEGIN 
		 SET @dealbtypeid='';
		 END
		IF @bCount % 150 = 0
			SET @BillCount = @bCount / 150
		ELSE
			SET @BillCount = @bCount / 150 + 1
		
		--EXEC Gp_GetSubValue 'period',@szPeriod out
		SELECT TOP 1 @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
		IF GetDate()<@BeginDate 
			BEGIN 
				--RAISERROR('录单日期小于本期开始日期 ！',16,1)
				RETURN -33
			END
		
		SET @i =  1
		
		WHILE @i<=@BillCount
			BEGIN
				--生成单据编号
				IF EXISTS(SELECT BillType FROM CodeConfig WHERE BillType = @VchType) AND @BillCodeConfig = '1'
					BEGIN
						SELECT @MONTH = ''
						SELECT @DAY = FullName FROM Stock WHERE TypeID = @KTypeId
						SELECT @cefullname = E.fullname FROM Employee E WHERE E.TypeId = @OperatorId
						SELECT @cdfullname = FullName FROM dbo.Department  WHERE TypeId = @DTypeId
						
					END
		
				EXEC @Re=Gp_GetBillCode @VchType, @MONTH,@DAY,@VchHead,@NowDate,@stypeid,@BillCode OUTPUT,@cdfullname,@cefullname,-999
				
				IF @Re <> 0
					RETURN -2	
					
					
		
				--写入单据主表 SELECT * FROM OrderIndex
				IF @VchType IN (300,301)
					INSERT INTO OrderIndex (BillDate,BillCode,BillType,btypeid,etypeid,ktypeid,checke,totalmoney,Ntotalmoney,totalqty,tax,period,RedWord,waybillcode,packway,TEL,IfAudit,DTypeId,Explain,OrderState,etypeid2,waymode,goodsnumber,STypeID,CID,Rate,DealBTypeID)
					VALUES(CONVERT(varchar(10),GetDate(),120),@BillCode,@VchType,@dealbtypeid,'',CASE WHEN @KTypeId = '00000' THEN '' ELSE @KTypeId END,@OperatorId,0,0,0,@Tax,@period,0,'','','','1','',@Explain,0,'','','',@STypeID,@cid,1,@MxBTypeId)
				ELSE
					INSERT INTO BillIndex (AlertDay,checkTime,BillDate,BillCode,BillType,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,NTotalMoney,totalinmoney,NTotalInMoney,totalqty,tax,period,RedWord,draft,OrderId,waybillcode,packway,TEL,IfAudit,preferencemoney,DTypeId,Explain,STypeID,CID,Rate,ATypeID1,DealBTypeID)
					VALUES(9999,GETDATE(),CONVERT(varchar(10),GetDate(),120),@BillCode,@VchType,'','',@dealbtypeid,'',CASE WHEN @KTypeId = '00000' THEN '' ELSE @KTypeId END,'','f',@OperatorId,0,0,0,0,0,@Tax,@period,0,1,0,'','','','3',0,'',@Explain,@STypeID,@cid,1,@atypeid1,@MxBTypeId)
				
				IF @@ROWCOUNT = 0
					RETURN -3
				ELSE
					SET @nBillId = SCOPE_IDENTITY();
					
				--插入明细表
		 		IF @VchType = 34
					BEGIN
						IF @GridType = 1
                            INSERT  INTO BuyBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     NQty,
                                     MQty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     KTypeId,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     MUnitID,
                                     CargoID,
                                     UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        baseqty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE baseqty/b.rate
                                        END,
                                        qty,
                                        baserecPrice,
                                        baserecPrice,
                                        recprice,
                                        recprice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        baserecPrice,
                                        baserecPrice,
                                        recPrice,
                                        recprice,
                                        CAST(CAST(baserecPrice*(1+@Tax/100)*Qty AS  NUMERIC(24, 10) )/Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(baserecPrice*(1+@Tax/100)*Qty AS  NUMERIC(24, 10) )/Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100)*Qty AS  NUMERIC(24, 10) )/Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100)*Qty AS  NUMERIC(24, 10) )/Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100)*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*(1+@Tax/100)*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @KTypeId,
                                        @STypeID,
                                        baseunitid,
                                        b.aunitid,
                                        unitid,
                                        @cargoid,
                                        b.rate,
                                        a.rate,
                                       
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),-1
                                    FROM
                                        #MxBill a
                                    INNER JOIN #GetManPTypeId1 b
                                        ON a.ptypeid=b.typeid
                                    WHERE
                                        nid>(@i-1)*150 AND
                                        nid<=@i*150 AND
                                        BTypeId=@MxBTypeId
						ELSE IF @GridType = 2
                            INSERT  INTO BuyBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     MQty,
                                     nqty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     KTypeId,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     MUnitID,
                                     CargoID,
                                     UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        baseQty,
                                        Qty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE baseQty/b.rate
                                        END,
                                        CAST(baserecPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                        CAST(baserecPrice*Qty/@Discount/baseqty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                        CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                        CAST(recPrice AS  NUMERIC(24, 10) ),
                                        CAST(recPrice AS  NUMERIC(24, 10) ),
                                        CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                        CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                        CAST(recPrice AS  NUMERIC(24, 10) ),
                                        CAST(recPrice AS  NUMERIC(24, 10) ),
                                        CAST(recPrice* Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty/@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty/@Discount AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @KTypeId,
                                        @STypeID,
                                        baseunitid,
                                        b.aunitid,
                                        unitid,
                                        @cargoid,
                                        b.rate,
                                       a.rate,
                                        CAST(CAST(recPrice AS  NUMERIC(24, 10) )*
                                        Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice AS  NUMERIC(24, 10) )*
                                        Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),-1
                                    FROM
                                        #MxBill a
                                    INNER JOIN #GetManPTypeId1 b
                                        ON a.ptypeid=b.typeid
                                    WHERE
                                        nid>(@i-1)*150 AND
                                        nid<=@i*150 AND
                                        BTypeId=@MxBTypeId	
						ELSE IF @GridType = 3
                            INSERT  INTO BuyBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     mqty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     KTypeId,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     MUnitID,
                                     CargoID,
                                     UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        baseQty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE baseQty/b.rate
                                        END,
                                        qty,  
                                        baserecPrice,
                                        baserecPrice,
                                        recprice,
                                        recprice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        baserecPrice,
                                        baserecPrice,
                                        recPrice,
                                        recPrice,
                                        baserecPrice,
                                        baserecPrice,
                                        recPrice,
                                        recPrice,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @KTypeId,
                                        @STypeID,
                                        baseunitid,
                                        b.aunitid,
                                        unitid,
                                        @cargoid,
                                        b.rate,
                                        a.rate,
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),-1
                                    FROM
                                        #MxBill a
                                    INNER JOIN #GetManPTypeId1 b
                                        ON a.ptypeid=b.typeid
                                    WHERE
                                        nid>(@i-1)*150 AND
                                        nid<=@i*150 AND
                                        BTypeId=@MxBTypeId
						ELSE
                            INSERT  INTO BuyBill
                                    (BillNumberId,
                                     PTypeId,
                                     Qty,
                                     nqty,
                                     mqty,
                                     SalePrice,
                                     NSalePrice,
                                     MSalePrice,
                                     CurMSalePrice,
                                     Total,
                                     NTotal,
                                     Discount,
                                     DiscountPrice,
                                     NDiscountPrice,
                                     MDiscountPrice,
                                     CurMDiscountPrice,
                                     TaxPrice,
                                     NTaxPrice,
                                     MTaxPrice,
                                     CurMTaxPrice,
                                     TaxTotal,
                                     NTaxTotal,
                                     SaleTotal,
                                     NSaleTotal,
                                     tax,
                                     KTypeId,
                                     STypeID,
                                     UnitID,
                                     NUnitID,
                                     MUnitID,
                                     CargoID,
                                     UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                    SELECT
                                        @nBillId,
                                        PTypeId,
                                        baseQty,
                                        CASE WHEN b.rate=0 THEN 0
                                             ELSE baseQty/b.rate
                                        END,
                                        qty,
                                        CAST(baserecPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                        CAST(baserecPrice*baseQty/@Discount/baseqty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                        @Discount,
                                        CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                        CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                        CAST(recPrice AS  NUMERIC(24, 10) ),
                                        CAST(recPrice AS  NUMERIC(24, 10) ),
                                        CAST(CAST(baserecPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(baserecPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/Qty AS  NUMERIC(24, 10) ),
                                        CAST(CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/Qty AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty *(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty/@Discount AS  NUMERIC(24, 10) ),
                                        CAST(recPrice*Qty/@Discount AS  NUMERIC(24, 10) ),
                                        @Tax,
                                        @KTypeId,
                                        @STypeID,
                                        baseunitid,
                                        b.aunitid,
                                        unitid,
                                        @cargoid,
                                        b.rate,
                                        a.rate,
                                      
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-  CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                         CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-  CAST(recPrice*Qty AS  NUMERIC(24, 10) ),-1
                                    FROM
                                        #MxBill a
                                    INNER JOIN #GetManPTypeId1 b
                                        ON a.ptypeid=b.typeid
                                    WHERE
                                        nid>(@i-1)*150 AND
                                        nid<=@i*150 AND
                                        BTypeId=@MxBTypeId

						--修改BillIndex的TotalMoney
					
						SELECT @TotalQty =ISNULL(SUM(Qty),0) ,@TotalMoney = ISNULL(SUM(TaxTotal),0) FROM BuyBill WHERE BillNumberId = @nBillId
						UPDATE BillIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney ,NTotalMoney=@TotalMoney WHERE BillNumberId = @nBillId	
						--处理货位
						UPDATE dbo.BuyBill SET ShowOrder=ID WHERE BillNumberId=@nBillId
					END
				ELSE IF @VchType IN (300,301)
					BEGIN
						IF @VchType = 301
							BEGIN
								IF @GridType = 1
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             NQty,
                                             mqty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeId,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             MUnitID,
                                             CargoID,
                                             UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                baseQty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE baseQty/b.rate
                                                END,
                                                qty,
                                                baserecPrice,
                                                baserecPrice,
                                                recPrice,
                                                recPrice,
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                1,
                                                baserecPrice,
                                                baserecPrice,
                                                recPrice,
                                                recprice,
                                                CAST(CAST(baserecPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/qty AS  NUMERIC(24, 10) ),
                                                CAST(CAST(baserecPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/qty AS  NUMERIC(24, 10) ),
                                                CAST(CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/qty AS  NUMERIC(24, 10) ),
                                                CAST(CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                @Tax,
                                                @KTypeId,
                                                @STypeID,
                                                baseunitid,
                                                b.aunitid,
                                                unitid,
                                                @cargoid,
                                                b.rate,
                                                a.rate,
                                                CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),-1
                                            FROM
                                                #MxBill a
                                            INNER JOIN #GetManPTypeId1 b
                                                ON a.ptypeid=b.typeid
                                            WHERE
                                                nid>(@i-1)*150 AND
                                                nid<=@i*150 AND
                                                BTypeId=@MxBTypeId	
								ELSE IF @GridType = 2
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             nqty,
                                             mqty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeId,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             MUnitID,
                                             CargoID,
                                             UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                baseQty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE baseQty/b.rate
                                                END,
                                                qty,
                                                CAST(baserecPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                                CAST(baserecPrice*baseQty/@Discount/baseqty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                @Discount,
                                                CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                                CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                                CAST(recPrice AS  NUMERIC(24, 10) ),
                                                CAST(recPrice AS  NUMERIC(24, 10) ),
                                                CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                                CAST(baserecPrice AS  NUMERIC(24, 10) ),
                                                CAST(recPrice AS  NUMERIC(24, 10) ),
                                                CAST(recPrice AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty/@Discount AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty/@Discount AS  NUMERIC(24, 10) ),
                                                @Tax,
                                                @KTypeId,
                                                @STypeID,
                                                baseunitid,
                                                b.aunitid,
                                                unitid,
                                                @cargoid,
                                                b.rate,
                                                a.rate,
                                                CAST(CAST(recPrice AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(CAST(recPrice AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(recPrice*Qty AS  NUMERIC(24, 10) ),-1
                                            FROM
                                                #MxBill a
                                            INNER JOIN #GetManPTypeId1 b
                                                ON a.ptypeid=b.typeid
                                            WHERE
                                                nid>(@i-1)*150 AND
                                                nid<=@i*150 AND
                                                BTypeId=@MxBTypeId	
								ELSE IF @GridType = 3
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             nqty,
                                             mqty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeId,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             MUnitID,
                                             CargoID,
                                             UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                baseQty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE baseQty/b.rate
                                                END,
                                                Qty,
                                                baserecPrice,
                                                baserecPrice,
                                                recPrice,
                                                recPrice,
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                @Discount,
                                                baserecPrice,
                                                baserecPrice,
                                                recPrice,
                                                recPrice,
                                                baserecPrice,
                                                baserecPrice,
                                                recPrice,
                                                recPrice,
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                @Tax,
                                                @KTypeId,
                                                @STypeID,
                                                baseunitid,
                                                b.aunitid,
                                                unitid,
                                                @cargoid,
                                                b.rate,
                                                a.rate,
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
												CAST(recPrice*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),-1
                                            FROM
                                                #MxBill a
                                            INNER JOIN #GetManPTypeId1 b
                                                ON a.ptypeid=b.typeid
                                            WHERE
                                                nid>(@i-1)*150 AND
                                                nid<=@i*150 AND
                                                BTypeId=@MxBTypeId	
								ELSE
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             NQty,
                                             mqty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeId,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             MUnitID,
                                             CargoID,
                                             UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                baseQty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE baseQty/b.rate
                                                END,
                                                qty,
                                                CAST(baserecPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                                CAST(baserecPrice*baseQty/@Discount/baseqty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty/@Discount/qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                @Discount,
                                                baserecPrice,
                                                baserecPrice,
                                                recPrice,
                                                recPrice,
                                                CAST(CAST(baserecPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/qty AS  NUMERIC(24, 10) ),
                                                CAST( CAST(baserecPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/qty AS  NUMERIC(24, 10) ),
                                                CAST( CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/qty AS  NUMERIC(24, 10) ),
                                                CAST( CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) )/qty AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty/@Discount AS  NUMERIC(24, 10) ),
                                                CAST(recPrice*Qty/@Discount AS  NUMERIC(24, 10) ),
                                                @Tax,
                                                @KTypeId,
                                                @STypeID,
                                                baseunitid,
                                                b.aunitid,
                                                unitid,
                                                @cargoid,
                                                b.rate,
                                                a.rate,
                                                CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),
                                                 CAST(CAST(recPrice*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )-CAST(recPrice*Qty AS  NUMERIC(24, 10) ),-1
                                            FROM
                                                #MxBill a
                                            INNER JOIN #GetManPTypeId1 b
                                                ON a.ptypeid=b.typeid
                                            WHERE
                                                nid>(@i-1)*150 AND
                                                nid<=@i*150 AND
                                                BTypeId=@MxBTypeId	
							END
						ELSE
							BEGIN
								IF @GridType = 1
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             NQty,
                                             mqty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeId,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             MUnitID,
                                             CargoID,
                                             UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                baseQty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE baseQty/b.rate
                                                END,
                                                qty,
                                                0,
                                                0,
                                                0,
                                                0,
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                @Discount,
                                                0,
                                                0,
                                                0,
                                                0,
                                                CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) ),
                                                CAST(CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                CAST(CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                0,
                                                0,
                                                @Tax,
                                                @KTypeId,
                                                @STypeID,
                                                baseunitid,
                                                unitid,
                                                b.aunitid,
                                                @cargoid,
                                                b.rate,
                                               a.rate,
                                                CAST(CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(0*Qty AS  NUMERIC(24, 10) ),
												CAST(CAST(0*(1+@Tax/100) AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(0*Qty AS  NUMERIC(24, 10) ),-1
                                            FROM
                                                #MxBill a
                                            INNER JOIN #GetManPTypeId1 b
                                                ON a.ptypeid=b.typeid
                                            WHERE
                                                nid>(@i-1)*150 AND
                                                nid<=@i*150 AND
                                                BTypeId=@MxBTypeId	
								ELSE IF @GridType = 2
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             NQty,
                                             mqty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeId,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             MUnitID,
                                             CargoID,
                                             UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                baseQty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE baseQty/b.rate
                                                END,
                                                qty,
                                                0,
                                                0,
                                                0,
                                                0,
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                @Discount,
                                                CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                CAST(0*@Discount AS  NUMERIC(24, 10) ),
                                                CAST(CAST(0*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                CAST(CAST(0*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) ),
                                                0,
                                                0,
                                                @Tax,
                                                @KTypeId,
                                                @STypeID,
                                                baseunitid,
                                                b.aunitid,
                                                unitid,
                                                @cargoid,
                                                b.rate,
                                               a.rate,
                                                CAST(CAST(0*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(0*Qty AS  NUMERIC(24, 10) ),
												CAST(CAST(0*@Discount AS  NUMERIC(24, 10) )*Qty AS  NUMERIC(24, 10) )- CAST(0*Qty AS  NUMERIC(24, 10) ),-1
                                            FROM
                                                #MxBill a
                                            INNER JOIN #GetManPTypeId1 b
                                                ON a.ptypeid=b.typeid
                                            WHERE
                                                nid>(@i-1)*150 AND
                                                nid<=@i*150 AND
                                                BTypeId=@MxBTypeId	
								ELSE IF @GridType = 3
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             nqty,
                                             mqty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeId,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             MUnitID,
                                             CargoID,
                                             UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                baseQty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE baseQty/b.rate
                                                END,
                                                qty,
                                                0,
                                                0,
                                                0,
                                                0,
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                @Discount,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                @Tax,
                                                @KTypeId,
                                                @STypeID,
                                                baseunitid,
                                                b.aunitid,
                                                unitid,
                                                @cargoid,
                                                b.rate,
                                                 a.rate,
                                                 CAST(0*Qty AS  NUMERIC(24, 10) )-CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                 CAST(0*Qty AS  NUMERIC(24, 10) )-CAST(0*Qty AS  NUMERIC(24, 10) ),-1
                                            FROM
                                                #MxBill a
                                            INNER JOIN #GetManPTypeId1 b
                                                ON a.ptypeid=b.typeid
                                            WHERE
                                                nid>(@i-1)*150 AND
                                                nid<=@i*150 AND
                                                BTypeId=@MxBTypeId	
								ELSE
                                    INSERT  INTO OrderBill
                                            (BillNumberId,
                                             PTypeId,
                                             Qty,
                                             nqty,
                                             mqty,
                                             Price,
                                             NSalePrice,
                                             MSalePrice,
                                             CurMSalePrice,
                                             Total,
                                             NTotal,
                                             Discount,
                                             DiscountPrice,
                                             NDiscountPrice,
                                             MDiscountPrice,
                                             CurMDiscountPrice,
                                             TaxPrice,
                                             NTaxPrice,
                                             MTaxPrice,
                                             CurMTaxPrice,
                                             TaxTotal,
                                             NTaxTotal,
                                             SaleTotal,
                                             NSaleTotal,
                                             tax,
                                             KTypeId,
                                             STypeID,
                                             UnitID,
                                             NUnitID,
                                             MUnitID,
                                             CargoID,
                                             UnitRate,MUnitRate,TaxMoney,NTaxMoney,GoodsCostPrice)
                                            SELECT
                                                @nBillId,
                                                PTypeId,
                                                baseQty,
                                                CASE WHEN b.rate=0 THEN 0
                                                     ELSE baseQty/b.rate
                                                END,
                                                qty,
                                                0,
                                                0,
                                                0,
                                                0,
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                @Discount,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                @Tax,
                                                @KTypeId,
                                                @STypeID,
                                                baseunitid,
                                                b.aunitid,
                                                unitid,
                                                @cargoid,
                                                b.rate,
                                                a.rate,
                                                CAST(0*Qty AS  NUMERIC(24, 10) )- CAST(0*Qty AS  NUMERIC(24, 10) ),
                                                CAST(0*Qty AS  NUMERIC(24, 10) )- CAST(0*Qty AS  NUMERIC(24, 10) ),-1
                                            FROM
                                                #MxBill a
                                            INNER JOIN #GetManPTypeId1 b
                                                ON a.ptypeid=b.typeid
                                            WHERE
                                                nid>(@i-1)*150 AND
                                                nid<=@i*150 AND
                                                BTypeId=@MxBTypeId	
							END
						
						UPDATE dbo.OrderBill SET ShowOrder=ID WHERE billNumberID=@nBillID
						--修改OrderIndex的TotalMoney，TotalQty
						SELECT @TotalQty =ISNULL(SUM(Qty),0) ,@TotalMoney =ISNULL(SUM(TaxTotal),0)  FROM OrderBill WHERE BillNumberId = @nBillId
						UPDATE OrderIndex SET TotalQty = @TotalQty,TotalMoney = @TotalMoney,Ntotalmoney=@TotalMoney WHERE BillNumberId = @nBillId
					END
		
				--返回单据编号
				IF @VchType IN (300,301)
					BEGIN
						SELECT @TmpBillCode = BillCode FROM OrderIndex WHERE BillNumberId = @nBillId	
						--如果订单有审核，特殊处理
						IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @VchType AND IfUse = 1 AND LEFT(AuditingReason,1)<>1)
							BEGIN
								UPDATE OrderIndex SET IfAudit = 0 WHERE BillNumberId = @nBillId	
							END
					END
				ELSE
					SELECT @TmpBillCode = BillCode FROM BillIndex WHERE BillNumberId = @nBillId	
					
				SET @bCodeList = @bCodeList + ' ' + @TmpBillCode

				IF NOT EXISTS(
					SELECT ConfigNo
					FROM Userconfig
					WHERE ConfigName='BillcodeCreateTime'
					AND Value=2
				)
				BEGIN
					EXEC GP_SaveBillCode_Seed	@nBillId,@NowDate,@VchType,@TmpBillCode
				END

				IF @@error<>0 
					BEGIN
						RETURN -2
					END 
							
		
				SET @i = @i + 1
				
				IF @VchType NOT IN (300,301)
				BEGIN
					-- 自动生成的单据会影响草稿库存
					EXECUTE GP_CopyOrCreateBill_DraftQTY @nBillId,@VchType
				END
				IF @VchType IN (300,301)
				BEGIN
					-- 自动生成的单据会影响订单库存
					EXECUTE GP_Deal_OrderQTY @nBillId,@VchType,'+'
				END
			END

		FETCH NEXT FROM BilCursor INTO @MxBTypeId
	END

SET @rbcode = @bCodeList
               CLOSE BilCursor
				DEALLOCATE BilCursor
RETURN 0	

DROP TABLE #GetManPTypeId,#MxBill,#GetManKTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_QueryStockPtypeAnsi]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_QueryStockPtypeAnsi]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	 作者：谢吉康
	 日期：2010-07-27
	 描述：配件存货智能分析
*/
CREATE PROCEDURE QP_QueryStockPtypeAnsi
    (
      @OperatorId VARCHAR(100) ,	--操作员ID
      @StartDate VARCHAR(20) ,	--开始日期
      @EndDate VARCHAR(20) ,	--截止日期
      @KTypeId VARCHAR(100) ,	--仓库ID
      @Dhkc NUMERIC(18, 0) ,	--订货库存公式对应天数
      @Sxgs NUMERIC(18, 0) ,	--上限公式对应天数
      @Xxgs NUMERIC(18, 0) ,	--下限公式对应天数
      @Xsts NUMERIC(18, 0) ,	--销售天数
      @StypeId VARCHAR(8000) ,
      @displaystop VARCHAR(10)
    )
    --@encode$--
AS 
    SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT

    IF @Re <> 0 
        RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--选择分支机构
    CREATE TABLE #GetSelectSTypeId ( TypeId VARCHAR(100) )
    INSERT  INTO #GetSelectSTypeId
            ( TypeId
            )
            SELECT  typeid
            FROM    F_GetAllManagerBaseTypeId('', 11, @OperatorID)

--商品
    CREATE TABLE #GetManPTypeId ( TypeId VARCHAR(100) )
    INSERT  INTO #GetManPTypeId
            ( TypeId
            )
            SELECT  TypeId
            FROM    F_GetAllManagerBaseTypeId('', 1, @OperatorID)

--仓库
    CREATE TABLE #GetManKTypeId ( TypeId VARCHAR(100) )
    IF @KTypeId = '' 
        BEGIN
            INSERT  INTO #GetManKTypeId
                    ( TypeId
                    )
                    SELECT  s.TypeId
                    FROM    Stock s
                    WHERE   s.SonNum = 0
            INSERT  INTO #GetManKTypeId
                    ( TypeId )
            VALUES  ( '10000' )
        END
    ELSE 
        BEGIN
            INSERT  INTO #GetManKTypeId
                    ( TypeId
                    )
                    SELECT  kbase.TypeId
                    FROM    F_GetAllManagerBaseTypeId(@KTypeId, 4, @OperatorID) kbase
                            INNER JOIN ( SELECT TypeId
                                         FROM   stock
                                         WHERE  STypeID IN (
                                                SELECT  TypeId
                                                FROM    #GetSelectSTypeId )
                                       ) s ON kbase.TypeId = s.typeId
        END
	
    CREATE CLUSTERED INDEX CIX_GetManPTypeID ON #GetManPTypeId(TypeID)	

--销售数据
    CREATE TABLE #XsData
        (
          PTypeId VARCHAR(100) ,
          Qty NUMERIC(24, 10) ,
          RjQty NUMERIC(24, 10) ,
          SxgsQty NUMERIC(24, 10) ,
          XxgsQty NUMERIC(24, 10) ,
          DhkcQty NUMERIC(24, 10) ,
          Total NUMERIC(24, 10) ,
          CostTotal NUMERIC(24, 10)
        )

    INSERT  INTO #XsData
            SELECT  PTypeId ,
                    SUM(-1 * Qty) AS Qty ,
                    CAST(SUM(-1 * Qty) / @Xsts AS NUMERIC(24, 10)) AS RjQty ,
                    CAST(CAST(SUM(-1 * Qty) / @Xsts AS NUMERIC(24, 10))
                    * @Sxgs AS NUMERIC(18, 0)) AS SxgsQty ,
                    CAST(CAST(SUM(-1 * Qty) / @Xsts AS NUMERIC(24, 10))
                    * @Xxgs AS NUMERIC(18, 0)) AS XxgsQty ,
                    CAST(CAST(SUM(-1 * Qty) / @Xsts AS NUMERIC(24, 10))
                    * @Dhkc AS NUMERIC(18, 0)) AS DhkcQty ,
                    SUM(-1 * Total) AS Total ,
                    SUM(-1 * CostTotal) AS CostTotal
            FROM    InOutstocktable
                    INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = InOutStockTable.KTypeId
                    INNER JOIN #GetSelectSTypeId ss ON InOutstocktable.STypeID = ss.TypeId
            WHERE   BillType IN ( 305, 11, 45, 141, 160, 402, 403,12,215,46 )
                    AND BillDate >= @StartDate
                    AND BillDate <= @EndDate
                    AND Audited = 1
            GROUP BY PTypeId	
		
--库存数量		
    CREATE TABLE #KcData
        (
          PTypeId VARCHAR(100) ,
          Qty NUMERIC(24, 10)
        )			

    INSERT  INTO #KCData
            SELECT  PTypeId ,
                    Qty
            FROM    GoodsStocks
                    INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = GoodsStocks.KTypeId

    CREATE TABLE #StockAlarm
        (
          PTypeId VARCHAR(100) ,
          UpLimitQty NUMERIC(24, 10) ,
          DownLimitQty NUMERIC(24, 10) ,
          OrderQty NUMERIC(24, 10)
        )
    IF @KTypeId = '' 
        INSERT  INTO #StockAlarm
                SELECT  PTypeId ,
                        UpLimitQty ,
                        DownLimitQty ,
                        OrderQty
                FROM    StockAlarm
                WHERE   KTypeId = '00000'
    ELSE 
        INSERT  INTO #StockAlarm
                SELECT  PTypeId ,
                        UpLimitQty ,
                        DownLimitQty ,
                        OrderQty
                FROM    StockAlarm
                        INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = StockAlarm.KTypeId

--最后结果
    SELECT  P.TypeId ,
            ISNULL(M.Qty, 0) AS Qty ,
            ISNULL(M.RjQty, 0) AS RjQty ,
            ISNULL(M.UpLimitQty, 0) AS UpLimitQty ,
            ISNULL(M.SxgsQty, 0) AS SxgsQty ,
            ISNULL(M.DownLimitQty, 0) AS DownLimitQty ,
            ISNULL(M.XxgsQty, 0) AS XxgsQty ,
            ISNULL(M.OrderQty, 0) AS OrderQty ,
            ISNULL(M.DhkcQty, 0) AS DhkcQty ,
            ISNULL(M.KcQty, 0) AS KcQty ,
            ISNULL(M.Total, 0) AS Total ,
            ISNULL(M.CostTotal, 0) AS CostTotal ,
            CAST(ISNULL(Total, 0) - ISNULL(CostTotal, 0) AS NUMERIC(24, 10)) AS MaoLi ,
            CASE WHEN CAST(ISNULL(Total, 0) AS NUMERIC(24,10) )  = 0 THEN 0
                 ELSE ( CAST( ( ISNULL(Total, 0) - ISNULL(CostTotal, 0) ) AS NUMERIC(24,10) )
                        / CAST( ISNULL(Total, 0) AS NUMERIC (24,10) )) * 100
            END AS MaoLiLv
    FROM    F_GetManPTypeAll(@OperatorID) p
            LEFT JOIN ( SELECT  R.PTypeId ,
                                SUM(R.Qty) AS Qty ,
                                SUM(R.RjQty) AS RjQty ,
                                SUM(R.SxgsQty) AS SxgsQty ,
                                SUM(R.XxgsQty) AS XxgsQty ,
                                SUM(R.DhkcQty) AS DhkcQty ,
                                SUM(R.KcQty) AS KcQty ,
                                SUM(R.Total) AS Total ,
                                SUM(R.CostTotal) AS CostTotal ,
                                SUM(R.UpLimitQty) AS UpLimitQty ,
                                SUM(R.DownLimitQty) AS DownLimitQty ,
                                SUM(R.OrderQty) AS OrderQty
                        FROM    ( SELECT    PTypeId ,
                                            Qty ,
                                            RjQty ,
                                            SxgsQty ,
                                            XxgsQty ,
                                            DhkcQty ,
                                            0 AS KcQty ,
                                            Total ,
                                            CostTotal ,
                                            0 AS UpLimitQty ,
                                            0 AS DownLimitQty ,
                                            0 AS OrderQty
                                  FROM      #XsData
                                  UNION ALL
                                  SELECT    PTypeId ,
                                            0 AS Qty ,
                                            0 AS RjQty ,
                                            0 AS SxgsQty ,
                                            0 AS XxgsQty ,
                                            0 AS DhkcQty ,
                                            Qty AS KcQty ,
                                            0 AS Total ,
                                            0 AS CostTotal ,
                                            0 AS UpLimitQty ,
                                            0 AS DownLimitQty ,
                                            0 AS OrderQty
                                  FROM      #KcData
                                  UNION ALL
                                  SELECT    PTypeId ,
                                            0 AS Qty ,
                                            0 AS RjQty ,
                                            0 AS SxgsQty ,
                                            0 AS XxgsQty ,
                                            0 AS DhkcQty ,
                                            0 AS KcQty ,
                                            0 AS Total ,
                                            0 AS CostTotal ,
                                            UpLimitQty ,
                                            DownLimitQty ,
                                            OrderQty
                                  FROM      #StockAlarm
                                ) R
                                INNER JOIN #GetManPTypeId M ON M.TypeId = R.PTypeId
                        GROUP BY R.PTypeId
                      ) M ON P.typeid = M.PTypeID
    WHERE   P.SonNum = 0
            AND p.IsService = 0
            AND p.iscombinationproduct = 0
            AND p.deleted LIKE '%' + @displaystop + '%'            
    ORDER BY P.UserCode	


    DROP TABLE #XsData,#KcData,#GetManPTypeId,#GetManKTypeId,#StockAlarm,#GetSelectSTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO








if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryStockPtypeAnsiAutoData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryStockPtypeAnsiAutoData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	 作者：谢吉康
	 日期：2010-07-27
	 描述：配件存货智能分析[生成报警数据]
*/
CREATE PROCEDURE QP_QueryStockPtypeAnsiAutoData
(
	@OperatorId		VARCHAR(100),	--操作员ID
	@StartDate		VARCHAR(20),	--开始日期
	@EndDate		VARCHAR(20),	--截止日期
	@KTypeId		VARCHAR(100),	--仓库ID
	@Dhkc			NUMERIC(18,0),	--订货库存公式对应天数
	@Sxgs			NUMERIC(18,0),	--上限公式对应天数
	@Xxgs			NUMERIC(18,0),	--下限公式对应天数
	@Xsts			NUMERIC(18,0),	--销售天数
	@PTypeId		VARCHAR(8000),	--商品ID列表
	@nType			VARCHAR(10),		--报警类型 O.订货库存 U.上限报警 D.下限报警
	@StypeId		VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId('',11,@OperatorID)

	
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @KTypeId = ''
	BEGIN
		INSERT INTO #GetManKTypeId(TypeId)
		SELECT s.TypeId FROM Stock s 
						INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
						WHERE s.Deleted = 0 AND s.SonNum = 0
		INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')
	END
ELSE
	BEGIN
		INSERT INTO #GetManKTypeId(TypeId) 
		SELECT kbase.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) kbase
						INNER JOIN (SELECT st.typeid FROM stock st INNER JOIN  #GetSelectSTypeId ssk ON st.STypeID=ssk.TypeId) ss On kbase.TypeId=ss.typeId	
	END

--销售数据
CREATE TABLE #XsData
(
	PTypeId		VARCHAR(100),
	Qty			 NUMERIC(24, 10) ,
	RjQty		 NUMERIC(24, 10) ,
	SxgsQty		 NUMERIC(24, 10) ,
	XxgsQty		 NUMERIC(24, 10) ,
	DhkcQty		 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) 
)

INSERT INTO #XsData
SELECT	PTypeId,
		SUM(-1*Qty) AS Qty,
		CAST(SUM(-1*Qty)/@Xsts AS  NUMERIC(24, 10) ) AS RjQty,
		CAST(CAST(SUM(-1*Qty)/@Xsts AS  NUMERIC(24, 10) )*@Sxgs AS NUMERIC(18,0)) AS SxgsQty,
		CAST(CAST(SUM(-1*Qty)/@Xsts AS  NUMERIC(24, 10) )*@Xxgs AS NUMERIC(18,0)) AS XxgsQty,
		CAST(CAST(SUM(-1*Qty)/@Xsts AS  NUMERIC(24, 10) )*@Dhkc AS NUMERIC(18,0)) AS DhkcQty,
		SUM(-1*Total) AS Total,
		SUM(-1*CostTotal) AS CostTotal
FROM	InOutstocktable
INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = InOutStockTable.KTypeId
INNER JOIN #GetSelectSTypeId ss ON InOutstocktable.STypeID=ss.TypeId
WHERE	BillDate >= @StartDate
		AND BillDate <= @EndDate
		AND BillType IN (305,11,45,141,160)
		AND Audited = 1	 
GROUP BY PTypeId		
		
--库存数量		
CREATE TABLE #KcData
(
	PTypeId		VARCHAR(100),
	Qty			 NUMERIC(24, 10) 
)			

INSERT INTO #KCData
SELECT	PTypeId,
		SUM(Qty) AS Qty
FROM 	GoodsStocks
INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = GoodsStocks.KTypeId
GROUP BY PTypeId

CREATE TABLE #StockAlarm
(
	PTypeId			VARCHAR(100),
	UpLimitQty		 NUMERIC(24, 10) ,
	DownLimitQty	 NUMERIC(24, 10) ,
	OrderQty		 NUMERIC(24, 10) 
)
IF @KTypeId = ''
	INSERT INTO #StockAlarm
	SELECT	PTypeId,
			UpLimitQty,
			DownLimitQty,
			OrderQty
	FROM	StockAlarm
	WHERE 	KTypeId = '00000'
ELSE
	INSERT INTO #StockAlarm
	SELECT	PTypeId,
			UpLimitQty,
			DownLimitQty,
			OrderQty
	FROM	StockAlarm
	INNER JOIN #GetManKTypeId ON #GetManKTypeId.TypeId = StockAlarm.KTypeId

--最后结果
CREATE TABLE #Result
(
	PTypeId			VARCHAR(100),
	KTypeId			VARCHAR(100),
	Qty				 NUMERIC(24, 10) ,
	RjQty			 NUMERIC(24, 10) ,
	SxgsQty			 NUMERIC(24, 10) ,
	XxgsQty			 NUMERIC(24, 10) ,
	DhkcQty			 NUMERIC(24, 10) ,
	KcQty			 NUMERIC(24, 10) ,
	Total			 NUMERIC(24, 10) ,
	CostTotal		 NUMERIC(24, 10) ,
	UpLimitQty		 NUMERIC(24, 10) ,
	DownLimitQty 	 NUMERIC(24, 10) ,
	OrderQty		 NUMERIC(24, 10) 
)
INSERT INTO #Result
SELECT	R.PTypeId,
		CASE WHEN @KTypeId = '' THEN '00000' ELSE @KTypeId END AS KTypeId,
		SUM(R.Qty) AS Qty,
		SUM(R.RjQty) AS RjQty,
		SUM(R.SxgsQty) AS SxgsQty,
		SUM(R.XxgsQty) AS XxgsQty,
		SUM(R.DhkcQty) AS DhkcQty,
		SUM(R.KcQty) AS KcQty,
		SUM(R.Total) AS KcQty,
		SUM(R.CostTotal) AS CostTotal,
		SUM(R.UpLimitQty) AS UpLimitQty,
		SUM(R.DownLimitQty) AS DownLimitQty,
		SUM(R.OrderQty) AS OrderQty
FROM	(
			SELECT	PTypeId,
					Qty,
					RjQty,
					SxgsQty,
					XxgsQty,
					DhkcQty,
					0 AS KcQty,
					Total,
					CostTotal,
					0 AS UpLimitQty,
					0 AS DownLimitQty,
					0 AS OrderQty
			FROM 	#XsData
			UNION ALL
			SELECT	PTypeId,
					0 AS Qty,
					0 AS RjQty,
					0 AS SxgsQty,
					0 AS XxgsQty,
					0 AS DhkcQty,
					Qty AS KcQty,
					0 AS Total,
					0 AS CostTotal,
					0 AS UpLimitQty,
					0 AS DownLimitQty,
					0 AS OrderQty
			FROM 	#KcData
			UNION ALL
			SELECT	PTypeId,
					0 AS Qty,
					0 AS RjQty,
					0 AS SxgsQty,
					0 AS XxgsQty,
					0 AS DhkcQty,
					0 AS KcQty,
					0 AS Total,
					0 AS CostTotal,
					UpLimitQty,
					DownLimitQty,
					OrderQty
			FROM	#StockAlarm
) R INNER JOIN #GetManPTypeId M ON M.TypeId = R.PTypeId
GROUP BY R.PTypeId
	
--开始生成数据
DECLARE @SQL VARCHAR(8000)
SET @SQL = 'DECLARE @RPTypeId	VARCHAR(100),
					@RKTypeId	VARCHAR(100),
					@RDhkcQty	 NUMERIC(24, 10) ,
					@RSxgsQty	 NUMERIC(24, 10) ,
					@RXxgsQty	 NUMERIC(24, 10) 
					
			DECLARE Tmp_Cursor CURSOR FOR '
			
IF @nType = 'O'
	SET @SQL = @SQL + 'SELECT PTypeId,KTypeId,DhkcQty,UpLimitQty AS SxgsQty,DownLimitQty AS XxgsQty FROM #Result'
ELSE IF @nType = 'U'	
	SET @SQL = @SQL + 'SELECT PTypeId,KTypeId,OrderQty AS DhkcQty,SxgsQty,DownLimitQty AS XxgsQty FROM #Result '
ELSE
	SET @SQL = @SQL + 'SELECT PTypeId,KTypeId,OrderQty AS DhkcQty,UpLimitQty AS SxgsQty,XxgsQty FROM #Result '	

SET @SQL = @SQL + '				
			OPEN Tmp_Cursor
			
			FETCH NEXT FROM Tmp_Cursor INTO @RPTypeId,@RKTypeId,@RDhkcQty,@RSxgsQty,@RXxgsQty
			
			WHILE @@FETCH_STATUS = 0
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM StockAlarm WHERE PTypeId = @RPTypeId AND KTypeId = @RKTypeId)
						UPDATE	StockAlarm
						SET		UpLimitQty 		= @RSxgsQty,
								DownLimitQty 	= @RXxgsQty,
								OrderQty		= @RDhkcQty
						WHERE	PTypeId			= @RPTypeId
								AND KTypeId 	= @RKTypeId
					ELSE
						INSERT INTO StockAlarm(PTypeId,KTypeId,UpLimitQty,DownLimitQty,OrderQty)
						VALUES(@RPTypeId,@RKTypeId,@RSxgsQty,@RXxgsQty,@RDhkcQty)
						
					FETCH NEXT FROM Tmp_Cursor INTO @RPTypeId,@RKTypeId,@RDhkcQty,@RSxgsQty,@RXxgsQty
				END
				
			CLOSE Tmp_Cursor
			DEALLOCATE Tmp_Cursor'
--PRINT(@SQL)			
EXEC(@SQL)

RETURN 0

DROP TABLE #XsData,#KcData,#Result,#GetManPTypeId,#GetManKTypeId,#StockAlarm,#GetSelectSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryTransport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryTransport]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：郑红霞
	日期：2011-11-22
	描述：运输方式定义查询
*/
CREATE PROCEDURE QP_QueryTransport
(
	@OperatorId		varchar(100)		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--往来单位
CREATE TABLE #Btype (TypeID varchar(50))
INSERT INTO #Btype (TypeID) VALUES ('')
INSERT INTO #Btype select typeid from F_GetAllManagerBaseTypeId('',2,@OperatorID)

SELECT a.ID,
       a.fullname,
       a.usercode,
       a.pycode,
       a.btypeid,
       a.comment
       FROM QP_Transport a INNER JOIN #Btype b ON b.typeId = a.btypeid ORDER BY   a.usercode ASC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_QueryVkInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_QueryVkInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-10
	描述：虚拟库存询价、历史采购订单
	SELECT * FROM OrderIndex
*/
CREATE PROCEDURE Qp_QueryVkInfo
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@PTypeId		VARCHAR(8000),
	@OrderType		VARCHAR(100),
	@BTypeId		VARCHAR(8000),
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM PType WHERE SonNum = 0 AND TypeId LIKE @PTypeId + '%'

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)
IF @BTypeId = ''
	BEGIN
		INSERT INTO #GetManBTypeId(TypeId)VALUES('')
	END

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)
INSERT INTO #GetManKTypeId(TypeId)VALUES('')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

DECLARE @SQL VARCHAR(8000)

SET @SQL = 'SELECT	a.BillNumberId,
					a.BillDate,
					a.BillCode,
					a.BillType,
					a.ReachDate,
					--CASE
					--	WHEN a.OrderState = 0 THEN ''未完成订单''
					--	WHEN a.OrderState = 1 THEN ''已完成订单''
					--	WHEN a.BillOver = 1   THEN ''中止订单''
					--	ELSE ''全部订单''
					--END AS OrderType,
					CASE WHEN	a.OrderState = 1 THEN ''已完成'' WHEN a.OrderState = 0 THEN ''未完成订单''
					WHEN	BI1.ReachQty=0 AND BI.BID IS NULL THEN ''未引用''
					ELSE ''已引用未完成'' END  AS OrderType,
					a.DealBTypeId,
					(select usercode from btype where typeid=a.DealBTypeId) as dusercode,
					(select fullname from btype where typeid=a.DealBTypeId) as dfullname,
					a.STypeId,
					SUM(I.Qty) AS Qty,
					ABS(I.DiscountPrice) AS Price,
					SUM(I.Total) AS Total,
					ABS(I.TaxPrice) AS TaxPrice,
					SUM(I.TaxTotal) AS TaxTotal,
					I.Comment,
					I.goodsnumber,
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=I.ItemId,
					itemname= CASE WHEN I.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= I.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= I.ItemId ) END,
					iscombined=I.IsCombined
			FROM 	OrderIndex a
			INNER JOIN OrderBill I ON I.BillNumberId = a.BillNumberId
			INNER JOIN #GetManKTypeId K ON I.KTypeId = K.TypeId
			INNER JOIN #GetManPTypeId P ON P.TypeId = I.PTypeId
			INNER JOIN dbo.PType pt ON I.PTypeId = pt.TypeID 
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = a.DealBTypeId
			INNER JOIN #GetManSTypeId S ON S.TypeId = a.STypeId'
SET @SQL = @SQL + '
	INNER JOIN (
				SELECT a.BillNumberID,max(a.BID) as BID
				FROM 
				(				
					SELECT distinct detail.BillNumberID,(BB.orderid) as BID
					FROM OrderBill detail 
					LEFT JOIN 
					(
						SELECT bb.orderid from buybill bb --ON detail.OrderID=bb.orderid
						INNER JOIN BillIndex bi ON bb.billnumberid=bi.billnumberid and bi.redword=0--排除红冲单据
					) bb ON detail.OrderID=bb.orderid
					INNER JOIN PType p ON detail.PtypeID=p.typeid'
IF @PTypeId <> '' SET @SQL = @SQL + ' WHERE detail.PTypeID = ''' + @PTypeId + ''''
SET @SQL = @SQL + '
				)a GROUP BY A.billNumberID
				) bi ON i.billNumberId=BI.billNumberID
	INNER JOIN (								
				SELECT B.billNumberID,
					   sum(b.WaitQty) AS WaitQty,
					   sum(b.Qty) AS Qty,
					   sum(b.ReachQty) AS ReachQty 
				FROM(								
					SELECT detail.BillNumberID,
						   detail.WaitQty,
						   detail.Qty,
						   detail.ReachQty
					FROM OrderBill detail
					) b GROUP BY B.billNumberID
				) BI1 ON i.billnumberid=BI1.billnumberid '

SET @SQL = @SQL + 'WHERE	a.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND a.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
					AND a.BillType IN (301) '

IF(@OrderType=4)  --未引用订单
	SET @SQL+= ' AND BI1.ReachQty=0 AND BI.BID IS NULL '
ELSE
	SET @SQL+= CASE @OrderType WHEN 1 THEN ' AND (a.OrderState = 0 AND BI.BID IS NOT NULL)' --未完成订单
								WHEN 2 THEN ' AND a.OrderState = 1'  --已完成订单
								WHEN 5 THEN ' AND a.OrderState = 0'  --未完成订单
								ELSE ' AND (a.OrderState = 1 OR a.OrderState = 0)' 
				END
--IF @OrderType = '0'
--	SET @SQL = @SQL + ' AND 1 = 1 '
--ELSE IF @OrderType = '1'
--	SET @SQL = @SQL + ' AND a.OrderState = 0 '
--ELSE IF @OrderType = '2'
--	SET @SQL = @SQL + ' AND a.OrderState = 1 '
--ELSE
--	SET @SQL = @SQL + ' AND a.BillOver = 1 '
	

SET @SQL = @SQL + '
			GROUP BY a.BillNumberId,
  					 a.BillDate,
					 a.BillCode,
					 a.BillType,
					 a.ReachDate,
					 a.BillOver,
					 a.OrderState,
					 a.BTypeId,
					 a.DealBTypeId,
					 a.STypeId,
					 I.DiscountPrice,
					 I.TaxPrice,
					 I.Comment,
					 I.goodsnumber,
					 pt.customitemid,
					 pt.customitemfrom,
					 pt.customitemname,
					 pt.customitemrefid,
					 I.ItemId,
					 I.IsCombined,BI1.ReachQty,BI.BID
			ORDER BY a.BillDate DESC'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManPTypeId,#GetManBTypeId,#GetManKTypeId,#GetManSTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_QueryWorkGroupList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_QueryWorkGroupList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：czc
	日期：2010-9-03
	描述：人员组
*/
CREATE PROCEDURE QP_QueryWorkGroupList
(
	@OperatorId		varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
--DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
--            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
--EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
--
--IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

	SELECT * FROM dbo.QP_WorkGroup ORDER BY UserCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Recount_DraftQty]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Recount_DraftQty]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：从算草稿库存数据
	返回结果：
	作    者：施训果
	创建时间：2017-03-03
	修改历史：
	
*/
CREATE   PROCEDURE QP_Recount_DraftQty 

AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF


--将主表的单据状态与明细表integralexchangebill单据状态修改为一致
UPDATE integralexchangebill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM integralexchangebill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)

--将主表的单据状态与明细表BuyBill单据状态修改为一致
UPDATE BuyBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM BuyBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)

--将主表的单据状态与明细表单据状态修改为一致
UPDATE BuyBackBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM BuyBackBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)

--将主表的单据状态与明细表单据状态修改为一致
UPDATE BuyGoodsExchangeBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM BuyGoodsExchangeBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)

--将主表的单据状态与明细表单据状态修改为一致
UPDATE SaleGoodsExchangeBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM SaleGoodsExchangeBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE MoveBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM MoveBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE gatheringBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM gatheringBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE AccountCredence SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM AccountCredence AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE AdDebtBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM AdDebtBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE AdPriceBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM AdPriceBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE Advantage SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM Advantage AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE AppraisalBackBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM AppraisalBackBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE AppraisalBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM AppraisalBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE AskPriceBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM AskPriceBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE AssetIncDecBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM AssetIncDecBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE CapitalTransfer_Bill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM CapitalTransfer_Bill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE chargeoffbill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM chargeoffbill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE CommissionBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM CommissionBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE GiveBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM GiveBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE GivemeBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM GivemeBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE LoseBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=I.ktypeid,ifWX=I.ifWX
FROM LoseBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR i.ktypeid!=b.ktypeid OR I.ifWX!=B.ifWX)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE MoneyBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM MoneyBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE MoveBjBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM MoveBjBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE MoveMoneyBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM MoveMoneyBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE OtherInOutBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM OtherInOutBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE overflowBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=I.ktypeid,ifWX=I.ifWX
FROM overflowBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR I.ktypeid!=b.ktypeid OR I.ifWX!=B.ifWX)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE PayBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM PayBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE PreBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM PreBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE PriceProtectBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM PriceProtectBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE PT_Combin_SaleBackBillDetail SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM PT_Combin_SaleBackBillDetail AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE PT_Combin_SaleBillDetail SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM PT_Combin_SaleBillDetail AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE QuotePriceBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM QuotePriceBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE RetailBackBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=I.ktypeid
FROM RetailBackBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR i.ktypeid!=b.ktypeid)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE retailBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=I.ktypeid
FROM retailBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR i.ktypeid!=b.ktypeid)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE SaleBackBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM SaleBackBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE SaleBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM SaleBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE SendBackBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM SendBackBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE SendBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM SendBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE ShareSourceBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM ShareSourceBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE STypeMoveBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM STypeMoveBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE Transportbill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM Transportbill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE VipAddMoneyBatchBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM VipAddMoneyBatchBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_Bill_Call SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM wx_Bill_Call AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_bill_in SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=I.ktypeid
FROM wx_bill_in AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR i.ktypeid!=b.ktypeid)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_bill_send SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM wx_bill_send AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_bill_sendback SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM wx_bill_sendback AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_Bill_Self SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=i.ktypeid
FROM wx_Bill_Self AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR i.ktypeid!=b.ktypeid)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_Bill_Replace SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=i.ktypeid
FROM wx_Bill_Replace AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR i.ktypeid!=b.ktypeid)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_Bill_Out SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=I.ktypeid
FROM wx_Bill_Out AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR i.ktypeid!=b.ktypeid)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_bill_move SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM wx_bill_move AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_bill_jiejian SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM wx_bill_jiejian AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_Bill_Goto SET DraftFlag=I.draft,IsIniFlag=I.IsIni,ktypeid=I.ktypeid
FROM wx_Bill_Goto AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag OR i.ktypeid!=b.ktypeid)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE wx_bill_getback SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM wx_bill_getback AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE Qp_PickingBackBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM Qp_PickingBackBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE DisassembleBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM DisassembleBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE QP_QuickRepairBill_PType SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM QP_QuickRepairBill_PType AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE Qp_SuccorBill_PType SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM Qp_SuccorBill_PType AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE Qp_PickingBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM Qp_PickingBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE DepBill SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM DepBill AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)


--将主表的单据状态与明细表单据状态修改为一致
UPDATE FixedAssetsDetails SET DraftFlag=I.draft,IsIniFlag=I.IsIni
FROM FixedAssetsDetails AS B,BillIndex I
WHERE b.BillNumberId=i.BillNumberId AND (i.draft!=b.DraftFlag OR i.IsIni!=b.IsIniFlag)

--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'

----------------------------------------------------------重算草稿库存数据到草稿库存数据表 start------------------------------------------------------------
TRUNCATE TABLE GoodsStocks_Draft
INSERT INTO GoodsStocks_Draft
(
	PTypeId,
	KtypeID,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	CargoID,
	ItemID,
	IsCombined,
	GoodsCostPrice,
	RQty,
	CQty,
	Qty
)
SELECT	
	B.PTypeId,
	B.KtypeID,
	B.GoodsNumber,
	B.ProduceDate,
	B.ValidDate,
	B.CargoID,
	B.ItemID,
	B.IsCombined,
	B.GoodsCostPrice,
	SUM(ISNULL(B.RQty,0)) AS RQty,
	SUM(ISNULL(B.CQty,0)) AS CQty,
	SUM(ISNULL(B.Qty,0)) AS Qty
FROM	
(			
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM BuyBill S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM SaleBackBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM RetailBackBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM BuyGoodsExchangeBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND InOrOut = 'I'
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM SaleGoodsExchangeBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND InOrOut = 'I'
	UNION ALL
	SELECT S.PTypeId,S.KTypeId2,S.GoodsNumber,ProduceDate,ValidDate,InCargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM MoveBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeId2,S.GoodsNumber,ProduceDate,ValidDate,InCargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM MoveBjBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM DisassembleBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND InOrOut = 'I'
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM OverflowBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM CommissionBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND [Type] = 144 
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM CommissionBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND [Type] = 142
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM GiveMeBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM Wx_Bill_OUT  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeId2,S.GoodsNumber,ProduceDate,ValidDate,InCargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM STypeMoveBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND B.BillType = 188 
	UNION ALL 
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM OtherInOutBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND B.BillType = 201
	UNION ALL --暂估入库单
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM AppraisalBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL --发出商品退货单
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM SendBackBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL --组合品销售退货
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,Qty AS RQty,0 AS CQty,Qty AS Qty FROM PT_Combin_SalebackBillDetail  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL --门店配送退货单
	SELECT S.PTypeId,s.inktypeid,S.GoodsNumber,ProduceDate,ValidDate,s.inCargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,s.Qty AS RQty,0 AS CQty,s.Qty AS Qty FROM dbo.DeliveryBackBill  S,dbo.PosAllotApplyBillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1  AND B.IsIni=0 
	
	
	--出库部分
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM BuyBackBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM SaleBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM BuyGoodsExchangeBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND InOrOut = 'O' 
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM SaleGoodsExchangeBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND InOrOut = 'O'
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,OutCargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM MoveBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,OutCargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM MoveBjBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM DisassembleBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND InOrOut = 'O'
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM LoseBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM CommissionBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND [Type] = 146
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM CommissionBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND [Type] = 140 
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM RetailBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0	
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM GiveBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0	
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM Wx_Bill_SELF  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND InOrOut = 'O' AND WxProperty = 0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM Wx_Bill_REPLACE  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND WxProperty = 0 	
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM Wx_Bill_GoTo  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND InOrOut = 'O' AND WxProperty = 0
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM Wx_Bill_IN  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0	
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM IntegralExchangeBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0	
	UNION ALL
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,OutCargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM STypeMoveBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND B.BillType = 187
	UNION ALL 
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM OtherInOutBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0 AND B.BillType = 202
	UNION ALL --暂估退货单
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM AppraisalBackBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL--发出商品出库单  
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM SendBill  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL--组合品销售  
	SELECT S.PTypeId,S.KTypeID,S.GoodsNumber,ProduceDate,ValidDate,CargoID,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,Qty AS CQty,-Qty AS Qty FROM dbo.PT_Combin_SaleBillDetail  S,BillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.ifwx=0 AND B.IsIni=0 AND B.AdPriceType=0
	UNION ALL--门店配送单  
	SELECT S.PTypeId,S.ktypeidout,S.GoodsNumber,ProduceDate,ValidDate,s.CargoIDout,ISNULL(ItemID,0) AS ItemID,ISNULL(IsCombined,0) AS IsCombined,CASE WHEN @COST='3' THEN ISNULL(GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,0 AS RQty,s.Qty AS CQty,-s.Qty AS Qty FROM dbo.DeliveryBill  S,dbo.PosAllotApplyBillIndex B WHERE B.BillNumberId = S.BillNumberId AND B.draft=1 AND B.IsIni=0 

) AS B 
GROUP BY B.PTypeId,B.KTypeID,B.GoodsNumber,B.ProduceDate,B.ValidDate,B.CargoID,B.ItemID,B.IsCombined,B.GoodsCostPrice
----------------------------------------------------------重算草稿库存数据到草稿库存数据表   end------------------------------------------------------------
--删除各维度数量为0的商品
DELETE dbo.GoodsStocks_Draft WHERE CQty=0 AND RQty=0 AND Qty=0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[QP_Recount_IniGoodsStocksQty]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[QP_Recount_IniGoodsStocksQty]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

	
/*
	功能说明：重算期初库存状况数量核算表
	返回结果：
	作    者：冯波
	创建时间：2017-009-12：
	
*/
CREATE PROCEDURE QP_Recount_IniGoodsStocksQty 

AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--先写货位变成默认货位的
DECLARE
	@intProduceDate INT,
	@intValidDate	INT,
	@intGoodsNumber	INT

SELECT @intProduceDate=Value FROM Userconfig WHERE ConfigName='ifuseproducedate'--物流单据商品采用生产日期
SELECT @intGoodsNumber=Value FROM Userconfig WHERE ConfigName='ifusegoodsnumber'--物流单据商品采用批号
SELECT @intValidDate=Value FROM Userconfig WHERE ConfigName='ifusevaliddate'--物流单据商品采用效期至


UPDATE dbo.Ini_GOODSSTOCKS_QTY
SET CargoID=b.CargoID,ProduceDate=CASE @intProduceDate WHEN 0 THEN '' ELSE Ini_GOODSSTOCKS_QTY.ProduceDate END,
ValidDate=CASE @intValidDate WHEN 0 THEN '' ELSE Ini_GOODSSTOCKS_QTY.ValidDate END,
GoodsNumber=CASE @intGoodsNumber WHEN 0 THEN '' ELSE Ini_GOODSSTOCKS_QTY.GoodsNumber END
FROM dbo.CargoType b
WHERE Ini_GOODSSTOCKS_QTY.KTypeID=b.KtypeID
AND b.IsDefault=1


SELECT PTypeID,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
SUM(Qty) Qty,SUM(NQty) NQty,SUM(LockNumber) LockNumber,GoodsCostPrice
INTO #TEMPINIGOODSSTOCKS_QTY
FROM dbo.Ini_GOODSSTOCKS_QTY
GROUP BY PTypeID,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
GoodsCostPrice

TRUNCATE TABLE Ini_GOODSSTOCKS_QTY

INSERT Ini_GOODSSTOCKS_QTY(PTypeID,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
Qty,NQty,GoodsCostPrice,LockNumber)
SELECT PTypeID,KTypeID,CargoID,ItemID,Iscombined,GoodsNumber,ProduceDate,ValidDate,
Qty,NQty,GoodsCostPrice,LockNumber
FROM #TEMPINIGOODSSTOCKS_QTY

DROP TABLE #TEMPINIGOODSSTOCKS_QTY


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Recount_LimitQty]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Recount_LimitQty]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理LimitSaleQty/LimitBuyQty 
	
*/
CREATE   PROCEDURE QP_Recount_LimitQty 
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT
)

AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

-- 设置明细表表名
DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(100),	--明细表名
		@IndexName VARCHAR(50),		--主表名
		@LimitOrderReferQtyName VARCHAR(50)='LimitSaleQty',
		@OrderTableName VARCHAR(100)='OrderBill',	--订单明细表名
		@Groupby varchar(100)='PTypeId',
		@OrderBillType VARCHAR(50)='300',
		@SQLWhere VARCHAR(100)=''


IF @BillType=34 OR @BillType=144 OR @BillType=400
BEGIN
	SET @LimitOrderReferQtyName='LimitBuyQty'
	SET @OrderBillType='301'
END

IF @BillType=12
BEGIN
	SET @OrderTableName='PT_Combin_OrderBillDetail'
	SET @OrderBillType='313'
END
		
SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType

--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	IF @BillType=34 OR @BillType=144 OR @BillType=400
	BEGIN
		SET @Groupby='DiscountPrice'
	END
	ELSE
	BEGIN
		SET @Groupby='GoodsCostPrice'
	END
	SET @SQLWhere=' AND A.'+@Groupby+'=C.GoodsCostPrice '
END

CREATE TABLE #TEMP(	
		[PtypeId]	VARCHAR(50) NOT NULL,	
		[KtypeId]	VARCHAR(50) NOT NULL,		
		[GoodsNumber]	VARCHAR(100) NOT NULL ,	
		[ProduceDate]	VARCHAR(50) NOT NULL ,
		[ValidDate]	VARCHAR(50) NOT NULL ,
		[CargoID]	INT NOT NULL ,
		[ItemID]	INT NOT NULL ,
		[IsCombined]	BIT NOT NULL ,	
		GoodsCostPrice	  NUMERIC(24,10) NOT NULL 
	)
SET @SQL = '
		INSERT INTO #TEMP
				SELECT DISTINCT B.PTypeId,B.KTypeID,ISNULL(B.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(B.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(B.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
						ISNULL(B.CargoID,0) AS CargoID,ISNULL(B.ItemID,0) AS ItemID,ISNULL(B.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(B.'+@Groupby+',0) ELSE -1 END AS GoodsCostPrice
				FROM ' + @TableName + ' A
				LEFT JOIN '+@OrderTableName+' B ON B.ORDERID=A.ORDERID 
				WHERE A.BillNumberId = ' + @BillNumberID + ' AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'''' AND B.CargoID<>0'
EXEC (@SQL)

----------------------------------------------------------处理LimitSaleQty/LimitBuyQty start------------------------------------------------------------
IF @BillType=34 OR @BillType=144 OR @BillType=400
BEGIN
	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
				SUM(ISNULL((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN (A.ReachQty+A.WaitQty) ELSE A.qty END),0)) AS QTY 
				FROM '+@OrderTableName+' A
				INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype='+@OrderBillType+'
				INNER JOIN #TEMP C
				ON A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND isnull(A.GoodsNumber,'''')=C.GoodsNumber AND isnull( A.ProduceDate,'''')=C.ProduceDate 
				  AND isnull(A.ValidDate,'''')=C.ValidDate AND isnull(A.CargoID,0)=C.CargoID AND isnull(A.ItemID,0)=C.ItemID AND isnull(A.IsCombined,0)=C.IsCombined '+@SQLWhere+'
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@LimitOrderReferQtyName+'=S.QTY;'
	EXEC (@SQL)
END

ELSE--销售
BEGIN
	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
						SUM(ISNULL(C.QTY,0)) AS QTY
				FROM
				(SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
				SUM((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN (A.ReachQty+A.WaitQty) ELSE A.qty END)) AS QTY 
				FROM OrderBill A
				INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype =300
				INNER JOIN #TEMP C
				ON A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND isnull(A.GoodsNumber,'''')=C.GoodsNumber AND isnull(A.ProduceDate,'''')=C.ProduceDate 
					  AND isnull(A.ValidDate,'''')=C.ValidDate AND isnull(A.CargoID,0)=C.CargoID AND isnull(A.ItemID,0)=C.ItemID AND isnull(A.IsCombined,0)=C.IsCombined '+@SQLWhere+'
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
				
				UNION ALL
				
				SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
				SUM((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN (A.ReachQty+A.WaitQty) ELSE A.qty END)) AS QTY 
				FROM PT_Combin_OrderBillDetail A
				INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype =313
				INNER JOIN #TEMP C
				ON A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND isnull( A.GoodsNumber,'''')=C.GoodsNumber AND isnull(A.ProduceDate,'''')=C.ProduceDate 
					  AND isnull(A.ValidDate,'''')=C.ValidDate AND isnull(A.CargoID,0)=C.CargoID AND isnull(A.ItemID,0)=C.ItemID AND isnull(A.IsCombined,0)=C.IsCombined '+@SQLWhere+'
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice) C
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@LimitOrderReferQtyName+'=S.QTY;'
	EXEC (@SQL)
END
----------------------------------------------------------处理LimitSaleQty/LimitBuyQty  end------------------------------------------------------------
DROP TABLE #TEMP

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Recount_LimitQty_BuyBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Recount_LimitQty_BuyBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：处理LimitBuyQty，用于销售自动生成采购入库单的处理
	
*/
CREATE   PROCEDURE QP_Recount_LimitQty_BuyBill
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT
)

AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

-- 设置明细表表名
DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(100),	--明细表名
		@IndexName VARCHAR(50),		--主表名
		@LimitOrderReferQtyName VARCHAR(50)='LimitSaleQty',
		@OrderTableName VARCHAR(100)='OrderBill',	--订单明细表名
		@Groupby varchar(100)='PTypeId',
		@OrderBillType VARCHAR(50)='300',
		@SQLWhere VARCHAR(100)=''


IF @BillType=34
BEGIN
	SET @LimitOrderReferQtyName='LimitBuyQty'
	SET @OrderBillType='301'
END
		
SELECT @TableName=detailTable,@IndexName=IndexTable FROM dbo.BillName WHERE Billtype=@BillType

--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	IF @BillType=34
	BEGIN
		SET @Groupby='DiscountPrice'
	END
	SET @SQLWhere=' AND ISNULL(A.'+@Groupby+',0)=C.GoodsCostPrice '
END

CREATE TABLE #TEMP
(	
	[OrderId]		INT	NOT NULL,
	[PtypeId]		VARCHAR(50) NOT NULL,	
	[KtypeId]		VARCHAR(50) NOT NULL,		
	[GoodsNumber]	VARCHAR(100) NOT NULL ,	
	[ProduceDate]	VARCHAR(50) NOT NULL ,
	[ValidDate]		VARCHAR(50) NOT NULL ,
	[CargoID]		INT NOT NULL ,
	[ItemID]		INT NOT NULL ,
	[IsCombined]	BIT NOT NULL ,	
	GoodsCostPrice	NUMERIC(24,10) NOT NULL,
	Qty				NUMERIC(24,10) NOT NULL
	)
SET @SQL = '
		INSERT INTO #TEMP
		SELECT	DISTINCT 
				B.OrderId,
				B.PTypeId,
				B.KTypeID,
				ISNULL(B.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,
				ISNULL(B.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,
				ISNULL(B.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
				ISNULL(B.CargoID,0) AS CargoID,
				ISNULL(B.ItemID,0) AS ItemID,
				ISNULL(B.IsCombined,0) AS IsCombined '
				
		IF @COST = '3'
			SET @SQL = @SQL + ',B.DiscountPrice AS GoodsCostPrice '	
		ELSE
			SET @SQL = @SQL + ',-1 AS GoodsCostPrice '	
				
		SET @SQL = @SQL + '		
				,SUM(ISNULL(A.Qty,0)) AS Qty
		FROM	OrderBill B
		INNER JOIN(
					SELECT	DISTINCT 
							B.OrderId,							
							ISNULL(B.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,
							ISNULL(B.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,
							ISNULL(B.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
							ISNULL(B.CargoID,0) AS CargoID,
							ISNULL(B.ItemID,0) AS ItemID,
							ISNULL(B.IsCombined,0) AS IsCombined '
					IF @COST = '3'
						SET @SQL = @SQL + ',ISNULL(B.DiscountPrice,0) AS DiscountPrice'
					
					SET @SQL = @SQL + '		
							,SUM(B.Qty) AS Qty
					FROM	BuyBill B							
					WHERE	B.BillNumberId = ' + @BillNumberID + '
					GROUP BY B.OrderId,						
							 B.GoodsNumber,
							 B.ProduceDate,
							 B.ValidDate,
							 B.CargoID,
							 B.ItemID,
							 B.IsCombined '
							 
					IF @COST = '3'
						SET @SQL = @SQL + ',B.DiscountPrice ' 
						
					SET @SQL = @SQL + '	
		)A ON B.ORDERID=A.ORDERID 
		WHERE	EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) 
				AND B.KTypeID<>'''' 
				AND B.CargoID<>0
		GROUP BY B.OrderId,
				 B.PTypeId,
				 B.KTypeID,
				 B.GoodsNumber,
				 B.ProduceDate,
				 B.ValidDate,
				 B.CargoID,
				 B.ItemID,
				 B.IsCombined '
				 
		IF @COST = '3'
			SET @SQL = @SQL + ',B.DiscountPrice ' 

--PRINT(@SQL)
EXEC (@SQL)
----------------------------------------------------------处理LimitBuyQty start------------------------------------------------------------
SET @SQL = '
	MERGE INTO GoodsStocks_Order AS T
	USING 
		(
			SELECT	C.PTypeId,
					C.KTypeID,
					C.GoodsNumber,
					C.ProduceDate,
					C.ValidDate,
					C.CargoID,
					C.ItemID,
					C.IsCombined,
					C.GoodsCostPrice,
					SUM(ISNULL((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN C.qty ELSE case when (A.ReachQty+A.WaitQty-C.qty)<=A.qty then (a.qty-(A.ReachQty+A.WaitQty-C.qty)) else 0 end END),0)) AS QTY  
			FROM OrderBill A
			INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype=301
			INNER JOIN #TEMP C ON A.OrderId = C.OrderId AND A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND isnull(A.GoodsNumber,'''')=C.GoodsNumber AND isnull( A.ProduceDate,'''')=C.ProduceDate AND isnull(A.ValidDate,'''')=C.ValidDate AND isnull(A.CargoID,0)=C.CargoID AND isnull(A.ItemID,0)=C.ItemID AND isnull(A.IsCombined,0)=C.IsCombined '+@SQLWhere+'
			GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
		) AS S  
	ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
	AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
	WHEN MATCHED
		THEN UPDATE SET T.LimitBuyQty=T.LimitBuyQty + S.QTY;'

--PRINT(@SQL)
EXEC (@SQL)
----------------------------------------------------------处理LimitBuyQty  end------------------------------------------------------------
DROP TABLE #TEMP

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Recount_LimitQty_ByOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Recount_LimitQty_ByOrder]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：删除订单处理LimitSaleQty/LimitBuyQty 
	
*/
CREATE   PROCEDURE QP_Recount_LimitQty_ByOrder 
(
	@BillNumberID VARCHAR(50),	--单据编号
	@BillType		INT
)

AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

-- 设置明细表表名
DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(100),	--明细表名
		@IndexName VARCHAR(50),		--主表名
		@LimitOrderReferQtyName VARCHAR(50)='LimitSaleQty',
		@OrderTableName VARCHAR(100)='OrderBill',	--订单明细表名
		@Groupby varchar(100)='PTypeId',
		@OrderBillType VARCHAR(50)='300',
		@SQLWhere VARCHAR(100)=''


IF @BillType=301
BEGIN
	SET @LimitOrderReferQtyName='LimitBuyQty'
	SET @OrderBillType='301'
END

IF @BillType=313
BEGIN
	SET @OrderTableName='PT_Combin_OrderBillDetail'
	SET @OrderBillType='313'
END

--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF @COST='3'
BEGIN
	IF @BillType=301
	BEGIN
		SET @Groupby='DiscountPrice'
	END
	ELSE
	BEGIN
		SET @Groupby='GoodsCostPrice'
	END
	SET @SQLWhere=' AND A.'+@Groupby+'=C.GoodsCostPrice '
END

CREATE TABLE #TEMP(	
		[PtypeId]	VARCHAR(50) NOT NULL,	
		[KtypeId]	VARCHAR(50) NOT NULL,		
		[GoodsNumber]	VARCHAR(100) NOT NULL ,	
		[ProduceDate]	VARCHAR(50) NOT NULL ,
		[ValidDate]	VARCHAR(50) NOT NULL ,
		[CargoID]	INT NOT NULL ,
		[ItemID]	INT NOT NULL ,
		[IsCombined]	BIT NOT NULL ,	
		GoodsCostPrice	  NUMERIC(24,10) NOT NULL 
	)
SET @SQL = '
		INSERT INTO #TEMP
				SELECT DISTINCT B.PTypeId,B.KTypeID,ISNULL(B.GoodsNumber,' + CHAR(39) + CHAR(39) + ') AS GoodsNumber,ISNULL(B.ProduceDate,'+CHAR(39)+CHAR(39)+') AS ProduceDate,ISNULL(B.ValidDate,'+CHAR(39)+CHAR(39)+') AS ValidDate,
						ISNULL(B.CargoID,0) AS CargoID,ISNULL(B.ItemID,0) AS ItemID,ISNULL(B.IsCombined,0) AS IsCombined,CASE WHEN '+@COST+'=''3'' THEN ISNULL(B.'+@Groupby+',0) ELSE -1 END AS GoodsCostPrice
				FROM '+@OrderTableName+' B 
				WHERE B.BillNumberId = ' + @BillNumberID + ' AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'''' AND B.CargoID<>0'
EXEC (@SQL)

----------------------------------------------------------处理LimitSaleQty/LimitBuyQty start------------------------------------------------------------
IF @BillType=301
BEGIN
	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
				SUM(ISNULL((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN (A.ReachQty+A.WaitQty) ELSE A.qty END),0)) AS QTY 
				FROM '+@OrderTableName+' A
				INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype = '+@OrderBillType+' AND A.billNumberID<>'+@BillNumberID+'
				INNER JOIN #TEMP C
				ON A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND A.GoodsNumber=C.GoodsNumber AND A.ProduceDate=C.ProduceDate 
					  AND A.ValidDate=C.ValidDate AND A.CargoID=C.CargoID AND A.ItemID=C.ItemID AND A.IsCombined=C.IsCombined '+@SQLWhere+'
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@LimitOrderReferQtyName+'=S.QTY;'
	EXEC (@SQL)
END
ELSE IF @BillType=300
BEGIN
	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
						SUM(ISNULL(C.QTY,0)) AS QTY
				FROM
				(SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
				SUM((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN (A.ReachQty+A.WaitQty) ELSE A.qty END)) AS QTY 
				FROM '+@OrderTableName+' A
				INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype = '+@OrderBillType+' AND A.billNumberID<>'+@BillNumberID+'
				INNER JOIN #TEMP C
				ON A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND A.GoodsNumber=C.GoodsNumber AND A.ProduceDate=C.ProduceDate 
					  AND A.ValidDate=C.ValidDate AND A.CargoID=C.CargoID AND A.ItemID=C.ItemID AND A.IsCombined=C.IsCombined '+@SQLWhere+'
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
				
				UNION ALL
				
				SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
				SUM((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN (A.ReachQty+A.WaitQty) ELSE A.qty END)) AS QTY 
				FROM PT_Combin_OrderBillDetail A
				INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype =313
				INNER JOIN #TEMP C
				ON A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND A.GoodsNumber=C.GoodsNumber AND A.ProduceDate=C.ProduceDate 
					  AND A.ValidDate=C.ValidDate AND A.CargoID=C.CargoID AND A.ItemID=C.ItemID AND A.IsCombined=C.IsCombined '+@SQLWhere+'
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice)C
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@LimitOrderReferQtyName+'=S.QTY;'
	EXEC (@SQL)
END
ELSE
BEGIN
	SET @SQL = '
		MERGE INTO GoodsStocks_Order AS T
		USING 
			(
				SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
						SUM(ISNULL(C.QTY,0)) AS QTY
				FROM
				(SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
				SUM((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN (A.ReachQty+A.WaitQty) ELSE A.qty END)) AS QTY 
				FROM '+@OrderTableName+' A
				INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype = '+@OrderBillType+' AND A.billNumberID<>'+@BillNumberID+'
				INNER JOIN #TEMP C
				ON A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND A.GoodsNumber=C.GoodsNumber AND A.ProduceDate=C.ProduceDate 
					  AND A.ValidDate=C.ValidDate AND A.CargoID=C.CargoID AND A.ItemID=C.ItemID AND A.IsCombined=C.IsCombined '+@SQLWhere+'
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
				
				UNION ALL
				
				SELECT C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,
						C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice,
				SUM((CASE WHEN (A.ReachQty+A.WaitQty)<=A.qty THEN (A.ReachQty+A.WaitQty) ELSE A.qty END)) AS QTY 
				FROM OrderBill A
				INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype =300
				INNER JOIN #TEMP C
				ON A.PTypeId=C.PTypeId AND A.KTypeID=C.KTypeID AND A.GoodsNumber=C.GoodsNumber AND A.ProduceDate=C.ProduceDate 
					  AND A.ValidDate=C.ValidDate AND A.CargoID=C.CargoID AND A.ItemID=C.ItemID AND A.IsCombined=C.IsCombined '+@SQLWhere+'
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice)C
				GROUP BY C.PTypeId,C.KTypeID,C.GoodsNumber,C.ProduceDate,C.ValidDate,C.CargoID,C.ItemID,C.IsCombined,C.GoodsCostPrice
			) AS S  
		ON T.PTypeId=S.PTypeId AND T.KTypeID=S.KTypeID AND T.GoodsNumber=S.GoodsNumber AND T.ProduceDate=S.ProduceDate 
		AND T.ValidDate=S.ValidDate AND T.CargoID=S.CargoID AND T.ItemID=S.ItemID AND T.IsCombined=S.IsCombined AND T.GoodsCostPrice=S.GoodsCostPrice
		WHEN MATCHED
		THEN UPDATE SET T.'+@LimitOrderReferQtyName+'=S.QTY;'
	EXEC (@SQL)
END
----------------------------------------------------------处理LimitSaleQty/LimitBuyQty  end------------------------------------------------------------
DROP TABLE #TEMP

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Recount_OrderQty]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Recount_OrderQty]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：重算订单库存 
	
*/
CREATE   PROCEDURE QP_Recount_OrderQty 
(
	@flag int =0		--0标示重建、升级，1标示年结存
)

AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF


--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'

--BILLINDEX临时表
CREATE TABLE #BillIndex
(
	BillNumberID [numeric](18, 0) NOT NULL,
	[BillType] [numeric](4, 0) NOT NULL,	
	[draft] [bit] NOT NULL,
	[ifcheck] [char](1) NOT NULL
)
INSERT INTO #BillIndex
(
	BillNumberID,
	[BillType],
	[draft],
	[ifcheck]
)
SELECT A.BillNumberId,A.BillType,A.draft,A.ifcheck FROM BillIndex A WHERE A.draft=1 AND A.ifcheck='f' AND A.BillType IN(11,12,34,140,144,400,402)
--orderindex临时表
CREATE TABLE #OrderIndex
(
	BillNumberID [numeric](18, 0) NOT NULL,
	[billtype] [smallint] NOT NULL
)
INSERT INTO #OrderIndex
(
	BillNumberID,
	[BillType]
)
SELECT A.billNumberId,A.billtype FROM OrderIndex A

----------------------------------------------------------更新orderbill的waitqty start------------------------------------------------------------
CREATE TABLE #WaitQty
(
	BillNumberID [numeric](18, 0) NOT NULL,
	OrderID [int] NOT NULL ,	
	WaitQty [numeric](24,10) NOT NULL
) 
INSERT INTO #WaitQty
(
	BillNumberID,
	OrderID,
	WaitQty
)
SELECT 
	A.billNumberID,
	A.OrderID,
	SUM(isnull(A.QTY,0)) AS WaitQty
FROM
(
--采购入库
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,BuyBill B,#BillIndex A WHERE A.BillType=34 AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID

--暂估入库
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C, AppraisalBill B,#BillIndex A WHERE A.BillType=400 AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID

--受托收货
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,CommissionBill B,#BillIndex A WHERE A.BillType=144 AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID AND B.Type=144

--销售出库
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,SaleBill B,#BillIndex A WHERE A.BillType=11 AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID 

--委托发货
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,CommissionBill B,#BillIndex A WHERE A.BillType=140 AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID AND B.Type=140

--发出商品出库
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,SendBill B,#BillIndex A WHERE A.BillType=402 AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID 
) AS A 
GROUP BY A.billNumberID,A.OrderID

IF (SELECT count(*) FROM #WaitQty)>0
BEGIN
	UPDATE A SET WaitQty=ISNULL(B.WaitQty,0)
	FROM OrderBill A 
	JOIN #WaitQty B ON A.billNumberID=B.billNumberID AND A.OrderId=B.OrderId 
	
	UPDATE A SET WaitQty=0
	FROM OrderBill A WHERE A.OrderID NOT IN (SELECT B.OrderId FROM #WaitQty B)
END
ELSE
BEGIN
	UPDATE A SET WaitQty=0
	FROM OrderBill A
END
----------------------------------------------------------更新orderbill的waitqty END------------------------------------------------------------

----------------------------------------------------------更新PT_Combin_OrderBillDetail/PT_Combin_OrderBill的waitqty start------------------------------------------------------------
CREATE TABLE #PtWaitQty
(
	BillNumberID [numeric](18, 0) NOT NULL,
	OrderID [int] NOT NULL ,	
	WaitQty [numeric](24,10) NOT NULL,
	pindex varchar(300) NOT NULL
) 
INSERT INTO #PtWaitQty
(
	BillNumberID,
	OrderID,
	WaitQty,
	pindex
)
--组合品出库
SELECT 
	C.billNumberID,
	C.OrderID,
	SUM(isnull(B.Qty,0)) AS WaitQty,
	C.pindexid
FROM PT_Combin_OrderBillDetail C,PT_Combin_SaleBillDetail B,#BILLINDEX A WHERE A.BillType=12 AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID 
GROUP BY C.billNumberID,C.OrderID,C.pindexid

IF (SELECT count(*) FROM #PtWaitQty)>0
BEGIN
	UPDATE A SET WaitQty=ISNULL(B.WaitQty,0)
	FROM PT_Combin_OrderBillDetail A 
	JOIN #PtWaitQty B ON A.billNumberID=B.billNumberID AND A.OrderId=B.OrderId 
	
	UPDATE A SET WaitQty=0
	FROM PT_Combin_OrderBillDetail A WHERE A.OrderID NOT IN (SELECT B.OrderId FROM #PtWaitQty B)

	UPDATE A SET WaitQty=ISNULL(B.WaitQty,0)
	FROM PT_Combin_OrderBill A 
	JOIN(
		SELECT billNumberID,pindex,sum(isnull(WaitQty,0)) AS WaitQty FROM #PtWaitQty GROUP BY BillNumberID,pindex
	)B ON A.billNumberID=B.billNumberID AND A.pindexid=B.pindex
	
	UPDATE A SET WaitQty=0
	FROM PT_Combin_OrderBill A WHERE A.pindexid NOT IN (SELECT B.pindex FROM #PtWaitQty B)
END
ELSE
BEGIN
	UPDATE A SET WaitQty=0
	FROM PT_Combin_OrderBillDetail A 

	UPDATE A SET WaitQty=0
	FROM PT_Combin_OrderBill A 
END
----------------------------------------------------------更新PT_Combin_OrderBillDetail/PT_Combin_OrderBill的waitqty END------------------------------------------------------------

----------------------------------------------------------重算订单库存 表 start------------------------------------------------------------
TRUNCATE TABLE GoodsStocks_Order
INSERT INTO GoodsStocks_Order
(
	PTypeId,
	KtypeID,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	CargoID,
	ItemID,
	IsCombined,
	GoodsCostPrice,
	SaleOrderQty,
	SaleReferQty,
	SaleReachQty,
	LimitSaleQty,
	BuyOrderQty,
	BuyReferQty,
	BuyReachQty,
	LimitBuyQty
)
SELECT	
	B.PTypeId,
	B.KtypeID,
	B.GoodsNumber,
	B.ProduceDate,
	B.ValidDate,
	B.CargoID,
	B.ItemID,
	B.IsCombined,
	B.GoodsCostPrice,
	SUM(ISNULL(B.SaleOrderQty,0)) AS SaleOrderQty,
	SUM(ISNULL(B.SaleReferQty,0)) AS SaleReferQty,
	SUM(ISNULL(B.SaleReachQty,0)) AS SaleReachQty,
	SUM(ISNULL(B.LimitSaleQty,0)) AS LimitSaleQty,
	SUM(ISNULL(B.BuyOrderQty,0)) AS BuyOrderQty,
	SUM(ISNULL(B.BuyReferQty,0)) AS BuyReferQty,
	SUM(ISNULL(B.BuyReachQty,0)) AS BuyReachQty,
	SUM(ISNULL(B.LimitBuyQty,0)) AS LimitBuyQty
FROM	
(	
	--明细
	--采购、暂估、受托
	SELECT B.ptypeid,B.KTypeID,isnull(B.GoodsNumber,'') AS GoodsNumber,isnull(B.ProduceDate,'') AS ProduceDate,isnull(B.ValidDate,'') AS ValidDate,
			isnull(B.CargoID,'') AS CargoID,isnull(B.ItemID,'') AS ItemID,isnull(B.IsCombined,'') AS IsCombined,
			CASE WHEN @COST='3' THEN ISNULL(B.DiscountPrice,0) ELSE -1 END AS GoodsCostPrice,
			0 AS SaleOrderQty,
			0 AS SaleReferQty,
			0 AS SaleReachQty,
			0 AS LimitSaleQty,
			CASE WHEN B.BillOver=0 THEN B.Qty ELSE(CASE WHEN B.qty>=(B.WaitQty+B.ReachQty) THEN (B.WaitQty+B.ReachQty) ELSE B.qty END) END AS BuyOrderQty,
			B.WaitQty AS BuyReferQty,
			B.ReachQty AS BuyReachQty,
			CASE WHEN (B.ReachQty+B.WaitQty)<=B.qty THEN (B.ReachQty+B.WaitQty) ELSE B.qty END AS LimitBuyQty
	FROM OrderBill B,#OrderIndex A WHERE A.billtype=301 AND A.billNumberId=B.billNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'' AND B.CargoID<>0
	
	--销售、发出商品出库、委托
	UNION ALL
	SELECT B.ptypeid,B.KTypeID,isnull(B.GoodsNumber,'') AS GoodsNumber,isnull(B.ProduceDate,'') AS ProduceDate,isnull(B.ValidDate,'') AS ValidDate,
			isnull(B.CargoID,'') AS CargoID,isnull(B.ItemID,'') AS ItemID,isnull(B.IsCombined,'') AS IsCombined,
			CASE WHEN @COST='3' THEN ISNULL(B.GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,
			CASE WHEN B.BillOver=0 THEN B.qty ELSE(CASE WHEN B.qty>=(B.WaitQty+B.ReachQty) THEN (B.WaitQty+B.ReachQty) ELSE B.qty END) END AS SaleOrderQty,
			B.WaitQty AS SaleReferQty,
			B.ReachQty AS SaleReachQty,
			CASE WHEN (B.ReachQty+B.WaitQty)<=B.qty THEN (B.ReachQty+B.WaitQty) ELSE B.qty END AS LimitSaleQty,			
			0 AS BuyOrderQty,
			0 AS BuyReferQty,
			0 AS BuyReachQty,
			0 AS LimitBuyQty
	FROM OrderBill B,#OrderIndex A WHERE A.billtype=300 AND A.billNumberId=B.billNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'' AND B.CargoID<>0
	
	--组合品销售
	UNION ALL
	SELECT B.ptypeid,B.KTypeID,isnull(B.GoodsNumber,'') AS GoodsNumber,isnull(B.ProduceDate,'') AS ProduceDate,isnull(B.ValidDate,'') AS ValidDate,
			isnull(B.CargoID,'') AS CargoID,isnull(B.ItemID,'') AS ItemID,isnull(B.IsCombined,'') AS IsCombined,
			CASE WHEN @COST='3' THEN ISNULL(B.GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,
			CASE WHEN B.BillOver=0 THEN B.qty ELSE(CASE WHEN B.qty>=(B.WaitQty+B.ReachQty) THEN (B.WaitQty+B.ReachQty) ELSE B.qty END) END AS SaleOrderQty,
			B.WaitQty AS SaleReferQty,
			B.ReachQty AS SaleReachQty,
			CASE WHEN (B.ReachQty+B.WaitQty)<=B.qty THEN (B.ReachQty+B.WaitQty) ELSE B.qty END AS LimitSaleQty,
			0 AS BuyOrderQty,
			0 AS BuyReferQty,
			0 AS BuyReachQty,
			0 AS LimitBuyQty
	FROM PT_Combin_OrderBillDetail B,#OrderIndex A WHERE A.billtype=313 AND A.billNumberId=B.billNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'' AND B.CargoID<>0

) AS B 
GROUP BY B.PTypeId,B.KTypeID,B.GoodsNumber,B.ProduceDate,B.ValidDate,B.CargoID,B.ItemID,B.IsCombined,B.GoodsCostPrice
----------------------------------------------------------重算订单库存  end------------------------------------------------------------

--删除各维度数量为0的商品
DELETE dbo.GoodsStocks_Order WHERE SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0

DROP TABLE #WaitQty,#PtWaitQty,#BILLINDEX,#ORDERINDEX

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Recount_OrderQty_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Recount_OrderQty_Update]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：重算订单库存 
	
*/
CREATE   PROCEDURE QP_Recount_OrderQty_Update 


AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF


--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'

--BILLINDEX临时表
CREATE TABLE #BillIndex
(
	BillNumberID [numeric](18, 0) NOT NULL,
	[BillType] [numeric](4, 0) NOT NULL,	
	[draft] [bit] NOT NULL,
	[ifcheck] [char](1) NOT NULL,
	RedWord bit not null
)
INSERT INTO #BillIndex
(
	BillNumberID,
	[BillType],
	[draft],
	[ifcheck],
	RedWord
)
SELECT A.BillNumberId,A.BillType,A.draft,A.ifcheck,A.RedWord FROM BillIndex A WHERE A.BillType IN(11,12,34,140,144,400,402)
--orderindex临时表
CREATE TABLE #OrderIndex
(
	BillNumberID [numeric](18, 0) NOT NULL,
	[billtype] [smallint] NOT NULL
)
INSERT INTO #OrderIndex
(
	BillNumberID,
	[BillType]
)
SELECT A.billNumberId,A.billtype FROM OrderIndex A

----------------------------------------------------------更新orderbill的waitqty start------------------------------------------------------------
CREATE TABLE #WaitQty
(
	BillNumberID [numeric](18, 0) NOT NULL,
	OrderID [int] NOT NULL ,	
	WaitQty [numeric](24,10) NOT NULL
) 
INSERT INTO #WaitQty
(
	BillNumberID,
	OrderID,
	WaitQty
)
SELECT 
	A.billNumberID,
	A.OrderID,
	SUM(isnull(A.QTY,0)) AS WaitQty
FROM
(
--采购入库
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,BuyBill B,#BillIndex A WHERE A.BillType=34 AND A.draft=1 AND A.ifcheck='f' AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID

--暂估入库
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,AppraisalBill B,#BillIndex A WHERE A.BillType=400 AND A.draft=1 AND A.ifcheck='f' AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID

--受托收货
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,CommissionBill B,#BillIndex A WHERE A.BillType=144 AND A.draft=1 AND A.ifcheck='f' AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID AND B.Type=144

--销售出库
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,SaleBill B,#BillIndex A WHERE A.BillType=11 AND A.draft=1 AND A.ifcheck='f' AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID 

--委托发货
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,CommissionBill B,#BillIndex A WHERE A.BillType=140 AND A.draft=1 AND A.ifcheck='f' AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID AND B.Type=140

--发出商品出库
UNION ALL
SELECT C.billNumberID,C.OrderID,B.Qty
FROM OrderBill C,SendBill B,#BillIndex A WHERE A.BillType=402 AND A.draft=1 AND A.ifcheck='f' AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID 
) AS A 
GROUP BY A.billNumberID,A.OrderID

IF (SELECT count(*) FROM #WaitQty)>0
BEGIN
	UPDATE A SET WaitQty=ISNULL(B.WaitQty,0)
	FROM OrderBill A 
	JOIN #WaitQty B ON A.billNumberID=B.billNumberID AND A.OrderId=B.OrderId 
	
	UPDATE A SET WaitQty=0
	FROM OrderBill A WHERE A.OrderID NOT IN (SELECT B.OrderId FROM #WaitQty B)
END
ELSE
BEGIN
	UPDATE A SET WaitQty=0
	FROM OrderBill A
END
----------------------------------------------------------更新orderbill的waitqty END------------------------------------------------------------

----------------------------------------------------------更新PT_Combin_OrderBillDetail/PT_Combin_OrderBill的waitqty start------------------------------------------------------------
CREATE TABLE #PtWaitQty
(
	BillNumberID [numeric](18, 0) NOT NULL,
	OrderID [int] NOT NULL ,	
	WaitQty [numeric](24,10) NOT NULL,
	pindex varchar(300) NOT NULL
) 
INSERT INTO #PtWaitQty
(
	BillNumberID,
	OrderID,
	WaitQty,
	pindex
)
--组合品出库
SELECT 
	C.billNumberID,
	C.OrderID,
	SUM(isnull(B.Qty,0)) AS WaitQty,
	C.pindexid
FROM PT_Combin_OrderBillDetail C,PT_Combin_SaleBillDetail B,#BillIndex A WHERE A.BillType=12 AND A.draft=1 AND A.ifcheck='f' AND A.BillNumberId=B.BillNumberId AND B.orderid=C.OrderID 
GROUP BY C.billNumberID,C.OrderID,C.pindexid

IF (SELECT count(*) FROM #PtWaitQty)>0
BEGIN
	UPDATE A SET WaitQty=ISNULL(B.WaitQty,0)
	FROM PT_Combin_OrderBillDetail A 
	JOIN #PtWaitQty B ON A.billNumberID=B.billNumberID AND A.OrderId=B.OrderId 
	
	UPDATE A SET WaitQty=0
	FROM PT_Combin_OrderBillDetail A WHERE A.OrderID NOT IN (SELECT B.OrderId FROM #PtWaitQty B)

	UPDATE A SET WaitQty=ISNULL(B.WaitQty,0)
	FROM PT_Combin_OrderBill A 
	JOIN(
		SELECT billNumberID,pindex,sum(isnull(WaitQty,0)) AS WaitQty FROM #PtWaitQty GROUP BY BillNumberID,pindex
	)B ON A.billNumberID=B.billNumberID AND A.pindexid=B.pindex
	
	UPDATE A SET WaitQty=0
	FROM PT_Combin_OrderBill A WHERE A.pindexid NOT IN (SELECT B.pindex FROM #PtWaitQty B)
END
ELSE
BEGIN
	UPDATE A SET WaitQty=0
	FROM PT_Combin_OrderBillDetail A 

	UPDATE A SET WaitQty=0
	FROM PT_Combin_OrderBill A 
END
----------------------------------------------------------更新PT_Combin_OrderBillDetail/PT_Combin_OrderBill的waitqty END------------------------------------------------------------

----------------------------------------------------------重算订单库存 表 start------------------------------------------------------------
TRUNCATE TABLE GoodsStocks_Order
INSERT INTO GoodsStocks_Order
(
	PTypeId,
	KtypeID,
	GoodsNumber,
	ProduceDate,
	ValidDate,
	CargoID,
	ItemID,
	IsCombined,
	GoodsCostPrice,
	SaleOrderQty,
	SaleReferQty,
	SaleReachQty,
	LimitSaleQty,
	BuyOrderQty,
	BuyReferQty,
	BuyReachQty,
	LimitBuyQty
)
SELECT	
	B.PTypeId,
	B.KtypeID,
	B.GoodsNumber,
	B.ProduceDate,
	B.ValidDate,
	B.CargoID,
	B.ItemID,
	B.IsCombined,
	B.GoodsCostPrice,
	SUM(ISNULL(B.SaleOrderQty,0)) AS SaleOrderQty,
	SUM(ISNULL(B.SaleReferQty,0)) AS SaleReferQty,
	SUM(ISNULL(B.SaleReachQty,0)) AS SaleReachQty,
	SUM(ISNULL(B.LimitSaleQty,0)) AS LimitSaleQty,
	SUM(ISNULL(B.BuyOrderQty,0)) AS BuyOrderQty,
	SUM(ISNULL(B.BuyReferQty,0)) AS BuyReferQty,
	SUM(ISNULL(B.BuyReachQty,0)) AS BuyReachQty,
	SUM(ISNULL(B.LimitBuyQty,0)) AS LimitBuyQty
FROM	
(	
	--明细
	--采购、暂估、受托
	SELECT B.ptypeid,B.KTypeID,isnull(B.GoodsNumber,'') AS GoodsNumber,isnull(B.ProduceDate,'') AS ProduceDate,isnull(B.ValidDate,'') AS ValidDate,
			isnull(B.CargoID,'') AS CargoID,isnull(B.ItemID,'') AS ItemID,isnull(B.IsCombined,'') AS IsCombined,
			CASE WHEN @COST='3' THEN ISNULL(B.DiscountPrice,0) ELSE -1 END AS GoodsCostPrice,
			0 AS SaleOrderQty,
			0 AS SaleReferQty,
			0 AS SaleReachQty,
			0 AS LimitSaleQty,
			CASE WHEN B.BillOver=0 THEN B.Qty ELSE (CASE WHEN B.qty>=(B.WaitQty+B.ReachQty) THEN (B.WaitQty+B.ReachQty) ELSE B.qty END) END AS BuyOrderQty,
			B.WaitQty AS BuyReferQty,
			B.ReachQty AS BuyReachQty,
			CASE WHEN (B.ReachQty+B.WaitQty)<=B.qty THEN (B.ReachQty+B.WaitQty) ELSE B.qty END AS LimitBuyQty
	FROM OrderBill B,#OrderIndex A WHERE A.billtype=301 AND A.billNumberId=B.billNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'' AND B.CargoID<>0
	
	--销售、发出商品出库、委托
	UNION ALL
	SELECT B.ptypeid,B.KTypeID,isnull(B.GoodsNumber,'') AS GoodsNumber,isnull(B.ProduceDate,'') AS ProduceDate,isnull(B.ValidDate,'') AS ValidDate,
			isnull(B.CargoID,'') AS CargoID,isnull(B.ItemID,'') AS ItemID,isnull(B.IsCombined,'') AS IsCombined,
			CASE WHEN @COST='3' THEN ISNULL(B.GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,
			CASE WHEN B.BillOver=0 THEN B.qty ELSE (CASE WHEN B.qty>=(B.WaitQty+B.ReachQty) THEN (B.WaitQty+B.ReachQty) ELSE B.Qty END) END AS SaleOrderQty,
			B.WaitQty AS SaleReferQty,
			B.ReachQty AS SaleReachQty,
			CASE WHEN (B.ReachQty+B.WaitQty)<=B.qty THEN (B.ReachQty+B.WaitQty) ELSE B.qty END AS LimitSaleQty,			
			0 AS BuyOrderQty,
			0 AS BuyReferQty,
			0 AS BuyReachQty,
			0 AS LimitBuyQty
	FROM OrderBill B,#OrderIndex A WHERE A.billtype=300 AND A.billNumberId=B.billNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'' AND B.CargoID<>0
	
	--组合品销售
	UNION ALL
	SELECT B.ptypeid,B.KTypeID,isnull(B.GoodsNumber,'') AS GoodsNumber,isnull(B.ProduceDate,'') AS ProduceDate,isnull(B.ValidDate,'') AS ValidDate,
			isnull(B.CargoID,'') AS CargoID,isnull(B.ItemID,'') AS ItemID,isnull(B.IsCombined,'') AS IsCombined,
			CASE WHEN @COST='3' THEN ISNULL(B.GoodsCostPrice,0) ELSE -1 END AS GoodsCostPrice,
			CASE WHEN B.BillOver=0 THEN B.qty ELSE(CASE WHEN B.qty>=(B.WaitQty+B.ReachQty) THEN (B.WaitQty+B.ReachQty) ELSE B.qty END) END AS SaleOrderQty,
			B.WaitQty AS SaleReferQty,
			B.ReachQty AS SaleReachQty,
			CASE WHEN (B.ReachQty+B.WaitQty)<=B.qty THEN (B.ReachQty+B.WaitQty) ELSE B.qty END AS LimitSaleQty,
			0 AS BuyOrderQty,
			0 AS BuyReferQty,
			0 AS BuyReachQty,
			0 AS LimitBuyQty
	FROM PT_Combin_OrderBillDetail B,#OrderIndex A WHERE A.billtype=313 AND A.billNumberId=B.billNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=B.ptypeid AND IsService=0) AND B.KTypeID<>'' AND B.CargoID<>0

) AS B 
GROUP BY B.PTypeId,B.KTypeID,B.GoodsNumber,B.ProduceDate,B.ValidDate,B.CargoID,B.ItemID,B.IsCombined,B.GoodsCostPrice
----------------------------------------------------------重算订单库存  end------------------------------------------------------------

--删除各维度数量为0的商品
DELETE dbo.GoodsStocks_Order WHERE SaleOrderQty=0 AND SaleReferQty=0 AND SaleReachQty=0 AND BuyOrderQty=0 AND BuyReferQty=0 AND BuyReachQty=0

DROP TABLE #WaitQty,#PtWaitQty,#BILLINDEX,#ORDERINDEX

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Recount_ReachQty_For_YearProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Recount_ReachQty_For_YearProc]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：重算期初订单库存 
	
*/
CREATE   PROCEDURE QP_Recount_ReachQty_For_YearProc 

AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--orderINDEX临时表
CREATE TABLE #orderINDEX
(
	BillNumberID [numeric](18, 0) NOT NULL,
	[BillType] [numeric](4, 0) NOT NULL
)
INSERT INTO #orderINDEX
(
	BillNumberID,
	[BillType]
)
SELECT A.BillNumberId,A.BillType FROM OrderIndex A 

----------------------------------------------------------重算期初订单库存 表 start------------------------------------------------------------
TRUNCATE TABLE Ini_GoodsStocks_Order
INSERT INTO Ini_GoodsStocks_Order
(
	BillNumberID,
	OrderID,
	BillType,
	ReachQty,
	ReachTotal,
	ReachTaxTotal
)
SELECT 
	A.billNumberID,
	A.OrderID,
	A.BillType,
	SUM(isnull(A.ReachQty,0)) AS ReachQty,
	SUM(isnull(A.ReachTotal,0)) AS ReachTotal,
	SUM(isnull(A.ReachTaxTotal,0)) AS ReachTaxTotal
FROM
(
--采购销售
SELECT C.billNumberID,C.OrderID,A.BillType,C.ReachQty,C.ReachTotal,C.ReachTaxTotal
FROM OrderBill C,#orderINDEX A WHERE A.BillType IN (300,301) AND C.billNumberID=A.BillNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=C.ptypeid AND IsService=0) AND C.KTypeID<>'' AND C.CargoID<>0

--组合品
UNION ALL
SELECT C.billNumberID,C.OrderID,A.BillType,C.ReachQty,C.ReachTotal,C.ReachTaxTotal
FROM PT_Combin_OrderBillDetail C,#orderINDEX A WHERE A.BillType=313 AND C.billNumberID=A.BillNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=C.ptypeid AND IsService=0) AND C.KTypeID<>'' AND C.CargoID<>0

) AS A 
GROUP BY A.billNumberID,A.OrderID,A.BillType

----------------------------------------------------------重算期初订单库存 表 END------------------------------------------------------------
DELETE FROM Ini_GoodsStocks_Order WHERE ReachQty=0 AND ReachTotal=0 AND ReachTaxTotal=0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Recount_ReachQty_For_YearProc_DateTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Recount_ReachQty_For_YearProc_DateTime]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	功能说明：重算期初订单库存-指定时间年结存 
	
*/
CREATE   PROCEDURE QP_Recount_ReachQty_For_YearProc_DateTime 
(
	@yearendDatetime		VARCHAR(20)		--年结存的时间
)
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--删除此前的数据
DELETE FROM OrderIndex WHERE BillDate <= @yearendDatetime

--orderINDEX临时表
CREATE TABLE #orderINDEX
(
	BillNumberID [numeric](18, 0) NOT NULL,
	[BillType] [numeric](4, 0) NOT NULL
)
INSERT INTO #orderINDEX
(
	BillNumberID,
	[BillType]
)
SELECT A.BillNumberId,A.BillType FROM OrderIndex A

----------------------------------------------------------重算期初订单库存 表 start------------------------------------------------------------
TRUNCATE TABLE Ini_GoodsStocks_Order
INSERT INTO Ini_GoodsStocks_Order
(
	BillNumberID,
	OrderID,
	BillType,
	ReachQty,
	ReachTotal,
	ReachTaxTotal
)
SELECT 
	A.billNumberID,
	A.OrderID,
	A.BillType,
	SUM(isnull(A.ReachQty,0)) AS ReachQty,
	SUM(isnull(A.ReachTotal,0)) AS ReachTotal,
	SUM(isnull(A.ReachTaxTotal,0)) AS ReachTaxTotal
FROM
(
--采购销售
SELECT C.billNumberID,C.OrderID,A.BillType,C.ReachQty,C.ReachTotal,C.ReachTaxTotal
FROM OrderBill C,#orderINDEX A WHERE A.BillType IN (300,301) AND C.billNumberID=A.BillNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=C.ptypeid AND IsService=0) AND C.KTypeID<>'' AND C.CargoID<>0

--组合品
UNION ALL
SELECT C.billNumberID,C.OrderID,A.BillType,C.ReachQty,C.ReachTotal,C.ReachTaxTotal
FROM PT_Combin_OrderBillDetail C,#orderINDEX A WHERE A.BillType=313 AND C.billNumberID=A.BillNumberID AND EXISTS (SELECT TOP 1 1 FROM ptype WHERE typeId=C.ptypeid AND IsService=0) AND C.KTypeID<>'' AND C.CargoID<>0

) AS A 
GROUP BY A.billNumberID,A.OrderID,A.BillType

----------------------------------------------------------重算期初订单库存 表 END------------------------------------------------------------
DELETE FROM Ini_GoodsStocks_Order WHERE ReachQty=0 AND ReachTotal=0 AND ReachTaxTotal=0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_RepairCombItem_Update]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_RepairCombItem_Update]
GO


----========================
----修改者：蔡志成
----日期：2010-7-22
----描述：汽配维修套餐档案
----========================
CREATE  PROCEDURE QP_RepairCombItem_Update
    (
      @p_typeid [varchar](6000)
    )
--@encode$--
AS 
    SET NOCOUNT ON
    DECLARE @SQL VARCHAR(7000)
    SELECT @SQL='
    UPDATE QP_RepairSetMeal_Items 
    SET 
		QP_RepairSetMeal_Items.StandardManHour=a.StandardManHour,
		QP_RepairSetMeal_Items.CheckManHour=a.CheckHour,
		QP_RepairSetMeal_Items.ManHourExpense= CASE a.ChargeMode WHEN 0 THEN 0 WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END 
    FROM dbo.QP_RepairSetMeal_Items m
		INNER JOIN dbo.QP_RepairItems a	ON 
		(m.RepairItemsTypeID = a.TypeID AND m.TypeID IN ('+@p_typeid+'))        
		'   

    EXEC(@SQL)
    SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_RepairCombPrice_Update]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_RepairCombPrice_Update]
GO


----========================
----修改者：蔡志成
----日期：2010-7-22
----描述：汽配维修套餐档案
----========================
CREATE  PROCEDURE QP_RepairCombPrice_Update
    (
      @p_typeid [varchar](6000),
	  @str_price [VARCHAR] (6000)
    )
--@encode$--
AS 

SET NOCOUNT ON
DECLARE @SQL VARCHAR(7000)
IF @p_typeid like 'all,%'--更新所有配件的价格
BEGIN		 
	 EXEC(@str_price)		
END
ELSE--更新套餐档案的配件价格
BEGIN		
	SELECT @SQL='
	UPDATE	dbo.QP_RepairSetMeal_Fittings
	SET		dbo.QP_RepairSetMeal_Fittings.Price= case when ('+@str_price+')<0 then 0 else '+@str_price+' end ,
			dbo.QP_RepairSetMeal_Fittings.Total=case when  a.Qty*('+@str_price+')<0 then 0 else ROUND(a.Qty*('+@str_price+'),2) end 
	FROM	QP_RepairSetMeal_Fittings a
	INNER JOIN dbo.ptype p ON (a.ptypeid=p.typeid AND a.typeid IN ('+@p_typeid+'))  	 
	INNER JOIN PType_Price p1 ON (p.typeId=p1.PTypeID)  '   
END
	
--PRINT @SQL
EXEC(@SQL)
SET NOCOUNT OFF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryRepairOperationTypeQueryDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryRepairOperationTypeQueryDataSource]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王刚
	日期：2011-05-5
	描述：查询业务类别的相关信息
*/

CREATE PROCEDURE Web_QueryRepairOperationTypeQueryDataSource
(	
	@OperatorId				VARCHAR(100),		--操作员id
	@startdate				VARCHAR(MAX),		--结算开始日期
	@enddate				VARCHAR(MAX),		--结算结束日期
	@stypeid				VARCHAR(MAX),		--分支机构id
	@billtype				VARCHAR(MAX)		--单据类型
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--选择单据类型
CREATE TABLE #BillNumberId(BillNumberId numeric(10,0))
IF(@BillType = 0)
	INSERT INTO #BillNumberId(BillNumberId)
	SELECT	BillNumberId FROM BillIndex WHERE BillType IN(166,178)				
ELSE IF(@BillType = 1)
	INSERT INTO #BillNumberId(BillNumberId)
	SELECT BillNumberId FROM BillIndex WHERE BillType=178				
ELSE IF(@BillType = 2)
	INSERT INTO #BillNumberId(BillNumberId)
	SELECT BillNumberId FROM BillIndex WHERE BillType=166
	
--聚合快修单，维修单
CREATE TABLE #Quick_Repari_RepairBill
(
	billnumberid INT,
	discounttotal  NUMERIC(24, 10) ,		 --折后工时费
	costtotal  NUMERIC(24, 10) 				 --折后工时成本
)
INSERT INTO #Quick_Repari_RepairBill
SELECT BillNumberId,ISNULL(SUM(DiscountTotal),0),ISNULL(SUM(CostTotal),0) FROM QP_QuickRepairBill_RepairItems GROUP BY BillNumberId
UNION ALL
SELECT BillNumberId,ISNULL(SUM(DiscountTotal),0),ISNULL(SUM(CostTotal),0) FROM Qp_ReceptionBill_RepairItems GROUP BY BillNumberId

--材料成本
CREATE TABLE #InOutstocktable
(
	billnumberid INT,
	ptypetotal  NUMERIC(24, 10) ,					--材料总额（折后金额）
	costtotal  NUMERIC(24, 10) 						--材料成本		
)
INSERT INTO #InOutstocktable
SELECT i.BillNumberId, ISNULL(SUM(i.Total),0),ISNULL(SUM(i.CostTotal),0) 
FROM InOutstocktable i
INNER JOIN #BillNumberId b ON i.BillNumberId = b.BillNumberId
WHERE i.BillDate >= @StartDate AND i.BillDate <= @EndDate AND i.Stypeid = @stypeid
GROUP BY i.BillNumberId

CREATE TABLE #GetSum
(
	repairtotal  NUMERIC(24, 10) ,
	repaircost  NUMERIC(24, 10) ,
	repairprofit  NUMERIC(24, 10) 
)
INSERT INTO #GetSum
SELECT ISNULL(SUM(QR.discounttotal + InOut.ptypetotal),0) AS repairtotal,									--维修总额
	   ISNULL(SUM(QR.costtotal + InOut.costtotal),0) AS repaircost,											--维修总成本
	   ISNULL(SUM(QR.discounttotal + InOut.ptypetotal - QR.costtotal - InOut.costtotal),0) AS repairprofit	--维修毛利 
FROM Billindex_CarRepair BC
INNER JOIN #Quick_Repari_RepairBill QR ON BC.BillNumberId = QR.billnumberid
INNER JOIN #InOutstocktable InOut ON BC.BillNumberId = InOut.billnumberid  
GROUP BY BC.OperationSort

CREATE TABLE #Result
(
	Data		 NUMERIC(24, 10) 	
)
INSERT INTO #Result(Data)
SELECT repairtotal  FROM #GetSum
INSERT INTO #Result(Data)
SELECT repaircost FROM #GetSum
INSERT INTO #Result(Data)
SELECT repairprofit FROM #GetSum

SELECT Data FROM #Result



DROP TABLE #GetManSTypeId, #BillNumberId, #Quick_Repari_RepairBill, #InOutstocktable, #GetSum,#Result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RepairTalkBack_BillCreate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].QP_RepairTalkBack_BillCreate
GO
/****** Object:  StoredProcedure [dbo].[QP_RepairTalkBack_BillCreate]    Script Date: 05/07/2011 14:42:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		丁超
-- Create date: 2011-05-04 14:50
-- Description:	用户维修回访单增加
-- =============================================
CREATE PROCEDURE [dbo].[QP_RepairTalkBack_BillCreate]
	@billnumberId numeric(18, 0),  --单据ID
	@etypeid   varchar(50),        --回访人ID
	@repaircontentmentdegree  varchar(200),   --维修满意度
	@compcontentmentdegree   varchar(200),    --公司满意度
	@customerquestion  varchar(2000),         --客户问题
	@dealresult  varchar(2000),                --处理意见
	@talkbackcomment  varchar(258)                --处理意见
	--@encode$--	
AS
BEGIN
	SET NOCOUNT ON;

 declare @SQL varchar(max)
 ----插入回访单明细表Qp_IntendingTalkBack_Bill
   
insert into Qp_IntendingTalkBack_Bill(BillNumberId,ETypeID,RepairContentmentDegree,CompContentmentDegree,CustomerQuestion,DealResult,Comment)     
select @billnumberId,@etypeid,@repaircontentmentdegree,@compcontentmentdegree,@customerquestion,@dealresult,@talkbackcomment
       
END

GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RM_List]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_RM_List]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：蔡志成
	日期：2010-07-19
	描述：维修套餐档案-树型表
*/
CREATE PROCEDURE QP_RM_List
(
	@OperatorId		varchar(100),		--操作员ID
	@strFullname	VARCHAR(100),		--名称
	@strUserCode	VARCHAR(300),		--名称
	@TypeId			varchar(100)		--基本信息ID
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
--DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
--            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
--EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
--
--IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


IF @strFullname='' AND @strUserCode=''
BEGIN
	
	DECLARE @SonNum int

	SELECT @SonNum = SonNum FROM dbo.QP_RepairSetMeal WHERE TypeId = @TypeId

	IF @SonNum = 0 
		SELECT * FROM QP_RepairSetMeal WHERE TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
	ELSE
		SELECT * FROM QP_RepairSetMeal WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode

END
ELSE
BEGIN
	SELECT * FROM QP_RepairSetMeal 
	WHERE FullName LIKE '%'+@strFullname+'%' AND UserCode LIKE '%'+@strUserCode+'%' AND SonNum=0
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_RM_List_Detail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_RM_List_Detail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：蔡志成
	日期：2010-07-19
	描述：维修套餐档案-树型表
*/
CREATE PROCEDURE QP_RM_List_Detail
(
	@StrTYPEID			VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON

SELECT 
	   b.RepairItemsTypeID,
	   b.StandardManHour,
	   b.CheckManHour,
	   b.ManHourExpense, 
	   a.UserCode,
	   a.FullName,
	   a.TypeID,
	   a.ItemType,
	   a.ChargeMode,
--	   CASE a.ChargeMode WHEN 0 THEN 0 WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END AS manhourexpense,
	   CASE CAST(a.ChargeMode AS VARCHAR(10)) WHEN '0' THEN '按工时' WHEN '1' THEN '标准价' WHEN '2' THEN '最高价' WHEN '3' THEN '最低价' END AS chargemodename,
	   CASE CAST(a.ItemType AS VARCHAR(10)) WHEN '0' THEN '维修项目' WHEN '1' THEN '保养项目' END AS Itemtypename
FROM QP_RepairSetMeal_Items b LEFT JOIN dbo.QP_RepairItems a ON b.RepairItemsTypeID=a.TypeID
WHERE b.TypeID=@StrTYPEID
ORDER BY a.UserCode


SELECT 
	a.PTypeID AS typeid,
	a.Qty,
	a.Price,
	a.Total,
	p.UserCode,
	p.Fullname,p.Unit1 
FROM dbo.QP_RepairSetMeal_Fittings a LEFT JOIN dbo.ptype p ON a.PTypeID=p.typeId
WHERE a.TypeID=@StrTYPEID
ORDER BY p.UserCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_SalePlanIfUsed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_SalePlanIfUsed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-08-06
--	描述：销售计划是否已经使用
---------------------------------------------
CREATE PROCEDURE QP_SalePlanIfUsed
( 
	@id			VARCHAR(MAX),
	@idtype		VARCHAR(MAX),
	@fullname	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

IF @idtype='timeid'
	BEGIN
		SELECT @fullname=FullName FROM SaleTimeTotal WHERE ID=@id
		IF @id in (select TotalID from StypeSaleAllPlan)
			BEGIN
				RAISERROR('该销售计划【%s】已经被分支机构销售计划引用，不能修改！',16,1,@fullname)RETURN -1
			END
		IF @id in (select TotalID from DtypeSaleAllPlan)
			BEGIN
				RAISERROR('该销售计划【%s】被部门销售计划中引用，不能修改！',16,1,@fullname)RETURN -1
			END
		RETURN 0
	END
DECLARE @DETIALID VARCHAR(MAX)

IF @idtype='splanid'
	BEGIN
		SELECT @fullname=FullName FROM StypeSaleAllPlan WHERE ID=@id
		IF EXISTS (SELECT *FROM DtypeSaleAllPlan WHERE STypePlanID IN (SELECT ID FROM StypeSaleplan WHERE SplanID =@id))
		BEGIN
			RAISERROR('该销售计划【%s】已经被部门销售计划引用，不能修改！',16,1,@fullname)RETURN -1
		END
		RETURN 0
	END

IF @idtype='dplanid'
	BEGIN
		SELECT @fullname=FullName FROM DtypeSaleAllPlan WHERE ID=@id
		IF EXISTS (SELECT *FROM EtypeSaleAllPlan WHERE DTypePlanID IN (SELECT ID FROM DtypeSaleplan WHERE DplanID =@id))
		BEGIN
			RAISERROR('该销售计划【%s】已经被职员销售计划引用，不能修改！',16,1,@fullname)RETURN -1
		END
		RETURN 0
	END
RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_SaveMiantenanceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].QP_SaveMiantenanceInfo
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-09-09
	描述：处理保养档案信息
*/
CREATE PROCEDURE QP_SaveMiantenanceInfo
(
	@repairautotypeid	varchar(100),	--基本信息ID
	@hightmileage		numeric(18,0),	--行驶里程上限
	@lowmileage			numeric(18,0),	--行驶里程下限
	@nType				varchar(20)	,	--类型 a.新增  m.修改 
	@id					int,
	@suggestion         varchar(max)    --拼音码
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @mileage numeric(18,0)=0
IF @lowmileage>@hightmileage
BEGIN
	SET @mileage=@lowmileage
	SET	@lowmileage=@hightmileage
	SET	@hightmileage=@mileage
END

IF @nType = 'a' 
	BEGIN
		INSERT INTO qp_miantenanceinfo
		(
			RepairAutoTypeID,
			hightMileage,
			lowMileage,
			Suggestion
		)
		VALUES
		(
			@repairautotypeid,
			@hightmileage,
			@lowmileage,
			@suggestion
		)
		IF @@ERROR<>0
			RAISERROR('添加保养档案失败！',16,1)
	END
ELSE 
	BEGIN
		UPDATE	qp_miantenanceinfo
		SET		RepairAutoTypeID=@repairautotypeid,
				hightMileage	=@hightmileage,
				lowMileage		=@lowmileage,
				Suggestion		=@suggestion
		WHERE   ID=@id
		IF @@ERROR<>0
			RAISERROR('修改保养档案失败！',16,1)	
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT  TOP 1 1 FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QP_SelAc_CashMoneyItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
	DROP PROCEDURE [dbo].[QP_SelAc_CashMoneyItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON
GO

-- ========================================================================
-- 描述：现金流量项目信息列表数据
-- 时间：2012-06-14	
-- 作者：廖晨雨
-- ========================================================================
CREATE PROC [dbo].[QP_SelAc_CashMoneyItems]
(
	@Parid			VARCHAR(50),	--父级ID
	@chvOperatorID	VARCHAR(50)		--操作人
)
--@encode$--
AS 
SET NOCOUNT ON 

--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL 
	RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE 
		@intRe INT,
		@chvMPtypeid VARCHAR(50)

SELECT @chvMPtypeid=MangerPTypeID FROM loginuser WHERE etypeid=@chvOperatorID

SELECT 
	typeid,
	ParId,
	Leveal,
	SonNum,
	SonCount,
	UserCode,
	FullName,
	sysrow 
FROM Ac_CashMoneyItems 
WHERE parid = @Parid
ORDER BY UserCode

--------	权限检查 - End		--------

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SelectRecpionIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_SelectRecpionIndex]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：毛欣蓉
	日期：2011-04-28
	描述：掉接件主表
*/

CREATE PROCEDURE Qp_SelectRecpionIndex
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@BillCode		VARCHAR(400),
	@STypeId		VARCHAR(MAX),
	@eTypeId		VARCHAR(MAX),
	@dTypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))

--职员
INSERT INTO #Etype select typeid from F_GetAllManagerBaseTypeId(@eTypeId,3,@OperatorID)

--部门
INSERT INTO #Dtype select typeid from F_GetAllManagerBaseTypeId(@dTypeId,9,@OperatorID)

--分支机构
INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

DECLARE   @SQL  VARCHAR(max)
		
SET @SQL='	
	select	bi.billnumberid,
			bi.billtype,
			bi.billdate,
			bi.billcode,
			bi.stypeid,
			bi.etypeid,
			bi.dtypeid,
			bi.comment,
			bi.btypeid,
			b.price,
			b.fullname as bfullname,
			bi.explain,
			ca.ratypeid,
			bi.checke,
			e1.fullname as checkename,
			ca.BillState,
			car.PlateNumber as rafullname,
			d1.fullname as dfullname
	from billindex bi 
	INNER JOIN Billindex_carrepair ca on bi.billnumberid=ca.billnumberid 
	INNER JOIN QP_RepairAutoInfo car on car.typeid=ca.ratypeid 
	INNER JOIN Btype b on b.typeid=bi.btypeid
	INNER JOIN Department d1 on d1.typeid=bi.dtypeid
	INNER JOIN Employee e1 on e1.typeid=bi.checke '
IF @stypeid<>'''' or @MStypeid<>'00000'
	Set @sql=@sql+' inner join #stype s on s.typeid = bi.stypeid '
IF @Etypeid<>'''' or @MEtypeid<>'00000'
	Set @sql=@sql+' inner join #etype e on ( e.typeid = bi.etypeid  ) '
IF @Dtypeid<>'''' or @MDtypeid<>'00000'
	Set @sql=@sql+' inner join #dtype d on (d.typeid = bi.dtypeid ) '

SET @SQL=@SQL+' WHERE bi.billcode like ''%'+@billcode+'%'' 
						AND bi.billdate<='''+@EndDate+''' 
						AND bi.billdate>='''+@StartDate+'''
						AND bi.billtype=195 '
		
set @sql=@sql+' and ca.BillState=2 
				order by bi.billnumberid desc'

--print(@sql)
exec(@sql)

DROP TABLE #Etype ,#Dtype , #Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_SelectRecpionPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_SelectRecpionPtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：毛欣蓉
	日期：2011-04-28
	描述：掉接件单明细
*/

CREATE PROCEDURE Qp_SelectRecpionPtype
(
	@OperatorId		VARCHAR(100),
	@BillIds		VARCHAR(max)=''
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
CREATE TABLE #Ptype 
(
	TypeID varchar(50),
	fullname varchar(200),
	usercode varchar(200),
	unit1 varchar(8),
	unit2 varchar(8),
	unitrate1  NUMERIC(24, 10) ,
	entrycode varchar(100)
)

INSERT INTO #Ptype 
	select p.typeid,p.fullname,p.usercode,p.unit1,p.unit2,p.unitrate1,p.EntryCode
	from ptype p 
	inner join  F_GetAllManagerBaseTypeId('',1,@OperatorID) b on p.typeid=b.typeid

DECLARE   @SQL 			VARCHAR(max)
		
CREATE TABLE #SplitBillNumberId
(
	BillNumberId		NUMERIC(18,0)
)	   
INSERT INTO #SplitBillNumberId(BillNumberId) SELECT A FROM dbo.f_split(@BillIds,',') WHERE ISNULL(A,'')<>''
	
	select	bi.billnumberid,
			bi.billtype,
			bi.billdate,
			bi.billcode,
			bi.stypeid,
			bi.etypeid,
			bi.dtypeid,
			yg.comment,
			bi.explain,
			yg.ptypeid,
			yg.qty,
			yg.price,
			yg.total,
			yg.Insurance,
			yg.id as receptionbillid,
			p.typeid,
			p.unit1 as unitone,
			p.unit2 as unittwo,
			p.unitrate1 as unitrate,
			0 as isunittwo,
			p.usercode,
			p.fullname,
			p.unit1 as unit,
			p.entrycode,
			case when yg.qty>isnull(ck.qty,0) then yg.qty-isnull(ck.qty,0) else 0 end as notsendqty
	from billindex bi
	INNER JOIN Qp_ReceptionBill_PType yg on bi.billnumberid=yg.billnumberid
	INNER JOIN #Ptype p on p.typeid=yg.ptypeid
	LEFT  JOIN (
			 select sum(sj.qty) as qty,sj.ReceptionBillPTypeId 
			 from Qp_ReceptionBill_FactUsePType sj 
			 INNER JOIN #PTYPE	P1 on p1.typeid=sj.ptypeid group by sj.ReceptionBillPTypeId 
	) ck  on (yg.id=ck.ReceptionBillPTypeId)
	where bi.billnumberid in (select BillNumberId from #SplitBillNumberId)
	
DROP TABLE #SplitBillNumberId,#Ptype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_SelectThreePacetsPTypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_SelectThreePacetsPTypeDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
功能：调三包索赔单的配件明细 

*/
CREATE          PROCEDURE QP_SelectThreePacetsPTypeDetail
( 
 @BillNumberId numeric(10,0),
 @Insurance	 VARCHAR(10)=''
)
--@encode$--
AS
SET NOCOUNT ON 


	SELECT  a.BillNumberId,
        a.Qty,
        a.TaxPrice,
        a.TaxTotal,
        a.InsuranceTotal,
        a.Comment,
        a.IsUnit2,
        a.Virtual,
        p.typeId,
        p.UserCode,
        p.FullName,
        a.isunit2 AS unittwo,
        a.isunit2 AS isunittwo,
        CASE a.isunit2 WHEN 1 THEN p.unit2 ELSE p.unit1 END AS unit,
        a.Comment,
        a.ID AS AID
FROM    Qp_ThreePacketsBill_PType a
        LEFT JOIN dbo.ptype p ON a.PTypeID = p.typeId    
       
WHERE a.BillNumberId=@BillNumberId
     

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_SelectThreePacetsRepairItemDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_SelectThreePacetsRepairItemDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
功能：调三包索赔单项目明细
*/
CREATE          PROCEDURE QP_SelectThreePacetsRepairItemDetail
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 



SELECT  a.BillNumberId,
        a.StandardManHour,
        a.RepairTotal,
        a.InsuranceTotal,
        a.CostTotal,
        b.fullname,
        b.typeid,
        b.ChargeMode,
        b.UserCode,
        a.CostTotal,
        a.Comment,
        a.ID AS RID
       
        
FROM    Qp_ThreePacketsBill_RepairItems a
        LEFT JOIN QP_RepairItems b ON a.repairitemstypeid = b.TypeID
       
WHERE a.BillNumberId=@BillNumberId
        


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  * FROM    dbo.sysobjects  WHERE   id = OBJECT_ID(N'[dbo].[QP_SelFr ]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
DROP PROCEDURE [dbo].[QP_SelFr ]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		丁超
-- Create date: 2011年9月19日
-- Description:	维修故障档案查询
-- =============================================
CREATE PROCEDURE QP_SelFr 
(
	  @Parid VARCHAR(50),					---父节点ID
      @chvOperatorID VARCHAR(50) = '00001'  ---操作员ID
)
--@encode$--
AS
BEGIN
	--------	权限检查 - Start	--------
    IF @chvOperatorID IS NULL 
        RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
    DECLARE @intRe INT,
        @chvMAtypeid VARCHAR(50),
        @chvMBtypeid VARCHAR(50),
        @chvMBtypeid2 VARCHAR(50),
        @chvMEtypeid VARCHAR(50),
        @chvMKtypeid VARCHAR(50),
        @chvMPtypeid VARCHAR(50),
        @chvMExpense VARCHAR(50),
        @chvMIncome VARCHAR(50),
        @chvMCapital VARCHAR(50),
        @chvMDtypeid VARCHAR(50)
    EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMAtypeid OUTPUT,
        @chvMBtypeid OUTPUT, @chvMBtypeid2 OUTPUT, @chvMEtypeid OUTPUT,
        @chvMKtypeid OUTPUT, @chvMPtypeid OUTPUT, @chvMExpense OUTPUT,
        @chvMIncome OUTPUT, @chvMCapital OUTPUT, @chvMDtypeid OUTPUT
    IF @intRe <> 0 
        RETURN @intRe
--------	权限检查 - End		--------
DECLARE @SonNum INT
DECLARE @sql VARCHAR(MAX)
CREATE TABLE #Frtype ( TypeID VARCHAR(50))

INSERT  INTO #Frtype ( TypeID )
        SELECT  typeId
        FROM    frtype
        WHERE   ParId=@Parid
SET @sql='SELECT typeid,
				 parid,
				 leveal,
				 sonnum,
				 soncount,
				 UserCode,
				 FaultExplain,
				 FaultReason,
				 XiWaMaxNumber
	      FROM frtype
	      WHERE typeid IN(SELECT typeid FROM #Frtype)
	      ORDER BY UserCode ASC'
--PRINT @sql
EXEC (@sql)
DROP TABLE #Frtype
END
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_SelP]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_SelP]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



CREATE          PROC [dbo].[QP_SelP]
    (
      @Parid VARCHAR(50),
      @ifDeleted INT = 0,   --显示停用信息
      @chvOperatorID VARCHAR(50) = '00001'
    )
--@encode$--
AS 
SET NOCOUNT ON 

--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL 
RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,
@chvMPtypeid VARCHAR(50)

SELECT @chvMPtypeid=MangerPTypeID FROM loginuser WHERE etypeid=@chvOperatorID

--------	权限检查 - End		--------

DECLARE @SonNum INT
DECLARE @sql [varchar](MAX)
DECLARE @Deleted VARCHAR(30)

CREATE TABLE #Ptype ( TypeID VARCHAR(50) )

--优化单位

CREATE TABLE #PTypeExt
(
	PtypeID			VARCHAR(50) ,
	UnitsId			INT  NULL,
	Rate			NUMERIC(24,10),
	UnitsIdName		VARCHAR(200),

	SaleUnitId		INT NULL,
	SaleUnitIdRate	DECIMAL(24, 10) NULL,
	SaleUnitIdName	VARCHAR(200),

	BuyUnitId		INT NULL,
	BuyUnitIdRate	DECIMAL(24, 10) NULL,
	BuyUnitIdName	VARCHAR(200),

	StockUnitId		INT NULL,
	StockUnitIdRate	DECIMAL(24, 10) NULL,
	StockUnitIdName	VARCHAR(200),

	AssistantUnitId		INT NULL,
	AssistantUnitIdRate	DECIMAL(24, 10) NULL,
	AssistantUnitIdName	VARCHAR(200),

	SaleUnitID1		INT NULL,
	SaleUnitRate1	DECIMAL(24, 10) NULL,
	SaleUnitID2		INT NULL,
	SaleUnitRate2	DECIMAL(24, 10) NULL,
	SaleUnitID3		INT NULL,
	SaleUnitRate3	DECIMAL(24, 10) NULL
)


INSERT INTO #PTypeExt
        ( PtypeID ,
          UnitsId ,
          Rate ,
		  UnitsIdName,
          SaleUnitId ,
          SaleUnitIdRate ,
		  SaleUnitIdName,
          BuyUnitId ,
          BuyUnitIdRate ,
		  BuyUnitIdName,
          StockUnitId ,
          StockUnitIdRate ,
		  StockUnitIdName,
          AssistantUnitId ,
          AssistantUnitIdRate ,
		  AssistantUnitIdName
        )

SELECT	A.PtypeID,
		MAX(CASE WHEN A.UnitsId=b.baseUnitId THEN a.UnitsId  END) AS unitsId,
		MAX(CASE WHEN A.UnitsId=b.baseUnitId THEN a.Rate  END) AS unitsIdRate,
			MAX(CASE WHEN U.UnitsId=b.baseUnitId THEN U.FullName  END) AS unitsIdFullname,

		MAX(CASE WHEN A.UnitsId=b.SaleUnitId THEN a.UnitsId END) AS SaleUnitId,
		MAX(CASE WHEN A.UnitsId=b.SaleUnitId THEN a.Rate END) AS SaleUnitIdRate,
		MAX(CASE WHEN U.UnitsId=b.SaleUnitId THEN U.FullName  END) AS SaleUnitIdFullname,

		MAX(CASE WHEN A.UnitsId=b.BuyUnitId THEN a.UnitsId END) AS BuyUnitId,
		MAX(CASE WHEN A.UnitsId=b.BuyUnitId THEN a.Rate END) AS BuyUnitIdRate,
		MAX(CASE WHEN U.UnitsId=b.BuyUnitId THEN U.FullName  END) AS BuyUnitIdFullname,

		MAX(CASE WHEN A.UnitsId=b.StockUnitId THEN a.UnitsId END) AS StockUnitId,
		MAX(CASE WHEN A.UnitsId=b.StockUnitId THEN a.Rate END) AS StockUnitIdRate,
		MAX(CASE WHEN U.UnitsId=b.StockUnitId THEN U.FullName  END) AS StockUnitIdFullname,

		MAX(CASE WHEN A.UnitsId=b.AssistantUnitId THEN a.UnitsId END) AS AssistantUnitId, 
		MAX(CASE WHEN A.UnitsId=b.AssistantUnitId THEN a.Rate END) AS AssistantUnitIdRate,
		MAX(CASE WHEN U.UnitsId=b.AssistantUnitId THEN U.FullName  END) AS AssistantUnitIdFullname
FROM PType_Units_Ext A
INNER JOIN (
	SELECT	typeId,
			baseUnitId,
			SaleUnitId,
			BuyUnitId,
			StockUnitId,
			AssistantUnitId 
	FROM ptype
) B ON b.typeid=a.PtypeID
INNER JOIN PType_Units U ON U.UnitsId=a.UnitsId
GROUP BY A.PtypeID

MERGE INTO #PTypeExt AS pe
USING (SELECT	pe.PtypeID,
				pe.SaleUnitID1,
				pe.SaleUnitRate1,
				pe.SaleUnitID2,
				pe.SaleUnitRate2,
				pe.SaleUnitID3,
				pe.SaleUnitRate3 
		FROM PType_AuxiliaryUnits_Ext pe
		WHERE (ISNULL(SaleUnitID1,'')<>'' OR ISNULL(SaleUnitID2,'')<>'' OR ISNULL(SaleUnitID3,'')<>'')  
		GROUP BY	pe.PtypeID,
					pe.SaleUnitID1,
					pe.SaleUnitRate1,
					pe.SaleUnitID2,
					pe.SaleUnitRate2,
					pe.SaleUnitID3,
					pe.SaleUnitRate3 
) AS ae ON pe.PtypeID=ae.PtypeID
WHEN  MATCHED
THEN UPDATE SET pe.SaleUnitID1=ae.SaleUnitID1,
				pe.SaleUnitRate1=ae.SaleUnitRate1,
				pe.SaleUnitID2=ae.SaleUnitID2,
				pe.SaleUnitRate2=ae.SaleUnitRate2,
				pe.SaleUnitID3=ae.SaleUnitID3,
				pe.SaleUnitRate3=ae.SaleUnitRate3;
--结束

IF @ifDeleted = 0 
SET @Deleted = ' AND p.deleted=0 '
ELSE 
SET @Deleted = ''

IF @chvMPtypeid<>'00000'
INSERT  INTO #PType ( typeid )
        SELECT  p.typeid
        FROM   F_BaseGetManPType(@chvOperatorID) p 
        where  p.ParId=@Parid
set  @sql = '
		SELECT DISTINCT  p.typeId,
			serial= CASE WHEN p.sonnum>0 then '''' else CASE WHEN p.ifserial=''1'' then ''强制'' else ''—'' end  end,
			unitrate = CASE WHEN p.unit2='''' then p.unit1 else p.unit2+'
    + '''/''' + '+p.unit1+' + '''(1:'''
    + '+dbo.fn_sms_format(p.unitrate1)+' + ''')'' end,
			
		   p.ParId,
		   p.leveal,
		   p.sonnum,
		   p.soncount,
		   p.CanModify,
		   p.UserCode,
		   p.FullName,
		   p.[Name],
		   p.Standard,
		   p.[Type],
		   p.Area,
		   p.Integral,
		   p.Unit1,
		   p.Unit2,
		   p.UnitRate1,
		   p.UnitRate2,
		   p.UsefulLifeMonth,
		   p.UsefulLifeDay,
		   p.Comment,
		   -- p.recPrice,
		   pp.RecAmgSTypeBuyPrice AS recPrice,-- 不再用ptype 表里面的最近进价了
		   p.deleted,
		   p.ColorGroupID,
		   p.SizeGroupID,
		   case when p.sonnum = 0 then p.entrycode else '''' end as EntryCode,
		   case when p.sonnum = 0 then p.MultEntryCode else '''' end as MultEntryCode, 
		   p.IfSerial,
		   p.PyCode,
		   p.SerialCount,
		   p.ValidDays,
		   p.XiWaMaxNumber,
		   p.DwgNo,
		   p.ImgURL,
		   p.SortID,
		   case  p.IsOm   when 0 then ''未发布'' else ''已发布''end as  IsOm,
		   p.IsOm as IsOm1,
			e.Brand,
			case e.import when ''1'' then ''进口'' when ''2'' then ''国产'' else '''' end as import,
			e.GeneralType,
			e.GeneralDwgNo,
			case e.[property] when ''0'' then ''配件'' when ''1'' then ''材料'' when ''2'' then ''低值易耗品'' end as [property],
			
			e.PackageQty,
			e.[Weight],
			e.TaxNumber,
			e.Taxrate,
			b.usercode as btypeusercode,
			e.BTypeID,
			b.fullname AS BFullname,
			e.FcUnit,
			e.FcPrice,
			pp.PreBuyPrice1,
			pp.PreBuyPrice2,
			pp.PreBuyPrice3,
			pp.PreBuyPrice4,
			pp.PreBuyPrice5,
			pp.PreSalePrice1,
			pp.PreSalePrice2,
			pp.PreSalePrice3,
			pp.PreSalePrice4,
			pp.PreSalePrice5,
			pp.PreSalePrice6,
			pp.PreSalePrice7,
			pp.PreSalePrice8,
			pp.PreSalePrice9,
			pp.PreSalePrice10,
			pp.RetailPrice,
			pp.TopSalePrice,
			pp.LowSalePrice,
			pp.TopBuyPrice,
			P.createdate,
			case when ((select   COUNT(ImgURL) as iCOUNT from PType_Picture PC where PC.ptypeid=p.typeid)>0) then ''有'' else ''无''   end  ImgURL2,
			p.stopbuy,
			(case ISNULL(p.stopbuy,0) when 0 THEN ''否'' ELSE ''是'' END) as stopbuytext,
				case when p.sonnum = 0 then dbo.F_GetUnitName(p.BaseUnitId,0) else '''' end as baseunitname,

			--pext.UnitsIdName as baseunitname,
			pext.Rate as baseunitrate,
			pext.AssistantUnitIdName as fzunitname,
			pext.AssistantUnitIdRate as fzunitrate,
			pext.BuyUnitIdName as buyunitname,
			pext.BuyUnitIdRate as buyunitrate,
			pext.SaleUnitIdName as saleunitname,
			pext.SaleUnitIdRate as saleunitrate,
			pext.StockUnitIdName as stockunitname,
			pext.StockUnitIdRate as stockunitrate,

			(select fullname from PType_Units where UnitsId=pext.SaleUnitID1) as saleunit1name,
			pext.SaleUnitRate1 as saleunit1rate,

			(select fullname from PType_Units where UnitsId=pext.SaleUnitID2) as saleunit2name,
			pext.SaleUnitRate2 as saleunit2rate,

			(select fullname from PType_Units where UnitsId=pext.SaleUnitID3) as saleunit3name,
			pext.SaleUnitRate3 as saleunit3rate,

			CASE WHEN ISNULL(P.IfSerial,0)=0 THEN ''否'' ELSE ''是'' END AS ifserialtext,
			CASE WHEN ISNULL(P.IFUSEENTRYCODE,0)=0 THEN ''否'' ELSE ''是'' END AS ifuseentrycodetext,
			isnull(p.omprice,0) as omprice,
			CASE WHEN ISNULL(P.IFUSEGOODSNUM,0)=0 THEN ''否'' ELSE ''是'' END AS ifusegoodsnumtext,
			p.BuyDefaultRate,
			p.SaleDefaultRate,
			bi.FullName as ifullname,
			p.PtypeCategoryID,
			pc.usercode as pcateusercode,
			pc.FullName as categoryname,
			p.weight as pweight,
			p.volume,
			p.iscombinationproduct,
			p.brandartypeid,
			pb.IsSys as pbsys,
			pb.usercode as pbusercode,
			pb.fullname as ptypebrandarfullname,
			p.othercomment1,
			p.othercomment2,
			p.othercomment3,
			p.othercomment4,
			p.othercomment5
		FROM ptype  p 
		LEFT JOIN PType_AuxiliaryUnits_Ext PAU ON P.TYPEID=PAU.ptypeid 
		LEFT JOIN Base_InventoryType bi on bi.NID=P.InventoryTypeID
		INNER JOIN #PTypeExt PEXT ON PEXT.ptypeid=p.typeid  '
		
IF @chvMPtypeid<>'00000'
	SET @sql=@sql+'
		INNER JOIN #ptype P1 ON P.typeid=p1.typeid '
		
SET @sql=@sql+'
		LEFT JOIN QP_PType_Ext e ON p.typeid= e.ptypeid
		LEFT JOIN PType_Price pp ON p.typeid = pp.ptypeid and p.BaseUnitId=pp.unitid
		LEFT JOIN dbo.btype b ON e.BTypeID= b.typeid  
		LEFT JOIN ptypecategory pc on p.PtypeCategoryID=pc.typeid 
		LEFT JOIN brandar_Commodity pb on p.brandartypeid=pb.typeid 
		WHERE p.parId=' + CHAR(39) + @parid + CHAR(39)
		+ @deleted
		+ '  order by p.SortID'

		--PRINT @sql
		EXEC (@sql)


DROP TABLE #Ptype,#PTypeExt
GO



if EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[QP_ToolsCreateAcount]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[QP_ToolsCreateAcount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-5-24
	描述：工具开帐
-------------------------------------------*/
CREATE PROCEDURE QP_ToolsCreateAcount
(
	@OperatorID	VARCHAR(MAX),		--操作员ID
	@STypeId	varchar(MAX),		--分支机构
	@ETypeId	varchar(MAX)='',	--经手人
	@DTypeId	VARCHAR(MAX)=''		--部门
)
--@encode$--
AS
SET NOCOUNT ON

--职员
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--部门
CREATE TABLE #GetMANDTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetMANDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

DECLARE @billdate	DATETIME,
		@billflag	VARCHAR(MAX),
		@billcode	VARCHAR(MAX),
		@billtype	VARCHAR(MAX),
		@Checke		VARCHAR(MAX),
		@InOutType	VARCHAR(MAX),
		@BillNumberId VARCHAR(MAX),
		@PtypeId	VARCHAR(MAX),
		@QTY		VARCHAR(MAX),
		@PRICE		VARCHAR(MAX),
		@ValidDate	VARCHAR(MAX),
		@DAY		VARCHAR(MAX),
		@MONTH		VARCHAR(MAX),
		@cefullname			VARCHAR(500)='',		--制单人
		@cdfullname			VARCHAR(500)=''			--部门
		
CREATE TABLE #billnumberid(ID VARCHAR(MAX))

--取开帐时间	
SELECT @billdate=StartDate FROM MonthProc WHERE period = 1	
SET @DAY=DAY(@billdate)
SET @MONTH=MONTH(@billdate)

DECLARE indexcursor CURSOR FOR 
	SELECT  ETypeID,
			STypeID,
			DTypeID,
			Checke,
			InOutType
	FROM	( 
				SELECT	(CASE InOutType	WHEN '0' THEN '0' 
										WHEN '1' THEN '2'
										WHEN '2' THEN '2' 
										WHEN '3' THEN '0'
										WHEN '4' THEN '0'
										END) AS InOutType,
						ETypeID,
						STypeID,
						DTypeID,
						Checke
				FROM	ToolIndex T
				INNER JOIN #GetManSTypeId S ON T.STypeId = S.TypeId
				INNER JOIN #GetManETypeId E ON T.ETypeId = E.TypeId
				INNER JOIN #GetMANDTypeId D ON T.DTypeId = D.TypeId
				WHERE	BillType IN ('193','194')
			) T
		GROUP BY	
			T.InOutType,
			T.DTypeID,
			T.ETypeID,
			T.STypeID,
			T.Checke
			
OPEN indexcursor

FETCH NEXT FROM indexcursor INTO @ETypeID,
								 @STypeID,
								 @DTypeID,
								 @Checke,
								 @InOutType
		
WHILE @@FETCH_STATUS=0
BEGIN
	--是否自定义单据编号
	IF EXISTS(SELECT *FROM CodeConfig WHERE Billtype IN (193,194))
	BEGIN
		SELECT @MONTH = typeid  FROM employee WHERE typeId=@ETypeId
	END
	IF @InOutType='0'
		BEGIN
			SET @billtype='193'
			SET	@billflag='GJR'
		END
	ELSE
		BEGIN
			SET @billtype='194'
			SET @billflag='GJC'
		END
	
	SELECT @cefullname = fullname  FROM employee WHERE typeId=@Checke	
	SELECT @cdfullname = fullname  FROM dbo.Department WHERE typeId=@DTypeID	
	
	--生成单据编号
	EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,@billflag,@billdate,@STypeId,@billcode OUT,@cdfullname,@cefullname
	
	--主表数据写入
	SET @BillNumberId = 0
	
	INSERT INTO ToolIndex(BillDate,BillCode,BillType,ETypeID,STypeID,DTypeID,Checke,Explain,Comment,InOutType)
	VALUES(@billdate,@billcode,@billtype,@ETypeID,@STypeID,@DTypeID,@Checke,'','上年数据结存',@InOutType)
	
	IF @@ROWCOUNT = 0
		RETURN -10
	ELSE			
		SET @BillNumberId = SCOPE_IDENTITY();
	
	--保存单据编号的种子数
	EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
	
	INSERT INTO #billnumberid (ID) VALUES(@BillNumberId)
	
	IF @InOutType='0'
		SET @InOutType='0,3,4'
	ELSE 
		SET @InOutType='1,2'
		
	--明细表数据写入
	INSERT INTO ToolBill(BillNumberId,PTypeID,Qty,Price,ValidDate,Comment,IsUnit2)
	SELECT	@BillNumberId AS BillNumberId,
			b.PTypeID,
			SUM(CASE
					WHEN i.InOutType IN (0,2) THEN Qty
					ELSE -Qty
				END
			) AS Qty,
			ISNULL(SUM( CASE i.InOutType
							WHEN 0 THEN qty*Price
							ELSE 0
						END)
					/SUM(CASE i.InOutType 
								WHEN 0 THEN Qty
						 END
						)
			,0) AS Price,
			b.ValidDate,
			'上年数据结存',
			0
	FROM	ToolIndex i
	INNER JOIN ToolBill b ON i.BillNumberId=b.BillNumberId
	WHERE  B.BillNumberId IN 
				(
					SELECT	BillNumberId 
					FROM	ToolIndex 
					WHERE	I.ETypeID=@ETypeID 
							AND I.STypeID=@STypeID 
							AND I.DTypeID=@DTypeID 
							AND I.Checke=@Checke
							AND I.InOutType in (SELECT a FROM f_split(@InOutType,','))
				)
	GROUP BY 
			b.PTypeID,
			b.ValidDate

		---读取下一行数据
		FETCH NEXT FROM indexcursor INTO @ETypeID,
										 @STypeID,
										 @DTypeID,
										 @Checke,
										 @InOutType
END

CLOSE indexcursor
DEALLOCATE  indexcursor

--删除非汇总的单据
DELETE ToolIndex WHERE BillNumberId NOT IN (SELECT ID FROM #billnumberid) AND STypeID IN (SELECT TYPEID FROM #GetManSTypeId)
DELETE ToolBill WHERE  BillNumberId NOT IN (SELECT BillNumberId FROM ToolIndex) 

--删除临时表
DROP TABLE #GetManETypeId,#GetMANDTypeId,#GetManSTypeId,#billnumberid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_AskPriceBillQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_AskPriceBillQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：Wang Wei
	日期：2010-09-13
	描述：y询价单查询
*/
/*
	修改：李灏龙
	日期：2012年2月13日11:22:25
	描述：增添查询字段，以显示商品被调用的次数，具体修改处注释：zs001
*/
/*
	修改：舒珊
	日期：2016年2月23日15:59:00
	描述：增添表头、表体自定义显示字段
*/
/*
    修改: 魏伟
    日期: 2015-05-23
    描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
    
    日期：2015-05-26
    描述：表头自定义、表体自定义分别新增10个文本自定义、5个数字自定义、1个日期型自定义
    
    修改：赵燕琴
	日期：2019-05-29
	描述： 报价状态原来取主表改成取明细表的报价状态
*/
CREATE PROCEDURE Qp_Web_AskPriceBillQuery 
(
	@OperatorID	VARCHAR(100),
	@startdate	DATETIME,
	@enddate	DATETIME,
	@dealbtypeid	VARCHAR(8000)='',
	@Ptypeid	VARCHAR(8000)='',
	@priceType	VARCHAR(5)='-1',
	@Comment	VARCHAR(MAX),
	@Stypeid    VARCHAR(8000)='00001', --分支机构
	@Dtypeid    VARCHAR(8000)='',      --部门
	@Etypeid    VARCHAR(8000)='',       --经手人,
	@shzt		VARCHAR(10)='9',					--审核状态
	@ptypecategoryid VARCHAR(MAX ),     --商品类别ID
	@IsReporting	INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
 
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @MPtypeid='-99999'
	INSERT INTO #GetManPTypeId(TypeId) 
	SELECT p.TypeId FROM F_LinePC(@OperatorID,@ptypecategoryid) p  INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
ELSE
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_ManPTypeInCategoryID(@OperatorID,@Ptypeid,@ptypecategoryid)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999' OR @MBtypeid2='-99999'
	INSERT INTO #GetManBTypeId(TypeId) 
	SELECT b.typeid FROM F_GetManDetailBType(@OperatorID) b	INNER JOIN dbo.F_GetAllBaseTypeId(@dealbtypeid,2) sb ON b.TypeId = sb.TypeId
ELSE 
	INSERT INTO #GetManBTypeId(TypeId)	SELECT typeid FROM	F_GetAllBaseTypeId(@dealbtypeid,2)


--分支机构
CREATE TABLE #Stype(TypeId	varchar(100))
IF @Stypeid<>'' OR @MStypeid='-99999'
	INSERT INTO #Stype(TypeId)  select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)
	
--部门
CREATE TABLE #Dtype(TypeId varchar(100))
IF @Dtypeid<>'' OR @MDtypeid='-99999'
    INSERT INTO #Dtype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@Dtypeid,9,@OperatorID)
    
--经手人
CREATE TABLE #Etype(TypeId varchar(100))
IF @Etypeid<>'' OR @MEtypeid='-99999'
    INSERT INTO #Etype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@Etypeid,3,@OperatorID)


	----------------------------------------多单位计算Start-------------------------------------------------------
	--DECLARE @unitrate    NVARCHAR(200),
	--		@tmptab  NVARCHAR(2000)
	--SET @tmptab='  LEFT JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') f ON b.ptypeID=f.typeID'
	--IF @unitconvert=0
	--BEGIN
	--SELECT  @unitrate='qpb.qty/f.saleunitrate'
	--END
	--IF @unitconvert=1
	--BEGIN
	--SELECT  @unitrate='qpb.qty/f.buyunitrate'
	--END
	--IF @unitconvert=2
	--BEGIN
	--SELECT  @unitrate='qpb.qty/f.stockunitrate'
	--END
	--IF @unitconvert=3
	--BEGIN
	--SELECT  @unitrate='qpb.qty'
	--END
	---------------------------------------------多单位计算End--------------------------------------------------
---------------单据审核状态--------------
CREATE TABLE #AuditingBill
(
	BillNumberId NUMERIC(18,0),
	CheckState	 VARCHAR(50),
	IfAudit      CHAR(2)
)

IF @shzt <> '9' --非全部状态(9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据)
BEGIN
	--IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @orderBillType AND IfUse = 1)
	--BEGIN
		IF @shzt = '0'	--原始单据
			INSERT INTO #AuditingBill(BillNumberId,CheckState,IfAudit)
			SELECT	B.BillNumberId,
					'原始单据' AS CheckState,
					'1 ' 
			FROM	BillIndex B			
			WHERE	B.BillDate >= @startdate
					AND B.BillDate <= @enddate
					AND B.billtype = 185
					AND NOT EXISTS
					(
						SELECT	A.billNumberId,a.IfAudit 
						FROM	AuditingBill A
						INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						INNER JOIN #stype S ON S.TypeID = F.Stypeid											
						WHERE a.BillNumberID = B.billNumberId AND BillIndexType='2'	AND f.BillType=185		
					)
		ELSE
			INSERT INTO #AuditingBill(BillNumberId,CheckState,IfAudit)
			SELECT	A.BillNumberId,
					CASE @shzt
						WHEN '1' THEN '待审核单据'
						WHEN '2' THEN '审核通过单据'
						ELSE '审核不通过单据'
					END AS CheckState,
					a.IfAudit
			FROM	AuditingBill A
			INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
			INNER JOIN #stype S ON S.TypeID = F.Stypeid
			WHERE	A.BillDate >= @startdate
					AND A.BillDate <= @enddate													
					AND F.IfUse = 1
					AND F.billtype = 185
					AND A.BillIndexType = 2
					AND A.IfAudit = CASE
										WHEN @shzt = '1' THEN '0'
										WHEN @shzt = '2' THEN '1'
										ELSE '-1'
									END		
									
	--END
END


DECLARE @Sql VARCHAR(8000)
--zs001 在原来的基础上添加x.usedsum、x.ID字段和LEFT JOIN部分
SET @Sql='
	SELECT	bi.billNumberId,
			qpb.id as CustomdetailID,
			bi.billcode,
			bi.billDate,
			bi.btypeid,
			bi.dealbtypeid,
			bi.billtype,
			--bi.DealBTypeID,
			ordqty.orderdqty,
			x.usedsum,										--调用次数
			--x.ID  AS customdetailid,						--报价表明细id  杨俊2013-04-03修改 列名重复
			qpb.ptypeid,
			qpb.qty,										--数量
			--qpb.nsaleprice,								--原币单价
			--qpb.nsaletotal,								--原币金额
			qpb.NDISCOUNTPRICE,								--原币折后单价
			qpb.NTOTAL,										--原币折后金额
			qpb.ntaxprice,									--原币含税单价
			qpb.ntaxtotal,								    --原币价税合计
			ac.FullName as currencyFullName,				--原币币别
			it.fullname as fullname,						--自由项
			ISNULL(qpb.DiscountPrice,0) As DiscountPrice ,  --单价(折后单价)
			ISNULL(qpb.Total,0) As Total,					--金额(折后金额)
			ISNULL(qpb.TaxPrice,0) As TaxPrice,				--含税单价
			ISNULL(qpb.TaxTotal,0) As TaxTotal,				--价税合计
			qpb.IfBargainOn, 								--报价状态(明细表)
			CASE
							WHEN ISNULL(AB.CheckState,'''') = '''' THEN ''原始单据''
							ELSE AB.CheckState
						END AS CheckState,
						isnull(AB.IfAudit,''1 '') as IfAudit,
			SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,
			SysDiy8_head,SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,
			SysDiy15_head,SysDiy16_head,SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,						SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,SysDiy26_head,						SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head, 
			SysDiy1, SysDiy2, SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9, SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,SysDiy17,SysDiy18,					SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,SysDiy26,SysDiy27,SysDiy28,					SysDiy29,SysDiy30,SysDiy31,SysDiy32

			
	FROM dbo.BillIndex bi 
	INNER JOIN AskPriceBill qpb ON bi.BillNumberId=qpb.BillNumberId
	LEFT JOIN (
				SELECT BillNumberID,id,sum(usedsum) AS usedsum
				FROM(
				SELECT		a.BillNumberID,a.ID,COUNT(o.billnumberid) AS usedsum
				FROM		AskPriceBill a
				LEFT JOIN	OrderBill O ON a.BillNumberID=o.AskBillNumberID AND a.ID=o.askBillID
				GROUP BY	a.BillNumberID,a.ID
				UNION ALL
				SELECT		a.BillNumberID,a.ID,COUNT(o.billnumberid) AS usedsum
				FROM		AskPriceBill a
				LEFT JOIN	buybill O ON a.BillNumberID=o.AskBillNumberID AND a.ID=o.askBillID
				GROUP BY	a.BillNumberID,a.ID
				)XX GROUP BY BillNumberID,ID
				
			  ) x ON qpb.BillNumberId = x.BillNumberID AND qpb.ID = x.ID
    LEFT JOIN (
				SELECT SUM(ISNULL(orderdqty,0)) AS ORDERDQTY,ORD.BillNumberID,ptypeid
				FROM
				(
					SELECT  CASE WHEN  a.billover <>0
								  THEN ISNULL(A.ReachQty,0) 
								  ELSE ISNULL(A.QTY,0)end orderdqty ,q.BillNumberID,A.ptypeid
								  FROM AskPriceBill Q
								  LEFT JOIN orderbill A ON q.BillNumberID=A.askBillNumberID AND q.ID=A.askBillID  
					)ORD		  
				GROUP BY ORD.BillNumberID,ptypeid
				)ordqty on ordqty.BillNumberID=bi.BillNumberId and ordqty.ptypeid=qpb.ptypeid
	LEFT JOIN Custom_BillIndex csindex on bi.billnumberid=csindex.BillId and bi.billtype=csindex.billtype
	LEFT JOIN Custom_BillDetails csdetail on bi.billnumberid=csdetail.BillId and bi.billtype=csdetail.billtype AND qpb.ID=csdetail.Detailid
	LEFT JOIN AC_CURRENCY ac ON bi.CID=ac.CID
	LEFT JOIN vWeb_ItemIDByIsCombined it ON qpb.ItemID=it.id and  qpb.IsCombined=it.iscombined
	'
	IF @shzt <> '9'
		SET @SQL = @SQL + ' INNER JOIN #AuditingBill AB ON AB.BillNumberId = bi.BillNumberId '
    ELSE
		SET @SQL = @SQL + ' LEFT JOIN (
											SELECT	A.BillNumberId,
													CASE A.IfAudit
														WHEN 0 THEN ''待审核单据''
														WHEN 1 THEN ''审核通过单据''
														ELSE ''审核不通过单据''
													END AS CheckState,
													A.IfAudit
											FROM	AuditingBill A
											INNER JOIN AuditingFlowSet F ON A.AuditingId = F.AuditingId AND F.BillType = 185
											WHERE	A.BillIndexType = 2
													AND A.BillDate >= '''+CAST(@startdate AS VARCHAR(100))+'''
													AND A.BillDate <= '''+CAST(@enddate AS VARCHAR(100))+'''
									   )AB ON AB.BillNumberId = BI.BillNumberId '			  
IF @MPtypeid='-99999' OR @Ptypeid<>'' OR @ptypecategoryid<>''
	SET @Sql=@Sql+' INNER JOIN #GetManPTypeId p ON qpb.ptypeid=p.typeid'
--IF @Comment<>''
--	SET @Sql=@Sql+' INNER JOIN ptype pcm ON pcm.typeid=qpb.ptypeid '
	
IF @MBtypeid='-99999' OR @MBtypeid2='-99999' OR @dealbtypeid<>''
	SET @Sql=@Sql+' INNER JOIN #GetManBTypeId b ON bi.dealbtypeid=b.typeid'	
	
IF @Stypeid<>'' OR @MStypeid='-99999'
   SET @Sql=@Sql+' INNER JOIN #Stype s ON bi.stypeid=s.typeid'
   
IF @Dtypeid<>'' OR @MDtypeid='-99999'
   SET @Sql=@Sql+' INNER JOIN #Dtype d ON bi.dtypeid=d.typeid'
   
IF @Etypeid<>'' OR @MEtypeid='-99999'
   SET @Sql=@Sql+' INNER JOIN #Etype e ON bi.etypeid=e.typeid'		
	
SET @Sql=@Sql+' WHERE bi.billtype=185 AND bi.Billdate>= '+CHAR(39)+CAST(@startdate AS VARCHAR(100))+CHAR(39)+' AND bi.Billdate<= '+CHAR(39)+CAST(@enddate AS VARCHAR(100))+CHAR(39)

IF @priceType<>'-1'
	SET @Sql=@Sql+' AND qpb.IfBargainOn='+@priceType
	
	
	
IF @Comment<>''
	--SET @Sql=@Sql+' AND pcm.Comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)
	SET @Sql=@Sql+' AND qpb.Comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)	
	
	
--SET @Sql=@Sql+' ORDER BY billDate desc ,billcode desc'	--默认排序：报价日期、报价单号的降序。	
--print(@Sql)
--EXEC(@Sql)
--SELECT * FROM #AuditingBill
----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
IF(@IsReporting = 0)
BEGIN
	SET @Sql=@Sql+' ORDER BY billDate desc ,billcode desc'	--默认排序：报价日期、报价单号的降序。
	PRINT @SQL
	--SELECT * FROM #GetManPTypeId
	EXEC(@SQL)
END
ELSE IF(@IsReporting = 1)
BEGIN
	CREATE TABLE #tmp_result
	(
		Costom1		VARCHAR(max),
		Costom2		VARCHAR(max),
		Costom3		VARCHAR(max),
		Costom4		VARCHAR(max),
		Costom5		VARCHAR(max),
		Costom6		VARCHAR(max),
		Costom7		VARCHAR(max),
		Costom8		VARCHAR(max),
		Costom9		VARCHAR(max),
		Costom10	VARCHAR(max),
		Costom11	VARCHAR(max),
		Costom12	VARCHAR(max),
		Costom13	VARCHAR(max),
		Costom14	VARCHAR(max),
		Costom15	VARCHAR(max),
		Costom16	VARCHAR(max),
		Costom1detail		varchar(max),
		Costom2detail		varchar(max),
		Costom3detail		varchar(max),
		Costom4detail		varchar(max),
		Costom5detail		varchar(max),
		Costom6detail		varchar(max),
		Costom7detail		varchar(max),
		Costom8detail		varchar(max),
		Costom9detail		varchar(max),
		Costom10detail		varchar(max),
		Costom11detail		varchar(max),
		Costom12detail		varchar(max),
		Costom13detail		varchar(max),
		Costom14detail		varchar(max),
		Costom15detail		varchar(max),
		Costom16detail		varchar(max),
		row_id				varchar(100)
	)
	--生成rowid
	SET @SQL = 'SELECT row_number() over (order by bi.BillnumberID) as rowid,' + SUBSTRING(@SQL,CHARINDEX('SELECT',@SQL) + 6,LEN(@SQL))
	
	SET @SQL ='SELECT * INTO #temp1 FROM (' + @Sql + ') AS A ORDER BY billDate DESC ,billcode DESC' + 
			  ' 
			   DECLARE @p1 dbo.Tb_QueryCustom  
			   INSERT INTO @p1 SELECT billnumberid,billtype,CustomdetailID,row_number() over (order by BillnumberID) from #temp1 
			   INSERT INTO #tmp_result EXEC Web_QueryCustomData @p1,2 

				--显示最终结果
				SELECT a.*,b.* 
					  FROM #temp1 a 
					  left join #tmp_result b on a.rowid=b.row_id 
						  
				DROP TABLE #temp1,#tmp_result
			   '
   -- select * from #GetManPTypeId
	EXEC (@SQL)
	
	 
END	
----------------------------------------------------------



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_WEB_BillUpFileLog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_WEB_BillUpFileLog]
GO





/*
	作者：Wang Wei		
	日期：2011-6-14
	描述：查询单据上传的日志
*/

CREATE               PROCEDURE QP_WEB_BillUpFileLog
(
	@OperatorID		VARCHAR(100),       		------------操作员id
	@startdate     	varchar(50),
	@EndDate        varchar(50),
	@EtypeId		VARCHAR(100)='',	--操作员
	@FileUpEtypeID      VARCHAR(100)='',--附件上传人
	@billnumberid	VARCHAR(100),
	@guid			VARCHAR(600),
	@billindextype	VARCHAR(10)	
)
--@encode$--
AS

SET ANSI_WARNINGS OFF
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL VARCHAR(MAX)
SET @SQL='
SELECT	l.OperateDate,
		l.ETypeId,
		l.logtype,
		l.FileName,
		CAST(l.FileSize/1024 AS NUMERIC(18,0)) AS sizek,
		l.FileComment,
		l.FileUpEtype,
		l.FileUpTime,
		l.BillType,
		(
			CASE WHEN  l.BillNumberId<>-1 
				THEN 
					CASE l.billindextype
						WHEN 0 THEN (SELECT TOP 1 billcode FROM billindex b where b.billnumberid=l.billnumberid)
						WHEN 1 THEN (SELECT TOP 1 billcode FROM orderindex ob where ob.billnumberid=l.billnumberid)
						WHEN 2 THEN (SELECT TOP 1 billcode FROM LendIndex lb where lb.billnumberid=l.billnumberid)
					ELSE ''''
					END	
			ELSE '''' END
		) as billcode
FROM	BillAttachFilesLog l
WHERE   l.OperateDate>='+CHAR(39)+@startdate+CHAR(39)+'
		AND l.billindextype='+CHAR(39)+@billindextype+CHAR(39)+'
		AND l.OperateDate<='+CHAR(39)+@EndDate+CHAR(39)+'
'
if @EtypeId<>'' SET @SQL=@SQL+' AND l.Etypeid='+CHAR(39)+@EtypeId+CHAR(39)
if @EtypeId<>'' SET @SQL=@SQL+' AND l.FileUpEtypeID='+CHAR(39)+@FileUpEtypeID+CHAR(39)
if @billnumberid<>'' SET @SQL=@SQL+' AND l.billnumberid='+CHAR(39)+@billnumberid+CHAR(39)
if @billnumberid='-1' AND @guid<>''  SET @SQL=@SQL+' AND l.billGuid='+CHAR(39)+@guid+CHAR(39)

SET @SQL=@SQL+' ORDER by l.OperateDate desc'
Exec (@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_BirthdayALert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_BirthdayALert]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_BirthdayALert (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @intDay int=0,
   @chvSortFild varchar(50)  ,				--排序字段
   @chvSortType	varchar(10)				--排序方式
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Btype(typeid VARCHAR(50))

--往来单位    
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetManDetailBType(@OperatorID)


-- 取得当前日期
DECLARE  @TotDay varchar(200)
	SET @TotDay = Convert(varchar(20),year(GetDate())) +'-'+Convert(varchar(20),Month(GetDate()))+'-'+Convert(varchar(20),Day(GetDate()))

-- 取得当前日期加一定的天数后的新的日期
DECLARE  @TotDay1 Datetime
	SET @TotDay1=DATEADD(Day,@intDay,@TotDay)

DECLARE  @TotDayAdd varchar(200)
	SET @TotDayAdd = Convert(varchar(20),year(@TotDay1)) +'-'+Convert(varchar(20),Month(@TotDay1))+'-'+Convert(varchar(20),Day(@TotDay1))

IF(@chvSortFild='') 
   SET @chvSortFild = 'A.VipCardCode'
IF(@chvSortType='')
   SET @chvSortType = 'ASC'

DECLARE @SQL varchar(4000)
SET @SQL='SELECT A.VipCardID,
                 B.VipCardTypeID,
                 A.RATypeID,
                 A.BTypeID,
                 A.CarType,
                 A.VipCardCode,
                 A.Btel,
                 A.Bname,
                 A.Bbirthday,
                 A.deleted AS deleted,
                 B.TypeName AS TypeName,
				 CASE 
					WHEN A.deleted = 0 THEN ''启用''
					WHEN A.deleted = 2 THEN ''停用''
					WHEN A.deleted = 3 THEN ''挂失''
					ELSE ''启用''
				 END AS zt,	
                 A.Comment AS Comment
             FROM  nVipCardSign   A
                   INNER JOIN nVipCardSet B ON A.VipCardTypeID=B.VipCardTypeID  '

           IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	       SET @SQL=@SQL + ' INNER JOIN  #Btype BB ON  A.BTypeID=BB.typeid '
IF(year(GetDate())=year(@TotDayAdd))
BEGIN
	IF(ISNULL(@intDay,0)>=0)
	SET @SQL=@SQL+ '   WHERE  Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) >=Convert(datetime,'+char(39)+@TotDay+char(39)+')
	                          AND Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) <=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+') ' 
	ELSE
	SET @SQL=@SQL+ '   WHERE  Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) >=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+')
	                          AND Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) <=Convert(datetime,'+char(39)+@TotDay+char(39)+') ' 
END
ELSE
BEGIN
    IF(ISNULL(@intDay,0)>=0)
    BEGIN
    SET @TotDayAdd=Convert(varchar(20),year(GetDate())) +'-'+Convert(varchar(20),Month(@TotDayAdd))+'-'+Convert(varchar(20),Day(@TotDayAdd))
	SET @SQL=@SQL+ '   WHERE  Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) >=Convert(datetime,'+char(39)+@TotDay+char(39)+')
	                          AND Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday)))<=Convert(datetime,Convert(varchar(20),year(GetDate()))+''-12-31'') 
                           OR Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday)))>=Convert(datetime,Convert(varchar(20),year(GetDate()))+''-01-01'') 
                              AND Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) <=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+')  ' 
    END
    ELSE
    BEGIN
    SET @SQL=@SQL+ '   WHERE  Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) >=Convert(datetime,Convert(varchar(20),year(GetDate()))+''-01-01'')
	                          AND Convert(datetime,Convert(varchar(20),year(GetDate()))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) <=Convert(datetime,'+char(39)+@TotDay+char(39)+') 
                           OR Convert(datetime,Convert(varchar(20),year('''+@TotDayAdd+'''))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday))) >=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+')
                              AND Convert(datetime,Convert(varchar(20),year('''+@TotDayAdd+'''))+''-'' + Convert(varchar(20),Month(A.Bbirthday))+''-'' + Convert(varchar(20),Day(A.Bbirthday)))<=
                              Convert(datetime,'''+Convert(varchar(20),year(@TotDayAdd))+'-12-31'')' 
    END
END

SET @SQL=@SQL+ ' ORDER BY  ' + @chvSortFild + '  ' +  @chvSortType
--PRINT @SQL RETURN     
EXEC(@SQL)        
           
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QP_Web_BtypeBuySort]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[QP_Web_BtypeBuySort]
GO

/*
供货商采购排行榜
*/




CREATE  PROCEDURE QP_Web_BtypeBuySort
(
	@StartDate	VARCHAR(30), 		--  2、查询起始时间
	@EndDate	VARCHAR(30),		--  3、查询结束时间
	@PTypeId	VARCHAR(MAX),		--  4、商品类别查询范围父节点 ID		
	@BTypeId	VARCHAR(MAX),		--  5、结算单位类别查询范围父节点 ID
	@dealbtypeid VARCHAR(MAX),      --  往来单位类别查询范围父节点 ID    
	@ETypeId	VARCHAR(MAX),		--  6、职员类别查询范围父节点 ID
	@KTypeId	VARCHAR(MAX),		--  7、仓库类别查询范围父节点 ID		
	@UserCode	VARCHAR(200)= '',   	--  8、编号过滤条件
	@FullName	VARCHAR(200)= '',   	--  9、全名过滤条件
	@OperatorID	VARCHAR(50),		--  11、操作员 ID（作权限范围检查用）
	@Comment	VARCHAR(30),		--  12、说明
	@ZY		VARCHAR(30),		--  13、摘要
	@chkPf		CHAR(1)='0',
	@chkDx		CHAR(1)='0',       	--  是否显示代销
	@Billtype	VARCHAR(200),		--  单据类型
	@DTypeId	VARCHAR(MAX)='',	 	--  部门ID	
	@stypeid	VARCHAR(MAX),
	@ptypecategoryid    VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


IF @PtypeID=''
	SET @PtypeID='00000'
IF @BtypeID=''
	SET @BtypeID='00000'

IF @dealbtypeid=''
	SET @dealbtypeid='00000'	

CREATE TABLE #PType (TypeID VARCHAR(50))
CREATE TABLE #Btype (TypeID VARCHAR(50))
CREATE TABLE #dealBtype (TypeID VARCHAR(50))
CREATE TABLE #Etype (TypeID VARCHAR(50))
CREATE TABLE #Ktype (TypeID VARCHAR(50))
CREATE TABLE #Dtype (TypeID VARCHAR(50))
CREATE TABLE #STYPE (TypeID VARCHAR(50))
--商品
IF NOT (@PTypeID ='00000' AND @MPtypeid = '00000' AND @ptypecategoryid='')
	INSERT INTO #PType(typeid) SELECT TypeId FROM F_ManPTypeInCategoryID (@OperatorID,@PtypeID,@ptypecategoryid)
		
--结算单位    
IF NOT (@BtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	INSERT INTO #Btype(typeid)SELECT typeid FROM F_GetAllManagerBaseTypeId(@BtypeID,2,@OperatorID) 

--往来单位
--IF NOT (@dealBtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
INSERT INTO #dealBtype(typeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealBtypeID,2,@OperatorID)

--职员
IF NOT (@EtypeID ='00000' AND @MEtypeid = '00001')
	INSERT INTO #Etype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@EtypeID,3,@OperatorID)

--分支机构
IF NOT (@STypeID ='00000' AND @MStypeid = '00000')
INSERT INTO #STYPE(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID)

--仓库
IF NOT (@KTypeID ='00000' AND @MKtypeid = '00000')
BEGIN
	INSERT INTO #Ktype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@KTypeID,4,@OperatorID)
	IF @chkDx='1' OR @KTypeID='' -- 全部仓库或部分仓库显示代销数据
		INSERT INTO #Ktype VALUES( '10000')
END

--部门
IF NOT (@DtypeID ='00000' AND @MDtypeid = '00000')
BEGIN
	INSERT INTO #Dtype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@DtypeID,9,@OperatorID)
	IF @DTypeId = ''
		INSERT INTO #Dtype SELECT ''
END

DECLARE @tempSql VARCHAR(2000) = ''
DECLARE @SQLWhere VARCHAR(max)=''


CREATE TABLE #temp(typeid VARCHAR(50)) -- 存放筛选基本信息ID
IF @FullName<>''
	SET @tempSql += ' AND '+@FullName
	
IF @UserCode<>''
	SET @tempSql += ' AND '+@UserCode

IF @tempSql<>''
BEGIN
	SET @tempSql=' INSERT INTO #temp(typeid) select typeid from btype b where b.sonnum =0 and b.deleted =0 '+@tempSql
	EXEC(@tempSql)
	DELETE FROM #btype WHERE typeid NOT IN (SELECT typeid FROM #temp)
	DELETE FROM #dealbtype WHERE typeid NOT IN (SELECT typeid FROM #temp)
END

CREATE TABLE [dbo].[#Billtype] (
	[Billtype] VARCHAR(200)
)
INSERT INTO #Billtype SELECT a AS Billtype FROM dbo.f_split(@Billtype,',')
CREATE TABLE #BillIndex(
	BillNumberId NUMERIC(10, 0) 
)


-----------CLD
SET @tempSql='INSERT INTO #BillIndex(BillnumberID) 
						SELECT b.BillnumberID  
						FROM BillIndex b  
	                        INNER JOIN #Billtype n ON  b.billtype=n.billtype '

	IF NOT (@BtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQLWhere=@SQLWhere+' INNER JOIN #Btype bt ON  b.btypeid=bt.typeid  '
	
	IF NOT (@dealBtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQLWhere=@SQLWhere+' INNER JOIN #dealBtype bt1 ON  b.dealbtypeid=bt1.typeid  '
	
	IF NOT (@ETypeId = '' AND @METypeId = '00001')
	SET @SQLWhere=@SQLWhere+' INNER JOIN #Etype e  ON  b.etypeid=e.typeid '

	IF NOT (@DTypeId = '' AND @MDtypeid='00000')	 
	SET @SQLWhere=@SQLWhere+' INNER JOIN #Dtype d  ON  b.DtypeID=d.typeid ' 
	
	IF NOT (@STypeId = '' AND @MStypeid='00000')	 
	SET @SQLWhere=@SQLWhere+' INNER JOIN #Stype S ON  b.StypeID=S.typeid ' 
	               
	SET @SQLWhere=@SQLWhere+' WHERE b.BillDate>='''+@StartDate+''' AND b.BillDate<='''+@EndDate+'''  
						    AND b.RedWord=0 
						    AND b.Draft =0  
						    AND b.ifYearBill= 0 '
	
	IF @Comment <> ''
		SET @SQLWhere += ' AND b.explain   LIKE ''%'+@Comment +'%'''
	
	IF @ZY <> ''
		SET @SQLWhere += 'AND b.Comment  LIKE ''%'+@ZY +'%'''
					
    EXEC(@tempSql+@SQLWhere)
-----------CLD

--------------------------------------------------------暂估开票单据的处理 ------------------开始
CREATE TABLE #ZGKPBillIndex(
	BillNumberId numeric(10, 0) 
)

SET @tempSql='		INSERT INTO #ZGKPBillIndex(BillnumberID)    
				SELECT b.BillnumberID  
				FROM ReceiptBillIndex b 
                  INNER JOIN  #Billtype n ON b.billtype =n.billtype '

EXEC (@tempSql+@SQLWhere)

                
--------------------------------------------------------暂估开票单据的处理 ------------------结束

-- 价保、返利单据临时表ID，只管辖非红冲单据
CREATE TABLE #BillIndex1(
	BillNumberId NUMERIC(10, 0),
	dealBtypeId  VARCHAR (50),
	EtypeId  VARCHAR (50),
	isini    BIT
)
IF  @chkPf ='1' 
BEGIN
-----CLD
SET @tempSql='INSERT INTO #BillIndex1(BillnumberID,dealBtypeid,Etypeid,isini) 
            SELECT b.BillnumberID,
                   b.dealbtypeid,
                   b.etypeid,isini 
            FROM BillIndex b '

        IF NOT (@BtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
        SET @tempSql=@tempSql + ' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '
        
        IF NOT (@dealBtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @tempSql=@tempSql + ' INNER JOIN #dealBtype bt1 ON b.dealbtypeid=bt1.typeid '

        IF NOT (@ETypeId = '' AND @METypeId = '00001')
        SET @tempSql=@tempSql + ' INNER JOIN #Etype e  ON b.etypeid=e.typeid '

        IF NOT (@DTypeId = '' AND @MDtypeid='00000')	 
        SET @tempSql=@tempSql + ' INNER JOIN #Dtype d  ON b.DtypeID=d.typeid '
        
        IF NOT (@STypeId = '' AND @MStypeid='00000')	 
		SET @tempSql=@tempSql+' INNER JOIN #Stype S ON  b.StypeID=S.typeid ' 

        SET @tempSql=@tempSql + ' WHERE b.billtype in (150,151) 
						          AND b.BillDate>='''+@StartDate+''' AND b.BillDate<='''+@EndDate+''' 
						          AND b.RedWord=0 
						          AND b.Draft =0 
						          AND b.ifYearBill= 0 
						          AND b.isini=0 '
						          
		IF @Comment <> ''
			SET @tempSql += ' AND b.explain LIKE ''%'+ @Comment+'%'' '
		
		IF @ZY <> ''
			SET @tempSql += ' AND b.Comment  LIKE ''%'+@ZY +'%'' '	
		
EXEC (@tempSql)
--CLD
		
END

	
CREATE TABLE #InoutStockTable(
	BillNumberId NUMERIC(10, 0) ,
	BillType NUMERIC(4,0),
	PtypeId VARCHAR (50),
	BtypeId VARCHAR (50),
	Qty  NUMERIC(24, 10) ,
	Price  NUMERIC(24, 10) ,
	Total  NUMERIC(24, 10) ,
	TaxTotal  NUMERIC(24, 10) ,
	giftqty  NUMERIC(24, 10) 
)

 -----CLD
SET @tempSql='INSERT INTO #InoutStockTable(BillnumberID,BillType,PtypeID,BtypeID,Qty,Price,Total,TaxTotal,giftqty)
                     SELECT a.BillnumberID,
                            a.BillType,
                            a.PtypeID,
                            a.BtypeID,
                            a.Qty,Price,
                            Convert( NUMERIC(24, 10) ,a.Total),
                            Convert( NUMERIC(24, 10) ,a.TaxTotal),
                            case when  a.isgift=1 then a.Qty else 0  end
						FROM #Billindex b 
						     INNER JOIN InoutStockTable a ON a.BillnumberID=b.BillnumberID AND a.billtype <> 400 AND a.billtype<>401 AND a.billtype <> 404 /*剔除暂估类单据,后面单独统计*/  '

    IF NOT (@PTypeID ='00000' AND @MPtypeid = '00000' AND @ptypecategoryid='')
	SET @tempSql=@tempSql +' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
    
    IF NOT (@KTypeID='' AND @MKtypeid='00000')
	SET @tempSql=@tempSql +' INNER JOIN #Ktype k ON a.ktypeid=k.typeid '
	
	IF NOT (@STypeId = '' AND @MStypeid='00000')	 
	SET @tempSql=@tempSql+' INNER JOIN #Stype S ON  A.StypeID=S.typeid ' 
EXEC (@tempSql)
-----CLD
---------------------------------------------------暂估类单据数据插入--开始--------------------------------------------------------------	
	DECLARE @RKSQL VARCHAR(MAX)=''
	
	SET @RKSQL+='	
			INSERT INTO #InoutStockTable(BillnumberID,BillType,PtypeID,BtypeID,Qty,Price,Total,TaxTotal,giftqty)
			/*暂估入库单数据*/
			SELECT a.BillnumberID,
				  c.BillType,
				  a.PtypeID,
				  c.DealBTypeID AS BtypeID,
				  (a.qty-a.InvoiceQty) as Qty, /*采购数量*/
				  a.DiscountPrice as price,  /*折后单价*/
				  CASE WHEN a.InvoiceQty=0 THEN a.Total ELSE (a.qty-a.InvoiceQty)*a.DiscountPrice  END as Total, /*折后金额*/
				  CASE WHEN a.InvoiceQty=0 THEN a.TaxTotal ELSE (a.qty-a.InvoiceQty)*a.TaxPrice END as TaxTotal, /*价税合计*/
				  case when  a.isgift=1 then (a.qty-a.InvoiceQty) else 0  end as giftqty /*单据赠品数量*/
			FROM #Billindex b 
			INNER JOIN AppraisalBill a ON a.BillnumberID=b.BillnumberID
			INNER JOIN Billindex c ON b.BillnumberID=c.BillnumberID
	   		INNER JOIN ptype p1 on a.ptypeid=  p1.typeid
	   	
			' 
			IF NOT (@PTypeID ='00000' AND @MPtypeid = '00000' AND @ptypecategoryid='')
				SET @RKSQL=@RKSQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
			IF NOT (@KTypeId='' AND @MKtypeid='00000')
				SET @RKSQL=@RKSQL+' INNER JOIN #Ktype k ON a.ktypeid=k.typeid '
				
DECLARE @THSQL VARCHAR(MAX)=''
SET @THSQL+=' UNION ALL
			/*暂估退货单数据*/
			SELECT a.BillnumberID,
				  c.BillType,
				  a.PtypeID,
				  c.DealBTypeID AS BtypeID,
				  -(a.qty-a.InvoiceQty) as Qty, /*采购数量*/
				   a.DiscountPrice  as price,  /*折后单价*/
				  CASE WHEN a.InvoiceQty=0 THEN -a.Total ELSE -(a.qty-a.InvoiceQty)*a.DiscountPrice  END as Total, /*折后金额*/
				  CASE WHEN a.InvoiceQty=0 THEN -a.TaxTotal ELSE -(a.qty-a.InvoiceQty)*a.TaxPrice END as TaxTotal, /*价税合计*/
				  case when  a.isgift=1 then -(a.qty-a.InvoiceQty) else 0  end as giftqty /*单据赠品数量*/
			FROM #Billindex b 
			INNER JOIN AppraisalBackBill a ON a.BillnumberID=b.BillnumberID
			INNER JOIN Billindex c ON b.BillnumberID=c.BillnumberID
	   		INNER JOIN ptype p1 on a.ptypeid=  p1.typeid
			
			' 
			IF NOT (@PTypeID ='00000' AND @MPtypeid = '00000' AND @ptypecategoryid='')
				SET @THSQL=@THSQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
			IF NOT (@KTypeId='' AND @MKtypeid='00000')
				SET @THSQL=@THSQL+' INNER JOIN #Ktype k ON a.ktypeid=k.typeid' 
DECLARE @KPSQL VARCHAR(MAX)=''
SET @THSQL+=' UNION ALL
			/*采购暂估开票数据*/
			SELECT a.BillnumberID,
				  c.BillType,
				  a.PtypeID,
				  c.DealBTypeID AS BtypeID,
				  a.qty as Qty, /*采购数量*/
				  a.price,  /*折后单价*/
				  a.Total, /*折后金额*/
				  a.TaxTotal, /*价税合计*/
				  case when  a.isgift=1 then a.qty else 0  end as giftqty /*单据赠品数量*/ 
			FROM #ZGKPBillIndex b 
			INNER JOIN ReceiptBill a ON a.BillnumberID=b.BillnumberID
			INNER JOIN ReceiptBillIndex c ON b.BillnumberID=c.BillnumberID
	   		INNER JOIN ptype p1 on a.ptypeid=  p1.typeid
			' 
			IF NOT (@PTypeID ='00000' AND @MPtypeid = '00000')
				SET @KPSQL=@KPSQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
			IF NOT (@KTypeId='' AND @MKtypeid='00000')
				SET @KPSQL=@KPSQL+' INNER JOIN #Ktype k ON a.ktypeid=k.typeid '

--有暂估类单据才执行@zgSQL
IF EXISTS(SELECT TOP 1 1 FROM #Billtype WHERE Billtype IN ('400','401','404'))
BEGIN
	EXEC (@RKSQL+@THSQL+@KPSQL)

END				

---------------------------------------------------暂估类单据数据插入--结束--------------------------------------------------------------	

DECLARE @PRICE_SQL VARCHAR(2000)   		-- 价保SQL语句
DECLARE @ADVANTAGE_SQL VARCHAR(2000)    -- 返利SQL语句

	
	IF NOT (@PTypeID ='00000' AND @MPtypeid = '00000' AND @ptypecategoryid='')
	BEGIN
		SET @PRICE_SQL ='SELECT Distinct b.BillnumberID,b.dealBtypeID,b.EtypeID,A.ID,A.PtypeID,Convert( NUMERIC(24, 10) ,A.Total) as PriceTotal  
						From PriceProtectBill A,#Billindex1 b ,#Ptype p
						where  A.BillnumberID =B.billnumberID  AND a.PtypeID=p.typeid'
		SET @ADVANTAGE_SQL = 'SELECT B.dealBtypeID,Sum(Convert( NUMERIC(24, 10) ,A.Total)) as AdvantageTotal 
							From Advantage A,#Billindex1 b ,#ptype p
							WHERE  A.BillnumberID =B.billnumberID AND a.ptypeid=p.typeid'
	END
	ELSE
	BEGIN
		SET @PRICE_SQL ='SELECT Distinct b.BillnumberID,b.dealBtypeID,b.EtypeID,A.ID,A.PtypeID,Convert( NUMERIC(24, 10) ,A.Total) as PriceTotal  
						From PriceProtectBill A,#Billindex1 b
						where  A.BillnumberID =B.billnumberID '
		SET @ADVANTAGE_SQL = 'SELECT B.dealBtypeID,Sum(Convert( NUMERIC(24, 10) ,A.Total)) as AdvantageTotal 
							From Advantage A,#Billindex1 b
							WHERE  A.BillnumberID =B.billnumberID '
	END
	
	
DECLARE @SQL_WHERE VARCHAR(2000)=''

DECLARE @sql VARCHAR(MAX),
		@where_sql VARCHAR(MAX),
		@length VARCHAR(2)


	SET @PRICE_SQL 	   = 'INSERT INTO #PRICE_TABLE SELECT Y.dealBtypeID,sum(Y.PriceTotal) as PriceTotal FROM ('+@PRICE_SQL+') Y GROUP BY Y.dealBtypeID'
	SET @ADVANTAGE_SQL = 'INSERT INTO #ADVANTAGE_TABLE '+@ADVANTAGE_SQL+' GROUP BY B.dealBtypeID'

CREATE TABLE #PRICE_TABLE
(
typeID VARCHAR(50),
PriceTotal  NUMERIC(24, 10) 
)

CREATE TABLE #ADVANTAGE_TABLE
(
typeID VARCHAR(50),
AdvantageTotal  NUMERIC(24, 10) 
)


ALTER TABLE #PType ADD AdvantageTotal  NUMERIC(24, 10) 
ALTER TABLE #PType ADD PriceTotal  NUMERIC(24, 10) 

ALTER TABLE #dealBType ADD AdvantageTotal  NUMERIC(24, 10) 
ALTER TABLE #dealBType ADD PriceTotal  NUMERIC(24, 10) 

DECLARE @SQL1 VARCHAR(1000)

IF  @chkPf ='1' 
BEGIN
	EXEC(@PRICE_SQL)
	EXEC(@ADVANTAGE_SQL)
	
		SET @SQL1 ='UPDATE #dealBType SET PriceTotal =ISNULL(b.PriceTotal,0)
		FROM #dealBType a INNER JOIN #PRICE_TABLE b 
		on a.typeid=b.typeid '
		EXEC(@SQL1)
		SET @SQL1 ='UPDATE #dealBType SET AdvantageTotal =ISNULL(b.AdvantageTotal,0)
		FROM #dealBType a INNER JOIN #ADVANTAGE_TABLE b 
		on a.typeid=b.typeid '
		EXEC(@SQL1)
END


		SELECT @sql='
			SELECT 		
					b.TypeID AS btypeid,
					SUM(Case WHEN a.BillType=145 Then Convert( NUMERIC(24, 10) ,-1*a.Qty) Else Convert( NUMERIC(24, 10) ,a.qty) End) AS Sum_Qty,
					SUM(Case WHEN a.BillType=145 Then Convert( NUMERIC(24, 10) ,-1*a.Total) Else Convert( NUMERIC(24, 10) ,a.Total) End) AS Sum_Total,
					SUM(CAST(Case WHEN a.BillType=145 Then -a.taxtotal ELSE a.taxtotal END as  NUMERIC(24, 10) )) AS Sum_TaxTotal,
					ZeroPriceQty = SUM(
										CASE 
											WHEN a.Price=0 AND a.BillType = 145 THEN ABS(a.Qty)
											WHEN a.Price=0 THEN a.Qty
											ELSE 0
										END
								   ) ,
					isnull(b.AdvantageTotal,0) as AdvantageTotal,
					isnull(b.PriceTotal,0) as PriceTotal,
					SUM(Case WHEN a.BillType=145 Then Convert( NUMERIC(24, 10) ,-1*a.giftQty) Else Convert( NUMERIC(24, 10) ,a.giftQty) End) AS giftQty
	        FROM 	#InOutstocktable a,
					#dealBtype b
	        WHERE 	a.BtypeId=b.typeId 
	      			'

		SET @sql =@sql +' GROUP BY b.TypeId,b.AdvantageTotal,b.pricetotal'

SET @sql='SELECT btypeid,
				  Sum_Qty  AS Sum_Qty,
			      giftQty  AS gift_qty,
				Sum_Total,Sum_TaxTotal,ZeroPriceQty,AdvantageTotal,PriceTotal,
                 CASE WHEN ISNULL(sum_qty,0)=0 THEN 0 ELSE ISNULL(sum_total,0)/ISNULL(sum_qty,1) END AS price,
                 ISNULL(sum_taxtotal,0)-ISNULL(sum_total,0) AS taxge FROM ('+@sql+')  Y order by sum_total desc '

 		
PRINT(@SQL)
EXEC(@sql)

DROP TABLE #Billtype,#temp,#Ptype,#Btype,#Etype,#Ktype,#Dtype,#Billindex,#Billindex1,#InoutStocktable,#ADVANTAGE_TABLE,#PRICE_TABLE,#STYPE





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_BuyPriceAnalysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_BuyPriceAnalysis]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*-----------------------------------------
	作者：毛欣蓉
	日期：2010-08-13
	描述：进价分析
--------------------------------------------*/

CREATE    PROCEDURE QP_Web_BuyPriceAnalysis
(
	@OperatorId		varchar(100),
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@PType			varchar(256),
	@flag           int,			--查询类型 1是查询表体数据 0是查询表头数据
	@stypeid		varchar(max),
	@isap           int	
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @OperatorId

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

IF @flag=0
BEGIN
	DECLARE @recsaleprice  NUMERIC(24, 10) 
	DECLARE @recbuyprice  NUMERIC(24, 10)  
	DECLARE @maxprice  NUMERIC(24, 10) 
	DECLARE @minprice  NUMERIC(24, 10) 
	
	SET @recsaleprice=0 
	SET @recbuyprice=0 
	SET @maxprice=0
	SET @minprice=0

	CREATE TABLE #returntable
	(
		recsaleprice  NUMERIC(24, 10) ,--最近销售价
		recbuyprice  NUMERIC(24, 10) , --最近进价
		maxprice  NUMERIC(24, 10) ,    --期间最高价	
		minprice  NUMERIC(24, 10)      --期间最低价
	)

	--最近售价
	SET @recsaleprice=(SELECT top 1 discountprice
				FROM (
						(
							SELECT	discountprice,
									b.billnumberid
							FROM	billindex b 
									inner join RetailBill s  on b.billnumberid=s.billnumberid
									INNER JOIN #GetManSTypeId MS ON B.Stypeid = MS.TypeId
							WHERE	s.ptypeid=@ptype 
									and b.billtype=305  
									and b.ifcheck='t' 
									and b.redword=0
						)
						union all
						(
							SELECT 	discountprice,
									b.billnumberid 
							FROM	billindex b 
							inner join salebill s  on b.billnumberid=s.billnumberid
							INNER JOIN #GetManSTypeId MS ON B.Stypeid = MS.TypeId
							WHERE	s.ptypeid=@ptype 
									and  b.billtype=11 
									and b.ifcheck='t' 
									and b.redword=0
						)
		
						
					)as x  order by x.billnumberid desc)
					
	 IF(@isap = 1)
	 BEGIN
	    SET @recsaleprice=(SELECT top 1 discountprice
				FROM (
						
						(
							SELECT 	discountprice,
									b.billnumberid 
							FROM	billindex b 
							inner join SendBill   s  on b.billnumberid=s.billnumberid
							INNER JOIN #GetManSTypeId MS ON B.Stypeid = MS.TypeId
							WHERE	s.ptypeid=@ptype 
									and  b.billtype=402
									and b.ifcheck='t' 
									and b.redword=0
						)
					)as x  order by x.billnumberid desc)
	 END			
	 
	--最近进价
	SET @recbuyprice=(SELECT top 1 discountprice
				FROM (
						(
							SELECT	discountprice,
									b.billnumberid
							FROM	billindex b 
									inner join dbo.BuyBill s  on b.billnumberid=s.billnumberid
									INNER JOIN #GetManSTypeId MS ON B.Stypeid = MS.TypeId
							WHERE	s.ptypeid=@ptype 
									and b.billtype=34  
									and b.ifcheck='t' 
									and b.redword=0
						)
					)as x  order by x.billnumberid desc)
					
	 IF(@isap = 1)
	 BEGIN
	    SET @recbuyprice=(SELECT top 1 discountprice
				FROM (
						
						(
							SELECT 	discountprice,
									b.billnumberid 
							FROM	billindex b 
							inner join dbo.AppraisalBill   s  on b.billnumberid=s.billnumberid
							INNER JOIN #GetManSTypeId MS ON B.Stypeid = MS.TypeId
							WHERE	s.ptypeid=@ptype 
									and  b.billtype=400
									and b.ifcheck='t' 
									and b.redword=0
						)
					)as x  order by x.billnumberid desc)
	 END			
	
	--期间最高价和最低价
	SELECT	@maxprice=max(discountprice), 
			@minprice=min(discountprice)
	FROM
	(
	select discountprice from	billindex b
	inner join buybill s on b.billnumberid=s.billnumberid
	INNER JOIN #GetManSTypeId MS ON B.Stypeid = MS.TypeId
	WHERE	b.IfCheck = 't' 
			and b.redword=0 
			and s.ptypeid=@ptype 
			and billtype=34
			AND (@startdate='' or b.billdate>=@startdate)
			AND (@enddate='' or b.billdate<=@enddate) 
			


   ) a
   
   IF(@isap = 1)
   BEGIN
   SELECT	@maxprice=max(discountprice), 
			@minprice=min(discountprice)
	FROM
	(
	select discountprice from	billindex b
	inner join AppraisalBill s on b.billnumberid=s.billnumberid
	INNER JOIN #GetManSTypeId MS ON B.Stypeid = MS.TypeId
	WHERE	b.IfCheck = 't' 
			and b.redword=0 
			and s.ptypeid=@ptype 
			and billtype=400
			AND (@startdate='' or b.billdate>=@startdate)
			AND (@enddate='' or b.billdate<=@enddate) 

   ) a
   END
   
   
   

 	INSERT INTO #returntable VALUES(@recsaleprice,@recbuyprice,@maxprice,@minprice)

	SELECT  * FROM #returntable
	DROP TABLE #returntable
	
END

IF @flag=1
BEGIN	
	DECLARE @SQLWHERE VARCHAR(1000)
	DECLARE @SQLWHEREAB VARCHAR(1000)
	DECLARE @SQLRES VARCHAR(8000)
	
	SET @SQLWHERE='  WHERE O.PTYPEID= '''+@PType+''' AND i.ifcheck=''t'' AND i.redword=0 AND i.billtype=34 '
	if @startdate<>''
		set @SQLWHERE=@SQLWHERE+' AND  i.billdate>='''+@startdate+''''
	if @enddate<>''
		set @SQLWHERE=@SQLWHERE+' AND i.billdate<='''+@enddate+''''
		
	--SET @SQLWHERE=@SQLWHERE+' ORDER BY I.BILLDATE DESC  '
	
	
	SET @SQLWHEREAB='  WHERE ab.PTYPEID= '''+@PType+''' AND i.ifcheck=''t'' AND i.redword=0 AND i.billtype=400 '
	if @startdate<>''
		set @SQLWHEREAB=@SQLWHEREAB+' AND  i.billdate>='''+@startdate+''''
	if @enddate<>''
		set @SQLWHEREAB=@SQLWHEREAB+' AND i.billdate<='''+@enddate+''''
		
	--SET @SQLWHEREAB=@SQLWHEREAB+' ORDER BY I.BILLDATE DESC   '
	
	
	DECLARE @SQL VARCHAR(8000)
	DECLARE @SQLAB VARCHAR(8000)

	
	SET @SQL='  SELECT  i.billnumberid,
						i.btypeid,
						i.stypeid,
						i.billcode,
						i.billdate,
						i.billtype,
						o.ptypeid,
						o.qty,
						o.discountprice,
						o.goodsnumber,
					    pt.customitemid,
					    pt.customitemfrom,
					    pt.customitemname,
					    pt.customitemrefid,		        
					    itemid=o.ItemId,
					    itemname= CASE WHEN o.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= o.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= o.ItemId ) END,
					    iscombined=o.IsCombined,
						billname=(select billname from billname where billtype=i.billtype),
						i.dealbtypeid,
						(select fullname from btype where typeid=i.dealbtypeid) as dealbfullname
				FROM billindex i
				INNER JOIN #GetManSTypeId MS ON I.Stypeid = MS.TypeId
				INNER JOIN buybill o ON i.billnumberid=o.billnumberid
				INNER JOIN dbo.PType pt ON o.PTypeID = pt.TypeID
				
				 '
	
	SET @SQL=@SQL+@SQLWHERE
	
	
	
	SET @SQLAB='
	
	 
	  
	  SELECT  i.billnumberid,
						i.btypeid,
						i.stypeid,
						i.billcode,
						i.billdate,
						i.billtype,
						ab.ptypeid,
						ab.qty,
						ab.discountprice,
						ab.goodsnumber,
					    pt.customitemid,
					    pt.customitemfrom,
					    pt.customitemname,
					    pt.customitemrefid,		        
					    itemid=ab.ItemId,
					    itemname= CASE WHEN ab.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= ab.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= ab.ItemId ) END,
					    iscombined=ab.IsCombined,
						billname=(select billname from billname where billtype=i.billtype),
						i.dealbtypeid,
						(select fullname from btype where typeid=i.dealbtypeid) as dealbfullname
				FROM billindex i
				INNER JOIN #GetManSTypeId MS ON I.Stypeid = MS.TypeId
				INNER JOIN AppraisalBill ab ON i.billnumberid=ab.billnumberid
				INNER JOIN dbo.PType pt ON ab.PTypeID = pt.TypeID
				
				 '
	
	SET @SQLAB=@SQLAB+@SQLWHEREAB
	
	
	
	SET @SQLRES=@SQL
	
	IF(@isap = 1)
	SET @SQLRES=@SQLAB
	
	--print(@SQLRES)
	EXEC(@SQLRES)
END

DROP TABLE #GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_BuyPriceAnalysisChart]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_BuyPriceAnalysisChart]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*-----------------------------------------
	作者：毛欣蓉
	日期：2010-08-16
	描述：进价趋势分析
--------------------------------------------*/

CREATE    PROCEDURE QP_Web_BuyPriceAnalysisChart
(
	@OperatorId		varchar(100),
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@PType			varchar(256),
	@STypeId		varchar(max),
	@isap           INT
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @OperatorId

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
	DECLARE @SQLWHERE VARCHAR(1000)
	
	SET @SQLWHERE='  WHERE O.PTYPEID= '''+@PType+''' AND i.ifcheck=''t'' AND i.redword=0 AND i.billtype=34 ' 
	
IF @StartDate<>''
	SET @SQLWHERE=@SQLWHERE + ' AND  i.billdate>='''+@startdate+''''
IF @enddate<>''
	SET @SQLWHERE=@SQLWHERE + ' AND i.billdate<='''+@enddate+''''

SET @SQLWHERE=@SQLWHERE + ' ORDER BY I.BILLDATE'

if(@isap=1)
BEGIN
	SET @SQLWHERE='  WHERE O.PTYPEID= '''+@PType+''' AND i.ifcheck=''t'' AND i.redword=0 AND i.billtype=400 ' 
	
IF @StartDate<>''
	SET @SQLWHERE=@SQLWHERE + ' AND  i.billdate>='''+@startdate+''''
IF @enddate<>''
	SET @SQLWHERE=@SQLWHERE + ' AND i.billdate<='''+@enddate+''''

SET @SQLWHERE=@SQLWHERE + ' ORDER BY I.BILLDATE'
END


DECLARE @SQL VARCHAR(8000)

SET @SQL='  SELECT  i.billdate,
					o.discountprice,
					o.qty
			FROM billindex i
			INNER JOIN #GetManSTypeId MS ON I.Stypeid = MS.TypeId
			INNER JOIN buybill o ON i.billnumberid=o.billnumberid '
			
			
if(@isap=1)
BEGIN
SET @SQL='  SELECT  i.billdate,
					o.discountprice,
					o.qty
			FROM billindex i
			INNER JOIN #GetManSTypeId MS ON I.Stypeid = MS.TypeId
			INNER JOIN AppraisalBill o ON i.billnumberid=o.billnumberid '
END

SET @SQL=@SQL+@SQLWHERE

PRINT(@SQL)
EXEC(@SQL)


DROP TABLE #GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_carWash]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_carWash]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_Web_carWash
(
   @OperatorID		varchar(50),				--操作员 ID（作权限范围检查用）
   @startDate		varchar(50),
   @endDate			varchar(50),
   @ratypeid		varchar(4000),
   @btypeid			varchar(4000),
   @dtypeid			varchar(4000),
   @etypeid			varchar(4000)='',
   @stypeid			varchar(4000)=''
  -- @chvSortFild	varchar(50)='',				--排序字段
   --@chvSortType	varchar(10)=''				--排序方式
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #Btype(typeid VARCHAR(50))
CREATE TABLE #Etype(typeid VARCHAR(50),fullname VARCHAR(200))
CREATE TABLE #Dtype(typeid VARCHAR(50))
CREATE TABLE #nVipCardSign(ratypeid VARCHAR(50))

create table #stype
(
	typeid		varchar(50)
)
--分支机构
INSERT INTO #stype(typeid) SELECT  A.typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A
	

--往来单位    
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)

--职员
INSERT INTO #Etype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)

--部门（客户反馈应该要控制部门）
--INSERT INTO #Dtype(typeid) SELECT  A FROM dbo.f_split(@dtypeid,',') 
INSERT INTO #Dtype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)

--车牌号
INSERT INTO #nVipCardSign(ratypeid) 
SELECT  Q.TypeID FROM dbo.f_split(@ratypeid,',') W 
INNER JOIN  QP_RepairAutoInfo Q  ON  LEFT(Q.TypeID,LEN(W.A)) = W.A 
WHERE   Q.SonNum=0

DECLARE @SQL varchar(4000)
SET @SQL='SELECT A.billnumberid,
                 A.billdate,
                 A.stypeid,
                 A.billcode,
                 AA.RATypeID,
                 A.stypeid,
                 case A.IfMulAccount when 1 then ''-99999'' else  A.atypeid end as atypeid,
                 A.btypeid,
                 A.DTypeID,
                 A.vipcardID,
                 B.VipCardCode,
                 CASE WHEN A.TotalMoney=0 AND A.TotalInMoney=0 THEN ''是''else ''否'' END AS IsWashTimes,
                 A.TotalMoney,
                 A.TotalInMoney,
                 A.comment,
                 A.explain,
                 A.billtype
            FROM Billindex A 
            LEFT JOIN nVipCardSign  B ON A.vipcardID=B.VipCardID '
 
IF(@ratypeid<>'')
SET @SQL=@SQL + ' INNER JOIN Billindex_CarRepair AA ON  A.billnumberid=AA.billnumberid '
ELSE
SET @SQL=@SQL + ' LEFT JOIN Billindex_CarRepair AA ON  A.billnumberid=AA.billnumberid '

--IF NOT (@etypeid = '' AND @METypeId = '00001')
--SET @SQL=@SQL + ' INNER JOIN  (SELECT DISTINCT BillNumberId FROM QP_WashCarBill Q INNER JOIN #Etype E ON Q.ETypeID=E.typeid)  M ON  A.BillNumberId=M.BillNumberId '
 
IF(@ratypeid<>'')
SET @SQL=@SQL + ' INNER JOIN  #nVipCardSign NV ON  AA.ratypeid=NV.ratypeid'

--IF NOT (@btypeid = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
--SET @SQL=@SQL + ' INNER JOIN  #Btype BB ON  A.btypeid=BB.typeid'

--IF NOT (@dtypeid = '' AND @MDtypeid='00000')	

IF NOT (@dtypeid = '' AND @MDtypeid = '00000')
  SET @SQL=@SQL + ' INNER JOIN  #Dtype D ON LEFT(A.DTypeID,LEN(D.typeid)) = D.typeid '

IF @stypeid<>'' OR @MStypeid<>'00000'
	SET @SQL=@SQL+' INNER JOIN #STYPE S ON S.TYPEID=A.STYPEID '

SET @SQL=@SQL + ' WHERE  A.billtype=179  AND A.RedWord=0 '

IF(ISNULL(@startDate,'')<>'')
	SET @SQL=@SQL + '       AND Convert(datetime,A.billdate) >=Convert(datetime,'+char(39)+@startDate+char(39)+') '

IF(ISNULL(@endDate,'')<>'')
	SET @SQL=@SQL + '       AND Convert(datetime,A.billdate) <=Convert(datetime,'+char(39)+@endDate+char(39)+') ' 

SET @Sql=@Sql + ' AND a.ifYearBill= 0 '    --年节存标志

SET @SQL=@SQL + '  ORDER BY  A.billdate DESC ,A.billcode DESC    '

--PRINT @SQL
EXEC(@SQL)   

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_CarWashBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_CarWashBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_CarWashBill (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @BillnumberId    numeric(10, 0)=0 
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

DECLARE @SQL varchar(4000)

SELECT	B.billnumberid,
		Checke,E1.fullname as CheckeName,
		B.BillDate,BillCode,
		B.BillType BillType,
		B.dtypeid,  
		D.fullname as dfullname,
		N.VipCardID,
		N.VipCardCode,
		Q.PlateNumber,
		AA.RATypeID,
		N.czyemoney, 
		N.CanWashTimes,
		N.CarWashPrice,
		B.comment,
		B.explain,
		B.atypeid,
		A.fullname as afullname,
		B.btypeid, 
		BB.fullname as bfullname,
		B.TotalMoney,
		TotalInMoney ,
		B.RedWord,
		b.etypeid,
		e.FullName AS efullname,
		b.stypeid,
		s.fullname as sfullname
FROM	BILLINDEX B  
		left JOIN Billindex_CarRepair AA ON  B.billnumberid=AA.billnumberid 
		Left JOIN QP_RepairAutoInfo Q ON AA.RATypeID=Q.TypeID  
		INNER JOIN employee E1 ON B.Checke=E1.typeid 
		LEFT JOIN nVipCardSign N ON B.vipcardID=N.VipCardID  
		LEFT JOIN employee E ON  B.etypeid=e.typeid  
		LEFT JOIN Department D ON  B.dtypeid=D.typeid 
		LEFT JOIN Btype BB ON B.btypeid=BB.typeid 
		LEFT JOIN atype A  ON B.atypeid=A.typeid  
		LEFT JOIN stype s  ON B.stypeid=s.typeid  
		WHERE B.billnumberid=@BillnumberId  AND B.BillType=179
		-- WHERE B.billnumberid=7  AND B.BillType=179 AND AA.BillType=179
		
--PRINT @SQL RETURN   
EXEC(@SQL)        
      
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_carWashCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_carWashCheck]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_Web_carWashCheck(
   @OperatorID	varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @startDate varchar(50),
   @endDate varchar(50),
   @etypeid varchar(4000),
   @stypeid varchar(4000),
   @SortFild varchar(50)=''  ,				--排序字段
   @SortType	varchar(10)=''				--排序方式
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #Etype(typeid VARCHAR(50),usercode VARCHAR(200),FullName VARCHAR(200))

create table #stype(typeid varchar(100))

--分支机构
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--职员
INSERT INTO #Etype(typeid,usercode,FullName) 
SELECT A.typeid,usercode,FullName FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID) A INNER JOIN employee E ON A.typeid=E.typeid

IF(ISNULL(@SortFild,'')='')
  SET @SortFild='E.usercode'

IF(ISNULL(@SortType,'')='')
  SET @SortType='asc'

DECLARE @SQL varchar(4000)

SET @SQL='SELECT  ETypeID,washTimetotal,washTime FROM #Etype E 
		INNER JOIN 
                (SELECT ETypeID, ISNULL(SUM(washTimetotal),0) washTimetotal,COUNT(0)  washTime  FROM  ( /*总算出每个职员每张单据的兑换分数*/
				    SELECT B.BillNumberId,/*算出每个职员每张单据的兑换分数*/
		                   Convert( NUMERIC(24, 10) , CASE WHEN ISNULL(COUNT(0),0)=0 THEN 1 ELSE 1.0/ISNULL(COUNT(0),1) END) washTimetotal 
					       FROM  Billindex A 
					       INNER JOIN QP_WashCarBill B  ON A.BillNumberId=B.BillNumberId  '
		IF @stypeid<>'' OR @MStypeid<>'00000'
			SET @SQL=@SQL+' INNER JOIN #STYPE S ON  S.TYPEID=A.STYPEID '
					       
           set @SQL=@SQL+' WHERE A.billtype=179 AND A.RedWord=0  '

IF(ISNULL(@startDate,'')<>'')
SET @SQL=@SQL + '         AND Convert(datetime,A.billdate) >=Convert(datetime,'+char(39)+@startDate+char(39)+') '

IF(ISNULL(@endDate,'')<>'')
SET @SQL=@SQL + '         AND Convert(datetime,A.billdate) <=Convert(datetime,'+char(39)+@endDate+char(39)+') ' 

SET @Sql=@Sql + ' AND a.ifYearBill= 0 '    --年节存标志

SET @SQL=@SQL+ ' 			  GROUP BY B.BillNumberId
	            ) T  
                         INNER JOIN QP_WashCarBill C ON  T.BillNumberId=C.BillNumberId 
           GROUP BY ETypeID) M   ON E.typeid=M.ETypeID '


SET @SQL=@SQL+ ' ORDER BY  ' + @SortFild + '  ' +  @SortType
--PRINT @SQL RETURN     

EXEC(@SQL)   
      
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_carWashDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_carWashDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_Web_carWashDetail(
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @startDate varchar(50),
   @endDate varchar(50),
   @etypeid varchar(8000)='',
   @stypeid	varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #Etype(typeid VARCHAR(50),fullname VARCHAR(200))
CREATE TABLE #stype(typeid VARCHAR(50))
--职员
INSERT INTO #Etype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DECLARE @SQL varchar(4000)
SET @SQL='SELECT A.billnumberid,
                 A.billdate,
                 A.billcode,
                 AA.RATypeID,
                 M.ETypeID,
                 A.btypeid,
                 A.DTypeID,
                 A.vipcardID,
                 B.VipCardCode,
                 1 as  washTime,
                 (SELECT  Convert( NUMERIC(24, 10) , CASE WHEN COUNT(0)=0 THEN 0 ELSE 1.0 /COUNT(0) END)  FROM QP_WashCarBill WHERE BillNumberId=A.BillNumberId) washTimetotal,
                 A.comment,
                 A.explain,
                 A.billtype
            FROM Billindex A 
                  LEFT JOIN nVipCardSign  B ON A.vipcardID=B.VipCardID 
                  LEFT JOIN Billindex_CarRepair AA ON  A.billnumberid=AA.billnumberid 
                  INNER JOIN  QP_WashCarBill M ON  A.BillNumberId=M.BillNumberId 
                  INNER JOIN #Stype s on s.typeid=a.stypeid'
	

SET @SQL=@SQL + ' WHERE  A.billtype=179  AND A.RedWord=0 '
SET @SQL=@SQL + '    AND  M.ETypeID= '+char(39)+ @etypeid +char(39)+' '


IF(ISNULL(@startDate,'')<>'')
SET @SQL=@SQL + '       AND Convert(datetime,A.billdate) >=Convert(datetime,'+char(39)+@startDate+char(39)+') '

IF(ISNULL(@endDate,'')<>'')
SET @SQL=@SQL + '       AND Convert(datetime,A.billdate) <=Convert(datetime,'+char(39)+@endDate+char(39)+') ' 

SET @Sql=@Sql + ' AND a.ifYearBill= 0 '    --年节存标志

SET @SQL=@SQL + '  ORDER BY  A.billdate DESC ,A.billcode DESC    '

--PRINT @SQL RETURN     
EXEC(@SQL)   
      
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_CentChangeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_CentChangeDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_CentChangeDetail (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @startdate varchar(50), --开始时间
   @enddate varchar(50),--结束时间
   @chvDtypeID varchar(4000),
   @chvEtypeID varchar(4000),
   @chvBtypeID varchar(4000),
   @chvKTypeID varchar(4000),
   @chvPTypeID varchar(4000),
   @STypeId	   varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50), fullname varchar(200)) 
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Wtype (TypeID varchar(50))

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--商品
INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

--往来单位    
INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID)

--职员
INSERT INTO #Etype(typeid,fullname) 
SELECT W.typeid,E.fullname FROM F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID) W  INNER JOIN employee E ON W.typeid=E.typeId

--仓库
INSERT INTO #Ktype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvKTypeID,4,@OperatorID)

--部门
INSERT INTO #Dtype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@OperatorID)	

DECLARE @SQL varchar(8000)

SET @SQL='SELECT	A.BillNumberId,
					A.BillDate,
					A.BillCode,
					A.BillType,
					A.dealbtypeid,
					A.btypeid,
					B.PTypeID,
					Qty,
					Price,
					total,
					B.KTypeID ,
					A.etypeid,
					A.DTypeId , 
					B.Comment,
					A.STypeId,
					u1.fullname as basename
           FROM  Billindex A 
		   INNER JOIN  IntegralExchangeBill B ON A.BillNumberId=B.BillNumberId
           INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId '
      SET @SQL+= 'INNER join ptype fg  on b.ptypeid=fg.typeid '+ +dbo.F_GetPtypeUnitsAndRates('fg','1','1')     
    IF NOT (@chvPTypeID ='' AND @MPtypeid = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Ptype P ON  B.PTypeID=P.TypeID '

    IF NOT (@chvBtypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL=@SQL+ ' INNER JOIN  #Btype BB ON A.Btypeid=BB.typeid  '

    IF NOT (@chvETypeId = '' AND @METypeId = '00001')
		SET @SQL=@SQL+ ' INNER JOIN  #Etype E ON A.Etypeid=E.TypeID '
    
    IF NOT (@chvDTypeId = '' AND @MDtypeid = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Dtype D ON D.TypeId = A.DTypeId  '   

    IF NOT (@chvKTypeID = '' AND @MKTypeId = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Ktype K ON B.KTypeID=K.TypeID '

    -------------条件-----------
    SET @SQL = @SQL + '  WHERE A.BillType=183  AND A.RedWord=0 '
    SET @SQL = @SQL + '  AND A.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND A.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)
	SET @SQL = @SQL + ' AND A.IfCheck = ''t'''
	
	SET @Sql=@Sql + ' AND A.ifYearBill= 0 '    --年节存标志
    SET @SQL=@SQL+ '  ORDER BY A.BillDate ASC, A.BillCode ASC '

--PRINT @SQL RETURN
EXEC(@SQL)        

DROP TABLE #Ptype
DROP TABLE #Btype
DROP TABLE #Etype
DROP TABLE #Ktype
DROP TABLE #Dtype,#GetManSTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_CentChangeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_CentChangeLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_CentChangeLine (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @startdate varchar(50), --开始时间
   @enddate varchar(50),--结束时间
   @chvDtypeID varchar(4000),
   @chvEtypeID varchar(4000),
   @chvBtypeID varchar(4000),
   @chvKTypeID varchar(4000),
   @chvPTypeID varchar(4000),
   @STypeId	   varchar(max)	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Wtype (TypeID varchar(50))

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,deleted int) 


--商品
INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

--往来单位    
INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID)

--职员
INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID)

--仓库
INSERT INTO #Ktype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvKTypeID,4,@OperatorID)

--部门
INSERT INTO #Dtype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@OperatorID)	

DECLARE @sonnum int 
SET @sonnum =0


SELECT @sonnum = sonnum FROM Ptype WHERE Typeid =@chvPTypeID
IF @chvPTypeID='00000'
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p
	where typeid in (select typeid from F_BaseGetManDetailPType(@OperatorID))  And p.typeid<>'00000'
ELSE
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p
	where typeid in (select typeid from F_BaseGetManDetailPType(@OperatorID) where typeid like @chvPTypeID+'%')  And p.typeid<>'00000'

DECLARE @SQL varchar(8000)

SET @SQL='SELECT m.TypeID,
          m.sonnum,
        u1.fullname as basename ,
          ISNULL(Qty,0) AS Qty,
          ISNULL(Price,0) AS Price,
          ISNULL(total,0) AS total
          FROM #MainType M  INNER JOIN  (
                SELECT  PtypeID,
		        ISNULL(SUM(Qty),0) as Qty,
			    CASE WHEN ISNULL(SUM(Qty),0)=0 THEN 0 ELSE  ISNULL(SUM(total),0)/ISNULL(SUM(Qty),1) END as Price,
			    ISNULL(SUM(total),0) as total
			    FROM  
			    (
                     SELECT	B.PtypeID ,
							B.Qty AS Qty,total
                     FROM	Billindex A 
                     INNER JOIN  IntegralExchangeBill B ON A.BillNumberId=B.BillNumberId
                     INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId '

    IF NOT (@chvPTypeID ='' AND @MPtypeid = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Ptype P ON B.PTypeID=P.TypeID '

    IF NOT (@chvBtypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL=@SQL+ ' INNER JOIN  #Btype BB ON A.Btypeid=BB.typeid  '

    IF NOT (@chvETypeId = '' AND @METypeId = '00001')
		SET @SQL=@SQL+ ' INNER JOIN  #Etype E ON A.Etypeid=E.TypeID '
    
    IF NOT (@chvDTypeId = '' AND @MDtypeid = '00000')	
		SET @SQL=@SQL+ ' INNER JOIN  #Dtype D ON A.DTypeId = D.TypeId  '	
    

    IF NOT (@chvKTypeID = '' AND @MKTypeId = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Ktype K ON B.KTypeID=K.TypeID '

    -------------条件-----------
    SET @SQL = @SQL + '  WHERE A.BillType=183  AND A.RedWord=0 '
    SET @SQL = @SQL + '  AND A.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND A.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)
	SET @SQL = @SQL + ' AND A.IfCheck = ''t'''
	
	SET @Sql=@Sql + ' AND A.ifYearBill= 0 '    --年节存标志
	 
    SET @SQL=@SQL+ ' ) TT GROUP BY PtypeID )  T  ON LEFT(M.TypeID,LEN(T.PTypeID)) = T.PTypeID
     INNER join ptype fg  on m.typeid=fg.typeid '+ +dbo.F_GetPtypeUnitsAndRates('fg','1','1')
 set  @SQL+=' ORDER BY   m.usercode ASC '

--PRINT @SQL RETURN
EXEC(@SQL)        

DROP TABLE #MainType
DROP TABLE #Ptype
DROP TABLE #Btype
DROP TABLE #Etype
DROP TABLE #Ktype
DROP TABLE #Dtype,#GetManSTypeId          
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_CentChangeList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_CentChangeList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_CentChangeList 
(
   @OperatorID	varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @parid		varchar(100)='00000',
   @startdate	varchar(50),		--开始时间
   @enddate		varchar(50),		--结束时间
   @chvDtypeID	varchar(4000),
   @chvEtypeID	varchar(4000),
   @chvBtypeID	varchar(4000),
   @chvKTypeID	varchar(4000),
   @chvPTypeID	varchar(4000),
   @STypeId		varchar(max)		-- 分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Wtype (TypeID varchar(50))

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)


IF(@parid='00000' AND ISNULL(@chvPTypeID,'')<>'')
SET @parid=@chvPTypeID

CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,deleted INT,sortid INT) 

--商品
INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

--往来单位    
INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID)

--职员
INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID)

--仓库
INSERT INTO #Ktype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvKTypeID,4,@OperatorID)

--部门
INSERT INTO #Dtype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@OperatorID)	

DECLARE @sonnum INT
SET @sonnum =0
SELECT @sonnum = sonnum FROM Ptype WHERE Typeid=@Parid

IF @sonnum =0 	
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,sortid) 
	SELECT distinct  p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.sortid FROM Ptype p
	,(select * from F_BaseGetManPTypeAll(@OperatorID) where typeid =@Parid) a where p.typeid=a.typeid And p.typeid<>'00000' and p.iscombinationproduct=0
ELSE
	IF @Parid='00000'
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,sortid) 
		SELECT distinct p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.sortid FROM Ptype p
		,(select * from F_BaseGetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid And p.typeid<>'00000' and p.iscombinationproduct=0
	ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,sortid) 
		SELECT distinct p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.sortid FROM Ptype p
		,(select * from F_BaseGetManPTypeAll(@OperatorID) where parid=@Parid) a where p.typeid=a.typeid And p.typeid<>'00000' and p.iscombinationproduct=0

DECLARE @SQL varchar(8000)
SET @SQL=' SELECT M.TypeID,
                M.sonnum,
              case when M.sonnum>0 then null else   fg.baseunitfullname  end as basename ,
		        ISNULL(SUM(Qty),0) as Qty,
			    CASE WHEN ISNULL(SUM(Qty),0)=0 THEN 0 ELSE  ISNULL(SUM(total),0)/ISNULL(SUM(Qty),1) END as Price,
			    ISNULL(SUM(total),0) as total
			    FROM  #MainType M  LEFT JOIN 
                    (
						SELECT	B.PtypeID ,
								B.Qty AS Qty,total
						FROM	Billindex A 
						INNER JOIN  IntegralExchangeBill B ON A.BillNumberId=B.BillNumberId
						INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId '

    IF NOT (@chvPTypeID ='' AND @MPtypeid = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Ptype P ON B.PTypeID=P.TypeID '

    IF NOT (@chvBtypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL=@SQL+ ' INNER JOIN  #Btype BB ON A.Btypeid=BB.typeid  '

    IF NOT (@chvETypeId = '' AND @METypeId = '00001')
		SET @SQL=@SQL+ ' INNER JOIN  #Etype E ON A.Etypeid=E.TypeID '
    
    IF NOT (@chvDTypeId = '' AND @MDtypeid = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Dtype D ON A.DTypeId = D.TypeId  '

    IF NOT (@chvKTypeID = '' AND @MKTypeId = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Ktype K ON B.KTypeID=K.TypeID '

    -------------条件-----------
    SET @SQL = @SQL + '  WHERE	A.BillType=183  
								AND A.RedWord=0 
								AND A.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND A.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)
								
	SET @Sql=@Sql + ' AND A.ifYearBill= 0 '    --年节存标志
			
	SET @SQL = @SQL + ' AND A.IfCheck = ''t'''
 
    SET @SQL=@SQL+ ' ) TT  ON LEFT(TT.PTypeID,LEN(M.TypeID)) = M.TypeID
    Inner JOIN F_GetManPTypeDetailALL('''+@OperatorID+''') fg on fg.typeid = m.typeid
    GROUP BY M.TypeID,M.usercode,M.sonnum,fg.baseunitfullname,m.sortid
    ORDER BY   M.sortid  '

--PRINT @SQL --RETURN

EXEC(@SQL)        


DROP TABLE #MainType,#Ptype,#Btype,#Etype,#Ktype,#Dtype,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--SELECT * FROM dbo.sqlLog ORDER BY id DESC
--exec QP_web_CentChangeList @OperatorID='00001',@parid='00000',@startdate='2012-06-01',@enddate='2012-06-25',@chvDtypeID='',@chvEtypeID='',@chvBtypeID='',@chvKTypeID='',@chvPTypeID='',@STypeId='00001'



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_EtypeSaleReview]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_EtypeSaleReview]
GO


/**---------------------------------------------------------------**/
--作者：毛欣蓉
--日期：2010-09-02
--功能：职员销售考评
--涉及单据：零售单、销售出库单、销售退货单、销售换货单、委托代销结算单,零售退货单(9.2新增)

-- 修改: 舒珊
-- 日期: 2016-07-12
-- 描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
/**--------------------------------------------------------------**/
CREATE  PROCEDURE  Qp_Web_EtypeSaleReview
(	
	@OperatorID		varchar(50),		--  1、操作员 ID（作权限范围检查用）
	@startDate		varchar(30),		--  2、查询起始时间
	@EndDate		varchar(30),		--  3、查询结束时间
	@BTypeID		varchar(1550),		--  4、往来单位ID
	@ETypeID		varchar(1550),		--  5、职员 ID
	@DtypeID     	varchar(1550)='',       --  6、部门id
	@Billtype   	varchar(200),	        --  7. 单据类型
	@STypeId		varchar(max),
	@isAllot		INT   --是否按分配查询 add by dongzhan 2012.10.10
)
--@encode$--
AS
set nocount on
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
create table #btype(typeid varchar(100))
INSERT INTO #btype(typeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

create table #etype(typeid varchar(100))
INSERT INTO #etype(typeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

create table #dtype(typeid varchar(100))
INSERT INTO #dtype(typeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

declare @sql varchar(8000)

IF @isAllot=0
	BEGIN
		--billindex 临时表
		create table #billindex
		(
			billnumberid 	int,
			billtype	int,
			etypeid 	varchar(100),
			backtotal  	 NUMERIC(24, 10) ,
			preferencemoney  NUMERIC(24, 10) 
		)

		

		set @sql='	INSERT INTO #billindex(billnumberid,billtype,etypeid,backtotal,preferencemoney)
					select DISTINCT b.billnumberid,
							b.billtype,
							b.etypeid,
							case when b.billtype in (45,215,46) then -1*(isnull(b.totalinmoney,0)+isnull(b.completetotal,0)) 
								else isnull(b.totalinmoney,0)+isnull(b.completetotal,0) 
							end as backtotal,
							case  when  b.billtype in (45,215,46) then -1*b.preferencemoney
		 						else b.preferencemoney
							end as preferencemoney
					from	billindex b 
					inner join #dtype d on d.typeid=b.dtypeid
					inner join #btype bt on bt.typeid=b.dealbtypeid
					inner join #etype e on e.typeid=b.etypeid
					INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId 
					where	b.RedWord=0 
							AND b.Draft =0 
							and b.billtype in('+@Billtype+') 
							AND b.billdate>='''+@startdate+'''
							AND b.billdate<='''+@enddate+'''
							AND b.ifYearBill=''0''' --年节存标志

		--print(@sql)
		exec(@sql)
	
		create table #inoutstocktable
		(
			billnumberid	int,
			saletotal  	 NUMERIC(24, 10) ,
			salecost	 NUMERIC(24, 10) ,
			salebacktotal	 NUMERIC(24, 10) ,
			salebackcost	 NUMERIC(24, 10) 
		)

		set @sql='	INSERT INTO #inoutstocktable(billnumberid,saletotal,salecost,salebacktotal,salebackcost)
					select billnumberid,sum(saletotal),sum(salecost),sum(salebacktotal),sum(salebackcost)
    				from (
							select	s.billnumberid,
									case when s.total<0 then abs(s.total)
									else null  end as saletotal,
									case when s.costtotal<0 then abs(s.costtotal)
									else   null end as salecost,
									case when s.total>0 then -1*s.total
									else null end as salebacktotal,
									case when s.costtotal>0 then -1*s.costtotal
									else null end as salebackcost
							from	inoutstocktable s					
							where	s.billtype in('+@Billtype+')
									AND  s.billdate>='''+@startdate+'''
									AND s.billdate<='''+@enddate+'''
						)as a
					group by a.billnumberid	'

		exec(@sql)
		
		select	a.*,
				(a.saletotal+a.salebacktotal-(a.salecost+a.salebackcost)-a.preferencemoney) as maoli,
				case when (a.saletotal+a.salebacktotal)=0 then 0 
				else
				CAST((a.saletotal+a.salebacktotal-(a.salecost+a.salebackcost)-a.preferencemoney) AS NUMERIC(24, 10))/CAST((a.saletotal+a.salebacktotal) AS NUMERIC(24, 10))*100 
				end as maolilu			
		from (
				select 	b.etypeid,
						isnull(sum(isnull(b.backtotal,0)),0) as backtotal,
						isnull(sum(isnull(b.preferencemoney,0)),0) as preferencemoney,
						isnull(sum(isnull(i.saletotal,0)),0) as saletotal,
						isnull(sum(isnull(i.salecost,0)),0) as salecost,
						isnull(sum(isnull(i.salebacktotal,0)),0) as salebacktotal,
						isnull(sum(isnull(i.salebackcost,0)),0) as salebackcost
				from #billindex b
				inner join  #inoutstocktable i on b.billnumberid=i.billnumberid
				group by b.etypeid
			) a
			drop table #billindex,#inoutstocktable
   END
ELSE       ----按分配业绩查询
	BEGIN 
		--billindex1 零时表,只取分摊后了的单据(判断条件就好bx.total>0和b.redword not in (1,2))
		--modify by dongzhan 2013-3-22      跟需求确认，参数@etypeid经手人选项，当勾分配业绩选项后，意义改变，意思是被分配的人，不再是单据上的etypeid
		create table #billindex1
		(
			billnumberid 	int,
			billtype	int,
			etypeid 	varchar(100),
			--Performance	 NUMERIC(24, 10) ,		--分配比例
			backtotal  	 NUMERIC(24, 10) ,		--回款金额
			preferencemoney  NUMERIC(24, 10)    --结算金额,抹零金额
		)

		--set @sql='	INSERT INTO #billindex1(billnumberid,billtype,etypeid,Performance,backtotal,preferencemoney)
		set @sql='	INSERT INTO #billindex1(billnumberid,billtype,etypeid,backtotal,preferencemoney)
					select DISTINCT b.billnumberid,
							b.billtype,
							CASE WHEN p.ETypeID IS NULL THEN b.etypeid ELSE p.ETypeID END, 
							--CASE WHEN p.ETYPEID IS NULL THEN 100 WHEN p.ETYPEID='''' THEN 100 ELSE p.Proportion END,
							case  
								when b.billtype in (45,215,46) then -1*(isnull(b.totalinmoney,0)+isnull(b.completetotal,0)) 
								else isnull(b.totalinmoney,0)+isnull(b.completetotal,0) 
							end as backtotal,
							case  
								when b.billtype in (45,215,46) then -1*b.preferencemoney
		 						else b.preferencemoney
							end as preferencemoney
					from	billindex b 
					LEFT JOIN PerformanceDistribution p ON b.billnumberid=p.billnumberid
					inner join #dtype d on d.typeid=b.dtypeid
					inner join #btype bt on bt.typeid=b.dealbtypeid
					--inner join #etype e on e.typeid=b.etypeid
					INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId 
					INNER JOIN (
					                  SELECT	BillNumberId,
									  ISNULL(SUM(Total),0) AS Total
									  FROM	PerformanceDistribution		
									  GROUP BY BillNumberId
							   ) bx ON b.BillNumberId=bx.BillNumberId AND bx.Total>0
					where	b.RedWord=0 
							AND b.Draft =0 
							and b.billtype in('+@Billtype+') 
							AND b.billdate>='''+@startdate+'''
							AND b.billdate<='''+@enddate+'''
							AND b.ifYearBill=''0''' --年节存标志

		print(@sql)
		exec(@sql)
		
		create table #inoutstocktable1
		(
			billnumberid	int,
			etypeid VARCHAR(200),
			saletotal  	 NUMERIC(24, 10) ,--销售出库金额
			salecost	 NUMERIC(24, 10) ,--销售出库成本
			salebacktotal	 NUMERIC(24, 10) , --销售退货金额
			salebackcost	 NUMERIC(24, 10)  --销售退货成本
		)

		set @sql='	INSERT INTO #inoutstocktable1(billnumberid,etypeid,saletotal,salecost,salebacktotal,salebackcost)
					select billnumberid,etypeid,sum(saletotal),sum(salecost),sum(salebacktotal),sum(salebackcost)
    				from (
							SELECT A.billnumberid,A.etypeid,
									CASE 
										WHEN B.BillType IN(11,305,141,160,12) THEN A.DiscountTotal 
										ELSE 0 
									END AS saletotal,
									CASE 
										WHEN B.BillType IN(11,305,141,160,12) THEN A.CostTotal 
										ELSE 0 
									END AS salecost, 
									CASE 
										WHEN B.BillType IN(45,215,46) THEN -1 * A.DiscountTotal 
										ELSE 0 
									END AS salebacktotal,
									CASE 
										WHEN B.BillType IN(45,215,46) THEN -1 * A.CostTotal 
										ELSE 0 
									END AS salebackcost 
							FROM PerformanceDistribution AS A 
							INNER JOIN BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
							WHERE A.Total > 0
									AND B.billtype in('+@Billtype+')
									AND B.billdate>='''+@startdate+'''
									AND B.billdate<='''+@enddate+'''
						)as a
					group by a.billnumberid,a.etypeid	'

		exec(@sql)
		print @sql
		
		set @sql='
		select	a.*,
				(a.saletotal+a.salebacktotal-(a.salecost+a.salebackcost)-a.preferencemoney) as maoli,
				case when (a.saletotal+a.salebacktotal)=0 then 0 
				else
				cast((a.saletotal+a.salebacktotal-(a.salecost+a.salebackcost)-a.preferencemoney) as NUMERIC(24, 10))/ cast((a.saletotal+a.salebacktotal) as NUMERIC(24, 10))*100 
				end as maolilu			
		from (
				select 	b.etypeid,
						sum(isnull(b.backtotal,0)) as backtotal,
						sum(isnull(b.preferencemoney,0)) as preferencemoney,
						sum(isnull(i.saletotal,0)) as saletotal,
						sum(isnull(i.salecost,0)) as salecost,
						sum(isnull(i.salebacktotal,0)) as salebacktotal,
						sum(isnull(i.salebackcost,0)) as salebackcost
				from #billindex1 b
				inner join  #inoutstocktable1 i on b.billnumberid=i.billnumberid and b.etypeid = i.etypeid
				group by b.etypeid
			) a '
		
			if @etypeid !=''
				set @sql=@sql+' JOIN  (SELECT e.typeid FROM 
				                      (SELECT e.typeId FROM dbo.f_split('''+@etypeid+''','','') f 
									  JOIN dbo.employee e ON e.typeId LIKE f.a+''%'' AND e.deleted=0 AND e.sonnum=0) f
							          JOIN #etype e on e.typeid=f.typeid) f
							    ON a.etypeid=f.typeid' 
		    ELSE
				set @sql=@sql+' join #etype e on e.typeid=a.etypeid'    
			--PRINT @sql
			exec(@sql)
			
		drop table #billindex1,#inoutstocktable1
	END 

drop table #btype,#etype,#dtype,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_EventALert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_EventALert]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_Web_EventALert (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @intDay int=0,
   @chvSortFild varchar(50)  ,				--排序字段
   @chvSortType	varchar(10)				--排序方式
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Btype(typeid VARCHAR(50))

--往来单位    
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetManDetailBType(@OperatorID)


-- 取得当前日期
DECLARE  @TotDay varchar(200)
	SET @TotDay = Convert(varchar(20),year(GetDate())) +'-'+Convert(varchar(20),Month(GetDate()))+'-'+Convert(varchar(20),Day(GetDate()))

-- 取得当前日期加一定的天数后的新的日期
DECLARE  @TotDay1 Datetime
	SET @TotDay1=DATEADD(Day,@intDay,@TotDay)

DECLARE  @TotDayAdd varchar(200)
	SET @TotDayAdd = Convert(varchar(20),year(@TotDay1)) +'-'+Convert(varchar(20),Month(@TotDay1))+'-'+Convert(varchar(20),Day(@TotDay1))

IF(@chvSortFild='') 
   SET @chvSortFild = 'B.VipCardCode'
IF(@chvSortType='')
   SET @chvSortType = 'ASC'

DECLARE @SQL varchar(4000)
SET @SQL='SELECT B.VipCardID,
                 B.VipCardTypeID,
                 B.RATypeID,
                 B.BTypeID,
                 B.CarType,
                 B.VipCardCode,
                 B.Btel,
                 B.Bname,
                 B.Btel,
                 A.RemindContent,
                 A.RemindDate,
                 B.deleted AS deleted,
				 CASE 
					WHEN B.deleted = 0 THEN ''启用''
					WHEN B.deleted = 2 THEN ''停用''
					WHEN B.deleted = 3 THEN ''挂失''
					ELSE ''启用''
				 END AS zt,	
                 A.Comment AS Comment
             FROM  QP_nVipCardSign_RemindEvent  A
                   INNER JOIN nVipCardSign B ON A.VipCardID=B.VipCardID  '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
SET @SQL=@SQL + ' INNER JOIN  #Btype BB ON  B.BTypeID=BB.typeid '

IF(ISNULL(@intDay,0)>=0)
SET @SQL=@SQL+ '   WHERE  Convert(datetime,A.RemindDate) >=Convert(datetime,'+char(39)+@TotDay+char(39)+')
                          AND Convert(datetime,A.RemindDate) <=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+') ' 
ELSE
SET @SQL=@SQL+ '   WHERE  Convert(datetime,A.RemindDate) >=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+')
                          AND Convert(datetime,A.RemindDate) <=Convert(datetime,'+char(39)+@TotDay+char(39)+') ' 

SET @SQL=@SQL+ ' ORDER BY  ' + @chvSortFild + '  ' +  @chvSortType
--PRINT @SQL RETURN     

EXEC(@SQL)   
   
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_FindCarRepairCountInMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_FindCarRepairCountInMonth]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：郑红霞
	日期：2011-06-10
	描述：维修车次月统计
	说明：把他们的sql预计转化成了存储过程
-------------------------------------------*/
CREATE PROCEDURE [dbo].[Qp_Web_FindCarRepairCountInMonth]
(
    @operatorId    VARCHAR(50),
    @stypeid       VARCHAR(50),       
	@billtype      VARCHAR(1550)
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @SQL VARCHAR(3000)
	
	set @SQL=' select CONVERT(char(7),b.BillDate,120) as repairMonth,
	          COUNT(*) as repairCount  
	     from BillIndex b,
	          stype s,
	          Billindex_CarRepair bi
        where b.Stypeid=s.TypeId and b.Stypeid in((SELECT typeid FROM F_GetAllManagerBaseTypeId('''+@stypeid+''',11,'''+@operatorId+'''))) and b.BillType in('+@billtype+') 
              and bi.BillState not in (5) and bi.BillNumberId=b.BillNumberId 
              and b.ifcheck=''t'' and b.RedWord = 0 and b.IfYearBill = 0 and b.Draft = 0

              group by CONVERT(char(7),b.BillDate,120) order by repairMonth'
   exec (@SQL)
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_FirstMaintainReachDayALert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_FirstMaintainReachDayALert]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2011.10.11
	描述：首保到期提醒
*/
CREATE   PROCEDURE QP_Web_FirstMaintainReachDayALert 
(
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @intDay			int=0
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

--往来单位    
CREATE TABLE #Btype(typeid VARCHAR(50))
INSERT INTO #Btype(typeid)
SELECT typeid FROM F_BaseGetAllManagerBaseTypeId('',2,@OperatorID)

-- 取得当前日期
DECLARE  @TotDay varchar(200)
SET @TotDay = Convert(varchar(20),year(GetDate())) +'-'+Convert(varchar(20),Month(GetDate()))+'-'+Convert(varchar(20),Day(GetDate()))

-- 取得当前日期加一定的天数后的新的日期
DECLARE  @TotDay1 Datetime
SET @TotDay1=DATEADD(Day,@intDay,@TotDay)

DECLARE  @TotDayAdd varchar(200)
SET @TotDayAdd = Convert(varchar(20),year(@TotDay1)) +'-'+Convert(varchar(20),Month(@TotDay1))+'-'+Convert(varchar(20),Day(@TotDay1))


DECLARE @SQL varchar(MAX)

SET @SQL = 'SELECT	A.TypeId AS RATypeID,
					B.TypeId AS BTypeID
			FROM	QP_RepairAutoInfo A 
					INNER JOIN BType B ON A.BTypeID = B.TypeId'
				
IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL=@SQL + '	INNER JOIN  #Btype BB ON  A.BTypeID=BB.typeid '

IF(ISNULL(@intDay,0)>=0)
	SET @SQL=@SQL + '	WHERE  Convert(datetime,A.FirstMaintainDate) >=Convert(datetime,'+char(39)+@TotDay+char(39)+')
							AND Convert(datetime,A.FirstMaintainDate) <=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+') ' 
ELSE
	SET @SQL=@SQL + '	WHERE  Convert(datetime,A.FirstMaintainDate) >=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+')
							AND Convert(datetime,A.FirstMaintainDate) <=Convert(datetime,'+char(39)+@TotDay+char(39)+') ' 
SET @SQL=@SQL + '		ORDER BY A.FirstMaintainDate ASC, A.PlateNumber ASC'
--PRINT @SQL RETURN 
EXEC(@SQL)
DROP TABLE #Btype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_ForceMaintainReachDayALert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_ForceMaintainReachDayALert]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2011.10.11
	描述：强保到期提醒
*/
CREATE   PROCEDURE QP_Web_ForceMaintainReachDayALert 
(
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @intDay          int=0
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

--往来单位 
CREATE TABLE #Btype(typeid VARCHAR(50))
INSERT INTO #Btype(typeid)
SELECT typeid FROM F_BaseGetAllManagerBaseTypeId('',2,@OperatorID)
-- 取得当前日期
DECLARE  @TotDay varchar(200)
SET @TotDay = Convert(varchar(20),year(GetDate())) +'-'+Convert(varchar(20),Month(GetDate()))+'-'+Convert(varchar(20),Day(GetDate()))
-- 取得当前日期加一定的天数后的新的日期
DECLARE  @TotDay1 Datetime
SET @TotDay1=DATEADD(Day,@intDay,@TotDay)

DECLARE  @TotDayAdd varchar(200)
SET @TotDayAdd = Convert(varchar(20),year(@TotDay1)) +'-'+Convert(varchar(20),Month(@TotDay1))+'-'+Convert(varchar(20),Day(@TotDay1))

DECLARE @SQL varchar(MAX)

SET @SQL = 'SELECT	A.TypeId AS RATypeID,
				    B.TypeId AS BTypeID
			FROM	QP_RepairAutoInfo A
					INNER JOIN BType B ON A.BTypeID = B.TypeId'
				
IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL=@SQL + '	INNER JOIN  #Btype BB ON  A.BTypeID=BB.typeid '

IF(ISNULL(@intDay,0)>=0)
	SET @SQL=@SQL + '	WHERE  Convert(datetime,A.ForceMaintainDate) >=Convert(datetime,'+char(39)+@TotDay+char(39)+')
							AND Convert(datetime,A.ForceMaintainDate) <=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+') ' 
ELSE
	SET @SQL=@SQL + '	WHERE  Convert(datetime,A.ForceMaintainDate) >=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+')
							AND Convert(datetime,A.ForceMaintainDate) <=Convert(datetime,'+char(39)+@TotDay+char(39)+') ' 

SET @SQL=@SQL	+ '		ORDER BY A.ForceMaintainDate ASC, A.PlateNumber ASC'
--PRINT @SQL RETURN 
EXEC(@SQL)
DROP TABLE #Btype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_GetAllSuccorChargeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_GetAllSuccorChargeItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：赵斌
	日期：2011-4-20
	描述：查询所有救援收费项目
-------------------------------------------*/
CREATE PROCEDURE Qp_Web_GetAllSuccorChargeItems
--@encode$--
AS
SET NOCOUNT ON

SELECT	* FROM	Qp_SuccorChargeItems ORDER BY FullName


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_getAtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_getAtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_getAtype(
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @usercode    varchar(250)=''
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #AType(typeid VARCHAR(50))
INSERT INTO #AType(typeid) SELECT ntypeid FROM F_GetManDetailAllAType(@OperatorID)
INSERT INTO #AType(TypeId) SELECT nTypeId FROM Ac_Items WHERE nTypeId IN ('0000200006')    --预收账款
SELECT top 1 A.typeid,A.fullname FROM atype A 
INNER JOIN  #AType B ON A.typeid=B.typeid
WHERE sonnum=0 and  deleted=0  and (usercode=@usercode OR fullname=@usercode)

  
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_GetRepairAutoInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_GetRepairAutoInfo]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		徐辉
-- Create date: 2011-05-03
-- Description:	获取维修车辆信息，维修单号
-- =============================================
CREATE PROCEDURE QP_Web_GetRepairAutoInfo
(
	@operatorId		VARCHAR(50),	--操作员
	@platenumber	VARCHAR(50),	--车牌号
	@stypeid		VARCHAR(max)	--分支机构
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON

    SELECT b.BillNumberId,b.BillCode,c.PlateNumber,b.Stypeid,b.btypeid FROM BillIndex b 
    LEFT JOIN Billindex_CarRepair a ON a.BillnumberID=b.billnumberid
    LEFT JOIN QP_RepairAutoInfo c ON a.RATypeID=c.typeid
    WHERE  a.billstate IN(0,1,2)
    AND c.platenumber LIKE '%'+@platenumber+'%'
    AND b.stypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@operatorId))
    AND b.billtype=195
    AND b.draft=1
    AND a.BillState=2
    ORDER BY b.BillCode
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_GetRepairItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_GetRepairItems]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		徐辉
-- Create date: 2011-05-03
-- Description:	获取维修维修项目明细
-- =============================================
CREATE PROCEDURE QP_Web_GetRepairItems
(
	@billnumberid	VARCHAR(50)		--单据id
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON

    SELECT	
			a.*,
			b.*
	FROM Qp_ReceptionBill_RepairItems a 
	LEFT JOIN QP_RepairItems b ON a.RepairItemsTypeID=b.typeid
	WHERE a.billnumberid=@billnumberid 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_GetRepairReceptionIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_GetRepairReceptionIndex]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		徐辉
-- Create date: 2011-05-03
-- Description:	获取维修接待单信息
-- =============================================
CREATE PROCEDURE QP_Web_GetRepairReceptionIndex
(
	@billnumberid	VARCHAR(50)		--单据id
)
--@encode$--	
AS
BEGIN
	SET NOCOUNT ON

    SELECT	
			a.BillNumberId,
			a.BillCode,
			a.ktypeid,
			a.Stypeid,
			b.billstate,
			b.RATypeID,
			b.OperationSort,
			b.completedate,
			b.itemprincipal,
			b.InPriceType,
			g.FullName AS itemprincipalfullname,
			b.monitorprincipal,
			h.FullName AS monitorprincipalfullname,
			b.infactorydate,
			c.PlateNumber,
			c.BTypeID,
			f.FullName AS bfullname,
			c.enginenumber ,
			c.vin,
			c.repairautotypeid,
			c.color,
			d.btypeid AS insurancebtypeid,
			e.FullName AS insurancebfullname,
			d.AccidentDate,
			d.AccidentAddr,
			d.AccidentReason
	FROM BillIndex a 
    LEFT JOIN Billindex_CarRepair b ON a.BillnumberID=b.billnumberid
    LEFT JOIN employee g ON b.itemprincipal=g.typeid
    LEFT JOIN employee h ON b.monitorprincipal=h.typeid
    LEFT JOIN QP_RepairAutoInfo c ON b.RATypeID=c.typeid
    LEFT JOIN btype f ON c.BTypeID=f.typeid
    LEFT JOIN Qp_ReceptionBill_Insurance d ON a.billnumberid=d.billnumberid
    LEFT JOIN btype e ON d.btypeid=e.typeId
    WHERE a.billnumberid=@billnumberid 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_HisSaleInof]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_HisSaleInof]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：郑红霞
	日期：2011-5-24
	描述：查看维修项目
-------------------------------------------*/
CREATE PROCEDURE Qp_Web_HisSaleInof
(
    @BillNumberId  VARCHAR(max)     
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @SQL VARCHAR(3000)
	SET @SQL ='SELECT a.PlateNumber,
                      e.FullName as username,
                      q.TypeID as witypeid,
                      c.BillCode,
                      qp.StandardManHour,
                      qp.CheckHour,
                      qp.Total,
                      qp.RepairProcess
                 from Billindex_CarRepair b 
                      inner join QP_RepairAutoInfo a on a.Typeid = b.RATypeID
                      inner join Qp_ReceptionBill_RepairItems qp on qp.BillNumberId=b.BillNumberId
                      inner join QP_RepairItems q on q.TypeID=qp.RepairItemsTypeID
                      inner join BillIndex c on c.BillNumberId=b.BillNumberId
                      inner join btype e on e.typeId=c.btypeid
                where b.BillNumberId='''+@BillNumberId+''''  
	EXEC (@sql)
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_HistoryOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_HistoryOrder]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：查看该车历史用料
-------------------------------------------*/
CREATE PROCEDURE Qp_Web_HistoryOrder
(
    @BeginDate  VARCHAR(20), 
    @EndDate    VARCHAR(20),  
    @OperatorID    VARCHAR(50),       
	@Ktypeid       VARCHAR(1550)='',         --仓库
    @stypeid       VARCHAR(1550)='00001',    --分支机构
    @RAtypeId      VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @Ptypeid  VARCHAR(1550)=''

--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorId IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
				@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
--配件
CREATE TABLE #Ptype (TypeID VARCHAR(200))
INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Ptypeid,1,@OperatorID)

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50))
INSERT INTO #Ktype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Ktypeid,4,@OperatorID)	

--分支机构
CREATE TABLE #Stype (TypeID VARCHAR(50))
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DECLARE @SQL VARCHAR(3000) 
CREATE TABLE #FactPickBill  -----实际领料表
   (
     billnumberid   varchar(max),
     billcode       varchar(max),
     billdate       datetime,
     ID             varchar(max),
     pickingid      varchar(max),
     stypeid        varchar(max),
     ptypeid        varchar(max),
     Insurance      varchar(max),
     Comment        varchar(max),
     KTypeId        varchar(max),
     username       varchar(max),
     discount        NUMERIC(24, 10) ,
     discountprice  varchar(max),
     discounttotal  varchar(max)
     
   )
INSERT INTO  #FactPickBill 
(
	billnumberid,
	billcode,
	billdate,
	ID,pickingid,
	stypeid,
	ptypeid,
	Insurance,
	Comment,
	KTypeId,
	username,
	discount,
	discountprice,
	discounttotal
) 
SELECT	b.BillNumberId,
		 b.BillCode,
		 b.BillDate,
		 F.ID,
		 F.PickingId,
		 b.Stypeid,
		 F.PTypeID,
		 F.Insurance,
		 F.Comment,
		 qp.KTypeID,
		 e.FullName,
		 F.Discount,
		 F.DiscountPrice,
		 F.DiscountTotal
FROM   Qp_ReceptionBill_FactUsePType F
INNER JOIN  BillIndex b on F.BillNumberId=b.BillNumberId
INNER JOIN  Qp_PickingBill qp on qp.ID = F.PickingId
INNER JOIN  employee e on e.typeId = F.ETypeID   
INNER JOIN  #stype m on m.typeid = b.stypeid
INNER JOIN  #ktype k on k.typeid = qp.ktypeid
INNER JOIN  #ptype ps on ps.typeid = F.PTypeID
WHERE	F.ReceptionBillnumberId IN (
										SELECT	BillNumberId 
										FROM	Billindex_CarRepair Bc
										INNER JOIN QP_RepairAutoInfo R ON Bc.RATypeID = R.TypeID AND R.PlateNumber = ''+@RAtypeId+''
										WHERE	RATypeID=(SELECT TypeID FROM QP_RepairAutoInfo WHERE PlateNumber = ''+@RAtypeId+'') 
												AND BillDate>=''+@BeginDate+'' 
												AND BillState=4 
												AND BillDate<=''+@EndDate+'' 
								  ) 
		and b.draft=0
CREATE TABLE  #FactBackBill   ----退回表
(
     billnumberid   varchar(max),
     billcode       varchar(max),
     billdate       datetime,
     ID             varchar(max),
     pickingid      varchar(max),
     stypeid        varchar(max),
     ptypeid        varchar(max),
     Insurance      varchar(max),
     Comment        varchar(max),
     KTypeId        varchar(max),
     username       varchar(max),
     discount        NUMERIC(24, 10) ,
     discountprice  varchar(max),
     discounttotal  varchar(max)
  )  
INSERT INTO  #FactBackBill
(
	billnumberid,
	billcode,
	billdate,
	ID,
	pickingid,
	stypeid,
	ptypeid,
	Insurance,
	Comment,
	KTypeId,
	username,
	discount,
	discountprice,
    discounttotal
)
SELECT  b.BillNumberId,
		b.BillCode,
		b.BillDate,
		back.ID,
		back.ID,
		b.Stypeid,
		back.PTypeId,
		back.Insurance,
		back.Comment,
		back.KTypeId,
		e.FullName,
		F.Discount,
	    F.DiscountPrice,
	    F.DiscountTotal
FROM   Qp_ReceptionBill_FactUsePType F
INNER JOIN  Qp_PickingBill p ON F.PickingId=p.ID
INNER JOIN  Qp_PickingBackBill back ON back.PickingId=p.ID
INNER JOIN  BillIndex b on back.BillNumberId=b.BillNumberId
INNER JOIN  employee e on e.typeId = F.ETypeID
WHERE	F.ReceptionBillnumberId IN (
										SELECT	BillNumberId 
										FROM	Billindex_CarRepair Bc
										INNER JOIN QP_RepairAutoInfo R ON Bc.RATypeID = R.TypeID AND R.PlateNumber = ''+@RAtypeId+''
										WHERE	RATypeID=(SELECT TypeID FROM QP_RepairAutoInfo WHERE PlateNumber = ''+@RAtypeId+'') 
												AND BillDate>=''+@BeginDate+'' 
												AND BillState=4 
												AND BillDate<=''+@EndDate+''
									) 
		and b.draft=0
--WHERE F.ReceptionBillnumberId IN(
--									(SELECT BillNumberId from Billindex_CarRepair where
--									RATypeID=(SELECT TypeID FROM QP_RepairAutoInfo WHERE PlateNumber = '0000997') 
--									and  BillDate>='2011-06-22' and BillState=4 and BillDate<='2011-07-22'))
CREATE TABLE #FactpickingBackBill  ----合并
(
     billnumberid varchar(max),
     billcode     varchar(max),
     billdate     datetime,
     ID           varchar(max),
     pickingid    varchar(max),
     stypeid      varchar(max),
     ptypeid      varchar(max),
     Insurance    varchar(max),
     Comment      varchar(max),
     KTypeId      varchar(max),
     username     varchar(max),
     discount      NUMERIC(24, 10) ,
     discountprice  varchar(max),
     discounttotal  varchar(max)
 ) 

INSERT INTO  #FactpickingBackBill 
(   billnumberid,
	billcode,
	billdate,
	ID,
	pickingid,
	stypeid,
	ptypeid,
	Insurance,
	Comment,
	KTypeId,
	username,
	discount,
	discountprice,
    discounttotal
)
  SELECT * FROM #FactPickBill
  UNION
  SELECT * FROM #FactBackBill
SET @SQL ='SELECT F.BillNumberId,
	           F.BillCode,
               F.ID,
               F.BillDate,
               F.ptypeid,
               -(I.Qty) as qty,
               F.discount,
               I.Price,
               -(I.Qty * I.Price) as Total,
               -(I.TaxTotal-I.Total) AS Tax,
               F.discountprice,
               F.discounttotal,
               I.CostPrice,
               -(I.CostTotal) as CostTotals,
              -(((I.Qty *I.Price) * F.discount))-(-(I.CostTotal)) AS maoli,
               F.Insurance,
               F.Comment,
               F.KTypeID ktypeid,
               F.username,
               P.usercode
          FROM #FactpickingBackBill F
              -- INNER JOIN InOutstocktable i on i.ID=F.pickingid
               INNER JOIN InOutstocktable i on i.billnumberid=F.billnumberid and i.ID=F.pickingid
               INNER JOIN ptype p on p.typeid=F.ptypeid
               ORDER BY  F.BillDate DESC,P.usercode DESC'
EXEC (@sql)
DROP TABLE #FactPickBill,#FactBackBill,#FactpickingBackBill,#Ptype,#Ktype,#Stype
END
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_HistoryOrderQuotePrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_HistoryOrderQuotePrice]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*-----------------------------------------
	作者：毛欣蓉
	日期：2010-08-10
	描述：历史销售订单
	
	修改：统一销售订单，组合品销售订单查询 需要优化查询
--------------------------------------------*/

CREATE    PROCEDURE QP_Web_HistoryOrderQuotePrice
(
	@OperatorId		varchar(100),
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@PType			varchar(256),
	@btypeid		varchar(1000),
	@OrderState		int,  			--订单状态 0为全部 1为未完成 2为已完成 3为中止订单
	@STypeId		varchar(max),	--分支机构
	@BillType		VARCHAR(10)='300'
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @OperatorId

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********

CREATE TABLE #btype(typeid varchar(100),tel varchar(50),linkman varchar(50))
CREATE TABLE #ktype(typeid varchar(100))

-- 往来单位
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)
if @btypeid=''
	INSERT INTO #btype(typeid,tel,linkman) values('','','') --复制的订单无往来位

-- 仓库
INSERT INTO #KTYPE  SELECT TypeID  FROM F_BaseGetManDetailKType(@chvOperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
-- ******** 权限范围单独处理 - End ********

DECLARE @SQLWHERE VARCHAR(1000)

SET @SQLWHERE='  WHERE O.PTYPEID= '''+@PType+''''

IF @ORDERSTATE=5
BEGIN
	SET @SQLWHERE=@SQLWHERE+' and i.orderstate=''0'' '
END

IF @ORDERSTATE=1
BEGIN
	SET @SQLWHERE=@SQLWHERE+' and i.orderstate=''0'' '
END

IF @ORDERSTATE=2
BEGIN
	SET @SQLWHERE=@SQLWHERE+' and i.orderstate=''1'' '
END

IF @ORDERSTATE=3
BEGIN
	SET @SQLWHERE=@SQLWHERE+' and i.billover=''1'' '
END

IF @ORDERSTATE=4
BEGIN
	SET @SQLWHERE=@SQLWHERE+' and i.billover=''0'' '	
END

if @startdate<>''
	set @SQLWHERE=@SQLWHERE+' AND  i.billdate>='''+@startdate+''''
if @enddate<>''
BEGIN
	set @SQLWHERE=@SQLWHERE+' AND i.billdate<='''+@enddate+''''
END

CREATE TABLE #Order
(
	BillNumberID	INT,
	orderid			INT,
	Comment			VARCHAR(500),
	DiscountPrice	NUMERIC(24,10),
	TaxPrice		NUMERIC(24,10),
	Taxtotal		NUMERIC(24,10),
	PTypeID			VARCHAR(100),
	GoodsNumber		VARCHAR(100),
	ItemID			INT,
	IsCombined		INT,
	Total			NUMERIC(24,10),
	Qty				NUMERIC(24,10),
	WaitQty			NUMERIC(24,10),
	ReachQty		NUMERIC(24,10),
	ktypeid     VARCHAR(500)
)

INSERT INTO #Order
        ( BillNumberID ,
          orderid ,
          Comment ,
          DiscountPrice ,
          TaxPrice ,
          Taxtotal ,
          PTypeID ,
          GoodsNumber ,
          ItemID ,
          IsCombined ,
          Qty ,
          WaitQty ,
          ReachQty,
          Total,
          ktypeid
        )
SELECT	  
	BillNumberID , orderid ,  Comment , DiscountPrice , TaxPrice ,
	Taxtotal , PTypeID ,  GoodsNumber , ItemID , IsCombined ,Qty , WaitQty ,ReachQty,Total,KTypeID
FROM
(	
	SELECT
		A.BillNumberID , orderid ,  A.Comment , DiscountPrice , TaxPrice ,
		Taxtotal , PTypeID ,  A.GoodsNumber , ItemID , IsCombined ,Qty , WaitQty ,ReachQty,Total,A.KTypeID
    FROM dbo.OrderBill A INNER JOIN OrderIndex B ON A.billNumberID=B.billNumberId AND B.billtype=300
    WHERE PTypeID=CASE WHEN @PType<>'' THEN @PType ELSE ptypeid END
    UNION ALL 
    SELECT
		BillNumberID , orderid ,  Comment , DiscountPrice , TaxPrice ,
		Taxtotal , PTypeID ,  '' AS GoodsNumber , ItemID , IsCombined ,Qty , WaitQty ,ReachQty,Total ,KTypeID
    FROM dbo.PT_Combin_OrderBill WHERE PTypeID=CASE WHEN @PType<>'' THEN @PType ELSE ptypeid END
)  [Order]


SET @SQLWHERE=@SQLWHERE+'
			GROUP BY i.BillNumberId,
  					 i.BillDate,
					 i.BillCode,
					 i.BillType,
					 i.BTypeId,
					 i.DealBTypeId,
					 i.stypeid,
					 o.comment,
					 o.DiscountPrice,
					 o.TaxPrice,
					 o.ptypeid,
					 o.goodsnumber,
					 pt.customitemid,
					 pt.customitemfrom,
					 pt.customitemname,
					 pt.customitemrefid,		        
					 o.ItemId,
					 o.IsCombined,
					 BI.BID,
					 i.ReachDate,
					 i.BillOver,
					 i.OrderState,
					 BI1.ReachQty
			ORDER BY I.BILLDATE DESC'


DECLARE @SQL VARCHAR(8000)

SET @SQL='  SELECT  i.billnumberid,
					i.btypeid,
					i.DealBTypeId,
					(select usercode from btype where typeid=i.DealBTypeId) as dusercode,
					(select fullname from btype where typeid=i.DealBTypeId) as dfullname,
					i.billcode,
					i.billdate,					
					i.billtype,
					i.stypeid,
					o.comment,
					o.ptypeid,
					o.goodsnumber,
					i.orderstate,BI1.ReachQty,i.billover,i.reachdate,pt.customitemid,
					pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid,		        
					itemid=o.ItemId,
					itemname= CASE WHEN o.IsCombined = 0  THEN
								(SELECT FullName FROM xw_SelfData WHERE _Id= o.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= o.ItemId ) END,
					iscombined=o.IsCombined,				
					sum(o.qty) as qty,
					abs(o.discountprice) as discountprice,
					sum(o.total) as discounttotal,
					abs(o.taxprice) as taxprice,
					sum(o.taxtotal) as taxtotal,
					CASE WHEN i.BillType=300 THEN ''销售订单'' ELSE ''组合品销售订单'' END as billname,
					CASE WHEN	i.OrderState = 1 THEN ''已完成''  WHEN  i.orderstate=0 THEN ''未完成订单''
					WHEN	BI1.ReachQty=0 AND BI.BID IS NULL THEN ''未引用''
					ELSE ''已引用未完成'' END  AS ordertype
			FROM OrderIndex i
			INNER JOIN #GetManSTypeId S ON i.STypeId = S.TypeId
			INNER JOIN #Order o ON i.billnumberid=o.billnumberid
			INNER JOIN dbo.PType pt ON o.PTypeID = pt.TypeID
			INNER JOIN (
				SELECT a.BillNumberID,max(a.BID) as BID
				FROM 
				(				
					SELECT distinct detail.BillNumberID,(BB.orderid) as BID
					FROM #Order detail 
					LEFT JOIN 
					(
						SELECT bb.orderid from salebill bb --ON detail.OrderID=bb.orderid
						INNER JOIN BillIndex bi ON bb.billnumberid=bi.billnumberid and bi.redword=0--排除红冲单据
					) bb ON detail.OrderID=bb.orderid
					INNER JOIN PType p ON detail.PtypeID=p.typeid'

SET @SQL = @SQL + '
				)a GROUP BY A.billNumberID
				) bi ON i.billNumberId=BI.billNumberID
	INNER JOIN (								
				SELECT B.billNumberID,
					   sum(b.WaitQty) AS WaitQty,
					   sum(b.Qty) AS Qty,
					   sum(b.ReachQty) AS ReachQty 
				FROM(								
					SELECT detail.BillNumberID,
						   detail.WaitQty,
						   detail.Qty,
						   detail.ReachQty
					FROM #Order detail
					) b GROUP BY B.billNumberID
				) BI1 ON i.billnumberid=BI1.billnumberid '

IF NOT @chvMKTypeId = '00000'
	SET @SQL = @SQL + ' INNER JOIN #KTYPE K ON K.TypeId = o.kTypeId '

IF NOT (@btypeid = '' AND @chvMBTypeId = '00001' AND @chvMBTypeId2 = '00002')
	SET @SQL=@SQL + ' INNER JOIN  #Btype B ON  i.DealBTypeId=B.typeid '
	
IF(@OrderState=4)  --未引用订单
BEGIN
	SET @SQL+= ' AND BI1.ReachQty=0 AND BI.BID IS NULL '
END
ELSE
BEGIN
	SET @SQL+= CASE @OrderState WHEN 1 THEN ' AND (i.OrderState = 0 AND BI.BID IS NOT NULL)' --未完成订单
								WHEN 2 THEN ' AND i.OrderState = 1'  --已完成订单
								WHEN 5 THEN ' AND i.OrderState = 0'  --未完成订单
								ELSE ' AND (i.OrderState = 1 OR i.OrderState = 0)' 
				END
END				
SET @SQL=@SQL+@SQLWHERE
--print @sql
PRINT @SQL
EXEC(@SQL)

DROP TABLE #BTYPE,#KTYPE,#GetManSTypeId,#Order


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_InsuranceBillQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_InsuranceBillQuery]
GO


/**---------------------------------------------------------------**/
--作者：毛欣蓉
--日期：2010-0917
--功能：保险理赔单查询
/**--------------------------------------------------------------**/

CREATE  PROCEDURE  Qp_Web_InsuranceBillQuery
(	
	@OperatorID		varchar(100),
	@startdate		varchar(20)='',
	@enddate		varchar(20)='',	
	@etypeid		varchar(2000)='',
	@ratypeid       varchar(2000)='',     	--车牌号
	@btypeid   		varchar(2000)='',    	--保险公司
	@btypeid1   	varchar(2000)='',	--往来单位
	@billcode		varchar(100)='',	--理赔单号
	@STypeId		varchar(max)
)
--@encode$--
AS
set nocount on
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--保险公司   
create table #btype(typeid varchar(100),usercode varchar(100),fullname varchar(200),linkman varchar(100))
INSERT INTO #Btype(typeid,usercode,fullname,linkman) SELECT b.typeid,b.usercode,b.fullname,b.linkman1 FROM btype b ,F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) a where a.typeid=b.typeid 

--往来单位    
create table #btype1(typeid varchar(100))
INSERT INTO #Btype1(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid1,2,'00001')

create table #etype(typeid varchar(100))
INSERT INTO #Etype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--车牌号
create table #car(typeid varchar(100),PlateNumber varchar(200))
IF @ratypeid<>''
	INSERT INTO #car(typeid,PlateNumber) SELECT typeid,PlateNumber from Qp_repairautoinfo a,(select * from  dbo.f_split(@ratypeid,',')) b where left(a.typeid,len(b.a))=b.a
ELSE
	INSERT INTO #car(typeid,PlateNumber) SELECT typeid,PlateNumber from Qp_repairautoinfo

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

-------------多级权限检查 end --------------

declare @sql varchar(8000)


SET @sql='
	SELECT 	i.billnumberid,
			i.billtype,
			i.billcode,
			i.billdate,
			i.btypeid,
			i.stypeid,
			bb.usercode as busercode,
			bb.fullname as bfullname,
			bb.linkman as blinkman,
			i.etypeid,
			i.explain,
			i.comment,
			i.redword,
			i.cwcheck,
			c.ratypeid,
			c.BTypeID1,
			c.QuickRepairBillID,
			bi.billcode as wxbillcode,
			c.ManHourInsuranceTotal,
			c.PTypeInsuranceTotal,
			isnull(c.ManHourInsuranceTotal,0)+isnull(c.PTypeInsuranceTotal,0) as total,
			''保险理赔单'' as billname	
	FROM	billindex i
	INNER JOIN billindex_carRepair c on i.billnumberid=c.billnumberid
	INNER JOIN #car a on a.typeid=c.ratypeid 
	INNER JOIN  #Btype BB ON  i.btypeid=BB.typeid
	INNER JOIN billindex bi on c.QuickRepairBillID=bi.billnumberid
	INNER JOIN #GetManDTypeId D ON D.TypeId = I.DTypeId '

	IF NOT (@btypeid1 = '' AND @MBTypeId = '00001')
		SET @SQL=@SQL + ' INNER JOIN  #Btype1 B ON  b.typeid=c.btypeid1 '

	IF NOT (@etypeid = '' AND @METypeId = '00001')
		SET @SQL=@SQL + ' INNER JOIN  #Etype e ON  e.typeid=i.etypeid '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '					

	SET @sql=@sql+' WHERE	i.billtype=186 
							AND i.ifcheck=''t'' 
							AND i.redword=0 
							AND i.billcode like ''%'+@billcode+'%'''
	SET @Sql=@Sql + ' AND i.ifYearBill= 0 '    --年节存标志
	IF @startdate<>''
		set @sql=@sql+' AND  i.billdate>='''+@startdate+''''
	IF @enddate<>''
		set @sql=@sql+' AND i.billdate<='''+@enddate+''''

	SET @sql=@sql + ' ORDER  by  i.BillDate DESC,i.billcode DESC'

	--PRINT(@sql)
	EXEC(@sql)

	DROP TABLE #btype,#btype1,#car,#GetManSTypeId,#GetManDTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_InsuranceitemsqueryDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_InsuranceitemsqueryDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王伟
	日期：2010-09-16
	描述：理赔项目查询明细表
*/

CREATE PROCEDURE Qp_Web_InsuranceitemsqueryDetail
(
	@OperatorID		VARCHAR(8000),
	@StartTime		DATETIME,
	@EndTime		DATETIME,
	@BTypeId		VARCHAR(8000),
	@WTypeId		VARCHAR(8000),
	@VirtualType	VARCHAR(10)='-1',
	@EtypeId		varchar(8000),
	@BtypeId1		varchar(8000),	--往来单位,
	@STypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
	
--保险公司
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorID)
			
--往来单位
CREATE TABLE #GetManBTypeId1(TypeId	varchar(100))
INSERT INTO #GetManBTypeId1(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BtypeId1,2,'00001')

--经手人
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) 
	SELECT e.typeid FROM F_GetManDetailEType(@OperatorID) e	INNER JOIN dbo.F_GetAllBaseTypeId(@etypeId,3) se ON e.TypeId = se.TypeId
ELSE 
	INSERT INTO #GetManETypeId(TypeId)	SELECT typeid FROM	F_GetAllBaseTypeId(@etypeId,3)
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)		
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)		
		
DECLARE @SQL VARCHAR(8000)
SET @SQL='
		SELECT 	bi.billdate,
				bi.billCode,
				bi.btypeid,
				bi.stypeid,
				(bi1.billCode) as wxbillcode,
				(cp.RATypeID)as ratypeid,			
				Ri.RepairItemsTypeID as witypeid,
				Ri.ManHour,
				Ri.Total,
				Ri.InsuranceTotal,
				Ri.CostTotal,
				CAST(ISNULL((Ri.InsuranceTotal-Ri.CostTotal),0) AS  NUMERIC(24, 10) ) AS GrossProfit, --毛利(理赔金额-工时成本)
				(CASE Ri.InsuranceTotal 
					WHEN 0 THEN 0
					ELSE CAST(ISNULL(((Ri.InsuranceTotal-Ri.CostTotal)/Ri.InsuranceTotal)*100,0) AS  NUMERIC(24, 10) )
				END) AS Gprofit, --毛利率(毛利/理赔金额(保留两位小数))	
				Ri.Comment,
				Ri.Virtual,
				bi.billtype,
				bi.billnumberid
		FROM BillIndex bi 
		INNER JOIN  QP_InsuranceBill_RepairItems Ri ON bi.BillNumberId = Ri.BillNumberId
		INNER JOIN Billindex_CarRepair cp ON  bi.BillNumberId =cp.BillNumberId 
		INNER JOIN BillIndex bi1 ON bi1.BillNumberId=cp.QuickRepairBillID
		INNER JOIN #GetManDTypeId D ON D.TypeId = Bi.DTypeId ' 
				
		IF @BTypeId<>'' OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL=@SQL+CHAR(10)+' INNER JOIN #GetManBTypeId b ON b.typeid=bi.btypeid '	
	
		IF @ETypeId<>'' OR @MEtypeid='-99999'
			SET @SQL=@SQL+CHAR(10)+' INNER JOIN #GetManETypeId e ON e.typeid=bi.etypeid '	
			
		IF @BTypeId1<>''  OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL=@SQL+CHAR(10)+' INNER JOIN #GetManBTypeId1 b1 ON b1.typeid=cp.btypeid1 '	
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '					

SET @Sql=@Sql+' 
		WHERE	bi.billtype=186 
				AND bi.ifcheck=''t''
				AND bi.RedWord=0
				AND bi.Billdate>= '+CHAR(39)+CAST(@StartTime AS VARCHAR(100))+CHAR(39)+' 
				AND bi.Billdate<= '+CHAR(39)+CAST(@EndTime AS VARCHAR(100))+CHAR(39)	
	SET @Sql=@Sql + ' AND bi.ifYearBill= 0 '    --年节存标志			
IF @VirtualType<>'-1' 
	SET @SQL = @SQL + ' AND Ri.Virtual= '+CAST(@VirtualType AS VARCHAR(10))
IF @WTypeId<>''
	SET @SQL=@SQL+' AND Ri.RepairItemsTypeID like '+CHAR(39)+@WTypeId+'%'+CHAR(39)		
	
SET @SQL = @SQL + ' ORDER BY  bi.billdate,bi.billCode asc '

--print(@Sql)
EXEC(@Sql)

DROP TABLE #GetManBTypeId1,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_InsuranceitemsqueryLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_InsuranceitemsqueryLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王伟
	日期：2010-09-16
	描述：理赔项目查询线性表
*/

CREATE PROCEDURE Qp_Web_InsuranceitemsqueryLine
(
	@OperatorID		VARCHAR(8000),
	@StartTime		DATETIME,
	@EndTime		DATETIME,
	@BTypeId		VARCHAR(8000),
	@WTypeId		VARCHAR(8000),
	@VirtualType	VARCHAR(10)='-1',
	@EtypeId		varchar(8000),
	@BtypeId1		varchar(8000),	--往来单位,
	@StypeId		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
		
--保险公司
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorID)
		
--往来单位
CREATE TABLE #GetManBTypeId1(TypeId	varchar(100))
INSERT INTO #GetManBTypeId1(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BtypeId1,2,'00001')

--经手人
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) 
	SELECT e.typeid FROM F_GetManDetailEType(@OperatorID) e	INNER JOIN dbo.F_GetAllBaseTypeId(@etypeId,3) se ON e.TypeId = se.TypeId
ELSE 
	INSERT INTO #GetManETypeId(TypeId)	SELECT typeid FROM	F_GetAllBaseTypeId(@etypeId,3)
	
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)		
	
DECLARE @SQL VARCHAR(8000)
SET @SQL='
		SELECT 	Items.typeid,
				ISNULL(M.ManHour,0) as ManHour,
				ISNULL(M.Total,0) as Total,
				ISNULL(M.InsuranceTotal,0) as InsuranceTotal,
				ISNULL(M.CostTotal,0) as CostTotal,
				CAST(
					(ISNULL(M.InsuranceTotal,0)-ISNULL(M.CostTotal,0)) AS  NUMERIC(24, 10) 
					) AS GrossProfit, --毛利(理赔金额-工时成本)			
				(CASE M.InsuranceTotal 
					WHEN 0 THEN 0
					ELSE
						CAST(ISNULL(((ISNULL(M.InsuranceTotal,0)-ISNULL(M.CostTotal,0))/M.InsuranceTotal)*100,0) AS  NUMERIC(24, 10)  )
				END)AS Gprofit, --毛利率(毛利/理赔金额(保留两位小数))	
				Items.sonnum
		FROM	QP_RepairItems	 Items
				INNER JOIN (
					SELECT 	
							Ri.RepairItemsTypeID,
							Sum(ISNULL(Ri.ManHour,0)) as ManHour,
							Sum(ISNULL(Ri.Total,0)) as Total,
							Sum(ISNULL(Ri.InsuranceTotal,0)) as InsuranceTotal,
							Sum(ISNULL(Ri.CostTotal,0)) as CostTotal
					FROM BillIndex bi  
					INNER JOIN Billindex_CarRepair cr ON bi.BillNumberId=cr.BillNumberId
					INNER JOIN  QP_InsuranceBill_RepairItems Ri ON bi.BillNumberId = Ri.BillNumberId
					INNER JOIN #GetManDTypeId D ON D.TypeId = Bi.DTypeId ' 
					
		IF @BTypeId<>'' OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL=@SQL+' INNER JOIN #GetManBTypeId b ON b.typeid=bi.btypeid '	
	
		IF @ETypeId<>'' OR @MEtypeid='-99999'
			SET @SQL=@SQL+' INNER JOIN #GetManETypeId e ON e.typeid=bi.etypeid '	
			
		IF @BTypeId1<>''  OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL=@SQL+' INNER JOIN #GetManBTypeId1 b1 ON b1.typeid=cr.btypeid1 '	
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '				
					
		SET @Sql=@Sql+' 
					WHERE bi.billtype=186 
							AND bi.ifcheck=''t''
							AND bi.RedWord=0		
							AND bi.Billdate>= '+CHAR(39)+CAST(@StartTime AS VARCHAR(100))+CHAR(39)+' 
							AND bi.Billdate<= '+CHAR(39)+CAST(@EndTime AS VARCHAR(100))+CHAR(39)	
							
SET @Sql=@Sql + ' AND bi.ifYearBill= 0 '    --年节存标志							
	IF @VirtualType<>'-1' 
		SET @SQL = @SQL + ' AND Ri.Virtual= '+CAST(@VirtualType AS VARCHAR(10))
SET @SQL = @SQL + ' 
					GROUP BY Ri.RepairItemsTypeID  '				
										
SET @Sql=@Sql+'	) M ON  M.RepairItemsTypeID=Items.TypeId '-- LEFT(LTRIM(RTRIM(M.RepairItemsTypeID)),LEN(LTRIM(RTRIM(Items.TypeId)))) = LTRIM(RTRIM(Items.TypeId))

SET @SQL = @SQL + ' WHERE Items.sonnum=0 '

IF @WTypeId<>''
	SET @SQL = @SQL + ' AND Items.TypeId like  '+CHAR(39)+@WTypeId+'%'+CHAR(39)

		
SET @SQL = @SQL + ' ORDER BY  Items.Usercode asc	'

--PRINT(@Sql)
EXEC(@Sql)
DROP TABLE #GetManBTypeId1,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_InsuranceitemsqueryList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_InsuranceitemsqueryList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王伟
	日期：2010-09-16
	描述：理赔项目查询树型表
*/

CREATE PROCEDURE Qp_Web_InsuranceitemsqueryList
(
	@OperatorID		VARCHAR(100),
	@StartTime		DATETIME,
	@EndTime		DATETIME,
	@BTypeId		VARCHAR(8000),	--保险公司
	@WTypeId		VARCHAR(8000),	--维修项目
	@VirtualType	VARCHAR(10)='-1',
	@EtypeId		varchar(8000),
	@BtypeId1		varchar(8000),	--往来单位,
	@STypeId		VARCHAR(MAX)
)

--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

IF @VirtualType IS NULL 
	SET @VirtualType='-1'
IF @WTypeId = ''
	SET @WTypeId = '00000'
			
--保险公司
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorID)
	
--往来单位
CREATE TABLE #GetManBTypeId1(TypeId	varchar(100))
INSERT INTO #GetManBTypeId1(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BtypeId1,2,'00001')	

--经手人
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) 
	SELECT e.typeid FROM F_GetManDetailEType(@OperatorID) e	INNER JOIN dbo.F_GetAllBaseTypeId(@etypeId,3) se ON e.TypeId = se.TypeId
ELSE 
	INSERT INTO #GetManETypeId(TypeId)	SELECT typeid FROM	F_GetAllBaseTypeId(@etypeId,3)
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)		
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

DECLARE @SQL VARCHAR(8000),@SonNum	INT
SELECT @SonNum = SonNum FROM QP_RepairItems WHERE typeId = @WTypeId
		
DECLARE @Len INT
SET @Len=5 
IF @WTypeId<>'00000' 	SET @Len=LEN(@WTypeId)+5
--print(@Len)	

SET @SQL='
		SELECT 	Items.typeid,
				ISNULL(M.ManHour,0) as ManHour,
				ISNULL(M.Total,0) as Total,
				ISNULL(M.InsuranceTotal,0) as InsuranceTotal,
				ISNULL(M.CostTotal,0) as CostTotal,
				CAST(
					(ISNULL(M.InsuranceTotal,0)-ISNULL(M.CostTotal,0)) AS  NUMERIC(24, 10) 
					) AS GrossProfit, --毛利(理赔金额-工时成本)

				(CASE M.InsuranceTotal 
					WHEN 0 THEN 0
					ELSE
						CAST(ISNULL(((ISNULL(M.InsuranceTotal,0)-ISNULL(M.CostTotal,0))/M.InsuranceTotal)*100,0) AS  NUMERIC(24, 10)  )
				END)AS Gprofit, --毛利率(毛利/理赔金额(保留两位小数))																			
				Items.sonnum
		FROM	QP_RepairItems	 Items
				LEFT JOIN (
					SELECT 	
							--Ri.RepairItemsTypeID,
							LEFT(Ri.RepairItemsTypeID,'+CAST(@Len as VARCHAR(100))+') as RepairItemsTypeID,
							Sum(ISNULL(Ri.ManHour,0)) as ManHour,
							Sum(ISNULL(Ri.Total,0)) as Total,
							Sum(ISNULL(Ri.InsuranceTotal,0)) as InsuranceTotal,
							Sum(ISNULL(Ri.CostTotal,0)) as CostTotal
					FROM BillIndex bi 
					INNER JOIN Billindex_CarRepair cr ON bi.BillNumberId=cr.BillNumberId
					INNER JOIN  QP_InsuranceBill_RepairItems Ri ON bi.BillNumberId = Ri.BillNumberId
					INNER JOIN #GetManDTypeId D ON D.TypeId = Bi.DTypeId ' 
					
		IF @BTypeId<>'' OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL=@SQL+' INNER JOIN #GetManBTypeId b ON b.typeid=bi.btypeid '	
			
		IF @ETypeId<>'' OR @MEtypeid='-99999'
			SET @SQL=@SQL+' INNER JOIN #GetManETypeId e ON e.typeid=bi.etypeid '	
			
		IF @BTypeId1<>''  OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL=@SQL+' INNER JOIN #GetManBTypeId1 b1 ON b1.typeid=cr.btypeid1 '	
		
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '				
			
		SET @Sql=@Sql+' 
					WHERE bi.billtype=186 
							AND bi.ifcheck=''t''
							AND bi.RedWord=0
							AND bi.Billdate>= '+CHAR(39)+CAST(@StartTime AS VARCHAR(100))+CHAR(39)+' 
							AND bi.Billdate<= '+CHAR(39)+CAST(@EndTime AS VARCHAR(100))+CHAR(39)	
SET @Sql=@Sql + ' AND bi.ifYearBill= 0 '    --年节存标志
							
	IF @VirtualType<>'-1' 
		SET @SQL = @SQL + ' AND Ri.Virtual= '+CAST(@VirtualType AS VARCHAR(10))

SET @SQL = @SQL + ' 
					--GROUP BY Ri.RepairItemsTypeID  
					GROUP BY LEFT(Ri.RepairItemsTypeID,'+CAST(@Len as VARCHAR(100))+') '	
		
										
SET @Sql=@Sql+'	) M ON M.RepairItemsTypeID like Items.TypeId+'+CHAR(39)+'%'+CHAR(39)

SET @SQL = @SQL + ' WHERE 1=1 AND Items.TypeId <> ''00000'''

IF @SonNum = 0
	SET @SQL = @SQL + ' AND Items.TypeId = '+CHAR(39)+@WTypeId+CHAR(39)
ELSE
	SET @SQL = @SQL + ' AND Items.ParId = '+CHAR(39)+@WTypeId+CHAR(39)
		
SET @SQL = @SQL + ' ORDER BY  Items.Usercode asc	'

--PRINT(@Sql)
EXEC(@Sql)

DROP TABLE #GetManBTypeId1,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_IPtypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_IPtypeDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_IPtypeDetail (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @startdate		varchar(50), --开始时间
   @enddate			varchar(50),--结束时间
   @chvBtypeID		varchar(4000),
   @chvPTypeID		varchar(4000),
   @chvETypeID		varchar(4000),
   @chvBtypeID1		varchar(4000),
   @Virtual			int =9,
   @STypeId			varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Btype1 (TypeID varchar(50))

--商品
INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

--职员
INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID)

--保险公司
INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID)

--往来单位    
INSERT INTO #Btype1(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID1,2,'00001')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

DECLARE @SQL varchar(8000)

SET @SQL='SELECT A.BillNumberId,
                 A.BillDate,
                 A.BillCode,
                 A.STypeid,
                 (SELECT BillCode FROM Billindex WHERE  BillNumberId=N.QuickRepairBillID) AS QuickRepairBillCode,
                 A.BillType,
                 N.ratypeid,                 
                 A.btypeid,
                 B.PTypeID,
                 B.Qty AS Qty,
                 B.TaxPrice AS TaxPrice,
                 B.TaxTotal AS TaxTotal,
                 B.InsuranceTotal,
                 CASE WHEN ISNULL(B.Qty,0)=0 THEN 0 ELSE ISNULL(B.GoodsCostTotal,0)/ISNULL(B.Qty,1) END AS CostPrice ,
                 B.GoodsCostTotal AS CostTotal,
                 ISNULL(B.InsuranceTotal,0)-ISNULL(B.GoodsCostTotal,0) AS Maoli,
                 CASE WHEN ISNULL(B.InsuranceTotal,0)=0 THEN 0 ELSE (ISNULL(B.InsuranceTotal,0)-ISNULL(B.GoodsCostTotal,0))/ISNULL(B.InsuranceTotal,0)*100 END AS Maolilu,          
                 A.DTypeId , 
                 B.Comment,
                 Virtual
           FROM  Billindex A 
		   INNER JOIN  Billindex_CarRepair N ON A.BillNumberId=N.BillNumberId 
           INNER JOIN  QP_InsuranceBill_PType B ON A.BillNumberId=B.BillNumberId
           INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeId '

IF NOT (@chvETypeId = '' AND @METypeId = '00001')
	SET @SQL=@SQL+ ' INNER JOIN  #Etype E ON A.ETypeID=E.TypeID '

IF NOT (@chvPTypeID ='' AND @MPtypeid = '00000')
	SET @SQL=@SQL+ ' INNER JOIN  #Ptype P ON B.PTypeID=P.TypeID '

IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '

IF NOT (@chvBtypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL=@SQL+ ' INNER JOIN #Btype BB ON LEFT(A.Btypeid,LEN(BB.TypeID)) = BB.TypeID '

IF NOT (@chvBtypeID1 = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL=@SQL+ ' INNER JOIN  Billindex_CarRepair BBB ON  A.BillNumberId=BBB.BillNumberId 
				 INNER JOIN  #Btype1 BBBB ON   N.BTypeID1=BBBB.typeid   '

-------------条件-----------
SET @SQL = @SQL + '  WHERE	A.BillType=186 
							AND A.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
							AND A.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
							AND A.RedWord=0							
							AND A.IfCheck = ''t'''
SET @Sql=@Sql + ' AND A.ifYearBill= 0 '    --年节存标志							
IF @Virtual=0
	SET @SQL = @SQL + ' AND B.Virtual = 0'
	
IF @Virtual=1
	SET @SQL = @SQL + ' AND B.Virtual = 1'

SET @SQL=@SQL+ '  ORDER BY A.BillDate ASC, A.BillCode ASC '

--PRINT @SQL RETURN
EXEC(@SQL)
        
DROP TABLE #Ptype,#Btype,#Etype,#GetManSTypeId,#GetManDTypeId

         
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_IPtypeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_IPtypeLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_IPtypeLine (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @startdate		varchar(50), --开始时间
   @enddate			varchar(50),--结束时间
   @chvBtypeID		varchar(4000),
   @chvPTypeID		varchar(4000),
   @chvETypeID		varchar(4000),
   @chvBtypeID1		varchar(4000),
   @Virtual			int =9,
   @STypeId			varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Btype1 (TypeID varchar(50))

CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,deleted int) 

--商品
INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

--职员
INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID)

--保险公司
INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID) --SELECT A FROM dbo.f_split(@chvBtypeID,',')

--往来单位    
INSERT INTO #Btype1(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID1,2,'00001')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

DECLARE @sonnum int 
SET @sonnum =0

SELECT @sonnum = sonnum FROM Ptype WHERE Typeid =@chvPTypeID
IF @chvPTypeID='00000'
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p WHERE p.typeid<>'00000' AND p.sonnum=0
ELSE
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p WHERE typeid like @chvPTypeID+'%' AND p.typeid<>'00000' AND  p.sonnum=0

DECLARE @SQL varchar(8000)

SET @SQL='SELECT	TypeID,
				  ISNULL(Qty,0)  AS Qty,
				  ISNULL(TaxTotal,0) AS TaxTotal,
				  ISNULL(InsuranceTotal,0) AS InsuranceTotal,
				  ISNULL(CostTotal,0) AS CostTotal,
				  ISNULL(Maoli,0) AS Maoli,
				  ISNULL(maolilu,0) AS  maolilu
          FROM #MainType M  
          INNER JOIN  (
                SELECT  PtypeID,
						ISNULL(SUM(Qty),0) as Qty,
						ISNULL(SUM(TaxTotal),0) as TaxTotal,
						ISNULL(SUM(InsuranceTotal),0) as InsuranceTotal,
						ISNULL(SUM(CostTotal),0) as CostTotal,
						ISNULL(SUM(InsuranceTotal),0)-ISNULL(SUM(CostTotal),0) as Maoli,
						CASE WHEN ISNULL(SUM(InsuranceTotal),0)=0 THEN 0 ELSE  (ISNULL(SUM(InsuranceTotal),0)-ISNULL(SUM(CostTotal),0))/ISNULL(SUM(InsuranceTotal),1)*100 END as maolilu
			    FROM  (
							SELECT	B.PtypeID ,
									B.Qty AS Qty,Convert( NUMERIC(24, 10) ,
									B.GoodsCostTotal) AS CostTotal, 
									Convert( NUMERIC(24, 10) ,B.TaxTotal) AS TaxTotal,
									Convert( NUMERIC(24, 10) ,B.InsuranceTotal) as InsuranceTotal
							FROM	Billindex A 
							INNER JOIN  QP_InsuranceBill_PType B ON A.BillNumberId=B.BillNumberId
							INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeId '

    IF NOT (@chvETypeId = '' AND @METypeId = '00001')
		SET @SQL=@SQL+ ' INNER JOIN  #Etype E ON A.ETypeID=E.TypeID '    

    IF NOT (@chvPTypeID ='' AND @MPtypeid = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Ptype P ON B.PTypeID=P.TypeID '

	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '

    IF NOT (@chvBtypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL=@SQL+ ' INNER JOIN #Btype BB ON LEFT(A.Btypeid,LEN(BB.TypeID)) = BB.TypeID '

    IF NOT (@chvBtypeID1 = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
    SET @SQL=@SQL+ ' INNER JOIN  Billindex_CarRepair BBB ON  A.BillNumberId=BBB.BillNumberId 
                     INNER JOIN  #Btype1 BBBB ON   BBB.BTypeID1=BBBB.typeid   '


    -------------条件-----------
    SET @SQL = @SQL + '  WHERE	A.BillType=186 
								AND A.RedWord=0
								AND	A.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND A.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)
								
	SET @Sql=@Sql + ' AND A.ifYearBill= 0 '    --年节存标志

	SET @SQL = @SQL + ' AND A.IfCheck = ''t'''
    IF @Virtual=0
        SET @SQL = @SQL + ' AND B.Virtual = 0'
    IF @Virtual=1
        SET @SQL = @SQL + ' AND B.Virtual = 1'
 
    SET @SQL=@SQL+ ' ) TT GROUP BY PtypeID )  T  ON LEFT(M.TypeID,LEN(T.PTypeID)) = T.PTypeID
    ORDER BY   usercode ASC '
    
--PRINT @SQL RETURN
EXEC(@SQL)        

DROP TABLE #MainType,#Ptype,#Btype,#Etype,#GetManSTypeId,#GetManDTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_IPtypeList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_IPtypeList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_web_IPtypeList (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @parid			varchar(100)='00000',
   @startdate		varchar(50), --开始时间
   @enddate			varchar(50),--结束时间
   @chvBtypeID		varchar(4000),
   @chvPTypeID		varchar(4000),
   @chvETypeID		varchar(4000),
   @chvBtypeID1		varchar(4000),
   @Virtual			int =9,
   @STypeId			varchar(max)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Btype1 (TypeID varchar(50))

IF(@parid='00000' AND ISNULL(@chvPTypeID,'')<>'')
SET @parid=@chvPTypeID

CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,deleted int) 

--商品
INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

--职员
INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID)

--保险公司
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBtypeID,'2',@OperatorID)

--往来单位    
INSERT INTO #Btype1(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID1,2,'00001')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

DECLARE @sonnum INT
SET @sonnum =0
SELECT @sonnum = sonnum FROM Ptype WHERE Typeid=@Parid

IF @sonnum =0 	
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p
	,(select * from F_GetManPTypeAll(@OperatorID) where typeid =@Parid) a where p.typeid=a.typeid And p.typeid<>'00000'
ELSE
	IF @Parid='00000'
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid And p.typeid<>'00000'
	ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where parid=@Parid) a where p.typeid=a.typeid And p.typeid<>'00000'

DECLARE @SQL varchar(8000)


SET @SQL=' SELECT	M.TypeID,M.sonnum,
					ISNULL(SUM(Qty),0) as Qty,
					ISNULL(SUM(TaxTotal),0) as TaxTotal,
					ISNULL(SUM(InsuranceTotal),0) as InsuranceTotal,
					ISNULL(SUM(CostTotal),0)  as CostTotal,
					ISNULL(SUM(InsuranceTotal),0)-ISNULL(SUM(CostTotal),0) as Maoli,
					CASE WHEN ISNULL(SUM(InsuranceTotal),0)=0 THEN 0 ELSE  (ISNULL(SUM(InsuranceTotal),0)-ISNULL(SUM(CostTotal),0))/ISNULL(SUM(InsuranceTotal),1)*100 END as maolilu
		   FROM		#MainType M  
		   LEFT JOIN (
						SELECT	B.PtypeID,
								B.Qty AS Qty,
								Convert( NUMERIC(24, 10) ,B.GoodsCostTotal) AS CostTotal, 
								Convert( NUMERIC(24, 10) ,B.TaxTotal) AS TaxTotal,
								Convert( NUMERIC(24, 10) ,B.InsuranceTotal) as InsuranceTotal
						FROM	Billindex A 
						INNER JOIN  QP_InsuranceBill_PType B ON A.BillNumberId=B.BillNumberId
						INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeId  '

    IF NOT (@chvETypeId = '' AND @METypeId = '00001')
		SET @SQL=@SQL+ ' INNER JOIN  #Etype E ON A.ETypeID=E.TypeID '

    IF NOT (@chvPTypeID ='' AND @MPtypeid = '00000')
		SET @SQL=@SQL+ ' INNER JOIN  #Ptype P ON B.PTypeID=P.TypeID '

	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	

    IF NOT (@chvBtypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL=@SQL+ ' INNER JOIN #Btype BB ON LEFT(A.Btypeid,LEN(BB.TypeID)) = BB.TypeID '

    IF NOT (@chvBtypeID1 = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL=@SQL+ ' INNER JOIN  Billindex_CarRepair BBB ON  A.BillNumberId=BBB.BillNumberId 
						 INNER JOIN  #Btype1 BBBB ON BBB.BTypeID1=BBBB.typeid   '

    -------------条件-----------
    SET @SQL = @SQL + '  WHERE	A.BillType=186 
								AND A.RedWord=0
								AND A.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND A.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND A.IfCheck = ''t''
								AND A.ifYearBill=0'		--年节存标志

    IF @Virtual=0
        SET @SQL = @SQL + ' AND B.Virtual = 0'
        
    IF @Virtual=1
        SET @SQL = @SQL + ' AND B.Virtual = 1'
 
    SET @SQL=@SQL+ ' ) TT  ON LEFT(TT.PTypeID,LEN(M.TypeID)) = M.TypeID GROUP BY M.TypeID,M.sonnum,M.usercode  
    ORDER BY   M.usercode ASC '

--PRINT @SQL RETURN
EXEC(@SQL)        
DROP TABLE #MainType,#Ptype,#Btype,#GetManSTypeId,#GetManDTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_IPtypeListList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_IPtypeListList]
GO

-- Procedure
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
-- Procedure
CREATE   PROCEDURE dbo.QP_web_IPtypeListList (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @parid varchar(100)='00000',
   @startdate varchar(50), --开始时间
   @enddate varchar(50),--结束时间
   @chvBtypeID varchar(4000),
   @chvPTypeID varchar(4000),
   @Virtual int =9
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Wtype (TypeID varchar(50))

CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,deleted int) 

--商品
INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

--往来单位    
INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID)

DECLARE @sonnum INT
SET @sonnum =0
SELECT @sonnum = sonnum FROM Ptype WHERE Typeid=@Parid

IF @sonnum =0 	
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p
	,(select * from F_BaseGetManPTypeAll(@OperatorID) where typeid =@Parid) a where p.typeid=a.typeid And p.typeid<>'00000'
ELSE
	IF @Parid='00000'
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p
		,(select * from F_BaseGetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid And p.typeid<>'00000'
	ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted FROM Ptype p
		,(select * from F_BaseGetManPTypeAll(@OperatorID) where parid=@Parid) a where p.typeid=a.typeid And p.typeid<>'00000'

DECLARE @SQL varchar(8000)


SET @SQL=' SELECT  M.TypeID,M.sonnum,
		        ISNULL(SUM(Qty),0) as Qty,
			    ISNULL(SUM(TaxTotal),0) as TaxTotal,
				ISNULL(SUM(TaxTotal),0) as TaxTotal,
			    ISNULL(SUM(InsuranceTotal),0) as InsuranceTotal,
                ISNULL(SUM(InsuranceTotal),0)-ISNULL(SUM(CostTotal),0) as Maoli,
                CASE WHEN ISNULL(SUM(InsuranceTotal),0)=0 THEN 0 ELSE  (ISNULL(SUM(TaxTotal),0)-ISNULL(SUM(InsuranceTotal),0))/ISNULL(SUM(InsuranceTotal),1)*100 END as maolilu
			    FROM #MainType M  LEFT JOIN 
                     ( SELECT B.PtypeID ,-B.Qty AS Qty,-Convert( NUMERIC(24, 10) ,B.CostTotal) AS CostTotal, -Convert( NUMERIC(24, 10) ,B.TaxTotal) AS TaxTotal,
                     Convert( NUMERIC(24, 10) ,Q.InsuranceTotal)
                     FROM  Billindex A 
                     INNER JOIN  Billindex_CarRepair N ON A.BillNumberId=N.BillNumberId 
                     INNER JOIN  InOutStocktable B ON A.BillNumberId=B.BillNumberId  
                     INNER JOIN  QP_InsuranceBill_PType Q ON B.[ID]=Q.[ID]'

    IF NOT (@chvPTypeID ='' AND @MPtypeid = '00000')
    SET @SQL=@SQL+ ' INNER JOIN  #Ptype P ON B.PTypeID=P.TypeID '

    IF NOT (@chvBtypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
    SET @SQL=@SQL+ ' INNER JOIN  #Btype BB ON A.Btypeid=BB.typeid  '

    -------------条件-----------
    SET @SQL = @SQL + '  WHERE A.BillType=178 AND N.BillType=178 '
    SET @SQL = @SQL + '  AND A.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND A.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)

    SET @SQL = @SQL + ' AND A.IfCheck = ''t'''

    IF @Virtual=0
        SET @SQL = @SQL + ' AND Q.Virtual = 0'
    IF @Virtual=1
        SET @SQL = @SQL + ' AND Q.Virtual = 1'
 
    SET @SQL=@SQL+ ' ) TT  ON LEFT(LTRIM(RTRIM(TT.PTypeID)),LEN(LTRIM(RTRIM(M.TypeID)))) = LTRIM(RTRIM(M.TypeID)) GROUP BY M.TypeID,M.sonnum,M.usercode  
    ORDER BY   M.usercode ASC '

--PRINT @SQL RETURN
EXEC(@SQL)        
DROP TABLE #MainType
DROP TABLE #Ptype
DROP TABLE #Btype
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_LoadInsuranceBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_LoadInsuranceBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
作者:wang wei 
时间:2010-9-21
描述:加载理赔单主表信息
*/
CREATE          PROCEDURE QP_Web_LoadInsuranceBill 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (8000)
select @sql='
SELECT temp.*,au.BillDetail	
FROM ( 		
				SELECT 	DISTINCT
						a.billdate,
						a.billcode,
						a.etypeid,
						e.fullname as efullname,		
						a.dtypeid,
						d.fullname as dfullname,
						a.btypeid,--保险理赔单的保险公司
						b.fullname as bfullname,
						kx.billcode as wxbillcode,
						cr.ratypeid,
						a.totalqty,
						a.totalmoney,
						a.totalinmoney,
						Qr.PlateNumber as rafullname,
						cr.btypeid1,--往来单位
						b1.fullname as bfullname1,
						a.explain,
						a.comment,
						cr.ManHourInsuranceTotal,
						cr.PTypeInsuranceTotal,
						(CAST(cr.ManHourInsuranceTotal AS  NUMERIC(24, 10) ) + CAST(cr.PTypeInsuranceTotal AS  NUMERIC(24, 10) ) ) as insurancealltotal,
						a.BillNumberId,
						a.redword,
						CASE WHEN ISNULL(a.CwCheck,0) = 0 THEN ''否'' ELSE ''是'' END AS CwCheck,
						(Select TOp 1 curre.fullname From employee curre where curre.typeid=a.checke) as checke,
						a.billtype,
						kx.billnumberid as QuickRepairBillID,
						a.stypeid,
						s.fullname as sfullname
				FROM 	BillIndex a
						INNER JOIN Billindex_CarRepair   cr ON a.billnumberid=cr.billnumberid
						LEFT JOIN BillIndex kx ON cr.QuickRepairBillID=kx.billnumberid
						INNER JOIN Employee e ON a.etypeid=e.typeid
						INNER JOIN btype  b ON b.typeid=a.btypeid
						INNER JOIN Department d ON d.typeid=a.dtypeid
						INNER JOIN stype  s ON s.typeid=a.stypeid
						LEFT JOIN QP_RepairAutoInfo  Qr ON Qr.typeid=cr.ratypeid
						LEFT JOIN btype  b1 ON b1.typeid=cr.btypeid1
				WHERE  a.billnumberid = '+cast(@billnumberid as char)
SET @sql=@sql+' )temp 
				LEFT JOIN AuditingBill au	ON (au.billnumberid=temp.billnumberid AND Au.BillIndexType = 2)
'		
--print @sql
exec (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_LoadInsurancePtypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_LoadInsurancePtypeDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
作者:wang wei 
时间:2010-9-21
描述:加载理赔单维修项目信息
*/
CREATE          PROCEDURE QP_Web_LoadInsurancePtypeDetail 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (8000)
select @sql='
SELECT 	a.PTypeID as typeid,
		p.fullname,
		p.usercode,
		a.Qty,
		a.TaxPrice as discountprice,
		a.TaxTotal as discounttotal,
		a.Virtual as Virtual1,
		a.Comment,
		a.GoodsCostTotal,
		a.InsuranceTotal,
		a.BillNumberId,
		A.QuickOrReceptionBillId
FROM QP_InsuranceBill_PType a
		INNER JOIN PType  p ON p.typeid=a.ptypeid
WHERE  a.billnumberid = '+cast(@billnumberid as char)
		
--print @sql
exec (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_LoadInsuranceRiDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_LoadInsuranceRiDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
作者:wang wei 
时间:2010-9-21
描述:加载理赔单维修项目信息
*/
CREATE          PROCEDURE QP_Web_LoadInsuranceRiDetail 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (8000)
select @sql='
SELECT	r.RepairItemsTypeID as typeid,
		qr.fullname,
		qr.usercode, 
		r.ManHour as standardmanhour,
		r.Total as discounttotal,
		r.InsuranceTotal,
		r.CostTotal,
		r.Virtual as Virtual1,
		r.Comment,
		R.QuickOrReceptionBillId
FROM QP_InsuranceBill_RepairItems r		
		INNER JOIN QP_RepairItems qr ON r.RepairItemsTypeID=qr.typeid
WHERE  r.billnumberid = '+cast(@billnumberid as char)
		
--print @sql
exec (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_LoadScheme]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_LoadScheme]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王伟
	日期：2011-12-12
	描述：加载查询方案
*/
/*
	修改：李灏龙
	日期：2012年2月15日16:45:26
	描述：增加查询条件，解决页面共用问题；		  
		  具体修改：zs001
*/

CREATE	PROCEDURE QP_Web_LoadScheme 
( 
	@OperatorId		varchar(100),		--操作员ID
	@reportName		VARCHAR(500),		--页面
	@schemeid		DECIMAL(18,0),
	@isdefault		int,
	@inputtype		VARCHAR(200)		--zs001：页面类型
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @SQL VARCHAR(MAX)
SET @SQL='
			SELECT	sd.nid,
					sd.datafield,
					sd.dataValue,
					sd.dataText,
					sd.controltype,
					sd.basetype
			FROM	Scheme S
			INNER JOIN	SchemeDetail  sd	ON S.SchemeId = SD.SchemeId
 			WHERE	S.ETypeID = '+CHAR(39)+@OperatorId+CHAR(39)+
 					' AND  ReportName='+CHAR(39)+@reportName+CHAR(39)+
 					' AND inputtype='+CHAR(39)+@inputtype+CHAR(39)		--zs001:增加条件控制
 					
IF @schemeid>0 
	SET @SQL+=' AND S.SchemeId='+CAST(@schemeid as VARCHAR(500))
IF @isdefault>=0  
	SET @SQL+='  AND isdefault='+CAST(@isdefault as VARCHAR(10))

EXEC (@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_LoadThreePacketsBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_LoadThreePacketsBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
作者:
时间:
描述:加载三包索赔单主表信息
*/
CREATE          PROCEDURE QP_Web_LoadThreePacketsBill 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (8000)
select @sql=
'SELECT temp.*,au.BillDetail	
FROM ( 		
				SELECT 	DISTINCT
						a.billdate,
						a.billcode,
						a.etypeid,
						e.fullname as efullname,		
						a.dtypeid,
						d.fullname as dfullname,
						a.btypeid,
						b.fullname as bfullname,
						kx.billcode as wxbillcode,
						cr.ratypeid,
						Qr.PlateNumber as rafullname,
						cr.btypeid1,--往来单位
						b1.fullname as bfullname1,
						a.totalinmoney,
						a.totalmoney,
						a.totalqty,
						a.explain,
						a.comment,
						CASE WHEN ISNULL(a.CwCheck,0) = 0 THEN ''否'' ELSE ''是'' END AS CwCheck,
						cr.ManHourInsuranceTotal,
						cr.PTypeInsuranceTotal,
						(CAST(cr.ManHourInsuranceTotal AS  NUMERIC(24, 10) ) + CAST(cr.PTypeInsuranceTotal AS  NUMERIC(24, 10) ) ) as insurancealltotal,
						a.BillNumberId,
						a.redword,
						(Select TOp 1 curre.fullname From employee curre where curre.typeid=a.checke) as checke,
						a.billtype,
						kx.billnumberid as QuickRepairBillID,
						a.stypeid,
						s.fullname as sfullname
				FROM 	BillIndex a
						INNER JOIN Billindex_CarRepair   cr ON a.billnumberid=cr.billnumberid
						LEFT JOIN BillIndex kx ON cr.QuickRepairBillID=kx.billnumberid
						INNER JOIN Employee e ON a.etypeid=e.typeid
						INNER JOIN btype  b ON b.typeid=a.btypeid
						INNER JOIN Department d ON d.typeid=a.dtypeid
						INNER JOIN stype  s ON s.typeid=a.stypeid
						LEFT JOIN QP_RepairAutoInfo  Qr ON Qr.typeid=cr.ratypeid
						LEFT JOIN btype  b1 ON b1.typeid=cr.btypeid1
				WHERE  a.billnumberid = '+cast(@billnumberid as char)
SET @sql=@sql+' )temp 
				LEFT JOIN AuditingBill au	ON (au.billnumberid=temp.billnumberid AND Au.BillIndexType = 2)
'		
--print @sql
exec (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_LoadThreePacketsPtypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_LoadThreePacketsPtypeDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
作者:
时间:
描述:加载三包索赔单配件信息
*/
CREATE          PROCEDURE QP_Web_LoadThreePacketsPtypeDetail 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (8000)
select @sql='
SELECT 	a.PTypeID as typeid,
		p.fullname,
		p.usercode,
		a.Qty,
		a.costtotal,
		a.taxprice as discountprice,
		a.taxtotal as discounttotal,
		a.Virtual as Virtual1,
		a.Comment,
		a.InsuranceTotal,
		a.BillNumberId,
		a.QuickOrReceptionBillId
FROM QP_ThreePacketsBill_PType a
		INNER JOIN PType  p ON p.typeid=a.ptypeid
WHERE  a.billnumberid = '+cast(@billnumberid as char)
		
--print @sql
exec (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_LoadThreePacketsRiDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_LoadThreePacketsRiDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
作者:
时间:
描述:加载三包索赔单维修项目信息
*/
CREATE          PROCEDURE QP_Web_LoadThreePacketsRiDetail 
( 
 @BillNumberId numeric(10,0)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql varchar (8000)
select @sql='
SELECT	r.RepairItemsTypeID as typeid,
		qr.fullname,
		qr.usercode, 
		r.standardmanhour,
		r.repairtotal AS discounttotal,
		r.insurancetotal,
		r.costtotal,
		r.Virtual as Virtual1,
		r.Comment,
		r.QuickOrReceptionBillId
		
FROM QP_ThreePacketsBill_RepairItems r		
		INNER JOIN QP_RepairItems qr ON r.RepairItemsTypeID=qr.typeid
WHERE  r.billnumberid = '+cast(@billnumberid as char)+'
ORDER BY r.ID
'
		
--print @sql
exec (@sql)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_OtherBillOperation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_OtherBillOperation]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：郑红霞
	日期：2011-7-6
	描述：查询业务类别
	
-------------------------------------------*/
CREATE PROCEDURE Qp_Web_OtherBillOperation
(
	@Serch		VARCHAR(100),	---输入的条件
	@BillType	VARCHAR(20),  ---单据类型
	@stypeid	VARCHAR(100),
	@OperatorId VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ac_Items(TypeID	VARCHAR(50))

--IF @BillType = 'INTYPE'
--BEGIN
--	INSERT INTO #Ac_Items(TypeId) 
--	SELECT nid FROM F_GetManDetailATypeSr(@OperatorId)
--	UNION
--	SELECT nId FROM Ac_Items A --WHERE A.nId BETWEEN 3 AND 12
--	WHERE nTypeId LIKE '00003%' AND LEFT(nTypeId,10) <> '0000300003'
--		  AND SonNum = 0
--END
--ELSE
--BEGIN
--	INSERT INTO #Ac_Items(TypeId) 
--	SELECT nid FROM F_GetManDetailATypeFy(@OperatorId)
--	UNION
--	SELECT nId FROM Ac_Items 
--	WHERE nTypeId LIKE '00004%' AND LEFT(nTypeId,10) <> '0000400003'
--		 AND SonNum = 0
--END

INSERT INTO #Ac_Items(TypeId) 
SELECT nid FROM F_GetManDetailATypeSr(@OperatorId)
UNION
SELECT nId FROM Ac_Items A --WHERE A.nId BETWEEN 3 AND 12
WHERE nTypeId LIKE '00003%' AND LEFT(nTypeId,10) <> '0000300003'
	  AND SonNum = 0
UNION 
SELECT nid FROM F_GetManDetailATypeFy(@OperatorId)
UNION
SELECT nId FROM Ac_Items 
WHERE nTypeId LIKE '00004%' AND LEFT(nTypeId,10) <> '0000400003'
	 AND SonNum = 0
	 
INSERT INTO #Ac_Items(TypeID) VALUES('')

DECLARE @SQL varchar(max)

SET @SQL= 'SELECT   o.id,
					o.fullname,
					o.atypeid,					
					o.atypeid1,
					o.inouttype,
					CASE o.inouttype 
					WHEN 0 THEN ''入库'' 
					WHEN 1 THEN ''出库''
					WHEN 2 THEN ''出入库'' END AS inouttypename,
					a.UserCode as  atypecode,
					a.FullName as atypename,
					a.deleted,
					b.UserCode as  atypecode1,
					b.FullName as atypename1,
					b.deleted as deleted1
            FROM    OtherInOutType o   
			LEFT JOIN ac_items a ON a.nid = o.AtypeId
			LEFT JOIN ac_items b ON b.nid = o.AtypeId1
			INNER JOIN #Ac_Items c ON c.typeid = o.AtypeId
			INNER JOIN #Ac_Items d ON d.typeid = o.AtypeId1
			WHERE o.FullName LIKE ''%' + @Serch + '%'''
IF @BillType='INTYPE'
   SET @SQL = @SQL + 'AND (o.inouttype = 0 OR o.inouttype = 2)'
IF @BillType='OUTTYPE'
   SET @SQL = @SQL + 'AND (o.inouttype = 1 OR o.inouttype = 2)'
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Ac_Items

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryBackPicking]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryBackPicking]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：查看领料退回详情
-------------------------------------------*/
CREATE PROCEDURE [dbo].[Qp_Web_QueryBackPicking]
(
    @OperatorID    VARCHAR(50),       
	@Ktypeid       VARCHAR(1550)='',         --仓库
    @stypeid       VARCHAR(1550)='00001',    --分支机构
    @BillNumberId  VARCHAR(max)              --维修单号
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @Ptypeid  VARCHAR(1550)='',
	        @SQL VARCHAR(3000)
	set @Ptypeid = (select ptypeid from BillIndex where BillNumberId=@BillNumberId) 
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorId IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
				@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------

	CREATE TABLE #Ptype (TypeID VARCHAR(200))
	CREATE TABLE #Ktype (TypeID VARCHAR(50))
	CREATE TABLE #Stype (TypeID VARCHAR(50))

	--配件
	INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Ptypeid,1,@OperatorID)

	--仓库
	--INSERT INTO #Ktype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Ktypeid,4,@OperatorID)	

	--分支机构
	INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	
	SET @SQL ='select back.PickingId,
	           b.BillCode,
	           b.BillDate,
	           p.UserCode,
	           p.FullName pname,
               p.DwgNo,
               back.Qty,
               back.Price,
               back.Total,
               back.Insurance,
               back.Comment,
               s.FullName stockname,
               e.FullName username
	           from Qp_PickingBackBill back
	           INNER JOIN BillIndex  b on b.BillNumberId = back.BillNumberId
	           INNER JOIN ptype p on p.typeId = back.PTypeId
	           INNER JOIN stock s on s.typeId=b.Stypeid
	           INNER JOIN employee e on e.typeId = b.etypeid 
	           INNER JOIN #stype m on m.typeid = b.stypeid
		       INNER JOIN  #ptype ps on ps.typeid = back.PTypeId
         where 
         back.PickingId in(select PickingId  from  Qp_ReceptionBill_FactUsePType where ReceptionBillnumberId='''+@BillNumberId+''')
         AND b.draft=0 and b.ifcheck=''t'''
	EXEC (@sql)
END
DROP  TABLE #Ptype,#Ktype,#Stype
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryBespokeRepair]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryBespokeRepair]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-04-21
	描述：查询预约维修单
*/

CREATE PROCEDURE Qp_Web_QueryBespokeRepair
(	
	@OperatorId				VARCHAR(100),		--操作员id
	@receptionstartdate		VARCHAR(MAX),		--接待开始日期
	@receptionenddate		VARCHAR(MAX),		--接待结束日期
	@bespokestartdate		VARCHAR(MAX),		--预约开始日期
	@bespokeenddate			VARCHAR(MAX),		--预约结束日期
	@wcitypeid				VARCHAR(MAX),		--车牌号
	@btypeid				VARCHAR(MAX),		--往来单位id
	@stypeid				VARCHAR(MAX),		--分支机构id
	@dtypeid				VARCHAR(MAX),		--部门id
	@etypeid				VARCHAR(MAX),		--经手人id
	@billcode				VARCHAR(MAX)		--维修单编号
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	

--车牌号
CREATE TABLE #GetManWTypeId(TypeId	varchar(100))
INSERT INTO #GetManWTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@wcitypeid,12,@OperatorID)	

--构造SQL语句
DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'SELECT	B.BillNumberId,
					B.BillType,
					B.totalmoney,
					Bc.BeSpokeDate,
					B.BillCode,
					B.BillDate,
					Bc.ReceptionDate,
					Bc.RATypeID,
					B.STypeId,
					B.BTypeId,
					B.ETypeId,
					B.DTypeId,
					Bc.RepairMode,
					Bc.OperationSort,
					B.Explain,
					B.Comment
			FROM	BillIndex B
			INNER JOIN BillIndex_CarRepair Bc ON B.BillNumberId = Bc.BillNumberId
			INNER JOIN QP_RepairAutoInfo Qr ON Bc.RATypeID = Qr.TypeID
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			INNER JOIN #GetManWTypeId W ON W.TypeId=Qr.TypeID
			WHERE	Bc.BeSpokeDate>='''+@bespokestartdate+'''
					AND Bc.BeSpokeDate<='''+@bespokeenddate+'''
					AND CONVERT(char(10),Bc.ReceptionDate,120)>='''+@receptionstartdate+'''
					AND CONVERT(char(10),Bc.ReceptionDate,120)<='''+@receptionenddate+'''
					AND Bc.RepairType = 1
					AND Bc.BillState = 1
					AND B.BillCode LIKE ''%'+@billcode+'%''
					AND b.ifYearBill=0'	 --年节存标志
SET @SQL = @SQL + ' ORDER BY Bc.BeSpokeDate DESC,B.BillCode DESC'
	
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManDTypeId,#GetManETypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryExpireNoComplete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryExpireNoComplete]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-04-21
	描述：到期未完工车辆查询
*/
CREATE PROCEDURE Qp_Web_QueryExpireNoComplete
(
	@OperatorId			VARCHAR(MAX),	--操作员ID
	@StartDate			VARCHAR(MAX),	--开始日期
	@EndDate			VARCHAR(MAX),	--截止日期
	@STypeId			VARCHAR(MAX),	--分支机构
	@WciTypeId			VARCHAR(MAX),	--车牌号
	@BTypeId			VARCHAR(MAX),	--往来单位
	@DTypeId			VARCHAR(MAX),	--部门ID
	@ETypeId			VARCHAR(MAX),	--经手人ID
	@BillState			VARCHAR(MAX),	--维修进度
	@BillCode			VARCHAR(MAX)	--单据编号
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--车牌号(不用控制权限范围)
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,00001)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)	

DECLARE @SQL VARCHAR(MAX)
					
SET @SQL = 'SELECT	B.BillNumberId,
					B.BillType,
					Bc.ReceptionDate,
					B.BillCode,
					CASE Bc.BillState WHEN 1 THEN''登记'' WHEN 2 THEN ''在修'' WHEN 3 THEN ''完工待结算'' WHEN 4 THEN ''已结算'' WHEN 5 THEN ''中止维修'' END AS BillState,
					Bc.RATypeID,
					B.STypeId,
					B.BTypeId,
					B.ETypeId,
					B.DTypeId,
					Bc.CompleteDate,
					Bc.OperationSort,
					Bc.RepairMode,
					B.Explain,
					B.Comment
			FROM	BillIndex	B
			INNER JOIN BillIndex_CarRepair Bc ON B.BillNumberId = Bc.BillNumberId
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			WHERE	B.BillType = 195
					AND Bc.CompleteDate < GETDATE()
					AND CONVERT(varchar(10),Bc.ReceptionDate,120)>='''+@StartDate+'''
					AND CONVERT(varchar(10),Bc.ReceptionDate,120)<='''+@EndDate+'''
					AND B.BillCode LIKE ''%'+@BillCode+'%'''
					
--维修状态
IF @BillState = '0'
	SET @SQL = @SQL + ' AND Bc.BillState IN (1,2)'
ELSE IF @BillState = '1'		
	SET @SQL = @SQL + ' AND Bc.BillState = 1'
ELSE IF @BillState = '2'		
	SET @SQL = @SQL + ' AND Bc.BillState = 2'
	
SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志	

SET @SQL = @SQL + ' ORDER BY B.BillDate DESC,B.BillCode DESC'
	

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManDTypeId,#GetManETypeId,#GetManWciTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryMultiBarCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryMultiBarCode]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-18
	描述：多条码打印
	Qp_Web_QueryMultiBarCode '00001','','11'
*/

CREATE PROCEDURE Qp_Web_QueryMultiBarCode
(
	@OperatorId		VARCHAR(100),	
	@PTypeId		VARCHAR(MAX),
	@stypeid		VARCHAR(MAX),
	@Price			VARCHAR(100),
	@unitsid		INT
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------


/*判断有没有启用分支机构价格*/
DECLARE @Type int
set @Type=(select top 1 pricetype from stype where typeid=@stypeid)

CREATE TABLE #TempPtype
(
	ID		INT,
	A		VARCHAR(200)
)

INSERT INTO #TempPtype
(
	ID,
	A
)
SELECT ID,A FROM DBO.F_Splitan(@PTypeId,',')

DECLARE @SQL VARCHAR(MAX)


SET @SQL = 'SELECT 
				A.EntryCode,
				A.multentrycode,
				A.usercode,
				A.fullname,
				a.name,
				a.area,
				a.Standard,
				a.type,
				a.usefullifeday,
				a.TypeID,
				a.ifuseentrycode,
				a.BuyUnitId,
				a.SaleUnitId,
				a.StockUnitId,
				a.baseUnitId,
				'+CASE @unitsid WHEN 1 THEN 'a.BuyUnitId as unitsid,u1.fullname as unitsname, u1.usercode as unitscode, ' 
				WHEN 2 THEN 'a.SaleUnitId as unitsid,u2.fullname as unitsname, u2.usercode as unitscode, ' 
				WHEN 3 THEN 'a.StockUnitId as unitsid,u4.fullname as unitsname, u4.usercode as unitscode, ' 
				ELSE  'a.baseUnitId as unitsid,u3.fullname as unitsname, u3.usercode as unitscode, ' END +'
				a.customitemid,
				a.customitemfrom,
				a.customitemname,
				cast(0 as numeric(18,0)) as qty,
				u1.fullname as buyunitfullname,
				u1.usercode as buyunitusercode,
				u2.fullname as saleunitfullname,
				u2.usercode as saleunitusercode,
				u3.fullname as baseunitfullname,
				u3.usercode as baseunitusercode,
				u4.fullname as stockunitfullname,
				u4.usercode as stockunitusercode,
				r.presaleprice1,
				r.presaleprice2,
				r.presaleprice3,
				r.presaleprice4,
				r.presaleprice5,
				r.presaleprice6,
				r.presaleprice7,
				r.presaleprice8,
				r.presaleprice9,
				r.presaleprice10,
				r.RetailPrice,
				r.TopSalePrice,
				r.LowSalePrice,'
IF @Price = 0 
	SET @SQL = @SQL + ' null AS Price'
ELSE IF @Price = 11
	SET @SQL = @SQL + ' r.RetailPrice AS Price'
ELSE IF @Price = 12
	SET @SQL = @SQL + ' r.TopSalePrice AS Price'
ELSE IF @Price = 13
	SET @SQL = @SQL + ' r.LowSalePrice AS Price'
ELSE
	SET @SQL = @SQL + ' r.PreSalePrice' + @Price + '  AS Price'

IF @Type=1
BEGIN
	SET @SQL = @SQL + '
			FROM	F_GetManPTypeAll('''+@OperatorId+''') a
					left JOIN PType_STypePrice r on (a.TypeID=R.PTypeID AND R.STypeID='''+@STypeId+''' ) AND '
					+CASE @unitsid WHEN 1 THEN 'a.BuyUnitId'
					WHEN 2 THEN 'a.SaleUnitId'
					WHEN 3 THEN 'a.StockUnitId'
					ELSE ' a.baseUnitId ' END +' = r.UnitID
					LEFT join PType_Units u1 on u1.unitsid=a.buyunitid
					LEFT join PType_Units u2 on u2.unitsid=a.saleunitid
					LEFT join PType_Units u3 on u3.unitsid=a.baseunitid
					LEFT join PType_Units u4 on u4.unitsid=a.stockunitid
					INNER JOIN #TempPtype M ON M.A = a.TypeId
			WHERE	a.SonNum = 0
					AND ISNULL(a.EntryCode,'''')<>'''' 
			ORDER BY m.id'

END
ELSE
	SET @SQL = @SQL + '
			FROM	F_GetManPTypeAll('''+@OperatorId+''') a
					Left JOIN PType_Price r on a.typeid=R.Ptypeid AND '
					+CASE @unitsid WHEN 1 THEN 'a.BuyUnitId'
					WHEN 2 THEN 'a.SaleUnitId'
					WHEN 3 THEN 'a.StockUnitId'
					ELSE ' a.baseUnitId ' END +' = r.UnitID
					LEFT join PType_Units u1 on u1.unitsid=a.buyunitid
					LEFT join PType_Units u2 on u2.unitsid=a.saleunitid
					LEFT join PType_Units u3 on u3.unitsid=a.baseunitid
					LEFT join PType_Units u4 on u4.unitsid=a.stockunitid
					INNER JOIN #TempPtype M ON M.A = a.TypeId
			WHERE	a.SonNum = 0
					AND ISNULL(a.EntryCode,'''')<>'''' 
			 ORDER BY m.id'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #TempPtype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryMultiBarCodeCopy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryMultiBarCodeCopy]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2010-08-18
	描述：用于通过序列号查询商品信息
	Qp_Web_QueryMultiBarCode '00001','','11'
*/

CREATE PROCEDURE Qp_Web_QueryMultiBarCodeCopy
(
	@OperatorId		VARCHAR(100),	
	@PTypeId		VARCHAR(MAX),
	@stypeid		VARCHAR(MAX),
	@Price			VARCHAR(100),
	@serial         VARCHAR(1000)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------


/*判断有没有启用分支机构价格*/
DECLARE @Type int
set @Type=(select top 1 pricetype from stype where typeid=@stypeid)

DECLARE @SQL VARCHAR(8000)

SET @SQL = 'SELECT 
				a.EntryCode EntryCode,
				A.usercode,
				A.fullname,
				a.name,
				a.area,
				a.Standard,
				a.type,
				a.usefullifeday,
				a.TypeID,
				a.ifuseentrycode,
				a.BuyUnitId,
				a.SaleUnitId,
				a.StockUnitId,
				a.baseUnitId,
				a.customitemid,
				a.customitemfrom,
				a.customitemname,
				cast(0 as numeric(18,0)) as qty,
				u1.fullname as buyunitfullname,
				u1.usercode as buyunitusercode,
				u2.fullname as saleunitfullname,
				u2.usercode as saleunitusercode,
				u3.fullname as baseunitfullname,
				u3.usercode as baseunitusercode,
				u4.fullname as stockunitfullname,
				u4.usercode as stockunitusercode,
				r.presaleprice1,
				r.presaleprice2,
				r.presaleprice3,
				r.presaleprice4,
				r.presaleprice5,
				r.presaleprice6,
				r.presaleprice7,
				r.presaleprice8,
				r.presaleprice9,
				r.presaleprice10,
				r.RetailPrice,
				r.TopSalePrice,
				r.LowSalePrice,
				1 as qty,
				u3.fullname as pricklename,
				isnull(c.FullName,'''') as cargofullname,'
IF @Price = 0 
	SET @SQL = @SQL + ' 0 AS Price'
ELSE IF @Price = 11
	SET @SQL = @SQL + ' r.RetailPrice AS Price'
ELSE IF @Price = 12
	SET @SQL = @SQL + ' r.TopSalePrice AS Price'
ELSE IF @Price = 13
	SET @SQL = @SQL + ' r.LowSalePrice AS Price'
ELSE
	SET @SQL = @SQL + ' r.PreSalePrice' + @Price + '  AS Price'

IF @Type=1
BEGIN 
	SET @SQL = @SQL + '
			FROM	F_GetManPTypeAll('''+@OperatorId+''') a
					INNER JOIN dbo.gp_CruPtypeSerial gp on gp.PtypeID = a.typeid
					LEFT JOIN CargoType c on c.CargoID = gp.CargoID
					left JOIN PType_STypePrice r on (a.TypeID=R.PTypeID AND R.STypeID='''+@STypeId+''' )  AND a.baseUnitId = r.UnitID
					LEFT join PType_Units u1 on u1.unitsid=a.buyunitid
					LEFT join PType_Units u2 on u2.unitsid=a.saleunitid
					LEFT join PType_Units u3 on u3.unitsid=a.baseunitid
					LEFT join PType_Units u4 on u4.unitsid=a.stockunitid
					INNER JOIN (SELECT A FROM dbo.F_Split('+CHAR(39)+@PTypeId+CHAR(39)+','','')) M ON M.A = a.TypeId
			WHERE	a.SonNum = 0 AND gp.Serial = '''+@serial +'''
					--AND ISNULL(a.EntryCode,'''')<>''''
			ORDER BY a.UserCode'

END
ELSE
	SET @SQL = @SQL + '
			FROM	F_GetManPTypeAll('''+@OperatorId+''') a
					INNER JOIN dbo.gp_CruPtypeSerial gp on gp.PtypeID = a.typeid
					LEFT JOIN CargoType c on c.CargoID = gp.CargoID
					Left JOIN PType_Price r on a.typeid=R.Ptypeid  AND a.baseUnitId = r.UnitID
					LEFT join PType_Units u1 on u1.unitsid=a.buyunitid
					LEFT join PType_Units u2 on u2.unitsid=a.saleunitid
					LEFT join PType_Units u3 on u3.unitsid=a.baseunitid
					LEFT join PType_Units u4 on u4.unitsid=a.stockunitid
					INNER JOIN (SELECT A FROM dbo.F_Split('+CHAR(39)+@PTypeId+CHAR(39)+','','')) M ON M.A = a.TypeId
			WHERE	a.SonNum = 0 AND gp.Serial = '''+@serial +'''
					--AND ISNULL(a.EntryCode,'''')<>''''
			ORDER BY a.UserCode'

--PRINT(@SQL)
EXEC(@SQL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryOtherInorOutBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryOtherInorOutBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2011-07-08
	描述：其他出库或入库查询树型表
	INNER JOIN #GetManBTypeId bi ON bi.TypeId = b.BTypeId
*/
CREATE PROCEDURE Qp_Web_QueryOtherInorOutBill 
(
	@OperatorId			VARCHAR(MAX),		 --操作员ID
	@StartDate			VARCHAR(MAX),		 --开始日期
	@EndDate			VARCHAR(MAX),		 --截止日期
	@STypeId			VARCHAR(MAX)='',	--分支机构
	@dealBTypeId			VARCHAR(MAX)='',	--往来单位
	@DTypeId			VARCHAR(MAX)='',	--部门ID
	@KTypeId			VARCHAR(MAX)='',    --仓库
	@BillType			VARCHAR(MAX),	    --单据类型
	@EtypeId            VARCHAR(MAX)='',	--经手人
	@PTypeId			VARCHAR(MAX),
	@businessid         VARCHAR(max)         --业务类别
)
--@encode$--
AS
SET NOCOUNT ON
 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealBTypeId,2,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)	
--SELECT * FROM #GetManPTypeId
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID)	


DECLARE @SQL		VARCHAR(MAX),
		@SonNum		INT

SET @SQL = ''

IF @PTypeId = '' 
   SET @PTypeId = '00000'
	
SELECT @SonNum = SonNum FROM PType WHERE TypeID = @PTypeId	 
SET @SQL = 'SELECT	P.TypeId, 
					P.SonNum, 
					P.usercode, 
                    ISNULL((SUM(o.Qty)),0) AS Qty,
                    CASE WHEN SUM(o.Qty) = 0  THEN 0
					ELSE ISNULL(SUM(o.Total),0)/SUM(o.Qty) END AS Price,
					ISNULL((SUM(o.Total)),0) AS Total,	
					case when P.SonNum>0 then null
					else	
	                u1.fullname  end AS basename,
	                dbo.F_GetCustomAssist(P.TypeId,ISNULL((SUM(o.Qty)),0)) AS customassistantunit
	               
			FROM  PType P'+dbo.F_GetPtypeUnitsAndRates('p','1','1')
		SET @SQL+='	
			INNER JOIN (
					   SELECT	inout.PtypeId,
								SUM(inout.Price) AS Price,
								SUM(inout.Qty) AS Qty,
								SUM(inout.Total) AS Total
						FROM OtherInOutBill inout
						INNER JOIN BillIndex b ON b.BillNumberId = inout.BillNumberId
						INNER JOIN #GetManSTypeId S ON S.TypeId = inout.Stypeid
						INNER JOIN #GetManKTypeId K ON K.TypeId = inout.KtypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = b.DTypeId
						INNER JOIN #GetManBTypeId bi ON bi.TypeId = b.dealBTypeId
						INNER JOIN #GetManPTypeId pi ON pi.TypeId = inout.PtypeId
						INNER JOIN #GetManETypeId e  ON e.TypeId =b.etypeid '
						IF @businessid!=''
						 BEGIN
							SET @SQL+='	inner join  dbo.f_split('''+@businessid+''', '','') JJ on b.OtherInOutType= JJ.a'
					     END
					SET @SQL+='	WHERE	B.BillDate>='''+@StartDate+'''
						AND B.BillDate<='''+@EndDate+'''							
						AND B.RedWord = 0
						AND b.draft=0
				        AND b.ifcheck=''t''	
						AND b.ifYearBill=0'	 --年节存标志
						
 --IF @STypeId<>''  SET @SQL = @SQL + 'AND b.stypeid like @STypeId '
 IF @BillType = 'OUTTYPE'
	SET @SQL = @SQL + 'AND B.BillType = 202'

 IF @BillType = 'INTYPE'
	SET @SQL = @SQL + 'AND B.BillType = 201'
	
SET @SQL = @SQL + ' GROUP BY inout.PtypeId )o ON LEFT(o.PTypeId,LEN(P.TypeId)) = P.TypeId '
--SET @SQL = @SQL + 'right JOIN #GetManPTypeId pi ON pi.TypeId = p.typeId'
IF @SonNum = 0 
    SET @SQL = @SQL + ' WHERE P.TypeId = '''+@PTypeId+''''
ELSE
	SET @SQL = @SQL + ' WHERE P.ParId = '''+@PTypeId+''''
				
SET @SQL = @SQL + '	GROUP By P.TypeId,
							 P.SonNum,
							 P.usercode,
							u1.fullname,
							p.sortid
					ORDER BY P.sortid '	
					
					--PRINT @SQL
EXEC(@SQL)
DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManKTypeId,#GetManDTypeId,#GetManPTypeId,#GetManETypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryOtherInOutBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryOtherInOutBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2011-07-20
	描述：其他出入库查询树型表
	INNER JOIN #GetManBTypeId bi ON bi.TypeId = b.BTypeId
*/
CREATE PROCEDURE Qp_Web_QueryOtherInOutBill
(
	@OperatorId			VARCHAR(MAX),		--操作员ID
	@StartDate			VARCHAR(MAX),		--开始日期
	@EndDate			VARCHAR(MAX),		--截止日期
	@STypeId			VARCHAR(MAX),		--分支机构
	@dealBTypeId		VARCHAR(MAX),		--往来单位
	@DTypeId			VARCHAR(MAX),		--部门ID
	@KTypeId			VARCHAR(MAX),		--仓库
	@etypeId            VARCHAR(MAX),	    --经手人
--	@BillType			VARCHAR(MAX),	    --单据类型
	@PTypeId			VARCHAR(MAX),
	@businessid         VARCHAR(max)         --业务类别
)
--@encode$--
AS
SET NOCOUNT ON
 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealBTypeId,2,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	
 

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeId,3,@OperatorID)

	

CREATE TABLE #Otherouttable  -----其他出库临时表
   (
     PTypeId varchar(100),
     BillNumberId varchar(max),
     Qty  NUMERIC(24, 10) ,
     Price  NUMERIC(24, 10) ,
     Total  NUMERIC(24, 10) ,
     stypeid varchar(max),
     ktypeid varchar(max)
   )
INSERT INTO  #Otherouttable 
(   PTypeId,
	BillNumberId,
	Qty,
	Price,
	Total,
	stypeid,
	ktypeid
) 

SELECT  o.PtypeId,
		o.BillNumberId,
		o.Qty ,
		o.Price,
		o.Total,
		o.Stypeid,
		o.KtypeId
FROM  OtherInOutBill o
			  INNER JOIN BillIndex b       ON b.BillNumberId = o.BillNumberId
			  INNER JOIN #GetManSTypeId S  ON S.TypeId = o.Stypeid
			  INNER JOIN #GetManKTypeId K  ON K.TypeId = o.KtypeId
			  INNER JOIN #GetManDTypeId D  ON D.TypeId = b.DTypeId
			  INNER JOIN #GetManBTypeId bi ON bi.TypeId = b.DealBTypeID
			  INNER JOIN #GetManETypeId e  ON e.TypeId =b.etypeid
			  INNER JOIN #GetManPTypeId p  ON p.TypeId = o.PtypeId
    WHERE	B.BillDate>=@StartDate
			  AND B.BillDate<=@EndDate							
			  AND B.RedWord = 0
			  AND b.draft=0
		      AND b.ifcheck='t'	
			  AND o.BillTYpe=202
			  AND b.ifYearBill=0
			  AND (b.OtherInOutType IN (SELECT * FROM dbo.f_split(@businessid,',')) OR @businessid='')
			  	 --年节存标志
CREATE TABLE  #OtherIntable  ----其他入库临时表
(
	 PTypeId varchar(100),
	 BillNumberId numeric(10, 0) ,
	 Qty  NUMERIC(24, 10) ,
	 Price  NUMERIC(24, 10) ,
	 Total  NUMERIC(24, 10) ,
	 stypeid varchar(max),
	 ktypeid varchar(max)
  )	
INSERT INTO #OtherIntable 
(	PTypeId,
	BillNumberId,
	Qty,
	Price,
	Total,
	stypeid,
	ktypeid
)
SELECT  o.PtypeId,
		o.BillNumberId,
		o.Qty,
		o.Price,
		o.Total,
		o.Stypeid,
		o.KtypeId 
FROM  OtherInOutBill o 
		  INNER JOIN BillIndex b       ON b.BillNumberId = o.BillNumberId
		  INNER JOIN #GetManSTypeId S  ON S.TypeId = o.Stypeid
		  INNER JOIN #GetManKTypeId K  ON K.TypeId = o.KtypeId
		  INNER JOIN #GetManDTypeId D  ON D.TypeId = b.DTypeId
		  INNER JOIN #GetManBTypeId bi ON bi.TypeId = b.DealBTypeID
		  INNER JOIN #GetManETypeId e  ON e.TypeId =b.etypeid
		  INNER JOIN #GetManPTypeId p  ON p.TypeId = o.PtypeId
		  
	WHERE	B.BillDate>=@StartDate
		  AND B.BillDate<=@EndDate						
		  AND B.RedWord = 0
		  AND b.draft=0
		  AND b.ifcheck='t'	
		  AND o.BillTYpe=201
		  AND b.ifYearBill=0	
		  AND (b.OtherInOutType IN (SELECT * FROM dbo.f_split(@businessid,',')) OR @businessid='')
		   --年节存标志	
CREATE TABLE  #OtherInOuttable  ----其他入库临时表
(
     PTypeId		    varchar(max),
     outqty				 NUMERIC(24, 10) ,
     outprice			 NUMERIC(24, 10) ,
     outtotal			 NUMERIC(24, 10) ,
     inqty				 NUMERIC(24, 10) ,
     inprice			 NUMERIC(24, 10) ,
     intotal			 NUMERIC(24, 10) ,
     differentialqty     NUMERIC(24, 10) ,
     differentialtotal   NUMERIC(24, 10)  
)	
INSERT INTO #OtherInOuttable 
(   PTypeId,
	outqty,
	outprice,
	outtotal,
	inqty,
	inprice,
	intotal,
	differentialqty,
	differentialtotal
)
SELECT  i.PTypeId,0,0,0,i.Qty as inqty,i.Price as inprice,i.Total as intotal,0,0 from #OtherIntable i
UNION ALL
SELECT o.PTypeId,o.Qty as outqty,o.Price as outprice,o.Total as outtotal,0,0,0,0,0 from #Otherouttable o  

DECLARE @SQL	    VARCHAR(MAX),
		@SonNum		INT
SET @SQL = ''

IF @PTypeId = '' 
   SET @PTypeId = '00000'
SELECT @SonNum = SonNum FROM PType WHERE TypeID = @PTypeId	
SET @SQL = ' SELECT	P.TypeId, 
					P.SonNum, 
					P.usercode,
					--ISNULL((SUM(o.inprice)),0) AS inprice, 
					CASE WHEN SUM(o.inqty) = 0  THEN SUM(o.intotal)
					  ELSE ISNULL(SUM(o.intotal),0)/SUM(o.inqty) END AS inprice,
                    ISNULL((SUM(o.inqty)),0) AS inqty,
                    ISNULL((SUM(o.intotal)),0) AS intotal,
                    --ISNULL((SUM(o.outprice)),0) AS outprice,
                    CASE WHEN SUM(o.outqty) = 0  THEN SUM(o.outtotal)
					   ELSE ISNULL(SUM(o.outtotal),0)/SUM(o.outqty) END AS outprice,
					ISNULL((SUM(o.outqty)),0) AS outqty,
					ISNULL((SUM(o.outtotal)),0) AS outtotal,
					ISNULL((SUM(o.differentialqty)),0) AS differentialqty,
					ISNULL((SUM(o.differentialtotal)),0) AS differentialtotal,
					case when p.SonNum>0 then null else 
					fg.baseunitfullname end AS basename
			FROM	PType P 
			        left JOIN F_GetManPTypeDetailALL('''+@OperatorId+''') fg ON fg.typeid = p.typeid
			INNER JOIN (
						select  inout.ptypeid,
								SUM(inout.outqty) AS outqty,
								SUM(inout.outprice) AS outprice,
								--CASE WHEN SUM(inout.outqty) = 0  THEN SUM(inout.outtotal)
						  --        ELSE ISNULL(SUM(inout.outtotal),0)/SUM(inout.outqty) END AS outprice,
								SUM(inout.outtotal) AS outtotal,
								SUM(inout.inqty) AS inqty,
								SUM(inout.inqty) AS inprice,
								--CASE WHEN SUM(inout.inqty) = 0  THEN SUM(inout.intotal)
						  --        ELSE ISNULL(SUM(inout.intotal),0)/SUM(inout.inqty) END AS inprice,
								SUM(inout.intotal) AS intotal,
								sum(isnull(inout.outqty,0))-sum(isnull(inout.inqty,0)) as differentialqty,
								sum(isnull(inout.outtotal,0)) - sum(isnull(inout.intotal,0)) as differentialtotal
						from #OtherInOuttable inout
						'
SET @SQL = @SQL + ' GROUP BY inout.PtypeId )o ON LEFT(o.PtypeId,LEN(P.TypeId)) = P.TypeId'

IF @SonNum = 0 
    SET @SQL = @SQL + ' WHERE P.TypeId = '''+@PTypeId+''''
ELSE
	SET @SQL = @SQL + ' WHERE P.ParId = '''+@PTypeId+''''
				
SET @SQL = @SQL + '	GROUP By P.TypeId,
							 P.SonNum,
							 P.usercode,
							 p.sortid,
							 fg.baseunitfullname
						ORDER BY P.sortid '	
EXEC(@SQL)
DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManKTypeId,#GetManDTypeId,#OtherInOuttable,#OtherIntable,#Otherouttable
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryPicking]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryPicking]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：查看领料详情
-------------------------------------------*/
CREATE PROCEDURE [dbo].[Qp_Web_QueryPicking]
(
    @OperatorID    VARCHAR(50),       
	@Ktypeid       VARCHAR(1550)='',         --仓库
    @stypeid       VARCHAR(1550)='',    --分支机构
    @BillNumberId  VARCHAR(max)              --维修单号
)
--@encode$--
AS
  
SET NOCOUNT ON

DECLARE @Ptypeid  VARCHAR(1550)='',
        @SQL VARCHAR(3000)
SET @Ptypeid = (SELECT ptypeid FROM BillIndex WHERE BillNumberId=@BillNumberId) 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
			@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--配件
CREATE TABLE #Ptype (TypeID VARCHAR(200))
INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Ptypeid,1,@OperatorID)

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50))
INSERT INTO #Ktype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Ktypeid,4,@OperatorID)	

--分支机构
CREATE TABLE #Stype (TypeID VARCHAR(50))
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

SET @SQL ='SELECT  F.*,
				   b.BillCode,
				   b.BillDate,
				   q.KTypeID,
				   e.FullName username,
				   q.ID as pickingids,
				   q.BackQty as backqty,
				   q.Qty as totalqty,
				   (q.Qty-q.BackQty) as factqty,
				   ((q.Qty-q.BackQty)*q.Price) as facttotal
           FROM  Qp_ReceptionBill_FactUsePType F
           INNER JOIN BillIndex b on b.BillNumberId=F.BillNumberId
           INNER JOIN ptype p on p.typeId=F.PTypeID
           INNER JOIN employee e on e.typeId = F.ETypeID 
           INNER JOIN Qp_PickingBill q on q.ID = F.PickingId
           INNER JOIN stock s on s.typeId=b.ktypeid
           INNER JOIN #stype m on m.typeid = b.stypeid
	       INNER JOIN  #ktype k on k.typeid = q.ktypeid
	       INNER JOIN  #ptype ps on ps.typeid = F.PTypeID
	       WHERE F.ReceptionBillnumberId='''+@BillNumberId+'''
           ORDER BY  b.BillDate desc,p.UserCode desc' 
EXEC (@sql)
DROP  TABLE #Ptype,#Ktype,#Stype
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryPickingBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryPickingBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-04-25
	描述：领料单查询
*/
CREATE PROCEDURE Qp_Web_QueryPickingBill
(
	@OperatorId			VARCHAR(MAX),	--操作员ID
	@StartDate			VARCHAR(MAX),	--开始日期
	@EndDate			VARCHAR(MAX),	--截止日期
	@STypeId			VARCHAR(MAX),	--分支机构
	@WciTypeId			VARCHAR(MAX),	--车牌号
	@DTypeId			VARCHAR(MAX),	--部门ID
	@ETypeId			VARCHAR(MAX),	--经手人ID
	@KTypeId			VARCHAR(MAX),	--仓库
	@BillState			VARCHAR(MAX),	--维修进度
	@BillCode			VARCHAR(MAX),	--领料单号
	@RepairBillCode		VARCHAR(MAX),	--维修单号
	@Comment			VARCHAR(MAX),	--备注
	@Explain			VARCHAR(MAX),	--摘要
	@InnerPicking		VARCHAR(MAX)	--是否为内部领料
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--车牌号(不用控制权限范围)
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,00001)

--往来单位(查询条件里面不用往来单位)
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorId)	

--仓库
CREATE TABLE #GetManKTypeId(TypeId varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	

DECLARE @SQL VARCHAR(MAX)


SET @SQL = 'SELECT BillType,
				   BillNumberId,
				   RepairBillCode,
				   STypeId,
				   BillDate,
				   KTypeId,
				   Case BillState When 2 THEN ''在修'' When 3 Then ''未结算'' when 4 then ''已结算'' when 0 THEN ''内部领料'' end as billstate,
				   RATypeID,
				   BTypeId,
				   DTypeId,
				   ETypeId,
				   Explain,
				   Comment,
				   CostTotal,
				   SaleTotal,
				   GrossProfit,
				   BillCode
			FROM'
--不是内部领料
IF @InnerPicking = 'FALSE'
BEGIN
	SET @SQL = @SQL + '
			(SELECT B.BillType,
					B.BillNumberId,
					B2.BillCode AS repairbillcode,
					B.STypeId,
					B.BillDate,
					BC2.BillState,
					B.KTypeId,
					BC.RATypeId,
					B.BTypeId,
					B.DTypeId,
					B.ETypeId,
					B.Explain,
					B.Comment,
					I.CostTotal,
					I.SaleTotal,
					I.GrossProfit,
					 b.BillCode as billcode
			FROM Qp_PickingBill	P
			INNER JOIN BillIndex B ON P.BillNumberId = B.BillNumberId
			INNER JOIN (
							SELECT BillNumberId,
								   -SUM(CostTotal) AS CostTotal,
								   -SUM(SaleTotal) AS SaleTotal,
								   -((SUM(SaleTotal) - SUM(CostTotal))) AS GrossProfit
							FROM InOutstocktable
							WHERE BillType = ''191''
							GROUP BY BillNumberId
			)I ON P.BillNumberId = I.BillNumberId
			INNER JOIN Billindex_CarRepair BC ON P.BillNumberId = BC.BillNumberId
			left JOIN BillIndex B2 ON B2.BillNumberId = BC.QuickRepairBillID
			left JOIN Billindex_CarRepair BC2 ON B2.BillNumberId = BC2.BillNumberId
			INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId 
			INNER JOIN #GetManWciTypeId W ON W.TypeId = Bc.RATypeID
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId
			INNER JOIN QP_RepairAutoInfo rai ON rai.TypeID = bc.RATypeID
			INNER JOIN #GetManBTypeId MB ON rai.BTypeID = MB.TypeId
			WHERE B.BillDate >='''+@StartDate+'''
				  AND B.BillDate <='''+@EndDate+'''
				  AND B.BillCode LIKE ''%'+@BillCode+'%''
' 
	--维修状态
IF @BillState = '0'					
	SET @SQL = @SQL + ' AND BC2.BillState = 2'
IF @BillState = '1'
	SET @SQL = @SQL + ' AND BC2.BillState = 3'
IF @BillState = '2'
	SET @SQL = @SQL + ' AND BC2.BillState = 4'
	
--摘要，备注
SET @SQL = @SQL + '	AND B.Explain LIKE ''%'+@Comment+'%''
					AND B.Comment LIKE ''%'+@Explain+'%''
					AND B.RedWord = 0
					AND b.ifYearBill=0'	 --年节存标志
SET @SQL = @SQL + 'UNION ALL

				   SELECT B0.BillType,
							pb.BillNumberId,
						  B2.BillCode AS repairbillcode,
						  B.STypeId,
						  B0.BillDate,
						  BC3.BillState,
						  B0.KTypeId,
						  BC2.RATypeId,
						  MB.TypeId as BTypeid,
						  
						  B0.DTypeId,
						  B0.ETypeId,
						  B0.Explain,
						  B0.Comment,
						  I.CostTotal,
						  I.SaleTotal,
						  I.GrossProfit,
						  B0.BillCode as billcode
				   FROM Qp_PickingBackBill PB
				   INNER JOIN Billindex_CarRepair BC ON PB.BillNumberId = BC.BillNumberId
				   INNER JOIN BillIndex B0 ON PB.BillNumberId = B0.BillNumberId			   
				   INNER JOIN BillIndex B ON BC.QuickRepairBillID = B.BillNumberId			   
				   INNER JOIN Qp_PickingBill P ON B.BillNumberId=P.BillNumberId
				   INNER JOIN (
									SELECT BillNumberId,
										   -SUM(CostTotal) AS CostTotal,
										   -SUM(SaleTotal) AS SaleTotal,
										   ((-SUM(SaleTotal) - (-SUM(CostTotal)))) AS GrossProfit
									FROM InOutstocktable
									WHERE BillType = ''197''
									GROUP BY BillNumberId
					)I ON PB.BillNumberId = I.BillNumberId
					INNER JOIN Billindex_CarRepair BC2 ON P.BillNumberId = BC2.BillNumberId
					left JOIN BillIndex b2 ON BC2.QuickRepairBillID = b2.BillNumberId
					left JOIN Billindex_CarRepair BC3 ON BC3.BillNumberId = b2.BillNumberId
					INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId 
					INNER JOIN #GetManWciTypeId W ON W.TypeId = Bc2.RATypeID
					INNER JOIN #GetManDTypeId D ON D.TypeId = B0.DTypeId
					INNER JOIN #GetManETypeId E ON E.TypeId = B0.ETypeId
					INNER JOIN QP_RepairAutoInfo rai ON rai.TypeID = bc2.RATypeID
					INNER JOIN #GetManBTypeId MB ON rai.BTypeID = MB.TypeId
					INNER JOIN #GetManKTypeId K ON K.TypeId = B0.KTypeId
					WHERE B0.BillDate >='''+@StartDate+'''
						  AND B0.BillDate <='''+@EndDate+'''
						  AND B0.BillCode LIKE ''%'+@BillCode+'%''
						  AND B0.ifYearBill=0
	  '
	
	--维修状态
IF @BillState = '0'					
	SET @SQL = @SQL + ' AND BC3.BillState = 2'
IF @BillState = '1'
	SET @SQL = @SQL + ' AND BC3.BillState = 3'
IF @BillState = '2'
	SET @SQL = @SQL + ' AND BC3.BillState = 4'
	
--摘要，备注
SET @SQL = @SQL + '	AND B0.Explain LIKE ''%'+@Comment+'%''
					AND B0.Comment LIKE ''%'+@Explain+'%''
					AND B0.RedWord = 0
					)R
					WHERE RepairBillCode LIKE ''%'+@RepairBillCode+'%''
					GROUP BY   BillType,
							   BillNumberId,
							   RepairBillCode,
							   STypeId,
							   BillDate,
							   KTypeId,
							   billstate,
							   RATypeID,
							   BTypeId,
							   DTypeId,
							   ETypeId,
							   Explain,
							   Comment,
							   CostTotal,
							   SaleTotal,
							   GrossProfit,
							   BillCode
					ORDER BY   BillCode'	

END
	
ELSE
	
	BEGIN
	SET @SQL = @SQL + '
		(SELECT B.BillType,
					B.BillNumberId,
					''内部领料'' AS repairbillcode,
					B.STypeId,
					B.BillDate,
					0 as BillState,
					b.KTypeId,
					NULL as RATypeId,
					NULL as BTypeId,
					B.DTypeId,
					B.ETypeId,
					B.Explain,
					B.Comment,
					I.CostTotal,
					I.SaleTotal,
					I.GrossProfit,
					 b.BillCode as billcode
			FROM Qp_PickingBill	P
			INNER JOIN BillIndex B ON P.BillNumberId = B.BillNumberId
			INNER JOIN (
							SELECT BillNumberId,
								   -SUM(CostTotal) AS CostTotal,
								   -SUM(SaleTotal) AS SaleTotal,
								   -((SUM(SaleTotal) - SUM(CostTotal))) AS GrossProfit
							FROM InOutstocktable
							WHERE BillType = ''191''
							GROUP BY BillNumberId
			)I ON P.BillNumberId = I.BillNumberId
			INNER JOIN Billindex_CarRepair BC ON P.BillNumberId = BC.BillNumberId
			INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId 
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId
			WHERE B.BillDate >='''+@StartDate+'''
				  AND B.BillDate <='''+@EndDate+'''
				  AND B.BillCode LIKE ''%'+@BillCode+'%''
' 	
--摘要，备注
SET @SQL = @SQL + '	AND B.Explain LIKE ''%'+@Comment+'%''
					AND B.Comment LIKE ''%'+@Explain+'%''
					AND B.RedWord = 0
					AND BC.QuickRepairBillID = 0
					AND b.ifYearBill=0'		--年节存标志
IF @WciTypeId <> '' OR @RepairBillCode <> ''
			SET @SQL = @SQL + 'and 1=2'
SET @SQL = @SQL + 'UNION ALL

				   SELECT B0.BillType,
						  pb.BillNumberId,
						  ''内部领料'' AS repairbillcode,
						  B.STypeId,
						  B0.BillDate,
						  0 as BillState,
						   B0.KTypeId,
						  NULL as RATypeId,
						  NULL as BTypeId,
						 
						  B0.DTypeId,
						  B0.ETypeId,
						  B0.Explain,
						  B0.Comment,
						  I.CostTotal,
						  I.SaleTotal,
						  I.GrossProfit,
						  B0.BillCode as billcode
				   FROM Qp_PickingBackBill PB
				   INNER JOIN Billindex_CarRepair BC ON PB.BillNumberId = BC.BillNumberId
				   INNER JOIN BillIndex B0 ON PB.BillNumberId = B0.BillNumberId			   
				   INNER JOIN BillIndex B ON BC.QuickRepairBillID = B.BillNumberId			   
				   INNER JOIN Qp_PickingBill P ON B.BillNumberId=P.BillNumberId
				   INNER JOIN (
									SELECT BillNumberId,
										   -SUM(CostTotal) AS CostTotal,
										   -SUM(SaleTotal) AS SaleTotal,
										   ((-SUM(SaleTotal) - (-SUM(CostTotal)))) AS GrossProfit
									FROM InOutstocktable
									WHERE BillType = ''197''
									GROUP BY BillNumberId
					)I ON PB.BillNumberId = I.BillNumberId
					INNER JOIN Billindex_CarRepair BC2 ON P.BillNumberId = BC2.BillNumberId
					INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId 
					INNER JOIN #GetManDTypeId D ON D.TypeId = B0.DTypeId
					INNER JOIN #GetManETypeId E ON E.TypeId = B0.ETypeId
					INNER JOIN #GetManKTypeId K ON K.TypeId = PB.KTypeId
					WHERE B0.BillDate >='''+@StartDate+'''
						  AND B0.BillDate <='''+@EndDate+'''
						  AND B0.BillCode LIKE ''%'+@BillCode+'%''
						  AND b.ifYearBill=0	
	  '
IF @WciTypeId <> ''
			SET @SQL = @SQL + 'and 1=2'
	
--摘要，备注
SET @SQL = @SQL + '	AND B0.Explain LIKE ''%'+@Comment+'%''
					AND B0.Comment LIKE ''%'+@Explain+'%''
					AND B0.RedWord = 0
					AND BC2.QuickRepairBillID = 0
					)R'
IF @RepairBillCode <> ''
	SET @SQL += ' 
					WHERE 1 = 2'
	
SET @SQL += '
					GROUP BY   BillType,
							   BillNumberId,
							   RepairBillCode,
							   STypeId,
							   BillDate,
							   KTypeId,
							   billstate,
							   RATypeID,
							   BTypeId,
							   DTypeId,
							   ETypeId,
							   Explain,
							   Comment,
							   CostTotal,
							   SaleTotal,
							   GrossProfit,
							   BillCode
					ORDER BY   BillCode'				
	
END
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManDTypeId,#GetManETypeId,#GetManWciTypeId,#GetManKTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QuerypType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QuerypType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-04-21
	描述：查询维修材料
*/

CREATE PROCEDURE Qp_Web_QuerypType 
(
	@billnumberid VARCHAR(MAX)	--单据主表id
)
--@encode$--
AS
SET NOCOUNT ON
SELECT	P.typeId,
		P.UserCode,						--配件编号
		P.FullName,						--配件名称
		P.DwgNo,						--图号
		RF.Qty,							--数量
		RF.Price,						--单价
		RF.Total						--金额
FROM Qp_ReceptionBill_PType RF INNER JOIN PType P ON RF.PTypeID = P.typeId
WHERE RF.BillNumberId = @billnumberid
ORDER BY P.UserCode ASC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryPTypePickingBillTree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryPTypePickingBillTree]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-04-26
	描述：配件领用查询树型表
*/
CREATE PROCEDURE Qp_Web_QueryPTypePickingBillTree
(
	@OperatorId			VARCHAR(MAX),	--操作员ID
	@StartDate			VARCHAR(MAX),	--开始日期
	@EndDate			VARCHAR(MAX),	--截止日期
	@STypeId			VARCHAR(MAX),	--分支机构
	@BTypeId			VARCHAR(MAX),	--往来单位
	@WciTypeId			VARCHAR(MAX),	--车牌号
	@DTypeId			VARCHAR(MAX),	--部门ID
	@ETypeId			VARCHAR(MAX),	--经手人ID
	@KTypeId			VARCHAR(MAX),	--仓库
	@BillState			VARCHAR(MAX),	--维修进度
	@PTypeId			VARCHAR(MAX),	--配件ID
	@PTypeIdState		VARCHAR(MAX),	--配件状态
	@InnerPicking		VARCHAR(MAX)	--是否为内部领料
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--车牌号
CREATE TABLE #GetManWiTypeId(TypeId	varchar(100))
INSERT INTO #GetManWiTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	


DECLARE @SQL		VARCHAR(MAX),
		@SonNum		INT

SET @SQL = ''

--处理基本信息ID
IF @PTypeId = '' 
	SET @PTypeId = '00000'
		
SELECT @SonNum = SonNum FROM PType WHERE TypeID = @PTypeId	
CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),sonnum int,unit1 varchar(max),dwgNo varchar(max),parid varchar(max)) 
IF @sonnum =0 	
	INSERT INTO #MainType(typeid,usercode,sonnum,unit1,dwgNo,parid) 
	SELECT p.typeid,p.usercode,p.sonnum,p.Unit1,p.DwgNo,p.ParId FROM Ptype p
	,(select * from F_GetManPTypeAll(@OperatorID) where typeid =@PTypeId) a where p.typeid=a.typeid And p.typeid<>'00000'
ELSE
	IF @PTypeId='00000'
		INSERT INTO #MainType(typeid,usercode,sonnum,unit1,dwgNo,parid) 
		SELECT p.typeid,p.usercode,p.sonnum,p.Unit1,p.DwgNo,p.ParId FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid And p.typeid<>'00000'
	ELSE
		INSERT INTO #MainType(typeid,usercode,sonnum,unit1,dwgNo,parid) 
		SELECT p.typeid,p.usercode,p.sonnum,p.Unit1,p.DwgNo,p.ParId FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where parid=@PTypeId) a where p.typeid=a.typeid And p.typeid<>'00000'
		
--内部领料,将维修单号设置为空
IF @InnerPicking = 'TRUE'
BEGIN
		SET @SQL = 'SELECT	P.TypeId,
					P.UserCode,
					P.SonNum,
					P.Unit1,
					P.DwgNo,
					CASE SUM(ISNULL(PB.Qty,0))
						WHEN 0
							THEN 0
						ELSE
							SUM(ISNULL(PB.Total,0))/SUM(ISNULL(PB.Qty,0))
					END
					AS Price,
					SUM(ISNULL(PB.Qty,0)) AS Qty,
					SUM(ISNULL(PB.Total,0)) AS Total			
			FROM	#MainType P
			LEFT JOIN (
						SELECT	QPB.PTypeId,
								QPB.Price,
								ISNULL(SUM(QPB.Qty),0) AS Qty,
								ISNULL(SUM(QPB.Total),0) AS Total
						FROM Qp_PickingBill QPB
						INNER JOIN BillIndex B ON B.BillNumberId = QPB.BillNumberId
						INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = B.BillNumberId
						INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
						INNER JOIN #GetManKTypeId K ON K.TypeId = QPB.KTypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManPTypeId P ON QPB.PTypeId = P.TypeId
						INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
						WHERE	B.BillDate>='''+@StartDate+'''
						AND B.BillDate<='''+@EndDate+'''							
						AND B.RedWord = 0
						AND B.ifCheck = ''t''
						'
		SET @SQL = @SQL + 'AND Bc.QuickRepairBillId = 0'
		
		SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志
		
		--配件状态
IF @PTypeIdState = 1
	SET @SQL = @SQL + 'AND QPB.insurance = 0'
ELSE IF @PTypeIdState = 2
	SET @SQL = @SQL + 'AND QPB.insurance = 2'
ELSE IF @PTypeIdState = 3
	SET @SQL = @SQL + 'AND QPB.insurance = 1'
ELSE IF @PTypeIdState = 4
	SET @SQL = @SQL + 'AND QPB.insurance = 3'
ELSE IF @PTypeIdState = 5
	SET @SQL = @SQL + 'AND QPB.insurance = 4'
	
IF @BTypeId <> ''
			SET @SQL = @SQL + ' AND 1 = 2'
IF @WciTypeId <> ''
			SET @SQL = @SQL + ' AND 1 = 2'
			
SET @SQL = @SQL + '
						GROUP BY QPB.PTypeId,
								QPB.Price
					UNION ALL
					SELECT	QPB.PTypeId,
								QPB.Price,
								-ISNULL(SUM(QPB.Qty),0) AS Qty,
								-ISNULL(SUM(QPB.Total),0) AS Total
						FROM QP_PickingBackBill QPB 
						INNER JOIN BillIndex B ON B.BillNumberId = QPB.BillNumberId
						INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = B.BillNumberId
						INNER JOIN Billindex_CarRepair Bc2 ON Bc.QuickRepairBillID = Bc2.BillNumberId
						INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
						INNER JOIN #GetManKTypeId K ON K.TypeId = QPB.KTypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManPTypeId P ON QPB.PTypeId = P.TypeId
						INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
						WHERE	B.BillDate>='''+@StartDate+'''
						AND B.BillDate<='''+@EndDate+'''							
						AND B.RedWord = 0
						AND B.ifCheck = ''t''
						'
		SET @SQL = @SQL + 'AND Bc2.QuickRepairBillId = 0'
		
		SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志
		
		--配件状态
IF @PTypeIdState = 1
	SET @SQL = @SQL + 'AND QPB.insurance = 0'
ELSE IF @PTypeIdState = 2
	SET @SQL = @SQL + 'AND QPB.insurance = 2'
ELSE IF @PTypeIdState = 3
	SET @SQL = @SQL + 'AND QPB.insurance = 1'
ELSE IF @PTypeIdState = 4
	SET @SQL = @SQL + 'AND QPB.insurance = 3'
ELSE IF @PTypeIdState = 5
	SET @SQL = @SQL + 'AND QPB.insurance = 4'
	
IF @BTypeId <> ''
			SET @SQL = @SQL + ' AND 1 = 2'
IF @WciTypeId <> ''
			SET @SQL = @SQL + ' AND 1 = 2'
END
--维修状态
ELSE 
BEGIN
	SET @SQL = 'SELECT	P.TypeId,
					P.UserCode,
					P.SonNum,
					P.Unit1,
					P.DwgNo,
					CASE SUM(ISNULL(PB.Qty,0))
						WHEN 0
							THEN 0
						ELSE
							SUM(ISNULL(PB.Total,0))/SUM(ISNULL(PB.Qty,0))
					END
					AS Price,
					SUM(ISNULL(PB.Qty,0)) AS Qty,
					SUM(ISNULL(PB.Total,0)) AS Total			
				FROM	#MainType P
				LEFT JOIN (
							SELECT	QPB.PTypeId,
									QPB.Price,
									ISNULL(SUM(QPB.Qty),0) AS Qty,
									ISNULL(SUM(QPB.Total),0) AS Total
							FROM Qp_PickingBill QPB
							INNER JOIN BillIndex B ON B.BillNumberId = QPB.BillNumberId
							INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = B.BillNumberId
							INNER JOIN Billindex_CarRepair Bc2 ON Bc2.BillNumberId = Bc.QuickRepairBillID
							INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
							INNER JOIN #GetManKTypeId K ON K.TypeId = QPB.KTypeId
							INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
							INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
							INNER JOIN #GetManPTypeId Pi ON Pi.TypeId = QPB.PTypeId
							INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
							INNER JOIN #GetManWiTypeId Wi ON Wi.TypeID = Bc.RATypeID
							WHERE	B.BillDate>='''+@StartDate+'''
							AND B.BillDate<='''+@EndDate+'''							
							AND B.RedWord = 0
							AND B.ifCheck = ''t''
						'
	IF @BillState = '0'					
		SET @SQL = @SQL + ' AND Bc2.BillState = 2'
	ELSE IF @BillState = '1'					
		SET @SQL = @SQL + ' AND Bc2.BillState = 3'
	ELSE IF @BillState = '2'					
		SET @SQL = @SQL + ' AND Bc2.BillState = 4'
		
	SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志	
	
		--配件状态
IF @PTypeIdState = 1
	SET @SQL = @SQL + 'AND QPB.insurance = 0'
ELSE IF @PTypeIdState = 2
	SET @SQL = @SQL + 'AND QPB.insurance = 2'
ELSE IF @PTypeIdState = 3
	SET @SQL = @SQL + 'AND QPB.insurance = 1'
ELSE IF @PTypeIdState = 4
	SET @SQL = @SQL + 'AND QPB.insurance = 3'
ELSE IF @PTypeIdState = 5
	SET @SQL = @SQL + 'AND QPB.insurance = 4'


SET @SQL = @SQL + 'GROUP BY QPB.PTypeId,
								QPB.Price
						UNION ALL
							SELECT	QPB.PTypeId,
									QPB.Price,
									-ISNULL(SUM(QPB.Qty),0) AS Qty,
									-ISNULL(SUM(QPB.Total),0) AS Total
							FROM QP_PickingBackBill QPB
							INNER JOIN BillIndex B ON B.BillNumberId = QPB.BillNumberId
							INNER JOIN Billindex_CarRepair Bc ON Bc.BillNumberId = B.BillNumberId
							INNER JOIN Billindex_CarRepair Bc2 ON Bc2.BillNumberId = Bc.QuickRepairBillID
							INNER JOIN Billindex_CarRepair Bc3 ON Bc3.BillNumberId = Bc2.QuickRepairBillID
							INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
							INNER JOIN #GetManKTypeId K ON K.TypeId = QPB.KTypeId
							INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
							INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
							INNER JOIN #GetManPTypeId Pi ON Pi.TypeId = QPB.PTypeId
							INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
							INNER JOIN #GetManWiTypeId Wi ON Wi.TypeID = Bc.RATypeID
							WHERE	B.BillDate>='''+@StartDate+'''
							AND B.BillDate<='''+@EndDate+'''							
							AND B.RedWord = 0
							AND B.ifCheck = ''t''
						'
	IF @BillState = '0'					
		SET @SQL = @SQL + ' AND Bc3.BillState = 2'
	ELSE IF @BillState = '1'					
		SET @SQL = @SQL + ' AND Bc3.BillState = 3'
	ELSE IF @BillState = '2'					
		SET @SQL = @SQL + ' AND Bc3.BillState = 4'
	
	SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志
		
		--配件状态
IF @PTypeIdState = 1
	SET @SQL = @SQL + 'AND QPB.insurance = 0'
ELSE IF @PTypeIdState = 2
	SET @SQL = @SQL + 'AND QPB.insurance = 2'
ELSE IF @PTypeIdState = 3
	SET @SQL = @SQL + 'AND QPB.insurance = 1'
ELSE IF @PTypeIdState = 4
	SET @SQL = @SQL + 'AND QPB.insurance = 3'
ELSE IF @PTypeIdState = 5
	SET @SQL = @SQL + 'AND QPB.insurance = 4'

END
SET @SQL = @SQL + '
						GROUP BY QPB.PTypeId,
								QPB.Price
			)PB ON LEFT(PB.PTypeId,LEN(P.TypeId)) = P.TypeId
			'	

IF @SonNum = 0 
	SET @SQL = @SQL + ' WHERE P.TypeId = '''+@PTypeId+''''
ELSE
	SET @SQL = @SQL + ' WHERE P.ParId = '''+@PTypeId+''''
	
SET @SQL = @SQL + '
				GROUP BY	P.TypeId,
							P.SonNum,
							P.UserCode,
							P.Unit1,
							P.DwgNo	
				   ORDER BY P.UserCode ASC'		

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManETypeId,#GetManBTypeId,#GetManPTypeId,#GetManKTypeId,#GetManDTypeId,#MainType,#GetManWiTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryRecepation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Qp_Web_QueryRecepation
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-04-20
	描述：接待登记查询
*/

CREATE PROCEDURE Qp_Web_QueryRecepation 
(
	@operatorid		VARCHAR(100),	--操作员ID
	@startdate		VARCHAR(MAX),	--开始日期
	@enddate		VARCHAR(MAX),	--截止日期
	@stypeid		VARCHAR(MAX),	--分支机构ID
	@btypeId		VARCHAR(MAX),	--往来单位ID
	@dtypeId		VARCHAR(MAX),	--部门ID
	@etypeId		VARCHAR(MAX),	--经手人ID
	@wcitypeid		VARCHAR(MAX),	--车牌号
	@BillState		VARCHAR(MAX),	--维修进度
	@billcode		VARCHAR(MAX)	--单据编号
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	

--车牌号
CREATE TABLE #GetManWTypeId(TypeId	varchar(100))
INSERT INTO #GetManWTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@wcitypeid,12,'00001')	

--构造SQL语句
DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'SELECT	Bc.BillnumberID,
					Bc.BeSpokeDate,
					CASE DATEPART(YY,Bc.InFactoryDate) WHEN 9999 THEN NULL ELSE Bc.InFactoryDate END AS InFactoryDate, 
					Bc.ReceptionDate,
					Bc.CompleteDate,
					Bc.RepairMode,
					CASE Bc.BillState WHEN 1 THEN ''登记'' WHEN 2 THEN ''在修'' WHEN 3 THEN ''完工待结算'' WHEN 4 THEN ''已结算'' END AS BillState ,
					Bc.OperationSort,
					E1.fullname as Reception,
					e2.fullname as UnitSatrap,
					Bc.SendPerson,
					B.TotalMoney AS Total,
					B.Tel,
					B.BillCode,
					B.STypeId,
					B.BTypeId,
					B.ETypeId,
					B.DTypeId,
					B.Explain,
					B.Comment,
					Bc.RATypeID
			FROM	BillIndex B
			INNER JOIN BillIndex_CarRepair Bc ON B.BillNumberId = Bc.BillNumberId
			LEFT JOIN Employee e1 on bc.ReceptionId=e1.typeid
			LEFT JOIN Employee e2 on bc.UnitSatrap=e2.typeid
			INNER JOIN #GetManWTypeId W ON W.typeid=Bc.RATypeID
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			WHERE	B.BillType=195
					AND B.RedWord=0
					AND Bc.ReceptionDate>='''+@startdate+'''
					AND CONVERT (DATE,Bc.ReceptionDate,120)<='''+@enddate+'''
					AND B.BillCode LIKE ''%'+@billcode+'%'''
IF 	@BillState<>0
	BEGIN
		IF @BillState<>1		
			SET @SQL=@SQL+'AND	Bc.BillState='+CAST((@BillState-1) AS VARCHAR(1))
		ELSE
			SET @SQL=@SQL+'AND	Bc.BillState IN (1,2,3)'
	END

SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志
SET @SQL = @SQL + ' ORDER BY B.BillDate DESC,B.BillCode DESC'		
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManDTypeId,#GetManETypeId,#GetManWTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryRepairItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QueryRepairItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-04-21
	描述：查询维修项目
*/

CREATE PROCEDURE Qp_Web_QueryRepairItems 
(
	@billnumberid VARCHAR(MAX)	--单据主表id
)
--@encode$--
AS
SET NOCOUNT ON
SELECT	RR.RepairItemsTypeID,			--维修项目编号
		R.FullName,						--维修项目名称
		RR.StandardManHour,				--维修项目标准工时
		RR.Total						--维修项目工时费
FROM Qp_ReceptionBill_RepairItems RR 
INNER JOIN QP_RepairItems R ON RR.RepairItemsTypeID = R.TypeID
WHERE RR.BillNumberId	=	@billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QuerySerialMultiBarCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QuerySerialMultiBarCode]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：颜熙
	日期：2017-09-05
	描述：根据序列号查询商品多条码
	Qp_Web_QueryMultiBarCode '00001','','11'
*/

CREATE PROCEDURE Qp_Web_QuerySerialMultiBarCode
(
	@OperatorId		VARCHAR(100),	
	@stypeid		VARCHAR(MAX),
	@serial         VARCHAR(1000),
	@Price			VARCHAR(100)    
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @PtypeId VARCHAR(50)
SELECT @PtypeId = PtypeID FROM dbo.gp_CruPtypeSerial WHERE Serial = @serial

EXEC Qp_Web_QueryMultiBarCodeCopy @OperatorId,@PTypeId,@stypeid,@Price,@serial

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QueryStopItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Qp_Web_QueryStopItems
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-04-20
	描述：停工项目查询
*/

CREATE PROCEDURE Qp_Web_QueryStopItems
(
	@operatorid			VARCHAR(100),	--操作员ID
	@startdate			VARCHAR(MAX),	--开始日期
	@enddate			VARCHAR(MAX),	--截止日期
	@stypeid			VARCHAR(MAX),	--分支机构ID
	@dtypeId			VARCHAR(MAX),	--部门ID
	@etypeId			VARCHAR(MAX),	--维修人ID
	@witypeid			VARCHAR(MAX),	--维修项目
	@stopreason			VARCHAR(MAX)	--停工原因
)
--@encode$--
AS
SET NOCOUNT ON

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,'00001')

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dtypeid,9,'00001')	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,'00001')	

--维修项目
CREATE TABLE #GetWiTypeId(witypeid	varchar(100))
INSERT INTO #GetWiTypeId(witypeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@witypeid,13,'00001')

DECLARE @SQL VARCHAR(MAX)

SET @SQL='SELECT	R.TypeID,
		R.UserCode,		
		Rb.BillNumberId,
		Rb.StandardManHour,
		Rb.CheckHour,
		Rb.Total,
		CASE Rb.RepairProcess WHEN 1 THEN ''未派工'' WHEN 2 THEN ''正在修理'' WHEN 3 THEN ''修理完毕'' WHEN 4 THEN ''停工'' END AS RepairProcess,
		CASE Rb.Insurance WHEN 0 THEN ''正常'' WHEN 1 THEN ''保险'' WHEN 2 THEN ''三包'' WHEN 3 THEN ''返修'' WHEN 4 THEN ''赠送'' END AS State,
		CASE DATEPART(YY,Rb.AppointTime) WHEN 9999 THEN NULL ELSE Rb.AppointTime END AS AppointTime,
		Rb.StopTime,
		Rb.StopReason,
		Rb.RepairMan,
		Rb.Comment,
		B.Stypeid,
		B.BillCode
		FROM Qp_ReceptionBill_RepairItems Rb
		INNER JOIN BillIndex B ON B.BillNumberId=Rb.BillNumberId
		INNER JOIN QP_RepairItems R ON Rb.RepairItemsTypeID=R.TypeID'
IF @etypeId<>''
	SET @SQL+=' INNER JOIN (SELECT DISTINCT(rr.RepairItemsTypeID),
								   ab.RepairItemsID,
								   ab.BillNumberId
							FROM Qp_AttemperBill_RepairItemsPerson AB
							INNER JOIN Qp_ReceptionBill_RepairItems RR ON ab.RepairItemsID=RR.ID 
							INNER JOIN #GetManETypeId ET ON ET.TypeId=AB.etypeid
					) BILL ON BILL.RepairItemsTypeID=R.TypeID AND B.BillNumberId=BILL.BillNumberId AND Rb.id=BILL.RepairItemsID'	
								
SET @SQL+=' INNER JOIN #GetWiTypeId W ON W.witypeid=R.TypeID
		INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
WHERE	Rb.StopTime>='''+@startdate+'''
		AND CONVERT (DATE,Rb.StopTime,120)<='''+@enddate+'''
		AND Rb.StopReason LIKE ''%'+@stopreason+'%''
		AND RB.RepairProcess=4
		AND b.ifYearBill=0	 --年节存标志
ORDER BY R.UserCode ASC'

--PRINT @SQL
EXEC(@SQL)		
DROP TABLE #GetManSTypeId,#GetManDTypeId,#GetManETypeId,#GetWiTypeId  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_QuotePriceBillQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_QuotePriceBillQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：Wang Wei
	日期：2010-09-13
	描述：报价单查询
*/

/*
	修改：李灏龙
	日期：2012年2月10日13:48:58
	描述：增添查询字段，以显示商品被调用的次数，具体修改处注释：zs001
*/
/*
	修改：舒珊
	日期：2016年2月23日15:59:00
	描述：增添表头、表体自定义显示字段
	
			
	修改：舒珊
	日期：2016-05-27
	描述： 添加商品类别筛选
	
	修改：舒珊
	日期：2016-05-31
	描述： 添加表头表体新增加的自定义字段
	
	修改：舒珊
	日期：2016-06-13
	描述： 报价单引用规则调整-报价单查询调整(添加“已转订单数”查询列)
	
	修改：赵燕琴
	日期：2019-05-29
	描述： 报价状态原来取主表改成取明细表的报价状态
*/
CREATE PROCEDURE Qp_Web_QuotePriceBillQuery 
(
	@OperatorID	VARCHAR(100),
	@startdate	VARCHAR(60),
	@enddate	VARCHAR(60),
	--@BtypeId	VARCHAR(8000)='',
	@dealbtypeid	VARCHAR(8000)='',
	@Ptypeid	VARCHAR(8000)='',
	@priceType	VARCHAR(5)='-1',
	@Comment	VARCHAR(MAX),
	@Stypeid    VARCHAR(8000)='00001', --分支机构
	@Dtypeid    VARCHAR(8000)='',      --部门
	@Etypeid    VARCHAR(8000)='',	   --经手人
	@shzt		VARCHAR(10)='9'	,				--审核状态
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @MPtypeid='-99999'
	INSERT INTO #GetManPTypeId(TypeId) 
	SELECT p.TypeId FROM F_ManPTypeInCategoryID(@OperatorID,@Ptypeid,@ptypecategoryid) p  INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
ELSE
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_ManPTypeInCategoryID(@OperatorID,@Ptypeid,@ptypecategoryid)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999' OR @MBtypeid2='-99999'
	INSERT INTO #GetManBTypeId(TypeId) 
	SELECT b.typeid FROM F_GetManDetailBType(@OperatorID) b	INNER JOIN dbo.F_GetAllBaseTypeId(@dealbtypeid,2) sb ON b.TypeId = sb.TypeId
ELSE 
	INSERT INTO #GetManBTypeId(TypeId)	SELECT typeid FROM	F_GetAllBaseTypeId(@dealbtypeid,2)


--分支机构
CREATE TABLE #Stype(TypeId	varchar(100))
IF @Stypeid<>'' OR @MStypeid='-99999'
	INSERT INTO #Stype(TypeId)  select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)

--部门
CREATE TABLE #Dtype(TypeId varchar(100))
IF @Dtypeid<>'' OR @MDtypeid='-99999'
    INSERT INTO #Dtype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@Dtypeid,9,@OperatorID)
    
--经手人
CREATE TABLE #Etype(TypeId varchar(100))
IF @Etypeid<>'' OR @MEtypeid='-99999'
    INSERT INTO #Etype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@Etypeid,3,@OperatorID)


DECLARE @Sql VARCHAR(8000)


---------------单据审核状态--------------
CREATE TABLE #AuditingBill
(
	BillNumberId NUMERIC(18,0),
	CheckState	 VARCHAR(50),
	IfAudit      CHAR(2)
)

IF @shzt <> '9' --非全部状态(9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据)
BEGIN
	--IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @orderBillType AND IfUse = 1)
	--BEGIN
		IF @shzt = '0'	--原始单据
			BEGIN
				SET @Sql=' INSERT INTO #AuditingBill(BillNumberId,CheckState,IfAudit)
								SELECT	B.BillNumberId,
										''原始单据'' AS CheckState,
										''1'' 
								FROM	BillIndex B			
								WHERE	B.BillDate >='+CHAR(39)+ @startdate+CHAR(39)+'
										AND B.BillDate <= '+CHAR(39)+ @enddate+CHAR(39)+' 
										AND B.billtype = 184
										AND NOT EXISTS
										(
											SELECT	A.billNumberId,a.IfAudit 
											FROM	AuditingBill A
											INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID '
											IF @Stypeid<>'' OR @MStypeid='-99999'
												SET @Sql+=' INNER JOIN #stype S ON S.TypeID = F.Stypeid	'	
																					
				SET @Sql+='	WHERE a.BillNumberID = B.billNumberId AND BillIndexType=''2''	AND f.BillType=184		) '
			END
		ELSE
			BEGIN
				SET @Sql=' INSERT INTO #AuditingBill(BillNumberId,CheckState,IfAudit)
						SELECT	A.BillNumberId,
								CASE '+CHAR(39)+ @shzt+CHAR(39)+'
									WHEN ''1'' THEN ''待审核单据''
									WHEN ''2'' THEN ''审核通过单据''
									ELSE ''审核不通过单据''
								END AS CheckState,
								a.IfAudit
						FROM	AuditingBill A
						INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID '
				
				IF @Stypeid<>'' OR @MStypeid='-99999'
							SET @Sql+=' INNER JOIN #stype S ON S.TypeID = F.Stypeid	'	
							
                    SET @Sql += '	WHERE	A.BillDate >=' + CHAR(39) + @startdate + CHAR(39) + '
								AND A.BillDate <= ' + CHAR(39) + @enddate + CHAR(39) + '							
								AND F.IfUse = 1
								AND F.billtype = 184
								AND A.BillIndexType = 2
								AND A.IfAudit = CASE
													WHEN ' + CHAR(39) + @shzt + CHAR(39) + ' = ''1'' THEN ''0''
													WHEN ' + CHAR(39) + @shzt + CHAR(39) + ' = ''2'' THEN ''1''
													ELSE ''-1''
												END		'
			END					
	--END
	--PRINT(@Sql)
	EXEC(@Sql)
END

------------------------------------
--select * from #AuditingBill


--zs001 在原来的基础上添加x.usedsum、x.ID字段和LEFT JOIN部分
SET @Sql='
	SELECT	bi.billNumberId,
			bi.billcode,
			bi.billDate,
			bi.btypeid,
			bi.dealbtypeid,
			bi.billtype,
			x.usedsum,										--调用次数
			x.ID AS customdetailid, 						--报价表明细id
			qpb.ptypeid,
			qpb.qty,										--数量
			ISNULL(ordqty.orderdqty,0) AS orderdqty,								--已转订单数
			--qpb.nsaleprice,									--原币单价
			--qpb.nsaletotal,									--原币金额
			qpb.NDISCOUNTPRICE,								--原币折后单价
			qpb.NTOTAL,										--原币折后金额
			qpb.ntaxprice,									--原币含税单价
			qpb.ntaxtotal,								    --原币价税合计
			ac.FullName as currencyFullName,				--原币币别
			it.fullname as fullname,						--自由项
			ISNULL(qpb.DiscountPrice,0) As DiscountPrice ,	--单价(折后单价)
			ISNULL(qpb.Total,0) As Total,					--金额(折后金额)
			ISNULL(qpb.TaxPrice,0) As TaxPrice,				--含税单价
			ISNULL(qpb.TaxTotal,0) As TaxTotal,				--价税合计
			qpb.IfBargainOn, 								--报价状态(明细表)
			CASE
							WHEN ISNULL(AB.CheckState,'''') = '''' THEN ''原始单据''
							ELSE AB.CheckState
						END AS CheckState,
						isnull(AB.IfAudit,''1 '') as IfAudit,
			SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
			SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
			SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
			SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
			SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
			SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
			SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32			
	FROM dbo.BillIndex bi 
	INNER JOIN QuotePriceBill qpb ON bi.BillNumberId=qpb.BillNumberId
	LEFT JOIN (
				SELECT		q.BillNumberID,q.ID,COUNT(o.billnumberid) AS usedsum
				FROM		QuotePriceBill q
				LEFT JOIN	OrderBill O ON q.BillNumberID=o.askBillNumberID AND q.ID=o.askBillID
				GROUP BY	q.BillNumberID,q.ID
			  ) x ON qpb.BillNumberId = x.BillNumberID AND qpb.ID = x.ID
	LEFT JOIN (
				SELECT SUM(ISNULL(orderdqty,0)) AS ORDERDQTY,ORD.BillNumberID,ptypeid
				FROM
				(
					SELECT  CASE WHEN  a.billover <>0
								  THEN ISNULL(A.ReachQty,0) 
								  ELSE ISNULL(A.QTY,0)end orderdqty ,q.BillNumberID,A.ptypeid
								  FROM QuotePriceBill Q
								  LEFT JOIN orderbill A ON q.BillNumberID=A.askBillNumberID AND q.ID=A.askBillID  
					)ORD		  
				GROUP BY ORD.BillNumberID,ptypeid
				)ordqty on ordqty.BillNumberID=bi.BillNumberId and ordqty.ptypeid=qpb.ptypeid
	LEFT JOIN Custom_BillIndex csindex on bi.billnumberid=csindex.BillId and bi.billtype=csindex.billtype
	LEFT JOIN Custom_BillDetails csdetail on bi.billnumberid=csdetail.BillId and bi.billtype=csdetail.billtype AND qpb.ID=csdetail.Detailid
	LEFT JOIN AC_CURRENCY ac ON bi.CID=ac.CID
	LEFT JOIN vWeb_ItemIDByIsCombined it ON qpb.ItemID=it.id and  qpb.IsCombined=it.iscombined'
	
	IF @shzt <> '9'
		SET @SQL = @SQL + ' INNER JOIN #AuditingBill AB ON AB.BillNumberId = BI.BillNumberId '
	ELSE
		SET @SQL = @SQL + ' LEFT JOIN (
											SELECT	A.BillNumberId,
													CASE A.IfAudit
														WHEN 0 THEN ''待审核单据''
														WHEN 1 THEN ''审核通过单据''
														ELSE ''审核不通过单据''
													END AS CheckState,
													A.IfAudit
											FROM	AuditingBill A
											INNER JOIN AuditingFlowSet F ON A.AuditingId = F.AuditingId AND F.BillType = 184
											WHERE	A.BillIndexType = 2
													AND A.BillDate >= '''+CAST(@startdate AS VARCHAR(100))+'''
													AND A.BillDate <= '''+CAST(@enddate AS VARCHAR(100))+'''
									   )AB ON AB.BillNumberId = BI.BillNumberId '
			  
IF @MPtypeid='-99999' OR @Ptypeid<>'' OR @ptypecategoryid<>''
	SET @Sql=@Sql+' INNER JOIN #GetManPTypeId p ON qpb.ptypeid=p.typeid '
--IF @Comment<>''
--	SET @Sql=@Sql+' INNER JOIN ptype pcm ON pcm.typeid=qpb.ptypeid '
IF @MBtypeid='-99999' OR @MBtypeid2='-99999' OR @dealbtypeid<>''
	SET @Sql=@Sql+' INNER JOIN #GetManBTypeId b ON bi.dealbtypeid=b.typeid'	
	
IF @Stypeid<>'' OR @MStypeid='-99999'
   SET @Sql=@Sql+' INNER JOIN #Stype s ON bi.stypeid=s.typeid'	

IF @Dtypeid<>'' OR @MDtypeid='-99999'
   SET @Sql=@Sql+' INNER JOIN #Dtype d ON bi.dtypeid=d.typeid'
   
IF @Etypeid<>'' OR @MEtypeid='-99999'
   SET @Sql=@Sql+' INNER JOIN #Etype e ON bi.etypeid=e.typeid'
 
SET @Sql=@Sql+' WHERE bi.billtype=184 AND bi.Billdate>= '+CHAR(39)+CAST(@startdate AS VARCHAR(100))+CHAR(39)+' AND bi.Billdate<= '+CHAR(39)+CAST(@enddate AS VARCHAR(100))+CHAR(39)

IF @priceType<>'-1'
	SET @Sql=@Sql+' AND qpb.IfBargainOn='+@priceType
	
IF @Comment<>''
	--SET @Sql=@Sql+' AND pcm.Comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)
	SET @Sql=@Sql+' AND qpb.Comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)	

SET @Sql=@Sql+' AND bi.ifYearBill=''0'''	--年节存标志
SET @Sql=@Sql+' ORDER BY billDate desc ,billcode desc'	--默认排序：报价日期、报价单号的降序。	
--print(@Sql)
EXEC(@Sql)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_ReachDayALert]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_ReachDayALert]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_Web_ReachDayALert (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @intDay int=0,
   @chvSortFild varchar(50)  ,				--排序字段
   @chvSortType	varchar(10)				--排序方式
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Btype(typeid VARCHAR(50))

--往来单位    
INSERT INTO #Btype(typeid) SELECT typeid FROM F_GetManDetailBType(@OperatorID)

-- 取得当前日期
DECLARE  @TotDay varchar(200)
	SET @TotDay = Convert(varchar(20),year(GetDate())) +'-'+Convert(varchar(20),Month(GetDate()))+'-'+Convert(varchar(20),Day(GetDate()))

-- 取得当前日期加一定的天数后的新的日期
DECLARE  @TotDay1 Datetime
	SET @TotDay1=DATEADD(Day,@intDay,@TotDay)

DECLARE  @TotDayAdd varchar(200)
	SET @TotDayAdd = Convert(varchar(20),year(@TotDay1)) +'-'+Convert(varchar(20),Month(@TotDay1))+'-'+Convert(varchar(20),Day(@TotDay1))

IF(@chvSortFild='') 
   SET @chvSortFild = 'A.VipCardCode'
IF(@chvSortType='')
   SET @chvSortType = 'ASC'
--select * from nVipCardSign where VipCardCode='008'
DECLARE @SQL varchar(4000)
SET @SQL='SELECT A.VipCardID,
                 A.VipCardTypeID,
                 A.RATypeID,
                 A.BTypeID,
                 A.CarType,
                 A.VipCardCode,
                 A.Bname,
                 A.Btel,
                 A.EndDate,
                 A.deleted AS deleted,
				 CASE 
					WHEN A.deleted = 0 THEN ''启用''
					WHEN A.deleted = 2 THEN ''停用''
					WHEN A.deleted = 3 THEN ''挂失''
					ELSE ''启用''
				 END AS zt,	
                 CASE 
					WHEN A.IsCZ = 0 THEN ''否''
					WHEN A.IsCZ = 1 THEN ''是''
				 END AS IsCZ,	
                 A.czyemoney,
                 CASE 
                    WHEN A.IsWashTimes=0 THEN ''否''
                    WHEN A.IsWashTimes=1 THEN ''是''
                 END AS IsWashTimes,
                 A.CanWashTimes,
                 A.Comment AS Comment,
                 B.TypeName
             FROM  nVipCardSign A
                   INNER JOIN nVipCardSet  B ON A.VipCardTypeID=B.VipCardTypeID '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
SET @SQL=@SQL + ' INNER JOIN  #Btype BB ON  A.BTypeID=BB.typeid '

IF(ISNULL(@intDay,0)>=0)
SET @SQL=@SQL+ '  WHERE  Convert(datetime,A.EndDate) >=Convert(datetime,'+char(39)+@TotDay+char(39)+')
                          AND Convert(datetime,A.EndDate) <=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+') ' 
ELSE
SET @SQL=@SQL+ '  WHERE  Convert(datetime,A.EndDate) >=Convert(datetime,'+char(39)+@TotDayAdd+char(39)+')
                          AND Convert(datetime,A.EndDate) <=Convert(datetime,'+char(39)+@TotDay+char(39)+') ' 

SET @SQL=@SQL+ ' ORDER BY  ' + @chvSortFild + '  ' +  @chvSortType
--PRINT @SQL RETURN     

EXEC(@SQL)   
      
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_RepairBalanceBill_Ptype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_RepairBalanceBill_Ptype]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

查询维修结算单的实际维修配件

*/
CREATE          PROCEDURE Qp_Web_RepairBalanceBill_Ptype
( 
 @BillNumberId numeric(10,0),
 @Insurance	VARCHAR(10)=''
)
--@encode$--
AS
SET NOCOUNT ON 
/*查询接待登记相关联的领料出库*/
CREATE TABLE #billindex
(
	billnumberid		[numeric](10, 0),
	QuickRepairBillID	[numeric](10, 0),			
)
DECLARE @zk  NUMERIC(24, 10) 
SELECT Top 1 @zk=value FROM Userconfig WHERE ConfigName like '%ZeKouValue%'
DECLARE @SQL VARCHAR(MAX)
SET @SQL=' 
SELECT		pb.qty,
			pb.Price,
			pb.Total,
			pb.costtotal,
			pb.Insurance,
			--(CAST('+CAST(@zk as VARCHAR(20))+' as  NUMERIC(24, 10) ))as discount,
			pb.discount,
			pb.discountprice,
			--(CAST('+CAST(@zk as VARCHAR(20))+' as  NUMERIC(24, 10) ) * CAST(pb.Price as  NUMERIC(24, 10) ))as discountprice,
			--(CAST('+CAST(@zk as VARCHAR(20))+' as  NUMERIC(24, 10) ) * CAST(pb.Total as  NUMERIC(24, 10) ))as discounttotal,
			pb.discounttotal,
			pb.virtual as virtual1,
			pb.ID,
			p.UserCode,
			pb.PTypeID as typeid,
			p.FullName,
			pb.comment
FROM	Qp_ReceptionBill_FactUsePType pb 
		INNER JOIN  ptype p ON p.typeId=pb.PTypeID 
WHERE pb.qty>0 AND pb.ReceptionBillnumberId='+CAST(@BillNumberId AS VARCHAR(100))
IF ISNULL(@Insurance,'')<>'' 	 
	SET @SQL=@SQL+' AND pb.Insurance='+@Insurance
SET @SQL=@SQL+' order by pb.ID '	
print @SQL
EXEC(@SQL)



/*
INSERT INTO #billindex
SELECT b.billnumberid,c.QuickRepairBillID
FROM	BillIndex b 
		INNER JOIN Billindex_CarRepair c ON b.BillNumberId=c.BillNumberId AND QuickRepairBillID=@BillNumberId
WHERE	b.BillType=191



DECLARE @SQL VARCHAR(MAX)


SET @SQL=' 
SELECT		pb.qty,
			pb.Price,
			pb.Total,
			pb.costtotal,
			pb.Insurance,
			pb.discount,
			pb.discountprice,
			pb.discounttotal,
			pb.virtual as virtual1,
			pb.ID,
			p.UserCode,
			pb.PTypeID as typeid,
			p.FullName,
			pb.comment
FROM	#billindex b
		INNER JOIn  Qp_ReceptionBill_FactUsePType pb ON b.billnumberid=pb.BillNumberId AND pb.qty>0
		INNER JOIN  ptype p ON p.typeId=pb.PTypeID '
IF ISNULL(@Insurance,'')<>'' 	 
	SET @SQL=@SQL+' WHERE pb.Insurance='+@Insurance
EXEC(@SQL)

DROP TABLE #billindex
*/
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_RepairDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_RepairDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	修改者：赵斌
	日期：2011-05-11
	描述：增加单据类型，修改查询条件
*/

CREATE   PROCEDURE QP_web_RepairDetail (
   @OperatorID	varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @startdate	varchar(50), --开始时间
   @enddate		varchar(50),--结束时间
   @chvDtypeID	varchar(4000),
   @chvEtypeID	varchar(4000),
   @wcitypeid	varchar(4000), --车牌号
   @chvBtypeID	varchar(4000),
   @chvKTypeID	varchar(4000),
   @chvPTypeID	varchar(4000),
   @Xzzd		int =9,
   @wxjd		int =9,
   @Bxzt		int =9,
   @StypeId		varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--车牌号(不用控制权限范围)
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,'00001')

CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

CREATE TABLE #GetManKTypeId(TypeId varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeID,4,@OperatorID)

DECLARE @SQL VARCHAR(MAX)
SET @SQL = ''				 
CREATE TABLE #RESULT(BillNumberId varchar(max),
				PtypeId varchar(max),
				Qty  NUMERIC(24, 10) ,
				CostTotal  NUMERIC(24, 10) ,
				TaxTotal  NUMERIC(24, 10) ,
				CostPrice  NUMERIC(24, 10) ,
				TaxPrice  NUMERIC(24, 10) ,
				EtypeId varchar(max),
				KtypeId varchar(max),
				Comment varchar(max))

SET @SQL = 'INSERT INTO 
			#RESULT
					(	
						BillNumberId,
						PTypeId,
						Qty,
						CostTotal,
						TaxTotal,
						CostPrice,
						TaxPrice,
						EtypeId,
						KtypeId,
						Comment
					)
					(		    
				    select	B.BillNumberId,
							RF.PTypeID,
							RF.Qty,
					Convert( NUMERIC(24, 10) ,RF.CostTotal) as CostTotal,
					Convert( NUMERIC(24, 10) ,RF.DiscountTotal) as TaxTotal,
										CASE RF.Qty 
						WHEN 0
							THEN 0
						ELSE 
							Convert( NUMERIC(24, 10) ,RF.CostTotal/RF.Qty) 
					END as CostPrice,
					Rf.DiscountPrice AS TaxPrice,
					rf.ETypeID,
					pb.KTypeID,
					RF.Comment	
					FROM Qp_ReceptionBill_FactUsePType RF
					--维修单
					INNER JOIN BillIndex B ON RF.ReceptionBillnumberId = B.BillNumberId
					INNER JOIN Billindex_CarRepair bc ON B.BillNumberId = Bc.BillNumberId
					--领料出库
					INNER JOIN Qp_PickingBill pb ON RF.PickingId = pb.ID
					INNER JOIN #GetManETypeId E ON E.TypeId = RF.ETypeId
					INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
					INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
					INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
					INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
					INNER JOIN #GetManPTypeId P ON rf.PTypeId = P.TypeId
					INNER JOIN #GetManKTypeId K ON pb.KTypeId = K.TypeId'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND B.RedWord = 0
								AND B.IfYearBill = 0'
IF @Wxjd = 0
	SET @SQL = @SQL + '			AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + '			AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + '			AND Bc.BillState = 4'
ELSE		
	SET @SQL = @SQL + '			AND 1 = 1'
	
IF @Bxzt = 0
	SET @SQL = @SQL + '			AND rf.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + '			AND rf.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + '			AND rf.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + '			AND rf.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + '			AND rf.Insurance = 4'
ELSE 
	SET @SQL = @SQL + '			AND 1 = 1'
	
IF @Xzzd = 0
	SET @SQL = @SQL + '			AND 1 = 2'

SET @SQL = @SQL + '
							UNION ALL 
							
						SELECT	B.BillNumberId,
								RF.PtypeID,
								RF.Qty AS Qty,
								Convert( NUMERIC(24, 10) ,RF.CostTotal) AS CostTotal, 
								Convert( NUMERIC(24, 10) ,RF.DiscountTotal) AS TaxTotal,
								CASE RF.Qty 
									WHEN 0
										THEN 0
									ELSE 
										Convert( NUMERIC(24, 10) ,RF.CostTotal/RF.Qty) 
								END as CostPrice,
								RF.DiscountPrice AS TaxPrice,
								RF.EtypeId as EtypeID,
								NULL AS KTypeID,		
								RF.Comment
						FROM Qp_ReceptionBill_FactUsePType RF
						INNER JOIN BillIndex B ON B.BillNumberId = RF.ReceptionBillnumberId
						INNER JOIN BillIndex_CarRepair Bc ON Bc.BillNumberId = RF.ReceptionBillnumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = RF.ETypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						INNER JOIN #GetManPTypeId P ON RF.PTypeId = P.TypeId'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND B.RedWord = 0
								AND B.IfYearBill = 0
								AND RF.Virtual = 1'
IF @Wxjd = 0
	SET @SQL = @SQL + '			AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + '			AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + '			AND Bc.BillState = 4'
ELSE		
	SET @SQL = @SQL + '			AND 1 = 1'
	
IF @Bxzt = 0
	SET @SQL = @SQL + '			AND RF.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + '			AND RF.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + '			AND RF.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + '			AND RF.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + '			AND RF.Insurance = 4'
ELSE 
	SET @SQL = @SQL + '			AND 1 = 1'
	
IF @Xzzd = 1
	SET @SQL = @SQL + '			AND 1 = 2'
	
IF @chvKTypeID <> '' OR @chvEtypeID <> ''
	SET @SQL = @SQL + '			AND 1 = 2'
	

	
SET @SQL = @SQL + '					
						UNION ALL
						
						SELECT	B.BillNumberId,
								QP.PtypeID,
								QP.Qty AS Qty,
								Convert( NUMERIC(24, 10) ,QP.GoodsCostTotal) AS CostTotal, 
								Convert( NUMERIC(24, 10) ,QP.DiscountTotal) AS TaxTotal,
								Convert( NUMERIC(24, 10) ,QP.GoodsCostPrice) AS CostPrice,
								Convert( NUMERIC(24, 10) ,QP.DiscountPrice) AS TaxPrice,
								QP.RepairManTypeID AS ETypeID,
								QP.KTypeID AS KTypeID,
								QP.Comment
						FROM QP_QuickRepairBill_PType QP
						INNER JOIN BillIndex B ON B.BillNumberId = QP.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON Bc.BillNumberId = QP.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = QP.RepairManTypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						INNER JOIN #GetManPTypeId P ON QP.PTypeId = P.TypeId
						INNER JOIN #GetManKTypeId K On K.TypeId = QP.KTypeid
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND B.RedWord = 0
								AND B.IfYearBill = 0'
						
IF @Wxjd = 9
	SET @SQL = @SQL + '			AND 1 = 1'
ELSE IF @Wxjd = 0
	SET @SQL = @SQL + '			AND Bc.Status = 0'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + '			AND Bc.Status = 1'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + '			AND Bc.Status = 2'
	
IF @Bxzt = 0
	SET @SQL = @SQL + '			AND QP.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + '			AND QP.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + '			AND QP.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + '			AND QP.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + '			AND QP.Insurance = 4'
ELSE 
	SET @SQL = @SQL + '			AND 1 = 1'

IF @Xzzd = 0
	SET @SQL = @SQL + '			AND 1 = 2'
ELSE 
	SET @SQL = @SQL + '			AND 1 = 1'

SET @SQL = @SQL + '						
						UNION ALL
						
						SELECT	B.BillNumberId,
								SR.PtypeID,
								SR.Qty AS Qty,
								Convert( NUMERIC(24, 10) ,SR.CostTotal) AS CostTotal, 
								Convert( NUMERIC(24, 10) ,SR.Total) AS TaxTotal,
								Convert( NUMERIC(24, 10) ,SR.CostTotal/SR.Qty) AS CostPrice,
								Convert( NUMERIC(24, 10) ,SR.Total/SR.Qty) AS TaxPrice,
								SR.EtypeId AS EtypeID,
								SR.KTypeID AS KTypeID,
								SR.Comment
						FROM Qp_SuccorBill_PType SR
						INNER JOIN BillIndex B ON B.BillNumberId = SR.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON Bc.BillNumberId = SR.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = SR.ETypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						INNER JOIN #GetManPTypeId P ON SR.PTypeId = P.TypeId
						INNER JOIN #GetManKTypeId K On K.TypeId = SR.KTypeid
						'
						
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
								AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
								AND B.RedWord = 0
								AND B.IfYearBill = 0 '
							
IF @Xzzd = 0
	SET @SQL = @SQL + '			AND 1 = 2'
ELSE 
	SET @SQL = @SQL + '			AND 1 = 1'
	
SET @SQL = @SQL + ')'

--print(@sql)
EXEC(@SQL)

DECLARE @SQL2 VARCHAR(MAX)

SET @SQL2 = '
				SELECT B.ifcheck,
						B.BillNumberId,
					   B.BillDate,
					   B.BillCode,
					   B.BillType,
					   Bc.ratypeid,
					   Bc.BillState,
					   B.Btypeid,
					   R.Ptypeid,
					   R.Qty,
					   R.CostPrice,
					   R.CostTotal,
					   R.TaxPrice,
					   B.stypeid,
					   R.TaxTotal,
					   R.TaxTotal-R.CostTotal AS MaoLi,
					   CASE WHEN ISNULL(-R.TaxTotal,0)=0 THEN 0 ELSE (-R.TaxTotal-(-R.CostTotal))/ISNULL(-R.TaxTotal,0)*100 END AS Maolilu, 
					   (SELECT fullname FROM employee E1 WHERE E1.typeid= R.etypeid) AS Efullname,  
					    B.DTypeId, 
						R.Comment,
						R.EtypeId,
						R.KTypeId
				FROM BillIndex B
				INNER JOIN BillIndex_CarRepair Bc ON B.BillNumberId = Bc.BillNumberId
				INNER JOIN #RESULT R ON B.BillNumberId = R.BillNumberId
				WHERE R.QTY <> 0
				AND R.PTypeId LIKE '+CHAR(39)+@chvPTypeID+'%'+CHAR(39)
				
SET @SQL2 = @SQL2 + '
				ORDER BY B.BillDate ASC,
					   B.BillCode ASC
					   '
						
--print(@sql2)
EXEC(@SQL2)
DROP TABLE #GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetManWciTypeId,#GetManPTypeId
drop table #RESULT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_RepairItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Qp_Web_RepairItems
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-04-20
	描述：接待登记查询
*/

CREATE PROCEDURE Qp_Web_RepairItems 
(
	@billnumberid VARCHAR(MAX)	--单据主表id
)
--@encode$--
AS
SET NOCOUNT ON
SELECT  Rb.RepairItemsTypeID AS typeid,
		Rb.StandardManHour,
		Rb.Total,
		CASE Rb.RepairProcess WHEN 1 THEN '未派工' WHEN 2 THEN '正在修理' WHEN 3 THEN '修理完毕' WHEN 4 THEN '停工' END AS RepairProcess ,
		CASE Rb.Insurance WHEN 0 THEN '正常' WHEN 1 THEN '保险' WHEN 2 THEN '三包' WHEN 3 THEN '返修' WHEN 4 THEN '赠送' END AS Insurance
		FROM Qp_ReceptionBill_RepairItems Rb
		WHERE Rb.BillNumberId=@billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_RepairItemsPerson]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_RepairItemsPerson]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：郑红霞
	日期：2011-5-24
	描述：查看维修项目的派工情况
	--d.FullName as departmentname,
	--q.UserCode as RepairUserCode,
                      q.FullName,
-------------------------------------------*/
CREATE PROCEDURE Qp_Web_RepairItemsPerson
(
    @BillNumberId  VARCHAR(max)     
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @SQL VARCHAR(3000)
	SET @SQL ='select 
                      q.TypeID as witypeid,
                      e.typeId as etypeid,
                      d.typeid as dtypeid,
                      qpp.CheckHour,
                      qpp.Total
                 from Billindex_CarRepair b 
                      inner join Qp_ReceptionBill_RepairItems qp on qp.BillNumberId=b.BillNumberId
                      inner join QP_RepairItems q on q.TypeID=qp.RepairItemsTypeID
                      inner join Qp_AttemperBill_RepairItemsPerson qpp on qpp.RepairItemsId=qp.ID
                      inner join BillIndex c on c.BillNumberId=b.BillNumberId
                      inner join employee e on e.typeId=qpp.ETypeId
                      inner join department d on d.typeid = e.DtypeID
                where b.BillNumberId='''+@BillNumberId+''''  
	EXEC (@sql)
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_RepairItemsQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_RepairItemsQuery]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










/*
 作者:Wang Wei
 时间:2010-9-20
 描述:查询维修项目
*/
CREATE          PROCEDURE QP_Web_RepairItemsQuery
( 
 @typeid	VARCHAR(8000)
)
--@encode$--
AS
SET NOCOUNT ON 

CREATE TABLE #Temp(typeid VARCHAR(100))
INSERT INTO #Temp SELECT * FROM dbo.f_split(@typeid,',') 

SELECT R.typeid,
	   R.usercode,
	   R.fullname,
	   R.standardmanhour
	FROM 	QP_RepairItems R
	INNER JOIN #Temp t ON LEFT(R.typeid,LEN(T.typeid))=t.typeid
	WHERE SonNum=0 
	
DROP TABLE #Temp
        

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_RepairLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_RepairLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-08-10
	描述：维修配件统计线性表
*/


CREATE PROCEDURE QP_web_RepairLine
(	
   @OperatorID		varchar(50),   
   @startdate		varchar(50), 
   @enddate			varchar(50),
   @chvDtypeID		varchar(4000),
   @chvEtypeID		varchar(4000),
   @wcitypeid		varchar(4000), --维修车辆信息档案ID
   @chvBtypeID		varchar(4000),
   @chvKTypeID		varchar(4000),
   @chvPTypeID		varchar(4000), --维修配件档案ID
   @Xzzd			int =9,			--虚增字段	
   @wxjd			int =9,			--维修进度
   @Bxzt			int =9,			--状态
   @STypeId			varchar(max)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------	
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--车牌号(不用控制权限范围)
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,00001)

CREATE TABLE #GetManPTypeId(TypeId varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

CREATE TABLE #GetManKTypeId(TypeId varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeID,4,@OperatorID)

DECLARE @SQL 		VARCHAR(8000),
		@SQL2 		VARCHAR(8000),
		@SonNum		INT		
	
SELECT @sonnum = sonnum FROM Ptype WHERE Typeid=@chvPTypeID	

--处理基本信息ID
IF @chvPTypeID = '00000' 
	SET @chvPTypeID = '%'
	
SET @SQL=' SELECT	MM.TypeID,
					MM.sonnum,
					ISNULL(SUM(Qty),0) as Qty,
					CASE WHEN ISNULL(SUM(Qty),0)=0 THEN 0 ELSE  ISNULL(SUM(TaxTotal),0)/ISNULL(SUM(Qty),1) END as TaxPrice,
					ISNULL(SUM(TaxTotal),0) as TaxTotal,
					CASE WHEN ISNULL(SUM(Qty),0)=0 THEN 0 ELSE  ISNULL(SUM(CostTotal),0)/ISNULL(SUM(Qty),1) END as CostPrice,
					ISNULL(SUM(CostTotal),0) as CostTotal,
					ISNULL(SUM(TaxTotal),0)-ISNULL(SUM(CostTotal),0) as Maoli,
					CASE WHEN ISNULL(SUM(TaxTotal),0)=0 THEN 0 ELSE  (ISNULL(SUM(TaxTotal),0)-ISNULL(SUM(CostTotal),0))/ISNULL(SUM(TaxTotal),1)*100 END  as maolilu
		   FROM		F_GetManPTypeAll('''+@OperatorID+''') MM  
		   LEFT JOIN (
		   
								
    		select	RF.PTypeID,
					sum(RF.Qty) as Qty,
					Convert( NUMERIC(24, 10) ,sum(RF.CostTotal)) as CostTotal,
					Convert( NUMERIC(24, 10) ,sum(RF.DiscountTotal)) as TaxTotal	
		    FROM Qp_ReceptionBill_FactUsePType RF		    
		    --维修单
		    INNER JOIN BillIndex B ON RF.ReceptionBillnumberId = B.BillNumberId
		    INNER JOIN Billindex_CarRepair bc ON B.BillNumberId = Bc.BillNumberId
		    --领料出库
		    INNER JOIN Qp_PickingBill pb ON RF.PickingId = pb.ID
		    INNER JOIN #GetManETypeId E ON E.TypeId = RF.ETypeId
		    INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
		    INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
		    INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
		    INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
		    INNER JOIN #GetManPTypeId P ON rf.PTypeId = P.TypeId
		    INNER JOIN #GetManKTypeId K ON pb.KTypeId = K.TypeId
		    '
		   
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 
						AND RF.Qty <> 0'
IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.BillState = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND RF.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND RF.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND RF.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND RF.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND RF.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
if @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2 '
	
SET @SQL = @SQL + ' GROUP BY RF.PTypeID
						UNION ALL

			select rb.PTypeID,
				   sum(rb.Qty) as Qty,
				   Convert( NUMERIC(24, 10) ,sum(rb.CostTotal)) as CostTotal,
				   Convert( NUMERIC(24, 10) ,sum(rb.DiscountTotal)) as TaxTotal	
			from Qp_ReceptionBill_FactUsePType rb
			inner join BillIndex b on b.BillNumberId = rb.ReceptionBillnumberId
			INNER JOIN Billindex_CarRepair bc ON b.BillNumberId = bc.BillNumberId
			INNER JOIN #GetManETypeId E ON E.TypeId = rb.ETypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
			INNER JOIN #GetManPTypeId P ON rb.PTypeId = P.TypeId'
	
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '	
						
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND rb.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND rb.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND rb.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND rb.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND rb.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'	
	
IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.BillState = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

if @Xzzd = 1
	SET @SQL = @SQL + ' AND 1 = 2'
if @chvKTypeID <> '' OR  @chvEtypeID <> ''
	SET @SQL = @SQL + ' AND 1 = 2'
SET @SQL = @SQL + ' AND rb.Virtual = 1
					GROUP BY rb.PTypeID'

SET @SQL = @SQL + '					
						UNION ALL
						
						SELECT	QP.PtypeID,
								QP.Qty AS Qty,'

IF @Wxjd = 0 OR  @Wxjd = 1
	SET @SQL = @SQL + ' 0 AS CostTotal,'
ELSE
	SET @SQL = @SQL + ' QP.GoodsCOstTOtal AS COstTOtal,'
	
SET @SQL = @SQL + '
								
								Convert( NUMERIC(24, 10) ,QP.discountTotal) AS TaxTotal
						FROM QP_QuickRepairBill_PType QP
						INNER JOIN BillIndex B ON B.BillNumberId = QP.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON Bc.BillNumberId = QP.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = QP.RepairManTypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManKTypeId K On K.TypeId = QP.KTypeid
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						INNER JOIN #GetManPTypeId P ON QP.PTypeId = P.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Wxjd = 9
	SET @SQL = @SQL + ' AND 1 = 1'
ELSE IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.Status = 0'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.Status = 1'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.Status = 2'
	
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND QP.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND QP.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND QP.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND QP.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND QP.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

IF @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

SET @SQL = @SQL + '						
						UNION ALL
						
						SELECT	SR.PtypeID,
								SR.Qty AS Qty,
								Convert( NUMERIC(24, 10) ,ISNULL(SR.CostTotal,0)) AS CostTotal, 
								Convert( NUMERIC(24, 10) ,SR.Total) AS TaxTotal
						FROM Qp_SuccorBill_PType SR
						INNER JOIN BillIndex B ON B.BillNumberId = SR.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON Bc.BillNumberId = SR.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = SR.ETypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManKTypeId K On K.TypeId = SR.KTypeid
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						INNER JOIN #GetManPTypeId P ON SR.PTypeId = P.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0'
						
IF @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

SET @SQL = @SQL + '
						)M ON LEFT(M.PtypeID,LEN(MM.TypeId)) = MM.TypeID
						WHERE MM.TypeId LIKE '''+@chvPTypeID+'%''
							  AND MM.SonNum = 0
							  AND (Qty <> 0
								   OR TaxTotal <> 0)
						GROUP BY MM.TypeId,
							  MM.UserCode,
							  MM.SonNum											
						ORDER BY MM.UserCode 
						'
--PRINT(@SQL)	
EXEC(@SQL)

DROP TABLE #GetManETypeId,#GetManDTypeId,#GetManBTypeId,#GetManSTypeId,#GetManWciTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_RepairList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_RepairList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-08-10
	描述：维修配件统计树型表
*/


CREATE PROCEDURE QP_web_RepairList
(	
   @OperatorID		varchar(50),   
   @startdate		varchar(50), 
   @enddate			varchar(50),
   @chvDtypeID		varchar(4000),
   @chvEtypeID		varchar(4000),
   @wcitypeid		varchar(4000), --维修车辆信息档案ID
   @chvBtypeID		varchar(4000),
   @chvKTypeID		varchar(4000),
   @chvPTypeID		varchar(4000), --维修配件档案ID
   @Xzzd			int =9,			--虚增字段	
   @wxjd			int =9,			--维修进度
   @Bxzt			int =9,			--状态
   @STypeId			varchar(max)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------	
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvEtypeID,3,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvBtypeID,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--车牌号(不用控制权限范围)
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,00001)

CREATE TABLE #GetManPTypeId(TypeId varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvPTypeID,1,@OperatorID)

CREATE TABLE #GetManKTypeId(TypeId varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvKTypeID,4,@OperatorID)

DECLARE @SQL 		VARCHAR(8000),
		@SQL2 		VARCHAR(8000),
		@SonNum		INT		


IF @chvPTypeID=''
	SET @chvPTypeID='00000'
	
SELECT @sonnum = sonnum FROM Ptype WHERE Typeid=@chvPTypeID	

SET @SQL=' SELECT	M.TypeID,
					M.sonnum,
					ISNULL(SUM(Qty),0) as Qty,
					CASE WHEN ISNULL(SUM(Qty),0)=0 THEN 0 ELSE  ISNULL(SUM(TaxTotal),0)/ISNULL(SUM(Qty),1) END as TaxPrice,
					ISNULL(SUM(TaxTotal),0) as TaxTotal,
					CASE WHEN ISNULL(SUM(Qty),0)=0 THEN 0 ELSE  ISNULL(SUM(CostTotal),0)/ISNULL(SUM(Qty),1) END as CostPrice,
					ISNULL(SUM(CostTotal),0) as CostTotal,
					ISNULL(SUM(TaxTotal),0)-ISNULL(SUM(CostTotal),0) as Maoli,
					CASE WHEN ISNULL(SUM(TaxTotal),0)=0 THEN 0 ELSE  (ISNULL(SUM(TaxTotal),0)-ISNULL(SUM(CostTotal),0))/ISNULL(SUM(TaxTotal),1)*100 END  as maolilu
		   FROM		F_GetManPTypeAll('''+@OperatorID+''') M  
		   LEFT JOIN (
		   
								
			  
    		select	RF.PTypeID,
					sum(RF.Qty) as Qty,
					Convert( NUMERIC(24, 10) ,sum(RF.CostTotal)) as CostTotal,
					Convert( NUMERIC(24, 10) ,sum(RF.DiscountTotal)) as TaxTotal	
		    FROM Qp_ReceptionBill_FactUsePType RF
		    --维修单
		    INNER JOIN BillIndex B ON RF.ReceptionBillnumberId = B.BillNumberId
		    INNER JOIN Billindex_CarRepair bc ON B.BillNumberId = Bc.BillNumberId
		    --领料出库
		    INNER JOIN Qp_PickingBill pb ON RF.PickingId = pb.ID
		    INNER JOIN #GetManETypeId E ON E.TypeId = RF.ETypeId
		    INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
		    INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
		    INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
		    INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
		    INNER JOIN #GetManPTypeId P ON rf.PTypeId = P.TypeId
		    INNER JOIN #GetManKTypeId K ON pb.KTypeId = K.TypeId
		    '
		   
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0
						AND RF.Qty <> 0 '
IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.BillState = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND RF.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND RF.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND RF.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND RF.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND RF.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
if @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2 '
	
SET @SQL = @SQL + ' GROUP BY RF.PTypeID'

	
SET @SQL = @SQL + '
						UNION ALL

			select rb.PTypeID,
				   sum(rb.Qty) as Qty,
				   Convert( NUMERIC(24, 10) ,sum(rb.CostTotal)) as CostTotal,
				   Convert( NUMERIC(24, 10) ,sum(rb.DiscountTotal)) as TaxTotal	
			from Qp_ReceptionBill_FactUsePType rb
			inner join BillIndex b on b.BillNumberId = rb.ReceptionBillnumberId
			INNER JOIN Billindex_CarRepair bc ON b.BillNumberId = bc.BillNumberId
			INNER JOIN #GetManETypeId E ON E.TypeId = rb.ETypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
			INNER JOIN #GetManPTypeId P ON Rb.PTypeId = P.TypeId'
	
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '	
						
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND rb.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND rb.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND rb.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND rb.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND rb.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'	

IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.BillState = 2'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.BillState = 3'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.BillState = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'
	
if @Xzzd = 1
	SET @SQL = @SQL + ' AND 1 = 2'
if @chvKTypeID <> ''OR @chvEtypeID <> ''
	SET @SQL = @SQL + ' AND 1 = 2'
SET @SQL = @SQL + ' AND rb.Virtual = 1
					GROUP BY rb.PTypeID'

SET @SQL = @SQL + '					
						UNION ALL
						
						SELECT	QP.PtypeID,
								QP.Qty AS Qty,'

IF @Wxjd = 0 OR  @Wxjd = 1
	SET @SQL = @SQL + ' 0 AS CostTotal,'
ELSE
	SET @SQL = @SQL + ' QP.GoodsCOstTOtal AS COstTOtal,'
	
SET @SQL = @SQL + '
								
								Convert( NUMERIC(24, 10) ,QP.discountTotal) AS TaxTotal
						FROM QP_QuickRepairBill_PType QP
						INNER JOIN BillIndex B ON B.BillNumberId = QP.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON Bc.BillNumberId = QP.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = QP.RepairManTypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManKTypeId K On K.TypeId = QP.KTypeid
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						INNER JOIN #GetManPTypeId P ON QP.PTypeId = P.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0 '
						
IF @Wxjd = 9
	SET @SQL = @SQL + ' AND 1 = 1'
ELSE IF @Wxjd = 0
	SET @SQL = @SQL + ' AND Bc.Status = 0'
ELSE IF @Wxjd = 1
	SET @SQL = @SQL + ' AND Bc.Status = 1'
ELSE IF @Wxjd = 2
	SET @SQL = @SQL + ' AND Bc.Status = 2'
	
IF @Bxzt = 0
	SET @SQL = @SQL + ' AND QP.Insurance = 0'
ELSE IF @Bxzt = 1
	SET @SQL = @SQL + ' AND QP.Insurance = 1'
ELSE IF @Bxzt = 2
	SET @SQL = @SQL + ' AND QP.Insurance = 2'
ELSE IF @Bxzt = 3
	SET @SQL = @SQL + ' AND QP.Insurance = 3'
ELSE IF @Bxzt = 4
	SET @SQL = @SQL + ' AND QP.Insurance = 4'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

IF @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

SET @SQL = @SQL + '						
						UNION ALL
						
						SELECT	SR.PtypeID,
								SR.Qty AS Qty,
								Convert( NUMERIC(24, 10) ,ISNULL(SR.CostTotal,0)) AS CostTotal, 
								Convert( NUMERIC(24, 10) ,SR.Total) AS TaxTotal
						FROM Qp_SuccorBill_PType SR
						INNER JOIN BillIndex B ON B.BillNumberId = SR.BillNumberId
						INNER JOIN BillIndex_CarRepair Bc ON Bc.BillNumberId = SR.BillNumberId
						INNER JOIN #GetManETypeId E ON E.TypeId = SR.ETypeId
						INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
						INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
						INNER JOIN #GetManKTypeId K On K.TypeId = SR.KTypeid
						INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
						INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
						INNER JOIN #GetManPTypeId P ON SR.PTypeId = P.TypeId
						'
SET @SQL = @SQL + '
						WHERE	B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND B.RedWord = 0
						AND B.IfYearBill = 0'
						
IF @Xzzd = 0
	SET @SQL = @SQL + ' AND 1 = 2'
ELSE 
	SET @SQL = @SQL + ' AND 1 = 1'

SET @SQL = @SQL + '
						)MM ON LEFT(MM.PtypeID,LEN(M.TypeId)) = M.TypeID'
						
IF @SonNum <> 0
	SET @SQL = @SQL + ' WHERE M.ParId = '''+@chvPTypeID+''''
ELSE						
	SET @SQL = @SQL + ' WHERE M.TypeId = '''+@chvPTypeID+''''
				
SET @SQL = @SQL + '		GROUP BY M.TypeID,M.sonnum,M.usercode  
						ORDER BY   M.usercode ASC  '
--PRINT(@SQL)	
EXEC(@SQL)

DROP TABLE #GetManETypeId,#GetManDTypeId,#GetManBTypeId,#GetManSTypeId,#GetManWciTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_RepairOperationQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_RepairOperationQuery]
GO

/**---------------------------------------------------------------**/
--作者：毛欣蓉
--日期：2010-08-12
--功能：维修业务查询
/**--------------------------------------------------------------**/

CREATE  PROCEDURE  Qp_Web_RepairOperationQuery
(	
	@OperatorID  varchar(100),
	@startdate   varchar(20)='',
	@enddate	 varchar(20)='',
	@ratypeid    varchar(8000)='', --车牌号
	@btypeid   	 varchar(8000)='',
	@dtypeid	 varchar(8000)='',
	@etypeid	 varchar(8000)='',
	@ktypeid	 varchar(8000)='',
	@status      int=1, --维修状态 -1为全部，0为在修 1为完工未结算 2为已结算
	@stypeid	 varchar(max)		--分支机构
)
--@encode$--
AS
set nocount on
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

------------多级权限检查 star t------------

create table #btype(typeid varchar(100))
create table #etype(typeid varchar(100))
create table #stock(typeid varchar(100))
create table #car(typeid varchar(100),PlateNumber varchar(200))
create table #dtype(typeid varchar(100))


--往来单位    
INSERT INTO #Btype(typeid) SELECT  typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)

--职员
INSERT INTO #Etype(typeid) SELECT  typeid FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)

--仓库
INSERT INTO #STOCK(typeid) SELECT  typeid FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)

--部门
INSERT INTO #Dtype(typeid) SELECT  typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)

--车牌号
IF @ratypeid<>''
	INSERT INTO #car(typeid,PlateNumber) SELECT typeid,PlateNumber from Qp_repairautoinfo a,(select * from  dbo.f_split(@ratypeid,',')) b where left(a.typeid,len(b.a))=b.a
ELSE
	INSERT INTO #car(typeid,PlateNumber) SELECT typeid,PlateNumber from Qp_repairautoinfo

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		DELETE FROM #STOCK WHERE typeid NOT IN (SELECT typeid FROM Stock WHERE STypeID IN (SELECT typeId FROM #GetManSTypeId))
	END
	
	
-------------多级权限检查 end --------------

--会员卡关联卡类型
create table #vipcard(vipcardid int,typename varchar(100),vipcardcode varchar(50))
INSERT INTO #vipcard(vipcardid,typename,vipcardcode) select c.vipcardid,s.typename,c.vipcardcode from nvipcardsign c,nvipcardset s where c.vipcardtypeid=s.vipcardtypeid

declare @sql varchar(8000)

SET @sql='SELECT 	i.billnumberid,
					i.billtype,
					i.billcode,
					i.billdate,
					i.btypeid,
					i.etypeid,
					i.ktypeid,
					i.dtypeid,
					i.totalmoney-i.PreferenceMoney as ysje,
					i.totalinmoney,
					case i.IfMulAccount when 1 then ''-99999'' else  ISNULL(i.atypeid,'''') end as atypeid,
					i.vipcardid,
					i.PreferenceMoney,
					i.explain,
					i.comment,
					arrearsmoney=i.totalmoney-i.PreferenceMoney-i.totalinmoney-i.completetotal,
					c.ratypeid,
					c.operationsort,
					--o.fullname as operationname,
					c.repairmode,
					--r.fullname as repairname,
					c.mileage,
					c.epibolyitem,
					c.otheritem,
					case c.status 
						when 0 then ''在修''
						when 1 then ''完工待结算''
						when 2 then ''已结算''
					else ''''
					end as state,
					c.manhourtotal,
					c.manhourtax,
					c.manhourtaxtotal,
					manhourtaxmoney=c.manhourtaxtotal-c.manhourtotal,
					c.ptypetotal,
					c.ptypetax,
					c.ptypetaxtotal,
					ptypetaxmoney=c.ptypetaxtotal-c.ptypetotal, 
					c.epibolytotal,
					c.othertotal,
					n.typename as viptype,
					n.vipcardcode,
					a.PlateNumber,
					i.completetotal
			FROM billindex i
				INNER JOIN billindex_carRepair c on i.billnumberid=c.billnumberid
				left JOIN #vipcard n on i.vipcardid=n.vipcardid
				INNER JOIN #car a on a.typeid=c.ratypeid 
				INNER JOIN #Dtype d on d.typeid=i.dtypeid '

IF NOT (@btypeid = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL=@SQL + ' INNER JOIN  #Btype BB ON  i.btypeid=BB.typeid '

IF NOT (@etypeid = '' AND @METypeId = '00001')
	SET @SQL=@SQL + ' INNER JOIN  #Etype E ON  i.ETypeID=E.typeid '

IF NOT (@ktypeid='' AND @MKTypeId='00000')
	SET @sql=@sql+' INNER JOIN #stock k on i.ktypeid=k.typeid'

IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON i.STypeId = S.TypeId '	

SET @sql=@sql+' WHERE i.billtype=178 and c.billtype=178 and i.ifyearbill<>1 AND i.RedWord=0'
	
DECLARE @State varchar(2)
SET @State=@status

--SET @status=cast(@status as varchar) 

IF @status<>-1
	SET @sql=@sql+' AND c.status ='+@State


IF @startdate<>''
	set @sql=@sql+' AND  i.billdate>='''+@startdate+''''
IF @enddate<>''
	set @sql=@sql+' AND i.billdate<='''+@enddate+''''

SET @sql=@sql + ' ORDER  by  i.BillDate DESC,i.billcode DESC'

--print(@sql)

exec(@sql)


drop table #btype,#etype,#stock,#Dtype,#car,#vipcard,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[QP_Web_SearchBase]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[QP_Web_SearchBase]
GO




/*
  功能：对基本信息的查询
  参数：
	  Mode : 1 库存商品 2 客户 3 供货商 4 内部职员 5 银行帐户 6 存货仓库 7 其他收入 8 其他费用 9 固定资产 10 货位档案 20 分支机构
	  UserCode,FullName 编号，名称的过滤条件
	  FiltVal 其他过滤条件
          PageNo 当前页号
	  PageCount 是否查页数
  返回：-1 Mode参数错误
  2002-4-10 加入商品的  2002-5-10 加入分支机构
*/
CREATE   PROCEDURE QP_Web_SearchBase
    (
      @MagEType VARCHAR(50),
      @Mode INT,
      @UserCode VARCHAR(3000) = '',
      @FullName VARCHAR(3000) = '',
      @PageNo INT = 1,
      @PageCount INT = 1,				-- PageCount 0:查询数据 1:查询页数
      @FiltVal VARCHAR(200) = '',
      @Barcode VARCHAR(3000) = '',      --条码查询
      @KtypeID VARCHAR(50) = '',
      @ParID VARCHAR(50) = '',
      @PageSize INT = 14,
      @StartDate VARCHAR(50) = '',
      @EndDate VARCHAR(50) = ''
    )
--@encode$--
AS 
    SET NOCOUNT ON




    CREATE TABLE #MainType ( TypeID VARCHAR(50) )


    DECLARE @SQLDB VARCHAR(20)
    DECLARE @SQLWHERE VARCHAR(6000)
    DECLARE @VPathMode INT
    IF @KtypeID = '00000' 
        SET @KtypeID = ''
    SELECT  @SQLWHERE = ' Where [sonnum]=0 '



    IF @Mode = 1 
        BEGIN
            INSERT  INTO #MainType ( typeid )
                    SELECT  Typeid
                    FROM    F_BaseGetManDetailPType(@MagEType)
            SELECT  @SQLDB = '[ptype]'
            SELECT  @SQLWHERE = @SQLWHERE + ' AND  [TypeId]<>''00000'' '
            SELECT  @VPathMode = 4
            IF @ParID = '00000' 
                SET @ParID = ''
        END
    ELSE 
        RETURN -1 
-- 加入编号，名称限制
/*
IF @Mode = 1
BEGIN
	IF @UserCode<>'' 
		SELECT @SQLWHERE = @SQLWHERE + @UserCode
	IF @FullName<>'' 
		SELECT @SQLWHERE = @SQLWHERE + @FullName
	IF @Barcode<>'' 
		SELECT @SQLWHERE = @SQLWHERE + @Barcode
END
ELSE*/
    BEGIN
        IF @UserCode <> '' 
		--IF @Mode=1  --商品加入条形码
			--SELECT @SQLWHERE = @SQLWHERE + ' AND ([UserCode] LIKE ''%' + RTRIM(@UserCode) +'%''  or [entrycode] like ''%'+RTRIM(@UserCode) +'%'')'
		--else
            SELECT  @SQLWHERE = @SQLWHERE + ' AND [UserCode] LIKE ''%'
                    + RTRIM(@UserCode) + '%'' '
        IF @FullName <> '' 
            SELECT  @SQLWHERE = @SQLWHERE + ' AND [FullName] LIKE ''%'
                    + RTRIM(@FullName) + '%'' '
        IF @Barcode <> '' 
            SELECT  @SQLWHERE = @SQLWHERE + ' AND [Entrycode] LIKE ''%'
                    + RTRIM(@Barcode) + '%'' '
    END

-- 加入权限限制
    DECLARE @MPTYPE VARCHAR(50)

--加多级权限后，去掉单级权限
    SET @MPTYPE = ''


    IF @MPTYPE <> '00000'
        AND @Mode = 1 
        SELECT  @SQLWHERE = @SQLWHERE + ' AND [TypeID] LIKE '''
                + RTRIM(@MPTYPE) + '%'' '

    DECLARE @re INT
    SET @re = 1
-- 多级权限范围表

    SELECT  @SQLWHERE = @SQLWHERE
            + ' AND TypeID in (select typeid from #MainType)'

--PRINT @SQLWHERE
    IF @PageCount = 1 
        BEGIN
            EXEC ( 'SELECT Count(*) AS PageCount FROM ' + @SQLDB + @SQLWHERE
                )
        END
    ELSE 
        BEGIN	-- 查询数据
            DECLARE @TOPNUMMIN INT

            DECLARE @SELTEXT VARCHAR(8000)
	-- 插入到临时表中
            DECLARE @TableName VARCHAR(40)
            DECLARE @BaseID VARCHAR(50)
            DECLARE @VPath VARCHAR(5000)
            SET @TableName = '##WebBasInfLie'
                + CONVERT(VARCHAR(2), DATEPART(dd, GETDATE()))
                + CONVERT(VARCHAR(2), DATEPART(hh, GETDATE()))
                + CONVERT(VARCHAR(2), DATEPART(m, GETDATE()))
                + CONVERT(VARCHAR(2), DATEPART(s, GETDATE()))
                + CONVERT(VARCHAR(4), DATEPART(ms, GETDATE()))
            SET @TOPNUMMIN = ( @PageNo - 1 ) * @PageSize--14
--	SET @SELTEXT='SELECT top 14 * FROM '+ @SQLDB + @SQLWHERE+' AND TypeID Not In (SELECT top '+STR(@TOPNUMMIN)+' TypeID FROM '+ @SQLDB + @SQLWHERE+' ORDER BY UserCode)  ORDER BY UserCode'

            SET @SELTEXT = 'SELECT top ' + CONVERT(VARCHAR(10), @PageSize)
                + ' *,dbo.F_GetPath(TypeID,'+LTrim(@VPathMode)+') AS VPath  FROM ' + @SQLDB
                + @SQLWHERE + ' AND TypeID Not In (SELECT top '
                + STR(@TOPNUMMIN) + ' TypeID FROM ' + @SQLDB + @SQLWHERE
                + ' ORDER BY UserCode)  ORDER BY UserCode'            
            IF @Mode = 1 -- 商品特殊处理
            BEGIN
            DECLARE @sql VARCHAR(3000)
			SElECT	@sql = '
				SELECT 
					serial= CASE WHEN p.sonnum>0 then '''' else CASE WHEN p.ifserial=''1'' then ''强制'' else ''—'' end  end,
					unitrate = CASE WHEN p.unit2='''' then p.unit1 else p.unit2+'
            + '''/''' + '+p.unit1+' + '''(1:'''
            + '+dbo.fn_sms_format(p.unitrate1)+' + ''')'' end,
					p.typeId,
				   p.ParId,
				   p.leveal,
				   p.sonnum,
				   p.soncount,
				   p.CanModify,
				   p.UserCode,
				   p.FullName,
				   p.[Name],
				   p.Standard,
				   p.[Type],
				   p.Area,
				   p.Unit1,
				   p.Unit2,
				   p.UnitRate1,
				   p.UnitRate2,
				   p.UsefulLifeMonth,
				   p.UsefulLifeDay,
				   p.Comment,
				  -- p.recPrice,
				  pp.RecAmgSTypeBuyPrice AS recPrice,-- 不再用ptype 表里面的最近进价了
				   p.deleted,
				   p.stopbuy,
				   (case ISNULL(p.stopbuy,0) when 0 THEN ''否'' ELSE ''是'' END) as stopbuytext,
				   p.ColorGroupID,
				   p.SizeGroupID,
				   p.EntryCode,
				   p.IfSerial,
				   p.PyCode,
				   p.SerialCount,
				   p.ValidDays,
				   p.XiWaMaxNumber,
				   p.DwgNo,
				   p.ImgURL,
					e.Brand,
					case e.import when ''1'' then ''进口'' when ''2'' then ''国产'' else '''' end as import,
					e.GeneralType,
					e.GeneralDwgNo,
					case e.[property] when ''0'' then ''范围配件'' when ''1'' then ''材料'' when ''2'' then ''低值易耗品'' end as [property],
					
					e.PackageQty,
					e.[Weight],
					e.TaxNumber,
					e.Taxrate,
					e.BTypeID,
					b.fullname AS BFullname,
					e.FcUnit,
					e.FcPrice,
					pp.PreBuyPrice1,
					pp.PreBuyPrice2,
					pp.PreBuyPrice3,
					pp.PreBuyPrice4,
					pp.PreBuyPrice5,
					pp.PreSalePrice1,
					pp.PreSalePrice2,
					pp.PreSalePrice3,
					pp.PreSalePrice4,
					pp.PreSalePrice5,
					pp.PreSalePrice6,
					pp.PreSalePrice7,
					pp.PreSalePrice8,
					pp.PreSalePrice9,
					pp.PreSalePrice10,
					pp.RetailPrice,
					pp.TopSalePrice,
					pp.TopBuyPrice,
					case when ((select COUNT(ImgURL) as iCOUNT from PType_Picture PC where PC.ptypeid=p.typeid)>0) then ''有'' else ''无''   end  ImgURL2,
					pp.LowSalePrice,
--					c.KTypeID,
--					c.FullName AS cFullname	,
					p.vpath			
				FROM (' + @SELTEXT +') AS  p
				LEFT JOIN QP_PType_Ext e ON p.typeid= e.ptypeid
				LEFT JOIN PType_Price pp ON p.typeid = pp.ptypeid
--				LEFT JOIN CargoSpace c ON p.typeid = c.ptypeid 
				LEFT JOIN dbo.btype b ON e.BTypeID= b.typeid  '

				EXEC(@sql)
--				WHERE p.parId=' + CHAR(39) + @parid + CHAR(39)
--            + @deleted
--            + ' AND p.typeid in (SELECT typeid FROM #ptype)  order by p.usercode'
            
--                EXEC
--                    ( 'SELECT serial= case when sonnum>0 then '''' else case when ifserial=''1'' then ''强制'' else ''—'' end  end,
--					unitrate = case when unit2='''' then unit1 else unit2+'
--                      + '''/''' + '+unit1+' + '''(1:'''
--                      + '+dbo.fn_sms_format(unitrate1)+' + ''')'' end,
--			* FROM ' + @TableName
--                    )
			END
            ELSE 
                EXEC ( 'SELECT p.* FROM (' + @SELTEXT +') AS p'
                    )
        END
    DROP TABLE #MainType
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (SELECT * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_SearchBillIndexAppData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_SearchBillIndexAppData]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_Web_SearchBillIndexAppData
(
	@chvBillType		VARCHAR(50),			-- 单据类型编号
	@chvStartDate		VARCHAR(50),			-- 开始日期
	@chvENDDate			VARCHAR(50),			-- 结束日期
	@chvBTypeID			VARCHAR(50)		= '',	-- 往来单位 ID 值
	@chvKTypeID			VARCHAR(50)		= '',	-- 仓库 ID 值
	@chvKTypeID1		VARCHAR(50)		= '',	-- 仓库 ID 值
	@chvETypeID			VARCHAR(50)		= '',	-- 经手人 ID 值
	@chvBillCode		VARCHAR(200)	= '',	-- 单据编号
	@chvOperatorID		VARCHAR(50)			,	-- 操作员 ID ( 作权限范围检查用 )
	@chvBillStyle		VARCHAR(50),			--单据特性（是否有往来单位、仓库、帐户、商品等）
	@flag				int	,					--其他的附带的条件(2为三包索赔单，1为保险理赔单，3为维修结算）
	@chvStypeid			VARCHAR(50),
	@RATypeID			VARCHAR(50)='',
	@IfAudit			VARCHAR(2)				-- 审核的类型   -1.审核不通过  0.待审核   1.审核通过  2.没有审核  兼容以前草稿  AuditingBill 中的IfAudit
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT, @chvMATypeID VARCHAR(50), @chvMBTypeID VARCHAR(50), @chvMBTypeID2 VARCHAR(50), @chvMETypeID VARCHAR(50), @chvMKTypeID VARCHAR(50), @chvMPTypeID VARCHAR(50), @chvMExpense VARCHAR(50), @chvMIncome VARCHAR(50), @chvMCapital VARCHAR(50), @chvMDtypeid VARCHAR(50), @chvMStypeid VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man VARCHAR(1000)
SET @SQL_Man = ''

-- 往来单位
IF @chvBillStyle LIKE '%B%' AND (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999')
BEGIN
	DECLARE @chvBTypeAll char(1)
	SET @chvBTypeAll = '0'
	SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'
	
	SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)
	DECLARE @SQL_ManB VARCHAR(100)
	SET @SQL_ManB = ' INNER JOIN #F_BaseGetManDetailBType B ON a.BTypeID = B.TypeID '
	
	IF @chvBTypeAll = '0'
	BEGIN
		IF @chvBillStyle LIKE '%B1%' AND @chvBillStyle LIKE '%B2%'
			SET @SQL_Man = @SQL_Man + @SQL_ManB
		ELSE IF @chvBillStyle LIKE '%B1%' AND @chvMBTypeID = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00001%'' '
		ELSE IF @chvBillStyle LIKE '%B2%' AND @chvMBTypeID2 = '-99999'	
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND B.TypeID LIKE ''00002%'' '			
	END
	ELSE
	BEGIN
		IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB
	END
END

-- 职员
IF @chvMETypeID = '-99999'
BEGIN
	DECLARE @lim VARCHAR(1)
	SET @lim = '0'
	IF @chvBillType = '17' or @chvBillType = '21'
		SELECT @lim = SUBSTRING(lim,439,1) FROM LoginUser WHERE ETypeID=@chvOperatorID

	IF @lim = '0'
	BEGIN
		SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
		SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
	END
END

-- 分支机构
IF   @chvMStypeid = '-99999' or @chvStypeid<>'' 
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailSType FROM F_GetAllManagerBaSETypeId(@chvStypeid,11,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

--部门
IF  @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaSETypeId('',9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END
-- ******** 权限范围单独处理 - END ********



DECLARE @re 			int,	-- 修改他人草稿的权限
		@Re467  		int,	-- 审核人可以审核他人草稿的权限
		@ReLimitPass 	int		-- 单据过帐权限
/*
	修改人：谢吉康
	日  期：2004-04-10
	描  述：有审核权限的人不受是否修改他人草稿权限的限制[修改成修改他人草稿权限优先]
*/

IF @chvOperatorID = '00001'
	SET @re = 0
ELSE
BEGIN	
	EXEC @Re467 = GP_CheckLimit @chvOperatorID,467  --查看他人业务草稿
	EXEC @re = GP_CheckLimit @chvOperatorID,135  --修改草稿
	IF @Re467=1 SET @re=1 
	IF @re = 1 AND (@IfAudit = 0 OR @IfAudit = 1)
	BEGIN
		IF @IfAudit=0
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSET
				WHERE BillType = @chvBillType AND IfUse = 1 AND LEFT(AuditingReason,1) <> 1)	-- 检查单据是否有审核流程
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSET A,AuditingFlowDetail B
					WHERE A.AuditingID = B.AuditingID AND A.BillType = @chvBillType AND A.IfUse = 1
					AND LEFT(A.AuditingReason,1) <> 1 AND B.ETypeID = @chvOperatorID)	-- 检测具体人针对具体的单据是否有审核流程
				BEGIN
					IF @Re467 = 0
						SET @re = 0
					ELSE
						SET @re = 1
				END
				ELSE
					IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowDetail B,AuditingFlowSET A
						WHERE A.AuditingID = B.AuditingID AND B.ETypeID = @chvOperatorID
						AND B.AuditingStep = 0 AND A.BillType = @chvBillType)	-- 检测用户是否具有特批人权限
					BEGIN
						IF @Re467 = 0
							SET @re = 0
						ELSE
							SET @re = 1
					END
			END
		END
		ELSE 
			SET @re = 0
	END
END

IF @re = 2 RETURN @re

CREATE TABLE  #TmpBil
(
	billnumberid INT
)

INSERT INTO #TmpBil 
SELECT DISTINCT ReceptionBillnumberId from Qp_ReceptionBill_FactUsePType where Insurance=2
UNION ALL
SELECT DISTINCT billnumberid from Qp_ReceptionBill_RepairItems where Insurance=2
UNION ALL
SELECT DISTINCT billnumberid from QP_QuickRepairBill_PType where Insurance=2
UNION ALL
SELECT DISTINCT billnumberid from QP_QuickRepairBill_RepairItems where Insurance=2


-- 声明 SQL 执行语句变量
DECLARE @SQL VARCHAR(3000)
SET @SQL = '
	SELECT	DISTINCT
			a.BillNumberID,
			a.BillDate,
			a.BillCode,
			a.TotalMoney,
			a.TotalInMoney,
			a.TotalQty,
			a.Comment,
			a.RedWord,
			a.BTypeID,
			a.KTypeID,
			a.ETypeID,
			a.ATypeID,
			a.stypeid,
			a.billtype
	FROM	BillIndex a 
			INNER JOIN Billindex_CarRepair cr ON a.billnumberid=cr.billnumberid ' +CHAR(10)+ @SQL_Man + ''
IF @IfAudit <> 2
	SET @SQL = @SQL + '
			INNER JOIN AuditingBill ab ON a.BillNumberID = ab.BillNumberID 
											AND ab.BillIndexType = 2 
											AND ab.IfAudit = ''' + @IfAudit + ''''
											
SET @SQL=@SQL +'
 	WHERE	a.BillDate >= ''' + @chvStartDate + ''' AND a.BillDate <= ''' + @chvENDDate + '''
			AND a.BillType IN(' + @chvBillType + ')
			AND Redword=0 
			AND (a.Ifcheck=''t'' OR a.BillType=195)
			'
IF @IfAudit = 2
	SET @SQL+='
			AND NOT EXISTS(
				SELECT	ab.BillNumberID 
				FROM	AuditingBill ab
				WHERE	a.BillNumberID = ab.BillNumberID 
						AND ab.BillIndexType = 2
						AND ab.IfAudit IN (''0'',''-1'')
			)
			'				
IF @flag=1 
BEGIN
	SET @SQL=@SQL + ' AND a.Draft = 0 
					  AND cr.InsuranceStatus=1 '
	SET @Sql=@sql+' AND ((a.billtype=195 and cr.billstate=4) OR a.billtype=178)'
	SET @sql=@sql+'  and cr.InsuranceStatus<>2   '
END
IF @flag=3
	SET @sql=@sql+' AND cr.billstate=3'
IF @flag=2
BEGIN
	SET @SQl=@sql+' AND ((a.billtype=195 and cr.billstate=4) OR a.billtype=178) AND a.billnumberid in (SELECT billnumberid from #TmpBil) '
	SET @sql=@sql+' And cr.CounterClaimStatus<>2 '
END


IF @chvBTypeID <> '' SET @SQL = @SQL + ' AND a.BTypeID=''' + @chvBTypeID + ''''
IF @chvETypeID <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @chvETypeID + ''''
IF @chvKTypeID <> '' SET @SQL = @SQL + ' AND a.KTypeID=''' + @chvKTypeID + ''''
IF @chvKTypeID1 <> '' SET @SQL = @SQL + ' AND a.KTypeID2=''' + @chvKTypeID1 + ''''
IF @RATypeID <> '' SET @SQL = @SQL + ' AND cr.RATypeID = ''' + @RATypeID + ''''

IF @chvBillCode <> ''	-- 单据编号
	SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @chvBillCode + '%'' '
SET @SQL = @SQL + '
	ORDER BY a.BillDate DESC, a.BillCode'

--PRINT @SQL
EXEC(@SQL)

IF @chvBillStyle LIKE '%B%' AND (@chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999') DROP TABLE #F_BaseGetManDetailBType
IF @chvBillStyle LIKE '%K%' AND @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMStypeid = '-99999' or @chvStypeid<>''  DROP TABLE #F_BaseGetManDetailSType
IF @chvMDtypeid = '-99999' DROP TABLE #F_BaseGetManDetailDType
DROP TABLE #TmpBil

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_SearchOneRaCarpa]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_SearchOneRaCarpa]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		维修项目树形选择
-- 作    者：		蔡志成
-- 创建时间：		2010-07-12
-- ========================================================================
CREATE  PROCEDURE QP_Web_SearchOneRaCarpa
(
	@chvQueryType		varchar(50),		-- 查询的类型
	@chvParid			varchar(50),		-- 节点的父亲节点	
	@chvPOS				varchar(500) = '',	-- SearchOne 模糊查询的 FullName 或 UserCode
	@intPageNo			int = '',			-- 当前查询的页码
	@intPageSize		int = '',			-- 每页的显示记录数
	@chrRowsReturn		char(1) = '',		-- 是否计算记录总数，1 为计算 ( 只返回记录总数 )
	@chvOperatorID		varchar(50),		-- 操作员 ID（作权限范围检查用）
	@intRowCount		int = 0 output		-- 返回总记录数
)
--@encode$--
AS
SET NOCOUNT ON 

IF @chvParid = '' SET @chvParid = '00000'
SELECT	IDENTITY(INT,1,1) AS AutoID,
		a.*,
		a.PlateNumber AS FullName,
		b.FullName AS bfullname,
		B1.FullName AS BaoxianBfullname,
		b.Price AS prePrice,
		c.ManHourRate,
		c.FullName AS ChargingName,
		d.Fullname AS AutotypeName
INTO	#QP_RepairAutoInfo
FROM	QP_RepairAutoInfo a
LEFT JOIN dbo.btype b ON a.BTypeID=b.typeId
LEFT JOIN dbo.btype b1 ON a.BaoxianBtypeid=b1.typeId
LEFT JOIN QP_ChargingStandards c ON a.ChargingStandardsID = c.[ID]
LEFT JOIN QP_RepairAutoType d ON a.RepairAutoTypeID = d.TypeID
WHERE	a.TypeID <> '00000'
		and (@chvPOS <> '' AND a.SonNum = 0 AND (a.PlateNumber LIKE '%' + @chvPOS + '%' OR a.PYCode LIKE '%' + @chvPOS + '%'))
		OR (@chvPOS = '' AND a.Parid = @chvParid)
ORDER BY a.PlateNumber

SET @intRowCount = @@ROWCOUNT
SELECT * FROM #QP_RepairAutoInfo WHERE AutoID > (@intPageNo-1)*@intPageSize AND AutoID <= @intPageNo*@intPageSize

DROP TABLE #QP_RepairAutoInfo

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_SearchOneRiCarpa]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_SearchOneRiCarpa]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		维修项目树形选择
-- 作    者：		蔡志成
-- 创建时间：		2010-07-12
-- ========================================================================
CREATE   PROCEDURE QP_Web_SearchOneRiCarpa
(
	@chvIsMult			varchar(1) = '1',	-- 0：线性；1：树型
	@chvQueryType		varchar(50),		-- 查询的类型
	@chvParid			varchar(50),		-- 节点的父亲节点	
	@chvPOS				varchar(500) = '',	-- SearchOne 模糊查询的 FullName 或 UserCode 或 PyCode
	@intPageNo			int = '',			-- 当前查询的页码
	@intPageSize		int = '',			-- 每页的显示记录数
	@chrRowsReturn		char(1) = '',		-- 是否计算记录总数，1 为计算 ( 只返回记录总数 )
	@chvVipCardID		VARCHAR(10),
	@chvPageDiscount	 NUMERIC(24, 10) ,
	@decManhouresrate	 NUMERIC(24, 10) ,
	@chvOperatorID		varchar(50),		-- 操作员 ID（作权限范围检查用）
	@intRowCount		int = 0 output		-- 返回总记录数
)
--@encode$--
AS
SET NOCOUNT ON 
	
DECLARE @chvSQLWhere varchar(8000)
DECLARE @chvSQL varchar(8000)
DECLARE @TempTable varchar(50)

SET @chvSQLWhere = ''
SET @chvSQL = ''

IF @chvParid = '' SET @chvParid = '00000'
--如果页面没有录入会员卡或已经录入表头扣率将不考虑会员卡信息直接计算，扣率带入表头扣率
IF @chvVipCardID = '' OR @chvPageDiscount <> 1
BEGIN
	SELECT	IDENTITY(INT,1,1) AS AutoID,
			a.TypeID ,
          a.ParID ,
          a.Leveal ,
          a.SonCount ,
          a.SonNum ,
          a.UserCode ,
          a.FullName ,
          a.ItemType ,
          a.StandardManHour ,
          a.CheckHour ,
          a.StandardPrice ,
          a.TopPrice ,
          a.LowPrice ,
          a.ChargeMode ,
          a.RepairAutoTypeID ,
          a.MaintainDays ,
          a.Comment ,
          a.XiWaMaxNumber ,
          a.MaintainMileage ,
          a.UserDefine1 ,
          a.UserDefine2 ,
          a.UserDefine3 ,
          a.UserDefine4 ,
          a.UserDefine5 ,
          a.PyCode,
			CASE a.ItemType WHEN '0' THEN '维修项目' WHEN '1' THEN '保养项目' END AS Itemtypename,
			CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour,2) WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END AS manhourexpense,
			@chvPageDiscount AS discount,
			CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour*@chvPageDiscount,2) WHEN 1 THEN ROUND(a.StandardPrice*@chvPageDiscount,2) WHEN 2 THEN ROUND(a.TopPrice*@chvPageDiscount,2) WHEN 3 THEN ROUND(a.LowPrice*@chvPageDiscount,2) END AS discountmanhourexpense,
			CASE a.ChargeMode WHEN 0 THEN '按工时' WHEN 1 THEN '标准价' WHEN 2 THEN '最高价' WHEN 3 THEN '最低价' END AS chargemodename,
			0 AS vipcutofftype
	INTO	#QP_RepairItems 
	FROM	QP_RepairItems a
	WHERE	((@chvPOS <> '' AND a.SonNum = 0 AND (a.UserCode LIKE '%' + @chvPOS + '%' OR a.FullName LIKE '%' + @chvPOS + '%' OR a.PyCode LIKE '%' + @chvPOS + '%'))
			OR (@chvPOS = '' AND @chvIsMult = '1' AND a.Parid = @chvParid)
			OR (@chvPOS = '' AND @chvIsMult = '0' AND a.SonNum = 0)) AND a.TypeID<>'00000'
	ORDER BY a.UserCode

	SET @intRowCount = @@ROWCOUNT
	SELECT * FROM #QP_RepairItems WHERE AutoID > (@intPageNo-1)*@intPageSize AND AutoID <= @intPageNo*@intPageSize
	
	DROP TABLE #QP_RepairItems
	RETURN
END
ELSE
BEGIN
	--得到会员优惠信息
	DECLARE @intDiscountType int, @decItemDiscount  NUMERIC(24, 10) 
	SET @intDiscountType = 1
	SELECT TOP 1 @intDiscountType = Value FROM Userconfig WHERE ConfigName = 'RepairItemsDiscountType'

	--得到该会员卡的项目折扣
	SELECT	TOP 1 @decItemDiscount = 1
	FROM	nVipCardSet a
	WHERE	a.VipCardTypeID = (SELECT TOP 1 VipCardTypeID FROM nVipCardSign WHERE VipCardID = @chvVipCardID)

	SELECT  a.* INTO #temp_price 
	FROM 
	(
		--优先选择限次修项目
		SELECT  a.VipCardID,a.VipCardCode,a.VipCardTypeID,b.RepairItemsTypeID,
				b.VIPPrice AS discountmanhourexpense,1 AS discount,1 AS flag,1 AS counts
		FROM    nVipCardSign a INNER JOIN QP_nVipCardSign_RepairItems b ON a.VipCardID = b.VipCardID
		WHERE	b.AllowUsedTimes > 0 AND a.VipCardID = @chvVipCardID
		UNION ALL 
		--再选择特价维修项目
		SELECT  a.VipCardID,a.VipCardCode,a.VipCardTypeID,b.RepairItemsTypeID,
				--会员价优惠的话直接取会员价
				CASE @intDiscountType WHEN 1 THEN b.VIPPrice ELSE 0 END AS discountmanhourexpense, 
				--折扣优惠直接取折扣
				CASE @intDiscountType WHEN 2 THEN b.Discount ELSE 1 END AS discount,
				2 AS flag,1 AS counts
		FROM    nVipCardSign a INNER JOIN QP_nVipCardSet_RepairItems b ON a.VipCardTypeID = b.VipCardTypeID
		WHERE b.RepairItemsType = 1 AND a.VipCardID = @chvVipCardID
	) a 

	UPDATE #temp_price SET #temp_price.counts = b.counts
	FROM #temp_price a LEFT JOIN 
	(
		SELECT	RepairItemsTypeID,VipCardID,COUNT(1) AS counts 
		FROM	#temp_price
		GROUP BY RepairItemsTypeID,VipCardID
	) b ON a.RepairItemsTypeID = b.RepairItemsTypeID AND a.VipCardID = b.VipCardID

	--如有限次修项目则删除特价项目
	DELETE #temp_price WHERE flag > 1 AND counts > 1

	--录入会员卡后将根据会员卡信息带入扣率等信息
	SELECT	IDENTITY(INT,1,1) AS AutoID,
			a.*,
			CASE a.ItemType WHEN '0' THEN '维修项目' WHEN '1' THEN '保养项目' END AS Itemtypename,
			CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour,2) WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END AS manhourexpense,		   
			CASE c.flag 
				--当该项目为限次项目时  扣率＝折后工时费/工时费
				WHEN 1 THEN	--工时费为0时，扣率＝1
					CASE (CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour,2) WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END) 
						WHEN 0 THEN 1 
						ELSE ROUND(c.discountmanhourexpense/(CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour,2) WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END) ,2)
					END 
				--当该项目为特价项目时
				WHEN 2 THEN 
					CASE @intDiscountType 
						WHEN 1 THEN
							CASE (CASE a.ChargeMode WHEN 0 THEN @decManhouresrate*a.StandardManHour WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END) 
								WHEN 0 THEN 1 
								ELSE ROUND(c.discountmanhourexpense/(CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour,2) WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END) ,2)
							END 
						ELSE c.discount
				    END
				--既不是特价项目又不是限次项目时取项目折扣				 
				ELSE @decItemDiscount
			END AS discount,
			CASE c.flag 
				--当该项目为限次项目时 工时费＝项目设定工时费，折后工时费＝会员价
				WHEN 1 THEN c.discountmanhourexpense
				--当该项目为特价项目时
				WHEN 2 THEN
					CASE @intDiscountType
						WHEN 1 THEN c.discountmanhourexpense
						ELSE ROUND(c.discount* (CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour,2) WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END),2)
				    END
				--既不是特价项目又不是限次项目时取项目折扣				 
				ELSE ROUND(@decItemDiscount*(CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour,2) WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END),2)
			END AS discountmanhourexpense,
			CASE a.ChargeMode WHEN 0 THEN '按工时' WHEN 1 THEN '标准价' WHEN 2 THEN '最高价' WHEN 3 THEN '最低价' END AS chargemodename,
			c.flag AS vipcutofftype
	INTO	#QP_RepairItems1
	FROM	QP_RepairItems a
	LEFT JOIN #temp_price c ON a.TypeID = c.RepairItemsTypeID
	WHERE	(@chvPOS <> '' AND a.SonNum = 0 AND typeid<>'00000' and  (a.UserCode LIKE '%' + @chvPOS + '%' OR a.FullName LIKE '%' + @chvPOS + '%' OR a.PyCode LIKE '%' + @chvPOS + '%'))
			OR (@chvPOS = '' AND @chvIsMult = '1' AND a.Parid = @chvParid) OR (@chvPOS = '' AND @chvIsMult = '0' AND a.SonNum = 0)
	ORDER BY a.UserCode

	SET @intRowCount = @@ROWCOUNT
	SELECT * FROM #QP_RepairItems1 WHERE AutoID > (@intPageNo-1)*@intPageSize AND AutoID <= @intPageNo*@intPageSize
	
	DROP TABLE #QP_RepairItems1
	RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_web_SerchHistoryOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_web_SerchHistoryOrder]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：郑红霞
	日期：2011-06-13
	描述：查询汽车历史用料
-------------------------------------------*/
CREATE PROCEDURE QP_web_SerchHistoryOrder
(
   @BeginDate  VARCHAR(20),  --开始时期
   @EndDate    VARCHAR(20),  --结束时期
   @RAtypeId      VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @str VARCHAR(MAX)
	SET @str='SELECT F.BillNumberId,
	           b.BillCode,
               F.ID,
               b.BillDate,
               p.UserCode,
               p.FullName pname,
               p.DwgNo,
               -(I.qty) as qty,
               I.Discount,
               I.Price,
              -(I.Total) as Total,
               -(I.TaxTotal-I.Total) AS Tax,
               I.SalePrice*I.Discount as discountprice,
              -(I.SaleTotal * I.Discount) as discounttotal,
               I.CostPrice,
               -(I.CostTotal) as CostTotals,
              (I.SalePrice*I.Discount)-I.CostTotal AS maoli,
               F.Insurance,
               F.Comment,
               s.FullName stockname,
               e.FullName username
          from Qp_ReceptionBill_FactUsePType F
               inner join  BillIndex b on F.ReceptionBillnumberId=b.BillNumberId
               inner join InOutstocktable i on i.ID=F.PickingId
               inner join ptype p on p.typeId=F.PTypeID
               inner join stock s on s.typeId=b.Stypeid
               inner join employee e on e.typeId = F.ETypeID 
         where F.ReceptionBillnumberId in
               ((select BillNumberId from Billindex_CarRepair where
               RATypeID=(SELECT TypeID FROM QP_RepairAutoInfo WHERE PlateNumber = '''+ @RATypeID+''') 
          and  BillDate>='''+@BeginDate+''' and BillState=4 and BillDate<='''+@EndDate+'''))'
	EXEC (@str)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO            



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_ShowPriceinfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_ShowPriceinfo]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/****
 Author：Wang Wei
 DateTime： 2010-8-9
 Description：查看选中商品的物价信息
***/

CREATE  PROCEDURE QP_Web_ShowPriceinfo
(
	@OperatorID 	varchar(100),
	@ptypeid 		VARCHAR(8000),--商品ID
	@ktypeId		VARCHAR(100),
	@Btypeid 		VARCHAR(100),
	@BillType		NUMERIC(18,0),
	@stypeid		varchar(100)
)

--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------

/*判断有没有启用分支机构价格*/
DECLARE @priceType int
set @priceType=(select top 1 pricetype from stype where typeid=@stypeid)

/*该仓库的成本均价*/

DECLARE @Cost  NUMERIC(24, 10) 
SELECT @Cost=CAST(CASE 
			WHEN ISNULL(s.qty,0) = 0 THEN 0
			ELSE (s.total/s.qty)
			END AS  NUMERIC(24, 10) )
FROM goodsstocks s 
WHERE PtypeId=@ptypeid AND Ktypeid=@ktypeId

/*最近进价*/
DECLARE @recprice    NUMERIC(24, 10) 


/*预设售价,预设进价*/
DECLARE @presaleprice1  NUMERIC(24, 10) , @presaleprice2  NUMERIC(24, 10) ,@presaleprice3  NUMERIC(24, 10) ,@presaleprice4  NUMERIC(24, 10) ,
		@presaleprice5  NUMERIC(24, 10) ,@presaleprice6  NUMERIC(24, 10) ,@presaleprice7  NUMERIC(24, 10) ,@presaleprice8  NUMERIC(24, 10) ,
		@presaleprice9  NUMERIC(24, 10) ,@presaleprice10  NUMERIC(24, 10) ,
		@prebuyprice1  NUMERIC(24, 10) ,@prebuyprice2  NUMERIC(24, 10) ,@prebuyprice3  NUMERIC(24, 10) ,@prebuyprice4  NUMERIC(24, 10) ,
		@prebuyprice5  NUMERIC(24, 10) ,@retailprice  NUMERIC(24, 10) ,@topsaleprice  NUMERIC(24, 10) ,@LowSalePrice  NUMERIC(24, 10) 	
		 
IF @priceType=1 and @stypeid<>''
begin
	SELECT 	@prebuyprice1=isnull(pp.PreBuyPrice1,0),
		@prebuyprice2=isnull(pp.PreBuyPrice2,0),
		@prebuyprice3=isnull(pp.PreBuyPrice3,0),
		@prebuyprice4=isnull(pp.PreBuyPrice4,0),
		@prebuyprice5=isnull(pp.PreBuyPrice5,0),
		@presaleprice1=isnull(pp.PreSalePrice1,0),
		@presaleprice2=isnull(pp.PreSalePrice2,0),
		@presaleprice3=isnull(pp.PreSalePrice3,0),
		@presaleprice4=isnull(pp.PreSalePrice4,0),
		@presaleprice5=isnull(pp.PreSalePrice5,0),
		@presaleprice6=isnull(pp.PreSalePrice6,0),
		@presaleprice7=isnull(pp.PreSalePrice7,0),
		@presaleprice8=isnull(pp.PreSalePrice8,0),
		@presaleprice9=isnull(pp.PreSalePrice9,0),
		@presaleprice10=isnull(pp.PreSalePrice10,0),
		@retailprice=isnull(pp.RetailPrice,0),
		@topsaleprice=isnull(pp.TopSalePrice,0),
		@LowSalePrice=isnull(pp.LowSalePrice,0)
	FROM PType_STypePrice pp
	WHERE PTypeID=@ptypeid and stypeid=@stypeid
end	
else
begin	
	--SELECT TOP 1 @recprice=recprice FROM ptype  WHERE typeid=@ptypeid
	SELECT 	@prebuyprice1=pp.PreBuyPrice1,
			@prebuyprice2=pp.PreBuyPrice2,
			@prebuyprice3=pp.PreBuyPrice3,
			@prebuyprice4=pp.PreBuyPrice4,
			@prebuyprice5=pp.PreBuyPrice5,
			@presaleprice1=pp.PreSalePrice1,
			@presaleprice2=pp.PreSalePrice2,
			@presaleprice3=pp.PreSalePrice3,
			@presaleprice4=pp.PreSalePrice4,
			@presaleprice5=pp.PreSalePrice5,
			@presaleprice6=pp.PreSalePrice6,
			@presaleprice7=pp.PreSalePrice7,
			@presaleprice8=pp.PreSalePrice8,
			@presaleprice9=pp.PreSalePrice9,
			@presaleprice10=pp.PreSalePrice10,
			@retailprice=pp.RetailPrice,
			@topsaleprice=pp.TopSalePrice,
			@LowSalePrice=pp.LowSalePrice
	FROM PType_Price pp
	WHERE PTypeID=@ptypeid
end
if @stypeid<>''
	SELECT TOP 1 @recprice=recprice FROM PType_STypePrice  WHERE ptypeid=@ptypeid  and stypeid=@stypeid
--print(@recprice)
DECLARE @rec INT,@b1 INT,@b2 INT,@b3 INT ,@b4 INT ,@b5 INT,@s1 INT ,@s2 INT ,@s3 INT,@s4 INT,
		@s5 INT ,@s6 INT ,@s7 INT ,@s8 INT,@s9 INT ,@s10 INT ,@retail INT ,@top INT ,@lows INT 
IF @OperatorID='00001'
BEGIN
	SELECT @rec=0,@b1 =0,@b2=0,@b3 =0 ,@b4 =0 ,@b5=0,@s1 =0 ,@s2 =0 ,@s3=0,@s4=0,
		@s5=0 ,@s6=0 ,@s7=0 ,@s8=0,@s9=0 ,@s10=0 ,@retail=0 ,@top=0 ,@lows=0 
END
ELSE
BEGIN	
	EXEC @rec=GP_CheckLimit @OperatorID, 166
	EXEC @b1=GP_CheckLimit @OperatorID, 703
	EXEC @b2=GP_CheckLimit @OperatorID, 704
	EXEC @b3=GP_CheckLimit @OperatorID, 705
	EXEC @b4=GP_CheckLimit @OperatorID,706
	EXEC @b5=GP_CheckLimit @OperatorID,707
	EXEC @s1=GP_CheckLimit @OperatorID, 219
	EXEC @s2=GP_CheckLimit @OperatorID, 220
	EXEC @s3=GP_CheckLimit @OperatorID, 221
	EXEC @s4=GP_CheckLimit @OperatorID, 222
	EXEC @s5=GP_CheckLimit @OperatorID, 697
	EXEC @s6=GP_CheckLimit @OperatorID, 698
	EXEC @s7=GP_CheckLimit @OperatorID, 699
	EXEC @s8=GP_CheckLimit @OperatorID, 700
	EXEC @s9=GP_CheckLimit @OperatorID, 701
	EXEC @s10=GP_CheckLimit @OperatorID, 702
	EXEC @retail=GP_CheckLimit @OperatorID, 708
	EXEC @top=GP_CheckLimit @OperatorID, 709
	EXEC @lows=GP_CheckLimit @OperatorID, 710
END


CREATE TABLE #Result(Sid INT IDENTITY(1,1),explain VARCHAR(400),col VARCHAR(100), bind  NUMERIC(24, 10) )
IF @rec=0
	INSERT INTO #Result VALUES('该仓库成本均价','cost',@Cost)	
IF @s1=0
	INSERT INTO #Result VALUES('预设售价1','presaleprice1',@presaleprice1)
IF @s2=0
	INSERT INTO #Result VALUES('预设售价2','presaleprice2',@presaleprice2)
IF @s3=0
	INSERT INTO #Result VALUES('预设售价3','presaleprice3',@presaleprice3)
IF @s4=0
	INSERT INTO #Result VALUES('预设售价4','presaleprice4',@presaleprice4)
IF @s5=0
	INSERT INTO #Result VALUES('预设售价5','presaleprice5',@presaleprice5)
IF @s6=0
	INSERT INTO #Result VALUES('预设售价6','presaleprice6',@presaleprice6)
IF @s7=0
	INSERT INTO #Result VALUES('预设售价7','presaleprice7',@presaleprice7)
IF @s8=0
	INSERT INTO #Result VALUES('预设售价8','presaleprice8',@presaleprice8)
IF @s9=0
	INSERT INTO #Result VALUES('预设售价9','presaleprice9',@presaleprice9)
IF @s10=0
	INSERT INTO #Result VALUES('预设售价10','presaleprice10',@presaleprice10)
IF @retail=0
	INSERT INTO #Result VALUES('零售价','retailprice',@retailprice)
IF @top=0
	INSERT INTO #Result VALUES('最高售价','topsaleprice',@topsaleprice)
IF @lows=0
	INSERT INTO #Result VALUES('最低售价','lowsaleprice',@LowSalePrice)
IF @b1=0
	INSERT INTO #Result VALUES('预设进价1','prebuyprice1',@prebuyprice1)
IF @b2=0
	INSERT INTO #Result VALUES('预设进价2','prebuyprice2',@prebuyprice2)
IF @b3=0
	INSERT INTO #Result VALUES('预设进价3','prebuyprice3',@prebuyprice3)
IF @b4=0
	INSERT INTO #Result VALUES('预设进价4','prebuyprice4',@prebuyprice4)
IF @b5=0
	INSERT INTO #Result VALUES('预设进价5','prebuyprice5',@prebuyprice5)
IF @rec=0		
	INSERT INTO #Result VALUES('最近进价','recprice',@recprice)

IF (@BillType=34 OR @BillType=144 OR @BillType=301 OR @BillType=185) AND @rec=0	
BEGIN
	DECLARE @Buyprice  NUMERIC(24, 10) 
	SELECT @Buyprice=CostPrice FROM PriceTrack WHERE BtypeID=@Btypeid AND PtypeID=@ptypeid AND Stypeid=@stypeid
	INSERT INTO #Result VALUES('该往来单位最近采购价','buyprice',@Buyprice)
END
IF @BillType=11 OR @BillType=140 OR @BillType=300 OR @BillType=184 OR @BillType=191
BEGIN
	DECLARE @Saleprice  NUMERIC(24, 10) 
	SELECT @Saleprice=SalePrice FROM PriceTrack WHERE BtypeID=@Btypeid AND PtypeID=@ptypeid AND Stypeid=@stypeid
	INSERT INTO #Result VALUES('该往来单位最近销售价','saleprice',@Saleprice)
END

SELECT * FROM #Result

DROP TABLE #Result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_SuccorBillIndexQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_SuccorBillIndexQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	查询救援单草稿index
-- 时间：	2011-05-04
-- 作者：	赵斌

-- ========================================================================
CREATE PROCEDURE Qp_Web_SuccorBillIndexQuery
(
	@BillNumberID	varchar(100)	-- 单据编号
)
--@encode$--

AS
SET NOCOUNT ON 

SELECT	B.BillNumberId,			
		B.BillDate,				--单据日期
		B.BillCode,				--单据编号
		B.etypeid,				--主修人id
		
		B.Stypeid,				--分支机构id
		B.DTypeId,				--部门	
		B.Comment,				--摘要
		B.explain,				--说明
		B.btypeid,				--往来单位id
		e.FullName as efullname,				--主修人
		RA.PlateNumber AS rafullname,			--车牌号
		
		bt.FullName AS bfullname,				--往来单位
		
		s.FullName AS sfullname,				--分支机构
		D.FullName AS dfullname,				--部门
		
		Bc.ReceptionId,							--接电人id
		e2.FullName AS efullname2,				--接电人
		
		Bc.RATypeID,			--车辆信息
		Bc.InPriceType,			--收费标准
			
		SB.SuccorAddr,			--申救地点
		SB.ServiceCardNo,		--维修车号
		SB.SuccorId,			--救援类型
		
		CONVERT(char(10),SB.StartDate,120) AS StartDate,			--出发日期
		CONVERT(char(10),SB.ReturnDate,	120)AS ReturnDate,		--返回日期
		CONVERT(char(10),SB.ReachDate,120)AS ReachDate,			--到达日期
		
		CONVERT(char(8),SB.StartDate,114) AS StartTime,			--出发时间
		CONVERT(char(8),SB.ReturnDate,114)AS ReturnTime,		--返回时间
		CONVERT(char(8),SB.ReachDate,114)AS ReachTime,			--到达时间

		SB.LinkPerson,			--联系人
		SB.LinkTel,				--联系电话
		
		SE.Comment AS errdescription				--故障描述
FROM	BillIndex	B
INNER	JOIN	Billindex_CarRepair				Bc	ON	B.BillNumberId = Bc.BillNumberId
INNER	JOIN	QP_RepairAutoInfo				RA	ON	Bc.RATypeID	= RA.TypeID
INNER	JOIN	Qp_SuccorBill					SB	ON	B.BillNumberId = SB.BillNumberId
INNER	JOIN	Qp_SuccorBill_ErrDescription	SE	ON	B.BillNumberId = SE.BillNumberId
INNER	JOIN	btype							bt	ON	B.btypeid = bt.typeId
INNER	JOIN	employee						e	ON	B.checke = e.typeId
INNER	JOIN	employee						e2	ON	Bc.ReceptionId = e2.typeId
INNER	JOIN	Department						D	ON	B.DTypeId = D.typeid
INNER	JOIN	SType							S	ON	B.Stypeid = S.TypeId
WHERE	B.BillNumberId = @BillNumberID
ORDER	BY	B.BillDate DESC,B.BillNumberId ASC

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_SuccorType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_SuccorType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：韩林
	日期：2011-04-20
	描述：查询救援类型
*/

CREATE PROCEDURE Qp_Web_SuccorType

 --@encode$--
AS
SET NOCOUNT ON 
SELECT * FROM Qp_SuccorType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_UpdateRiVipInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_UpdateRiVipInfo]
GO


-- ========================================================================
-- 功能说明：		维修项目树形选择
-- 作    者：		蔡志成
-- 创建时间：		2010-07-12
-- ========================================================================
CREATE PROCEDURE QP_Web_UpdateRiVipInfo
(
	@chvRITypeID		VARCHAR(60),
	@chvVipCardID		VARCHAR(10),
	@decManhouresrate	 NUMERIC(24, 10) ,
	@chvOperatorID		varchar(50)		-- 7、操作员 ID（作权限范围检查用）
)
--@encode$--
--QP_Web_UpdateRiVipInfo '','','',1,14,'','00001'
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------	权限检查 - Start	--------
if @chvOperatorID is null return 1	-- @intOperatorID由调用存储过程中传入的职员参数
--declare @intRe int, @chvMAtypeid varchar(50), @chvMBtypeid varchar(50), @chvMBtypeid2 varchar(50), @chvMEtypeid varchar(50), @chvMKtypeid varchar(50), @chvMPtypeid varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50)
--exec @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMAtypeid output, @chvMBtypeid output, @chvMBtypeid2 output, @chvMEtypeid output, @chvMKtypeid output, @chvMPtypeid output, @chvMExpense output, @chvMIncome output,@chvMCapital output, @chvMDtypeid output
--if @intRe <> 0 return @intRe
	
DECLARE @chvSQLWhere	varchar(8000)
DECLARE @chvSQL 	varchar(8000)
DECLARE @TempTable 	varchar(50)

SELECT @chvSQLWhere=''
SELECT @chvSQL=''

	--得到会员优惠信息
	DECLARE @intDiscountType INT,@decItemDiscount  NUMERIC(24, 10) 
	SET @intDiscountType=1
	SELECT @intDiscountType=value FROM dbo.Userconfig WHERE configName='RepairItemsDiscountType'
	--得到该会员卡的项目折扣
	 SELECT @decItemDiscount=1
	 FROM   nVipCardSet a
	 WHERE  a.VipCardTypeID = 
	 (
		SELECT  TOP 1 b.VipCardTypeID
		FROM    nVipCardSign b
		WHERE   b.VipCardID = @chvVipCardID
	  )

	SELECT  a.* INTO #temp_price 
	FROM 
	(
		--优先选择限次修项目
		SELECT  a.VipCardID,a.VipCardCode,a.VipCardTypeID,b.RepairItemsTypeID,
				b.VIPPrice AS discountmanhourexpense,1 AS discount,1 AS flag,1 AS counts
		FROM    nVipCardSign a inner JOIN dbo.[QP_nVipCardSign_RepairItems ] b ON a.VipCardID = b.VipCardID
		WHERE b.AllowUsedTimes>0 AND a.VipCardID=@chvVipCardID
		UNION ALL 
		--再选择特价维修项目
		SELECT  a.VipCardID,a.VipCardCode,a.VipCardTypeID,b.RepairItemsTypeID,
				--会员价优惠的话直接取会员价
				CASE @intDiscountType WHEN 1 THEN b.VIPPrice ELSE 0 END AS discountmanhourexpense, 
				--折扣优惠直接取折扣
				CASE @intDiscountType WHEN 2 THEN b.Discount ELSE 1 END AS discount,
				2 AS flag,1 AS counts
		FROM    nVipCardSign a inner JOIN dbo.[QP_nVipCardSet_RepairItems ] b ON a.VipCardTypeID=b.VipCardTypeID
		WHERE b.RepairItemsType=1 AND a.VipCardID=@chvVipCardID
	) a 

	UPDATE #temp_price SET #temp_price.counts=b.counts
	FROM #temp_price a LEFT JOIN 
	(
	   SELECT RepairItemsTypeID,vipcardid,COUNT(1) AS counts 
	   FROM  #temp_price
	   GROUP BY RepairItemsTypeID,vipcardid
	) b ON a.RepairItemsTypeID=b.RepairItemsTypeID AND a.vipcardid=b.vipcardid

	--如有限次修项目则删除特价项目
	DELETE #temp_price WHERE flag>1 AND counts>1


	--首先计算当前项目相关结果如：价格信息等
	SELECT TypeID,
		   ParID,
		   Leveal,
		   SonCount,
		   SonNum,
		   UserCode,
		   FullName,
		   ItemType,
		   StandardManHour,
		   CheckHour,
		   StandardPrice,
		   TopPrice,
		   LowPrice,
		   ChargeMode,
		   RepairAutoTypeID,
		   MaintainDays,
		   Comment,
		   CASE CAST(a.ChargeMode AS VARCHAR(10)) WHEN '0' THEN '按工时' WHEN '1' THEN '标准价' WHEN '2' THEN '最高价' WHEN '3' THEN '最低价' END AS chargemodename,
		   CASE CAST(a.ItemType AS VARCHAR(10)) WHEN '0' THEN '维修项目' WHEN '1' THEN '保养项目' END AS Itemtypename,
		   CASE a.ChargeMode WHEN 0 THEN ROUND(@decManhouresrate*a.StandardManHour,2) WHEN 1 THEN a.StandardPrice WHEN 2 THEN a.TopPrice WHEN 3 THEN a.LowPrice END AS manhourexpense,
		   XiWaMaxNumber
	INTO #QP_RepairItems0 FROM dbo.QP_RepairItems a WHERE a.TypeID=@chvRITypeID
	
	--录入会员卡后将根据会员卡信息带入扣率等信息
	SELECT a.TypeID,
		   a.ParID,
		   a.Leveal,
		   a.SonCount,
		   a.SonNum,
		   a.UserCode,
		   a.FullName,
		   a.ItemType,
		   Itemtypename,
		   a.StandardManHour,
		   a.CheckHour AS checkmanhour,
		   a.StandardPrice,
		   a.TopPrice,
		   a.LowPrice,
		   a.ChargeMode,
		   a.RepairAutoTypeID,
		   b.FullName AS AutoName,
		   a.MaintainDays,
		   a.Comment,
		   a.manhourexpense,		   
		   CASE c.flag 
				--当该项目为限次项目时 工时费＝项目设定工时费，折后工时费＝会员价
				WHEN 1 THEN c.discountmanhourexpense
				--当该项目为特价项目时
				WHEN 2 THEN 
							CASE @intDiscountType 
								 WHEN 1 THEN c.discountmanhourexpense
								 ELSE ROUND(c.discount* (a.manhourexpense),2)
						    END
				--既不是特价项目又不是限次项目时取项目折扣				 
				ELSE ROUND(@decItemDiscount*(a.manhourexpense),2)
		   END AS discounttotal,
		   CASE c.flag 
				--当该项目为限次项目时  扣率＝折后工时费/工时费
				WHEN 1 THEN --工时费为0时，扣率＝1
							CASE (a.manhourexpense) 
								WHEN 0 THEN 1 
								ELSE ROUND(c.discountmanhourexpense/(a.manhourexpense),2) 
							END 
				--当该项目为特价项目时
				WHEN 2 THEN 
							CASE @intDiscountType 
								 WHEN 1 THEN 									
										CASE (a.manhourexpense) 
											WHEN 0 THEN 1 
											ELSE ROUND(c.discountmanhourexpense/(a.manhourexpense),2) 
										END 
								 ELSE c.discount
						    END
				--既不是特价项目又不是限次项目时取项目折扣				 
				ELSE @decItemDiscount
		   END AS discount,		   
		   a.chargemodename,
		   c.flag AS vipcutofftype,
		   a.XiWaMaxNumber
	INTO #QP_RepairItems1 
	FROM  #QP_RepairItems0 a  
		LEFT JOIN dbo.QP_RepairAutoType b ON a.RepairAutoTypeID=b.TypeID
		LEFT JOIN #temp_price c ON a.TypeID=c.RepairItemsTypeID
	WHERE a.typeid = @chvRITypeID
	
	SELECT * FROM #QP_RepairItems1
	
	DROP TABLE #QP_RepairItems1
	DROP TABLE #QP_RepairItems0

GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_VipAddValuesQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_VipAddValuesQuery]
GO

/**---------------------------------------------------------------**/
--作者：毛欣蓉
--日期：2010-09-07
--功能：会员充值查询
--涉及单据：会员储值充值单、洗车次数卡充值单
/**--------------------------------------------------------------**/
CREATE  PROCEDURE  Qp_Web_VipAddValuesQuery
(	
	@OperatorID		varchar(100),
	@startdate		varchar(20)='',
	@enddate		varchar(20)='',
	@vipCardId		varchar(100)='',
	@vipType   		int='0',
	@STypeId		varchar(max),
	@etypeid		varchar(100),
	@vipcardtype	varchar(100)
)
--@encode$--
AS
set nocount on
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
create table #btype(typeid varchar(100))
create table #etype(typeid varchar(100))

INSERT INTO #ETYPE(TypeId) SELECT TypeId FROM  F_GetAllManagerBaseTypeId(@eTypeId,3,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
  /*
DECLARE @cartype varchar(50)
IF @viptype='0'
	SET @CARTYPE=' AND (n.iscz=''1'' or n.iswashtimes=''1'') '
IF @VIPTYPE='1'
	SET @CARTYPE=' AND n.ISCZ=''1'' '
IF @VIPTYPE='2'
	SET @CARTYPE=' AND n.ISWASHTIMES=''1'''		 
IF @VIPCARDID=''
	SET @vipcardid='%'		*/

declare @sql varchar(8000)

SELECT* FROM(
		SELECT  A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
				'会员储值充值单' AS billname,
				A.BillCode,
				a.btypeid,
				A.ETypeId,
			 	a.TotalInMoney as ssje,
				case a.billtype
					when 181 then a.PreferenceMoney
				else null
				end as yhje,
				case a.billtype when 181 then a.TotalMoney 
				else null end as czje			
		FROM	BillIndex A 
		INNER JOIN #ETYPE E ON E.TypeId = a.ETypeId
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId 
		INNER JOIN nvipcardsign n ON a.vipcardid=n.vipcardid
		WHERE	A.BillType IN (181) 				
				AND A.IfCheck = 't'
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND (@vipcardid = '' OR n.vipcardid=@vipcardid   )
                AND  a.billdate>=@startdate
				AND a.billdate<=@enddate
				and (@vipcardtype = '' OR n.vipcardtypeid=@vipcardtype   )
				 AND a.ifYearBill= 0 
		 UNION ALL
		 SELECT  A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
				'会员批量储值充值单' AS billname,
				A.BillCode,
				a.btypeid,
				A.ETypeId,
			 	bill.TotalInMoney as ssje,
				bill.PreferenceMoney as yhje,
				bill.ChargeMoney as czje
		FROM	BillIndex A 
		INNER JOIN VipAddMoneyBatchBill bill ON a.BillNumberId=bill.BillNumberId 
		INNER JOIN #ETYPE E ON E.TypeId = a.ETypeId
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId 
		INNER JOIN nvipcardsign n ON bill.vipcardid=n.vipcardid
		WHERE	A.BillType IN (312) 				
				AND A.IfCheck = 't'
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND (@vipcardid = '' OR n.vipcardid=@vipcardid   )
                AND  a.billdate>=@startdate
				AND a.billdate<=@enddate
				and (@vipcardtype = '' OR n.vipcardtypeid=@vipcardtype   )
				 AND a.ifYearBill= 0 
		UNION ALL
		SELECT  A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
				'积分转储值单' AS billname,
				A.BillCode,
				a.btypeid,
				A.ETypeId,
			 	0 ssje,
				0 yhje,
				bill.ChangeMoney as czje
		FROM	BillIndex A 
		INNER JOIN VipCentToMoneyBill bill ON a.BillNumberId=bill.BillNumberId 
		INNER JOIN #ETYPE E ON E.TypeId = a.ETypeId
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId 
		INNER JOIN nvipcardsign n ON bill.vipcardid=n.vipcardid
		WHERE	A.BillType=427			
				AND A.IfCheck = 't'
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND (@vipcardid = '' OR n.vipcardid=@vipcardid   )
                AND  a.billdate>=@startdate
				AND a.billdate<=@enddate
				and (@vipcardtype = '' OR n.vipcardtypeid=@vipcardtype   )
				 AND a.ifYearBill= 0 
				 )a
		 order by  a.BillDate DESC,a.VipCardCode



drop table #etype,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_VipCardSendNote]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_VipCardSendNote]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_Web_VipCardSendNote (
   @OperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
   @Bname        varchar(50),--客户姓名
   @btel        varchar(50) --手机好
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeID varchar(50), @MBTypeID varchar(50), @MBTypeID2 varchar(50), @METypeID varchar(50),
            @MKtypeID varchar(50), @MPtypeID varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeID varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeID OUTPUT,@MBTypeID OUTPUT,@MBTypeID2 OUTPUT,@METypeID OUTPUT,@MKtypeID OUTPUT,@MPtypeID OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeID OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 


DECLARE @SQL varchar(4000)
SET @SQL='SELECT A.VipCardID,
                 A.VipCardTypeID,
                 A.RATypeID,
                 A.BTypeID,
                 A.Bname,
                 A.Btel,
                 A.VipCardCode,
                 B.TypeName,
                 A.EndDate,
                 CASE 
					WHEN A.deleted = 0 THEN ''启用''
					WHEN A.deleted = 2 THEN ''停用''
					WHEN A.deleted = 3 THEN ''挂失''
					ELSE ''启用''
				 END AS zt,
                 A.Comment AS Comment,
                 A.czyemoney
                 FROM  nVipCardSign A 
                 INNER JOIN nVipCardSet B ON A.VipCardTypeID=B.VipCardTypeID' 
IF(ISNULL(@Bname,'')<>'')
SET @SQL=@SQL+ ' WHERE  A.Bname LIKE ''%'+@Bname+'%'''

IF(ISNULL(@Bname,'')<>'')
   SET @SQL=@SQL+ ' AND A.Btel LIKE ''%'+@btel+'%'''
ELSE
   SET @SQL=@SQL+ ' WHERE  A.Btel LIKE ''%'+@btel+'%'''

SET @SQL=@SQL+ ' ORDER BY  A.VipCardCode asc '

--PRINT @SQL RETURN     

EXEC(@SQL)   
   
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_VipColligationSum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_VipColligationSum]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/*
	Author：Wang Wei 
	DateTime：2010-08-3
	Description：会员卡汇总统计
*/
CREATE	PROCEDURE QP_Web_VipColligationSum
(
 	@OperatorID 		VARCHAR(100),
	@chvStartDate		VARCHAR(30),	
	@chvENDDate			VARCHAR(30)		--  3、查询结束时间
)
--@encode$--
AS
SET NOCOUNT ON 

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE  TABLE #CardSum(Fullname VARCHAR(100),Total  NUMERIC(24, 10) )


DECLARE @Num	NUMERIC(18,0),	--本期会员开卡数量
		@McardNum NUMERIC(18,0),--会员储值数量
		@carNum NUMERIC(18,0),	--次数洗车数量
		@currTM  NUMERIC(24, 10) ,--本期实收金额
		@currPM  NUMERIC(24, 10) ,--本期优惠金额
		@currAM  NUMERIC(24, 10) , --本期会员储值充值金额	
		@currPayM  NUMERIC(24, 10) , --本期会员储值卡的支付情况
		@currCarPayNum  NUMERIC(24, 10) ,--本期洗车次数卡支付次数	
		@WxTotal   NUMERIC(24, 10) 		--本期会员洗车充值次数

SELECT @McardNum=COUNT(VipCardID) 
FROM nVipCardSign 
WHERE createdate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME) AND IsCz=1 

SELECT @carNum=COUNT(VipCardID) 
FROM nVipCardSign 
WHERE createdate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME) AND IsWashTimes=1

SELECT @Num=COUNT(VipCardID) 
FROM nVipCardSign 
WHERE createdate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME)


/*
SELECT 	@currTM=ISNULL(SUM(TotalInMoney),0),
		@currPM=ISNULL(SUM(PreferenceMoney),0),
		@currAM=ISNULL(SUM(aMoney),0)
FROM (
	 SELECT TotalInMoney,PreferenceMoney,aMoney
	 FROM nVipAddMoney
	 WHERE BillDate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME) 
	 UNION ALL  
	 SELECT TotalInMoney,PreferenceMoney,aMoney
	 FROM QP_nVipAddWashTimes
	 WHERE BillDate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME)
	) A
*/
SELECT 	@currTM=ISNULL(SUM(TotalInMoney),0),
		@currPM=ISNULL(SUM(PreferenceMoney),0)
FROM billindex WHERE billtype in (181,182) AND BillDate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME) AND ifYearBill=0	 --年节存标志


SELECT @currAM=ISNULL(SUM(TotalMoney),0)
FROM billindex WHERE billtype in (181) AND BillDate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME) AND ifYearBill=0	 --年节存标志

SELECT @WxTotal=ISNULL(SUM(wxTotal),0)
FROM billindex WHERE billtype in (182) AND BillDate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME) AND ifYearBill=0	 --年节存标志


SELECT 
@currPayM=ISNULL(SUM(CASE billtype WHEN 45 THEN -1*total ELSE  ABS(total) END ),0)--当销售退货单时，增加了相应的会员卡的储值金额，所以乘以-1 Wang Wei 2010-8-17

FROM Listtable	
WHERE BillDate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME) AND Atypeid='0000200005' AND Audited=1 AND BillType not in( 159,181,182)

SELECT @currCarPayNum=COUNT(BillNumberId) 
FROM billindex 
WHERE 	BillType=179 AND draft=0 AND RedWord=0 AND ISNUll(VipCardID,-1)<>-1 AND TotalInMoney=0
		AND BillDate BETWEEN CAST(@chvStartDate AS DATETIME) AND CAST(@chvENDDate AS DATETIME)
		AND ifYearBill=0	 --年节存标志 

	
INSERT INTO #CardSum VALUES('本期会员开卡数量',@Num)
INSERT INTO #CardSum VALUES('	    其中:	会员储值数量',@McardNum)
INSERT INTO #CardSum VALUES('				  次数洗车数量',@carNum)
INSERT INTO #CardSum VALUES('本期会员储值充值金额',@currAM)
INSERT INTO #CardSum VALUES('本期会员洗车充值次数',@WxTotal)
INSERT INTO #CardSum VALUES('本期会员实收金额',@currTM)
INSERT INTO #CardSum VALUES('本期会员优惠金额',@currPM)
INSERT INTO #CardSum VALUES('本期会员储值支付金额',@currPayM)
INSERT INTO #CardSum VALUES('本期洗车次数卡支付次数',@currCarPayNum)

SELECT Fullname,Total FROM #CardSum


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Qp_Web_VipCzXfDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Qp_Web_VipCzXfDetail]
GO

/**---------------------------------------------------------------**/
--作者：毛欣蓉
--日期：2010-08-04
--功能：会员储值明细查询
--涉及单据：快修单、销售单、销售退货单、零售单、会员储值充值单、洗车结算单、洗车次数卡充值单、收款单
/**--------------------------------------------------------------**/
/**---------------------------------------------------------------**/
--作者：覃雨翔
--日期：2011-08-04
--功能：会员储值明细查询
--涉及单据：快修单、销售单、销售退货单、零售单、会员储值充值单、洗车结算单、洗车次数卡充值单、收款单
/**--------------------------------------------------------------**/
CREATE  PROCEDURE  Qp_Web_VipCzXfDetail
(	
	@OperatorID		varchar(100),
	@startdate		varchar(20)='',
	@enddate		varchar(20)='',
	@vipCardId		varchar(100)='',
	@vipType   		int='0',
	@STypeId		varchar(max),	--分支机构
	@vipcardtypeid	varchar(200),	--卡类型
	@billtype		varchar(200),	--单据类型
	@etypeid		varchar(200)	--职员名称
)
--@encode$--
AS
set nocount on
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
/*create table #btype(typeid varchar(100))
create table #etype(typeid varchar(100))

INSERT INTO #ETYPE(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID)
INSERT INTO #BTYPE(Typeid) SELECT Typeid FROM F_GetManDetailBType(@OperatorID) */

if @billtype='-1'
	set @billtype=''

DECLARE @cartype varchar(50),@vipid  varchar(50)

SELECT @vipid = NID FROM Ac_Items WHERE UserCode='2181'

IF @viptype='0'
	SET @CARTYPE=' AND (n.iscz=''1'' or n.iscz=''0'') '	  -- AND (n.iscz=''1'' or n.iswashtimes=''1'')
IF @VIPTYPE='1'
	SET @CARTYPE=' AND n.ISCZ=''1'' '
IF @VIPTYPE='2'
	SET @CARTYPE=' AND n.ISWASHTIMES=''1'''
IF @VIPCARDID=''
	SET @vipcardid='%'

declare @sql VARCHAR(MAX)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

CREATE TABLE #Temp(BillNumberID varchar(100))
INSERT INTO #Temp SELECT a.BillNumberId FROM BillIndex a LEFT JOIN gatheringBill g on a.BillNumberId=g.BillNumberId where g.VipCardID like @vipCardId

----处理单据类型，卡类型，职员名称----
CREATE TABLE #BILLTYPE(ID VARCHAR(MAX))
CREATE TABLE #CARDCODE(CODE VARCHAR(MAX))
CREATE TABLE #ETYPE(ID VARCHAR(MAX))
IF @billtype<>''
	INSERT INTO #BILLTYPE(ID) SELECT * FROM f_split(@billtype,',')
ELSE
	INSERT INTO #BILLTYPE(ID) SELECT Billtype FROM BillName
	
IF @vipcardtypeid<>''
	INSERT INTO #CARDCODE(CODE) SELECT VipCardCode FROM nvipcardsign WHERE VipCardTypeID=@vipcardtypeid
ELSE
	INSERT INTO #CARDCODE(CODE) SELECT VipCardCode FROM nvipcardsign
	
IF @etypeid<>''
	INSERT INTO #ETYPE(ID) SELECT typeId FROM employee E INNER JOIN (SELECT * FROM f_split(@etypeid,',')) A ON E.typeId like A.a+'%'
ELSE
	INSERT INTO #ETYPE(ID) SELECT typeId FROM employee
--快修单、销售单、销售退货单、零售单、收款单、会员储值充值单、洗车次数充值单、 快修单178、洗车结算单179

--解决@sql拼接过长超出VARCHAR(MAX)的问题
--CREATE TABLE #BillIndex
--(
--	billnumberid	numeric(10, 0),
--	billtype		numeric(4, 0),
--	BillDate		datetime,
--	vipcardcode		varchar(50),
--	bname			varchar(200),
--	billname		varchar(50),
--	BillCode		varchar(200),
--)

SET @sql='
         SELECT A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
				''会员储值充值单'' AS billname,
				A.BillCode,
				c.RATypeID,
				a.btypeid,
				A.ETypeId,
				a.TotalInMoney as ssje,
				a.PreferenceMoney as yhje,
				a.TotalMoney as czje,
				null as czcs,
				a.totalinmoney AS xfje,
				null as xfcs,
				A.stypeid,
				CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
		INNER JOIN nvipcardsign n ON a.vipcardid=n.vipcardid
		LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid'
	set @sql=@sql+'
		WHERE	A.BillType=181	
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
			
Set @sql=@sql+@cartype
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''
	
SET @sql=@sql+'
	union all
         SELECT A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
				''会员储值批量充值单'' AS billname,
				A.BillCode,
				c.RATypeID,
				a.btypeid,
				A.ETypeId,
				bill.TotalInMoney as ssje,
				bill.PreferenceMoney as yhje,
				bill.ChargeMoney as czje,
				null as czcs,
				bill.TotalInMoney AS xfje,
				null as xfcs,
				A.stypeid,
				CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		INNER JOIN VipAddMoneyBatchBill bill ON A.billnumberid=	bill.billnumberid
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
		INNER JOIN nvipcardsign n ON bill.vipcardid=n.vipcardid
		LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid'
	set @sql=@sql+'
		WHERE	A.BillType=312	
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
			
Set @sql=@sql+@cartype
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''



SET @sql=@sql+'
		union all
         SELECT A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
				CASE A.BillType
					WHEN 45 THEN ''销售退货单''
					WHEN 215 THEN ''零售退货单''
					WHEN 46 THEN ''组合品销售退货单''
					WHEN 182 THEN ''洗车次数充值单''
					ELSE ''''
				END AS billname,
				A.BillCode,
				c.RATypeID,
				a.btypeid,
				A.ETypeId,
				case a.billtype
					when 182 then a.TotalInMoney
					when 4 then a.TotalInMoney
				else null
				end as ssje,
				null as yhje,
				null as czje,
				case a.billtype 
					when 182 then a.wxTotal
				else null
				end as czcs,
				--CASE A.BillType
				--	WHEN 45 THEN -1*BM.Total
				--	WHEN 215 THEN -1*BM.Total
				--	WHEN 182 THEN NULL
				--ELSE A.TotalMoney
				CASE A.BillType
					WHEN 45 THEN -1*a.TotalInmoney
					WHEN 46 THEN -1*a.TotalInmoney
					WHEN 215 THEN -1*a.TotalInmoney
					WHEN 182 THEN NULL
				ELSE A.TotalInmoney
				END AS xfje,
				null as xfcs,
				A.stypeid,
				CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
		--INNER JOIN BillMulAccount BM ON A.Billnumberid=BM.Billnumberid
		--INNER JOIN nvipcardsign n ON bm.vipcardid=n.vipcardid
		INNER JOIN nvipcardsign n ON a.vipcardid=n.vipcardid
		LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid'
	set @sql=@sql+'
		WHERE	A.BillType IN (45,182,215,46)		
				--AND  ((A.BillType = 45 AND A.TotalinMoney <> 0) OR a.BillType <> 45)
				--AND ((A.BillType = 215 AND A.TotalinMoney <> 0) OR a.BillType <> 215)		
				AND A.IfCheck = ''t''
				--AND BM.Atypeid='+@vipid+'	
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
			
Set @sql=@sql+@cartype
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''
	

SET @sql=@sql+'
    UNION ALL
        SELECT A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
			    CASE a.billtype
			      WHEN 178 THEN ''快修单''
			      WHEN 11 THEN ''销售出库单''
			      WHEN 12 THEN ''组合品销售出库单''
			      WHEN 305 THEN ''零售单''
			      WHEN 179 THEN ''洗车结算单''
			      WHEN 195 THEN ''维修结算单''
			      WHEN 196 THEN ''救援单''
			      WHEN 182 THEN ''洗车次数充值单''
			      ELSE ''''
			      END AS billname,
				A.BillCode,
				c.RATypeID,
				a.btypeid,
				A.ETypeId,
				null AS ssje,
				null AS yhje,
				null AS czje,
				null AS czcs,
				ISNULL(a.TotalInmoney,0) AS xfje,
				--ISNULL(BM.Total,0) AS xfje,
				null as xfcs,
				A.stypeid,CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
		--INNER JOIN BillMulAccount BM ON A.Billnumberid=BM.Billnumberid
		--INNER JOIN nvipcardsign n ON BM.vipcardid=n.vipcardid
	    INNER JOIN nvipcardsign n ON a.vipcardid=n.vipcardid
		LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid'
		
		SET @sql=@sql+'
		WHERE A.BillType IN (178,11,305,179,195,196,182,12)
		        --AND BM.Atypeid='+@vipid+'		
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
							
							
Set @sql=@sql+@cartype
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''
	
	--PRINT(@sql)
	--减次数的洗车结算单
	SET @sql=@sql+'
    union all
		SELECT	A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
			   ''洗车结算单'' AS billname,
				A.BillCode,
				c.RATypeID,
				a.btypeid,
				A.ETypeId,
				null as ssje,
				null as yhje,
				null as czje,
				null as czcs,
				ISNULL(A.TotalMoney,0) AS xfje,
				1 as xfcs,
				A.stypeid,CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
		INNER JOIN nvipcardsign n ON a.vipcardid=n.vipcardid
		left join billindex_carrepair c on a.billnumberid=c.billnumberid '
		
	set @sql=@sql+'
		WHERE	A.billtype=179
		        AND A.Atypeid=''''
		        AND A.TotalMoney=0
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+'''' 
				Set @sql=@sql+@cartype
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''
	
	

Set @sql=@sql+'
    union all SELECT A.billnumberid,
				     A.billtype,
				     A.BillDate,
				     n.vipcardcode,
				     n.bname,
			         ''收款单'' AS billname,
				     A.BillCode,
				     c.RATypeID,
				     a.btypeid,
				     A.ETypeId,
				     null as ssje,
				     null as yhje,
				     null as czje,
				     null as czcs,
				     ISNULL(g.Total,0) AS xfje,
				     null as xfcs,
				     A.stypeid,
				     CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		        INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
				LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid
		        INNER JOIN gatheringBill g on a.BillNumberId=g.billnumberid
		        INNER JOIN nvipcardsign n ON n.vipcardid=g.vipcardid'
		    Set @sql=@sql+'
		        where a.billtype=4			
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
				
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''
	
	
----增加积分兑换单的处理----
SET @sql=@sql+'
    UNION ALL
        SELECT A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
			   ''积分兑换单'' AS billname,
				A.BillCode,
				c.RATypeID,
				a.btypeid,
				A.ETypeId,
				null AS ssje,
				null AS yhje,
				null AS czje,
				null AS czcs,
				null AS xfje,
				null as xfcs,
				a.stypeid,
				null as atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
	    INNER JOIN nvipcardsign n ON a.vipcardid=n.vipcardid
		LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid'
		
		SET @sql=@sql+'
		WHERE A.BillType =183
		        --AND BM.Atypeid='+@vipid+'	
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
							
							
--Set @sql=@sql+@cartype
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''

--------------------------------------------------------------------

Set @sql=@sql+'
    union all SELECT A.billnumberid,
				     A.billtype,
				     A.BillDate,
				     n.vipcardcode,
				     n.bname,
			         ''预收款单'' AS billname,
				     A.BillCode,
				     c.RATypeID,
				     a.btypeid,
				     A.ETypeId,
				     null as ssje,
				     null as yhje,
				     null as czje,
				     null as czcs,
				     ISNULL(g.Total,0) AS xfje,
				     null as xfcs,
				     A.stypeid,
				     CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		        INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
		        INNER JOIN PreBill g on a.BillNumberId=g.billnumberid
		        LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid
		        INNER JOIN nvipcardsign n ON n.vipcardid=g.vipcardid'
		    Set @sql=@sql+'
		        where a.billtype=189			
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
				
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''
--------------------------------------------------------------------
--维修取件单\整机更换单\上门维修单
SET @sql=@sql+'
    union all SELECT A.billnumberid,
					 A.billtype,
					 A.BillDate,
					 n.vipcardcode,
					 n.bname,
					 CASE a.billtype
					 WHEN 167 THEN ''维修取件单''
					 WHEN 168 THEN ''整机更换单''
					 WHEN 172 THEN ''上门维修单''
					 ELSE ''''
					 END AS billname,
					 A.BillCode,
					 c.RATypeID,
					 a.btypeid,
					 A.ETypeId,
					 null as ssje,
					 null as yhje,
					 null as czje,
					 null as czcs,
					 A.TotalInmoney AS xfje,
					 null as xfcs,
					 A.stypeid,
				     CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		--INNER JOIN BillMulAccount BM ON A.Billnumberid=BM.Billnumberid
		        INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
		        LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid
		        INNER JOIN nvipcardsign n ON n.vipcardid=a.vipcardid'
		    Set @sql=@sql+'
		        where a.billtype IN(167,168,172)
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
				
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''
--积分转储值单	
SET @sql=@sql+'
	union all
         SELECT A.billnumberid,
				A.billtype,
				A.BillDate,
				n.vipcardcode,
				n.bname,
				''积分转储值单'' AS billname,
				A.BillCode,
				c.RATypeID,
				a.btypeid,
				A.ETypeId,
				0 ssje,
				0 yhje,
				bill.ChangeMoney czje,
				null as czcs,
				0 xfje,
				null as xfcs,
				A.stypeid,
				CASE
							WHEN a.IfMulAccount = 1 THEN ''-99999''
							ELSE ISNULL(at.nTypeId,'''')
						END AS atypeid
		FROM	BillIndex A  
		left join ac_items at on a.atypeid=at.nid
		INNER JOIN VipCentToMoneyBill bill ON A.billnumberid=bill.billnumberid
		INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId
		INNER JOIN nvipcardsign n ON bill.vipcardid=n.vipcardid
		LEFT JOIN billindex_carrepair c on a.billnumberid=c.billnumberid'
	set @sql=@sql+'
		WHERE	A.BillType=427	
				AND A.IfCheck = ''t''
				AND A.RedWord = 0
				AND A.IfYearBill = 0
				AND n.vipcardid like'''+@vipcardid+''''
			
Set @sql=@sql+@cartype
if @startdate<>''
	set @sql=@sql+'AND  a.billdate>='''+@startdate+''''
if @enddate<>''
	set @sql=@sql+'AND a.billdate<='''+@enddate+''''

--------------------------------------------------------------------
	
--将单据上录入会员卡但未使用会员储值的消费金额清零
--print(@sql)
SET @sql='select b.billnumberid,
			b.billtype,
			b.BillDate,
			b.vipcardcode,
			b.bname,
			b.billname,
		    b.BillCode,
			b.RATypeID,
			b.btypeid,
			b.ETypeId,
			b.ssje,
			b.yhje,
			b.czje,
			b.czcs,
			b.xfje as xfje,
			b.xfcs,
			b.stypeid,
			b.atypeid 
		from ('+@sql+') as b 
		INNER JOIN #ETYPE E ON B.ETYPEID=E.ID
		INNER JOIN #BILLTYPE BT ON BT.ID=B.BILLTYPE
		INNER JOIN #CARDCODE CC ON CC.CODE=B.vipcardcode
		order by  b.BillDate DESC,b.VipCardCode'
--print(@sql)
--case  when b.atypeid=''0000200005'' or b.billtype in(181,182) then b.xfje
--			     else 0
--			end

--print(@sql)
exec(@sql)


--drop table #btype,#etype

DROP TABLE #GetManSTypeId
DROP TABLE #Temp
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_VipDisappearDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_VipDisappearDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	Author：Wang Wei
	DateTime：2010-8-2
	Description：查询 @IntDay 天以上无服务会员
	
	QP_Web_VipDisappearDetail '00001',1
	SELECT * From nVipCardSign
*/
CREATE PROCEDURE QP_Web_VipDisappearDetail
(
	@OperatorID	VARCHAR(100),
	@IntDay		 NUMERIC(24, 10) 
)
--@encode$-- 
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999' OR @MBtypeid2='-99999'
	INSERT INTO #GetManBTypeId(TypeId) 	SELECT typeid FROM F_GetManDetailBType(@OperatorID) 


DECLARE @billtype VARCHAR(100)
SET @billtype='11,45,305,4,179,178,181,182' --销售单、销售退货单、零售单、收款单,洗车单,快修单,会员储值充值单,洗车次数充值单

DECLARE @SQL VARCHAR(8000)
SET @SQL='
	SELECT	v.VipCardCode,--会员卡号
			v.bname,--持卡人
			v.RAtypeid,--车牌号
			v.btypeid,--客户名称
			(CASE WHEN A.MaxDate IS NULL  THEN v.CreateDate ELSE A.MaxDate END)As MaxDate,--上次服务日期[如果单据中没有会员卡最后使用的记录，则查询创建时间]			
			(CASE WHEN  A.CardDay IS NULL THEN  DATEDIFF(dd,v.CreateDate,GETDATE())
			  ELSE ISNULL(A.CardDay,-1) END )AS AllCardDay, --无服务天数 
			v.EndDate,--到期日期
			v.VipCardTypeID, --会员卡类型
			v.IsCz,	--会员储值
			v.cZyeMoney, --储值余额
			v.IsWashTimes,--次数洗车
			ISNULL(v.CanWashTimes,0) As CanWashTimes,--可洗车次数
			v.deleted,	--状态
			v.comment	--备注
	INTO #tmp
	FROM  	nVipCardSign v
			LEFT JOIN
			(
				SELECT VipCardID,
						MAX(BillDate) AS MaxDate,
						DATEDIFF(dd,MAX(BillDate),GETDATE())AS CardDay
				FROM billindex b 
				WHERE 	ISNULL(VipCardID,-1)<>-1
						AND Billtype IN('+@billtype+')
						AND Draft=0
						AND RedWord=0
						AND b.ifYearBill=0
				GROUP BY VipCardID
			)A 	ON v.VipCardID = A.VipCardID 
			
	SELECT	t.VipCardCode,--会员卡号
			t.bname,--持卡人
			t.RAtypeid,--车牌号
			t.btypeid,--客户名称
			t.MaxDate,	--上次服务日期
			t.AllCardDay,--无服务天数
			t.EndDate,--到期日期
			t.VipCardTypeID, --会员卡类型ID
			s.TypeName,		--会员卡类型
			t.IsCz,			--是否储值
			(CASE WHEN t.IsCz=1 THEN ''是'' ELSE  ''否'' END) As Czbool,
			t.cZyeMoney, --储值余额
			t.IsWashTimes,--次数洗车			
			(CASE WHEN t.IsWashTimes=1 THEN ''是'' ELSE  ''否'' END) As WashTimesbool,		
			t.CanWashTimes,--可洗车次数
			t.deleted,	--状态
			(CASE WHEN t.deleted=0 THEN ''启用'' 
				  WHEN t.deleted=2 THEN ''停用'' 
				  WHEN t.deleted=3 THEN ''挂失''
			 END
			) As state,
			t.comment	--备注 
	FROM 	#tmp t
			INNER JOIN nVipCardSet s ON  t.VipCardTypeID=s.VipCardTypeID '

IF  @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL=@SQL+' INNER JOIN #GetManBTypeId b ON b.typeid=t.btypeid '	
				
SET @SQL=@SQL+'
	WHERE	AllCardDay>'+CAST(@IntDay AS VARCHAR(100))+'
	ORDER BY VipCardCode ASC
	
	DROP TABLE #tmp '
--PRINT(@SQL)
EXEC(@SQL)
DROP TABLE #GetManBTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QP_Web_WorkGroup]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QP_Web_WorkGroup]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE   PROCEDURE QP_Web_WorkGroup (
   @OperatorID		varchar(50)		-- 15、操作员 ID（作权限范围检查用）

)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeID varchar(50), @MBTypeID varchar(50), @MBTypeID2 varchar(50), @METypeID varchar(50),
            @MKtypeID varchar(50), @MPtypeID varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeID varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeID OUTPUT,@MBTypeID OUTPUT,@MBTypeID2 OUTPUT,@METypeID OUTPUT,@MKtypeID OUTPUT,@MPtypeID OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeID OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
-- 取得当前日期
 SELECT * FROM QP_WorkGroup  ORDER BY  UserCode
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Query_Ac_Assist]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Query_Ac_Assist
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*	
	创 建 者：唐韬
	日    期：2014-06-18 10:55:59.583
	创建原因：导入财务期初 核算项目 验证
*/

CREATE PROC Query_Ac_Assist
(
	@StypeId VARCHAR(50),				--分支机构
	@AscIds	INT,						--核算项目id
	@UserCode	[varchar](100)='',		--核算项目编号
	@FullName	[varchar](100)='',		--核算项目名称
	@Number		INT=0,		--核算项目序号
	@Column     VARCHAR(50) OUTPUT,		--列名
	@ReturnID		VARCHAR(100) OUTPUT,
	@ErrMsg			VARCHAR(100) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON
IF(@AscIds IS NOT NULL)
BEGIN
	IF(@AscIds = 1)
	BEGIN
		IF(@UserCode = '')
			BEGIN
				SET @ErrMsg = '分支机构编号不能为空'
				RETURN -1
			END
		ELSE IF (@FullName = '')
			BEGIN
				SET @ErrMsg = '分支机构名称不能为空'
				RETURN -1
			END
		ELSE IF(NOT EXISTS(SELECT typeId FROM dbo.SType WHERE UserCode = @UserCode AND FullName=@FullName AND Deleted=0))
			BEGIN
				SET @ErrMsg = '分支机构不存在或停用'
				RETURN -1
			END
		ELSE
		BEGIN
			IF(EXISTS(SELECT typeId FROM dbo.SType WHERE UserCode = @UserCode AND FullName=@FullName AND soncount>0 ))
				BEGIN
					SET @ErrMsg = '该分支机构为父节点，不能导入'
					RETURN -1
				END
			ELSE
			BEGIN
				SELECT @ReturnID =typeId FROM dbo.SType WHERE UserCode = @UserCode AND FullName=@FullName 
				SET @Column ='fzhs'+CAST(@Number AS VARCHAR)
				RETURN 0
			END
		END
	END
	IF (@AscIds = 2)
	BEGIN
		IF(@UserCode = '')
			BEGIN
				SET @ErrMsg = '部门编号不能为空'
				RETURN -1
			END
		ELSE IF (@FullName = '')
			BEGIN
				SET @ErrMsg = '部门名称不能为空'
				RETURN -1
			END
		ELSE IF(NOT EXISTS(SELECT typeId FROM dbo.Department WHERE UserCode = @UserCode AND FullName=@FullName AND Deleted=0))
			BEGIN
				SET @ErrMsg = '部门不存在或停用'
				RETURN -1
			END
		ELSE
		BEGIN
			IF( EXISTS(SELECT typeId FROM dbo.Department WHERE UserCode = @UserCode AND  soncount>0 AND Deleted=0 ))
				BEGIN
					SET @ErrMsg = '该部门为父节点，不能导入'
					RETURN -1
				END
			ELSE
			BEGIN
				SELECT @ReturnID =typeId FROM dbo.Department WHERE UserCode = @UserCode AND FullName=@FullName 
				SET @Column ='fzhs'+CAST(@Number AS VARCHAR)
				RETURN 0
			END
		END
	END
	
	IF (@AscIds = 3)
	BEGIN
		IF(@UserCode = '')
			BEGIN
				SET @ErrMsg = '职员编号不能为空'
				RETURN -1
			END
		ELSE IF (@FullName = '')
			BEGIN
				SET @ErrMsg = '职员名称不能为空'
				RETURN -1
			END
		ELSE IF(NOT EXISTS(SELECT typeId FROM dbo.employee WHERE UserCode = @UserCode AND FullName=@FullName AND Deleted=0))
			BEGIN
				SET @ErrMsg = '职员不存在或停用'
				RETURN -1
			END
		ELSE
		BEGIN
			IF( EXISTS(SELECT typeId FROM dbo.employee WHERE UserCode = @UserCode AND  soncount>0 AND Deleted=0 ))
				BEGIN
					SET @ErrMsg = '该职员为父节点，不能导入'
					RETURN -1
				END
			ELSE
			BEGIN
				SELECT @ReturnID =typeId FROM dbo.employee WHERE UserCode = @UserCode AND FullName=@FullName 
				SET @Column ='fzhs'+CAST(@Number AS VARCHAR)
				RETURN 0
			END
		END
	END
	
	IF (@AscIds = 4)
	BEGIN
		IF(@UserCode = '')
			BEGIN
				SET @ErrMsg = '往来单位编号不能为空'
				RETURN -1
			END
		ELSE IF (@FullName = '')
			BEGIN
				SET @ErrMsg = '往来单位名称不能为空'
				RETURN -1
			END
		ELSE IF(NOT EXISTS(SELECT typeId FROM dbo.btype WHERE UserCode = @UserCode AND FullName=@FullName AND Deleted=0))
			BEGIN
				SET @ErrMsg = '往来单位不存在或停用'
				RETURN -1
			END
		ELSE
		BEGIN
			IF( EXISTS(SELECT typeId FROM dbo.btype WHERE UserCode = @UserCode AND  soncount>0 AND Deleted=0 ))
				BEGIN
					SET @ErrMsg = '该往来单位为父节点，不能导入'
					RETURN -1
				END
			ELSE
			BEGIN
				SELECT @ReturnID =typeId FROM dbo.btype WHERE UserCode = @UserCode AND FullName=@FullName 
				SET @Column ='fzhs'+CAST(@Number AS VARCHAR)
				RETURN 0
			END
		END
	END
	IF (@AscIds > 4)
		BEGIN
			IF(@UserCode = '')
				BEGIN
					SET @ErrMsg = '辅助核算'+CAST(@Number AS VARCHAR)+'编号不能为空'
					RETURN -1
				END
			ELSE IF (@FullName = '')
				BEGIN
					SET @ErrMsg = '辅助核算'+CAST(@Number AS VARCHAR)+'名称不能为空'
					RETURN -1
				END
			ELSE IF(NOT EXISTS(SELECT TypeId FROM dbo.Ac_Assist_CheckItemsDetail WHERE UserCode = @UserCode AND FullName=@FullName AND AscIds=@AscIds))
				BEGIN
					SET @ErrMsg = '辅助核算'+CAST(@Number AS VARCHAR)+'不存在'
					RETURN -1
				END
			ELSE IF EXISTS(SELECT typeId FROM dbo.Ac_Assist_CheckItemsDetail WHERE UserCode = @UserCode AND FullName=@FullName AND AscIds=@AscIds AND SonNum>0)
				BEGIN
					SET @ErrMsg = '辅助核算'+CAST(@Number AS VARCHAR)+'为父节点，不能导入'
					RETURN -1
				END
			ELSE
				BEGIN
					SELECT @ReturnID =TypeId FROM dbo.Ac_Assist_CheckItemsDetail WHERE UserCode = @UserCode AND FullName=@FullName AND AscIds=@AscIds
					SET @Column ='fzhs'+CAST(@Number AS VARCHAR)
					RETURN 0
				END
		END
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QueryUserMacAndIP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QueryUserMacAndIP]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇
	日期：2015-03-19
	描述：操作员登录限制的mac和硬盘号
*/
CREATE PROCEDURE QueryUserMacAndIP
(
	@etypeid			VARCHAR(50)	--当前操作员	
)
--@encode$--
AS
SET NOCOUNT ON
    SELECT  MacAddress ,
            HardDiskNo,
            etypeid
    FROM    EtypeMacAndIP WHERE etypeid  IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@etypeid))
    order by etypeid
 

GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT
                *
            FROM
                dbo.sysobjects
            WHERE
                id=OBJECT_ID(N'[dbo].[ReleaseOmProduct]') AND
                OBJECTPROPERTY(id,N'IsProcedure')=1 ) 
   DROP PROCEDURE [dbo].[ReleaseOmProduct]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇	
	日期：2012-04-11
	描述：Om商品发布,取消发布。同时对于发布的商品创建索引视图 @controlType=ok表示发布，cancel表示取消
*/
CREATE PROCEDURE ReleaseOmProduct
( 
       @typeid VARCHAR(50),
       @controlType VARCHAR(10)
)
--@encode$--       
AS 
SET NOCOUNT ON
IF (@controlType='ok')--发布
   BEGIN
         IF EXISTS ( SELECT TOP 1
                        1
                     FROM
                        dbo.ptype
                     WHERE
                        typeId=@typeid ) 
            BEGIN
                  UPDATE
                    dbo.ptype
                  SET
                    IsOm=1
                  WHERE
                    typeId=@typeid
                    IF @@ROWCOUNT=0
                    RETURN 0--失败
                    ELSE
                    RETURN 1--成功
                    
            END
            ELSE
            RETURN 3--数据不存在 
   END
ELSE 
   IF (@controlType='cancel') --取消
      BEGIN 
            IF EXISTS ( SELECT TOP 1
                            1
                        FROM
                            dbo.ptype
                        WHERE
                            typeId=@typeid ) 
               BEGIN
                     UPDATE
                        dbo.ptype
                     SET
                        IsOm=0
                     WHERE
                        typeId=@typeid    
                           IF @@ROWCOUNT=0
                    RETURN 0--失败
                    ELSE
                    RETURN 1--成功
               END
               ELSE
               
               RETURN 3--数据不存在 
      END
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[SalesPromotionManageInfo]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[SalesPromotionManageInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

----传的值: 0:“全部”、1:“未审核”(0,)、2:“审核未执行”(1,0) and (now < StartDate )、3:“执行中( StartDate < now < EndDate) ”、4:“终止(,1)”、5:“完成(now > EndDate)”

CREATE PROCEDURE SalesPromotionManageInfo
    (
      @BillDateTimeBegin VARCHAR(10),
      @BillDateTimeEnd VARCHAR(10),
      @StartDate VARCHAR(10),
      @EndDate VARCHAR(10),
      @BillCode VARCHAR(30),
      @ktypeid VARCHAR(25),
      @OperationsType VARCHAR(30),
      @BillTypeName VARCHAR(30) 
    )
--@encode$--    
AS 
    DECLARE @DateTimeBegin_ld VARCHAR(30),
        @DateTimeEnd_ld VARCHAR(30)
 --录入日期变量
    DECLARE @DateTimeBegin_cx VARCHAR(30),
        @DateTimeEnd_cx VARCHAR(30)
 --促销日期变量
    DECLARE @sql VARCHAR(4000),
        @IsHQ VARCHAR(10)
	--@IsHQ是用于仓库是否是总部的标记 0 是 1否

    SET @DateTimeBegin_ld = @BillDateTimeBegin + ' ' + '00:00:00.000'
    SET @DateTimeEnd_ld = @BillDateTimeEnd + ' ' + '23:59:59.990'
    SET @DateTimeBegin_cx = @StartDate + ' ' + '00:00:00.000'
    SET @DateTimeEnd_cx = @EndDate + ' ' + '23:59:59.990'


    SET @SQL = '
SELECT Distinct I.BillNumberID INTO ##NewTableManage	FROM CX_SalePlanIndex I 
INNER JOIN CX_SaleStocksArea C ON I.BillNumberId=C.BillNumberId
WHERE BillCode like ''%' + @BillCode + '%''
      AND KtypeId like  ''' + @ktypeid + '%''
      AND (BillDateTime >=''' + @DateTimeBegin_ld + ''' AND BillDateTime<='''
        + @DateTimeEnd_ld + ''')
      AND NOT (StartDate>''' + @DateTimeEnd_cx + ''' or EndDate<'''
        + @DateTimeBegin_cx + ''' )     '

    EXEC ( @SQL
        )
    PRINT ( @SQL )
--RETURN



/*
0代表否,1代表是,2过期
是否审核     是否到促销期	         是否终止        状态
0		0		   0
1		1		   1
		2
================================================================
0		0,1,2		   0		未审核		(只有此情况可以审核,修改,删除) [特殊：如果已过促销期不能审核]
1		0		   0		审核未执行	(只有此情况可以反审核)
1		1		   0		执行中		(只有此情况可以终止)	
1		2		   0		完成		(不能操作)
1		2		   1		终止		(不能操作)
1		1		   1	        终止		(只有此情况可以恢复)
终止按钮根据加载明细的 终止状态显示为不同的 文字 
(状态为终止时，显示 恢复，状态为启用时显示 终止)，在点了按钮后在具体判断能不能进行具体的操作
注：只有未审核且没有过促销期的单据能够审核；(2过期后不能审核，该状态自动是 未审核)
只有审核后但还没有进入促销期的单据允许反审核；
审核后单据不允许修改；
点审核后，方案记录审核标记;审核时自动保存方案当前内容。	
*/
IF @BillTypeName = 0  SET @BillTypeName = '%'

    SELECT  CASE BillType
              WHEN '1' THEN '特价促销'
              WHEN '2' THEN '赠品促销'
              WHEN '3' THEN '手工促销'
              WHEN '4' THEN '组合促销'
            END AS 'BillTypeName',
            StateName,
            State,
            BillNumberid,
            BillType,
            BillName,
            BillCode,
            CONVERT(VARCHAR(10), StartDate, 20) AS StartDate,
            CONVERT(VARCHAR(10), EndDate, 20) AS EndDate,
            JsrFullNname,
            ShrFullNname, --Checke
            ISNULL(E3.Fullname, '') AS ZZrFullNname, --Breake
            Remark,
            BillStatus,
            BreakStatus,
            EtypeId,
            Checke,
            Breake,
            CheckeDateTime
    FROM    ( SELECT    StateName,
                        State,
                        BillNumberid,
                        BillType,
                        BillName,
                        BillCode,
                        StartDate,
                        EndDate,
                        EtypeId,
                        JsrFullNname,
                        Checke,
                        ISNULL(E2.Fullname, '') AS ShrFullNname,
                        Breake,
                        Remark,
                        BillStatus,
                        BreakStatus,
                        CheckeDateTime
              FROM      ( SELECT    StateName,
                                    State,
                                    BillNumberid,
                                    BillType,
                                    BillName,
                                    BillCode,
                                    StartDate,
                                    EndDate,
                                    A1.EtypeId,
                                    ISNULL(E1.Fullname, '') AS JsrFullNname,
                                    Checke,
                                    Breake,
                                    Remark,
                                    BillStatus,
                                    BreakStatus,
                                    CheckeDateTime
                          FROM      ( SELECT    StateName,
                                                State,
                                                BillNumberid,
                                                BillType,
                                                BillName,
                                                BillCode,
                                                StartDate,
                                                EndDate,
                                                EtypeId,
                                                Checke,
                                                Breake,
                                                Remark,
                                                BillStatus,
                                                BreakStatus,
                                                CheckeDateTime
                                      FROM      ( SELECT    CASE State
                                                              WHEN '000' THEN '未审核'
                                                              WHEN '010' THEN '未审核'
                                                              WHEN '020' THEN '未审核'
                                                              WHEN '100' THEN '审核未执行'
                                                              WHEN '110' THEN '执行中'
                                                              WHEN '120' THEN '完成'
                                                              WHEN '121' THEN '终止'
                                                              WHEN '111' THEN '终止'
                                                            END AS 'StateName',
                                                            State,
                                                            BillNumberid,
                                                            BillType,
                                                            BillName,
                                                            BillCode,
                                                            StartDate,
                                                            EndDate,
                                                            EtypeId,
                                                            Checke,
                                                            Breake,
                                                            Remark,
                                                            BillStatus,
                                                            BreakStatus,
                                                            CheckeDateTime
                                                  FROM      ( SELECT    BillStatus + Isday + BreakStatus AS 'State',
                                                                        BillNumberid,
                                                                        BillType,
                                                                        BillName,
                                                                        BillCode,
                                                                        StartDate,
                                                                        EndDate,
                                                                        EtypeId,
                                                                        Checke,
                                                                        Breake,
                                                                        Remark,
                                                                        BillStatus,
                                                                        BreakStatus,
                                                                        CheckeDateTime
                                                              FROM      (
					 --根据系统当前日期，得到促销日期的状态.(0未到，1在促销日期中，2过了促销期)
                                         --                                 SELECT    CASE WHEN GETDATE() < StartDate THEN '0'
                                         --                                                WHEN ( StartDate <= GETDATE()
                                         --                                                       AND GETDATE() <= EndDate
                                         --                                                     ) THEN '1'
                                         --                                                ELSE '2'
                                         --                                           END AS 'Isday',
                                                                          SELECT    CASE WHEN CONVERT(VARCHAR(20), GETDATE(), 120) < CONVERT(VARCHAR(11), StartDate, 120) + StartTime THEN '0'
                                                                                         WHEN ( CONVERT(VARCHAR(11), StartDate, 120) + StartTime <= CONVERT(VARCHAR(20), GETDATE(), 120)
                                                                                                AND CONVERT(VARCHAR(20), GETDATE(), 120) <= CONVERT(VARCHAR(11), EndDate, 120) + EndTime
                                                                                              ) THEN '1'
                                                                                         ELSE '2'
                                                                                    END AS 'Isday',
                                                                                    BillNumberid,
                                                                                    BillType,
                                                                                    BillName,
                                                                                    BillCode,
                                                                                    StartDate,
                                                                                    EndDate,
                                                                                    EtypeId,
                                                                                    Checke,
                                                                                    Breake,
                                                                                    Remark,
                                                                                    BillStatus,
                                                                                    BreakStatus,
                                                                                    CheckeDateTime
                                                                          FROM      CX_SalePlanIndex
                                                                          WHERE     BillNumberID IN ( SELECT    BillNumberID
                                                                                                      FROM      ##NewTableManage ) AND BillType LIKE @BillTypeName
                                                                        ) A
                                                            ) B
                                                ) TAB
                                      WHERE     statename LIKE @OperationsType
                                                + '%'
                                    ) A1
                                    LEFT JOIN Employee E1 ON A1.Etypeid = E1.typeid
                                                             AND E1.Deleted = 0
                        ) A2
                        LEFT JOIN Employee E2 ON A2.Checke = E2.typeid
                                                 AND E2.Deleted = 0
            ) A3
            LEFT JOIN Employee E3 ON A3.Breake = E3.typeid
                                     AND E3.Deleted = 0


    DROP TABLE ##NewTableManage
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelA]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelA]
GO

















/****** Object:  Stored Procedure dbo.SelA    Script Date: 2002-6-20 10:14:53 ******/

CREATE  proc SelA
( @Parid varchar(50),
 @cFlag char(1)
)
--@encode$--
as
set nocount on
select  * from atype where parid=@parid and deleted=0 and sysflag=@cflag


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelAtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelAtype]
GO



























/****** Object:  Stored Procedure dbo.SelE    Script Date: 2002-6-20 10:14:53    吴德水 2002-11-29重写******/
CREATE              proc SelAtype
(
    @Parid VARCHAR(50),
    @DbName varchar(30),
    @ifDeleted int=0,  --显示停用信息
	@MagEType VARCHAR(50)
)
--@encode$--
as
SET NOCOUNT ON 
declare @SonNum  int
declare @sql [varchar](5000)
declare @Deleted varchar(15)
DECLARE @SQLWHERE varchar(2000)
SET @SQLWHERE =''

-- 加入权限限制
DECLARE @MBTYPE  VARCHAR(50)
DECLARE @MBTYPE2 VARCHAR(50)
DECLARE @MPTYPE  VARCHAR(50)
DECLARE @MKTYPE  VARCHAR(50)
DECLARE @METYPE  VARCHAR(50)
DECLARE @MATYPE  VARCHAR(50)

DECLARE @mftypeid  VARCHAR(50)
DECLARE @mitypeid  VARCHAR(50)
DECLARE @mctypeid  VARCHAR(50)
DECLARE @mdtypeid  VARCHAR(50)

SELECT @MBTYPE = MangerBTypeID, @MBTYPE2 = MangerBTypeID2
	, @MPTYPE = MangerPTypeID, @METYPE = MangerETypeID 
	, @MKTYPE = MangerKTypeID
	, @MATYPE = MangerATypeID
	, @mftypeid =MangerExpense
	, @mitypeid = MangerIncome

	, @mctypeid = MangerCpaital
	, @mdtypeid = MangerDtypeID
FROM loginuser
WHERE [EtypeID] = @MagEType

-- 特殊处理权限为全部的情况 == begin
IF @MBTYPE ='00000' OR @MBTYPE='0000'
	SET @MBTYPE =''
IF @MBTYPE2 ='00000' OR @MBTYPE2='0000'
	SET @MBTYPE2 =''
IF @MPTYPE ='00000' OR @MPTYPE='0000'
	SET @MPTYPE =''
IF @METYPE ='00000' OR @METYPE='0000'
	SET @METYPE =''
IF @MKTYPE ='00000' OR @MKTYPE='0000'
	SET @MKTYPE =''

DECLARE @MATYPE_TEMP VARCHAR(50)
IF @MATYPE ='00000' OR @MATYPE='0000' --银行帐户
	SET @MATYPE ='0000100004'
SET @MATYPE_TEMP = @MATYPE
IF @mftypeid='0000'  -- 费用权限
	SET @mftypeid='0000400003'
IF @mitypeid='0000'  -- 收入权限
	SET @mitypeid='0000300003'
IF @mctypeid ='0000' -- 『固定资产合计』
	SET @mctypeid='0000100002'
IF @mdtypeid='00000' OR  @mdtypeid='0000'
	SET @mdtypeid =''
-- ************************************************ 资产
IF @Parid ='00001'
BEGIN
	SET @MATYPE =''
	SET @mctypeid=''
END
IF LEFT(@Parid,10) ='0000100004' --银行帐户
BEGIN
	IF LEN(@MATYPE)-LEN(@Parid) =5
		SET @MATYPE =@MATYPE
	IF LEN(@MATYPE)-LEN(@Parid) =10
		SET @MATYPE =LEFT(@MATYPE,LEN(@MATYPE)-5)
	IF LEN(@MATYPE)-LEN(@Parid) =15
		SET @MATYPE =LEFT(@MATYPE,LEN(@MATYPE)-10)
END
IF LEFT(@Parid,10)='0000100003' -- 现金
BEGIN
	SET @MATYPE =@MATYPE
END
IF LEFT(@Parid,10) ='0000100002' -- 固定资产
BEGIN
	IF LEN(@mctypeid)-LEN(@Parid) =5
		SET @mctypeid =@mctypeid
	IF LEN(@mctypeid)-LEN(@Parid) =10
		SET @mctypeid =LEFT(@mctypeid,LEN(@mctypeid)-5)
	IF LEN(@mctypeid)-LEN(@Parid) =15
		SET @mctypeid =LEFT(@mctypeid,LEN(@mctypeid)-10)
END
-- ************************************************ 资产

-- ************************************************ 收入类
IF @Parid='00003'
BEGIN
	SET @mitypeid=''
END
IF LEFT(@Parid,10) ='0000300003' -- 其他收入
BEGIN
	IF LEN(@mitypeid)-LEN(@Parid) =5
		SET @mitypeid =@mitypeid
	IF LEN(@mitypeid)-LEN(@Parid) =10
		SET @mitypeid =LEFT(@mitypeid,LEN(@mitypeid)-5)
	IF LEN(@mitypeid)-LEN(@Parid) =15
		SET @mitypeid =LEFT(@mitypeid,LEN(@mitypeid)-10)
END
-- ************************************************ 收入类

-- ************************************************ 支出类
IF @Parid='00004'
BEGIN
	SET @mftypeid=''
END
IF LEFT(@Parid,10) ='0000400003' -- 费用权限
BEGIN
	IF LEN(@mftypeid)-LEN(@Parid) =5
		SET @mftypeid =@mftypeid
	IF LEN(@mftypeid)-LEN(@Parid) =10
		SET @mftypeid =LEFT(@mftypeid,LEN(@mftypeid)-5)
	IF LEN(@mftypeid)-LEN(@Parid) =15
		SET @mftypeid =LEFT(@mftypeid,LEN(@mftypeid)-10)
END
-- ************************************************ 支出类

SET @mftypeid='0000400003'
SET @mitypeid='0000300003'
SET @mctypeid='0000100002'
SET @MATYPE='0000100004'

CREATE TABLE #Atype (TypeID varchar(50))

IF LEFT(@parid,10)='0000100004'
	INSERT INTO #AType(typeid) 
	SELECT a.typeid FROM Atype a
	,(select * from F_BaseGetManATypeAll(@MagEType) where parid=@Parid) b where a.typeid=b.typeid
ELSE IF  LEFT(@parid,10)='0000100002'
	INSERT INTO #AType(typeid) 
	SELECT a.typeid FROM Atype a
	,(select * from F_BaseGetManATypeZcAll(@MagEType) where parid=@Parid) b where a.typeid=b.typeid
ELSE IF LEFT(@parid,10)='0000300003' 
	INSERT INTO #AType(typeid) 
	SELECT a.typeid FROM Atype a
	,(select * from F_BaseGetManATypeSrAll(@MagEType) where parid=@Parid) b where a.typeid=b.typeid
ELSE IF LEFT(@parid,10)='0000400003'
	INSERT INTO #AType(typeid) 
	SELECT a.typeid FROM Atype a
	,(select * from F_BaseGetManATypeFyAll(@MagEType) where parid=@Parid) b where a.typeid=b.typeid
ELSE
	INSERT INTO #AType(typeid) 
	SELECT a.typeid FROM Atype a where parid =@parid




if @ifDeleted=0
	set @Deleted=' and deleted=0'
else
	set @Deleted=''

if @DbName='atype'
    begin
	if @ifDeleted=0
	    select @SonNum=sonnum from atype  where typeid=@Parid and deleted=0
	else	
	    select @SonNum=sonnum from atype  where typeid=@Parid

                 if @SonNum= 0 
                    Select @sql='select * from atype  where typeid not like ''00005%'' AND typeId='+CHAR(39)+@parid+CHAR(39)+@deleted +' AND FullName <> '+char(39)+'借转采购结算与成本差'+char(39)+' AND FullName <> '+char(39)+'『借入商品』'+char(39)+' AND FullName <> '+char(39)+'『借出商品』'+char(39)+' AND FullName <> '+char(39)+'借转进货结算与成本差'+char(39)
                 else 
                    Select @sql='select * from atype  where typeid not like ''00005%'' AND parId='+CHAR(39)+@parid+CHAR(39)+@deleted+' AND FullName <> '+char(39)+'借转采购结算与成本差'+char(39)+' AND FullName <> '+char(39)+'『借入商品』'+char(39)+' AND FullName <> '+char(39)+'『借出商品』'+char(39)+' AND FullName <> '+char(39)+'借转进货结算与成本差'+char(39)
    end


IF @Parid ='00001' AND @MATYPE_TEMP='0000100003' --只管现金，不管银行时
	SELECT @SQLWHERE = @SQLWHERE +' AND TypeID NOT LIKE '+char(39)+'0000100004'+'%'+char(39)
SELECT @SQLWHERE = @SQLWHERE + ' AND   TypeID NOT LIKE '+char(39)+'00005%'+char(39)+' AND
											(
											 (TypeID LIKE '+char(39) +'00001%'+char(39) +' AND TypeID NOT LIKE '+char(39)+'0000100004%'+char(39) +' AND TypeID NOT LIKE '+char(39)+'0000100002%' +char(39)+')'+ ' OR 
											 (TypeID LIKE '+char(39) +@MATYPE+'%'+char(39)+')'+ ' OR 
											 (TypeID LIKE '+char(39) +@mctypeid+'%'+char(39)+')'+ ' OR 
											 (TypeID LIKE '+char(39) +'00002%'+char(39) +')'+ ' OR 
											 (TypeID LIKE '+char(39) +'00003%'+char(39) +' AND TypeID NOT LIKE '+char(39)+'0000300003%'+char(39) +')'+ ' OR 
											 (TypeID LIKE '+char(39) +@mitypeid+'%'+char(39)+')'+ ' OR 
											 (TypeID LIKE '+char(39) +'00004%'+char(39) +' AND TypeID NOT LIKE '+char(39)+'0000400003%'+char(39) +')'+ ' OR 
											 (TypeID LIKE '+char(39) +@mftypeid+'%'+char(39)+')'+ ') '


SET @sql = @sql +@SQLWHERE+' AND typeid in (select typeid from #Atype)  order by usercode'
--PRINT @SQL
exec (@sql)

DROP TABLE #Atype
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelB]
GO



/****** Object:  Stored Procedure dbo.SelE    Script Date: 2004-1-5 10:14:53   陈启华 重写******/

-- ===========因为要加一个建档日期

/*
	作者：廖晨羽
	日期：2011-08-17
	描述：添加职员名称查询
*/

/*
	作者：吕文祺
	日期：2012-04-18
	描述：支持输出结算单位字段
*/

CREATE            proc SelB
(
    @Parid VARCHAR(50),
    @DbName varchar(30)='btype',
    @ifDeleted int=0,   --显示停用信息
	@CStartDate varchar(50) ='',
	@CEndDate varchar(50) ='',
	@chvOperatorID VARCHAR(50)='00001'
)
--@encode$--
as
SET NOCOUNT ON 
declare @SonNum  int
declare @sql [varchar](500)
declare @Deleted varchar(15)
declare @SQL_WHERE varchar(200)

SET @SQL_WHERE = ''
if @CStartDate<>'' 
	BEGIN
		SET @SQL_WHERE = 'AND CreateDate>=' + char(39) + @CStartDate + char(39)
	END
if @CEndDate<>'' 
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE+ 'AND CreateDate<=' + char(39) + @CEndDate + char(39)
	END

if @ifDeleted=0
	set @SQL_WHERE = @SQL_WHERE+' and b.deleted=0'


CREATE TABLE #BType (TypeID varchar(50))


INSERT INTO #BType(typeid) 
SELECT b.typeid FROM Btype b
,(select * from F_BaseGetManBTypeAll(@chvOperatorID) where parid=@Parid) a where a.typeid=b.typeid


if @DbName='btype'
	begin
		if @ifDeleted=0
			begin
				select @SonNum=sonnum from btype  where typeid=@Parid and deleted=0
			end
		else
			begin
				select @SonNum=sonnum from btype  where typeid=@Parid
			end
		if @SonNum= 0  and len(@parid)>5
			begin
				Select @sql='select b.*, c.typeId as denominatedid, c.FullName as denname,areaName=isnull((select top 1 fullname from areatype where typeid=b.areatypeid),''''),efullname=isnull((select top 1 fullname from employee where typeid=b.etypeid),'''') from btype b left join btype c on b.denominatedid=c.typeId  where b.typeId='+CHAR(39)+@parid+CHAR(39)+@SQL_WHERE+' and b.typeid in (select typeid from #BType)  order by b.usercode'
			end 
		else 
			begin	
				Select @sql='select b.*, c.typeId as denominatedid, c.FullName as denname,areaName=isnull((select top 1 fullname from areatype where typeid=b.areatypeid),''''),efullname=isnull((select top 1 fullname from employee where typeid=b.etypeid),'''') from btype b left join btype c on b.denominatedid=c.typeId where b.parId='+CHAR(39)+@parid+CHAR(39)+@SQL_WHERE+' and b.typeid in (select typeid from #BType)    order by b.usercode'
			end 
	end

--print @sql
exec (@sql)
DROP TABLE #BType

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelE]
GO

/****** Object:  StoredProcedure [dbo].[SelE]    Script Date: 03/29/2012 10:38:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--最后修改
--作    者：徐辉
--日    期：2008-08-29
--修改原因：收入，银行，费用，固定资产权限没有控制到子节点


--最后修改
--作    者：林军
--日    期：2010-05-07
--修改原因：增加分支机构表

-- 修改 
-- 作者:zhua
-- 日期:2012-03-29 10:47:26.640
-- 原因：分支机构调整，把最顶层的分支机构放出来，只是stype情况下才放出来

CREATE            proc [dbo].[SelE]
(
    @Parid VARCHAR(50),
    @DbName varchar(30),
    @ifDeleted int=0,   --显示停用信息
    @chvOperatorID VARCHAR(50)='00001'
)
--@encode$--
as
SET NOCOUNT ON 

--------	权限检查 - Start	--------
if @chvOperatorID is null return 1	-- @intOperatorID由调用存储过程中传入的职员参数
declare @intRe int, @chvMAtypeid varchar(50), @chvMBtypeid varchar(50), @chvMBtypeid2 varchar(50), @chvMEtypeid varchar(50), @chvMKtypeid varchar(50), @chvMPtypeid varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50)
exec @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMAtypeid output, @chvMBtypeid output, @chvMBtypeid2 output, @chvMEtypeid output, @chvMKtypeid output, @chvMPtypeid output, @chvMExpense output, @chvMIncome output,@chvMCapital output, @chvMDtypeid output
if @intRe <> 0 return @intRe
--------	权限检查 - End		--------

declare @SonNum  int
declare @sql [varchar](5000)
declare @Deleted varchar(15)

CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Atype (TypeID varchar(50))
--CREATE TABLE #Stype (TypeID varchar(50))        --分支机构表
CREATE TABLE #dtype (TypeID varchar(50)) 

if @ifDeleted=0
	set @Deleted=' and deleted=0'
else
	set @Deleted=''

if @DbName='atype'
    begin
		 begin
		    if left(@parid,10) = '0000100004' --现金银行
			begin
				INSERT INTO #AType(typeid) 
				SELECT a.typeid FROM Atype a
				,(select * from F_BaseGetManATypeAll(@chvOperatorID) where parid=@Parid) b where a.typeid=b.typeid

        		Select @sql='select * from atype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+' and typeid in (select typeid from #Atype)  order by usercode'
			end
		    else if left(@parid,10) = '0000300003' --其他收入
			begin
				INSERT INTO #AType(typeid) 
				SELECT a.typeid FROM Atype a
				,(select * from F_BaseGetManATypeSrAll(@chvOperatorID) where parid=@Parid) b where a.typeid=b.typeid

                    	Select @sql='select * from atype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'  and typeid in (select typeid from #Atype)  order by usercode'
			end
		    else if left(@parid,10) = '0000400003' --费用类型
			begin
				INSERT INTO #AType(typeid) 
				SELECT a.typeid FROM Atype a
				,(select * from F_BaseGetManATypeFyAll(@chvOperatorID) where parid=@Parid) b where a.typeid=b.typeid

                    	Select @sql='select * from atype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'  and typeid in (select typeid from #Atype)  order by usercode'
			end
		    else if left(@parid,10) = '0000100002' --固定资产
			begin
				INSERT INTO #AType(typeid) 
				SELECT a.typeid FROM Atype a
				,(select * from F_BaseGetManATypeZcAll(@chvOperatorID) where parid=@Parid) b where a.typeid=b.typeid

                    	Select @sql='select * from atype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'  and typeid in (select typeid from #Atype)  order by usercode'
			end
		    else
			begin
				INSERT INTO #AType(typeid) 
				SELECT a.typeid FROM Atype a
				,(select * from F_BaseGetManATypeAll(@chvOperatorID) where parid=@Parid) b where a.typeid=b.typeid

				Select @sql='select * from atype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'  and typeid in (select typeid from #Atype) order by usercode'
			end
		 end
    end
if @DbName='btype'
    begin
    if @ifDeleted=0
       select @SonNum=sonnum from btype  where typeid=@Parid and deleted=0
    else
       select @SonNum=sonnum from btype  where typeid=@Parid

                 if @SonNum= 0  and len(@parid)>5
                   Select @sql='select * from btype  where typeId='+CHAR(39)+@parid+CHAR(39)+@deleted
                 else 
                    Select @sql='select * from btype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'  order by usercode'
    end
if @DbName='employee'
    begin
	IF @Parid='00001'
			INSERT INTO #EType(typeid) 
			SELECT e.typeid FROM Employee e
			,(select * from F_BaseGetManETypeAll(@chvOperatorID) where parid='00001') a where e.typeid=a.typeid

	ELSE
			INSERT INTO #EType(typeid) 
			SELECT e.typeid FROM Employee e
		,(select * from F_BaseGetManETypeAll(@chvOperatorID) where parid=@Parid) a where e.typeid=a.typeid

                    Select @sql='select BtypeID,typeId,Parid,leveal,soncount,sonnum,FullName,[Name],UserCode,Department,Tel,Address,Comment,deleted,Sex,Nation,Knowledge,Blood,Health,IDcard,
						case when Birthday=''2050-01-01'' then null else Birthday end as Birthday,Marriage,Job,Job2,
						case when ((select   COUNT(ImgURL) as iCOUNT from EType_Picture PC where PC.etypeid=typeid)>0) then ''有'' else ''无''   end  ImgURL2,
						case when JobTime=''2050-01-01'' then null else JobTime end as JobTime,Tel2,Mob,Mail,political,nat_place,college,for_language,reg_place,com_level,weight,stature,fam_status,informer,speciality,for_lan_level,PostCode,
						Email,DtypeID,PyCode,case when MaxPre =-999999999918.99 then null else maxpre end as maxpre,smsMobile,smsComment,tichengRate,qq,msn,blog,mblog,buyerminvalue,saleminvalue
								 from employee  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+' and typeid in (select typeid from #EType) order by usercode'
    end
if @DbName='ptype'
begin
	IF @Parid='00000'
			INSERT INTO #PType(typeid) 
			SELECT p.typeid FROM Ptype p
			,(select * from F_BaseGetManPTypeAll(@chvOperatorID) where parid='00000') a where p.typeid=a.typeid
	ELSE
			INSERT INTO #PType(typeid) 
			SELECT p.typeid FROM Ptype p
		,(select * from F_BaseGetManPTypeAll(@chvOperatorID) where parid=@Parid) a where p.typeid=a.typeid

        Select @sql='select 
						serial= case when sonnum>0 then '''' else case when ifserial=''1'' then ''强制'' else ''—'' end  end,
						unitrate = case when unit2='''' then unit1 else unit2+'+'''/'''+'+unit1+'+'''(1:'''+'+dbo.fn_sms_format(unitrate1)+'+''')'' end,
						* from ptype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+' and typeid in (select typeid from #ptype)  order by usercode'


end
if @DbName='stock'
    begin

	IF @Parid='00000'
			INSERT INTO #KType(typeid) 
			SELECT k.typeid FROM stock k
			,(select * from F_BaseGetManKTypeAll(@chvOperatorID) where parid='00000') a where k.typeid=a.typeid
	ELSE
			INSERT INTO #KType(typeid) 
			SELECT k.typeid FROM stock k
		,(select * from F_BaseGetManKTypeAll(@chvOperatorID) where parid=@Parid) a where k.typeid=a.typeid

                    Select @sql='select * from stock  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+' and typeid in (select typeid from #ktype)  order by usercode'
    end
if @DbName='DepartMent'
    begin
     IF @Parid='00000'
			INSERT INTO #dtype(typeid) 
			SELECT d.typeid FROM Department d
			,(select * from F_BaseGetManDTypeAll(@chvOperatorID) where parid='00000') a where d.typeid=a.typeid
	ELSE
			INSERT INTO #dtype(typeid) 
			SELECT d.typeid FROM Department d
		,(select * from F_BaseGetManDTypeAll(@chvOperatorID) where parid=@Parid) a where d.typeid=a.typeid

    Select @sql='select * from Department  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+' and typeid in (select typeid from #dtype)  order by usercode'
    end
if @DbName='ltype'
    begin
     if @ifDeleted=0
    	select @SonNum=sonnum from ltype  where typeid=@Parid and deleted=0
    else
    	select @SonNum=sonnum from ltype  where typeid=@Parid
                 if @SonNum= 0 and @parid<>'00000'
                    Select @sql='select * from ltype  where typeId='+CHAR(39)+@parid+CHAR(39)+@deleted
                 else 
                    Select @sql='select * from ltype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'  order by usercode'

    end
if @DbName='AreaType'
    begin
     if @ifDeleted=0
    	select @SonNum=sonnum from AreaType  where typeid=@Parid and deleted=0
    else
    	select @SonNum=sonnum from AreaType  where typeid=@Parid
                 if @SonNum= 0 and @parid<>'00000'
                    Select @sql='select * from AreaType  where typeId='+CHAR(39)+@parid+CHAR(39)+@deleted
                 else 
                    Select @sql='select * from AreaType  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+'  order by usercode'
    end

IF @DbName='Stype'
	SET @sql='
		SELECT * FROM stype w WHERE parid='+QUOTENAME(@parid,'''')+@deleted+' AND (w.typeid=''00000'' OR w.typeid IN 
			(SELECT a.typeid FROM F_BaseGetManSType('+QUOTENAME(@chvOperatorID,'''')+') A 
				JOIN stype s ON a.TypeId=s.TypeId WHERE s.parid='+QUOTENAME(@parid,'''')+')'+@deleted+'
		)ORDER BY w.UserCode
		';
		
--print @sql return
exec (@sql)

DROP TABLE #Ptype
DROP TABLE #Etype
DROP TABLE #Ktype
DROP TABLE #Atype
--DROP TABLE #Stype

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelL]
GO


















/****** Object:  Stored Procedure dbo.SelE    Script Date: 2002-6-20 10:14:53    吴德水 2002-11-29重写******/
CREATE       proc SelL
(
    @Parid VARCHAR(50),
    @DbName varchar(30),
	@KtypeID VARCHAR(50),
    @ifDeleted int=0   --显示停用信息
)
--@encode$--
as
SET NOCOUNT ON 
declare @SonNum  int
declare @sql [varchar](500)
declare @Deleted varchar(15)

if @ifDeleted=0
	set @Deleted=' and deleted=0'
else
	set @Deleted=''
DECLARE @K_WHERE varchar(500)
SET @K_WHERE =''
IF not(@KtypeID ='' or @KtypeID='00000')
	SET @K_WHERE =' AND Ktypeid like ' + char(39) + @KtypeID +'%' +char(39)
	

if @DbName='ltype'
    begin
     if @ifDeleted=0
    	select @SonNum=sonnum from ltype  where typeid=@Parid and deleted=0
    else
    	select @SonNum=sonnum from ltype  where typeid=@Parid
                 if @SonNum= 0 and @parid<>'00000'
                    Select @sql='select * from ltype  where typeId='+CHAR(39)+@parid+CHAR(39)+@deleted + @K_WHERE + ' and SysFlag=0 order by usercode'
                 else 
                    Select @sql='select * from ltype  where parId='+CHAR(39)+@parid+CHAR(39)+@deleted+@K_WHERE+ ' and SysFlag=0 order by usercode'
    end
	--print @SQL
exec (@sql)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelP]
GO

















/****** Object:  Stored Procedure dbo.SelP    Script Date: 2002-6-20 10:14:53 ******/

CREATE  proc SelP
    @Parid varchar(50),
    @DbName varchar(30)
--    @keyid varchar(50),
--    @nleveal  smallint
--@encode$--
as
SET NOCOUNT ON 
declare @sql [varchar](500)
select @sql='select * from '
 +@dbname+' where parid='+CHAR(39)+@parid+CHAR(39)
--select fullname ,etypeid, parid ,leveal ,sonnum,soncount from employee 
--where parid=@parid
 exec (@sql)
return -1


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelS]
GO

















/****** Object:  Stored Procedure dbo.SelS    Script Date: 2002-6-20 10:14:53 ******/

CREATE  proc SelS
    @DbName varchar(30)
--@encode$--
as
SET NOCOUNT ON 
declare @sql [varchar](500)
select @sql='select * from '
 +@dbname+' where deleted = 0'
exec (@sql)


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_BindReportData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_BindReportData]
GO












/*
	作者：谢吉康
	日期：2004-08-24
	描述：数据绑定，包括绑定报表表头数据和表体数据
*/
CREATE    PROCEDURE sp_BindReportData
(
	@sp_ReportId	int,			--报表的ID值
	@sp_ProcName	varchar(200),	--报表执行的存储过程名称
	@bindType		int=0			--绑定类型  0.表头名称  1.表体数据
)
--@encode$--
AS
SET NOCOUNT ON

IF @bindType = 0
	SELECT	I.sp_TableName,
			S.is_Tree,
			S.Hidd_Value,
			S.OnClick,
			S.OnDbClick,
			I.OrderId			
	FROM 	SP_SysTableName I,
			SP_SysProce  S
	WHERE	S.sp_ReportId = I.sp_Id
			AND S.sp_ReportId = @sp_ReportId
			AND S.sp_ProcName = @sp_ProcName
	ORDER 	BY
			I.OrderId
ELSE
	SELECT 	E.En_Item,
			E.Align,
			E.[Format],
			E.Format_Num,
			E.is_Sum,
			E.OrderId,
			S.is_Tree,
			S.Hidd_Value,
			S.OnClick,
			S.OnDbClick
	FROM	SP_SysTEnItem E,
			SP_SysTableName T,
			SP_SysProce S
	WHERE	E.sp_SysTableName_Id = T.[Id]
			AND E.sp_Id = S.sp_ReportId
			AND S.sp_ReportId = @sp_ReportId
			AND S.sp_ProcName = @sp_ProcName
	ORDER BY
			E.OrderId












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[sp_who_lock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_who_lock]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2020-04-14
	描述：查询死锁资源的存储过程
	
	BEGIN TRY
		EXEC sp_who_lock
	END TRY
	BEGIN CATCH
	END CATCH
*/

CREATE procedure sp_who_lock   
AS 
BEGIN      
	DECLARE @spid INT     
	DECLARE @blk INT     
	DECLARE @count INT     
	DECLARE @index INT     
	DECLARE @lock tinyINT      
	SET @lock=0      
   
	CREATE TABLE #temp_who_lock      
	(      
		id INT identity(1,1),      
		spid INT,      
		blk INT     
	)      
	
	IF @@error<>0 RETURN @@error      
 
	INSERT INTO #temp_who_lock(spid,blk)      
	SELECT 0 ,blocked       
	FROM (
			SELECT	* 
			FROM	master..sysprocesses 
			WHERE	blocked>0
	)a      
	WHERE NOT EXISTS(
						SELECT  * 
						FROM	master..sysprocesses 
						WHERE	a.blocked =spid and blocked>0
	)      
	UNION 
	SELECT	spid,
			blocked 
	FROM	master..sysprocesses 
	WHERE	blocked>0      
	
	IF @@error<>0 RETURN @@error      
 
	SELECT	@count=count(*),@index=1 
	FROM	#temp_who_lock      
 
	IF @@error<>0 RETURN @@error      
 
	IF @count=0      
	BEGIN     
		SELECT '没有阻塞和死锁信息'     
		RETURN 0      
	END
	
	WHILE @index<=@count      
	BEGIN     
		IF EXISTS(SELECT 1 FROM #temp_who_lock a WHERE id>@index and exists(SELECT 1 FROM #temp_who_lock WHERE id<=@index and a.blk=spid))      
		BEGIN     
			SET @lock=1      
			SELECT @spid=spid,@blk=blk FROM #temp_who_lock WHERE id=@index     
			SELECT '引起数据库死锁的是: '+ CAST(@spid AS VARCHAR(10)) + '进程号,其执行的SQL语法如下'     
			SELECT  @spid, @blk    
			DBCC inputbuffer(@spid)      
			DBCC inputbuffer(@blk)      
		END
		SET @index=@index+1      
	END 
 
	IF @lock=0       
	BEGIN     
		SET @index=1      
		WHILE @index<=@count      
		BEGIN     
			SELECT @spid=spid,@blk=blk FROM #temp_who_lock WHERE id=@index     
			IF @spid=0      
				SELECT '引起阻塞的是:'+cast(@blk as varchar(10))+ '进程号,其执行的SQL语法如下'     
			ELSE 
				SELECT '进程号SPID：'+ CAST(@spid AS VARCHAR(10))+ '被' + '进程号SPID：'+ CAST(@blk AS VARCHAR(10)) +'阻塞,其当前进程执行的SQL语法如下'     
			
			DBCC inputbuffer(@spid)    
			DBCC inputbuffer(@blk)      
			SET @index=@index+1      
		END
	END	    
 
	DROP TABLE #temp_who_lock      
	RETURN  0      
END          
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spCRM_CheckMessage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spCRM_CheckMessage]
GO


/*
操作员是否有消息
*/
CREATE     PROCEDURE spCRM_CheckMessage
(
	@chvETypeID		VARCHAR(50)
)
--@encode$--
AS

SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 * FROM sysdata WHERE SubName = 'curdate' AND SubValue <> CONVERT(VARCHAR(10),GETDATE(),120))
BEGIN
	UPDATE sysdata SET SubValue = '' WHERE SubName IN ('curdate','curflag','curinfo')
	UPDATE sysdata1 SET SubValue = '' WHERE SubName = 'curinfo'
	UPDATE Userconfig SET Value = '' WHERE ConfigName = 'curinfo'
END

DECLARE @SQL varchar(8000)

SELECT @SQL ='SELECT isnull(Count(Type),0) as Qty FROM CRM_MessageNoRead  WHERE ReceiverTypeID ='+char(39)+@chvETypeID+char(39)

EXEC(@SQL)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spCRM_MsgSendBatch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spCRM_MsgSendBatch]
GO












/*
批量发送信息
批量接收者的TypeID用","号分割,如"00001,00002,00003"
*/
CREATE       PROCEDURE spCRM_MsgSendBatch
(
	@chvMode			VARCHAR(20), -- 模式 OnlyOne
	@chvSenderTypeID		VARCHAR(50), -- 发送者职员ID
	@chvReceiverTypeIDList		VARCHAR(MAX), -- 接收者职员ID       
	@chvContent			VARCHAR(MAX), -- 内容
	@chvType			VARCHAR(20),   -- 模式 System normal
	@chvBeginDate			VARCHAR(30),   -- 提醒时间 在这个时间以后提醒
	@chvSource			VARCHAR(20),   -- 日程类型(事件，计划，循环提醒)
	@chvSourceTypeID		int    -- 对应日程ID号
)
--@encode$--

AS
SET NOCOUNT ON 

IF 'OnlyOne' = @chvMode SELECT @chvType = 'System'
--IF 'System' = @chvType SELECT @chvSenderTypeID = '00001'

--初始化批量接收人TypeID字符串
DECLARE @chvTempStr VARCHAR(50)
DECLARE @chvReceiverName VARCHAR(40)
DECLARE @chvSenderName VARCHAR(40)
DECLARE @nReceiverCount INT
DECLARE @nSendMsgID INT
DECLARE @chvShowTitle VARCHAR(50)
DECLARE @chvValue VARCHAR(2)
DECLARE @chvStatus VARCHAR(20)
SELECT @nReceiverCount = 0


IF RIGHT(@chvReceiverTypeIDList,1) <> CHAR(44)
	SELECT @chvReceiverTypeIDList = @chvReceiverTypeIDList + CHAR(44)	--CHAR(44) 逗号


WHILE LEN(@chvReceiverTypeIDList) >1
BEGIN
	SELECT @chvTempStr = LTRIM(RTRIM(LEFT(@chvReceiverTypeIDList,CHARINDEX(CHAR(44),@chvReceiverTypeIDList)-1)))
     		SELECT @chvReceiverTypeIDList = RIGHT(@chvReceiverTypeIDList,LEN(@chvReceiverTypeIDList)-CHARINDEX(CHAR(44),@chvReceiverTypeIDList))

 IF NOT EXISTS(SELECT TOP 1 1 FROM [Employee] WHERE deleted=0 AND [TypeID]=@chvTempStr)
 BEGIN
	 RAISERROR('当前存在已经停用的抄送人，保存失败！',16,1) RETURN
 END
 
	SELECT @chvReceiverName = ISNULL((SELECT TOP 1 [Name] FROM [Employee] WHERE [TypeID]=@chvTempStr),'')
	SELECT @chvSenderName = ISNULL((SELECT TOP 1 [Name] FROM [Employee] WHERE [TypeID]=@chvSenderTypeID),'')

	--存入接收人拥有的消息
	
	INSERT INTO CRM_Message (CreateDate,SenderTypeID,ReceiverTypeID,CreatorTypeID,Content,IsRead,[Type],[BeginDate],[Source],[SourceTypeID],[ReceiverName],[SenderName])
	VALUES(
			GETDATE(),
			@chvSenderTypeID,
			@chvTempStr,
			@chvTempStr,
			@chvContent,
			0,
			@chvType,
			@chvBeginDate,
			@chvSource,
			@chvSourceTypeID,
			@chvReceiverName,
			@chvSenderName)		

	SELECT @nSendMsgID = ISNULL(MAX(ID),0) + 1 FROM CRM_MessageNoRead

	--在未读消息表中同步存入该消息
	INSERT INTO CRM_MessageNoRead ([ID],CreateDate,SenderTypeID,ReceiverTypeID,CreatorTypeID,Content,IsRead,[Type],[BeginDate],[Source],[SourceTypeID],[ReceiverName],[SenderName])
	VALUES(
			@nSendMsgID,
			GETDATE(),
			@chvSenderTypeID,
			@chvTempStr,
			@chvTempStr,
			@chvContent,
			0,
			@chvType,
			@chvBeginDate,
			@chvSource,
			@chvSourceTypeID,
			@chvReceiverName,
			@chvSenderName)


END
	
RETURN 1










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spCRM_ScheduleAdd]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spCRM_ScheduleAdd]
GO









/*
新增一条日程（CRM_Schedule表） cqhua 2006-03-15
*/
CREATE    PROCEDURE spCRM_ScheduleAdd
(
	@chvCreatorTypeID	VARCHAR(50),			--创建者
	@Date			VARCHAR(30),			--日程日期
	@chvTitle		VARCHAR(100),			--主题
	@chvContent		VARCHAR(MAX)	,		--内容
	@chvID			int OUTPUT		--返回新增日程的ID
)
--@encode$--

AS
SET NOCOUNT ON 

IF @chvCreatorTypeID IS null  -- @intOperatorID由调用存储过程中传入的职员参数
BEGIN
	SET @chvID = '-1' 	
	RETURN
END

INSERT INTO CRM_Schedule ([Type],[CreatorTypeID],[Date],[CreateDate],[AlterDate],[Title],[Content],[IsAlert]) 
VALUES (
	'Event',
	@chvCreatorTypeID,
	@Date,  --日程日期
	GETDATE(), -- CreateDate 写日期的日期
	GETDATE(),
	@chvTitle,
	@chvContent,
	'0'
	)

IF @@ROWCOUNT =0  OR @@error<>0
	SET @chvID = '-1'
ELSE
	SET @chvID =SCOPE_IDENTITY(); 










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spCRM_ScheduleDel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spCRM_ScheduleDel]
GO









/*
删除一条日程（CRM_Schedule表） cqhua 2006-03-15
*/
CREATE    PROCEDURE spCRM_ScheduleDel
(
	@ID			INT
)
--@encode$--

AS
SET NOCOUNT ON 

-- 删除日程
DELETE FROM CRM_Schedule 
WHERE   
	[ID] = @ID

-- 删除抄送人的消息
DELETE FROM Crm_Message WHERE SourceTypeID =@ID
DELETE FROM Crm_MessageNoRead WHERE SourceTypeID =@ID

RETURN 1






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spCRM_ScheduleEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spCRM_ScheduleEdit]
GO









/*
修改一条日程（CRM_Schedule表） cqhua 2006-03-15
*/
CREATE    PROCEDURE spCRM_ScheduleEdit
(
	@ID			INT,
	@Date			VARCHAR(30),			--日程日期
	@chvTitle		VARCHAR(100),			--主题
	@chvContent		VARCHAR(2000)			--内容
)
--@encode$--

AS
SET NOCOUNT ON 

-- 修改日程
UPDATE CRM_Schedule 
SET
	[Date]	 = @Date ,
	Title    = @chvTitle ,
	Content  = @chvContent
WHERE   
	[ID] = @ID

-- 删除抄送人的消息
DELETE FROM Crm_Message WHERE SourceTypeID =@ID
DELETE FROM Crm_MessageNoRead WHERE SourceTypeID =@ID

RETURN 1






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spCRM_ScheduleList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spCRM_ScheduleList]
GO










/*
日程列表
最后修改 By 杨硕宇 日程浏览范围
*/
CREATE     PROCEDURE spCRM_ScheduleList
(
	@chvStartDate		VARCHAR(30),
	@chvEndDate		VARCHAR(30),
	@chvETypeID		VARCHAR(50)
)
--@encode$--
AS

SET NOCOUNT ON

DECLARE @SQL varchar(8000)

SELECT @SQL ='SELECT 
		* 
	      FROM 
		  CRM_Schedule 
	      WHERE  
		      Date>='+char(39)+@chvStartDate+char(39)+'
		  AND Date<='+char(39)+@chvEndDate+char(39)+'
		  AND (CreatorTypeID = '+char(39)+@chvETypeID+char(39) +' 
		       OR  ID IN (SELECT SourceTypeID FROM CRM_Message WHERE ReceiverTypeID ='+char(39)+@chvETypeID+char(39)+'))'+ ' 
	      ORDER BY  [Date],[ID] '
	     
		
--PRINT @SQL
EXEC(@SQL)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spCRM_ScheduleListAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spCRM_ScheduleListAll]
GO












/*
日程列表汇总
*/
CREATE        PROCEDURE spCRM_ScheduleListAll
(
	@chvStartDate		VARCHAR(30),
	@chvEndDate		VARCHAR(30),
	@chvETypeID		VARCHAR(50),
	@chvTitle		VARCHAR(500),
	@chvContent		VARCHAR(500),
	@Flag                   int = 1  -- 1 统计记录 3算合计数
)
--@encode$--
AS

SET NOCOUNT ON

--SELECT *,'a' as FUllName FROM CRM_Schedule WHERE Title LIKE '%'+@chvTitle+'%'
--RETURN
DECLARE @SQL varchar(8000)
IF @Flag = 1
	SELECT 
		C.* ,E.FullName
	      FROM 
		  CRM_Schedule C ,Employee E
	      WHERE  
		      C.CreatorTypeID=E.TypeID
		  AND DATEDIFF(day,@chvStartDate,C.[Date]) >= 0
		  AND DATEDIFF(day,C.[Date],@chvEndDate) >= 0
		  AND (CreatorTypeID = @chvETypeID
		      	  OR  ID IN (SELECT SourceTypeID FROM CRM_Message WHERE ReceiverTypeID =@chvETypeID)
		      )
		  AND  Title LIKE '%'+@chvTitle+'%'
		  AND  Content LIKE '%'+@chvContent+'%'
	      ORDER BY  [Date],[ID] 

ELSE
	SELECT 
			isnull(Count(*),0) as Qty
		      FROM 
			  CRM_Schedule 
		      WHERE  
			  DATEDIFF(day,@chvStartDate,[Date]) >= 0
		  	  AND DATEDIFF(day,[Date],@chvEndDate) >= 0
			  AND (CreatorTypeID = @chvETypeID
			      	  OR  ID IN (SELECT SourceTypeID FROM CRM_Message WHERE ReceiverTypeID =@chvETypeID)
			      )
			  AND  Title LIKE '%'+@chvTitle+'%'
			  AND  Content LIKE '%'+@chvContent+'%'
			
	     
		
--PRINT @SQL
--EXEC(@SQL)

--select * from CRM_Message








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SubsidiaryLedgerQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SubsidiaryLedgerQuery]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：俞俊杰
	日期：2012-4-19
	描述：科目余额表查询
-------------------------------------------*/
CREATE PROCEDURE SubsidiaryLedgerQuery
(
    @STypeId 	VARCHAR(50),		---分支机构ID
    @ATypeId		VARCHAR(50),	---会计科目ID    
    @Cid			INT,			---币别ID(-1:所有币别 0：本位币）
	@FPeriodStart VARCHAR(10),		---起始期间
	@FPeriodEnd  VARCHAR(10),		---结束期间    
	@IsShowByFdc   INT,				---是否按科目设置方向显示
	@isshownotpost INT				---是否显示未过账凭证 1：是 0：否
)
AS 
SET NOCOUNT ON
DECLARE @sql VARCHAR(max) --一个期间的查询语句
DECLARE @CidQuery VARCHAR(50) --币别
DECLARE @notpostQuery VARCHAR(50) ---是否显示未过账凭证

--是否显示已过账凭证
IF (@isshownotpost = 0)
 SET @notpostQuery = ' AND AUDITED = 1'
ELSE
 SET @notpostQuery = ''
 
--所有币别  
IF(@Cid=-1)
  SET @CidQuery ='select UserCode from Ac_Currency'
ELSE
  SET @CidQuery = CONVERT(varchar, @Cid)
  
--获取余额方向 1：借方 -1：贷方
declare @Fdc varchar(10) 
set @Fdc =(select TOP 1
case  
when Fdc  =  1 then '借' 
when Fdc  = -1 then '贷'
end as cd 
from Ac_Account 
where StypeId=@STypeId and TypeId = @ATypeId and Fdc is not null);
  
---创建数据表
create table #SubsidiaryLedger(
 fperiod int,
 vouchertime date,
 fserialname varchar(50),
 summary varchar(500),
 fdebittotal  NUMERIC(24, 10) ,
 fcredittotal  NUMERIC(24, 10) ,
 fdc varchar(10),
 total  NUMERIC(24, 10) 
)
---循环取每月数据
while CONVERT(int ,@FPeriodStart) <= CONVERT(int,@FPeriodEnd)
BEGIN
set @sql = '
--取出数据
SELECT * INTO #temp FROM
( 
---临时期初余额
SELECT 
	0 AS id,
	t1.FPERIOD AS fperiod,
	t3.FBegin AS vouchertime,
	'''' AS fserialname,
	''期初余额'' AS summary,
	CASE 
	when t2.Fdc =1 then FBeginBalanceFor 
	end AS fdebittotal,
	CASE 
	when t2.Fdc =-1 then FBeginBalanceFor 
	end AS fcredittotal,
	CASE 
	when t2.Fdc =1 then ''借''
	when t2.Fdc =-1 then ''贷''
	end AS fdc , 
	FBeginBalanceFor AS total
	FROM Ac_Balance t1 
	left join Ac_Account t2 ON t1.ATypeId = t2.TypeId
	left join AC_PERIOD t3 ON t3.FPERIOD = t1.FPERIOD
WHERE t3.FPERIOD = '+@FPeriodStart+' AND t2.TypeId = '''+@ATypeId+''' AND t2.STYPEID = '+@STypeId +'AND t1.CID in ('+@CidQuery+')
UNION ALL
--分类明细表
SELECT 
t1.BILLNUMBERID + t2.ID AS id,
t1.FPERIOD AS fperiod,
t1.BILLDATE AS vouchertime,
t3.FULLNAME+''-''+CONVERT(varchar,t1.FSERIALNUM) AS fserialname ,
t2.SUMMARY AS summary,
t2.FDEBITTOTAL AS fdebittotal ,
t2.FCREDITTOTAL AS fcredittotal,
'''' AS fdc,
null AS total
FROM AC_VOUCHER t1 
left join AC_VOUCHER_BILL t2 on t1.BillNumberId = t2.BillNumberId 
left join AC_VOUCHER_GROUP t3 on t3.VGID = t1.VGID 
WHERE t1.STypeId = '+@STypeId+@notpostQuery+' AND t1.FPERIOD = '+@FPeriodStart+' AND t2.ATypeId = '''+@ATypeId+'''
) a
---对数据进行计算
SELECT t1.id,sum(isnull(t2.fdebittotal,0)-isnull(t2.fcredittotal,0)) AS total,'
IF @IsShowByFdc = 0
set @sql = @sql +
'CASE 
when sum(isnull(t2.fdebittotal,0)-isnull(t2.fcredittotal,0))>0 then ''借''
when sum(isnull(t2.fdebittotal,0)-isnull(t2.fcredittotal,0))<0 then ''贷''
end AS fdc '
ELSE
set @sql = @sql +''''+ @Fdc +
''' AS fdc '

set @sql = @sql +' INTO #total  
FROM #temp t1
inner join #temp t2
on t2.ID<=t1.ID
GROUP BY t1.id

SELECT 
t1.BILLNUMBERID + t2.ID AS id,
t1.FPERIOD AS fperiod,
t1.BILLDATE AS vouchertime,
t3.FULLNAME+''-''+CONVERT(varchar,t1.FSERIALNUM) AS fserialname ,
t2.SUMMARY AS summary,
t2.FDEBITTOTAL AS fdebittotal ,
t2.FCREDITTOTAL AS fcredittotal,
'''' AS fdc,
null AS total
INTO #ledger
FROM AC_VOUCHER t1 
left join AC_VOUCHER_BILL t2 on t1.BillNumberId = t2.BillNumberId 
left join AC_VOUCHER_GROUP t3 on t3.VGID = t1.VGID 
where t1.STYPEID = '+@STypeId+@notpostQuery+' AND t1.FPERIOD = '+@FPeriodStart+' AND t2.ATypeId = '''+@ATypeId+'''
----拼凑表数据(期初余额，明细账)
SELECT * INTO #temptable1 FROM 
(
SELECT 
	t1.FPERIOD AS fperiod,
	t3.FBegin AS vouchertime,
	'''' AS fserialname,
	''期初余额'' AS summary,
	null AS fdebittotal,
	null AS fcredittotal,
	CASE 
	when t2.Fdc =1 then ''借''
	when t2.Fdc =-1 then ''贷''
	end AS fdc , 
	FBeginBalanceFor AS total
	FROM Ac_Balance t1 
	left join Ac_Account t2 ON t1.ATypeId = t2.TypeId
	left join AC_PERIOD t3 on t3.FPERIOD = t1.FPERIOD
WHERE t3.FPERIOD = '+@FPeriodStart+' AND t2.TypeId = '''+@ATypeId+''' AND t1.STYPEID ='+@STypeId+' AND t1.CID in ( '+@CidQuery+' )
UNION ALL
SELECT 
	fperiod,
	vouchertime,
	fserialname,
	summary,
	fdebittotal,
	fcredittotal,
	t2.fdc, '
	IF @IsShowByFdc = 0 
	set @sql = @sql + 'abs(t2.total) AS total '
	else
	set @sql = @sql + 't2.total AS total '
	set @sql = @sql + ' FROM #ledger t1 
	left join #total t2
    on t1.id = t2.id
    ) a
    
--拼凑本期合计
SELECT 
	t1.fperiod,
	t2.FEnd AS vouchertime,
	'''' AS fserialname,
	''本期合计'' AS summary,
	SUM(fdebittotal) AS fdebittotal,
	SUM(fcredittotal)AS fcredittotal, '
	IF @IsShowByFdc = 0
	set @sql = @sql + 'CASE 
	when isnull(SUM(fdebittotal),0) - isnull(SUM(fcredittotal),0)>0 then ''借''
	when isnull(SUM(fdebittotal),0) - isnull(SUM(fcredittotal),0)<0 then ''贷''
	end AS fdc,
	abs(isnull(SUM(fdebittotal),0) - isnull(SUM(fcredittotal),0)) AS total '
	ELSE
	set @sql = @sql +''''+ @Fdc + ''' AS fdc,
	isnull(SUM(fdebittotal),0) - isnull(SUM(fcredittotal),0) AS total '
	
	set @sql = @sql + 'INTO #temptable2
	FROM #temptable1 t1
	left join AC_PERIOD t2 on t1.fperiod = t2.FPeriod
	WHERE t2.FPERIOD = '+@FPeriodStart+'
	GROUP BY t1.fperiod,t2.FEnd
--拼凑本年累计'
IF(@FPeriodStart=1)
set @sql = @sql+'
SELECT 
	null AS fperiod,
	t1.vouchertime,
	'''' AS fserialname,
	''本年累计'' AS summary,
	CASE 
	when t2.Fdc = 1 then isnull(t1.fdebittotal,0)
	end AS fdebittotal,
	CASE 
	when t2.Fdc = -1 then isnull(t1.fcredittotal,0)
	end AS fcredittotal,
	''暂缓'' AS fdc,
	NULL AS total
	into #temptable3
FROM #temptable2 t1 
left join Ac_Account t2 on t2.TypeId = '''+@ATypeId+'''
GROUP BY t1.vouchertime,t2.fdc,t1.fcredittotal,t1.fdebittotal
UPDATE #temptable3 
'
ELSE
set @sql = @sql+'
SELECT 
	null AS fperiod,
	t1.vouchertime,
	'''' AS fserialname,
	''本年累计'' AS summary,
	CASE 
	when t3.Fdc = 1 then sum(isnull(t1.fdebittotal,0)+ isnull(t2.FEndBalanceFor,0))
	else  isnull(t1.fdebittotal,0)
	end AS fdebittotal,
	CASE 
	when t3.Fdc = -1 then sum(isnull(t1.fcredittotal,0)+isnull(t2.FEndBalanceFor,0))
	else  isnull(t1.fcredittotal,0)
	end AS fcredittotal,
	''暂缓'' AS fdc,
	NULL AS total
	INTO #temptable3
FROM #temptable2 t1 
left join Ac_Balance t2 on t1.fperiod = t2.FPeriod + 1
left join Ac_Account t3 on t3.TypeId = '''+@ATypeId+'''
WHERE  t2.STYPEID = '+@STypeId+' AND t2.CID in ( '+@CidQuery+') AND t2.ATypeId= '''+@ATypeId+'''
GROUP BY t1.vouchertime,t3.fdc,t1.fcredittotal,t1.fdebittotal
 UPDATE #temptable3 
'
IF @IsShowByFdc = 0 
set @sql = @sql +'
--计算本年累计方向与余额
SET fdc = 
CASE 
	when isnull(fdebittotal,0)- isnull(fcredittotal,0)>0 then ''借''
	when isnull(fdebittotal,0)- isnull(fcredittotal,0)<0 then ''贷''
end,
total = abs(isnull(fdebittotal,0)- isnull(fcredittotal,0))
'
ELSE
set @sql = @sql + '
SET fdc = '''+@Fdc+''',
total = isnull(fdebittotal,0)- isnull(fcredittotal,0)
'

set @sql = @sql +'--最后拼凑
insert into #SubsidiaryLedger
SELECT * FROM
(
SELECT * FROM #temptable1
UNION ALL
SELECT * FROM #temptable2
UNION ALL
SELECT * FROM #temptable3
) a
--删除临时表
if  exists (select * from tempdb.dbo.sysobjects where id = object_id(N''tempdb..#temp'') and type=''U'')
drop table #temp
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N''tempdb..#total'') and type=''U'')
drop table #total
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N''tempdb..#ledger'') and type=''U'')
drop table #ledger
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N''tempdb..#temptable1'') and type=''U'')
drop table #temptable1
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N''tempdb..#temptable2'') and type=''U'')
drop table #temptable2
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N''tempdb..#temptable3'') and type=''U'')
drop table #temptable3
'
print @sql
exec (@sql)
SET @FPeriodStart = @FPeriodStart +1
END
UPDATE #SubsidiaryLedger SET fdc = '平' WHERE total = 0 
exec('select * from #SubsidiaryLedger ')

if  exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#SubsidiaryLedger') and type='U')
drop table #SubsidiaryLedger
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[A_UFO_QueryBillnumberid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].A_UFO_QueryBillnumberid
GO


CREATE PROCEDURE A_UFO_QueryBillnumberid
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),          --结算单位
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @OperatorId	VARCHAR(50),		--当前操作员
    @billtype int
)
--@encode$--
AS
SET NOCOUNT ON
	
	declare @sql varchar(max)='',@sqlJoin varchar(max)='',@flag varchar(1)='t'

	--===============================创建临时数据表并取值【BEGIN】===================================
	
	if(@billtype in (184,185,204))
		set @flag='f'
	
    --有分支机构单据
	create	TABLE #stype(TypeId VARCHAR(50))
	INSERT INTO #stype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #Stype s ON bill.stypeid=s.typeid'



	--往来单位
	if(@billtype not in (5,9,10,14,16,17,21,45,57,77,78,115,116,128,129,158,159,173,174,181,188,204,205,206))
	begin
	create	TABLE  #dealbtype(TypeId VARCHAR(50))
	INSERT INTO #dealbtype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #dealbtype dealb ON bill.dealbtypeid=dealb.typeid'
	end
	
	--结算单位
	if(@billtype not in (5,9,10,14,16,17,21,45,57,77,78,115,116,128,129,158,159,173,174,181,188,204,205,206,215,305))
	begin
	create	TABLE #btype(TypeId VARCHAR(50))
	INSERT INTO #btype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #btype b ON bill.btypeid=b.typeid'
	end
	
	--经手人
	create	TABLE #Etype(TypeId VARCHAR(50))
	INSERT INTO #Etype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #Etype e ON bill.etypeid=e.typeid'
	
	--仓库
	if(@billtype not in (4,5,10,36,66,77,78,84,85,93,115,116,128,129,141,145,147,148,149,150,151,158,159,181,184,185,189,190,204,205,206))
	begin
		create	TABLE #KType(TypeId VARCHAR(50))
		INSERT INTO #KType(TypeId)	
		SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)
		
		set @sqlJoin = @sqlJoin+' AND (bill.ktypeid in (select typeid from #KType) or bill.ktypeid2 in (select typeid from #KType)) '
		if @billtype='57'
			insert into #ktype values('00000');
	end
	
	--部门
	create	TABLE #dtype(TypeId VARCHAR(50))
	INSERT INTO #dtype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #dtype d ON bill.dtypeid=d.typeid'
	
	--===============================创建临时数据表并取值【END】===================================
	
	
	
	create table #bill(billnumberid numeric(20))
	set @sql = 'insert into #bill
				select billnumberid from billindex bill ' + @sqlJoin + 
				' 
				where bill.billtype='+CONVERT(varchar(5), @billtype)+' AND bill.IfCheck='''+@flag+''' AND bill.IfYearBill = 0 
							AND bill.IsIni = 0 and bill.redword=0 and bill.billdate>='''+ @BeginDate +''' and bill.billdate<='''+ @EndDate+''''
							
	  	  
	  
	if(@billtype in (204))
		set @sql = 'insert into #bill
				select billnumberid from requestindex bill ' + @sqlJoin + 
				' 
				where bill.billtype='+CONVERT(varchar(5), @billtype)+'  AND bill.IfYearBill = 0 
				 and bill.billdate>='''+ @BeginDate +''' and bill.billdate<='''+ @EndDate+''''
				 
		
	if(@billtype in (300,301))
		set @sql = 'insert into #bill
				select billnumberid from orderindex bill ' + @sqlJoin + 
				' 
				where bill.billtype='+CONVERT(varchar(5), @billtype)+'  
				 and bill.billdate>='''+ @BeginDate +''' and bill.billdate<='''+ @EndDate+''''				 

	if(@CID<>0)
	  set @sql+=' and bill.cid='+@CID		
	  
	 --print @sql;

	exec (@sql)
	select billnumberid from #bill

	--===============================得到数据并返回结果============================================
	
	
	--select * from #Stype
	--select * from #dealbtype
	--select * from #btype
	--select * from #Etype
	--select * from #KType
    --select * from #dtype

	drop table #stype,#Etype,#dtype,#bill
	if(@billtype not in (184,204,185,145,147,116,115,128,129,4,189,66,190,148,150,149,151,36,158,77,93,5,10,84,85,78,181,159,205,206,141))
	 drop table #KType
	if(@billtype not in (5,9,10,14,16,17,21,45,57,77,78,115,116,128,129,158,159,173,174,181,188,204,205,206))
	 drop table #dealbtype
	if(@billtype not in (5,9,10,14,16,17,21,45,57,77,78,115,116,128,129,158,159,173,174,181,188,204,205,206,215,305))
	 drop table #btype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[A_UFO_QuerydoubleBillnumberid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].A_UFO_QuerydoubleBillnumberid
GO


CREATE PROCEDURE A_UFO_QuerydoubleBillnumberid
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @OperatorId	VARCHAR(50),		--当前操作员
    @billtype int
)
--@encode$--
AS
SET NOCOUNT ON
	
	declare @sql varchar(max)='',@sqlJoin varchar(max)='',@sqlWhere varchar(max)=''

	--===============================创建临时数据表并取值【BEGIN】===================================
	

	create	TABLE #stype(TypeId VARCHAR(50))
	INSERT INTO #stype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #Stype s ON bill.stypeid=s.typeid'
	
	if(@billtype not in (17,21,187,188,16,173,174))
	begin
	create	TABLE  #dealbtype(TypeId VARCHAR(50))
	INSERT INTO #dealbtype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #dealbtype dealb ON bill.dealbtypeid=dealb.typeid'
	end
	
	if(@billtype not in (17,21,187,188,16,173,174))
	begin
	create	TABLE #btype(TypeId VARCHAR(50))
	INSERT INTO #btype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #btype b ON bill.btypeid=b.typeid'
	end
	
	create	TABLE #Etype(TypeId VARCHAR(50))
	INSERT INTO #Etype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #Etype e ON bill.etypeid=e.typeid'
	
		create	TABLE #KType(TypeId VARCHAR(50))
		INSERT INTO #KType(TypeId)	
		SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)
		set @sqlWhere = ' AND (bill.ktypeid in (select typeid from #KType) or bill.ktypeid2 in (select typeid from #KType)) '
	
	create	TABLE #dtype(TypeId VARCHAR(50))
	INSERT INTO #dtype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #dtype d ON bill.dtypeid=d.typeid'
	
	--===============================创建临时数据表并取值【END】===================================
	
	
	
	create table #bill(billnumberid numeric(20))
	set @sql = 'insert into #bill
				select billnumberid from billindex bill ' + @sqlJoin + 
				' 
				where bill.billtype='+CONVERT(varchar(5), @billtype)+' ' + @sqlWhere+' AND bill.IfCheck=''t'' AND bill.IfYearBill = 0 
							AND bill.IsIni = 0 and bill.redword=0 and bill.billdate>='''+ @BeginDate +''' and bill.billdate<='''+ @EndDate+''''
	--print @sql
	
		if(@CID<>0)
	  set @sql+=' and bill.cid='+@CID		
	  
	exec (@sql)
	--print @sql
	select billnumberid from #bill

	--===============================得到数据并返回结果============================================


	drop table #stype,#Etype,#dtype,#bill
	if(@billtype not in (17,21,187,188,16,173,174))
	begin
		drop table #dealbtype,#btype
	end
	 drop table #KType
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[A_UFO_QueryorderBillnumberid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].A_UFO_QueryorderBillnumberid
GO


CREATE PROCEDURE A_UFO_QueryorderBillnumberid
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @OperatorId	VARCHAR(50),		--当前操作员
    @billtype int
)
--@encode$--
AS
SET NOCOUNT ON
	
	declare @sql varchar(max)='',@sqlJoin varchar(max)=''

	--===============================创建临时数据表并取值【BEGIN】===================================
	

	create	TABLE #stype(TypeId VARCHAR(50))
	INSERT INTO #stype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #Stype s ON bill.stypeid=s.typeid'
	
	create	TABLE  #dealbtype(TypeId VARCHAR(50))
	INSERT INTO #dealbtype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #dealbtype dealb ON bill.dealbtypeid=dealb.typeid'
	
	create	TABLE #btype(TypeId VARCHAR(50))
	INSERT INTO #btype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #btype b ON bill.btypeid=b.typeid'
	
	create	TABLE #Etype(TypeId VARCHAR(50))
	INSERT INTO #Etype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,3,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #Etype e ON bill.etypeid=e.typeid'
	
		create	TABLE #KType(TypeId VARCHAR(50))
		INSERT INTO #KType(TypeId)	
		SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,4,@OperatorID)
		set @sqlJoin = @sqlJoin+' INNER JOIN #KType k ON bill.ktypeid=k.typeid'
	
	create	TABLE #dtype(TypeId VARCHAR(50))
	INSERT INTO #dtype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,9,@OperatorID)
	set @sqlJoin = @sqlJoin+' INNER JOIN #dtype d ON bill.dtypeid=d.typeid'
	
	--===============================创建临时数据表并取值【END】===================================
	
	
	
	create table #bill(billnumberid numeric(20))
	set @sql = 'insert into #bill
				select billnumberid from orderindex bill ' + @sqlJoin + 
							' where bill.billtype='+CONVERT(varchar(5), @billtype)+'
							 AND bill.IsIni = 0 and bill.redword=0 and bill.billdate>='''+ @BeginDate +''' and bill.billdate<='''+ @EndDate+''''
							 
	if(@CID<>0)
	  set @sql+=' and bill.cid='+@CID
	  
	  	exec (@sql)
	select billnumberid from #bill

	--===============================得到数据并返回结果============================================


	drop table #stype,#dealbtype,#btype,#Etype,#dtype,#bill
	 drop table #KType
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_BJD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_BJD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-报价单
-- =============================================
CREATE PROCEDURE UFO_BJD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,184
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,184)
	
	set @sql = 'select @re='+@sqlcolumn+' from quotepricebill bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_BJDBD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_BJDBD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-变价调拨单
-- =============================================
CREATE PROCEDURE UFO_BJDBD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QuerydoubleBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,21
	--select * from #billnumberid;
	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,21)

	--print @sqlcolumn;
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,21)
	--print @tablename;
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_BSD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_BSD
GO


CREATE PROCEDURE UFO_BSD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,9
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,9)
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,9)
	--print @tablename
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_BYD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_BYD
GO


CREATE PROCEDURE UFO_BYD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,14
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,14)
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,14)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_CBTJD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_CBTJD
GO


CREATE PROCEDURE UFO_CBTJD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
    DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,57
	
	--select * from #billnumberid;

	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,57)
	--print @sqlcolumn;

	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,57)
	--print @tablename;

	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_CGDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_CGDD
GO


CREATE PROCEDURE UFO_CGDD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,301

	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,301)

	
	
	set @sql = 'select @re='+@sqlcolumn+' from orderbill bill,#billnumberid id where bill.billnumberid = id.typeid'

	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_CGFYFT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_CGFYFT
GO


CREATE PROCEDURE UFO_CGFYFT
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,205
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,205)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,205)
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_CGHHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_CGHHD
GO


CREATE PROCEDURE UFO_CGHHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(billnumberid numeric(20))
	insert into #billnumberid
	exec A_UFO_QuerydoubleBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,161
	
	--select * from #billnumberid;

	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,161)
	--print @sqlcolumn;

	
	if(@numberOfType in ('入库金额','入库折后金额','入库价税合计'))
	begin
		set @sql = 'select @re='+@sqlcolumn+' from #billnumberid b,buygoodsexchangebill bgcb,InOutstocktable bill  
			where bgcb.BillNumberId=b.billnumberid and bill.billnumberid = bgcb.billnumberid and bgcb.InOrOut=''I'' and bgcb.id=bill.id '
	end
	else if(@numberOfType in ('出库金额','出库折后金额','出库价税合计','出库成本'))
	begin
		set @sql = 'select @re='+@sqlcolumn+' from #billnumberid b,buygoodsexchangebill bgcb,InOutstocktable bill  
			where bgcb.BillNumberId=b.billnumberid and bill.billnumberid = bgcb.billnumberid and bgcb.InOrOut=''O'' and bgcb.id=bill.id '
	end
	else 
	begin
		set @sql = 'select @re='+@sqlcolumn+' from billindex bill,#billnumberid id where bill.billnumberid = id.billnumberid'
	end
	
	--print @sql;
		
	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_CGRKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_CGRKD
GO


CREATE PROCEDURE UFO_CGRKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,34
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,34)

	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,34)

	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_CGTHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_CGTHD
GO


CREATE PROCEDURE UFO_CGTHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,6
	

	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,6)

	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,6)

	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_DTFYFS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_DTFYFS
GO


CREATE PROCEDURE UFO_DTFYFS
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,5
	
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,5)
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,5)
	--print @tablename
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_DTFYTX]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_DTFYTX
GO


CREATE PROCEDURE UFO_DTFYTX
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,10
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,10)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,10)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_FKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_FKD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-付款单
-- =============================================
CREATE PROCEDURE UFO_FKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,66
	 
	 --select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,66)
	print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,66)
	print @tablename;

		
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_FLZXD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_FLZXD
GO


CREATE PROCEDURE UFO_FLZXD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,148
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,148)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,148)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_FYD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_FYD
GO


CREATE PROCEDURE UFO_FYD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,36
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,36)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,36)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_FZJGCKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_FZJGCKD
GO


CREATE PROCEDURE UFO_FZJGCKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QuerydoubleBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,187
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,187)

	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,187)
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_FZJGRKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_FZJGRKD
GO


CREATE PROCEDURE UFO_FZJGRKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QuerydoubleBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,188
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,188)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,188)
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_HDJB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_HDJB
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-获得价保单(价保金额)
-- =============================================
CREATE PROCEDURE UFO_HDJB
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,151

	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,151)
	
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,151)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_HLZXD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_HLZXD
GO


CREATE PROCEDURE UFO_HLZXD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,150
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,150)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,150)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_HYZCD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_HYZCD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-会员储值充值单
-- =============================================
CREATE PROCEDURE UFO_HYZCD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,181

	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,181)
	
	--print @sqlcolumn
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,181)
	--print @tablename
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_HZD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_HZD
GO


CREATE PROCEDURE UFO_HZD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,126
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,126)
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,126)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_JBZXD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_JBZXD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-价保执行单(价保金额,付款金额)
-- =============================================
CREATE PROCEDURE UFO_JBZXD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,149


	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,149)
	
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,149)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_JFDHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_JFDHD
GO


CREATE PROCEDURE UFO_JFDHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,183
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,183)
	

	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,183)

	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_LSD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_LSD
GO


CREATE PROCEDURE UFO_LSD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40),@total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,305
	
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,305)
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,305)
	--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'


	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_LSTHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_LSTHD
GO


CREATE PROCEDURE UFO_LSTHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,215
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,215)
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,215)
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_QGD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_QGD
GO


CREATE PROCEDURE UFO_QGD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	
	create table #billnumberid(typeid numeric(20))
    insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,204


	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,204)


	
	set @sql = 'select @re='+@sqlcolumn+' from requestbill bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_QTCKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_QTCKD
GO


CREATE PROCEDURE UFO_QTCKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,202
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,202)
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,202)
	--print @tablename;
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_QTRKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_QTRKD
GO


CREATE PROCEDURE UFO_QTRKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,201
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,201)
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,201)
	--print @tablename;
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_QTSRD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_QTSRD
GO


CREATE PROCEDURE UFO_QTSRD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,93
	

	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,93)

	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,93)
	

	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_QueryBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_QueryBillDetail
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-16
-- Description:	业务单据函数联查明细
-- =============================================
create PROCEDURE UFO_QueryBillDetail
(
    @functionCode  VARCHAR(200),
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200)		--结束日期
)
--@encode$--
AS
SET NOCOUNT ON;

--获取单据类型编号
DECLARE @billType varchar(50)
  select @billType=(select billtype from  BillName where billname =(select name from UFO_DefineFunctions where code =@functionCode))
        

--联查明细sql        
select 
    billIndex.billdate    , --日期
    billIndex.billcode    , --编号
    billIndex.stypeid     , --分支机构关联ID
    stype.UserCode    as stypeCode , 
    stype.FullName as stypename ,
    billIndex.etypeid     , --职员关联ID
    employee.UserCode,
    employee.FullName as etypename,
    billIndex.dtypeid     , --部门关联ID
    department.UserCode as  departmentCode,
    department.FullName  as dtypename  ,
    billIndex.dealbtypeid , --往来单位关联ID
    DealBtype.UserCode as dealbtypeCode,
    DealBtype.FullName  as dealbtypename      ,
    billIndex.btypeid     , --结算单位关联ID
    btype.UserCode as btypeCode,
    btype.FullName    as btypename    ,
    billIndex.ktypeid     , --仓库关联ID
    stock.FullName    as ktypename    ,
    stock.UserCode as stockCode,
    billIndex.totalqty    , --合计数量
    billIndex.atypeid     , --账户关联ID
    atype.UserCode as atypeCode,
    atype.FullName    as atypename    ,
    billIndex.cid         , --币种
    acCurrency.FullName  as cidname  ,
    billIndex.ntotalmoney , --原币合计金额 
    billIndex.checke      , --制单人
    billIndex.poster      , --过账人
    billIndex.posttime    , --过账时间
    billIndex.comment     , --摘要
    billIndex.explain        --说明
    from  BillIndex billIndex
    --分支机构
    left join Stype stype on stype.TypeId=billIndex.stypeid
    --职员
    left join Employee employee on employee.TypeId=billIndex.etypeid
    --部门
    left join Department department on department.TypeId=billIndex.dtypeid
    --往来单位
    left join Btype DealBtype on DealBtype.TypeId=billIndex.dealbtypeid
    --结算单位
    left join Btype btype on btype.TypeId=billIndex.BtypeId
    --仓库
    left join Stock stock on stock.TypeId=billindex.KtypeId
    --账户
    left join Atype atype on atype.TypeId=billindex.atypeid
    --币种
    left join Ac_Currency acCurrency on acCurrency.Cid=billindex.Cid
    
    where billindex.ifcheck='t' and billtype=@billType  and billdate between @begindate and @enddate 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_SCCZD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_SCCZD
GO


CREATE PROCEDURE UFO_SCCZD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QuerydoubleBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,16

	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,16)

	--print @sqlcolumn;
	
	if(@numberOfType in ('入库成本'))
	begin
		set @sql = 'select @re='+@sqlcolumn+' from #billnumberid b,disassemblebill sgcb,InOutstocktable bill  
		where sgcb.BillNumberId=b.typeid and bill.billnumberid = b.typeid and sgcb.ID=bill.id and sgcb.InOrOut=''I'''
	end
	else if(@numberOfType in ('出库成本'))
	begin
		set @sql = 'select @re='+@sqlcolumn+' from #billnumberid b,disassemblebill sgcb,InOutstocktable bill  
		where sgcb.BillNumberId=b.typeid and bill.billnumberid = b.typeid and sgcb.ID=bill.id and sgcb.InOrOut=''O'''
	end
	
	--print @sql;


	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_SKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_SKD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-收款单
-- =============================================
CREATE PROCEDURE UFO_SKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,4

 
	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,4)

	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,4)
		
	
		
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_SMWXD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_SMWXD
GO


CREATE PROCEDURE UFO_SMWXD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QuerydoubleBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,172
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,172)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,172)
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_STJSD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_STJSD
GO


CREATE PROCEDURE UFO_STJSD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,145
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,145)
	--print @sqlcolumn;
	
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,145)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_STSHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_STSHD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-受托代销收货单(金额)
-- =============================================
CREATE PROCEDURE UFO_STSHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,144

	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,144)
	
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,144)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid and ktypeid<>10000'
	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_STTHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_STTHD
GO


CREATE PROCEDURE UFO_STTHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,146
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,146)
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,146)
	--print @tablename
	
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid and bill.ktypeid<>''10000'''
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_STTJD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_STTJD
GO


CREATE PROCEDURE UFO_STTJD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,147
	
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,147)
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,147)
	--print @tablename
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_SXFHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_SXFHD
GO


CREATE PROCEDURE UFO_SXFHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,170
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,170)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,170)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_TJDBD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_TJDBD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-
-- =============================================
CREATE PROCEDURE UFO_TJDBD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QuerydoubleBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,17


	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,17)
	--print @sqlcolumn;
	
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,17)
	--print @tablename;
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_WTFHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_WTFHD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-受托代销收货单(折后金额,价税合计,成本金额)
-- =============================================
CREATE PROCEDURE UFO_WTFHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,140
	--select * from #billnumberid;

	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,140)
	--print @sqlcolumn;
	
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,140)
	
	--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid and ktypeid<>''10000''' 
	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_WTJSD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_WTJSD
GO


CREATE PROCEDURE UFO_WTJSD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,141
	--select * from #billnumberid
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,141)
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,141)
	--print @tablename
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'-- and ktypeid<>''10000''' 

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_WTTHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_WTTHD
GO


CREATE PROCEDURE UFO_WTTHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,142
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,142)
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,142)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid  and ktypeid<>''10000''' 
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_WXD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_WXD
GO


CREATE PROCEDURE UFO_WXD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,166
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,166)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,166)
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_WXPDC]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_WXPDC
GO


CREATE PROCEDURE UFO_WXPDC
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,174
	
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,174)
	
	--print @sqlcolumn;
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,174)
	--print @tablename;
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_WXPDR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_WXPDR
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-维修品调入单 
-- =============================================
CREATE PROCEDURE UFO_WXPDR
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,173
	--select * from #billnumberid;


	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,173)
	--print @sqlcolumn;


	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,173)
	--print @tablename;
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_WXQJD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_WXQJD
GO


CREATE PROCEDURE UFO_WXQJD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,167
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,167)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,167)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_XJD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_XJD
GO


CREATE PROCEDURE UFO_XJD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,185
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,185)
	
	set @sql = 'select @re='+@sqlcolumn+' from askpricebill bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_XJFYD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_XJFYD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-现金费用单 
-- =============================================
CREATE PROCEDURE UFO_XJFYD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,158
	
	
	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,158)
	
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,158)

	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_XSCKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_XSCKD
GO


CREATE PROCEDURE UFO_XSCKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,11
	
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,11)
	print @sqlcolumn;

	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,11)
	print @tablename;
	
	
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_XSDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_XSDD
GO


CREATE PROCEDURE UFO_XSDD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryorderBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,300
	
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,300)

	
	set @sql = 'select @re='+@sqlcolumn+' from orderbill bill,#billnumberid id where bill.billnumberid = id.typeid'
	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_XSFYFT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_XSFYFT
GO


CREATE PROCEDURE UFO_XSFYFT
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,206
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,206)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,206)
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_XSHHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_XSHHD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-销售换货单(抹零金额)
-- =============================================
CREATE PROCEDURE UFO_XSHHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(billnumberid numeric(20))
	insert into #billnumberid exec A_UFO_QuerydoubleBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,160
	--select * from #billnumberid;
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,160)
	--print @sqlcolumn
	
	if(@numberOfType in ('入库金额','入库折后金额','入库价税合计','入库成本'))
	begin
		set @sql = 'select @re='+@sqlcolumn+' from #billnumberid b,salegoodsexchangebill sgcb,InOutstocktable bill  where sgcb.BillNumberId=b.billnumberid and bill.billnumberid = sgcb.billnumberid and sgcb.id=bill.id  and sgcb.InOrOut=''I'''
	end
	else if(@numberOfType in ('出库金额','出库折后金额','出库价税合计','出库成本'))
	begin
		set @sql = 'select @re='+@sqlcolumn+' from #billnumberid b,salegoodsexchangebill sgcb,InOutstocktable bill  where sgcb.BillNumberId=b.billnumberid and bill.billnumberid = sgcb.billnumberid and sgcb.id=bill.id and sgcb.InOrOut=''O'''
	end
	else 
	begin
		set @sql = 'select @re='+@sqlcolumn+' from billindex bill,#billnumberid id where bill.billnumberid = id.billnumberid '
	end
	
	--print @sql;

	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_XSTHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_XSTHD
GO


CREATE PROCEDURE UFO_XSTHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,45
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,45)
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,45)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_YFJSD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_YFJSD
GO


CREATE PROCEDURE UFO_YFJSD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,129
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,129)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,129)
		--print @tablename
		
	--查询到指定表体的结算单位
	create	TABLE #btype(TypeId VARCHAR(50))
	INSERT INTO #btype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)


	if(len(@btypeid)=0)
	begin
		set @sql ='select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid '
	end
	else
	begin
	    set @sql ='select @re=sum(total) from addebtbill bill,#billnumberid id  where bill.billnumberid = id.typeid and bill.btypeid in(select typeid from #btype ) '
	end
		
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_YFKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_YFKD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-预付款单
-- Function: 金额
-- =============================================
CREATE PROCEDURE UFO_YFKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,190
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,190)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,190)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_YFZJD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_YFZJD
GO


CREATE PROCEDURE UFO_YFZJD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,128
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,128)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,128)
		
	--查询到指定表体的结算单位
	create	TABLE #btype(TypeId VARCHAR(50))
	INSERT INTO #btype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)


	if(len(@btypeid)=0)
	begin
		set @sql ='select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid '
	end
	else
	begin
	    set @sql ='select @re=sum(total) from addebtbill bill,#billnumberid id  where bill.billnumberid = id.typeid and bill.btypeid in(select typeid from #btype ) '
	end
	
	--print @sql;

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_YSJSD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_YSJSD
GO


CREATE PROCEDURE UFO_YSJSD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,115
	

	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,115)
	

	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,115)
	
	
	--查询到指定表体的结算单位
	create	TABLE #btype(TypeId VARCHAR(50))
	INSERT INTO #btype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)


	if(len(@btypeid)=0)
	begin
		set @sql ='select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid '
	end
	else
	begin
	    set @sql ='select @re=sum(total) from addebtbill bill,#billnumberid id  where bill.billnumberid = id.typeid and bill.btypeid in(select typeid from #btype ) '
	end
	
	--print @sql;

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_YSKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_YSKD
GO


CREATE PROCEDURE UFO_YSKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,189
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,189)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,189)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_YSZJD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_YSZJD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-应收增加单 
-- =============================================

CREATE PROCEDURE UFO_YSZJD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20));
	
	insert into #billnumberid exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,116;
	
	--select * from #billnumberid;
		
	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,116);
	
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,116);
	--print @tablename;
	
	--查询到指定表体的结算单位
	create	TABLE #btype(TypeId VARCHAR(50))
	INSERT INTO #btype(TypeId)	
	SELECT TypeId FROM DBO.F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)


	if(len(@btypeid)=0)
	begin
		set @sql ='select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid '
	end
	else
	begin
	    set @sql ='select @re=sum(total) from addebtbill bill,#billnumberid id  where bill.billnumberid = id.typeid and bill.btypeid in(select typeid from #btype ) '
	end


	--print @sql;
			
	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output;
	select @total
	
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_YWPZ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_YWPZ
GO


CREATE PROCEDURE UFO_YWPZ
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,159
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,159)
	
	set @sql = 'select @re='+@sqlcolumn+' from AccountCredence bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_ZCBMD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_ZCBMD
GO


CREATE PROCEDURE UFO_ZCBMD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,85
	
	--select * from #billnumberid
	
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,85)
	--print @sqlcolumn
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,85)
    --print @tablename
    
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_ZCGMD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_ZCGMD
GO

-- =============================================
-- Author:		杨川
-- Create date: 2014-09-11
-- Description:	自定义报表函数取值-固定资产（项目）购买
-- =============================================
CREATE PROCEDURE UFO_ZCGMD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,84

	--取值字段
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,84)
	
	--取值表
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,84)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_ZCZJD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_ZCZJD
GO


CREATE PROCEDURE UFO_ZCZJD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,78
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,78)
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,78)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_ZJGHD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_ZJGHD
GO


CREATE PROCEDURE UFO_ZJGHD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,168
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,168)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,168)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_ZKD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_ZKD
GO


CREATE PROCEDURE UFO_ZKD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40), @total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,77
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,77)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,77)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'

	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[UFO_ZSD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].UFO_ZSD
GO


CREATE PROCEDURE UFO_ZSD
(
	@StypeId	VARCHAR(8000),	--分支机构 
    @begindate	VARCHAR(200),		--开始时间
    @enddate	VARCHAR(200),		--结束日期
    @dealbtypeid  	VARCHAR(8000), 		--往来单位
    @btypeid  	VARCHAR(8000),
	@EtypeId	VARCHAR(8000),
	@KTypeId    VARCHAR(8000),
	@dtypeId  	VARCHAR(8000),
    @cid VARCHAR(200), --币种id
    @numberOfType Varchar(200), --取数类型
    @OperatorId	VARCHAR(50)		--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE  @sqlcolumn varchar(400),@sql nvarchar(max)='', @tablename varchar(40),@total  NUMERIC(24, 10) =0.00--返回值
	--出符合条件的billnumberid
	create table #billnumberid(typeid numeric(20))
	insert into #billnumberid
	exec A_UFO_QueryBillnumberid @StypeId,@begindate,@enddate,@dealbtypeid,@btypeid,@EtypeId,@KTypeId,@dtypeId,@cid,@OperatorId,139
	--出列名
	select @sqlcolumn = dbo.F_GetNumberOfType(@numberOfType, @cid,139)
	
	--出表名
	select @tablename = dbo.F_GetBIllNumberOfType(@numberOfType,139)
		--print @tablename
	set @sql = 'select @re='+@sqlcolumn+' from '+@tablename+' bill,#billnumberid id where bill.billnumberid = id.typeid'
	EXEC sp_executesql @sql,N'@re  NUMERIC(24, 10)  output',@total output
	select @total
	drop table #billnumberid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryNCD]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].WEB_QueryNCD
GO
          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--================================================
--by:glj	
--date:2015-12-21
--function:年初贷方余额
--================================================
CREATE PROC WEB_QueryNCD
(
	@STypeId VARCHAR(50) ,		-- 分支机构
	@AUserCode VARCHAR(400) ,	-- 会计科目编号
	@Cid VARCHAR(20) = '' ,		-- 币别
	@FYear INT ,				-- 会计年度
	@FPeriod INT ,				-- 会计期间
	@Draft INT ,				-- 包含未记账的凭证 0.不包含  1.包含
	@Fdc INT ,					-- 科目的余额方向
	@Value VARCHAR(50) ,		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
	@AssiValue VARCHAR(MAX) ,	-- 辅助核算列表  [分支机构=A,客户=B]
	@OperatorID VARCHAR(100),	--操作员ID
	@DepartmentID VARCHAR(50)	--辅助核算 部门ID
)
--@encode$--
--@encode$--
AS
SET NOCOUNT ON 
	--查询条件选择部门
	IF @DepartmentID<>''
		BEGIN
			DECLARE @DUserCode	VARCHAR(200)=''
			SELECT @DUserCode=usercode FROM Department WHERE TypeId=@DepartmentID
			DECLARE @RET INT=0
			SELECT @RET=CHARINDEX('%',@AssiValue,1)
			IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1
				SET @AssiValue='部门='+@DUserCode+'%'+SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
			ELSE 
				SET @AssiValue=@AssiValue+'部门='+@DUserCode+'%'
		END
	DECLARE 
		@Total		 NUMERIC(24, 10) =0.00 ,
		@ATypeId	VARCHAR(50) ,
		@AFdc		INT 
				
	--只取本位币
	SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
		
	--分支机构权限检查
	DECLARE @SType TABLE ( TypeId VARCHAR(50) )
	--辅助核算
	DECLARE @Assists TABLE(Ascids INT ,FieldValue VARCHAR(50),UserCode VARCHAR(200))
	--会计科目
	DECLARE @AType TABLE(TypeId VARCHAR(50) ,Fdc INT ,STypeId VARCHAR(50))
		
	INSERT INTO @SType(TypeId)
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID)			
	
	--如果选中分支该操作员没有权限，直接返回0
	IF NOT EXISTS(SELECT TOP 1 1 FROM @SType)
		RETURN 0
	
	--获取科目余额方向
	IF NOT EXISTS(SELECT  TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode)
		RETURN 0 
	ELSE 
		SELECT  
			@AFdc = Fdc,
			@ATypeId=TypeId
		FROM Ac_Account
		WHERE 
			StypeId = @STypeId 
			AND UserCode = @AUserCode
		
	INSERT INTO @AType(TypeId,Fdc,STypeId)
	SELECT  
		A.TypeId,
		A.Fdc,
		A.StypeId
	FROM Ac_Account A
	INNER JOIN @SType S ON S.TypeId=A.StypeId AND A.TypeId LIKE @ATypeId+'%'
	
	--如果辅助核算不为空
	IF(ISNULL(@AssiValue,'')<>'')
		BEGIN
			INSERT INTO @Assists(Ascids,FieldValue,UserCode)
            SELECT 
				Ascids,
                FieldValue,
                UserCode
            FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)
		END
	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND SFYear=@FYear)
		BEGIN
			IF ISNULL(@AssiValue,'')=''
				BEGIN
					SELECT @Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND A.Fdc=@AFdc THEN I.iniYTotal ELSE -I.iniYTotal END),0)
					FROM Ac_IniAccount I
					INNER JOIN @SType S ON S.TypeId=I.STypeId
					INNER JOIN @AType A ON A.TypeId=I.ATypeId AND A.STypeId=S.TypeId
					WHERE 
						I.FYear<=@FYear
				END
			ELSE IF ISNULL(@AssiValue,'')<>''
				BEGIN
					SELECT
						@Total+=ISNULL(SUM(CASE WHEN @Fdc IN(0,1) AND A.Fdc=@AFdc THEN D.iniYTotal ELSE -D.iniYTotal END),0)
					FROM Ac_IniAccount_Assist_CheckItems_Detail D
					INNER JOIN @SType S ON S.TypeId=D.STypeId
					INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
					INNER JOIN (
								SELECT 
									D.STypeId,
									D.ATypeId,
									MAX(D.Ascids) Ascids
								FROM Ac_IniAccount_Assist_CheckItems_Detail D
								INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids AND ((A1.FieldValue<>'' AND  D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
								WHERE 
									D.FYear=@FYear
									AND D.FPeriod=@FPeriod
								GROUP BY D.STypeId,D.ATypeId
								) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids
					WHERE 
						D.FYear<=@FYear
						AND D.FPeriod=@FPeriod
					
				END
		END
	ELSE 
		BEGIN
			DECLARE 
				@Period INT,	--查询科目余额表期间值
				@Year INT		--查询科目余额表年度值

				
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear=@FYear AND STypeId=@STypeId)
				BEGIN
					SET @Year=@FYear
					SELECT @Period=MIN(FMonth) FROM Ac_Period WHERE FYear=@Year
				END	
			ELSE 
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear<@FYear  AND STypeId=@STypeId)
						BEGIN
							SELECT @Year=MAX(FYear) FROM Ac_Balance
							SELECT @Period=MAX(FPeriod) FROM Ac_Period WHERE FYear=@Year
						END
				END
				

			IF ISNULL(@AssiValue,'')=''
				BEGIN
					SELECT 
						@Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN CASE WHEN @Year<@FYear THEN B.FEndBalance ELSE B.FBeginBalance END ELSE CASE WHEN @Year<@FYear THEN -B.FEndBalance ELSE -B.FBeginBalance END END),0)
					FROM Ac_Balance  B 
					INNER JOIN @SType S ON S.TypeId=B.STypeId
					INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
					WHERE 
						B.FYear=@Year
						AND B.FPeriod=@Period
						AND B.Cid=0
				END
			ELSE IF ISNULL(@AssiValue,'')<>''
				BEGIN
					SELECT
						@Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN CASE WHEN @Year<@FYear THEN D.FEndBalance ELSE D.IniTotal END ELSE CASE WHEN @Year<@FYear THEN -D.FEndBalance ELSE -D.IniTotal END END),0)
					FROM Ac_Balance_Assist_CheckItems_Detail D
					INNER JOIN @SType S ON D.STypeId=S.TypeId
					INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
					INNER JOIN (
								SELECT 
									D.STypeId,
									D.ATypeId,
									MAX(D.Ascids) Ascids 
								FROM Ac_Balance_Assist_CheckItems_Detail D
								INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids AND ((A1.FieldValue<>'' AND D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
								WHERE 
									D.FYear=@Year
									AND D.FPeriod=@Period
									AND D.Cid=0
								GROUP BY D.STypeId,D.ATypeId
								) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids
					WHERE 
						D.FYear=@Year
						AND D.FPeriod=@Period
						AND D.Cid=0
				END
		END
		IF @Draft=1
			BEGIN
				IF ISNULL(@AssiValue,'')=''
					BEGIN
						SELECT @Total+=ISNULL(SUM(CASE WHEN @AFdc<>AA.Fdc AND AA.Fdc=1 THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END),0)
						FROM Ac_Voucher_Bill B
						INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
						INNER JOIN @SType S ON S.TypeId=B.STypeId 
						INNER JOIN @AType AA ON AA.TypeId=B.ATypeId AND AA.StypeId=@StypeID
						WHERE
							B.FYear<@FYear
					END
				ELSE IF ISNULL(@AssiValue,'')<>''
					BEGIN
						SELECT @Total+=ISNULL(SUM(CASE WHEN @AFdc<>A.Fdc AND A.Fdc=1 THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END),0)
						FROM Ac_Voucher_Bill B
						INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
						INNER JOIN @SType S ON S.TypeId=B.STypeId 
						INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.StypeId=S.TypeId
						INNER JOIN (
										SELECT D.BillNumberId,D.vBId
										FROM Ac_Voucher_Bill_Assist_CheckItems D 
										INNER JOIN @Assists A1 ON A1.UserCode=D.typeName AND ((A1.FieldValue<>'' AND  D.TypeId LIKE A1.FieldValue+'%') OR A1.FieldValue='')
										GROUP BY D.BillNumberId,D.vBId											
									) F ON F.BillNumberId=B.BillNumberId AND F.vBId=B.ID
						WHERE
							B.FYear<@FYear
						GROUP BY A.FDC
					END
			END	


	--取科目的年初贷方数据；如该科目年初数据为贷方负数应看作是年初借方数据，此时该函数取值为零；
	IF(@AFdc=1 AND @Total>0)
		SET @Total=0
	ELSE IF(@AFdc=1 AND @Total<0)
		SET @Total=ABS(@Total)
	ELSE IF(@AFdc=-1 AND @Total>0)
		SET @Total=@Total
	ELSE IF(@AFdc=-1 AND @Total<0)
		SET @Total=0
	
SELECT @Total
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryNCJ]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].WEB_QueryNCJ
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--===========================================
--by:glj
--date:2015-12-08
--function:取科目的年初借方数据；如该科目年初数据为借方负数应看作是年初贷方数据，此时该函数取值为零
--=============================================
CREATE PROC WEB_QueryNCJ
(
	@STypeId VARCHAR(50) ,		--分支机构
	@AUserCode VARCHAR(400) ,	--会计科目编号
	@Cid VARCHAR(20) = '' ,		--币别
	@FYear INT ,				--会计年度
	@FPeriod INT ,				--会计期间
	@Draft INT ,				--包含未记账的凭证 0.不包含  1.包含
	@Fdc INT ,					--科目的余额方向
	@Value VARCHAR(50) ,		--取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
	@AssiValue VARCHAR(MAX) ,	--辅助核算列表  [分支机构=A,客户=B]
	@OperatorID VARCHAR(100),	--操作员ID
	@DepartmentID VARCHAR(50)	--辅助核算 部门ID
)
--@encode$--
--@encode$--
AS
SET NOCOUNT ON 
	--查询条件选择部门
	IF @DepartmentID<>''
		BEGIN
			DECLARE @DUserCode	VARCHAR(200)=''
			SELECT @DUserCode=usercode FROM Department WHERE TypeId=@DepartmentID
			DECLARE @RET INT=0
			SELECT @RET=CHARINDEX('%',@AssiValue,1)
			IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1
				SET @AssiValue='部门='+@DUserCode+'%'+SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
			ELSE 
				SET @AssiValue=@AssiValue+'部门='+@DUserCode+'%'
		END
	DECLARE 
		@Total		 NUMERIC(24, 10) =0.00 ,
		@ATypeId	VARCHAR(50) ,
		@AFdc		INT 
				
	--只取本位币
	SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
		
	--分支机构权限检查
	DECLARE @SType TABLE ( TypeId VARCHAR(50) )
	--辅助核算
	DECLARE @Assists TABLE(Ascids INT ,FieldValue VARCHAR(50),UserCode VARCHAR(200))
	--会计科目
	DECLARE @AType TABLE(TypeId VARCHAR(50) ,Fdc INT ,STypeId VARCHAR(50))
		
	INSERT INTO @SType(TypeId)
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID)			
	
	--如果选中分支该操作员没有权限，直接返回0
	IF NOT EXISTS(SELECT TOP 1 1 FROM @SType)
		RETURN 0
	
	--获取科目余额方向
	IF NOT EXISTS(SELECT  TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode)
		RETURN 0 
	ELSE 
		SELECT  
			@AFdc = Fdc,
			@ATypeId=TypeId
		FROM Ac_Account
		WHERE 
			StypeId = @STypeId 
			AND UserCode = @AUserCode
		
	INSERT INTO @AType(TypeId,Fdc,STypeId)
	SELECT  
		A.TypeId,
		A.Fdc,
		A.StypeId
	FROM Ac_Account A
	INNER JOIN @SType S ON S.TypeId=A.StypeId AND A.TypeId LIKE @ATypeId+'%'
	
	--如果辅助核算不为空
	IF(ISNULL(@AssiValue,'')<>'')
		BEGIN
			INSERT INTO @Assists(Ascids,FieldValue,UserCode)
            SELECT 
				Ascids,
                FieldValue,
                UserCode
            FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)
		END
	
	IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND SFYear=@FYear)
		BEGIN
			IF ISNULL(@AssiValue,'')=''
				BEGIN
					SELECT @Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN I.iniYTotal ELSE -I.iniYTotal END),0)
					FROM Ac_IniAccount I
					INNER JOIN @SType S ON S.TypeId=I.STypeId
					INNER JOIN @AType A ON A.TypeId=I.ATypeId AND A.STypeId=S.TypeId
					WHERE 
						I.FYear<=@FYear
				END
			ELSE IF ISNULL(@AssiValue,'')<>''
				BEGIN
					SELECT
						@Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN D.iniYTotal ELSE -D.iniYTotal END),0)
					FROM Ac_IniAccount_Assist_CheckItems_Detail D
					INNER JOIN @SType S ON S.TypeId=D.STypeId
					INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
					INNER JOIN (
								SELECT 
									D.STypeId,
									D.ATypeId,
									MAX(D.Ascids) Ascids
								FROM Ac_IniAccount_Assist_CheckItems_Detail D
								INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids AND ((A1.FieldValue<>'' AND  D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
								WHERE 
									D.FYear<=@FYear
									AND D.FPeriod=@FPeriod
								GROUP BY D.STypeId,D.ATypeId
								) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids
					WHERE 
						D.FYear=@FYear
						AND D.FPeriod=@FPeriod
					
				END
		END
	ELSE 
		BEGIN
			DECLARE 
				@Period INT,	--查询科目余额表期间值
				@Year INT		--查询科目余额表年度值

				
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear=@FYear AND STypeId=@STypeId)
				BEGIN
					SET @Year=@FYear
					SELECT @Period=MIN(FMonth) FROM Ac_Period WHERE FYear=@Year
				END	
			ELSE 
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear<@FYear  AND STypeId=@STypeId)
						BEGIN
							SELECT @Year=MAX(FYear) FROM Ac_Balance
							SELECT @Period=MAX(FPeriod) FROM Ac_Period WHERE FYear=@Year
						END
				END
				

			IF ISNULL(@AssiValue,'')=''
				BEGIN
					SELECT 
						@Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN CASE WHEN @Year<@FYear THEN B.FEndBalance ELSE B.FBeginBalance END ELSE CASE WHEN @Year<@FYear THEN -B.FEndBalance ELSE -B.FBeginBalance END END),0)
					FROM Ac_Balance  B 
					INNER JOIN @SType S ON S.TypeId=B.STypeId
					INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
					WHERE 
						B.FYear=@Year
						AND B.FPeriod=@Period
						AND B.Cid=0
				END
			ELSE IF ISNULL(@AssiValue,'')<>''
				BEGIN
					SELECT
						@Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN CASE WHEN @Year<@FYear THEN D.FEndBalance ELSE D.IniTotal END ELSE CASE WHEN @Year<@FYear THEN -D.FEndBalance ELSE -D.IniTotal END END),0)
					FROM Ac_Balance_Assist_CheckItems_Detail D
					INNER JOIN @SType S ON D.STypeId=S.TypeId
					INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
					INNER JOIN (
								SELECT 
									D.STypeId,
									D.ATypeId,
									MAX(D.Ascids) Ascids 
								FROM Ac_Balance_Assist_CheckItems_Detail D
								INNER JOIN @Assists A1 ON A1.Ascids=D.Ascids AND ((A1.FieldValue<>'' AND D.FieldValue LIKE A1.FieldValue+'%') OR A1.FieldValue='')
								WHERE 
									D.FYear=@Year
									AND D.FPeriod=@Period
									AND D.Cid=0
								GROUP BY D.STypeId,D.ATypeId
								) F ON F.STypeId=D.STypeId AND F.ATypeId=D.ATypeId AND F.Ascids=D.Ascids
					WHERE 
						D.FYear=@Year
						AND D.FPeriod=@Period
						AND D.Cid=0
				END
		END
		IF @Draft=1
			BEGIN
				IF ISNULL(@AssiValue,'')=''
					BEGIN
						SELECT @Total+=ISNULL(SUM(CASE WHEN AA.Fdc=1 OR @AFdc<>AA.Fdc THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END),0)
						FROM Ac_Voucher_Bill B
						INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
						INNER JOIN @SType S ON S.TypeId=B.STypeId 
						INNER JOIN @AType AA ON AA.TypeId=B.ATypeId AND AA.StypeId=@StypeID
						WHERE
							B.FYear<@FYear
					END
				ELSE IF ISNULL(@AssiValue,'')<>''
					BEGIN
						SELECT @Total+=ISNULL(SUM(CASE WHEN A.Fdc=1 OR @AFdc<>A.Fdc THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END),0)
						FROM Ac_Voucher_Bill B
						INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
						INNER JOIN @SType S ON S.TypeId=B.STypeId 
						INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.StypeId=S.TypeId
						INNER JOIN (
										SELECT D.BillNumberId,D.vBId
										FROM Ac_Voucher_Bill_Assist_CheckItems D 
										INNER JOIN @Assists A1 ON A1.UserCode=D.typeName AND ((A1.FieldValue<>'' AND  D.TypeId LIKE A1.FieldValue+'%') OR A1.FieldValue='')
										GROUP BY D.BillNumberId,D.vBId											
									) F ON F.BillNumberId=B.BillNumberId AND F.vBId=B.ID
						WHERE
							B.FYear<@FYear
						GROUP BY A.FDC
					END
			END	
			
--取科目的年初借方数据；如该科目年初数据为借方负数应看作是年初贷方数据，此时该函数取值为零
IF(@AFdc=1 AND @Total>0)
	SET @Total=@Total
ELSE IF(@AFdc=1 AND @Total<0)
	SET @Total=0
ELSE IF(@AFdc=-1 AND @Total>0)
	SET @Total=0
ELSE IF(@AFdc=-1 AND @Total<0)
	SET @Total=ABS(@Total)
	
SELECT @Total

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryQMD]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].WEB_QueryQMD
GO
          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--================================================
--by:glj	
--date:2015-12-21
--function:期末贷方余额
--================================================
CREATE PROC WEB_QueryQMD
(
	@STypeId VARCHAR(50) ,		-- 分支机构
	@AUserCode VARCHAR(400) ,	-- 会计科目编号
	@Cid VARCHAR(20) = '' ,		-- 币别
	@FYear INT ,				-- 会计年度
	@FPeriod INT ,				-- 会计期间
	@Draft INT ,				-- 包含未记账的凭证 0.不包含  1.包含
	@Fdc INT ,					-- 科目的余额方向
	@Value VARCHAR(50) ,		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
	@AssiValue VARCHAR(MAX) ,	-- 辅助核算列表  [分支机构=A,客户=B]
	@OperatorID VARCHAR(100),	--操作员ID
	@DepartmentID VARCHAR(50)	--辅助核算 部门ID
)
--@encode$--
--@encode$--
AS
SET NOCOUNT ON 

--查询条件选择部门
IF @DepartmentID<>''
	BEGIN
		DECLARE @DUserCode	VARCHAR(200)=''
		SELECT @DUserCode=usercode FROM Department WHERE TypeId=@DepartmentID
		DECLARE @RET INT=0
		SELECT @RET=CHARINDEX('%',@AssiValue,1)
		IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1
			SET @AssiValue='部门='+@DUserCode+'%'+SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
		ELSE 
			SET @AssiValue=@AssiValue+'部门='+@DUserCode+'%'
	END
DECLARE
	@heard		VARCHAR(MAX)='',
	@Total		NUMERIC(22,10)=0.00 ,
	@ATypeId	VARCHAR(50) ,
	@AFdc		INT,
	@J			INT=1	--辅助核算参数共有多少条信息
	
--只取本位币
SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
	
--分支机构权限检查
DECLARE @SType TABLE(TypeId VARCHAR(50))
--辅助核算
DECLARE @Assists TABLE(NID INT IDENTITY(1,1),Ascids INT,UserCode VARCHAR(200) ,FieldValue VARCHAR(MAX))
--会计科目
DECLARE @AType TABLE(TypeId VARCHAR(50) ,Fdc INT ,STypeId VARCHAR(50))
	
INSERT INTO @SType(TypeId)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID)			

--如果选中分支该操作员没有权限，直接返回0
IF NOT EXISTS(SELECT TOP 1 1 FROM @SType)
	RETURN 0

--获取科目余额方向
IF NOT EXISTS(SELECT  TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode)
	RETURN 0 
ELSE 
	SELECT  
		@AFdc = Fdc,
		@ATypeId=TypeId
	FROM Ac_Account
	WHERE 
		StypeId = @STypeId 
		AND UserCode = @AUserCode
	
INSERT INTO @AType(TypeId,Fdc,STypeId)
SELECT  
	A.TypeId,
	A.Fdc,
	A.StypeId
FROM Ac_Account A
INNER JOIN @SType S ON S.TypeId=A.StypeId AND A.TypeId LIKE @ATypeId+'%'

--如果辅助核算不为空
IF(ISNULL(@AssiValue,'')<>'')
	BEGIN
		INSERT INTO @Assists(Ascids,UserCode,FieldValue)
        SELECT 
			D.AscIds,
			D.UserCode,
            FieldValue
        FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)  F
        INNER JOIN Ac_Assist_CheckItems	 D ON D.AscIds=F.Ascids
        
        SELECT @J=@@ROWCOUNT
	END

IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=0)
	BEGIN
		IF ISNULL(@AssiValue,'')=''
			BEGIN
				SELECT @Total+=ISNULL(SUM(CASE WHEN @AFdc=A.Fdc THEN I.IniTotal ELSE -I.IniTotal END),0)
				FROM Ac_IniAccount I
				INNER JOIN @SType S ON S.TypeId=I.STypeId
				INNER JOIN @AType A ON A.TypeId=I.ATypeId AND A.STypeId=S.TypeId
			END					 
		ELSE IF ISNULL(@AssiValue,'')<>''
			BEGIN
		SELECT @Total=ISNULL(SUM(CASE WHEN @AFdc=A.Fdc THEN D.IniTotal ELSE -D.IniTotal END),0) 
		FROM Ac_IniAccount_Assist_CheckItems D
		INNER JOIN @SType S ON S.TypeId=D.STypeId
		INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
		WHERE EXISTS(
			SELECT 
				TOP 1 1 
			FROM Ac_IniAccount_Assist_CheckItems_Detail D	
			INNER JOIN @SType S ON S.TypeId=D.STypeId
			INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
			WHERE 
				D.ATypeId=D.ATypeId		
				AND EXISTS(SELECT TOP 1 1 FROM @Assists WHERE Ascids=D.Ascids AND ((FieldValue<>'' AND D.FieldValue LIKE FieldValue+'%') OR FieldValue=''))
			GROUP BY D.ATypeId
			HAVING COUNT(D.ATypeId)>=@J
			)
				END
	END
ELSE 
	BEGIN
		DECLARE 
			@Period INT,	--查询科目余额表期间值
			@Year INT		--查询科目余额表年度值
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE CONVERT(INT,FYear)<=@FYear )
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE CONVERT(INT,FYear)=@FYear)
					BEGIN
						SET @Year=@FYear
						SELECT @Period=MIN(FMonth) FROM Ac_Period WHERE FYear=@Year
					END	
				ELSE IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE CONVERT(INT,FYear)<@FYear)
					BEGIN
						SELECT @Year=MAX(CONVERT(INT,FYear)) FROM Ac_Balance
						SELECT @Period=MAX(CONVERT(INT,FPeriod)) FROM Ac_Balance WHERE CONVERT(INT,FYear)=@Year
					END
				END

		IF ISNULL(@AssiValue,'')=''
			BEGIN
				SELECT
					@Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN B.FEndBalance ELSE -B.FEndBalance END),0)
				FROM Ac_Balance  B 
				INNER JOIN @SType S ON S.TypeId=B.STypeId
				INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
				WHERE 
					B.FYear=@Year
					AND B.FPeriod=@Period
					AND B.Cid=0
			END
		ELSE IF ISNULL(@AssiValue,'')<>''
			BEGIN	 
				SELECT @Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN D.FEndBalance ELSE -D.FEndBalance END),0)
				FROM Ac_Balance_Assist_CheckItems_Detail D
				INNER JOIN @SType S ON S.TypeId=D.STypeId
				INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
				WHERE 
					D.FYear=@Year
					AND D.FPeriod=@Period
					AND D.Cid=0	
					AND EXISTS(
						SELECT 
							TOP 1 1 
						FROM Ac_Balance_Assist_CheckItems_Detail D	
						INNER JOIN @SType S ON S.TypeId=D.STypeId
						INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
						WHERE 
							D.ATypeId=D.ATypeId	
							AND D.FYear=@Year
							AND D.FPeriod=@Period
							AND D.Cid=0	
							AND EXISTS(SELECT TOP 1 1 FROM @Assists WHERE Ascids=D.Ascids AND ((FieldValue<>'' AND D.FieldValue LIKE FieldValue+'%') OR FieldValue=''))
						GROUP BY D.ATypeId
						HAVING COUNT(D.ATypeId)>=@J
					)
			END
	END
IF @Draft=1
	BEGIN
		IF ISNULL(@AssiValue,'')=''
			BEGIN
				SELECT 
					@Total+=ISNULL(SUM(CASE WHEN @AFdc<>AA.Fdc OR AA.Fdc=1 THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END),0)
				FROM Ac_Voucher_Bill B
				INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
				INNER JOIN @SType S ON S.TypeId=B.STypeId 
				INNER JOIN @AType AA ON AA.TypeId=B.ATypeId AND AA.StypeId=@StypeID
				WHERE
					((B.FYear=@FYear AND B.FPeriod<=@FPeriod) 
						OR B.FYear<@FYear)
			END
		ELSE IF ISNULL(@AssiValue,'')<>''
			BEGIN
			
				SELECT @Total+=ISNULL(SUM(CASE WHEN @AFdc<>A.Fdc AND A.Fdc=1 THEN Bill.FDebitTotal-Bill.FCreditTotal ELSE Bill.FCreditTotal-Bill.FDebitTotal END),0)
				FROM Ac_Voucher_Bill Bill
				INNER JOIN @SType S ON S.TypeId=Bill.STypeId
				INNER JOIN @AType A ON A.TypeId=Bill.ATypeId AND A.STypeId=S.TypeId
				WHERE 
					((Bill.FYear=@FYear AND Bill.FPeriod<=@FPeriod) OR Bill.FYear<@FYear)
					AND EXISTS(
						SELECT 
							TOP 1 1 
						FROM Ac_Voucher_Bill B   
						INNER JOIN Ac_Voucher_Bill_Assist_CheckItems D ON D.BillNumberId=B.BillNumberId AND D.vBId=B.ID  
						INNER JOIN @SType S ON S.TypeId=B.STypeId
						INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
						WHERE 
							((B.FYear=@FYear AND B.FPeriod<=@FPeriod) OR B.FYear<@FYear)
							AND B.ATypeId=Bill.ATypeId
							AND EXISTS(SELECT TOP 1 1 FROM @Assists WHERE UserCode=D.typeName AND ((FieldValue<>'' AND D.TypeId LIKE FieldValue+'%') OR FieldValue=''))
						GROUP BY B.ATypeId
						HAVING COUNT(B.ATypeId)>=@J
					)
			END
	END	
	
--取科目的期末贷方数据；如该科目期末数据为贷方负数应看作是期末借方数据，此时该函数取值为零；
IF(@AFdc=1 AND @Total>0)
	SET @Total=0
ELSE IF(@AFdc=1 AND @Total<0)
	SET @Total=ABS(@Total)
ELSE IF(@AFdc=-1 AND @Total>0)
	SET @Total=@Total
ELSE IF(@AFdc=-1 AND @Total<0)
	SET @Total=0
	
SELECT @Total	
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryQMJ]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].WEB_QueryQMJ
GO
          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--================================================
--by:glj	
--date:2015-12-21
--function:期末借方余额
--================================================
CREATE PROC WEB_QueryQMJ
(
	@STypeId VARCHAR(50) ,		-- 分支机构
	@AUserCode VARCHAR(400) ,	-- 会计科目编号
	@Cid VARCHAR(20) = '' ,		-- 币别
	@FYear INT ,				-- 会计年度
	@FPeriod INT ,				-- 会计期间
	@Draft INT ,				-- 包含未记账的凭证 0.不包含  1.包含
	@Fdc INT ,					-- 科目的余额方向
	@Value VARCHAR(50) ,		-- 取值(如果是父类节点，则取节点下所有数据，否则去科目编号对应的值)
	@AssiValue VARCHAR(MAX) ,	-- 辅助核算列表  [分支机构=A,客户=B]
	@OperatorID VARCHAR(100),	--操作员ID
	@DepartmentID VARCHAR(50)	--辅助核算 部门ID
)
--@encode$--
--@encode$--
AS
SET NOCOUNT ON 

--查询条件选择部门
IF @DepartmentID<>''
	BEGIN
		DECLARE @DUserCode	VARCHAR(200)=''
		SELECT @DUserCode=usercode FROM Department WHERE TypeId=@DepartmentID
		DECLARE @RET INT=0
		SELECT @RET=CHARINDEX('%',@AssiValue,1)
		IF (SELECT CHARINDEX('部门=',@AssiValue,1))>=1
			SET @AssiValue='部门='+@DUserCode+'%'+SUBSTRING(@AssiValue,@RET+1,LEN(@AssiValue))
		ELSE 
			SET @AssiValue=@AssiValue+'部门='+@DUserCode+'%'
	END
DECLARE
	@heard		VARCHAR(MAX)='',
	@Total		NUMERIC(22,10)=0.00 ,
	@ATypeId	VARCHAR(50) ,
	@AFdc		INT,
	@J			INT=1	--辅助核算参数共有多少条信息
	
--只取本位币
SELECT @Cid = Cid FROM Ac_Currency WHERE Sysrow = 1
	
--分支机构权限检查
DECLARE @SType TABLE(TypeId VARCHAR(50))
--辅助核算
DECLARE @Assists TABLE(NID INT IDENTITY(1,1),Ascids INT,UserCode VARCHAR(200) ,FieldValue VARCHAR(MAX))
--会计科目
DECLARE @AType TABLE(TypeId VARCHAR(50) ,Fdc INT ,STypeId VARCHAR(50))
	
INSERT INTO @SType(TypeId)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID)			

--如果选中分支该操作员没有权限，直接返回0
IF NOT EXISTS(SELECT TOP 1 1 FROM @SType)
	RETURN 0

--获取科目余额方向
IF NOT EXISTS(SELECT  TOP 1 1 FROM dbo.Ac_Account WHERE StypeId = @STypeId AND UserCode = @AUserCode)
	RETURN 0 
ELSE 
	SELECT  
		@AFdc = Fdc,
		@ATypeId=TypeId
	FROM Ac_Account
	WHERE 
		StypeId = @STypeId 
		AND UserCode = @AUserCode
	
INSERT INTO @AType(TypeId,Fdc,STypeId)
SELECT  
	A.TypeId,
	A.Fdc,
	A.StypeId
FROM Ac_Account A
INNER JOIN @SType S ON S.TypeId=A.StypeId AND A.TypeId LIKE @ATypeId+'%'

--如果辅助核算不为空
IF(ISNULL(@AssiValue,'')<>'')
	BEGIN
		INSERT INTO @Assists(Ascids,UserCode,FieldValue)
        SELECT 
			D.AscIds,
			D.UserCode,
            FieldValue
        FROM DBO.F_Get_Ac_Assist_CheckItems_Value(@AssiValue)  F
        INNER JOIN Ac_Assist_CheckItems	 D ON D.AscIds=F.Ascids
        
        SELECT @J=@@ROWCOUNT
	END

IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=0)
	BEGIN
		IF ISNULL(@AssiValue,'')=''
			BEGIN
				SELECT @Total+=ISNULL(SUM(ISNULL(CASE WHEN @AFdc=A.Fdc THEN I.iniTotal ELSE -I.iniTotal END,0)),0)
				FROM Ac_IniAccount I
				INNER JOIN @SType S ON S.TypeId=I.STypeId
				INNER JOIN @AType A ON A.TypeId=I.ATypeId AND A.STypeId=S.TypeId
			END					 
		ELSE IF ISNULL(@AssiValue,'')<>''
			BEGIN
				SELECT @Total=ISNULL(SUM(iniTotal),0) 
				FROM Ac_IniAccount_Assist_CheckItems D
				INNER JOIN @SType S ON S.TypeId=D.STypeId
				INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
				WHERE EXISTS(
					SELECT 
						TOP 1 1 
					FROM Ac_IniAccount_Assist_CheckItems_Detail D	
					INNER JOIN @SType S ON S.TypeId=D.STypeId
					INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
					WHERE 
						D.ATypeId=D.ATypeId		
						AND EXISTS(SELECT TOP 1 1 FROM @Assists WHERE Ascids=D.Ascids AND ((FieldValue<>'' AND D.FieldValue LIKE FieldValue+'%') OR FieldValue=''))
					GROUP BY D.ATypeId
					HAVING COUNT(D.ATypeId)>=@J
					)
			END
	END
ELSE 
	BEGIN
		DECLARE 
			@Period INT,	--查询科目余额表期间值
			@Year INT		--查询科目余额表年度值
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE CONVERT(INT,FYear)<=@FYear )
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE CONVERT(INT,FYear)=@FYear)
					BEGIN
						SET @Year=@FYear
						SELECT @Period=MIN(FMonth) FROM Ac_Period WHERE FYear=@Year
					END	
				ELSE IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE CONVERT(INT,FYear)<@FYear)
					BEGIN
						SELECT @Year=MAX(CONVERT(INT,FYear)) FROM Ac_Balance
						SELECT @Period=MAX(CONVERT(INT,FPeriod)) FROM Ac_Balance WHERE CONVERT(INT,FYear)=@Year
					END
				END

		IF ISNULL(@AssiValue,'')=''
			BEGIN
				SELECT
					@Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN B.FEndBalance ELSE -B.FEndBalance END),0)
				FROM Ac_Balance  B 
				INNER JOIN @SType S ON S.TypeId=B.STypeId
				INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
				WHERE 
					B.FYear=@Year
					AND B.FPeriod=@Period
					AND B.Cid=0
			END
		ELSE IF ISNULL(@AssiValue,'')<>''
			BEGIN	 
				SELECT @Total+=ISNULL(SUM(CASE WHEN A.Fdc=@AFdc THEN D.FEndBalance ELSE -D.FEndBalance END),0)
				FROM Ac_Balance_Assist_CheckItems_Detail D
				INNER JOIN @SType S ON S.TypeId=D.STypeId
				INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
				WHERE 
					D.FYear=@Year
					AND D.FPeriod=@Period
					AND D.Cid=0	
					AND EXISTS(
						SELECT 
							TOP 1 1 
						FROM Ac_Balance_Assist_CheckItems_Detail D	
						INNER JOIN @SType S ON S.TypeId=D.STypeId
						INNER JOIN @AType A ON A.TypeId=D.ATypeId AND A.STypeId=S.TypeId
						WHERE 
							D.ATypeId=D.ATypeId	
							AND D.FYear=@Year
							AND D.FPeriod=@Period
							AND D.Cid=0	
							AND EXISTS(SELECT TOP 1 1 FROM @Assists WHERE Ascids=D.Ascids AND ((FieldValue<>'' AND D.FieldValue LIKE FieldValue+'%') OR FieldValue=''))
						GROUP BY D.ATypeId
						HAVING COUNT(D.ATypeId)>=@J
					)
			END
	END
IF @Draft=1
	BEGIN
		IF ISNULL(@AssiValue,'')=''
			BEGIN
				SELECT 
					@Total+=ISNULL(SUM(CASE WHEN AA.Fdc=1 OR @AFdc<>AA.Fdc  THEN B.FdebitTotal-B.FcreditTotal ELSE B.FcreditTotal-B.FdebitTotal END),0)
				FROM Ac_Voucher_Bill B
				INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
				INNER JOIN @SType S ON S.TypeId=B.STypeId 
				INNER JOIN @AType AA ON AA.TypeId=B.ATypeId AND AA.StypeId=@StypeID
				WHERE
					((B.FYear=@FYear AND B.FPeriod<=@FPeriod) 
						OR B.FYear<@FYear)
			END
		ELSE IF ISNULL(@AssiValue,'')<>''
			BEGIN
			
				SELECT @Total+=ISNULL(SUM(CASE WHEN A.Fdc=1 OR @AFdc<>A.Fdc THEN Bill.FDebitTotal-Bill.FCreditTotal ELSE Bill.FCreditTotal-Bill.FDebitTotal END),0)
				FROM Ac_Voucher_Bill Bill
				INNER JOIN @SType S ON S.TypeId=Bill.STypeId
				INNER JOIN @AType A ON A.TypeId=Bill.ATypeId AND A.STypeId=S.TypeId
				WHERE 
					((Bill.FYear=@FYear AND Bill.FPeriod<=@FPeriod) OR Bill.FYear<@FYear)
					AND EXISTS(
						SELECT 
							TOP 1 1 
						FROM Ac_Voucher_Bill B   
						INNER JOIN Ac_Voucher_Bill_Assist_CheckItems D ON D.BillNumberId=B.BillNumberId AND D.vBId=B.ID  
						INNER JOIN @SType S ON S.TypeId=B.STypeId
						INNER JOIN @AType A ON A.TypeId=B.ATypeId AND A.STypeId=S.TypeId
						WHERE 
							((B.FYear=@FYear AND B.FPeriod<=@FPeriod) OR B.FYear<@FYear)
							AND B.ATypeId=Bill.ATypeId
							AND EXISTS(SELECT TOP 1 1 FROM @Assists WHERE UserCode=D.typeName AND ((FieldValue<>'' AND D.TypeId LIKE FieldValue+'%') OR FieldValue=''))
						GROUP BY B.ATypeId
						HAVING COUNT(B.ATypeId)>=@J
					)
			END
	END	
--取科目的期末借方数据；如该科目期末数据为借方负数应看作是期末贷方数据，此时该函数取值为零
IF(@AFdc=1 AND @Total>0)
	SET @Total=@Total
ELSE IF(@AFdc=1 AND @Total<0)
	SET @Total=0
ELSE IF(@AFdc=-1 AND @Total>0)
	SET @Total=0
ELSE IF(@AFdc=-1 AND @Total<0)
	SET @Total=ABS(@Total)
	
SELECT @Total	
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateBtypeArApData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].UpdateBtypeArApData
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--====================================================================
	--功能：升级时处理应收应付期初数据以及通过期初数据生成期初单据
	--作者：Hanlin
	--时间：2012-09-10
--====================================================================
CREATE          PROCEDURE UpdateBtypeArApData
--@encode$--
AS
BEGIN

	DECLARE @cid INT=1,@BasisType int=0,@rate  NUMERIC(24, 10) 
	SELECT @cid=CId,@BasisType=BasisType,@rate=Rate FROM dbo.Ac_Currency WHERE Sysrow=1

	UPDATE	dbo.BType_ArApTotal
	SET		CID			=	@cid,
			nAPTotal	=	ROUND(CASE @BasisType WHEN 0 THEN APTotal/@rate ELSE  APTotal*@rate END ,2),
			nAPTotal00	=	ROUND(CASE @BasisType WHEN 0 THEN APTotal00/@rate ELSE  APTotal00*@rate END ,2),
			nARTotal	=	ROUND(CASE @BasisType WHEN 0 THEN ARTotal/@rate ELSE  ARTotal*@rate END ,2),
			nARTotal00	=	ROUND(CASE @BasisType WHEN 0 THEN ARTotal00/@rate ELSE  ARTotal00*@rate END,2),
			nYSTotal	=	ROUND(CASE @BasisType WHEN 0 THEN YSTotal/@rate ELSE  YSTotal*@rate END ,2),
			nYSTotal00	=	ROUND(CASE @BasisType WHEN 0 THEN YSTotal00/@rate ELSE  YSTotal00*@rate END,2),
			nYFTotal	=	ROUND(CASE @BasisType WHEN 0 THEN YFTotal/@rate ELSE  YFTotal*@rate END ,2),
			nYFTotal00	=	ROUND(CASE @BasisType WHEN 0 THEN YFTotal00/@rate ELSE  YFTotal00*@rate END ,2)
	
	DELETE FROM dbo.BType_ArApTotal WHERE ARTotal=0 AND ARTotal00=0 AND APTotal=0 AND APTotal00=0 AND YSTotal=0 AND YSTotal00=0 AND YFTotal=0 AND YFTotal00=0	
			
	CREATE TABLE #btype_araptotal
	(
		BTypeID varchar (50) NOT NULL,
		STypeID varchar (50) NOT NULL,
		CID	INT null,
		YSYFTotal00 DECIMAL(22,10),
		NYSYFTotal00 DECIMAL(22,10),
		billtype VARCHAR(50),
		Comment VARCHAR(50),
		sort int
	)

	DECLARE @startdate DATETIME=GETDATE()
	SELECT @startdate=DATEADD(day,-1,FBegin) FROM dbo.Ac_Period WHERE FPeriod=FMonth
	--考虑重复升级
	DELETE FROM billindex WHERE isini=1 AND BillType IN(189,190)
	--预收预付期初生成期初单据
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BType_ArApTotal WHERE (YSTotal00<>0 AND nYSTotal00<>0) OR (YFTotal00<>0 AND nYFTotal00<>0))
	BEGIN	
		INSERT INTO #btype_araptotal
		( 
				BTypeID ,
				STypeID ,
				CID ,
				YSYFTotal00 ,
				NYSYFTotal00 ,
				billtype ,
				Comment,
				sort
		)
		SELECT	BTypeID,
				STypeID,
				CID,
				SUM(YSTotal00),
				SUM(nYSTotal00),
				189,
				'预收期初生成',
				0	
		FROM	BType_ArApTotal
		WHERE	YSTotal00<>0 
				AND nYSTotal00<>0
		GROUP BY	BTypeID,
					STypeID,
					CID

		INSERT INTO #btype_araptotal
		( 
				BTypeID ,
				STypeID ,
				CID ,
				YSYFTotal00 ,
				NYSYFTotal00 ,
				billtype ,
				Comment,
				sort
		)
		SELECT	BTypeID,
				STypeID,
				CID,
				SUM(YFTotal00),
				SUM(nYFTotal00),
				190,
				'预付期初生成',
				0	
		FROM	BType_ArApTotal
		WHERE	YFTotal00<>0 
				AND nYFTotal00<>0
		GROUP BY	BTypeID,
					STypeID,
					CID

		UPDATE #btype_araptotal
		SET sort=b.sort
		FROM
		(
			SELECT	RANK() OVER
					(PARTITION BY billtype ORDER BY BTypeID,STypeID,CID)sort,
					STypeID,
					BTypeID,
					cid,
					billtype
			FROM	#btype_araptotal
		)b 
		WHERE	#btype_araptotal.billtype=b.billtype
				AND #btype_araptotal.STypeID=b.STypeID
				AND #btype_araptotal.BTypeID=b.BTypeID
				AND #btype_araptotal.CID=b.cid

		INSERT INTO [dbo].[BillIndex] 
		(
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype WHEN 189 THEN 'IniYskBill-' ELSE 'IniYfkBill-' END + STypeID +'-'+CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			billtype,
			Comment,
			'',
			'',
			BTypeID,
			'',
			'',
			'',
			'f',
			'',
			0,
			YSYFTotal00,
			0,
			0,
			1,
			'',
			0,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			BTypeID,
			cid,	
			@rate,
			NYSYFTotal00,
			0,	
			0,	
			0,	
			(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
			1,
			0,
			1
		FROM	#btype_araptotal b	
		
		DECLARE @atypeid INT=1
		SELECT @atypeid=nid FROM dbo.Ac_Items WHERE UserCode='1001'
		INSERT INTO dbo.PreBill
				( BillNumberId ,
				  BillType ,
				  Comment ,
				  AtypeId ,
				  total ,
				  Stypeid ,
				  vipcardid ,
				  ntotal
				)
		SELECT	  BillNumberId ,
				  BillType ,
				  '' ,
				  @atypeid ,
				  totalmoney ,
				  Stypeid ,
				  -1 ,
				  NTotalMoney
		FROM	dbo.BillIndex
		WHERE BillType IN(189,190) AND IsIni=1 AND ifYearBill=0
	        
		IF @@ERROR<>0
			RAISERROR('处理预收预付生成单据失败！',16,1)            
	END

	TRUNCATE TABLE #btype_araptotal



	--应收应付期初生成单据
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BType_ArApTotal WHERE (ARTotal00<>0 AND nARTotal00<>0) OR (APTotal00<>0 AND nAPTotal00<>0)) 
	BEGIN
		DELETE FROM dbo.BillIndex WHERE IsIni=1 AND BillType NOT IN (190,189)
		INSERT INTO #btype_araptotal
		( 
				BTypeID ,
				STypeID ,
				CID ,
				YSYFTotal00 ,
				NYSYFTotal00 ,
				billtype ,
				Comment ,
				sort
		)
		SELECT	BTypeID,
				STypeID,
				CID,
				ABS(SUM(ARTotal00)),
				ABS(SUM(nARTotal00)),
				CASE WHEN SUM(ARTotal00)>0 
						THEN 116
					 ELSE 115
				END,
				'应收期初生成',
				0			
		FROM	BType_ArApTotal
		GROUP BY	BTypeID,
					STypeID,
					CID
		HAVING SUM(ARTotal00)<>0 AND SUM(nARTotal00)<>0
		
		INSERT INTO #btype_araptotal
		( 
				BTypeID ,
				STypeID ,
				CID ,
				YSYFTotal00 ,
				NYSYFTotal00 ,
				billtype ,
				Comment ,
				sort
		)
		SELECT	BTypeID,
				STypeID,
				CID,
				ABS(SUM(APTotal00)),
				ABS(SUM(nAPTotal00)),
				CASE WHEN SUM(APTotal00)>0 
						THEN 128
					 ELSE 129
				END,
				'应付期初生成',
				0			
		FROM	BType_ArApTotal
		GROUP BY	BTypeID,
					STypeID,
					CID
		HAVING SUM(APTotal00)<>0 AND SUM(nAPTotal00)<>0
	END
		
	IF EXISTS(SELECT 1 FROM #btype_araptotal) 
	BEGIN
		INSERT INTO [dbo].[BillIndex] 
		(
			[vipczmoney],
			[BillDate],
			[BillCode],
			[BillType],
			[Comment],
			[atypeid],
			[ptypeid],
			[btypeid],
			[etypeid],
			[ktypeid],
			[ktypeid2],
			[ifcheck],
			[checke],
			[totalqty],
			[totalmoney],
			[totalinmoney],
			[tax],
			[period],
			[explain], 
			[draft],
			[RedWord],
			[orderid],
			[waybillcode],
			[goodsnumber],
			[packway],
			[Tel],
			[preferencemoney],
			[AlertDay],
			[ID],
			[Assessor],
			[IfAudit],
			[Audit_explain],
			[DtypeId],
			[VipCardID],
			[KTypeID3],
			[LinkMan],
			[LinkTel],
			[LinkAddr],
			[wxManID],
			[JieJianBillNumberID],
			[JieJianID],
			[BaoXiuBillNumberID],
			[BaoXiuID],
			[BuyDate],
			[Serial],
			[wxTotal],
			[ErrDes],
			[ifHideJieJian],
			[ifWX],
			[IfBargainOn],
			[Stypeid],
			[FromBillNumberID],
			[CostSale],
			[ifmulaccount],
			otherinouttype,
			PosBillType,
			checkTime,
			LastUpdateTime,
			ShareMode,
			uf1,
			uf2,
			uf3,
			uf4,
			uf5,
			DEALBTYPEID,
			cid,	
			rate,	
			ntotalmoney,
			ntotalinmoney,	
			npreferencemoney,	
			nvipczmoney,	
			atypeid1,
			billproperty,
			ncompletetotal,
			IsIni
		)

		SELECT	
			0.00,
			CONVERT(DATE, @startdate),
			CASE billtype 
				WHEN '116' THEN 'IniYzBill-' 
				WHEN '115' THEN 'IniYjBill-' 
				WHEN '128' THEN 'IniFzBill-'
				WHEN '129' THEN 'IniFjBill-'
			END + STypeID+'-'+CONVERT(VARCHAR(10),@startdate,120)+'-'+CAST(sort AS VARCHAR(10)),
			billtype,
			Comment,
			'',
			'',
			'',
			'',
			'',
			'',
			'f',
			'',
			0,
			YSYFTotal00,
			0,
			0,
			1,
			'',
			0,
			0,
			0,
			'',
			'',
			'',
			'',
			0,
			9999,
			0,
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'-1',
			'-1',
			'-1',
			'-1',
			'',
			'',
			0,
			'',
			0,
			0,
			0,
			STypeID,
			0,
			0,
			0,
			-1,
			'',
			@startdate,
			NULL,
			0,
			'',
			'',
			'',
			'',
			'',
			'',
			cid,	
			@rate,	
			NYSYFTotal00,
			0,	
			0,	
			0,	
			(SELECT AtypeId from dbo.BillAtype ba WHERE ba.StypeId=b.stypeid AND ba.BillTypeId=b.billtype ),
			1,
			0,
			1
		FROM
		(
			SELECT	RANK() OVER
					(PARTITION BY billtype ORDER BY stypeid,cid)sort,
					Stypeid,
					CID,
					BillType,
					Comment,
					SUM(YSYFTotal00) AS YSYFTotal00,
					SUM(NYSYFTotal00) AS NYSYFTotal00
			FROM #btype_araptotal
			GROUP BY Stypeid,CID,BillType,Comment
		)b	

		INSERT INTO dbo.AdDebtBill
		( 
				  BillNumberId ,
				  Comment ,
				  BtypeId ,
				  total ,
				  CompleteTotal ,
				  Stypeid ,
				  NTotal ,
				  NCompleteTotal
		)
		SELECT	  b.BillNumberId,
				  '',
				  ba.btypeid,
				  YSYFTotal00,
				  0,
				  ba.stypeid,
				  nYSYFTotal00,
				  0
		FROM	#btype_araptotal ba
		INNER JOIN dbo.BillIndex b ON ba.stypeid=b.Stypeid AND ba.cid=b.cid AND ba.billtype=b.BillType
		WHERE	b.BillType IN (116,115,128,129)
				AND b.IsIni=1
				AND ifYearBill=0
					
		IF @@ERROR<>0
			RAISERROR('处理应收应生成单据失败！',16,1)       
	END

	DROP TABLE #btype_araptotal

END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateCargoIDDefault]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[UpdateCargoIDDefault]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇	
	日期：2013-04-09
	描述：
*/
CREATE PROCEDURE UpdateCargoIDDefault
--@encode$--
AS
SET NOCOUNT ON

--商品档案默认货位
UPDATE S 
	SET CargoId=C.CargoID
FROM DefaultStock S 
INNER JOIN stock K ON K.typeId=S.ktypeid AND S.CargoId<>0
INNER JOIN CargoType C ON C.KtypeID=K.typeId AND C.IsDefault=1

--零售单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE retailbill SET CargoID=c.CargoID FROM dbo.retailBill a INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId INNER JOIN dbo.CargoType  c  ON b.ktypeid=c.KtypeID WHERE c.IsDefault=1
--销售订单,销售出库单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.OrderBill SET CargoID=b.CargoID FROM dbo.OrderBill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1
--销售退货单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.salebackbill SET CargoID=b.CargoID FROM dbo.salebackbill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1
--销售换货单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.salegoodsexchangebill SET CargoID=b.CargoID FROM dbo.salegoodsexchangebill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1
--赠送单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE givebill SET CargoID=c.CargoID FROM dbo.givebill a INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId INNER JOIN dbo.CargoType  c  ON b.ktypeid=c.KtypeID WHERE c.IsDefault=1
--委托代销发货单,委托代销退货单,委托代销调价单,委托代销结算单,受托代销收货单,受托代销退货单,受托代销调价单,受托代销结算单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.commissionbill SET CargoID=b.CargoID FROM dbo.commissionbill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1
--采购入库单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.BuyBill SET CargoID=b.CargoID FROM dbo.BuyBill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1
--采购退货单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.buybackbill SET CargoID=b.CargoID FROM dbo.buybackbill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1
--采购换货单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.buygoodsexchangebill SET CargoID=b.CargoID FROM dbo.buygoodsexchangebill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1
--获赠单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE givemebill SET CargoID=c.CargoID FROM dbo.givemebill a INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId INNER JOIN dbo.CargoType  c  ON b.ktypeid=c.KtypeID WHERE c.IsDefault=1
--同价调拨单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.movebill SET InCargoID=b.CargoID FROM dbo.movebill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid2=b.KtypeID WHERE b.IsDefault=1
UPDATE dbo.movebill SET OutCargoID=b.CargoID FROM dbo.movebill a  INNER JOIN dbo.CargoType  b  ON a.KTypeId=b.KtypeID WHERE b.IsDefault=1
--变价调拨单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.movebjbill SET InCargoID=b.CargoID FROM dbo.movebjbill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid2=b.KtypeID WHERE b.IsDefault=1
UPDATE dbo.movebjbill SET OutCargoID=b.CargoID FROM dbo.movebjbill a  INNER JOIN dbo.CargoType  b  ON a.KTypeId=b.KtypeID WHERE b.IsDefault=1
--分支机构调拨出库单,分支机构调拨入库单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.stypemovebill SET InCargoID=b.CargoID FROM dbo.stypemovebill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid2=b.KtypeID WHERE b.IsDefault=1
UPDATE dbo.stypemovebill SET OutCargoID=b.CargoID FROM dbo.stypemovebill a  INNER JOIN dbo.CargoType  b  ON a.KTypeId=b.KtypeID WHERE b.IsDefault=1
--其他出库单，其他入库单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.otherinoutbill SET CargoID=b.CargoID FROM dbo.otherinoutbill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1
--报损单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE losebill SET CargoID=c.CargoID FROM dbo.losebill a INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId INNER JOIN dbo.CargoType  c  ON b.ktypeid=c.KtypeID WHERE c.IsDefault=1
--报溢单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE overflowbill SET CargoID=c.CargoID FROM dbo.overflowbill a INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId INNER JOIN dbo.CargoType  c  ON b.ktypeid=c.KtypeID WHERE c.IsDefault=1

--借出开单,借进开单,借出还回单,借进还出单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE lendbill SET CargoID=c.CargoID FROM dbo.lendbill a INNER JOIN dbo.LendIndex b ON a.BillNumberId = b.BillNumberId INNER JOIN dbo.CargoType  c  ON b.ktypeid=c.KtypeID WHERE c.IsDefault=1
--生产拆装单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.disassemblebill SET CargoID=b.CargoID FROM dbo.disassemblebill a  INNER JOIN dbo.CargoType  b  ON a.KTypeId=b.KtypeID WHERE b.IsDefault=1

--维修品调入单的草稿数据中的货位改为对应仓库的默认货位
UPDATE wx_bill_in SET CargoID=c.CargoID FROM dbo.wx_bill_in a INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId INNER JOIN dbo.CargoType  c  ON b.ktypeid=c.KtypeID WHERE c.IsDefault=1
--维修品调出单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.wx_Bill_Out SET CargoID=c.CargoID FROM dbo.wx_Bill_Out a INNER JOIN dbo.BillIndex b ON a.BillNumberId = b.BillNumberId INNER JOIN dbo.CargoType  c  ON b.ktypeid2=c.KtypeID WHERE c.IsDefault=1
--积分兑换单中的草稿数据中的货位改为对应仓库的默认货位
UPDATE dbo.integralexchangebill SET CargoID=b.CargoID FROM dbo.integralexchangebill a  INNER JOIN dbo.CargoType  b  ON a.ktypeid=b.KtypeID WHERE b.IsDefault=1

--把期初的库存货位改为对应仓库的默认货位
UPDATE Ini_GOODSSTOCKS_QTY SET   CargoID=b.CargoID FROM Ini_GOODSSTOCKS_QTY a INNER JOIN dbo.CargoType b  ON a.KTypeID=b.KtypeID WHERE b.IsDefault=1 
UPDATE IniFactStocks_Qty   SET   CargoID=b.CargoID FROM IniFactStocks_Qty a INNER JOIN dbo.CargoType b  ON a.KTypeID=b.KtypeID WHERE b.IsDefault=1 
    
--把期初锁库信息货位改为对应仓库的默认货位
UPDATE dbo.PT_SaleOrderLockDetail SET  CargoID=b.CargoID FROM dbo.PT_SaleOrderLockDetail a INNER JOIN dbo.CargoType b ON a.KTypeID = b.KtypeID WHERE b.IsDefault=1   

--处理期初序列号
UPDATE	gp_initPtypeSerial 
SET		CargoID=b.CargoID ,iniflag=b.cargoid
FROM	gp_initPtypeSerial a 
INNER JOIN dbo.CargoType b  ON a.KTypeID=b.KtypeID 
WHERE	b.IsDefault=1 

UPDATE	gp_iniFactPtypeSerial
SET		CargoID=b.CargoID,iniFlag=b.cargoid
FROM	gp_iniFactPtypeSerial a 
INNER JOIN dbo.CargoType b  ON a.KTypeID=b.KtypeID 
WHERE	b.IsDefault=1 

--把期初数据合并到默认货位
SELECT	PTypeID ,
		KTypeID ,
		CargoID ,
		ItemID ,
		Iscombined ,
		GoodsNumber ,
		ProduceDate ,
		ValidDate ,
		SUM(Qty) AS qty,
		SUM(NQty) AS Nqty,
		GOODSCOSTPRICE,
		SUM(LockNumber) AS LockNumber
INTO	#GOODSSTOCKS_QTY
FROM	dbo.ini_GOODSSTOCKS_QTY
GROUP BY  
		PTypeID ,
		KTypeID ,
		CargoID ,
		ItemID ,
		Iscombined ,
		GoodsNumber,
		GoodsCostPrice,
		ProduceDate,
		ValidDate 
				  				  
TRUNCATE TABLE dbo.Ini_GOODSSTOCKS_QTY
--SET identity_insert Ini_GOODSSTOCKS_QTY ON--打开
INSERT INTO dbo.Ini_GOODSSTOCKS_QTY
(       PTypeID ,
		KTypeID ,
		CargoID ,
		ItemID ,
		Iscombined ,
		GoodsNumber ,
		ProduceDate ,
		ValidDate ,
		Qty ,
		NQty ,
		GoodsCostPrice,
		LockNumber
)
SELECT	PTypeID ,
		KTypeID ,
		CargoID ,
		ItemID ,
		Iscombined ,
		GoodsNumber ,
		ProduceDate ,
		ValidDate ,
		Qty ,
		NQty ,
		GoodsCostPrice,
		LockNumber
FROM #GOODSSTOCKS_QTY
--set identity_insert Ini_GOODSSTOCKS_QTY OFF--关闭
DROP TABLE #GOODSSTOCKS_QTY

--实物库存期初的合并
SELECT	PTypeID,
		KTypeID,
		CargoID,
		ItemID,
		Iscombined,
		goodsnumber,
		ProduceDate,
		ValidDate,
		SUM(qty) AS qty,
		SUM(nqty) AS nqty
INTO	#IniFactStocks_Qty
FROM	IniFactStocks_Qty
GROUP BY 
		PTypeID,
		KTypeID,
		CargoID,
		ItemID,
		Iscombined,
		goodsnumber,
		ProduceDate,
		ValidDate
DELETE FROM IniFactStocks_Qty
INSERT INTO dbo.IniFactStocks_Qty
( 
	PTypeID ,
	KTypeID ,
	CargoID ,
	ItemID ,
	Iscombined ,
	GoodsNumber ,
	ProduceDate ,
	ValidDate ,
	Qty ,
	NQty
)
SELECT	PTypeID ,
          KTypeID ,
          CargoID ,
          ItemID ,
          Iscombined ,
          GoodsNumber ,
          ProduceDate ,
          ValidDate ,
          Qty ,
          NQty
FROM	  #IniFactStocks_Qty
DROP TABLE #IniFactStocks_Qty                
		
		
--把锁库记录合并到默认货位
SELECT    BillNumberId ,
          OrderID ,
          Ptypeid ,
          Etypeid ,
          KTypeID ,
          CargoID ,
          UnitID ,
          GoodsOrder ,
          GoodsNumber ,
          GoodsCostPrice ,
          ItemID ,
          IsCombined ,
          ProduceDate ,
          ValidDate ,
          SUM(LockNumber) AS  LockNumber,
          OrderType
INTO #PT_SaleOrderLockDetail
FROM dbo.PT_SaleOrderLockDetail
GROUP BY BillNumberId ,
          OrderID ,
          Ptypeid ,
          Etypeid ,
          KTypeID ,
          CargoID ,
          UnitID ,
          GoodsOrder ,
          GoodsNumber ,
          GoodsCostPrice ,
          ItemID ,
          IsCombined ,
          ProduceDate ,
          ValidDate ,
          OrderType
TRUNCATE TABLE dbo.PT_SaleOrderLockDetail
INSERT INTO dbo.PT_SaleOrderLockDetail
        ( BillNumberId ,
          OrderID ,
          Ptypeid ,
          Etypeid ,
          KTypeID ,
          CargoID ,
          UnitID ,
          GoodsOrder ,
          GoodsNumber ,
          GoodsCostPrice ,
          ItemID ,
          IsCombined ,
          ProduceDate ,
          ValidDate ,
          LockNumber ,
          OrderType
        )
SELECT BillNumberId ,
          OrderID ,
          Ptypeid ,
          Etypeid ,
          KTypeID ,
          CargoID ,
          UnitID ,
          GoodsOrder ,
          GoodsNumber ,
          GoodsCostPrice ,
          ItemID ,
          IsCombined ,
          ProduceDate ,
          ValidDate ,
          LockNumber ,
          OrderType
FROM #PT_SaleOrderLockDetail
DROP TABLE #PT_SaleOrderLockDetail


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateFaPiaoState]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[UpdateFaPiaoState]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王刚
	日期：2011-12-21
	描述：删除发票后，要更改billindex中的state
	
	修改人：丁超
	日期：2012-2-24
	描述：将所有删除放到存储过程进行操作
*/

CREATE PROCEDURE UpdateFaPiaoState
(
	@OperatorId			VARCHAR(100),	--操作员ID
	@billnumberids		VARCHAR(500),	--删除的发票ID
	@businesstype		int
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL  VARCHAR(5000)

CREATE TABLE #listid( billnumberid VARCHAR(50) )
IF @businesstype=1
BEGIN
	SET @SQL = ' INSERT INTO #listid(billnumberid) SELECT DISTINCT MainBillNumberID FROM FaPiaoBill WHERE BillNumberId IN ('+@billnumberids+') and MainBillNumberID > = 0 '
	EXEC (@SQL)

	IF(@@ERROR=0)
	BEGIN
		--------更新状态
		DECLARE @NumBerID VARCHAR(50)
		DECLARE CursorName CURSOR  ------查询游标
			LOCAL SCROLL STATIC 
			FOR SELECT billnumberid FROM #listid
			OPEN CursorName
			FETCH NEXT FROM CursorName
			INTO @NumBerID

			WHILE @@FETCH_STATUS=0
			BEGIN	
				EXEC Gp_UpdateInvoiceState @billnumberid = @NumBerID,@fapiaobillnumberid=@billnumberids,@otype=0	
				FETCH NEXT FROM CursorName
				INTO @NumBerID
			END
			CLOSE CursorName
			DEALLOCATE CursorName
		END

		DROP TABLE #listid

		SET @SQL = '
			DELETE FROM FaPiaoBillIndex WHERE BillNumberId IN ('+@billnumberids+')
			DELETE FROM FaPiaoBill WHERE BillNumberId IN ('+@billnumberids+')
			DELETE FROM QP_InvoiceOtherTotalDetails WHERE BillNumberId IN ('+@billnumberids+')
			DELETE FROM qp_invoicerepairitems WHERE BillNumberId IN ('+@billnumberids+')
			UPDATE PrintRecord SET RecordState=0 WHERE BillType in (''162'',''163'',''207'') AND BillNumberId IN ('+@billnumberids+')'
		EXEC(@SQL)
END
IF @businesstype=2
BEGIN
		SET @SQL = ' INSERT INTO #listid(billnumberid) SELECT  BillNumberId FROM ReceiptBillIndex WHERE BillNumberId IN ('+@billnumberids+') and  draft = 0 '
		EXEC (@SQL)
	    IF @@ROWCOUNT>0
	    BEGIN
			 RAISERROR('存在已经过账的单据，请刷新后重试！',16,1) 
			 RETURN 
		END
		
		SET @SQL = ' INSERT INTO #listid(billnumberid) SELECT  BillNumberId FROM ListTable WHERE BillNumberId IN ('+@billnumberids+') AND BillType IN(404,405)'
		EXEC (@SQL)
	    IF @@ROWCOUNT>0
	    BEGIN
			 RAISERROR('存在已经过账的单据，请刷新后重试！',16,1) 
			 RETURN 
		END
		
		SET @SQL = ' INSERT INTO #listid(billnumberid) SELECT  BillNumberId FROM InOutstocktable WHERE BillNumberId IN ('+@billnumberids+') AND BillType IN(404,405)'
		EXEC (@SQL)
	    IF @@ROWCOUNT>0
	    BEGIN
			 RAISERROR('存在已经过账的单据，请刷新后重试！',16,1) 
			 RETURN 
		END
		SET @SQL = '
			DELETE FROM ReceiptBillIndex WHERE BillNumberId IN ('+@billnumberids+') and draft=1
			DELETE FROM ReceiptBill WHERE BillNumberId IN ('+@billnumberids+')
			UPDATE PrintRecord SET RecordState=0 WHERE BillType IN (''404'',''405'') AND BillNumberId IN  ('+@billnumberids+')
		  '
		EXEC(@SQL)
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateIniFactFlag]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[UpdateIniFactFlag]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：舒珊
	日期：2016-12-30
	描述：实物库存期初录入序列号(gp_iniFactPtypeSerial) iniflag 存成了行号，当配置改变(货位 自由项 等等)的时候 iniflag没合并导致出不来了
*/
CREATE PROCEDURE UpdateIniFactFlag
--@encode$--
AS
SET NOCOUNT ON

create table #Temp_IniFactPtypeSerial(
				ptypeid					varchar(50),
				ktypeid					varchar(50),
				CargoID					int,
				itemid					int,
				iscombined				bit,
				goodsnumber				varchar(100),
				produceDate				varchar(50),
				ValidDate				varchar(50),
				id						int
			
)

insert into #Temp_IniFactPtypeSerial
select  PTypeID ,
		KTypeID ,
		CargoID ,
		ItemID ,
		Iscombined ,
		GoodsNumber,
		ProduceDate,
		ValidDate ,
		ROW_NUMBER() OVER (PARTITION BY PTypeID ,ktypeid
		 ORDER BY PTypeID,ktypeid) as id
		 from IniFactStocks_Qty  
		
update  gp_iniFactPtypeSerial set iniflag=a.id
 from gp_iniFactPtypeSerial b
 inner join #Temp_IniFactPtypeSerial a on a.PTypeID=b.PTypeID and a.KTypeID=b.KTypeID  and a.cargoid =b.cargoid
						and a.ItemID=b.ItemID  and a.Iscombined=b.Iscombined   and a.GoodsNumber=b.GoodsNumber 
						and  a.ProduceDate=b.ProduceDate  and a.ValidDate=b.ValidDate
						
	    
if @@error>0
return -2
		 
DROP TABLE #Temp_IniFactPtypeSerial


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateInvoiceData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].UpdateInvoiceData
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--====================================================================
	--功能：升级时处理开票金额和数量字段为null的情况
	--作者: Hanlin	
	--时间: 2012-09-10
--====================================================================
CREATE PROCEDURE UpdateInvoiceData
--@encode$--
AS
SET NOCOUNT ON
UPDATE billindex SET InvoiceMoney=0,NInvoiceMoney=0 WHERE InvoiceMoney IS NULL
Update SaleBill Set InvoiceQty=0,InvoiceMoney=0,NInvoiceMoney=0  WHERE InvoiceQty IS NULL
Update retailBill Set InvoiceQty=0,InvoiceMoney=0,NInvoiceMoney=0  WHERE InvoiceQty IS NULL
Update CommissionBill Set InvoiceQty=0,InvoiceMoney=0,NInvoiceMoney=0  WHERE InvoiceQty IS NULL
Update SaleGoodsExchangeBill Set InvoiceQty=0,InvoiceMoney=0,NInvoiceMoney=0  WHERE InvoiceQty IS NULL
Update BuyGoodsExchangeBill Set InvoiceQty=0,InvoiceMoney=0,NInvoiceMoney=0  WHERE InvoiceQty IS NULL
Update saleBackBill Set InvoiceQty=0,InvoiceMoney=0,NInvoiceMoney=0  WHERE InvoiceQty IS NULL
Update BuyBill Set InvoiceQty=0,InvoiceMoney=0,NInvoiceMoney=0   WHERE InvoiceQty IS NULL
Update BuyBackBill Set InvoiceQty=0,InvoiceMoney=0,NInvoiceMoney=0  WHERE InvoiceQty IS NULL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateStockCheck60ToA8]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[UpdateStockCheck60ToA8]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
exec UpdateStockCheck60ToA8
从6.0升级到A8之后特殊处理Stockcheck表的stockcheck
*/
CREATE	PROCEDURE UpdateStockCheck60ToA8

--@encode$--
AS

SET NOCOUNT ON
SET ANSI_WARNINGS OFF

DECLARE @Ptypeid	VARCHAR(100),
		@Ktypeid	VARCHAR(100),
		@stockCheckId	VARCHAR(100),
		@BillDate		DateTime,
		@ifwx			INT 
DECLARE stock_cursor cursor FOR
SELECT  s.PTypeID,si.KTypeID,s.StockCheckID,si.BillDate,si.ifwx
FROM	StockCheck S
		INNER JOIN StockCheckIndex  si ON s.StockCheckID=si.StockCheckID

Open stock_cursor
Fetch Next From  stock_cursor INTO @Ptypeid,@Ktypeid,@stockCheckId,@BillDate,@ifwx
WHILE @@FETCH_STATUS = 0
BEGIN
	
	DECLARE @SQL VARCHAR(8000)
	SET @SQL = '
				UPDATE	StockCheck
				SET		StockQty = ISNULL(result.Qty,0)
				FROM	StockCheck S,
						(
							SELECT	B.PTypeId,
									SUM(Qty) AS Qty,
									'+@stockCheckId+' as stockcheckid
							FROM	(	
											SELECT	I.PTypeId, 
													I.Qty AS Qty '
													
				IF  @ifwx=0	SET @SQL=@SQL+' FROM	IniGoodsStocks I ' 																	
				ELSE		SET @SQL=@SQL+' FROM	Wx_IniGoodsStocks I ' 																			
				SET @SQL=@SQL+'				WHERE	i.PtypeId='+CHAR(39)+@Ptypeid+CHAR(39)+'
													AND i.ktypeid='+CHAR(39)+@Ktypeid+CHAR(39)+'
											UNION ALL
											SELECT	PTypeId,
													SUM(Qty) AS Qty '
				IF  @ifwx=0	SET @SQL=@SQL+' FROM	InOutStockTable i ' 																	
				ELSE		SET @SQL=@SQL+' FROM	Wx_InOutStockTable i ' 																			
				SET @SQL=@SQL+'			
											WHERE	i.Audited = 1
													AND i.Qty<>0
													AND i.KTypeId <> ''10000''
													AND i.PtypeId='+CHAR(39)+@Ptypeid+CHAR(39)+'
													AND i.ktypeid='+CHAR(39)+@Ktypeid+CHAR(39)+'
													AND i.BillDate<='''+CAST(@BillDate as VARCHAR(100))+'''
											GROUP BY i.PTypeId
									)B GROUP BY B.PTypeId 
						)result
				WHERE	result.stockcheckid=S.StockCheckId AND result.PTypeId = S.PTypeId 	 		
				'
	EXEC(@SQL)
	--print (@SQL)
	Fetch Next From  stock_cursor INTO @Ptypeid,@Ktypeid,@stockCheckId,@BillDate,@ifwx
END

CLOSE stock_cursor
DEALLOCATE stock_cursor


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[UpgradeAdPriceBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[UpgradeAdPriceBill]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		InoutstockTable表Comment处理
-- 最后修改作者：	施训果
-- 最后修改时间：	2016-03-31
-- ========================================================================
CREATE PROCEDURE UpgradeAdPriceBill
--@encode$--
AS
SET NOCOUNT ON


--AdPriceBill升级数据表数据
DECLARE @costing VARCHAR(50)
SELECT @costing=SubValue FROM dbo.sysdata WHERE SubName='costing'

IF @costing='0'
BEGIN
	UPDATE dbo.AdPriceBill SET ChangeTotal=total-BeforeTotal WHERE ChangeTotal IS NULL OR ChangeTotal=0
	UPDATE B SET B.totalmoney=A.changetotal,B.ntotalmoney=A.changetotal
	FROM dbo.BillIndex B,
	(
		SELECT BillNumberId,SUM(ISNULL(ChangeTotal,0)) AS changetotal
		FROM AdPriceBill
		GROUP BY BillNumberId
	) A
	WHERE b.BillNumberId=A.BillNumberId AND b.BillType=57 AND A.changetotal=0
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[UpgradeInoutstockTable]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[UpgradeInoutstockTable]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		InoutstockTable表Comment处理
-- 最后修改作者：	施训果
-- 最后修改时间：	2016-03-31
-- ========================================================================
CREATE PROCEDURE UpgradeInoutstockTable
--@encode$--
AS
SET NOCOUNT ON

-----------------------------------------------------InoutstockTable表Comment处理 start------------------------------------------------------------------
DECLARE @Sql VARCHAR(max)
DECLARE @TBN VARCHAR(100)
DECLARE @billType VARCHAR(50)
DECLARE BillType_Cursort CURSOR FOR 
SELECT detailTable,Billtype FROM dbo.BillName WHERE BillType IN  (11,34,6,45,4,66,17,21,305,159,144,145,146,147,160,161,139,126,9,14,57,16,157,140,141,142,143,
		165,166,167,168,169,170,171,172,173,174,175,178,183,186,187,188,191,195,196,197,200,182,179,201,202,205,215,312,400,401,402,403) ORDER BY Billtype
OPEN BillType_Cursort
FETCH NEXT FROM BillType_Cursort INTO @TBN,@billType
WHILE @@FETCH_STATUS=0
BEGIN
	SET @Sql='UPDATE A
			SET A.Comment=B.Comment
			FROM dbo.InOutstocktable A
			INNER JOIN '+@TBN+' B
			ON A.BillNumberId=B.BillNumberId 
			AND A.BillType='+@billType+'
			AND A.ID=B.ID
			WHERE A.Comment is Null OR A.Comment='''' '
	PRINT @Sql
	EXEC(@Sql)
FETCH NEXT FROM BillType_Cursort INTO @TBN,@billType
END
CLOSE BillType_Cursort
DEALLOCATE BillType_Cursort
-----------------------------------------------------InoutstockTable表Comment处理   end------------------------------------------------------------------


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/****** 对象:  Table [dbo].[Vacation]    脚本日期: 2011.10.26 14:46:47 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[VacationDetails]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[VacationDetails](
		[IndexId] [numeric](10, 0)  NOT NULL,
		[VacationDetailsDate] [date] NOT NULL					--假期明细
	) ON [PRIMARY]
END
GO
------------------------------------------表修改区域开始-------------------------------------------------



------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------删除索引区域开始-----------------------------------------------

------------------------------------------删除索引区域结束-----------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------

------------------------------------------创建索引区域结束-----------------------------------------------



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[WEB_ACAccountExtend]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[WEB_ACAccountExtend]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/30
	Description	: 查询会计科目
*/
CREATE PROCEDURE WEB_ACAccountExtend
(
	@ParId		VARCHAR(100),	--父节点ID
	@StypeId	VARCHAR(100),	--分支机构
	@deleted	VARCHAR(2),		--是否停用
	@AcID		INT				--科目表treeid
)
--@encode$--
AS 
SET NOCOUNT ON

IF ISNULL(@ParId,'')='' 
	SET @ParId = ''

IF ISNULL(@StypeId,'')='' 
	SET @StypeId = ''
   
IF @deleted=1
	SET @deleted='%'

DECLARE @syscid INT
SELECT TOP 1 @syscid = cid FROM Ac_Currency WHERE Sysrow = 1

SELECT  
	A.*,
	REPLICATE('    ',A.FLeveal-1) + A.UserCode FUserCode,
	--F.UserCode AS FUserCode,
	CASE LEFT(A.TypeId, 5)
		  WHEN '00001' THEN '资产'
		  WHEN '00002' THEN '负债'
		  WHEN '00003' THEN '损益'
		  WHEN '00004' THEN '成本'
		  WHEN '00005' THEN '权益'
		  WHEN '00006' THEN '共同'
		  ELSE '其他'
		END AS GroupName,
	CASE A.Fdc
		  WHEN 1 THEN '借'
		  ELSE '贷'
		END AS fdcName,
	CASE A.IsCash
		  WHEN 1 THEN '√'
		  ELSE ''
		END AS cashname,
	CASE A.isbank
		  WHEN 1 THEN '√'
		  ELSE ''
		END AS bankname,
	CASE A.IsOther
		  WHEN 1 THEN '√'
		  ELSE ''
		END AS othername,
	CASE A.cid
		  WHEN 0 THEN '所有币种'
		  WHEN @syscid THEN '不核算'
		  ELSE c.FullName
		END AS cidname, 
	CASE WHEN t.checkitemcount > 0 THEN '√'
		  ELSE ''
		END AS ascidname,
	A.FContact,
	CASE A.FContact
		  WHEN 1 THEN '√'
		  ELSE ''
		END AS fcontactname,
	A.AcId,
	A.AdjustAccounts,
	CASE A.AdjustAccounts
		  WHEN 1 THEN '√'
		  ELSE ''
		END AS AdjustAccountsname
FROM Ac_Account A
--INNER JOIN DBO.F_GetStandard_Ac_Account('00001') F ON F.TypeId = A.TypeId AND F.StypeId = A.StypeId
LEFT JOIN Ac_Currency c ON c.cid = A.Cid
LEFT JOIN (SELECT   stypeid, ATypeId,
                    COUNT(1) AS checkitemcount
           FROM     Ac_Account_Assist_CheckItems
           GROUP BY STypeId, atypeid) t ON t.stypeid = a.StypeId
                                           AND t.ATypeId = A.TypeId
WHERE 
	A.StypeId = @StypeId  
	AND AcId=@AcID
	AND A.TypeId LIKE @ParId + '%'
	AND A.TypeId > '00000'
	AND A.UserCode > '' ---用 UserCode > '' 代替 usercode <> ''
	AND A.Deleted LIKE @deleted
ORDER BY A.UserCode


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_AcAllGeneralLedger]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_AcAllGeneralLedger]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/21
	Description	: 查询所有币别总分类账
*/

CREATE PROCEDURE WEB_AcAllGeneralLedger
(
   @STypeId 		VARCHAR(50),   ---分支机构ID
   @ATypeId			VARCHAR(MAX),  ---会计科目ID(可以多值，以,为分隔符 例：xxx,xxx,xx)        
   @Leveal		    INT,		   ---科目级别
   @Cid				INT,		   ---综合本位币，所有币别    
   @FYear			INT,        
   @FPeriodStart    INT,		   ---起始期间
   @FPeriodEnd      INT,		   ---结束期间
   @IsPost			BIT,		   ---是否显示未过账凭证 1：是 0：否
   @IsPeriodNull    BIT,		   ---是否显示本期没有发生额的科目 1：是 0：否 
   @IsBalanceNull   BIT,           ---是否显示余额为空的科目 1：是 0：否
   @IsYearNull		BIT,           ---是否显示本年没有发生额的科目 1：是 0：否
   @IsDetail		BIT,		   ---只显示明细
   @chvOperatorID	VARCHAR(50),	---操作员ID
   @IsShowPL		INT				--时候包含结转损益
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	DECLARE	@SQL			NVARCHAR(MAX),
			@iniFYear		VARCHAR(5),
			@FPeriod		INT,
			@tempPeriodS	INT=@FPeriodStart,
			@tempPeriodE	INT=@FPeriodEnd

	SELECT @iniFYear=SUBVALUE FROM SYSDATA WHERE SUBNAME='fyear'
	IF @iniFYear=@Fyear
		SELECT @FPeriod=SUBVALUE FROM SYSDATA WHERE SUBNAME='fmonth'
	ELSE 
		SELECT @Fperiod=MIN(CONVERT(INT,FPeriod)) FROM dbo.Ac_Period 
	-----------------------------------------该职员权限-----------------------------------------------------------------------------------
	IF NOT EXISTS(SELECT * FROM dbo.F_GetManDetailAllSType(@chvOperatorID) WHERE TypeId=@STypeId)
		SET @STypeId=''
	 -------------------------------无论选择过账与否,都重新生成一个临时科目余额表-----------------------------------------------------------
 --建立临时余额表，所有科目
CREATE TABLE #tempAcBalance 
(
	STypeId			VARCHAR(50),	--分支机构
	ATypeId			VARCHAR(50),	--科目
	Fdc				INT,			--科目方向
	FYear			VARCHAR(10),	--年度
	FPeriod			VARCHAR(10),	--期间
	Cid				INT,			--币种
	FBeginBalanceFor  NUMERIC(24, 10)  DEFAULT 0,--期初
	FDebitFor		 NUMERIC(24, 10)  DEFAULT 0,--本期借方
	FCreditFor		 NUMERIC(24, 10)  DEFAULT 0,--本期贷方
	FEndBalanceFor	 NUMERIC(24, 10)  DEFAULT 0,--期末
	FYtdDebitFor	 NUMERIC(24, 10)  DEFAULT 0,--本年借方
	FYtdCreditFor	 NUMERIC(24, 10)  DEFAULT 0--本年贷方
)

	DECLARE 
		@BillDateStart DATETIME,
		@BillDateEnd DATETIME
	SELECT @BillDateStart=FBegin FROM Ac_Period WHERE FYear=@Fyear AND FPeriod=@FPeriodStart
	SELECT @BillDateEnd=FEnd FROM Ac_Period WHERE FYear=@Fyear AND FPeriod=@FPeriodEnd		

	INSERT INTO #tempAcBalance
	EXEC WEB_SubsiAcBalanceQueryFromVoucher @StypeId,@Atypeid,@Fyear,@BilldateStart,@BilldateEnd,@Cid,@IsPost,@chvOperatorID
	-----------------------------------把符合条件的科目插入临时表---------------------------------------------------------------------
	
	BEGIN--处理会计科目多级权限
		CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
		INSERT INTO #Ac_Account_L (Typeid,StypeId) 
		SELECT L.Typeid,L.Stypeid FROM F_TreeAccount(@chvOperatorID,'') L
	END;
	
	
	--保存查询的科目
	CREATE TABLE #temp1
	(
		TYPEID			VARCHAR(50),    ----查询的科目
		FULLNAME		VARCHAR(200),	----科目的名称
		USERCODE		VARCHAR(200),	----科目代码
		FDC				VARCHAR(5)		----科目方向
	)
	IF @ATypeId<>''
		BEGIN
			SET @SQL='INSERT INTO #temp1
					SELECT c.TYPEID,
						   c.FULLNAME,
						   d.USERCODE,
						   c.FDC
					FROM (
							SELECT a FROM F_Split(@ATypeId,'','')
						 ) b
					JOIN dbo.Ac_Account c ON b.a=c.TYPEID AND c.STYPEID=@STypeId AND c.LEVEAL>1 AND c.FLEVEAL<=@Leveal
					INNER JOIN F_LineAccount('''+@chvOperatorID+''','''') F ON F.TypeId=C.TypeId AND F.StypeId=C.StypeId '
			IF @IsDetail=1
				SET @SQL+=' AND c.SONNUM=0 '
			SET @SQL+=' INNER JOIN #Ac_Account_L L ON C.TYPEID=L.TYPEID AND C.STYPEID=L.STYPEID '
			SET @SQL+='JOIN (
								SELECT * FROM F_GetStandard_Ac_Account(@chvOperatorID)
							) d ON c.STYPEID=d.STYPEID AND c.TYPEID=d.TYPEID'
			EXEC sp_executesql @SQL,N'@STypeId VARCHAR(50),@ATypeId VARCHAR(MAX),@Leveal INT,@chvOperatorID VARCHAR(50)',@STypeId,@ATypeId,@Leveal,@chvOperatorID
		END
	ELSE
		BEGIN
			SET @SQL='INSERT INTO #temp1
					SELECT a.TYPEID,
						   a.FULLNAME,
						   d.USERCODE,
						   a.FDC 
					FROM dbo.Ac_Account a
					INNER JOIN F_LineAccount('''+@chvOperatorID+''','''') F ON F.TypeId=A.TypeId AND F.StypeId=A.StypeId 
					JOIN (
							SELECT * FROM F_GetStandard_Ac_Account(@chvOperatorID)
					     ) d ON a.STYPEID=d.STYPEID AND a.TYPEID=d.TYPEID 
					INNER JOIN #Ac_Account_L L ON a.TYPEID=L.TYPEID AND a.STYPEID=L.STYPEID
					WHERE a.STYPEID=@STypeId  AND a.LEVEAL>1 AND a.FLEVEAL<=@Leveal '--AND a.DELETED=0
			IF @IsDetail=1
				SET @SQL+=' AND a.SONNUM=0'
			EXEC sp_executesql @SQL,N'@STypeId VARCHAR(50),@Leveal INT,@chvOperatorID VARCHAR(50)',@STypeId,@Leveal,@chvOperatorID
		END
	SET @SQL=''
	
	---保存要查询科目的所有子节点科目
	CREATE TABLE #temp2
	(
		STYPEID 		VARCHAR(50),	----分支机构ID
		FATHERID        VARCHAR(50),    ----查询的科目ID
		SONID			VARCHAR(50),	----查询的科目子节点的ID
		FULLNAME		VARCHAR(200),	----查询的科目名称
		USERCODE		VARCHAR(200),	----查询的科目代码
		FDC				VARCHAR(5),		----查询的科目方向
		SONFDC			INT				----子科目的方向
	)

	INSERT INTO #temp2
	SELECT B.StypeId,
		   a.TYPEID,
		   b.TYPEID,
		   a.FULLNAME,
		   a.USERCODE,
		   a.FDC,
		   b.FDC
	FROM #temp1 a
	JOIN dbo.Ac_Account b ON  b.STYPEID=@STypeId AND b.TYPEID LIKE a.TYPEID+'%' AND b.SONNUM=0 --AND b.DELETED=0  
	INNER JOIN F_LineAccount(@chvOperatorID,'') F ON F.TypeId=B.TypeId AND F.StypeId=b.StypeId
	ORDER BY a.TYPEID,b.TYPEID
	-----------------------------根据temp2中的子科目，剔除重复科目，生成一个只含有子科目的临时表temp3，用于关联科目余额表-------
	 SELECT DISTINCT STYPEID AS STYPEID,
		    SONID AS TYPEID
	 INTO #temp3
	 FROM #temp2
	---------------------------------把#temp3科目关联ac_balance后所得的子科目统计数据分别存入temp4：统计的是子科目的本期发生额，本年发生额和余额-----------------------
	-----子科目的本期发生额，是查看凭证，而不是查看acbalance表
	CREATE TABLE #tempSonAccountPeriod
	(
	    TYPEID			VARCHAR(50),
	    PERIODCHANGE	 NUMERIC(24, 10) 
	)
	INSERT INTO #tempSonAccountPeriod
	SELECT TYPEID,
		   SUM(ABS(ISNULL(BORROW,0)))+SUM(ABS(ISNULL(LEND,0)))
	FROM #temp3 c
	LEFT JOIN 
	(
		SELECT b.STYPEID,
			   b.ATYPEID,
			   ISNULL(b.FDEBITTOTAL,0) AS BORROW,
			   ISNULL(b.FCREDITTOTAL,0) AS LEND
		FROM Ac_Voucher a 
		JOIN Ac_Voucher_Bill b ON a.BillNumberId=b.BillNumberId
		INNER JOIN F_LineAccount(@chvOperatorID,@STypeId) F ON F.TypeID=B.ATypeId AND F.Stypeid=b.STypeId
		WHERE a.FYear=@FYear AND 
			  a.FPERIOD>=@FPeriodStart AND 
			  a.FPERIOD<=@FPeriodEnd AND 
			  a. FChecked <> -1 AND 
			  ((@IsPost=0 AND IfCheck='t') OR @IsPost=1) 
	) d ON c.STYPEID=d.STYPEID AND c.TYPEID=d.ATYPEID
	GROUP BY c.TYPEID
    
	
	-----子科目的本年发生额，是查看凭证，而不是查看acbalance表
	CREATE TABLE #tempSonAccountYear
	(
	    TYPEID			VARCHAR(50),
	    YEARCHANGE		 NUMERIC(24, 10) 
	)
	INSERT INTO #tempSonAccountYear
	SELECT TYPEID,
		   SUM(ABS(ISNULL(BORROW,0)))+SUM(ABS(ISNULL(LEND,0)))
	FROM #temp3 c
	LEFT JOIN 
	(
		SELECT b.STYPEID,
			   b.ATYPEID,
			   ISNULL(b.FDEBITTOTAL,0) AS BORROW,
			   ISNULL(b.FCREDITTOTAL,0) AS LEND
		FROM Ac_Voucher a 
		JOIN Ac_Voucher_Bill b ON a.BillNumberId=b.BillNumberId 
		INNER JOIN F_LineAccount(@chvOperatorID,@STypeId) F ON F.TypeID=B.ATypeId AND F.Stypeid=b.STypeId
		WHERE a.FYear=@FYear AND 
			  a.FPERIOD<=@FPeriodEnd AND 
			  a. FChecked <> -1 AND 
			  ((@IsPost=0 AND IfCheck='t') OR @IsPost=1) 
	) d ON c.STYPEID=d.STYPEID AND c.TYPEID=d.ATYPEID
	GROUP BY c.TYPEID
	
	-----将统计数据插入temp4
	CREATE TABLE #temp4
	 (
		SONID			VARCHAR(50),
		PERIODCHANGE	 NUMERIC(24, 10) ,			---本期发生额
		YEARCHANGE		 NUMERIC(24, 10) ,			---本年发生额
		BALANCE			 NUMERIC(24, 10) 			---余额
	 ) 
	INSERT INTO #temp4
    SELECT  c.TYPEID,
		    c.PERIODCHANGE,
		    d.YEARCHANGE,
		    f.BALANCE
	FROM #tempSonAccountPeriod c
	JOIN #tempSonAccountYear d ON c.TYPEID=d.TYPEID
	JOIN    
	(
	   SELECT i.TYPEID,
			  ISNULL(FENDBALANCE,0)                    AS BALANCE   
	   FROM 
        (
			SELECT h.STYPEID,
				   h.TYPEID,
				   ISNULL(MAX(FPERIOD),@FPeriodEnd) AS FPERIOD 
			FROM #temp3 h
			LEFT JOIN #tempAcBalance g ON g.STYPEID=h.STYPEID AND g.ATYPEID=h.TYPEID AND g.FYEAR=@FYear AND g.CID=0 AND g.FPeriod<=@FPeriodEnd
			GROUP BY h.TYPEID,h.STYPEID	
		) i 
		LEFT JOIN #tempAcBalance e ON i.STYPEID=e.STYPEID AND i.TYPEID=e.ATYPEID AND i.FPERIOD=e.FPERIOD AND e.CID=0 AND e.FYEAR=@FYear
	) f ON c.TYPEID=f.TYPEID
	-----------------------------#temp2与#temp4关联，生成查询科目的数据，保存到临时表AccountTotalData--------------------------------------
	CREATE TABLE #AccountTotalData
	 (
		STYPEID			VARCHAR(50),
		TYPEID			VARCHAR(50),
		PERIODCHANGE	 NUMERIC(24, 10) ,
		YEARCHANGE		 NUMERIC(24, 10) ,
		BALANCE			 NUMERIC(24, 10) 
	 )
	 ;WITH a AS
	(
			SELECT b.STYPEID,
				   b.FATHERID,
				   b.SONFDC,
				   SUM(ISNULL(PERIODCHANGE,0)) AS PERIODCHANGE,
				   SUM(ISNULL(YEARCHANGE,0)) AS YEARCHANGE,
				CASE									 
					WHEN b.FDC=b.SONFDC THEN SUM(ISNULL(BALANCE,0))
					ELSE -SUM(ISNULL(BALANCE,0))
				END AS BALANCE
			FROM #temp2 b 
			JOIN #temp4 c ON b.SONID=c.SONID
			GROUP BY b.STYPEID,b.FATHERID,b.FDC,b.SONFDC
	)
	INSERT INTO #AccountTotalData
	SELECT a.STYPEID,
		   a.FATHERID,
		   SUM(PERIODCHANGE),
		   SUM(YEARCHANGE),
		   SUM(BALANCE)
	FROM a 
	GROUP BY a.STYPEID,a.FATHERID
	
	---------根据查询条件的父科目,取出符合条件的父科目 
	CREATE TABLE #temp5
	(
	 STYPEID		 VARCHAR(50),
	 TYPEID			 VARCHAR(50)
	)
	INSERT INTO #temp5
	SELECT STYPEID,
		   TYPEID 
	FROM #AccountToTalData 
	WHERE ((@IsPeriodNull=1 AND PERIODCHANGE>0) OR @IsPeriodNull=0) AND
		  ((@IsYearNull=1 AND YEARCHANGE>0) OR @IsYearNull=0) AND
		  ((@IsBalanceNull=0 AND BALANCE!=0) OR @IsBalanceNull=1)
	-----将子科目的各个统计数据插入temp6
	---所有币别
	 CREATE TABLE #Cid
     (
       CID INT
     )
     INSERT INTO #Cid
     SELECT CID FROM dbo.Ac_Currency
     UNION 
     SELECT 0
	
	CREATE TABLE #temp6
	(
		SONID				VARCHAR(50),
		CID					INT,
		SELFBORROW			 NUMERIC(24, 10) ,
		ORIBORROW			 NUMERIC(24, 10) ,
		SELFLEND			 NUMERIC(24, 10) ,
		ORILEND				 NUMERIC(24, 10) ,
		YEARSELFBORROW		 NUMERIC(24, 10) ,
		YEARORIBORROW		 NUMERIC(24, 10) ,
		YEARSELFLEND		 NUMERIC(24, 10) ,
		YEARORILEND			 NUMERIC(24, 10) ,
		BSELFBALANCE		 NUMERIC(24, 10) ,			--期初
		BORIBALANCE			 NUMERIC(24, 10) ,			--期初
		ESELFBALANCE		 NUMERIC(24, 10) ,			--期末
		EORIBALANCE			 NUMERIC(24, 10) ,			--期末
		FPERIOD				INT
	)
	WHILE @tempPeriodS<=@tempPeriodE
		BEGIN
			INSERT INTO #temp6
			SELECT  c.TYPEID,
			        c.CID,
			        c.FDEBIT,
				    c.FDEBITFOR,
				    c.FCREDIT,
				    c.FCREDITFOR,
				    d.FYTDDEBIT,
				    d.FYTDDEBITFOR,
				    d.FYTDCREDIT,
				    d.FYTDCREDITFOR,
				    f.FBEGINBALANCE,
				    f.FBEGINBALANCEFOR,
				    d.FENDBALANCE,
				    d.FENDBALANCEFOR,
				    c.FPERIOD
			FROM 
			(
				SELECT a.TYPEID,
					   a.CID,
				       ISNULL(FDEBIT,0)		      AS FDEBIT,
					   ISNULL(FDEBITFOR,0)        AS FDEBITFOR,
					   ISNULL(FCREDIT,0)          AS FCREDIT,
					   ISNULL(FCREDITFOR,0)       AS FCREDITFOR,
					   --ISNULL(FBEGINBALANCE,0)    AS FBEGINBALANCE,
					   --ISNULL(FBEGINBALANCEFOR,0) AS FBEGINBALANCEFOR,
					   @tempPeriodS               AS FPERIOD
				FROM 
					(
					   SELECT * FROM #temp3,#Cid
					) a
			    LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.TYPEID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS AND a.CID=b.CID
			) c
			JOIN 
			(
			    SELECT i.TYPEID,
					   i.CID,
					   ISNULL(FYTDDEBIT,0)	       AS FYTDDEBIT,
					   ISNULL(FYTDDEBITFOR,0)	   AS FYTDDEBITFOR,
					   ISNULL(FYTDCREDIT,0)        AS FYTDCREDIT,
				       ISNULL(FYTDCREDITFOR,0)     AS FYTDCREDITFOR,
				       ISNULL(FENDBALANCE,0)       AS FENDBALANCE,   
					   ISNULL(FENDBALANCEFOR,0)    AS FENDBALANCEFOR   
			    FROM 
				(
					SELECT h.STYPEID,
						   h.TYPEID,
						   h.CID,
						   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD 
					FROM 
						( 
							SELECT * FROM #temp3,#Cid
						) h
					LEFT JOIN #tempAcBalance g ON g.STYPEID=h.STYPEID AND g.ATYPEID=h.TYPEID AND g.FYEAR=@FYear AND g.CID=h.CID AND g.FPeriod<=@tempPeriodS
					GROUP BY h.TYPEID,h.STYPEID,h.CID	
				) i 
				LEFT JOIN #tempAcBalance e ON i.STYPEID=e.STYPEID AND i.TYPEID=e.ATYPEID AND i.FPERIOD=e.FPERIOD AND e.CID=i.CID AND e.FYEAR=@FYear
			) d ON c.TYPEID=d.TYPEID AND c.CID=d.CID
			JOIN 
			(
				SELECT i.TYPEID,
					   i.CID,
					   CASE 
							WHEN i.FPERIOD=@tempPeriodS THEN ISNULL(FBEGINBALANCE,0)
							ELSE ISNULL(FENDBALANCE,0) 
					   END AS FBEGINBALANCE, 
					   CASE 
							WHEN i.FPERIOD=@tempPeriodS THEN ISNULL(FBEGINBALANCEFOR,0)
							ELSE ISNULL(FENDBALANCEFOR,0) 
					   END AS FBEGINBALANCEFOR        
				FROM 
				(
					SELECT h.STYPEID,
						   h.TYPEID,
						   h.CID,
						   CASE
								WHEN MAX(FPERIOD)=@tempPeriodS AND MAX(FPERIOD)!=@FPeriod THEN @tempPeriodS-1
								ELSE MAX(FPERIOD)
						   END AS FPERIOD
					FROM 
						( 
							SELECT * FROM #temp3,#Cid
						) h
					LEFT JOIN #tempAcBalance g ON g.STYPEID=h.STYPEID AND g.ATYPEID=h.TYPEID AND g.FYEAR=@FYear AND g.CID=h.CID AND g.FPeriod<=@tempPeriodS
					GROUP BY h.TYPEID,h.STYPEID,h.CID
				) i
				LEFT JOIN #tempAcBalance e ON i.STYPEID=e.STYPEID AND i.TYPEID=e.ATYPEID AND i.FPERIOD=e.FPERIOD AND e.CID=i.CID AND e.FYEAR=@FYear
			) f ON c.TYPEID=f.TYPEID AND c.CID=f.CID
			SET @tempPeriodS+=1
		END
	------------#temp6关联#temp2
	CREATE TABLE #AccountData
	 (
		STYPEID				VARCHAR(50),
		TYPEID				VARCHAR(50),
		CID					INT,
		FDC					INT,
		SELFBORROW			 NUMERIC(24, 10) ,
		ORIBORROW			 NUMERIC(24, 10) ,
		SELFLEND			 NUMERIC(24, 10) ,
		ORILEND				 NUMERIC(24, 10) ,
		YEARSELFBORROW		 NUMERIC(24, 10) ,
		YEARORIBORROW		 NUMERIC(24, 10) ,
		YEARSELFLEND		 NUMERIC(24, 10) ,
		YEARORILEND			 NUMERIC(24, 10) ,
		BSELFBALANCE		 NUMERIC(24, 10) ,			--期初
		BORIBALANCE			 NUMERIC(24, 10) ,			--期初
		ESELFBALANCE		 NUMERIC(24, 10) ,			--期末
		EORIBALANCE			 NUMERIC(24, 10) ,			--期末
		FPERIOD				INT
	 )
	INSERT INTO #AccountData
    SELECT a.STYPEID,
		   a.FATHERID,
		   a.CID,
		   a.FDC,
		   SUM(SELFBORROW),
		   SUM(ORIBORROW),
		   SUM(SELFLEND),
		   SUM(ORILEND),
		   SUM(YEARSELFBORROW),
		   SUM(YEARORIBORROW),
		   SUM(YEARSELFLEND),
		   SUM(YEARORILEND),
		   SUM(BSELFBALANCE),
		   SUM(BORIBALANCE),
		   SUM(ESELFBALANCE),
		   SUM(EORIBALANCE),
		   a.FPERIOD
    FROM 
    (
		SELECT b.STYPEID,
			   b.FATHERID,
			   b.FDC,
			   c.FPERIOD,
			   c.CID,
			   b.SONFDC,
			   SUM(ISNULL(SELFBORROW,0))     AS SELFBORROW,
			   SUM(ISNULL(ORIBORROW,0))      AS ORIBORROW,
			   SUM(ISNULL(SELFLEND,0))       AS SELFLEND,
			   SUM(ISNULL(ORILEND,0))        AS ORILEND,
			   SUM(ISNULL(YEARSELFBORROW,0)) AS YEARSELFBORROW,
			   SUM(ISNULL(YEARORIBORROW,0))  AS YEARORIBORROW,
			   SUM(ISNULL(YEARSELFLEND,0))   AS YEARSELFLEND,
			   SUM(ISNULL(YEARORILEND,0))    AS YEARORILEND,
				CASE 
					WHEN b.FDC=b.SONFDC THEN SUM(ISNULL(BSELFBALANCE,0)) 
					ELSE -SUM(ISNULL(BSELFBALANCE,0)) 
				END AS BSELFBALANCE,
				CASE 
					WHEN b.FDC=b.SONFDC THEN SUM(ISNULL(BORIBALANCE,0)) 
					ELSE -SUM(ISNULL(BORIBALANCE,0)) 
				END AS BORIBALANCE,
				CASE 
					WHEN b.FDC=b.SONFDC THEN SUM(ISNULL(ESELFBALANCE,0)) 
					ELSE -SUM(ISNULL(ESELFBALANCE,0)) 
				END AS ESELFBALANCE,
				CASE 
					WHEN b.FDC=b.SONFDC THEN SUM(ISNULL(EORIBALANCE,0)) 
					ELSE -SUM(ISNULL(EORIBALANCE,0)) 
				END AS EORIBALANCE
		FROM  #temp2 b 
		JOIN #temp6 c ON b.SONID=c.SONID
		GROUP BY b.STYPEID,b.FATHERID,b.FDC,b.SONFDC,c.FPERIOD,c.CID
	) a
	GROUP BY a.STYPEID,a.FATHERID,a.FPERIOD,a.FDC,a.CID
	------------#AccountData关联#temp5，剔除不符合条件的查询科目
	SELECT a.STYPEID,
		   a.TYPEID,
		   a.CID,
		   FDC,
		   SELFBORROW,
		   ORIBORROW,
		   SELFLEND,
		   ORILEND,
		   YEARSELFBORROW,
		   YEARORIBORROW,
		   YEARSELFLEND,
		   YEARORILEND,
		   BSELFBALANCE,
		   BORIBALANCE,
		   ESELFBALANCE,
		   EORIBALANCE,
		   FPERIOD 
	INTO #temp7
	FROM #AccountData a
	JOIN #temp5 b ON a.STYPEID=b.STYPEID AND a.TYPEID=b.TYPEID
	
	--不包含结转损益数据单独处理 by:2014-08-29
	IF(@IsShowPL=1)
		BEGIN
			--凭证表临时表
			CREATE TABLE #VoucherBill
			(
				ATypeId		VARCHAR(50),				--科目ID
				Cid			INT,						--币种
				FYear		INT,						--年度
				FPeriod		INT,						--期间
				OFDebitFor	 NUMERIC(24, 10)  DEFAULT 0,	--本位币借方
				OFCreditFor	 NUMERIC(24, 10)  DEFAULT 0,	--本位币贷方
				SFDebitFor	 NUMERIC(24, 10)  DEFAULT 0,	--原币借方
				SFCreditFor	 NUMERIC(24, 10)  DEFAULT 0		--原币贷方
			)
			INSERT INTO #VoucherBill(ATypeId,Cid,FYear,FPeriod,OFDebitFor,OFCreditFor)
			SELECT
				B.ATypeId,
				0 Cid,
				B.FYear,
				B.FPeriod,
				SUM(B.FDebitTotal) OFDebitFor,
				SUM(B.FCreditTotal) OFCreditFor
			FROM Ac_Voucher V 
			INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND ((@IsPost=0 AND V.IfCheck='T') OR @IsPost=1)  AND V.FChecked<>-1
			INNER JOIN #temp1 T ON B.ATypeId LIKE T.TypeId+'%'	
			WHERE 
				B.STypeId=@StypeId
				AND B.FYear=@Fyear
				AND B.FPeriod>=@FPeriodStart
				AND B.FPeriod<=@FPeriodEnd
				AND V.VoucherType=2
			GROUP BY B.ATypeId,B.FYear,B.FPeriod

			INSERT INTO #VoucherBill(ATypeId,Cid,FYear,FPeriod,SFDebitFor,SFCreditFor)
			SELECT
				B.ATypeId,
				B.Cid,
				B.FYear,
				B.FPeriod,
				SUM(FDebitTotalFor) SFDebitFor,
				SUM(FCreditTotalFor) SFCreditFor
			FROM Ac_Voucher V 
			INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND ((@IsPost=0 AND V.IfCheck='T') OR @IsPost=1)  AND V.FChecked<>-1
			INNER JOIN #temp1 T ON B.ATypeId LIKE T.TypeId+'%'
			WHERE 
				B.STypeId=@StypeId
				AND B.FYear=@Fyear
				AND B.FPeriod>=@FPeriodStart
				AND B.FPeriod<=@FPeriodEnd
				AND V.VoucherType=2
			GROUP BY B.ATypeId,B.Cid,B.FYear,B.FPeriod
			--减掉本位币相应的金额
			UPDATE #temp7
			SET 
				ORIBORROW-=T.FDebitFor,
				ORILEND-=T.FCreditFor,
				YEARORIBORROW-=T.FDebitFor,
				YEARORILEND-=T.FCreditFor,
				EORIBALANCE-=CASE WHEN B.FDC=1 THEN T.FDebitFor ELSE T.FCreditFor END
			FROM #temp7 B
			INNER JOIN (SELECT ATypeId,FPeriod,SUM(OFDebitFor) AS FDebitFor,SUM(OFCreditFor) AS FCreditFor FROM  #VoucherBill WHERE CID=0 GROUP BY ATypeId,FPeriod ) T ON T.ATypeId=B.TypeId AND B.FPeriod=T.FPeriod	
			--减掉原币相应的金额
			UPDATE #temp7
			SET 
				SELFBORROW-=T.FDebitFor,
				SELFLEND-=T.FCreditFor,
				YEARSELFBORROW-=T.FDebitFor,
				YEARSELFLEND-=T.FCreditFor,
				ESELFBALANCE-=CASE WHEN B.FDC=1 THEN T.FDebitFor ELSE T.FCreditFor END
			FROM #temp7 B
			INNER JOIN (SELECT ATypeId,CID,FPeriod,SUM(SFDebitFor) AS FDebitFor,SUM(SFCreditFor) AS FCreditFor FROM #VoucherBill GROUP BY ATypeId,CID,FPeriod ) T ON T.ATypeId=B.TypeId AND B.FPeriod=T.FPeriod AND B.CID=T.CID
						
			DROP TABLE #VoucherBill
		END
	------------根据#temp7生成最后符合格式的数据------------------------------------------------------------------------------------
	CREATE TABLE #GeneralBegin
	(
		TYPEID			VARCHAR(50),
		CID				INT,
		FULLNAME		VARCHAR(200),
		USERCODE		VARCHAR(200),
		FPERIOD 		INT,					--期间
		SUMMARY			VARCHAR(400),			--摘要
		FDEBITTOTAL		 NUMERIC(24, 10) ,			--借本
		FDEBITTOTALFOR	 NUMERIC(24, 10) ,			--借原
		FCREDITTOTAL	 NUMERIC(24, 10) ,			--贷本
		FCREDITTOTALFOR	 NUMERIC(24, 10) ,			--贷原
		FDC				VARCHAR(10),			--方向
		TOTAL			 NUMERIC(24, 10) ,			--余额本
		TOTALFOR		 NUMERIC(24, 10) 			--余额原
	)	
	CREATE TABLE #GeneralPeriod
	(
		TYPEID			VARCHAR(50),
		CID				INT,
		FULLNAME		VARCHAR(200),
		USERCODE		VARCHAR(200),
		FPERIOD 		INT,					--期间
		SUMMARY			VARCHAR(400),			--摘要
		FDEBITTOTAL		 NUMERIC(24, 10) ,			--借本
		FDEBITTOTALFOR	 NUMERIC(24, 10) ,			--借原
		FCREDITTOTAL	 NUMERIC(24, 10) ,			--贷本
		FCREDITTOTALFOR	 NUMERIC(24, 10) ,			--贷原
		FDC				VARCHAR(10),			--方向
		TOTAL			 NUMERIC(24, 10) ,			--余额本
		TOTALFOR		 NUMERIC(24, 10) 			--余额原
	)	
	CREATE TABLE #GeneralYear
	(
		TYPEID			VARCHAR(50),
		CID				INT,
		FULLNAME		VARCHAR(200),
		USERCODE		VARCHAR(200),
		FPERIOD 		INT,					--期间
		SUMMARY			VARCHAR(400),			--摘要
		FDEBITTOTAL		 NUMERIC(24, 10) ,			--借本
		FDEBITTOTALFOR	 NUMERIC(24, 10) ,			--借原
		FCREDITTOTAL	 NUMERIC(24, 10) ,			--贷本
		FCREDITTOTALFOR	 NUMERIC(24, 10) ,			--贷原
		FDC				VARCHAR(10),			--方向
		TOTAL			 NUMERIC(24, 10) ,			--余额本
		TOTALFOR		 NUMERIC(24, 10) 			--余额原
	)	
	INSERT INTO #GeneralBegin
	SELECT a.TYPEID,
		   a.CID,
		   b.FULLNAME,
		   b.USERCODE,
		   a.FPERIOD,
		   '期初余额' AS SUMMARY,
			0 AS FDEBITTOTAL,
			0 AS FDEBITTOTALFOR,
			0 AS FCREDITTOTAL, 
			0 AS FCREDITTOTALFOR, 
			CASE 
				WHEN a.BSELFBALANCE=0 THEN '平' 
			    WHEN a.FDC=1 THEN '借'
			    ELSE '贷'
			END AS FDC,
			BSELFBALANCE,
			BORIBALANCE
	FROM #temp7 a                     
	JOIN #temp1 b ON a.TYPEID=b.TYPEID
	WHERE FPERIOD=@FPeriodStart	
	
	INSERT INTO #GeneralPeriod
	SELECT a.TYPEID,
		   a.CID,
		   b.FULLNAME,
		   b.USERCODE,
		   a.FPERIOD,
		   '本期合计' AS SUMMARY,
		   SELFBORROW,
		   ORIBORROW,
		   SELFLEND, 
		   ORILEND,
			CASE 
				WHEN a.ESELFBALANCE=0 THEN '平'
				WHEN a.FDC=1 THEN '借'
				ELSE '贷'
			END AS FDC,
		    ESELFBALANCE,
		    EORIBALANCE
	FROM #temp7 a 
	JOIN #temp1 b ON a.TYPEID=b.TYPEID
	
	INSERT INTO #GeneralYear
	SELECT a.TYPEID,
		   a.CID,
		   b.FULLNAME,
		   b.USERCODE,
		   a.FPERIOD,
		   '本年累计' AS SUMMARY,
			YEARSELFBORROW,
			YEARORIBORROW,
			YEARSELFLEND,
			YEARORILEND, 
			CASE 
				WHEN a.ESELFBALANCE=0 THEN '平'
				WHEN a.FDC=1 THEN '借'
				ELSE '贷'
			END AS FDC,
		    ESELFBALANCE,
		    EORIBALANCE
	FROM #temp7 a 
	JOIN #temp1 b ON a.TYPEID=b.TYPEID
	
	---------------------------------------------所有币别是动态列,先求出有多少列----------------------------------------------------------------
	SELECT COLNAME,FDC 
	INTO #tempColName1 
	FROM (SELECT 'borrow' AS COLNAME,'借' AS FDC 
	UNION ALL
	SELECT 'lend' AS COLNAME,'贷' AS FDC 
	UNION ALL 
	SELECT 'balance' AS COLNAME,'余额' AS FDC) a
     
	SELECT CID,USERCODE 
	INTO #tempColName2
	FROM (SELECT CID,USERCODE FROM AC_CURRENCY
	UNION ALL 
	SELECT 0 AS CID,'self' AS USERCODE) b
   
	--#temp表中的colname值就是结果表中的列名，即该表有多少条数据，在结果表中就有多少列显示
	SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,FDC,CID 
	INTO #tempColName
	FROM #tempColName1,#tempColName2
	
	--行转列的时候用
	DECLARE @TurnCol VARCHAR(MAX)
	SELECT @TurnCol=(ISNULL(@TurnCol+'],[','') +  COLNAME) 
	FROM #tempColName GROUP BY COLNAME 
	SET @TurnCol='['+@TurnCol+']'
	----------------------------------行专列临时表-----------------------------------------------------------------------------------------------------
	CREATE TABLE #tempGeneralBegin
	(
	    TYPEID			VARCHAR(50),
		FPERIOD 		INT,					
		COLNAME			VARCHAR(MAX),
		FVALUE			 NUMERIC(24, 10) 
	)
	INSERT INTO #tempGeneralBegin
	SELECT b.TYPEID,
		   b.FPERIOD,
		   a.COLNAME,
		CASE 
			WHEN a.FDC='借' AND a.CID=b.CID THEN FDEBITTOTALFOR
			WHEN a.FDC='贷' AND a.CID=b.CID THEN FCREDITTOTALFOR
			WHEN a.FDC='余额' AND a.CID=b.CID THEN TOTALFOR
		END
	FROM #tempColName a,#GeneralBegin b
	
	CREATE TABLE #tempGeneralPeriod
	(
	    TYPEID			VARCHAR(50),
		FPERIOD 		INT,					
		COLNAME			VARCHAR(MAX),
		FVALUE			 NUMERIC(24, 10) 
	)
	INSERT INTO #tempGeneralPeriod
	SELECT b.TYPEID,
		   b.FPERIOD,
		   a.COLNAME,
		CASE 
			WHEN a.FDC='借' AND a.CID=b.CID THEN FDEBITTOTALFOR
			WHEN a.FDC='贷' AND a.CID=b.CID THEN FCREDITTOTALFOR
			WHEN a.FDC='余额' AND a.CID=b.CID THEN TOTALFOR
		END
	FROM #tempColName a,#GeneralPeriod b
	
	CREATE TABLE #tempGeneralYear
	(
	    TYPEID			VARCHAR(50),
		FPERIOD 		INT,					
		COLNAME			VARCHAR(MAX),
		FVALUE			 NUMERIC(24, 10) 
	)
	INSERT INTO #tempGeneralYear
	SELECT b.TYPEID,
		   b.FPERIOD,
		   a.COLNAME,
		CASE 
			WHEN a.FDC='借' AND a.CID=b.CID   THEN FDEBITTOTALFOR
			WHEN a.FDC='贷' AND a.CID=b.CID   THEN FCREDITTOTALFOR
			WHEN a.FDC='余额' AND a.CID=b.CID THEN TOTALFOR
		END
	FROM #tempColName a,#GeneralYear b
	
    SET @SQL='SELECT * 
		  INTO #temp 
		  FROM
		 (
	      SELECT a.TYPEID,
				 a.FPERIOD,
				 a.FULLNAME,
				 a.USERCODE,
				 a.SUMMARY,
				 a.FDC,
				 '+@TurnCol+'
		  FROM #GeneralBegin a
		  JOIN (
		         SELECT *  FROM  #tempGeneralBegin  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
			   ) b ON a.TYPEID=b.TYPEID AND a.FPERIOD=b.FPERIOD
		   WHERE a.CID=0
		   UNION ALL
		  SELECT  a.TYPEID,
				  a.FPERIOD,
				  a.FULLNAME,
				  a.USERCODE,
				  a.SUMMARY,
				  a.FDC,
				  '+@TurnCol+'
		  FROM #GeneralPeriod a
		  JOIN (
		         SELECT *  FROM  #tempGeneralPeriod  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
			   ) b ON a.TYPEID=b.TYPEID AND a.FPERIOD=b.FPERIOD
		   WHERE a.CID=0
		   UNION ALL
		   SELECT  a.TYPEID,
				   a.FPERIOD,
				   a.FULLNAME,
				   a.USERCODE,
				   a.SUMMARY,
				   a.FDC,
				   '+@TurnCol+'
		  FROM #GeneralYear a
		  JOIN (
		         SELECT *  FROM  #tempGeneralYear  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
			   ) b ON a.TYPEID=b.TYPEID AND a.FPERIOD=b.FPERIOD
		   WHERE a.CID=0
		   ) c  '
    IF @Cid=0
		SET @SQL+=' SELECT a.* FROM #temp a JOIN dbo.Ac_Account aa ON a.TYPEID=aa.TypeId AND aa.StypeId='''+@STypeId+''' 	INNER JOIN F_LineAccount('''+@chvOperatorID+''','''') F ON F.TypeId=AA.TypeId AND F.StypeId=AA.StypeId
  ORDER BY aa.USERCODE,a.FPERIOD,SUMMARY DESC'
	ELSE 
		SET @SQL+=' SELECT a.TYPEID,
						   a.USERCODE,
						   a.FULLNAME,
						   a.FPERIOD,
						   a.SUMMARY,
						   a.BORROWSELF  AS FDEBITTOTAL,
						   a.LENDSELF	   AS FCREDITTOTAL,
						   a.BALANCESELF AS TOTAL,
						   a.FDC         AS FDC
					FROM #temp a
					JOIN dbo.Ac_Account aa ON a.TYPEID=aa.TypeId AND aa.StypeId='''+@STypeId+'''
					INNER JOIN F_LineAccount('''+@chvOperatorID+''','''') F ON F.TypeId=AA.TypeId AND F.StypeId=AA.StypeId
					ORDER BY aa.USERCODE,a.FPERIOD,SUMMARY DESC'
	EXEC(@SQL)
	DROP TABLE #tempAcBalance,#temp1,#temp2,#temp3,#temp4,#AccountTotalData,#temp5,#Cid,#temp6,#AccountData,#temp7,#GeneralBegin,#GeneralPeriod,#GeneralYear,#tempColName1,#tempColName2,#tempColName,#tempGeneralBegin,#tempGeneralPeriod,#tempSonAccountPeriod,#tempSonAccountYear
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_AcAssistBalanceDetailFromVoucher]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].WEB_AcAssistBalanceDetailFromVoucher
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：佘海源
	日期：2012-06-05
	描述：辅助余额表-在凭证中未过账查询
	
*/
CREATE PROCEDURE WEB_AcAssistBalanceDetailFromVoucher
(
	@IsShowNoAccount	INT,			---是否显示未过账
	@Fyear				INT,	---年度
	@STypeId			VARCHAR(50)		---分支机构
	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @iniFyear INT, 
		@PreMaxFperiod INT
SELECT TOP 1 @iniFYear=SUBVALUE FROM SYSDATA WHERE SUBNAME='fyear'
--SELECT @PreMaxFperiod=MAX(FPeriod) FROM dbo.Ac_Period	
SELECT @PreMaxFperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance WHERE FYear=@Fyear-1	 AND STypeId=STypeId


IF (@IsShowNoAccount=0)
	BEGIN
		--修改bug，后期优化改存储过程
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId)--如果指定分支机构没有开账
			BEGIN
				DECLARE @Details TABLE(STypeId VARCHAR(50),ATypeId VARCHAR(50),Cid INT,AscIds INT,Fieldvalue VARCHAR(50),FDebit  NUMERIC(24, 10) ,FDebitFor  NUMERIC(24, 10) ,FCredit  NUMERIC(24, 10) ,FCreditFor  NUMERIC(24, 10) ,IniTotal  NUMERIC(24, 10) ,IniTotalFor  NUMERIC(24, 10) ,Fendbalance  NUMERIC(24, 10) ,Fendbalancefor	 NUMERIC(24, 10) ,FYear VARCHAR(10),FPeriod INT)
				--插入财务期初数据
				INSERT INTO @Details(STypeId,ATypeId,Cid,Ascids,FieldValue,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,Fendbalance,Fendbalancefor,FYear,FPeriod)			
				SELECT 
					D.STypeId,
					ATypeId,
					D.Cid,
					D.Ascids,
					FieldValue,
					0 FDebit,
					0 FDebitFor,
					0 FCredit,
					0 FCreditFor,
					IniTotal,
					IniTotalFor,
					IniTotal AS  Fendbalance,
					IniTotalFor AS Fendbalancefor,
					FYear,
					FPeriod 
				FROM Ac_IniAccount_Assist_CheckItems_Detail D  
				INNER JOIN Ac_Account A ON A.TypeId=D.ATypeId AND D.STypeId=A.StypeId AND D.STypeId=@STypeId AND D.FYear=@Fyear
				--返回期初数据值
				SELECT 
					STypeId,
					ATypeId,
					Cid,
					Ascids,
					FieldValue,
					FDebit,
					FDebitFor,
					FCredit,
					FCreditFor,
					IniTotal,
					IniTotalFor,
					Fendbalance,
					Fendbalancefor,
					FYear,
					FPeriod
				FROM @Details 
				UNION  ALL
				SELECT 
					STypeId,
					ATypeId,
					0 Cid,
					Ascids,
					FieldValue,
					SUM(ISNULL(FDebit,0)) FDebit,
					SUM(ISNULL(FDebitFor,0)) FDebitFor,
					SUM(ISNULL(FCredit,0)) FCredit,
					SUM(ISNULL(FCreditFor,0)) FCreditFor,
					SUM(ISNULL(IniTotal,0)) IniTotal,
					SUM(ISNULL(IniTotalFor,0)) IniTotalFor,
					SUM(ISNULL(Fendbalance,0)) Fendbalance,
					SUM(ISNULL(Fendbalancefor,0)) Fendbalancefor,
					@Fyear,
					FPeriod
				FROM @Details 	
				GROUP BY STypeId,ATypeId,AscIds,Fieldvalue,FPeriod						
			END
		ELSE
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM dbo.AC_BALANCE_ASSIST_CHECKITEMS_DETAIL WHERE FYear=@Fyear)
					SELECT 
						STypeId,
						ATypeId,
						Cid,
						Ascids,
						FieldValue,
						FDebit,
						FDebitFor,
						FCredit,
						FCreditFor,
						IniTotal,
						IniTotalFor,
						Fendbalance,
						Fendbalancefor,
						FYear,
						FPeriod 
					FROM AC_BALANCE_ASSIST_CHECKITEMS_DETAIL  WHERE STypeId=@STypeId AND FYear=@Fyear
				ELSE 
					SELECT STypeId,ATypeId,cid,Ascids,FieldValue,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,Fendbalance,Fendbalancefor,@Fyear,1
					FROM AC_BALANCE_ASSIST_CHECKITEMS_DETAIL  
					WHERE STypeId=@STypeId AND FYear=@Fyear-1 AND FPeriod=@PreMaxFperiod
			END
				
		RETURN 
	END

CREATE TABLE #tempAcBalanceAssistDetailTable  ---辅助核算余额明细表临时表
(
   	STypeId             VARCHAR(50),       
	ATypeId             VARCHAR(50),        
	Cid                 INT,           
	AscIds              INT,                
	Fieldvalue           VARCHAR(50),        
	FDebit				 NUMERIC(24, 10) ,		
	FDebitFor			 NUMERIC(24, 10) ,		
	FCredit				 NUMERIC(24, 10) ,		
	FCreditFor			 NUMERIC(24, 10) ,		
	IniTotal			 NUMERIC(24, 10) ,	
	IniTotalFor			 NUMERIC(24, 10) ,		
	Fendbalance			 NUMERIC(24, 10) ,		
	Fendbalancefor		 NUMERIC(24, 10) ,		
	FYear               VARCHAR(10),       
	FPeriod             INT,
	Fdc					INT          
)

 

/********************************************获取账务数据*************************************/
CREATE TABLE #Ac_IniAccount_AssistTemp
(
	stypeid VARCHAR(50),
	atypeid VARCHAR(50),
	cid INT,
	ascids   INT,
	FieldValue VARCHAR(50),
	fyear VARCHAR(10),
	fperiod INT,
	IniTotal  NUMERIC(24, 10) ,
	IniTotalFor  NUMERIC(24, 10) 
)
IF @iniFyear=@Fyear
		INSERT INTO #Ac_IniAccount_AssistTemp
		SELECT	STypeId,
				ATypeId,
				Cid,
				Ascids,
				FieldValue,
				FYear,
				FPeriod,
				Sum(IniTotal) AS IniTotal ,
				Sum(IniTotalFor) AS IniTotalFor
		FROM	Ac_IniAccount_Assist_CheckItems_Detail
	GROUP BY	STypeId,ATypeId,Cid,Ascids,FieldValue,FYear,FPeriod
ELSE 
	INSERT INTO #Ac_IniAccount_AssistTemp
	SELECT	STypeId,
				ATypeId,
				Cid,
				Ascids,
				FieldValue,
				@Fyear,
				1,
				Sum(FEndBalance) AS IniTotal ,
				Sum(FEndBalanceFor) AS IniTotalFor
		FROM	dbo.Ac_Balance_Assist_CheckItems_Detail
		WHERE cid<>0 AND FYear=@Fyear-1 AND FPeriod=@PreMaxFperiod
	GROUP BY	STypeId,ATypeId,Cid,Ascids,FieldValue,FYear,FPeriod
/********************************************获取凭证科目数据（包含过账和未过账）*************************************/
INSERT INTO	#tempAcBalanceAssistDetailTable
SELECT A.STypeId,
	A.ATypeId,
	A.Cid,
	CI.AscIds,
	C.TypeId AS Fieldvalue,
	SUM(A.FDebitTotal) AS FDebit ,
	SUM(A.FDebitTotalFor) AS FDebitFor,
	SUM(A.FCreditTotal) AS FCredit,
	SUM(A.FCreditTotalFor) AS FCreditFor,
	0 AS IniTotal ,
	0 AS IniTotalFor,
	0 AS Fendbalance,
	0 AS Fendbalancefor,
	A.FYear,
	A.FPeriod,
	D.Fdc
FROM	Ac_Voucher_Bill A
JOIN	Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1
JOIN	Ac_Voucher_Bill_Assist_CheckItems C ON A.ID = C.vBId
INNER JOIN Ac_Assist_CheckItems CI ON CI.UserCode=C.typeName
JOIN	Ac_Account D ON D.TypeId=A.ATypeId AND D.StypeId=A.STypeId
WHERE	A.FYear = @Fyear AND A.STypeId=@STypeId		
GROUP BY A.FYear,A.FPeriod,A.STypeId,A.ATypeId,C.typeName,C.TypeId,A.Cid,D.Fdc ,CI.AscIds
IF(@iniFyear<>@Fyear)
	BEGIN
		SELECT 
			A.STypeId,
			A.ATypeId,
			A.Cid,
			CI.AscIds,
			C.TypeId AS Fieldvalue,
			SUM(A.FDebitTotal) AS FDebit ,
			SUM(A.FDebitTotalFor) AS FDebitFor,
			SUM(A.FCreditTotal) AS FCredit,
			SUM(A.FCreditTotalFor) AS FCreditFor,
			0 AS IniTotal ,
			0 AS IniTotalFor,
			0 AS Fendbalance,
			0 AS Fendbalancefor,
			A.FAdc,
			C.typeName
		INTO #VoucherTemp
		FROM	Ac_Voucher_Bill A
		JOIN	Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1 AND B.IfCheck='f'
		JOIN	Ac_Voucher_Bill_Assist_CheckItems C ON A.ID = C.vBId
		INNER JOIN Ac_Assist_CheckItems CI ON CI.UserCode=C.typeName
		WHERE	A.FYear < @Fyear AND A.STypeId=@STypeId		
		GROUP BY A.STypeId,A.ATypeId,C.typeName,C.TypeId,A.Cid,A.FAdc ,CI.AscIds

		INSERT INTO  #tempAcBalanceAssistDetailTable
		SELECT 
			@STypeId STypeId,
			T.ATypeId,
			T.Cid,
			T.AscIds,
			T.Fieldvalue,
			0 FDebit,
			0 FDebitFor,
			0 FCredit,
			0 FCreditFor,
			0 IniTotal,
			0 IniTotalFor,
			0 Fendbalance,
			0 Fendbalancefor,
			@Fyear FYear,
			1 FPeriod,
			A.Fdc
		FROM #VoucherTemp T
		INNER JOIN Ac_Account A ON A.TypeId=T.ATypeId 
		INNER JOIN #tempAcBalanceAssistDetailTable B ON B.ATypeId<>T.ATypeId OR B.Cid<>T.Cid OR B.AscIds<>T.AscIds OR B.Fieldvalue<>T.Fieldvalue
		GROUP BY T.ATypeId,T.Cid,A.Fdc,T.AscIds,T.Fieldvalue
		
		
		---修改bug
		INSERT INTO  #tempAcBalanceAssistDetailTable
		SELECT 
			@STypeId STypeId,
			T.ATypeId,
			T.Cid,
			T.AscIds,
			T.Fieldvalue,
			0 FDebit,
			0 FDebitFor,
			0 FCredit,
			0 FCreditFor,
			0 IniTotal,
			0 IniTotalFor,
			0 Fendbalance,
			0 Fendbalancefor,
			@Fyear FYear,
			1 FPeriod,
			A.Fdc
		FROM #VoucherTemp T
		INNER JOIN Ac_Account A ON A.TypeId=T.ATypeId 
		LEFT JOIN #tempAcBalanceAssistDetailTable B ON B.ATypeId=T.ATypeId AND  B.Cid=T.Cid AND B.AscIds=T.AscIds AND B.Fieldvalue=T.Fieldvalue AND B.ATypeId IS NULL
		GROUP BY T.ATypeId,T.Cid,A.Fdc,T.AscIds,T.Fieldvalue
		 
		
		UPDATE #tempAcBalanceAssistDetailTable
		SET	IniTotal+=CASE WHEN T.Fdc=V.FAdc AND T.Fdc=1 THEN V.FDebit ELSE -V.FCredit END,
			IniTotalFor+=CASE WHEN T.Fdc=V.FAdc AND T.Fdc=1 THEN V.FDebitFor ELSE -V.FCreditFor END,
			Fendbalance+=CASE WHEN T.Fdc=V.FAdc AND T.Fdc=1 THEN V.FDebit ELSE -V.FCredit END,
			Fendbalancefor+=CASE WHEN T.Fdc=V.FAdc AND T.Fdc=1 THEN V.FDebitFor ELSE -V.FCreditFor END
		FROM #tempAcBalanceAssistDetailTable T
		INNER JOIN #VoucherTemp V ON T.ATypeId=V.ATypeId AND T.Cid=V.Cid AND T.AscIds=V.AscIds AND T.Fieldvalue=V.Fieldvalue
		WHERE T.Fyear=@Fyear AND T.Fperiod=1		
		DROP TABLE #VoucherTemp	
	END	

			/**********根据期初赋值第一期期初数据******/
			IF @iniFyear=@Fyear
				UPDATE  #tempAcBalanceAssistDetailTable
				SET		IniTotal=B.IniTotal,
						IniTotalFor = B.IniTotalFor
				FROM	#tempAcBalanceAssistDetailTable A
				JOIN	#Ac_IniAccount_AssistTemp B ON B.FYear=@Fyear AND A.FPeriod = B.FPeriod 
						AND B.STypeId=@STypeId AND A.ATypeId = B.ATypeId AND A.AscIds=B.Ascids 
						AND A.Fieldvalue=B.FieldValue AND	A.Cid = B.Cid 
			ELSE 
				UPDATE  #tempAcBalanceAssistDetailTable
				SET		IniTotal+=B.IniTotal,
						IniTotalFor += B.IniTotalFor
				FROM	#tempAcBalanceAssistDetailTable A
				JOIN	#Ac_IniAccount_AssistTemp B ON B.FYear=@Fyear 
						AND B.STypeId=@STypeId AND A.ATypeId = B.ATypeId AND A.AscIds=B.Ascids 
						AND A.Fieldvalue=B.FieldValue AND	A.Cid = B.Cid 

			/**********根据期初期间 插入期初辅助明细科目数据(并集)******/
			INSERT INTO	#tempAcBalanceAssistDetailTable
				 SELECT A.STypeId,
						ATypeId,
						A.Cid,
						A.Ascids,
						FieldValue,
						0,0,0,0,
						IniTotal,
						IniTotalFor,
						IniTotal,
						IniTotalFor,
						FYear,
						FPeriod,
						B.Fdc
				 FROM	#Ac_IniAccount_AssistTemp A
				 INNER JOIN Ac_Account B ON B.StypeId=@STypeId AND A.ATypeId=B.TypeId
				 --JOIN	(SELECT TypeId,Fdc FROM Ac_Account WHERE StypeId=@STypeId ) B ON A.ATypeId=B.TypeId
				 WHERE  FYear=@Fyear AND A.STypeId=@STypeId AND	
						NOT EXISTS(SELECT * FROM #tempAcBalanceAssistDetailTable 
									WHERE FYear=@Fyear AND  STypeId=@STypeId  AND Fperiod=A.FPeriod 
									AND  ATypeId=A.ATypeId AND AscIds=A.Ascids AND Fieldvalue= A.FieldValue 
									AND Cid=A.Cid
									)		
				/*****************计算第一期期末***************/
					UPDATE	#tempAcBalanceAssistDetailTable
					SET		FEndBalance = 
							(CASE	WHEN Fdc=1	THEN FDebit-FCredit+IniTotal
									WHEN Fdc=-1	THEN FCredit-FDebit+IniTotal
							END),
							FEndBalanceFor = 
							(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+IniTotalFor
									WHEN Fdc=-1	THEN FCreditFor-FDebitFor+IniTotalFor
							END)
					FROM	#tempAcBalanceAssistDetailTable
					WHERE	Fperiod=(SELECT MIN(Fperiod) FROM #tempAcBalanceAssistDetailTable)		

	

		
/*********************************************************************************************************************/	
/*													按期间循环计算													 */
/* 参数	@MaxFPeriod：最大期间  	@MinFPeriod：初始期间		@FPeriodNum：期间循环参数，初始=@MinFPeriod																										 */
/*********************************************************************************************************************/		 
	DECLARE @MaxFPeriod INT  
	DECLARE @MinFPeriod INT
	DECLARE @MaxFPeriodVocher INT  
	IF @iniFyear=@Fyear
			BEGIN
				SELECT @MaxFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='FPeriod'
				SELECT @MinFPeriod=ISNULL(MIN(CONVERT(INT,FPeriod)),@MaxFPeriod)  FROM Ac_Balance WHERE STypeId=@STypeId AND FYear=@Fyear
			END
		ELSE 
			BEGIN
				SELECT @MinFPeriod=MIN(FPeriod) FROM #tempAcBalanceAssistDetailTable
				SELECT @MaxFPeriod=MAX(FPeriod) FROM dbo.Ac_Period
			END
	SELECT  @MaxFPeriodVocher=IsNULL(MAX(CONVERT(INT,FPeriod)),0) FROM #tempAcBalanceAssistDetailTable  
	IF @MaxFPeriodVocher>@MaxFPeriod SET @MaxFPeriod=@MaxFPeriodVocher
	
	DECLARE @FPeriodNum INT SET  @FPeriodNum=@MinFPeriod+1
	
	WHILE @FPeriodNum<=@MaxFPeriod
	BEGIN
		
	/***********************************根据上一期进行本期计算*********************************
	** 期初=上期期末		期末=期初+本期发生	
	** 本期科目=上一期科目+本期发生科目	
	** 本期有的科目而上期没有的科目	期初默认0 所有只计算期末									
	*******************************************************************************************/

		 /*上期临时表*/
		 SELECT *  INTO #PreDetailTempTable 
		 FROM #tempAcBalanceAssistDetailTable 
		 WHERE FPeriod=@FPeriodNum-1
		 
		/******************计算期初********************/
		UPDATE	#tempAcBalanceAssistDetailTable
		SET		IniTotal=B.Fendbalance,
				IniTotalFor=B.FendbalanceFor
		FROM	#tempAcBalanceAssistDetailTable A
		JOIN	#PreDetailTempTable B 
		ON		A.ATypeId = B.ATypeId AND A.Cid=B.Cid AND A.AscIds=B.AscIds AND A.Fieldvalue = B.Fieldvalue
		WHERE	A.FPeriod = @FPeriodNum

		/******************计算期末********************/
		UPDATE	#tempAcBalanceAssistDetailTable
		SET		FEndBalance = 
				(CASE	WHEN Fdc=1	THEN FDebit-FCredit+IniTotal
						WHEN Fdc=-1	THEN FCredit-FDebit+IniTotal
				END),
				FEndBalanceFor = 
				(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+IniTotalFor
						WHEN Fdc=-1	THEN FCreditFor-FDebitFor+IniTotalFor
				END)
	/***********************合并上期科目**********************************************/
	/* 上期科目本期没有发生额，直接复制到本期--本期期初=上期期末=本期期末 本期发生=0 */
	/*********************************************************************************/
		
		 /*本期临时表*/
		SELECT * INTO #CurDetailTempTable 
				FROM  #tempAcBalanceAssistDetailTable 
				WHERE FPeriod = @FPeriodNum
		
		INSERT INTO	#tempAcBalanceAssistDetailTable 
			 SELECT	A.STypeId,
					A.ATypeId,
					A.Cid,
					A.AscIds,
					A.Fieldvalue,
					0,0,0,0,
					A.Fendbalance,
					A.FendbalanceFor,
					A.Fendbalance,
					A.FendbalanceFor,
					A.FYear,
					@FPeriodNum,
					A.Fdc
			   FROM #PreDetailTempTable A
			  WHERE NOT EXISTS(SELECT * FROM #CurDetailTempTable WHERE ATypeId=A.ATypeId 
								AND AscIds=A.AscIds AND Fieldvalue=A.Fieldvalue  AND Cid=A.Cid  )
			  		 	
		DROP TABLE #PreDetailTempTable,#CurDetailTempTable
	--	/*循环下一期间*/
		SET @FPeriodNum=@FPeriodNum+1
	END /*循环结束*/
	
	
	ALTER TABLE #tempAcBalanceAssistDetailTable DROP COLUMN Fdc    /*Fdc不是AC_Balance默认字段 此处作为临时使用，故删除*/
	
			
/************************************************************************************************/
/*										计算综合本位币											*/
/************************************************************************************************/		
	INSERT INTO #tempAcBalanceAssistDetailTable
		SELECT	STypeId,
				ATypeId,
				0,
				AscIds,
				Fieldvalue,
				SUM(FDebit),
				SUM(FDebit),
				SUM(FCredit),
				SUM(FCredit),
				SUM(IniTotal),
				SUM(IniTotal),
				SUM(Fendbalance),
				SUM(Fendbalance),
				@Fyear,
				FPeriod
		  FROM	#tempAcBalanceAssistDetailTable
		  GROUP BY STypeId,FPeriod,ATypeId,AscIds,Fieldvalue
	
 SELECT  * FROM #tempAcBalanceAssistDetailTable ORDER BY AtypeId
 DROP TABLE #Ac_IniAccount_AssistTemp,#tempAcBalanceAssistDetailTable


	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_AcAssistBalanceFromVoucher]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_AcAssistBalanceFromVoucher]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：佘海源
	日期：2012-06-05
	描述：科目辅助余额表-在凭证中未过账查询
	
*/
CREATE PROCEDURE WEB_AcAssistBalanceFromVoucher
(
	@IsShowNoAccount INT,	---是否显示未过账
	@Fyear INT,		---年度
	@STypeId VARCHAR(50)	---分支机构
	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @iniFyear INT, 
		@PreMaxFperiod INT
SELECT TOP 1 @iniFYear=SUBVALUE FROM SYSDATA WHERE SUBNAME='fyear'
SELECT @PreMaxFperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance WHERE FYear=@Fyear-1	 AND STypeId=STypeId

IF (@IsShowNoAccount=0)
	BEGIN
		--修改bug，后期优化改存储过程
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId)--如果指定分支机构没有开账
			BEGIN
				DECLARE @Details TABLE(STypeId VARCHAR(50),ATypeId VARCHAR(50),Cid INT,IniYTotal  NUMERIC(24, 10) ,IniYTotalFor          NUMERIC(24, 10) ,FDebit  NUMERIC(24, 10) ,FDebitFor  NUMERIC(24, 10) ,FCredit  NUMERIC(24, 10) ,FCreditFor  NUMERIC(24, 10) ,IniTotal  NUMERIC(24, 10) ,IniTotalFor  NUMERIC(24, 10) ,Fyear VARCHAR(10),Fperiod VARCHAR(10),Fendbalance  NUMERIC(24, 10) ,Fendbalancefor	     NUMERIC(24, 10) )
				--插入财务期初数据			
				INSERT INTO @Details(STypeId,ATypeId,Cid,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,Fyear,Fperiod,Fendbalance,Fendbalancefor)
				SELECT 
					D.STypeId,
					ATypeId,
					D.Cid,
					IniYTotal,
					IniYTotalFor,
					0 FDebit,
					0 FDebitFor,
					0 FCredit,
					0 FCreditFor,
					IniTotal,
					IniTotalFor,
					Fyear,
					Fperiod,
					CASE WHEN A.Fdc=1	THEN D.FDebit-D.FCredit+D.IniTotal
						 WHEN A.Fdc=-1 THEN D.FCredit-D.FDebit+D.IniTotal
					END Fendbalance,
					CASE WHEN A.Fdc=1	THEN D.FDebitFor-D.FCreditFor+D.IniTotalFor
						 WHEN A.Fdc=-1 THEN D.FCreditFor-D.FDebitFor+D.IniTotalFor
					END Fendbalancefor 
				FROM Ac_IniAccount_Assist_CheckItems D
				INNER JOIN Ac_Account A ON A.StypeId=D.STypeId AND A.TypeId=D.ATypeId AND D.STypeId=@STypeId AND D.FYear=@Fyear
				--返回期初数据值	
				SELECT
					STypeId,
					ATypeId,
					Cid,
					IniYTotal,
					IniYTotalFor,
					FDebit,
					FDebitFor,
					FCredit,
					FCreditFor,
					IniTotal,
					IniTotalFor,
					Fyear,
					Fperiod,
					Fendbalance,
					Fendbalancefor
				FROM @Details
				UNION ALL
				SELECT
					STypeId,
					ATypeId,
					0,
					SUM(ISNULL(IniYTotal,0)) IniYTotal,
					SUM(ISNULL(IniYTotalFor,0)) IniYTotalFor,
					SUM(ISNULL(FDebit,0)) FDebit,
					SUM(ISNULL(FDebitFor,0)) FDebitFor,
					SUM(ISNULL(FCredit,0)) FCredit,
					SUM(ISNULL(FCreditFor,0)) FCreditFor,
					SUM(ISNULL(IniTotal,0)) IniTotal,
					SUM(ISNULL(IniTotalFor,0)) IniTotalFor,
					@Fyear,
					Fperiod,
					SUM(ISNULL(Fendbalance,0)) Fendbalance,
					SUM(ISNULL(Fendbalancefor,0)) Fendbalancefor
				FROM @Details
				GROUP BY STypeId,ATypeId,Fperiod
								
			END
		ELSE
			IF EXISTS(SELECT TOP 1 1 FROM dbo.AC_BALANCE_ASSIST_CHECKITEMS_DETAIL WHERE FYear=@Fyear)
				SELECT * FROM AC_BALANCE_ASSIST_CHECKITEMS  WHERE STypeId=@STypeId AND FYear=@Fyear
			ELSE 
				SELECT STypeId,ATypeId,cid,IniYTotal,IniYTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniTotal,IniTotalFor,@Fyear,1,Fendbalance,Fendbalancefor
				FROM AC_BALANCE_ASSIST_CHECKITEMS WHERE  STypeId=@STypeId AND FYear=@Fyear-1 AND FPeriod=@PreMaxFperiod
		RETURN 
	END

CREATE TABLE #tempAcBalanceAssistTable --辅助核算零时表
(
       STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   Cid                  int                  null default -1,	   
	   IniYTotal             NUMERIC(24, 10)         null default 0,
	   IniYTotalFor          NUMERIC(24, 10)         null default 0,
	   FDebit                NUMERIC(24, 10)         null default 0,
	   FDebitFor             NUMERIC(24, 10)         null default 0,
	   FCredit               NUMERIC(24, 10)         null default 0,
	   FCreditFor            NUMERIC(24, 10)         null default 0,
	   IniTotal              NUMERIC(24, 10)         null default 0,
	   IniTotalFor           NUMERIC(24, 10)         null default 0,
	   Fyear			    INT,
	   Fperiod				INT,
	   Fendbalance           NUMERIC(24, 10) ,
	   Fendbalancefor	     NUMERIC(24, 10) ,
	   Fdc					INT
)
IF @iniFyear=@Fyear
		INSERT INTO #tempAcBalanceAssistTable
		SELECT	ac.STypeId,
				ac.ATypeId,
				ac.Cid,
			   SUM(IniYTotal),           
			   SUM(IniYTotalFor),              
			   0,              
			   0,           
			   0,             
			   0,          
			   0,            
			   0,         
			   Fyear,			   
			   Fperiod,			
			   0,         
			   0,
			   Fdc				
		FROM	Ac_IniAccount_Assist_CheckItems ac JOIN dbo.Ac_Account aa ON ac.STypeId=aa.StypeId AND ac.ATypeId=aa.TypeId 
	    GROUP BY ac.STypeId,ac.ATypeId,ac.Cid,FYear,FPeriod,Fdc
ELSE 
	INSERT INTO #tempAcBalanceAssistTable
		SELECT	ac.STypeId,
				ac.ATypeId,
				ac.Cid,
			   SUM(IniYTotal),           
			   SUM(IniYTotalFor),        
			   SUM(FDebit),              
			   SUM(FDebitFor),           
			   SUM(FCredit),             
			   SUM(FCreditFor),          
			   SUM(IniTotal),            
			   SUM(IniTotalFor),         
			   @Fyear,			   
			   1,			
			   0,         
			   0,	   
			   Fdc				
		FROM Ac_Balance_Assist_CheckItems ac JOIN dbo.Ac_Account aa ON ac.STypeId=aa.StypeId AND ac.ATypeId=aa.TypeId 
		WHERE ac.cid<>0 AND FYear=@Fyear-1 AND FPeriod=@PreMaxFperiod
	    GROUP BY ac.STypeId,ac.ATypeId,ac.Cid,FYear,FPeriod,Fdc
/********************************************获取凭证科目数据（包含过账和未过账）*************************************/
INSERT INTO	#tempAcBalanceAssistTable
SELECT A.STypeId,
	A.ATypeId,
	A.Cid,
	0 AS IniYTotal,
	0 AS IniYTotalFor,
	SUM(A.FDebitTotal) AS FDebit ,
	SUM(A.FDebitTotalFor) AS FDebitFor,
	SUM(A.FCreditTotal) AS FCredit,
	SUM(A.FCreditTotalFor) AS FCreditFor,
	0 AS IniTotal ,
	0 AS IniTotalFor,
	A.FYear,
	A.FPeriod,
	0 AS Fendbalance,
	0 AS Fendbalancefor,
	A.Fdc
FROM	Ac_Voucher_Bill A
JOIN	Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1
JOIN	Ac_Voucher_Bill_Assist_CheckItems C ON A.ID = C.vBId
WHERE	A.FYear = @Fyear AND A.STypeId=@STypeId		
GROUP BY A.FYear,A.FPeriod,A.STypeId,A.ATypeId,A.Cid,A.Fdc 

IF(@iniFyear<>@Fyear)
	BEGIN
		SELECT 
			A.ATypeId,
			A.Cid,
			SUM(A.FDebitTotal) AS FDebit ,
			SUM(A.FDebitTotalFor) AS FDebitFor,
			SUM(A.FCreditTotal) AS FCredit,
			SUM(A.FCreditTotalFor) AS FCreditFor,
			A.FAdc
		INTO #VoucherTemp
		FROM	Ac_Voucher_Bill A
		JOIN	Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1 AND B.IfCheck='f'
		JOIN	Ac_Voucher_Bill_Assist_CheckItems C ON A.ID = C.vBId
		WHERE	A.FYear < @Fyear AND A.STypeId=@STypeId		
		GROUP BY A.ATypeId,A.Cid,A.FAdc 

		INSERT INTO  #tempAcBalanceAssistTable
		SELECT 
			@STypeId STypeId,
			T.ATypeId,
			T.Cid,
			0 IniYTotal,
			0 IniYTotalFor,
			0 FDebit,
			0 FDebitFor,
			0 FCredit,
			0 FCreditFor,
			0 IniTotal,
			0 IniTotalFor,
			@Fyear Fyear,
			1 Fperiod,
			0 Fendbalance,
			0 Fendbalancefor,
			A.Fdc
		FROM #VoucherTemp T
		INNER JOIN Ac_Account A ON A.TypeId=T.ATypeId AND A.StypeId=@STypeId 
		INNER JOIN #tempAcBalanceAssistTable B ON B.ATypeId<>T.ATypeId OR B.Cid<>T.Cid
		GROUP BY T.ATypeId,T.Cid,A.Fdc
		
		---修改bug
		INSERT INTO  #tempAcBalanceAssistTable
		SELECT 
			@STypeId STypeId,
			T.ATypeId,
			T.Cid,
		    0 IniYTotal,
			0 IniYTotalFor,
			0 FDebit,
			0 FDebitFor,
			0 FCredit,
			0 FCreditFor,
			0 IniTotal,
			0 IniTotalFor,
			@Fyear Fyear,
			1 Fperiod,
			0 Fendbalance,
			0 Fendbalancefor,
			A.Fdc
		FROM #VoucherTemp T
		INNER JOIN Ac_Account A ON A.TypeId=T.ATypeId 
		LEFT JOIN #tempAcBalanceAssistTable B ON B.ATypeId=T.ATypeId AND  B.Cid=T.Cid AND B.ATypeId IS NULL
		GROUP BY T.ATypeId,T.Cid,A.Fdc
		
		UPDATE #tempAcBalanceAssistTable
		SET	IniYTotal+=CASE WHEN T.Fdc=V.FAdc AND T.Fdc=1 THEN V.FDebit ELSE -V.FCredit END,
			IniYTotalFor+=CASE WHEN T.Fdc=V.FAdc AND T.Fdc=1 THEN V.FDebitFor ELSE -V.FCreditFor END,
			Fendbalance+=CASE WHEN T.Fdc=V.FAdc AND T.Fdc=1 THEN V.FDebit ELSE -V.FCredit END,
			Fendbalancefor+=CASE WHEN T.Fdc=V.FAdc AND T.Fdc=1 THEN V.FDebitFor ELSE -V.FCreditFor END
		FROM #tempAcBalanceAssistTable T
		INNER JOIN #VoucherTemp V ON T.ATypeId=V.ATypeId AND T.Cid=V.Cid
		WHERE T.Fyear=@Fyear AND T.Fperiod=1
		DROP TABLE #VoucherTemp
	END
	
IF @iniFyear=@Fyear
	BEGIN
		/**********根据期初对年初进行赋值******/
		UPDATE  #tempAcBalanceAssistTable
		SET		
			IniYTotal=B.IniYTotal,
			IniYTotalFor = B.IniYTotalFor
		FROM	#tempAcBalanceAssistTable A
		JOIN	Ac_IniAccount_Assist_CheckItems B ON  B.FYear=@Fyear AND B.STypeId=@STypeId
		AND A.ATypeId = B.ATypeId AND	A.Cid = B.Cid 
		/**********根据期初期间 插入期初科目(交集)******/

		INSERT INTO	#tempAcBalanceAssistTable
		SELECT STypeId,
			ATypeId,
			Cid,
			IniYTotal,
			IniYTotalFor,
			0,0,0,0,
			IniTotal,
			IniTotalFor,
			FYear,
			FPeriod,
			IniTotal,
			IniTotalFor,
			B.Fdc
		FROM	Ac_IniAccount_Assist_CheckItems A
		JOIN	(SELECT TypeId,Fdc FROM Ac_Account WHERE StypeId=@STypeId ) B ON A.ATypeId=B.TypeId
		WHERE A.FYear=@Fyear AND A.STypeId=@STypeId AND NOT EXISTS(
			SELECT * FROM #tempAcBalanceAssistTable WHERE STypeId=@STypeId 
			AND FYear=@Fyear AND CONVERT(INT,FPeriod)=A.FPeriod AND  ATypeId=A.ATypeId 
			AND Cid=A.Cid
		)	
	END
ELSE 
	BEGIN
		/**********根据期初对年初进行赋值******/
		UPDATE  #tempAcBalanceAssistTable
		SET		
			IniYTotal+=B.IniYTotal,
			IniYTotalFor += B.IniYTotalFor
		FROM	#tempAcBalanceAssistTable A
		JOIN	Ac_Balance_Assist_CheckItems B ON  B.FYear=@Fyear AND B.STypeId=@STypeId
		AND A.ATypeId = B.ATypeId AND	A.Cid = B.Cid 
		/**********根据期初期间 插入期初科目(交集)******/

		INSERT INTO	#tempAcBalanceAssistTable
		SELECT STypeId,
			ATypeId,
			Cid,
			IniYTotal,
			IniYTotalFor,
			0,0,0,0,
			IniTotal,
			IniTotalFor,
			FYear,
			FPeriod,
			IniTotal,
			IniTotalFor,
			B.Fdc
		FROM	Ac_Balance_Assist_CheckItems A
		JOIN	(SELECT TypeId,Fdc FROM Ac_Account WHERE StypeId=@STypeId ) B ON A.ATypeId=B.TypeId
		WHERE A.FYear=@Fyear AND A.STypeId=@STypeId AND NOT EXISTS(
			SELECT * FROM #tempAcBalanceAssistTable WHERE STypeId=@STypeId 
			AND FYear=@Fyear AND CONVERT(INT,FPeriod)=A.FPeriod AND  ATypeId=A.ATypeId 
			AND Cid=A.Cid
		)	
	END
/*****************计算第一期期末***************/
UPDATE	#tempAcBalanceAssistTable
SET		FEndBalance = 
		(CASE	WHEN Fdc=1	THEN FDebit-FCredit+IniTotal
				WHEN Fdc=-1	THEN FCredit-FDebit+IniTotal
		END),
		FEndBalanceFor = 
		(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+IniTotalFor
				WHEN Fdc=-1	THEN FCreditFor-FDebitFor+IniTotalFor
		END)
FROM	#tempAcBalanceAssistTable
WHERE	Fperiod=(SELECT MIN(CONVERT(int,FPeriod)) FROM #tempAcBalanceAssistTable)				

			 
/*********************************************************************************************************************/	
/*													按期间循环计算													 */
/* 参数	@MaxFPeriod：最大期间  	@MinFPeriod：初始期间		@FPeriodNum：期间循环参数，初始=@MinFPeriod																										 */
/*********************************************************************************************************************/		 
	DECLARE @MaxFPeriod INT  
	DECLARE @MinFPeriod INT
	DECLARE @MaxFPeriodVocher INT  
	--SELECT @MaxFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='FPeriod'
	--SELECT @MinFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='fmonth'
	IF @iniFyear=@Fyear
			BEGIN
				SELECT @MaxFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='FPeriod'
				SELECT @MinFPeriod=ISNULL(MIN(CONVERT(INT,FPeriod)),@MaxFPeriod)  FROM Ac_Balance WHERE STypeId=@STypeId AND FYear=@Fyear
			END
		ELSE 
			BEGIN
				SELECT @MinFPeriod=MIN(FPeriod) FROM #tempAcBalanceAssistTable
				SELECT @MaxFPeriod=MAX(FPeriod) FROM dbo.Ac_Period
			END
	
	SELECT  @MaxFPeriodVocher=IsNULL(MAX(CONVERT(INT,FPeriod)),0) FROM #tempAcBalanceAssistTable  
	IF @MaxFPeriodVocher>@MaxFPeriod SET @MaxFPeriod=@MaxFPeriodVocher
	DECLARE @FPeriodNum INT SET  @FPeriodNum=@MinFPeriod+1
	WHILE @FPeriodNum<=@MaxFPeriod
	BEGIN
		
	/***********************************根据上一期进行本期计算*********************************
	** 期初=上期期末		期末=期初+本期发生	
	** 本期科目=上一期科目+本期发生科目	
	** 本期有的科目而上期没有的科目	期初默认0 所有只计算期末									
	*******************************************************************************************/

		 /*上期临时表*/
		 SELECT *  INTO #PreAcBalanceTempTable 
		 FROM #tempAcBalanceAssistTable 
		 WHERE FPeriod=@FPeriodNum-1
		 
		/******************计算期初********************/
		UPDATE	#tempAcBalanceAssistTable
		SET		IniTotal=B.Fendbalance,
				IniTotalFor=B.FendbalanceFor
		FROM	#tempAcBalanceAssistTable A
		JOIN	#PreAcBalanceTempTable B 
		ON		A.ATypeId = B.ATypeId AND A.Cid=B.Cid
		WHERE	A.FPeriod = @FPeriodNum

		/******************计算期末********************/
		UPDATE	#tempAcBalanceAssistTable
		SET		FEndBalance = 
				(CASE	WHEN Fdc=1	THEN FDebit-FCredit+IniTotal
						WHEN Fdc=-1	THEN FCredit-FDebit+IniTotal
				END),
				FEndBalanceFor = 
				(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+IniTotalFor
						WHEN Fdc=-1	THEN FCreditFor-FDebitFor+IniTotalFor
				END)
	/***********************合并上期科目**********************************************/
	/* 上期科目本期没有发生额，直接复制到本期--本期期初=上期期末=本期期末 本期发生=0 */
	/*********************************************************************************/
		
		 /*本期临时表*/
		SELECT * INTO #CurAcBalanceTempTable 
				FROM  #tempAcBalanceAssistTable 
				WHERE FPeriod = @FPeriodNum
		
		INSERT INTO	#tempAcBalanceAssistTable 
			 SELECT	A.STypeId,
					A.ATypeId,
					A.Cid,
					A.IniYTotal,
					A.IniYTotalFor,
					0,0,0,0,
					A.Fendbalance,
					A.FendbalanceFor,
					A.FYear,
					@FPeriodNum,
					A.Fendbalance,
					A.FendbalanceFor,
					A.Fdc
			   FROM #PreAcBalanceTempTable A
			  WHERE NOT EXISTS(SELECT * FROM #CurAcBalanceTempTable WHERE ATypeId=A.ATypeId AND Cid=A.Cid)
			  		 	
		DROP TABLE #PreAcBalanceTempTable,#CurAcBalanceTempTable
	--	/*循环下一期间*/
		SET @FPeriodNum=@FPeriodNum+1
	END /*循环结束*/
	
	
	ALTER TABLE #tempAcBalanceAssistTable DROP COLUMN Fdc    /*Fdc不是AC_Balance默认字段 此处作为临时使用，故删除*/
	
/************************************************************************************************/
/*										计算综合本位币											*/
/************************************************************************************************/		
	INSERT INTO #tempAcBalanceAssistTable
		SELECT	STypeId,
				ATypeId,
				0,
				SUM(IniYTotal),
				SUM(IniYTotal),
				SUM(FDebit),
				SUM(FDebit),
				SUM(FCredit),
				SUM(FCredit),
				SUM(IniTotal),
				SUM(IniTotal),
				@Fyear,
				FPeriod,
				SUM(Fendbalance),
				SUM(Fendbalance)
		  FROM	#tempAcBalanceAssistTable
		  GROUP BY STypeId,FPeriod,ATypeId
		  
 SELECT  * FROM #tempAcBalanceAssistTable ORDER BY AtypeId
 DROP TABLE #tempAcBalanceAssistTable


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_AcAssistBalanceQuery]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[WEB_AcAssistBalanceQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--=============================
--by:glj
--date:2016-04-07
--function:重写辅助核算余额表
--==============================
CREATE PROCEDURE WEB_AcAssistBalanceQuery 
(
	@STypeId 		VARCHAR(50),	--分支机构ID
	@Ascids 		INT,			--辅助核算类型
	@AscidsTypeID 	VARCHAR(MAX),	--辅助核算明细ID
	@ATypeId		VARCHAR(MAX),	--会计科目ID(可以多值，以,为分隔符 例：xxx,xxx,xx)        
	@Cid			INT,			--币别ID(-1:所有币别）
	@Leveal		    INT,			--科目级别(1-10) -1:所有级别     
	@FYear		    INT,			--会计年度       
	@FPeriodStart   INT,			--起始期间
	@FPeriodEnd     INT,			--结束期间
	@IsShowNoAccount BIT,			--是否显示未过账
	@IsShowFNull    BIT,			--不显示发生额为空的科目 1：是 0：否
	@IsBalanceNull  BIT,			--不显示期末余额为空的科目 1：是 0：否
	@IsShowFYNull   BIT,			--不显示本年没有发生额的科目 1：是 0：否
	@IsShowSubTotal BIT,			--是否显示小计
	@chvOperatorID	VARCHAR(50)		--操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON
--=============================================临时表定义及赋值【BEGIN】================================			
---分支机构权限判断
IF NOT EXISTS(SELECT * from dbo.F_GetManDetailAllSType(@chvOperatorID) WHERE TypeId=@STypeId)
	SET @STypeId=''

 --创建币种临时表
CREATE TABLE #Ac_Currency(Nid INT IDENTITY(1,1),CId INT,FullName VARCHAR(200))
IF(@Cid=-1)--所有币种
	BEGIN
		INSERT INTO #Ac_Currency(CId,FullName)
		SELECT CId,FullName FROM Ac_Currency
	END
IF(@Cid IN(0,-1))--综合币种、所有币种
	BEGIN
		INSERT INTO #Ac_Currency(CId,FullName)
		SELECT 0 CId,'综合本位币' FullName
	END
IF(@Cid NOT IN(0,-1))--具体币种
	BEGIN
		INSERT INTO #Ac_Currency(CId,FullName)
		SELECT CId,FullName FROM Ac_Currency WHERE CId=@Cid
	END
	
DECLARE @SQL VARCHAR(MAX)
--满足查询条件的科目
CREATE TABLE #TSonAtype(StypeId VARCHAR(50),ATypeId VARCHAR(50),Fdc INT,cid INT)
SET @SQL='
INSERT INTO #TSonAtype(StypeId,ATypeId,Fdc,cid)
SELECT 
	A.StypeId,
	A.TypeId ATypeId,
	A.Fdc,
	C.cid
FROM Ac_Account A
INNER JOIN  Ac_Account_Assist_CheckItems C ON C.STypeId=A.StypeId AND C.ATypeId=A.TypeId AND C.Ascids='+CAST(@Ascids AS VARCHAR)+'
INNER JOIN F_LineAccount('''+@chvOperatorID+''','''+@STypeId+''') F ON F.Stypeid=A.StypeId AND F.Typeid=A.TypeId AND A.SonNum=0'
IF(ISNULL(@Atypeid,'')<>'')
	SET @SQL+='INNER JOIN f_split('''+@ATypeId+''','','') F1 ON F1.a=A.TypeId'+CHAR(13)
IF(@Cid NOT IN(0,-1))
	SET @SQL+=' WHERE C.Cid='+CAST(@Cid AS VARCHAR(2))
EXEC(@SQL)

CREATE TABLE #TempResult
(
	FieldValue		VARCHAR(50)
)

INSERT INTO #TempResult(FieldValue)
SELECT FieldValue 
FROM Ac_IniAccount_Assist_CheckItems_Detail  D 
INNER JOIN #TSonAtype A ON A.StypeId=D.STypeId AND A.ATypeId=D.ATypeId AND D.Ascids=@Ascids

INSERT INTO #TempResult(FieldValue)
SELECT FieldValue FROM Ac_Balance_Assist_CheckItems_Detail D
INNER JOIN #TSonAtype A ON A.StypeId=D.STypeId AND A.ATypeId=D.ATypeId AND D.Ascids=@Ascids

INSERT INTO #TempResult(FieldValue)
SELECT	DISTINCT C.TypeId FieldValue
FROM	 Ac_Voucher_Bill D 
INNER JOIN #TSonAtype A ON A.StypeId=D.STypeId AND A.ATypeId=D.ATypeId
INNER JOIN Ac_Voucher_Bill_Assist_CheckItems C ON C.BillNumberId=D.BillNumberId
INNER JOIN Ac_Assist_CheckItems CI ON CI.UserCode=C.typeName AND CI.AscIds=@Ascids
	
--满足查询条件科目-辅助核算项目
CREATE TABLE #AssistDetailsTemp(AssistUserCode VARCHAR(200),AssistFullName VARCHAR(200),TypeId VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
CREATE CLUSTERED INDEX AssistDetailsTemp_IX ON #AssistDetailsTemp(TypeId)

INSERT INTO #AssistDetailsTemp(AssistUserCode,AssistFullName,TypeId,UserCode,FullName)
SELECT	F.AssistUserCode,
		F.AssistFullName,
		F.FieldValue TypeId,
		F.Usercode,
		F.FullName 
FROM F_GetAssisitItem(@Ascids,@AscidsTypeID,@chvOperatorID) F
INNER JOIN #TempResult T ON  T.FieldValue=F.FieldValue

CREATE TABLE #AssistDetails(AssistUserCode VARCHAR(200),AssistFullName VARCHAR(200),TypeId VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
CREATE CLUSTERED INDEX AssistDetails_IX ON #AssistDetails(TypeId)

INSERT INTO #AssistDetails(AssistUserCode,AssistFullName,TypeId,UserCode,FullName)
SELECT	DISTINCT
		F.AssistUserCode,
		F.AssistFullName,
		F.TypeId,
		F.Usercode,
		F.FullName 
FROM #AssistDetailsTemp F
--=============================================临时表定义及赋值【END】================================

--======================================业务逻辑处理【BEGIN】================================
--临时子级科目表数据 FOR原币,只算本位币
CREATE TABLE #TempData
(
	STypeId					VARCHAR(50),
	ATypeId					VARCHAR(50),
	Fdc						INT,
	Cid						INT,
	CName					VARCHAR(200),
	Ascids					INT,
	FieldTypeID				VARCHAR(50),
	FieldUserCode			VARCHAR(200),
	FieldFullName			VARCHAR(200),
	FBeginBalanceDebit		NUMERIC(22,10),
	FBeginBalanceDebitFor	NUMERIC(22,10),
	FBeginBalanceCredit		NUMERIC(22,10),
	FBeginBalanceCreditFor	NUMERIC(22,10),
	FDebit					NUMERIC(22,10),
	FDebitFor				NUMERIC(22,10),
	FCredit					NUMERIC(22,10),
	FCreditFor				NUMERIC(22,10),
	FYtdDebit				NUMERIC(22,10),
	FYtdDebitFor			NUMERIC(22,10),
	FYtdCredit				NUMERIC(22,10),
	FYtdCreditFor			NUMERIC(22,10),
	FEndBalanceDebit		NUMERIC(22,10),
	FEndBalanceDebitFor		NUMERIC(22,10),
	FEndBalanceCredit		NUMERIC(22,10),
	FEndBalanceCreditFor	NUMERIC(22,10)
)
INSERT INTO #TempData(STypeId,ATypeId,Fdc,Cid,CName,Ascids,FieldTypeID,FieldUserCode,FieldFullName,FBeginBalanceDebit,FBeginBalanceDebitFor,FBeginBalanceCredit,FBeginBalanceCreditFor,FDebit,FDebitFor,FCredit,FCreditFor,FYtdDebit,FYtdDebitFor,FYtdCredit,FYtdCreditFor,FEndBalanceDebit,FEndBalanceDebitFor,FEndBalanceCredit,FEndBalanceCreditFor)
SELECT
	A.StypeId,
	A.ATypeId,
	A.Fdc,
	C.CId,
	C.FullName CName,
	@Ascids Ascids,
	D.TypeId FieldTypeID,
	D.UserCode FieldUserCode,
	D.FullName FieldFullName,
	0 FBeginBalanceDebit,
	0 FBeginBalanceDebitFor,
	0 FBeginBalanceCredit,
	0 FBeginBalanceCreditFor,
	0 FDebit,
	0 FDebitFor,
	0 FCredit,
	0 FCreditFor,
	0 FYtdDebit,
	0 FYtdDebitFor,
	0 FYtdCredit,
	0 FYtdCreditFor,
	0 FEndBalanceDebit,
	0 FEndBalanceDebitFor,
	0 FEndBalanceCredit,
	0 FEndBalanceCreditFor
FROM #TSonAtype A,#AssistDetails D,#Ac_Currency C
GROUP BY
	A.StypeId,
	A.ATypeId,
	A.Fdc,
	D.TypeId,
	D.UserCode,
	D.FullName,
	C.CId,
	C.FullName

--分支机构是否开账 
IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=0)--账务期初
	BEGIN
		IF(@Cid<>0)
			BEGIN
				UPDATE #TempData
				SET 
					FBeginBalanceDebit+=CASE WHEN T.Fdc=1 THEN D.IniTotal ELSE 0 END,
					FBeginBalanceDebitFor+=CASE WHEN T.Fdc=1 THEN D.IniTotalFor ELSE 0 END,
					FBeginBalanceCredit+=CASE WHEN T.Fdc=-1 THEN D.IniTotal ELSE 0 END,
					FBeginBalanceCreditFor+=CASE WHEN T.Fdc=-1 THEN D.IniTotalFor ELSE 0 END,
					FYtdDebit+=D.FDebit,
					FYtdDebitFor+=D.FDebitFor,
					FYtdCredit+=D.FCredit,
					FYtdCreditFor+=D.FCreditFor,
					FEndBalanceDebit+=CASE WHEN T.Fdc=1 THEN D.IniTotal ELSE 0 END,
					FEndBalanceDebitFor+=CASE WHEN T.Fdc=1 THEN D.IniTotalFor ELSE 0 END,
					FEndBalanceCredit+=CASE WHEN T.Fdc=-1 THEN D.IniTotal ELSE 0 END,
					FEndBalanceCreditFor+=CASE WHEN T.Fdc=-1 THEN D.IniTotalFor ELSE 0 END
				FROM #TempData T
				INNER JOIN(
					SELECT
						D.STypeId,
						D.ATypeId,
						D.Cid,
						D.Ascids,
						D.FieldValue,
						SUM(D.IniTotal) IniTotal,
						SUM(D.IniTotalFor) IniTotalFor,
						SUM(D.FDebit) FDebit,
						SUM(D.FDebitFor) FDebitFor,
						SUM(D.FCredit) FCredit,
						SUM(D.FCreditFor) FCreditFor
					FROM Ac_IniAccount_Assist_CheckItems_Detail D
					INNER JOIN #TempData T ON T.STypeId=D.STypeId AND T.ATypeId=D.ATypeId AND T.Cid=D.Cid AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID
					GROUP BY D.STypeId,D.ATypeId,D.Ascids,D.FieldValue,D.Cid
				) D ON D.STypeId=T.STypeId AND T.ATypeId=D.ATypeId AND D.Cid=T.Cid AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID
			END
		--综合本位币
		IF(@CID IN(0,-1))
			BEGIN
				UPDATE #TempData
				SET 
					FBeginBalanceDebit+=CASE WHEN T.Fdc=1 THEN D.IniTotal ELSE 0 END,
					FBeginBalanceDebitFor+=CASE WHEN T.Fdc=1 THEN D.IniTotal ELSE 0 END,
					FBeginBalanceCredit+=CASE WHEN T.Fdc=-1 THEN D.IniTotal ELSE 0 END,
					FBeginBalanceCreditFor+=CASE WHEN T.Fdc=-1 THEN D.IniTotal ELSE 0 END,
					FYtdDebit+=D.FDebit,
					FYtdDebitFor+=D.FDebitFor,
					FYtdCredit+=D.FCredit,
					FYtdCreditFor+=D.FCreditFor,
					FEndBalanceDebit+=CASE WHEN T.Fdc=1 THEN D.IniTotal ELSE 0 END,
					FEndBalanceDebitFor+=CASE WHEN T.Fdc=1 THEN D.IniTotal ELSE 0 END,
					FEndBalanceCredit+=CASE WHEN T.Fdc=-1 THEN D.IniTotal ELSE 0 END,
					FEndBalanceCreditFor+=CASE WHEN T.Fdc=-1 THEN D.IniTotal ELSE 0 END
				FROM #TempData T
				INNER JOIN 
				(
					SELECT
						D.STypeId,
						D.ATypeId,
						0 Cid,
						D.Ascids,
						D.FieldValue,
						SUM(D.IniTotal) IniTotal,
						SUM(D.IniTotal) IniTotalFor,
						SUM(D.FDebit) FDebit,
						SUM(D.FDebit) FDebitFor,
						SUM(D.FCredit) FCredit,
						SUM(D.FCredit) FCreditFor
					FROM Ac_IniAccount_Assist_CheckItems_Detail D
					INNER JOIN #TempData T ON T.STypeId=D.STypeId AND T.ATypeId=D.ATypeId AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID AND T.Cid=0
					GROUP BY D.STypeId,D.ATypeId,D.Ascids,D.FieldValue
				) D ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Cid=T.Cid AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID
			END
	END
ELSE 
	BEGIN
		DECLARE 
			@MaxFyear		INT=@FYear,
			@MaxSFPeriod	INT=@FPeriodStart,
			@MaxEFPeriod	INT=@FPeriodEnd
			
		--判断准确年度 起止期间
		IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE STypeId=@STypeId AND FYear>=@FYear)		
			SELECT @MaxFyear=MAX(CAST(FYear AS INT)),@MaxSFPeriod=MAX(CAST(FPeriod AS INT)),@MaxEFPeriod=MAX(CAST(FPeriod AS INT)) FROM Ac_Balance_Assist_CheckItems_Detail WHERE STypeId=@STypeId
		ELSE 
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE STypeId=@STypeId AND FYear=@FYear AND FPeriod>=@FPeriodStart)		
					SELECT @MaxSFPeriod=MAX(CAST(FPeriod AS INT)),@MaxEFPeriod=MAX(CAST(FPeriod AS INT)) FROM Ac_Balance_Assist_CheckItems_Detail WHERE STypeId=@STypeId AND FYear=@FYear
					
				IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Balance_Assist_CheckItems_Detail WHERE STypeId=@STypeId AND FYear=@FYear AND FPeriod>=@MaxEFPeriod)
					SELECT @MaxEFPeriod=MAX(FPeriod) FROM Ac_Balance_Assist_CheckItems_Detail WHERE STypeId=@STypeId AND FYear=@FYear		
			END
			
		--期初
		UPDATE #TempData
		SET
			FBeginBalanceDebit+=CASE WHEN T.Fdc=1 THEN CASE WHEN @MaxFyear=@FYear AND @MaxSFPeriod=@FPeriodStart THEN D.IniTotal ELSE D.FEndBalance END ELSE 0 END,
			FBeginBalanceDebitFor+=CASE WHEN T.Fdc=1 THEN CASE WHEN @MaxFyear=@FYear AND @MaxSFPeriod=@FPeriodStart THEN D.IniTotalFor ELSE D.FEndBalanceFor END ELSE 0 END,
			FBeginBalanceCredit =CASE WHEN T.Fdc=-1 THEN CASE WHEN @MaxFyear=@FYear AND @MaxSFPeriod=@FPeriodStart THEN D.IniTotal ELSE D.FEndBalance END ELSE 0 END,
			FBeginBalanceCreditFor+=CASE WHEN T.Fdc=-1 THEN CASE WHEN @MaxFyear=@FYear AND @MaxSFPeriod=@FPeriodStart THEN D.IniTotalFor ELSE D.FEndBalanceFor END ELSE 0 END
		FROM #TempData T
		INNER JOIN Ac_Balance_Assist_CheckItems_Detail D  ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID AND D.Cid=T.Cid AND D.FYear=@MaxFyear AND D.FPeriod=@MaxSFPeriod
		
		--本期
		UPDATE #TempData
		SET
			FDebit+=CASE WHEN @FYear=@MaxFyear AND @MaxEFPeriod>=@FPeriodStart THEN D.FDebit ELSE 0 END,
			FDebitFor+=CASE WHEN @FYear=@MaxFyear AND @MaxEFPeriod>=@FPeriodStart THEN D.FDebitFor ELSE 0 END,
			FCredit+=CASE WHEN @FYear=@MaxFyear AND @MaxEFPeriod>=@FPeriodStart THEN D.FCredit ELSE 0 END,
			FCreditFor+=CASE WHEN @FYear=@MaxFyear AND @MaxEFPeriod>=@FPeriodStart THEN D.FCreditFor ELSE 0 END
		FROM #TempData T
		INNER JOIN
		(	
			SELECT
				D.STypeId,
				D.ATypeId,
				D.Ascids,
				D.FieldValue,
				D.Cid, 
				SUM(D.FDebit) FDebit,
				SUM(D.FDebitFor) FDebitFor,
				SUM(D.FCredit) FCredit,
				SUM(D.FCreditFor) FCreditFor
			FROM Ac_Balance_Assist_CheckItems_Detail D
			INNER JOIN #TempData T ON T.STypeId=D.STypeId AND T.ATypeId=D.ATypeId AND T.Cid=D.Cid AND T.Ascids=D.Ascids AND T.FieldTypeID=D.FieldValue AND D.FYear=@MaxFyear AND D.FPeriod BETWEEN @MaxSFPeriod AND @MaxEFPeriod
			GROUP BY D.STypeId,D.ATypeId,D.Ascids,D.FieldValue,D.Cid 
		)D ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Cid=T.Cid AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID
		
		--本年数据
		SELECT
			D.STypeId,
			D.ATypeId,
			D.Ascids,
			D.FieldValue,
			D.Cid, 
			SUM(D.FDebit) FDebit,
			SUM(D.FDebitFor) FDebitFor,
			SUM(D.FCredit) FCredit,
			SUM(D.FCreditFor) FCreditFor
		INTO #CurrentYearData
		FROM Ac_Balance_Assist_CheckItems_Detail D
		INNER JOIN #TempData T ON T.STypeId=D.STypeId AND T.ATypeId=D.ATypeId AND T.Cid=D.Cid AND T.Ascids=D.Ascids AND T.FieldTypeID=D.FieldValue AND D.FYear=@FYear AND D.FPeriod<=@FPeriodEnd
		GROUP BY D.STypeId,D.ATypeId,D.Ascids,D.FieldValue,D.Cid 
		
		--账务期初
		IF(@Cid<>0)
			BEGIN
				INSERT INTO #CurrentYearData(STypeId,ATypeId,Ascids,FieldValue,Cid,FDebit,FDebitFor,FCredit,FCreditFor)
				SELECT
					D.STypeId,
					D.ATypeId,
					D.Ascids,
					D.FieldValue,
					D.Cid,
					SUM(D.FDebit) FDebit,
					SUM(D.FDebitFor) FDebitFor,
					SUM(D.FCredit) FCredit,
					SUM(D.FCreditFor) FCreditFor
				FROM Ac_IniAccount_Assist_CheckItems_Detail D
				INNER JOIN #TempData T ON T.STypeId=D.STypeId AND T.ATypeId=D.ATypeId AND T.Cid=D.Cid AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID AND D.FYear=@FYear
				GROUP BY D.STypeId,D.ATypeId,D.Ascids,D.FieldValue,D.Cid
			END
		--综合本位币
		IF(@CID IN(0,-1))
			BEGIN
				INSERT INTO #CurrentYearData(STypeId,ATypeId,Ascids,FieldValue,Cid,FDebit,FDebitFor,FCredit,FCreditFor)
				SELECT
					D.STypeId,
					D.ATypeId,
					D.Ascids,
					D.FieldValue,
					0 Cid,
					SUM(D.FDebit) FDebit,
					SUM(D.FDebit) FDebitFor,
					SUM(D.FCredit) FCredit,
					SUM(D.FCredit) FCreditFor
				FROM Ac_IniAccount_Assist_CheckItems_Detail D
				INNER JOIN #TempData T ON T.STypeId=D.STypeId AND T.ATypeId=D.ATypeId AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID AND T.Cid=0 AND D.FYear=@FYear
				GROUP BY D.STypeId,D.ATypeId,D.Ascids,D.FieldValue
			END
		--本年
		UPDATE #TempData
		SET
			FYtdDebit+=ISNULL(D.FDebit,0),
			FYtdDebitFor+=ISNULL(D.FDebitFor,0),
			FYtdCredit+=ISNULL(D.FCredit,0),
			FYtdCreditFor+=ISNULL(D.FCreditFor,0)
		FROM #TempData T
		INNER JOIN
		(	
			SELECT
				STypeId,
				ATypeId,
				Ascids,
				FieldValue,
				Cid, 
				SUM(FDebit) FDebit,
				SUM(FDebitFor) FDebitFor,
				SUM(FCredit) FCredit,
				SUM(FCreditFor) FCreditFor
			FROM #CurrentYearData
			GROUP BY STypeId,ATypeId,Ascids,FieldValue,Cid 
		)D ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Cid=T.Cid AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID
			
		DROP TABLE #CurrentYearData	
		--期末	
		UPDATE #TempData
		SET
			FEndBalanceDebit+=CASE WHEN T.Fdc=1 THEN D.FEndBalance ELSE 0 END,
			FEndBalanceDebitFor+=CASE WHEN T.Fdc=1 THEN D.FEndBalanceFor ELSE 0 END,
			FEndBalanceCredit+=CASE WHEN T.Fdc=-1 THEN D.FEndBalance ELSE 0 END,
			FEndBalanceCreditFor+=CASE WHEN T.Fdc=-1 THEN D.FEndBalanceFor ELSE 0 END
		FROM #TempData T
		INNER JOIN Ac_Balance_Assist_CheckItems_Detail D  ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Ascids=T.Ascids AND D.FieldValue=T.FieldTypeID AND D.Cid=T.Cid AND D.FYear=@MaxFyear AND D.FPeriod=@MaxEFPeriod

		--显示未记账
		IF(@IsShowNoAccount=1)
			BEGIN
				CREATE TABLE #Voucher
				(
					STypeId			VARCHAR(50),
					ATypeId			VARCHAR(50),
					FieldValue		VARCHAR(50),
					Cid				INT,
					FYear			INT,
					FPeriod			INT,
					FDebitTotal		NUMERIC(22,10),
					FDebitTotalFor	NUMERIC(22,10),
					FCreditTotal	NUMERIC(22,10),
					FCreditTotalFor NUMERIC(22,10),
					Total			NUMERIC(22,10),
					TotalFor		NUMERIC(22,10)
				)
				IF(@Cid<>0)
					BEGIN
						INSERT INTO #Voucher(STypeId,ATypeId,FieldValue,Cid,FYear,FPeriod,FDebitTotal,FDebitTotalFor,FCreditTotal,FCreditTotalFor,Total,TotalFor)
						SELECT
							B.STypeId,
							B.ATypeId,
							AD.TypeId FieldValue,
							B.Cid,
							B.FYear,
							B.FPeriod,
							SUM(B.FDebitTotal) FDebitTotal,
							SUM(B.FDebitTotalFor) FDebitTotalFor,
							SUM(B.FCreditTotal) FCreditTotal,
							SUM(B.FCreditTotalFor) FCreditTotalFor,
							SUM(CASE WHEN S.Fdc=1 THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END) Total,
							SUM(CASE WHEN S.Fdc=1 THEN B.FDebitTotalFor-B.FCreditTotalFor ELSE B.FCreditTotalFor-B.FDebitTotalFor END) TotalFor
						FROM Ac_Voucher A
						INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=A.BillNumberId
						INNER JOIN #TSonAtype S ON S.StypeId=B.STypeId AND S.ATypeId=B.ATypeId AND (CAST(B.FYear AS INT)<@FYear OR (CAST(B.FYear AS INT)=@FYear AND B.FPeriod<=@FPeriodEnd)) AND A.IfCheck='F' AND FChecked<>-1 AND ((@Cid=-1 AND B.Cid = S.cid) OR (@Cid<>-1 AND B.Cid=@Cid))
						INNER JOIN Ac_Voucher_Bill_Assist_CheckItems C ON C.BillNumberId=B.BillNumberId AND C.vBId=B.ID
						INNER JOIN #AssistDetails AD ON AD.AssistUserCode=C.typeName AND AD.TypeId=C.TypeId
						GROUP BY B.STypeId,B.ATypeId,AD.TypeId,B.Cid,B.FYear,B.FPeriod
					END
					
				IF(@Cid=0)
					BEGIN
						INSERT INTO #Voucher(STypeId,ATypeId,FieldValue,Cid,FYear,FPeriod,FDebitTotal,FDebitTotalFor,FCreditTotal,FCreditTotalFor,Total,TotalFor)
						SELECT
							B.STypeId,
							B.ATypeId,
							AD.TypeId FieldValue,
							0 Cid,
							B.FYear,
							B.FPeriod,
							SUM(B.FDebitTotal) FDebitTotal,
							SUM(B.FDebitTotal) FDebitTotalFor,
							SUM(B.FCreditTotal) FCreditTotal,
							SUM(B.FCreditTotal) FCreditTotalFor,
							SUM(CASE WHEN S.Fdc=1 THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END) Total,
							SUM(CASE WHEN S.Fdc=1 THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END) TotalFor
						FROM Ac_Voucher A
						INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=A.BillNumberId
						INNER JOIN #TSonAtype S ON S.StypeId=B.STypeId AND S.ATypeId=B.ATypeId AND (CAST(B.FYear AS INT)<@FYear OR (CAST(B.FYear AS INT)=@FYear AND B.FPeriod<=@FPeriodEnd)) AND A.IfCheck='F' AND FChecked<>-1 AND  B.Cid = S.cid
						INNER JOIN Ac_Voucher_Bill_Assist_CheckItems C ON C.BillNumberId=B.BillNumberId AND C.vBId=B.ID
						INNER JOIN #AssistDetails AD ON AD.AssistUserCode=C.typeName AND AD.TypeId=C.TypeId
						GROUP BY B.STypeId,B.ATypeId,AD.TypeId,B.FYear,B.FPeriod	
					END
					
				--期初
				UPDATE #TempData
				SET
					FBeginBalanceDebit+=CASE WHEN T.Fdc=1 THEN Total ELSE 0 END,
					FBeginBalanceDebitFor+=CASE WHEN T.Fdc=1 THEN TotalFor ELSE 0 END,
					FBeginBalanceCredit+=CASE WHEN T.Fdc=-1 THEN Total ELSE 0 END,
					FBeginBalanceCreditFor+=CASE WHEN T.Fdc=-1 THEN TotalFor ELSE 0 END
				FROM #TempData T
				INNER JOIN 
				(
					SELECT
						STypeId,
						ATypeId,
						FieldValue,
						Cid,
						SUM(Total) Total,
						SUM(TotalFor) TotalFor
					FROM #Voucher A
					WHERE (FYear<@FYear OR (FYear=@FYear AND FPeriod<@FPeriodStart)) 
					GROUP BY STypeId,ATypeId,FieldValue,Cid	
				) D ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Cid=T.Cid AND D.FieldValue=T.FieldTypeID

				--本期
				UPDATE #TempData
				SET
					FDebit+=D.FDebitTotal,
					FDebitFor+=D.FDebitTotalFor,
					FCredit+=D.FCreditTotal,
					FCreditFor+=D.FCreditTotalFor
				FROM #TempData T
				INNER JOIN 
				(
					SELECT
						STypeId,
						ATypeId,
						FieldValue,
						Cid,
						SUM(FDebitTotal) FDebitTotal,
						SUM(FDebitTotalFor) FDebitTotalFor,
						SUM(FCreditTotal) FCreditTotal,
						SUM(FCreditTotalFor) FCreditTotalFor
					FROM #Voucher A
					WHERE FYear=@FYear AND FPeriod BETWEEN @FPeriodStart AND @FPeriodEnd
					GROUP BY STypeId,ATypeId,FieldValue,Cid	
				) D ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Cid=T.Cid AND D.FieldValue=T.FieldTypeID
				
				--本年
				UPDATE #TempData
				SET
					FYtdDebit+=D.FDebitTotal,
					FYtdDebitFor+=D.FDebitTotalFor,
					FYtdCredit+=D.FCreditTotal,
					FYtdCreditFor+=D.FCreditTotalFor
				FROM #TempData T
				INNER JOIN 
				(
					SELECT
						STypeId,
						ATypeId,
						FieldValue,
						Cid,
						SUM(FDebitTotal) FDebitTotal,
						SUM(FDebitTotalFor) FDebitTotalFor,
						SUM(FCreditTotal) FCreditTotal,
						SUM(FCreditTotalFor) FCreditTotalFor
					FROM #Voucher A
					WHERE  
						FYear=@FYear 
						AND FPeriod<=@FPeriodEnd 
					GROUP BY STypeId,ATypeId,FieldValue,Cid
				) D ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Cid=T.Cid AND D.FieldValue=T.FieldTypeID
				--期末
				UPDATE #TempData
				SET
					FEndBalanceDebit+=CASE WHEN T.Fdc=1 THEN Total ELSE 0 END,
					FEndBalanceDebitFor+=CASE WHEN T.Fdc=1 THEN TotalFor ELSE 0 END,
					FEndBalanceCredit+=CASE WHEN T.Fdc=-1 THEN Total ELSE 0 END,
					FEndBalanceCreditFor+=CASE WHEN T.Fdc=-1 THEN TotalFor ELSE 0 END
				FROM #TempData T
				INNER JOIN 
				(
					SELECT
						STypeId,
						ATypeId,
						FieldValue,
						Cid,
						SUM(Total) Total,
						SUM(TotalFor) TotalFor
					FROM #Voucher A
					GROUP BY STypeId,ATypeId,FieldValue,Cid
				) D ON D.STypeId=T.STypeId AND D.ATypeId=T.ATypeId AND D.Cid=T.Cid AND D.FieldValue=T.FieldTypeID
				--删除凭证临时表数据
				DROP TABLE #Voucher
		END
	END	
--整合数据	
----删除所有数据为空的数据
DELETE FROM #TempData WHERE FBeginBalanceDebit=0 AND FBeginBalanceDebitFor=0 AND FBeginBalanceCredit=0 AND FBeginBalanceCreditFor=0 AND FDebit=0 AND FDebitFor=0 AND FCredit=0 AND FCreditFor=0 AND FYtdDebit=0 AND FYtdDebitFor=0 AND FYtdCredit=0 AND FYtdCreditFor=0 AND FEndBalanceDebit=0 AND FEndBalanceDebitFor=0 AND FEndBalanceCredit=0 AND FEndBalanceCreditFor=0
	
--不显示发生额为空的科目 1：是 0：否
IF(@IsShowFNull=1)
	BEGIN	
		DELETE FROM #TempData WHERE (FDebit=0 AND FDebitFor=0 AND FCredit=0 AND FCreditFor=0)
	END	
--不显示期末余额为空的科目 1：是 0：否
IF(@IsBalanceNull=1)
	BEGIN	
		DELETE FROM #TempData WHERE (FEndBalanceDebit=0 AND FEndBalanceDebitFor=0 AND FEndBalanceCredit=0 AND FEndBalanceCreditFor=0)
	END	
--不显示本年没有发生额的科目 1：是 0：否	
IF(@IsShowFYNull=1)
	BEGIN	
		DELETE FROM #TempData WHERE (FYtdDebit=0 AND FYtdDebitFor=0 AND FYtdCredit=0 AND FYtdCreditFor=0)
	END
BEGIN--父节点数据合计	
SELECT
	0 SubID,
	F.FullName Class,
	T.STypeId,
	A.TypeId ATypeId,
	A.FLeveal,
	A.Fdc,
	T.Ascids,
	T.FieldTypeID,
	T.FieldUserCode,
	T.FieldFullName,
	A.UserCode OrderUserCode,
	REPLICATE('    ',A.FLeveal)+A.UserCode UserCode,
	A.FullName FullName,
	T.Cid,
	T.CName,
	SUM(FBeginBalanceDebit) FBeginBalanceDebit,
	SUM(FBeginBalanceDebitFor) FBeginBalanceDebitFor,
	SUM(FBeginBalanceCredit) FBeginBalanceCredit,
	SUM(FBeginBalanceCreditFor) FBeginBalanceCreditFor,
	SUM(FDebit) FDebit,
	SUM(FDebitFor) FDebitFor,
	SUM(FCredit) FCredit,
	SUM(FCreditFor) FCreditFor,
	SUM(FYtdDebit) FYtdDebit,
	SUM(FYtdDebitFor) FYtdDebitFor,
	SUM(FYtdCredit) FYtdCredit,
	SUM(FYtdCreditFor) FYtdCreditFor,
	SUM(FEndBalanceDebit) FEndBalanceDebit,
	SUM(FEndBalanceDebitFor) FEndBalanceDebitFor,
	SUM(FEndBalanceCredit) FEndBalanceCredit,
	SUM(FEndBalanceCreditFor) FEndBalanceCreditFor
INTO #ResultTable
FROM #TempData  T
INNER JOIN Ac_Account A ON A.StypeId=T.STypeId AND T.ATypeId LIKE A.TypeId+'%' AND A.FLeveal<=@Leveal AND A.ParId<>'00000'
INNER JOIN (
	SELECT StypeId,TypeId,FullName FROM Ac_Account WHERE StypeId=@STypeId AND ParId='00000'
) F  ON F.StypeId=A.StypeId AND F.TypeId=SUBSTRING(A.TypeId,1,5)
GROUP BY 
	A.ParId,
	F.FullName,
	T.STypeId,
	A.TypeId,
	A.FLeveal,
	A.Fdc,
	T.Ascids,
	T.FieldTypeID,
	T.FieldUserCode,
	T.FieldFullName,
	A.UserCode,
	A.FullName,
	T.Cid,
	T.CName,
	A.FLeveal
	
--是否小计
IF(@IsShowSubTotal=0)
	BEGIN
		INSERT INTO #ResultTable(SubID,Class,STypeId,ATypeId,FLeveal,Fdc,Ascids,FieldTypeID,FieldUserCode,FieldFullName,OrderUserCode,UserCode,FullName,Cid,CName,FBeginBalanceDebit,FBeginBalanceDebitFor,FBeginBalanceCredit,FBeginBalanceCreditFor,FDebit,FDebitFor,FCredit,FCreditFor,FYtdDebit,FYtdDebitFor,FYtdCredit,FYtdCreditFor,FEndBalanceDebit,FEndBalanceDebitFor,FEndBalanceCredit,FEndBalanceCreditFor)
		SELECT
			1 SubID,
			'' Class,
			T.STypeId,
			'' ATypeId,
			0 FLeveal,
			-1 Fdc,
			Ascids,
			FieldTypeID,
			FieldUserCode,
			FieldFullName,
			'99999' OrderUserCode,
			'小计' UserCode,
			'' FullName,
			Cid,
			CName,
			SUM(FBeginBalanceDebit) FBeginBalanceDebit,
			SUM(FBeginBalanceDebitFor) FBeginBalanceDebitFor,
			SUM(FBeginBalanceCredit) FBeginBalanceCredit,
			SUM(FBeginBalanceCreditFor) FBeginBalanceCreditFor,
			SUM(FDebit) FDebit,
			SUM(FDebitFor) FDebitFor,
			SUM(FCredit) FCredit,
			SUM(FCreditFor) FCreditFor,
			SUM(FYtdDebit) FYtdDebit,
			SUM(FYtdDebitFor) FYtdDebitFor,
			SUM(FYtdCredit) FYtdCredit,
			SUM(FYtdCreditFor) FYtdCreditFor,
			SUM(FEndBalanceDebit) FEndBalanceDebit,
			SUM(FEndBalanceDebitFor) FEndBalanceDebitFor,
			SUM(FEndBalanceCredit) FEndBalanceCredit,
			SUM(FEndBalanceCreditFor) FEndBalanceCreditFor
		FROM #ResultTable  T 
		WHERE FLeveal=1
		GROUP BY 
			STypeId,
			Ascids,
			FieldTypeID,
			FieldUserCode,
			FieldFullName,
			Cid,
			CName
	END	
END;	

--======================================业务逻辑处理【END】================================

--============================查询结果集/删除临时表【BEGIN】================================
IF(@Cid=-1)
	BEGIN
		SET @SQL='
		SELECT 
			SubID,
			Class,
			ATypeId,
			FieldTypeID,
			FieldUserCode,
			FieldFullName,
			OrderUserCode,
			UserCode,
			FullName,
			FLeveal'
		SELECT @SQL=@SQL+',SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FBeginBalanceDebit ELSE 0 END) ['+FullName+'FBeginBalanceDebit]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FBeginBalanceDebitFor ELSE 0 END) ['+FullName+'FBeginBalanceDebitFor]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FBeginBalanceCredit ELSE 0 END) ['+FullName+'FBeginBalanceCredit]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FBeginBalanceCreditFor ELSE 0 END) ['+FullName+'FBeginBalanceCreditFor]
		
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FDebit ELSE 0 END) ['+FullName+'FDebit]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FDebitFor ELSE 0 END) ['+FullName+'FDebitFor]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FCredit ELSE 0 END) ['+FullName+'FCredit]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FCreditFor ELSE 0 END) ['+FullName+'FCreditFor]
		
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FYtdDebit ELSE 0 END) ['+FullName+'FYtdDebit]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FYtdDebitFor ELSE 0 END) ['+FullName+'FYtdDebitFor]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FYtdCredit ELSE 0 END) ['+FullName+'FYtdCredit]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FYtdCreditFor ELSE 0 END) ['+FullName+'FYtdCreditFor]
		
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FEndBalanceDebit ELSE 0 END) ['+FullName+'FEndBalanceDebit]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FEndBalanceDebitFor ELSE 0 END) ['+FullName+'FEndBalanceDebitFor]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FEndBalanceCredit ELSE 0 END) ['+FullName+'FEndBalanceCredit]
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FEndBalanceCreditFor ELSE 0 END) ['+FullName+'FEndBalanceCreditFor]'
		FROM #Ac_Currency	
		SET @SQL+='
		FROM #ResultTable 
		GROUP BY 
			SubID,
			Class,
			ATypeId,
			FieldTypeID,
			FieldUserCode,
			FieldFullName,
			OrderUserCode,
			UserCode,
			FullName,
			FLeveal
		 ORDER BY 
			FieldUserCode,SubID,OrderUserCode'
		EXEC(@SQL)
	END
ELSE 
	BEGIN
		--页面数据
		SELECT * FROM #ResultTable ORDER BY FieldUserCode,SubID,OrderUserCode
	END
	
--删除临时表
DROP TABLE #Ac_Currency,#AssistDetails,#TSonAtype,#TempData,#ResultTable,#TempResult,#AssistDetailsTemp
--============================查询结果集/删除临时表【BEGIN】================================
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_AcAssistCombinationQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_AcAssistCombinationQuery]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
    作者：佘海源
	日期：2012-05-29
	描述：辅助核算组合表查询
-------------------------------------------*/
CREATE PROCEDURE WEB_AcAssistCombinationQuery 
(
       @STypeId 		VARCHAR(100),	---分支机构ID
       @ATypeId			VARCHAR(Max),	---会计科目ID   
       @AscidW 			INT,			---辅助核算类型(横向)
       @AscidH 			INT,			---辅助核算类型(纵向)
       @DataType		INT,			---取数类型（0-借方发生额 1-贷方发生额 2-期初余额 3-期末余额）     
       @Cid				INT,			---币别ID(-1:所有币别）
	   @FYear		    INT,			---会计年度       
	   @FPeriodStart    INT,			---起始期间
	   @FPeriodEnd      INT,			---结束期间
	   @IsShowNoAccount INT,			---是否显示未过账
	   @IsShowNull		INT,			---全部金额为零不显示()
	   @chvOperatorID	VARCHAR(50)		---操作员ID
)
----@encode$--
AS 
SET NOCOUNT ON


---分支机构权限判断
IF NOT EXISTS(SELECT * from dbo.F_GetManDetailAllSType(@chvOperatorID) WHERE TypeId=@STypeId)
SET @STypeId=''


--辅助类型Code--
DECLARE @AsCodeW  VARCHAR(100) set @AsCodeW=(SELECT UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@AscidW)
DECLARE @AsCodeH  VARCHAR(100) set @AsCodeH=(SELECT UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@AscidH)

	BEGIN--处理会计科目多级权限
		CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
		INSERT INTO #Ac_Account_L (Typeid,StypeId) 
		SELECT L.Typeid,L.Stypeid FROM F_TreeAccount(@chvOperatorID,'') L
	END; 	
 ---------------------------------------获取期初数据-------------------------------------------
 -- 1.期初也有辅助核算
 -- 2.并且期初和凭证里科目可能不同，凭证查询出来的， 期初里未必有；相反也一样
 -- 3.期初数据不含综合本位币，所有在查询出来的期初数据要加入综合本位币项
 -----------------------------------------------------------------------------------------------
DECLARE @Year INT=0
SELECT @Year=SFYear FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
CREATE TABLE #IniAccount
(
	ATypeId 		VARCHAR(100),	
	AssNameW		VARCHAR(max),	
	AssNameH 		VARCHAR(max),		
	Cid 			INT,			
	IniTotalFor		 NUMERIC(24, 10) ,			
	IniTotal		 NUMERIC(24, 10) ,		
	FDebitTotalFor	 NUMERIC(24, 10) ,	    
	FDebitTotal		 NUMERIC(24, 10) ,
	FCreditTotalFor	 NUMERIC(24, 10) ,	    
	FCreditTotal	 NUMERIC(24, 10) ,
	FPeriod			INT	    
)
SELECT * INTO #IniDetails FROM #IniAccount

/*******************************************计算期初：综合本位币以单币别循环计算*******************************************/
--筛选数据
CREATE TABLE #IniAccountDetails
(
	ATypeId 		VARCHAR(100),	
	Cid 			INT,			
	IniTotalFor		 NUMERIC(24, 10) ,			
	IniTotal		 NUMERIC(24, 10) ,		
	FDebitTotalFor	 NUMERIC(24, 10) ,	    
	FDebitTotal		 NUMERIC(24, 10) ,
	FCreditTotalFor	 NUMERIC(24, 10) ,	    
	FCreditTotal	 NUMERIC(24, 10) ,
	FPeriod			INT,
	GroupId			INT
)
INSERT INTO #IniAccountDetails(ATypeId,Cid,IniTotalFor,IniTotal,FDebitTotalFor,FDebitTotal,FCreditTotalFor,FCreditTotal,FPeriod,GroupId)
SELECT DISTINCT	
	H.ATypeId,
	H.Cid,
	MAX(ISNULL(H.IniTotalFor,0)) IniTotalFor,
	MAX(ISNULL(H.IniTotal,0)) IniTotal,
	0 FDebitTotalFor,
	0 FDebitTotal,
	0 FCreditTotalFor,
	0 FCreditTotal,
	H.FPeriod,
	H.GroupId
FROM Ac_IniAccount_Assist_CheckItems_Detail H
INNER JOIN #Ac_Account_L L ON H.ATypeId=L.TypeId AND L.StypeId=H.StypeId
WHERE  
	H.ATypeId=@ATypeId
	AND H.STypeId=@STypeId
	AND H.Ascids IN(@AscidW,@AscidH)
GROUP BY H.ATypeId,H.Cid,H.FPeriod,H.GroupId

DECLARE @CheckItems TABLE(STypeID VARCHAR(50),ATypeID VARCHAR(50),AssNameW VARCHAR(100),AssNameH VARCHAR(100),GroupId INT,CID INT)--合并列表
--如果指定分支机构没有开账期初取财务期初辅助表 否则就直接去科目余额辅助表
INSERT INTO @CheckItems(STypeID,ATypeID,AssNameW,AssNameH,GroupId,CID)
SELECT DISTINCT
	A.STypeId,
	A.ATypeId,
	dbo.AssisitItemSelector(@AsCodeW,A.FieldValue,@chvOperatorID,@STypeId) AS AssNameW,
	dbo.AssisitItemSelector(@AsCodeH,B.FieldValue,@chvOperatorID,@STypeId) AS AssNameH,
	A.GroupId,
	A.Cid
FROM Ac_IniAccount_Assist_CheckItems_Detail A
INNER JOIN #Ac_Account_L L ON A.ATypeId=L.TypeId AND L.StypeId=A.StypeId
INNER JOIN Ac_IniAccount_Assist_CheckItems_Detail B ON B.STypeId=A.STypeId AND B.ATypeId=A.ATypeId AND B.Ascids=@AsCodeH AND A.GroupId=B.GroupId AND B.Cid=A.Cid
WHERE 
	A.Ascids=@AsCodeW
	AND A.STypeId=@STypeId
	AND A.ATypeId=@ATypeId
	
INSERT INTO #IniDetails(ATypeId,AssNameW,AssNameH,Cid,IniTotalFor,IniTotal,FDebitTotalFor,FDebitTotal,FCreditTotalFor,FCreditTotal,FPeriod)
SELECT DISTINCT	D.ATypeId,
	I.AssNameW,
	I.AssNameH,
	D.Cid,
	D.IniTotalFor,
	D.IniTotal,
	0 FDebitTotalFor,
	0 FDebitTotal,
	0 FCreditTotalFor,
	0 FCreditTotal,
	D.FPeriod
FROM #IniAccountDetails D
INNER JOIN @CheckItems I ON I.ATypeID=D.ATypeId AND I.CID=D.Cid AND I.GroupId=D.GroupId

--计算综合本位币
INSERT INTO #IniAccount(ATypeId,AssNameW,AssNameH,Cid,IniTotalFor,IniTotal,FDebitTotalFor,FDebitTotal,FCreditTotalFor,FCreditTotal,FPeriod)
SELECT 
	ATypeId,
	AssNameW,
	AssNameH,
	Cid,
	IniTotalFor,
	IniTotal,
	FDebitTotalFor,
	FDebitTotal,
	FCreditTotalFor,
	FCreditTotal,
	FPeriod 
FROM #IniDetails
UNION ALL
SELECT ATypeId,
	AssNameW,
	AssNameH,
	0 Cid,
	Sum(IniTotal) AS IniTotalFor,
	Sum(IniTotal) AS IniTotal,
	Sum(FDebitTotal) AS FDebitTotalFor,
	Sum(FDebitTotal) AS FDebitTotal,
	Sum(FCreditTotal) AS FCreditTotalFor,
	Sum(FCreditTotal) AS FCreditTotal,
	FPeriod
FROM #IniDetails
GROUP BY ATypeId,AssNameW,AssNameH,FPeriod
DROP TABLE #IniAccountDetails,#IniDetails	
----------------------------------------凭证组合查询---------------------------------------------- 
--1.首先需从Ac_Voucher_Bill_Assist_CheckItems进行组合查询
--2.根据1中查询结果，再从Ac_Voucher_Bill获取具体数据
--3.凭证中也没有单独的综合本位币项，此处需要计算（综合本位币=外币换算的本位币+本币） 
---------------------------------------------------------------------------------------------------

 --------------------组合基本查询，获取凭证号--------------------- 
SELECT	A.BillNumberId,
		A.vBId,
		dbo.AssisitItemSelector(A.typeName,A.TypeId,@chvOperatorID,@STypeId) AS AssNameW,
		dbo.AssisitItemSelector(B.typeName,B.TypeId,@chvOperatorID,@STypeId) AS AssNameH
  INTO	#AssSource		
  FROM	Ac_Voucher_Bill_Assist_CheckItems A 
  JOIN	(SELECT TypeId,typeName,vBId FROM Ac_Voucher_Bill_Assist_CheckItems WHERE typeName=@AsCodeH) B ON A.vBId=B.vBId
 WHERE	A.typeName=@AsCodeW
  
 ---------------------------基本数据获取-------------------
 
SELECT	bill.ATypeId,
		AssS.AssNameW,
		AssS.AssNameH,
		Cid,
		CASE WHEN bill.Fdc=1 THEN SUM(bill.FDebitTotalFor - bill.FCreditTotalFor) 
			 ELSE SUM(bill.FCreditTotalFor - bill.FDebitTotalFor) 
		END AS FEndTotalFor,
		CASE WHEN bill.Fdc=1 THEN SUM(bill.FDebitTotal - bill.FCreditTotal)
			 ELSE SUM(bill.FCreditTotal - bill.FDebitTotal) 
		END AS FEndTotal,
		SUM(bill.FDebitTotalFor) AS FDebitTotalFor ,
		SUM(bill.FDebitTotal) AS FDebitTotal,
		SUM(bill.FCreditTotalFor) AS FCreditTotalFor,
		SUM(bill.FCreditTotal) AS FCreditTotal,
		bill.FPeriod,
		bill.FYear
  INTO	#CountSource	
  FROM	Ac_Voucher_Bill bill
  JOIN	#AssSource AssS ON AssS.vBId=bill.ID   			
  JOIN	Ac_Voucher V ON bill.BillNumberId = V.BillNumberId 
		AND ((@IsShowNoAccount=0 AND V.IfCheck='t')OR (@IsShowNoAccount=1))
		AND V.FChecked<>-1
 WHERE	bill.STypeId=@STypeId
   AND  bill.ATypeId=@ATypeId
   AND	bill.FYear<=@FYear
 GROUP BY bill.FPeriod,AssS.AssNameW,AssS.AssNameH,Cid,bill.ATypeId,bill.Fdc,bill.FYear


 ---------------------------计算综合本位币-------------------
  
  INSERT INTO #CountSource
  SELECT ATypeId,
		 AssNameW,
		 AssNameH,
		 0 AS Cid,
		 SUM(FEndTotal)AS FEndTotalFor,
		 SUM(FEndTotal)AS FEndTotal,
		 SUM(FDebitTotal)AS  FDebitTotalFor,
		 SUM(FDebitTotal)AS  FDebitTotal,
		 SUM(FCreditTotal)AS FCreditTotalFor,
		 SUM(FCreditTotal)AS FCreditTotal,
		 FPeriod,
		 FYear
	FROM #CountSource
GROUP BY FPeriod,AssNameW,AssNameH,ATypeId,FYear



---------------------------------根据查询条件具体计算选择项-----------------------------
--取数类型@DataType：0-借方发生额 1-贷方发生额 2-期初余额 3-期末余额”
--借、贷方发生额=累计借、贷+期初借、贷
--期初余额=上期期末+期初
--期末余额=期末余额+期初
-----------------------------------------------------------------------------------------
 
CREATE TABLE #AllTemp (AssNameH VARCHAR(max),AssNameW VARCHAR(max),Data  NUMERIC(24, 10)  )
DECLARE @DataFiled VARCHAR(max) SET @DataFiled=''
DECLARE @AddFiled  VARCHAR(max) SET @AddFiled=''
DECLARE @mysql VARCHAR(max) SET @mysql=''

	IF(@DataType=0)
	BEGIN
		SET	@AddFiled='FDebitTotalFor'
		SET	@DataFiled ='FDebitTotalFor' 
	END
	ELSE IF(@DataType=1)
	BEGIN
		SET	@AddFiled = 'FCreditTotalFor'
		SET	@DataFiled ='FCreditTotalFor'
	END
	ELSE IF(@DataType=2)
	BEGIN
		SET @FPeriodEnd = @FPeriodStart-1
		SET @FPeriodStart=0
		SET @DataFiled ='FEndTotalFor'
		SET @AddFiled='IniTotalFor'
	END
	ELSE IF(@DataType=3)
	BEGIN
		SET	@AddFiled='IniTotalFor'
		SET	@DataFiled ='FEndTotalFor'
		SET @FPeriodStart=1
	END 
IF(@FYear=@Year)
	BEGIN
		SET @mysql=' INSERT INTO #AllTemp
		SELECT AssNameH,AssNameW,SUM('+@DataFiled+')AS Data FROM
		( 
		SELECT AssNameH,AssNameW,'+@DataFiled+' 
		FROM #CountSource
		WHERE Cid='+CAST(@Cid AS VARCHAR(10))+'
		AND CONVERT(INT,FPeriod) >= '+CAST(@FPeriodStart AS VARCHAR(10))+' 
		AND CONVERT(INT,FPeriod) <= '+CAST(@FPeriodEnd AS VARCHAR(10))+' 
		UNION ALL
		SELECT AssNameH,AssNameW,'+@AddFiled+' FROM #IniAccount
		WHERE Cid='+CAST(@Cid AS VARCHAR(10))+'
		) t
		WHERE (('+CAST(@IsShowNull AS VARCHAR(10))+'=0 AND '+@DataFiled+'<>0)OR ('+CAST(@IsShowNull AS VARCHAR(10))+'=1))
		GROUP BY AssNameH,AssNameW '
	END
ELSE 
	BEGIN
		SET @mysql=' 
		INSERT INTO #AllTemp
		SELECT 
			AssNameH,
			AssNameW,
			SUM('+@DataFiled+')AS Data 
		FROM
		( 
			SELECT 
				AssNameH,
				AssNameW,
				CASE WHEN '''+@DataFiled+''' IN(''FDebitTotalFor'',''FCreditTotalFor'')  THEN 0 ELSE '+@DataFiled+' END '+@DataFiled+'
			FROM #CountSource
			WHERE 
				Cid='+CAST(@Cid AS VARCHAR(10))+'
				AND FYear<'+CAST(@FYear AS VARCHAR(10))+'	
			UNION ALL
			SELECT 
				AssNameH,
				AssNameW,
				'+@DataFiled+' 
			FROM #CountSource
			WHERE 
				Cid='+CAST(@Cid AS VARCHAR(10))+'
				AND FYear='+CAST(@FYear AS VARCHAR(10))+'	
				AND FPeriod>= '+CAST(@FPeriodStart AS VARCHAR(10))+' 
				AND FPeriod<= '+CAST(@FPeriodEnd AS VARCHAR(10))+' 
			UNION ALL
			SELECT 
				AssNameH,
				AssNameW,
				'+@AddFiled+' 
			FROM #IniAccount
			WHERE 
				Cid='+CAST(@Cid AS VARCHAR(10))+'
		) t
		WHERE 
			('+CAST(@IsShowNull AS VARCHAR(10))+'=0 AND '+@DataFiled+'<>0)
			OR ('+CAST(@IsShowNull AS VARCHAR(10))+'=1)
		GROUP BY AssNameH,AssNameW '
	END
	 --PRINT (@mysql)
     EXEC(@mysql)
----------------二维变换-------------

IF  EXISTS(SELECT * FROM #AllTemp) 
BEGIN
	DECLARE @sql VARCHAR(MAX) 
	SELECT  @sql=ISNULL(@sql+',','')+'SUM(CASE WHEN AssNameW='''+AssNameW+''' THEN Data ELSE NULL END) AS ['+AssNameW+']'
	FROM(SELECT DISTINCT AssNameW FROM #AllTemp )t 
	--PRINT(@sql)
	EXEC('SELECT AssNameH,'+@sql+' FROM #AllTemp GROUP BY AssNameH  ') 
END 
ELSE 
	SELECT '没有查询到相关组合数据' AS back
		 
DROP TABLE #AssSource,#CountSource,#AllTemp,#IniAccount



			 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_AcBalanceQuery]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[WEB_AcBalanceQuery]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
    作者：glj
	日期：2012-03-31
	描述：科目余额表查询/
-------------------------------------------*/
CREATE PROCEDURE WEB_AcBalanceQuery
(
	@STypeId 			VARCHAR(MAX),	--分支机构ID
	@ATypeId			NVARCHAR(MAX),	--会计科目ID(可以多值，以,为分隔符 例：xxx,xxx,xx)        
	@Cid				INT,			--币别ID(-1:所有币别）
	@Leveal				INT,			--科目级别(1-10) -1:所有级别     
	@FYear				INT,			--会计年度       
	@FPeriodStart		INT,			--起始期间
	@FPeriodEnd			INT,			--结束期间
	@IsShowNoAccount	BIT=0,			--包含未记账凭证
	@IsShowFNull		BIT=0,			--不显示本期没有发生额的科目
	@IsBalanceNull		BIT=0,			--不包括余额为零的科目
	@IsShowFYNull		BIT=0,			--不显示本年没有发生额的科目
	@IsShowSubTotal		BIT=0,			--不显示科目小计
	@IsShowPL			BIT=0,			--不包含查询期间内结转损益数据
	@IsShowQty			BIT=0,			--数量金额显示
	@isnotshow0			BIT=0,			--不显示为0的数据
	@chvOperatorID		VARCHAR(50)		---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON
--========================================临时表及赋值【BEGIN】=====================================
CREATE TABLE #Ac_Balance   --返回数据表
(
	STypeId				VARCHAR(50),						--分支机构
	ATypeId				VARCHAR(50),						--科目
	Fdc					INT,								--科目方向
	Cid					INT,								--币种
	NCDebitFor			NUMERIC(24, 10)	NOT NULL DEFAULT(0),--年初借方
	NCCreditFor			NUMERIC(24, 10) NOT NULL DEFAULT(0),--年初贷方
	FDebitBeginFor		NUMERIC(24, 10)	NOT NULL DEFAULT(0),--期初借方
	FCreditBeginFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),--期初贷方
	FDebitFor			NUMERIC(24, 10) NOT NULL DEFAULT(0),--本期借方
	FCreditFor			NUMERIC(24, 10) NOT NULL DEFAULT(0),--本期贷方
	FYtdDebitFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),--本年借方
	FYtdCreditFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),--本年贷方
	FDebitEndFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),--期末借方
	FCreditEndFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),--期末贷方
	NCDebitForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),--年初借方数量
	NCCreditForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),--年初贷方数量
	FDebitBeginForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),--期初借方数量
	FCreditBeginForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),--期初贷方数量
	FDebitForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),--本期借方数量
	FCreditForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),--本期贷方数量
	FYtdDebitForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),--本年借方数量
	FYtdCreditForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),--本年贷方数量
	FDebitEndForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),--期末借方数量
	FCreditEndForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0)	--期末贷方数量
)
--WEB_AcBalanceSumQuery
INSERT INTO #Ac_Balance EXEC WEB_QueryAcBalanceFromVoucher  @STypeId,@FYear,@Cid,@FPeriodStart,@FPeriodEnd,@IsShowNoAccount,@IsShowPL,@chvOperatorID

--币种
CREATE TABLE #AcCurrency(CId INT,FullName VARCHAR(200))
IF(@Cid=-1)
	BEGIN
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT CId,FullName FROM Ac_Currency 
		UNION ALL
		SELECT 0,'综合本位币'
	END
ELSE IF @Cid=0
	BEGIN
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT 0,'综合本位币'
	END
ELSE
	BEGIN
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT CId,FullName FROM Ac_Currency  WHERE CId=@Cid
	END
--直接匹配科目，只有之类科目ID 科目判断，如果是单独子类科目，需要单独处理获取父节点
IF (SELECT COUNT(*) FROM dbo.f_split(@STypeId,','))=1 AND EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND TypeId=@ATypeId AND SonNum=0 AND FLeveal<>1)
	BEGIN
		DECLARE @ATypeId_L VARCHAR(MAX)=''--包含父节点
		;WITH Parid AS
		(
			SELECT ParId,TypeId FROM Ac_Account WHERE StypeId=@STypeId AND TypeId=@ATypeId
			UNION ALL 
			SELECT A.ParId,A.TypeId FROM Ac_Account A INNER JOIN Parid P ON P.ParId=A.TypeId AND A.StypeId=@STypeId AND A.FLeveal>=1
		)
		SELECT @ATypeId_L+=TypeId+',' FROM Parid
		IF(@ATypeId_L<>'')
			SET @ATypeId=SUBSTRING(@ATypeId_L,1,LEN(@ATypeId_L)-1)
	END

DECLARE @SQL VARCHAR(MAX)=''	
--所有科目
CREATE TABLE #Account(STypeId VARCHAR(50),Class VARCHAR(200),TypeID VARCHAR(50),OrderUserCode VARCHAR(MAX),UserCode VARCHAR(200),FullName VARCHAR(200),FLeveal INT,Fdc INT)	
SET @SQL='
INSERT INTO #Account(STypeId,Class,TypeID,UserCode,OrderUserCode,FullName,FLeveal,Fdc)
SELECT
	A.STypeId,
	A1.FullName Class,
	A.TypeId,
	REPLICATE(''    '',A.FLeveal-1) + A.UserCode UserCode, 
	A.UserCode OrderUserCode,
	A.FullName,
	A.FLeveal,
	A.Fdc
FROM Ac_Account A
INNER JOIN f_split('''+@STypeId+''','','') S ON S.a=A.STypeId
INNER JOIN Ac_Account A1 ON A1.ParId=''00000'' AND A1.Stypeid=A.Stypeid AND A1.TypeId=SUBSTRING(A.TypeId,1,5)
INNER JOIN F_TreeAccount('''+@chvOperatorID+''','''') L ON L.Stypeid=A.StypeId AND L.Typeid=A.TypeId AND A.ParId<>''00000'' AND A.FLeveal<='+CAST(@Leveal AS VARCHAR(2))+CHAR(13)
IF ISNULL(@ATypeId,'')<>''
	SET @SQL+='	INNER JOIN f_split('''+@ATypeId+''','','') F ON F.a=A.TypeId'
EXEC(@SQL)

--删除多余科目数据
IF(SELECT COUNT(*) FROM dbo.f_split(@STypeId,','))=1 AND ISNULL(@ATypeId,'')<>''
	BEGIN
		DELETE FROM #Ac_Balance WHERE NOT EXISTS(SELECT * FROM #Account A WHERE A.STypeId=STypeId AND ATypeId LIKE A.TypeID+'%')
	END
--========================================临时表及赋值【END】=====================================

--========================================获取数据【BEGIN】  =====================================
--不显示数据为0的科目
--IF(@isnotshow0=1)
--	BEGIN
--		DELETE FROM #Ac_Balance 
--		WHERE 
--			NCDebitFor=0
--			AND NCCreditFor=0
--			AND FDebitBeginFor=0
--			AND FCreditBeginFor=0
--			AND FDebitFor=0
--			AND FCreditFor=0
--			AND FYtdDebitFor=0
--			AND FYtdCreditFor=0
--			AND FDebitEndFor=0
--			AND FCreditEndFor=0
--			AND NCDebitForQty=0
--			AND NCCreditForQty=0
--			AND FDebitBeginForQty=0
--			AND FCreditBeginForQty=0
--			AND FDebitForQty=0
--			AND FCreditForQty=0
--			AND FYtdDebitForQty=0
--			AND FYtdCreditForQty=0
--			AND FDebitEndForQty=0
--			AND FCreditEndForQty=0
--	END

SELECT	TOP 0
	A.Class,
	A.TypeID,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	C.CId,
	C.FullName CidName,
	A.FLeveal,
	(B.NCDebitFor) NCDebitFor,
	(B.NCCreditFor) NCCreditFor,
	(B.FDebitBeginFor) FBeginBalanceDebitFor,
	(B.FCreditBeginFor) FBeginBalanceCreditFor,
	(B.FDebitFor) FDebitFor,
	(B.FCreditFor) FCreditFor,
	(B.FYtdDebitFor) FYtdDebitFor,
	(B.FYtdCreditFor) FYtdCreditFor,
	(B.FDebitEndFor) FEndBalanceDebitFor,
	(B.FCreditEndFor) FEndBalanceCreditFor,
	(B.NCDebitForQty) NCDebitForQty,
	(B.NCCreditForQty) NCCreditForQty,
	(B.FDebitBeginForQty) FBeginBalanceDebitForQty,
	(B.FCreditBeginForQty) FBeginBalanceCreditForQty,
	(B.FDebitForQty) FDebitForQty,
	(B.FCreditForQty) FCreditForQty,
	(B.FYtdDebitForQty) FYtdDebitForQty,
	(B.FYtdCreditForQty) FYtdCreditForQty,
	(B.FDebitEndForQty) FEndBalanceDebitForQty,
	(B.FCreditEndForQty) FEndBalanceCreditForQty
INTO #ResultTable
FROM #Ac_Balance B	
INNER JOIN #Account A ON A.STypeId=B.STypeId AND B.ATypeId = A.TypeID 
INNER JOIN #AcCurrency C ON C.CId=B.Cid

--计算父类
IF @IsShowSubTotal=0 AND @Cid<>-1
	BEGIN
		INSERT INTO #ResultTable(Class,TypeID,UserCode,OrderUserCode,FullName,CId,CidName,FLeveal,NCDebitFor,NCCreditFor,FBeginBalanceDebitFor,FBeginBalanceCreditFor,FDebitFor,FCreditFor,FYtdDebitFor,FYtdCreditFor,FEndBalanceDebitFor,FEndBalanceCreditFor,NCDebitForQty,NCCreditForQty,FBeginBalanceDebitForQty,FBeginBalanceCreditForQty,FDebitForQty,FCreditForQty,FYtdDebitForQty,FYtdCreditForQty,FEndBalanceDebitForQty,FEndBalanceCreditForQty)
		SELECT
			A.Class,
			A.TypeID,
			A.UserCode,
			A.OrderUserCode,
			A.FullName,
			C.CId,
			C.FullName CidName,
			A.FLeveal,
			SUM(B.NCDebitFor) NCDebitFor,
			SUM(B.NCCreditFor) NCCreditFor,
			SUM(B.FDebitBeginFor) FBeginBalanceDebitFor,
			SUM(B.FCreditBeginFor) FBeginBalanceCreditFor,
			SUM(B.FDebitFor) FDebitFor,
			SUM(B.FCreditFor) FCreditFor,
			SUM(B.FYtdDebitFor) FYtdDebitFor,
			SUM(B.FYtdCreditFor) FYtdCreditFor,
			SUM(B.FDebitEndFor) FEndBalanceDebitFor,
			SUM(B.FCreditEndFor) FEndBalanceCreditFor,
			SUM(B.NCDebitForQty) NCDebitForQty,
			SUM(B.NCCreditForQty) NCCreditForQty,
			SUM(B.FDebitBeginForQty) FBeginBalanceDebitForQty,
			SUM(B.FCreditBeginForQty) FBeginBalanceCreditForQty,
			SUM(B.FDebitForQty) FDebitForQty,
			SUM(B.FCreditForQty) FCreditForQty,
			SUM(B.FYtdDebitForQty) FYtdDebitForQty,
			SUM(B.FYtdCreditForQty) FYtdCreditForQty,
			SUM(B.FDebitEndForQty) FEndBalanceDebitForQty,
			SUM(B.FCreditEndForQty) FEndBalanceCreditForQty
		--INTO #ResultTable
		FROM #Ac_Balance B
		INNER JOIN #Account A ON A.STypeId=B.STypeId AND B.ATypeId LIKE A.TypeID+'%' 
		INNER JOIN #AcCurrency C ON C.CId=B.Cid
		WHERE
			((@IsShowFNull=1 AND (B.FDebitFor!=0 OR B.FCreditFor!=0)) OR @IsShowFNull=0)
			AND ((@IsBalanceNull=1 AND (B.FDebitEndFor!=0 OR B.FCreditEndFor!=0 OR B.FDebitBeginFor!=0 OR B.FCreditBeginFor!=0)) OR @IsBalanceNull=0)
			AND ((@IsShowFYNull=1 AND (B.FYtdDebitFor!=0 OR B.FYtdCreditFor!=0)) OR @IsShowFYNull=0)

		GROUP BY 
			A.Class,
			A.TypeID,
			A.Class,
			A.TypeID,
			A.UserCode,
			A.OrderUserCode,
			A.FullName,
			C.CId,
			C.FullName,
			A.FLeveal
		ORDER BY A.OrderUserCode
		
	END
ELSE 
	BEGIN
		INSERT INTO #ResultTable(Class,TypeID,UserCode,OrderUserCode,FullName,CId,CidName,FLeveal,NCDebitFor,NCCreditFor
								,FBeginBalanceDebitFor,FBeginBalanceCreditFor,FDebitFor,FCreditFor,FYtdDebitFor,FYtdCreditFor
								,FEndBalanceDebitFor,FEndBalanceCreditFor,NCDebitForQty,NCCreditForQty,FBeginBalanceDebitForQty,FBeginBalanceCreditForQty
								,FDebitForQty,FCreditForQty,FYtdDebitForQty,FYtdCreditForQty,FEndBalanceDebitForQty,FEndBalanceCreditForQty)
		SELECT
			A.Class,
			A.TypeID,
			A.UserCode,
			A.OrderUserCode,
			A.FullName,
			C.CId,
			C.FullName CidName,
			A.FLeveal,
			SUM(B.NCDebitFor) NCDebitFor,
			SUM(B.NCCreditFor) NCCreditFor,
			SUM(B.FDebitBeginFor) FBeginBalanceDebitFor,
			SUM(B.FCreditBeginFor) FBeginBalanceCreditFor,
			SUM(B.FDebitFor) FDebitFor,
			SUM(B.FCreditFor) FCreditFor,
			SUM(B.FYtdDebitFor) FYtdDebitFor,
			SUM(B.FYtdCreditFor) FYtdCreditFor,
			SUM(B.FDebitEndFor) FEndBalanceDebitFor,
			SUM(B.FCreditEndFor) FEndBalanceCreditFor,
			SUM(B.NCDebitForQty) NCDebitForQty,
			SUM(B.NCCreditForQty) NCCreditForQty,
			SUM(B.FDebitBeginForQty) FBeginBalanceDebitForQty,
			SUM(B.FCreditBeginForQty) FBeginBalanceCreditForQty,
			SUM(B.FDebitForQty) FDebitForQty,
			SUM(B.FCreditForQty) FCreditForQty,
			SUM(B.FYtdDebitForQty) FYtdDebitForQty,
			SUM(B.FYtdCreditForQty) FYtdCreditForQty,
			SUM(B.FDebitEndForQty) FEndBalanceDebitForQty,
			SUM(B.FCreditEndForQty) FEndBalanceCreditForQty
		FROM #Ac_Balance B
		INNER JOIN #Account A ON A.STypeId=B.STypeId AND B.ATypeId LIKE A.TypeID+'%'
		INNER JOIN #AcCurrency C ON C.CId=B.Cid
		WHERE
			((@IsShowFNull=1 AND (B.FDebitFor!=0 OR B.FCreditFor!=0)) OR @IsShowFNull=0)
			AND ((@IsBalanceNull=1 AND (B.FDebitEndFor!=0 OR B.FCreditEndFor!=0 OR B.FDebitBeginFor!=0 OR B.FCreditBeginFor!=0)) OR @IsBalanceNull=0)
			AND ((@IsShowFYNull=1 AND (B.FYtdDebitFor!=0 OR B.FYtdCreditFor!=0)) OR @IsShowFYNull=0)
		GROUP BY 
			A.Class,
			A.TypeID,
			A.Class,
			A.TypeID,
			A.UserCode,
			A.OrderUserCode,
			A.FullName,
			C.CId,
			C.FullName,
			A.FLeveal
		ORDER BY A.OrderUserCode
	END
--========================================获取数据【END】    =====================================
--不显示数据为0且没有子科目的科目
IF(@isnotshow0=1)
BEGIN
	DECLARE @TMPLeveal	INT
	SET @TMPLeveal = @Leveal
	
	WHILE @TMPLeveal > 0
	BEGIN
		;WITH SONS AS 
		(
			SELECT	LEFT(TypeID,5*FLeveal) AS parenttypeid
			FROM	#ResultTable
			WHERE	FLeveal = @TMPLeveal + 1
				
		)
		DELETE FROM #ResultTable 
		WHERE	NCDebitFor=0
				AND NCCreditFor=0
				AND FBeginBalanceDebitFor=0
				AND FBeginBalanceCreditFor=0
				AND FDebitFor=0
				AND FCreditFor=0
				AND FYtdDebitFor=0
				AND FYtdCreditFor=0
				AND FEndBalanceDebitFor=0
				AND FEndBalanceCreditFor=0
				AND NCDebitForQty=0
				AND NCCreditForQty=0
				AND FBeginBalanceDebitForQty=0
				AND FBeginBalanceCreditForQty=0
				AND FDebitForQty=0
				AND FCreditForQty=0
				AND FYtdDebitForQty=0
				AND FYtdCreditForQty=0
				AND FEndBalanceDebitForQty=0
				AND FEndBalanceCreditForQty=0
				AND FLeveal = @TMPLeveal
				AND	NOT EXISTS(SELECT TOP 1 1 FROM SONS WHERE parenttypeid = TypeID)
				
		SET @TMPLeveal = @TMPLeveal - 1
	END
END

--小计放在最后处理
IF @IsShowSubTotal = 0 AND @Cid<>-1
BEGIN	
	INSERT INTO #ResultTable(Class,TypeID,UserCode,OrderUserCode,FullName,CId,CidName,FLeveal,NCDebitFor,NCCreditFor,FBeginBalanceDebitFor,FBeginBalanceCreditFor,FDebitFor,FCreditFor,FYtdDebitFor,FYtdCreditFor,FEndBalanceDebitFor,FEndBalanceCreditFor,NCDebitForQty,NCCreditForQty,FBeginBalanceDebitForQty,FBeginBalanceCreditForQty,FDebitForQty,FCreditForQty,FYtdDebitForQty,FYtdCreditForQty,FEndBalanceDebitForQty,FEndBalanceCreditForQty)
	SELECT
		B.Class,
		NULL TypeID,
		NULL UserCode,
		MAX(B.UserCode)+1 OrderUserCode,
		B.Class+'小计' FullName,
		C.CId,
		C.FullName CidName,
		0 FLeveal,
		SUM(NCDebitFor) NCDebitFor,
		SUM(NCCreditFor) NCCreditFor,
		SUM(FBeginBalanceDebitFor) FBeginBalanceDebitFor,
		SUM(FBeginBalanceCreditFor) FBeginBalanceCreditFor,
		SUM(FDebitFor) FDebitFor,
		SUM(FCreditFor) FCreditFor,
		SUM(FYtdDebitFor) FYtdDebitFor,
		SUM(FYtdCreditFor) FYtdCreditFor,
		SUM(FEndBalanceDebitFor) FEndBalanceDebitFor,
		SUM(FEndBalanceCreditFor) FEndBalanceCreditFor,
		SUM(NCDebitForQty) NCDebitForQty,
		SUM(NCCreditForQty) NCCreditForQty,
		SUM(FBeginBalanceDebitForQty) FBeginBalanceDebitForQty,
		SUM(FBeginBalanceCreditForQty) FBeginBalanceCreditForQty,
		SUM(FDebitForQty) FDebitForQty,
		SUM(FCreditForQty) FCreditForQty,
		SUM(FYtdDebitForQty) FYtdDebitForQty,
		SUM(FYtdCreditForQty) FYtdCreditForQty,
		SUM(FEndBalanceDebitForQty) FEndBalanceDebitForQty,
		SUM(FEndBalanceCreditForQty) FEndBalanceCreditForQty
	FROM #ResultTable B
	INNER JOIN #AcCurrency C ON C.CId=B.Cid
	WHERE B.FLeveal=1
	GROUP BY 
		B.Class,
		C.CId,
		C.FullName
END
--返回结果集	
SELECT * FROM #ResultTable ORDER BY OrderUserCode
--========================================删除临时表【BEGIN】=====================================
DROP TABLE #AcCurrency,#Account,#Ac_Balance,#ResultTable
--========================================删除临时表【END】	 =====================================	
	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_AcBalanceQueryFromVoucher]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_AcBalanceQueryFromVoucher]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：佘海源
	日期：2012-06-05
	描述：科目余额表-在凭证中未过账查询
	
*/
CREATE PROCEDURE WEB_AcBalanceQueryFromVoucher
(
	@IsShowNoAccount	INT,		---是否显示未过账
	@Fyear				INT,		---年度
	@StypeId			VARCHAR(50)---分支机构
)
AS
SET NOCOUNT ON
--修改未开账的情况下没有财务期初数据的情况
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND IsUse=1)--如果指定分支机构没有开账
	BEGIN
		DECLARE @Details TABLE (STypeId VARCHAR(50),ATypeId VARCHAR(50),FBeginBalance  NUMERIC(24, 10) ,FBeginBalanceFor  NUMERIC(24, 10) ,FDebit  NUMERIC(24, 10) ,FDebitFor  NUMERIC(24, 10) ,FCredit  NUMERIC(24, 10) ,FCreditFor  NUMERIC(24, 10) ,Cid INT,FEndBalance  NUMERIC(24, 10)  ,FEndBalanceFor  NUMERIC(24, 10) ,FYtdDebit  NUMERIC(24, 10) ,FYtdDebitFor  NUMERIC(24, 10) ,FYtdCredit  NUMERIC(24, 10) ,FYtdCreditFor  NUMERIC(24, 10) ,FYear VARCHAR(10),FPeriod VARCHAR(10))

		INSERT INTO @Details(STypeId,ATypeId,FBeginBalance,FBeginBalanceFor,FDebit,FDebitFor,FCredit,FCreditFor,Cid,FEndBalance,FEndBalanceFor,FYtdDebit,FYtdDebitFor,FYtdCredit,FYtdCreditFor,FYear,FPeriod)
		SELECT
			STypeId,
			ATypeId,
			iniTotal FBeginBalance,
			iniTotalFor FBeginBalanceFor,
			0 FDebit,
			0 FDebitFor,
			0 FCredit,
			0 FCreditFor,
			Cid,
			iniTotal FEndBalance,
			iniTotalFor FEndBalanceFor,
			FDebit FYtdDebit,
			FDebitFor FYtdDebitFor,
			FCredit FYtdCredit,
			FCreditFor FYtdCreditFor,
			FYear,
			FPeriod
		FROM Ac_IniAccount
		WHERE FYear<=@Fyear AND STypeId=@StypeId
		
		SELECT 
			STypeId,
			ATypeId,
			FBeginBalance,
			FBeginBalanceFor,
			FDebit,
			FDebitFor,
			FCredit,
			FCreditFor,
			Cid,
			FEndBalance,
			FEndBalanceFor,
			FYtdDebit,
			FYtdDebitFor,
			FYtdCredit,
			FYtdCreditFor,
			FYear,
			FPeriod
		FROM @Details
		UNION ALL
		SELECT 
			STypeId,
			ATypeId,
			SUM(ISNULL(FBeginBalance,0)) FBeginBalance,
			SUM(ISNULL(FBeginBalanceFor,0)) FBeginBalanceFor,
			SUM(ISNULL(FDebit,0)) FDebit,
			SUM(ISNULL(FDebitFor,0)) FDebitFor,
			SUM(ISNULL(FCredit,0)) FCredit,
			SUM(ISNULL(FCreditFor,0)) FCreditFor,
			0,
			SUM(ISNULL(FEndBalance,0)) FEndBalance,
			SUM(ISNULL(FEndBalanceFor,0)) FEndBalanceFor,
			SUM(ISNULL(FYtdDebit,0)) FYtdDebit,
			SUM(ISNULL(FYtdDebitFor,0)) FYtdDebitFor,
			SUM(ISNULL(FYtdCredit,0)) FYtdCredit,
			SUM(ISNULL(FYtdCreditFor,0)) FYtdCreditFor,
			@Fyear,
			FPeriod
		FROM @Details
		GROUP BY STypeId,FPeriod,ATypeId
		RETURN	
	END

DECLARE @iniFyear INT, 
		@PreMaxFperiod INT
SELECT @iniFyear=SFYear FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeId
--SELECT @PreMaxFperiod=MAX(FPeriod) FROM dbo.Ac_Period		
SELECT @PreMaxFperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance WHERE FYear=@Fyear-1 AND STypeId=@StypeId

IF(@IsShowNoAccount=0)
BEGIN	
	--modify bug by dongzhan 2013.10.9 特殊情况 ，余额表是2013年11月，我查询2014年1月，1月的期初是11月的期末 
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Balance WHERE FYear=@Fyear AND STypeId=@StypeId)
		BEGIN
		   SELECT 
				STypeId,
				ATypeId,
				FBeginBalance,
				FBeginBalanceFor,
				FDebit,
				FDebitFor,
				FCredit,
				FCreditFor,
				Cid,
				FEndBalance,
				FEndBalanceFor,
				FYtdDebit,
				FYtdDebitFor,
				FYtdCredit,
				FYtdCreditFor,
				FYear,
				FPeriod 
			FROM Ac_Balance WHERE STypeId=@StypeId AND FYear<=@Fyear
		END
	ELSE 
		SELECT STypeId,ATypeId,FEndBalance,FEndBalanceFor,0,0,0,0,cid,FEndBalance,FEndBalanceFor,0,0,0,0,@Fyear,1 FROM dbo.Ac_Balance WHERE FYear=@Fyear-1 AND FPeriod=@PreMaxFperiod  AND STypeId=@StypeId
	RETURN
END


 
CREATE TABLE #AcBalanceTable   --余额临时表，处理未过账凭证
(
 STypeId VARCHAR(50),
 ATypeId VARCHAR(50),
 FBeginBalance  NUMERIC(24, 10)  DEFAULT 0,
 FBeginBalanceFor  NUMERIC(24, 10)  DEFAULT 0,
 FDebit  NUMERIC(24, 10)  DEFAULT 0,
 FDebitFor  NUMERIC(24, 10)  DEFAULT 0,
 FCredit  NUMERIC(24, 10)  DEFAULT 0,
 FCreditFor  NUMERIC(24, 10)  DEFAULT 0,
 Cid INT,
 FEndBalance  NUMERIC(24, 10)  DEFAULT 0,
 FEndBalanceFor  NUMERIC(24, 10)  DEFAULT 0,
 FYtdDebit  NUMERIC(24, 10)  DEFAULT 0,
 FYtdDebitFor  NUMERIC(24, 10)  DEFAULT 0,
 FYtdCredit  NUMERIC(24, 10)  DEFAULT 0,
 FYtdCreditFor  NUMERIC(24, 10)  DEFAULT 0,
 FYear INT,
 FPeriod INT,
 Fdc INT
)
 
	/********************************************获取凭证科目数据（包含过账和未过账）*************************************/
		INSERT INTO	#AcBalanceTable
			 SELECT A.STypeId,
					A.ATypeId,
					0 AS FBeginBalance,
					0 AS FBeginBalanceFor,
					SUM(A.FDebitTotal) AS FDebit ,
					SUM(FDebitTotalFor) AS FDebitFor,
					SUM(A.FCreditTotal) AS FCredit,
					SUM(FCreditTotalFor) AS FCreditFor,
					A.Cid,
					0 AS FEndBalance ,
					0 AS FEndBalanceFor,
					0 AS FYtdDebit,
					0 AS FYtdDebitFor,
					0 AS FYtdCredit,
					0 AS FYtdCreditFor,
					A.FYear,
					A.FPeriod,
					C.Fdc
					FROM Ac_Voucher_Bill A
			 		JOIN Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1
			 		JOIN Ac_Account  C ON C.TypeId=A.ATypeId AND C.STypeId=@STypeId
			 WHERE A.FYear = @Fyear AND A.STypeId=@STypeId		
			 GROUP BY A.FYear,A.FPeriod,A.STypeId,A.ATypeId,A.Cid,C.Fdc 
	        
	        -----modify by dongzhan 2013.4.11     修复某个期间某科目未做凭证，而没有该期间数据的bug
			INSERT INTO	#AcBalanceTable
			SELECT  a.STypeId,
					a.ATypeId,
					0 AS FBeginBalance,
					0 AS FBeginBalanceFor,
					0 AS FDebit ,
					0 AS FDebitFor,
					0 AS FCredit,
					0 AS FCreditFor,
					a.Cid,
					0 AS FEndBalance ,
					0 AS FEndBalanceFor,
					0 AS FYtdDebit,
					0 AS FYtdDebitFor,
					0 AS FYtdCredit,
					0 AS FYtdCreditFor,
					a.FYear,
					a.FPeriod,
					C.Fdc
			 FROM dbo.Ac_Balance a 
			 LEFT JOIN #AcBalanceTable b ON a.STypeId=b.STypeId AND a.ATypeId=b.ATypeId AND a.Cid=b.Cid AND a.FYear=b.FYear AND a.FPeriod=b.FPeriod 
			 JOIN dbo.Ac_Account c ON c.TypeId=a.ATypeId AND c.StypeId=@STypeId
			 WHERE a.cid!=0 AND a.FYear=@Fyear AND a.STypeId=@StypeId  AND b.FPeriod IS NULL ORDER BY  a.ATypeId,a.FPeriod 
	  
	--/*********************************************************************************************************************/	
	--/*													按期间循环计算													 */
	--/* 参数	@MaxFPeriod：最大期间  	@MinFPeriod：初始期间		@FPeriodNum：期间循环参数，初始=@MinFPeriod																										 */
	--/*********************************************************************************************************************/				
			DECLARE @MaxFPeriod INT  
			DECLARE @MinFPeriod INT
			DECLARE @MaxFPeriodVocher INT  
			IF @iniFyear=@Fyear
				BEGIN
					SELECT @MaxFPeriod=MAX(FPeriod) FROM Ac_Period WHERE FYear=@Fyear
					--SELECT @MaxFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='FPeriod'
					SELECT @MinFPeriod=ISNULL(MIN(CONVERT(INT,FPeriod)),@MaxFPeriod)  FROM Ac_Balance WHERE STypeId=@STypeId AND FYear=@Fyear
				END
			ELSE 
				BEGIN
					SELECT @MinFPeriod=IsNULL(MIN(FPeriod),1) FROM #AcBalanceTable
					SELECT @MaxFPeriod=MAX(FPeriod) FROM dbo.Ac_Period
				END
			SELECT  @MaxFPeriodVocher=IsNULL(MAX(CONVERT(INT,FPeriod)),0) FROM #AcBalanceTable  
			IF @MaxFPeriodVocher>@MaxFPeriod SET @MaxFPeriod=@MaxFPeriodVocher
			 
			DECLARE @FPeriodNum INT SET  @FPeriodNum=@MinFPeriod
			WHILE @FPeriodNum<=@MaxFPeriod
			BEGIN
				/***********************************第一期单独计算*********************************/
				IF @FPeriodNum=@MinFPeriod
					BEGIN
						/******************计算期初、期初本年累计************/
						IF @iniFyear=@Fyear   --从期初取
							UPDATE	#AcBalanceTable
							SET		FBeginBalance=B.iniTotal,
									FBeginBalanceFor=B.iniTotalFor,
									FYtdDebit = B.FDebit,
									FYtdDebitFor = B.FDebitFor,
									FYtdCredit = B.FCredit,
									FYtdCreditFor = B.FCreditFor
							FROM #AcBalanceTable A
							JOIN Ac_IniAccount B ON B.FYear = @Fyear AND B.STypeId=@STypeId	AND A.ATypeId = B.ATypeId AND A.Cid=B.Cid	
						ELSE --从上年最后一期
							BEGIN
								--修复上一年ac_blance表中有数据，而要查询的年度没凭证，以至于临时表没科目的bug
								INSERT INTO #AcBalanceTable
								         (STypeId,
								          ATypeId,
								          FBeginBalance,
								          FBeginBalanceFor,
								          FDebit,
								          FDebitFor,
								          FCredit,
								          FCreditFor,
								          Cid,
								          FEndBalance,
								          FEndBalanceFor,
								          FYtdDebit,
								          FYtdDebitFor,
								          FYtdCredit,
								          FYtdCreditFor,
								          FYear,
								          FPeriod,
								          Fdc)
							   SELECT  a.STypeId,
										a.ATypeId,
										0 AS FBeginBalance,
										0 AS FBeginBalanceFor,
										0 AS FDebit ,
										0 AS FDebitFor,
										0 AS FCredit,
										0 AS FCreditFor,
										a.Cid,
										0 AS FEndBalance ,
										0 AS FEndBalanceFor,
										0 AS FYtdDebit,
										0 AS FYtdDebitFor,
										0 AS FYtdCredit,
										0 AS FYtdCreditFor,
										@Fyear,
										@MinFPeriod,
										C.Fdc
								 FROM dbo.Ac_Balance a 
								 LEFT JOIN #AcBalanceTable b ON a.STypeId=b.STypeId AND a.Cid=b.Cid AND a.ATypeId=b.Atypeid AND a.FYear=b.FYear-1 
								 JOIN dbo.Ac_Account c ON c.TypeId=a.ATypeId AND c.StypeId=@STypeId
								 WHERE a.cid!=0 AND a.FYear=@Fyear-1 AND a.STypeId=@StypeId  AND b.atypeid IS NULL AND a.FPeriod=@PreMaxFperiod
								 ORDER BY  a.ATypeId,a.FPeriod 
								
								UPDATE #AcBalanceTable
								SET		FBeginBalance=B.FEndBalance,
										FBeginBalanceFor=B.FEndBalanceFor,
										FYtdDebit = 0,
										FYtdDebitFor = 0,
										FYtdCredit = 0,
										FYtdCreditFor = 0
								FROM #AcBalanceTable A
								JOIN dbo.Ac_Balance B ON B.STypeId=@STypeId AND B.FYear=@Fyear-1 AND B.FPeriod=@PreMaxFperiod AND A.ATypeId = B.ATypeId AND A.Cid=B.Cid	
		
								--特殊情况，勾选了包含未过账凭证，余额表是2013年11月，我查询2014年1月，1月的期初是11月的期末+12月的未记账凭证
								IF(@IsShowNoAccount=1)
									BEGIN
										WITH T AS
										(
										SELECT A.STypeId,
										A.ATypeId,
										SUM(A.FDebitTotal) AS FDebit ,
										SUM(FDebitTotalFor) AS FDebitFor,
										SUM(A.FCreditTotal) AS FCredit,
										SUM(FCreditTotalFor) AS FCreditFor,
										A.Cid,
										C.Fdc
										FROM Ac_Voucher_Bill A
		 								JOIN Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1 
		 								JOIN Ac_Account  C ON C.TypeId=A.ATypeId AND C.STypeId=@STypeId
										WHERE A.FYear = @Fyear-1 AND A.STypeId=@STypeId AND A.FPeriod>=@PreMaxFperiod AND IfCheck='f'  	
										GROUP BY A.STypeId,A.ATypeId,A.Cid,C.Fdc
										)
										UPDATE A 
										SET  A.FBeginBalance+=(CASE WHEN t.fdc=1 THEN t.FDebit-t.FCredit ELSE t.FCredit-t.FDebit END),
											 A.FBeginBalanceFor+=(CASE WHEN t.fdc=1 THEN t.FDebitFor-t.FCreditFor ELSE t.FCreditFor-t.FDebitFor END)
										FROM #AcBalanceTable A
										JOIN T ON A.Atypeid=T.Atypeid AND A.cid=T.cid
									END		
									
									--特殊情况2，勾选了包含未过账凭证，余额表没值，我查询2014年1月，1月的期初是去年未记账凭证
								IF (@IsShowNoAccount=1)
									BEGIN
										 	WITH T AS
										(
										SELECT A.STypeId,
										A.ATypeId,
										SUM(A.FDebitTotal) AS FDebit ,
										SUM(FDebitTotalFor) AS FDebitFor,
										SUM(A.FCreditTotal) AS FCredit,
										SUM(FCreditTotalFor) AS FCreditFor,
										A.Cid,
										C.Fdc
										FROM Ac_Voucher_Bill A
		 								JOIN Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1 
		 								JOIN Ac_Account  C ON C.TypeId=A.ATypeId AND C.STypeId=@STypeId
										WHERE A.FYear = @Fyear-1 AND A.STypeId=@STypeId AND IfCheck='f'  	
										GROUP BY A.STypeId,A.ATypeId,A.Cid,C.Fdc
										)
										INSERT INTO #AcBalanceTable
										SELECT t.STypeId,
											   t.ATypeId,
											   CASE WHEN t.fdc=1 THEN t.FDebit-t.FCredit ELSE t.FCredit-t.FDebit END AS FBeginBalance,
												CASE WHEN t.fdc=1 THEN t.FDebitFor-t.FCreditFor ELSE t.FCreditFor-t.FDebitFor END AS FBeginBalanceFor,
												0 AS FDebit ,
												0 AS FDebitFor,
												0 AS FCredit,
												0 AS FCreditFor,
												t.Cid,
												CASE WHEN t.fdc=1 THEN t.FDebit-t.FCredit ELSE t.FCredit-t.FDebit END  AS FEndBalance ,
												CASE WHEN t.fdc=1 THEN t.FDebitFor-t.FCreditFor ELSE t.FCreditFor-t.FDebitFor END AS FEndBalanceFor,
												0 AS FYtdDebit,
												0 AS FYtdDebitFor,
												0 AS FYtdCredit,
												0 AS FYtdCreditFor,
												@Fyear,
												@MinFPeriod,
												t.Fdc
										FROM T t LEFT JOIN #AcBalanceTable a ON t.STypeId=a.stypeid AND t.ATypeId=a.atypeid AND t.cid=a.cid AND a.atypeid IS NULL
										WHERE t.ATypeId NOT IN (SELECT ATypeId FROM #AcBalanceTable)
									END		
							END
								
		
						/******************计算期末、当期本年累计************/
						UPDATE	#AcBalanceTable
						SET		FEndBalance = 
								CASE	WHEN Fdc=1	THEN	FDebit-FCredit+FBeginBalance
										WHEN Fdc=-1	THEN	FCredit-FDebit+FBeginBalance	 
								END,
								FEndBalanceFor = 
								CASE	WHEN Fdc=1	THEN	FDebitFor-FCreditFor+FBeginBalanceFor
										WHEN Fdc=-1	THEN	FCreditFor-FDebitFor+FBeginBalanceFor	 
								END,
								FYtdDebit = FDebit+FYtdDebit,
								FYtdDebitFor = FDebitFor+FYtdDebitFor,
								FYtdCredit =FCredit + FYtdCredit,
								FYtdCreditFor = FCreditFor + FYtdCreditFor
								
						/***********************合并期初科目************************/
						IF @iniFyear=@Fyear   --从期初取
							INSERT INTO	#AcBalanceTable
								 SELECT	A.STypeId,
										ATypeId,
										iniTotal AS FBeginBalance ,
										iniTotalFor AS FBeginBalanceFor,
										0 AS FDebit,
										0 AS FDebitFor,
										0 AS FCredit,
										0 AS FCreditFor,
										Cid,
										iniTotal AS FEndBalance,
										iniTotalFor AS FEndBalanceFor,
										FDebit AS FYtdDebit,
										FDebitFor AS FYtdDebitFor,
										FCredit AS FYtdCredit,
										FCreditFor AS FYtdCreditFor,
										@Fyear AS FYear,
										CONVERT(VARCHAR(10),@MinFPeriod) AS FPeriod,
										B.Fdc
								   FROM Ac_IniAccount A
								   JOIN (SELECT STypeID,TypeId,Fdc FROM Ac_Account WHERE StypeId=@STypeId ) B ON A.ATypeId=B.TypeId AND B.STypeID=@StypeId
								   WHERE NOT EXISTS(SELECT * FROM #AcBalanceTable WHERE ATypeId=A.ATypeId AND Cid=A.Cid AND STypeId=@STypeId AND FPeriod=A.FPeriod)
										 AND A.STypeId=@STypeId AND A.FYear=@Fyear
			             ELSE 
							INSERT INTO #AcBalanceTable
							SELECT A.STypeId,
								   A.ATypeId,
								   FBeginBalance,
								   FEndBalanceFor,
								   FDebit,
								   FDebitFor,
								   FCredit,
								   FCreditFor,
								   cid,
								   FEndBalance,
								   FEndBalanceFor,
								   0,
								   0,
								   0,
								   0,
								   @Fyear AS FYear,
								   CONVERT(VARCHAR(10),@MinFPeriod) AS FPeriod,
								   B.Fdc
							FROM dbo.Ac_Balance A
							JOIN (SELECT STypeID,TypeId,Fdc FROM Ac_Account WHERE StypeId=@STypeId ) B ON A.ATypeId=B.TypeId AND B.STypeID=@StypeId
							WHERE NOT  EXISTS  (SELECT * FROM #AcBalanceTable WHERE ATypeId=A.ATypeId AND Cid=A.Cid AND STypeId=@STypeId AND FPeriod=A.FPeriod)
										 AND A.STypeId=@STypeId AND A.FYear=@Fyear AND A.cid<>0
					END
				/***********************************非第一期进行累加计算*********************************
				** 期初=上期期末	本年累计=上期本年累计+本期发生	期末=期初+本期发生	
				** 本期科目=上一期科目+本期发生科目														
				****************************************************************************************/
				ELSE 
					/******************计算期初、本年累计********************/
					BEGIN
						 /*上期临时表*/
						 SELECT *  INTO #PreAcBalanceTempTable 
						 FROM #AcBalanceTable 
						 WHERE FPeriod=CONVERT(VARCHAR(10),@FPeriodNum-1) AND STypeId=@STypeId
					
						UPDATE	#AcBalanceTable
						SET		FBeginBalance=B.FEndBalance,
								FBeginBalanceFor=B.FEndBalanceFor,
								FYtdDebit = B.FYtdDebit + A.FDebit,
								FYtdDebitFor = B.FYtdDebitFor + A.FDebitFor,
								FYtdCredit = B.FYtdCredit + A.FCredit,
								FYtdCreditFor = B.FYtdCreditFor + A.FCreditFor
						FROM #AcBalanceTable A
						JOIN #PreAcBalanceTempTable B 
						ON   A.ATypeId = B.ATypeId AND A.Cid=B.Cid AND A.STypeId=B.STypeId
						WHERE  A.FPeriod = CONVERT(VARCHAR(10),@FPeriodNum)
						
						/*计算本期有的科目而上期没有的科目---期初=0 期末=本期发生 */
						/*此情况发生在期初没有科目或新增有科目					  */
						UPDATE	#AcBalanceTable 
						SET		FBeginBalance=0,
								FBeginBalanceFor=0,
								FYtdDebit=A.FDebit,
								FYtdDebitFor=A.FDebitFor,
								FYtdCredit=A.FCredit,
								FYtdCreditFor=A.FCreditFor
						FROM	#AcBalanceTable A
						WHERE   FPeriod = CONVERT(VARCHAR(10),@FPeriodNum)
						  AND	NOT EXISTS(SELECT * FROM #PreAcBalanceTempTable WHERE ATypeId=A.ATypeId AND Cid=A.Cid AND STypeId=@STypeId)
						
						/******************计算期末********************/
						UPDATE	#AcBalanceTable
						SET		FEndBalance = 
								(CASE	WHEN Fdc=1	THEN FDebit-FCredit+FBeginBalance
										WHEN Fdc=-1	THEN FCredit-FDebit+FBeginBalance
								END),
								FEndBalanceFor = 
								(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+FBeginBalanceFor
										WHEN Fdc=-1	THEN FCreditFor-FDebitFor+FBeginBalanceFor
								END)
						/***********************合并上期科目**********************************************/
						/* 上期科目本期没有发生额，直接复制到本期--本期期初=上期期末=本期期末 本期发生=0 */
						/*********************************************************************************/
						
						SELECT * INTO #CurAcBalanceTempTable 
								FROM  #AcBalanceTable 
								WHERE FPeriod = CONVERT(VARCHAR(10),@FPeriodNum)
						
						INSERT INTO	#AcBalanceTable 
							 SELECT	A.STypeId,
									A.ATypeId,
									A.FEndBalance,
									A.FEndBalanceFor,
									0,0,0,0,
									A.Cid,
									A.FEndBalance,
									A.FEndBalanceFor,
									A.FYtdDebit,
									A.FYtdDebitFor,
									A.FYtdCredit,
									A.FYtdCreditFor,       
									@Fyear,
									CONVERT(VARCHAR(10),@FPeriodNum),
									A.Fdc
							   FROM #PreAcBalanceTempTable A
							  WHERE NOT EXISTS(SELECT * FROM #CurAcBalanceTempTable WHERE ATypeId=A.ATypeId AND Cid=A.Cid AND StypeId=@StypeId)
							  		 	
					DROP TABLE #PreAcBalanceTempTable,#CurAcBalanceTempTable
					END
				/*循环下一期间*/
				SET @FPeriodNum=@FPeriodNum+1
			END /*循环结束*/
			
			
			ALTER TABLE #AcBalanceTable DROP COLUMN Fdc    /*Fdc不是AC_Balance默认字段 此处作为临时使用，故删除*/
			/************************************************************************************************/
			/*										计算综合本位币											*/
			/************************************************************************************************/		
			INSERT INTO #AcBalanceTable
				SELECT	STypeId,
						ATypeId,
						SUM(FBeginBalance),
						SUM(FBeginBalance),
						SUM(FDebit),
						SUM(FDebit),
						SUM(FCredit),
						SUM(FCredit),
						0,
						SUM(FEndBalance),
						SUM(FEndBalance),
						SUM(FYtdDebit),
						SUM(FYtdDebit),
						SUM(FYtdCredit),
						SUM(FYtdCredit),
						@Fyear,
						FPeriod
				  FROM	#AcBalanceTable
				  GROUP BY STypeId,FPeriod,ATypeId	

 SELECT  * FROM #AcBalanceTable ORDER BY AtypeId
 DROP TABLE #AcBalanceTable




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_AcBalanceSumQuery]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].[WEB_AcBalanceSumQuery]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：黄清	
	日期：2014年11月4日 16:20:45
	描述：科目余额汇总表查询
-------------------------------------------*/
CREATE PROCEDURE WEB_AcBalanceSumQuery
(
	@STypeId 			VARCHAR(MAX),	---分支机构ID
	@ATypeId			NVARCHAR(MAX),	---会计科目ID(可以多值，以,为分隔符 例：xxx,xxx,xx)   
	@chvOperatorID		VARCHAR(50),	--操作员ID     
	@Cid				INT,			---币别ID(-1:所有币别）
	--@Leveal				INT,		---科目级别(1-10) -1:所有级别     
	@FYear				INT,			---会计年度       
	@FPeriodStart		INT,			---起始期间
	@FPeriodEnd			INT,			---结束期间
	@IsShowNoAccount	INT,			---包含未记账凭证
	@IsShowFNull		INT,			---是否显示发生额为空的科目 1：是 0：否
	@IsBalanceNull		INT,			---是否显示期末余额为空的科目 1：是 0：否
	@IsShowFYNull		INT,			---是否显示本年没有发生额的科目 1：是 0：否
	@IsShowSubTotal		INT,			---是否显示小计
	@IsShowPL			INT				---是否包含损益结转数据
)
--@encode$--
AS 
SET NOCOUNT ON
--========================================临时表及赋值【BEGIN】=====================================
--BEGIN --测试
--	EXEC WEB_AcBalanceSumQuery '0000300002','','00001','1','2014','10','11','1','1','1'
--	PRINT 1
--END;


BEGIN --处理分支机构权限和查询条件
CREATE TABLE #STYPE (TYPEID VARCHAR(50))
IF @STypeId=''
	INSERT INTO #STYPE SELECT TypeId FROM F_GetMANDetailSType(@chvOperatorID)
ELSE
	INSERT INTO #STYPE
	SELECT TypeId FROM F_GetMANDetailSType(@chvOperatorID) F
	INNER JOIN (SELECT a FROM f_split(@STypeId,',')) S ON F.TypeId LIKE S.a+'%'
END

BEGIN --处理会计科目权限
	CREATE TABLE #account_l (TYPEID VARCHAR(50),stypeid VARCHAR(50))
	INSERT INTO #account_l(TYPEID,stypeid)
	SELECT Typeid,Stypeid FROM F_TreeAccount(@chvOperatorID,@STypeId)
	IF @ATypeId <>''
	BEGIN
		DELETE FROM #account_l 
		WHERE TYPEID NOT IN (SELECT TYPEID FROM #account_l L INNER JOIN (SELECT A FROM f_split(@ATypeId,',')) A ON L.TYPEID LIKE A.a+'%') 
	END
	
END


BEGIN --币种写入#AcCurrency临时表
CREATE TABLE #AcCurrency(CId INT,FullName VARCHAR(200))
IF(@Cid=-1)
	BEGIN
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT CId,FullName FROM Ac_Currency 
		UNION ALL
		SELECT 0,'综合本位币'
	END
ELSE IF @Cid=0
	BEGIN
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT 0,'综合本位币'
	END
ELSE
	BEGIN
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT CId,FullName FROM Ac_Currency  WHERE CId=@Cid
	END
END

BEGIN --写入科目数据#Account 
	DECLARE @SQL VARCHAR(MAX)=''
	CREATE TABLE #Account(Class VARCHAR(200),parid varchar(50),TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200),storingcode VARCHAR(200))

	SET @SQL='
	INSERT INTO #Account(Class,parid,TypeID,UserCode,FullName,storingcode)
	SELECT	DISTINCT 
			(SELECT FullName FROM Ac_Account P WHERE P.TypeId=A.ParId AND StypeId=''00000'') AS class,
			a.parid,
			A.TypeId AS typeid,
			a.UserCode,
			a.FullName,
			a.usercode AS storingcode
	FROM Ac_Account A  
	INNER JOIN #account_l L ON A.TYPEID=L.TYPEID
	INNER JOIN #AcCurrency C ON A.cid=c.cid or a.cid=0 OR c.cid=0'
	IF ISNULL(@ATypeId,'')<>''
		SET @SQL+='	INNER JOIN f_split('''+@ATypeId+''','','') F ON F.a=A.TypeId'
	SET @SQL+='
	WHERE	EXISTS(SELECT 1 FROM SType WHERE TypeId=A.StypeId)
			AND A.Leveal=2 '
	
	IF @IsShowSubTotal=1 AND @Cid<>-1
		BEGIN
			SET @SQL+='
			INSERT INTO #Account(Class,parid,TypeID,usercode,FullName,storingcode)
			SELECT	A.Class,
					''00000'' AS parid,
					a.parid,
					'''' AS usercode,
					A.Class+''小计'' FullName,
					MAX(A.storingcode)+1 storingcode
			FROM #Account A WHERE LEN(a.parid)=5
			GROUP BY A.Class,a.parID'
		END
	EXEC (@SQL)

END

BEGIN --处理开账和未开账的期间问题
	
	SELECT	S.TypeId,
			@FYear AS FYear,
			ISNULL(P.FPeriod,0) AS isok,
			CASE WHEN EXISTS(SELECT top 1 1 FROM Ac_Balance B WHERE B.STypeId=S.TYPEID AND B.FYear=@FYear) THEN 1
			ELSE 0 END AS fperiod
	INTO #speriod
	FROM #SType S
	LEFT JOIN Ac_AccountsPeroid_Stype P ON S.TypeId=P.Stypeid

	--没有开账的年度设为启用年度
	UPDATE #speriod SET FYear=(SELECT TOP 1 SubValue FROM sysdata WHERE SubName='fyear') WHERE FYear IS NULL

END
--select *from #speriod

BEGIN --余额数据表
	--临时表，不区分借贷
	CREATE TABLE #Ac_BalanceUnFdc   
	(
		 ATypeId		VARCHAR(50),				--科目
		 StypeId		VARCHAR(50),				--分支机构
		 Cid			INT,						--币种
		 FBeginBalance	 NUMERIC(24, 10)  DEFAULT 0,	--期初余额
		 FEndBalance	 NUMERIC(24, 10)  DEFAULT 0,	--期末余额
		 FDebitFor		 NUMERIC(24, 10)  DEFAULT 0,	--本期借方
		 FCreditFor		 NUMERIC(24, 10)  DEFAULT 0,	--本期贷方
		 FYtdDebitFor	 NUMERIC(24, 10)  DEFAULT 0,	--本年借方
		 FYtdCreditFor	 NUMERIC(24, 10)  DEFAULT 0		--本年贷方
	)
	BEGIN --写入期初数据
	DECLARE @INISQL VARCHAR(MAX)
	SET @INISQL='
		INSERT INTO #Ac_BalanceUnFdc
		(
			StypeId,
			ATypeId,
			Cid,
			FBeginBalance
		)
		SELECT	B.STypeId,
				B.ATypeId,
				B.Cid, 
				CASE WHEN B.fperiod='+CAST(@FPeriodStart AS VARCHAR)+' THEN FBeginBalanceFor 
					ELSE FEndBalanceFor END AS FBeginBalance 
		FROM Ac_Balance B
		INNER JOIN #STYPE S ON S.Typeid=B.stypeid
		INNER JOIN #account_l L ON B.ATYPEID=L.TYPEID AND B.STYPEID=L.STYPEID
		INNER JOIN #speriod SP ON B.STypeId=SP.TypeId AND sp.FYear=b.FYear AND SP.fperiod<>0 
		INNER JOIN #AcCurrency C ON C.CID=B.CID
		WHERE (B.FPeriod='+CAST(@FPeriodStart AS VARCHAR)+' AND b.FYear='+CAST(@FYear AS VARCHAR)+')		--查询开始期间 余额表存在
				OR (B.FPeriod<'+CAST(@FPeriodStart AS VARCHAR)+' 
					AND NOT EXISTS(SELECT 1 FROM Ac_Balance WHERE FPeriod='+CAST(@FPeriodStart AS VARCHAR)+' AND STypeId=B.STypeId AND FYear='+CAST(@FYear AS VARCHAR)+' )
					AND B.FPeriod = (SELECT MAX(CAST(FPeriod AS INT)) FROM Ac_Balance WHERE STypeId=B.STypeId AND FYear='+CAST(@FYear AS VARCHAR)+'  )
					) 
		--未开账查询期初
		UNION ALL 
		SELECT	INI.STypeId,
				INI.ATypeId,
				INI.Cid,'
		BEGIN --处理列
		IF @Cid=-1 OR @Cid=0
			SET @INISQL+=' iniTotal '
		ELSE
			SET @INISQL+=' iniTotalFor '
		END;
		SET @INISQL+='			
		FROM Ac_IniAccount INI
		INNER JOIN #STYPE S ON S.Typeid=INI.stypeid
		INNER JOIN #account_l L ON INI.ATYPEID=L.TYPEID AND INI.STYPEID=L.STYPEID
		INNER JOIN #AcCurrency C ON C.CID=INI.CID
		INNER JOIN #speriod SP ON SP.TypeId=INI.STypeId AND SP.FYear=INI.FYear  AND SP.isok=0 
		WHERE INI.fperiod<='+CAST(@FPeriodStart AS VARCHAR)
		IF @Cid<>-1 AND @Cid<>0
			SET @INISQL+=' AND INI.CID='+CAST(@Cid AS VARCHAR)
			
		IF @Cid=-1 OR @Cid=0
		BEGIN
			SET @INISQL+='
		UNION ALL 
		SELECT	INI.STypeId,
				INI.ATypeId,
				0 AS CID, 
				SUM(iniTotal) AS  iniTotal			
		FROM Ac_IniAccount INI
		INNER JOIN #STYPE S ON S.Typeid=INI.stypeid
		INNER JOIN #account_l L ON INI.ATYPEID=L.TYPEID AND INI.STYPEID=L.STYPEID
		INNER JOIN #speriod SP ON SP.TypeId=INI.STypeId AND SP.FYear=INI.FYear  AND SP.isok=0 
		WHERE INI.fperiod<='+CAST(@FPeriodStart AS VARCHAR)+'
		GROUP BY INI.STYPEID,INI.ATYPEID'		
		END		
	--PRINT (@INISQL)
	EXEC(@INISQL)
	END;

	BEGIN --写入期末数据
		DECLARE @endsql VARCHAR(MAX)
		SET @endsql='
		INSERT INTO #Ac_BalanceUnFdc
		(
			StypeId,
			ATypeId,
			Cid,
			FEndBalance
		)
		SELECT	B.STypeId,
				B.ATypeId,
				B.Cid,
				FEndBalanceFor 
		FROM Ac_Balance B
		INNER JOIN #STYPE S ON S.Typeid=B.stypeid
		INNER JOIN #account_l L ON B.ATYPEID=L.TYPEID AND B.STYPEID=L.STYPEID
		INNER JOIN #AcCurrency C ON C.CID=B.CID
		INNER JOIN #speriod SP ON B.STypeId=SP.TypeId AND B.FYear=sp.FYear AND SP.fperiod<>0
		WHERE	B.FPeriod='+CAST(@FPeriodEnd AS VARCHAR)+'
				OR (B.FPeriod<'+CAST(@FPeriodEnd AS VARCHAR)+' 
					AND NOT EXISTS(SELECT 1 FROM Ac_Balance WHERE FPeriod='+CAST(@FPeriodEnd AS VARCHAR)+' AND STypeId=B.STypeId AND FYear='+CAST(@FYear AS VARCHAR)+')
					AND B.FPeriod = (SELECT MAX(CAST(FPeriod AS INT)) FROM Ac_Balance WHERE STypeId=B.STypeId AND FYear='+CAST(@FYear AS VARCHAR)+' )
					)
		UNION ALL 
		SELECT	INI.STypeId,
				INI.ATypeId,
				INI.Cid, '
		BEGIN --处理列
		IF @Cid=-1 OR @Cid=0
			SET @endsql+=' iniTotalFor '
		ELSE
			SET @endsql+=' iniTotal '
		END
		SET @endsql+='
		FROM Ac_IniAccount INI
		INNER JOIN #STYPE S ON S.Typeid=INI.stypeid
		INNER JOIN #account_l L ON INI.ATYPEID=L.TYPEID AND INI.STYPEID=L.STYPEID
		INNER JOIN #AcCurrency C ON C.CID=INI.CID
		INNER JOIN #speriod SP ON SP.TypeId=INI.STypeId AND SP.FYear=INI.FYear AND SP.isok=0 
		WHERE INI.fperiod<='+CAST(@FPeriodEnd AS VARCHAR)
		IF @Cid=-1 OR @Cid=0
		BEGIN
			SET @endsql+='
		UNION ALL 
		SELECT	INI.STypeId,
				INI.ATypeId,
				0 AS CID, 
				SUM(iniTotal) AS  iniTotal			
		FROM Ac_IniAccount INI
		INNER JOIN #STYPE S ON S.Typeid=INI.stypeid
		INNER JOIN #account_l L ON INI.ATYPEID=L.TYPEID AND INI.STYPEID=L.STYPEID
		INNER JOIN #speriod SP ON SP.TypeId=INI.STypeId AND SP.FYear=INI.FYear  AND SP.isok=0 
		WHERE INI.fperiod<='+CAST(@FPeriodEnd AS VARCHAR)+'
		GROUP BY INI.STYPEID,INI.ATYPEID'		
		END	
	--PRINT (@endsql)
	EXEC(@endsql)
	
	END;
	
	BEGIN --写入本期发生
		INSERT INTO #Ac_BalanceUnFdc(StypeId,ATypeId,Cid,FDebitFor,FCreditFor)
		SELECT	B.stypeid,
				b.ATypeId,
				b.Cid,
				SUM(FDebitFor), --借
				SUM(FCreditFor) --贷
		FROM Ac_Balance B
		INNER JOIN #AcCurrency C ON B.Cid=C.CId
		INNER JOIN #STYPE S ON B.STypeId=S.TypeId
		INNER JOIN #account_l L ON B.ATYPEID=L.TYPEID AND B.STYPEID=L.STYPEID
		WHERE	FPeriod>=@FPeriodStart 
				AND FPeriod<=@FPeriodEnd
				AND B.FYear=@FYear
		GROUP BY B.STypeId,ATypeId,B.Cid		
	END;
	
	BEGIN --写入本年发生
		INSERT INTO #Ac_BalanceUnFdc(StypeId,ATypeId,Cid,FYtdDebitFor,FYtdCreditFor)
		SELECT	B.stypeid,
				b.ATypeId,
				b.Cid,
				SUM(FDebitFor), --借
				SUM(FCreditFor) --贷
		FROM Ac_Balance B
		INNER JOIN #AcCurrency C ON B.Cid=C.CId
		INNER JOIN #STYPE S ON B.STypeId=S.TypeId
		INNER JOIN #account_l L ON B.ATYPEID=L.TYPEID AND B.STYPEID=L.STYPEID
		WHERE	FYear=@FYear
		GROUP BY B.STypeId,ATypeId,B.Cid
		UNION ALL 
		SELECT	INI.STypeId,
				INI.ATypeId,
				INI.Cid,
				CASE WHEN @Cid=-1 OR @Cid=0 THEN INI.FDebit
					ELSE INI.FDebitFor END AS FYtdDebit,
				CASE WHEN @Cid=-1 OR @Cid=0 THEN INI.FCredit
					ELSE INI.FCreditFor END AS FYtdCredit
		FROM Ac_IniAccount INI
		INNER JOIN #STYPE S ON S.Typeid=INI.stypeid
		INNER JOIN #account_l L ON INI.ATYPEID=L.TYPEID AND INI.STYPEID=L.STYPEID
		INNER JOIN #AcCurrency C ON C.CID=INI.CID
		INNER JOIN #speriod SP ON SP.TypeId=INI.STypeId AND SP.FYear=INI.FYear AND SP.isok=0 
		WHERE INI.FYear=@FYear
		
		--所有币种和综合本位币时，多写一条综合本位币数据
		IF @Cid=-1 OR @Cid=0
		BEGIN
			INSERT INTO #Ac_BalanceUnFdc(StypeId,ATypeId,Cid,FYtdDebitFor,FYtdCreditFor)
			SELECT	INI.STypeId,
					INI.ATypeId,
					0,
					SUM(INI.FDebit),
					SUM(INI.FCredit)
			FROM Ac_IniAccount INI
			INNER JOIN #STYPE S ON S.Typeid=INI.stypeid
			INNER JOIN #account_l L ON INI.ATYPEID=L.TYPEID AND INI.STYPEID=L.STYPEID
			INNER JOIN #speriod SP ON SP.TypeId=INI.STypeId AND SP.FYear=INI.FYear AND SP.isok=0 
			WHERE INI.FYear=@FYear
			GROUP BY INI.STypeId,ATypeId
		END
	END
	
	--余额表数据，区分借贷
	CREATE TABLE #Ac_Balance   --返回数据表
	(
		 ATypeId			VARCHAR(50),				--科目
		 STYPEID			VARCHAR(50),
		 Cid				INT,						--币种
		 FDebitBeginFor		 NUMERIC(24, 10)  DEFAULT 0,	--期初借方
		 FCreditBeginFor	 NUMERIC(24, 10)  DEFAULT 0,	--期初借方
		 FDebitEndFor		 NUMERIC(24, 10)  DEFAULT 0,	--期末借方
		 FCreditEndFor		 NUMERIC(24, 10)  DEFAULT 0,	--期末贷方
		 FDebitFor			 NUMERIC(24, 10)  DEFAULT 0,	--本期借方
		 FCreditFor			 NUMERIC(24, 10)  DEFAULT 0,	--本期贷方
		 FYtdDebitFor		 NUMERIC(24, 10)  DEFAULT 0,	--本年借方
		 FYtdCreditFor		 NUMERIC(24, 10)  DEFAULT 0		--本年贷方

	)
	BEGIN --整理数据
		INSERT INTO #Ac_Balance
		(
			ATypeId,
			STYPEID,
			Cid,
			FDebitBeginFor,
			FCreditBeginFor,
			FDebitEndFor,
			FCreditEndFor,
			FDebitFor,
			FCreditFor,
			FYtdDebitFor,
			FYtdCreditFor
		)
		SELECT	B.ATypeId,
				B.StypeId,
				B.Cid,
				CASE WHEN MAX(Fdc)=1 THEN SUM(FBeginBalance)
					ELSE 0 END AS FDebitBeginFor,
				CASE WHEN MAX(Fdc)=-1 THEN SUM(FBeginBalance)
					ELSE 0 END AS FCreditBeginFor,
				CASE WHEN MAX(Fdc)=1 THEN SUM(FEndBalance)
					ELSE 0 END AS FDebitEndFor,
				CASE WHEN MAX(Fdc)=-1 THEN SUM(FEndBalance)
					ELSE 0 END AS FCreditEndFor,
				SUM(FDebitFor) AS FDebitFor,
				SUM(FCreditFor) AS FCreditFor,
				SUM(FYtdDebitFor) AS FYtdDebitFor,
				SUM(FYtdCreditFor) AS FYtdCreditFor
		FROM #Ac_BalanceUnFdc B
		INNER JOIN Ac_Account A ON B.ATypeId=A.TypeId AND B.StypeId=A.StypeId
		GROUP BY ATypeId,B.StypeId,B.Cid

	END;
	
END;

BEGIN --处理条件
	--凭证表临时表
	CREATE TABLE #VoucherBill
	(
		ATypeId		VARCHAR(50),				--科目ID
		STypeId		VARCHAR(50),				--分支机构
		Cid			INT,						--币种
		FYear		INT,						--年度
		FPeriod		INT,						--期间
		FDebitFor	 NUMERIC(24, 10)  DEFAULT 0,	--借方
		FCreditFor	 NUMERIC(24, 10)  DEFAULT 0		--贷方
	)
	DECLARE @VSQL VARCHAR(MAX)
	IF @IsShowPL=1 --勾选不包含结转数据时，处理已记账凭证
	BEGIN
		SET @VSQL='
		INSERT INTO #VoucherBill(ATypeId,STypeId,Cid,FYear,FPeriod,FDebitFor,FCreditFor)
		SELECT	B.ATypeId,
				B.Stypeid,
				B.cid Cid,
				B.FYear,
				B.FPeriod,
				SUM(B.FDebitTotalFor) FDebitFor,
				SUM(B.FCreditTotalFor) FCreditFor
		FROM Ac_Voucher V 
		INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.IfCheck=''T'' AND V.FChecked<>-1
		INNER JOIN #account_l L ON B.ATYPEID=L.TYPEID AND B.STYPEID=L.STYPEID 
		INNER JOIN #AcCurrency C ON B.Cid=C.CId 
		INNER JOIN #STYPE S ON S.TYPEID=V.STypeId 
		WHERE	B.FYear='+CAST(@FYear AS VARCHAR)+'
				AND B.FPeriod>='+CAST(@FPeriodStart AS VARCHAR)+'
				AND B.FPeriod<='+CAST(@FPeriodEnd AS VARCHAR)+'
				AND V.VoucherType=2
				GROUP BY B.ATypeId,B.Stypeid,B.CID,B.FYear,B.FPeriod'+CHAR(13)
		--PRINT (@VSQL)
		EXEC (@VSQL)
		IF @Cid=-1 OR @Cid=0  --写入综合本位币数据
		BEGIN
			SET @VSQL+='
			UNION ALL
			SELECT	B.ATypeId,
				B.Stypeid,
				0 Cid,
				B.FYear,
				B.FPeriod,
				SUM(B.FDebitTotal) FDebitFor,
				SUM(B.FCreditTotal) FCreditFor
		FROM Ac_Voucher V 
		INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.IfCheck=''T'' AND V.FChecked<>-1
		INNER JOIN #account_l L ON B.ATYPEID=L.TYPEID AND B.STYPEID=L.STYPEID 
		INNER JOIN #STYPE S ON S.TYPEID=V.STypeId 
		WHERE	B.FYear='+CAST(@FYear AS VARCHAR)+'
				AND B.FPeriod>='+CAST(@FPeriodStart AS VARCHAR)+'
				AND B.FPeriod<='+CAST(@FPeriodEnd AS VARCHAR)+'
				AND V.VoucherType=2
				GROUP BY B.ATypeId,B.Stypeid,B.CID,B.FYear,B.FPeriod'+CHAR(13)
		END
		--有结转损益数据
		IF EXISTS(SELECT TOP 1 1 FROM #VoucherBill)
		BEGIN
			--将没有在#Ac_Balance内的科目写入
			INSERT INTO #Ac_Balance(STYPEID,ATypeId,Cid)
			SELECT STypeId,ATypeId,Cid FROM #VoucherBill V 
			WHERE ATypeId NOT IN (SELECT ATypeId FROM #Ac_Balance B WHERE B.STYPEID=V.STypeId AND B.Cid=V.Cid)
			
			--期初
			UPDATE #Ac_Balance
			SET FDebitBeginFor-=T.FDebitFor,
				FCreditBeginFor-=T.FCreditFor
			FROM #Ac_Balance B
			INNER JOIN (SELECT	ATypeId,STypeId,Cid,SUM(FDebitFor) AS FDebitFor,SUM(FCreditFor) AS FCreditFor 
						FROM  #VoucherBill 
						WHERE ((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<@FPeriodStart)) 
						GROUP BY STypeId,ATypeId,Cid ) T ON T.ATypeId=B.ATypeId AND T.Cid=B.Cid AND T.STypeId=B.STYPEID
			--期末
			UPDATE #Ac_Balance
			SET FDebitEndFor-=T.FDebitFor,
				FCreditEndFor-=T.FCreditFor
			FROM #Ac_Balance B
			INNER JOIN (SELECT STypeId,ATypeId,Cid,SUM(FDebitFor) AS FDebitFor,SUM(FCreditFor) AS FCreditFor 
						FROM  #VoucherBill 
						WHERE ((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<=@FPeriodEnd)) 
						GROUP BY STypeId,ATypeId,Cid ) T ON T.ATypeId=B.ATypeId AND T.Cid=B.Cid AND B.STYPEID=T.STypeId

			--本年
			UPDATE #Ac_Balance
			SET FYtdDebitFor-=T.FDebitFor,
				FYtdCreditFor-=T.FCreditFor
			FROM #Ac_Balance B
			INNER JOIN (SELECT STypeId,ATypeId,Cid,ISNULL(SUM(FDebitFor),0) AS FDebitFor,ISNULL(SUM(FCreditFor),0) AS FCreditFor 
						FROM  #VoucherBill 
						WHERE ((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<=@FPeriodEnd)) 
						GROUP BY STypeId,ATypeId,Cid ) T ON T.ATypeId=B.ATypeId AND T.Cid=B.Cid AND T.STypeId=B.STYPEID

			--本期
			UPDATE #Ac_Balance
			SET FDebitFor-=ISNULL(T1.FDebitFor,0),
				FCreditFor-=ISNULL(T1.FCreditFor,0)
			FROM #Ac_Balance B
			LEFT JOIN (SELECT	STypeId,ATypeId,Cid,ISNULL(SUM(FDebitFor),0) AS FDebitFor,ISNULL(SUM(FCreditFor),0) AS FCreditFor 
						FROM  #VoucherBill 
						WHERE ((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<=@FPeriodEnd AND FPeriod>=@FPeriodStart)) 
						GROUP BY ATypeId,STypeId,Cid ) T1 ON T1.ATypeId=B.ATypeId AND T1.Cid=B.Cid AND T1.STypeId=B.STYPEID
		END
	END

	--清除已记账的凭证数据
	DELETE FROM #VoucherBill

	IF @IsShowNoAccount=1 --包含未记账凭证，处理未记账凭证
	BEGIN
		DECLARE @fsql VARCHAR(MAX)
		SET @fsql='
		INSERT INTO #VoucherBill(STypeId,ATypeId,Cid,FYear,FPeriod,FDebitFor,FCreditFor)
		SELECT	B.STypeId,
				B.ATypeId,
				b.Cid,
				B.FYear,
				B.FPeriod,
				SUM(B.FDebitTotalFor) FDebitFor,
				SUM(B.FCreditTotalFor) FCreditFor
		FROM Ac_Voucher V 
		INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.IfCheck=''F'' AND V.FChecked<>-1
		INNER JOIN #account_l L ON B.ATYPEID=L.TYPEID AND B.STYPEID=L.STYPEID 
		INNER JOIN #AcCurrency C ON B.Cid=C.CId 
		INNER JOIN #STYPE S ON S.TYPEID=V.STypeId 
		WHERE B.FYear='+CAST(@FYear AS VARCHAR)
		IF @IsShowPL =1
			SET @fsql+=' AND V.BillNumberId NOT IN( SELECT BillNumberId FROM Ac_Voucher WHERE VoucherType=2 AND FYear='+CAST(@Fyear AS VARCHAR(4))+'
				AND FPeriod>='+CAST(@FPeriodStart AS VARCHAR) +'
				AND FPeriod<='+CAST(@FPeriodEnd AS VARCHAR) +')'
		SET @fsql+='
		GROUP BY B.STypeId,B.ATypeId,b.Cid,B.FYear,B.FPeriod '
		IF @Cid=-1 OR @Cid=0  --写入综合本位币数据
		BEGIN
			SET @fsql+='
			UNION ALL
			SELECT	b.stypeid,
					B.ATypeId,
					0 Cid,
					B.FYear,
					B.FPeriod,
					SUM(B.FDebitTotal) FDebitFor,
					SUM(B.FCreditTotal) FCreditFor
			FROM Ac_Voucher V 
			INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.IfCheck=''F'' AND V.FChecked<>-1
			INNER JOIN #account_l L ON B.ATYPEID=L.TYPEID AND B.STYPEID=L.STYPEID
			INNER JOIN #STYPE S ON S.TYPEID=V.STypeId 
			WHERE B.FYear='+CAST(@FYear AS VARCHAR)
			IF @IsShowPL =1
				SET @fsql+=' AND V.BillNumberId NOT IN( SELECT BillNumberId FROM Ac_Voucher WHERE VoucherType=2 AND FYear='+CAST(@Fyear AS VARCHAR(4))+'
					AND FPeriod>='+CAST(@FPeriodStart AS VARCHAR) +'
					AND FPeriod<='+CAST(@FPeriodEnd AS VARCHAR) +')'
			SET @fsql+='
			GROUP BY B.STypeId,B.ATypeId,b.Cid,B.FYear,B.FPeriod '
			
		END
		
		--PRINT (@fsql)
		EXEC (@fsql)	
		
		--将没有在#Ac_Balance内的科目写入
		INSERT INTO #Ac_Balance(STYPEID,ATypeId,Cid)
		SELECT STypeId,ATypeId,Cid FROM #VoucherBill V 
		WHERE ATypeId NOT IN (SELECT ATypeId FROM #Ac_Balance B WHERE B.STYPEID=V.STypeId AND B.Cid=V.Cid)
		
		IF EXISTS(SELECT TOP 1 1 FROM #VoucherBill) --存在未记账数据,更新
		BEGIN	
			--期初
			UPDATE #Ac_Balance
			SET FDebitBeginFor+=T.FDebitFor,
				FCreditBeginFor+=T.FCreditFor
			FROM #Ac_Balance B
			INNER JOIN (SELECT STypeId,ATypeId,Cid,SUM(FDebitFor) AS FDebitFor,SUM(FCreditFor) AS FCreditFor 
						FROM  #VoucherBill 
						WHERE ((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<@FPeriodStart)) 
						GROUP BY STypeId,ATypeId,Cid ) T ON T.ATypeId=B.ATypeId AND T.Cid=B.Cid AND B.STYPEID=T.STypeId
						
			--期末
			UPDATE #Ac_Balance
			SET FDebitEndFor+=T.FDebitFor,
				FCreditEndFor+=T.FCreditFor
			FROM #Ac_Balance B
			INNER JOIN (SELECT STypeId,ATypeId,Cid,SUM(FDebitFor) AS FDebitFor,SUM(FCreditFor) AS FCreditFor 
						FROM  #VoucherBill 
						WHERE ((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<=@FPeriodEnd)) 
						GROUP BY STypeId,ATypeId,Cid ) T ON T.ATypeId=B.ATypeId AND T.Cid=B.Cid  AND B.STYPEID=T.STypeId
				
			--本年
			UPDATE #Ac_Balance
			SET FYtdDebitFor+=T.FDebitFor,
				FYtdCreditFor+=T.FCreditFor
			FROM #Ac_Balance B
			INNER JOIN (SELECT STypeId,ATypeId,Cid,ISNULL(SUM(FDebitFor),0) AS FDebitFor,ISNULL(SUM(FCreditFor),0) AS FCreditFor 
						FROM  #VoucherBill 
						WHERE ((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<=@FPeriodEnd)) 
						GROUP BY STypeId,ATypeId,Cid ) T ON T.ATypeId=B.ATypeId AND B.STYPEID=T.STypeId AND T.Cid=B.Cid 
									
			--本期
			UPDATE #Ac_Balance
			SET FDebitFor+=ISNULL(T1.FDebitFor,0),
				FCreditFor+=ISNULL(T1.FCreditFor,0)
			FROM #Ac_Balance B
			LEFT JOIN (SELECT STypeId,ATypeId,Cid,ISNULL(SUM(FDebitFor),0) AS FDebitFor,ISNULL(SUM(FCreditFor),0) AS FCreditFor 
						FROM  #VoucherBill 
						WHERE ((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<=@FPeriodEnd AND FPeriod>=@FPeriodStart)) 
						GROUP BY STypeId,ATypeId,Cid ) T1 ON T1.ATypeId=B.ATypeId AND B.STYPEID=T1.STypeId AND T1.Cid=B.Cid 
		END
	END
END;

BEGIN --最后数据整理
	
	SELECT	A.Class,
			A.TypeID,
			A.UserCode,
			A.storingcode,
			A.FullName,
			b.CId,
			C.FullName CidName,
			ISNULL(SUM(B.FDebitBeginFor),0) FBeginBalanceDebitFor,
			ISNULL(SUM(B.FCreditBeginFor),0) FBeginBalanceCreditFor,
			ISNULL(SUM(B.FDebitFor),0) FDebitFor,
			ISNULL(SUM(B.FCreditFor),0) FCreditFor,
			ISNULL(SUM(B.FYtdDebitFor),0) FYtdDebitFor,
			ISNULL(SUM(B.FYtdCreditFor),0) FYtdCreditFor,
			ISNULL(SUM(B.FDebitEndFor),0) FEndBalanceDebitFor,
			ISNULL(SUM(B.FCreditEndFor),0) FEndBalanceCreditFor
	INTO #UnfdcRESULT
	FROM #Account A
	LEFT JOIN #Ac_Balance B ON B.ATypeId LIKE A.TypeID+'%'
	LEFT JOIN #AcCurrency C ON C.CId=B.Cid
	WHERE A.TypeID IN (SELECT TYPEID FROM #account_l)
	GROUP BY	A.Class,
				A.TypeID,
				A.UserCode,
				A.storingcode,
				A.FullName,
				b.CId,
				C.FullName
	ORDER BY A.storingcode	
	
	--整理期初，期末借贷方向
	SELECT	R.Class,
			R.TypeID,
			R.UserCode,
			R.FullName,
			R.CId,
			R.CidName,
			CASE WHEN A.Leveal=1 THEN  FBeginBalanceDebitFor
				WHEN A.Fdc=1 THEN FBeginBalanceDebitFor-FBeginBalanceCreditFor 
				ELSE 0 END AS FBeginBalanceDebitFor,
			CASE WHEN A.Leveal=1 THEN  FBeginBalanceCreditFor
				WHEN A.Fdc=-1 THEN FBeginBalanceCreditFor-FBeginBalanceDebitFor
				ELSE 0 END AS FBeginBalanceCreditFor,
			FDebitFor,
			FCreditFor,
			FYtdDebitFor,
			FYtdCreditFor,
			CASE WHEN A.Fdc=1 THEN FEndBalanceDebitFor-FEndBalanceCreditFor
				ELSE 0 END AS FEndBalanceDebitFor,
			CASE WHEN A.Fdc=-1 THEN FEndBalanceCreditFor-FEndBalanceDebitFor
				ELSE 0 END AS FEndBalanceCreditFor
	INTO #Result
	FROM #UnfdcRESULT R
	LEFT JOIN Ac_Account A ON StypeId='00000' AND Leveal<=2 AND R.TypeID=A.TypeId
	WHERE	((@IsShowFNull=0 AND (R.FDebitFor!=0 OR R.FCreditFor!=0)) OR @IsShowFNull=1)
			AND ((@IsBalanceNull=0 AND (R.FEndBalanceDebitFor!=0 OR R.FEndBalanceCreditFor!=0)) OR @IsBalanceNull=1)
			AND ((@IsShowFYNull=0 AND (R.FYtdDebitFor!=0 OR R.FYtdCreditFor!=0)) OR @IsShowFYNull=1)
	
	IF @IsShowSubTotal=1 AND @Cid<>-1
	BEGIN
		--小计调整	
		UPDATE #Result
		SET FBeginBalanceCreditFor=R.FBC,
			FBeginBalanceDebitFor=R.FBD,
			FEndBalanceCreditFor=R.FEC,
			FEndBalanceDebitFor=R.FED
		FROM (SELECT	R2.TypeID,
						R2.CId,
						SUM(R1.FBeginBalanceDebitFor) FBD,
						SUM(R1.FBeginBalanceCreditFor) FBC, 
						SUM(R1.FEndBalanceCreditFor) FEC,
						SUM(R1.FEndBalanceDebitFor) FED 
			FROM #Result R1 
			INNER JOIN #Result R2 ON R1.TypeID LIKE R2.TypeID+'%' AND R1.TypeID<>R2.TypeID 
			WHERE LEN(R1.TypeID)>5  GROUP BY R2.TypeID,R2.CId) R WHERE R.TypeID=#Result.TypeID AND R.CId=#Result.CId
	END
	SELECT *FROM #Result
END;

DROP TABLE #speriod

DROP TABLE #AcCurrency,#Account,#Ac_Balance,#STYPE


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









IF EXISTS(select * from dbo.sysobjects where id=object_id(N'Web_AcBankLine') and OBJECTPROPERTY(id,N'isProcedure')=1)
	DROP PROC dbo.Web_AcBankLine
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
功能说明：查询银行账户
作 者： 董湛
创建日期： 2012-04-16
返回结果： 
*/
CREATE PROCEDURE Web_AcBankLine
(
	@Deleted		INT=0,				--是否删除
	@OpertiorId		VARCHAR(50)			--操作人
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @sql [varchar](5000)
SET @sql='SELECT 
				item.nId, 
				item.UserCode, 
				item.FullName,
				item.CreateBank, 
				item.BankType, 
				item.Comment,
				item.Deleted,
				item.IsBank,
				item.Sysrow,
				IsModify,
				dbo.Fn_GetIsUse_Items(item.nId,2) isuse 
		 FROM Ac_Items item'+CHAR(13)
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeID = @OpertiorId AND MangerATypeID='-99999')
		SET @sql+= '	INNER JOIN AType_L a ON a.ETypeID = '''+@OpertiorId+''' AND a.Flag = ''1'' AND a.TypeID = item.nId '+CHAR(13)
SET @sql+='	WHERE  TypeName=''B'''+CHAR(13)
IF @Deleted=0
	SET @sql+=' AND item.deleted=0'+CHAR(13)
SET @sql+=' ORDER BY item.UserCode'
EXEC (@sql)

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_AcComparePeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].WEB_AcComparePeriod
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/15
	Description	: 查询单币别总分类账
*/

CREATE PROCEDURE WEB_AcComparePeriod
(
   @Fyear			VARCHAR(5),
   @STypeId 		VARCHAR(50),   ---分支机构ID
   @ATypeId			VARCHAR(50),  ---会计科目ID      
   @Cid				INT,		   ---币别ID            
   @IsPost			BIT		   ---是否显示未过账凭证 1：是 0：否
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	--取查询期间
	DECLARE @FPeriodStart INT,@FPeriodEnd INT 	
	SELECT @FPeriodStart=MIN(FPeriod),@FPeriodEnd=MAX(FPeriod) FROM dbo.Ac_Period	  
	---------------------------------要查询科目的子科目
	CREATE TABLE #temp1
	(
		STYPEID 		VARCHAR(50),	----分支机构ID
		FATHERID        VARCHAR(50),    ----查询的科目ID
		SONID			VARCHAR(50),	----查询的科目子节点的ID
	)

	INSERT INTO #temp1
	SELECT STYPEID,
		   @ATypeId,
		   TYPEID
	FROM dbo.Ac_Account 
	WHERE STYPEID=@STypeId AND TYPEID LIKE @ATypeId+'%' AND SONNUM=0 --AND DELETED=0  
	ORDER BY TypeId   
	 
	-------------------------------要查询的科目的凭证统计成每期的借和贷------------------------------------------------------------
	SELECT c.FATHERID AS typeid,
		   a.fPeriod,                                          
		   ISNULL(SUM(ISNULL(b.FDEBITTOTALFOR,0)),0) AS BORROW,
		   ISNULL(SUM(ISNULL(b.FCREDITTOTALFOR,0)),0) AS LEND,
		   b.cid 
	INTO #temp2 
	FROM Ac_Voucher a 
	JOIN Ac_Voucher_Bill b ON a.BillNumberId=b.BillNumberId  
	JOIN #temp1 c ON b.STypeId=c.STYPEID AND b.ATypeId=c.SONID 
	WHERE a.FYear=@FYear AND 
		  a.FPERIOD>=@FPeriodStart AND 
		  a.FPERIOD<=@FPeriodEnd AND 
		  a. FChecked <> -1 AND 
		  ((@IsPost=0 AND IfCheck='t') OR @IsPost=1) 
	GROUP BY c.FATHERID,a.FPeriod,b.Cid
	ORDER BY Cid,a.FPeriod
	
	--综合本位币
	INSERT INTO #temp2
	SELECT c.FATHERID AS typeid,
		   a.fPeriod,                                          
		   ISNULL(SUM(ISNULL(b.FDEBITTOTAL,0)),0) AS BORROW,
		   ISNULL(SUM(ISNULL(b.FCREDITTOTAL,0)),0) AS LEND,
		   0
	FROM Ac_Voucher a 
	JOIN Ac_Voucher_Bill b ON a.BillNumberId=b.BillNumberId  
	JOIN #temp1 c ON b.STypeId=c.STYPEID AND b.ATypeId=c.SONID 
	WHERE a.FYear=@FYear AND 
		  a.FPERIOD>=@FPeriodStart AND 
		  a.FPERIOD<=@FPeriodEnd AND 
		  a. FChecked <> -1 AND 
		  ((@IsPost=0 AND IfCheck='t') OR @IsPost=1) 
	GROUP BY c.FATHERID,a.FPeriod 
	-----------------------------------------------------------------------------------------------------------------------------------
	----期间表
	CREATE TABLE #temp3
	(
		Fperiod  INT
	)
    WHILE @FPeriodStart<=@FPeriodEnd
		BEGIN
			INSERT INTO #temp3 (Fperiod)
			SELECT @FPeriodStart
			
			SET @FPeriodStart=@FPeriodStart+1
		END
		
	----结果表
    CREATE TABLE #temp4
    (
		cid INT,
		fperiod INT,
		borrow  NUMERIC(24, 10) ,
		lend    NUMERIC(24, 10) 
    )
	INSERT INTO #temp4 (cid, fperiod)
	SELECT c.cid,f.fperiod 
	FROM (SELECT cid FROM dbo.Ac_Currency
	      UNION ALL 
	      SELECT 0 AS cid) c,#temp3 f
	ORDER BY cid,Fperiod
	
	--各币别更新
	UPDATE t SET t.borrow=ISNULL(d.borrow,0),t.lend=ISNULL(d.lend,0)  
	FROM #temp4 t LEFT JOIN #temp2 d ON t.cid=d.Cid AND t.fperiod=d.FPeriod  
	
	CREATE TABLE #temp
	(
		[期间]			NVARCHAR(10),
		[借方金额]		 NUMERIC(24, 10) ,
		[贷方金额]		 NUMERIC(24, 10) 
	)
	DECLARE @SQL VARCHAR(MAX) 
	
	IF @Cid=0 --所有币别
		BEGIN
			  INSERT INTO #temp 
			  SELECT CONVERT(NVARCHAR(5),fperiod)+'期',borrow,lend FROM #temp4 WHERE cid=0
			  
			  SELECT @SQL = ISNULL(@SQL + '],[' , '') + [期间] FROM #temp 
			  SET @SQL = '[' + @SQL + ']' 
			   
			  --给#temp4添加列
			  ALTER TABLE #temp4 ADD [期间] NVARCHAR(10)
			  UPDATE #temp4 SET [期间]=CONVERT(NVARCHAR(5),fperiod)+'期'
			  
			  --遍历币别
			  DECLARE @ExeSQL VARCHAR(max)='',@CidName VARCHAR(200),@CidID INT,@CidCount INT,@index INT=1 
			  
			  SELECT cid,FullName,ROW_NUMBER() OVER (ORDER BY CId) AS ordercol 
			  INTO #tempcid 
			  FROM dbo.Ac_Currency
			  
			  SELECT @CidCount=MAX(ordercol) FROM #tempcid 
			  
			  WHILE @index<=@CidCount
				BEGIN
					--获取币别名称
					SELECT @CidName=FullName,@CidID=cid FROM #tempcid WHERE ordercol=@index
					IF @index=1
						BEGIN
							SET @ExeSQL='select '''+@CidName+'借方金额'' as ''项目'','+CONVERT(VARCHAR(3),@CidID)+' as cid,'+@SQL+' 
										 FROM (select borrow,[期间] from  #temp4 where cid='+CONVERT(VARCHAR(3),@CidID)+') a PIVOT (MAX(borrow) for [期间] in ('+ @SQL + ')) b 
										 UNION ALL 
										 select '''+@CidName+'贷方金额'' as ''项目'','+CONVERT(VARCHAR(3),@CidID)+' as cid,'+@SQL+' 
										 FROM (select lend,[期间] from  #temp4 where cid='+CONVERT(VARCHAR(3),@CidID)+') a PIVOT (MAX(lend) for [期间] in ('+ @SQL + ')) b '
						END
					ELSE
						BEGIN
							SET @ExeSQL=@ExeSQL+'UNION ALL  
										 select '''+@CidName+'借方金额'' as ''项目'','+CONVERT(VARCHAR(3),@CidID)+' as cid,'+@SQL+' 
										 FROM (select borrow,[期间] from  #temp4 where cid='+CONVERT(VARCHAR(3),@CidID)+') a PIVOT (MAX(borrow) for [期间] in ('+ @SQL + ')) b 
										 UNION ALL 
										 select '''+@CidName+'贷方金额'' as ''项目'','+CONVERT(VARCHAR(3),@CidID)+' as cid,'+@SQL+' 
										 FROM (select lend,[期间] from  #temp4 where cid='+CONVERT(VARCHAR(3),@CidID)+') a PIVOT (MAX(lend) for [期间] in ('+ @SQL + ')) b '
						END
					SET @index=@index+1
				END
				 
			IF @ExeSQL<>''
				BEGIN
					 --综合本位币
					 SET @ExeSQL=@ExeSQL+'UNION ALL  
						 select ''综合本位币借方金额'' as ''项目'',0 as cid,'+@SQL+' 
						 FROM (select borrow,[期间] from  #temp4 where cid=0) a PIVOT (MAX(borrow) for [期间] in ('+ @SQL + ')) b 
						 UNION ALL 
						 select ''综合本位币贷方金额'' as ''项目'',0 as cid,'+@SQL+' 
						 FROM (select lend,[期间] from  #temp4 where cid=0) a PIVOT (MAX(lend) for [期间] in ('+ @SQL + ')) b '
					 
					 PRINT @ExeSQL
					 EXEC(@ExeSQL)
				END
				
			DROP TABLE #tempcid
		END
	ELSE 
		BEGIN
			--筛选
			IF @Cid>0 --具体币种 
				INSERT INTO #temp 
				SELECT CONVERT(NVARCHAR(5),fperiod)+'期',borrow,lend FROM #temp4 WHERE cid=@Cid
			ELSE      --查询的是综合本位币
				INSERT INTO #temp 
				SELECT CONVERT(NVARCHAR(5),fperiod)+'期',borrow,lend FROM #temp4 WHERE cid=0 
			
			SELECT @SQL = ISNULL(@SQL + '],[' , '') + [期间] FROM #temp 
			SET @SQL = '[' + @SQL + ']' 
		      
		    DECLARE @tempcid VARCHAR(3)
		    SET @tempcid=CONVERT(VARCHAR(3),@Cid)
		
		    EXEC ('
					SELECT ''借方金额'' as ''项目'',' + @tempcid+' as cid,'+ @SQL + '  FROM  (select [借方金额],[期间] from  #temp) a PIVOT (MAX([借方金额])  FOR [期间] IN (' + @SQL + ')) b 
					UNION ALL
					SELECT ''贷方金额'' as ''项目'',' + @tempcid+' as cid,'+ @SQL + '  FROM  (select [贷方金额],[期间] from #temp) a PIVOT (MAX([贷方金额])  FOR [期间] IN (' + @SQL + ')) b 
				 ') 
		END
		
	DROP TABLE #temp,#temp1,#temp2,#temp3,#temp4
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_AcComparePeriodView]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].WEB_AcComparePeriodView
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/15
	Description	: 查询单币别总分类账
*/

CREATE PROCEDURE WEB_AcComparePeriodView
(
   @Fyear			VARCHAR(5),
   @STypeId 		VARCHAR(50),   ---分支机构ID
   @ATypeId			VARCHAR(50),  ---会计科目ID      
   @Cid				INT,		   ---币别ID            
   @IsPost			BIT		   ---是否显示未过账凭证 1：是 0：否
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	--取查询期间
	DECLARE @FPeriodStart INT,@FPeriodEnd INT	
	SELECT @FPeriodStart=MIN(FPeriod),@FPeriodEnd=MAX(FPeriod) FROM dbo.Ac_Period	  
	
	---------------------------------要查询科目的子科目
	CREATE TABLE #temp1
	(
		STYPEID 		VARCHAR(50),	----分支机构ID
		FATHERID        VARCHAR(50),    ----查询的科目ID
		SONID			VARCHAR(50),	----查询的科目子节点的ID
	)

	INSERT INTO #temp1
	SELECT STYPEID,
		   @ATypeId,
		   TYPEID
	FROM dbo.Ac_Account 
	WHERE STYPEID=@STypeId AND TYPEID LIKE @ATypeId+'%' AND SONNUM=0 --AND DELETED=0  
	ORDER BY TypeId   
	-------------------------------要查询的科目的凭证统计成每期的借和贷------------------------------------------------------------
	SELECT c.FATHERID AS typeid,
		   a.fPeriod,                                          
		   ISNULL(SUM(ISNULL(b.FDEBITTOTALFOR,0)),0) AS BORROW,
		   ISNULL(SUM(ISNULL(b.FCREDITTOTALFOR,0)),0) AS LEND,
		   b.cid     
	INTO #temp2 
	FROM Ac_Voucher a 
	JOIN Ac_Voucher_Bill b ON a.BillNumberId=b.BillNumberId  
	JOIN #temp1 c ON b.STypeId=c.STYPEID AND b.ATypeId=c.SONID 
	WHERE a.FYear=@FYear AND 
		  a.FPERIOD>=@FPeriodStart AND 
		  a.FPERIOD<=@FPeriodEnd AND 
		  a. FChecked <> -1 AND 
		  ((@IsPost=0 AND IfCheck='t') OR @IsPost=1) 
	GROUP BY c.FATHERID,a.FPeriod,b.Cid
	ORDER BY Cid,a.FPeriod
	
	--综合本位币
	INSERT INTO #temp2
	SELECT c.FATHERID AS typeid,
		   a.fPeriod,                                          
		   ISNULL(SUM(ISNULL(b.FDEBITTOTAL,0)),0) AS BORROW,
		   ISNULL(SUM(ISNULL(b.FCREDITTOTAL,0)),0) AS LEND,
		   0
	FROM Ac_Voucher a 
	JOIN Ac_Voucher_Bill b ON a.BillNumberId=b.BillNumberId  
	JOIN #temp1 c ON b.STypeId=c.STYPEID AND b.ATypeId=c.SONID 
	WHERE a.FYear=@FYear AND 
		  a.FPERIOD>=@FPeriodStart AND 
		  a.FPERIOD<=@FPeriodEnd AND 
		  a. FChecked <> -1 AND 
		  ((@IsPost=0 AND IfCheck='t') OR @IsPost=1) 
	GROUP BY c.FATHERID,a.FPeriod 
	-----------------------------------------------------------------------------------------------------------------------------------
	----期间表
	CREATE TABLE #temp3
	(
		Fperiod  INT
	)
    WHILE @FPeriodStart<=@FPeriodEnd
		BEGIN
			INSERT INTO #temp3 (Fperiod)
			SELECT @FPeriodStart
			
			SET @FPeriodStart=@FPeriodStart+1
		END
		
	----结果表
    CREATE TABLE #temp4
    (
		cid INT,
		fperiod INT,
		[借方金额]  NUMERIC(24, 10) ,
		[贷方金额]    NUMERIC(24, 10) 
    )
	INSERT INTO #temp4 (cid, fperiod)
	SELECT c.cid,f.fperiod 
	FROM (SELECT cid FROM dbo.Ac_Currency
	      UNION ALL 
	      SELECT 0 AS cid) c,#temp3 f
	ORDER BY cid,Fperiod
	
	--各币别更新
	UPDATE t SET t.[借方金额]=ISNULL(d.borrow,0),t.[贷方金额]=ISNULL(d.lend,0)  
	FROM #temp4 t LEFT JOIN #temp2 d ON t.cid=d.Cid AND t.fperiod=d.FPeriod  
	
	----列转行
	IF @cid<0 --查询的是综合本位币
		SET @Cid=0   
	
	SELECT @FYear+'第'+CONVERT(VARCHAR(5),fperiod)+'期' AS QueryTime,
	FullName,
	VALUE
	FROM (SELECT * FROM #temp4 WHERE cid=@Cid) t
	UNPIVOT ( 
	 VALUE FOR FullName IN ([借方金额], [贷方金额])
	)AS unpvt 		
		
	DROP TABLE #temp1,#temp2,#temp3,#temp4
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AccountAtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_AccountAtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊
	日期：2015-01-26
	描述：科目类别权限设置
*/ 
CREATE PROCEDURE Web_AccountAtype  
(
	@etypeid	VARCHAR(500),
	@stypeid	VARCHAR(500),
	@OperatorId	VARCHAR(500)		--操作员Id  
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------  
IF @OperatorID IS NULL RETURN 1  
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),  
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)  
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT  
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------  
IF((SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = @stypeid AND typeid = '00000') >= 1
	OR (SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = '00000' AND typeid = '00000') >= 1)
BEGIN
	SELECT 1 AS selected,TypeId,FullName,
	CASE 
		WHEN FullName='资产' THEN 1
        WHEN FullName='负债' THEN 2
        WHEN FullName='共同' THEN 3
        WHEN FullName='权益' THEN 4
        WHEN FullName='成本' THEN 5
        WHEN FullName='损益' THEN 6
    END AS ordercol 
	FROM dbo.Ac_Account 
	WHERE StypeId = @stypeid AND ParId = '00000'
	ORDER BY ordercol
END
ELSE
BEGIN
	SELECT 
	ISNULL((
		SELECT flag FROM dbo.Ac_Account_L 
		WHERE etypeid = @etypeid AND stypeid = @stypeid AND typeid = ac.typeid
	),0) AS selected,TypeId,FullName,
	CASE 
		WHEN FullName='资产' THEN 1
        WHEN FullName='负债' THEN 2
        WHEN FullName='共同' THEN 3
        WHEN FullName='权益' THEN 4
        WHEN FullName='成本' THEN 5
        WHEN FullName='损益' THEN 6
    END AS ordercol 
	FROM dbo.Ac_Account AS ac 
	WHERE StypeId = @stypeid 
		AND ParId = '00000'
		AND TypeId NOT IN 
		(
			SELECT b.typeid 
			FROM dbo.Ac_Account_L AS a 
			INNER JOIN 
			(
				SELECT TypeId FROM dbo.Ac_Account WHERE StypeId = @stypeid AND ParId = '00000'
			) AS b ON (LEFT(a.typeid,5) = b.TypeId)
			WHERE etypeid = @etypeid AND stypeid = @stypeid AND LEN(a.typeid) > 5
			GROUP BY b.TypeId
		)
	ORDER BY ordercol
END
--------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AccountCashBankReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AccountCashBankReport]
GO

-------------------------------------------------------------------------  
--现金银行报表查询  
--作者：王浩源  
--日期：2004-01-14  
--引用：GP_CheckOperatorRight23  
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-10
	--说明：对转款单的统计进行处理（单据编号77）
-------------------------------------------------------------------------  
--修改纪录
--修改原因：拥有全部银行帐户权限的非管理员查询时没有收款单和付款单
--修改人：徐辉
--修改日期：2004-4-9
--修改记号：#-01
-------------------------------------------------------------------------  
--修改纪录
--修改原因：增加一个不显示实收\实付为0的按钮
--修改人：滕强
--修改日期：2004-5-8
--修改记号：#-02
----------------------------------------------------------------------------
--修改作者：谢吉康
--修改日期：2004-08-31
--修改原因：处理优惠金额
--修改结果：本地测试正确
----------------------------------------------------------------------------
----------------------------------------------------------------------------
--修改作者：徐辉
--修改日期：2005-01-4
--修改原因：除有出入库的生产拆装单，商品换货单外对其他其他单证不对Ktypeid2进行权限控制
--修改结果：本地测试正确
--修改标志：#03
----------------------------------------------------------------------------

----------------------------------------------------------------------------
--修改作者：徐辉
--修改日期：2005-09-7
--修改原因：零售单添加了优惠金额，相应的调整
--修改结果：本地测试正确
--修改标志：#04
----------------------------------------------------------------------------
----------------------------------------------------------------------------
--修改作者：徐辉
--修改日期：2008-02-29
--修改原因：添加，有些单据是没有仓库的，有仓库权限限制的操作员查询不出这些单据
--修改结果：本地测试正确
--修改标志：#05

--修改作者：毛欣蓉
--修改日期：2010-7-26
--修改原因：优化，压缩数据在连接提高执行效率
--修改结果：本地测试正确
----------------------------------------------------------------------------
----------------------------------------------------------------------------
--修改作者：董湛 
--修改日期：2013-3-26
--修改原因：9.1版本需求变更
----------------------------------------------------------------------------
CREATE  PROCEDURE Web_AccountCashBankReport  
(  
 @BillDateBegin		VARCHAR(20),  --时间范围下限  
 @BillDateEnd 		VARCHAR(20),  --时间范围上限  
 @OperatorID  		VARCHAR(50),  --操作员ID号  
 @StypeID			VARCHAR(max), --分支机构
 @BTypeID  			VARCHAR(max), --往来单位  
 @ETypeID  			VARCHAR(max), --经手人  
 @ATypeID  			VARCHAR(max), --项目  
 @DTypeID			VARCHAR(max), --部门  
 @BillType			VARCHAR(500), --单据类型
 @Comment			NVARCHAR(max),--摘要
 @Explain			NVARCHAR(max),--说明
 @hidezero		int=1, -- 1 不显示，0显示
 @SortField			VARCHAR(50)   --排序字段
)  
--@encode$--
AS  
  
SET NOCOUNT ON  
BEGIN
--------------------------------------------------------------权限检查-------------------------------------------------------  
	if @OperatorId is null return 1
	declare @Re int,@MAtypeid varchar(50),@MBtypeid varchar(50),@MBtypeid2 varchar(50),@MEtypeid varchar(50),@MKtypeid varchar(50),@MPtypeid varchar(50),
			@MExpense varchar(50),@MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	exec @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,
										 @MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	if @Re<>0 return @Re
--------------------------------------------------------------权限检查完毕-------------------------------------------------------  
	  
	DECLARE @SQL  NVARCHAR(max)  --用于保存动态SQL语句的变量  

    CREATE TABLE #Stype (TypeID varchar(50))
	CREATE TABLE #Atype (nId INT)
	CREATE TABLE #Btype (TypeID varchar(50))
	CREATE TABLE #Etype (TypeID varchar(50))
	CREATE TABLE #Ktype (TypeID varchar(50))
	CREATE TABLE #Dtype (TypeID varchar(50))

    -----------------------分支机构
    IF @StypeID=''
		INSERT INTO #Stype SELECT typeid FROM dbo.F_GetManDetailSType(@OperatorID)
    ELSE		    
		INSERT INTO #Stype SELECT s.TypeId FROM dbo.f_split(@StypeID,',') f  JOIN stype s ON s.TypeId LIKE f.a+'%' AND s.sonnum=0 AND s.deleted=0 JOIN F_GetManDetailSType(@OperatorID) r ON s.TypeId=r.typeid 
		        
	-----------------------往来单位
	IF @BTypeID=''
		BEGIN
			INSERT INTO #Btype select typeid from F_GetManDetailBType(@OperatorID) 
			INSERT INTO #Btype SELECT ''
		END
	ELSE
		BEGIN
	        INSERT INTO #Btype SELECT b.TypeId FROM dbo.f_split(@BTypeID,',') f  JOIN btype b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0 AND b.deleted=0 JOIN F_GetManDetailBType(@OperatorID) r ON b.typeId=r.TypeId
	    END
	--------------------经手人
	IF @ETypeID=''
		BEGIN
			INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
		END
	ELSE
		INSERT INTO #Etype select e.typeid from dbo.f_split(@EtypeID,',') f  JOIN dbo.employee e ON e.TypeId LIKE f.a+'%' AND e.sonnum=0 AND e.deleted=0	JOIN F_GetManDetailEType(@OperatorID) r ON e.typeId=r.TypeId
	-------------------仓库
		INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorID)
		INSERT into #Ktype select ''
	-------------------部门
	IF @DTypeID=''
		INSERT INTO #Dtype select typeid from dbo.F_GetManDetailDType(@OperatorID)
	ELSE
		INSERT INTO #Dtype select d.typeid from dbo.f_split(@DTypeID,',') f  JOIN dbo.Department d ON d.TypeId LIKE f.a+'%' AND d.sonnum=0 AND d.deleted=0	JOIN F_GetManDetailDType(@OperatorID) r ON d.typeid=r.TypeId	
    --------------------------项目
	IF @ATypeID=''
		INSERT INTO #Atype select nId from F_GetManDetailAType(@OperatorID)
	ELSE
		INSERT INTO #Atype SELECT a.nId FROM (select a.nTypeId FROM dbo.f_split(@ATypeID,',') f  JOIN ac_items a ON f.a=a.nid) t JOIN ac_items a ON a.Deleted=0 AND a.SonNum=0 AND a.nTypeId LIKE t.nTypeId+'%' JOIN F_GetManDetailAType(@OperatorID) r ON a.nid=r.nid
   ----------------------------------------------------------------------------------------------------------------------------------------------------------------
	CREATE TABLE #BillIndex
	(
		BillNumberId		NUMERIC(18,0),
		BillDate			DATETIME,
		StypeId			    VARCHAR(50), --分支机构 
		BTypeId				VARCHAR(100),  --结算单位
		DealBTypeID			VARCHAR(100),  --往来单位
		BillCode			VARCHAR(400),
		BillType			INT,
		BilltypeName		NVARCHAR(200),
		ETypeId				VARCHAR(100),
		ATypeId				VARCHAR(100),
		TotalMoney			 NUMERIC(24, 10) ,
		TotalInMoney		 NUMERIC(24, 10) ,
		CompleteTotal		 NUMERIC(24, 10) ,
		preferencemoney		 NUMERIC(24, 10) ,
		Comment				VARCHAR(2000),
		Explain				VARCHAR(2000)
	)
			
	SET @SQL='	INSERT INTO #BillIndex
				SELECT	BillNumberID,
						BillDate,
						b.Stypeid,
						BTypeID,
						DealBTypeID,
						BillCode,
						b.BillType,
						bn.BillName,
						ETypeID,
						b.ATypeID,
						ISNULL(TotalMoney,0) as TotalMoney,                 ---单据金额（应收）
						ISNULL(TotalInMoney,0) as TotalInMoney,             ---收款金额（实收）
						ISNULL(CompleteTotal,0) as CompleteTotal,			---按单结算金额
						ISNULL(preferencemoney,0) as preferencemoney,       ---优惠金额
						b.Comment,
						b.Explain
				FROM	( SELECT  BillNumberId ,
									BillDate ,
									Stypeid ,
									btypeid ,
									DealBTypeID ,
									BillCode ,
									BillType ,
									etypeid ,
									atypeid ,
									totalmoney ,                ---单据金额（应收）
									totalinmoney ,             ---收款金额（实收）
									CompleteTotal ,			---按单结算金额
									preferencemoney ,       ---优惠金额
									Comment ,
									explain,
									ifcheck,
									RedWord,
									draft,
									ktypeid,
									ktypeid2,
									Dtypeid
							FROM    BillIndex
							UNION ALL
							SELECT  BillNumberID ,
									BillDate ,
									STypeID ,
									BTypeID ,
									DealBTypeID ,
									BillCode ,
									BillType ,
									ETypeID ,
									ATypeID ,
									TotalMoney ,
									TotalInMoney ,
									CompleteTotal ,
									preferencemoney ,
									Comment ,
									'''' Explain,
									ifcheck,
									RedWord,
									draft,
									InKTypeId,
									OutKTypeId,
									Dtypeid
							FROM    Coupon_BillIndex
							WHERE (BillType = 423 AND FromType = 2) OR (BillType = 424 AND FromType = 2) OR BILLTYPE = 426 )b
				JOIN #Stype s ON s.Typeid=b.Stypeid  
				JOIN Stype ON b.stypeid=Stype.typeid 
				--inner join #atype a on (b.atypeid=a.nid or isnull(b.atypeid,'''')='''' or b.atypeid=''-99999'') 
				JOIN BillName bn ON b.BillType=bn.billtype '
				---结算单位 
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' INNER JOIN #Btype ON b.Btypeid=#Btype.typeid '

	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' INNER JOIN #Etype ON b.Etypeid=#Etype.typeid '

	IF NOT (@DTypeId = '' AND @MDtypeid='00000')
		SET @SQL =@SQL+' INNER JOIN #Dtype ON b.Dtypeid=#Dtype.typeid '

	IF NOT (@MKTypeId = '00000')
		SET @SQL =@SQL+' INNER JOIN #Ktype k1 ON b.Ktypeid=k1.typeid 
						 INNER JOIN #Ktype k2 ON b.ktypeid2=k2.typeid '
			
	SET @SQL=@SQL+'WHERE b.BillType IN('+@BillType+')
						AND IfCheck = ''t''
						AND RedWord = 0
						AND Draft=0 
						and (b.atypeid in (select nid from #atype)  or isnull(b.atypeid,'''')='''' or b.atypeid=''-99999'')
						AND b.BillDate>=''' + @BillDateBegin + '''
						AND b.BillDate<=''' + @BillDateEnd + ''''
	IF @Comment!=''
		SET @SQL=@SQL+' AND ISNULL(b.Comment,'''') LIKE ''%'+@Comment+'%'''
	IF @Explain!=''
		SET @SQL=@SQL+' AND ISNULL(b.Explain,'''') LIKE ''%'+@Explain+'%'''
		
	EXEC(@sql)

	/**/
	/*单据金额,显示都始终是正数*/ 
	DECLARE @TotalMOneySql VARCHAR(1000)
	SET @TotalMOneySql=' Bi.TotalMoney, '
	/*实收金额*/
	DECLARE @InArSql VARCHAR(1000)
	SET @InArSql=' (CASE
						WHEN (Bi.BillType=4 OR 
							  Bi.BillType=11 OR	  Bi.BillType=12   OR
							  /*Bi.BillType=45 OR*/
							  Bi.BillType=6 OR
							  Bi.BillType=85 OR Bi.BillType=213 OR
							  Bi.BillType=93 OR 
							  Bi.BillType=141 OR 
							  Bi.BillType=150 OR 
							  Bi.BillType=151 OR 
							  Bi.BillType=160 OR   
							  Bi.BillType=167 OR 
							  Bi.BillType=168 OR 
							  Bi.BillType=172 OR 
							  Bi.BillType=181 OR
							  Bi.BillType=312 OR  
							  Bi.BillType=189 OR
							  Bi.BillType=305 /*OR
							  Bi.BillType=215*/ OR
							  Bi.BillType=77 OR
							  Bi.BillType = 424 OR
							  (bi.BillType=159 and t.total>0) )
							 THEN t.Total	
						ELSE 0
					END
					 ) AS TotalInMoney_Ar, '			
	/*应收金额*/
	DECLARE @ArSql varchar(1000)
	SET @ArSql=' (CASE
					WHEN (Bi.BillType=11 OR  Bi.BillType=12   OR
						  Bi.BillType=85 OR Bi.BillType=213 OR
						  Bi.BillType=93 OR 
						  Bi.BillType=141 OR 
						  Bi.BillType=150 OR 
						  Bi.BillType=151 OR
						  Bi.BillType=160 OR    --销售换货单
						  Bi.BillType=167 OR 
						  Bi.BillType=168 OR 
						  Bi.BillType=172 OR 
						  Bi.BillType=181 OR
						  Bi.BillType=312 OR
						  Bi.BillType = 424 OR
						  Bi.BillType=305) 
						 THEN (Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney) 
					WHEN (Bi.BillType IN (/*45,215*/6))                      
						THEN -(Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney)
					ELSE 0
				  END
				  ) AS TotalMoney_Ar, '
				  
	/*实付金额*/
	DECLARE @InApSql VARCHAR(1000)
	SET @InApSql='	(CASE
							WHEN (Bi.BillType=5 OR 
								  /*Bi.BillType=6 OR*/ Bi.BillType=45 OR Bi.BillType=215 OR	Bi.BillType=46 OR
								  Bi.BillType=34 OR 
							      Bi.BillType=36 OR
								  Bi.BillType=66 OR 
								  Bi.BillType=84 OR Bi.BillType=212 OR
								  Bi.BillType=145 OR 
								  Bi.BillType=148 OR 
								  Bi.BillType=149 OR 
								  Bi.BillType=158 OR 
								  Bi.BillType=161 OR
								  Bi.BillType=170 OR
								  Bi.BillType=190 OR
								  Bi.BillType=414  OR
								  Bi.BillType = 423 OR Bi.BillType = 426 OR
								  (bi.BillType=159 and t.total<0) ) 
							     THEN -t.Total	 
							 WHEN Bi.BillType=77 
								THEN t.total
							ELSE 0
						END
						) AS TotalInMoney_Ap, '
	/*应付金额*/
	DECLARE @ApSql VARCHAR(1000)
	SET @ApSql='	(CASE
						WHEN ( Bi.BillType=36 OR  
							   Bi.BillType=84 OR Bi.BillType=212 OR
							   Bi.BillType=145 OR 
							   Bi.BillType=148 OR 
							   Bi.BillType=149) OR  Bi.BillType=414   
							  THEN (Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal)
						WHEN (Bi.BillType=34 OR 
							  Bi.BillType = 423 OR
							  Bi.BillType=161 OR   --采购入库，换货单  
							  Bi.BillType=170) 
							THEN (Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney)
						WHEN (Bi.BillType=45 OR Bi.BillType=215  OR Bi.BillType=46 OR Bi.BillType = 426)     --采购退货     
							THEN /*-*/(Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney)
						ELSE 0
					END
					) AS TotalMoney_Ap, '

	SET @SQL='  
	 SELECT	bi.BillNumberID,
			bi.BillDate,
			bi.stypeid,
			bi.billtypename as billname,
			bi.BTypeID,
			bi.DealBTypeID,
			bi.BillCode,
			bi.BillType,
			bi.ETypeID,
			(case when bi.billtype=''77'' then ''''  else bi.ATypeID end) as ATypeId,'
	SET @SQL=@SQL+@TotalMOneySql+@InArSql+@ArSql+@InApSql+@ApSql
	SET @SQL=@SQL+'	
			bi.Comment,
			bi.Explain
	FROM #BillIndex bi  '
if isnull(@atypeid,'')=''
	SET @SQL=@SQL+'	LEFT JOIN '
ELSE
    SET @SQL=@SQL+'	INNER JOIN '
SET @SQL=@SQL+' (                         
		SELECT b.BillNumberID,SUM(CASE WHEN l.billtype=77 AND l.total<0 THEN 0 else l.Total end) AS total,b.billtype
		FROM #BillIndex b
		INNER join ListTable l on b.billnumberid = l.billnumberid AND B.BILLTYPE = L.BILLTYPE 
	    INNER  JOIN #atype a ON l.atypeid=a.nid
	    GROUP BY b.BillNumberId ,b.billtype
	) t  ON bi.billnumberId=t.billnumberId AND bi.billtype = t.billtype'
    
	--exec( @SQL)
	print @SQL
	DECLARE @reuslt varchar(max)
	--IF @AlterDisplay = '1'
	--	SET @SQL = 'SELECT * FROM ('+@SQL+') X WHERE TotalInMoney_Ap<>.0000 OR TotalInMoney_Ar<>.0000 AND BillNumberID NOT IN (77,159)' --转换单和业务凭证4列都是0，要显示
 --   else 
 set @reuslt='SELECT 
			a.BillNumberID,
			a.BillDate,
			a.stypeid,
			a.billtypename as billname,
			a.BTypeID,
			a.DealBTypeID,
			a.BillCode,
			a.BillType,
			a.ETypeID,
			(case when a.billtype=''77'' then ''''  else a.ATypeID end) as ATypeId ,
			CASE WHEN a.BillType IN (34,161,145,45,215,170,212,84,190,66,36,158,5,148,149,46,414,423,426) THEN -1 ELSE 1 END*a.TotalMoney as TotalMoney,
			case when x.billnumberid is null then 0 else  isnull(x.TotalinMoney_Ar,0) end as TotalinMoney_Ar
			,case when x.billnumberid is null then 
				case when a.billtype in (34,161,145,45,215,170,212,84,190,66,36,158,5,148,149,46,414,423,426) then 0 else a.totalmoney end
			else 
				case when a.billtype in(6) then abs(x.TotalMoney_Ar) else x.TotalMoney_Ar end
			 end as TotalMoney_Ar
			,case when x.billnumberid is null then 0 else isnull(x.TotalinMoney_Ap,0) end as TotalinMoney_Ap
			,case when x.billnumberid is null then 
			case when a.billtype in (34,161,145,45,215,170,212,84,190,66,36,158,5,148,149,46,414,423,426) then a.totalmoney else 0 end
			else x.TotalMoney_Ap end as TotalMoney_Ap
			,a.Comment
			,a.Explain
			FROM #billindex a '
			
	  set @reuslt=@reuslt+' inner JOIN ('+@sql+') x ON a.billnumberId=x.billnumberId AND a.billtype = x.billtype' 
 	  if @hidezero=1
			set @reuslt=@reuslt+'  WHERE (x.TotalinMoney_Ar<>0 OR TotalinMoney_Ap<>0) '
		
		
    IF @SortField=''
		SET @reuslt+=' ORDER BY Billdate,billcode,Stypeid'
	else 
		BEGIN
			DECLARE @Sort VARCHAR(50), @Asc VARCHAR(10)
			SET @Asc=left(@SortField,1)
			IF @Asc='d'
				SET @Asc=' DESC'
			ELSE
				SET @Asc=' ASC'
			SET @Sort=SUBSTRING(@SortField,2,LEN(@SortField)-1)
			SET @reuslt+=' ORDER BY '+@Sort+@Asc
		END 
	--PRINT @reuslt	
	EXEC(@reuslt)
	

	DROP TABLE #billindex,#Atype,#Btype,#Dtype,#Etype,#Ktype,#Stype
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AccountCashBankReportDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AccountCashBankReportDetail]
GO

--===================================================================================================
 -- 功能说明: 实现现金日报表中的格式转换
 -- 返回结果: 查询结果集
 -- 作    者：滕强
 -- 创建时间: 2004-5-17
--===================================================================================================
----------------------------------------------------------------------------
--修改作者：谢吉康
--修改日期：2004-08-31
--修改原因：处理优惠金额
--修改结果：本地测试正确
----------------------------------------------------------------------------
--修改作者：徐辉
--修改日期：2005-01-4
--修改原因：除有出入库的生产拆装单，商品换货单外对其他其他单证不对Ktypeid2进行权限控制
--修改结果：本地测试正确
--修改标志：#03

----------------------------------------------------------------------------
--修改作者：徐辉
--修改日期：2008-02-29
--修改原因：添加，有些单据是没有仓库的，有仓库权限限制的操作员查询不出这些单据
--修改结果：本地测试正确
--修改标志：#05
----------------------------------------------------------------------------
--修改作者：Wang Wei
--修改日期：2008-02-29
--修改原因：添加新增的单据,178,179,181,182,特殊处理洗车结算单
--修改结果：本地测试正确
--修改标志：#06
----------------------------------------------------------------------------
----------------------------------------------------------------------------
--修改作者：董湛 
--修改日期：2013-3-26
--修改原因：9.1版本需求变更
----------------------------------------------------------------------------
CREATE PROCEDURE Web_AccountCashBankReportDetail  
(  
 @BillDateBegin		VARCHAR(20),  --时间范围下限  
 @BillDateEnd 		VARCHAR(20),  --时间范围上限  
 @OperatorID  		VARCHAR(50),  --操作员ID号  
 @StypeID			VARCHAR(max), --分支机构
 @BTypeID  			VARCHAR(max), --往来单位  
 @ETypeID  			VARCHAR(max), --经手人  
 @ATypeID  			VARCHAR(max), --项目  
 @DTypeID			VARCHAR(max), --部门  
 @BillType			VARCHAR(500), --单据类型
 @Comment			NVARCHAR(max),--摘要
 @Explain			NVARCHAR(max),--说明
 --@AlterDisplay		VARCHAR(20),  --增加显示'不显示实收/实付为零的'页面  --#-02
 @SortField			VARCHAR(50)   --排序字段
)  
--@encode$--
AS  
  
SET NOCOUNT ON  
BEGIN
	--------------------------------------------------------------权限检查-------------------------------------------------------  
	if @OperatorId is null return 1
	declare @Re int,@MAtypeid varchar(50),@MBtypeid varchar(50),@MBtypeid2 varchar(50),@MEtypeid varchar(50),@MKtypeid varchar(50),@MPtypeid varchar(50),
			@MExpense varchar(50),@MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	exec @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,
										 @MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	if @Re<>0 return @Re
--------------------------------------------------------------权限检查完毕-------------------------------------------------------  
	  
	DECLARE @SQL  NVARCHAR(max)  --用于保存动态SQL语句的变量  

    CREATE TABLE #Stype (TypeID varchar(50))
	CREATE TABLE #Atype (nId INT)
	CREATE TABLE #Btype (TypeID varchar(50))
	CREATE TABLE #Etype (TypeID varchar(50))
	CREATE TABLE #Ktype (TypeID varchar(50))
	CREATE TABLE #Dtype (TypeID varchar(50))

      -----------------------分支机构
    IF @StypeID=''
		INSERT INTO #Stype SELECT typeid FROM dbo.F_GetManDetailSType(@OperatorID)
    ELSE		    
		INSERT INTO #Stype SELECT s.TypeId FROM dbo.f_split(@StypeID,',') f  JOIN stype s ON s.TypeId LIKE f.a+'%' AND s.sonnum=0 AND s.deleted=0 JOIN F_GetManDetailSType(@OperatorID) r ON s.TypeId=r.typeid 
		        
	-----------------------往来单位
	IF @BTypeID=''
		BEGIN
			INSERT INTO #Btype select typeid from F_GetManDetailBType(@OperatorID) 
			INSERT INTO #Btype SELECT ''
		END
	ELSE
		BEGIN
	        INSERT INTO #Btype SELECT b.TypeId FROM dbo.f_split(@BTypeID,',') f  JOIN btype b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0 AND b.deleted=0 JOIN F_GetManDetailBType(@OperatorID) r ON b.typeId=r.TypeId
	    END
	--------------------经手人
	IF @ETypeID=''
		BEGIN
			INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
		END
	ELSE
		INSERT INTO #Etype select e.typeid from dbo.f_split(@EtypeID,',') f  JOIN dbo.employee e ON e.TypeId LIKE f.a+'%' AND e.sonnum=0 AND e.deleted=0	JOIN F_GetManDetailEType(@OperatorID) r ON e.typeId=r.TypeId
	-------------------仓库
		INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorID)
		INSERT into #Ktype select ''
	-------------------部门
	IF @DTypeID=''
		INSERT INTO #Dtype select typeid from dbo.F_GetManDetailDType(@OperatorID)
	ELSE
		INSERT INTO #Dtype select d.typeid from dbo.f_split(@DTypeID,',') f  JOIN dbo.Department d ON d.TypeId LIKE f.a+'%' AND d.sonnum=0 AND d.deleted=0	JOIN F_GetManDetailDType(@OperatorID) r ON d.typeid=r.TypeId	
    --------------------------项目
	
	IF @ATypeID=''
		INSERT INTO #Atype select nId from F_GetManDetailAType(@OperatorID)
	ELSE
		INSERT INTO #Atype SELECT a.nId FROM (select a.nTypeId FROM dbo.f_split(@ATypeID,',') f  JOIN ac_items a ON f.a=a.nid) t JOIN ac_items a ON a.Deleted=0 AND a.SonNum=0 AND a.nTypeId LIKE t.nTypeId+'%' JOIN F_GetManDetailAType(@OperatorID) r ON a.nid=r.nid
  
   ----------------------------------------------------------------------------------------------------------------------------------------------------------------
   CREATE TABLE #tempbill(billnumerid NUMERIC(18,0),billtype INT)
   CREATE TABLE #billNum(orderid INT IDENTITY(1,1),billnumerid NUMERIC(18,0),billtype INT)
   SET @SQL='	INSERT INTO #tempbill
				SELECT DISTINCT	b.BillNumberID AS billnumerid,b.billtype as billtype
				FROM 
				(SELECT BillNumberID,STYPEID,billtype,Btypeid,Etypeid,Dtypeid,Ktypeid,ktypeid2,IfCheck,RedWord,Draft,BillDate,Comment,Explain FROM BillIndex
				 UNION ALL
				 SELECT BillNumberID,STYPEID,billtype,Btypeid,Etypeid,Dtypeid,inktypeid as ktypeid,outktypeid as ktypeid2,IfCheck,RedWord,Draft,BillDate,Comment,Explain FROM Coupon_BillIndex) b
				JOIN #Stype s ON s.Typeid=b.Stypeid  
				join ListTable l on b.billnumberid = l.billnumberid and b.billtype = l.billtype       
			    JOIN #atype a ON l.atypeid=a.nid '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' INNER JOIN #Btype ON b.Btypeid=#Btype.typeid '

	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' INNER JOIN #Etype ON b.Etypeid=#Etype.typeid '

	IF NOT (@DTypeId = '' AND @MDtypeid='00000')
		SET @SQL =@SQL+' INNER JOIN #Dtype ON b.Dtypeid=#Dtype.typeid '

	IF NOT (@MKTypeId = '00000')
		SET @SQL =@SQL+' INNER JOIN #Ktype k1 ON b.Ktypeid=k1.typeid 
						 INNER JOIN #Ktype k2 ON b.ktypeid2=k2.typeid '
			
	SET @SQL=@SQL+'WHERE b.BillType IN('+@BillType+')
						AND IfCheck = ''t''
						AND RedWord = 0
						AND Draft=0 
						AND b.BillDate>=''' + @BillDateBegin + '''
						AND b.BillDate<=''' + @BillDateEnd + ''''
	IF @Comment!=''
		SET @SQL=@SQL+' AND ISNULL(b.Comment,'''') LIKE ''%'+@Comment+'%'''
	IF @Explain!=''
		SET @SQL=@SQL+' AND ISNULL(b.Explain,'''') LIKE ''%'+@Explain+'%'''
	EXEC (@SQL)
	--PRINT @SQL
	
	
	   -- WHERE b.BillType IN(305,215,34,11,6,45,215,161,160,66,4,145,141,36,93,84,85,5,150,148,149,151,77,158,159,167,168,170,172,181,189,190,312,423,424,426,12,46)
				--AND IfCheck = 't'
				--AND RedWord = 0
				--AND Draft=0 
				--AND b.BillDate>='2018-01-04 00:00:00'
				--AND b.BillDate<='2018-01-04 00:00:00'

	---------------------先排序
	
	IF @SortField!=''
		BEGIN
			DECLARE @Sort VARCHAR(50), @Asc VARCHAR(10)
			SET @Asc=left(@SortField,1)
			IF @Asc='d'
				SET @Asc=' DESC'
			ELSE
				SET @Asc=' ASC'
			SET @Sort=SUBSTRING(@SortField,2,LEN(@SortField)-1)
			SET @SQL='INSERT INTO #billNum select b.BillNumberID,b.billtype FROM (SELECT BillNumberID,BillCode,STYPEID,billtype,Btypeid,Etypeid,Dtypeid,Ktypeid,ktypeid2,IfCheck,RedWord,Draft,BillDate,Comment,Explain,totalmoney FROM BillIndex
				 UNION ALL
				 SELECT BillNumberID,BillCode,STYPEID,billtype,Btypeid,Etypeid,Dtypeid,inktypeid as ktypeid,outktypeid as ktypeid2,IfCheck,RedWord,Draft,BillDate,Comment,Explain,totalmoney FROM Coupon_BillIndex) b
				 JOIN #tempbill t ON b.BillNumberID=t.billnumerid and b.billtype = t.billtype ORDER BY b.'+@Sort+@Asc
		END
	ELSE 
		SET @SQL='INSERT INTO #billNum select b.BillNumberID,b.billtype FROM (SELECT billcode,BillNumberID,STYPEID,billtype,Btypeid,Etypeid,Dtypeid,Ktypeid,ktypeid2,IfCheck,RedWord,Draft,BillDate,Comment,Explain,totalmoney FROM BillIndex
				 UNION ALL
				 SELECT billcode, BillNumberID,STYPEID,billtype,Btypeid,Etypeid,Dtypeid,inktypeid as ktypeid,outktypeid as ktypeid2,IfCheck,RedWord,Draft,BillDate,Comment,Explain,totalmoney FROM Coupon_BillIndex) b
				 JOIN #tempbill t ON b.BillNumberID=t.billnumerid and b.billtype = t.billtype ORDER BY b.Billdate,b.billcode'
	
	EXEC (@SQL)

	-----------------查数据
	CREATE TABLE #BillIndex
	(
		ID                  INT IDENTITY(1,1),     ---字段用来分组求
		BillNumberID		NUMERIC(18,0),
		BillDate			DATETIME,
		billName			VARCHAR(200),
		BTypeID				VARCHAR(100),
		Dealbtypeid			VARCHAR(100),
		BillCode			VARCHAR(400),
		BillType			INT,
		ETypeId				VARCHAR(100),
		StypeID				VARCHAR(50),
		ATypeId				VARCHAR(100),
		ATypeName			VARCHAR(400),
		TotalMoney			 NUMERIC(24, 10) , ---单据金额
		TotalinMoney_ar	     NUMERIC(24, 10) , ---项目实收金额
		TotalMoney_ar		 NUMERIC(24, 10) , ---项目应收金额
		TotalinMoney_ap		 NUMERIC(24, 10) , ---项目实付金额
		TotalMoney_ap		 NUMERIC(24, 10) , ---项目应付金额
		Comment				VARCHAR(max),
		Explain				VARCHAR(max),
	)
	
    INSERT INTO #BillIndex
     (BillNumberID,
      BillDate,
      billName,
      BTypeID,
      Dealbtypeid,
      BillCode,
      BillType,
      ETypeId,
      StypeID,
      ATypeId,
      ATypeName,
      TotalinMoney_ar,
      TotalMoney_ar,
      TotalinMoney_ap,
      TotalMoney_ap,
      Comment,
      Explain)
	SELECT b.BillNumberId,
		   b.BillDate,
		   bn.BillName,
		   b.btypeid,
		   b.DealBTypeID,
		   b.BillCode,
		   b.BillType,
		   b.etypeid,
		   b.StypeID,
		   l.AtypeId,
		   ai.FullName,
		   ---实收
		   CASE WHEN (b.BillType=4 OR 
					  b.BillType=11 OR	 b.BillType=12	OR
					  /*b.BillType=45 OR b.Billtype=215*/b.billtype=6 OR
					  b.BillType=85 OR b.BillType=213 OR
					  b.BillType=93 OR 
					  b.BillType=141 OR 
					  b.BillType=150 OR 
					  b.BillType=151 OR 
					  b.BillType=160 OR 
					  b.BillType=167 OR 
					  b.BillType=168 OR 
					  b.BillType=172 OR 
					  b.BillType=181 OR 
					  b.BillType=312 OR
					  b.BillType=305 OR
					  b.BillType=189)
				THEN l.Total
				WHEN (b.BillType=77 OR b.BillType=159) AND l.Total>0   ---业务凭证和转换单单独处理,金额大于0就是收
                THEN l.Total     				
		   ELSE 0 END,
		   0,---应收
		   ---实付
		   CASE WHEN (/*b.BillType=6 OR */ b.BillType=45 OR b.billtype=215 OR  b.billtype=46 OR 
						  b.BillType=34 OR  b.BillType=414 OR
						  b.BillType=36 OR 
						  b.BillType=66 OR 
						  b.BillType=84 OR b.BillType=212 OR
						  b.BillType=145 OR 
						  b.BillType=148 OR 
						  b.BillType=149 OR 
						  b.BillType=158 OR 
						  b.BillType=161 OR 
						  b.BillType=170 OR
						  b.BillType=5 OR
						  b.BillType=158 OR 
						  b.BillType=190) 
				 THEN -l.Total
				 WHEN (b.BillType=77 OR b.BillType=159) AND l.Total<0   ---业务凭证和转换单单独处理,金额小于0就是付，显示为正
                 THEN -l.Total 
		   ELSE 0 END,
		   0,---应付
		   b.Comment,
		   b.explain
	FROM #billNum bi
	JOIN dbo.BillIndex b ON b.BillNumberId=bi.billnumerid AND b.BillType = bi.billtype
	JOIN dbo.SType s ON b.Stypeid=s.TypeId
	JOIN dbo.BillName bn ON b.BillType=bn.Billtype
	JOIN dbo.ListTable l ON b.BillNumberId=l.BillNumberId AND l.BillType = b.BillType
	JOIN #Atype a ON l.AtypeId=a.nId
	JOIN dbo.Ac_Items ai ON a.nId=ai.nId  
    ORDER BY bi.orderid
	
	  INSERT INTO #BillIndex
     (BillNumberID,
      BillDate,
      billName,
      BTypeID,
      Dealbtypeid,
      BillCode,
      BillType,
      ETypeId,
      StypeID,
      ATypeId,
      ATypeName,
      TotalinMoney_ar,
      TotalMoney_ar,
      TotalinMoney_ap,
      TotalMoney_ap,
      Comment,
      Explain)
	SELECT b.BillNumberId,
		   b.BillDate,
		   bn.BillName,
		   b.btypeid,
		   b.DealBTypeID,
		   b.BillCode,
		   b.BillType,
		   b.etypeid,
		   b.StypeID,
		   l.AtypeId,
		   ai.FullName,
		   ---实收
		   CASE WHEN (
					  b.BillType=424 )
				THEN l.Total			
		   ELSE 0 END,
		   0,---应收
		   ---实付
		   CASE WHEN (    b.BillType=426 OR
						  b.BillType=423 
				     ) 
				 THEN -l.Total
		   ELSE 0 END,
		   0,---应付
		   b.Comment,
		   b.explain
	FROM #billNum bi
	JOIN dbo.Coupon_BillIndex b ON b.BillNumberId=bi.billnumerid AND b.BillType = bi.billtype
	JOIN dbo.SType s ON b.Stypeid=s.TypeId
	JOIN dbo.BillName bn ON b.BillType=bn.Billtype
	JOIN dbo.ListTable l ON b.BillNumberId=l.BillNumberId AND l.BillType = bi.billtype
	JOIN #Atype a ON l.AtypeId=a.nId
	JOIN dbo.Ac_Items ai ON a.nId=ai.nId  
    ORDER BY bi.orderid

	-------------确定更新单据的哪行为应收，应付
	CREATE TABLE #temp(id INT,billnumerid NUMERIC(18,0),billtype INT)
	INSERT INTO #temp(id, billnumerid,billtype)
    SELECT MAX(id),BillNumberID,BillType FROM #BillIndex GROUP BY BillNumberID,BillType
	
	---------单据的应收，应付
	CREATE TABLE #Money
	(
		BillNumberID		NUMERIC(18,0),
		YF					 NUMERIC(24, 10) ,  ---应付
		YS					 NUMERIC(24, 10) ,  ---应收
		ID					INT				---#temp中的id
	)
	INSERT INTO #Money
	(BillNumberID, YF, YS,ID)
	SELECT BillNumberID,
		   -----应付
	       CASE
						WHEN ( Bi.BillType=36 OR  
							   Bi.BillType=84 OR Bi.BillType=212 OR
							   Bi.BillType=145 OR 
							   Bi.BillType=148 OR 
							   Bi.BillType=149) 
							  THEN (Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal)
						WHEN (Bi.BillType=34 OR Bi.BillType=414 OR
							  Bi.BillType=161 OR  --采购入库，换货单  
							  Bi.BillType=170) 
							THEN (Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney)
						WHEN (Bi.BillType=/*6*/45 OR bi.BillType=215 OR bi.BillType=46)     --采购退货      
							THEN /*-*/(Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney)
						ELSE 0
					END,
		   -----应收
		  CASE
					WHEN (Bi.BillType=11 OR Bi.BillType=12 OR
						  Bi.BillType=85 OR Bi.BillType=213 OR
						  Bi.BillType=93 OR 
						  Bi.BillType=141 OR 
						  Bi.BillType=150 OR 
						  Bi.BillType=151 OR
						  Bi.BillType=160 OR    --销售换货单
						  Bi.BillType=167 OR 
						  Bi.BillType=168 OR 
						  Bi.BillType=172 OR 
						  Bi.BillType=181 OR 
						   Bi.BillType=312 OR
						  Bi.BillType=305) 
						 THEN (Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney) 
					WHEN (Bi.BillType IN (/*45,215*/6))                   
						THEN /*-*/(Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney)
					ELSE 0
				  END,
			t.id
	FROM #billNum b   
	JOIN BillIndex Bi  ON Bi.BillNumberId=b.billnumerid AND Bi.BillType = b.billtype
	JOIN #temp t ON Bi.BillNumberId=t.billnumerid AND t.billtype = b.billtype
	
	
	INSERT INTO #Money
	(BillNumberID, YF, YS,ID)
	SELECT BillNumberID,
		   -----应付
	       CASE
						WHEN (Bi.BillType=423 ) 
							THEN (Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney)
						WHEN (Bi.BillType=426 )     --采购退货      
							THEN /*-*/(Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney)
						ELSE 0
					END,
		   -----应收
		  CASE
					WHEN (Bi.BillType=424) 
						 THEN (Bi.TotalMoney-Bi.TotalInMoney-Bi.CompleteTotal-Bi.preferencemoney) 
					ELSE 0
				  END,
			t.id
	FROM #billNum b   
	JOIN dbo.Coupon_BillIndex Bi  ON Bi.BillNumberId=b.billnumerid AND Bi.BillType = b.billtype
	JOIN #temp t ON Bi.BillNumberId=t.billnumerid AND t.billtype = b.billtype
	
	
	
	--------------剔除应付应收是0的
	--IF @AlterDisplay = '1'
	--	DELETE #Money WHERE YF=0 AND YS=0 AND BillNumberID NOT IN (77,159)
    
    ------------更新应付，应收
    UPDATE b SET TotalMoney_ar=YS, ---应收金额
						  TotalMoney_ap=YF  ---应付
	FROM #BillIndex b,#Money m WHERE b.id=m.id 

	SELECT * FROM #BillIndex 
	
	DROP TABLE #Atype
	DROP TABLE #Btype
	DROP TABLE #Etype
	DROP TABLE #Ktype
	DROP TABLE #Dtype
	drop table #stype
	DROP TABLE #billindex,#tempbill,#billNum,#temp,#Money
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AccountMultiLevel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_AccountMultiLevel]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊
	日期：2014-11-18
	描述：会计科目多级权限
*/ 
CREATE PROCEDURE Web_AccountMultiLevel  
(  
	@OperatorId  VARCHAR(500)		--操作员Id  
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------  
IF @OperatorID IS NULL RETURN 1  
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),  
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)  
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT  
IF @Re<>0 RETURN @Re  
--------------------------------------------------------------权限检查-------------------------------------------------------  
------------------------------------------------------------临时表------------------------------------------------------------
--最终数据
CREATE TABLE #TEMP
(
	etypeid VARCHAR(500),
	eusercode VARCHAR(500),
	efullname VARCHAR(500),
	stypeid VARCHAR(MAX),
	sfullname VARCHAR(MAX)
)
--------------------------------------------------------------------------------------------------------------------------
DECLARE @Etypeid VARCHAR(500),@EUserCode VARCHAR(500),@EFullName VARCHAR(500),@Stypeid VARCHAR(500),@SFullName VARCHAR(500)
DECLARE AccountLCursor CURSOR FOR 
--SELECT A.etypeid,B.UserCode AS eusercode,B.FullName AS efullname,A.stypeid,C.FullName AS sfullname 
--FROM Ac_Account_L AS A 
--INNER JOIN employee AS B ON(A.etypeid = B.typeId)
--INNER JOIN stype AS C ON(A.stypeid = C.TypeId)
SELECT DISTINCT A.typeid AS etypeid,A.UserCode AS eusercode,A.FullName AS efullname,B.stypeid,B.sfullname 
FROM employee AS A 
INNER JOIN LoginUser AS T ON(A.typeId = T.etypeid)
INNER JOIN F_GetManeTypeAll(@OperatorId) AS c ON(t.etypeid = C.typeId)
LEFT JOIN 
(
	SELECT AC.etypeid,AC.stypeid,
	CASE AC.stypeid
		WHEN '00000' THEN '全部分支机构'
		ELSE s.FullName
	END AS sfullname 
	FROM Ac_Account_L AS AC 
	INNER JOIN stype AS S ON(AC.stypeid = S.TypeId)
	--WHERE S.soncount = 0
) AS B ON(A.typeId = B.etypeid)
WHERE A.typeId NOT IN('00000','00001',@OperatorId)
ORDER BY A.typeid,B.stypeid
OPEN AccountLCursor 
FETCH NEXT FROM AccountLCursor INTO @Etypeid,@EUserCode,@EFullName,@Stypeid,@SFullName
WHILE(@@FETCH_STATUS = 0)
BEGIN 
	IF ((SELECT COUNT(1) FROM #TEMP WHERE etypeid = @Etypeid) = 0)
	BEGIN
		INSERT INTO #TEMP(etypeid,eusercode,efullname,stypeid,sfullname)
		VALUES(@etypeid,@EUserCode,@EFullName,@Stypeid,@SFullName)
	END
	ELSE
	BEGIN
		UPDATE #TEMP SET stypeid += ';' +@Stypeid,sfullname += ';' + @SFullName
		WHERE etypeid = @Etypeid
	END
	FETCH NEXT FROM AccountLCursor INTO @Etypeid,@EUserCode,@EFullName,@Stypeid,@SFullName
END
CLOSE AccountLCursor
DEALLOCATE AccountLCursor
--最终显示
SELECT * FROM #TEMP
--------------------------------------------------------------------------------------------------------------------------
DROP TABLE #TEMP
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Web_AccountReportAssistStypeQuery]    Script Date: 06/09/2011 14:50:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AccountReportAssistStypeQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_AccountReportAssistStypeQuery
GO
/*
	作者：董湛
	日期：2013-5-8
	描述：总账报表辅助核算项分支机构选择,从Web_QuerySearchMoreInfo搬移过来
*/

CREATE   PROCEDURE [dbo].Web_AccountReportAssistStypeQuery
(
	@OperatorId		VARCHAR(100),		--操作员Id	
	@bType			VARCHAR(10),		--基本信息类型
	@BTypeLx		VARCHAR(10)='3',
	@TypeId			VARCHAR(100),		--基本信息的Id
	@Filter			VARCHAR(300)='',	--过滤 1、编号  2、名称  3、拼音码 4、联系电话
	@nType			VARCHAR(10)='0',
	@accountassiststype        varchar(50)          --分支机构id   

)
--@encode$--
AS
SET NOCOUNT ON
--特殊处理传bool值的情况
IF LOWER(@nType)='true' OR LOWER(@nType)='false'
	BEGIN
		IF LOWER(@nType)='false'
			SET @nType = '0'
		ELSE
			SET @nType = '1'
	END
--特殊处理[符号
SET @Filter = REPLACE(@Filter,'[','[[]')	
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--************************************************************分支机构基本信息************************************************************
IF @bType = 'S'
	BEGIN
		DECLARE @fzSonNum 	int,
				@fzParId		VARCHAR(200)

		SELECT @fzSonNum = SonNum,@fzParId=ParId FROM SType WHERE TypeId = @TypeId

		CREATE TABLE #SFType
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Deleted		int
		)
        --modify by dongzhan 2013.5.31 配置中新增“独立分支间只允许存在买卖关系”，sysdata下SubName='innerstypesaleralation'
        DECLARE @result VARCHAR(30)
        SELECT @result=SubValue FROM dbo.sysdata WHERE SubName='innerstypesaleralation'
        
        IF @result='1'
			BEGIN
				--判断权限范围
				IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT f.TypeId,f.ParId,f.SonNum,f.UserCode,f.FullName,f.PyCode,f.Deleted FROM F_GetManSTypeAll(@OperatorId) f
					JOIN dbo.SType s ON  s.TypeId=f.TypeId AND s.VerifyID=@accountassiststype
				ELSE
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM SType  WHERE VerifyID=@accountassiststype
	
				  ---特殊情况，A分支机构下的机构B，他的核算是C
	            INSERT INTO #SFType(TypeID,ParId,SonNum,UserCode,FullName,PyCode,Deleted)
	            SELECT  s.TypeId,s.ParId,s.SonNum,s.UserCode,s.FullName,s.PyCode,s.Deleted FROM dbo.SType s JOIN #SFType sf ON sf.ParId=s.TypeId
	            WHERE s.TypeID NOT IN (SELECT TypeID FROM #SFType) AND s.TypeId<>'00000'				
			END
        ELSE
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM F_GetManSTypeAll(@OperatorId)
				ELSE
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM SType
			END
			 
		IF @Filter = ''
			BEGIN
				IF @result='1'
					BEGIN
						IF @TypeId = '00000'
							SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE ParId = '00000' AND TypeId <> '00000' ORDER BY UserCode
						ELSE IF @nType = '0'
							BEGIN
								IF @TypeId = @MSTypeId
									SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE ParId = @fzParId AND TypeId <> '00000' ORDER BY UserCode
							END
						ELSE
							BEGIN
								IF @fzSonNum = 0
									SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE SonNum = 0 AND TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
							END
					END
				ELSE 
					BEGIN
						IF @TypeId = '00000'
							SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE ParId = '00000' AND TypeId <> '00000' ORDER BY UserCode
						ELSE IF @nType = '0'
							BEGIN
								IF @TypeId = @MSTypeId
									SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE ParId = @fzParId AND TypeId <> '00000' ORDER BY UserCode
							END
						ELSE
							BEGIN
								IF @fzSonNum = 0
									SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE SonNum = 0 AND TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
							END
					END
			END
		ELSE
			SELECT	TypeId,SonNum,UserCode,FullName FROM #SFType WHERE SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%') AND TypeId <> '00000'  ORDER BY UserCode

		DROP TABLE #SFType			
	END
	--************************************************************部门基本信息************************************************************
	IF @bType = 'D'
	BEGIN
		IF @TypeId = '' 
			SET @TypeId = '00000'
			
		CREATE TABLE #DType(TypeId VARCHAR(100),ParId VARCHAR(max),SonNum int,UserCode	VARCHAR(256),FullName VARCHAR(256),PyCode VARCHAR(max))
		
		--判断权限范围
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerDTypeId = '00000')
			INSERT INTO #DType SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode FROM F_GetManDTypeAll(@OperatorId)
		ELSE
			INSERT INTO #DType SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode FROM Department

		DECLARE @dSonNum int,@dParId VARCHAR(200)
		SELECT @dSonNum = SonNum,@dParId = ParId FROM Department WHERE TypeId = @TypeId 
		
		IF @Filter = ''
			BEGIN
				IF @TypeId = '00000'
					SELECT TypeId,SonNum,UserCode,FullName FROM #DType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode	
				ELSE IF @nType = '0'
					SELECT TypeId,SonNum,UserCode,FullName FROM #DType WHERE ParId = @dParId AND TypeId <> '00000' ORDER BY UserCode	
				ELSE
					BEGIN
						IF @dSonNum = 0
							SELECT TypeId,SonNum,UserCode,FullName FROM #DType WHERE SonNum = 0 AND TypeId LIKE @TypeId + '%' AND TypeId <> '00000' ORDER BY UserCode	
						ELSE
							SELECT TypeId,SonNum,UserCode,FullName FROM #DType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode	
					END
			END
		ELSE
			SELECT TypeId,SonNum,UserCode,FullName FROM #DType WHERE SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%') ORDER BY UserCode	

		DROP TABLE #DType
	END
	--************************************************************职员机构基本信息************************************************************
	IF @bType = 'E'
	BEGIN
		IF @TypeId = '' SET @TypeId = '00001'
		DECLARE @eSonNum int,
				@eParId  VARCHAR(200)

		CREATE TABLE #Employee
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Deleted		int
		)

		--判断权限范围
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeId = '00001')
			INSERT INTO #Employee(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM F_GetManETypeAll(@OperatorId)
		ELSE
			INSERT INTO #Employee(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM Employee

		SELECT @eSonNum = SonNum,@eParId=ParId FROM #Employee WHERE TypeId = @TypeId 

		IF @Filter = ''
			BEGIN
				IF @TypeId = '00001'
					SELECT	TypeId,SonNum,UserCode,FullName	FROM #Employee WHERE  ParId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode	
				ELSE IF @nType = '0'
					SELECT	TypeId,SonNum,UserCode,FullName	FROM #Employee WHERE  ParId = @eParId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode	
				ELSE
					BEGIN
						IF @eSonNum = 0
							SELECT	TypeId,SonNum,UserCode,FullName	FROM #Employee WHERE SonNum = 0 AND TypeId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode
						ELSE
							SELECT	TypeId,SonNum,UserCode,FullName	FROM #Employee WHERE ParId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode	
					END
			END
		ELSE
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName	FROM #Employee WHERE SonNum = 0 AND TypeId LIKE @METypeId + '%' AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%')
						AND TypeId <> '00000'	
						AND TypeId <> '00001'
				ORDER BY UserCode
			END

		DROP TABLE #Employee
	END
	--************************************************************往来单位机构基本信息************************************************************
	IF @bType = 'B'
	BEGIN
		IF @TypeId = ''
		BEGIN
			IF @BTypeLx = '3' SET @TypeId = '00000'
			ELSE IF @BTypeLx = '1' SET @TypeId = '00001'
			ELSE SET @TypeId = '00002'
		END

		DECLARE @bSonNum 	int,
				@BTypeAll	int,
				@BTypeId	VARCHAR(200),
				@bParId		VARCHAR(200)
		
		IF @BTypeLx = '3'
			SET @BTypeAll = 1
		ELSE
			SELECT	@BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

		CREATE TABLE #BType
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Tel1        varchar(max),
			Tel2        varchar(max),
			Tel3       varchar(max),
			Deleted		int
		)

		--判断权限范围
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerBTypeId = '00001' AND MangerBTypeId2 = '00002')
			INSERT INTO #BType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted FROM F_GetManBTypeAll(@OperatorId)
		ELSE
			INSERT INTO #BType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted FROM BType

		SELECT @bSonNum = SonNum,@bParId=ParId FROM #BType WHERE TypeId = @TypeId

		IF @BTypeAll = 0	--客户和供货商不统一
			BEGIN
				IF @BTypeLx = '1'	--客户
					BEGIN
						IF @Filter = ''
							BEGIN
								IF @nType = '0'
									BEGIN
										IF @TypeId = '00001' 
											SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE TypeId = @TypeId AND TypeId NOT IN ('00000') ORDER BY UserCode
										ELSE
											SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = @bParId AND TypeId NOT IN ('00000') ORDER BY UserCode
									END
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
							END
						ELSE
							SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%' OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000' AND TypeId LIKE '00001%' ORDER BY UserCode
					END
				ELSE				--供货商
					BEGIN
						IF @Filter = ''
							BEGIN
								IF @nType = '0'
									BEGIN
										IF @TypeId = '00002'
											SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE TypeId = @TypeId AND TypeId NOT IN ('00000') ORDER BY UserCode
										ELSE 
											SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = @bParId AND TypeId NOT IN ('00000') ORDER BY UserCode
									END
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
							END
						ELSE
							SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE SonNum = 0 AND SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%' OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000' AND TypeId LIKE '00002%' ORDER BY UserCode
					END
			END
		ELSE				--客户和供货商统一
			BEGIN
				IF @TypeId = '00000'
					BEGIN
						IF @Filter = ''
							SELECT TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = '00000' ORDER BY UserCode
						ELSE
							SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%' OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000' ORDER BY UserCode
					END
				ELSE
					BEGIN
						IF LEN(@TypeId) = 5
							BEGIN
								IF @Filter = ''
									BEGIN
										IF @nType = '0'
											SELECT TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = '00000' ORDER BY UserCode
										ELSE
											BEGIN
												IF LEFT(@TypeId,5)='00001'
													BEGIN
														IF LEN(@TypeId)<LEN('00001')													
															SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE TypeId = @MBTypeId AND TypeId <> '00000' ORDER BY UserCode
														ELSE
															SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
													END
												ELSE
													BEGIN
														IF LEN(@TypeId)<LEN('00002')
															SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE TypeId = @MBTypeId2 AND TypeId <> '00000' ORDER BY UserCode
														ELSE
															SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = @TypeId AND TypeId <> '00000'  ORDER BY UserCode
													END
											END
									END
								ELSE
									BEGIN
										SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%' OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000' ORDER BY UserCode
									END
							END
						ELSE
							BEGIN
								IF @Filter = ''
									BEGIN									
										IF @nType = '0'
											SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = @bParId AND TypeId <> '00000' ORDER BY UserCode
										ELSE
											SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
									END
								ELSE
									BEGIN
										SELECT	TypeId,SonNum,UserCode,FullName FROM #BType WHERE SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%' OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000' ORDER BY UserCode
									END
							END
					END
			END

		DROP TABLE #BType
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AccountStype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_AccountStype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊
	日期：2015-01-12
	描述：分支机构会计科目权限
*/ 
CREATE PROCEDURE Web_AccountStype  
(
	@etypeid	VARCHAR(500),
	@filter		VARCHAR(500),
	@OperatorId	VARCHAR(500)		--操作员Id  
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------  
IF @OperatorID IS NULL RETURN 1  
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),  
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)  
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT  
IF @Re<>0 RETURN @Re  
--------------------------------------------------------------权限检查-------------------------------------------------------  
IF((SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = '00000') = 1)
BEGIN
	SELECT 1 AS selected,TypeId,UserCode,FullName 
	FROM SType AS A
	WHERE soncount = 0 
		AND IsSelfVerify = 1 
		AND EXISTS(SELECT TOP 1 TypeId FROM Ac_Account WHERE StypeId = A.TypeId)
		AND (NOT(@filter <> '') 
				OR(@filter <> '') AND (UserCode LIKE '%' + @filter + '%' OR FullName LIKE '%' + @filter + '%'))
END
ELSE
BEGIN
	SELECT ISNULL(B.flag,0) AS selected,A.TypeId,UserCode,FullName 
	FROM SType AS A
	LEFT JOIN Ac_Account_L AS B ON(A.TypeId = B.stypeid AND B.typeid = '00000' AND B.etypeid = @etypeid)
	WHERE soncount = 0 
		AND IsSelfVerify = 1 
		AND EXISTS(SELECT TOP 1 TypeId FROM Ac_Account WHERE StypeId = A.TypeId)
		AND A.TypeId NOT IN(SELECT stypeid FROM Ac_Account_L WHERE etypeid = @etypeid AND TypeId <> '00000' GROUP BY stypeid)
		AND (NOT(@filter <> '') 
				OR(@filter <> '') AND (A.UserCode LIKE '%' + @filter + '%' OR A.FullName LIKE '%' + @filter + '%'))
END
--------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_AccountSummary]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_AccountSummary]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/05/03
	Description	: 查询未、已分配会计科目
*/
CREATE PROCEDURE Web_AccountSummary
(
	@chvOperatorId		VARCHAR(50),	--当前操作员
	@ShowDistributed	INT,			--0=未分配会计科目,1=已分配会计科目
	@STypeId			VARCHAR(MAX),	--分支机构ID
	@AcId				INT				--科目表treeID
)
--@encode$--
AS 
SET NOCOUNT ON

IF @showdistributed NOT IN (0, 1) 
    BEGIN
        RAISERROR ('参数不正确', 16, 1);
        RETURN -1;
    END


--保存stypeid到临时表;

SELECT  a AS stypeid
INTO    #temp_stype
FROM    dbo.f_split(@stypeid, ',');
 


IF @showdistributed = 1 
    BEGIN
        WITH temp AS (
            SELECT  atypeid
            FROM    BillAtype b
            JOIN    #temp_stype t ON t.stypeid = b.StypeId
            UNION
            SELECT atypeid FROM SType s JOIN #temp_stype ts ON ts.stypeid = s.typeid
            UNION
            SELECT atypeid2 FROM SType s JOIN #temp_stype ts ON ts.stypeid = s.typeid
            UNION
            SELECT atypeid3 FROM SType s JOIN #temp_stype ts ON ts.stypeid = s.typeid
            UNION
            SELECT atypeid4 FROM SType s JOIN #temp_stype ts ON ts.stypeid = s.typeid            
        )
        SELECT  DISTINCT
                a.typeid,
                a.ParId,
                a.UserCode orderUserCode,
                REPLICATE('    ',A.FLeveal-1)+A.UserCode UserCode,
                a.fullname,
                CASE WHEN (a.typeid IN (SELECT atypeid FROM temp)) THEN 1 ELSE 0 END as isset
        FROM    Ac_Account a
        JOIN    #temp_stype s
                ON s.stypeid = a.StypeId
        WHERE   FLeveal > 0 AND a.IsDist = 1 and a.AcId=@AcId
       ORDER by a.UserCode
    END
ELSE 
    BEGIN
	    --没选择分支机构，什么都不返回；
        IF NOT EXISTS ( SELECT  1
                        FROM    #temp_stype ) 
            BEGIN
                SELECT  DISTINCT
                        TypeID,
                        ParId,
                        UserCode,
                        FullName
                FROM    Ac_Account
                WHERE   1 < 1;
            
                RETURN 0;
            END;
    
        WITH    ACTypeId
                  AS (
                      SELECT    typeid
                      FROM      Ac_Account
                      WHERE     stypeid = '00000'
                                AND FLeveal > 0 AND AcId=@AcId
                      EXCEPT
                      (
                       --查询出所有分配了的科目的typeid
                       --过滤出所选择分支机构没有选择的会计科目
                       SELECT   typeid
                       FROM     Ac_Account a
                       JOIN     #temp_stype s
                                ON a.stypeid = s.stypeid AND A.AcId=@AcId
                       GROUP BY typeid
                       HAVING   COUNT(typeid) = (
                                            SELECT
                                            COUNT(1)
                                            FROM
                                            #temp_stype
                                            )
                      )
                     )
            SELECT  DISTINCT
                    ac.TypeID,
                    ac.ParId,
                    Ac.UserCode orderUserCode,
                    REPLICATE('    ',Ac.FLeveal-1)+Ac.UserCode UserCode,
                    ac.FullName
            FROM    Ac_Account ac
            JOIN    ACTypeId aci ON ac.TypeId = aci.typeid
            WHERE   ac.stypeid = '00000'
                    AND FLeveal > 0 AND AC.AcId=@AcId
            ORDER by Ac.UserCode
    END
    drop table #temp_stype
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AccountTimeDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AccountTimeDetailQuery]
GO










/*
	作者：谢吉康
	日期：2003-9-18
	描述：职员和客户的帐龄分析的明晰表
*/

CREATE      PROCEDURE Web_AccountTimeDetailQuery
(
	@StartDate 	VARCHAR(30),
	@EndDate 	VARCHAR(30),
	@ETypeId 	VARCHAR(8000),
	@BTypeId 	VARCHAR(8000),
	@STypeId 	VARCHAR(8000),
	@szOrderBy 	VARCHAR(50)='',
	@OperatorID VARCHAR(512)=''
)
--@encode$--
AS

SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--职员：
CREATE TABLE #GetSelETypeId(TypeId varchar(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--单位：
CREATE TABLE #GetSelBTypeId(TypeId varchar(100))
INSERT INTO #GetSelBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

--获取所有管辖职员-线性表
CREATE TABLE #GetDetailEType(TypeId varchar(100))
INSERT INTO #GetDetailEType(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID)

--获取所有管辖往来单位-线性表
CREATE TABLE #GetDetailBType(TypeId varchar(100))
INSERT INTO #GetDetailBType(TypeId) SELECT TypeId FROM F_GetManDetailBType(@OperatorID)

--获取基本信息的节点ID，带了权限范围
CREATE TABLE #GetAllManagerBaseTypeId(TypeId varchar(100))
INSERT INTO #GetAllManagerBaseTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

--------------------------------------------------------------客户供货商统一检查-------------------------------------------------------
DECLARE @IsBTypeAll bit
EXEC IsBTypeAll @IsBTypeAll OUTPUT
--------------------------------------------------------------客户供货商统一检查-------------------------------------------------------
DECLARE @sql VARCHAR(3000),@where_sql VARCHAR(2000),@length VARCHAR(2)
SELECT @where_sql=''
SELECT @sql=''
IF (ISDATE(RTRIM(@StartDate))=1)
  SELECT @where_sql=' AND b1.BillDate>='+CHAR(39)+@StartDate+CHAR(39)
IF (ISDATE(RTRIM(@EndDate))=1)
  SELECT @where_sql=@where_sql+' AND b1.BillDate<='+CHAR(39)+@EndDate+CHAR(39)
IF RTRIM(@ETypeId)=''
  BEGIN
    SELECT @ETypeId=''
  END

IF RTRIM(@ETypeId)!=''
  SELECT @where_sql=@where_sql+' AND b1.EtypeId IN (SELECT * FROM #GetSelETypeId)'

IF RTRIM(@BTypeId)!=''
  SELECT @where_sql=@where_sql+' AND b1.BTypeId IN (SELECT * FROM F_GetManDetailBType('+char(39)+@OperatorID+char(39)+'))'

DECLARE @szOrderSql VARCHAR(100)
SELECT @szOrderSql=''
IF RTRIM(@szOrderBy)!=''
  SELECT @szOrderSql=' ORDER BY '+@szOrderBy

-- 谢吉康  2003-9-18 
SELECT  @SQL = '
				SELECT	Bil.BillNumberID,
						Bil.BillDate,
						Bil.BillCode,
						Bil.BillType,
						Bil.RedWord,
						Bil.Comment,
						Bil.BTypeId,
						CASE WHEN Bil.IfMulAccount=1 THEN -99999	
						ELSE Bil.ATypeId 
						END AS Atypeid,
						Bil.STypeId,
						ISNULL(SUM(Bil.TotalMoney),0) AS GoodsTotal,
						SUM(ISNULL(Bil.TotalInMoney,0)+ISNULL(Bil.CompleteTotal,0)) AS Sum_Total,
						SUM(ISNULL(Bil.TotalMoney,0)-ISNULL(Bil.TotalInMoney,0)-ISNULL(Bil.CompleteTotal,0)-ISNULL(Bil.preferenceMoney,0)) AS LeftMoney
				FROM 	BillIndex Bil
				INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId				
				WHERE 	Bil.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
						AND Bil.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
						AND Bil.EtypeId IN (SELECT * FROM #GetSelETypeId)
						AND Bil.EtypeID IN (SELECT * FROM #GetDetailEType)
						AND Bil.BtypeID IN (SELECT * FROM #GetSelBTypeId)
						AND Bil.BTypeId IN (SELECT * FROM #GetDetailBType)	
						AND Bil.DTypeId IN (SELECT TypeId FROM #GetAllManagerBaseTypeId)							
						AND Bil.ifcheck = ''t''
						AND Bil.draft = 0 
						AND Bil.RedWord = 0
						AND Bil.IfStopMoney = 0
						AND Bil.BillType IN (11)
						AND Bil.AlertDay <> 9999
						AND Bil.IfYearBill = 0
						AND ISNULL(Bil.TotalMoney,0)-ISNULL(Bil.TotalInMoney,0)-ISNULL(Bil.CompleteTotal,0)-ISNULL(Bil.PreferenceMoney,0)>0
				GROUP BY
						Bil.BillNumberID,
						Bil.BillDate,
						Bil.BillCode,
						Bil.BillType,
						Bil.RedWord,
						Bil.Comment,
						Bil.BTypeId,
						Bil.AtypeID,
						Bil.STypeID,
						Bil.IfMulAccount
				ORDER BY 
						Bil.BillDate'
				
				--PRINT(@SQL)
				EXEC (@SQL)


DROP TABLE #GetSelETypeId,#GetSelBTypeId,#GetManSTypeId,#GetDetailEType,#GetDetailBType,#GetAllManagerBaseTypeId




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AccountTimeLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AccountTimeLineQuery]
GO


/*
	作者：谢吉康
	日期：2003-9-18
	描述：职员和客户的帐龄分析的线性表	
	周华 2012-12-06 添加了时间条件
*/
CREATE	PROCEDURE Web_AccountTimeLineQuery
(
	@chrInputType	CHAR(1),		--  1、相应的统计报表功能识别参数	
	@chvEndDate		VARCHAR(30),	--  2、截止时间
	@chvETypeId		VARCHAR(8000),	--  3、职员类别查询范围父节点 ID
	@chvBTypeId		VARCHAR(8000),	--  4、往来单位类别查询范围父节点 ID
	@STypeId		VARCHAR(8000),	-- 分支机构
    @chvUserCode	VARCHAR(200)	= '',   --  5、编号过滤条件
	@chvFullName	VARCHAR(200)	= '',   --  6、全名过滤条件
	@chvOrderBy		VARCHAR(50)	= '',   --  7、排序条件
	@chvOperatorID	VARCHAR(50),		-- 	8、操作员 ID（作权限范围检查用）
	@datstartdate	VARCHAR(30),
	@datenddate		VARCHAR(30),
	@cid			VARCHAR(10)
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
-- 客户供货商统一判断
DECLARE @chvBTypeAll VARCHAR(50)
SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'

--单位：
CREATE TABLE #GetSelBTypeId(TypeId varchar(100))
--IF @chvBTypeAll = '1'
	INSERT INTO #GetSelBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvBTypeId,2,@chvOperatorID)
--ELSE
	--INSERT INTO #GetSelBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvBTypeId,2,@chvOperatorID) WHERE TypeId LIKE '00001%'
--职员：
CREATE TABLE #GetSelETypeId(TypeId varchar(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvETypeId,3,@chvOperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperatorID)	
	
CREATE TABLE #Dtype (TypeId VARCHAR(100))
INSERT INTO #Dtype SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)

DECLARE @chvSql VARCHAR(MAX),			--Sql字符串
		@chvWhere_sql VARCHAR(2000),	--WHERE子句条件
		@chvEWhere_sql VARCHAR(2000),
        @chvBWhere_sql VARCHAR(2000),
		@chvFieldName VARCHAR(100)		--根据不同的条件替代不同的字段名
		
SELECT @chvWhere_sql = ''
SELECT @chvSql = ''
SELECT @chvEWhere_sql=''
SELECT @chvBWhere_sql=''
SELECT @chvFieldName=''

DECLARE @ExpenseToAr VARCHAR(10)='0'
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'	
	
DECLARE @chvDate VARCHAR(50)

IF (ISDATE(RTRIM(@chvEndDate))=1)
	BEGIN
  		SELECT @chvWhere_sql = @chvWhere_sql+'a.BillDate<='''+@datenddate+''' AND a.BillDate>='''+@datstartdate+'''  '
		SELECT @chvDate=CHAR(39)+@chvEndDate+CHAR(39)
	END


IF RTRIM(@chvUserCode)!=''
	BEGIN
  		SELECT @chvBWhere_sql=@chvBWhere_sql+' AND a.UserCode LIKE ''%'+@chvUserCode+'%'+CHAR(39)

		SELECT @chvEWhere_sql=@chvEWhere_sql+' AND a.UserCode LIKE ''%'+@chvUserCode+'%'+CHAR(39)
	END

IF RTRIM(@chvFullName)!=''
	BEGIN
  		SELECT @chvBWhere_sql=@chvBWhere_sql+' AND a.FullName LIKE ''%'+@chvFullName+'%'+CHAR(39)
		SELECT @chvEWhere_sql=@chvEWhere_sql+' AND a.FullName LIKE ''%'+@chvFullName+'%'+CHAR(39)
	END

create table #billindex
(
	billnumberid int,
	billtype	int,
	alertday   int,
	BillDate  DATETIME,
	BtypeID     VARCHAR(50),
	EtypeID		VARCHAR(50),
	total      NUMERIC(24,10),
	ntotal	   NUMERIC(24,10)
)
DECLARE @billindexSql VARCHAR(8000)
SET @billindexSql='
	INSERT INTO #billindex
	SELECT BillNumberId,BillType,AlertDay,BillDate,BtypeID,EtypeID,
		    CASE WHEN billtype IN (11,160,141,93,85,167,168,172,181,213,312,12,424) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney -isnull(ChargeOffTotal,0)
					 WHEN BillType IN (45,148,149,46,426) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-isnull(ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like ''00001%'' AND '+@ExpenseToAr+'=''1''
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-isnull(ChargeOffTotal,0))
					 WHEN Billtype= 450 
						THEN  totalmoney-CompleteTotal-isnull(ChargeOffTotal,0)
					ELSE 0 
				END AS Total,
			 CASE WHEN billtype IN (11,160,141,93,85,167,168,172,181,213,312,12,424) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-isnull(nChargeOffTotal,0) 
					 WHEN BillType IN (45,148,149,46,426) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-isnull(nChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like ''00001%'' AND '+@ExpenseToAr+'=''1''
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-isnull(nChargeOffTotal,0))
					 WHEN Billtype= 450 
						THEN  ntotalmoney-nCompleteTotal-isnull(nChargeOffTotal,0)
					ELSE 0 
				END AS nTotal	
	FROM  (
		SELECT  dtypeid,BillNumberId,BillType,AlertDay,BillDate,BtypeID,EtypeID,totalmoney,preferencemoney,CompleteTotal,totalinmoney
  	    ,ChargeOffTotal,NTotalMoney,NTotalInMoney,NCompleteTotal,NPreferenceMoney,NChargeOffTotal,ifcheck,RedWord,
  	    ifYearBill,ChargeOffType,IsIni,STypeId,cid FROM dbo.BillIndex
  	    UNION ALL
  	    SELECT  dtypeid,BillNumberId,BillType,9999 AlertDay,BillDate,BtypeID,EtypeID,totalmoney,preferencemoney,CompleteTotal,totalinmoney
  	    ,ChargeOffTotal,NTotalMoney,NTotalInMoney,NCompleteTotal,NPreferenceMoney,NChargeOffTotal,ifcheck,RedWord,
  	    ifYearBill,0 ChargeOffType,IsIni,STypeId,cid FROM dbo.Coupon_BillIndex)  A'

		IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
		IF NOT (@chvBTypeId = '' AND @Mbtypeid = '00001' AND  @Mbtypeid2 = '00002')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelBTypeId b ON a.bTypeId = b.TypeId '	
		IF NOT (@chveTypeId = '' AND @MEtypeid = '00001')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelETypeId e ON A.eTypeId = e.TypeId '	
		IF  @MDtypeid <> '00000'
						SET @billindexSql = @billindexSql + ' INNER JOIN #dtype d ON A.dTypeId = d.TypeId '		
SET @billindexSql=@billindexSql+'
	WHERE  '+@chvWhere_sql+' AND A.BillType in(11,160,141,93,85,167,168,172,181,213,312,45,148,149,36,450,12,46,424,426)
  	    AND ( (A.ifcheck=''t'' AND A.RedWord = 0 AND A.IfYearBill = 0) OR A.isini=1 )  
  	    AND (a.billtype<>450 OR (a.billtype=450 AND a.ChargeOffType in(2,5) ) ) '
  	IF @cid <> 0
			SET	@billindexSql += ' AND a.cid = '+CONVERT(VARCHAR(10), @cid)+''
--PRINT(@billindexSql)						
EXEC(@billindexSql)		
--RETURN 

				
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='isinvoice' and SubValue='1')
BEGIN
	SET @billindexSql='
	INSERT INTO #billindex
	SELECT BillNumberId,BillType,AlertDay,BillDate,BtypeID,EtypeID,
	   a.TaxTotalMoney-a.CompleteTotal  AS Total,
	   a.nTaxTotalMoney-a.nCompleteTotal  AS nTotal
	FROM ReceiptBillIndex A '

		IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
		IF NOT (@chvBTypeId = '' AND @Mbtypeid = '00001' AND  @Mbtypeid2 = '00002')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelBTypeId b ON a.bTypeId = b.TypeId '	
		IF NOT (@chveTypeId = '' AND @MEtypeid = '00001')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelETypeId e ON A.eTypeId = e.TypeId '	
		IF  @MDtypeid <> '00000'
						SET @billindexSql = @billindexSql + ' INNER JOIN #dtype d ON A.dTypeId = d.TypeId '		
	SET @billindexSql=@billindexSql+'
		WHERE  '+@chvWhere_sql+' 
			AND a.billtype=405
			AND ( (A.ifcheck=''t'' AND A.RedWord = 0 AND A.IfYearBill = 0) OR A.isini=1 ) '
	 IF @cid <> 0
			SET	@billindexSql += ' AND a.cid = '+CONVERT(VARCHAR(10), @cid)+''
			
	--PRINT(@billindexSql)						
	EXEC(@billindexSql)		
	--RETURN 
END
--应收增加，应收减少
SET @billindexSql='
	INSERT INTO #billindex
	SELECT a.BillNumberId,a.BillType,ad.AlertDay,a.BillDate,ad.BtypeID,a.EtypeID,
		CASE WHEN a.billtype = 116
				THEN ad.total -ad.CompleteTotal-isnull(ad.ChargeOffTotal,0)
			 WHEN a.billtype = 115
				THEN -(ad.total -ad.CompleteTotal -isnull(ad.ChargeOffTotal,0))
		ELSE 0
		END AS Total,
		CASE WHEN a.billtype = 116
				THEN ad.ntotal -ad.nCompleteTotal-isnull(ad.nChargeOffTotal,0)
			 WHEN a.billtype = 115
				THEN -(ad.ntotal -ad.nCompleteTotal-isnull(ad.nChargeOffTotal,0))
		ELSE 0
		END AS nTotal
	FROM billindex A 
	INNER JOIN AdDebtBill ad ON ad.BillNumberId =a.BillNumberId '

		IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
		IF NOT (@chvBTypeId = '' AND @Mbtypeid = '00001' AND  @Mbtypeid2 = '00002')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelBTypeId b ON ad.bTypeId = b.TypeId '	
		IF NOT (@chveTypeId = '' AND @MEtypeid = '00001')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelETypeId e ON A.eTypeId = e.TypeId '	
		IF  @MDtypeid <> '00000'
						SET @billindexSql = @billindexSql + ' INNER JOIN #dtype d ON A.dTypeId = d.TypeId '		
	SET @billindexSql=@billindexSql+'
		WHERE  '+@chvWhere_sql+' AND  a.billtype in(115,116)
			AND ( (A.ifcheck=''t'' AND A.RedWord = 0 AND A.IfYearBill = 0) OR A.isini=1 ) '
	 IF @cid <> 0
			SET	@billindexSql += ' AND a.cid = '+CONVERT(VARCHAR(10), @cid)+''
			
	--PRINT(@billindexSql)						
	EXEC(@billindexSql)		
	--RETURN 

--业务凭证
SET @billindexSql='
	INSERT INTO #billindex
	SELECT a.BillNumberId,a.BillType,ad.AlertDay,a.BillDate,ad.ATypeID BtypeID,a.EtypeID,
		J_Total-D_Total Total,
		nJ_Total-nD_Total nTotal
	FROM billindex A 
	INNER JOIN accountcredence ad ON ad.BillNumberId =a.BillNumberId '

		IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
		IF @chvBTypeId NOT IN('','00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelBTypeId b ON ad.ATypeID = b.TypeId '	
		IF NOT (@chveTypeId = '' AND @MEtypeid = '00001')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelETypeId e ON ad.eTypeId = e.TypeId '	
		IF  @MDtypeid <> '00000'
						SET @billindexSql = @billindexSql + ' INNER JOIN #dtype d ON ad.dTypeId = d.TypeId '		
	SET @billindexSql=@billindexSql+'
		WHERE  '+@chvWhere_sql+' AND  a.billtype=159 AND  AD.TypeATypeID=33
			AND ( (A.ifcheck=''t'' AND A.RedWord = 0 AND A.IfYearBill = 0) OR A.isini=1 ) '
	 IF @cid <> 0
			SET	@billindexSql += ' AND ad.cid = '+CONVERT(VARCHAR(10), @cid)+''
							
	EXEC(@billindexSql)		
	--RETURN 
--处理账龄分析的具体配置
DECLARE @Col  varchar(100),
		@Col0 varchar(100),
		@Col1 varchar(100),
		@Col2 varchar(100),
		@Col3 varchar(100),
		@Col4 varchar(100),
		@Col5 varchar(100),
		@Col6 varchar(100),
		@Col7 varchar(100),
		@Col8 varchar(100),
		@Col9 varchar(100)

SET @Col = 1
SELECT	@Col0 = ISNULL(Col0,0),
		@Col1 = ISNULL(Col1,0),
		@Col2 = ISNULL(Col2,0),
		@Col3 = ISNULL(Col3,0),
		@Col4 = ISNULL(Col4,0),
		@Col5 = ISNULL(Col5,0),
		@Col6 = ISNULL(Col6,0),
		@Col7 = ISNULL(Col7,0),
		@Col8 = ISNULL(Col8,0),
		@Col9 = ISNULL(Col9,0)
FROM	AccountTimeConfig
WHERE	ETypeId = @chvOperatorId

DECLARE @bitIsLeaf bit
DECLARE @chvLen VARCHAR(20)

IF @chrInputType='B'
	BEGIN
		SELECT @chvSql='
			SELECT	A.*
			FROM	(
						SELECT 	a.fullname,
								a.UserCode,
								a.Sonnum,
								ISNULL(SUM(c.YszkTOTAL),0) AS YszkTOTAL, 																		--应收帐款					
								ISNULL(SUM(c.NYszkTOTAL),0) AS NYszkTOTAL,
								ISNULL(SUM(c.QxnyszkTOTAL),0) AS QxnyszkTOTAL,
								ISNULL(SUM(c.NQxnyszkTOTAL),0) AS NQxnyszkTOTAL,'
						IF @Col0 = '0'
				SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total1),0) AS Total1,
										  ISNULL(SUM(C.NTotal1),0) AS NTotal1,'
			ELSE
				BEGIN
					SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total1),0) AS Total1,
											  ISNULL(SUM(C.NTotal1),0) AS NTotal1,'
					IF @Col2 = '0'
						SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total2),0) AS Total2,
												  ISNULL(SUM(C.NTotal2),0) AS NTotal2,'
					ELSE
						BEGIN
							SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total2),0) AS Total2,
													  ISNULL(SUM(C.NTotal2),0) AS NTotal2,'	
							IF @Col4 = '0'
								SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total3),0) AS Total3,
														  ISNULL(SUM(C.NTotal3),0) AS NTotal3,'	
							ELSE
								BEGIN
									SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total3),0) AS Total3,
															  ISNULL(SUM(C.NTotal3),0) AS NTotal3,'
									IF @Col6 = '0'
										SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total4),0) AS Total4,
																  ISNULL(SUM(C.NTotal4),0) AS NTotal4,'
									ELSE
										BEGIN
											SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total4),0) AS Total4,
																	  ISNULL(SUM(C.NTotal4),0) AS NTotal4,'
											IF @Col8 = '0'
												SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total5),0) AS Total5,
																		  ISNULL(SUM(C.NTotal5),0) AS NTotal5,'
											ELSE
												BEGIN
													SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total5),0) AS Total5,
																			  ISNULL(SUM(C.NTotal5),0) AS NTotal5,'
													SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total6),0) AS Total6,
																			  ISNULL(SUM(C.NTotal6),0) AS NTotal6,'
												END
										END
								END
						END
				END
					SET @chvSQL = @chvSQL + ' A.TypeId
						FROM F_GetManBTypeAll('+char(39)+@chvOperatorID+char(39)+') a 
						LEFT JOIN 
						(
							SELECT  SUM(a.total) AS YszkTOTAL,		
									SUM(a.ntotal) AS NYszkTOTAL,		
									
							--期限内应本币	
									SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')<=a.alertday 
											THEN a.total 
									END)
									AS QxnyszkTOTAL,	
							--期限内应原币
									SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')<=a.alertday
											THEN  a.ntotal 
									END)
									AS NQxnyszkTOTAL, '
									
						--处理具体的时间
						IF @Col0='0'
							SET @chvSQL = @chvSQL + 'SUM (CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')>a.alertday
															THEN  a.total	
														END)
													 AS TOTAL1,
													 SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')>a.alertday 
															THEN  a.ntotal  
													  END)
													 AS NTOTAL1, 
													 '
						ELSE
							BEGIN
								SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday,a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>=1 AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col0+')
															    THEN  a.total END)
														 AS TOTAL1,
														  
														 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday,a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>=1 AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col0+')
															    THEN  a.ntotal END)
														 AS NTOTAL1, 
														 '
								IF @Col2='0'
									SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+')	
																	THEN  a.total  END)
															 AS TOTAL2,
															SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+') 
																	THEN  a.ntotal  END)
															 AS NTOTAL2,
															 ' 
								ELSE
									BEGIN
										SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col2+')
																	   THEN  a.total END)
																  AS TOTAL2,
																 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col2+')
																		THEN  a.ntotal END)
																  AS NTOTAL2,
																  '
										IF @Col4='0'
											SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+')	 
																			  THEN  a.total END)
																	 AS TOTAL3,
																	 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+')
																			  THEN  a.ntotal END)
																	 AS NTOTAL3,
															 '
										ELSE
											BEGIN
												SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col4+') 
																				 THEN  a.total END)
																		 AS TOTAL3,
																		 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col4+')
																				 THEN  a.ntotal END)
																		 AS nTOTAL3,
																		 '
												IF @Col6='0'
													SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+')	
																					 THEN  a.total END)
																			 AS TOTAL4,
																			SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+')
																					 THEN  a.ntotal END)
																			 AS NTOTAL4,  '
												  ELSE
													BEGIN
														SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col6+')   
																					 THEN  a.total END)
																				 AS TOTAL4,
																				SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col6+')	    
																					 THEN  a.ntotal END)
																				 AS NTOTAL4,  '
														IF @Col8='0'
															SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+')	  
																						 THEN  a.total END)
																					 AS TOTAL5,
																					SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+')  
																						 THEN  a.ntotal END)
																					 AS NTOTAL5,  '
														ELSE	
															BEGIN
																SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col8+')   
																								  THEN  a.total END)
																						 AS TOTAL5,
																						SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col8+') 
																								  THEN  a.ntotal END)
																						 AS NTOTAL5,  '
																SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col9+')   
																								 THEN  a.total END)
																						 AS TOTAL6,
																						SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col9+')   
																								 THEN  a.ntotal END)
																						 AS NTOTAL6,'
													END
											END
									END
							END
					END
								--增加往来单位
					SET @chvSQL = @chvSQL + ' a.BTypeId 
						FROM #BillIndex a 
						GROUP BY a.BTypeID
							) c	ON a.typeid=c.btypeid
						WHERE 	a.sonnum=0 '+@chvBWhere_sql+' 								
						GROUP BY
								a.typeid,
								a.fullname,
								a.Sonnum,
								a.UserCode,
								a.ARLimitTime
				)A
		WHERE	A.YszkTOTAL<>0 '
			if @Col!='0'			
			set @chvSql+=' OR a.total1<>0'
			if @Col2!='0'			
			set @chvSql+=' OR a.total2<>0'
			if @Col4!='0'			
			set @chvSql+=' OR a.total3<>0'
			if @Col6!='0'			
			set @chvSql+=' OR a.total4<>0'
			if @Col9!='0'			
			set @chvSql+=' OR a.total5<>0'
			if @Col9!='0'			
			set @chvSql+=' OR a.total6<>0'
					
			
		set @chvSql+=' 	ORDER BY a.UserCode'

			--print @chvSql
			EXEC(@chvSql)
	END
--====================================备注=======
--应收帐款				YszkTOTAL
--本期应收				BqysTOTAL
--本期实收[计算回款率]	BqssTOTAL
--期限内应收款			QxnyszkTOTAL
--30天内				TOTAL60
--60天内				TOTAL60
--90-180天内			TOTAL90_180
--210-360天内			TOTAL210_360
--360天以上				TOTAL360
--===============================================
--===============================================职员帐龄分析
IF @chrInputType='E'
	BEGIN
		SELECT @chvSql='
			SELECT	A.*
			FROM	(
						SELECT 	A.UserCode,
								A.fullname,
								A.Sonnum,
								ISNULL(SUM(c.YszkTOTAL),0) AS YszkTOTAL, 																		--应收帐款					
								ISNULL(SUM(c.NYszkTOTAL),0) AS NYszkTOTAL,
								ISNULL(SUM(c.QxnyszkTOTAL),0) AS QxnyszkTOTAL,
								ISNULL(SUM(c.NQxnyszkTOTAL),0) AS NQxnyszkTOTAL,'
						IF @Col0 = '0'
				SET @chvSQL += ' ISNULL(SUM(C.Total1),0) AS Total1,
								 ISNULL(SUM(C.NTotal1),0) AS NTotal1,'
			ELSE
				BEGIN
					SET @chvSQL += ' ISNULL(SUM(C.Total1),0) AS Total1,
									 ISNULL(SUM(C.NTotal1),0) AS NTotal1,'
					IF @Col2 = '0'
						SET @chvSQL += ' ISNULL(SUM(C.Total2),0) AS Total2,
										 ISNULL(SUM(C.NTotal2),0) AS NTotal2,'
					ELSE
						BEGIN
							SET @chvSQL += ' ISNULL(SUM(C.Total2),0) AS Total2,
											 ISNULL(SUM(C.NTotal2),0) AS NTotal2,'
							IF @Col4 = '0'
								SET @chvSQL += ' ISNULL(SUM(C.Total3),0) AS Total3,
												 ISNULL(SUM(C.NTotal3),0) AS NTotal3,'	
							ELSE
								BEGIN
									SET @chvSQL +=' ISNULL(SUM(C.Total3),0) AS Total3,
													ISNULL(SUM(C.NTotal3),0) AS NTotal3,'
									IF @Col6 = '0'
										SET @chvSQL += ' ISNULL(SUM(C.Total4),0) AS Total4,
														 ISNULL(SUM(C.NTotal4),0) AS NTotal4,'
									ELSE
										BEGIN
											SET @chvSQL += ' ISNULL(SUM(C.Total4),0) AS Total4,
															 ISNULL(SUM(C.NTotal4),0) AS NTotal4,'
											IF @Col8 = '0'
												SET @chvSQL += ' ISNULL(SUM(C.Total5),0) AS Total5,
																 ISNULL(SUM(C.NTotal5),0) AS NTotal5,'
											ELSE
												BEGIN
													SET @chvSQL +=  ' ISNULL(SUM(C.Total5),0) AS Total5,
																	  ISNULL(SUM(C.NTotal5),0) AS NTotal5,'
													SET @chvSQL += ' ISNULL(SUM(C.Total6),0) AS Total6,
																	 ISNULL(SUM(C.NTotal6),0) AS NTotal6,'
												END
										END
								END
						END
				END
					SET @chvSQL = @chvSQL + ' A.TypeId 
			
						FROM F_GetManETypeAll('+char(39)+@chvOperatorID+char(39)+') a 
							LEFT JOIN 
									(
										SELECT  SUM(a.total) AS YszkTOTAL,		
												SUM(a.ntotal) AS NYszkTOTAL,		
												
										--期限内应本币	
												SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')<=a.alertday 
														THEN a.total 
												END)
												AS QxnyszkTOTAL,	
										--期限内应原币
												SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')<=a.alertday
														THEN  a.ntotal 
												END)
												AS NQxnyszkTOTAL, '
												
									--处理具体的时间
									IF @Col0='0'
										SET @chvSQL = @chvSQL + 'SUM (CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')>a.alertday
																		THEN  a.total	
																	END)
																 AS TOTAL1,
																 SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')>a.alertday 
																		THEN  a.ntotal  
																  END)
																 AS NTOTAL1, 
																 '
									ELSE
										BEGIN
											SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday,a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>=1 AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col0+')
																			THEN  a.total END)
																	 AS TOTAL1,
																	  
																	 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday,a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>=1 AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col0+')
																			THEN  a.ntotal END)
																	 AS NTOTAL1, 
																	 '
											IF @Col2='0'
												SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+')	
																				THEN  a.total  END)
																		 AS TOTAL2,
																		SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+') 
																				THEN  a.ntotal  END)
																		 AS NTOTAL2,
																		 ' 
											ELSE
												BEGIN
													SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col2+')
																				   THEN  a.total END)
																			  AS TOTAL2,
																			 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col2+')
																					THEN  a.ntotal END)
																			  AS NTOTAL2,
																			  '
													IF @Col4='0'
														SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+')	 
																						  THEN  a.total END)
																				 AS TOTAL3,
																				 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+')
																						  THEN  a.ntotal END)
																				 AS NTOTAL3,
																		 '
													ELSE
														BEGIN
															SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col4+') 
																							 THEN  a.total END)
																					 AS TOTAL3,
																					 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col4+')
																							 THEN  a.ntotal END)
																					 AS nTOTAL3,
																					 '
															IF @Col6='0'
																SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+')	
																								 THEN  a.total END)
																						 AS TOTAL4,
																						SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+')
																								 THEN  a.ntotal END)
																						 AS NTOTAL4,  '
															  ELSE
																BEGIN
																	SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col6+')   
																								 THEN  a.total END)
																							 AS TOTAL4,
																							SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col6+')	    
																								 THEN  a.ntotal END)
																							 AS NTOTAL4,  '
																	IF @Col8='0'
																		SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+')	  
																									 THEN  a.total END)
																								 AS TOTAL5,
																								SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+')  
																									 THEN  a.ntotal END)
																								 AS NTOTAL5,  '
																	ELSE	
																		BEGIN
																			SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col8+')   
																											  THEN  a.total END)
																									 AS TOTAL5,
																									SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col8+') 
																											  THEN  a.ntotal END)
																									 AS NTOTAL5,  '
																			SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col9+')   
																											 THEN  a.total END)
																									 AS TOTAL6,
																									SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col9+')   
																											 THEN  a.ntotal END)
																									 AS NTOTAL6,'
																END
														END
												END
										END
								END
								--增加经手人ID
								SET @chvSQL = @chvSQL + ' a.ETypeId'		
			
								SET @chvSQL = @chvSQL + ' 
								FROM 	#BillIndex  a	
								GROUP BY a.ETypeID
								) c	ON a.typeid=c.Etypeid
						WHERE 	a.sonnum=0 '+@chvEWhere_sql+' 								
						GROUP BY
								a.typeid,
								a.fullname,
								a.Sonnum,
								a.UserCode
				)A
			WHERE	A.YszkTOTAL<>0 '
			if @Col!='0'			
			set @chvSql+=' OR a.total1<>0'
			if @Col2!='0'			
			set @chvSql+=' OR a.total2<>0'
			if @Col4!='0'			
			set @chvSql+=' OR a.total3<>0'
			if @Col6!='0'			
			set @chvSql+=' OR a.total4<>0'
			if @Col9!='0'			
			set @chvSql+=' OR a.total5<>0'
			if @Col9!='0'			
			set @chvSql+=' OR a.total6<>0'
					
			
		set @chvSql+=' 	ORDER BY a.UserCode'

			--print @chvSql
			EXEC(@chvSql)
	END

DROP TABLE #GetSelBTypeId,#GetSelETypeId,#GetManSTypeId,#Dtype




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AccountTimeListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_AccountTimeListQuery
GO


/*
	作者：谢吉康
	日期：2003-9-18
	描述：职员和客户的帐龄分析的数量树型表
	
	2013-04-28 周华 修改时间条件
*/
CREATE PROCEDURE Web_AccountTimeListQuery
(
	@chrInputType	CHAR(1),		--  1、相应的统计报表功能识别参数	
	@chvEndDate		VARCHAR(30),	--  2、截止时间
	@chvBTypeId		VARCHAR(8000),	--  3、往来单位类别查询范围父节点 ID
	@chvETypeId		VARCHAR(8000),	--  4、职员类别查询范围父节点 ID
	@STypeId		VARCHAR(8000),	--  分支机构
    @chvUserCode	VARCHAR(200)	= '',   --  5、编号过滤条件
	@chvFullName	VARCHAR(200)	= '',   --  6、全名过滤条件
	@chvOrderBy		VARCHAR(50)	= '',   --  7、排序条件
	@chvOperatorID	VARCHAR(50),		-- 	8、操作员 ID（作权限范围检查用）
	@datstartdate	VARCHAR(30),
	@datenddate		VARCHAR(30),
	@cid			VARCHAR(10)			--NID
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--单位：
CREATE TABLE #GetSelBTypeId(TypeId varchar(100))

INSERT INTO #GetSelBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvBTypeId,2,@chvOperatorID)

--职员：
CREATE TABLE #GetSelETypeId(TypeId varchar(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@chvETypeId,3,@chvOperatorID)


CREATE TABLE #Dtype (TypeId VARCHAR(100))
INSERT INTO #Dtype SELECT TypeId FROM F_GetAllManagerBaseTypeId('00000',9,@chvOperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperatorID)	

DECLARE @chvSql VARCHAR(MAX),			--Sql字符串
		@chvWhere_sql VARCHAR(2000),	--WHERE子句条件
        @chvEWhere_sql VARCHAR(1000),
        @chvBWhere_sql VARCHAR(1000),
		@chvFieldName VARCHAR(100)		--根据不同的条件替代不同的字段名
		
	DECLARE @ExpenseToAr VARCHAR(10)='0'
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'	
		
SELECT @chvWhere_sql = ''
SELECT @chvSql = ''
SELECT @chvBWhere_sql=''
SELECT @chvEWhere_sql=''
SELECT @chvFieldName=''

IF @chvBTypeId='' 
	SET @chvBTypeId='00000'
	
IF @chrInputType='E' AND  ISNULL(@chvETypeId,'')=''
	SET @chvETypeId='00001' 

IF (ISDATE(RTRIM(@datenddate))=1)
	BEGIN
  		SELECT @chvWhere_sql = @chvWhere_sql+'a.BillDate<='+CHAR(39)+@datenddate+CHAR(39)+' AND a.BillDate>='''+@datstartdate+''' ';
	END


IF RTRIM(@chvUserCode)!=''
	BEGIN
  		SELECT @chvBWhere_sql=@chvBWhere_sql+' AND a.UserCode LIKE '''+@chvUserCode+'%'+CHAR(39)
		SELECT @chvEWhere_sql=@chvEWhere_sql+' AND a.UserCode LIKE '''+@chvUserCode+'%'+CHAR(39)
	END

IF RTRIM(@chvFullName)!=''
	BEGIN
  		SELECT @chvBWhere_sql=@chvBWhere_sql+' AND a.FullName LIKE '''+@chvFullName+'%'+CHAR(39)
		SELECT @chvEWhere_sql=@chvEWhere_sql+' AND a.FullName LIKE '''+@chvFullName+'%'+CHAR(39)
	END
	
create table #billindex
(
	billnumberid int,
	billtype	int,
	alertday   int,
	BillDate  DATETIME,
	BtypeID     VARCHAR(50),
	EtypeID		VARCHAR(50),
	total      NUMERIC(24,10),
	ntotal	   NUMERIC(24,10)
)
DECLARE @billindexSql VARCHAR(8000)
SET @billindexSql='
	INSERT INTO #billindex
	SELECT BillNumberId,BillType,AlertDay,BillDate,BtypeID,EtypeID,
		    CASE WHEN billtype IN (11,160,141,93,85,167,168,172,181,213,312,12,424) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney -isnull(ChargeOffTotal,0)
					 WHEN BillType IN (45,148,149,46,426) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-isnull(ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like ''00001%'' AND '+@ExpenseToAr+'=''1''
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-isnull(ChargeOffTotal,0))
					 WHEN Billtype= 450 
						THEN  totalmoney-CompleteTotal-isnull(ChargeOffTotal,0)
					ELSE 0 
				END AS Total,
			 CASE WHEN billtype IN (11,160,141,93,85,167,168,172,181,213,312,12,424) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-isnull(nChargeOffTotal,0) 
					 WHEN BillType IN (45,148,149,46,426) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-isnull(nChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like ''00001%'' AND '+@ExpenseToAr+'=''1''
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-isnull(nChargeOffTotal,0))
					 WHEN Billtype= 450 
						THEN  ntotalmoney-nCompleteTotal-isnull(nChargeOffTotal,0)
					ELSE 0 
				END AS nTotal	
	FROM      
  	    (SELECT  dtypeid,BillNumberId,BillType,AlertDay,BillDate,BtypeID,EtypeID,totalmoney,preferencemoney,CompleteTotal,totalinmoney
  	    ,ChargeOffTotal,NTotalMoney,NTotalInMoney,NCompleteTotal,NPreferenceMoney,NChargeOffTotal,ifcheck,RedWord,
  	    ifYearBill,ChargeOffType,IsIni,STypeId,cid FROM dbo.BillIndex
  	    UNION ALL
  	    SELECT  dtypeid,BillNumberId,BillType,9999 AlertDay,BillDate,BtypeID,EtypeID,totalmoney,preferencemoney,CompleteTotal,totalinmoney
  	    ,ChargeOffTotal,NTotalMoney,NTotalInMoney,NCompleteTotal,NPreferenceMoney,NChargeOffTotal,ifcheck,RedWord,
  	    ifYearBill,0 ChargeOffType,IsIni,STypeId,cid FROM dbo.Coupon_BillIndex)  A'

		IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
		IF NOT (@chvBTypeId = '' AND @Mbtypeid = '00001' AND  @Mbtypeid2 = '00002')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelBTypeId b ON a.bTypeId = b.TypeId '	
		IF NOT (@chveTypeId = '' AND @MEtypeid = '00001')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelETypeId e ON A.eTypeId = e.TypeId '	
		IF  @MDtypeid <> '00000'
						SET @billindexSql = @billindexSql + ' INNER JOIN #dtype d ON A.dTypeId = d.TypeId '		
SET @billindexSql=@billindexSql+'
	WHERE  '+@chvWhere_sql+' AND A.BillType in(11,160,141,93,85,167,168,172,181,213,312,45,148,149,36,450,12,46,424,426)
  	    AND ( (A.ifcheck=''t'' AND A.RedWord = 0 AND A.IfYearBill = 0) OR A.isini=1 ) 
  	    AND (a.billtype<>450 OR (a.billtype=450 AND a.ChargeOffType in(2,5) ) ) '
  	IF @cid <> 0
			SET	@billindexSql += ' AND a.cid = '+CONVERT(VARCHAR(10), @cid)+''

--PRINT(@billindexSql)						
EXEC(@billindexSql)		
--RETURN 
				
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='isinvoice' and SubValue='1')
BEGIN
	SET @billindexSql='
	INSERT INTO #billindex
	SELECT BillNumberId,BillType,AlertDay,BillDate,BtypeID,EtypeID,
	   a.TaxTotalMoney-a.CompleteTotal-isnull(a.ChargeOffTotal,0)  AS Total,
	   a.nTaxTotalMoney-a.nCompleteTotal-isnull(a.nChargeOffTotal,0)  AS nTotal
	FROM ReceiptBillIndex A '

		IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
		IF NOT (@chvBTypeId = '' AND @Mbtypeid = '00001' AND  @Mbtypeid2 = '00002')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelBTypeId b ON a.bTypeId = b.TypeId '	
		IF NOT (@chveTypeId = '' AND @MEtypeid = '00001')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelETypeId e ON A.eTypeId = e.TypeId '	
		IF  @MDtypeid <> '00000'
						SET @billindexSql = @billindexSql + ' INNER JOIN #dtype d ON A.dTypeId = d.TypeId '		
	SET @billindexSql=@billindexSql+'
		WHERE  '+@chvWhere_sql+' 
			AND a.billtype=405
			AND ( (A.ifcheck=''t'' AND A.RedWord = 0 AND A.IfYearBill = 0) OR A.isini=1 ) '
	 IF @cid <> 0
			SET	@billindexSql += ' AND a.cid = '+CONVERT(VARCHAR(10), @cid)+''
			
	--PRINT(@billindexSql)						
	EXEC(@billindexSql)		
	--RETURN 
END
--应收增加，应收减少
SET @billindexSql='
	INSERT INTO #billindex
	SELECT a.BillNumberId,a.BillType,ad.AlertDay,a.BillDate,ad.BtypeID,a.EtypeID,
		CASE WHEN a.billtype = 116
				THEN ad.total -ad.CompleteTotal-isnull(ad.ChargeOffTotal,0)
			 WHEN a.billtype = 115
				THEN -(ad.total -ad.CompleteTotal -isnull(ad.ChargeOffTotal,0))
		ELSE 0
		END AS Total,
		CASE WHEN a.billtype = 116
				THEN ad.ntotal -ad.nCompleteTotal-isnull(ad.nChargeOffTotal,0)
			 WHEN a.billtype = 115
				THEN -(ad.ntotal -ad.nCompleteTotal-isnull(ad.nChargeOffTotal,0))
		ELSE 0
		END AS nTotal
	FROM billindex A 
	INNER JOIN AdDebtBill ad ON ad.BillNumberId =a.BillNumberId '

		IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
		IF NOT (@chvBTypeId = '' AND @Mbtypeid = '00001' AND  @Mbtypeid2 = '00002')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelBTypeId b ON ad.BtypeID = b.TypeId '	
		IF NOT (@chveTypeId = '' AND @MEtypeid = '00001')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelETypeId e ON A.eTypeId = e.TypeId '	
		IF  @MDtypeid <> '00000'
						SET @billindexSql = @billindexSql + ' INNER JOIN #dtype d ON A.dTypeId = d.TypeId '		
	SET @billindexSql=@billindexSql+'
		WHERE  '+@chvWhere_sql+' AND a.billtype in(115,116)
			AND ( (A.ifcheck=''t'' AND A.RedWord = 0 AND A.IfYearBill = 0) OR A.isini=1 ) '
	 IF @cid <> 0
			SET	@billindexSql += ' AND a.cid = '+CONVERT(VARCHAR(10), @cid)+''
			
	--PRINT(@billindexSql)						
	EXEC(@billindexSql)		
	--RETURN 
	
--业务凭证
SET @billindexSql='
	INSERT INTO #billindex
	SELECT a.BillNumberId,a.BillType,ad.AlertDay,a.BillDate,ad.ATypeID BtypeID,a.EtypeID,
		J_Total-D_Total Total,
		nJ_Total-nD_Total nTotal
	FROM billindex A 
	INNER JOIN accountcredence ad ON ad.BillNumberId =a.BillNumberId '

		IF NOT (@STypeId = '' AND @MStypeid = '00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
		IF @chvBTypeId NOT IN('','00000')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelBTypeId b ON ad.ATypeID = b.TypeId '	
		IF NOT (@chveTypeId = '' AND @MEtypeid = '00001')
						SET @billindexSql = @billindexSql + ' INNER JOIN #GetSelETypeId e ON ad.eTypeId = e.TypeId '	
		IF  @MDtypeid <> '00000'
						SET @billindexSql = @billindexSql + ' INNER JOIN #dtype d ON ad.dTypeId = d.TypeId '		
	SET @billindexSql=@billindexSql+'
		WHERE  '+@chvWhere_sql+' AND a.billtype=159 AND  AD.TypeATypeID=33
			AND ( (A.ifcheck=''t'' AND A.RedWord = 0 AND A.IfYearBill = 0) OR A.isini=1 ) '
	 IF @cid <> 0
			SET	@billindexSql += ' AND aD.cid = '+CONVERT(VARCHAR(10), @cid)+''
							
	EXEC(@billindexSql)		
	--RETURN 

  --SELECT * FROM #billindex
--处理账龄分析的具体配置
DECLARE @Col  varchar(100),
		@Col0 varchar(100),
		@Col1 varchar(100),
		@Col2 varchar(100),
		@Col3 varchar(100),
		@Col4 varchar(100),
		@Col5 varchar(100),
		@Col6 varchar(100),
		@Col7 varchar(100),
		@Col8 varchar(100),
		@Col9 varchar(100)

SET @Col = 1
SELECT	@Col0 = ISNULL(Col0,0),
		@Col1 = ISNULL(Col1,0),
		@Col2 = ISNULL(Col2,0),
		@Col3 = ISNULL(Col3,0),
		@Col4 = ISNULL(Col4,0),
		@Col5 = ISNULL(Col5,0),
		@Col6 = ISNULL(Col6,0),
		@Col7 = ISNULL(Col7,0),
		@Col8 = ISNULL(Col8,0),
		@Col9 = ISNULL(Col9,0)
FROM	AccountTimeConfig
WHERE	ETypeId = @chvOperatorId


DECLARE @bitIsLeaf bit
DECLARE @chvLen VARCHAR(20)

IF @chrInputType='B'
	BEGIN	
		--该节点是否是叶节点 1表示是,否则为0
		SELECT @bitIsLeaf=	CASE 
								WHEN EXISTS((SELECT * FROM BType WHERE TypeID=@chvBTypeId AND SonNum=0)) THEN 1 
								ELSE 0		
					        END
					     
		IF @bitIsLeaf = 1	--子节点
			SELECT @chvFieldName='a.TypeID = '''+@chvBTypeId+''''
		ELSE
			SELECT @chvFieldName='a.ParId = '''+@chvBTypeId+''''
		
		IF @chvBTypeId='00000' 
			SET @chvLen='5'
		ELSE
			SET @chvLen=CAST(LEN(@chvBTypeId)+5 AS VARCHAR(20))		

		SELECT @chvSql='
			SELECT 	a.usercode,
					a.fullname,
					a.Sonnum,
					ISNULL(SUM(c.YszkTOTAL),0) AS YszkTOTAL, 																		--应收帐款
					ISNULL(SUM(c.NYszkTOTAL),0) AS NYszkTOTAL, 
					ISNULL(SUM(c.QxnyszkTOTAL),0) AS QxnyszkTOTAL,
					ISNULL(SUM(c.NQxnyszkTOTAL),0) AS NQxnyszkTOTAL,'
			IF @Col0 = '0'
				SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total1),0) AS Total1,
										  ISNULL(SUM(C.NTotal1),0) AS NTotal1,'
			ELSE
				BEGIN
					SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total1),0) AS Total1,
											  ISNULL(SUM(C.NTotal1),0) AS NTotal1,'
					IF @Col2 = '0'
						SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total2),0) AS Total2,
												  ISNULL(SUM(C.NTotal2),0) AS NTotal2,'
					ELSE
						BEGIN
							SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total2),0) AS Total2,
													  ISNULL(SUM(C.NTotal2),0) AS NTotal2,'	
							IF @Col4 = '0'
								SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total3),0) AS Total3,
														  ISNULL(SUM(C.NTotal3),0) AS NTotal3,'	
							ELSE
								BEGIN
									SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total3),0) AS Total3,
															  ISNULL(SUM(C.NTotal3),0) AS NTotal3,'
									IF @Col6 = '0'
										SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total4),0) AS Total4,
																  ISNULL(SUM(C.NTotal4),0) AS NTotal4,'
									ELSE
										BEGIN
											SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total4),0) AS Total4,
																	  ISNULL(SUM(C.NTotal4),0) AS NTotal4,'
											IF @Col8 = '0'
												SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total5),0) AS Total5,
																		  ISNULL(SUM(C.NTotal5),0) AS NTotal5,'
											ELSE
												BEGIN
													SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total5),0) AS Total5,
																			  ISNULL(SUM(C.NTotal5),0) AS NTotal5,'
													SET @chvSQL = @chvSQL + ' ISNULL(SUM(C.Total6),0) AS Total6,
																			  ISNULL(SUM(C.NTotal6),0) AS NTotal6,'
												END
										END
								END
						END
				END
		SET @chvSQL = @chvSQL + ' A.TypeId
			FROM F_GetManBTypeAll('+char(39)+@chvOperatorID+char(39)+') a 
				LEFT JOIN 
				(
					SELECT  SUM(a.total) AS YszkTOTAL,		
							SUM(a.ntotal) AS NYszkTOTAL,		
							
					--期限内应本币	
							SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')<=a.alertday 
									THEN a.total 
							END)
							AS QxnyszkTOTAL,	
					--期限内应原币
							SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')<=a.alertday
									THEN  a.ntotal 
							END)
							AS NQxnyszkTOTAL, '
							
						--处理具体的时间
						IF @Col0='0'
							SET @chvSQL = @chvSQL + 'SUM (CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')>a.alertday
															THEN  a.total	
														END)
													 AS TOTAL1,
													 SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')>a.alertday 
															THEN  a.ntotal  
													  END)
													 AS NTOTAL1, 
													 '
						ELSE
							BEGIN
								SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday,a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>=1 AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col0+')
															    THEN  a.total END)
														 AS TOTAL1,
														  
														 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday,a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>=1 AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col0+')
															    THEN  a.ntotal END)
														 AS NTOTAL1, 
														 '
								IF @Col2='0'
									SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+')	
																	THEN  a.total  END)
															 AS TOTAL2,
															SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+') 
																	THEN  a.ntotal  END)
															 AS NTOTAL2,
															 ' 
								ELSE
									BEGIN
										SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col2+')
																	   THEN  a.total END)
																  AS TOTAL2,
																 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col2+')
																		THEN  a.ntotal END)
																  AS NTOTAL2,
																  '
										IF @Col4='0'
											SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+')	 
																			  THEN  a.total END)
																	 AS TOTAL3,
																	 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+')
																			  THEN  a.ntotal END)
																	 AS NTOTAL3,
															 '
										ELSE
											BEGIN
												SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col4+') 
																				 THEN  a.total END)
																		 AS TOTAL3,
																		 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col4+')
																				 THEN  a.ntotal END)
																		 AS nTOTAL3,
																		 '
												IF @Col6='0'
													SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+')	
																					 THEN  a.total END)
																			 AS TOTAL4,
																			SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+')
																					 THEN  a.ntotal END)
																			 AS NTOTAL4,  '
												  ELSE
													BEGIN
														SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col6+')   
																					 THEN  a.total END)
																				 AS TOTAL4,
																				SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col6+')	    
																					 THEN  a.ntotal END)
																				 AS NTOTAL4,  '
														IF @Col8='0'
															SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+')	  
																						 THEN  a.total END)
																					 AS TOTAL5,
																					SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+')  
																						 THEN  a.ntotal END)
																					 AS NTOTAL5,  '
														ELSE	
															BEGIN
																SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col8+')   
																								  THEN  a.total END)
																						 AS TOTAL5,
																						SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col8+') 
																								  THEN  a.ntotal END)
																						 AS NTOTAL5,  '
																SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col9+')   
																								 THEN  a.total END)
																						 AS TOTAL6,
																						SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col9+')   
																								 THEN  a.ntotal END)
																						 AS NTOTAL6,'
													END
											END
									END
							END
					END
					--增加往来单位
					SET @chvSQL = @chvSQL + ' a.BTypeId 
					FROM #BillIndex a 
					GROUP BY a.BtypeId
				) c	ON a.typeid=LEFT(c.btypeid,LEN(a.TypeID))
			WHERE 	'+@chvFieldName + @chvBWhere_sql +' 					
			GROUP BY
					a.typeid,
					a.fullname,
					a.Sonnum,
					a.UserCode
			ORDER BY a.UserCode' 
			
			--PRINT(@chvSql)
			EXEC(@chvSql)
	END		
--====================================备注=======
--应收帐款				YszkTOTAL
--本期应收				BqysTOTAL
--本期实收[计算回款率]	BqssTOTAL
--期限内应收款			QxnyszkTOTAL
--30天内				TOTAL60
--60天内				TOTAL60
--90-180天内			TOTAL90_180
--210-360天内			TOTAL210_360
--360天以上				TOTAL360
--===============================================
--===============================================职员帐龄分析
IF @chrInputType='E'
	BEGIN	
		--该节点是否是叶节点 1表示是,否则为0
		SELECT @bitIsLeaf=CASE 
			WHEN EXISTS((SELECT * FROM EMPLOYEE WHERE TypeID=@chvETypeId AND SonNum=0)) THEN 1 ELSE 0
        END
		IF @bitIsLeaf=0
			SELECT @chvFieldName='a.ParID ='''+@chvETypeId+''''
		ELSE
			SELECT @chvFieldName='a.TypeID ='''+@chvETypeId+''''
		IF @chvBTypeId='00000' 
			SET @chvLen='5'
		ELSE
			SET @chvLen=CAST(LEN(@chvETypeId)+5 AS VARCHAR(20))		
		SELECT @chvSql='
			SELECT 	a.usercode,
					A.fullname,
					A.Sonnum,
					ISNULL(SUM(c.YszkTOTAL),0) AS YszkTOTAL, 			--应收帐款
					ISNULL(SUM(c.NYszkTOTAL),0) AS NYszkTOTAL,			
					ISNULL(SUM(c.QxnyszkTOTAL),0) AS QxnyszkTOTAL,
					ISNULL(SUM(c.NQxnyszkTOTAL),0) AS NQxnyszkTOTAL,'
			IF @Col0 = '0'
				SET @chvSQL += ' ISNULL(SUM(C.Total1),0) AS Total1,
								 ISNULL(SUM(C.NTotal1),0) AS NTotal1,'
			ELSE
				BEGIN
					SET @chvSQL += ' ISNULL(SUM(C.Total1),0) AS Total1,
									 ISNULL(SUM(C.NTotal1),0) AS NTotal1,'
					IF @Col2 = '0'
						SET @chvSQL += ' ISNULL(SUM(C.Total2),0) AS Total2,
										 ISNULL(SUM(C.NTotal2),0) AS NTotal2,'
					ELSE
						BEGIN
							SET @chvSQL += ' ISNULL(SUM(C.Total2),0) AS Total2,
											 ISNULL(SUM(C.NTotal2),0) AS NTotal2,'
							IF @Col4 = '0'
								SET @chvSQL += ' ISNULL(SUM(C.Total3),0) AS Total3,
												 ISNULL(SUM(C.NTotal3),0) AS NTotal3,'	
							ELSE
								BEGIN
									SET @chvSQL +=' ISNULL(SUM(C.Total3),0) AS Total3,
													ISNULL(SUM(C.NTotal3),0) AS NTotal3,'
									IF @Col6 = '0'
										SET @chvSQL += ' ISNULL(SUM(C.Total4),0) AS Total4,
														 ISNULL(SUM(C.NTotal4),0) AS NTotal4,'
									ELSE
										BEGIN
											SET @chvSQL += ' ISNULL(SUM(C.Total4),0) AS Total4,
															 ISNULL(SUM(C.NTotal4),0) AS NTotal4,'
											IF @Col8 = '0'
												SET @chvSQL += ' ISNULL(SUM(C.Total5),0) AS Total5,
																 ISNULL(SUM(C.NTotal5),0) AS NTotal5,'
											ELSE
												BEGIN
													SET @chvSQL +=  ' ISNULL(SUM(C.Total5),0) AS Total5,
																	  ISNULL(SUM(C.NTotal5),0) AS NTotal5,'
													SET @chvSQL += ' ISNULL(SUM(C.Total6),0) AS Total6,
																	 ISNULL(SUM(C.NTotal6),0) AS NTotal6,'
												END
										END
								END
						END
				END
		SET @chvSQL = @chvSQL + ' A.TypeId 	
			FROM F_GetManETypeAll('+char(39)+@chvOperatorID+char(39)+') a 
			LEFT JOIN 
				(
					SELECT  SUM(a.total) AS YszkTOTAL,		
							SUM(a.ntotal) AS NYszkTOTAL,		
							
					--期限内应本币	
							SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')<=a.alertday 
									THEN a.total 
							END)
							AS QxnyszkTOTAL,	
					--期限内应原币
							SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')<=a.alertday
									THEN  a.ntotal 
							END)
							AS NQxnyszkTOTAL, '
							
						--处理具体的时间
						IF @Col0='0'
							SET @chvSQL = @chvSQL + 'SUM (CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')>a.alertday
															THEN  a.total	
														END)
													 AS TOTAL1,
													 SUM(CASE WHEN  DATEDIFF(DAY,a.BillDate,'+CHAR(39)+@chvEndDate+CHAR(39)+')>a.alertday 
															THEN  a.ntotal  
													  END)
													 AS NTOTAL1, 
													 '
						ELSE
							BEGIN
								SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday,a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>=1 AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col0+')
															    THEN  a.total END)
														 AS TOTAL1,
														  
														 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday,a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>=1 AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col0+')
															    THEN  a.ntotal END)
														 AS NTOTAL1, 
														 '
								IF @Col2='0'
									SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+')	
																	THEN  a.total  END)
															 AS TOTAL2,
															SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+') 
																	THEN  a.ntotal  END)
															 AS NTOTAL2,
															 ' 
								ELSE
									BEGIN
										SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col2+')
																	   THEN  a.total END)
																  AS TOTAL2,
																 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col1+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col2+')
																		THEN  a.ntotal END)
																  AS NTOTAL2,
																  '
										IF @Col4='0'
											SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+')	 
																			  THEN  a.total END)
																	 AS TOTAL3,
																	 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+')
																			  THEN  a.ntotal END)
																	 AS NTOTAL3,
															 '
										ELSE
											BEGIN
												SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col4+') 
																				 THEN  a.total END)
																		 AS TOTAL3,
																		 SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col3+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col4+')
																				 THEN  a.ntotal END)
																		 AS nTOTAL3,
																		 '
												IF @Col6='0'
													SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+')	
																					 THEN  a.total END)
																			 AS TOTAL4,
																			SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+')
																					 THEN  a.ntotal END)
																			 AS NTOTAL4,  '
												  ELSE
													BEGIN
														SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col6+')   
																					 THEN  a.total END)
																				 AS TOTAL4,
																				SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col5+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col6+')	    
																					 THEN  a.ntotal END)
																				 AS NTOTAL4,  '
														IF @Col8='0'
															SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+')	  
																						 THEN  a.total END)
																					 AS TOTAL5,
																					SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+')  
																						 THEN  a.ntotal END)
																					 AS NTOTAL5,  '
														ELSE	
															BEGIN
																SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col8+')   
																								  THEN  a.total END)
																						 AS TOTAL5,
																						SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col7+' AND DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')<='+@Col8+') 
																								  THEN  a.ntotal END)
																						 AS NTOTAL5,  '
																SET @chvSQL = @chvSQL + 'SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col9+')   
																								 THEN  a.total END)
																						 AS TOTAL6,
																						SUM(CASE WHEN (DATEDIFF(DAY, DATEADD(DAY, a.alertday, a.BillDate), '+CHAR(39)+@chvEndDate+CHAR(39)+')>='+@Col9+')   
																								 THEN  a.ntotal END)
																						 AS NTOTAL6,'
													END
											END
									END
							END
					END
					--增加经手人ID
					SET @chvSQL = @chvSQL + ' a.ETypeId'		

					SET @chvSQL = @chvSQL + ' 
						FROM 	#BillIndex a	
						GROUP BY a.ETypeID
							
					) c	ON a.typeid=LEFT(c.Etypeid,LEN(a.TypeID))
			WHERE 	'+@chvFieldName + @chvEWhere_sql +' 					
			GROUP BY
					a.typeid,
					a.fullname,
					a.Sonnum,
					a.UserCode
			ORDER BY a.UserCode'
			
			--PRINT(@chvSql)
			EXEC(@chvSql)
END

DROP TABLE #GetSelBTypeId,#GetSelETypeId,#GetManSTypeId,#dtype




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AccountTreeViewData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_AccountTreeViewData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊
	日期：2014-11-26
	描述：会计科目多级权限-取树
*/ 
CREATE PROCEDURE Web_AccountTreeViewData  
(  
	@type		INT,				--0为添加,1为查看
	@etypeid	VARCHAR(500),		--职员Id
	@ifstype	INT					--是否A8
)
--@encode$--
AS 
--------------------------------------------------------------------------------------------------------------------------
IF(@type = 0)
BEGIN
	SELECT TypeId,parid,FullName,
	CASE 
		WHEN FullName='资产' THEN 1
        WHEN FullName='负债' THEN 2
        WHEN FullName='共同' THEN 3
        WHEN FullName='权益' THEN 4
        WHEN FullName='成本' THEN 5
        WHEN FullName='损益' THEN 6
    END AS ordercol 
    FROM Ac_Account WHERE ParId='00000' AND StypeId = '00000' 
    ORDER BY ordercol
	RETURN
END
IF(@ifstype = 0)
BEGIN
	SELECT TypeId + '0' AS TypeId,parid,
	CASE 
		WHEN (SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid IN('00000','00001') AND typeid = '00000') >= 1 THEN FullName + '（全部）'
		WHEN (SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = '00001' AND typeid = A.typeid) >= 1 THEN FullName + '（全部）'
		ELSE FullName
	END AS FullName,
	StypeId,'C' AS sparid,
	CASE 
		WHEN FullName='资产' THEN 1
        WHEN FullName='负债' THEN 2
        WHEN FullName='共同' THEN 3
        WHEN FullName='权益' THEN 4
        WHEN FullName='成本' THEN 5
        WHEN FullName='损益' THEN 6
    END AS ordercol 
    FROM Ac_Account AS A WHERE ParId='00000' AND StypeId = '00001'
    ORDER BY ordercol
	RETURN
END
------------------------------------------------------------临时表------------------------------------------------------------
--最终数据
CREATE TABLE #TEMP
(
	stypeid VARCHAR(500),
	typeid VARCHAR(500),
	parid VARCHAR(500),
	fullname VARCHAR(500),
	sParid VARCHAR(10),
	ordercol VARCHAR(10),
	etypeid VARCHAR(500)
)
--------------------------------------------------------------------------------------------------------------------------
--有用所有分支机构科目权限
IF((SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = '00000' AND typeid = '00000') = 1)
BEGIN
	INSERT INTO #TEMP(stypeid,typeid,parid,fullname,sParid,ordercol,etypeid)
	SELECT A.TypeId AS stypeid,A.TypeId,'00000' AS parid,A.FullName + '（全部）','F' AS sParid,0 AS ordercol,@etypeid 
	FROM stype AS A 
	INNER JOIN F_GetManSTypeAll(@etypeid) AS B ON(A.TypeId = B.TypeId)
	WHERE A.soncount = 0 AND A.IsSelfVerify = 1 AND EXISTS(SELECT TOP 1 TypeId FROM Ac_Account WHERE StypeId = A.TypeId)
	
	--分支机构下要显示的科目
	INSERT INTO #TEMP(stypeid,typeid,parid,fullname,sParid,ordercol,etypeid)
	SELECT DISTINCT A.typeid AS stypeid,
	CASE 
		WHEN C.TypeId IS NULL THEN C.typeid + '0' 
		ELSE C.TypeId + '0' 
	END AS typeid,
	A.typeid as parid,
	C.FullName + '（全部）' AS fullname,
	'C' AS sParid,
	CASE 
		WHEN C.FullName='资产' THEN 1
		WHEN C.FullName='负债' THEN 2
		WHEN C.FullName='共同' THEN 3
		WHEN C.FullName='权益' THEN 4
		WHEN C.FullName='成本' THEN 5
		WHEN C.FullName='损益' THEN 6
	END AS ordercol,A.etypeid 
	FROM #TEMP AS A 
	INNER JOIN Ac_Account AS C ON(A.stypeid = C.StypeId AND C.typeid LIKE C.TypeId + '%' AND C.ParId='00000')
END
ELSE --不拥有所有分支机构科目权限
BEGIN
	--已分配科目的分支机构
	INSERT INTO #TEMP(stypeid,typeid,parid,fullname,sParid,ordercol,etypeid)
	SELECT A.TypeId AS stypeid,A.TypeId,'00000' AS parid,A.FullName,'F' AS sParid,0 AS ordercol,B.etypeid 
	FROM stype AS A 
	INNER JOIN 
	(
		SELECT A.etypeid,A.stypeid
		FROM Ac_Account_L AS A
		INNER JOIN F_GetManSTypeAll(@etypeid) AS B ON(A.stypeid = B.TypeId)
		GROUP BY A.etypeid,A.stypeid
	) AS B ON(A.TypeId = B.stypeid)
	WHERE B.etypeid = @etypeid

	--递归写入当前职员有分配科目分支机构的科目类
	DECLARE @stypeid VARCHAR(100)
	DECLARE InTypeidCursor CURSOR FOR
	SELECT stypeid 
	FROM stype AS A 
	INNER JOIN 
	(
		SELECT A.etypeid,A.stypeid
		FROM Ac_Account_L AS A
		INNER JOIN F_GetManSTypeAll(@etypeid)  AS B ON(A.stypeid = B.TypeId)
		GROUP BY A.etypeid,A.stypeid
	) AS B ON(A.TypeId = B.stypeid)
	WHERE B.etypeid = @etypeid
	OPEN InTypeidCursor
	FETCH NEXT FROM InTypeidCursor INTO @stypeid
	WHILE(@@FETCH_STATUS = 0)
	BEGIN 
		--有当前分支机构全部科目权限
		IF((SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = @stypeid AND typeid = '00000') >= 1)
		BEGIN
			UPDATE #TEMP SET fullname = fullname + '（全部）' WHERE stypeid = @stypeid AND sParid = 'F' AND ordercol = 0
			INSERT INTO #TEMP(stypeid,typeid,parid,fullname,sParid,ordercol,etypeid)
			SELECT @stypeid AS stypeid,
			CASE 
				WHEN TypeId IS NULL THEN typeid + '0' 
				ELSE TypeId + '0' 
			END AS typeid,
			@stypeid as parid,
			FullName + '（全部）' AS fullname,
			'C' AS sParid,
			CASE 
				WHEN FullName='资产' THEN 1
				WHEN FullName='负债' THEN 2
				WHEN FullName='共同' THEN 3
				WHEN FullName='权益' THEN 4
				WHEN FullName='成本' THEN 5
				WHEN FullName='损益' THEN 6
			END AS ordercol,
			@etypeid AS etypeid 
			FROM Ac_Account 
			WHERE StypeId = @stypeid AND ParId='00000'
		END
		ELSE --没有当前分支机构全部科目权限
		BEGIN
			INSERT INTO #TEMP(stypeid,typeid,parid,fullname,sParid,ordercol,etypeid)
			SELECT B.stypeid AS stypeid,
			CASE 
				WHEN A.TypeId IS NULL THEN A.typeid + '0' 
				ELSE A.TypeId + '0' 
			END AS typeid,
			B.stypeid as parid,
			CASE 
				WHEN (SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @etypeid AND stypeid = @stypeid AND typeid = A.typeid) >= 1
				THEN A.FullName + '（全部）'
				ELSE A.FullName
			END AS fullname,
			'C' AS sParid,
			CASE 
				WHEN A.FullName='资产' THEN 1
				WHEN A.FullName='负债' THEN 2
				WHEN A.FullName='共同' THEN 3
				WHEN A.FullName='权益' THEN 4
				WHEN A.FullName='成本' THEN 5
				WHEN A.FullName='损益' THEN 6
			END AS ordercol,
			B.etypeid 
			FROM Ac_Account AS A
			INNER JOIN Ac_Account_L AS B ON(A.StypeId = B.stypeid AND B.typeid LIKE A.TypeId + '%')
			WHERE A.ParId = '00000' AND A.StypeId = @stypeid AND B.etypeid = @etypeid
			GROUP BY B.stypeid,A.TypeId,B.etypeid,A.FullName
		END
		FETCH NEXT FROM InTypeidCursor INTO @stypeid
	END
	CLOSE InTypeidCursor
	DEALLOCATE InTypeidCursor
	
	--如果通过【科目类别权限设置】设置了全部科目类，在查看时就将分支机构后加上（全部）
	UPDATE #TEMP 
	SET fullname = CASE 
						WHEN (SELECT COUNT(1) FROM Ac_Account_L 
							WHERE etypeid = @etypeid 
								AND stypeid = @stypeid 
								AND typeid IN('00001','00002','00003','00004','00005','00006')
						 ) = 6
						THEN fullname + '（全部）'
						ELSE fullname
				   END
	WHERE stypeid = @stypeid AND sParid = 'F' AND ordercol = 0
END

SELECT * FROM #TEMP 
ORDER BY stypeid,ordercol
--------------------------------------------------------------------------------------------------------------------------
DROP TABLE #TEMP
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AcCurrencyIsUse]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROC [dbo].[Web_AcCurrencyIsUse]
GO


-- ===================================================
-- 描述：	判断币别是否使用
-- 时间：	2012-05-30
-- 作者：	古丽娟
-- ==================================================
CREATE PROC [dbo].[Web_AcCurrencyIsUse]
(
	@Cid VARCHAR(50)			--币别
)   
--@encode$--   
AS 
SET NOCOUNT ON       
	IF EXISTS(SELECT TOP 1 1 FROM Ac_Voucher_Bill WHERE Cid IS NOT NULL AND Cid<>'')
		RETURN 1
 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(select * from dbo.sysobjects where id=object_id(N'Web_AcFixedAssetsQuery') and OBJECTPROPERTY(id,N'isProcedure')=1)
DROP PROC dbo.Web_AcFixedAssetsQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：查询固定资产信息	
-- 时间：2012-04-18	
-- 作者：古丽娟	
-- 参数:@Deleted是否删除 1：已删除 0 未删除
-- ========================================================================
CREATE PROCEDURE Web_AcFixedAssetsQuery
(	
	@operatorid VARCHAR(50),	--操作人
	@usercode VARCHAR(200)='',	--固定资产编号
	@fullname VARCHAR(200)=''	--固定资产名称
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @Sql VARCHAR(4000),@IFDeleted VARCHAR(50)
Select @sql='SELECT 
			f.Nid,
			f.TypeId,
			f.STypeId,
			f.Parid,
			S.FullName stypename,
			f.UserCode, 
			f.FullName,
			f.Comment,
			f.AtypeID,
			f.DepATypeId,
			f.DisATypeId,
			f.Deleted
	FROM Ac_FixedAssets f
	LEFT JOIN SType s ON S.ATypeID=F.STypeId
	LEFT JOIN Ac_Account ac1 ON ac1.TypeId=f.AtypeID
	WHERE 1=1 and f.typeid<>''0000100002'''
IF(ISNULL(@usercode,'')<>'')
	SET @Sql+=' AND f.usercode like ''%'+@usercode+'%'''
IF(ISNULL(@fullname,'')<>'')
	SET @Sql+=' AND f.fullname like ''%'+@fullname+'%'''
SET @Sql+= 'order by f.usercode'
exec(@Sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_AcGeneralLedger]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_AcGeneralLedger]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===============================================
--  create by：glj
--	date：2014-12-16
--	function：查询总分类账
--=================================================
CREATE PROCEDURE WEB_AcGeneralLedger
(
   @STypeId 		VARCHAR(50),	--分支机构ID
   @ATypeId			VARCHAR(MAX),	--会计科目ID(可以多值，以,为分隔符 例：xxx,xxx,xx)        
   @Cid				INT,			--币别ID 
   @Leveal		    INT,			--科目级别  
   @Fyear			INT,			--年度           
   @FPeriodStart    INT,			--起始期间
   @FPeriodEnd      INT,			--结束期间
   @IsPost			BIT,			--是否显示未过账凭证 1：是 0：否
   @IsPeriodNull    BIT,			--本期无发生额不显示 1：是 0：否      
   @IsBalanceNull   BIT,			--包括余额为0的科目  1：是 0：否
   @IsYearNull		BIT,			--本年无发生额不显示 1：是 0：否
   @IsDetail		BIT,			--只显示明细
   @chvOperatorID	VARCHAR(50),	---操作员ID
   @IsShowPL		INT				--是否包含结转损益
)
--@encode$--
AS 
SET NOCOUNT ON

BEGIN--===================================基本数据临时表生成【BEGIN】===========================================
DECLARE	@SQL	VARCHAR(MAX)--	--动态sql
--判断分支机构权限
IF NOT EXISTS(SELECT * FROM dbo.F_GetManDetailAllSType(@chvOperatorID) WHERE TypeId=@STypeId)
	SET @STypeId=''
	
--建立临时余额表，权限范围内所有科目
CREATE TABLE #tempAcBalance
(
	STypeId				VARCHAR(50),	--分支机构
	ATypeId				VARCHAR(50),	--科目
	Fdc					INT,			--科目方向
	FYear				INT,	--年度
	FPeriod				INT,	--期间
	Cid					INT,			--币种
	FBeginBalanceFor	NUMERIC(24, 10)  DEFAULT 0,--期初
	FBeginBalanceForQty NUMERIC(24, 10)  DEFAULT 0,--期初数量
	FDebitFor			NUMERIC(24, 10)  DEFAULT 0,--本期借方
	FDebitForQty		NUMERIC(24, 10)  DEFAULT 0,--本期借方数量
	FCreditFor			NUMERIC(24, 10)  DEFAULT 0,--本期贷方
	FCreditForQty		NUMERIC(24, 10)  DEFAULT 0,--本期贷方数量
	FEndBalanceFor		NUMERIC(24, 10)  DEFAULT 0,--期末
	FEndBalanceForQty	NUMERIC(24, 10)  DEFAULT 0,--期末数量
	FYtdDebitFor		NUMERIC(24, 10)  DEFAULT 0,--本年借方
	FYtdDebitForQty		NUMERIC(24, 10)  DEFAULT 0,--本年借方数量
	FYtdCreditFor		NUMERIC(24, 10)  DEFAULT 0,--本年贷方
	FYtdCreditForQty	NUMERIC(24, 10)  DEFAULT 0--本年贷方数量
)

--查询条件期间起止具体时间 【WEB_SubsiAcBalanceQueryFromVoucher】 公用，查询具体日期
DECLARE 
	@BillDateStart	DATETIME,
	@BillDateEnd	DATETIME,
	@T_ATypeId		VARCHAR(MAX)=''
	
SELECT @BillDateStart=FBegin FROM Ac_Period WHERE FYear=@Fyear AND FPeriod=@FPeriodStart
SELECT @BillDateEnd=FEnd FROM Ac_Period WHERE FYear=@Fyear AND FPeriod=@FPeriodEnd		

IF ISNULL(@ATypeId,'')<>'' AND NOT EXISTS(SELECT TOP 1 1 FROM Ac_Account WHERE StypeId=@STypeId AND TypeId=@ATypeId AND SonNum=0)
	BEGIN
		SELECT @T_ATypeId+=A.TypeId+',' 
		FROM Ac_Account A
		INNER JOIN F_TreeAccount(@chvOperatorID,@STypeId) T ON T.Stypeid=A.StypeId AND T.Typeid=A.TypeId AND A.SonNum=0
		INNER JOIN f_split(@ATypeId,',') F ON a.TypeId=F.a  
		
		IF(ISNULL(@T_ATypeId,'')<>'')
			SET @T_ATypeId=SUBSTRING(@T_ATypeId,1,LEN(@T_ATypeId)-1)
	END
ELSE 
	SET @T_ATypeId=@ATypeId	
	
INSERT INTO #tempAcBalance
EXEC WEB_SubsiAcBalanceQueryFromVoucher @StypeId,@T_ATypeId,@Fyear,@BilldateStart,@BilldateEnd,@Cid,@IsPost,@chvOperatorID

--币种
CREATE TABLE #Currency(ID INT IDENTITY(1,1),Cid INT,UserCode VARCHAR(200),FullName VARCHAR(200),Rate  NUMERIC(24, 10) )
IF @Cid<>0
BEGIN
	INSERT INTO #Currency(Cid,UserCode,FullName,Rate)
	SELECT CId,UserCode,FullName,Rate FROM Ac_Currency 
	WHERE 
		((@Cid<>-1 AND CId=@Cid) 
		OR @Cid=-1)
END
IF(@Cid IN(0,-1))
BEGIN
	INSERT INTO #Currency(Cid,UserCode,FullName,Rate)
	SELECT 0 CId,'self' UserCode,'综合本位币' FullName,Rate FROM Ac_Currency WHERE Sysrow=1
END

DECLARE @I	INT=@FPeriodStart
CREATE TABLE #FP(FPeriod INT)
WHILE(@I<=@FPeriodEnd)
BEGIN
	INSERT INTO #FP(FPeriod)
	SELECT @I
	SET @I+=1
END

--符合条件的科目表
IF(ISNULL(@T_ATypeId,'')='')
	SET @T_ATypeId=@ATypeId
CREATE TABLE #Account(TypeID VARCHAR(50),UserCode VARCHAR(200),OrderUserCode VARCHAR(MAX),FullName VARCHAR(200),Fdc INT,FPeriod INT,CID INT)
SET @SQL='
INSERT INTO #Account(TypeID,UserCode,OrderUserCode,FullName,Fdc,FPeriod,CID)
SELECT	DISTINCT
	F.TypeID,
	F.UserCode,
	F.OrderUserCode,
	F.FullName,
	F.Fdc,
	P.FPeriod,
	C.CID 
FROM #Currency C,#FP P,(
	SELECT
		A.TypeId,
		REPLICATE(''	'',A.Leveal-1) + A.UserCode UserCode,
		A.UserCode OrderUserCode,
		A.FullName,
		A.Fdc
	FROM Ac_Account A
	INNER JOIN F_TreeAccount('''+@chvOperatorID+''','''+@STypeId+''') F ON F.StypeId=A.StypeId AND F.TypeId=A.TypeId AND A.Leveal>1 AND A.FLeveal<='+CAST(@Leveal AS VARCHAR(2))
	IF(@IsDetail=1)--只显示明细
		SET @SQL+=' AND A.SonNum=0'
	SET @SQL+=CHAR(13)
	IF ISNULL(@T_ATypeId,'')<>''
		SET @SQL+='	INNER JOIN f_split('''+@T_ATypeId+''','','') F1 ON F1.a LIKE A.TypeId+''%'''+CHAR(13)
	SET @SQL+='
	GROUP BY 
		A.TypeId,
		A.UserCode,
		A.FullName,
		A.Fdc,
		A.Leveal
) F
GROUP BY 
	F.TypeID,
	F.UserCode,
	F.OrderUserCode,
	F.FullName,
	F.Fdc,
	P.FPeriod,
	C.CID 
	'
EXEC(@SQL)
--===================================基本数据临时表生成【END】==================================================
END;


BEGIN --===================================业务处理【BEGIN】==========================================================
--不包含结转损益数据单独处理 by:2014-08-29
--凭证表临时表
CREATE TABLE #VoucherBill
(
	ATypeId		VARCHAR(50),				--科目ID
	CID			INT,						--币种
	FYear		INT,						--年度
	FPeriod		INT,						--期间
	FDebitFor	 NUMERIC(24, 10)  DEFAULT 0,	--借方
	FCreditFor	 NUMERIC(24, 10)  DEFAULT 0		--贷方
)

IF(@IsShowPL=1)
BEGIN
	IF(@Cid<>0)
	BEGIN
		INSERT INTO #VoucherBill(ATypeId,CID,FYear,FPeriod,FDebitFor,FCreditFor)
		SELECT
			B.ATypeId,
			B.Cid,
			B.FYear,
			B.FPeriod,
			ISNULL(SUM(B.FDebitTotalFor),0) FDebitFor,
			ISNULL(SUM(B.FCreditTotalFor),0) FCreditFor
		FROM Ac_Voucher_Bill B
		INNER JOIN #Account F ON F.TypeID=B.ATypeId AND F.FPeriod=B.FPeriod AND F.CID=B.Cid AND B.STypeId=@STypeId
		INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.VoucherType=2 AND V.FChecked<>-1 AND ((@IsPost=0 AND V.IfCheck='T') OR @IsPost=1) AND B.FYear=@Fyear AND B.FPeriod BETWEEN @FPeriodStart AND @FPeriodEnd AND (@Cid=-1 OR (@Cid<>-1 AND B.Cid=@Cid))
		GROUP BY 
			B.ATypeId,
			B.FYear,
			B.FPeriod,
			B.Cid
	END
	IF(@Cid IN(0,-1))
	BEGIN
		INSERT INTO #VoucherBill(ATypeId,CID,FYear,FPeriod,FDebitFor,FCreditFor)
		SELECT
			B.ATypeId,
			0 CID,
			B.FYear,
			B.FPeriod,
			ISNULL(SUM(B.FDebitTotal),0) FDebitFor,
			ISNULL(SUM(B.FCreditTotal),0) FCreditFor
		FROM Ac_Voucher_Bill B
		INNER JOIN #Account F ON F.TypeID=B.ATypeId AND F.FPeriod=B.FPeriod AND F.CID=B.Cid AND B.STypeId=@STypeId
		INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId  AND V.VoucherType=2 AND V.FChecked<>-1 AND ((@IsPost=0 AND V.IfCheck='T') OR @IsPost=1) AND B.FYear=@Fyear AND B.FPeriod BETWEEN @FPeriodStart AND @FPeriodEnd
		GROUP BY 
			B.ATypeId,
			B.FYear,
			B.FPeriod
	END
	
	UPDATE #tempAcBalance 
	SET
		FDebitFor-=F.FDebitFor,
		FCreditFor-=F.FCreditFor,
		FEndBalanceFor-=(SELECT CASE WHEN T.Fdc=1 THEN SUM(FDebitFor-FCreditFor) ELSE SUM(FCreditFor-FDebitFor) END FROM #VoucherBill WHERE ATypeId=T.ATypeId AND CID=T.Cid AND FPeriod<=T.FPeriod),
		FYtdDebitFor-=(SELECT SUM(FDebitFor) FROM #VoucherBill WHERE ATypeId=T.ATypeId AND CID=T.Cid AND FPeriod<=T.FPeriod),
		FYtdCreditFor-=(SELECT SUM(FCreditFor) FROM #VoucherBill WHERE ATypeId=T.ATypeId AND CID=T.Cid AND FPeriod<=T.FPeriod)	
	FROM #tempAcBalance T
	INNER JOIN (SELECT ATypeId,CID,FPeriod,SUM(FDebitFor) FDebitFor, SUM(FCreditFor) FCreditFor FROM #VoucherBill GROUP BY ATypeId,FPeriod,CID) F ON T.ATypeId=F.ATypeId AND F.FPeriod=T.FPeriod  AND F.CID=T.Cid
	
END

--不显示本期没有发生额的科目     
IF(@IsPeriodNull=1)
	BEGIN
		DELETE FROM #tempAcBalance WHERE ATypeId IN(
			SELECT ATypeId 
			FROM (
				SELECT 
					ATypeId,
					SUM(FDebitFor) FDebitFor,
					SUM(FCreditFor) FCreditFor
				FROM #tempAcBalance 
				WHERE 
					FPeriod BETWEEN @FPeriodStart AND @FPeriodEnd 
					AND ((@Cid=-1 AND CID=0) OR (@Cid<>-1 AND CID=@Cid)) 
					
				GROUP BY ATypeId 
			) F WHERE FDebitFor=0 AND FCreditFor=0
			GROUP BY ATypeId
		)
	END
--不包括余额为零的科目     
IF(@IsBalanceNull=0)
	BEGIN
		DELETE FROM #tempAcBalance WHERE ATypeId IN(
			SELECT ATypeId 
			FROM (
				SELECT 
					ATypeId,
					SUM(FEndBalanceFor) FEndBalanceFor
				FROM #tempAcBalance 
				WHERE 
					FPeriod BETWEEN @FPeriodStart AND @FPeriodEnd 
					AND ((@Cid=-1 AND CID=0) OR (@Cid<>-1 AND CID=@Cid))
				GROUP BY ATypeId 
			) F WHERE  FEndBalanceFor=0
			GROUP BY ATypeId
		)
	END	
--不显示本年没有发生额的科目
IF(@IsYearNull=1)
	BEGIN
		DELETE FROM #tempAcBalance WHERE ATypeId IN(
			SELECT ATypeId 
			FROM (
				SELECT 
					ATypeId,
					SUM(FYtdDebitFor) FYtdDebitFor,
					SUM(FYtdCreditFor) FYtdCreditFor
				FROM #tempAcBalance 
				WHERE 
					FPeriod=@FPeriodEnd 
					AND ((@Cid=-1 AND CID=0) OR (@Cid<>-1 AND CID=@Cid)) 
				GROUP BY ATypeId 
			) F  WHERE FYtdDebitFor=0 AND FYtdCreditFor=0
			GROUP BY ATypeId
		)
	END


--符合条件的数据表	
CREATE TABLE #General
(
	TypeId			VARCHAR(50),		--科目ID
	CID				INT,				--币种ID
	UserCode		VARCHAR(200),		--科目编号
	OrderUserCode	VARCHAR(MAX),		--科目编号
	FullName		VARCHAR(200),		--科目名称
	FPeriod 		INT,				--期间
	Summary			VARCHAR(400),		--摘要
	FDebitTotal		 NUMERIC(24, 10) ,		--借方
	FCreditTotal	 NUMERIC(24, 10) ,		--贷方
	Fdc				VARCHAR(10),		--方向
	Total			 NUMERIC(24, 10) 		--金额
)
INSERT INTO #General(TypeId,CID,UserCode,OrderUserCode,FullName,FPeriod,Summary,FDebitTotal,FCreditTotal,Fdc,Total)
SELECT
	A.TypeID,
	B.Cid,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	@FPeriodStart FPeriod,
	'期初余额' Summary,
	0 FDebitTotal,
	0 FCreditTotal, 
	CASE 
		WHEN SUM(CASE WHEN A.Fdc=B.Fdc THEN B.FBeginBalanceFor ELSE -B.FBeginBalanceFor END)=0 THEN '平' 
		WHEN A.FDC=1 THEN '借'
		ELSE '贷'
	END AS FDC,
	SUM(CASE WHEN A.Fdc<>B.Fdc THEN -B.FBeginBalanceFor ELSE B.FBeginBalanceFor END) Total
FROM #Account A
INNER JOIN #tempAcBalance B ON B.ATypeId LIKE A.TypeID+'%' AND FYear=@Fyear AND B.FPeriod=@FPeriodStart AND B.FPeriod=A.FPeriod AND A.CID=B.Cid
GROUP BY 
	A.TypeID,
	B.Cid,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	A.Fdc
UNION ALL
SELECT
	A.TypeID,
	B.Cid,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	A.FPeriod,
	'本期合计' Summary,
	SUM(B.FDebitFor) FDebitTotal,
	SUM(B.FCreditFor) FCreditTotal, 
	CASE 
		WHEN SUM(CASE WHEN A.Fdc=B.Fdc THEN B.FEndBalanceFor ELSE -B.FEndBalanceFor END)=0 THEN '平' 
		WHEN A.FDC=1 THEN '借'
		ELSE '贷'
	END AS FDC,
	SUM(CASE WHEN A.Fdc<>B.Fdc THEN -B.FEndBalanceFor ELSE B.FEndBalanceFor END ) Total
FROM #Account A
INNER JOIN #tempAcBalance B ON B.ATypeId LIKE A.TypeID+'%' AND A.FPeriod=B.FPeriod AND A.CID=B.Cid
GROUP BY 
	A.TypeID,
	B.Cid,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	A.FPeriod,
	A.Fdc
UNION ALL
SELECT
	A.TypeID,
	B.Cid,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	A.FPeriod,
	'本年累计' Summary,
	SUM(B.FYtdDebitFor) FDebitTotal,
	SUM(B.FYtdCreditFor) FCreditTotal, 
	CASE 
		WHEN SUM(CASE WHEN A.Fdc=B.Fdc THEN B.FEndBalanceFor ELSE -B.FEndBalanceFor END)=0 THEN '平' 
		WHEN A.FDC=1 THEN '借'
		ELSE '贷'
	END AS FDC,
	SUM(CASE WHEN A.Fdc<>B.Fdc THEN -B.FEndBalanceFor ELSE B.FEndBalanceFor END) Total
FROM #Account A
INNER JOIN #tempAcBalance B ON B.ATypeId LIKE A.TypeID+'%' AND B.FPeriod=A.FPeriod AND A.CID=B.Cid
GROUP BY
	A.TypeID,
	B.Cid,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	A.Fdc,
	A.FPeriod
--===================================业务处理【END】==========================================================
END;

BEGIN--===================================返回结果并删除临时表【BEGIN】  =======================================
IF(@Cid<>-1)
BEGIN
	SELECT 
		TypeID,
		UserCode,
		OrderUserCode,
		FullName,
		FPeriod,
		Summary,
		FDebitTotal,
		FCreditTotal, 
		FDC,
		Total
	FROM #General
	ORDER BY 
		OrderUserCode,
		FPeriod,
		Summary DESC	
END
ELSE 
BEGIN
	SET @SQL='
	SELECT
		T.TypeID,
		T.FPeriod,
		T.FullName,
		T.UserCode,
		T.Summary,
		T.FDC,
		A.*
	FROM 
	(
		SELECT
			TypeID,
			FPeriod,
			Summary'
		SELECT @SQL=@SQL+',SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FDebitTotal ELSE 0 END) [Borrow'+UserCode+']
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN FCreditTotal ELSE 0 END) [Lend'+UserCode+']
		,SUM(CASE WHEN Cid='+CAST(Cid AS VARCHAR)+' THEN Total ELSE 0 END) [Balance'+UserCode+']'
		FROM #Currency	
		SET @SQL+='
		FROM #General 
		GROUP BY
			TypeID,
			FPeriod,
			Summary
	) A
	INNER JOIN #General T ON T.TypeID=A.TypeID AND T.FPeriod=A.FPeriod  AND T.Summary=A.Summary AND T.CID=0 
	ORDER BY 
		T.OrderUserCode,
		T.FPeriod,
		T.Summary DESC
		'
	EXEC(@SQL)
END



--删除临时表
DROP TABLE
	#FP, 
	#Account,
	#Currency,
	#tempAcBalance,
	#VoucherBill,
	#General
--===================================返回结果并删除临时表【END】	===============================================
END;

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_AcGoodsBillVoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_AcGoodsBillVoucherBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	凭证查审核
-- 时间：	2012-06-15
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Web_AcGoodsBillVoucherBill
(
	@BillNumberId	VARCHAR(50)='',			--凭证ID
	@VoucherType	INT,					--凭证类型 5:部门转移 6计提减值准备
	@iscommission	INT = 0					--1.提成单 2:暂估 3：优惠券
)
--@encode$--
AS
SET NOCOUNT ON

IF @iscommission = 1
BEGIN
	SELECT 
		bill.BillNumberId,
		bill.BillDate,
		bill.BillCode,
		311 AS BillType,
		'提成单' AS BillName,
		e.FullName efullname,
		dp.fullname dfullname,
		'' AS bfullname,
		NULL AS ntotalmoney,
		ce.FullName AS cefullname
	FROM dbo.Ac_CommissionBill_VoucherBill ac
	INNER JOIN dbo.CommissionBillNew bill ON bill.BillNumberId=ac.GoodsBillId
	LEFT JOIN employee e ON E.typeId=BILL.Checke
	LEFT JOIN department dp ON e.dtypeid=dp.typeid
	LEFT JOIN dbo.employee ce ON ce.typeId = bill.checke
	WHERE ac.VourchBillId=@BillNumberId	
END
ELSE IF @iscommission = 2
BEGIN
	SELECT 
		bill.BillNumberId,
		bill.BillDate,
		bill.BillCode,
		bill.BillType,
		name.BillName,
		e.FullName efullname,
		dp.fullname dfullname,
		b.FullName AS bfullname,
		bill.NTotalMoney AS ntotalmoney,
		ce.FullName AS cefullname
	FROM dbo.Ac_ReceiptBill_VoucherBill ac
	INNER JOIN dbo.ReceiptBillIndex bill ON bill.BillNumberId=ac.GoodsBillId
	LEFT JOIN employee e ON E.typeId=BILL.Checke
	LEFT JOIN department dp ON e.dtypeid=dp.typeid
	LEFT JOIN dbo.BillName name ON bill.BillType = name.Billtype
	LEFT JOIN dbo.employee ce ON ce.typeId = bill.checke
	LEFT JOIN dbo.btype b ON bill.BTypeID = b.typeId
	WHERE ac.VourchBillId=@BillNumberId	
END
ELSE IF(@iscommission=3)--优惠券
	BEGIN
		SELECT 
			bill.BillNumberId,
			bill.BillDate,
			bill.BillCode,
			bill.BillType,
			name.BillName,
			e.FullName efullname,
			dp.fullname dfullname,
			b.FullName AS bfullname,
			bill.NTotalMoney AS ntotalmoney,
			ce.FullName AS cefullname
		FROM dbo.Ac_CouponBill_VoucherBill ac
		INNER JOIN dbo.Coupon_BillIndex bill ON bill.BillNumberId=ac.CouponBillId
		LEFT JOIN employee e ON E.typeId=BILL.ETypeId
		LEFT JOIN department dp ON e.dtypeid=dp.typeid
		LEFT JOIN dbo.BillName name ON bill.BillType = name.Billtype
		LEFT JOIN dbo.employee ce ON ce.typeId = bill.Maker
		LEFT JOIN dbo.btype b ON bill.BTypeID = b.typeId
		WHERE ac.VourchBillId=@BillNumberId	
	END
ELSE IF(@iscommission=4)--门店配送单
	BEGIN
		SELECT 
			bill.BillNumberId,
			bill.BillDate,
			bill.BillCode,
			bill.BillType,
			name.BillName,
			e.FullName efullname,
			dp.fullname dfullname,
			'' AS bfullname,
			bill.Total AS ntotalmoney,
			ce.FullName AS cefullname
		FROM dbo.Ac_DeliveryBill_VoucherBill ac
		INNER JOIN dbo.PosAllotApplyBillIndex bill ON bill.BillNumberId=ac.DeliveryBillId
		LEFT JOIN employee e ON E.typeId=BILL.ApplyEtypeId
		LEFT JOIN department dp ON e.dtypeid=dp.typeid
		LEFT JOIN dbo.BillName name ON bill.BillType = name.Billtype
		LEFT JOIN dbo.employee ce ON ce.typeId = bill.checkE
		--LEFT JOIN dbo.btype b ON bill.BTypeID = b.typeId
		WHERE ac.VourchBillId=@BillNumberId	
	END
ELSE IF @iscommission = -1
BEGIN
	SELECT 
		bill.BillNumberId,
		bill.BillDate,
		bill.BillCode,
		bill.BillType,
		bn.BillName,
		e.FullName efullname,
		d.FullName dfullname,
		b.FullName AS bfullname,
		ce.FullName AS cefullname,
		bill.ntotalmoney
	FROM Ac_GoodsBill_VoucherBill ac
	INNER JOIN BillIndex bill ON bill.BillNumberId=ac.GoodsBillId
	LEFT JOIN BillName bn ON bn.Billtype=bill.BillType
	LEFT JOIN employee e ON E.typeId=BILL.etypeid
	LEFT JOIN Department d ON d.typeid=bill.DTypeId
	LEFT JOIN dbo.btype b ON b.typeId = bill.btypeid
	LEFT JOIN dbo.employee ce ON ce.typeId = bill.checke
	WHERE ac.VourchBillId=@BillNumberId	
	UNION ALL
	SELECT 
		bill.BillNumberId,
		bill.BillDate,
		bill.BillCode,
		bill.BillType,
		name.BillName,
		e.FullName efullname,
		dp.fullname dfullname,
		b.FullName AS bfullname,
		ce.FullName AS cefullname,
		bill.NTotalMoney AS ntotalmoney
	FROM dbo.Ac_ReceiptBill_VoucherBill ac
	INNER JOIN dbo.ReceiptBillIndex bill ON bill.BillNumberId=ac.GoodsBillId
	LEFT JOIN employee e ON E.typeId=BILL.Checke
	LEFT JOIN department dp ON e.dtypeid=dp.typeid
	LEFT JOIN dbo.BillName name ON bill.BillType = name.Billtype
	LEFT JOIN dbo.employee ce ON ce.typeId = bill.checke
	LEFT JOIN dbo.btype b ON bill.BTypeID = b.typeId
	WHERE ac.VourchBillId=@BillNumberId	
	RETURN
END

IF @VoucherType=5
	BEGIN
		SELECT 
		    D.Id BillNumberId,
			D.BusinessDate BillDate,
			C.UserCode BillCode,
			2 BillType,
			'部门转移' BillName,
			e.FullName efullname,
			''	AS bfullname,
			'' AS cefullname,
			NULL AS ntotalmoney
		FROM Ac_Provision_Voucher ac
		INNER JOiN Ac_AssetsModifyRecords D ON ac.SourceType=2 AND ac.SourceId=d.Id
		INNER JOIN Ac_AssetsCards C ON C.Id=d.CardId 
		INNER JOIN employee E ON E.typeId=D.ETypeId
		WHERE ac.VoucherId=@BillNumberId	
	END
ELSE IF @VoucherType=6
	BEGIN
		SELECT 
		    D.Id BillNumberId,
			D.BusinessDate BillDate,
			C.UserCode BillCode,
			1 BillType,
			'计提减值准备' BillName,
			e.FullName efullname,
			''	AS bfullname,
			'' AS cefullname,
			NULL AS ntotalmoney
		FROM Ac_Provision_Voucher ac
		INNER JOiN Ac_ProvisionForImpairment D ON ac.SourceType=1 AND ac.SourceId=d.Id
		INNER JOIN Ac_AssetsCards C ON C.Id=d.CardId 
		INNER JOIN employee E ON E.typeId=D.ETypeId
		WHERE ac.VoucherId=@BillNumberId	
	END
ELSE
	BEGIN
		SELECT 
			bill.BillNumberId,
			bill.BillDate,
			bill.BillCode,
			bill.BillType,
			bn.BillName,
			e.FullName efullname,
			d.FullName dfullname,
			b.FullName AS bfullname,
			ce.FullName AS cefullname,
			bill.ntotalmoney
		FROM Ac_GoodsBill_VoucherBill ac
		INNER JOIN BillIndex bill ON bill.BillNumberId=ac.GoodsBillId
		LEFT JOIN BillName bn ON bn.Billtype=bill.BillType
		LEFT JOIN employee e ON E.typeId=BILL.etypeid
		LEFT JOIN Department d ON d.typeid=bill.DTypeId
		LEFT JOIN dbo.btype b ON b.typeId = bill.btypeid
		LEFT JOIN dbo.employee ce ON ce.typeId = bill.checke
		WHERE ac.VourchBillId=@BillNumberId	
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AcIniAccountQueryAssistStype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_AcIniAccountQueryAssistStype
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-5-8
	描述：账务期初辅助核算项分支机构选择,从Web_QuerySearchOneBaseInfoDelete搬移过来
*/
CREATE   PROCEDURE Web_AcIniAccountQueryAssistStype
(
	@OperatorId		VARCHAR(100),		--操作员Id	
	@bType			VARCHAR(10),		--基本信息类型
	@BTypeLx		VARCHAR(10)='3',
	@TypeId			VARCHAR(100),
	@Filter			VARCHAR(300)='',	--过滤 1、编号  2、名称  3、拼音码 4、联系电话
	@nType			VARCHAR(10)='0',
	@IniAccountStypeId        varchar(50)          --分支机构id   
)
--@encode$--
AS
SET NOCOUNT ON
--特殊处理传bool值的情况
DECLARE @KnType VARCHAR(10)=@nType
IF LOWER(@nType)='true' OR LOWER(@nType)='false'
	BEGIN
		IF LOWER(@nType)='false'
			SET @nType = '0'
		ELSE
			SET @nType = '1'
	END
--特殊处理[符号
SET @Filter = REPLACE(@Filter,'[','[[]')		
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--************************************************************部门基本信息************************************************************
IF @bType = 'D'
	BEGIN
		IF @TypeId = '' 
			SET @TypeId = '00000'
			
		CREATE TABLE #DType(TypeId VARCHAR(100),ParId VARCHAR(max),SonNum int,UserCode	VARCHAR(256),FullName VARCHAR(256),PyCode VARCHAR(500))
		
		--判断权限范围
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerDTypeId = '00000')
			INSERT INTO #DType SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode FROM F_GetManDTypeAll(@OperatorId)  WHERE deleted=0
		ELSE
			INSERT INTO #DType SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode FROM Department WHERE deleted=0

		DECLARE @dSonNum int,@dParId VARCHAR(200)
		SELECT @dSonNum = SonNum,@dParId = ParId FROM Department WHERE TypeId = @TypeId AND Deleted = 0
		
		IF @Filter = ''
			BEGIN
				IF @TypeId = '00000'
					SELECT TypeId,SonNum,UserCode,FullName,ParId FROM #DType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode	
				ELSE IF @nType = '0'
					SELECT TypeId,SonNum,UserCode,FullName,ParId FROM #DType WHERE ParId = @dParId AND TypeId <> '00000' ORDER BY UserCode	
				ELSE
					BEGIN
						IF @dSonNum = 0
							SELECT TypeId,SonNum,UserCode,FullName,ParId FROM #DType WHERE SonNum = 0 AND TypeId LIKE @TypeId + '%' AND TypeId <> '00000' ORDER BY UserCode	
						ELSE
							SELECT TypeId,SonNum,UserCode,FullName,ParId FROM #DType WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode	
					END
			END
		ELSE
			SELECT	TypeId,SonNum,UserCode,FullName,ParId
			FROM	#DType 
			WHERE	SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%')		
			ORDER BY UserCode
		DROP TABLE #DType
	END
--************************************************************职员基本信息************************************************************
IF @bType = 'E'
	BEGIN
		IF @TypeId = '' SET @TypeId = '00001'
		DECLARE @eSonNum int,
				@eParId  VARCHAR(200)

		CREATE TABLE #Employee
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Deleted		int
		)

		--判断权限范围
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeId = '00001')
			INSERT INTO #Employee(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM F_GetManETypeAll(@OperatorId)
		ELSE
			INSERT INTO #Employee(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM Employee

		SELECT @eSonNum = SonNum,@eParId=ParId FROM #Employee WHERE TypeId = @TypeId AND Deleted = 0

		IF @Filter = ''
			BEGIN
				IF @TypeId = '00001'
					SELECT	TypeId,SonNum,UserCode,FullName,ParId	FROM #Employee WHERE Deleted = 0 AND ParId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode	
				ELSE IF @nType = '0'
					SELECT	TypeId,SonNum,UserCode,FullName,ParId	FROM #Employee WHERE Deleted = 0 AND ParId = @eParId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode	
				ELSE
					BEGIN
						IF @eSonNum = 0
							SELECT	TypeId,SonNum,UserCode,FullName,ParId	FROM #Employee WHERE	Deleted = 0 AND SonNum = 0 AND TypeId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode
						ELSE
							SELECT	TypeId,SonNum,UserCode,FullName,ParId	FROM #Employee WHERE	Deleted = 0 AND ParId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode	
					END
			END
		ELSE
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId	FROM #Employee WHERE	Deleted = 0 AND SonNum = 0 AND TypeId LIKE @METypeId + '%' AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%')
						AND TypeId <> '00000'	
						AND TypeId <> '00001'
				ORDER BY UserCode
			END

		DROP TABLE #Employee
	END
--************************************************************单位基本信息************************************************************
IF @bType = 'B'
	BEGIN
		IF @TypeId = ''
		BEGIN
			IF @BTypeLx = '3' SET @TypeId = '00000'
			ELSE IF @BTypeLx = '1' SET @TypeId = '00001'
			ELSE SET @TypeId = '00002'
		END

		DECLARE @bSonNum 	int,
				@BTypeAll	int,
				@BTypeId	VARCHAR(200),
				@bParId		VARCHAR(200)
		
		IF @BTypeLx = '3'
			SET @BTypeAll = 1
		ELSE
			SELECT	@BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

		CREATE TABLE #BType
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Tel1        varchar(max),
			Tel2        varchar(max),
			Tel3        varchar(max),
			Deleted		int
		)

		--判断权限范围
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerBTypeId = '00001' AND MangerBTypeId2 = '00002')
			INSERT INTO #BType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted FROM F_GetManBTypeAll(@OperatorId)
		ELSE
			INSERT INTO #BType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted FROM BType

		SELECT @bSonNum = SonNum,@bParId=ParId FROM #BType WHERE TypeId = @TypeId AND Deleted = 0

		IF @BTypeAll = 0	--客户和供货商不统一
			BEGIN
				IF @BTypeLx = '1'	--客户
					BEGIN
						IF @Filter = ''
							BEGIN
								IF @nType = '0'
									BEGIN
										IF @TypeId = '00001' 
											SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND TypeId = @TypeId AND TypeId NOT IN ('00000') ORDER BY UserCode
										ELSE
											SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND ParId = @bParId AND TypeId NOT IN ('00000') ORDER BY UserCode
									END
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
							END
						ELSE
							SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%'OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000' AND TypeId LIKE '00001%' ORDER BY UserCode
					END
				ELSE				--供货商
					BEGIN
						IF @Filter = ''
							BEGIN
								IF @nType = '0'
									BEGIN
										IF @TypeId = '00002'
											SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND TypeId = @TypeId AND TypeId NOT IN ('00000') ORDER BY UserCode
										ELSE 
											SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND ParId = @bParId AND TypeId NOT IN ('00000') ORDER BY UserCode
									END
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
							END
						ELSE
							SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND SonNum = 0 AND SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%'OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000' AND TypeId LIKE '00002%' ORDER BY UserCode
					END
			END
		ELSE				--客户和供货商统一
			BEGIN
				IF @TypeId = '00000'
					BEGIN
						IF @Filter = ''
							SELECT TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE ParId = '00000' ORDER BY UserCode
						ELSE
							SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND SonNum = 0 AND Deleted = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%'OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000' ORDER BY UserCode
					END
				ELSE IF @Filter = ''
					BEGIN
						IF LEN(@TypeId) = 5
							BEGIN	
								IF @nType = '0'
									SELECT TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE ParId = '00000' ORDER BY UserCode
								ELSE
									BEGIN
										IF LEFT(@TypeId,5)='00001'
											BEGIN
												IF LEN(@TypeId)<LEN('00001')													
													SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND TypeId = @MBTypeId AND TypeId <> '00000' ORDER BY UserCode
												ELSE
													SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
											END
										ELSE
											BEGIN
												IF LEN(@TypeId)<LEN('00002')
													SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND TypeId = @MBTypeId2 AND TypeId <> '00000' ORDER BY UserCode
												ELSE
													SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
											END
									END
							END
						ELSE
							BEGIN
								IF @nType = '0'
									SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND ParId = @bParId AND TypeId <> '00000' ORDER BY UserCode
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
							END
					END
				ELSE
					BEGIN
						SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #BType WHERE Deleted = 0 AND SonNum = 0 AND Deleted = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%'OR Tel3 LIKE '%'+@Filter+'%' OR Tel1 LIKE '%'+@Filter+'%' OR Tel2 LIKE '%'+@Filter+'%') AND TypeId <> '00000'  ORDER BY UserCode
					END
			END

		DROP TABLE #BType
	END
--************************************************************分支机构基本信息************************************************************
IF @bType = 'S'
	BEGIN
		IF @TypeId = '' SET @TypeId = '00000'
		DECLARE @fzSonNum 	int,
				@fzParId		VARCHAR(200)

		SELECT @fzSonNum = SonNum,@fzParId=ParId FROM SType WHERE TypeId = @TypeId AND Deleted = 0
		
		
		CREATE TABLE #SFType
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Deleted		int,
			SFyear		INT,
			SFPeriod	INT,
			IsSelfVerify	varchar(2),
			VerifyID		VARCHAR(50)
		)

		--modify by dongzhan 2013.7.17 配置中新增“独立分支间只允许存在买卖关系”，sysdata下SubName='innerstypesaleralation'
        DECLARE @result VARCHAR(30)
        SELECT @result=SubValue FROM dbo.sysdata WHERE SubName='innerstypesaleralation'
       
		--判断权限范围
		IF @result='1'
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify,VerifyID,SFyear,SFPeriod) SELECT f.TypeId,f.ParId,f.SonNum,f.UserCode,f.FullName,f.PyCode,f.Deleted,s.IsSelfVerify,s.VerifyID,SFyear,SFPeriod FROM F_GetManSTypeAll(@OperatorId) f
					JOIN dbo.SType s ON  s.TypeId=f.TypeId AND s.VerifyID=@IniAccountStypeId
					LEFT JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=S.VerifyID
				ELSE
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify,VerifyID,SFyear,SFPeriod) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify,VerifyID,SFyear,SFPeriod FROM SType  S
					LEFT JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=S.VerifyID WHERE VerifyID=@IniAccountStypeId	
	            ---特殊情况，A分支机构下的机构B，他的核算是C
	            INSERT INTO #SFType(TypeID,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify,VerifyID,SFyear,SFPeriod)
	            SELECT  s.TypeId,s.ParId,s.SonNum,s.UserCode,s.FullName,s.PyCode,s.Deleted,s.IsSelfVerify,s.VerifyID,SFYear,SFPeriod FROM dbo.SType s JOIN #SFType sf ON sf.ParId=s.TypeId
	            WHERE s.TypeID NOT IN (SELECT TypeID FROM #SFType) AND s.TypeId<>'00000'
			END
		ELSE 
			BEGIN
				IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify,VerifyID,SFyear,SFPeriod) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify,VerifyID,SFYear,SFPeriod FROM F_GetManSTypeAll(@OperatorId) S
					LEFT JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=S.VerifyID
				ELSE
					INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify,VerifyID,SFyear,SFPeriod) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify,VerifyID,SFYear,SFPeriod FROM SType S
					LEFT JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=S.VerifyID
			END
		
		IF @Filter = ''
			BEGIN
				--IF @result='1'
				--	 SELECT * FROM #SFType ORDER BY UserCode
				--ELSE 
				--	BEGIN
						IF @TypeId = '00000'
							SELECT	TypeId,SonNum,UserCode,FullName,IsSelfVerify,VerifyID ,SFyear,SFPeriod FROM #SFType WHERE Deleted = 0 AND ParId = '00000' AND TypeId <> '00000' ORDER BY UserCode
						ELSE IF @nType = '0'
							BEGIN
								IF @TypeId = @MSTypeId
									SELECT	TypeId,SonNum,UserCode,FullName,IsSelfVerify,VerifyID,SFyear,SFPeriod FROM #SFType WHERE Deleted = 0 AND TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName,IsSelfVerify,VerifyID,SFyear,SFPeriod FROM #SFType WHERE Deleted = 0 AND ParId = @fzParId AND TypeId <> '00000' ORDER BY UserCode
							END
						ELSE
							BEGIN
								IF @fzSonNum = 0
									SELECT	TypeId,SonNum,UserCode,FullName,IsSelfVerify,VerifyID,SFyear,SFPeriod FROM #SFType WHERE Deleted = 0 AND SonNum = 0 AND TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
								ELSE
									SELECT	TypeId,SonNum,UserCode,FullName,IsSelfVerify,VerifyID,SFyear,SFPeriod FROM #SFType WHERE Deleted = 0 AND ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
							END
					--END
			END
		ELSE
			SELECT	TypeId,SonNum,UserCode,FullName,IsSelfVerify,VerifyID,SFyear,SFPeriod FROM #SFType WHERE Deleted = 0 AND SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%') AND TypeId <> '00000'  ORDER BY UserCode

		DROP TABLE #SFType			
	END
	
--************************************************************仓库基本信息************************************************************
IF @bType = 'K'
	BEGIN
			
		CREATE TABLE #Stock
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Deleted		int
		)

		--判断权限范围
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerKTypeID <> '00000')
			INSERT INTO #Stock(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM F_GetManKTypeAll(@OperatorId) WHERE deleted=0
		ELSE
			INSERT INTO #Stock(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM stock WHERE deleted=0

		DECLARE @KParId	VARCHAR(50)=''--父节点
		SELECT @KParId=ParId FROM #Stock WHERE TypeID=@TypeId
		
		IF @Filter = ''
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #Stock 
				WHERE 
					((ParId=@TypeId AND (@KnType='0' OR @KnType='True')) OR (@KnType='False' AND ParId=@KParId))
					--((@nType=1 AND ParId=@TypeId) OR (@nType=0 AND ParId=@KParId))
					AND TypeId <> '00000' 
				ORDER BY UserCode	
			END
		ELSE
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId FROM #Stock WHERE Deleted = 0 AND SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%')
						AND TypeId <> '00000'
				ORDER BY UserCode
			END

		DROP TABLE #Stock
	END

--************************************************************客户档案/供货商 基本信息************************************************************
IF @bType = 'J' OR @bType = 'G'
	BEGIN
		--DECLARE @J_BTypeAll INT
		
		--SELECT	@J_BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

		CREATE TABLE #J_BType
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Tel1        varchar(max),
			Tel2        varchar(max),
			Tel3        varchar(max),
			Deleted		int
		)

		--判断权限范围
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerBTypeId = '00001' AND MangerBTypeId2 = '00002')
			INSERT INTO #J_BType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted FROM F_GetManBTypeAll(@OperatorId) WHERE deleted=0
		ELSE
			INSERT INTO #J_BType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted FROM BType WHERE deleted=0
			
		DECLARE @NParId	VARCHAR(50)=''--父节点
		SELECT @NParId=ParId FROM #J_BType WHERE TypeID=@TypeId
		
		IF @Filter = ''
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId 
				FROM #J_BType
				WHERE 
					((@nType=1 AND ParId=@TypeId) OR (@nType=0 AND ParId=@NParId))
					AND TypeID<>'00000'
					AND ((@bType='J' AND LEFT(TypeID,5)='00001') OR (@bType='G' AND LEFT(TypeID,5)='00002'))  
				ORDER BY UserCode
			END
		ELSE 
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId 
				FROM #J_BType
				 WHERE 
					SonNum=0 
					AND TypeID<>'00000'
					AND ((@bType='J' AND LEFT(TypeID,5)='00001') OR (@bType='G' AND LEFT(TypeID,5)='00002'))  
					AND (UserCode LIKE '%'+@Filter+'%'  OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%')
				ORDER BY UserCode
			END
		DROP TABLE #J_BType
	END
--************************************************************商品基本信息************************************************************
IF @bType = 'P'
	BEGIN
			
		CREATE TABLE #PType
		(
			TypeID		VARCHAR(100),
			ParId		VARCHAR(100),
			SonNum		int,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Deleted		int,
			Standard	VARCHAR(400),
			type		VARCHAR(400),
			baseUnitId	VARCHAR(400),
			baseUnitFullname	VARCHAR(400),
			
			customitemid	INT,
			customitemfrom	INT,
			customitemname	VARCHAR(MAX),
			customitemrefid VARCHAR(MAX)
		)

		--判断权限范围
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerPTypeID <> '00000')
			INSERT INTO #PType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,Standard,type,baseUnitId,baseUnitFullname,customitemid,customitemfrom,customitemname,customitemrefid) SELECT P.TypeId,P.ParId,P.SonNum,P.UserCode,P.FullName,P.PyCode,P.Deleted,P.Standard,P.type,P.baseUnitId,PU.FullName baseUnitFullname,P.customitemid,P.customitemfrom,P.customitemname,P.customitemrefid FROM F_GetManPTypeAll(@OperatorId) p INNER JOIN PType_Units PU ON PU.UnitsId=P.baseUnitId AND P.deleted=0 AND P.iscombinationproduct=0
		ELSE
			INSERT INTO #PType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,Standard,type,baseUnitId,baseUnitFullname,customitemid,customitemfrom,customitemname,customitemrefid) SELECT P.TypeId,P.ParId,P.SonNum,P.UserCode,P.FullName,P.PyCode,P.Deleted,P.Standard,P.type,P.baseUnitId,PU.FullName baseUnitFullname,P.customitemid,P.customitemfrom,P.customitemname,P.customitemrefid FROM ptype P INNER JOIN PType_Units PU ON PU.UnitsId=P.baseUnitId AND P.deleted=0  AND P.iscombinationproduct=0

		DECLARE @PParId	VARCHAR(50)=''--父节点
		SELECT @PParId=ParId FROM #PType WHERE TypeID=@TypeId
		
		IF @Filter = ''
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId,Standard,type,baseUnitId,baseUnitFullname,customitemid,customitemfrom,customitemname,customitemrefid FROM #PType 
				WHERE 
					((ParId=@TypeId AND (@KnType='0' OR @KnType='True')) OR (@KnType='False' AND ParId=@KParId))
					AND TypeId <> '00000' 
				ORDER BY UserCode	
			END
		ELSE
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId,Standard,type,baseUnitId,baseUnitFullname,customitemid,customitemfrom,customitemname,customitemrefid FROM #PType WHERE Deleted = 0 AND SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%')
						AND TypeId <> '00000'
				ORDER BY UserCode
			END

		DROP TABLE #PType
	END
--==================================================项目======================================
IF @bType = 'I'
	BEGIN
		CREATE TABLE #Item
		(
			TypeID		VARCHAR(50),
			ParId		VARCHAR(50),
			SonNum		INT,
			UserCode	VARCHAR(400),
			FullName	VARCHAR(400),
			PyCode		VARCHAR(400),
			Deleted		INT
		)

			INSERT INTO #Item(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) 
			SELECT nTypeId,nParId,SonNum,UserCode,FullName,PyCode,Deleted 
			FROM F_AllTreeA(@OperatorId)
			WHERE deleted=0
			UNION ALL 
			SELECT nTypeId,nParId,SonNum,UserCode,FullName,PyCode,Deleted
			FROM F_AllTreeF(@OperatorId)
			WHERE deleted=0
			
		DECLARE @ItemParId	VARCHAR(50)=''--父节点
		SELECT @ItemParId=ParId FROM #Item WHERE TypeID=@TypeId
			
		IF @Filter = ''
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId 
				FROM #Item
				WHERE 
					(((@KnType='0' OR @KnType='True') AND ((@TypeId='00000' AND ParId IN(SELECT nTypeId FROM Ac_Items WHERE nParId='00000')) 
																OR(ParId=@TypeId AND @TypeId<>'00000'))
															)
					OR (@KnType='False' AND ((LEN(@ItemParId)=5 AND ParId IN(SELECT nTypeId FROM Ac_Items WHERE nParId='00000')) OR ParId=@ItemParId)))
				ORDER BY UserCode
			END
		ELSE 
			BEGIN
				SELECT	TypeId,SonNum,UserCode,FullName,ParId 
				FROM #Item
				 WHERE 
					SonNum=0 
					AND (UserCode LIKE '%'+@Filter+'%'  OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%')
				ORDER BY UserCode
			END
		DROP TABLE #Item
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AcTypeSelectorQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_AcTypeSelectorQuery
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：佘海源
	日期：2012-04-17
	描述：科目选择
-------------------------------------------*/
CREATE PROCEDURE Web_AcTypeSelectorQuery
(
	@STypeId 			VARCHAR(50),    ---分支机构
	@ParId				VARCHAR(100),   ---父节点   
	@Query				VARCHAR(100),   ---查询参数
	@chvOperatorID		VARCHAR(100),   ---操作员ID
	@AssistCheckItems	VARCHAR(50),	--辅助核算限制
	@AssistCheckItemCount	INT,	--辅助核算数目
	@Delete				INT             --1是不出停用科目，0是出所有
)
--@encode$--
AS 
SET NOCOUNT ON
--------
DECLARE @VerifyStypeid VARCHAR(50)
SELECT @VerifyStypeid=VerifyID FROM dbo.SType WHERE TypeId=@STypeId  

DECLARE @SQL	NVARCHAR(MAX)
		

CREATE TABLE #temp_Account
(
	atypeid		VARCHAR(50),
	stypeid		VARCHAR(50)
)
IF @AssistCheckItems <> ''
BEGIN
	SET @SQL = '
	INSERT INTO	#temp_Account(atypeid,stypeid)
	SELECT DISTINCT 
		x.ATypeId,
		x.stypeid
	FROM Ac_Account_Assist_CheckItems x 
	INNER JOIN	(
		SELECT	 ATypeId
				,stypeid
				,COUNT(1) AS counts
		FROM	Ac_Account_Assist_CheckItems 
		WHERE	STypeId = '''+@STypeId+'''
			AND Ascids IN ('+@AssistCheckItems+')
		GROUP BY	ATypeId,stypeid,Cid
		
	) z ON z.ATypeId = x.ATypeId AND z.counts = '+ CAST(@AssistCheckItemCount AS VARCHAR)
	+
	'
	WHERE x.Ascids IN ('+@AssistCheckItems+') 
	AND	X.STypeId = '''+@VerifyStypeid+''''
	EXEC(@SQL)

END
print @sql



--------默认显示资产类科目--------
IF(@ParId='') 
 SET @ParId=@VerifyStypeid

------ 查询功能（按科目代码、名称、拼音码)-------

--带有查询条件匹配数据表
CREATE TABLE #Temp(TypeId VARCHAR(50),StypeId VARCHAR(50))

IF(@Query!='')--不为空则进行过滤查询
  BEGIN
  
	 SET @Query='%'+@Query+'%'
	 
	 --如果科目数据量大的话，数据like查询比较慢。先匹配出符合条件数据
	  --匹配父类
	;WITH AtypeParid AS
	 (
		SELECT 
			A.TypeId,
			A.StypeId,
			A.ParId
		FROM dbo.Ac_Account A
		INNER JOIN F_TreeAccount(@chvOperatorID,@VerifyStypeid) F1 ON F1.Typeid=A.TypeId  AND F1.Stypeid=A.StypeId
		WHERE
			(A.UserCode LIKE @Query OR A.FullName LIKE @Query OR A.PyCode LIKE @Query) 
			AND A.Leveal >1
			AND ((@Delete=1 AND A.Deleted=0) OR (@Delete=0))
			AND A.ParId<>''
		UNION ALL
		SELECT 
			A.TypeId,
			A.StypeId,
			A.ParId
		FROM dbo.Ac_Account A
		INNER JOIN F_TreeAccount(@chvOperatorID,@VerifyStypeid) F ON F.Typeid=A.TypeId  AND F.Stypeid=A.StypeId
		INNER JOIN AtypeParid F1 ON A.TypeId=F1.ParId AND F1.Stypeid=A.StypeId AND A.ParId<>'00000'
	 )
	 INSERT INTO #Temp(TypeId,StypeId)
	 SELECT TypeId,StypeId FROM AtypeParid GROUP BY TypeId,StypeId
	 SET @SQL = '
		SELECT 
			DISTINCT 
			AA.TypeId,
			AA.Usercode AS code, 
			REPLICATE(''    '',AA.FLeveal-1) + AA.UserCode UserCode,
			AA.FullName,
			CASE WHEN AA.Fdc=1  THEN ''借''
				 WHEN AA.Fdc=-1 THEN ''贷''
			END AS Fdc,
			CASE WHEN AA.Cid=0  THEN ''所有币种''
				 WHEN AA.Cid=1  THEN ''不核算''
				 ELSE C.FullName
			END AS FAcnt,
			AA.SonNum AS SNum,
			AA.ParId,
			dbo.F_GetAc_Assist_CheckItems_FullName(AA.TypeId,AA.StypeId) AS AssisitItem
		FROM Ac_Account AA
		INNER JOIN #Temp  T ON T.TypeId=AA.TypeId AND T.StypeId=AA.StypeId
		LEFT JOIN Ac_Currency C ON C.CId=AA.Cid
		'+CASE WHEN @AssistCheckItems <> '' THEN ' INNER JOIN	#temp_Account  TA ON TA.atypeid = aa.typeid ' ELSE '' END +
		'
		ORDER BY AA.Usercode
  '
  END
  
-------查询全部科目（含子节点）---------
ELSE
BEGIN
	SET @SQL = '
		SELECT 
			AA.TypeId,
			REPLICATE(''    '',AA.FLeveal-1) + AA.UserCode UserCode,
			AA.FullName,
			CASE WHEN Fdc=1  THEN ''借''
				 WHEN Fdc=-1 THEN ''贷''
			END AS Fdc,
			CASE WHEN AA.Cid=0  THEN ''所有币种''
				 WHEN AA.Cid=1  THEN ''不核算''
				 ELSE C.FullName
			END AS FAcnt,
			AA.SonNum AS SNum,
			AA.ParId,
			dbo.F_GetAc_Assist_CheckItems_FullName(AA.TypeId,AA.StypeId)  AS AssisitItem
		FROM Ac_Account AA
		INNER JOIN F_TreeAccount('''+@chvOperatorID+''','''+@VerifyStypeid+''') F ON F.Typeid=AA.TypeId AND F.Stypeid=AA.StypeId
		AND AA.ParId LIKE '''+@ParId+'''+''%'' AND Leveal >1 AND (('+CAST(@Delete AS VARCHAR)+'=1 AND AA.Deleted=0) OR ('+CAST(@Delete AS VARCHAR)+'=0))
		LEFT JOIN Ac_Currency C ON C.CId=AA.Cid	
		'+CASE WHEN @AssistCheckItems <> '' THEN ' INNER JOIN	#temp_Account  TA ON TA.atypeid = aa.typeid ' ELSE '' END +
		'
		ORDER BY AA.Usercode
   '
END
EXEC(@SQL)

DROP TABLE #temp_Account,#Temp

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AcTypeSELECTShowFirstLeveal]') AND OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].Web_AcTypeSELECTShowFirstLeveal
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：黄清
	日期：2014年11月4日 14:38:47
	描述：科目选择（多分支机构，且只显示1级科目）
-------------------------------------------*/
CREATE PROCEDURE Web_AcTypeSELECTShowFirstLeveal
(
       @STypeId 	   VARCHAR(MAX),    ---分支机构
       @ParId		   VARCHAR(100),   ---父节点   
       @Query		   VARCHAR(100),   ---查询参数
       @chvOperatorID  VARCHAR(100),   ---操作员ID
       @AssistCheckItems	VARCHAR(50),	--辅助核算限制
       @AssistCheckItemCount	INT,	--辅助核算数目
       @Delete		   INT             --1是不出停用科目，0是出所有
)
--@encode$--
AS 
SET NOCOUNT ON
--------
CREATE TABLE #STYPE (TYPEID VARCHAR(50))
IF @STypeId=''
	INSERT INTO #STYPE SELECT TypeId FROM F_GetMANDetailSType(@chvOperatorID)
ELSE
	INSERT INTO #STYPE
	SELECT TypeId FROM F_GetMANDetailSType(@chvOperatorID) F
	INNER JOIN (SELECT a FROM f_split(@STypeId,',')) S ON F.TypeId LIKE S.a+'%'

CREATE TABLE #Ac_account_l(TYPEID VARCHAR(50),STYPEID VARCHAR(50))
INSERT INTO #Ac_account_l (TYPEID,STYPEID)
SELECT L.Typeid,L.Stypeid FROM F_TreeAccount(@chvOperatorID,'') L
INNER JOIN #STYPE S ON S.TYPEID=L.Stypeid

DECLARE @SQL	NVARCHAR(MAX)	
SET @SQL='
SELECT	DISTINCT
		AA.TypeId,
		aa.UserCode,
		aa.FullName, 
		CASE WHEN Fdc=1  THEN ''借''
			 WHEN Fdc=-1 THEN ''贷''
		    END AS Fdc,
	    CASE WHEN AA.Cid=0  THEN ''所有币种''
			 WHEN AA.Cid=1  THEN ''不核算''
			 ELSE (SELECT FullName  FROM Ac_Currency WHERE CId=AA.Cid)
		END AS FAcnt,
	    0 AS SNum,
	    AA.ParId,
		dbo.F_GetAc_Assist_CheckItems_FullName(AA.TypeId,AA.StypeId)  AS AssisitItem
FROM Ac_Account AA
INNER JOIN #SType S ON S.TypeId=AA.StypeId
INNER JOIN #Ac_account_l L ON AA.TYPEID=L.TYPEID AND AA.STYPEID=L.STYPEID
WHERE	AA.Leveal=2
		AND AA.ParId='+CHAR(39)+@ParId+CHAR(39)
IF @Delete<>'0'
	SET @SQL+='
	AND AA.DELETE='+CHAR(39)+@Delete+CHAR(39)

IF @Query<>''
	SET @SQL=@SQL+'  AND (usercode like '''+'%'+@Query+'%'+''' or fullname like '''+'%'+@Query+'%'+''' or pycode like '''+'%'+@Query+'%'+'''  )'

SET @SQL=@SQL+ '  ORDER BY AA.USERCODE '
PRINT @SQL
EXEC(@SQL)

DROP TABLE #STYPE

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AcTypeSonSelectorQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_AcTypeSonSelectorQuery
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：董湛
	日期：2013-05-10
	描述：科目选择
-------------------------------------------*/
CREATE PROCEDURE Web_AcTypeSonSelectorQuery
(
       @STypeId 	   VARCHAR(50),    ---分支机构   
       @ParId		   VARCHAR(100),   ---父节点  
       @Query		   VARCHAR(100),   ---查询参数
       @chvOperatorID  VARCHAR(100),   ---操作员ID
       @Delete		   INT             --1是不出停用科目，0是出所有
)
--@encode$--
AS 
SET NOCOUNT ON
--------默认显示资产类科目--------
IF(@ParId='') 
 SET @ParId=@STypeId
------ 查询功能（按科目代码、名称、拼音码)-------

IF(@Query!='')--不为空则进行过滤查询
  BEGIN
	DECLARE @Class VARCHAR(50) SET @Class='' 
	IF(LEN(@Query)=5)
		SET @Class=@Query
	 SET @Query='%'+@Query+'%'
	SELECT DISTINCT 
			AA.TypeId,
			AA.Usercode, 
		    AA.FullName,
		    CASE WHEN AA.Fdc=1  THEN '借'
				 WHEN AA.Fdc=-1 THEN '贷'
		    END AS Fdc,
		    CASE WHEN AA.Cid=0  THEN '所有币种'
				 WHEN AA.Cid=1  THEN '不核算'
				 ELSE (SELECT FullName  FROM Ac_Currency WHERE CId=AA.Cid)
			END AS FAcnt,
		    AA.SonNum AS SNum,
		    AA.ParId,
		    dbo.F_GetAc_Assist_CheckItems_FullName(AA.TypeId,AA.StypeId) AS AssisitItem
	   FROM Ac_Account AA
	   JOIN (SELECT * FROM dbo.Ac_Account
			  WHERE StypeId=@STypeId
				AND ( LEFT(TypeId,5)=@Class OR UserCode LIKE @Query OR FullName LIKE @Query OR PyCode LIKE @Query) 
				AND Leveal >1
				AND ((@Delete=1 AND Deleted=0) OR (@Delete=0))
			) AC ON AC.TypeId LIKE AA.TypeId+'%' AND AC.StypeId=@STypeId
	WHERE AA.StypeId=@STypeId AND AA.SonNum=0	 
    ORDER BY AA.Usercode
  
  END
  
-------查询全部科目（含子节点）---------
ELSE
BEGIN
    SELECT AA.TypeId,
		    AA.UserCode,
		    AA.FullName,
		    CASE WHEN Fdc=1  THEN '借'
				 WHEN Fdc=-1 THEN '贷'
		    END AS Fdc,
		    CASE WHEN AA.Cid=0  THEN '所有币种'
				 WHEN AA.Cid=1  THEN '不核算'
				 ELSE (SELECT FullName  FROM Ac_Currency WHERE CId=AA.Cid)
			END AS FAcnt,
		    AA.SonNum AS SNum,
		    AA.ParId,
		    dbo.F_GetAc_Assist_CheckItems_FullName(AA.TypeId,AA.StypeId)  AS AssisitItem
	   FROM Ac_Account AA
	  WHERE AA.StypeId=@STypeId
			AND AA.ParId LIKE @ParId+'%'
            AND Leveal >1
            AND ((@Delete=1 AND AA.Deleted=0) OR (@Delete=0)) 
            AND AA.sonnum=0
   ORDER BY AA.Usercode
END


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AcVoucherBillnumberIdQuery]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_AcVoucherBillnumberIdQuery]
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回凭证查询条件查询出来的凭证id
-- 时间：	2013-06-09 
-- 作者：	李灏龙
-- ========================================================================
CREATE PROC Web_AcVoucherBillnumberIdQuery
(
	@stypeid			VARCHAR(400),		--分支结构
	@Fyear				VARCHAR(10),		--年度
	@vouchertype		VARCHAR(50),		--凭证类型
	@dateChoose			VARCHAR(1),			--期间选择0 期间 1凭证日期
	@startfperiod		VARCHAR(2),			--开始期间 @startfperiod @endfperiod
	@endfperiod			VARCHAR(2),			--截止期间
	@startbilldate		VARCHAR(50),		-- 凭证开始日期
	@endbilldate		VARCHAR(50),		--凭证截止日期
	@atypeid			VARCHAR(MAX),		--科目
	@cid				VARCHAR(MAX),		--币别
	@summary			VARCHAR(400),		--摘要
	@vgid				VARCHAR(500),		--凭证字
	@startfserialnum	VARCHAR(100),		--开始_凭证号
	@endfserialnum		VARCHAR(100),		--截止_凭证号
	@yfdc				VARCHAR(2),			--原币借贷关系
	@ystarttotal		VARCHAR(50),		--原币金额
 	@yrealtionship		VARCHAR(5) ,		--原币且或关系
	@yendtotal			VARCHAR(50),		--原币金额
	@bfdc				VARCHAR(2),			--本币借贷关系
	@bstarttotal		VARCHAR(50),		--本币金额
	@brealtionship		VARCHAR(5) ,		--本币且或关系
	@bendtotal			VARCHAR(50),		--本币金额
	@etypeid			VARCHAR(MAX),		--制单人
	@auditid			VARCHAR(MAX),		--审核人
	@recheckid			VARCHAR(MAX),		--复核人
	@tallyid			VARCHAR(MAX),		--记账人
	@fchecked			VARCHAR(1),			--是否审核
	@audited			VARCHAR(1),			--是否过账
	@operatorid			VARCHAR(100),		--当前操作人
	@stypeid1			VARCHAR(MAX),		--辅助核算 分支结构
	@dtypeid			VARCHAR(MAX),		--部门
	@staftypeid			VARCHAR(MAX),		--职员
	@companytypeid		VARCHAR(MAX)
	--,		--往来单位
	--@nPageCol			INT=1,				--页数
	--@nPageColSize		INT=10,				--显示条数
	--@outRet				INT=0 OUTPUT,			--数据总共条数
	--@sumFdebittotal		 NUMERIC(24, 10) =0 OUTPUT,	--借方合计
	--@sumFcredittotal	 NUMERIC(24, 10) =0 OUTPUT	--贷方合计
	
)

--@encode$--
AS
SET NOCOUNT ON 
DECLARE 
	@Str		NVARCHAR(MAX)='',				--sql主体语句
	@TbStr		NVARCHAR(MAX)='',				--sql关联语句
	@Link		NVARCHAR(MAX)='',				--关联 sql
	@WhStr		NVARCHAR(MAX)='',				--是否需要辅助项目
	@TableName	VARCHAR(1000)

SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

	
SELECT @Str='CREATE TABLE '+N'##'+@TableName+'
(
	--BID				INT IDENTITY(1,1),
	BillNumberId	NUMERIC(18,0)
	,
	--nid				NUMERIC(18,0),
	--BillDate		DATETIME,
	--FPeriodDate		VARCHAR(50),
	--FSerialNum		INT,
	--FullName		VARCHAR(500),
	FlowNo			INT,
	--RowNo			INT,
	--Summary			VARCHAR(400),
	--TypeCode		VARCHAR(200),
	--TypeName		VARCHAR(500),
	--currencyName	VARCHAR(200),
	--FAmountFor		 NUMERIC(24, 10) ,
	--FDebitTotal		 NUMERIC(24, 10) ,
	--FCreditTotal	 NUMERIC(24, 10) ,
	--ETypeId			VARCHAR(50),
	--AuditId			VARCHAR(50),
	--TallyId			VARCHAR(50),
	--recheckId		VARCHAR(50),
	--fsettletype		VARCHAR(200),
	--FSettleNo		VARCHAR(200),
	--AttachFileCount	INT,
	--Comment			VARCHAR(500),
	--FChecked		INT,
	--Audited			INT,
	--IfCheck			VARCHAR(2),
	--Fdc				INT,
	--BillType		INT,
	--markerror		VARCHAR(200),
	--billState		VARCHAR(10),
	--VoucherType		INT,
	--ID				INT,
	FPeriod			INT,
	AscIds			VARCHAR(4000)
)'
EXEC(@Str)
 --------------------------------------sql主体 begin---------------------------------------------
SET @Str='
	INSERT '+N'##'+@TableName+'
	SELECT 
		vc.BillNumberId
		,
		--bill.BillNumberId nid,
		--vc.BillDate,
		--CONVERT(VARCHAR(4),vc.FYear)+''年第''+ CONVERT(VARCHAR(2),vc.FPeriod) +''期'' FPeriodDate,
		--vc.FSerialNum,
		--gr.FullName+''-''+CONVERT(VARCHAR(10),vc.FlowNo) FullName,
		vc.FlowNo,
		--bill.RowNo,
		--bill.Summary,
		--at.UserCode TypeCode,
		--at.FullName TypeName, 
		--cc.fullname currencyName,
		--CASE WHEN bill.FAdc=1 THEN bill.FdebitTotalFor ELSE bill.FcreditTotalFor END FAmountFor,
		--bill.FDebitTotal,
		--bill.FCreditTotal,
		--vc.ETypeId,
		--CASE WHEN vc.FChecked=1 THEN vc.AuditId ELSE '''' END AuditId,
		--vc.TallyId,
		--vc.recheckId,
		--abt.fullname fsettletype,
		--bill.FSettleNo,
		--vc.AttachFileCount,
		--bill.Comment,
		--vc.FChecked,
		--vc.Audited,
		--vc.IfCheck,
		--bill.Fdc,
		--210 AS BillType,
		--vc.markerror,
		----dbo.F_GetAssistCheckItemsName(bill.ID) checkitemName,
		--CASE 
		--	WHEN FChecked=0 AND IfCheck = ''f'' AND ISNULL(MarkError,'''')='''' AND ISNULL(ReCheckId,'''')='''' AND IfCheck = ''f'' THEN ''保存''
		--	WHEN FChecked=1 AND IfCheck = ''f'' AND ISNULL(ReCheckId,'''')='''' AND ISNULL(ReCheckId,'''')='''' AND IfCheck = ''f''  THEN ''审核''
		--	WHEN ISNULL(ReCheckId,'''')<>'''' AND IfCheck = ''f'' THEN ''已复核''
		--	WHEN IfCheck=''t'' THEN ''已记账'' 
		--	WHEN FChecked=-1 AND IfCheck = ''f'' THEN ''作废''
		--	WHEN ISNULL(MarkError,'''')<>'''' AND IfCheck = ''f'' THEN ''标错'' END billState,
		--vc.VoucherType,
		--bill.ID,
		vc.FPeriod,
		bill.AscIds
	FROM Ac_Voucher vc 
	INNER JOIN Ac_Voucher_Bill bill ON VC.BillNumberId=bill.BillNumberId
	INNER JOIN Ac_Voucher_Group gr on gr.VgId=vc.VgId 
	INNER JOIN Ac_Currency cc ON cc.cid=bill.cid
	INNER JOIN Ac_Account at ON at.TypeId=bill.ATypeId and vc.stypeid=at.stypeid
	INNER JOIN Ac_VoucherType VT ON VT.Id=vc.VoucherType
	'+CHAR(13)
	
--------------------------------------sql 主体 end---------------------------------------------
 
--------------------------------------定义临时表begin---------------------------------------------
--分支机构
CREATE TABLE #Stype (BillNumberId VARCHAR(50))
IF ISNULL(@stypeid,'')<>''
	BEGIN
		INSERT INTO #Stype(BillNumberId)
		SELECT vc.BillNumberId
		FROM Ac_Voucher vc
		INNER JOIN F_GetAllManagerBaseTypeId(@stypeid,11,@operatorid) F ON F.TypeId=vc.STypeId 
		
		SET @TbStr+='INNER JOIN #Stype Stype ON Stype.BillNumberId=vc.BillNumberId'+CHAR(13)
	END
	
--币种
CREATE TABLE #Ctype(BillNumberId VARCHAR(50))
IF ISNULL(@cid,'')<>''
	BEGIN
		INSERT INTO	#Ctype(BillNumberId)
		SELECT bill.BillNumberId
		FROM Ac_Voucher_Bill bill
		INNER JOIN F_GetAllManagerBaseByTypeId(@cid,16,@OperatorID,@stypeid) F ON F.TypeId=bill.Cid
		GROUP BY bill.BillNumberId
		
		SET @TbStr+='INNER JOIN #Ctype Ctype ON Ctype.BillNumberId=vc.BillNumberId'+CHAR(13)
	END

--凭证字
CREATE TABLE #Vtype (BillNumberId VARCHAR(50))
IF ISNULL(@vgid,'')<>''
	BEGIN
			INSERT INTO #Vtype(BillNumberId)
			SELECT vc.BillNumberId
			FROM Ac_Voucher vc
			INNER JOIN F_GetAllManagerBaseByTypeId(@vgid,15,@OperatorID,@stypeid) F ON F.TypeId=vc.VgId
			GROUP BY vc.BillNumberId
		SET @TbStr+='INNER JOIN #Vtype Vtype ON Vtype.BillNumberId=vc.BillNumberId'+CHAR(13)
	END

--科目
CREATE TABLE #Atype(BillNumberId VARCHAR(50))
IF ISNULL(@atypeid,'')<>''
	BEGIN
		INSERT INTO	#Atype(BillNumberId)
		SELECT bill.BillNumberId
		FROM Ac_Voucher_Bill bill
		INNER JOIN F_GetAllManagerBaseByTypeId(@atypeid,18,@OperatorID,@stypeid) F ON F.TypeId=bill.ATypeId	
		GROUP BY bill.BillNumberId
		
		SET @TbStr+='INNER JOIN #Atype Atype ON Atype.BillNumberId=vc.BillNumberId'+CHAR(13)
	END
	
--制单人
CREATE TABLE #E_type (BillNumberId VARCHAR(50))
IF ISNULL(@etypeid,'')<>''
	BEGIN
		INSERT INTO	#E_type(BillNumberId)
		SELECT vc.BillNumberId
		FROM Ac_Voucher vc
		INNER JOIN F_GetAllManagerBaseByTypeId(@etypeid,3,@OperatorID,@stypeid) F ON F.TypeId=vc.ETypeId
		GROUP BY vc.BillNumberId
		
		SET @TbStr+='INNER JOIN #E_type E_type ON E_type.BillNumberId=vc.BillNumberId'+CHAR(13)
	END

--审核人
CREATE TABLE #A_type (BillNumberId VARCHAR(50))
IF ISNULL(@auditid,'')<>''
	BEGIN
		INSERT INTO	#A_type(BillNumberId)
		SELECT vc.BillNumberId
		FROM Ac_Voucher vc
		INNER JOIN F_GetAllManagerBaseByTypeId(@auditid,3,@OperatorID,@stypeid) F ON F.TypeId=vc.AuditId
		GROUP BY vc.BillNumberId
			
		SET @TbStr+='INNER JOIN #A_type A_type ON A_type.BillNumberId=vc.BillNumberId'+CHAR(13)
	END

--复核人
CREATE TABLE #R_type (BillNumberId VARCHAR(50))
IF ISNULL(@recheckid,'')<>''
	BEGIN
		INSERT INTO	#R_type(BillNumberId)
		SELECT vc.BillNumberId
		FROM Ac_Voucher vc
		INNER JOIN F_GetAllManagerBaseByTypeId(@recheckid,3,@OperatorID,@stypeid) F ON F.TypeId=vc.ReCheckId
		GROUP BY vc.BillNumberId

		SET @TbStr+='INNER JOIN #R_type R_type ON R_type.BillNumberId=vc.BillNumberId'+CHAR(13)
	END

--记账人
CREATE TABLE #T_type (BillNumberId VARCHAR(50))
IF ISNULL(@tallyid,'')<>''
	BEGIN
		INSERT INTO	#T_type(BillNumberId)
		SELECT vc.BillNumberId
		FROM Ac_Voucher vc
		INNER JOIN F_GetAllManagerBaseByTypeId(@tallyid,3,@OperatorID,@stypeid) F ON F.TypeId=vc.TallyId
		GROUP BY vc.BillNumberId
					
		SET @TbStr+='INNER JOIN #T_type T_type ON T_type.BillNumberId=vc.BillNumberId'+CHAR(13)
	END

--摘要
CREATE TABLE #Summary (BillNumberId VARCHAR(50))
IF ISNULL(@summary,'')<>''
	BEGIN
		INSERT INTO	#Summary(BillNumberId)
		SELECT vc.BillNumberId
		FROM Ac_Voucher vc
		INNER JOIN Ac_Voucher_Bill bill ON bill.BillNumberId=vc.BillNumberId AND bill.Summary like '%'+@summary+'%'
		GROUP BY vc.BillNumberId
					
		SET @TbStr+='INNER JOIN #Summary summary ON summary.BillNumberId=vc.BillNumberId'+CHAR(13)
	END
	
--原币
CREATE TABLE #yfdctype (BillNumberId VARCHAR(50))
DECLARE @yfdcStr VARCHAR(MAX)=''
--原币
IF(ISNULL(@yfdc,'')<>'' OR ISNULL(@ystarttotal,'')<>'' OR ISNULL(@yendtotal,'')<>'')
	BEGIN
		SET @yfdcStr+='INSERT INTO #yfdctype(BillNumberId)
									SELECT bill.BillNumberId
									FROM Ac_Voucher_Bill bill 
									WHERE 1=1 '
		IF(ISNULL(@yfdc,'')<>'')
			BEGIN
				SET @yfdcStr+='	AND (bill.FAdc='+@yfdc 
				IF(ISNULL(@ystarttotal,'')<>'' OR ISNULL(@yendtotal,'')<>'')
					BEGIN
						IF(@yfdc='1')--借
							BEGIN
								IF(ISNULL(@ystarttotal,'')<>'')--原币>=
									SET @yfdcStr+=' AND  Bill.FDebitTotalFor>='+@ystarttotal
								IF(ISNULL(@yrealtionship,'')<>'' AND ISNULL(@yendtotal,'')<>'')--且/或不为空 原币<=
									SET @yfdcStr+=' '+@yrealtionship+' Bill.FDebitTotalFor<='+@yendtotal
								ELSE IF(ISNULL(@yrealtionship,'')='' AND ISNULL(@yendtotal,'')<>'')--且/或为空 原币<=
									SET @yfdcStr+=' AND Bill.FDebitTotalFor<='+@yendtotal
							END
						ELSE IF(@yfdc='-1')--贷
							BEGIN
								IF(ISNULL(@ystarttotal,'')<>'')--原币>=
									SET @yfdcStr+=' AND Bill.FCreditTotalFor>='+@ystarttotal
								IF(ISNULL(@yrealtionship,'')<>''AND ISNULL(@yendtotal,'')<>'')--且/或不为空 原币<=
									SET @yfdcStr+=' '+@yrealtionship+' Bill.FCreditTotalFor<='+@yendtotal
								IF(ISNULL(@yrealtionship,'')='' AND ISNULL(@yendtotal,'')<>'')--且/或为空 原币<=
									SET @yfdcStr+=' AND Bill.FCreditTotalFor<='+@yendtotal
							END
					END
				SET @yfdcStr+=' )'
			END
		ELSE IF((ISNULL(@ystarttotal,'')<>'' OR ISNULL(@yendtotal,'')<>'') AND (ISNULL(@yfdc,'')='' AND ISNULL(@yrealtionship,'')=''))
			BEGIN
				IF(ISNULL(@ystarttotal,'')<>'')
					SET @yfdcStr+=' AND (Bill.FDebitTotalFor>='+@ystarttotal+' OR Bill.FCreditTotalFor>='+@ystarttotal+' ) ' --zs001:少一个关键字  李灏龙暂补
				IF(ISNULL(@yrealtionship,'')<>'' AND ISNULL(@yendtotal,'')<>'')
					SET @yfdcStr+=@yrealtionship+' (Bill.FDebitTotalFor<='+@yendtotal+' OR Bill.FCreditTotalFor<='+@yendtotal+' )'
				ELSE IF(ISNULL(@yrealtionship,'')='' AND ISNULL(@yendtotal,'')<>'')
					SET @yfdcStr+=' AND (Bill.FDebitTotalFor<='+@yendtotal+' OR Bill.FCreditTotalFor<='+@yendtotal+' )'
			END
		SET @yfdcStr+='			GROUP BY bill.BillNumberId'
		EXEC(@yfdcStr)
		SET @TbStr+='INNER JOIN #yfdctype yfdctype ON yfdctype.BillNumberId=vc.BillNumberId'+CHAR(13)
	END
--本币
CREATE TABLE #bfdctype (BillNumberId VARCHAR(50))
DECLARE @bfdctypeStr VARCHAR(MAX)=''
--本币
IF(ISNULL(@bfdc,'')<>'' OR ISNULL(@bstarttotal,'')<>'' OR ISNULL(@bendtotal,'')<>'')
	BEGIN
		SET @bfdctypeStr+='INSERT INTO #bfdctype(BillNumberId)
									SELECT bill.BillNumberId
									FROM Ac_Voucher_Bill bill 
									WHERE 1=1 '
		IF(ISNULL(@bfdc,'')<>'')
			BEGIN
				SET @bfdctypeStr+='	AND (bill.FAdc='+@bfdc 
				IF(ISNULL(@bstarttotal,'')<>'' OR ISNULL(@bendtotal,'')<>'')
					BEGIN
						IF(@bfdc='1')--借
							BEGIN
								IF(ISNULL(@bstarttotal,'')<>'')--本币>=
									SET @bfdctypeStr+=' AND Bill.FDebitTotal>='+@bstarttotal
								IF(ISNULL(@brealtionship,'')<>'' AND ISNULL(@bendtotal,'')<>'')--且/或不为空 本币<=
									SET @bfdctypeStr+=' '+@brealtionship+' Bill.FDebitTotal<='+@bendtotal
								ELSE IF(ISNULL(@brealtionship,'')='' AND ISNULL(@bendtotal,'')<>'')--且/或为空 本币<=
									SET @bfdctypeStr+=' AND Bill.FDebitTotal<='+@bendtotal
							END
						ELSE IF(@bfdc='-1')--贷
							BEGIN
								IF(ISNULL(@bstarttotal,'')<>'')--原币>=
									SET @bfdctypeStr+=' AND Bill.FCreditTotal>='+@bstarttotal
								IF(ISNULL(@brealtionship,'')<>''AND ISNULL(@bendtotal,'')<>'')--且/或不为空 本币<=
									SET @bfdctypeStr+=' '+@brealtionship+' Bill.FCreditTotal<='+@bendtotal
								IF(ISNULL(@brealtionship,'')='' AND ISNULL(@bendtotal,'')<>'')--且/或为空 本币<=
									SET @bfdctypeStr+=' AND Bill.FCreditTotal<='+@bendtotal

							END
						
					END
				SET @bfdctypeStr+=' )'
			END
		ELSE IF((ISNULL(@bstarttotal,'')<>'' OR ISNULL(@bendtotal,'')<>'') AND (ISNULL(@bfdc,'')='' AND ISNULL(@brealtionship,'')=''))
			BEGIN
				IF(ISNULL(@bstarttotal,'')<>'')
					SET @bfdctypeStr+=' AND (Bill.FDebitTotal>='+@bstarttotal+' OR Bill.FCreditTotal>='+@bstarttotal+' ) '  --zs001: 少一个关键字 李灏龙暂补
				IF(ISNULL(@brealtionship,'')<>'' AND ISNULL(@bendtotal,'')<>'')
					SET @bfdctypeStr+=@brealtionship+' (Bill.FDebitTotal<='+@bendtotal+' OR Bill.FCreditTotal<='+@bendtotal+' )'
				ELSE IF(ISNULL(@brealtionship,'')='' AND ISNULL(@bendtotal,'')<>'')
					SET @bfdctypeStr+=' AND (Bill.FDebitTotal<='+@bendtotal+' OR Bill.FCreditTotal<='+@bendtotal+' )'
			END
		
		SET @bfdctypeStr+='			GROUP BY bill.BillNumberId'
		EXEC (@bfdctypeStr)
		SET @TbStr+='INNER JOIN #bfdctype bfdctype ON bfdctype.BillNumberId=vc.BillNumberId'+CHAR(13)
	END
	
SET @TbStr+='
	LEFT JOIN Ac_BalanceType abt on abt.BtId=bill.fsettletypeid '	
--------------------------------------定义临时表end---------------------------------------------

--------------------------------------sql where begin---------------------------------------------
SET @Link+='	WHERE 1=1 '+CHAR(13)

--期间/凭证字选择
IF(ISNULL(@dateChoose,'')='0')
	BEGIN
		IF(ISNULL(@startfperiod,'')<>'' AND ISNULL(@endfperiod,'')<>'')
			SET @WhStr+='	AND vc.Fperiod>='+@startfperiod+' AND vc.Fperiod<='+@endfperiod+CHAR(13)
		ELSE IF(ISNULL(@startfperiod,'')='' AND ISNULL(@endfperiod,'')<>'')
			SET @WhStr+='	AND vc.Fperiod <='+@endfperiod+CHAR(13)
		ELSE IF(ISNULL(@startfperiod,'')<>'' AND ISNULL(@endfperiod,'')='')
			SET @WhStr+='	AND vc.Fperiod >='+@startfperiod+CHAR(13)	
	END
ELSE IF ISNULL(@dateChoose,'')='1'
	BEGIN
		IF(ISNULL(@startbilldate,'')<>'' AND ISNULL(@endbilldate,'')<>'')
			SET @WhStr+='	AND vc.BillDate >='''+@startbilldate+''' AND vc.BillDate<='''+@endbilldate+''''+CHAR(13)
		ELSE IF(ISNULL(@startbilldate,'')='' AND ISNULL(@endbilldate,'')<>'')
			SET @WhStr+='	AND vc.BillDate <='''+@endbilldate+''''+CHAR(13)
		ELSE IF(ISNULL(@startbilldate,'')<>'' AND ISNULL(@endbilldate,'')='')
			SET @WhStr+='	AND vc.BillDate >='''+@startbilldate+''''+CHAR(13)	
	END 
	
--凭证号	
IF(ISNULL(@startfserialnum,'')<>'' AND ISNULL(@endfserialnum,'')<>'')
	SET @WhStr+='	AND vc.FlowNo>='+@startfserialnum+' AND vc.FlowNo<='+@endfserialnum+''+CHAR(13)
ELSE IF(ISNULL(@startfserialnum,'')<>'' AND ISNULL(@endfserialnum,'')='')
	SET @WhStr+='	AND vc.FlowNo >='+@startfserialnum+CHAR(13)
ELSE IF(ISNULL(@startfserialnum,'')='' AND ISNULL(@endfserialnum,'')<>'')
	SET @WhStr+='	AND vc.FlowNo <='+@endfserialnum+CHAR(13)

IF(ISNULL(@fchecked,'')<>'')--是否审核
	SET @WhStr+='	AND vc.FChecked='+@fchecked+CHAR(13)
IF(ISNULL(@audited,'')<>'')--是否过账
	SET @WhStr+='	AND vc.Audited='+@audited+CHAR(13)
IF(ISNULL(@vouchertype,'')<>'')--凭证类型
	SET @WhStr+=' AND vc.VoucherType in('+@vouchertype+')'+CHAR(13)

--------------------------------------sql where end---------------------------------------------

--PRINT @Str+@TbStr+@Link+@WhStr
EXEC(@Str+@TbStr+@Link+@WhStr)--执行sql语句



--=========================================满足辅助核算条件的凭证【BEGIN】==============================================
CREATE TABLE #BillNumberId(BillNumberId NUMERIC(18,0))--满足条件凭证
CREATE TABLE #Bill_BillNumberId(BillNumberId NUMERIC(18,0))--不包含辅助核算的凭证
CREATE TABLE #AscIds_BillNumberId(BillNumberId NUMERIC(18,0))--包含辅助核算的凭证

--包含辅助核算的凭证
SET @Str='
INSERT INTO #AscIds_BillNumberId(BillNumberId) SELECT BillNumberId FROM '+N'##'+@TableName+'  WHERE ISNULL(AscIds,'''')<>'''' GROUP BY BillNumberId'
EXEC(@Str)


SET @Str='INSERT INTO #BillNumberId(BillNumberId)'+CHAR(13)
	
IF(ISNULL(@stypeid1,'')='' AND ISNULL(@dtypeid,'')='' AND ISNULL(@staftypeid,'')='' AND ISNULL(@companytypeid,'')='')	
	BEGIN
		--不包含辅助核算的凭证
		INSERT INTO #Bill_BillNumberId(BillNumberId) SELECT BillNumberId FROM Ac_Voucher WHERE BillNumberId NOT IN(SELECT BillNumberId FROM #AscIds_BillNumberId)
		
		SET @Str+='	SELECT BillNumberId FROM #Bill_BillNumberId  UNION ALL'+CHAR(13)
	END

SET @Str+='SELECT bill.BillNumberId FROM #AscIds_BillNumberId bill'+CHAR(13)
/***辅助核算***/
--分支机构
CREATE TABLE #Stype1 (BillNumberId VARCHAR(50))
INSERT INTO #Stype1(BillNumberId)
SELECT item.BillNumberId
FROM Ac_Voucher_Bill_Assist_CheckItems item
INNER JOIN F_GetAllManagerBaseByTypeId(ISNULL(@stypeid1,''),11,@OperatorID,@stypeid) F ON F.TypeId=item.TypeId 
WHERE item.typeName='01'
GROUP BY item.BillNumberId
IF ISNULL(@stypeid1,'')<>''
	BEGIN
		SET @Str+='INNER JOIN #Stype1 Stype1 ON Stype1.BillNumberId=bill.BillNumberId'+CHAR(13)
	END

	
--部门
CREATE TABLE #Dtype (BillNumberId VARCHAR(50))
INSERT INTO #Dtype(BillNumberId)
SELECT item.BillNumberId
FROM Ac_Voucher_Bill_Assist_CheckItems item
INNER JOIN  F_GetAllManagerBaseByTypeId(ISNULL(@dtypeid,''),9,@OperatorID,@stypeid)F ON F.TypeId=item.TypeId
WHERE item.typeName='02'
GROUP BY item.BillNumberId

IF ISNULL(@dtypeid,'')<>''
	SET @Str+='INNER JOIN #Dtype Dtype ON Dtype.BillNumberId=bill.BillNumberId'+CHAR(13)

--职员
CREATE TABLE #Etype (BillNumberId VARCHAR(50))
INSERT INTO #Etype(BillNumberId)
SELECT item.BillNumberId
FROM Ac_Voucher_Bill_Assist_CheckItems item
INNER JOIN  F_GetAllManagerBaseByTypeId(ISNULL(@staftypeid,''),3,@OperatorID,@stypeid)F ON F.TypeId=item.TypeId
WHERE item.typeName='03'
GROUP BY item.BillNumberId

IF ISNULL(@staftypeid,'')<>''
	SET @Str+='INNER JOIN #Etype Etype ON Etype.BillNumberId=bill.BillNumberId'+CHAR(13)

--往来单位
CREATE TABLE #Comtype (BillNumberId VARCHAR(50))

INSERT INTO	#Comtype(BillNumberId)
SELECT  item.BillNumberId
FROM Ac_Voucher_Bill_Assist_CheckItems item
INNER JOIN  F_GetAllManagerBaseTypeId(ISNULL(@companytypeid,''),2,@OperatorID)F ON F.TypeId=item.TypeId
WHERE item.typeName='04'
GROUP BY item.BillNumberId
IF ISNULL(@companytypeid,'')<>''
	SET @Str+='INNER JOIN #Comtype Comtype ON Comtype.BillNumberId=bill.BillNumberId'+CHAR(13)

--当辅助核算查询条件都未空时，判断全部权限
IF ISNULL(@stypeid1,'')='' AND ISNULL(@dtypeid,'')='' AND  ISNULL(@staftypeid,'')='' AND ISNULL(@companytypeid,'')=''
	BEGIN
		SET @Str+='WHERE 
						bill.BillNumberId IN(SELECT BillNumberId FROM #Stype1)
						OR bill.BillNumberId IN(SELECT BillNumberId FROM #Dtype)
						OR bill.BillNumberId IN(SELECT BillNumberId FROM #Etype)
						OR bill.BillNumberId IN(SELECT BillNumberId FROM #Comtype)'
	END

EXEC(@Str)  

--=========================================满足辅助核算条件的凭证【END】==============================================

------------------------------------执行 sql并drop临时表 begin--------------------------------
				
--DECLARE @RetCount		VARCHAR(50)='',
--		@Fdebittotal	 NUMERIC(24, 10) ,
--		@Fcredittotal	 NUMERIC(24, 10) 
----计算凭证总条数
--SELECT @Str='SELECT @RetCount=COUNT(*),@Fdebittotal=sum(Fdebittotal),@Fcredittotal=sum(Fcredittotal) FROM '+N'##'+@TableName +' A  INNER JOIN #BillNumberId B ON B.BillNumberId=A.BillNumberId'
--exec sp_executesql @Str,N'@RetCount int out,@Fdebittotal  NUMERIC(24, 10)  out,@Fcredittotal  NUMERIC(24, 10)  out ',@outRet out,@sumFdebittotal out,@sumFcredittotal out

DROP TABLE #Dtype,#Comtype,#Stype1,#Etype,#Atype,#Ctype,#Vtype,#E_type,#A_type,#R_type,#T_type,#yfdctype,#bfdctype,#Stype,#AscIds_BillNumberId,#Bill_BillNumberId

--IF(@nPageCol<=1)
--	BEGIN
		SELECT @Str= '
				
				SELECT	DISTINCT A.BillNumberId,A.FPeriod,A.FlowNo
				FROM '+N'##'+@TableName+' A  
				INNER JOIN #BillNumberId B ON B.BillNumberId=A.BillNumberId
				ORDER BY FPeriod,FlowNo,A.BillNumberId
				DROP TABLE '+N'##'+@TableName
--	END
--ELSE 
--	BEGIN
--		SELECT @Str='
--			SELECT TOP '+CAST(@nPageColSize AS varchar(50))+' *
--			FROM '+N'##'+@TableName+'
--			WHERE BID NOT IN(
--				SELECT TOP '+CAST((@nPageCol-1)*@nPageColSize AS varchar(50))+' BID
--				FROM '+N'##'+@TableName+' A
--				INNER JOIN #BillNumberId B ON B.BillNumberId=A.BillNumberId
--				ORDER BY FPeriod,FlowNo,A.BillNumberId,RowNo
--			)
--			ORDER BY FPeriod,FlowNo,BillNumberId,RowNo
--			DROP TABLE '+N'##'+@TableName
--	END
	

EXEC (@Str)
DROP TABLE  #BillNumberId
--------------------------------------执行 sql并drop临时表 begin---------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AcVoucherQuery]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_AcVoucherQuery
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回凭证查询条件查询出列表信息
-- 时间：	2012-04-21
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Web_AcVoucherQuery
(
	@stypeid			VARCHAR(400),		--分支结构
	@Fyear				VARCHAR(10),		--年度
	@vouchertype		VARCHAR(MAX),		--凭证类型
	@dateChoose			VARCHAR(1),			--期间选择0 期间 1凭证日期
	@startfperiod		VARCHAR(2),			--开始期间 @startfperiod @endfperiod
	@endfperiod			VARCHAR(2),			--截止期间
	@startbilldate		VARCHAR(50),		-- 凭证开始日期
	@endbilldate		VARCHAR(50),		--凭证截止日期
	@atypeid			VARCHAR(MAX),		--科目
	@cid				VARCHAR(MAX),		--币别
	@summary			VARCHAR(400),		--摘要
	@vgid				VARCHAR(500),		--凭证字
	@startfserialnum	VARCHAR(100),		--开始_凭证号
	@endfserialnum		VARCHAR(100),		--截止_凭证号
	@yfdc				VARCHAR(2),			--原币借贷关系
	@ystarttotal		VARCHAR(50),		--原币金额
 	@yrealtionship		VARCHAR(5) ,		--原币且或关系
	@yendtotal			VARCHAR(50),		--原币金额
	@bfdc				VARCHAR(2),			--本币借贷关系
	@bstarttotal		VARCHAR(50),		--本币金额
	@brealtionship		VARCHAR(5) ,		--本币且或关系
	@bendtotal			VARCHAR(50),		--本币金额
	@etypeid			VARCHAR(MAX),		--制单人
	@auditid			VARCHAR(MAX),		--审核人
	@recheckid			VARCHAR(MAX),		--复核人
	@tellerid			VARCHAR(MAX),		--出纳人  --add by2014-07-02
	@tallyid			VARCHAR(MAX),		--记账人
	@fchecked			VARCHAR(1),			--是否审核
	@audited			VARCHAR(1),			--是否过账
	@operatorid			VARCHAR(100),		--当前操作人
	@stypeid1			VARCHAR(MAX),		--辅助核算 分支结构
	@dtypeid			VARCHAR(MAX),		--部门
	@staftypeid			VARCHAR(MAX),		--职员
	@companytypeid		VARCHAR(MAX),		--往来单位
	@TypeId05			VARCHAR(MAX)='',	--自定义
	@TypeId06			VARCHAR(MAX)='',	--自定义
	@TypeId07			VARCHAR(MAX)='',	--自定义
	@TypeId08			VARCHAR(MAX)='',	--自定义
	@TypeId09			VARCHAR(MAX)='',	--自定义
	@OrderStr			VARCHAR(MAX),		--排序字段
	@isteller			INT=0,				--出纳签字查询
	@IncludeSign		INT=0,				--是否包含出纳已签字(出纳签字共用此存储过程)
	@ShowType			INT	,				--1:凭证分录模式 2：单据格式
	@customAssistItem   VARCHAR(MAX),        --自定义辅助核算项typeid,以逗号分隔
	@injournal			INT=0				--登入日记账过滤：0全部，1未登入的，2已登入的
)

--@encode$--
AS
SET NOCOUNT ON 
DECLARE 
	@Str			VARCHAR(MAX)='',	--sql主体语句
	@TbStr			VARCHAR(MAX)='',	--sql关联语句
	@Link			VARCHAR(MAX)='',	--关联 sql
	@WhStr			VARCHAR(MAX)='',	--是否需要辅助项目
	@Result			VARCHAR(MAX)='',	--排序语句
	@ShowItemsName	VARCHAR(5)='',		--是否显示报表辅助核算列
	@AssistLimit	VARCHAR(5)='',		--操作员记忆列显示与否
	@LimitOwnVoucher INT=0				--【仅能查看本人制单的会计凭证】
	
	
IF @isteller=1
	SELECT @ShowItemsName=ISNULL(Display,0) FROM LoginUserCol WHERE ColDataField='tellerQuery' AND ETypeID=@operatorid
ELSE 	
	SELECT @ShowItemsName=ISNULL(Display,0) FROM LoginUserCol WHERE ColDataField='voucherQuery' AND ETypeID=@operatorid
	
SELECT @AssistLimit=SUBSTRING(lim,4687,1) FROM LoginUser WHERE etypeid=@operatorid
 
 --仅能查看本人制单的会计凭证
IF(@OperatorId<>'00001')
	SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@operatorid

 --------------------------------------sql主体 begin---------------------------------------------
SET @Str='
SELECT	DISTINCT
		BillNumberId,
		BillDate,
		FPeriodDate,
		FSerialNum,
		grFullName ,
		FullName,
		FlowNo,
		nid,
		Summary,
		TypeCode,
		TypeName,
		currencyName,
		FAmountFor,
		FDebitTotal,
		FCreditTotal,
		ID,
		AscIds,
		fsettletype,
		FSettleNo,
		STypeID,
		FComment,
		TotalFor,
		Fdc,
		Comment,
		ETypeId,
		AuditId,
		TallyId,
		recheckId,
		AttachFileCount,
		Teller,
		FChecked,
		Audited,
		IfCheck,
		BillType,
		markerror,
		billState,
		VoucherType,
		FPeriod,
		RChecker rauditid,
		vouchertypename vouchertypename,
		IsCommission,
		'+CASE WHEN (@isteller=1 AND ISNULL(@ShowItemsName,'')='') OR(@isteller<>1 AND ISNULL(@ShowItemsName,'')='' AND @AssistLimit=1)  THEN ' dbo.F_GetAssistCheckItemsName(ID,'''+@operatorid+''',STypeId)' ELSE '''''' END +' assist,
		injournal
FROM(
	SELECT 
		vc.BillNumberId,
		vc.BillDate,
		CONVERT(VARCHAR(4),vc.FYear)+''年第''+ CONVERT(VARCHAR(2),vc.FPeriod) +''期'' FPeriodDate,
		vc.FSerialNum,
		gr.FullName grFullName ,
		gr.FullName+''-''+CONVERT(VARCHAR(10),vc.FlowNo) FullName,
		vc.FlowNo,'
IF(@ShowType IN(2,3))
	BEGIN
		SET @Str+='
	bill.BillNumberId nid,
	'''' Summary,
	'''' TypeCode,
	'''' TypeName,
	'''' currencyName,
	0 FAmountFor,
	0 FDebitTotal,
	0 FCreditTotal,
	0 ID,
	'''' AscIds,
	'''' fsettletype,
	'''' FSettleNo,
	bill.STypeID,
	VC.FComment,
	VC.FDebitTotal TotalFor,
	0 Fdc,
	'''' Comment,
	'
	END
ELSE 
	BEGIN
		SET @Str+='
	bill.BillNumberId nid,
	bill.Summary,	--dbo.F_GetSummaryByLimit(bill.ID,'''+@operatorid+''',bill.STypeID,bill.Summary) Summary,
	CASE WHEN ISNULL(bill.ATypeId,'''')<>'''' AND ISNULL(F.TypeId,'''')='''' THEN ''****''
		WHEN ISNULL(bill.ATypeId,'''')='''' THEN '''' 
		ELSE at.UserCode 
	END TypeCode,
	CASE WHEN ISNULL(bill.ATypeId,'''')<>'''' AND ISNULL(F.TypeId,'''')='''' THEN ''****'' 
		WHEN ISNULL(bill.ATypeId,'''')='''' THEN '''' 
		ELSE at.FullName 
	END TypeName,
	cc.fullname currencyName,
	CASE WHEN bill.FAdc=1 THEN bill.FdebitTotalFor ELSE bill.FcreditTotalFor END FAmountFor,
	bill.FDebitTotal,
	bill.FCreditTotal,
	bill.ID,
	bill.AscIds,
	abt.fullname fsettletype,
	isnull(bill.FSettleNo,'''') as FSettleNo,
	bill.STypeID,
	'''' FComment,
	0 TotalFor,
	bill.Fdc,
	bill.Comment,
	'
	END
SET @Str+='
		vc.ETypeId,
		CASE WHEN vc.FChecked=1 THEN vc.AuditId ELSE '''' END AuditId,
		vc.TallyId,
		vc.recheckId,
		vc.AttachFileCount,
		isnull(vc.Teller,'''') as Teller,
		vc.FChecked,
		vc.Audited,
		vc.IfCheck,
		210 AS BillType,
		vc.markerror,
		vc.RChecker,
		CASE 
			WHEN FChecked=0 AND IfCheck = ''f'' AND ISNULL(MarkError,'''')='''' AND ISNULL(ReCheckId,'''')='''' AND IfCheck = ''f'' THEN ''保存''
			WHEN FChecked=1 AND IfCheck = ''f'' AND ISNULL(ReCheckId,'''')='''' AND ISNULL(ReCheckId,'''')='''' AND IfCheck = ''f''  THEN ''审核''
			WHEN ISNULL(ReCheckId,'''')<>'''' AND IfCheck = ''f'' THEN ''已复核''
			WHEN IfCheck=''t'' THEN ''已记账'' 
			WHEN FChecked=-1 AND IfCheck = ''f'' THEN ''作废''
			WHEN ISNULL(MarkError,'''')<>'''' AND IfCheck = ''f'' THEN ''标错'' END billState,
		vc.VoucherType,
		vc.FPeriod,
		VT.FullName vouchertypename,
		vc.IsCommission,
		CASE WHEN isnull(TJD.ID,'''') ='''' THEN '''' ELSE ''登入'' END AS injournal
	FROM Ac_Voucher vc 
	INNER JOIN Ac_Voucher_Bill bill ON bill.BillNumberId=vc.BillNumberId AND vc.FYear='+CAST(@Fyear AS VARCHAR(4))+'
	INNER JOIN Ac_VoucherType VT ON VT.Id=vc.VoucherType
	INNER JOIN Ac_Account at ON at.TypeId=bill.ATypeId AND bill.stypeid=at.stypeid
	LEFT JOIN Ac_Voucher_Group gr on gr.VgId=vc.VgId 
	LEFT JOIN Ac_Currency cc ON cc.cid=bill.cid	
	LEFT JOIN #F_LineAccount F ON F.TypeId=at.TypeId AND F.StypeId=at.StypeId
	LEFT JOIN te_journal_Detail TJD ON TJD.VOUCHERID = BILL.ID
	'+CHAR(13)
	
--------------------------------------sql 主体 end---------------------------------------------
--科目
CREATE TABLE #F_LineAccount(TYPEID VARCHAR(50),STYPEID VARCHAR(50))
INSERT INTO #F_LineAccount(TYPEID,STYPEID)
SELECT	Typeid,Stypeid
FROM	F_LineAccount(@OperatorID,@STypeId)

--科目
--因为是包含有查询科目的分录，则整张凭证就要显示，所以要统计符合条件的billnumberid，而不能直接用科目去过滤
CREATE TABLE #AcAccount(BillNumberId VARCHAR(50))
IF ISNULL(@isteller,0)=1
	BEGIN
		INSERT INTO	#AcAccount(BillNumberId)
		SELECT bill.BillNumberId
		FROM Ac_Voucher_Bill bill
		INNER JOIN Ac_Account C ON bill.ATypeId = C.TypeId AND bill.STypeId = C.STypeId AND (C.Isbank = 1 OR C.IsCash = 1)
		GROUP BY bill.BillNumberId
		
		SET @TbStr+='INNER JOIN #AcAccount AA ON AA.BillNumberId=vc.BillNumberId'+CHAR(13)
		--SET @TbStr+='INNER JOIN Ac_Account AA ON AA.TypeId=bill.ATypeId AND AA.STypeId = bill.STypeId AND (AA.Isbank = 1 OR AA.IsCash = 1)'
	END


--------------------------------------定义临时表begin---------------------------------------------
IF(ISNULL(@vouchertype,'')<>'')--凭证类型
	BEGIN
		SET @TbStr+=' INNER JOIN f_split('''+@vouchertype+''','','') F1 ON F1.a=vc.VoucherType'+CHAR(13)
	END
	
--自定义辅助核算项筛选 bug706
IF @customAssistItem IS NOT  NULL AND @customAssistItem != ''
BEGIN 
SELECT DISTINCT avb.BillNumberId INTO #BillnumberidTemp FROM Ac_Voucher_Bill_Assist_CheckItems avb  
LEFT  JOIN dbo.Ac_Assist_CheckItemsDetail acid ON acid.TypeId = avb.TypeId
LEFT JOIN Ac_Assist_CheckItems aci ON aci.AscIds = acid.AscIds 
WHERE avb.TypeId IN (SELECT * FROM dbo.f_split(@customAssistItem,','))
SET @TbStr+='INNER JOIN #BillnumberidTemp btemp ON btemp.BillNumberId = bill.BillNumberId'+CHAR(13)
END 
	
--分支机构
CREATE TABLE #F_Stype(typeid VARCHAR(50))
IF ISNULL(@stypeid,'')<>''
BEGIN
	INSERT INTO #F_Stype(typeid)
	SELECT	TypeId
	FROM	F_GetAllManagerBaseTypeId(@stypeid,11,@operatorid)
	--SET @TbStr+='INNER JOIN F_GetAllManagerBaseTypeId('''+@stypeid+''',11,'''+@operatorid+''') Stype ON Stype.TypeId=vc.STypeId'+CHAR(13)
	SET @TbStr+='INNER JOIN #F_Stype Stype ON Stype.TypeId=vc.STypeId'+CHAR(13)
END

--币种
CREATE TABLE #Ctype(BillNumberId NUMERIC(18,0))
IF ISNULL(@cid,'')<>''
BEGIN
	INSERT INTO	#Ctype(BillNumberId)
	SELECT bill.BillNumberId
	FROM	Ac_Voucher_Bill bill
	INNER JOIN 	F_GetAllManagerBaseByTypeId(@cid,16,@OperatorID,@stypeid) F ON F.TypeId = BILL.Cid
	GROUP BY bill.BillNumberId
	
	SET @TbStr+='INNER JOIN #Ctype Ctype ON Ctype.BillNumberId=VC.BillNumberId '+CHAR(13)
END

--凭证字
IF ISNULL(@vgid,'')<>''
	SET @TbStr+='INNER JOIN F_GetAllManagerBaseByTypeId('''+@vgid+''',15,'''+@OperatorID+''','''+@stypeid+''') Vtype ON Vtype.TypeId=vc.VgId'+CHAR(13)
	
--科目
CREATE TABLE #Atype(BillNumberId NUMERIC(18,0))
IF ISNULL(@atypeid,'')<>''
BEGIN
	INSERT INTO	#Atype(BillNumberId)
	SELECT	bill.BillNumberId
	FROM	Ac_Voucher_Bill bill
	INNER JOIN F_GetAllManagerBaseByTypeId(@atypeid,18,@OperatorID,@stypeid) F ON F.TypeId=bill.ATypeId	
	GROUP BY bill.BillNumberId
	
	SET @TbStr+='INNER JOIN #Atype Atype ON Atype.BillNumberId=vc.BillNumberId'+CHAR(13)
END
	
CREATE TABLE #F_EtypeWithType(Typeid VARCHAR(50),eType INT)
--制单人
IF ISNULL(@etypeid,'')<>''
BEGIN
	INSERT INTO #F_EtypeWithType(Typeid,eType)
	SELECT	TypeId,1
	FROM	F_GetAllManagerBaseByTypeId(@etypeid,3,@OperatorID,@stypeid)
	SET @TbStr+='INNER JOIN #F_EtypeWithType E_type ON E_type.eType = 1 AND E_type.TypeId=vc.ETypeId'+CHAR(13)
END

--审核人
IF ISNULL(@auditid,'')<>''
BEGIN
	INSERT INTO #F_EtypeWithType(Typeid,eType)
	SELECT	TypeId,2
	FROM	F_GetAllManagerBaseByTypeId(@auditid,3,@OperatorID,@stypeid)
	SET @TbStr+='INNER JOIN #F_EtypeWithType A_type ON A_type.eType = 2 AND A_type.TypeId=vc.AuditId'+CHAR(13)
END

--复核人
IF ISNULL(@recheckid,'')<>''
BEGIN
	INSERT INTO #F_EtypeWithType(Typeid,eType)
	SELECT	TypeId,3
	FROM	F_GetAllManagerBaseByTypeId(@recheckid,3,@OperatorID,@stypeid)
	SET @TbStr+='INNER JOIN #F_EtypeWithType R_type ON R_type.eType = 3 AND R_type.TypeId=vc.ReCheckId'+CHAR(13)
END

--出纳人
IF ISNULL(@tellerid,'')<>''
BEGIN
	INSERT INTO #F_EtypeWithType(Typeid,eType)
	SELECT	TypeId,4
	FROM	F_GetAllManagerBaseByTypeId(@tellerid,3,@OperatorID,@stypeid)
	SET @TbStr+='INNER JOIN #F_EtypeWithType Teller_type ON Teller_type.eType = 4 AND Teller_type.TypeId=vc.Teller'+CHAR(13)
END

--记账人
IF ISNULL(@tallyid,'')<>''
BEGIN
	INSERT INTO #F_EtypeWithType(Typeid,eType)
	SELECT	TypeId,5
	FROM	F_GetAllManagerBaseByTypeId(@tallyid,3,@OperatorID,@stypeid)
	SET @TbStr+='INNER JOIN #F_EtypeWithType T_type ON T_type.eType = 5 AND T_type.TypeId=vc.TallyId'+CHAR(13)
END

--摘要
CREATE TABLE #Summary (BillNumberId VARCHAR(50))
IF ISNULL(@summary,'')<>''
	BEGIN
		SET @summary=replace(@summary,'%','[%]')
		INSERT INTO	#Summary(BillNumberId)
		SELECT vc.BillNumberId
		FROM Ac_Voucher vc
		INNER JOIN Ac_Voucher_Bill bill ON bill.BillNumberId=vc.BillNumberId AND bill.Summary like '%'+@summary+'%'
		GROUP BY vc.BillNumberId
					
		SET @TbStr+='INNER JOIN #Summary summary ON summary.BillNumberId=vc.BillNumberId'+CHAR(13)
	END

--===========================================辅助核算【BEGIN】======================================================
--分支机构
CREATE TABLE #Stype1 (BillNumberId VARCHAR(50))
IF ISNULL(@stypeid1,'')<>''
BEGIN
	INSERT INTO #Stype1(BillNumberId)
	SELECT item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN dbo.F_AssistByStype(@stypeid,@stypeid1,@OperatorID) F ON item.typeName='01' AND F.TypeId=item.TypeId
	GROUP BY item.BillNumberId
	SET @TbStr+='INNER JOIN #Stype1 Stype1 ON Stype1.BillNumberId=bill.BillNumberId'+CHAR(13)
END

--部门
CREATE TABLE #Dtype (BillNumberId VARCHAR(50))
IF ISNULL(@dtypeid,'')<>''
BEGIN
	INSERT INTO #Dtype(BillNumberId)
	SELECT item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN  F_GetAllManagerBaseByTypeId(ISNULL(@dtypeid,''),9,@OperatorID,@stypeid)F ON item.typeName='02' AND  F.TypeId=item.TypeId
	GROUP BY item.BillNumberId
	SET @TbStr+='INNER JOIN #Dtype Dtype ON Dtype.BillNumberId=bill.BillNumberId'+CHAR(13)
END
--职员
CREATE TABLE #Etype (BillNumberId VARCHAR(50))
IF ISNULL(@staftypeid,'')<>''
BEGIN
	INSERT INTO #Etype(BillNumberId)
	SELECT item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN  F_GetAllManagerBaseByTypeId(ISNULL(@staftypeid,''),3,@OperatorID,@stypeid)F ON item.typeName='03' AND F.TypeId=item.TypeId
	GROUP BY item.BillNumberId
	SET @TbStr+='INNER JOIN #Etype Etype ON Etype.BillNumberId=bill.BillNumberId'+CHAR(13)
END
--往来单位
CREATE TABLE #Comtype (BillNumberId VARCHAR(50))
IF ISNULL(@companytypeid,'')<>''
BEGIN
	INSERT INTO	#Comtype(BillNumberId)
	SELECT  item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN  F_GetAllManagerBaseTypeId(ISNULL(@companytypeid,''),2,@OperatorID)F ON item.typeName='04' AND  F.TypeId=item.TypeId
	GROUP BY item.BillNumberId
	SET @TbStr+='INNER JOIN #Comtype Comtype ON Comtype.BillNumberId=bill.BillNumberId'+CHAR(13)
END
--自定义辅助核算明细 (权限函数,先还没有该功能但是稳妥起走^_^ F_GetAllAssistCheckItemsDetail)
DECLARE 
	@AscIds		INT,		--类型ID
	@TypeName	VARCHAR(200)--类型UserCode
CREATE TABLE #ItemsDetail05 (BillNumberId VARCHAR(50))
IF ISNULL(@TypeId05,'')<>''
BEGIN
	--得到类型ID及USERCODE
	SELECT TOP 1 @AscIds=C.AscIds,@TypeName=C.UserCode FROM Ac_Assist_CheckItems C 
	INNER JOIN Ac_Assist_CheckItemsDetail D ON D.AscIds=C.AscIds
	INNER JOIN f_split(@TypeId05,',') F ON F.a=D.TypeId
	
	INSERT INTO	#ItemsDetail05(BillNumberId)
	SELECT  item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN F_GetAllAssistCheckItemsDetail(@TypeId05,@AscIds,@operatorid) F ON item.typeName=@TypeName AND F.TypeId=item.TypeId
	GROUP BY item.BillNumberId

	SET @TbStr+='INNER JOIN #ItemsDetail05 T05 ON T05.BillNumberId=bill.BillNumberId'+CHAR(13)
END

CREATE TABLE #ItemsDetail06 (BillNumberId VARCHAR(50))
IF ISNULL(@TypeId06,'')<>''
BEGIN
	--得到类型ID及USERCODE
	SELECT TOP 1 @AscIds=C.AscIds,@TypeName=C.UserCode FROM Ac_Assist_CheckItems C 
	INNER JOIN Ac_Assist_CheckItemsDetail D ON D.AscIds=C.AscIds
	INNER JOIN f_split(@TypeId06,',') F ON F.a=D.TypeId
	
	INSERT INTO	#ItemsDetail06(BillNumberId)
	SELECT  item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN F_GetAllAssistCheckItemsDetail(@TypeId06,@AscIds,@operatorid) F ON item.typeName=@TypeName AND F.TypeId=item.TypeId
	GROUP BY item.BillNumberId

	SET @TbStr+='INNER JOIN #ItemsDetail06 T06 ON T06.BillNumberId=bill.BillNumberId'+CHAR(13)
END
CREATE TABLE #ItemsDetail07 (BillNumberId VARCHAR(50))
IF ISNULL(@TypeId07,'')<>''
BEGIN
	--得到类型ID及USERCODE
	SELECT TOP 1 @AscIds=C.AscIds,@TypeName=C.UserCode FROM Ac_Assist_CheckItems C 
	INNER JOIN Ac_Assist_CheckItemsDetail D ON D.AscIds=C.AscIds
	INNER JOIN f_split(@TypeId07,',') F ON F.a=D.TypeId
	
	INSERT INTO	#ItemsDetail07(BillNumberId)
	SELECT  item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN F_GetAllAssistCheckItemsDetail(@TypeId07,@AscIds,@operatorid) F ON item.typeName=@TypeName AND F.TypeId=item.TypeId
	GROUP BY item.BillNumberId

	SET @TbStr+='INNER JOIN #ItemsDetail07 T07 ON T07.BillNumberId=bill.BillNumberId'+CHAR(13)
END
CREATE TABLE #ItemsDetail08 (BillNumberId VARCHAR(50))
IF ISNULL(@TypeId08,'')<>''
BEGIN
	--得到类型ID及USERCODE
	SELECT TOP 1 @AscIds=C.AscIds,@TypeName=C.UserCode FROM Ac_Assist_CheckItems C 
	INNER JOIN Ac_Assist_CheckItemsDetail D ON D.AscIds=C.AscIds
	INNER JOIN f_split(@TypeId08,',') F ON F.a=D.TypeId
	
	INSERT INTO	#ItemsDetail08(BillNumberId)
	SELECT  item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN F_GetAllAssistCheckItemsDetail(@TypeId08,@AscIds,@operatorid) F ON item.typeName=@TypeName AND F.TypeId=item.TypeId
	GROUP BY item.BillNumberId

	SET @TbStr+='INNER JOIN #ItemsDetail08 T08 ON T08.BillNumberId=bill.BillNumberId'+CHAR(13)
END
CREATE TABLE #ItemsDetail09 (BillNumberId VARCHAR(50))
IF ISNULL(@TypeId09,'')<>''
BEGIN
	--得到类型ID及USERCODE
	SELECT TOP 1 @AscIds=C.AscIds,@TypeName=C.UserCode FROM Ac_Assist_CheckItems C 
	INNER JOIN Ac_Assist_CheckItemsDetail D ON D.AscIds=C.AscIds
	INNER JOIN f_split(@TypeId09,',') F ON F.a=D.TypeId
	
	INSERT INTO	#ItemsDetail09(BillNumberId)
	SELECT  item.BillNumberId
	FROM Ac_Voucher_Bill_Assist_CheckItems item
	INNER JOIN F_GetAllAssistCheckItemsDetail(@TypeId09,@AscIds,@operatorid) F ON item.typeName=@TypeName AND F.TypeId=item.TypeId
	GROUP BY item.BillNumberId

	SET @TbStr+='INNER JOIN #ItemsDetail09 T09 ON T09.BillNumberId=bill.BillNumberId'+CHAR(13)
END
--===========================================辅助核算【END】=========================================================
	


	
--原币
CREATE TABLE #yfdctype (BillNumberId VARCHAR(50))
DECLARE @yfdcStr VARCHAR(MAX)=''
--原币
IF(ISNULL(@yfdc,'')<>'' OR ISNULL(@ystarttotal,'')<>'' OR ISNULL(@yendtotal,'')<>'')
	BEGIN
		SET @yfdcStr+='INSERT INTO #yfdctype(BillNumberId)
									SELECT bill.BillNumberId
									FROM Ac_Voucher_Bill bill 
									WHERE 1=1 '
		IF(ISNULL(@yfdc,'')<>'')
			BEGIN
				SET @yfdcStr+='	AND (bill.FAdc='+@yfdc 
				IF(ISNULL(@ystarttotal,'')<>'' OR ISNULL(@yendtotal,'')<>'')
					BEGIN
						IF(@yfdc='1')--借
							BEGIN
								IF(ISNULL(@ystarttotal,'')<>'')--原币>=
									SET @yfdcStr+=' AND  Bill.FDebitTotalFor>='+@ystarttotal
								IF(ISNULL(@yrealtionship,'')<>'' AND ISNULL(@yendtotal,'')<>'')--且/或不为空 原币<=
									SET @yfdcStr+=' '+@yrealtionship+' Bill.FDebitTotalFor<='+@yendtotal
								ELSE IF(ISNULL(@yrealtionship,'')='' AND ISNULL(@yendtotal,'')<>'')--且/或为空 原币<=
									SET @yfdcStr+=' AND Bill.FDebitTotalFor<='+@yendtotal
							END
						ELSE IF(@yfdc='-1')--贷
							BEGIN
								IF(ISNULL(@ystarttotal,'')<>'')--原币>=
									SET @yfdcStr+=' AND Bill.FCreditTotalFor>='+@ystarttotal
								IF(ISNULL(@yrealtionship,'')<>''AND ISNULL(@yendtotal,'')<>'')--且/或不为空 原币<=
									SET @yfdcStr+=' '+@yrealtionship+' Bill.FCreditTotalFor<='+@yendtotal
								IF(ISNULL(@yrealtionship,'')='' AND ISNULL(@yendtotal,'')<>'')--且/或为空 原币<=
									SET @yfdcStr+=' AND Bill.FCreditTotalFor<='+@yendtotal
							END
					END
				SET @yfdcStr+=' )'
			END
		ELSE IF((ISNULL(@ystarttotal,'')<>'' OR ISNULL(@yendtotal,'')<>'') AND (ISNULL(@yfdc,'')='' AND ISNULL(@yrealtionship,'')=''))
			BEGIN
				IF(ISNULL(@ystarttotal,'')<>'')
					SET @yfdcStr+=' AND (Bill.FDebitTotalFor>='+@ystarttotal+' OR Bill.FCreditTotalFor>='+@ystarttotal+' ) ' --zs001:少一个关键字  李灏龙暂补
				IF(ISNULL(@yrealtionship,'')<>'' AND ISNULL(@yendtotal,'')<>'')
					SET @yfdcStr+=@yrealtionship+' (Bill.FDebitTotalFor<='+@yendtotal+' OR Bill.FCreditTotalFor<='+@yendtotal+' )'
				ELSE IF(ISNULL(@yrealtionship,'')='' AND ISNULL(@yendtotal,'')<>'')
					SET @yfdcStr+=' AND (Bill.FDebitTotalFor<='+@yendtotal+' OR Bill.FCreditTotalFor<='+@yendtotal+' )'
			END
		SET @yfdcStr+='			GROUP BY bill.BillNumberId'
		EXEC(@yfdcStr)
		SET @TbStr+='INNER JOIN #yfdctype yfdctype ON yfdctype.BillNumberId=vc.BillNumberId'+CHAR(13)
	END
--本币
CREATE TABLE #bfdctype (BillNumberId VARCHAR(50))
DECLARE @bfdctypeStr VARCHAR(MAX)=''
--本币
IF(ISNULL(@bfdc,'')<>'' OR ISNULL(@bstarttotal,'')<>'' OR ISNULL(@bendtotal,'')<>'')
	BEGIN
		SET @bfdctypeStr+='INSERT INTO #bfdctype(BillNumberId)
									SELECT bill.BillNumberId
									FROM Ac_Voucher_Bill bill 
									WHERE 1=1 '
		IF(ISNULL(@bfdc,'')<>'')
			BEGIN
				SET @bfdctypeStr+='	AND (bill.FAdc='+@bfdc 
				IF(ISNULL(@bstarttotal,'')<>'' OR ISNULL(@bendtotal,'')<>'')
					BEGIN
						IF(@bfdc='1')--借
							BEGIN
								IF(ISNULL(@bstarttotal,'')<>'')--本币>=
									SET @bfdctypeStr+=' AND Bill.FDebitTotal>='+@bstarttotal
								IF(ISNULL(@brealtionship,'')<>'' AND ISNULL(@bendtotal,'')<>'')--且/或不为空 本币<=
									SET @bfdctypeStr+=' '+@brealtionship+' Bill.FDebitTotal<='+@bendtotal
								ELSE IF(ISNULL(@brealtionship,'')='' AND ISNULL(@bendtotal,'')<>'')--且/或为空 本币<=
									SET @bfdctypeStr+=' AND Bill.FDebitTotal<='+@bendtotal
							END
						ELSE IF(@bfdc='-1')--贷
							BEGIN
								IF(ISNULL(@bstarttotal,'')<>'')--原币>=
									SET @bfdctypeStr+=' AND Bill.FCreditTotal>='+@bstarttotal
								IF(ISNULL(@brealtionship,'')<>''AND ISNULL(@bendtotal,'')<>'')--且/或不为空 本币<=
									SET @bfdctypeStr+=' '+@brealtionship+' Bill.FCreditTotal<='+@bendtotal
								IF(ISNULL(@brealtionship,'')='' AND ISNULL(@bendtotal,'')<>'')--且/或为空 本币<=
									SET @bfdctypeStr+=' AND Bill.FCreditTotal<='+@bendtotal

							END
						
					END
				SET @bfdctypeStr+=' )'
			END
		ELSE IF((ISNULL(@bstarttotal,'')<>'' OR ISNULL(@bendtotal,'')<>'') AND (ISNULL(@bfdc,'')='' AND ISNULL(@brealtionship,'')=''))
			BEGIN
				IF(ISNULL(@bstarttotal,'')<>'')
					SET @bfdctypeStr+=' AND (Bill.FDebitTotal>='+@bstarttotal+' OR Bill.FCreditTotal>='+@bstarttotal+' ) '  --zs001: 少一个关键字 李灏龙暂补
				IF(ISNULL(@brealtionship,'')<>'' AND ISNULL(@bendtotal,'')<>'')
					SET @bfdctypeStr+=@brealtionship+' (Bill.FDebitTotal<='+@bendtotal+' OR Bill.FCreditTotal<='+@bendtotal+' )'
				ELSE IF(ISNULL(@brealtionship,'')='' AND ISNULL(@bendtotal,'')<>'')
					SET @bfdctypeStr+=' AND (Bill.FDebitTotal<='+@bendtotal+' OR Bill.FCreditTotal<='+@bendtotal+' )'
			END
		
		SET @bfdctypeStr+='			GROUP BY bill.BillNumberId'
		EXEC (@bfdctypeStr)
		SET @TbStr+='INNER JOIN #bfdctype bfdctype ON bfdctype.BillNumberId=vc.BillNumberId'+CHAR(13)
	END
	
SET @TbStr+='
	LEFT JOIN Ac_BalanceType abt on abt.BtId=bill.fsettletypeid '	
--------------------------------------定义临时表end---------------------------------------------

--------------------------------------sql where begin---------------------------------------------
SET @Link+='	WHERE 1=1 '+CHAR(13)

--【仅能查看本人制单的会计凭证】
IF(@LimitOwnVoucher=1)
	SET @WhStr+=' AND VC.ETypeId='''+@operatorid+''''

--期间/凭证字选择
IF(ISNULL(@dateChoose,'')='0')
	BEGIN
		IF(ISNULL(@startfperiod,'')<>'' AND ISNULL(@endfperiod,'')<>'')
			SET @WhStr+='	AND vc.Fperiod>='+@startfperiod+' AND vc.Fperiod<='+@endfperiod+CHAR(13)
		ELSE IF(ISNULL(@startfperiod,'')='' AND ISNULL(@endfperiod,'')<>'')
			SET @WhStr+='	AND vc.Fperiod <='+@endfperiod+CHAR(13)
		ELSE IF(ISNULL(@startfperiod,'')<>'' AND ISNULL(@endfperiod,'')='')
			SET @WhStr+='	AND vc.Fperiod >='+@startfperiod+CHAR(13)	
	END
ELSE IF ISNULL(@dateChoose,'')='1'
	BEGIN
		IF(ISNULL(@startbilldate,'')<>'' AND ISNULL(@endbilldate,'')<>'')
			SET @WhStr+='	AND vc.BillDate >='''+@startbilldate+''' AND vc.BillDate<='''+@endbilldate+''''+CHAR(13)
		ELSE IF(ISNULL(@startbilldate,'')='' AND ISNULL(@endbilldate,'')<>'')
			SET @WhStr+='	AND vc.BillDate <='''+@endbilldate+''''+CHAR(13)
		ELSE IF(ISNULL(@startbilldate,'')<>'' AND ISNULL(@endbilldate,'')='')
			SET @WhStr+='	AND vc.BillDate >='''+@startbilldate+''''+CHAR(13)	
	END 
	
--凭证号	
IF(ISNULL(@startfserialnum,'')<>'' AND ISNULL(@endfserialnum,'')<>'')
	SET @WhStr+='	AND vc.FlowNo>='+@startfserialnum+' AND vc.FlowNo<='+@endfserialnum+''+CHAR(13)
ELSE IF(ISNULL(@startfserialnum,'')<>'' AND ISNULL(@endfserialnum,'')='')
	SET @WhStr+='	AND vc.FlowNo >='+@startfserialnum+CHAR(13)
ELSE IF(ISNULL(@startfserialnum,'')='' AND ISNULL(@endfserialnum,'')<>'')
	SET @WhStr+='	AND vc.FlowNo <='+@endfserialnum+CHAR(13)

IF(ISNULL(@fchecked,'')<>'')--是否审核
	SET @WhStr+='	AND vc.FChecked='+@fchecked+CHAR(13)
IF(ISNULL(@audited,'')<>'')--是否过账
	SET @WhStr+='	AND vc.Audited='+@audited+CHAR(13)
	
--是否按出纳签字查询
IF @isteller = 1
	SET @WhStr+= ' AND ISNULL(vc.MarkError,'''') = '''''
--查询条件是否包含出纳已签字
IF @IncludeSign = 0
	SET @WhStr+= 'AND ISNULL(vc.Teller,'''') = '''' '
	
IF @injournal = 1
	SET @WhStr += ' AND ISNULL(TJD.ID,'''') ='''' AND (at.IsCash = 1 OR at.IsBank = 1)'
ELSE IF @injournal = 2
	SET @WhStr += ' AND ISNULL(TJD.ID,'''') <>'''' '
	





--------------------------------------sql where end---------------------------------------------

------------------------------------执行 sql并drop临时表 begin--------------------------------


IF ISNULL(@OrderStr,'')=''
	SET @OrderStr='billdate asc,grfullname asc,flowno asc'
ELSE
	BEGIN
		IF (SELECT CHARINDEX('billdate',@OrderStr))>0 OR (SELECT CHARINDEX('fullname',@OrderStr))>0 OR (SELECT CHARINDEX('attachfilecount',@OrderStr))>0
			SET @OrderStr=@OrderStr
		ELSE 
			SET @OrderStr='billdate asc,grfullname asc,flowno asc,'+@OrderStr
	END	
SET @Result=') F ORDER BY '+@OrderStr

EXEC(@Str+@TbStr+@Link+@WhStr+@Result)--执行sql语句

DROP TABLE #Atype,#Ctype,#yfdctype,#bfdctype,#Summary,#Comtype,#Dtype,#Etype,#Stype1
			--,#AcAccount
			,#F_LineAccount
			,#F_EtypeWithType
			,#F_Stype

--------------------------------------执行 sql并drop临时表 begin---------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AcVoucherQueryForAdjustBreakingNo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AcVoucherQueryForAdjustBreakingNo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	
*/
CREATE PROCEDURE Web_AcVoucherQueryForAdjustBreakingNo
(
	@OperatorId		VARCHAR(50),		--当前操作员ID
	@Stypeid		VARCHAR(50),		--分支机构
	@Fyear			INT,				--年度
	@Fperiod		INT,				--期间
	@Vgid			VARCHAR(1000) = ''	--凭证字
)
--@encode$--
AS
SET NOCOUNT ON

SELECT	V.BillNumberId
		,V.STypeId
		,S.FullName AS SFULLNAME
		,V.VgId
		,G.FullName AS VGIDFULLNAME
		,V.FlowNo
		,'' AS newFlowNo
		,E.FullName AS EFULLNAME
		,V.FComment
		,V.FYear
		,V.FPeriod
FROM dbo.Ac_Voucher v
LEFT JOIN SType S ON S.TypeId = V.STypeId
LEFT JOIN employee E ON E.typeId = V.ETypeId
LEFT JOIN Ac_Voucher_Group G ON G.VgId = V.VgId
WHERE V.STypeId = @Stypeid AND V.FYear = @Fyear AND V.FPeriod = @Fperiod AND V.VgId = @Vgid


RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_ApiAuditBillList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_ApiAuditBillList]
GO

/*
	作者：
	日期：
	描述：Api单据审核查询
*/
CREATE   PROCEDURE Web_ApiAuditBillList
(
	@OperatorId		VARCHAR(100)='00001',		--操作员ID
	@StartDate		VARCHAR(20)='',		--开始日期
	@EndDate		VARCHAR(20)='',		--截至日期
	@APPID			VARCHAR(50)='',		--APPID
	@CompanyName	VARCHAR(200)='',		--公司名称
	@ContactName	VARCHAR(50)='',		--联系人名称
	@ContactNum		VARCHAR(50)='',		--联系人手机号
	@BillState		VARCHAR(10)='-1'					--0=单据经手人，1=往来单位关联职员
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF


DECLARE @SQL VARCHAR(MAX)=''
SET @SQL='SELECT A.BillNumberId,A.BillCode AS APPID,A.CompanyName,A.BizLinecenseCode,A.ContactName,A.ContactNum
			,CAST(A.SubmitDate AS DATE) AS SubmitDate
			,CASE A.BillState WHEN 0 THEN ''未审核'' WHEN 1 THEN ''已审核'' WHEN 2 THEN ''已拒绝'' END AS BillState,
			e.fullname as Auditor,AuditDate
		FROM APIApplicationBill A 
		Left JOIN employee E ON A.Auditor=E.TYPEID
		WHERE 1=1 '
IF @StartDate<>''
	SET @SQL+=' AND CAST(A.SubmitDate AS DATE)>='''+@StartDate+''''
IF @EndDate<>''
	SET @SQL+=' AND CAST(A.SubmitDate AS DATE)<='''+@EndDate+''''
IF @APPID<>''
	SET @SQL+=' AND A.BILLCODE LIKE ''%'+@APPID+'%'''
IF @CompanyName<>''
	SET @SQL+=' AND A.CompanyName LIKE ''%'+@CompanyName+'%'''
IF @ContactName<>''
	SET @SQL+=' AND A.ContactName LIKE ''%'+@ContactName+'%'''
IF @ContactNum<>''
	SET @SQL+=' AND A.ContactNum LIKE ''%'+@ContactNum+'%'''
IF @BillState<>'-1'
	SET @SQL+=' AND A.BillState IN('+@BillState+')'	
SET @SQL+=' ORDER BY A.SubmitDate DESC'	
	
PRINT @SQL	
EXEC(@SQL) 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ArApAnsiDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_ArApAnsiDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：毛欣蓉
	日期：2011-10-09
	描述：往来综合分析往来对账
*/
/*
	修改：李灏龙
	日期：2012年2月28日16:34:14
	描述：将单据内的商品展开显示，本次修改通过直接调用：
	应收查询（统一客户和供货商）Web_QueryArApWldz_Gsqh_YH_TY 和应付查询（统一客户和供货商）Web_QueryArApWldz_Gsqh_GYS_YH_TY
	两个存储过程来进行联合查询得到最终数据
*/
CREATE PROCEDURE Web_ArApAnsiDetail
(
	@OperatorId		VARCHAR(100),
	@BtypeID      	VARCHAR(max),               --往来单位typeid
	@StartDate   	VARCHAR(20),                --起始日期
	@EndDate    	VARCHAR(20),                --截至日期
	@showRedWord	INT=1,						--是否显示红冲单据  1.显示   0.不显示
	@stypeid		VARCHAR(max),
	@IncludePre		INT=0,
	@CID            VARCHAR(5)='5',
	@expensetoar    INT=0,
	@dtypeid		VARCHAR(MAX),	--部门
	@DtypeIsVisible	INT			--1=使用部门 0=不使用部门     
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
--应收
CREATE TABLE #temp_YS(
	bfullname		VARCHAR(200),
	unitfullname    VARCHAR(200),
    sortid          INT,
	zy				VARCHAR(400),
	ptypeid			VARCHAR(200),
	qty				 NUMERIC(24, 10) ,
	taxprice		 NUMERIC(24, 10) ,
	ntaxprice		 NUMERIC(24, 10) ,
	incomment		VARCHAR(2000),
	aradd			 NUMERIC(24, 10) ,
	naradd			 NUMERIC(24, 10) ,
	ArReduce		 NUMERIC(24, 10) ,
	NArReduce		 NUMERIC(24, 10) ,
	BillDate		DATETIME,
	BillCode		VARCHAR(400),
	etypeid			VARCHAR(100),
	dtypeid			VARCHAR(100),
	ktypeid			VARCHAR(100),
	TeamNo			VARCHAR(20),
	id				INT,
	btypeid			VARCHAR(100),
	BillNumberId	NUMERIC(18,0),
	BillType		VARCHAR(20),
	TeamNo1			VARCHAR(20),
	RedWord			VARCHAR(20),
	Comment			VARCHAR(2000),
	cfullname       VARCHAR(200),
	rate             NUMERIC(24, 10) ,
	atypeid         INT,
	goodsnumber     VARCHAR(100),
	remark           VARCHAR(2000),--备注
	unit             INT ,--计量单位
	MQty             NUMERIC(24, 10) ,--数量
	MTaxPrice            NUMERIC(24, 10) ,--含税单价
	conversionrelationship VARCHAR(200),--换算关系
	customassistantunit VARCHAR(200), --自定义辅助数量
	BillFlag		INT,
	uninvoiceqty	NUMERIC(24,10),
	nuninvoicemoney NUMERIC(24,10),
	uninvoicemoney   NUMERIC(24,10)
	
	)

INSERT INTO #temp_YS
EXEC Web_QueryArApWldz_Gsqh_YH_TY @OperatorID,NULL,@BtypeID,@StartDate,@EndDate,@showRedWord,@stypeid,@IncludePre,'',@CID,@expensetoar, @dtypeid,@DtypeIsVisible



--应付
CREATE TABLE #temp_YF(
	bfullname		VARCHAR(200),
	unitfullname    VARCHAR(200),
    sortid          INT,
	zy				VARCHAR(400),
	ptypeid			VARCHAR(200),
	qty				 NUMERIC(24, 10) ,
	taxprice		 NUMERIC(24, 10) ,
	ntaxprice		 NUMERIC(24, 10) ,
	incomment		VARCHAR(2000),
	apadd			 NUMERIC(24, 10) ,
	napadd			 NUMERIC(24, 10) ,
	ApReduce		 NUMERIC(24, 10) ,
	NApReduce		 NUMERIC(24, 10) ,
	BillDate		DATETIME,
	BillCode		VARCHAR(400),
	etypeid			VARCHAR(100),
	dtypeid			VARCHAR(100),
	ktypeid			VARCHAR(100),
	TeamNo			VARCHAR(20),
	id				INT,
	btypeid			VARCHAR(100),
	BillNumberId	NUMERIC(18,0),
	BillType		VARCHAR(20),
	TeamNo1			VARCHAR(20),
	RedWord			VARCHAR(20),
	Comment			VARCHAR(2000),
    cfullname       VARCHAR(200),
	rate             NUMERIC(24, 10) ,
	atypeid         INT,
	goodsnumber     VARCHAR(100),
	remark           VARCHAR(2000),--备注
	unit             INT ,--计量单位
	MQty             NUMERIC(24, 10) ,--数量
	MTaxPrice            NUMERIC(24, 10) ,--含税单价
	conversionrelationship VARCHAR(200),--换算关系
	customassistantunit VARCHAR(200), --自定义辅助数量
	BillFlag		INT,
	uninvoiceqty	NUMERIC(24,10),
	nuninvoicemoney NUMERIC(24,10),
	uninvoicemoney   NUMERIC(24,10)
	)
	
INSERT INTO #temp_YF
EXEC Web_QueryArApWldz_Gsqh_GYS_YH_TY @OperatorID,NULL,@BtypeID,@StartDate,@EndDate,@showRedWord,@stypeid,@IncludePre,'',@CID,@expensetoar, @dtypeid,@DtypeIsVisible

--联合查询
SELECT  sortid,
        zy,
		ptypeid,	
		qty ,	
		taxprice ,
		ntaxprice,	
		incomment,
		0 AS apadd, 
		0 AS napadd, 
		0 AS ApReduce,
		0 AS NApReduce,	
		aradd,	
		naradd,	
		ArReduce,
		NArReduce,	
		BillDate,	
		BillCode,	
		etypeid,	
		dtypeid,	
		ktypeid,
		TeamNo,	
		id,	
		btypeid,	
		BillNumberId,
		BillType,
		TeamNo1,
		RedWord,
		Comment,
		cfullname,
		rate,
		atypeid,
		goodsnumber ,
		bfullname,
		remark,
		unit,
		MQty,
		MTaxPrice,
		conversionrelationship,
		customassistantunit,
		unitfullname,
		BillFlag
FROM	#temp_YS
UNION ALL
SELECT  sortid,
        zy, 
		ptypeid,	
		qty,	
		taxprice,
		ntaxprice,	
		incomment,
		apadd,
		napadd, 
		ApReduce,
		NApReduce,
		0 AS aradd,
		0 AS naradd,
		0 AS ArReduce,
		0 AS NArReduce,	
		BillDate,	
		BillCode,	
		etypeid,	
		dtypeid,	
		ktypeid,	
		TeamNo,	
		id,	
		btypeid,	
		BillNumberId,
		BillType,
		TeamNo1,
		RedWord,
		Comment,
		cfullname,
		rate,
		atypeid,
		goodsnumber ,
		bfullname,
		remark,
		unit,
		MQty,
		MTaxPrice,
		conversionrelationship,
		customassistantunit,
		unitfullname,
		BillFlag
FROM	#temp_YF
ORDER BY BillFlag,BillDate,BillNumberId,BillCode,id,sortid DESC

DROP TABLE #temp_YS,#temp_YF

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ArApQeuryLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_ArApQeuryLine
GO













/*
	作者：毛欣蓉
	日期：2011-01-05
	描述：应收、应付查询分布表线性表
        
*/
CREATE  PROCEDURE Web_ArApQeuryLine
( 
	@OperatorID 	varchar(100) ,   --操作员id
	@btypeid		varchar(50),
	@stypeid		varchar(1055),
	@flag			varchar(2)			--1,3  应收  2,4应付
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId varchar(50), @MBTypeid varchar(50), @MBTypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL varchar(8000)

CREATE TABLE #BType
(
	TypeId		VARCHAR(100)
)

create table #stype
(
	typeid		varchar(50)
)
IF  EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value=1) and (@btypeid='00000' or @btypeid='')
		INSERT INTO #BType(TypeId)
				SELECT 	A.TypeId
					FROM 	F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) A 
ELSE IF @flag='a'
	INSERT INTO #BType(TypeId)
				SELECT 	A.TypeId
					FROM 	F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) A WHERE a.typeid like '00001%'
else 
	INSERT INTO #BType(TypeId)
				SELECT 	A.TypeId
					FROM 	F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) A WHERE a.typeid like '00002%'


--分支机构
INSERT INTO #stype(typeid) 
	SELECT  A.typeid
		FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A
		
IF @flag='a'
begin
	SET @SQL='
			SELECT 
					a.typeid,
					m.stypeid,
					M.ArTotal AS atotal,
					M.ysTotal AS ytotal,
					isnull(M.ArTotal,0)-isnull(ysTotal,0) AS aytotal
			FROM 	#BType a  
			LEFT JOIN 
				(select b.artotal,b.ystotal,b.stypeid,b.btypeid
				 from BType_ARAPTotal b 
				 inner join #stype s on s.typeid=b.stypeid 
				 )M ON M.bTypeId = a.TypeId
			where M.ArTotal <>0 or M.ysTotal<>0'
end
IF @flag ='p'
begin
	SET @SQL='
			SELECT 
					a.typeid,
					m.stypeid,
					M.ApTotal AS atotal,
					M.yfTotal AS ytotal,
					isnull(M.ApTotal,0)-isnull(yfTotal,0) AS aytotal
			FROM 	#BType a  
			LEFT JOIN 
				(select b.aptotal,b.yftotal,b.stypeid,b.btypeid
				 from BType_ARAPTotal b 
				inner join #stype s on s.typeid=b.stypeid 
				)M  ON M.bTypeId = a.TypeId
			
			where M.ApTotal<>0 or M.yfTotal<>0'
end
--select * from #stype
--select * from #BType
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #BType,#stype












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_ArApQeuryList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_ArApQeuryList
GO

/*
	作者：毛欣蓉
	日期：2011-01-05
	描述：应收、应付查询分布表线性表
    
    日期:2012-06-07
    作者:黄清
    描述:添加币别条件,调整科目
*/
CREATE  PROCEDURE Web_ArApQeuryList
( 
	@OperatorID 	VARCHAR(100) ,   --操作员id
	@btypeid		VARCHAR(50),
	@stypeid		VARCHAR(1055),
	@StartDate		VARCHAR(50),
	@EndDate		VARCHAR(50),
	@IncludePre		VARCHAR(10)='False',
	@option			INT=0,	--选项  0全部显示 1不显示金额为0 2只显示金额为0，3无发生额不显示
	@flag			VARCHAR(2),			--1,3  应收  2,4应付
	@cid			VARCHAR(MAX)	--币别
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL VARCHAR(8000),
		@lstSQL VARCHAR(8000),
		@SonNum INT,
		@SqlWhere	VARCHAR(8000),
		@preSql1	VARCHAR(1000), --应收增加条件(本币)
		@NpreSql1	VARCHAR(1000), --应收增加条件(原币)
		@preSql2	VARCHAR(1000), --应收减少条件(本币)
		@NpreSql2	VARCHAR(1000), --应收减少条件(原币)
		@AtypeType	VARCHAR(1000), --要查询的科目
		@aratypeID	VARCHAR(50),
		@ysatypeID	VARCHAR(50),
		@apatypeID	VARCHAR(50),
		@yfatypeID	VARCHAR(50)

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'
		
IF @option=1
	SET @SqlWhere=' WHERE a.qmtotal<>0 ORDER BY a.usercode'
IF @option=2
	SET @SqlWhere=' WHERE a.qmtotal=0  ORDER BY a.usercode'
IF @option=3
	SET @SqlWhere=' WHERE a.bqaddtotal<>0 OR a.bqrectotal<>0 ORDER BY a.usercode'
	
SET @preSql1=''
SET @preSql2=''
SET @NpreSql1=''
SET @NpreSql2=''
		
IF @btypeid = '00000'
	SET @btypeid = ''


CREATE TABLE #BType1
(
	TypeId		VARCHAR(100),
	Stypeid		VARCHAR(100),
	Total00		 NUMERIC(24, 10) ,
	NTotal00	 NUMERIC(24, 10) ,
	BqaddTotal	 NUMERIC(24, 10) ,
	NBqaddTotal	 NUMERIC(24, 10) ,
	BqrecTotal	 NUMERIC(24, 10) ,
	NBqrecTotal	 NUMERIC(24, 10) ,
	Qmtotal		 NUMERIC(24, 10) ,
	NQmtotal	 NUMERIC(24, 10) ,
	ArLimit		 NUMERIC(24, 10) 
)
	
CREATE TABLE #stype(typeid	VARCHAR(50))

--分支机构
INSERT INTO #stype(typeid) 
SELECT  A.typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A
		
CREATE TABLE #BtypeAll(TypeID VARCHAR(100))

DECLARE @sqll VARCHAR(MAX)
SELECT @sqll=dbo.F_GetAllBaseInfoTypeId(@btypeid,2,@OperatorID,'#BtypeAll')

EXEC(@sqll)

DECLARE @ArLimitTableName VARCHAR(MAX)
IF NOT EXISTS(SELECT TOP 1 1 FROM #BtypeAll)
  BEGIN
       SET @ArLimitTableName=' Btype '
  END
ELSE
  BEGIN
       SET @ArLimitTableName=' #BtypeAll '
  END
  
IF @cid=0
BEGIN
CREATE TABLE #BType_ARAPTotal
(
	BTypeId			VARCHAR(100),
	STypeId			VARCHAR(100),
	Total00			NUMERIC(24,10),
	NTotal00		NUMERIC(24,10),
	BqaddTotal		NUMERIC(24,10),
	NBqaddTotal		NUMERIC(24,10),
	BqrecTotal		NUMERIC(24,10),
	NBqrecTotal		NUMERIC(24,10),
	ApTotal			NUMERIC(24,10),
	NApTotal		NUMERIC(24,10),
	ARTotal			NUMERIC(24,10),
	NARTotal		NUMERIC(24,10),
	ystotal			NUMERIC(24,10),
	nystotal		NUMERIC(24,10),
	yftotal			NUMERIC(24,10),
	nyftotal		NUMERIC(24,10)
)
DECLARE @SQLBTYPE VARCHAR(8000)
SET @SQLBTYPE = '
				INSERT INTO #BType_ARAPTotal
				SELECT	BTypeId,
						STypeId,
						0 AS Total00,
						0 AS NTotal00,
						0 AS BqaddTotal,
						0 AS NBqaddTotal,
						0 AS BqrecTotal,
						0 AS NBqrecTotal,
						SUM(ApTotal) AS ApTotal,
						SUM(NApTotal) AS NApTotal,
						SUM(ARTotal) AS ARTotal,    
						SUM(NARTotal) AS NARTotal , 
						SUM(ystotal) AS ystotal , 
						SUM(nystotal) AS nystotal,   
						SUM(yftotal) AS yftotal,
						SUM(nyftotal) AS nyftotal
				FROM	BType_ARAPTotal	a'
    IF @stypeid <> '' OR @MStypeid <> '00000' 
        SET @SQLBTYPE = @SQLBTYPE + ' INNER JOIN #stype s ON a.StypeId=s.typeid '

    IF @btypeid <> '' 
        SET @SQLBTYPE = @SQLBTYPE + ' WHERE	a.BTypeID LIKE '''+@btypeid+'%''' 

    SET @SQLBTYPE = @SQLBTYPE + ' GROUP BY BTypeId,
		 STypeId'
		
    --PRINT ( @SQLBTYPE )	 
    EXEC(@SQLBTYPE)	 

END
ELSE
BEGIN
CREATE TABLE #BType_ARAPTotal1
(
	BTypeId			VARCHAR(100),
	STypeId			VARCHAR(100),
	Total00			NUMERIC(24,10),
	NTotal00		NUMERIC(24,10),
	BqaddTotal		NUMERIC(24,10),
	NBqaddTotal		NUMERIC(24,10),
	BqrecTotal		NUMERIC(24,10),
	NBqrecTotal		NUMERIC(24,10),
	ApTotal			NUMERIC(24,10),
	NApTotal		NUMERIC(24,10),
	ARTotal			NUMERIC(24,10),
	NARTotal		NUMERIC(24,10),
	ystotal			NUMERIC(24,10),
	nystotal		NUMERIC(24,10),
	yftotal			NUMERIC(24,10),
	nyftotal		NUMERIC(24,10),
	cid				VARCHAR(MAX)	--币别
)
DECLARE @SQLBTYPE1 VARCHAR(8000)
SET @SQLBTYPE1 = '
				INSERT INTO #BType_ARAPTotal1
				SELECT	BTypeId,
						STypeId,
						0 AS Total00,
						0 AS NTotal00,
						0 AS BqaddTotal,
						0 AS NBqaddTotal,
						0 AS BqrecTotal,
						0 AS NBqrecTotal,
						SUM(ApTotal) AS ApTotal,
						SUM(NApTotal) AS NApTotal,
						SUM(ARTotal) AS ARTotal,    
						SUM(NARTotal) AS NARTotal , 
						SUM(ystotal) AS ystotal , 
						SUM(nystotal) AS nystotal,   
						SUM(yftotal) AS yftotal,
						SUM(nyftotal) AS nyftotal ,
						cid 		
				FROM	BType_ARAPTotal	a'
    IF @stypeid <> ''  OR @MStypeid <> '00000' 
        SET @SQLBTYPE1 = @SQLBTYPE1 + ' INNER JOIN #stype s ON a.StypeId=s.typeid '

    IF @btypeid <> '' 
        SET @SQLBTYPE1 = @SQLBTYPE1 + ' WHERE	a.BTypeID LIKE '''+@btypeid+'%''' 

    SET @SQLBTYPE1 = @SQLBTYPE1 + ' GROUP BY BTypeId,
		 STypeId,cid'
		
    --PRINT ( @SQLBTYPE1 )	 
    EXEC(@SQLBTYPE1)	 
END

SET @SQL='
		INSERT INTO #BType1
		SELECT	a.TypeId,
				c.stypeid,
				0 AS Total00,
				0 AS NTotal00,
				0 AS BqaddTotal,
				0 AS NBqaddTotal,
				0 AS BqrecTotal,
				0 AS NBqrecTotal,
				0 AS Qmtotal,	
				0 AS NQmtotal,
				SUM(ISNULL(c.credit,0)) AS ArLimit
		FROM	'+@ArLimitTableName+' a
		LEFT JOIN btype_credit c ON c.BtypeId=a.typeId
'
IF @stypeid<>'' OR @MStypeid<>'00000' 
	SET @SQL=@SQL+' INNER JOIN #stype s ON c.StypeId=s.typeid '

SET @SQL=@SQL+'  GROUP BY A.typeId,c.stypeid '
EXEC(@sql)
	
Declare @QmSql VARCHAR(1000)

IF @flag='a' --应收
BEGIN
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@ysatypeID+CHAR(39)+','+CHAR(39)+@aratypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.Total) '
		SET @NpreSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.NTotal<0  THEN ABS(l.NTotal) '
		SET @preSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total>0 THEN l.Total '
		SET @NpreSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.NTotal>0 THEN l.NTotal '
		SET @QmSql=' 
		SUM(ISNULL(a.ARTotal,0)-ISNULL(a.ystotal,0)-ISNULL(b.addtotal,0)+ISNULL(b.rectotal,0)) AS qmtotal,
		SUM(ISNULL(a.nARTotal,0)-ISNULL(a.nystotal,0)-ISNULL(b.naddtotal,0)+ISNULL(b.nrectotal,0)) AS Nqmtotal,  '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)
		SET @QmSql='
		SUM(ISNULL(a.ARTotal,0)-ISNULL(b.addtotal,0)+ISNULL(b.rectotal,0)) AS qmtotal, 
		SUM(ISNULL(a.nARTotal,0)-ISNULL(b.naddtotal,0)+ISNULL(b.nrectotal,0)) AS Nqmtotal, '
	END

	SET @SQL='
	INSERT INTO #BType1
	(
		TypeId,
		stypeid,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	a.BTypeID,
			a.stypeid,
			0 AS Total00,
			0 AS NTotal00,
			0 AS BqaddTotal,
			0 AS NBqaddTotal,
			0 AS BqrecTotal,
			0 AS NBqrecTotal,
			'+@QmSql+'
			0 AS arlimit'
	IF @cid=0
	BEGIN
		SET @SQL=@SQL+' FROM #BType_ARAPTotal a '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+' FROM #BType_ARAPTotal1 a '
	END
	

	IF @stypeid<>'' OR @MStypeid<>'00000' 
		SET @SQL=@SQL+' INNER JOIN #stype s ON a.StypeId=s.typeid '
		--print (@SQL)	
	SET @SQL=@SQL+'
	LEFT JOIN 
		(SELECT	L.BTypeId,
				SUM(CASE  WHEN l.billtype in (45,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
						WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					  WHEN l.BillType in(11,405,424)  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					  WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426) THEN l.Total '+@preSql1+'
					  ELSE 0 
					  END) AS addtotal,
				SUM(CASE  WHEN l.billtype in (45,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
						WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					  WHEN l.BillType in(11,405,424)  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					  WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.nTotal>0 AND l.BillType NOT IN(45,215,11,160,405,424,426) THEN l.NTotal '+@NpreSql1+'
					  ELSE 0 
					  END) AS Naddtotal,
				SUM(CASE  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426) THEN ABS(l.Total)'+@preSql2+'
					  ELSE 0 
					  END) AS rectotal,
				SUM(CASE  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426) THEN ABS(l.NTotal)'+@NpreSql2+'
					  ELSE 0 
					  END) AS Nrectotal,
				l.STypeID
		FROM	ListTable L 
				'
	IF @stypeid<>'' OR @MStypeid<>'00000' 
		SET @SQL=@SQL+' INNER JOIN #stype s ON L.StypeId=s.typeid '

	SET @SQL=@SQL+' WHERE	L.BillDate>'''+@EndDate+''' 
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39) 
	SET @SQL=@SQL+'
		GROUP BY L.BTypeId,l.STypeID) b ON a.BTypeID=b.BtypeId AND b.STypeID=a.STypeID '
	IF @cid<>0
		SET @SQL=@SQL+' WHERE a.cid='+CHAR(39)+@cid+CHAR(39)
	SET @SQL=@SQL+'
		GROUP BY a.btypeid,a.stypeid
		'
	--PRINT @SQL
	EXEC(@sql)
	
	SET @SQL='
		INSERT INTO #BType1
		(
			TypeId,
			stypeid,
			Total00,
			NTotal00,
			BqaddTotal,
			NBqaddTotal,
			BqrecTotal,
			NBqrecTotal,
			Qmtotal,
			NQmtotal,
			ArLimit
		)
		SELECT	L.BTypeId,
				L.stypeid,
				0 AS total00,
				0 AS Ntotal00,
				SUM(CASE  WHEN l.billtype in (45,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
							WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
						  WHEN l.BillType in(11,405,424)  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
						  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
						  --WHEN l.billtype=424  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
						  --WHEN l.billtype=426  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN -l.Total
						  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426) THEN l.Total'+@preSql1+'
						  ELSE 0
					END) AS bqaddtotal,
				SUM(CASE  WHEN l.billtype in (45,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
							WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
						  WHEN l.BillType in(11,405,424) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
						  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
						  --WHEN l.billtype=424  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
						  --WHEN l.billtype=426  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN -l.NTotal
						  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(45,215,11,160,405,424,426) THEN l.NTotal'+@NpreSql1+'
						  ELSE 0
						END) AS Nbqaddtotal,
				SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426) THEN ABS(l.Total)'+@preSql2+'
					 ELSE 0
					END) AS bqrectotal,
				SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426) THEN ABS(l.NTotal)'+@NpreSql2+'
					 ELSE 0
					END) AS Nbqrectotal,
				0 AS qmtotal,
				0 AS Nqmtotal,
				0 AS ArLimit	
		FROM	ListTable L'
	IF @stypeid<>'' OR @MStypeid<>'00000' 
		SET @SQL=@SQL+' INNER JOIN #stype s ON L.StypeId=s.typeid '

	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@EndDate+' ''
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET	@SQL=@SQL+'	GROUP BY L.BTypeId,L.Stypeid '

	EXEC(@sql)
END
IF @flag ='p' --应付
BEGIN
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)+','+CHAR(39)+@yfatypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.Total) '
		SET @NpreSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.NTotal<0  THEN ABS(l.NTotal) '
		SET @preSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total>0 THEN l.Total '
		SET @NpreSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.NTotal>0 THEN l.NTotal '
		SET @QmSql=' 
		SUM(ISNULL(a.ApTotal,0)-ISNULL(a.yftotal,0)-ISNULL(b.addtotal,0)+ISNULL(b.rectotal,0)) AS qmtotal,
		SUM(ISNULL(a.NApTotal,0)-ISNULL(a.Nyftotal,0)-ISNULL(b.Naddtotal,0)+ISNULL(b.Nrectotal,0)) AS Nqmtotal, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)
		SET @QmSql=' 
		SUM(ISNULL(a.ApTotal,0)-ISNULL(b.addtotal,0)+ISNULL(b.rectotal,0)) AS qmtotal, 
		SUM(ISNULL(a.NApTotal,0)-ISNULL(b.Naddtotal,0)+ISNULL(b.Nrectotal,0)) AS Nqmtotal,'
	END
	
	SET @SQL='
	INSERT INTO #BType1
	(
		TypeId,
		stypeid,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	a.BTypeID,
			a.stypeid,
			0 AS Total00,
			0 AS NTotal00,
			0 AS BqaddTotal,
			0 AS NBqaddTotal,
			0 AS BqrecTotal,
			0 AS NBqrecTotal,
		    '+@QmSql+'
			0 AS arlimit'
	IF @cid=0
	BEGIN
		SET @SQL=@SQL+' FROM #BType_ARAPTotal a '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+' FROM #BType_ARAPTotal1 a '
	END
	
	IF @stypeid<>'' OR @MStypeid<>'00000' 
		SET @SQL=@SQL+' INNER JOIN #stype s ON a.StypeId=s.typeid '
		--print (@SQL)
	SET @SQL=@SQL+' 
	LEFT JOIN 
	(SELECT	L.BTypeId,
			SUM(CASE  WHEN l.billtype=6 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN l.BillType in(34,404,423)  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN l.billtype=161 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(6,34,161,404,423) THEN l.Total'+@preSql1+'
				  ELSE 0 END) AS addtotal,
			SUM(CASE  WHEN l.billtype=6 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN l.BillType in(34,404,423)  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN l.billtype=161 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(6,34,161,404,423) THEN l.NTotal'+@npreSql1+'
				  ELSE 0 END) AS Naddtotal,
			SUM(CASE 
				 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,404,423) THEN ABS(l.Total)'+@preSql2+'
				 ELSE 0 END) AS rectotal,
			SUM(CASE 
				 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,404,423) THEN ABS(l.NTotal)'+@NpreSql2+'
				 ELSE 0 END) AS Nrectotal,
			l.STypeID
	FROM	ListTable L '
		IF @stypeid<>'' OR @MStypeid<>'00000' 
			SET @SQL=@SQL+' INNER JOIN #stype s ON L.StypeId=s.typeid '

	SET @SQL=@SQL+' WHERE	L.BillDate>'''+@EndDate+'''
					AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39) 
	SET @SQL=@SQL+'
		GROUP BY L.BTypeId,l.STypeID) b ON a.BTypeID=b.BtypeId AND b.STypeID=a.STypeID '
	IF @cid<>0
		SET @SQL=@SQL+' WHERE a.cid='+CHAR(39)+@cid+CHAR(39)
	SET @SQL=@SQL+'
		GROUP BY a.btypeid,a.stypeid'
		
	EXEC(@sql)


	SET @SQL='
		INSERT INTO #BType1
		(
			TypeId,
			stypeid,
			Total00,
			NTotal00,
			BqaddTotal,
			NBqaddTotal,
			BqrecTotal,
			NBqrecTotal,
			Qmtotal,
			NQmtotal,
			ArLimit
		)
		SELECT	L.BTypeId,
				L.stypeid,
				0 AS total00,
				0 AS Ntotal00,
				SUM(CASE  WHEN l.billtype=6 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
					  WHEN l.BillType in(34,404,423)  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
					  WHEN l.billtype=161  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
					  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(6,34,161,404,423) THEN l.Total'+@preSql1+'
					  ELSE 0
				END) AS bqaddtotal,
				SUM(CASE  WHEN l.billtype=6 AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
					  WHEN l.BillType in(34,404,423)  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
					  WHEN l.billtype=161  AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
					  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(6,34,161,404,423) THEN l.NTotal'+@npreSql1+'
					  ELSE 0
				END) AS Nbqaddtotal,
				SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,404,423) THEN ABS(l.Total)'+@preSql2+'
					 ELSE 0
				END) AS bqrectotal,
				SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,404,423) THEN ABS(l.NTotal)'+@npreSql2+'
					 ELSE 0
				END) AS Nbqrectotal,
				0 AS qmtotal,
				0 AS Nqmtotal,
				0 AS ArLimit	
		FROM	ListTable L'
	IF @stypeid<>'' OR @MStypeid<>'00000' 
		SET @SQL=@SQL+' INNER JOIN #stype s ON L.StypeId=s.typeid '

	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@EndDate+''' 
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET	@SQL=@SQL+'	GROUP BY L.BTypeId,L.stypeid '
	--print @sql
	EXEC(@sql)
END


DECLARE @TableName VARCHAR(MAX)
IF NOT EXISTS(SELECT TOP 1 1 FROM #BtypeAll)
  BEGIN
       SET @TableName=' Btype B '
  END
ELSE
  BEGIN
       SET @TableName=' Btype B INNER JOIN #BtypeAll BA ON B.TypeID=BA.TypeID '
  END

SET @SQL='
SELECT 	B.TypeId,
		B.SonNum,
		B.UserCode,
		B.FullName,
		m.stypeid,
		SUM(ISNULL(m.Qmtotal,0)-ISNULL(m.bqaddtotal,0)+ISNULL(m.bqrectotal,0)) AS total00,
		SUM(ISNULL(m.NQmtotal,0)-ISNULL(m.Nbqaddtotal,0)+ISNULL(m.Nbqrectotal,0)) AS ntotal00,
		SUM(ISNULL(m.BqaddTotal,0)) AS bqaddtotal,
		SUM(ISNULL(m.NBqaddTotal,0)) AS Nbqaddtotal,
		SUM(ISNULL(m.BqrecTotal,0)) AS bqrectotal,
		SUM(ISNULL(m.NBqrecTotal,0)) AS Nbqrectotal,
		SUM(ISNULL(m.Qmtotal,0)) AS qmtotal,
		SUM(ISNULL(m.NQmtotal,0)) AS Nqmtotal,
		SUM(ISNULL(M.ArLimit,0)) AS ArLimit,
		SUM(CASE WHEN limitartotal>0 THEN limitartotal
			ELSE NULL
		END) AS limitartotal
FROM	
'+@TableName+'
LEFT JOIN (
	SELECT	TypeId,
			stypeid,
			SUM(ISNULL(BqaddTotal,0)) AS bqaddtotal,
			SUM(ISNULL(NBqaddTotal,0)) AS Nbqaddtotal,
			SUM(ISNULL(BqrecTotal,0)) AS bqrectotal,
			SUM(ISNULL(NBqrecTotal,0)) AS Nbqrectotal,
			SUM(ISNULL(Qmtotal,0)) AS qmtotal,
			SUM(ISNULL(NQmtotal,0)) AS Nqmtotal,
			SUM(ISNULL(ArLimit,0)) AS ArLimit,
			CASE WHEN SUM(ISNULL(arlimit,0))=0 THEN NULL 
				ELSE   SUM(ISNULL(qmtotal,0)-ISNULL(arlimit,0)) 
				END AS limitartotal
	FROM 	#BType1
	GROUP BY TypeId,stypeid
)M ON  M.typeid=b.typeid WHERE B.Sonnum=0 '
IF @btypeid<>''	
	SET @SQL=@SQL+'
	GROUP BY	B.TypeId,
				B.SonNum,
				B.UserCode,
				B.FullName,
				m.stypeid
	'
ELSE
	SET @SQL=@SQL+'
	GROUP BY	B.TypeId,
				B.SonNum,
				B.UserCode,
				B.FullName,
				m.stypeid '

IF @option=2
	SET @SQL='SELECT * FROM ('+@SQL+') AS a WHERE a.typeid NOT IN (SELECT typeid FROM ('+@SQL+') AS b WHERE b.qmtotal<>0)'
IF @option<>0 AND @option<>2
	SET @SQL='SELECT * FROM ('+@SQL+') AS a '+@SqlWhere
IF @option=0
	SET @SQL=@SQL+' ORDER BY B.UserCode'
--PRINT(@SQL)
--select * from #BType_ARAPTotal
EXEC(@SQL)

DROP TABLE #stype,#BType1,#BtypeAll
if(@cid=0)
DROP TABLE #BType_ARAPTotal
else
DROP TABLE #BType_ARAPTotal1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AreaIncExpLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AreaIncExpLineQuery]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------
--地区费用报表线性表
--作者：徐辉
--日期：2005-08-29
--引用：GP_CheckOperatorRight23
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示
	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
	--修改记录#05--------------------------------------------------------
	--人员：徐辉
	--日期：2005-1-29
	--说明：停用职员也要纳入统计	
	--修改记录#06--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-09
	--说明：添加行合计（v3.9）

	--修改记录#07--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修科目(qp1.0)

-------------------------------------------------------------------------
CREATE      PROCEDURE Web_AreaIncExpLineQuery  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(1550),	--指定要查询的财务科目节点ID
	@StartDate		VARCHAR(20),	--时间范围下限
	@EndDate		VARCHAR(20),	--时间范围上限
	@ArTypeid		VARCHAR(50),	--职员ID
	@STypeID		VARCHAR(1550),	--分支机构ID
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@nPageCol		INT,			--分页会计科目的页码
	@nPageColSize	int,
	@UserCode		VARCHAR(50)='',	--过滤职员Usercode
	@FullName		VARCHAR(50)='',	--过滤职员姓名
	@Flag           int =0          -- 0页面，1打印
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--徐辉 2005-08-29
--说明：该存储过程是又职员费用，收入报表修改的来，此处EtypeId既指地区Id
SET @METypeID = '' --部门目前没有权限范围
DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@nPageColSize
SET @MColCount=0
DECLARE @Point			INT				--用于保存截取子字符串位置的变量
DECLARE @SUBSTRING		VARCHAR(255)	--用于保存子字符串的变量
--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
--IF @AtypeID=''
--BEGIN
--	SET @ATypeID=CASE @QueryType
--		WHEN 0 THEN '00003'			--“收入类”科目根节点
--		--WHEN 1 THEN '0000400003'	--“费用合计”科目根节点 --#04 注释了
--		WHEN 1 THEN '00004' --“支出类”科目根节点 #04 添加
--	END
--END

CREATE TABLE #AType (TypeID varchar(50),NID VARCHAR(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #AreaType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #Stype (TypeID varchar(50))

CREATE TABLE #DetailATypeSr(TypeID varchar(50),NID VARCHAR(50))
INSERT INTO #DetailATypeSr select a.typeid AS ntypeid,a.nid from F_LineIncomeC(@OperatorID) a

CREATE TABLE #DetailATypeFy(TypeID varchar(50),NID VARCHAR(50))
INSERT INTO #DetailATypeFy select a.typeid AS ntypeid,a.nid from F_LineExpenseC(@OperatorID) a

CREATE TABLE #DetailDType(TypeID varchar(50))
INSERT INTO #DetailDType select typeid from F_GetManDetailDType(@OperatorID)

CREATE TABLE #DetailBType(TypeID varchar(50))
INSERT INTO #DetailBType select typeid from F_GetManDetailBType(@OperatorID)
INSERT INTO #DetailBType VALUES('')

CREATE TABLE #DetailEType(TypeID varchar(50))
INSERT INTO #DetailEType select typeid from F_GetManDetailEType(@OperatorID)

IF @QueryType=0 -- 收入
	IF @ATypeID=''
	BEGIN
		INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		from AC_Items a INNER JOIN #DetailATypeSr SR ON A.ntypeId=SR.TypeID
		----IF NOT EXISTS(select * from #Atype) --无管辖其他收入时，临时表为空,插入收入类科目（不包含其他收入类科目）
		--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		--select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		--from AC_Items a LEFT JOIN #AType a1 ON a.ntypeId=a1.TypeID 
		--where a.sonnum=0 and a.ntypeid LIKE '00003%' AND a.ntypeid NOT like '0000300003%' AND a1.typeid is null
	END
	ELSE
	BEGIN
		INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum)
		select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		from AC_Items a 
		INNER JOIN #DetailATypeSr SR ON A.ntypeId=SR.TypeID
		INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) B ON SR.TypeID LIKE b.ntypeid+'%'		
		----IF NOT EXISTS(select * from #Atype) --无管辖其他收入，临时表为空,插入收入类科目（不包含其他收入类科目）
		--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		--select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		--from AC_Items a 
		--INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b ON a.ntypeid LIKE b.ntypeid+'%'
		--LEFT JOIN #AType a1 ON a.ntypeId=a1.TypeID 
		--where a.sonnum=0 and a.ntypeid LIKE '00003%' AND a.ntypeid NOT like '0000300003%' AND a1.typeid is null
	END
ELSE  --费用
	IF @ATypeID=''
	BEGIN
		INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		from AC_Items a INNER JOIN #DetailATypeFy fy ON fy.TypeID=a.ntypeId
		----IF NOT EXISTS(select * from #Atype) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		--select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		--from AC_Items a LEFT JOIN #AType a1 ON a.ntypeId=a1.TypeID 
		--where a.sonnum=0 and a.ntypeid LIKE '00004%' AND a.ntypeid NOT like '0000400003%' AND a1.TypeID is null
	END
	ELSE
	BEGIN
		INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum)
		select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		from AC_Items a 
		INNER JOIN #DetailATypeFy SR ON A.ntypeId=SR.TypeID
		INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) B ON SR.TypeID LIKE b.ntypeid+'%'
		----IF NOT EXISTS(select * from #Atype) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		--select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		--from AC_Items a 
		--INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b ON a.ntypeid LIKE b.ntypeid+'%'
		--LEFT JOIN #AType a1 ON a.ntypeId=a1.TypeID 
		--where a.sonnum=0 and a.ntypeid LIKE  '00004%' AND a.ntypeid NOT like '0000400003%' AND a1.typeid is null
	END
DELETE FROM #Atype where typeid='000030000200007' --删除借转采购科目
DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #Atype where typeid='000040000200004'--#07 删除商品送修科目						
	
DELETE FROM #Atype where Sonnum<>0
DECLARE @sonnum int 
SET @sonnum =0

SELECT @sonnum = sonnum FROM AreaType WHERE Typeid =@ArTypeid
IF @sonnum =0 
	INSERT INTO #AreaType(typeid,usercode,fullname,sonnum) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum  FROM AreaType a where sonnum=0 and typeid<>'00000' and typeid=@ArTypeid  
ELSE
BEGIN
	INSERT INTO #AreaType(typeid,usercode,fullname,sonnum) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum FROM AreaType a WHERE sonnum=0 AND typeid<>'00000' and typeid LIKE CASE WHEN  @ArTypeid='00000' then +'%' else @ArTypeid+'%' end
END

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a inner join  (select * from  dbo.f_split(@StypeID,',')) b on a.typeid LIKE b.a+'%'

--#02以上------------------------------------------------------
--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(50),
	ETypeCode	VARCHAR(26),
	ETypeName	VARCHAR(66),
	SonNum		INT,
	ATypeCount	INT
)
IF @ArTypeid='00000'
	SET @ArTypeid = ''

DECLARE @AtypeName varchar(66)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'

DECLARE @ColName varchar(4000)
SET  @ColName =' EtypeID,EtypeCode,EtypeName+''(''+EtypeCode+'')'' as [地区/'+@AtypeName+'],Sonnum,ATypeCount,RowTotal'
IF @Flag =1
	SET  @ColName =' EtypeID,EtypeName+''(''+EtypeCode+'')'' as [地区/'+@AtypeName+'],RowTotal as RowTotal'


--对结果集合填充满足条件的部门数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum)
SELECT 
	a.TypeID AS ETypeID,
	a.UserCode AS ETypeCode,
	a.FullName AS ETypeName,
	a.SonNum AS SonNum
FROM  #areatype a
WHERE 
	a.SonNum = 0 
'

--判断是否显示其他地区时使用
DECLARE @OldFilterCode varchar(50),@OldFilterName varchar(50)
SELECT @OldFilterCode = @UserCode
SELECT @OldFilterName = @FullName
--组织职员编号过滤条件
IF @UserCode<>'' 
BEGIN
	SET @Point=charindex(',',@UserCode)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@UserCode,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @SUBSTRING + '%'''
		SET @UserCode=SUBSTRING(@UserCode,@Point+1,len(@UserCode)-@Point)
		SET @Point=charindex(',',@UserCode)
	END 
	IF @UserCode<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @UserCode + '%'''
	END 
END 
--组织职员名称过滤条件
IF @FullName<>'' 
BEGIN
	SET @Point=charindex(',',@FullName)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FullName,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @SUBSTRING + '%'''
		SET @FullName=SUBSTRING(@FullName,@Point+1,len(@FullName)-@Point)
		SET @Point=charindex(',',@FullName)
	END 
	IF @FullName<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @FullName + '%'''
	END	
END 
SET @SQL=@SQL + '
GROUP BY a.TypeID,a.UserCode,a.FullName,a.SonNum
ORDER BY a.UserCode
'
EXECUTE (@SQL)
--其他地区
IF @OldFilterCode = '' AND @OldFilterName = '' AND @ArTypeid = ''
BEGIN
	INSERT INTO #Temp_Result(ETypeID,ETypeCode,ETypeName,SonNum) VALUES ('99999','其他地区','其他地区',0)
END

--#06
--添加行合计值
ALTER TABLE #Temp_Result ADD [RowTotal]  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES


SELECT	a.TypeID AS ETypeID,
		#atype.typeid AS ATypeID,
		ISNULL(SUM(l.Total),0) AS Total
INTO #Temp_SubListTable
FROM ListTable l
--LEFT JOIN Billindex b ON b.BillNumberId = l.BillNumberId
LEFT JOIN
(
	SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.BillIndex
	UNION ALL
	SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.ReceiptBillIndex
	UNION ALL
	SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.Coupon_BillIndex
) AS b ON(b.BillNumberId = l.BillNumberId AND b.BillType = l.BillType)
LEFT JOIN btype w ON w.typeid = b.btypeid
INNER JOIN #AreaType a ON a.typeid = w.AreaTypeID
INNER JOIN #atype ON #atype.nid=l.atypeid
INNER JOIN #Stype ON #Stype.TypeID=l.STypeID
INNER JOIN #DetailDType D ON D.TypeID=L.DTypeID
INNER JOIN #DetailEType E ON E.TypeID=L.EtypeId
INNER JOIN #DetailBType B1 ON B1.TypeID=L.BtypeId
WHERE	l.Audited=1
		AND l.BillDate>=@StartDate
		AND l.BillDate<=@EndDate
GROUP BY a.TypeID,#atype.typeid


--特殊处理地区费用报表需要统计往来调账单据涉及的费用 2005-10-12
SELECT	B.areatypeid AS Etypeid, 
		#atype.typeid AS atypeid, 
		A.total AS total
INTO #Temp_SubListTable1
FROM addebtbill A
INNER JOIN listtable L ON L.billnumberid = A.billnumberid 
INNER JOIN #DetailDType D ON D.TypeID=L.DTypeID
INNER JOIN #DetailEType E ON E.TypeID=L.EtypeId
INNER JOIN #DetailBType B1 ON B1.TypeID=L.BtypeId
LEFT JOIN btype B ON B.Typeid = A.btypeid
INNER JOIN #atype ON #atype.nid=L.Atypeid
INNER JOIN #Stype s ON s.typeid=A.STypeID 
WHERE	L.Audited=1
		AND L.BillDate>=@StartDate
		AND L.BillDate<=@EndDate
		
--其他地区
IF @OldFilterCode = '' AND @OldFilterName = '' AND @ArTypeid = ''
BEGIN
	INSERT INTO #Temp_SubListTable 
	SELECT	'99999' AS ETypeID,
			a.typeid AS ATypeID,
			ISNULL(SUM(l.Total),0) AS Total
	FROM ListTable l
	--LEFT JOIN Billindex b ON b.BillNumberId = l.BillNumberId
	LEFT JOIN
	(
		SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.BillIndex
		UNION ALL
		SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.Coupon_BillIndex
	) AS b ON(b.BillNumberId = l.BillNumberId AND b.BillType = l.BillType)
	LEFT JOIN btype w ON w.typeid = b.btypeid
	INNER JOIN #atype a ON a.nid=l.atypeid
	INNER JOIN #Stype s ON s.TypeID=l.STypeID
	INNER JOIN #DetailDType D ON D.TypeID=L.DTypeID
	INNER JOIN #DetailEType E ON E.TypeID=L.EtypeId
	INNER JOIN #DetailBType B1 ON B1.TypeID=L.BtypeId
	WHERE	l.Audited=1
		AND l.BillDate>=@StartDate
		AND l.BillDate<=@EndDate
		AND 
		(
			((w.AreaTypeID IS null OR w.AreaTypeID='') AND l.BtypeID <> '')
			OR
			(l.BtypeID = '' AND l.Billtype = 159)
			OR
			((l.BtypeID IS NULL OR l.BtypeID = '') AND ( l.Billtype not in( 159,115,116,128,129)))
		)
	GROUP BY a.typeid
	--****9.6需求修改-文档遗漏导致BUG：667 杨俊2015-05-13--
	UNION ALL
	SELECT '99999' AS ETypeID,
	(SELECT TOP 1 NTypeID FROM Ac_Items WHERE FullName = '业务提成') AS ATypeID,
	ISNULL(SUM(CBND.CommissionTotal),0) AS Total 
	FROM CommissionBillNew AS CBN
	INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
	INNER JOIN #DetailEType E ON E.TypeID=CBND.EtypeId
	INNER JOIN #DetailDType D ON D.Typeid=CBND.DTypeID
	INNER JOIN #Stype s ON s.typeid=CBN.STypeID 
	WHERE CBN.ifcheck = 't'
		AND CBN.BillDate>=@StartDate
		AND CBN.BillDate<=@EndDate
	--GROUP BY CBND.EtypeID
	--****************************************************************************--
	
	
	--显示其他地区
	UPDATE #Temp_SubListTable1 SET ETypeId = '99999' WHERE Etypeid IS NULL OR Etypeid = ''
END
--合并结果集
SELECT  Etypeid,
		Atypeid,
		SUM(Total) AS Total
INTO #Temp_SubListTable2
FROM	(
		SELECT 	*
		from	#Temp_SubListTable1
		UNION ALL
		SELECT	*
		FROM	#Temp_SubListTable
) B
GROUP BY Etypeid,Atypeid

--#06 行合计
SELECT EtypeID, SUM(total) AS Total
INTO #Temp_RowSumSubListTable
FROM #Temp_SubListTable2
GROUP BY
	EtypeID

--#06 行合计
UPDATE #Temp_Result SET [RowTotal] = b.Total
FROM #Temp_Result AS a, #Temp_RowSumSubListTable b
WHERE a.ETypeID=b.ETypeID

DROP TABLE #Temp_RowSumSubListTable

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(50)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(26)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT TypeID,UserCode,FullName FROM #Atype 
OPEN MAtypeCursor
FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount
WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@nPageCol - 1) * @MColPageNum
	BEGIN
		IF @Flag =0
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + '|' + @MyUserCode + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName + '|' + @MyUserCode + ']'
			
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '|' + @MyUserCode + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable2 b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
			
		END 
		ELSE
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName + ']'
			
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable2 b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
			
		END 
	END
	IF @MColCount = @nPageCol * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
deallocate MAtypeCursor
--SELECT * FROM #Temp_Result
EXEC('SELECT '+@Colname+' FROM #Temp_Result WHERE RowTotal<>0')

--SELECT * FROM employee
--SELECT * FROM listtable
--SELECT col_length('employee','fullname')
--EXECUTE Web_EmployeeIncExpLineQuery 0,'','','','00001','','00001',1
--EXECUTE Web_EmployeeIncExpLineQuery 0,'','2003-6-30','2003-8-29','00001','','00001',1

DROP TABLE #Atype,#AreaType,#Stype, #Temp_Result,#DetailATypeFy,#DetailATypeSr,#DetailDType,#DetailEType,#DetailBType



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AreaIncExpLineQueryPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AreaIncExpLineQueryPrint]
GO








-------------------------------------------------------------------------
--地区费用报表线性表
--作者：徐辉
--日期：2005-08-29
--引用：GP_CheckOperatorRight23
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示
	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
	--修改记录#05--------------------------------------------------------
	--人员：徐辉
	--日期：2005-1-29
	--说明：停用职员也要纳入统计	
	--修改记录#06--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-09
	--说明：添加行合计（v3.9）
-------------------------------------------------------------------------
CREATE                              PROCEDURE Web_AreaIncExpLineQueryPrint  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(25),	--指定要查询的财务科目节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@ETypeID		VARCHAR(25),	--职员编号
	@EmployeeName	VARCHAR(66),	--职员姓名
	@OperatorID 	VARCHAR(25),	--操作员ID号
	@ATypePageNo	INT,			--分页会计科目的页码
	@ColPageNum		int,
	@FilterCode		VARCHAR(25)='',	--过滤职员Usercode
	@FilterName		VARCHAR(25)=''	--过滤职员姓名
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--徐辉 2005-08-29
--说明：该存储过程是又职员费用，收入报表修改的来，此处EtypeId既指地区Id
SET @METypeID = '' --部门目前没有权限范围
DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@ColPageNum
SET @MColCount=0
DECLARE @Point			INT				--用于保存截取子字符串位置的变量
DECLARE @SUBSTRING		VARCHAR(255)	--用于保存子字符串的变量
--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
IF @AtypeID=''
	BEGIN
		SET @ATypeID=CASE @QueryType
			WHEN 0 THEN '00003'			--“收入类”科目根节点
			--WHEN 1 THEN '0000400003'	--“费用合计”科目根节点 --#04 注释了
			WHEN 1 THEN '00004' --“支出类”科目根节点 #04 添加
		END
	END
--目前只有费用报表
--SET @ATypeID='00004'
--#02以下------------------------------------------------------
IF @QueryType=0 SET @MAtypeid=@MIncome
IF @QueryType=1 SET @MAtypeid=@MExpense
SET @MAtypeid=@MExpense --强行指定为费用权限范围
--#02以上------------------------------------------------------
--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(25),
	ETypeCode	VARCHAR(26),
	ETypeName	VARCHAR(66),
	SonNum		INT,
	ATypeCount	INT
)
IF @ETypeID='00000'
	SET @ETypeID = ''

DECLARE @AtypeName varchar(20)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'

DECLARE @ColName varchar(4000)
SET  @ColName ='EtypeName+''(''+EtypeCode+'')'' as [地区/'+@AtypeName+'],RowTotal as [总计]'

--对结果集合填充满足条件的部门数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum)
SELECT 
	a.TypeID AS ETypeID,
	a.UserCode AS ETypeCode,
	a.FullName AS ETypeName,
	a.SonNum AS SonNum
FROM AreaType a
WHERE 
	--a.Deleted=0 #05
	a.SonNum = 0 AND
	a.TypeID LIKE ''' + @ETypeID + '%''
'
IF @METypeID<>''
	--SET @SQL=@SQL + 'AND ''' + @METypeID + ''' LIKE a.TypeID + ''%'''--#03 新添加---------------------------------
	SET @SQL=@SQL + 'AND a.TypeID LIKE ''' + @METypeID + '%'''--#03 新添加---------------------------------
-- print @SQL 
-- return 0
--判断是否显示其他地区时使用
DECLARE @OldFilterCode varchar(25),@OldFilterName varchar(25)
SELECT @OldFilterCode = @FilterCode
SELECT @OldFilterName = @FilterName
--组织职员编号过滤条件
IF @FilterCode<>'' 
BEGIN
	SET @Point=charindex(',',@FilterCode)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FilterCode,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @SUBSTRING + '%'''
		SET @FilterCode=SUBSTRING(@FilterCode,@Point+1,len(@FilterCode)-@Point)
		SET @Point=charindex(',',@FilterCode)
	END 
	IF @FilterCode<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @FilterCode + '%'''
	END 
END 
--组织职员名称过滤条件
IF @FilterName<>'' 
BEGIN
	SET @Point=charindex(',',@FilterName)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FilterName,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @SUBSTRING + '%'''
		SET @FilterName=SUBSTRING(@FilterName,@Point+1,len(@FilterName)-@Point)
		SET @Point=charindex(',',@FilterName)
	END 
	IF @FilterName<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @FilterName + '%'''
	END	
END 
SET @SQL=@SQL + '
GROUP BY a.TypeID,a.UserCode,a.FullName,a.SonNum
ORDER BY a.UserCode
'
EXECUTE (@SQL)
--其他地区
IF @OldFilterCode = '' AND @OldFilterName = '' AND @ETypeID = ''
BEGIN
	INSERT INTO #Temp_Result(ETypeID,ETypeCode,ETypeName,SonNum) VALUES ('DDDDD','其他地区','其他地区',0)
END

--#06
--添加行合计值
ALTER TABLE #Temp_Result ADD [RowTotal]  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES


--SELECT * FROM #Temp_Result
SELECT a.TypeID AS ETypeID,l.ATypeID AS ATypeID,ISNULL(SUM(l.Total),0) AS Total
INTO #Temp_SubListTable
FROM ListTable l
LEFT JOIN Billindex b
ON b.BillNumberId = l.BillNumberId
LEFT JOIN btype w
ON w.typeid = b.btypeid
LEFT JOIN AreaType a
ON a.typeid = w.AreaTypeID
WHERE 
	l.Audited=1
	AND l.BillDate>=@BillDateBegin
	AND l.BillDate<=@BillDateEnd
	AND a.TypeID LIKE @ETypeID + '%'
	AND a.TypeID LIKE @MEtypeid + '%'
	AND l.ATypeID LIKE @ATypeID + '%'
	AND l.ATypeID LIKE @MAtypeid + '%'
	AND l.ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
GROUP BY a.TypeID,l.ATypeID
--特殊处理地区费用报表需要统计往来调账单据涉及的费用 2005-10-12
SELECT btype.areatypeid AS Etypeid, listtable.atypeid AS atypeid, addebtbill.total AS total
INTO #Temp_SubListTable1
FROM addebtbill
LEFT JOIN listtable ON listtable.billnumberid = addebtbill.billnumberid
LEFT JOIN btype ON btype.Typeid = addebtbill.btypeid
WHERE listtable.Atypeid LIKE @ATypeID + '%'
		AND listtable.Audited=1
		AND listtable.BillDate>=@BillDateBegin
		AND listtable.BillDate<=@BillDateEnd
--其他地区
IF @OldFilterCode = '' AND @OldFilterName = '' AND @ETypeID = ''
BEGIN
	INSERT INTO #Temp_SubListTable SELECT 'DDDDD' AS ETypeID,l.ATypeID AS ATypeID,ISNULL(SUM(l.Total),0) AS Total
	FROM ListTable l
	LEFT JOIN Billindex b
	ON b.BillNumberId = l.BillNumberId
	LEFT JOIN btype w
	ON w.typeid = b.btypeid
	WHERE 
		l.Audited=1
		AND l.BillDate>=@BillDateBegin
		AND l.BillDate<=@BillDateEnd
		AND 
			(
				((w.AreaTypeID IS null OR w.AreaTypeID='') AND l.BtypeID <> '')
				OR
				(l.BtypeID = '' AND l.Billtype = 159)
				OR
				((l.BtypeID IS NULL OR l.BtypeID = '') AND ( l.Billtype <> 159 AND l.Billtype <> 115 AND l.Billtype <> 116 AND l.Billtype <> 128 AND l.Billtype <> 129) )
			)
		AND l.ATypeID LIKE @ATypeID + '%'
		AND l.ATypeID LIKE @MAtypeid + '%'
		AND l.ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
	GROUP BY l.ATypeID
	--显示其他地区
	UPDATE #Temp_SubListTable1 SET ETypeId = 'DDDDD' WHERE Etypeid IS NULL OR Etypeid = ''
END
--合并结果集
SELECT  Etypeid,Atypeid,SUM(Total) AS Total
INTO #Temp_SubListTable2
 FROM	(
			SELECT 	*
			from	#Temp_SubListTable1
			UNION ALL
			SELECT	*
			FROM	#Temp_SubListTable
	) B
GROUP BY Etypeid,Atypeid

--#06 行合计
SELECT EtypeID, SUM(total) AS Total
INTO #Temp_RowSumSubListTable

FROM #Temp_SubListTable2
GROUP BY
	EtypeID

--#06 行合计
UPDATE #Temp_Result SET [RowTotal] = b.Total
FROM #Temp_Result AS a, #Temp_RowSumSubListTable b
WHERE a.ETypeID=b.ETypeID

DROP TABLE #Temp_RowSumSubListTable

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(25)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(26)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT TypeID,UserCode,FullName FROM Atype 
WHERE 
	SonNum=0
	AND TypeID LIKE @ATypeID + '%'--#03-------------
	AND TypeID LIKE @MAtypeid + '%'--#03-------------
	AND TypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
OPEN MAtypeCursor
FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount
WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@ATypePageNo - 1) * @MColPageNum
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName  + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName  + ']'
			
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName  + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable2 b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
			
		END 
	
	IF @MColCount = @ATypePageNo * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
deallocate MAtypeCursor
--SELECT * FROM #Temp_Result
EXEC('SELECT '+@Colname+' FROM #Temp_Result')

--SELECT * FROM employee
--SELECT * FROM listtable
--SELECT col_length('employee','fullname')
--EXECUTE Web_EmployeeIncExpLineQuery 0,'','','','00001','','00001',1
--EXECUTE Web_EmployeeIncExpLineQuery 0,'','2003-6-30','2003-8-29','00001','','00001',1








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AreaIncExpListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AreaIncExpListQuery]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


-------------------------------------------------------------------------
--地区费用收入报表树型表查询
--作者：徐辉
--日期：2005-08-29
--引用：GP_CheckOperatorRight23
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示
	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2003-11-21
	--说明：有错误：当筛选具体的一个职员时，返回空结果结合。
	--修改记录#05--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
	--修改记录#06--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-09
	--说明：添加行合计（v3.9）

	--修改记录#07--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修科目(qp1.0)
-------------------------------------------------------------------------
CREATE        PROCEDURE Web_AreaIncExpListQuery  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(1550),	--指定要查询的财务科目节点ID
	@StartDate		VARCHAR(20),	--时间范围下限
	@EndDate		VARCHAR(20),	--时间范围上限
	@ArTypeID		VARCHAR(50),	--地区Id
	@STypeId		VARCHAR(1550),	--分支机构
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@nPageCol		INT,			--分页会计科目的页码
	@nPageColSize	int,
	@Flag int =0                    -- 0页面，1打印
)
--@encode$--
AS
--徐辉2005-8-29
--说明，此存储过程又职员费用报表修改得到，所有此处的EType都是指地区
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SET @MEtypeid='' --地区暂时未设权限范围
DECLARE @SQL 			VARCHAR(max)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@nPageColSize
SET @MColCount=0

DECLARE @AtypeName varchar(66)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'
--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
--此处预留后期可能添加收入报表
--IF @AtypeID=''
--	BEGIN
--		SET @ATypeID=CASE @QueryType
--			WHEN 0 THEN ''			--“收入类”科目根节点
--			--WHEN 1 THEN '0000400003'	--“费用合计”科目根节点 --#05 注释了
--			WHEN 1 THEN '' --“支出类”科目根节点 #05 添加
--		END
--	END

--#02以上------------------------------------------------------
IF @ArTypeID='' SET @ArTypeID='00000'

CREATE TABLE #AType (TypeID varchar(50),NID VARCHAR(50),usercode varchar(300),fullname varchar(300),sonnum int)

CREATE TABLE #DetailATypeSr(TypeID varchar(50),NID VARCHAR(50))
INSERT INTO #DetailATypeSr select a.ntypeid,a.nid from F_AllTreeIncomeC(@OperatorID) a

CREATE TABLE #DetailATypeFy(TypeID varchar(50),NID VARCHAR(50))
INSERT INTO #DetailATypeFy select a.typeid AS ntypeid,a.nid from F_LineExpenseC(@OperatorID) a

CREATE TABLE #AreaType (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #Btype(TypeID varchar(50))
CREATE TABLE #Etype(TypeID varchar(50))
CREATE TABLE #Dtype(Typeid varchar(50))

IF @QueryType=0 -- 收入
	IF @ATypeID=''
	BEGIN
		INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		from AC_Items a 
		INNER JOIN #DetailATypeSr SR ON A.NtypeId=SR.TypeID
		----IF NOT EXISTS(select * from #Atype) --无管辖其他收入时，临时表为空,插入收入类科目（不包含其他收入类科目）
		--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		--select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		--from AC_Items a 
		--LEFT JOIN #AType a1 ON a.ntypeId=a1.TypeID 
		--where a.sonnum=0 and a.ntypeid LIKE '00003%' AND a.ntypeid NOT like '0000300003%' AND a1.typeid is null
	
	END
	ELSE
	BEGIN
		INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum)
		select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		from AC_Items a 
		INNER JOIN #DetailATypeSr SR ON A.ntypeId=SR.TypeID
		INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) B ON SR.TypeID LIKE b.ntypeid+'%'	
		----IF NOT EXISTS(select * from #Atype) --无管辖其他收入，临时表为空,插入收入类科目（不包含其他收入类科目）
		--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		--select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		--from AC_Items a 
		--INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b ON a.typeid LIKE b.ntypeid+'%'
		--LEFT JOIN #AType a1 ON a.ntypeId=a1.TypeID 
		--where a.sonnum=0 and a.ntypeid LIKE '00003%' AND a.ntypeid NOT like '0000300003%' AND a1.typeid is null
		
		
	END
ELSE  --费用
	IF @ATypeID=''
	BEGIN
		INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		from AC_Items a INNER JOIN #DetailATypeFy fy ON fy.TypeID=a.ntypeId
		----IF NOT EXISTS(select * from #Atype) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		--select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		--from AC_Items a LEFT JOIN #AType a1 ON a.ntypeId=a1.TypeID 
		--where a.sonnum=0 and a.ntypeid LIKE '00004%' AND a.ntypeid NOT like '0000400003%' AND a1.TypeID is null
	END
	ELSE
	BEGIN
		INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum)
		select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		from AC_Items a 
		INNER JOIN #DetailATypeFy SR ON A.ntypeId=SR.TypeID
		INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) B ON SR.TypeID LIKE b.ntypeid+'%'
		----IF NOT EXISTS(select * from #Atype) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		--select a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum 
		--from AC_Items a 
		--INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b ON a.ntypeid LIKE b.ntypeid+'%'
		--LEFT JOIN #AType a1 ON a.ntypeId=a1.TypeID 
		--where a.sonnum=0 and a.ntypeid LIKE  '00004%' AND a.ntypeid NOT like '0000400003%' AND a1.typeid is null
	 --  PRINT(1)
	END

DELETE FROM #Atype where typeid='000030000200007' --删除借转采购科目
DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #Atype where typeid='000040000200004'--#07 删除商品送修科目					

DECLARE @sonnum int 
SET @sonnum =0

SELECT @sonnum = sonnum FROM AreaType WHERE Typeid =@ArTypeID
IF @sonnum =0 
BEGIN
	INSERT INTO #AreaType(typeid) 
	SELECT a.typeid FROM AreaType a where typeid=@ArTypeID and typeid<>'00000'
END
ELSE
BEGIN
	INSERT INTO #AreaType(typeid) 
	SELECT a.typeid FROM AreaType a WHERE  sonnum=0 and typeid<>'00000' AND typeid LIKE CASE WHEN  @ArTypeID='00000' then +'%' else @ArTypeID+'%' end
END


IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where a.typeid LIKE b.a+'%'

INSERT INTO #Btype(typeid) select ba.TypeId from (select typeid from F_GetManDetailBType(@OperatorID) UNION SELECT '' AS typeid)ba
INSERT INTO #Etype(typeid) select typeid from F_GetManDetailEType(@OperatorID)
INSERT INTO #Dtype(TYPEID) select typeid from F_GetManDetailDType(@OperatorID)
--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(50),
	ETypeCode	VARCHAR(50),
	ETypeName	VARCHAR(200),
	SonNum		INT,
	ATypeCount	INT,
	deleted     int
)
DECLARE @ColName varchar(max)
SET  @ColName =' EtypeID,EtypeCode,EtypeName+''(''+EtypeCode+'')'' as [地区/'+@AtypeName+'],Sonnum,ATypeCount,RowTotal,deleted'
IF @Flag =1
	SET  @ColName =' EtypeID,EtypeName+''(''+EtypeCode+'')'' as [地区/'+@AtypeName+'],RowTotal as RowTotal'
--对结果集合填充满足条件的部门数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum,deleted)
SELECT 
	TypeID AS ETypeID,
	UserCode AS ETypeCode,
	FullName AS ETypeName,
	SonNum AS SonNum,
	deleted
FROM AreaType
WHERE 
'
IF @sonnum=0
	SET @SQL=@SQL +' typeid='''+@ArTypeID+''''
ELSE
	SET @SQL=@SQL +' parid='''+@ArTypeID+''''
SET @SQL=@SQL +'
AND typeid<>''00000''
ORDER BY UserCode'
--print @SQL
EXECUTE(@SQL)

--第一层才显示其他地区
IF @ArTypeID='00000'
BEGIN
	--记录下没有部门全记录到其他地区
	INSERT INTO #Temp_Result(ETypeID,ETypeCode,ETypeName,SonNum) VALUES ('99999','其他地区','其他地区',0) 
END

--#06
--添加行合计值
ALTER TABLE #Temp_Result ADD [RowTotal]  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES

--SELECT * FROM #Temp_Result
-- print @ArTypeID
-- print @METypeID
-- Print @ATypeID
-- print @MAtypeid
-- return 0
IF @ArTypeID='00000'  SET @ArTypeID='' --前面设置了现在设置回来
--根据条件筛选地区信息到一个临时表
--SELECT * FROM ListTable
 
SELECT	SUBSTRING(w.AreaTypeID,1,len(@ArTypeID)+5) AS ETypeID,
		a.TypeID AS ATypeID,
		ISNULL(SUM(l.Total),0) AS Total
INTO #Temp_SubListTable
FROM ListTable l
INNER JOIN #Atype a ON a.nid=l.atypeid 
INNER JOIN #Stype s ON s.TypeID=l.STypeID
--LEFT JOIN Billindex b ON b.BillNumberId = l.BillNumberId
LEFT JOIN
(
	SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.BillIndex
	UNION ALL
	SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.ReceiptBillIndex
	UNION ALL
	SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.Coupon_BillIndex
) AS b ON(b.BillNumberId = l.BillNumberId AND b.BillType = l.BillType)
LEFT JOIN btype w ON w.typeid = b.btypeid
INNER JOIN #areatype ar ON w.areatypeid=ar.typeid
INNER JOIN #Etype E ON E.TypeID=L.EtypeId
INNER JOIN #Btype B1 ON B1.TypeID=L.BtypeId
INNER JOIN #Dtype D ON D.Typeid=L.DTypeID
WHERE	l.Audited=1
		AND l.BillDate>=@StartDate
		AND l.BillDate<=@EndDate
		AND b.ifYearBill=0	 --年节存标志
GROUP BY SUBSTRING(w.AreaTypeID,1,len(@ArTypeID)+5),a.TypeID


--特殊处理地区费用报表需要统计往来调账单据涉及的费用 2005-10-12
SELECT	SUBSTRING(btype.areatypeid,1,len(@ArTypeID)+5) AS Etypeid,
		a1.typeid AS atypeid, 
		a.total AS total
INTO #Temp_SubListTable1
FROM addebtbill a
INNER JOIN listtable L ON L.billnumberid = a.billnumberid 
INNER JOIN #Etype E ON E.TypeID=L.EtypeId
INNER JOIN #Btype B1 ON B1.TypeID=L.BtypeId
INNER JOIN #Dtype D ON D.Typeid=L.DTypeID
LEFT JOIN btype ON btype.Typeid = a.btypeid
INNER JOIN #Atype a1 ON a1.nid=l.atypeid 
INNER JOIN #Stype s ON s.typeid=a.STypeID 
WHERE	l.Audited=1
		AND l.BillDate>=@StartDate
		AND l.BillDate<=@EndDate

--第一层才显示其他地区
IF @ArTypeID = ''
BEGIN
	INSERT INTO #Temp_SubListTable 
	SELECT	'99999' AS ETypeID,
			a1.TypeID AS ATypeID,
			ISNULL(SUM(l.Total),0) AS Total
	FROM ListTable l
	--LEFT JOIN Billindex b ON b.BillNumberId = l.BillNumberId
	LEFT JOIN 
	(
		SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.BillIndex
		UNION ALL
		SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillNumberId,BillType,btypeid,ifYearBill FROM dbo.Coupon_BillIndex
	) AS b ON(b.BillNumberId = l.BillNumberId AND b.BillType = l.BillType)
	LEFT JOIN btype w ON w.typeid = b.btypeid
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	INNER JOIN #Btype B1 ON B1.TypeID=L.BtypeId
	INNER JOIN #Dtype D ON D.Typeid=L.DTypeID
	INNER JOIN #Atype a1 ON a1.nid=l.atypeid 
	INNER JOIN #Stype s ON s.typeid=l.STypeID 
	WHERE	l.Audited=1
			AND l.BillDate>=@StartDate
			AND l.BillDate<=@EndDate
			AND 
			(
				((w.AreaTypeID IS NULL OR w.AreaTypeID='') AND l.BtypeID <> '')
		  			OR 
				(l.BtypeID = '' AND l.Billtype = 159)
					OR
				((l.BtypeID IS NULL OR l.BtypeID = '') AND ( l.Billtype not in( 159,115,116,128,129)))
			)
			AND b.ifYearBill=0	 --年节存标志
	GROUP BY a1.TypeID
	--****9.6需求修改-文档遗漏导致BUG：667 杨俊2015-05-13--
	UNION ALL
	SELECT '99999' AS ETypeID,
	(SELECT TOP 1 NTypeID FROM Ac_Items WHERE FullName = '业务提成') AS ATypeID,
	ISNULL(SUM(CBND.CommissionTotal),0) AS Total 
	FROM CommissionBillNew AS CBN
	INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
	INNER JOIN #Etype E ON E.TypeID=CBND.EtypeId
	INNER JOIN #Dtype D ON D.Typeid=CBND.DTypeID
	INNER JOIN #Stype s ON s.typeid=CBN.STypeID 
	WHERE CBN.ifcheck = 't'
		AND CBN.BillDate>=@StartDate
		AND CBN.BillDate<=@EndDate
	--GROUP BY CBND.EtypeID
	--****************************************************************************--

	--显示其他地区
	UPDATE #Temp_SubListTable1 SET ETypeId = '99999' WHERE Etypeid IS NULL OR Etypeid = ''
END

--合并结果集
SELECT  Etypeid,Atypeid,
		SUM(Total) AS Total
INTO #Temp_SubListTable2
FROM	(
		SELECT 	*
		from	#Temp_SubListTable1
		UNION ALL
		SELECT	*
		FROM	#Temp_SubListTable
) B
GROUP BY Etypeid,Atypeid

--#06 行合计
SELECT	EtypeID, 
		SUM(total) AS Total
INTO #Temp_RowSumSubListTable
FROM #Temp_SubListTable2
GROUP BY EtypeID

--#06 行合计
UPDATE #Temp_Result SET [RowTotal] = b.Total
FROM #Temp_Result AS a, #Temp_RowSumSubListTable b
WHERE a.ETypeID=b.ETypeID

DROP TABLE #Temp_RowSumSubListTable

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(50)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(26)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT TypeID,UserCode,FullName FROM #Atype 
OPEN MAtypeCursor
FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount
WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@nPageCol - 1) * @MColPageNum
	BEGIN
		IF @Flag =0
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + '|' + @MyUserCode + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
	
			EXECUTE(@SQL)
			
			SET  @ColName= @ColName+',[' + @MyATypeName + '|' + @MyUserCode + ']'

			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '|' + @MyUserCode + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable2 b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			--print @SQL
			EXECUTE(@SQL)
			
		END 
		ELSE
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			
			SET  @ColName= @ColName+',[' + @MyATypeName +  ']'

			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable2 b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			--print @SQL
			EXECUTE(@SQL)
		END 
	END	
	IF @MColCount = @nPageCol * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
deallocate MAtypeCursor
--SELECT * FROM #Temp_Result

EXEC('SELECT '+@Colname+' FROM #Temp_Result WHERE RowTotal<>0')

DROP TABLE #Atype,#Stype,#AreaType,#Temp_Result,#Btype,#Etype,#DetailATypeFy,#DetailATypeSr,#Dtype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AreaIncExpListQueryPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AreaIncExpListQueryPrint]
GO









-------------------------------------------------------------------------
--地区费用收入报表树型表查询
--作者：徐辉
--日期：2005-08-29
--引用：GP_CheckOperatorRight23
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示
	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2003-11-21
	--说明：有错误：当筛选具体的一个职员时，返回空结果结合。
	--修改记录#05--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
	--修改记录#06--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-09
	--说明：添加行合计（v3.9）
-------------------------------------------------------------------------
CREATE                                    PROCEDURE Web_AreaIncExpListQueryPrint  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(50),	--指定要查询的财务科目节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@ETypeID		VARCHAR(50),	--职员编号
	@EmployeeName	VARCHAR(66),	--职员姓名
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@ATypePageNo	INT,				--分页会计科目的页码
	@ColPageNum		int
)
--@encode$--
AS
--徐辉2005-8-29
--说明，此存储过程又职员费用报表修改得到，所有此处的EType都是指地区
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SET @MEtypeid='' --地区暂时未设权限范围
DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@ColPageNum
SET @MColCount=0

DECLARE @AtypeName varchar(20)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'
--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
--此处预留后期可能添加收入报表
IF @AtypeID=''
	BEGIN
		SET @ATypeID=CASE @QueryType
			WHEN 0 THEN '00003'			--“收入类”科目根节点
			--WHEN 1 THEN '0000400003'	--“费用合计”科目根节点 --#05 注释了
			WHEN 1 THEN '00004' --“支出类”科目根节点 #05 添加
		END
	END
--#02以下------------------------------------------------------
IF @QueryType=0 SET @MAtypeid=@MIncome
IF @QueryType=1 SET @MAtypeid=@MExpense
--#02以上------------------------------------------------------
IF @ETypeID='' SET @ETypeID='00000'
--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(25),
	ETypeCode	VARCHAR(26),
	ETypeName	VARCHAR(66),
	SonNum		INT,
	ATypeCount	INT,
	deleted     int
)
DECLARE @ColName varchar(4000)
SET  @ColName ='EtypeName+''(''+EtypeCode+'')'' as [地区/'+@AtypeName+'],RowTotal as [总计]'
--对结果集合填充满足条件的部门数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum,deleted)
SELECT 
	TypeID AS ETypeID,
	UserCode AS ETypeCode,
	FullName AS ETypeName,
	SonNum AS SonNum,
	deleted
FROM AreaType
WHERE '
--#04 Begin---------------------------------
DECLARE @ETypeSonNum INT
SELECT @ETypeSonNum=SonNum FROM AreaType WHERE Deleted=0 AND TypeID=@ETypeID
--print @ETypeSonNum
IF @ETypeSonNum>0 
	BEGIN
	SET @SQL=@SQL + '
	ParID=''' + @ETypeID +''''
	END
ELSE
	BEGIN
	SET @SQL=@SQL + '
	TypeID=''' + @ETypeID +''''
	END
--#04 End  ---------------------------------
--print @SQL
--select * from #Temp_Result
IF @METypeID<>''
	--SET @SQL=@SQL + 'AND ''' + @METypeID + ''' LIKE TypeID + ''%'''--#03 新添加---------------------------------
	SET @SQL=@SQL + 'AND TypeID LIKE ''' + @METypeID + '%'''--#03 新添加---------------------------------
SET @SQL=@SQL +'	
ORDER BY UserCode'
--print @SQL
EXECUTE(@SQL)
--第一层才显示其他地区
IF @ETypeID='00000'
BEGIN
	--记录下没有部门全记录到其他地区
	INSERT INTO #Temp_Result(ETypeID,ETypeCode,ETypeName,SonNum) VALUES ('DDDDD','其他地区','其他地区',0) 
END

--#06
--添加行合计值
ALTER TABLE #Temp_Result ADD [RowTotal]  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES

--SELECT * FROM #Temp_Result
-- print @ETypeID
-- print @METypeID
-- Print @ATypeID
-- print @MAtypeid
-- return 0
IF @ETypeID='00000'  SET @ETypeID='' --前面设置了现在设置回来
--根据条件筛选地区信息到一个临时表
--SELECT * FROM ListTable
SELECT SUBSTRING(a.TypeID,1,len(@ETypeID)+5) AS ETypeID,l.ATypeID AS ATypeID,ISNULL(SUM(l.Total),0) AS Total
INTO #Temp_SubListTable
FROM ListTable l
LEFT JOIN Billindex b
ON b.BillNumberId = l.BillNumberId
LEFT JOIN btype w
ON w.typeid = b.btypeid
LEFT JOIN AreaType a
ON a.typeid = w.AreaTypeID
WHERE 
	l.Audited=1
	AND l.BillDate>=@BillDateBegin
	AND l.BillDate<=@BillDateEnd
	AND a.TypeID LIKE @ETypeID + '%'
	AND a.TypeID LIKE @MEtypeid + '%'
	AND l.ATypeID LIKE @ATypeID + '%'
	AND l.ATypeID LIKE @MAtypeid + '%'
	AND l.ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
GROUP BY SUBSTRING(a.TypeID,1,len(@ETypeID)+5),l.ATypeID
--特殊处理地区费用报表需要统计往来调账单据涉及的费用 2005-10-12
SELECT SUBSTRING(btype.areatypeid,1,len(@ETypeID)+5) AS Etypeid, listtable.atypeid AS atypeid, addebtbill.total AS total
INTO #Temp_SubListTable1
FROM addebtbill
LEFT JOIN listtable ON listtable.billnumberid = addebtbill.billnumberid
LEFT JOIN btype ON btype.Typeid = addebtbill.btypeid
WHERE listtable.Atypeid LIKE @ATypeID + '%'
		AND listtable.Audited=1
		AND listtable.BillDate>=@BillDateBegin
		AND listtable.BillDate<=@BillDateEnd
--第一层才显示其他地区
IF @ETypeID = ''
BEGIN
	INSERT INTO #Temp_SubListTable SELECT 'DDDDD' AS ETypeID,l.ATypeID AS ATypeID,ISNULL(SUM(l.Total),0) AS Total
	FROM ListTable l
	LEFT JOIN Billindex b
	ON b.BillNumberId = l.BillNumberId
	LEFT JOIN btype w
	ON w.typeid = b.btypeid
	WHERE 
		l.Audited=1
		AND l.BillDate>=@BillDateBegin
		AND l.BillDate<=@BillDateEnd
		AND 
			(
				((w.AreaTypeID IS NULL OR w.AreaTypeID='') AND l.BtypeID <> '')
			  		OR 
				(l.BtypeID = '' AND l.Billtype = 159)
					OR
				((l.BtypeID IS NULL OR l.BtypeID = '') AND ( l.Billtype <> 159 AND l.Billtype <> 115 AND l.Billtype <> 116 AND l.Billtype <> 128 AND l.Billtype <> 129) )
			)
		AND l.ATypeID LIKE @ATypeID + '%'
		AND l.ATypeID LIKE @MAtypeid + '%'
		AND l.ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
	GROUP BY l.ATypeID
	--显示其他地区
	UPDATE #Temp_SubListTable1 SET ETypeId = 'DDDDD' WHERE Etypeid IS NULL OR Etypeid = ''
END
--合并结果集
SELECT  Etypeid,Atypeid,SUM(Total) AS Total
INTO #Temp_SubListTable2
 FROM	(
			SELECT 	*
			from	#Temp_SubListTable1
			UNION ALL
			SELECT	*
			FROM	#Temp_SubListTable
	) B
GROUP BY Etypeid,Atypeid

--#06 行合计
SELECT EtypeID, SUM(total) AS Total
INTO #Temp_RowSumSubListTable
FROM #Temp_SubListTable2
GROUP BY
	EtypeID

--#06 行合计
UPDATE #Temp_Result SET [RowTotal] = b.Total
FROM #Temp_Result AS a, #Temp_RowSumSubListTable b
WHERE a.ETypeID=b.ETypeID

DROP TABLE #Temp_RowSumSubListTable

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(25)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(26)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT TypeID,UserCode,FullName FROM Atype 
WHERE 
	SonNum=0
	AND TypeID LIKE @ATypeID + '%'--#03-------------
	AND TypeID LIKE @MAtypeid + '%'--#03-------------
	AND TypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
OPEN MAtypeCursor
FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount
WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@ATypePageNo - 1) * @MColPageNum
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName  + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			
			SET  @ColName= @ColName+',[' + @MyATypeName  + ']'

			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName  + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable2 b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			--print @SQL
			EXECUTE(@SQL)
			
		END 
	
	IF @MColCount = @ATypePageNo * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
deallocate MAtypeCursor
--SELECT * FROM #Temp_Result

EXEC('SELECT '+@Colname+' FROM #Temp_Result')
--SELECT * FROM employee
--SELECT * FROM listtable
--SELECT col_length('employee','fullname')
--EXECUTE Web_EmployeeIncExpListQuery 0,'','','','00001','','00001',1
--EXECUTE Web_EmployeeIncExpListQuery 0,'','2003-6-30','2003-8-29','00001','','00001',1









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AreaSaleDist]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_AreaSaleDist]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-06-25
function:地区销售分布表树形表
*/
CREATE PROCEDURE Web_AreaSaleDist
(
	@OperatorId		VARCHAR(100),		--操作员Id
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--结束日期
	@StypeId        VARCHAR(MAX),		--分支机构Id
	@PtypeCategoryId VARCHAR(MAX),		--商品类别ID
	@PTypeId		VARCHAR(MAX),		--商品Id
	@AreaTypeId		VARCHAR(MAX),		--部门Id
	@nType			VARCHAR(10),		--金额的查询方式
	@BillType		VARCHAR(100),		--单据类型
	@ShowZero		VARCHAR(5),			--0.不显示红冲单据   1.显示红冲单据
	@UnitConvert	INT,				--单位
	@Sort		    NVARCHAR(200),		--排序
	@Ck				INT,				--1：升序 0降序

	@BCount			INT=10,				--基本信息的默认个数
	@BPageNo		INT=0,				--基本信息的页数
	@IsPrint		INT=0				--是否是打印算法
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------

DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================

--根据单位获取相关值
DECLARE
	@TempColumn			VARCHAR(50),
	@TempQty			VARCHAR(1000)='',
	@TempTable			VARCHAR(1000)=''
	
--销售单位		
IF @UnitConvert=0
	BEGIN
		SET @TempColumn='SaleUnitId'
		SET @TempTable='
		LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.SaleUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
		
	END
--采购单位
ELSE IF @UnitConvert=1
	BEGIN
		SET @TempColumn='BuyUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.BuyUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--存货单位
ELSE IF @UnitConvert=2
	BEGIN
		SET @TempColumn='StockUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.StockUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--基本单位
ELSE IF @UnitConvert=3
	BEGIN
		SET @TempColumn='baseUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.baseUnitId = R.UnitsId'
		SET @TempQty='B.Qty'
	END

--商品
IF(ISNULL(@PTypeId,'')='')
	SET @PTypeId='00000'

--父级
CREATE TABLE #ParidPtype(
	RowId				INT,
	TypeID				VARCHAR(50),
	SonNum				INT,
	UserCode			VARCHAR(200),
	AssistUnitFullName	VARCHAR(200),
	UnitFullName		VARCHAR(200),
	Rate				NUMERIC(24,10)
) 
CREATE CLUSTERED INDEX #ParidPtype_P_K ON #ParidPtype(TypeId)

DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,@PTypeId,@PtypeCategoryId)

SET @SQL='
INSERT INTO #ParidPtype(RowId,TypeID,SonNum,UserCode,AssistUnitFullName,UnitFullName,Rate)
SELECT
	ROW_NUMBER()OVER(ORDER BY P.UserCode) RowId,
	P.typeId,
	P.sonnum,
	P.UserCode,
	E.FullName AssistUnitFullName,
	PU.FullName UnitFullName,
	R.Rate
 '+@LinkStr+'
 LEFT JOIN PType_Units E ON P.AssistantUnitId=E.UnitsId
 '+@TempTable+'
 LEFT JOIN PType_Units PU ON PU.UnitsId=P.'+@TempColumn+'
 WHERE
	P.ParId='''+@PTypeId+'''
	AND P.iscombinationproduct=0'

EXEC(@SQL)

--实际查询商品
CREATE TABLE #Ptype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)
INSERT INTO #Ptype(TypeID)
SELECT
	P.typeId
FROM ptype P
INNER JOIN #ParidPtype F ON P.typeId LIKE F.TypeID+'%' AND P.sonnum=0 AND P.iscombinationproduct=0 

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	BEGIN
		INSERT INTO #Stype(typeid) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
	END

--部门
CREATE TABLE #Dtype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
IF(@MDtypeid='-99999')
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetManDetailDType(@OperatorId)
	END

--往来单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetManDetailBType(@OperatorId)
	END

--职员
CREATE TABLE #Etype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF (@MEtypeid='-99999')
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetManDetailEType(@OperatorId)
	END

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeId)
IF (@MKtypeid='-99999')
	BEGIN
		INSERT INTO #Ktype(TypeID)
		SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
		UNION ALL
		SELECT '10000' TypeId
	END

--所有地区
CREATE TABLE #AreaType(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Areatype_P_K ON #Areatype(TypeId)
IF(@AreaTypeId='')
	BEGIN
		INSERT INTO #AreaType(RowId,TypeID,UserCode,FullName)
		SELECT
			ROW_NUMBER()OVER(ORDER BY UserCode) RowId,
			typeId,
			UserCode,
			FullName
		FROM( 
			SELECT 
				typeId,
				UserCode,
				FullName
			FROM AreaType WHERE sonnum=0 AND typeId<>'00000'
			UNION ALL
			SELECT '9999' typeId, '其他地区' UserCode, '其他地区' FullName
		) F
		ORDER BY UserCode
	END
ELSE 
	BEGIN
		INSERT INTO #AreaType(RowId,TypeID,UserCode,FullName)
		SELECT 
			ROW_NUMBER()OVER(ORDER BY D.usercode) RowId,
			D.TypeId,
			D.usercode,
			D.FullName
		FROM AreaType D
		INNER JOIN f_split(@AreaTypeId,',') F ON D.sonnum=0 AND D.typeId<>'00000' AND F.a=LEFT(D.typeid,LEN(F.A))
		ORDER BY usercode
	END

--当前页地区
CREATE TABLE #PageAreaType(TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #PageAreaType(TypeID,UserCode,FullName)
SELECT 
	typeid,
	UserCode,
	FullName 
FROM #Areatype
WHERE RowId BETWEEN (@bPageNo-1)*@bCount+1 AND @bPageNo*@bCount

--=============================基本信息权限范围获取【END】=======================================

--=============================业务处理【BEGIN】=====================================
SET @SQL=''

--BillIndex
CREATE TABLE #BillIndex
(
	BillNumberId 	NUMERIC(18,0),
	AreaTypeId		VARCHAR(50),
	BillType		INT	
) 
CREATE CLUSTERED INDEX #BillIndex_P_K ON #BillIndex(BillNumberId)

SET @SQL='
INSERT INTO #BillIndex
(
	BillNumberId,
	AreaTypeID,
	BillType
)
SELECT	
	B.BillNumberId,
	CASE WHEN ISNULL(BT.AreaTypeID,'''')='''' THEN ''9999'' ELSE BT.AreaTypeID END AreaTypeID,
	B.BillType
FROM BillIndex B
INNER JOIN btype BT ON BT.TypeID=B.DealBTypeID  AND B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' AND B.BillType IN ('+@BillType+') AND B.RedWord=0 AND B.IfCheck=''t'' AND B.Draft=0 AND B.ifYearBill=0' +CHAR(13)	

--分支机构
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	SET @SQL+='INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid'+CHAR(13)	
	
--地区
IF NOT(ISNULL(@AreaTypeId,'')='')
	SET @SQL+='INNER JOIN #AreaType B_T ON B_T.TypeID=BT.AreaTypeID'+CHAR(13)	
	
--往来单位
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		SET @SQL+='INNER JOIN #Btype B_B ON B_B.TypeID=B.BTypeID'+CHAR(13)
		SET @SQL+='INNER JOIN #Btype B_B1 ON B_B1.TypeID=B.DealBTypeID'+CHAR(13)
	END

--职员		
IF(@MEtypeid='-99999')
	SET @SQL+='INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid'+CHAR(13)

--部门
IF(@MDtypeid='-99999')
	SET @SQL+='INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId'+CHAR(13)

EXEC(@SQL)
SET @SQL=''

--数据明细表
CREATE TABLE #SaleBill
(
	PTypeId			VARCHAR(50),
	AreaTypeID	VARCHAR(50),
	Qty				NUMERIC(24,10),
	NQty			NUMERIC(24,10),
	TaxTotal		NUMERIC(24,10) 
)
CREATE CLUSTERED INDEX #SaleBill_P_K ON #SaleBill(PTypeId)

--零售单
IF CHARINDEX('305',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN retailBill B ON I.BillType=305 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--零售退货单
IF CHARINDEX('215',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN RetailBackBill B ON I.BillType=215 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
	
END

--销售出库单
IF CHARINDEX('11',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN SaleBill B ON I.BillType=11 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--销售退货单
IF CHARINDEX('45',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN saleBackBill B ON I.BillType=45 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--销售换货单
IF CHARINDEX('160',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		CASE WHEN B.InOrOut = ''o'' THEN SUM('+@tempqty+') ELSE -SUM('+@tempqty+') END Qty,
		CASE WHEN B.InOrOut = ''o'' THEN SUM(B.NQty) ELSE -SUM(B.NQty) END NQty,
		CASE WHEN B.InOrOut = ''o'' THEN CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END
			 ELSE CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END
		END TaxTotal 
	FROM #BillIndex I 
	INNER JOIN SaleGoodsExchangeBill B ON I.BillType=160 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
	
	SET @SQL+='WHERE 
		B.InOrOut=''i'' 
		OR B.InOrOut=''o''  
	GROUP BY B.PTypeId,I.AreaTypeID,B.InOrOut'+CHAR(13)
END

--委托代销结算单
IF CHARINDEX('141',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN CommissionBill B ON I.BillType=141 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--组合品销售出库单
IF CHARINDEX('12',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN  PT_Combin_SaleBillDetail B ON I.BillType=12 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--组合品销售退货单
IF CHARINDEX('46',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN PT_Combin_SaleBackBillDetail B ON I.BillType=46 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

SET @SQL='
INSERT INTO #SaleBill
(
	PTypeId,
	AreaTypeID,
	Qty,
	NQty,
	TaxTotal
)
SELECT 
	PtypeId,
	AreaTypeID,
	SUM(ISNULL(F.Qty,0)) Qty,
	SUM(ISNULL(F.NQty,0)) NQty,
	SUM(ISNULL(F.TaxTotal,0)) TaxTotal
 FROM 
('+SUBSTRING(@SQL,10,LEN(@SQL))+'
)F
GROUP BY F.PTypeId,F.AreaTypeID
'
EXEC(@SQL)

--生成分布表
SET @SQL = '
SELECT
	P.typeid,
	P.SonNum 父节点,
	p.AssistUnitFullName 浮动单位,
	SUM(ISNULL(B.Qty,0)) 总计数量,
	SUM(ISNULL(B.NQty,0)) 总计浮动数量,
	SUM(ISNULL(B.TaxTotal,0)) 总计金额'

IF @bCount='10'
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+FullName+'数量]
						,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+FullName+'浮动数量]
						,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+FullName+'金额]'  
	FROM #PageAreaType ORDER BY UserCode   
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+FullName+'数量]
						,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+FullName+'浮动数量]
						,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+FullName+'金额]'  
	FROM #AreaType ORDER BY UserCode    
END 
SET @SQL+='
FROM #ParidPtype P
LEFT JOIN #SaleBill B ON B.PTypeId LIKE P.TypeID+''%'''  

SET @SQL+='
GROUP BY
	P.RowId,
	P.TypeID,
	P.SonNum,
	p.AssistUnitFullName
ORDER BY'

IF ISNULL(@sort,'')=''
	SET @SQL+='	p.RowId'   
	 
IF ISNULL(@sort,'')='0'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.Qty,0)) desc '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.Qty,0))'  
  END				
IF ISNULL(@sort,'')='1'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.NQty,0)) desc '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.NQty,0))'  
  END
IF	ISNULL(@sort,'')='2'
  BEGIN
	IF @ck!=1
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0)) desc '    
    ELSE
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0))'  
  END
				
EXEC(@SQL)
--=============================业务处理【END】=======================================



--=============================删除临时表【BEGIN】=====================================

DROP TABLE #AreaType,#Btype,#Dtype,#Etype,#Ktype,#Ptype,#Stype,#BillIndex,#PageAreaType,#SaleBill,#ParidPtype

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_AreaSaleDistLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_AreaSaleDistLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-06-25
function:地区销售分布线性表
*/
CREATE PROCEDURE Web_AreaSaleDistLine
(
	@OperatorId		VARCHAR(50),		--操作员Id
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--结束日期
	@StypeId        VARCHAR(MAX),		--分支机构Id
	@PtypeCategoryId VARCHAR(MAX),		--商品类别ID
	@PTypeId		VARCHAR(MAX),		--商品Id
	@AreaTypeId		VARCHAR(MAX),		--职员Id
	@nType			VARCHAR(10),		--金额的查询方式
	@BillType		VARCHAR(100),		--单据类型
	@ShowZero		VARCHAR(5),			--0.不显示红冲单据   1.显示红冲单据
	@CheckZero		BIT,				--0不显示为0的数据，1显示所有
	@UnitConvert	INT,				--单位
	@Sort		    NVARCHAR(200),		--排序
	@Ck				INT,				--1：升序 0降序
	
	@BCount			INT=10,				--基本信息的默认个数
	@BPageNo		INT=0				--基本信息的页数
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN --------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE 
	@Re INT,
	@MAtypeid VARCHAR(50), 
	@MBtypeid VARCHAR(50), 
	@MBtypeid2 VARCHAR(50), 
	@MEtypeid VARCHAR(50),
	@MKtypeid VARCHAR(50), 
	@MPtypeid VARCHAR(50), 
	@MExpense VARCHAR(50), 
	@MIncome VARCHAR(50),
	@MCapital VARCHAR(50),
	@MDtypeid VARCHAR(50),
	@MStypeid VARCHAR(50)
	
EXEC @Re=GP_CheckOperatorRight23_Rep 
		@OperatorID,
		@MAtypeid OUTPUT,
		@MBtypeid OUTPUT,
		@MBtypeid2 OUTPUT,
		@MEtypeid OUTPUT,
		@MKtypeid OUTPUT,
		@MPtypeid OUTPUT,
		@MExpense OUTPUT,
		@MIncome OUTPUT,
		@MCapital OUTPUT,
		@MDtypeid OUTPUT,
		@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------
END;
	
DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================

--根据单位获取相关值
DECLARE
	@TempColumn			VARCHAR(50),
	@TempQty			VARCHAR(1000)='',
	@TempTable			VARCHAR(1000)=''
	
--销售单位		
IF @UnitConvert=0
	BEGIN
		SET @TempColumn='SaleUnitId'
		SET @TempTable='
		LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.SaleUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
		
	END
--采购单位
ELSE IF @UnitConvert=1
	BEGIN
		SET @TempColumn='BuyUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.BuyUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--存货单位
ELSE IF @UnitConvert=2
	BEGIN
		SET @TempColumn='StockUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.StockUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--基本单位
ELSE IF @UnitConvert=3
	BEGIN
		SET @TempColumn='baseUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.baseUnitId = R.UnitsId'
		SET @TempQty='B.Qty'
	END

--商品
IF(ISNULL(@PTypeId,'')='')
	SET @PTypeId='00000'

--实际查询商品
CREATE TABLE #Ptype(
	RowId				INT,
	TypeID				VARCHAR(50),
	SonNum				INT,
	UserCode			VARCHAR(200),
	AssistUnitFullName	VARCHAR(200),
	UnitFullName		VARCHAR(200),
	Rate				NUMERIC(24,10)
) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)

DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,@PTypeId,@PtypeCategoryId)

SET @SQL+='
INSERT INTO #Ptype(RowId,TypeID,SonNum,UserCode,AssistUnitFullName,UnitFullName,Rate)
SELECT
	ROW_NUMBER()OVER(ORDER BY P.UserCode) RowId,
	P.typeId,
	P.sonnum,
	P.UserCode,
	E.FullName AssistUnitFullName,
	PU.FullName UnitFullName,
	R.Rate
 '+@LinkStr+'
 LEFT JOIN PType_Units E ON P.AssistantUnitId=E.UnitsId
 '+@TempTable+'
 LEFT JOIN PType_Units PU ON PU.UnitsId=P.'+@TempColumn+'
 WHERE
	P.sonnum=0
	AND P.iscombinationproduct=0'

EXEC(@SQL)

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	BEGIN
		INSERT INTO #Stype(typeid) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
	END

--部门
CREATE TABLE #Dtype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
IF (@MDtypeid='-99999')
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetManDetailDType(@OperatorId)
	END

--往来单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetManDetailBType(@OperatorId)
	END

--职员
CREATE TABLE #Etype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF (@MEtypeid='-99999')
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetManDetailEType(@OperatorId)
	END

--仓库
CREATE TABLE #Ktype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeId)
IF (@MKtypeid='-99999')
	BEGIN
		INSERT INTO #Ktype(TypeID)
		SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
		UNION ALL
		SELECT '10000' TypeId
	END

--所有地区
CREATE TABLE #AreaType(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Areatype_P_K ON #Areatype(TypeId)
IF(@AreaTypeId='')
	BEGIN
		INSERT INTO #AreaType(RowId,TypeID,UserCode,FullName)
		SELECT
			ROW_NUMBER()OVER(ORDER BY UserCode) RowId,
			typeId,
			UserCode,
			FullName
		FROM( 
			SELECT 
				typeId,
				UserCode,
				FullName
			FROM AreaType WHERE sonnum=0 AND typeId<>'00000'
			UNION ALL
			SELECT '9999' typeId, '其他地区' UserCode, '其他地区' FullName
		) F
		ORDER BY UserCode
	END
ELSE 
	BEGIN
		INSERT INTO #AreaType(RowId,TypeID,UserCode,FullName)
		SELECT 
			ROW_NUMBER()OVER(ORDER BY D.usercode) RowId,
			D.TypeId,
			D.usercode,
			D.FullName
		FROM AreaType D
		INNER JOIN f_split(@AreaTypeId,',') F ON D.sonnum=0 AND D.typeId<>'00000' AND F.a=LEFT(D.typeid,LEN(F.A))
		ORDER BY usercode
	END

--当前页地区
CREATE TABLE #PageAreaType(TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #PageAreaType(TypeID,UserCode,FullName)
SELECT 
	typeid,
	UserCode,
	FullName 
FROM #Areatype
WHERE RowId BETWEEN (@bPageNo-1)*@bCount+1 AND @bPageNo*@bCount
--=============================基本信息权限范围获取【END】=======================================


--=============================业务处理【BEGIN】=====================================
SET @SQL=''

--BillIndex
CREATE TABLE #BillIndex
(
	BillNumberId 	NUMERIC(18,0),
	AreaTypeID		VARCHAR(50),
	BillType		INT	
) 
CREATE CLUSTERED INDEX #BillIndex_P_K ON #BillIndex(BillNumberId)

SET @SQL='
INSERT INTO #BillIndex
(
	BillNumberId,
	AreaTypeID,
	BillType
)
SELECT	
	B.BillNumberId,
	CASE WHEN ISNULL(BT.AreaTypeID,'''')='''' THEN ''9999'' ELSE BT.AreaTypeID END AreaTypeID,
	B.BillType
FROM BillIndex B
INNER JOIN btype BT ON BT.TypeID=B.DealBTypeID AND B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' AND B.BillType IN ('+@BillType+') AND B.RedWord=0 AND B.IfCheck=''t'' AND B.Draft=0 AND B.ifYearBill=0' +CHAR(13)	

--分支机构
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	SET @SQL+='INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid'+CHAR(13)	
	
--部门
IF(@MDtypeid='-99999')
	SET @SQL+='INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId '+CHAR(13)	
	
--往来单位
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		SET @SQL+='INNER JOIN #Btype B_B ON B_B.TypeID=B.BTypeID'+CHAR(13)
		SET @SQL+='INNER JOIN #Btype B_B1 ON B_B1.TypeID=B.DealBTypeID'+CHAR(13)
	END

--职员		
IF (@MEtypeid='-99999')
	SET @SQL+='INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid'+CHAR(13)
	
EXEC(@SQL)
SET @SQL=''


--数据明细表
CREATE TABLE #SaleBill
(
	PTypeId		VARCHAR(50),
	AreaTypeID	VARCHAR(50),
	Qty			NUMERIC(24,10),
	NQty        NUMERIC(24,10),
	TaxTotal	NUMERIC(24,10) 
)
CREATE CLUSTERED INDEX #SaleBill_P_K ON #SaleBill(PTypeId)

--零售单
IF CHARINDEX('305',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN retailBill B ON I.BillType=305 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--零售退货单
IF CHARINDEX('215',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN RetailBackBill B ON I.BillType=215 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
	
END

--销售出库单
IF CHARINDEX('11',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN SaleBill B ON I.BillType=11 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--销售退货单
IF CHARINDEX('45',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN saleBackBill B ON I.BillType=45 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--销售换货单
IF CHARINDEX('160',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		CASE WHEN B.InOrOut = ''o'' THEN SUM('+@TempQty+') ELSE -SUM('+@TempQty+') END Qty,
		CASE WHEN B.InOrOut = ''o'' THEN SUM(B.NQty) ELSE -SUM(B.NQty) END NQty,
		CASE WHEN B.InOrOut = ''o'' THEN CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END
			 ELSE CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END
		END TaxTotal 
	FROM #BillIndex I
	INNER JOIN SaleGoodsExchangeBill B ON I.BillType=160 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='WHERE 
		B.InOrOut=''i'' 
		OR B.InOrOut=''o''  
	GROUP BY B.PTypeId,I.AreaTypeID,B.InOrOut'+CHAR(13)
END

--委托代销结算单
IF CHARINDEX('141',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN CommissionBill B ON I.BillType=141 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--组合品销售出库单
IF CHARINDEX('12',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBillDetail B ON I.BillType=12 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

--组合品销售退货单
IF CHARINDEX('46',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.AreaTypeID,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBackBillDetail B ON I.BillType=46 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.AreaTypeID'+CHAR(13)
END

SET @SQL='
INSERT INTO #SaleBill
(
	PTypeId,
	AreaTypeID,
	Qty,
	NQty,
	TaxTotal
)
SELECT 
	PtypeId,
	AreaTypeID,
	SUM(ISNULL(F.Qty,0)) Qty,
	SUM(ISNULL(F.NQty,0)) NQty,
	SUM(ISNULL(F.TaxTotal,0)) TaxTotal
 FROM 
('+SUBSTRING(@SQL,10,LEN(@SQL))+'
)F
INNER JOIN #AreaType T ON T.TypeID=F.AreaTypeID
GROUP BY F.PTypeId,F.AreaTypeID
'
EXEC(@SQL)

--生成分布表
SET @SQL = '
SELECT
	P.typeid,
	P.SonNum,
	P.AssistUnitFullName 浮动单位,
	P.UnitFullName 计量单位,
	SUM(ISNULL(B.Qty,0)) 总计数量,
	SUM(ISNULL(B.NQty,0)) 总计浮动数量,
	SUM(ISNULL(B.TaxTotal,0)) 总计金额'

IF @bCount='10'
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+FullName+'数量]
						,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+FullName+'浮动数量]
						,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+FullName+'金额]'  
	FROM #PageAreaType ORDER BY UserCode 
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+FullName+'数量]
						,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+FullName+'浮动数量]
						,SUM(CASE WHEN B.AreaTypeID = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+FullName+'金额]'  
	FROM #AreaType ORDER BY UserCode 
END 
SET @SQL+='
FROM #Ptype P
LEFT JOIN #SaleBill B ON B.PTypeId=P.TypeID'+CHAR(13) 

--是否显示销售为0的数据
IF(ISNULL(@CheckZero,0)=0)
	SET @SQL+='INNER JOIN (SELECT SUM(ISNULL(Qty,0)) Qty,PTypeId FROM #SaleBill GROUP BY PTypeId) FS ON FS.Qty<>0 AND FS.PTypeId=P.TypeID'+CHAR(13)

SET @SQL+='
GROUP BY
	P.RowId,
	P.TypeID,
	P.SonNum,
	P.AssistUnitFullName,
	P.UnitFullName
ORDER BY'

IF ISNULL(@sort,'')=''
	SET @SQL+='	p.RowId'   
	 
IF ISNULL(@sort,'')='0'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.Qty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.Qty,0))'  
  END				
IF ISNULL(@sort,'')='1'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.NQty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.NQty,0))'  
  END
IF	ISNULL(@sort,'')='2'
  BEGIN
	IF @ck!=1
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0)) DESC '    
    ELSE
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0))'  
  END
				
EXEC(@SQL)

--=============================业务处理【END】=======================================



--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#Dtype,#Etype,#Ktype,#Ptype,#Stype,#BillIndex,#PageAreaType,#SaleBill,#AreaType

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_AssetsChangeCheck]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_AssetsChangeCheck]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013-05-16
	描述：项目管理切换至卡片管理，检查数据
*/
CREATE PROCEDURE Web_AssetsChangeCheck

--@encode$--
AS 
SET NOCOUNT ON

--校验固定资产单据都已生成凭证
IF EXISTS ( SELECT TOP 1 1
            FROM    dbo.BillIndex
            WHERE   BillNumberId NOT IN (
                    SELECT  GoodsBillId
                    FROM    dbo.Ac_GoodsBill_VoucherBill )
                    AND BillType IN ( 84, 85, 78 )
                    AND IsIni = 0 
                    AND RedWord = 0) 
BEGIN
    SELECT '尚有资产购买单、折旧单、变卖单未生成凭证或存在草稿，不能进行切换'
    RETURN -1
END

DECLARE @fperiod INT--分支机构

--校验项目与科目，固定资产金额一致
DECLARE @STypeId VARCHAR(50),@SFullName VARCHAR(100),@msg VARCHAR(MAX)
DECLARE @ItemTotal  NUMERIC(24, 10) ,@ATypeTotal  NUMERIC(24, 10) ,@DepATypeTotal  NUMERIC(24, 10) 

DECLARE CheckCur CURSOR READ_ONLY FOR
	SELECT TypeId,FullName
	FROM dbo.SType WHERE IsSelfVerify = 1 AND sonnum = 0
OPEN CheckCur

FETCH NEXT FROM CheckCur INTO @STypeId,@SFullName

WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT @fperiod=FPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	
	SET @msg = ''
	
	SELECT @ItemTotal = SUM(T1.Total)
	FROM dbo.AType_Total T1
		INNER JOIN dbo.Ac_Items T2 ON T1.ATypeID = T2.nId AND T2.TypeName = 'F'
	WHERE T1.STypeID IN (SELECT TypeId FROM dbo.SType WHERE VerifyID = @STypeId)
	
	
	SELECT *
	INTO #TmpBalance
	FROM
	(
	SELECT DISTINCT ISNULL(T3.UserCode,'') AS Ausercode,ISNULL(T4.FEndBalance,0) AS ATotal,'' DuserCode,0 DTotal
	FROM dbo.Ac_Items T1
		LEFT JOIN dbo.Ac_Items_Detail T2 ON T1.nId = T2.nId AND T2.STypeId = @stypeid
		LEFT JOIN dbo.Ac_Account T3 ON T2.ATypeId = T3.TypeId AND T2.STypeId = T3.StypeId
		LEFT JOIN dbo.Ac_Balance T4 ON T3.TypeId = T4.ATypeId AND T3.StypeId = T4.STypeId AND T4.Cid = 0 AND T4.FPeriod = @fperiod
	WHERE T1.TypeName = 'F' AND T1.SonNum = 0
	UNION ALL
	SELECT DISTINCT '' Ausercode,0 ATotal,ISNULL(T3_D.UserCode,'') AS DuserCode,ISNULL(T4_D.FEndBalance,0) AS DTotal
	FROM dbo.Ac_Items T1
		LEFT JOIN dbo.Ac_Items_Detail T2 ON T1.nId = T2.nId AND T2.STypeId = @stypeid
		LEFT JOIN dbo.Ac_Account T3_D ON T2.DepATypeId = T3_D.TypeId AND T2.STypeId = T3_D.StypeId
		LEFT JOIN dbo.Ac_Balance T4_D ON T3_D.TypeId = T4_D.ATypeId AND T3_D.StypeId = T4_D.STypeId AND T4_D.Cid = 0 AND T4_D.FPeriod = @fperiod
	WHERE T1.TypeName = 'F' AND T1.SonNum = 0
	)T
	WHERE T.AuserCode <> '' OR T.DuserCode <> ''
	
	SELECT @ATypeTotal=SUM(ATotal),@DepATypeTotal=SUM(DTotal)
	FROM #TmpBalance
	
	
	--弹出异常
	IF @ItemTotal <> (@ATypeTotal - @DepATypeTotal)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		SET @msg = '分支机构['+@sfullname+']'
		SELECT  @msg+ '项目固定资产总余额与财务固定资产总余额不一致，请调整后重试' AS info,
				@SFullName AS SFullName,@ItemTotal AS ItemTotal,@ATypeTotal AS ATypeTotal,@DepATypeTotal AS DepATypeTotal
		SELECT DISTINCT Ausercode,ATotal FROM #TmpBalance WHERE ISNULL(Ausercode,'') <> '' 
		SELECT DISTINCT DuserCode,DTotal FROM #TmpBalance WHERE ISNULL(Dusercode,'') <> ''
		
		CLOSE CheckCur
		DEALLOCATE CheckCur
		DROP TABLE #TmpBalance
		RETURN -1
	END
	
	DROP TABLE #TmpBalance
	FETCH NEXT FROM CheckCur INTO @STypeId,@SFullName
END

CLOSE CheckCur
DEALLOCATE CheckCur
IF (SELECT COUNT(*) FROM dbo.Ac_Period T1 WHERE FYear = (SELECT SubValue FROM dbo.sysdata WHERE SubName='fyear')) >= 12
	SELECT ''
ELSE
	SELECT '会计期间数小于12，不能使用卡片管理'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AssetsInitDataNoAcCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AssetsInitDataNoAcCheck]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.04.10
	描述：非总账下，固定资产初始化检测数据值
*/
CREATE PROCEDURE Web_AssetsInitDataNoAcCheck
(
	@stypeid	VARCHAR(50)--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @NetValueTotal	 NUMERIC(24, 10) ,
		@ATypeTotal		 NUMERIC(24, 10) ,
		@sfullname		VARCHAR(100)

--初始卡片净值总计
SELECT @NetValueTotal=ISNULL(SUM(ISNULL(NetValue,0)),0)
FROM dbo.AC_AssetsCards

--固定资产项目总计
SELECT @ATypeTotal = SUM(Total) 
FROM dbo.Ac_Items T1
	INNER JOIN dbo.AType_Total T2 ON T1.nId = T2.ATypeID
WHERE nTypeId LIKE '0000100002%' AND T2.STypeID = @stypeid

--分支机构名称
SELECT @sfullname = FullName FROM dbo.SType WHERE TypeId = @stypeid

SELECT @sfullname AS sfullname,ISNULL(@NetValueTotal,0) AS assetstotal,ISNULL(@ATypeTotal,0) AS atypetotal

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'WEB_AtypeAssistCheckItems')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE WEB_AtypeAssistCheckItems;
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





/*
	Created	:	喻堂
	Date	:	2012/05/08
	Description	: 获取会计科目的辅助核算项目
*/



CREATE PROCEDURE WEB_AtypeAssistCheckItems
(
	@STypeID	VARCHAR(50),	--分支机构
	@ATypeID	VARCHAR(50),	--类型ID
	@IsUsed		BIT				--是否已经使用
)
--@encode$--
AS 
IF(@IsUsed=1)
	BEGIN
		SELECT 
			I.AscIds Typeid,
			I.UserCode,
			I.FullName
		FROM Ac_Account_Assist_CheckItems AC
		INNER JOIN Ac_Assist_CheckItems I ON I.AscIds=AC.Ascids AND AC.STypeId=@STypeID AND AC.ATypeId=@ATypeID
		GROUP BY 
			I.AscIds,
			I.UserCode,
			I.FullName
		ORDER BY I.AscIds
	END
ELSE 
	BEGIN
		DECLARE @I INT=0
		DECLARE @Temp TABLE(Typeid VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(50))
		INSERT INTO @Temp(Typeid,UserCode,FullName)
		SELECT 
			I.AscIds Typeid,
			I.UserCode,
			I.FullName
		FROM Ac_Account_Assist_CheckItems AC
		INNER JOIN Ac_Assist_CheckItems I ON I.AscIds=AC.Ascids AND AC.STypeId=@STypeID AND AC.ATypeId=@ATypeID
		GROUP BY 
			I.AscIds,
			I.UserCode,
			I.FullName
		ORDER BY I.AscIds
		
		SELECT @I=@@ROWCOUNT
		
		WHILE (@I<6)
			BEGIN
				INSERT INTO @Temp(Typeid,UserCode,FullName)
				SELECT 
					'' Typeid,
					'' UserCode,
					'' FullName
				SET @I+=1
			END
		SELECT * FROM @Temp
	END
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AtypeBillDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AtypeBillDetailQuery]
GO





/*
------------------------------------------
修改:Wang Wei 
时间:2010-7-2
标识:#1
描述:将职员的权限放开


修改：毛欣蓉
时间：2010-7-15
标志：#2
描述：修改为结果集中只读取需要字段加快访问速度并做简单的优化

修改：徐辉
时间：2011-3-15
标志：#3
描述：添加了分支机构，取期初改动
*/

CREATE             PROCEDURE Web_AtypeBillDetailQuery
(
	@ATypeID 		VARCHAR(50),	--指定要查询的节点ID
	@StypeID		VARCHAR(MAX),	--分支机构
	@StartDate		VARCHAR(30),	--时间范围下限
	@EndDate    	VARCHAR(30),	--时间范围上限
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@Flag 			varchar(10)='',
	@OrderBy		VARCHAR(50),	--排序类型
	@total           NUMERIC(24, 10)  output  --当前科目期初
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorId is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
exec @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL 	VARCHAR(max)	--用于保存动态SQL语句的变量

IF @AtypeID='00000'
	SET @AtypeID=''

--判断资产负债表的权限 
DECLARE @Lim INT --1:没有权限 0有权限
EXEC @Lim = GP_CheckLimit @OperatorID,4226

CREATE TABLE #Item(NId INT,NTypeID VARCHAR(50))
INSERT INTO #Item(NId,NTypeID)
SELECT nId,nTypeId FROM Ac_Items 
WHERE 
	nTypeId LIKE @ATypeID+'%'
	AND (@Lim=0 OR (@Lim=1 AND nTypeId IN(
						SELECT nTypeId FROM F_AllTreeAssetsT(@OperatorID)--资产合计(固定资产+银行账户+管辖其他资产)
						UNION ALL
						SELECT nTypeId FROM F_AllTreeInDebtT(@OperatorID)--负债合计（管辖负债+账户里面的预收）
						UNION ALL
						SELECT nTypeId FROM F_AllTreeOwnerEquityT(@OperatorID)--所有者权益
						UNION ALL
						SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
						UNION ALL
						SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出）
						)
					)
		)

CREATE TABLE #Stype (TypeID varchar(50))
IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a

DECLARE @TotalOut  NUMERIC(24, 10) 
SET @TotalOut = 0

SELECT @TotalOut=@TotalOut+ISNULL(sum(a.Total00),0)  
FROM 
(
	SELECT ISNULL(w.atypeid,v.atypeid) AS atypeid,ISNULL(w.stypeid,v.stypeid) AS stypeid,ISNULL(v.InnerARTotal00,w.total00) AS total00,w.Total,ISNULL(w.cid,1) AS cid
		,ISNULL(v.InnerARTotal00,w.Ntotal00) AS Ntotal00,w.Ntotal FROM atype_total w 
		full JOIN (SELECT 28 as AtypeId,stypeid,SUM(InnerARTotal00) AS InnerARTotal00 FROM dbo.SType_InnerARTotal GROUP BY stypeid) v 
		ON w.STypeID=v.stypeid AND w.ATypeID=28 
) a
INNER JOIN #Item AC ON a.AtypeID=AC.nid
INNER JOIN #Stype S ON S.TypeID=A.stypeid

IF @StartDate<>''
BEGIN
	SELECT @TotalOut=@TotalOut+ISNULL(SUM(lt.total),0)
	FROM listtable lt 
	INNER JOIN 
	(
		SELECT billtype,billdate,billnumberid,ifyearbill,RedWord from dbo.billindex
		UNION
		SELECT 311,     billdate,billnumberid,0 ,RedWord         from dbo.CommissionBillNew --提成单
		UNION 
		SELECT BillType,BillDate,BillNumberID,ifYearBill,RedWord FROM dbo.ReceiptBillIndex --销售开票、采购开票
		UNION 
		SELECT BillType,BillDate,BillNumberID,ifYearBill,RedWord FROM dbo.Coupon_BillIndex --优惠券
		UNION 
		SELECT BillType,BillDate,BillNumberID,ifYearBill,RedWord FROM dbo.PosAllotApplyBillIndex --门店类单据
	) i on(lt.BillNumberID=i.BillNumberID AND lt.BillType=i.billtype) 	
	INNER JOIN #Item AC ON lt.Atypeid=AC.nid	
	INNER JOIN #Stype S ON S.TypeID=lt.STypeID
	where  
		i.billdate < @StartDate
		AND lt.Audited = 1
		AND i.ifYearBill=0	 --年节存标志
		AND i.RedWord=0
END

SET @total=@totalOut

IF @Flag='00' -- 只得到科目余额
BEGIN
	DROP TABLE #Stype
	RETURN 0
END

DECLARE @usercod VARCHAR(50)='', @sqlCond VARCHAR(max)=''
SELECT @usercod= usercode FROM dbo.Ac_Items WHERE nTypeId=@atypeid
IF(@usercod IN ('044599','221199'))--业务提成、员工提成
BEGIN
	SET @sqlCond='  LEFT Join 
		  (
			SELECT billtype,billdate,billnumberid,stypeid,comment,etypeid,billcode,posttime,ifyearbill,
			ktypeid,ktypeid2,btypeid,DealBTypeID,DTypeId,explain,RedWord from billindex
			UNION
			SELECT 311,billdate,billnumberid,stypeid,comment,'''' AS etypeid,billcode,PostTime,0,'''' AS ktypeid,
			'''' AS ktypeid2,'''' AS btypeid,'''' AS DealBTypeID,'''' AS DTypeId,explain,RedWord from dbo.CommissionBillNew
			UNION 
			SELECT BillType,BillDate,BillNumberID,stypeid,comment,etypeid,billcode,posttime,ifYearBill,'''' AS ktypeid,
			'''' AS ktypeid2,btypeid,DealBTypeID,DTypeId,explain,RedWord FROM dbo.Coupon_BillIndex --优惠券
			UNION
			SELECT billtype,billdate,billnumberid,stypeid,comment,ApplyEtypeId etypeid,billcode,posttime,ifyearbill,
			ktypeid,Inktypeid as ktypeid2,'''' as btypeid,'''' AS DealBTypeID,DTypeId,explain,RedWord from PosAllotApplyBillIndex --门店类单据
		  ) i on(lt.BillNumberID=i.BillNumberID AND lt.BillType=i.billtype)  '
END
ELSE
BEGIN
	--SET @sqlCond=' LEFT Join billindex i on(lt.BillNumberID=i.BillNumberID)  '
	SET @sqlCond=' LEFT Join 
					(
						SELECT BillType,BillDate,BillNumberID,stypeid,comment,etypeid,Checke,billcode,PostTime,ifYearBill,
						ktypeid,ktypeid2,btypeid,DealBTypeID,DTypeId,explain,RedWord FROM billindex 
						UNION 
						SELECT BillType,BillDate,BillNumberID,stypeid,comment,etypeid,Checke,billcode,PostTime,ifYearBill,
						'''' AS ktypeid,'''' AS ktypeid2,btypeid,DealBTypeID,DTypeId,explain,RedWord FROM dbo.ReceiptBillIndex --销售开票、采购开票
						UNION 
						SELECT BillType,BillDate,BillNumberID,stypeid,comment,etypeid,Checker,billcode,PostTime,ifYearBill,
						outktypeid AS ktypeid,inktypeid AS ktypeid2,btypeid,DealBTypeID,DTypeId,explain,RedWord FROM dbo.Coupon_BillIndex --优惠券
						UNION
						SELECT BillType,BillDate,BillNumberID,stypeid,comment,ApplyEtypeId etypeid,Checke,billcode,CheckerTime,
						ifYearBill,ktypeid,inktypeid  as ktypeid2,'''','''',DTypeId,explain,RedWord FROM dbo.PosAllotApplyBillIndex 	--门店				
					) i on(lt.BillNumberID=i.BillNumberID AND lt.BillType=i.billtype)  '
END

/*
166	维修单
167	维修取件单
168	整机更换单
169	送修单
170	送修返回单
171	报修单
172	上门维修单
173	维修品调入单
174	维修品调出单
175	维修品调拨单
*/

SET @SQL ='
		  SELECT	jetotal=0.00,
					lt.total AS ltTotal,
					i.billdate,
					i.billcode,
					i.stypeid,
					i.billtype,
					i.comment,
					i.etypeid,
					i.billnumberid,
					CASE
						when i.billtype in (160) then i.ktypeid2
						WHEN i.billtype in (305,11,215,139,140,141,12,6,161,146,17,21,187,188,202,9,16,
						183,401,402,166,168,172,173,175,428,429,329,327,328) then i.ktypeid
						ELSE ''''
					END as ktypeid,
					CASE
						when i.billtype in (34,45,142,46,144,145,201,14,160,400,403) then i.ktypeid
						WHEN i.billtype in (161,17,21,16,174,188,187,428,429,329,327,328) then i.ktypeid2
						ELSE ''''
					END AS ktypeid2,
					i.btypeid,
					i.dealbtypeid,
					i.dTypeId,
					i.explain
		  FROM		listtable lt
		  INNER JOIN #Item AC ON lt.AtypeID=AC.nid
			INNER JOIN #Stype S ON S.TypeID=lt.STypeID
		   ' +@sqlCond+'  
		  WHERE 
				lt.audited =1'                            --# 将#Etype替换成 Employee

if @StartDate<>'' 
BEGIN
	SET @SQL = @SQL +' AND i.billdate>='''+@startDate+''''
END
if @EndDate<>'' 
BEGIN
	SET @SQL = @SQL +' AND i.billdate<='''+@EndDate+''''
END

SET @Sql=@Sql + ' AND i.ifYearBill= 0 AND i.RedWord = 0 '    --年节存标志



-- 排序
DECLARE @SQL_ORDER VARCHAR(200)
IF RTRIM(ISNULL(@OrderBy,''))=''
	SELECT @SQL_ORDER = ' Order By  i.Billdate asc,i.posttime asc '
IF @OrderBy ='ByDate_a'
	SELECT @SQL_ORDER = ' Order By i.Billdate asc,i.posttime asc '
IF @OrderBy ='ByDate_d'
	SELECT @SQL_ORDER = ' Order By i.Billdate desc ,i.posttime desc'
IF @OrderBy ='ByBillNo_a'
	SELECT @SQL_ORDER = ' Order By i.BillCode asc ,i.posttime asc '
IF @OrderBy ='ByBillNo_d'
	SELECT @SQL_ORDER = ' Order By i.BillCode desc ,i.posttime desc'
IF @OrderBy ='ByBillID_a'
	SELECT @SQL_ORDER = ' Order By i.posttime asc '
IF @OrderBy ='ByBillID_d'
	SELECT @SQL_ORDER = ' Order By i.posttime desc ' 

SET @SQL = @SQL +@SQL_ORDER
--PRINT @SQL
EXEC(@SQL)

DROP TABLE #SType,#Item

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AtypeDepartBillDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AtypeDepartBillDetailQuery]
GO


CREATE      PROCEDURE Web_AtypeDepartBillDetailQuery
(
  @ATypeID		VARCHAR(50),	--指定要查询的节点ID
  @DTypeID		VARCHAR(MAX),	--指定部门ID
  @STypeID		VARCHAR(MAX),	--分支机构
  @StartDate	VARCHAR(30),	--时间范围下限
  @EndDate		VARCHAR(30),	--时间范围上限
  @OperatorID	VARCHAR(50),	--操作员ID号
  @Flag			VARCHAR(10) = '',
  @total		 NUMERIC(24, 2)  OUTPUT  --当前科目期初
)
--@encode$--
AS 
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID, '') = '' 
    RETURN 1
DECLARE @Re INT,
    @MAtypeid VARCHAR(50),
    @MBtypeid VARCHAR(50),
    @MBtypeid2 VARCHAR(50),
    @MEtypeid VARCHAR(50),
    @MKtypeid VARCHAR(50),
    @MPtypeid VARCHAR(50),
    @MExpense VARCHAR(50),
    @MIncome VARCHAR(50),
    @MCapital varchar(50),
    @MDtypeid varchar(50),
    @MStypeid varchar(50)
EXEC @Re= GP_CheckOperatorRight23_rep @OperatorID, @MAtypeid OUTPUT, @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT, @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,@MCapital OUTPUT, @MDtypeid OUTPUT,
    @MStypeid OUTPUT
IF @Re <> 0 
    RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Stype (TypeID varchar(50))

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a
	
CREATE TABLE #Dtype (TypeID varchar(50))

IF @DTypeID=''
	INSERT INTO #Dtype(typeid)  select typeid from F_BaseGetManDetailDType(@OperatorID)
ELSE
	INSERT INTO #Dtype(typeid)  select a.typeid from F_BaseGetManDetailDType(@OperatorID) a, (select * from  dbo.f_split(@DtypeID,',')) b where left(a.typeid,len(b.a))=b.a


DECLARE @SQL VARCHAR(6000)	--用于保存动态SQL语句的变量
IF @AtypeID = '00000' 
    SET @AtypeID = ''
--IF @ATypeID<>''
--	SELECT @ATypeID=ntypeid FROM ac_items  WHERE nid=@atypeid
SET @AtypeID = @AtypeID + '%'

--管辖费用、管辖其他收入

CREATE TABLE #ntypeid (ntypeid VARCHAR(50));

INSERT INTO #ntypeid
SELECT nTypeId FROM dbo.Ac_Items WHERE ntypeid LIKE @ATypeID 
AND (nid IN (SELECT nid FROM dbo.F_TreeIncomeC(@OperatorID))
OR nid IN (SELECT nid FROM dbo.F_TreeExpenseC(@OperatorID)) );


DECLARE @TotalOut  NUMERIC(24, 10) 
SET @TotalOut = 0


--****9.6需求修改 杨俊2015-04-16，因为这改动有点大还是保留原代码****
--3.15.2、职员部门费用表及部门收支表统计提成单 ,关联9.4BUG:4395
--IF @DTypeID = 'DDDDD' 
--    SELECT  @TotalOut = ISNULL(SUM(lt.total), 0)
--    FROM    listtable lt
--            INNER	JOIN billindex i ON ( lt.BillNumberID = i.BillNumberID )
--            LEFT JOIN dbo.Ac_Items ac ON ac.nId=lt.atypeid
--    WHERE   --ac.ntypeid LIKE @ATypeID
--			ac.ntypeid IN (SELECT nTypeId FROM #ntypeid)
--            AND i.billdate < @StartDate
--            AND lt.DtypeId = ''
--            AND lt.Audited = 1
--            AND	lt.StypeId IN(SELECT typeid FROM #Stype)
--            AND i.ifYearBill=0	 --年节存标志
--ELSE 
--    BEGIN
--        SET @DTypeID = @DTypeID + '%'
--        SELECT  @TotalOut = ISNULL(SUM(lt.total), 0)
--        FROM    listtable lt
--                INNER	JOIN billindex i ON ( lt.BillNumberID = i.BillNumberID )
--                LEFT JOIN dbo.Ac_Items ac ON ac.nId=lt.atypeid
--        WHERE  --ac.ntypeid LIKE @ATypeID
--				ac.ntypeid IN (SELECT nTypeId FROM #ntypeid)
--                AND i.billdate < @StartDate
--                AND lt.DTypeID IN (SELECT typeid FROM #Dtype)
--                AND lt.Audited = 1
--                AND	lt.StypeId IN(SELECT typeid FROM #Stype)
--                AND i.ifYearBill=0	 --年节存标志
--    END

--SET @total = @totalOut
--IF @Flag = '00' -- 只得到科目余额
--BEGIN
--	DROP TABLE #Dtype,#Stype
--    RETURN 0
--END


--SET @SQL = 'SELECT 
--				0.00 as jetotal,lt.total AS ltTotal,i.billdate,i.billcode,i.comment,lt .etypeid,lt.stypeid,lt.billtype,lt.BillNumberID
--			FROM 
--				listtable lt  
--			LEFT Join billindex i on(lt.BillNumberID=i.BillNumberID)  
--			LEFT JOIN dbo.Ac_Items ac ON ac.nId=lt.atypeid
--			where
--				--lt.atypeid = ''' + @atypeid + '''
--				--ac.ntypeid LIKE '''+@ATypeID+'''
--				ac.ntypeid in (select ntypeid from #ntypeid)
--	    		AND lt.audited =1  
--	    		AND	lt.StypeId IN(SELECT typeid FROM #Stype)'

--IF @DTypeID ='DDDDD' 
--	SET @SQL = @SQL +' AND lt.Dtypeid ='+char(39)+''+char(39)
--ELSE
--	SET @SQL = @SQL +' AND lt.DTypeID IN (SELECT typeid FROM #Dtype) '

--IF @StartDate <> '' 
--    BEGIN
--        SET @SQL = @SQL + ' AND i.billdate>=''' + @startDate + ''''
--    END
--IF @EndDate <> '' 
--    BEGIN
--        SET @SQL = @SQL + ' AND i.billdate<=''' + @EndDate + ''''
--    END
    
--SET @Sql=@Sql + ' AND i.ifYearBill= 0 '    --年节存标志    
----PRINT @SQL
--SET @SQL = @SQL + ' Order by i.ID '
--EXEC ( @SQL  )

IF @DTypeID = 'DDDDD' 
    SELECT  @TotalOut = ISNULL(SUM(total),0)
    FROM 
    (
		SELECT ISNULL(lt.total, 0) AS total
		FROM    listtable lt
				--INNER	JOIN billindex i ON ( lt.BillNumberID = i.BillNumberID )
				INNER	JOIN
				(
					SELECT BillNumberId,BillType,BillDate,ifYearBill FROM dbo.BillIndex
					UNION ALL
					SELECT BillNumberId,BillType,BillDate,ifYearBill FROM dbo.ReceiptBillIndex
					UNION ALL
					SELECT BillNumberId,BillType,BillDate,ifYearBill FROM dbo.Coupon_BillIndex
				) AS i ON(lt.BillNumberId = i.BillNumberId AND lt.BillType = i.BillType)
				LEFT JOIN dbo.Ac_Items ac ON ac.nId=lt.atypeid
		WHERE   ac.ntypeid IN (SELECT nTypeId FROM #ntypeid)
				AND i.billdate < @StartDate
				AND lt.DtypeId = ''
				AND lt.Audited = 1
				AND	lt.StypeId IN(SELECT typeid FROM #Stype)
				AND i.ifYearBill=0	 --年节存标志
				AND i.BillType NOT IN (214,78)
		UNION ALL
		SELECT ISNULL(CBND.CommissionTotal,0) AS total
		FROM CommissionBillNew AS CBN
		INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
		WHERE CBN.ifcheck = 't'
				AND CBN.billdate < @StartDate
				AND CBND.DtypeId = ''
				AND	CBN.StypeId IN(SELECT typeid FROM #Stype)
		UNION ALL
		SELECT d.Depreciation AS total
		FROM dbo.DepBill d INNER JOIN dbo.BillIndex b ON b.BillNumberId = d.BillNumberId 
		WHERE 
			'000040000300002' in (select ntypeid from #ntypeid) 
			AND d.DTypeID IN(SELECT typeid FROM #dtype)
			AND	b.STypeID IN(SELECT typeid FROM #Stype)
			AND b.BillDate < @StartDate
			AND b.ifYearBill=0
			AND b.RedWord = 0
			AND b.ifcheck = 't'
			AND b.BillType = 214
		UNION ALL
		SELECT d.total AS total
		FROM dbo.MoneyBill d INNER JOIN dbo.BillIndex b ON b.BillNumberId = d.BillNumberId
		WHERE 
			'000040000300002' in (select ntypeid from #ntypeid) 
			AND b.BillType = 78
			AND d.DTypeID IN(SELECT typeid FROM #dtype)
			AND	b.STypeID IN(SELECT typeid FROM #Stype)
			AND b.BillDate < @StartDate
			AND b.ifYearBill=0
			AND b.RedWord = 0
			AND b.ifcheck = 't'
	) AS TEMP
ELSE 
    BEGIN
        SET @DTypeID = @DTypeID + '%'
        SELECT  @TotalOut = ISNULL(SUM(total),0)
        FROM
        (	
			SELECT ISNULL(lt.total, 0) AS total
			FROM    listtable lt
					--INNER	JOIN billindex i ON ( lt.BillNumberID = i.BillNumberID )
					INNER	JOIN
					(
						SELECT BillNumberId,BillType,BillDate,ifYearBill FROM dbo.BillIndex
						UNION ALL
						SELECT BillNumberId,BillType,BillDate,ifYearBill FROM dbo.ReceiptBillIndex
						UNION ALL
						SELECT BillNumberId,BillType,BillDate,ifYearBill FROM dbo.Coupon_BillIndex
					) AS i ON(lt.BillNumberId = i.BillNumberId AND lt.BillType = i.BillType)
					LEFT JOIN dbo.Ac_Items ac ON ac.nId=lt.atypeid
			WHERE   ac.ntypeid IN (SELECT nTypeId FROM #ntypeid)
					AND i.billdate < @StartDate
					AND lt.DTypeID IN (SELECT typeid FROM #Dtype)
					AND lt.Audited = 1
					AND	lt.StypeId IN(SELECT typeid FROM #Stype)
					AND i.ifYearBill=0	 --年节存标志
					AND i.BillType NOT IN (214,78)
			UNION ALL
			SELECT ISNULL(CBND.CommissionTotal,0) AS total
			FROM CommissionBillNew AS CBN
			INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
			WHERE CBN.ifcheck = 't'
					AND CBN.billdate < @StartDate
					AND CBND.DTypeID IN (SELECT typeid FROM #Dtype)      
					AND	CBN.StypeId IN(SELECT typeid FROM #Stype)
			UNION ALL
			SELECT d.Depreciation AS total
			FROM dbo.DepBill d INNER JOIN dbo.BillIndex b ON b.BillNumberId = d.BillNumberId
			WHERE 
				'000040000300002' in (select ntypeid from #ntypeid) 
				AND d.DTypeID IN(SELECT typeid FROM #dtype)
				AND	b.STypeID IN(SELECT typeid FROM #Stype)
				AND b.BillDate < @startdate 
				AND b.ifYearBill=0
				AND b.RedWord = 0
				AND b.ifcheck = 't'
				AND b.BillType = 214
			UNION ALL
			SELECT d.total AS total
			FROM dbo.MoneyBill d INNER JOIN dbo.BillIndex b ON b.BillNumberId = d.BillNumberId 
			WHERE 
				'000040000300002' in (select ntypeid from #ntypeid) 
				AND d.DTypeID IN(SELECT typeid FROM #dtype)
				AND	b.STypeID IN(SELECT typeid FROM #Stype)
				AND b.BillDate < @StartDate
				AND b.ifYearBill=0
				AND b.BillType = 78
				AND b.RedWord = 0
			AND b.ifcheck = 't'
		) AS TEMP 
    END

SET @total = @totalOut
IF @Flag = '00' -- 只得到科目余额
BEGIN
	DROP TABLE #Dtype,#Stype
    RETURN 0
END

SELECT * FROM 
(
SELECT 
0.00 as jetotal,lt.total AS ltTotal,i.billdate,i.billcode,i.comment,lt.etypeid,lt.stypeid,lt.billtype,lt.BillNumberID
FROM listtable lt
--LEFT JOIN billindex i on(lt.BillNumberID=i.BillNumberID) 
LEFT	JOIN
(
	SELECT BillNumberId,BillType,BillDate,ifYearBill,BillCode,Comment FROM dbo.BillIndex
	UNION ALL
	SELECT BillNumberId,BillType,BillDate,ifYearBill,BillCode,Comment FROM dbo.ReceiptBillIndex
	UNION ALL
	SELECT BillNumberId,BillType,BillDate,ifYearBill,BillCode,Comment FROM dbo.Coupon_BillIndex
) AS i ON(lt.BillNumberId = i.BillNumberId AND lt.BillType = i.BillType) 
LEFT JOIN dbo.Ac_Items ac ON ac.nId=lt.atypeid
WHERE ac.ntypeid in (select ntypeid from #ntypeid)
		AND lt.audited = 1
		AND	lt.StypeId IN(SELECT typeid FROM #Stype)
		AND (NOT(@DTypeID = 'DDDDD') AND lt.DTypeID IN(SELECT typeid FROM #Dtype)
		OR (@DTypeID = 'DDDDD') AND lt.Dtypeid = '')
		AND (NOT(@StartDate <> '') 
		OR (@StartDate <> '') AND i.billdate >= @startDate)
		AND (NOT(@EndDate <> '') 
		OR (@EndDate <> '') AND i.billdate <= @EndDate)
		AND i.ifYearBill= 0
		AND i.BillType NOT IN (214,78)
UNION ALL 
SELECT 0.00 as jetotal,ISNULL(SUM(CBND.CommissionTotal),0) AS ltTotal,CBN.BillDate,CBN.BillCode,
CBN.Comment,'' AS EtypeID,CBN.StypeID,'311' AS BillType,CBN.BillNumberId
FROM CommissionBillNew AS CBN
INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
WHERE CBN.ifcheck = 't'
		AND EXISTS(select ntypeid from #ntypeid WHERE ntypeid = (SELECT nTypeId FROM dbo.Ac_Items WHERE nId = 55))
		AND	CBN.StypeId IN(SELECT typeid FROM #Stype)
		AND (NOT(@DTypeID = 'DDDDD') AND CBND.DTypeID IN(SELECT typeid FROM #Dtype)
		OR (@DTypeID = 'DDDDD') AND CBND.Dtypeid = '')
		AND (NOT(@StartDate <> '') 
		OR (@StartDate <> '') AND CBN.billdate >= @startDate)
		AND (NOT(@EndDate <> '') 
		OR (@EndDate <> '') AND CBN.billdate <= @EndDate)
GROUP BY CBN.BillDate,CBN.BillCode,CBN.Comment,CBN.StypeID,CBN.BillNumberId
UNION ALL 
SELECT 0.00 as jetotal,ISNULL(SUM(d.Depreciation),0) AS ltTotal,b.BillDate,b.BillCode,
'',b.etypeid AS EtypeID,b.StypeID,'214' AS BillType,b.BillNumberId
FROM dbo.DepBill AS d
INNER JOIN dbo.BillIndex AS b ON d.BillNumberId = b.BillNumberId
WHERE   EXISTS(select ntypeid from #ntypeid WHERE ntypeid = (SELECT nTypeId FROM dbo.Ac_Items WHERE nId = 25))
		AND	b.Stypeid IN(SELECT typeid FROM #Stype)
		AND (NOT(@DTypeID = 'DDDDD') AND d.DTypeID IN(SELECT typeid FROM #Dtype)
		OR (@DTypeID = 'DDDDD') AND b.Dtypeid = '')
		AND (NOT(@StartDate <> '') 
		OR (@StartDate <> '') AND b.billdate >= @startDate)
		AND (NOT(@EndDate <> '') 
		OR (@EndDate <> '') AND b.billdate <= @EndDate)
		AND b.RedWord = 0
		AND b.ifYearBill = 0
		AND b.ifcheck = 't'
		AND b.BillType = 214
GROUP BY d.DTypeId,b.BillDate,b.BillCode,b.Stypeid,b.BillNumberId,b.etypeid
UNION ALL 
SELECT 0.00 as jetotal,ISNULL(SUM(d.total),0) AS ltTotal,b.BillDate,b.BillCode,
'',b.etypeid AS EtypeID,b.StypeID,'78' AS BillType,b.BillNumberId
FROM dbo.MoneyBill AS d INNER JOIN dbo.BillIndex AS b ON d.BillNumberId = b.BillNumberId
WHERE   EXISTS(select ntypeid from #ntypeid WHERE ntypeid = (SELECT nTypeId FROM dbo.Ac_Items WHERE nId = 25))
		AND	b.Stypeid IN(SELECT typeid FROM #Stype)
		AND (NOT(@DTypeID = 'DDDDD') AND d.DTypeID IN(SELECT typeid FROM #Dtype)
		OR (@DTypeID = 'DDDDD') AND b.Dtypeid = '')
		AND (NOT(@StartDate <> '') 
		OR (@StartDate <> '') AND b.billdate >= @startDate)
		AND (NOT(@EndDate <> '') 
		OR (@EndDate <> '') AND b.billdate <= @EndDate)
		AND b.RedWord = 0
		AND b.ifYearBill = 0
		AND b.ifcheck = 't'
		AND b.BillType = 78
GROUP BY d.DTypeId,b.BillDate,b.BillCode,b.Stypeid,b.BillNumberId,b.etypeid
) AS TEMP 
ORDER BY BillDate
--****************************************************************************--
DROP TABLE #Dtype,#Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_AuthorUploadData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_AuthorUploadData]
GO














/***** Object:  Stored Procedure dbo.Web_AuthorUploadData    Script Date: 2002-6-20 10:14:53 ******/



--上传的单据数据存为草稿、过帐
--author:刘畅
--last modified:2001-10-30
/*-- 错误号码
  1 : 没有数据需要处理
 -51 : 是离线版
 -52 : @Off_Id、@TaskID全为空值
 -53 : 插入Index 失败
 -54 : 写入明细失败
 -55 : 对相同的单据过帐
 -56 : 删除离线数据失败
  : 过帐失败
*/
CREATE  PROCEDURE Web_AuthorUploadData
(
 @Off_Id varchar(200)='',
 @TaskID varchar(25)='',
 @Type   int
)
--@encode$--
AS
SET NOCOUNT ON
-- @Type  0 :存为草稿 1:全部过帐
Declare @RetVal Int
Declare @Cur_Off_Id uniqueidentifier
Declare @BillType Int
Declare @Cur_BillNumberId Int
Declare @szCheckMan varchar(25)
Declare @szPId varchar(25) 
-- 判断是否离线版本?
  if exists(select * from sysdata1 where SubNo=1 and SubValue='1') 
	return -51 --是离线版返回 -1
-- 建立正确的转换集
if @Off_Id <> '' 
begin
   -- 判断是否存在相同的记录(对批量处理时忽略)
   if EXISTS(Select * from billindex where OFF_ID = @Off_Id) return - 55
   Declare UploadData Cursor For 
      Select Off_Id,BillType,checke From Offline_BillIndex Where OFF_ID = @Off_Id 
end
else if @TaskID <> ''    
   Declare UploadData Cursor For 
      Select Off_Id,BillType,checke From Offline_BillIndex Where TaskID = @TaskID 

else -- 全为空值
   return -52
Open UploadData  
Fetch Next From UploadData Into @Cur_Off_Id, @BillType, @szCheckMan
if @@Fetch_Status<>0  --没有数据需要处理
  begin
    Close UploadData  
    deallocate UploadData 
    return 1
  end
-- 循环处理
Begin Tran
While @@Fetch_Status=0
Begin
     -- 判断是否存在相同的记录
     if not EXISTS(Select * from billindex where OFF_ID = @Cur_Off_Id)     
     begin
	     -- 插入 Index 记录
	     Insert Into BillIndex (BillDate,BillCode,BillType,Comment,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,explain,RedWord,draft,OrderId,waybillcode,goodsnumber,packway,TEL,OFF_ID)
	     Select BillDate,BillCode,BillType,Comment,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,'f',checke,totalmoney,totalinmoney,totalqty,tax,period,explain,RedWord,1,OrderId,waybillcode,goodsnumber,packway,TEL, @Cur_Off_Id
	     From Offline_BillIndex
	     where Off_Id = @Cur_Off_Id
	     If @@error<>0 
	         begin 
		    Select @RetVal = -53 
		    Goto Error 
		 end
	     Select @Cur_BillNumberId = SCOPE_IDENTITY();
	     -- 插入 明细  记录
	     If @BillType = 11 --销售单
	        Insert into salebill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1)
		Select @Cur_BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 45 --销售退货单
	        Insert into salebackbill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1)
		Select @Cur_BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNO1
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 4 --收款单
	        Insert into gatheringbill(BillNumberId,AtypeId,total,Comment,TeamNo,TeamNO1)
		Select @Cur_BillNumberId,AtypeId,total,Comment,TeamNo,TeamNO1
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 34 --进货单
	        Insert into buybill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNo1)
		Select @Cur_BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNo1
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 6 --进货退货单
	        Insert into buybackbill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNo1)		Select @Cur_BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,TeamNo1
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 66 --付款单
	        Insert into paybill(BillNumberId,AtypeId,total,Comment,TeamNo,TeamNO1)
		Select @Cur_BillNumberId,AtypeId,total,Comment,TeamNo,TeamNO1
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 21 --变价调拨单
	        Insert into movebjbill(BillNumberId,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate)
		Select @Cur_BillNumberId,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 17 --同价调拨单
	        Insert into movebill(BillNumberId,Comment,PtypeId,Qty,Jobnumber,GoodsNo,OutFactoryDate)
		Select @Cur_BillNumberId,Comment,PtypeId,Qty,Jobnumber,GoodsNo,OutFactoryDate
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 57 --调价单
	        Insert into adpricebill(BillNumberId,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate)
		Select @Cur_BillNumberId,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 9 --报损单
	        Insert into losebill(BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate)
		Select @Cur_BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 14 --报益单
 	       Insert into overflowbill(BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate)
		Select @Cur_BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType in(36,93) -- 费用，其他收入
        	Insert into moneybill(BillNumberId,AtypeId,total,Comment)
		Select @Cur_BillNumberId,AtypeId,total,Comment
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType=77 -- 转款单
	        Insert into MoveMoneyBill(BillNumberId,AtypeId,total,Comment)
		Select @Cur_BillNumberId,AtypeId,total,Comment
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType in(115,116,128,129) -- 调帐单
	        Insert into addebtbill(BillNumberId,Comment,BtypeId,total,TeamNo,TeamNO1)
		Select @Cur_BillNumberId,Comment,BtypeId,total,TeamNo,TeamNO1
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
	     Else If @BillType = 16 --拆装单
	        Insert into DisassembleBill(BillNumberId,PtypeId,Qty,costprice,jobnumber,total,inorout,outfactorydate,comment,goodsno)
		Select @Cur_BillNumberId,PtypeId,Qty,costprice,jobnumber,total,inorout,outfactorydate,comment,goodsno
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id
             Else If @BillType = 305 --零售单
	        Insert into RetailBill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1)
		Select @Cur_BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id

            Else if @BillType=139 --赠送单
                Insert into GiveBill(BillNumberId,Comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate) 
                select @Cur_BillNumberId,comment,PtypeId,Qty,jobnumber,goodsno,OutFactoryDate
                From Offline_Bill
		Where Off_Id = @Cur_Off_Id
            
            Else if @BillType=126 --获增单
                insert into givemebill(BillNumberId,Comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate)
                select @Cur_BillNumberId,comment,PtypeId,Qty,jobnumber,goodsno,OutFactoryDate
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id

            Else if @BillType=84 --固定资产购买
                insert into MoneyBill(BillNumberId,Comment,AtypeId,TeamNo,TeamNO1,total) 
                select @Cur_BillNumberId,comment,AtypeId,TeamNo,TeamNO1,total
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id

            Else if @BillType=85 --固定资产变卖
                insert into MoneyBill(BillNumberId,Comment,AtypeId,TeamNo,TeamNO1,total) 
                select @Cur_BillNumberId,comment,AtypeId,TeamNo,TeamNO1,total
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id

            Else if @BillType=78 --固定资产折旧
                insert into MoneyBill(BillNumberId,Comment,AtypeId,TeamNo,TeamNO1,total) 
                select @Cur_BillNumberId,comment,AtypeId,TeamNo,TeamNO1,total
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id

            Else if @BillType=5 --待摊费用发生
                insert into MoneyBill(BillNumberId,Comment,AtypeId,TeamNo,TeamNO1,total) 
                select @Cur_BillNumberId,comment,AtypeId,TeamNo,TeamNO1,total
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id

            Else if @BillType=10 --待摊费用摊销
                insert into MoneyBill(BillNumberId,Comment,AtypeId,TeamNo,TeamNO1,total) 
                select @Cur_BillNumberId,comment,AtypeId,TeamNo,TeamNO1,total
		From Offline_Bill
		Where Off_Id = @Cur_Off_Id

	     If @@error<>0 
	        begin
		  Select @RetVal=-54 
		  Goto Error
		end 
	     -- 过帐
	     if @Type = 1 
	        Begin
		  Exec @RetVal=Gp_Auditing @Cur_BillNumberId,@szCheckMan,@szPId output
	        end 
	     If (@@error<>0) or (@RetVal<>0)
	       begin
	         Goto Error
	       end 
     end
     else   --如果该Task_ID中的单据存在已过帐或存为草稿单据,则弹回提示
     begin
         select @RetVal=-57
         Goto Error
     end 
     Fetch Next From UploadData Into @Cur_Off_Id, @BillType, @szCheckMan 
end
-- 删除说有的相关的离线数据
if @Off_Id <> '' 
   Delete From Offline_BillIndex Where OFF_ID = @Off_Id 
else if @TaskID <> '' 
   Delete From Offline_BillIndex Where TaskID = @TaskID 
If @@error<>0
   begin
     Select @RetVal=-56
     Goto Error
   end 
commit tran
Close UploadData  
deallocate UploadData  
return 0
Error:
  rollback tran 
  Close UploadData  
  deallocate UploadData 
  return @RetVal













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_AuxiliaryAccount]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_AuxiliaryAccount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-07-21
	描述：辅助核算总账
*/
CREATE PROCEDURE Web_AuxiliaryAccount
    (
      @aacategorytypeid		INT,	--辅助类别ID
      @typeid				VARCHAR(MAX),	--项目ID
      @atypeid				VARCHAR(MAX),	--科目ID
      @stypeid				VARCHAR(MAX),	--分支机构
      @fyear				INT,			--年度
      @fperiodstart			INT,			--开始日期
      @fperiodend			INT,			--结束日期
      @cid					INT,			--币别ID
      @leveal				INT,			--科目级别
      @IsShowNotPost		INT,			--包括未过账凭证:1为是0为否
      @IsProNull			INT,			--无发生额科目不显示:1为是0为否
      @IsProNot				INT,			--无余额科目不显示:1为是0为否
      @chvOperatorID		VARCHAR(100)	--操作员ID
    )
--@encode$--
AS 
SET NOCOUNT ON
DECLARE 
	@sql		NVARCHAR(MAX),
	@fperiod	INT,
	@iniFYear	VARCHAR(5),	--启用年度	
	@maxfperiod	INT,		--算年度期初用
	@TypeName	VARCHAR(200)--类别编号
--辅助核算类别编号
SELECT @TypeName=UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@aacategorytypeid	
  
SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
SELECT @maxfperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE FYear=@fyear-1 AND STypeId=@stypeid
IF @iniFYear=@Fyear
	SELECT @Fperiod=SFPeriod from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
ELSE 
	SELECT @Fperiod=MIN(FPeriod) FROM dbo.Ac_Period
---判断分支机构权限
IF NOT EXISTS ( SELECT *  FROM   dbo.F_GetManDetailAllSType(@chvOperatorID)   WHERE  TypeId = @StypeID ) 
SET @StypeID = ''

--本位币
DECLARE @selfcid INT
SELECT @selfcid=CId FROM dbo.Ac_Currency WHERE Sysrow=1

BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
	INSERT INTO #Ac_Account_L (Typeid,StypeId) 
	SELECT L.Typeid,L.Stypeid FROM F_TreeAccount(@chvOperatorID,'') L
END;

---根据提取要查询的科目(即界面上要显示的有哪些科目)    
CREATE TABLE #temp1
(
	atypeid   VARCHAR(50),
	NAME		NVARCHAR(200),
	usercode    NVARCHAR(200), 
	fdc			INT,
	flag        INT                --标示该项目是子节点还是父节点
)	

--先找出符合有该辅助核算项的科目
IF @atypeid=''
	BEGIN
		INSERT INTO #temp1
		SELECT DISTINCT A.TypeId,FullName,UserCode,Fdc,SonNum 
		FROM dbo.Ac_Account a 
		INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND L.StypeId=A.StypeId
		JOIN  Ac_Account_Assist_CheckItems aa ON aa.ATypeId LIKE a.TypeId+'%' AND aa.STypeId=a.StypeId AND ((@cid>0 AND aa.cid=@cid) OR @cid<=0) AND aa.Ascids=@aacategorytypeid
		WHERE a.StypeId=@stypeid AND ParId<>'root' AND ParId<>'00000'  --AND LEVEAL>1 AND  FLEVEAL<=@Leveal 
		ORDER BY A.TypeId
	END
ELSE 
	INSERT INTO #temp1
	SELECT f.a,a.FullName,UserCode,Fdc,SonNum 
	FROM dbo.f_getparatypeitem(@atypeid,',',@stypeid,@aacategorytypeid,@cid) f 
	JOIN dbo.Ac_Account a ON f.a=a.TypeId AND a.StypeId=@stypeid --AND  LEVEAL>1 AND  FLEVEAL<=@Leveal   
	INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND L.StypeId=A.StypeId 
  
 
 ---根据#temp1找出要查询科目的子科目
 CREATE TABLE #temp2
 (
	fatheratypeid   VARCHAR(50),
	atypeid         VARCHAR(50),
	fdc		       INT,  --父科目的方向
	sonfdc         INT
 )
 INSERT INTO #temp2(fatheratypeid, atypeid, fdc, sonfdc)
 SELECT a.atypeid,b.atypeid,a.fdc,b.fdc 
 FROM 
 ( SELECT t.*,aa.FLeveal,aa.Leveal FROM #temp1 t JOIN dbo.Ac_Account aa ON t.atypeid=aa.TypeId AND aa.StypeId=@stypeid )a 
 JOIN #temp1 b ON b.atypeid LIKE a.atypeid+'%'  AND b.flag=0
 WHERE LEVEAL>1 AND  FLEVEAL<=@Leveal  
   
 ----操作#temp1
 DELETE #temp1 WHERE atypeid NOT IN (SELECT fatheratypeid FROM #temp2)
   
 -----期初数据
CREATE TABLE #tempIniData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	atypeid      VARCHAR(50),
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
IF @cid>0
		BEGIN
			IF @iniFYear=@Fyear
				BEGIN
					--原币
					INSERT INTO #tempIniData
					SELECT  t.FYear,t.FPeriod,t.fatheratypeid,SUM(borrow),SUM(lend),SUM(balance),cid
					FROM 
					(
					SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,a.atypeid,SUM(FDebitFOR) AS borrow,SUM(FCreditFor) AS lend,cid,
						   CASE WHEN a.fdc=a.sonfdc THEN SUM(IniTotalFor)
								ELSE -SUM(IniTotalFor)
						   END AS balance
					FROM #temp2  a 
					JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND cid=@cid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
					GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.atypeid,Cid,a.fdc,a.sonfdc
					) t
					GROUP BY t.FYear,t.FPeriod,t.fatheratypeid,cid	
					
					IF @cid<>@selfcid 
						---本位币
						INSERT INTO #tempIniData
						SELECT  t.FYear,t.FPeriod,t.fatheratypeid,SUM(borrow),SUM(lend),SUM(balance),0
						FROM 
						(
						SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,a.atypeid,SUM(FDebit) AS borrow,SUM(FCredit) AS lend,cid,
							   CASE WHEN a.fdc=a.sonfdc THEN SUM(IniTotal)
									ELSE -SUM(IniTotal)
							   END AS balance
						FROM #temp2  a 
						JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND cid=@cid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
						GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.atypeid,Cid,a.fdc,a.sonfdc
						) t
						GROUP BY t.FYear,t.FPeriod,t.fatheratypeid 		
				END
			ELSE                --不是期初年
				BEGIN
					INSERT INTO #tempIniData
					SELECT  t.FYear,t.FPeriod,t.fatheratypeid,SUM(borrow),SUM(lend),SUM(balance),cid
					FROM 
					(
					SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,a.atypeid,
					       0 AS borrow,--SUM(FDebitFor) AS borrow,
					       0 AS lend,--SUM(FCreditFor) AS lend,
					       cid,
						   CASE WHEN a.fdc=a.sonfdc THEN SUM(FEndBalanceFor)
								ELSE -SUM(FEndBalanceFor)
						   END AS balance
					FROM #temp2  a 
					JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND cid=@cid AND ai.FPeriod=@maxfperiod
																		AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid AND ai.FYear=@fyear-1
					GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.atypeid,Cid,a.fdc,a.sonfdc
					) t
					GROUP BY t.FYear,t.FPeriod,t.fatheratypeid,cid	
					
				    --特殊处理
				 IF @IsShowNotPost=1
					BEGIN
						IF EXISTS (SELECT TOP 1 1 FROM   (
									SELECT a.fatheratypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp2 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1  AND Cid=@cid) t WHERE fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData))
							BEGIN
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   a.fatheratypeid,0,0,0,Cid
	 									FROM  dbo.Ac_Voucher t1 
										JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
										JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
										JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
										JOIN #temp2 a ON a.atypeid=t2.ATypeId 
										WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1  AND Cid=@cid
										AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData)	
							 
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   a.fatheratypeid,0,0,0,0
	 									FROM  dbo.Ac_Voucher t1 
										JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
										JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
										JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
										JOIN #temp2 a ON a.atypeid=t2.ATypeId 
										WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1   
										AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
										 
							END								
					
						;WITH T AS
						(
							SELECT a.fatheratypeid,SUM(t2.FDebitTotalFor) AS borrow,SUM(t2.FCreditTotalFor) AS lend,Cid,a.fdc
 							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1  AND Cid=@cid
							GROUP BY a.fatheratypeid,Cid,a.fdc
				 		)
				 		UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
				 		from #tempIniData i
				 		JOIN T ON i.atypeid=T.fatheratypeid AND i.cid=T.cid 
					END
						
						
					 --特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				 	IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT a.fatheratypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp2 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid) t
									LEFT JOIN #tempIniData ti  ON t.fatheratypeid=ti.atypeid AND ti.atypeid IS NULL WHERE fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData))
				 	BEGIN
				 		 	INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						           a.fatheratypeid,
						           0,
						           0,
						           CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotal)- SUM(t2.FCreditTotal) ELSE SUM(t2.FCreditTotal)-SUM(t2.FDebitTotal) END  ,
						           t2.Cid
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti  ON a.fatheratypeid=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  AND t2.Cid=@cid 
							AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData)	
							GROUP BY t1.FYear,a.fatheratypeid,t2.cid,a.fdc
						 
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   a.fatheratypeid,
								   0,
								   0,
								   CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti ON a.fatheratypeid=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,a.fatheratypeid,a.fdc
				 	END
				 		
				 				
					IF @cid<>@selfcid 
						BEGIN
							--本位币		
							INSERT INTO #tempIniData
							SELECT  t.FYear,t.FPeriod,t.fatheratypeid,
							0,--SUM(borrow),--修改bug，这里的借和贷都是0
							0,--SUM(lend),
							SUM(balance),0  
							FROM 
							(
							SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,a.atypeid,SUM(FDebit) AS borrow,SUM(FCredit) AS lend,cid,
								   CASE WHEN a.fdc=a.sonfdc THEN SUM(FEndBalance)
										ELSE -SUM(FEndBalance)
								   END AS balance
							FROM #temp2  a 
							JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND cid=@cid AND ai.FPeriod=@maxfperiod
																				AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid AND ai.FYear=@fyear-1
							GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.atypeid,Cid,a.fdc,a.sonfdc
							) t
							GROUP BY t.FYear,t.FPeriod,t.fatheratypeid 
							
							IF @IsShowNotPost=1
								WITH T AS
								(
									SELECT a.fatheratypeid,SUM(t2.FDebitTotal) AS borrow,SUM(t2.FCreditTotal) AS lend,Cid,a.fdc
									FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp2 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   AND Cid=@cid
									GROUP BY a.fatheratypeid,Cid,a.fdc
			 					)
			 					UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 					from #tempIniData i
			 					JOIN T ON i.atypeid=T.fatheratypeid WHERE i.cid=0 
						END
				END
			
		END
ELSE IF @cid=-1  --所有币别
	BEGIN
		IF @iniFYear=@Fyear
			BEGIN
				INSERT INTO #tempIniData
				SELECT  t.FYear,t.FPeriod,t.fatheratypeid,SUM(borrow),SUM(lend),SUM(balance),cid
				FROM 
				(
				SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,SUM(FDebitFor) AS borrow,SUM(FCreditFor) AS lend,cid,
					   CASE WHEN a.fdc=a.sonfdc THEN SUM(IniTotalFor)
							ELSE -SUM(IniTotalFor)
					   END AS balance
				FROM #temp2  a 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
				GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.fdc,a.atypeid,a.sonfdc,ai.cid
				) t
				GROUP BY t.FYear,t.FPeriod,t.fatheratypeid,cid
				
				---综合本位币
				INSERT INTO #tempIniData
				SELECT  t.FYear,t.FPeriod,t.fatheratypeid,SUM(borrow),SUM(lend),SUM(balance),0
				FROM 
				(
				SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,SUM(FDebit) AS borrow,SUM(FCredit) AS lend,cid,
					   CASE WHEN a.fdc=a.sonfdc THEN SUM(IniTotal)
							ELSE -SUM(IniTotal)
					   END AS balance
				FROM #temp2  a 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid  
				GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.fdc,a.atypeid,a.sonfdc,ai.Cid
				) t
				GROUP BY t.FYear,t.FPeriod,t.fatheratypeid
			END
		ELSE                        --不是期初年
			BEGIN
				INSERT INTO #tempIniData
				SELECT  t.FYear,t.FPeriod,t.fatheratypeid,
				0,--SUM(borrow),
				0,--SUM(lend),
				SUM(balance),cid
				FROM 
				(
				SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,SUM(FDebitFor) AS borrow,SUM(FCreditFor) AS lend,cid,
					   CASE WHEN a.fdc=a.sonfdc THEN SUM(FEndBalanceFor)
							ELSE -SUM(FEndBalanceFor)
					   END AS balance
				FROM #temp2  a 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid 
																	AND ai.FieldValue=@typeid AND ai.FYear=@fyear-1 AND ai.FPeriod=@maxfperiod AND cid<>0
				GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.fdc,a.atypeid,a.sonfdc,ai.cid
				) t
				GROUP BY t.FYear,t.FPeriod,t.fatheratypeid,cid
				
				---综合本位币
				INSERT INTO #tempIniData
				SELECT  t.FYear,t.FPeriod,t.fatheratypeid,
				0,--SUM(borrow),
				0,--SUM(lend),
				SUM(balance),0
				FROM 
				(
				SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,SUM(FDebit) AS borrow,SUM(FCredit) AS lend,cid,
					   CASE WHEN a.fdc=a.sonfdc THEN SUM(FEndBalance)
							ELSE -SUM(FEndBalance)
					   END AS balance
				FROM #temp2  a 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid 
																	AND ai.FieldValue=@typeid AND ai.FYear=@fyear-1 AND ai.FPeriod=@maxfperiod AND cid<>0
				GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.fdc,a.atypeid,a.sonfdc,ai.Cid
				) t
				GROUP BY t.FYear,t.FPeriod,t.fatheratypeid
				
				--特殊情况
				IF @IsShowNotPost=1
					BEGIN
						IF EXISTS (SELECT TOP 1 1 FROM   (
									SELECT a.fatheratypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp2 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1) t WHERE fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData))
							 BEGIN
							 	INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   a.fatheratypeid,0,0,0,Cid
	 									FROM  dbo.Ac_Voucher t1 
										JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
										JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
										JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
										JOIN #temp2 a ON a.atypeid=t2.ATypeId 
										WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1   
										AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData)	
							 
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   a.fatheratypeid,0,0,0,0
	 									FROM  dbo.Ac_Voucher t1 
										JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
										JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
										JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
										JOIN #temp2 a ON a.atypeid=t2.ATypeId 
										WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1   
										AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							 END
					
					
						;WITH T AS
						(
							SELECT a.fatheratypeid,SUM(t2.FDebitTotalFor) AS borrow,SUM(t2.FCreditTotalFor) AS lend,Cid,a.fdc
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
							GROUP BY a.fatheratypeid,Cid,a.fdc
			 			)
			 			UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.atypeid=T.fatheratypeid AND i.cid=T.cid
			 			 
			 			--综合本位币
			 			;WITH T AS
						(
							SELECT a.fatheratypeid,SUM(t2.FDebitTotal) AS borrow,SUM(t2.FCreditTotal) AS lend,a.fdc
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   
							GROUP BY a.fatheratypeid,a.fdc
	 					)
	 					UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
	 					from #tempIniData i
	 					JOIN T ON i.atypeid=T.fatheratypeid WHERE i.cid=0
					END
						 
						 
					--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT a.fatheratypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp2 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1) t
									LEFT JOIN #tempIniData ti  ON t.fatheratypeid=ti.atypeid AND ti.atypeid IS NULL WHERE fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData))
					BEGIN
						    INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						           a.fatheratypeid,
						           0,
						           0,
						           CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotal)- SUM(t2.FCreditTotal) ELSE SUM(t2.FCreditTotal)-SUM(t2.FDebitTotal) END  ,
						           t2.Cid
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti  ON a.fatheratypeid=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  
							AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData)	
							GROUP BY t1.FYear,a.fatheratypeid,t2.cid,a.fdc
						 
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   a.fatheratypeid,
								   0,
								   0,
								   CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti ON a.fatheratypeid=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,a.fatheratypeid,a.fdc
					END						
			END
	END
ELSE ---综合本位币
	BEGIN
		IF @iniFYear=@Fyear
			INSERT INTO #tempIniData
			SELECT  t.FYear,t.FPeriod,t.fatheratypeid,SUM(borrow),SUM(lend),SUM(balance),0
			FROM 
			(
			SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,SUM(FDebit) AS borrow,SUM(FCredit) AS lend,cid,
				   CASE WHEN a.fdc=a.sonfdc THEN SUM(IniTotal)
						ELSE -SUM(IniTotal)
				   END AS balance
			FROM #temp2  a 
			JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
			GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.fdc,a.atypeid,a.sonfdc,ai.Cid
			) t
			GROUP BY t.FYear,t.FPeriod,t.fatheratypeid	
		ELSE 
			BEGIN
				INSERT INTO #tempIniData
				SELECT  t.FYear,t.FPeriod,t.fatheratypeid,SUM(borrow),SUM(lend),SUM(balance),0
				FROM 
				(
				SELECT ai.FYear,ai.FPeriod,a.fatheratypeid,
					   0 AS borrow,--SUM(FDebit) AS borrow,
					   0 AS lend,--SUM(FCredit) AS lend,
					   cid,
					   CASE WHEN a.fdc=a.sonfdc THEN SUM(FEndBalance)
							ELSE -SUM(FEndBalance)
					   END AS balance
				FROM #temp2  a 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid 
																	AND ai.FieldValue=@typeid AND ai.FYear=@fyear-1 AND ai.FPeriod=@maxfperiod AND cid<>0
				GROUP BY ai.FYear,ai.FPeriod,a.fatheratypeid,a.fdc,a.atypeid,a.sonfdc,ai.Cid
				) t
				GROUP BY t.FYear,t.FPeriod,t.fatheratypeid
				
				--特殊情况
				IF @IsShowNotPost=1
					BEGIN
						IF EXISTS (SELECT TOP 1 1 FROM   (
									SELECT a.fatheratypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp2 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1) t WHERE fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData))
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						   a.fatheratypeid,0,0,0,0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1   
							AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData)						
					
						;WITH T AS
						(
							SELECT a.fatheratypeid,SUM(t2.FDebitTotal) AS borrow,SUM(t2.FCreditTotal) AS lend,a.fdc
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   
							GROUP BY a.fatheratypeid,a.fdc
 						)
 						UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
 						from #tempIniData i
 						JOIN T ON i.atypeid=T.fatheratypeid WHERE i.cid=0
					END
					
				--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT a.fatheratypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp2 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1) t
									LEFT JOIN #tempIniData ti  ON t.fatheratypeid=ti.atypeid AND ti.atypeid IS NULL WHERE fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData))
					BEGIN
								INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   a.fatheratypeid,
								   0,
								   0,
								   CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp2 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti ON a.fatheratypeid=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND a.fatheratypeid NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,a.fatheratypeid,a.fdc
					END						
			END
				
	END
		
  
---本期累计
CREATE  TABLE #tempPeriodData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	atypeid	     VARCHAR(50),
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
IF @cid>0
	BEGIN
		--原币
		INSERT INTO #tempPeriodData
	 	SELECT t1.FYear,t1.FPeriod,a.fatheratypeid,SUM(t2.FDebitTotalFor),SUM(t2.FCreditTotalFor),0,Cid
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #temp2 a ON a.atypeid=t2.ATypeId 
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,a.fatheratypeid,Cid   
		
		IF @cid<>@selfcid 
			--本位币
			INSERT INTO #tempPeriodData
	 		SELECT t1.FYear,t1.FPeriod,a.fatheratypeid,SUM(t2.FDebitTotal),SUM(t2.FCreditTotal),0,0
	 		FROM  dbo.Ac_Voucher t1 
			JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
			JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
			JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
			JOIN #temp2 a ON a.atypeid=t2.ATypeId 
			WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear  AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
			GROUP BY t1.FYear,t1.FPeriod,a.fatheratypeid 
	END
		          
ELSE IF @cid=-1  --所有币别
	BEGIN
		INSERT INTO #tempPeriodData
	 	SELECT t1.FYear,t1.FPeriod,a.fatheratypeid,SUM(t2.FDebitTotalFor),SUM(t2.FCreditTotalFor),0,Cid
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #temp2 a ON a.atypeid=t2.ATypeId 
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear  AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,a.fatheratypeid,Cid  
		
		--综合本位币
	 	INSERT INTO #tempPeriodData
	 	SELECT FYear,FPeriod,atypeid,SUM(FDebit),SUM(FCredit),0,0
	 	FROM
	 	(
	 	SELECT t1.FYear,t1.FPeriod,a.fatheratypeid AS atypeid,SUM(t2.FDebitTotal) AS FDebit,SUM(t2.FCreditTotal) AS FCredit,Cid
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #temp2 a ON a.atypeid=t2.ATypeId 
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear  AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,a.fatheratypeid,Cid  
		) t 
		GROUP BY FYear,FPeriod,atypeid 
	END
 ELSE   --综合本位币
		INSERT INTO #tempPeriodData
	 	SELECT FYear,FPeriod,atypeid,SUM(FDebit),SUM(FCredit),0,0
	 	FROM
	 	(
	 	SELECT t1.FYear,t1.FPeriod,a.fatheratypeid AS atypeid,SUM(t2.FDebitTotal) AS FDebit,SUM(t2.FCreditTotal) AS FCredit,Cid
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #temp2 a ON a.atypeid=t2.ATypeId 
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,a.fatheratypeid,Cid  
		) t
		GROUP BY FYear,FPeriod,atypeid 
  
---本年累计
CREATE TABLE #tempYearData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	atypeid   VARCHAR(50),
	fdc			INT,
	qichu		  NUMERIC(24, 10) ,   --多加一列期初
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	yearborrow    NUMERIC(24, 10) ,
	yearlend      NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
--建表
DECLARE @iniFpeirod INT=@fperiod
WHILE @iniFpeirod<=@fperiodend
	BEGIN
		IF @cid=-1 --所有币别
			BEGIN
				INSERT INTO #tempYearData 
				SELECT @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,CId FROM 
				(
			    SELECT CId FROM dbo.Ac_Currency
			    UNION ALL 
			    SELECT 0 AS cid 
			    ) c,#temp1 i     
			END
		ELSE IF @cid>0 --具体币别
			BEGIN
				IF @cid=@selfcid
					INSERT INTO #tempYearData
					Select @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,@cid
					from #temp1 i   
				ELSE 
					INSERT INTO #tempYearData
					Select @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,@cid
					from #temp1 i   
					UNION ALL 
					Select @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,0
					from #temp1 i  
			END
		else   --综合本位币 
			BEGIN
				INSERT INTO #tempYearData
				Select @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,0
				from #temp1 i   
			END
		
		--更新本期数据
		update y set y.borrow=ISNULL(i.borrow,0),y.lend=ISNULL(i.lend,0)
		from #tempYearData y 
		LEFT join #tempPeriodData i on y.atypeid=i.atypeid and y.cid=i.cid AND y.fperiod=i.fperiod
	
		--更新开账的期初期初
		if @iniFpeirod=@fperiod
			BEGIN
				--第一期期初
				update y set y.qichu=i.balance 
				from #tempYearData y 
				join #tempIniData i on y.atypeid=i.atypeid and y.cid=i.cid
				WHERE y.fperiod=@iniFpeirod
			END
		else 
			BEGIN
				--取上期的期初
				UPDATE y SET y.qichu=y1.balance 
				FROM #tempYearData y 
				JOIN #tempYearData y1 on y.atypeid=y1.atypeid and y.cid=y1.cid and y.fperiod=y1.fperiod+1
				where y.fperiod=@iniFpeirod
			end
	   
	   --计算期末
		UPDATE #tempYearData SET balance=(CASE WHEN fdc=1 THEN qichu+borrow-lend
											   ELSE  qichu-borrow+lend
										  END)
		
		--更新年累计数据
		UPDATE y SET y.yearborrow=isnull(T.borrow,0)+isnull(i.borrow,0),y.yearlend=ISNULL(T.lend,0)+ISNULL(i.lend,0)
	    FROM #tempYearData y 
	    LEFT JOIN  
	    ( select @iniFpeirod as fperiod,atypeid,cid,sum(borrow) as borrow,sum(lend) as lend
	      from #tempPeriodData where fperiod<=@iniFpeirod group by atypeid,cid ) T 
	    ON y.fperiod=T.fperiod and y.atypeid=T.atypeid and y.cid=T.cid 
	    LEFT JOIN #tempIniData i ON y.atypeid=i.atypeid and y.cid=i.cid 
	    WHERE y.fperiod=@iniFpeirod
			
		SET @iniFpeirod=@iniFpeirod+1      
	END
  
   
  
    --筛选不符合条件的科目
    CREATE TABLE #tempItems
    (
		atypeid		  varchar(50),
		periodchange   NUMERIC(24, 10) ,
		balance        NUMERIC(24, 10) 
    )
    IF @cid=@selfcid OR @cid=0     --本位币和综合本位币
		insert into #tempItems
		select i.atypeid,p.periodchange,b.balance from #temp1 i 
		join 
		(    
		SELECT atypeid,balance FROM #tempYearData where fperiod=@fperiodend
		)  b on b.atypeid=i.atypeid
		join 
		(
		SELECT atypeid,SUM(ABS(borrow))+SUM(ABS(lend)) AS periodchange FROM #tempYearData WHERE fperiod>=@fperiodstart AND fperiod<=@fperiodend group by atypeid
		) p on p.atypeid=i.atypeid
	ELSE    --所有币别或外币，直接看综合本位币
		insert into #tempItems
		select i.atypeid,p.periodchange,b.balance from #temp1 i 
		join 
		(    
		SELECT atypeid,balance FROM #tempYearData where fperiod=@fperiodend and cid=0
		)  b on b.atypeid=i.atypeid
		join 
		(
		SELECT atypeid,SUM(ABS(borrow))+SUM(ABS(lend)) AS periodchange FROM #tempYearData WHERE fperiod>=@fperiodstart AND fperiod<=@fperiodend and cid=0 group by atypeid
		) p on p.atypeid=i.atypeid
      ------------------------------------------------查询结果
      IF @cid=0 OR @cid=@selfcid  --本位币单币别或者综合本位币
		SELECT fperiod AS period,
			   usercode AS atypeid,   --报表的穿透功能用此列
			   NAME AS atypename,
			   usercode AS typeusercode,
			   case when qichu=0 then '平' WHEN i.fdc=1 THEN '借' ELSE '贷'  end as beginbalancefdc,
			   qichu as beginbalancetotal,
			   borrow as debit,
			   lend as credit,
			   yearborrow as ytddebit,
			   yearlend as ytdcredit,
			   case when balance=0 then '平' WHEN i.fdc=1 THEN '借' ELSE '贷' end as endbalancefdc,
			   balance as endbalancetotal
		FROM #tempYearData y 
		JOIN #temp1 i ON y.atypeid=i.atypeid
		join (
				select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
			 ) t on y.atypeid=t.atypeid
		where fperiod>=@fperiodstart
	    order by usercode,fperiod
	ELSE  
		BEGIN
			  -----------------------------------------------------------所有币别是动态列,先求出有多少列----------------------------------------------------------
			  CREATE TABLE #tempColName1
			  (
				cid INT,
				usercode  VARCHAR(200)
			  )
			  IF @cid<>-1  --具体币别
				INSERT INTO #tempColName1
				SELECT CID,USERCODE 
				FROM (SELECT CID,USERCODE FROM AC_CURRENCY WHERE CId=@cid
					  UNION ALL 
					  SELECT 0 AS CID,'' AS USERCODE) b
			  ELSE
				INSERT INTO #tempColName1
			    SELECT CID,USERCODE 
				FROM (SELECT CID,USERCODE FROM AC_CURRENCY
					  UNION ALL 
					  SELECT 0 AS CID,'' AS USERCODE) b
					  
			-----------------------------------------------期初
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColNameqichu
			FROM #tempColName1,(SELECT 'beginbalancetotal' AS COLNAME)T
			
			--行转列的时候用
			DECLARE @qichuTurnCol VARCHAR(MAX)
			SELECT @qichuTurnCol=(ISNULL(@qichuTurnCol+'],[','') +  colname) 
			FROM #tempColNameqichu GROUP BY COLNAME 
			SET @qichuTurnCol='['+@qichuTurnCol+']'
			
			SELECT b.atypeid,
				   b.fperiod,
			       a.COLNAME,
				   b.qichu AS fvalue
	       INTO #tempqichu
		   FROM #tempColNameqichu a,#tempYearData b WHERE a.cid=b.cid
			---------------------------------------------期末
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColNameqimo
			FROM #tempColName1,(SELECT 'endbalancetotal' AS COLNAME)T
			
			--行转列的时候用
			DECLARE @qimoTurnCol VARCHAR(MAX)
			SELECT @qimoTurnCol=(ISNULL(@qimoTurnCol+'],[','') +  colname) 
			FROM #tempColNameqimo GROUP BY COLNAME 
			SET @qimoTurnCol='['+@qimoTurnCol+']'
			
			SELECT b.atypeid,
				   b.fperiod,
			       a.COLNAME,
				   b.balance AS fvalue
	       INTO #tempqimo
		   FROM #tempColNameqimo a,#tempYearData b WHERE a.cid=b.cid
			--------------------------------------------借贷
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColNamejd
			FROM #tempColName1,(SELECT 'debit' AS COLNAME
								UNION ALL
								SELECT 'credit' AS COLNAME)T
			
			--行转列的时候用
			DECLARE @jdTurnCol VARCHAR(MAX)
			SELECT @jdTurnCol=(ISNULL(@jdTurnCol+'],[','') +  colname) 
			FROM #tempColNamejd GROUP BY COLNAME 
			SET @jdTurnCol='['+@jdTurnCol+']'
			
			SELECT b.atypeid,
				   b.fperiod,
			       a.COLNAME,
				   CASE WHEN COLNAME LIKE 'debit'+'%' THEN borrow ELSE lend END AS fvalue
	       INTO #tempjd
		   FROM #tempColNamejd a,(SELECT atypeid,fperiod,borrow,lend,cid FROM  #tempYearData) b WHERE a.cid=b.cid
		   --------------------------------------------累计借贷
		   SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColNameyjd
			FROM #tempColName1,(SELECT 'ytddebit' AS COLNAME
								UNION ALL
								SELECT 'ytdcredit' AS COLNAME)T
			
			--行转列的时候用
			DECLARE @yjdTurnCol VARCHAR(MAX)
			SELECT @yjdTurnCol=(ISNULL(@yjdTurnCol+'],[','') +  colname) 
			FROM #tempColNameyjd GROUP BY COLNAME 
			SET @yjdTurnCol='['+@yjdTurnCol+']'
			
			SELECT b.atypeid,
				   b.fperiod,
			       a.COLNAME,
				   CASE WHEN COLNAME LIKE 'ytddebit'+'%' THEN yearborrow ELSE yearlend END AS fvalue
	       INTO #tempyjd
		   FROM #tempColNameyjd a,(SELECT atypeid,fperiod,yearborrow,yearlend,cid FROM  #tempYearData) b WHERE a.cid=b.cid
			---------------------------------------------全部
			SELECT COLNAME  
			INTO #tempColName2 
			FROM (
			SELECT 'beginbalancetotal' AS COLNAME
			UNION ALL   
			SELECT 'debit' AS COLNAME
			UNION ALL
			SELECT 'credit' AS COLNAME
			UNION ALL 
			SELECT 'endbalancetotal' AS COLNAME
			UNION ALL 
			SELECT 'ytddebit' AS COLNAME
			UNION ALL
			SELECT 'ytdcredit' AS COLNAME
			) a
		     
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColName
			FROM #tempColName1,#tempColName2
			
			--行转列的时候用
			DECLARE @TurnCol VARCHAR(MAX)
			SELECT @TurnCol=(ISNULL(@TurnCol+'],[','') +  colname) 
			FROM #tempColName GROUP BY COLNAME 
			SET @TurnCol='['+@TurnCol+']'
		   
			--------------------------------------------结果
			SET @sql='SELECT a.atypeid,a.Fperiod,'+@TurnCol+' 
			INTO #tempall 
			FROM #tempYearData a 
			JOIN (
				SELECT *  FROM  #tempqichu  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@qichuTurnCol+')) t
				 ) b ON b.atypeid=a.atypeid and a.fperiod=b.fperiod 
			JOIN ( 
				 SELECT *  FROM  #tempqimo  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@qimoTurnCol+') ) t
				 ) c ON c.atypeid=a.atypeid and a.fperiod=c.fperiod 
			JOIN (
				SELECT *  FROM  #tempjd  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@jdTurnCol+')) t
				 ) d ON d.atypeid=a.atypeid and a.fperiod=d.fperiod 
			JOIN (
				SELECT *  FROM  #tempyjd  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@yjdTurnCol+')) t
				 ) e ON e.atypeid=a.atypeid and a.fperiod=e.fperiod   
			where cid=0 
			 
			 SELECT fperiod AS period,
			   usercode as atypeid,
			   NAME AS atypename,
			   usercode AS typeusercode,
			   case when beginbalancetotal=0 then ''平'' WHEN fdc=1 THEN ''借'' ELSE ''贷'' end as beginbalancefdc,
			   case when endbalancetotal=0 then ''平'' WHEN fdc=1 THEN ''借'' ELSE ''贷'' end as endbalancefdc,
			   '+@TurnCol+'
			FROM #tempall y 
			JOIN #temp1 i ON y.atypeid=i.atypeid
			join (
					select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
				 ) t on y.atypeid=t.atypeid
			where fperiod>=@fperiodstart
			order by usercode,fperiod;
		    
			drop table #tempall'
			
			PRINT @TurnCol
			 EXEC sp_executesql @SQL,N'@IsProNull INT,@IsProNot INT,@fperiodstart INT',@IsProNull,@IsProNot,@fperiodstart
			 
			 DROP TABLE #tempColName,#tempColName1,#tempColName2,#tempColNamejd,#tempColNameqichu,#tempColNameqimo,#tempColNameyjd
		END
	DROP TABLE #temp1,#temp2,#tempIniData,#tempPeriodData,#tempYearData,#tempItems
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_AuxiliaryAccount1]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_AuxiliaryAccount1]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-07-13
	描述：辅助核算总账
*/
CREATE PROCEDURE Web_AuxiliaryAccount1
    (
      @aacategorytypeid		INT,	--辅助类别ID
      @aacategoryprotypeid	VARCHAR(MAX),	--辅助项目ID
      @atypeid1				VARCHAR(MAX),	--科目ID
      @stypeid				VARCHAR(MAX),	--分支机构
      @fyear				INT,
      @fperiodstart			INT,			--开始日期
      @fperiodend			INT,			--结束日期
      @cid					INT,	--币别ID
      @IsShowNotPost		INT,			--包括未过账凭证:1为是0为否
      @IsBalanceNull		INT,			--无发生额项目不显示:1为是0为否
      @IsBalanceNot			INT,			--无余额项目不显示:1为是0为否
      @chvOperatorID		VARCHAR(100)	--操作员ID
    )
--@encode$--
AS 
SET NOCOUNT ON
DECLARE 
	@sql		NVARCHAR(MAX),
	@fperiod	INT,
	@iniFYear	VARCHAR(5),	 --启用年度	
	@maxfperiod	INT,		--算年度期初用	
	@TypeName	VARCHAR(200)--类别编号
--辅助核算类别编号
SELECT @TypeName=UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@aacategorytypeid	
  
SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
SELECT @maxfperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE FYear=@fyear-1 AND STypeId=@stypeid
	IF @iniFYear=@Fyear
		SELECT @FPeriod=SFPeriod from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	ELSE 
		SELECT @Fperiod=MIN(FPeriod) FROM dbo.Ac_Period		 
---判断分支机构权限
 IF NOT EXISTS ( SELECT *  FROM   dbo.F_GetManDetailAllSType(@chvOperatorID)   WHERE  TypeId = @StypeID ) 
    SET @StypeID = ''
 
BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
	INSERT INTO #Ac_Account_L (Typeid,StypeId) 
	SELECT L.Typeid,L.Stypeid FROM F_TreeAccount(@chvOperatorID,'') L
END; 

--本位币
DECLARE @selfcid INT
SELECT @selfcid=CId FROM dbo.Ac_Currency WHERE Sysrow=1

DECLARE @iniFpeirod INT=@fperiod,
		@Fdc   INT,
		@FdcName  VARCHAR(5)
SELECT @Fdc=Fdc,@FdcName=CASE WHEN fdc=1 THEN '借' ELSE '贷' END FROM dbo.Ac_Account A
INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND L.StypeId=A.StypeId 
WHERE A.TypeId=@atypeid1

---根据要查询的辅助核算找出要查询的辅助核算项目（包括父节点项目和子节点,显示用）
CREATE TABLE #tempAllAssistItems
(
	fieldValue  VARCHAR(50),
	NAME		NVARCHAR(200),
	usercode    NVARCHAR(200), 
	flag        INT                --标示该项目是子节点还是父节点
)	
IF @aacategorytypeid=1 --分支机构
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				IF EXISTS(SELECT * FROM sysdata WHERE SubName='innerstypesaleralation' AND SubValue=1)  --存在买卖关系
					INSERT INTO #tempAllAssistItems 
					SELECT s.TypeId,FullName,UserCode,sonnum 
					FROM dbo.SType s
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
					WHERE deleted=0  AND parid<>'root' AND VerifyID=@stypeid
				ELSE 
					INSERT INTO #tempAllAssistItems 
					SELECT s.TypeId,FullName,UserCode,sonnum 
					FROM dbo.SType s 
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
					WHERE deleted=0  AND parid<>'root'
			END
		ELSE     
			BEGIN
				IF EXISTS(SELECT * FROM sysdata WHERE SubName='innerstypesaleralation' AND SubValue=1)  --存在买卖关系
					INSERT INTO #tempAllAssistItems
					SELECT s.TypeId,s.FullName,s.UserCode,s.sonnum FROM dbo.f_getparassistitem(@aacategoryprotypeid,',') f JOIN dbo.SType s ON f.a=s.TypeId AND parid<>'root' AND VerifyID=@stypeid
					UNION 
					SELECT s.TypeId,s.FullName,s.UserCode,s.sonnum FROM dbo.f_split(@aacategoryprotypeid,',') f JOIN dbo.SType s ON s.TypeId LIKE f.a+'%' AND VerifyID=@stypeid
				ELSE 
					INSERT INTO #tempAllAssistItems
					SELECT s.TypeId,s.FullName,s.UserCode,s.sonnum FROM dbo.f_getparassistitem(@aacategoryprotypeid,',') f JOIN dbo.SType s ON f.a=s.TypeId AND parid<>'root'  
					UNION 
					SELECT s.TypeId,s.FullName,s.UserCode,s.sonnum FROM dbo.f_split(@aacategoryprotypeid,',') f JOIN dbo.SType s ON s.TypeId LIKE f.a+'%'  
				
				DELETE #tempAllAssistItems WHERE fieldValue NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) )
			END
	END
ELSE IF @aacategorytypeid=2 --部门
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempAllAssistItems 
				SELECT d.TypeId,FullName,UserCode,sonnum FROM dbo.Department d
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID) 
					   ) c ON d.TypeId=c.TypeId
				WHERE deleted=0  AND parid<>'root'  
			END
		ELSE    
			BEGIN
				INSERT INTO #tempAllAssistItems
				SELECT d.typeid,d.FullName,d.UserCode,d.sonnum FROM dbo.f_getparassistitem(@aacategoryprotypeid,',') f  JOIN dbo.Department d ON f.a=d.typeid AND parid<>'root' 
				UNION   
				SELECT d.typeid,d.FullName,d.UserCode,d.sonnum FROM dbo.f_split(@aacategoryprotypeid,',') f JOIN dbo.Department d ON d.TypeId LIKE f.a+'%' 
				
				DELETE #tempAllAssistItems WHERE fieldValue NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID) )
			END
	END
ELSE IF @aacategorytypeid=3 --职员
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempAllAssistItems 
				SELECT e.TypeId,FullName,UserCode,sonnum FROM dbo.employee e
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID) 
					   ) c ON e.TypeId=c.TypeId
				WHERE deleted=0 AND parid<>'root'  AND Parid<>'00000'  
			END
		ELSE    
			BEGIN
				INSERT INTO #tempAllAssistItems
				SELECT e.typeId,e.FullName,e.UserCode,e.sonnum FROM dbo.f_getparassistitem(@aacategoryprotypeid,',') f  JOIN dbo.employee e ON f.a=e.typeId AND parid<>'root'  AND Parid<>'00000'  
				UNION 
				SELECT e.typeId,e.FullName,e.UserCode,e.sonnum FROM dbo.f_split(@aacategoryprotypeid,',') f JOIN dbo.employee e ON e.TypeId LIKE f.a+'%' 
				
				DELETE #tempAllAssistItems WHERE fieldValue NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID) )
			END
	END
ELSE IF @aacategorytypeid=4 --往来单位	
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempAllAssistItems 
				SELECT b.TypeId,FullName,UserCode,sonnum FROM dbo.btype b
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID) 
					   ) c ON b.TypeId=c.TypeId
				WHERE deleted=0 AND parid<>'root'  AND Parid<>'00000'
			END
		ELSE     
			BEGIN
				INSERT INTO #tempAllAssistItems
				SELECT b.typeId,b.FullName,b.UserCode,b.sonnum FROM dbo.f_getparassistitem(@aacategoryprotypeid,',') f JOIN dbo.btype b ON f.a=b.typeid AND parid<>'root'  AND Parid<>'00000'
				UNION 
				SELECT b.typeId,b.FullName,b.UserCode,b.sonnum FROM dbo.f_split(@aacategoryprotypeid,',') f JOIN dbo.btype b ON b.TypeId LIKE f.a+'%' 
				
				DELETE #tempAllAssistItems WHERE fieldValue NOT IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID) )
			END
	END
ELSE 
	BEGIN
		INSERT INTO #tempAllAssistItems
		SELECT 
			B.TypeId,
			B.FullName,
			B.UserCode,
			B.SonNum 
		FROM Ac_Assist_CheckItemsDetail B
		INNER JOIN dbo.F_GetAllAssistCheckItemsDetail(@aacategoryprotypeid,@aacategorytypeid,@chvOperatorID) F ON F.TypeId=B.TypeId AND B.AscIds=@aacategorytypeid AND B.SonNum=0
	END
	 
	 
----根据要显示的项目，找出他们对应的要查询的子项目
CREATE TABLE #tempSonAssistItems
(
	FatherfieldValue   VARCHAR(50),
	fieldValue			VARCHAR(50)
)
INSERT INTO #tempSonAssistItems
SELECT a.fieldValue,b.fieldValue FROM #tempAllAssistItems a JOIN #tempAllAssistItems b ON b.fieldValue LIKE a.fieldValue+'%' AND b.flag=0


-----期初数据
CREATE TABLE #tempIniData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	fieldValue   VARCHAR(50),
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
IF @cid>0  --单币别
	BEGIN
		IF @iniFYear=@Fyear
			BEGIN
				--原币
				INSERT INTO #tempIniData   
				SELECT FYear,FPeriod,i.FatherfieldValue,SUM(FDebitFor),SUM(FCreditFor),SUM(IniTotalFor),Cid
				FROM #tempSonAssistItems i 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND Cid=@cid AND i.fieldValue=ai.FieldValue
				GROUP BY FYear,FPeriod,i.FatherfieldValue,ai.Cid
				
				IF @cid<>@selfcid 
					---本位币
					INSERT INTO #tempIniData   
					SELECT FYear,FPeriod,i.FatherfieldValue,SUM(FDebit),SUM(FCredit),SUM(IniTotal),0
					FROM #tempSonAssistItems i 
					JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND Cid=@cid AND i.fieldValue=ai.FieldValue
					GROUP BY FYear,FPeriod,i.FatherfieldValue		
			END
		ELSE 
			BEGIN
				--原币
				INSERT INTO #tempIniData   
				SELECT FYear,FPeriod,i.FatherfieldValue,
					0,--SUM(FDebitFor),
					0,--SUM(FCreditFor),
					SUM(FEndBalanceFor),Cid
				FROM #tempSonAssistItems i 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid 
																	AND Cid=@cid AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.FPeriod=@maxfperiod
				GROUP BY FYear,FPeriod,i.FatherfieldValue,ai.Cid
				
				 IF @IsShowNotPost=1
					BEGIN
						--修复上一年没数据，只有未过账凭证，没期初的情况
						IF EXISTS(SELECT TOP 1 1 FROM (SELECT FatherfieldValue 
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid) T WHERE FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
							BEGIN
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   FatherfieldValue,0,0,0,Cid
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
												AND FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData)
												
							   INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   FatherfieldValue,0,0,0,0
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
												AND FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData WHERE cid=0)
							END					
					
						;WITH T AS
						(
							SELECT i.FatherfieldValue,SUM(t2.FDebitTotalFor) AS  borrow,SUM(t2.FCreditTotalFor) AS lend,Cid
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
							GROUP BY i.FatherfieldValue,Cid 
			 			)
			 			UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.fieldValue=T.FatherfieldValue AND i.cid=T.cid 	
					END
					
				  --特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				 	IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT FatherfieldValue 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #tempSonAssistItems i ON  t3.TypeId=i.fieldValue
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid) t
									LEFT JOIN #tempIniData ti  ON t.FatherfieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
									WHERE FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
				 	BEGIN
				 		 	INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						           FatherfieldValue,
						           0,
						           0,
						           CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotal)- SUM(t2.FCreditTotal) ELSE SUM(t2.FCreditTotal)-SUM(t2.FDebitTotal) END  ,
						           t2.Cid
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON FatherfieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  AND t2.Cid=@cid 
							AND FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData)	
							GROUP BY t1.FYear,FatherfieldValue,t2.cid 
						 
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   FatherfieldValue,
								   0,
								   0,
								   CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON FatherfieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,FatherfieldValue 
				 	END 
				
				IF @cid<>@selfcid 
					BEGIN
						---本位币
						INSERT INTO #tempIniData   
						SELECT FYear,FPeriod,i.FatherfieldValue,
						0,--SUM(FDebit),
						0,--SUM(FCredit),
						SUM(FEndBalance),0
						FROM #tempSonAssistItems i 
						JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid 
																			AND Cid=@cid AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.FPeriod=@maxfperiod
						GROUP BY FYear,FPeriod,i.FatherfieldValue
						
						 IF @IsShowNotPost=1
							WITH T AS
							(
								SELECT i.FatherfieldValue,SUM(t2.FDebitTotal) AS  borrow,SUM(t2.FCreditTotal) AS lend,Cid
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
								GROUP BY i.FatherfieldValue,Cid 
			 				)
			 				UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 				from #tempIniData i
			 				JOIN T ON i.fieldValue=T.FatherfieldValue AND i.cid=0
					END
							
			END
	END
		
ELSE IF @cid=-1  --所有币别
	BEGIN
		IF @iniFYear=@Fyear
			BEGIN
				INSERT INTO #tempIniData   
				SELECT FYear,FPeriod,i.FatherfieldValue,SUM(FDebitFor),SUM(FCreditFor),SUM(IniTotalFor),Cid
				FROM #tempSonAssistItems i 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND i.fieldValue=ai.FieldValue
				GROUP BY FYear,FPeriod,i.FatherfieldValue,ai.Cid
				 
				--综合本位币
				INSERT INTO #tempIniData  
				SELECT FYear,FPeriod,FieldValue,SUM(FDebit),SUM(FCredit),SUM(IniTotal),0
				FROM 
				( 
					SELECT FYear,FPeriod,i.FatherfieldValue AS FieldValue,SUM(FDebit) AS FDebit,SUM(FCredit) AS FCredit,SUM(IniTotal) AS IniTotal,Cid
					FROM #tempSonAssistItems i 
					JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND i.fieldValue=ai.FieldValue
					GROUP BY FYear,FPeriod,i.FatherfieldValue,ai.Cid
				) t
				GROUP BY FYear,FPeriod,FieldValue
			END
		ELSE 
			BEGIN
				INSERT INTO #tempIniData   
				SELECT FYear,FPeriod,i.FatherfieldValue,
						0,--SUM(FDebitFor),
						0,--SUM(FCreditFor),
						SUM(FEndBalanceFor),Cid
				FROM #tempSonAssistItems i 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid
																	 AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.FPeriod=@maxfperiod AND ai.Cid<>0
				GROUP BY FYear,FPeriod,i.FatherfieldValue,ai.Cid
				 
				--综合本位币
				INSERT INTO #tempIniData  
				SELECT FYear,FPeriod,FieldValue,
					0,--SUM(FDebit),
					0,--SUM(FCredit),
					SUM(FEndBalance),0
				FROM 
				( 
					SELECT FYear,FPeriod,i.FatherfieldValue AS FieldValue,SUM(FDebit) AS FDebit,SUM(FCredit) AS FCredit,SUM(FEndBalance) AS FEndBalance,Cid
					FROM #tempSonAssistItems i 
					JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid 
																	AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.FPeriod=@maxfperiod AND ai.Cid<>0
					GROUP BY FYear,FPeriod,i.FatherfieldValue,ai.Cid
				) t
				GROUP BY FYear,FPeriod,FieldValue
				
				 --特殊情况
				 IF @IsShowNotPost=1
					BEGIN
						--修复上一年没数据，只有未过账凭证，没期初的情况
						IF EXISTS(SELECT TOP 1 1 FROM (SELECT FatherfieldValue 
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1) T WHERE FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
							BEGIN
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   FatherfieldValue,0,0,0,Cid
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1
												AND FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData)
												
							   INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   FatherfieldValue,0,0,0,0
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
												AND FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData WHERE cid=0)
							END					
					
						;WITH T AS
						(
							SELECT i.FatherfieldValue,SUM(t2.FDebitTotalFor) AS  borrow,SUM(t2.FCreditTotalFor) AS lend,Cid
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   
							GROUP BY i.FatherfieldValue,Cid 
			 			)
			 			UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.fieldValue=T.FatherfieldValue AND i.cid=T.cid 
			 			
			 			;WITH T AS
						(
							SELECT i.FatherfieldValue,SUM(t2.FDebitTotal) AS  borrow,SUM(t2.FCreditTotal) AS lend
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   
							GROUP BY i.FatherfieldValue
			 			)
			 			UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.fieldValue=T.FatherfieldValue AND i.cid=0 
					END
						--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT FatherfieldValue
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  AND t2.ATypeId=@atypeid1 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #tempSonAssistItems i ON  t3.TypeId=i.fieldValue
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1) t
									LEFT JOIN #tempIniData ti  ON t.FatherfieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
									 WHERE FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
					BEGIN
						    INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						           FatherfieldValue,
						           0,
						           0,
						           CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotal)- SUM(t2.FCreditTotal) ELSE SUM(t2.FCreditTotal)-SUM(t2.FDebitTotal) END  ,
						           t2.Cid
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON  t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON FatherfieldValue=ti.fieldValue AND ti.fieldValue IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  
							AND FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData)	
							GROUP BY t1.FYear,FatherfieldValue,t2.cid 
						 
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   FatherfieldValue,
								   0,
								   0,
								   CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON  t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON FatherfieldValue=ti.fieldValue AND ti.fieldValue IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND FatherfieldValue NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,FatherfieldValue 
					END				 
			END
	END
ELSE --综合本位币
	BEGIN
		IF @iniFYear=@Fyear
			INSERT INTO #tempIniData  
			SELECT FYear,FPeriod,FieldValue,SUM(FDebit),SUM(FCredit),SUM(IniTotal),0
			FROM 
			( 
				SELECT FYear,FPeriod,i.FatherfieldValue AS FieldValue,SUM(FDebit) AS FDebit,SUM(FCredit) AS FCredit,SUM(IniTotal) AS IniTotal,Cid
				FROM #tempSonAssistItems i 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND i.fieldValue=ai.FieldValue
				GROUP BY FYear,FPeriod,i.FatherfieldValue,ai.Cid
			) t
			GROUP BY FYear,FPeriod,FieldValue
		ELSE 
			BEGIN
				INSERT INTO #tempIniData  
				SELECT FYear,FPeriod,FieldValue,
						0,--SUM(FDebit),
						0,--SUM(FCredit),
						SUM(FEndBalance),0
				FROM 
				( 
					SELECT FYear,FPeriod,i.FatherfieldValue AS FieldValue,SUM(FDebit) AS FDebit,SUM(FCredit) AS FCredit,SUM(FEndBalance) AS FEndBalance,Cid
					FROM #tempSonAssistItems i 
					JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid 
																	AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.FPeriod=@maxfperiod AND ai.Cid<>0
					GROUP BY FYear,FPeriod,i.FatherfieldValue,ai.Cid
				) t
				GROUP BY FYear,FPeriod,FieldValue
				
				IF @IsShowNotPost=1
					BEGIN
						--修复上一年没数据，只有未过账凭证，没期初的情况
						IF EXISTS(SELECT TOP 1 1 FROM (SELECT FatherfieldValue 
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1) T WHERE FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
							   INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   FatherfieldValue,0,0,0,0
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
												AND FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData)
							
						;WITH T AS
						(
							SELECT i.FatherfieldValue,SUM(t2.FDebitTotal) AS  borrow,SUM(t2.FCreditTotal) AS lend
 							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   
							GROUP BY i.FatherfieldValue
		 				)
		 				UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
		 				from #tempIniData i
		 				JOIN T ON i.fieldValue=T.FatherfieldValue AND i.cid=0 	
					END
						
						--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT FatherfieldValue
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  AND t2.ATypeId=@atypeid1 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #tempSonAssistItems i ON  t3.TypeId=i.fieldValue
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1) t
									LEFT JOIN #tempIniData ti  ON t.FatherfieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
									 WHERE FatherfieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
					BEGIN
								INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   FatherfieldValue,
								   0,
								   0,
								   CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempSonAssistItems i ON  t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON FatherfieldValue=ti.fieldValue AND ti.fieldValue IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND FatherfieldValue NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,FatherfieldValue 
					END			
			END
	END
	
---本期累计
CREATE  TABLE #tempPeriodData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	fieldValue   VARCHAR(50),
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
IF @cid>0  --单币别
	 BEGIN
		--原币
	 	INSERT INTO #tempPeriodData
	 	SELECT t1.FYear,t1.FPeriod,i.FatherfieldValue,SUM(t2.FDebitTotalFor),SUM(t2.FCreditTotalFor),0,Cid
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear  AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,i.FatherfieldValue,Cid             
		
		IF @cid<>@selfcid 
			--本位币
			INSERT INTO #tempPeriodData
	 		SELECT t1.FYear,t1.FPeriod,i.FatherfieldValue,SUM(t2.FDebitTotal),SUM(t2.FCreditTotal),0,0
	 		FROM  dbo.Ac_Voucher t1 
			JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
			JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
			JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
			JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
			WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear  AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
			GROUP BY t1.FYear,t1.FPeriod,i.FatherfieldValue,Cid  
	 END
ELSE IF @cid=-1  --所有币别
	BEGIN
 		INSERT INTO #tempPeriodData
 		SELECT t1.FYear,t1.FPeriod,i.FatherfieldValue,SUM(t2.FDebitTotalFor),SUM(t2.FCreditTotalFor),0,Cid
 		FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear  AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
        GROUP BY t1.FYear,t1.FPeriod,i.FatherfieldValue,Cid 
		                          
		--综合本位币
	 	INSERT INTO #tempPeriodData
	 	SELECT FYear,FPeriod,TypeId,SUM(FDebit),SUM(FCredit),0,0
	 	FROM
	 	(
	 		SELECT t1.FYear,t1.FPeriod,i.FatherfieldValue AS typeid,SUM(t2.FDebitTotal) AS FDebit,SUM(t2.FCreditTotal) AS FCredit,0 AS balance,Cid
	 		FROM  dbo.Ac_Voucher t1 
			JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
			JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
			JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
			JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
			WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear  AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1)
			GROUP BY t1.FYear,t1.FPeriod,i.FatherfieldValue,Cid
		) t
		GROUP BY FYear,FPeriod,TypeId 
	END
ELSE --综合本位币
		INSERT INTO #tempPeriodData
	 	SELECT FYear,FPeriod,TypeId,SUM(FDebit),SUM(FCredit),0,0
	 	FROM
	 	(
	 	SELECT t1.FYear,t1.FPeriod,i.FatherfieldValue AS typeid,SUM(t2.FDebitTotal) AS FDebit,SUM(t2.FCreditTotal) AS FCredit,0 AS balance,Cid
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear  AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1)
		GROUP BY t1.FYear,t1.FPeriod,i.FatherfieldValue,Cid
		) t
		GROUP BY FYear,FPeriod,TypeId 
 
---本年累计
CREATE TABLE #tempYearData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	fieldValue   VARCHAR(50),
	qichu		  NUMERIC(24, 10) ,   --多加一列期初
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	yearborrow    NUMERIC(24, 10) ,
	yearlend      NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
--建表

WHILE @iniFpeirod<=@fperiodend
	BEGIN
		IF @cid=-1 --所有币别
			BEGIN
				INSERT INTO #tempYearData 
				SELECT @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,CId FROM 
				(
					SELECT CId FROM dbo.Ac_Currency
					UNION ALL 
					SELECT 0 AS cid 
			    ) c,#tempAllAssistItems i     
			END
		ELSE IF @cid>0 --具体币别
			BEGIN
				IF @cid=@selfcid
					INSERT INTO #tempYearData
					Select @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,@cid
					from #tempAllAssistItems i   
				ELSE 
					INSERT INTO #tempYearData
					Select @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,@cid
					from #tempAllAssistItems i  
					UNION ALL 
					Select @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,0
					from #tempAllAssistItems i  
			END
		else   --综合本位币 
			BEGIN
				INSERT INTO #tempYearData
				Select @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,0
				from #tempAllAssistItems i   
			END
		
		--更新本期数据
		update y set y.borrow=ISNULL(i.borrow,0),y.lend=ISNULL(i.lend,0)
		from #tempYearData y 
		LEFT join #tempPeriodData i on y.fieldValue=i.fieldValue and y.cid=i.cid AND y.fperiod=i.fperiod
	
		--更新开账的期初期初
		if @iniFpeirod=@fperiod
			BEGIN
				--第一期期初
				update y set y.qichu=i.balance 
				from #tempYearData y 
				join #tempIniData i on y.fieldValue=i.fieldValue and y.cid=i.cid
				WHERE y.fperiod=@iniFpeirod
			END
		else 
			BEGIN
				--取上期的期初
				UPDATE y SET y.qichu=y1.balance 
				FROM #tempYearData y 
				JOIN #tempYearData y1 on y.fieldValue=y1.fieldValue and y.cid=y1.cid and y.fperiod=y1.fperiod+1
				where y.fperiod=@iniFpeirod
			end
	   
	   --计算期末
		IF @Fdc=1 
			UPDATE #tempYearData SET balance=qichu+borrow-lend where fperiod=@iniFpeirod 
		ELSE 
			UPDATE #tempYearData SET balance=qichu-borrow+lend where fperiod=@iniFpeirod
		
		--更新年累计数据
		UPDATE y SET y.yearborrow=isnull(T.borrow,0)+isnull(i.borrow,0),y.yearlend=ISNULL(T.lend,0)+ISNULL(i.lend,0)
	    FROM #tempYearData y 
	    LEFT JOIN  
	    ( select @iniFpeirod as fperiod,fieldValue,cid,sum(borrow) as borrow,sum(lend) as lend
	      from #tempPeriodData where fperiod<=@iniFpeirod group by fieldValue,cid ) T 
	    ON y.fperiod=T.fperiod and y.fieldvalue=T.fieldValue and y.cid=T.cid 
	    LEFT JOIN #tempIniData i ON y.fieldvalue=i.fieldValue and y.cid=i.cid 
	    WHERE y.fperiod=@iniFpeirod
			
		SET @iniFpeirod=@iniFpeirod+1      
	END
     
    --筛选不符合条件的项目
    CREATE TABLE #tempItems
    (
		fieldvalue	  varchar(50),
		periodchange   NUMERIC(24, 10) ,
		balance        NUMERIC(24, 10) 
    )
    IF @cid=@selfcid OR @cid=0     --本位币和综合本位币
		insert into #tempItems
		select i.fieldvalue,p.periodchange,b.balance from #tempAllAssistItems i 
		join 
		(    
		SELECT fieldValue,balance FROM #tempYearData where fperiod=@fperiodend
		)  b on b.fieldValue=i.fieldValue
		join 
		(
		SELECT fieldValue,SUM(ABS(borrow))+SUM(ABS(lend)) AS periodchange FROM #tempYearData WHERE fperiod>=@fperiodstart AND fperiod<=@fperiodend group by fieldValue
		) p on p.fieldValue=i.fieldValue
    ELSE 
		insert into #tempItems
		select i.fieldvalue,p.periodchange,b.balance from #tempAllAssistItems i 
		join 
		(    
		SELECT fieldValue,balance FROM #tempYearData where fperiod=@fperiodend and cid=0
		)  b on b.fieldValue=i.fieldValue
		join 
		(
		SELECT fieldValue,SUM(ABS(borrow))+SUM(ABS(lend)) AS periodchange FROM #tempYearData WHERE fperiod>=@fperiodstart AND fperiod<=@fperiodend and cid=0 group by fieldValue
		) p on p.fieldValue=i.fieldValue
       
    IF @cid=0 OR @cid=@selfcid  --本位币单币别或者综合本位币
		SELECT fperiod AS period,
			   usercode AS atypeid,   --报表的穿透功能用此列
			   NAME AS atypename,
			   usercode AS typeusercode,
			   case when qichu=0 then '平' else @fdcname end as beginbalancefdc,
			   qichu as beginbalancetotal,
			   borrow as debit,
			   lend as credit,
			   yearborrow as ytddebit,
			   yearlend as ytdcredit,
			   case when balance=0 then '平' else @fdcname end as endbalancefdc,
			   balance as endbalancetotal
		FROM #tempYearData y 
		JOIN #tempAllAssistItems i ON y.fieldValue=i.fieldValue
		join (
				select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
			 ) t on y.fieldValue=t.fieldValue
		where fperiod>=@fperiodstart
	    order by usercode,fperiod
	ELSE 
		BEGIN
			  -----------------------------------------------------------所有币别是动态列,先求出有多少列----------------------------------------------------------
			 CREATE TABLE #tempColName1
			  (
				cid INT,
				usercode  VARCHAR(200)
			  )
			  IF @cid<>-1  --具体币别
				INSERT INTO #tempColName1
				SELECT CID,USERCODE 
				FROM (SELECT CID,USERCODE FROM AC_CURRENCY WHERE CId=@cid
					  UNION ALL 
					  SELECT 0 AS CID,'' AS USERCODE) b
			  ELSE
				INSERT INTO #tempColName1
			    SELECT CID,USERCODE 
				FROM (SELECT CID,USERCODE FROM AC_CURRENCY
					  UNION ALL 
					  SELECT 0 AS CID,'' AS USERCODE) b
			-----------------------------------------------期初
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColNameqichu
			FROM #tempColName1,(SELECT 'beginbalancetotal' AS COLNAME)T
			
			--行转列的时候用
			DECLARE @qichuTurnCol VARCHAR(MAX)
			SELECT @qichuTurnCol=(ISNULL(@qichuTurnCol+'],[','') +  colname) 
			FROM #tempColNameqichu GROUP BY COLNAME 
			SET @qichuTurnCol='['+@qichuTurnCol+']'
			
			SELECT b.fieldValue,
				   b.fperiod,
			       a.COLNAME,
				   b.qichu AS fvalue
	       INTO #tempqichu
		   FROM #tempColNameqichu a,#tempYearData b WHERE a.cid=b.cid
			---------------------------------------------期末
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColNameqimo
			FROM #tempColName1,(SELECT 'endbalancetotal' AS COLNAME)T
			
			--行转列的时候用
			DECLARE @qimoTurnCol VARCHAR(MAX)
			SELECT @qimoTurnCol=(ISNULL(@qimoTurnCol+'],[','') +  colname) 
			FROM #tempColNameqimo GROUP BY COLNAME 
			SET @qimoTurnCol='['+@qimoTurnCol+']'
			
			SELECT b.fieldValue,
				   b.fperiod,
			       a.COLNAME,
				   b.balance AS fvalue
	       INTO #tempqimo
		   FROM #tempColNameqimo a,#tempYearData b WHERE a.cid=b.cid
			--------------------------------------------借贷
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColNamejd
			FROM #tempColName1,(SELECT 'debit' AS COLNAME
								UNION ALL
								SELECT 'credit' AS COLNAME)T
			
			--行转列的时候用
			DECLARE @jdTurnCol VARCHAR(MAX)
			SELECT @jdTurnCol=(ISNULL(@jdTurnCol+'],[','') +  colname) 
			FROM #tempColNamejd GROUP BY COLNAME 
			SET @jdTurnCol='['+@jdTurnCol+']'
			
			SELECT b.fieldValue,
				   b.fperiod,
			       a.COLNAME,
				   CASE WHEN COLNAME LIKE 'debit'+'%' THEN borrow ELSE lend END AS fvalue
	       INTO #tempjd
		   FROM #tempColNamejd a,(SELECT fieldValue,fperiod,borrow,lend,cid FROM  #tempYearData) b WHERE a.cid=b.cid
		   --------------------------------------------累计借贷
		   SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColNameyjd
			FROM #tempColName1,(SELECT 'ytddebit' AS COLNAME
								UNION ALL
								SELECT 'ytdcredit' AS COLNAME)T
			
			--行转列的时候用
			DECLARE @yjdTurnCol VARCHAR(MAX)
			SELECT @yjdTurnCol=(ISNULL(@yjdTurnCol+'],[','') +  colname) 
			FROM #tempColNameyjd GROUP BY COLNAME 
			SET @yjdTurnCol='['+@yjdTurnCol+']'
			
			SELECT b.fieldValue,
				   b.fperiod,
			       a.COLNAME,
				   CASE WHEN COLNAME LIKE 'ytddebit'+'%' THEN yearborrow ELSE yearlend END AS fvalue
	       INTO #tempyjd
		   FROM #tempColNameyjd a,(SELECT fieldValue,fperiod,yearborrow,yearlend,cid FROM  #tempYearData) b WHERE a.cid=b.cid
			---------------------------------------------全部
			SELECT COLNAME  
			INTO #tempColName2 
			FROM (
			SELECT 'beginbalancetotal' AS COLNAME
			UNION ALL   
			SELECT 'debit' AS COLNAME
			UNION ALL
			SELECT 'credit' AS COLNAME
			UNION ALL 
			SELECT 'endbalancetotal' AS COLNAME
			UNION ALL 
			SELECT 'ytddebit' AS COLNAME
			UNION ALL
			SELECT 'ytdcredit' AS COLNAME
			) a
		     
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID 
			INTO #tempColName
			FROM #tempColName1,#tempColName2
			
			--行转列的时候用
			DECLARE @TurnCol VARCHAR(MAX)
			SELECT @TurnCol=(ISNULL(@TurnCol+'],[','') +  colname) 
			FROM #tempColName GROUP BY COLNAME 
			SET @TurnCol='['+@TurnCol+']'
		
			--------------------------------------------结果
			SET @sql='SELECT a.fieldValue,a.Fperiod,'+@TurnCol+' 
			INTO #tempall 
			FROM #tempYearData a 
			JOIN (
				SELECT *  FROM  #tempqichu  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@qichuTurnCol+')) t
				 ) b ON b.fieldValue=a.fieldValue and a.fperiod=b.fperiod 
			JOIN ( 
				 SELECT *  FROM  #tempqimo  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@qimoTurnCol+') ) t
				 ) c ON c.fieldValue=a.fieldValue and a.fperiod=c.fperiod 
			JOIN (
				SELECT *  FROM  #tempjd  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@jdTurnCol+')) t
				 ) d ON d.fieldValue=a.fieldValue and a.fperiod=d.fperiod 
			JOIN (
				SELECT *  FROM  #tempyjd  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@yjdTurnCol+')) t
				 ) e ON e.fieldValue=a.fieldValue and a.fperiod=e.fperiod   
			where cid=0 
			 
			 SELECT fperiod AS period,
			   usercode as atypeid,
			   NAME AS atypename,
			   usercode AS typeusercode,
			   case when beginbalancetotal=0 then ''平'' else @fdcname end as beginbalancefdc,
			   case when endbalancetotal=0 then ''平'' else @fdcname end as endbalancefdc,
			   '+@TurnCol+'
			FROM #tempall y 
			JOIN #tempAllAssistItems i ON y.fieldValue=i.fieldValue
			join (
					select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
				 ) t on y.fieldValue=t.fieldValue
			where fperiod>=@fperiodstart
			order by usercode,fperiod;
		    
			drop table #tempall'
			 EXEC sp_executesql @SQL,N'@IsBalanceNull INT,@IsBalanceNot INT,@fdcname varchar(10),@fperiodstart INT',@IsBalanceNull,@IsBalanceNot,@fdcname,@fperiodstart
			 
			 DROP TABLE #tempColName,#tempColName1,#tempColName2,#tempColNamejd,#tempColNameqichu,#tempColNameqimo,#tempColNameyjd
		END
	DROP TABLE #tempAllAssistItems,#tempIniData,#tempPeriodData,#tempYearData,#tempItems
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_AuxiliaryAccountTree]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_AuxiliaryAccountTree]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-8-6
	描述：辅助核算项目总账/明细账树查询
*/
CREATE PROCEDURE Web_AuxiliaryAccountTree
(
	@STypeId				VARCHAR(MAX),	--分支机构
	@ATypeId				VARCHAR(MAX),	--科目ID
	@aacategorytypeid		INT,			--辅助类别ID
	@aacategoryprotypeid	VARCHAR(MAX),	--辅助项目ID
	@leveal					INT,			--科目级别
	@fperiodstart			INT,			--开始日期
	@fperiodend				INT,			--结束日期
	@cid					INT,			--币别ID
	@fyear					INT,
	@IsShowNotPost			INT,			--包括未过账凭证:1为是0为否
	@IsBalanceNull			INT,			--项目无发生额不显示:1为是0为否
	@IsBalanceNot			INT,			--项目无余额不显示:1为是0为否
	@chvOperatorID			VARCHAR(50)	--操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON

DECLARE 
	@sql		NVARCHAR(MAX),
	@iniFYear	VARCHAR(5),	--启用年度
	@maxfperiod	INT,		--算年度期初用	 
	@TypeName	VARCHAR(200)--类别编号
--辅助核算类别编号
SELECT @TypeName=UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@aacategorytypeid
	
SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
SELECT @maxfperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE FYear=@fyear-1 AND STypeId=@stypeid
---判断分支机构权限
IF NOT EXISTS ( SELECT *  FROM   dbo.F_GetManDetailAllSType(@chvOperatorID)   WHERE  TypeId = @StypeID ) 
SET @StypeID = ''

	-----------------------------------------处理辅助核算项目---------------------------------------------------------------------------
	----找出要查询的项目的所有子项目
	CREATE TABLE #tempSonAssistItems
	(
		fieldValue  VARCHAR(50),
		FullNAME   NVARCHAR(200),
	    Usercode   NVARCHAR(200)
	)	
IF @aacategorytypeid=1 --分支机构
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				IF EXISTS(SELECT * FROM sysdata WHERE SubName='innerstypesaleralation' AND SubValue=1)  --存在买卖关系
					INSERT INTO #tempSonAssistItems
					SELECT s.TypeId,s.fullname,s.usercode FROM dbo.SType s 
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
					WHERE s.deleted=0  AND s.sonnum=0 AND s.VerifyID=@stypeid
				ELSE 
					INSERT INTO #tempSonAssistItems 
					SELECT s.TypeId,s.fullname,s.usercode FROM dbo.SType s
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
					WHERE s.deleted=0  AND s.sonnum=0
			END
		ELSE     
			BEGIN
				IF EXISTS(SELECT * FROM sysdata WHERE SubName='innerstypesaleralation' AND SubValue=1)  --存在买卖关系
					INSERT INTO #tempSonAssistItems
					SELECT s.TypeId,s.fullname,s.usercode FROM dbo.f_split(@aacategoryprotypeid,',') f 
					JOIN dbo.SType s ON s.TypeId LIKE f.a+'%' AND s.sonnum=0 AND VerifyID=@stypeid
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId 
				ELSE 
					INSERT INTO #tempSonAssistItems
					SELECT s.TypeId,s.fullname,s.usercode FROM dbo.f_split(@aacategoryprotypeid,',') f 
					JOIN dbo.SType s ON s.TypeId LIKE f.a+'%' AND s.sonnum=0 
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId 
			END
	END
ELSE IF @aacategorytypeid=2 --部门
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempSonAssistItems 
				SELECT d.TypeId,d.fullname,d.usercode FROM dbo.Department d 
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID) 
					   ) c ON d.TypeId=c.TypeId
				WHERE d.deleted=0  AND d.sonnum=0 
			END
		ELSE    
			BEGIN
				INSERT INTO #tempSonAssistItems
				SELECT d.typeid,d.fullname,d.usercode FROM dbo.f_split(@aacategoryprotypeid,',') f  
				JOIN dbo.Department d ON d.TypeId LIKE f.a+'%' AND d.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID) 
					   ) c ON d.TypeId=c.TypeId
			END
	END
ELSE IF @aacategorytypeid=3 --职员
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempSonAssistItems 
				SELECT e.TypeId,e.fullname,e.usercode FROM dbo.employee e
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID) 
					   ) c ON e.TypeId=c.TypeId
				WHERE e.deleted=0  AND e.sonnum=0    
			END
		ELSE   
			BEGIN
				INSERT INTO #tempSonAssistItems
				SELECT e.typeId,e.fullname,e.usercode 
				FROM dbo.f_split(@aacategoryprotypeid,',') f  
				JOIN dbo.employee e ON e.TypeId LIKE f.a+'%' AND e.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID) 
					   ) c ON e.TypeId=c.TypeId
			END
	END
ELSE IF @aacategorytypeid=4 --往来单位	
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempSonAssistItems 
				SELECT b.TypeId,b.fullname,b.usercode FROM dbo.btype b
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID) 
					   ) c ON b.TypeId=c.TypeId
				WHERE b.deleted=0  AND b.sonnum=0    
			END
		ELSE    --todo 
			BEGIN
				INSERT INTO #tempSonAssistItems
				SELECT b.typeId,b.fullname,b.usercode FROM dbo.f_split(@aacategoryprotypeid,',') f 
				JOIN dbo.btype b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID) 
					   ) c ON b.TypeId=c.TypeId
			END
	END
ELSE 
	BEGIN
		INSERT INTO #tempSonAssistItems
		SELECT
			D.TypeId,
			D.FullName,
			D.UserCode 
		FROM Ac_Assist_CheckItemsDetail D
		INNER JOIN F_GetAllAssistCheckItemsDetail(@aacategoryprotypeid,@aacategorytypeid,@chvOperatorID) F ON F.TypeId=D.TypeId AND D.AscIds=@aacategorytypeid AND D.SonNum=0
	END
 
   -------------------------------取出所有勾选的科目(都是子科目),存入temp1--------------------------------------------------------------------------------
   CREATE TABLE #temp
   (
	 stypeid VARCHAR(50),
	 typeid VARCHAR(50),
	 fdc    INT
   )
   IF @atypeid=''
		INSERT INTO #temp(stypeid, typeid,fdc)
		SELECT ac.StypeId,ac.TypeId,ac.Fdc FROM 
		(SELECT StypeId,TypeId FROM dbo.Ac_Account WHERE StypeId=@STypeId AND LEVEAL>1 AND FLEVEAL<=@leveal) t 
		JOIN Ac_Account ac ON T.stypeid=ac.stypeid AND ac.typeid LIKE T.typeid+'%' AND ac.SonNum=0 
		INNER JOIN F_TreeAccount(@chvOperatorID,'') F ON F.Typeid=AC.TypeId AND F.Stypeid=AC.StypeId
   ELSE 
		INSERT INTO #temp(stypeid, typeid,fdc)
		SELECT ac.StypeId,ac.TypeId,ac.Fdc FROM 
		(SELECT f.a FROM F_Split(@ATypeId,',') f JOIN Ac_Account aa ON f.a=aa.TypeId AND  aa.StypeId=@STypeId AND aa.LEVEAL>1 AND aa.FLEVEAL<=@leveal) t 
		JOIN Ac_Account ac ON ac.stypeid=@STypeId AND ac.typeid LIKE T.a+'%' AND ac.SonNum=0 
		INNER JOIN F_TreeAccount(@chvOperatorID,'') F ON F.Typeid=AC.TypeId AND F.Stypeid=AC.StypeId
  
  
   CREATE TABLE #temp1
	(
	  STYPEID	 VARCHAR(50),
	  TYPEID	 VARCHAR(50),
	  FDC		 INT
	)	
  SET @SQL='INSERT INTO #temp1
		  SELECT DISTINCT
				 a.STYPEID,
				 a.TYPEID,
				 a.FDC
		  FROM dbo.#temp a
		  JOIN dbo.Ac_Account_Assist_CheckItems ac ON a.StypeId=ac.STypeId AND a.TypeId=ac.ATypeId AND ac.Ascids=@aacategorytypeid '
  IF @cid>0
	SET @SQL+=' AND ac.Cid=@cid '
   
   EXEC sp_executesql @SQL,N'@aacategorytypeid INT,@cid VARCHAR(100)',@aacategorytypeid,@cid
	
     -----科目的各个辅助核算项本期发生额，是查看凭证
	CREATE TABLE #tempSonAccountPeriod
	(
	    --ATYPEID			VARCHAR(50),
	    FIELDVALUE		VARCHAR(50),
	    PERIODCHANGE	 NUMERIC(24, 10) 
	)
	IF @Cid>0  --具体币别  
		INSERT INTO #tempSonAccountPeriod
		SELECT a.FIELDVALUE,ISNULL(t.PERIODCHANGE,0)
		FROM #tempSonAssistItems a 
		LEFT JOIN 
		(
			SELECT i.fieldValue,ISNULL(SUM(ABS(t2.FDebitTotal)),0)+ISNULL(SUM(ABS(t2.FCreditTotal)),0)  AS PERIODCHANGE
	 		FROM  dbo.Ac_Voucher t1 
			JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid
			JOIN #temp1 ac ON t2.ATypeId=ac.TYPEID AND t2.STypeId=ac.STYPEID  
			JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
			JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
			JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
			WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
			GROUP BY i.fieldValue   
		) t ON  a.fieldValue=t.fieldValue
	ELSE   --所有币别
		INSERT INTO #tempSonAccountPeriod
		SELECT a.FIELDVALUE,t.PERIODCHANGE
		FROM #tempSonAssistItems a 
		LEFT JOIN 
		(
		SELECT i.fieldValue,ISNULL(SUM(ABS(t2.FDebitTotalfor)),0)+ISNULL(SUM(ABS(t2.FCreditTotalfor)),0)  AS PERIODCHANGE
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId
		JOIN #temp1 ac ON t2.ATypeId=ac.TYPEID AND t2.STypeId=ac.STYPEID  
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY i.fieldValue     
		 ) t ON  a.fieldValue=t.fieldValue
		 
		 
	----科目的各个辅助核算项目期初
	 CREATE TABLE #tempSonAccountIni
	 (
		ATYPEID			VARCHAR(50),
		FIELDVALUE		VARCHAR(50),
	    INITOTAL		 NUMERIC(24, 10) 
	 )
	 IF @fyear=@inifyear
		BEGIN
			IF @cid>0
				INSERT INTO #tempSonAccountIni
				SELECT ai.ATypeId,i.fieldValue,SUM(IniTotal)                 
				FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail ai
				JOIN #temp1 ac ON  ai.STypeId=ac.STYPEID AND ai.ATypeId=ac.TYPEID
				JOIN #tempSonAssistItems i ON ai.FieldValue=i.fieldValue
				WHERE ai.Cid=@cid AND ai.Ascids=@TypeName 
				GROUP BY ai.ATypeId,i.fieldValue
			ELSE 
				INSERT INTO #tempSonAccountIni
				SELECT ai.ATypeId,i.fieldValue,SUM(IniTotalFor)                 
				FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail ai
				JOIN #temp1 ac ON  ai.STypeId=ac.STYPEID AND ai.ATypeId=ac.TYPEID
				JOIN #tempSonAssistItems i ON ai.FieldValue=i.fieldValue
				WHERE ai.Ascids=@TypeName 
				GROUP BY ai.ATypeId,i.fieldValue
		END
	 ELSE 
		BEGIN
			IF @cid>0
				INSERT INTO #tempSonAccountIni(ATYPEID, FIELDVALUE, INITOTAL)
				SELECT b.ATypeId,b.FieldValue,FEndBalance 
				FROM dbo.Ac_Balance_Assist_CheckItems_Detail b
				JOIN #temp1 ac ON  b.STypeId=ac.STYPEID AND b.ATypeId=ac.TYPEID
				JOIN #tempSonAssistItems i ON b.FieldValue=i.fieldValue
				WHERE b.Ascids=@TypeName AND b.FYear=@fyear-1 AND b.fperiod=@maxfperiod AND b.cid=@cid
			ELSE 
				INSERT INTO #tempSonAccountIni(ATYPEID, FIELDVALUE, INITOTAL)
				SELECT b.ATypeId,b.FieldValue,FEndBalanceFor 
				FROM dbo.Ac_Balance_Assist_CheckItems_Detail b
				JOIN #temp1 ac ON  b.STypeId=ac.STYPEID AND b.ATypeId=ac.TYPEID
				JOIN #tempSonAssistItems i ON b.FieldValue=i.fieldValue
				WHERE b.Ascids=@TypeName AND b.FYear=@fyear-1 AND b.fperiod=@maxfperiod AND b.cid=0
		END
	 
	-----符合条件的凭证,算余额用
	 CREATE TABLE #Voucher
	 (
		ATYPEID     VARCHAR(50),
		FIELDVALUE  VARCHAR(50),
		BORROW      NUMERIC(24, 10) ,
		LEND        NUMERIC(24, 10) ,
	 )	
	 IF @Cid>0  --具体币别  
		INSERT INTO #Voucher
		SELECT ac.TypeId,i.fieldValue,SUM(t2.FDebitTotal),SUM(t2.FCreditTotal)
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid
		JOIN #temp1 ac ON t2.ATypeId=ac.TYPEID AND t2.STypeId=ac.STYPEID  
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue	
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY ac.typeid,i.fieldValue
	ELSE 
		INSERT INTO #Voucher
		SELECT ac.TypeId,i.fieldValue,SUM(t2.FDebitTotalfor),SUM(t2.FCreditTotalfor)
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
		JOIN #temp1 ac ON t2.ATypeId=ac.TYPEID AND t2.STypeId=ac.STYPEID  
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue	
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1)
		GROUP BY ac.typeid,i.fieldValue
	
	------算余额
	CREATE TABLE #tempSonBalance
	(
		Atypeid		VARCHAR(50),
		FIELDVALUE	varchar(50),
		fullname	nvarchar(200),
		usercode	nvarchar(200),
		BALANCE		 NUMERIC(24, 10) 
	)
	--把借贷结果插入期初表，通过sum算余额
	INSERT INTO #tempSonAccountIni
	SELECT v.ATYPEID,
		   v.FIELDVALUE,
		   CASE WHEN t.fdc=1 THEN v.Borrow-v.Lend
		        ELSE v.Lend-v.borrow 
		   END VALUE 
	FROM #Voucher v JOIN #temp1 t ON v.ATYPEID=t.typeid  
	
	INSERT INTO #tempSonBalance
	SELECT ATYPEID,a.FIELDVALUE,a.fullname,a.usercode,SUM(INITOTAL)
	FROM #tempSonAssistItems a
	LEFT JOIN #tempSonAccountIni i  ON i.FIELDVALUE=a.FIELDVALUE   
	GROUP BY i.ATYPEID,a.FIELDVALUE,a.fullname,a.usercode
	------------------------------------------根据查询条件选择符合条件的项目-----------------------------------------------------
	;WITH T AS 
	(
		SELECT b.FIELDVALUE,b.fullname,b.usercode,ISNULL(PERIODCHANGE,0) AS PERIODCHANGE,BALANCE
		FROM #tempSonBalance b
		join #tempSonAccountPeriod p ON b.FIELDVALUE=p.FIELDVALUE
	)
	SELECT DISTINCT fieldValue AS typeid,
		   FullName,
		   USERCODE  
	FROM T 
	WHERE ((@IsBalanceNull=1 AND PERIODCHANGE>0) OR @IsBalanceNull=0) AND
	      ((@IsBalanceNot=1 AND BALANCE<>0) OR @IsBalanceNot=0)
	      
	DROP TABLE #temp,#temp1,#tempSonAccountIni,#tempSonBalance,#Voucher,#tempSonAssistItems
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_AuxiliaryAccountTree1]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].Web_AuxiliaryAccountTree1
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-7-12
	描述：辅助核算项目总账/明细账树查询（科目）
*/
CREATE PROCEDURE Web_AuxiliaryAccountTree1
(
	@stypeid				VARCHAR(MAX),	--分支机构
	@atypeid				VARCHAR(MAX),	--科目ID
	@aacategorytypeid		INT,			--辅助类别ID
	@aacategoryprotypeid	VARCHAR(MAX),	--辅助项目ID
	@fperiodstart			INT,			--开始日期
	@fperiodend				INT,			--结束日期
	@cid					INT,			--币别ID
	@fyear					INT,
	@IsShowNotPost			INT,			--包括未过账凭证:1为是0为否
	@IsProNull				INT,				--科目无发生额不显示:1为是0为否
	@IsProNot				INT,				--科目无余额不显示:1为是0为否
	@chvOperatorID			VARCHAR(100)	--操作员ID
)
--@encode$--
AS 
DECLARE 
	@SQL		NVARCHAR(MAX),	--动态sql语句
	@iniFYear	VARCHAR(5),		--启用年度	 
	@maxfperiod	INT,			--算年度期初用	
	@TypeName	VARCHAR(200)	--类别编号
--辅助核算类别编号
SELECT @TypeName=UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@aacategorytypeid	 

SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
SELECT @maxfperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE FYear=@fyear-1 AND STypeId=@stypeid	  
	-----------------------------------------该职员权限-----------------------------------------------------------------------------------
	IF NOT EXISTS(SELECT * FROM dbo.F_GetManDetailAllSType(@chvOperatorID) WHERE TypeId=@STypeId)
		SET @STypeId=''
	-----------------------------------------处理辅助核算项目---------------------------------------------------------------------------
	----找出要查询的项目的所有子项目
	CREATE TABLE #tempSonAssistItems
	(
		fieldValue  VARCHAR(50)
	)	
	IF @aacategorytypeid=1 --分支机构
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				IF EXISTS(SELECT * FROM sysdata WHERE SubName='innerstypesaleralation' AND SubValue=1)  --存在买卖关系
					INSERT INTO #tempSonAssistItems
					SELECT s.TypeId FROM dbo.SType s 
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
					WHERE s.deleted=0  AND s.sonnum=0 AND s.VerifyID=@stypeid
				ELSE 
					INSERT INTO #tempSonAssistItems 
					SELECT s.TypeId FROM dbo.SType s
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
					WHERE s.deleted=0  AND s.sonnum=0
			END
		ELSE     
			BEGIN
				INSERT INTO #tempSonAssistItems
				SELECT s.TypeId FROM dbo.f_split(@aacategoryprotypeid,',') f 
				JOIN dbo.SType s ON s.TypeId LIKE f.a+'%' AND s.sonnum=0
				JOIN 
				   (
					 SELECT TypeId
					 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
				   ) c ON s.TypeId=c.TypeId
			END
	END
ELSE IF @aacategorytypeid=2 --部门
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempSonAssistItems 
				SELECT d.TypeId FROM dbo.Department d 
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID) 
					   ) c ON d.TypeId=c.TypeId
				WHERE d.deleted=0  AND d.sonnum=0 
			END
		ELSE    
			BEGIN
				INSERT INTO #tempSonAssistItems
				SELECT d.typeid FROM dbo.f_split(@aacategoryprotypeid,',') f  
				JOIN dbo.Department d ON d.TypeId LIKE f.a+'%' AND d.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID) 
					   ) c ON d.TypeId=c.TypeId
			END
	END
ELSE IF @aacategorytypeid=3 --职员
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempSonAssistItems 
				SELECT e.TypeId FROM dbo.employee e
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID) 
					   ) c ON e.TypeId=c.TypeId
				WHERE e.deleted=0  AND e.sonnum=0    
			END
		ELSE   
			BEGIN
				INSERT INTO #tempSonAssistItems
				SELECT e.typeId 
				FROM dbo.f_split(@aacategoryprotypeid,',') f  
				JOIN dbo.employee e ON e.TypeId LIKE f.a+'%' AND e.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID) 
					   ) c ON e.TypeId=c.TypeId
			END
	END
ELSE IF @aacategorytypeid=4 --往来单位	
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempSonAssistItems 
				SELECT b.TypeId FROM dbo.btype b
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID) 
					   ) c ON b.TypeId=c.TypeId
				WHERE b.deleted=0  AND b.sonnum=0    
			END
		ELSE    --todo 
			BEGIN
				INSERT INTO #tempSonAssistItems
				SELECT b.typeId FROM dbo.f_split(@aacategoryprotypeid,',') f 
				JOIN dbo.btype b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID) 
					   ) c ON b.TypeId=c.TypeId
			END
	END
ELSE 
	BEGIN
		INSERT INTO #tempSonAssistItems
		SELECT
			D.TypeId
		FROM Ac_Assist_CheckItemsDetail D
		INNER JOIN F_GetAllAssistCheckItemsDetail(@aacategoryprotypeid,@aacategorytypeid,@chvOperatorID) F ON F.TypeId=D.TypeId AND D.AscIds=@aacategorytypeid AND D.SonNum=0
	END
 
    -------------------------------取出所有勾选的科目(都是子科目),存入temp1--------------------------------------------------------------------------------
	CREATE TABLE #temp1
	(
	  STYPEID	 VARCHAR(50),
	  TYPEID	 VARCHAR(50),
	  FullNAME   VARCHAR(200),
	  Usercode   VARCHAR(200),
	  FDC		 INT
	)	
	IF @ATypeId=''
		BEGIN
			SET @SQL='INSERT INTO #temp1
				  SELECT DISTINCT
						 a.STYPEID,
						 a.TYPEID,
						 a.FULLNAME,
						 a.USERCode,
						 a.FDC
				  FROM dbo.Ac_Account a
				  INNER JOIN F_TreeAccount('''+@chvOperatorID+''','''') F ON F.Typeid=A.TypeId AND F.Stypeid=A.StypeId
				  JOIN dbo.Ac_Account_Assist_CheckItems ac ON a.StypeId=ac.STypeId AND a.TypeId=ac.ATypeId AND ac.Ascids=@aacategorytypeid '
				  IF @cid>0
					SET @SQL+=' AND ac.Cid=@cid '
				  SET @SQL+=' WHERE a.STYPEID=@STypeId AND 
						 
						a.LEVEAL>1 AND 
						a.SONNUM=0' 
			EXEC sp_executesql @SQL,N'@STypeId VARCHAR(50),@aacategorytypeid VARCHAR(MAX),@cid VARCHAR(100)',@STypeId,@aacategorytypeid,@cid
		END
	ELSE
		BEGIN	
			SET @SQL='INSERT INTO #temp1
					SELECT DISTINCT
						   d.STYPEID,
					       d.TYPEID,
					       d.FULLNAME,
						   d.USERCode,
					       d.FDC 
					FROM dbo.Ac_Account d
				    INNER JOIN F_TreeAccount('''+@chvOperatorID+''','''') F ON F.Typeid=D.TypeId AND F.Stypeid=D.StypeId
					JOIN dbo.Ac_Account_Assist_CheckItems ac ON d.StypeId=ac.STypeId AND d.TypeId=ac.ATypeId AND ac.Ascids=@aacategorytypeid '
					IF @cid>0
						SET @SQL+=' AND ac.Cid=@cid'
					SET @SQL+='
					JOIN 
					(
	    				 SELECT a AS TYPEID 
		    			 FROM (SELECT a FROM F_Split(@ATypeId,'','')) b
					) c ON d.TYPEID=c.TYPEID 
					WHERE d.STYPEID=@STypeId AND 
						  d.LEVEAL>1 AND 
						  d.SONNUM=0'
	 
			EXEC sp_executesql @SQL,N'@STypeId VARCHAR(50),@ATypeId VARCHAR(MAX),@aacategorytypeid INT,@cid VARCHAR(100)',@STypeId,@ATypeId,@aacategorytypeid,@cid
		END
		
	 -----子科目的本期发生额，是查看凭证，而不是查看acbalance表
	CREATE TABLE #tempSonAccountPeriod
	(
	    TYPEID			VARCHAR(50),
	    PERIODCHANGE	 NUMERIC(24, 10) 
	)
	IF @Cid>0  --具体币别  
		INSERT INTO #tempSonAccountPeriod
		SELECT ac.TypeId,SUM(ABS(t2.FDebitTotal))+SUM(ABS(t2.FCreditTotal)) 
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid
		JOIN #temp1 ac ON t2.ATypeId=ac.TYPEID AND t2.STypeId=ac.STYPEID  
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY ac.TYPEID            
	ELSE   --所有币别
		INSERT INTO #tempSonAccountPeriod
		SELECT ac.TypeId,SUM(ABS(t2.FDebitTotalfor))+SUM(ABS(t2.FCreditTotalfor)) 
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId
		JOIN #temp1 ac ON t2.ATypeId=ac.TYPEID AND t2.STypeId=ac.STYPEID  
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY ac.TYPEID     
	 -----------------------期初---------------------------------------------------------------------------------------	
	 CREATE TABLE #tempSonAccountIni
	 (
		TYPEID			VARCHAR(50),
	    INITOTAL		 NUMERIC(24, 10) 
	 )
	 IF @fyear=@inifyear
		BEGIN
			IF @cid>0
				INSERT INTO #tempSonAccountIni
				SELECT ai.ATypeId,SUM(IniTotal)                 
				FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail ai
				JOIN #temp1 ac ON  ai.STypeId=ac.STYPEID AND ai.ATypeId=ac.TYPEID
				JOIN #tempSonAssistItems i ON ai.FieldValue=i.fieldValue
				WHERE ai.Cid=@cid AND ai.Ascids=@TypeName 
				GROUP BY ai.ATypeId
			ELSE 
				INSERT INTO #tempSonAccountIni
				SELECT ai.ATypeId,SUM(IniTotalFor)                 
				FROM dbo.Ac_IniAccount_Assist_CheckItems_Detail ai
				JOIN #temp1 ac ON  ai.STypeId=ac.STYPEID AND ai.ATypeId=ac.TYPEID
				JOIN #tempSonAssistItems i ON ai.FieldValue=i.fieldValue
				WHERE ai.Ascids=@TypeName 
				GROUP BY ai.ATypeId
		END
	ELSE
		BEGIN
			IF @cid>0
				INSERT INTO #tempSonAccountIni
				SELECT ai.ATypeId,ai.FEndBalance               
				FROM dbo.Ac_Balance_Assist_CheckItems_Detail ai
				JOIN #temp1 ac ON  ai.STypeId=ac.STYPEID AND ai.ATypeId=ac.TYPEID
				JOIN #tempSonAssistItems i ON ai.FieldValue=i.fieldValue
				WHERE ai.Cid=@cid AND ai.Ascids=@TypeName AND ai.fperiod=@maxfperiod AND ai.FYear=@fyear-1
			ELSE 
				INSERT INTO #tempSonAccountIni
				SELECT ai.ATypeId,FEndBalanceFor               
				FROM dbo.Ac_Balance_Assist_CheckItems_Detail ai
				JOIN #temp1 ac ON  ai.STypeId=ac.STYPEID AND ai.ATypeId=ac.TYPEID
				JOIN #tempSonAssistItems i ON ai.FieldValue=i.fieldValue
				WHERE ai.Ascids=@TypeName AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod AND cid=0
		END 
 
	-----符合条件的凭证,算余额用
	 CREATE TABLE #Voucher
	 (
		typeid     VARCHAR(50),
		borrow      NUMERIC(24, 10) ,
		lend        NUMERIC(24, 10) ,
	 )	
	 IF @Cid>0  --具体币别  
		INSERT INTO #Voucher
		SELECT ac.TypeId,SUM(t2.FDebitTotal),SUM(t2.FCreditTotal)
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid
		JOIN #temp1 ac ON t2.ATypeId=ac.TYPEID AND t2.STypeId=ac.STYPEID  
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue	
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY ac.typeid
	ELSE 
		INSERT INTO #Voucher
		SELECT ac.TypeId,SUM(t2.FDebitTotalfor),SUM(t2.FCreditTotalfor)
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
		JOIN #temp1 ac ON t2.ATypeId=ac.TYPEID AND t2.STypeId=ac.STYPEID  
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempSonAssistItems i ON t3.TypeId=i.fieldValue	
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1)
		GROUP BY ac.typeid
		 	
	------算余额
	CREATE TABLE #tempSonAccountBalance
	(
		TYpeid  VARCHAR(50),
		fullname VARCHAR(200),
		usercode VARCHAR(200), 
		BALANCE	 NUMERIC(24, 10) 
	)
	INSERT INTO #tempSonAccountBalance
	SELECT a.typeid,
		   a.fullname,
		   a.usercode,
		   CASE WHEN a.fdc=1 then isnull(i.INITOTAL,0)+isnull(v.borrow,0)-isnull(v.lend,0)
							  else isnull(i.INITOTAL,0)-isnull(v.borrow,0)+isnull(v.lend,0) 
		   END 
	FROM #temp1 a
	LEFT JOIN #tempSonAccountIni i ON a.TYPEID=i.typeid
	LEFT JOIN #Voucher v ON a.TYPEID=v.typeid
	------------------------------------------根据查询条件，从#AccountData选择符合条件的科目-----------------------------------------------------
	;WITH T AS 
	(
		SELECT b.typeid,b.fullname,b.usercode,ISNULL(PERIODCHANGE,0) AS PERIODCHANGE,BALANCE
		FROM #tempSonAccountBalance b
		left join #tempSonAccountPeriod p ON b.TYpeid=p.TYPEID
	)
	SELECT DISTINCT T.TYPEID,
		   T.FullName,
		   T.USERCODE  
	FROM T 
	WHERE ((@IsProNull=1 AND PERIODCHANGE>0) OR @IsProNull=0) AND
	      ((@IsProNot=1 AND BALANCE<>0) OR @IsProNot=0)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_AuxiliaryDetailedAccount]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_AuxiliaryDetailedAccount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-07-21
	描述：辅助核算明细账
*/
CREATE PROCEDURE Web_AuxiliaryDetailedAccount
(
	@aacategorytypeid		INT,			--辅助类别ID
	@typeid					VARCHAR(MAX),	--辅助核算明细ID
	@atypeid				VARCHAR(MAX),	--科目ID
	@stypeid				VARCHAR(MAX),	--分支机构
	@fyear					INT,			--年度
	@fperiodstart			INT,			--开始日期
	@fperiodend				INT,			--结束日期
	@cid					INT,			--币别ID
	@IsShowNotPost			INT,			--包括未过账凭证:1为是0为否
	@IsProNull				INT,			--科目无发生额不显示:1为是0为否
	@IsProNot				INT, 			--科目无余额项目不显示:1为是0为否
	@chvOperatorID			VARCHAR(100)	--操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON
DECLARE 
	@sql		NVARCHAR(MAX),
	@fperiod	INT,
	@iniFYear	VARCHAR(5),	--启用年度	 
	@maxfperiod	INT,		--算年度期初用	
	@TypeName	VARCHAR(200),--辅助核算类别编号
	@LimitOwnVoucher INT=0--仅能查看本人制单的会计凭证
		
SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@chvOperatorID
	
--辅助核算类别编号
SELECT @TypeName=UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@aacategorytypeid 
		      
SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
SELECT @maxfperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE FYear=@fyear-1 AND STypeId=@stypeid	  
IF @iniFYear=@Fyear
	SELECT @FPeriod=SFPeriod from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
ELSE 
	SELECT @Fperiod=MIN(CONVERT(INT,FPeriod)) FROM dbo.Ac_Period		 			 
---判断分支机构权限
 IF NOT EXISTS ( SELECT *  FROM   dbo.F_GetManDetailAllSType(@chvOperatorID)   WHERE  TypeId = @StypeID ) 
    SET @StypeID = ''

--本位币
DECLARE @selfcid INT
SELECT @selfcid=CId FROM dbo.Ac_Currency WHERE Sysrow=1

BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
	INSERT INTO #Ac_Account_L (Typeid,StypeId) 
	SELECT L.Typeid,L.Stypeid FROM F_TreeAccount(@chvOperatorID,'') L
END; 
---根据提取要查询的科目(只显示子科目)
CREATE TABLE #temp1
(
	atypeid   VARCHAR(50),
	NAME		NVARCHAR(200),
	usercode    NVARCHAR(200),
	fdc         INT
)	
 
IF @atypeid=''
	BEGIN
		INSERT INTO #temp1
		SELECT DISTINCT A.TypeId,FullName,UserCode,Fdc
		FROM dbo.Ac_Account a 
		INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND L.StypeId=A.StypeId
		JOIN  Ac_Account_Assist_CheckItems aa ON aa.ATypeId=a.TypeId AND aa.STypeId=a.StypeId AND ((@cid>0 AND aa.cid=@cid) OR @cid<=0) AND aa.Ascids=@aacategorytypeid
		WHERE a.StypeId=@stypeid AND SonNum=0
		ORDER BY A.TypeId
	END
ELSE 
	INSERT INTO #temp1
	SELECT DISTINCT f.a,a.FullName,UserCode,Fdc 
	FROM dbo.f_split(@atypeid,',') f 
	JOIN dbo.Ac_Account a ON f.a=a.TypeId AND a.StypeId=@stypeid AND a.SonNum=0   
	INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND L.StypeId=A.StypeId  
	JOIN  Ac_Account_Assist_CheckItems aa ON aa.ATypeId=a.TypeId AND aa.STypeId=a.StypeId AND ((@cid>0 AND aa.cid=@cid) OR @cid<=0) AND aa.Ascids=@aacategorytypeid
 
 -----期初数据
CREATE TABLE #tempIniData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	atypeid      VARCHAR(50),
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
IF @cid>0
	BEGIN
		IF @iniFYear=@Fyear
			BEGIN
				---原币
				INSERT INTO #tempIniData
				SELECT ai.FYear,ai.FPeriod,a.atypeid,SUM(FDebitFor) AS borrow,SUM(FCreditFor) AS lend,SUM(IniTotalFor) AS balance,Cid
				FROM #temp1  a 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND cid=@cid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
				GROUP BY ai.FYear,ai.FPeriod,a.atypeid,Cid
				
				IF @cid<>@selfcid 
					---本位币
					INSERT INTO #tempIniData
					SELECT ai.FYear,ai.FPeriod,a.atypeid,SUM(FDebit) AS borrow,SUM(FCredit) AS lend,SUM(IniTotal) AS balance,0
					FROM #temp1  a 
					JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND cid=@cid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
					GROUP BY ai.FYear,ai.FPeriod,a.atypeid
			END
		ELSE 
			BEGIN
				---原币
				INSERT INTO #tempIniData
				SELECT ai.FYear,ai.FPeriod,a.atypeid,
						0 AS borrow,--SUM(FDebitFor) AS borrow,
						0 AS lend,--SUM(FCreditFor) AS lend,
						SUM(FEndBalanceFor) AS balance,Cid
				FROM #temp1  a 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND cid=@cid 
																	AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid  AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod
				GROUP BY ai.FYear,ai.FPeriod,a.atypeid,Cid
				 
				 --特殊情况
				IF @IsShowNotPost=1
					BEGIN
						--修复上一年没数据，只有未过账凭证，没期初的情况
						IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT a.atypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp1 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1  AND Cid=@cid) t WHERE atypeid NOT IN (SELECT atypeid FROM #tempIniData))
							BEGIN
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   a.atypeid,0,0,0,Cid
	 									FROM  dbo.Ac_Voucher t1 
										JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
										JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
										JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
										JOIN #temp1 a ON a.atypeid=t2.ATypeId 
										WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1  AND Cid=@cid
										AND a.atypeid NOT IN (SELECT atypeid FROM #tempIniData)
										
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
							       a.atypeid,0,0,0,0
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp1 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.Fperiod>=@maxfperiod AND t1.FYear=@Fyear-1  
											AND a.atypeid NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							END
								 
						
						---更新期初
						;WITH T AS
						(
						SELECT a.atypeid,SUM(t2.FDebitTotalFor) AS borrow,SUM(t2.FCreditTotalFor) AS lend,Cid,a.fdc
	 					FROM  dbo.Ac_Voucher t1 
						JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
						JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
						JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
						JOIN #temp1 a ON a.atypeid=t2.ATypeId 
						WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
						GROUP BY a.atypeid,a.fdc,Cid
						)
						UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.atypeid=T.atypeid AND i.cid=T.cid 
					END
			    	 --特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				 	IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT a.atypeid  
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp1 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid) t
									LEFT JOIN #tempIniData ti  ON t.atypeid=ti.atypeid AND ti.atypeid IS NULL 
									WHERE t.atypeid NOT IN (SELECT atypeid FROM #tempIniData))
				 	BEGIN
				 		 	INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						           a.atypeid,
						           0,
						           0,
						           CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotal)- SUM(t2.FCreditTotal) ELSE SUM(t2.FCreditTotal)-SUM(t2.FDebitTotal) END  ,
						           t2.Cid
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp1 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti  ON a.atypeid=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  AND t2.Cid=@cid 
							AND a.atypeid NOT IN (SELECT atypeid FROM #tempIniData)	
							GROUP BY t1.FYear,a.atypeid,t2.cid,a.fdc
						 
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   a.atypeid,
								   0,
								   0,
								   CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp1 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti ON a.atypeid=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND a.atypeid NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,a.atypeid,a.fdc
				 	END
				IF @cid<>@selfcid 
					BEGIN
						---本位币
						INSERT INTO #tempIniData
						SELECT ai.FYear,ai.FPeriod,a.atypeid,
						0 AS borrow,--SUM(FDebit) AS borrow,
						0 AS lend,--SUM(FCredit) AS lend,
						SUM(FEndBalance) AS balance,0
						FROM #temp1  a 
						JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND cid=@cid 
																			AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid  AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod
						GROUP BY ai.FYear,ai.FPeriod,a.atypeid
						
						IF @IsShowNotPost=1
							WITH T AS
							(
							SELECT a.atypeid,SUM(t2.FDebitTotal) AS borrow,SUM(t2.FCreditTotal) AS lend,Cid,a.fdc
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp1 a ON a.atypeid=t2.ATypeId 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
							GROUP BY a.atypeid,a.fdc,Cid
							)
							UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 				from #tempIniData i
			 				JOIN T ON i.atypeid=T.atypeid AND i.cid=0
					END
			END
	END
ELSE IF @cid=-1  --所有币别
	BEGIN
		IF @iniFYear=@Fyear
			BEGIN
				INSERT INTO #tempIniData
				SELECT ai.FYear,ai.FPeriod,a.atypeid,SUM(FDebitFor) AS borrow,SUM(FCreditFor) AS lend,SUM(IniTotalFor) AS  balance,cid
				FROM #temp1  a 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
				GROUP BY ai.FYear,ai.FPeriod,a.atypeid,cid 
				
				---综合本位币
				INSERT INTO #tempIniData
				SELECT ai.FYear,ai.FPeriod,a.atypeid,SUM(FDebit) AS borrow,SUM(FCredit) AS lend,SUM(IniTotal) AS  balance,0
				FROM #temp1  a 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
				GROUP BY ai.FYear,ai.FPeriod,a.atypeid
			END
		ELSE 
			BEGIN
				INSERT INTO #tempIniData
				SELECT ai.FYear,ai.FPeriod,a.atypeid,
				0,--SUM(FDebitFor) AS borrow,
				0,--SUM(FCreditFor) AS lend,
				SUM(FEndBalanceFor) AS  balance,cid
				FROM #temp1  a 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid 
																	AND ai.FieldValue=@typeid AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod AND ai.cid<>0
				GROUP BY ai.FYear,ai.FPeriod,a.atypeid,cid 
				
				---综合本位币
				INSERT INTO #tempIniData
				SELECT ai.FYear,ai.FPeriod,a.atypeid,
				0,--SUM(FDebit) AS borrow,
				0,--SUM(FCredit) AS lend,
				SUM(FEndBalance) AS  balance,0
				FROM #temp1  a 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid 
																	AND ai.FieldValue=@typeid AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod AND ai.Cid<>0
				GROUP BY ai.FYear,ai.FPeriod,a.atypeid
				
				IF @IsShowNotPost=1
					BEGIN
						--修复上一年没数据，只有未过账凭证，没期初的情况
						IF EXISTS(SELECT TOP 1 1 FROM (SELECT a.atypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp1 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1) T WHERE atypeid NOT IN (SELECT atypeid FROM #tempIniData))
							BEGIN
									INSERT INTO #tempIniData 
									SELECT DISTINCT t1.FYear,12,--期间随便写
										   a.atypeid,0,0,0,Cid
	 										FROM  dbo.Ac_Voucher t1 
											JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
											JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
											JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
											JOIN #temp1 a ON a.atypeid=t2.ATypeId 
											WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
													AND a.atypeid NOT IN (SELECT atypeid FROM #tempIniData)
													
								    INSERT INTO #tempIniData 
									SELECT DISTINCT t1.FYear,12,--期间随便写
										   a.atypeid,0,0,0,0
	 										FROM  dbo.Ac_Voucher t1 
											JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
											JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
											JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
											JOIN #temp1 a ON a.atypeid=t2.ATypeId 
											WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
													AND a.atypeid NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							END
							
						;WITH T AS
						(
						SELECT a.atypeid,SUM(t2.FDebitTotalFor) AS borrow,SUM(t2.FCreditTotalFor) AS lend,Cid,a.fdc
	 					FROM  dbo.Ac_Voucher t1 
						JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
						JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
						JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
						JOIN #temp1 a ON a.atypeid=t2.ATypeId 
						WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
						GROUP BY a.atypeid,a.fdc,Cid
						)
						UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.atypeid=T.atypeid AND i.cid=T.cid 
			 			
			 			--综合本位币
			 			;WITH T AS
						(
						SELECT a.atypeid,SUM(t2.FDebitTotal) AS borrow,SUM(t2.FCreditTotal) AS lend,a.fdc
	 					FROM  dbo.Ac_Voucher t1 
						JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
						JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
						JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
						JOIN #temp1 a ON a.atypeid=t2.ATypeId 
						WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
						GROUP BY a.atypeid,a.fdc
						)
						UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.atypeid=T.atypeid AND i.cid=0
					END
					
					--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT a.ATypeId 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp1 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1) t
									LEFT JOIN #tempIniData ti  ON t.ATypeId=ti.atypeid AND ti.atypeid IS NULL 
									WHERE t.ATypeId NOT IN (SELECT atypeid FROM #tempIniData))
					BEGIN
						    INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						           a.ATypeId,
						           0,
						           0,
						           CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotal)- SUM(t2.FCreditTotal) ELSE SUM(t2.FCreditTotal)-SUM(t2.FDebitTotal) END  ,
						           t2.Cid
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp1 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti  ON a.ATypeId=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  
							AND a.ATypeId NOT IN (SELECT atypeid FROM #tempIniData)	
							GROUP BY t1.FYear,a.ATypeId,t2.cid,a.fdc
						 
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   a.ATypeId,
								   0,
								   0,
								   CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp1 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti ON a.ATypeId=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND a.ATypeId NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,a.ATypeId,a.fdc
					END				
			END
	END
ELSE ---综合本位币
	BEGIN
		IF @iniFYear=@Fyear
			INSERT INTO #tempIniData
			SELECT ai.FYear,ai.FPeriod,a.atypeid,SUM(FDebit) AS borrow,SUM(FCredit) AS lend,SUM(IniTotal) AS  balance,0
			FROM #temp1  a 
			JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid AND ai.FieldValue=@typeid
			GROUP BY ai.FYear,ai.FPeriod,a.atypeid
		ELSE 
			BEGIN
				INSERT INTO #tempIniData
				SELECT ai.FYear,ai.FPeriod,a.atypeid,
						0,--SUM(FDebit) AS borrow,
						0,--SUM(FCredit) AS lend,
				SUM(FEndBalance) AS  balance,0
				FROM #temp1  a 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON a.atypeid=ai.atypeid AND ai.stypeid=@stypeid AND Ascids=@aacategorytypeid 
																	AND ai.FieldValue=@typeid AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod AND ai.cid<>0
				GROUP BY ai.FYear,ai.FPeriod,a.atypeid
			
				IF @IsShowNotPost=1
					BEGIN
						IF EXISTS(SELECT TOP 1 1 FROM (
									SELECT a.atypeid 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp1 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1) T WHERE atypeid NOT IN (SELECT atypeid FROM #tempIniData))
							  INSERT INTO #tempIniData 
							  SELECT DISTINCT t1.FYear,12,--期间随便写
						        a.atypeid,0,0,0,0
 								FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #temp1 a ON a.atypeid=t2.ATypeId 
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
										AND a.atypeid NOT IN (SELECT atypeid FROM #tempIniData)	
						
						;WITH T AS
						(
						SELECT a.atypeid,SUM(t2.FDebitTotal) AS borrow,SUM(t2.FCreditTotal) AS lend,a.fdc
						FROM  dbo.Ac_Voucher t1 
						JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
						JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
						JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
						JOIN #temp1 a ON a.atypeid=t2.ATypeId 
						WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
						GROUP BY a.atypeid,a.fdc
						)
						UPDATE i SET i.balance+=(CASE WHEN T.fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
	 					from #tempIniData i
	 					JOIN T ON i.atypeid=T.atypeid AND i.cid=0
					END
					
				--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT a.ATypeId 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #temp1 a ON a.atypeid=t2.ATypeId 
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1) t
									LEFT JOIN #tempIniData ti  ON t.ATypeId=ti.atypeid AND ti.atypeid IS NULL 
									WHERE t.ATypeId NOT IN (SELECT atypeid FROM #tempIniData))
					BEGIN
								INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   a.ATypeId,
								   0,
								   0,
								   CASE WHEN a.fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #temp1 a ON a.atypeid=t2.ATypeId 
							LEFT JOIN #tempIniData ti ON a.ATypeId=ti.atypeid AND ti.atypeid IS NULL
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND a.ATypeId NOT IN (SELECT atypeid FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,a.ATypeId,a.fdc
					END			
			END
			
	END
	
 
---本期累计
CREATE  TABLE #tempPeriodData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	atypeid	     VARCHAR(50),
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
IF @cid>0
	BEGIN
		INSERT INTO #tempPeriodData
	 	SELECT t1.FYear,t1.FPeriod,a.atypeid,SUM(t2.FDebitTotalFor),SUM(t2.FCreditTotalFor),0,Cid
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #temp1 a ON a.atypeid=t2.ATypeId 
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,a.atypeid,Cid    
		
		IF @cid<>@selfcid 
			---本位币 
			INSERT INTO #tempPeriodData
	 		SELECT t1.FYear,t1.FPeriod,a.atypeid,SUM(t2.FDebitTotal),SUM(t2.FCreditTotal),0,0
	 		FROM  dbo.Ac_Voucher t1 
			JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
			JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
			JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
			JOIN #temp1 a ON a.atypeid=t2.ATypeId 
			WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
			GROUP BY t1.FYear,t1.FPeriod,a.atypeid
	END
ELSE IF @cid=-1  --所有币别
	BEGIN
		INSERT INTO #tempPeriodData
	 	SELECT t1.FYear,t1.FPeriod,a.atypeid,SUM(t2.FDebitTotalFor),SUM(t2.FCreditTotalFor),0,Cid
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #temp1 a ON a.atypeid=t2.ATypeId 
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,a.atypeid,Cid  
		
		--综合本位币
	 	INSERT INTO #tempPeriodData
 		SELECT t1.FYear,t1.FPeriod,a.atypeid,SUM(t2.FDebitTotal) AS FDebit,SUM(t2.FCreditTotal) AS FCredit,0,0
 		FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #temp1 a ON a.atypeid=t2.ATypeId 
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,a.atypeid 
	END
 ELSE   --综合本位币
	INSERT INTO #tempPeriodData
	SELECT t1.FYear,t1.FPeriod,a.atypeid,SUM(t2.FDebitTotal) AS FDebit,SUM(t2.FCreditTotal) AS FCredit,0,0
	FROM  dbo.Ac_Voucher t1 
	JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId 
	JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
	JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
	JOIN #temp1 a ON a.atypeid=t2.ATypeId 
	WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
	GROUP BY t1.FYear,t1.FPeriod,a.atypeid 
  
 
---本年累计
CREATE TABLE #tempYearData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	atypeid   VARCHAR(50),
	fdc			INT,
	qichu		  NUMERIC(24, 10) ,   --多加一列期初
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	yearborrow    NUMERIC(24, 10) ,
	yearlend      NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
--建表
DECLARE @iniFpeirod INT=@fperiod
WHILE @iniFpeirod<=@fperiodend
	BEGIN
		IF @cid=-1 --所有币别
			BEGIN
				INSERT INTO #tempYearData 
				SELECT @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,CId FROM 
				(
			    SELECT CId FROM dbo.Ac_Currency
			    UNION ALL 
			    SELECT 0 AS cid 
			    ) c,#temp1 i     
			END
		ELSE IF @cid>0 --具体币别
			BEGIN
				IF @cid=@selfcid
					INSERT INTO #tempYearData
					Select @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,@cid
					from #temp1 i   
				ELSE 
					INSERT INTO #tempYearData
					Select @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,@cid
					from #temp1 i  
					UNION ALL 
					Select @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,0
					from #temp1 i  
			END
		else   --综合本位币 
			BEGIN
				INSERT INTO #tempYearData
				Select @FYear,@iniFpeirod,atypeid,i.fdc,0,0,0,0,0,0,0
				from #temp1 i   
			END
		
		--更新本期数据
		update y set y.borrow=ISNULL(i.borrow,0),y.lend=ISNULL(i.lend,0)
		from #tempYearData y 
		LEFT join #tempPeriodData i on y.atypeid=i.atypeid and y.cid=i.cid AND y.fperiod=i.fperiod
	    
		--更新开账的期初 
		if @iniFpeirod=@fperiod
			BEGIN
				--第一期期初
				update y set y.qichu=i.balance 
				from #tempYearData y 
				join #tempIniData i on y.atypeid=i.atypeid and y.cid=i.cid
				WHERE y.fperiod=@iniFpeirod
			END
		else 
			BEGIN
				--取上期的期初
				UPDATE y SET y.qichu=y1.balance 
				FROM #tempYearData y 
				JOIN #tempYearData y1 on y.atypeid=y1.atypeid and y.cid=y1.cid and y.fperiod=y1.fperiod+1
				where y.fperiod=@iniFpeirod
			end
	   
	   --计算期末
		UPDATE #tempYearData SET balance=(CASE WHEN fdc=1 THEN qichu+borrow-lend
											   ELSE  qichu-borrow+lend
										  END)
		
		--更新年累计数据
		UPDATE y SET y.yearborrow=isnull(T.borrow,0)+isnull(i.borrow,0),y.yearlend=ISNULL(T.lend,0)+ISNULL(i.lend,0)
	    FROM #tempYearData y 
	    LEFT JOIN  
	    ( select @iniFpeirod as fperiod,atypeid,cid,sum(borrow) as borrow,sum(lend) as lend
	      from #tempPeriodData where fperiod<=@iniFpeirod group by atypeid,cid ) T 
	    ON y.fperiod=T.fperiod and y.atypeid=T.atypeid and y.cid=T.cid 
	    LEFT JOIN #tempIniData i ON y.atypeid=i.atypeid and y.cid=i.cid 
	    WHERE y.fperiod=@iniFpeirod
			 
		SET @iniFpeirod=@iniFpeirod+1      
	END
 
    --筛选不符合条件的科目
    CREATE TABLE #tempItems
    (
		atypeid		  varchar(50),
		periodchange   NUMERIC(24, 10) ,
		balance        NUMERIC(24, 10) 
    )
     IF @cid=@selfcid OR @cid=0     --本位币和综合本位币 
		insert into #tempItems
		select i.atypeid,p.periodchange,b.balance from #temp1 i 
		join 
		(    
		SELECT atypeid,balance FROM #tempYearData where fperiod=@fperiodend
		)  b on b.atypeid=i.atypeid
		join 
		(
		SELECT atypeid,SUM(ABS(borrow))+SUM(ABS(lend)) AS periodchange FROM #tempYearData WHERE fperiod>=@fperiodstart AND fperiod<=@fperiodend group by atypeid
		) p on p.atypeid=i.atypeid
     ELSE   --所有币别或外币，直接看综合本位币
		insert into #tempItems
		select i.atypeid,p.periodchange,b.balance from #temp1 i 
		join 
		(    
		SELECT atypeid,balance FROM #tempYearData where fperiod=@fperiodend and cid=0
		)  b on b.atypeid=i.atypeid
		join 
		(
		SELECT atypeid,SUM(ABS(borrow))+SUM(ABS(lend)) AS periodchange FROM #tempYearData WHERE fperiod>=@fperiodstart AND fperiod<=@fperiodend and cid=0 group by atypeid
		) p on p.atypeid=i.atypeid
         
 ---------------------凭证
 CREATE TABLE #Voucher
 (
	orderid    INT IDENTITY(1,1),   --算余额的排序列
	atypeid	  varchar(50),
	cid         INT,
	fyear        VARCHAR(10),
	fperiod		 INT,
	BILLNUMBERID  INT,
	BILLDATE     DATE,
	FSERIALNAME		VARCHAR(200),			--凭证字号
	vouchertype  NVARCHAR(100),  --凭证类型 
	summary      NVARCHAR(500),
	fdc          VARCHAR(10),
	tempfdc		INT,
	borrow		 NUMERIC(24, 10) ,
	lend		 NUMERIC(24, 10) ,
	endbalance		 NUMERIC(24, 10) ,     --余额
	selfborrow	 NUMERIC(24, 10) ,
	selflend		 NUMERIC(24, 10) ,
	selfendbalance		 NUMERIC(24, 10) ,
	ETypeId		VARCHAR(50) NOT NULL DEFAULT('')--制单人
 )
INSERT INTO #Voucher
SELECT  i.atypeid,
		t2.cid,
		t1.fyear,
		t1.fperiod,
		t1.BILLNUMBERID,
		t1.BILLDATE,
		CASE WHEN @LimitOwnVoucher=1 AND T1.ETypeId<>@chvOperatorID THEN '****' ELSE t5.FullName+'-'+CONVERT(VARCHAR(10),t1.FlowNo) END,
		at.FullName,
		 CASE WHEN @LimitOwnVoucher=1 AND T1.ETypeId<>@chvOperatorID THEN '****' ELSE dbo.F_GetSummaryByLimit(t2.ID,@chvOperatorID,t2.STypeID,t2.Summary) END Summary,
		   CASE WHEN i.fdc=1 THEN '借' ELSE '贷'  END,
		   i.fdc,
		   t2.FDebitTotalFor,
		   t2.FCreditTotalFor,
		   0,
		   t2.FDebitTotal,
		   t2.FCreditTotal,
		   0,
		   t1.ETypeId
FROM  dbo.Ac_Voucher t1 
JOIN Ac_VoucherType at ON t1.VoucherType=at.id 
JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND ((@cid>0 AND t2.Cid=@cid ) OR @cid<=0)
JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName AND t3.TypeId=@typeid
JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
JOIN #temp1 i ON i.atypeid=t2.ATypeId 
WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) AND t1.FYear=@Fyear
ORDER BY t1.fperiod,i.atypeid,t1.BILLDATE,t1.BILLNUMBERID   
       
----计算余额
SET @sql='
			UPDATE v SET v.endbalance=(case when v.tempfdc=1 then  y.qichu+v1.borrow-v1.lend 
											else y.qichu-v1.borrow+v1.lend end ) 
			FROM #Voucher v 
			JOIN 
			(
				SELECT t.orderid,t.atypeid,t.fperiod,t.cid,SUM(t1.borrow) as borrow,SUM(t1.lend) as lend 
				FROM #Voucher t 
				JOIN #Voucher t1 ON t.atypeid=t1.atypeid AND t.fperiod=t1.fperiod AND t1.orderid<=t.orderid AND t.cid=t1.cid
				GROUP BY t.orderid,t.atypeid,t.fperiod,t.cid
			) v1 ON v.orderid=v1.orderid AND v.cid=v1.cid 
		    JOIN #tempYearData y ON v.fperiod=y.fperiod AND v.atypeid=y.atypeid '
IF @cid<>0  --有币别的情况
			SET @sql+=' AND v.cid=y.cid'
		EXEC(@sql)
   
IF @cid=@selfcid
	UPDATE #Voucher SET selfendbalance=endbalance
ELSE 
	--综合本位币
	UPDATE v SET v.selfendbalance=(case when v.tempfdc=1 then  y.qichu+v1.selfborrow-v1.selflend 
									else y.qichu-v1.selfborrow+v1.selflend end ) 
	FROM #Voucher v 
	JOIN 
	(
		SELECT t.orderid,t.atypeid,t.fperiod,t.cid,SUM(t1.selfborrow) as selfborrow,SUM(t1.selflend) as selflend 
		FROM #Voucher t 
		JOIN #Voucher t1 ON t.atypeid=t1.atypeid AND t.fperiod=t1.fperiod AND t1.orderid<=t.orderid  
		GROUP BY t.orderid,t.atypeid,t.fperiod,t.cid
	) v1 ON v.orderid=v1.orderid AND v.cid=v1.cid 
	JOIN #tempYearData y ON v.fperiod=y.fperiod AND v.atypeid=y.atypeid AND y.cid=0  
	      
	     
------更新方向
UPDATE #Voucher SET fdc='平' WHERE selfendbalance=0
ALTER TABLE #Voucher DROP COLUMN tempfdc
    
 -------合计
 CREATE TABLE #tempSummary 
 (
	fperiod  INT,
	qichufdc INT,
    qichu     NUMERIC(24, 10) ,
	borrow    NUMERIC(24, 10) ,
	lend	  NUMERIC(24, 10) ,
	yearborrow    NUMERIC(24, 10) ,
	yearlend	  NUMERIC(24, 10) ,
	balancefdc INT,
	balance   NUMERIC(24, 10) ,
	cid		 INT
 )
 
 IF EXISTS (SELECT TOP 1 1 FROM #tempYearData )
	BEGIN
		;WITH t AS 
		 (
			 SELECT fperiod,
					fdc,
					SUM(qichu) AS qichu,
					SUM(borrow) AS borrow,
					SUM(lend) AS lend,
					SUM(yearborrow) AS yearborrow,
					SUM(yearlend) AS yearlend,
					SUM(balance) AS balance,
					cid 
			 FROM #tempYearData
			 WHERE atypeid IN (select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0))
			 GROUP BY fperiod,fdc,cid 
		 ) 
		 INSERT INTO #tempSummary 
		 SELECT t1.fperiod,t2.qichufdc,t2.qichu,t1.borrow,t1.lend,t1.yearborrow,t1.yearlend,t2.balancefdc,t2.balance,t1.cid       
		 FROM 
		 (
			SELECT fperiod,SUM(borrow) AS borrow,SUM(lend) AS lend,SUM(yearborrow) AS yearborrow,SUM(yearlend) AS yearlend,cid FROM t GROUP BY fperiod,cid
		 ) t1 
		 JOIN 
		 (
			SELECT DISTINCT a.fperiod,a.cid,CASE WHEN @cid>0 AND ISNULL(a.balance,0)>ISNULL(b.balance,0) THEN a.fdc   --单币别
												 WHEN @cid>0 AND ISNULL(a.balance,0)<ISNULL(b.balance,0) AND b.fdc IS NULL THEN -(a.fdc) --修改bug，特殊情况
												 WHEN @cid>0 AND ISNULL(a.balance,0)<ISNULL(b.balance,0) THEN b.fdc 
												 WHEN @cid<=0 AND a.cid=0 AND ISNULL(a.balance,0)>ISNULL(b.balance,0) THEN a.fdc --多币别
												 WHEN @cid<=0 AND a.cid=0 AND ISNULL(a.balance,0)<ISNULL(b.balance,0) AND b.fdc IS NULL THEN -(a.fdc) --修改bug，特殊情况
												 WHEN @cid<=0 AND a.cid=0 AND ISNULL(a.balance,0)<ISNULL(b.balance,0) THEN b.fdc
												 ELSE 0 END AS balancefdc,
											CASE WHEN @cid>0 THEN ABS(ISNULL(a.balance,0)-ISNULL(b.balance,0)) --单币别
												 WHEN @cid<=0 AND  a.cid=0 THEN ABS(ISNULL(a.balance,0)-ISNULL(b.balance,0))  
												 WHEN @cid<=0 AND a.cid<>0 THEN ISNULL(a.balance,0)-ISNULL(b.balance,0)
												 END AS balance,  
											CASE WHEN @cid>0 AND ISNULL(a.qichu,0)>ISNULL(b.qichu,0) THEN a.fdc 
												 WHEN @cid>0 AND ISNULL(a.qichu,0)<ISNULL(b.qichu,0) AND b.fdc IS NULL THEN -(a.fdc) --修改bug，特殊情况
											     WHEN @cid>0 AND ISNULL(a.qichu,0)<ISNULL(b.qichu,0) THEN b.fdc 
											     WHEN @cid<=0 AND a.cid=0 AND ISNULL(a.qichu,0)>ISNULL(b.qichu,0) THEN a.fdc --多币别
											     WHEN @cid<=0 AND a.cid=0 AND ISNULL(a.qichu,0)<ISNULL(b.qichu,0) AND b.fdc IS NULL THEN -(a.fdc) --修改bug，特殊情况
												 WHEN @cid<=0 AND a.cid=0 AND ISNULL(a.qichu,0)<ISNULL(b.qichu,0) THEN b.fdc
											     ELSE 0 END AS qichufdc,
											CASE WHEN @cid>0 THEN ABS(ISNULL(a.qichu,0)-ISNULL(b.qichu,0)) --单币别
												 WHEN @cid<=0 AND  a.cid=0 THEN ABS(ISNULL(a.qichu,0)-ISNULL(b.qichu,0))  
												 WHEN @cid<=0 AND a.cid<>0 THEN ISNULL(a.qichu,0)-ISNULL(b.qichu,0)
												 END AS qichu  
			FROM t a LEFT JOIN t b ON a.cid=b.cid AND a.fperiod=b.fperiod AND a.fdc<>b.fdc
			GROUP BY a.fperiod,a.cid,a.balance,b.balance,a.fdc,b.fdc,a.qichu,b.qichu
		 ) t2 ON t1.fperiod=t2.fperiod AND t1.cid=t2.cid 
	END
	  
	  
	  
	------查询结果
	 IF @cid=0 OR @cid=@selfcid  --本位币单币别或者综合本位币
		BEGIN
			WITH T AS (
			SELECT y.fperiod AS period,
				   0 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.fBEGIN AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '期初余额' AS summary,
				   0 AS debit,
				   0 AS credit,
				   qichu AS balance,
				   CASE WHEN qichu=0 THEN '平' WHEN i.fdc=1 THEN '借' ELSE '贷' END AS balancefdc,
				   0 AS flag,--排序用
				   0 AS orderid,----排序用
				   '' ETypeId
			FROM #tempYearData y 
			JOIN #temp1 i ON y.atypeid=i.atypeid
			join (
				select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
			     ) t on y.atypeid=t.atypeid
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT y.fperiod AS period,
				   9999998 AS billnumberid,
				   NAME AS atypename, 
				   usercode AS atypeusercode,
				   p.FEnd AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '本期合计' AS summary,
				   y.borrow AS debit,
				   y.lend AS credit,
				   balance,
				   CASE WHEN balance=0 THEN '平' WHEN i.fdc=1 THEN '借' ELSE '贷' END AS balancefdc,
				   0 AS flag,--排序用
				   9999998 AS orderid,----排序用
				   '' ETypeId
			FROM #tempYearData y
			JOIN #temp1 i ON y.atypeid=i.atypeid
			join (
				select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
				 ) t on y.atypeid=t.atypeid
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT y.fperiod AS period,
				   9999999 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.FEnd AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '本年累计' AS summary,
				   yearborrow AS debit,
				   yearlend AS credit,
				   balance AS balance,
				   CASE WHEN balance=0 THEN '平' WHEN i.fdc=1 THEN '借' ELSE '贷' END AS balancefdc,
				   0 AS flag,--排序用
				   9999999 AS orderid,----排序用
				   '' ETypeId
			FROM #tempYearData y
			JOIN #temp1 i ON y.atypeid=i.atypeid
			join (
				select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
				 ) t on y.atypeid=t.atypeid
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT fperiod AS period,
				   billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   BILLDATE AS vouchertime,
				   FSERIALNAME AS vg,
				   vouchertype,
				   summary,
				   selfborrow AS debit,
				   selflend AS credit,
				   selfendbalance AS balance,
				   v.fdc AS balancefdc,
				   0 AS flag,--排序用
				   orderid, 
				   v.ETypeId
			FROM #Voucher v
			JOIN #temp1 i ON v.atypeid=i.atypeid
			UNION ALL 
			SELECT s.fperiod AS period,
			       10000000 AS billnumerid,
			       '小计' AS atypename,
			       'X' AS atypeusercode,
			        p.fBEGIN AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '期初余额' AS summary,
				   0 AS debit,
				   0 AS credit,
				   qichu AS balance,
				   case when qichufdc=0 then '平' when qichufdc=1 then '借' ELSE '贷' END AS balancefdc,
				   1 AS flag,--排序用
				   10000000 as orderid,
				   '' ETypeId
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT s.fperiod AS period,
			       10000001 AS billnumerid,
			       '小计' AS atypename,
			       'Y' AS atypeusercode,
			        p.FEnd AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '本期合计' AS summary,
				   borrow AS debit,
				   lend AS credit,
				   balance,
				   case when balance=0 then '平' when balancefdc=1 then '借' ELSE '贷' END AS balancefdc,
				   1 AS flag,--排序用
				   10000001 as orderid,
				   '' ETypeId
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT s.fperiod AS period,
			       10000002 AS billnumerid,
			       '小计' AS atypename,
			       'Z' AS atypeusercode,
			        p.FEnd AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '本年累计' AS summary,
				   yearborrow AS debit,
				   yearlend AS credit,
				   balance,
				   case when balance=0 then '平' when balancefdc=1 then '借' ELSE '贷' END AS balancefdc,
				   1 AS flag,--排序用
				   10000002 as orderid,
				   '' ETypeId
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			)
			
			SELECT *,atypeusercode AS atypeid FROM t WHERE period>=@fperiodstart ORDER BY period,atypeusercode,vouchertime,orderid
		END
	ELSE 	
		BEGIN
			-----------------------------------------------------------所有币别是动态列,先求出有多少列----------------------------------------------------------
		     CREATE TABLE #tempColName1
			  (
				cid INT,
				usercode  VARCHAR(200)
			  )
			  IF @cid<>-1  --具体币别
				INSERT INTO #tempColName1
				SELECT CID,USERCODE 
				FROM (SELECT CID,USERCODE FROM AC_CURRENCY WHERE CId=@cid
					  UNION ALL 
					  SELECT 0 AS CID,'' AS USERCODE) b
			  ELSE
				INSERT INTO #tempColName1
			    SELECT CID,USERCODE 
				FROM (SELECT CID,USERCODE FROM AC_CURRENCY
					  UNION ALL 
					  SELECT 0 AS CID,'' AS USERCODE) b
		    
					   
			SELECT COLNAME,FDC
			INTO #tempColName2 
			FROM (
			SELECT 'balance' AS COLNAME,'余额' AS FDC     
			UNION ALL   
			SELECT 'debit' AS COLNAME,'借' AS FDC 
			UNION ALL
			SELECT 'credit' AS COLNAME,'贷' AS FDC 
			) a
			
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID,FDC 
			INTO #tempColName
			FROM #tempColName1,#tempColName2
			
			--行转列的时候用
			DECLARE @TurnCol VARCHAR(MAX)
			SELECT @TurnCol=(ISNULL(@TurnCol+'],[','') +  colname) 
			FROM #tempColName GROUP BY COLNAME 
			SET @TurnCol='['+@TurnCol+']'
			
			----转换表
			CREATE TABLE #Voucher1
			(
				FPeriod INT,
				atypeid varchar(50),
				orderID		INT,
				COLNAME	VARCHAR(MAX),
				FVALUE	 NUMERIC(24, 10) 
			)
			INSERT INTO #Voucher1
			SELECT a.FPERIOD,a.atypeid,a.orderID,b.COLNAME,
					CASE 
						WHEN a.CID=b.CID AND b.FDC='借'   THEN a.borrow
						WHEN a.CID=b.CID AND b.FDC='贷'   THEN a.lend
						WHEN a.CID=b.CID AND b.FDC='余额' THEN a.endbalance
						WHEN b.CID=0 AND b.FDC='借'       THEN a.selfborrow
						WHEN b.CID=0 AND b.FDC='贷'       THEN a.selflend
						WHEN b.CID=0 AND b.FDC='余额'     THEN a.selfendbalance
					END
			FROM #Voucher a,#tempColName b
			
			create table #temptotal
			(
				period int,
				atypeid  varchar(50),
				billnumberid int,
				atypename nvarchar(200),
				atypeusercode nvarchar(200),
				vouchertime  date,
				vg           nvarchar(100),
				vouchertype  nvarchar(100),
				summary      nvarchar(500),
				borrow         NUMERIC(24, 10) ,
				lend		 NUMERIC(24, 10) ,
				endbalance	 NUMERIC(24, 10) ,
				balancefdc	NVARCHAR(10),
				orderid     INT,
				cid         INT
			)
			insert into #temptotal
			SELECT y.fperiod AS period,
					y.atypeid,
				   0 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.fBEGIN AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '期初余额' AS summary,
				   0 AS debit,
				   0 AS credit,
				   qichu AS balance,
				   CASE WHEN qichu=0 THEN '平' WHEN i.fdc=1 THEN '借' ELSE '贷' END AS balancefdc,
				   0 AS orderid,----排序用
				   y.cid
			FROM #tempYearData y 
			JOIN #temp1 i ON y.atypeid=i.atypeid
			join (
				select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
			     ) t on y.atypeid=t.atypeid
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT y.fperiod AS period,
					y.atypeid,
				   9999998 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.FEnd AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '本期合计' AS summary,
				   y.borrow AS debit,
				   y.lend AS credit,
				   balance,
				   CASE WHEN balance=0 THEN '平' WHEN i.fdc=1 THEN '借' ELSE '贷' END AS balancefdc,
				   9999998 AS orderid,----排序用
				   y.cid
			FROM #tempYearData y
			JOIN #temp1 i ON y.atypeid=i.atypeid
			join (
				select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
				 ) t on y.atypeid=t.atypeid
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT y.fperiod AS period,
					y.atypeid,
				   9999999 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.FEnd AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '本年累计' AS summary,
				   yearborrow AS debit,
				   yearlend AS credit,
				   balance,
				   CASE WHEN balance=0 THEN '平' WHEN i.fdc=1 THEN '借' ELSE '贷' END AS balancefdc,
				   9999999 AS orderid,----排序用
				   y.cid
			FROM #tempYearData y
			JOIN #temp1 i ON y.atypeid=i.atypeid
			join (
				select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
				 ) t on y.atypeid=t.atypeid
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
		
			CREATE TABLE #Total
			(
				FPeriod INT,
				atypeid varchar(50),
				orderID		INT,
				COLNAME	VARCHAR(MAX),
				FVALUE	 NUMERIC(24, 10) 
			)
			
			INSERT INTO #Total
			SELECT a.PERIOD,a.atypeid,a.orderid,b.COLNAME,
					CASE 
						WHEN a.CID=b.CID AND b.FDC='借'     THEN a.borrow
						WHEN a.CID=b.CID AND b.FDC='贷'     THEN a.lend
						WHEN a.CID=b.CID AND b.FDC='余额'   THEN a.endbalance
					END
			FROM #temptotal a,#tempColName b 
		  
            -----合计
            CREATE TABLE #tempSummaryTotal
            (
				period int,
				atypeid  varchar(50),
				billnumberid int,
				atypename nvarchar(200),
				atypeusercode nvarchar(200),
				vouchertime  date,
				vg           nvarchar(100),
				vouchertype  nvarchar(100),
				summary      nvarchar(500),
				borrow         NUMERIC(24, 10) ,
				lend		 NUMERIC(24, 10) ,
				endbalance	 NUMERIC(24, 10) ,
				balancefdc	NVARCHAR(10),
				orderid     INT,
				cid         INT
            )		  
		    INSERT INTO #tempSummaryTotal
		    SELECT s.fperiod AS period,
				   'X',
			       10000000 AS billnumerid,
			       '小计' AS atypename,
			        'X',
			        p.fBEGIN AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '期初余额' AS summary,
				   0 AS debit,
				   0 AS credit,
				   qichu AS balance,
				   case when qichufdc=0 then '平' when qichufdc=1 then '借' ELSE '贷' END AS balancefdc,
				   10000000 as orderid,
				   cid
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT s.fperiod AS period,
				   'Y',
			       10000001 AS billnumerid,
			       '小计' AS atypename,
			       'Y' AS atypeusercode,
			        p.FEnd AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '本期合计' AS summary,
				   borrow AS debit,
				   lend AS credit,
				   balance,
				   case when balancefdc=0 then '平' when balancefdc=1 then '借' ELSE '贷' END AS balancefdc,
				   10000001 as orderid,
				   cid
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT s.fperiod AS period,
				   'Z',
			       10000002 AS billnumerid,
			       '小计' AS atypename,
			       'Z' AS atypeusercode,
			        p.FEnd AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '本年累计' AS summary,
				   yearborrow AS debit,
				   yearlend AS credit,
				   balance,
				   case when balancefdc=0 then '平' when balancefdc=1 then '借' ELSE '贷' END AS balancefdc,
				   10000002 as orderid,
				   cid
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
		  
		    CREATE TABLE #Summary
			(
				FPeriod INT,
				atypeid varchar(50),
				orderID		INT,
				COLNAME	VARCHAR(MAX),
				FVALUE	 NUMERIC(24, 10) 
			)
			
			INSERT INTO #Summary
			SELECT a.PERIOD,a.atypeid,a.orderid,b.COLNAME,
					CASE 
						WHEN a.CID=b.CID AND b.FDC='借'     THEN a.borrow
						WHEN a.CID=b.CID AND b.FDC='贷'     THEN a.lend
						WHEN a.CID=b.CID AND b.FDC='余额'   THEN a.endbalance
					END
			FROM #tempSummaryTotal a,#tempColName b 
		  
			SET @SQL='SELECT * INTO #Result
						FROM
						(
							SELECT d.FPERIOD as period,
								   d.atypeid,
								   d.BILLNUMBERID,
								   NAME AS atypename,
								   usercode AS atypeusercode,
								   BILLDATE AS vouchertime,
								   FSERIALNAME AS vg,
								   vouchertype,
								   summary,
								   d.FDC AS balancefdc,
								   0 as flag,
								   d.orderid,
								   d.ETypeId,'+@TurnCol+'
							FROM #Voucher d
							JOIN 
							(
							SELECT *  FROM  #Voucher1  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
							) c ON d.FPERIOD=c.FPERIOD AND d.orderid=c.orderid AND d.atypeid=c.atypeid
							JOIN #temp1 i ON d.atypeid=i.atypeid
							
							UNION ALL
							
							SELECT d.PERIOD as period,
								   d.atypeid,
								   d.BILLNUMBERID,
								   d.atypename,
								   d.atypeusercode,
								   vouchertime,
								   vg,
								   vouchertype,
								   summary,
								   balancefdc,
								   0 as flag,
								   d.orderid,
								   '''' ETypeId,'+@TurnCol+'
							FROM #tempTotal d
							JOIN 
							(
								SELECT *  FROM  #Total  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
							) c ON d.PERIOD=c.FPERIOD AND d.orderid=c.orderid AND d.atypeid=c.atypeid
							WHERE d.CID=0
							
							UNION ALL
							
							SELECT d.PERIOD as period,
								   d.atypeid,
								   d.BILLNUMBERID,
								   d.atypename,
								   d.atypeusercode,
								   vouchertime,
								   vg,
								   vouchertype,
								   summary,
								   balancefdc,
								   1 as flag,
								   d.orderid,
								   '''' ETypeId,'+@TurnCol+'
							FROM #tempSummaryTotal d
							JOIN 
							(
								SELECT *  FROM  #Summary  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
							) c ON d.PERIOD=c.FPERIOD AND d.orderid=c.orderid AND d.atypeid=c.atypeid
							WHERE d.CID=0
						) a  ;
						
						SELECT y.*,y.atypeusercode as atypeid 
						FROM #Result y
						join (
								select atypeid from #tempItems where ((@IsProNull=1 and periodchange>0) or @IsProNull=0) and  ((@IsProNot=1 and balance<>0) or @IsProNot=0)
								UNION ALL 
								select ''X''
								UNION ALL 
								select ''Y''
								UNION ALL 
								select ''Z''
							 ) t on y.atypeid=t.atypeid
						where period>=@fperiodstart
						ORDER BY period,flag,atypeusercode,vouchertime,orderid;
						
				drop table #Result'	
				EXEC sp_executesql @SQL,N'@IsProNull INT,@IsProNot INT,@fperiodstart INT',@IsProNull,@IsProNot,@fperiodstart
				DROP TABLE #Total,#temptotal,#Voucher1,#tempColName,#tempColName1,#tempColName2,#Summary,#tempSummaryTotal
		END
		DROP TABLE #Voucher,#temp1,#tempIniData,#tempPeriodData,#tempYearData,#tempItems,#tempSummary,#Ac_Account_L

	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_AuxiliaryDetailedAccount1]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].Web_AuxiliaryDetailedAccount1
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-07-14
	描述：辅助核算明细账
*/
CREATE PROCEDURE Web_AuxiliaryDetailedAccount1
(
	@aacategorytypeid		INT,			--辅助类别ID
	@aacategoryprotypeid	VARCHAR(MAX),	--辅助核算明细ID
	@atypeid1				VARCHAR(MAX),	--科目ID
	@stypeid				VARCHAR(MAX),	--分支机构
	@fyear					INT,			--年度
	@fperiodstart			INT,			--开始日期
	@fperiodend				INT,			--结束日期
	@cid					INT,			--币别ID
	@IsShowNotPost			INT,			--包括未过账凭证:1为是0为否
	@IsBalanceNull			INT,			--项目无发生额不显示:1为是0为否
	@IsBalanceNot			INT,			--项目无余额项目不显示:1为是0为否
	@chvOperatorID			VARCHAR(100)	--操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON
DECLARE 
	@sql		NVARCHAR(MAX),
	@fperiod	INT,
	@iniFYear	VARCHAR(5),	--启用年度	 
	@maxfperiod	INT,		--算年度期初用	
	@TypeName	VARCHAR(200),--类别编号	
	@LimitOwnVoucher INT=0--仅能查看本人制单的会计凭证
		
SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@chvOperatorID

--辅助核算类别编号
SELECT @TypeName=UserCode FROM Ac_Assist_CheckItems WHERE AscIds=@aacategorytypeid 

SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
SELECT @maxfperiod=MAX(CONVERT(INT,FPeriod)) FROM dbo.Ac_Balance_Assist_CheckItems_Detail WHERE FYear=@fyear-1 AND STypeId=@stypeid
IF @iniFYear=@Fyear
	SELECT @FPeriod=SFPeriod from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
ELSE 
	SELECT @Fperiod=MIN(CONVERT(INT,FPeriod)) FROM dbo.Ac_Period		 			 
---判断分支机构权限
 IF NOT EXISTS ( SELECT *  FROM   dbo.F_GetManDetailAllSType(@chvOperatorID)   WHERE  TypeId = @StypeID ) 
    SET @StypeID = ''
 
--本位币
DECLARE @selfcid INT
SELECT @selfcid=CId FROM dbo.Ac_Currency WHERE Sysrow=1

BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
	INSERT INTO #Ac_Account_L (Typeid,StypeId) 
	SELECT L.Typeid,L.Stypeid FROM F_TreeAccount(@chvOperatorID,'') L
END; 

DECLARE @iniFpeirod INT=@fperiod,
		@Fdc   INT,
		@FdcName  VARCHAR(5)
SELECT @Fdc=Fdc,@FdcName=CASE WHEN fdc=1 THEN '借' ELSE '贷' END FROM dbo.Ac_Account A
INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND L.StypeId=A.StypeId 
WHERE A.TypeId=@atypeid1

---根据要查询的辅助核算找出要查询的辅助核算项目（只有子项目）
CREATE TABLE #tempAllAssistItems
(
	fieldValue  VARCHAR(50),
	NAME		NVARCHAR(200),
	usercode    NVARCHAR(200) 
)	
IF @aacategorytypeid=1 --分支机构
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				IF EXISTS(SELECT * FROM sysdata WHERE SubName='innerstypesaleralation' AND SubValue=1)  --存在买卖关系
					INSERT INTO #tempAllAssistItems 
					SELECT s.TypeId,FullName,UserCode FROM dbo.SType s
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
					WHERE deleted=0  AND  sonnum=0 AND VerifyID=@stypeid
				ELSE 
					INSERT INTO #tempAllAssistItems 
					SELECT s.TypeId,FullName,UserCode FROM dbo.SType s
					JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
					WHERE deleted=0  AND  sonnum=0
			END
		ELSE     
			BEGIN
				INSERT INTO #tempAllAssistItems
				SELECT s.TypeId,s.FullName,s.UserCode 
				FROM dbo.f_split(@aacategoryprotypeid,',') f 
				JOIN dbo.SType s ON s.TypeId LIKE f.a+'%' AND s.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',11,@chvOperatorID) 
					   ) c ON s.TypeId=c.TypeId
			END
	END
ELSE IF @aacategorytypeid=2 --部门
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempAllAssistItems 
				SELECT d.TypeId,FullName,UserCode FROM dbo.Department d
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID) 
					   ) c ON d.TypeId=c.TypeId
				WHERE deleted=0  AND  sonnum=0
			END
		ELSE    
			BEGIN
				INSERT INTO #tempAllAssistItems
				SELECT d.typeid,d.FullName,d.UserCode 
				FROM dbo.f_split(@aacategoryprotypeid,',') f 
				JOIN dbo.Department d ON d.TypeId LIKE f.a+'%' AND d.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID) 
					   ) c ON d.TypeId=c.TypeId
			END
	END
ELSE IF @aacategorytypeid=3 --职员
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempAllAssistItems 
				SELECT e.TypeId,FullName,UserCode FROM dbo.employee e
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID) 
					   ) c ON e.TypeId=c.TypeId
				WHERE deleted=0 AND sonnum=0
			END
		ELSE    
			BEGIN
				INSERT INTO #tempAllAssistItems
				SELECT e.typeId,e.FullName,e.UserCode 
				FROM dbo.f_split(@aacategoryprotypeid,',') f 
				JOIN dbo.employee e ON e.TypeId LIKE f.a+'%' AND e.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID) 
					   ) c ON e.TypeId=c.TypeId
			END
	END  
ELSE IF @aacategorytypeid=4 --往来单位	
	BEGIN
		IF @aacategoryprotypeid=''
			BEGIN
				INSERT INTO #tempAllAssistItems 
				SELECT b.TypeId,FullName,UserCode FROM dbo.btype b
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID) 
					   ) c ON b.TypeId=c.TypeId
				WHERE deleted=0 AND sonnum=0  
			END
		ELSE     
			BEGIN
				INSERT INTO #tempAllAssistItems
				SELECT b.typeId,b.FullName,b.UserCode 
				FROM dbo.f_split(@aacategoryprotypeid,',') f 
				JOIN dbo.btype b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0
				JOIN 
					   (
						 SELECT TypeId
						 FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID) 
					   ) c ON b.TypeId=c.TypeId
			END
	END
ELSE 
	BEGIN
		INSERT INTO #tempAllAssistItems
		SELECT 
			B.TypeId,
			B.FullName,
			B.UserCode
		FROM Ac_Assist_CheckItemsDetail B
		INNER JOIN dbo.F_GetAllAssistCheckItemsDetail(@aacategoryprotypeid,@aacategorytypeid,@chvOperatorID) F ON F.TypeId=B.TypeId AND B.AscIds=@aacategorytypeid AND B.SonNum=0
	END
  
-----期初数据
CREATE TABLE #tempIniData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	fieldValue   VARCHAR(50),
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
IF @cid>0  --单币别
	BEGIN
		IF @iniFYear=@Fyear
			BEGIN
				--原币
				INSERT INTO #tempIniData   
				SELECT FYear,FPeriod,i.fieldValue,SUM(FDebitFor),SUM(FCreditFor),SUM(IniTotalFor),Cid
				FROM #tempAllAssistItems i 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND Cid=@cid AND i.fieldValue=ai.FieldValue
				GROUP BY FYear,FPeriod,i.fieldValue,ai.Cid
				
				IF @cid<>@selfcid 
					---本位币
					INSERT INTO #tempIniData   
					SELECT FYear,FPeriod,i.fieldValue,SUM(FDebit),SUM(FCredit),SUM(IniTotal),0
					FROM #tempAllAssistItems i 
					JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND Cid=@cid AND i.fieldValue=ai.FieldValue
					GROUP BY FYear,FPeriod,i.fieldValue
			END
		ELSE 
			BEGIN
				--原币
				INSERT INTO #tempIniData   
				SELECT FYear,FPeriod,i.fieldValue,
						0,--SUM(FDebitFor),
						0,--SUM(FCreditFor),
				SUM(FEndBalanceFor),Cid
				FROM #tempAllAssistItems i 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND Cid=@cid 
																	AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod
				GROUP BY FYear,FPeriod,i.fieldValue,ai.Cid
				 
				 IF @IsShowNotPost=1
					BEGIN
						--修复上一年没数据，只有未过账凭证，没期初的情况
						IF EXISTS(SELECT TOP 1 1 FROM (SELECT fieldValue 
	 								FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid) T WHERE fieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
							BEGIN
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   fieldValue,0,0,0,Cid
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
												AND fieldValue NOT IN (SELECT fieldValue FROM #tempIniData)
												
							   INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   fieldValue,0,0,0,0
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
												AND fieldValue NOT IN (SELECT fieldValue FROM #tempIniData WHERE cid=0)
							END	
					
						;WITH T AS
						(
							SELECT i.fieldValue,SUM(t2.FDebitTotalFor) AS  borrow,SUM(t2.FCreditTotalFor) AS lend,Cid
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
							GROUP BY i.fieldValue,Cid 
			 			)
			 			UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.fieldValue=T.fieldValue AND i.cid=T.cid 
					END
					
				--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				 IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT fieldValue 
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #tempAllAssistItems i ON  t3.TypeId=i.fieldValue
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid) t
									LEFT JOIN #tempIniData ti  ON t.fieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
									WHERE t.fieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
				 	BEGIN
				 		 	INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						           i.fieldValue,
						           0,
						           0,
						           CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotal)- SUM(t2.FCreditTotal) ELSE SUM(t2.FCreditTotal)-SUM(t2.FDebitTotal) END  ,
						           t2.Cid
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON i.fieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  AND t2.Cid=@cid 
							AND i.fieldValue NOT IN (SELECT fieldValue FROM #tempIniData)	
							GROUP BY t1.FYear,i.fieldValue,t2.cid 
						 
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   i.fieldValue,
								   0,
								   0,
								   CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.Cid=@cid 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON i.fieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND i.fieldValue NOT IN (SELECT fieldValue FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,i.fieldValue 
				 	END 		
				
				IF @cid<>@selfcid 
					BEGIN
						---本位币
						INSERT INTO #tempIniData   
						SELECT FYear,FPeriod,i.fieldValue,
								0,--SUM(FDebit),
								0,--SUM(FCredit),
								SUM(FEndBalance),0
						FROM #tempAllAssistItems i 
						JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND Cid=@cid 
																			AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod
						GROUP BY FYear,FPeriod,i.fieldValue
						
						IF @IsShowNotPost=1
							WITH T AS
							(
								SELECT i.fieldValue,SUM(t2.FDebitTotal) AS  borrow,SUM(t2.FCreditTotal) AS lend,Cid
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  AND Cid=@cid
								GROUP BY i.fieldValue,Cid 
			 				)
			 				UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 				from #tempIniData i
			 				JOIN T ON i.fieldValue=T.fieldValue AND i.cid=0 	 
					END
						
			END	
	END
ELSE IF @cid=-1  --所有币别
	BEGIN
		IF @iniFYear=@Fyear
			BEGIN
				INSERT INTO #tempIniData   
				SELECT FYear,FPeriod,i.fieldValue,SUM(FDebitFor),SUM(FCreditFor),SUM(IniTotalFor),Cid
				FROM #tempAllAssistItems i 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid AND i.fieldValue=ai.FieldValue
				GROUP BY FYear,FPeriod,i.fieldValue,ai.Cid
				
				--综合本位币
				INSERT INTO #tempIniData  
				SELECT FYear,FPeriod,i.fieldValue,SUM(FDebit) AS FDebit,SUM(FCredit) AS FCredit,SUM(IniTotal) AS IniTotal,0
				FROM #tempAllAssistItems i 
				JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid  
																	AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear
				GROUP BY FYear,FPeriod,i.fieldValue
			END
		ELSE 
			BEGIN
				INSERT INTO #tempIniData   
				SELECT FYear,FPeriod,i.fieldValue,
						0,--SUM(FDebitFor),
						0,--SUM(FCreditFor),
						SUM(FEndBalanceFor),Cid
				FROM #tempAllAssistItems i 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid 
																	AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod AND ai.cid<>0
				GROUP BY FYear,FPeriod,i.fieldValue,ai.Cid
				
				--综合本位币
				INSERT INTO #tempIniData  
				SELECT FYear,FPeriod,i.fieldValue,
						0,--SUM(FDebit) AS FDebit,
						0,--SUM(FCredit) AS FCredit,
						SUM(FEndBalance) AS IniTotal,0
				FROM #tempAllAssistItems i 
				JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid  
																	AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod AND ai.cid<>0
				GROUP BY FYear,FPeriod,i.fieldValue
				
				IF @IsShowNotPost=1
					BEGIN
						--修复上一年没数据，只有未过账凭证，没期初的情况
						IF EXISTS(SELECT TOP 1 1 FROM (SELECT fieldValue 
	 								FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1) T WHERE fieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
							BEGIN
								INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   fieldValue,0,0,0,Cid
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1  
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   
												AND fieldValue NOT IN (SELECT fieldValue FROM #tempIniData)
												
							   INSERT INTO #tempIniData 
								SELECT DISTINCT t1.FYear,12,--期间随便写
									   fieldValue,0,0,0,0
	 							FROM  dbo.Ac_Voucher t1 
								JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1  
								JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
								JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
								JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
								WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
												AND fieldValue NOT IN (SELECT fieldValue FROM #tempIniData WHERE cid=0)
							END
						;WITH T AS
						(
							SELECT i.fieldValue,SUM(t2.FDebitTotalFor) AS  borrow,SUM(t2.FCreditTotalFor) AS lend,Cid
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   
							GROUP BY i.fieldValue,Cid 
			 			)
			 			UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
			 			from #tempIniData i
			 			JOIN T ON i.fieldValue=T.fieldValue AND i.cid=T.cid 
			 			
			 			--综合本位币
			 			;WITH T AS
						(
							SELECT i.fieldValue,SUM(t2.FDebitTotal) AS  borrow,SUM(t2.FCreditTotal) AS lend
 							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
							GROUP BY i.fieldValue
		 				)
		 				UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
		 				from #tempIniData i
		 				JOIN T ON i.fieldValue=T.fieldValue AND i.cid=0 
					END
				--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT fieldValue
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  AND t2.ATypeId=@atypeid1 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #tempAllAssistItems i ON  t3.TypeId=i.fieldValue
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1) t
									LEFT JOIN #tempIniData ti  ON t.fieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
									 WHERE t.fieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
					BEGIN
						    INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
						            i.fieldValue,
						           0,
						           0,
						           CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotal)- SUM(t2.FCreditTotal) ELSE SUM(t2.FCreditTotal)-SUM(t2.FDebitTotal) END  ,
						           t2.Cid
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON i.fieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1  
							AND i.fieldValue NOT IN (SELECT fieldValue FROM #tempIniData)		
							GROUP BY t1.FYear,i.fieldValue,t2.cid 
						 
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   i.fieldValue,
								   0,
								   0,
								   CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON i.fieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND i.fieldValue NOT IN (SELECT fieldValue FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,i.fieldValue  
					END				 
			END
	END
ELSE --综合本位币
	IF @iniFYear=@Fyear
		INSERT INTO #tempIniData  
		SELECT FYear,FPeriod,i.fieldValue,SUM(FDebit) AS FDebit,SUM(FCredit) AS FCredit,SUM(IniTotal) AS IniTotal,0
		FROM #tempAllAssistItems i 
		JOIN dbo.Ac_IniAccount_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid  AND i.fieldValue=ai.FieldValue
		GROUP BY FYear,FPeriod,i.fieldValue 
	ELSE 
		BEGIN
			INSERT INTO #tempIniData  
			SELECT FYear,FPeriod,i.fieldValue,
					0,--SUM(FDebit) AS FDebit,
					0,--SUM(FCredit) AS FCredit,
					SUM(FEndBalance) AS IniTotal,0
			FROM #tempAllAssistItems i 
			JOIN dbo.Ac_Balance_Assist_CheckItems_Detail ai ON ai.STypeId=@stypeid AND ai.ATypeId=@atypeid1 AND ai.Ascids=@aacategorytypeid  
																AND i.fieldValue=ai.FieldValue AND ai.FYear=@fyear-1 AND ai.fperiod=@maxfperiod AND ai.cid<>0
			GROUP BY FYear,FPeriod,i.fieldValue
			
			IF @IsShowNotPost=1
				BEGIN
					IF EXISTS(SELECT TOP 1 1 FROM (SELECT fieldValue 
	 								FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1) T WHERE fieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
						   INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
							       fieldValue,0,0,0,0
	 						FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1  
											AND fieldValue NOT IN (SELECT fieldValue FROM #tempIniData)
											
					;WITH T AS
					(
						SELECT i.fieldValue,SUM(t2.FDebitTotal) AS  borrow,SUM(t2.FCreditTotal) AS lend
						FROM  dbo.Ac_Voucher t1 
						JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1  
						JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
						JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
						JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
						WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod>=@maxfperiod AND IfCheck='f' AND t1.FYear=@Fyear-1   
						GROUP BY i.fieldValue
 					)
 					UPDATE i SET i.balance+=(CASE WHEN @fdc=1 THEN T.borrow-T.lend ELSE T.lend-T.borrow END )
 					from #tempIniData i
 					JOIN T ON i.fieldValue=T.fieldValue AND i.cid=0 	
				END
				
					--特殊处理1, 跨年结账后反结账回来，做未过账凭证，再查下一年的数据，对应9.3bug347
				IF EXISTS(SELECT TOP 1 1 FROM   (
									SELECT fieldValue
	 								FROM  dbo.Ac_Voucher t1 
									JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  AND t2.ATypeId=@atypeid1 
									JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
									JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
									JOIN #tempAllAssistItems i ON  t3.TypeId=i.fieldValue
									WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1) t
									LEFT JOIN #tempIniData ti  ON t.fieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
									 WHERE t.fieldValue NOT IN (SELECT fieldValue FROM #tempIniData))
					BEGIN
							INSERT INTO #tempIniData 
							SELECT DISTINCT t1.FYear,12,--期间随便写
								   i.fieldValue,
								   0,
								   0,
								   CASE WHEN @fdc=1 THEN  SUM(t2.FDebitTotalFor)- SUM(t2.FCreditTotalFor) ELSE SUM(t2.FCreditTotalFor)-SUM(t2.FDebitTotalFor) END  ,
								   0
							FROM  dbo.Ac_Voucher t1 
							JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId  
							JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName 
							JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
							JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
							LEFT JOIN #tempIniData ti  ON i.fieldValue=ti.fieldValue AND ti.fieldValue IS NULL 
							WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND IfCheck='f' AND t1.FYear=@Fyear-1   
							AND i.fieldValue NOT IN (SELECT fieldValue FROM #tempIniData WHERE cid=0)
							GROUP BY t1.FYear,i.fieldValue  
					END 
		END
			
---本期累计
CREATE  TABLE #tempPeriodData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	fieldValue   VARCHAR(50),
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
IF @cid>0  --单币别
	 BEGIN
		--原币
		INSERT INTO #tempPeriodData
 		SELECT t1.FYear,t1.FPeriod,i.fieldValue,SUM(t2.FDebitTotalFor),SUM(t2.FCreditTotalFor),0,Cid
 		FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
		GROUP BY t1.FYear,t1.FPeriod,i.fieldValue,Cid 
		
	 	IF @cid<>@selfcid 
			---本位币         
			INSERT INTO #tempPeriodData
 			SELECT t1.FYear,t1.FPeriod,i.fieldValue,SUM(t2.FDebitTotal),SUM(t2.FCreditTotal),0,0
 			FROM  dbo.Ac_Voucher t1 
			JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND t2.Cid=@cid 
			JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
			JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
			JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
			WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
			GROUP BY t1.FYear,t1.FPeriod,i.fieldValue    
	 END
ELSE IF @cid=-1  --所有币别
	BEGIN
 		INSERT INTO #tempPeriodData
 		SELECT t1.FYear,t1.FPeriod,i.fieldValue,SUM(t2.FDebitTotalFor),SUM(t2.FCreditTotalFor),0,Cid
 		FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) 
        GROUP BY t1.FYear,t1.FPeriod,i.fieldValue,Cid 
		 
		                          
		--综合本位币
	 	INSERT INTO #tempPeriodData
	 	SELECT t1.FYear,t1.FPeriod,i.fieldValue,SUM(t2.FDebitTotal) AS FDebit,SUM(t2.FCreditTotal) AS FCredit,0 AS balance,0
	 	FROM  dbo.Ac_Voucher t1 
		JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
		JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
		JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
		JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
		WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1)
		GROUP BY t1.FYear,t1.FPeriod,i.fieldValue 
	END
ELSE --综合本位币
	INSERT INTO #tempPeriodData
 	SELECT t1.FYear,t1.FPeriod,i.fieldValue,SUM(t2.FDebitTotal) AS FDebit,SUM(t2.FCreditTotal) AS FCredit,0 AS balance,0
 	FROM  dbo.Ac_Voucher t1 
	JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 
	JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
	JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
	JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
	WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND t1.FYear=@Fyear AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1)
	GROUP BY t1.FYear,t1.FPeriod,i.fieldValue 
 
---本年累计
CREATE TABLE #tempYearData
(
	fyear        VARCHAR(10),
	fperiod		 INT,
	fieldValue   VARCHAR(50),
	qichu		  NUMERIC(24, 10) ,   --多加一列期初
	borrow		  NUMERIC(24, 10) ,
	lend          NUMERIC(24, 10) ,
	yearborrow    NUMERIC(24, 10) ,
	yearlend      NUMERIC(24, 10) ,
	balance		  NUMERIC(24, 10) ,
	cid			 INT
)
--建表

WHILE @iniFpeirod<=@fperiodend
	BEGIN
		IF @cid=-1 --所有币别
			BEGIN
				INSERT INTO #tempYearData 
				SELECT @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,CId FROM 
				(
			    SELECT CId FROM dbo.Ac_Currency
			    UNION ALL 
			    SELECT 0 AS cid 
			    ) c,#tempAllAssistItems i     
			END
		ELSE IF @cid>0 --具体币别
			BEGIN
				IF @cid=@selfcid
					INSERT INTO #tempYearData
					Select @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,@cid
					from #tempAllAssistItems i   
				ELSE 
					INSERT INTO #tempYearData
					Select @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,@cid
					from #tempAllAssistItems i   
					UNION ALL 
					Select @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,0
					from #tempAllAssistItems i   
			END
		else   --综合本位币 
			BEGIN
				INSERT INTO #tempYearData
				Select @FYear,@iniFpeirod,fieldValue,0,0,0,0,0,0,0
				from #tempAllAssistItems i   
			END
		
		--更新本期数据
		update y set y.borrow=ISNULL(i.borrow,0),y.lend=ISNULL(i.lend,0)
		from #tempYearData y 
		LEFT join #tempPeriodData i on y.fieldValue=i.fieldValue and y.cid=i.cid AND y.fperiod=i.fperiod
	
		--更新开账的期初期初
		if @iniFpeirod=@fperiod
			BEGIN
				--第一期期初
				update y set y.qichu=i.balance 
				from #tempYearData y 
				join #tempIniData i on y.fieldValue=i.fieldValue and y.cid=i.cid
				WHERE y.fperiod=@iniFpeirod
			END
		else 
			BEGIN
				--取上期的期初
				UPDATE y SET y.qichu=y1.balance 
				FROM #tempYearData y 
				JOIN #tempYearData y1 on y.fieldValue=y1.fieldValue and y.cid=y1.cid and y.fperiod=y1.fperiod+1
				where y.fperiod=@iniFpeirod
			end
	   
	   --计算期末
		IF @Fdc=1 
			UPDATE #tempYearData SET balance=qichu+borrow-lend where fperiod=@iniFpeirod 
		ELSE 
			UPDATE #tempYearData SET balance=qichu-borrow+lend where fperiod=@iniFpeirod
		
		--更新年累计数据
		UPDATE y SET y.yearborrow=isnull(T.borrow,0)+isnull(i.borrow,0),y.yearlend=ISNULL(T.lend,0)+ISNULL(i.lend,0)
	    FROM #tempYearData y 
	    LEFT JOIN  
	    ( select @iniFpeirod as fperiod,fieldValue,cid,sum(borrow) as borrow,sum(lend) as lend
	      from #tempPeriodData where fperiod<=@iniFpeirod group by fieldValue,cid ) T 
	    ON y.fperiod=T.fperiod and y.fieldvalue=T.fieldValue and y.cid=T.cid 
	    LEFT JOIN #tempIniData i ON y.fieldvalue=i.fieldValue and y.cid=i.cid 
	    WHERE y.fperiod=@iniFpeirod
			
		SET @iniFpeirod=@iniFpeirod+1      
	END
	
	 
     
	 --筛选不符合条件的项目
    CREATE TABLE #tempItems
    (
		fieldvalue	  varchar(50),
		periodchange   NUMERIC(24, 10) ,
		balance        NUMERIC(24, 10) 
    )
     IF @cid=@selfcid OR @cid=0     --本位币和综合本位币  
		insert into #tempItems
		select i.fieldvalue,p.periodchange,b.balance from #tempAllAssistItems i 
		join 
		(    
		SELECT fieldValue,balance FROM #tempYearData where fperiod=@fperiodend
		)  b on b.fieldValue=i.fieldValue
		join 
		(
		SELECT fieldValue,SUM(ABS(borrow))+SUM(ABS(lend)) AS periodchange FROM #tempYearData WHERE fperiod>=@fperiodstart AND fperiod<=@fperiodend group by fieldValue
		) p on p.fieldValue=i.fieldValue
	ELSE   --所有币别或外币，直接看综合本位币
		insert into #tempItems
		select i.fieldvalue,p.periodchange,b.balance from #tempAllAssistItems i 
		join 
		(    
		SELECT fieldValue,balance FROM #tempYearData where fperiod=@fperiodend and cid=0
		)  b on b.fieldValue=i.fieldValue
		join 
		(
		SELECT fieldValue,SUM(ABS(borrow))+SUM(ABS(lend)) AS periodchange FROM #tempYearData WHERE fperiod>=@fperiodstart AND fperiod<=@fperiodend and cid=0 group by fieldValue
		) p on p.fieldValue=i.fieldValue
       
 ---------------------凭证
 CREATE TABLE #Voucher
 (
	orderid    INT IDENTITY(1,1),   --算余额的排序列
	fieldvalue	  varchar(50),
	cid         INT,
	fyear        VARCHAR(10),
	fperiod		 INT,
	BILLNUMBERID  INT,
	BILLDATE     DATE,
	FSERIALNAME		VARCHAR(200),			--凭证字号
	vouchertype  NVARCHAR(100),  --凭证类型 
	summary      NVARCHAR(500),
	fdc			VARCHAR(10),			--方向
	borrow		 NUMERIC(24, 10) ,
	lend		 NUMERIC(24, 10) ,
	endbalance		 NUMERIC(24, 10) ,     --余额
	selfborrow	 NUMERIC(24, 10) ,
	selflend		 NUMERIC(24, 10) ,
	selfendbalance		 NUMERIC(24, 10),
	ETypeId		VARCHAR(50) NOT NULL DEFAULT('')--制单人
 )
INSERT INTO #Voucher
SELECT  
	i.fieldValue,
	t2.cid,
	t1.fyear,
	t1.fperiod,
	t1.BILLNUMBERID,
	t1.BILLDATE,
	CASE WHEN @LimitOwnVoucher=1 AND T1.ETypeId<>@chvOperatorID THEN '****' ELSE t5.FullName+'-'+CONVERT(VARCHAR(10),t1.FlowNo) END,
	at.FullName,
	CASE WHEN @LimitOwnVoucher=1 AND T1.ETypeId<>@chvOperatorID THEN '****' ELSE dbo.F_GetSummaryByLimit(t2.ID,@chvOperatorID,t2.STypeID,t2.Summary) END Summary,
	@FdcName,
	t2.FDebitTotalFor,
	t2.FCreditTotalFor,
	0,
	t2.FDebitTotal,
	t2.FCreditTotal,
	0,
	t1.ETypeId
FROM  dbo.Ac_Voucher t1 
JOIN Ac_VoucherType at ON t1.VoucherType=at.id 
JOIN  dbo.Ac_Voucher_Bill t2 ON t1.BillNumberId = t2.BillNumberId AND t2.ATypeId=@atypeid1 AND ((@cid>0 AND t2.Cid=@cid ) OR @cid<=0)
JOIN  dbo.Ac_Voucher_Bill_Assist_CheckItems t3 ON t2.BillNumberId = t3.BillNumberId AND t2.ID = t3.vBId AND t3.typeName=@TypeName
JOIN  AC_VOUCHER_GROUP t5 ON t1.VgId = t5.VgId
JOIN #tempAllAssistItems i ON t3.TypeId=i.fieldValue
WHERE t1.STypeId=@stypeid AND FChecked <> -1 AND t1.Fperiod<=@fperiodend AND ((@IsShowNotPost=0 AND IfCheck='t') or @IsShowNotPost=1) AND t1.FYear=@Fyear
ORDER BY t1.fperiod,i.fieldValue,t1.BILLDATE,t1.BILLNUMBERID 
  
   
  
---更新余额
SET @sql='
	UPDATE v SET v.endbalance=(case when @fdc=1 then y.qichu+v1.tempboroow-v1.templend
									else qichu-v1.tempboroow+v1.templend end )
	FROM #Voucher v 
	JOIN 
	(
		SELECT t.orderid,t.fieldvalue,t.fperiod,t.cid,SUM(t1.borrow) AS tempboroow,SUM(t1.lend) AS templend
		FROM #Voucher t 
		JOIN #Voucher t1 ON t.fieldvalue=t1.fieldvalue AND t.fperiod=t1.fperiod AND t1.orderid<=t.orderid AND t.cid=t1.cid
		GROUP BY t.orderid,t.fieldvalue,t.fperiod,t.cid
	) v1 ON v.orderid=v1.orderid AND v.cid=v1.cid 
	JOIN #tempYearData y ON v.fperiod=y.fperiod AND v.fieldvalue=y.fieldValue  '
IF @cid<>0  --有币别的情况
	SET @sql+=' AND v.cid=y.cid'
EXEC sp_executesql @SQL,N'@fdc INT',@fdc
 
IF @cid=@selfcid
	UPDATE #Voucher SET selfendbalance=endbalance
ELSE 
--综合本位币
	UPDATE v SET v.selfendbalance=(case when @fdc=1 then  y.qichu+v1.selfborrow-v1.selflend 
									else y.qichu-v1.selfborrow+v1.selflend end ) 
	FROM #Voucher v 
	JOIN 
	(
		SELECT t.orderid,t.fieldvalue,t.fperiod,t.cid,SUM(t1.selfborrow) as selfborrow,SUM(t1.selflend) as selflend  
		FROM #Voucher t 
		JOIN #Voucher t1 ON t.fieldvalue=t1.fieldvalue AND t.fperiod=t1.fperiod AND t1.orderid<=t.orderid  
		GROUP BY t.orderid,t.fieldvalue,t.fperiod,t.cid
	) v1 ON v.orderid=v1.orderid AND v.cid=v1.cid 
    JOIN #tempYearData y ON v.fperiod=y.fperiod AND v.fieldvalue=y.fieldValue AND y.cid=0  
    
 
------更新方向
UPDATE #Voucher SET fdc='平' WHERE selfendbalance=0

------合计
 CREATE TABLE #tempSummary 
 (
	fperiod  INT,
    qichu     NUMERIC(24, 10) ,
	borrow    NUMERIC(24, 10) ,
	lend	  NUMERIC(24, 10) ,
	yearborrow    NUMERIC(24, 10) ,
	yearlend	  NUMERIC(24, 10) ,
	balance   NUMERIC(24, 10) ,
	cid		 INT
 )
 INSERT INTO #tempSummary 
 SELECT fperiod,
		SUM(qichu) AS qichu,
		SUM(borrow) AS borrow,
		SUM(lend) AS lend,
		SUM(yearborrow) AS yearborrow,
		SUM(yearlend) AS yearlend,
		SUM(balance) AS balance,
		cid 
 FROM #tempYearData y
 join (
				select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
 ) t on y.fieldValue=t.fieldValue
 GROUP BY fperiod,cid 
  
	IF @cid=0 OR @cid=@selfcid  --本位币单币别或者综合本位币
		BEGIN
			WITH T AS (
			SELECT y.fperiod AS period,
				   0 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.fBEGIN AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '期初余额' AS summary,
				   0 AS debit,
				   0 AS credit,
				   qichu AS balance,
				   CASE WHEN qichu=0 THEN '平' ELSE @fdcname END AS balancefdc,
				   0 AS flag,--排序用
				   0 AS orderid,----排序用
				   '' ETypeId
			FROM #tempYearData y 
			JOIN #tempAllAssistItems i ON y.fieldValue=i.fieldValue
			join (
				select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
			     ) t on y.fieldValue=t.fieldValue
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT y.fperiod AS period,
				   9999998 AS billnumberid,
				   NAME AS atypename, 
				   usercode AS atypeusercode,
				   p.FEnd AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '本期合计' AS summary,
				   y.borrow AS debit,
				   y.lend AS credit,
				   balance AS balance,
				   CASE WHEN balance=0 THEN '平' ELSE @fdcname END AS balancefdc,
				   0 AS flag,--排序用
				   9999998 AS orderid,----排序用
				   '' ETypeId
			FROM #tempYearData y
			JOIN #tempAllAssistItems i ON y.fieldValue=i.fieldValue
			join (
				select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
				 ) t on y.fieldValue=t.fieldValue
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT y.fperiod AS period,
				   9999999 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.FEnd AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '本年累计' AS summary,
				   yearborrow AS debit,
				   yearlend AS credit,
				   balance AS balance,
				   CASE WHEN balance=0 THEN '平' ELSE @fdcname END AS balancefdc,
				   0 AS flag,--排序用
				   9999999 AS orderid,----排序用
				   '' ETypeId
			FROM #tempYearData y
			JOIN #tempAllAssistItems i ON y.fieldValue=i.fieldValue
			join (
				select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
				 ) t on y.fieldValue=t.fieldValue
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT fperiod AS period,
				   billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   BILLDATE AS vouchertime,
				   FSERIALNAME AS vg,
				   vouchertype,
				   summary,
				   selfborrow AS debit,
				   selflend AS credit,
				   selfendbalance AS balance,
				   v.fdc AS balancefdc,
				   0 AS flag,--排序用
				   orderid,
				   V.ETypeId 
			FROM #Voucher v
			JOIN #tempAllAssistItems i ON v.fieldValue=i.fieldValue
			UNION ALL 
			SELECT s.fperiod AS period,
			       10000000 AS billnumerid,
			       '小计' AS atypename,
			       'X' AS atypeusercode,
			        p.fBEGIN AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '期初余额' AS summary,
				   0 AS debit,
				   0 AS credit,
				   qichu AS balance,
				   case when qichu=0 then '平' ELSE @fdcname END AS balancefdc,
				   1 AS flag,--排序用
				   10000000 as orderid,
				   '' ETypeId
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT s.fperiod AS period,
			       10000001 AS billnumerid,
			       '小计' AS atypename,
			       'Y' AS atypeusercode,
			        p.FEnd AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '本期合计' AS summary,
				   borrow AS debit,
				   lend AS credit,
				   balance,
				   case when balance =0 THEN '平' ELSE @fdcname END AS balancefdc,
				   1 AS flag,--排序用
				   10000001 as orderid,
				   '' ETypeId
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT s.fperiod AS period,
			       10000002 AS billnumerid,
			       '小计' AS atypename,
			       'Z' AS atypeusercode,
			        p.FEnd AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '本年累计' AS summary,
				   yearborrow AS debit,
				   yearlend AS credit,
				   balance,
				   case when balance=0 then '平' ELSE @fdcname END AS balancefdc,
				   1 AS flag,--排序用
				   10000002 as orderid,
				   '' ETypeId
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			
			)
			SELECT *,atypeusercode AS atypeid FROM t WHERE period>=@fperiodstart ORDER BY period,flag,atypeusercode,vouchertime,orderid
		END
	ELSE 	
		BEGIN
			-----------------------------------------------------------所有币别是动态列,先求出有多少列----------------------------------------------------------
		    CREATE TABLE #tempColName1
			  (
				cid INT,
				usercode  VARCHAR(200)
			  )
			  IF @cid<>-1  --具体币别
				INSERT INTO #tempColName1
				SELECT CID,USERCODE 
				FROM (SELECT CID,USERCODE FROM AC_CURRENCY WHERE CId=@cid
					  UNION ALL 
					  SELECT 0 AS CID,'' AS USERCODE) b
			  ELSE
				INSERT INTO #tempColName1
			    SELECT CID,USERCODE 
				FROM (SELECT CID,USERCODE FROM AC_CURRENCY
					  UNION ALL 
					  SELECT 0 AS CID,'' AS USERCODE) b
		    
			SELECT COLNAME,FDC
			INTO #tempColName2 
			FROM (
			SELECT 'balance' AS COLNAME,'余额' AS FDC     
			UNION ALL   
			SELECT 'debit' AS COLNAME,'借' AS FDC 
			UNION ALL
			SELECT 'credit' AS COLNAME,'贷' AS FDC 
			) a
			
			SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,CID,FDC 
			INTO #tempColName
			FROM #tempColName1,#tempColName2
			
			--行转列的时候用
			DECLARE @TurnCol VARCHAR(MAX)
			SELECT @TurnCol=(ISNULL(@TurnCol+'],[','') +  colname) 
			FROM #tempColName GROUP BY COLNAME 
			SET @TurnCol='['+@TurnCol+']'
			
			----转换表
			CREATE TABLE #Voucher1
			(
				FPeriod INT,
				fieldValue varchar(50),
				orderID		INT,
				COLNAME	VARCHAR(MAX),
				FVALUE	 NUMERIC(24, 10) 
			)
			INSERT INTO #Voucher1
			SELECT a.FPERIOD,a.fieldValue,a.orderID,b.COLNAME,
					CASE 
						WHEN a.CID=b.CID AND b.FDC='借'   THEN a.borrow
						WHEN a.CID=b.CID AND b.FDC='贷'   THEN a.lend
						WHEN a.CID=b.CID AND b.FDC='余额' THEN a.endbalance
						WHEN b.CID=0 AND b.FDC='借'       THEN a.selfborrow
						WHEN b.CID=0 AND b.FDC='贷'       THEN a.selflend
						WHEN b.CID=0 AND b.FDC='余额'     THEN a.selfendbalance
					END
			FROM #Voucher a,#tempColName b
			 
			create table #temptotal
			(
				period int,
				fieldValue  varchar(50),
				billnumberid int,
				atypename nvarchar(200),
				atypeusercode nvarchar(200),
				vouchertime  date,
				vg           nvarchar(100),
				vouchertype  nvarchar(100),
				summary      nvarchar(500),
				borrow         NUMERIC(24, 10) ,
				lend		 NUMERIC(24, 10) ,
				endbalance	 NUMERIC(24, 10) ,
				balancefdc	NVARCHAR(10),
				orderid     INT,
				cid         INT
			)
			insert into #temptotal
			SELECT y.fperiod AS period,
					y.fieldValue,
				   0 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.fBEGIN AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '期初余额' AS summary,
				   0 AS debit,
				   0 AS credit,
				   qichu AS balance,
				   CASE WHEN qichu=0 THEN '平' ELSE @fdcname END AS balancefdc,
				   0 AS orderid,----排序用
				   y.cid
			FROM #tempYearData y 
			JOIN #tempAllAssistItems i ON y.fieldValue=i.fieldValue
			join (
				select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
			     ) t on y.fieldValue=t.fieldValue
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT y.fperiod AS period,
					y.fieldValue,
				   9999998 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.FEnd AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '本期合计' AS summary,
				   y.borrow AS debit,
				   y.lend AS credit,
				   balance,
				   CASE WHEN balance=0 THEN '平' ELSE @fdcname END AS balancefdc,
				   9999998 AS orderid,----排序用
				   y.cid
			FROM #tempYearData y
			JOIN #tempAllAssistItems i ON y.fieldValue=i.fieldValue
			join (
				select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
				 ) t on y.fieldValue=t.fieldValue
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT y.fperiod AS period,
					y.fieldValue,
				   9999999 AS billnumberid,
				   NAME AS atypename,
				   usercode AS atypeusercode,
				   p.FEnd AS vouchertime,
				   '' AS  vg,
				   '' AS vouchertype,
				   '本年累计' AS summary,
				   yearborrow AS debit,
				   yearlend AS credit,
				   balance,
				   CASE WHEN balance=0 THEN '平' ELSE @fdcname END AS balancefdc,
				   9999999 AS orderid,----排序用
				   y.cid
			FROM #tempYearData y
			JOIN #tempAllAssistItems i ON y.fieldValue=i.fieldValue
			join (
				select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
				 ) t on y.fieldValue=t.fieldValue
			JOIN dbo.Ac_Period p ON p.FPeriod=y.fperiod AND p.FYear=@Fyear
			
		
			
			CREATE TABLE #Total
			(
				FPeriod INT,
				fieldValue varchar(50),
				orderID		INT,
				COLNAME	VARCHAR(MAX),
				FVALUE	 NUMERIC(24, 10) 
			)
			
			INSERT INTO #Total
			SELECT a.PERIOD,a.fieldValue,a.orderid,b.COLNAME,
					CASE 
						WHEN a.CID=b.CID AND b.FDC='借'     THEN a.borrow
						WHEN a.CID=b.CID AND b.FDC='贷'     THEN a.lend
						WHEN a.CID=b.CID AND b.FDC='余额'   THEN a.endbalance
					END
			FROM #temptotal a,#tempColName b 
		 
		   ---合计
		   CREATE TABLE #tempSummaryTotal
            (
				period int,
				atypeid  varchar(50),
				billnumberid int,
				atypename nvarchar(200),
				atypeusercode nvarchar(200),
				vouchertime  date,
				vg           nvarchar(100),
				vouchertype  nvarchar(100),
				summary      nvarchar(500),
				borrow         NUMERIC(24, 10) ,
				lend		 NUMERIC(24, 10) ,
				endbalance	 NUMERIC(24, 10) ,
				balancefdc	NVARCHAR(10),
				orderid     INT,
				cid         INT
            )		  
		    INSERT INTO #tempSummaryTotal
		    SELECT s.fperiod AS period,
				   'X',
			       10000000 AS billnumerid,
			       '小计' AS atypename,
			        'X',
			        p.fBEGIN AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '期初余额' AS summary,
				   0 AS debit,
				   0 AS credit,
				   qichu AS balance,
				   case when qichu=0 then '平' ELSE @fdcname END AS balancefdc,
				   10000000 as orderid,
				   cid
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT s.fperiod AS period,
				   'Y',
			       10000001 AS billnumerid,
			       '小计' AS atypename,
			       'Y' AS atypeusercode,
			        p.FEnd AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '本期合计' AS summary,
				   borrow AS debit,
				   lend AS credit,
				   balance,
				   case when balance=0 then '平' ELSE @fdcname END AS balancefdc,
				   10000001 as orderid,
				   cid
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
			UNION ALL 
			SELECT s.fperiod AS period,
				   'Z',
			       10000002 AS billnumerid,
			       '小计' AS atypename,
			       'Z' AS atypeusercode,
			        p.FEnd AS vouchertime,
			        '' AS  vg,
				   '' AS vouchertype,
				   '本年累计' AS summary,
				   yearborrow AS debit,
				   yearlend AS credit,
				   balance,
				   case when balance=0 then '平' ELSE @fdcname END AS balancefdc,
				   10000002 as orderid,
				   cid
			FROM #tempSummary s 
			JOIN dbo.Ac_Period p ON p.FPeriod=s.fperiod AND p.FYear=@Fyear
		  
		    CREATE TABLE #Summary
			(
				FPeriod INT,
				atypeid varchar(50),
				orderID		INT,
				COLNAME	VARCHAR(MAX),
				FVALUE	 NUMERIC(24, 10) 
			)
			
			INSERT INTO #Summary
			SELECT a.PERIOD,a.atypeid,a.orderid,b.COLNAME,
					CASE 
						WHEN a.CID=b.CID AND b.FDC='借'     THEN a.borrow
						WHEN a.CID=b.CID AND b.FDC='贷'     THEN a.lend
						WHEN a.CID=b.CID AND b.FDC='余额'   THEN a.endbalance
					END
			FROM #tempSummaryTotal a,#tempColName b 
		 
		 
			SET @SQL='SELECT * INTO #Result
						FROM
						(
							SELECT d.FPERIOD as period,
								   d.fieldValue,
								   d.BILLNUMBERID,
								   NAME AS atypename,
								   usercode AS atypeusercode,
								   BILLDATE AS vouchertime,
								   FSERIALNAME AS vg,
								   vouchertype,
								   summary,
								   FDC AS balancefdc,
								   0 as flag,
								   d.orderid,
								   d.ETypeId,'+@TurnCol+'
							FROM #Voucher d
							JOIN 
							(
							SELECT *  FROM  #Voucher1  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
							) c ON d.FPERIOD=c.FPERIOD AND d.orderid=c.orderid AND d.fieldValue=c.fieldValue
							JOIN #tempAllAssistItems i ON d.fieldValue=i.fieldValue
							
							UNION ALL
							
							SELECT d.PERIOD as period,
								   d.fieldValue,
								   d.BILLNUMBERID,
								   d.atypename,
								   d.atypeusercode,
								   vouchertime,
								   vg,
								   vouchertype,
								   summary,
								   balancefdc,
								   0 as flag,
								   d.orderid,
								   '''' ETypeId,'+@TurnCol+'
							FROM #tempTotal d
							JOIN 
							(
								SELECT *  FROM  #Total  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
							) c ON d.PERIOD=c.FPERIOD AND d.orderid=c.orderid AND d.fieldValue=c.fieldValue
							WHERE d.CID=0
							
							UNION ALL
							
							SELECT d.PERIOD as period,
								   d.atypeid,
								   d.BILLNUMBERID,
								   d.atypename,
								   d.atypeusercode,
								   vouchertime,
								   vg,
								   vouchertype,
								   summary,
								   balancefdc,
								   1 as flag,
								   d.orderid,
								   '''' ETypeId,'+@TurnCol+'
							FROM #tempSummaryTotal d
							JOIN 
							(
								SELECT *  FROM  #Summary  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) c
							) c ON d.PERIOD=c.FPERIOD AND d.orderid=c.orderid AND d.atypeid=c.atypeid
							WHERE d.CID=0
						) a  ;
						
						SELECT y.*,y.atypeusercode as atypeid 
						FROM #Result y
						join (
								select fieldValue from #tempItems where ((@IsBalanceNull=1 and periodchange>0) or @IsBalanceNull=0) and  ((@IsBalanceNot=1 and balance<>0) or @IsBalanceNot=0)
								UNION ALL 
								select ''X''
								UNION ALL 
								select ''Y''
								UNION ALL 
								select ''Z''	
							 ) t on y.fieldValue=t.fieldValue
						where period>=@fperiodstart
						ORDER BY period,flag,atypeusercode,vouchertime,orderid;
						
				drop table #Result'	
				EXEC sp_executesql @SQL,N'@IsBalanceNull INT,@IsBalanceNot INT,@fdcname varchar(10),@fperiodstart INT',@IsBalanceNull,@IsBalanceNot,@fdcname,@fperiodstart
				DROP TABLE #Total,#temptotal,#Voucher1,#tempColName,#tempColName1,#tempColName2      
		END
		DROP TABLE #Voucher,#tempAllAssistItems,#tempIniData,#tempPeriodData,#tempYearData,#tempItems
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BalanceQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BalanceQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：徐辉
	日期：2009-7-9（乐乐2月了！！）
	描述：按单结算存储过程
*/
CREATE       PROCEDURE Web_BalanceQuery
(
	@OperatorId		varchar(100),	--操作员Id
	@BillNumberId	varchar(30),	--收付款单单据id（草稿过账单据使用）
	@ReBalance		varchar(1),	--重新结算标志
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@BTypeId		varchar(100),	--往来单位Id
	@ETypeId		varchar(100),	--职员Id
	@KTypeId		varchar(100),	--仓库Id
	@BillTypeList	varchar(100),	--单据类型列表（字串）
	@BillCode		varchar(300),	--单据编号	
	@stypeid		varchar(100),
	@cid			varchar(30)='0',
	@flag			varchar(30)='0',--收付款单标识 0:付款单 1:收款单
	@expensetoar    varchar(30)='0', --费用单核算客户时计入应收
	@comment		varchar(256),     --摘要
	@reconciliationbill int=0,	--对账单据:0,全部显示;1,只显示对账标记;2,不显示对账标记的单据
	@btypelist		varchar(max)='',
	@brandarList    VARCHAR(max)='',
	@isbrandarbalance INT=0			--是否品牌结算
)

AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @OperatorId
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''
DECLARE @SQL_Man_Receipt varchar(1000)
SET @SQL_Man_Receipt=''
IF @btypelist <> ''
BEGIN
	SET @btypelist = ''''+replace(@btypelist,',',''',''')+''''
END
IF @brandarList <> ''
BEGIN
	SET @brandarList = ''''+replace(@brandarList,',',''',''')+''''
END
--职员 
IF @chvMETypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '
	INSERT INTO #F_BaseGetManDetailEType(TypeID) VALUES('')
	CREATE CLUSTERED INDEX #EtypeId_INDEX_TYPEID ON #F_BaseGetManDetailEType(Typeid)
END

-- 分支机构
IF @chvMStypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailsType FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType S ON a.sTypeID = s.TypeID '
	CREATE CLUSTERED INDEX #StypeId_INDEX_TYPEID ON #F_BaseGetManDetailsType(Typeid)
END

-- 部门
IF @chvMdtypeid = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetaildType FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
	INSERT INTO #F_BaseGetManDetaildType(TypeID) VALUES('')
	CREATE CLUSTERED INDEX #DtypeId_INDEX_TYPEID ON #F_BaseGetManDetaildType(Typeid)
END
SET @SQL_Man_Receipt=@SQL_Man
-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('')
	INSERT INTO #F_BaseGetManDetailKType(TypeID) VALUES('10000')
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K
ON (a.KTypeID<>'''' AND a.KTypeID=K.TypeID) OR (a.KTypeID2<>'''' AND a.KTypeID2=K.TypeID) OR (a.KTypeID='''' AND a.KTypeID2='''' AND K.TypeID='''')'
	CREATE CLUSTERED INDEX #KtypeId_INDEX_TYPEID ON #F_BaseGetManDetailKType(Typeid)
END
-- ******** 权限范围单独处理 - End ********
DECLARE @intIfNewBill int
IF @BillNumberId='' OR @BillNumberId IS NULL OR @BillNumberId = '-1' -- 新单据结算
	SET @intIfNewBill = 1
ELSE -- 收付款单草稿，过账单据按单结算
	SET @intIfNewBill = 0
	
--查询单据对应品牌数据，添加带临时表中
CREATE TABLE #barndarType(
id INT IDENTITY(1,1),
BrandarTypeID NVARCHAR(200),
BillNumberId INT,
billtype INT,
ptypeid NVARCHAR(200)
)
SELECT detailTable,SortId,Billtype INTO #DetailTable FROM dbo.BillName WHERE Billtype IN (11,45,160,141,405,12,46,93)
--组合品出库单的品牌应该统计上表体，而不是下表体
update #DetailTable set detailtable='PT_Combin_SaleBill' where billtype=12 or billtype=46

DECLARE @detailTable NVARCHAR(100), @SortId INT=0,@Billtype NVARCHAR(100)

IF @brandarList <> ''
  BEGIN

	WHILE EXISTS(SELECT detailTable FROM #DetailTable)
	BEGIN

		SET ROWCOUNT 1
		SELECT @detailTable=detailTable , @SortId=SortId ,@Billtype=Billtype FROM #DetailTable
		SET ROWCOUNT 0
		IF @Billtype='93'
		BEGIN
			EXEC ('INSERT INTO #barndarType
					( BrandarTypeID ,
					  BillNumberId ,
					  billtype,
					  ptypeid
					)
			SELECT s.BrandarTypeID,s.BillNumberId ,'+@Billtype+',null
			FROM  '+@detailTable+' s 
			INNER JOIN BillIndex bi ON s.BillNumberId=bi.BillNumberId
			WHERE bi.stypeid ='''+@stypeid+''' ')
			--INNER JOIN dbo.Brandar_ArApTotal ba ON ba.BrandarTypeID=s.BrandarTypeID and ba.stypeid ='''+@stypeid+'''')
		END  
		ELSE
		BEGIN
			EXEC(' INSERT INTO #barndarType
					( BrandarTypeID ,
					  BillNumberId ,
					  billtype,
					  ptypeid
					)
			SELECT DISTINCT p.BrandarTypeID,s.BillNumberId ,'+@Billtype+',p.typeID
			FROM dbo.ptype p 
			INNER JOIN '+@detailTable+' s ON p.typeId=s.PtypeId 
			INNER JOIN BillIndex bi ON s.BillNumberId=bi.BillNumberId
			WHERE bi.stypeid ='''+@stypeid+''' and bi.btypeid IN ('''+@BTypeId+''') and p.BrandarTypeID in ('+@brandarList+')')
			--INNER JOIN dbo.Brandar_ArApTotal ba ON ba.BrandarTypeID=p.BrandarTypeID and ba.stypeid ='''+@stypeid+''' where ba.btypeid IN ('''+@BTypeId+''')')
			
		END
  

		DELETE FROM #DetailTable WHERE SortId=@SortId
	END
END


CREATE NONCLUSTERED INDEX #BrandarType_Index_BrandarTypeID ON #barndarType(BrandarTypeID,BillNumberId)


DECLARE @SQL varchar(max)
DECLARE @NSQL VARCHAR(8000)
DECLARE @RSQL VARCHAR(MAX)
DECLARE @ChargeOffSQL VARCHAR(MAX)
SET @SQL = '
	SELECT	DISTINCT 
			a.BillNumberID,
			a.BillType,
			CASE WHEN a.isini = 1 THEN ''期初单据''
				 WHEN a.ifYearBill = 1 THEN ''年结前单据''				 
				 ELSE ''正常单据''
			END AS ifyearbill,
			a.BillDate,
			a.BillCode,
			em.FullName AS eFullName,
			CASE WHEN a.BillType IN (45,46,148,149,6,150,151) THEN -1 ELSE 1 END *
				CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney - a.nchargeofftotal AS  NUMERIC(24, 10) ) AS nunCompleteTotal,
			CASE WHEN a.BillType IN (45,46,148,149,6,150,151) THEN -1 ELSE 1 END * nPreferenceMoney AS nPreferenceMoney,
			CASE WHEN a.BillType IN (45,46,148,149,6,150,151) THEN -1 ELSE 1 END * nTotalMoney AS nCompleteTotal,
			CASE WHEN a.BillType IN (45,46,148,149,6,150,151) THEN -1 ELSE 1 END *
				CAST(a.nTotalInMoney + a.nCompleteTotal AS  NUMERIC(24, 10) ) AS nTotalInMoney,
			ss.fullname as sfullname,
			a.stypeid,
			ac.FullName,
			a.isini, 
			a.jsstate,
			a.jsstyle, 
			'''' as id,
			a.comment,
			a.btypeid,
			a.dealbtypeid,
			bt.fullname as bfullname,
			CASE ISNULL(a.NChargeOffTotal,0) WHEN 0 THEN ''0'' ELSE ''1'' END AS ischarge,
			a.nchargeofftotal,
			BrandarStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype '+CASE WHEN @intIfNewBill = 1 THEN '' ELSE ' AND MoneyBillID<>' + @BillNumberId END + '),0),
			BrandarStatus2=ISNULL(('+CASE WHEN @intIfNewBill = 1 THEN '0' ELSE 'SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype  AND MoneyBillID = ' + @BillNumberId END + '),0),'
--PRINT @intIfNewBill
IF @intIfNewBill = 1
	SET @SQL = @SQL + '
			CAST(null AS DECIMAL) AS NownCompleteTotal,
			GoodStatus1 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			GoodStatus2 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			GoodStatus3 = 0,
			Status = CASE WHEN ISNULL(ct.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'
ELSE
	SET @SQL = @SQL + '
			ct.nCompleteTotal AS NownCompleteTotal,
			ct.IsSelect,
			GoodStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=a.BillNumberID AND BillType=a.BillType),0),
			GoodStatus2=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
			GoodStatus3=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType and MoneyBillID=' + @BillNumberId + '),0),
			Status=ISNULL((SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
			CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'

SET @SQL = @SQL + '
	FROM	BillIndex a ' + @SQL_Man + ' 
	LEFT JOIN Employee em ON a.ETypeID = em.TypeID 
	INNER join stype ss on ss.typeid=a.stypeid 
	INNER JOIN btype bt ON a.dealbtypeid=bt.typeid
	LEFT  JOIN Ac_Currency ac ON a.cid = ac.CId'

--不控制往来单位权限（如果需要控制，放开即可）
--IF @OperatorId<>'00001'
--BEGIN
--	SET @SQL = @SQL+' INNER JOIN btype_l BL ON a.dealbtypeid=BL.TYPEID
--	AND BL.ETYPEID='''+@OperatorId+''''
--END
IF @intIfNewBill = 1
	SET @SQL = @SQL + '
	LEFT JOIN CompleteTotal ct ON a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType
	LEFT JOIN CompleteGoodTotal cgt ON a.BillNumberID = cgt.GoodsBillID AND a.BillType=cgt.BillType'
ELSE
	SET @SQL = @SQL + '
	LEFT JOIN CompleteTotal ct ON ct.MoneyBillID = ' + @BillNumberId + ' AND a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType'

IF @brandarList <> ''
BEGIN
    SET @SQL = @SQL + ' 
    LEFT JOIN #barndarType t ON a.BillNumberId=t.BillNumberId AND a.BillType=t.billtype'
END
	
SET @SQL = @SQL + ' 
	WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			--AND a.BTypeID = ''' + @BTypeId + '''
			AND a.BillType IN (' + @BillTypeList +')
			AND a.BillType NOT IN (36,115,116,128,129)
			AND a.CID = ' + @cid + '
			AND ((a.RedWord = 0 AND a.Draft = 0) OR a.isini=1)
			AND (a.IfStopMoney = 0 OR a.IfStopMoney IS NULL)
			AND CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney AS  NUMERIC(24, 10))<>0
			AND (
				(a.nTotalMoney-a.nCompleteTotal<>0 AND a.nTotalInMoney=0 AND a.nPreferenceMoney=0)
				OR (
					(
						(a.nTotalMoney-(a.nCompleteTotal+a.nTotalInMoney+a.nPreferenceMoney)<0 AND a.nTotalMoney<0)
						OR
						(a.nTotalMoney-(a.nCompleteTotal+a.nTotalInMoney+a.nPreferenceMoney)>0 AND a.nTotalMoney>=0)
					)
					AND (a.nTotalInMoney<>0 OR a.nPreferenceMoney<>0)
				)
				OR (a.BillType IN (160,161) AND a.jsStyle=''2'' AND a.jsState=''1'')
			)
			AND CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney - a.nchargeofftotal AS  NUMERIC(24, 10) ) <> 0
			'
IF @BTypeId <> ''
BEGIN
	SET @SQL = @SQL + ' AND a.BTypeID = ''' + @BTypeId + ''''
END
IF @btypelist <> ''
BEGIN
	SET @SQL = @SQL + ' AND a.dealbtypeid IN ('+@btypelist+')'
END
IF @brandarList <> ''
BEGIN
    SET @SQL = @SQL + ' and t.BrandarTypeID in ('+@brandarList+')'
END
IF @ETypeId <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @ETypeId + ''''
IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @stypeid <> '' SET @SQL = @SQL + ' AND a.sTypeID=''' + @stypeid + ''''
IF @KTypeId <> '' SET @SQL = @SQL + ' AND (a.KTypeID=''' + @KTypeId + ''' OR a.KTypeID2=''' + @KTypeId + ''')'
IF @comment <> '' SET @SQL = @SQL + ' AND a.comment LIKE ''%' + @comment + '%'' '
IF @reconciliationbill ='1' 
BEGIN
	SET @SQL = @SQL + ' AND a.Reconciliation=''t'''
END
ELSE IF @reconciliationbill ='2' 
BEGIN
	SET @SQL = @SQL + ' AND a.Reconciliation<>''t'''
END

SET @SQL = @SQL + '  UNION' 

---------------------------------------------以下单独处理费用单-------------------------------------------
IF (@expensetoar=1 OR @flag=0) AND (@BillTypeList = '36' OR CHARINDEX('36',@BillTypeList)>0 )
BEGIN
SET @RSQL = '
	SELECT	DISTINCT 
			a.BillNumberID,
			a.BillType,
			CASE WHEN a.isini = 1 THEN ''期初单据''
				 WHEN a.ifYearBill = 1 THEN ''年结前单据''				 
				 ELSE ''正常单据''
			END AS ifyearbill,
			a.BillDate,
			a.BillCode,
			em.FullName AS eFullName,'
			
IF @flag = '1'			
SET @RSQL = @RSQL + '-1*CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney - a.nchargeofftotal AS  NUMERIC(24, 10) ) AS nunCompleteTotal,
						 -1*nPreferenceMoney AS nPreferenceMoney,
						 -1*nTotalMoney AS nCompleteTotal,
						 -1*CAST(a.nTotalInMoney + a.nCompleteTotal AS  NUMERIC(24, 10) ) AS nTotalInMoney,'
ELSE
	SET @RSQL = @RSQL + 'CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney - a.nchargeofftotal AS  NUMERIC(24, 10) ) AS nunCompleteTotal,
						 nPreferenceMoney AS nPreferenceMoney,
						 nTotalMoney AS nCompleteTotal,
						 CAST(a.nTotalInMoney + a.nCompleteTotal AS  NUMERIC(24, 10) ) AS nTotalInMoney,'
						 
SET @RSQL= @RSQL + '	
			ss.fullname as sfullname,
			a.stypeid,
			ac.FullName,
			a.isini, 
			a.jsstate,
			a.jsstyle, 
			'''' as id,
			a.comment,
			a.btypeid,
			a.dealbtypeid,
			bt.fullname as bfullname,
			CASE ISNULL(NChargeOffTotal,0) WHEN 0 THEN ''0'' ELSE ''1'' END AS ischarge,
			a.nchargeofftotal,
			BrandarStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype '+CASE WHEN @intIfNewBill = 1 THEN '' ELSE ' AND MoneyBillID<>' + @BillNumberId END + '),0),
			BrandarStatus2=ISNULL(('+CASE WHEN @intIfNewBill = 1 THEN '0' ELSE 'SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype  AND MoneyBillID = ' + @BillNumberId END + '),0),'
			
IF @intIfNewBill = 1
	SET @RSQL = @RSQL + '
			CAST(null AS DECIMAL) AS NownCompleteTotal,
			GoodStatus1 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			GoodStatus2 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			GoodStatus3 = 0,
			Status = CASE WHEN ISNULL(ct.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'
ELSE
	SET @RSQL = @RSQL + '
			ct.nCompleteTotal AS NownCompleteTotal,
			ct.IsSelect,
			GoodStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=a.BillNumberID AND BillType=a.BillType),0),
			GoodStatus2=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
			GoodStatus3=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType and MoneyBillID=' + @BillNumberId + '),0),
			Status=ISNULL((SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
			CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'
SET @RSQL = @RSQL + '
	FROM	BillIndex a ' + @SQL_Man + ' 
	LEFT JOIN Employee em ON a.ETypeID = em.TypeID 
	INNER join stype ss on ss.typeid=a.stypeid 
	INNER JOIN btype bt ON a.dealbtypeid=bt.typeid
	LEFT  JOIN Ac_Currency ac ON a.cid = ac.CId '

--不控制往来单位权限（如果需要控制，放开即可）
--IF @OperatorId<>'00001'
--BEGIN
--	SET @RSQL = @RSQL+' INNER JOIN btype_l BL ON a.dealbtypeid=BL.TYPEID
--	AND BL.ETYPEID='''+@OperatorId+''''
--END
IF @intIfNewBill = 1
	SET @RSQL = @RSQL + '
	LEFT JOIN CompleteTotal ct ON a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType
	LEFT JOIN CompleteGoodTotal cgt ON a.BillNumberID = cgt.GoodsBillID AND cgt.BillType=a.BillType'
ELSE
	SET @RSQL = @RSQL + '
	LEFT JOIN CompleteTotal ct ON ct.MoneyBillID = ' + @BillNumberId + ' AND a.BillNumberID = ct.GoodsBillID'
SET @RSQL = @RSQL + '
	WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			--AND a.BTypeID = ''' + @BTypeId + '''			
			AND a.BillType = 36
			AND a.CID = ' + @cid + '			
			AND ((a.RedWord = 0 AND a.Draft = 0) OR a.isini=1)
			AND (a.IfStopMoney = 0 OR a.IfStopMoney IS NULL)
			AND CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney AS  NUMERIC(24, 10))<>0
			AND (
				(a.nTotalMoney-a.nCompleteTotal<>0 AND a.nTotalInMoney=0 AND a.nPreferenceMoney=0)
				OR (
					(
						(a.nTotalMoney-(a.nCompleteTotal+a.nTotalInMoney+a.nPreferenceMoney)<0 AND a.nTotalMoney<0)
						OR
						(a.nTotalMoney-(a.nCompleteTotal+a.nTotalInMoney+a.nPreferenceMoney)>0 AND a.nTotalMoney>=0)
					)
					AND (a.nTotalInMoney<>0 OR a.nPreferenceMoney<>0)
				)
				OR (a.BillType IN (160,161) AND a.jsStyle=''2'' AND a.jsState=''1'')
			)
			AND CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney - a.nchargeofftotal AS  NUMERIC(24, 10) )<>0
			'
IF @BTypeId <> ''
BEGIN
	SET @RSQL = @RSQL + ' AND a.BTypeID = ''' + @BTypeId + ''''
END
IF @btypelist <> ''
BEGIN
	SET @RSQL = @RSQL + ' AND a.dealbtypeid IN ('+@btypelist+')'
END
IF @expensetoar=1 AND @flag=1
BEGIN
	SET @RSQL = @RSQL + ' 
	AND A.BTypeID LIKE ''00001%'''
END	
IF @expensetoar=1 AND @flag=0
BEGIN
	SET @RSQL = @RSQL + ' 
	AND A.BTypeID LIKE ''00002%'''
END		
IF @ETypeId <> '' SET @RSQL = @RSQL + ' AND a.ETypeID=''' + @ETypeId + ''''
IF @BillCode <> '' SET @RSQL = @RSQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @stypeid <> '' SET @RSQL = @RSQL + ' AND a.sTypeID=''' + @stypeid + ''''
IF @KTypeId <> '' SET @RSQL = @RSQL + ' AND (a.KTypeID=''' + @KTypeId + ''' OR a.KTypeID2=''' + @KTypeId + ''')'
IF @comment <> '' SET @RSQL = @RSQL + ' AND a.comment LIKE ''%' + @comment + '%'' '
IF @reconciliationbill ='1' 
BEGIN
	SET @RSQL = @RSQL + ' AND a.Reconciliation=''t'''
END
ELSE IF @reconciliationbill ='2' 
BEGIN
	SET @RSQL = @RSQL + ' AND a.Reconciliation<>''t'''
END
SET @RSQL = @RSQL + '  UNION' 
END
----------------以下为处理应收款增加/减少单、应付款增加/减少单-------------------------------------------

CREATE TABLE #AdDebtBill
(
	BillNumberId	NUMERIC(18,0),
	BtypeId			VARCHAR(50),
	ntotal			 NUMERIC(24, 10) ,
	TeamNo			INT,
	TeamNO1			INT,
	id				int,
	NCompleteTotal	 NUMERIC(24, 10) ,
	NChargeOffTotal NUMERIC(24, 10),
	STypeID			VARCHAR(50),
	cid				INT ,
	BrandarTypeID   VARCHAR(100)
)
IF @BTypeId <> ''
BEGIN
INSERT INTO #AdDebtBill 
	SELECT	A.BillNumberId,
			A.BtypeId,SUM(A.NTotal) AS ntotal,
			A.TeamNo,
			A.TeamNO1,
			a.id,
			SUM(ISNULL(A.NCompleteTotal,0)) AS NCompleteTotal,
			SUM(ISNULL(A.NChargeOffTotal,0)) AS NChargeOffTotal,
			A.Stypeid,
			ac.CId,
			A.BrandarTypeID
	FROM	AdDebtBill A
	INNER JOIN BillIndex B ON B.BillNumberId = A.BillNumberId
	INNER JOIN Ac_Currency ac ON ac.CId = B.CID
	WHERE	A.BtypeId = @BTypeId
			AND B.BillType IN (115,116,128,129)
			AND (B.ifcheck = 't' OR B.IsIni=1)
			AND  isnull(A.IfStopMoney,0)=0
			AND ((@isbrandarbalance = 0 AND (a.BrandarTypeID = '-99999' OR a.BrandarTypeId = '')) OR (@isbrandarbalance = 1 AND a.BrandarTypeID <>'-99999' AND a.BrandarTypeId <>''))
	GROUP BY A.BillNumberId,A.BtypeId,A.TeamNo,A.TeamNO1,A.Stypeid,ac.CId,a.ID,A.BrandarTypeID
END
ELSE
BEGIN
INSERT INTO #AdDebtBill 
	SELECT	A.BillNumberId,
			A.BtypeId,SUM(A.NTotal) AS ntotal,
			A.TeamNo,
			A.TeamNO1,
			a.id,
			SUM(ISNULL(A.NCompleteTotal,0)) AS NCompleteTotal,
			SUM(ISNULL(A.NChargeOffTotal,0)) AS NChargeOffTotal,
			A.Stypeid,
			ac.CId,
			a.BrandarTypeID
	FROM	AdDebtBill A
	INNER JOIN BillIndex B ON B.BillNumberId = A.BillNumberId
	INNER JOIN Ac_Currency ac ON ac.CId = B.CID
	WHERE	B.BillType IN (115,116,128,129)
			AND (B.ifcheck = 't' OR B.IsIni=1)
			AND  isnull(A.IfStopMoney,0)=0
			AND ((@isbrandarbalance = 0 AND (a.BrandarTypeID = '-99999' OR a.BrandarTypeId = '')) OR (@isbrandarbalance = 1 AND a.BrandarTypeID <>'-99999' AND a.BrandarTypeId <>''))
	GROUP BY A.BillNumberId,A.BtypeId,A.TeamNo,A.TeamNO1,A.Stypeid,ac.CId,a.ID,A.BrandarTypeID
END

CREATE NONCLUSTERED INDEX #AdDebtBill_Index_Billnumberid ON #AdDebtBill(BillNumberId)
	
SET @NSQL = '
	SELECT	DISTINCT a.BillNumberID,
			a.BillType,
			CASE WHEN a.isini = 1 THEN ''期初单据''
				 WHEN a.ifYearBill = 1 THEN ''年结前单据''				 
				 ELSE ''正常单据''
			END AS ifyearbill,
			a.BillDate,
			a.BillCode,
			em.FullName AS eFullName,			
			CASE WHEN a.BillType IN (115,129) THEN -1*CAST(isnull(adb.ntotal,0)- isnull(adb.ncompletetotal,0) - adb.nchargeofftotal AS  NUMERIC(24, 10) )
				 WHEN a.BillType IN (116,128) THEN CAST(isnull(adb.nTotal,0)  - isnull(adb.ncompletetotal,0) - adb.nchargeofftotal AS  NUMERIC(24, 10) ) END AS nunCompleteTotal,
			0 AS nPreferenceMoney,
			CASE WHEN a.BillType IN (115,129) THEN	-1*adb.nTotal
				 WHEN a.BillType IN (116,128) THEN isnull(adb.nTotal,0)  END AS nCompleteTotal,
			CASE WHEN a.BillType IN (115,129) THEN	-1*CAST(isnull(adb.NCompleteTotal,0) AS  NUMERIC(24, 10) )
				 WHEN a.BillType IN (116,128) THEN CAST(isnull(adb.NCompleteTotal,0) AS  NUMERIC(24, 10) ) END AS nTotalInMoney,
			ss.fullname as sfullname,
			a.stypeid, 
			ac.fullname,
			a.isini, 
			a.jsstate,
			a.jsstyle, 
			adb.id,
			a.comment,
			a.btypeid,
			a.dealbtypeid,
			bt.fullname as bfullname,
			CASE ISNULL(adb.NChargeOffTotal,0) WHEN 0 THEN ''0'' ELSE ''1'' END AS ischarge,
			CASE WHEN a.BillType IN (115,129) THEN	-1*adb.nchargeofftotal
				 WHEN a.BillType IN (116,128) THEN isnull(adb.nchargeofftotal,0)  END AS nchargeofftotal,
			BrandarStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype '+CASE WHEN @intIfNewBill = 1 THEN '' ELSE ' AND MoneyBillID<>' + @BillNumberId END + '),0),
			BrandarStatus2=ISNULL(('+CASE WHEN @intIfNewBill = 1 THEN '0' ELSE 'SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype  AND MoneyBillID = ' + @BillNumberId END + '),0),'
IF @intIfNewBill = 1
	SET @NSQL = @NSQL + '
			CAST(null AS DECIMAL) AS NownCompleteTotal,
			GoodStatus1 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			GoodStatus2 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			GoodStatus3 = 0,
			Status = CASE WHEN ISNULL(ct.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
			CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'
ELSE
	SET @NSQL = @NSQL + '
			ct.nCompleteTotal AS NownCompleteTotal,
			ct.IsSelect,
			GoodStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=a.BillNumberID AND BillType=a.BillType),0),
			GoodStatus2=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
			GoodStatus3=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType and MoneyBillID=' + @BillNumberId + '),0),
			Status=ISNULL((SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
			CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'

SET @NSQL = @NSQL + '
	FROM	BillIndex a ' + @SQL_Man + ' 
	LEFT JOIN Employee em ON a.ETypeID = em.TypeID 
	inner join stype ss on ss.typeid=a.stypeid
	LEFT JOIN #AdDebtBill adb ON adb.BillNumberId=a.BillNumberId
	LEFT  JOIN Ac_Currency ac ON a.cid = ac.CId
	LEFT JOIN btype bt ON a.dealbtypeid=bt.typeid '

--应收款增加单、减少单没有往来单位
--IF @OperatorId<>'00001'
--BEGIN
--	SET @NSQL = @NSQL+' INNER JOIN btype_l BL ON a.dealbtypeid=BL.TYPEID
--	AND BL.ETYPEID='''+@OperatorId+''''
--END
IF @intIfNewBill = 1
	SET @NSQL = @NSQL + '
	LEFT JOIN CompleteTotal ct ON a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType
	LEFT JOIN CompleteGoodTotal cgt ON a.BillNumberID = cgt.GoodsBillID AND cgt.BillType=a.BillType'
ELSE
	SET @NSQL = @NSQL + '
	LEFT JOIN CompleteTotal ct ON ct.MoneyBillID = ' + @BillNumberId + ' AND a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType AND adb.id=ct.GoodsBillDetailID '
SET @NSQL = @NSQL + '
	WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			--AND (a.BTypeID = ''' + @BTypeId + ''''+' OR adb.BTypeID = ''' + @BTypeId + ''')
			AND a.BillType IN (115,116,128,129)
			AND a.CID = ' + @cid + '
			AND a.BillType IN (' + @BillTypeList +')
			AND ((a.RedWord = 0 AND a.Draft = 0 AND a.IfYearBill = ''0'') OR a.IsIni=1)
			AND (a.IfStopMoney = 0 OR a.IfStopMoney IS NULL)
			AND CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney AS  NUMERIC(24, 10))<>0
			AND ((a.isini=0 AND abs(adb.ntotal) <> abs(adb.ncompletetotal)) OR (a.isini=1 AND abs(adb.ntotal) <> abs(adb.ncompletetotal)))
			AND CAST(isnull(adb.nTotal,0)  - isnull(adb.ncompletetotal,0) - adb.nchargeofftotal AS  NUMERIC(24, 10) )<>0 
			'
IF @BTypeId <> ''
BEGIN
	SET @NSQL = @NSQL + ' AND (a.BTypeID = ''' + @BTypeId + ''''+' OR adb.BTypeID = ''' + @BTypeId + ''')'
END

--IF @btypelist <> ''
--BEGIN
--	SET @NSQL = @NSQL + ' AND a.dealbtypeid IN ('+@btypelist+')'
--END			
IF @ETypeId <> '' SET @NSQL = @NSQL + ' AND a.ETypeID=''' + @ETypeId + ''''
IF @BillCode <> '' SET @NSQL = @NSQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @stypeid <> '' SET @NSQL = @NSQL + ' AND a.sTypeID=''' + @stypeid + ''''
IF @KTypeId <> '' SET @NSQL = @NSQL + ' AND (a.KTypeID=''' + @KTypeId + ''' OR a.KTypeID2=''' + @KTypeId + ''')'
IF @comment <> '' SET @NSQL = @NSQL + ' AND a.comment LIKE ''%' + @comment + '%'' '
IF @reconciliationbill ='1' 
BEGIN
	SET @NSQL = @NSQL + ' AND a.Reconciliation=''t'''
END
ELSE IF @reconciliationbill ='2' 
BEGIN
	SET @NSQL = @NSQL + ' AND a.Reconciliation<>''t'''
END
IF @brandarList <> ''
BEGIN
    SET @NSQL += ' and adb.BrandarTypeID in ('+@brandarList+')'
END
--PRINT @NSQL
---------------------------采购\销售发货开票 Begin---------------------------------
IF @BillTypeList = '404' OR CHARINDEX('404',@BillTypeList)>0 OR @BillTypeList = '405' OR CHARINDEX('405',@BillTypeList)>0 
BEGIN
	SET @NSQL = @NSQL + ' UNION '
	DECLARE @ReceiptSQL VARCHAR(MAX)
	SET @ReceiptSQL = '
		SELECT	DISTINCT 
				a.BillNumberID,
				a.BillType,
				CASE WHEN a.isini = 1 THEN ''期初单据''
					 WHEN a.ifYearBill = 1 THEN ''年结前单据''				 
					 ELSE ''正常单据''
				END AS ifyearbill,
				a.BillDate,
				a.BillCode,
				em.FullName AS eFullName,
				CAST(a.NTaxTotalMoney - a.nCompleteTotal - a.nchargeofftotal as  NUMERIC(24, 10) )AS nunCompleteTotal,--未结算金额
				0 as nPreferenceMoney,
				a.NTaxTotalMoney AS nCompleteTotal,--发生金额
				a.nCompleteTotal AS nTotalInMoney,
				ss.fullname as sfullname,
				a.stypeid,
				ac.FullName,
				a.isini, 
				a.jsstate,
				a.jsstyle, 
				'''' as id,
				a.comment,
				a.btypeid,
				a.dealbtypeid,
				bt.fullname as bfullname,
				CASE ISNULL(NChargeOffTotal,0) WHEN 0 THEN ''0'' ELSE ''1'' END AS ischarge,
				a.nchargeofftotal,
				BrandarStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype '+CASE WHEN @intIfNewBill = 1 THEN '' ELSE ' AND MoneyBillID<>' + @BillNumberId END + '),0),
				BrandarStatus2=ISNULL(('+CASE WHEN @intIfNewBill = 1 THEN '0' ELSE 'SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype  AND MoneyBillID = ' + @BillNumberId END + '),0),'
	IF @intIfNewBill = 1
		SET @ReceiptSQL = @ReceiptSQL + '
				CAST(null AS DECIMAL) AS NownCompleteTotal,
				GoodStatus1 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				GoodStatus2 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				GoodStatus3 = 0,
				Status = CASE WHEN ISNULL(ct.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'
	ELSE
		SET @ReceiptSQL = @ReceiptSQL + '
				ct.nCompleteTotal AS NownCompleteTotal,
				ct.IsSelect,
				GoodStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=a.BillNumberID AND BillType=a.BillType),0),
				GoodStatus2=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
				GoodStatus3=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType and MoneyBillID=' + @BillNumberId + '),0),
				Status=ISNULL((SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
				CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'

	SET @ReceiptSQL = @ReceiptSQL + '
		FROM	ReceiptBillIndex a ' + @SQL_Man_Receipt + ' 
		LEFT JOIN Employee em ON a.ETypeID = em.TypeID 
		INNER join stype ss on ss.typeid=a.stypeid 
		INNER JOIN btype bt ON a.dealbtypeid=bt.typeid
		LEFT  JOIN Ac_Currency ac ON a.cid = ac.CId '

	IF @intIfNewBill = 1
		SET @ReceiptSQL = @ReceiptSQL + '
		LEFT JOIN CompleteTotal ct ON a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType
		LEFT JOIN CompleteGoodTotal cgt ON a.BillNumberID = cgt.GoodsBillID AND cgt.BillType=a.BillType'
	ELSE
		SET @ReceiptSQL = @ReceiptSQL + '
		LEFT JOIN CompleteTotal ct ON ct.MoneyBillID = ' + @BillNumberId + ' AND a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType'
	IF @brandarList <> ''
	BEGIN
		SET @ReceiptSQL = @ReceiptSQL + ' 
		LEFT JOIN #barndarType t ON a.BillNumberId=t.BillNumberId AND a.BillType=t.billtype'
	END	
	SET @ReceiptSQL = @ReceiptSQL + '
		WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
				--AND a.BTypeID = ''' + @BTypeId + '''
				AND a.BillType IN (' + @BillTypeList +')
				AND a.BillType NOT IN (36,115,116,128,129)
				AND a.CID = ' + @cid + '
				AND ((a.RedWord = 0 AND a.Draft = 0) OR a.isini=1)
				AND (a.IfStopMoney = 0 OR a.IfStopMoney IS NULL)
				AND CAST(a.NTaxTotalMoney - a.nCompleteTotal AS  NUMERIC(24, 10))<>0
				AND (
					(a.NTaxTotalMoney-a.nCompleteTotal<>0)
					OR (
							(a.NTaxTotalMoney-a.nCompleteTotal<0 AND a.NTaxTotalMoney<0)
							OR
							(a.NTaxTotalMoney-a.nCompleteTotal>0 AND a.NTaxTotalMoney>=0)
						)
						AND (a.NTaxTotalMoney<>0)
					OR (a.BillType IN (160,161) AND a.jsStyle=''2'' AND a.jsState=''1'')
				)'
	IF @BTypeId <> ''
	BEGIN
		SET @ReceiptSQL = @ReceiptSQL + ' AND a.BTypeID = ''' + @BTypeId + ''''
	END
	IF @btypelist <> ''
	BEGIN
		SET @ReceiptSQL = @ReceiptSQL + ' AND a.dealbtypeid IN ('+@btypelist+')'
	END
	IF @brandarList <> ''
	BEGIN
		SET @ReceiptSQL = @ReceiptSQL + ' and t.BrandarTypeID in ('+@brandarList+')'
	END
	IF @ETypeId <> '' SET @ReceiptSQL = @ReceiptSQL + ' AND a.ETypeID=''' + @ETypeId + ''''
	IF @BillCode <> '' SET @ReceiptSQL = @ReceiptSQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
	IF @stypeid <> '' SET @ReceiptSQL = @ReceiptSQL + ' AND a.sTypeID=''' + @stypeid + ''''
	--IF @KTypeId <> '' SET @ReceiptSQL = @ReceiptSQL + ' AND (a.KTypeID=''' + @KTypeId + ''' OR a.KTypeID2=''' + @KTypeId + ''')'
	IF @comment <> '' SET @ReceiptSQL = @ReceiptSQL + ' AND a.comment LIKE ''%' + @comment + '%'' '
	IF @reconciliationbill ='1' 
	BEGIN
		SET @ReceiptSQL = @ReceiptSQL + ' AND a.Reconciliation=''t'''
	END
	ELSE IF @reconciliationbill ='2' 
	BEGIN
		SET @ReceiptSQL = @ReceiptSQL + ' AND a.Reconciliation<>''t'''
	END
END
---------------------------采购\销售发货开票 end  ---------------------------------


---------------------------优惠券入库\出库单 Begin---------------------------------
DECLARE @CouponSQL VARCHAR(MAX)
SET @CouponSQL = ''
IF @BillTypeList = '423' OR CHARINDEX('423',@BillTypeList)>0 OR @BillTypeList = '424' OR CHARINDEX('424',@BillTypeList)>0 
	OR @BillTypeList = '426' OR CHARINDEX('426',@BillTypeList)>0 
BEGIN
	SET @CouponSQL =  ' UNION ALL'
	SET @CouponSQL += '
		SELECT	DISTINCT 
				a.BillNumberID,
				a.BillType,
				CASE WHEN a.isini = 1 THEN ''期初单据''
					 WHEN a.ifYearBill = 1 THEN ''年结前单据''				 
					 ELSE ''正常单据''
				END AS ifyearbill,
				a.BillDate,
				a.BillCode,
				em.FullName AS eFullName,
				CASE WHEN a.BillType IN (426) THEN -1 ELSE 1 END * CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney - a.nchargeofftotal as  NUMERIC(24, 10) )AS nunCompleteTotal,--未结算金额
				CASE WHEN a.BillType IN (426) THEN -1 ELSE 1 END * a.nPreferenceMoney as nPreferenceMoney,
				CASE WHEN a.BillType IN (426) THEN -1 ELSE 1 END * a.NTotalMoney AS nCompleteTotal,--发生金额
				CASE WHEN a.BillType IN (426) THEN -1 ELSE 1 END * (a.nTotalInMoney + a.nCompleteTotal) AS nTotalInMoney,
				ss.fullname as sfullname,
				a.stypeid,
				ac.FullName,
				a.isini, 
				a.jsstate,
				1 as jsstyle, 
				'''' as id,
				a.comment,
				a.btypeid,
				a.dealbtypeid,
				bt.fullname as bfullname,
				CASE ISNULL(NChargeOffTotal,0) WHEN 0 THEN ''0'' ELSE ''1'' END AS ischarge,
				CASE WHEN a.BillType IN (426) THEN -1 ELSE 1 END * a.nchargeofftotal AS nchargeofftotal,
				BrandarStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype '+CASE WHEN @intIfNewBill = 1 THEN '' ELSE ' AND MoneyBillID<>' + @BillNumberId END + '),0),
				BrandarStatus2=ISNULL(('+CASE WHEN @intIfNewBill = 1 THEN '0' ELSE 'SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype  AND MoneyBillID = ' + @BillNumberId END + '),0),'
	IF @intIfNewBill = 1
		SET @CouponSQL = @CouponSQL + '
				CAST(null AS DECIMAL) AS NownCompleteTotal,
				GoodStatus1 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				GoodStatus2 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				GoodStatus3 = 0,
				Status = CASE WHEN ISNULL(ct.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation '
	ELSE
		SET @CouponSQL = @CouponSQL + '
				ct.nCompleteTotal AS NownCompleteTotal,
				ct.IsSelect,
				GoodStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=a.BillNumberID AND BillType=a.BillType),0),
				GoodStatus2=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
				GoodStatus3=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType and MoneyBillID=' + @BillNumberId + '),0),
				Status=ISNULL((SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
				CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'

	SET @CouponSQL = @CouponSQL + '
		FROM	Coupon_BillIndex a ' + @SQL_Man_Receipt + ' 
		LEFT JOIN Employee em ON a.ETypeID = em.TypeID 
		INNER join stype ss on ss.typeid=a.stypeid 
		INNER JOIN btype bt ON a.dealbtypeid=bt.typeid
		LEFT  JOIN Ac_Currency ac ON a.cid = ac.CId '

	IF @intIfNewBill = 1
		SET @CouponSQL = @CouponSQL + '
		LEFT JOIN CompleteTotal ct ON a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType
		LEFT JOIN CompleteGoodTotal cgt ON a.BillNumberID = cgt.GoodsBillID AND cgt.BillType=a.BillType'
	ELSE
		SET @CouponSQL = @CouponSQL + '
		LEFT JOIN CompleteTotal ct ON ct.MoneyBillID = ' + @BillNumberId + ' AND a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType'
	SET @CouponSQL = @CouponSQL + '
		WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
				AND a.BillType IN (' + @BillTypeList +')
				AND a.CID = ' + @cid + '
				AND ((a.RedWord = 0 AND a.Draft = 0) OR a.isini=1)
				AND CAST(a.NTotalMoney - a.nCompleteTotal - a.nchargeofftotal AS  NUMERIC(24, 10))<>0
				AND a.jsState<>2 '
				
	IF NOT(@BillTypeList = '426' OR CHARINDEX('426',@BillTypeList)>0)
		SET @CouponSQL += '
				AND a.FromType = 2
				'
				
	IF @BTypeId <> ''
	BEGIN
		SET @CouponSQL = @CouponSQL + ' AND a.BTypeID = ''' + @BTypeId + ''''
	END
	IF @btypelist <> ''
	BEGIN
		SET @CouponSQL = @CouponSQL + ' AND a.dealbtypeid IN ('+@btypelist+')'
	END
	IF @ETypeId <> '' SET @CouponSQL = @CouponSQL + ' AND a.ETypeID=''' + @ETypeId + ''''
	IF @BillCode <> '' SET @CouponSQL = @CouponSQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
	IF @stypeid <> '' SET @CouponSQL = @CouponSQL + ' AND a.sTypeID=''' + @stypeid + ''''
	--IF @KTypeId <> '' SET @ReceiptSQL = @ReceiptSQL + ' AND (a.KTypeID=''' + @KTypeId + ''' OR a.KTypeID2=''' + @KTypeId + ''')'
	IF @comment <> '' SET @CouponSQL = @CouponSQL + ' AND a.comment LIKE ''%' + @comment + '%'' '
	
	IF @reconciliationbill ='1' 
	BEGIN
		SET @CouponSQL = @CouponSQL + ' AND a.Reconciliation=''t'''
	END
	ELSE IF @reconciliationbill ='2' 
	BEGIN
		SET @CouponSQL = @CouponSQL + ' AND a.Reconciliation<>''t'''
	END
END
---------------------------优惠券入库\出库单 end  ---------------------------------

---------------------------往来核销单 start  ---------------------------------
IF @BillTypeList = '450' OR CHARINDEX('450',@BillTypeList)>0
BEGIN
	SET @ChargeOffSQL = ' UNION 
		SELECT	DISTINCT 
				a.BillNumberID,
				a.BillType,
				CASE WHEN a.isini = 1 THEN ''期初单据''
					 WHEN a.ifYearBill = 1 THEN ''年结前单据''				 
					 ELSE ''正常单据''
				END AS ifyearbill,
				a.BillDate,
				a.BillCode,
				em.FullName AS eFullName,
				CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nchargeofftotal AS  NUMERIC(24, 10) ) AS nunCompleteTotal,
				nPreferenceMoney AS nPreferenceMoney,
				nTotalMoney AS nCompleteTotal,
				CAST(a.nTotalInMoney + a.nCompleteTotal AS  NUMERIC(24, 10) ) AS nTotalInMoney,
				ss.fullname as sfullname,
				a.stypeid,
				ac.FullName,
				a.isini, 
				a.jsstate,
				a.jsstyle, 
				'''' as id,
				a.comment,
				a.btypeid,
				a.dealbtypeid,
				bt.fullname as bfullname,
				CASE ISNULL(a.NChargeOffTotal,0) WHEN 0 THEN ''0'' ELSE ''1'' END AS ischarge,
				a.nchargeofftotal,
				BrandarStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype '+CASE WHEN @intIfNewBill = 1 THEN '' ELSE ' AND MoneyBillID<>' + @BillNumberId END + '),0),
				BrandarStatus2=ISNULL(('+CASE WHEN @intIfNewBill = 1 THEN '0' ELSE 'SELECT TOP 1 1 FROM CompleteBrandarTotal WHERE GoodsbillID=a.BillNumberID AND BillType = a.billtype  AND MoneyBillID = ' + @BillNumberId END + '),0),'
	IF @intIfNewBill = 1
		SET @ChargeOffSQL = @ChargeOffSQL + '
				CAST(null AS DECIMAL) AS NownCompleteTotal,
				GoodStatus1 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				GoodStatus2 = CASE WHEN ISNULL(cgt.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				GoodStatus3 = 0,
				Status = CASE WHEN ISNULL(ct.GoodsBillID,0) = 0 THEN 0 ELSE 1 END,
				CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'
	ELSE
		SET @ChargeOffSQL = @ChargeOffSQL + '
				ct.nCompleteTotal AS NownCompleteTotal,
				ct.IsSelect,
				GoodStatus1=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsBillID=a.BillNumberID AND BillType=a.BillType),0),
				GoodStatus2=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
				GoodStatus3=ISNULL((SELECT TOP 1 1 FROM CompleteGoodTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType and MoneyBillID=' + @BillNumberId + '),0),
				Status=ISNULL((SELECT TOP 1 1 FROM CompleteTotal WHERE GoodsbillID=a.BillNumberID AND BillType=a.BillType AND MoneyBillID<>' + @BillNumberId + '),0),
				CASE WHEN a.Reconciliation=''t'' THEN ''√'' ELSE '''' END AS reconciliation'

	SET @ChargeOffSQL = @ChargeOffSQL + '
		FROM	BillIndex a ' + @SQL_Man + ' 
		INNER JOIN stype ss on ss.typeid=a.stypeid 
		INNER JOIN Employee em ON a.ETypeID = em.TypeID 
		LEFT JOIN btype bt ON a.chargeoffbtypeid=bt.typeid
		LEFT  JOIN Ac_Currency ac ON a.cid = ac.CId '
	IF @intIfNewBill = 1
		SET @ChargeOffSQL = @ChargeOffSQL + '
		LEFT JOIN CompleteTotal ct ON a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType
		LEFT JOIN CompleteGoodTotal cgt ON a.BillNumberID = cgt.GoodsBillID AND a.BillType=cgt.BillType'
	ELSE
		SET @ChargeOffSQL = @ChargeOffSQL + '
		LEFT JOIN CompleteTotal ct ON ct.MoneyBillID = ' + @BillNumberId + ' AND a.BillNumberID = ct.GoodsBillID AND ct.BillType=a.BillType'
	SET @ChargeOffSQL = @ChargeOffSQL + '
		WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
				AND a.BillType = 450 
				AND a.CID = ' + @cid + '
				AND ((a.RedWord = 0 AND a.Draft = 0) OR a.isini=1)
				AND (a.IfStopMoney = 0 OR a.IfStopMoney IS NULL)
				AND CAST(a.nTotalMoney - a.nTotalInMoney - a.nCompleteTotal - a.nPreferenceMoney -a.NChargeOffTotal AS  NUMERIC(24, 10))<>0
				AND (
					(a.nTotalMoney-a.nCompleteTotal<>0 AND a.nTotalInMoney=0 AND a.nPreferenceMoney=0)
					OR (
						(
							(a.nTotalMoney-(a.nCompleteTotal+a.nTotalInMoney+a.nPreferenceMoney)<0 AND a.nTotalMoney<0)
							OR
							(a.nTotalMoney-(a.nCompleteTotal+a.nTotalInMoney+a.nPreferenceMoney)>0 AND a.nTotalMoney>=0)
						)
						AND (a.nTotalInMoney<>0 OR a.nPreferenceMoney<>0)
					)
					OR (a.BillType IN (160,161) AND a.jsStyle=''2'' AND a.jsState=''1'')
				)'
	IF @flag=0
	BEGIN
		SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.chargeofftype IN (3,4) '
	END
	ELSE IF @flag=1
	BEGIN
		SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.chargeofftype IN (2,5)'
	END
	IF @BTypeId <> ''
	BEGIN
		SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.BTypeID = ''' + @BTypeId + ''''
	END
	IF @btypelist <> ''
	BEGIN
		SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.chargeoffbtypeid IN ('+@btypelist+')'
	END
	IF @ETypeId <> '' SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.ETypeID=''' + @ETypeId + ''''
	IF @BillCode <> '' SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
	IF @stypeid <> '' SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.sTypeID=''' + @stypeid + ''''
	IF @KTypeId <> '' SET @ChargeOffSQL = @ChargeOffSQL + ' AND (a.KTypeID=''' + @KTypeId + ''' OR a.KTypeID2=''' + @KTypeId + ''')'
	IF @comment <> '' SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.comment LIKE ''%' + @comment + '%'' '
	IF @reconciliationbill ='1' 
	BEGIN
		SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.Reconciliation=''t'''
	END
	ELSE IF @reconciliationbill ='2' 
	BEGIN
		SET @ChargeOffSQL = @ChargeOffSQL + ' AND a.Reconciliation<>''t'''
	END
END
---------------------------往来核销单 end  ---------------------------------
--SET @NSQL = @NSQL + ' ORDER BY a.BillDate,a.BillCode ASC '
--PRINT @SQL
--PRINT @RSQL
--PRINT @NSQL
--PRINT @ReceiptSQL
--PRINT @ChargeOffSQL
--print @CouponSQL
EXEC (@SQL+@RSQL+@NSQL+@ReceiptSQL+@CouponSQL+@ChargeOffSQL + ' ORDER BY BillDate,BillCode ASC ')
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMETypeID = '-99999' DROP TABLE #F_BaseGetManDetailEType
IF @chvMStypeid = '-99999' DROP TABLE #F_BaseGetManDetailsType
DROP TABLE #AdDebtBill,#barndarType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BalanceSheetQuery]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].Web_BalanceSheetQuery
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO


CREATE  PROCEDURE [dbo].[Web_BalanceSheetQuery]
(
	@OperatorID	varchar(50),		--操作员ID
	--@szFlag		varchar(10)=null,
	@StypeId	varchar(max),		--分支机构id
	@ifDate		INT,
	@Period	varchar(2)='',
	@year		INT=2016,
	@enddate varchar(50)='',	-- 结束日期
	@HideZero int=0,	-- 0显示，1隐藏
	@itemLeveal int = 10    --项目级次
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE 
	@ALL_INCOME_ID varchar(50),       
	@ALL_EXPENSE_ID varchar(50),                
	@ASSETS_ID varchar(50),           
	@DEBT_ID varchar(50)             

SELECT @ALL_INCOME_ID='00003' --          【收入类】
SELECT @ALL_EXPENSE_ID='00004'--         【支出类】
SELECT @ASSETS_ID ='00001'  --【资产合计】
SELECT @DEBT_ID='00002'   --【负债合计】

SET @itemLeveal = @itemLeveal + 1
IF @enddate='' SET @enddate=GETDATE()

DECLARE @proinfo int
SELECT @proinfo=subvalue FROM sysdata where subname='proinfo'

--判断资产负债表的权限
DECLARE @re INT 
EXEC @re = GP_CheckLimit @OperatorID,4226

CREATE TABLE #Stype (TypeID varchar(50),IfAssetsIni int)

INSERT INTO #Stype(typeid,IfAssetsIni)  
	select a.typeid,c.IfAssetsIni
		FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) a
		JOIN stype c ON a.typeid=c.TypeId

CREATE TABLE #t1(atypeid NVARCHAR(50),total  NUMERIC(24, 10));

INSERT INTO #t1	
	SELECT atypeid,ISNULL(SUM(total),0) AS total 
	FROM ListTable
	WHERE billdate <=@enddate  AND STypeID IN ( SELECT typeId FROM #Stype )
	GROUP BY atypeid

--是否启用发票立账
DECLARE @isinvoice INT
SET @isinvoice = ISNULL((SELECT SubValue FROM dbo.sysdata WHERE SubName = 'isinvoice'),0)

--2015-05-18 杨俊修改 因需求HH，强烈需要这样干，所以把[发出商品]放在[库存商品总值]下一行、[应付暂估]放在[应付合计]下一行
SELECT  p.nparid AS parid ,
		p.deleted ,
		p.leveal ,
		p.ntypeId AS typeid,
		CASE FullName
			WHEN '发出商品' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '库存商品总值') + '1'
			WHEN '应付暂估' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '应付合计') + '1'
			ELSE p.ntypeId
		END AS ordertypeid,
		p.UserCode ,
		p.FullName ,
		p.sonnum ,
		ISNULL(s.Total00,0)+ISNULL(t1.total,0) AS total ,
		ISNULL(s.total00,0) AS total00,
		nId
INTO    #Atype
FROM    dbo.Ac_Items p
		LEFT JOIN ( 
			SELECT a.atypeid,SUM(a.Total00) AS total00
			FROM dbo.AType_Total a
			INNER JOIN #Stype s ON a.STypeID=s.typeid
			GROUP BY a.ATypeID
		) s ON s.ATypeID = p.nId
		LEFT JOIN #t1 t1 ON t1.atypeid=p.nId
WHERE   p.ntypeId <> '00000'
	AND (NOT(@isinvoice = 0)--是否启用发票立账
	OR (@isinvoice = 0) AND P.UserCode NOT IN('1251','2122'))

IF @re =1	--没有查看损益表所有项目的权限
BEGIN
	DELETE 
	FROM	#Atype 
	WHERE	typeid NOT IN (
		SELECT nTypeId FROM F_AllTreeAssetsT(@OperatorID)--资产合计(固定资产+银行账户+管辖其他资产)
		UNION ALL
		SELECT nTypeId FROM F_AllTreeInDebtT(@OperatorID)--负债合计（管辖负债+账户里面的预收）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeOwnerEquityT(@OperatorID)--所有者权益
		UNION ALL
		SELECT '00001' AS nTypeId
		UNION ALL
		SELECT '00002' AS nTypeId
		UNION ALL
		SELECT '00005' AS nTypeId
		UNION ALL
		SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出）		
	)
END

SELECT	a.* 
INTO	#MonthProc
FROM	MonthProc a
INNER JOIN(
	SELECT MIN(Year) AS YE,MIN(period) AS period,STypeID FROM dbo.MonthProc  GROUP BY STypeID 
)B	ON A.Year=B.YE AND A.STypeID=B.STypeID 
WHERE A.period=b.period
		
-- 控制显示 
-- 资产负债表调整成分支机构合计的方式 --
DECLARE @display_1 INT=0;


CREATE TABLE #stypeinfo (stypeid VARCHAR(100),iniDate DATETIME,iscard INT,val  NUMERIC(24, 10) )

INSERT INTO #stypeinfo 
SELECT  a.typeid,
		b.InitDate,
		CASE WHEN EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'assets' AND SubValue = '1') THEN 1 ELSE 0 END,
		0.0 
FROM	#stype a 
LEFT JOIN (
			SELECT u.*,v.typeid FROM Ac_FixedAssetsInit_Stype u JOIN stype v ON u.stypeid=v.VerifyID
) b ON a.typeid=b.typeid;
   
--卡片模式才统计卡片的数据
IF  EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
BEGIN
	-- 取卡片的
	UPDATE #stypeinfo SET iscard=1 
	FROM #MonthProc m 
	WHERE #stypeinfo.stypeid=m.stypeid 
	and iniDate<=ISNULL(m.enddate,@enddate)

	SELECT @display_1=1 WHERE EXISTS(SELECT 1 FROM #stypeinfo WHERE iscard=1) --显示为卡片

	-- 卡片数据
	;WITH cte AS (
		SELECT rn=ROW_NUMBER() over(PARTITION BY STypeId,AssertsCardId ORDER BY BusinessDate desc,id desc),Id,STypeId,AssertsCardId,NetValue,a.BillType 
		FROM Ac_AssetsCards_History a 
		WHERE CAST(a.BusinessDate AS date)<=@enddate AND a.audittype NOT IN (-3,-4)
			AND a.STypeId IN (SELECT typeid FROM #stype)
	)
	UPDATE a SET a.val=b.NetValue 
	FROM #stypeinfo a 
	JOIN (
		SELECT stypeid,SUM(netvalue) AS netvalue FROM cte WHERE rn=1 AND (billtype<>213 OR billtype IS NULL)
		 GROUP BY stypeid
	) b ON a.stypeid=b.stypeid WHERE a.iscard=1
END
ELSE
BEGIN
	-- 项目数据
	UPDATE a SET a.val=b.total FROM #stypeinfo a 
	 INNER JOIN (
		 SELECT stypeid,ISNULL(SUM(total),0) AS total 
		 FROM dbo.AType_Total WHERE atypeid LIKE'0000100002%' GROUP BY stypeid
	) b ON a.stypeid=b.stypeid
	WHERE a.iscard=0 
END


IF @ifDate=2
BEGIN
	IF NOT EXISTS(SELECT 1 FROM #stypeinfo WHERE iscard=0) --全部卡片
		SELECT 1 AS datacase
	ELSE IF EXISTS(SELECT 1 FROM #stypeinfo WHERE iscard=1) --混合的
		SELECT 2 AS datacase
	ELSE --项目
		SELECT 0 AS datacase
	
	DROP TABLE #stypeinfo,#stype,#Atype,#t1	
	RETURN
END	

 --资产
create table #Tmp
(
	id   int IDENTITY (1,1),
	usercode varchar(300),
	fullname varchar(300),
	leveal int,
	typeid varchar(50),
	sonnum int,
	parid varchar(50),  
	total  NUMERIC(24, 10) ,      
)
--负债
create table #Tmp1
(
	id   int IDENTITY (1,1),
	fullname1 varchar(300),
	leveal1 int,
	total1  NUMERIC(24, 10) ,
	parid1 varchar(50),
	typeid1 varchar(50),
	Sonnum1 int       
)
--资产负债
create table #Tmp2
(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	usercode varchar(300),
	fullname varchar(300),
	leveal int,
	typeid varchar(50),
	sonnum int,
	parid varchar(50),
	total  NUMERIC(24, 10) ,
	fullname1 varchar(300),
	leveal1 int,
	total1  NUMERIC(24, 10) ,
	parid1 varchar(50),
	typeid1 varchar(50),
	Sonnum1 int              
)


DECLARE @dTotalIncom  NUMERIC(24, 10) ,@dTotalExpense  NUMERIC(24, 10) 
IF @Period=''
BEGIN
	--收入
	SELECT @dTotalIncom=isnull(sum(total),0) FROM #Atype WHERE left(typeid,5)=@ALL_INCOME_ID
	--支出类
	SELECT @dTotalExpense=isnull(sum(total),0) FROM #Atype WHERE left(typeid,5)=@ALL_EXPENSE_ID

	Create TABLE #Bassert
	(
		[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
		usercode varchar(300),
		fullname varchar(300),
		leveal int,
		typeid varchar(50),
		sonnum int,
		parid varchar(50),
		total  NUMERIC(24, 10) ,
		fullname1 varchar(300),
		leveal1 int,
		total1  NUMERIC(24, 10) ,
		parid1 varchar(50),
		typeid1 varchar(50),
		Sonnum1 int
	)
	DECLARE @MaxID int
	SET @MaxID =0

	INSERT  INTO #Bassert
			( usercode ,
			  fullname ,
			  leveal ,
			  typeid ,
			  sonnum ,
			  parid ,
			  total
			)
			SELECT  a.usercode ,
					a.fullname ,
					a.leveal ,
					a.typeid ,
					a.sonnum ,
					a.parid ,
					( SELECT    ISNULL(SUM(b.total), 0)
					  FROM      #Atype b
					  WHERE     LEFT(b.typeid, LEN(a.typeid)) = a.typeid
					) AS 'Total'
			FROM    #Atype a
			WHERE   LEFT(a.typeid, 5) = @ASSETS_ID
					AND a.typeid <> '0000200002'
					AND a.typeid <> '0000100006'
					-- 卡片管理 固定资产
					AND (@display_1=1 
							AND (a.typeid NOT LIKE '0000100002%' OR a.typeid ='0000100002')
						OR @display_1<>1)
				
					AND a.usercode NOT IN ('SYC-1601','SYC-1602')
			ORDER BY a.ordertypeid
			
	SET @MaxID =@@Rowcount 

	DECLARE @fullname1 varchar(300)
	DECLARE @leveal1 int
	DECLARE @Total1  NUMERIC(24, 10) 
	DECLARE @typeid1 varchar(50)
	DECLARE @parid1 varchar(50)
	DECLARE @sonnum1 int
	DECLARE @j int
	SET @j =1
	DECLARE BassCurSor CURSOR FOR	
	SELECT a.fullname,a.leveal,a.typeid,a.parid,a.sonnum,
	(
		SELECT isnull(sum(b.total),0) 
		FROM #Atype b
		WHERE left(b.typeid,len(a.typeid))=a.typeid
	) as 'Total' 
	FROM #Atype a 
	WHERE a.typeid<>'0000200002' and a.typeid<>'0000100006' and (left(a.typeid,5)=@DEBT_ID
		or (left(a.typeid,5)='00005' ))
	order by a.ordertypeid
	
	OPEN BassCurSor
	FETCH NEXT FROM BassCurSor INTO @fullname1,@leveal1,@typeid1,@parid1,@sonnum1,@Total1
	WHILE @@FETCH_STATUS =0
	BEGIN
	IF @j<=@MaxID
	BEGIN
		UPDATE #Bassert SET fullname1=@fullname1,leveal1=@leveal1,total1=@Total1,typeid1=@typeid1,parid1=@parid1,sonnum1=@sonnum1 WHERE [ID]=@j
	END	
	ELSE
	BEGIN
		INSERT INTO #Bassert(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) SELECT @fullname1,@leveal1,@Total1,@typeid1,@parid1,@sonnum1
	END
	SET @j = @j + 1
	FETCH NEXT FROM BassCurSor INTO @fullname1,@leveal1,@typeid1,@parid1,@sonnum1,@Total1
	END
	CLOSE BassCurSor
	DEALLOCATE BassCurSor

	-- 内部应收合计
	UPDATE #Bassert SET total=(
			SELECT ISNULL(SUM(total),0) FROM dbo.ListTable
			WHERE atypeid=28 AND stypeid IN (SELECT typeid FROM #stype)
			AND billdate <=@enddate --同 billdate<=@ed
		)+(SELECT ISNULL(SUM(InnerARTotal00),0) FROM dbo.SType_InnerARTotal WHERE stypeid IN (SELECT typeid FROM #stype))
	WHERE typeid='0000100010'
	
	--V1没有内部应收
	--IF @proinfo = 4 
	--	DELETE FROM #Bassert WHERE  typeid='0000100010'

	IF(@display_1=1)
	BEGIN
		UPDATE #Bassert SET total= (SELECT SUM(val) FROM #stypeinfo) WHERE typeid='0000100002'
	END
			
	-- 资产合计
	UPDATE #Bassert SET total=(SELECT sum(isnull(total,0)) FROM #Bassert WHERE parid='00001' ) WHERE typeid='00001'
	
	--应付款合计
	--UPDATE #Bassert SET total1=(SELECT total FROM #atype WHERE nid=35) WHERE typeid1='0000200001'
	
	-- 修改负债合计
	UPDATE #Bassert SET total1=(SELECT sum(isnull(Total1,0)) as total FROM #Bassert WHERE  typeid1 NOT in ('0000200002') AND LEFT(parid1,5)='00002' and sonnum1=0 ) WHERE typeid1='00002'
	
	--UPDATE #Bassert SET total1=total1+(SELECT sum(isnull(Total1,0)) as total FROM #Bassert WHERE  typeid1 ='0000200001' ) WHERE typeid1='00002' -- +应付
	
	
	-- 未分配利润
	UPDATE #Bassert SET total1=total1+((SELECT ISNULL(sum(total),0)-ISNULL(SUM(total00),0) FROM #Atype WHERE typeid like '00003%' and sonnum=0)-(SELECT ISNULL(sum(total),0)-ISNULL(SUM(total00),0) FROM #Atype WHERE typeid like '00004%' and sonnum=0)) WHERE typeid1='0000500005'
		
	-- 修改所有者权益 = 资产-负债
	UPDATE #Bassert SET total1=(SELECT total FROM #Bassert WHERE typeid in ('00001'))-(SELECT total1 FROM #Bassert WHERE typeid1 in ('00002') ) WHERE typeid1='00005'

	--其他资本
	UPDATE #Bassert SET total1=(SELECT total1 FROM #Bassert WHERE typeid1 ='00005')-(SELECT ISNULL(SUM(total1),0) FROM #Bassert WHERE typeid1 LIKE '00005%' AND typeid1<>'0000500002' AND sonnum1=0) WHERE typeid1='0000500002'
	
	
	UPDATE  #Bassert SET fullname='    '+isnull(fullname,'') WHERE leveal=2 
	UPDATE  #Bassert SET fullname1='    '+isnull(fullname1,'') WHERE leveal1=2
	
	UPDATE  #Bassert SET fullname='        '+isnull(fullname,'') WHERE leveal=3
	UPDATE  #Bassert SET fullname1='        '+isnull(fullname1,'') WHERE leveal1=3
	
	UPDATE  #Bassert SET fullname='            '+isnull(fullname,'') WHERE leveal=4
	UPDATE  #Bassert SET fullname1='            '+isnull(fullname1,'') WHERE leveal1=4
	
	UPDATE  #Bassert SET fullname='                '+isnull(fullname,'') WHERE leveal=5
	UPDATE  #Bassert SET fullname1='                '+isnull(fullname1,'') WHERE leveal1=5

	UPDATE  #Bassert SET fullname='                    '+isnull(fullname,'') WHERE leveal=6
	UPDATE  #Bassert SET fullname1='                    '+isnull(fullname1,'') WHERE leveal1=6

	UPDATE  #Bassert SET fullname='                        '+isnull(fullname,'') WHERE leveal=7
	UPDATE  #Bassert SET fullname1='                        '+isnull(fullname1,'') WHERE leveal1=7

	UPDATE  #Bassert SET fullname='                            '+isnull(fullname,'') WHERE leveal=8
	UPDATE  #Bassert SET fullname1='                            '+isnull(fullname1,'') WHERE leveal1=8

	UPDATE  #Bassert SET fullname='                                '+isnull(fullname,'') WHERE leveal=9
	UPDATE  #Bassert SET fullname1='                                '+isnull(fullname1,'') WHERE leveal1=9

	UPDATE  #Bassert SET fullname='                                    '+isnull(fullname,'') WHERE leveal=10
	UPDATE  #Bassert SET fullname1='                                    '+isnull(fullname1,'') WHERE leveal1=10	

	IF @hidezero=1
	BEGIN
		;WITH c1 AS (
			SELECT rn=ROW_NUMBER() OVER(ORDER BY a.id),ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname,ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE ISNULL(a.total,0) END AS total ,a.Leveal
			FROM #Bassert a 
			WHERE ISNULL(a.total,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #bassert b WHERE a.typeid like b.typeid+'%' AND b.total=0 AND b.sonnum<>0 )
		),c2 AS (
			SELECT rn=ROW_NUMBER() OVER(ORDER BY id), ISNULL(a.typeid1,'') AS typeid1,ISNULL(a.parid1,'') AS parid1,ISNULL(a.fullname1,'') AS fullname1,ISNULL(a.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(typeid1,'')='' THEN total1 ELSE  ISNULL(total1,0) END AS total1,a.Leveal1
			FROM #Bassert a WHERE ISNULL(total1,0)<>0
			AND NOT EXISTS(SELECT 1 FROM #bassert b WHERE a.typeid1 LIKE b.typeid1+'%' AND b.total1=0 AND b.sonnum<>0 )
		)
		INSERT INTO #Tmp2(typeid,parid,usercode , fullname , sonnum,total,  typeid1 ,  parid1 , fullname1 , Sonnum1,total1 ,leveal , leveal1)
		SELECT ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname, ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE  ISNULL(a.total,0) END  AS total
				,ISNULL(b.typeid1,'') AS typeid1,ISNULL(b.parid1,'') AS parid1,ISNULL(b.fullname1,'') AS fullname1,ISNULL(b.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(b.typeid1,'')='' THEN b.total1 ELSE ISNULL(b.total1,0) end AS total1 ,a.Leveal,b.Leveal1
		FROM c1 a 
		FULL JOIN c2 b ON a.rn=b.rn;
	END
	ELSE
	BEGIN
		INSERT INTO #Tmp2(typeid,parid,usercode , fullname , sonnum,total,  typeid1 ,  parid1 , fullname1 , Sonnum1,total1 ,leveal , leveal1)
		SELECT 
			isnull(typeid,'') as typeid,isnull(parid,'') as parid,isnull(usercode,'') as usercode,isnull(fullname,'') as fullname,isnull(sonnum,0) as sonnum,case when isnull(typeid,'')='' then total else isnull(total,0)  end as total,
			isnull(typeid1,'') as typeid1,isnull(parid1,'') as parid1,isnull(fullname1,'') as fullname1,isnull(sonnum1,0) as sonnum1,case when isnull(typeid1,'')='' then total1 else isnull(total1,0)  end as total1,Leveal,Leveal1
		FROM  #Bassert
		DROP TABLE #Bassert
	END
END
ELSE 
BEGIN
	SELECT  
			m.ATypeID ,
			a.typeid,
			SUM(ISNULL(m.total, 0)) AS Total ,
			SUM(ISNULL(m.bqtotal, 0)) AS bqTotal ,
			a.sonnum
	INTO    #monthatypehistory
	FROM    monthatypehistory m 
	INNER JOIN #Atype a ON a.nid=m.ATypeID
	WHERE   StypeId IN ( SELECT typeid
						 FROM   #Stype )
			AND M.period=@Period
			AND m.YEAR=@year
	GROUP BY m.StypeId ,
			m.ATypeID,
			a.typeid,
			a.sonnum
			
	--SELECT '历史资产负债表'
	SELECT @dTotalIncom=isnull(sum(total),0) FROM #monthatypehistory WHERE left(atypeid,5)=@ALL_INCOME_ID 
	SELECT @dTotalExpense=isnull(sum(total),0) FROM #monthatypehistory WHERE left(atypeid,5)=@ALL_EXPENSE_ID 
	
	Create TABLE #BassertHistory
	(
		[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
		usercode varchar(300),
		fullname varchar(300),
		leveal int,
		typeid varchar(50),
		sonnum int,
		parid varchar(50),
		total  NUMERIC(24, 10) ,
		fullname1 varchar(300),
		leveal1 int,
		total1  NUMERIC(24, 10) ,
		parid1 varchar(50),
		typeid1 varchar(50),
		Sonnum1 int
	)
	
	DECLARE @MaxIDHis int
	SET @MaxIDHis =0

	
    INSERT  INTO #BassertHistory
    ( 
		usercode ,
		fullname ,
		leveal ,
		typeid ,
		sonnum ,
		parid ,
		total
    )
    SELECT  a.usercode ,
            a.fullname ,
            a.leveal ,
            a.typeid ,
            a.sonnum ,
            a.parid ,
            ( SELECT    ISNULL(SUM(b.total), 0)
              FROM      #monthatypehistory b
              WHERE     b.typeid LIKE a.typeid + '%'
                        
            ) AS 'Total'
    FROM    #Atype a
    WHERE   LEFT(a.typeid, 5) = @ASSETS_ID
            AND a.typeid <> '0000200002'
            AND a.typeid <> '0000100006'
            -- 卡片管理 固定资产
			AND (@display_1=1
					AND (a.typeid NOT LIKE '0000100002%' OR a.typeid ='0000100002') 
				OR @display_1<>1)
			AND a.usercode NOT IN ('SYC-1601','SYC-1602')
    ORDER BY a.ordertypeid

	SET @MaxIDHis =@@Rowcount
	
	DECLARE @fullnameHis varchar(300)
	DECLARE @levealHis int
	DECLARE @TotalHis  NUMERIC(24, 10) 
	DECLARE @typeidHis varchar(50)
	DECLARE @paridHis varchar(50)
	DECLARE @sonnumHis int
	DECLARE @jHis int
	SET @jHis =1
	DECLARE BassCurSor CURSOR FOR	
    SELECT  a.fullname ,
            a.leveal ,
            a.typeid ,
            a.parid ,
            a.sonnum ,
            ( 
            SELECT    ISNULL(SUM(b.total), 0)
              FROM      #monthatypehistory b
			WHERE  left(b.typeid,len(a.typeid))=a.typeid
			      
		
            ) AS 'Total'
    FROM    #Atype a
    WHERE   ( LEFT(a.typeid, 5) = @DEBT_ID
              OR ( LEFT(a.typeid, 5) = '00005' ) )
            AND a.typeid <> '0000200002'
            AND a.typeid <> '0000100006'
    ORDER BY a.ordertypeid
   
	OPEN BassCurSor
	FETCH NEXT FROM BassCurSor INTO @fullnameHis,@levealHis,@typeidHis,@paridHis,@sonnumHis,@TotalHis
	WHILE @@FETCH_STATUS =0
	BEGIN
	IF @jHis<=@MaxIDHis
	BEGIN
		UPDATE #BassertHistory 
		SET fullname1=@fullnameHis,leveal1=@levealHis,total1=@TotalHis,typeid1=@typeidHis,parid1=@paridHis,sonnum1=@sonnumHis 
		WHERE [ID]=@jHis
	END	
	ELSE
	BEGIN
		INSERT INTO #BassertHistory(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) 
		VALUES( @fullnameHis,@levealHis,@TotalHis,@typeidHis,@paridHis,@sonnumHis)
	END
	SET @jHis = @jHis + 1
	FETCH NEXT FROM BassCurSor INTO @fullnameHis,@levealHis,@typeidHis,@paridHis,@sonnumHis,@TotalHis
	END
	CLOSE BassCurSor
	DEALLOCATE BassCurSor

	--应付合计
	--UPDATE #BassertHistory SET total1=(select sum(Total)  FROM #monthatypehistory where typeid='0000200001') where typeid1='0000200001' 


	-- 内部应收合计
	UPDATE #BassertHistory SET total=(
		SELECT ISNULL(SUM(total),0) FROM dbo.ListTable
		WHERE atypeid=28 AND stypeid IN (SELECT typeid FROM #stype)
		AND billdate <=@enddate
	)+(
		SELECT ISNULL(SUM(InnerARTotal00),0) FROM dbo.SType_InnerARTotal WHERE stypeid IN (SELECT typeid FROM #stype)
	)
	WHERE typeid='0000100010'
			
	-- 卡片管理 更新
	UPDATE #BassertHistory SET total=(SELECT ISNULL(SUM(NetValue),0) FROM dbo.Ac_AssetsCards_History 
										WHERE BusinessDate=@enddate and AuditType=-4 AND STypeId IN (SELECT typeid FROM #stype)) 
	WHERE typeid='0000100002' AND @display_1=1

	-- 资产合计
	UPDATE	#BassertHistory 
	SET		total=(SELECT isnull(sum(total),0) FROM #BassertHistory WHERE parid='00001' ) 
	WHERE   typeid='00001'


	-- 修改负债合计
	UPDATE	#BassertHistory 
	SET		total1=(SELECT isnull(sum(Total1),0) as total FROM #BassertHistory WHERE  typeid1 NOT in ('0000200002') AND LEFT(parid1,5)='00002' and sonnum1=0 ) 
	WHERE	typeid1='00002'

	-- 未分配利润
	UPDATE #BassertHistory SET total1=total1+(SELECT isnull(sum(m.total),0) FROM 
	( SELECT ISNULL(SUM(total),0) AS total,ATypeID from monthatypehistory WHERE Stypeid IN(SELECT typeid FROM #Stype) AND period=@Period AND YEAR=@year GROUP BY atypeid ) m,#atype a WHERE m.atypeid=a.nid AND a.typeid LIKE '00003%')
	-(SELECT isnull(sum(m.total),0)FROM 
	(SELECT ISNULL(SUM(total),0) AS total,atypeid from monthatypehistory WHERE  Stypeid IN(SELECT typeid FROM #Stype) AND period=@Period AND YEAR=@year GROUP BY atypeid ) m,#atype a WHERE m.atypeid= a.nid AND a.typeid LIKE '00004%'  ) WHERE typeid1='0000500005'


	-- 修改所有者权益 = 资产-负债
	UPDATE	#BassertHistory 
	SET		total1=(SELECT total FROM #BassertHistory WHERE typeid in ('00001'))-(SELECT total1 FROM #BassertHistory WHERE typeid1 in ('00002') ) 
	WHERE	typeid1='00005'

	--其他资本
	UPDATE #BassertHistory SET total1=(SELECT total1 FROM #BassertHistory WHERE typeid1 ='00005')-(SELECT ISNULL(SUM(total1),0) FROM #BassertHistory WHERE typeid1 LIKE '00005%' AND typeid1<>'0000500002' AND sonnum1=0) WHERE typeid1='0000500002'
	
	UPDATE  #BassertHistory SET fullname='    '+isnull(fullname,'') WHERE leveal=2 
	UPDATE  #BassertHistory SET fullname1='    '+isnull(fullname1,'') WHERE leveal1=2
	
	UPDATE  #BassertHistory SET fullname='        '+isnull(fullname,'') WHERE leveal=3
	UPDATE  #BassertHistory SET fullname1='        '+isnull(fullname1,'') WHERE leveal1=3
	
	UPDATE  #BassertHistory SET fullname='            '+isnull(fullname,'') WHERE leveal=4
	UPDATE  #BassertHistory SET fullname1='            '+isnull(fullname1,'') WHERE leveal1=4
	
	UPDATE  #BassertHistory SET fullname='                '+isnull(fullname,'') WHERE leveal=5
	UPDATE  #BassertHistory SET fullname1='                '+isnull(fullname1,'') WHERE leveal1=5

	UPDATE  #BassertHistory SET fullname='                    '+isnull(fullname,'') WHERE leveal=6
	UPDATE  #BassertHistory SET fullname1='                    '+isnull(fullname1,'') WHERE leveal1=6
	
	UPDATE  #BassertHistory SET fullname='                        '+isnull(fullname,'') WHERE leveal=7
	UPDATE  #BassertHistory SET fullname1='                        '+isnull(fullname1,'') WHERE leveal1=7
	
	UPDATE  #BassertHistory SET fullname='                            '+isnull(fullname,'') WHERE leveal=8
	UPDATE  #BassertHistory SET fullname1='                            '+isnull(fullname1,'') WHERE leveal1=8
	
	UPDATE  #BassertHistory SET fullname='                                '+isnull(fullname,'') WHERE leveal=9
	UPDATE  #BassertHistory SET fullname1='                                '+isnull(fullname1,'') WHERE leveal1=9
	
	UPDATE  #BassertHistory SET fullname='                                    '+isnull(fullname,'') WHERE leveal=10
	UPDATE  #BassertHistory SET fullname1='                                    '+isnull(fullname1,'') WHERE leveal1=10
	

	IF @hidezero=1
	BEGIN
		;WITH c1 AS (
			SELECT rn=ROW_NUMBER() OVER(ORDER BY a.id),ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname,ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE ISNULL(a.total,0) END AS total ,a.leveal
			FROM #BassertHistory a WHERE ISNULL(a.total,0)<>0
			AND NOT EXISTS(SELECT 1 FROM #BassertHistory b WHERE a.typeid like b.typeid+'%' AND b.total=0 AND b.sonnum<>0 )
		),c2 AS (
			SELECT rn=ROW_NUMBER() OVER(ORDER BY id), ISNULL(a.typeid1,'') AS typeid1,ISNULL(a.parid1,'') AS parid1,ISNULL(a.fullname1,'') AS fullname1,ISNULL(a.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(typeid1,'')='' THEN total1 ELSE  ISNULL(total1,0) END AS total1, a.leveal1
			FROM #BassertHistory a WHERE ISNULL(total1,0)<>0
			AND NOT EXISTS(SELECT 1 FROM #BassertHistory b WHERE a.typeid1 LIKE b.typeid1+'%' AND b.total1=0 AND b.sonnum<>0 )
		)
		INSERT INTO #Tmp2( typeid,parid,usercode , fullname , sonnum,total,  typeid1 ,  parid1 , fullname1 , Sonnum1,total1 , leveal , leveal1)
		SELECT ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname, ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE  ISNULL(a.total,0) END  AS total
			,ISNULL(b.typeid1,'') AS typeid1,ISNULL(b.parid1,'') AS parid1,ISNULL(b.fullname1,'') AS fullname1,ISNULL(b.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(b.typeid1,'')='' THEN b.total1 ELSE ISNULL(b.total1,0) end AS total1 ,a.leveal, b.leveal1
		FROM c1 a FULL JOIN c2 b ON a.rn=b.rn;
	END
	ELSE
	BEGIN
		INSERT INTO #Tmp2(typeid,parid,usercode , fullname , sonnum,total,  typeid1 ,  parid1 , fullname1 , Sonnum1,total1 , leveal , leveal1)
		SELECT 
			isnull(typeid,'') as typeid,isnull(parid,'') as parid,isnull(usercode,'') as usercode,isnull(fullname,'') as fullname,isnull(sonnum,0) as sonnum,case when isnull(typeid,'')='' then total else isnull(total,0)  end as total,
			isnull(typeid1,'') as typeid1,isnull(parid1,'') as parid1,isnull(fullname1,'') as fullname1,isnull(sonnum1,0) as sonnum1,case when isnull(typeid1,'')='' then total1 else isnull(total1,0)  end as total1,leveal,leveal1
		FROM  #BassertHistory
	END
	
	DROP TABLE #BassertHistory,#monthatypehistory
END


INSERT INTO #Tmp
		(  usercode , fullname ,  leveal , typeid ,  sonnum , parid ,  total)
		SELECT usercode , fullname ,  leveal , typeid ,  sonnum , parid ,  total 
		FROM #Tmp2 WHERE leveal  <= @itemleveal

INSERT INTO #Tmp1
		(  fullname1 , leveal1 , total1 , parid1 ,typeid1 ,Sonnum1 )
		 SELECT fullname1 , leveal1 , total1 , parid1 ,typeid1 ,Sonnum1 
		 FROM #Tmp2 where leveal1 <= @itemleveal

TRUNCATE TABLE #Tmp2


declare @RowCount int,@ii int,@TmpCount int, @TmpCount1 INT

select @TmpCount=COUNT(1) from #Tmp
select @TmpCount1=COUNT(1)  from #Tmp1

if(@TmpCount <= @TmpCount1)
	set @RowCount = @TmpCount1
else
	set @RowCount = @TmpCount


set @RowCount = @RowCount + 1
set @ii = 1

--资产负债

DECLARE 	
	@usercodea varchar(300),
	@fullnamea varchar(300),
	@leveala int,
	@typeida varchar(50),
	@sonnuma int,
	@parida varchar(50),
	@totala  NUMERIC(24, 10) ,
	@fullname1a varchar(300),
	@leveal1a int,
	@total1a  NUMERIC(24, 10) ,
	@parid1a varchar(50),
	@typeid1a varchar(50),
	@Sonnum1a int 

while @ii < @RowCount
begin
	if(@ii < = @TmpCount)
	BEGIN
		select @usercodea = usercode ,@fullnamea = fullname , @leveala = leveal,@typeida =typeid, @sonnuma = sonnum ,@parida = parid ,@totala = total 
		from #Tmp where id = @ii
	end
	else
	begin
		set @usercodea = null 
		set @fullnamea = null 
		set @leveala = null 
		set @typeida = null 
		set @sonnuma = null 
		set @parida = null 
		set @totala = null 
	end
	if(@ii < = @TmpCount1)
	BEGIN
		select @fullname1a = fullname1 ,@leveal1a = leveal1 , @total1a = total1 ,@parid1a = parid1, @typeid1a = typeid1, @Sonnum1a = Sonnum1
		from #Tmp1 where id = @ii
	end
	else
	begin
		set @fullname1a = null 
		set @leveal1a = null 
		set @total1a = null  
		set @parid1a = null  
		set @typeid1a = null  
		set @Sonnum1a = null  
	end
	insert into #Tmp2 values (@usercodea,@fullnamea,@leveala,@typeida,@sonnuma,@parida,@totala
							,@fullname1a,@leveal1a,@total1a,@parid1a,@typeid1a,@Sonnum1a)
	Set @ii = @ii + 1
END

--特殊处理所有者权益
IF NOT EXISTS(SELECT TOP 1 1 FROM #Tmp2 WHERE typeid1 LIKE '00005%' AND SonNum1 = 0)
BEGIN
	UPDATE #Tmp2 SET Total1 = 0 WHERE typeid1 = '00005'
END
ELSE
BEGIN
	UPDATE	#Tmp2
	SET		Total1 = (SELECT SUM(ISNULL(Total1,0)) FROM #Tmp2 WHERE parid1 = '00005' )
	WHERE	TypeId1 = '00005'
END

SELECT * FROM #Tmp2

DROP TABLE #Tmp2
DROP TABLE #Tmp1
DROP TABLE #Tmp


DROP TABLE #Atype,#MonthProc
DROP TABLE #t1;

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BankStatementDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BankStatementDetailQuery]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
    作者：李灏龙
	日期：2014年5月4日 15:43:21
	描述：银行对账
-------------------------------------------*/
CREATE PROCEDURE Web_BankStatementDetailQuery 
(
       @STypeId 		VARCHAR(100),	---分支机构ID
       @AccountId 		INT,	---银行账户ID
	   @businessdateStart    DATE,			---起始业务日期
	   @businessdateEnd      DATE,			---结束业务日期
	   @banktellername		VARCHAR(500),	--柜员名称
	   @FSettleid		INT,
	   @FSettleNo		VARCHAR(500),
	   @businessid	VARCHAR(500),
	   @cid				INT,			--币种
	   @isCheckRelevance	INT,
	   @DebitOrCredit	INT,			--借贷方向
	   @chvOperatorID	VARCHAR(50)		---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON


CREATE TABLE #temp
(
	id		INT,
	businessdate	DATE,
	businesscode	VARCHAR(500),
	summary		VARCHAR(1000),
	fdebit	 NUMERIC(24, 10) ,
	fcredit	 NUMERIC(24, 10) ,
	fendbalance	 NUMERIC(24, 10) ,
	tellerid	VARCHAR(50),
	tellername	VARCHAR(66),
	cid			INT,
	FSettleNo	VARCHAR(66),
	FSettlename	VARCHAR(66),
	isCheckRelevance	INT,
	isdaysum		INT,	--是否是本日合计  0：不是  1：是
	issum		INT,   --是否是合计	0：不是   1：是   ps：主要用于排序  合计行isdaysum和issum都为1  本日合计行isdaysum为1，issum为0  其他行两者均为0
	banktellername	VARCHAR(66),   --柜员
	businessid	VARCHAR(500),
	sourceid	INT,
	sourcename	VARCHAR(66),
	cidfullname	VARCHAR(50)
)

DECLARE 
	@SQL		NVARCHAR(MAX),	
	@SFyear		INT,	--出纳当前启用年度
	@SFPeriod	INT,	--出纳当前启用期间
	@StartDate	DATETIME=@businessdateStart,	--出纳当前期间启用时间
	@LASTENDBALANCE	 NUMERIC(24, 10),--余额
	@IsInitial	INT=0			--是否期初值

IF EXISTS(SELECT TOP 1 1 FROM Te_StartPeriod T INNER JOIN Ac_Period P ON T.SFYear=P.FYear AND T.SFPeriod=P.FPeriod AND T.STypeId=@STypeId AND P.FBegin>@businessdateStart)
	BEGIN
		SELECT @SFyear=T.SFYear,@SFPeriod=T.SFPeriod,@StartDate=P.FBegin,@IsInitial=1,@businessdateStart=P.FBegin FROM Te_StartPeriod T INNER JOIN Ac_Period P ON T.SFYear=P.FYear AND T.SFPeriod=P.FPeriod AND T.STypeId=@STypeId
	END	
ELSE 
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Te_Period T INNER JOIN Ac_Period P ON T.FYear=P.FYear AND T.FPeriod=P.FPeriod AND T.STypeId=@STypeId AND P.FEnd<@businessdateStart)
			BEGIN
				SELECT @SFyear=T.FYear,@SFPeriod=T.FPeriod,@StartDate=P.FBegin FROM Te_Period T INNER JOIN Ac_Period P ON T.FYear=P.FYear AND T.FPeriod=P.FPeriod AND T.STypeId=@STypeId
			END	
		ELSE 
			BEGIN
				SELECT @SFyear=FYear,@SFPeriod=FPeriod,@StartDate=FBegin FROM Ac_Period WHERE @businessdateStart BETWEEN FBegin AND FEnd
			END
	END			


SELECT @LASTENDBALANCE=ISNULL(InitBalanceFor,0) FROM Te_Balance WHERE AccountId=@AccountId AND STypeid=@STypeId AND Cid = @cid AND FYear=@SFyear AND FPeriod=@SFPeriod AND BUId = 3

-----以上期余额为基础，计算查询日期上日余额
SELECT	 
	@LASTENDBALANCE+=dbo.f_roundtotal(CASE WHEN @cid=0 AND ac.BasisType = 0 THEN (tjd.FCredit-tjd.FDebit)*tjd.Rate
											WHEN @cid=0 AND ac.BasisType = 1 THEN (tjd.FCredit-tjd.FDebit)/tjd.Rate
											ELSE tjd.FCredit-tjd.FDebit
										END) 		
FROM Te_BankStatementDetail tjd
LEFT JOIN Ac_Currency ac ON ac.CId = tjd.cid
WHERE
	tjd.BusinessDate >= @StartDate
	AND tjd.BusinessDate < @businessdateStart 
	AND tjd.AccountId = @AccountId
	AND (tjd.cid = @cid OR @cid = 0)

------插入上日余额（或是期初）数据
INSERT INTO #temp(id,businessdate,summary,fendbalance,cid,cidfullname) 
VALUES(0,DATEADD(DAY,-1,@businessdateStart),CASE WHEN @businessdateStart=@StartDate AND @IsInitial=1 THEN '期初数据' ELSE '上日余额' END,@LASTENDBALANCE,@cid,CASE WHEN @cid= 0 THEN '综合本位币' ELSE (SELECT TOP 1 FullName FROM Ac_Currency WHERE CId= @cid) END)
--------上日余额部分结束------------------


CREATE TABLE #ETYPEID
(
	etypeid	VARCHAR(500),
	efullname	VARCHAR(500)
)
INSERT INTO #ETYPEID(etypeid,efullname)
SELECT	 typeId
		,FullName
FROM	F_AllTreeE(@chvOperatorID)
WHERE	sonnum = 0
	AND	FullName LIKE '%'+@banktellername+'%'


SET @SQL = '
INSERT INTO #temp(id,businessdate,businesscode,summary,fdebit,fcredit,tellerid,tellername,cid,FSettleNo,FSettlename,isCheckRelevance,isdaysum,issum,banktellername,businessid,sourceid,sourcename,cidfullname)
SELECT	 tbsd.Id
		,tbsd.BusinessDate
		,tbsd.BusinessId
		,tbsd.Summary
		,dbo.f_roundtotal(CASE WHEN @cid=0 AND ac.BasisType = 0 THEN tbsd.FDebit*tbsd.Rate
			  WHEN @cid=0 AND ac.BasisType = 1 THEN tbsd.FDebit/tbsd.Rate
		 ELSE tbsd.FDebit
		 END)
		,dbo.f_roundtotal(CASE WHEN @cid=0 AND ac.BasisType = 0 THEN tbsd.FCredit*tbsd.Rate
			  WHEN @cid=0 AND ac.BasisType = 1 THEN tbsd.FCredit/tbsd.Rate
		 ELSE tbsd.FCredit
		 END)
		,tbsd.ETypeId as tellerid
		,e.fullname as tellername
		,tbsd.cid
		,tbsd.FSettleNo
		,abt.FullName
		,CASE WHEN EXISTS(SELECT TOP 1 StatementId FROM Te_CheckRelevance WHERE StatementId = tbsd.Id) THEN 1
		 ELSE 0
		 END 
		,0
		,0
		,tbsd.tellername
		,tbsd.businessid
		,tbsd.sourceid
		,tjs.FullName AS sourcename
		,CASE WHEN @cid=0 THEN ''综合本位币''
		 ELSE ac.fullname
		 END
FROM	Te_BankStatementDetail tbsd
INNER JOIN	employee e ON e.typeid = tbsd.ETypeId
LEFT JOIN	Ac_Currency ac ON ac.CId = tbsd.cid
LEFT JOIN	Ac_BalanceType abt ON abt.BtId = tbsd.FSettleId
LEFT JOIN	Te_Journal_SourceType tjs ON tjs.Id = tbsd.SourceId
WHERE	tbsd.BusinessDate >= @businessdateStart 
	AND	tbsd.BusinessDate <= @businessdateEnd
	AND	tbsd.AccountId = @AccountId
	AND (tbsd.cid = @cid OR @cid = 0)
	AND tbsd.TellerName LIKE ''%''+@banktellername+''%''
'+
CASE WHEN @DebitOrCredit = 0 THEN ' AND	tbsd.FDebit != 0 '
WHEN @DebitOrCredit = 1 THEN ' AND	tbsd.FCredit ! = 0 '
ELSE '' END

IF ISNULL(@FSettleid,0) <>0
	SET @SQL += ' AND tbsd.FSettleid = @FSettleid '
IF ISNULL(@FSettleNo,'') <>''
	SET @SQL += ' AND tbsd.FSettleNo LIKE ''%''+@FSettleNo+''%'''
IF ISNULL(@businessid,'') <>''
	SET @SQL += ' AND tbsd.businessid LIKE ''%''+@businessid+''%'''

SET @SQL +='
ORDER BY	BusinessDate,id
'
print @sql
EXEC sp_executesql @SQL,N'@businessdateStart    DATE,			
	   @businessdateEnd      DATE,	
	   @cid				INT,			--币种
       @AccountId 		INT,		
	   @FSettleid		INT,
	   @FSettleNo		VARCHAR(500),
	   @businessid		VARCHAR(500),
	   @banktellername		VARCHAR(500)',@businessdateStart, @businessdateEnd,@cid,@AccountId,@FSettleid,@FSettleNo,@businessid,@banktellername

IF @isCheckRelevance != 2
	DELETE FROM #temp WHERE isCheckRelevance != @isCheckRelevance


UPDATE #temp  SET	@LASTENDBALANCE = @LASTENDBALANCE + fcredit - fdebit
					,fendbalance = @LASTENDBALANCE
WHERE businessdate >= @businessdateStart				


DECLARE	@MAXID	INT
SELECT TOP 1 @MAXID = id+1 FROM #temp ORDER BY id DESC


INSERT INTO #temp(id,fdebit,fcredit,fendbalance,isCheckRelevance,isdaysum,issum)
SELECT	 @MAXID+1
		,SUM(fdebit)
		,SUM(fcredit)
		,@LASTENDBALANCE
		,0
		,1
		,1
FROM	#temp T1

INSERT INTO #temp(id,businessdate,fdebit,fcredit,fendbalance,isCheckRelevance,isdaysum,issum)
SELECT	 @MAXID
		,businessdate
		,SUM(fdebit)
		,SUM(fcredit)
		,(SELECT TOP 1 fendbalance  FROM #temp T2 WHERE T2.businessdate = T1.businessdate ORDER BY T2.id DESC)
		,0
		,1
		,0
FROM	#temp T1
WHERE	id < @MAXID
	AND id > 0
GROUP BY T1.businessdate

--select * from #temp
SELECT	 id
		,CASE WHEN isdaysum=1 AND issum = 1 THEN '合计'
		 WHEN isdaysum = 1 AND issum = 0 THEN '本日合计'
		 ELSE CAST(businessdate AS VARCHAR) END AS businessdate
		,businesscode
		,summary
		,fdebit
		,fcredit
		,fendbalance
		,tellerid
		,tellername
		,cid
		,FSettleNo
		,FSettlename
		,CASE WHEN isCheckRelevance = 1 THEN '√'
		 ELSE ''
		 END AS isCheckRelevance
		,issum
		,banktellername
		,sourceid
		,sourcename
		,cidfullname
		,isdaysum
FROM	#temp t
--WHERE	isCheckRelevance = @isCheckRelevance OR @isCheckRelevance = 2
ORDER BY	issum,t.businessdate,isdaysum,id	


DROP TABLE #ETYPEID,#temp
			 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_Base_FixedReasonForChange]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_Base_FixedReasonForChange
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回变更原因列表、明细列表
-- 时间：	2016-05-12
-- 作者：	lxl
-- ========================================================================
CREATE PROC Web_Base_FixedReasonForChange
(
	@TId			INT,			--存货类型ID
	@STypeID		VARCHAR(MAX),	--分支机构
	@OperatorID		VARCHAR(50),	--当前操作员
	@Type			INT				--查询界面 1：列表 2：明细
	
)
--@encode$--
AS
SET NOCOUNT ON 
IF(@Type=1)
	BEGIN
		SELECT
			NID,
			NID TID,
			UserCode,
			FullName,
			Comment,
			dbo.Fn_GetIsUse_Items(NID,100) IsUsed
		FROM Base_FixedReasonForChange
	END 
ELSE 
	BEGIN
		--处理会计科目多级权限
		CREATE TABLE #Ac_Account_L (StypeId VARCHAR(50),TypeId VARCHAR(50),FullName VARCHAR(200))
		INSERT INTO #Ac_Account_L (StypeId,Typeid,FullName) 
		SELECT L.Stypeid,L.Typeid,A.FullName FROM F_LineAccount(@OperatorID,'') L
		INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
		
		SELECT
			D.NID,
			D.TID,
			S.VerifyID,
			D.STypeID,
			S.FullName SFullName,
			D.EnterATypeID,
			CASE WHEN ISNULl(D.EnterATypeID,'')='' THEN '' ELSE  ISNULL(A1.FullName,'****') END EnterFullName,
			D.ForeignATypeID,
			CASE WHEN ISNULl(D.ForeignATypeID,'')='' THEN '' ELSE  ISNULL(A2.FullName,'****') END ForeignFullName,
			D.RateATypeID,
			CASE WHEN ISNULl(D.RateATypeID,'')='' THEN '' ELSE  ISNULL(A3.FullName,'****') END RateFullName,
			dbo.Fn_GetIsUse_Items(D.TID,100) IsUsed
		FROM Base_FixedReasonForChangeDetails D
		INNER JOIN dbo.F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID) F ON F.TypeId=D.STypeId
		INNER JOIN SType S ON S.TypeId=F.TypeId
		LEFT JOIN #Ac_Account_L A1 ON A1.typeId=D.EnterATypeID AND ((A1.stypeid=S.TypeId AND S.IsSelfVerify=1) OR (A1.StypeId=S.VerifyID AND S.IsSelfVerify=0))
		LEFT JOIN #Ac_Account_L A2 ON A2.TypeId=D.ForeignATypeID AND ((A2.stypeid=S.TypeId AND S.IsSelfVerify=1) OR (A2.StypeId=S.VerifyID AND S.IsSelfVerify=0))
		LEFT JOIN #Ac_Account_L A3 ON A3.TypeId=D.RateATypeID AND ((A3.stypeid=S.TypeId AND S.IsSelfVerify=1)OR (A3.StypeId=S.VerifyID AND S.IsSelfVerify=0))	
		WHERE 
			D.TID=@TId
		DROP TABLE #Ac_Account_L
	END
	
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_Base_QueryBase_FixedReasonForChangeList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_Base_QueryBase_FixedReasonForChangeList
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回变更原因列表、明细列表
-- 时间：	2016-05-12
-- 作者：	lxl
-- ========================================================================
CREATE PROC Web_Base_QueryBase_FixedReasonForChangeList
(
	@TId			INT,			--变更原因ID
	@STypeID		VARCHAR(MAX),	--分支机构
	@OperatorID		VARCHAR(50),	--当前操作员
	@Type			INT				--查询界面 1：列表 2：明细
	
)
--@encode$--
AS
SET NOCOUNT ON 
IF(@Type=1)
	BEGIN
		SELECT
			NID,
			NID TID,
			UserCode,
			FullName,
			Comment,
			dbo.Fn_GetIsUse_Items(NID,100) IsUsed
		FROM Base_FixedReasonForChange
	END 
ELSE 
	BEGIN
		--处理会计科目多级权限
		CREATE TABLE #Ac_Account_L (StypeId VARCHAR(50),TypeId VARCHAR(50),FullName VARCHAR(200))
		INSERT INTO #Ac_Account_L (StypeId,Typeid,FullName) 
		SELECT L.Stypeid,L.Typeid,A.FullName FROM F_LineAccount(@OperatorID,'') L
		INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
		
		SELECT
			D.NID,
			D.TID,
			S.VerifyID,
			D.STypeID,
			S.FullName SFullName,
			D.EnterATypeID,
			CASE WHEN ISNULl(D.EnterATypeID,'')='' THEN '' ELSE  ISNULL(A1.FullName,'****') END EnterFullName,
			D.ForeignATypeID,
			CASE WHEN ISNULl(D.ForeignATypeID,'')='' THEN '' ELSE  ISNULL(A2.FullName,'****') END ForeignFullName,
			D.RateATypeID,
			CASE WHEN ISNULl(D.RateATypeID,'')='' THEN '' ELSE  ISNULL(A3.FullName,'****') END RateFullName,
			dbo.Fn_GetIsUse_Items(D.TID,100) IsUsed
		FROM Base_FixedReasonForChangeDetails D
		INNER JOIN dbo.F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID) F ON F.TypeId=D.STypeId
		INNER JOIN SType S ON S.TypeId=F.TypeId
		LEFT JOIN #Ac_Account_L A1 ON A1.typeId=D.EnterATypeID AND ((A1.stypeid=S.TypeId AND S.IsSelfVerify=1) OR (A1.StypeId=S.VerifyID AND S.IsSelfVerify=0))
		LEFT JOIN #Ac_Account_L A2 ON A2.TypeId=D.ForeignATypeID AND ((A2.stypeid=S.TypeId AND S.IsSelfVerify=1) OR (A2.StypeId=S.VerifyID AND S.IsSelfVerify=0))
		LEFT JOIN #Ac_Account_L A3 ON A3.TypeId=D.RateATypeID AND ((A3.stypeid=S.TypeId AND S.IsSelfVerify=1)OR (A3.StypeId=S.VerifyID AND S.IsSelfVerify=0))	
		WHERE 
			D.TID=@TId
		DROP TABLE #Ac_Account_L
	END
	
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_Base_QueryFixedReasonForChangeList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_Base_QueryFixedReasonForChangeList
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回变更原因列表、明细列表
-- 时间：	2016-05-12
-- 作者：	lxl
-- ========================================================================
CREATE PROC Web_Base_QueryFixedReasonForChangeList
(
	@TId			INT,			--变更原因ID
	@STypeID		VARCHAR(MAX),	--分支机构
	@OperatorID		VARCHAR(50),	--当前操作员
	@Type			INT				--查询界面 1：列表 2：明细
	
)
--@encode$--
AS
SET NOCOUNT ON 
IF(@Type=1)
	BEGIN
		SELECT
			NID,
			NID TID,
			UserCode,
			FullName,
			Comment,
			dbo.Fn_GetIsUse_Items(NID,100) IsUsed
		FROM Base_FixedReasonForChange
	END 
ELSE 
	BEGIN
		--处理会计科目多级权限
		CREATE TABLE #Ac_Account_L (StypeId VARCHAR(50),TypeId VARCHAR(50),FullName VARCHAR(200))
		INSERT INTO #Ac_Account_L (StypeId,Typeid,FullName) 
		SELECT L.Stypeid,L.Typeid,A.FullName FROM F_LineAccount(@OperatorID,'') L
		INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
		
		SELECT
			D.NID,
			D.TID,
			S.VerifyID,
			D.STypeID,
			S.FullName SFullName,
			D.EnterATypeID,
			CASE WHEN ISNULl(D.EnterATypeID,'')='' THEN '' ELSE  ISNULL(A1.FullName,'****') END EnterFullName,
			D.ForeignATypeID,
			CASE WHEN ISNULl(D.ForeignATypeID,'')='' THEN '' ELSE  ISNULL(A2.FullName,'****') END ForeignFullName,
			D.RateATypeID,
			CASE WHEN ISNULl(D.RateATypeID,'')='' THEN '' ELSE  ISNULL(A3.FullName,'****') END RateFullName,
			dbo.Fn_GetIsUse_Items(D.TID,110) IsUsed
		FROM Base_FixedReasonForChangeDetails D
		INNER JOIN dbo.F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID) F ON F.TypeId=D.STypeId
		INNER JOIN SType S ON S.TypeId=F.TypeId
		LEFT JOIN #Ac_Account_L A1 ON A1.typeId=D.EnterATypeID AND ((A1.stypeid=S.TypeId AND S.IsSelfVerify=1) OR (A1.StypeId=S.VerifyID AND S.IsSelfVerify=0))
		LEFT JOIN #Ac_Account_L A2 ON A2.TypeId=D.ForeignATypeID AND ((A2.stypeid=S.TypeId AND S.IsSelfVerify=1) OR (A2.StypeId=S.VerifyID AND S.IsSelfVerify=0))
		LEFT JOIN #Ac_Account_L A3 ON A3.TypeId=D.RateATypeID AND ((A3.stypeid=S.TypeId AND S.IsSelfVerify=1)OR (A3.StypeId=S.VerifyID AND S.IsSelfVerify=0))	
		WHERE 
			D.TID=@TId
		DROP TABLE #Ac_Account_L
	END
	
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_Base_QueryInventoryTypeList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_Base_QueryInventoryTypeList
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回存货类型列表、明细列表
-- 时间：	2016-04-27
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_Base_QueryInventoryTypeList
(
	@TId			INT,			--存货类型ID
	@STypeID		VARCHAR(MAX),	--分支机构
	@OperatorID		VARCHAR(50),	--当前操作员
	@Type			INT				--查询界面 1：列表 2：明细
	
)
--@encode$--
AS
SET NOCOUNT ON 
IF(@Type=1)
	BEGIN
		SELECT
			NID,
			NID TID,
			UserCode,
			FullName,
			Comment,
			Sysrow
		FROM Base_InventoryType
	END 
ELSE 
	BEGIN
		--处理会计科目多级权限
		CREATE TABLE #Ac_Account_L (StypeId VARCHAR(50),TypeId VARCHAR(50),FullName VARCHAR(200))
		INSERT INTO #Ac_Account_L (StypeId,Typeid,FullName) 
		SELECT L.Stypeid,L.Typeid,A.FullName FROM F_LineAccount(@OperatorID,'') L
		INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
		
		SELECT
			DISTINCT
			D.NID,
			D.TID,
			S.VerifyID,
			D.STypeID,
			S.FullName SFullName,
			D.StockATypeID,
			CASE WHEN ISNULl(D.StockATypeID,'')='' THEN '' ELSE  ISNULL(A1.FullName,'****') END StockFullName,
			D.IncomeATypeID,
			CASE WHEN ISNULl(D.IncomeATypeID,'')='' THEN '' ELSE  ISNULL(A2.FullName,'****') END IncomeFullName,
			D.CostATypeID,
			CASE WHEN ISNULl(D.CostATypeID,'')='' THEN '' ELSE  ISNULL(A3.FullName,'****') END CostFullName
		FROM Base_InventoryTypeDetails D
		INNER JOIN dbo.F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID) F ON F.TypeId=D.STypeId
		INNER JOIN SType S ON S.TypeId=F.TypeId AND S.sonnum=0
		LEFT JOIN #Ac_Account_L A1 ON A1.typeId=D.StockATypeID AND A1.stypeid=S.VerifyID
		LEFT JOIN #Ac_Account_L A2 ON A2.TypeId=D.IncomeATypeID AND A1.stypeid=S.VerifyID
		LEFT JOIN #Ac_Account_L A3 ON A3.TypeId=D.CostATypeID AND A1.stypeid=S.VerifyID
		WHERE 
			D.TID=@TId
		DROP TABLE #Ac_Account_L
	END
	
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_BaseInfo_QueryBtype]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_BaseInfo_QueryBtype]
GO



/*
	By ：Haiyang, Li
	Date：2012-12-03
	Description：优化并重写基本信息查询, 供应商, 去掉公用权限函数调用
*/


CREATE PROCEDURE [dbo].[Web_BaseInfo_QueryBtype]
    (
      @Parid VARCHAR(50) ,					--fu'jie
      @showDisable INT = 0 ,   --显示停用信息
      @StartOfCreateDate VARCHAR(50) = '' ,
      @EndOfCreateDate VARCHAR(50) = '' ,
      @UserID VARCHAR(50) = '00001'
    )
--@encode$--
AS 
    SET NOCOUNT ON 


		--DECLARE @dt DATETIME
		--set @dt = GETDATE();
    
		
		DECLARE @hasAllPermission BIT, @RootType VARCHAR(5)
		SET @hasAllPermission = 0
		SET @RootType = LEFT(@Parid, 5)
		IF @RootType = '00001'
		BEGIN
			SELECT @hasAllPermission = 1 FROM loginuser WHERE ETypeId = @UserID AND MangerBTypeID = '00001'
		END
		ELSE
		BEGIN
			SELECT @hasAllPermission = 1 FROM loginuser WHERE ETypeId = @UserID AND MangerBTypeID2 = '00002'
		END
		CREATE TABLE #BType ( TypeID VARCHAR(50) )
		
		

--供货商
--SELECT @hasAllPermission
IF @hasAllPermission = 1 
		INSERT INTO #BType(TypeId) SELECT TypeID FROM BType WHERE parid = @Parid
ELSE --有输入参数
		INSERT INTO #BType(TypeId)
		SELECT	DISTINCT B.TypeId 
		FROM	BType_L L
		INNER JOIN BType B ON B.TypeId LIKE L.TypeId + '%'
		WHERE	L.etypeid = @UserID
				AND L.Flag = 1
				AND B.parid = @Parid
		UNION ALL
		SELECT L.TypeID
		FROM	btype_l L
		WHERE	L.etypeid = @UserID
				AND L.flag = 0
				AND L.typeid LIKE @Parid + '%'
				AND L.typeid <> @Parid
				AND L.typeid <> @RootType

				

---- '#BType', DATEDIFF(ms,@dt,GETDATE())

--set @dt = GETDATE();

			 SELECT  b.* ,
								c.typeId AS denominatedid ,
								c.FullName AS denname ,
								A.FullName AS areaName ,
								A.UserCode As ausercode,
								E.FullName AS efullname,
								E.usercode as eusercode,
								c.usercode as  busercode,
					CASE WHEN ((SELECT COUNT(ImgURL)from dbo.BType_Picture BP where b.typeid=BP.BTypeID)>0) THEN '有' ELSE '无'  END  ImgURL,
					CASE b.iscarrier WHEN 1 THEN '是' ELSE '否'  END iscarrierText,
					CASE b.PriceTrackEnable WHEN 1 THEN '是' ELSE '否' END pricetrackenable1 
			 FROM    btype B
			   INNER JOIN #BType BR ON BR.typeid = B.typeId
			   LEFT JOIN AreaType A ON A.typeId = B.AreaTypeID
			   LEFT JOIN employee E ON E.typeId = B.etypeid
			   LEFT JOIN btype c ON b.denominatedid = c.typeId
			 WHERE   ( @showDisable <> 0 OR b.deleted = 0)
			   AND ( @StartOfCreateDate = '' OR b.CreateDate > @StartOfCreateDate)
			   AND ( @EndOfCreateDate = '' OR b.CreateDate < @EndOfCreateDate)
			   and b.parid=@Parid
			   ORDER BY b.UserCode

DROP TABLE #BType

--SELECT '出结果集', DATEDIFF(ms,@dt,GETDATE())


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BassetReportMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BassetReportMonth]
GO

/*
	作者:武智均
	日期:2019-09-12
	描述:资产负债表按月比较
	
	SQL说明: 0.查出所有的结果集放到 #Total（构造多列）
			 1.update 累加 #Total 中的Total
			 2.子集 Total 合集放到#Temp
			 3.update 单独处理所有者权益 
			 4.显示结果集
*/

CREATE   PROCEDURE Web_BassetReportMonth
(
	@OperatorID	VARCHAR(50),		--操作员ID
	@StypeId	VARCHAR(max),		--分支机构id
	@HideZero	INT = 0,			-- 0显示，1隐藏
	@Leveal 	INT = 10			--项目级次
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(MAX)
SET @Leveal = @Leveal + 1

-- 分支机构 - 月结开始时间和结束时间
CREATE TABLE #Stype (TypeID varchar(50))

-- 月结
CREATE TABLE #Months
(	
	StartDate	DATETIME,
	EndDate		DATETIME,
	stypeid		VARCHAR(500),
	MonthNo		VARCHAR(200),
	Period		VARCHAR(200),
	YEAR		INT
)

--处理期初数据
CREATE TABLE #Total 
(
	nTypeId		VARCHAR(200), 
	MonthNo		VARCHAR(200), 
	FullName	VARCHAR(200), 
	TOTAL		NUMERIC(24, 10), 
	Total00		NUMERIC(24, 10),
	StartDate	DATETIME,
	EndDate		DATETIME 
)
-- 临时存放结果集
CREATE TABLE #TEMP 
(
	USERCODE	VARCHAR(200),
	FULLNAME	VARCHAR(200),
	LEVEAL		INT,
	NTYPEID		VARCHAR(200),
	NPARID		VARCHAR(200),
	SONNUM		VARCHAR(200),
	MONTHNO		VARCHAR(200),
	TOTAL		NUMERIC(24, 10),
	CURRENTTOTAL NUMERIC(24, 10)
)

INSERT INTO #Stype(TypeID)
SELECT TypeId FROM dbo.F_BaseGetAllManagerBaseTypeId(@StypeId,11,@OperatorID)

IF NOT EXISTS (SELECT TOP 1 1 fROM #Stype)
BEGIN
	RETURN -1
END

--INSERT INTO 	#Months
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'stypeindependentopen' AND SubValue = 1)  -- 启用分支机构独立
	 INSERT INTO #Months
	 SELECT StartDate,EndDate,STypeID,MonthNo,Period,YEAR 
	 FROM 
		(SELECT	MonthNo,
				StartDate, 
				EndDate,
				Period,
				STypeID,
				Year 
		FROM  monthproc
		INNER JOIN #Stype S on STypeID=S.TypeID )M 
	 GROUP BY StartDate,EndDate,MonthNo,year,Period,M.STypeID
	 ORDER BY STypeID,year,Period
ELSE
	 INSERT INTO #Months
	 SELECT StartDate,EndDate,STypeID,MonthNo,Period,Year
	 FROM MonthProc
	 WHERE STypeID IN 
		 (SELECT TOP 1 s1.typeid FROM #Stype s1 
		 INNER JOIN stype s ON s1.TypeID=s.TypeID WHERE s.sonnum=0 )
	 ORDER BY Year,period
	 
UPDATE #Months SET EndDate = '2099-01-01'  WHERE EndDate IS NULL

DELETE #Months WHERE monthno='本期' AND StartDate<(SELECT MAX(StartDate) FROM #Months WHERE monthno='本期' )


DECLARE @FirstMonthNo VARCHAR(100) --第一个月结存月份
SET @FirstMonthNo = (SELECT TOP 1 MonthNo FROM dbo.MonthProc M LEFT JOIN dbo.ListTable L ON L.BillDate BETWEEN M.StartDate AND M.EndDate ORDER BY M.StartDate )


-- 控制显示 
-- 资产负债表调整成分支机构合计的方式 --
DECLARE @display_1 INT=0;

CREATE TABLE #stypeinfo 
(
	stypeid		VARCHAR(100),
	iniDate		DATETIME,
	iscard		INT,
	val			NUMERIC(24, 10),
	StartDate	DATETIME,
	EndDate		DATETIME,
	MonthNo		VARCHAR(200)
)

INSERT INTO #stypeinfo 
SELECT  a.typeid,
		b.InitDate,
		CASE WHEN EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'assets' AND SubValue = '1') THEN 1 ELSE 0 END,
		0.0 ,
		m.StartDate,
		m.EndDate,
		m.MonthNo
FROM	#stype a
LEFT JOIN #Months m ON a.typeid=m.stypeid
LEFT JOIN (SELECT u.*,v.typeid FROM Ac_FixedAssetsInit_Stype u JOIN stype v ON u.stypeid=v.VerifyID) b ON a.typeid=b.typeid;

  
--卡片模式才统计卡片的数据
IF  EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')
BEGIN
	-- 取卡片的
	UPDATE #stypeinfo SET iscard=1 
	FROM #Months m 
	WHERE #stypeinfo.stypeid=m.stypeid 
	and iniDate<=ISNULL(m.enddate,m.EndDate)

	SELECT @display_1=1 WHERE EXISTS(SELECT 1 FROM #stypeinfo WHERE iscard=1) --显示为卡片
	
	DECLARE Cousor_MonthPro CURSOR FOR 
	SELECT startdate,enddate,stypeid,MonthNo FROM #Months GROUP BY stypeid,startdate,enddate,MonthNo,YEAR,Period
	
	OPEN Cousor_MonthPro
	
	DECLARE @startdatestr VARCHAR(150),@enddatestr VARCHAR(150),@stypeidstr VARCHAR(150),@monthnostr VARCHAR(150)
	
	FETCH NEXT FROM Cousor_MonthPro INTO @startdatestr,@enddatestr,@stypeidstr,@monthnostr
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 卡片数据
		;WITH cte AS (
			SELECT  rn=ROW_NUMBER() over(PARTITION BY STypeId,AssertsCardId ORDER BY BusinessDate desc,id desc),
					NetValue,
					@monthnostr AS MonthNo,
					BillType,
					stypeid
			FROM Ac_AssetsCards_History a 
			WHERE CAST(a.BusinessDate AS date)<=@enddatestr  
			AND a.audittype NOT IN (-3,-4) AND a.STypeId IN (SELECT typeid FROM #stype)
		)
		UPDATE a SET a.val=b.NetValue
		FROM #stypeinfo a 
		INNER JOIN 
		(
			SELECT	stypeid,
					SUM(netvalue) AS netvalue,
					MonthNo
			FROM	cte 
			WHERE  rn=1  AND (billtype<>213 OR billtype IS NULL)
			GROUP BY stypeid,MonthNo
			) b ON a.stypeid=b.stypeid  AND a.MonthNo=b.MonthNo
		WHERE a.iscard=1
		
		FETCH NEXT FROM Cousor_MonthPro INTO @startdatestr,@enddatestr,@stypeidstr,@monthnostr
	END
	
	CLOSE Cousor_MonthPro
	DEALLOCATE Cousor_MonthPro
	
END
ELSE
BEGIN
	-- 项目数据
	UPDATE a SET a.val=b.total FROM #stypeinfo a 
	 INNER JOIN (
		 SELECT a.stypeid,ISNULL(SUM(total),0) AS total 
		 FROM dbo.AType_Total a,#Months m WHERE atypeid LIKE'0000100002%' GROUP BY a.stypeid
	) b ON a.stypeid=b.stypeid
	WHERE a.iscard=0 
END


--缺少的代码（拷贝资产负债表）

--判断资产负债表的权限
DECLARE @res INT 
EXEC @res = GP_CheckLimit @OperatorID,4226

CREATE TABLE #t1(atypeid NVARCHAR(50),total  NUMERIC(24, 10),stypeid VARCHAR(100),MonthNo VARCHAR(200));

INSERT INTO #t1	
	SELECT atypeid,ISNULL(SUM(total),0) AS total,
	l.STypeID,
	MonthNo
	FROM ListTable l,#Months m
	WHERE billdate <=m.EndDate  AND l.STypeID IN ( SELECT typeId FROM #Stype )
	GROUP BY l.STypeID,atypeid,MonthNo

--是否启用发票立账
DECLARE @isinvoice INT
SET @isinvoice = ISNULL((SELECT SubValue FROM dbo.sysdata WHERE SubName = 'isinvoice'),0)

--2015-05-18 杨俊修改 因需求HH，强烈需要这样干，所以把[发出商品]放在[库存商品总值]下一行、[应付暂估]放在[应付合计]下一行
SELECT  p.nparid AS parid ,
		p.deleted ,
		p.leveal ,
		p.ntypeId AS typeid,
		CASE FullName
			WHEN '发出商品' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '库存商品总值') + '1'
			WHEN '应付暂估' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '应付合计') + '1'
			ELSE p.ntypeId
		END AS ordertypeid,
		p.UserCode ,
		p.FullName ,
		p.sonnum ,
		ISNULL(s.Total00,0)+ISNULL(t1.total,0) AS total ,
		ISNULL(s.total00,0) AS total00,
		nId,
		m.MonthNo
INTO    #Atype
FROM    dbo.Ac_Items p
		LEFT JOIN ( 
			SELECT a.atypeid,SUM(a.Total00) AS total00
			FROM dbo.AType_Total a
			INNER JOIN #Stype s ON a.STypeID=s.typeid
			GROUP BY a.ATypeID
		) s ON s.ATypeID = p.nId
		LEFT JOIN #t1 t1 ON t1.atypeid=p.nId
		LEFT JOIN #Months m ON m.MonthNo=t1.MonthNo AND m.stypeid=t1.stypeid
WHERE   p.ntypeId <> '00000'
	AND (NOT(@isinvoice = 0)--是否启用发票立账
	OR (@isinvoice = 0) AND P.UserCode NOT IN('1251','2122'))


IF @res =1	--没有查看损益表所有项目的权限
BEGIN
	DELETE 
	FROM	#Atype 
	WHERE	typeid NOT IN (
		SELECT nTypeId FROM F_AllTreeAssetsT(@OperatorID)--资产合计(固定资产+银行账户+管辖其他资产)
		UNION ALL
		SELECT nTypeId FROM F_AllTreeInDebtT(@OperatorID)--负债合计（管辖负债+账户里面的预收）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeOwnerEquityT(@OperatorID)--所有者权益
		UNION ALL
		SELECT '00001' AS nTypeId
		UNION ALL
		SELECT '00002' AS nTypeId
		UNION ALL
		SELECT '00005' AS nTypeId
		UNION ALL
		SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出） 		
	)
END


--减少临时表复杂程度
CREATE TABLE #LeftTable
(
	MonthNo			VARCHAR(200),
	Total			NUMERIC(24, 10),
	AtypeId			VARCHAR(200),
	StartDate		DATETIME,
	EndDate			DATETIME
)
CREATE NONCLUSTERED INDEX Non_#LeftTable_Index_A ON #LeftTable(AtypeId)

INSERT INTO #LeftTable
SELECT	B.MonthNo,
		ISNULL(SUM(LT.Total),0) Total,
		LT.AtypeId,
		B.StartDate,
		B.EndDate 
FROM	#Months B
INNER JOIN ListTable LT on LT.BillDate <= B.EndDate
INNER JOIN #Stype S ON S.TypeID = LT.STypeID
GROUP BY B.MonthNo,LT.AtypeId,B.StartDate,B.EndDate

CREATE TABLE #InnerTable
(
	nTypeId			VARCHAR(200)
)
CREATE NONCLUSTERED INDEX Non_#InnerTable_Index_n ON #InnerTable(nTypeId)

INSERT INTO #InnerTable
SELECT nTypeId FROM F_AllTreeAssetsT(@OperatorID)--资产合计(固定资产+银行账户+管辖其他资产)
UNION ALL
SELECT nTypeId FROM F_AllTreeInDebtT(@OperatorID)--负债合计（管辖负债+账户里面的预收）
UNION ALL
SELECT nTypeId FROM F_AllTreeOwnerEquityT(@OperatorID)--所有者权益


--新增#Total（方便处理期初数据）
INSERT INTO #Total(nTypeId,MonthNo,FullName,TOTAL,Total00,StartDate,EndDate)
SELECT		nTypeId, 
			MonthNo, 
			FullName, 
			SUM(Total)+(CASE WHEN @FirstMonthNo=MonthNo OR MonthNo IS NULL THEN SUM(Total00) ELSE 0 END), 
			SUM(Total00),
			StartDate,
			EndDate
FROM (   
		SELECT	Ac.nTypeId,
				M.MonthNo,
				Ac.FullName,
				0 Total,
				0 Total00,
				StartDate,
				EndDate
		FROM	Ac_Items Ac,#Months M
		UNION
		SELECT	A1.nTypeId,
				L.MonthNo, 
				A1.FullName, 
				TOTAL, 
				0 Total00, 
				StartDate, 
				EndDate
		FROM	Ac_Items A1
		INNER JOIN #InnerTable opera ON opera.nTypeId=A1.nTypeId
		--非期初金额
		LEFT JOIN #LeftTable L ON L.AtypeId = A1.nId
		)T
		WHERE nTypeId <> '00000' 
		GROUP BY nTypeId, MonthNo, FullName,StartDate,EndDate
		

    UPDATE a SET a.total00=ISNULL(b.Total00,0) FROM #Total a,(
    SELECT SUM(a.Total00)total00,c.nTypeId FROM dbo.AType_Total a
    INNER JOIN #Stype s ON a.STypeID=s.TypeID
    INNER JOIN dbo.Ac_Items c ON a.ATypeID=c.nId
    INNER JOIN (
			SELECT nTypeId FROM F_AllTreeAssetsT(@OperatorID)--资产合计(固定资产+银行账户+管辖其他资产)
			UNION ALL
			SELECT nTypeId FROM F_AllTreeInDebtT(@OperatorID)--负债合计（管辖负债+账户里面的预收）
			UNION ALL
			SELECT nTypeId FROM F_AllTreeOwnerEquityT(@OperatorID)--所有者权益
		) opera ON opera.nTypeId=C.nTypeId
    GROUP BY c.nTypeId)b
    WHERE a.nTypeId=b.nTypeId

--UPDATE A SET a.total00=ISNULL(b.Total00,0) FROM #Total A,dbo.AType_Total b,dbo.Ac_Items c WHERE a.nTypeId=c.nTypeId AND b.ATypeID=c.nid

--SELECT * FROM #Total
--return

-- 初始化期初值
--UPDATE #Total SET	TOTAL = TOTAL+(SELECT ISNULL(SUM(B.Total00),0) FROM #Total B WHERE A.nTypeId = B.nTypeId AND B.Total00 > 0 AND B.MonthNo IS NULL ), 
--					Total00 = (SELECT ISNULL(SUM(B.Total00),0) FROM #Total B WHERE A.nTypeId = B.nTypeId AND B.Total00 > 0 AND B.MonthNo IS NULL ) 
--					FROM  #Total A


DELETE #Total WHERE MonthNo IS NULL

-- 迭代累加Total
UPDATE #Total SET TOTAL = TOTAL+Total00

-- 查询结果集
INSERT INTO #TEMP
SELECT  A.UserCode,
		A.FullName,
		A.Leveal,
		A.NTypeId,
		A.NParId,
		A.SonNum,
		tmp.MonthNo,
		ISNULL(SUM(tmp.Total),0) as Total,
		ISNULL(SUM(tmp.Total),0) - ISNULL(SUM(tmp.Total00),0)CurrentTotal
FROM	Ac_Items A
Inner JOIN #Total tmp ON tmp.nTypeId like A.nTypeId + '%'
WHERE  A.ntypeId <> '00000' 
GROUP BY A.UserCode,A.FullName,A.Leveal,A.ntypeId,A.NParId,A.SonNum,tmp.MonthNo


DECLARE @MonthNo VARCHAR(100)  
DECLARE BassCurSor CURSOR FOR SELECT MonthNo FROM #Months

OPEN BassCurSor
FETCH NEXT FROM BassCurSor INTO @MonthNo
WHILE @@FETCH_STATUS =0
BEGIN

	IF(@display_1=1)
	BEGIN
		IF @Leveal<>0
		BEGIN
			DELETE #TEMP WHERE NparId='0000100002' AND MonthNo = @MonthNo
		END
		UPDATE #TEMP SET total= (SELECT SUM(val) FROM #stypeinfo WHERE  MonthNo = @MonthNo) WHERE nTypeId='0000100002' AND MonthNo = @MonthNo
	END
	
	-- 资产合计
	UPDATE #TEMP SET total=(SELECT sum(isnull(total,0)) FROM #TEMP WHERE NparId ='00001' AND MonthNo = @MonthNo) WHERE nTypeId='00001'  AND MonthNo = @MonthNo


	-- 未分配利润
	--UPDATE #TEMP 
	--SET		Total = ISNULL(Total,0) + (SELECT ISNULL(SUM(Total),0) FROM #TEMP WHERE nTypeId LIKE '00003%' AND Sonnum = 0 
	--				AND MonthNo = @MonthNo) - (SELECT ISNULL(SUM(Total),0) FROM #TEMP WHERE nTypeId LIKE '00004%' AND Sonnum = 0 
	--				AND MonthNo = @MonthNo) 
	--WHERE #TEMP.nTypeId = '0000500005' AND MonthNo = @MonthNo
	
	-- 未分配利润
	UPDATE #TEMP SET total=total+((SELECT ISNULL(sum(total),0)-ISNULL(SUM(total00),0) FROM #Atype WHERE parid like '00003%' and sonnum=0 AND MonthNo = @MonthNo)-(SELECT ISNULL(sum(total),0)-ISNULL(SUM(total00),0) FROM #Atype WHERE parid like '00004%' and sonnum=0 AND MonthNo = @MonthNo)) WHERE ntypeid='0000500005' AND MonthNo = @MonthNo


	-- 修改所有者权益 = 资产-负债
	UPDATE #TEMP 
	SET		Total = (SELECT ISNULL(SUM(Total),0) FROM #TEMP WHERE nTypeId = '00001' 
					AND MonthNo = @MonthNo) - (SELECT ISNULL(SUM(Total),0) FROM #TEMP WHERE nTypeId  = '00002' 
					AND MonthNo = @MonthNo) 
	WHERE #TEMP.nTypeId = '00005' AND MonthNo = @MonthNo
	
	
	--其他资本
	UPDATE #TEMP 
	SET		Total = (SELECT ISNULL(Total,0) FROM #TEMP WHERE nTypeId = '00005'  
					AND MonthNo = @MonthNo ) - (SELECT ISNULL(SUM(Total),0) FROM #TEMP WHERE nTypeId LIKE '00005%' AND nTypeId <> '0000500002' 
					AND Sonnum = 0  AND MonthNo = @MonthNo )
	 WHERE #TEMP.nTypeId = '0000500002' AND MonthNo = @MonthNo
		
	FETCH NEXT FROM BassCurSor INTO @MonthNo
END
CLOSE BassCurSor
DEALLOCATE BassCurSor

-- 筛选
DELETE #TEMP WHERE nTypeId LIKE '00003%'  OR  nTypeId LIKE '00004%' OR Leveal > @Leveal
DELETE #TEMP WHERE Ntypeid ='0000100013' OR Ntypeid ='0000100014'

--判断损益表的权限
DECLARE @re INT 
EXEC @re = GP_CheckLimit @OperatorID,4226
--SELECT @re 're'
IF @re =1	--没有查看损益表所有项目的权限
BEGIN
	DELETE 
	FROM	#TEMP 
	WHERE	NTypeId NOT IN (
		SELECT nTypeId FROM F_AllTreeAssetsT(@OperatorID)--资产合计(固定资产+银行账户+管辖其他资产)
		UNION ALL
		SELECT nTypeId FROM F_AllTreeInDebtT(@OperatorID)--负债合计（管辖负债+账户里面的预收）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeOwnerEquityT(@OperatorID)--所有者权益
	)
END

---- 隐藏为0的数据
DELETE #TEMP WHERE @HideZero =1 AND TOTAL = 0 AND CURRENTTOTAL = 0

-- 修改显示格式
UPDATE #TEMP SET FullName ='    '+FullName WHERE Leveal =2
UPDATE #TEMP SET FullName ='        '+FullName WHERE Leveal =3
UPDATE #TEMP SET FullName ='            '+FullName WHERE Leveal =4
UPDATE #TEMP SET FullName ='                '+FullName WHERE Leveal =5
UPDATE #TEMP SET FullName ='                    '+FullName WHERE Leveal =6
UPDATE #TEMP SET FullName ='                        '+FullName WHERE Leveal =7
UPDATE #TEMP SET FullName ='                            '+FullName WHERE Leveal =8
UPDATE #TEMP SET FullName ='                                '+FullName WHERE Leveal =9
UPDATE #TEMP SET FullName ='                                    '+FullName WHERE Leveal =10		
	
SET @SQL = 'SELECT A.UserCode,A.FullName,A.Leveal,A.ntypeId,A.NParId,A.SonNum' 
SELECT @SQL = @SQL + ',SUM(CASE WHEN A.MONTHNO = '''+MONTHNO+''' THEN TOTAL ELSE 0 END) ['+MonthNo+']' FROM #Months
SET @SQL += 'FROM #TEMP A GROUP BY A.UserCode,A.FullName,A.Leveal,A.ntypeId,A.NParId,A.SonNum ORDER BY A.NTYPEID'

--print @sql
EXEC (@SQL)


DROP TABLE #TEMP,#Months,#Stype,#Total,#LeftTable,#InnerTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BatchDelBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BatchDelBill]
GO




/*
	作者：谢吉康
	日期：2008-04-01
	描述：批量删除草稿
	
	
	--2017-03-24 梁晰 删除附件日志bug169
*/
CREATE    PROCEDURE Web_BatchDelBill
(
	@nBillIds	varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON

--判断是否含有由pos上次数据生成的零售单--此类单据不能删除-9.2--
IF EXISTS(SELECT 1 FROM BillIndex WHERE BILLNUMBERID IN (SELECT * FROM f_split(@nBillIds,',')) AND BillType in (305,215,11) AND NewPosBill=1)
BEGIN
	RETURN -3
END

--2017-03-20 梁晰 判断是否含有已支付过的草稿 不能删除
IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillNumberId IN (SELECT * FROM f_split(@nBillIds,',')) AND (PayType <> 0 OR PayType IS NULL))
BEGIN
    RETURN -4
END

--易聚客生成的单据不能删除
IF EXISTS(SELECT 1 FROM BillIndex WHERE BILLNUMBERID IN (SELECT * FROM f_split(@nBillIds,',')) AND BillType in (305,215,11) AND ISNULL(YjkBillCode,'')<>'')
BEGIN
    RETURN -5
END

IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE IfCheck = 't' AND draft=0 AND BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		  UNION ALL
		  SELECT TOP 1 1 FROM dbo.ListTable A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND A.BillType=B.BillType
			WHERE B.BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		  UNION ALL
		  SELECT TOP 1 1 FROM dbo.InOutstocktable A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId AND A.BillType=B.BillType
			WHERE B.BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		  )
	RETURN -1

ELSE
	BEGIN
		-- 删除维修受理单
		UPDATE 	RepairEngage 
		SET 	Stat =1 
		Where 	BillnumberID IN (
									SELECT 	EngageBillID 
									FROM 	RepairDeal 
									WHERE 	BillNumberID IN (
																SELECT 	BillNumberID 
																FROM 	BillIndex 
																WHERE 	BillType = 157 
																		AND IfCheck = 'f' 
																		AND Draft = 1 
																		AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,','))
																		AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
															)
								)

		DELETE 
		FROM	RepairDeal 
		WHERE	BillnumberID IN (SELECT BillNumberID FROM BillIndex WHERE BillType = 157 AND IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,',')))
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)

		DELETE 
		FROM	CompleteTotal 
		WHERE	(
					GoodsBillID IN (SELECT BillNumberID FROM BillIndex WHERE IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,','))) 
					AND GoodsBillID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				)
				OR 
				(
					MoneyBillID IN (SELECT BillNumberID FROM BillIndex WHERE IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,',')))
					AND MoneyBillID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				)
				 --处理按单结算的问题
		
		DELETE 
		FROM	CompleteGoodTotal 
		WHERE	(
					GoodsBillID IN (SELECT BillNumberID FROM BillIndex WHERE IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,','))) 
					AND GoodsBillID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				)
				OR 
				(
					MoneyBillID IN (SELECT BillNumberID FROM BillIndex WHERE IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,',')))
					AND MoneyBillID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				)	-- 处理按商品结算
		
		-- 删除发票
		DELETE 
		FROM	invoiceBill 
		WHERE	BillNumberID IN (
									SELECT	BillNumberID 
									FROM	BillIndex 
									WHERE	IfCheck = 'f' 
											AND Draft = 1 
											AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,','))
											AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
								)
								
		-- 删除网店订单单据对应关系
		DELETE 
		FROM	dbo.WdShopBillRelation 
		WHERE Billnumberid IN (SELECT * FROM F_Split(@nBillIds,','))

		--删除快修单
		DELETE 
		FROM	Billindex_CarRepair 
		WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)

		--删除附件
		DELETE 
		FROM	BillAttachFiles 
		WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		
		--删除附件日志
		DELETE 
		FROM	BillAttachFilesLog 
		WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		
		--删除多账户信息 排除优惠券的billnumberid,订单的billnumberid
		DELETE 
		FROM	BillMulAccount 
		WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))		
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				AND billtype NOT IN (423,424,425,426,300,313,301)
		
		--删除多账户品牌信息
		DELETE 
		FROM	BillMulBrand 
		WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))		
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		
		--删除单据操作日志
		DELETE 
		FROM	BillOperateLog 
		WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))		
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		
		--删除打印日志 2015-06-11 9.6BUG 1175 杨俊修改：删除草稿时不清除打印记录
		--DELETE 
		--FROM	PrintRecord 
		--WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))	
		--		AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
		
		--删除增加的打印次数记录
		--DELETE FROM AddPrintCountRecord WHERE BillNumberId IN (SELECT * FROM F_Split(@nBillIds,',')) AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)	
		--**********************--	
			
		--删除销售出库单时，删除调用电脑配置单的记录
		IF EXISTS (SELECT *FROM BillIndex WHERE BillNumberId IN (SELECT * FROM F_Split(@nBillIds,',')) AND BillType='11')
		BEGIN
			CREATE	TABLE #BillNumBerID (ID VARCHAR(50))
			
			INSERT INTO #BillNumBerID			
			SELECT	BillNumberId 
			FROM	BillIndex 
			WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,',')) AND BillType='11'
					AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
			
			DELETE DiyBillTypePSaleTypeID WHERE SalebillNumberId IN (SELECT * FROM #BillNumBerID)
			DROP TABLE #BillNumBerID
		END	
		
		--删除销售出库单时，更新订单里的待发货数量
		IF EXISTS (SELECT *FROM BillIndex BI INNER JOIN SaleBill SA ON SA.BillNumberId=BI.BillNumberId WHERE BI.BillNumberId IN (SELECT * FROM F_Split(@nBillIds,',')) AND BI.BillType='11' AND SA.OrderID<>'-1') 
		BEGIN
			CREATE	TABLE #Bill (QTY INT,ORDERID INT)
			
			INSERT INTO #Bill		
			SELECT	SUM(SA.Qty),
					SA.OrderID
			FROM	BillIndex BI
			INNER JOIN SaleBill SA ON SA.BillNumberId=BI.BillNumberId 
			WHERE	BI.BillNumberId IN (SELECT * FROM F_Split(@nBillIds,',')) AND BillType='11' AND SA.OrderID<>'-1'
					AND BI.BillNumberId NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
			GROUP BY SA.OrderID
			
			--UPDATE OrderBill SET OrderBill.WaitQty=CASE WHEN OrderBill.WaitQty-B.QTY>0 THEN OrderBill.WaitQty-B.QTY ELSE 0 END FROM #Bill B WHERE B.ORDERID=ORDERBILL.OrderID
			DROP TABLE #Bill
			
		END	
		
		--删除价格促销信息
		DELETE FROM BeforePromoteIndex WHERE BillNumberId in 
								(select BeforePromoBillNumberId from BillIndex where BillNumberId in (select * from f_split(@nBillIds,',')))
		DELETE FROM BeforePromoteRetailBill WHERE BillNumberId in 
								(select BeforePromoBillNumberId from BillIndex where BillNumberId in (select * from f_split(@nBillIds,',')))
		DELETE FROM BeforePromoteSaleBill WHERE BillNumberId in 
								(select BeforePromoBillNumberId from BillIndex where BillNumberId in (select * from f_split(@nBillIds,',')))								
								
		
		--删除固定资产增加、减少单时，删除AssetIncDecBill表对应数据
		DELETE FROM AssetIncDecBill WHERE BillType in (212,213) AND BILLNUMBERID IN (SELECT * FROM f_split(@nBillIds,','))
		
		--删除
		DELETE FROM Coupon_BillUsed WHERE BILLNUMBERID IN (SELECT * FROM f_split(@nBillIds,',')) AND billtype IN (305, 215, 11, 45, 12, 46)
		
		--删除积分转储值单		
		DELETE FROM dbo.VipCentToMoneyBill WHERE BillNumberId IN (SELECT * FROM f_split(@nBillIds,','))
		
		--删除WMS单据
		DELETE FROM WMS_ERPBillRelation WHERE ERP_BillNumberID IN (SELECT * FROM f_split(@nBillIds,','))
		
		--最后执行这步
		DELETE 
		FROM	BillIndex 
		WHERE	IfCheck = 'f' 
				AND Draft = 1 
				AND PosBillType = 0
				AND BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				
		IF @@ROWCOUNT = 0
			RETURN -2
		ELSE
			RETURN 0
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BatchDeleteBtypeSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BatchDeleteBtypeSelector]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：舒珊
	日期：2016-04-15
	描述：往来单位的模糊匹配
-------------------------------------------*/
CREATE PROCEDURE Web_BatchDeleteBtypeSelector
(
	@OperatorID			VARCHAR(50),	
	@IsSon				INT,
	@IsStop				INT,--0：全部；1：是；2：否
	@IsLimit			INT,
	@UserCode			VARCHAR(3000) ,--单位编码
	@AreaTypeId			VARCHAR(MAX)='',-- 地区
	@FullName			VARCHAR(3000) ,--单位名称
	@SelectorType		VARCHAR(50),
	@TypeId				VARCHAR(100),	--基本信息的Id
	@IsNext				INT
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @First    INT=0  --首次进入 对往来单位有用 其他为0

DECLARE @SQL VARCHAR(MAX)
DECLARE @SonNum INT
DECLARE @ParId	VARCHAR(100)

DECLARE @MinSql VARCHAR(500) = ''

SET @MinSql = ' WHERE 1 = 1 '
IF @IsStop = 1--默认显示停用
	SET @MinSql += ' AND deleted = 1'
ELSE IF @IsStop = 2--未停用
	SET @MinSql += ' AND deleted = 0'
IF @IsSon = 1
	SET @MinSql += ' AND sonnum = 0'
	
IF @TypeId = '' SET @TypeId = '00000'

CREATE TABLE #BtypeInfo
(
	TypeID		VARCHAR(100),
	ParId		VARCHAR(100),
	SonNum		INT,
	deleted		INT,			
	UserCode	VARCHAR(256),
	FullName	VARCHAR(256),
	PyCode		VARCHAR(256),
	SortID		NUMERIC(10,0) DEFAULT(0),
	AreaTypeId	VARCHAR(50)
)
DECLARE @BTypeAll INT=0  --1全部
--判断供货商和客户是否统一
IF @SelectorType = 'vb'
	SET @BTypeAll = 1
ELSE
	SELECT	@BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

IF @IsLimit = 0 OR @MBtypeid = '00000'
	SET @SQL = 'INSERT INTO #BtypeInfo(TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,AreaTypeId) 
				SELECT TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,AreaTypeId FROM btype '
ELSE
	SET @SQL = 'INSERT INTO #BtypeInfo(TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,AreaTypeId) 
				SELECT TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,AreaTypeId FROM F_GetManBTypeAll('''+@OperatorId+''') ' 

SET @SQL += @MinSql
EXEC(@SQL)
IF @BTypeAll = 0  --非统一时删除数据
BEGIN
	IF @SelectorType = 'gb'--供货商
		DELETE #BaseInfo WHERE TypeID LIKE '00001%'
	IF @SelectorType = 'kb'--客户
		DELETE #BaseInfo WHERE TypeID LIKE '00002%'
END

--重新设置Typeid
IF @TypeId = '00000' AND @BTypeAll = 0 AND @SelectorType <> 'vb'
BEGIN
	IF @SelectorType = 'kb' 
		SET @TypeId = '00001'
	ELSE
		SET @TypeId = '00002'
	
	SET @First = 1
END




--公用
SELECT @SonNum = SonNum,@ParId=ParId FROM #BtypeInfo WHERE TypeId = @TypeId
DELETE #BtypeInfo WHERE TypeID = '00000'

print @TypeId
print @ParId
--如果筛选项未填信息，停用为'全部'时，出树形表
IF @IsStop = 0 AND @UserCode='' AND @AreaTypeId='' AND @FullName=''
BEGIN
	IF @IsNext = '0'
		BEGIN
			SELECT * FROM #BtypeInfo WHERE ParId = @ParId ORDER BY SortID,UserCode
		END
	ELSE --下一层
		BEGIN			
			IF @SonNum = 0
				SELECT * FROM #BtypeInfo WHERE SonNum = 0 AND TypeId = @TypeId ORDER BY SortID,UserCode
			ELSE
				BEGIN
					IF @First = 1 AND (@TypeId = '00001' OR @TypeId = '00002')
						SELECT * FROM #BtypeInfo WHERE TypeID = @TypeId ORDER BY SortID,UserCode
					ELSE
						SELECT * FROM #BtypeInfo WHERE ParId = @TypeId ORDER BY SortID,UserCode		
				END
		END
END
ELSE
BEGIN
--单位编码、单位名称、地区 任一有值 或者不为停用时 出线性表
	IF @AreaTypeId =''
		BEGIN
			SET @SQL = 
				'SELECT * FROM #BtypeInfo
				 WHERE	SonNum = 0 
						AND UserCode LIKE ''%'+@UserCode+'%'' AND FullName LIKE ''%'+@FullName+'%'''
				EXEC(@SQL)	
		END 
	ELSE 
		BEGIN
			SET @AreaTypeId = LTRIM(RTRIM(@AreaTypeId))
			CREATE TABLE #AreaType(TypeId	varchar(100))
			INSERT INTO #AreaType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@AreaTypeId,10,@OperatorID)	
			SET @SQL = 
			'SELECT * FROM #BtypeInfo
			 WHERE	SonNum = 0 
					AND UserCode LIKE ''%'+@UserCode+'%'' AND FullName LIKE ''%'+@FullName+'%'' AND ISNULL(AreaTypeId,'''') IN (SELECT TypeId FROM #AreaType)'
					
			EXEC(@SQL)
			DROP TABLE #AreaType	
		END 			 
END

DROP TABLE #BtypeInfo



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BatchDeletePtypeSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BatchDeletePtypeSelector]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：舒珊
	日期：2016-04-15
	描述：商品的模糊匹配
-------------------------------------------*/
CREATE PROCEDURE Web_BatchDeletePtypeSelector
(
	@OperatorID			VARCHAR(50),	
	@IsSon				INT,
	@IsStop				INT,--0：全部；1：是；2：否
	@IsLimit			INT,
	@UserCode			VARCHAR(3000) ,--商品编码
	@FullName			VARCHAR(3000) ,--商品名称
	@Standard			VARCHAR(3000),--商品规格
	@Type				VARCHAR(3000),--商品型号
	@EntryCode          VARCHAR(3000),--商品条码
	@TypeId				VARCHAR(100),--商品Id
	@IsNext				INT,
	@Flag				VARCHAR			--公用字段  商品（1=不包含服务类商品）				
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL VARCHAR(MAX)
DECLARE @SonNum INT
DECLARE @ParId	VARCHAR(100)

DECLARE @MinSql VARCHAR(500) = ''

SET @MinSql = ' WHERE 1 = 1 '
IF @IsStop = 1--默认显示停用
	SET @MinSql += ' AND deleted = 1'
ELSE IF @IsStop = 2--未停用
	SET @MinSql += ' AND deleted = 0'
IF @IsSon = 1
	SET @MinSql += ' AND sonnum = 0'
	
--特殊处理 Start
IF  @Flag = '1' --不包含服务商品
BEGIN
	SET @MinSql += ' AND IsService = 0 '
END

--特殊处理 End
IF @TypeId = '' SET @TypeId = '00000'

CREATE TABLE #PtypeInfo
(
	TypeID		VARCHAR(50),
	ParId		VARCHAR(50),
	SonNum		INT,
	deleted		INT,			
	UserCode	VARCHAR(256),
	FullName	VARCHAR(256),
	PyCode		VARCHAR(256),
	SortID		NUMERIC(10,0) DEFAULT(0),
	EntryCode	VARCHAR(256),
	[Standard]	VARCHAR(200),
	[Type]		VARCHAR(200)

	
)

--判断权限范围
IF @IsLimit = 0 OR @MPtypeid = '00000'
	SET @SQL = 'INSERT INTO #PtypeInfo(TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID,EntryCode,[Standard],[Type]) 
				SELECT TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID,EntryCode,[Standard],[Type] FROM PType '
ELSE
	SET @SQL = 'INSERT INTO #PtypeInfo(TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID,EntryCode,[Standard],[Type]) 
				SELECT TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID,EntryCode,[Standard],[Type]  FROM F_GetManPTypeAll('''+@OperatorId+''') ' 
	
SET @SQL += @MinSql
EXEC(@SQL)

--公用
SELECT @SonNum = SonNum,@ParId=ParId FROM #PtypeInfo WHERE TypeId = @TypeId
DELETE #PtypeInfo WHERE TypeID = '00000'

--如果筛选项未填信息，停用为'全部'时，出树形表
IF @IsStop = 0 AND @UserCode='' AND @FullName='' AND @Standard='' AND @Type='' AND @EntryCode=''
BEGIN
	IF @IsNext = '0'
		BEGIN
			SELECT * FROM #PtypeInfo WHERE ParId = @ParId ORDER BY SortID,UserCode
		END
	ELSE --下一层
		BEGIN			
			IF @SonNum = 0
				SELECT * FROM #PtypeInfo WHERE SonNum = 0 AND TypeId = @TypeId ORDER BY SortID,UserCode
			ELSE
				BEGIN
						SELECT * FROM #PtypeInfo WHERE ParId = @TypeId ORDER BY SortID,UserCode		
				END
		END
END
ELSE
	BEGIN
		--商品编码、名称、规格、型号、条码 任一有值 或者不为停用时 出线性表
		SET @SQL = '
		SELECT * 
		FROM #PtypeInfo
		WHERE
			SonNum=0'+CHAR(13)
		--编码
		IF(ISNULL(@UserCode,'')<>'')
			SET @SQL+='AND UserCode LIKE ''%'+@UserCode+'%'''+CHAR(13)
		--名称
		IF(ISNULL(@FullName,'')<>'')
			SET @SQL+='AND FullName LIKE ''%'+@FullName+'%'''+CHAR(13)
		--规格
		IF(ISNULL(@Standard,'')<>'')
			SET @SQL+='AND [Standard] LIKE ''%'+@Standard+'%'''+CHAR(13)
		--型号
		IF(ISNULL(@Type,'')<>'')
			SET @SQL+='AND [Type] LIKE ''%'+@Type+'%'''+CHAR(13)
		--条码
		IF(ISNULL(@EntryCode,'')<>'')
			SET @SQL+='AND EXISTS(SELECT * FROM PType_EntryCode_Ext WHERE EntryCode LIKE ''%'+@EntryCode+'%'')'+CHAR(13)
			
		EXEC(@SQL) 
	END

DROP TABLE #PtypeInfo


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BatchDelFactBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BatchDelFactBill]
GO




/*
	作者：魏伟
	日期：2016-07-14
	描述：批量删除草稿
*/
CREATE    PROCEDURE Web_BatchDelFactBill
(
	@nBillIds	varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON

----判断是否含有由pos上次数据生成的零售单--此类单据不能删除-9.2--
--IF EXISTS(SELECT 1 FROM BillIndex WHERE BILLNUMBERID IN (SELECT * FROM f_split(@nBillIds,',')) AND BillType in (305,215) AND NewPosBill=1)
--BEGIN
--	RETURN -3
--END

IF EXISTS(SELECT TOP 1 1 FROM dbo.FactIndex WHERE IfCheck = 't' AND draft=0 AND BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		  UNION ALL
		  SELECT TOP 1 1 FROM dbo.ListTable A INNER JOIN dbo.FactIndex B ON A.BillNumberId=B.BillNumberId AND A.BillType=B.OtherType
			WHERE B.BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		  UNION ALL
		  SELECT TOP 1 1 FROM dbo.InOutstocktable A INNER JOIN dbo.FactIndex B ON A.BillNumberId=B.BillNumberId AND A.BillType=B.OtherType
			WHERE B.BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
		  )
	RETURN -1

ELSE
	BEGIN 
		DELETE 
		FROM	CompleteTotal 
		WHERE	(
					GoodsBillID IN (SELECT BillNumberID FROM dbo.FactIndex WHERE IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,','))) 
					AND GoodsBillID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				)
				OR 
				(
					MoneyBillID IN (SELECT BillNumberID FROM dbo.FactIndex WHERE IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,',')))
					AND MoneyBillID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				)
				 --处理按单结算的问题
		
		DELETE 
		FROM	CompleteGoodTotal 
		WHERE	(
					GoodsBillID IN (SELECT BillNumberID FROM dbo.FactIndex WHERE IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,','))) 
					AND GoodsBillID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				)
				OR 
				(
					MoneyBillID IN (SELECT BillNumberID FROM dbo.FactIndex WHERE IfCheck = 'f' AND Draft = 1 AND BillNumberID IN (SELECT * FROM F_Split(@nBillIds,',')))
					AND MoneyBillID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2 AND IfAudit = 1)
				)	-- 处理按商品结算 
	 

		--删除附件
		DELETE 
		FROM	BillAttachFiles 
		WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType =7 AND IfAudit = 1) 
		--删除单据操作日志
		DELETE 
		FROM	BillOperateLog 
		WHERE	BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))		
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 7 AND IfAudit = 1) 
				
		
		--获取billtype
		DECLARE @TableName VARCHAR(50)
		DECLARE @BILLNUMBERID INT,@billtype INT
		DECLARE @SQL NVARCHAR(2000)
				
		--删除表体明细
		DECLARE detail_cursor CURSOR
		FOR
			SELECT isnull(bn.Detailtable,''),fi.billnumberid,fi.BillType from dbo.FactIndex  fi 
			       inner join  billname bn on fi.billtype=bn.billtype
				where	fi.IfCheck = 'f' 
				AND fi.Draft = 1  
				AND fi.BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
				AND fi.BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 7 AND IfAudit = 1)
				
		FOR READ only

		OPEN detail_cursor
		FETCH NEXT FROM detail_cursor INTO  @TableName,@BILLNUMBERID,@billtype
		WHILE @@fetch_status=0
		BEGIN
		IF @TableName<>''
		BEGIN
		
			 IF @billtype IN(418,419)
			 BEGIN
				DECLARE		@GoodsBillNumberID INT,					/*出库单单据编号*/
					@GoodsBillType     INT,					/*出库单单据类型*/
					@RowIndex          INT,					
					@RowCount          INT					/*运输单明细行数*/
					DECLARE	    @Tmp			   TABLE
					(
						GoodsBillNumberID INT,
						GoodsBillType     INT,
						RowIndex          INT
					)
					
					INSERT INTO @Tmp(GoodsBillNumberID,GoodsBillType,RowIndex)
					SELECT 
						   FromBillNumberID,
						   FromBillType,
						   ROW_NUMBER() OVER(ORDER BY GETDATE())
					FROM dbo.FactDepotInOut 
					WHERE billNumberID=@BILLNUMBERID	AND FromBillNumberID>0 AND FromBillType>0
					
					--删除明细数据
					DELETE FROM FactDepotInOut WHERE BillNumberID = @billnumberid
					
					SELECT @RowIndex=1,@RowCount=COUNT(1) FROM @Tmp
					/*仓库入库单*/
					IF @BillType=418
					BEGIN
						WHILE(@RowIndex<=@RowCount)
						BEGIN
							SELECT @GoodsBillNumberID=GoodsBillNumberID,
								   @GoodsBillType=GoodsBillType
							FROM @Tmp WHERE @RowIndex=RowIndex
							
							IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId AND b.RedWord=0 
								WHERE A.FromBillNumberID=@GoodsBillNumberID AND A.FromBillType=@GoodsBillType)
							BEGIN
								IF @GoodsBillType IN(71,72,87,88)
								BEGIN
									UPDATE dbo.LendIndex 
									SET 
										InFactRefState=0
									WHERE BillNumberId=@GoodsBillNumberID
									
								END
								ELSE
								BEGIN
									UPDATE dbo.BillIndex 
									SET 
										InFactRefState=0
									WHERE BillNumberId=@GoodsBillNumberID
								END
							END
							SET @RowIndex=@RowIndex+1
						END
						
					END
					/*仓库出库单*/
					IF @BillType=419
					BEGIN
						WHILE(@RowIndex<=@RowCount)
						BEGIN
							SELECT @GoodsBillNumberID=GoodsBillNumberID,@GoodsBillType=GoodsBillType FROM @Tmp WHERE RowIndex=@RowIndex
							
							IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.FactDepotInOut A INNER JOIN dbo.FactIndex B ON A.BillNumberID=B.BillNumberId AND b.RedWord=0 
							WHERE A.FromBillNumberID=@GoodsBillNumberID AND A.FromBillType=@GoodsBillType)		
							BEGIN
								IF @GoodsBillType IN(71,72,87,88)
								BEGIN
									UPDATE dbo.LendIndex 
									SET 
										OutFactRefState=0
									WHERE BillNumberId=@GoodsBillNumberID
								END
								ELSE
								BEGIN
									UPDATE dbo.BillIndex 
									SET 
										OutFactRefState=0
									WHERE BillNumberId=@GoodsBillNumberID
								END
							END
							SET @RowIndex=@RowIndex+1
						END
					END
			 END
			 IF @billtype = 420
			    DELETE FROM FactDepotAllot WHERE BillNumberID = @billnumberid
		
			   --SELECT @sql= 'delete  '+ @TableName + ' WHERE billnumberid='+ cast (@BILLNUMBERID as varchar(100))
			   --EXEC(@sql)
			END
			  FETCH NEXT FROM detail_cursor INTO  @TableName,@BILLNUMBERID,@billtype
		END

		CLOSE detail_cursor
		DEALLOCATE detail_cursor
		
		---自定义 
		DELETE FROM Custom_BillIndex  FROM (SELECT fi.billnumberid,fi.billtype FROM F_Split(@nBillIds,',') f inner join factindex fi on f.a=fi.billnumberid ) b WHERE BillId=b.BillNumberId AND b.BillType=Custom_BillIndex.BillType
		DELETE FROM Custom_BillDetails  FROM (SELECT fi.billnumberid,fi.billtype FROM F_Split(@nBillIds,',')f inner join factindex fi on f.a=fi.billnumberid ) b WHERE BillId=b.BillNumberId AND b.BillType=Custom_BillDetails.BillType
			
	 	--如果有审核，则删除单据审核里面的数据
		DECLARE @AuditCount INT
		SELECT @AuditCount=COUNT(AuditingBill.BillNumberID) FROM AuditingBill INNER JOIN (SELECT * FROM F_Split(@nBillIds,','))deleted ON AuditingBill.BillNumberID=deleted.a WHERE AuditingBill.BillIndexType=7
		
		IF ISNULL(@AuditCount,0) <> 0
		BEGIN
			DELETE FROM AuditingBillDetail WHERE BillNumberID IN(SELECT * FROM F_Split(@nBillIds,',')) AND BillIndexType=7
			DELETE FROM AuditingBill WHERE BillNumberID IN(SELECT * FROM F_Split(@nBillIds,',')) AND BillIndexType=7
		END
		 
		DELETE FROM dbo.Fact_InOutstocktable WHERE  billnumberid IN (SELECT * FROM F_Split(@nBillIds,','))
			
		--最后执行这步
		DELETE 
		FROM	dbo.FactIndex 
		WHERE	IfCheck = 'f' 
				AND Draft = 1  
				AND BillNumberId IN (SELECT * FROM F_Split(@nBillIds,','))
				AND BillNumberID NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 7 AND IfAudit = 1)
			
			 
		
				
				
		IF @@ROWCOUNT = 0
			RETURN -2
		ELSE
			RETURN 0
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BCommissionDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BCommissionDetailQuery]
GO









--==========================================
--作者：cqhua
--日期：2005-04-27
--描述：委托、受托代销客户,库存线性报表
--==========================================
--==========================================
--作者：Wang Wei Modify
--日期：2010-03-22
--描述：将@sortType从int=1 改成 varchar(10)='asc'
--==========================================
/* 
    修改: 舒珊
    日期: 2015-05-27
    描述: 增加查询参数@ptypecategoryid 商品类别ID 
    
    修改: 舒珊
    日期: 2015-05-31
    描述: 增加表头、表体新增的自定义字段查询
*/
CREATE	PROCEDURE [Web_BCommissionDetailQuery] 
(
	@OperatorID 	varchar(50),			--操作员ID 
	@startDate      varchar(20),           	--开始时间
	@endDate        varchar(20),			--结束时间
	@mType 			varchar(20),		    --查询的小类  WB=委托客户查询	SB=受托客户查询	WK 委托库存 SK 受托库存
	@PtypeID 		varchar(1550),			--商品的ID
	--@BtypeID 		varchar(1550),			--结算单位ID
	@sortfield 		varchar(20),			--排序字段
	@sortType 		varchar(10) ='asc',		--排序方式；"asc","desc"
	@Stypeid        varchar(1550)='00001',
	@dealbtypeid    VARCHAR(1550),           --客户的ID
	@IsReporting	INT	,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@ptypecategoryid    VARCHAR(MAX )     --商品类别ID	
)
--@encode$--
AS

SET NOCOUNT ON


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

IF @PtypeID=''
	SET @PtypeID='00000'
--IF @BtypeID=''
--	SET @BtypeID='00000'
IF @dealbtypeid=''
	SET @dealbtypeid='00000'
DECLARE @CurSonNum int
DECLARE @isSon int    -- 客户是否叶子结点 1 父结点 0 儿子结点
DECLARE @BtypeAll int -- 是否客户供货商统一 1 统一 0 不统一
DECLARE @SQL varchar(8000)
DECLARE @SortSQL varchar(600)

SET @SQL = ''
SET @SortSQL = ''

-- 由于不管职员和仓库权限，所以将二者置为全部权限(树形表，线性表没有管辖仓库、职员权限，为了两者数据一致，明细表也不管)

CREATE TABLE #Ptype (TypeID varchar(50),usercode varchar(200),fullname varchar(200),standard varchar(200),entrycode varchar(200),type varchar(200),unit1 varchar(8))
--CREATE TABLE #Btype (TypeID varchar(50),usercode varchar(200),fullname varchar(200))
CREATE TABLE #Stype (TypeID varchar(50))

IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #Ptype(typeid,UserCode,FullName,standard,entrycode,type,unit1) Select typeid,UserCode,FullName,standard,entrycode,type,unit1 FROM Ptype WHERE Typeid in ( select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a)
ELSE
	INSERT INTO #Ptype(typeid,UserCode,FullName,standard,entrycode,type,unit1) Select typeid,UserCode,FullName,standard,entrycode,type,unit1 FROM Ptype WHERE Typeid in ( select a.typeid from F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a)
	
--IF @BtypeID='' OR @BtypeID ='00000'
--	INSERT INTO #Btype(typeid,UserCode,FullName) Select typeid,UserCode,FullName FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
--ELSE
--	INSERT INTO #Btype(typeid,UserCode,FullName) Select typeid,UserCode,FullName FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a)
	
--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50))
IF @dealBtypeID='' OR @dealBtypeID ='00000'
	INSERT INTO #dealBtype(typeid) Select typeid FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
ELSE
	INSERT INTO #dealBtype(typeid) Select typeid FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@dealBtypeID,',')) b where left(a.typeid,len(b.a))=b.a)

IF EXISTS (SELECT Value FROM userconfig WHERE ConfigName='btypeAll' AND Value=1)
	SET @BtypeAll = 1
ELSE
	SET @BtypeAll = 0

IF NOT (@Stypeid='' AND @MStypeid='00000')
    INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)
  


CREATE TABLE [dbo].[#Stock] (
	[typeId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[parid] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[sonnum] [int] NOT NULL ,
	[FullName] [varchar] (66) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[UserCode] [varchar] (26) COLLATE Chinese_PRC_CI_AS NULL ,
	[deleted] [bit] NOT NULL ,
) ON [PRIMARY]

DECLARE @unitsql  VARCHAR(500)
SELECT @unitsql=dbo.F_GetPtypeUnitsAndRates('p1','1,5','1')


insert into #stock select typeid,parid,sonnum,fullname,usercode,deleted from stock 
insert into #stock (parid,typeid,usercode,fullname,deleted,sonnum) values ('00000','10000','10000','代销库',0,0)

DECLARE @TaxType char(10)
SET @TaxType='0'
IF EXISTS(SELECT * FROM UserConfig WHERE Configname='GridType' AND Value=1)
	SET @TaxType='1'


IF @mType='WB'
BEGIN

	SELECT @SQL='
		SELECT 	bil.btypeid,
				bil.billnumberid,	
				bil.billdate,
				sum(isnull(case b.billtype when ''140'' then -b.total when ''142'' then -b.total else b.total end,0)) as total,
				sum(isnull(case b.billtype when ''140'' then -b.qty when ''142'' then -b.qty else b.qty end,0)) as qty,
				b.price,
				bil.ktypeid,
				bil.billcode,
				bil.comment,
				bil.billtype,b.ptypeid,
				billname=(select top 1 billname from billname where billtype=bil.billtype),
				bil.Stypeid,
				cc.fullname AS cname,
				bil.rate AS rate,
			    b.nprice AS nprice,
			    sum(isnull(case b.billtype when ''140'' then -b.ntotal when ''142'' then -b.ntotal else b.ntotal end,0)) as ntotal,
			    b.ntaxprice AS ntaxprice,
			    b.ntaxtotal AS ntaxtotal,
			    v.fullname AS itemname,
				sum(isnull(case b.billtype when ''140'' then -b.nqty when ''142'' then -b.nqty else b.nqty end,0)) as nqty,
				pu.fullname AS munit,
				cast( sum(isnull(case b.billtype when ''140'' then -b.qty when ''142'' then -b.qty else b.qty end,0)) as NUMERIC(24, 10))/cast(pe.rate as NUMERIC(24, 10)) AS mqty,
				u1.fullname AS baseunitfullname,
				u5.fullname AS assistantfullname,
				b.goodsnumber,
				bil.dealbtypeid,
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32
		FROM    BillIndex  bil
		        INNER JOIN AC_Currency cc  ON bil.cid = cc.cid
		        INNER JOIN InOutStockTable b ON bil.billnumberid=b.billnumberid
		        left  JOIN  vWeb_ItemIDByIsCombined v on b.iscombined = v.iscombined AND b.itemid = v.id
	            left JOIN PType_Units pu on pu.unitsid = b.munitid
			    left JOIN ptype_units_ext pe on pe.unitsid = b.munitid AND b.ptypeid = pe.ptypeid
			   
		        --INNER JOIN #btype bt ON bil.btypeid =bt.typeid 
		        INNER JOIN #ptype p  ON b.ptypeid=p.typeid
		        inner JOIN #DealBtype db ON db.typeid = bil.btypeid 	
		        inner join ptype p1 on b.ptypeid=p1.typeid
		        
		         left join Custom_BillIndex csindex on bil.billnumberid=csindex.BillId and bil.billtype=csindex.billtype
left join Custom_BillDetails csdetail on bil.billnumberid=csdetail.BillId and bil.billtype=csdetail.billtype AND b.id=csdetail.Detailid
		'+@unitsql	
		        
IF NOT (@Stypeid='' AND @MStypeid='00000')	        
	SELECT @SQL=@SQL+' INNER JOIN #stype s  ON bil.stypeid=s.typeid		 '
		        
SELECT @SQL=@SQL+' WHERE 	bil.draft=0
							AND bil.RedWord=0
							AND bil.ifcheck=''t''
							AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
							AND bil.billtype in (140,141,142,143) 
							AND 
								(
									(b.billtype=140 AND b.ktypeid<>''10000'')  OR
					  				(b.billtype=141 AND b.ktypeid=''10000'' )  OR
									(b.billtype=142 AND b.ktypeid<>''10000'')  OR
									(b.billtype=143 AND b.ktypeid=''10000'' )
								)'
		
		SELECT @SQL=@SQL+' Group By bil.btypeid,bil.billnumberid,bil.billdate,bil.ktypeid,bil.billcode,b.price,bil.comment,bil.billtype,b.qty,b.ptypeid,bil.Stypeid,cc.fullname,
				bil.rate,
				b.qty,
			    b.nprice,
			    b.ntotal,
			    b.ntaxprice,
			    b.ntaxtotal,
			    v.fullname,
				b.nqty,
				pu.fullname,
				pe.rate,
				u1.fullname,
				u5.fullname,
				b.goodsnumber,
				bil.dealbtypeid ,
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32'
		
		--=======================================构造排序字段
		SELECT @SortSQL=''
		IF @sortfield='BillDate'   SELECT @SortSQL=' Order By  Y.billdate '
		IF @sortfield='BillCode'   SELECT @SortSQL=' Order By  Y.BillCode '
		IF @sortfield='Qty'  	  SELECT @SortSQL=' Order By  Y.Qty '
		IF @sortfield='BillType'   SELECT @SortSQL=' Order By  Y.BillType '
		IF @SortSQL=''
			SELECT @SortSQL = ' Order By  Y.billdate '

		SELECT @SortSQL = @SortSQL +@sortType

		SET @SQL = 'SELECT Y.* FROM ('+@SQL+') Y ' --+ @SortSQL

END
IF @mType='SB'  -- SB 委托客户统计
BEGIN
	SELECT @CurSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID	
	SELECT @SQL='
			SELECT 	bil.btypeid,
					bil.billnumberid,
					bil.billdate,
					sum(isnull(b.total,0)) as total,
					sum(isnull(b.qty,0)) as qty,
					b.price,
					bil.ktypeid,
					bil.billcode,
					bil.comment,
					bil.billtype,b.ptypeid,
					billname=(select top 1 billname from billname where billtype=bil.billtype),
					bil.Stypeid,
					cc.fullname AS cname,
				    bil.rate AS rate,
					b.nprice AS nprice,
					sum(isnull(b.ntotal,0)) as ntotal,
					b.ntaxprice AS ntaxprice,
					b.ntaxtotal AS ntaxtotal,
					v.fullname AS itemname,
					sum(isnull(b.nqty,0)) as nqty,
					pu.fullname AS munit,
				CAST(	sum(isnull(b.qty,0)) AS NUMERIC(24, 10))/ CAST(pe.rate AS NUMERIC(24, 10)) AS mqty,
					u1.fullname AS baseunitfullname,
					u5.fullname AS assistantfullname,
					b.goodsnumber,
					bil.dealbtypeid,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32
			FROM    BillIndex  bil 
					INNER JOIN InOutStockTable b ON bil.billnumberid=b.billnumberid
					INNER JOIN AC_Currency cc  ON bil.cid = cc.cid
					left  JOIN  vWeb_ItemIDByIsCombined v on b.iscombined = v.iscombined AND b.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = b.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = b.munitid AND b.ptypeid = pe.ptypeid
					--INNER JOIN #btype bt ON bil.btypeid =bt.typeid 
					INNER JOIN #ptype p  ON b.ptypeid=p.typeid
					INNER JOIN #DealBtype db ON db.typeid = bil.btypeid	     
					inner join ptype p1 on b.ptypeid=p1.typeid
					   left join Custom_BillIndex csindex on bil.billnumberid=csindex.BillId and bil.billtype=csindex.billtype
left join Custom_BillDetails csdetail on bil.billnumberid=csdetail.BillId and bil.billtype=csdetail.billtype AND b.id=csdetail.Detailid
		'+@unitsql	
IF NOT (@Stypeid='' AND @MStypeid='00000')
 SELECT @SQL=@SQL+' INNER JOIN #stype s  ON bil.stypeid=s.typeid '
					
 SELECT @SQL=@SQL+' WHERE 	bil.draft=0
					AND bil.RedWord=0
					AND bil.ifcheck=''t''
					AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
					AND bil.billtype in (144,145,146,147) 
					AND 
					(
						(b.billtype=144 AND b.ktypeid<>''10000'')  OR
					  	(b.billtype=145 AND b.ktypeid=''10000'' )  OR
						(b.billtype=146 AND b.ktypeid<>''10000'')  OR
						(b.billtype=147 AND b.ktypeid=''10000'')
					) '
			SELECT @SQL=@SQL+' Group By bil.btypeid,bil.billnumberid,bil.billdate,bil.ktypeid,bil.billcode,bil.comment,b.price,bil.billtype,b.ptypeid,b.qty,bil.Stypeid,cc.fullname,bil.rate,b.qty,
			    b.nprice,
			    b.ntotal,
			    b.ntaxprice,
			    b.ntaxtotal,
			    v.fullname,
				b.nqty,
				pu.fullname,
				pe.rate,
				u1.fullname,
				u5.fullname,
				b.goodsnumber,
				bil.dealbtypeid, 
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32'
	
			--=======================================构造排序字段
			SELECT @SortSQL=''
			IF @sortfield='BillDate'   SELECT @SortSQL=' Order By  Y.billdate '
			IF @sortfield='BillCode'   SELECT @SortSQL=' Order By  Y.BillCode '
			IF @sortfield='Qty'  	  SELECT @SortSQL=' Order By  Y.Qty '
			IF @sortfield='BillType'   SELECT @SortSQL=' Order By  Y.BillType '
			IF @SortSQL=''
				SELECT @SortSQL = ' Order By  Y.billdate '

			SELECT @SortSQL = @SortSQL +@sortType

			SET @SQL = 'SELECT Y.* FROM ('+@SQL+') Y ' --+ @SortSQL
					

END
IF @mType='WK' 
BEGIN
	SELECT @SQL='
		  SELECT 	
				bil.billdate,
				b.id AS CustomdetailID,
				bil.billcode,
			    p.typeid as ptypeid,
                p.usercode as pusercode,
                p.fullname as pfullname,
				bil.btypeid,
				sum(isnull(case b.billtype when ''140'' then -b.qty when ''142'' then -b.qty else b.qty end,0)) as qty,
				sum(isnull( b.costprice,0)) as costprice,
				sum(isnull(case b.Billtype when ''140'' then -b.costtotal when ''142'' then -b.costtotal else b.costtotal end,0)) as costtotal,
				bil.billtype,
				bil.billnumberid,
				sum(isnull(case b.Billtype when ''140'' then -b.total when ''142'' then -b.total else b.total end,0)) as total,
				bil.checke,
				e.fullname as efullname,							
				bil.totalmoney,
				bil.comment,
				b.tax,
				taxtotal =sum(Convert( NUMERIC(24, 10) ,case b.Billtype when ''140'' then -b.taxtotal when ''142'' then -b.taxtotal else b.taxtotal end)),
				CASE Bil.BillType
					WHEN 141 THEN ''10000''
					ELSE bil.ktypeid
				END AS KTypeID,
				bil.etypeid ,
				b.price AS jsprice ,
				
				k.UserCode as KUserCode,
				k.fullname as kFullname,
				ee.Fullname as CheckeName,
				billname=(select top 1 billname from billname where billtype=bil.billtype),
				bil.Stypeid,
				cc.fullname AS cname,
				bil.rate AS rate,
			    b.nprice AS nprice,
			    b.taxprice,
				sum(isnull(case b.Billtype when ''140'' then -b.ntotal when ''142'' then -b.ntotal else b.ntotal end,0)) as ntotal,
				b.ntaxprice ,
			
				ntaxtotal =sum(Convert( NUMERIC(24, 10) ,case b.Billtype when ''140'' then -b.ntaxtotal when ''142'' then -b.ntaxtotal else b.ntaxtotal end)),
				v.fullname AS itemname,
				sum(isnull(case b.billtype when ''140'' then -b.nqty when ''142'' then -b.nqty else b.nqty end,0)) as nqty,
				pu.fullname AS munit,
			  CAST(   sum(isnull(case b.billtype when ''140'' then -b.qty when ''142'' then -b.qty else b.qty end,0)) AS NUMERIC(24, 10)) /CAST( pe.rate AS NUMERIC(24, 10)) as mqty,
				u1.fullname AS baseunitfullname,
				u5.fullname AS assistantfullname,
				b.goodsnumber,
				bil.dealbtypeid,
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32
		  FROM  InOutStockTable b
				INNER JOIN billindex bil ON bil.billnumberid=b.billnumberid
				INNER JOIN AC_Currency cc  ON bil.cid = cc.cid
				left  JOIN  vWeb_ItemIDByIsCombined v on b.iscombined = v.iscombined AND b.itemid = v.id
				left JOIN PType_Units pu on pu.unitsid = b.munitid
				left JOIN ptype_units_ext pe on pe.unitsid = b.munitid AND b.ptypeid = pe.ptypeid
				INNER JOIN #ptype p ON b.ptypeid=p.typeid
				--INNER JOIN #btype bt ON bil.btypeid=bt.typeid
				INNER JOIN employee e ON bil.etypeId=e.TypeID	
				INNER JOIN employee ee ON bil.checke=ee.TypeID
				INNER JOIN #stock k	 ON bil.ktypeID =k.typeID
				inner JOIN #DealBtype db ON db.typeid = bil.btypeid	    
				inner join ptype p1 on b.ptypeid=p1.typeid
				  left join Custom_BillIndex csindex on bil.billnumberid=csindex.BillId and bil.billtype=csindex.billtype
left join Custom_BillDetails csdetail on bil.billnumberid=csdetail.BillId and bil.billtype=csdetail.billtype AND b.id=csdetail.Detailid
		'+@unitsql	
IF NOT (@Stypeid='' AND @MStypeid='00000')      
	SELECT @SQL=@SQL+' INNER JOIN #stype s  ON bil.stypeid=s.typeid '
								
 SELECT @SQL=@SQL+' WHERE bil.draft=0
				AND bil.RedWord=0
				AND bil.ifcheck=''t''
				AND 
					(
						(b.billtype=140 AND b.ktypeid<>''10000'')  OR
					  	(b.billtype=141 AND b.ktypeid=''10000'' )  OR
						(b.billtype=142 AND b.ktypeid<>''10000'')  OR
						(b.billtype=143 AND b.ktypeid=''10000'')
					)'
				
				SELECT @SQL=@SQL+' AND bil.billtype in (140,141,142,143)'
				
				SELECT @SQL=@SQL + ' 
				AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)

		SELECT @SQL=@SQL+'GROUP BY  
					bil.billdate,
					bil.billcode,
					b.id,
                    p.usercode,
                    p.fullname,
					p.typeid,
				   bil.btypeid,
					bil.billtype,
					bil.billnumberid,
					bil.checke,
					e.fullname,
					ee.fullname,
					k.fullname,
					k.UserCode,									
					bil.totalmoney,
					bil.comment,
					b.tax,
					b.qty,
					bil.ktypeid,
					bil.etypeid,
					b.price,
					bil.Stypeid,
					cc.fullname,
					bil.rate,
					b.nprice,
					b.ntotal,
					b.ntaxprice,
					b.taxprice,
					b.ntaxtotal,
					v.fullname,
					b.nqty,
					pu.fullname,
					pe.rate,
					u1.fullname,
					u5.fullname,
					b.goodsnumber,
					bil.dealbtypeid,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32 '	
			--=======================================构造排序字段
			SELECT @SortSQL=''
			IF @sortfield='BillDate'   SELECT @SortSQL=' Order By  Y.billdate '
			IF @sortfield='BillCode'   SELECT @SortSQL=' Order By  Y.BillCode '
			IF @sortfield='EtypeID'    SELECT @SortSQL=' Order By  Y.Efullname '
			IF @sortfield='PUserCode'  SELECT @SortSQL=' Order By  Y.PUserCode '
			IF @sortfield='PFullName'  SELECT @SortSQL=' Order By  Y.PFullName '
			IF @sortfield='Qty'  	  SELECT @SortSQL=' Order By  Y.Qty '
			IF @sortfield='Checke'     SELECT @SortSQL=' Order By  Y.CheckeName '
			IF @sortfield='BillType'   SELECT @SortSQL=' Order By  Y.BillType '
			IF @sortfield='KtypeID'    SELECT @SortSQL=' Order By  Y.KTypeId '
			IF @sortfield='UserCode'   SELECT @SortSQL=' Order By  Y.billdate '
			IF @sortfield='CostTotal'  SELECT @SortSQL=' Order By  Y.CostTotal '
			IF @SortSQL=''
				SELECT @SortSQL = ' Order By  Y.billdate '

			SELECT @SortSQL = @SortSQL +@sortType

			SET @SQL = 'SELECT Y.*,
							--jsprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.Total/Y.qty end),
						--	taxprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.TaxTotal/Y.qty end),
							--nprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.nTotal/Y.qty end),
						--	ntaxprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.nTaxTotal/Y.qty end),
							taxge=Convert( NUMERIC(24, 10) ,(Y.taxtotal-Y.total)),
						--	costprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.CostTotal/Y.qty end),
							maoli =Convert( NUMERIC(24, 10) ,case y.Billtype when ''141'' then abs(y.total)-abs(y.Costtotal) else  Y.Total-Y.CostTotal end),
						
		maolilu =case when Y.total =0 then 0 else CAST( (Y.Total-Y.CostTotal)AS NUMERIC(24, 10))/CAST( Y.total AS NUMERIC(24, 10))*100 end					
						FROM ('+@SQL+') Y ' --+ @SortSQL

END
IF @mType='SK' 
BEGIN
	SELECT @SQL='
	  SELECT	bil.billdate,
				bil.billcode,
                p.typeid as ptypeid,
                p.UserCode as pusercode,
                p.fullname as pfullname,
				bil.btypeid,
				sum(isnull(b.qty,0)) as qty,
				b.price AS jsprice,
				sum(isnull(b.costprice,0)) as costprice,
				sum(isnull(b.costtotal,0)) as costtotal,
				bil.billtype,
				bil.billnumberid,
				sum(isnull(b.total,0)) as total,
				bil.checke,
				e.fullname as efullname,
				bil.totalmoney,
				bil.comment,
				b.tax,
				taxtotal =sum(Convert( NUMERIC(24, 10) ,b.taxtotal)),
				CASE Bil.BillType
					WHEN 145 THEN ''10000''
					ELSE bil.ktypeid
				END AS KTypeId,				bil.etypeid,
				k.UserCode as KUserCode,
				k.fullname as kFullname,
				ee.Fullname as CheckeName,
				billname=(select top 1 billname from billname where billtype=bil.billtype),
				bil.Stypeid,
				cc.fullname AS cname,
				bil.rate AS rate,
			    b.nprice AS nprice,
				sum(isnull(b.ntotal,0)) as ntotal,
				b.TaxPrice,
				b.ntaxprice AS ntaxprice,
	            ntaxtotal =sum(Convert( NUMERIC(24, 10) ,b.ntaxtotal)),
				v.fullname AS itemname,
				sum(isnull(b.nqty,0)) as nqty,
				pu.fullname AS munit,
			   CAST(	sum(isnull(b.qty,0)) AS NUMERIC(24, 10))/CAST( pe.rate AS NUMERIC(24, 10)) as mqty,
				u1.fullname AS baseunitfullname,
				u5.fullname AS assistantfullname,
				b.goodsnumber,
				bil.dealbtypeid, 
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32
	  FROM  InOutStockTable b
			INNER JOIN billindex bil ON bil.billnumberid=b.billnumberid
			INNER JOIN AC_Currency cc  ON bil.cid = cc.cid
			left  JOIN  vWeb_ItemIDByIsCombined v on b.iscombined = v.iscombined AND b.itemid = v.id
		    left JOIN PType_Units pu on pu.unitsid = b.munitid
		    left JOIN ptype_units_ext pe on pe.unitsid = b.munitid AND b.ptypeid = pe.ptypeid
			INNER JOIN #ptype p ON b.ptypeid=p.typeid
			--INNER JOIN #btype bt ON bil.btypeid=bt.typeid
			INNER JOIN employee e ON bil.etypeId=e.TypeID	
			INNER JOIN employee ee ON bil.checke=ee.TypeID
			INNER JOIN #stock k	ON 	bil.ktypeID =k.typeID 
			INNER  JOIN #DealBtype db ON db.typeid = bil.btypeid     
			inner join ptype p1 on b.ptypeid=p1.typeid
			 left join Custom_BillIndex csindex on bil.billnumberid=csindex.BillId and bil.billtype=csindex.billtype
left join Custom_BillDetails csdetail on bil.billnumberid=csdetail.BillId and bil.billtype=csdetail.billtype AND b.id=csdetail.Detailid
		'+@unitsql	
IF NOT (@Stypeid='' AND @MStypeid='00000')
	SELECT @SQL=@SQL+' INNER JOIN #stype s  ON bil.stypeid=s.typeid '
							
SELECT @SQL=@SQL+' WHERE bil.draft=0
			AND bil.RedWord=0
			AND bil.ifcheck=''t''
			'
			SELECT @SQL=@SQL+' AND bil.billtype in (144,145,146,147)'
			SELECT @SQL=@SQL+'AND b.ktypeid='+char(39)+'10000'+char(39)+'
			AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)

	
	SELECT @SQL=@SQL+' GROUP BY  
				bil.billdate,
				bil.billcode,
                p.typeid,
                p.usercode,
                p.fullname,
				bil.btypeid,
				bil.billtype,
				bil.billnumberid,
				bil.checke,
				e.fullname,
				ee.FullName,
				k.UserCode,								
				bil.totalmoney,
				bil.comment,
				b.tax,
				b.price,
				bil.ktypeid,
				k.fullname,
				bil.etypeid,
				bil.Stypeid,
				bil.rate,
				b.nprice,
				b.ntotal,
				b.ntaxprice,
				b.taxprice,
				b.ntaxtotal,
				v.fullname,
				b.nqty,
				pu.fullname,
				pe.rate,
				u1.fullname,
				u5.fullname,
				b.goodsnumber,
				cc.fullname,
				b.qty,
				bil.dealbtypeid, 
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32 '
			--=======================================构造排序字段
			SELECT @SortSQL=''
			IF @sortfield='BillDate'   SELECT @SortSQL=' Order By  Y.billdate '
			IF @sortfield='BillCode'   SELECT @SortSQL=' Order By  Y.BillCode '
			IF @sortfield='EtypeID'    SELECT @SortSQL=' Order By  Y.EFullName '
			IF @sortfield='PUserCode'  SELECT @SortSQL=' Order By  Y.Pusercode '
			IF @sortfield='PFullName'  SELECT @SortSQL=' Order By  Y.PFullname '
			IF @sortfield='Qty'  	  SELECT @SortSQL=' Order By  Y.Qty '
			IF @sortfield='Checke'     SELECT @SortSQL=' Order By  Y.CheckeName '
			IF @sortfield='BillType'   SELECT @SortSQL=' Order By  Y.BillType '
			IF @sortfield='KtypeID'    SELECT @SortSQL=' Order By  Y.KTypeId '
			IF @sortfield='UserCode'   SELECT @SortSQL=' Order By  Y.billdate '
			IF @sortfield='CostTotal'  SELECT @SortSQL=' Order By  Y.CostTotal '
            IF @SortSQL=''
				SELECT @SortSQL = ' Order By  Y.billdate '
		
			SELECT @SortSQL = @SortSQL + @sortType

			SET @SQL = 'SELECT Y.*,
							--jsprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.Total/Y.qty end),
						--	taxprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.TaxTotal/Y.qty end),
						--	nprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.nTotal/Y.qty end),
							--ntaxprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.nTaxTotal/Y.qty end),
							taxge=Convert( NUMERIC(24, 10) ,(Y.taxtotal-Y.total)),
						--	costprice=Convert( NUMERIC(24, 10) ,case when Y.qty=0 then 0 else Y.CostTotal/Y.qty end),
							maoli =Convert( NUMERIC(24, 10) ,Y.Total-Y.CostTotal),
							maolilu =case when Y.total =0 then 0 else CAST( (Y.Total-Y.CostTotal)AS NUMERIC(24, 10))/CAST( Y.total AS NUMERIC(24, 10))*100 end
						FROM ('+@SQL+') Y ' --+ @SortSQL
					


END



--EXEC (@SQL)


----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
	SET @SQL = @SQL + @SortSQL
	PRINT @SQL
	EXEC(@SQL)
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
--	CREATE TABLE #tmp_result
--	(
--		billnumberid VARCHAR(100),
--		billtype     VARCHAR(100),
--		Costom1		VARCHAR(max),
--		Costom2		VARCHAR(max),
--		Costom3		VARCHAR(max),
--		Costom4		VARCHAR(max),
--		Costom5		VARCHAR(max),
--		Costom6		VARCHAR(max),
--		Costom7		VARCHAR(max),
--		Costom8		VARCHAR(max),
--		Costom9		VARCHAR(max),
--		Costom10	VARCHAR(max),
--		Costom11	VARCHAR(max),
--		Costom12	VARCHAR(max),
--		Costom13	VARCHAR(max),
--		Costom14	VARCHAR(max),
--		Costom15	VARCHAR(max),
--		Costom16	VARCHAR(max)
--	)
--	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS Y ' + @SortSQL +
--			  '
--			   DECLARE @p1 dbo.TBType_SelfType  
--			   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
--			   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 
			   
--				--显示最终结果
--				SELECT DISTINCT Y.*,
--						  b.Costom1,
--						  b.Costom2,
--						  b.Costom3,
--						  b.Costom4,
--						  b.Costom5,
--						  b.Costom6,
--						  b.Costom7,
--						  b.Costom8,
--						  b.Costom9,
--						  b.Costom10,
--						  b.Costom11,
--						  b.Costom12,
--						  b.Costom13,
--						  b.Costom14,
--						  b.Costom15,
--						  b.Costom16 
--						  FROM #temp1 Y 
--						  LEFT join #tmp_result b on Y.billnumberid=b.billnumberid and Y.billtype=b.billtype ' 
--						  + @SortSQL +
						  
--			  ' DROP TABLE #temp1,#tmp_result
--			  '
--	EXEC (@SQL)
--END
----------------------------------------------------------

DROP TABLE #stock,#Stype,#Ptype,#dealbtype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--SELECT * FROM dbo.sqlLog ORDER BY id DESC
--exec Web_BCommissionDetailQuery @OperatorID='00001',@startDate='2012-06-01',@endDate='2012-06-26',@mType='SK',@PtypeID='00009',@BtypeID='00001',@sortfield='qty',@sortType='asc',@Stypeid='00001'



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BCommissionLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BCommissionLineQuery]
GO





--==========================================
--作者：cqhua
--日期：2005-04-27
--描述：委托、受托代销客户,库存线性报表
--==========================================
--==========================================
--日期：2010-03-22  Wang Wei 
--描述：将@sortType后面的类型从[int]改成varchar
--==========================================
--==========================================
--日期：2016-05-26  舒珊
--描述：添加商品类别筛选
--==========================================
CREATE	PROCEDURE [Web_BCommissionLineQuery] 
(
	@OperatorID varchar(50),	--操作员ID 
	@mType varchar(20),		    --查询的小类  WB=委托客户查询	SB=受托客户查询	WK 委托库存 SK 受托库存
	@PtypeID varchar(1550),		--商品的ID
--	@BtypeID varchar(1550),		--结算单位的ID
	@dealbtypeid VARCHAR(1550),		--往来单位
	@sortfield varchar(20),		--排序字段
	@sortType varchar(10) ='asc' ,	--排序方式；"asc","desc"
	@showZero int	,		    --1=显示库存为0    0=不显示库存为0
    @BtypeAll int=0, -- 是否客户供货商统一 1 统一 0 不统一
    @stypeid  varchar(1550),		--商品的ID
    @ptypecategoryid VARCHAR(MAX)  --商品类别ID
)
--@encode$--
AS

SET NOCOUNT ON


DECLARE @CurSonNum int
DECLARE @isSon int    -- 客户是否叶子结点 1 父结点 0 儿子结点
--DECLARE @BtypeAll int -- 是否客户供货商统一 1 统一 0 不统一
DECLARE @SQL varchar(8000)
DECLARE @SortSQL varchar(600)

SET @SQL = ''
SET @SortSQL = ''

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #Ptype (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
--CREATE TABLE #Btype (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)

CREATE TABLE #dealBtype (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #Stype (TypeID varchar(50))


IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #Ptype(typeid,UserCode,FullName,Sonnum) 
	Select	typeid,UserCode,FullName,Sonnum 
	FROM	Ptype 
	WHERE	Typeid in ( select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a) 
			AND IsService=0
			AND iscombinationproduct = 0
ELSE
	INSERT INTO #Ptype(typeid,UserCode,FullName,Sonnum) 
	Select	typeid,UserCode,FullName,Sonnum 
	FROM	Ptype 
	WHERE	Typeid in ( select a.typeid from  F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, 
			(select * from  dbo.f_split(@PtypeID,',')) b 
	where	left(a.typeid,len(b.a))=b.a)
			AND IsService=0
			AND iscombinationproduct = 0


IF @dealbtypeid='' OR @dealbtypeid ='00000'
begin
    if(@BtypeAll=1)
	   INSERT INTO #dealBtype(typeid,UserCode,FullName,Sonnum) Select typeid,UserCode,FullName,Sonnum FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
    else
    begin
       if (@mType='WB' OR @mType='WK')
           INSERT INTO #dealBtype(typeid,UserCode,FullName,Sonnum) Select typeid,UserCode,FullName,Sonnum FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID ) a  where typeid LIKE '00001%' )
       else
           INSERT INTO #dealBtype(typeid,UserCode,FullName,Sonnum) Select typeid,UserCode,FullName,Sonnum FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID)  a  where typeid LIKE '00002%' )
    end
end
ELSE
	INSERT INTO #dealBtype(typeid,UserCode,FullName,Sonnum) Select typeid,UserCode,FullName,Sonnum FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@dealbtypeid,',')) b where left(a.typeid,len(b.a))=b.a)

	

IF NOT(@stypeid='' AND @MStypeid='00000')
    INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

IF @mType='WB'
BEGIN
	SELECT @SQL='
			SELECT  b.usercode,b.fullname,b.sonnum,b.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.total,0)) as total,sum(isnull(a.costtotal,0)) as costtotal	
			FROM #dealBtype b
				LEFT JOIN
					(
						SELECT c.qty,c.costtotal,c.total,c.ptypeid,c.btypeid
						FROM  commissionstock c '
						
	--IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')				
	--	SELECT @SQL=@SQL+' INNER JOIN #btype b ON c.btypeid =b.typeid '
		
	IF NOT(@dealBtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')				
		SELECT @SQL=@SQL+' INNER JOIN #dealbtype b1 ON c.btypeid =b1.typeid '	
	
	IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')
		SELECT @SQL=@SQL+' INNER JOIN #Ptype p ON c.ptypeid=p.typeid  '
	
	IF NOT(@stypeid='' AND @MStypeid='00000')
		SELECT @SQL=@SQL+' INNER JOIN #stype s ON c.stypeid=s.typeid  '
	
	SELECT @SQL=@SQL+' WHERE c.Type in (140,141,142)	
					)a
			ON   b.typeid=a.btypeid'
	IF @showZero=0 
		SELECT @SQL=@SQL+' WHERE qty<>0'
	SELECT @SQL=@SQL+' GROUP BY b.usercode,b.fullname,b.sonnum,b.typeid'


	IF @sortfield ='qty'
			SELECT @SortSQL=' Order By Qty '					
	IF @sortfield ='CostTotal'
		SELECT @SortSQL=' Order By Total '	
	IF @SortSQL=''
		SELECT @SortSQL=@SortSQL+' Order By b.UserCode'

	SELECT @SortSQL=@SortSQL +@sortType

	SELECT @SQL = @SQL + @SortSQL


END
IF @mType='SB'  -- SB 委托客户统计
BEGIN
	SELECT @SQL='
			SELECT  b.usercode,b.fullname,b.sonnum,b.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.total,0)) as total,sum(isnull(a.costtotal,0)) as costtotal	
			FROM #dealBtype b
				LEFT JOIN
					(
						SELECT c.qty,c.costtotal,c.total,c.ptypeid,c.btypeid
						FROM  commissionstock c '
						
  --   IF NOT (@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
		--SELECT @SQL=@SQL+' INNER JOIN #btype b ON c.btypeid =b.typeid '
	     IF NOT (@dealBtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
		SELECT @SQL=@SQL+' INNER JOIN #dealbtype b1 ON c.btypeid =b1.typeid '	
	 
	 IF NOT (@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')
		SELECT @SQL=@SQL+' INNER JOIN #Ptype p ON c.ptypeid=p.typeid '
	 
	 IF NOT (@stypeid='' AND @MStypeid='00000')
		SELECT @SQL=@SQL+' INNER JOIN #Stype S ON c.stypeid=s.typeid '
	  
	 SELECT @SQL=@SQL+' WHERE c.Type in (144,145,146)	
					)a
			ON   b.typeid=a.btypeid'
	IF @showZero=0 
		SELECT @SQL=@SQL+' WHERE qty<>0'
	SELECT @SQL=@SQL+' GROUP BY b.usercode,b.fullname,b.sonnum,b.typeid'
	
	IF @sortfield ='qty'
			SELECT @SortSQL=' Order By Qty '					
	IF @sortfield ='CostTotal'
		SELECT @SortSQL=' Order By Total '	
	IF @SortSQL=''
		SELECT @SortSQL=@SortSQL+' Order By b.UserCode'

	SELECT @SortSQL=@SortSQL +@sortType

	SELECT @SQL = @SQL + @SortSQL

END
IF @mType='WK' 
BEGIN
	SELECT @SQL='
				SELECT  p.typeid,p.usercode,p.fullname,p.sonnum,
				sum(isnull(b.qty,0)) as qty,
				sum(isnull(b.total,0)) as total,
				sum(isnull(b.costtotal,0)) as costtotal ,
				price =case when sum(isnull(b.qty,0)) =0 then 0 else cast( sum(isnull(b.total,0)) as NUMERIC(24, 10))/ cast(sum(isnull(b.qty,0)) as NUMERIC(24, 10)) end,
				costprice =case when sum(isnull(b.qty,0)) =0 then 0 else cast( sum(isnull(b.costtotal,0)) as NUMERIC(24, 10))/cast( sum(isnull(b.qty,0)) as NUMERIC(24, 10)) end
				FROM #ptype p
					LEFT JOIN
					(
						SELECT	c.qty,								c.ptypeid,
								c.total,
								c.costtotal
						FROM 	commissionstock c '
						
	 --IF NOT (@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')					
		--SELECT @SQL=@SQL+' INNER JOIN #btype b ON c.btypeid =b.typeid '
		
	IF NOT (@dealBtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')					
		SELECT @SQL=@SQL+' INNER JOIN #dealbtype b1 ON c.btypeid =b1.typeid '	
		
	 IF NOT (@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='' )				
		SELECT @SQL=@SQL+' INNER JOIN #Ptype p ON c.ptypeid=p.typeid '
		
	 IF NOT (@stypeid='' AND @MStypeid='00000' )				
		SELECT @SQL=@SQL+' INNER JOIN #Stype s ON c.stypeid=s.typeid '				
						
	 SELECT @SQL=@SQL+' WHERE c.type =140
				)b
				ON p.typeid=b.ptypeid '

		IF @showZero=0 
			SELECT @SQL=@SQL+' WHERE qty<>0'
		SELECT @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.fullname,p.sonnum'
	
		
		--=======================================构造排序字段
		IF @sortfield ='qty'
				SELECT @SortSQL=' Order By Qty '					
		IF @sortfield ='CostTotal'
			SELECT @SortSQL=' Order By Total '	
		IF @SortSQL=''
			SELECT @SortSQL=@SortSQL+' Order By p.UserCode'

		SELECT @SortSQL=@SortSQL +@sortType

		SELECT @SQL = @SQL + @SortSQL

END
IF @mType='SK' 
BEGIN
	SELECT @SQL='
			SELECT  p.typeid,p.usercode,p.fullname,p.sonnum,
				sum(isnull(b.qty,0)) as qty,
				sum(isnull(b.total,0)) as total,
				sum(isnull(b.costtotal,0)) as costtotal,
				price =case when sum(isnull(b.qty,0)) =0 then 0 else cast( sum(isnull(b.total,0)) as NUMERIC(24, 10))/ cast(sum(isnull(b.qty,0)) as NUMERIC(24, 10)) end,
				costprice =case when sum(isnull(b.qty,0)) =0 then 0 else cast( sum(isnull(b.costtotal,0)) as NUMERIC(24, 10))/cast( sum(isnull(b.qty,0)) as NUMERIC(24, 10)) end
			FROM #ptype p
				LEFT JOIN
				(
					SELECT	c.qty,
							c.ptypeid,
							c.total,
							c.costtotal
					FROM 	commissionstock  c '
					
 --IF NOT (@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
	--SELECT @SQL=@SQL+' INNER JOIN #btype b ON c.btypeid =b.typeid '
	
 IF NOT (@dealBtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
	SELECT @SQL=@SQL+' INNER JOIN #dealbtype b1 ON c.btypeid =b1.typeid '	
 
 IF NOT (@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')
	SELECT @SQL=@SQL+' INNER JOIN #Ptype p ON c.ptypeid=p.typeid '
 
 IF NOT (@stypeid='' AND @MStypeid='00000')
	SELECT @SQL=@SQL+' INNER JOIN #Stype s ON c.stypeid=s.typeid '
 
 SELECT @SQL=@SQL+' WHERE  type in (144,145,146) AND qty>=0					               
				)b		               
			ON p.typeid=b.ptypeid
			'
	IF @showZero=0 
		SELECT @SQL=@SQL+' WHERE qty<>0'
	SELECT @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.fullname,p.sonnum'

	--=======================================构造排序字段
	IF @sortfield ='qty'
			SELECT @SortSQL=' Order By Qty '					
	IF @sortfield ='CostTotal'
		SELECT @SortSQL=' Order By Total '	
	IF @SortSQL=''
		SELECT @SortSQL=@SortSQL+' Order By p.UserCode'

	SELECT @SortSQL=@SortSQL +@sortType

	SELECT @SQL = @SQL + @SortSQL	
END


--PRINT @SQL 
EXEC (@SQL)

DROP TABLE #Ptype
--DROP TABLE #Btype
DROP TABLE #dealbtype





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BCommissionListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BCommissionListQuery]
GO



--==========================================
--作者：cqhua
--日期：2005-04-27
--描述：委托、受托代销客户,库存树形报表
--==========================================
--==========================================
--修改: 魏伟
--日期: 2015-05-23
--描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
--==========================================
CREATE                                                           PROCEDURE [Web_BCommissionListQuery] 
(
	@OperatorID varchar(50),	--操作员ID 
	@mType varchar(20),		    --查询的小类  WB=委托客户查询	SB=受托客户查询	WK 委托库存 SK 受托库存
	@PtypeID varchar(1550),		--商品的ID
	--@BtypeID varchar(1550),		--结算单位的ID
	@dealbtypeid VARCHAR(200),   --单位单位
	@stypeid varchar(1550),  	--分支机构的ID
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
	 
)
--@encode$--
AS

SET NOCOUNT ON


DECLARE @CurSonNum int
DECLARE @isSon int    -- 客户是否叶子结点 1 父结点 0 儿子结点
DECLARE @BtypeAll int -- 是否客户供货商统一 1 统一 0 不统一
DECLARE @SQL varchar(8000)

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #Ptype (TypeID varchar(50))
--CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #dealBtype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum INT,sortid INT)


IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #Ptype(typeid) 
	select a.typeid 
	from F_LinePC(@OperatorID,@ptypecategoryid) a 
	INNER JOIN dbo.ptype b ON a.TypeId = b.typeId 
	WHERE	 b.iscombinationproduct = 0
			AND b.IsService =0
ELSE
	INSERT INTO #Ptype(typeid) select a.typeid from F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a,dbo.ptype c
	where	a.TypeId=c.typeId  
			AND c.iscombinationproduct = 0
			AND c.IsService =0

IF @dealBtypeID='' OR @dealBtypeID ='00000'
	INSERT INTO #dealBtype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #dealBtype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@dealBtypeID,',')) b where left(a.typeid,len(b.a))=b.a
	

IF NOT (@STypeId = '' AND @MStypeid = '00000')
	INSERT INTO #Stype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

DECLARE @sonnum int 
SET @sonnum =0

IF @mType='SK' OR @mType='WK'
BEGIN
	SELECT @sonnum = sonnum FROM Ptype WHERE Typeid =case when @PtypeID='' then '00000' else @PtypeID end
	IF @sonnum =0 
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sortid) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.SortID 
		FROM Ptype p									  
		,#Ptype a where p.typeid=a.typeid --AND p.IsService=0
	ELSE
		IF @PtypeID ='' OR @PtypeID='00000'
				INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sortid) 
				SELECT DISTINCT p.typeid,p.usercode,p.fullname,p.sonnum,p.SortID 
				FROM Ptype p
				,dbo.F_TreeP(@OperatorID) A,
				 #Ptype pt   
				where P.parid=(case  when @PtypeID='' then '00000' else @PtypeID end)  AND p.typeid=a.typeid --AND p.IsService=0
			    AND pt.typeid LIKE p.typeid + '%'
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sortid) 
			SELECT DISTINCT p.typeid,p.usercode,p.fullname,p.sonnum,p.SortID 
			FROM Ptype p
			,dbo.F_TreeP(@OperatorID) TR,#Ptype pt  
			where P.parid=(case  when @PtypeID='' then '00000' else @PtypeID END)    and P.typeid LIKE @PtypeID+'%' 
			AND TR.typeid=P.typeid --AND p.IsService=0
			  AND pt.typeid LIKE p.typeid + '%'
END
ELSE IF @mType='WB' OR @mType='SB'
BEGIN	
	SELECT @sonnum = sonnum FROM Btype WHERE Typeid =case when @dealBtypeID='' then '00000' else @dealBtypeID end
	IF @sonnum =0 	
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum) 
		SELECT b.typeid,b.usercode,b.fullname,b.sonnum FROM Btype b
		,(select * from F_GetManBTypeAll(@OperatorID) where typeid =@dealBtypeID) a where b.typeid=a.typeid 
	ELSE
		IF @dealBtypeID='' or @dealBtypeID='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum) 
			SELECT b.typeid,b.usercode,b.fullname,b.sonnum FROM Btype b
			,(select * from F_GetManBTypeAll(@OperatorID) where parid=case  when @dealBtypeID='' then '00000' else @dealBtypeID end ) a where b.typeid=a.typeid 
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum) 
			SELECT b.typeid,b.usercode,b.fullname,b.sonnum FROM Btype b
			,(select * from F_GetManBTypeAll(@OperatorID) where parid=case  when @dealBtypeID='' then '00000' else @dealBtypeID end   and typeid LIKE @dealBtypeID+'%') a where b.typeid=a.typeid
END
IF @mType='WB'
BEGIN
	SELECT @SQL='
			SELECT  
				b.usercode,
				b.fullname,
				b.sonnum,
				b.typeid,
				isnull(a.type,0) as billtype,
				abs(sum(isnull(a.qty,0))) as qty,
				sum(isnull(a.total,0)) as total,
				sum(isnull(a.costtotal,0)) as costtotal	
			FROM #MainType b
			LEFT JOIN
					(
						SELECT c.qty,c.costtotal,c.total,c.ptypeid,c.btypeid,c.type
						FROM  commissionstock c '
						
	IF NOT(@PtypeID='' AND @MStypeid='00000'  AND @ptypecategoryid='')
		SELECT @SQL=@SQL+'  INNER JOIN #ptype p ON c.ptypeid=p.typeid  '
	
	--	IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
	--SELECT @SQL=@SQL+'  INNER JOIN #btype b ON c.btypeid=b.typeid '
	
	
		IF NOT(@dealBtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
	SELECT @SQL=@SQL+'  INNER JOIN #dealbtype b1 ON c.btypeid=b1.typeid '
	
	IF NOT (@Stypeid='' AND @MStypeid='00000')
		SELECT @SQL=@SQL+'  INNER JOIN #stype s ON c.stypeid=s.typeid  '
	
	SELECT @SQL=@SQL+'	WHERE  c.Type = 140
					)a
			ON   b.typeid=left(a.btypeid,len(b.typeid)) 
		 '
	SELECT @SQL=@SQL+' GROUP BY b.usercode,b.fullname,b.sonnum,b.typeid,a.type'
	
	SELECT @SQL=@SQL+' Order By b.UserCode'
END

IF @mType='SB'  -- SB 委托客户统计
BEGIN
	SELECT @SQL='
			SELECT  b.usercode,b.fullname,b.sonnum,b.typeid,isnull(a.type,0) as billtype,abs(sum(isnull(a.qty,0))) as qty,sum(isnull(a.total,0)) as total,sum(isnull(a.costtotal,0)) as costtotal	
			FROM #MainType b
				LEFT JOIN
					(
						SELECT c.qty,c.costtotal,c.total,c.ptypeid,c.btypeid,c.type
						FROM  commissionstock c '
						
	IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')					
		SELECT @SQL=@SQL+' INNER JOIN #ptype p ON c.ptypeid =p.typeid '
	
  --  IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
		--SELECT @SQL=@SQL+' INNER JOIN #btype b1 ON c.btypeid=b1.typeid '
		
	   IF NOT(@dealBtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
		SELECT @SQL=@SQL+' INNER JOIN #dealbtype b ON c.btypeid=b.typeid '	
	
	IF NOT (@Stypeid='' AND @MStypeid='00000')
		SELECT @SQL=@SQL+' INNER JOIN #stype s ON c.stypeid=s.typeid '
	
	SELECT @SQL=@SQL+' WHERE   c.Type = 144
							      )a

			ON   b.typeid=left(a.btypeid,len(b.typeid))
			 
			 '
	SELECT @SQL=@SQL+' GROUP BY b.usercode,b.fullname,b.sonnum,b.typeid,a.type'

	SELECT @SQL=@SQL+' Order By b.UserCode'
END

IF @mType='WK' 
BEGIN

	SELECT @SQL='
			SELECT  p.typeid,p.usercode,p.fullname,p.sonnum,sum(isnull(b.qty,0)) as qty,
					sum(isnull(b.total,0)) as total,
					sum(isnull(b.costtotal,0)) as costtotal,
					price =case when sum(isnull(b.qty,0)) =0 then 0 else cast( sum(isnull(b.total,0)) as NUMERIC(24, 10))/cast( sum(isnull(b.qty,0)) as NUMERIC(24, 10)) end,
					costprice =case when sum(isnull(b.qty,0)) =0 then 0 else cast(sum(isnull(b.costtotal,0)) as NUMERIC(24, 10))/cast( sum(isnull(b.qty,0)) as NUMERIC(24, 10)) end
			FROM #MainType p
				LEFT JOIN
				(
					SELECT	c.qty,
							c.ptypeid,
							c.total,
							c.costtotal,
							c.type
					FROM 	commissionstock c '
					
	IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')				
		SELECT @SQL=@SQL+' INNER JOIN #ptype p ON c.ptypeid =p.typeid '
    
  --  IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00002')		
		--SELECT @SQL=@SQL+' INNER JOIN #btype b1 ON  c.btypeid=b1.typeid '
		
	    IF NOT(@dealBtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00002')		
		SELECT @SQL=@SQL+' INNER JOIN #dealbtype b ON  c.btypeid=b.typeid '	
			
	IF NOT (@stypeid='' AND @MStypeid='00000')
		SELECT @SQL=@SQL+' INNER JOIN #stype s ON c.stypeid=s.typeid '		  
					  
	SELECT @SQL=@SQL+' WHERE    c.Type = 140
								--AND qty>=0
				)b
			ON p.typeid=left(b.ptypeid,len(p.typeid))
			
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
			
	SELECT @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.fullname,p.sonnum,sortid'

	SELECT @SQL=@SQL+' Order By p.sortid'

END
IF @mType='SK' 
BEGIN

	SELECT @SQL='
			SELECT  p.typeid,p.usercode,p.fullname,p.sonnum,b.type as billtype,sum(isnull(b.qty,0)) as qty,
					sum(isnull(b.total,0)) as total,
					sum(isnull(b.costtotal,0)) as costtotal ,
				
					price =case when sum(isnull(b.qty,0)) =0 then 0 else cast( sum(isnull(b.total,0)) as NUMERIC(24, 10))/cast( sum(isnull(b.qty,0)) as NUMERIC(24, 10)) end,
					costprice =case when sum(isnull(b.qty,0)) =0 then 0 else cast(sum(isnull(b.costtotal,0)) as NUMERIC(24, 10))/cast( sum(isnull(b.qty,0)) as NUMERIC(24, 10)) end
					
			FROM #MainType p
				LEFT JOIN
				(
					SELECT	c.qty,
							c.ptypeid,
							c.total,
							c.costtotal,
							c.type					
					FROM 	commissionstock c '
					
	IF NOT(@PtypeID='' AND @MPtypeid='00000'  AND @ptypecategoryid='')					
		SELECT @SQL=@SQL+' INNER JOIN #ptype p ON c.ptypeid =p.typeid '
	
	--IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00002' )	
	--	SELECT @SQL=@SQL+' INNER JOIN #btype b1 ON c.btypeid=b1.typeid '
		
		
	IF NOT(@dealBtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00002' )	
		SELECT @SQL=@SQL+' INNER JOIN #dealbtype b ON c.btypeid=b.typeid '
		
	
	IF NOT (@Stypeid='' AND @MStypeid='00000')
		SELECT @SQL=@SQL+' INNER JOIN #stype s ON c.stypeid =s.typeid '
	
	SELECT @SQL=@SQL+' WHERE  c.Type = 144
						   AND qty>=0
				)b		               
			ON p.typeid=left(b.ptypeid,len(p.typeid))
			--INNER JOIN #Ptype pt ON pt.typeid LIKE p.typeid + ''%''
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
	SELECT @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.fullname,p.sonnum,b.type'
	SELECT @SQL=@SQL+' Order By p.UserCode'	

END  
--PRINT @SQL 

EXEC (@SQL)

DROP TABLE #Ptype,#MainType,#dealbtype




  




















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BeforeRebuildCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_BeforeRebuildCheck
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2019-09-29
	描述：系统重建前检查信息
	EXEC Web_BeforeRebuildCheck '00001'
*/

CREATE PROCEDURE Web_BeforeRebuildCheck
(	
	@stypeid		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #checkResult
(
	nid				INT IDENTITY(1,1),
	checkFlag		VARCHAR(10),
	CheckMsg		VARCHAR(200)
)

--会员卡检查
DECLARE @nVipCount		INT,
		@nI				INT,
		@vipcardid		INT,
		@vstypeid		VARCHAR(200),
		@cZyeMoney		NUMERIC(24,10),
		@xFyeMoney		NUMERIC(24,10),
		@stypename		VARCHAR(500),
		@vipcardcode	VARCHAR(500)

CREATE TABLE #VipCardSType
(
	nid			INT IDENTITY(1,1),
	STypeId		VARCHAR(200),
	vipcardid	VARCHAR(100),
	vipcardcode	VARCHAR(500),
	cZyeMoney	NUMERIC(24,10)
)

--有会员卡才进来
IF EXISTS(SELECT TOP 1 1 FROM nVipCardSign)
BEGIN
	INSERT INTO #VipCardSType
	( 
		STypeId, 
		vipcardid,
		vipcardcode,
		cZyeMoney 
	)
	SELECT  v.jkStypeId,
			v.VipCardID,
			v.vipcardcode,
			v.cZyeMoney
	FROM	dbo.nVipCardSign v
	INNER JOIN DBO.f_split(@stypeid,',') f ON v.jkStypeId = f.a
	
	SET @nVipCount = @@ROWCOUNT

    CREATE NONCLUSTERED INDEX CIX_VipCardSType ON #VipCardSType(NID,STypeId)
	
	SET @nI = 1

	CREATE TABLE #Result
	(
		VipCardID		VARCHAR(100),
		NTotalMoney		NUMERIC(24,0),
		STypeId			VARCHAR(50)
	)

	INSERT INTO #Result(VipCardID,NTotalMoney,STypeId)
	SELECT	m.VipCardID,
			ISNULL(SUM(m.NTotalMoney),0),
			b.Stypeid
	FROM	dbo.BillMulAccount m
	INNER JOIN Billindex b ON m.BillNumberId = b.BillNumberId AND m.BillType = b.BillType
	WHERE	ISNULL(m.VipCardID,'')<>'-1'
	GROUP BY m.VipCardID,
			 b.Stypeid

	WHILE @nI <= @nVipCount
	BEGIN
		SELECT	@vipcardid	 = vipcardid,
				@vstypeid	 = stypeid,
				@vipcardcode = vipcardcode,
				@cZyeMoney	 = cZyeMoney
		FROM	#VipCardSType 
		WHERE	nid = @nI
		
		SELECT	@xFyeMoney = ISNULL(SUM(m.NTotalMoney),0)
		FROM	#Result M
		WHERE	m.VipCardID = @vipcardid
				AND NOT EXISTS (
					SELECT stypeid FROM #VipCardSType WHERE stypeid = m.stypeid
				)				
				
		--判断具体值是否超出
		IF @cZyeMoney - @xFyeMoney < 0 
		BEGIN
			SELECT @stypename = FullName FROM SType WHERE TypeId = @vstypeid
			
			INSERT INTO #checkResult(checkFlag,CheckMsg)VALUES('-1',CAST(@stypename + '分支机构系统重建后，会导致会员卡'+@vipcardcode+'的余额为负，请确认后重试！' AS VARCHAR(2000)))
		END		
		
		SET @nI = @nI + 1
	END

	DROP TABLE #Result
END

--判断优惠券
DECLARE @nCouponCount	INT,
		@cI				INT,
		@couponCode		VARCHAR(500),
		@couponstypeid	VARCHAR(50)

CREATE TABLE #CouponInfo
(
	nid				INT IDENTITY(1,1),
	stypeid			VARCHAR(50),
	couponcode		VARCHAR(500)
)

--有优惠券信息才进来
IF EXISTS(SELECT TOP 1 1 FROM Coupon_CodeInfo)
BEGIN
	INSERT INTO #CouponInfo
	(
		stypeid,
		couponcode
	)
	SELECT	s.STypeID,
			c.CouponCode		
	FROM	Coupon_CodeInfo c
	INNER JOIN stock s ON c.KtypeId = s.typeId
	INNER JOIN DBO.f_split(@stypeid,',') f ON s.STypeID = f.a

	CREATE CLUSTERED INDEX CIX_CouponInfo ON #CouponInfo(stypeid,couponcode)

	SET @nCouponCount = @@ROWCOUNT

	SET @cI = 1

	WHILE @cI <= @nCouponCount
	BEGIN
		SELECT	@couponCode    = couponcode,
				@couponstypeid = stypeid
		FROM	#CouponInfo 
		WHERE	nid = @cI
		
		IF EXISTS(
					SELECT	TOP 1 1 
					FROM	dbo.Coupon_BillUsed C
					INNER JOIN Billindex B ON c.BillnumberId = B.BillNumberId
					WHERE	c.CouponCode = 	@couponCode
							AND B.Stypeid NOT IN (SELECT a FROM DBO.f_split(@stypeid,','))
		)
		BEGIN
			SELECT @stypename = FullName FROM SType WHERE TypeId = @couponstypeid
			
			INSERT INTO #checkResult(checkFlag,CheckMsg)
			SELECT	'-2',
					'['+@stypename+']分支机构中新建的优惠券在['+@couponCode+']分支机构['+s.fullname+']有使用，重建时无法清理，需要手动红冲相关单据，请确认后重试！'
			FROM	dbo.Coupon_BillUsed C
			INNER JOIN Billindex B ON c.BillnumberId = B.BillNumberId
			INNER JOIN stype s ON s.typeid = b.stypeid
			WHERE	c.CouponCode = 	@couponCode
					AND B.Stypeid NOT IN (SELECT a FROM DBO.f_split(@stypeid,','))
		END
		
		SET @cI = @cI + 1
	END
END 	

--出纳的判断
DECLARE @nClCount	INT,
		@nClI		INT
		
CREATE TABLE #ClTable
(
	nid		INT IDENTITY(1,1),
	stypeid	VARCHAR(50)
)

--有出纳的数据才进来
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE billtype = 310)
BEGIN
	INSERT INTO #ClTable
	(
		stypeid
	)
	SELECT	a
	FROM	DBO.f_split(@stypeid,',')

	SET @nClCount = @@ROWCOUNT

	SET @nClI = 1

	WHILE @nClI <= @nClCount
	BEGIN
		IF EXISTS(
					SELECT  TOP 1 1 
					FROM	dbo.BillIndex
					WHERE	STypeId NOT IN (SELECT a FROM DBO.f_split(@stypeid,','))
		)
		BEGIN
			SELECT	@stypename = s.FullName 
			FROM	SType s
			INNER JOIN #ClTable C ON s.typeid = c.stypeid
			WHERE	c.nid = @nClI
			
			INSERT INTO #checkResult(checkFlag,CheckMsg)
			SELECT	'-3',
					'['+@stypename+']分支机构和['+s.FullName+']分支机构间存在资金调拨单编号['+billcode+']，重建时无法清理，需要手动红冲相关单据，请确认后重试！'
			FROM	BillIndex B
			INNER JOIN stype s ON b.stypeid2 = s.TypeId
			WHERE	B.BillType = 310
					AND B.stypeid2 NOT IN (SELECT a FROM DBO.f_split(@stypeid,','))			
		END
		
		SET @nClI = @nClI + 1
	END	
END

SELECT * FROM #checkResult

DROP TABLE #checkResult,#VipCardSType,#CouponInfo,#ClTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BeforeYearCheckData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BeforeYearCheckData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2019-08-09
	描述：年结存前检测异常数据
*/
CREATE PROCEDURE Web_BeforeYearCheckData
(
	@OutMsg	VARCHAR(1000) OUTPUT		--异常检测输出异常
)
--@encode$--
AS
SET NOCOUNT ON

--销售单无仓库
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillType = 11 AND ISNULL(KTypeId,'') = '')
BEGIN
	SET @OutMsg = '系统存在无仓库的销售出库单，请确认！'
	RETURN -1
END

SET @OutMsg = ''
RETURN 0


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BeyondYearBaseSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BeyondYearBaseSelector]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-06-11
	描述：【跨模块】基本信息的模糊匹配
-------------------------------------------*/
CREATE PROCEDURE Web_BeyondYearBaseSelector
(
	@OperatorID			VARCHAR(50),
	@TypeName			VARCHAR(50),
	@IsSon				INT,
	@IsStop				INT,
	@IsLimit			INT,
	@Filter				VARCHAR(256),
	@SelectorType		VARCHAR(50),
	@TypeId				VARCHAR(100),	--基本信息的Id
	@IsNext				INT,
	@Flag				VARCHAR(4),			--公用字段  商品（1=不包含服务类商品）
	@accconstr			VARCHAR(2000)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @First    INT=0  --首次进入 对往来单位有用 其他为0

DECLARE @SQL VARCHAR(MAX)
DECLARE @SonNum INT
DECLARE @ParId	VARCHAR(100)

DECLARE @MinSql VARCHAR(500) = ''

SET @MinSql = ' WHERE 1 = 1 '
IF @IsStop = 0
	SET @MinSql += ' AND deleted = 0'
IF @IsSon = 1
	SET @MinSql += ' AND sonnum = 0'


--特殊处理 Start
IF @SelectorType = 'vp'  --商品
BEGIN
	SET @MinSql += ' AND iscombinationproduct = 0 '
	
	IF @Flag = '1' AND EXISTS(SELECT a.Name FROM syscolumns a  INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='PType' AND a.Name='IsService')
		SET @MinSql += ' AND IsService = 0 '
END

--特殊处理 End



IF @TypeId = '' SET @TypeId = '00000'

CREATE TABLE #BaseInfo
(
	TypeID		VARCHAR(100),
	XID			INT,
	ParId		VARCHAR(100),
	SonNum		INT,
	deleted		INT,			
	UserCode	VARCHAR(256),
	FullName	VARCHAR(256),
	PyCode		VARCHAR(256),
	Tel1        VARCHAR(100),
	Tel2        VARCHAR(100),
	Tel3       VARCHAR(100),
	SortID		NUMERIC(10,0) DEFAULT(0)
)

IF @SelectorType = 'vp' --商品
BEGIN
	IF EXISTS (SELECT name FROM syscolumns WHERE id = OBJECT_ID(N''+@accconstr+'.dbo.PType') AND name = 'SortID' )
	BEGIN
		--判断权限范围
		IF @IsLimit = 0 OR @MPtypeid = '00000'
			SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID) 
						SELECT TypeId,pid,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID FROM '+@accconstr+'.dbo.PType '
		ELSE
			SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID) 
						SELECT TypeId,pid,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID FROM '+@accconstr+'.dbo.F_GetManPTypeAll('''+@OperatorId+''') ' 
		
		SET @SQL += @MinSql
		
		--PRINT @SQL
		EXEC(@SQL)
	END
	ELSE
	BEGIN
		--判断权限范围
		IF @IsLimit = 0 OR @MPtypeid = '00000'
			SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode) 
						SELECT TypeId,pid,ParId,SonNum,deleted,UserCode,FullName,PyCode FROM '+@accconstr+'.dbo.PType '
		ELSE
			SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode) 
						SELECT TypeId,pid,ParId,SonNum,deleted,UserCode,FullName,PyCode FROM '+@accconstr+'.dbo.F_GetManPTypeAll('''+@OperatorId+''') ' 
			
		SET @SQL += @MinSql
		
		PRINT @SQL
		EXEC(@SQL)
	END
END

ELSE IF @SelectorType = 'vs' --分支机构
BEGIN
	--判断权限范围
	IF @IsLimit = 0 OR @MStypeid = '00000'
		SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode) 
					SELECT TypeId,sid,ParId,SonNum,deleted,UserCode,FullName,PyCode FROM '+@accconstr+'.dbo.stype '
	ELSE
		SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode) 
					SELECT TypeId,sid,ParId,SonNum,deleted,UserCode,FullName,PyCode FROM '+@accconstr+'.dbo.F_GetManSTypeAll('''+@OperatorId+''') ' 
		
	SET @SQL += @MinSql
	
	EXEC(@SQL)
END

ELSE IF @SelectorType = 'vk' --仓库
BEGIN
	--判断权限范围
	IF @IsLimit = 0 OR @MStypeid = '00000'
		SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode) 
					SELECT TypeId,kid,ParId,SonNum,deleted,UserCode,FullName,PyCode FROM '+@accconstr+'.dbo.Stock '
	ELSE
		SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode) 
					SELECT TypeId,kid,ParId,SonNum,deleted,UserCode,FullName,PyCode FROM '+@accconstr+'.dbo.F_GetManKTypeAll('''+@OperatorId+''') ' 
		
	SET @SQL += @MinSql
	
	EXEC(@SQL)
END

ELSE IF @SelectorType = 'vb' OR @SelectorType = 'gb' OR @SelectorType = 'kb'  --往来单位
BEGIN
	DECLARE @BTypeAll INT=0  --1全部
	--判断供货商和客户是否统一
	IF @SelectorType = 'vb'
		SET @BTypeAll = 1
	ELSE
		SELECT	@BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'
	
	IF @IsLimit = 0 OR (@MBtypeid = '00001' AND @MBtypeid2='00002')
		SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode,Tel1,Tel2,Tel3) 
					SELECT TypeId,bid,ParId,SonNum,deleted,UserCode,FullName,PyCode,Tel1,Tel2,Tel3 FROM '+@accconstr+'.dbo. btype '
	ELSE
		SET @SQL = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,deleted,UserCode,FullName,PyCode,Tel1,Tel2,Tel3) 
					SELECT TypeId,bid,ParId,SonNum,deleted,UserCode,FullName,PyCode,Tel1,Tel2,Tel3 FROM '+@accconstr+'.dbo.F_GetManBTypeAll('''+@OperatorId+''') ' 
	
	SET @SQL += @MinSql
	EXEC(@SQL)
	
	IF @BTypeAll = 0  --非统一时删除数据
	BEGIN
		IF @SelectorType = 'gb'
			DELETE #BaseInfo WHERE TypeID LIKE '00001%'
		IF @SelectorType = 'kb'
			DELETE #BaseInfo WHERE TypeID LIKE '00002%'
	END
	
	--重新设置Typeid
	IF @TypeId = '00000' AND @BTypeAll = 0 AND @SelectorType <> 'vb'
	BEGIN
		IF @SelectorType = 'kb' 
			SET @TypeId = '00001'
		ELSE
			SET @TypeId = '00002'
		
		SET @First = 1
	END
END



--公用

--IF @SelectorType = 've'
--BEGIN
--	IF @TypeId = '00000' SET @TypeId = '00001'
--END

SELECT @SonNum = SonNum,@ParId=ParId FROM #BaseInfo WHERE TypeId = @TypeId
DELETE #BaseInfo WHERE TypeID = '00000'
	
IF @Filter = ''
BEGIN
	IF @IsNext = '0'
		BEGIN
			SELECT * FROM #BaseInfo WHERE ParId = @ParId ORDER BY SortID,UserCode
		END
	ELSE --下一层
		BEGIN			
			IF @SonNum = 0
				SELECT * FROM #BaseInfo WHERE SonNum = 0 AND TypeId = @TypeId ORDER BY SortID,UserCode
			ELSE
				BEGIN
					IF @First = 1 AND (@TypeId = '00001' OR @TypeId = '00002')
						SELECT * FROM #BaseInfo WHERE TypeID = @TypeId ORDER BY SortID,UserCode
					ELSE
						SELECT * FROM #BaseInfo WHERE ParId = @TypeId ORDER BY SortID,UserCode		
				END
		END
END
ELSE
BEGIN
	SET @SQL = '
		SELECT * FROM #BaseInfo
		WHERE	SonNum = 0 
				AND (UserCode LIKE ''%'+@Filter+'%'' OR FullName LIKE ''%'+@Filter+'%'' OR PyCode LIKE ''%'+@Filter+'%'')'
	
	IF @SelectorType = 'vb' OR @SelectorType = 'gb' OR @SelectorType = 'kb' --往来单位
		SET @SQL = 
		'SELECT * FROM #BaseInfo
		 WHERE	SonNum = 0 
				AND (UserCode LIKE ''%'+@Filter+'%'' OR FullName LIKE ''%'+@Filter+'%'' OR PyCode LIKE ''%'+@Filter+'%''
					 OR Tel1 LIKE ''%'+@Filter+'%'' OR Tel2 LIKE ''%'+@Filter+'%'' OR Tel3 LIKE ''%'+@Filter+'%'')'	 
END

--PRINT @SQL
EXEC(@SQL)


DROP TABLE #BaseInfo


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BeyondYearBaseSelectorAccurate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BeyondYearBaseSelectorAccurate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-04-09
	描述：【跨模块】基本信息的精确匹配
-------------------------------------------*/
CREATE PROCEDURE Web_BeyondYearBaseSelectorAccurate
(
	@OperatorID			VARCHAR(50),
	@TypeName			VARCHAR(50),
	@IsStop				INT,
	@IsLimit			INT,
	@Filter				VARCHAR(256),
	@SelectorType		VARCHAR(50),
	@Flag				VARCHAR(4)	--公用字段  商品（1=不包含服务类商品）
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #BaseInfo
(
	TypeID		VARCHAR(100),
	XID			INT,
	ParId		VARCHAR(100),
	SonNum		INT,			
	UserCode	VARCHAR(256),
	FullName	VARCHAR(256)
)

DECLARE @SQL VARCHAR(MAX)

DECLARE @MainSql	VARCHAR(500)
DECLARE @MinSQL		VARCHAR(500) --精确
DECLARE @MinSQLFilter VARCHAR(500) --模糊


--公用 Start
SET @MinSQL = ' AND (UserCode = '''+@Filter+''' OR FullName = '''+@Filter+''') '
SET @MinSQLFilter = ' AND ( UserCode LIKE ''%'+@Filter+'%'' OR FullName LIKE ''%'+@Filter+'%'') '
IF @IsStop = 0
	SET @MinSQL += ' AND deleted = 0 '
--公用 End



--特殊处理 Start
IF @SelectorType = 'vp' AND @Flag = '1' --商品
BEGIN
	IF EXISTS(SELECT a.Name FROM syscolumns a  INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='PType' AND a.Name='IsService')
	BEGIN
		SET @MinSQL += ' AND IsService = 0 '
		SET @MinSQLFilter += ' AND IsService = 0 '
	END
END

--特殊处理 End


IF @SelectorType = 'vp' --商品
BEGIN
	--判断权限范围
	IF @IsLimit = 0 OR @MPtypeid = '00000'
	BEGIN
		SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,UserCode,FullName) 
						SELECT TOP 2 TypeId,pid,ParId,SonNum,UserCode,FullName FROM PType WHERE sonnum = 0 '
		SET @SQL = @MainSql + @MinSQL
		EXEC(@SQL)
		IF @@ROWCOUNT = 0
		BEGIN
			SET @SQL = @MainSql + @MinSQLFilter
			EXEC(@SQL)
		END
		SELECT * FROM #BaseInfo
	END
	ELSE
	BEGIN
		SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,UserCode,FullName) 
					SELECT TOP 2 TypeId,pid,ParId,SonNum,UserCode,FullName FROM F_GetManPTypeAll('''+@OperatorId+''') WHERE sonnum = 0 '
		SET @SQL = @MainSql + @MinSQL
		EXEC(@SQL)
		IF @@ROWCOUNT = 0
		BEGIN
			SET @SQL = @MainSql + @MinSQLFilter
			EXEC(@SQL)
		END
		SELECT * FROM #BaseInfo
	END
END

ELSE IF @SelectorType = 'vs'  --分支机构
BEGIN
	--判断权限范围
	IF @IsLimit = 0 OR @MStypeid = '00000'
	BEGIN
		SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,UserCode,FullName) 
						SELECT TOP 2 TypeId,sid,ParId,SonNum,UserCode,FullName FROM stype WHERE sonnum = 0 '
		SET @SQL = @MainSql + @MinSQL
		EXEC(@SQL)
		IF @@ROWCOUNT = 0
		BEGIN
			SET @SQL = @MainSql + @MinSQLFilter
			EXEC(@SQL)
		END
		SELECT * FROM #BaseInfo
	END
	ELSE
	BEGIN
		SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,UserCode,FullName) 
					SELECT TOP 2 TypeId,sid,ParId,SonNum,UserCode,FullName FROM F_GetManSTypeAll('''+@OperatorId+''') WHERE sonnum = 0 '
		SET @SQL = @MainSql + @MinSQL
		EXEC(@SQL)
		IF @@ROWCOUNT = 0
		BEGIN
			SET @SQL = @MainSql + @MinSQLFilter
			EXEC(@SQL)
		END
		SELECT * FROM #BaseInfo
	END
	
END

ELSE IF @SelectorType = 'vk'  --仓库
BEGIN
	--判断权限范围
	IF @IsLimit = 0 OR @MEtypeid = '00000'
	BEGIN
		SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,UserCode,FullName) 
						SELECT TOP 2 TypeId,kid,ParId,SonNum,UserCode,FullName FROM Stock WHERE sonnum = 0 '
		SET @SQL = @MainSql + @MinSQL
		EXEC(@SQL)
		IF @@ROWCOUNT = 0
		BEGIN
			SET @SQL = @MainSql + @MinSQLFilter
			EXEC(@SQL)
		END
		SELECT * FROM #BaseInfo
	END
	ELSE
	BEGIN
		SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,UserCode,FullName) 
					SELECT TOP 2 TypeId,kid,ParId,SonNum,UserCode,FullName FROM F_GetManKTypeAll('''+@OperatorId+''') WHERE sonnum = 0 '
		SET @SQL = @MainSql + @MinSQL
		EXEC(@SQL)
		IF @@ROWCOUNT = 0
		BEGIN
			SET @SQL = @MainSql + @MinSQLFilter
			EXEC(@SQL)
		END
		SELECT * FROM #BaseInfo
	END
	
END

ELSE IF @SelectorType = 'vb' OR @SelectorType = 'gb' OR @SelectorType = 'kb'  --往来单位
BEGIN
	DECLARE @BTypeAll INT=0  --1全部
	IF @SelectorType = 'vb'
		SET @BTypeAll = 1
	ELSE
		SELECT	@BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

	IF @IsLimit = 0 OR @MBtypeid = '00000'
	BEGIN
		SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,UserCode,FullName) 
						SELECT TOP 2 TypeId,bid,ParId,SonNum,UserCode,FullName FROM btype WHERE sonnum = 0 '
		SET @SQL = @MainSql + @MinSQL
		IF @BTypeAll = 0
		BEGIN
			IF @SelectorType = 'gb'
					SET @SQL += ' AND TypeId LIKE ''00002%'' '
				ELSE
					SET @SQL += ' AND TypeId LIKE ''00001%'' '
		END
		
		EXEC(@SQL)
		IF @@ROWCOUNT = 0
		BEGIN
			SET @SQL = @MainSql + @MinSQLFilter
			IF @BTypeAll = 0
			BEGIN
				IF @SelectorType = 'gb'
					SET @SQL += ' AND TypeId LIKE ''00002%'' '
				ELSE
					SET @SQL += ' AND TypeId LIKE ''00001%'' '
			END
			
			EXEC(@SQL)
		END
		SELECT * FROM #BaseInfo
	END
	ELSE
	BEGIN
		SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,XID,ParId,SonNum,UserCode,FullName) 
						SELECT TOP 2 TypeId,bid,ParId,SonNum,UserCode,FullName FROM F_GetManBTypeAll('''+@OperatorId+''') WHERE sonnum = 0 '
		SET @SQL = @MainSql + @MinSQL
		IF @BTypeAll = 0
		BEGIN
			IF @SelectorType = 'gb'
				SET @SQL += ' AND TypeId LIKE ''00002%'' '
			ELSE
				SET @SQL += ' AND TypeId LIKE ''00001%'' '
		END
		
		EXEC(@SQL)
		IF @@ROWCOUNT = 0
		BEGIN
			SET @SQL = @MainSql + @MinSQLFilter
			IF @BTypeAll = 0
			BEGIN
				IF @SelectorType = 'gb'
					SET @SQL += ' AND TypeId LIKE ''00002%'' '
				ELSE
					SET @SQL += ' AND TypeId LIKE ''00001%'' '
			END
			
			EXEC(@SQL)
		END
		SELECT * FROM #BaseInfo
	END
END
ELSE
BEGIN
	RAISERROR('出错了啦！',16,1)
END


DROP TABLE #BaseInfo


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BeyondYearCurrencySelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BeyondYearCurrencySelector]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-6-20
	描述：跨年账 币种selector
-------------------------------------------*/
CREATE PROCEDURE Web_BeyondYearCurrencySelector
(
	@Filter			VARCHAR(50),
	@OperatorID		VARCHAR(50),
	@Flag			INT,	--1模糊 0=精确
	@accconstr			VARCHAR(2000)
)
--@encode$--
AS
SET NOCOUNT ON


DECLARE @SQL VARCHAR(8000) =''

IF @Flag = 1
BEGIN
	IF @Filter = ''
		SET @SQL='
		SELECT t.typeid,t.FullName
		FROM
		(
			SELECT -1 AS typeid,''所有币种'' AS FullName
			UNION ALL
			SELECT 0 AS typeid,''综合本位币'' AS FullName
			UNION ALL
			SELECT CId AS typeid,FullName FROM '+@accconstr+'.dbo.Ac_Currency
		) t
		ORDER BY t.typeid '
	ELSE
		SET @SQL='
		SELECT t.typeid,t.FullName
		FROM
		(
			SELECT -1 AS typeid,''所有币种'' AS FullName
			UNION ALL
			SELECT 0 AS typeid,''综合本位币'' AS FullName
			UNION ALL
			SELECT CId AS typeid,FullName FROM '+@accconstr+'.dbo.Ac_Currency
		) t
		WHERE FullName LIKE ''%'''+@Filter+'''%''
		ORDER BY t.typeid '
	EXEC (@SQL)
END

--精确
IF @Flag = 0
BEGIN
	DECLARE @MinSQL		VARCHAR(500) --精确
	DECLARE @MinSQLFilter VARCHAR(500) --模糊

	CREATE TABLE #Result
	(
		TypeID		VARCHAR(100),
		FullName	VARCHAR(256)
	)
	SET @SQL='
	INSERT #Result(TypeID,FullName)
	SELECT t.typeid,t.FullName
	FROM
	(
		SELECT -1 AS typeid,''所有币种'' AS FullName
		UNION ALL
		SELECT 0 AS typeid,''综合本位币'' AS FullName
		UNION ALL
		SELECT CId AS typeid,FullName FROM '+@accconstr+'.dbo.Ac_Currency
	) t
	WHERE t.FullName = '''+@Filter+''' 
	
	IF @@ROWCOUNT = 0
	BEGIN
		INSERT #Result(TypeID,FullName)
		SELECT TOP 2 t.typeid,t.FullName
		FROM
		(
			SELECT -1 AS typeid,''所有币种'' AS FullName
			UNION ALL
			SELECT 0 AS typeid,''综合本位币'' AS FullName
			UNION ALL
			SELECT CId AS typeid,FullName FROM '+@accconstr+'.dbo.Ac_Currency
		) t
		WHERE t.FullName LIKE ''%'''+@Filter+'''%''
	END '
	EXEC(@SQL)
	SELECT * FROM #Result
	DROP TABLE #Result
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BeyondYearSchemeSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BeyondYearSchemeSelector]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-6-10
	描述：跨年账 方案selector
-------------------------------------------*/
CREATE PROCEDURE Web_BeyondYearSchemeSelector
(
	@Filter			VARCHAR(50),
	@OperatorID		VARCHAR(50),
	@Flag			INT	--1模糊 0=精确
)
--@encode$--
AS
SET NOCOUNT ON

IF @Flag = 1
BEGIN
	IF @Filter = ''
		SELECT ID AS typeid,SchemeName AS FullName 
		FROM SchemeIndex ORDER BY SchemeName
	ELSE
		SELECT ID AS typeid,SchemeName AS FullName 
		FROM SchemeIndex WHERE SchemeName LIKE '%' + @Filter + '%' ORDER BY SchemeName
END

--精确
IF @Flag = 0
BEGIN
	DECLARE @MinSQL		VARCHAR(500) --精确
	DECLARE @MinSQLFilter VARCHAR(500) --模糊

	CREATE TABLE #Result
	(
		TypeID		VARCHAR(100),
		FullName	VARCHAR(256)
	)
	
	INSERT #Result(TypeID,FullName)
	SELECT ID AS typeid,SchemeName AS FullName FROM SchemeIndex WHERE SchemeName = @Filter
	
	IF @@ROWCOUNT = 0
	BEGIN
		INSERT #Result(TypeID,FullName)
		SELECT TOP 2 ID AS typeid,SchemeName AS FullName FROM SchemeIndex WHERE SchemeName LIKE '%'+@Filter+'%'
	END
	
	SELECT * FROM #Result
	DROP TABLE #Result
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Bill_BeginningBillQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Bill_BeginningBillQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-------------------------------------------------------------------------
/*
	作者：俞俊杰
	日期：2012-07-04
	描述：期初单据查询
*/
CREATE PROCEDURE [dbo].[Web_Bill_BeginningBillQuery]
(
    @OperatorID		varchar(100) 	,  			-- 操作员
	@Beginbilltype	 	varchar(MAX)   	='',		-- 单据类型
	@startdate	 	varchar(25)  	='', 		-- 开始时间
	@enddate	 	varchar(25)  	='',   		-- 结束时间
	@billcode	 	varchar(200) 	='',  		-- 单据编号
	--@etypeid	 	varchar(1550)	='',    	-- 经手人
	@btypeid	 	varchar(1550)	='',     	-- 结算单位
	@dealbtypeid    varchar(1550)   ='',        -- 往来单位
	@comment        VARCHAR(1550)   ='',        -- 摘要
	--@dtypeid		varchar(8000)	='',		-- 部门
	@stypeid        varchar(1550)	='00001'  	-- 分支机构
	
	,@dtypeid		varchar(max)='' --部门
	,@etypeid		varchar(max)='' --经手人
	,@showempty		bit=0  --是否显示部门或经手人为空的
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @operatorid IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

--分支机构
CREATE TABLE #Stype (TypeID VARCHAR(50))
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--单据类型
CREATE TABLE #Billtype (BillType VARCHAR(200))
INSERT INTO #Billtype SELECT a AS Billtype FROM dbo.f_split(@Beginbilltype,',')

--结算单位	
CREATE TABLE #Btype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Btype SELECT typeid,usercode,fullname FROM Btype a WHERE EXISTS(SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) b WHERE a.typeId = b.TypeId )

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #DealBtype SELECT typeid,usercode,fullname FROM Btype a WHERE EXISTS(SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID) b WHERE a.typeId = b.TypeId)

--职员
CREATE TABLE #Etype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Etype SELECT typeid,usercode,fullname FROM Employee a WHERE EXISTS(SELECT typeid FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID) b WHERE a.typeId = b.TypeId )

--部门
CREATE TABLE #dtype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #dtype SELECT typeid,usercode,fullname FROM dbo.Department a WHERE EXISTS(SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID) b WHERE a.typeId = b.TypeId )


IF @btypeid =''
	INSERT INTO #Btype (TypeID,UserCode,FullName) VALUES('','','')
IF @dealbtypeid =''
	INSERT INTO #DealBtype (TypeID,UserCode,FullName) VALUES('','','')
IF @etypeid = ''
	INSERT INTO #Etype (TypeID,UserCode,FullName) VALUES('','','')
IF @dtypeid = ''
	INSERT INTO #dtype (TypeID,UserCode,FullName) VALUES('','','')

CREATE TABLE #stypeConfig(stypeid VARCHAR(50),value INT)

INSERT #stypeConfig
    SELECT u.StypeId,U.Value FROM SType_Config C,SType_UserConfig U 
	WHERE C.ConfigNo = U.ConfigNo 
	AND C.ConfigName = 'stypeinicanmodify' 

--业务SQL
DECLARE @sql VARCHAR(max)
SET @sql = 'SELECT b.billnumberid,
                   b.billdate,
                   b.billcode,
                   b.billtype,
                   b.stypeid,
                   b.etypeid,
                   b.dtypeid,
                   b.btypeid,
                   b.dealbtypeid,
                   b.totalqty,
                   b.totalmoney,
                   b.ntotalmoney,
                   b.checke,
                   b.comment,
                   b.isini,
                   b.ifYearBill,
                   ifcanmodify=(case when /*b.ifYearBill=1 or*/ isnull(sc.value,0)=1 then 1 else 0 end),
                   ''期初'' + bn.billname AS billname,
                   b.AddDTypeETypeType,
                   b.FaPiaoCode
            FROM '
            IF EXISTS (SELECT BillType FROM #Billtype WHERE BillType=-1)
             SET @sql = @sql +
            '(
				SELECT billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,btypeid,dealbtypeid,
				totalqty,totalmoney,ntotalmoney,checke,comment,isini,ifYearBill,AddDTypeETypeType,'''' as FaPiaoCode
				FROM billindex 
				UNION 
				SELECT billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,btypeid,dealbtypeid,
				totalqty,totalmoney=TaxTotalMoney,ntotalmoney=NTaxTotalMoney,checke,comment,isini,ifYearBill,'''' AS AddDTypeETypeType ,FaPiaoCode
				FROM ReceiptBillIndex 
				UNION 
				SELECT billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,btypeid,dealbtypeid,
				totalqty,totalmoney,ntotalmoney,Maker,comment,isini,ifYearBill,'''' AS AddDTypeETypeType,'''' as FaPiaoCode
				FROM Coupon_BillIndex 
				union
				SELECT distinct fi.billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,'''' AS btypeid,dealbtypeid,
				fio.totalqty,null AS totalmoney,null AS ntotalmoney,checke,comment,isini,0 AS ifYearBill,'''' AS AddDTypeETypeType,'''' as FaPiaoCode
				FROM dbo.FactIndex fi
				LEFT JOIN (select billnumberid,sum(qty) as totalqty from factinout group by billnumberid)fio on fi.billnumberid= fio.billnumberid
				UNION ALL
				SELECT distinct billnumberid,billdate,billcode,billtype,stypeid,checkE AS etypeid,dtypeid,'''' AS btypeid, '''' AS	dealbtypeid,Qty totalqty,total AS totalmoney,total AS ntotalmoney,checke,comment,isini,0 AS ifYearBill,'''' AS						AddDTypeETypeType,'''' as FaPiaoCode
				FROM dbo.PosAllotApplyBillIndex
			) '
            ELSE IF EXISTS (SELECT billtype FROM #Billtype WHERE billtype IN(404,405)) 
            --原币金额取单据上的加税合计，本币金额取单据上的本位币加税合计
            SET @sql = @sql +
            '(
				SELECT billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,btypeid,dealbtypeid,
				totalqty,totalmoney,ntotalmoney,checke,comment,isini,ifYearBill,AddDTypeETypeType,'''' as FaPiaoCode
				FROM billindex 
				UNION 
				SELECT billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,btypeid,dealbtypeid,
				totalqty,totalmoney=TaxTotalMoney,ntotalmoney=NTaxTotalMoney,checke,comment,isini,ifYearBill,'''' AS AddDTypeETypeType ,FaPiaoCode
				FROM ReceiptBillIndex 
			) '
			
			ELSE IF EXISTS (SELECT billtype FROM #Billtype WHERE billtype IN(421,422))
			 SET @sql = @sql +
            '(				
				SELECT distinct fi.billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,'''' AS btypeid,dealbtypeid,
				fio.totalqty,null AS totalmoney,null AS ntotalmoney,checke,comment,isini,0 AS ifYearBill,'''' AS AddDTypeETypeType,'''' as FaPiaoCode
				FROM dbo.FactIndex fi
				LEFT JOIN (select billnumberid,sum(qty) as totalqty from factinout group by billnumberid)fio on fi.billnumberid= fio.billnumberid
			
			) '
			
			-- 期初未验收门店配送，退货单
			ELSE IF EXISTS (SELECT billtype FROM #Billtype WHERE billtype IN(327,328))
			 SET @sql = @sql +
            '(				
				SELECT distinct billnumberid,billdate,billcode,billtype,stypeid,checkE AS etypeid,dtypeid,'''' AS btypeid, '''' AS	dealbtypeid,Qty totalqty,total AS totalmoney,total AS ntotalmoney,checke,comment,isini,0 AS ifYearBill,'''' AS						AddDTypeETypeType,'''' as FaPiaoCode
				FROM dbo.PosAllotApplyBillIndex
			) '
			ELSE
			     SET @sql = @sql +
            '(
				SELECT billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,btypeid,dealbtypeid,
				totalqty,totalmoney,ntotalmoney,checke,comment,isini,ifYearBill,AddDTypeETypeType,'''' as FaPiaoCode
				FROM billindex 
				UNION 
				SELECT billnumberid,billdate,billcode,billtype,stypeid,etypeid,dtypeid,btypeid,dealbtypeid,
				totalqty,totalmoney,ntotalmoney,checker,comment,isini,ifYearBill,'''' AS AddDTypeETypeType,'''' as FaPiaoCode
				FROM Coupon_BillIndex 
			) '
			
			SET @sql = @sql +
			' b
            LEFT JOIN #stypeConfig sc ON b.stypeid = sc.stypeid
            INNER JOIN billname bn ON b.billtype = bn.billtype
           '
--根据参数是否为空及全部权限控制
IF @btypeid <> '' OR @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
BEGIN
	SET @sql = @sql + ' INNER JOIN #Btype bb ON bb.typeid = b.btypeid '
END

IF @dealbtypeid <> '' OR @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
BEGIN
	SET @sql = @sql + ' INNER JOIN #DealBtype db ON db.typeid = b.dealbtypeid '
END

IF @stypeid <> '' OR @MStypeid = '-99999'
	SET @sql = @sql + ' INNER JOIN #Stype s ON s.typeid = b.stypeid'
	
IF @Beginbilltype <> '-1'
	SET @sql = @sql + ' INNER JOIN #Billtype bt ON bt.billtype = b.billtype'

--
IF @etypeid <> '' OR @MEtypeid = '-99999'
	SET @sql = @sql + ' INNER JOIN #Etype e ON e.typeid = b.etypeid'

IF @dtypeid <> '' OR @MDtypeid = '-99999'
	SET @sql = @sql + ' INNER JOIN #Dtype d ON d.typeid = b.dtypeid'
--

SET @sql= @sql + ' AND b.isini= 1'

IF @startdate <> '' AND @enddate <> ''
	SET @sql = @sql + ' AND  b.billdate >= '''+ @startdate +''' AND b.billdate <= '''+ @enddate +''''

IF @billcode  <> ''
	SET @sql = @sql + ' AND  b.billcode Like '+CHAR(39)+'%'+@billcode+'%'+CHAR(39)
	
IF @comment  <> ''
	SET @sql = @sql + ' AND  b.comment  Like '+CHAR(39)+'%'+@comment+'%'+CHAR(39)
	
IF @showempty=1 --显示空
	SET @sql+=' and (b.dtypeid='''' or b.etypeid='''') ';

SET @sql = @sql + ' ORDER BY b.billdate' 

--PRINT @sql
EXECUTE(@sql)

DROP TABLE #Stype,#Etype,#Btype,#DealBtype,#Billtype,#stypeConfig  ,#dtype
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BillCheckVoucher]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BillCheckVoucher]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013-05-17
	描述：业务单据是否生成凭证校验
*/
CREATE PROCEDURE Web_BillCheckVoucher
(
	@STypeId	VARCHAR(50),
	@StartDate	DATETIME,
	@EndDate	DATETIME
)
--@encode$--
AS
SET NOCOUNT ON


IF NOT EXISTS(SELECT * FROM dbo.SType WHERE TypeId = @STypeId AND IsSelfVerify = 1)
BEGIN
	RAISERROR('此分支机构非独立核算，无需检查',16,1)
	RETURN -1
END

 
--消息列表
CREATE TABLE #TmpInfo
(
	ContentText	VARCHAR(MAX),--消息内容
	Detail		INT	--是否具体信息
)

INSERT INTO #TmpInfo( ContentText, Detail )
SELECT '存在业务单据未生成凭证',1
INSERT INTO #TmpInfo( ContentText, Detail )
SELECT BillCode,2
FROM dbo.BillIndex T1
WHERE T1.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND BillDate >= @StartDate AND BillDate <= @EndDate
	AND (BillType IN (11,45,160,305,139,140,142,141,34,6,161,126,144,146,145,21,187,188,201,202,9,14,16,116,115,128,129,4,189,66,190,148,
					150,149,151,36,84,85,78,158,77,93,5,10,57,205,181,427,183,166,167,168,170,172,159,173,174,215,147,312,400,401,402,403,12,46)
				OR	(BillType = 414 AND IsFreightMoney = 1))
	AND draft = 0 AND IsIni = 0 AND T1.ifYearBill = 0 AND RedWord = 0
	AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill)
	AND BillNumberId NOT IN (SELECT BillnumberId FROM Ac_ProvisionForImpairment)
UNION ALL
SELECT BillCode,2
FROM dbo.CommissionBillNew T1
WHERE T1.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND BillDate >= @StartDate AND BillDate <= @EndDate
	AND draft = 0 AND RedWord = 0
	AND BillNumberId NOT IN(SELECT GoodsBillId FROM Ac_CommissionBill_VoucherBill)
UNION ALL
SELECT BillCode,2
FROM dbo.ReceiptBillIndex T1
WHERE T1.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND BillDate >= @StartDate AND BillDate <= @EndDate
	AND draft = 0 AND IsIni = 0 AND T1.ifYearBill = 0 AND RedWord = 0
	AND BillNumberId NOT IN(SELECT GoodsBillId FROM Ac_ReceiptBill_VoucherBill)
UNION ALL
SELECT BillCode,2
		FROM dbo.BillIndex
		WHERE BillType = 310 AND draft = 0 AND RedWord = 0 AND ifYearBill =0
			AND (Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) 
					AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = -1)
				OR
				Stypeid2 IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) 
					AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill WHERE InOutType = 1)
				)
			AND BillDate >= @StartDate AND BillDate <= @EndDate
UNION ALL
SELECT BillCode,2
FROM dbo.Coupon_BillIndex T1
INNER JOIN dbo.SType S ON S.TypeId=T1.STypeId AND S.VerifyID=@Stypeid 
WHERE 
	T1.BillType IN(423,424,426,428,429)
	AND T1.BillDate >= @StartDate 
	AND T1.BillDate <= @EndDate
	AND draft = 0 
	AND IsIni = 0 
	AND T1.ifYearBill = 0 
	AND RedWord = 0
	AND T1.FromType<>3
	AND T1.BillNumberId NOT IN (SELECT CouponBillId FROM dbo.Ac_CouponBill_VoucherBill)
UNION ALL
SELECT BillCode,2
FROM dbo.PosAllotApplyBillIndex T1
INNER JOIN dbo.SType S ON S.TypeId=T1.STypeId AND S.VerifyID=@Stypeid 
WHERE	T1.BillType IN(327,328,329)
		AND T1.BillDate >= @StartDate 
		AND T1.BillDate <= @EndDate
		AND draft = 0 
		AND IsIni = 0 
		AND T1.ifYearBill = 0 
		AND RedWord = 0		
		AND T1.BillNumberId NOT IN (SELECT DeliveryBillId FROM dbo.Ac_DeliveryBill_VoucherBill)	
	
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpInfo WHERE Detail = 2)
BEGIN
	DELETE FROM #TmpInfo WHERE Detail = 1
END

IF   EXISTS(SELECT 1 FROM billindex b WHERE b.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND draft=0 AND RedWord=0 AND isini=0 AND BillDate >= @StartDate AND BillDate <= @EndDate AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) AND BillType IN (305,215,11,45,160,141,405,12,46) )
OR EXISTS(SELECT 1 FROM ReceiptBillIndex b WHERE b.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND draft=0 AND RedWord=0 AND isini=0 AND BillDate >= @StartDate AND BillDate <= @EndDate AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) AND BillType IN (305,215,11,45,160,141,405,12,46) )
BEGIN
	INSERT INTO #TmpInfo( ContentText, Detail )
	SELECT '存在出库类单据未生成基本凭证',1
	INSERT INTO #TmpInfo( ContentText, Detail )
	SELECT BillCode,2
	FROM billindex b 
	WHERE b.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill =0 AND BillDate >= @StartDate AND BillDate <= @EndDate 
	AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) 
	AND BillType IN (305,215,11,45,160,141,405,12,46)
	UNION ALL
	SELECT BillCode,2
	FROM ReceiptBillIndex b 
	WHERE b.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill =0 AND BillDate >= @StartDate AND BillDate <= @EndDate 
	AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(0,2)) 
	AND BillType IN (305,215,11,45,160,141,405,12,46)
END

IF   EXISTS(SELECT 1 FROM billindex b WHERE b.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill =0 AND BillDate >= @StartDate AND BillDate <= @EndDate AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46) )
OR	EXISTS(SELECT 1 FROM ReceiptBillIndex b WHERE b.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill = 0 AND BillDate >= @StartDate AND BillDate <= @EndDate AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46) )
BEGIN
	INSERT INTO #TmpInfo( ContentText, Detail )
	SELECT '存在出库类单据未生成成本凭证',1
	INSERT INTO #TmpInfo( ContentText, Detail )
	SELECT BillCode,2
	FROM billindex b WHERE b.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill = 0 AND BillDate >= @StartDate AND BillDate <= @EndDate 
	AND NOT EXISTS(SELECT 1 FROM Ac_GoodsBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) 
	AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46)
	UNION ALL
	SELECT BillCode,2
	FROM ReceiptBillIndex b WHERE b.Stypeid IN( SELECT TypeId FROM dbo.SType WHERE VerifyID = @Stypeid) AND draft=0 AND RedWord=0 AND isini=0 AND b.ifYearBill = 0 AND BillDate >= @StartDate AND BillDate <= @EndDate 
	AND NOT EXISTS(SELECT 1 FROM Ac_ReceiptBill_VoucherBill WHERE GoodsBillId=b.BillNumberId AND IsCost IN(1,2)) 
	AND BillType IN (305,215,11,45,160,139,140,142,141,402,403,405,12,46) 
END	

IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpInfo WHERE Detail = 2)
BEGIN
	DELETE FROM #TmpInfo WHERE Detail = 1
	INSERT INTO #TmpInfo( ContentText, Detail )
	SELECT '业务单据全部生成凭证',1
END

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')  --1是卡片模式,add by dongzhan 2013.6.9
	BEGIN
		--结账的分支机构及挂靠它的机构
		CREATE TABLE #tempStype
		(
			typeid VARCHAR(50)
		)
		INSERT INTO #tempStype(typeid)
		SELECT typeid FROM stype WHERE VerifyID=@Stypeid
		
		IF EXISTS(SELECT TOP 1 1 
				FROM dbo.BillIndex T1
				JOIN #tempStype s ON T1.Stypeid=s.typeid 
				WHERE BillDate >= @StartDate AND BillDate <= @EndDate  AND BillType IN (212,213,214) AND T1.draft=1)
			INSERT INTO #TmpInfo(ContentText, Detail)
			SELECT '存在固定资产业务单据未过账',5
			INSERT INTO #TmpInfo( ContentText, Detail )
			SELECT BillCode,6
			FROM dbo.BillIndex T1
			JOIN #tempStype s ON T1.Stypeid=s.typeid 
			WHERE BillDate >= @StartDate AND BillDate <= @EndDate   AND BillType IN (212,213,214) AND T1.draft=1
			
		IF EXISTS(SELECT TOP 1 1 
				FROM dbo.BillIndex T1
				JOIN #tempStype s ON T1.Stypeid=s.typeid 
				WHERE BillDate >= @StartDate AND BillDate <= @EndDate  AND BillType IN (212,213,214) AND Isini = 0
					AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill) AND BillType IN (212,213,214) AND RedWord=0   --减少单,增加单，折旧单,排除红蓝单
				UNION ALL
				SELECT TOP 1 1 																			  --减值准备
				FROM Ac_ProvisionForImpairment ap 
				JOIN Ac_AssetsCards aa ON ap.cardid=aa.Id 
				JOIN #tempStype s ON aa.stypeid=s.typeid 
				WHERE ap.BusinessDate>= @StartDate AND ap.BusinessDate <= @EndDate   
					  AND ap.id NOT IN (SELECT SourceId FROM Ac_Provision_Voucher WHERE SourceType=1)
				UNION ALL 
				SELECT TOP 1 1																			  --部门变更
				FROM Ac_Assetsmodifyrecords ap 
				JOIN Ac_AssetsCards aa ON ap.cardid=aa.Id    
				JOIN #tempStype s ON aa.stypeid=s.typeid 
				WHERE ap.BusinessDate>= @StartDate AND ap.BusinessDate <= @EndDate   
					  AND ap.id NOT IN (SELECT SourceId FROM Ac_Provision_Voucher WHERE SourceType=2)
				)
		BEGIN
			----固定资产1 未生成凭证
			INSERT INTO #TmpInfo(ContentText, Detail)
			SELECT '存在固定资产业务单据未生成凭证',3
			INSERT INTO #TmpInfo( ContentText, Detail )
			SELECT BillCode,4
			FROM dbo.BillIndex T1
			JOIN #tempStype s ON T1.Stypeid=s.typeid 
			WHERE BillDate >= @StartDate AND BillDate <= @EndDate   AND BillType IN (212,213,214) AND Isini = 0
				AND BillNumberId NOT IN (SELECT GoodsBillId FROM dbo.Ac_GoodsBill_VoucherBill) AND BillType IN (212,213,214) AND RedWord=0   --减少单,增加单，折旧单,排除红蓝单
			UNION ALL
			SELECT aa.FullName,4																				  --减值准备
			FROM Ac_ProvisionForImpairment ap 
			JOIN Ac_AssetsCards aa ON ap.cardid=aa.Id 
			JOIN #tempStype s ON aa.stypeid=s.typeid 
			WHERE ap.BusinessDate>= @StartDate AND ap.BusinessDate <= @EndDate   
				  AND ap.id NOT IN (SELECT SourceId FROM Ac_Provision_Voucher WHERE SourceType=1)
			UNION ALL 
			SELECT aa.FullName,4																				  --部门变更
			FROM Ac_Assetsmodifyrecords ap 
			JOIN Ac_AssetsCards aa ON ap.cardid=aa.Id    
			JOIN #tempStype s ON aa.stypeid=s.typeid 
			WHERE ap.BusinessDate>= @StartDate AND ap.BusinessDate <= @EndDate   
				  AND ap.id NOT IN (SELECT SourceId FROM Ac_Provision_Voucher WHERE SourceType=2)
		END
		 
	END
		
IF NOT EXISTS(SELECT TOP 1 1 FROM #TmpInfo WHERE Detail = 4)
BEGIN
	DELETE FROM #TmpInfo WHERE Detail = 3
	INSERT INTO #TmpInfo(ContentText, Detail)
	SELECT '固定资产业务单据全部生成凭证',3
END
 


IF EXISTS(SELECT TOP 1 1 FROM #TmpInfo)
BEGIN
	SELECT * FROM #TmpInfo
	DROP TABLE #TmpInfo
	RETURN -1
END
 
	  


SELECT * FROM #TmpInfo

DROP TABLE #TmpInfo

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BillPrintConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BillPrintConfig]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-11-3
	描述：单据打印配置--查询
-------------------------------------------*/
CREATE PROCEDURE Web_BillPrintConfig
(
	@IsA8	  INT,
	@IsCP	  INT,
	@Flag INT --查询的哪类 采购，销售 ，财务。。。。
)
--@encode$--
AS
SET NOCOUNT ON
--版本 1:V3 2:A8 4:V1
DECLARE @ProInfo INT=0
SELECT @ProInfo=SubValue FROM SysData WHERE SubName='ProInfo'		 

--1要出序列号的单据类型
DECLARE @IsSerial INT=1		 
SELECT @IsSerial = 0 FROM sysdata WHERE SubName = 'Edition' AND (SubValue = 1 OR SubValue=6)

--总账
DECLARE @IsUseacSystem INT = 0 
SELECT @IsUseacSystem = ISNULL(SubValue,0) FROM sysdata WHERE SubName = 'isuseacsystem'

--移动加权=0	先进先出=1	后进先出=2	手工指定=3
DECLARE @IsCosting INT = 0
SELECT @IsCosting = ISNULL(SubValue,0) FROM sysdata WHERE SubName = 'costing'

DECLARE @IsInvoice INT = 0

SELECT @IsInvoice = ISNULL(SubValue,0) FROM sysdata WHERE SubName = 'IsInvoice'

DECLARE @serialrelation INT = 0
select @serialrelation=Value from Userconfig where ConfigName='serialrelation'

 --实物库存
DECLARE @isFactStock INT = 0
SELECT @isFactStock = ISNULL(SubValue,0) FROM sysdata WHERE SubName = 'isphysicalsstock'
--组合品
DECLARE @useCombine INT=0 
SELECT @useCombine = ISNULL(SubValue,0) FROM sysdata WHERE SubName = 'combinationproduct'

--启用上架
DECLARE @useonshelves  int =0
 SELECT @useonshelves = ISNULL(SubValue,0) FROM sysdata WHERE SubName = 'useonshelves'
 
--启用拣货
DECLARE @usepickgoods INT = 0
 SELECT @usepickgoods = ISNULL(SubValue,0) FROM sysdata WHERE SubName = 'usepickgoods'
 
--启用运输
DECLARE @usetransport INT = 0 
SELECT @usetransport = ISNULL(SubValue,0) FROM sysdata WHERE SubName = 'usetransport'
--usepickgoods  usetransport

--门店配送
DECLARE @usepostrans INT = 0
SELECT  @usepostrans = ISNULL(Value,0) FROM dbo.Userconfig WHERE ConfigName = 'usepostrans'

CREATE TABLE #PrintConfig
(
	billtype INT,
	Billtypes VARCHAR(10),
	billname  VARCHAR(100),
	addstate	INT,
	savestate	INT,
	passstate	INT,
	savealert	INT,
	passalert	INT,
	printnum	INT
)

INSERT INTO #PrintConfig
SELECT 0 AS BillType, 0 AS BillTypes, '全选全清' AS billname,0 as addstate,0 as savestate,0 as passstate,0 as savealert,0 as passalert,null AS printnum

INSERT INTO #PrintConfig
SELECT p.BillType, p.BillTypes, b.BillName, p.AddState,p.SaveState,p.PassState,p.SaveAlert,p.PassAlert,p.PrintNum
FROM BillPrintConfig p
INNER JOIN
(
	SELECT BillName,Billtypes,Billtype FROM BillName WHERE Billtype NOT IN (181,183,307)
	UNION ALL
	SELECT BillName,6 AS Billtypes,Billtype  FROM BillName WHERE Billtype IN (181,183,307)
	UNION ALL
	SELECT '业务员提成规则设置',6,164
	UNION ALL
	SELECT '生产模版',3,127
	UNION ALL
	SELECT '使用登记单',20,208
	UNION ALL
	SELECT '车辆费用单',20,209
	
) b ON b.Billtype = p.BillType
WHERE P.BillTypes = @Flag
	  AND(@IsA8 = 1 OR (@IsA8=0 AND B.Billtype NOT IN(187,188,428,429)))
	  AND(
			@IsCP = 1 AND B.Billtype NOT IN(78,84,85) --卡片模式下排查项目的单据
			OR 
			@IsCP = 0 AND B.Billtype NOT IN(212,213,214,307)--项目模式下排查卡片类的单据
		 )
	  AND(
			@IsSerial = 0 AND B.Billtype NOT IN(203)
			OR
			@IsSerial = 1
		  )
	  AND(
			(@IsA8 <> 1 OR @IsUseacSystem = 0) AND B.Billtype NOT IN(310)
			OR
			(@IsA8 = 1 AND @IsUseacSystem = 1)
		 ) AND(
			@IsCosting = 0 OR @IsCosting <> 0 AND B.Billtype NOT IN(205)
		 )
	And (@IsInvoice=1 or (@IsInvoice=0 ANd b.Billtype not in(400,401,402,403,404,405)))
	And (@serialrelation=0 or (@serialrelation=1 ANd b.Billtype not in(203)))
	AND (@isFactStock=1 OR (@isFactStock=0 AND b.Billtype NOT IN(418,419,420,421,422)))
	AND (@useCombine=1 OR (@useCombine=0 AND b.Billtype NOT IN(12,46,313))	 )
	AND (@useonshelves=1 OR (@useonshelves=0 AND b.Billtype NOT IN(412))  )
	AND (@usepickgoods=1 OR (@usepickgoods=0 AND b.Billtype NOT IN(413)) )
	AND (@usetransport=1 OR (@usetransport=0 AND b.Billtype NOT IN(414)))
	AND (@usepostrans=1 OR (@usepostrans=0 AND b.BillType NOT IN (326,327,328,329)))
	AND (@Flag=6 AND B.Billtype NOT IN(411,410) OR @Flag<>6)
	AND (@ProInfo!=4 OR (@ProInfo=4 AND B.Billtype NOT IN(208,209)))	
	 
ORDER BY P.SortID

SELECT * FROM #PrintConfig WHERE ((@ProInfo=4 AND Billtype NOT IN(148,150,149,151,139,126,165,166,167,168,169,170,171,172,173,174,175,307,311,209,400,401,402,403,404,405,187,188,203,326,327,328,329)) OR @ProInfo<>4)

DROP TABLE #PrintConfig	  
--PRINT(@SQL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (SELECT * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BillStockDistributing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BillStockDistributing]
GO







/*
	作者：冯波
	日期：2010-08-09
	描述：单据库存分布表(不需要判断商品和仓库的权限范围)
	
	--梁晰 2017-03-23 GoodsStocks_Draft没有TypeId字段
*/

CREATE    PROCEDURE Web_BillStockDistributing
(
	@OperatorID 	varchar(100),   --操作员id
	@PTypeId		varchar(8000),	--商品Id
	@stypeid		VARCHAR(MAX),
	@Parid   			varchar(100)='00000',    --商品的父节点号
	@szKtypeId  		varchar(8000)='',         --仓库id号
	@sortfield 			varchar(20),            --按何种方式排序
	@EntryCode			varchar(200),			--商品条码
	@Standard			varchar(200),			--商品规格
	@Type				varchar(200),			--商品型号
	@Area				varchar(200),			--商品产地
	@virtualqtysql  VARCHAR(max)='isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)',
	@nostype            varchar(200),
	@stotype			varchar(200)='1'			--"单据助手下库存分布上仓库权限有效" 权限,默认拥有权限的仓库
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
if(@nostype = '1')
INSERT INTO #GetSelectSTypeId(TypeId) values (@stypeid)
else 
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)


DECLARE @SQL varchar(MAX)  

--- 虚拟库存

--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
        @Lendqty NVARCHAR(2000),
        @Borrowqty NVARCHAR(2000),
		@RQty NVARCHAR(2000),
		@CQty NVARCHAR(2000),
		@BuyOrderQty NVARCHAR(2000),
		@BuyReachQty NVARCHAR(2000),
		@SaleOrderQty NVARCHAR(2000),
		@SaleReachQty NVARCHAR(2000),
		@UnitRate NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
		@BaseUnitName NVARCHAR(2000),
        @temptable  NVARCHAR(2000),
         @temptable1 NVARCHAR(2000)
SET @temptable=' inner JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') c ON o.ptypeID=c.typeID'
SET @temptable1=' LEFT JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') c ON a.typeID=c.typeID'

SELECT  @Qty='o.Qty',
		@Lendqty='o.Lendqty',
		@Borrowqty='o.Borrowqty',   
		@BuyReachQty='o.BuyReachQty', 
		@RQty='o.RQty',        
		@CQty='o.CQty',        
		@BuyOrderQty='o.BuyOrderQty', 
		@BuyReachQty='o.BuyReachQty', 
		@SaleOrderQty='o.SaleOrderQty',
		@SaleReachQty='o.SaleReachQty',
		@UnitRate = 'c.baseUnitRate',
		@UnitName = 'c.baseunitfullname',
		@BaseUnitName = 'c.baseunitfullname'

--------多单位计算End---------
-----------------------------------------------------------------------------------------------------------------------------


--商品
CREATE TABLE #GetManPTypeId
(
	TypeId			varchar(100)
)
CREATE UNIQUE CLUSTERED INDEX [Ptypeidx] ON [dbo].[#GetManPTypeId] 
(
	[typeId]
)

SELECT @SQL='INSERT INTO #GetManPTypeId SELECT p.typeId FROM 
             ptype p INNER JOIN F_GetManDetailPType('''+@OperatorID+''') mp	ON mp.TypeId=p.typeId WHERE 1=1 and p.typeid<>''0000'''
        
        IF @EntryCode<>''
		SELECT @SQL = @SQL +'   AND ISNULL(p.EntryCode,'''') LIKE '+CHAR(39)+'%'+@EntryCode+'%'+CHAR(39)+''		
		IF @Standard<>''
		SELECT @SQL = @SQL +' AND ISNULL(p.Standard,'''')  LIKE '+CHAR(39)+'%'+@Standard+'%'+CHAR(39)+''
		IF @Type<>''
		SELECT @SQL = @SQL +' AND ISNULL(p.[Type],'''')  LIKE '+CHAR(39)+'%'+@Type+'%'+CHAR(39)+''
		IF @Area<>''
		SELECT @SQL = @SQL +' AND ISNULL(p.Area,'''')  LIKE '+CHAR(39)+'%'+@Area+'%'+CHAR(39)+''
EXEC(@SQL)			


--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF(@stotype='1')
BEGIN
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT sk.TypeId FROM F_BaseGetAllManagerBaseTypeId(@szKTypeId,4,@OperatorID) sk
	INNER JOIN stock S ON sk.Typeid=S.Typeid
	INNER JOIN #GetSelectSTypeId ST ON S.STYPEID=ST.TYPEID
END
ELSE IF(@stotype='0')
BEGIN
	INSERT INTO #GetManKTypeId(TypeId)
	SELECT S.TypeId FROM STOCK S INNER JOIN #GetSelectSTypeId ST ON S.STYPEID=ST.TYPEID
END





CREATE TABLE #GetManPTypeAll
(
	TypeId			varchar(100),
	FullName        varchar(200),
	UserCode        varchar(100),
	EntryCode		varchar(100),
	[Standard]		varchar(100),
	[Type]			varchar(20),
	Area			varchar(30),
	Sonnum          int,
	Leveal          int,
	Parid           varchar(200),
	unit1           varchar(100),
	unit2           varchar(100),
	unitrate1       varchar(100),
	IsService       INT 
)

CREATE UNIQUE CLUSTERED INDEX [PtypeAllidx] ON [dbo].[#GetManPTypeAll] 
(
	[typeId]
)

SET @SQL='INSERT INTO #GetManPTypeAll SELECT P.TypeId,P.FullName,P.UserCode,P.EntryCode,P.Standard,P.Type,P.Area,P.Sonnum,P.Leveal,
         P.Parid,P.unit1,P.unit2,P.unitrate1,p.IsService FROM F_GetManPTypeAll('''+@OperatorID+''') P '


EXEC(@SQL)



DECLARE @MMPtypeid VARCHAR(100)
SET @MMPtypeid=''

IF LEFT(@parid,len(@MMPtypeid))<>@MMPtypeid SET @parid=LEFT(@MMPtypeid,len(@MMPtypeid)-5)
IF @Parid='' SET @Parid='00000'   ---肖伟 2002-06-27加速库存状况查询,并补漏:
                                  ---如果某操作员设置了权限,并浏览第一层,那么此时的Parid='',什么商品都看不到

IF @szKtypeId='' OR @szKtypeId='00000'   SELECT @szKtypeId='%'	-- 全部仓库
		
CREATE TABLE #DGS
(
	PTypeId		varchar(100),
	RQty		 NUMERIC(24, 10) ,
	CQty		 NUMERIC(24, 10) ,
	TypeId      varchar(100)
)


--草稿库存

--计算普通单据草稿库存
SELECT	BillNumberId,
		BillType,
		KTypeId,
		KTypeId2
INTO	#BillIndex
FROM	BillIndex
WHERE	BillType IN (34,6,161,11,45,215,160,17,21,16,9,14,144,146,140,142,305,126,139,183,187,188,201,202)
		AND Draft = 1
		AND IfWx = 0


--维修单据草稿库存
SELECT	BillNumberId,
		BillType,
		KTypeId,
		KTypeId2
INTO	#WxBillIndex
FROM	BillIndex
WHERE	BillType IN (166,168,172,173,174,178,191,196,197)
		AND Draft = 1

INSERT INTO #DGS
(
	PTypeId,
	RQty,
	CQty,
	TypeId
)
SELECT	B.PTypeId,
		ISNULL(SUM(B.RQty),0) AS RQty,
		ISNULL(SUM(B.CQty),0) AS CQty,
		KtypeId AS Typeid
FROM GoodsStocks_Draft B INNER JOIN #GetManPTypeId P ON P.TypeId=B.PtypeId			
              INNER	JOIN	#GetManKTypeId K ON B.KtypeId = K.TypeId
			GROUP BY B.PTypeId,KtypeId



CREATE TABLE #LeftJoinTable
(
	TypeId			 VARCHAR(50),
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	Qty				 NUMERIC(24, 10) ,
	Lendqty			 NUMERIC(24, 10) ,
	Borrowqty		 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) ,
	SaleReachQty	 NUMERIC(24, 10) ,
	BuyReachQty		 NUMERIC(24, 10) ,
	KTypeId         VARCHAR(50)
)

SELECT @SQL='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	KTypeId
	
)
		SELECT	o.PTypeId AS TypeId,
				'+@RQty+',
				'+@CQty+',
				0 AS Qty,
				0 AS Lendqty,
				0 AS Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty,
				0 AS SaleReachQty,
				0 AS BuyReachQty,
				o.TypeId AS KTypeId
		FROM	#DGS o'+ @temptable	
EXEC (@SQL)
		
SELECT @sql ='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	KTypeId
)		
		
		SELECT 	p.typeid,
				0 AS RQty,
				0 AS CQty,
				SUM('+@qty+') AS qty,
				0 AS Lendqty,
				0 AS Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty,
				0 AS SaleReachQty,
				0 AS BuyReachQty,
				k.TypeId
        FROM 	goodsstocks o 
                inner join #GetManPTypeID p on p.typeid=o.ptypeid and o.ptypeid='''+@PTypeId+'''
				inner join #GetManKTypeId k on o.KTypeId=k.TypeId'+ @temptable
		IF @parid = '00000'
			SELECT @SQL = @SQL +' WHERE 1=1'
		ELSE
			SELECT @SQL = @SQL +' WHERE o.ptypeid LIKE '''+@parid+'%'''
			
		SELECT @SQL=@SQL+' GROUP BY p.typeid,k.TypeId'
EXEC (@SQL)		
		
SELECT @sql ='		
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	KTypeId
)					
        SELECT 	a.typeid,
				0 AS RQty,
				0 AS CQty,
				0 AS qty,
				SUM(o.Lend-o.LendBack)/'+@UnitRate+' AS Lendqty,
				SUM(o.Borrow-o.BorrowBack)/'+@UnitRate+' AS  Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty,
				0 AS SaleReachQty,
				0 AS BuyReachQty,
				k.typeid
		FROM 	V_LendStatus o 
		       inner join #GetManPTypeID a on a.typeid=o.ptypeid and o.ptypeid='''+@PTypeId+'''
		       inner join #GetManKTypeId k on o.ktypeid=k.typeid' + @temptable+'
				 GROUP BY a.typeid,k.TypeId,'+@UnitRate
EXEC (@SQL)		
				
SELECT @sql ='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	KTypeId
)	
        SELECT 	a.typeid,
				0 AS RQty,
				0 AS CQty,
				0 AS qty,
				0 AS LendQty,
				0 AS BorrowQty,
				CASE WHEN SUM(ISNULL(O.SaleOrderQty,0)-ISNULL(O.LimitSaleQty,0)) >=0 
				THEN SUM(ISNULL(O.SaleOrderQty,0)-ISNULL(O.LimitSaleQty,0)) ELSE 0 
				END AS SaleOrderQty,
				CASE WHEN SUM(ISNULL(O.BuyOrderQty,0)-ISNULL(O.LimitBuyQty,0))>=0 
				THEN SUM(ISNULL(O.BuyOrderQty,0)-ISNULL(O.LimitBuyQty,0)) ELSE 0 
				END AS BuyOrderQty,
				0 AS SaleReachQty,
				0 AS BuyReachQty,
				k.typeid		 
        FROM 	GoodsStocks_order o
				inner join #GetManPTypeID a on a.typeid=o.ptypeid and o.ptypeid='''+@PTypeId+'''
				inner join #GetManKTypeId k on o.KTypeId=k.typeid '+ @temptable
					

	SELECT @SQL=@SQL+' GROUP BY a.typeid,k.TypeId'
EXEC(@SQL)

SELECT @SQL='
	SELECT	a.typeid as pid,
			a.fullname,
			a.usercode,
			a.EntryCode,
			a.Standard,
			a.Type,
			a.Area,
			a.sONnum,
			a.leveal,
			a.parid,
			a.unit1,
			a.unit2,
			a.unitrate1,
			o.ktypeid as typeid,
			ISNULL(SUM(o.qty),0) AS qty,
			ISNULL(SUM(o.Lendqty),0) AS Lendqty,
			ISNULL(SUM(o.borrowqty),0) AS Borrowqty,
			ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.borrowqty),0)-ISNULL(SUM(o.lendqty),0) AS FactQty,
			ISNULL(SUM(o.rqty),0) AS RQty,
			ISNULL(SUM(o.cqty),0) AS CQty,
			ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.rqty),0)-ISNULL(SUM(o.cqty),0) AS KFHQty,
			CASE
				WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
				ELSE 0
			END AS BuyOrderQty,
			CASE 
				WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0) 
				ELSE 0
			END AS SaleOrderQty,
			CASE 
				WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0) THEN  ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
				WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  THEN ISNULL(SUM(o.qty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
				WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0)  THEN ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
				WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  THEN ISNULL(SUM(o.qty),0)
			END AS SaleCanQty,
			case when a.Sonnum>0 then null else   '+@UnitName+' end AS unitname,
			case when a.Sonnum>0 then null else   '+@BaseUnitName+' end AS baseunitname,
			case when a.Sonnum>0 then null else  '+@UnitRate+' end AS unitrate,
			o.KTypeId,
			a.IsService,
			cast(0 as varchar(200)) as virtualqtysql,
			'''+@OperatorID+'''  as ope,
			'''+@stypeid+'''   as sid
	INTO #result			
	FROM #GetManPTypeAll a 
	LEFT JOIN #LeftJoinTable o ON LEFT(o.typeid,LEN(a.typeid))=a.typeid '+ @temptable1
	+	
	' where	a.typeid= '''+@PTypeId+'''
	
	'			

SELECT @SQL = @SQL +' 
	GROUP BY	a.typeid,
				a.fullname,
				a.usercode,
				a.EntryCode,
				a.Standard,
				a.Type,
				a.Area,
				a.sONnum,
				a.leveal,
				a.parid,
				a.unit1,
				a.unitrate1,
				a.unit2,
				a.IsService,
				o.KTypeId,	
			case when a.Sonnum>0 then null else '+@UnitName+' end,
			case when a.Sonnum>0 then null else	 '+@BaseUnitName+' END,
			case when a.Sonnum>0 then null else '+@UnitRate+' END '
IF @sortfield<>'' SELECT @SQL=@SQL+' ORDER BY a.fullname' ELSE SELECT @SQL=@SQL+' ORDER BY a.usercode '

EXEC(@SQL)

SET @SQL=@SQL+'
DECLARE @pid NVARCHAR(200),
        @kid NVARCHAR(200),
        @tempres varchar(200),
        @ope varchar(100),
        @sid varchar(max)

		
DECLARE TC CURSOR FOR
	SELECT  A.pId,A.ktypeid,A.ope,A.sid FROM #result A
OPEN TC

FETCH NEXT FROM TC INTO @pid,@kid,@ope,@sid

WHILE @@FETCH_STATUS = 0
BEGIN
   
  
   
   
   CREATE TABLE #res(res	varchar(200))
   insert into #res exec Gp_GetVirtualStockByConfig @pid ,@ope,@kid,@sid
   select @tempres=res from #res

   
   update #result set virtualqtysql=@tempres where IsService=0 and pid=@pid and ktypeid=@kid

   
   drop table #res

   FETCH NEXT FROM TC INTO @pid,@kid,@ope,@sid
END

CLOSE TC
DEALLOCATE TC
'

SET @SQL=@SQL+'SELECT * FROM #result'
	
EXEC(@SQL)


 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#GetSelectSTypeId]'))
 drop table [dbo].[#GetSelectSTypeId]
 GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#DGS]'))
 drop table [dbo].[#DGS]
 GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#GetManKTypeId]'))
 drop table [dbo].[#GetManKTypeId]
 GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#GetManPTypeId]'))
 drop table [dbo].[#GetManPTypeId]
 GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#GetManPTypeAll]'))
 drop table [dbo].[#GetManPTypeAll]
 GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#LeftJoinTable]'))
 drop table [dbo].[#LeftJoinTable]
 GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#result]'))
 drop table [dbo].[#result]
 GO
 
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BillUniteSearch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BillUniteSearch]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：田小波
	日期：2015-05-20
	描述：单据联查
*/

CREATE PROCEDURE Web_BillUniteSearch
(
	@OperatorId			VARCHAR(100),
	@BillType			VARCHAR(100)=-1,
	@BillNumberID		VARCHAR(400)=-1,--单据编号--
	@BillFlag			VARCHAR(10)=-1
	--用于标识查询哪个数据--
	--（1：采购订单，2：暂估开票，3：成本调价，4：暂估退货，5：暂估入库，6：付款，7：销售订单，8：发货开票，9：发出商品退货，10：发出商品出库，11：收款单）--
	--(12：采购入库单，13：预付款单,14:销售出库单,15:采购退货单,16:采购换货单,17:采购发票,18:委托代销退货,19:委托代销结算,20:委托代销收货,21:零售退货单,22:零售单)--
	--(23:预收款单,24:销售退货单,25:销售换货,26:销售发票,27:受托代销发货,28:受托代销退货,29:受托代销结算,34:费用单，35：采购费用分摊单,43:分支机构调拨入库单,44:分支机构调拨出库单)--
	--(45:调拨申请单,46:同价调拨单,47:变价调拨单,48:要货申请单,49:门店配送单,50:门店配送退货单,51:配送验收单)--
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

DECLARE @BillIndexTable VARCHAR(100),
		@SQL			VARCHAR(8000)
--销售采购订单，42组合品销售
IF @BillFlag in (1,7,42)
BEGIN
	SET @BillIndexTable = 'OrderIndex'
END
else IF @BillFlag in (2,8)
BEGIN
	SET @BillIndexTable = 'ReceiptBillIndex'
END
else IF @BillFlag IN (3,4,5,6,9,10,11,12,13,14,15,16,18,19,20,21,22,23,24,25,27,28,29,35,37,34,36,38,39,40,41,46,47)
BEGIN
	SET @BillIndexTable = 'BillIndex'
END
else IF @BillFlag IN(17,26)
BEGIN
	SET @BillIndexTable='FaPiaoBillIndex'
END
else IF @billflag IN(30,32)
BEGIN
    SET @BillIndexTable = 'FactIndex'
END
else if @BillFlag in(45,48,49,50,51)
	set @BillIndexTable = 'PosAllotApplyBillIndex'

--采购订单
IF @BillFlag=1
BEGIN
	SET @SQL = 'SELECT	AA.*,
						GT.ReachQty,
						GT.ReachTotal,
						GT.ResidueQty,
						GT.ResidueTotal,
						GT.SaleOrderReachQty
				FROM(
				SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.ETypeId,
						B.Stypeid,
						ST.FullName AS STFullName,
						CASE 
						WHEN B.OrderState=''1'' THEN ''已完成''
						WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
						WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
						WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
						WHEN AT.IfAudit=''2'' THEN ''原始草稿''
						WHEN B.OrderState=''0'' THEN ''未完成''
						WHEN AT.IfAudit is null THEN ''原始单据''
						END AS BillStatus,
						E.FullName AS EFullName,
						B.dealbtypeid AS btypepeid,
						DT.FullName AS dbtypeFullname,
						B.btypeid AS btypeid1,
						BT.FullName AS btypeFullname,
						B.DTypeId,
						D.FullName AS dFullname,
						B.TotalQty,
						B.TotalMoney,
						B.redword,
						CE.FullName AS CheckeName,
						B.Comment,
						CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) 
						ELSE B.CID END  AS cid,
						CASE WHEN B.CID=0 THEN
						(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
						ELSE
						(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
						B.Explain
				FROM	'+@BillIndexTable+' B 
						INNER JOIN BType BT ON BT.typeId = B.btypeid
						INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
						INNER JOIN Department D ON D.typeid = B.DtypeId
						INNER JOIN Employee E ON B.etypeid=E.TypeId
						INNER JOIN Employee CE ON B.Checke=CE.TypeId
						INNER JOIN SType ST ON ST.typeId= B.Stypeid
						LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=0 '
				IF @BillType='400'
				BEGIN
					SET @SQL = @SQL+'WHERE B.BillNumberID IN (SELECT OldBillNumberID FROM AppraisalBill A where A.BillNumberID = '+@BillNumberID+'))AA '
				END
				ELSE IF @BillType='300'
				BEGIN
					SET @SQL = @SQL+'WHERE B.BillNumberID IN (SELECT DISTINCT OBB.billNumberId FROM dbo.OrderBill OB INNER JOIN dbo.OrderBill OBB ON OB.OrderID = OBB.SaleOrderID where OB.billNumberID = '+@BillNumberID+'))AA '
				END				
				ELSE IF @BillType='313' --组合品销售订单
				BEGIN
					SET @SQL = @SQL+'WHERE B.BillNumberID IN (SELECT DISTINCT billNumberID FROM orderbill WHERE PTCombinOrderBillDetailID IN (SELECT OrderID FROM dbo.PT_Combin_OrderBillDetail WHERE billNumberID='+@BillNumberID+')))AA '
				END
				ELSE IF @BillType='34'
				BEGIN
					SET @SQL = @SQL+'WHERE B.BillNumberID IN (SELECT billNumberId From OrderBill WHERE OrderID IN (SELECT OrderID FROM BuyBill A where A.BillNumberID = '+@BillNumberID+')))AA '
				END
				ELSE IF @BillType='144'
				BEGIN
					SET @SQL = @SQL+'WHERE B.BillNumberID IN (SELECT billNumberId From OrderBill WHERE OrderID IN (SELECT OrderID FROM CommissionBill A where A.BillNumberID = '+@BillNumberID+' AND A.Type=''144'')))AA '
				END
				ELSE IF @BillType='204'
				BEGIN
				    SET @SQL=@SQL+'where b.billnumberid in (SELECT billNumberID FROM dbo.OrderBill WHERE RequestBillNumberID='+@BillNumberID+'))AA '
				END
				ELSE IF @BillType='185'
				BEGIN
				    SET @SQL=@SQL+'where b.billnumberid in (SELECT billNumberID FROM dbo.OrderBill WHERE AskBillNumberID='+@BillNumberID+'))AA '
				END
				ELSE
				BEGIN
					SET @SQL = @SQL+'WHERE B.BillNumberID IN (SELECT FromBillNumberID FROM OrderBill A where A.BillNumberID = '+@BillNumberID+') AND 1=0)AA '
				END
				SET @SQL = @SQL +'INNER JOIN (
												SELECT	O.billNumberID,
														SUM(O.Qty-O.ReachQty) AS ResidueQty, 
														SUM(ISNULL((O.Qty-O.ReachQty),0)*(O.TaxTotal/O.Qty)) AS ResidueTotal,
														SUM(O.Qty) AS BaseQty,SUM(O.TaxTotal) AS BaseTotal, 
														SUM(O.ReachQty) AS ReachQty,SUM(O.ReachTaxTotal) AS ReachTotal '
				IF @BillType='12'
				BEGIN
					SET @SQL = @SQL +',0 AS SaleOrderReachQty ';
				END
				ELSE
				BEGIN
					SET @SQL = @SQL +',SUM(O.SaleOrderReachQty) AS SaleOrderReachQty ';
				END																	
				set @sql += 'FROM '				
				SET @SQL = @SQL + ' OrderBill O '				
				SET @SQL = @SQL + '														
												
												GROUP BY O.billNumberID
											) GT ON GT.billNumberID=aa.billNumberId
						ORDER BY AA.BillDate DESC'		
END
--销售订单
IF @BillFlag=7
BEGIN
	SET @SQL = 'SELECT	AA.*,
						GT.ReachQty,
						GT.ReachTotal,
						GT.ResidueQty,
						GT.ResidueTotal,
						GT.SaleOrderReachQty ';
		
	IF @Billtype ='12'
	BEGIN
	    SET @sql += ',GT.TotalQty,GT.TotalMoney ';
	END
		
	SET @Sql += 'FROM(
		SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,
				B.Stypeid,
				ST.FullName AS STFullName,
				CASE 
				WHEN B.OrderState=''1'' THEN ''已完成''
				WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
				WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
				WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
				WHEN AT.IfAudit=''2'' THEN ''原始草稿''
				WHEN B.OrderState=''0'' THEN ''未完成''
				WHEN AT.IfAudit is null THEN ''原始单据''
				END AS BillStatus,
				E.FullName AS EFullName,
				B.dealbtypeid AS btypepeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				D.FullName AS dFullname,';

        IF @Billtype != '12'
        BEGIN
            SET @Sql += 'B.totalqty,B.totalMoney,'
        END

		SET @Sql += 'B.redword,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) 
				ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				LEFT JOIN BType BT ON BT.typeId = B.btypeid
				LEFT JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				LEFT JOIN Department D ON D.typeid = B.DtypeId
				LEFT JOIN Employee E ON B.etypeid=E.TypeId
				LEFT JOIN Employee CE ON B.Checke=CE.TypeId
				LEFT JOIN SType ST ON ST.typeId= B.Stypeid
				LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=0
				WHERE B.BillNumberID IN '
				IF @BillType='402'
				BEGIN
					SET @SQL = @SQL+'(SELECT OldBillNumberID FROM SendBill A where A.BillNumberID = '+@BillNumberID+''
				END
				ELSE IF @BillType='11'
				BEGIN
					SET @SQL = @SQL+'(SELECT billNumberId From OrderBill WHERE OrderID IN (SELECT OrderID FROM SaleBill A where A.BillNumberID = '+@BillNumberID+')'
				END
				ELSE IF @BillType='12'
				BEGIN
					SET @SQL = @SQL+'(SELECT billNumberId From PT_Combin_OrderBill WHERE OrderID IN (SELECT OrderID FROM PT_Combin_SaleBill A where A.BillNumberID = '+@BillNumberID+')'
				END
				ELSE IF @BillType='301'
				BEGIN
					SET @SQL = @SQL+'(SELECT DISTINCT OBB.billNumberId FROM dbo.OrderBill OB INNER JOIN dbo.OrderBill OBB ON OB.SaleOrderID = OBB.OrderID where OB.billNumberID = '+@BillNumberID+'
									UNION ALL
									SELECT B.billNumberId FROM OrderIndex A INNER JOIN OrderIndex B ON B.FromBillNumberID=A.billNumberId AND A.billNumberId='+@BillNumberID+''
					
				END
				ELSE IF @BillType='140'
				BEGIN
					SET @SQL = @SQL+'(SELECT billNumberId From OrderBill WHERE OrderID IN (SELECT OrderID FROM CommissionBill A where A.BillNumberID = '+@BillNumberID+' AND A.Type=''140'')'
				END
				ELSE IF @BillType='184'
				BEGIN
				    SET @SQL=@SQL+'(SELECT billNumberID FROM OrderBill WHERE AskBillNumberID='+@BillNumberID+''
				END
				ELSE
				BEGIN
					SET @SQL = @SQL+'(SELECT billNumberId From OrderBill WHERE OrderID IN (SELECT OrderID FROM SaleBill A where A.BillNumberID = '+@BillNumberID+' AND 1=0)'
				END

		SET @SQL = @SQL +'))AA
				INNER JOIN (SELECT O.billNumberID,SUM(O.Qty-O.ReachQty) AS ResidueQty, 
				SUM(ISNULL((O.Qty-O.ReachQty),0)*(O.TaxTotal/O.Qty)) AS ResidueTotal,
				SUM(O.Qty) AS BaseQty,SUM(O.TaxTotal) AS BaseTotal, 
				SUM(O.ReachQty) AS ReachQty,SUM(O.ReachTaxTotal) AS ReachTotal'
		IF @BillType='12'
		BEGIN
			SET @SQL = @SQL +',
				0 AS SaleOrderReachQty ';
		END
		ELSE
		BEGIN
			SET @SQL = @SQL +',
				SUM(O.SaleOrderReachQty) AS SaleOrderReachQty ';
		END
		if @billtype = '12'
		begin
		set @sql += ',SUM(O.qty) AS TotalQty, SUM(O.total) AS TotalMoney ';
		end		
				
		 set @sql += 'FROM '
		IF @BillType='12'
		BEGIN
			SET @SQL = @SQL + ' PT_Combin_OrderBill O '
		END
		ELSE
		BEGIN
			SET @SQL = @SQL + ' OrderBill O '
		END
		SET @SQL = @SQL + ' GROUP BY O.billNumberID) GT ON GT.billNumberID=aa.billNumberId
				ORDER BY AA.BillDate DESC'	
END
--开票--
IF @BillFlag in (2,8)
BEGIN
	SET @SQL = 'SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.Stypeid,	
					ST.FullName AS STFullName,
					B.dealbtypeid AS btypepeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					E.FullName AS efullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					CE.FullName AS CheckeName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,
					B.Comment,
					B.redword,
					B.FaPiaoCode,
					B.FaPiaoType,
					ISNULL(CASE B.redword when 2 then -RB.TotalQty else RB.TotalQty END,0) as TotalQty,
					ISNULL(CASE B.redword when 2 then -RB.NTotalMoney else RB.NTotalMoney END,0) as NTotalMoney,
					ISNULL(CASE B.redword when 2 then -RB.NTaxTotalMoney else RB.NTaxTotalMoney END,0) as NTaxTotalMoney,
					ISNULL(CASE B.redword when 2 then -RB.NTaxMoney else RB.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE B.redword when 2 then -RB.TotalMoney else RB.TotalMoney END,0) as TotalMoney,
					ISNULL(CASE B.redword when 2 then -RB.TaxTotalMoney else RB.TaxTotalMoney END,0) as TaxTotalMoney,
					ISNULL(CASE B.redword when 2 then -RB.TaxMoney else RB.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE B.redword when 2 then -RB.CompleteTotal else RB.CompleteTotal END,0) as CompleteTotal,
					ISNULL(CASE B.redword when 2 then -RB.NCompleteTotal else RB.NCompleteTotal END,0) as NCompleteTotal,
					ISNULL(CASE B.redword when 2 then -RB.ResidueMoney else RB.ResidueMoney END,0) as ResidueMoney,
					ISNULL(CASE B.redword when 2 then -RB.ResidueNMoney else RB.ResidueNMoney END,0) as ResidueNMoney,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=5
					RIGHT JOIN (SELECT R.BillNumberID,SUM(R.Qty) TotalQty,SUM(R.NTotal) NTotalMoney,SUM(R.NTaxMoney) NTaxMoney,SUM(R.NTaxTotal) NTaxTotalMoney,
					SUM(R.Total) TotalMoney,SUM(R.TaxMoney) TaxMoney,SUM(R.TaxTotal) TaxTotalMoney,SUM(R.CompleteTotal) CompleteTotal,
					SUM(R.NCompleteTotal) NCompleteTotal,SUM(R.TaxTotal-R.CompleteTotal) ResidueMoney,SUM(R.NTaxTotal-R.NCompleteTotal) ResidueNMoney
					FROM ReceiptBill R WHERE r.MainBillNumberID  in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')  
					GROUP BY R.BillNumberID) RB ON B.BillNumberID = RB.BillNumberID 
					ORDER BY B.BillDate DESC'
END
--成本调价--
IF @BillFlag=3
BEGIN
	SET @SQL = '
	SELECT 
	ISNULL(CASE B.redword when 2 then -A.total else A.total END,0) as total,
	ISNULL(CASE B.redword when 2 then -A.NTotal else A.NTotal END,0) as NTotal,
	B.*
	FROM(
	SELECT SUM(A.total) AS total,SUM(A.NTotal) AS NTotal,BillNumberId
	FROM AdPriceBill A WHERE'
	IF @BillType='404'
	BEGIN
		SET @SQL=@SQL+ ' A.FromBillNumberID in ('+@BillNumberID+') '
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+ ' A.FromBillID in (SELECT r.ID FROM ReceiptBill r WHERE r.MainBillNumberID= '+@BillNumberID+')'
	END
	SET @SQL=@SQL+ ' GROUP BY BillNumberId) A 
	INNER JOIN (SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,
				B.Stypeid,	
				ST.FullName AS STFullName,
				E.FullName AS EFullName,
				B.dealbtypeid AS btypepeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				B.redword,
				CASE
				WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
				WHEN B.IsIni=1 THEN ''期初单据''
				WHEN B.Ifcheck=''t'' THEN ''已过账'' 
				WHEN AT.IfAudit is null THEN ''原始单据''
				WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
				WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
				WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
				WHEN AT.IfAudit=''2'' THEN ''原始草稿''
				END AS BillStatus,
				D.FullName AS dtypeFullname,
				B.checke,
				CE.FullName AS CheckeName,
				B.Comment,
				B.AdPriceType,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				INNER JOIN BType BT ON BT.typeId = B.btypeid
				INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				INNER JOIN Department D ON D.typeid = B.DtypeId
				INNER JOIN Employee E ON B.etypeid=E.TypeId
				INNER JOIN Employee CE ON B.Checke=CE.TypeId
				LEFT JOIN SType ST ON ST.typeId= B.Stypeid
				LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
				) B ON B.BillNumberId = A.BillNumberId  
				ORDER BY B.BillDate DESC'
END
--暂估退货--
IF @BillFlag=4
BEGIN
	IF @BillType='404'
	BEGIN
		SET @SQL = 'SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoneyEX else AD.InvoiceMoneyEX END,0) as InvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
					WHERE B.BillCode IN(SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in (SELECT MainBillNumberID FROM ReceiptBill R WHERE R.BillNumberID='+@BillNumberID+'))) AI
					INNER JOIN (SELECT AB.BillNumberID,SUM(AB.Qty) AS Qty,SUM(AB.total) AS Total,SUM(AB.NTotal) AS NTotal,
					SUM(AB.TaxMoney) AS TaxMoney,SUM(AB.NTaxMoney) AS NTaxMoney,
					SUM(AB.TaxTotal) AS TaxTotal,SUM(AB.NTaxTotal) AS NTaxTotal,SUM(AB.InvoiceQty) AS InvoiceQty,
					SUM(AB.InvoiceMoney) AS InvoiceMoney,SUM(AB.NInvoiceMoney) AS NInvoiceMoney,
					SUM(AB.InvoiceMoneyEX) AS InvoiceMoneyEX,SUM(AB.NInvoiceMoneyEX) AS NInvoiceMoneyEX,
					SUM(AB.InvoiceNQty) AS InvoiceNQty,
					SUM(CASE WHEN (AB.Qty-AB.InvoiceQty)>=0 THEN (AB.Qty-AB.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(AB.Invoiceqty,0)=0 THEN AB.Total - AB.Invoicemoneyex
					ELSE (AB.Qty-ISNULL(AB.InvoiceQty,0)) * AB.DiscountPrice
					END) AS residueInvoiceMoney,
					SUM(CASE WHEN ISNULL(AB.Invoiceqty,0)=0 THEN AB.NTotal - AB.NInvoicemoneyex
					ELSE (AB.Qty-ISNULL(AB.InvoiceQty,0)) * AB.NDiscountPrice
					END) AS ResiduenInvoiceMoney
					FROM AppraisalBackBill AB GROUP BY AB.BillNumberID) AD ON AD.BillNumberID = AI.BillNumberID
					WHERE AI.BillType=''401''
					ORDER BY AI.BillDate DESC'
	END
	
	ELSE IF @BillType='400'
	BEGIN
		SET @SQL = 'SELECT 
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoneyEX else AD.InvoiceMoneyEX END,0) as InvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty,
					AI.*
					FROM
					(SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,
					SUM(A.NTotal) AS NTotal,SUM(A.TaxMoney) AS TaxMoney,SUM(A.NTaxMoney) AS NTaxMoney,
					SUM(A.TaxTotal) AS TaxTotal,SUM(A.NTaxTotal) AS NTaxTotal,
					SUM(A.InvoiceQty) AS InvoiceQty,SUM(A.InvoiceMoney) AS InvoiceMoney,SUM(A.NInvoiceMoney) AS NInvoiceMoney,
					SUM(A.InvoiceNQty) AS InvoiceNQty,SUM(A.InvoiceMoneyEX) AS InvoiceMoneyEX,
					SUM(A.NInvoiceMoneyEX) AS NInvoiceMoneyEX,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.Invoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
					END) AS residueInvoiceMoney,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney
					FROM AppraisalBackBill A WHERE A.OldBillNumberID  in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')
					GROUP BY A.BillNumberID) AD 
					INNER JOIN 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,		
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI ON AI.BillNumberID = AD.BillNumberID
					ORDER BY AI.BillDate DESC'
	END
	ELSE
	BEGIN
		SET @SQL = 'SELECT 
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoneyEX else AD.InvoiceMoneyEX END,0) as InvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty,
					AI.*
					FROM
					(SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,
					SUM(A.NTotal) AS NTotal,SUM(A.TaxMoney) AS TaxMoney,SUM(A.NTaxMoney) AS NTaxMoney,
					SUM(A.TaxTotal) AS TaxTotal,SUM(A.NTaxTotal) AS NTaxTotal,
					SUM(A.InvoiceQty) AS InvoiceQty,SUM(A.InvoiceMoney) AS InvoiceMoney,SUM(A.NInvoiceMoney) AS NInvoiceMoney,
					SUM(A.InvoiceNQty) AS InvoiceNQty,SUM(A.InvoiceMoneyEX) AS InvoiceMoneyEX,SUM(A.NInvoiceMoneyEX) AS NInvoiceMoneyEX,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.Invoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
					END) AS residueInvoiceMoney,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney
					FROM AppraisalBackBill A WHERE A.OldBillNumberID in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+') 
					GROUP BY A.BillNumberID) AD 
					INNER JOIN 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI ON AI.BillNumberID = AD.BillNumberID
					WHERE 1=0
					ORDER BY AI.BillDate DESC'
	END
END
--暂估入库单
IF @BillFlag=5
BEGIN
	IF @BillType='401'
	BEGIN
		SET @SQL = '
					SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -BB.ABQty else BB.ABQty END,0) as backqty,
					ISNULL(CASE AI.redword when 2 then -BB.ABTotal else BB.ABTotal END,0) as backmoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceQty else AD.ResidueInvoiceQty END,0) as ResidueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.ResiduenInvoiceMoney else AD.ResiduenInvoiceMoney END,0) as ResiduenInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.Stypeid,	
					ST.FullName AS STFullName,
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					B.redword,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
					WHERE B.BillNumberID in (SELECT OldBillNumberID FROM AppraisalBackBill A WHERE A.BillNumberId = '+@BillNumberID+')) AI
					INNER JOIN (SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
					SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
					SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney,
					SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
					SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney,SUM(ISNULL(A.NInvoiceMoneyEX,0)) AS NInvoiceMoneyEX,
					SUM(A.InvoiceNQty) AS InvoiceNQty
					FROM AppraisalBill A 
					GROUP BY A.BillNumberId) AD 
					ON AI.BillNumberId = AD.BillNumberId
					LEFT JOIN (SELECT AB.OldBillNumberID,SUM(ISNULL(AB.Qty,0)) AS ABQty, SUM(ISNULL(AB.Total,0)) AS ABTotal
					FROM AppraisalBackBill AB LEFT JOIN BillIndex BI ON AB.BillNumberId =BI.BillNumberId 
					Where BI.RedWord=0 AND BI.draft=0 GROUP BY AB.OldBillNumberID) BB 
					ON BB.OldBillNumberID= AI.BillNumberId
					ORDER BY AI.BillDate DESC'
	END

	ELSE IF @BillType='404'
	BEGIN
		SET @SQL = 'SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -BB.ABQty else BB.ABQty END,0) as backqty,
					ISNULL(CASE AI.redword when 2 then -BB.ABTotal else BB.ABTotal END,0) as backmoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceQty else AD.ResidueInvoiceQty END,0) as ResidueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.ResiduenInvoiceMoney else AD.ResiduenInvoiceMoney END,0) as ResiduenInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,		
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
					WHERE B.BillNumberID in (SELECT MainBillNumberID FROM ReceiptBill R WHERE R.BillNumberID='+@BillNumberID+')) AI
					INNER JOIN (SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(A.NTotal) AS NTotal,SUM(A.BackQty) AS BackQty,
					SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
					SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney,
					SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney,
					SUM(ISNULL(A.NInvoiceMoneyEX,0)) AS NInvoiceMoneyEX,SUM(A.InvoiceNQty) AS InvoiceNQty
					FROM AppraisalBill A
					GROUP BY A.BillNumberId) AD ON AD.BillNumberID = AI.BillNumberID
					LEFT JOIN (SELECT AB.OldBillNumberID,SUM(ISNULL(AB.Qty,0)) AS ABQty, SUM(ISNULL(AB.Total,0)) AS ABTotal
					FROM AppraisalBackBill AB LEFT JOIN BillIndex BI ON AB.BillNumberId =BI.BillNumberId 
					Where BI.RedWord=0 AND BI.draft=0 GROUP BY AB.OldBillNumberID) BB 
					ON BB.OldBillNumberID= AI.BillNumberId
					WHERE AI.BillType=''400''
					ORDER BY AI.BillDate DESC'
	END
	
	ELSE IF @BillType='301'
	BEGIN
		SET @SQL = '
					SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceQty else AD.ResidueInvoiceQty END,0) as ResidueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.ResiduenInvoiceMoney else AD.ResiduenInvoiceMoney END,0) as ResiduenInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,	
					B.Stypeid,
					ST.FullName AS STFullName,
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					B.redword,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI
					INNER JOIN (SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
					SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
					SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.Invoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
					END) AS ResidueInvoiceMoney,
					SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
					SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney,SUM(ISNULL(A.NInvoiceMoneyEX,0)) AS NInvoiceMoneyEX,
					SUM(A.InvoiceNQty) AS InvoiceNQty
					FROM AppraisalBill A 
					WHERE a.OldBillNumberID in (SELECT BI.BillNumberID FROM OrderIndex BI LEFT JOIN OrderBill BI1 ON BI.billNumberID = BI1.billNumberID WHERE BI1.BillNumberID='+@BillNumberID+')
					GROUP BY A.BillNumberId) AD 
					ON AI.BillNumberId = AD.BillNumberId
					ORDER BY AI.BillDate DESC'
	END
	ELSE
	BEGIN
			SET @SQL = 'SELECT AI.*
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
					WHERE 1=0) AI'
	END
END
--付款单/预付款单--
IF @BillFlag in (6,13)
BEGIN
	SET @SQL = 'SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,	
					B.Stypeid,
					ST.FullName AS STFullName,
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					B.redword,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.IfMulAccount<>0 THEN ''多账户'''
					IF @BillType = '404'
					BEGIN
					 	SET @SQL = @SQL+' ELSE AC.FullName END AS accountName,'
					END
					ELSE
					BEGIN
						SET @SQL = @SQL+' ELSE G.FullName END AS accountName,'
					END
					SET @SQL = @SQL+' ISNULL(CASE B.redword when 2 then -G.total else G.total END,0) as total,
					ISNULL(CASE B.redword when 2 then -G.ntotal else G.ntotal END,0) as ntotal,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid'
					IF @BillType = '404'
					 BEGIN
						SET @SQL = @SQL+' LEFT JOIN Ac_Items AC ON B.atypeid=AC.nid'
					END
					SET @SQL = @SQL+' LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2 '
					IF @BillType in ('300','301')
					BEGIN
						SET @SQL = @SQL+' INNER JOIN (SELECT ac.FullName,p.BillNumberID,SUM(total) AS total,SUM(ntotal) AS ntotal FROM '
						IF @BillFlag = 13
						BEGIN
						 	SET @SQL = @SQL+' PreBill'
						END
						ELSE
						BEGIN
							SET @SQL = @SQL+' PayBill'
						END
						SET @SQL = @SQL+'   p left join OrderIndex o on p.RelevanceBillId = o.billNumberId left join Ac_Items Ac ON o.atypeid=AC.nid where o.billNumberId='+@BillNumberID+'
						 GROUP BY p.BillNumberID,ac.FullName) G ON G.BillNumberId = B.BillNumberId WHERE B.RedWord=0 ORDER BY B.BillDate DESC'
					END
					
				 	ELSE IF @BillType='404'
					BEGIN
						SET @SQL = @SQL+' INNER JOIN (SELECT BillNumberID,SUM(total) AS total,SUM(ntotal) AS ntotal FROM  PayBill GROUP BY BillNumberID) G ON G.BillNumberId = B.BillNumberId
					WHERE B.BillNumberID in (SELECT C.MoneyBillID FROM CompleteTotal C WHERE C.GoodsBillID='+@BillNumberID+' and BillType=404) ORDER BY B.BillDate DESC'
					END
					ELSE
					BEGIN
					SET @SQL = @SQL+'INNER JOIN (SELECT ac.FullName,p.BillNumberID,SUM(p.total) AS total,SUM(ntotal) AS ntotal FROM '
						IF @BillFlag = 13
						BEGIN
							SET @SQL = @SQL + ' PreBill p LEFT JOIN CompleteTotal ct on p.BillNumberId= ct.MoneyBillID 
							LEFT JOIN Ac_Items ac ON p.AtypeId=ac.nid WHERE p.BillType=''190'' AND '
						END
						ELSE
						BEGIN
							SET @SQL = @SQL + 'PayBill p LEFT JOIN CompleteTotal ct on p.BillNumberId= ct.MoneyBillID 
							LEFT JOIN Ac_Items ac ON p.AtypeId=ac.nid WHERE '
						END
						
						SET @SQL = @SQL + ' ct.GoodsBillID = '+@BillNumberID+'  GROUP BY BillNumberID,ac.FullName) G ON G.BillNumberId = B.BillNumberId WHERE B.RedWord=0 ORDER BY B.BillDate DESC'
					END
				
END
--发出商品退货--
IF @BillFlag=9
BEGIN
	IF @BillType='402'
	BEGIN
		SET @SQL = 'SELECT 
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoneyEX else AD.InvoiceMoneyEX END,0) as InvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty,
					AI.*
					FROM
					(SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,
					SUM(A.NTotal) AS NTotal,SUM(A.TaxMoney) AS TaxMoney,SUM(A.NTaxMoney) AS NTaxMoney,SUM(A.TaxTotal) AS TaxTotal,SUM(A.NTaxTotal) AS NTaxTotal,
					SUM(A.InvoiceQty) AS InvoiceQty,SUM(A.InvoiceMoney) AS InvoiceMoney,SUM(A.NInvoiceMoney) AS NInvoiceMoney,
					SUM(A.InvoiceNQty) AS InvoiceNQty,SUM(A.InvoiceMoneyEX) AS InvoiceMoneyEX,SUM(A.NInvoiceMoneyEX) AS NInvoiceMoneyEX,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.Invoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
					END) AS residueInvoiceMoney,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney
					FROM SendBackBill A WHERE A.OldBillNumberID in (SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')
					 GROUP BY A.BillNumberID) AD 
					LEFT JOIN 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账''
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,		
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI 
					ON AI.BillNumberID = AD.BillNumberID
					ORDER BY AI.BillDate DESC'
	END
	
	ELSE IF @BillType='405'
	BEGIN
		SET @SQL = 'SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoneyEX else AD.InvoiceMoneyEX END,0) as InvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
					WHERE B.BillCode IN(SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in (SELECT MainBillNumberID FROM ReceiptBill R WHERE R.BillNumberID='+@BillNumberID+'))) AI
					LEFT JOIN (SELECT AB.BillNumberID,SUM(AB.Qty) AS Qty,SUM(AB.total) AS Total,SUM(AB.NTotal) AS NTotal,SUM(AB.TaxMoney) AS TaxMoney,SUM(AB.NTaxMoney) AS NTaxMoney,
					SUM(AB.TaxTotal) AS TaxTotal,SUM(AB.NTaxTotal) AS NTaxTotal,SUM(AB.InvoiceQty) AS InvoiceQty,SUM(AB.InvoiceMoney) AS InvoiceMoney,SUM(AB.NInvoiceMoney) AS NInvoiceMoney,
					SUM(AB.InvoiceNQty) AS InvoiceNQty,SUM(AB.InvoiceMoneyEX) AS InvoiceMoneyEX,SUM(AB.NInvoiceMoneyEX) AS NInvoiceMoneyEX,
					SUM(CASE WHEN (AB.Qty-AB.InvoiceQty)>=0 THEN (AB.Qty-AB.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(AB.Invoiceqty,0)=0 THEN AB.Total - AB.Invoicemoneyex
					ELSE (AB.Qty-ISNULL(AB.InvoiceQty,0)) * AB.DiscountPrice
					END) AS residueInvoiceMoney,
					SUM(CASE WHEN ISNULL(AB.Invoiceqty,0)=0 THEN AB.NTotal - AB.NInvoicemoneyex
					ELSE (AB.Qty-ISNULL(AB.InvoiceQty,0)) * AB.NDiscountPrice
					END) AS ResiduenInvoiceMoney
					FROM SendBackBill AB GROUP BY AB.BillNumberID) AD ON AD.BillNumberID = AI.BillNumberID
					WHERE AI.BillType=''403''
					ORDER BY AI.BillDate DESC'
	END
	ELSE
	BEGIN
			SET @SQL = 'SELECT A.*
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2
					WHERE 1=0) A'
	END
	
END
--发出商品出库--
IF @BillFlag=10
BEGIN
		SET @SQL = 'SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -BB.SBQty else BB.SBQty END,0) as backqty,
					ISNULL(CASE AI.redword when 2 then -BB.SBTotal else BB.SBTotal END,0) as backmoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoneyEX else AD.InvoiceMoneyEX END,0) as InvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoneyEX else AD.NInvoiceMoneyEX END,0) as NInvoiceMoneyEX,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceQty else AD.ResidueInvoiceQty END,0) as ResidueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.ResiduenInvoiceMoney else AD.ResiduenInvoiceMoney END,0) as ResiduenInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceMoney else AD.ResidueInvoiceMoney END,0) as ResidueInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceNQty else AD.InvoiceNQty END,0) as InvoiceNQty
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2'
					IF @BillType='405'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode IN (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in (SELECT R.MainBillNumberID FROM ReceiptBill R WHERE R.BillNumberID='+@BillNumberID+'))) AI'
					END
					ELSE IF @BillType='300'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select BillNumberId from SendBill s where s.OldBillNumberID='+@BillNumberID+'))) AI'
					END 
					ELSE
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select OldBillNumberID from SendBackBill s where s.BillNumberId='+@BillNumberID+'))) AI'
					END
					SET @SQL=@SQL+' INNER JOIN (SELECT A.BillNumberId,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,SUM(A.NTotal) AS NTotal,
					SUM(A.BackQty) AS BackQty,SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
					SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.Invoicemoneyex
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
					END) AS ResidueInvoiceMoney,
					SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney,
					SUM(A.InvoiceNQty) AS InvoiceNQty,SUM(ISNULL(A.InvoiceMoneyEX,0)) AS InvoiceMoneyEX,SUM(ISNULL(A.NInvoiceMoneyEX,0)) AS NInvoiceMoneyEX'
	IF @BillType IN ('405','300')
	BEGIN
		SET @SQL=@SQL+' FROM SendBill A GROUP BY A.BillNumberId) AD
		 ON AI.BillNumberId = AD.BillNumberId 
		 LEFT JOIN (SELECT SB.OldBillNumberID,SUM(ISNULL(SB.Qty,0)) AS SBQty, SUM(ISNULL(SB.Total,0)) AS SBTotal
		FROM SendBackBill SB LEFT JOIN BillIndex BI ON SB.BillNumberId =BI.BillNumberId 
		WHERE BI.RedWord=0 AND BI.draft=0 GROUP BY SB.OldBillNumberID) BB 
		ON BB.OldBillNumberID= AI.BillNumberId
		 WHERE AI.BillType=''402'''
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+' FROM SendBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId
		LEFT JOIN (SELECT SB.OldBillNumberID,SUM(ISNULL(SB.Qty,0)) AS SBQty, SUM(ISNULL(SB.Total,0)) AS SBTotal
		FROM SendBackBill SB LEFT JOIN BillIndex BI ON SB.BillNumberId =BI.BillNumberId 
		Where BI.RedWord=0 AND BI.draft=0 GROUP BY SB.OldBillNumberID) BB 
		ON BB.OldBillNumberID= AI.BillNumberId'
	END
	SET @SQL= @SQL+' ORDER BY AI.BillDate DESC'
END
--收款单/预收款单--
IF @BillFlag in (11,23)
BEGIN
	SET @SQL = 'SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypepeid,
					DT.FullName as dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName as btypeFullname,
					B.DTypeId,B.redword,
					D.FullName as dtypeFullname,
					B.checke,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.IfMulAccount<>0 THEN ''多账户'''
					IF @BillType = '405'
					BEGIN
					 	SET @SQL = @SQL+' ELSE AC.FullName END AS accountName,'
					END
					ELSE
					BEGIN
						SET @SQL = @SQL+' ELSE G.FullName END AS accountName,'
					END
					SET @SQL = @SQL+' ISNULL(CASE B.redword when 2 then -G.total else G.total END,0) as total,
					ISNULL(CASE B.redword when 2 then -G.ntotal else G.ntotal END,0) as ntotal,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  as cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END as accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid'
					IF @BillType = '405'
					BEGIN
						SET @SQL = @SQL+' LEFT JOIN Ac_Items AC ON B.atypeid=AC.nid'
					END
					SET @SQL = @SQL+' LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2 '
					IF @BillType in ('300','301','313')
					BEGIN
						SET @SQL = @SQL+' INNER JOIN (SELECT ac.FullName,p.BillNumberID,SUM(total) AS total,SUM(ntotal) AS ntotal FROM '
						IF @BillFlag = 23
						BEGIN
						 	SET @SQL = @SQL+' PreBill'
						END
						ELSE
						BEGIN
							SET @SQL = @SQL+' gatheringBill'
						END
						SET @SQL = @SQL+' p left join OrderIndex o on p.RelevanceBillId = o.billNumberId left join Ac_Items Ac ON o.atypeid=AC.nid where o.billNumberId='+@BillNumberID+'
						 GROUP BY p.BillNumberID,ac.FullName) G ON G.BillNumberId = B.BillNumberId WHERE B.RedWord=0 ORDER BY B.BillDate DESC'
					END
					ELSE IF @BillType = '405'
					BEGIN
						SET @SQL =@SQL+' INNER JOIN (SELECT BillNumberID,SUM(total) AS total,SUM(ntotal) AS ntotal FROM  gatheringBill GROUP BY BillNumberID) G ON G.BillNumberId = B.BillNumberId
						WHERE B.RedWord=0 AND B.BillNumberID in (SELECT C.MoneyBillID FROM CompleteTotal C WHERE C.GoodsBillID='+@BillNumberID+'  and BillType=405) ORDER BY B.BillDate DESC'
					END
					ELSE 
					BEGIN
						SET @SQL = @SQL+'INNER JOIN (SELECT ac.FullName,p.BillNumberID,SUM(p.total) AS total,SUM(ntotal) AS ntotal FROM '
						IF @BillFlag = 23
						BEGIN
							SET @SQL = @SQL + ' PreBill p LEFT JOIN CompleteTotal ct on p.BillNumberId= ct.MoneyBillID
							LEFT JOIN Ac_Items ac ON p.AtypeId=ac.nid WHERE p.BillType=''189'' AND '
						END
						ELSE
						BEGIN
							SET @SQL = @SQL + 'gatheringBill p LEFT JOIN CompleteTotal ct on p.BillNumberId= ct.MoneyBillID
							LEFT JOIN Ac_Items ac ON p.AtypeId=ac.nid WHERE '
						END
						
						SET @SQL = @SQL + ' ct.GoodsBillID = '+@BillNumberID+'  GROUP BY BillNumberID,ac.FullName) G ON G.BillNumberId = B.BillNumberId 
						WHERE B.RedWord=0 ORDER BY B.BillDate DESC'
					END

END
--采购入库单
IF @BillFlag=12
BEGIN
	SET @SQL = '
				SELECT AI.*,
				ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
				ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
				ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
				ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceQty else AD.ResidueInvoiceQty END,0) as ResidueInvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.ResiduenInvoiceMoney else AD.ResiduenInvoiceMoney END,0) as ResiduenInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceMoney else AD.ResidueInvoiceMoney END,0) as ResidueInvoiceMoney
				 FROM 
				(SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,
				B.Stypeid,	
				ST.FullName AS STFullName,
				E.FullName AS EFullName,
				B.dealbtypeid AS btypeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				B.redword,
				CASE
				WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
				WHEN B.IsIni=1 THEN ''期初单据''
				WHEN B.Ifcheck=''t'' THEN ''已过账'' 
				WHEN AT.IfAudit is null THEN ''原始单据''
				WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
				WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
				WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
				WHEN AT.IfAudit=''2'' THEN ''原始草稿''
				END AS BillStatus,	
				D.FullName AS dtypeFullname,
				B.checke,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				LEFT JOIN BType BT ON BT.typeId = B.btypeid
				LEFT JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				LEFT JOIN Department D ON D.typeid = B.DtypeId
				LEFT JOIN Employee E ON B.etypeid=E.TypeId
				LEFT JOIN Employee CE ON B.Checke=CE.TypeId
				INNER JOIN SType ST ON ST.typeId= B.Stypeid
				LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI
				INNER JOIN ('
				IF @BillType='301'
				BEGIN
					SET @SQL = @SQL+'SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS ResidueInvoiceMoney,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
				SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney FROM BuyBill A WHERE a.orderid in(SELECT orderid FROM OrderBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+') 
				GROUP BY A.BillNumberId) AD
				ON AI.BillNumberId = AD.BillNumberId
				ORDER BY AI.BillDate DESC'
				END
				ElSE IF @BillType='11'
				BEGIN
					SET @SQL = @SQL+'SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS ResidueInvoiceMoney,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
				SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney FROM BuyBill A WHERE a.FromBillNumberID in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN SaleBill BI1 ON BI.billNumberID = BI1.billNumberID WHERE BI1.BillNumberID='+@BillNumberID+') 
				GROUP BY A.BillNumberId) AD
				ON AI.BillNumberId = AD.BillNumberId
				ORDER BY AI.BillDate DESC'
				END
				ELSE IF @BillType ='6'
				BEGIN
					SET @SQL = @SQL+'SELECT A.BillNumberID,B.BillCode,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS ResidueInvoiceMoney,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
				SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney FROM BuyBill A LEFT JOIN BillIndex B ON A.BillNumberId= B.BillNumberId WHERE a.BillNumberId in(SELECT BI1.OldBillNumberID FROM BuyBackBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+') 
				GROUP BY A.BillNumberId,B.BillCode) AD
				ON AI.BillCode = AD.BillCode
				ORDER BY AI.BillDate DESC'
				END
				ELSE IF @BillType ='126'
				BEGIN
					SET @SQL = @SQL+'SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS ResidueInvoiceMoney,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
				SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney FROM BuyBill A WHERE a.BillNumberId in(SELECT BI1.OldBillNumberID FROM GivemeBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+') 
				GROUP BY A.BillNumberId) AD
				ON AI.BillNumberId = AD.BillNumberId
				ORDER BY AI.BillDate DESC'
				END
				ELSE IF @BillType='161'
				BEGIN
					SET @SQL = @SQL+'SELECT A.BillNumberID,B.BillCode,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS ResidueInvoiceMoney,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
				SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney FROM BuyBill A  LEFT JOIN BillIndex B ON A.BillNumberId= B.BillNumberId WHERE a.BillNumberId in(SELECT BI1.OldBillNumberID FROM BuyGoodsExchangeBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+') 
				GROUP BY A.BillNumberId,B.BillCode) AD
				ON AI.BillCode = AD.BillCode
				ORDER BY AI.BillDate DESC'
				END
				ELSE IF @BillType='205'
				BEGIN
				    SET @SQL=@SQL+'SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS ResidueInvoiceMoney,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
				SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney FROM BuyBill A WHERE a.BillNumberId in(SELECT BI1.FromBillNumberID FROM sharesourcebill BI1 WHERE BI1.BillNumberID='+@BillNumberID+') 
				GROUP BY A.BillNumberId) AD
				ON AI.BillNumberId = AD.BillNumberId
				ORDER BY AI.BillDate DESC'
				END
				ELSE IF @BillType='185'
				BEGIN
				     SET @SQL=@SQL+'SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS ResidueInvoiceMoney,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
				SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney FROM BuyBill A WHERE a.AskBillNumberID='+@BillNumberID+' 
				GROUP BY A.BillNumberId) AD
				ON AI.BillNumberId = AD.BillNumberId
				ORDER BY AI.BillDate DESC'
				END
				ELSE
				BEGIN
					SET @SQL = @SQL+'SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS ResidueInvoiceMoney,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,
				SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney FROM BuyBill A WHERE a.BillNumberId in(SELECT BI1.OldBillNumberID FROM BuyGoodsExchangeBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+') AND 1=0 
				GROUP BY A.BillNumberId) AD
				ON AI.BillNumberId = AD.BillNumberId
				ORDER BY AI.BillDate DESC'
				END
END
--销售出库单--
IF @BillFlag=14
BEGIN
		SET @SQL = 'SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceQty else AD.ResidueInvoiceQty END,0) as ResidueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.ResiduenInvoiceMoney else AD.ResiduenInvoiceMoney END,0) as ResiduenInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceMoney else AD.ResidueInvoiceMoney END,0) as ResidueInvoiceMoney
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,
					B.CostSale,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					Left JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2'
					IF @BillType='34'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select FromBillNumberID from BuyBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					ELSE IF @BillType ='45'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select OldBillNumberID from saleBackBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					ELSE IF @BillType ='160'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select OldBillNumberID from SaleGoodsExchangeBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					ELSE IF @BillType='300'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select BillNumberId from SaleBill s where s.OrderID IN (SELECT OrderID FROM OrderBill WHERE BillNumberID='+@BillNumberID+' )))'
					END
					ELSE IF @BillType='313'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select BillNumberId from PT_Combin_SaleBill s where s.OrderID IN (SELECT OrderID FROM PT_Combin_OrderBill WHERE BillNumberID='+@BillNumberID+' )))'
					END
					ELSE IF @BillType='46'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select OldBillNumberID from PT_Combin_SaleBackBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					ELSE IF @BillType='206'
					BEGIN
					    SET @SQL=@SQL+' WHERE B.BillNumberID in (SELECT BillNumberID FROM BillIndex BI WHERE BI.BillNumberID in(select FromBillNumberID from dbo.ShareSourceBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					ELSE
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select FromBillNumberID from BuyBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					SET @SQL=@SQL+') AI INNER JOIN (SELECT A.BillNumberId,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,SUM(A.NTotal) AS NTotal,
					SUM(A.BackQty) AS BackQty,SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
					SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
					END) AS ResidueInvoiceMoney,
					SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney'
	IF @BillType IN ('34','300','45','160')
	BEGIN
		SET @SQL=@SQL+' FROM SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId'
	END
	ELSE IF @BillType = '313'
	BEGIN
		SET @SQL=@SQL+' FROM PT_Combin_SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId'
	END
	ELSE IF @BillType = '46'
	BEGIN
		SET @SQL=@SQL+' FROM PT_Combin_SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId'
	END
	ELSE IF @BillType='206'
	BEGIN
	    IF (SELECT DISTINCT FromBillType FROM ShareSourceBill WHERE BillNumberId=@BillNumberID)=11
		BEGIN
			--销售出库单
			SET @SQL=@SQL+' FROM SaleBill A GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId'
		END
		ELSE
		BEGIN
		    SET @SQL=@SQL+'  FROM SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId AND 1=2'
		END
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'  FROM SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId AND 1=2'
	END
	SET @SQL= @SQL+' ORDER BY AI.BillDate DESC'
END
--采购退货--
IF @BillFlag=15
BEGIN
	SET @SQL = 'SELECT 
				ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
				ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
				ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
				ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
				AI.*
				FROM
				(SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,
				SUM(A.NTotal) AS NTotal,SUM(A.TaxMoney) AS TaxMoney,SUM(A.NTaxMoney) AS NTaxMoney,
				SUM(A.TaxTotal) AS TaxTotal,SUM(A.NTaxTotal) AS NTaxTotal,
				SUM(A.InvoiceQty) AS InvoiceQty,SUM(A.InvoiceMoney) AS InvoiceMoney,SUM(A.NInvoiceMoney) AS NInvoiceMoney,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.Invoicemoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS residueInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney
				FROM BuyBackBill A WHERE A.OldBillNumberID  in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')
				GROUP BY A.BillNumberID) AD 
				INNER JOIN 
				(SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,
				B.redword,
				B.Stypeid,
				ST.FullName AS STFullName,
				CASE
				WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
				WHEN B.IsIni=1 THEN ''期初单据''
				WHEN B.Ifcheck=''t'' THEN ''已过账'' 
				WHEN AT.IfAudit is null THEN ''原始单据''
				WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
				WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
				WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
				WHEN AT.IfAudit=''2'' THEN ''原始草稿''
				END AS BillStatus,		
				E.FullName AS EFullName,
				B.dealbtypeid AS btypeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				D.FullName AS dtypeFullname,
				B.checke,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				INNER JOIN BType BT ON BT.typeId = B.btypeid
				INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				INNER JOIN Department D ON D.typeid = B.DtypeId
				INNER JOIN Employee E ON B.etypeid=E.TypeId
				INNER JOIN Employee CE ON B.Checke=CE.TypeId
				INNER JOIN SType ST ON ST.typeId= B.Stypeid
				LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI ON AI.BillNumberID = AD.BillNumberID'
			IF @BillType!= '34'
			BEGIN
				SET @SQL = @SQL+' WHERE 1=0 '
			END
				SET @SQL = @SQL+' ORDER BY AI.BillDate DESC'
	
END
--采购换货--
IF @BillFlag=16
BEGIN
	SET @SQL = 'SELECT 
				ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
				ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
				ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
				ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
				AI.*
				FROM
				
				(SELECT A.BillNumberID,SUM(B.Qty) AS Qty,SUM(B.total) AS Total,
				SUM(B.NTotal) AS NTotal,SUM(B.TaxMoney) AS TaxMoney,SUM(B.NTaxMoney) AS NTaxMoney,
				SUM(b.TaxTotal) AS TaxTotal,SUM(b.NTaxTotal) AS NTaxTotal,
				SUM(B.InvoiceQty) AS InvoiceQty,SUM(B.InvoiceMoney) AS InvoiceMoney,SUM(B.NInvoiceMoney) AS NInvoiceMoney,
				SUM(CASE WHEN (B.Qty-B.InvoiceQty)>=0 THEN (B.Qty-B.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(B.Invoiceqty,0)=0 THEN B.Total - B.Invoicemoney
				ELSE (B.Qty-ISNULL(B.InvoiceQty,0)) * B.DiscountPrice
				END) AS residueInvoiceMoney,
				SUM(CASE WHEN ISNULL(b.Invoiceqty,0)=0 THEN b.NTotal - b.NInvoicemoney
				ELSE (b.Qty-ISNULL(b.InvoiceQty,0)) * b.NDiscountPrice
				END) AS ResiduenInvoiceMoney
				FROM BuyGoodsExchangeBill A 
				INNER JOIN BuyGoodsExchangeBill B ON A.BillNumberId=B.BillNumberId AND B.InOrOut=''I''
				
				WHERE A.OldBillNumberID in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')
				AND A. InOrOut=''O''			
				GROUP BY A.BillNumberID) AD 
				INNER JOIN 
				(SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,
				B.redword,
				B.Stypeid,
				ST.FullName AS STFullName,
				CASE
				WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
				WHEN B.IsIni=1 THEN ''期初单据''
				WHEN B.Ifcheck=''t'' THEN ''已过账'' 
				WHEN AT.IfAudit is null THEN ''原始单据''
				WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
				WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
				WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
				WHEN AT.IfAudit=''2'' THEN ''原始草稿''
				END AS BillStatus,		
				E.FullName AS EFullName,
				B.dealbtypeid AS btypeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				D.FullName AS dtypeFullname,
				B.checke,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				INNER JOIN BType BT ON BT.typeId = B.btypeid
				INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				INNER JOIN Department D ON D.typeid = B.DtypeId
				INNER JOIN Employee E ON B.etypeid=E.TypeId
				INNER JOIN Employee CE ON B.Checke=CE.TypeId
				INNER JOIN SType ST ON ST.typeId= B.Stypeid
				LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI ON AI.BillNumberID = AD.BillNumberID'
		IF @BillType!= '34'
		BEGIN
			SET @SQL = @SQL+' WHERE 1=0 '
		END
			SET @SQL = @SQL+' ORDER BY AI.BillDate DESC'
END
--采购/销售发票--
IF @BillFlag in (17,26)
BEGIN
	SET @SQL = 'SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,	
					B.Stypeid,
					ST.FullName AS STFullName,
					B.dealbtypeid AS btypepeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					E.FullName AS efullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					CE.FullName AS CheckeName,
					CASE
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,
					B.Comment,
					B.FaPiaoCode,
				    0 as CompleteTotal,
					0 as NCompleteTotal,
					0 as ResidueMoney,
					0 as ResidueNMoney,
					B.FaPiaoType,
					ISNULL(RB.TotalQty,0) as TotalQty,
					ISNULL(RB.NTotalMoney,0) as NTotalMoney,
					ISNULL(RB.NTaxTotalMoney,0) as NTaxTotalMoney,
					ISNULL(RB.NTaxMoney,0) as NTaxMoney,
					ISNULL(RB.TotalMoney,0) as TotalMoney,
					ISNULL(RB.TaxTotalMoney,0) as TaxTotalMoney,
					ISNULL(RB.TaxMoney,0) as TaxMoney,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=5
					RIGHT JOIN (SELECT R.BillNumberID,SUM(R.Qty) TotalQty,SUM(R.NTotal) NTotalMoney,SUM(R.NTaxMoney) NTaxMoney,SUM(R.NTaxTotal) NTaxTotalMoney,
					SUM(R.Total) TotalMoney,SUM(R.TaxMoney) TaxMoney,SUM(R.TaxTotal) TaxTotalMoney
					FROM '
					IF @BillType in ('34','6','161')
						SET @SQL = @SQL+'FaPiaoBill R WHERE BillType=''163'' '
					ELSE IF @BillType in ('11','45','160','12','46')
						SET @SQL = @SQL+'FaPiaoBill R WHERE BillType=''162'' '
					ELSE 
						SET @SQL = @SQL+'FaPiaoBill R WHERE 1=0 '
					SET @SQL=@SQL + ' AND r.MainBillNumberID  in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')  
					GROUP BY R.BillNumberID) RB ON B.BillNumberID = RB.BillNumberID 
					ORDER BY B.BillDate DESC'
END
--委托/受托代销退货--
IF @BillFlag in (18,27)
BEGIN
	SET @SQL = 'SELECT DISTINCT  
				ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
				ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
				ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
				ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
				AI.*
				FROM
				(SELECT A.BillNumberID,ba.BillCode,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,
				SUM(A.NTotal) AS NTotal,SUM(A.TaxMoney) AS TaxMoney,SUM(A.NTaxMoney) AS NTaxMoney,
				SUM(A.TaxTotal) AS TaxTotal,SUM(A.NTaxTotal) AS NTaxTotal
				FROM CommissionBill A LEFT JOIN BillIndex ba ON a.BillNumberId = ba.BillNumberId WHERE'
				IF @BillType='144'
				BEGIN
					SET @SQL = @SQL+' A.Type=''146'' AND'
				END
				ELSE IF @BillType='140'
				BEGIN
					SET @SQL = @SQL+' A.Type=''142'' AND'
				END
				SET @SQL = @SQL + ' A.OldBilliD  in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')
				GROUP BY A.BillNumberID,ba.BillCode) AD 
				INNER JOIN 
				(SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,	
				B.Stypeid,
				ST.FullName AS STFullName,
				CASE
				WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
				WHEN B.IsIni=1 THEN ''期初单据''
				WHEN B.Ifcheck=''t'' THEN ''已过账''
				END AS BillStatus,	
				E.FullName AS EFullName,
				B.dealbtypeid AS btypeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				B.redword,
				D.FullName AS dtypeFullname,
				B.checke,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				INNER JOIN BType BT ON BT.typeId = B.btypeid
				INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				INNER JOIN Department D ON D.typeid = B.DtypeId
				INNER JOIN Employee E ON B.etypeid=E.TypeId
				INNER JOIN SType ST ON ST.typeId= B.Stypeid
				INNER JOIN Employee CE ON B.Checke=CE.TypeId) AI ON AI.billcode = AD.billcode'
			IF @BillType not in('144','140')
			BEGIN
				SET @SQL = @SQL+' WHERE 1=0 '
			END
				SET @SQL = @SQL+' ORDER BY AI.BillDate DESC'
	
END
--委托/受托代销结算--
IF @BillFlag in (19,28)
BEGIN
	SET @SQL = 'SELECT DISTINCT  
				ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
				ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
				ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
				ISNULL(CASE AI.redword when 2 then -BB.ABQty else BB.ABQty END,0) as backqty,
				ISNULL(CASE AI.redword when 2 then -BB.ABTotal else BB.ABTotal END,0) as backmoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NCompleteTotal else AD.NCompleteTotal END,0) as NCompleteTotal,
				ISNULL(CASE AI.redword when 2 then -AD.Residuenmoney else AD.Residuenmoney END,0) as Residuenmoney,
				AI.*
				FROM
				(SELECT A.BillNumberID, ba.billcode,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,
				SUM(A.NTotal) AS NTotal,SUM(A.TaxMoney) AS TaxMoney,SUM(A.NTaxMoney) AS NTaxMoney,
				SUM(A.TaxTotal) AS TaxTotal,SUM(A.NTaxTotal) AS NTaxTotal,SUM(A.NCompleteTotal) AS NCompleteTotal,SUM(A.NTotal-A.NCompleteTotal) AS Residuenmoney,
				SUM(A.InvoiceQty) AS InvoiceQty,SUM(A.InvoiceMoney) AS InvoiceMoney,SUM(A.NInvoiceMoney) AS NInvoiceMoney,
				SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.Invoicemoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
				END) AS residueInvoiceMoney,
				SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoney
				ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
				END) AS ResiduenInvoiceMoney 
				FROM CommissionBill A LEFT JOIN dbo.BillIndex ba ON a.BillNumberId = ba.BillNumberId WHERE'
				IF @BillType in('144','146')
				BEGIN
					SET @SQL = @SQL+' A.Type=''145'' AND'
				END
				ELSE IF @BillType in('140','142')
				BEGIN
					SET @SQL = @SQL+' A.Type=''141'' AND'
				END
				SET @SQL = @SQL + ' A.OldBillNumberID  in(SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')
				GROUP BY A.BillNumberID,ba.billcode) AD 
				INNER JOIN 
				(SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,	
				B.Stypeid,
				ST.FullName AS STFullName,
				CASE
				WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
				WHEN B.IsIni=1 THEN ''期初单据''
				WHEN B.Ifcheck=''t'' THEN ''已过账''
				END AS BillStatus,
				E.FullName AS EFullName,
				B.dealbtypeid AS btypeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				B.redword,
				D.FullName AS dtypeFullname,
				B.checke,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				INNER JOIN BType BT ON BT.typeId = B.btypeid
				INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				INNER JOIN Department D ON D.typeid = B.DtypeId
				INNER JOIN Employee E ON B.etypeid=E.TypeId
				INNER JOIN SType ST ON ST.typeId= B.Stypeid
				INNER JOIN Employee CE ON B.Checke=CE.TypeId) AI ON AI.billcode = AD.billcode
				LEFT JOIN (SELECT AB.OldBillNumberID,SUM(ISNULL(AB.Qty,0)) AS ABQty, SUM(ISNULL(AB.Total,0)) AS ABTotal
						FROM CommissionBill AB LEFT JOIN BillIndex BI ON AB.BillNumberId =BI.BillNumberId 
						Where BI.RedWord=0 AND BI.draft=0 AND AB.Type=''146'' GROUP BY AB.OldBillNumberID) BB ON BB.OldBillNumberID= AI.BillNumberId'
			IF @BillType not in('144','146','140','142')
			BEGIN
				SET @SQL = @SQL+' WHERE 1=0 '
			END
				SET @SQL = @SQL+' ORDER BY AI.BillDate DESC'
	
END
--委托/受托代销收/发货--
IF @BillFlag in (20,29)
BEGIN
	SET @SQL = '
				SELECT DISTINCT AI.*,
				ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
				ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
				ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
				'
				+
					CASE WHEN @BillType IN(300,301,141,142,145,146)
						 THEN 'ISNULL(AD.BQty,0)'
					ELSE
						'ISNULL(CASE AI.redword when 2 then -BB.ABQty else BB.ABQty END,0)'
					END
				+
				' as backqty,
				ISNULL(CASE AI.redword when 2 then -BB.ABTotal else BB.ABTotal END,0) as backmoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal
				 FROM 
				(SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,	
				CASE
				WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
				WHEN B.IsIni=1 THEN ''期初单据''
				WHEN B.Ifcheck=''t'' THEN ''已过账''
				WHEN AT.IfAudit is null THEN ''原始单据''
				WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
				WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
				WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
				WHEN AT.IfAudit=''2'' THEN ''原始草稿''
				END AS BillStatus,
				E.FullName AS EFullName,
				B.dealbtypeid AS btypeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				B.redword,	
				B.Stypeid,
				ST.FullName AS STFullName,
				D.FullName AS dtypeFullname,
				B.checke,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				INNER JOIN BType BT ON BT.typeId = B.btypeid
				INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				INNER JOIN Department D ON D.typeid = B.DtypeId
				INNER JOIN Employee E ON B.etypeid=E.TypeId
				INNER JOIN Employee CE ON B.Checke=CE.TypeId
				INNER JOIN SType ST ON ST.typeId= B.Stypeid
				LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI
				INNER JOIN (SELECT A.BillNumberID,ba.BillCode,SUM(A.Qty) AS Qty,SUM(ISNULL(A.total,0)) AS Total,SUM(ISNULL(A.NTotal,0)) AS NTotal,SUM(A.BackQty) AS BackQty,
				SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
				SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,
				SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal '
				IF @BillType in('300','301')
				BEGIN
					SET @SQL = @SQL+',SUM(ISNULL(A.BQty,0)) AS BQty FROM CommissionBill A LEFT JOIN dbo.BillIndex ba ON a.BillNumberId = ba.BillNumberId WHERE'
						IF @BillType ='301'
						BEGIN
							SET @SQL = @SQL+' A.Type=''144'' AND'
						END
						ELSE IF @BillType ='300'
						BEGIN
							SET @SQL = @SQL+' A.Type=''140'' AND'
						END
					SET @SQL = @SQL + ' A.orderid in(SELECT orderid FROM OrderBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+')'
					SET @SQL = @SQL + 'GROUP BY A.BillNumberId,ba.billCode) AD 
					ON AI.billCode = AD.BillCode
					LEFT JOIN (SELECT AB.OldBillid,SUM(ISNULL(AB.Qty,0)) AS ABQty, SUM(ISNULL(AB.Total,0)) AS ABTotal
						FROM CommissionBill AB LEFT JOIN BillIndex BI ON AB.BillNumberId =BI.BillNumberId 
						Where BI.RedWord=0 AND BI.draft=0 AND AB.Type=''146'' GROUP BY AB.OldBillid) BB ON BB.OldBillid= AI.BillNumberId
					ORDER BY AI.BillDate DESC'
				END
				ELSE IF @BillType in ('146','142')
				BEGIN
						SET @SQL = @SQL+',SUM(ISNULL(A.BQty,0)) AS BQty  FROM CommissionBill A  LEFT JOIN dbo.BillIndex ba ON a.BillNumberId = ba.BillNumberId WHERE'
						IF @BillType ='146'
						BEGIN
							SET @SQL = @SQL+' A.Type=''144'' AND'
						END
						ELSE IF @BillType ='142'
						BEGIN
							SET @SQL = @SQL+' A.Type=''140'' AND'
						END
					SET @SQL = @SQL + ' A.BillNumberId in(SELECT BI1.OldBillid FROM CommissionBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+')'
					SET @SQL = @SQL + 'GROUP BY A.BillNumberId,ba.billcode) AD 
					ON AI.billcode = AD.billcode
					LEFT JOIN (SELECT AB.OldBillid,SUM(ISNULL(AB.Qty,0)) AS ABQty, SUM(ISNULL(AB.Total,0)) AS ABTotal
						FROM CommissionBill AB LEFT JOIN BillIndex BI ON AB.BillNumberId =BI.BillNumberId 
						Where BI.RedWord=0 AND BI.draft=0 AND AB.Type='+@BillType+' GROUP BY AB.OldBillid) BB ON BB.OldBillid= AI.BillNumberId
					ORDER BY AI.BillDate DESC'
				END
				ELSE IF @BillType in ('145','141')
				BEGIN
						SET @SQL = @SQL+' ,SUM(ISNULL(A.BQty,0)) AS BQty FROM CommissionBill A  LEFT JOIN dbo.BillIndex ba ON a.BillNumberId = ba.BillNumberId WHERE'
						IF @BillType ='145'
						BEGIN
							SET @SQL = @SQL+' A.Type=''144'''
						END
						ELSE IF @BillType ='141'
						BEGIN
							SET @SQL = @SQL+' A.Type=''140'''
						END
					SET @SQL = @SQL + ' AND A.BillNumberId in(SELECT BI1.OldBillNumberID FROM CommissionBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+')'
					SET @SQL = @SQL + 'GROUP BY A.BillNumberId,ba.billcode) AD 
					ON AI.billcode = AD.billcode
					LEFT JOIN (SELECT AB.OldBillid,AB.OldBillNumberID,SUM(ISNULL(AB.Qty,0)) AS ABQty, SUM(ISNULL(AB.Total,0)) AS ABTotal
						FROM CommissionBill AB LEFT JOIN BillIndex BI ON AB.BillNumberId =BI.BillNumberId 
						Where BI.RedWord=0 AND BI.draft=0 AND AB.Type='+CASE WHEN @BilLType='145' THEN '146' ELSE '142' END+' GROUP BY AB.OldBillNumberID,AB.OldBillid) BB ON BB.OldBillid= AI.BillNumberId
					ORDER BY AI.BillDate DESC'
				END
				ELSE
				BEGIN
					SET @SQL = @SQL+'FROM BuyBill A LEFT JOIN dbo.BillIndex ba ON a.BillNumberId = ba.BillNumberId WHERE a.BillNumberId in(SELECT BI1.OldBillNumberID FROM CommissionBill BI1 WHERE BI1.BillNumberID='+@BillNumberID+') AND 1=0 '
					SET @SQL = @SQL + 'GROUP BY A.BillNumberId,ba.billcode) AD 
					ON AI.billcode = AD.billcode 
					LEFT JOIN (SELECT AB.OldBillid,SUM(ISNULL(AB.Qty,0)) AS ABQty, SUM(ISNULL(AB.Total,0)) AS ABTotal 
					FROM CommissionBill AB LEFT JOIN BillIndex BI ON AB.BillNumberId =BI.BillNumberId 
					Where BI.RedWord=0 AND BI.draft=0 AND AB.Type=''146'' GROUP BY AB.OldBillid) BB ON BB.OldBillid= AI.BillNumberId
					ORDER BY AI.BillDate DESC'
				END
	
END
--零售退货--
IF @BillFlag=21
BEGIN
			SET @SQL = 'SELECT 
			ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
			ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
			ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
			ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
			ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
			ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
			ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
			ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
			ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
			ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
			AI.*
			FROM
			(SELECT A.BillNumberID,ba.billcode,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,
			SUM(A.NTotal) AS NTotal,SUM(A.TaxMoney) AS TaxMoney,SUM(A.NTaxMoney) AS NTaxMoney,SUM(A.TaxTotal) AS TaxTotal,SUM(A.NTaxTotal) AS NTaxTotal,
			SUM(A.InvoiceQty) AS InvoiceQty,SUM(A.InvoiceMoney) AS InvoiceMoney,SUM(A.NInvoiceMoney) AS NInvoiceMoney
			FROM RetailBackBill A
			LEFT JOIN dbo.BillIndex ba ON a.BillNumberId = ba.BillNumberId WHERE A.OldBillNumberID in (SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')
			 GROUP BY A.BillNumberID, ba.billcode) AD 
			LEFT JOIN 
			(SELECT	B.BillNumberId,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.ETypeId,
			B.redword,
			B.Stypeid,
			ST.FullName AS STFullName,
			CASE
			WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
			WHEN B.IsIni=1 THEN ''期初单据''
			WHEN B.Ifcheck=''t'' THEN ''已过账''
			END AS BillStatus,
			E.FullName AS EFullName,
			B.dealbtypeid AS btypeid,
			DT.FullName AS dbtypeFullname,
			B.btypeid AS btypeid1,
			BT.FullName AS btypeFullname,
			B.DTypeId,
			D.FullName AS dtypeFullname,
			B.checke,
			CE.FullName AS CheckeName,
			B.Comment,
			CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
			CASE WHEN B.CID=0 THEN
			(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
			ELSE
			(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
			B.Explain
	FROM	'+@BillIndexTable+' B 
			INNER JOIN BType BT ON BT.typeId = B.btypeid
			INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
			INNER JOIN Department D ON D.typeid = B.DtypeId
			INNER JOIN Employee E ON B.etypeid=E.TypeId
			INNER JOIN SType ST ON ST.typeId= B.Stypeid
			INNER JOIN Employee CE ON B.Checke=CE.TypeId) AI 
			ON AI.billCode = AD.billCode
			ORDER BY AI.BillDate DESC'
	
END
--零售单--
IF @BillFlag=22
BEGIN
		SET @SQL = 'SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -BB.SBQty else BB.SBQty END,0) as backqty,
					ISNULL(CASE AI.redword when 2 then -BB.SBTotal else BB.SBTotal END,0) as backmoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					INNER JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2 '
					IF @BillType='206'
					BEGIN
					    SET @SQL+=' WHERE B.BillNumberID IN (SELECT BillNumberID FROM BillIndex BI WHERE BI.BillNumberID in (select FromBillNumberID from dbo.ShareSourceBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					ELSE
					BEGIN
					    SET @SQL+=' WHERE B.BillCode IN (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in (SELECT R.OldBillNumberID FROM RetailBackBill R WHERE R.BillNumberID='+@BillNumberID+'))'
					END
					SET @SQL+=') AI 
					INNER JOIN (SELECT A.BillNumberId,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,SUM(A.NTotal) AS NTotal,
					SUM(A.BackQty) AS BackQty,SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
					SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal'
	IF @BillType='215'
	BEGIN
		SET @SQL=@SQL+' FROM RetailBill A GROUP BY A.BillNumberId) AD
		 ON AI.BillNumberId = AD.BillNumberId 
		 LEFT JOIN (SELECT SB.OldBillNumberID,SUM(ISNULL(SB.Qty,0)) AS SBQty, SUM(ISNULL(SB.Total,0)) AS SBTotal
		FROM RetailBackBill SB LEFT JOIN BillIndex BI ON SB.BillNumberId =BI.BillNumberId 
		WHERE BI.RedWord=0 AND BI.draft=0 GROUP BY SB.OldBillNumberID) BB 
		ON BB.OldBillNumberID= AI.BillNumberId
		 WHERE AI.BillType=''305'''
	END
	ELSE IF @BillType='206'
	BEGIN
	    SET @SQL=@SQL+' FROM RetailBill A GROUP BY A.BillNumberId) AD
		 ON AI.BillNumberId = AD.BillNumberId 
		 LEFT JOIN (SELECT SB.OldBillNumberID,SUM(ISNULL(SB.Qty,0)) AS SBQty, SUM(ISNULL(SB.Total,0)) AS SBTotal
		FROM RetailBackBill SB LEFT JOIN BillIndex BI ON SB.BillNumberId =BI.BillNumberId 
		WHERE BI.RedWord=0 AND BI.draft=0 GROUP BY SB.OldBillNumberID) BB 
		ON BB.OldBillNumberID= AI.BillNumberId
		 WHERE AI.BillType=''305'''
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+' FROM RetailBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId
		LEFT JOIN (SELECT SB.OldBillNumberID,SUM(ISNULL(SB.Qty,0)) AS SBQty, SUM(ISNULL(SB.Total,0)) AS SBTotal
		FROM RetailBackBill SB LEFT JOIN BillIndex BI ON SB.BillNumberId =BI.BillNumberId 
		Where BI.RedWord=0 AND BI.draft=0 GROUP BY SB.OldBillNumberID) BB 
		ON BB.OldBillNumberID= AI.BillNumberId AND 1=0'
	END
	SET @SQL= @SQL+' ORDER BY AI.BillDate DESC'
END
--销售退货--
IF @BillFlag=24
BEGIN
SET @SQL = 'SELECT 
		ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
		ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
		ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
		ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
		ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
		ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
		ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
		ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
		ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
		ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
		ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
		ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
		ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
		AI.*
		FROM
		(SELECT A.BillNumberID,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,
		SUM(A.NTotal) AS NTotal,SUM(A.TaxMoney) AS TaxMoney,SUM(A.NTaxMoney) AS NTaxMoney,SUM(A.TaxTotal) AS TaxTotal,SUM(A.NTaxTotal) AS NTaxTotal,
		SUM(A.InvoiceQty) AS InvoiceQty,SUM(A.InvoiceMoney) AS InvoiceMoney,SUM(A.NInvoiceMoney) AS NInvoiceMoney,
		SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
		SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.Invoicemoney
		ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
		END) AS residueInvoiceMoney,
		SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoicemoney
		ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
		END) AS ResiduenInvoiceMoney
		FROM '
IF @BillType='12'
BEGIN
	SET @SQL = @SQL + 'PT_Combin_SaleBackBill A '
END
ELSE
BEGIN
	SET @SQL = @SQL + 'SaleBackBill A '
END
SET @SQL = @SQL + ' WHERE A.OldBillNumberID in (SELECT BI.BillNumberID FROM BillIndex BI LEFT JOIN BillIndex BI1 ON BI.BillCode = BI1.BillCode WHERE BI1.BillNumberID='+@BillNumberID+')
		 GROUP BY A.BillNumberID) AD 
		LEFT JOIN 
		(SELECT	B.BillNumberId,
		B.BillDate,
		B.BillCode,
		B.BillType,
		B.ETypeId,
		B.redword,
		B.Stypeid,
		ST.FullName AS STFullName,
		CASE
		WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
		WHEN B.IsIni=1 THEN ''期初单据''
		WHEN B.Ifcheck=''t'' THEN ''已过账''
		WHEN AT.IfAudit is null THEN ''原始单据''
		WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
		WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
		WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
		WHEN AT.IfAudit=''2'' THEN ''原始草稿''
		END AS BillStatus,		
		E.FullName AS EFullName,
		B.dealbtypeid AS btypeid,
		DT.FullName AS dbtypeFullname,
		B.btypeid AS btypeid1,
		BT.FullName AS btypeFullname,
		B.DTypeId,
		D.FullName AS dtypeFullname,
		B.checke,
		CE.FullName AS CheckeName,
		B.Comment,
		CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
		CASE WHEN B.CID=0 THEN
		(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
		ELSE
		(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
		B.Explain
FROM	'+@BillIndexTable+' B 
		INNER JOIN BType BT ON BT.typeId = B.btypeid
		INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
		INNER JOIN Department D ON D.typeid = B.DtypeId
		INNER JOIN Employee E ON B.etypeid=E.TypeId
		INNER JOIN Employee CE ON B.Checke=CE.TypeId
		INNER JOIN SType ST ON ST.typeId= B.Stypeid
		LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI 
		ON AI.BillNumberID = AD.BillNumberID
		ORDER BY AI.BillDate DESC'
	
END
--销售换货--
IF @BillFlag=25
BEGIN
	SET @SQL = 'SELECT 
				ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
				ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
				ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
				ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
				ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceQty else AD.residueInvoiceQty END,0) as residueInvoiceQty,
				ISNULL(CASE AI.redword when 2 then -AD.residueNInvoiceMoney else AD.residueNInvoiceMoney END,0) as residueNInvoiceMoney,
				ISNULL(CASE AI.redword when 2 then -AD.residueInvoiceMoney else AD.residueInvoiceMoney END,0) as residueInvoiceMoney,
				AI.*
				FROM								
				(SELECT b.BillNumberID
				,SUM(b.totalqty) AS Qty
				,SUM(o.total)-SUM(i.total) AS Total
				,SUM(o.NTotal)-SUM(i.NTotal)  AS NTotal
				,SUM(o.TaxMoney)-SUM(i.TaxMoney)  AS TaxMoney
				,SUM(o.NTaxMoney)-SUM(i.NTaxMoney)  AS NTaxMoney
				,SUM(b.totalmoney)  AS TaxTotal
				,SUM(b.NTotalMoney)  AS NTaxTotal
				,SUM(o.InvoiceQty)-SUM(i.InvoiceQty)  AS InvoiceQty
				,SUM(b.InvoiceMoney)  AS InvoiceMoney
				,SUM(b.NInvoiceMoney)  AS NInvoiceMoney
				,SUM(CASE WHEN (o.Qty-o.InvoiceQty)>=0 THEN (o.Qty-o.InvoiceQty) ELSE 0 END) - SUM(CASE WHEN (i.Qty-i.InvoiceQty)>=0 THEN (i.Qty-i.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty
				,SUM(b.totalmoney)-SUM(b.InvoiceMoney) AS residueInvoiceMoney
				,SUM(b.NTotalMoney)-SUM(b.NInvoiceMoney) AS ResiduenInvoiceMoney
FROM dbo.BillIndex b
INNER JOIN  (SELECT BillNumberId,SUM(qty) AS qty, SUM(total) AS total,SUM(NTotal) AS ntotal,SUM(TaxMoney) AS taxmoney,SUM(NTaxMoney) AS ntaxmoney,SUM(InvoiceQty) AS InvoiceQty FROM  SaleGoodsExchangeBill WHERE BillNumberID IN(SELECT billnumberid FROM SaleGoodsExchangeBill WHERE OldBillNumberID =' + @Billnumberid + ' ) AND InOrOut = ''O'' GROUP BY BillNumberId) o ON o.BillNumberId = b.BillNumberId   
INNER JOIN  (SELECT BillNumberId,SUM(qty) AS qty, SUM(total) AS total,SUM(NTotal) AS ntotal,SUM(TaxMoney) AS taxmoney,SUM(NTaxMoney) AS ntaxmoney,SUM(InvoiceQty) AS InvoiceQty FROM SaleGoodsExchangeBill WHERE OldBillNumberID = ' + @Billnumberid + ' AND InOrOut = ''I'' GROUP BY BillNumberId) i ON i.BillNumberId=b.BillNumberId  		
GROUP BY b.BillNumberID) AD 
				INNER JOIN 
				(SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,
				B.redword,
				B.Stypeid,
				ST.FullName AS STFullName,
				CASE
				WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
				WHEN B.IsIni=1 THEN ''期初单据''
				WHEN B.Ifcheck=''t'' THEN ''已过账'' 
				WHEN AT.IfAudit is null THEN ''原始单据''
				WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
				WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
				WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
				WHEN AT.IfAudit=''2'' THEN ''原始草稿''
				END AS BillStatus,		
				E.FullName AS EFullName,
				B.dealbtypeid AS btypeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				D.FullName AS dtypeFullname,
				B.checke,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				INNER JOIN BType BT ON BT.typeId = B.btypeid
				INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				INNER JOIN Department D ON D.typeid = B.DtypeId
				INNER JOIN Employee E ON B.etypeid=E.TypeId
				INNER JOIN Employee CE ON B.Checke=CE.TypeId
				INNER JOIN SType ST ON ST.typeId= B.Stypeid
				LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2) AI ON AI.BillNumberID = AD.BillNumberID'
		IF @BillType!= '11'
		BEGIN
			SET @SQL = @SQL+' WHERE 1=0 '
		END
			SET @SQL = @SQL+' ORDER BY AI.BillDate DESC'
END

if @billflag in(30,31)
begin

  set @sql = 'SELECT 
                      fi.BillDate,
                      fi.BillNumberId, 
                      fi.BillCode,
                      fi.billtype,
                      fi.redword,
                      s.FullName AS kfullname,
                      s.UserCode AS ktypecode,
                      e.FullName AS efullname,
                      d.FullName AS dtypefullname,
                      ee.FullName AS checkename,
                      fi.Comment,
                      CASE
		                 WHEN fi.redword=''2'' AND fi.Ifcheck=''T'' THEN ''已红冲''
		                 WHEN fi.IsIni=1 THEN ''期初单据''
		                 WHEN fi.Ifcheck=''t'' THEN ''已过账''
		                 WHEN AT.IfAudit is null THEN ''原始单据''
		                 WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
		                 WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
		                 WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
		                 WHEN AT.IfAudit=''2'' THEN ''原始草稿''
		              END AS BillStatus,
	                ISNULL(CASE fi.redword when 2 then -ABS(ISNULL(ad.qty, 0)) else ABS(ISNULL(ad.qty, 0)) END,0) as Qty,
		            fi.explain,
		            bn.BillName
 FROM dbo.FactIndex fi
LEFT JOIN dbo.Stock s ON fi.ktypeid = s.typeId
LEFT JOIN dbo.employee e ON e.typeId = fi.etypeid
LEFT JOIN dbo.employee ee ON ee.typeId = fi.checke
LEFT JOIN dbo.Department d ON d.typeid = fi.dtypeId
LEFT JOIN AuditingBill AT ON AT.BillNumberId = fi.BillNumberID AND AT.BillIndexType=7
LEFT JOIN dbo.BillName bn ON bn.Billtype = ' + @BillType + '
INNER JOIN (
    SELECT a.BillNumberID,SUM(a.qty) AS qty FROM dbo.FactDepotInOut a
    WHERE a.FromBillNumberID = ' + @Billnumberid + ' AND a.FromBillType = ' + @BillType + '    
   GROUP BY a.BillNumberID 
)ad ON ad.BillNumberID = fi.BillNumberId';


if @billflag = 30
begin
set @sql = @sql + ' WHERE fi.billtype = 418 '
end
else if @billflag = 31
begin
set @sql = @sql + ' WHERE fi.billtype = 419 '
end

set @sql = @sql + ' ORDER BY fi.BillDate DESC';

end

if @billflag = 33
begin                    
     declare @table varchar(50);
     declare @dBilltype varchar(50); 
     declare @detailtable varchar(50);
      SELECT @table = IndexTable,@dBilltype = billtype,@detailtable = detailTable FROM dbo.BillName WHERE Billtype = (
          select top 1 frombilltype from FactDepotInOut where billnumberid = @billnumberid 
      );

      set @sql = 'SELECT  b.BillDate,
      b.BillCode,
      b.BillNumberId,
      b.BillType,
      e.FullName AS efullname,
      d.fullname AS dtypefullname, 
      ce.fullname AS checkename,
      b.comment,
      b.redword, 
      CASE
         WHEN b.redword=''2'' AND B.Ifcheck=''T'' THEN ''已红冲''
         WHEN b.IsIni=1 THEN ''期初单据''
         WHEN b.Ifcheck=''t'' THEN ''已过账''
         WHEN AT.IfAudit is null THEN ''原始单据''
         WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
         WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
         WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
         WHEN AT.IfAudit=''2'' THEN ''原始草稿''
     END AS BillStatus, 
     ISNULL(CASE b.redword when 2 then -ABS(ISNULL(bb.qty, 0)) else ABS(ISNULL(bb.qty, 0)) END,0) as Qty,
     ISNULL(CASE b.redword when 2 then -ABS(ISNULL(q.qty, 0)) else ABS(ISNULL(q.qty, 0)) END,0) as rukuqty,
     ISNULL(CASE b.redword when 2 then -(ABS(ISNULL(bb.qty, 0)) - ABS(ISNULL(q.qty, 0))) else (ABS(ISNULL(bb.qty, 0)) - ABS(ISNULL(q.qty, 0))) END,0) as weirukuqty 
FROM ' + @table + ' b '

IF @table = 'PosAllotApplyBillIndex'
	SET @SQL += 'INNER JOIN Employee E ON B.applyetypeid=E.TypeId '
ELSE
	SET @SQL += 'INNER JOIN Employee E ON B.etypeid=E.TypeId '

SET @SQL += '
INNER JOIN Department D ON D.typeid = B.DtypeId 
INNER JOIN Employee CE ON B.Checke = CE.TypeId
LEFT JOIN AuditingBill AT ON AT.BillNumberId = b.BillNumberID   
INNER JOIN(
    SELECT fd.FromBillType,
   fd.FromBillNumberID, 
   CASE WHEN fd.FromBillType IN (71,72,87,88) THEN (SELECT billCode FROM dbo.LendIndex WHERE BillNumberId = fd.FromBillNumberId)
   WHEN fd.FromBillType IN (327,328,329) THEN (SELECT billCode FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId = fd.FromBillNumberId)
				ELSE (SELECT billcode FROM BillIndex WHERE billnumberid = fd.FromBillNumberId)
				END AS FromBillCode 
     FROM dbo.FactDepotInOut fd 
     LEFT JOIN dbo.FactIndex ff ON ff.BillNumberId = fd.BillNumberID  
    WHERE fd.BillNumberID = ' + @BillNumberID + ' AND fd.FromBillType = ' + @dBilltype + ' AND fd.BillType = ' + @BillType + ' 
    GROUP BY fd.FromBillType,fd.FromBillNumberID
)fdq ON fdq.FromBillType = b.BillType AND b.BillCode = fdq.FromBillCode
LEFT JOIN (
    SELECT SUM(fd.qty) AS qty,fd.FromBillNumberID    
     FROM dbo.FactDepotInOut fd 
     LEFT JOIN dbo.FactIndex ff ON ff.BillNumberId = fd.BillNumberID  
    WHERE fd.FromBillType = ' + @dBilltype + ' AND fd.BillType = ' + @BillType + '  AND ff.draft = 0 AND ff.RedWord=0
    GROUP BY fd.FromBillNumberID  
)q on q.FromBillNumberID = fdq.FromBillNumberID 
INNER JOIN(
    SELECT SUM(bb.Qty) AS qty,bb.billnumberid FROM ' + @detailtable + ' bb
    --LEFT JOIN ' + @table + ' bi ON bi.BillNumberId = bb.BillNumberId 
    WHERE 1= 1 ';
if @detailtable = 'disassemblebill'  or @detailtable = 'salegoodsexchangebill' or  @detailtable = 'buygoodsexchangebill' or @detailtable = 'wx_bill_self'
or @detailtable = 'wx_bill_goto'
begin

  if @billtype = 418
  begin
    set @sql += ' AND bb.inorout = ''I''';
  end 
  else if @billtype = 419
  begin
    set @sql += ' AND bb.inorout = ''O''';
  end
end

if @detailtable = 'wx_bill_self' or @detailtable = 'wx_bill_goto' or @detailtable = 'wx_bill_replace'
BEGIN
   set @sql += ' AND bb.wxProperty = 0 '
END

set @sql += ' GROUP BY bb.billnumberid 
)bb ON bb.billnumberid = b.billnumberid';

END

IF @BillFlag=34--费用单
BEGIN
    SET @SQL='SELECT 
	F.Comment as base,
	F.ID,
	F.FromBillID,
	F.FromBillNumberID,
	ai.FullName AS atypefullname,
	b.ntotal,
	s.FullName AS stypefullname,
	I.BillCode,
	I.Billtype,
	I.BillDate,
	bt.FullName AS dbtypefullname,
	e.FullName AS efullname,
	d.FullName AS dtypefullname ,
	i.BillNumberId
FROM ShareFeeBill F
INNER JOIN MoneyBill B ON F.FromBillID=B.ID
INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
INNER JOIN SType s ON b.Stypeid=s.TypeId
INNER JOIN Ac_Items ai ON b.AtypeId=ai.nId
INNER JOIN employee e ON e.typeId=I.etypeid
INNER JOIN Department d ON d.typeid=i.DTypeId
INNER JOIN btype bt ON bt.typeId=i.DealBTypeID
WHERE F.BillNumberId='+@BillNumberID+'
order by I.BillDate desc
'
END

IF @BillFlag=35--入库费用分摊单
BEGIN
    SET @SQL='SELECT b.BillDate,
	   b.BillCode,
	   e.FullName AS efullname,
	   d.FullName AS dtypefullname,
	   CASE b.ShareMode WHEN 0 THEN ''全部'' WHEN 1 THEN ''按金额'' WHEN 2 THEN ''按数量'' END AS shareMode,
	   b.Comment,
	   b.BillNumberId,
	   b.Billtype,
	   ce.FullName AS CheckeName,
	   CASE
	   WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
		WHEN B.Ifcheck=''t'' THEN ''已过账'' 
		WHEN AT.IfAudit is null THEN ''原始单据''
		WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
		WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
		WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
		WHEN AT.IfAudit=''2'' THEN ''原始草稿''
		END AS BillStatus,
		bi.totalqty,
		b.totalmoney,
		b.NTotalMoney,
		CASE WHEN B.CID=0 THEN
		(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
		 ELSE
		(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname
FROM BillIndex b
LEFT JOIN SType s ON b.Stypeid=s.TypeId
LEFT JOIN employee e ON e.typeId=b.etypeid
LEFT JOIN dbo.employee ce ON ce.typeId=b.checke
LEFT JOIN Department d ON d.typeid=b.DTypeId
LEFT JOIN AuditingBill AT ON at.BillNumberID=b.BillNumberId AND AT.BillIndexType=2
LEFT JOIN BillIndex bi on bi.BillNumberId = '+@BillNumberID
IF @BillType IN (34,16)
BEGIN
    SET @SQL+=' WHERE b.BillNumberId in (SELECT BillNumberId FROM ShareSourceBill WHERE FromBillNumberID='+@BillNumberID+') '
END
ELSE IF @BillType=36
BEGIN
    SET @SQL+=' WHERE b.BillNumberId in (SELECT BillNumberId FROM ShareFeeBill WHERE FromBillNumberID='+@BillNumberID+') and b.billtype=205 '
END
ELSE
BEGIN
    SET @SQL+=' WHERE and 1=2'
END

SET @SQL+=' ORDER BY b.BillDate DESC '
END

IF @BillFlag=37--销售费用分摊单
BEGIN
    SET @SQL='SELECT b.BillDate,
	   b.BillCode,
	   e.FullName AS efullname,
	   d.FullName AS dtypefullname,
	   CASE b.ShareMode WHEN 0 THEN ''全部'' WHEN 1 THEN ''按金额'' WHEN 2 THEN ''按数量'' END AS shareMode,
	   b.Comment,
	   b.BillNumberId,
	   b.Billtype,
	   ce.FullName AS CheckeName,
	   CASE
	   WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
		WHEN B.Ifcheck=''t'' THEN ''已过账'' 
		WHEN AT.IfAudit is null THEN ''原始单据''
		WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
		WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
		WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
		WHEN AT.IfAudit=''2'' THEN ''原始草稿''
		END AS BillStatus,
		bi.totalqty,
		b.totalmoney,
		b.NTotalMoney,
		CASE WHEN B.CID=0 THEN
		(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
		 ELSE
		(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname
FROM BillIndex b
LEFT JOIN SType s ON b.Stypeid=s.TypeId
LEFT JOIN employee e ON e.typeId=b.etypeid
LEFT JOIN dbo.employee ce ON ce.typeId=b.checke
LEFT JOIN Department d ON d.typeid=b.DTypeId
LEFT JOIN AuditingBill AT ON at.BillNumberID=b.BillNumberId AND AT.BillIndexType=2
LEFT JOIN BillIndex bi on bi.BillNumberId = '+@BillNumberID
IF @BillType=36
BEGIN
    SET @SQL+=' WHERE b.BillNumberId in (SELECT BillNumberId FROM ShareFeeBill WHERE FromBillNumberID='+@BillNumberID+') and b.billtype=206 '
END
ELSE IF @BillType IN (305,11,12)
BEGIN
     SET @SQL+=' WHERE b.BillNumberId in (SELECT BillNumberId FROM ShareSourceBill WHERE FromBillNumberID='+@BillNumberID+') '
END
ELSE
BEGIN
    SET @SQL+=' WHERE 1=2 '
END

SET @SQL+=' ORDER BY b.BillDate DESC '
END

--销售费用分摊单单据联查的销售出库单的类型不止一种，如果都在@BillFlag=14中处理。会造成销售费用分摊中的组合品销售出库单的数据也显示在销售出库单中，或者相反，所以在这里特殊处理
IF @BillFlag=36
BEGIN
    SET @SQL = 'SELECT AI.*,
					ISNULL(CASE AI.redword when 2 then -AD.Qty else AD.Qty END,0) as Qty,
					ISNULL(CASE AI.redword when 2 then -AD.Total else AD.Total END,0) as Total,
					ISNULL(CASE AI.redword when 2 then -AD.NTotal else AD.NTotal END,0) as NTotal,
					ISNULL(CASE AI.redword when 2 then -AD.TaxMoney else AD.TaxMoney END,0) as TaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxMoney else AD.NTaxMoney END,0) as NTaxMoney,
					ISNULL(CASE AI.redword when 2 then -AD.TaxTotal else AD.TaxTotal END,0) as TaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.NTaxTotal else AD.NTaxTotal END,0) as NTaxTotal,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceQty else AD.InvoiceQty END,0) as InvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.InvoiceMoney else AD.InvoiceMoney END,0) as InvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.NInvoiceMoney else AD.NInvoiceMoney END,0) as NInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceQty else AD.ResidueInvoiceQty END,0) as ResidueInvoiceQty,
					ISNULL(CASE AI.redword when 2 then -AD.ResiduenInvoiceMoney else AD.ResiduenInvoiceMoney END,0) as ResiduenInvoiceMoney,
					ISNULL(CASE AI.redword when 2 then -AD.ResidueInvoiceMoney else AD.ResidueInvoiceMoney END,0) as ResidueInvoiceMoney
					 FROM 
					(SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.redword,
					B.Stypeid,
					ST.FullName AS STFullName,
					CASE
					WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					WHEN B.IsIni=1 THEN ''期初单据''
					WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					WHEN AT.IfAudit is null THEN ''原始单据''
					WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					END AS BillStatus,	
					E.FullName AS EFullName,
					B.dealbtypeid AS btypeid,
					DT.FullName AS dbtypeFullname,
					B.btypeid AS btypeid1,
					BT.FullName AS btypeFullname,
					B.DTypeId,
					D.FullName AS dtypeFullname,
					B.checke,
					CE.FullName AS CheckeName,
					B.Comment,
					CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					CASE WHEN B.CID=0 THEN
					(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
					ELSE
					(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,
					B.CostSale,					
					B.Explain
			FROM	'+@BillIndexTable+' B 
					INNER JOIN BType BT ON BT.typeId = B.btypeid
					INNER JOIN BType DT ON DT.typeId = B.dealbtypeid 	
					INNER JOIN Department D ON D.typeid = B.DtypeId
					Left JOIN Employee E ON B.etypeid=E.TypeId
					INNER JOIN Employee CE ON B.Checke=CE.TypeId
					INNER JOIN SType ST ON ST.typeId= B.Stypeid
					LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=2'
					IF @BillType='313'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select BillNumberId from PT_Combin_SaleBill s where s.OrderID IN (SELECT OrderID FROM PT_Combin_OrderBill WHERE BillNumberID='+@BillNumberID+' )))'
					END
					ELSE IF @BillType='46'
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select OldBillNumberID from PT_Combin_SaleBackBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					ELSE IF @BillType='206'
					BEGIN
					    SET @SQL=@SQL+' WHERE B.BillNumberID in (SELECT BillNumberID FROM BillIndex BI WHERE BI.BillNumberID in(select FromBillNumberID from dbo.ShareSourceBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					ELSE
					BEGIN
						SET @SQL=@SQL+' WHERE B.BillCode in (SELECT BillCode FROM BillIndex BI WHERE BI.BillNumberID in(select FromBillNumberID from BuyBill s where s.BillNumberId='+@BillNumberID+'))'
					END
					SET @SQL=@SQL+') AI INNER JOIN (SELECT A.BillNumberId,SUM(A.Qty) AS Qty,SUM(A.total) AS Total,SUM(A.NTotal) AS NTotal,
					SUM(A.BackQty) AS BackQty,SUM(ISNULL(A.TaxMoney,0)) AS TaxMoney,SUM(ISNULL(A.NTaxMoney,0)) AS NTaxMoney,
					SUM(ISNULL(A.TaxTotal,0)) AS TaxTotal,SUM(ISNULL(A.NTaxTotal,0)) AS NTaxTotal,
					SUM(CASE WHEN (A.Qty-A.InvoiceQty)>=0 THEN (A.Qty-A.InvoiceQty) ELSE 0 END) AS ResidueInvoiceQty,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.NTotal - A.NInvoiceMoney
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.NDiscountPrice
					END) AS ResiduenInvoiceMoney,
					SUM(CASE WHEN ISNULL(A.Invoiceqty,0)=0 THEN A.Total - A.InvoiceMoney
					ELSE (A.Qty-ISNULL(A.InvoiceQty,0)) * A.DiscountPrice
					END) AS ResidueInvoiceMoney,
					SUM(A.InvoiceQty) AS InvoiceQty,SUM(ISNULL(A.InvoiceMoney,0)) AS InvoiceMoney,SUM(ISNULL(A.NInvoiceMoney,0)) AS NInvoiceMoney'
    IF @BillType = '313'
	BEGIN
		SET @SQL=@SQL+' FROM PT_Combin_SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId'
	END
	ELSE IF @BillType = '46'
	BEGIN
		SET @SQL=@SQL+' FROM PT_Combin_SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId'
	END
	ELSE IF @BillType='206'
	BEGIN
	    IF (SELECT DISTINCT FromBillType FROM ShareSourceBill WHERE BillNumberId=@BillNumberID)=12
		BEGIN
		    --组合品销售出库单
		    SET @SQL=@SQL+' FROM PT_Combin_SaleBill A GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId'
		END
		ELSE
		BEGIN
		    SET @SQL=@SQL+'  FROM SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId AND 1=2'
		END
	END
	ELSE
	BEGIN
		SET @SQL=@SQL+'  FROM SaleBill A 
		GROUP BY A.BillNumberId) AD ON AD.BillNumberId=AI.BillNumberId AND 1=2'
	END
	SET @SQL= @SQL+' ORDER BY AI.BillDate DESC'
END

IF @BillFlag=38--生产拆装单
BEGIN
    SET @SQL='SELECT  b.BillType,
        b.BillNumberId,
        b.BillCode,
        s.FullName AS stypefullname,
        e.FullName AS efullname,
        d.FullName AS dtypefullname,
        st.FullName AS stockFullname,
        b.Comment,
        CASE WHEN B.CID=0 THEN
		(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
		 ELSE
		(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,
		CASE
		WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
		WHEN B.Ifcheck=''t'' THEN ''已过账'' 
		WHEN AT.IfAudit is null THEN ''原始单据''
		WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
		WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
		WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
		WHEN AT.IfAudit=''2'' THEN ''原始草稿''
		END AS BillStatus,
		b.BillDate
FROM dbo.BillIndex b
INNER JOIN dbo.SType s ON b.Stypeid=s.TypeId
INNER JOIN dbo.employee e ON b.etypeid=e.typeId
INNER JOIN dbo.Department d ON b.DTypeId=d.typeid
INNER JOIN dbo.Stock st ON b.ktypeid=st.typeId
LEFT JOIN AuditingBill AT ON at.BillNumberID=b.BillNumberId AND AT.BillIndexType=2'
IF @BillType=205
BEGIN
    IF (SELECT DISTINCT FromBillType FROM ShareSourceBill WHERE BillNumberId=@BillNumberID)=16
    BEGIN
        SET @SQL+=' WHERE B.BillNumberID in (select FromBillNumberID from dbo.ShareSourceBill s where s.BillNumberId='+@BillNumberID+') '
    END
    ELSE
    BEGIN
        SET @SQL+=' WHERE B.BillNumberID in (select FromBillNumberID from dbo.ShareSourceBill s where s.BillNumberId='+@BillNumberID+') and 1=0 '
    END
END
ELSE
BEGIN
     SET @SQL+=' WHERE B.BillNumberID in (select FromBillNumberID from dbo.ShareSourceBill s where s.BillNumberId='+@BillNumberID+') and 1=0 '
END
SET @SQL= @SQL+' ORDER BY b.BillDate DESC'
END

IF @BillFlag=39--报价单
BEGIN
    SET @SQL='SELECT b.BillDate,
	   b.BillCode,
	   s.FullName AS sfullname,
	   e.FullName AS efullname,
	   d.FullName AS dfullname,
	   bt.FullName AS bfullname,
	   CASE WHEN B.CID=0 THEN
		(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
		 ELSE
		(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,
		b.totalqty,
		b.totalmoney,
		ee.FullName AS checkeName,
		b.Comment,
		b.explain,
		b.BillNumberId,
		b.BillType,
		b.etypeid,
		b.Stypeid,
		b.dtypeid,
		b.btypeid
FROM BillIndex b
INNER JOIN SType s ON b.Stypeid=s.TypeId
INNER JOIN employee e ON b.etypeid=e.typeId
INNER JOIN employee ee ON b.checke=ee.typeId
INNER JOIN Department d ON b.DTypeId = d.typeid
INNER JOIN btype bt ON b.btypeid=bt.typeId
WHERE b.BillNumberId IN (SELECT DISTINCT AskBillNumberID FROM OrderBill WHERE BillNumberId='+@BillNumberID+')
ORDER BY b.BillDate DESC'
END

IF @BillFlag=40--请购单
BEGIN
    SET @SQL='SELECT r.BillNumberId,
	   r.BillType,
	   r.BillCode,
	   r.BillDate,
	   s.FullName AS sfullname,
	   d.FullName AS dfullname,
	   e.FullName AS efullname,
	   ee.FullName AS checkename,
	   r.Comment,
	   r.explain,
	   r.totalqty,
	   r.totalmoney,
	   r.etypeid,
	   r.stypeid,
	   r.dtypeid
FROM dbo.RequestIndex R
INNER JOIN dbo.SType s ON r.Stypeid=s.TypeId
INNER JOIN dbo.Department d ON r.dtypeid=d.typeid
INNER JOIN dbo.employee e ON r.etypeid=e.typeId
INNER JOIN dbo.employee ee ON r.checke=ee.typeId
WHERE R.BillNumberId IN (SELECT DISTINCT RequestBillNumberID FROM dbo.OrderBill WHERE billNumberID='+@BillNumberID+')
ORDER BY r.BillDate DESC'
END

IF @BillFlag=41--询价单
BEGIN
    SET @SQL='SELECT b.BillCode,
	   b.BillNumberId,
	   b.BillType,
	   b.BillDate,
	   s.FullName AS sfullname,
	   e.FullName AS efullname,
	   d.FullName AS dfullname,
	   bt.FullName AS bfullname,
	   ee.FullName AS checkename,
	   b.totalqty,
	   b.totalmoney,
	   b.Comment,
	   b.explain,
	    CASE WHEN B.CID=0 THEN
		(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
		 ELSE
		(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,
		b.stypeid,
		b.etypeid,
		b.dtypeid,
		b.btypeid
FROM dbo.BillIndex b
INNER JOIN dbo.SType s ON b.Stypeid=s.TypeId
INNER JOIN dbo.employee e ON b.etypeid=e.typeId
INNER JOIN dbo.Department d ON b.DTypeId=d.typeid
INNER JOIN dbo.btype bt ON b.DealBTypeID=bt.typeId
INNER JOIN dbo.employee ee ON b.checke =ee.typeId'
IF @BillType='301'
BEGIN
    SET @SQL+='
    WHERE b.BillNumberId IN (SELECT AskBillNumberID FROM dbo.OrderBill WHERE BillNumberId='+@BillNumberID+')'
END
ELSE IF @BillType='34'
BEGIN
    SET @SQL+='
    Where b.BillNumberId IN (SELECT AskBillNumberID FROM dbo.BuyBill WHERE BillNumberId='+@BillNumberID+')'
END

SET @SQL+='
ORDER BY b.BillDate DESC'
END

--组合品销售订单
IF @BillFlag=42
BEGIN
     SET @SQL='SELECT	AA.*,
						GT.ReachQty,
						GT.ReachTotal,
						GT.ResidueQty,
						GT.ResidueTotal,
					    GT.TotalQty,GT.TotalMoney 

		
        FROM(
		SELECT	B.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.ETypeId,
				B.Stypeid,
				ST.FullName AS STFullName,
				CASE 
				WHEN B.OrderState=''1'' THEN ''已完成''
				WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
				WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
				WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
				WHEN AT.IfAudit=''2'' THEN ''原始草稿''
				WHEN B.OrderState=''0'' THEN ''未完成''
				WHEN AT.IfAudit is null THEN ''原始单据''
				END AS BillStatus,
				E.FullName AS EFullName,
				B.dealbtypeid AS btypepeid,
				DT.FullName AS dbtypeFullname,
				B.btypeid AS btypeid1,
				BT.FullName AS btypeFullname,
				B.DTypeId,
				D.FullName AS dFullname,
		        B.redword,
				CE.FullName AS CheckeName,
				B.Comment,
				CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) 
				ELSE B.CID END  AS cid,
				CASE WHEN B.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				ELSE
				(select fullname from Ac_Currency where cid=B.CID) END AS accrencyname,					
				B.Explain
		FROM	'+@BillIndexTable+' B 
				LEFT JOIN BType BT ON BT.typeId = B.btypeid
				LEFT JOIN BType DT ON DT.typeId = B.dealbtypeid 	
				LEFT JOIN Department D ON D.typeid = B.DtypeId
				LEFT JOIN Employee E ON B.etypeid=E.TypeId
				LEFT JOIN Employee CE ON B.Checke=CE.TypeId
				LEFT JOIN SType ST ON ST.typeId= B.Stypeid
				LEFT JOIN AuditingBill AT ON AT.BillNumberId = B.BillNumberID AND AT.BillIndexType=0
				WHERE B.BillNumberID IN '
			    IF @BillType='12'
				BEGIN
					SET @SQL = @SQL+'(SELECT billNumberId From PT_Combin_OrderBill WHERE OrderID IN (SELECT OrderID FROM PT_Combin_SaleBill A where A.BillNumberID = '+@BillNumberID+')'
				END
				ELSE IF @BillType='301'
				BEGIN
					SET @SQL = @SQL+'(SELECT DISTINCT OBB.billNumberId FROM dbo.OrderBill OB
                                    INNER JOIN dbo.PT_Combin_OrderBillDetail OBB ON OB.PTCombinOrderBillDetailID = OBB.OrderID where OB.billNumberID ='+@BillNumberID+''
					
				END
				
				
			SET @SQL = @SQL +'))AA
				INNER JOIN (SELECT O.billNumberID,SUM(O.Qty-O.ReachQty) AS ResidueQty, 
				SUM(ISNULL((O.Qty-O.ReachQty),0)*(O.TaxTotal/O.Qty)) AS ResidueTotal,
				SUM(O.Qty) AS BaseQty,SUM(O.TaxTotal) AS BaseTotal, 
				SUM(O.ReachQty) AS ReachQty,SUM(O.ReachTaxTotal) AS ReachTotal,
				SUM(O.qty) AS TotalQty, SUM(O.total) AS TotalMoney
                FROM PT_Combin_OrderBill O
		        GROUP BY O.billNumberID) GT ON GT.billNumberID=aa.billNumberId
				ORDER BY AA.BillDate DESC'

END

--分支机构调皮出入库单据(43:入库,44:出库)
IF @billflag IN(43)
BEGIN
	SET @SQL='SELECT  CONVERT(varchar(100), b.BillDate, 23) as BillDate,
					 b.billtype,
					 b.billnumberid,
					 b.billcode,
					 s.fullname as sfullname,
					 e.fullname as efullname,
					 d.fullname as dfullname,
					 st.fullname as ikfullname,
					 ey.fullname as checke,
					 st1.fullname as okfullname,
					 b.TotalQty,
					 b.TotalMoney,
					 b.comment,
					 CASE
					 WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					 WHEN B.IsIni=1 THEN ''期初单据''
					 WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					 WHEN AT.IfAudit is null THEN ''原始单据''
					 WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					 WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					 WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					 WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					 END AS BillStatus,
					 CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					 CASE WHEN B.CID=0 THEN
				     (select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				     ELSE
				     (select fullname from Ac_Currency where cid=B.CID) END AS accrencyname			
			  FROM BillIndex b 
			  INNER JOIN 
			  (
				SELECT DISTINCT s.billnumberid	--,s.ktypeid,s.ktypeid2,s.comment 
				from stypemovebill s
				--inner join billindex b on  s.billnumberid=b.billnumberid
				WHERE s.frombillnumberid ='+@BillNumberID+' 
			  )sb on sb.billnumberid=b.billnumberid
			  LEFT JOIN stype s on s.typeid=b.stypeid
			  LEFT JOIN employee e on e.typeid=b.etypeid
			  LEFT JOIN employee ey on ey.typeid=b.checke
			  LEFT JOIN Department d on d.typeid=b.dtypeid
			  LEFT JOIN Stock st on st.typeid=b.ktypeid
			  LEFT JOIN Stock st1 on st1.typeid=b.ktypeid2
			  LEFT JOIN AuditingBill AT ON AT.BillNumberId = b.BillNumberID AND AT.BillIndexType=2
			 '
	SET @SQL+=' ORDER BY b.BillDate DESC'
END

--分支机构调皮出入库单据(43:入库,44:出库)
IF @billflag IN(44)
BEGIN
	SET @SQL='SELECT CONVERT(varchar(100), b.BillDate, 23) as BillDate,
					 b.billtype,
					 b.billnumberid,
					 b.billcode,
					 s.fullname as sfullname,
					 e.fullname as efullname,
					 d.fullname as dfullname,
					 st.fullname as ikfullname,
					 ey.fullname as checke,
					 st1.fullname as okfullname,
					 b.TotalQty,
					 b.TotalMoney,
					 b.comment,
					 CASE
					 WHEN B.redword=''2'' AND B.Ifcheck=''t'' THEN ''已红冲''
					 WHEN B.IsIni=1 THEN ''期初单据''
					 WHEN B.Ifcheck=''t'' THEN ''已过账'' 
					 WHEN AT.IfAudit is null THEN ''原始单据''
					 WHEN AT.IfAudit=''0'' THEN ''待审核草稿''
					 WHEN AT.IfAudit=''-1'' THEN ''审核不通过草稿''
					 WHEN AT.IfAudit=''1'' THEN ''审核通过草稿''
					 WHEN AT.IfAudit=''2'' THEN ''原始草稿''
					 END AS BillStatus,
					 CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
					 CASE WHEN B.CID=0 THEN
				     (select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
				     ELSE
				     (select fullname from Ac_Currency where cid=B.CID) END AS accrencyname			
			  FROM BillIndex b 
			  INNER JOIN 
			  (
				SELECT DISTINCT s.frombillnumberid
				from stypemovebill s
				WHERE s.billnumberid ='+@BillNumberID+' 
			  )sb on sb.frombillnumberid=b.billnumberid
			  INNER JOIN stype s on s.typeid=b.stypeid
			  INNER JOIN employee e on e.typeid=b.etypeid
			  INNER JOIN employee ey on ey.typeid=b.checke
			  INNER JOIN Department d on d.typeid=b.dtypeid
			  INNER JOIN Stock st on st.typeid=b.ktypeid
			  INNER JOIN Stock st1 on st1.typeid=b.ktypeid2
			  LEFT JOIN AuditingBill AT ON AT.BillNumberId = b.BillNumberID AND AT.BillIndexType=2 '
	SET @SQL+=' ORDER BY b.BillDate DESC'
END

--同价调拨单
IF @billflag IN(46)
BEGIN	
	;with allotbillids as 
	(
		select distinct b.BillNumberId 
		from MoveBill b
		inner join PosAllotApplyBill paab on paab.ID = b.AllotID and paab.BillNumberId = @BillNumberID
	)
	SELECT CONVERT(varchar(100), b.BillDate, 23) as BillDate,
		 b.billtype,
		 b.billnumberid,
		 b.billcode,
		 s.fullname as sfullname,
		 e.fullname as efullname,
		 d.fullname as dfullname,
		 st.fullname as okfullname,
		 ey.fullname as checke,
		 st1.fullname as ikfullname,
		 b.TotalQty,
		 b.TotalMoney,
		 b.comment,
		 CASE
		 WHEN B.redword=2 AND B.Ifcheck='t' THEN '已红冲'
		 WHEN B.IsIni=1 THEN '期初单据'
		 WHEN B.Ifcheck='t' THEN '已过账'
		 WHEN AT.IfAudit is null THEN '原始单据'
		 WHEN AT.IfAudit='0' THEN '待审核草稿'
		 WHEN AT.IfAudit='-1' THEN '审核不通过草稿'
		 WHEN AT.IfAudit='1' THEN '审核通过草稿'
		 WHEN AT.IfAudit='2' THEN '原始草稿'
		 END AS BillStatus,
		 CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
		 CASE WHEN B.CID=0 THEN
		 (select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
		 ELSE
		 (select fullname from Ac_Currency where cid=B.CID) END AS accrencyname			
	FROM BillIndex b 
	inner join allotbillids ab on ab.BillNumberId = b.BillNumberId
	INNER JOIN stype s on s.typeid=b.stypeid
	INNER JOIN employee e on e.typeid=b.etypeid
	INNER JOIN employee ey on ey.typeid=b.checke
	INNER JOIN Department d on d.typeid=b.dtypeid
	INNER JOIN Stock st on st.typeid=b.ktypeid
	INNER JOIN Stock st1 on st1.typeid=b.ktypeid2
	LEFT JOIN AuditingBill AT ON AT.BillNumberId = b.BillNumberID AND AT.BillIndexType=2
	ORDER BY b.BillDate DESC
END

--变价调拨单
IF @billflag IN(47)
BEGIN
	;with allotbjbillids as 
	(
		select distinct b.BillNumberId 
		from MoveBjBill b
		inner join PosAllotApplyBill paab on paab.ID = b.AllotID and paab.BillNumberId = @BillNumberID
	)
	SELECT CONVERT(varchar(100), b.BillDate, 23) as BillDate,
		 b.billtype,
		 b.billnumberid,
		 b.billcode,
		 s.fullname as sfullname,
		 e.fullname as efullname,
		 d.fullname as dfullname,
		 st.fullname as okfullname,
		 ey.fullname as checke,
		 st1.fullname as ikfullname,
		 b.TotalQty,
		 b.TotalMoney,
		 b.comment,
		 CASE
		 WHEN B.redword=2 AND B.Ifcheck='t' THEN '已红冲'
		 WHEN B.IsIni=1 THEN '期初单据'
		 WHEN B.Ifcheck='t' THEN '已过账'
		 WHEN AT.IfAudit is null THEN '原始单据'
		 WHEN AT.IfAudit='0' THEN '待审核草稿'
		 WHEN AT.IfAudit='-1' THEN '审核不通过草稿'
		 WHEN AT.IfAudit='1' THEN '审核通过草稿'
		 WHEN AT.IfAudit='2' THEN '原始草稿'
		 END AS BillStatus,
		 CASE WHEN B.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE B.CID END  AS cid,
		 CASE WHEN B.CID=0 THEN
		 (select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
		 ELSE
		 (select fullname from Ac_Currency where cid=B.CID) END AS accrencyname			
	FROM BillIndex b 
	inner join allotbjbillids ab on ab.BillNumberId = b.BillNumberId
	INNER JOIN stype s on s.typeid=b.stypeid
	INNER JOIN employee e on e.typeid=b.etypeid
	INNER JOIN employee ey on ey.typeid=b.checke
	INNER JOIN Department d on d.typeid=b.dtypeid
	INNER JOIN Stock st on st.typeid=b.ktypeid
	INNER JOIN Stock st1 on st1.typeid=b.ktypeid2
	LEFT JOIN AuditingBill AT ON AT.BillNumberId = b.BillNumberID AND AT.BillIndexType=2
	ORDER BY b.BillDate DESC
END

--调拨申请单
IF @billflag IN(45)
BEGIN

	select distinct BillNumberId 
	into #posallotapplybillids
	from PosAllotApplyBill 
	where ID in(
		select AllotID from MoveBill where BillNumberId = @BillNumberID
		union all 
		select AllotID from MoveBjBill where BillNumberId = @BillNumberID
	)
		
    create table #billexecstate(execstate int,billnumberid  NUMERIC(10, 0))
    
    insert into #billexecstate (execstate,billnumberid)
    select case when pb.isdone =1 then 7
				when m.qty>0 and pb.isdone=0 then 6
				else 3 end as execstate,
				pb.billnumberid
    from PosAllotApplyBillIndex pb
    inner join #posallotapplybillids b on b.BillNumberId = pb.BillNumberId
    LEFT JOIN
		(	SELECT ISNULL(SUM(m.qty),0) as qty,pb.billnumberid
				FROM (
					SELECT Qty,AllotID FROM dbo.MoveBill m 
					INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
					WHERE bi.RedWord=0 ----引用要算草稿
					UNION ALL SELECT Qty,AllotID FROM dbo.MoveBjBill m
					INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
					WHERE bi.RedWord=0 ----引用要算草稿 
					UNION ALL SELECT s.Qty,s.AllotID FROM dbo.STypeMoveBill s 
					INNER JOIN dbo.BillIndex bi ON s.BillNumberId=bi.BillNumberId
					 WHERE bi.RedWord=0 ----引用要算草稿 
				) m
				INNER JOIN dbo.PosAllotApplyBill pb ON pb.ID=m.AllotID 
				inner join #posallotapplybillids b on b.BillNumberId = pb.BillNumberId
				group by pb.billnumberid
			
		)m ON pb.billnumberid=m.billnumberid
		
	SELECT CONVERT(varchar(100), b.BillDate, 23) as BillDate,
		 b.billtype,
		 b.billnumberid,
		 b.billcode,
		 s.fullname as sfullname,
		 e.fullname as efullname,
		 d.fullname as dfullname,
		 st.fullname as ikfullname,
		 ey.fullname as checke,
		 st1.fullname as okfullname,
		 b.Qty as totalqty,
		 b.comment,
		CASE
		WHEN bs.execstate=7 THEN '已完成' 
		WHEN bs.execstate=6 THEN '已引用未完成' 
		WHEN b.BillState=0 THEN '原始单据'
		WHEN b.BillState=1 THEN '已审核'
		WHEN b.BillState=2 THEN '已接受'
		WHEN b.BillState=3 THEN '已拒绝'
		WHEN b.BillState=4 THEN '已作废' 
		ELSE '未引用' END AS BillStatus	
	FROM PosAllotApplyBillIndex b 
	inner join #posallotapplybillids bids on bids.BillNumberId = b.BillNumberId
	inner join #billexecstate bs on bs.billnumberid = b.BillNumberId
	INNER JOIN stype s on s.typeid=b.stypeid
	INNER JOIN employee e on e.typeid=b.ApplyEtypeId
	INNER JOIN employee ey on ey.typeid=b.checke
	INNER JOIN Department d on d.typeid=b.dtypeid
	INNER JOIN Stock st on st.typeid=b.InKtypeId
	INNER JOIN Stock st1 on st1.typeid=b.KtypeId
	ORDER BY b.BillDate DESC
	
	drop table #billexecstate,#posallotapplybillids 
	return
END


--要货申请单
IF @billflag IN(48)
BEGIN
	SELECT CONVERT(varchar(100), b2.BillDate, 23) as BillDate,
		 b2.billtype,
		 b2.billnumberid,
		 b2.billcode,
		 s.fullname as sfullname,
		 e.fullname as efullname,
		 d.fullname as dfullname,
		 st.fullname as ikfullname,
		 ey.fullname as checke,
		 st1.fullname as okfullname,
		 b2.Qty as totalqty,
		 SUM(da.Total) totalmoney,
		 ac.FullName accrencyname,
		 b2.comment,
		 b2.redword,
		 CASE
		WHEN b2.redword='2' AND b2.Ifcheck='t' THEN '已红冲'
		WHEN b2.IsIni=1 THEN '期初单据'
		WHEN b2.Ifcheck='t' THEN '已过账'
		WHEN AT.IfAudit is null THEN '原始单据'
		WHEN AT.IfAudit='0' THEN '待审核草稿'
		WHEN AT.IfAudit='-1' THEN '审核不通过草稿'
		WHEN AT.IfAudit='1' THEN '审核通过草稿'
		WHEN AT.IfAudit='2' THEN '原始草稿'
		END AS BillStatus	
	FROM PosAllotApplyBillIndex b 
	INNER JOIN DeliveryBill db on db.BillNumberId = b.BillNumberId
	INNER JOIN DeliveryApplyBill da ON da.ID = db.DeliveryApplyBillId
	INNER JOIN PosAllotApplyBillIndex b2 ON b2.BillNumberId = da.BillNumberId
	INNER JOIN stype s on s.typeid=b2.stypeid
	INNER JOIN employee e on e.typeid=b2.ApplyEtypeId
	INNER JOIN employee ey on ey.typeid=b2.checke
	INNER JOIN Department d on d.typeid=b2.dtypeid
	INNER JOIN Stock st on st.typeid=b2.InKtypeId
	INNER JOIN Stock st1 on st1.typeid=b2.KtypeId
	LEFT  JOIN dbo.Ac_Currency ac ON ac.CId = b2.CID
	LEFT JOIN AuditingBill AT ON AT.BillNumberId = B2.BillNumberID AND AT.BillIndexType=0 
	WHERE b.BillNumberId = @BillNumberId AND b.BillType = @BillType AND b2.redword = 0
	GROUP BY b2.BillDate,b2.billtype,b2.billnumberid,b2.billcode,s.fullname,e.fullname,d.fullname,st.fullname,ey.fullname,st1.fullname,b2.Qty,ac.FullName,b2.comment,b2.redword,b2.Ifcheck,b2.IsIni,AT.IfAudit
	ORDER BY b2.BillDate DESC
	RETURN
END


--门店配送单
IF @billflag IN(49)
BEGIN

	IF @BillType = 326	--要货查下游配送单
	BEGIN
		SELECT CONVERT(varchar(100), b2.BillDate, 23) as BillDate,
			 b2.billtype,
			 b2.billnumberid,
			 b2.billcode,
			 s.fullname as sfullname,
			 e.fullname as efullname,
			 d.fullname as dfullname,
			 st.fullname as ikfullname,
			 ey.fullname as checke,
			 st1.fullname as okfullname,
			 b2.Qty as totalqty,
			 SUM(bi.Total) totalmoney,
			 ac.FullName accrencyname,
			 b2.comment,
			 b2.redword,
		 CASE
		WHEN b2.redword='2' AND b2.Ifcheck='t' THEN '已红冲'
		WHEN b2.IsIni=1 THEN '期初单据'
		WHEN b2.Ifcheck='t' THEN '已过账'
		WHEN AT.IfAudit is null THEN '原始单据'
		WHEN AT.IfAudit='0' THEN '待审核草稿'
		WHEN AT.IfAudit='-1' THEN '审核不通过草稿'
		WHEN AT.IfAudit='1' THEN '审核通过草稿'
		WHEN AT.IfAudit='2' THEN '原始草稿'
		END AS BillStatus	
		FROM PosAllotApplyBillIndex b 
		INNER JOIN DeliveryApplyBill da ON b.BillNumberId = da.BillNumberId
		INNER JOIN DeliveryBill bi ON bi.DeliveryApplyBillId = da.ID
		INNER JOIN PosAllotApplyBillIndex b2 ON b2.BillNumberId = bi.BillNumberId
		INNER JOIN stype s ON s.typeid=b.stypeid
		INNER JOIN employee e ON e.typeid=b2.ApplyEtypeId
		INNER JOIN employee ey ON ey.typeid=b2.checke
		INNER JOIN Department d ON d.typeid=b2.dtypeid
		INNER JOIN Stock st ON st.typeid=b2.InKtypeId
		INNER JOIN Stock st1 ON st1.typeid=b2.KtypeId
		LEFT  JOIN dbo.Ac_Currency ac ON ac.CId = b2.CID
		LEFT JOIN AuditingBill AT ON AT.BillNumberId = B2.BillNumberID AND AT.BillIndexType=0 
		WHERE b.BillNumberId = @BillNumberId AND b.BillType = @BillType AND b2.redword = 0
		GROUP BY b2.BillDate,b2.billtype,b2.billnumberid,b2.billcode,s.fullname,e.fullname,d.fullname,st.fullname,ey.fullname,st1.fullname,b2.Qty,ac.FullName,b2.comment,b2.redword,b2.Ifcheck,b2.IsIni,AT.IfAudit
		ORDER BY b2.BillDate DESC
		RETURN
	END
	ELSE IF @BillType = 328 --退货查上游配送单
	BEGIN
		SELECT CONVERT(varchar(100), b2.BillDate, 23) as BillDate,
			 b2.billtype,
			 b2.billnumberid,
			 b2.billcode,
			 s.fullname as sfullname,
			 e.fullname as efullname,
			 d.fullname as dfullname,
			 st.fullname as ikfullname,
			 ey.fullname as checke,
			 st1.fullname as okfullname,
			 b2.Qty as totalqty,
			 SUM(bi.Total) totalmoney,
			 ac.FullName accrencyname,
			 b2.comment,
			 b2.redword,
		 CASE
		WHEN b2.redword='2' AND b2.Ifcheck='t' THEN '已红冲'
		WHEN b2.IsIni=1 THEN '期初单据'
		WHEN b2.Ifcheck='t' THEN '已过账'
		WHEN AT.IfAudit is null THEN '原始单据'
		WHEN AT.IfAudit='0' THEN '待审核草稿'
		WHEN AT.IfAudit='-1' THEN '审核不通过草稿'
		WHEN AT.IfAudit='1' THEN '审核通过草稿'
		WHEN AT.IfAudit='2' THEN '原始草稿'
		END AS BillStatus	
		FROM PosAllotApplyBillIndex b 
		INNER JOIN DeliveryBackBill db on db.BillNumberId = b.BillNumberId
		INNER JOIN DeliveryBill bi ON db.DeliveryID = bi.ID
		INNER JOIN PosAllotApplyBillIndex b2 ON b2.BillNumberId = bi.BillNumberId
		INNER JOIN stype s on s.typeid=b2.stypeid
		INNER JOIN employee e on e.typeid=b2.ApplyEtypeId
		INNER JOIN employee ey on ey.typeid=b2.checke
		INNER JOIN Department d on d.typeid=b2.dtypeid
		INNER JOIN Stock st on st.typeid=b2.InKtypeId
		INNER JOIN Stock st1 on st1.typeid=b2.KtypeId
		LEFT  JOIN dbo.Ac_Currency ac ON ac.CId = b2.CID
		LEFT JOIN AuditingBill AT ON AT.BillNumberId = B2.BillNumberID AND AT.BillIndexType=0 
		WHERE b.BillNumberId = @BillNumberId AND b.BillType = @BillType AND b2.redword = 0
		GROUP BY b2.BillDate,b2.billtype,b2.billnumberid,b2.billcode,s.fullname,e.fullname,d.fullname,st.fullname,ey.fullname,st1.fullname,b2.Qty,ac.FullName,b2.comment,b2.redword,b2.Ifcheck,b2.IsIni,AT.IfAudit
		ORDER BY b2.BillDate DESC
		RETURN
	END
END

--配送退货单
IF @billflag IN(50)
BEGIN
	SELECT CONVERT(varchar(100), b2.BillDate, 23) as BillDate,
		 b2.billtype,
		 b2.billnumberid,
		 b2.billcode,
		 s.fullname as sfullname,
		 e.fullname as efullname,
		 d.fullname as dfullname,
		 st.fullname as ikfullname,
		 ey.fullname as checke,
		 st1.fullname as okfullname,
		 b2.Qty as totalqty,
		 SUM(bi.Total) totalmoney,
		 ac.FullName accrencyname,
		 b2.comment,
		 b2.redword,
		 CASE
		WHEN b2.redword='2' AND b2.Ifcheck='t' THEN '已红冲'
		WHEN b2.IsIni=1 THEN '期初单据'
		WHEN b2.Ifcheck='t' THEN '已过账'
		WHEN AT.IfAudit is null THEN '原始单据'
		WHEN AT.IfAudit='0' THEN '待审核草稿'
		WHEN AT.IfAudit='-1' THEN '审核不通过草稿'
		WHEN AT.IfAudit='1' THEN '审核通过草稿'
		WHEN AT.IfAudit='2' THEN '原始草稿'
		END AS BillStatus	
	FROM PosAllotApplyBillIndex b 
	INNER JOIN dbo.DeliveryBill db ON db.BillNumberId = b.BillNumberId
	INNER JOIN DeliveryBackBill bi on bi.DeliveryID = db.ID
	INNER JOIN PosAllotApplyBillIndex b2 ON b2.BillNumberId = bi.BillNumberId
	INNER JOIN stype s on s.typeid=b2.stypeid
	INNER JOIN employee e on e.typeid=b2.ApplyEtypeId
	INNER JOIN employee ey on ey.typeid=b2.checke
	INNER JOIN Department d on d.typeid=b2.dtypeid
	INNER JOIN Stock st on st.typeid=b2.InKtypeId
	INNER JOIN Stock st1 on st1.typeid=b2.KtypeId
	LEFT  JOIN dbo.Ac_Currency ac ON ac.CId = b2.CID
	LEFT JOIN AuditingBill AT ON AT.BillNumberId = B2.BillNumberID AND AT.BillIndexType=0 
	WHERE b.BillNumberId = @BillNumberId AND b.BillType = @BillType AND b2.redword = 0
	GROUP BY b2.BillDate,b2.billtype,b2.billnumberid,b2.billcode,s.fullname,e.fullname,d.fullname,st.fullname,ey.fullname,st1.fullname,b2.Qty,ac.FullName,b2.comment,b2.redword,b2.Ifcheck,b2.IsIni,AT.IfAudit
	ORDER BY b2.BillDate DESC
	RETURN
END

--配送验收单
IF @billflag IN(51)
BEGIN
	SELECT CONVERT(varchar(100), b2.BillDate, 23) as BillDate,
		 b2.billtype,
		 b2.billnumberid,
		 b2.billcode,
		 s.fullname as sfullname,
		 e.fullname as efullname,
		 d.fullname as dfullname,
		 st.fullname as ikfullname,
		 ey.fullname as checke,
		 st1.fullname as okfullname,
		 b2.Qty as totalqty,
		 SUM(bi.Total) totalmoney,
		 ac.FullName accrencyname,
		 b2.comment,
		 b2.redword,
		 CASE
		WHEN b2.redword='2' AND b2.Ifcheck='t' THEN '已红冲'
		WHEN b2.IsIni=1 THEN '期初单据'
		WHEN b2.Ifcheck='t' THEN '已过账'
		WHEN AT.IfAudit is null THEN '原始单据'
		WHEN AT.IfAudit='0' THEN '待审核草稿'
		WHEN AT.IfAudit='-1' THEN '审核不通过草稿'
		WHEN AT.IfAudit='1' THEN '审核通过草稿'
		WHEN AT.IfAudit='2' THEN '原始草稿'
		END AS BillStatus	
	FROM PosAllotApplyBillIndex b 
	INNER JOIN dbo.DeliveryBill db ON db.BillNumberId = b.BillNumberId
	INNER JOIN DeliveryCheckBill bi on bi.DeliveryID = db.ID
	INNER JOIN PosAllotApplyBillIndex b2 ON b2.BillNumberId = bi.BillNumberId
	INNER JOIN stype s on s.typeid=b2.stypeid
	INNER JOIN employee e on e.typeid=b2.ApplyEtypeId
	INNER JOIN employee ey on ey.typeid=b2.checke
	INNER JOIN Department d on d.typeid=b2.dtypeid
	INNER JOIN Stock st on st.typeid=b2.InKtypeId
	INNER JOIN Stock st1 on st1.typeid=b2.KtypeId
	LEFT JOIN dbo.Ac_Currency ac ON ac.CId = b2.CID
	LEFT JOIN AuditingBill AT ON AT.BillNumberId = B2.BillNumberID AND AT.BillIndexType=0 
	WHERE b.BillNumberId = @BillNumberId AND b.BillType = @BillType AND b2.redword = 0
	GROUP BY b2.BillDate,b2.billtype,b2.billnumberid,b2.billcode,s.fullname,e.fullname,d.fullname,st.fullname,ey.fullname,st1.fullname,b2.Qty,ac.FullName,b2.comment,b2.redword,b2.Ifcheck,b2.IsIni,AT.IfAudit
	ORDER BY b2.BillDate DESC
	RETURN
END
--PRINT(@SQL)
EXEC(@SQL)			

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BorrowLendBillDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_BorrowLendBillDraft
GO


/*------------------------------------------
 作者：蒋奎
 日期：2015-4-9
 描述：借欠单据草稿查询
-------------------------------------------*/
CREATE          PROCEDURE Web_BorrowLendBillDraft
( 
	@OperatorID		VARCHAR(50),
	@BeginDate		VARCHAR(25)='',
	@EndDate		VARCHAR(25)='',
	@BillCode		VARCHAR(200)='',
	@BillType		VARCHAR(5)='',
	@EtypeName		VARCHAR(max)='',  --经手人
	@BtypeName		VARCHAR(max)='',  --客户
	@KtypeName		VARCHAR(max)='',  --仓库
	@Comment		VARCHAR(256)='',
	@Explain		VARCHAR(256)='',
	@Memo			VARCHAR(256)='',
	@BillNumberId	NUMERIC(10)=0,
	@OrderBy		VARCHAR(250)='',
	@FilterBill		VARCHAR(250)='',
	@STypeId		VARCHAR(MAX),
	@IsReporting	INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQLFrom  VARCHAR(1000)
DECLARE @SQLList  VARCHAR(2000)
DECLARE @SQLWhere VARCHAR(8000)
DECLARE @SQLOrder VARCHAR(200)

SELECT @SQLFrom  = ''
SELECT @SQLList  = ''
SELECT @SQLWhere = ''
SELECT @SQLOrder = ''

--多级权限
SELECT a.* INTO #btype FROM F_GetManBtypeAll(@OperatorID) a --往来单位权限
SELECT a.* INTO #stock FROM F_GetManKtypeAll(@OperatorID) a --仓库权限
SELECT a.TypeId INTO #employee FROM F_GetManDetailEtype(@OperatorID) a --职员权限
IF ISNULL(@EtypeName,'') = ''
	INSERT INTO #employee(TypeId)VALUES('')



-- 基本的显示字段
SELECT @SQLList = 'SELECT bi.*'
		     +',CBillType= '
		     +' CASE BillType '
		     +' WHEN 71 THEN ''借进'' '
		     +' WHEN 72  THEN ''借进还出'' '
		     +' WHEN 87  THEN ''借出'' '
		     +' WHEN 88 THEN ''借出还回'' '
		     +' END '
             +',ISNULL(e.TypeId,'''') AS etype '
		     +',ISNULL(k1.TypeId,'''') AS Ktype '
		     +',ISNULL(k1.usercode,'''') AS kusercode '
		     +',ISNULL(k2.FULLNAME,'''') AS Ktype2 '
		     +',ISNULL(b.TypeId,'''') AS btype '
		     +',ISNULL(a.TypeId,'''') AS atype '
		     +',ISNULL(p.TypeId,'''') AS ptype '
		     +',ISNULL(e.FULLNAME,'''') AS checkman '
		     +',ISNULL(e1.FULLNAME,'''') AS checkefullname '
		     
		     
-- 基本列表的SQL
SELECT @SQLFrom=' FROM LendIndex bi '
		      +' LEFT JOIN Btype b ON (bi.[dealBTypeId] = b.[TypeId]) '
		      +' LEFT JOIN Stock k1 ON (bi.[KtypeId] = k1.[Typeid]) '
		      +' LEFT JOIN Employee e ON (bi.[EtypeId] = e.[Typeid]) '
		      +' LEFT JOIN Employee e1 ON (bi.[checke] = e1.[Typeid]) '
		      +' LEFT  JOIN Atype a ON (bi.[AtypeId] = a.[TypeId]) '
		      +' LEFT  JOIN Ptype p ON (bi.[PtypeId] = p.[TypeId]) '
		      +' LEFT  JOIN Stock k2 ON (bi.[KtypeId2] = k2.[Typeid])'
                                 +' RIGHT OUTER JOIN (SELECT dbo.lendbill.billNumberId FROM lendbill WHERE (dbo.LendBill.comment LIKE ''%'
		      +RTRIM(@Memo)
		      +'%'') GROUP BY dbo.LendBill.billNumberId)  lb ON (bi.BillNumberId = lb.BillNumberId) '
		      

-- 限制条件
IF RTRIM(@BeginDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillDate]>=''' + RTRIM(@BeginDate) +''' '
IF RTRIM(@EndDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillDate]<=''' + RTRIM(@EndDate) +''' '
IF @BillNumberId<>0
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillNumberID]=' + STR(@BillNumberId) +' '
IF RTRIM(@BillCode)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillCode] LIKE ''%' + RTRIM(@BillCode) +'%'' '
IF RTRIM(@Comment)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[Comment] LIKE ''%' + RTRIM(@Comment) +'%'' '
IF RTRIM(@Explain)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[Explain] LIKE ''%' + RTRIM(@Explain) +'%'' '
IF RTRIM(@BillType)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillType] = ' + RTRIM(@BillType) +' '

IF RTRIM(@EtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.[etypeid] IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@EtypeName+''',3))) '
IF RTRIM(@BtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.dealbtypeid IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@BtypeName+''',2))) '
IF RTRIM(@KtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.[ktypeid] IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@KtypeName+''',4))) '

SELECT @SQLWhere = @SQLWhere + ' AND bi.STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''+@STypeId+''',11,'''+@OperatorID+''')) '	
SELECT @SQLWhere = @SQLWhere + ' AND (bi.DTypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''',9,'''+@OperatorID+''')) OR ISNULL(bi.DTypeId,'''')='''' )'	
	
--多级权限过滤
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[etypeid] IN (SELECT typeid FROM #employee))'
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[dealbtypeid] IN (SELECT typeid FROM #btype))'
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[ktypeid] IN (SELECT typeid FROM #stock))'

 
-- 去掉多余的 AND
IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + RIGHT(@SQLWhere,LEN(@SQLWhere)-4)

-- 排序
IF RTRIM(@OrderBy)<>''
	SELECT @SQLOrder = ' ORDER BY ' + RTRIM(@OrderBy)
ELSE
	SELECT @SQLOrder = ' ORDER BY  bi.[BillDate], bi.[BillCode] '


--PRINT(@SQLList + @SQLFrom + @SQLWhere +  @SQLOrder )
--EXEC (@SQLList + @SQLFrom + @SQLWhere +  @SQLOrder )


----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
IF(@IsReporting = 0)
BEGIN
	--PRINT @SQL
	EXEC (@SQLList + @SQLFrom + @SQLWhere +  @SQLOrder )
END
ELSE IF(@IsReporting = 1)
BEGIN
	CREATE TABLE #tmp_result
	(
		billnumberid VARCHAR(100),
		billtype     VARCHAR(100),
		Costom1		VARCHAR(max),
		Costom2		VARCHAR(max),
		Costom3		VARCHAR(max),
		Costom4		VARCHAR(max),
		Costom5		VARCHAR(max),
		Costom6		VARCHAR(max),
		Costom7		VARCHAR(max),
		Costom8		VARCHAR(max),
		Costom9		VARCHAR(max),
		Costom10	VARCHAR(max),
		Costom11	VARCHAR(max),
		Costom12	VARCHAR(max),
		Costom13	VARCHAR(max),
		Costom14	VARCHAR(max),
		Costom15	VARCHAR(max),
		Costom16	VARCHAR(max)
	)
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQLList + @SQLFrom + @SQLWhere + ') AS bi ' + @SQLOrder + 
			  ' 
			   DECLARE @p1 dbo.TBType_SelfType  
			   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
			   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 

				--显示最终结果
				SELECT a.*,
						  b.Costom1,
						  b.Costom2,
						  b.Costom3,
						  b.Costom4,
						  b.Costom5,
						  b.Costom6,
						  b.Costom7,
						  b.Costom8,
						  b.Costom9,
						  b.Costom10,
						  b.Costom11,
						  b.Costom12,
						  b.Costom13,
						  b.Costom14,
						  b.Costom15,
						  b.Costom16 
						  FROM #temp1 a 
						  left join #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
						  
				DROP TABLE #temp1,#tmp_result
			   '
	EXEC (@SQL)
END	
----------------------------------------------------------


--删除零时表
DROP TABLE #btype 
DROP TABLE #stock
DROP TABLE #employee












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_BorrowLendQtyLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].Web_BorrowLendQtyLine
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
	作者：蒋奎
	日期：2015-3-25
	描述：借欠线性表
-------------------------------------------*/
CREATE PROCEDURE Web_BorrowLendQtyLine
  (
    @OperatorID varchar(50),		--操作员ID
 	@StartDate	VARCHAR(50),
	@EndDate	VARCHAR(50),
	@PtypeId	VARCHAR(max),
	@BtypeId	VARCHAR(max),
	@EtypeId	VARCHAR(max),
	@KtypeId	VARCHAR(max),
	@STypeId		VARCHAR(MAX),	--分支机构ID
	@dtypeId	VARCHAR(max),
 	@explain    VARCHAR(500),
	@comment	VARCHAR(500),
 	@IsReporting	INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
DECLARE @SQL VARCHAR(MAX)
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--多级权限
SELECT TypeId INTO #ptype FROM F_GetAllManagerBaseTypeId(@PtypeId,1,@OperatorID) a --商品权限
SELECT TypeId INTO #btype FROM F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorID) a --往来单位权限
SELECT TypeId INTO #stock FROM F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorID) a --仓库权限
SELECT TypeId INTO #employee FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID) a --职员权限
SELECT TypeId INTO #stype FROM  F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)a --分支机构权限
SELECT TypeId INTO #dtype FROM  F_GetAllManagerBaseTypeId(@dtypeId,9,@OperatorId)a --部门权限
	
-------------------------------------------------------出借欠商品汇总数据开始---------------------------------------------------------------
	
    SELECT  a.Ptypeid ,
            SUM(CASE WHEN x.BillType = 71 THEN a.qty
                     ELSE 0
                END) AS 'BorrowQty' , /*借进数量*/
            SUM(CASE WHEN x.BillType = 72 THEN a.qty
                     ELSE 0
                END) AS 'BorrowBackQty' ,/*借进还出数量*/
            ABS(SUM(CASE WHEN x.BillType = 71 THEN a.qty
                         ELSE 0
                    END)) - ABS(SUM(CASE WHEN x.BillType = 72 THEN a.qty
                                         ELSE 0
                                    END)) AS 'BorrowNotBackQty' ,/*借进未还数量*/
            SUM(CASE WHEN x.BillType = 87 THEN a.qty
                     ELSE 0
                END) AS 'LendQty' , /*借出数量*/
            SUM(CASE WHEN x.BillType = 88 THEN a.qty
                     ELSE 0
                END) AS 'LendBackQty' , /*借出还回数量*/
            ABS(SUM(CASE WHEN x.BillType = 87 THEN a.qty
                         ELSE 0
                    END)) - ABS(SUM(CASE WHEN x.BillType = 88 THEN a.qty
                                         ELSE 0
                                    END)) AS 'LendNotBackQty'  /*借出未还数量*/ ,
            0 AS saleqty ,
            0 AS buyqty
    INTO    #BorrowLendQty
    FROM    lendbill a
            INNER JOIN lendindex x ON a.billnumberid = x.billnumberid
            INNER JOIN dbo.ptype p ON a.PtypeId = p.typeId /*此连接用来出商品名称,商品编码等*/
            INNER JOIN #ptype tp ON a.PtypeId = tp.TypeId  /*此连接用来过滤商品*/
            INNER JOIN #employee e ON x.etypeid = e.TypeId
            INNER JOIN #btype b ON x.btypeid = b.TypeId
            INNER JOIN #stock s ON x.ktypeid = s.TypeId
            INNER JOIN #stype ss ON x.Stypeid = ss.TypeId
            INNER JOIN #dtype d ON x.DTypeID = d.TypeId
    WHERE   x.billdate BETWEEN @StartDate AND @EndDate
            AND p.deleted = 0
            AND x.ifcheck = 't'
            AND RedWord = 0
            AND x.explain LIKE '%' + @explain + '%'
            AND x.Comment LIKE '%' + @comment + '%'
            AND p.IsService = 0
            AND p.iscombinationproduct =0
    GROUP BY a.PtypeId
    UNION ALL
    SELECT  bb.Ptypeid ,
            0 , /*借进数量*/
            0 ,/*借进还出数量*/
            0 ,/*借进未还数量*/
            0 , /*借出数量*/
            0 , /*借出还回数量*/
            0  /*借出未还数量*/ ,
            SUM(bb.Qty) AS saleqty ,
            0
    FROM    dbo.BillIndex a
            INNER JOIN dbo.SaleBill bb ON a.BillNumberId = bb.BillNumberId
            INNER JOIN dbo.ptype p ON bb.PtypeId = p.typeId /*此连接用来出商品名称,商品编码等*/
            INNER JOIN #ptype tp ON bb.PtypeId = tp.TypeId  /*此连接用来过滤商品*/
            INNER JOIN #employee e ON a.etypeid = e.TypeId
            INNER JOIN #btype b ON a.btypeid = b.TypeId
            INNER JOIN #stock s ON a.ktypeid = s.TypeId
            INNER JOIN #stype ss ON a.Stypeid = ss.TypeId
            INNER JOIN #dtype d ON a.DTypeID = d.TypeId
    WHERE   IsLend = 1
            AND a.billdate BETWEEN @StartDate AND @EndDate
            AND p.deleted = 0
            AND a.ifcheck = 't'
            AND RedWord = 0
            AND a.explain LIKE '%' + @explain + '%'
            AND a.Comment LIKE '%' + @comment + '%'
            AND p.IsService = 0
            AND p.iscombinationproduct =0
    GROUP BY bb.PtypeId
    UNION ALL
    SELECT  bb.Ptypeid ,
            0 , /*借进数量*/
            0 ,/*借进还出数量*/
            0 ,/*借进未还数量*/
            0 , /*借出数量*/
            0 , /*借出还回数量*/
            0  /*借出未还数量*/ ,
            0 ,
            SUM(bb.Qty) AS buyqty
    FROM    dbo.BillIndex a
            INNER JOIN dbo.BuyBill bb ON a.BillNumberId = bb.BillNumberId
            INNER JOIN dbo.ptype p ON bb.PtypeId = p.typeId /*此连接用来出商品名称,商品编码等*/
            INNER JOIN #ptype tp ON bb.PtypeId = tp.TypeId  /*此连接用来过滤商品*/
            INNER JOIN #employee e ON a.etypeid = e.TypeId
            INNER JOIN #btype b ON a.btypeid = b.TypeId
            INNER JOIN #stock s ON a.ktypeid = s.TypeId
            INNER JOIN #stype ss ON a.Stypeid = ss.TypeId
            INNER JOIN #dtype d ON a.DTypeID = d.TypeId
    WHERE   IsLend = 1
            AND a.billdate BETWEEN @StartDate AND @EndDate
            AND p.deleted = 0
            AND a.ifcheck = 't'
            AND RedWord = 0
            AND a.explain LIKE '%' + @explain + '%'
            AND a.Comment LIKE '%' + @comment + '%'
            AND p.IsService = 0
            AND p.iscombinationproduct =0
    GROUP BY bb.PtypeId
-------------------------------------------------------出借欠商品汇总数据结束---------------------------------------------------------------

		
--全部商品
IF @PtypeId =''
BEGIN
		SELECT 
				p.typeId,
				p.ParId,
				p.sonnum,
				p.UserCode,
				p.FullName,
				p.[Standard],
				ABS(ISNULL(q.borrowqty,0)) AS 'BorrowQty',
				ABS(ISNULL(q.borrowbackqty,0)) AS 'borrowbackqty',
				(ISNULL(q.borrownotbackqty,0)-q.buyqty) AS 'borrownotbackqty',
				ABS(ISNULL(q.lendqty,0)) AS 'lendqty',
				ABS(ISNULL(q.lendbackqty,0)) AS 'lendbackqty',
				(ISNULL(q.lendnotbackqty,0)-q.saleqty) AS 'lendnotbackqty',				
				ABS(ISNULL(q.saleqty,0)) AS 'saleqty',
			   	ABS(ISNULL(q.buyqty,0)) AS 'buyqty'
		FROM dbo.ptype p
		INNER JOIN #ptype b ON p.typeId=b.TypeId
		LEFT JOIN (SELECT PtypeId,SUM(BorrowQty)AS BorrowQty
		               ,SUM(BorrowBackQty)AS BorrowBackQty
		               , SUM (BorrowNotBackQty) AS BorrowNotBackQty
		               ,SUM(lendqty) AS lendqty
		               ,SUM(lendbackqty) AS lendbackqty
		               ,SUM(lendnotbackqty) AS lendnotbackqty
		               ,SUM(saleqty) AS saleqty
		               ,SUM(buyqty) AS buyqty
		   FROM #BorrowLendQty GROUP BY PtypeId) q  ON p.typeid=q.PtypeId
		WHERE	p.sonnum=0 
				AND p.IsService=0
				AND p.iscombinationproduct = 0
		ORDER BY  p.UserCode
END

--某个商品
IF @PtypeId <>'' 
BEGIN
		SELECT 
				p.typeId,
				p.ParId,
				p.sonnum,
				p.UserCode,
				p.FullName,
				p.[Standard],
				ABS(ISNULL(q.borrowqty,0)) AS 'BorrowQty',
				ABS(ISNULL(q.borrowbackqty,0)) AS 'borrowbackqty',
				(ISNULL(q.borrownotbackqty,0)-q.buyqty) AS 'borrownotbackqty',
				ABS(ISNULL(q.lendqty,0)) AS 'lendqty',
				ABS(ISNULL(q.lendbackqty,0)) AS 'lendbackqty',
				(ISNULL(q.lendnotbackqty,0)-q.saleqty) AS 'lendnotbackqty',
					   ABS(ISNULL(q.saleqty,0)) AS 'saleqty',
			   	ABS(ISNULL(q.buyqty,0)) AS 'buyqty'
		FROM dbo.ptype p
		INNER JOIN #ptype b ON p.typeId=b.TypeId
		LEFT JOIN (SELECT PtypeId,SUM(BorrowQty)AS BorrowQty
		               ,SUM(BorrowBackQty)AS BorrowBackQty
		               , SUM (BorrowNotBackQty) AS BorrowNotBackQty
		               ,SUM(lendqty) AS lendqty
		               ,SUM(lendbackqty) AS lendbackqty
		               ,SUM(lendnotbackqty) AS lendnotbackqty
		               ,SUM(saleqty) AS saleqty
		               ,SUM(buyqty) AS buyqty
		   FROM #BorrowLendQty GROUP BY PtypeId) q  ON p.typeid=q.PtypeId
		WHERE	p.IsService=0
				AND p.iscombinationproduct = 0
		ORDER BY  p.UserCode
END	

 

-----------------------------------------------------------------------------------------------------------------------------------

--删除零时表
DROP TABLE #ptype,#btype,#stock,#stype,#employee,#BorrowLendQty
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_BorrowLendQtyList]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
    DROP PROCEDURE [dbo].Web_BorrowLendQtyList;
GO

SET QUOTED_IDENTIFIER ON; 
GO
SET ANSI_NULLS ON; 
GO
/*------------------------------------------
	作者：蒋奎
	日期：2015-3-25
	描述：借欠树形表
-------------------------------------------*/
CREATE PROCEDURE Web_BorrowLendQtyList
    (
      @OperatorID VARCHAR(50) ,		--操作员ID
      @ntype BIT ,		--下一步状态
      @TypeID VARCHAR(50) ,		--上下层传的商品ID , 如果有值就是上下层查询 ,没值为查询条件查询
      @paridq VARCHAR(100) ,		--前台传的父节点ID
      @selectType VARCHAR(50) ,		--查询类型
      @StartDate VARCHAR(50) ,
      @EndDate VARCHAR(50) ,
      @PtypeId VARCHAR(MAX) ,
      @BtypeId VARCHAR(MAX) ,
      @EtypeId VARCHAR(MAX) ,
      @KtypeId VARCHAR(MAX) ,
      @STypeId VARCHAR(MAX) ,		--分支机构ID
      @dTypeId VARCHAR(MAX) ,		
      @explain VARCHAR(500) ,
      @comment VARCHAR(500) ,
      @IsReporting INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
    )
--@encode$--
AS
    DECLARE @SQL VARCHAR(MAX);
    SET NOCOUNT ON; 
    SET ANSI_WARNINGS OFF;
--------------------------------------------------------------权限检查-------------------------------------------------------
    IF @OperatorID IS NULL
        RETURN 1;
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50);
    EXEC @Re= GP_CheckOperatorRight23 @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT;
    IF @Re <> 0
        RETURN @Re;
--------------------------------------------------------------权限检查-------------------------------------------------------
--多级权限
    SELECT  TypeId
    INTO    #ptype
    FROM    F_GetAllManagerBaseTypeId(@PtypeId, 1, @OperatorID) a; --商品权限
    SELECT  TypeId
    INTO    #btype
    FROM    F_GetAllManagerBaseTypeId(@BtypeId, 2, @OperatorID) a; --往来单位权限
    SELECT  TypeId
    INTO    #stock
    FROM    F_GetAllManagerBaseTypeId(@KtypeId, 4, @OperatorID) a; --仓库权限
    SELECT  TypeId
    INTO    #employee
    FROM    F_GetAllManagerBaseTypeId(@EtypeId, 3, @OperatorID) a; --职员权限
    SELECT  TypeId
    INTO    #stype
    FROM    F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID) a; --分支机构权限
    SELECT  TypeId
    INTO    #dtype
    FROM    F_GetAllManagerBaseTypeId(@dtypeId, 9, @OperatorID) a; --部门权限
	
-------------------------------------------------------出借欠商品汇总数据开始---------------------------------------------------------------
		
    SELECT  a.PtypeId ,
            SUM(CASE WHEN x.BillType = 71 THEN a.Qty
                     ELSE 0
                END) AS 'BorrowQty' , /*借进数量*/
            SUM(CASE WHEN x.BillType = 72 THEN a.Qty
                     ELSE 0
                END) AS 'BorrowBackQty' ,/*借进还出数量*/
            ABS(SUM(CASE WHEN x.BillType = 71 THEN a.Qty
                         ELSE 0
                    END)) - ABS(SUM(CASE WHEN x.BillType = 72 THEN a.Qty
                                         ELSE 0
                                    END)) AS 'BorrowNotBackQty' ,/*借进未还数量*/
            SUM(CASE WHEN x.BillType = 87 THEN a.Qty
                     ELSE 0
                END) AS 'LendQty' , /*借出数量*/
            SUM(CASE WHEN x.BillType = 88 THEN a.Qty
                     ELSE 0
                END) AS 'LendBackQty' , /*借出还回数量*/
            ABS(SUM(CASE WHEN x.BillType = 87 THEN a.Qty
                         ELSE 0
                    END)) - ABS(SUM(CASE WHEN x.BillType = 88 THEN a.Qty
                                         ELSE 0
                                    END)) AS 'LendNotBackQty'  /*借出未还数量*/ ,
            0 AS saleqty ,
            0 AS buyqty
    INTO    #BorrowLendQty
    FROM    LendBill a
            INNER JOIN LendIndex x ON a.BillNumberId = x.BillNumberId
            INNER JOIN dbo.ptype p ON a.PtypeId = p.typeId /*此连接用来出商品名称,商品编码等*/
            INNER JOIN #ptype tp ON a.PtypeId = tp.TypeId  /*此连接用来过滤商品*/
            INNER JOIN #employee e ON x.etypeid = e.TypeId
            INNER JOIN #btype b ON x.btypeid = b.TypeId
            INNER JOIN #stock s ON x.ktypeid = s.TypeId
            INNER JOIN #stype ss ON x.Stypeid = ss.TypeId
            INNER JOIN #dtype d ON x.DTypeID = d.TypeId
    WHERE   x.BillDate BETWEEN @StartDate AND @EndDate
            AND p.deleted = 0
            AND x.ifcheck = 't'
            AND RedWord = 0
            AND x.explain LIKE '%' + @explain + '%'
            AND x.Comment LIKE '%' + @comment + '%'
            AND p.IsService = 0
            AND p.iscombinationproduct = 0
    GROUP BY a.PtypeId
    UNION ALL
    SELECT  bb.PtypeId ,
            0 , /*借进数量*/
            0 ,/*借进还出数量*/
            0 ,/*借进未还数量*/
            0 , /*借出数量*/
            0 , /*借出还回数量*/
            0  /*借出未还数量*/ ,
            SUM(bb.Qty) AS saleqty ,
            0
    FROM    dbo.BillIndex a
            INNER JOIN dbo.SaleBill bb ON a.BillNumberId = bb.BillNumberId
            INNER JOIN dbo.ptype p ON bb.PtypeId = p.typeId /*此连接用来出商品名称,商品编码等*/
            INNER JOIN #ptype tp ON bb.PtypeId = tp.TypeId  /*此连接用来过滤商品*/
            INNER JOIN #employee e ON a.etypeid = e.TypeId
            INNER JOIN #btype b ON a.btypeid = b.TypeId
            INNER JOIN #stock s ON a.ktypeid = s.TypeId
            INNER JOIN #stype ss ON a.Stypeid = ss.TypeId
            INNER JOIN #dtype d ON a.DTypeId = d.TypeId
    WHERE   a.BillDate BETWEEN @StartDate AND @EndDate
            AND p.deleted = 0
            AND a.ifcheck = 't'
            AND RedWord = 0
            AND a.explain LIKE '%' + @explain + '%'
            AND a.Comment LIKE '%' + @comment + '%'
            AND IsLend = 1
            AND p.IsService = 0
            AND p.iscombinationproduct = 0
    GROUP BY bb.PtypeId
    UNION ALL
    SELECT  bb.PtypeId ,
            0 , /*借进数量*/
            0 ,/*借进还出数量*/
            0 ,/*借进未还数量*/
            0 , /*借出数量*/
            0 , /*借出还回数量*/
            0  /*借出未还数量*/ ,
            0 ,
            SUM(Qty) AS buyqty
    FROM    dbo.BillIndex a
            INNER JOIN dbo.BuyBill bb ON a.BillNumberId = bb.BillNumberId
            INNER JOIN dbo.ptype p ON bb.PtypeId = p.typeId /*此连接用来出商品名称,商品编码等*/
            INNER JOIN #ptype tp ON bb.PtypeId = tp.TypeId  /*此连接用来过滤商品*/
            INNER JOIN #employee e ON a.etypeid = e.TypeId
            INNER JOIN #btype b ON a.btypeid = b.TypeId
            INNER JOIN #stock s ON a.ktypeid = s.TypeId
            INNER JOIN #stype ss ON a.Stypeid = ss.TypeId
            INNER JOIN #dtype d ON a.DTypeId = d.TypeId
    WHERE   a.BillDate BETWEEN @StartDate AND @EndDate
            AND p.deleted = 0
            AND a.ifcheck = 't'
            AND RedWord = 0
            AND a.explain LIKE '%' + @explain + '%'
            AND a.Comment LIKE '%' + @comment + '%'
            AND IsLend = 1
    GROUP BY bb.PtypeId;
--调试SQL
--SELECT	* FROM 	#BorrowLendQty	
-------------------------------------------------------出借欠商品汇总数据结束---------------------------------------------------------------
    DECLARE @chvLen VARCHAR(10);

--上下层时@ptypeid的处理
    IF @TypeID <> ''
        AND @ntype = '1' --下一层
        SET @PtypeId = @TypeID;
    IF @TypeID <> ''
        AND @ntype = '0' --上一层
        SET @PtypeId = ( SELECT ParId
                         FROM   dbo.ptype
                         WHERE  typeId = @TypeID
                       );

--@chvLen 是 GROUP BY 用的截取长度,用做父节点汇总
    IF @PtypeId = '00000'
        SET @chvLen = '5';
    ELSE
        SET @chvLen = CAST(LEN(@PtypeId) + 5 AS VARCHAR(20));


    DECLARE @SQLOut VARCHAR(MAX)= '';
--数据源
    SET @SQLOut += '
			
				SELECT 
					p.typeId,
					p.ParId,
					p.sonnum,
					p.UserCode,
					p.FullName,
					p.[Standard],
					ABS(ISNULL(q.borrowqty,0)) AS ''BorrowQty'',
					ABS(ISNULL(q.borrowbackqty,0)) AS ''borrowbackqty'',
					ISNULL(q.borrownotbackqty,0)-q.buyqty AS ''borrownotbackqty'',
					ABS(ISNULL(q.lendqty,0)) AS ''lendqty'',
					ABS(ISNULL(q.lendbackqty,0)) AS ''lendbackqty'',
					ISNULL(q.lendnotbackqty,0)-q.saleqty  AS ''lendnotbackqty'',
					ABS(ISNULL(q.saleqty,0)) AS ''saleqty'',
					ABS(ISNULL(q.buyqty,0)) AS ''buyqty''
				FROM dbo.ptype p
				INNER JOIN dbo.F_TreeP(''' + @OperatorID
        + ''') b ON p.typeId=b.TypeId AND p.IsService=0 and p.iscombinationproduct = 0
				LEFT JOIN ( /*贴汇总数据*/
							SELECT
								SUBSTRING(a.PtypeId, 1,' + @chvLen
        + ') AS PtypeID,
								SUM( ABS(ISNULL(a.borrowqty,0)) ) AS ''BorrowQty'',
								SUM( ABS(ISNULL(a.borrowbackqty,0)) ) AS ''borrowbackqty'',
								SUM( ISNULL(a.borrownotbackqty,0) ) AS ''borrownotbackqty'',
								SUM( ABS(ISNULL(a.lendqty,0)) ) AS ''lendqty'',
								SUM( ABS(ISNULL(a.lendbackqty,0)) ) AS ''lendbackqty'',
								SUM( ISNULL(a.lendnotbackqty,0) ) AS ''lendnotbackqty'',
								SUM( ABS(ISNULL(a.saleqty,0)) ) AS ''saleqty'',
								SUM( ABS(ISNULL(a.buyqty,0)) ) AS ''buyqty''
							FROM #BorrowLendQty a
							GROUP BY
								SUBSTRING(a.PtypeId, 1,' + @chvLen + ')
				) q  ON q.PtypeId=p.typeid
			';
--查询
    IF @TypeID = ''
        BEGIN
            IF @PtypeId = ''  --查询所有
                SET @SQLOut += '
					WHERE ParId = ''00000'' 
					ORDER BY  p.SortID
					';
		 
		
            IF @PtypeId <> ''	--查询指定商品
		--	SET @SQLOut+='
		--			WHERE p.typeId = '''+@PtypeId +'''
		--			ORDER BY  p.SortID
		--			'
                BEGIN
                    SET @SQLOut += '
					WHERE p.typeId like ''' + @PtypeId + '%''
					
					';
                    DECLARE @sql2 VARCHAR(5000);
                    SET @sql2 = 'SELECT ''' + @PtypeId + ''' AS typeId,
						   SUM(A.BorrowQty) AS BorrowQty,
						   SUM(A.borrowbackqty) borrowbackqty,
						   SUM(A.borrownotbackqty) borrownotbackqty,
						   SUM(A.lendqty) lendqty, 
						   SUM(A.lendbackqty) lendbackqty,
						   SUM(A.lendnotbackqty) lendnotbackqty,
						   SUM(A.saleqty) saleqty,
						   SUM(A.buyqty) buyqty FROM (';
                    SET @sql2 = @sql2 + @SQLOut;
                    SET @sql2 = @sql2 + ') AS A ';
                    SET @sql2 = 'SELECT P.sonnum ,
											 P.UserCode ,
											 P.FullName ,
											 P.[Standard] , B.* FROM ('
                        + @sql2
                        + ') B INNER JOIN PTYPE P ON P.TYPEID=B.typeId';
                    SET @SQLOut = @sql2;
                END; 
        END;

--上一层下一层查询

    IF @TypeID <> ''
        BEGIN
            DECLARE @ParId VARCHAR(50);
	--取ParId
            SELECT  @ParId = p.ParId
            FROM    dbo.ptype p
                    INNER JOIN dbo.F_TreeP(@OperatorID) b ON p.typeId = b.TypeId
            WHERE   p.typeId = @TypeID;
	--上一层
            IF @ntype = '0'
                SET @SQLOut += '
					WHERE p.ParId = ''' + @ParId + '''
					ORDER BY  p.SortID
					'; 
		
		 
	--下一层
            IF @ntype = '1'
                SET @SQLOut += '
					WHERE p.ParId = ''' + @TypeID + '''
					ORDER BY  p.SortID
					'; 
			
        END;
--SELECT @SQLOut
    EXEC (@SQLOut);


-----------------------------------------------------------------------------------------------------------------------------------

--删除零时表
    DROP TABLE #ptype,#btype,#dtype,#stock,#stype,#employee,#BorrowLendQty;
GO
SET QUOTED_IDENTIFIER OFF; 
GO
SET ANSI_NULLS ON; 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BrandarCommondityCanDel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BrandarCommondityCanDel]
GO

/*
	作者：谢吉康
	日期：2017-11-26
	描述：判断能否删除品牌ID
*/
CREATE PROCEDURE Web_BrandarCommondityCanDel
(
	@TypeId			VARCHAR(500),			--品牌ID
	@errMsg			VARCHAR(500) OUTPUT		--输出信息
)
AS
SET NOCOUNT ON

--判断商品是否使用
IF EXISTS(select top 1 1 from ptype where brandartypeid = @TypeId)
BEGIN
	SET @errMsg = '商品品牌已经被商品信息使用，不能修改或者删除！'
	RETURN -1
END

--相关单据判断
/*
SELECT s.NAME FROM sysobjects s,syscolumns c WHERE s.id = c.id AND s.xtype = 'u' AND c.name = 'brandartypeid' ORDER BY s.name ASC
AdDebtBill
BillMulBrand
Brandar_ArApTotal
CompleteBrandarTotal
gatheringBill
ImportMoneyBillTemp
MoneyBill
PreBill
ptype
AccountCredence
*/
IF EXISTS(select top 1 1 from AdDebtBill where brandartypeid = @TypeId AND ISNULL(brandartypeid,'') <> '')
	OR EXISTS(select top 1 1 from BillMulBrand where brandartypeid = @TypeId AND ISNULL(brandartypeid,'') <> '')
	OR EXISTS(select top 1 1 from Brandar_ArApTotal where brandartypeid = @TypeId AND ISNULL(brandartypeid,'') <> '')
	OR EXISTS(select top 1 1 from CompleteBrandarTotal where brandartypeid = @TypeId AND ISNULL(brandartypeid,'') <> '')
	OR EXISTS(select top 1 1 from gatheringBill where brandartypeid = @TypeId AND ISNULL(brandartypeid,'') <> '')
	OR EXISTS(select top 1 1 from ImportMoneyBillTemp where brandartypeid = @TypeId AND ISNULL(brandartypeid,'') <> '')
	OR EXISTS(select top 1 1 from MoneyBill M INNER JOIN BillIndex B ON B.BillNumberId=M.BillNumberId AND B.BillType<>158 AND M.BrandarTypeId= @TypeId AND ISNULL(M.BrandarTypeId,'') <> '')
	OR EXISTS(select top 1 1 from PreBill where brandartypeid = @TypeId AND ISNULL(brandartypeid,'') <> '')
	OR EXISTS(select top 1 1 from AccountCredence where brandartypeid = @TypeId AND ISNULL(brandartypeid,'') <> '')
BEGIN
	SET @errMsg = '商品品牌已经被相关单据使用，不能删除！'
	RETURN -1
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BTypeGatherDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BTypeGatherDetailQuery]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：黄飞佳	
	日期：2012-05-24
	描述：客户销售汇总明细
*/
/*
    修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
    
    修改：舒珊
    日期：2015-05-27
    描述： 添加商品类别筛选
    
    修改：舒珊
    日期：2016-06-21
    描述： 换算率变更前销售单位数量统计
*/
/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Web_BTypeGatherDetailQuery
(
	@chvStartDate		VARCHAR(30),			-- 查询起始时间
	@chvENDDate		    VARCHAR(30),			-- 查询结束时间
	@chvPTypeID			VARCHAR(max),			-- 树型表或线性表商品类别查询范围父节点 ID
	@chvBTypeID			VARCHAR(max),			-- 结算单位
	@chvETypeID			VARCHAR(max),			-- 树型表或线性表职员类别查询范围父节点 ID
	@chvKTypeID			VARCHAR(max),			-- 树型表或线性表仓库类别查询范围父节点 ID
	@chvDTypeID			VARCHAR(max),			-- 树型表或线性表部门类别查询范围父节点 ID
	@chvStypeID			VARCHAR(max)='00000',	-- 树型表或线性表分支机构类别查询范围父节点 ID
	@sortfield			VARCHAR(50),			-- 明细表排序方式
	@checkCode			VARCHAR(max)= '',	    -- 制单人编号
	@checkName			VARCHAR(max)= '',	    -- 制单人名称
	@chvOperatorID		VARCHAR(50),			-- 操作员 ID ( 作权限范围检查用 )
	@chkRed        		CHAR(1) ='0',		    -- 显示红冲单据
	@chvBilltype    	VARCHAR(200),           -- 单据类型
	@chvComment     	VARCHAR(200)='',        -- 说明
	@chvZY 				VARCHAR(200)='',        -- 摘要
	@dealbtypeid        VARCHAR(max),           -- 往来单位
	@chvPF        		CHAR(1) ='0'  ,          --价保获利反利等
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON

--------权限检查-Start--------
IF @chvOperatorID is null RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re <> 0 RETURN @Re
--------权限检查-End--------  


--------创建临时表-Start--------
--单据类型
CREATE TABLE #Billtype (BillType VARCHAR(200))
INSERT INTO #Billtype SELECT a AS Billtype FROM dbo.f_split(@chvBilltype,',')

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Ktype SELECT typeid,usercode,fullname FROM Stock WHERE typeId in(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvKTypeID,4,@chvOperatorID))
IF (@chvKTypeID='10000' OR  @chvKTypeID='' OR  @chvKTypeID='00000') AND NOT EXISTS(SELECT * FROM #Ktype WHERE typeid='10000') 
INSERT INTO #Ktype SELECT '10000','10000','代销仓库'

	
--商品
CREATE TABLE #Ptype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Ptype SELECT typeid,usercode,fullname FROM Ptype WHERE typeid IN(SELECT typeid FROM F_ManPTypeInCategoryID ( @chvOperatorID,@chvPTypeID,@ptypecategoryid))

--分支机构
CREATE TABLE #Stype (TypeID VARCHAR(50))
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvSTypeID,11,@chvOperatorID)

--结算单位	
CREATE TABLE #Btype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Btype SELECT typeid,usercode,fullname FROM Btype WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBTypeID,2,@chvOperatorID))

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #DealBtype SELECT typeid,usercode,fullname FROM Btype WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID))
--职员
CREATE TABLE #Etype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Etype SELECT typeid,usercode,fullname FROM Employee WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvETypeID,3,@chvOperatorID))

--部门
CREATE TABLE #Dtype (TypeID VARCHAR(50))
INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@chvOperatorID)

--费用分摊设置
DECLARE @config int=0
SELECT	@config=Value FROM Userconfig WHERE ConfigName='sharefee'	

	

--------创建索引Start-------
CREATE CLUSTERED INDEX CIX_GetManKTypeID ON #Ktype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManETypeID ON #Etype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManPTypeID ON #Ptype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManSTypeID ON #Stype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManBTypeID ON #Btype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManDTypeID ON #Dtype(TypeID)
--------创建索引End-------

--单据索引表
	CREATE TABLE #BillIndex
	(
	    BillNumberID NUMERIC(18,0),
	    BillCode VARCHAR(200),
	    BillDate DATETIME,
	    Billtype NUMERIC(10,0),
	    Tax  NUMERIC(24, 10) ,
	    RedWord INT,
		TotalMoney  NUMERIC(24, 10) ,
		TotalInMoney  NUMERIC(24, 10) ,
		CompleteTotal  NUMERIC(24, 10) ,
		BTypeID  VARCHAR (50),
		ETypeID  VARCHAR (50),
		ID			INT,
		PTypeID  VARCHAR (50),
		KTypeID  VARCHAR (50),
		PreferenceMoney  NUMERIC(24, 10) ,
		DtypeID VARCHAR(50),
		Checke  VARCHAR(50),
		Stypeid   VARCHAR(50),
		Draft BIT,
		Posttime DATETIME,
		Dealbtypeid VARCHAR(50),
		CName VARCHAR(200),
		Rate   NUMERIC(24, 10) ,
		Explain VARCHAR(MAX),
		comment	VARCHAR(2000)
	)

	DECLARE	@strBill   VARCHAR(MAX)
	SET @strBill = 
	             'INSERT INTO #BillIndex 
	              SELECT billnumberid,
	                     billcode,
	                     billdate,
	                     a.billtype,
	                     tax,
	                     redword,
	                     totalmoney,
	                     totalinmoney,
	                     completetotal,
	                     a.btypeid,
	                     a.etypeid,
						 A.ID,
	                     a.ptypeid,
	                     a.ktypeid,
	                     preferencemoney,
	                     a.dtypeid,
	                     checke,
	                     a.stypeid,
	                     a.draft,
	                     a.posttime,
	                     a.dealbtypeid,
	                     cu.fullname,
	                     a.rate,
	                     a.Explain,
	                     a.comment
	               FROM dbo.BillIndex a
	               INNER JOIN #Billtype b ON a.BillType = b.Billtype
	               INNER JOIN AC_Currency cu  ON a.cid = cu.cid
	               INNER JOIN #DealBtype dd ON a.dealbtypeid = dd.typeid '
	               IF (@chvBTypeID<>'' OR @MBTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF (@chvDTypeID<>'' OR @MDTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
                   IF (@chvETypeID<>'' OR @METypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Etype e ON a.etypeid = e.TypeID'
	               IF (@chvSTypeID<>'' OR @MSTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0''' 
	               
	               --增加发票立账405
	              SET @strBill += '
					UNION ALL 
					SELECT billnumberid,billcode,billdate,a.billtype,tax,redword,TotalMoney,0 as totalinmoney,completetotal,
					a.btypeid,a.etypeid,1 ID,'''' AS ptypeid,'''' AS ktypeid,TotalMoney AS preferencemoney,a.dtypeid,checke,
					a.stypeid,a.draft, posttime,a.dealbtypeid,cc.fullname,a.rate,
	                a.Explain ,a.comment
					FROM dbo.ReceiptBillIndex AS a 
					INNER JOIN #Billtype b ON a.BillType = b.Billtype
					INNER JOIN AC_Currency cc  ON a.cid = cc.cid 
					INNER JOIN #DealBtype dd ON a.dealbtypeid = dd.typeid '   
				   IF (@chvBTypeID<>'' OR @MBTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF (@chvDTypeID<>'' OR @MDTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
                   IF (@chvETypeID<>'' OR @METypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Etype e ON a.etypeid = e.TypeID'
	               IF (@chvSTypeID<>'' OR @MSTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0''' 
	--PRINT @strBill
	EXEC(@strBill)
--红冲
DECLARE @RED_WHERE varchar(200)
SET @RED_WHERE= ''
IF @chkRed ='0'
	SET @RED_WHERE ='  b.Redword='+char(39)+'0'+char(39)
ELSE
	SET @RED_WHERE =' 1=1 '
	
	
-- 确定查询时间段
DECLARE @SQL_WHERE varchar(2000)
SELECT  @SQL_WHERE = ' AND b.BillDate >= ''' + @chvStartDate + '''' + ' AND b.BillDate <= ''' + @chvENDDate + ''''	
----出入库表
    CREATE TABLE #InoutStockTable
    (
		BillNumberId numeric(18, 0) ,
		BillDate datetime,
		BillType numeric(10,0),
		ID			INT,
		PtypeId varchar (50),
		KtypeId varchar (50),
		Qty  NUMERIC(24, 10) ,
		Price    NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		taxprice  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		tax  NUMERIC(24, 10) ,
		costPrice  NUMERIC(24, 10) ,
		ShareFee  NUMERIC(24, 10) ,
		Cargoid INT,
		NPrice  NUMERIC(24, 10) ,
		NTotal  NUMERIC(24, 10) ,
		NSalePrice  NUMERIC(24, 10) ,
		NSaleTotal  NUMERIC(24, 10) ,
		NTaxPrice   NUMERIC(24, 10) ,
		NTaxTotal   NUMERIC(24, 10) ,
		FullName VARCHAR(2000),
		UserCode VARCHAR(200),
		NQty  NUMERIC(24, 10) ,
		MUnitID INT,
		NumName VARCHAR(200),
		Rate  NUMERIC(24, 10) ,
		nbrcqty  NUMERIC(24, 10) ,
		BaseUnitFullname  VARCHAR(50),
        AssistantFullname VARCHAR(50),
        GoodsNumber VARCHAR(100),
        bfullname		VARCHAR(200),
        saletotal		 NUMERIC(24, 10) ,
        saleprice		 NUMERIC(24, 10) ,
        comment			VARCHAR(1000),
		CustomdetailID int,
		zy  	VARCHAR(2000),
        discount    NUMERIC(24, 10)	
	)
	
	DECLARE @strInOut VARCHAR(MAX)
--**********************增加发票立账单据***********************--
	--SET @strInOut = 
	--         'INSERT INTO #InoutStockTable
	--          SELECT  b.BillnumberID,																														
	--                  a.BillDate,																														
	--                  a.BillType,																															
	--                  a.PtypeID,																															
	--                  a.KtypeID,
	--                  a.Qty,
	--				  a.price,
	--				  a.Total,	  
	--				  a.CostTotal,
	--				  a.taxprice,  
	--				  a.TaxTotal,
	--				  a.tax,
	--				  a.costprice,
	--				  a.sharefee,
	--				  a.cargoid,
	--				  a.nprice,
	--				  a.ntotal,
	--				  a.nsaleprice,
	--				  a.nsaletotal,
	--				  a.ntaxprice,
	--				  a.ntaxtotal,
	--				  v.fullname,
	--				  bb.usercode,
	--				  a.nqty,
	--				  a.munitid,
	--				  pu.fullname AS numname,
	--				  pe.rate AS rate,
	--				  fg.baseunitfullname AS baseunitfullname,
	--			      fg.assistantfullname AS assistantfullname,
	--			      a.goodsnumber,
	--			      BB.Fullname as bfullname,
	--			      SaleTotal,
	--			      SalePrice,
	--			      a.comment
	--          FROM	  InoutStockTable a 
	--          INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID AND a.BillType = b.BillType 
	--          LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	--          left JOIN PType_Units pu on pu.unitsid = a.munitid
	--		  left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
	--		  left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	--          INNER JOIN #PType p ON a.PTypeID=p.typeid
	--          INNER JOIN #dealBType bb ON bb.typeid = b.dealbtypeid'
	--	      IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
	--	          SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
 --             SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	--          IF (@checkCode<>'')
	--	          SET @strInOut = @strInOut + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	--	      IF (@checkName<>'')
	--	          SET @strInOut = @strInOut + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
	SET @strInOut = 
	         'INSERT INTO #InoutStockTable
				SELECT
				BillnumberID,																														
				BillDate,																														
				BillType,
				ID,																															
				PtypeID,																															
				KtypeID,
				Qty,
				price,
				Total,	  
				CostTotal,
				taxprice,  
				TaxTotal,
				tax,
				costprice,
				sharefee,
				cargoid,
				nprice,
				ntotal,
				nsaleprice,
				nsaletotal,
				ntaxprice,
				ntaxtotal,
				fullname,
				usercode,
				nqty,
				munitid,
				numname,
				rate,
				T.nbrcqty  AS nbrcqty,--换算率变更前销售单位数量
				baseunitfullname,
				assistantfullname,
				goodsnumber,
				bfullname,
				SaleTotal,
				SalePrice,
				comment,
				CustomdetailID,
				zy,
				discount
				FROM 
				(
					SELECT  
					b.BillnumberID,																														
					a.BillDate,																														
					a.BillType,		
					A.ID,																													
					a.PtypeID,																															
					a.KtypeID,
					a.Qty,
					a.price,
					a.Total,	  
					a.CostTotal,
					a.taxprice,  
					a.TaxTotal,
					a.tax,
					a.costprice,
					a.sharefee,
					a.cargoid,
					a.nprice,
					a.ntotal,
					a.nsaleprice,
					a.nsaletotal,
					a.ntaxprice,
					a.ntaxtotal,
					v.fullname,
					bb.usercode,
					a.nqty,
					a.munitid,
					pu.fullname AS numname,
					pe.rate AS rate,
					CAST(-a.qty/a.MUnitRate AS  NUMERIC(24, 10) )  AS nbrcqty,--换算率变更前销售单位数量
					fg.baseunitfullname AS baseunitfullname,
					fg.assistantfullname AS assistantfullname,
					a.goodsnumber,
					BB.Fullname as bfullname,
					SaleTotal,
					SalePrice,
					a.comment,
					a.id as CustomdetailID,
					b.comment as zy,
					a.discount
					FROM InoutStockTable a 
					INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID AND a.BillType = b.BillType 
					LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = a.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
					left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
					INNER JOIN #PType p ON a.PTypeID=p.typeid
					INNER JOIN #dealBType bb ON bb.typeid = b.dealbtypeid'
					
					IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
					  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
					SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
					IF (@checkCode<>'')
					  SET @strInOut = @strInOut + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
					IF (@checkName<>'')
					  SET @strInOut = @strInOut + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
		      
					SET @strInOut += '
					AND A.BillType NOT IN(402,403,405) 
					
					UNION ALL
					--发出商品出库单
					SELECT
					b.BillnumberID,																														
					B.BillDate,																														
					B.BillType,		
					A.ID,																													
					a.PtypeID,																															
					a.KtypeID,
					CASE T.RedWord
						WHEN 2 THEN a.Qty - a.InvoiceQty
						ELSE -(a.Qty - a.InvoiceQty) 
					END AS Qty,
					a.DiscountPrice AS Price,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
					END AS Total,
					CASE T.RedWord
						WHEN 2 THEN a.CostTotal - a.InvoiceCostTotal
						ELSE -(a.CostTotal - a.InvoiceCostTotal)
					END AS CostTotal,
					a.taxprice,  
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
					END AS TaxTotal,
					a.tax,
					a.costprice,
					a.sharefee,
					a.cargoid,
					a.NDiscountPrice AS nprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice)  END
					END AS ntotal,
					a.nsaleprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.nsaletotal ELSE (a.Qty - a.InvoiceQty) * a.NSalePrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.nsaletotal ELSE -((a.Qty - a.InvoiceQty) * a.NSalePrice) END
					END AS nsaletotal,
					a.ntaxprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
					END AS ntaxtotal,
					v.fullname,
					bb.usercode,
					CASE T.RedWord
						WHEN 2 THEN a.NQty - a.InvoiceNQty
						ELSE -(a.NQty - a.InvoiceNQty)
					END AS nqty,
					a.munitid,
					pu.fullname AS numname,
					pe.rate AS rate,
					a.Mqty-(a.InvoiceQty*a.MunitRate)  AS nbrcqty,--换算率变更前销售单位数量
					fg.baseunitfullname AS baseunitfullname,
					fg.assistantfullname AS assistantfullname,
					a.goodsnumber,
					BB.Fullname as bfullname,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.SaleTotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.SaleTotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
					END AS SaleTotal,
					A.SalePrice,
					a.comment,
					a.id as CustomdetailID,
					t.Comment AS zy,
					a.discount
					FROM SendBill AS A
					INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
					INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
					LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = a.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
					left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
					INNER JOIN #PType p ON a.PTypeID=p.typeid
					INNER JOIN #dealBType bb ON bb.typeid = b.dealbtypeid
					'
					IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
					  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
					SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
					IF (@checkCode<>'')
					  SET @strInOut = @strInOut + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
					IF (@checkName<>'')
					  SET @strInOut = @strInOut + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
					SET @strInOut += ' 
					AND T.ifYearBill = 0
					
					UNION ALL
					--发出商品退货单
					SELECT
					b.BillnumberID,																														
					B.BillDate,																														
					B.BillType,			
					A.ID,																															
					a.PtypeID,																															
					a.KtypeID,
					CASE T.RedWord
						WHEN 2 THEN -(a.Qty - a.InvoiceQty)
						ELSE a.Qty - a.InvoiceQty
					END AS Qty,
					a.DiscountPrice AS Price,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
					END AS Total,
					CASE T.RedWord
						WHEN 2 THEN -(a.CostTotal - a.InvoiceCostTotal)
						ELSE a.CostTotal - a.InvoiceCostTotal
					END AS CostTotal,
					a.taxprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
					END AS TaxTotal,
					a.tax,
					a.costprice,
					a.sharefee,
					a.cargoid,
					a.NDiscountPrice AS nprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
					END AS ntotal,
					a.nsaleprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.nsaletotal ELSE -((a.NQty - a.InvoiceNQty) * a.NSalePrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.nsaletotal ELSE (a.NQty - a.InvoiceNQty) * a.NSalePrice END
					END AS nsaletotal,
					a.ntaxprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
					END AS ntaxtotal,
					v.fullname,
					bb.usercode,
					CASE T.RedWord
						WHEN 2 THEN -(a.NQty - a.InvoiceNQty)
						ELSE a.NQty - a.InvoiceNQty
					END AS nqty,
					a.munitid,
					pu.fullname AS numname,
					pe.rate AS rate,
					a.Mqty-(a.InvoiceQty*a.MunitRate)   AS nbrcqty,--换算率变更前销售单位数量
					fg.baseunitfullname AS baseunitfullname,
					fg.assistantfullname AS assistantfullname,
					a.goodsnumber,
					BB.Fullname as bfullname,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.SaleTotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.SaleTotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
					END AS SaleTotal,
					A.SalePrice,
					a.comment,
					a.id as CustomdetailID   ,
					t.Comment AS zy,
					a.discount
					FROM SendBackBill AS A
					INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
					INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
					LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = a.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
					left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
					INNER JOIN #PType p ON a.PTypeID=p.typeid
					INNER JOIN #dealBType bb ON bb.typeid = b.dealbtypeid
					' 
					IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
					  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
					SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
					IF (@checkCode<>'')
					  SET @strInOut = @strInOut + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
					IF (@checkName<>'')
					  SET @strInOut = @strInOut + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
					SET @strInOut += ' 
					AND T.ifYearBill = 0
					
					UNION ALL
					--销售发货开票
					SELECT
					b.BillnumberID,																														
					B.BillDate,																														
					B.BillType,					
					A.ID,																													
					a.PtypeID,																															
					a.KtypeID,
					CASE T.RedWord
						WHEN 2 THEN a.Qty
						ELSE -a.Qty 
					END AS Qty,
					a.Price,
					CASE T.RedWord
						WHEN 2 THEN a.total
						ELSE -a.total 
					END AS total,
					CASE T.RedWord
						WHEN 2 THEN a.InvoiceCostTotal
						ELSE -a.InvoiceCostTotal
					END AS CostTotal,
					a.taxprice,  
					CASE T.RedWord
						WHEN 2 THEN a.TaxTotal
						ELSE -a.TaxTotal
					END AS TaxTotal,
					a.tax,
					a.InvoiceCostPrice AS costprice,
					0 AS sharefee,
					a.cargoid,
					a.NPrice AS nprice,
					CASE T.RedWord
						WHEN 2 THEN a.Ntotal
						ELSE -a.Ntotal
					END AS Ntotal,
					a.nsaleprice,
					CASE T.RedWord
						WHEN 2 THEN a.nsaletotal
						ELSE -a.nsaletotal
					END AS nsaletotal,
					a.ntaxprice,
					CASE T.RedWord
						WHEN 2 THEN a.ntaxtotal
						ELSE -a.ntaxtotal
					END AS ntaxtotal,
					v.fullname,
					bb.usercode,
					CASE T.RedWord
						WHEN 2 THEN a.NQty
						ELSE -a.NQty
					END AS nqty,
					a.munitid,
					pu.fullname AS numname,
					pe.rate AS rate,
					a.MQty  AS nbrcqty,--换算率变更前销售单位数量
					fg.baseunitfullname AS baseunitfullname,
					fg.assistantfullname AS assistantfullname,
					a.goodsnumber,
					BB.Fullname as bfullname,
					CASE T.RedWord
						WHEN 2 THEN a.SaleTotal
						ELSE -a.SaleTotal
					END AS SaleTotal,
					A.SalePrice,
					a.comment,
					a.id as CustomdetailID,
					t.Comment AS zy,
					a.discount
					FROM ReceiptBill AS A
					INNER JOIN ReceiptBillIndex AS T ON(A.BillnumberID = T.BillnumberID AND A.BillType = T.BillType)
					INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
					LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = a.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
					left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
					INNER JOIN #PType p ON a.PTypeID=p.typeid
					INNER JOIN #dealBType bb ON bb.typeid = b.dealbtypeid
					' 
					IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
					  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
					SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
					IF (@checkCode<>'')
					  SET @strInOut = @strInOut + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
					IF (@checkName<>'')
					  SET @strInOut = @strInOut + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
					SET @strInOut += ' 
					AND T.ifYearBill = 0
					'
										 
		SET @strInOut += '
				) AS T
		'    
--********************************************************--
EXEC(@strInOut)   

declare  @insertTemp varchar(max)  
if @chvPF='1'
  begin
   set @insertTemp = 'INSERT INTO #inoutstocktable(usercode,bfullname)
                        SELECT 
                        dd.usercode,
                        dd.fullname
						FROM 	billindex b 
						INNER JOIN PriceProtectBill a ON b.billnumberid = a.billnumberid
						INNER JOIN #Btype bb	On bb.typeid =b.btypeid
						INNER JOIN #DealBtype dd ON b.dealbtypeid = dd.typeid '
		                IF  @chvETypeID<>'' OR @METypeID=-99999 
			                SET @insertTemp=@insertTemp+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)
	    
		                IF  @chvDTypeID<>'' OR @MDTypeID=-99999 
			                SET @insertTemp=@insertTemp+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF  @chvStypeID<>''    OR @MStypeid=-99999 
			                SET @insertTemp=@insertTemp+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

		                    SET @insertTemp=@insertTemp+'	inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 AND '+@RED_WHERE+@SQL_WHERE
									
		                    SET @insertTemp = @insertTemp +' AND b.Billtype =''149'''
		
		                IF (@checkCode<>'')
		                    SET @insertTemp = @insertTemp + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		                IF (@checkName<>'')
		                    SET @insertTemp = @insertTemp + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		                IF(ISNULL(@chvComment,'')!='')
			                SET @insertTemp = @insertTemp +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		                IF(ISNULL(@chvZY,'')!='')
			                SET @insertTemp = @insertTemp +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
		                SET @insertTemp = @insertTemp +' AND b.ifYearBill=''0'' AND b.isini=0'
EXEC(@insertTemp)	
 SET	@insertTemp = 'INSERT INTO #inoutstocktable(usercode,bfullname)  SELECT 	
                        dd.usercode,
                        dd.fullname
					FROM billindex b 
					INNER JOIN Advantage a ON b.billnumberid =a.billnumberid
					INNER JOIN #Btype bb   ON bb.typeid =b.btypeid 
					INNER JOIN #DealBtype dd ON b.dealbtypeid = dd.typeid'
					IF @chvETypeID<>'' OR @METypeID=-99999 
						SET @insertTemp=@insertTemp+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)
	                
					IF @chvDTypeID<>'' OR @MDTypeID=-99999 
						SET @insertTemp=@insertTemp+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	               
					IF @chvStypeID<>'' OR @MStypeid=-99999 
						SET @insertTemp=@insertTemp+' inner Join #Stype ss	On ss.typeid =b.stypeid '+CHAR(13)

					SET @insertTemp=@insertTemp+'	 inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 and  '+@RED_WHERE+@SQL_WHERE
							
			        SET @insertTemp = @insertTemp +' AND b.Billtype =''148'''
			
	                IF (@checkCode<>'')
		                SET @insertTemp = @insertTemp + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		            IF (@checkName<>'')
		                SET @insertTemp = @insertTemp + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		            IF(ISNULL(@chvComment,'')!='')
			            SET @insertTemp = @insertTemp +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		            IF(ISNULL(@chvZY,'')!='')
			            SET @insertTemp = @insertTemp +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
	                SET @insertTemp = @insertTemp +' AND b.ifYearBill=''0'' AND b.isini=0'
	       exec(@insertTemp) 
	       end                
--------创建临时表-End--------

--------价保、返利-Start--------
print @insertTemp
	
DECLARE @PRICE_SQL varchar(MAX)  --价保
SET     @PRICE_SQL ='
						SELECT 	b.billcode,	
						        b.stypeid,
								b.billtype,
								b.billdate,
								b.billnumberid,	
								b.btypeid,
								b.dealbtypeid,
								b.etypeid,
								b.dtypeid,
								b.ktypeid,
								null,
								A.ID,
								p.typeid  as ptypeid,
								null,
								 null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								v.fullname as itemname,
								b.checke,
								cc.fullname,
								b.rate,
								null,
								null,
								null,
								null,
								null,
								null,
								0 AS antantotal,
							    0 AS aqty,
								CASE WHEN b.redword = 2  THEN (-a.total)
								ELSE a.total
								END AS PriceTotal,
								CASE WHEN b.redword = 2 THEN (-a.qty)
								ELSE a.qty
								END AS pqty,
								null,
								dd.usercode,
								2 AS Flag,
								null,
								null,
								a.goodsnumber,
								''价保执行单'' AS billtypename,
								B.redword,
								null,null,null,null,
								null,null,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
							  NULL,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null
						FROM 	billindex b 
						INNER JOIN PriceProtectBill a ON b.billnumberid = a.billnumberid
						left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
						INNER JOIN #Btype bb	On bb.typeid =b.btypeid
						INNER JOIN #DealBtype dd ON b.dealbtypeid = dd.typeid 
						 INNER JOIN AC_Currency cc  ON b.cid = cc.cid '
		                IF  @chvETypeID<>'' OR @METypeID=-99999 
			                SET @PRICE_SQL=@PRICE_SQL+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)
	    
		                IF  @chvDTypeID<>'' OR @MDTypeID=-99999 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF  @chvStypeID<>''    OR @MStypeid=-99999 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

		                    SET @PRICE_SQL=@PRICE_SQL+'	inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 AND '+@RED_WHERE+@SQL_WHERE
									
		                    SET @PRICE_SQL = @PRICE_SQL +' AND b.Billtype =''149'''
		
		                IF (@checkCode<>'')
		                    SET @PRICE_SQL = @PRICE_SQL + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		                IF (@checkName<>'')
		                    SET @PRICE_SQL = @PRICE_SQL + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		                IF(ISNULL(@chvComment,'')!='')
			                SET @PRICE_SQL = @PRICE_SQL +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		                IF(ISNULL(@chvZY,'')!='')
			                SET @PRICE_SQL = @PRICE_SQL +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
		                SET @PRICE_SQL = @PRICE_SQL +' AND b.ifYearBill=''0'' AND b.isini=0'
		
---------------------------------------------------------------------------------------------------------------------	
		
DECLARE @ADTAN_SQL varchar(MAX)  --返利
SET @ADTAN_SQL ='
					 SELECT 	b.billcode,	
						        b.stypeid,
								b.billtype,
								b.billdate,
								b.billnumberid,	
								b.btypeid,
								b.DealBTypeID,
								b.etypeid,
								b.dtypeid,
								b.ktypeid,
								null,
								A.ID,
								p.typeid  as ptypeid,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								v.fullname as itemname,
								b.checke,
								cc.fullname,
								b.rate,
								null,
								null,
								null,
								null,
								null,
								null,
							    CASE WHEN b.redword = 2 THEN -a.total
								ELSE a.total
								END AS antantotal,
								CASE WHEN b.redword = 2 THEN (-a.qty)
								ELSE a.qty
								END AS aqty,
								0 AS PriceTotal,
								0 AS pqty,
								null,
								dd.usercode,
								2 AS Flag,
								null,
								null,
								a.goodsnumber,
								''返利执行单'' as billtypename,
								B.redword,
								null,null,null,null,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
							    null,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
					FROM billindex b 
					INNER JOIN Advantage a ON b.billnumberid =a.billnumberid
					left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					INNER JOIN #Btype bb   ON bb.typeid =b.btypeid 
					INNER JOIN #DealBtype dd ON b.dealbtypeid = dd.typeid
						 INNER JOIN AC_Currency cc  ON b.cid = cc.cid  '
					IF @chvETypeID<>'' OR @METypeID=-99999 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)
	                
					IF @chvDTypeID<>'' OR @MDTypeID=-99999 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	               
					IF @chvStypeID<>'' OR @MStypeid=-99999 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Stype ss	On ss.typeid =b.stypeid '+CHAR(13)

					SET @ADTAN_SQL=@ADTAN_SQL+'	 inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 and  '+@RED_WHERE+@SQL_WHERE
							
			        SET @ADTAN_SQL = @ADTAN_SQL +' AND b.Billtype =''148'''
			
	                IF (@checkCode<>'')
		                SET @ADTAN_SQL = @ADTAN_SQL + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		            IF (@checkName<>'')
		                SET @ADTAN_SQL = @ADTAN_SQL + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		            IF(ISNULL(@chvComment,'')!='')
			            SET @ADTAN_SQL = @ADTAN_SQL +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		            IF(ISNULL(@chvZY,'')!='')
			            SET @ADTAN_SQL = @ADTAN_SQL +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
	                SET @ADTAN_SQL = @ADTAN_SQL +' AND b.ifYearBill=''0'' AND b.isini=0'
--------价保、返利-End--------


----- 拼接头-商品编号、商品名Start-----
DECLARE  @head  VARCHAR(MAX)
SET @head= 
          'SELECT ''【''+b.usercode+''】''+isnull(b.bfullname,''''),
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
				  1 ID,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  b.usercode,
                  1 AS Flag,
                  NULL,
	     		  NULL,
	     		  NULL,
	     		  NULL,
	     		  NULL,
	     		  NULL,null,null,null,
	     		  null as Explain ,
	     		  null,
	     		NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                null,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
          FROM #InoutStockTable b GROUP BY b.usercode,b.bfullname' 
          
----- 拼接头-商品编号、商品名End-----
		   
			DECLARE	@Digit int=10
			SELECT @Digit = DecimalDigit FROM DigitConfiguration WHERE ItemName='qty'

			CREATE TABLE #tmpcalc
			(
				ptypeid VARCHAR(50),
				r1		NUMERIC(24,10),
				sf1		VARCHAR(50),
				r2		NUMERIC(24,10),
				sf2		VARCHAR(50),
				r3		NUMERIC(24,10),
				sf3		VARCHAR(50)
			)

			INSERT INTO #tmpcalc
			SELECT	pae.ptypeid,
					ISNULL(pae.SaleUnitRate1,0) as r1,								
					ISNULL(pu1.fullname,'''') as sf1,
					ISNULL(pae.SaleUnitRate2,0) as r2,
					ISNULL(pu2.fullname,'''') as sf2,
					ISNULL(pae.SaleUnitRate3,0) as r3,
					ISNULL(pu3.fullname,'''') as sf3
			FROM	PType_AuxiliaryUnits_Ext pae
			LEFT JOIN PType_Units pu1 ON pu1.UnitsId = pae.SaleUnitID1
			LEFT JOIN PType_Units pu2 ON pu2.UnitsId = pae.SaleUnitID2
			LEFT JOIN PType_Units pu3 ON pu3.UnitsId = pae.SaleUnitID3


-----业务SQL语句-Start-----
DECLARE @strSQL VARCHAR(MAX)
SET @strSQL = 
            '
			SELECT   b.billcode,
             		  b.stypeid,																																																									
	                  a.billtype,
	                  a.billdate,
                      a.billnumberid,
	                  b.btypeid,
	                  b.dealbtypeid,
	                  b.etypeid,
	                  b.dtypeid,
	                  a.ktypeid,																																																											
	                  a.cargoid,
					  A.ID,
	                  a.ptypeid,
					  MPs.usercode pmulusercode,
	                  -(a.Qty)AS qty,
					  isnull(a.Price,0) AS price,
					  isnull(a.taxPrice,0) AS taxprice,
                      -(a.Total) AS total,
					  -(a.TaxTotal) AS taxtotal, 
					  -(taxtotal)-(-total) AS taxge,
					  isnull((b.Totalinmoney+isnull(b.completeTotal,0)),0) AS totalinmoney,
					  CASE ABS(a.Qty) 
						  WHEN 0 THEN 0
						  ELSE a.costprice
					  END costprice,
					  --a.costprice,
					  -(a.CostTotal) AS costtotal,
					  -(ISNULL(a.sharefee,0)) AS sharefee,
					  -(ISNULL(b.preferencemoney,0)) AS preferencemoney,
					  a.nprice,
					  -(a.ntotal) AS ntotal,
					  a.nsaleprice,
					  -(a.nsaletotal) AS nsaletotal,
					  a.ntaxprice,
					  -(a.ntaxtotal) AS ntaxtotal,
					  a.fullname as itemname,
					  b.checke,
					  b.cname,
					  b.rate,
					  -(a.nqty) AS nqty,
					  a.numname AS munit,
					  -(a.qty/a.rate) AS mqty,
					    CASE a.nbrcqty  WHEN  -(a.qty/a.rate) THEN NULL ELSE a.nbrcqty  END AS nbrcqty,
					  CASE '+CAST( @config AS VARCHAR)+' WHEN 1  THEN -(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0)) ELSE  -(a.Total) - (-a.CostTotal) END AS maoli,
					    CASE a.Total WHEN 0 THEN 0 
					  ELSE 
					  (CASE '+CAST( @config AS VARCHAR)+' 
					  WHEN 1  THEN cast( (-(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0))) as 
NUMERIC(24, 10))/cast( -(a.total) as 
NUMERIC(24, 10))
                      ELSE cast( (-(a.Total) - (-a.CostTotal))as 
NUMERIC(24, 10))/cast(-(a.total)  as NUMERIC(24, 10))
                      END)*100
					  END AS maolilu,
					  
					  CASE WHEN b.billtype IN (148,150) THEN -(a.total)
                      ELSE 0
                      END AS antantotal,
					  CASE WHEN b.billtype IN (148,150) THEN -(a.qty)
					  ELSE 0
					  END AS aqty,
					  CASE WHEN b.billtype IN (149,151) THEN -(a.total)
					  ELSE 0
					  END AS PriceTotal,
					  CASE WHEN b.billtype IN (149,151) THEN -(a.qty)
					  ELSE 0
					  END AS pqty,
					  b.posttime,
					  a.usercode,
					  2 AS Flag,
					  a.baseunitfullname,
					  a.assistantfullname,
					  a.goodsnumber,
					  CASE a.billtype
						WHEN 11		THEN ''销售出库单''
						WHEN 45		THEN ''销售退货单''
						WHEN 215	THEN ''零售退货单''
						WHEN 305	THEN ''零售单''
						WHEN 141	THEN ''委托结算单''
						WHEN 34 	THEN ''采购入库单''
						WHEN 6 		THEN ''采购退货单''
						WHEN 145	THEN ''受托代销结算单''
						WHEN 149	THEN ''价保执行单''
						WHEN 151	THEN ''获得价保执行单''
						WHEN 148	THEN ''返利执行单''
						WHEN 150	THEN ''获利执行单''
						WHEN 160	THEN ''销售换货单''
						WHEN 161	THEN ''采购换货单''
						WHEN 402	THEN ''发出商品出库单''
						WHEN 403	THEN ''发出商品退货单''
						WHEN 405	THEN ''销售发货开票''
						WHEN 12		THEN ''组合品销售出库单''
						WHEN 46		THEN ''组合品销售退货单''
					  END AS billtypename,
					 b.redword AS RedWord,
					 (-A.Ntaxtotal)-(-A.Ntotal) AS ntaxge,
					 -(a.saletotal)as saletotal,
					 a.saleprice,
					 a.comment,
					 b.Explain,
					 (a.nsaleprice * pe.rate) as MunitPrice,  /*销售单位单价*/
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	,
					SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40,
					--customassist=dbo.F_GetCustomAssist(a.Ptypeid,-(a.Qty)),
					customassist=dbo.F_GetCustomAssistDirect(ISNULL(a.qty,0),pae.r1,pae.sf1,pae.r2,pae.sf2,pae.r3,pae.sf3,'+CAST(@Digit AS VARCHAR)+'),
				a.zy,
				a.discount
			FROM #InoutStockTable a
			INNER JOIN #BillIndex b ON a.BillNumberId = b.BillNumberID	  and a.billtype=b.billtype			  
			LEFT JOIN dbo.PType_Units_Ext pe ON a.MUNITID=pe.UnitsId AND a.PtypeId=pe.PtypeID
			LEFT JOIN PUserCode MPs ON MPs.PTypeID=A.PtypeId AND MPs.btypeid=B.dealbtypeid
			left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
			left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid
			LEFT JOIN #tmpcalc pae ON pae.ptypeid = a.ptypeid
			'

			  ---筛选制单人
			  IF @checkCode <> '' OR @checkName <> ''
              IF NOT(@checkCode='10000' OR @checkName = '代销仓库')
                 --加‘10000’是查仓库的时候要包含代销仓库
				 SET @strSQL = @strSQL +' INNER JOIN (SELECT TypeID FROM BType UNION SELECT ''10000'') AS T  ON b.BTypeID = T.TypeID'
-----业务SQL语句-End-----

            IF  @chvPF ='1' 
			    SELECT @strSQL = @strSQL +' UNION ALL ' +@PRICE_SQL +' UNION ALL ' + @ADTAN_SQL 
			    --PRINT @ADTAN_SQL
			--print @PRICE_SQL			
-----拼接尾-商品相关金额小计Start-----
DECLARE @tail VARCHAR(MAX);
SELECT @tail = 
       'WITH strSql AS
        ('+@strSQL+')
        SELECT * FROM strSql
        UNION ALL
        SELECT  NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
				1 ID,
                NULL,
                NULL,
                SUM(strSql.Qty),
                NULL,
                NULL,
                SUM(strSql.Total),
                SUM(strSql.Taxtotal),
                SUM(strSql.Taxge),
                NULL,
                NULL,
                SUM(strSql.CostTotal),
                SUM(strSql.sharefee),
                NULL,
                NULL,
                SUM(strSql.ntotal),
                NULL,
                SUM(strsql.nsaletotal),
                NULL,
                SUM(strSql.ntaxtotal),
                NULL,
                NULL,
                NULL,
                NULL,
                SUM(strSql.nqty),
                NULL,
                SUM(strSql.mqty),
                SUM(strSql.nbrcqty),
                SUM(strSql.maoli),
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                strSql.usercode,
                3 AS Flag,
                NULL,
                NULL,
                NULL,
              ''小计'',
                NULL,
                SUM(strSql.ntaxge),SUM(strsql.saletotal),NULL,NULL,
                null as Explain,
                NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
         FROM strSql
         GROUP BY strSql.usercode
         UNION ALL ' 
         +@head   
-----拼接尾-商品相关金额小计End-----
DECLARE @SQL_ORDER VARCHAR(MAX) 
SELECT  @SQL_ORDER = ' ORDER BY usercode,Flag'
+ CASE @sortfield
			WHEN 'ByDate_a'		THEN ', BillDate,Billcode,ID'	-- 按日期排序
			WHEN 'ByBillNo_a'	THEN ', BillCode'		    -- 按单据编号排序
			WHEN 'ByBillType_a'	THEN ', BillType,BillDate,ID'	-- 按单据类型排序
			WHEN 'ByBillID_a'	THEN ', posttime'			-- 按单据真实过帐顺序排序
			WHEN 'ByDate_d'		THEN ', Billdate DESC,Billcode DESC,ID'
			WHEN 'ByBillNo_d'	THEN ', BillCode DESC'
			WHEN 'ByBillType_d'	THEN ', BillType DESC,BillDate,ID'
			WHEN 'ByBillID_d'	THEN ', posttime DESC,ID '
			ELSE ',posttime DESC,ID '
			END
print @SQL_ORDER
DECLARE @SQL VARCHAR(MAX)
SET @SQL =@tail + @SQL_ORDER
--print @SQL
EXEC(@SQL)
DROP TABLE #Billtype,#Ptype,#Btype,#Etype,#Ktype,#Dtype,#Stype,#BillIndex,#DealBtype,#InoutStockTable,#tmpcalc
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_BTypeSaleDist]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_BTypeSaleDist]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-06-25
function:单位销售分布表树形表
*/
CREATE PROCEDURE Web_BTypeSaleDist
(
	@OperatorId		VARCHAR(50),		--操作员Id
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--结束日期
	@StypeId        VARCHAR(MAX),		--分支机构Id
	@PtypeCategoryId VARCHAR(MAX),		--商品类别ID
	@PTypeId		VARCHAR(MAX),		--商品Id
	@BTypeId		VARCHAR(MAX),		--结算单位Id
	@DealBTypeId    VARCHAR(MAX),		--往来单位ID
	@nType			VARCHAR(10),		--金额的查询方式
	@BillType		VARCHAR(100),		--单据类型
	@ShowZero		VARCHAR(5),			--0.不显示红冲单据   1.显示红冲单据
	@UnitConvert	INT,				--单位
	@Sort		    NVARCHAR(200),		--排序
	@Ck				INT,				--1：升序 0降序
	
	@BCount			INT=10,				--基本信息的默认个数
	@BPageNo		INT=0,				--基本信息的页数
	@IsPrint		INT=0				--是否是打印算法
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------

DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================

--根据单位获取相关值
DECLARE
	@TempColumn			VARCHAR(50),
	@TempQty			VARCHAR(1000)='',
	@TempTable			VARCHAR(1000)=''
	
--销售单位		
IF @UnitConvert=0
	BEGIN
		SET @TempColumn='SaleUnitId'
		SET @TempTable='
		LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.SaleUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
		
	END
--采购单位
ELSE IF @UnitConvert=1
	BEGIN
		SET @TempColumn='BuyUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.BuyUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--存货单位
ELSE IF @UnitConvert=2
	BEGIN
		SET @TempColumn='StockUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.StockUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--基本单位
ELSE IF @UnitConvert=3
	BEGIN
		SET @TempColumn='baseUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.baseUnitId = R.UnitsId'
		SET @TempQty='B.Qty'
	END

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	BEGIN
		INSERT INTO #Stype(typeid) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
	END

--商品
IF(ISNULL(@PTypeId,'')='')
	SET @PTypeId='00000'

--父级
CREATE TABLE #ParidPtype(
	RowId				INT,
	TypeID				VARCHAR(50),
	SonNum				INT,
	UserCode			VARCHAR(400),
	AssistUnitFullName	VARCHAR(400),
	UnitFullName		VARCHAR(400),
	Rate				NUMERIC(24,10)
) 
CREATE CLUSTERED INDEX #ParidPtype_P_K ON #ParidPtype(TypeId)

DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,@PTypeId,@PtypeCategoryId)

SET @SQL='
INSERT INTO #ParidPtype(RowId,TypeID,SonNum,UserCode,AssistUnitFullName,UnitFullName,Rate)
SELECT
	ROW_NUMBER()OVER(ORDER BY P.UserCode) RowId,
	P.typeId,
	P.sonnum,
	P.UserCode,
	E.FullName AssistUnitFullName,
	PU.FullName UnitFullName,
	R.Rate
 '+@LinkStr+'
 LEFT JOIN PType_Units E ON P.AssistantUnitId=E.UnitsId
 '+@TempTable+'
 LEFT JOIN PType_Units PU ON PU.UnitsId=P.'+@TempColumn+'
 WHERE
	P.ParId='''+@PTypeId+'''
	AND P.iscombinationproduct=0'

EXEC(@SQL)

--实际查询商品
CREATE TABLE #Ptype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)
INSERT INTO #Ptype(TypeID)
SELECT
	P.typeId
FROM ptype P
INNER JOIN #ParidPtype F ON P.typeId LIKE F.TypeID+'%' AND P.sonnum=0 AND P.iscombinationproduct=0 

--部门
CREATE TABLE #Dtype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
IF (@MDtypeid='-99999')
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetManDetailDType(@OperatorId)
	END
	
--职员
CREATE TABLE #Etype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF (@MEtypeid='-99999')
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetManDetailEType(@OperatorId)
	END

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeId)
IF (@MKtypeid='-99999')
	BEGIN
		INSERT INTO #Ktype(TypeID)
		SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
		UNION ALL
		SELECT '10000' TypeId
	END

--往来单位
CREATE TABLE #DealBtype (RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(400),FullName VARCHAR(400)) CREATE CLUSTERED INDEX #DealBtype_P_K ON #DealBtype(TypeId)
IF(ISNULL(@DealBTypeId,'')='' AND NOT(@MBtypeid2='-99999' OR @MBTypeID='-99999'))
	BEGIN
		INSERT INTO #DealBtype(RowId,TypeID,UserCode,FullName)
		SELECT 
			ROW_NUMBER()OVER(ORDER BY UserCode) RowId,
			typeId,
			UserCode,
			FullName
		FROM btype WHERE sonnum=0 AND typeId NOT IN('00001','00002')
		ORDER BY UserCode
	END
ELSE 
	BEGIN
		INSERT INTO #DealBtype(RowId,TypeID,UserCode,FullName)
		SELECT 
			ROW_NUMBER()OVER(ORDER BY D.usercode) RowId,
			F.TypeId,
			D.usercode,
			D.FullName
		FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId) F
		INNER JOIN btype D ON F.TypeId=D.typeid
		ORDER BY usercode
	END

--当前页部门
CREATE TABLE #PageDealBtype(TypeID VARCHAR(50),UserCode VARCHAR(400),FullName VARCHAR(400))
INSERT INTO #PageDealBtype(TypeID,UserCode,FullName)
SELECT 
	typeid,
	UserCode,
	FullName 
FROM #DealBtype
WHERE RowId BETWEEN (@bPageNo-1)*@bCount AND @bPageNo*@bCount

	
--结算单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(ISNULL(@BTypeId,'')<>'' OR @MBTypeID='-99999')--所有权限
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorId)
	END
--=============================基本信息权限范围获取【END】=======================================

--=============================业务处理【BEGIN】=====================================
SET @SQL=''

--BillIndex
CREATE TABLE #BillIndex
(
	BillNumberId 	NUMERIC(18,0),
	BTypeID			VARCHAR(50),
	DealBTypeID		VARCHAR(50),
	BillType		INT	
) 
CREATE CLUSTERED INDEX #BillIndex_P_K ON #BillIndex(BillNumberId)

SET @SQL='
INSERT INTO #BillIndex
(
	BillNumberId,
	BTypeID,
	DealBTypeID,
	BillType
)
SELECT	
	B.BillNumberId,
	B.BTypeID,
	B.DealBTypeID,
	B.BillType
FROM BillIndex B' +CHAR(13)	

--分支机构
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	SET @SQL+='INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid'+CHAR(13)	
	
--结算单位	
IF ISNULL(@BTypeId,'')<>'' OR @MBtypeid='-99999'
	SET @SQL += 'INNER JOIN #Btype bb ON BB.TypeID = B.BTypeID '

--往来单位
IF ISNULL(@DealBTypeId,'')<>'' OR @MBtypeid='-99999'
	SET @SQL += 'INNER JOIN #DealBtype D1 ON D1.TypeID = B.DealBTypeID '
		
--部门
IF(@MDtypeid='-99999')
	SET @SQL+='INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId'+CHAR(13)

--职员		
IF (@MEtypeid='-99999')
	SET @SQL+='INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid'+CHAR(13)
	
SET @SQL+='
WHERE 
	B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' 
	AND B.BillType IN ('+@BillType+')
	AND B.IfCheck=''t'' 
	AND B.RedWord=0 
	AND B.Draft=0 
	AND B.ifYearBill=0'+CHAR(13)
	
EXEC(@SQL)
SET @SQL=''

--数据明细表
CREATE TABLE #SaleBill
(
	PTypeId		VARCHAR(50),
	BTypeID		VARCHAR(50),
	DealBTypeID	VARCHAR(50),
	Qty			NUMERIC(24,10),
	NQty        NUMERIC(24,10),
	TaxTotal	NUMERIC(24,10) 
)
CREATE CLUSTERED INDEX #SaleBill_P_K ON #SaleBill(PTypeId)

--零售单
IF CHARINDEX('305',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN retailBill B ON I.BillType=305 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,DealBTypeID'+CHAR(13)
END

--零售退货单
IF CHARINDEX('215',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN RetailBackBill B ON I.BillType=215 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,DealBTypeID'+CHAR(13)
	
END

--销售出库单
IF CHARINDEX('11',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN SaleBill B ON I.BillType=11 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,DealBTypeID'+CHAR(13)
END

--销售退货单
IF CHARINDEX('45',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN saleBackBill B ON I.BillType=45 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,DealBTypeID'+CHAR(13)
END

--销售换货单
IF CHARINDEX('160',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		CASE WHEN B.InOrOut = ''o'' THEN SUM('+@tempqty+') ELSE -SUM('+@tempqty+') END Qty,
		CASE WHEN B.InOrOut = ''o'' THEN SUM(B.NQty) ELSE -SUM(B.NQty) END NQty,
		CASE WHEN B.InOrOut = ''o'' THEN CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END
			 ELSE CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END
		END TaxTotal 
	FROM #BillIndex I
	INNER JOIN SaleGoodsExchangeBill B ON I.BillType=160 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='WHERE 
		B.InOrOut=''i'' 
		OR B.InOrOut=''o''  
	GROUP BY B.PTypeId,I.BTypeID,DealBTypeID,B.InOrOut'+CHAR(13)
END

--委托代销结算单
IF CHARINDEX('141',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN CommissionBill B ON I.BillType=141 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,DealBTypeID'+CHAR(13)
END

--组合品销售出库单
IF CHARINDEX('12',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBillDetail B ON I.BillType=12 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,DealBTypeID'+CHAR(13)
END

--组合品销售退货单
IF CHARINDEX('46',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBackBillDetail B ON I.BillType=46 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,DealBTypeID'+CHAR(13)
END

SET @SQL='
INSERT INTO #SaleBill
(
	PTypeId,
	BTypeID,
	DealBTypeID,
	Qty,
	NQty,
	TaxTotal
)
SELECT 
	PtypeId,
	BTypeID,
	DealBTypeID,
	SUM(ISNULL(F.Qty,0)) Qty,
	SUM(ISNULL(F.NQty,0)) NQty,
	SUM(ISNULL(F.TaxTotal,0)) TaxTotal
 FROM 
('+SUBSTRING(@SQL,10,LEN(@SQL))+'
)F
INNER JOIN #DealBtype T ON T.TypeId=F.BTypeID
GROUP BY F.PTypeId,F.BTypeID,F.DealBTypeID
'
EXEC(@SQL)

--生成分布表
SET @SQL = '
SELECT
	P.typeid,
	P.SonNum 父节点,
	p.AssistUnitFullName 浮动单位,
	SUM(ISNULL(B.Qty,0)) 总计数量,
	SUM(ISNULL(B.NQty,0)) 总计浮动数量,
	SUM(ISNULL(B.TaxTotal,0)) 总计金额'

IF @bCount='10'
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+CASE WHEN LEN(FullName)>=128 THEN LEFT(FullName,100) ELSE '('+UserCode+')'+FullName END+'数量]
						,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+CASE WHEN LEN(FullName)>=128 THEN LEFT(FullName,100) ELSE '('+UserCode+')'+FullName END+'浮动数量]
						,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+CASE WHEN LEN(FullName)>=128 THEN LEFT(FullName,100) ELSE '('+UserCode+')'+FullName END+'金额]'  
	FROM #PageDealBtype ORDER BY UserCode  
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+CASE WHEN LEN(FullName)>=128 THEN LEFT(FullName,100) ELSE '('+UserCode+')'+FullName END+'数量]
						,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+CASE WHEN LEN(FullName)>=128 THEN LEFT(FullName,100) ELSE '('+UserCode+')'+FullName END+'浮动数量]
						,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+CASE WHEN LEN(FullName)>=128 THEN LEFT(FullName,100) ELSE '('+UserCode+')'+FullName END+'金额]'  
	FROM #DealBtype ORDER BY UserCode  
END 
SET @SQL+='
FROM #ParidPtype P
LEFT JOIN #SaleBill B ON B.PTypeId LIKE P.TypeID+''%'''  

SET @SQL+='
GROUP BY
	P.RowId,
	P.TypeID,
	P.SonNum,
	p.AssistUnitFullName
ORDER BY'

IF ISNULL(@sort,'')=''
	SET @SQL+='	p.RowId'   
	 
IF ISNULL(@sort,'')='0'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.Qty,0)) desc '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.Qty,0))'  
  END				
IF ISNULL(@sort,'')='1'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.NQty,0)) desc '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.NQty,0))'  
  END
IF	ISNULL(@sort,'')='2'
  BEGIN
	IF @ck!=1
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0)) desc '    
    ELSE
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0))'  
  END
			
--PRINT(@SQL)				
EXEC(@SQL)
--=============================业务处理【END】=======================================



--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#Dtype,#Etype,#Ktype,#Ptype,#Stype,#BillIndex,#PageDealBtype,#SaleBill,#ParidPtype,#DealBtype

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_BTypeSaleDistLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_BTypeSaleDistLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-06-25
function:单位销售分布线性表
*/
CREATE PROCEDURE Web_BTypeSaleDistLine
(
	@OperatorId		VARCHAR(50),		--操作员Id
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--结束日期
	@StypeId        VARCHAR(MAX),		--分支机构Id
	@PtypeCategoryId VARCHAR(MAX),		--商品类别ID
	@PTypeId		VARCHAR(MAX),		--商品Id
	@BTypeId		VARCHAR(MAX),		--结算单位Id
	@DealBTypeId    VARCHAR(MAX),		--往来单位ID
	@nType			VARCHAR(10),		--金额的查询方式
	@BillType		VARCHAR(100),		--单据类型
	@ShowZero		VARCHAR(5),			--0.不显示红冲单据   1.显示红冲单据
	@CheckZero		BIT,				--显示销售为0的数据 1：显示
	@UnitConvert	INT,				--单位
	@Sort		    NVARCHAR(200),		--排序
	@Ck				INT,				--1：升序 0降序
	
	@BCount			INT=10,				--基本信息的默认个数
	@BPageNo		INT=0				--基本信息的页数
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN --------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE 
	@Re INT,
	@MAtypeid VARCHAR(50), 
	@MBtypeid VARCHAR(50), 
	@MBtypeid2 VARCHAR(50), 
	@MEtypeid VARCHAR(50),
	@MKtypeid VARCHAR(50), 
	@MPtypeid VARCHAR(50), 
	@MExpense VARCHAR(50), 
	@MIncome VARCHAR(50),
	@MCapital VARCHAR(50),
	@MDtypeid VARCHAR(50),
	@MStypeid VARCHAR(50)
	
EXEC @Re=GP_CheckOperatorRight23_Rep 
		@OperatorID,
		@MAtypeid OUTPUT,
		@MBtypeid OUTPUT,
		@MBtypeid2 OUTPUT,
		@MEtypeid OUTPUT,
		@MKtypeid OUTPUT,
		@MPtypeid OUTPUT,
		@MExpense OUTPUT,
		@MIncome OUTPUT,
		@MCapital OUTPUT,
		@MDtypeid OUTPUT,
		@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------
END;
	
DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================

--根据单位获取相关值
DECLARE
	@TempColumn			VARCHAR(50),
	@TempQty			VARCHAR(1000)='',
	@TempTable			VARCHAR(1000)=''
	
--销售单位		
IF @UnitConvert=0
	BEGIN
		SET @TempColumn='SaleUnitId'
		SET @TempTable='
		LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.SaleUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
		
	END
--采购单位
ELSE IF @UnitConvert=1
	BEGIN
		SET @TempColumn='BuyUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.BuyUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--存货单位
ELSE IF @UnitConvert=2
	BEGIN
		SET @TempColumn='StockUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.StockUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--基本单位
ELSE IF @UnitConvert=3
	BEGIN
		SET @TempColumn='baseUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.baseUnitId = R.UnitsId'
		SET @TempQty='B.Qty'
	END

--商品
IF(ISNULL(@PTypeId,'')='')
	SET @PTypeId='00000'

--实际查询商品
CREATE TABLE #Ptype(
	RowId				INT,
	TypeID				VARCHAR(50),
	SonNum				INT,
	UserCode			VARCHAR(200),
	AssistUnitFullName	VARCHAR(200),
	UnitFullName		VARCHAR(200),
	Rate				NUMERIC(24,10)
) 
CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)

DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,@PTypeId,@PtypeCategoryId)

SET @SQL+='
INSERT INTO #Ptype(RowId,TypeID,SonNum,UserCode,AssistUnitFullName,UnitFullName,Rate)
SELECT
	ROW_NUMBER()OVER(ORDER BY P.UserCode) RowId,
	P.typeId,
	P.sonnum,
	P.UserCode,
	E.FullName AssistUnitFullName,
	PU.FullName UnitFullName,
	R.Rate
 '+@LinkStr+'
 LEFT JOIN PType_Units E ON P.AssistantUnitId=E.UnitsId
 '+@TempTable+'
 LEFT JOIN PType_Units PU ON PU.UnitsId=P.'+@TempColumn+'
 WHERE
	P.sonnum=0
	AND P.iscombinationproduct=0'

EXEC(@SQL)

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	BEGIN
		INSERT INTO #Stype(typeid) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
	END
	
--部门
CREATE TABLE #Dtype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
IF (@MDtypeid='-99999')
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetManDetailDType(@OperatorId)
	END

--职员
CREATE TABLE #Etype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF (@MEtypeid='-99999')
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetManDetailEType(@OperatorId)
	END
	
--仓库
CREATE TABLE #Ktype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeId)
IF (@MKtypeid='-99999')
	BEGIN
		INSERT INTO #Ktype(TypeID)
		SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
		UNION ALL
		SELECT '10000' TypeId
	END


--往来单位
CREATE TABLE #DealBtype (RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #DealBtype_P_K ON #DealBtype(TypeId)
IF(ISNULL(@DealBTypeId,'')='' AND NOT(@MBtypeid2='-99999' OR @MBTypeID='-99999'))
	BEGIN
		INSERT INTO #DealBtype(RowId,TypeID,UserCode,FullName)
		SELECT 
			ROW_NUMBER()OVER(ORDER BY UserCode) RowId,
			typeId,
			UserCode,
			FullName
		FROM btype WHERE sonnum=0 AND typeId NOT IN('00001','00002')
		ORDER BY UserCode
	END
ELSE 
	BEGIN
		INSERT INTO #DealBtype(RowId,TypeID,UserCode,FullName)
		SELECT 
			ROW_NUMBER()OVER(ORDER BY D.usercode) RowId,
			F.TypeId,
			D.usercode,
			D.FullName
		FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId) F
		INNER JOIN btype D ON F.TypeId=D.typeid
		ORDER BY usercode
	END

--当前页部门
CREATE TABLE #PageDealBtype(TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #PageDealBtype(TypeID,UserCode,FullName)
SELECT 
	typeid,
	UserCode,
	FullName 
FROM #DealBtype
WHERE RowId BETWEEN (@bPageNo-1)*@bCount AND @bPageNo*@bCount
	
--结算单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(ISNULL(@BTypeId,'')<>'' OR @MBTypeID='-99999')--所有权限
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorId)
	END
--=============================基本信息权限范围获取【END】=======================================


--=============================业务处理【BEGIN】=====================================
SET @SQL=''

--BillIndex
CREATE TABLE #BillIndex
(
	BillNumberId 	NUMERIC(18,0),
	BTypeID			VARCHAR(50),
	DealBTypeID		VARCHAR(50),
	BillType		INT	
) 
CREATE CLUSTERED INDEX #BillIndex_P_K ON #BillIndex(BillNumberId)

SET @SQL='
INSERT INTO #BillIndex
(
	BillNumberId,
	BTypeID,
	DealBTypeID,
	BillType
)
SELECT	
	B.BillNumberId,
	B.BTypeID,
	B.DealBTypeID,
	B.BillType
FROM BillIndex B' +CHAR(13)	

--分支机构
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	SET @SQL+='INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid'+CHAR(13)	

--结算单位	
IF ISNULL(@BTypeId,'')<>'' OR @MBtypeid='-99999'
	SET @SQL += 'INNER JOIN #Btype bb ON BB.TypeID = B.BTypeID '

--往来单位
IF ISNULL(@DealBTypeId,'')<>'' OR @MBtypeid='-99999'
	SET @SQL += 'INNER JOIN #DealBtype D1 ON D1.TypeID = B.DealBTypeID '
		
--部门
IF(@MDtypeid='-99999')
	SET @SQL+='INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId '+CHAR(13)	
	
--职员		
IF (@MEtypeid='-99999')
	SET @SQL+='INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid'+CHAR(13)
	

SET @SQL+='
WHERE 
	B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' 
	AND B.BillType IN ('+@BillType+')
	AND B.RedWord=0 
	AND B.IfCheck=''t'' 
	AND B.Draft=0 
	AND B.ifYearBill=0'+CHAR(13)
	
EXEC(@SQL)
SET @SQL=''


--数据明细表
CREATE TABLE #SaleBill
(
	PTypeId		VARCHAR(50),
	BTypeID		VARCHAR(50),
	DealBTypeID	VARCHAR(50),
	Qty			NUMERIC(24,10),
	NQty        NUMERIC(24,10),
	TaxTotal	NUMERIC(24,10) 
)
CREATE CLUSTERED INDEX #SaleBill_P_K ON #SaleBill(PTypeId)

--零售单
IF CHARINDEX('305',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN retailBill B ON I.BillType=305 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,I.DealBTypeID'+CHAR(13)
END

--零售退货单
IF CHARINDEX('215',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN RetailBackBill B ON I.BillType=215 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,I.DealBTypeID'+CHAR(13)
	
END

--销售出库单
IF CHARINDEX('11',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN SaleBill B ON I.BillType=11 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,I.DealBTypeID'+CHAR(13)
END

--销售退货单
IF CHARINDEX('45',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN saleBackBill B ON I.BillType=45 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,I.DealBTypeID'+CHAR(13)
END

--销售换货单
IF CHARINDEX('160',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		CASE WHEN B.InOrOut = ''o'' THEN SUM('+@TempQty+') ELSE -SUM('+@TempQty+') END Qty,
		CASE WHEN B.InOrOut = ''o'' THEN SUM(B.NQty) ELSE -SUM(B.NQty) END NQty,
		CASE WHEN B.InOrOut = ''o'' THEN CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END
			 ELSE CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END
		END TaxTotal 
	FROM #BillIndex I
	INNER JOIN SaleGoodsExchangeBill B ON I.BillType=160 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='WHERE 
		B.InOrOut=''i'' 
		OR B.InOrOut=''o''  
	GROUP BY B.PTypeId,I.BTypeID,I.DealBTypeID,B.InOrOut'+CHAR(13)
END

--委托代销结算单
IF CHARINDEX('141',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN CommissionBill B ON I.BillType=141 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,I.DealBTypeID'+CHAR(13)
END

--组合品销售出库单
IF CHARINDEX('12',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBillDetail B ON I.BillType=12 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,I.DealBTypeID'+CHAR(13)
END

--组合品销售退货单
IF CHARINDEX('46',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.BTypeID,
		I.DealBTypeID,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBackBillDetail B ON I.BillType=46 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.BTypeID,I.DealBTypeID'+CHAR(13)
END

SET @SQL='
INSERT INTO #SaleBill
(
	PTypeId,
	BTypeID,
	DealBTypeID,
	Qty,
	NQty,
	TaxTotal
)
SELECT 
	PtypeId,
	BTypeID,
	DealBTypeID,
	SUM(ISNULL(F.Qty,0)) Qty,
	SUM(ISNULL(F.NQty,0)) NQty,
	SUM(ISNULL(F.TaxTotal,0)) TaxTotal
 FROM 
('+SUBSTRING(@SQL,10,LEN(@SQL))+'
)F
GROUP BY F.PTypeId,F.BTypeID,F.DealBTypeID
'
EXEC(@SQL)

--生成分布表
SET @SQL = '
SELECT
	P.typeid,
	P.UserCode,
	P.SonNum,
	P.AssistUnitFullName 浮动单位,
	P.UnitFullName 计量单位,
	SUM(ISNULL(B.Qty,0)) 总计数量,
	SUM(ISNULL(B.NQty,0)) 总计浮动数量,
	SUM(ISNULL(B.TaxTotal,0)) 总计金额'

IF @bCount='10'
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) [('+CASE WHEN LEN(UserCode)>=50 THEN LEFT(UserCode,50) ELSE UserCode END+')'+CASE WHEN LEN(FullName)>=50 THEN LEFT(FullName,50) ELSE FullName END+'数量]
						,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) [('+CASE WHEN LEN(UserCode)>=50 THEN LEFT(UserCode,50) ELSE UserCode END+')'+CASE WHEN LEN(FullName)>=50 THEN LEFT(FullName,50) ELSE FullName END+'浮动数量]
						,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) [('+CASE WHEN LEN(UserCode)>=50 THEN LEFT(UserCode,50) ELSE UserCode END+')'+CASE WHEN LEN(FullName)>=50 THEN LEFT(FullName,50) ELSE FullName END+'金额]'  
	FROM #PageDealBtype ORDER BY UserCode 
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) [('+CASE WHEN LEN(UserCode)>=50 THEN LEFT(UserCode,50) ELSE UserCode END+')'+CASE WHEN LEN(FullName)>=50 THEN LEFT(FullName,50) ELSE FullName END+'数量]
						,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) [('+CASE WHEN LEN(UserCode)>=50 THEN LEFT(UserCode,50) ELSE UserCode END+')'+CASE WHEN LEN(FullName)>=50 THEN LEFT(FullName,50) ELSE FullName END+'浮动数量]
						,SUM(CASE WHEN B.DealBTypeID = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) [('+CASE WHEN LEN(UserCode)>=50 THEN LEFT(UserCode,50) ELSE UserCode END+')'+CASE WHEN LEN(FullName)>=50 THEN LEFT(FullName,50) ELSE FullName END+'金额]'  
	FROM #DealBtype ORDER BY UserCode 
END

SET @SQL+='
FROM #Ptype P
LEFT JOIN #SaleBill B ON B.PTypeId=P.TypeID' +CHAR(13)

--是否显示销售为0的数据
IF(ISNULL(@CheckZero,0)=0)
	SET @SQL+='INNER JOIN (SELECT SUM(ISNULL(Qty,0)) Qty,PTypeId FROM #SaleBill GROUP BY PTypeId) FS ON FS.Qty<>0 AND FS.PTypeId=P.TypeID'+CHAR(13)

SET @SQL+='
GROUP BY
	P.RowId,
	P.TypeID,
	P.UserCode,
	P.SonNum,
	P.AssistUnitFullName,
	P.UnitFullName
ORDER BY'

IF ISNULL(@sort,'')=''
	SET @SQL+='	p.RowId'   
	 
IF ISNULL(@sort,'')='0'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.Qty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.Qty,0))'  
  END				
IF ISNULL(@sort,'')='1'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.NQty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.NQty,0))'  
  END
IF	ISNULL(@sort,'')='2'
  BEGIN
	IF @ck!=1
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0)) DESC '    
    ELSE
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0))'  
  END
				
EXEC(@SQL)

--=============================业务处理【END】=======================================



--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#Dtype,#Etype,#Ktype,#Ptype,#Stype,#BillIndex,#DealBtype,#PageDealBtype,#SaleBill

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BuyBTypeMonthReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BuyBTypeMonthReport]
GO

/*
	作者：谢吉康
	日期：2009-01-08
	描述：单位采购月分析
*/

/*
	修改: 魏伟
	日期: 2015-05-24
	描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
*/
CREATE       PROCEDURE Web_BuyBTypeMonthReport
(
	@OperatorID	varchar(100),
	@StartDate	varchar(20),
	@EndDate	varchar(20),
	@dealBTypeId	VARCHAR(max),--结算单位
	@deal_btypeid	VARCHAR(max),--往来单位
	@PTypeId	varchar(8000),
	@ETypeId	varchar(8000),
	@DTypeId	varchar(8000),
	@KTypeId	varchar(8000),
	@Stypeid	varchar(8000),
	@BillType	varchar(100),
	@Flag		varchar(100),  	--ZH.折后  SH.税后
	@mPageNo	int=1,
	@mSize		int=12,
	@IsPrint	int=0,
	@bPageNo	int=1,
	@bSize		int=14,
	@ptypecategoryid    VARCHAR(MAX)    --商品类别ID

)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype1 (TypeID varchar(50), sonnum varchar(100),UserCode varchar(200),FullName varchar(200))
CREATE TABLE #dealbtype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))

/*DECLARE @sqlman VARCHAR(8000) 
SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId(@PtypeID,1,@OperatorID,'#PTYPE')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@dealBtypeID,2,@OperatorID,'#Btype1')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@etypeid,3,@OperatorID,'#ETYPE')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@ktypeid,4,@OperatorID,'#KTYPE')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@Stypeid,11,@OperatorID,'#STYPE')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@DTypeId,9,@OperatorID,'#Dtype')
--PRINT @sql
EXEC(@sqlman)*/


--商品
INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid)
--往来单位    
INSERT INTO  #Btype1(typeid,sonnum,UserCode,FullName) select B.typeid,b.sonnum, usercode,fullname from btype B, F_GetAllManagerBaseTypeId(@deal_btypeid,2,@OperatorID) W WHERE  B.typeid=W.typeid

--结算单位    
INSERT INTO  #dealbtype(typeid) select B.typeid from btype B, F_GetAllManagerBaseTypeId(@dealBTypeId,2,@OperatorID) W WHERE  B.typeid=W.typeid
--职员
INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@EtypeID,3,@OperatorID)

--仓库
IF @KTypeID=''
BEGIN
	INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorID)
	insert into #Ktype select '10000'
END
ELSE
	INSERT INTO #Ktype(typeid) select typeid from F_GetAllManagerBaseTypeId(@KTypeID,4,@OperatorID)

IF @DtypeID=''
BEGIN
	INSERT INTO #dtype(typeid) select typeid from F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)
	INSERT INTO #Dtype VALUES( '')
END
ELSE
    INSERT INTO #Dtype(typeid) select typeid from F_GetAllManagerBaseTypeId(@DtypeID,9,@OperatorID)

INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)


DECLARE @intBegin	int,
		@intEnd		int,
		@intBMonth	int,
		@intEMonth	int,
		@i			int

SET @intBegin = LEFT(@StartDate,4)+1
SET @intEnd   = LEFT(@EndDate,4)

SET @intBMonth =  Month(@StartDate)
SET @intEMonth = Month(@EndDate)

CREATE TABLE #dDate
(
	nID			int identity(1,1),
	FullName	varchar(100),
	StartDate	datetime,
	EndDate		datetime
)
--开始年份处理
IF  @intBegin-1<@intEnd
	BEGIN
		IF (@intBegin-1) % 4 = 0
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
		ELSE
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
	END

--中间年份数据处理
WHILE @intBegin<@intEnd
	BEGIN
		SET @i = 1
		WHILE @i<=12
			BEGIN
				IF @i = 1
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年01月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-31' as varchar(100)))
				ELSE IF @i = 2
					BEGIN
						IF @intBegin % 4 = 0
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-29' as varchar(100)))
						ELSE
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-28' as varchar(100)))
					END
				ELSE IF @i = 3
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年03月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-31' as varchar(100)))
				ELSE IF @i = 4
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年04月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-30' as varchar(100)))
				ELSE IF @i = 5
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年05月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-31' as varchar(100)))
				ELSE IF @i = 6
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年06月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-30' as varchar(100)))
				ELSE IF @i = 7
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年07月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-31' as varchar(100)))
				ELSE IF @i = 8
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年08月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-31' as varchar(100)))
				ELSE IF @i = 9
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年09月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-30' as varchar(100)))
				ELSE IF @i = 10
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年10月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-31' as varchar(100)))
				ELSE IF @i = 11
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年11月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-30' as varchar(100)))
				ELSE IF @i = 12
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年12月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-31' as varchar(100)))
				SET @i = @i + 1
			END

		SET @intBegin = @intBegin + 1
	END

--最后数据处理
IF @intBegin-1=@intEnd
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END
ELSE
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END

--处理开始日期和截止日期
DECLARE @nID		int,
		@rCount		int

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate ASC
UPDATE #dDate SET StartDate = @StartDate WHERE nID = @nID

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate DESC
UPDATE #dDate SET EndDate = @EndDate WHERE nID = @nID

SELECT @rCount = COUNT(*) FROM #dDate

--最后得到日期列表
DECLARE @TableHeadName 	varchar(200),
		@TableBodyName	varchar(200),
		@SQL 			varchar(8000)
SELECT 	@TableHeadName='WebDate'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableHeadName+'
	(
		nID			int identity(1,1),
		FullName	varchar(100),
		StartDate	datetime,
		EndDate		datetime
	)
	INSERT INTO '+N'##'+@TableHeadName+'(FullName,StartDate,EndDate)
	SELECT 	FullName,
			StartDate,
			EndDate 
	FROM 	#dDate 
	ORDER BY StartDate ASC'

EXEC(@SQL)


--过滤单位信息
CREATE TABLE #BType
(
	TypeID		varchar(100),
	sonnum		varchar(100),
	UserCode	varchar(200),
	FullName	varchar(200)
)
IF @IsPrint = 0
	INSERT INTO #BType(TypeId,sonnum,UserCode,FullName)
	SELECT	b.TypeId,b.sonnum,b.UserCode,b.FullName
	FROM	#BType1 b1 INNER JOIN dbo.btype b ON b1.TypeId = b.typeId
	ORDER BY b.UserCode
ELSE
	BEGIN
		SET @SQL =' INSERT INTO #BType(TypeId,sonnum,UserCode,FullName)
					SELECT	TOP '+CAST(@bSize AS varchar(50))+' b.TypeId,b.sonnum,b.UserCode,b.FullName
					FROM	#BType1 b1 INNER JOIN dbo.btype b ON b1.TypeId = b.typeId
					WHERE	b.UserCode NOT IN (
								SELECT	TOP ' + CAST((@bPageNo-1) * @bSize AS varchar(50)) + ' b.UserCode
								FROM	#BType1 b1 INNER JOIN dbo.btype b ON b1.TypeId = b.typeId
								ORDER BY b.UserCode										
							)
					ORDER BY b.UserCode '
					PRINT @sql
		EXEC(@SQL)
	END

DECLARE @ColName varchar(4000)
SET @ColName ='typeid,usercode,fullname,[总计数量],[总计金额]'


--得到表体数据列表
SELECT 	@TableBodyName='WebBody'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableBodyName+'
	(
		TypeId		varchar(100),
		sonnum		varchar(100),
		UserCode 	varchar (200) NULL ,
		FullName 	varchar (256) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)
	INSERT INTO '+N'##'+@TableBodyName+'
	(
		TypeId,
		sonnum,
		UserCode,
		FullName,
		总计数量,
		总计金额
	)
	SELECT	TypeId,
			sonnum,
			UserCode,
			FullName,
			0,
			0
	FROM	#BType '
EXEC(@SQL)

----------------------------------------------
    CREATE TABLE #BillName ( Billtype INT )
    INSERT  INTO #BillName
            SELECT  A
            FROM    DBO.f_split(@BillType, ',')


    CREATE TABLE #Billnum
        (
           dealBTypeId			varchar(50),
           btypeid				varchar(200),	
           BillNumberID          NUMERIC(24, 10) ,
		   billtype             INT,
           BillDate				DATETIME,
           EtypeID				varchar(50),
           DtypeID				varchar(50)
        )

	CREATE TABLE #BillDetails
        (
          dealBTypeId	varchar(50),
          btypeid				varchar(200),
          BillDate		DATETIME ,
          Qty			 NUMERIC(24, 10)  ,
          Total			 NUMERIC(24, 10) ,
          PTypeId		VARCHAR(50) ,
          EtypeID		varchar(50),
          DtypeID		varchar(50),
          KtypeID		varchar(50)
        )
        
     SET @sql ='INSERT INTO #Billnum 
					 SELECT dealBTypeId,btypeid,BillNumberId,BillType,BillDate,EtypeID,DtypeID
					 FROM BillIndex bil'         
     IF NOT (@STypeId = '' AND @MStypeid = '00000') 
        SET @SQL = @SQL + ' INNER JOIN #Stype S ON bil.stypeID =S.typeid '	
    SET @SQL = @SQL + ' WHERE	Bil.BillDate>=''' + @StartDate +'''
						AND Bil.BillDate<=''' + @EndDate + '''
						AND Bil.BillType IN (' + @BillType + ')
						AND Bil.IfCheck = ''t''
						AND Bil.RedWord = 0
						AND Bil.Draft = 0
						and ifYearBill=0
						' 
						
    EXEC (@sql) 

 SET @sql = '  
	IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 34)
	INSERT INTO #BillDetails
	SELECT dealBTypeId,btypeid,b.BillDate,SUM(a.Qty) as Qty,
	SUM(
		CASE
			WHEN  '+char(39)+@Flag+char(39)+'=''SH'' THEN a.TaxTotal
			WHEN  '+char(39)+@Flag+char(39)+'=''ZH'' THEN a.Total
			ELSE 0	END
		) as total,PTypeId,EtypeID,DtypeID,a.KtypeID
	FROM Buybill A
	INNER JOIN #BillNum b
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 34
	GROUP BY dealBTypeId,B.BillDate,PTypeId,EtypeID,DtypeID,a.KtypeID,btypeid'

	EXEC (@sql)

 SET @sql = ' 
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 6)
	INSERT INTO #BillDetails
	SELECT dealBTypeId,btypeid,b.BillDate,-SUM(a.Qty) as Qty,
	-SUM(
		CASE
			WHEN '+char(39)+@Flag+char(39)+'=''SH'' THEN A.TaxTotal
			WHEN '+char(39)+@Flag+char(39)+'=''ZH'' THEN A.Total
			ELSE 0  END
		) AS TOTAL,PTypeId,EtypeID,DtypeID,a.KtypeID
	FROM buybackbill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 6
	GROUP BY dealBTypeId,B.BillDate,PTypeId,EtypeID,DtypeID,a.KtypeID,btypeid'
	EXEC (@sql)

 SET @SQL = '
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 161)
	INSERT INTO #BillDetails
	SELECT dealBTypeId,btypeid,b.BillDate,
	SUM(
		CASE WHEN a.InOrOut=''O'' THEN -a.qty
			 ELSE a.qty END
		) AS QTY,	
	SUM(
		CASE
			WHEN a.InOrOut=''I'' AND '+char(39)+@Flag+char(39)+'=''SH'' THEN a.TaxTotal
			WHEN a.InOrOut=''I'' AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN a.Total
			WHEN a.InOrOut=''O'' AND '+char(39)+@Flag+char(39)+'=''SH'' THEN -a.TaxTotal
			WHEN a.InOrOut=''O'' AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN -a.TotaL
			ELSE 0	END
		) as total,PTypeId,EtypeID,DtypeID,a.KtypeID 
	FROM buygoodsexchangebill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 161
	GROUP BY dealBTypeId,B.BillDate,PTypeId,EtypeID,DtypeID,a.KtypeID,btypeid'
	EXEC (@sql)
	--PRINT(@SQL)
		
SET @SQL = '
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 145)
	INSERT INTO #BillDetails
	SELECT dealBTypeId,btypeid,b.BillDate,SUM(a.Qty) as Qty,
	SUM(
			CASE WHEN '+char(39)+@Flag+char(39)+'=''SH'' THEN a.TaxTotal
				 WHEN '+char(39)+@Flag+char(39)+'=''ZH'' THEN a.Total
				 ELSE 0	END
		) AS total,PTypeId,EtypeID,DtypeID,10000
	FROM commissionbill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
	WHERE a.Type=''145'' AND B.BillType = 145
	GROUP BY dealBTypeId,B.BillDate,PTypeId,EtypeID,DtypeID,btypeid'
	EXEC (@sql)
	
--更新数据源


CREATE TABLE #InOutStockTable
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) 
)



    SET @SQL = 'INSERT INTO #InOutStockTable
		(
			PTypeId,
			BillDate,
			Qty,
			Total
		)
		SELECT	i.dealBTypeId,
				i.BillDate,
				i.Qty,
				i.Total
		FROM	#BillDetails I '
	IF NOT (@PTypeId ='' AND @MPtypeid = '00000' AND @ptypecategoryid='')
       SET @SQL = @SQL+ '  INNER JOIN #ptype p ON I.PtypeID=p.typeid '
       
    IF NOT (@dealBTypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
       SET @SQL = @SQL+ '  INNER JOIN #BType B ON i.dealBTypeId = B.TypeId '   
   
       IF NOT (@deal_BTypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
       SET @SQL = @SQL+ '  INNER JOIN #dealbtype Bb ON i.btypeid = Bb.TypeId '  
   
    IF NOT (@ETypeId = '' AND @METypeId = '00001')
       SET @SQL = @SQL+ '  INNER JOIN #Etype e ON i.EtypeID=e.typeid '
	
	IF NOT (@KTypeId = '' AND @MKTypeId = '00001')
        SET @SQL = @SQL+ ' INNER JOIN #Ktype k ON I.KtypeID=k.typeid '
    
    IF NOT (@DTypeId = '' AND @MDtypeid='00000')	
		SET @SQL = @SQL+ ' INNER JOIN #Dtype d ON i.DtypeID=d.typeid '    
		

--PRINT(@SQL)
    EXEC(@SQL) 


--更新总计数据
    SET @SQL = '
	UPDATE	' + N'##' + @TableBodyName + '
	SET		总计数量 = ISNULL(I.Qty,0),
			总计金额 = ISNULL(I.Total,0)
	FROM	' + N'##' + @TableBodyName + ' T
	LEFT JOIN (
		SELECT	PTypeId,
				SUM(Qty) AS Qty,
				SUM(Total) AS Total
		FROM	#InOutStockTable
		GROUP BY PTypeId
	)I ON T.TypeId = I.PTypeId'
    EXEC(@SQL)

--更新数据源
    CREATE TABLE #InOutStockTableMx
        (
          PTypeId VARCHAR(100) ,
          BillDate DATETIME ,
          Qty  NUMERIC(24, 10)  ,
          Total  NUMERIC(24, 10) 
        )

--更新明细数据
    DECLARE @sBdate DATETIME ,
        @sEdate DATETIME

    EXEC Web_GetTwoDateMonth @StartDate, @EndDate, @mPageNo, 0, @sBdate OUTPUT,
        @sEdate OUTPUT

    IF ISNULL(@sEdate, '') = ''
        OR ISNULL(@sEdate, '') = '1900-01-01'
        OR ISNULL(@sEdate, '') = '1900-1-1' 
        SET @sEDate = @EndDate

    IF @IsPrint = 0 
        INSERT  INTO #InOutStockTableMx
                SELECT  PTypeId ,
                        BillDate ,
                        Qty ,
                        Total
                FROM    #InOutStockTable
                WHERE   BillDate >= @sBdate
                        AND BillDate <= @sEdate
    ELSE 
        INSERT  INTO #InOutStockTableMx
                SELECT  PTypeId ,
                        BillDate ,
                        Qty ,
                        Total
                FROM    #InOutStockTable
                WHERE   BillDate >= @StartDate
                        AND BillDate <= @EndDate


--更新数量，金额数据
    DECLARE @FullName VARCHAR(100) ,
        @sDate DATETIME ,
        @eDate DATETIME

    SET @SQL = '
	DECLARE MxCursor CURSOR FOR
		SELECT 	FullName,
				StartDate,
				EndDate 
		FROM 	' + N'##' + @TableHeadName + '
		WHERE	nID>' + CAST(( @mPageNo - 1 ) * @mSize AS VARCHAR(100)) + '
				AND nID<=' + CAST(@mPageNo * @mSize AS VARCHAR(100))
    EXEC(@SQL)
    OPEN MxCursor
    FETCH NEXT FROM MxCursor INTO @FullName, @sDate, @eDate
    WHILE @@FETCH_STATUS = 0 
        BEGIN
            EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '数量]  NUMERIC(24, 10) ')
            EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '金额]  NUMERIC(24, 10) ')
            SET @ColName = @ColName + ',Case when [' + @FullName
                + '数量] =0 then null else [' + @FullName + '数量] end as ['
                + @FullName + '数量]'
            SET @ColName = @ColName + ',Case when [' + @FullName
                + '金额] =0 then null else [' + @FullName + '金额] end as ['
                + @FullName + '金额]'

            SET @SQL = '
			UPDATE	' + N'##' + @TableBodyName + '
			SET		[' + @FullName + '数量] = ISNULL(I.Qty,0),
					[' + @FullName + '金额] = ISNULL(I.Total,0)
			FROM	' + N'##' + @TableBodyName + ' T
			LEFT JOIN (
				SELECT	PTypeId,
						SUM(Qty) AS Qty,
						SUM(Total) AS Total
				FROM	#InOutStockTableMx
				WHERE	BillDate>=' + CHAR(39)
                + CONVERT(VARCHAR(10), @sDate, 120) + CHAR(39) + '
						AND BillDate<=' + CHAR(39)
                + CONVERT(VARCHAR(10), @eDate, 120) + CHAR(39) + '
				GROUP BY PTypeId
			)I ON T.TypeId = I.PTypeId'
            EXEC(@SQL)
            FETCH NEXT FROM MxCursor INTO @FullName, @sDate, @eDate
        END
    CLOSE MxCursor
    DEALLOCATE MxCursor

    IF @IsPrint = 1 --全部打印
        EXEC('SELECT * FROM '+N'##'+@TableBodyName+' WHERE [总计数量]<>0 OR [总计金额]<>0 ORDER BY UserCode')
    ELSE 
        EXEC('SELECT * FROM '+N'##'+@TableBodyName+' WHERE [总计数量]<>0 OR [总计金额]<>0 ORDER BY UserCode')

--删除临时表
    EXEC('DROP TABLE #dDate,#Billnum,#billname,#BillDetails,#InOutStockTable,#InOutStockTableMx,#BType,#Btype1,#Ptype,#Etype,#Ktype,#Dtype,#Stype,'+N'##'+@TableHeadName+','+N'##'+@TableBodyName)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BuyBTypeMonthReportPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BuyBTypeMonthReportPrint]
GO




























/*
	作者：谢吉康
	日期：2009-01-08
	描述：单位采购月分析
*/
CREATE  PROCEDURE Web_BuyBTypeMonthReportPrint
(
	@OperatorID	varchar(100),
	@StartDate	varchar(20),
	@EndDate	varchar(20),
	@BTypeId	varchar(100),
	@PTypeId	varchar(100),
	@ETypeId	varchar(100),
	@DTypeId	varchar(100),
	@KTypeId	varchar(100),
	@BillType	varchar(100),
	@Flag		varchar(100),  	--ZH.折后  SH.税后
	@mPageNo	int=1,
	@mSize		int=12,
	@IsPrint	int=0,
	@bPageNo	int=1,
	@bSize		int=14
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------
IF @BTypeId = '00000'
	SET @BTypeId = '%'
IF @PTypeId = '00000'
	SET @PTypeId = '%'
IF @KTypeId = '00000'
	SET @KTypeId = '%'
IF @DTypeId = '00000'
	SET @DTypeId = '%'

DECLARE @intBegin	int,
		@intEnd		int,
		@intBMonth	int,
		@intEMonth	int,
		@i			int,
		@re_Limit  int

--成本查看权限
EXEC @re_Limit=GP_CheckLimit @OperatorID,166

SET @intBegin = LEFT(@StartDate,4)+1
SET @intEnd   = LEFT(@EndDate,4)

SET @intBMonth = SUBSTRING(@StartDate,6,2)
SET @intEMonth = SUBSTRING(@EndDate,6,2)

CREATE TABLE #dDate
(
	nID			int identity(1,1),
	FullName	varchar(100),
	StartDate	datetime,
	EndDate		datetime
)
--开始年份处理
IF  @intBegin-1<@intEnd
	BEGIN
		IF (@intBegin-1) % 4 = 0
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
		ELSE
			WHILE @intBMonth<=12
				BEGIN

					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
	END

--中间年份数据处理
WHILE @intBegin<@intEnd
	BEGIN
		SET @i = 1
		WHILE @i<=12
			BEGIN
				IF @i = 1
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年01月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-31' as varchar(100)))
				ELSE IF @i = 2
					BEGIN
						IF @intBegin % 4 = 0
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-29' as varchar(100)))
						ELSE
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-28' as varchar(100)))
					END
				ELSE IF @i = 3
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年03月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-31' as varchar(100)))
				ELSE IF @i = 4
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年04月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-30' as varchar(100)))
				ELSE IF @i = 5
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年05月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-31' as varchar(100)))
				ELSE IF @i = 6
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年06月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-30' as varchar(100)))
				ELSE IF @i = 7
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年07月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-31' as varchar(100)))
				ELSE IF @i = 8
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年08月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-31' as varchar(100)))
				ELSE IF @i = 9
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年09月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-30' as varchar(100)))
				ELSE IF @i = 10
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年10月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-31' as varchar(100)))
				ELSE IF @i = 11
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年11月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-30' as varchar(100)))
				ELSE IF @i = 12
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年12月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-31' as varchar(100)))
				SET @i = @i + 1
			END

		SET @intBegin = @intBegin + 1
	END

--最后数据处理
IF @intBegin-1=@intEnd
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END
ELSE
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END

--处理开始日期和截止日期
DECLARE @nID		int,
		@rCount		int

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate ASC
UPDATE #dDate SET StartDate = @StartDate WHERE nID = @nID

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate DESC
UPDATE #dDate SET EndDate = @EndDate WHERE nID = @nID

SELECT @rCount = COUNT(*) FROM #dDate

--最后得到日期列表
DECLARE @TableHeadName 	varchar(200),
		@TableBodyName	varchar(200),
		@SQL 			varchar(8000)
SELECT 	@TableHeadName='WebDate'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableHeadName+'
	(
		nID			int identity(1,1),
		FullName	varchar(100),
		StartDate	datetime,
		EndDate		datetime
	)
	INSERT INTO '+N'##'+@TableHeadName+'(FullName,StartDate,EndDate)
	SELECT 	FullName,
			StartDate,
			EndDate 
	FROM 	#dDate 
	ORDER BY StartDate ASC'

EXEC(@SQL)

--过滤商品信息
CREATE TABLE #BType
(
	TypeID		varchar(100),
	UserCode	varchar(200),
	FullName	varchar(200)
)

INSERT INTO #BType(TypeId,UserCode,FullName)
SELECT	TypeId,UserCode,FullName
FROM	BType
WHERE	Deleted = 0
		AND SonNum=0
		AND TypeId LIKE @BTypeId + '%'
		AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
ORDER BY UserCode

--得到表体数据列表
SELECT 	@TableBodyName='WebBody'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableBodyName+'
	(
		TypeId		varchar(100),
		UserCode 	varchar (200) NULL ,
		FullName 	varchar (256) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)
	INSERT INTO '+N'##'+@TableBodyName+'
	(
		TypeId,
		UserCode,
		FullName,
		总计数量,
		总计金额
	)
	SELECT	TypeId,
			UserCode,
			FullName,
			0,
			0
	FROM	#BType '
EXEC(@SQL)

--更新数据源
CREATE TABLE #InOutStockTable
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) 
)

SET @SQL = 'INSERT INTO #InOutStockTable
		(
			PTypeId,
			BillDate,
			Qty,
			Total
		)
		SELECT	B.BTypeId,
				B.BillDate,
				ISNULL(SUM(B.Qty),0) AS Qty,
				ISNULL(CAST(SUM(B.Total) AS  NUMERIC(24, 10) ),0) AS Total
		FROM	(				
				SELECT	I.BTypeId,
						I.BillDate,
						CASE
							WHEN Bil.BillType IN (34,161) THEN I.Qty
							WHEN Bil.BillType = 157 AND I.Qty>0 THEN I.Qty
							WHEN Bil.BillType = 157 AND I.Qty<0 THEN 0
							WHEN Bil.BillType = 145 THEN -1*I.Qty
							ELSE I.Qty
						END AS Qty,
						CASE
							WHEN Bil.BillType IN (34,161) AND '+char(39)+@Flag+char(39)+'=''SH'' THEN CAST(I.qty*I.price*(1+Bil.Tax/100) as  NUMERIC(24, 10) )
							WHEN Bil.BillType IN (157) AND I.Qty>0 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN CAST(I.qty*I.price*(1+Bil.Tax/100) as  NUMERIC(24, 10) )
							WHEN Bil.BillType IN (157) AND I.Qty<0 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN 0
							WHEN Bil.BillType IN (145) AND '+char(39)+@Flag+char(39)+'=''SH'' THEN CAST(-1*I.qty*I.price*(1+Bil.Tax/100) as  NUMERIC(24, 10) )
							WHEN Bil.BillType = 6 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN CAST(I.qty*I.price*(1+Bil.Tax/100) as  NUMERIC(24, 10) )
							WHEN Bil.BillType IN (34,161) AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							WHEN Bil.BillType IN (157) AND I.Qty>0 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							WHEN Bil.BillType IN (157) AND I.Qty<0 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN 0
							WHEN Bil.BillType IN (145) AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN -1*I.Total
							WHEN Bil.BillType = 6 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							ELSE 0					
						END AS Total
				FROM	BillIndex Bil,
						InOutStockTable I,
						#BType B
				WHERE	Bil.BillNumberId = I.BillNumberId
						AND I.BTypeId = B.TypeId
						AND Bil.BillType IN ('+@BillType+')
						AND Bil.IfCheck = ''t''
						AND Bil.RedWord = 0
						AND Bil.Draft = 0									

						AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
						AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
						AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
						AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
						AND (I.KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'  OR I.KTypeId=''10000'')
						AND (I.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR I.KTypeId=''10000'')
						AND I.PTypeId LIKE '+char(39)+@PTypeId+'%'+char(39)+'
						AND I.PTypeId LIKE '+char(39)+@MPTypeId+'%'+char(39)+'
						AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
						AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
						AND Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+'
		)B GROUP BY B.BTypeId,B.BillDate'

--PRINT(@SQL)
EXEC(@SQL)

--更新总计数据
IF @re_Limit = 0 
	SET @SQL = '
		UPDATE	'+N'##'+@TableBodyName+'
		SET		总计数量 = ISNULL(I.Qty,0),
				总计金额 = ISNULL(I.Total,0)
		FROM	'+N'##'+@TableBodyName+' T
		LEFT JOIN (
			SELECT	PTypeId,
					SUM(Qty) AS Qty,
					SUM(Total) AS Total
			FROM	#InOutStockTable
			GROUP BY PTypeId
		)I ON T.TypeId = I.PTypeId'
ELSE
	SET @SQL = '
		UPDATE	'+N'##'+@TableBodyName+'
		SET		总计数量 = ISNULL(I.Qty,0),
				总计金额 = ISNULL(0,0)
		FROM	'+N'##'+@TableBodyName+' T
		LEFT JOIN (
			SELECT	PTypeId,
					SUM(Qty) AS Qty,
					SUM(Total) AS Total
			FROM	#InOutStockTable
			GROUP BY PTypeId
		)I ON T.TypeId = I.PTypeId'EXEC(@SQL)

--更新数据源
CREATE TABLE #InOutStockTableMx
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) 
)

--更新明细数据
DECLARE @sBdate datetime,
		@sEdate datetime

EXEC Web_GetTwoDateMonth @StartDate,@EndDate,@mPageNo,0,@sBdate OUTPUT,@sEdate OUTPUT

IF ISNULL(@sEdate,'')='' OR ISNULL(@sEdate,'') = '1900-01-01' OR ISNULL(@sEdate,'')='1900-1-1'
	SET @sEDate = @EndDate

IF @IsPrint = 0
	INSERT INTO #InOutStockTableMx SELECT PTypeId,BillDate,Qty,Total FROM #InOutStockTable WHERE BillDate>=@sBdate AND BillDate<=@sEdate
ELSE
	INSERT INTO #InOutStockTableMx SELECT PTypeId,BillDate,Qty,Total FROM #InOutStockTable WHERE BillDate>=@StartDate AND BillDate<=@EndDate


--更新数量，金额数据
DECLARE @FullName 	varchar(100),
		@sDate		datetime,
		@eDate		datetime

SET @SQL = '
	DECLARE MxCursor CURSOR FOR
		SELECT 	FullName,
				StartDate,
				EndDate 
		FROM 	'+N'##'+@TableHeadName+'
		WHERE	nID>'+CAST((@mPageNo-1)*@mSize as varchar(100))+'
				AND nID<='+CAST(@mPageNo*@mSize as varchar(100))
EXEC(@SQL)
OPEN MxCursor
FETCH NEXT FROM MxCursor INTO @FullName,@sDate,@eDate
WHILE @@FETCH_STATUS=0
	BEGIN
		EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '数量]  NUMERIC(24, 10) ')
		EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '金额]  NUMERIC(24, 10) ')
		IF @re_Limit = 0 
			SET @SQL = '
				UPDATE	'+N'##'+@TableBodyName+'
				SET		['+@FullName+'数量] = ISNULL(I.Qty,0),
						['+@FullName+'金额] = ISNULL(I.Total,0)
				FROM	'+N'##'+@TableBodyName+' T
				LEFT JOIN (
					SELECT	PTypeId,
							SUM(Qty) AS Qty,
							SUM(Total) AS Total
					FROM	#InOutStockTableMx
					WHERE	BillDate>='+char(39)+CONVERT(varchar(10),@sDate,120)+char(39)+'
							AND BillDate<='+char(39)+CONVERT(varchar(10),@eDate,120)+char(39)+'
					GROUP BY PTypeId
				)I ON T.TypeId = I.PTypeId'
		ELSE
			SET @SQL = '
				UPDATE	'+N'##'+@TableBodyName+'
				SET		['+@FullName+'数量] = ISNULL(I.Qty,0),
						['+@FullName+'金额] = ISNULL(0,0)
				FROM	'+N'##'+@TableBodyName+' T
				LEFT JOIN (
					SELECT	PTypeId,
							SUM(Qty) AS Qty,
							SUM(Total) AS Total
					FROM	#InOutStockTableMx
					WHERE	BillDate>='+char(39)+CONVERT(varchar(10),@sDate,120)+char(39)+'
							AND BillDate<='+char(39)+CONVERT(varchar(10),@eDate,120)+char(39)+'
					GROUP BY PTypeId
				)I ON T.TypeId = I.PTypeId'
		EXEC(@SQL)
		FETCH NEXT FROM MxCursor INTO @FullName,@sDate,@eDate
	END

CLOSE MxCursor
DEALLOCATE MxCursor

IF @IsPrint = 0
	EXEC('SELECT * FROM '+N'##'+@TableBodyName+' WHERE [总计数量]<>0 OR [总计金额]<>0 ORDER BY UserCode')
ELSE
	BEGIN
		SET @SQL =' SELECT	TOP '+CAST(@bSize AS varchar(50))+' *
					FROM	'+N'##'+@TableBodyName+'
					WHERE	([总计数量]<>0 OR [总计金额]<>0)
							AND UserCode NOT IN (
								SELECT	TOP ' + CAST((@bPageNo-1) * @bSize AS varchar(50)) + ' UserCode
								FROM	'+N'##'+@TableBodyName+'
								WHERE	([总计数量]<>0 OR [总计金额]<>0)
								ORDER BY UserCode										
							)
					ORDER BY UserCode '
		EXEC(@SQL)
	END

--删除临时表
EXEC('DROP TABLE #dDate,#InOutStockTable,#InOutStockTableMx,#BType,'+N'##'+@TableHeadName+','+N'##'+@TableBodyName)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_BuyInvoiceStat]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_BuyInvoiceStat
GO


/*
	作者：蒋奎
	日期：2015-05-25
	描述：发票统计 -- 业务类型发票 
 */
CREATE  PROCEDURE Web_BuyInvoiceStat
 (
	@OperatorId		VARCHAR(50),	--操作员ID
	@PTypeId		VARCHAR(MAX),	--商品ID
	@ETypeId		VARCHAR(MAX),	--职员ID
	@BTypeId		VARCHAR(MAX),	--往来单位ID
	@DTypeId		VARCHAR(MAX),	--部门ID
	@KTypeId		VARCHAR(MAX),	--仓库ID 
	@StartDate		VARCHAR(100),	--开始日期
	@EndDate		VARCHAR(100),	--结束日期
	@Comment		VARCHAR(MAX)='',--备注
	@BillType		VARCHAR(MAX),	--单据类型
	@nType			VARCHAR(20),	--查询类型   
	@STypeId		VARCHAR(MAX),
	@ifini			BIT
)
--@encode$--
AS

SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------
--多级权限
SELECT TypeId INTO #stype FROM  F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId) --分支机构权限
SELECT TypeId INTO #ptype FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID) --商品权限
--SELECT TypeId INTO #dealBtype FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)  --往来单位权限
SELECT TypeId INTO #btype FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)  --结算单位权限
SELECT TypeId INTO #Etype FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID) --职员权限
SELECT TypeId INTO #ktype FROM F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorID)  --仓库权限
SELECT TypeId INTO #dtype FROM  F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorId) --部门权限

------------------------------------------------------	出BillIndex的数据 - 开始	-------------------------------------------------

DECLARE @SQLBill VARCHAR(MAX)=''
	
CREATE TABLE #BillIndex(
	BillNumberId numeric(10, 0) ,
	Btypeid varchar(max)
 )
CREATE TABLE [dbo].[#Billtype] (
	[Billtype] varchar(200)
)
INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@billType,',')
	
 
SET  @SQLBill+=' 
							INSERT INTO #BillIndex (BillnumberID,Btypeid) 
							SELECT b.BillnumberID,b.Btypeid
							FROM BillIndex b
							INNER JOIN #Billtype BILL ON b.billtype=BILL.billtype '
	

IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
	SET @SQLBill=@SQLBill+' 
							INNER JOIN #Btype bt ON b.btypeid=bt.typeid '


IF @etypeid<>'' OR @METypeID=-99999 
	SET @SQLBill=@SQLBill+' 
							INNER JOIN #Etype e  ON b.etypeid=e.typeid '

IF NOT(@stypeid='' and @MStypeid='00000')
    SET @SQLBill=@SQLBill+' 
							INNER JOIN #Stype s  ON  b.stypeID=s.typeid '
							
IF NOT(@dtypeid='' and @MDtypeid='00000')
    SET @SQLBill=@SQLBill+' 
							INNER JOIN #Dtype d  ON  b.dtypeID=d.typeid '
 
SET @SQLBill=@SQLBill+' 
							WHERE b.BillDate>='''+@startDate +''' AND b.BillDate<='''+@endDate+''' 
									AND b.RedWord=0 ' 
							
IF @ifini = 0
	SET @SQLBill+=' AND b.ifcheck=''t'' AND b.draft = 0 AND b.isini = 0'
ELSE
	SET @SQLBill+=' AND (b.draft = 0 OR b.isini = 1) '
	
IF(@Comment <> '')
 	SET @SQLBill = @SQLBill + ' AND  b.Comment like ''%' + @Comment + '%'' '
 
--SET @SQLBill=@SQLBill+'  AND b.ifYearBill=''0'' '  --年节存标志

EXEC(@SQLBill) 
--调试SQL
--PRINT (@SQLBill)
--SELECT * FROM #Billtype
--SELECT * FROM #Stype
--SELECT * FROM #BillIndex

----------------------------------------------------	出BillIndex的数据 - 结束	-------------------------------------------------

CREATE TABLE #AppraisalTable(
 	Btypeid varchar (max),  
	Qty  NUMERIC(24, 10) ,
	Total  NUMERIC(24, 10) ,
	KQty  NUMERIC(24, 10) ,
	KTotal  NUMERIC(24, 10) ,
	WQty  NUMERIC(24, 10) ,
	WTotal  NUMERIC(24, 10) ,
	billType varchar (500)
)
------------------------------------------------------	出AppraisalBill的汇总SQL - 开始	-------------------------------------------------

DECLARE @SQLAppraisalBill VARCHAR(MAX)
SET @SQLAppraisalBill = 'INSERT INTO #AppraisalTable
						SELECT 
								b.Btypeid, 
			 					SUM(a.Qty) as qty, /*销售数量*/
								SUM(a.TaxTotal) as total, /*价税合计*/
								SUM(a.InvoiceQty) as kqty , /*开票数量*/
								SUM(a.InvoiceMoney) as ktotal,  /*开票金额*/
								SUM(a.Qty - a.InvoiceQty) as wqty , /*未开票数量*/
								SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ) as wtotal , /*未开票金额（含税）*/
								''400'' as billType
						FROM  AppraisalBill a
						INNER JOIN #BillIndex b ON a.BillnumberID=b.BillnumberID 
						INNER JOIN BillIndex bi ON bi.BillnumberID=b.BillnumberID 
						
					 '
IF @ptypeid<>'' OR @MPTypeID=-99999 
	SET @SQLAppraisalBill+='	INNER JOIN #Ptype p ON a.ptypeid=p.typeid ' 

IF @ktypeid<>'' OR @MKTypeID=-99999 
	SET @SQLAppraisalBill+='	INNER JOIN #Ktype k ON a.ktypeid=k.typeid ' 

SET @SQLAppraisalBill += ' WHERE  bi.BillDate BETWEEN '+CHAR(39)+@startDate+CHAR(39)+' AND '+CHAR(39)+@endDate+CHAR(39)
SET @SQLAppraisalBill +=	'
						GROUP BY
								b.Btypeid 
						 
						'
------------------------------------------------------	出AppraisalBill的汇总SQL - 结束	-------------------------------------------------

------------------------------------------------------	出AppraisalBackBill的汇总SQL - 开始	-------------------------------------------------
DECLARE @SQLAppraisalBackBill VARCHAR(MAX)
SET @SQLAppraisalBackBill = 'INSERT INTO #AppraisalTable
							SELECT 
									b.Btypeid, 
			 						-SUM(a.Qty) as qty, /*销售数量*/
									-SUM(a.TaxTotal) as total, /*价税合计*/
									-SUM(a.InvoiceQty) as kqty , /*开票数量*/
									-SUM(a.InvoiceMoney) as ktotal, /*开票金额*/
									-SUM(a.Qty - a.InvoiceQty) as wqty , /*未开票数量*/
									-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ) as wtotal , /*未开票金额（含税）*/
									''401'' as billType
							FROM  AppraisalBackBill a
							INNER JOIN #BillIndex b ON a.BillnumberID=b.BillnumberID
							INNER JOIN BillIndex bi ON bi.BillnumberID=b.BillnumberID 
							 
					 '
IF @ptypeid<>'' OR @MPTypeID=-99999 
	SET @SQLAppraisalBackBill+='	INNER JOIN #Ptype p ON a.ptypeid=p.typeid ' 

IF @ktypeid<>'' OR @MKTypeID=-99999 
	SET @SQLAppraisalBackBill+='	INNER JOIN #Ktype k ON a.ktypeid=k.typeid ' 

SET @SQLAppraisalBackBill += ' WHERE  bi.BillDate BETWEEN '+CHAR(39)+@startDate+CHAR(39)+' AND '+CHAR(39)+@endDate+CHAR(39)
SET @SQLAppraisalBackBill +=	'
							GROUP BY
									b.Btypeid 
							 
							'
------------------------------------------------------	出AppraisalBackBill的汇总SQL - 结束	-------------------------------------------------

------------------------------------------------------	出汇总数据#SendTable- 开始	-------------------------------------------------

IF @billType = '400' --暂估入库单
BEGIN
	EXEC (@SQLAppraisalBill)
	--PRINT ( @SQLAppraisalBill)
	--SELECT * FROM #SendTable

END
IF @billType = '401' --暂估退货单
BEGIN
	EXEC (@SQLAppraisalBackBill)
	--PRINT ( @SQLAppraisalBackBill)
	--SELECT * FROM #SendTable

END
IF @billType = '400,401' --出库单+退货单
BEGIN
	EXEC (@SQLAppraisalBill+@SQLAppraisalBackBill) --将出库单+退货单的数据SUM到#SendTable
	INSERT INTO #AppraisalTable
	SELECT 
		Btypeid  ,
		SUM(Qty),  
		SUM(Total),  
		SUM(KQty), 
		SUM(KTotal),
		SUM(WQty), 
		SUM(WTotal),
		'400,401' --此值标识 SUM后的数据
   FROM #AppraisalTable
   GROUP BY Btypeid
   
   DELETE FROM #AppraisalTable WHERE billType ='400' OR billType='401' --删除不需要的汇总数据
  --PRINT ( @SQLAppraisalBill+@SQLAppraisalBackBill)
   --SELECT * FROM #SendTable

END
------------------------------------------------------	出汇总数据#SendTable- 结束	-------------------------------------------------

--最终出数据
DECLARE @SQLOut VARCHAR(MAX)
SET @SQLOut='
				SELECT 
					st.btypeId as typeid,
					ISNULL(st.Qty,0) as Qty,      
					ISNULL(st.Total,0) as Total,      
					ISNULL(st.KQty ,0) as KQty,      
					ISNULL(st.KTotal,0) as KTotal,    
					ISNULL(st.WQty,0) as WQty,    
					ISNULL(st.WTotal,0) AS WTotal    
 				FROM #AppraisalTable st  
 				
				'

EXEC(@SQLOut)
 


 
--删除临时表
DROP TABLE #stype,#ptype,#btype,#Etype,#ktype,#AppraisalTable,#Dtype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_BuyInvoiceStatDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].Web_BuyInvoiceStatDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
	作者：蒋奎
	日期：2015-5-25
	描述：采购开票明细账
-------------------------------------------*/
CREATE PROCEDURE Web_BuyInvoiceStatDetail
  (
	@OperatorId		VARCHAR(50),	--操作员ID
	@PTypeId		VARCHAR(MAX),	--商品ID
	@ETypeId		VARCHAR(MAX),	--职员ID
	@BTypeId		VARCHAR(MAX),	--往来单位ID
	@DTypeId		VARCHAR(MAX),	--部门ID
	@KTypeId		VARCHAR(MAX),	--仓库ID
	@StartDate		VARCHAR(100),	--开始日期
	@EndDate		VARCHAR(100),	--结束日期
	@Comment		VARCHAR(MAX)='',--备注
	@BillType		VARCHAR(MAX),	--单据类型
	@nType			VARCHAR(20),	--查询类型  sale:销售  buy:采购
	@STypeId		VARCHAR(max),
	@ifini			BIT
)
--@encode$--
AS

SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------
--多级权限
SELECT TypeId INTO #stype FROM  F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId) --分支机构权限
SELECT TypeId INTO #ptype FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID) --商品权限
SELECT TypeId INTO #btype FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)  --结算单位权限
SELECT TypeId INTO #Etype FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID) --职员权限
SELECT TypeId INTO #ktype FROM F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorID)  --仓库权限
SELECT TypeId INTO #dtype FROM  F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorId) --部门权限
 
------------------------------------------------------	出权限和查询内单据#BillIndex  - 开始	-------------------------------------------------
 
DECLARE 
	@SQL VARCHAR(MAX)='',
	@SqlWhere  VARCHAR(MAX)=''
	
CREATE TABLE #BillIndex(BillNumberId NUMERIC(10,0),cname VARCHAR(200),BillType NUMERIC(10,0),RedWord INT,CheckeName VARCHAR(200), Btypeid varchar(max))
		
SET @SQL+='
			INSERT INTO #BillIndex(BillNumberId,cname,BillType,RedWord,CheckeName,Btypeid)
			SELECT
				B.BillNumberId,
				AC.FullName as cname,
				B.BillType,
				B.RedWord,
				C.FullName CheckeName,
				B.Btypeid
			FROM BillIndex B
			'+CHAR(13)

IF NOT (ISNULL(@Stypeid,'') = '' AND @MStypeid = '00000')      	
	SET @SQL+='	INNER JOIN #Stype S ON B.Stypeid=S.TypeID '+CHAR(13)

IF NOT (ISNULL(@DTypeId,'') = '' AND @MDTypeId = '00000')      	
	SET @SQL+='	INNER JOIN #Dtype D ON B.Dtypeid=D.TypeID '+CHAR(13)
	
IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL+='	INNER JOIN #Btype bt ON B.Btypeid=bt.typeid ';

IF ISNULL(@etypeid,'') NOT IN ('','00001') OR @METypeID=-99999 	
	SET @SQL+='	INNER JOIN #Etype E ON B.etypeid=E.TypeID'+CHAR(13)

IF ISNULL(@etypeid,'') NOT IN ('','00001') OR @METypeID=-99999 	
	SET @SQL+='	INNER JOIN #ktype k ON B.ktypeid=k.TypeID'+CHAR(13)

--============ where 查询条件【BEGIN】============================================= 
--SET @SqlWhere+=' AND b.ifYearBill=''0'' ' +CHAR(13)--年节存标志

IF ( ISDATE(RTRIM(@startdate)) = 1 )--查询时间段
	SET @SqlWhere+= ' AND b.BillDate >= ''' + @startdate + ''''+CHAR(13)

IF ( ISDATE(RTRIM(@enddate)) = 1 )
	SET @SqlWhere+= ' AND b.BillDate <= ''' + @enddate + ''''+CHAR(13)

IF @ifini = 0
	SET @SqlWhere+=' AND b.ifcheck=''t'' AND b.draft = 0 AND b.isini = 0'
ELSE
	SET @SqlWhere+=' AND (b.draft = 0 OR b.isini = 1) '
		
SET @SqlWhere +=' AND b.Redword=0'+CHAR(13)

IF(@Comment <> '')--摘要筛选
	SET @SqlWhere+=' AND  b.Comment like ''%' + @Comment + '%'' '+CHAR(13)


--============ where 查询条件【END】============================================= 
		
SET @SQL+='
		INNER JOIN Ac_Currency AC ON AC.CID=B.CID  /*出币种*/
		LEFT JOIN Employee C ON B.Checke=C.TypeID
		WHERE 
			1=1 '+CHAR(13)+@SqlWhere
EXEC(@SQL)
--调试SQL
--PRINT (@SQL)
--SELECT * FROM #BillIndex
------------------------------------------------------	出权限和查询内单据#BillIndex - 结束	-------------------------------------------------
CREATE TABLE [dbo].[#Billtype] (
	[Billtype] varchar(200)
)
INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@billType,',')

 SELECT
					ab.id,
					ab.billnumberid,
					ab.ptypeid as typeid,
					BI.billdate, 
					BN.billname,
					BI.billtype,
 					BI.billcode,
 					B.cname,
 					BI.stypeid,
 					ab.qty,
					ab.total,
					ab.ntotal,
					ab.kqty,
					ab.ktotal,
					ab.Nktotal,
					ab.wqty,
					ab.wtotal,
					ab.nwtotal,
					SysDiy1_head ,
					SysDiy2_head ,
				   SysDiy3_head ,
				   SysDiy4_head ,
				   SysDiy5_head ,
				   SysDiy6_head ,
				   SysDiy7_head ,
				   SysDiy8_head ,
				   SysDiy9_head ,
				   SysDiy10_head ,
				   SysDiy11_head ,
				   SysDiy12_head ,
				   SysDiy13_head ,
				   SysDiy14_head ,
				   SysDiy15_head ,
				   SysDiy16_head,
				   SysDiy1 ,
				   SysDiy2 ,
				   SysDiy3 ,
				   SysDiy4 ,
				   SysDiy5 ,
				   SysDiy6 ,
				   SysDiy7 ,
				   SysDiy8 ,
				   SysDiy9 ,
				   SysDiy10 ,
				   SysDiy11 ,
				   SysDiy12 ,
				   SysDiy13 ,
				   SysDiy14 ,
				   SysDiy15 ,
				   SysDiy16 
   				FROM #BillIndex B
   				INNER JOIN 
   				(
   					SELECT 
   						a.id,
   						a.ptypeid,
   						a.BillNumberID,
   						SUM(a.qty) as qty, /*数量*/
						ISNULL(SUM(a.TaxTotal),0) as total, /*本币金额*/
						ISNULL(SUM(a.NTaxTotal),0) as ntotal, /*原币金额*/
						ISNULL(SUM(a.InvoiceQty),0) as kqty , /*开票数量*/
						ISNULL(SUM(a.InvoiceMoney),0) as ktotal, /*本币开票金额*/
						ISNULL(SUM(a.NInvoiceMoney),0) as Nktotal, /*原币开票金额*/
						ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0) as wqty , /*未开票数量*/
						ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) as wtotal,  /*本币未开票金额(含税)*/
						ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice) ,0) as nwtotal  /*原币未开票金额(含税)*/
   					FROM AppraisalBill a
   					INNER JOIN #PType P ON a.PTypeId = P.TypeId
   					INNER JOIN #ktype	k	ON a.ktypeid=k.typeid   /*明细再过滤哈,避免多仓库出了权限外的数据*/ 
   					GROUP BY
   						a.ptypeid,
   						a.BillNumberID,
   						a.id
   					UNION ALL
   					SELECT 
   						a.id,
   						a.ptypeid,
   						a.BillNumberID,
   						-SUM(a.qty) as qty, /*数量*/
						ISNULL(-SUM(a.TaxTotal),0) as total, /*本币金额*/
						ISNULL(-SUM(a.NTaxTotal),0) as ntotal, /*原币金额*/
						ISNULL(-SUM(a.InvoiceQty),0) as kqty , /*开票数量*/
						ISNULL(-SUM(a.InvoiceMoney),0) as ktotal, /*本币开票金额*/
						ISNULL(-SUM(a.NInvoiceMoney),0) as Nktotal, /*原币开票金额*/
						ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0) as wqty , /*未开票数量*/
						ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) as wtotal,  /*本币未开票金额(含税)*/
						ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice) ,0) as nwtotal  /*原币未开票金额(含税)*/
   					FROM AppraisalBackBill a
   					INNER JOIN #PType P ON a.PTypeId = P.TypeId
   					INNER JOIN #ktype	k	ON a.ktypeid=k.typeid   /*明细再过滤哈,避免多仓库出了权限外的数据*/ 
   					GROUP BY
   						a.ptypeid,
   						a.BillNumberID ,
   						a.id
   				)ab  ON ab.BillNumberID = B.BillNumberID
				INNER JOIN BillIndex BI ON B.BillNumberId=BI.BillNumberId
				INNER JOIN #Billtype t	ON B.Billtype=t.billtype   /*单据类型筛选*/
				INNER JOIN BillName bn on bn.BillType= BI.BillType
				LEFT JOIN Custom_BillIndex ci ON ab.BillNumberId=ci.BillId AND BI.BillType=ci.BillType
				LEFT JOIN Custom_BillDetails cd ON ab.BillNumberId=cd.BillId AND BI.BillType=cd.BillType AND cd.Detailid=ab.Id
			
 			
--删除临时表
DROP TABLE #stype,#ptype,#btype,#Etype,#ktype,#dtype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BuyOrderIndexFromSaleOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BuyOrderIndexFromSaleOrder]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2017-10-22
	描述：采购订单调销售订单	
*/
CREATE       PROCEDURE Web_BuyOrderIndexFromSaleOrder
(
	@OperatorId		varchar(256),
	@BillType		int,
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@ReachDate		varchar(20),
	@SType			varchar(256),
	@KType			varchar(256),
	@BType			varchar(256),
	@EType			varchar(256),
	@BillCode		varchar(256),
	@PType			varchar(256),
	@Explain		varchar(1000),
	@Comment		varchar(1000),
	@OrderState		int,
	@IfAudit		int,
	@IsIni			int=0,					--1为期初单据，0为非期初单据
	@billproperty	int,						--单据属性：0为普通，1为OM，billtype == 300,2为委托，billtype == 301,2为受托
	@cid            VARCHAR(50) = '',
	@areatypeid		VARCHAR(max)='',		--地区（多选,不确定值的大小所以用max）
	@checkEtypeid	VARCHAR(max)='',		--制单人（多选,不确定值的大小所以用max）
	@loadcomplete	int
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @OperatorId
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''


DECLARE @chvBTypeAll char(1)
SET @chvBTypeAll = '0'
SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'

SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)


DECLARE @SQL_ManB varchar(100)
SET @SQL_ManB = ' INNER JOIN #F_BaseGetManDetailBType B ON a.dealbtypeid = B.TypeID '

IF @chvBTypeAll = '0'
BEGIN
	IF @BillType = 300 
		SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND (B.TypeID LIKE ''00001%'') '

	IF @BillType = 301 
		SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND (B.TypeID LIKE ''00002%'') '
END
ELSE
BEGIN
	--IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
		SET @SQL_Man = @SQL_Man + @SQL_ManB
END

-- 职员
SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '

-- 商品
DECLARE @SQL_ManP varchar(100)
SET @SQL_ManP = ''
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
	SET @SQL_ManP = ' INNER JOIN #F_BaseGetManDetailPType P ON detail.PTypeID = P.TypeID '
END

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
END

-- 分支机构
IF @chvMStypeid='-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailSType FROM F_BaseGetManDetailSType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

--部门
IF  @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END

DECLARE @tbName VARCHAR(100)
DECLARE @orderTable VARCHAR(30)
SET @orderTable=' orderbill '
IF @BillType = 300 
	SET @tbName='salebill'
ELSE 
	SET @tbName='buybill'


-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(3000)
SET @SQL = '
	SELECT	a.billtype,
			a.BillNumberID,
			a.BillDate,
			a.ReachDate,
			a.BillCode, 
			a.STypeID, 
			a.ETypeID,			
			a.dealbtypeid AS BTypeID,
			a.KTypeID,
			BI1.Qty,
			BI1.WaitQty,		
			BI1.ReachQty,
			a.Comment,
			a.Explain,
			BI.BID,
			a.CustomerTotal as customertotal,
			CASE WHEN	a.OrderState = 1 THEN ''已完成''
				 WHEN	BI1.ReachQty=0 AND BI.BID IS NULL THEN ''未引用''
				 ELSE ''已引用未完成'' END  AS UseMark,
			ISNULL(a.VipCardId,-1)
	FROM	OrderIndex a ' + @SQL_Man
SET @SQL = @SQL + '
	INNER JOIN (
				SELECT a.BillNumberID,					
							max(a.BID) as BID
				FROM 
				(				
					SELECT distinct detail.BillNumberID,							
						   (BB.orderid) as BID
					FROM	'+@orderTable+' detail 
				LEFT JOIN 
				(
				SELECT bb.OrderID,bb.BillNumberID FROM  (SELECT OrderID,BillNumberId FROM '+@tbName+
				--调组合品订单不需要关联发出、暂估、委托、受托
				CASE @BillType WHEN 313 THEN '' ELSE 
					' UNION ALL '
					--引用状态增加发出商品出库,暂估入库关联
					+CASE @BillType 
					 WHEN 300 THEN 'SELECT OrderId,BillNumberId FROM SendBill ' 
					 ELSE          'SELECT OrderId,BillNumberId FROM AppraisalBill' END
					+' UNION ALL '
					+CASE @BillType 
					 WHEN 300 THEN 'SELECT OrderId,BillNumberId FROM commissionbill where [Type]=140 ' 
					 ELSE          'SELECT OrderId,BillNumberId FROM commissionbill where [Type]=144 ' END
				 END+
				'
				) AS bb  INNER JOIN BillIndex bi ON bb.billnumberid=bi.billnumberid and bi.redword=0--排除红冲单据
				)bb ON detail.OrderID=bb.orderid
				' + @SQL_ManP + ''
--983需求,带商品查询时,需查询未中止,且数量未完成的,已完成不引入
IF @PType <> '' AND @loadcomplete=1
BEGIN
	SET @SQL = @SQL + ' WHERE detail.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where ptypeid = ''' + @PType + '''
				AND BillOver=0 AND ReachQty<QTY)'
END
--未勾选已完成不引入,则不判断完成数量
ELSE IF @PType <> '' AND @loadcomplete=0
BEGIN
	SET @SQL = @SQL + ' WHERE detail.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where ptypeid = ''' + @PType + '''
				AND BillOver=0)'
END

SET @SQL = @SQL + '
				)a GROUP BY A.billNumberID) bi ON A.billNumberId=BI.billNumberID
				INNER JOIN (								
					SELECT B.billNumberID,
							sum(b.WaitQty) AS WaitQty,
							sum(b.Qty) AS Qty,
							sum(b.ReachQty) AS ReachQty 
					FROM(								
							SELECT	detail.BillNumberID,
									(detail.WaitQty) AS WaitQty,
									(detail.Qty) AS Qty,
									(detail.ReachQty) AS ReachQty
							FROM	'+@orderTable+' detail
				) b GROUP BY B.billNumberID) BI1 ON a.billnumberid=BI1.billnumberid 
	
	WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			AND a.Checked = 0 AND a.BillOver = 0
			AND a.BillType = ' + CAST(@BillType AS varchar(10))
IF @IsIni=1
	SET @SQL+=' AND a.IsIni = 1'

IF @cid <> ''
	SET @SQL = @SQL + ' AND a.cid = ''' + @cid + ''''
	
IF @billproperty = 2
	SET @SQL+=' AND a.billproperty = ' + CAST(@billproperty AS varchar(10))
				
IF(@OrderState=4)  --未引用订单	
	SET @SQL+= ' AND BI1.ReachQty=0 AND BI.BID IS NULL '
ELSE	
	SET @SQL+= CASE @OrderState WHEN 1 THEN ' AND (a.OrderState = 0 AND (BI.BID IS NOT NULL OR BI1.ReachQty<>0))' --未完成订单
								WHEN 2 THEN ' AND a.OrderState = 1'  --已完成订单
								WHEN 3 THEN ' AND a.OrderState=0'--未完成订单
								WHEN 4 THEN ' AND BI1.ReachQty=0 AND BI.BID IS NULL'--未引用订单
								ELSE ' AND (a.OrderState = 1 OR a.OrderState = 0)' 
				END
				
IF @BType <> '' SET @SQL = @SQL + ' AND a.dealbtypeid=''' + @BType + ''''
IF @EType <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EType + ''''
IF @KType <> '' SET @SQL = @SQL + ' AND a.KTypeID=''' + @KType + ''''
IF @SType <> '' SET @SQL = @SQL + ' AND a.STypeID=''' + @SType + ''''
IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @Explain <> '' SET @SQL = @SQL + ' AND a.Explain LIKE ''%' + @Explain + '%'''
IF @Comment <> '' SET @SQL = @SQL + ' AND a.Comment LIKE ''%' + @Comment + '%'''
IF @ReachDate <> '' SET @SQL = @SQL + ' AND a.ReachDate = ''' + @ReachDate + ''''
IF @IfAudit = 1 SET @SQL = @SQL + ' AND a.IfAudit = 1'
IF @areatypeid<>''
BEGIN
	SET @SQL = @SQL+' AND a.dealbtypeid IN (SELECT typeid FROM btype WHERE areatypeid in ('''+REPLACE(@areatypeid,',',''',''')+'''))'
END
IF @checkEtypeid<>''
BEGIN
	SET @SQL = @SQL+' AND a.CHECKE IN ('''+REPLACE(@checkEtypeid,',',''',''')+''')'
END
SET @SQL = @SQL + ' ORDER BY a.BillDate DESC,a.BillCode'

--PRINT(@SQL)
EXEC (@SQL)

IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999' DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
DROP TABLE #F_BaseGetManDetailEType
IF @chvMPTypeID = '-99999' DROP TABLE #F_BaseGetManDetailPType
IF @chvMSTypeID = '-99999' DROP TABLE #F_BaseGetManDetailSType
IF @chvMDtypeid = '-99999' DROP TABLE #F_BaseGetManDetailDType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BuyOrderLoadSaleOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BuyOrderLoadSaleOrderBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





/*
	作者：谢吉康
	日期：2017-10-22
	描述：采购订单调销售订单	
*/
CREATE    PROCEDURE Web_BuyOrderLoadSaleOrderBill
(
	@intBillNumberID        varchar(max),
	@loadcomplete			char(1),
	@chvOperatorID          varchar(50),
	@showServicePtype		char(1)='1',--是否显示服务类商品：0，不显示；1，显示
	@billtype				int=300
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''
DECLARE @SQL_ManKtype varchar(1000)
SET @SQL_ManKtype=''
-- 商品
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
	SET @SQL_Man = ' INNER JOIN #F_BaseGetManDetailPType FP ON a.PTypeID = FP.TypeID '
END

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (a.KtypeID=K.TypeID OR ISNULL(a.KtypeID,'''')='''') '
END
-- ******** 权限范围单独处理 - End ********
DECLARE @detailTable varchar(30)
SET @detailTable='OrderBill'
DECLARE @SQL nvarchar(2000)
SET @SQL = '
	SELECT  a.KTypeid,
			a.PTypeID,
			a.Qty,
			a.Qty-a.ReachQty AS wwcQty,
			a.WaitQty AS waitqtydetail,
			a.OrderID,
			a.BillNumberID,
			b.btypeid,
			b.dealbtypeid,
			p.isservice,
			a.comment,
			CASE WHEN a.isgift=0 THEN '' '' ELSE ''赠品'' END AS isgift,
			CASE WHEN a.IsCombined = 0  THEN (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END AS itemname,'

SET @SQL = @SQL + ''''' AS pindexid '

SET @SQL = @SQL + '
	FROM	'+@detailTable+' a 
	INNER JOIN Ptype p on a.ptypeid=p.typeid 
	INNER JOIN OrderIndex b ON a.billnumberid=b.billnumberid ' + @SQL_Man + '
	WHERE a.BillNumberID IN (SELECT * FROM DBO.F_Split(''' + @intBillNumberID + ''','','') WHERE ISNULL(A,'''') <> '''')
	AND a.BillOver=0 '

IF @loadcomplete = '1'
	SET @SQL = @SQL +'
			AND a.Qty-a.ReachQty >0 '

IF @showServicePtype='0'
	SET @SQL=@SQL+' AND p.isservice=0'

SET @SQL = @SQL +'
	ORDER BY ShowOrder ASC'

--PRINT(@SQL)
--EXEC (@SQL)

exec sp_executesql @SQL,N'@intBillNumberID varchar(max)',@intBillNumberID

IF @chvMPTypeID = '-99999' DROP TABLE #F_BaseGetManDetailPType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BuyPTypeMonthReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BuyPTypeMonthReport]
GO


/*
	作者：谢吉康
	日期：2009-01-08
	描述：商品采购月分析
*/

/*
	作者：彭勇	
	日期：2012-06-12
	描述：多单位转换，计量单位
*/

/*
	修改: 魏伟
	日期: 2015-05-24
	描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
*/
CREATE     PROCEDURE Web_BuyPTypeMonthReport
(
	@OperatorID	varchar(100),
	@StartDate	varchar(20),
	@EndDate	varchar(20),
	@dealBTypeId	VARCHAR(max),--结算单位
	@deal_btypeid	VARCHAR(max),--往来单位
	@PTypeId	varchar(8000),
	@ETypeId	varchar(8000),
	@DTypeId	varchar(8000),
	@KTypeId	varchar(8000),
	@StypeId	varchar(8000),
	@BillType	varchar(100),
	@Flag		varchar(100),  	--ZH.折后  SH.税后
	@mPageNo	int=1,
	@mSize		int=12,
	@IsPrint	int=0,
	@bPageNo	int=1,
	@bSize		int=14,
	@unitconvert    varchar(10),    --多单位计算
	@ptypecategoryid    VARCHAR(MAX)    --商品类别ID

)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype1 (TypeID varchar(50),UserCode varchar(200),FullName varchar(200))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #deal_btype(typeid VARCHAR(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))


--商品
INSERT INTO #Ptype1(typeid,UserCode,FullName) 
	SELECT P.typeid,usercode,fullname 
	from ptype P,F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) W 
	WHERE P.typeid=W.typeid
	
--结算单位    
INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@dealBTypeId,2,@OperatorID)
--往来单位  
INSERT INTO #deal_btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@deal_btypeid,2,@OperatorID)

--职员
INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@EtypeID,3,@OperatorID)
--仓库
INSERT INTO #Ktype(typeid) select typeid from F_GetAllManagerBaseTypeId(@KTypeID,4,@OperatorID)

IF @KTypeID=''
BEGIN
    INSERT INTO #Ktype VALUES('10000')
END
--部门
IF @DtypeID=''
BEGIN
	INSERT INTO #dtype(typeid) select typeid from F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)
	INSERT INTO #Dtype VALUES( '')
END
ELSE
    INSERT INTO #Dtype(typeid) select typeid from F_GetAllManagerBaseTypeId(@DtypeID,9,@OperatorID)
    
--分支机构
INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID)

DECLARE @intBegin	int,
		@intEnd		int,
		@intBMonth	int,
		@intEMonth	int,
		@i			int

SET @intBegin = LEFT(@StartDate,4)+1
SET @intEnd   = LEFT(@EndDate,4)

SET @intBMonth = Month(@StartDate)
SET @intEMonth = Month(@EndDate)

CREATE TABLE #dDate
(
	nID			int identity(1,1),
	FullName	varchar(100),
	StartDate	datetime,
	EndDate		datetime
)
--开始年份处理
IF  @intBegin-1<@intEnd
	BEGIN
		IF (@intBegin-1) % 4 = 0
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
		ELSE
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
	END

--中间年份数据处理
WHILE @intBegin<@intEnd
	BEGIN
		SET @i = 1
		WHILE @i<=12
			BEGIN
				IF @i = 1
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年01月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-31' as varchar(100)))
				ELSE IF @i = 2
					BEGIN
						IF @intBegin % 4 = 0
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-29' as varchar(100)))
						ELSE
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-28' as varchar(100)))
					END
				ELSE IF @i = 3
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年03月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-31' as varchar(100)))
				ELSE IF @i = 4
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年04月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-30' as varchar(100)))
				ELSE IF @i = 5
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年05月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-31' as varchar(100)))
				ELSE IF @i = 6
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年06月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-30' as varchar(100)))
				ELSE IF @i = 7
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年07月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-31' as varchar(100)))
				ELSE IF @i = 8
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年08月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-31' as varchar(100)))
				ELSE IF @i = 9
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年09月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-30' as varchar(100)))
				ELSE IF @i = 10
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年10月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-31' as varchar(100)))
				ELSE IF @i = 11
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年11月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-30' as varchar(100)))
				ELSE IF @i = 12
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年12月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-31' as varchar(100)))
				SET @i = @i + 1
			END

		SET @intBegin = @intBegin + 1
	END

--最后数据处理
IF @intBegin-1=@intEnd
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END
ELSE
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END


--处理开始日期和截止日期
DECLARE @nID		int,
		@rCount		int

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate ASC
UPDATE #dDate SET StartDate = @StartDate WHERE nID = @nID

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate DESC
UPDATE #dDate SET EndDate = @EndDate WHERE nID = @nID

SELECT @rCount = COUNT(*) FROM #dDate

--最后得到日期列表
DECLARE @TableHeadName 	varchar(200),
		@TableBodyName	varchar(200),
		@SQL 			varchar(8000)
SELECT 	@TableHeadName='WebDate'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableHeadName+'
	(
		nID			int identity(1,1),
		FullName	varchar(100),
		StartDate	datetime,
		EndDate		datetime
	)
	INSERT INTO '+N'##'+@TableHeadName+'(FullName,StartDate,EndDate)
	SELECT 	FullName,
			StartDate,
			EndDate 
	FROM 	#dDate 
	ORDER BY StartDate ASC'

EXEC(@SQL)

--过滤商品信息
CREATE TABLE #PType
(
	TypeID		varchar(100),
	UserCode	varchar(200),
	FullName	varchar(200)
)
IF @IsPrint = 0
	INSERT INTO #PType(TypeId,UserCode,FullName)
	SELECT	TypeId,UserCode,FullName
	FROM	#PType1
	ORDER BY UserCode
ELSE
	BEGIN
		SET @SQL =' INSERT INTO #PType(TypeId,UserCode,FullName)
					SELECT	TOP '+CAST(@bSize AS varchar(50))+' TypeId,UserCode,FullName
					FROM	#PType1
					WHERE	UserCode NOT IN (
								SELECT	TOP ' + CAST((@bPageNo-1) * @bSize AS varchar(50)) + ' UserCode
								FROM	#PType1
								ORDER BY UserCode										
							)
					ORDER BY UserCode '
		EXEC(@SQL)
	END

DECLARE @ColName varchar(4000)
SET @ColName ='typeid,usercode,fullname,[总计数量],[总计金额]'

--得到表体数据列表
SELECT 	@TableBodyName='WebBody'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableBodyName+'
	(
		TypeId			varchar(100),
		SonNum			varchar(max),
		单位关系		varchar(max),
		单位			varchar(max),
		大单位			varchar(max),
		关系			varchar(100),
		UserCode 		varchar (200) NULL ,
		FullName 		varchar (256) NOT NULL,
		计量单位        varchar(200), 
		总计数量		 NUMERIC(24, 10) ,
		总计浮动数量	 NUMERIC(24, 10) ,
		总计金额		 NUMERIC(24, 10) 
	)
	INSERT INTO '+N'##'+@TableBodyName+'
	(
		TypeId,
		SonNum,
		单位关系,
		单位,
		大单位,
		关系,
		UserCode,
		FullName,
		计量单位,
		总计数量,
		总计浮动数量,
		总计金额
	)
	SELECT	P.TypeId,
			P.SonNum,
			CASE
				WHEN P.Unit1<>'''' AND P.Unit2<>'''' AND P.UnitRate1<>0 THEN ''有关系''
				ELSE ''''
			END,
			P.Unit1,
			P.Unit2,
			CAST(P.UnitRate1 AS VARCHAR(100)),
			P.UserCode,
			P.FullName,
			null,
			0,
			0,
			0
	FROM	PType P
	INNER JOIN #PType ON #PType.TypeId = P.TypeId '
EXEC(@SQL)


----------------------------------------------
    CREATE TABLE #BillName ( Billtype INT )
    INSERT  INTO #BillName
            SELECT  A
            FROM    DBO.f_split(@BillType, ',')


    CREATE TABLE #Billnum
        (
           BillNumberID          NUMERIC(24, 10) ,
		   billtype             INT,
           BillDate				DATETIME,
           dealBTypeId			varchar(50),
           btypeid				varchar(50),
           EtypeID				varchar(50),
           DtypeID				varchar(50)
        )
       
    CREATE TABLE #BillDetails
        (
          PTypeId		VARCHAR(50),
          BillDate		DATETIME ,
          Qty			 NUMERIC(24, 10) ,
          NQty			 NUMERIC(24, 10)  ,
          Total			 NUMERIC(24, 10) ,
          dealBTypeId	varchar(50),
          btypeid		varchar(50),
          EtypeID		varchar(50),
          DtypeID		varchar(50),
          KtypeID		varchar(50),
          jlfullname	VARCHAR(200)
        )    


	DECLARE @tempqty    NVARCHAR(2000),
		@temptable  NVARCHAR(2000),
			@tempunit   NVARCHAR(2000)
--	SET @temptable=' INNER JOIN  F_GetManPTypeDetailALL('''+@OperatorId+''') c ON a.PtypeID=c.typeID'
	IF @unitconvert=0
	BEGIN
	SELECT @temptable =dbo.F_GetPtypeUnitsAndRates('p1','1,3','3'),
		@tempqty='a.qty/isnull(r3.rate,1)',
		@tempunit='u3.fullname'
	END
	IF @unitconvert=1
	BEGIN
	SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,2','2'),
		@tempqty='a.qty/isnull(r2.rate,1)',
		@tempunit='u2.fullname'
	END
	IF @unitconvert=2
	BEGIN
	SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,4','4'),
		@tempqty='a.qty/isnull(r4.rate,1)',
		@tempunit='u4.fullname'
	END
	IF @unitconvert=3
	BEGIN
	SELECT @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1','1'),
		@tempqty='a.qty',
		@tempunit='u1.fullname'
	END


SET @sql ='INSERT INTO #Billnum 
					 SELECT BillNumberId,BillType,BillDate,dealBTypeId,btypeid,EtypeID,DtypeID
					 FROM BillIndex bil'  
IF @STypeId <> '' or @MStypeid<>'00000'	
      SET @SQL = @SQL+ ' INNER JOIN #Stype S ON bil.stypeID =S.typeid  '

SET @SQL = @SQL+ ' WHERE	Bil.BillDate>='+char(39)+@StartDate+char(39)+'
						AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					    AND Bil.BillType IN ('+@BillType+')
						AND Bil.IfCheck = ''t''
						AND Bil.RedWord = 0
						AND Bil.Draft = 0		
						AND Bil.ifYearBill=0	 --年节存标志'	

    EXEC (@sql) 
    
SET @sql = '  
 IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 34)
	INSERT INTO #BillDetails
	SELECT a.PTypeId,b.BillDate,SUM('+@tempqty+') as Qty,SUM(a.nQty) as nQty,
	SUM(
		CASE
			WHEN  '+char(39)+@Flag+char(39)+'=''SH'' THEN a.TaxTotal
			WHEN  '+char(39)+@Flag+char(39)+'=''ZH'' THEN a.Total
			ELSE 0	END
		) as total,dealBTypeId,btypeid,EtypeID,DtypeID,a.KtypeID,'+@tempunit+'
	FROM Buybill A
	INNER JOIN #BillNum b
	ON A.BillNumberId=B.BillNumberID
	inner join ptype p1 on a.ptypeid=  p1.typeid
	' +@temptable+ '
	WHERE B.BillType = 34
	GROUP BY a.PTypeId,B.BillDate,dealBTypeId,EtypeID,btypeid,DtypeID,a.KtypeID,'+@tempunit
	EXEC (@sql)
		
 SET @sql = ' 
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 6)
	INSERT INTO #BillDetails
	SELECT a.PTypeId,b.BillDate,-SUM('+@tempqty+') as Qty,-SUM(a.nQty) as nQty,
	-SUM(
		CASE
			WHEN '+char(39)+@Flag+char(39)+'=''SH'' THEN A.TaxTotal
			WHEN '+char(39)+@Flag+char(39)+'=''ZH'' THEN A.Total
			ELSE 0  END
		) AS TOTAL,dealBTypeId,btypeid,EtypeID,DtypeID,a.KtypeID,'+@tempunit+'
	FROM buybackbill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
	inner join ptype p1 on a.ptypeid=  p1.typeid
	' +@temptable+ '
	WHERE B.BillType = 6
	GROUP BY a.PTypeId,B.BillDate,dealBTypeId,btypeid,EtypeID,DtypeID,a.KtypeID,'+@tempunit
	EXEC (@sql)

 SET @SQL = '
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 161)
	INSERT INTO #BillDetails
	SELECT a.PTypeId,b.BillDate,
	SUM(
		CASE WHEN a.InOrOut=''O'' THEN -'+@tempqty+'
			 ELSE '+@tempqty+' END
		) AS QTY,
	SUM(
		CASE WHEN a.InOrOut=''O'' THEN -a.nqty
			 ELSE a.nqty END
		) AS nQTY,		
	SUM(
		CASE
			WHEN a.InOrOut=''I'' AND '+char(39)+@Flag+char(39)+'=''SH'' THEN a.TaxTotal
			WHEN a.InOrOut=''I'' AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN a.Total
			WHEN a.InOrOut=''O'' AND '+char(39)+@Flag+char(39)+'=''SH'' THEN -a.TaxTotal
			WHEN a.InOrOut=''O'' AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN -a.TotaL
			ELSE 0	END
		) as total,dealBTypeId,btypeid,EtypeID,DtypeID,a.KtypeID,'+@tempunit+' 
	FROM buygoodsexchangebill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
	inner join ptype p1 on a.ptypeid=  p1.typeid
	' +@temptable+ '
	WHERE B.BillType = 161
	GROUP BY a.PTypeId,B.BillDate,dealBTypeId,btypeid,EtypeID,DtypeID,a.KtypeID,'+@tempunit
	EXEC (@sql)
	--PRINT(@SQL)
		
SET @SQL = '
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 145)
	INSERT INTO #BillDetails
	SELECT a.PTypeId,b.BillDate,SUM('+@tempqty+') as Qty,SUM(a.nQty) as nQty,
	SUM(
			CASE WHEN '+char(39)+@Flag+char(39)+'=''SH'' THEN a.TaxTotal
				 WHEN '+char(39)+@Flag+char(39)+'=''ZH'' THEN a.Total
				 ELSE 0	END
		) AS total,dealBTypeId,btypeid,EtypeID,DtypeID,10000,'+@tempunit+'
	FROM commissionbill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
		inner join ptype p1 on a.ptypeid=  p1.typeid
	' +@temptable+ '
	WHERE a.Type=''145'' AND B.BillType = 145
	GROUP BY a.PTypeId,B.BillDate,dealBTypeId,btypeid,EtypeID,DtypeID,a.KtypeID,'+@tempunit
	EXEC (@sql)    


--更新数据源
CREATE TABLE #InOutStockTable
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	nqty         NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	jlfullname  VARCHAR(200)
)



SET @SQL = 'INSERT INTO #InOutStockTable
		(
			PTypeId,
			BillDate,
			Qty,
			nqty,
			Total,
			jlfullname		
		)  
        SELECT	i.PTypeId,
				i.BillDate,
				i.Qty,
				i.nQty,
				i.Total,
				i.jlfullname
				
		FROM	#BillDetails I '

IF NOT (@PTypeId ='' AND @MPtypeid = '00000' AND @ptypecategoryid='')
      SET @SQL = @SQL+ ' INNER JOIN #PType P ON I.PTypeId = P.TypeId '

IF NOT (@dealBTypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
      SET @SQL = @SQL+ ' INNER JOIN #Btype b ON i.btypeid=b.typeid '
IF NOT (@deal_BTypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
      SET @SQL = @SQL+ ' INNER JOIN #deal_btype bb ON i.dealbtypeid=bb.typeid '
IF NOT (@ETypeId = '' AND @METypeId = '00001')
      SET @SQL = @SQL+ ' INNER JOIN #Etype e ON i.etypeid=e.typeid '

IF NOT (@KTypeId = '' AND @MKTypeId = '00001')
      SET @SQL = @SQL+ ' INNER JOIN #Ktype k ON I.KtypeID=k.typeid '

IF NOT (@DTypeId = '' AND @MDtypeid='00000')	
      SET @SQL = @SQL+ ' INNER JOIN #Dtype d ON i.DtypeID =d.typeid  '


EXEC(@SQL)  --select * from #InOutStockTable return 


--更新总计数据
SET @SQL = '
	UPDATE	'+N'##'+@TableBodyName+'
	SET		总计数量 = ISNULL(B.Qty,0),
	        计量单位=b.jlfullname,  
			总计浮动数量 =isnull(b.nqty,0),
			总计金额 = ISNULL(B.Total,0)
	FROM	'+N'##'+@TableBodyName+' A
	LEFT JOIN (
		SELECT	PTypeId,
				SUM(Qty) AS Qty,
				SUM(nqty) AS nqty,
				SUM(Total) AS Total,
				jlfullname
		FROM	#InOutStockTable
		GROUP BY PTypeId,jlfullname
	)B ON A.TypeId = B.PTypeId'
EXEC(@SQL)

--更新数据源
CREATE TABLE #InOutStockTableMx
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	nqty        NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) 
)

--更新明细数据
DECLARE @sBdate datetime,
		@sEdate datetime

EXEC Web_GetTwoDateMonth @StartDate,@EndDate,@mPageNo,0,@sBdate OUTPUT,@sEdate OUTPUT

IF ISNULL(@sEdate,'')='' OR ISNULL(@sEdate,'') = '1900-01-01' OR ISNULL(@sEdate,'')='1900-1-1'
	SET @sEDate = @EndDate

IF @IsPrint = 0
	INSERT INTO #InOutStockTableMx SELECT PTypeId,BillDate,Qty,nqty,Total FROM #InOutStockTable WHERE BillDate>=@sBdate AND BillDate<=@sEdate
ELSE
	INSERT INTO #InOutStockTableMx SELECT PTypeId,BillDate,Qty,nqty,Total FROM #InOutStockTable WHERE BillDate>=@StartDate AND BillDate<=@EndDate


--更新数量，金额数据
DECLARE @FullName 	varchar(100),
		@sDate		datetime,
		@eDate		datetime

SET @SQL = '
	DECLARE MxCursor CURSOR FOR
		SELECT 	FullName,
				StartDate,
				EndDate 
		FROM 	'+N'##'+@TableHeadName+'
		WHERE	nID>'+CAST((@mPageNo-1)*@mSize as varchar(100))+'
				AND nID<='+CAST(@mPageNo*@mSize as varchar(100))
EXEC(@SQL)
OPEN MxCursor
FETCH NEXT FROM MxCursor INTO @FullName,@sDate,@eDate
WHILE @@FETCH_STATUS=0
	BEGIN
		EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '数量]  NUMERIC(24, 10) ')
		EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '浮动数量]  NUMERIC(24, 10) ')
		EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '金额]  NUMERIC(24, 10) ')
		SET @ColName = @ColName +',Case when ['+ @FullName + '数量] =0 then null else ['+ @FullName + '数量] end as ['+ @FullName + '数量]'
		SET @ColName = @ColName +',Case when ['+ @FullName + '浮动数量] =0 then null else ['+ @FullName + '浮动数量] end as ['+ @FullName + '浮动数量]'
		SET @ColName = @ColName +',Case when ['+ @FullName + '金额] =0 then null else ['+ @FullName + '金额] end as ['+ @FullName + '金额]'
		SET @SQL = '
			UPDATE	'+N'##'+@TableBodyName+'
			SET		['+@FullName+'数量] = ISNULL(B.Qty,0),
					['+@FullName+'浮动数量] = ISNULL(b.nqty,0),
					['+@FullName+'金额] = ISNULL(B.Total,0)
			FROM	'+N'##'+@TableBodyName+' A
			LEFT JOIN (
				SELECT	PTypeId,
						SUM(Qty) AS Qty,
						SUM(nqty)AS nqty,
						SUM(Total) AS Total
				FROM	#InOutStockTableMx
				WHERE	BillDate>='+char(39)+CONVERT(varchar(10),@sDate,120)+char(39)+'
						AND BillDate<='+char(39)+CONVERT(varchar(10),@eDate,120)+char(39)+'
				GROUP BY PTypeId
			)B ON A.TypeId = B.PTypeId'
		EXEC(@SQL)
		FETCH NEXT FROM MxCursor INTO @FullName,@sDate,@eDate
	END
CLOSE MxCursor
DEALLOCATE MxCursor
 
IF @IsPrint=1 --全部打印
	EXEC('SELECT * FROM '+N'##'+@TableBodyName+' WHERE [总计数量]<>0 OR [总计金额]<>0 ORDER BY UserCode')
ELSE
	EXEC('SELECT * FROM '+N'##'+@TableBodyName+' WHERE [总计数量]<>0 OR [总计金额]<>0 ORDER BY UserCode')

--删除临时表
EXEC('DROP TABLE #dDate,#Billnum,#billname,#BillDetails,#InOutStockTable,#InOutStockTableMx,#PType,#btype,#Etype,#Ktype,#Ptype1,#Dtype,#Stype,'+N'##'+@TableHeadName+','+N'##'+@TableBodyName)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BuyPTypeMonthReportChart]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BuyPTypeMonthReportChart]
GO









/*
	作者：谢吉康
	日期：2009-01-08
	描述：商品采购月分析
	
	修改：舒珊
    日期：2016-06-06
    描述： 添加商品类别筛选
*/
CREATE     PROCEDURE Web_BuyPTypeMonthReportChart
(
	@OperatorID	varchar(100),
	@StartDate	varchar(20),
	@EndDate	varchar(20),
	@dealBTypeId	varchar(8000),
	@PTypeId	varchar(8000),
	@ETypeId	varchar(8000),
	@DTypeId	varchar(8000),
	@KTypeId	varchar(8000),
	@STypeId	varchar(8000),
	@BillType	varchar(100),
	@Flag		varchar(100),  	--ZH.折后  SH.税后
	@mPageNo	int=1,
	@mSize		int=12,
	@IsPrint	int=0,
	@bPageNo	int=1,
	@bSize		int=14,
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ptype (TypeID varchar(50),UserCode varchar(200),FullName varchar(200))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))

IF @PTypeID =''
	INSERT INTO #Ptype(typeid,UserCode,FullName) select typeid,usercode,fullname from ptype where typeid in ( select typeid from dbo.F_LinePC(@OperatorID,@ptypecategoryid))
ELSE
	INSERT INTO #Ptype(typeid,UserCode,FullName) select typeid,usercode,fullname from ptype where typeid in ( select a.typeid from dbo.F_ManPTypeInCategoryID ( @OperatorID,@PTypeId,@ptypecategoryid)  a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a)


IF @dealBtypeID =''
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@dealBtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @ETypeID=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@EtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @KTypeID=''
BEGIN
	INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorID)
	insert into #Ktype select '10000'
END
ELSE
	INSERT INTO #Ktype select a.typeid from F_GetManDetailKType(@OperatorID) a,  (select * from  dbo.f_split(@KtypeID,',')) b where left(a.typeid,len(b.a))=b.a

	
INSERT INTO #Dtype(typeid) select typeid from F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)
IF @DtypeID=''
	INSERT INTO #Dtype SELECT ''


INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

DECLARE @intBegin	int,
		@intEnd		int,
		@intBMonth	int,
		@intEMonth	int,
		@i			int,
		@pName		varchar(100)

SELECT @pName = FullName FROM PType WHERE TypeId = @PTypeId AND SonNum = 0 AND Deleted = 0

SET @intBegin = LEFT(@StartDate,4)+1
SET @intEnd   = LEFT(@EndDate,4)

--SET @intBMonth = SUBSTRING(@StartDate,6,2)
--SET @intEMonth = SUBSTRING(@EndDate,6,2)

SET @intBMonth = Month(@StartDate)--SUBSTRING(@StartDate,6,2)
SET @intEMonth = Month(@EndDate)--SUBSTRING(@EndDate,6,2)

CREATE TABLE #dDate
(
	nID			int identity(1,1),
	FullName	varchar(100),
	StartDate	datetime,
	EndDate		datetime
)
--开始年份处理
IF  @intBegin-1<@intEnd
	BEGIN
		IF (@intBegin-1) % 4 = 0
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
		ELSE

			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
	END

--中间年份数据处理
WHILE @intBegin<@intEnd
	BEGIN
		SET @i = 1
		WHILE @i<=12
			BEGIN
				IF @i = 1
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年01月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-31' as varchar(100)))
				ELSE IF @i = 2
					BEGIN
						IF @intBegin % 4 = 0
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-29' as varchar(100)))
						ELSE
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-28' as varchar(100)))
					END
				ELSE IF @i = 3
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年03月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-31' as varchar(100)))
				ELSE IF @i = 4
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年04月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-30' as varchar(100)))
				ELSE IF @i = 5
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年05月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-31' as varchar(100)))
				ELSE IF @i = 6
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年06月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-30' as varchar(100)))

				ELSE IF @i = 7
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年07月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-31' as varchar(100)))
				ELSE IF @i = 8
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年08月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-31' as varchar(100)))
				ELSE IF @i = 9
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年09月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-30' as varchar(100)))
				ELSE IF @i = 10
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年10月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-31' as varchar(100)))
				ELSE IF @i = 11
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年11月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-30' as varchar(100)))
				ELSE IF @i = 12
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年12月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-31' as varchar(100)))
				SET @i = @i + 1
			END

		SET @intBegin = @intBegin + 1
	END

--最后数据处理
IF @intBegin-1=@intEnd
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END
ELSE
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END

--处理开始日期和截止日期
DECLARE @nID		int,
		@rCount		int

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate ASC
UPDATE #dDate SET StartDate = @StartDate WHERE nID = @nID

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate DESC
UPDATE #dDate SET EndDate = @EndDate WHERE nID = @nID

SELECT @rCount = COUNT(*) FROM #dDate

--最后得到日期列表
DECLARE @TableHeadName 	varchar(200),
		@TableBodyName	varchar(200),
		@SQL 			varchar(8000)
SELECT 	@TableHeadName='WebDate'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableHeadName+'
	(
		nID			int identity(1,1),
		FullName	varchar(100),
		StartDate	datetime,
		EndDate		datetime
	)
	INSERT INTO '+N'##'+@TableHeadName+'(FullName,StartDate,EndDate)
	SELECT 	FullName,
			StartDate,
			EndDate 
	FROM 	#dDate 
	ORDER BY StartDate ASC'

EXEC(@SQL)


--得到表体数据列表
SELECT 	@TableBodyName='WebBody'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableBodyName+'
	(
		QueryTime 		varchar (256) NOT NULL,
		FullName		varchar(100),
		sum_qty			 NUMERIC(24, 10) 
	)'
EXEC(@SQL)

--更新数据源
CREATE TABLE #InOutStockTable
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) 
)

SET @SQL = 'INSERT INTO #InOutStockTable
		(
			PTypeId,
			BillDate,
			Qty,
			Total
		)
		SELECT	B.PTypeId,
				B.BillDate,
				ISNULL(SUM(B.Qty),0) AS Qty,
				ISNULL(CAST(SUM(B.Total) AS  NUMERIC(24, 10) ),0) AS Total
		FROM	(	
				SELECT	I.PTypeId,
						I.BillDate,
						CASE
							WHEN Bil.BillType IN (34,161) THEN I.Qty
							WHEN Bil.BillType = 157 AND I.Qty>0 THEN I.Qty
							WHEN Bil.BillType = 157 AND I.Qty<0 THEN 0
							WHEN Bil.BillType = 145 THEN -1*I.Qty
							ELSE I.Qty
						END AS Qty,
						CASE
							WHEN Bil.BillType IN (34,161) AND '+char(39)+@Flag+char(39)+'=''SH'' THEN CAST(I.TaxTotal as  NUMERIC(24, 10) )
							WHEN Bil.BillType IN (157) AND I.Qty>0 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN CAST(I.TaxTotal as  NUMERIC(24, 10) )
							WHEN Bil.BillType IN (157) AND I.Qty<0 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN 0
							WHEN Bil.BillType IN (145) AND '+char(39)+@Flag+char(39)+'=''SH'' THEN CAST(-1*I.TaxTotal as  NUMERIC(24, 10) )
							WHEN Bil.BillType = 6 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN CAST(I.TaxTotal as  NUMERIC(24, 10) )
							WHEN Bil.BillType IN (34,161) AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							WHEN Bil.BillType IN (157) AND I.Qty>0 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							WHEN Bil.BillType IN (157) AND I.Qty<0 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN 0
							WHEN Bil.BillType IN (145) AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN -1*I.Total
							WHEN Bil.BillType = 6 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							ELSE 0					
						END AS Total
				FROM	BillIndex Bil,
						InOutStockTable I,
						#PType P,#Btype b,#Etype e,#Ktype k,#Dtype d,#stype s
				WHERE	Bil.BillNumberId = I.BillNumberId
						AND I.PTypeId = P.TypeId
						AND Bil.dealBtypeID=b.typeid
						AND Bil.EtypeID =e.typeid
						AND I.KtypeID=k.typeid
						AND	i.stypeid=s.typeid
						AND Bil.DtypeID=d.typeid
						AND Bil.BillType IN ('+@BillType+')
						AND Bil.IfCheck = ''t''
						AND Bil.RedWord = 0
						AND Bil.Draft = 0									
						AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
						AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
						AND Bil.ifYearBill=0	 --年节存标志
		)B GROUP BY B.PTypeId,B.BillDate'

--PRINT(@SQL)
EXEC(@SQL)

--更新数据源
CREATE TABLE #InOutStockTableMx
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) 
)

--更新明细数据
DECLARE @sBdate datetime,
		@sEdate datetime

EXEC Web_GetTwoDateMonth @StartDate,@EndDate,@mPageNo,0,@sBdate OUTPUT,@sEdate OUTPUT

IF ISNULL(@sEdate,'')='' OR ISNULL(@sEdate,'') = '1900-01-01' OR ISNULL(@sEdate,'')='1900-1-1'
	SET @sEDate = @EndDate

IF @IsPrint = 0
	INSERT INTO #InOutStockTableMx SELECT PTypeId,BillDate,Qty,Total FROM #InOutStockTable WHERE BillDate>=@sBdate AND BillDate<=@sEdate
ELSE
	INSERT INTO #InOutStockTableMx SELECT PTypeId,BillDate,Qty,Total FROM #InOutStockTable WHERE BillDate>=@StartDate AND BillDate<=@EndDate

--更新数量，金额数据
DECLARE @FullName 	varchar(100),
		@sDate		datetime,
		@eDate		datetime,
		@numQty		 NUMERIC(24, 10) ,
		@numTotal	 NUMERIC(24, 10) 

SET @SQL = '
	DECLARE MxCursor CURSOR FOR
		SELECT 	FullName,
				StartDate,
				EndDate 
		FROM 	'+N'##'+@TableHeadName+'
		WHERE	nID>'+CAST((@mPageNo-1)*@mSize as varchar(100))+'
				AND nID<='+CAST(@mPageNo*@mSize as varchar(100))
EXEC(@SQL)
OPEN MxCursor
FETCH NEXT FROM MxCursor INTO @FullName,@sDate,@eDate
WHILE @@FETCH_STATUS=0
	BEGIN
		SELECT	@numQty = ISNULL(SUM(Qty),0),@numTotal = ISNULL(SUM(Total),0) FROM #InOutStockTableMx WHERE BillDate>=@sDate AND BillDate<=@eDate

		SET @SQL = 'INSERT INTO '+N'##'+@TableBodyName+'(QueryTime,sum_qty,FullName)VALUES('+char(39)+CAST(Right(@FullName,LEN(@FullName)-2) AS varchar(100))+char(39)+','+CAST(@numQty as varchar(100))+',''数量'')'
		EXEC(@SQL)
		SET @SQL = 'INSERT INTO '+N'##'+@TableBodyName+'(QueryTime,sum_qty,FullName)VALUES('+char(39)+CAST(Right(@FullName,LEN(@FullName)-2) AS varchar(100))+char(39)+','+CAST(@numTotal as varchar(100))+',''金额'')'
		EXEC(@SQL)

		FETCH NEXT FROM MxCursor INTO @FullName,@sDate,@eDate
	END
CLOSE MxCursor
DEALLOCATE MxCursor

DECLARE	@re_Limit  int
--成本查看权限
EXEC @re_Limit=GP_CheckLimit @OperatorID,166
IF @re_Limit = 0
	EXEC('SELECT * FROM '+N'##'+@TableBodyName+'')
ELSE
	EXEC('SELECT * FROM '+N'##'+@TableBodyName+' WHERE FullName=''数量''')

--删除临时表
EXEC('DROP TABLE #dDate,#InOutStockTable,#InOutStockTableMx,#PType,#Btype,#Etype,#Ktype,#Dtype,#stype,'+N'##'+@TableHeadName+','+N'##'+@TableBodyName)









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BuyPTypeMonthReportPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_BuyPTypeMonthReportPrint]
GO


























/*
	作者：谢吉康
	日期：2009-01-08
	描述：商品采购月分析
*/
CREATE  PROCEDURE Web_BuyPTypeMonthReportPrint
(
	@OperatorID	varchar(100),
	@StartDate	varchar(20),
	@EndDate	varchar(20),
	@BTypeId	varchar(100),
	@PTypeId	varchar(100),
	@ETypeId	varchar(100),
	@DTypeId	varchar(100),
	@KTypeId	varchar(100),
	@BillType	varchar(100),
	@Flag		varchar(100),  	--ZH.折后  SH.税后
	@mPageNo	int=1,
	@mSize		int=12,
	@IsPrint	int=0,
	@bPageNo	int=1,
	@bSize		int=14
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------
IF @BTypeId = '00000'
	SET @BTypeId = '%'
IF @PTypeId = '00000'
	SET @PTypeId = '%'
IF @KTypeId = '00000'
	SET @KTypeId = '%'
IF @DTypeId = '00000'
	SET @DTypeId = '%'

DECLARE @intBegin	int,
		@intEnd		int,
		@intBMonth	int,
		@intEMonth	int,
		@i			int,
		@re_Limit  int

--成本查看权限
EXEC @re_Limit=GP_CheckLimit @OperatorID,166

SET @intBegin = LEFT(@StartDate,4)+1
SET @intEnd   = LEFT(@EndDate,4)

SET @intBMonth = SUBSTRING(@StartDate,6,2)
SET @intEMonth = SUBSTRING(@EndDate,6,2)

CREATE TABLE #dDate
(
	nID			int identity(1,1),
	FullName	varchar(100),
	StartDate	datetime,
	EndDate		datetime
)
--开始年份处理
IF  @intBegin-1<@intEnd
	BEGIN
		IF (@intBegin-1) % 4 = 0
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
		ELSE
			WHILE @intBMonth<=12
				BEGIN

					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
	END

--中间年份数据处理
WHILE @intBegin<@intEnd
	BEGIN
		SET @i = 1
		WHILE @i<=12
			BEGIN
				IF @i = 1
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年01月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-31' as varchar(100)))
				ELSE IF @i = 2
					BEGIN
						IF @intBegin % 4 = 0
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-29' as varchar(100)))
						ELSE
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-28' as varchar(100)))
					END
				ELSE IF @i = 3
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年03月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-31' as varchar(100)))
				ELSE IF @i = 4
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年04月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-30' as varchar(100)))
				ELSE IF @i = 5
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年05月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-31' as varchar(100)))
				ELSE IF @i = 6
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年06月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-30' as varchar(100)))
				ELSE IF @i = 7
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年07月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-31' as varchar(100)))
				ELSE IF @i = 8
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年08月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-31' as varchar(100)))
				ELSE IF @i = 9
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年09月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-30' as varchar(100)))
				ELSE IF @i = 10
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年10月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-31' as varchar(100)))
				ELSE IF @i = 11
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年11月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-30' as varchar(100)))
				ELSE IF @i = 12
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年12月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-31' as varchar(100)))
				SET @i = @i + 1
			END

		SET @intBegin = @intBegin + 1
	END

--最后数据处理
IF @intBegin-1=@intEnd
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END
ELSE
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END

--处理开始日期和截止日期
DECLARE @nID		int,
		@rCount		int

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate ASC
UPDATE #dDate SET StartDate = @StartDate WHERE nID = @nID

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate DESC
UPDATE #dDate SET EndDate = @EndDate WHERE nID = @nID

SELECT @rCount = COUNT(*) FROM #dDate

--最后得到日期列表
DECLARE @TableHeadName 	varchar(200),
		@TableBodyName	varchar(200),
		@SQL 			varchar(8000)
SELECT 	@TableHeadName='WebDate'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableHeadName+'
	(
		nID			int identity(1,1),
		FullName	varchar(100),
		StartDate	datetime,
		EndDate		datetime
	)
	INSERT INTO '+N'##'+@TableHeadName+'(FullName,StartDate,EndDate)
	SELECT 	FullName,
			StartDate,
			EndDate 
	FROM 	#dDate 
	ORDER BY StartDate ASC'

EXEC(@SQL)

--过滤商品信息
CREATE TABLE #PType
(
	TypeID		varchar(100),
	UserCode	varchar(200),
	FullName	varchar(200)
)

INSERT INTO #PType(TypeId,UserCode,FullName)
SELECT	TypeId,UserCode,FullName
FROM	PType
WHERE	Deleted = 0
		AND SonNum=0
		AND TypeId LIKE @PTypeId + '%'
		AND TypeId LIKE @MPTypeId + '%'
ORDER BY UserCode

--得到表体数据列表
SELECT 	@TableBodyName='WebBody'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableBodyName+'
	(
		TypeId		varchar(100),
		UserCode 	varchar (200) NULL ,
		FullName 	varchar (256) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)
	INSERT INTO '+N'##'+@TableBodyName+'
	(
		TypeId,
		UserCode,
		FullName,
		总计数量,
		总计金额
	)
	SELECT	TypeId,
			UserCode,
			FullName,
			0,
			0
	FROM	#PType '
EXEC(@SQL)

--更新数据源
CREATE TABLE #InOutStockTable
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) 
)

SET @SQL = 'INSERT INTO #InOutStockTable
		(
			PTypeId,
			BillDate,
			Qty,
			Total
		)
		SELECT	B.PTypeId,
				B.BillDate,
				ISNULL(SUM(B.Qty),0) AS Qty,
				ISNULL(CAST(SUM(B.Total) AS  NUMERIC(24, 10) ),0) AS Total
		FROM	(	
				SELECT	I.PTypeId,
						I.BillDate,
						CASE
							WHEN Bil.BillType IN (34,161) THEN I.Qty
							WHEN Bil.BillType = 157 AND I.Qty>0 THEN I.Qty
							WHEN Bil.BillType = 157 AND I.Qty<0 THEN 0
							WHEN Bil.BillType = 145 THEN -1*I.Qty
							ELSE I.Qty
						END AS Qty,
						CASE
							WHEN Bil.BillType IN (34,161) AND '+char(39)+@Flag+char(39)+'=''SH'' THEN I.qty*I.price*(1+Bil.Tax/100)
							WHEN Bil.BillType IN (157) AND I.Qty>0 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN I.qty*I.price*(1+Bil.Tax/100)
							WHEN Bil.BillType IN (157) AND I.Qty<0 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN 0
							WHEN Bil.BillType IN (145) AND '+char(39)+@Flag+char(39)+'=''SH'' THEN -1*I.qty*I.price*(1+Bil.Tax/100)
							WHEN Bil.BillType = 6 AND '+char(39)+@Flag+char(39)+'=''SH'' THEN I.qty*I.price*(1+Bil.Tax/100)
							WHEN Bil.BillType IN (34,161) AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							WHEN Bil.BillType IN (157) AND I.Qty>0 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							WHEN Bil.BillType IN (157) AND I.Qty<0 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN 0
							WHEN Bil.BillType IN (145) AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN -1*I.Total
							WHEN Bil.BillType = 6 AND '+char(39)+@Flag+char(39)+'=''ZH'' THEN I.Total
							ELSE 0					
						END AS Total
				FROM	BillIndex Bil,
						InOutStockTable I,
						#PType P
				WHERE	Bil.BillNumberId = I.BillNumberId
						AND I.PTypeId = P.TypeId
						AND Bil.BillType IN ('+@BillType+')
						AND Bil.IfCheck = ''t''
						AND Bil.RedWord = 0
						AND Bil.Draft = 0									
						AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
						AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
						AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
						AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
						AND (I.KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'  OR I.KTypeId=''10000'')
						AND (I.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR I.KTypeId=''10000'')
						AND I.PTypeId LIKE '+char(39)+@PTypeId+'%'+char(39)+'
						AND I.PTypeId LIKE '+char(39)+@MPTypeId+'%'+char(39)+'
						AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
						AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
						AND Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+'
		)B GROUP BY B.PTypeId,B.BillDate'

--PRINT(@SQL)
EXEC(@SQL)

--更新总计数据
IF @re_Limit = 0
	SET @SQL = '
		UPDATE	'+N'##'+@TableBodyName+'
		SET		总计数量 = ISNULL(I.Qty,0),
				总计金额 = ISNULL(I.Total,0)
		FROM	'+N'##'+@TableBodyName+' T
		LEFT JOIN (
			SELECT	PTypeId,
					SUM(Qty) AS Qty,
					SUM(Total) AS Total
			FROM	#InOutStockTable
			GROUP BY PTypeId
		)I ON T.TypeId = I.PTypeId'
ELSE
	SET @SQL = '
		UPDATE	'+N'##'+@TableBodyName+'
		SET		总计数量 = ISNULL(I.Qty,0),
				总计金额 = ISNULL(0,0)
		FROM	'+N'##'+@TableBodyName+' T
		LEFT JOIN (
			SELECT	PTypeId,
					SUM(Qty) AS Qty,
					SUM(Total) AS Total
			FROM	#InOutStockTable
			GROUP BY PTypeId
		)I ON T.TypeId = I.PTypeId'
EXEC(@SQL)

--更新数据源
CREATE TABLE #InOutStockTableMx
(
	PTypeId 	varchar(100),
	BillDate	datetime,
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) 
)

--更新明细数据
DECLARE @sBdate datetime,
		@sEdate datetime

EXEC Web_GetTwoDateMonth @StartDate,@EndDate,@mPageNo,0,@sBdate OUTPUT,@sEdate OUTPUT

IF ISNULL(@sEdate,'')='' OR ISNULL(@sEdate,'') = '1900-01-01' OR ISNULL(@sEdate,'')='1900-1-1'
	SET @sEDate = @EndDate

IF @IsPrint = 0
	INSERT INTO #InOutStockTableMx SELECT PTypeId,BillDate,Qty,Total FROM #InOutStockTable WHERE BillDate>=@sBdate AND BillDate<=@sEdate
ELSE
	INSERT INTO #InOutStockTableMx SELECT PTypeId,BillDate,Qty,Total FROM #InOutStockTable WHERE BillDate>=@StartDate AND BillDate<=@EndDate


--更新数量，金额数据
DECLARE @FullName 	varchar(100),
		@sDate		datetime,
		@eDate		datetime

SET @SQL = '
	DECLARE MxCursor CURSOR FOR
		SELECT 	FullName,
				StartDate,
				EndDate 
		FROM 	'+N'##'+@TableHeadName+'
		WHERE	nID>'+CAST((@mPageNo-1)*@mSize as varchar(100))+'
				AND nID<='+CAST(@mPageNo*@mSize as varchar(100))
EXEC(@SQL)
OPEN MxCursor
FETCH NEXT FROM MxCursor INTO @FullName,@sDate,@eDate
WHILE @@FETCH_STATUS=0
	BEGIN
		EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '数量]  NUMERIC(24, 10) ')
		EXEC('ALTER TABLE '+N'##'+@TableBodyName+ ' ADD ['+ @FullName + '金额]  NUMERIC(24, 10) ')
		IF @re_Limit = 0
			SET @SQL = '
				UPDATE	'+N'##'+@TableBodyName+'
				SET		['+@FullName+'数量] = ISNULL(I.Qty,0),
	
						['+@FullName+'金额] = ISNULL(I.Total,0)
				FROM	'+N'##'+@TableBodyName+' T
				LEFT JOIN (
					SELECT	PTypeId,
							SUM(Qty) AS Qty,
							SUM(Total) AS Total
					FROM	#InOutStockTableMx
					WHERE	BillDate>='+char(39)+CONVERT(varchar(10),@sDate,120)+char(39)+'
							AND BillDate<='+char(39)+CONVERT(varchar(10),@eDate,120)+char(39)+'
					GROUP BY PTypeId
				)I ON T.TypeId = I.PTypeId'
		ELSE
			SET @SQL = '
				UPDATE	'+N'##'+@TableBodyName+'
				SET		['+@FullName+'数量] = ISNULL(I.Qty,0),
	
						['+@FullName+'金额] = ISNULL(0,0)
				FROM	'+N'##'+@TableBodyName+' T
				LEFT JOIN (
					SELECT	PTypeId,
							SUM(Qty) AS Qty,
							SUM(Total) AS Total
					FROM	#InOutStockTableMx
					WHERE	BillDate>='+char(39)+CONVERT(varchar(10),@sDate,120)+char(39)+'
							AND BillDate<='+char(39)+CONVERT(varchar(10),@eDate,120)+char(39)+'
					GROUP BY PTypeId
				)I ON T.TypeId = I.PTypeId'
		EXEC(@SQL)
		FETCH NEXT FROM MxCursor INTO @FullName,@sDate,@eDate
	END
CLOSE MxCursor
DEALLOCATE MxCursor

IF @IsPrint = 0
	EXEC('SELECT * FROM '+N'##'+@TableBodyName+' WHERE [总计数量]<>0 OR [总计金额]<>0 ORDER BY UserCode')
ELSE
	BEGIN
		SET @SQL =' SELECT	TOP '+CAST(@bSize AS varchar(50))+' *
					FROM	'+N'##'+@TableBodyName+'
					WHERE	([总计数量]<>0 OR [总计金额]<>0)
							AND UserCode NOT IN (
								SELECT	TOP ' + CAST((@bPageNo-1) * @bSize AS varchar(50)) + ' UserCode
								FROM	'+N'##'+@TableBodyName+'
								WHERE	([总计数量]<>0 OR [总计金额]<>0)
								ORDER BY UserCode										
							)
					ORDER BY UserCode '
		EXEC(@SQL)
	END

--删除临时表
EXEC('DROP TABLE #dDate,#InOutStockTable,#InOutStockTableMx,#PType,'+N'##'+@TableHeadName+','+N'##'+@TableBodyName)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_BuyRequestDraftQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_BuyRequestDraftQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	返回请购单明细信息
-- 时间：	2011-08-17
-- 作者：	韩林

-- ========================================================================
CREATE PROCEDURE Web_BuyRequestDraftQuery
(
	@BillNumberID	varchar(100)	-- 单据编号
)
--@encode$--

AS
SET NOCOUNT ON 

SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId=@BillNumberID AND cbd.BillType=204

CREATE TABLE #temp
(
	id INT,
	orderQty NUMERIC(24,10),
	sendQty NUMERIC(24,10)
)

INSERT INTO #temp(id) SELECT ID  FROM dbo.RequestBill WHERE  BillNumberId = @BillNumberID

--已订货数
UPDATE a SET a.orderQty = ISNULL(d.qty,0) FROM #temp a
LEFT JOIN (
	SELECT b.RequestBillID, SUM(ISNULL(b.qty,0)) AS qty FROM dbo.OrderBill b 
	JOIN dbo.OrderIndex c ON b.billNumberID = c.billNumberId
	JOIN #temp a ON a.ID = b.RequestBillID
	WHERE b.RequestBillID > 0 AND b.BillOver = 0 AND c.IfAudit = 1
	GROUP BY b.RequestBillID 
) d
ON a.id = d.RequestBillID

--已入库数
UPDATE a SET a.sendQty = ISNULL(e.qty,0) FROM #temp a
LEFT JOIN (
	SELECT a.id ,SUM(ISNULL(b.qty,0)) AS qty FROM dbo.BuyBill b
	JOIN dbo.BillIndex c ON b.BillNumberId = c.BillNumberId
	JOIN dbo.OrderBill d ON b.orderid = d.OrderID
	JOIN #temp a ON a.id = d.RequestBillID
	WHERE c.ifcheck='t' AND c.RedWord= 0
	GROUP BY a.id
) e
ON a.id = e.id


SELECT a.BillNumberId,
	   a.PTypeID,
	   a.Qty,
	   a.SalePrice AS price,
	   a.SaleTotal AS total,
	   a.discount,
	   a.DiscountPrice,
	   a.total AS discounttotal,
	   a.Tax,
	   a.discount,
	   a.TaxPrice,
	   a.TaxTotal,
	   a.Stypeid,
	   a.RequestDate,
	   CASE CONVERT(DATE,a.OrderDate) WHEN '9999-12-31' THEN NULL ELSE a.OrderDate END AS OrderDate,
	   a.Btypeid,
	   B.FullName AS bfullname,
	   a.state,
	   a.Etypeid,
	   a.Comment as Base,
	   p.fullname,
	   p.usercode,
	   p.typeid,
	   p.UnitsType,
	   a.MUnitID,
	   a.NUnitID,
	   a.UnitID,
	   a.mqty,
	   a.isstop,
	   a.curmsaleprice,
	   a.nsaletotal,
	   a.nsaleprice,
	   a.MUnitRate,
	   CASE WHEN ISNULL(a.nunitid,0) = 0 THEN NULL
	   ELSE a.unitrate END AS unitrate,
	   CASE WHEN ISNULL(a.nunitid,0) = 0 THEN NULL
	   ELSE a.nqty END AS nqty,
	   a.discount,
	   a.curmdiscountprice,
	   a.ntotal,
	   a.curmtaxprice,
	   a.ntaxmoney,
	   a.ntaxtotal,
	   a.taxmoney,
	   p.usefullifeday,
	   p.customitemid ,
	   p.customitemfrom ,
	   p.customitemname,
	   p.customitemrefid,
	   p.isservice,
	   a.itemid,
	   CASE WHEN a.IsCombined = 0  THEN
		   (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
	   ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END AS itemname,
	   a.IsCombined,	   
	   a.ndiscountprice,
	   a.ntaxprice,
	   a.msaleprice,
	   a.mdiscountprice,
	   a.mtaxprice,
	   a.ID,
	   u1.FullName AS munit,
	   u2.FullName AS nunit,
	   u3.FullName AS unit,
	   a.requestdate,
	   a.PriceSource,
	   (dbo.F_GetAllEntrycode(p.TypeId,a.munitid,2)) AS salemunitcode,
	   (dbo.F_GetAllEntrycode(p.TypeId,a.munitid,2)) AS buymunitcode,
	   (dbo.F_GetAllEntrycode(p.TypeId,a.munitid,2)) AS stockmunitcode,
	   cbd.*,
	   (select sum(ReachQty) from orderbill where requestbillnumberid=a.BillNumberId and requestbillid=a.id)as sendqty,
	   (select  dbo.F_GetRequestQTY(a.id)) as orderqty
FROM  RequestBill a 	
INNER JOIN PType p ON a.PTypeID = p.TypeID
LEFT JOIN BType B ON B.typeId =A.Btypeid
LEFT JOIN  PType_Units u1 ON u1.UnitsId=a.MUnitID
LEFT JOIN  PType_Units u2 ON u2.UnitsId=a.NUnitID
LEFT JOIN  PType_Units u3 ON u3.UnitsId=a.UnitID
LEFT JOIN #Custom_T cbd ON cbd.detailid=a.id
LEFT JOIN #temp c ON a.ID = c.id 
WHERE a.BillNumberID =  @BillNumberID 
ORDER BY a.ID 

DROP TABLE #Custom_T , #temp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_CacheBASeInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CacheBASeInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*
	作者：谢吉康
	日期：2010-07-15
	描述：处理基本信息缓存
	
	作者：张陈仁
	日期：2012-07-12
	描述：基本信息增加自定义属性值
*/
CREATE PROCEDURE [dbo].[Web_CacheBASeInfo]
(
	@DbName				varchar(100),	--基本信息名称
	@XiWaMaxNumber		numeric(18,0)	--最大基本信息ID
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------------自定义属性-------------------------------------------------
DECLARE @tempSQL VARCHAR(max), @tSQL VARCHAR(MAX),@cCount INT,@strSELECT VARCHAR(MAX)=' t.* ',@i INT=1,@bASeType VARCHAR(50),@newBASetype VARCHAR(50)
DECLARE @RE INT
IF  EXISTS( SELECT BASeType FROM CustomBASeInforColumnsDefines)
	SET @RE=1
ELSE 
	SET @RE=0

SET @tSQL=' '	
IF LOWER(@DbName)='ptype_qp'
BEGIN
	set @bASeType='ptype'
	SET @newBASetype='ptype'
END
ELSE IF LOWER(@DbName)='gbtype'
BEGIN
	SET @DbName='btype'
	set @bASeType='gbtype'
	SET @newBASetype='gtype'
END
	
ELSE IF LOWER(@DbName)='department'
BEGIN
	set @bASeType='dtype'
	SET @newBASetype='dtype'
END
ELSE IF LOWER(@DbName)='stock'
BEGIN
	SET @bASeType='ktype' 
	SET @newBASetype='ktype'
END
ELSE IF LOWER(@DbName)='employee'
BEGIN
	SET @bASeType='etype' 
	SET @newBASetype='etype'
END
ELSE 
BEGIN
	set @bASeType=LOWER(@DbName)
	SET @newBASetype=LOWER(@DbName)
END
	
DECLARE 
	@CursorBaseType VARCHAR(MAX)='',--创建表增加字段列时basetype
	@BtypeColumnStr VARCHAR(MAX)='',--Btype列
	@GtypeColumnStr VARCHAR(MAX)='',--gtype列
	@ColumnStr VARCHAR(MAX)=''--总计表列

IF @RE=1
BEGIN	
	SET @tSQL='CREATE TABLE #TC ('

	DECLARE @CustomerOrder INT 
	DECLARE CUSTOMER_CURSOR CURSOR FORWARD_ONLY STATIC FOR
	SELECT BaseType,CustomerOrder FROM CustomBASeInforColumnsDefines WHERE (@newBASetype IN('gtype','btype') AND BASeType IN('gtype','btype')) OR (@newBASetype NOT IN('gtype','btype') AND BASeType=@newBASetype) ORDER BY CustomerOrder
	OPEN CUSTOMER_CURSOR 
	FETCH NEXT FROM CUSTOMER_CURSOR INTO @CursorBaseType,@CustomerOrder
		 WHILE @@FETCH_STATUS = 0
		 BEGIN
			IF(@CursorBaseType IN('gtype','btype'))--如果启用了合并供货商选项
				BEGIN
					IF(@CursorBaseType='gtype')--供货商档案
						SET @GtypeColumnStr+='Costom'+CAST(@CustomerOrder AS varchar(10))+',bASeFullName'+CAST(@CustomerOrder AS varchar(10))+','
					ELSE --客户档案
						SET @BtypeColumnStr+='Costom'+CAST(@CustomerOrder AS varchar(10))+',bASeFullName'+CAST(@CustomerOrder AS varchar(10))+','
					
					IF(CHARINDEX('Costom'+CAST(@CustomerOrder AS varchar(10)),@ColumnStr,1)=0)--判断临时表  该列是否存在 不存在就增加该列
						BEGIN
							SET @ColumnStr+='Costom'+CAST(@CustomerOrder AS varchar(10))+',bASeFullName'+CAST(@CustomerOrder AS varchar(10))+','
						
							SET @tSQL+=' Costom'+CAST(@CustomerOrder AS varchar(10))+' VARCHAR(600),bASeFullName'+CAST(@CustomerOrder AS varchar(10))+' VARCHAR(600),'				
						END				
				END
			ELSE 		
				SET @tSQL+=' Costom'+CAST(@CustomerOrder AS varchar(10))+' VARCHAR(600),bASeFullName'+CAST(@CustomerOrder AS varchar(10))+' VARCHAR(600),'
			
			FETCH NEXT FROM CUSTOMER_CURSOR INTO @CursorBaseType,@CustomerOrder
		 END
	CLOSE CUSTOMER_CURSOR
	DEALLOCATE CUSTOMER_CURSOR
	SET @tSQL+='Tid VARCHAR(50) ) '
	
	IF(@newBASetype IN('gtype','btype'))
		BEGIN
			SET @GtypeColumnStr+='Tid'
			SET @BtypeColumnStr+='Tid'
			SET @tSQL+='INSERT #TC('+@GtypeColumnStr+') exec GP_GetBASeInforCustomData @BASeType=''gbtype'',@TypeId=NULL 
			INSERT #TC('+@BtypeColumnStr+') exec GP_GetBASeInforCustomData @BASeType=''btype'',@TypeId=NULL 
			'
		END
	ELSE 
		SET @tSQL+=' INSERT #TC exec GP_GetBASeInforCustomData @BASeType='''+@bASeType+''',@TypeId=NULL '
END
--PRINT @tSQL
-------------------------------自定义属性-------------------------------------------------

DECLARE @SQL varchar(8000)

IF @DbName = 'stock'	--仓库
	BEGIN
	SET @tempSQL=@tSQL+'
		SELECT 	''10000'' AS TypeId,
				''00000'' AS ParId,
				0 AS SonNum,''代销库'' AS FullName,
				'''' AS Name,''10000'' AS UserCode,
				'''' AS Comment,
				'''' AS [Add],
				'''' AS Tel,
				'''' AS LinkMan,''dxk'' AS PyCode,
				sfullname = (SELECT FullName FROM Stype(NOLOCK) WHERE TypeId = STypeId AND SonNum = 0),
				'''' as mdusercode,
				'''' as mdfullname,
				job,
				mobile,
				sheng,
				shi,
				xian,
				postcode,
				'
	IF @RE=1
		SET @tempSQL = @tempSQL+@strSelect+','			
	SET @tempSQL = @tempSQL+ '
				XiWaMaxNumber   
		FROM 	Stock(NOLOCK) '
	IF @RE=1
		SET @tempSQL = @tempSQL+' a left join #TC t ON a.TypeId=t.Tid ' 
	SET @tempSQL = @tempSQL+
		'WHERE 	TypeId = ''00000'' 
		UNION ALL 
		SELECT 	typeid as typeid,
				parid,
				sonnum,
				fullname,
				[name],
				usercode,
				comment,
				[add],
				tel,
				linkman,
				pycode,
				sfullname = (SELECT FullName FROM Stype(NOLOCK) WHERE TypeId = a.STypeId AND SonNum = 0),
				usercode as mdusercode,
				fullname as mdfullname,
				job,
				mobile,
				sheng,
				shi,
				xian,
				postcode,
				'
	IF @RE=1
		SET @tempSQL = @tempSQL+@strSelect+','			
	SET @tempSQL = @tempSQL+ '
		XiWaMaxNumber  
		FROM 	stock(NOLOCK) a '
	IF @RE=1 
		SET @tempSQL = @tempSQL+' left join #TC t ON a.TypeId=t.Tid '  
	SET @tempSQL = @tempSQL+' WHERE 	XiWaMaxNumber >= '+CAST(@XiWaMaxNumber AS VARCHAR(50))
	IF @RE=1
		SET @tempSQL = @tempSQL+' 
		drop TABLE #TC 
		'
		--print(@tempSQL)
		EXECUTE(@tempSQL)
	END
ELSE IF @DbName = 'department'	--部门
	BEGIN
	SET @tempSQL=@tSQL+'
		SELECT	''99999'' as typeid,
				''00000'' as parid,
				0 as sonnum,
				''其他部门'' as usercode,
				''其他部门'' as fullname,
				'''' as [name],
				'''' as comment,
				'''' as tel,
				'''' as linkman,
				'''' as fax,
				''qtbm'' as pycode,
				'
	IF @RE=1
		SET	@tempSQL= @tempSQL+@strSelect+','
	SET	@tempSQL= @tempSQL+	'
		XiWaMaxNumber  
		FROM 	department(NOLOCK) a '
	IF @RE=1
		SET	@tempSQL= @tempSQL+	' left join #TC t ON a.TypeId=t.Tid '
	SET	@tempSQL= @tempSQL+	'
		WHERE 	typeid = ''00000'' 
		UNION ALL 
		SELECT 	typeid,
				parid,
				sonnum,
				usercode,
				fullname,
				[name],
				comment,
				tel,
				linkman,
				fax,
				pycode, 
				'
		IF @RE=1
			SET	@tempSQL= @tempSQL+@strSelect+','
		SET @tempSQL= @tempSQL+' 
		XiWaMaxNumber 
		FROM 	department(NOLOCK) a '
		IF @RE=1
			SET @tempSQL= @tempSQL+' left join #TC t ON a.TypeId=t.Tid '		
		SET @tempSQL= @tempSQL+'
		WHERE 	XiWaMaxNumber >= '+cast(@XiWaMaxNumber as varchar(50))
		IF @RE=1
			SET @tempSQL= @tempSQL+'
		DROP table #TC 
		'
		--print @tempSQL
		exec (@tempSQL)
	END
ELSE IF @DbName = 'btype'	--往来单位
	BEGIN
		SET @tempSQL=@tSQL+'
		SELECT 	''99999'' as typeid,
				''00000'' as parid,
				0 as sonnum,
				''其他单位'' as usercode,
				''其他单位'' as fullname,
				'''' as [name],
				'''' as telandaddress,
				'''' as postcode,
				'''' as taxnumber,
				'''' as bankandacount,
				'''' as comment,
	            a.tel1,
				a.tel2,
				a.tel3,
				a.www,
				'''' as bank,
				a.bankname,
				a.email,
				''qtdw'' as pycode,
				a.XiWaMaxNumber,
				a.fax,
				'''' AS AreaTypeName,
				a.linkman1,
				a.linktel1,
				a.linkmobile1,
				a.linkman2,
				a.linktel2,
				a.linkmobile2,
				CASE WHEN a.arlimittime=9999 THEN NULL ELSE convert(numeric(18,0),a.arlimittime)  END AS arlimittime,
				CASE WHEN a.paymentltime=9999 THEN NULL ELSE convert(numeric(18,0),a.paymentltime) END AS paymentltime,
				a.salezekou,
				a.buyzekou,
				a.consignee, 
				a.consigneetel,				
				e.fullname as linkemployee,
				a.sheng,
				a.shi,
				a.xian,
				a.blevel,
				'
		IF @RE=1			
			SET @tempSQL=@tempSQL+@strSelect+','
		SET @tempSQL=@tempSQL+' 
				a.consigneeaddress,
				a.denominatedid as denominatedid,
				den.usercode as denusercode,
				den.fullname as denfullname
		FROM 	BType(NOLOCK) a '
		IF @RE=1
		SET @tempSQL=@tempSQL+' left join #TC t ON a.TypeId=t.Tid '
		SET @tempSQL=@tempSQL+
		'
		LEFT JOIN dbo.employee(NOLOCK) e ON e.typeid=a.etypeid
		INNER JOIN BTYPE DEN ON A.denominatedid=DEN.TYPEID
		WHERE 	a.TypeId = ''00000''                                                
        UNION ALL 
		SELECT 	a.typeid,
				a.parid,
				a.sonnum,
				a.usercode,
				a.fullname,
				a.[name],
				a.telandaddress,
				a.postcode,
				a.taxnumber,
				a.bankandacount,
				a.comment,
				a.tel1,
				a.tel2,
				a.tel3,
				a.www,
				a.bank,
				a.bankname,
				a.email,
				a.pycode,
				a.XiWaMaxNumber,
				a.fax,
				AreaTypeName = (SELECT FullName FROM AreaType(NOLOCK) WHERE SonNum = 0 AND AreaType.TypeId = a.AreaTypeId),
				a.linkman1,
				a.linktel1,
				a.linkmobile1,
				a.linkman2,
				a.linktel2,
				a.linkmobile2,
				CASE WHEN a.arlimittime=9999 THEN NULL ELSE convert(numeric(18,0),a.arlimittime) END AS arlimittime,
				CASE WHEN a.paymentltime=9999 THEN NULL ELSE  convert(numeric(18,0),a.paymentltime)  END AS paymentltime,
				a.salezekou,
				a.buyzekou,
				a.consignee, 
				a.consigneetel,
				e.fullname as linkemployee,
				a.sheng,
				a.shi,
				a.xian,
				a.blevel,
				'
		IF @RE=1		
			SET @tempSQL=@tempSQL+@strSelect+','
		SET @tempSQL=@tempSQL+	'  
				a.consigneeaddress,
				a.denominatedid as denominatedid,
				den.usercode as denusercode,
				den.fullname as denfullname
		FROM 	BType(NOLOCK) a '
		IF @RE=1
		SET @tempSQL=@tempSQL+' left join #TC t ON a.TypeId=t.Tid '
		SET @tempSQL=@tempSQL+'
		LEFT JOIN dbo.employee(NOLOCK) e ON e.typeid=a.etypeid
		INNER JOIN BTYPE DEN ON A.denominatedid=DEN.TYPEID
		WHERE 	a.XiWaMaxNumber >= '+CAST(@XiWaMaxNumber as varchar(50))
		IF @RE=1
			SET @tempSQL=@tempSQL+ ' 
		DROP table #TC	'
		--PRINT(@tempSQL)
		exec (@tempSQL)
	END
ELSE IF @DbName = 'areatype'	--地区
	BEGIN
	SET @tempSQL=@tSQL+'
		SELECT 	''99999'' as typeId, 
				''00000'' as parid, 
				0 as sonnum, 
				''其他地区'' as FullName, 
				'''' as Name, 
				''其他地区'' as UserCode, 
				'''' as Comment, 
				'''' as TEL, 
				'''' as LinkMan, 
				''qtdq'' as PyCode, 
				'
		IF @RE=1
			SET	@tempSQL=@tempSQL+@strSelect+','
		SET	@tempSQL=@tempSQL+' 
		XiWaMaxNumber
		FROM 	AREATYPE(NOLOCK) a '
		IF @RE=1
			SET	@tempSQL=@tempSQL+' left join #TC t ON a.TypeId=t.Tid '
		SET	@tempSQL=@tempSQL+'	
		WHERE 	TypeId = ''00000'' 
		UNION ALL 
		SELECT 	typeId, 
				parid, 
				sonnum,
				FullName, 
				Name, 
				UserCode, 
				Comment, 
				TEL, 
				LinkMan, 
				PyCode, 
				'
		IF @RE=1
			SET	@tempSQL=@tempSQL+@strSelect+','
		SET	@tempSQL=@tempSQL+'
		XiWaMaxNumber 
		FROM 	AREATYPE(NOLOCK) a'
		IF @RE=1 
			SET	@tempSQL=@tempSQL+' left join #TC t ON a.TypeId=t.Tid '
		SET	@tempSQL=@tempSQL+'	
		WHERE 	XiWaMaxNumber >= '+cast(@XiWaMaxNumber as varchar(50))
		IF @RE=1
		SET	@tempSQL=@tempSQL+'  
		DROP table #TC	'
		--print @tempSQL
		exec (@tempSQL)
	END
ELSE IF @DbName = 'ptype' 	--商品
	BEGIN
	CREATE TABLE #PType_Units  --商品计量单位扩展
	(
		UnitsId INT,
		Rate  NUMERIC(24, 10) ,
		FullName VARCHAR(200),
		ptypeid varchar(50)
	)
	CREATE NONCLUSTERED INDEX CIX_PType_Units ON #PType_Units(UnitsId,ptypeid)
	
	INSERT INTO #PType_Units
	SELECT c.UnitsId,c.Rate,d.FullName,PtypeID FROM PType_Units_Ext c 
	INNER JOIN PType_Units d
	ON c.UnitsId = d.UnitsId
	
	SET @tempSQL=@tSQL+'	
		SELECT 	''TCDSP'' AS TypeId,
				''root'' AS ParId,
				0 AS SonNum,
				'''' AS UserCode,
				''直接收款'' AS FullName,
				a.[Name],
				a.Standard,
				a.Type,
				a.Area,
				a.Unit1,
				a.Unit2,
				a.UnitRate1,
				a.UseFulLifeDay,
				a.Comment,
				a.EntryCode,
				a.PyCode,
				a.weight,
				a.volume,
				b.prebuyprice1,
				b.prebuyprice2,
				b.prebuyprice3,
				b.prebuyprice4,
				b.prebuyprice5,
				b.presaleprice1,
				b.presaleprice2,
				b.presaleprice3,
				b.presaleprice4,
				b.presaleprice5,
				b.presaleprice6,
				b.presaleprice7,
				b.presaleprice8,
				b.presaleprice9,
				b.presaleprice10,
				b.RetailPrice,
				b.LowSalePrice,
				b.topsaleprice,			
				b.TopBuyPrice,
				b.referprice,
				(SELECT fullname FROM #PType_Units d WHERE d.UnitsId = a.SaleUnitId and d.ptypeid = a.typeId) AS SaleUnitfullname,
				(SELECT fullname FROM #PType_Units d WHERE d.UnitsId = a.BuyUnitId and d.ptypeid = a.typeId) AS BuyUnitfullname,
				(SELECT fullname FROM #PType_Units d WHERE d.UnitsId = a.StockUnitId and d.ptypeid = a.typeId) AS StockUnitfullname,
				(SELECT fullname FROM #PType_Units d WHERE d.UnitsId = a.baseunitid and d.ptypeid = a.typeId) AS baseunitfullname,
				(SELECT Rate FROM #PType_Units d WHERE d.UnitsId = a.SaleUnitId and d.ptypeid = a.typeId) AS SaleUnitRate,
				(SELECT Rate FROM #PType_Units d WHERE d.UnitsId = a.BuyUnitId and d.ptypeid = a.typeId) AS BuyUnitRate,
				(SELECT Rate FROM #PType_Units d WHERE d.UnitsId = a.StockUnitId and d.ptypeid = a.typeId) AS StockUnitRate,
				(SELECT Rate FROM #PType_Units d WHERE d.UnitsId = a.baseunitid and d.ptypeid = a.typeId) AS baseunitRate,
				bc.fullname AS brandarfullname,
				pc.fullname as categoryfullname,
				qpe.fullname AS ptypebfullname,
				'
		IF @RE=1
			SET	@tempSQL=@tempSQL+@strSelect+','
		SET	@tempSQL=@tempSQL+' a.XiWaMaxNumber
		FROM 	PType a(NOLOCK) 
		LEFT JOIN brandar_Commodity bc ON bc.typeid = a.brandartypeid
		LEFT JOIN PTypeCategory pc ON pc.typeid = a.PtypeCategoryID '
		IF @RE=1
			SET	@tempSQL=@tempSQL+' left join #TC t ON a.TypeId=t.Tid  '
		SET	@tempSQL=@tempSQL+'	
		LEFT JOIN dbo.PType_Price b(NOLOCK) ON a.typeid=b.ptypeid AND b.IsDefaultUnit=1
		LEFT JOIN 
        (
			SELECT	qp.PTypeID,
					B.FullName
			FROM	QP_PType_Ext qp
			INNER JOIN BType B ON qp.BTypeID = B.TypeId
			WHERE	ISNULL(qp.BTypeId,'''') <> ''''
        )qpe ON qpe.PTypeId = a.TypeId
		WHERE 	a.TypeId = ''00000''
		UNION ALL 
		SELECT 	a.typeid,
				a.parid,
				a.sonnum,
				a.usercode,
				a.fullname,
				a.[Name],
				a.Standard,
				a.Type,
				a.Area,
				a.Unit1,
				a.Unit2,
				a.UnitRate1,
				a.UseFulLifeDay,
				a.Comment,
				a.EntryCode,
				a.PyCode,
				a.weight,
				a.volume,
				b.prebuyprice1,
				b.prebuyprice2,
				b.prebuyprice3,
				b.prebuyprice4,
				b.prebuyprice5,
				b.presaleprice1,
				b.presaleprice2,
				b.presaleprice3,
				b.presaleprice4,
				b.presaleprice5,
				b.presaleprice6,
				b.presaleprice7,
				b.presaleprice8,
				b.presaleprice9,
				b.presaleprice10,
				b.RetailPrice,
				b.LowSalePrice,
				b.topsaleprice,			
				b.TopBuyPrice,
				b.referprice,
				(SELECT fullname FROM #PType_Units d WHERE d.UnitsId = a.SaleUnitId and d.ptypeid = a.typeId) AS SaleUnitfullname,
				(SELECT fullname FROM #PType_Units d WHERE d.UnitsId = a.BuyUnitId and d.ptypeid = a.typeId) AS BuyUnitfullname,
				(SELECT fullname FROM #PType_Units d WHERE d.UnitsId = a.StockUnitId and d.ptypeid = a.typeId) AS StockUnitfullname,
				(SELECT fullname FROM #PType_Units d WHERE d.UnitsId = a.baseunitid and d.ptypeid = a.typeId) AS baseunitfullname,
				(SELECT Rate FROM #PType_Units d WHERE d.UnitsId = a.SaleUnitId and d.ptypeid = a.typeId) AS SaleUnitRate,
				(SELECT Rate FROM #PType_Units d WHERE d.UnitsId = a.BuyUnitId and d.ptypeid = a.typeId) AS BuyUnitRate,
				(SELECT Rate FROM #PType_Units d WHERE d.UnitsId = a.StockUnitId and d.ptypeid = a.typeId) AS StockUnitRate,
				(SELECT Rate FROM #PType_Units d WHERE d.UnitsId = a.baseunitid and d.ptypeid = a.typeId) AS baseunitRate,
				bc.fullname AS brandarfullname,
				pc.fullname as categoryfullname,
				qpe.fullname AS ptypebfullname,
				'
		IF @RE=1
			SET	@tempSQL=@tempSQL+@strSelect+','
		SET	@tempSQL=@tempSQL+' a.XiWaMaxNumber
		FROM 	PType a(NOLOCK) 
		LEFT JOIN brandar_Commodity bc ON bc.typeid = a.brandartypeid
		LEFT JOIN PTypeCategory pc ON pc.typeid = a.PtypeCategoryID
		LEFT JOIN 
        (
			SELECT	qp.PTypeID,
					B.FullName
			FROM	QP_PType_Ext qp
			INNER JOIN BType B ON qp.BTypeID = B.TypeId
			WHERE	ISNULL(qp.BTypeId,'''') <> ''''
        )qpe ON qpe.PTypeId = a.TypeId '
		IF @RE=1
			SET	@tempSQL=@tempSQL+' left join #TC t ON a.TypeId=t.Tid '
		SET	@tempSQL=@tempSQL+'
		LEFT JOIN dbo.PType_Price b(NOLOCK) ON  a.typeid=b.ptypeid AND b.IsDefaultUnit=1
		WHERE 	a.XiWaMaxNumber >= '+CAST(@XiWaMaxNumber as varchar(50))
		IF @RE=1
			SET	@tempSQL=@tempSQL+' 	
		DROP table #TC	'
		
		--print @tempSQL
		Exec(@tempSQL)
		DROP TABLE	#PType_Units
	END
ELSE IF @DbName = 'ptype_qp'
	BEGIN
	CREATE TABLE #qp_PType_Units  --商品计量单位扩展
	(
		UnitsId		INT,
		Rate		NUMERIC(24, 10) ,
		FullName	VARCHAR(200),
		ptypeid		varchar(50),
		UnitsSortId	int,
		entrycode	varchar(500)		
	)
	CREATE NONCLUSTERED INDEX CIX_qp_PType_Units ON #qp_PType_Units(UnitsId,ptypeid)
	
	INSERT INTO #qp_PType_Units
	SELECT c.UnitsId,c.Rate,d.FullName,c.PtypeID,c.UnitsSortId,c.entrycode
	FROM PType_Units_Ext c 
	INNER JOIN PType_Units d ON c.UnitsId = d.UnitsId
	
	CREATE CLUSTERED INDEX IX_PType_Units ON #qp_PType_Units(UnitsID,PTypeID)
	
	SELECT TypeID
	INTO #MultipleUnit
	FROM dbo.PType  PP
	WHERE 
	(PP.SaleUnitId<>PP.baseUnitId
	OR PP.BuyUnitId<>PP.baseUnitId
	OR PP.StockUnitId<>PP.baseUnitId
	)
	SET @tempSQL=@tSQL+'
        SELECT  ''TCDSP'' AS TypeId,
                ''root'' AS ParId,
                0 AS SonNum,
                '''' AS UserCode,
                ''直接收款'' AS FullName,
                p.dwgno,
                p.entrycode,
                p.multentrycode,
                p.[name],
                '''' as brand,
                '''' as import,
                p.area,
                p.type,
                '''' as GeneralType,
                '''' as generaldwgno,
                p.comment,
                '''' as  property,
                '''' as packageqty,
                p.weight,
                '''' as taxnumber,
                '''' as taxrate,
                '''' as btypeid,
                '''' as bfullname,
                '''' as fcunit,
                '''' as fcprice,
                p.Unit1,
				p.Unit2,
				p.Standard,
				p.UnitRate1,
				''zjsk'' AS PyCode,
				0 AS Integral,
				p.usefullifeday,
				p.volume,
				b.prebuyprice1,
				b.prebuyprice2,
				b.prebuyprice3,
				b.prebuyprice4,
				b.prebuyprice5,
				b.presaleprice1,
				b.presaleprice2,
				b.presaleprice3,
				b.presaleprice4,
				b.presaleprice5,
				b.presaleprice6,
				b.presaleprice7,
				b.presaleprice8,
				b.presaleprice9,
				b.presaleprice10,
				b.RetailPrice,
				b.LowSalePrice,
				b.topsaleprice,			
				b.TopBuyPrice,
				b.referprice, 
				'''' SaleUnitfullname,
				'''' BuyUnitfullname,
				'''' StockUnitfullname,
				'''' baseunitfullname,
				'''' assistantunitfullname,
				0 SaleUnitRate,
				0 BuyUnitRate,
				0 StockUnitRate,
				0 baseunitRate,
				0 as BuyDefaultRate,
				0 as SaleDefaultRate,
				bc.fullname AS brandarfullname,
				pc.FullName AS categoryfullname,
				''baseunitentrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and (UnitsSortId = 1 OR UnitsSortId = 0 )),
				''unit1entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),				
				''unit1rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),				
				''baseunit1fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and (UnitsSortId = 1 OR UnitsSortId = 0 )),
				''unit1fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),
				qpe.FullName AS ptypebfullname,
				p.othercomment1,
				p.othercomment2,
				p.othercomment3,
				p.othercomment4,
				p.othercomment5,
               '
        IF @RE=1
			SET	@tempSQL=@tempSQL+@strSelect+','
		SET	@tempSQL=@tempSQL+'  p.XiWaMaxNumber
        FROM    PType p(NOLOCK)
        LEFT JOIN brandar_Commodity bc ON bc.typeid = p.brandartypeid
        LEFT JOIN PTypeCategory pc ON pc.typeid = p.PtypeCategoryID
        LEFT JOIN 
        (
			SELECT	qp.PTypeID,
					B.FullName
			FROM	QP_PType_Ext qp
			INNER JOIN BType B ON qp.BTypeID = B.TypeId
			WHERE	ISNULL(qp.BTypeId,'''') <> ''''
        )qpe ON qpe.PTypeId = p.TypeId  '
        IF @RE=1 
			SET	@tempSQL=@tempSQL+' left join #TC t ON p.TypeId=t.Tid '
        SET	@tempSQL=@tempSQL+'        
        LEFT JOIN dbo.PType_Price b(NOLOCK) ON p.typeid=b.ptypeid AND b.IsDefaultUnit=1
        WHERE   p.TypeId = ''00000''
        UNION ALL
        SELECT  p.TypeId,
                p.ParId,
                p.SonNum,
                p.UserCode,
                p.FullName,
                p.dwgno,
                p.entrycode,
                p.multentrycode,
                p.[name],
                '''' as brand,
                '''' as import,
                p.area,
                p.type,
                '''' as GeneralType,
                '''' as generaldwgno,
                p.comment,
                '''' as property,
                '''' as packageqty,
                p.weight,
                '''' as taxnumber,
                '''' as taxrate,
                '''' as btypeid,
                '''' as bfullname,
                '''' as fcunit,
                '''' as fcprice,
                p.Unit1,
				p.Unit2,
				p.Standard,
				p.UnitRate1,
				p.PyCode,
				p.Integral,
				p.usefullifeday,				
				p.volume,
				b.prebuyprice1,
				b.prebuyprice2,
				b.prebuyprice3,
				b.prebuyprice4,
				b.prebuyprice5,
				b.presaleprice1,
				b.presaleprice2,
				b.presaleprice3,
				b.presaleprice4,
				b.presaleprice5,
				b.presaleprice6,
				b.presaleprice7,
				b.presaleprice8,
				b.presaleprice9,
				b.presaleprice10,
				b.RetailPrice,
				b.LowSalePrice,
				b.topsaleprice,			
				b.TopBuyPrice,
				b.referprice,
				ps1.fullname as SaleUnitfullname,
				ps2.fullname AS BuyUnitfullname,
				ps3.fullname AS StockUnitfullname,
				ps4.fullname AS baseunitfullname,
				ps5.fullname AS assistantunitfullname,
				ps1.rate AS SaleUnitRate,
				ps2.rate AS BuyUnitRate,
				ps3.rate AS StockUnitRate,
				ps4.rate AS baseunitRate,
                p.BuyDefaultRate,
				p.SaleDefaultRate,
				bc.fullname AS brandarfullname,
				pc.FullName AS categoryfullname,
				''baseunitentrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and (UnitsSortId = 1 OR UnitsSortId = 0 )),
				''unit1entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),				
				''unit1rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),				
				''baseunit1fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and (UnitsSortId = 1 OR UnitsSortId = 0 )),
				''unit1fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),
				qpe.FullName AS ptypebfullname,
				p.othercomment1,
				p.othercomment2,
				p.othercomment3,
				p.othercomment4,
				p.othercomment5,
				'
        IF @RE=1
			SET	@tempSQL=@tempSQL+@strSelect+','
		SET	@tempSQL=@tempSQL+' p.XiWaMaxNumber 
        FROM    PType p(NOLOCK)
        LEFT JOIN brandar_Commodity bc ON bc.typeid = p.brandartypeid
        LEFT JOIN PTypeCategory pc ON pc.typeid = p.PtypeCategoryID '
        IF @RE=1 
			SET	@tempSQL=@tempSQL+' left join #TC t ON p.TypeId=t.Tid '
		SET	@tempSQL=@tempSQL+'	
		LEFT JOIN dbo.PType_Price b(NOLOCK) ON p.typeid=b.ptypeid AND b.IsDefaultUnit=1
        INNER JOIN #MultipleUnit pp ON p.TypeID=pp.TypeID
        LEFT JOIN  #qp_PType_Units ps1 ON ps1.UnitsId = p.SaleUnitId and ps1.ptypeid = p.typeId
		LEFT JOIN  #qp_PType_Units ps2 ON ps2.UnitsId = p.BuyUnitId and ps2.ptypeid = p.typeId
		LEFT JOIN  #qp_PType_Units ps3 ON ps3.UnitsId = p.StockUnitId and ps3.ptypeid = p.typeId
		LEFT JOIN  #qp_PType_Units ps4 ON ps4.UnitsId = p.baseunitid and ps4.ptypeid = p.typeId
		LEFT JOIN  #qp_PType_Units ps5 ON ps5.UnitsId = p.AssistantUnitId and ps5.ptypeid = p.typeId
		LEFT JOIN 
        (
			SELECT	qp.PTypeID,
					B.FullName
			FROM	QP_PType_Ext qp
			INNER JOIN BType B ON qp.BTypeID = B.TypeId
			WHERE	ISNULL(qp.BTypeId,'''') <> ''''
        )qpe ON qpe.PTypeId = p.TypeId
        WHERE 	p.XiWaMaxNumber >= '+CAST(@XiWaMaxNumber as varchar(50))+'
        UNION ALL
        SELECT  p.TypeId,
                p.ParId,
                p.SonNum,
                p.UserCode,
                p.FullName,
                p.dwgno,
                p.entrycode,
                p.multentrycode,
                p.[name],
                '''' as brand,
                '''' as import,
                p.area,
                p.type,
                '''' as GeneralType,
                '''' as generaldwgno,
                p.comment,
                '''' as property,
                '''' as packageqty,
                p.weight,
                '''' as taxnumber,
                '''' as taxrate,
                '''' as btypeid,
                '''' as bfullname,
                '''' as fcunit,
                '''' as fcprice,
                p.Unit1,
				p.Unit2,
				p.Standard,
				p.UnitRate1,
				p.PyCode,
				p.Integral,
				p.usefullifeday,				
				p.volume,
				b.prebuyprice1,
				b.prebuyprice2,
				b.prebuyprice3,
				b.prebuyprice4,
				b.prebuyprice5,
				b.presaleprice1,
				b.presaleprice2,
				b.presaleprice3,
				b.presaleprice4,
				b.presaleprice5,
				b.presaleprice6,
				b.presaleprice7,
				b.presaleprice8,
				b.presaleprice9,
				b.presaleprice10,
				b.RetailPrice,
				b.LowSalePrice,
				b.topsaleprice,			
				b.TopBuyPrice,
				b.referprice,
				ps4.fullname as SaleUnitfullname,
				ps4.fullname AS BuyUnitfullname,
				ps4.fullname AS StockUnitfullname,
				ps4.fullname AS baseunitfullname,
				ps4.fullname AS assistantunitfullname,
				ps4.rate AS SaleUnitRate,
				ps4.rate AS BuyUnitRate,
				ps4.rate AS StockUnitRate,
				ps4.rate AS baseunitRate,
				p.BuyDefaultRate,
				p.SaleDefaultRate,
				bc.fullname AS brandarfullname,
				pc.FullName AS categoryfullname,
				''baseunitentrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and (UnitsSortId = 1 OR UnitsSortId = 0 )),
				''unit1entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3entrycode'' = (SELECT TOP 1 entrycode FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),				
				''unit1rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3rate'' = (SELECT TOP 1 ISNULL(rate,0) AS rate FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),				
				''baseunit1fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and (UnitsSortId = 1 OR UnitsSortId = 0 )),
				''unit1fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 2),
				''unit2fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 3),
				''unit3fullname'' = (SELECT TOP 1 fullname FROM #qp_PType_Units WHERE PTypeId = p.typeid and UnitsSortId = 4),
				qpe.FullName AS ptypebfullname,
				p.othercomment1,
				p.othercomment2,
				p.othercomment3,
				p.othercomment4,
				p.othercomment5,
				'
		IF @RE=1
			SET	@tempSQL=@tempSQL+@strSelect+','
		SET	@tempSQL=@tempSQL+' p.XiWaMaxNumber 
        FROM    PType p(NOLOCK)
        LEFT JOIN brandar_Commodity bc ON bc.typeid = p.brandartypeid
        LEFT JOIN PTypeCategory pc ON pc.typeid = p.PtypeCategoryID '
        IF @RE=1 
			SET	@tempSQL=@tempSQL+' left join #TC t ON p.TypeId=t.Tid '
		SET	@tempSQL=@tempSQL+'
        LEFT JOIN  #qp_PType_Units ps4 ON ps4.UnitsId = p.baseunitid and ps4.ptypeid = p.typeId 
        LEFT JOIN dbo.PType_Price b(NOLOCK) ON p.typeid=b.ptypeid AND b.IsDefaultUnit=1
        LEFT JOIN 
        (
			SELECT	qp.PTypeID,
					B.FullName
			FROM	QP_PType_Ext qp
			INNER JOIN BType B ON qp.BTypeID = B.TypeId
			WHERE	ISNULL(qp.BTypeId,'''') <> ''''
        )qpe ON qpe.PTypeId = p.TypeId
        WHERE 	p.XiWaMaxNumber >= '+CAST(@XiWaMaxNumber as varchar(50))+'	
        AND p.TypeID NOT IN
        (
			SELECT TypeID
			FROM #MultipleUnit
        )'
        IF @RE=1
			SET	@tempSQL=@tempSQL+ '	
        drop TABLE #TC
        '
        --print @tempSQL
        exec(@tempSQL)
        DROP TABLE	#qp_PType_Units,#MultipleUnit
	END
ELSE IF @DbName = 'employee'	--职员信息
	BEGIN
	SET @tempSQL=@tSQL+'
		SELECT 	typeId, 
				Parid, 
				sonnum, 
				FullName, 
				UserCode,
				FullName AS syyfullname, 
				UserCode AS syyusercode, 
				Tel, 
				Address, 
				Comment, 
				sfullname = (SELECT FullName FROM Stype(NOLOCK) WHERE TypeId = a.STypeId AND SonNum = 0),
				Department = (SELECT FullName FROM Department(NOLOCK) WHERE TypeId = a.DTypeId AND SonNum = 0),
				CASE WHEN ISNULL(Birthday,'''')=''2050-01-01'' THEN NULL ELSE CONVERT(VARCHAR(10),Birthday,120) END AS Birthday, 
				Mob, 
				Mail, 
				PostCode, 
				PyCode,
				Job, 
				Team,
				IfPic = CASE
							WHEN EXISTS(SELECT TOP 1 1 FROM EType_Picture(NOLOCK) WHERE ETypeID = a.typeId) THEN ''有''
							ELSE ''无''
						END,
				CASE  WHEN maxpre=999999999918.99 OR MaxPre = -999999999918.99 THEN NULL ELSE maxpre END  AS maxpre,
				CASE  WHEN tichengrate=0 THEN NULL ELSE tichengrate END  AS tichengrate,
				buyerminvalue,
				saleminvalue,
				'
		IF @RE=1
			SET	@tempSQL=@tempSQL+@strSelect+','
		SET	@tempSQL=@tempSQL+' 
		XiWaMaxNumber 
		FROM 	employee(NOLOCK) a '
		IF @RE=1
			SET	@tempSQL=@tempSQL+' left join #TC t ON a.TypeId=t.Tid '
		SET	@tempSQL=@tempSQL+'
		WHERE 	XiWaMaxNumber >= '+CAST(@XiWaMaxNumber AS VARCHAR(50))
		IF @RE=1
		SET	@tempSQL=@tempSQL+'
		drop TABLE #TC
		'
		exec(@tempSQL)
	END
ELSE IF @DbName = 'wctype'		--维修车型档案
	BEGIN
		SELECT 	* 
		FROM 	QP_RepairAutoType(NOLOCK)
		WHERE 	XiWaMaxNumber >= @XiWaMaxNumber
	END
ELSE IF @DbName = 'witype'		--维修项目资料
	BEGIN
		SELECT 	I.TypeId,
				I.SonNum,
				I.ParId,
				I.UserCode,
				I.FullName,
				CASE I.ChargeMode
					WHEN 0 THEN '按工时'
					WHEN 1 THEN '标准价'
					WHEN 2 THEN '最高价'
					ELSE '最低价'
				END AS chargemode,
				CASE I.ItemType
					WHEN '0' THEN '维修项目'
					ELSE '保养项目'
				END AS itemtype,
				I.Comment,
				ISNULL(I.maintaindays,0) AS maintaindays,
				ISNULL(I.maintainmileage,0) AS maintainmileage,
				A.FullName AS AFullName,
				I.PyCode,
				I.UserDefine1,
				I.UserDefine2,
				I.UserDefine3,
				I.UserDefine4,
				I.UserDefine5
		FROM 	QP_RepairItems I(NOLOCK)
		LEFT JOIN (
				SELECT	TypeId,
						FullName
				FROM	Qp_RepairAutoType(NOLOCK)
		)A ON I.RepairAutoTypeID = A.TypeId
		WHERE 	I.XiWaMaxNumber >= @XiWaMaxNumber
	END
ELSE IF @DbName = 'wcitype'		--维修车辆信息档案
	BEGIN
		SELECT 	I.TypeId,
				I.ParId,
				I.SonNum,
				I.platenumber,
				A.FullName AS afullname,
				I.enginenumber,
				I.framenumber,
				I.transmissionnumber,
				I.vin,
				I.color,
				CASE WHEN I.recorddate='1900-01-01' THEN NULL ELSE CONVERT(VARCHAR(10),I.recorddate,120) END AS recorddate,
				CASE WHEN I.forcemaintaindate='1900-01-01' THEN NULL ELSE CONVERT(VARCHAR(10),I.forcemaintaindate,120) END AS forcemaintaindate,
				I.forcemaintainmileage,
				CASE WHEN I.firstmaintaindate='1900-01-01' THEN NULL ELSE CONVERT(VARCHAR(10),I.firstmaintaindate,120) END AS firstmaintaindate,
				I.firstmaintainmileage,
				I.comment,
				I.leavefactorynum,
				CASE WHEN I.leavefactorydate='1900-01-01' THEN NULL ELSE CONVERT(VARCHAR(10),I.leavefactorydate,120) END AS leavefactorydate,
				I.driver,
				I.drivermobilephone,
				I.cardnumber,
				I.PYCode,
				C.FullName AS cfullname
		FROM 	QP_RepairAutoInfo I(NOLOCK),
				QP_RepairAutoType A(NOLOCK),
				QP_ChargingStandards C(NOLOCK)
		WHERE 	I.RepairAutoTypeId = A.TypeId
				AND I.ChargingStandardsId = C.[ID]
				AND I.XiWaMaxNumber >= @XiWaMaxNumber
	END
ELSE IF @DbName='stype'
BEGIN
	SET @tempSQL=@tSQL+' SELECT	a.TypeId,
			a.parid,
			a.leveal,
			a.sonnum,
			a.soncount,
			a.FullName,
			a.[Name],
			a.UserCode,
			a.Comment,
			a.LinkMan,
			a.[Address],
			a.Tel,
			a.PostCode,
			a.TaxNo,
			a.Bank,
			a.Account,
			a.deleted,
			a.PyCode,
			a.BTypeID1,
			a.BTypeID2,
			a.PriceType,
			(CASE  WHEN a.priceType=''0'' THEN ''商品物价信息'' ELSE ''本分支机构物价信息'' END ) AS pricetypefull,
			(SELECT fullname FROM btype(NOLOCK) where typeId= a.btypeid1 ) as btype1full,
			(SELECT usercode FROM btype(NOLOCK) where typeId= a.btypeid1 ) as btype1usercode,
			(SELECT fullname FROM btype(NOLOCK) where typeId= a.BTypeID2 ) as btype2full,
			(SELECT usercode FROM btype(NOLOCK) where typeId= a.btypeid2 ) as btype2usercode,'
	IF @RE=1
		SET	@tempSQL=@tempSQL+@strSelect+','
	SET	@tempSQL=@tempSQL+'	
			a.XiWaMaxNumber
	  FROM	[SType] a(NOLOCK)'
	IF @RE=1
		SET	@tempSQL=@tempSQL+' left join #TC t ON a.TypeId=t.Tid '
	SET	@tempSQL=@tempSQL+'
	  WHERE	XiWaMaxNumber >= '+CAST(@XiWaMaxNumber AS VARCHAR(50))
	IF @RE=1
		SET @tempSQL=@tempSQL+ '	
	  DROP table #TC	'
	  EXEC(@tempSQL)
END 
else IF @DbName='acaccount'
BEGIN	
	SELECT	a.TypeId,
			a.KeyId,
			a.ParId,
			a.Leveal,
			a.SonNum,
			a.SonCount,
			a.UserCode,
			a.FullName,
			a.Name,
			a.PyCode,
			s.FullName as sfullname,
			CASE a.fdc WHEN 1 THEN '借' 
					   WHEN -1 THEN '贷'
			END AS fdc,
			CASE a.cid WHEN -1 THEN '不核算' 
					   WHEN 0 THEN '所有'
					   ELSE b.FullName
			END AS cid,
			CASE WHEN a.IsCash = 1 THEN '现金' 
				 WHEN a.IsBank = 1 THEN '银行'
				 WHEN a.IsOther = 1 THEN '其他货币资金'
				 ELSE ''
			END AS moneytype,
			dbo.F_GetAc_Assist_CheckItems_FullName(a.TypeId,a.StypeId) AS assistcheckitem,
			a.XiWaMaxNumber
	FROM 	Ac_Account(NOLOCK) a
			LEFT JOIN  stype s ON a.StypeId=s.TypeId
			LEFT JOIN Ac_Currency b ON b.CId=a.cid
	WHERE 	a.XiWaMaxNumber >=@XiWaMaxNumber
END
else IF @DbName='cargotype'
BEGIN
	SELECT	a.CargoID,
			a.UserCode,
			a.FullName,
			a.Comment,
			a.PyCode,
			a.KtypeID
			--,s.FullName AS kfullname
	FROM 	CargoType(NOLOCK) a
			--LEFT JOIN  stock s ON a.KtypeID=s.TypeId
	WHERE 	a.XiWaMaxNumber >=@XiWaMaxNumber
END
else IF @DbName='banktype'
BEGIN
	SELECT	a.id as typeid,
			a.UserCode,
			a.FullName,
			a.Comment
			--,s.FullName AS kfullname
	FROM 	Te_BankAccount(NOLOCK) a
			--LEFT JOIN  stock s ON a.KtypeID=s.TypeId
	WHERE 	a.XiWaMaxNumber >=@XiWaMaxNumber
END

ELSE IF @DbName = 'posinfo'		--pos信息
	BEGIN
		SELECT 	posid,usercode,fullname 
		FROM 	posinfo(NOLOCK)
		WHERE 	XiWaMaxNumber >= @XiWaMaxNumber
	END
ELSE IF @DbName='assets' --固定资产卡片
BEGIN
    SELECT  aa.id AS cardid,
			aa.typeid,
			aa.usercode,
			aa.fullname,
			aa.stypeid,
			aa.finishwork,
			aa.workunit,
			aa.expectwork,
			s.UserCode as stypeusercode,
			s.fullname AS stypename,
			aa.dtypeid,
			d.usercode AS dtypeusercode,
			d.fullname AS dtypename,
			CONVERT(VARCHAR(10),inaccountdate,120) AS inaccountdate,
			aa.categoryid,
			aac.fullname AS categorytype,
			aa.locationid,
			al.LocatiON,
			aa.barcode,
			aa.ConditionId,
			awc.Comment AS conditionfullname,
			aa.BusinessTypeId,
			abt.FullName as businesstypename,
			aa.AssertATypeId as assertatypeid,
			(SELECT UserCode FROM Ac_Account WHERE TypeId=AA.AssertATypeId AND Ac_Account.StypeId=s.VerifyID) AS assertusercode,
			(SELECT FullName FROM Ac_Account WHERE TypeId=AA.AssertATypeId AND Ac_Account.StypeId=s.VerifyID) AS assertfullname,
			aa.DepATypeId,
			(SELECT usercode FROM Ac_Account WHERE TypeId=aa.DepATypeId AND Ac_Account.StypeId=s.VerifyID) AS depusercode,
			(SELECT FullName FROM Ac_Account WHERE TypeId=aa.DepATypeId AND Ac_Account.StypeId=s.VerifyID) AS depfullname,
			aa.DisATypeId,
			(SELECT usercode FROM Ac_Account WHERE TypeId=aa.DisATypeId  AND Ac_Account.StypeId=s.VerifyID) AS disusercode,
			(SELECT FullName FROM Ac_Account WHERE TypeId=aa.DisATypeId  AND Ac_Account.StypeId=s.VerifyID) AS disfullname,
			aa.DevalueATypeId,
			(SELECT usercode FROM Ac_Account WHERE TypeId=aa.DevalueATypeId  AND Ac_Account.StypeId=s.VerifyID) AS devalueusercode,
			(SELECT FullName FROM Ac_Account WHERE TypeId=aa.DevalueATypeId  AND Ac_Account.StypeId=s.VerifyID) AS devaluefullname,
			aa.XiWaMaxNumber
			--aa.AssetsState,
			--acs.Comment as assetsstatename,
			--aa.comment 
	FROM Ac_ASsetsCards aa 
	JOIN stype s ON aa.stypeid=s.typeid 
	JOIN Department d ON aa.DTypeid=d.typeid 
	JOIN Ac_ASsetsCategory aac ON aa.CategoryId=aac.Id 
	LEFT JOIN Ac_ASsetStorageLocatiON al ON aa.LocatiONId=al.ID 
	JOIN Ac_AssetsCardsState acs on acs.Id=aa.AssetsState 
	LEFT JOIN Ac_AssetWorkingCondition awc on awc.Id=aa.ConditionId
	JOIN Ac_AssetBusinessType abt on abt.Id=aa.BusinessTypeId
	WHERE aa.XiWaMaxNumber>=@XiWaMaxNumber
END
ELSE
BEGIN
	SET @SQL = 'SELECT  '
	IF @DbName='Ac_Items'
	BEGIN
		SET @SQL +=' usercode as cusercode,fullname as cfullname,'
	END
	SET @SQL +=' * FROM 	'+@DbName+'(NOLOCK)
				WHERE	XiWaMaxNumber >= '+CAST(@XiWaMaxNumber AS varchar(100))				
	
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	--PRINT(@SQL)
	EXEC(@SQL)
	
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalBTypeSaleDist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalBTypeSaleDist]
GO





/*
	Web_CalBTypeSaleDist '00001','2006-1-1','2006-5-29','00000','00000','305,11,45,141,155,157',0,140000,1,10,1,0
	作者：谢吉康
	日期：2005-8-9
	描述：单位销售分布
*/
CREATE PROCEDURE Web_CalBTypeSaleDist
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@PTypeId		varchar(100),	--商品Id
	@BTypeId		varchar(100),	--部门Id
	@BillType		varchar(100),	--单据类型
	@nType			varchar(10),	--金额的查询方式
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@showZero		varchar(5)		--0.不显示红冲单据   1.显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @showZero = 1
	SET @showZero = '0,1,2'

IF @BTypeId = '00000'
	SET @BTypeId = '%'

DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@SQL1			varchar(8000),
		@SQL2			varchar(8000),
		@SQL3			varchar(8000),
		@SQL4			varchar(8000),
		@SQL5			varchar(8000),
		@PTypeIdMx		varchar(100)

IF @PTypeId = '00000'
	SET @PTypeIdMx = '%'
ELSE
	SET @PTypeIdMx = @PTypeId

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		typeid 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计数量,总计金额)VALUES(0,0,0,0)'

EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************
--压缩BillIndex表
CREATE TABLE #BillIndex
(
	BillNumberId 	numeric(18,0),
	BTypeId			varchar(50),
	RedWord			int
)
--压缩商品表
CREATE TABLE #PType
(
	TypeId varchar(50)
)
--压缩销售明细表
CREATE TABLE #SaleBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 	
)
--压缩零售明细
CREATE TABLE #retailBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩销售退货明细
CREATE TABLE #SaleBackBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩代销明细
CREATE TABLE #CommissionBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩换货明细
CREATE TABLE #GoodsExchangeBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩维修明细
CREATE TABLE #RepairDealDetail
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩销售换货单明细
CREATE TABLE #SaleGoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	BTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
SET @SQL = '
	INSERT INTO	#BillIndex
	SELECT	Bil.BillNumberId,
			Bil.BTypeId,
			Bil.RedWord	
	FROM	BillIndex Bil
	WHERE	Bil.IfCheck = ''t''
			AND Bil.Draft = 0

			AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
			AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
			AND Bil.BillType IN ('+@BillType+')
			AND Bil.RedWord IN ('+@showZero+')
			AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
			AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 '

EXEC(@SQL)

INSERT INTO #PType
SELECT	TypeId
FROM	PType
WHERE	Deleted = 0
		AND SonNum  = 0	
-------------------------处理含税金额
IF @nType = 0
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO	#SaleBill
					SELECT	Bil.RedWord,
							Bil.BTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal
					FROM	BillIndex Bil,
							SaleBill S
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.BillType IN ('+@BillType+')
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 
					GROUP BY Bil.RedWord,Bil.BTypeId '
				
				EXEC(@SQL)
			END

		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('45',@BillType)<>0
			BEGIN
				INSERT INTO #SaleBackBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN
				INSERT INTO #SaleGoodsExchangeBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	SaleGoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.InOrOut = 'o'
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId

				INSERT INTO #SaleGoodsExchangeBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						-1*SUM(S.Qty) AS Qty,
						-1*SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	SaleGoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.InOrOut = 'i'
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END
	END
ELSE
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO	#SaleBill
					SELECT	Bil.RedWord,
							Bil.BTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal
					FROM	BillIndex Bil,
							SaleBill S
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.BillType IN ('+@BillType+')
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 
					GROUP BY Bil.RedWord,Bil.BTypeId '
				
				EXEC(@SQL)
			END		
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('45',@BillType)<>0
			BEGIN
				INSERT INTO #SaleBackBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN
				INSERT INTO #SaleGoodsExchangeBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	SaleGoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.InOrOut = 'o'
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId

				INSERT INTO #SaleGoodsExchangeBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						-1*SUM(S.Qty) AS Qty,
						-1*SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	SaleGoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.InOrOut = 'i'
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END
	END
--********************************************************************************以上压缩数据***************************************************************
SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET [总计数量] = ISNULL(X.Qty,0),
			[总计金额] = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
			SELECT	B.PTypeId,
					ISNULL(SUM(B.Qty),0) AS Qty,
					ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBill S						
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#retailBill S '
				SET @SQL1 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
									ELSE ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
									ELSE ISNULL(S.TaxTotal,0)
								END AS Total	
						FROM 	#SaleBackBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#CommissionBill S '
				SET @SQL2 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#GoodsExchangeBill S						
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)

									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#RepairDealDetail S 
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleGoodsExchangeBill S
			)B GROUP BY B.PTypeId
		)X ON (X.PTypeId = A.TypeId OR A.TypeId=0) '

--PRINT(@SQL+@SQL1+@SQL2)
EXEC(@SQL+@SQL1+@SQL2)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    BType 
	    WHERE  	SonNum = 0
				AND Deleted = 0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	BType
					WHERE 	SonNum = 0
							AND Deleted = 0
							AND TypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND (TypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR TypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
	                ORDER BY
							UserCode
	            )
				AND TypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
				AND (TypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR TypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
	    ORDER BY UserCode '

	EXEC(@SQLCursor)
	
	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @BaseTypeId = '99999'
				SET @xjkang = '谢吉康'

			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '数量]  NUMERIC(24, 10) '
			EXEC(@SQL)
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '金额]  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'数量] = ISNULL(X.Qty,0),
						['+@BaseFullName+'金额] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	B.PTypeId,
								ISNULL(SUM(B.Qty),0) AS Qty,
								ISNULL(SUM(B.Total),0) AS Total
						FROM	(
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#retailBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL2 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
												ELSE ISNULL(S.Qty,0)
											END AS Qty,
											CASE

												WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
												ELSE ISNULL(S.TaxTotal,0)
											END AS Total	
									FROM 	#SaleBackBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#CommissionBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL3 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#GoodsExchangeBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#RepairDealDetail S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleGoodsExchangeBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
								)B GROUP BY B.PTypeId
					)X ON (X.PTypeId = A.TypeId OR A.TypeId=0) '
			
			--PRINT(@SQL+@SQL2+@SQL3)
			EXEC(@SQL+@SQL2+@SQL3)
	
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		int,
		@BaseInfoCount 	int,
		@pSonNum 		int,
		@TotalpPages	int,	--商品页数
		@TotalbPages	int		--基本信息页数

SELECT @pSonNum = SonNum FROM PType WHERE TypeId = @PTypeId AND Deleted = 0 AND TypeId LIKE @MPTypeId + '%'

IF @pSonNum = 0 
	SELECT	@PTypeCount = COUNT(*)
	FROM	PType
	WHERE	Deleted = 0
			AND TypeId LIKE @PTypeId + '%' 
			AND TypeId LIKE @MPTypeId + '%'
ELSE
	SELECT	@PTypeCount = COUNT(*)
	FROM	PType
	WHERE	Deleted = 0
			AND ParId = @PTypeId
			AND TypeId LIKE @MPTypeId + '%'
		
IF @PTypeCount%14<>0 
    SET @TotalpPages=@PTypeCount/14+1
ELSE
    SET @TotalpPages=@PTypeCount/14

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@TotalpPages AS varchar(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*) FROM BType WHERE SonNum = 0 AND Deleted = 0 AND TypeId LIKE @BTypeId + '%' AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@TotalbPages AS varchar(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)


--删除定义的临时表
DROP TABLE #PType,#BillIndex,#SaleBill,#retailBill,#CommissionBill,#GoodsExchangeBill,#RepairDealDetail,#SaleGoodsExchangeBill
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BillIndex0]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[BillIndex0]
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalBTypeSaleDistLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalBTypeSaleDistLine]
GO










/*
	作者：谢吉康
	日期：2005-8-9
	描述：单位销售分布
*/
CREATE PROCEDURE Web_CalBTypeSaleDistLine
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@PTypeId		varchar(100),	--商品Id
	@BTypeId		varchar(100),	--部门Id
	@BillType		varchar(100),	--单据类型
	@nType			varchar(10),	--金额的查询方式
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@showZero		varchar(5)		--0.不显示红冲单据   1.显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SET @showZero = 0
IF @showZero = 1
	SET @showZero = '0,1,2'

IF @BTypeId = '00000'
	SET @BTypeId = '%'

DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@SQL1			varchar(8000),
		@SQL2			varchar(8000),
		@SQL3			varchar(8000),
		@SQL4			varchar(8000),
		@PTypeIdMx		varchar(100)

IF @PTypeId = '00000'
	SET @PTypeIdMx = @MPTypeId
ELSE
	SET @PTypeIdMx = @PTypeId

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		typeid 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计数量,总计金额)VALUES(0,0,0,0)'

EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************
--压缩BillIndex表
CREATE TABLE #BillIndex
(
	BillNumberId 	numeric(18,0),
	BTypeId			varchar(50),
	RedWord			int
)
--压缩商品表
CREATE TABLE #PType
(
	TypeId varchar(50)
)
--压缩销售明细表
CREATE TABLE #SaleBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 	
)
--压缩零售明细
CREATE TABLE #retailBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩销售退货明细
CREATE TABLE #SaleBackBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩代销明细
CREATE TABLE #CommissionBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩换货明细
CREATE TABLE #GoodsExchangeBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩维修明细
CREATE TABLE #RepairDealDetail
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩销售换货单明细
CREATE TABLE #SaleGoodsExchangeBill
(
	RedWord		int,
	BTypeId		varchar(50),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
SET @SQL = '
	INSERT INTO	#BillIndex
	SELECT	BillNumberId,
			BTypeId,
			RedWord	
	FROM	BillIndex
	WHERE	IfCheck = ''t''
			AND Draft = 0
			AND BillType IN ('+@BillType+')
			AND RedWord IN ('+@showZero+')
			AND BillDate>='+char(39)+@StartDate+char(39)+'
			AND BillDate<='+char(39)+@EndDate+char(39)+'			
			AND BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
			AND ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND (KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR KTypeId = ''10000'')
			AND (BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 
			AND BillType <> 160 '

EXEC(@SQL)

INSERT INTO #PType
SELECT	TypeId
FROM	PType
WHERE	Deleted = 0
		AND SonNum  = 0
		AND TypeId LIKE @PTypeIdMx+'%'
		AND TypeId LIKE @MPTypeId+'%'
-------------------------处理含税金额
IF @nType = 0
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO	#SaleBill
					SELECT	Bil.RedWord,
							Bil.BTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal
					FROM	#BillIndex Bil,
							SaleBill S,
							#PType P
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND P.TypeId = S.PTypeId
					GROUP BY Bil.RedWord,Bil.BTypeId '
				
				EXEC(@SQL)
			END

		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		

		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	Bil.RedWord,
							Bil.BTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S,
							BillIndex Bil,
							#PType P
					WHERE	S.PTypeId = P.TypeId
							AND Bil.BillNumberId = S.BillNumberId
							AND S.PTypeId IN (SELECT DISTINCT PTypeId FROM InOutStockTable WHERE BillType = 160 AND Qty<=0 AND BillNumberId = Bil.BillNumberId AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+')
							AND S.InOrOut = ''o''
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'							
							AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY Bil.RedWord,Bil.BTypeId,S.InOrOut '

				EXEC(@SQL)

				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	Bil.RedWord,
							Bil.BTypeId,
							-1*SUM(S.Qty) AS Qty,
							-1*SUM(S.TaxTotal) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S,
							BillIndex Bil,
							#PType P
					WHERE	S.PTypeId = P.TypeId
							AND Bil.BillNumberId = S.BillNumberId
							AND S.PTypeId IN (SELECT DISTINCT PTypeId FROM InOutStockTable WHERE BillType = 160 AND Qty>=0 AND BillNumberId = Bil.BillNumberId AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+')
							AND S.InOrOut = ''i''
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'							
							AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY Bil.RedWord,Bil.BTypeId,S.InOrOut '

				EXEC(@SQL)
			END
	END
ELSE
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO	#SaleBill
					SELECT	Bil.RedWord,
							Bil.BTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.Total) AS TaxTotal
					FROM	#BillIndex Bil,
							SaleBill S,
							#PType P
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND P.TypeId = S.PTypeId
					GROUP BY Bil.RedWord,Bil.BTypeId '
				
				EXEC(@SQL)
			END		
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END

		IF CharIndex('45',@BillType)<>0
			BEGIN					
				INSERT INTO #SaleBackBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END		
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	Bil.RedWord,
						Bil.BTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.BTypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	Bil.RedWord,
							Bil.BTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.Total) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S,
							BillIndex Bil,
							#PType P
					WHERE	S.PTypeId = P.TypeId
							AND Bil.BillNumberId = S.BillNumberId
							AND S.PTypeId IN (SELECT DISTINCT PTypeId FROM InOutStockTable WHERE BillType = 160 AND Qty<=0 AND BillNumberId = Bil.BillNumberId AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+')
							AND S.InOrOut = ''o''
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY Bil.RedWord,Bil.BTypeId,S.InOrOut '

				EXEC(@SQL)

				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	Bil.RedWord,
							Bil.BTypeId,
							-1*SUM(S.Qty) AS Qty,
							-1*SUM(S.Total) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S,
							BillIndex Bil,
							#PType P
					WHERE	S.PTypeId = P.TypeId
							AND Bil.BillNumberId = S.BillNumberId
							AND S.PTypeId IN (SELECT DISTINCT PTypeId FROM InOutStockTable WHERE BillType = 160 AND Qty>=0 AND BillNumberId = Bil.BillNumberId AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+')
							AND S.InOrOut = ''i''
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'							
							AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY Bil.RedWord,Bil.BTypeId,S.InOrOut '

				EXEC(@SQL)
			END
	END
--********************************************************************************以上压缩数据***************************************************************
SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET [总计数量] = ISNULL(X.Qty,0),
			[总计金额] = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
			SELECT	B.PTypeId,
					ISNULL(SUM(B.Qty),0) AS Qty,
					ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#retailBill S '
				SET @SQL1 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
									ELSE ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
									ELSE ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBackBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#CommissionBill S '

				SET @SQL2 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#GoodsExchangeBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#RepairDealDetail S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleGoodsExchangeBill S
					)B GROUP BY B.PTypeId
		)X ON (X.PTypeId = A.TypeId OR A.TypeId=0)'


--PRINT(@SQL+@SQL1+@SQL2)
EXEC(@SQL+@SQL1+@SQL2)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    BType 
	    WHERE  	SonNum = 0
				AND Deleted = 0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	BType
					WHERE 	SonNum = 0
							AND Deleted = 0
							AND TypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND (TypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR TypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
	                ORDER BY
							UserCode
	            )
				AND TypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
				AND (TypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR TypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
	    ORDER BY UserCode '

	EXEC(@SQLCursor)
	
	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @BaseTypeId = '99999'
				SET @xjkang = '谢吉康'

			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '数量]  NUMERIC(24, 10) '
			EXEC(@SQL)
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '金额]  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'数量] = ISNULL(X.Qty,0),
						['+@BaseFullName+'金额] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	B.PTypeId,
								ISNULL(SUM(B.Qty),0) AS Qty,
								ISNULL(SUM(B.Total),0) AS Total
						FROM	(
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#retailBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL2 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
												ELSE ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
												ELSE ISNULL(S.TaxTotal,0)
											END AS Total	
									FROM 	#SaleBackBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#CommissionBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL3 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#GoodsExchangeBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#RepairDealDetail S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleGoodsExchangeBill S
									WHERE	S.BTypeId = '+char(39)+@BaseTypeId+char(39)+'
								)B GROUP BY B.PTypeId
					)X ON (X.PTypeId = A.TypeId OR A.TypeId=0) '
			
			--PRINT(@SQL+@SQL2+@SQL3)
			EXEC(@SQL+@SQL2+@SQL3)
	
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		int,
		@BaseInfoCount 	int,
		@pSonNum 		int,
		@TotalpPages	int,	--商品页数
		@TotalbPages	int		--基本信息页数

IF @PTypeId = '00000'
	SET @PTypeId = '%'

SELECT	@PTypeCount = COUNT(*)
FROM	PType
WHERE	Deleted = 0
		AND SonNum = 0
		AND TypeId LIKE @PTypeId + '%' 
		AND TypeId LIKE @MPTypeId + '%' 

		
IF @PTypeCount%14<>0 
    SET @TotalpPages=@PTypeCount/14+1
ELSE
    SET @TotalpPages=@PTypeCount/14

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@TotalpPages AS varchar(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*) FROM BType WHERE SonNum = 0 AND Deleted = 0 AND TypeId LIKE @BTypeId + '%' AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@TotalbPages AS varchar(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)

--删除定义的临时表
DROP TABLE #PType,#BillIndex,#SaleBill,#retailBill,#CommissionBill,#GoodsExchangeBill,#RepairDealDetail

RETURN 0






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalculateCostPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalculateCostPrice]
GO








/*
	功能说明：	根据不同的成本算法返回一定数量在一定仓库的成本价
	返回结果：	成本单价
	作    者：	徐辉
	创建时间：	2004-5-27
	修改历史：
*/
CREATE                       PROCEDURE Web_CalculateCostPrice(
	@chvPtypeId	varchar(50),		--商品Id
	@chvKtypeId varchar(50),		--仓库Id
	@decQty		 NUMERIC(24, 10) ,	--商品数量
	@intCosting	int,			--成本算法:0,移动加权平均;1,先进先出;2,后进先出
	@BillType int=-1,
	@BillNumberId int=-1
)
--@encode$--
As
SET NOCOUNT ON 
DECLARE	@decCostingPrice  NUMERIC(24, 10) ,		--商品成本价
		@intAverageCostPrice int,			--各仓库商品成本均价是否一致
		@chvSql	varchar(2000)	
			
IF @intCosting = 0 		--移动加权平均
BEGIN

	IF @BillNumberId = -1
	BEGIN
		SELECT TOP 1 @intAverageCostPrice=value FROM Userconfig WHERE ConfigName='AverageCostPrice'
		IF @intAverageCostPrice=0 	--各仓库商品成本均价不一致
		BEGIN
			SET @chvSql='SELECT CostPrice = ISNULL((cast(SUM(Total)AS Numeric(22,10)) / CASE WHEN SUM(QTY) = 0 THEN NULL ELSE cast(SUM(QTY)AS Numeric(22,10)) END),0)
						 FROM	GoodsStocks
						 WHERE  kTypeId=''' + @chvKtypeId + ''' AND Ptypeid='''+@chvPtypeId+''''
		END
		ELSE
		BEGIN
			SET @chvSql='SELECT CostPrice = (cast(SUM(Total)AS Numeric(22,10)) / CASE WHEN SUM(QTY) = 0 THEN NULL ELSE cast(SUM(QTY)AS Numeric(22,10)) END)
						 FROM	GoodsStocks
						 WHERE  Ptypeid='''+@chvPtypeId+''''
		END
		EXEC(@chvSql)
	END
	ELSE
	BEGIN
		SELECT CostPrice From InOutstocktable WHERE BillNumberId=@BillnumberId AND BillType=@BillType
		AND Ktypeid=@chvKtypeId AND Ptypeid=@chvPtypeId
	END
	RETURN
END


DECLARE 
		@decSumQty		 NUMERIC(24, 10) ,
		@decQtyCursor	 NUMERIC(24, 10) ,
		@decSumQtyTemp	 NUMERIC(24, 10) ,
		@decSumTotal	 NUMERIC(24, 10) ,
		@decSumTotalTemp	 NUMERIC(24, 10) ,
		@decTotalCursor		 NUMERIC(24, 10) ,
		@intOrderCursor		int
CREATE TABLE #TempGoodsStocks(Qty  NUMERIC(24, 10) ,Total  NUMERIC(24, 10) ,GoodsOrder int)


DECLARE @TotalDigit INT

SELECT @TotalDigit = DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName = 'total'

IF @intCosting = 1		--先进先出
BEGIN
	SET	@decSumQty=0
	SET	@decSumQtyTemp=0
	SET	@decSumTotal=0
	SET	@decSumTotalTemp=0
	SET @chvSql='DECLARE CostPrice_Cursor CURSOR FOR				
					 SELECT  Qty,Total,GoodsOrder 
					 FROM GoodsStocks 
					 WHERE Ptypeid ='''+ @chvPtypeId + ''' 
						  AND Ktypeid ='''+ @chvKtypeId + ''' ORDER BY GoodsOrder' 
	
	EXEC(@chvSql)
	OPEN CostPrice_Cursor          --打开游标
	FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
	WHILE  @@FETCH_STATUS = 0	AND @decSumQty < @decQty   --循环写入临时表
	BEGIN 
		INSERT INTO #TempGoodsStocks VALUES(@decQtyCursor,@decTotalCursor,@intOrderCursor)
		SELECT @decSumQty=SUM(Qty),@decSumTotal=SUM(Total) FROM #TempGoodsStocks
		IF @decQty<=@decSumQty 	OR  @decSumQty=0--加了该批次就大于调拨数量了,或者没有库存
			BREAK
		SET	@decSumQtyTemp=@decSumQty
		SET @decSumTotalTemp=@decSumTotal
		FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
	END
	CLOSE CostPrice_Cursor 
    	DEALLOCATE CostPrice_Cursor
 	DROP TABLE #TempGoodsStocks
	IF @decSumQty <= @decQty  --库存商品数量小于调拨数量
	BEGIN
		IF @decSumQty=0
			SET @decCostingPrice=0
		ELSE
			SET @decCostingPrice=@decSumTotal/@decSumQty
	END
	IF @decSumQty > @decQty         --库存商品数量大于调拨数量
	BEGIN
		SET @decCostingPrice=(ROUND((@decSumTotal-@decSumTotalTemp)/(@decSumQty-@decSumQtyTemp)*(@decQty-@decSumQtyTemp),@TotalDigit) + @decSumTotalTemp)/@decQty
	END
	SELECT @decCostingPrice AS CostPrice
	RETURN
END

IF @intCosting = 2		--后进先出
BEGIN
	SET	@decSumQty=0
	SET	@decSumQtyTemp=0
	SET	@decSumTotal=0
	SET	@decSumTotalTemp=0
	
	SET @chvSql='DECLARE CostPrice_Cursor CURSOR FOR				
					 SELECT  Qty,Total,GoodsOrder 
					 FROM GoodsStocks 
					 WHERE Ptypeid ='''+ @chvPtypeId + ''' 
						  AND Ktypeid ='''+ @chvKtypeId + ''' ORDER BY GoodsOrder DESC'
	EXEC(@chvSql)
	OPEN CostPrice_Cursor          --打开游标
	FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
	WHILE  @@FETCH_STATUS = 0	AND @decSumQty < @decQty   --循环写入临时表
	BEGIN  
		INSERT INTO #TempGoodsStocks VALUES(@decQtyCursor,@decTotalCursor,@intOrderCursor)
		SELECT @decSumQty=SUM(Qty),@decSumTotal=SUM(Total) 
		FROM
			#TempGoodsStocks
		IF @decQty<=@decSumQty 	OR @decSumQty=0	--加了该批次就大于调拨数量了
			BREAK
		SET	@decSumQtyTemp=@decSumQty
		SET @decSumTotalTemp=@decSumTotal
		FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
	END
	CLOSE CostPrice_Cursor 
    DEALLOCATE CostPrice_Cursor

	DROP TABLE #TempGoodsStocks

	IF @decSumQty <= @decQty  --库存商品数量小于调拨数量
	BEGIN
		IF @decSumQty=0
			SET @decCostingPrice=0
		ELSE
			SET @decCostingPrice=@decSumTotal/@decSumQty
	END
	IF @decSumQty > @decQty         --库存商品数量大于调拨数量
		SET @decCostingPrice=(ROUND((@decSumTotal-@decSumTotalTemp)/(@decSumQty-@decSumQtyTemp)*(@decQty-@decSumQtyTemp),@TotalDigit)+@decSumTotalTemp)/@decQty
	SELECT @decCostingPrice AS CostPrice
	RETURN
END
IF @intCosting = 3		--手工指定法
BEGIN
	DECLARE @Stypeid varchar(100)
	DECLARE @recPrice  NUMERIC(24, 10) 
	
	SELECT @Stypeid=stypeid FROM Stock where typeId=@chvKtypeId
	
	SELECT @recPrice=recPrice FROM PType_STypePrice WHERE ptypeId=@chvPtypeId and STypeID=@Stypeid
	IF @recPrice=0
		SELECT NULL AS CostPrice FROM Ptype WHERE typeId=@chvPtypeId
	ELSE
		SELECT recPrice AS CostPrice FROM PType_STypePrice WHERE ptypeId=@chvPtypeId
	RETURN
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalculateCostPrice1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalculateCostPrice1]
GO














/*
	功能说明：	根据不同的成本算法返回一定数量在一定仓库的成本价
	返回结果：	成本单价
	作    者：	徐辉 
	创建时间：	2004-5-27
	修改  cqhua 2006-04-06
	修改历史：
*/



CREATE                   PROCEDURE Web_CalculateCostPrice1(
	@chvPtypeId	varchar(50),		--商品Id
	@chvKtypeId varchar(50),		--仓库Id
	@decQty		 NUMERIC(24, 10) ,	--商品数量
	@intCosting	int	,--成本算法
								--0：移动加权平均
								--1：先进先出
								--2：后进先出
	@CostPrice       NUMERIC(24, 10)  output  --返回成本

)
--@encode$--
As
SET NOCOUNT ON 
DECLARE	@decCostingPrice  NUMERIC(24, 10) ,		--商品成本价
		@intAverageCostPrice int,			--各仓库商品成本均价是否一致
		@chvSql	varchar(2000)	
			
IF @intCosting = 0 		--移动加权平均
BEGIN
	CREATE TABLE TempCostPrice(Costprice  NUMERIC(24, 10) )
	SELECT @intAverageCostPrice=value FROM Userconfig WHERE ConfigName='AverageCostPrice'
	IF @intAverageCostPrice=0 	--各仓库商品成本均价不一致
	BEGIN
		SET @chvSql='SELECT CostPrice = ISNULL((SUM(Total) / CASE WHEN SUM(QTY) = 0 THEN NULL ELSE SUM(QTY) END),0)
					 FROM	GoodsStocks
					 WHERE  kTypeId=''' + @chvKtypeId + ''' AND Ptypeid='''+@chvPtypeId+''''
	END
	ELSE
	BEGIN
		SET @chvSql='SELECT CostPrice = ISNULL((SUM(Total) / CASE WHEN SUM(QTY) = 0 THEN NULL ELSE SUM(QTY) END),0)
					 FROM	GoodsStocks
					 WHERE  Ptypeid='''+@chvPtypeId+''''
	END
	SET @chvSql ='INSERT INTO TempCostPrice SELECT *  FROM ('+@chvSql+') D '
	--PRINT @chvSql
	EXEC(@chvSql)
	--SELECT * FROM TempCostPrice
	SELECT @decCostingPrice = CostPrice FROM TempCostPrice
	DROP TABLE TempCostPrice
	
	SET @CostPrice= @decCostingPrice
	RETURN
	
	
END


DECLARE 
		@decSumQty		 NUMERIC(24, 10) ,
		@decQtyCursor	 NUMERIC(24, 10) ,
		@decSumQtyTemp	 NUMERIC(24, 10) ,
		@decSumTotal	 NUMERIC(24, 10) ,
		@decSumTotalTemp	 NUMERIC(24, 10) ,
		@decTotalCursor		 NUMERIC(24, 10) ,
		@intOrderCursor		int
CREATE TABLE #TempGoodsStocks(Qty  NUMERIC(24, 10) ,Total  NUMERIC(24, 10) ,GoodsOrder int)

IF @intCosting = 1		--先进先出
BEGIN
	SET	@decSumQty=0
	SET	@decSumQtyTemp=0
	SET	@decSumTotal=0
	SET	@decSumTotalTemp=0
	SET @chvSql='DECLARE CostPrice_Cursor CURSOR FOR				
					 SELECT  Qty,Total,GoodsOrder 
					 FROM GoodsStocks 
					 WHERE Ptypeid ='''+ @chvPtypeId + ''' 
						  AND Ktypeid ='''+ @chvKtypeId + ''' ORDER BY GoodsOrder' 
	
	EXEC(@chvSql)
	OPEN CostPrice_Cursor          --打开游标
	FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
	WHILE  @@FETCH_STATUS = 0	AND @decSumQty < @decQty   --循环写入临时表
	BEGIN 
		INSERT INTO #TempGoodsStocks VALUES(@decQtyCursor,@decTotalCursor,@intOrderCursor)
		SELECT @decSumQty=SUM(Qty),@decSumTotal=SUM(Total) FROM #TempGoodsStocks
		IF @decQty<=@decSumQty 	OR  @decSumQty=0--加了该批次就大于调拨数量了,或者没有库存
			BREAK
		SET	@decSumQtyTemp=@decSumQty
		SET @decSumTotalTemp=@decSumTotal
		FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
	END
	CLOSE CostPrice_Cursor 
    DEALLOCATE CostPrice_Cursor
 	DROP TABLE #TempGoodsStocks
	IF @decSumQty <= @decQty  --库存商品数量小于调拨数量
	BEGIN
		IF @decSumQty=0
			SET @decCostingPrice=0
		ELSE
			SET @decCostingPrice=@decSumTotal/@decSumQty
	END
	IF @decSumQty > @decQty         --库存商品数量大于调拨数量
	BEGIN
		SET @decCostingPrice=(ROUND((@decSumTotal-@decSumTotalTemp)/(@decSumQty-@decSumQtyTemp)*(@decQty-@decSumQtyTemp),2) + @decSumTotalTemp)/@decQty
	END
	SELECT @decCostingPrice AS CostPrice
	SET @CostPrice =@decCostingPrice
	RETURN 
END

IF @intCosting = 2		--后进先出
BEGIN
	SET	@decSumQty=0
	SET	@decSumQtyTemp=0
	SET	@decSumTotal=0
	SET	@decSumTotalTemp=0
	
	SET @chvSql='DECLARE CostPrice_Cursor CURSOR FOR				
					 SELECT  Qty,Total,GoodsOrder 
					 FROM GoodsStocks 
					 WHERE Ptypeid ='''+ @chvPtypeId + ''' 
						  AND Ktypeid ='''+ @chvKtypeId + ''' ORDER BY GoodsOrder DESC'
	EXEC(@chvSql)
	OPEN CostPrice_Cursor          --打开游标
	FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
	WHILE  @@FETCH_STATUS = 0	AND @decSumQty < @decQty   --循环写入临时表
	BEGIN  
		INSERT INTO #TempGoodsStocks VALUES(@decQtyCursor,@decTotalCursor,@intOrderCursor)
		SELECT @decSumQty=SUM(Qty),@decSumTotal=SUM(Total) 
		FROM
			#TempGoodsStocks
		IF @decQty<=@decSumQty 	OR @decSumQty=0	--加了该批次就大于调拨数量了
			BREAK
		SET	@decSumQtyTemp=@decSumQty
		SET @decSumTotalTemp=@decSumTotal
		FETCH NEXT FROM CostPrice_Cursor INTO @decQtyCursor,@decTotalCursor,@intOrderCursor
	END
	CLOSE CostPrice_Cursor 
    DEALLOCATE CostPrice_Cursor

	DROP TABLE #TempGoodsStocks
	IF @decSumQty <= @decQty  --库存商品数量小于调拨数量
	BEGIN
		IF @decSumQty=0
			SET @decCostingPrice=0
		ELSE
			SET @decCostingPrice=@decSumTotal/@decSumQty
	END
	IF @decSumQty > @decQty         --库存商品数量大于调拨数量
		SET @decCostingPrice=(ROUND((@decSumTotal-@decSumTotalTemp)/(@decSumQty-@decSumQtyTemp)*(@decQty-@decSumQtyTemp),2)+@decSumTotalTemp)/@decQty
	SELECT @decCostingPrice AS CostPrice
	SET @CostPrice =@decCostingPrice
	RETURN 
END

IF @intCosting = 3		--手工指定法
BEGIN
	DECLARE @recPrice  NUMERIC(24, 10) 
	SELECT @recPrice=recPrice FROM Ptype WHERE typeId=@chvPtypeId
	IF @recPrice=0
		SELECT NULL AS CostPrice FROM Ptype WHERE typeId=@chvPtypeId
	ELSE
		SELECT recPrice AS CostPrice FROM Ptype WHERE typeId=@chvPtypeId
	RETURN
END





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalculateCostPriceOverFlow]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalculateCostPriceOverFlow]
GO






/*
	功能说明：	根据不同的成本算法返回一定数量在一定仓库的成本价
	返回结果：	成本单价
	作    者：	徐辉
	创建时间：	2004-5-27
	修改历史：
*/
CREATE                 PROCEDURE Web_CalculateCostPriceOverFlow(
	@chvPtypeId	varchar(25),		--商品Id
	@chvKtypeId varchar(25),		--仓库Id
	@decQty		 NUMERIC(24, 10) ,	--商品数量
	@intCosting	int				--成本算法
								--0：移动加权平均
								--1：先进先出
								--2：后进先出
)
--@encode$--
As
SET NOCOUNT ON 
DECLARE	@decCostingPrice  NUMERIC(24, 10) ,		--商品成本价
		@intAverageCostPrice int,			--各仓库商品成本均价是否一致
		@chvSql	varchar(2000)	
			
IF @intCosting = 0 		--移动加权平均
BEGIN
	SELECT TOP 1 @intAverageCostPrice=value FROM Userconfig WHERE ConfigName='AverageCostPrice'
	IF @intAverageCostPrice=0 	--各仓库商品成本均价不一致
	BEGIN
		SET @chvSql='SELECT CostPrice = (SUM(Total) / CASE WHEN SUM(QTY) = 0 THEN NULL ELSE SUM(QTY) END)
					 FROM	GoodsStocks
					 WHERE  kTypeId=''' + @chvKtypeId + ''' AND Ptypeid='''+@chvPtypeId+''''
	END
	ELSE
	BEGIN
		SET @chvSql='SELECT CostPrice = (SUM(Total) / CASE WHEN SUM(QTY) = 0 THEN NULL ELSE SUM(QTY) END)
					 FROM	GoodsStocks
					 WHERE  Ptypeid='''+@chvPtypeId+''''
	END
	EXEC(@chvSql)
	RETURN
END

IF @intCosting = 3 OR @intCosting = 1 OR @intCosting = 2	--手工指定法、先进先出、后进先出
BEGIN
	DECLARE @recPrice  NUMERIC(24, 10) 
	SELECT @recPrice=recPrice FROM Ptype WHERE typeId=@chvPtypeId
	IF @recPrice=0
		SELECT NULL AS CostPrice FROM Ptype WHERE typeId=@chvPtypeId
	ELSE
		SELECT recPrice AS CostPrice FROM Ptype WHERE typeId=@chvPtypeId
	RETURN
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalculateStockDistributing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalculateStockDistributing]
GO















/****** Object:  Stored Procedure dbo.Web_CalculateStockDistributing    Script Date: 2002-6-20 10:14:53 ******/

--author:王跃
--last modified:2001-10-16
--最后修改:添加权限管理
CREATE  PROCEDURE Web_CalculateStockDistributing
(@UserCode varchar(26)='',
 @FullName varchar(66)='',
 @PageRows int=14,
 --权限管理
 @mangerPtypeid varchar(100)='00000', --管辖的商品编号
 @mangerKtypeid varchar(100)='00000'  --管辖的仓库编号
)
--@encode$--
AS
Set Nocount on
Declare @TotalPages int,@TotalQty  NUMERIC(24, 10) 
Declare @RecordCount int
if @UserCode is null or @UserCode=''
 Select @UserCode='%'
else
 Select @UserCode=@UserCode+'%'
if @FullName is null or @UserCode=''
 Select @FullName='%'
else
 Select @FullName=@FullName+'%'
if @PageRows=0 
  select @PageRows=14
--计算总页数
if @mangerPtypeid is null or @mangerPtypeid='00000'
  Select @RecordCount=Count(*) From Ptype Where  [UserCode] Like @UserCode and [FullName] Like @FullName and  Deleted=0 and Sonnum=0
else
  Select @RecordCount=Count(*) From Ptype Where  [UserCode] Like @UserCode and [FullName] Like @FullName and  Deleted=0 and Sonnum=0 and left(typeid,len(@mangerPtypeid))=@mangerPtypeid
if @RecordCount%@PageRows<>0 
  select @TotalPages=@RecordCount/@PageRows+1
else
 select @TotalPages=@RecordCount/@PageRows
Declare @StockName varchar(66),@TypeId varchar(100),@i int,@j int,@ReSql varchar(8000),@Sql varchar(8000),@Qty  NUMERIC(24, 10) 
Declare @TableName varchar(16)
--计算所有仓库的合计
if (@mangerKtypeid is null or @mangerKtypeid='00000') and (@mangerPtypeid is null or @mangerPtypeid='00000')
 select @TotalQty=sum(g.qty) from vWeb_StockDistributing g inner join ptype p on(p.typeid=g.ptypeid) where p.UserCode Like @UserCode and p.FullName Like @FullName and  p.Deleted=0 and p.Sonnum=0
else if (@mangerKtypeid<>'00000') and (@mangerPtypeid is null or @mangerPtypeid='00000')
  select @TotalQty=sum(g.qty) from vWeb_StockDistributing g inner join ptype p on(p.typeid=g.ptypeid) where p.UserCode Like @UserCode and p.FullName Like @FullName and  p.Deleted=0 and p.Sonnum=0 and left(g.ktypeid,len(@mangerktypeid))=@mangerktypeid 
else if (@mangerKtypeid is null or @mangerKtypeid='00000') and (@mangerPtypeid<>'00000')
  select @TotalQty=sum(g.qty) from vWeb_StockDistributing g inner join ptype p on(p.typeid=g.ptypeid) where p.UserCode Like @UserCode and p.FullName Like @FullName and  p.Deleted=0 and p.Sonnum=0 and left(p.typeid,len(@mangerptypeid))=@mangerptypeid 
else
  select @TotalQty=sum(g.qty) from vWeb_StockDistributing g inner join ptype p on(p.typeid=g.ptypeid) where p.UserCode Like @UserCode and p.FullName Like @FullName and  p.Deleted=0 and p.Sonnum=0 and left(p.typeid,len(@mangerptypeid))=@mangerptypeid and  left(g.ktypeid,len(@mangerktypeid))=@mangerktypeid 
--计算每个仓库的合计
Select @TableName='Web'+convert(varchar(2),datepart(dd,GetDate()))+convert(varchar(2),datepart(hh,GetDate()))+convert(varchar(2),datepart(m,GetDate()))+convert(varchar(2),datepart(s,GetDate()))+convert(varchar(4),datepart(ms,GetDate()))
Select @Sql='Create Table '+N'##'+@TableName+'([总页数] int,[总计]  NUMERIC(24, 10) )'
Exec(@sql)
if @@error<>0
begin
 --RAISERROR('创建临时表发生错误！',16,1)
 return
end
Select @Sql='Insert '+N'##'+@TableName+'([总页数],[总计] )
                                        Values('+convert(varchar(10),@TotalPages)+','+convert(varchar(18),@TotalQty)+')'
Exec(@Sql)
if @@error<>0
begin
 --RAISERROR('插入数据发生错误！',16,1)
 return
end
declare @cursorsql varchar(2000)
if (@mangerKtypeid is null or @mangerKtypeid='00000') and (@mangerPtypeid is null or @mangerPtypeid='00000')
  Declare Stock Cursor
   for 
     SELECT Top 1015 SUM(vWeb_StockDistributing.Qty) AS Qty, Stock.typeId,Stock.FullName
     FROM Stock INNER JOIN vWeb_StockDistributing ON Stock.typeId = vWeb_StockDistributing.KtypeId Inner join Ptype on(vWeb_StockDistributing.PTypeId=PType.Typeid)
     where Stock.sonnum=0 and Stock.deleted=0 and Ptype.Deleted=0 and Ptype.sonnum=0 and Ptype.UserCode Like @UserCode and Ptype.FullName Like @FullName GROUP BY Stock.typeId,Stock.FullName 
     Order By Stock.typeId ASC
   for read only
else if (@mangerKtypeid<>'00000') and (@mangerPtypeid is null or @mangerPtypeid='00000')
 begin
  select @cursorsql='
  Declare Stock Cursor
   for 
    SELECT Top 1015 SUM(vWeb_StockDistributing.Qty) AS Qty, Stock.typeId,Stock.FullName
    FROM Stock INNER JOIN vWeb_StockDistributing ON Stock.typeId = vWeb_StockDistributing.KtypeId Inner join Ptype on(vWeb_StockDistributing.PTypeId=PType.Typeid)
    where Stock.sonnum=0 and Stock.deleted=0 and Ptype.Deleted=0 and Ptype.sonnum=0 and Ptype.UserCode Like '''+@UserCode+''' and Ptype.FullName Like '''+@FullName+''' 
    and left(Stock.typeid,len('''+@mangerktypeid+'''))='''+@mangerktypeid+'''
    GROUP BY Stock.typeId,Stock.FullName 
    Order By Stock.typeId ASC
  for read only'
  exec(@cursorsql)
  if @@error<>0 return
 end
else if (@mangerKtypeid is null or @mangerKtypeid='00000') and (@mangerPtypeid<>'00000')
 begin 
  select @cursorsql='
  Declare Stock Cursor
  for 
   SELECT Top 1015 SUM(vWeb_StockDistributing.Qty) AS Qty, Stock.typeId,Stock.FullName
   FROM Stock INNER JOIN vWeb_StockDistributing ON Stock.typeId = vWeb_StockDistributing.KtypeId Inner join Ptype on(vWeb_StockDistributing.PTypeId=PType.Typeid)
   where Stock.sonnum=0 and Stock.deleted=0 and Ptype.Deleted=0 and Ptype.sonnum=0 and Ptype.UserCode Like '''+@UserCode+''' and Ptype.FullName Like '''+@FullName +'''
   and left(Ptype.typeid,len('''+@mangerptypeid+'''))='''+@mangerptypeid+'''
   GROUP BY Stock.typeId,Stock.FullName 
   Order By Stock.typeId ASC
  for read only'
  exec(@cursorsql)
  if @@error<>0 return
 end
else
 begin
 select @cursorsql=' 
  Declare Stock Cursor
  for 
    SELECT Top 1015 SUM(vWeb_StockDistributing.Qty) AS Qty, Stock.typeId,Stock.FullName
    FROM Stock INNER JOIN vWeb_StockDistributing ON Stock.typeId = vWeb_StockDistributing.KtypeId Inner join Ptype on(vWeb_StockDistributing.PTypeId=PType.Typeid)
    where Stock.sonnum=0 and Stock.deleted=0 and Ptype.Deleted=0 and Ptype.sonnum=0 and Ptype.UserCode Like '''+@UserCode+''' and Ptype.FullName Like '''+@FullName+''' 
    and left(Ptype.typeid,len('''+@mangerptypeid+'''))='''+@mangerptypeid+''' and left(Stock.typeid,len('''+@mangerktypeid+'''))='''+@mangerktypeid+'''
    GROUP BY Stock.typeId,Stock.FullName 
    Order By Stock.typeId ASC
   for read only'
  exec(@cursorsql)
  if @@error<>0 return
 end
Open Stock
Fetch Next From Stock Into @Qty,@TypeId,@StockName
if @@Fetch_status<>0
begin
 Close Stock
 Deallocate Stock
 --RAISERROR('没有可用的仓库或仓库没有商品或没有商品！',16,1)
 return 
end 
Select @Sql=''
Select @ReSql='[总页数],[总计]'
While @@Fetch_status=0
Begin
 --检查列名是否存在
 Select @i=0
 Select @j=0
 Select @i=CharIndex('['+ @StockName + ']',@ReSql,@i)
 while @i>0
 begin
   Select @i=CharIndex('['+ @StockName + ']',@ReSql,@i+len('['+ @StockName + ']'))
   Select @j=@j+1  
 end
 if @j>0 
   Select @StockName=@StockName+convert(varchar(4),@j)
 Select @Sql='Alter Table '+N'##'+@TableName+ ' Add ['+ @StockName + ']  NUMERIC(24, 10) '
 Exec(@sql)
 if @@error<>0
 begin
   Close Stock
   Deallocate Stock
   --RAISERROR('更改临时表发生错误！',16,1)
   return
 end
 Select @Sql='Update '+N'##'+@TableName+' Set ['+@StockName+']='+convert(varchar(18),@Qty)
 Exec(@sql)
 if @@error<>0
 begin
  Close Stock
  Deallocate Stock
  --RAISERROR('更新商品数量生错误！',16,1)
  return
 end
 Select @ReSql=@ReSql+',['+ @StockName + ']'
 Fetch Next From Stock Into @Qty,@TypeId,@StockName
end
 Close Stock
 Deallocate Stock
Select @ReSql='Select '+@ReSql+' From '+N'##'+@TableName
Exec(@ReSql)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalculateStockDistributingPtypeId]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalculateStockDistributingPtypeId]
GO





--根据条件计算出ptypeid
--author:王跃
--last modified:2001-10-16
--最后修改:添加权限管理
CREATE  PROCEDURE Web_CalculateStockDistributingPtypeId
(
  @BeginDate smalldatetime,
  @EndDate   smalldatetime,
  @UserCode varchar(26),
  @FullName varchar(66),
  @szKtypeId varchar(100),
  @CurPageNo int,
  @PageRows int,
  @szFlag    char(1),
  --权限管理
  @mangerptypeid varchar(100),
  @mangerktypeid varchar(100),
  --
  @PtypeId varchar(100) output
)
--@encode$--
AS
SET NOCOUNT ON 
declare @Row int,@Re int
if @szFlag='P' and (@BeginDate is null or @EndDate is null)
 begin
  --RAISERROR('日期参数不能为空！',16,1)
  return
 end
if @CurPageNo<1  select @CurPageNo=1
select @Row=(@CurPageNo-1)*@PageRows+1
if @UserCode is null or @UserCode=''  Select @UserCode='%'
else  Select @UserCode='%'+@UserCode+'%'
if @FullName is null or @UserCode=''  Select @FullName='%'
else Select @FullName='%'+@FullName+'%'
if @szKtypeId is null or @szKtypeId=''
 Select @szKtypeId='%'
declare @sql varchar(2000)
if @mangerptypeid='00000' and @mangerKtypeid='00000'
begin
 if @szFlag='A'
    declare Cal Cursor Scroll
      for
        Select TypeId From Ptype Where  [UserCode] Like @UserCode and [FullName] Like @FullName and  Deleted=0 and Sonnum=0 Order By TypeId Asc
        For Read Only
 else
    declare Cal Cursor Scroll 
        for
            Select distinct i.ptypeid FROM  inoutstocktable i inner join ptype p on  p.typeid=i.ptypeid   where i.billdate>=@BeginDate and i.billdate<=@EndDate and i.ktypeid like @szKtypeId and i.billtype<>57 and p.UserCode Like @UserCode and p.FullName Like @FullName and  p.Deleted=0 and p.Sonnum=0 Order By i.pTypeId Asc
         For Read Only 
end
else
if @mangerptypeid<>'00000' and @mangerKtypeid='00000'
begin
 if @szFlag='A'
 begin 
  select @sql='
    declare Cal Cursor Scroll
      for
        Select TypeId From Ptype Where  [UserCode] Like '''+@UserCode+''' and [FullName] Like +'''+@FullName+''' and  Deleted=0 and Sonnum=0 and left(typeid,len('''+@mangerptypeid+'''))='''+@mangerptypeid+''' Order By TypeId Asc
        For Read Only'
    exec(@sql)
    if @@error<>0 return 1
 end
 else
  begin
   select @sql='
   declare Cal Cursor Scroll 
             for
               Select distinct i.ptypeid FROM  inoutstocktable i inner join ptype p on  p.typeid=i.ptypeid   where i.billdate>='''+convert(varchar(10),@BeginDate,110)+''' and i.billdate<='''+convert(varchar(10),@EndDate,110)+''' and i.ktypeid like '''+@szKtypeId+''' and i.billtype<>57 and p.UserCode Like '''+@UserCode+''' and p.FullName Like '''+@FullName+''' and  p.Deleted=0 and p.Sonnum=0 and left(p.typeid,len('''+@mangerptypeid+'''))='''+@mangerptypeid+''' Order By i.pTypeId Asc
             For Read Only '
    exec(@sql)
    if @@error<>0 return 1
  end
end
else
if @mangerptypeid='00000' and @mangerKtypeid<>'00000'
begin
 if @szFlag='A'
    declare Cal Cursor Scroll
      for
        Select TypeId From Ptype Where  [UserCode] Like @UserCode and [FullName] Like @FullName and  Deleted=0 and Sonnum=0  Order By TypeId Asc
        For Read Only
 else
  begin
   select @sql='
       declare Cal Cursor Scroll 
             for
               Select distinct i.ptypeid FROM  inoutstocktable i inner join ptype p on  p.typeid=i.ptypeid   where i.billdate>='''+convert(varchar(10),@BeginDate,110)+''' and i.billdate<='''+convert(varchar(10),@EndDate,110)+''' and i.ktypeid like '''+@szKtypeId+''' and i.billtype<>57 and p.UserCode Like '''+@UserCode+''' and p.FullName Like '''+@FullName+''' and  p.Deleted=0 and p.Sonnum=0 and left(i.ktypeid,len('''+@mangerktypeid+'''))='''+@mangerktypeid+''' Order By i.pTypeId Asc
             For Read Only '
    exec(@sql)
    if @@error<>0 return 1
  end
end
else
if @mangerptypeid<>'00000' and @mangerKtypeid<>'00000'
begin
 if @szFlag='A'
  begin
   select @sql='

    declare Cal Cursor Scroll
      for
        Select TypeId From Ptype Where  [UserCode] Like '''+@UserCode+''' and [FullName] Like '''+@FullName+''' and  Deleted=0 and Sonnum=0 and left(typeid,len('''+@mangerptypeid+'''))='''+@mangerptypeid+''' Order By TypeId Asc
        For Read Only '
    exec(@sql)
    if @@error<>0 return 1
  end
 else
  begin
   select @sql='
    declare Cal Cursor Scroll 
             for
               Select distinct i.ptypeid FROM  inoutstocktable i inner join ptype p on  p.typeid=i.ptypeid   where i.billdate>='''+convert(varchar(10),@BeginDate,110)+''' and i.billdate<='''+convert(varchar(10),@EndDate,110)+''' and i.ktypeid like '''+@szKtypeId+''' and i.billtype<>57 and p.UserCode Like '''+@UserCode+''' and p.FullName Like '''+@FullName+''' and  p.Deleted=0 and p.Sonnum=0 and left(p.typeid,len('''+@mangerptypeid+'''))='''+@mangerptypeid+''' and left(i.ktypeid,len('''+@mangerktypeid+'''))='''+@mangerktypeid+''' Order By i.pTypeId Asc
             For Read Only '
    exec(@sql)
    if @@error<>0 return 1
  end
end
    open Cal
    Fetch ABSOLUTE @Row From Cal into @PtypeId
    Close Cal
    Deallocate Cal
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalculateStockTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalculateStockTotal]
GO









/*
	作者：谢吉康
	日期：2006-6-2
	描述：提速

	Web_CalculateStockTotal '00001','2006-1-1','2006-6-2','','','','P','','',14,'one','1'
*/
CREATE                 PROCEDURE Web_CalculateStockTotal
(
	@OperatorID 	varchar(100),
	@BeginDate 		datetime,
	@EndDate   		datetime,
	@szPtypeId 		varchar(100)='',        --新加入的商品或商品类ID( Peter )
	@szKtypeId 		varchar(100)='',
	@szEtypeId 		varchar(100)='',        --新加入的经手人ID
	@szFlag    		char(1)='A',
	@UserCode 		varchar(26)='',
	@FullName 		varchar(66)='',
	@PageRows 		int=14, 
	@szPTypeKind 	varchar(10),         --是显示具体商品还是大类商品 ( Peter )
	@ShowSum 		int
)
--@encode$--
AS
SET Nocount ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @TotalPages int
DECLARE @RecordCount int

DECLARE @AllSaleBillNumber  NUMERIC(24, 10) ,@AllSaleQty  NUMERIC(24, 10) ,@AllSaleTotal  NUMERIC(24, 10) ,@AllSalePriceTotal  NUMERIC(24, 10) 
DECLARE @AllBuyQty  NUMERIC(24, 10) ,@AllBuyTotal  NUMERIC(24, 10) ,@AllBuyBillNumber  NUMERIC(24, 10)   
DECLARE @AllBuyBackQty  NUMERIC(24, 10) ,@AllBuyBackTotal  NUMERIC(24, 10) ,@AllBuyBackBillNumber  NUMERIC(24, 10) 
DECLARE @AllSaleBackQty  NUMERIC(24, 10) ,@AllSaleBackTotal  NUMERIC(24, 10) ,@AllSaleBackBillNumber  NUMERIC(24, 10) ,@AllSaleBackPriceTotal  NUMERIC(24, 10)   
DECLARE @AllLoseQty  NUMERIC(24, 10) ,@AllLoseTotal  NUMERIC(24, 10)  
DECLARE @AllOverFlowQty  NUMERIC(24, 10) ,@AllOverFlowTotal  NUMERIC(24, 10)  
DECLARE @AllZengSongQty  NUMERIC(24, 10) ,@AllZengSongTotal  NUMERIC(24, 10)  
DECLARE @AllHuoZengQty  NUMERIC(24, 10) ,@AllHuoZengTotal  NUMERIC(24, 10)  
DECLARE @AllPacketRKQty  NUMERIC(24, 10) ,@AllPacketRKTotal  NUMERIC(24, 10)  
DECLARE @AllPacketCKQty  NUMERIC(24, 10) ,@AllPacketCKTotal  NUMERIC(24, 10)  
DECLARE @AllChgPriceRKQty  NUMERIC(24, 10) ,@AllChgPriceRKTotal  NUMERIC(24, 10)  
DECLARE @AllChgPriceCKQty  NUMERIC(24, 10) ,@AllChgPriceCKTotal  NUMERIC(24, 10)  
DECLARE @AllTjdbQty  NUMERIC(24, 10) ,@AllTjdbTotal  NUMERIC(24, 10) 
DECLARE @AllTjdbCQty  NUMERIC(24, 10) ,@AllTjdbCTotal  NUMERIC(24, 10) 
DECLARE @AllBjdbRKQty  NUMERIC(24, 10) ,@AllBjdbRKTotal  NUMERIC(24, 10)  
DECLARE @AllBjdbCKQty  NUMERIC(24, 10) ,@AllBjdbCKTotal  NUMERIC(24, 10)  
DECLARE @AllWtfhQty  NUMERIC(24, 10) ,@AllWtfhTotal  NUMERIC(24, 10)  
DECLARE @AllWtthQty  NUMERIC(24, 10) ,@AllWtthTotal  NUMERIC(24, 10)  
DECLARE @AllStshQty  NUMERIC(24, 10) ,@AllStshTotal  NUMERIC(24, 10)  
DECLARE @AllStthQty  NUMERIC(24, 10) ,@AllStthTotal  NUMERIC(24, 10)  

DECLARE @AllhhrkQty  NUMERIC(24, 10) ,@AllhhrkTotal  NUMERIC(24, 10)  
DECLARE @AllhhckQty  NUMERIC(24, 10) ,@AllhhckTotal  NUMERIC(24, 10)  

DECLARE @AllwxrkQty  NUMERIC(24, 10) ,@AllwxrkTotal  NUMERIC(24, 10)  
DECLARE @AllwxckQty  NUMERIC(24, 10) ,@AllwxckTotal  NUMERIC(24, 10)  


DECLARE @initAllQty  NUMERIC(24, 10) ,@initAllTotal  NUMERIC(24, 10)  
DECLARE @LastAllQty  NUMERIC(24, 10) ,@LastAllTotal  NUMERIC(24, 10)  
DECLARE @ThisAllQty  NUMERIC(24, 10) ,@ThisAllTotal  NUMERIC(24, 10) 

IF @BeginDate IS NULL OR @EndDate IS NULL
BEGIN
    --RAISERROR('日期参数不能为空！',16,1)
    RETURN
END

-- ////////	2002-10-8 卢春修改 - Start	////////
IF @UserCode IS NULL OR @UserCode=''
   SELECT @UserCode='%'
ELSE
   SELECT @UserCode='%'+@UserCode+'%'
IF @FullName IS NULL OR @FullName=''
   SELECT @FullName='%'
ELSE
   SELECT @FullName='%'+@FullName+'%'
-- ////////	2002-10-08 卢春修改 - END	////////

SELECT @PageRows=14
IF @szKtypeId<>''  SELECT @MKTypeID = @szKTypeID

IF @UserCode = '%' AND @FullName = '%'
	IF @szPtypeId<>''  SELECT @MPTypeID = @szPTypeID

IF @szEtypeId<>''  SELECT @METypeID = @szETypeID

SELECT 	TypeID 
INTO 	#TempPType 
FROM 	PType 
WHERE 	[UserCode] LIKE @UserCode 
		AND [FullName] LIKE @FullName 
		AND Deleted=0 
		AND Sonnum=0 
		AND TypeId LIKE @szPtypeId+'%'
		AND TypeID LIKE @MPTypeID+'%' 


SELECT 	i.Qty,
		i.CostTotal,
		i.BillType,
		i.PTypeID
INTO 	#InOutStockTable0
FROM	InOutStockTable i
WHERE	i.Audited = 1
		AND i.Audited=1 
		AND i.KTypeID<>'10000'		
		AND i.BillDate>=@BeginDate 
		AND i.BillDate<=@EndDate  
		AND i.kTypeID LIKE @MKTypeID + '%' 
		AND i.PTypeID LIKE @MPTypeID + '%' 
        AND i.EtypeID LIKE @METypeID + '%'

SELECT	I.*
INTO	#InOutStockTable
FROM	#InOutStockTable0 I,
		#TempPType P
WHERE	I.PTypeId = P.TypeId

   
IF @ShowSum=1
	BEGIN
        SELECT @AllSaleQty=ISNULL(SUM(Qty),0),@AllSaleTotal=ISNULL(SUM(CostTotal),0)  FROM #InOutStockTable WHERE BillType IN (11,305)  --305【零售单 11  【销售
        SELECT @AllBuyQty=ISNULL(SUM(Qty),0),@AllBuyTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=34  --34  【进货单                 
        SELECT @AllSaleBackQty=ISNULL(SUM(Qty),0),@AllSaleBackTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=45  --45  【销售退货                 
        SELECT @AllBuyBackQty=ISNULL(SUM(Qty),0),@AllBuyBackTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=6  --6    【进货退货
        SELECT @AllLoseQty=ISNULL(SUM(Qty),0),@AllLoseTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=9  --9    【报损
        SELECT @AllOverFlowQty=ISNULL(SUM(Qty),0),@AllOverFlowTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=14  --14  【报溢
        SELECT @AllPacketRKQty=ISNULL(SUM(Qty),0),@AllPacketRKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=16 AND Qty>0  --16  【商品拆装单
        SELECT @AllPacketCKQty=ISNULL(SUM(Qty),0),@AllPacketCKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=16 AND Qty<0
        SELECT @AllChgPriceRKQty=ISNULL(SUM(Qty),0),@AllChgPriceRKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=57 AND Qty>0  --57  【调价
        SELECT @AllChgPriceCKQty=ISNULL(SUM(Qty),0),@AllChgPriceCKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=57 AND Qty<0  --57  【调价
        SELECT @AllTjdbQty=ISNULL(SUM(Qty),0),@AllTjdbTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=17 AND Qty>0  --17  【同价调拨
        SELECT @AllTjdbCQty=ISNULL(SUM(Qty),0),@AllTjdbCTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=17 AND Qty<0  --17  【同价调拨
        SELECT @AllBjdbRKQty=ISNULL(SUM(Qty),0),@AllBjdbRKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=21 AND Qty>0  --21  【变价调拨
        SELECT @AllBjdbCKQty=ISNULL(SUM(Qty),0),@AllBjdbCKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=21 AND Qty<0
        SELECT @AllZengSongQty=ISNULL(SUM(Qty),0),@AllZengSongTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=139  --139【赠送单
        SELECT @AllHuoZengQty=ISNULL(SUM(Qty),0),@AllHuoZengTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=126  --126【获赠单
        SELECT @AllWtfhQty=ISNULL(SUM(Qty),0),@AllWtfhTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=140 and Qty < 0 --140【委托代销发货单      --徐辉2004-4-29 受托委托统计有问题140\142\144\146
        SELECT @AllWtthQty=ISNULL(SUM(Qty),0),@AllWtthTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=142 and Qty > 0  --142【委托代销退货单
        SELECT @AllStshQty=ISNULL(SUM(Qty),0),@AllStshTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=144 --144【受托代销收货单
        SELECT @AllStthQty=ISNULL(SUM(Qty),0),@AllStthTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=146  --146【受托代销退货单

        SELECT @AllhhrkQty=ISNULL(SUM(Qty),0),@AllhhRKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=155 AND Qty>0  --155  【商品换货
        SELECT @AllhhckQty=ISNULL(SUM(Qty),0),@AllhhCKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=155 AND Qty<0  --155  【商品换货

        SELECT @AllwxrkQty=ISNULL(SUM(Qty),0),@AllwxRKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=157 AND Qty>0  --157  【商品维修
        SELECT @AllwxckQty=ISNULL(SUM(Qty),0),@AllwxCKTotal=ISNULL(SUM(CostTotal),0) FROM #InOutStockTable WHERE BillType=157 AND Qty<0  --157  【商品维修

		IF @szFlag = 'P' AND @szPTypeKind='one'
			BEGIN
        		SELECT 	@initAllQty = ISNULL(SUM(Qty),0),
						@initAllTotal = ISNULL(SUM(Total),0)
				FROM 	IniGoodsStocks
                WHERE 	Qty<>0
						AND PTypeID IN (SELECT TypeId FROM #TempPType)
						AND kTypeID LIKE @MKTypeID + '%' 
						AND PTypeID LIKE @MPTypeID+'%' 

	        	SELECT 	@LastAllQty=ISNULL(SUM(Qty),0),
						@LastAllTotal=ISNULL(SUM(CostTotal),0) 
				FROM 	InOutStockTable 
	            WHERE 	Audited=1 
						AND KTypeID<>'10000'
						AND billdate<@BeginDate 
						AND PTypeID IN (SELECT TypeId FROM #TempPType)
						AND kTypeID LIKE @MKTypeID + '%' 
						AND PTypeID LIKE @MPTypeID + '%' 
						AND ETypeID LIKE @METypeID + '%'						
			END
		ELSE
			BEGIN
		    	SELECT 	@initAllQty = ISNULL(SUM(Qty),0),
						@initAllTotal = ISNULL(SUM(Total),0)
				FROM 	IniGoodsStocks
               	WHERE 	Qty<>0
						AND kTypeID LIKE @MKTypeID + '%' 
						AND PTypeID LIKE @MPTypeID+'%' 		
						AND PTypeID IN (SELECT TypeId FROM #TempPType)
		
		       	SELECT 	@LastAllQty=ISNULL(SUM(Qty),0),
						@LastAllTotal=ISNULL(SUM(CostTotal),0) 
				FROM 	InOutStockTable 
               	WHERE 	Audited=1 
						AND KTypeID<>'10000'
						AND billdate<@BeginDate 
						AND PTypeID IN (SELECT TypeId FROM #TempPType)
						AND kTypeID LIKE @MKTypeID + '%' 
						AND PTypeID LIKE @MPTypeID + '%' 
					    AND ETypeID LIKE @METypeID + '%'
			END        

        	SELECT @LastAllQty = @initAllQty + @LastAllQty

        	SELECT @LastAllTotal = @initAllTotal + @LastAllTotal

			SELECT @ThisAllQty = @LastAllQty + @AllBuyQty + @AllSaleBackQty + @AllOverFlowQty + @AllHuoZengQty + @AllPacketRKQty + @AllChgPriceRKQty + @AllBjdbRKQty + @AllWtthQty + @AllStshQty + @AllhhrkQty + @AllwxrkQty+@AllTjdbQty
			SELECT @ThisAllQty = @ThisAllQty + @AllSaleQty + @AllBuyBackQty + @AllLoseQty + @AllZengSongQty + @AllPacketCKQty + @AllChgPriceCKQty  + @AllBjdbCKQty + @AllWtfhQty + @AllStthQty + @AllhhckQty + @AllwxckQty+@AllTjdbCQty
			
			SELECT @ThisAllTotal = @LastAllTotal + @AllBuyTotal + @AllSaleBackTotal + @AllOverFlowTotal + @AllHuoZengTotal + @AllPacketRKTotal + @AllChgPriceRKTotal + @AllBjdbRKTotal + @AllWtthTotal + @AllStshTotal + @AllhhrkTotal + @AllwxrkTotal+@AllTjdbTotal			
			SELECT @ThisAllTotal = @ThisAllTotal + @AllSaleTotal + @AllBuyBackTotal + @AllLoseTotal + @AllZengSongTotal + @AllPacketCKTotal + @AllChgPriceCKTotal + @AllBjdbCKTotal + @AllWtfhTotal + @AllStthTotal + @AllhhckTotal + @AllwxckTotal+@AllTjdbCTotal
	END

IF @szPTypeKind='one'    --具体商品    Peter
	BEGIN               
        IF @szFlag='A'
            SELECT 	@RecordCount=COUNT(*) 
			FROM 	Ptype 
			WHERE  	[UserCode] LIKE @UserCode 
					AND [FullName] LIKE @FullName 
					AND Deleted=0 
					AND Sonnum=0 
					AND [TypeID] LIKE @MPTypeID+'%' 
					AND TypeId LIKE @szPTypeId+'%'
        ELSE
            SELECT 	@RecordCount=COUNT(DISTINCT ptypeid) 
			FROM 	#InOutStockTable

        IF @RecordCount%@PageRows<>0 
            SELECT @TotalPages=@RecordCount/@PageRows+1
        ELSE
            SELECT @TotalPages=@RecordCount/@PageRows
	END
ELSE         --大类商品 Peter
	BEGIN
       IF  @szPtypeId='' SET @szPtypeId='00000'
       DECLARE @TempSonnum int
       SELECT @TempSonnum=Sonnum FROM PType WHERE TypeID=@szPtypeId
       IF @TempSonnum = 0
           SELECT @RecordCount=1
       ELSE
           SELECT @RecordCount=COUNT(*) FROM Ptype WHERE  [UserCode] LIKE @UserCode AND [FullName] LIKE @FullName AND  Deleted=0 AND [TypeID] LIKE @MPTypeID+'%' AND [parid]=@szPtypeId

       IF @RecordCount%@PageRows<>0
            SELECT @TotalPages=@RecordCount/@PageRows+1
       ELSE
            SELECT @TotalPages=@RecordCount/@PageRows
	END

IF @ShowSum=1
	BEGIN
    	SELECT	@TotalPages AS TotalPages,
                ABS(@LastAllQty) AS LastAllQty,ABS(@LastAllTotal) AS LastAllTotal,
                @ThisAllQty AS ThisAllQty,@ThisAllTotal AS ThisAllTotal,
                ABS(@AllBuyQty) AS AllQty1,ABS(@AllBuyTotal) AS AllTotal1,ABS(@AllBuyBillNumber) AS AllBillNumber1,
                ABS(@AllSaleBackQty) AS AllQty2,ABS(@AllSaleBackTotal) AS AllTotal2,ABS(@AllSaleBackBillNumber) AS AllBillNumber2,ABS(@AllSaleBackPriceTotal) AS AllPriceTotal1,
                ABS(@AllOverFlowQty) AS AllQty3,ABS(@AllOverFlowTotal) AS AllTotal3,
                ABS(@AllTjdbQty) AS AllQty4,ABS(@AllTjdbTotal) AS AllTotal4,
                ABS(@AllBjdbRKQty) AS AllQty5,ABS(@AllBjdbRKTotal) AS AllTotal5,
                ABS(@AllPacketRKQty) AS AllQty6,ABS(@AllPacketRKTotal) AS AllTotal6,
                ABS(@AllChgPriceRKQty) AS AllQty7,ABS(@AllChgPriceRKTotal) AS AllTotal7,
                ABS(@AllHuoZengQty) AS AllQty8,ABS(@AllHuoZengTotal) AS AllTotal8,
                ABS(@AllWtthQty) AS AllQty9,ABS(@AllWtthTotal) AS AllTotal9,
                ABS(@AllStshQty) AS AllQty10,ABS(@AllStshTotal) AS AllTotal10,
                ABS(@AllSaleQty) AS AllQty11,ABS(@AllSaleTotal) AS AllTotal11,ABS(@AllSaleBillNumber) AS AllBillNumber3,ABS(@AllSalePriceTotal) AS AllPriceTotal2,
                ABS(@AllBuyBackQty) AS AllQty12,ABS(@AllBuyBackTotal) AS AllTotal12,ABS(@AllBuyBackBillNumber) AS AllBillNumber4,

                ABS(@AllLoseQty) AS AllQty13,ABS(@AllLoseTotal) AS AllTotal13,
                ABS(@AllTjdbCQty) AS AllQty14,ABS(@AllTjdbCTotal) AS AllTotal14,
                ABS(@AllBjdbCKQty) AS AllQty15,ABS(@AllBjdbCKTotal) AS AllTotal15,
                ABS(@AllPacketCKQty) AS AllQty16,ABS(@AllPacketCKTotal) AS AllTotal16,
                ABS(@AllChgPriceCKQty) AS AllQty17,ABS(@AllChgPriceCKTotal) AS AllTotal17,
                ABS(@AllZengSongQty) AS AllQty18,ABS(@AllZengSongTotal) AS AllTotal18,
                ABS(@AllWtfhQty) AS AllQty19,ABS(@AllWtfhTotal) AS AllTotal19,
                ABS(@AllStthQty) AS AllQty20,ABS(@AllStthTotal) AS AllTotal20,

                ABS(@AllhhrkQty) AS AllQty21,ABS(@AllhhrkTotal) AS AllTotal21,
                ABS(@AllhhckQty) AS AllQty22,ABS(@AllhhckTotal) AS AllTotal22,


                ABS(@AllwxrkQty) AS AllQty23,ABS(@AllwxrkTotal) AS AllTotal23,
                ABS(@AllwxckQty) AS AllQty24,ABS(@AllwxckTotal) AS AllTotal24
				
	END
ELSE
	BEGIN
         SELECT @TotalPages AS TotalPages
	END






























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalDepartmentSaleDist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalDepartmentSaleDist]
GO















/*
	作者：谢吉康
	日期：2005-8-9
	描述：部门销售分布
*/
CREATE PROCEDURE Web_CalDepartmentSaleDist
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@PTypeId		varchar(100),	--商品Id
	@DTypeId		varchar(100),	--部门Id
	@BillType		varchar(100),	--单据类型
	@nType			varchar(10),	--金额的查询方式
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@showZero		varchar(5)		--0.不显示红冲单据   1.显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @showZero = 1
	SET @showZero = '0,1,2'

DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@SQL1			varchar(8000),
		@SQL2			varchar(8000),
		@SQL3			varchar(8000),
		@PTypeIdMx		varchar(100)

IF @PTypeId = '00000'
	SET @PTypeIdMx = '%'
ELSE
	SET @PTypeIdMx = @PTypeId

IF @DTypeId = '00000'
	SET @DTypeId = '%'

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		typeid 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计数量,总计金额)VALUES(0,0,0,0)'

EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************
--压缩BillIndex表
CREATE TABLE #BillIndex
(
	BillNumberId 	numeric(18,0),
	DTypeId			varchar(100),
	RedWord			int
)
--压缩商品表
CREATE TABLE #PType
(
	TypeId varchar(100)
)
--压缩销售明细表
CREATE TABLE #SaleBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 	
)
--压缩零售明细
CREATE TABLE #retailBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩销售退货明细
CREATE TABLE #SaleBackBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩代销明细
CREATE TABLE #CommissionBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩换货明细
CREATE TABLE #GoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩维修明细
CREATE TABLE #RepairDealDetail
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
SET @SQL = '
	INSERT INTO #BillIndex
	SELECT	Bil.BillNumberId,
			CASE
				WHEN Bil.DTypeId='''' THEN ''99999''
				ELSE Bil.DTypeId
			END AS DTypeId,
			Bil.RedWord
	FROM	BillIndex Bil
	WHERE	Bil.IfCheck = ''t''
			AND Bil.Draft = 0
			AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
			AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
			AND Bil.BillType IN ('+@BillType+')
			AND Bil.RedWord IN ('+@showZero+')
			AND (Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+' OR Bil.DTypeId='''')
			AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 '

EXEC(@SQL)

INSERT INTO #PType
SELECT	TypeId
FROM	PType
WHERE	SonNum = 0
		AND Deleted = 0
		AND TypeId LIKE @PTypeIdMx+'%'

-------------------------处理含税金额
IF @nType = 0
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleBill
					SELECT	S.PTypeId,			
							Bil.RedWord,
							Bil.DTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal	
					FROM	BillIndex Bil,
							SaleBill S
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.BillType IN ('+@BillType+')
							AND Bil.RedWord IN ('+@showZero+')
							AND (Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+' OR Bil.DTypeId='''')
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+') 
					GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId '	
				
				EXEC(@SQL)
			END		
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		

		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.DTypeId
			END
	END
ELSE
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleBill
					SELECT	S.PTypeId,			
							Bil.RedWord,
							Bil.DTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal	
					FROM	BillIndex Bil,
							SaleBill S
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.BillType IN ('+@BillType+')
							AND Bil.RedWord IN ('+@showZero+')
							AND (Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+' OR Bil.DTypeId='''')
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+') 
					GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId '	
				
				EXEC(@SQL)
			END		
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END

		
		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.DTypeId
			END
	END
--********************************************************************************以上压缩数据***************************************************************
SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET [总计数量] = ISNULL(X.Qty,0),
			[总计金额] = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
			SELECT	B.DTypeId,
					ISNULL(SUM(B.Qty),0) AS Qty,
					ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	0 AS DTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)									
								END AS Total
						FROM 	#SaleBill S
						UNION ALL
						SELECT	0 AS DTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#retailBill S '
				SET @SQL1 = '
						UNION ALL
						SELECT	0 AS DTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
									ELSE ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
									ELSE ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBackBill S
						UNION ALL
						SELECT	0 AS DTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#CommissionBill S '
					SET @SQL2 = '
						UNION ALL
						SELECT	0 AS DTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#GoodsExchangeBill S
						UNION ALL
						SELECT	0 AS DTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#RepairDealDetail S
					)B GROUP BY B.DTypeId
		)X ON (X.DTypeId = A.TypeId OR A.TypeId=0)'

--PRINT(@SQL+@SQL1+@SQL2)
EXEC(@SQL+@SQL1+@SQL2)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
--创建部门的临时表
CREATE TABLE #DType
(
	TypeId		varchar(100),
	UserCode	varchar(256),
	FullName	varchar(256)
)
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

SET @xjkang = ''

INSERT INTO #DType SELECT TypeId,UserCode,FullName FROM Department WHERE TypeId LIKE @DTypeId + '%' AND SonNum = 0 AND Deleted = 0 ORDER BY UserCode

INSERT INTO #DType(TypeId,UserCode,FullName)VALUES('99999','xjk','其他部门')

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    #DType 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	#DType
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '

	EXEC(@SQLCursor)

	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @BaseTypeId = '99999'
				SET @xjkang = '谢吉康'

			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '数量]  NUMERIC(24, 10) '
			EXEC(@SQL)
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '金额]  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'数量] = ISNULL(X.Qty,0),
						['+@BaseFullName+'金额] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	B.PTypeId,
								ISNULL(SUM(B.Qty),0) AS Qty,
								ISNULL(SUM(B.Total),0) AS Total
						FROM	(
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBill S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#retailBill S 
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL2='
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
												ELSE ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
												ELSE ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBackBill S			
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'						
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#CommissionBill S 
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL3 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#GoodsExchangeBill S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#RepairDealDetail S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'
								)B GROUP BY B.PTypeId
					)X ON (X.PTypeId = A.TypeId OR A.TypeId = 0) '
					
			--PRINT(@SQL+@SQL2+@SQL3)
			EXEC(@SQL+@SQL2+@SQL3)
			
			--修改其他部门的数量和金额
			IF @xjkang = '谢吉康'
				BEGIN
					SET @SQL = '
							UPDATE '+N'##'+@TableName+'
							SET [其他部门数量] = ISNULL(X.Qty,0),
								[其他部门金额] = ISNULL(X.Total,0)
							FROM '+N'##'+@TableName+' A
							LEFT JOIN (
								SELECT	B.PTypeId,
										ISNULL(SUM(B.Qty),0) AS Qty,
										ISNULL(SUM(B.Total),0) AS Total
								FROM	(
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#SaleBill S	
											WHERE 	S.DTypeId = ''99999''									
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#retailBill S 
											WHERE 	S.DTypeId = ''99999'''											
								SET @SQL2 = '
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
														ELSE ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
														ELSE ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#SaleBackBill S	
											WHERE 	S.DTypeId = ''99999''										
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#CommissionBill S 
											WHERE 	S.DTypeId = ''99999'''
									SET @SQL3 = '
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#GoodsExchangeBill S
											WHERE 	S.DTypeId = ''99999''										
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#RepairDealDetail S
											WHERE 	S.DTypeId = ''99999''											
										)B GROUP BY B.PTypeId
							)X ON (X.PTypeId = A.TypeId OR A.TypeId = 0)'
					
					--PRINT(@SQL+@SQL2+@SQL3)
					EXEC(@SQL+@SQL2+@SQL3)
				END
			
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		int,
		@BaseInfoCount 	int,
		@pSonNum 		int,
		@TotalpPages	int,	--商品页数
		@TotalbPages	int		--基本信息页数

SELECT @pSonNum = SonNum FROM PType WHERE TypeId = @PTypeId AND Deleted = 0 AND TypeId LIKE @MPTypeId + '%'

IF @pSonNum = 0 
	SELECT	@PTypeCount = COUNT(*)
	FROM	PType
	WHERE	Deleted = 0
			AND TypeId LIKE @PTypeId + '%' 
			AND TypeId LIKE @MPTypeId + '%'
ELSE
	SELECT	@PTypeCount = COUNT(*)
	FROM	PType
	WHERE	Deleted = 0
			AND ParId = @PTypeId
			AND TypeId LIKE @MPTypeId + '%'
		
IF @PTypeCount%14<>0 
    SET @TotalpPages=@PTypeCount/14+1
ELSE
    SET @TotalpPages=@PTypeCount/14

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@TotalpPages AS varchar(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*) FROM #DType

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@TotalbPages AS varchar(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)

--删除定义的临时表
DROP TABLE #DType,#BillIndex,#SaleBill,#retailBill,#CommissionBill,#GoodsExchangeBill,#RepairDealDetail
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BillIndex0]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[BillIndex0]















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalDepartmentSaleDistLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalDepartmentSaleDistLine]
GO








/*
	作者：谢吉康
	日期：2005-8-9
	描述：部门销售分布
*/
CREATE PROCEDURE Web_CalDepartmentSaleDistLine
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@PTypeId		varchar(100),	--商品Id
	@DTypeId		varchar(100),	--部门Id
	@BillType		varchar(100),	--单据类型
	@nType			varchar(10),	--金额的查询方式
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@showZero		varchar(5)		--0.不显示红冲单据   1.显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SET @showZero = 0
IF @showZero = 1
	SET @showZero = '0,1,2'

DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@SQL1			varchar(8000),
		@SQL2			varchar(8000),
		@SQL3			varchar(8000),
		@PTypeIdMx		varchar(100)

IF @PTypeId = '00000'
	SET @PTypeIdMx = @MPTypeId
ELSE
	SET @PTypeIdMx = @PTypeId

IF @DTypeId = '00000'
	SET @DTypeId = '%'

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		typeid 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计数量,总计金额)VALUES(0,0,0,0)'

EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************
--压缩BillIndex表
CREATE TABLE #BillIndex
(
	BillNumberId 	numeric(18,0),
	DTypeId			varchar(100),
	RedWord			int
)
--压缩商品表
CREATE TABLE #PType
(
	TypeId varchar(100)
)
--压缩销售明细表
CREATE TABLE #SaleBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 	
)
--压缩零售明细
CREATE TABLE #retailBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩销售退货明细
CREATE TABLE #SaleBackBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩代销明细
CREATE TABLE #CommissionBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩换货明细
CREATE TABLE #GoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩维修明细
CREATE TABLE #RepairDealDetail
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩销售换货单明细
CREATE TABLE #SaleGoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	DTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
SET @SQL = '
	INSERT INTO #BillIndex
	SELECT	BillNumberId,
			CASE
				WHEN DTypeId='''' THEN ''99999''
				ELSE DTypeId
			END AS DTypeId,
			RedWord
	FROM	BillIndex
	WHERE	IfCheck = ''t''
			AND Draft = 0
			AND BillType IN ('+@BillType+')
			AND RedWord IN ('+@showZero+')
			AND BillDate>='+char(39)+@StartDate+char(39)+'
			AND BillDate<='+char(39)+@EndDate+char(39)+'			
			AND (DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+' OR DTypeId='''')
			AND ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND (KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR KTypeId = ''10000'')
			AND (BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 
			AND BillType <> 160 '

EXEC(@SQL)

INSERT INTO #PType
SELECT	TypeId
FROM	PType
WHERE	SonNum = 0
		AND Deleted = 0
		AND TypeId LIKE @PTypeIdMx+'%'
		AND TypeId LIKE @MPTypeId+'%'

-------------------------处理含税金额
IF @nType = 0
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleBill
					SELECT	S.PTypeId,			
							Bil.RedWord,
							Bil.DTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal	
					FROM	#BillIndex Bil,
							SaleBill S,
							#PType P
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND P.TypeId = S.PTypeId
					GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId '	
				
				EXEC(@SQL)
			END		
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND P.TypeId = S.PTypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('45',@BillType)<>0
			BEGIN
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND P.TypeId = S.PTypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND P.TypeId = S.PTypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND P.TypeId = S.PTypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND P.TypeId = S.PTypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.DTypeId
			END

		IF CharIndex('160',@BillType)<>0		
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	S.PTypeId,
							Bil.RedWord,
							CASE
								WHEN Bil.DTypeId='''' THEN ''99999''
								ELSE Bil.DTypeId
							END AS DTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S,
							BillIndex Bil,
							#PType P
					WHERE	S.PTypeId = P.TypeId
							AND Bil.BillNumberId = S.BillNumberId
							AND S.PTypeId IN (SELECT DISTINCT PTypeId FROM InOutStockTable WHERE BillType = 160 AND Qty<=0 AND BillNumberId = Bil.BillNumberId AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+')
							AND S.InOrOut = ''o''
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+' OR Bil.DTypeId='''')
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId,S.InOrOut '

				EXEC(@SQL)

				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	S.PTypeId,
							Bil.RedWord,
							CASE
								WHEN Bil.DTypeId='''' THEN ''99999''
								ELSE Bil.DTypeId
							END AS DTypeId,
							-1*SUM(S.Qty) AS Qty,
							-1*SUM(S.TaxTotal) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S,
							BillIndex Bil,
							#PType P
					WHERE	S.PTypeId = P.TypeId
							AND Bil.BillNumberId = S.BillNumberId
							AND S.PTypeId IN (SELECT DISTINCT PTypeId FROM InOutStockTable WHERE BillType = 160 AND Qty>=0 AND BillNumberId = Bil.BillNumberId AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+')
							AND S.InOrOut = ''i''
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+' OR Bil.DTypeId='''')
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId,S.InOrOut '

				EXEC(@SQL)
			END
	END
ELSE
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleBill
					SELECT	S.PTypeId,			
							Bil.RedWord,
							Bil.DTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.Total) AS TaxTotal	
					FROM	#BillIndex Bil,
							SaleBill S,
							#PType P
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND P.TypeId = S.PTypeId
					GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId '	
				
				EXEC(@SQL)
			END		
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND P.TypeId = S.PTypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('45',@BillType)<>0
			BEGIN
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND P.TypeId = S.PTypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND P.TypeId = S.PTypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND P.TypeId = S.PTypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.DTypeId
			END		
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.DTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND P.TypeId = S.PTypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.DTypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	S.PTypeId,
							Bil.RedWord,
							CASE
								WHEN Bil.DTypeId='''' THEN ''99999''
								ELSE Bil.DTypeId
							END AS DTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.Total) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S,
							BillIndex Bil,
							#PType P
					WHERE	S.PTypeId = P.TypeId
							AND Bil.BillNumberId = S.BillNumberId
							AND S.PTypeId IN (SELECT DISTINCT PTypeId FROM InOutStockTable WHERE BillType = 160 AND Qty<=0 AND BillNumberId = Bil.BillNumberId AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+')
							AND S.InOrOut = ''o''
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+' OR Bil.DTypeId='''')
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId,S.InOrOut '

				EXEC(@SQL)

				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	S.PTypeId,
							Bil.RedWord,
							CASE
								WHEN Bil.DTypeId='''' THEN ''99999''
								ELSE Bil.DTypeId
							END AS DTypeId,
							-1*SUM(S.Qty) AS Qty,
							-1*SUM(S.Total) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S,
							BillIndex Bil,
							#PType P
					WHERE	S.PTypeId = P.TypeId
							AND Bil.BillNumberId = S.BillNumberId
							AND S.PTypeId IN (SELECT DISTINCT PTypeId FROM InOutStockTable WHERE BillType = 160 AND Qty>=0 AND BillNumberId = Bil.BillNumberId AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+')
							AND S.InOrOut = ''i''
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+' OR Bil.DTypeId='''')
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY S.PTypeId,Bil.RedWord,Bil.DTypeId,S.InOrOut '

				EXEC(@SQL)
			END
	END
--********************************************************************************以上压缩数据***************************************************************
SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET [总计数量] = ISNULL(X.Qty,0),
			[总计金额] = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
			SELECT	B.PTypeId,
					ISNULL(SUM(B.Qty),0) AS Qty,
					ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)

								END AS Total

						FROM 	#SaleBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#retailBill S '
				SET @SQL1 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
									ELSE ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
									ELSE ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBackBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#CommissionBill S '

					SET @SQL2 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#GoodsExchangeBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#RepairDealDetail S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleGoodsExchangeBill S
					)B GROUP BY B.PTypeId
		)X ON (X.PTypeId = A.TypeId OR A.TypeId=0)'

--PRINT(@SQL+@SQL1+@SQL2)
EXEC(@SQL+@SQL1+@SQL2)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
--创建部门的临时表
CREATE TABLE #DType
(
	TypeId		varchar(100),
	UserCode	varchar(256),
	FullName	varchar(256)
)
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

SET @xjkang = ''

INSERT INTO #DType SELECT TypeId,UserCode,FullName FROM Department WHERE TypeId LIKE CASE @DTypeId WHEN '00000' THEN '%' ELSE @DTypeId + '%' END AND SonNum = 0 AND Deleted = 0 AND TypeId <> '00000' ORDER BY UserCode

INSERT INTO #DType(TypeId,UserCode,FullName)VALUES('99999','xjk','其他部门')

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    #DType 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	#DType
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '

	EXEC(@SQLCursor)
	
	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @BaseTypeId = '99999'
				SET @xjkang = '谢吉康'

			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '数量]  NUMERIC(24, 10) '

			EXEC(@SQL)
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '金额]  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'数量] = ISNULL(X.Qty,0),
						['+@BaseFullName+'金额] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	B.PTypeId,
								ISNULL(SUM(B.Qty),0) AS Qty,
								ISNULL(SUM(B.Total),0) AS Total
						FROM	(
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBill S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#retailBill S 
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL1 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
												ELSE ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
												ELSE ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBackBill S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#CommissionBill S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL3 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#GoodsExchangeBill S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#RepairDealDetail S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleGoodsExchangeBill S
									WHERE	S.DTypeId = '+char(39)+@BaseTypeId+char(39)+'
								)B GROUP BY B.PTypeId
					)X ON (X.PTypeId = A.TypeId OR A.TypeId=0) '
			
			--PRINT(@SQL+@SQL1+@SQL3)
			EXEC(@SQL+@SQL1+@SQL3)
			
			--修改其他部门的数量和金额
			IF @xjkang = '谢吉康'
				BEGIN
					SET @SQL = '
							UPDATE '+N'##'+@TableName+'
							SET [其他部门数量] = ISNULL(X.Qty,0),
								[其他部门金额] = ISNULL(X.Total,0)
							FROM '+N'##'+@TableName+' A
							LEFT JOIN (
								SELECT	B.PTypeId,
										ISNULL(SUM(B.Qty),0) AS Qty,
										ISNULL(SUM(B.Total),0) AS Total
								FROM	(
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#SaleBill S
											WHERE 	S.DTypeId = ''99999''
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#retailBill S
											WHERE 	S.DTypeId = ''99999'''
									SET @SQL2 = '
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
														ELSE ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
														ELSE ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#SaleBackBill S
											WHERE	S.DTypeId = ''99999''
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#CommissionBill S
											WHERE 	S.DTypeId = ''99999'''
									SET @SQL3 = '
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#GoodsExchangeBill S
											WHERE 	S.DTypeId = ''99999''									
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#RepairDealDetail S
											WHERE 	S.DTypeId = ''99999''	
											UNION ALL
											SELECT	0 AS PTypeId,
													CASE
														WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
														ELSE -1*ISNULL(S.Qty,0)
													END AS Qty,
													CASE
														WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
														ELSE -1*ISNULL(S.TaxTotal,0)
													END AS Total
											FROM 	#SaleGoodsExchangeBill S
											WHERE 	S.DTypeId = ''99999''				
										)B GROUP BY B.PTypeId
							)X ON (X.PTypeId = A.TypeId OR A.TypeId = 0)'
					
					--PRINT(@SQL+@SQL2+@SQL3)
					EXEC(@SQL+@SQL2+@SQL3)
				END
			
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		int,
		@BaseInfoCount 	int,
		@pSonNum 		int,
		@TotalpPages	int,	--商品页数
		@TotalbPages	int		--基本信息页数

IF @PTypeId = '00000'
	SET @PTypeId = '%'

SELECT	@PTypeCount = COUNT(*)
FROM	PType
WHERE	Deleted = 0
		AND SonNum = 0
		AND TypeId LIKE @PTypeId + '%' 
		AND TypeId LIKE @MPTypeId + '%'
		
IF @PTypeCount%14<>0 
    SET @TotalpPages=@PTypeCount/14+1
ELSE
    SET @TotalpPages=@PTypeCount/14

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@TotalpPages AS varchar(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*) FROM #DType

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@TotalbPages AS varchar(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)

--删除定义的临时表
DROP TABLE #PType,#DType,#BillIndex,#SaleBill,#retailBill,#CommissionBill,#GoodsExchangeBill,#RepairDealDetail,#SaleGoodsExchangeBill


RETURN 0

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalEmployeeSaleDist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalEmployeeSaleDist]
GO
















/*
	作者：谢吉康
	日期：2005-8-9
	描述：部门销售分布
*/
CREATE PROCEDURE Web_CalEmployeeSaleDist
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@PTypeId		varchar(100),	--商品Id
	@ETypeId		varchar(100),	--部门Id
	@BillType		varchar(100),	--单据类型
	@nType			varchar(10),	--金额的查询方式
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@showZero		varchar(5)		--0.不显示红冲单据   1.显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @showZero = 1
	SET @showZero = '0,1,2'

DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@SQL1			varchar(8000),
		@SQL2			varchar(8000),
		@SQL3			varchar(8000),
		@SQL4			varchar(8000),
		@PTypeIdMx		varchar(100)

IF @PTypeId = '00000'
	SET @PTypeIdMx = '%'
ELSE
	SET @PTypeIdMx = @PTypeId

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		typeid 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计数量,总计金额)VALUES(0,0,0,0)'

EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************
--压缩BillIndex表
CREATE TABLE #BillIndex
(
	BillNumberId 	numeric(18,0),
	ETypeId			varchar(100),
	RedWord			int
)
--压缩商品表
CREATE TABLE #PType
(
	TypeId varchar(100)
)
--压缩销售明细表
CREATE TABLE #SaleBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 	
)
--压缩零售明细
CREATE TABLE #retailBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩销售退货明细
CREATE TABLE #SaleBackBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩代销明细
CREATE TABLE #CommissionBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩换货明细
CREATE TABLE #GoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩维修明细
CREATE TABLE #RepairDealDetail
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
SET @SQL = '
	INSERT INTO #BillIndex
	SELECT	Bil.BillNumberId,
			Bil.ETypeId,
			Bil.RedWord
	FROM	BillIndex Bil
	WHERE	Bil.IfCheck = ''t''
			AND Bil.Draft = 0
			AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
			AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
			AND Bil.BillType IN ('+@BillType+')
			AND Bil.RedWord IN ('+@showZero+')
			AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
			AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 '

EXEC(@SQL)

SET @SQL = 'INSERT INTO #PType
			SELECT	TypeId
			FROM	PType
			WHERE	SonNum = 0
					AND Deleted = 0
					AND TypeId LIKE '+char(39)+@PTypeIdMx+'%'+char(39)


EXEC(@SQL)
-------------------------处理含税金额
IF @nType = 0
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
						INSERT INTO #SaleBill
						SELECT	S.PTypeId,
								Bil.RedWord,
								Bil.ETypeId,
								SUM(S.Qty) AS Qty,
								SUM(S.TaxTotal) AS TaxTotal
						FROM	BillIndex Bil,
								SaleBill S
						WHERE	Bil.BillNumberId = S.BillNumberId
								AND Bil.IfCheck = ''t''
								AND Bil.Draft = 0
								AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
								AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
								AND Bil.BillType IN ('+@BillType+')
								AND Bil.RedWord IN ('+@showZero+')
								AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
								AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
								AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
								AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	
						GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId  '
		
				EXEC(@SQL)
			END
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('141',@BillType)<>0
			BEGIN		
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('155',@BillType)<>0
			BEGIN		
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('157',@BillType)<>0
			BEGIN		
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.ETypeId
			END
	END
ELSE
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
						INSERT INTO #SaleBill
						SELECT	S.PTypeId,
								Bil.RedWord,
								Bil.ETypeId,
								SUM(S.Qty) AS Qty,
								SUM(S.TaxTotal) AS TaxTotal
						FROM	BillIndex Bil,
								SaleBill S
						WHERE	Bil.BillNumberId = S.BillNumberId
								AND Bil.IfCheck = ''t''
								AND Bil.Draft = 0
								AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
								AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
								AND Bil.BillType IN ('+@BillType+')
								AND Bil.RedWord IN ('+@showZero+')
								AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
								AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
								AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
								AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	
						GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId  '
		
				EXEC(@SQL)
			END
		
		IF CharIndex('305',@BillType)<>0
			BEGIN		
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END		
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('155',@BillType)<>0
			BEGIN		
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('157',@BillType)<>0
			BEGIN		
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.ETypeId
			END
	END
--********************************************************************************以上压缩数据***************************************************************
SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET [总计数量] = ISNULL(X.Qty,0),
			[总计金额] = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
			SELECT	B.PTypeId,
					ISNULL(SUM(B.Qty),0) AS Qty,
					ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#retailBill S '
				SET @SQL1 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
									ELSE ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
									ELSE ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBackBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#CommissionBill S '
					SET @SQL2 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#GoodsExchangeBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#RepairDealDetail S
					)B GROUP BY B.PTypeId
		)X ON (X.PTypeId = A.TypeId OR A.TypeId=0)'

--PRINT(@SQL+@SQL1+@SQL2)
EXEC(@SQL+@SQL1+@SQL2)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    Employee 
	    WHERE  	SonNum = 0
				AND Deleted = 0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	Employee
					WHERE 	SonNum = 0
							AND Deleted = 0
							AND TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
							AND TypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
	                ORDER BY
							UserCode
	            )
				AND TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
				AND TypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
	    ORDER BY UserCode '

	EXEC(@SQLCursor)
	
	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @BaseTypeId = '99999'
				SET @xjkang = '谢吉康'

			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '数量]  NUMERIC(24, 10) '
			EXEC(@SQL)
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '金额]  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'数量] = ISNULL(X.Qty,0),
						['+@BaseFullName+'金额] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	B.PTypeId,
								ISNULL(SUM(B.Qty),0) AS Qty,
								ISNULL(SUM(B.Total),0) AS Total
						FROM	(
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#retailBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL2 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
												ELSE ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
												ELSE ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBackBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#CommissionBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)
								SET @SQL3 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#GoodsExchangeBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#RepairDealDetail S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
								)B GROUP BY B.PTypeId
					)X ON (X.PTypeId = A.TypeId OR A.TypeId=0) '
			
			--PRINT(@SQL+@SQL2+@SQL3)
			EXEC(@SQL+@SQL2+@SQL3)			
	
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		int,
		@BaseInfoCount 	int,
		@pSonNum 		int,
		@TotalpPages	int,	--商品页数
		@TotalbPages	int		--基本信息页数

SELECT @pSonNum = SonNum FROM PType WHERE TypeId = @PTypeId AND Deleted = 0 AND TypeId LIKE @MPTypeId + '%'

IF @pSonNum = 0 
	SELECT	@PTypeCount = COUNT(*)
	FROM	PType
	WHERE	Deleted = 0
			AND TypeId LIKE @PTypeId + '%'
			AND TypeId LIKE @MPTypeId + '%' 
ELSE
	SELECT	@PTypeCount = COUNT(*)
	FROM	PType
	WHERE	Deleted = 0
			AND ParId = @PTypeId
			AND TypeId LIKE @MPTypeId + '%'
		
IF @PTypeCount%14<>0 
    SET @TotalpPages=@PTypeCount/14+1
ELSE
    SET @TotalpPages=@PTypeCount/14

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@TotalpPages AS varchar(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*) FROM Employee WHERE SonNum = 0 AND Deleted = 0 AND TypeId LIKE @ETypeId + '%' AND TypeId LIKE @METypeId + '%'

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@TotalbPages AS varchar(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)


--删除定义的临时表
DROP TABLE #BillIndex,#SaleBill,#retailBill,#CommissionBill,#GoodsExchangeBill,#RepairDealDetail
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BillIndex0]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[BillIndex0]













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalEmployeeSaleDistLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalEmployeeSaleDistLine]
GO






























/*
	作者：谢吉康
	日期：2005-8-9
	描述：部门销售分布
*/
CREATE PROCEDURE Web_CalEmployeeSaleDistLine
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@PTypeId		varchar(100),	--商品Id
	@ETypeId		varchar(100),	--部门Id
	@BillType		varchar(100),	--单据类型
	@nType			varchar(10),	--金额的查询方式
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@showZero		varchar(5)		--0.不显示红冲单据   1.显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SET @showZero = 0
IF @showZero = 1
	SET @showZero = '0,1,2'

DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@SQL1			varchar(8000),
		@SQL2			varchar(8000),
		@SQL3			varchar(8000),
		@SQL4			varchar(8000),
		@PTypeIdMx		varchar(100)

IF @PTypeId = '00000'
	SET @PTypeIdMx = @MPTypeId
ELSE
	SET @PTypeIdMx = @PTypeId

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		typeid 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计数量,总计金额)VALUES(0,0,0,0)'

EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************
--压缩BillIndex表
CREATE TABLE #BillIndex
(
	BillNumberId 	numeric(18,0),
	ETypeId			varchar(100),
	RedWord			int
)
--压缩商品表
CREATE TABLE #PType
(
	TypeId varchar(100)
)
--压缩销售明细表
CREATE TABLE #SaleBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 	
)
--压缩零售明细
CREATE TABLE #retailBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩销售退货明细
CREATE TABLE #SaleBackBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩代销明细
CREATE TABLE #CommissionBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩换货明细
CREATE TABLE #GoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩维修明细
CREATE TABLE #RepairDealDetail
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩销售换货单明细
CREATE TABLE #SaleGoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	ETypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
SET @SQL = '
	INSERT INTO #BillIndex
	SELECT	Bil.BillNumberId,
			Bil.ETypeId,
			Bil.RedWord
	FROM	BillIndex Bil
	WHERE	Bil.IfCheck = ''t''
			AND Bil.Draft = 0
			AND Bil.BillType IN ('+@BillType+')
			AND Bil.RedWord IN ('+@showZero+')
			AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
			AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
			AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
			AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND (Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR Bil.KTypeId = ''10000'')
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 
			AND Bil.BillType <> 160 '

EXEC(@SQL)

SET @SQL = 'INSERT INTO #PType
			SELECT	TypeId
			FROM	PType
			WHERE	SonNum = 0
					AND Deleted = 0
					AND TypeId LIKE '+char(39)+@PTypeIdMx+'%'+char(39)+'
					AND TypeId LIKE '+char(39)+@MPTypeId+'%'+char(39)


EXEC(@SQL)
-------------------------处理含税金额
IF @nType = 0
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
						INSERT INTO #SaleBill
						SELECT	S.PTypeId,
								Bil.RedWord,
								Bil.ETypeId,
								SUM(S.Qty) AS Qty,
								SUM(S.TaxTotal) AS TaxTotal
						FROM	#BillIndex Bil,
								SaleBill S,
								#PType P
						WHERE	Bil.BillNumberId = S.BillNumberId
								AND P.TypeId = S.PTypeId
						GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId  '
		
				EXEC(@SQL)
			END
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('141',@BillType)<>0
			BEGIN		
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('155',@BillType)<>0
			BEGIN		
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('157',@BillType)<>0
			BEGIN		
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.ETypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	I.PTypeId,
							Bil.RedWord,
							Bil.ETypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S
					INNER JOIN (
							SELECT	DISTINCT
									PTypeId
							FROM	InOutStockTable
							WHERE	BillType = 160
									AND Qty<=0
									AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
									AND Audited = 1
					)I ON I.PTypeId = S.PTypeId
					INNER JOIN BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
					INNER JOIN #PType P ON P.TypeId = S.PTypeId
					WHERE	S.InOrOut = ''o''							
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'	
							AND Bil.KTypeId2 LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY I.PTypeId,Bil.ETypeId,S.InOrOut,Bil.RedWord '

				EXEC(@SQL)

				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	I.PTypeId,
							Bil.RedWord,
							Bil.ETypeId,
							-1*SUM(S.Qty) AS Qty,
							-1*SUM(S.TaxTotal) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S
					INNER JOIN (
							SELECT	DISTINCT
									PTypeId
							FROM	InOutStockTable
							WHERE	BillType = 160
									AND Qty>=0
									AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
									AND Audited = 1
					)I ON I.PTypeId = S.PTypeId
					INNER JOIN BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
					INNER JOIN #PType P ON P.TypeId = S.PTypeId
					WHERE	S.InOrOut = ''i''							
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'		
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'	
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY I.PTypeId,Bil.ETypeId,S.InOrOut,Bil.RedWord '

				EXEC(@SQL)
			END
	END
ELSE
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
						INSERT INTO #SaleBill
						SELECT	S.PTypeId,
								Bil.RedWord,
								Bil.ETypeId,
								SUM(S.Qty) AS Qty,
								SUM(S.Total) AS TaxTotal
						FROM	#BillIndex Bil,
								SaleBill S,
								#PType P
						WHERE	Bil.BillNumberId = S.BillNumberId
								AND P.TypeId = S.PTypeId
						GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId  '
		
				EXEC(@SQL)
			END
		
		IF CharIndex('305',@BillType)<>0
			BEGIN		
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('141',@BillType)<>0
			BEGIN		
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('155',@BillType)<>0
			BEGIN		
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.ETypeId
			END
		
		IF CharIndex('157',@BillType)<>0

			BEGIN		
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.ETypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.ETypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	I.PTypeId,
							Bil.RedWord,
							Bil.ETypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.Total) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S
					INNER JOIN (
							SELECT	DISTINCT
									PTypeId
							FROM	InOutStockTable
							WHERE	BillType = 160
									AND Qty<=0
									AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
									AND Audited = 1
					)I ON I.PTypeId = S.PTypeId
					INNER JOIN BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
					INNER JOIN #PType P ON P.TypeId = S.PTypeId
					WHERE	S.InOrOut = ''o''							
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'	
							AND Bil.KTypeId2 LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY I.PTypeId,Bil.ETypeId,S.InOrOut,Bil.RedWord '

				EXEC(@SQL)

				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	I.PTypeId,
							Bil.RedWord,
							Bil.ETypeId,
							-1*SUM(S.Qty) AS Qty,
							-1*SUM(S.Total) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S
					INNER JOIN (
							SELECT	DISTINCT
									PTypeId
							FROM	InOutStockTable
							WHERE	BillType = 160
									AND Qty>=0
									AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
									AND Audited = 1
					)I ON I.PTypeId = S.PTypeId
					INNER JOIN BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
					INNER JOIN #PType P ON P.TypeId = S.PTypeId
					WHERE	S.InOrOut = ''i''							
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'		
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'	
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY I.PTypeId,Bil.ETypeId,S.InOrOut,Bil.RedWord '

				EXEC(@SQL)
			END
	END
--********************************************************************************以上压缩数据***************************************************************

SET @SQL = '
		UPDATE '+N'##'+@TableName+'

		SET [总计数量] = ISNULL(X.Qty,0),
			[总计金额] = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
			SELECT	B.PTypeId,
					ISNULL(SUM(B.Qty),0) AS Qty,
					ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#retailBill S '
				SET @SQL1 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
									ELSE ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
									ELSE ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBackBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#CommissionBill S '
					SET @SQL2 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#GoodsExchangeBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#RepairDealDetail S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleGoodsExchangeBill S
					)B GROUP BY B.PTypeId
		)X ON (X.PTypeId = A.TypeId OR A.TypeId=0)'

--PRINT(@SQL+@SQL1+@SQL2)
EXEC(@SQL+@SQL1+@SQL2)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    Employee 
	    WHERE  	SonNum = 0
				AND Deleted = 0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	Employee
					WHERE 	SonNum = 0
							AND Deleted = 0
							AND TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
							AND TypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
	                ORDER BY
							UserCode
	            )
				AND TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
				AND TypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
	    ORDER BY UserCode '

	EXEC(@SQLCursor)
	
	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @BaseTypeId = '99999'
				SET @xjkang = '谢吉康'

			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '数量]  NUMERIC(24, 10) '
			EXEC(@SQL)
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '金额]  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'数量] = ISNULL(X.Qty,0),
						['+@BaseFullName+'金额] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	B.PTypeId,
								ISNULL(SUM(B.Qty),0) AS Qty,
								ISNULL(SUM(B.Total),0) AS Total
						FROM	(
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#retailBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL2 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
												ELSE ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
												ELSE ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBackBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#CommissionBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)
								SET @SQL3 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#GoodsExchangeBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#RepairDealDetail S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleGoodsExchangeBill S
									WHERE	S.ETypeId = '+char(39)+@BaseTypeId+char(39)+'
								)B GROUP BY B.PTypeId
					)X ON (X.PTypeId = A.TypeId OR A.TypeId=0) '
			
			--PRINT(@SQL+@SQL2+@SQL3)
			EXEC(@SQL+@SQL2+@SQL3)
	
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		int,
		@BaseInfoCount 	int,
		@pSonNum 		int,
		@TotalpPages	int,	--商品页数
		@TotalbPages	int		--基本信息页数

IF @PTypeId = '00000'
	SET @PTypeId = '%'

SELECT	@PTypeCount = COUNT(*)
FROM	PType
WHERE	Deleted = 0
		AND SonNum = 0
		AND TypeId LIKE @PTypeId + '%' 
		AND TypeId LIKE @MPTypeId + '%'

		
IF @PTypeCount%14<>0 
    SET @TotalpPages=@PTypeCount/14+1
ELSE
    SET @TotalpPages=@PTypeCount/14

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@TotalpPages AS varchar(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*) FROM Employee WHERE SonNum = 0 AND Deleted = 0 AND TypeId LIKE @ETypeId + '%' AND TypeId LIKE @METypeId + '%'

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@TotalbPages AS varchar(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)

--删除定义的临时表
DROP TABLE #PType,#BillIndex,#SaleBill,#retailBill,#CommissionBill,#GoodsExchangeBill,#RepairDealDetail,#SaleGoodsExchangeBill

RETURN 0



























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_CalPeriodBalance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_CalPeriodBalance]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/04/19
	Description	: 查询账务期初的试算平衡
*/

CREATE PROCEDURE WEB_CalPeriodBalance
(
	@chvOperatorID	VARCHAR(100),     --操作员id
	@STypeId		VARCHAR(50)		  --分支机构id	
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	--指定分支机构启用年度、启用期间	
	DECLARE 
		@FYear			VARCHAR(10),
		@FPeriod		INT
	SELECT @FYear=SFYear,@FPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	
	---提出该机构所有父节点
	SELECT STYPEID,
		   TYPEID,
		   FDC,
		   SUBSTRING(TYPEID,1,5) AS ACCOUNTTYPE
    INTO #tempFather
    FROM AC_ACCOUNT a
    WHERE
	(
		a.TYPEID LIKE '00001%' OR  --资产
		a.TYPEID LIKE '00002%' OR  --负债
		a.TYPEID LIKE '00003%' OR  --损益
		a.TYPEID LIKE '00004%' OR  --成本
		a.TYPEID LIKE '00005%' OR  --权益
		a.TYPEID LIKE '00006%'     --共同
	)
	AND a.FLeveal=1
	AND a.STYPEID=@STypeId 
	AND a.DELETED=0
	ORDER BY a.TYPEID
    
    ---查询出副科目包含子科目及子科目的值
    CREATE TABLE #tempData
	(
	   FATHERID             VARCHAR(50),
	   FATHERFDC			INT,
	   SONID				VARCHAR(50),
	   SONFDC				INT,        
	   ACCOUNTTYPE			VARCHAR(5),  
	   INITOTAL              NUMERIC(24, 10) ,   --期初本币余额
	   INIYTOTAL			 NUMERIC(24, 10) 	 --年初本币余额
	)
	INSERT INTO #tempData 
	SELECT a.TYPEID AS FATHERID,
		   a.FDC, 
		   b.TYPEID AS SONID,
		   b.FDC,
		   a.ACCOUNTTYPE,
		   ISNULL(INITOTAL,0),
		   ISNULL(INIYTOTAL,0)
	FROM #tempFather a
	JOIN dbo.Ac_Account b         ON a.STYPEID=b.STYPEID AND b.TYPEID LIKE a.TYPEID+'%' AND b.DELETED=0 AND b.SONNUM=0
	LEFT JOIN dbo.Ac_IniAccount c ON b.STYPEID=c.STYPEID AND b.TYPEID=c.ATYPEID AND c.FYEAR=@FYear AND c.FPERIOD=@FPeriod 
    ORDER BY a.TYPEID
    
    ---求出父科目的值
    CREATE TABLE #AC_INIACCOUNT
	(   
	   ATYPEID              VARCHAR(50),  
	   FDC					INT,
	   ACCOUNTTYPE			VARCHAR(50),        
	   INITOTAL              NUMERIC(24, 10) ,
	   INIYTOTAL			 NUMERIC(24, 10) 
	)
	;WITH a AS
	 (
		 SELECT FATHERID,
				FATHERFDC,
				ACCOUNTTYPE,
				SONFDC,
				 CASE 
					WHEN a.FATHERFDC=a.SONFDC THEN SUM(INITOTAL)
					ELSE -SUM(INITOTAL)
				 END AS INITOTAL,
				 CASE 
					WHEN a.FATHERFDC=a.SONFDC THEN SUM(INIYTOTAL)
					ELSE -SUM(INIYTOTAL)
				 END AS INIYTOTAL
		 FROM 
			(     --科目各种币别的年初合
			      SELECT FATHERID,
						 FATHERFDC,
						 ACCOUNTTYPE,
						 SONFDC,
						 SONID,
						 SUM(INITOTAL) AS INITOTAL,
						 SUM(INIYTOTAL) AS INIYTOTAL
			      FROM #tempData
			      GROUP BY FATHERID,FATHERFDC,SONFDC,SONID,ACCOUNTTYPE
			) a
		 GROUP BY FATHERID,FATHERFDC,SONFDC,ACCOUNTTYPE
	 )
	 INSERT INTO #AC_INIACCOUNT
	 SELECT FATHERID,
		    FATHERFDC,
		    ACCOUNTTYPE,
		    SUM(INITOTAL),
		    SUM(INIYTOTAL)
	 FROM a 
	 GROUP BY a.FATHERID,a.FATHERFDC,ACCOUNTTYPE	
	 
    -------------------取出期初数据-----------------------------------------------------------------------------------------------
    CREATE TABLE #temp
    (
       ACCOUNTTYPE VARCHAR(50),		---科目类型
       FDC		   VARCHAR(5),		---余额方向
       FVALUE	    NUMERIC(24, 10) 	---余额值
    )
    
    INSERT INTO #temp
    SELECT ACCOUNTTYPE,
		   CASE 
			   WHEN FDC=1 THEN '借'
			   ELSE '贷'
		   END,
		   SUM(INITOTAL) 
    FROM #AC_INIACCOUNT
    GROUP BY ACCOUNTTYPE,FDC
    
    CREATE TABLE #Result
    (
	   ACCOUNTTYPE VARCHAR(50),		---科目类型
       FDC		   VARCHAR(5),		---余额方向
       FVALUE	    NUMERIC(24, 10) ,	---余额值
       GROUPID	   INT				---合计时使用，【资产，共同，成本】是一组，【负债，权益，损益】是一组
    )
    
    ---资产
	; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC  
       WHERE a.ACCOUNTTYPE='00001'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '资产',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a  
      
    ---共同
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00006'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '共同',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a           
	
	---成本
	; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00004'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '成本',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a    
    
    ---负债
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00002'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '负债',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷'
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
     
    ----权益
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC  
       WHERE a.ACCOUNTTYPE='00005'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '权益',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷' 
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
         
    --损益
     ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00003'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '损益',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷'  
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
    
    --------【资产，共同，成本】的合计
    IF (SELECT COUNT(*) FROM #Result WHERE GROUPID=1 AND FDC='平')=3
		INSERT INTO #Result
		SELECT '合计1','平',0,0
    ELSE
		WITH tempA AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					SUM(FVALUE) AS FVALUE
			FROM #Result b 
			WHERE b.GROUPID=1 AND b.FDC='借' 
			GROUP BY b.GROUPID,b.FDC
		)
		INSERT INTO #Result
		SELECT '合计1',
				CASE 
					WHEN FVALUE=0 THEN '平'
					ELSE '借'
				END,
				FVALUE,
				0
		FROM tempA

   --------【负债，权益，损益】的合计
   IF (SELECT COUNT(*) FROM #Result WHERE GROUPID=2 AND FDC='平')=3
		INSERT INTO #Result
		SELECT '合计2','平',0,0
   ELSE
		WITH tempB AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					SUM(FVALUE) AS FVALUE
			FROM #Result b 
			WHERE b.GROUPID=2 AND b.FDC='贷'
			GROUP BY b.GROUPID,b.FDC
		)
		INSERT INTO #Result
		SELECT '合计2',
			   CASE 
					WHEN FVALUE=0 THEN '平'
					ELSE '贷'
			   END,
			   FVALUE,
			   0
	   FROM tempB
  
   ---试算是否平衡
   IF (SELECT COUNT(*) FROM #Result WHERE GROUPID=0 AND FDC='平')=2
		INSERT INTO #Result
		SELECT '试算平衡','平',0,-1
   ELSE
		WITH tempC AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					b.FVALUE
			FROM #Result b 
			WHERE b.GROUPID=0 AND (b.FDC='借' OR b.FDC='贷')
		)
		INSERT INTO #Result
		SELECT TOP 1
			   '试算平衡',
			   CASE 
					WHEN FVALUE1=FVALUE2 THEN '平'
					WHEN FVALUE1>FVALUE2 THEN FDC1
					ELSE FDC2 
			   END,
			   ABS(FVALUE1-FVALUE2),
			   -1
	   FROM
	   ( 
			SELECT a.FDC AS FDC1,
				  a.FVALUE AS FVALUE1,
				  CASE 
					WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
					WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
					ELSE b.FDC
				  END AS FDC2,
				  CASE 
					WHEN b.FVALUE IS NULL THEN 0
					ELSE b.FVALUE
				  END AS FVALUE2
			FROM tempC a   
			LEFT JOIN tempC b ON a.GROUPID=b.GROUPID AND a.FDC!=b.FDC 
	   ) c 
	   
    ----查询所要的数据
    SELECT ACCOUNTTYPE,
		   CASE 
			  WHEN FDC='借' THEN '借 '+CONVERT(VARCHAR(24),dbo.F_RoundTotal(FVALUE))
			  WHEN FDC='贷' THEN '贷 '+CONVERT(VARCHAR(24),dbo.F_RoundTotal(FVALUE))
			  ELSE '平'
		   END AS LABEL 
    FROM #Result
    WHERE GROUPID BETWEEN 0 AND 2
    UNION ALL
    SELECT ACCOUNTTYPE,
		  CASE 
			 WHEN FDC='平' THEN '平'
			 ELSE '不平'
		  END AS LABEL
	FROM #Result
	WHERE GROUPID=-1
    --------------------------------------------------------------------------------------------------------------------------------------------------
    ---------------------------------------------------取出年初数据---------------------------------------------------------------------------------
    CREATE TABLE #temp1
    (
       ACCOUNTTYPE VARCHAR(50),		---科目类型
       FDC		   VARCHAR(5),		---余额方向
       FVALUE	    NUMERIC(24, 10) 	---余额值
    )
    
    INSERT INTO #temp1
    SELECT ACCOUNTTYPE,
		   CASE 
			   WHEN FDC=1 THEN '借'
			   ELSE '贷'
		   END,
		   SUM(INIYTOTAL) 
    FROM #AC_INIACCOUNT
    GROUP BY ACCOUNTTYPE,FDC
    
    CREATE TABLE #Result1
    (
	   ACCOUNTTYPE VARCHAR(50),		---科目类型
       FDC		   VARCHAR(5),		---余额方向
       FVALUE	    NUMERIC(24, 10) ,	---余额值
       GROUPID	   INT				---合计时使用，【资产，共同，成本】是一组，【负债，权益，损益】是一组
    )
    
    ---资产
	; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC  
       WHERE a.ACCOUNTTYPE='00001'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '资产',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a  
      
    ---共同
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00006'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '共同',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a           
	
	---成本
	; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00004'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '成本',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借' 
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a    
    
    ---负债
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00002'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '负债',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷'
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
     
    ----权益
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC  
       WHERE a.ACCOUNTTYPE='00005'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '权益',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷' 
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
         
    --损益
     ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00003'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '损益',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷'  
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
    
    --------【资产，共同，成本】的合计
    IF (SELECT COUNT(*) FROM #Result1 WHERE GROUPID=1 AND FDC='平')=3
		INSERT INTO #Result1
		SELECT '合计1','平',0,0
    ELSE
		WITH tempA AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					SUM(FVALUE) AS FVALUE
			FROM #Result1 b 
			WHERE b.GROUPID=1 AND b.FDC='借' 
			GROUP BY b.GROUPID,b.FDC
		)
		INSERT INTO #Result1
		SELECT TOP 1
			   '合计1',
			   CASE 
					WHEN FVALUE=0 THEN '平'
					ELSE '借'
			   END,
			   FVALUE,
			   0
	   FROM tempA
    
   --------【负债，权益，损益】的合计
   IF (SELECT COUNT(*) FROM #Result1 WHERE GROUPID=2 AND FDC='平')=3
		INSERT INTO #Result1
		SELECT '合计2','平',0,0
   ELSE
		WITH tempB AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					SUM(FVALUE) AS FVALUE
			FROM #Result1 b 
			WHERE b.GROUPID=2 AND  b.FDC='贷'
			GROUP BY b.GROUPID,b.FDC
		)
		INSERT INTO #Result1
		SELECT TOP 1
			   '合计2',
			   CASE 
					WHEN FVALUE=0 THEN '平'
					ELSE '贷'
			   END,
			   FVALUE,
			   0
	   FROM tempB
	  
   ---试算是否平衡
   IF (SELECT COUNT(*) FROM #Result1 WHERE GROUPID=0 AND FDC='平')=2
		INSERT INTO #Result1
		SELECT '试算平衡','平',0,-1
   ELSE
		WITH tempC AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					b.FVALUE
			FROM #Result1 b 
			WHERE b.GROUPID=0 AND (b.FDC='借' OR b.FDC='贷')
		)
		INSERT INTO #Result1
		SELECT TOP 1
			   '试算平衡',
			   CASE 
					WHEN FVALUE1=FVALUE2 THEN '平'
					WHEN FVALUE1>FVALUE2 THEN FDC1
					ELSE FDC2 
			   END,
			   ABS(FVALUE1-FVALUE2),
			   -1
	   FROM
	   ( 
			SELECT a.FDC AS FDC1,
				  a.FVALUE AS FVALUE1,
				  CASE 
					WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
					WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
					ELSE b.FDC
				  END AS FDC2,
				  CASE 
					WHEN b.FVALUE IS NULL THEN 0
					ELSE b.FVALUE
				  END AS FVALUE2
			FROM tempC a   
			LEFT JOIN tempC b ON a.GROUPID=b.GROUPID AND a.FDC!=b.FDC 
	   ) c 
	
	
    ----查询所要的数据
    SELECT ACCOUNTTYPE,
		   CASE 
			  WHEN FDC='借' THEN '借 '+CONVERT(VARCHAR(24),dbo.F_RoundTotal(FVALUE)) --+CONVERT(VARCHAR(18),FVALUE)
			  WHEN FDC='贷' THEN '贷 '+CONVERT(VARCHAR(24),dbo.F_RoundTotal(FVALUE)) --+CONVERT(VARCHAR(18),FVALUE)
			  ELSE '平'
		   END AS LABEL 
    FROM #Result1
    WHERE GROUPID BETWEEN 0 AND 2
    UNION ALL
    SELECT ACCOUNTTYPE,
		  CASE 
			 WHEN FDC='平' THEN '平'
			 ELSE '不平'
		  END AS LABEL
	FROM #Result1
	WHERE GROUPID=-1
    -------------------------------------------------------------------------------------------------------------------------------------------------
    -------------------------------------------本年累计----------------------------------------------------------------------------------------------
    CREATE TABLE #tempYearTotal
	(
	   FATHERID             VARCHAR(50),
	   SONID				VARCHAR(50),
	   ACCOUNTTYPE			VARCHAR(5),  
	   BORROW	             NUMERIC(24, 10) ,  
	   LEND					 NUMERIC(24, 10) 	  
	)
	INSERT INTO #tempYearTotal 
	SELECT a.TYPEID AS FATHERID,
		   b.TYPEID AS SONID,
		   a.ACCOUNTTYPE,
		   ISNULL(FDEBIT,0),
		   ISNULL(FCREDIT,0)
	FROM #tempFather a
	JOIN dbo.Ac_Account b         ON a.STYPEID=b.STYPEID AND b.TYPEID LIKE a.TYPEID+'%' AND b.DELETED=0 AND b.SONNUM=0
	LEFT JOIN dbo.Ac_IniAccount c ON b.STYPEID=c.STYPEID AND b.TYPEID=c.ATYPEID AND c.FYEAR=@FYear AND c.FPERIOD=@FPeriod 
    ORDER BY a.TYPEID
    
     CREATE TABLE #AC_YearTotal
	(   
	   ATYPEID              VARCHAR(50),  
	   ACCOUNTTYPE			VARCHAR(50),        
	   BORROW				 NUMERIC(24, 10) ,
	   LEND					 NUMERIC(24, 10) 
	)
	INSERT INTO #AC_YearTotal
	SELECT a.FATHERID,
		   a.ACCOUNTTYPE,
		   SUM(BORROW),
		   SUM(LEND)
	FROM #tempYearTotal a
	GROUP BY a.FATHERID,a.ACCOUNTTYPE
	
	CREATE TABLE #Result2
	(
		ACCOUNTTYPE VARCHAR(50),		---科目类型
		BORROW		 NUMERIC(24, 10) ,
		LEND		 NUMERIC(24, 10) ,
		GROUPID	    INT
	)
	---资产
	INSERT INTO #Result2
	SELECT '资产',
		   SUM(BORROW),
		   SUM(LEND),
		   1
	FROM #AC_YearTotal
	WHERE ACCOUNTTYPE='00001'
	GROUP BY ACCOUNTTYPE
	
	---共同
	INSERT INTO #Result2
	SELECT '共同',
		   SUM(BORROW),
		   SUM(LEND),
		   1
	FROM #AC_YearTotal
	WHERE ACCOUNTTYPE='00006'
	GROUP BY ACCOUNTTYPE
	
	----成本
	INSERT INTO #Result2
	SELECT '成本',
		   SUM(BORROW),
		   SUM(LEND),
		   1
	FROM #AC_YearTotal
	WHERE ACCOUNTTYPE='00004'
	GROUP BY ACCOUNTTYPE
	
	----负债
	INSERT INTO #Result2
	SELECT '负债',
		   SUM(BORROW),
		   SUM(LEND),
		   2
	FROM #AC_YearTotal
	WHERE ACCOUNTTYPE='00002'
	GROUP BY ACCOUNTTYPE
	
	----权益
	INSERT INTO #Result2
	SELECT '权益',
		   SUM(BORROW),
		   SUM(LEND),
		   2
	FROM #AC_YearTotal
	WHERE ACCOUNTTYPE='00005'
	GROUP BY ACCOUNTTYPE
	
	----损益
	INSERT INTO #Result2
	SELECT '损益',
		   SUM(BORROW),
		   SUM(LEND),
		   2
	FROM #AC_YearTotal
	WHERE ACCOUNTTYPE='00003'
	GROUP BY ACCOUNTTYPE
	
	--------【资产，共同，成本】的合计
	INSERT INTO #Result2
	SELECT '合计1',
		   ISNULL(SUM(BORROW),0),
		   ISNULL(SUM(LEND),0),
		   0
	FROM #Result2
	WHERE GROUPID=1
	
	--------【负债，权益，损益】的合计
	INSERT INTO #Result2
	SELECT '合计2',
		   ISNULL(SUM(BORROW),0),
		   ISNULL(SUM(LEND),0),
		   0
	FROM #Result2
	WHERE GROUPID=2
	
	SELECT ACCOUNTTYPE,dbo.F_RoundTotal(BORROW) AS BORROW,dbo.F_RoundTotal(LEND) AS LEND,GROUPID  FROM #Result2
	
    DROP TABLE #tempFather,#tempData,#AC_INIACCOUNT,#temp,#Result,#temp1,#Result1,#tempYearTotal,#AC_YearTotal,#Result2
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalQueryCheckGetMoneyList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalQueryCheckGetMoneyList]
GO

/*
	作者：谢吉康
	日期：2005-8-9
	描述：制单人收款统计
*/
CREATE PROCEDURE Web_CalQueryCheckGetMoneyList
(
	@OperatorId		VARCHAR(100),	--操作员Id
	@StartDate		VARCHAR(20),	--开始日期
	@STypeId		VARCHAR(8000),	--分支机构
	@EndDate		VARCHAR(20),	--结束日期	
	@PageRows 		INT=14,			--默认显示行数
	@GoPageNo 		INT=0,			--商品的页数
	@EUserCode		VARCHAR(256),	--职员编号
	@EFullName		VARCHAR(256),	--职员名称
	@bCount			INT=10,			--基本信息的默认个数
	@bPageNo		INT=0,			--基本信息的页数
	@BillTypeId		VARCHAR(1000),	--单据类型
	@cid			INT = 0
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 			VARCHAR(8000),
		@ReSQL			VARCHAR(1000),
		@TableName		VARCHAR(1000),
		@SQLCursor		VARCHAR(8000),
		@TypeId			VARCHAR(100),
		@UserCode		VARCHAR(256),
		@FullName		VARCHAR(256),
		@SQLTemp		VARCHAR(8000),
		@CloseCursor	VARCHAR(8000),
		@WhereCid		VARCHAR(200)
		
IF @cid = 0 OR @cid='' OR @cid IS NULL
	SET @WhereCid = ''
ELSE
	SET @WhereCid = ' AND Bil.CID='+CONVERT(VARCHAR,@CID)+'  '
		
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)		
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

CREATE TABLE #BANK(TypeId VARCHAR(50))
INSERT INTO #BANK(TypeId) 
SELECT b.NID FROM ac_items b 
WHERE  TypeName='B' AND UserCode NOT IN('2181','2131','1151')	
	

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(VARCHAR(2),DATEPART(dd,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(hh,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(m,GETDATE()))+CONVERT(VARCHAR(2),DATEPART(s,GETDATE()))+CONVERT(VARCHAR(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		TypeId 		VARCHAR (100) NOT NULL,
		父节点		VARCHAR (100) NOT NULL,
		总计		 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计)VALUES(0,0,0)'

EXEC(@SQL)

CREATE TABLE #BillIndex
(
	Checke		VARCHAR(100),
	ATypeId		VARCHAR(100),
	BillType	VARCHAR(100),
	Total		 NUMERIC(24, 10) 
)

SET @SQL = 'INSERT INTO #BillIndex
			SELECT	0 AS Checke,
					mul.ATypeId,
					Bil.BillType,
					ISNULL(SUM(
								CASE 
									WHEN Bil.BillType IN (305,11,141,160,93,85,157,167,168,172,178,182,179,181,312,196,12) 	THEN ISNULL(mul.NTotalMoney,0)
									WHEN (BIL.billtype =''213'' and bil.AssetBusinessTypeId in(10,11)) THEN ISNULL(mul.NTotalMoney,0)
									ELSE -1*ISNULL(mul.NTotalMoney,0)
								END 
							),0) AS Total
			FROM	BillIndex Bil,
					BillMulAccount mul,
					Employee E,
					LoginUser L,
					#bank b
			WHERE	Bil.BillType <> 195
					AND Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'	
					AND Bil.Checke = E.TypeId
					AND E.TypeId = L.ETypeId	
					AND mul.billnumberid=bil.billnumberid and bil.billtype = mul.billtype
					AND E.UserCode LIKE '+CHAR(39)+'%'+@EUserCode+'%'+CHAR(39)+'
					AND E.FullName LIKE '+CHAR(39)+'%'+@EFullName+'%'+CHAR(39)+'
					AND mul.atypeid = b.typeid
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.IfYearBill = 0
					AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','','')) '+@WhereCid

IF @METypeId = '-99999'
	SET @SQL = @SQL + '	AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'

IF @MATypeId = '-99999'
	SET @SQL = @SQL + '	AND (mul.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+')))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '		
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT * FROM #GetManDTypeId) '	
SET @SQL = @SQL + '
			GROUP BY mul.ATypeId,Bil.BillType '
			
			
SET @SQL = @SQL + 'INSERT INTO #BillIndex
			SELECT	0 AS Checke,
					mul.ATypeId,
					Bil.BillType,
					ISNULL(SUM(
								CASE 
									WHEN Bil.BillType IN (424) 	THEN ISNULL(mul.NTotalMoney,0)
									ELSE -1*ISNULL(mul.NTotalMoney,0)
								END 
							),0) AS Total
			FROM	Coupon_BillIndex Bil,
					BillMulAccount mul,
					Employee E,
					LoginUser L,
					#bank b
			WHERE	Bil.BillType in (424,426)
					AND Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'	
					AND Bil.Checke = E.TypeId
					AND E.TypeId = L.ETypeId	
					AND mul.billnumberid=bil.billnumberid and bil.billtype = mul.billtype
					AND mul.BillType=bil.BillType				
					AND E.UserCode LIKE '+CHAR(39)+'%'+@EUserCode+'%'+CHAR(39)+'
					AND E.FullName LIKE '+CHAR(39)+'%'+@EFullName+'%'+CHAR(39)+'
					AND mul.atypeid = b.typeid
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.IfYearBill = 0
					AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','','')) '+@WhereCid

IF @METypeId = '-99999'
	SET @SQL = @SQL + '	AND Bil.Checker IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'

IF @MATypeId = '-99999'
	SET @SQL = @SQL + '	AND (mul.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+')))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '		
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT * FROM #GetManDTypeId) '	
SET @SQL = @SQL + '
			GROUP BY mul.ATypeId,Bil.BillType '	
/*
SET @SQL = @SQL + '
			GROUP BY mul.ATypeId,Bil.BillType
			UNION ALL
			SELECT	0 AS Checke,
					mul.ATypeId,
					Bil.BillType,
					ISNULL(SUM(
								CASE 
									WHEN Bil.BillType IN (195) 	THEN ISNULL(mul.total,0)
									ELSE -1*ISNULL(mul.total,0)
								END 
							),0) AS Total
			FROM	BillIndex Bil,
					BillMulAccount mul,
					Employee E,
					LoginUser L,
					BillIndex_CarRepair Bic
			WHERE	Bil.BillType = 195
					AND CONVERT(VARCHAR(10),Bic.BalanceDate,120)>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND CONVERT(VARCHAR(10),Bic.BalanceDate,120)<='+CHAR(39)+@EndDate+CHAR(39)+'	
					AND Bil.Checke = E.TypeId
					AND E.TypeId = L.ETypeId	
					AND mul.billnumberid=bil.billnumberid				
					AND Bil.BillNumberId = Bic.BillNumberId
					AND E.UserCode LIKE '+CHAR(39)+'%'+@EUserCode+'%'+CHAR(39)+'
					AND E.FullName LIKE '+CHAR(39)+'%'+@EFullName+'%'+CHAR(39)+'
					AND (mul.ATypeId = ''0000100003'' OR mul.ATypeId LIKE ''0000100004%'')
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.IfYearBill = 0
					AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','','')) '

IF @METypeId = '-99999'
	SET @SQL = @SQL + '	AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'

IF @MATypeId = '-99999'
	SET @SQL = @SQL + '	AND (mul.ATypeId IN (SELECT * FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+')))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '		
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT * FROM #GetManDTypeId) '	
*/

SET @SQL = @SQL + '	
			UNION ALL	
			SELECT	0 AS Checke,	
					G.ATypeId,	
					Bil.BillType,									
					ISNULL(SUM(G.nTotal),0) AS Total
			FROM 	gatheringBill G,
					BillIndex Bil,
					Employee E,
					LoginUser L,
					#bank b
			WHERE	Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
					AND G.BillNumberId = Bil.BillNumberId
					AND Bil.Checke = E.TypeId
					AND E.TypeId = L.ETypeId					
					AND E.UserCode LIKE '+CHAR(39)+'%'+@EUserCode+'%'+CHAR(39)+'
					AND E.FullName LIKE '+CHAR(39)+'%'+@EFullName+'%'+CHAR(39)+'	
					AND g.atypeid = b.typeid 						
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.IfYearBill = 0
					AND Bil.BillType = 4 '+@WhereCid

IF @METypeId = '-99999'
	SET @SQL = @SQL + '	AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'

IF @MATypeId = '-99999'
	SET @SQL = @SQL + '	AND G.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '		
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT * FROM #GetManDTypeId) '	
	
SET @SQL = @SQL + '
			GROUP BY Bil.Checke,G.ATypeId,Bil.BillType
			UNION ALL
			SELECT	0 AS Checke,	
					G.ATypeId,	
					Bil.BillType,									
					ISNULL(SUM(CASE    WHEN BIL.BILLTYPE<>''213''  THEN G.NTotal
										WHEN (BIL.billtype =''213'' and bil.AssetBusinessTypeId in(10,11)) THEN G.NTotal ELSE 0 
								END),0) AS Total
			FROM 	PreBill G,
					BillIndex Bil,
					Employee E,
					LoginUser L,
					#bank b 
			WHERE	Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
					AND G.BillNumberId = Bil.BillNumberId
					AND Bil.Checke = E.TypeId
					AND E.TypeId = L.ETypeId					
					AND E.UserCode LIKE '+CHAR(39)+'%'+@EUserCode+'%'+CHAR(39)+'
					AND E.FullName LIKE '+CHAR(39)+'%'+@EFullName+'%'+CHAR(39)+'	
					AND g.atypeid = b.typeid 			
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.IfYearBill = 0
					AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','','')) ' +@WhereCid

IF @METypeId = '-99999'
	SET @SQL = @SQL + '	AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'

IF @MATypeId = '-99999'
	SET @SQL = @SQL + '	AND G.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '		
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT * FROM #GetManDTypeId) '	
	
SET @SQL = @SQL + '
			GROUP BY Bil.Checke,G.ATypeId,Bil.BillType'			
			
--PRINT @SQL
EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************


SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET 总计 = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
					SELECT 	0 AS Checke,
							ISNULL(SUM(B.Total),0) AS Total
					FROM	(
								SELECT	Checke,
										ISNULL(SUM(Total),0) AS Total
								FROM	#BillIndex
								GROUP BY Checke
							)B
		)X ON (X.Checke = A.TypeId OR A.TypeId = 0) '
PRINT @SQL
EXEC(@SQL)

--RETURN
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
DECLARE @bSonNum 		INT,
		@BaseTypeId		VARCHAR(100),
		@BaseFullName	VARCHAR(256),
		@xjkang			VARCHAR(256)

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS VARCHAR(50)) + ' 
				nid AS TypeID,							
				FullName
	     FROM    ac_items 
		    WHERE    TypeName=''B''
				AND (nTypeId Like ''0000100003%'' OR nTypeId LIKE ''0000100004%'') 
				AND sonnum=0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	ac_items
					WHERE 	(nTypeId LIKE ''0000100003%'' OR nTypeId LIKE ''0000100004%'') 
							AND SonNum = 0							
							AND (nTypeId IN (SELECT nTypeId FROM F_GetManDetailAType('+char(39)+@OperatorID+char(39)+')))
	                ORDER BY
							UserCode
	            )
				AND (nTypeId IN (SELECT nTypeId FROM F_GetManDetailAType('+char(39)+@OperatorID+char(39)+')))
	    ORDER BY UserCode '
	
	EXEC(@SQLCursor)
	
	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + ']  NUMERIC(24, 10) '
			EXEC(@SQL)
			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	0 AS Checke,
								X.ATypeId,
								ISNULL(SUM(X.Total),0) AS Total
						FROM (
								SELECT	0 AS Checke,
										ATypeId,
										ISNULL(SUM(Total),0) AS Total
								FROM 	#BillIndex
								WHERE	ATypeId = '+CHAR(39)+@BaseTypeId+CHAR(39)+'
								GROUP BY ATypeId
							)X GROUP BY X.Checke,X.ATypeId
					)X ON (X.Checke = A.TypeId OR A.TypeId = 0) '
			
		
			EXEC(@SQL)			
	
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		INT,
		@BaseInfoCount 	INT,
		@pSonNum 		INT,
		@TotalpPages	INT,	--商品页数
		@TotalbPages	INT		--基本信息页数

SELECT 	@PTypeCount = Count(E.TypeId)
FROM 	F_GetManETypeAll(@OperatorID) E,
		LoginUser L
WHERE 	E.TypeId = L.ETypeId		
		AND E.TypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
		AND (E.TypeId = '00001' OR E.SonNum =0) 
		AND E.UserCode LIKE '%'+@EUserCode+'%'
		AND E.FullName LIKE '%'+@EFullName+'%'

/*
计算错误
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorID AND MangerETypeId = '00001')
	SET @PTypeCount = @PTypeCount + 1
*/

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@PTypeCount AS VARCHAR(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*)+1 
FROM F_GetManATypeAll(@OperatorID) F
INNER JOIN AC_Items AC ON F.TypeID=AC.nid 
WHERE F.SonNum = 0 
AND (F.nid IN (SELECT nid FROM F_GetManDetailAType(@OperatorID))) AND (AC.TypeName='B')


SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@BaseInfoCount AS VARCHAR(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
				
EXEC(@ReSQL)
PRINT @ReSQL
DROP TABLE #GetManSTypeId,#GetManDTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalSaleDistPageNo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalSaleDistPageNo]
GO



















/*
	作者：谢吉康
	日期：2005-8-9
	描述：销售分布的页码合计
*/
CREATE PROCEDURE Web_CalSaleDistPageNo
(
	@OperatorId		varchar(100),			--操作员Id
	@nType			varchar(100),			--类型  D.部门  B.单位 E.职员  K.仓库
	@DTypeId		varchar(100),			--部门Id	
	@kPageCount		numeric(18,0) Output	--部门页数
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @BaseInfoCount 	int,
		@TotalbPages	int

--部门页数的合计
IF @nType = 'D'
	BEGIN
		CREATE TABLE #DType
		(
			TypeId		varchar(100),
			UserCode	varchar(256),
			FullName	varchar(256)
		)
		
		INSERT INTO #DType 
		SELECT 	TypeId,
				UserCode,
				FullName 
		FROM 	Department 
		WHERE 	TypeId LIKE 
				CASE @DTypeId 
					WHEN '00000' THEN '%' 
					ELSE @DTypeId + '%'
				END
				AND SonNum = 0 
				AND Deleted = 0 
		ORDER BY UserCode
		
		INSERT INTO #DType(TypeId,UserCode,FullName)VALUES('99999','xjk','其他部门')

		SELECT @BaseInfoCount=COUNT(*) FROM #DType

		--删除临时表
		DROP TABLE #DType
	END

--往来单位
IF @nType= 'B'
	BEGIN
		SELECT 	@BaseInfoCount=COUNT(*) 
		FROM 	BType 
		WHERE 	TypeId LIKE 
					CASE @DTypeId 
						WHEN '00000' THEN '%' 
						ELSE @DTypeId + '%'
					END
				AND Deleted = 0 
				AND SonNum = 0
				AND (TypeId LIKE @MBTypeId+'%' OR TypeId LIKE @MBTypeId2+'%')
	END

--职员信息
IF @nType = 'E'
	BEGIN
		SELECT 	@BaseInfoCount=COUNT(*) 
		FROM 	Employee 
		WHERE 	TypeId LIKE @DTypeId + '%'
				AND Deleted = 0
				AND SonNum = 0
				AND TypeId LIKE @METypeId + '%'
	END

--往来单位
IF @nType= 'K'
	BEGIN
		SELECT 	@BaseInfoCount=COUNT(*)+1 
		FROM 	Stock 
		WHERE 	TypeId LIKE 
					CASE @DTypeId 
						WHEN '00000' THEN '%' 
						ELSE @DTypeId + '%'
					END
				AND Deleted = 0 
				AND SonNum = 0
				AND TypeId LIKE @MKTypeId + '%'
	END

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET	@kPageCount = @TotalbPages





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalStockSaleDist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalStockSaleDist]
GO

















/*
	作者：谢吉康
	日期：2005-8-9
	描述：仓库销售分布
*/
CREATE PROCEDURE Web_CalStockSaleDist
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@PTypeId		varchar(100),	--商品Id
	@KTypeId		varchar(100),	--部门Id
	@BillType		varchar(100),	--单据类型
	@nType			varchar(10),	--金额的查询方式
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@showZero		varchar(5)		--0.不显示红冲单据   1.显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @showZero = 1
	SET @showZero = '0,1,2'

IF @KTypeId = '00000'
	SET @KTypeId = '%'

DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@SQL1			varchar(8000),
		@SQL2			varchar(8000),
		@SQL3			varchar(8000),
		@SQL4			varchar(8000),
		@PTypeIdMx		varchar(100)

IF @PTypeId = '00000'
	SET @PTypeIdMx = '%'
ELSE
	SET @PTypeIdMx = @PTypeId


--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		typeid 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计数量,总计金额)VALUES(0,0,0,0)'

EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************
--压缩BillIndex表
CREATE TABLE #BillIndex
(
	BillNumberId 	numeric(18,0),
	KTypeId			varchar(100),
	RedWord			int
)
--压缩商品表
CREATE TABLE #PType
(
	TypeId varchar(100)
)
--压缩销售明细表
CREATE TABLE #SaleBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 	
)
--压缩零售明细
CREATE TABLE #retailBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩销售退货明细
CREATE TABLE #SaleBackBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩代销明细
CREATE TABLE #CommissionBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩换货明细
CREATE TABLE #GoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩维修明细
CREATE TABLE #RepairDealDetail
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
SET @SQL = '
	INSERT INTO #BillIndex
	SELECT	Bil.BillNumberId,
			Bil.KTypeId,
			Bil.RedWord
	FROM	BillIndex Bil
	WHERE	Bil.IfCheck = ''t''

			AND Bil.Draft = 0
			AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
			AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
			AND Bil.BillType IN ('+@BillType+')
			AND Bil.RedWord IN ('+@showZero+')
			AND Bil.KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'
			AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 '

EXEC(@SQL)


SET @SQL = 'INSERT INTO #PType
			SELECT	B.TypeId
			FROM	'+N'##'+@TableName+' N
			LEFT JOIN (
				SELECT	TypeId
				FROM	PType
				WHERE	SonNum = 0
						AND Deleted = 0
			)B ON (LEFT(B.TypeId,LEN(N.TypeId))=N.TypeId) '

EXEC(@SQL)

-------------------------处理含税金额
IF @nType = 0
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleBill
					SELECT	S.PTypeId,
							Bil.RedWord,
							Bil.KTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal
					FROM	BillIndex Bil,
							SaleBill S
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.BillType IN ('+@BillType+')
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 
					GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId '
				
				EXEC(@SQL)
			END
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('45',@BillType)<>0
			BEGIN
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('141',@BillType)<>0
			BEGIN		
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('157',@BillType)<>0
			BEGIN		
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.KTypeId
			END
	END
ELSE
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleBill
					SELECT	S.PTypeId,
							Bil.RedWord,
							Bil.KTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal
					FROM	BillIndex Bil,
							SaleBill S
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
							AND Bil.BillType IN ('+@BillType+')
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 
					GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId '
				
				EXEC(@SQL)
			END
		
		IF CharIndex('305',@BillType)<>0
			BEGIN		
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('141',@BillType)<>0
			BEGIN		
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('155',@BillType)<>0
			BEGIN		
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('157',@BillType)<>0
			BEGIN		
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.PTypeId LIKE @MPTypeId + '%'
						AND S.PTypeId LIKE @PTypeIdMx + '%'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.KTypeId
			END
	END
--********************************************************************************以上压缩数据***************************************************************
SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET [总计数量] = ISNULL(X.Qty,0),
			[总计金额] = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
			SELECT	B.PTypeId,
					ISNULL(SUM(B.Qty),0) AS Qty,
					ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#retailBill S '
				SET @SQL1 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
									ELSE ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
									ELSE ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBackBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#CommissionBill S '
					SET @SQL2 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)

									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#GoodsExchangeBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#RepairDealDetail S
					)B GROUP BY B.PTypeId
		)X ON (X.PTypeId = A.TypeId OR A.TypeId=0)'

--PRINT(@SQL+@SQL1+@SQL2)
EXEC(@SQL+@SQL1+@SQL2)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

SELECT	TypeId,
		Deleted,
		SonNum,
		UserCode,
		FullName
INTO 	#Stock
FROM	Stock
WHERE	Deleted = 0
		AND SonNum = 0
		AND TypeId LIKE @MKTypeId + '%'

INSERT INTO #Stock(TypeId,Deleted,SonNum,UserCode,FullName)VALUES('10000',0,0,'10000','代销仓库')

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    #Stock 
	    WHERE  	SonNum = 0
				AND Deleted = 0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	#Stock
					WHERE 	SonNum = 0
							AND Deleted = 0
							AND (TypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+' OR TypeId = ''10000'')
							AND (TypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR TypeId = ''10000'')
	                ORDER BY
							UserCode
	            )
				AND (TypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+' OR TypeId = ''10000'')
				AND (TypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR TypeId = ''10000'')
	    ORDER BY UserCode '

	EXEC(@SQLCursor)
	
	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @BaseTypeId = '99999'
				SET @xjkang = '谢吉康'

			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '数量]  NUMERIC(24, 10) '
			EXEC(@SQL)
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '金额]  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'数量] = ISNULL(X.Qty,0),
						['+@BaseFullName+'金额] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	B.PTypeId,
								ISNULL(SUM(B.Qty),0) AS Qty,
								ISNULL(SUM(B.Total),0) AS Total
						FROM	(
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#retailBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)
						SET @SQL2 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
												ELSE ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBackBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#CommissionBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)
								SET @SQL3 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#GoodsExchangeBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#RepairDealDetail S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
								)B GROUP BY B.PTypeId
					)X ON (X.PTypeId = A.TypeId OR A.TypeId=0) '
			
			--PRINT(@SQL+@SQL2+@SQL3)
			EXEC(@SQL+@SQL2+@SQL3)
	
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		int,
		@BaseInfoCount 	int,
		@pSonNum 		int,
		@TotalpPages	int,	--商品页数
		@TotalbPages	int		--基本信息页数

SELECT @pSonNum = SonNum FROM PType WHERE TypeId = @PTypeId AND Deleted = 0 AND TypeId LIKE @MPTypeId + '%'

IF @pSonNum = 0 
	SELECT	@PTypeCount = COUNT(*)
	FROM	PType
	WHERE	Deleted = 0
			AND TypeId LIKE @PTypeId + '%' 
			AND TypeId LIKE @MPTypeId + '%'
ELSE
	SELECT	@PTypeCount = COUNT(*)
	FROM	PType
	WHERE	Deleted = 0
			AND ParId = @PTypeId
			AND TypeId LIKE @MPTypeId + '%'
		
IF @PTypeCount%14<>0 
    SET @TotalpPages=@PTypeCount/14+1
ELSE
    SET @TotalpPages=@PTypeCount/14

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@TotalpPages AS varchar(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*) FROM #Stock WHERE SonNum = 0 AND Deleted = 0 AND TypeId LIKE @KTypeId + '%' AND TypeId LIKE @MKTypeId + '%'

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@TotalbPages AS varchar(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)

--删除定义的临时表
DROP TABLE #Stock,#BillIndex,#SaleBill,#retailBill,#CommissionBill,#GoodsExchangeBill,#RepairDealDetail
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BillIndex0]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[BillIndex0]
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CalStockSaleDistLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CalStockSaleDistLine]
GO





























/*
	作者：谢吉康
	日期：2005-8-9
	描述：仓库销售分布
*/
CREATE PROCEDURE Web_CalStockSaleDistLine
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--结束日期
	@PTypeId		varchar(100),	--商品Id
	@KTypeId		varchar(100),	--部门Id
	@BillType		varchar(100),	--单据类型
	@nType			varchar(10),	--金额的查询方式
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@showZero		varchar(5)		--0.不显示红冲单据   1.显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SET @showZero = 0
IF @showZero = 1
	SET @showZero = '0,1,2'

IF @KTypeId = '00000'
	SET @KTypeId = '%'

DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@SQL1			varchar(8000),
		@SQL2			varchar(8000),
		@SQL3			varchar(8000),
		@SQL4			varchar(8000),
		@PTypeIdMx		varchar(100)

IF @PTypeId = '00000'
	SET @PTypeIdMx = @MPTypeId
ELSE
	SET @PTypeIdMx = @PTypeId

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		typeid 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		总计数量	 NUMERIC(24, 10) ,
		总计金额	 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeId,父节点,总计数量,总计金额)VALUES(0,0,0,0)'

EXEC(@SQL)
--********************************************************************************计算总合计*****************************************************************
--压缩BillIndex表
CREATE TABLE #BillIndex
(
	BillNumberId 	numeric(18,0),
	KTypeId			varchar(100),
	RedWord			int
)
--压缩商品表
CREATE TABLE #PType
(
	TypeId varchar(100)
)
--压缩销售明细表
CREATE TABLE #SaleBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 	
)
--压缩零售明细
CREATE TABLE #retailBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩销售退货明细
CREATE TABLE #SaleBackBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩代销明细
CREATE TABLE #CommissionBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) 
)
--压缩换货明细
CREATE TABLE #GoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩维修明细
CREATE TABLE #RepairDealDetail
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
--压缩销售换货单明细
CREATE TABLE #SaleGoodsExchangeBill
(
	PTypeId		varchar(100),
	RedWord		int,
	KTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	TaxTotal	 NUMERIC(24, 10) ,
	InOrOut		varchar(2)
)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
SET @SQL = '
	INSERT INTO #BillIndex
	SELECT	Bil.BillNumberId,
			Bil.KTypeId,
			Bil.RedWord
	FROM	BillIndex Bil
	WHERE	Bil.IfCheck = ''t''
			AND Bil.Draft = 0
			AND Bil.BillType IN ('+@BillType+')
			AND Bil.RedWord IN ('+@showZero+')
			AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
			AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'			
			AND (Bil.KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'  OR Bil.KTypeId = ''10000'')
			AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND (Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR Bil.KTypeId = ''10000'')
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')	 '

EXEC(@SQL)


SET @SQL = 'INSERT INTO #PType
			SELECT	TypeId
			FROM 	PType
			WHERE	SonNum = 0
					AND Deleted = 0
					AND TypeId LIKE '+char(39)+@PTypeIdMx+'%'+char(39)+'
					AND TypeId LIKE '+char(39)+@MPTypeId+'%'+char(39)

EXEC(@SQL)

-------------------------处理含税金额
IF @nType = 0
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleBill
					SELECT	S.PTypeId,
							Bil.RedWord,
							Bil.KTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal
					FROM	#BillIndex Bil,
							SaleBill S,
							#PType P
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND P.TypeId = S.PTypeId
					GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId '
				
				EXEC(@SQL)
			END
		
		IF CharIndex('305',@BillType)<>0
			BEGIN
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('141',@BillType)<>0
			BEGIN		
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('155',@BillType)<>0
			BEGIN
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('157',@BillType)<>0
			BEGIN
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.TaxTotal) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId=S.BillNumberId
						AND S.PTypeId=P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.KTypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN		
				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	I.PTypeId,
							Bil.RedWord,
							Bil.KTypeId2,
							SUM(S.Qty) AS Qty,
							SUM(S.TaxTotal) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S
					INNER JOIN (
							SELECT	DISTINCT
									PTypeId
							FROM	InOutStockTable
							WHERE	BillType = 160
									AND Qty<=0
									AND KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'
									AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
									AND Audited = 1
					)I ON I.PTypeId = S.PTypeId
					INNER JOIN BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
					INNER JOIN #PType P ON P.TypeId = S.PTypeId
					WHERE	S.InOrOut = ''o''							
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'	
							AND Bil.KTypeId2 LIKE '+char(39)+@KTypeId+'%'+char(39)+'	
							AND Bil.KTypeId2 LIKE '+char(39)+@MKTypeId+'%'+char(39)+'		
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY I.PTypeId,Bil.KTypeId2,S.InOrOut,Bil.RedWord '

				EXEC(@SQL)

				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	I.PTypeId,
							Bil.RedWord,
							Bil.KTypeId,
							-1*SUM(S.Qty) AS Qty,
							-1*SUM(S.TaxTotal) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S
					INNER JOIN (
							SELECT	DISTINCT
									PTypeId
							FROM	InOutStockTable
							WHERE	BillType = 160
									AND Qty>=0
									AND KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'
									AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
									AND Audited = 1
					)I ON I.PTypeId = S.PTypeId
					INNER JOIN BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
					INNER JOIN #PType P ON P.TypeId = S.PTypeId
					WHERE	S.InOrOut = ''i''							
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
							AND Bil.KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'	
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'			
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY I.PTypeId,Bil.KTypeId,S.InOrOut,Bil.RedWord '


				EXEC(@SQL)
			END
	END
ELSE
	BEGIN
		IF CharIndex('11',@BillType)<>0
			BEGIN
				SET @SQL = '
					INSERT INTO #SaleBill
					SELECT	S.PTypeId,
							Bil.RedWord,
							Bil.KTypeId,
							SUM(S.Qty) AS Qty,
							SUM(S.Total) AS TaxTotal
					FROM	#BillIndex Bil,
							SaleBill S,
							#PType P
					WHERE	Bil.BillNumberId = S.BillNumberId
							AND P.TypeId = S.PTypeId
					GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId '
				
				EXEC(@SQL)
			END
		
		IF CharIndex('305',@BillType)<>0
			BEGIN		
				INSERT INTO #retailBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	retailBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('45',@BillType)<>0
			BEGIN		
				INSERT INTO #SaleBackBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	SaleBackBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('141',@BillType)<>0
			BEGIN
				INSERT INTO #CommissionBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal
				FROM	CommissionBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
				GROUP BY S.PTypeId,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('155',@BillType)<>0
			BEGIN		
				INSERT INTO #GoodsExchangeBill
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	GoodsExchangeBill S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.KTypeId
			END
		
		IF CharIndex('157',@BillType)<>0
			BEGIN		
				INSERT INTO #RepairDealDetail
				SELECT	S.PTypeId,
						Bil.RedWord,
						Bil.KTypeId,
						SUM(S.Qty) AS Qty,
						SUM(S.Total) AS TaxTotal,
						InOrOut
				FROM	RepairDealDetail S,
						#BillIndex Bil,
						#PType P
				WHERE	Bil.BillNumberId = S.BillNumberId
						AND S.PTypeId = P.TypeId
						AND S.InOrOut = 'o'
				GROUP BY S.PTypeId,S.InOrOut,Bil.RedWord,Bil.KTypeId
			END

		IF CharIndex('160',@BillType)<>0
			BEGIN		
				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	I.PTypeId,
							Bil.RedWord,
							Bil.KTypeId2,
							SUM(S.Qty) AS Qty,
							SUM(S.Total) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S
					INNER JOIN (
							SELECT	DISTINCT
									PTypeId
							FROM	InOutStockTable
							WHERE	BillType = 160
									AND Qty<=0
									AND KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'
									AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
									AND Audited = 1
					)I ON I.PTypeId = S.PTypeId
					INNER JOIN BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
					INNER JOIN #PType P ON P.TypeId = S.PTypeId
					WHERE	S.InOrOut = ''o''							
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'		
							AND Bil.KTypeId2 LIKE '+char(39)+@KTypeId+'%'+char(39)+'	
							AND Bil.KTypeId2 LIKE '+char(39)+@MKTypeId+'%'+char(39)+'	
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY I.PTypeId,Bil.KTypeId2,S.InOrOut,Bil.RedWord '

				EXEC(@SQL)

				SET @SQL = '
					INSERT INTO #SaleGoodsExchangeBill
					SELECT	I.PTypeId,
							Bil.RedWord,
							Bil.KTypeId,
							-1*SUM(S.Qty) AS Qty,
							-1*SUM(S.Total) AS TaxTotal,
							S.InOrOut
					FROM	SaleGoodsExchangeBill S
					INNER JOIN (
							SELECT	DISTINCT
									PTypeId
							FROM	InOutStockTable
							WHERE	BillType = 160
									AND Qty>=0
									AND KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'
									AND KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'
									AND Audited = 1
					)I ON I.PTypeId = S.PTypeId
					INNER JOIN BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
					INNER JOIN #PType P ON P.TypeId = S.PTypeId
					WHERE	S.InOrOut = ''i''							
							AND Bil.IfCheck = ''t''
							AND Bil.Draft = 0
							AND Bil.RedWord IN ('+@showZero+')
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'	
							AND Bil.KTypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+'	
							AND Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+'		
							AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
							AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
					GROUP BY I.PTypeId,Bil.KTypeId,S.InOrOut,Bil.RedWord '


				EXEC(@SQL)
			END
	END
--********************************************************************************以上压缩数据***************************************************************
SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET [总计数量] = ISNULL(X.Qty,0),
			[总计金额] = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		LEFT JOIN (
			SELECT	B.PTypeId,
					ISNULL(SUM(B.Qty),0) AS Qty,
					ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total

						FROM 	#SaleBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#retailBill S '
			SET @SQL1 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
									ELSE ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
									ELSE ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleBackBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#CommissionBill S '
				SET @SQL2 = '
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#GoodsExchangeBill S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#RepairDealDetail S
						UNION ALL
						SELECT	0 AS PTypeId,
								CASE
									WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
									ELSE -1*ISNULL(S.Qty,0)
								END AS Qty,
								CASE
									WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
									ELSE -1*ISNULL(S.TaxTotal,0)
								END AS Total
						FROM 	#SaleGoodsExchangeBill S
					)B GROUP BY B.PTypeId
		)X ON (X.PTypeId = A.TypeId OR A.TypeId=0)'

--PRINT(@SQL+@SQL1+@SQL2)
EXEC(@SQL+@SQL1+@SQL2)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

SELECT	TypeId,
		Deleted,
		SonNum,
		UserCode,
		FullName
INTO 	#Stock
FROM	Stock
WHERE	Deleted = 0
		AND SonNum = 0
		AND TypeId LIKE @MKTypeId + '%'

INSERT INTO #Stock(TypeId,Deleted,SonNum,UserCode,FullName)VALUES('10000',0,0,'10000','代销仓库')

SET @SQLCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    #Stock 
	    WHERE  	SonNum = 0
				AND Deleted = 0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	#Stock
					WHERE 	SonNum = 0
							AND Deleted = 0
							AND (TypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+' OR TypeId = ''10000'')
							AND (TypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR TypeId = ''10000'')
	                ORDER BY
							UserCode
	            )
				AND (TypeId LIKE '+char(39)+@KTypeId+'%'+char(39)+' OR TypeId = ''10000'')
				AND (TypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR TypeId = ''10000'')
	    ORDER BY UserCode '

	EXEC(@SQLCursor)
	
	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @BaseTypeId = '99999'
				SET @xjkang = '谢吉康'

			--修改表结构
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '数量]  NUMERIC(24, 10) '
			EXEC(@SQL)
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + '金额]  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'数量] = ISNULL(X.Qty,0),
						['+@BaseFullName+'金额] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	B.PTypeId,
								ISNULL(SUM(B.Qty),0) AS Qty,
								ISNULL(SUM(B.Total),0) AS Total
						FROM	(
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#retailBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL2 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN -1*ISNULL(S.Qty,0) 
												ELSE ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN -1*ISNULL(S.TaxTotal,0)
												ELSE ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleBackBill S

									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#CommissionBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)
							SET @SQL3 = '
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#GoodsExchangeBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#RepairDealDetail S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
									UNION ALL
									SELECT	0 AS PTypeId,
											CASE
												WHEN S.RedWord IN (0,1) THEN ISNULL(S.Qty,0) 
												ELSE -1*ISNULL(S.Qty,0)
											END AS Qty,
											CASE
												WHEN S.RedWord IN (0,1) 	THEN ISNULL(S.TaxTotal,0)
												ELSE -1*ISNULL(S.TaxTotal,0)
											END AS Total
									FROM 	#SaleGoodsExchangeBill S
									WHERE	S.KTypeId = '+char(39)+@BaseTypeId+char(39)+'
								)B GROUP BY B.PTypeId
					)X ON (X.PTypeId = A.TypeId OR A.TypeId=0) '
			
			--PRINT(@SQL+@SQL2+@SQL3)
			EXEC(@SQL+@SQL2+@SQL3)
	
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

--处理商品，基本信息的总页数
DECLARE @PTypeCount		int,
		@BaseInfoCount 	int,
		@pSonNum 		int,
		@TotalpPages	int,	--商品页数
		@TotalbPages	int		--基本信息页数

IF @PTypeId = '00000'
	SET @PTypeId = '%'

SELECT	@PTypeCount = COUNT(*)
FROM	PType
WHERE	Deleted = 0
		AND SonNum = 0
		AND TypeId LIKE @PTypeId + '%' 
		AND TypeId LIKE @MPTypeId + '%' 
		
IF @PTypeCount%14<>0 
    SET @TotalpPages=@PTypeCount/14+1
ELSE
    SET @TotalpPages=@PTypeCount/14

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET TypeId = '+CAST(@TotalpPages AS varchar(100))
EXEC(@SQL)

----------------------------------------------------------------计算基本信息的合计
SELECT @BaseInfoCount=COUNT(*) FROM #Stock WHERE SonNum = 0 AND Deleted = 0 AND TypeId LIKE @KTypeId + '%' AND TypeId LIKE @MKTypeId + '%'

IF @BaseInfoCount%10<>0
	SET @TotalbPages=@BaseInfoCount/10+1
ELSE
	SET @TotalbPages=@BaseInfoCount/10

SET @SQL = 'UPDATE '+N'##'+@TableName+' SET 父节点 = '+CAST(@TotalbPages AS varchar(100))
EXEC(@SQL)


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)

--删除定义的临时表
DROP TABLE #PType,#Stock,#BillIndex,#SaleBill,#retailBill,#CommissionBill,#GoodsExchangeBill,#RepairDealDetail,#SaleGoodsExchangeBill

RETURN 0

























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CargoIsStopOrStartOrDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CargoIsStopOrStartOrDelete]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2012-6-20
	描述：货位的启用删除，暂停
-------------------------------------------*/
CREATE PROCEDURE Web_CargoIsStopOrStartOrDelete
(
	@strControlType			VARCHAR(20),
	@CargoID				INT
)
--@encode$--
AS
SET NOCOUNT ON

IF @strControlType = 'DELETE'
BEGIN
	DECLARE  @CarGoUsed	INT
	EXEC Web_CheckCargoIsUsed @Cargoid,@CarGoUsed OUTPUT 
	--@CarGoUsed	INT OUTPUT		--0代表未使用，1代表使用
	IF @CarGoUsed = 1
	BEGIN
		RAISERROR('此信息已被使用，不能删除！', 16,1)
		RETURN
	END
	DELETE CargoType WHERE CargoID = @CargoID
END
ELSE IF @strControlType = 'STOP'
BEGIN
	IF EXISTS(SELECT * FROM CargoType WHERE CargoID = @CargoID AND deleted = 0)
	BEGIN
		UPDATE CargoType SET deleted = 1 WHERE CargoID = @CargoID
	END
	ELSE
	BEGIN
		RAISERROR('要停用的记录不存在！', 16,1) RETURN
	END
END
ELSE
BEGIN
	IF EXISTS(SELECT * FROM CargoType WHERE CargoID = @CargoID AND deleted = 1)
	BEGIN
		UPDATE CargoType SET deleted = 0 WHERE CargoID = @CargoID
	END
	ELSE
	BEGIN
		RAISERROR('要启用的记录不存在！', 16,1) RETURN
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CargoSelect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CargoSelect]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2013-11-13
	描述：货位选择
-------------------------------------------*/
CREATE PROCEDURE Web_CargoSelect
(
	@OperatorID			VARCHAR(50),
	@Ktypeid			VARCHAR(50),		--仓库
	@Filter				VARCHAR(256),		--筛选字段
	@IsZero				INT=0,				--只显示有库存货位 1=勾选
	@IsShowCargo		INT = -1,			--  -1不需要出库存数量
	@PTypeid			VARCHAR(50)='',		--商品
	@ItemID				VARCHAR(10),		--自由项
	@Iscombined			VARCHAR(5),			--是否组合项
	@GoodsNumber		VARCHAR(100)='',	--批号
	@GoodsNumberPrice	VARCHAR(50),		--批次
	@Costing			INT					--成本算法 0=移动加权 1=先进先出 2=后进先出 3=手工指定
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #StockQty
(
	CargoID		NUMERIC(10,0),
	Qty			 NUMERIC(24, 10) 		
)

CREATE TABLE #CargoType
(
	parid		VARCHAR(50),
	CargoID		NUMERIC(10,0),
	UserCode	VARCHAR(256),
	FullName	VARCHAR(256),
	PyCode		VARCHAR(256)
)

--插入货位
INSERT INTO #CargoType(parid,CargoID,UserCode,FullName,PyCode)
SELECT '' AS parid, CargoID, UserCode, FullName, PyCode
FROM CARGOTYPE
WHERE deleted = 0 AND ktypeid = @Ktypeid 
	AND (userCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%') 
ORDER BY usercode 

IF @PTypeid = '' OR @IsZero = -1 OR @IsShowCargo = -1  --不需要出库存数量
BEGIN
	SELECT * FROM #CargoType
END
ELSE  --需要出库数量
BEGIN
	DECLARE @SQL VARCHAR(MAX)
	
	SET @SQL = 
		'	INSERT INTO #StockQty(CargoID,Qty)
			SELECT g.CargoID,ISNULL(SUM(g.Qty),0) AS Qty FROM GOODSSTOCKS_QTY g '
	
	--IF @GoodsOrder <> '' AND @GoodsOrder <> '0'
	--SET @SQL += ' INNER JOIN GOODSSTOCKS s ON s.PtypeId = g.PTypeID AND s.KtypeId = g.KTypeID AND s.GoodsNumber=g.GoodsNumber '
	
	SET @SQL += '  WHERE g.KTypeID = '''+@Ktypeid+''' AND g.PTypeID = '''+@PTypeid+''' '
		
	IF @ItemID <> '' AND @ItemID <> '0'
	SET @SQL += ' AND g.ItemID = '''+@ItemID+''' AND g.Iscombined = '''+@Iscombined+''' '
	
	IF @GoodsNumber <> '' AND @GoodsNumber <> '0'
	SET @SQL += ' AND g.GoodsNumber = '''+@GoodsNumber+''' '
	
	IF @Costing = 3 AND @GoodsNumberPrice <> '' AND CAST(@GoodsNumberPrice AS  NUMERIC(24, 10) ) <> -1
	SET @SQL += ' AND g.GoodsCostPrice = '''+@GoodsNumberPrice+''' '
	 
	SET @SQL += ' GROUP BY g.CargoID '
	
	--PRINT(@SQL)
	EXEC(@SQL)
	
	IF @IsZero = 1
		SELECT 0 AS multflag,C.*,S.Qty FROM #CargoType C INNER JOIN #StockQty S ON S.CargoID = C.CargoID WHERE Qty > 0 OR Qty < 0
	ELSE 
		SELECT 0 AS multflag,C.*,ISNULL(S.Qty,0) as Qty FROM #CargoType C LEFT JOIN #StockQty S ON S.CargoID = C.CargoID
END

DROP TABLE #CargoType,#StockQty

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CargoTypeExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CargoTypeExists]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2012-6-19
	描述：检测货位是否存在相同编号或名称
-------------------------------------------*/
CREATE PROCEDURE Web_CargoTypeExists
(
	@Ktypeid		VARCHAR(100),
	@UserCode		VARCHAR(100),
	@FullName		VARCHAR(100),
	@CargoID		VARCHAR(20)
)
--@encode$--
AS
SET NOCOUNT ON

IF ISNULL(@CargoID,'') = ''		--新增
BEGIN
	IF EXISTS(SELECT * FROM CargoType WHERE UserCode = @UserCode)
	BEGIN
		RETURN 1
	END
	
	IF EXISTS (SELECT * FROM CargoType WHERE FullName = @FullName)
	BEGIN
		RETURN 2
	END
	
	IF EXISTS (SELECT * FROM CargoType WHERE FullName = @FullName AND KtypeID = @Ktypeid)
	BEGIN
		RETURN 2
	END
END
ELSE
BEGIN
	IF EXISTS(SELECT * FROM CargoType WHERE UserCode = @UserCode AND CargoID <> @CargoID)
	BEGIN
		RETURN 1
	END
	
	IF EXISTS (SELECT * FROM CargoType WHERE FullName = @FullName AND UserCode <> @UserCode)
	BEGIN
		RETURN 2
	END
	
	IF EXISTS (SELECT * FROM CargoType WHERE FullName = @FullName AND KtypeID = @Ktypeid AND CargoID <> @CargoID)
	BEGIN
		RETURN 2
	END
END

RETURN 0;

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_CheckAccount
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：董湛	
	日期：2013-05-10
	描述：检查科目
-------------------------------------------*/
CREATE PROCEDURE Web_CheckAccount
(
       @STypeId 	   VARCHAR(50),    ---分支机构
       @AtypeId		   VARCHAR(max)    --科目
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	----要查询的分支机构(包含非独立核算机构)
	CREATE TABLE #tempStype(typeid varchar(50),verifytypeid VARCHAR(50))
	INSERT INTO #tempStype(typeid,verifytypeid)
	SELECT @STypeId,TypeId FROM dbo.SType WHERE deleted=0 AND sonnum=0 AND VerifyID=@STypeId
	----要查询的科目
    CREATE TABLE #tempAtype(STYPEID VARCHAR(50),TypeId VARCHAR(50),FullName NVARCHAR(max))
	IF @AtypeId=''
		INSERT INTO #tempAtype
	    SELECT B.verifytypeid,AA.TypeId,FullName 
	    FROM Ac_Account AA
	    JOIN #tempStype B ON AA.StypeId=B.typeid
	    WHERE AA.Leveal >1  AND AA.Deleted=0  AND AA.sonnum=0
	ELSE 
		INSERT INTO #tempAtype
		SELECT s.verifytypeid,aa.TypeID,aa.FUllNAME 
		FROM dbo.Ac_Account aa 
		JOIN  dbo.f_split(@AtypeId,',') f ON aa.TypeId=f.a
		JOIN #tempStype s ON aa.StypeId=s.typeid
		
	-----------------------------------------------------------------------------------------------------------------------------------------------------------------
	CREATE TABLE #tempResult
	(
	   ResultType   INT,  ---1会计凭证 2余额(2期初，3acblance余额) 4单据 5模版 6项目关联 7往来设置 8 固定资产卡片 9 常用凭证模版表 10 出纳-银行账户 11 出纳-初始化数据 12 出纳-未达账 13 出纳-资金调拨单 14：存货类型
	   AtypeName    NVARCHAR(max),
	   Relation		NVARCHAR(max)    ---关联的数据
	)	
	-----------------------1 会计凭证-----------------------------------------------------------------------------------------------------
	INSERT INTO #tempResult(ResultType, AtypeName)
	SELECT 1,a.FullName  
	FROM dbo.Ac_Voucher_Bill b 
	JOIN #tempAtype a ON b.ATypeId=a.TypeId AND b.STypeId=a.STYPEID
	----------------------2 余额 ---------------------------------------------------------------------------------------------------------
	 ---期初
	 INSERT INTO #tempResult(ResultType, AtypeName)
	 SELECT 2,a.FullName 
	 FROM dbo.Ac_IniAccount ai
	 JOIN #tempAtype a ON ai.ATypeId=a.TypeId AND ai.STypeId=a.STYPEID
	 WHERE (ai.FDebit!=0 OR ai.FDebitFor!=0 OR ai.FCredit!=0 OR ai.FCreditFor!=0 OR ai.iniTotal!=0 OR ai.iniTotalFor!=0 OR ai.FDebitqty<>0 OR ai.FCreditqty<>0 OR ai.iniqty<>0 OR ai.IniYqty<>0) 
	  
     --余额
	 INSERT INTO #tempResult(ResultType, AtypeName)
     SELECT 3,a.FullName
     FROM dbo.Ac_Balance ab 
     JOIN #tempAtype a ON ab.ATypeId=a.TypeId AND ab.STypeId=a.STYPEID
     WHERE (ab.FDebit!=0 OR ab.FDebitFor!=0 OR ab.FCredit!=0 OR ab.FCreditFor!=0 OR ab.FEndBalance!=0 OR ab.FEndBalanceFor!=0 OR AB.FBeginqty<>0 OR ab.FDebitqty<>0 OR ab.FCreditqty<>0 OR ab.FEndqty<>0 OR ab.FYtdDebitqty<>0 OR ab.FYtdCreditqty<>0) 
	---------------------4 单据---------------------------------------------------------------------------------------------------------------------------
	;WITH #temp4 AS 
	(
	SELECT DISTINCT a.TypeId,bn.BillName  
	FROM dbo.BillIndex b 
	JOIN #tempAtype a ON b.ATypeID1=a.TypeId AND b.Stypeid=a.STYPEID
	JOIN dbo.BillName bn ON b.BillType=bn.Billtype   
	)
	INSERT INTO #tempResult(ResultType, AtypeName, Relation)
	SELECT 4,a.FullName,t.BillName
	FROM  
	(
		SELECT  #temp4.TypeId,BillName=STUFF((select ',' + BillName from #temp4 t where TypeId = #temp4.TypeId for xml path('')) , 1 , 1 , '')  
		FROM #temp4 
		GROUP BY #temp4.TypeId
	) t
	JOIN #tempAtype a ON t.TypeId = a.TypeId
	
	-----------------------5 模版表---------------------------------------------------------------------------------------------------------------
    ;WITH #temp5 AS 
    (
    SELECT  a.TypeId,t.UserCode,t.FullName
	FROM Ac_Auditing_Template t
	JOIN Ac_Auditing_Template_Detail d ON d.Atid = t.AtId
	JOIN #tempAtype a ON d.ATypeId=a.TypeId AND t.STypeId=a.STYPEID
	)
	INSERT INTO #tempResult(ResultType, AtypeName, Relation)     
	SELECT 5,a.FullName,t.UserCode 
	FROM 
	(
	SELECT #temp5.TypeId,UserCode=STUFF((select ',' + UserCode+'('+FullName+')' from #temp5 t where TypeId = #temp5.TypeId for xml path('')) , 1 , 1 , '') 
	FROM #temp5 
	GROUP BY #temp5.TypeId
	) t
	JOIN #tempAtype a ON t.TypeId = a.TypeId
	----------------------------6项目关联--------------------------------------------------------------------------------------------------
	--INSERT INTO #tempResult(ResultType, AtypeName,Relation)
	--SELECT 6,a.FullName,ai.fullname                                       
	--FROM dbo.Ac_Items_Detail ac 
	--JOIN #tempAtype a ON (ac.ATypeId=a.TypeId OR ac.DepATypeId=a.TypeId OR ac.DisATypeId=a.TypeId) AND ac.STypeId=a.STYPEID 
	--JOIN Ac_Items ai ON ac.nid=ai.nid
	 ;WITH #temp6 AS 
    (
   	SELECT a.FullName,ai.fullname AS itemfullname                              
	FROM dbo.Ac_Items_Detail ac 
	JOIN #tempAtype a ON (ac.ATypeId=a.TypeId OR ac.DepATypeId=a.TypeId OR ac.DisATypeId=a.TypeId) AND ac.STypeId=a.STYPEID 
	JOIN Ac_Items ai ON ac.nid=ai.nid
	)
	INSERT INTO #tempResult(ResultType, AtypeName, Relation)     
	SELECT 6,a.FullName,t.itemfullname 
	FROM 
	(
	SELECT #temp6.FullName,itemfullname=STUFF((select ',' + itemfullname from #temp6 t where FullName = #temp6.FullName for xml path('')) , 1 , 1 , '')  
	FROM #temp6 
	GROUP BY #temp6.FullName
	) t
	JOIN #tempAtype a ON t.FullName = a.FullName
	
	
	---------------------------7 往来科目设置，只有分支机构那------------------------------------------------------------------------------------
	INSERT INTO #tempResult(ResultType, AtypeName)
	SELECT 7,a.FullName 
	FROM dbo.SType s 
	JOIN #tempAtype a ON (s.ATypeID=a.TypeId OR s.ATypeID2=a.TypeId OR s.ATypeID3=a.TypeId OR s.ATypeID4=a.TypeId ) AND s.TypeId=a.STYPEID
	UNION 
	SELECT DISTINCT 7,a.FullName 
	FROM BillAtype b 
	JOIN #tempAtype a ON b.AtypeId=a.TypeId AND b.StypeId=a.STYPEID
	--------------------------8 固定资产卡片-------------------------------------------------------------------------
	IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')  --卡片模式
		BEGIN
			--卡片
			INSERT INTO #tempResult(ResultType, AtypeName, Relation)
			SELECT 81,a.FullName,ac.FullName
			FROM Ac_AssetsCards ac
			JOIN #tempAtype a ON (ac.AssertATypeId=a.TypeId OR ac.DisATypeId=a.TypeId OR ac.DepATypeId=a.TypeId OR ac.DevalueATypeId=a.TypeId)
			--固定资产类别
			INSERT INTO #tempResult(ResultType, AtypeName)
			SELECT DISTINCT 82,a.FullName
			FROM Ac_AssetsCategory ac
			JOIN #tempAtype a ON (ac.AssertATypeId=a.TypeId OR ac.DepATypeId=a.TypeId OR ac.ExpenseATypeId=a.TypeId)
		END
		
	-----------------------9 常用凭证模版表---------------------------------------------------------------------------------------------------------------
    ;WITH #temp9 AS 
    (
    SELECT  a.TypeId,t.BillName
	FROM dbo.Ac_Voucher_Commonly t
	JOIN dbo.Ac_Voucher_Commonly_Bill d ON d.BillNumberId = t.BillNumberId
	JOIN #tempAtype a ON d.ATypeId=a.TypeId AND t.STypeId=a.STYPEID
	)
	INSERT INTO #tempResult(ResultType, AtypeName, Relation)     
	SELECT 9,a.FullName,t.BillName 
	FROM #temp9 t
	JOIN #tempAtype a ON t.TypeId = a.TypeId
	--------------------------10 出纳-银行账户-------------------------------------------------------------------------
	INSERT INTO #tempResult(ResultType, AtypeName,Relation)  
	SELECT 10,T2.fullname,T1.FullName
	FROM dbo.Te_BankAccount T1
		INNER JOIN #tempAtype T2 ON T1.ATypeId = T2.typeid
	WHERE T1.STypeId = @STypeId
	--------------------------11 出纳-初始化数据-----------------------------------------------------------------------
	INSERT INTO #tempResult(ResultType, AtypeName,Relation)  
	SELECT 11,T2.fullname,'【' + t5.FullName + '】' + t4.FullName
	FROM dbo.Te_InitDataDetail T1
		INNER JOIN #tempAtype T2 ON T1.ATypeId = T2.typeid
		LEFT JOIN Te_InitDataIndex T3 ON T3.Id = T1.IndexId
		LEFT JOIN dbo.Te_BusinessType T4 ON T3.BUId = T4.Id
		LEFT JOIN dbo.SType T5 ON T3.STypeId = T5.TypeId
	WHERE T1.FDebit <> 0 OR T1.FCredit <> 0 OR T1.InitBalance <> 0 AND T3.STypeId = @STypeId
	--------------------------12 出纳-未达账--------------------------------------------------------------------------
	INSERT INTO #tempResult(ResultType, AtypeName,Relation)  
	SELECT 12,T2.fullname,
			CASE WHEN T1.Type = 0 THEN '【银行未达账】' + T3.FullName
				ELSE '【企业未达账】' + T3.FullName
			END
	FROM dbo.Te_AccountInTransit_Index T1
		INNER JOIN #tempAtype T2 ON T1.ATypeId = T2.typeid
		INNER JOIN dbo.Te_BankAccount T3 ON T1.AccountId = T3.Id AND T3.STypeId = @STypeId
	--------------------------13 出纳-资金调拨单--------------------------------------------------------------------------
	INSERT INTO #tempResult(ResultType, AtypeName,Relation)  
	SELECT DISTINCT 13,T3.fullname,T1.BillCode FROM dbo.BillIndex T1
		INNER JOIN dbo.CapitalTransfer_Bill T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN #tempAtype T3 ON (T2.BankAccountIn = T3.TypeId AND T1.Stypeid = T3.StypeId) 
										OR (T2.BankAccountOut = T3.TypeId AND T1.Stypeid2 = T3.StypeId)
	WHERE BillType = 310 AND TransferType = 1 AND (T1.STypeId = @STypeId OR T1.StypeID2 = @STypeId)
	-----------------------14 存货类型-----------------------------------------------------------------------------------------------------
	INSERT INTO #tempResult(ResultType, AtypeName,Relation)
	SELECT 
		14 ResultType,
		a.FullName,
		T.FullName  
	FROM dbo.Base_InventoryType T
	INNER JOIN dbo.Base_InventoryTypeDetails b  ON B.TID=T.NID
	INNER JOIN #tempAtype a ON a.TypeId=B.StockATypeID AND a.STYPEID=b.STypeID	
	GROUP BY A.FullName,T.FullName
	
	UNION ALL
	
	SELECT 
		14 ResultType,
		a.FullName,
		T.FullName   
	FROM dbo.Base_InventoryType T
	INNER JOIN dbo.Base_InventoryTypeDetails b  ON B.TID=T.NID
	INNER JOIN #tempAtype a ON a.TypeId=B.IncomeATypeID AND a.STYPEID=b.STypeID	
	GROUP BY A.FullName,T.FullName
	
	UNION ALL
	
	SELECT 
		14 ResultType,
		a.FullName,
		T.FullName  
	FROM dbo.Base_InventoryType T
	INNER JOIN dbo.Base_InventoryTypeDetails b  ON B.TID=T.NID
	INNER JOIN #tempAtype a ON a.TypeId=B.CostATypeID AND a.STYPEID=b.STypeID
	GROUP BY A.FullName,T.FullName
	
	-----------------------15 多栏账设计-----------------------------------------------------------------------------------------------------
	INSERT INTO #tempResult(ResultType, AtypeName,Relation)
	SELECT 
		15 ResultType,
		a.FullName,
		T.AccountName Relation
	FROM dbo.Ac_MulColumnAccount T
	INNER JOIN #tempAtype a ON a.TypeId=T.ATypeid AND a.STYPEID=T.STypeid	
	GROUP BY A.FullName,T.AccountName
	
	------------------------------------查询结果-----------------------------------------------------------------
	SELECT DISTINCT * FROM #tempResult
	
	DROP TABLE #tempAtype,#tempResult
END
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckAllOrderBillIsStop]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckAllOrderBillIsStop]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE      PROCEDURE Web_CheckAllOrderBillIsStop 
(
	@orderids		VARCHAR(MAX),		--明细id的List
	@BillType		INT=-1		--当前单据类型
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #temp_orderids
(
	rowid INT IDENTITY(1,1),
	orderid VARCHAR(50) NOT NULL
)

CREATE TABLE #temp
(
	orderid INT NOT NULL,
	flag INT DEFAULT(0)		--标志单据、明细是否中止
)
INSERT INTO #temp_orderids SELECT * FROM f_split(@orderids,',')

DECLARE @billover INT --存储是否中止标志
DECLARE @orderid INT
DECLARE @rowcount INT
DECLARE @rowid INT
SELECT TOP 1 @rowcount=MAX(rowid) FROM #temp_orderids
SET @rowid=1

WHILE ( @rowid <= @rowcount )
BEGIN
	SELECT @orderid=CONVERT(INT,orderid) FROM #temp_orderids WHERE rowid=@rowid

	--判断单据是否中止，防止老单据中明细无标志无法判断
	IF @BillType=12
	BEGIN
		SELECT @billover = a.BillOver FROM dbo.OrderIndex a INNER JOIN dbo.PT_Combin_OrderBill b ON a.billNumberId = b.billNumberID WHERE OrderID = @orderid 
	END
	ELSE
	BEGIN
		SELECT @billover = a.BillOver FROM dbo.OrderIndex a INNER JOIN dbo.OrderBill b ON a.billNumberId = b.billNumberID WHERE OrderID = @orderid 
	END

	IF @billover = 1--已中止单据
	BEGIN
		INSERT INTO #temp VALUES(@orderid,2)
		
		SET @rowid=@rowid+1;
		IF (@rowid > @rowcount)
		BEGIN
			BREAK;
		END
		ELSE
		BEGIN
			CONTINUE;
		END
	END

	IF @BillType=12
	BEGIN
		SELECT @billover=BillOver FROM dbo.PT_Combin_OrderBill WHERE OrderID = @orderid
	END
	
	ELSE
	BEGIN
		--判断明细是否中止
		SELECT @billover=BillOver FROM dbo.OrderBill WHERE OrderID = @orderid
	END

	IF @billover = 1 --已中止明细
	BEGIN
		INSERT INTO #temp VALUES(@orderid,1)
	END
	ELSE
	BEGIN
		INSERT INTO #temp VALUES(@orderid,0)
	END
	
	SET @rowid=@rowid+1;
	IF (@rowid > @rowcount)
	BEGIN
		BREAK;
	END
END

SELECT * FROM #temp

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[#temp]'))
DROP TABLE [dbo].[#temp]
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[#temp_orderids]'))
DROP TABLE [dbo].[#temp_orderids]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckAssignInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckAssignInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2013-09-24
	描述：判断辅助信息
*/
CREATE  PROCEDURE Web_CheckAssignInfo
(
	@dUserCount			INT,			--客户使用的用户数	
	@intReVersion		INT OUTPUT,		--版本信息	
	@intReValue			INT OUTPUT		--返回值	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

SET @intReValue = 0

--数据表 LoginUser 中操作员数
DECLARE @intLoginUserCount INT

SELECT	@intLoginUserCount = COUNT(*)
FROM	LoginUser
WHERE	IsErp = 1

DECLARE @N INT, @intDogUserCount INT, @intVersion INT

--判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号
IF @N IS NULL SET @intReVersion = -2

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

-- 判断软件狗用户数
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 3	-- 检查用户数
IF @N IS NULL SET @intReValue = -2

IF @intVersion IN ( 2, 3, 5, 9, 7, 11, 13, 15 )	-- 试用版
	BEGIN
		SET @intDogUserCount = 5		
		IF @intLoginUserCount + @dUserCount -1 > @intDogUserCount SET @intReValue = -51
	END
ELSE
	BEGIN
		SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
		IF ( 3 & @N <> 3 ) SET @intReValue = -2
		IF @intLoginUserCount - 1 >= @intDogUserCount SET @intReValue = -50
		IF @intLoginUserCount + @dUserCount - 1 > @intDogUserCount SET @intReValue = -50
	END

SET @intReVersion = @intVersion


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckAuditingUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckAuditingUser]
GO



/*
	作者：谢吉康
	日期：2008-07-23
	描述：审核设置的人员判断
*/
CREATE PROCEDURE Web_CheckAuditingUser
(
	@AuditingID		int
)
--@encode$--
AS
SET NOCOUNT ON

RETURN 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckBalanceTeWithAc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckBalanceTeWithAc]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.05.21
	描述：出纳系统与总账系统平衡检查
*/
CREATE PROCEDURE Web_CheckBalanceTeWithAc
(
	@Type			INT,			--0.科目 1.账户明细
	@Pass			INT OUTPUT,		--检测通过标识
	@StypeId		VARCHAR(50),	--分支机构
	@chvOperatorID	VARCHAR(50)		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN	--会计科目多级权限
		CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),ATypeName VARCHAR(500),IsCash INT,IsBank INT)
		INSERT INTO #Ac_Account_L (Typeid,StypeId,ATypeName,IsCash,IsBank) 
		SELECT	L.Typeid,
				L.Stypeid,
				A.UserCode + A.FullName AS ATypeName,
				A.IsCash,
				A.IsBank
		FROM F_LineAccount(@chvOperatorID,@StypeId) L
		INNER JOIN Ac_Account A ON L.Typeid=A.TypeId AND L.Stypeid=A.StypeId
END;
DECLARE 
	@MAXFperiod	INT,
	@ExBit	INT=0
IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeId AND EXISTS(SELECT * FROM Te_StartPeriod T WHERE T.STypeId=@StypeId AND T.SFYear=FYear AND T.SFPeriod>FPeriod ))
	BEGIN
		SET @ExBit=1
		SELECT @MAXFperiod=FPeriod FROM Ac_AccountsPeroid_Stype WHERE STypeId=@StypeId
	END
SET @Pass = 0

--检查结果表
CREATE TABLE #Tmp
(
	AccountFullName		VARCHAR(200),
	AccountNumber		VARCHAR(200),
	ATypeName			VARCHAR(200),
	TeTotal				 NUMERIC(24, 10) ,
	AcTotal				 NUMERIC(24, 10) ,
	DValue				 NUMERIC(24, 10) 
)

--按需求调整后，只按账户明细方式出数据
--现金
INSERT INTO #Tmp
        ( AccountFullName ,
          AccountNumber ,
          ATypeName ,
          TeTotal ,
          AcTotal ,
          DValue
        )


SELECT 
	AccountFullName,
	AccountNumber,
	ATypeName,
	SUM(TeTotal) AS TeTotal,
	SUM(AcTotal) AS AcTotal,
	SUM(DValue) AS DValue
FROM
(
	SELECT DISTINCT *
	FROM
	(
		--现金已开账部分        
		SELECT  
			'' AS AccountFullName,
			'' AS AccountNumber,
			ISNULL(T4.ATypeName,'****') AS ATypeName,
			--dbo.f_roundtotal(ISNULL(CASE WHEN T5.BasisType = 0 THEN T2.InitBalance * T1.Rate
			--			ELSE T2.InitBalance / T1.Rate
			--		END,0)) AS TeTotal,
			dbo.f_roundtotal(T2.InitBalanceOri) AS TeTotal,
			0 AcTotal,
			--dbo.f_roundtotal(ISNULL(CASE WHEN T5.BasisType = 0 THEN T2.InitBalance * T1.Rate
			--			ELSE T2.InitBalance / T1.Rate
			--		END,0) - 0) AS DValue,
			dbo.f_roundtotal(T2.InitBalanceOri - 0) AS DValue
		FROM dbo.Te_InitDataIndex T1
		INNER JOIN dbo.Te_InitDataDetail T2 ON T1.id = T2.IndexId
		INNER JOIN dbo.Te_StartPeriod T6 ON T1.STypeId = T6.STypeId 
		INNER JOIN dbo.Ac_AccountsPeroid_Stype T7 ON T1.STypeId = T7.Stypeid
		LEFT JOIN dbo.Ac_Balance T3 ON T3.ATypeId=T2.ATypeId AND T3.STypeId=T1.STypeId AND T3.Cid = 0 AND T3.FYear = T6.SFYear AND T3.FPeriod = T6.SFPeriod
		LEFT JOIN #Ac_Account_L T4 ON T2.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		LEFT JOIN dbo.Ac_Currency T5 ON T1.Cid = T5.CId
		WHERE  
			T1.STypeId = @StypeId 
			AND T1.BUId = 1
			AND t7.IsUse = 1
		UNION ALL
		--现金未开账部分

		SELECT  
			'' AS AccountFullName,
			'' AS AccountNumber,
			ISNULL(T4.ATypeName,'****') AS ATypeName,
			--dbo.f_roundtotal(ISNULL(CASE WHEN T5.BasisType = 0 THEN T2.InitBalance * T1.Rate
			--			ELSE T2.InitBalance / T1.Rate
			--		END,0)) AS TeTotal,
			dbo.f_roundtotal(T2.InitBalanceOri) AS TeTotal,
			0 AcTotal,
			--dbo.f_roundtotal(ISNULL(CASE WHEN T5.BasisType = 0 THEN T2.InitBalance * T1.Rate
			--			ELSE T2.InitBalance / T1.Rate
			--		END,0) - 0) AS DValue,
			dbo.f_roundtotal(T2.InitBalanceOri - 0) AS DValue
		FROM dbo.Te_InitDataIndex T1
		INNER JOIN dbo.Te_InitDataDetail T2 ON T1.id = T2.IndexId
		LEFT JOIN dbo.Te_StartPeriod T6 ON T1.STypeId = T6.STypeId 
		INNER JOIN dbo.Ac_AccountsPeroid_Stype T7 ON T1.STypeId = T7.Stypeid
		LEFT JOIN (SELECT SUM(iniTotal) AS iniTotal,STypeId,ATypeId,Cid
					FROM dbo.Ac_IniAccount
					GROUP BY STypeId,ATypeId,Cid
				) T3 ON T2.ATypeId = T3.ATypeId AND T1.STypeId = T3.STypeId AND T1.Cid = T3.Cid
		LEFT JOIN #Ac_Account_L T4 ON T2.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		LEFT JOIN dbo.Ac_Currency T5 ON T1.Cid = T5.CId
		WHERE 
			T1.BUId = 1 
			AND  t7.IsUse = 0 
			AND T1.STypeId = @StypeId


		UNION ALL
		
		
		--银行账户已开账部分
		SELECT  
			T5.FullName AS AccountFullName,
			T5.AccountNumber,
			ISNULL(T4.ATypeName,'****') AS ATypeName,
			--dbo.f_roundtotal(ISNULL(CASE WHEN T6.BasisType = 0 THEN T2.InitBalance * T1.Rate
			--			ELSE T2.InitBalance / T1.Rate
			--		END,0)) AS TeTotal,
			dbo.f_roundtotal(T2.InitBalanceOri) AS TeTotal,
			0 AcTotal,
			--dbo.f_roundtotal(ISNULL(CASE WHEN T6.BasisType = 0 THEN T2.InitBalance * T1.Rate
			--			ELSE T2.InitBalance / T1.Rate
			--		END,0) - 0
			--) AS DValue,
			dbo.f_roundtotal(T2.InitBalanceOri - 0) AS DValue
		FROM dbo.Te_InitDataIndex T1
		INNER JOIN dbo.Te_InitDataDetail T2 ON T1.Id = T2.IndexId
		LEFT JOIN dbo.Te_BankAccount T5 ON T2.AccountId = T5.Id
		LEFT JOIN dbo.Te_StartPeriod T7 ON T1.STypeId = T7.STypeId 
		LEFT JOIN dbo.Ac_Balance T3 ON T3.ATypeId = T5.ATypeId AND T3.Cid = 0 AND T3.FYear = T7.SFYear AND T3.FPeriod = T7.SFPeriod AND T1.STypeId = T3.STypeId
		LEFT JOIN #Ac_Account_L T4 ON T2.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		LEFT JOIN dbo.Ac_Currency T6 ON T1.Cid = T6.CId
		INNER JOIN dbo.Ac_AccountsPeroid_Stype T8 ON T1.STypeId = T8.Stypeid
		WHERE 
			BUId =2 
			AND T1.STypeId = @StypeId
			AND t8.IsUse = 1

		UNION ALL
		--未开账部分

		SELECT  
			T5.FullName AS AccountFullName,
			T5.AccountNumber,
			ISNULL(T4.ATypeName,'****') AS ATypeName,
			--dbo.f_roundtotal(ISNULL(CASE WHEN T6.BasisType = 0 THEN T2.InitBalance * T1.Rate
			--			ELSE T2.InitBalance / T1.Rate
			--		END,0)) AS TeTotal,
			dbo.f_roundtotal(T2.InitBalanceOri) AS TeTotal,
			0 AcTotal,
			--dbo.f_roundtotal(ISNULL(CASE WHEN T6.BasisType = 0 THEN T2.InitBalance * T1.Rate
			--			ELSE T2.InitBalance / T1.Rate
			--		END,0) - 0
			--) AS DValue,
			dbo.f_roundtotal(T2.InitBalanceOri - 0) AS DValue
		FROM dbo.Te_InitDataIndex T1
		INNER JOIN dbo.Te_InitDataDetail T2 ON T1.Id = T2.IndexId
		LEFT JOIN dbo.Te_BankAccount T5 ON T2.AccountId = T5.Id
		LEFT JOIN dbo.Te_StartPeriod T7 ON T1.STypeId = T7.STypeId 
		LEFT JOIN (SELECT SUM(iniTotal) AS iniTotal,STypeId,ATypeId,Cid
					FROM dbo.Ac_IniAccount
					GROUP BY STypeId,ATypeId,Cid
				) T3 ON T3.ATypeId = T5.ATypeId AND T1.STypeId = T3.STypeId AND T1.Cid = T3.Cid
		LEFT JOIN #Ac_Account_L T4 ON T2.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		LEFT JOIN dbo.Ac_Currency T6 ON T1.Cid = T6.CId
		INNER JOIN dbo.Ac_AccountsPeroid_Stype T8 ON T1.STypeId = T8.Stypeid
		WHERE 
			BUId =2 
			AND  t8.IsUse = 0
			AND T1.STypeId = @StypeId

		UNION ALL
		---------------以总账为标准对--
		--现金已开账部分        
		SELECT  
			'' AS AccountFullName,
			'' AS AccountNumber,
			ISNULL(T4.ATypeName,'****') AS ATypeName,
			0 TeTotal,
			ISNULL(CASE WHEN @ExBit=1 THEN T1.FEndBalance ELSE T1.FBeginBalance END,0) AS AcTotal,
			(0 - ISNULL(CASE WHEN @ExBit=1 THEN T1.FEndBalance ELSE T1.FBeginBalance END,0)) AS DValue
		FROM dbo.Ac_Balance T1
		LEFT JOIN dbo.Te_InitDataIndex T2 ON T1.STypeId = T2.STypeId AND T2.BUId = 1
		LEFT JOIN dbo.Te_InitDataDetail T3 ON T2.id = T3.IndexId AND T1.ATypeId = T3.AtypeId
		INNER JOIN #Ac_Account_L T4 ON T1.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		LEFT JOIN dbo.Ac_Currency T5 ON T2.Cid= T5.CId
		INNER JOIN dbo.Ac_AccountsPeroid_Stype T6 ON T1.STypeId = T6.Stypeid
		INNER JOIN Te_StartPeriod T7 ON T7.SFYear = T1.FYear AND ((@ExBit=1 AND T1.FPeriod=@MAXFperiod) OR (@ExBit=0 AND T7.SFPeriod = T1.FPeriod ))
		WHERE T1.STypeId = @StypeId AND T1.Cid = 0 AND T4.IsCash = 1

		UNION ALL
		--未开账部分

		SELECT  
			'' AS AccountFullName,
			'' AS AccountNumber,
			ISNULL(T4.ATypeName,'****') AS ATypeName,
			0 TeTotal,
			ISNULL(T1.iniTotal,0) AS AcTotal,
			(0 - ISNULL(T1.iniTotal,0)) AS DValue
		FROM (
			SELECT 
				SUM(iniTotal) AS iniTotal,
				STypeId,
				ATypeId,
				Cid
			FROM dbo.Ac_IniAccount
			GROUP BY STypeId,ATypeId,Cid) T1
		LEFT JOIN dbo.Te_InitDataIndex T2 ON T1.STypeId = T2.STypeId AND BUId = 1 AND T1.Cid = T2.Cid
		LEFT JOIN dbo.Te_InitDataDetail T3 ON T2.id = T3.IndexId AND T1.ATypeId = T3.AtypeId
		INNER JOIN #Ac_Account_L T4 ON T1.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		INNER JOIN dbo.Ac_Currency T5 ON T1.Cid= T5.CId
		WHERE 
			EXISTS(SELECT Stypeid FROM dbo.Ac_AccountsPeroid_Stype WHERE stypeid=T1.STypeId AND IsUse = 0) 
			AND T1.STypeId = @StypeId 
			AND T4.IsCash = 1

		UNION ALL
		--银行账户已开账部分        
		SELECT  
			T7.FullName AS AccountFullName,
			T7.AccountNumber AS AccountNumber,
			ISNULL(T4.ATypeName,'****') AS ATypeName,
			0 TeTotal,
			ISNULL(CASE WHEN @ExBit=1 THEN T1.FEndBalance ELSE T1.FBeginBalance END,0) AS AcTotal,
			(0 - ISNULL(CASE WHEN @ExBit=1 THEN T1.FEndBalance ELSE T1.FBeginBalance END,0)) AS DValue
		FROM dbo.Ac_Balance T1
		LEFT JOIN (	SELECT	
						STypeId,
						AtypeId,
						Cid,
						InitBalance,
						Rate
						FROM dbo.Te_InitDataIndex I 
						INNER JOIN Te_InitDataDetail D ON I.Id=D.IndexId 
						WHERE BUId = 2 ) T2 ON T1.STypeId = T2.STypeId AND T1.ATypeId = T2.AtypeId
		INNER JOIN #Ac_Account_L T4 ON T1.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		LEFT JOIN dbo.Ac_Currency T5 ON T2.Cid= T5.CId
		INNER JOIN dbo.Ac_AccountsPeroid_Stype T6 ON T1.STypeId = T6.Stypeid
		INNER JOIN dbo.Te_BankAccount T7 ON T1.STypeId = T7.STypeId AND T1.ATypeId = T7.ATypeId AND T7.IsDestroy = 0
		INNER JOIN Te_StartPeriod T9 ON T9.SFYear = T1.FYear AND ((@ExBit=1 AND T1.FPeriod=@MAXFperiod) OR (@ExBit=0 AND T9.SFPeriod = T1.FPeriod ))
		WHERE 
			T1.STypeId = @StypeId 
			AND T1.Cid = 0 
			AND T4.IsBank = 1

		UNION ALL
		--未开账部分
		SELECT  
			T7.FullName AS AccountFullName,
			T7.AccountNumber AS AccountNumber,
			ISNULL(T4.ATypeName,'****') AS ATypeName,
			0 TeTotal,
			ISNULL(T1.iniTotal,0) AS AcTotal,
			(0 - ISNULL(T1.iniTotal,0)) AS DValue
		FROM (
				SELECT 
					SUM(iniTotal) AS iniTotal,
					STypeId,
					ATypeId,
					Cid
				FROM dbo.Ac_IniAccount
				GROUP BY STypeId,ATypeId,Cid) T1
		LEFT JOIN dbo.Te_InitDataIndex T2 ON T1.STypeId = T2.STypeId AND BUId = 2 AND T1.Cid = T2.Cid
		LEFT JOIN dbo.Te_InitDataDetail T3 ON T2.id = T3.IndexId AND T1.ATypeId = T3.AtypeId
		INNER JOIN #Ac_Account_L T4 ON T1.ATypeId = T4.TypeId AND T1.STypeId = T4.StypeId
		INNER JOIN dbo.Ac_Currency T5 ON T1.Cid= T5.CId
		INNER JOIN dbo.Te_BankAccount T7 ON T1.STypeId = T7.STypeId AND T1.ATypeId = T7.ATypeId AND T7.IsDestroy = 0
		WHERE 
			EXISTS(SELECT Stypeid FROM dbo.Ac_AccountsPeroid_Stype WHERE stypeid=T1.STypeId AND IsUse = 0) 
			AND T1.STypeId = @StypeId 
			AND T4.IsBank = 1
	)TT
)T
GROUP BY AccountFullName,AccountNumber,ATypeName


--存在不平，获取结果
IF EXISTS(SELECT TOP 1 1 FROM #Tmp WHERE ISNULL(DValue,0) <> 0)
	OR EXISTS(SELECT TOP 1 1 FROM #Tmp WHERE ISNULL(ATypeName,'') = '')
BEGIN
	SET @Pass = -1
	
	SELECT *
	FROM #Tmp
END
ELSE
	SELECT NULL



DROP TABLE #Tmp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckBillIsBeCalled]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckBillIsBeCalled]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- ========================================================================
CREATE  PROCEDURE Web_CheckBillIsBeCalled
(
	@chvBillNumberID	varchar(100),	-- 单据编号
	@chrBillType		VARCHAR(10)		-- 草稿单据查询样式
)
--@encode$--

AS
SET NOCOUNT ON 

DECLARE @chvTableName varchar(100)
SET @chvTableName = ''
SELECT @chvTableName = detailTable  FROM BillName WHERE BillType = @chrBillType

DECLARE @sql VARCHAR(max)
SET @sql='

SELECT 
CASE WHEN (SELECT COUNT(1) FROM onShelvespickIndex osi LEFT JOIN onShelvesbill osb on osi.BillNumberId=osb.BillNumberId and osi.RedWord=0 WHERE osb.GoodsBillNumberID=a.BillNumberId AND osb.GoodsBillID = a.id AND osb.Ptypeid=a.ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByShelvesBill,--是否已被上架单调用
CASE WHEN (SELECT COUNT(1) FROM onShelvespickIndex osi LEFT JOIN pickbill pic on osi.BillNumberId=pic.BillNumberId and osi.RedWord=0 WHERE pic.GoodsBillNumberID=a.BillNumberId AND pic.GoodsBillID = a.id AND pic.Ptypeid=a.ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByPickBill--是否已被拣货单单调用
FROM '+@chvTableName+' a WHERE a.BillNumberId= '+@chvBillNumberID+' AND 
((SELECT COUNT(1) FROM onShelvespickIndex osi LEFT JOIN pickbill pic on osi.BillNumberId=pic.BillNumberId and osi.RedWord=0 WHERE pic.GoodsBillNumberID=a.BillNumberId AND pic.GoodsBillID = a.id AND pic.Ptypeid=a.ptypeid) > 0
OR
((SELECT COUNT(1) FROM onShelvespickIndex osi LEFT JOIN onShelvesbill osb on osi.BillNumberId=osb.BillNumberId and osi.RedWord=0 WHERE osb.GoodsBillNumberID=a.BillNumberId AND osb.GoodsBillID = a.id AND osb.Ptypeid=a.ptypeid) > 0)
)'
PRINT(@sql)
EXEC(@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckBillReconciliation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckBillReconciliation]
GO


/*
	作者：谢吉康
	日期：2020-04-30
	描述：检查单据的对账状态
*/

CREATE PROCEDURE Web_CheckBillReconciliation
(
	@billnumberid		VARCHAR(100),
	@billtype			VARCHAR(10),
	@id					VARCHAR(10)
)
AS
SET NOCOUNT ON

DECLARE @indextable VARCHAR(100),
        @sql		VARCHAR(MAX),
		@detaltable	VARCHAR(100)

SELECT  @indextable = indextable,
		@detaltable = detailTable
FROM    billname 
WHERE   billtype = @billtype

IF @id = 0
BEGIN
	SET @sql = 'SELECT	TOP 1 1 
				FROM	'+@indextable+' 
				WHERE	billnumberid = '+@billnumberid+' 
						AND Reconciliation = ''t'''
END
ELSE
BEGIN
	SET @sql = 'SELECT	TOP 1 1 
				FROM	'+@detaltable+' 
				WHERE	billnumberid = '+@billnumberid+' 
						AND ID = '+@id+'
						AND Reconciliation = ''t'''
END

EXEC(@sql)
                            

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckCargoIsUsed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckCargoIsUsed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2011-7-21
	描述：检测cargoid是否被使用
-------------------------------------------*/
CREATE PROCEDURE Web_CheckCargoIsUsed
(
	@Cargoid	INT,
	@CarGoUsed	INT OUTPUT		--0代表未使用，1代表使用
)
--@encode$--
AS
SET NOCOUNT ON


CREATE TABLE #TempTable
(
	NumID			INT IDENTITY(1,1),
	dataField		VARCHAR(20),		--表字段
	tableNmae		VARCHAR(100)		--表名
)

INSERT #TempTable(dataField, tableNmae)
SELECT	a.name AS name, c.name AS tablename 
FROM	sys.columns a 
JOIN	sys.types b ON a.user_type_id = b.user_type_id join    sys.tables c on c.object_id = a.object_id
WHERE a.name like '%cargoid%' AND c.name Not IN('cargotype','PType_Price','PType_STypePrice','WdOrder') order by a.name


DECLARE @Num	INT
DECLARE @zd		VARCHAR(10)
DECLARE @tb		VARCHAR(100)
DECLARE @SQL	NVARCHAR(500)
SELECT TOP 1  @Num=COUNT(*) FROM #TempTable

DECLARE @CarGoUsed2 INT
SET @CarGoUsed2 = -99999
WHILE @Num >= 1
BEGIN
	SELECT @zd=dataField,@tb=tableNmae FROM #TempTable WHERE NumID = @Num
	SET @Num = @Num - 1
	SET @SQL = 'IF EXISTS (SELECT *  FROM '+@tb+' WHERE '+@zd+' = '+cast(@Cargoid as varchar(10))+') BEGIN SELECT @CarGoUsed1=1 END '
	EXEC sp_executesql @SQL,N'@CarGoUsed1 INT OUTPUT',@CarGoUsed2 OUTPUT 
	IF @CarGoUsed2<>-99999
	BEGIN
		SET @CarGoUsed=1	--使用
		RETURN 
	END
END

SET @CarGoUsed = 0		--未使用

DROP TABLE #TempTable


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckCommissionCal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckCommissionCal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2011-4-24
	描述：提成计算时的验证
-------------------------------------------*/
CREATE PROCEDURE Web_CheckCommissionCal
(
	@StartDate		VARCHAR(50),
	@EndDate		VARCHAR(50),
	@StypeID		VARCHAR(MAX),
	@SchemeID		NUMERIC(18,0),
	@SaleTimeID		VARCHAR(50),
	@OperatorID		VARCHAR(50),
	@CommissionType			INT	--1=规则提成  2= 参照计划提成
)
--@encode$--
AS
SET NOCOUNT ON


--检查成本查看权限
DECLARE	@CommissionRuleID NUMERIC(22,0), --提成方案ID
		@CommissionStandard INT,--提成基准
		@re_re INT
SELECT @CommissionRuleID = CommissionRuleID FROM CommissionScheme WHERE BillNumberId = @SchemeID
SELECT @CommissionStandard = CommissionStandard FROM CommissionRule WHERE BillNumberId = @CommissionRuleID
IF @OperatorID != '00001' AND @CommissionStandard = 4 -- 销售毛利
BEGIN
	EXEC @re_re=GP_CheckLimit @OperatorID,166   -- 成本查看权限
	IF @re_re <> 0
	BEGIN
		RAISERROR('您没有商品的成本查看权限，对涉及有【销售毛利】规则的提成方案无法计算提成，请重新选择其它方案或请有权限的操作员执行！',16,1)
		RETURN
	END
END

--提成计算--参照计划提成，对时间的处理
IF @CommissionType = 2
BEGIN
	SELECT @StartDate = StartTime,@EndDate = EndTime FROM SaleTime WHERE ID = @SaleTimeID
	IF @StartDate = '' OR @EndDate = ''
	BEGIN
		RAISERROR('信息被更改，需重新选择！',16,1)
		RETURN
	END
END


CREATE TABLE #Stype(stypeid VARCHAR(50))
INSERT #Stype(stypeid)
SELECT TOP 1 a
FROM f_split(@StypeID,',') WHERE a NOT IN (SELECT StypeID FROM CommissionSchemeStype WHERE BillNumberId = @SchemeID)

DECLARE @S VARCHAR(MAX)=''
DECLARE @MSG1 VARCHAR(MAX)=''

IF EXISTS(SELECT TOP 1 1 FROM #Stype)
BEGIN
	SELECT @S+= a.fullname FROM SType a,#Stype b WHERE a.TypeId = b.stypeid
	SET @MSG1 = '所选择的分支机构【'+@S+'】不属于提成方案的分支机构！'
	RAISERROR(@MSG1,16,1)
	RETURN
END

--清空分支机构
DELETE #Stype

INSERT #Stype(stypeid)
SELECT TOP 1 F.a FROM CommissionBillNew C
INNER JOIN CommissionBillNew S ON S.BillNumberId = C.BillNumberId
INNER JOIN f_split(@StypeID,',') F ON F.a = S.StypeID
WHERE	C.IsAuto = 1
		AND s.CommissionSchemeID = @SchemeID
		AND S.CommissionType = @CommissionType
		AND (	C.CommissionStart <= @StartDate AND C.CommissionEnd >= @StartDate
				OR C.CommissionStart <= @EndDate AND C.CommissionEnd >= @EndDate
			)

IF EXISTS(SELECT TOP 1 1 FROM #Stype)
BEGIN
	--SELECT @S+= a.fullname FROM SType a,#Stype b WHERE a.TypeId = b.stypeid
	--SET @MSG1 = '在当前时间段内，所选择的分支机构【'+@S+'】已有提成单！'
	SET @MSG1 = '本次提成时间段内的业绩已经计算完成，或本次提成时间与之前提成时间存在提成数据的交叉，请重新设置提成时间或删除已计算完成的提成单，再操作！'
	RAISERROR(@MSG1,16,1)
	RETURN
END	

		
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckContainSerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckContainSerial]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：鲁大林
	日期：2013-06-27
	描述：复制主表和明细表中新加的字段
	
*/
CREATE PROCEDURE Web_CheckContainSerial
(
	@BILLNUMBERIDS			VARCHAR(MAX)
 )
--@encode$--
AS
SET NOCOUNT ON

	CREATE TABLE #BILLNUMBERIDS(ID VARCHAR(MAX))
	CREATE TABLE #RESULT(IDS VARCHAR(MAX))
	DECLARE @RESULT	INT
	INSERT INTO #BILLNUMBERIDS SELECT * FROM f_split(@BILLNUMBERIDS,',')
	
	--检索所有存在该单据编号并且存在序列号的单据编号
	INSERT INTO #RESULT
	SELECT BillNumberId FROM RetailBackBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM OtherInOutBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM STypeMoveBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM IntegralExchangeBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_Move A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_Out A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_In A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_Goto A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_Call A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_SendBack A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_Send A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_Replace A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_GetBack A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_Self A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM wx_Bill_JieJian A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM BuyGoodsExchangeBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM SaleGoodsExchangeBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM RepairDealDetail A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM GoodsExchangeBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM PriceProtectBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM Advantage A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM CommissionBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM GiveBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM GivemeBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM DisassembleBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM Overflowbill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM Losebill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM Movebill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM Movebjbill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM Buybill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM BuyBackBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM Salebackbill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM SaleBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM retailBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM adpricebill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM SendBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM AppraisalBill A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM PT_Combin_SaleBillDetail A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM PT_Combin_SaleBackBillDetail A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''

	IF EXISTS(SELECT 1 FROM #RESULT)
		SET @RESULT=0
	ELSE
		SET @RESULT=1
	DROP TABLE #BILLNUMBERIDS
	RETURN @RESULT
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckFactContainSerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckFactContainSerial]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：鲁大林
	日期：2013-06-27
	描述：复制主表和明细表中新加的字段
	
*/
CREATE PROCEDURE Web_CheckFactContainSerial
(
	@BILLNUMBERIDS			VARCHAR(MAX)
 )
--@encode$--
AS
SET NOCOUNT ON

	CREATE TABLE #BILLNUMBERIDS(ID VARCHAR(MAX))
	CREATE TABLE #RESULT(IDS VARCHAR(MAX))
	DECLARE @RESULT	INT
	INSERT INTO #BILLNUMBERIDS SELECT * FROM f_split(@BILLNUMBERIDS,',')
	
	--检索所有存在该单据编号并且存在序列号的单据编号
	INSERT INTO #RESULT
	SELECT BillNumberId FROM FactDepotInOut A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''
	UNION 
	SELECT BillNumberId FROM FactDepotAllot A INNER JOIN #BILLNUMBERIDS B ON A.BillNumberId=B.ID WHERE CAST(A.Serial AS VARCHAR)<>''

	
	IF EXISTS(SELECT 1 FROM #RESULT)
		SET @RESULT=0
	ELSE
		SET @RESULT=1
	DROP TABLE #BILLNUMBERIDS
	RETURN @RESULT
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckLimitAddCopyCategory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckLimitAddCopyCategory]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王刚
	日期：2014-11-11
	描述：检测是否可以新增，复制，分类
*/
CREATE PROCEDURE Web_CheckLimitAddCopyCategory
(
	@OperatorID			VARCHAR(100),	--操作员ID
	@Parid				VARCHAR(100),
	@BaseType			VARCHAR(100),
	@Type				INT		--1=基本信息  0=项目
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--商品 P
--职员 E
--客户 B
--供货商 B
--部门 D
--仓库 K
--分支机构 S
--地区 AreaType

--资金类 B    ok
--其他收入 G  0000300003    2  6  ok
--费用类型 E  ok  0000400003 下的东西
--固定资产 F  ok
--资产项 C OK
--负载项目 L   ok
--所有者权益 A OK

--管辖帐户   type  0
--管辖费用		 1  7
--其他收入    2    0000300003
--固定资产 3
--其他资产4
--负债5

--收入6    
--支出 7
--所有者权益8


IF @OperatorID  = '00001'
	RETURN

SET @BaseType = UPPER(@BaseType)

IF @BaseType = 'AREATYPE' AND @Type = 1 --地区不控制权限
	RETURN
IF @BaseType = 'Ac_CashMoneyItems' AND @Type = 1 --现金流量项目不控制权限
	RETURN

IF @BaseType = 'AssetCard' or @BaseType='' --卡片
	RETURN

CREATE TABLE #Temp(typeid VARCHAR(50))

IF @BaseType = 'P' AND @Type = 1
BEGIN
	IF @MPtypeid = '00000'
		INSERT #Temp VALUES(@MPtypeid)
	ELSE
		INSERT #Temp
		SELECT TOP 1 typeid FROM ptype_l WHERE etypeid = @OperatorID AND flag=1 AND @Parid LIKE typeid + '%'
END
ELSE IF @BaseType = 'E' AND @Type = 1
BEGIN
	IF @MEtypeid = '00001'
		INSERT #Temp VALUES(@MEtypeid)
	ELSE
		INSERT #Temp
		SELECT TOP 1 typeid FROM etype_l WHERE etypeid = @OperatorID AND flag=1 AND @Parid LIKE typeid + '%'
END
ELSE IF @BaseType = 'B' AND @Type = 1
BEGIN
	IF @MBtypeid='00001' AND @MBtypeid2='00002'
		INSERT #Temp VALUES('00000')
	ELSE
		INSERT #Temp
		SELECT TOP 1 typeid FROM btype_l WHERE etypeid = @OperatorID AND flag=1 AND @Parid LIKE typeid + '%'
END
ELSE IF @BaseType = 'D' AND @Type = 1
BEGIN
	IF @MDtypeid = '00000'
		INSERT #Temp VALUES(@MDtypeid)
	ELSE
		INSERT #Temp
		SELECT TOP 1 typeid FROM dtype_l WHERE etypeid = @OperatorID AND flag=1 AND @Parid LIKE typeid + '%'
END
ELSE IF @BaseType = 'K' AND @Type = 1
BEGIN
	IF @MKtypeid = '00000'
		INSERT #Temp VALUES(@MKtypeid)
	ELSE
		INSERT #Temp
		SELECT TOP 1 typeid FROM ktype_l WHERE etypeid = @OperatorID AND flag=1 AND @Parid LIKE typeid + '%'
END
ELSE IF @BaseType = 'S' AND @Type = 1
BEGIN
	IF @MStypeid = '00000'
		INSERT #Temp VALUES(@MStypeid)
	ELSE
		INSERT #Temp
		SELECT TOP 1 typeid FROM stype_l WHERE etypeid = @OperatorID AND flag=1 AND @Parid LIKE typeid + '%'
END
--基本信息结束




--项目信息开始
ELSE IF @Type = 0 --资金类
BEGIN
	DECLARE @I INT
	IF @BaseType = 'B'
		SET @I = 0
	ELSE IF @BaseType = 'E'
		BEGIN
			IF LEFT(@Parid,10) = '0000400003'
				SET @I = 7
			ELSE
				SET @I = 1
		END
	ELSE IF @BaseType = 'G'
		BEGIN
			IF LEFT(@Parid,10) = '0000300003'
				SET @I = 2
			ELSE
				SET @I = 6
		END
	ELSE IF @BaseType = 'F'
		SET @I = 3
	ELSE IF @BaseType = 'C'
		SET @I = 4
	ELSE IF @BaseType = 'L'
		SET @I = 5
	ELSE IF @BaseType = 'A'
		SET @I = 8
		
		--IF @I = 7
		--	INSERT #Temp
		--	SELECT TOP 1 typeid FROM atype_l 
		--	WHERE	etypeid = @OperatorID AND flag=1  AND type=@I AND @Parid LIKE typeid + '%'
		--			AND LEFT(typeid,10)='0000400003'
		--ELSE IF @I = 2
		--	INSERT #Temp
		--	SELECT TOP 1 typeid FROM atype_l 
		--	WHERE	etypeid = @OperatorID AND flag=1  AND type=@I AND @Parid LIKE typeid + '%'
		--			AND LEFT(typeid,10)='0000300003'
		--ELSE IF @I = 5
		--	INSERT #Temp
		--	SELECT TOP 1 typeid FROM atype_l 
		--	WHERE	etypeid = @OperatorID AND flag=1  AND type=@I AND @Parid LIKE typeid + '%'
		--			AND LEFT(typeid,5)='00002'
		--ELSE
			INSERT #Temp
			SELECT TOP 1 typeid FROM atype_l WHERE etypeid = @OperatorID AND flag=1  AND type=@I AND @Parid LIKE typeid + '%'
			UNION ALL
			SELECT TOP 1 '1' FROM atype_l WHERE etypeid = @OperatorID AND flag=1  AND type=@I AND [type]='0000'
END

IF NOT EXISTS(SELECT TOP 1 1 FROM #Temp)
BEGIN
	RAISERROR('您没有当前操作的多级权限范围，请确定后重试！',16,1)
	RETURN
END


DROP TABLE #Temp


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckMenuEventInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_CheckMenuEventInfo
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2019-11-15
	描述：处理菜单配置信息
*/

CREATE PROCEDURE Web_CheckMenuEventInfo
--@encode$--
AS
SET NOCOUNT ON

--判断日期是否一致
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'uploadmenueventlogdate' AND SubValue = CONVERT(VARCHAR(10),GETDATE(),120))
BEGIN
	SELECT	0 AS Offset,
			0 AS nCount
			
	RETURN -1		
END
ELSE
BEGIN	
	SELECT	w.Offset,
			e.nCount
	FROM	dbo.WebMenu w
	INNER JOIN 
	(
		SELECT	TOP 50
				B.eventid,
				B.nCount
		FROM	(
					SELECT	eventid,
							COUNT(*) AS nCount
					FROM	dbo.EventLog 
					GROUP BY EventId
		)B	
		ORDER BY nCount DESC
	)e ON e.EventId = w.name
	ORDER BY e.nCount DESC

	--修改日期
	UPDATE dbo.sysdata SET SubValue = CONVERT(VARCHAR(10),GETDATE(),120) WHERE SubName = 'uploadmenueventlogdate'
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckMultiCouponCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckMultiCouponCode]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	功能说明：	检查couponcode
	作    者：	shushan
	修改时间：	
*/
CREATE             PROCEDURE Web_CheckMultiCouponCode
(
	@codetails		TBType_CouponCodes READONLY,
	@billtype		INT,
	@BillNumberID	numeric(18,0),
	@isini			INT ,
	@KTYPEID_IN	 VARCHAR(50),
	@KTYPEID_OUT	 VARCHAR(50)
)
--@encode$--
AS
	SET NOCOUNT ON
CREATE TABLE #ExistedCodes(
	COUPONCODE VARCHAR(200),
	CouponID VARCHAR(50)
)
CREATE TABLE #CurCodes(
	COUPONCODE VARCHAR(200),
	CouponID VARCHAR(50)
	
)

DECLARE @SQL VARCHAR(MAX)='',
		@TABLENAME VARCHAR(50)

IF @billtype =423
	SET @TABLENAME='coupon_InBill'
ELSE IF @billtype=424
	SET @TABLENAME='coupon_OutBill'
ELSE IF @billtype=425
	SET @TABLENAME='coupon_AllotBill'
ELSE IF @billtype=426
	SET @TABLENAME='coupon_BackBill'
ELSE IF @billtype IN(427,428,429)
	SET @TABLENAME='Coupon_AllotBillStype'

SELECT @SQL='
INSERT INTO #ExistedCodes(COUPONCODE,CouponID)
SELECT  B.StrColumn AS couponcode,CouponID
FROM    (SELECT StrXml = CONVERT(XML, ''<root><v>''+REPLACE( Couponcode, ''я'', ''</v><v>'')+''</v></root>'')  ,CouponID  FROM   
		   '+@TABLENAME+' WHERE BillNumberID='+cast (@BillNumberID  AS VARCHAR(50)) +'  ) A OUTER APPLY (SELECT StrColumn = N.v.value(''.'', ''nvarchar(200)'')  FROM   A.StrXml.nodes(''/root/v'') N (v)   ) B 
UNION ALL
SELECT  DISTINCT	couponcode,CouponID FROM Coupon_CodeInfo	   
	'
EXEC(@SQL)


INSERT INTO #CurCodes(COUPONCODE,CouponID)
SELECT  B.StrColumn AS couponcode,CouponID
FROM    (SELECT StrXml = CONVERT(XML, '<root><v>'+REPLACE( Couponcode, 'я', '</v><v>')+'</v></root>'),CouponID FROM   
		   @codetails  ) A OUTER APPLY (SELECT StrColumn = N.v.value('.', 'nvarchar(200)')  FROM   A.StrXml.nodes('/root/v') N (v)   ) B 

--优惠券入库单
IF @billtype  IN(423) --入库 
BEGIN
	IF EXISTS (
		SELECT C.CouponCode
		FROM  dbo.Coupon_CodeInfo C
		LEFT JOIN #ExistedCodes E ON  C.COUPONCODE=E.COUPONCODE
		INNER JOIN #CurCodes Cur ON CUR.COUPONCODE=C.CouponCode
		WHERE E.COUPONCODE IS NOT NULL 
		)
		RETURN -1;  --单据上有编码已经在库
		
	IF EXISTS (
		SELECT C.CouponId 
		FROM  @codetails C 
		LEFT JOIN  dbo.Coupon_TypeInfo T ON T.CouponId = C.CouponId
		WHERE (T.CouponId IS NULL OR t.IsDelete=1)
	)
	RETURN -6;	--券名称不存在
		
END 

--优惠券出库单
IF @billtype=424
BEGIN
	IF @isini=1
	BEGIN 
		IF EXISTS (
			SELECT C.CouponCode
			FROM  dbo.Coupon_CodeInfo C
			LEFT JOIN #ExistedCodes E ON  C.COUPONCODE=E.COUPONCODE
			INNER JOIN #CurCodes Cur ON CUR.COUPONCODE=C.CouponCode
			WHERE E.COUPONCODE IS NOT  NULL 
		)
		RETURN -1;  --单据上有编码已经在库
	END
	ELSE 
	BEGIN
		IF  EXISTS (
			SELECT C.CouponCode
			FROM  #CurCodes cur
			INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode
			WHERE cur.CouponID<>c.CouponId
		)
		RETURN -7; --券名称与券编码不匹配
		
		IF NOT EXISTS (
			SELECT C.CouponCode
			FROM  #CurCodes cur
			INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode AND c.CouponId=cur.CouponID
			WHERE  c.KtypeId=@KTYPEID_OUT
		)
		RETURN -5;  --该仓库下不存在该券编码
		
		IF NOT EXISTS (
			SELECT C.CouponCode
			FROM  #CurCodes cur
			INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode AND c.CouponId = cur.CouponID
			WHERE ISNULL(C.[State],0)=1
		)
		RETURN -2;  --引用了非在库状态的编码
	END  
END 

--优惠券调拨单
IF @billtype=425
BEGIN
	IF  EXISTS (
	SELECT C.CouponCode
	FROM  #CurCodes cur
	INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode
	WHERE cur.CouponID<>c.CouponId
	)
	RETURN -7;
	IF EXISTS (
	SELECT C.CouponCode
	FROM  #CurCodes cur
	INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode AND c.CouponId = cur.CouponID
	WHERE  c.KtypeId<>@KTYPEID_OUT
	)
	RETURN -5;  --该仓库下不存在该券编码
	IF NOT EXISTS (
	SELECT C.CouponCode
	FROM  #CurCodes cur
	INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode AND c.CouponId = cur.CouponID
	WHERE ISNULL(C.[State],0)=1
	)
	RETURN -3;  --引用了非在库状态的编码
END 

--优惠券退货单
IF @billtype=426
BEGIN
	IF  EXISTS (
	SELECT C.CouponCode
	FROM  #CurCodes cur
	INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode
	WHERE cur.CouponID<>c.CouponId
	)
	RETURN -7;
	IF NOT EXISTS (
	SELECT C.CouponCode
	FROM  #CurCodes cur
	INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode AND c.CouponId = cur.CouponID
	WHERE ISNULL(C.[State],0)=2
	)
	RETURN -4;  --引用了非出库状态的编码
END

--优惠券分支机构调拨入库单
IF @billtype=428
BEGIN
	IF  EXISTS(SELECT C.CouponCode
		FROM  dbo.Coupon_CodeInfo C
		LEFT JOIN #ExistedCodes E ON  C.COUPONCODE=E.COUPONCODE
		INNER JOIN #CurCodes Cur ON CUR.COUPONCODE=C.CouponCode
		WHERE E.COUPONCODE IS NOT NULL AND (C.STATE<>7) )
	RETURN -8;
	
	IF NOT EXISTS (
		SELECT C.CouponCode
		FROM  dbo.Coupon_CodeInfo C
		LEFT JOIN #ExistedCodes E ON  C.COUPONCODE=E.COUPONCODE
		INNER JOIN #CurCodes Cur ON CUR.COUPONCODE=C.CouponCode AND  c.CouponId=cur.CouponID
		WHERE c.KtypeId=@KTYPEID_OUT )
	RETURN -5;  --该仓库下不存在该券编码
	
	IF  EXISTS (
		SELECT C.CouponCode
		FROM  #CurCodes cur
		LEFT JOIN #ExistedCodes E ON  cur.COUPONCODE=E.COUPONCODE
		INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode AND c.CouponId = cur.CouponID
		WHERE ISNULL(C.[State],1)<>7
	)
	RETURN -8;  --录入了非【分支机构调拨出库】状态的券编码，不能保存或过账该单据！
END

--优惠券分支机构调拨出库单
IF @billtype=429
BEGIN
	IF  EXISTS (
		SELECT C.CouponCode
		FROM  #CurCodes cur
		LEFT JOIN #ExistedCodes E ON  cur.COUPONCODE=E.COUPONCODE
		INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode AND c.CouponId = cur.CouponID
		WHERE ISNULL(C.[State],1)<>1
	)
	RETURN -2;  --引用了非在库状态的编码	
	
	IF NOT EXISTS (
		SELECT C.CouponCode
		FROM  #CurCodes cur
		INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode AND c.CouponId=cur.CouponID
		WHERE  c.KtypeId=@KTYPEID_OUT
	)
	RETURN -5;  --该仓库下不存在该券编码

	IF  EXISTS(SELECT C.CouponCode
		FROM  dbo.Coupon_CodeInfo C
		LEFT JOIN #ExistedCodes E ON  C.COUPONCODE=E.COUPONCODE
		INNER JOIN #CurCodes Cur ON CUR.COUPONCODE=C.CouponCode
		WHERE E.COUPONCODE IS NOT NULL AND C.STATE<>1
	)		
		RETURN -1;
	
	IF  EXISTS (
		SELECT C.CouponCode
		FROM  #CurCodes cur
		INNER JOIN dbo.Coupon_CodeInfo c ON CUR.COUPONCODE=C.CouponCode
		WHERE cur.CouponID<>c.CouponId
	)
	RETURN -7;
		

END


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckMultiStockAlarm]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckMultiStockAlarm]
GO







/*
	作者：谢吉康
	日期：2004-10-25
	描述：根据操作员检查多级库存
*/
CREATE PROCEDURE Web_CheckMultiStockAlarm
(
	@OperatorID	VARCHAR(50),			--操作员ID
	@ParId		VARCHAR(256)			--仓库ID
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 		varchar(8000),
		@intSonNum 	int

SELECT @intSonNum = SonNum FROM Stock WHERE TypeId = @ParId AND Deleted = 0

IF @intSonNum = 0
	BEGIN
		SELECT  @SQL = '
			SELECT 	* 
			FROM 	Stock 
			WHERE 	TypeId <> ''00000''
					AND Deleted = 0
					AND TypeId = '+char(39)+@ParId+char(39)+'
					AND TypeId LIKE '+char(39)+@MKTypeId +'%'+char(39)+'
			ORDER BY UserCode'
	END
ELSE
	BEGIN
		SELECT  @SQL = '
			SELECT 	* 
			FROM 	Stock 
			WHERE 	TypeId <> ''00000''
					AND Deleted = 0
					AND ParId = '+char(39)+@ParId+char(39)+'
					AND TypeId LIKE '+char(39)+@MKTypeId +'%'+char(39)+'
			ORDER BY UserCode'
	END

EXEC(@SQL)










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_checkOnlineUserOutOfRange]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_checkOnlineUserOutOfRange]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2019-03-08
	描述：判断操作员在线数据
	EXEC Web_checkOnlineUserOutOfRange '0000100001'
*/

CREATE  PROCEDURE [dbo].Web_checkOnlineUserOutOfRange
(
	@etypeid			VARCHAR(50),		--操作员ID
	@username			VARCHAR(500),		--操作员名称
	@ipAddress			VARCHAR(500),		--IP地址
	@pollingtime		INT 				--轮询时间
)
AS
SET NOCOUNT ON

--先清理一次数据
DECLARE @dbName					VARCHAR(100),
		@sysdataDbuserCount		INT,
		@curtime				VARCHAR(30)

SET @dbName = DB_NAME()
SET @curtime = CONVERT(varchar(30),GETDATE(),120)		

--先判断条件，不满足则不进入
IF NOT (EXISTS(SELECT TOP 1 1 FROM sysdatadb.dbo.RWXsysadmin WHERE islimlogin = 1 AND ISNULL(dognumber,'')<>'')
			OR EXISTS(SELECT TOP 1 1 FROM sysdatadb.dbo.VirtualDirectoryWithAccount WHERE islimlogin = 1 AND ISNULL(dognumber,'')<>'')
	   )	
BEGIN
	UPDATE loginuser SET LogNum=ISNULL(LogNum,0) + 1 WHERE etypeid = @etypeID
	RETURN 0
END			
		
EXEC Gp_ClearLoginOnlineUser @etypeid,@username,@ipAddress,@pollingtime,@curtime

--试用版
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata1 WHERE SubName = 'zcflag' AND SubValue = '0')	
BEGIN
	UPDATE loginuser SET LogNum=ISNULL(LogNum,0) + 1 WHERE etypeid = @etypeID
	RETURN 0
END

--软件狗
DECLARE @dogNo	VARCHAR(30)			
SELECT @dogNo = subValue FROM dbo.sysdata1 WHERE SubName = 'DogNo'

--判断标识

IF @etypeid <> '00001'
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM sysdatadb.dbo.RWXsysadmin WHERE dognumber = @dogNo AND islimlogin = 1 AND ISNULL(dognumber,'')<>'')
		OR EXISTS(SELECT TOP 1 1 FROM sysdatadb.dbo.VirtualDirectoryWithAccount WHERE dognumber = @dogNo AND islimlogin = 1 AND ISNULL(dognumber,'')<>'')		
	BEGIN
		DECLARE @N int, @intDogUserCount int, @intVersion int
		-- 判断版本号，是否试用版
		SELECT	@N = CAST(SubValue AS int)
		FROM	SysData1
		WHERE	SubNo = 2	-- 版本号

		IF @N IS NULL RETURN -2

		DECLARE @intBit int, @intMask int
		SELECT @intBit = @N & 15
		SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
		SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

		-- 判断软件狗用户数
		SELECT	@N = CAST(SubValue AS int)
		FROM	SysData1
		WHERE	SubNo = 3	-- 检查用户数

		IF @N IS NULL RETURN -2
		
		SELECT @intDogUserCount = ( ( POWER(2,18) - 1 ) & @N ) / 4
		IF ( 3 & @N <> 3 ) RETURN -2
		
		SELECT @sysdataDbuserCount = COUNT(*) FROM SYSDATADB.DBO.Fx_OnlineUser WHERE DogNo = @dogNo AND ETypeID_UserTypeID <> '00001'
		
		IF @sysdataDbuserCount + 1 > @intDogUserCount
		BEGIN
			RETURN -1
		END
	END
END	

UPDATE loginuser SET LogNum=ISNULL(LogNum,0) + 1 WHERE etypeid = @etypeID

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckOrderBillIsStop]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckOrderBillIsStop]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE      PROCEDURE Web_CheckOrderBillIsStop 
(
	@orderid		INT,		--明细id
	@BillType		INT=-1		--当前单据类型
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @billover INT --存储是否中止标志

--判断单据是否中止，防止老单据中明细无标志无法判断
IF @BillType=12
	SELECT @billover = a.BillOver FROM dbo.OrderIndex a INNER JOIN dbo.PT_Combin_OrderBill b ON a.billNumberId = b.billNumberID WHERE OrderID = @orderid 
ELSE 
	SELECT @billover = a.BillOver FROM dbo.OrderIndex a INNER JOIN dbo.OrderBill b ON a.billNumberId = b.billNumberID WHERE OrderID = @orderid 

IF @billover = 1--已中止单据
RETURN 2

IF @BillType=12
BEGIN
	SELECT @billover=BillOver FROM dbo.PT_Combin_OrderBill WHERE OrderID = @orderid
END
ELSE
BEGIN
	--判断明细是否中止
	SELECT @billover=BillOver FROM dbo.OrderBill WHERE OrderID = @orderid
END

IF @billover = 1 --已中止明细
RETURN 1
ELSE
RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckOrderBillIsUse]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckOrderBillIsUse]
GO

/*
	作者：王刚
	日期：2011-03-21
	描述：检测销售和采购订单是否被调用
*/

CREATE  PROCEDURE Web_CheckOrderBillIsUse 
( 
	@billtype		INT,
	@billnumberid	VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON 


IF @billtype = 300	--检测销售订单是否被调用 + 被采购订单调用
BEGIN
	IF EXISTS(SELECT O.OrderID FROM OrderBill O
			  INNER JOIN SaleBill s ON s.OrderID = O.OrderID
			  INNER JOIN BillIndex B ON B.BillNumberId = S.BillNumberId
			  WHERE O.billNumberID = @billnumberid
					AND B.RedWord = 0)
	OR EXISTS(
			SELECT TOP 1 1
			FROM ORDERBILL 
			WHERE SALEORDERID IN (SELECT ORDERID FROM ORDERBILL WHERE billNumberID = @billnumberid)
	)
	BEGIN
	--此处格式不能调不然对比齐
--		RAISERROR('此销售订单被调用了，不能再次修改和保存，
--请关闭此窗口或在重新调入订单。',16,1) 
				   
		RETURN -1
	END
	
END

DECLARE @UsedOrderId INT

IF @billtype = 300	
BEGIN
	--检测是否被销售出库单调用
	SELECT TOP 1 @UsedOrderId = O.OrderID
	FROM OrderBill O
	INNER JOIN SaleBill s ON s.OrderID = O.OrderID
	INNER JOIN BillIndex B ON B.BillNumberId = S.BillNumberId
	WHERE	O.billNumberID = @billnumberid
		AND B.RedWord = 0
		
	--如果未被销售出库单调用，则继续检查是否被采购订单调用
	IF @UsedOrderId IS NULL
		SELECT TOP 1 @UsedOrderId = OrderID
		FROM ORDERBILL 
		WHERE SALEORDERID IN (SELECT ORDERID FROM ORDERBILL WHERE billNumberID = @billnumberid)
END
ELSE		--检测采购订单是否被调用
BEGIN
	SELECT TOP 1 @UsedOrderId = O.OrderID 
	FROM OrderBill O
	INNER JOIN BuyBill s ON s.OrderID = O.OrderID
	INNER JOIN BillIndex B ON B.BillNumberId = S.BillNumberId
	WHERE O.billNumberID = @billnumberid
		AND B.RedWord = 0
END

--如果没有调用	
IF @UsedOrderId IS NULL
	RETURN 1
ELSE
	RETURN -1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckOrderIsUsed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckOrderIsUsed]
GO


/*
	作者：zy
	日期：2017-08-11   
	描述：检查引用订单的单据是否存在
	
*/
CREATE	PROCEDURE Web_CheckOrderIsUsed
( 
	 @BillType		INT,  --采购、销售、组合品销售
	 @BillNumberid	INT
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

IF @BillType=300
BEGIN
	SELECT COUNT(*) FROM OrderIndex A
	INNER JOIN OrderBill B ON A.billNumberId=B.billNumberID
	INNER JOIN SaleBill C ON B.OrderID=C.OrderID
	INNER JOIN BillIndex D ON C.BillNumberId=D.BillNumberId AND D.RedWord=0
	WHERE A.billNumberId=@BillNumberid	
END
ELSE IF @BillType=313
BEGIN
	SELECT COUNT(*) FROM OrderIndex A
	INNER JOIN PT_Combin_OrderBill B ON A.billNumberId=B.billNumberID
	INNER JOIN PT_Combin_SaleBill C ON B.OrderID=C.OrderID
	INNER JOIN BillIndex D ON C.BillNumberId=D.BillNumberId AND D.RedWord=0
	WHERE A.billNumberId=@BillNumberid	
END
ELSE IF @BillType=301
BEGIN
	SELECT COUNT(*) FROM OrderIndex A
	INNER JOIN OrderBill B ON A.billNumberId=B.billNumberID
	INNER JOIN BuyBill C ON B.OrderID=C.OrderID
	INNER JOIN BillIndex D ON C.BillNumberId=D.BillNumberId AND D.RedWord=0
	WHERE A.billNumberId=@BillNumberid
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckPromotePrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckPromotePrice]
GO



/*
-- 功能说明：		根据商品、往来单位、仓库、经手人确定促销价格
-- 作者：		卢春
-- 最后修改时间：	2003-06-01
*/
CREATE        PROCEDURE Web_CheckPromotePrice
(
	@intPromotePrice	 NUMERIC(24, 10) 	output,	-- 查询出的结果集记录
	@chvPTypeID			varchar(50)	= '',	-- 商品 ID，只允许叶子数据
	@chvBTypeID			varchar(50)	= '',	-- 往来单位 ID
	@chvKTypeID			varchar(50)	= '',	-- 仓库 ID
	@chvETypeID			varchar(50)	= '',	-- 职员 ID
	@chvBillDate		varchar(100)	= '',	-- 单据日期
	@UnitID				INT						--商品单位
)
--@encode$--
AS
	SET NOCOUNT ON 
	--DECLARE @intPromotePrice  NUMERIC(24, 10) 
	-- 若没有符合时间段内的商品记录，则促销价为 0
	IF NOT EXISTS(
		SELECT	TOP 1 1
		FROM	PromotePrice
		WHERE	PTypeID = @chvPTypeID
			AND StartDate <= @chvBillDate
			AND EndDate >= @chvBillDate
			AND UnitID=@UnitID
		)
		BEGIN
			SET @intPromotePrice = 0
			RETURN
		END

	-- 若有符合时间段内的商品记录，且都满足往来单位、仓库、经手人参数条件，直接返回促销价格
	-- 此种情况，数据表中记录只可能有唯一的一条记录
	IF EXISTS(
		SELECT	TOP 1 1
		FROM	PromotePrice
		WHERE	PTypeID = @chvPTypeID
			AND BTypeID = @chvBTypeID
			AND KTypeID = @chvKTypeID
			AND ETypeID = @chvETypeID
			AND StartDate <= @chvBillDate
			AND EndDate >= @chvBillDate
			AND UnitID=@UnitID
		)
		BEGIN
			SELECT	TOP 1 @intPromotePrice = ISNULL(PromotePrice, 0)
			FROM	PromotePrice
			LEFT JOIN dbo.ptype p ON PTypeID = p.typeId
			WHERE	PTypeID = @chvPTypeID
				AND BTypeID = @chvBTypeID
				AND KTypeID = @chvKTypeID
				AND ETypeID = @chvETypeID
				AND StartDate <= @chvBillDate
				AND EndDate >= @chvBillDate
				AND UnitID=@UnitID
			RETURN
		END

	DECLARE @PTypeRowID int, @BTypeRowID int

	-- 建立查询临时表
	CREATE TABLE #temp_PromotePrice (
		RowID		int,		-- 唯一的行号 ID 值
		BTypeID		varchar(50),	-- 往来单位 ID 值
		KTypeID		varchar(50),	-- 仓库 ID 值
		ETypeID		varchar(50),	-- 经手人 ID 值
		Checked		int DEFAULT 0	-- 是否符合传入参数的节点数据标识，默认值 0
	)

	-- 查询出符合时间段内的所有商品 ID 值 ( 包括父节点 ID ) 记录，并插入临时表中
	INSERT INTO #temp_PromotePrice (
		RowID,
		BTypeID,
		KTypeID,
		ETypeID
		)
		SELECT	PromoteID,	-- 记录行号 ( 唯一 ID 值 )
			BTypeID,	-- 往来单位 ID 值
			KTypeID,	-- 仓库 ID 值
			ETypeID		-- 经手人 ID 值
		FROM	PromotePrice
		WHERE	PTypeID = @chvPTypeID
			AND StartDate <= @chvBillDate
			AND EndDate >= @chvBillDate
			AND UnitID=@UnitID


	-- ********	遍历符合传入参数条件的往来单位 ID 值 ( 包括父节点数据 )	********
	WHILE LEN(@chvBTypeID) >= 5
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice WHERE BTypeID = @chvBTypeID)
				BEGIN
					-- 若有符合传入往来单位 ID 值的记录 ( 或 ID 值属于其父节点 ID )，则 Checked 置 1
					UPDATE	#temp_PromotePrice
					SET	Checked = 1
					WHERE	BTypeID = @chvBTypeID
					
					SET @chvBTypeID = LEFT(@chvBTypeID,LEN(@chvBTypeID) - 5)
				END
			ELSE
				SET @chvBTypeID = LEFT(@chvBTypeID,LEN(@chvBTypeID) - 5)
		END

	-- 客户供货商统一
	UPDATE	#temp_PromotePrice
	SET	Checked = 1
	WHERE	BTypeID = '00000'

	-- 删除 Checked 值不为 1 的数据
	DELETE FROM #temp_PromotePrice
	WHERE	Checked <> 1

	-- 若此时数据库没有记录，则返回促销价格为 0
	IF NOT EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice)
		BEGIN
			SET @intPromotePrice = 0
			RETURN
		END

/*	SELECT	@intRowCount = COUNT(*)
	FROM	#temp_PromotePrice

	-- 若记录数大于 1，则作筛选删除
	IF @intRowCount > 1
		BEGIN
			-- 查询出记录中 BTypeID 值的最大位数
			DECLARE @intLenBTypeID int
			SELECT @intLenBTypeID = MAX(LEN(BTypeID)) FROM #temp_PromotePrice
		
			-- 删除小于 BTypeID 值最大位数的记录
			DELETE FROM #temp_PromotePrice
			WHERE	LEN(BTypeID) <> @intLenBTypeID
		END
*/
	-- 在客户供货商统一的情况下，若记录中存在有全部客户 ( 00000 ) 和 所有客户 ( 00001 ) 或 所有供货商 ( 00002 )
	-- 则删除全部客户 ( 00000 ) 的记录
	IF EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice WHERE BTypeID = '00000')
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice WHERE BTypeID <> '00000' AND LEN(BTypeID) = 5)
				BEGIN
					DELETE FROM #temp_PromotePrice
					WHERE	BTypeID = '00000'
				END
		END

	-- 重新将 Checked 值置为 0
	UPDATE	#temp_PromotePrice
	SET	Checked = 0


	-- ********	遍历符合传入参数条件的仓库 ID 值 ( 包括父节点数据 )	********
	WHILE LEN(@chvKTypeID) >= 5
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice WHERE KTypeID = @chvKTypeID)
				BEGIN
					-- 若有符合传入往来单位 ID 值的记录 ( 或 ID 值属于其父节点 ID )，则 Checked 置 1
					UPDATE	#temp_PromotePrice
					SET	Checked = 1
					WHERE	KTypeID = @chvKTypeID

					SET @chvKTypeID = LEFT(@chvKTypeID,LEN(@chvKTypeID) - 5)
				END
			ELSE
				SET @chvKTypeID = LEFT(@chvKTypeID,LEN(@chvKTypeID) - 5)
		END

	-- 所有仓库
	UPDATE	#temp_PromotePrice
	SET	Checked = 1
	WHERE	KTypeID = '00000'

	-- 删除 Checked 值不为 1 的数据
	DELETE FROM #temp_PromotePrice
	WHERE	Checked <> 1

	-- 若此时数据库没有记录，则返回促销价格为 0
	IF NOT EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice)
	BEGIN
		SET @intPromotePrice = 0
		RETURN
	END

	-- 若记录中有仓库 ID 为 ( 00000 )，则代表所有仓库，若用其他的 ID 为 5 位，如 ( 00001 )
	-- 则删除全部仓库 ( 00000 ) 的记录
	IF EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice WHERE KTypeID = '00000')
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice WHERE KTypeID <> '00000' AND LEN(KTypeID) = 5)
			BEGIN
				DELETE FROM #temp_PromotePrice
				WHERE	KTypeID = '00000'
			END
	END

	-- 重新将 Checked 值置为 0
	UPDATE	#temp_PromotePrice
	SET	Checked = 0

	-- ********	遍历符合传入参数条件的经手人 ID 值 ( 包括父节点数据 )	********
	WHILE LEN(@chvETypeID) >= 5
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice WHERE ETypeID = @chvETypeID)
		BEGIN
			-- 若有符合传入往来单位 ID 值的记录 ( 或 ID 值属于其父节点 ID )，则 Checked 置 1
			UPDATE	#temp_PromotePrice
			SET	Checked = 1
			WHERE	ETypeID = @chvETypeID

			SET @chvETypeID = LEFT(@chvETypeID,LEN(@chvETypeID) - 5)
		END
		ELSE
			SET @chvETypeID = LEFT(@chvETypeID,LEN(@chvETypeID) - 5)
	END

	-- 所有经手人
	UPDATE	#temp_PromotePrice
	SET	Checked = 1
	WHERE	ETypeID = '00000'

	-- 删除 Checked 值不为 1 的数据
	DELETE FROM #temp_PromotePrice
	WHERE	Checked <> 1

	-- 若此时数据库没有记录，则返回促销价格为 0
	IF NOT EXISTS(SELECT TOP 1 1 FROM #temp_PromotePrice)
		BEGIN
			SET @intPromotePrice = 0
			RETURN
		END

	-- ********	对筛选出来的记录按照优先顺序再次筛选	********
	-- ********	往来单位 > 仓库 > 经手人	********
	-- 统计临时表中的记录数
	DECLARE @intRowCount int

	-- 统计临时表中的记录数
	SELECT	@intRowCount = COUNT(*)
	FROM	#temp_PromotePrice

	-- 若记录数大于 1，则作筛选删除 ( 针对往来单位 )
	IF @intRowCount > 1
		BEGIN
			-- 查询出记录中 BTypeID 值的最大位数
			DECLARE @intLenBTypeID int
			SELECT @intLenBTypeID = MAX(LEN(BTypeID)) FROM #temp_PromotePrice
		
			-- 删除小于 BTypeID 值最大位数的记录
			DELETE FROM #temp_PromotePrice
			WHERE	LEN(BTypeID) <> @intLenBTypeID
		END

	-- 统计临时表中的记录数
	SELECT	@intRowCount = COUNT(*)
	FROM	#temp_PromotePrice

	-- 若记录数大于 1，则作筛选删除 ( 针对仓库 )
	IF @intRowCount > 1
		BEGIN
			-- 查询出记录中 KTypeID 值的最大位数
			DECLARE @intLenKTypeID int
			SELECT @intLenKTypeID = MAX(LEN(KTypeID)) FROM #temp_PromotePrice
		
			-- 删除小于 KTypeID 值最大位数的记录
			DELETE FROM #temp_PromotePrice
			WHERE	LEN(KTypeID) <> @intLenKTypeID
		END

	-- 统计临时表中的记录数
	SELECT	@intRowCount = COUNT(*)
	FROM	#temp_PromotePrice

	-- 若记录数大于 1，则作筛选删除 ( 针对经手人 )
	IF @intRowCount > 1
		BEGIN
			-- 查询出记录中 ETypeID 值的最大位数
			DECLARE @intLenETypeID int
			SELECT @intLenETypeID = MAX(LEN(ETypeID)) FROM #temp_PromotePrice
		
			-- 删除小于 ETypeID 值最大位数的记录
			DELETE FROM #temp_PromotePrice
			WHERE	LEN(ETypeID) <> @intLenETypeID
		END

	-- ********	筛选结束	********

	-- 选取最后筛选出来的促销价格
	SELECT	TOP 1 @intPromotePrice = ISNULL(PromotePrice, 0)
	FROM	PromotePrice
	LEFT JOIN dbo.ptype p ON PTypeID = p.typeId
	WHERE	PromoteID IN ( 
			SELECT	RowID
			FROM	#temp_PromotePrice
	)
	AND UnitID=@UnitID
	DROP TABLE #temp_PromotePrice

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckPtypeEntryCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckPtypeEntryCode]
GO

-- ========================================================================
-- 功能说明：		检测商品的编码不能重复
-- 作者    ：		王刚
-- 时间：			2012-06-27
-- ========================================================================
CREATE    PROCEDURE [dbo].[Web_CheckPtypeEntryCode]
(
	@ptypeid		VARCHAR(50),
	@unitEntryCode	VARCHAR(200),
	@EntryCode		VARCHAR(200)	
)
--@encode$--

AS

DECLARE @doubleUnit INT = 0			--0为单一单位
DECLARE @TempEntryCode VARCHAR(200)= ''
SELECT TOP 1 @doubleUnit = Value FROM Userconfig WHERE ConfigName = 'doubleunit'

CREATE TABLE #TempEntryCodeTable(entrycode VARCHAR(100))
INSERT #TempEntryCodeTable SELECT * FROM f_split(@unitEntryCode,',')


--读取是否允许条码相同配置
IF EXISTS (SELECT *FROM Userconfig WHERE ConfigName='equalentrycode' AND Value='1')
	RETURN

--增加商品
IF @ptypeid = ''
BEGIN
	IF LTRIM(RTRIM(@EntryCode)) <> ''
	BEGIN
		IF EXISTS(SELECT * FROM ptype WHERE EntryCode = @EntryCode) OR EXISTS (SELECT * FROM PType_Units_Ext WHERE EntryCode = @EntryCode)
		BEGIN
			RAISERROR('条码【%s】已存在！',16,1,@EntryCode) RETURN
		END
	END
	--多单位表
	IF @doubleUnit = 1
	BEGIN
		SELECT TOP 1  @TempEntryCode=P.EntryCode FROM PType_Units_Ext p INNER JOIN #TempEntryCodeTable T ON T.entrycode = P.EntryCode
		IF @TempEntryCode <> ''
		BEGIN
			RAISERROR('条码【%s】已存在！',16,1,@TempEntryCode) RETURN
		END
		ELSE
		BEGIN
			SELECT TOP 1  @TempEntryCode=P.EntryCode FROM PType p INNER JOIN #TempEntryCodeTable T ON T.entrycode = P.EntryCode
			IF @TempEntryCode <> ''
			BEGIN
				RAISERROR('条码【%s】已存在！',16,1,@TempEntryCode) RETURN
			END
		END
	END
END
ELSE
BEGIN
	IF LTRIM(RTRIM(@EntryCode)) <> ''
	BEGIN
		IF EXISTS(SELECT * FROM ptype WHERE EntryCode = @EntryCode AND typeId <> @ptypeid) 
			OR EXISTS (SELECT * FROM PType_Units_Ext WHERE EntryCode = @EntryCode AND PtypeID <> @ptypeid)
		BEGIN
			RAISERROR('条码【%s】已存在！',16,1,@EntryCode) RETURN
		END
	END
	--多单位表
	IF @doubleUnit = 1
	BEGIN
		SELECT TOP 1  @TempEntryCode=P.EntryCode FROM PType_Units_Ext p INNER JOIN #TempEntryCodeTable T ON T.entrycode = P.EntryCode AND P.PtypeID <> @ptypeid 
		IF @TempEntryCode <> ''
		BEGIN
			RAISERROR('条码【%s】已存在！',16,1,@TempEntryCode) RETURN
		END
		ELSE
		BEGIN
			SELECT TOP 1  @TempEntryCode=P.EntryCode FROM PType p INNER JOIN #TempEntryCodeTable T ON T.entrycode = P.EntryCode AND P.typeId <> @ptypeid
			IF @TempEntryCode <> ''
			BEGIN
				RAISERROR('条码【%s】已存在！',16,1,@TempEntryCode) RETURN
			END
		END
	END
END

DROP TABLE #TempEntryCodeTable


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_CheckReportCommon]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].Web_CheckReportCommon
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*------------------------------------------
 作者：蒋奎
 日期：2014-11-05
 描述：基本信息检测
-------------------------------------------*/
CREATE PROCEDURE Web_CheckReportCommon
    (
      @CheckType VARCHAR(50), --基本信息类型 
      @TypeID VARCHAR(50)	  --基本信息ID	
    )
--@encode$--    
AS
SET NOCOUNT ON

BEGIN
		--第一步获取检测范围
		SELECT	BaseinfoType,
				TableName,
				TableColumnname,
				Explain,
				Conditions 
		INTO #BaseCheck
		FROM dbo.BaseInfoAssitDetection 
		WHERE BaseinfoType=@CheckType
		--第二步循环检测并返回检测结果
		DECLARE @BaseinfoType VARCHAR(200)
		DECLARE @TableName VARCHAR(200)
		DECLARE @TableColumnname VARCHAR(200)
		DECLARE @Explain VARCHAR(400)
		DECLARE @Conditions VARCHAR(400)
		DECLARE @SQL VARCHAR(MAX)
		DECLARE @count INT=0
		SET @SQL=''
		
		DECLARE CHECK_CURSOR  CURSOR FOR
		SELECT * FROM #BaseCheck
		OPEN CHECK_CURSOR
		FETCH NEXT FROM CHECK_CURSOR INTO @BaseinfoType,@TableName,@TableColumnname,@Explain,@Conditions
		WHILE @@FETCH_STATUS=0
		BEGIN	
			IF @TableName = 'MoneyBill'
			BEGIN
				SELECT @count=COUNT(1) FROM dbo.MoneyBill m INNER JOIN dbo.BillIndex b ON b.BillNumberId = m.BillNumberId WHERE b.BillType=78 AND m.DTypeId=@typeid
				IF @count>0
				BEGIN
					SET @SQL +=	' SELECT TOP 1  ''该部门已在固定资产(项目)折旧单中使用!'' as Explain  UNION '
					--RAISERROR('该部门已在固定资产(项目)折旧单中使用!',16,1)
				END
				SELECT @count=COUNT(1) FROM dbo.MoneyBill m INNER JOIN dbo.BillIndex b ON b.BillNumberId = m.BillNumberId WHERE b.BillType !=78 AND m.DTypeId=@typeid
				IF @count>0
				BEGIN
					SET @SQL +=	' SELECT TOP 1  ''该部门已在现金费用单中使用!'' as Explain  UNION '
					--RAISERROR('该部门已在现金费用单中使用!',16,1)
				END
			END 
			ELSE
			BEGIN
			IF  @Conditions = ''
				SET @SQL +=	' SELECT TOP 1 '''+ @Explain +''' as Explain FROM '+@TableName+ ' WHERE '+@TableColumnname+'='''+@TypeID+''' UNION '
			IF	@Conditions <> ''
				SET @SQL +=	' SELECT TOP 1 '''+ @Explain +''' as Explain FROM '+@TableName+ ' WHERE '+@TableColumnname+'='''+@TypeID+''' AND '+@Conditions+' UNION '
			END 
			FETCH NEXT FROM CHECK_CURSOR INTO @BaseinfoType,@TableName,@TableColumnname,@Explain,@Conditions
		END
		CLOSE CHECK_CURSOR
		DEALLOCATE CHECK_CURSOR
		
		DECLARE @result INT =0
		exec @result=dbo.Web_Common_BaseInfoCustomCheck @ctypename='Stype',@ctypeid=@TypeId,@result=0
		IF @result=1
		BEGIN
			SET @SQL +=	 'SELECT ''当前信息已在自定义中关联!'' as Explain  UNION '
		END
		
		--@WHERE 变量的目的是避免Union空报错
		DECLARE @WHERE VARCHAR(50)
		SET @WHERE =' SELECT ''1'' WHERE 1<>1 '
		
		--PRINT (@SQL+@WHERE)
		EXEC (@SQL+@WHERE)
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckSelectLimitIsAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckSelectLimitIsAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-12-2
	描述：权限保存时，验证选择的父类是否是全部权限
-------------------------------------------*/
CREATE PROCEDURE Web_CheckSelectLimitIsAll
(
	@Type		INT,
	@TypeIDs	VARCHAR(MAX),
	@OperatorID VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON


DECLARE @MainTable	VARCHAR(100), --基本信息表
		@AllManID	VARCHAR(100),
		@TableName	VARCHAR(100),--权限表
		@atypeType  CHAR(1)
		
IF @Type IN (0,1)
BEGIN
	SET @MainTable = 'BType'
	SET @TableName = 'BType_L'
	IF @Type = 0
		SET @AllManID = '00001'
	ELSE
		SET @AllManID = '00002'
END
-- PType
ELSE IF @Type = 2
BEGIN
	SET @MainTable = 'PType'
	SET @TableName = 'PType_L'
	SET @AllManID = '00000'
END
-- KType
ELSE IF @Type = 3
BEGIN
	SET @MainTable = 'stock'
	SET @TableName = 'KType_L'
	SET @AllManID = '00000'
END
-- EType
ELSE IF @Type = 4
BEGIN
	SET @MainTable = 'employee'
	SET @AllManID = '00001'
	SET @TableName = 'EType_L'
END
-- DType
ELSE IF @Type = 9
	BEGIN
		SET @MainTable = 'Department'
		SET @AllManID = '00000'
		SET @TableName = 'DType_L'
	END
--SType
ELSE IF @Type = 10
BEGIN
	SET @MainTable = 'SType'
	SET @AllManID = '00000'
	SET @TableName = 'SType_L'
END
-- others
ELSE
BEGIN
	SET @MainTable = 'Ac_Items'
	SET @TableName = 'AType_L'
	SET @AllManID = '0000'
	IF @Type = 5
		SET @atypeType = '0'
	ELSE IF @Type = 6
		SET @atypeType = '1'
	ELSE IF @Type = 7
		SET @atypeType = '2'
	ELSE IF @Type=8
		SET @atypeType = '3'
	ELSE IF(@Type=11)
		SET @atypeType = '4'
	ELSE IF(@Type=12)
		SET @atypeType = '5'
	ELSE IF(@Type=13)
		SET @atypeType = '6'
	ELSE IF(@Type=14)
		SET @atypeType = '7'
	ELSE IF(@Type=15)
		SET @atypeType = '8'

END


CREATE TABLE #PartentID(typeid VARCHAR(50),FullName VARCHAR(200) DEFAULT(''))

--把下面的代码弄到上面来，在没有更改数据之前，要做验证
CREATE TABLE #TYPEIDS
(
	typeid VARCHAR(50)
)
--项目分类在9.0 Sp6中做特殊处理
IF @MainTable = 'Ac_Items'
	INSERT INTO #Typeids SELECT Ac.nTypeId a FROM f_split(@TypeIDs, ',') A INNER JOIN Ac_Items Ac on ac.nId = A.a
ELSE
	INSERT INTO #Typeids SELECT a FROM f_split(@TypeIDs, ',')

IF @Type = 0
	UPDATE 	#TYPEIDS SET typeid='00001' WHERE typeid='00000'
IF @Type = 1
	UPDATE 	#TYPEIDS SET typeid='00002' WHERE typeid='00000'

DECLARE @CheckSql VARCHAR(1000)=''

--检测权限(选择的父节点是否有全部权限)
IF @OperatorID <> '00001'
BEGIN
	DECLARE @FullName VARCHAR(300)
	DECLARE @MSG VARCHAR(500)
	
	SET @CheckSql = ' INSERT #PartentID(typeid)
					  SELECT TOP 1 T.typeid FROM #TYPEIDS T 
					  INNER JOIN '+@TableName+' L ON L.typeid = T.typeid 
					  WHERE L.flag = 0 AND L.etypeid = '''+@OperatorID+''' '
					  
	IF @MainTable = 'Ac_Items'
		SET @CheckSql += 'AND L.type = '+@atypeType+' '
	
	EXEC(@CheckSql)

	IF @MainTable = 'Ac_Items'
		UPDATE #PartentID SET FullName =A.FullName
		FROM Ac_Items A
		WHERE A.nTypeId = #PartentID.typeid
	ELSE
	BEGIN
		SET @CheckSql += '
			UPDATE #PartentID SET FullName =A.FullName
			FROM  '+@MainTable+' A
			WHERE A.TypeId = #PartentID.typeid '
		
		EXEC(@CheckSql)
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM #PartentID)
	BEGIN
		SELECT TOP 1 @FullName = FullName FROM #PartentID
		SET @MSG = '您没有该父类【'+@FullName+'】下所有子类的权限，不能直接勾选父类授权，
请选择相关子类授权或咨询管理员！'
		
		RAISERROR(@MSG,16,1)
		RETURN
	END
	
	
END


DROP TABLE #PartentID,#TYPEIDS


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckStockCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckStockCount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*
	作者：王伟
	日期：2010-05-25
	描述：AllotDistQueryInputService.cs 判断选中仓库的个数
*/


CREATE   PROCEDURE  Web_CheckStockCount
(
	@ktypeid		VARCHAR(100),			--查询仓库
	@auditinStock 	INT,					--审核单据时，仓库权限有效[0=true，1=False]
	@OperatorId			VARCHAR(50),			--用户
	@typeid  		VARCHAR(8000)='00000',	--对应仓库名称
	@stypeid		VARCHAR(MAX)
)

--@encode$--
AS
	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)


--------------------------构建当前的SQL变量
--DECLARE	@sql VARCHAR(8000)

--IF @typeid ='00000'	
--BEGIN
--	SET @sql='
--			SELECT	typeid,
--					fullname 
--			FROM 	stock 
--			WHERE 	typeid<>'+CHAR(39)+@ktypeid+CHAR(39)+' 
--					AND deleted = 0 
--					AND sonnum = 0 '
--END
--ELSE 
--BEGIN
--	SET @sql='
--				SELECT 	typeid,
--						fullname 
--				FROM 	stock 
--				WHERE 	typeid IN
--				(
--					SELECT 	a.typeid 
--					FROM 	stock a 
--					INNER JOIN 
--					(
--						SELECT A FROM dbo.f_split('+CHAR(39)+@typeid+CHAR(39)+','','')
--					) b 
--					ON a.typeid LIKE b.A+''%''
--				) 
--				AND typeid<>''' + @ktypeid + ''' 
--				AND deleted = 0 
--				AND sonnum = 0 '

--END

--IF @auditinStock=0 
--BEGIN
--	SET @sql=@sql+' AND typeid IN (select typeid from dbo.F_GetManDetailKType('''+@OperatorId+'''))'
--END

--SET @sql=@sql+' AND stypeid IN (SELECT typeid FROM #GetSelectSTypeId) ';

--PRINT(@sql)Select CHAR(39)
--EXEC(@sql)
CREATE TABLE #Stock
(
	TypeId		varchar(100)
)
IF @typeid = '00000' --全部仓库
	BEGIN
		IF @auditinStock = 1	--无效
			INSERT INTO #Stock(TypeId)
			SELECT S.TypeId 
			FROM Stock S	
				INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
			WHERE S.TypeID <> @ktypeid 
				
				AND S.SonNum = 0 
			ORDER BY S.UserCode
		ELSE
			INSERT INTO #Stock(TypeId)
			SELECT S.TypeId
			FROM F_GetManKTypeAll(@OperatorID) S 
					INNER JOIn #GetSelectSTypeId ss ON s.STypeId=ss.TypeId
			WHERE S.TypeID <> @ktypeid  AND S.SonNum = 0 
			ORDER BY S.UserCode
	END
ELSE
	BEGIN
		SELECT A INTO #SplitKType FROM F_Split(@typeid,',') WHERE A<>@ktypeid		
		IF  @auditinStock = 1	--无效
		BEGIN
			INSERT INTO #Stock(TypeId)
			SELECT s.TypeId 
			FROM dbo.Stock s
			INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
			INNER JOIN #SplitKType b ON s.typeid LIKE b.A+'%'
			WHERE s.sonnum=0 
				AND s.TypeId <> @ktypeid	
		END
		ELSE
		BEGIN
			INSERT INTO #Stock(TypeId)
			SELECT S.TypeId
			FROM F_GetManKTypeAll(@OperatorID) s
			INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
			INNER JOIN  #SplitKType b ON s.typeid LIKE b.A+'%'
			WHERE s.sonnum=0 
				AND s.TypeId <> @ktypeid	
			
		END
		DROP TABLE #SplitKType	
	END
SELECT * FROM #Stock
DROP TABLE #GetSelectSTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckSysValue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckSysValue]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	DECLARE @RE VARCHAR(MAX)
	EXEC Web_CheckSysValue 9,@RE OUTPUT
	SELECT @RE
*/
CREATE PROCEDURE Web_CheckSysValue
(
	@Flag			INT,
	@SysValue		VARCHAR(MAX) OUTPUT	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @sql		NVARCHAR(2000)

IF @Flag = 1
BEGIN
	SET @sql='SELECT TOP 1 @subvalue=SubValue FROM Sysdata WHERE SubNo  =   720' 
	EXEC sp_executesql @sql, N'@subvalue int out', @SysValue OUT
END
ELSE IF @Flag = 2
BEGIN
	SET @sql='SELECT TOP 1 @subvalue=sizename FROM fz_size WHERE sizeid  =   720' 
	EXEC sp_executesql @sql, N'@subvalue int out', @SysValue OUT
END
ELSE IF @Flag = 3
BEGIN
	SET @sql='SELECT TOP 1 @subvalue=SubValue FROM Sysdata WHERE SubNo  =   722' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @SysValue OUT
END
ELSE IF @Flag = 4
BEGIN
	SET @sql='SELECT TOP 1 @subvalue = CAST(ColorId / 2 AS VARCHAR(MAX)) + "." FROM dbo.FZ_Color WHERE LEFT(ColorName,1) = ''红''' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @SysValue OUT
END
ELSE IF @Flag = 5
BEGIN
	SET @sql='SELECT TOP 1 @subvalue = CAST(ColorId / 4 AS VARCHAR(MAX)) + "." FROM dbo.FZ_Color WHERE LEFT(ColorName,1) = ''橙''' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @SysValue OUT
END
ELSE IF @Flag = 6
BEGIN
	SET @sql='SELECT TOP 1 @subvalue = CAST(ColorId / 6 AS VARCHAR(MAX)) + "." FROM dbo.FZ_Color WHERE LEFT(ColorName,1) = ''黄''' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @SysValue OUT
END
ELSE IF @Flag = 7
BEGIN
	SET @sql='SELECT TOP 1 @subvalue = CAST(ColorId / 8 AS VARCHAR(MAX)) + "." FROM dbo.FZ_Color WHERE LEFT(ColorName,1) = ''绿''' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @SysValue OUT
END
ELSE IF @Flag = 8
BEGIN
	DECLARE @sysCurDate		VARCHAR(MAX),
			@fzCurDate		VARCHAR(MAX),
			@sysCurValue	INT,
			@fzCurValue		INT
			
	SET @sql='SELECT TOP 1 @subvalue=SubValue FROM Sysdata WHERE SubNo  =   719' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @sysCurDate OUT
	
	SET @sql='SELECT TOP 1 @subvalue=sizename FROM fz_size WHERE sizeid  =   719' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @fzCurDate OUT
				
	SET @sql='SELECT TOP 1 @subvalue=sizename FROM fz_size WHERE sizeid  =   720' 
	EXEC sp_executesql @sql, N'@subvalue int out', @SysValue OUT
	
	IF @sysCurDate <> @fzCurDate
		SET @SysValue = 3	
END
ELSE IF @Flag = 9
BEGIN
	DECLARE @srcValue  VARCHAR(MAX),
			@descValue  VARCHAR(MAX),
			@zeroValue	VARCHAR(MAX),
			@oneValue	VARCHAR(MAX)
			
	SET @zeroValue = 'bhWCruESCG0='			
	SET @oneValue = 'GJHJYRq9Rg8='
	
	SET @sql='SELECT TOP 1 @subvalue=password FROM Hr_Person WHERE Name = ''00003''' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @srcValue OUT
	
	SET @sql='SELECT TOP 1 @subvalue=password FROM Hr_Person WHERE Name = ''00004''' 
	EXEC sp_executesql @sql, N'@subvalue varchar(max) out', @descValue OUT
	
	IF @srcValue = '0'
	BEGIN
		IF @descValue <> @zeroValue
			SET @SysValue = 1
		ELSE
			SET @SysValue = 0
	END
	ELSE IF @srcValue = '1'
	BEGIN
		IF @descValue <> @oneValue
			SET @SysValue = 1
		ELSE IF @srcValue = 1
			SET @SysValue = 1
		ELSE		
			SET @SysValue = 0
	END
	ELSE
	BEGIN
		SET @SysValue = 1
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CheckTeWithAcConnect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CheckTeWithAcConnect]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.04.24
	描述：检测总账是否可与出纳联用
*/
CREATE PROCEDURE Web_CheckTeWithAcConnect
(
	@operatorid			VARCHAR(50),		-- 当前操作员ID
	@StypeId			VARCHAR(50),		-- 分支机构
	@SFYear				INT,				-- 启用年度
	@SFPeriod			INT					-- 启用期间
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @TFYear INT,
		@TFPeriod INT,
		@AFYear INT,
		@AFPeriod INT
		
IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_StartPeriod WHERE STypeId = @StypeId AND IsConnect = 1)
BEGIN
	RAISERROR('出纳系统已与总账系统联用',16,1)
	RETURN
END

--获取 出纳当前期间，未结束初始化无法联用
IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period WHERE STypeId = @StypeId)
BEGIN
	SELECT @TFYear = FYear,@TFPeriod = FPeriod FROM dbo.Te_Period WHERE STypeId = @StypeId
END
ELSE
BEGIN
	RAISERROR('出纳未结束初始化，无法联用',16,1)
	RETURN
END

--获取 总账当前期间
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @StypeId AND IsUse=0)
BEGIN
	RAISERROR('未开账，无法联用',16,1)
	RETURN 
END
ELSE 
	SELECT @AFYear = FYear,@AFPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @StypeId

IF @TFYear <>@AFYear OR @TFPeriod <> @AFPeriod
BEGIN
	RAISERROR('出纳系统与总账系统期间不匹配，无法联用',16,1)
	RETURN 
END


IF EXISTS(
SELECT TOP 1 1
FROM
(
SELECT T1.InitBalance,ISNULL(T2.FBeginBalanceFor,0) AS FBeginBalanceFor
FROM dbo.Te_Balance T1
LEFT JOIN dbo.Ac_Balance T2 ON T1.ATypeId = T2.ATypeId AND T1.Cid = T2.Cid AND T1.STypeid = T2.STypeId AND T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod
WHERE T1.Cid = 0 AND T1.FYear = @TFYear AND T1.FPeriod = @TFPeriod AND T1.STypeId = @StypeId AND T1.BUId <> 3

UNION ALL

SELECT ISNULL(T2.InitBalance,0) AS InitBalance,ISNULL(T1.FBeginBalanceFor,0) AS FBeginBalanceFor
FROM dbo.Ac_Balance T1
INNER JOIN dbo.Ac_Account T3 ON T1.STypeId = T3.StypeId AND T1.ATypeId = T3.TypeId AND T1.Cid = 0 AND T1.FYear = @TFYear AND T1.FPeriod = @TFPeriod AND T1.STypeId = @StypeId AND (T3.IsCash = 1 OR T3.IsBank = 1)
LEFT JOIN dbo.Te_Balance T2 ON T1.ATypeId = T2.ATypeId AND T1.Cid = T2.Cid AND T1.STypeid = T2.STypeId AND T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod AND ISNULL(T2.BUId,1) <> 3 
) AS T
WHERE T.InitBalance <> T.FBeginBalanceFor
)
BEGIN
	RAISERROR('出纳系统与总账系统当期期初余额不一致，无法联用,请检查两个系统中现金科目和银行科目的期初值。',16,1)
	RETURN 
END

IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'actellersign' AND SubValue = 0)
	UPDATE dbo.sysdata SET SubValue = 1 WHERE SubName = 'actellersign'

--没有问题，更新联用状态
UPDATE dbo.Te_StartPeriod SET IsConnect = 1,CFYear = @TFYear,CFPeriod = @TFPeriod WHERE STypeId = @StypeId

SELECT @TFYear AS cfyear,@TFPeriod AS cfperiod,CAST(@TFYear AS VARCHAR(10)) + '年' + CAST(@TFPeriod AS VARCHAR(10)) + '期' as connecttext

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_CombinationSaleOrderBillQuery]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_CombinationSaleOrderBillQuery
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回组合品销售订单采购查询列表
-- 时间：	2019-06-04
-- 作者：	赵燕琴
-- ========================================================================
CREATE PROC Web_CombinationSaleOrderBillQuery
(
	@InputStartDate 	VARCHAR(50),--录单开始时间
	@InputEndDate 		VARCHAR(50),--录单结束时间
	@StartDate 			VARCHAR(50),--发货开始时间
	@EndDate 			VARCHAR(50),--发货开始时间
	@StypeId 			VARCHAR(50),--分支机构ID
	@BillCode 			VARCHAR(200)='',--单据编号
	@ETypeId 			VARCHAR(MAX)='',--经手人
	@DTypeId			VARCHAR(MAX)='',--部门
	@DealBTypeId 		VARCHAR(MAX)='',--客户名称
	@KTypeId			VARCHAR(MAX)='',--仓库名称
	--@PTypecategoryId	VARCHAR(MAX)='',--商品类型
	@PTypeId 			VARCHAR(MAX)='',--商品名称
	@IComment			VARCHAR(256)='',--摘要
	@Explain			VARCHAR(200)='',--说明
	@WayBillCode 		VARCHAR(60)='',--运单号
	@Tel 				VARCHAR(20)='',--承运单位
	@GoodsNumber		VARCHAR(50)='',--物件数量
	@PackWay			VARCHAR(256)='',--包装方式
	@DComment 			VARCHAR(200),--备注
	@Cid				INT,--币种 0=所有币种
	@AuditStatus		INT=9,--审核状态 9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据
	@SaleStatus			INT=0,--发货状况 0=全部,1=未引用,2=已引用未完成,3=未完成,4=已完成
	@BuyStatus          INT=0,----采购状况 0=全部,1=未采购,2=已采购未完成,3=未完成采购,4=已完成采购
	@OperatorID			VARCHAR(50)--操作员ID
)

--@Encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--================================== 业务处理【BEGIN】  ===========================================
--分支机构
CREATE TABLE #SType(TypeId VARCHAR(50))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--往来单位/客户名称
CREATE TABLE #BType(TypeId VARCHAR(50))
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealBTypeId,2,@OperatorID)

--仓库
CREATE TABLE #KType(TypeId VARCHAR(50))
INSERT INTO #KType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	

--职员
CREATE TABLE #EType(TypeId VARCHAR(50))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID)	

--部门
CREATE TABLE #DType(TypeId VARCHAR(50),DFullName VARCHAR(200))
INSERT INTO #DType(TypeId,DFullName) SELECT F.TypeId,D.FullName DFullName FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID) F INNER JOIN Department D ON D.typeid=F.TypeId	

--商品
CREATE TABLE #PType(TypeId VARCHAR(50),PFullName VARCHAR(200),PUserCode VARCHAR(200),baseUnitId INT)
IF ISNULL(@PTypeId,'')='' OR @PTypeId='00000'
	INSERT INTO #PType(TypeId,PFullName,PUserCode,baseUnitId)  SELECT F.TypeId,P.FullName PFullName ,P.UserCode PUserCode,P.baseUnitId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID) F INNER JOIN dbo.ptype P ON P.typeId=F.TypeId
ELSE
	INSERT INTO #PType(TypeId,PFullName,PUserCode,baseUnitId)  
	SELECT  F.TypeId ,
			P.FullName PFullName ,
			P.UserCode PUserCode ,
			P.baseUnitId
	FROM    dbo.ptype P
			INNER JOIN ( SELECT ptypeid
						 FROM   CombinationProductDetail
						 WHERE  CombinationProductID IN (
								SELECT  CombinationProductID
								FROM    CombinationProductIndex
								WHERE   CombinationProductPtypeId = @PTypeId )
					   ) AS comproduct ON p.typeId = comproduct.ptypeid
			INNER JOIN F_GetManDetailPTypeIncludeCombination(@OperatorID) F ON P.typeId = F.TypeId
--查询订单状态
DECLARE @orderBillType INT
 
SET @orderBillType = 313	
DECLARE @SQL VARCHAR(MAX)=''

SET @SQL='
SELECT	
	A.BillNumberID,
	A.BillDate,
	a.ReachDate,
	A.Billcode,
	A.checkTime,
	CASE WHEN A.isyapi=1 THEN ''云分销订单'' ELSE ''正常订单'' END  [Type],
	
	CASE WHEN states.ReachQty IS NULL THEN ''未采购''
				 WHEN states.qty>states.ReachQty THEN ''已采购未完成''
				 WHEN states.qty<=states.ReachQty  THEN ''已完成采购''
				 END  AS StateName,

	PO.ptypeid,
	A.DealBTypeID,
	A.btypeid,
	A.etypeid,
	A.ktypeid,
	A.DtypeId,
	D.DFullName,
	cbi.CombinationProductFullName as PFullName,
	cbi.CombinationProductUsercode AS PUsercode,
	A.comment IComment,
	A.explain,
	PO.comment DComment,
	PO.qty,
	ISNULL(PO.ReachQty,0) SaleReachQty,
	ISNULL(po.SaleOrderReachQty,0) BuyQty,
	ISNULL(Buy.BuyReachQty,0) BuyReachQty,
	ISNULL(PP.RecAmgSTypeBuyPrice,0) RecPrice,
	A.Billtype,
	SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
	SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
	SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
	SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
	SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head
	
FROM OrderIndex A
--inner join PT_Combin_OrderBill bi on A.billNumberId=bi.billNumberID 	 
INNER JOIN PT_Combin_OrderBillDetail PO ON PO.billNumberID=A.billNumberId
INNER JOIN #SType S ON S.TypeId=A.Stypeid
INNER JOIN #PType P ON P.TypeId=PO.ptypeid
INNER JOIN #BType BT ON BT.TypeId=A.DealBTypeID
INNER JOIN #KType K ON K.TypeId=A.ktypeid
INNER JOIN #EType E ON E.TypeId=A.etypeid
INNER JOIN #DType D ON D.TypeId=A.DtypeId
LEFT JOIN PType_Price PP ON PP.PTypeID=P.TypeId and p.baseUnitId=pp.UnitID
LEFT JOIN combinationproductindex cbi  ON po.combinationptypeid=cbi.CombinationProductPtypeId
INNER JOIN (	/*订单状态集合*/
	
       		SELECT	OrderStateName = case dbo.F_GetCombinOrderState(BillNumberID,'+CONVERT (VARCHAR(10),@orderBillType)+')  
       												when ''1'' then ''已引用未完成''
													when ''2'' then ''已完成''
													when ''4'' then ''未引用''
													else '''' end ,
										billnumberid 
										FROM dbo.OrderIndex 
				
       						) Orderstates  ON a.billnumberid=Orderstates.billnumberid
 INNER JOIN (	/*采购状态集合*/
 
 		select c.OrderID, sum(c.Qty) AS Qty,sum(c.ReachQty) AS ReachQty
					 from (SELECT detail.OrderID, ob.qty,ob.ReachQty	FROM PT_Combin_OrderBillDetail  detail 
				        	left JOIN orderbill ob ON ob.PTCombinOrderBillDetailID=detail.OrderID) c
					GROUP BY c.OrderID
 
       						) states  ON po.OrderID=states.OrderID      						
       	
LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype        			
LEFT JOIN (
		SELECT
			B.PTCombinOrderBillDetailID,
			PO.PtypeId,
			ISNULL(SUM(B.ReachQty),0) BuyReachQty 
			FROM PT_Combin_OrderBillDetail PO
		INNER JOIN OrderBill B ON PO.OrderID=B.PTCombinOrderBillDetailID 
		INNER JOIN #PType P ON P.TypeId=PO.PtypeId
		INNER JOIN OrderIndex O ON O.BillNumberId=B.billNumberID AND O.RedWord=0 AND B.BillOver=0 AND B.PTCombinOrderBillDetailID>0 
		GROUP BY
			B.PTCombinOrderBillDetailID,
			PO.PtypeId
	) Buy ON Buy.PtypeId=PO.PtypeId AND Buy.PTCombinOrderBillDetailID=PO.OrderID
WHERE 
	A.billtype=313 
	AND PO.BillOver=0
	AND A.RedWord=0 '+CHAR(13)
	
IF( ISNULL(@InputStartDate,'')<>'')
	SET @SQL+='	AND A.BillDate>='''+@InputStartDate+''''+CHAR(13)
	
IF( ISNULL(@InputEndDate,'')<>'')
	SET @SQL+='	AND A.BillDate<='''+@InputEndDate+''''+CHAR(13)
	
IF( ISNULL(@StartDate,'')<>'')
	SET @SQL+='	AND A.ReachDate>='''+@StartDate+''''+CHAR(13)
	
IF( ISNULL(@EndDate,'')<>'')
	SET @SQL+='	AND A.ReachDate<='''+@EndDate+''''+CHAR(13)

IF( ISNULL(@BillCode,'')<>'')
	SET @SQL+='	AND A.Billcode LIKE ''%'+@BillCode+'%'''+CHAR(13)
	
IF( ISNULL(@IComment,'')<>'')
	SET @SQL+='	AND A.comment LIKE ''%'+@IComment+'%'''+CHAR(13)
	
IF( ISNULL(@Explain,'')<>'')
	SET @SQL+='	AND A.explain LIKE ''%'+@Explain+'%'''+CHAR(13)
	
IF( ISNULL(@WayBillCode,'')<>'')
	SET @SQL+='	AND A.WayBillCode LIKE ''%'+@WayBillCode+'%'''+CHAR(13)
	
IF( ISNULL(@Tel,'')<>'')
	SET @SQL+='	AND A.TEL LIKE ''%'+@Tel+'%'''+CHAR(13)
	
IF( ISNULL(@GoodsNumber,'')<>'')
	SET @SQL+='	AND A.GoodsNumber LIKE ''%'+@GoodsNumber+'%'''+CHAR(13)
	
IF( ISNULL(@PackWay,'')<>'')
	SET @SQL+='	AND A.PackWay LIKE ''%'+@PackWay+'%'''+CHAR(13)
	
IF( ISNULL(@DComment,'')<>'')
	SET @SQL+='	AND po.comment LIKE ''%'+@DComment+'%'''+CHAR(13)
	
IF(@Cid<>0)
	SET @SQL+='	AND A.CID='+CAST(@Cid AS VARCHAR(10))+CHAR(13)
		
--@AuditStatus		INT=9,--审核状态  9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据
IF(@AuditStatus=0)
	BEGIN
		SET @SQL+='	AND NOT EXISTS(
			SELECT
				TOP 1 1
			FROM AuditingBill A
			INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID AND F.BillType = '+CAST(@orderBillType AS VARCHAR(10))+'
			INNER JOIN #SType S ON S.TypeID = F.Stypeid											
			WHERE
				A.BillNumberID=BillNumberID
				AND BillIndexType = 0
			)'+CHAR(13)
	END
ELSE IF(@AuditStatus IN(1,2,3))
	BEGIN
		SET @SQL+='	AND EXISTS(
			SELECT
				TOP 1 1
			FROM AuditingBill A
			INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID AND F.BillType = '+CAST(@orderBillType AS VARCHAR(10))+'
			INNER JOIN #SType S ON S.TypeID = F.Stypeid											
			WHERE
				A.BillNumberID=BillNumberID
				AND F.IfUse=1 
				AND A.BillIndexType=0
				AND A.IfAudit=CASE WHEN '+CAST(@AuditStatus AS VARCHAR(2))+'=1 THEN 0
									WHEN '+CAST(@AuditStatus AS VARCHAR(2))+'=2 THEN 1
									ELSE -1
								END	
			)'+CHAR(13)						
	END

--	@SaleStatus INT=0,--发货状况  0=全部,1=未引用,2=已引用未完成,3=未完成,4=已完成
--IF(@SaleStatus=1)
--	SET @SQL+='	AND NOT EXISTS(SELECT * FROM PT_Combin_SaleBill WHERE OrderID=po.OrderID)'+CHAR(13)
--ELSE IF(@SaleStatus=2)
--	SET @SQL+='	AND (EXISTS(SELECT * FROM PT_Combin_SaleBill WHERE OrderID=po.OrderID) AND po.Qty>po.ReachQty)'+CHAR(13)
--ELSE IF(@SaleStatus=3)
--	SET @SQL+='	AND ((EXISTS(SELECT * FROM PT_Combin_SaleBill WHERE OrderID=po.OrderID) AND po.Qty>po.ReachQty)
--						OR (NOT EXISTS(SELECT * FROM PT_Combin_SaleBill WHERE OrderID=po.OrderID) AND po.ReachQty=0))'+CHAR(13)
--ELSE IF(@SaleStatus=4)
--	SET @SQL+='	AND po.Qty<=po.ReachQty'+CHAR(13)
	IF @SaleStatus = 1 --已引用未完成
		BEGIN
			SET  @SQL = @SQL + '  and OrderStateName=''已引用未完成'' '
		END
		
		IF @SaleStatus = 3 --未完成
		BEGIN
			SET  @SQL = @SQL + '  and (OrderStateName=''已引用未完成'' OR  OrderStateName=''未引用'' )'
		END

		
	    IF @SaleStatus = 2 --已完成
			SET  @SQL = @SQL + '  and OrderStateName=''已完成'' '
			
		IF @SaleStatus = 4 --未引用
		BEGIN
			SET  @SQL = @SQL + '  and OrderStateName=''未引用'' '
		END	
		
--@BuyStatus          INT=0,--采购状况 0=全部,1=未采购,2=已采购未完成,3=未完成采购,4=已完成采购
IF(@BuyStatus=1)
	SET @SQL+='	AND ISNULL(SaleOrderReachQty,0)=0'+CHAR(13)
ELSE IF(@BuyStatus=2)
	SET @SQL+='	AND ISNULL(SaleOrderReachQty,0) < ISNULL(B.Qty,0)	AND ISNULL(SaleOrderReachQty,0)<>0'+CHAR(13)
ELSE IF(@BuyStatus=3)
	SET @SQL+='	AND ISNULL(B.Qty,0)>ISNULL(SaleOrderReachQty,0)'+CHAR(13)
ELSE IF(@BuyStatus=4)
	SET @SQL+='	AND ISNULL(SaleOrderReachQty,0) = ISNULL(B.Qty,0)'+CHAR(13)
	
	
	
		--IF @SaleStatus = 1 --未采购
		--BEGIN
		--	SET  @SQL = @SQL + '  and StateName=''未采购'' '
		--END
		
		--IF @SaleStatus = 3 --未完成采购
		--BEGIN
		--	SET  @SQL = @SQL + '  and (StateName=''已采购未完成'' OR  StateName=''未采购'' )'
		--END

		
	 --   IF @SaleStatus = 4 --已完成采购
		--	SET  @SQL = @SQL + '  and StateName=''已完成采购'' '
			
		--IF @SaleStatus = 2 --已采购未完成
		--BEGIN
		--	SET  @SQL = @SQL + '  and StateName=''已采购未完成'' '
		--END	

SET @SQL+='ORDER BY A.BillDate,A.Billcode DESC'+CHAR(13)

--PRINT @SQL
EXEC(@SQL)
--================================== 业务处理【END】    ===========================================


--================================== 删除临时表【BEGIN】===========================================

DROP TABLE #SType,#BType,#DType,#EType,#KType,#PType

--================================== 删除临时表【END】  ===========================================
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CombinationSaleOrderCollectQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_CombinationSaleOrderCollectQuery]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ============================================= 

-- 作者: 魏伟
-- 日期: 2016-06-24
-- 描述: 组合品订单汇总表

-- =============================================

create PROCEDURE [dbo].Web_CombinationSaleOrderCollectQuery
(
	@OperatorID  		varchar(50),                     
	@StartDate 			varchar(30),
	@EndDate 			varchar(30),
	@Etypeid 			varchar(1550)='',
	@dealBtypeid 			varchar(1550)='',
	@Ktypeid 			varchar(1550)='',
	@Ptypeid 			varchar(1550)='',
	@dtypeid			varchar(1550)='' ,  
	@stypeid            varchar(1550)='00001',
	@IncludeStop		int=0,  --是否包含停用 0-不包含 1-包含  
	@unitconvert    VARCHAR(10)    --多单位种类

)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype (TypeID varchar(200))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50)) 
--商品
DECLARE @ptypecategoryid VARCHAR(MAX)=''     --商品类别ID	
INSERT INTO #Ptype select typeid from F_ManPTypeInCategoryID(@OperatorID,@Ptypeid,@ptypecategoryid)
 
							

--往来单位
INSERT INTO #Btype select typeid from F_GetAllManagerBaseTypeId(@dealBtypeid,2,@OperatorID)


--职员
INSERT INTO #Etype select typeid from F_GetAllManagerBaseTypeId(@Etypeid,3,@OperatorID)

--仓库
INSERT INTO #Ktype select typeid from F_GetAllManagerBaseTypeId(@Ktypeid,4,@OperatorID)	

--部门
INSERT INTO #Dtype select typeid from F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)


--分支机构
INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@ReachQty NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),    
        @converunit VARCHAR(2000),
        @unitrate  VARCHAR(200)
IF @unitconvert=0
BEGIN
SELECT  @Qty='bi.Qty/r3.rate',
		@ReachQty='bi.ReachQty/r3.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','3,1','3'),
		@unitrate='r3.rate',
		@converunit='u3.fullname'
		
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='bi.Qty/r2.rate',
		@ReachQty='bi.ReachQty/r2.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','2,1','2'),
		@unitrate='r2.rate',
		@converunit='u2.fullname'
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='bi.Qty/r4.rate',
		@ReachQty='bi.ReachQty/r4.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','4,1','4'),
		@unitrate='r4.rate',
		@converunit='u4.fullname'
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='bi.Qty',
		@ReachQty='bi.ReachQty',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','1','1'),
		@unitrate='r1.rate',
		@converunit='u1.fullname'
END
----------多单位计算End---------



create table #result
(
	dealbtypeid			varchar(100),
	etypeid			varchar(100),
	ptypeid			varchar(100),
	ktypeid			varchar(100),
	unit1			varchar(50),
	unit2			varchar(50),
	unitrate1		 NUMERIC(24, 10) ,
	qty				 NUMERIC(24, 10) ,
	total			 NUMERIC(24, 10) ,
	taxtotal		 NUMERIC(24, 10) ,
	reachqty		 NUMERIC(24, 10) ,
	reachtotal		 NUMERIC(24, 10) ,
	reachtaxtotal	 NUMERIC(24, 10) ,
	notqty			 NUMERIC(24, 10) ,
	nottotal		 NUMERIC(24, 10) ,
	nottaxtotal		 NUMERIC(24, 10) ,
	orderqty		 NUMERIC(24, 10) ,
	ordertotal		 NUMERIC(24, 10) ,
	ordertaxtotal	 NUMERIC(24, 10) ,
	overqty			 NUMERIC(24, 10) ,
	overtotal		 NUMERIC(24, 10) ,
	overtaxtotal	 NUMERIC(24, 10) ,
	customertotal	 NUMERIC(24, 10) ,
	billover		 INT,
	usercode         varchar(200),
	fullname		 varchar(200),
	type			 varchar(200),
	standard		 varchar(200)
)

declare @sql varchar(max)
declare @sqlwhre varchar(1000)
set @sqlwhre=''
IF @IncludeStop=0 
	set @sqlwhre=' and bi.billover=0 '
set @sql='
		insert into #result
		(
			dealbtypeid	,
			etypeid	,
			ptypeid,
			ktypeid	,
			unit1,
			unit2,
			unitrate1,
			qty,
			total,
			taxtotal,
			reachqty,
			reachtotal,
			reachtaxtotal,
			notqty,
			nottotal,
			nottaxtotal,
			orderqty,
			ordertotal,
			ordertaxtotal,
			overqty,
			overtotal,
			overtaxtotal,
			customertotal,
			billover,
			usercode,
			fullname,
			type,	
			standard 
		)
		select	a.dealbtypeid,
				a.etypeid,
				a.ptypeid,
				a.KTypeID,
				a.unit1,
				a.unit2,
				a.unitrate1,
				a.qty,
				a.total,
				a.TaxTotal,
				a.ReachQty,
				a.ReachTotal,
				a.ReachTaxTotal, 
				CASE WHEN a.billover = 0 THEN --中止的明细，未发货设为0
					isnull(a.qty-isnull(a.ReachQty,0),0)
				ELSE 
					0
				END as notqty,
				isnull(a.Total-isnull(a.ReachTotal,0),0) as nottotal,
				isnull(a.TaxTotal-isnull(a.ReachTaxTotal,0),0) as nottaxtotal,
				a.ReachQty-a.qty as orderqty,
				a.ReachTotal-a.total as ordertotal,
				a.ReachTaxTotal-a.TaxTotal as ordertaxtotal, '
IF @IncludeStop=0
	set @sql=@sql+'	null as overqty,
					null as overtotal,
					null as overtaxtotal, '
ELSE
	set @sql=@sql+'	case when a.BillOver =1 
						then isnull(a.qty,0)-isnull(a.ReachQty,0)
					 else null
				end as overqty,
				case when a.BillOver =1 
						then isnull(a.total,0)-isnull(a.ReachTotal,0)
					 else null
				end as overtotal,
				case when a.BillOver =1 
						then isnull(a.TaxTotal,0)-isnull(a.ReachTaxTotal,0)
					 else null
				end as overtaxtotal, '
SET @sql=@sql+'			
				a.CustomerTotal,
				a.billover,
				a.usercode,
				a.fullname,
				a.type,
				a.standard
		 from
			(--订单
			select	o.dealbtypeid,
					o.etypeid,
					bi.ptypeid,
					bi.KTypeID,
					u1.fullname as unit1,
					'+@converunit+' as unit2,
					'+@unitrate+' as unitrate1,
				 	'+@Qty+' as qty,
					bi.Total,
					bi.TaxTotal,
					'+@ReachQty+'  as reachqty,
					bi.ReachTotal,
					bi.ReachTaxTotal, 
					o.billNumberId,
					bi.billover,
					o.customertotal,
					p1.usercode,
					p1.fullname,
					p1.type,
					p1.standard
			from OrderIndex o 
			inner join PT_Combin_OrderBill bi on o.billNumberId=bi.billNumberID 	 
			inner join ptype p1 on bi.ptypeid=  p1.typeid
	' +@tmptab
	Set @sql=@sql+' inner join #stype s on s.typeid = o.stypeid '
	Set @sql=@sql+' inner join #btype b on ( b.typeid = o.dealbtypeid  ) '
	Set @sql=@sql+' inner join #etype e on ( e.typeid = o.etypeid  ) '
	Set @sql=@sql+' inner join #ktype k on ( k.typeid = bi.ktypeid ) '
	Set @sql=@sql+' inner join #dtype d on (d.typeid = o.dtypeid ) '
	Set @sql=@sql+' inner join #ptype p on p.typeid = bi.ptypeid '


	Set @sql=@sql+'	where o.billtype=313 and o.billdate<='''+@EndDate+''' and o.billdate>='''+@StartDate+''' '+@sqlwhre+'
			) a'


exec(@sql)
  
DECLARE  @typeid VARCHAR(50)
SET @typeid = ' R.ptypeid '
SET @sql = '
		select	'+@typeid+','

	SET @sql += '	R.unit1, R.unit2, R.unitrate1, '

			
SET @sql += '
				sum(cast(0 as  NUMERIC(24, 10) )) as price,
				sum(R.qty) as qty,
				sum(R.total) as total,
				sum(R.taxtotal) as taxtotal,
				sum(cast(0 as  NUMERIC(24, 10) )) as reachprice,
				sum(R.reachqty) as reachqty,
				sum(R.reachtotal) as reachtotal,
				sum(R.reachtaxtotal) as reachtaxtotal,
				sum(case when R.notqty<=0 or R.billover=1
					then null 
					else R.notqty  
				end ) as notqty,
				sum(case when R.notqty<=0 or R.billover=1
					then  null
					else R.nottotal
				end ) as nottotal,
				sum(case when R.notqty<=0 or R.billover=1
					then  null
					else R.nottaxtotal
				end ) as nottaxtotal,
				sum(case when R.notqty>=0 
					then null 
					else R.orderqty  
				end) as orderqty,
				sum(case when R.notqty>=0 
					then  null
					else R.ordertotal
				end) as ordertotal,
				sum(case when R.notqty>=0 
					then  null
					else R.ordertaxtotal
				end) as ordertaxtotal,
				sum(case when R.orderqty>0 then null 
					else R.overqty 
					end) as overqty,
				sum(case when R.ordertotal>0 then null 
					else R.overtotal 
					end) as overtotal,
				sum(case when R.ordertaxtotal>0 then null 
					else R.overtaxtotal 
					end) as overtaxtotal,
				sum(R.customertotal) as customertotal,
				sum(cast(0 as  NUMERIC(24, 10) )) as notprice,
				sum(cast(0 as  NUMERIC(24, 10) )) as orderprice,
				sum(cast(0 as  NUMERIC(24, 10) )) as overprice,
				sum(R.billover) as billover, 
				R.usercode,
				R.fullname,
				R.type,
				R.standard
				
		from #result R
		INNER JOIN ptype P ON P.typeId = R.ptypeid 
		GROUP BY R.ptypeid,R.unit1,R.unit2,R.unitrate1,R.usercode,
				R.fullname,
				R.type,	
				R.standard
' 
EXEC(@sql)

drop table #Ptype, #Btype ,#Etype ,#Ktype ,#Dtype , #Stype, #result

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CombinationStatTypeDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CombinationStatTypeDetailQuery]
GO

/*
	作者：魏伟      
	日期：2016-07-01
	描述：组合品销售统计明细表查询
*/
CREATE PROCEDURE [dbo].[Web_CombinationStatTypeDetailQuery]
( 
	@startdate		    varchar(30),		--  1、查询起始时间
	@enddate			varchar(30),		--  2、查询结束时间
	@parid		        varchar(1550),		--  3、当前双击选择的主信息类别查询范围父节点 ID
	@ptypeid			varchar(MAX),		--  4、树型表或线性表商品类别查询范围父节点 ID
	@btypeid			varchar(MAX),		--  5、树型表或线性表结算单位类别查询范围父节点 ID
	@dealbtypeid		varchar(MAX),		--  6、树型表或线性表往来单位类别查询范围父节点 ID
	@etypeid			varchar(MAX),		--  7、树型表或线性表职员类别查询范围父节点 ID
	@KTypeID			varchar(MAX),		--  8、树型表或线性表仓库类别查询范围父节点 ID
	@sortfield			varchar(25),		--  9、明细表排序方式
	@checkCode		    varchar(2000) = '',	-- 10、制单人编号
	@checkName		    varchar(2000) = '',	-- 11、制单人名称
	@intPageNo			int		= '',		-- 12、当前查询的页码
	@intPageSize		int		= '',		-- 13、每页的显示记录数
	@chvOperatorID		varchar(50),		-- 14、操作员 ID ( 作权限范围检查用 )
	@chkDx				char(1) ='0',   	-- 18. 部分仓库时是否显示代销数据
	@chkPf				char(1) ='0',   	-- 19. 是否显示价保、返利数据
	@chkRed				char(1) ='0',   	-- 19. 是否显示红冲单据
	@billType		    varchar(200),       -- 20. 单据类型
	@dtypeid        	varchar(MAX)='',
	@atypeid	    	varchar(MAX)='',
	@chrFlag			char(1),			-- 21、功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@PageNo 			int=1,
	@PriceMode			int=1,				-- 价格方式
	@Stypeid            varchar(MAX),		-- 22、分支机构查询范围父节点 ID
	@Explain			VARCHAR(MAX)='', --说明
	@Comment			VARCHAR(MAX)='',  --摘要
	@ptypeproperty      NVARCHAR(10) ,               --是否服务类商品
	@waybillcode     varchar(20)='',     --运单号
	@TEL             varchar(100)='',    --承运单位
	@goodsnumber     varchar(20)='',     --物件数量
	@packway         varchar(20)='',     --包装方式
	@bzcomment       varchar(250)=''     --备注
	
)
--@encode$--

AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
 --SELECT @ptypeid = @parid 

 

--=============================================临时表创建及赋值【BEGIN】=========================================
--商品
CREATE TABLE #PType (TypeID VARCHAR(200),EntryCode	VARCHAR(200),PrePrice  NUMERIC(24, 10) )
CREATE NONCLUSTERED INDEX CIX_PType_Typeid ON #PType(TypeID)

DECLARE @ptypecategoryid VARCHAR(MAX)    --商品类别ID
SET @ptypecategoryid=''

INSERT INTO #Ptype(TypeID,EntryCode) 
SELECT f.TypeId,p.entrycode
FROM F_ManPTypeInCategoryID ( @chvOperatorID,@ptypeid,@ptypecategoryid) f
INNER JOIN ptype p ON p.typeid=f.typeid

IF(ISNULL(@ptypeid,'')<>'')
BEGIN
	INSERT INTO #Ptype(TypeID,EntryCode) 
	SELECT DISTINCT p.typeId,p.EntryCode FROM dbo.CombinationProductDetail d
	LEFT JOIN 
	(
		SELECT	CombinationProductID 
		FROM	dbo.CombinationProductIndex 		
		WHERE	CombinationProductPtypeId IN (SELECT TypeID FROM #PType)
	) i ON i.CombinationProductID=d.CombinationProductID
	INNER JOIN dbo.ptype p ON p.typeId=d.Ptypeid
END

DECLARE @unitsql  VARCHAR(500)
SELECT @unitsql=dbo.F_GetPtypeUnitsAndRates('p1','1,5','1')


IF @PriceMode<>'0' -- 增加预设售价
BEGIN
	IF @PriceMode<=10
	BEGIN	
		EXEC('UPDATE #Ptype SET PrePrice =p.PreSalePrice'+@PriceMode+'
		FROM Ptype_Price p INNER JOIN #Ptype p1
		on p.ptypeid=p1.typeid')
	END
	ELSE 
	BEGIN	
		IF @PriceMode<=15
		BEGIN
			SELECT @PriceMode=CAST(CAST(@PriceMode AS INT)-10 AS VARCHAR(1))
			EXEC('UPDATE #Ptype SET PrePrice =p.PreBuyPrice'+@PriceMode+'
			FROM Ptype_Price p INNER JOIN #Ptype p1
			on p.ptypeid=p1.typeid')
		END
		ELSE IF @PriceMode=16 
		BEGIN
			EXEC('UPDATE #Ptype SET PrePrice =p.TopSalePrice
			FROM Ptype_Price p INNER JOIN #Ptype p1
			on p.ptypeid=p1.typeid')
		END
		ELSE IF @PriceMode=17
		BEGIN
			EXEC('UPDATE #Ptype SET PrePrice =p.LowSalePrice
			FROM Ptype_Price p INNER JOIN #Ptype p1
			on p.ptypeid=p1.typeid')
		END
		ELSE IF @PriceMode=18
		BEGIN
			EXEC('UPDATE #Ptype SET PrePrice =p.RetailPrice
			FROM Ptype_Price p INNER JOIN #Ptype p1
			on p.ptypeid=p1.typeid')
		END 
		ELSE IF @PriceMode=19
		BEGIN
			EXEC('UPDATE #Ptype SET PrePrice =p.TopBuyPrice
			FROM Ptype_Price p INNER JOIN #Ptype p1
			on p.ptypeid=p1.typeid')
		END
	END
END

--结算单位
CREATE TABLE #Btype (TypeID VARCHAR(50))
CREATE NONCLUSTERED INDEX CIX_BType_Typeid ON #BType(TypeID)

INSERT INTO #Btype(TypeID) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@btypeid,2,@chvOperatorID)

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50))
CREATE NONCLUSTERED INDEX CIX_DealBtype_Typeid ON #DealBtype(TypeID)

INSERT INTO #DealBtype(TypeID) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID) 
--职员
IF @etypeid='00000'  SET @etypeid='' 
CREATE TABLE #Etype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_EType_Typeid ON #EType(TypeID)

INSERT INTO #Etype(TypeID) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@etypeid,3,@chvOperatorID)

--仓库
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_KType_Typeid ON #KType(TypeID)

INSERT INTO #Ktype(TypeID) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@KTypeID,4,@chvOperatorID)
IF (@KTypeID='10000' OR  @KTypeID='' OR  @KTypeID='00000' OR @chkDx='1') AND NOT EXISTS(select TOP 1 TypeID from #Ktype where typeid='10000') 
	INSERT INTO #Ktype select typeid from F_LineK(@chvOperatorID)

--部门
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_DType_Typeid ON #DType(TypeID)

IF ISNULL(@dtypeid,'')='' OR @dtypeid='00000'
BEGIN
    INSERT INTO #Dtype select '' -- 其他部门
END
INSERT INTO #Dtype select typeid  from F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)

IF NOT EXISTS(select * from #Dtype where typeid='')
	IF Charindex('99999',@dtypeid)>0
		INSERT INTO #Dtype select '' -- 其他部门

--地区	
CREATE TABLE #Atype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_AType_Typeid ON #AType(TypeID)

IF ISNULL(@atypeid,'')='' OR @atypeid='00000'
BEGIN
	INSERT INTO #Atype select typeid from AreaType where Sonnum =0 and deleted =0
	INSERT INTO #Atype select '' --其他地区
END
ELSE
	INSERT INTO #Atype 
	SELECT typeId 
	FROM AreaType A 
	INNER JOIN dbo.f_split(@atypeid,',') B ON A.typeId LIKE B.a +'%'

--分支机构
CREATE TABLE #Stype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_SType_Typeid ON #SType(TypeID)

IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
    INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@chvOperatorID)

CREATE TABLE #BillType(BillType VARCHAR(200))
CREATE NONCLUSTERED INDEX CIX_BillType_Typeid ON #BillType(BillType)

INSERT INTO #BillType(BillType) SELECT a as Billtype FROM dbo.f_split(@billType,',')
 
 --备注
 CREATE TABLE #Comment(BillNumberId NUMERIC(10,0),BillType INT)
 CREATE NONCLUSTERED INDEX CIX_Comment_BillNumberId ON #Comment(BillNumberId)
 
 IF LTRIM(RTRIM(@bzcomment))<>''
 BEGIN
	 INSERT INTO #Comment(BillNumberId,BillType)
	 SELECT BillNumberId,46 BillType FROM dbo.PT_Combin_SaleBackBill WHERE comment LIKE '%'+@bzcomment+'%'
	 UNION ALL 
	 SELECT BillNumberId,12 BillType FROM dbo.PT_Combin_SaleBill WHERE comment LIKE '%'+@bzcomment+'%'
	 UNION ALL 
	 SELECT BillNumberId,305 BillType FROM dbo.RetailCombinationBill WHERE comment LIKE '%'+@bzcomment+'%'
END
	
--=============================================临时表创建及赋值【END】=========================================

DECLARE 
	@SQL VARCHAR(MAX)='',
	@SQL2 VARCHAR(MAX)='',
	@SqlWhere  VARCHAR(MAX)='',
	@SqlWhere1	VARCHAR(MAX)=''
	
--============================================= where 查询条件【BEGIN】============================================= 
SET @SqlWhere+=' AND b.ifYearBill=''0'' ' +CHAR(13)--年节存标志

IF ( ISDATE(RTRIM(@startdate)) = 1 )--查询时间段
	SET @SqlWhere+= ' AND b.BillDate >= ''' + @startdate + ''''+CHAR(13)

IF ( ISDATE(RTRIM(@enddate)) = 1 )
	SET @SqlWhere+= ' AND b.BillDate <= ''' + @enddate + ''''+CHAR(13)
		
IF @chkRed ='0'--是否为红单
	SET @SqlWhere +=' AND b.Redword=0'+CHAR(13)

IF(@Explain <> '')--说明
	SET @SqlWhere+=' AND  b.Explain like ''%' + @Explain + '%'' '+CHAR(13)
	
IF(@Comment <> '')--摘要筛选
	SET @SqlWhere+=' AND  b.Comment like ''%' + @Comment + '%'' '+CHAR(13)

IF @checkCode <> '' OR @checkName <> ''-- 筛选制单人 
	 SET @SqlWhere+= @checkCode + @checkName+CHAR(13)
IF(@waybillcode <> '')--运单号
	SET @SqlWhere+=' AND  b.waybillcode = '''+ @waybillcode +''' '+CHAR(13)	                   
IF(@TEL <> '')--承运单位
	SET @SqlWhere+=' AND  b.TEL = '''+ @TEL +''' '+CHAR(13)                                    
IF(@goodsnumber <> '')--物件数量
	SET @SqlWhere+=' AND  b.goodsnumber = '''+ @goodsnumber +''' '+CHAR(13)  
IF(@packway <> '')--包装方式
	SET @SqlWhere+=' AND  b.packway = '''+ @packway +''' '+CHAR(13)   

IF ( ISDATE(RTRIM(@startdate)) = 1 )--查询时间段
	SET @SqlWhere1+= ' AND b.BillDate >= ''' + @startdate + ''''+CHAR(13)

IF ( ISDATE(RTRIM(@enddate)) = 1 )
	SET @SqlWhere1+= ' AND b.BillDate <= ''' + @enddate + ''''+CHAR(13)
		
IF @chkRed ='0'--是否为红单
	SET @SqlWhere1 +=' AND b.Redword=0'+CHAR(13)

IF(@Explain <> '')--说明
	SET @SqlWhere1+=' AND  b.Explain like ''%' + @Explain + '%'' '+CHAR(13)
	
IF(@Comment <> '')--摘要筛选
	SET @SqlWhere1+=' AND  b.Comment like ''%' + @Comment + '%'' '+CHAR(13)
	
SET @SqlWhere1+=' AND b.ifYearBill=''0'' ' +CHAR(13)--年节存标志	

IF @checkCode <> '' OR @checkName <> ''-- 筛选制单人 
	 SET @SqlWhere1+= @checkCode + @checkName+CHAR(13)
	
--============================================= where 查询条件【END】============================================= 
CREATE TABLE #BillIndex
(
	BillNumberId NUMERIC(10,0),
	FullName	 VARCHAR(500),
	BillType	 NUMERIC(10,0),
	RedWord		 INT,
	CheckeName	 VARCHAR(500),
	STypeId		 VARCHAR(50),
	goodsnumber	 VARCHAR(100),
	KTypeId		 VARCHAR(50),
	DTypeId		 VARCHAR(50),
	DealBTypeID  VARCHAR(50),
	BTypeId		 VARCHAR(50),
	ETypeId		 VARCHAR(50)
)
CREATE NONCLUSTERED INDEX CIX_BillIndex_BillNumberId ON #BillIndex(BillNumberId,BillType)

SET @SQL+='
INSERT INTO #BillIndex(BillNumberId,FullName,BillType,RedWord,CheckeName,STypeId,goodsnumber,KTypeId,DTypeId,DealBTypeID,BTypeId,ETypeId)
SELECT	B.BillNumberId,
		AC.FullName,
		B.BillType,
		B.RedWord,
		C.FullName AS CheckeName,
		b.STypeId,
		b.goodsnumber,
		b.ktypeid,
		b.DTypeId,
		b.DealBTypeID,
		b.BTypeId,
		b.ETypeId
FROM	BillIndex B
INNER JOIN #Billtype t	ON b.Billtype=t.billtype '+CHAR(13)

IF NOT (ISNULL(@Stypeid,'') = '' AND @MStypeid = '00000')      	
	SET @SQL+='INNER JOIN #Stype S ON B.Stypeid=S.TypeID '+CHAR(13)
	
IF ISNULL(@dtypeid,'') NOT IN ('','00000') OR @MDTypeID=-99999 
	SET @SQL+='INNER JOIN #Dtype D ON B.DTypeId=D.TypeID'+CHAR(13)
	
IF ISNULL(@dealbtypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999 
	SET @SQL+='INNER JOIN #DealBtype B1 ON B.DealBTypeID=B1.TypeID'+CHAR(13)

IF ISNULL(@btypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQL+='INNER JOIN #Btype B2 ON B.btypeid=B2.TypeID'+CHAR(13)

IF ISNULL(@etypeid,'') NOT IN ('','00001') OR @METypeID=-99999 	
	SET @SQL+='INNER JOIN #Etype E ON B.etypeid=E.TypeID'+CHAR(13)

--筛选备注
IF ISNULL(@bzcomment,'')<>''	
	SET @SQL+='INNER JOIN #Comment MXB ON MXB.BillNumberId=B.BillNumberId AND MXB.BillType=B.BillType'+CHAR(13)
				
SET @SQL+='
INNER JOIN Ac_Currency AC ON AC.CID=B.CID
INNER JOIN Employee C ON B.Checke=C.TypeID
WHERE	B.Draft =0
		AND B.isini=0'+CHAR(13)+@SqlWhere
	
SET @SQL += '
UNION ALL 
SELECT	B.BillNumberId,
		AC.FullName,
		B.BillType,
		B.RedWord,
		C.FullName AS CheckeName,
		B.STypeId,
		'''' as goodsnumber,
		'''' as ktypeid,
		b.DTypeId,
		b.DealBTypeID,
		b.BTypeId,
		b.ETypeId 
FROM ReceiptBillIndex AS B
INNER JOIN #Billtype t	ON b.Billtype=t.billtype 
'
IF NOT (ISNULL(@Stypeid,'') = '' AND @MStypeid = '00000')      	
	SET @SQL+='INNER JOIN #Stype S ON B.Stypeid=S.TypeID '+CHAR(13)
	
IF ISNULL(@dtypeid,'') NOT IN ('','00000') OR @MDTypeID=-99999 
	SET @SQL+='INNER JOIN #Dtype D ON B.DTypeId=D.TypeID'+CHAR(13)
	
IF ISNULL(@dealbtypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQL+='INNER JOIN #DealBtype B1 ON B.DealBTypeID=B1.TypeID'+CHAR(13)

IF ISNULL(@btypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQL+='INNER JOIN #Btype B2 ON B.btypeid=B2.TypeID'+CHAR(13)

IF ISNULL(@etypeid,'') NOT IN ('','00001') OR @METypeID=-99999 	
	SET @SQL+='INNER JOIN #Etype E ON B.etypeid=E.TypeID'+CHAR(13)
--筛选备注
IF ISNULL(@bzcomment,'')<>''	
	SET @SQL+='INNER JOIN #Comment MXB ON MXB.BillNumberId=B.BillNumberId AND MXB.BillType=B.BillType'+CHAR(13)
		
SET @SQL+='
INNER JOIN Ac_Currency AC ON AC.CID=B.CID
INNER JOIN Employee C ON B.Checke=C.TypeID
WHERE	B.Draft =0
		AND B.isini=0'+CHAR(13)+@SqlWhere1
 
--PRINT @SQL
EXEC(@SQL)

CREATE TABLE #InOutStockTable
(
    billnumberid VARCHAR(200),
    billtype VARCHAR(50),
    id INT,
    PTypeID VARCHAR(200),
    ProduceDate VARCHAR(200),
    EntryCode VARCHAR(200),
    qty NUMERIC(24,10),
    nbrcqty NUMERIC(24,10),
    Price NUMERIC(24,10),
    nprice NUMERIC(24,10),
    Total NUMERIC(24,10),
    NTotal NUMERIC(24,10),
    TaxTotal NUMERIC(24,10),
    NTaxTotal NUMERIC(24,10),
    PrePrice NUMERIC(24,10),
    ktypeid VARCHAR(200),
    cargoid VARCHAR(200),
    NQty NUMERIC(24,10),
    itemname VARCHAR(200),
    GoodsNumber VARCHAR(200),
    munitid VARCHAR(200),
    billtypes VARCHAR(200),
    Comment VARCHAR(500),
    pindexid VARCHAR(100) -- 组合品表体关联ID
)
CREATE NONCLUSTERED INDEX cix_InOutStockTable_billnumberid ON #InOutStockTable(billnumberid)


DECLARE @SQLCondition VARCHAR(MAX)
SET @SQLCondition='
INSERT INTO #InOutStockTable
        ( 
          billnumberid,
          billtype,
          id ,
          PTypeID ,
          ProduceDate ,
          EntryCode,
          qty ,
          nbrcqty,
          Price ,
          nprice ,
          Total ,
          NTotal ,
          TaxTotal ,
          NTaxTotal ,
          PrePrice,
          ktypeid ,
          cargoid ,
          NQty ,
          itemname ,
          GoodsNumber ,
          munitid ,
          billtypes,
          Comment,
          pindexid
        )
        SELECT	  billnumberid,
				  billtype,
				  id ,
				  PTypeID ,
				  ProduceDate ,
				  EntryCode,
				  qty ,
				  nbrcqty,
				  Price ,
				  nprice ,
				  Total ,
				  NTotal ,
				  TaxTotal ,
				  NTaxTotal ,
				  PrePrice,
				  ktypeid ,
				  cargoid ,
				  NQty ,
				  itemname ,
				  GoodsNumber ,
				  munitid ,
				  billtypes,
				  Comment,
				  pindexid
		FROM(
				  SELECT  psb.BillNumberId,
						  B.billtype,
						  psb.ID,
						  psb.PtypeId,
						  '''' AS ProduceDate,
						  p.EntryCode,
						  CASE B.RedWord
							  WHEN 2 THEN psb.Qty
							  ELSE -psb.Qty END AS Qty,
						  psb.Mqty AS nbrcqty,
						  psb.SalePrice AS price,
						  psb.NSalePrice AS nprice,
						  CASE B.RedWord
							  WHEN 2 THEN psb.total
							  ELSE -psb.total END AS Total,
						  CASE B.RedWord
							  WHEN 2 THEN psb.NTotal
							  ELSE -psb.NTotal END AS NTotal,
						  CASE B.RedWord
							  WHEN 2 THEN psb.NTotal
							  ELSE -psb.TaxTotal END AS TaxTotal,
						  CASE B.RedWord
							  WHEN 2 THEN psb.NTaxTotal
							  ELSE -psb.NTaxTotal END AS NTaxTotal,
						  p.PrePrice,
						  psb.KTypeID,
						  psb.CargoID,
						  CASE B.RedWord
							  WHEN 2 THEN psb.NQty
							  ELSE -psb.NQty END AS NQty,
						  CASE WHEN psb.IsCombined = 0 THEN XW.FullName ELSE REPLACE(VW.FullName,''я'',''/'') END itemname,
						  b.goodsnumber,
						  psb.MUnitID,
						  n.Billtypes,
						  psb.comment,
						  psb.pindexid
          FROM	PT_Combin_SaleBackBill psb
          INNER JOIN #BillIndex b ON b.BillNumberId = psb.BillNumberId 
          INNER JOIN #PType p ON p.typeId=psb.PtypeId
          LEFT JOIN dbo.BillName n ON n.Billtype = b.BillType
          LEFT JOIN xw_SelfData XW ON XW._Id=psb.ItemId
          LEFT JOIN vWeb_ItemIDByIsCombined VW on VW.id=psb.ItemId AND VW.iscombined=1'
          
IF NOT (ISNULL(@Stypeid,'') = '' AND @MStypeid = '00000')      	
	SET @SQLCondition+='INNER JOIN #Stype S ON B.Stypeid=S.TypeID '+CHAR(13)
	
IF ISNULL(@dtypeid,'') NOT IN ('','00000') OR @MDTypeID=-99999 
	SET @SQLCondition+='INNER JOIN #Dtype D ON B.DTypeId=D.TypeID'+CHAR(13)
	
IF ISNULL(@dealbtypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQLCondition+='INNER JOIN #DealBtype B1 ON B.DealBTypeID=B1.TypeID'+CHAR(13)

IF ISNULL(@btypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQLCondition+='INNER JOIN #Btype B2 ON B.btypeid=B2.TypeID'+CHAR(13)

IF ISNULL(@etypeid,'') NOT IN ('','00001') OR @METypeID=-99999 	
	SET @SQLCondition+='INNER JOIN #Etype E ON B.etypeid=E.TypeID'+CHAR(13)

IF ISNULL(@atypeid,'') NOT IN ('','00000') OR @MAtypeID=-99999 	
	SET @SQLCondition+='INNER JOIN (SELECT btypeid FROM BillIndex BI 
	                                INNER JOIN btype B ON B.typeid=BI.btypeid
	                                INNER JOIN #Atype AT ON B.AreaTypeId=AT.typeid ) T ON T.btypeid=B.btypeid'+CHAR(13)
	
	
SET @SQLCondition=@SQLCondition+ 'UNION ALL
          SELECT  ps.BillNumberId,
				  B.billtype,
				  ps.ID,
				  ps.PtypeId,
				  '''' AS ProduceDate,
				  p.EntryCode,
				  CASE b.RedWord
					  WHEN 2 THEN -ps.Qty
					  ELSE ps.Qty END AS Qty,
				  ps.mqty AS nbrcqty,
				  ps.SalePrice AS price,
				  ps.NSalePrice AS nprice,
				  CASE b.Redword
					  WHEN 2 THEN -ps.total
					  ELSE ps.total END AS Total,
				  CASE b.Redword
					  WHEN 2 THEN -ps.NTotal
					  ELSE ps.NTotal END AS NTotal,
				  CASE b.Redword
					  WHEN 2 THEN -ps.TaxTotal
					  ELSE ps.TaxTotal END AS TaxTotal,
				  CASE b.Redword
					  WHEN 2 THEN -ps.NTaxTotal
					  ELSE ps.NTaxTotal END AS NTaxTotal,
				  p.PrePrice,
				  ps.KTypeID,
				  ps.CargoID,
				  CASE b.RedWord
					  WHEN 2 THEN -ps.NQty
					  ELSE ps.NQty END AS NQty,
				  CASE WHEN ps.IsCombined = 0 THEN XW.FullName ELSE REPLACE(VW.FullName,''я'',''/'') END itemname,
				  b.goodsnumber,
				  ps.MUnitID,
				  n.Billtypes,
				  ps.Comment,
				  ps.pindexid
          FROM PT_Combin_SaleBill ps
          LEFT JOIN #BillIndex b ON b.BillNumberId = ps.BillNumberId
          INNER JOIN #PType p ON p.typeId=ps.PtypeId
          LEFT JOIN dbo.BillName n ON n.Billtype = b.BillType
          LEFT JOIN xw_SelfData XW ON XW._Id=ps.ItemId
          LEFT JOIN vWeb_ItemIDByIsCombined VW on VW.id=ps.ItemId AND VW.iscombined=1'
          
IF NOT (ISNULL(@Stypeid,'') = '' AND @MStypeid = '00000')      	
	SET @SQLCondition+='INNER JOIN #Stype S ON B.Stypeid=S.TypeID '+CHAR(13)
	
IF ISNULL(@dtypeid,'') NOT IN ('','00000') OR @MDTypeID=-99999 
	SET @SQLCondition+='INNER JOIN #Dtype D ON B.DTypeId=D.TypeID'+CHAR(13)
	
IF ISNULL(@dealbtypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQLCondition+='INNER JOIN #DealBtype B1 ON B.DealBTypeID=B1.TypeID'+CHAR(13)

IF ISNULL(@btypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQLCondition+='INNER JOIN #Btype B2 ON B.btypeid=B2.TypeID'+CHAR(13)

IF ISNULL(@etypeid,'') NOT IN ('','00001') OR @METypeID=-99999 	
	SET @SQLCondition+='INNER JOIN #Etype E ON B.etypeid=E.TypeID'+CHAR(13)      
	
IF ISNULL(@atypeid,'') NOT IN ('','00000') OR @MAtypeID=-99999 	
	SET @SQLCondition+='INNER JOIN (SELECT btypeid FROM BillIndex BI 
	                                INNER JOIN btype B ON B.typeid=BI.btypeid
	                                INNER JOIN #Atype AT ON B.AreaTypeId=AT.typeid ) T ON T.btypeid=B.btypeid'+CHAR(13)
	    
SET @SQLCondition=@SQLCondition+ 'UNION ALL
          SELECT  r.BillNumberId,
				  B.billtype,
				  r.ID,
				  r.PtypeId,
				  '''' AS ProduceDate,
				  p.EntryCode,
				  CASE b.RedWord
					  WHEN 2 THEN -r.Qty
					  ELSE r.Qty END AS Qty,
				  r.mqty AS nbrcqty,
				  r.SalePrice AS price,
				  r.NSalePrice AS nprice,
				  CASE b.Redword
					  WHEN 2 THEN -r.total
					  ELSE r.total END AS Total,
				  CASE b.Redword
					  WHEN 2 THEN -r.NTotal
					  ELSE r.NTotal END AS NTotal,
				  CASE b.Redword
					  WHEN 2 THEN -r.TaxTotal
					  ELSE r.TaxTotal END AS TaxTotal,
				  CASE b.Redword
					  WHEN 2 THEN -r.NTaxTotal
					  ELSE r.NTaxTotal END AS NTaxTotal,
				  p.PrePrice,
				  b.KTypeID,
				  r.CargoID,
				  CASE b.RedWord
					  WHEN 2 THEN -r.NQty
					  ELSE r.NQty END AS NQty,
				  CASE WHEN r.IsCombined = 0 THEN XW.FullName ELSE REPLACE(VW.FullName,''я'',''/'') END itemname,
				  b.goodsnumber,
				  r.MUnitID,
				  n.Billtypes,
				  r.Comment,
				  r.pindexid
          FROM RetailCombinationBill r
          LEFT JOIN #BillIndex b ON b.BillNumberId = r.BillNumberId 
          INNER JOIN #PType p ON p.typeId=r.PtypeId
          LEFT JOIN dbo.BillName n ON n.Billtype = b.BillType
          LEFT JOIN xw_SelfData XW ON XW._Id=r.ItemId
          LEFT JOIN vWeb_ItemIDByIsCombined VW on VW.id=r.ItemId AND VW.iscombined=1'
          
IF NOT (ISNULL(@Stypeid,'') = '' AND @MStypeid = '00000')      	
	SET @SQLCondition+='INNER JOIN #Stype S ON B.Stypeid=S.TypeID '+CHAR(13)
	
IF ISNULL(@dtypeid,'') NOT IN ('','00000') OR @MDTypeID=-99999 
	SET @SQLCondition+='INNER JOIN #Dtype D ON B.DTypeId=D.TypeID'+CHAR(13)
	
IF ISNULL(@dealbtypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQLCondition+='INNER JOIN #DealBtype B1 ON B.DealBTypeID=B1.TypeID'+CHAR(13)

IF ISNULL(@btypeid,'') NOT IN ('','00000') OR @MBTypeID=-99999 OR @MBTypeID2=-99999  
	SET @SQLCondition+='INNER JOIN #Btype B2 ON B.btypeid=B2.TypeID'+CHAR(13)

IF ISNULL(@etypeid,'') NOT IN ('','00001') OR @METypeID=-99999 	
	SET @SQLCondition+='INNER JOIN #Etype E ON B.etypeid=E.TypeID'+CHAR(13)

IF ISNULL(@atypeid,'') NOT IN ('','00000') OR @MAtypeID=-99999 	
	SET @SQLCondition+='INNER JOIN (SELECT btypeid FROM BillIndex BI 
	                                INNER JOIN btype B ON B.typeid=BI.btypeid
	                                INNER JOIN #Atype AT ON B.AreaTypeId=AT.typeid ) T ON T.btypeid=B.btypeid'+CHAR(13)
	
SET @SQLCondition=@SQLCondition+ '
          ) AS T   ' 


--print(@SQLCondition)
EXEC(@SQLCondition)

CREATE TABLE #Money
(
    Id			numeric(18,0),
    sharefee	NUMERIC(24,10),
    CostTotal	NUMERIC(24,10),
    pindexid	VARCHAR(100) --组合品表体关联ID
)
CREATE NONCLUSTERED INDEX cix_Money_id ON #Money(Id)



SET @SQL = '
INSERT INTO #Money(Id,sharefee,CostTotal,pindexid)
SELECT Id,sharefee,CostTotal,pindexid
FROM(
		SELECT	DISTINCT
				a.BillNumberId as Id,
				case bi.redword
					when 2 then s.sharefee
					else -s.sharefee end as sharefee,'+CHAR(13)	

SET @SQL+='s.CostTotal as CostTotal'+CHAR(13)	
SET @SQL +=',s.pindexid
FROM #BillIndex B
INNER JOIN InOutStockTable a ON a.BillNumberID = B.BillNumberID AND B.BillType = A.BillType
INNER JOIN BillName bn on bn.BillType= a.BillType
INNER JOIN #PType P ON a.PTypeId = P.TypeId
inner join BillIndex bi on b.billnumberid = bi.billnumberid
inner join (SELECT 
a.PtypeId,
SUM(ISNULL(A.ShareFee,0)) AS sharefee, '
if @PriceMode=0
SET @SQL +='
-Convert( NUMERIC(24, 10) ,(a.CostTotal))  AS CostTotal,'
ELSE  SET @SQL +=' -sum(Convert( NUMERIC(24, 10) ,(a.Qty)*p.PrePrice )) AS CostTotal,'
SET @SQL+='
                a.BillNumberId,
                a.BillType,
                PD.pindexid
                FROM 
    InOutStockTable a
    INNER JOIN #Ptype p ON a.PtypeId=p.Typeid 
    INNER JOIN (
		SELECT ptypeid FROM dbo.CombinationProductDetail d INNER JOIN dbo.CombinationProductIndex i ON 
			d.CombinationProductID=i.CombinationProductID
    ) AS COM ON p.Typeid =COM.ptypeid
    INNER JOIN ( SELECT  ID ,
                                        BillnumberID ,
                                        pindexid
                                FROM    PT_Combin_SaleBillDetail
                                UNION ALL
                                SELECT  ID ,
                                        BillnumberID ,
                                        pindexid
                                FROM    PT_Combin_SaleBackBillDetail
                                UNION ALL
                                SELECT  ID ,
                                        BillnumberID ,
                                        pindexid
                                FROM    RetailBill
                              ) AS PD ON PD.BillnumberID = A.BillnumberID
                                         AND PD.ID = A.ID
    GROUP BY  A.BillnumberID,A.PtypeId,CostTotal,a.Qty,p.preprice,a.BillType,PD.pindexid) s on s.BillNumberID = B.BillNumberID AND s.PtypeId=a.Ptypeid
LEFT JOIN xw_SelfData XW ON XW._Id=A.ItemId
LEFT JOIN vWeb_ItemIDByIsCombined VW on VW.id=a.ItemId AND VW.iscombined=1
'
IF ISNULL(@KTypeID,'') NOT IN ('','00000') OR @MKTypeID=-99999 
	SET @SQL+='	INNER JOIN #ktype k ON a.ktypeid=k.TypeId '+CHAR(13)
SET @SQL +='
	WHERE A.BillType NOT IN(402,403,405)
' 
SET @SQL +=' ) AS A'

EXEC(@SQL)

CREATE TABLE #MoneyTemp
(
    Id			numeric(18,0),
    sharefee NUMERIC(24,10),
    CostTotal NUMERIC(24,10),
    pindexid VARCHAR(100) --组合品表体关联ID
)
CREATE NONCLUSTERED INDEX cix_MoneyTemp_id ON #MoneyTemp(Id)

INSERT INTO #MoneyTemp
SELECT Id,SUM(ShareFee) AS ShareFee,SUM(CostTotal) CostTotal,pindexid FROM #Money GROUP BY Id,pindexid

SET @SQL='
        SELECT	  a.id AS CustomdetailID,
				  PTypeID ,
				  ProduceDate ,
				  EntryCode,
				  Qty ,
				  nbrcqty,
				  Price ,
				  nprice ,
				  Total AS _Total ,
				  NTotal AS _NTotal,
				  TaxTotal ,
				  NTaxTotal ,
				  m.sharefee,
				  m.CostTotal,
				  PrePrice,
				  --ktypeid ,
				  cargoid ,
				  NQty ,
				  itemname ,
				  --GoodsNumber ,
				  munitid ,
				  Billtypes,
				  B.*,
				  Comment
          FROM #InOutStockTable a 
          LEFT JOIN #BillIndex B ON a.billnumberid=b.BillNumberId
          LEFT JOIN #MoneyTemp m ON a.billnumberid=m.Id AND M.PINDEXID = A.PINDEXID'
          
IF ISNULL(@KTypeID,'') NOT IN ('','00000') OR @MKTypeID=-99999 
	SET @SQL+='	INNER JOIN #ktype k ON a.ktypeid=k.TypeId '+CHAR(13)               

SET @SQL +='

--发出商品出库单
UNION ALL 
SELECT  a.id AS CustomdetailID,
		a.PTypeID,
		a.ProduceDate,
		P.entrycode,
		CASE T.RedWord
			WHEN 2 THEN -(a.qty - a.InvoiceQty)
			ELSE a.qty - a.InvoiceQty
		END AS Qty,
		a.MQty  AS nbrcqty,--换算率变更前销售单位数量
		a.DiscountPrice AS Price,
		a.NDiscountPrice as NPrice,

		CASE T.RedWord
			WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.qty - a.InvoiceQty) * a.DiscountPrice) END
			ELSE CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.qty - a.InvoiceQty) * a.DiscountPrice END
		END AS _Total,

		CASE T.RedWord
			WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice) END
			ELSE CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
		END AS _NTotal,

		CASE T.RedWord
			WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.qty - a.InvoiceQty) * a.TaxPrice) END
			ELSE CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.qty - a.InvoiceQty) * a.TaxPrice END
		END AS TaxTotal,

		CASE T.RedWord
			WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.NTaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
			ELSE CASE a.InvoiceQty WHEN 0 THEN a.NTaxTotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
		END AS NTaxTotal,

		CASE T.RedWord
			WHEN 2 THEN -s.sharefee
			ELSE s.sharefee
		END AS sharefee,'+CHAR(13)

		SET @SQL+='s.CostTotal as CostTotal,' +CHAR(13)
		SET @SQL+='
		P.PrePrice,
		--a.ktypeid,
		a.cargoid,
		CASE T.RedWord
			WHEN 2 THEN -(a.NQty - a.InvoiceNQty)
			ELSE a.NQty - a.InvoiceNQty
		END AS nqty,
		CASE 
			WHEN a.IsCombined = 0 THEN XW.FullName 
			ELSE REPLACE(VW.FullName,''я'',''/'') 
		END AS itemname,
		--a.GoodsNumber,
		a.munitid,
		bn.Billtypes,
		B.*,
		a.Comment
FROM SendBill AS A
INNER JOIN BillIndex AS T ON(A.BillNumberID = T.BillNumberID)
INNER JOIN #BillIndex AS B ON(T.BillNumberID = B.BillNumberID AND T.billtype = B.billtype)
INNER JOIN BillName bn on bn.BillType= T.BillType
INNER JOIN #PType P ON a.PTypeId = P.TypeId
inner join (SELECT a.ID,
SUM(ISNULL(ShareFee,0)) AS sharefee, '
IF @PriceMode = 0
SET @SQL+=' 
    SUM(Convert( NUMERIC(24, 10) ,CASE T.RedWord
						WHEN 2 THEN -(a.CostTotal - a.InvoiceCostTotal)
						ELSE (a.CostTotal - a.InvoiceCostTotal)
						END))  as CostTotal'
ELSE
SET @SQL+='
		SUM(Convert( NUMERIC(24, 10) ,CASE T.RedWord
						WHEN 2 THEN -((a.qty - a.InvoiceQty)*p.PrePrice)
						ELSE (a.qty - a.InvoiceQty)*p.PrePrice
						END)) as CostTotal'
SET @SQL+='
			   
                FROM  SendBill a
 INNER JOIN BillIndex AS T ON(A.BillNumberID = T.BillNumberID)
 INNER JOIN #Ptype p ON a.PtypeId=p.Typeid 
WHERE a.PtypeId IN( 
SELECT ptypeid FROM dbo.CombinationProductDetail d INNER JOIN dbo.CombinationProductIndex i ON d.CombinationProductID=i.CombinationProductID) 
GROUP BY t.RedWord,a.CostTotal,a.InvoiceCostTotal,a.ID) s ON a.ID=s.ID
LEFT JOIN xw_SelfData XW ON XW._Id=A.ItemId
LEFT JOIN vWeb_ItemIDByIsCombined VW on VW.id=a.ItemId AND VW.iscombined=1
'
IF ISNULL(@KTypeID,'') NOT IN ('','00000') OR @MKTypeID=-99999 
	SET @SQL+='	INNER JOIN #ktype k ON a.ktypeid=k.TypeId '+CHAR(13) 
SET @SQL +='

--发出商品退货单
UNION ALL 
SELECT 
		a.id AS CustomdetailID,
		a.PTypeID,
		a.ProduceDate,
		P.entrycode,
		CASE T.RedWord
			WHEN 2 THEN a.qty - a.InvoiceQty
			ELSE -(a.qty - a.InvoiceQty)
		END AS Qty,
		a.MQty  AS nbrcqty,--换算率变更前销售单位数量
		a.DiscountPrice AS Price,
		a.NDiscountPrice as NPrice,

		CASE T.RedWord
			WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.qty - a.InvoiceQty) * a.DiscountPrice END
			ELSE CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.qty - a.InvoiceQty) * a.DiscountPrice) END
		END AS _Total,

		CASE T.RedWord
			WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
			ELSE CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice) END
		END AS _NTotal,

		CASE T.RedWord
			WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.qty - a.InvoiceQty) * a.TaxPrice END
			ELSE CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.qty - a.InvoiceQty) * a.TaxPrice) END
		END AS TaxTotal,

		CASE T.RedWord
			WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.NTaxTotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
			ELSE CASE a.InvoiceQty WHEN 0 THEN -a.NTaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
		END AS NTaxTotal,

		CASE T.RedWord
			WHEN 2 THEN s.sharefee
			ELSE -s.sharefee
		END AS sharefee,'+CHAR(13)

		SET @SQL+='
		s.CostTotal,
		P.PrePrice,
		--a.ktypeid,
		a.cargoid,
		CASE T.RedWord
			WHEN 2 THEN a.NQty - a.InvoiceNQty
			ELSE -(a.NQty - a.InvoiceNQty)
		END AS nqty,
		CASE 
			WHEN a.IsCombined = 0 THEN XW.FullName 
			ELSE REPLACE(VW.FullName,''я'',''/'') 
		END AS itemname,
		--a.GoodsNumber,
		a.munitid,
		bn.Billtypes,
		B.*,
		a.Comment
FROM SendBackBill AS A
INNER JOIN BillIndex AS T ON(A.BillNumberID = T.BillNumberID)
INNER JOIN #BillIndex AS B ON(T.BillNumberID = B.BillNumberID AND T.billtype = B.billtype)
INNER JOIN BillName bn on bn.BillType= T.BillType
INNER JOIN #PType P ON a.PTypeId = P.TypeId
inner join (SELECT a.ID,
SUM(ISNULL(ShareFee,0)) AS sharefee, '
IF @PriceMode = 0
SET @SQL+=' 
    SUM(Convert( NUMERIC(24, 10) ,CASE T.RedWord
						WHEN 2 THEN -(a.CostTotal - a.InvoiceCostTotal)
						ELSE (a.CostTotal - a.InvoiceCostTotal)
						END))  as CostTotal'
ELSE
SET @SQL+='
		SUM(Convert( NUMERIC(24, 10) ,CASE T.RedWord
						WHEN 2 THEN -((a.qty - a.InvoiceQty)*p.PrePrice)
						ELSE (a.qty - a.InvoiceQty)*p.PrePrice
						END)) as CostTotal'
SET @SQL+='
			   
                FROM  SendBill a
 INNER JOIN BillIndex AS T ON(A.BillNumberID = T.BillNumberID)
 INNER JOIN #Ptype p ON a.PtypeId=p.Typeid 
WHERE a.PtypeId IN( 
SELECT ptypeid FROM dbo.CombinationProductDetail d INNER JOIN dbo.CombinationProductIndex i ON d.CombinationProductID=i.CombinationProductID) 
GROUP BY t.RedWord,a.CostTotal,a.InvoiceCostTotal,a.ID) s ON a.ID=s.ID
LEFT JOIN xw_SelfData XW ON XW._Id=A.ItemId
LEFT JOIN vWeb_ItemIDByIsCombined VW on VW.id=a.ItemId AND VW.iscombined=1
'
IF ISNULL(@KTypeID,'') NOT IN ('','00000') OR @MKTypeID=-99999 
	SET @SQL+='	INNER JOIN #ktype k ON a.ktypeid=k.TypeId '+CHAR(13)
	
SET @SQL +='

--销售发货开票
UNION ALL 
SELECT 
		a.id AS CustomdetailID,
		a.PTypeID,
		a.ProduceDate,
		P.entrycode,
		CASE T.RedWord
			WHEN 2 THEN -a.qty
			ELSE a.qty
		END AS qty,
		a.MQty  AS nbrcqty,--换算率变更前销售单位数量
		a.Price,
		a.NPrice,
		CASE T.RedWord
			WHEN 2 THEN -a.total
			ELSE a.total
		END AS total,
		CASE T.RedWord
			WHEN 2 THEN -a.Ntotal
			ELSE a.Ntotal
		END AS Ntotal,
		CASE T.RedWord
			WHEN 2 THEN -a.TaxTotal
			ELSE a.TaxTotal
		END AS TaxTotal,
		CASE T.RedWord
			WHEN 2 THEN -a.NTaxTotal
			ELSE a.NTaxTotal
		END AS NTaxTotal,
		0 AS sharefee,'+CHAR(13)

		SET @SQL+='
		s.CostTotal,
		P.PrePrice,
		--a.ktypeid,
		a.cargoid,
		CASE T.RedWord
			WHEN 2 THEN -a.NQty
			ELSE a.NQty
		END AS NQty,
		CASE 
			WHEN a.IsCombined = 0 THEN XW.FullName 
			ELSE REPLACE(VW.FullName,''я'',''/'') 
		END AS itemname,
		--a.GoodsNumber,
		a.munitid,
		bn.Billtypes,
		B.*,
		a.Comment
FROM ReceiptBill AS A
INNER JOIN ReceiptBillIndex AS T ON(A.BillNumberID = T.BillNumberID AND A.billtype = T.billtype)
INNER JOIN #BillIndex AS B ON(T.BillNumberID = B.BillNumberID AND T.billtype = B.billtype)
INNER JOIN BillName bn on bn.BillType= T.BillType 
INNER JOIN #PType P ON a.PTypeId = P.TypeId
inner join (SELECT a.ID,
 '
IF @PriceMode = 0
SET @SQL+=' 
    SUM(Convert( NUMERIC(24, 10) ,CASE T.RedWord
						WHEN 2 THEN -a.InvoiceCostTotal
						ELSE a.InvoiceCostTotal
						END)) as CostTotal'
ELSE
SET @SQL+='
		SUM(Convert( NUMERIC(24, 10) ,CASE T.RedWord
							WHEN 2 THEN -(a.qty*p.PrePrice)
							ELSE a.qty*p.PrePrice
							END)) as CostTotal'
SET @SQL+='    
 FROM  ReceiptBill a
 INNER JOIN BillIndex AS T ON(A.BillNumberID = T.BillNumberID)
 INNER JOIN #Ptype p ON a.PtypeId=p.Typeid 
WHERE a.PtypeId IN( 
SELECT ptypeid FROM dbo.CombinationProductDetail d INNER JOIN dbo.CombinationProductIndex i ON d.CombinationProductID=i.CombinationProductID) 
GROUP BY t.RedWord,a.InvoiceCostTotal,a.ID) s ON a.ID=s.ID 
LEFT JOIN xw_SelfData XW ON XW._Id=A.ItemId
LEFT JOIN vWeb_ItemIDByIsCombined VW on VW.id=a.ItemId AND VW.iscombined=1
'
--PRINT (@SQL)
IF ISNULL(@KTypeID,'') NOT IN ('','00000') OR @MKTypeID=-99999 
	SET @SQL+='	INNER JOIN #ktype k ON a.ktypeid=k.TypeId '+CHAR(13)

--****************************************--
DECLARE @SQL_LIST VARCHAR(MAX)='',
		@SQL_LIST1 VARCHAR(MAX)='',
		@config int=0
SELECT  @config=Value FROM Userconfig WHERE ConfigName='sharefee'
SET @SQL_LIST1 =' 
		SELECT	distinct 		       
				a.BillnumberID,
				a.CustomdetailID,
				B.BillDate,
				B.BillCode,
				B.Billtype,
				a.entrycode,
				A.ProduceDate producedata,
				(SELECT BillName FROM BillName WHERE BillType = B.BillType) AS BilltypeName,
				a.Ptypeid,
				p1.usercode,
				p1.fullname,
				B.BtypeID,
				A.ProduceDate,
				a.qty,
				a.price,
				a.nprice,
				total= case when B.billtype in(148,149) then null else a._total end,
				ntotal= case when B.billtype in(148,149) then null else a._ntotal end,
 				TaxTotal=a.TaxTotal,
 				ntaxtotal=a.NTaxTotal,
				a.CostTotal,-- =Convert( NUMERIC(24, 10) ,isnull(a.CostTotal,0)),
				MaoLi = case when B.billtype in(148,149) then null else  Convert( NUMERIC(24, 10) ,(isnull(a._Total,0)-isnull(a.CostTotal,0)'+CASE @config WHEN 1 THEN '-ISNULL(a.sharefee,0)'ELSE '' END+')) end,
				MaoLiLu = case when B.billtype in(148,149) then null else Case a._Total when 0 then 0 else  100*( CAST((isnull(a._Total,0)-isnull(a.CostTotal,0)'+CASE @config WHEN 1 THEN '-ISNULL(a.sharefee,0)'ELSE '' END+') AS NUMERIC(24, 10))/ cast(isnull(a._Total,0) AS NUMERIC(24, 10))) end end,
				B.EtypeID,
				--B.KtypeID,
				a.ktypeid,
				B.STypeID,
				a.CheckeName,
				case when B.billtype in(148,149) then null  else isnull(BB.sharefee,0) end as sharefee,
				B.Comment,
				a.Comment as comment1,
				B.RedWord,
				B.ID,
				a.cargoid,
				B.DealBTypeID,
				case when B.billtype in(148,149) then null else a.nqty  END AS nqty,
				A.FullName cname,--币种
				B.Rate,--汇率
				a.itemname,--自由项
				a.GoodsNumber,--批号
				b.posttime,
				case when B.billtype in(148,149) then null else u1.fullname  END AS baseunitfullname,--基本单位
				case when B.billtype in(148,149) then null else u5.fullname  END AS assistantfullname,
				CASE A.Billtypes WHEN ''1'' THEN a.qty/h.rate ELSE a.qty/h.rate END AS munitqty,--计量单位
				case a.nbrcqty when a.qty/h.rate then null else a.nbrcqty end as nbrcqty ,--换算率变更前销售单位数量
				case when B.billtype in(148,149) then null else r.fullname  END AS munit,--基本单位
				atotal=case B.billtype when ''148'' then Convert( NUMERIC(24, 10) ,isnull(a._Total,0)) else null end,--返利
				ptotal=case B.billtype when ''149'' then Convert( NUMERIC(24, 10) ,isnull(a._Total,0)) else null END,--价保
				taxge=case when B.billtype in(148,149) then null else Convert( NUMERIC(24, 10) ,isnull(a.TaxTotal,0))-Convert( NUMERIC(24, 10) ,isnull(a._Total,0)) END,
				costprice=case when B.billtype in(148,149) then null else case when '+convert(varchar(10),@PriceMode)+'=0 then Convert( NUMERIC(24, 10) ,case Convert( NUMERIC(24, 10) ,isnull(a.Qty,0)) when 0 then 0 else Convert( NUMERIC(24, 10) ,isnull(a.CostTotal,0))/Convert( NUMERIC(24, 10) ,isnull(a.Qty,0)) end) else a.PrePrice end end ,
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	,
				customassist=dbo.F_GetCustomAssist(a.Ptypeid,a.Qty)
				
		FROM 	(
		 	'
SET @SQL_LIST+=@SQL

SET @SQL_LIST +=' ) a 
inner join ptype p1 on a.ptypeid=p1.typeid
		'+@unitsql+'
LEFT JOIN #Comment c ON c.BillNumberId=a.BillnumberID
left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid AND  csdetail.InOrOut= ''I''
INNER JOIN 
(
	SELECT BillNumberId,BillDate,BillCode,Billtype,BtypeID,EtypeID,STypeID,Comment,RedWord,ID,DealBTypeID,Rate,posttime FROM BillIndex
	UNION ALL
	SELECT BillNumberId,BillDate,BillCode,Billtype,BtypeID,EtypeID,STypeID,Comment,RedWord,0 AS ID,DealBTypeID,Rate,posttime FROM ReceiptBillIndex
) B ON B.BillNumberId=A.BillNumberId 

INNER JOIN 
(

	SELECT BillNumberId,sum(sharefee) as sharefee FROM PT_Combin_SaleBillDetail 
	GROUP BY BillNumberId
	UNION ALL
	SELECT BillNumberId,0 as sharefee FROM PT_Combin_SaleBackBillDetail 
	UNION ALL
	SELECT BillNumberId,0 as sharefee FROM RetailCombinationBill 
    GROUP BY BillNumberId

) BB ON BB.BillNumberId=A.BillNumberId 

left join PType_Units_Ext AS h ON  a.munitid= h.unitsid AND a.ptypeid=h.ptypeid 
LEFT JOIN ptype_units AS r ON h.UnitsId = r.UnitsId WHERE ('+ @ptypeproperty +'=0 OR (p1.IsService=0 AND '+ @ptypeproperty+'=2)OR (p1.IsService=1 AND '+ @ptypeproperty+'=1)) and p1.iscombinationproduct=1
'+CHAR(13)
-------------------------------------------明细打印查询表体自定义列 ---------------------------------------------------


IF @sortfield = ''--添加排序
	SET @SQL_LIST +=' ORDER BY B.BillDate ASC ,B.billtype, B.BillCode'
IF @sortfield = 'ByBillID_a'
	SET @SQL_LIST +=' ORDER BY B.BillDate ASC ,B.billtype, B.BillCode'
IF @sortfield = 'ByBillID_d'
	SET @SQL_LIST +=' ORDER BY B.BillDate DESC ,B.billtype DESC, B.BillCode DESC'	
	
--PRINT @SQL_LIST1+@SQL_LIST
EXEC(@SQL_LIST1+@SQL_LIST)

DROP TABLE #Billtype,#Ptype,#Btype,#Etype,#Ktype,#Atype,#Dtype,#Stype,#dealbtype,#BillIndex,#InOutStockTable,#Money,#MoneyTemp,#Comment
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CombinationStatTypeQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CombinationStatTypeQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
作者： 魏伟
时间： 2016-06-29
描述:  获取商品组合品销售统计表
*/
 
CREATE	PROCEDURE Web_CombinationStatTypeQuery
(
	 
	@chkDiscountQuery	char(1),		--  1、折前销售金额查询标识；0：不显示；1：显示；
	@startDate		    varchar(30),		--  2、查询起始时间
	@endDate			varchar(30),		--  3、查询结束时间
	@parid		        varchar(50),		--  4、查询类别节点 ID
	@ptypeid			varchar(MAX),		--  5、商品类别查询范围父节点 ID
	@btypeid			varchar(MAX),		--  6、结算单位类别查询范围父节点 ID
	@dealbtypeid		VARCHAR(MAX),		--  往来单位
	@etypeid			varchar(MAX),		--  7、职员类别查询范围父节点 ID
	@ktypeid			varchar(MAX),		--  8、仓库类别查询范围父节点 ID
	@userCode	        varchar(MAX)	= '',	--  9、筛选的类别编号
	@fullName	        varchar(MAX)	= '',	-- 10、筛选的类别名称
	@sortfield		    varchar(50)	= '',	-- 11、排序的列名
	@sorttype		    varchar(50)	= '',	-- 12、排序的方式（升序或降序)
	@intPageNo		    int		= '',	-- 13、当前查询的页码
	@intPageSize		int		= '',	-- 14、每页的显示记录数
	@chvOperatorID		varchar(50),		-- 15、操作员 ID（作权限范围检查用）
	@delView        	int =0,        		-- 17. 是否显示已停用数据
	@chkDx			    char(1) ='0',   	-- 18. 部分仓库时是否显示代销数据
	@chkXs			    char(1) ='0',   	-- 19. 是否显示销售为0 的数据
	@chkPf              char(1) = '0',      -- 20. 是否显示价保、返利数据
	@chkPe              char(1) = '0',      -- 20. 是否优惠金额
	@chkRed             char(1) = '0',      -- 20. 是否显示红冲
	@billType           varchar(200),       -- 21. 单据类型
	@PriceMode          varchar(2)='0',
	@dtypeid            varchar(MAX)='',
	@atypeid	        varchar(50)='',
	@chrFlag		    char(1),				-- 22、功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@stypeid            varchar(MAX)='00001',		--  23、分支机构查询范围父节点 ID
	@Explain			VARCHAR(MAX)='', --说明
	@Comment			VARCHAR(MAX)=''  ,--摘要
	@unitconvert		INT	,			  --单位换算
	@ptypeproperty      int               --是否服务商品
	
)
--@encode$--

AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------


DECLARE	@tempsqlWhere VARCHAR(max)=''--说明，摘要筛选
-- ********	确定 SQL 语句中的 WHERE 部分的相关子句 - Start	********
		
IF(@Explain <> '')
	BEGIN
		SET @tempsqlWhere+=' AND  b.Explain like ''%' + @Explain + '%'' '
	END
	
IF(@Comment <> '')
	BEGIN
		SET @tempsqlWhere+=' AND  b.Comment like ''%' + @Comment + '%'' '
	END


-- =======end============== 
		--SET @ptypeid = @parid 

DECLARE 
	@chvColName		VARCHAR(15)= 'PTypeID'
									 
DECLARE 						 
@chvColName1		VARCHAR(15)=  'PTypeID'
										 
--============================= 根据传入的inputType报表类型,确定将要查询的主信息类型表名 及 主信息类型列名 END============================

DECLARE @tempqty    NVARCHAR(2000)='',
		@temprice   NVARCHAR(2000)='',
		@temptable  NVARCHAR(2000)='',
		@tempUnit   NVARCHAR(2000)='',
		@tempUnit1   NVARCHAR(2000)='',
		@tempassistantfullname VARCHAR(200)='',
		@baseunit     NVARCHAR(2000)='',
		@jlunit        NVARCHAR(2000)='',
		@unitRelation  NVARCHAR(2000)='',
		--发出商品增加
		@tempsendqty NVARCHAR(2000),
		@tempsendprice NVARCHAR(2000),
		@tempsendsaleprice NVARCHAR(2000),
		@tempsendtaxprice NVARCHAR(2000)
		
SET @tempassistantfullname ='u5.fullname as assistantfullname'
		

-------------------------------------------单位换算--------------------------------------
IF @unitconvert=0
BEGIN
	SET @temptable =dbo.F_GetPtypeUnitsAndRates('p1','1,3,5','3,1')
	SET @tempqty='-a.qty/isnull(r3.rate,1)'
	SET @tempsendqty='-((a.qty-a.InvoiceQty)/isnull(r3.rate,1))'
	SET @temprice='price*isnull(r3.rate,1)'
	SET @tempsendprice='discountprice*isnull(r3.rate,1)'
	SET @tempsendsaleprice='saleprice*isnull(r3.rate,1)'
	SET @tempsendtaxprice='taxprice*isnull(r3.rate,1)'
	SET @tempunit=',u3.fullname,u1.fullname,'
	SET @tempunit1='u3.fullname'
	SET @jlunit='isnull(r3.rate,1)'
	SET @unitRelation='''1''+u3.fullname+''=''+convert(varchar(200),CAST(r3.rate  AS real))+u1.fullname,'
END
IF @unitconvert=1
BEGIN
	SET @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,2,5','2,1')
	SET @tempqty='-a.qty/isnull(r2.rate,1)'
	SET @tempsendqty='-((a.qty-a.InvoiceQty)/isnull(r2.rate,1))'
	SET @temprice='price*isnull(r2.rate,1)'
	SET @tempsendprice='discountprice*isnull(r2.rate,1)'
	SET @tempsendsaleprice='saleprice*isnull(r2.rate,1)'
	SET @tempsendtaxprice='taxprice*isnull(r2.rate,1)'
	SET @tempunit=',u2.fullname,u1.fullname,'
	SET @tempunit1='u2.fullname'
	SET @jlunit='isnull(r2.rate,1)'
	SET @unitRelation='''1''+u2.fullname+''=''+convert(varchar(200),CAST(r2.rate  AS real))+u1.fullname,'
	
END
IF @unitconvert=2
BEGIN
	SET @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,4,5','4,1')
	SET @tempqty='-a.qty/isnull(r4.rate,1)'
	SET @tempsendqty='-((a.qty-a.InvoiceQty)/isnull(r4.rate,1))'
	SET @temprice='price*isnull(r4.rate,1)'
	SET @tempsendprice='discountprice*isnull(r4.rate,1)'
	SET @tempsendsaleprice='saleprice*isnull(r4.rate,1)'
	SET @tempsendtaxprice='taxprice*isnull(r4.rate,1)'
	SET @tempunit=',u4.fullname,u1.fullname,'
	SET @tempunit1='u4.fullname'
	SET @jlunit='isnull(r4.rate,1)'
	SET @unitRelation='''1''+u4.fullname+''=''+convert(varchar(200),CAST(r4.rate  AS real))+u1.fullname,'
END
IF @unitconvert=3
BEGIN
	SET @temptable=dbo.F_GetPtypeUnitsAndRates('p1','1,5','1')
	SET @tempqty='-a.qty'
	SET @tempsendqty='-(a.qty-a.InvoiceQty)'
	SET @temprice='price'
	SET @tempsendprice='discountprice'
	SET @tempsendsaleprice='saleprice'
	SET @tempsendtaxprice='taxprice'
	SET @tempunit=',u1.fullname,u1.fullname,'
	SET @tempunit1='u1.fullname'
	SET @jlunit='isnull(r1.rate,1)'
	SET @unitRelation='''1''+u1.fullname+''=''+convert(varchar(200),CAST(r1.rate  AS real))+u1.fullname,'
END
----------------------------------------------- END -------------------------------------





CREATE TABLE #Ptype (TypeID varchar(200),PrePrice  NUMERIC(24, 10) )
CREATE NONCLUSTERED INDEX CIX_PType_TypeId ON #Ptype(TypeId)

CREATE TABLE #Btype (TypeID varchar(50)) 
CREATE NONCLUSTERED INDEX CIX_BType_TypeId ON #Btype(TypeId)

CREATE TABLE #Dealbtype (TypeID varchar(50),AtypeID varchar(50)) 
CREATE NONCLUSTERED INDEX CIX_DealBType_TypeId ON #DealBtype(TypeId)

CREATE TABLE #Etype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_EType_TypeId ON #Etype(TypeId)

CREATE TABLE #Ktype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_KType_TypeId ON #Ktype(TypeId)

CREATE TABLE #Dtype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_DType_TypeId ON #Dtype(TypeId)

CREATE TABLE #Atype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_AType_TypeId ON #Atype(TypeId)

CREATE TABLE #Stype (TypeID varchar(50))
CREATE NONCLUSTERED INDEX CIX_SType_TypeId ON #Stype(TypeId)

CREATE TABLE #MainType 
(
		TypeID varchar(200),
		usercode varchar(200),
		fullname varchar(200),
		standard VARCHAR(200),
		type VARCHAR(200),
		sonnum int,
		deleted INT,
		entrycode VARCHAR(200),
		assistantfullname VARCHAR(200) ,
        ufullname			VARCHAR(200),  --计量单位
        basefullname      VARCHAR(200),--基本单位
        unitRelation      VARCHAR(200),
        jlunit              NUMERIC(24, 10)
)
CREATE NONCLUSTERED INDEX CIX_MainType_TypeId ON #MainType(TypeId)

DECLARE @ptypecategoryid VARCHAR(MAX)    --商品类别ID
SET @ptypecategoryid=''
DECLARE	@strTemp VARCHAR(MAX)
IF @ptypeid ='00000' OR @ptypeid=''
	INSERT INTO #Ptype(typeid) select typeid from dbo.F_LinePC(@chvOperatorId,@ptypecategoryid)
ELSE
	INSERT INTO #Ptype(typeid) SELECT TypeId FROM  F_ManPTypeInCategoryID ( @chvOperatorID,@ptypeid,@ptypecategoryid) 
DECLARE @intPriceMode INT=CAST(@PriceMode AS INT)

IF @intPriceMode<>0 -- 增加预设售价
BEGIN
	IF @intPriceMode<=10
		BEGIN
			EXEC('UPDATE #Ptype SET PrePrice =p.PreSalePrice'+@PriceMode+'
			FROM Ptype_Price p INNER JOIN #Ptype p1
			on p.ptypeid=p1.typeid')
		END
	ELSE 
		BEGIN	
			IF @intPriceMode<=15
				BEGIN
					SELECT @PriceMode=CAST(CAST(@PriceMode AS INT)-10 AS VARCHAR(1))
					EXEC('UPDATE #Ptype SET PrePrice =p.PreBuyPrice'+@PriceMode+'
					FROM Ptype_Price p INNER JOIN #Ptype p1
					on p.ptypeid=p1.typeid')
				END
			ELSE IF @intPriceMode=16
				BEGIN
					EXEC('UPDATE #Ptype SET PrePrice =p.TopSalePrice
					FROM Ptype_Price p INNER JOIN #Ptype p1
					on p.ptypeid=p1.typeid')
				END
			ELSE IF @intPriceMode=17
				BEGIN
					EXEC('UPDATE #Ptype SET PrePrice =p.LowSalePrice
					FROM Ptype_Price p INNER JOIN #Ptype p1
					on p.ptypeid=p1.typeid')
				END
			ELSE IF @intPriceMode=18
				BEGIN
					EXEC('UPDATE #Ptype SET PrePrice =p.RetailPrice
					FROM Ptype_Price p INNER JOIN #Ptype p1
					on p.ptypeid=p1.typeid')
				END
			ELSE IF @intPriceMode=19
				BEGIN
					EXEC('UPDATE #Ptype SET PrePrice =p.TopBuyPrice
					FROM Ptype_Price p INNER JOIN #Ptype p1
					on p.ptypeid=p1.typeid')
				END
		END
END

IF @btypeid ='' OR @btypeid ='00000'
	INSERT INTO #Btype(typeID) select typeid from F_LineB(@chvOperatorID)
ELSE
	INSERT INTO #Btype(typeID) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid, 2, @chvOperatorID) 
	
IF @dealbtypeid ='' OR @dealbtypeid ='00000'
	INSERT INTO #Dealbtype(typeID,AtypeID) select typeid,AreaTypeID from dbo.F_AllTreeB(@chvOperatorID)  WHERE sonnum = 0
ELSE
	INSERT INTO #Dealbtype(typeID,AtypeID) 
	select	F.TypeId, B.AreaTypeID 
	FROM	F_GetAllManagerBaseTypeId(@dealbtypeid, 2, @chvOperatorID) F
	INNER JOIN btype B ON B.typeId = F.TypeId

 
IF @etypeid='' OR @etypeid='00001'
	INSERT INTO #Etype select typeid from dbo.F_LineE(@chvOperatorID)
ELSE
	INSERT INTO #Etype 
	SELECT TypeId FROM  F_GetAllManagerBaseTypeId(@etypeid,3,@chvOperatorID)

IF @ktypeid='' OR @ktypeid='00000'
	INSERT INTO #Ktype select typeid from F_LineK(@chvOperatorID)
ELSE
	INSERT INTO #Ktype 
	SELECT TypeId FROM  F_GetAllManagerBaseTypeId(@ktypeid,4,@chvOperatorID)

--IF @ktypeid='' OR @ktypeid='10000' or @chkDx='1'  OR @ktypeid='00000'
--	INSERT INTO #Ktype SELECT '10000'


INSERT INTO #Dtype SELECT typeid from F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)

IF NOT(@stypeid='' and @MStypeid='00000')
    INSERT INTO #Stype SELECT typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperatorID)

IF @atypeid='' OR @atypeid='00000'
BEGIN
	INSERT INTO #Atype select typeid from AreaType where Sonnum =0 
	INSERT INTO #Atype SELECT ''
END
ELSE
	INSERT INTO #Atype 
	SELECT typeid FROM F_GetAllManagerBaseTypeId(@atypeid,10,@chvOperatorID) 

 

	SET @strTemp= 'INSERT INTO #MainType(typeid,usercode,fullname,standard,type,sonnum,deleted,entrycode,assistantfullname,ufullname,basefullname,unitRelation,jlunit) 
		SELECT 
			p1.typeid,
			p1.usercode,
			p1.fullname,
			p1.standard,
			p1.type,
			p1.sonnum,
			p1.deleted,
			p1.EntryCode,
			'+@tempassistantfullname+@tempUnit+@unitRelation+@jlunit+'
		FROM Ptype p1
		INNER JOIN  #Ptype pt ON PT.TypeID=p1.TypeId
		'+@temptable+'
		 WHERE (' +CONVERT(VARCHAR(1),@ptypeproperty)+'=0 OR (p1.IsService=0 AND '+ CONVERT(VARCHAR(1),@ptypeproperty)+'=2)OR (p1.IsService=1 AND '+CONVERT(VARCHAR(1),@ptypeproperty)+'=1)) and p1.iscombinationproduct=1 '
	 --  PRINT @strTemp
		 EXEC(@strTemp) 
		 
IF @userCode <> '' AND @userCode <> '其他地区' --满足条件直接删除UserCode不满足条件的数据
	BEGIN
		DELETE #MainType WHERE usercode NOT LIKE '%'+@userCode+'%'
	END

IF @fullName <> '' AND @fullName <> '其他地区'  --满足条件直接删除FullName不满足条件的数据
BEGIN   
	DELETE #MainType WHERE fullname NOT LIKE '%'+@fullName+'%'
END 
CREATE TABLE [dbo].[#Billtype]
    (
      [Billtype] VARCHAR(200)
    )
CREATE NONCLUSTERED INDEX CIX_BillType_Billtype ON #Billtype(Billtype)    
    
INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@billType,',')



CREATE TABLE #BillIndex(
	BillNumberId numeric(10, 0) ,
	atypeid varchar(50),
	preferencemoney  NUMERIC(24, 10) ,
	billtype INT 
)
CREATE NONCLUSTERED INDEX CIX_BillIndex_BillNumberId ON #BillIndex(BillNumberId)

SET @strTemp=' 
				INSERT INTO #BillIndex(BillnumberID,atypeid,preferencemoney,billtype) 
				SELECT 
					b.BillnumberID,
					dl.atypeid,
					b.preferencemoney,
					bill.billtype
				FROM BillIndex b 				
				INNER JOIN #Billtype BILL ON b.billtype=BILL.billtype
				INNER JOIN #Dealbtype DL ON  DL.typeID=B.dealbtypeid
				'

IF (NOT (@dtypeid ='' OR @dtypeid ='00000')) OR @MDTypeID='-99999'
	BEGIN
		SET @strTemp +=' INNER JOIN #Dtype d  ON  b.DtypeID=d.typeid '
	END

IF (NOT (@etypeid ='' OR @etypeid ='00000')) OR @METypeID='-99999'
	BEGIN
		SET @strTemp +=' INNER JOIN #Etype e  ON b.etypeid=e.typeid '
	END
	
IF (@MBtypeid <> '00000' OR @btypeid<>'' )
	BEGIN
		SET @strTemp +=  ' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '
	END
	
IF NOT(@stypeid='' and @MStypeid='00000')
	BEGIN
		SET @strTemp +=' INNER JOIN #Stype s  ON  b.stypeID=s.typeid '
	END

SET @strTemp += ' 
				WHERE 
					b.BillDate>='''+@startDate+''' AND 
					b.BillDate<='''+@endDate+''' AND 
					b.isini=0 and 
					b.RedWord=0  AND 
					b.ifYearBill=0 AND 
					b.Draft =0 '+@tempsqlWhere

SET @strTemp += ' 
--销售发货开票单据
UNION ALL
SELECT 
b.BillnumberID,
dl.atypeid,
0 AS preferencemoney,
bill.billtype 
FROM ReceiptBillIndex AS B
INNER JOIN #Billtype BILL ON b.billtype=BILL.billtype
INNER JOIN #Dealbtype DL ON  DL.typeID=B.dealbtypeid
'
IF (NOT (@dtypeid ='' OR @dtypeid ='00000')) OR @MDTypeID='-99999'
	BEGIN
		SET @strTemp +=' INNER JOIN #Dtype d  ON  b.DtypeID=d.typeid '
	END

IF (NOT (@etypeid ='' OR @etypeid ='00000')) OR @METypeID='-99999'
	BEGIN
		SET @strTemp +=' INNER JOIN #Etype e  ON b.etypeid=e.typeid '
	END
	
IF (@MBtypeid <> '00000' OR @btypeid<>'' )
	BEGIN
		SET @strTemp +=  ' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '
	END
	
IF NOT(@stypeid='' and @MStypeid='00000')
	BEGIN
		SET @strTemp +=' INNER JOIN #Stype s  ON  b.stypeID=s.typeid '
	END

SET @strTemp += ' 
				WHERE 
					b.BillDate>='''+@startDate+''' AND 
					b.BillDate<='''+@endDate+''' AND 
					b.isini=0 and 
					b.RedWord=0  AND 
					b.ifYearBill=0 AND 
					b.Draft =0 '+@tempsqlWhere

--PRINT @strTemp
EXEC(@strTemp)   
--SELECT * FROM #BillIndex

--CREATE CLUSTERED INDEX B_IN--建立 #BillIndex 临时表索引
--ON #BillIndex (BillNumberId)


-- 价保、返利单据临时表ID，只管辖非红冲单据
-- 价保、返利单据临时表ID，只管辖非红冲单据
CREATE TABLE #BillIndex1(
	BillNumberId numeric(10, 0),
	BtypeId  varchar (50),
	Dealbtypeid	VARCHAR(50),
	EtypeId  varchar (50),
	DtypeId  varchar (50),
	atypeid VARCHAR(50)
)
CREATE CLUSTERED INDEX B1_IN--建立 #BillIndex 临时表索引
ON #BillIndex1 (BillNumberId)

 


DECLARE @SQL1 varchar(2000)
IF @chkPf ='1' -- 显示价保返利
BEGIN
	ALTER TABLE #MainType ADD AdvantageTotal  NUMERIC(24, 10) 
	ALTER TABLE #MainType ADD PriceTotal  NUMERIC(24, 10) 
END
IF @chkPe='1'
BEGIN
   ALTER TABLE #MainType ADD preferencemoney  NUMERIC(24, 10) 
 END
 

CREATE TABLE #InoutStockTable
    (
		PtypeId varchar (50),
		BillNumberId INT,
		Dealbtypeid VARCHAR(50),
		EtypeId varchar (50),
		KtypeId varchar (50),
		preferencemoney  NUMERIC(24, 10) ,
		Qty  NUMERIC(24, 10) ,
		Price    NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		SaleTotal  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		DtypeID varchar(50),
		ShareFee  NUMERIC(24, 10) ,
		SShareFee  NUMERIC(24, 10) ,
		AtypeID varchar(50),
        nqty				 NUMERIC(24, 10)  ,
        baseqty            NUMERIC(24, 10) ,
        giftqty   NUMERIC(24, 10) ,
        giftcosttotal  NUMERIC(24, 10)          
    )
CREATE NONCLUSTERED INDEX CIX_InoutStockTable_PTypeId ON #InoutStockTable(PTypeId,BillNumberId)    
    

CREATE TABLE #Money
		(
			BillNumberId INT,
			CostTotal NUMERIC(24,10),
			ShareFee NUMERIC(24,10),
			SShareFee NUMERIC(24,10),
			giftqty NUMERIC(24,10),
			giftcosttotal NUMERIC(24,10),
			pindexid VARCHAR(100) --组合品表体关联ID  
		)
CREATE NONCLUSTERED INDEX CIX_Money_BillNumberId ON #Money(BillNumberId)    		

CREATE TABLE #InoutStockTableBill
    (
		PtypeId varchar (50),
		BillNumberId INT,
		Dealbtypeid VARCHAR(50),
		EtypeId varchar (50),
		KtypeId varchar (50),
		preferencemoney  NUMERIC(24, 10) ,
		Qty  NUMERIC(24, 10) ,
		Price    NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		SaleTotal  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		DtypeID varchar(50),
		ShareFee  NUMERIC(24, 10) ,
		SShareFee  NUMERIC(24, 10) ,
		AtypeID varchar(50),
        nqty				 NUMERIC(24, 10)  ,
        baseqty            NUMERIC(24, 10) ,
        giftqty   NUMERIC(24, 10) ,
        giftcosttotal  NUMERIC(24, 10),
        pindexid VARCHAR(100) --组合品表体关联ID  
    )
CREATE NONCLUSTERED INDEX CIX_InoutStockTableBill_BillNumberId ON #InoutStockTableBill(BillNumberId)       


SET @tempUnit=SUBSTRING(@tempunit,2,LEN(@tempunit))
SET @tempUnit=','+@tempUnit

DECLARE @tempcosttotal VARCHAR(2000),@tempsendcosttotal VARCHAR(2000),@tempreceiptcosttotal VARCHAR(2000)
--统计价格方式
IF @PriceMode='0' 
BEGIN
	SET @tempcosttotal = '-Convert( NUMERIC(24, 10) ,a.CostTotal)'
	SET @tempsendcosttotal = '-Convert( NUMERIC(24, 10) ,a.CostTotal - a.InvoiceCostTotal)'
	SET @tempreceiptcosttotal = '-Convert( NUMERIC(24, 10) ,a.InvoiceCostTotal)'
END
ELSE
BEGIN
	SET @tempcosttotal = '-Convert( NUMERIC(24, 10) ,a.qty*p.PrePrice)'
	SET @tempsendcosttotal = '-Convert( NUMERIC(24, 10) ,(a.qty - a.InvoiceQty)*p.PrePrice)'
	SET @tempreceiptcosttotal = '-Convert( NUMERIC(24, 10) ,a.qty*p.PrePrice)'
END

CREATE TABLE #InoutStockTableTemp
    (
		PtypeId varchar (50),
		BillNumberId INT,
		Dealbtypeid VARCHAR(50),
		EtypeId varchar (50),
		KtypeId varchar (50),
		preferencemoney  NUMERIC(24, 10) ,
		Qty  NUMERIC(24, 10) ,
		Price    NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		SaleTotal  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		DtypeID varchar(50),
		ShareFee  NUMERIC(24, 10) ,
		SShareFee  NUMERIC(24, 10) ,
		AtypeID varchar(50),
        nqty				 NUMERIC(24, 10)  ,
        baseqty            NUMERIC(24, 10) ,
        giftqty   NUMERIC(24, 10) ,
        giftcosttotal  NUMERIC(24, 10)
    )
CREATE NONCLUSTERED INDEX CIX_InoutStockTableTemp_BillNumberId ON #InoutStockTableTemp(BillNumberId)           
    
DECLARE @SQLtempbill VARCHAR(MAX)='
    INSERT INTO #InoutStockTableBill(PtypeID,BillNumberId,Dealbtypeid,EtypeID,KtypeID,preferencemoney,Qty,Price,Total,CostTotal,SaleTotal,TaxTotal,DtypeID,sharefee,sshareFee,AtypeID,nqty,baseqty,giftqty,giftcosttotal,pindexid)
SELECT 
PtypeId,
BillNumberId,
Dealbtypeid,
EtypeId,
KtypeId,
preferencemoney,
Qty,
Price,
Total,
CostTotal,
SaleTotal,
TaxTotal,
DtypeID,
ShareFee,
SShareFee,
AtypeID,
nqty,
baseqty,
giftqty,
giftcosttotal,
pindexid
FROM 
(
    SELECT	a.PtypeID,
			a.BillNumberId,
			a.BtypeID as dealbtypeid,
			a.EtypeID,
			a.KtypeID,
			b.preferencemoney,
			'+@tempqty+' AS Qty,
			'+@temprice+' AS Price,
			-Convert( NUMERIC(24, 10) ,a.Total) AS Total,
			'+@tempcosttotal+' AS CostTotal,
			-Convert( NUMERIC(24, 10) ,a.SaleTotal) AS SaleTotal,
			-Convert( NUMERIC(24, 10) ,a.TaxTotal) AS TaxTotal,
			a.DtypeID,
			-Convert( NUMERIC(24, 10) ,s.sharefee) AS sharefee,
			-Convert( NUMERIC(24, 10) ,a.sharefee) AS ssharefee,
			b.AtypeID,
			-a.nqty AS nqty,
			-a.qty AS baseqty,
			CASE 
				WHEN a.isgift=1 AND a.price=0 THEN ' + @tempqty + ' 
				ELSE 0
			END AS giftqty,
			CASE 
				WHEN a.isgift=1 AND a.price=0 THEN -Convert( NUMERIC(24, 10) ,a.CostTotal) 
				ELSE 0
			END AS giftcosttotal ,
			PD.pindexid
	FROM	#BillIndex b 
	INNER JOIN InoutStockTable a ON a.BillnumberID=b.BillnumberID
	INNER JOIN ptype p1 on a.ptypeid=  p1.typeid
	LEFT JOIN (
				SELECT ID,BillnumberID,pindexid FROM PT_Combin_SaleBillDetail
				UNION ALL
				SELECT ID,BillnumberID,pindexid FROM PT_Combin_SaleBackBillDetail
				UNION ALL
				SELECT ID,BillnumberID,pindexid FROM RetailBill
	)AS PD ON PD.BillnumberID = B.BillnumberID AND PD.ID = A.ID
	inner join (
				SELECT	SUM(ISNULL(I.ShareFee,0)) AS sharefee, 
						I.BillnumberID,
						I.BillType,
						I.ptypeid 
				FROM	dbo.InOutstocktable I
				--WHERE	PtypeId IN
				INNER JOIN 
						( 
							SELECT	ptypeid 
							FROM	dbo.CombinationProductDetail d 
							INNER JOIN dbo.CombinationProductIndex i ON d.CombinationProductID=i.CombinationProductID  
							inner join #Ptype p on p.typeid=i.CombinationProductPtypeId
						)M ON M.PTypeId = I.PTypeId				
				GROUP BY  I.BillnumberID,I.BillType,I.ptypeid
	) s ON a.BillnumberID=s.BillnumberID and s.ptypeid=a.ptypeid ' + @temptable
	
	IF @dtypeid<>'' or @MDtypeid='-99999'
	BEGIN
		SELECT @SQLtempbill=@SQLtempbill+'	INNER JOIN #Dtype d ON a.dtypeid=d.typeid	'+CHAR(13)
	END
	
	IF ((NOT (@ktypeid ='00000' OR @ktypeid='')) OR @MKTypeID='-99999')
	BEGIN
		SELECT @SQLtempbill=@SQLtempbill+'	INNER JOIN #Ktype k ON a.ktypeid=k.typeid	'+CHAR(13)
	END

	SET @SQLtempbill +='
		WHERE	a.BillDate>='''+@startDate+''' AND 
				a.BillDate<='''+@endDate+''' AND
				a.Audited=1 
				AND B.billtype NOT IN(402,403,405) ) AS T'
			
    --PRINT(@SQLtempbill)
    EXEC(@SQLtempbill)
    
-- INSERT #Money    	
	INSERT INTO #Money
	SELECT 
		BillNumberId,
		SUM(CostTotal) AS CostTotal,
		SUM(ShareFee) AS ShareFee,
		SUM(SShareFee) AS SShareFee,
		SUM(giftqty) AS giftqty,
		SUM(giftcosttotal) AS giftcosttotal,
		pindexid
	FROM #InoutStockTableBill 
	GROUP BY BillNumberId,pindexid
	
-- INSERT #InoutStockTableTemp
	INSERT INTO #InoutStockTableTemp
        ( PtypeId ,
          BillNumberId ,
          Dealbtypeid ,
          EtypeId ,
          KtypeId ,
          preferencemoney ,
          Qty ,
          Price ,
          Total ,
          CostTotal ,
          SaleTotal ,
          TaxTotal ,
          DtypeID ,
          AtypeID ,
          ShareFee,
          SShareFee,
          nqty ,
          baseqty,
          giftqty,
          giftcosttotal
        )
SELECT DISTINCT PtypeId ,
          BillNumberId ,
          Dealbtypeid ,
          EtypeId ,
          KtypeId ,
          preferencemoney ,
          Qty ,
          Price ,
          Total ,
          CostTotal ,
          SaleTotal ,
          TaxTotal ,
          DtypeID ,
          AtypeID ,
          ShareFee,
          SShareFee,
          nqty ,
          baseqty,
          giftqty,
          giftcosttotal
FROM(
    SELECT r.PtypeId,
    r.BillNumberId,
    Dealbtypeid,
    r.ETypeID,
    KtypeId,
    preferencemoney,
    Qty,
    Convert( NUMERIC(24, 10) ,r.SalePrice) AS Price,
    Convert( NUMERIC(24, 10) ,r.Total) AS Total,
	CostTotal,
	Convert( NUMERIC(24, 10) ,r.SaleTotal) AS SaleTotal,
	Convert( NUMERIC(24, 10) ,r.TaxTotal) AS TaxTotal,
    DtypeID,
    AtypeID,
    ShareFee,
    SShareFee,
    NQty,
	Convert( NUMERIC(24, 10) ,r.Qty) AS baseqty,
	CASE 
		WHEN r.isgift=1 AND r.SalePrice=0 THEN Convert( NUMERIC(24, 10) ,r.Qty) 
		ELSE 0
	END AS giftqty,
	i.giftcosttotal
    FROM dbo.RetailCombinationBill r
    LEFT JOIN dbo.BillIndex b ON r.BillNumberId=b.BillNumberId 
    LEFT JOIN #Money i ON r.BillNumberId=i.BillNumberId AND I.pindexid = r.pindexid
    UNION ALL
    SELECT ps.PtypeId,
    ps.BillNumberId,
    b.DealBTypeID,
    b.etypeid,
    b.ktypeid,
    b.preferencemoney,
    ps.Qty,
    Convert( NUMERIC(24, 10) ,ps.SalePrice) AS Price,
    Convert( NUMERIC(24, 10) ,ps.Total) AS Total,
	Convert( NUMERIC(24, 10) ,i.CostTotal) AS CostTotal,
	Convert( NUMERIC(24, 10) ,ps.SaleTotal) AS SaleTotal,
	Convert( NUMERIC(24, 10) ,ps.TaxTotal) AS TaxTotal,
	b.DTypeId,
	b.atypeid,
	Convert( NUMERIC(24, 10) ,i.ShareFee) AS ShareFee,
    Convert( NUMERIC(24, 10) ,i.SShareFee) AS SShareFee,
	ps.NQty,
	Convert( NUMERIC(24, 10) ,ps.Qty) AS baseqty,
	CASE 
		WHEN ps.isgift=1 AND ps.SalePrice=0 THEN Convert( NUMERIC(24, 10) ,ps.Qty) 
		ELSE 0
	END AS giftqty,
	i.giftcosttotal
    FROM PT_Combin_SaleBill ps
    LEFT JOIN dbo.BillIndex b ON ps.BillNumberId=b.BillNumberId
    LEFT JOIN #Money i ON i.BillNumberId = ps.BillNumberId AND I.pindexid = PS.pindexid
    UNION ALL
    SELECT psb.PtypeId,
    psb.BillNumberId,
    b.DealBTypeID,
    b.etypeid,
    b.ktypeid,
    b.preferencemoney,
    -psb.Qty,
    Convert( NUMERIC(24, 10) ,psb.SalePrice) AS Price,
    -Convert( NUMERIC(24, 10) ,psb.Total) AS Total,
	i.CostTotal,
	-Convert( NUMERIC(24, 10) ,psb.SaleTotal) AS SaleTotal,
	-Convert( NUMERIC(24, 10) ,psb.TaxTotal) AS TaxTotal,
	b.DTypeId,
	b.atypeid,
	i.ShareFee,
    i.SShareFee,
	psb.NQty,
	-Convert( NUMERIC(24, 10) ,psb.Qty) AS baseqty,
	CASE 
		WHEN psb.isgift=1 AND psb.SalePrice=0 THEN -Convert( NUMERIC(24, 10) ,psb.Qty) 
		ELSE 0
	END AS giftqty,
	i.giftcosttotal
	FROM PT_Combin_SaleBackBill psb 
	LEFT JOIN dbo.BillIndex b ON psb.BillNumberId=b.BillNumberId
	LEFT JOIN #Money i ON psb.BillNumberId=i.BillNumberId AND I.pindexid = psb.pindexid
	) AS A WHERE BillNumberId IN (SELECT BillNumberId FROM #BillIndex)
	
-- INSERT #InoutStockTable
SET @strTemp = '
INSERT INTO #InoutStockTable(PtypeID,BillNumberId,Dealbtypeid,EtypeID,KtypeID,preferencemoney,Qty,Price,Total,CostTotal,SaleTotal,TaxTotal,DtypeID,AtypeID,sharefee,sshareFee,nqty,baseqty,giftqty,giftcosttotal)
SELECT 
PtypeID,
BillNumberId,
dealbtypeid,
EtypeID,
KtypeID,
preferencemoney,
Qty,
Price,
Total,
CostTotal,
SaleTotal,
TaxTotal,
DtypeID,
AtypeID,
sharefee,
ssharefee,
nqty,
baseqty,
giftqty,
giftcosttotal
FROM 
(
	SELECT
	          PtypeId ,
	          BillNumberId ,
	          Dealbtypeid ,
	          EtypeId ,
	          KtypeId ,
	          preferencemoney ,
	          Qty ,
	          Price ,
	          Total ,
	          CostTotal ,
	          SaleTotal ,
	          TaxTotal ,
	          DtypeID ,
	          AtypeID ,
	          ShareFee ,
	          SShareFee ,
	          nqty ,
	          baseqty ,
	          giftqty ,
	          giftcosttotal
	          FROM #InoutStockTableTemp I
	          INNER JOIN #Ptype pt ON I.PtypeId=pt.typeid
	'
	
    IF @dtypeid<>'' or @MDtypeid='-99999'
	BEGIN
		SELECT @strTemp=@strTemp+'	INNER JOIN #Dtype d ON I.dtypeid=d.typeid	'+CHAR(13)
	END
	
	IF ((NOT (@ktypeid ='00000' OR @ktypeid='')) OR @MKTypeID='-99999')
	BEGIN
		SET @strTemp += '	INNER JOIN #Ktype k ON I.ktypeid=k.typeid	'+CHAR(13)
	END
	
	IF ((NOT (@atypeid ='00000' OR @atypeid='')) OR @MATypeID='-99999')
	BEGIN
		SET @strTemp += '	INNER JOIN (SELECT DISTINCT btypeid FROM BillIndex BI 
	                                INNER JOIN btype B ON B.typeid=BI.btypeid
	                                INNER JOIN #Atype AT ON B.AreaTypeId=AT.typeid ) T ON T.btypeid=I.dealbtypeid'+CHAR(13)
	END

    SET @strTemp +='
	UNION ALL
	--发出商品出库单
	SELECT 
	a.PtypeID,
	a.BillNumberId,
	B1.DealBTypeID,
	B1.EtypeID,
	a.KtypeID,
	b.preferencemoney,
	-('+@tempsendqty+') AS Qty,
	'+@tempsendprice+' AS Price,
	CASE a.InvoiceQty
		WHEN 0 THEN a.total
		ELSE Convert( NUMERIC(24, 10) ,-('+@tempsendqty+') * (' + @tempsendprice + '))
	END AS Total,
	-('+@tempsendcosttotal+') AS CostTotal,
	CASE a.InvoiceQty
		WHEN 0 THEN a.SaleTotal
		ELSE Convert( NUMERIC(24, 10) ,-('+@tempsendqty+') * (' + @tempsendsaleprice + '))
	END AS SaleTotal,
	CASE a.InvoiceQty
		WHEN 0 THEN a.TaxTotal
		ELSE Convert( NUMERIC(24, 10) ,-('+@tempsendqty+') * (' + @tempsendtaxprice + '))
	END AS TaxTotal,
	B1.DtypeID,
	b.AtypeID,
	0 AS sharefee,
	0 as ssharefee,
	a.NQty - a.InvoiceNQty AS nqty,
	a.qty - a.InvoiceQty AS baseqty,
	CASE 
		WHEN a.isgift=1 AND a.DiscountPrice=0 THEN -(' + @tempsendqty + ')  
		ELSE 0
	END AS giftqty,
	CASE 
		WHEN a.isgift=1 AND a.DiscountPrice=0 THEN Convert( NUMERIC(24, 10) ,a.CostTotal - a.InvoiceCostTotal) 
		ELSE 0
	END AS giftcosttotal 

	FROM SendBill AS A
	INNER JOIN BillIndex AS B1 ON(B1.BillNumberId = A.BillNumberId)
	INNER JOIN #Billindex b ON(B1.BillnumberID = B.BillnumberID AND B1.BillType = B.BillType)
	INNER JOIN #Ptype p	ON a.ptypeid=p.typeid
	INNER JOIN ptype p1 on a.ptypeid=  p1.typeid 
	' + @temptable
	
	IF @dtypeid<>'' or @MDtypeid='-99999'
	BEGIN
		SELECT @strTemp=@strTemp+'	INNER JOIN #Dtype d ON B1.dtypeid=d.typeid	'+CHAR(13)
	END
	
	IF ((NOT (@ktypeid ='00000' OR @ktypeid='')) OR @MKTypeID='-99999')
	BEGIN
		SET @strTemp += '	INNER JOIN #Ktype k ON a.ktypeid=k.typeid	'+CHAR(13)
	END
	
	IF ((NOT (@atypeid ='00000' OR @atypeid='')) OR @MATypeID='-99999')
	BEGIN
		SET @strTemp += '	INNER JOIN (SELECT DISTINCT btypeid FROM BillIndex BI 
	                                INNER JOIN btype B ON B.typeid=BI.btypeid
	                                INNER JOIN #Atype AT ON B.AreaTypeId=AT.typeid ) T ON T.btypeid=B1.dealbtypeid'+CHAR(13)
	END
	
	SET @strTemp +='
	WHERE  
		B1.BillDate>='''+@startDate+''' AND 
		B1.BillDate<='''+@endDate+''' 
		AND B1.draft = 0 
		AND B1.redword = 0
		AND B1.ifYearBill = ''0''
	
	UNION ALL
	--发出商品退货单
	SELECT 
	a.PtypeID,
	a.BillNumberId,
	B1.DealBTypeID,
	B1.EtypeID,
	a.KtypeID,
	b.preferencemoney,
	'+@tempsendqty+' AS Qty,
	'+@tempsendprice+' AS Price,
	CASE a.InvoiceQty
		WHEN 0 THEN -a.total
		ELSE -Convert( NUMERIC(24, 10) ,-('+@tempsendqty+') * (' + @tempsendprice + '))
	END AS Total,
	'+@tempsendcosttotal+' AS CostTotal,
	CASE a.InvoiceQty
		WHEN 0 THEN -a.SaleTotal
		ELSE -Convert( NUMERIC(24, 10) ,-('+@tempsendqty+') * (' + @tempsendsaleprice + '))
	END AS SaleTotal,
	CASE a.InvoiceQty
		WHEN 0 THEN -a.TaxTotal
		ELSE -Convert( NUMERIC(24, 10) ,-('+@tempsendqty+') * (' + @tempsendtaxprice + '))
	END AS TaxTotal,
	B1.DtypeID,
	b.AtypeID,
	0 AS sharefee,
	0 as ssharefee,
	-(a.NQty - a.InvoiceNQty) AS nqty,
	-(a.qty - a.InvoiceQty) AS baseqty,
	CASE 
		WHEN a.isgift=1 AND a.DiscountPrice=0 THEN ' + @tempsendqty + '  
		ELSE 0
	END AS giftqty,
	CASE 
		WHEN a.isgift=1 AND a.DiscountPrice=0 THEN -Convert( NUMERIC(24, 10) ,a.CostTotal - a.InvoiceCostTotal) 
		ELSE 0
	END AS giftcosttotal 

	FROM SendBackBill AS A
	INNER JOIN BillIndex AS B1 ON(B1.BillNumberId = A.BillNumberId)
	INNER JOIN #Billindex b ON(B1.BillnumberID = B.BillnumberID AND B1.BillType = B.BillType)
	INNER JOIN #Ptype p	ON a.ptypeid=p.typeid
	INNER JOIN ptype p1 on a.ptypeid=  p1.typeid 
	' + @temptable
	
	IF @dtypeid<>'' or @MDtypeid='-99999'
	BEGIN
		SELECT @strTemp=@strTemp+'	INNER JOIN #Dtype d ON B1.dtypeid=d.typeid	'+CHAR(13)
	END
	
	IF ((NOT (@ktypeid ='00000' OR @ktypeid='')) OR @MKTypeID='-99999')
	BEGIN
		SET @strTemp += '	INNER JOIN #Ktype k ON a.ktypeid=k.typeid	'+CHAR(13)
	END
	
	IF ((NOT (@atypeid ='00000' OR @atypeid='')) OR @MATypeID='-99999')
	BEGIN
		SET @strTemp += '	INNER JOIN (SELECT DISTINCT btypeid FROM BillIndex BI 
	                                INNER JOIN btype B ON B.typeid=BI.btypeid
	                                INNER JOIN #Atype AT ON B.AreaTypeId=AT.typeid ) T ON T.btypeid=B1.dealbtypeid'+CHAR(13)
	END
	
	SET @strTemp +='
	WHERE  
		B1.BillDate>='''+@startDate+''' AND 
		B1.BillDate<='''+@endDate+''' 
		AND B1.draft = 0 
		AND B1.redword = 0
		AND B1.ifYearBill = ''0''
	
	UNION ALL
	--销售发货开票
	SELECT 
	a.PtypeID,
	a.BillNumberId,
	B1.DealBTypeID,
	B1.EtypeID,
	a.KtypeID,
	0 AS preferencemoney,
	-('+@tempqty+') AS Qty,
	'+@temprice+' AS Price,
	Convert( NUMERIC(24, 10) ,a.total) AS Total,
	-('+@tempreceiptcosttotal+') AS CostTotal,
	Convert( NUMERIC(24, 10) ,a.SaleTotal) AS SaleTotal,
	Convert( NUMERIC(24, 10) ,a.TaxTotal) AS TaxTotal,
	B1.DtypeID,
	b.AtypeID,
	0 AS sharefee,
	0 as ssharefee,
	a.NQty AS nqty,
	a.qty AS baseqty,
	CASE 
		WHEN a.isgift=1 AND a.price=0 THEN -(' + @tempqty + ')  
		ELSE 0
	END AS giftqty,
	CASE 
		WHEN a.isgift=1 AND a.price=0 THEN Convert( NUMERIC(24, 10) ,a.InvoiceCostTotal) 
		ELSE 0
	END AS giftcosttotal 

	FROM ReceiptBill AS A
	INNER JOIN ReceiptBillIndex AS B1 ON(B1.BillNumberId = A.BillNumberId AND B1.billtype = A.billtype)
	INNER JOIN #Billindex b ON(B1.BillnumberID = B.BillnumberID AND B1.BillType = B.BillType)
	INNER JOIN #Ptype p	ON a.ptypeid=p.typeid
	INNER JOIN ptype p1 on a.ptypeid=  p1.typeid 
	' + @temptable
	
	IF @dtypeid<>'' or @MDtypeid='-99999'
	BEGIN
		SELECT @strTemp=@strTemp+'	INNER JOIN #Dtype d ON B1.dtypeid=d.typeid	'+CHAR(13)
	END
	
	IF ((NOT (@ktypeid ='00000' OR @ktypeid='')) OR @MKTypeID='-99999')
	BEGIN
		SET @strTemp += '	INNER JOIN #Ktype k ON a.ktypeid=k.typeid	'+CHAR(13)
	END
	
	
	SET @strTemp +='
	WHERE  
		B1.BillDate>='''+@startDate+''' AND 
		B1.BillDate<='''+@endDate+''' 
		AND B1.draft = 0 
		AND B1.billtype = 405 
		AND B1.redword = 0
		AND B1.ifYearBill = ''0''
	'

SET @strTemp += '
) AS T
'	
EXEC(@strTemp)

DECLARE @COL1 varchar(200)='',
		@COL2 varchar(100)='',
		@COL3 varchar(100)='',
		@GroupCol varchar(200)='',
		@mysql   VARCHAR(max)


SET @mysql=' '
exec(@mysql)
  
--select * from #InoutStockTable

	SET	@GroupCol =',entrycode,a.ufullname,a.assistantfullname,a.basefullname,a.unitRelation,a.jlunit'
	SET	@COL1 =',entrycode,a.ufullname,a.assistantfullname,a.basefullname,a.unitRelation,a.jlunit'  
IF @chkPe ='1'  
begin 
    SET @mysql=' 
          select '+@chvColName1+',sum(preferencemoney) preferencemoney INTO #preferencemoney
      from (select '+@chvColName1+',case when billtype=45 or billtype=215 then -max(b.preferencemoney) else max(b.preferencemoney) end preferencemoney from #InoutStockTable a  inner join #billindex b on a.BillnumberID=b.BillnumberID group by a.BillnumberID ,billtype,'+@chvColName1+')
       a group by '+@chvColName1+'
       
       UPDATE #MainType SET preferencemoney =ISNULL(a.preferencemoney,0)
				FROM #MainType b inner JOIN #preferencemoney a
				on b.typeid='+@chvColName1+' '
				--print(@mysql)
				EXEC(@mysql)
	SET @COL1 =@COL1+',ISNULL(a.preferencemoney,0) as preferencemoney'
	SET @COL3=@COL3+'-ISNULL(a.preferencemoney,0)'
	SET	@GroupCol = @GroupCol+',ISNULL(a.preferencemoney,0)'
 END

DECLARE @SQL varchar(8000),@config int=0
SELECT @config=Value FROM Userconfig WHERE ConfigName='sharefee'

IF @chkXs='1' --显示销售为0数据
	SET @SQL ='		
				SELECT  a.typeid as typeid,
						a.deleted,
						a.usercode,
						a.standard,
						a.type,
						SUM(ISNULL(b.qty,0)) as SUM_Qty,
						SUM(ISNULL(b.giftqty,0)) as gift_qty,
						SUM(CASE WHEN ISNULL(b.Price,0)=0 THEN ISNULL(b.Qty,0)	ELSE 0	END) AS ZeroPriceQty,
				
		CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE cast( SUM(ISNULL(b.total,0))as NUMERIC(24, 10)) /cast( SUM(ISNULL(b.qty,0)) as NUMERIC(24, 10))END as Price,				
						SUM(ISNULL(b.total,0)) as SUM_Total,
						
		CASE WHEN ISNULL(SUM(ISNULL(b.giftqty,0)),0)=0 THEN 0 ELSE  cast( SUM(ISNULL(b.giftcosttotal,0))as NUMERIC(24, 10))/cast( SUM(ISNULL(b.giftqty,0))as NUMERIC(24, 10)) END as giftprice,				
						SUM(ISNULL(b.giftcosttotal,0)) as giftcosttotal,
						SUM(ISNULL(b.TaxTotal,0)) as SUM_TaxTotal,
						SUM(ISNULL(b.TaxTotal,0))-SUM(ISNULL(b.total,0)) as TaxGe,
						CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  cast( SUM(ISNULL(b.CostTotal,0))as NUMERIC(24, 10))/cast( SUM(ISNULL(b.qty,0))as NUMERIC(24, 10)) END as CostPrice,	
						SUM(ISNULL(b.CostTotal,0)) as SUM_CostTotal,
						SUM(ISNULL(b.Total,0))-SUM(ISNULL(b.CostTotal,0))'+CASE @config WHEN 1 THEN '-SUM(ISNULL(b.ssharefee,0))'ELSE '' END+@COL2+@COL3+' as SUM_MaoLi,
					
		CASE WHEN SUM(ISNULL(b.Total,0))=0 THEN 0 ELSE 
				cast(	(SUM(ISNULL(b.Total,0))-SUM(ISNULL(b.CostTotal,0))'	+
					CASE @config WHEN 1 THEN '-ISNULL(SUM(ISNULL(b.ssharefee,0)),0)'ELSE '' END+@COL2+@COL3+') as NUMERIC(24, 10))/cast( SUM(ISNULL(b.Total,0))as NUMERIC(24, 10))*100 end as SUM_MaoLiLu,								
						SUM(ISNULL(b.sharefee,0)) as sharefee,
						SUM(ISNULL(b.SaleTotal,0)) as SUM_DiscountTotal,
						SUM(ISNULL(b.nqty,0)) as nqty,
						SUM(ISNULL(b.baseqty,0)) AS baseqty
						'+@COL1+',
						customassist=dbo.F_GetCustomAssist( a.typeid, SUM(ISNULL(b.baseqty,0)))
				     FROM #MainType a
				     Left JOIN  #InoutStockTable b  ON a.TypeID =  b.' + @chvColName +' 
				     GROUP BY 
						a.typeid,
						a.deleted,
						a.usercode,
						a.fullname,
						a.standard,
						a.type
						'+@GroupCol +' ORDER BY a.UserCode ASC'
ELSE
	SET @SQL ='		
				SELECT 
					    a.typeid as typeid,
						a.deleted,
						a.usercode,
						a.fullname,
						a.standard,
						a.type,
						SUM(ISNULL(b.qty,0)) as SUM_Qty,
						SUM(ISNULL(b.giftqty,0)) as gift_qty,
						SUM(CASE WHEN ISNULL(b.Price,0)=0 THEN ISNULL(b.Qty,0)	ELSE 0	END) AS ZeroPriceQty,
							CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE cast( SUM(ISNULL(b.total,0))as NUMERIC(24, 10)) /cast( SUM(ISNULL(b.qty,0)) as NUMERIC(24, 10))END as Price,	
			      CASE WHEN ISNULL(SUM(ISNULL(b.giftqty,0)),0)=0 THEN 0 ELSE  cast( SUM(ISNULL(b.giftcosttotal,0))as NUMERIC(24, 10))/cast( SUM(ISNULL(b.giftqty,0))as NUMERIC(24, 10)) END as giftprice,
						SUM(ISNULL(b.giftcosttotal,0)) as giftcosttotal,				
						SUM(ISNULL(b.total,0)) as SUM_Total,
						SUM(ISNULL(b.TaxTotal,0)) as SUM_TaxTotal,
						SUM(ISNULL(b.TaxTotal,0))-SUM(ISNULL(b.total,0)) as TaxGe,
						CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  cast( SUM(ISNULL(b.CostTotal,0))as NUMERIC(24, 10))/cast( SUM(ISNULL(b.qty,0))as NUMERIC(24, 10)) END as CostPrice,
						SUM(ISNULL(b.CostTotal,0)) as SUM_CostTotal,
						SUM(ISNULL(b.Total,0))-SUM(ISNULL(b.CostTotal,0))'+CASE @config WHEN 1 THEN '-SUM(ISNULL(b.ssharefee,0))'ELSE '' END+@COL2+@COL3+' as SUM_MaoLi,
						CASE WHEN SUM(ISNULL(b.Total,0))=0 THEN 0 ELSE 
				cast(	(SUM(ISNULL(b.Total,0))-SUM(ISNULL(b.CostTotal,0))'	+
					CASE @config WHEN 1 THEN '-ISNULL(SUM(ISNULL(b.ssharefee,0)),0)'ELSE '' END+@COL2+@COL3+') as NUMERIC(24, 10))/cast( SUM(ISNULL(b.Total,0))as NUMERIC(24, 10))*100 end as SUM_MaoLiLu,
						SUM(ISNULL(b.Total,0))-SUM(ISNULL(b.CostTotal,0))'+CASE @config WHEN 1 THEN '-SUM(ISNULL(b.ssharefee,0))'ELSE '' END+@COL3+' as SUM_PEMaoLi,
						Convert( NUMERIC(24, 10) ,CASE WHEN SUM(ISNULL(b.Total,0))=0 THEN 0 ELSE (SUM(ISNULL(b.Total,0))-SUM(ISNULL(b.CostTotal,0))'+CASE @config WHEN 1 THEN '-SUM(ISNULL(b.ssharefee,0))'ELSE '' END+@COL3+')/SUM(ISNULL(b.Total,0))*100 end) as SUM_PEMaoLiLu,
						SUM(ISNULL(b.sharefee,0)) as sharefee,
						SUM(ISNULL(b.SaleTotal,0)) as SUM_DiscountTotal,
						SUM(ISNULL(b.nqty,0)) as nqty,
						SUM(ISNULL(b.baseqty,0)) AS baseqty
						'+@COL1+',
												customassist=dbo.F_GetCustomAssist(a.typeid  , SUM(ISNULL(b.baseqty,0)))
				     FROM #MainType a
				     INNER JOIN  #InoutStockTable b  ON a.TypeID =  b.' + @chvColName +'
				     
				     GROUP BY 
						a.typeid,
						a.deleted,
						a.usercode,
						a.fullname,
						a.standard,
						a.type
						'+@GroupCol +' ORDER BY a.UserCode ASC  '

--print (@SQL)
EXEC(@SQL)

DROP TABLE #BillIndex1,#BillIndex,#Billtype,#Atype,#Dealbtype,#Ptype,#Btype,#Etype,#Ktype,#Dtype,#Maintype,#InoutStockTable,#Stype,#Money,#InoutStockTableTemp,#InOutStockTableBill
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CommissionBusinessTypeSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CommissionBusinessTypeSelector]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-5-15
	描述：高级提成--业务类别选择，Selector
-------------------------------------------*/
CREATE PROCEDURE Web_CommissionBusinessTypeSelector
(
	@OperatorID			VARCHAR(50),
	@Filter				VARCHAR(256),  --筛选条件
	@TypeId				VARCHAR(100),  --基本信息的Id
	@IsNext				INT			   --1=下一层 0=上一层
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)
DECLARE @SonNum INT
DECLARE @ParId	VARCHAR(100)

IF @TypeId = '' SET @TypeId = '00000'

CREATE TABLE #BaseInfo
(
	TypeID		VARCHAR(100),
	ParId		VARCHAR(100),
	SonNum		INT,		
	FullName	VARCHAR(256)
)

SET @SQL = 'INSERT INTO #BaseInfo(TypeId,ParId,SonNum,FullName) 
				SELECT TypeId,ParId,SonNum,FullName FROM CommissionType ' 

EXEC(@SQL)

SELECT @SonNum = SonNum,@ParId=ParId FROM #BaseInfo WHERE TypeId = @TypeId
DELETE #BaseInfo WHERE TypeID = '00000'
	
IF @Filter = ''
BEGIN
	IF @IsNext = '0'
		BEGIN
			SELECT * FROM #BaseInfo WHERE ParId = @ParId ORDER BY FullName
		END
	ELSE --下一层
		BEGIN			
			IF @SonNum = 0
				SELECT * FROM #BaseInfo WHERE SonNum = 0 AND TypeId = @TypeId ORDER BY FullName
			ELSE
				BEGIN
					SELECT * FROM #BaseInfo WHERE ParId = @TypeId ORDER BY FullName		
				END
		END
END
ELSE
BEGIN
	SET @SQL = '
		SELECT * FROM #BaseInfo
		WHERE	SonNum = 0 
				AND FullName LIKE ''%'+@Filter+'%'' '
END


EXEC(@SQL)


DROP TABLE #BaseInfo


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CommissionBusinessTypeSelectorAccurate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CommissionBusinessTypeSelectorAccurate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：WG
	日期：2014-5-15
	描述：高级提成--业务类别选择，Selector 精确匹配
	
-------------------------------------------*/
CREATE PROCEDURE Web_CommissionBusinessTypeSelectorAccurate
(
	@Filter		VARCHAR(256),	---输入的条件
	@OperatorId VARCHAR(100)
	
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #BaseInfo
(
	TypeID		VARCHAR(100),
	ParId		VARCHAR(100),
	SonNum		INT,			
	FullName	VARCHAR(256)
)

DECLARE @SQL VARCHAR(MAX)
DECLARE @MainSql VARCHAR(500)

SET @MainSql = 'INSERT INTO #BaseInfo(TypeId,ParId,SonNum,FullName) 
			SELECT TOP 2 TypeId,ParId,SonNum,FullName FROM CommissionType WHERE sonnum = 0 '

SET @SQL = @MainSql + ' AND FullName = '''+@Filter+''' '
EXEC(@SQL)

IF @@ROWCOUNT = 0
BEGIN
	SET @SQL += @MainSql + ' and  FullName LIKE ''%'+@Filter+'%'' '
	EXEC(@SQL)
END

SELECT *FROM #BaseInfo

DROP TABLE #BaseInfo

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_CommissionCal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_CommissionCal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-4-24
	描述：提成计算 并生成单据
-------------------------------------------*/
CREATE PROCEDURE Web_CommissionCal
(
	@StartDate			VARCHAR(50)='',
	@EndDate			VARCHAR(50)='',
	@StypeID			VARCHAR(MAX),
	@SchemeID			NUMERIC(18,0),
	@clientip			VARCHAR(200)='',
	@OperatorID			VARCHAR(50),
	@CommissionType		INT,			--1=规则提成  2= 参照计划提成
	@ESalePlanID		VARCHAR(50),	--职员销售计划ID
	@SaleTimeId			INT,			--销售时段ID
	@BillCode			VARCHAR(500) OUT
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--提成明细
CREATE TABLE #ResultDeatil
(
	StypeID			VARCHAR(50),
	EtypeID			VARCHAR(50),
	PtypeID			VARCHAR(50),
	SumValues		NUMERIC(24, 10),
	IsQty			INT			--0=金额统计 1=数量统计
)

--提成汇总的数据
CREATE TABLE #ResultData
(
	StypeID				VARCHAR(50),
	EtypeID				VARCHAR(50),
	Qty					NUMERIC(24, 10) ,
	Total				NUMERIC(24, 10) ,
	CommissionTotal		NUMERIC(24, 10) 
)

CREATE TABLE #LeaderData
(
	StypeID				VARCHAR(50),
	CommissionTypeID	VARCHAR(50),
	IsQty				INT,
	SumValues			NUMERIC(24, 10) 
)

--提成计算--2参照计划提成，对时间的处理
IF @CommissionType = 2
BEGIN
	SELECT @StartDate = StartTime,@EndDate = EndTime FROM SaleTime WHERE ID = @SaleTimeId
	IF @StartDate = '' OR @EndDate = ''
	BEGIN
		RAISERROR('信息被更改，需重新选择！',16,1)
		RETURN
	END
END

--分支机构
CREATE TABLE #Stype(ID NUMERIC(18,0) IDENTITY(1,1) ,TypeID	VARCHAR(50))
INSERT #Stype(TypeID) SELECT * FROM f_split(@StypeID,',')

--提成方案ID
--参考计划提成ID
DECLARE @CommissionRuleID NUMERIC(22,0),
		@ReferencePlanID NUMERIC(22,0)

SELECT @CommissionRuleID = CommissionRuleID,@ReferencePlanID = ReferencePlanID
FROM CommissionScheme 
WHERE BillNumberId = @SchemeID AND IsStop <> 1

IF @CommissionRuleID IS NULL OR @ReferencePlanID IS NULL
BEGIN
	RAISERROR('提成方案已被停用！',16,1)
	RETURN 
END

CREATE TABLE #CommissionRuleLeader
(
	BillNumberId			NUMERIC(18,0)	NOT NULL,
	CommissionTypeID		VARCHAR(50)		NOT NULL,	--提成类别
	MinRegion				NUMERIC(24, 10) NOT NULL,	--下限
	MaxRegion				NUMERIC(24, 10) NOT NULL,	--上限
	Proportion				NUMERIC(24, 10) NULL,		--提成率
	Percentage				NUMERIC(24, 10) NULL		--固定提成额
)

--处理上级参与提成时，选择全部的类型提成
IF EXISTS (SELECT * FROM CommissionRuleLeader WHERE BillNumberId = @CommissionRuleID AND CommissionTypeID='00000')
BEGIN
	INSERT #CommissionRuleLeader(BillNumberId,CommissionTypeID,MinRegion,MaxRegion,Proportion,Percentage)
	SELECT c.BillNumberId, t.TypeID, c.MinRegion, c.MaxRegion, c.Proportion,c.Percentage
	FROM CommissionType t,CommissionRuleLeader c
	WHERE	c.BillNumberId = @CommissionRuleID
			AND T.TypeID <> '00000'
			
	DELETE #CommissionRuleLeader WHERE CommissionTypeID = '00000'
END
ELSE
BEGIN
	INSERT #CommissionRuleLeader(BillNumberId,CommissionTypeID,MinRegion,MaxRegion,Proportion,Percentage)
	SELECT BillNumberId,CommissionTypeID,MinRegion,MaxRegion,Proportion,Percentage
	FROM CommissionRuleLeader
	WHERE BillNumberId = @CommissionRuleID
END

DECLARE	@SQL		VARCHAR(MAX)='',
		@ColumnName VARCHAR(100),		--要统计的列名 或者公式
		@BillTypes	VARCHAR(500),		--单据类型
		@Bcost		VARCHAR(50)='',		--成本条件
		@Scost		VARCHAR(50) ='',	--销售条件
		@IsSalesTC	INT, 				--是否是促销商品 1=是促销 0=不是 
		@IsBelowCost INT				--是否低于成本价  1=低于成本价 0=不低于成本价

	
--提成规则计算
IF @CommissionRuleID > 0 AND @CommissionType = 1
BEGIN
	DECLARE @IsUseEtypeCommission	INT,		--职员提成比例 1=勾选
			@ECommissionType		INT,		--提成人类型  1=业务员   2=上级参与提成
			@CommissionStandard		INT,		--1=折后金额 2=价税合计 3=销售数量 4=销售毛利 5=回款额 6=维修费7=获利金额
			@CommissionStyle		INT			--提成方式    1=单一提成 2=区间提成			

			
	SELECT  @IsUseEtypeCommission=IsUseEtypeCommission ,@ECommissionType=ECommissionType,
			@CommissionStyle=CommissionStyle,@CommissionStandard = CommissionStandard,@IsSalesTC=SalesFlag,@IsBelowCost=BelowCostFlag
	FROM CommissionRule WHERE BillNumberId = @CommissionRuleID
	
	if(isnull(@IsBelowCost,0)=1) --低于成本金额不参与提成 modify by 20160801
		SET @Bcost=' and abs(i.costtotal)<abs(i.ntotal)'--成本金额<折后金额
	if(isnull(@IsSalesTC,0)=1) --促销商品销售额不参与提成 modify by 20160801		
	SET @Scost=' and isnull(r.promotype,0) <= 0 '
	
	--筛选单据类型
	IF @CommissionStandard = 5
			SET @BillTypes = '(4,11,45,141,160,305,215,12,46,93)'
	ELSE IF @CommissionStandard IN(1,2,3,4)
		SET @BillTypes = '(11,45,141,160,305,215,12,46)'
	ELSE IF @CommissionStandard =6
		SET @BillTypes = '(167,168,172)'
	ELSE IF @CommissionStandard = 7
		SET @BillTypes = '(150)'


	--提成基准：获利金额（统计的单据类型：获利核算执行单）

			
	-- 提成基准：折后金额、价税合计、销售毛利（统计的单据类型：销售出库单、销售退货单、销售换货单、零售单、零售退货单、委托代销结算单）
	-- 9.8 修改，零售单和零售退货单取表体经手人
		
	IF @CommissionStandard IN (1,2,4)
	BEGIN
		IF @CommissionStandard = 1
			SET @ColumnName = 'I.Total'
		ELSE IF @CommissionStandard = 2
			SET @ColumnName = 'I.TaxTotal'
		ELSE IF @CommissionStandard = 4
			SET @ColumnName = 'I.Total - I.CostTotal'		

		
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,I.EtypeId,I.PtypeId, -SUM(' + @ColumnName + '),0
						FROM InOutstocktable I
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
							AND	( (B.billtype NOT IN(305,215,11,12)) OR (B.billtype IN(305,215) AND b.preferencemoney<>0))  
						GROUP BY B.StypeID,I.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
		 
		--305
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,R.EtypeId,I.PtypeId, -SUM(' + @ColumnName + '),0
						FROM InOutstocktable I
						INNER JOIN retailBill r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid 
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
							AND	B.billtype=305' +@Scost+'
							AND b.preferencemoney=0  
						 GROUP BY B.StypeID,r.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
		
		 --215
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,r.EtypeId,I.PtypeId, -SUM(' + @ColumnName + '),0
						FROM InOutstocktable I
						INNER JOIN RetailBackBill r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
							AND	B.billtype=215
							AND b.preferencemoney=0  
						GROUP BY B.StypeID,r.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
		
		--11 销售出库单
				
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,i.EtypeId,I.PtypeId, -SUM(' + @ColumnName + '),0
						FROM InOutstocktable I
						INNER JOIN salebill r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
							AND	B.billtype=11'+@Scost+'
						GROUP BY B.StypeID,I.EtypeId,I.PtypeId '
		EXEC(@SQL)

		
		 --12 组合品销售出库单
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,i.EtypeId,I.PtypeId, -SUM(' + @ColumnName + '),0
						FROM InOutstocktable I
						INNER JOIN PT_Combin_SaleBillDetail r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
							AND	B.billtype=12'+@Scost+'
						GROUP BY B.StypeID,I.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
	END
	ELSE IF @CommissionStandard IN(7)
	BEGIN
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,B.EtypeId,I.PtypeId, SUM(I.Total),0
						FROM Advantage I
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
						GROUP BY B.StypeID,B.EtypeId,I.PtypeId '
		EXEC(@SQL)
	END
	ELSE IF @CommissionStandard IN (3)
	BEGIN
		--销售数量（统计的单据类型：销售出库单、销售退货单、销售换货单、零售单、零售退货单、委托代销结算单）
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,I.EtypeId,I.PtypeId,-SUM(I.qty),1
						FROM InOutstocktable I
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
						    AND	( (B.billtype NOT IN(305,215,11,12)) OR (B.billtype IN(305,215) AND b.preferencemoney<>0))  
						GROUP BY B.StypeID,I.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
		--305
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,R.EtypeId,I.PtypeId,-SUM(I.qty),1
						FROM InOutstocktable I
						INNER JOIN RetailBill r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid 
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
						    AND	B.billtype=305' +@Scost+' AND b.preferencemoney=0 
					  GROUP BY B.StypeID,r.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
		--215
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,R.EtypeId,I.PtypeId,-SUM(I.qty),1
						FROM InOutstocktable I
						INNER JOIN RetailBackBill r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid 
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
						    AND	B.billtype=215 AND b.preferencemoney=0 
					  GROUP BY B.StypeID,r.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
		--11
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,i.EtypeId,I.PtypeId,-SUM(I.qty),1
						FROM InOutstocktable I
						INNER JOIN salebill r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
						    AND	B.billtype=11'+@Scost+'
					   GROUP BY B.StypeID,I.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
	    --12
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,i.EtypeId,I.PtypeId,-SUM(I.qty),1
						FROM InOutstocktable I
						INNER JOIN PT_Combin_SaleBillDetail r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId 
						INNER JOIN #Stype S ON S.typeid = B.stypeid
						WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
						    AND	B.billtype=12'+@Scost+'
					   GROUP BY B.StypeID,I.EtypeId,I.PtypeId '
		EXEC(@SQL)
		
		
	END
	ELSE IF @CommissionStandard IN (5,6)
	BEGIN
		--回款额（统计的单据类型：销售出库单、销售退货单、销售换货单、零售单、零售退货单、委托代销结算单、收款单）
		--维修费（统计的单据类型：维修取件单、整机更换单、上门维修单）
		IF @CommissionStandard = 5
			SET @ColumnName = 'CASE WHEN B.BillType IN(11,160,305,141,4,12,93) THEN B.totalinmoney ELSE -B.totalinmoney END'
		ELSE IF @CommissionStandard = 6
			SET @ColumnName = 'B.totalmoney'
		
		SET @SQL = ' INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
					 SELECT B.StypeID,B.etypeid,''00000'' ,SUM('+@ColumnName+'),0 
					 FROM BillIndex B 
					 INNER JOIN #Stype S ON S.typeid = B.stypeid
					 WHERE	B.draft=0 AND B.BillType IN '+@BillTypes+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
							AND RedWord = 0 AND ifcheck = ''t''
					 GROUP BY B.StypeID,B.etypeid '
		EXEC(@SQL)
	END
		
	--计算上级提成
	IF @ECommissionType = 2
	BEGIN
		IF 	@CommissionStyle = 2	--区间
		BEGIN
			--先合并上级下面明细的数据 不然区间不准确
			;WITH LeaderData AS
			(
				SELECT DISTINCT R.StypeID,R.EtypeID,C.CommissionTypeID,R.IsQty,R.SumValues
				FROM (
					SELECT	StypeID, EtypeID, IsQty, SUM(SumValues) AS SumValues
						FROM #ResultDeatil
						GROUP BY StypeID,EtypeID,IsQty
					) R
				 ,#CommissionRuleLeader C,CommissionType T,EtypeCommissionType E
				WHERE	C.BillNumberId=@CommissionRuleID
						AND E.CommissionTypeID LIKE C.CommissionTypeID + '%'
						AND E.ETypeID = R.EtypeID
						AND T.TypeID = C.CommissionTypeID
			)
			
			INSERT #LeaderData(StypeID,CommissionTypeID,IsQty,SumValues)
			SELECT StypeID,CommissionTypeID,IsQty,ISNULL(SUM(SumValues),0) 
			FROM LeaderData 
			GROUP BY StypeID,CommissionTypeID,IsQty
			
			INSERT #ResultData(StypeID,EtypeID,Qty,Total,CommissionTotal)
			SELECT	R.StypeID,
					E.EtypeID,
					CASE WHEN R.IsQty =1 THEN R.SumValues ELSE 0 END AS Qty,
					CASE WHEN R.IsQty =0 THEN R.SumValues ELSE 0 END AS Total,
					CASE WHEN R.IsQty =1 THEN R.SumValues*C.Proportion+C.Percentage ELSE R.SumValues*C.Proportion/100+C.Percentage END AS CommissionTotal
			FROM #CommissionRuleLeader C,#LeaderData R,CommissionType E
			WHERE	C.BillNumberId=@CommissionRuleID
					AND C.CommissionTypeID = E.TypeID
					AND C.CommissionTypeID = R.CommissionTypeID
					AND R.SumValues >=C.MinRegion AND R.SumValues < C.MaxRegion
		END
		ELSE IF @CommissionStyle = 1	--单一
		BEGIN
			INSERT #ResultData(StypeID,EtypeID,Qty,Total,CommissionTotal)
			SELECT	R.StypeID,
					T.EtypeID,
					CASE WHEN R.IsQty =1 THEN SumValues ELSE 0 END AS Qty,
					CASE WHEN R.IsQty =0 THEN SumValues ELSE 0 END AS Total,
					CASE WHEN R.IsQty =1 THEN SumValues*C.Proportion+C.Percentage ELSE SumValues*C.Proportion/100+C.Percentage END AS CommissionTotal
			FROM(
					--需合并，不然比例是按照明细来筛选的
					SELECT	StypeID, EtypeID, IsQty, SUM(SumValues) AS SumValues,Ptypeid
					FROM #ResultDeatil
					GROUP BY StypeID,EtypeID,IsQty,Ptypeid
				) R
			,#CommissionRuleLeader C,CommissionType T,EtypeCommissionType E,CommissionRulePtype C1
			WHERE	C.BillNumberId=@CommissionRuleID
					AND E.CommissionTypeID LIKE C.CommissionTypeID + '%'
					AND E.ETypeID = R.EtypeID
					AND T.TypeID = C.CommissionTypeID
					AND C1.billnumberid=C.billnumberid
					AND (C1.Etypeid='00000' OR R.EtypeID LIKE  C1.Etypeid+'%') AND (C1.PtypeID ='00000' OR R.PtypeID LIKE C1.PtypeID+'%')
		END
	END
	
	--职员的提成
	IF @CommissionStyle = 2 --区间
	BEGIN
		INSERT #ResultData(StypeID,EtypeID,Qty,Total,CommissionTotal)
		SELECT	StypeID,
				EtypeID,
				SUM(CASE WHEN IsQty =1 THEN SumValues ELSE 0 END) AS Qty,
				SUM(CASE WHEN IsQty =0 THEN SumValues ELSE 0 END) AS Total,
				SUM(CASE WHEN IsQty =1 THEN SumValues*Proportion+Percentage ELSE SumValues*Proportion/100+Percentage END) AS CommissionTotal
		FROM(
				SELECT  R.StypeID,
						R.EtypeID,
						R.IsQty,
						SUM(R.SumValues) SumValues,
						C.Proportion,
						C.Percentage,
						C.MinRegion,
						C.MaxRegion
				FROM #ResultDeatil R 
				INNER JOIN CommissionRuleRegion C ON (C.Etypeid='00000' OR R.EtypeID LIKE  C.Etypeid+'%') 
				WHERE C.BillNumberId = @CommissionRuleID AND (C.PtypeID ='00000' OR R.PtypeID LIKE C.PtypeID+'%')
				GROUP BY R.StypeID, R.EtypeID, R.IsQty,C.Proportion,C.Percentage,C.MinRegion,C.MaxRegion
			) T 
		WHERE SumValues >=MinRegion AND SumValues < MaxRegion 
		GROUP BY StypeID, EtypeID
	END
	ELSE IF @CommissionStyle = 1 --单一
	BEGIN
		IF @IsUseEtypeCommission = 0
		BEGIN
			INSERT #ResultData(StypeID,EtypeID,Qty,Total,CommissionTotal)
			SELECT	R.StypeID,
					R.EtypeID,
					SUM(CASE WHEN R.IsQty =1 THEN R.SumValues ELSE 0 END) AS Qty,
					SUM(CASE WHEN R.IsQty =0 THEN R.SumValues ELSE 0 END) AS Total,
					SUM(CASE WHEN R.IsQty =1 THEN R.SumValues*C.Proportion ELSE R.SumValues*C.Proportion/100 END) AS CommissionTotal
			FROM #ResultDeatil R 
			INNER JOIN CommissionRulePtype C ON 
					(C.Etypeid='00000' OR R.EtypeID LIKE  C.Etypeid+'%') AND (C.PtypeID ='00000' OR R.PtypeID LIKE C.PtypeID+'%')
			WHERE C.BillNumberId = @CommissionRuleID
			GROUP BY R.StypeID, R.EtypeID
		END
		ELSE --使用职员档案上的提成
		BEGIN
			INSERT #ResultData(StypeID,EtypeID,Qty,Total,CommissionTotal)
			SELECT	R.StypeID,
					R.EtypeID,
					SUM(CASE WHEN R.IsQty =1 THEN R.SumValues ELSE 0 END) AS Qty,
					SUM(CASE WHEN R.IsQty =0 THEN R.SumValues ELSE 0 END) AS Total,
					SUM(CASE WHEN R.IsQty =1 THEN R.SumValues*E.tichengRate ELSE R.SumValues*E.tichengRate/100 END) AS CommissionTotal
			FROM #ResultDeatil R 
			INNER JOIN employee E ON E.typeId = R.EtypeID
			INNER JOIN CommissionRulePtype C ON 
					(C.Etypeid='00000' OR R.EtypeID LIKE  C.Etypeid+'%') AND (C.PtypeID ='00000' OR R.PtypeID LIKE C.PtypeID+'%')
			WHERE C.BillNumberId = @CommissionRuleID
			GROUP BY R.StypeID, R.EtypeID
		END
	END
END
ELSE IF @ReferencePlanID > 0 AND @CommissionType = 2  --参考计划提成
BEGIN
	TRUNCATE TABLE #ResultDeatil

	DECLARE @PlanStandard INT --提成基准  1=销售额 2=价税合计
			
	SELECT @PlanStandard=CommissionStandard,@IsSalesTC=SalesFlag,@IsBelowCost=BelowCostFlag 
	FROM ReferencePlanCommission WHERE BillNumberId = @ReferencePlanID
	
	if(isnull(@IsBelowCost,0)=1) --低于成本金额不参与提成 modify by 20160801
	SET @Bcost=' and abs(i.costtotal)<abs(i.ntotal)'--成本金额<折后金额
		if(isnull(@IsSalesTC,0)=1) --促销商品销售额不参与提成 modify by 20160801		
	SET @Scost=' and isnull(r.promotype,0) > 0 '
	--筛选单据类型
	SET @BillTypes = '(4,45,141,160,215)'
	
	IF @PlanStandard = 1
		SET @ColumnName = 'I.Total'
	ELSE IF @PlanStandard = 2
		SET @ColumnName = 'I.TaxTotal'
	
	--这里一定要合并，否则下面筛选数据时，就是对明细做的筛选，而不是对总金额做筛选。
	SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
					SELECT  B.StypeID,I.EtypeId,''00000'', -SUM(' + @ColumnName + '),0
					FROM InOutstocktable I
					INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId
					WHERE I.BillType IN '+@BillTypes+' 
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
					GROUP BY B.StypeID,I.EtypeId'
		EXEC(@SQL)
		
		--11
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,I.EtypeId,''00000'', -SUM(' + @ColumnName + '),0
						FROM InOutstocktable I
						INNER JOIN salebill r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId
						WHERE I.BillType =11'+@Scost+'
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
						GROUP BY B.StypeID,I.EtypeId'
		EXEC(@SQL)
		
		--305
		SET @SQL = '	INSERT #ResultDeatil(StypeID,EtypeID,PtypeID,SumValues,IsQty)
						SELECT  B.StypeID,I.EtypeId,''00000'', -SUM(' + @ColumnName + '),0
						FROM InOutstocktable I
						INNER JOIN PT_Combin_SaleBillDetail r ON I.BillNumberId=R.BillNumberId AND I.ID=R.ID
						INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId
						WHERE I.BillType =305'+@Scost+'
							AND B.draft=0'+@Bcost+'
							AND B.BillDate >= '''+@StartDate+''' AND B.BillDate <= '''+@EndDate+'''
					  GROUP BY B.StypeID,I.EtypeId'
		EXEC(@SQL)
		
	--提成人提成计算
	INSERT #ResultData(StypeID,EtypeID,Qty,Total,CommissionTotal)
	SELECT R.StypeID,R.EtypeID,0,SUM(R.SumValues),SUM(R.SumValues*C.Proportion/100+C.Percentage) AS CommissionTotal
	FROM #ResultDeatil R 
	INNER JOIN
	(
		SELECT  p.StypeID,p.EtypeID,d.PlanValue
		FROM EtypeSaleAllPlan e
		INNER JOIN EtypeSaleplan p ON p.EplanID = e.ID
		INNER JOIN DetailEtypeSaleplan d on d.EtypeSaleplanID = p.ID
		WHERE e.ID = @ESalePlanID AND  d.DetailTimeID = @SaleTimeId	
	) T ON T.StypeID = R.StypeID AND T.EtypeID = R.EtypeID
	INNER JOIN ReferencePlanCommissionPlan C ON 
			C.Etypeid='00000' OR R.EtypeID LIKE  C.Etypeid+'%'
	WHERE C.BillNumberId=@ReferencePlanID
					AND R.SumValues >= C.MinRegion AND R.SumValues < C.MaxRegion 
	GROUP BY R.StypeID,R.EtypeID
END

DELETE FROM #ResultData WHERE CommissionTotal = 0

--计算表头的合计
CREATE TABLE #SumData
(
	StypeID			VARCHAR(50),
	Qty				 NUMERIC(24, 10) ,
	Total			 NUMERIC(24, 10) ,
	CommissionTotal  NUMERIC(24, 10) 
)
INSERT #SumData(StypeID,Qty,Total,CommissionTotal)
SELECT  StypeID, SUM(Qty), SUM(Total), SUM(CommissionTotal)
FROM #ResultData
GROUP BY StypeID


--写表头的分支机构
CREATE TABLE #BillHeadStype(ID NUMERIC(18,0) IDENTITY(1,1) ,TypeID	VARCHAR(50))
INSERT #BillHeadStype(TypeID) SELECT DISTINCT a.TypeID FROM #Stype a INNER JOIN #ResultData r ON r.StypeID = a.TypeID

--插入数据库
IF NOT EXISTS(SELECT TOP 1 1 FROM #ResultData)
BEGIN
	RAISERROR('没有数据需要处理！',16,1)
	RETURN
END

--生成单据开始
DECLARE @BillDate	DATETIME,
		@DAY		VARCHAR(200),
		@MONTH		VARCHAR(200),
		@BillNumberId  NUMERIC(24, 10) ,
		@BillType	INT,
		@cefullname			VARCHAR(500)=''

DECLARE @sid VARCHAR(50),
		@MaxCount INT,
		@Count INT
	
DECLARE @Qty			  NUMERIC(24, 10) ,
		@Total			  NUMERIC(24, 10) ,
		@CommissionTotal  NUMERIC(24, 10)  
	
	
SELECT @MaxCount = MAX(ID) FROM #BillHeadStype
SET @Count = 1


--取当前时间
SET @BillDate=GETDATE()
SET @DAY=DAY(@BillDate)
SET @MONTH=MONTH(@BillDate)
SET @BillDate=(SELECT CONVERT (VARCHAR(10),@BillDate,120))
SET @BillType = 311 --提成单
SELECT @cefullname = @OperatorID

WHILE @Count <= @MaxCount
BEGIN
	SELECT @sid = TypeID FROM #BillHeadStype WHERE ID = @Count
	SELECT @Qty= Qty, @Total= Total, @CommissionTotal= CommissionTotal FROM #SumData WHERE StypeID = @sid
	SET @BillCode=''
	

	--生成单据编号
	EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'TCD',@BillDate,@sid,@BillCode OUT,'',@cefullname

	INSERT CommissionBillNew(BillCode,BillDate,CommissionStart,CommissionEnd,CommissionSchemeID,Checke,Checker,CheckeTime,CheckerTime,Explain,Comment,IsAuto,BillState,StypeID,Qty,Total,CommissionTotal,CommissionType,billtype)
	VALUES(@BillCode,@BillDate,@StartDate,@EndDate,@SchemeID,@OperatorID,'',GETDATE(),NULL,'','',1,1,@sid,@Qty,@Total,@CommissionTotal,@CommissionType,@billtype)

	SET @BillNumberId = @@IDENTITY	

	IF @BillNumberId IS NULL
	BEGIN
		RAISERROR('发生致命的错误！',16,1)
		RETURN 
	END

	INSERT CommissionBillNewDetail(BillNumberId,EtypeID,Qty,Total,CommissionTotal,Comment,DtypeID)
	SELECT @BillNumberId,R.EtypeID,ISNULL(SUM(R.Qty),0),ISNULL(SUM(R.Total),0),CAST(ISNULL(SUM(R.CommissionTotal),0) AS  NUMERIC(24, 10) ),'',
		   DtypeID = (SELECT TOP 1 e.dtypeid FROM employee e where e.typeId = R.EtypeID)
	FROM #ResultData R
	WHERE R.StypeID = @sid
	GROUP BY R.EtypeID

	 --写单据操作日志
	INSERT INTO BillOperateLog(billnumberid,operatetype,etypeid,OperateTime,ip) VALUES(@BillNumberId,'制单',@OperatorID,GETDATE(),@clientip)

	--保存单据编号的种子数
	EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode
	
	--循环下一条记录
	SET @Count += 1
END



--反写方案的使用状态
--使用状态  1=未引用  2=引用  3=部分完成 4=全部完成
--改起耍哟

UPDATE CommissionScheme SET UseState = 2 WHERE BillNumberId = @SchemeID

--DECLARE @UseState INT =0
--SELECT @UseState =UseState FROM  CommissionScheme WHERE BillNumberId = @SchemeID
--IF @UseState = 4
--	UPDATE CommissionScheme SET UseState = 3 WHERE BillNumberId = @SchemeID
--ELSE IF @UseState = 1
--	UPDATE CommissionScheme SET UseState = 2 WHERE BillNumberId = @SchemeID

DROP TABLE #ResultDeatil,#ResultData,#Stype,#BillHeadStype,#SumData,#CommissionRuleLeader,#LeaderData


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CommissionDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CommissionDetailQuery]
GO
















/*
	--作者：谢吉康
	--日期：2003-08-13
	--描述：代销职员查询明细
*/
CREATE        PROCEDURE Web_CommissionDetailQuery
(
	@OperatorID	varchar(50),	--操作员的ID
	@StartDate	varchar(20),	--开始日期
	@EndDate	varchar(20),	--结束日期
	@PtypeID 	varchar(50),	--商品的ID
	@BtypeID 	varchar(50),	--客户的ID
	@EtypeID	varchar(50),	--职员的ID
	@QType		char(5),		--查询的方式   Qtype = W 委托   Qtype = S 受托
	@SortFild	varchar(50),	--排序字段
	@SortType	int				--排序的方式   1.升序	0.降序
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--------------------------当前职员的Employee的SonNum值
DECLARE 	@intESonNum int
SELECT 	@intESonNum = SonNum	FROM Employee WHERE TypeID = @EtypeID AND Deleted = 0
--------------------------当前职员的Btype的SonNum值
DECLARE 	@intBSonNum int
SELECT 	@intBSonNum = SonNum	FROM Btype WHERE TypeID = @BtypeID AND Deleted = 0
--------------------------当前职员的Ptype的SonNum值
DECLARE 	@intPSonNum int
SELECT 	@intPSonNum = SonNum	FROM Ptype WHERE TypeID = @PtypeID AND Deleted = 0
--------------------------构建当前的SQL变量
DECLARE 	@SQL VARCHAR(4000)
SELECT @SQL = ''
--------------------------判断整个系统是否是客户和供货商统一
DECLARE 	@intBtypeAll int
SELECT 	@intBtypeAll = value FROM UserConfig WHERE ConfigName = 'BtypeAll'
BEGIN
	---------------------------------------------------------------------------------构建核心的SQL查询过程
	SELECT @SQL = '

				SELECT	b.billcode,
						b.billdate,
						b.billnumberid,
						b.billtype,
						e.FullName AS EFullName,					
						p.UserCode AS PUserCode,
						p.FullName AS PFullName,
						bt.UserCode AS BUserCode,
						bt.FullName AS BFullName,
						b.ktypeid,
						sum(isnull(a.Qty,0)) as qty,
						a.price,
						ISNULL(SUM(a.Total),0) AS Total,
						ISNULL(SUM(a.CostTotal),0) AS CostTotal
				FROM 	InoutStockTable a,
						BillIndex b,
						Employee e,
						Ptype p,
						Btype bt
				WHERE 	a.BillNumberID = b.BillNumberID
						AND b.EtypeID = e.TypeID
						AND a.PtypeID = p.TypeID
						AND b.BtypeID = bt.TypeID
						AND b.Draft = 0
						AND b.RedWord = 0
						AND a.KtypeID = ''10000''
						AND b.BillDate >= '+char(39)+@StartDate+char(39)+'
						AND b.BillDate <= '+char(39)+@EndDate+char(39)
				-------------------------------------------------------委托职员
				IF @QType = 'W'								
					SELECT @SQL = @SQL + '	AND a.BillType in (140,141,142,143)'								
				ELSE
				-------------------------------------------------------委托职员
					SELECT @SQL = @SQL + '	AND a.BillType in (144,145,146,147)'
				-----------------------------------------------判断职员的范围
				IF @EtypeID = '00001'
					SELECT @SQL = @SQL +' AND b.EtypeID Like '+char(39)+'%'+char(39)
				ELSE
					BEGIN
						IF @intESonNum >= 1
							SELECT @SQL = @SQL + ' AND b.EtypeID Like '+char(39)+@EtypeID+'%'+char(39)
						ELSE													
							SELECT @SQL = @SQL + ' AND b.EtypeID = '+char(39)+@EtypeID+char(39)										
					END
				SELECT @SQL = @SQL +' AND b.EtypeID Like '+char(39)+@MEtypeID+'%'+char(39)													
				-----------------------------------------------判断商品的范围
				IF @PtypeID = '00000'
					SELECT @SQL = @SQL +' AND a.PtypeID Like '+char(39)+'%'+char(39)
				ELSE
					BEGIN
						IF @intPSonNum >= 1
							SELECT @SQL = @SQL + ' AND a.PtypeID Like '+char(39)+@PtypeID+'%'+char(39)
						ELSE													
							SELECT @SQL = @SQL + ' AND a.PtypeID = '+char(39)+@PtypeID+char(39)
					END
				SELECT @SQL = @SQL +' AND a.PtypeID Like '+char(39)+@MPtypeID+'%'+char(39)
				-----------------------------------------------判断客户的范围
				IF @BtypeID = '00000'
					BEGIN
						IF @intBtypeAll = 1 
							SELECT @SQL = @SQL +' AND b.BtypeID Like '+char(39)+'%'+char(39)
						ELSE
							IF @Qtype = 'W'
								SELECT @SQL = @SQL +' AND b.BtypeID Like '+char(39)+'00001'+'%'+char(39)
							ELSE
								SELECT @SQL = @SQL +' AND BtypeID Like '+char(39)+'00002'+'%'+char(39)
					END
				ELSE
					BEGIN
						IF @intBSonNum >= 1
							SELECT @SQL = @SQL +' AND b.BtypeID Like '+char(39)+@BtypeID+'%'+char(39)
						ELSE
							SELECT @SQL = @SQL +' AND b.BtypeID = '+char(39)+@BtypeID+char(39)
					END
				SELECT @SQL = @SQL + 'AND (	b.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+'
											OR b.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'	
				SELECT @SQL = @SQL +'
									GROUP BY 
										b.billcode,
										b.billdate,
										b.billnumberid,
										b.billtype,
										e.FullName,
										p.UserCode,
										p.FullName,
										bt.UserCode,
										bt.FullName,
										--a.qty,
										a.price,
										b.ktypeid'
				------------------------------------------------构造排序字段
				SELECT @SQL = @SQL +' ORDER BY '
					IF @SortFild = 'BillDate'  SELECT @SQL = @SQL +' b.BillDate'
					IF @SortFild = 'BillCode'  SELECT @SQL = @SQL +' b.BillCode'
					IF @SortFild = 'EtypeID'  SELECT @SQL = @SQL +'e.FullName'
					IF @SortFild = 'PUserCode'  SELECT @SQL = @SQL +' p.UserCode'
					IF @SortFild = 'Qty'  SELECT @SQL = @SQL +' a.Qty'
					IF @SortFild = 'CostTotal'  SELECT @SQL = @SQL +' a.CostTotal'
					IF @SortFild = 'Total'  SELECT @SQL = @SQL +' a.Total'
					IF @SortFild = 'KtypeID'  SELECT @SQL = @SQL +' b.KtypeID'
					IF @SortFild = 'PFullName'  SELECT @SQL = @SQL +' p.FullName'
					IF @SortFild = 'UserCode' SELECT @SQL = @SQL +' e.FullName'
				IF	@SortType = 1
					SELECT @SQL = @SQL + ' ASC'
				ELSE
					SELECT @SQL = @SQL + ' DESC' 
		
---------------------------------------------------------------------------------------------------------------出入库记录计算完毕
					------------------------------------------------执行SQL语句
					--Print(@SQL)
					EXEC(@SQL)
		
END















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CommissionGatherDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CommissionGatherDetailQuery]
GO









-- =============================================
-- 功能说明：		受托采购汇总明细
-- 作    者：		陈启华
-- 最后修改时间：	2003-08-14
-- =============================================

-- =============================================
-- 修改说明：		添加类别筛选
-- 修改者  ：		舒珊
-- 最后修改时间：	2016-05-27
-- =============================================

-- =============================================
--   修改: 舒珊
--   日期: 2015-05-31
--   描述: 增加表头、表体新增的自定义字段查询
-- =============================================

CREATE	PROCEDURE Web_CommissionGatherDetailQuery
(
	@OperatorID		varchar(50),		--操作员ID 
	@startDate		varchar(20),        --开始时间
	@endDate		varchar(20),
	@qType			varchar(20),		--查询的大类  W=委托代销查询    S=受托代销查询
	@mType			varchar(20),		--查询的小类  WB=委托客户查询	WK=委托仓库查询	WJ=委托结算	 SB=受托客户查询	SK=受托仓库查询	SJ=受托结算	
	@ChvpTypeId		varchar(1550),		--商品的ID
	@ChvbTypeId		varchar(1550),		--客户的ID
	@ChvkTypeId		varchar(50),		--仓库的ID
	@ChveTypeId		varchar(50),		--仓库的ID
	@ifLine			int,				--1.线性表 0.树型表 2.明细表
	@sortfield		varchar(20),		--排序字段	
	@sortType		varchar(20)='asc',	--排序方式；"asc","desc"
	@isSon			int,				--0.子节点  1.父节点
	@showZero		int,				--1=显示库存为0    0=不显示库存为0
	@Jtype			int		,			--结算类型  0.非结算  1.全部发货        2.已结算             3.未结算
	@intPageNo		int		= '',		-- 12、当前查询的页码
	@intPageSize	int		= 14,		-- 13、每页的显示记录数
	@ChrFlag		int		=1,			-- 1,显示记录，2.打印 3.合计
	@Stypeid		varchar(1550),		--分支机构的ID
	@dealbtypeid    VARCHAR(1550),   -- 树型表或线性表往来单位类别查询范围父节点 ID
	@ptypecategoryid    VARCHAR(MAX )     --商品类别ID	
)

--@encode$--
as


set nocount on
set ANSI_WARNINGS  off

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))

IF @chvPTypeID ='' OR  @chvPTypeID ='00000'
	INSERT INTO #Ptype(typeid) select typeid from F_LinePC(@OperatorID,@ptypecategoryid)
ELSE
	INSERT INTO #Ptype(typeid) select a.typeid from  F_ManPTypeInCategoryID ( @OperatorID,@ChvpTypeId,@ptypecategoryid) a, (select * from  dbo.f_split(@chvPtypeID,',')) b where left(a.typeid,len(b.a))=b.a
IF @chvBtypeID ='' OR  @chvBTypeID ='00000'
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@chvBtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF NOT (@STypeId = '' AND @MStypeid = '00000')
    INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50))
DECLARE @unitsql  VARCHAR(500)
SELECT @unitsql=dbo.F_GetPtypeUnitsAndRates('p1','1,5','1')

IF @dealbtypeid ='' OR  @dealbtypeid ='00000'
	INSERT INTO #dealBtype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #dealBtype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@dealbtypeid,',')) b where left(a.typeid,len(b.a))=b.a


DECLARE @CurSonNum int       --检测当前的SonNum 
DECLARE @BtypeAll int
SELECT @BtypeAll=value FROM UserConfig WHERE ConfigName='BtypeAll'
--------------------------当前职员的Employee的SonNum值
DECLARE 	@intESonNum int
SELECT 	@intESonNum = SonNum	FROM Employee WHERE TypeID = @ChvEtypeID AND Deleted = 0
--------------------------当前职员的Btype的SonNum值
DECLARE 	@intBSonNum int
SELECT 	@intBSonNum = SonNum	FROM Btype WHERE TypeID = @ChvBtypeID AND Deleted = 0
--------------------------当前职员的Ptype的SonNum值
DECLARE 	@intPSonNum int
SELECT 	@intPSonNum = SonNum	FROM Ptype WHERE TypeID = @ChvPtypeID AND Deleted = 0


DECLARE @SQL varchar(max)
DECLARE @SQL_WHERE varchar(max)
DECLARE @Temp_SQL varchar(max)
DECLARE @Sql_Group varchar(max)

DECLARE @SortSQL varchar(max)
SELECT @SortSQL=''
SELECT @SQL_WHERE = ''

-- ========================================================================= 构造条件语句

-----------------------------------------------判断商品的范围
SELECT @SQL_WHERE = @SQL_WHERE +' AND a.PtypeID  IN (select typeid from #Ptype)'
-----------------------------------------------判断客户的范围
DECLARE @BSQL varchar(max)
SET @BSQL =''

SELECT @BSQL = @BSQL +' AND b.BtypeID  IN (select typeid from #dealBtype)'
SELECT @SQL_WHERE = @SQL_WHERE +' AND b.BtypeID  IN (select typeid from #dealBtype) '

SET @Sql_Group='  Group By	 b.btypeid,
							b.billnumberid,
							b.billdate,
							b.ktypeid,
							b.billcode,
							b.comment,
							b.billtype,
							a.ptypeid,
							-- b.Totalinmoney,
							a.Total,
							b.Totalmoney,
							a.costprice,
							a.price,
							b.etypeid,
							a.qty,
							cc.fullname,
							b.rate,
							a.nprice,
							a.ntotal,
							a.ntaxprice,
							a.ntaxtotal,
							v.fullname,
							a.nqty,
							pu.fullname,
							pe.rate,
							u1.fullname,
							u5.fullname,
							a.goodsnumber,
							b.dealbtypeid,
							SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
							SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
							SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
							SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
							SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
							SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
							SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
							SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
							P1.Standard,P1.Type,P1.typeid '
SET @Temp_SQL='
		SELECT 
			b.dealbtypeid as btypeid,
			b.billtype,
			b.billnumberid,
			b.billdate,
			b.billcode,
			a.Ptypeid,
			b.ktypeid,
			b.comment,
'
SET @Temp_SQL= @Temp_SQL +
			' sum(isnull( case a.Billtype when 140 then Convert( NUMERIC(24, 10) ,-a.total) when 142 then Convert( NUMERIC(24, 10) ,-a.Total) else Convert( NUMERIC(24, 10) ,a.Total) end,0)) as total,
			  sum(isnull(case a.Billtype when 140 then Convert( NUMERIC(24, 10) ,-a.CostTotal) when 142 then Convert( NUMERIC(24, 10) ,-a.CostTotal) else Convert( NUMERIC(24, 10) ,a.CostTotal) end ,0)) as CostTotal,
			  sum(isnull(case a.billtype when  140  then -a.qty when  142   then -a.qty else a.qty end,0)) as qty,
			  sum(isnull(case a.billtype when  140  then -a.nqty when  142   then -a.nqty else a.nqty end,0)) as nqty,
			  sum(isnull(case a.billtype when  140  then -(a.qty/isnull(pe.rate,0)) when  142   then -(a.qty/isnull(pe.rate,0)) else (a.qty/isnull(pe.rate,0)) end,0)) as mqty,
			'

SET @Temp_SQL= @Temp_SQL +'
				--sum
				(isnull(a.price,0)) as price,
				a.price as price1,
				a.costprice,
				--b.Totalinmoney,
				sum(isnull( case a.Billtype when 140 then Convert( NUMERIC(24, 10) ,-a.total) when 142 then Convert( NUMERIC(24, 10) ,-a.Total) else Convert( NUMERIC(24, 10) ,a.Total) end,0)) as TotalinMoney,
				b.Totalmoney,
				b.Etypeid,
				cc.fullname AS cname,
				b.rate AS rate,
				a.nprice AS nprice,
				a.ntotal AS ntotal,
				a.ntaxprice AS ntaxprice,
				a.ntaxtotal AS ntaxtotal,
				v.fullname AS itemname,
				pu.fullname AS munit,
				u1.fullname AS baseunitfullname,
				u5.fullname AS assistantfullname,
				a.goodsnumber,
				b.btypeid as dealbtypeid,
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
				P1.Standard,
				P1.Type,
				P1.TypeId AS HzPTypeId
		FROM    BillIndex  b
		INNER JOIN InOutStockTable a ON  b.billnumberid=a.billnumberid
		INNER JOIN AC_Currency cc  ON b.cid = cc.cid
		LEFT  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	    LEFT JOIN PType_Units pu on pu.unitsid = a.munitid
	    LEFT JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
	    LEFT join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
		LEFT join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND a.id=csdetail.Detailid
	    inner join ptype p1 on a.ptypeid=p1.typeid
		'+@unitsql
IF NOT (@Stypeid='' AND @MStypeid='00000')		
	SET @Temp_SQL= @Temp_SQL +' INNER JOIN #Stype s ON  b.stypeid=s.TypeID	'
	
SET @Temp_SQL= @Temp_SQL +' 
                WHERE b.draft=0
				AND b.RedWord=0
				AND b.ifcheck=''t''
				AND b.billdate>='+char(39)+@startDate+char(39)+' AND b.billdate<='+char(39)+@endDate+char(39)
if @ChrFlag=1 or  @ChrFlag=2
BEGIN
	IF @qType='W'
	BEGIN
		IF @mType='WB'	
		BEGIN

			SELECT @SQL=@Temp_SQL+ '
					AND b.billtype in (140,141,142,143)
					AND a.PtypeID  IN (select typeid from #Ptype)
					AND 
						(
							(b.billtype=140 AND a.ktypeid<>''10000'')  OR
						  	(b.billtype=141 AND a.ktypeid=''10000''  )    OR
							(b.billtype=142 AND a.ktypeid<>''10000'') OR
							(b.billtype=143 AND a.ktypeid=''10000'' )
						)'
					
	
				--客户条件用@BSQL代替
				SELECT @SQL=@SQL+@BSQL
				SELECT @SQL=@SQL+@Sql_Group
				SELECT @SQL=@SQL+@SortSQL

		END
		IF @mType='WK'	 
		BEGIN
			SELECT @SQL=@Temp_Sql+'
					AND a.PtypeID  IN (select typeid from #Ptype)
					AND 
						(
							(b.billtype=140 AND a.ktypeid<>''10000''      )  OR
						  	(b.billtype=141 AND a.ktypeid=''10000''  )    OR
							(b.billtype=142 AND a.ktypeid<>''10000''      ) OR
							(b.billtype=143 AND a.ktypeid=''10000'' )
						)'
			SELECT @SQL=@SQL+' AND b.billtype in (140,141,142,143)'

			--客户条件用@BSQL代替
			SELECT @SQL=@SQL+@BSQL
			SELECT @SQL=@SQL+@Sql_Group
			--=======================================构造排序字段
			SELECT @SQL=@SQL+@SortSQL			
										
		END
	END
	ELSE   --受托查询
	BEGIN
		IF @mType='SB'   --受托客户
		BEGIN
			SELECT @CurSonNum=SonNum FROM Ptype WHERE TypeID=@ChvpTypeID	
			SELECT @SQL=@Temp_Sql+'
					AND b.billtype in (144,145,146,147)
					AND a.PtypeID  IN (select typeid from #Ptype)
					AND 
					(
						(b.billtype=144 AND a.ktypeid<>''10000''      )  OR
					  	(b.billtype=145 AND a.ktypeid=''10000''  )    OR
						(b.billtype=146 AND a.ktypeid<>''10000''      ) OR
						(b.billtype=147 AND a.ktypeid=''10000'' ))'
					--客户条件用@BSQL代替
					SELECT @SQL=@SQL+@BSQL
					SELECT @SQL=@SQL+@Sql_Group
					SELECT @SQL=@SQL+@SortSQL
		END
		IF @mType='SK'        --受托库存
		BEGIN
			SELECT @SQL=@Temp_Sql+'							 
					AND a.PtypeID  IN (select typeid from #Ptype)
					AND 
					(
						(b.billtype=144 AND a.ktypeid<>''10000''   )  OR
					  	(b.billtype=145 AND a.ktypeid=''10000''  )    OR
						(b.billtype=146 AND a.ktypeid<>''10000''   ) OR
						(b.billtype=147 AND a.ktypeid=''10000'' )
					)'
					SELECT @SQL=@SQL+' AND b.billtype in (144,145,146,147)'
					--客户条件用@BSQL代替
					SELECT @SQL=@SQL+@BSQL								
					SELECT @SQL=@SQL+@Sql_Group
					--=======================================构造排序字段
					SELECT @SQL=@SQL+@SortSQL
		END
	END
	
	IF (@mType='WB' or  @mType='SB')  AND @SortSQL ='' 
		SET @SortSQL=' Order by A.dealBtypeid '
	IF (@mType='WE' or  @mType='SE')  AND @SortSQL ='' 
		SET @SortSQL=' Order by A.etypeid '
	IF (@mType='WK' or  @mType='SK')  AND @SortSQL ='' 
		SET @SortSQL=' Order by A.Ptypeid '

	SET @SQL = 'DECLARE Rows_Cursor CURSOR FOR
					SELECT A.* FROM ('+@SQL+') A '
	
	SET @SQL = @SQL + @SortSQL + ', A.' + @sortfield + ' ' + @sortType
	
	--Print @SQL	
	EXEC(@SQL)
	--return
	
		
	-- 定义相关数据变量
	
	DECLARE @bTypeId varchar(50) 
	DECLARE @BillType numeric(4,0)
	DECLARE @BillNumberID numeric(10,0)
	DECLARE @BillDate datetime
	DECLARE @BillCode varchar(200)
	
	DECLARE @PTypeID varchar(50)
	DECLARE @KTypeID varchar(50) 
	DECLARE @ETypeID varchar(50) 
	
	DECLARE @Comment varchar(50) 
	DECLARE @Total  NUMERIC(24, 10)  
	DECLARE @CostTotal  NUMERIC(24, 10)  
	
	DECLARE @Qty  NUMERIC(24, 10)  
	DECLARE @price  NUMERIC(24, 10)  
	DECLARE @price1  NUMERIC(24, 10)  
	DECLARE @costprice  NUMERIC(24, 10)  
	DECLARE @Totalinmoney  NUMERIC(24, 10)  
	DECLARE @Totalmoney  NUMERIC(24, 10)  
	
	DECLARE @BillTypeName varchar(20), @FullName varchar(200),@UserCode varchar(200),@EntryCode varchar(256), @BName varchar(200), @EName varchar(200), @KName varchar(200), @CheckeName varchar(200), @MaoLi  NUMERIC(24, 10) , @MaoLiLu  NUMERIC(24, 10) 
	DECLARE @BName1 varchar(200)
	DECLARE @BFullName varchar(200)
	DECLARE @busercode varchar(200)
	DECLARE @Unit varchar(80)	
	DECLARE @cfname varchar(200),@brate  NUMERIC(24, 10) ,@anprice  NUMERIC(24, 10) ,@antotal  NUMERIC(24, 10) ,@antaxprice  NUMERIC(24, 10) ,@antaxtoal  NUMERIC(24, 10) ,@vfname varchar(200),@anqty  NUMERIC(24, 10) ,@pfname varchar(200),@mqty  NUMERIC(24, 10) ,@bufname varchar(200),@afname varchar(200),@agoodsn varchar(100),@dealbtype VARCHAR(50),
			@sysDiy1_head varchar(200),@SysDiy2_head varchar(200),@SysDiy3_head varchar(200),@SysDiy4_head varchar(200), @SysDiy5_head varchar(200),@SysDiy6_head varchar(200),@SysDiy7_head varchar(200),@SysDiy8_head varchar(200),@SysDiy9_head varchar(200),
			@SysDiy10_head varchar(200),@SysDiy11_head varchar(200),@SysDiy12_head varchar(200),@SysDiy13_head varchar(200),@SysDiy14_head varchar(200),@SysDiy15_head varchar(200),@SysDiy16_head varchar(200),
			@sysDiy17_head varchar(200),@SysDiy18_head varchar(200),@SysDiy19_head varchar(200),@SysDiy20_head varchar(200), @SysDiy21_head varchar(200),@SysDiy22_head varchar(200),@SysDiy23_head varchar(200),
			@SysDiy24_head varchar(200),@SysDiy25_head varchar(200),@SysDiy26_head varchar(200),@SysDiy27_head varchar(200),@SysDiy28_head varchar(200),@SysDiy29_head varchar(200),@SysDiy30_head varchar(200),@SysDiy31_head varchar(200),@SysDiy32_head varchar(200),
				
			@SysDiy1 varchar(200),@SysDiy2 varchar(200),@SysDiy3 varchar(200),@SysDiy4 varchar(200),@SysDiy5 varchar(200),@SysDiy6 varchar(200),@SysDiy7 varchar(200),@SysDiy8 varchar(200),@SysDiy9 varchar(200),@SysDiy10 varchar(200),
			@SysDiy11 varchar(200),@SysDiy12 varchar(200),@SysDiy13 varchar(200),@SysDiy14 varchar(200),@SysDiy15 varchar(200),@SysDiy16 varchar(200),	
			@SysDiy17 varchar(200),@SysDiy18 varchar(200),@SysDiy19 varchar(200),@SysDiy20 varchar(200),@SysDiy21 varchar(200),@SysDiy22 varchar(200),@SysDiy23 varchar(200),@SysDiy24 varchar(200),@SysDiy25 varchar(200),@SysDiy26 varchar(200),
			@SysDiy27 varchar(200),@SysDiy28 varchar(200),@SysDiy29 varchar(200),@SysDiy30 varchar(200),@SysDiy31 varchar(200),@SysDiy32 varchar(200)	
			
	DECLARE @Standard	VARCHAR(200),
			@Type		VARCHAR(200),
			@HzPTypeID	VARCHAR(50)

	DECLARE @PUserCode varchar(66)
	-- 声明取得游标个数、游标位置变量
	DECLARE @CursorCount int, @CursorPOS int
	SELECT @CursorCount = 1
	SELECT @CursorPOS = 1
	
	-- 返回结果不受影响
	SET NOCOUNT ON
	
	-- 打开游标
	OPEN Rows_Cursor
	
	-- 获取记录总行数
	DECLARE @RowsCount int
	SELECT @RowsCount = @@CURSOR_ROWS

	DECLARE @T int
	SET @T=1
	FETCH NEXT FROM Rows_Cursor INTO @bTypeId, @BillType, @BillNumberID, @BillDate, @BillCode, @PTypeID, @KTypeID, @Comment, @Total,  @CostTotal, @Qty,@anqty,@mqty, @Price,@price1,@CostPrice,@Totalinmoney,@Totalmoney,@Etypeid,@cfname,@brate,@anprice,@antotal,@antaxprice,@antaxtoal,@vfname,@pfname,@bufname,@afname,@agoodsn,@dealbtype,
	@sysDiy1_head,@SysDiy2_head,@SysDiy3_head,@SysDiy4_head, @SysDiy5_head,@SysDiy6_head,@SysDiy7_head,@SysDiy8_head,@SysDiy9_head,
	@SysDiy10_head,@SysDiy11_head,@SysDiy12_head,@SysDiy13_head,@SysDiy14_head,@SysDiy15_head,@SysDiy16_head,
	@sysDiy17_head,@SysDiy18_head,@SysDiy19_head,@SysDiy20_head, @SysDiy21_head,@SysDiy22_head,@SysDiy23_head,@SysDiy24_head,@SysDiy25_head,
	@SysDiy26_head,@SysDiy27_head,@SysDiy28_head,@SysDiy29_head,@SysDiy30_head,@SysDiy31_head,@SysDiy32_head,	
	@SysDiy1,@SysDiy2,@SysDiy3,@SysDiy4,@SysDiy5,@SysDiy6,@SysDiy7,@SysDiy8,@SysDiy9,@SysDiy10,
	@SysDiy11,@SysDiy12,@SysDiy13,@SysDiy14,@SysDiy15,@SysDiy16	,
	@SysDiy17,@SysDiy18,@SysDiy19,@SysDiy20,@SysDiy21,@SysDiy22,@SysDiy23,@SysDiy24,@SysDiy25,@SysDiy26,
	@SysDiy27,@SysDiy28,@SysDiy29,@SysDiy30,@SysDiy31,@SysDiy32,@Standard,@Type,@HzPTypeID	
	--return
	-- 循环游标到指定位置
	WHILE ( @@FETCH_STATUS = 0 ) AND @CursorPOS < ( @intPageSize * ( @intPageNo - 1 ) + 1 ) 	AND @ChrFlag ='1'	
		BEGIN
			IF @@Error <> 0
				BEGIN
					CLOSE Rows_Cursor
					DEALLOCATE Rows_Cursor
				END

			SELECT @CursorPOS = @CursorPOS + 1
			FETCH NEXT FROM Rows_Cursor INTO @bTypeId, @BillType, @BillNumberID, @BillDate, @BillCode, @PTypeID, @KTypeID, @Comment, @Total,  @CostTotal, @Qty,@anqty,@mqty, @Price,@price1,@CostPrice,@Totalinmoney,@Totalmoney,@Etypeid,@cfname,@brate,@anprice,@antotal,@antaxprice,@antaxtoal,@vfname,@pfname,@bufname,@afname,@agoodsn,@dealbtype,
			@sysDiy1_head,@SysDiy2_head,@SysDiy3_head,@SysDiy4_head, @SysDiy5_head,@SysDiy6_head,@SysDiy7_head,@SysDiy8_head,@SysDiy9_head,
			@SysDiy10_head,@SysDiy11_head,@SysDiy12_head,@SysDiy13_head,@SysDiy14_head,@SysDiy15_head,@SysDiy16_head,
			@sysDiy17_head,@SysDiy18_head,@SysDiy19_head,@SysDiy20_head, @SysDiy21_head,@SysDiy22_head,@SysDiy23_head,@SysDiy24_head,@SysDiy25_head,
			@SysDiy26_head,@SysDiy27_head,@SysDiy28_head,@SysDiy29_head,@SysDiy30_head,@SysDiy31_head,@SysDiy32_head,	
			@SysDiy1,@SysDiy2,@SysDiy3,@SysDiy4,@SysDiy5,@SysDiy6,@SysDiy7,@SysDiy8,@SysDiy9,@SysDiy10,
			@SysDiy11,@SysDiy12,@SysDiy13,@SysDiy14,@SysDiy15,@SysDiy16	,
			@SysDiy17,@SysDiy18,@SysDiy19,@SysDiy20,@SysDiy21,@SysDiy22,@SysDiy23,@SysDiy24,@SysDiy25,@SysDiy26,
			@SysDiy27,@SysDiy28,@SysDiy29,@SysDiy30,@SysDiy31,@SysDiy32,@Standard,@Type,@HzPTypeID			
		END
			
	-- 建立查询临时表 ( 表中的记录条数将为 intPageSize )
	CREATE TABLE #Detail (
		BName1			varchar(max),	-- 客户名称表头
		BillDate		datetime,	-- 单据日期
		BillNumberID	numeric(18,0),	-- 单据ID值
		BillTypeName	varchar(max),	-- 单据类型名称
		BillCode		varchar(max),	-- 单据编号
		PUserCode		varchar(max),	--商品编号
		FullName		varchar(max),	-- 商品名称
		EntryCode		varchar(256),	-- 商品条码
		Qty				 NUMERIC(24, 10) ,	-- 数量
		Price			 NUMERIC(24, 10) ,	-- 单价
		Total			 NUMERIC(24, 10) ,	-- 销售金额
		TotalinMoney     NUMERIC(24, 10) ,	-- 已结算金额
		CostPrice        NUMERIC(24, 10) ,	-- 成本单价
		CostTotal 		 NUMERIC(24, 10) ,	-- 成本
		MaoLi			 NUMERIC(24, 10) ,	-- 毛利
		MaoLiLu			 NUMERIC(24, 10) ,	-- 毛利率
		BFullName		varchar(max),
		busercode		VARCHAR(200),
		Unit			varchar(max),
		billtype		int,
		[IDT]			[int] IDENTITY (1, 1) NOT NULL ,
		cfname          varchar(200),
		brate            NUMERIC(24, 10) ,
		anprice          NUMERIC(24, 10) ,
		antotal          NUMERIC(24, 10) ,
		antaxprice       NUMERIC(24, 10) ,
		antaxtoal        NUMERIC(24, 10) ,
		vfname          varchar(200),
		anqty            NUMERIC(24, 10) ,
		pfname          varchar(200),
		mqty             NUMERIC(24, 10) ,
		bufname         varchar(200),
		afname          varchar(200),
		agoodsn         varchar(100),
		dealbtype       VARCHAR(50),
		sysDiy1_head varchar(200),SysDiy2_head varchar(200),SysDiy3_head varchar(200),SysDiy4_head varchar(200), SysDiy5_head varchar(200),SysDiy6_head varchar(200),SysDiy7_head varchar(200),SysDiy8_head varchar(200),SysDiy9_head varchar(200),
		SysDiy10_head varchar(200),SysDiy11_head varchar(200),SysDiy12_head varchar(200),SysDiy13_head varchar(200),SysDiy14_head varchar(200),SysDiy15_head varchar(200),SysDiy16_head varchar(200),
		sysDiy17_head varchar(200),SysDiy18_head varchar(200),SysDiy19_head varchar(200),SysDiy20_head varchar(200), SysDiy21_head varchar(200),SysDiy22_head varchar(200),SysDiy23_head varchar(200),SysDiy24_head varchar(200),SysDiy25_head varchar(200),
		SysDiy26_head varchar(200),SysDiy27_head varchar(200),SysDiy28_head varchar(200),SysDiy29_head varchar(200),SysDiy30_head varchar(200),SysDiy31_head varchar(200),SysDiy32_head varchar(200),
		
		SysDiy1 varchar(200),SysDiy2 varchar(200),SysDiy3 varchar(200),SysDiy4 varchar(200),SysDiy5 varchar(200),SysDiy6 varchar(200),SysDiy7 varchar(200),SysDiy8 varchar(200),SysDiy9 varchar(200),SysDiy10 varchar(200),
		SysDiy11 varchar(200),SysDiy12 varchar(200),SysDiy13 varchar(200),SysDiy14 varchar(200),SysDiy15 varchar(200),SysDiy16 varchar(200),
		SysDiy17 varchar(200),SysDiy18 varchar(200),SysDiy19 varchar(200),SysDiy20 varchar(200),SysDiy21 varchar(200),SysDiy22 varchar(200),SysDiy23 varchar(200),SysDiy24 varchar(200),SysDiy25 varchar(200),SysDiy26 varchar(200),
		SysDiy27 varchar(200),SysDiy28 varchar(200),SysDiy29 varchar(200),SysDiy30 varchar(200),SysDiy31 varchar(200),SysDiy32 varchar(200),	
		[Standard]		VARCHAR(200),
		[type]			VARCHAR(200),
		ptypeid			VARCHAR(50)
	)
	DECLARE @intTempRowCount int
	IF @RowsCount > 1

		SELECT @intTempRowCount = @RowsCount +1
	ELSE IF @RowsCount = 1
		SELECT @intTempRowCount = @RowsCount  + 1

	DECLARE @intPageSize_Temp numeric(4,0)
	IF @chrFlag = '2'
		SELECT @intPageSize_Temp = @RowsCount
	ELSE
		SELECT @intPageSize_Temp = @intPageSize

	
	--是否第一次向临时表写数据
	DECLARE @BNameCount numeric(6,0)
	set @BNameCount=0
	--声明是否第一次向临时表加入数据
	DECLARE @FirstFlag numeric(6,0)
	SELECT @FirstFlag=0
	DECLARE @Temp_Ptypeid varchar(50)
	DECLARE @Temp_Btypeid varchar(50)
	DECLARE @Temp_Etypeid varchar(50)
	DECLARE @Temp_Qty  NUMERIC(24, 10) 
	DECLARE @Temp_MQty  NUMERIC(24, 10) 
	DECLARE @Temp_NQty  NUMERIC(24, 10) 
	DECLARE @Temp_Total  NUMERIC(24, 10) 
	DECLARE @Temp_Totalinmoney  NUMERIC(24, 10) 
	DECLARE @Temp_CostTotal  NUMERIC(24, 10) 
	DECLARE @Temp_MaoLi  NUMERIC(24, 10) 
	
	SET @Temp_Qty = 0
	SET @Temp_MQty = 0
	SET @Temp_NQty = 0
	SET @Temp_Total = 0
	SET @Temp_Totalinmoney	 = 0
	SET @Temp_CostTotal = 0
	SET @Temp_MaoLi = 0

	WHILE ( @@FETCH_STATUS = 0 ) AND @CursorCount <= @intPageSize_Temp --+1
		BEGIN	
			
			IF @@Error <> 0
				BEGIN
					CLOSE Rows_Cursor
					DEALLOCATE Rows_Cursor
				END			

			-- 游标个数累计
			SELECT @CursorCount = @CursorCount + 1
	
			-- 游标位置移动增值
			SELECT @CursorPOS = @CursorPOS + 1
	

			-- 指定检索特定行
			IF @T<>1
				FETCH NEXT FROM Rows_Cursor INTO @bTypeId, @BillType, @BillNumberID, @BillDate, @BillCode, @PTypeID, @KTypeID, @Comment, @Total,  @CostTotal, @Qty,@anqty,@mqty, @Price,@price1,@CostPrice,@Totalinmoney,@Totalmoney,@Etypeid,@cfname,@brate,@anprice,@antotal,@antaxprice,@antaxtoal,@vfname,@pfname,@bufname,@afname,@agoodsn,@dealbtype,
				@sysDiy1_head,@SysDiy2_head,@SysDiy3_head,@SysDiy4_head, @SysDiy5_head,@SysDiy6_head,@SysDiy7_head,@SysDiy8_head,@SysDiy9_head,
				@SysDiy10_head,@SysDiy11_head,@SysDiy12_head,@SysDiy13_head,@SysDiy14_head,@SysDiy15_head,@SysDiy16_head,
				@sysDiy17_head,@SysDiy18_head,@SysDiy19_head,@SysDiy20_head, @SysDiy21_head,@SysDiy22_head,@SysDiy23_head,@SysDiy24_head,@SysDiy25_head,
				@SysDiy26_head,@SysDiy27_head,@SysDiy28_head,@SysDiy29_head,@SysDiy30_head,@SysDiy31_head,@SysDiy32_head,	
				@SysDiy1,@SysDiy2,@SysDiy3,@SysDiy4,@SysDiy5,@SysDiy6,@SysDiy7,@SysDiy8,@SysDiy9,@SysDiy10,
				@SysDiy11,@SysDiy12,@SysDiy13,@SysDiy14,@SysDiy15,@SysDiy16	,
				@SysDiy17,@SysDiy18,@SysDiy19,@SysDiy20,@SysDiy21,@SysDiy22,@SysDiy23,@SysDiy24,@SysDiy25,@SysDiy26,
				@SysDiy27,@SysDiy28,@SysDiy29,@SysDiy30,@SysDiy31,@SysDiy32,@Standard,@Type,@HzPTypeID	
			SET @T=@T+1	
			--print @BillNumberID
			SELECT @BillTypeName=
				CASE @BillType
					WHEN  140      THEN	'委托代销发货单'
					WHEN  141      THEN	'委托代销结算单'
					WHEN  142      THEN	'委托代销退货单'
					WHEN  143      THEN	'委托代销调价单'
					WHEN  144      THEN	'受托代销收货单'
					WHEN  145      THEN	'受托代销结算单'
					WHEN  146      THEN	'受托代销退货单'
					WHEN  147      THEN	'受托代销调价单'
					END
			SELECT @FullName = FullName,@PUserCode=UserCode,@EntryCode =EntryCode,@Unit = unit1 from ptype where typeid=@PTypeID
			SELECT @BFullName = FullName from Btype where typeid = @bTypeId
			SELECT @busercode = usercode FROM dbo.btype WHERE typeId=@bTypeId
			
			IF @BillType =141
			BEGIN	
				-- SET @MaoLi=abs(@Price*@Qty)-abs(@CostTotal) 由于折扣的问题，改由a.Total代替 @TotalinMoney
				SET @MaoLi=abs(@TotalinMoney)-abs(@CostTotal) 

				If @TotalinMoney=0
					BEGIN		
						SET @MaoLiLu=0
					END
				ELSE
					BEGIN
						SET @MaoLiLu=(abs(@TotalinMoney)-abs(@CostTotal))/(abs(@TotalinMoney))*100		
					END
			END
			ELSE
			BEGIN
				SET @MaoLi = 0
				SET @MaoLiLu = 0
			END
	
				
	-- 若位置数大于总记录行数，则不写入临时表中
	IF @CursorPOS <= @intTempRowCount
		BEGIN
			if @FirstFlag=0 
				BEGIN
					IF  @mType='WB' or @mType='SB'
						BEGIN
							SELECT @BName1=FullName,@UserCode=UserCode from Btype where typeid=@dealbtype
							insert into #Detail (
								BName1,			-- 客户名称表头
								FullName        -- 用Fullname 代替 客户的id								
								)
							Values(
								@BName1,
								@UserCode
							)
							
						END
					IF @mType='WK'  or  @mType='SK'
						BEGIN
							SELECT @BName1=@FullName
							insert into #Detail (
								BName1	,		-- 商品名称表头
								Fullname,		-- 用Fullname 代替 商品的id
								EntryCode
								)
							Values(
								@BName1,
								@PUserCode,    --  xiugai chen_qihua  2003-11-20 @Usercode ==>@pUsercode
								@EntryCode
							)
											
						END
					IF @mtype='WE' or @mType='SE'
						BEGIN
							select @BName1= FullName,@UserCode=UserCode from Employee where typeid=@Etypeid
							insert into #Detail (
								BName1	,		-- 职员名称表头
								Fullname		-- 用Fullname 代替 职员的id
								)
							Values(
								@BName1,
								@UserCode
							)

						END
					set @FirstFlag = 1
					set @Temp_Ptypeid = @Ptypeid
					set @Temp_Btypeid = @dealbtype
					set @Temp_Etypeid = @Etypeid
					set @Temp_Qty = @Qty
					set @Temp_MQty = @mqty
					set @Temp_NQty = @anqty
					set @Temp_Total = @Total
					set @Temp_Totalinmoney =@TotalinMoney
					set @Temp_CostTotal = @CostTotal
					set @Temp_MaoLi = @MaoLi

				END
			ELSE
				BEGIN
					IF @mType='WB' or @mType='SB'

						BEGIN
							IF @Temp_Btypeid <> @dealbtype
								BEGIN
									insert into #Detail (
										BName1,	-- 客户名称表头
										Qty,
										mqty,
										anqty,
										Total,
										TotalinMoney    ,	-- 已结算金额
										CostTotal 	,	-- 成本
										Maoli			-- 毛利
									)
									Values(
										'小计',
										@Temp_Qty,
										@Temp_MQty,
										@Temp_NQty,
										@Temp_Total,
										@Temp_TotalinMoney,
										@Temp_CostTotal,
										@Temp_MaoLi										
									)	
									set @FirstFlag = 1
									set @Temp_Ptypeid = @Ptypeid
									set @Temp_Btypeid = @dealbtype
									set @Temp_Etypeid = @Etypeid

									set @Temp_Qty = @Qty
									set @Temp_MQty = @mqty
									set @Temp_NQty = @anqty
									set @Temp_Total = @Total
									set @Temp_Totalinmoney =@TotalinMoney
									set @Temp_CostTotal = @CostTotal
									set @Temp_MaoLi = @MaoLi	
									-- 写下一个客户的名称
									SELECT @BName1=FullName,@UserCode=UserCode from Btype where typeid=@dealbtype
									insert into #Detail (
										BName1	,		-- 客户名称表头
										Fullname		-- 用Fullname 代替 客户的id
										)
									Values(
										@BName1,
										@UserCode
									)
						
								END
							ELSE
								BEGIN    -- 合计累加
									set @Temp_Qty          = @Temp_Qty    	    + @Qty
									set @Temp_MQty          = @Temp_MQty    	    + @mqty
									set @Temp_NQty          = @Temp_NQty    	    + @anqty
									set @Temp_Total        = @Temp_Total        +  @Total
									set @Temp_Totalinmoney = @Temp_Totalinmoney + @TotalinMoney
									set @Temp_CostTotal    = @Temp_CostTotal    + @CostTotal
									set @Temp_MaoLi        = @Temp_MaoLi        + @MaoLi
								END
						END
					IF @mType='WK' or @mType='SK'
						BEGIN
				
							IF @Temp_Ptypeid <> @Ptypeid
								BEGIN
													
									insert into #Detail (
										BName1,	-- 客户名称表头
										Qty,
										mqty,
										anqty,
										Total,
										TotalinMoney    ,	-- 已结算金额
										CostTotal 	,	-- 成本
										Maoli			-- 毛利
										)
									Values(
										'小计',
										@Temp_Qty,
										@Temp_MQty,
										@Temp_NQty,
										@Temp_Total,
										@Temp_TotalinMoney,
										@Temp_CostTotal,
										@Temp_MaoLi
									)	
									set @FirstFlag = 1
									set @Temp_Ptypeid = @Ptypeid
									set @Temp_Btypeid = @dealbtype
									set @Temp_Etypeid = @Etypeid
									set @Temp_Qty = @Qty
									set @Temp_MQty = @mqty
									set @Temp_NQty = @anqty
									set @Temp_Total = @Total
									set @Temp_Totalinmoney =@TotalinMoney
									set @Temp_CostTotal = @CostTotal
									-- 写商品名称表头
									set @Temp_MaoLi = @MaoLi	
									SELECT @BName1=@FullName
									insert into #Detail (
										BName1	,		
										Fullname	-- 用Fullname 代替 商品的id
										)
									Values(
										@BName1,
										@PUserCode
									)
						
								END
							ELSE
								BEGIN    -- 合计累加
									set @Temp_Qty          = @Temp_Qty    	    + @Qty
									set @Temp_MQty          = @Temp_MQty    	    + @mqty
									set @Temp_NQty          = @Temp_NQty    	    + @anqty
									set @Temp_Total        = @Temp_Total        +  @Total
									set @Temp_Totalinmoney = @Temp_Totalinmoney + @TotalinMoney
									set @Temp_CostTotal    = @Temp_CostTotal    + @CostTotal
									set @Temp_MaoLi        = @Temp_MaoLi        + @MaoLi
								END
	
						END
					IF @mType='WE' or @mType='SE'
						BEGIN
							IF @Temp_Etypeid <> @Etypeid
								BEGIN
									insert into #Detail (
										BName1,	-- 客户名称表头
										Qty,
										mqty,
										nqty,
										Total,
										TotalinMoney    ,	-- 已结算金额
										CostTotal 	,	-- 成本
										Maoli			-- 毛利
										)
									Values(
										'小计',
										@Temp_Qty,
										@Temp_MQty,
										@Temp_NQty,
										@Temp_Total,
										@Temp_TotalinMoney,
										@Temp_CostTotal,
										@Temp_MaoLi
									)	
									set @FirstFlag = 1
									set @Temp_Ptypeid = @Ptypeid
									set @Temp_Btypeid = @dealbtype
									set @Temp_Etypeid = @Etypeid
									set @Temp_Qty = @Qty
									set @Temp_MQty = @mqty
									set @Temp_NQty = @anqty
									set @Temp_Total = @Total
									set @Temp_Totalinmoney =@TotalinMoney
									set @Temp_CostTotal = @CostTotal
									set @Temp_MaoLi = @MaoLi	
									--  写职员名称表头
									select @BName1= FullName,@UserCode=UserCode from Employee where typeid=@Etypeid
									insert into #Detail (
										BName1,		
										Fullname	-- 用Fullname 代替 职员的id
										)
									Values(
										@BName1,
										@UserCode
									)
						
								END
							ELSE
								BEGIN    -- 合计累加
									set @Temp_Qty          = @Temp_Qty    	    + @Qty
									set @Temp_MQty         = @Temp_MQty    	    + @mqty
									set @Temp_NQty         = @Temp_NQty    	    + @anqty
									set @Temp_Total        = @Temp_Total        +  @Total
									set @Temp_Totalinmoney = @Temp_Totalinmoney + @TotalinMoney
									set @Temp_CostTotal    = @Temp_CostTotal    + @CostTotal
									set @Temp_MaoLi        = @Temp_MaoLi        + @MaoLi
									--print @Qty
								END
						END


					END
			
			--写单据明细数据		
			insert into #Detail (
					BillDate	,
					BillNumberID	,	-- 单据ID值
					billtype,
					BillTypeName	,	-- 单据类型名称
					BillCode	,	-- 单据编号
					PUserCode	,	--商品编号
					FullName	,	-- 商品名称
					EntryCode,		--商品条码
					Qty		,	-- 数量
					Price		,	-- 单价
					Total 		,       --销售金额
					TotalinMoney    ,	-- 已结算金额
					CostPrice       ,	-- 成本单价
					CostTotal 	,	-- 成本
					Maoli		,	-- 毛利
					MaoLiLu		,	-- 毛利率
					BFullName	,
					bUserCode	,
					Unit,
					cfname,    
					brate,     
					anprice,   
					antotal,  
					antaxprice,
					antaxtoal, 
					vfname,    
					anqty,     
					pfname,    
					mqty,      
					bufname,   
					afname,    
					agoodsn,
					dealbtype  ,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
					[Standard],
					[Type],
					PTypeID	 							
				)
			Values(
					@BillDate,
					@BillNumberID,
					@billtype,
					@BillTypeName,
					@BillCode,
					@PUserCode,
					@FullName,
					@EntryCode,
					@Qty,
					@Price,
					@Total,
					@TotalinMoney,
					@CostPrice,
					@CostTotal,
					@MaoLi,
					@MaoLiLu,
					@BFullName,
					@busercode,
					@Unit,
					@cfname,
					@brate,
					@anprice,
					@antotal,
					@antaxprice,
					@antaxtoal,
					@vfname,
					@anqty,
					@pfname,
					@mqty,
					@bufname,
					@afname,
					@agoodsn,
					@dealbtype,
					@sysDiy1_head,@SysDiy2_head,@SysDiy3_head,@SysDiy4_head, @SysDiy5_head,@SysDiy6_head,@SysDiy7_head,@SysDiy8_head,@SysDiy9_head,
					@SysDiy10_head,@SysDiy11_head,@SysDiy12_head,@SysDiy13_head,@SysDiy14_head,@SysDiy15_head,@SysDiy16_head,
					@sysDiy17_head,@SysDiy18_head,@SysDiy19_head,@SysDiy20_head, @SysDiy21_head,@SysDiy22_head,@SysDiy23_head,@SysDiy24_head,@SysDiy25_head,
					@SysDiy26_head,@SysDiy27_head,@SysDiy28_head,@SysDiy29_head,@SysDiy30_head,@SysDiy31_head,@SysDiy32_head,	
					@SysDiy1,@SysDiy2,@SysDiy3,@SysDiy4,@SysDiy5,@SysDiy6,@SysDiy7,@SysDiy8,@SysDiy9,@SysDiy10,
					@SysDiy11,@SysDiy12,@SysDiy13,@SysDiy14,@SysDiy15,@SysDiy16	,
					@SysDiy17,@SysDiy18,@SysDiy19,@SysDiy20,@SysDiy21,@SysDiy22,@SysDiy23,@SysDiy24,@SysDiy25,@SysDiy26,
					@SysDiy27,@SysDiy28,@SysDiy29,@SysDiy30,@SysDiy31,@SysDiy32,
					@Standard,@Type,@HzPTypeID
				)

			END		

		END

		--写小计数据
		insert into #Detail (
			BName1,	-- 客户名称表头
			Qty,
			mqty,
			anqty,
			Total,
			TotalinMoney    ,	-- 已结算金额
			CostTotal 	,	-- 成本
			Maoli,			-- 毛利
			Price           --借Price字段插入总的记录行数   
			)
		Values(
			'小计',
			@Temp_Qty,
			@Temp_MQty,
			@Temp_NQty,
			@Temp_Total,
			@Temp_TotalinMoney,
			@Temp_CostTotal,
			@Temp_MaoLi,
			@RowsCount
		)								

	CLOSE Rows_Cursor	-- 关闭游标
	DEALLOCATE Rows_Cursor	-- 释放游标所使用的资源
	select * from #Detail ORDER BY IDT ASC	
	DROP TABLE #Detail	
END




IF @ChrFlag=3
	BEGIN
		DECLARE @SQL_SUM  varchar(4000)
		SET @SQL_SUM='
			SELECT 
				ISNULL(sum(isnull(case a.billtype when  140  then -a.qty/pe.rate when  142   then -a.qty/pe.rate else a.qty/pe.rate end,0)),0) as sum_mqty,
				ISNULL(sum(isnull(case a.billtype when  140  then -a.qty when  142   then -a.qty else a.qty end,0)),0) as sum_Qty,
				ISNULL(sum(isnull(case a.billtype when  140  then -a.nqty when  142   then -a.nqty else a.nqty end,0)),0) as sum_anqty,
				ISNULL(sum(isnull(case a.Billtype when  140 then Convert( NUMERIC(24, 10) ,-a.total) when 142 then Convert( NUMERIC(24, 10) ,-a.Total) else Convert( NUMERIC(24, 10) ,a.Total) end,0)),0) as sum_Total,
				ISNULL(sum(isnull(case a.Billtype when  140 then Convert( NUMERIC(24, 10) ,-a.total) when 142 then Convert( NUMERIC(24, 10) ,-a.Total) else Convert( NUMERIC(24, 10) ,a.Total) end,0)),0) as sum_Totalinmoney,
				isnull(sum(case a.billtype when  140  then Convert( NUMERIC(24, 10) ,-a.CostTotal) when 142 then Convert( NUMERIC(24, 10) ,-a.CostTotal) else Convert( NUMERIC(24, 10) ,a.CostTotal) end),0) as sum_CostTotal,
				isnull(sum(case a.billtype when  141  then Convert( NUMERIC(24, 10) ,abs(a.total))-Convert( NUMERIC(24, 10) ,abs(a.costtotal)) else 0 end),0) as sum_MaoLi
			FROM      BillIndex  b 
			INNER JOIN InOutStockTable a ON b.billnumberid=a.billnumberid
			left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid '
			
IF NOT(@Stypeid='' AND @MStypeid='00000')		
SET @SQL_SUM= @SQL_SUM +' INNER JOIN #Stype s ON  b.stypeid=s.TypeID	'			
					
SET @SQL_SUM= @SQL_SUM +' WHERE b.draft=0
					AND b.RedWord=0
					AND b.ifcheck=''t''
					AND b.billdate>='+char(39)+@startDate+char(39)+' AND b.billdate<='+char(39)+@endDate+char(39)
					+@SQL_WHERE
		--PRINT @SQL_SUM
		--PRINT @SQL_WHERE
		IF @mType='WB'
		BEGIN
			SELECT @SQL=@SQL_SUM+'
						AND b.billtype in (140,141,142,143)
						AND 
						(
							(b.billtype=140 AND a.ktypeid<>''10000''  )  OR
						  	(b.billtype=141 AND a.ktypeid=''10000''  )    OR
							(b.billtype=142 AND a.ktypeid<>''10000''  ) OR
							(b.billtype=143 AND a.ktypeid=''10000'' )
						)'
			
		END
		IF @mType='WK'
		BEGIN
			SELECT @SQL=@SQL_SUM+'
					AND 
						(
							(b.billtype=140 AND a.ktypeid<>''10000''  )  OR
						  	(b.billtype=141 AND a.ktypeid=''10000''  )    OR
							(b.billtype=142 AND a.ktypeid<>''10000''  ) OR
							(b.billtype=143 AND a.ktypeid=''10000'' )
						)'

					SELECT @SQL=@SQL+' AND b.billtype in (140,141,142,143)'
		END
		IF @mType='SB'
		BEGIN
			SELECT @SQL=@SQL_SUM+'
					AND b.billtype in (144,145,146,147)
					AND 
						(
							(b.billtype=144 AND a.ktypeid<>''10000'' )  OR
						  	(b.billtype=145 AND a.ktypeid=''10000''  )    OR
							(b.billtype=146 AND a.ktypeid<>''10000'' ) OR
							(b.billtype=147 AND a.ktypeid=''10000'' )
						)'
		END
		IF  @mType='SK'
		BEGIN
			SELECT @SQL=@SQL_SUM+'							 
					AND 
						(
							(b.billtype=144 AND a.ktypeid<>''10000'' )  OR
						  	(b.billtype=145 AND a.ktypeid=''10000''  )    OR
							(b.billtype=146 AND a.ktypeid<>''10000'' ) OR
							(b.billtype=147 AND a.ktypeid=''10000'' )
						)'

					SELECT @SQL=@SQL+' AND b.billtype in (144,145,146,147)'
		END
	--PRINT(@SQL)
	exec(@SQL)
END

DROP TABLE #Ptype
DROP TABLE #Btype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CommissionLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CommissionLineQuery]
GO











/*
	--作者：谢吉康
	--日期：2003-08-13
	--描述：代销职员查询线性
*/
CREATE    PROCEDURE Web_CommissionLineQuery
(
	@OperatorID	varchar(50),	--操作员的ID
	@StartDate	varchar(20),	--开始日期
	@EndDate	varchar(20),	--结束日期
	@PtypeID 	varchar(50),	--商品的ID
	@BtypeID 	varchar(50),	--客户的ID
	@EtypeID	varchar(50),	--职员的ID
	@QType		char(5),		--查询的方式   Qtype = W 委托   Qtype = S 受托
	@SortFild	varchar(50),	--排序字段
	@SortType	int				--排序的方式   1.升序	2.降序
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--------------------------当前职员的Employee的SonNum值
DECLARE 	@intESonNum int
SELECT 	@intESonNum = SonNum	FROM Employee WHERE TypeID = @EtypeID AND Deleted = 0
--------------------------当前职员的Btype的SonNum值
DECLARE 	@intBSonNum int
SELECT 	@intBSonNum = SonNum	FROM Btype WHERE TypeID = @BtypeID AND Deleted = 0
--------------------------当前职员的Ptype的SonNum值
DECLARE 	@intPSonNum int
SELECT 	@intPSonNum = SonNum	FROM Ptype WHERE TypeID = @PtypeID AND Deleted = 0
--------------------------构建当前的SQL变量
DECLARE 	@SQL VARCHAR(4000)
SELECT @SQL = ''
--------------------------判断整个系统是否是客户和供货商统一
DECLARE 	@intBtypeAll int
SELECT 	@intBtypeAll = value FROM UserConfig WHERE ConfigName = 'BtypeAll'
BEGIN
	---------------------------------------------------------------------------------构建核心的SQL查询过程
	SELECT @SQL = '
					SELECT 	e.TypeID,
							e.UserCode,
							e.FullName,
							ISNULL(SUM(b.Qty),0) AS Qty,
							ISNULL(SUM(b.Total),0) AS Total,
							ISNULL(SUM(b.CostTotal),0) AS CostTotal
					FROM 	Employee e
					LEFT JOIN 
						(
							SELECT	a.EtypeID,
									a.Qty,
									a.Total,
									a.CostTotal
							FROM 	InoutStockTable a,
									BillIndex b
							WHERE 	a.BillNumberID = b.BillNumberID
									AND b.Draft = 0
									AND b.RedWord = 0
									AND a.KtypeID = ''10000''
									AND b.BillDate >= '+char(39)+@StartDate+char(39)+'
									AND b.BillDate <= '+char(39)+@EndDate+char(39)
							-------------------------------------------------------委托职员
							IF @QType = 'W'								
								SELECT @SQL = @SQL + '	AND a.BillType in (140,141,142,143)'								
							ELSE
							-------------------------------------------------------委托职员
								SELECT @SQL = @SQL + '	AND a.BillType in (144,145,146,147)'								
							-----------------------------------------------判断职员的范围
							IF @EtypeID = '00001'
								SELECT @SQL = @SQL +' AND b.EtypeID Like '+char(39)+'%'+char(39)
							ELSE
								BEGIN
									IF @intESonNum >= 1
										SELECT @SQL = @SQL + ' AND b.EtypeID Like '+char(39)+@EtypeID+'%'+char(39)
									ELSE													
										SELECT @SQL = @SQL + ' AND b.EtypeID = '+char(39)+@EtypeID+char(39)										
								END
							SELECT @SQL = @SQL +' AND b.EtypeID Like '+char(39)+@MEtypeID+'%'+char(39)													
							-----------------------------------------------判断商品的范围
							IF @PtypeID = '00000'
								SELECT @SQL = @SQL +' AND a.PtypeID Like '+char(39)+'%'+char(39)
							ELSE
								BEGIN
									IF @intPSonNum >= 1
										SELECT @SQL = @SQL + ' AND a.PtypeID Like '+char(39)+@PtypeID+'%'+char(39)
									ELSE													
										SELECT @SQL = @SQL + ' AND a.PtypeID = '+char(39)+@PtypeID+char(39)
								END
							SELECT @SQL = @SQL +' AND a.PtypeID Like '+char(39)+@MPtypeID+'%'+char(39)
							-----------------------------------------------判断客户的范围
							IF @BtypeID = '00000'
								BEGIN
									IF @intBtypeAll = 1 
										SELECT @SQL = @SQL +' AND b.BtypeID Like '+char(39)+'%'+char(39)
									ELSE
										IF @Qtype = 'W'
											SELECT @SQL = @SQL +' AND b.BtypeID Like '+char(39)+'00001'+'%'+char(39)
										ELSE
											SELECT @SQL = @SQL +' AND BtypeID Like '+char(39)+'00002'+'%'+char(39)
								END
							ELSE
								BEGIN
									IF @intBSonNum >= 1
										SELECT @SQL = @SQL +' AND b.BtypeID Like '+char(39)+@BtypeID+'%'+char(39)
									ELSE
										SELECT @SQL = @SQL +' AND b.BtypeID = '+char(39)+@BtypeID+char(39)
								END
							SELECT @SQL = @SQL + 'AND (	b.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+'
														OR b.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'	
---------------------------------------------------------------------------------------------------------------出入库记录计算完毕
							SELECT @SQL = @SQL + '
							UNION ALL
							SELECT 	EtypeID,
									Qty,
									Total,		
									CostTotal
							FROM 	IniCommissionStock'
							IF @QType = 'W'								
								SELECT @SQL = @SQL + '	WHERE Type = 140'								
							ELSE
							-------------------------------------------------------委托职员
								SELECT @SQL = @SQL + '	WHERE Type = 144'								
							-----------------------------------------------判断职员的范围
							IF @EtypeID = '00001'
								SELECT @SQL = @SQL +' AND EtypeID Like '+char(39)+'%'+char(39)
							ELSE
								BEGIN
									IF @intESonNum >= 1
										SELECT @SQL = @SQL + ' AND EtypeID Like '+char(39)+@EtypeID+'%'+char(39)
									ELSE													
										SELECT @SQL = @SQL + ' AND EtypeID = '+char(39)+@EtypeID+char(39)										
								END
							SELECT @SQL = @SQL +' AND EtypeID Like '+char(39)+@MEtypeID+'%'+char(39)													
							-----------------------------------------------判断商品的范围
							IF @PtypeID = '00000'
								SELECT @SQL = @SQL +' AND PtypeID Like '+char(39)+'%'+char(39)
							ELSE
								BEGIN
									IF @intPSonNum >= 1
										SELECT @SQL = @SQL + ' AND PtypeID Like '+char(39)+@PtypeID+'%'+char(39)
									ELSE													
										SELECT @SQL = @SQL + ' AND PtypeID = '+char(39)+@PtypeID+char(39)
								END
							SELECT @SQL = @SQL +' AND PtypeID Like '+char(39)+@MPtypeID+'%'+char(39)
							-----------------------------------------------判断客户的范围
							IF @BtypeID = '00000'
								BEGIN
									IF @intBtypeAll = 1 
										SELECT @SQL = @SQL +' AND BtypeID Like '+char(39)+'%'+char(39)
									ELSE
										IF @QType = 'W'	
											SELECT @SQL = @SQL +' AND BtypeID Like '+char(39)+'00001'+'%'+char(39)
										ELSE
											SELECT @SQL = @SQL +' AND BtypeID Like '+char(39)+'00002'+'%'+char(39)
								END
							ELSE
								BEGIN
									IF @intBSonNum >= 1
										SELECT @SQL = @SQL +' AND BtypeID Like '+char(39)+@BtypeID+'%'+char(39)
									ELSE
										SELECT @SQL = @SQL +' AND BtypeID = '+char(39)+@BtypeID+char(39)
								END
							SELECT @SQL = @SQL + ' AND (	BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+'
													 	OR BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'	
					SELECT @SQL = @SQL +'
						)b	ON LEFT(b.EtypeID,LEN(e.TypeID)) = e.TypeID
					WHERE	e.Deleted = 0
							AND e.SonNum = 0'
					-----------------------------------------------判断职员的范围					
					IF @EtypeID = '00001'
						SELECT @SQL = @SQL +' AND e.typeID Like '+char(39)+'%'+char(39)
					ELSE
						BEGIN
							IF @intESonNum >= 1
								SELECT @SQL = @SQL + ' AND e.typeID Like '+char(39)+@EtypeID+'%'+char(39)
							ELSE													
								SELECT @SQL = @SQL + ' AND e.typeID = '+char(39)+@EtypeID+char(39)										
						END
					SELECT @SQL = @SQL +' AND e.typeID Like '+char(39)+@MEtypeID+'%'+char(39)												
					SELECT @SQL = @SQL +'
					GROUP BY 	e.TypeID,
								e.UserCode,

								e.FullName					

					ORDER BY 	e.UserCode'
					------------------------------------------------执行SQL语句
					--Print(@SQL)
					EXEC(@SQL)
		
END










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CommissionListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CommissionListQuery]
GO













/*
	--作者：谢吉康
	--日期：2003-08-13
	--描述：代销职员查询树型
*/
CREATE      PROCEDURE Web_CommissionListQuery
(
	@OperatorID	VARCHAR(50),	--操作员的ID
	@StartDate	VARCHAR(20),	--开始日期
	@EndDate	VARCHAR(20),	--结束日期
	@PtypeID 	VARCHAR(50),	--商品的ID
	@BtypeID 	VARCHAR(50),	--客户的ID
	@EtypeID	VARCHAR(50),	--职员的ID
	@QType		CHAR(5),		--查询的方式   Qtype = W 委托   Qtype = S 受托
	@SortFild	VARCHAR(50),	--排序字段
	@SortType	INT				--排序的方式   1.升序	2.降序
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--------------------------当前职员的Employee的SonNum值
DECLARE 	@intESonNum INT
SELECT 	@intESonNum = SonNum	FROM Employee WHERE TypeID = @EtypeID AND Deleted = 0
--------------------------当前职员的Btype的SonNum值
DECLARE 	@intBSonNum INT
SELECT 	@intBSonNum = SonNum	FROM Btype WHERE TypeID = @BtypeID AND Deleted = 0
--------------------------当前职员的Ptype的SonNum值
DECLARE 	@intPSonNum INT
SELECT 	@intPSonNum = SonNum	FROM Ptype WHERE TypeID = @PtypeID AND Deleted = 0
--------------------------构建当前的SQL变量
DECLARE 	@SQL VARCHAR(4000)
SELECT @SQL = ''
--------------------------判断整个系统是否是客户和供货商统一
DECLARE 	@intBtypeAll INT
SELECT 	@intBtypeAll = value FROM UserConfig WHERE ConfigName = 'BtypeAll'
BEGIN
	---------------------------------------------------------------------------------构建核心的SQL查询过程
	SELECT @SQL = '
					SELECT 	e.TypeID,
							e.UserCode,
							e.FullName,
							e.SonNum,
							ISNULL(SUM(b.Qty),0) AS Qty,
							ISNULL(SUM(b.Total),0) AS Total,
							ISNULL(SUM(b.CostTotal),0) AS CostTotal
					FROM 	Employee e
					LEFT JOIN 
						(
							SELECT	a.EtypeID,
									a.Qty,
									a.Total,
									a.CostTotal
							FROM 	InoutStockTable a,
									BillIndex b
							WHERE 	a.BillNumberID = b.BillNumberID
									AND b.Draft = 0
									AND b.RedWord = 0
									AND a.KtypeID = ''10000''
									AND b.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
									AND b.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)
							-------------------------------------------------------委托职员
							IF @QType = 'W'								
								SELECT @SQL = @SQL + '	AND a.BillType IN (140,141,142,143)'								
							ELSE
							-------------------------------------------------------委托职员
								SELECT @SQL = @SQL + '	AND a.BillType IN (144,145,146,147)'
							-----------------------------------------------判断职员的范围
							IF @EtypeID = '00001'
								SELECT @SQL = @SQL +' AND b.EtypeID LIKE '+CHAR(39)+'%'+CHAR(39)
							ELSE
								BEGIN
									IF @intESonNum >= 1
										SELECT @SQL = @SQL + ' AND b.EtypeID LIKE '+CHAR(39)+@EtypeID+'%'+CHAR(39)
									ELSE													
										SELECT @SQL = @SQL + ' AND b.EtypeID = '+CHAR(39)+@EtypeID+CHAR(39)										
								END
							SELECT @SQL = @SQL +' AND b.EtypeID LIKE '+CHAR(39)+@MEtypeID+'%'+CHAR(39)													
							-----------------------------------------------判断商品的范围
							IF @PtypeID = '00000'
								SELECT @SQL = @SQL +' AND a.PtypeID LIKE '+CHAR(39)+'%'+CHAR(39)
							ELSE
								BEGIN
									IF @intPSonNum >= 1
										SELECT @SQL = @SQL + ' AND a.PtypeID LIKE '+CHAR(39)+@PtypeID+'%'+CHAR(39)
									ELSE													
										SELECT @SQL = @SQL + ' AND a.PtypeID = '+CHAR(39)+@PtypeID+CHAR(39)
								END
							SELECT @SQL = @SQL +' AND a.PtypeID LIKE '+CHAR(39)+@MPtypeID+'%'+CHAR(39)
							-----------------------------------------------判断客户的范围
							IF @BtypeID = '00000'
								BEGIN
									IF @intBtypeAll = 1 
										SELECT @SQL = @SQL +' AND b.BtypeID LIKE '+CHAR(39)+'%'+CHAR(39)
									ELSE
										IF @Qtype = 'W'
											SELECT @SQL = @SQL +' AND b.BtypeID LIKE '+CHAR(39)+'00001'+'%'+CHAR(39)
										ELSE
											SELECT @SQL = @SQL +' AND BtypeID LIKE '+CHAR(39)+'00002'+'%'+CHAR(39)
								END
							ELSE
								BEGIN
									IF @intBSonNum >= 1
										SELECT @SQL = @SQL +' AND b.BtypeID LIKE '+CHAR(39)+@BtypeID+'%'+CHAR(39)
									ELSE
										SELECT @SQL = @SQL +' AND b.BtypeID = '+CHAR(39)+@BtypeID+CHAR(39)
								END
							SELECT @SQL = @SQL + 'AND (	b.BtypeID LIKE '+CHAR(39)+@MBtypeID+'%'+CHAR(39)+'
														OR b.BtypeID LIKE '+CHAR(39)+@MBtypeID2+'%'+CHAR(39)+')'	
---------------------------------------------------------------------------------------------------------------出入库记录计算完毕
							SELECT @SQL = @SQL + '
							UNION ALL
							SELECT 	EtypeID,
									Qty,
									Total,		
									CostTotal
							FROM 	IniCommissionStock'
							IF @QType = 'W'								
								SELECT @SQL = @SQL + '	WHERE Type = 140'								
							ELSE
							-------------------------------------------------------委托职员
								SELECT @SQL = @SQL + '	WHERE Type = 144'								
							-----------------------------------------------判断职员的范围
							IF @EtypeID = '00001'
								SELECT @SQL = @SQL +' AND EtypeID LIKE '+CHAR(39)+'%'+CHAR(39)
							ELSE
								BEGIN
									IF @intESonNum >= 1
										SELECT @SQL = @SQL + ' AND EtypeID LIKE '+CHAR(39)+@EtypeID+'%'+CHAR(39)
									ELSE													
										SELECT @SQL = @SQL + ' AND EtypeID = '+CHAR(39)+@EtypeID+CHAR(39)										
								END
							SELECT @SQL = @SQL +' AND EtypeID LIKE '+CHAR(39)+@MEtypeID+'%'+CHAR(39)													
							-----------------------------------------------判断商品的范围
							IF @PtypeID = '00000'
								SELECT @SQL = @SQL +' AND PtypeID LIKE '+CHAR(39)+'%'+CHAR(39)
							ELSE
								BEGIN
									IF @intPSonNum >= 1
										SELECT @SQL = @SQL + ' AND PtypeID LIKE '+CHAR(39)+@PtypeID+'%'+CHAR(39)
									ELSE													
										SELECT @SQL = @SQL + ' AND PtypeID = '+CHAR(39)+@PtypeID+CHAR(39)
								END
							SELECT @SQL = @SQL +' AND PtypeID LIKE '+CHAR(39)+@MPtypeID+'%'+CHAR(39)
							-----------------------------------------------判断客户的范围
							IF @BtypeID = '00000'
								BEGIN
									IF @intBtypeAll = 1 
										SELECT @SQL = @SQL +' AND BtypeID LIKE '+CHAR(39)+'%'+CHAR(39)
									ELSE
										IF @QType = 'W'	
											SELECT @SQL = @SQL +' AND BtypeID LIKE '+CHAR(39)+'00001'+'%'+CHAR(39)
										ELSE
											SELECT @SQL = @SQL +' AND BtypeID LIKE '+CHAR(39)+'00002'+'%'+CHAR(39)
								END
							ELSE
								BEGIN
									IF @intBSonNum >= 1
										SELECT @SQL = @SQL +' AND BtypeID LIKE '+CHAR(39)+@BtypeID+'%'+CHAR(39)
									ELSE
										SELECT @SQL = @SQL +' AND BtypeID = '+CHAR(39)+@BtypeID+CHAR(39)
								END
							SELECT @SQL = @SQL + ' AND (	BtypeID LIKE '+CHAR(39)+@MBtypeID+'%'+CHAR(39)+'
													 	OR BtypeID LIKE '+CHAR(39)+@MBtypeID2+'%'+CHAR(39)+')'	
					SELECT @SQL = @SQL +'
						)b	ON LEFT(b.EtypeID,LEN(e.TypeID)) = e.TypeID
					WHERE	e.Deleted = 0'
					-----------------------------------------------判断职员的范围
					IF @EtypeID = '00001'
						SELECT @SQL = @SQL +' AND e.ParID ='+CHAR(39)+'00001'+CHAR(39)
					ELSE
						BEGIN
							IF @intESonNum >= 1
								SELECT @SQL = @SQL + ' AND e.ParID = '+CHAR(39)+@EtypeID+CHAR(39)
							ELSE													
								SELECT @SQL = @SQL + ' AND e.typeID = '+CHAR(39)+@EtypeID+CHAR(39)										
						END
					SELECT @SQL = @SQL +' AND e.typeID LIKE '+CHAR(39)+@MEtypeID+'%'+CHAR(39)						
					SELECT @SQL = @SQL +'
					GROUP BY 	e.TypeID,
								e.UserCode,
								e.FullName,
								e.SonNum					

					ORDER BY 	e.UserCode'
					------------------------------------------------执行SQL语句
					--Print(@SQL)
					EXEC(@SQL)
		
END












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_CommissionQuery_List]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].Web_CommissionQuery_List
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
	作者：蒋奎
	日期：2014-5-15
	描述：提成查询和单据联查
	修改记录: 2014-09-04 屏蔽审核人的查询
-------------------------------------------*/
CREATE PROCEDURE Web_CommissionQuery_List
    (
		@OperatorID varchar(50),	--操作员ID
		@Startdate VARCHAR(50) ,	--单据日期开始
		@Enddate VARCHAR(50) ,		--单据日期结束
		@BillCode VARCHAR(200) ,	--单据编号
		@StypeID VARCHAR(MAX) ,		--分支机构,
		@CommissionSchemeID VARCHAR(200) , --提成方案ID
		@Checke VARCHAR(MAX),		--制单人
		--@Checker VARCHAR(MAX),		--审核人
		@Poster VARCHAR(MAX),		--过账人
		@Comment VARCHAR(256) ,		--摘要
		@isVoucher VARCHAR(10),		--是否生成会计凭证
		@EtypeID VARCHAR(max),		--职员(单据联查的职员)
		@DtypeID VARCHAR(50),		--部门(单据联查的部门)
		@Hide VARCHAR(10),			--隐藏已完成单据
		@CommissionType VARCHAR(10) --提成类型 0=手工 1=提成规则设置  2= 参照计划提成设置 3= 全部
    )
--@encode$--    
AS
SET NOCOUNT ON

BEGIN
----------------------------------------------------------------提成单查询开始----------------------------------------------------------------------
IF	@EtypeID=''
BEGIN
 	--分支机构集合
	SELECT TypeID INTO #StypeID FROM F_GetAllManagerBaseTypeId(@StypeID,11,@OperatorID)
	/**此处职员筛选的逻辑是
		admin
			非空 出选的
			空 出所有

		普通操作员    
			非空 出选的
			空   出职员范围内的 + admin
			要制单人,审核人,过账人都在这个操作员管辖内的才出这个单据
	**/
	CREATE TABLE #Checke (TypeID VARCHAR(50))
	--CREATE TABLE #Checker (TypeID VARCHAR(50))
	CREATE TABLE #Poster (TypeID VARCHAR(50))
	CREATE TABLE #CommissionSchemeID (TypeID VARCHAR(50))
	IF	@OperatorID = '00001' --超级管理员
	BEGIN	
		--制单人集合
		IF	@Checke <> ''
		 	INSERT  INTO #Checke SELECT TypeID FROM F_GetAllManagerBaseTypeId(@Checke,3,@OperatorID) 
			
		--过账人集合
		IF	@Poster <> ''
			INSERT	INTO #Poster SELECT TypeID  FROM F_GetAllManagerBaseTypeId(@Poster,3,@OperatorID)
	    
	END
	IF	@OperatorID <> '00001' --普通操作员
	BEGIN	
		--制单人集合
		IF	@Checke <> ''
 			INSERT  INTO #Checke SELECT TypeID FROM F_GetAllManagerBaseTypeId(@Checke,3,@OperatorID)
 		ELSE 
 			INSERT  INTO #Checke SELECT TypeID FROM F_GetAllManagerBaseTypeId('',3,@OperatorID) UNION  SELECT '00001' UNION SELECT ''  
		 	 
			
		--过账人集合
		IF	@Poster <> ''
			INSERT	INTO #Poster SELECT TypeID  FROM F_GetAllManagerBaseTypeId(@Poster,3,@OperatorID)
 		ELSE 
			INSERT	INTO #Poster SELECT TypeID  FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)  UNION  SELECT '00001' UNION SELECT ''  
	    
	END
	
	--提成方案集合
	IF	@CommissionSchemeID <> ''
		INSERT	INTO #CommissionSchemeID SELECT A  FROM f_split(@CommissionSchemeID,',')
	--出明细sum后的集合
	DECLARE @Sql VARCHAR(max)
	SET @Sql='
				SELECT 
					BillNumberId, 
					SUM(Qty) AS Qty,
					SUM(Total) AS Total,
					SUM(CommissionTotal) AS CommissionTotal 
				INTO #CommissionDetailData
				FROM dbo.CommissionBillNewDetail
				GROUP BY 
					BillNumberId'
					
	--出提成单查询绑定字段		
	SET @Sql +='
				SELECT	a.BillNumberId ,
						a.BillDate ,	-- 业务日期
						a.BillCode ,	-- 单据编号
						st.fullname ,	--分支机构
						sc.SchemeName ,	-- 提成方案
						sc.BillNumberId as CommissionSchemeID , -- 提成方案ID 
						a.CommissionType as CommissionType, --规则来源 
						a.Comment ,		--摘要
						a.Explain,		--说明
						b.Qty ,			--数量
						b.Total ,		--金额
						b.CommissionTotal, -- 提成金额
						CASE WHEN a.ifcheck =''t''  THEN 5 ELSE  a.BillState  END  as BillState, 	--状态
						CASE WHEN d.GoodsBillId is null THEN ''false'' ELSE ''true'' END  as isVoucher,	--是否生成凭证
						ep.fullname as Checke,		--制单人
						a.CheckeTime,				--制单时间
						ep1.fullname as Checker,		--审核人
						a.CheckerTime,				--审核时间
						ep2.fullname as Poster,		--过账人
						a.PostTime,					--过账时间
						ep3.fullname as FChecker,	--反审核人
						a.FCheckerTime,				--反审核时间
						ep4.fullname as FPoster,		--反过账人
						a.FPostTime					--反过账时间
				FROM	dbo.CommissionBillNew a
				INNER JOIN #CommissionDetailData b ON a.BillNumberId = b.BillNumberId
				LEFT JOIN Stype st ON a.StypeID = st.TypeId
				LEFT JOIN employee ep ON a.Checke= ep.TypeID
				LEFT JOIN employee ep1 ON a.Checker= ep1.TypeID
				LEFT JOIN employee ep2 ON a.Poster= ep2.TypeID
				LEFT JOIN employee ep3 ON a.FChecker= ep3.TypeID
				LEFT JOIN employee ep4 ON a.FPoster= ep4.TypeID
				LEFT JOIN CommissionScheme sc ON a.CommissionSchemeID = sc.BillNumberId'
	--分支机构			
	IF  EXISTS(SELECT TOP 1 1 FROM #StypeID )
		SET @Sql += ' 
						INNER JOIN #StypeID s ON a.StypeID = s.TypeID  '	
	--制单人
	IF  EXISTS(SELECT TOP 1 1 FROM #Checke )
		SET @Sql += ' 
						INNER JOIN #Checke ck ON isnull(a.Checke,'''') =ck.TypeID  '	
	----审核人			
	--IF  EXISTS(SELECT TOP 1 1 FROM #Checker )
	--	SET @Sql += ' 
	--					INNER JOIN #Checker ckr ON isnull(a.Checker,'''') =ckr.TypeID '	
	--过账人	
	IF  EXISTS(SELECT TOP 1 1 FROM #Poster )
		SET @Sql += ' 
						INNER JOIN #Poster pt ON isnull(a.Poster,'''') =pt.TypeID '	
	--提成方案	
	IF  EXISTS(SELECT TOP 1 1 FROM #CommissionSchemeID )
		SET @Sql += '	
						INNER JOIN #CommissionSchemeID cs ON a.CommissionSchemeID =cs.TypeID '
			
	--是否生成凭证表连接
	SET @Sql +=	'	
						LEFT JOIN Ac_CommissionBill_VoucherBill d  on a.BillNumberId=d.GoodsBillId
						WHERE 1=1 '
	
	--单据日期 
	SET @Sql += ' and ( a.BillDate >= ''' + @Startdate + ''' and a.BillDate <='''+@Enddate+''')'
	
	--单据编号
	IF	@BillCode <> '' 
		SET @Sql += ' and a.BillCode like ''%' + @BillCode + '%'''
		
	--单据摘要	
	IF  @Comment  <> '' 
		SET @Sql += ' and a.Comment like ''%' + @Comment + '%'''
		
	-- 隐藏已完成的	
	IF	@Hide = 'true'
		SET @Sql += 'and d.GoodsBillId is null  '
		
	--是否生成凭证	
	IF	@isVoucher = 'True'
		SET @Sql += 'and d.GoodsBillId is not null '
	
	--规则来源 (3为全部)
	IF	@CommissionType <> '3'
		SET @Sql += 'and a.CommissionType = '+@CommissionType 
		
	--排序
	SET @Sql += ' 
					ORDER BY a.billdate , a.billcode  '
				
		
	SET @Sql += '
					DROP TABLE #CommissionDetailData'
	
	PRINT(@Sql) 
	EXEC (@Sql)
	
	DROP TABLE #StypeID,#Checke,#Poster
	
END

----------------------------------------------------------------提成单查询结束----------------------------------------------------------------------

----------------------------------------------------------------单据联查开始----------------------------------------------------------------------
IF @EtypeID !=''
BEGIN
		SELECT	a.BillNumberId ,
				a.BillDate ,	-- 业务日期
				a.BillCode ,	-- 单据编号
				st.fullname ,	--分支机构
				sc.SchemeName ,	-- 提成方案
				sc.BillNumberId as CommissionSchemeID , -- 提成方案ID 
				a.CommissionType as CommissionType, --规则来源 
				a.Comment ,		--摘要
				a.Explain,		--说明
				ep5.UserCode,		--职员编号
				ep5.fullname AS EtypeName ,	--职员名称 
				b.Qty ,			--数量
				b.Total ,		--金额
				b.CommissionTotal, -- 提成金额
				CASE WHEN a.ifcheck ='t'  THEN 5 ELSE  a.BillState  END  as BillState, 	--状态
				CASE WHEN d.GoodsBillId is null THEN 'false' ELSE 'true' END  as isVoucher,	--是否生成凭证
				ep.fullname as Checke,		--制单人
				a.CheckeTime,				--制单时间
				ep1.fullname as Checker,		--审核人
				a.CheckerTime,				--审核时间
				ep2.fullname as Poster,		--过账人
				a.PostTime,					--过账时间
				ep3.fullname as FChecker,	--反审核人
				a.FCheckerTime,				--反审核时间
				ep4.fullname as FPoster,		--反过账人
				a.FPostTime					--反过账时间
		FROM	dbo.CommissionBillNew a
				INNER JOIN (SELECT 
								BillNumberId, 
								SUM(Qty) AS Qty,
								SUM(Total) AS Total,
								SUM(CommissionTotal) AS CommissionTotal 
							FROM dbo.CommissionBillNewDetail
							GROUP BY 
								BillNumberId,
								EtypeID,
								DtypeID
							HAVING EtypeID=@EtypeID AND DtypeID=@DtypeID
							) b		ON a.BillNumberId=b.BillNumberId
									
				LEFT JOIN Stype st		ON a.StypeID = st.TypeId
				LEFT JOIN employee ep	ON a.Checke= ep.TypeID
				LEFT JOIN employee ep1	ON a.Checker= ep1.TypeID
				LEFT JOIN employee ep2	ON a.Poster= ep2.TypeID
				LEFT JOIN employee ep3	ON a.FChecker= ep3.TypeID
				LEFT JOIN employee ep4	ON a.FPoster= ep4.TypeID
				LEFT JOIN employee ep5	ON @EtypeID= ep5.TypeID
				LEFT JOIN CommissionScheme sc ON a.CommissionSchemeID = sc.BillNumberId 
				LEFT JOIN Ac_CommissionBill_VoucherBill d  on a.BillNumberId=d.GoodsBillId
		WHERE   
				a.BillDate >= @Startdate and a.BillDate <=@Enddate 
				AND a.StypeID=@StypeID 
				AND a.ifcheck ='t'
		ORDER BY a.billdate , a.billcode
	

END
----------------------------------------------------------------单据联查结束----------------------------------------------------------------------

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_CommissionQuery_Operate]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].Web_CommissionQuery_Operate
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
	作者：蒋奎
	日期：2014-5-14
	描述：提成查询--button
-------------------------------------------*/

CREATE PROCEDURE Web_CommissionQuery_Operate
    (
	  @BillNumberId NUMERIC(18,0),		--单据ID
      @Function  VARCHAR(50),			--Delete=删除单据 
      @UserID VARCHAR(50),				--审核人
      @CommissionSchemeID NUMERIC(18,0)	--提成方案ID
    )
--@encode$--    
AS
SET NOCOUNT ON

BEGIN
	-------------------------------------------------删除单据-------------------------------------------------------
	IF(@Function='Delete')
	BEGIN
		DECLARE @billstate INT
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.CommissionBillNew WHERE BillNumberId=@BillNumberId AND ifcheck='t'
				  UNION ALL
				  SELECT TOP 1 1 FROM dbo.ListTable WHERE BillNumberId=@BillNumberId AND BillType=311
				  UNION ALL
				  SELECT TOP 1 1 FROM dbo.InOutstocktable WHERE BillNumberId=@BillNumberId AND BillType=311)
		BEGIN
			RAISERROR('该单据已审核过账,不能删除,请刷新后重试！',16,1)	
			RETURN
		END
		SELECT @billstate=billstate FROM dbo.CommissionBillNew WHERE BillNumberId =@BillNumberId
		IF @billstate=1
		BEGIN
			BEGIN TRANSACTION
				BEGIN
					delete from CommissionBillNew where BillNumberId=@BillNumberId 
					delete from CommissionBillNewDetail where BillNumberId=@BillNumberId 
					--判断是否还有提成方案的引用,如果没有就改为未引用
					IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.CommissionBillNew WHERE CommissionSchemeID=@CommissionSchemeID)
						UPDATE CommissionScheme SET UseState=1 WHERE BillNumberId= @CommissionSchemeID
				END
			IF @@ERROR=0
				COMMIT TRANSACTION
			ELSE
				ROLLBACK TRANSACTION
		END
		ELSE
			RAISERROR('单据已审核,不能删除',16,1)	
	END
	
	 
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_Common_BaseInfoCustomCheck]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_Common_BaseInfoCustomCheck]
GO

SET QUOTED_IDENTIFIER ON 

GO
SET ANSI_NULLS ON 
GO

/*
	作者：duguolei
	日期：2012-07-11
	描述：查询判断‘基本资料’里的信息是否与‘自定义’已关联，如果关联基本信息里相关项不能被删除
*/
CREATE PROCEDURE Web_Common_BaseInfoCustomCheck
(			
						--
	@ctypename			VARCHAR(50),		--基本资料项名称(商品:Ptype 分支机构:Stype  仓库:Ktype  往来单位(客户供货商):Btype,gbtype  地区:Areatype  职员:Etype  部门:Dtype  )
	@ctypeid			VARCHAR(50),		--验证项id   (Ptype Stype Ktype Btype Areatype Etype Dtype)
	@result             INT OUTPUT			--返回结果		
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE
	@sql		Nvarchar(MAX)=''
		
		--基本信息自定义
		SELECT @sql=@sql+'IF EXISTS(SELECT 1 FROM '+(CASE BaseType WHEN 'gtype' THEN 'gbtype' ELSE BaseType END)+'_CustomColumns WHERE costom'+cast(CustomerOrder as varchar)+' = '''+@ctypeid+''') 
							BEGIN SELECT @RESULT=1 RETURN END '   --如果存在id，返回1
		FROM CustomBaseInforColumnsDefines
		WHERE CustomerType=@ctypename
		
		EXEC SP_EXECUTESQL @sql,N'@RESULT INT OUTPUT',@RESULT=@RESULT OUTPUT
		IF @RESULT=1  RETURN @RESULT

		SET @sql=''
		--单据表体自定义
		SELECT @sql=@sql+'IF EXISTS(SELECT 1 FROM CustomBillDetailColumns WHERE costom'+cast(CustomerOrder as varchar)+' = '''+@ctypeid+'''  and billtype='+CAST(billtype AS varchar)+') 
							BEGIN SELECT @RESULT=1 RETURN END '   --如果存在id，返回1
		FROM CustomBillDetailColumnsDefines
		WHERE CustomerType=@ctypename

		EXEC SP_EXECUTESQL @sql,N'@RESULT INT OUTPUT',@RESULT=@RESULT OUTPUT
		IF @RESULT=1  RETURN @RESULT
		
		
		SET @sql=''
		--单据表头自定义
		SELECT @sql=@sql+'IF EXISTS(SELECT 1 FROM CustomBillColumns WHERE costom'+cast(CustomerOrder as varchar)+' = '''+@ctypeid+''' and billtype='+CAST(billtype AS varchar)+') 
							BEGIN SELECT @RESULT=1 RETURN END '   --如果存在id，返回1
		FROM CustomBillColumnsDefines
		WHERE CustomerType=@ctypename

		EXEC SP_EXECUTESQL @sql,N'@RESULT INT OUTPUT',@RESULT=@RESULT OUTPUT
		RETURN @RESULT
	--END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ContactsQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_ContactsQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：往来查询
	描述：
*/
CREATE PROCEDURE Web_ContactsQuery
(
	@OperatorID VARCHAR(50), --操作员id
	@StypeID VARCHAR(max),	  --分支机构id,多个以逗号隔开
	@BtypeID VARCHAR(max),	  --往来单位id,多个以逗号隔开
	@bfullname VARCHAR(50),	  --往来单位名称筛选
	@Qtype	CHAR(1)  --I 应收  O应付
)
--@encode$--
AS
SET NOCOUNT ON
	SELECT @OperatorId = typeId FROM dbo.employee WHERE UserCode = @OperatorId or fullname=@OperatorId
	CREATE TABLE #stype(typeid VARCHAR(50))
	CREATE TABLE #btype(typeid VARCHAR(50))
	
	--分支权限
	INSERT INTO #stype
	SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeID,11,@OperatorID)
	
	--往来权限
	INSERT INTO #btype
	SELECT typeid FROM F_GetAllManagerBaseTypeId(@BtypeID,2,@OperatorID)
	
	IF @Qtype='I'
	BEGIN
		SELECT TOP 10 a.BTypeID,a.total,b.FullName,b.UserCode 
		FROM 
		(	SELECT a.BtypeID,SUM(a.ARTotal) AS total
			FROM dbo.BType_ArApTotal a
			INNER JOIN #stype s ON a.stypeid = s.typeid
			INNER JOIN #btype b ON a.BTypeID=b.typeId
			GROUP BY a.BTypeID   
		)a,
		dbo.btype b
		WHERE a.BTypeID=b.typeId
		AND b.typeId LIKE '00001%'
		AND (b.FullName LIKE	 '%'+@bfullname+'%' OR b.UserCode LIKE	 '%'+@bfullname+'%'  OR b.LinkMan1 LIKE	 '%'+@bfullname+'%' OR b.LinkMan2 LIKE	 '%'+@bfullname+'%')
		ORDER BY a.total DESC,b.usercode
	END
	ELSE
	BEGIN
		SELECT TOP 10 a.BTypeID,a.total,b.FullName,b.UserCode 
		FROM 
		(	SELECT a.BtypeID,SUM(a.ApTotal) AS total
			FROM dbo.BType_ArApTotal a
			INNER JOIN #stype s ON a.stypeid = s.typeid
			INNER JOIN #btype b ON a.BTypeID=b.typeId
			GROUP BY a.BTypeID   
		)a,
		dbo.btype b
		WHERE a.BTypeID=b.typeId
		AND b.typeId LIKE '00002%'
		AND (b.FullName LIKE	 '%'+@bfullname+'%'  OR b.UserCode LIKE	 '%'+@bfullname+'%'  OR b.LinkMan1 LIKE	 '%'+@bfullname+'%' OR b.LinkMan2 LIKE	 '%'+@bfullname+'%')
		ORDER BY a.total DESC,b.usercode
	END
	
	DROP TABLE #btype,#stype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_ConvertBillTypeOldSmsContentToHyyun]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Web_ConvertBillTypeOldSmsContentToHyyun]
GO

/*
	作者：谢吉康
	日期：2018-11-06
	描述：翻译叮咚云的短信模版到行业云
	行业云返回：{"result":0,"msg":"ok","id":2495,"status":1}

	DECLARE @smsbilltype INT
	SET @smsbilltype = -1
	
	DECLARE @content VARCHAR(8000)
	SET @content = '尊敬的【@持卡人】会员，您尾号为【@尾号】的会员卡于【@系统时间】充值【@本次储值金额】元，当前储值余额为【@储值余额】元。'	
	
	DECLARE @returncontent VARCHAR(MAX)
	
	EXEC Web_ConvertBillTypeOldSmsContentToHyyun @smsbilltype,@content,@returncontent OUTPUT
	
	SELECT @returncontent
*/
CREATE PROCEDURE Web_ConvertBillTypeOldSmsContentToHyyun
(
	@smsbilltype			VARCHAR(MAX),
	@content				VARCHAR(MAX),
	@returncontent			VARCHAR(MAX) OUTPUT		--返回串
)
AS
SET NOCOUNT ON

DECLARE @colName			VARCHAR(1000),
		@standardContext	VARCHAR(MAX),
		@vipContent			VARCHAR(MAX)
		
SET @standardContext = ''		
		
--先把标准模版数据拿到
IF @smsbilltype = '-1'
BEGIN
	DECLARE VipCursor CURSOR FOR
		SELECT Content from SMSInfo_Params WHERE BillType = @smsbilltype ORDER BY tempTypeId ASC	
		
	OPEN VipCursor
	
	FETCH NEXT FROM VipCursor INTO @vipContent
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @standardContext = ''
			SET @standardContext = @vipContent
		ELSE
			SET @standardContext = @standardContext + '、' + @vipContent
		
		FETCH NEXT FROM VipCursor INTO @vipContent
	END
	
	CLOSE VipCursor
	DEALLOCATE VipCursor	
END
ELSE
BEGIN
	SELECT @standardContext = Content from SMSInfo_Params WHERE BillType = @smsbilltype	
END

--拆分数据
DECLARE TmpCursor CURSOR FOR
	SELECT DISTINCT a FROM dbo.f_split_table(@standardContext,'、')
	
OPEN TmpCursor

FETCH NEXT FROM TmpCursor INTO @colName

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @content = REPLACE(@content,@colName,'◎')
	FETCH NEXT FROM TmpCursor INTO @colName
END

CLOSE TmpCursor
DEALLOCATE TmpCursor
	
--继续翻译数据
DECLARE @SourceSql  VARCHAR(MAX),
		@Result		VARCHAR(MAX),
		@i			INT,
		@j			INT
		
SET @j = 0	
SET @Result = ''	
SET @SourceSql=RTRIM(LTRIM(@content))
SET @i=charindex('◎',@SourceSql)
WHILE @i>=1
BEGIN		
	SET @Result = @Result + SUBSTRING(@SourceSql,0,charindex('◎',@SourceSql)) + '{' + CAST(@j AS VARCHAR) + '}'
	
    SET @SourceSql=SUBSTRING(@SourceSql,@i+1,len(@SourceSql)-@i)    
    
    PRINT(@SourceSql)
    
    SET @i=charindex('◎',@SourceSql)
    
    SET @j = @j + 1
END

SET @returncontent = @Result + @SourceSql

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CopyBillToDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CopyBillToDraft]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2004-07-21
	描述：复制草稿的时候没有复制优惠金额	
	
	【修改】：鲁大林
	日期：2012-06-29
	描述：复制主表和明细表中新加的字段
	
	2013.05.22 周华 添加prepricenum
	
	【修改】：杨俊
	日期：2014-06-24
	描述：复制主表新增调入机构
*/
CREATE PROCEDURE Web_CopyBillToDraft
(
	@OperatorId			VARCHAR(MAX),
	@BillNumberId  		NUMERIC(10,0),
	@Ip					VARCHAR(MAX),
	@copySerial			bit,--是否复制序列号
	@CUR_ID          	NUMERIC(10,0) OUTPUT
 )
--@encode$--
AS
SET NOCOUNT ON

DECLARE @BillType		[int]
DECLARE @Cur_BillNumberId	[numeric](10,0)

DECLARE @RetVal			[int],
		@VIP_ID			INT

SELECT @VIP_ID=NID FROM Ac_Items WHERE UserCode = '2181'
SELECT @CUR_ID = -1

-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid >= 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -5
	END
END  

-- ********	判断是否试用版 - END	********

-- 判断是否存在单据
SELECT 	@Cur_BillNumberId=[BillNumberId], 
		@BillType=[BillType]
FROM 	[BillIndex]
WHERE 	[BillNumberId] = @BillNumberId
IF @@ROWCOUNT = 0 RETURN -1

--如果是会计凭证，则判断是否是VIP充值卡自动生成的，如果是，则不允许复制 谢吉康 2009-01-12
IF @BillType = 159
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AccountCredence WHERE ATypeId = @VIP_ID AND BillNumberId = @BillNumberId AND TypeATypeId IN ('00002'))
			BEGIN
				RETURN -159
			END
	END
	
--调价全部仓库的草稿不允许复制单据 谢吉康 2011-04-15
IF EXISTS(SELECT TOP 1 1 FROM AdPriceBill WHERE BillNumberId = @BillNumberId AND ChangeAllStock = 1)
	RETURN -57
	
--收款单如果只有会员储值，则不允许复制草稿 
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillType = 4 AND BillNumberId = @BillNumberId)
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM gatheringBill WHERE BillNumberId = @BillNumberId AND (VipCardID = -1 OR vipcardid IS NULL) )
		RETURN -58
END

--预收款单如果只有会员储值，则不允许复制草稿 
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillType = 189 AND BillNumberId = @BillNumberId)
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM PreBill WHERE BillNumberId = @BillNumberId AND (VipCardID = -1 OR vipcardid IS NULL) )
		RETURN -59
END

--店账通单据不允许复制
IF EXISTS(SELECT TOP 1 1 FROM dbo.EshopBillRelation WHERE Billnumberid=@BillNumberId)
BEGIN
	RETURN -60
END
		
--积分转储值单
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND BillType=427)
	RETURN -61
	
BEGIN Tran _CopyBillToDraft

---------------------------------------- 插入INDEX 记录---------------------------------------------------------------------------
INSERT INTO BillIndex 
(
	AlertDay,
	BillDate,
	BillCode,
	BillType,
	Comment,
	atypeid,
	ptypeid,
	btypeid,
	etypeid,
	ktypeid,
	ktypeid2,
	ifcheck,
	checke,
	totalmoney,
	totalinmoney,
	totalqty,
	tax,
	period,
	explain,
	RedWord,
	draft,
	OrderId,
	waybillcode,
	goodsnumber,
	packway,
	TEL,
	IfAudit,
	preferencemoney,
	DTypeId,
	KTypeID3,
	LinkMan,
	LinkTel,
	LinkAddr,
	wxManID,
	JieJianBillNumberID,
	JieJianID,
	BaoXiuBillNumberID,
	BaoXiuID,
	BuyDate,
	wxTotal,
	ErrDes,
	ifHideJieJian,
	ifWX,
	Stypeid,
	StypeID2,
	CostSale,
	--FromBillNumberID,--调用关系不用复制过去
	IfMulAccount,
	OtherInOutType,
	uf1,
	uf2,
	uf3,
	uf4,
	uf5,
	DealBTypeID,
	CID,
	RATE,
	NTotalMoney,
	NTotalInMoney,
	NPreferenceMoney,
	NVIPCZMoney,
	billproperty,
	TallyId,
	ATID,
	atypeid1,
	IfCargo,
	prepricenum,
	PromoRuleId,
	BeforePromoBillNumberId,
	AssetBusinessTypeId,
	IsYapi,
	YapiOrderID,
	IfConfirm,
	TransferType,
	DeliveryAddress,
	discount,
	AdPriceType,
	IsLend   ,
	ChargeOffBtypeid,
	ChargeOffType,
	ChargeOffTotal,
	NChargeOffTotal,
	iscombinationstyle   ,
	IsNeedTransport,
	isByBrandarType
)
SELECT 	AlertDay,
		BillDate,
		BillCode,
		BillType,
		case when NewPosBill=1 and BillType in (305,215) then '' else comment end,
		CASE WHEN atypeid = @VIP_ID THEN '' ELSE atypeid END,
		ptypeid,
		btypeid,
		etypeid,
		ktypeid,
		ktypeid2,
		'f',
		checke,
		totalmoney,
		CASE WHEN atypeid = @VIP_ID THEN 0 ELSE TotalInMoney END,
		totalqty,
		tax,
		period,
		explain,
		0,
		1,
		OrderId,
		waybillcode,
		goodsnumber,
		packway,
		TEL,
		'3',
		preferencemoney,
		DTypeId,
		KTypeID3,
		LinkMan,
		LinkTel,
		LinkAddr,
		wxManID,
		JieJianBillNumberID,
		JieJianID,
		BaoXiuBillNumberID,
		BaoXiuID,
		BuyDate,
		wxTotal,
		ErrDes,
		ifHideJieJian,
		ifWX,
		Stypeid,
		stypeid2,
		CostSale,
		--CASE WHEN BillType=188 THEN 0 ELSE FromBillNumberID END,
		IfMulAccount,
		OtherInOutType,
		uf1,
		uf2,
		uf3,
		uf4,
		uf5,
		DealBTypeID,
		CID,
		RATE,
		NTotalMoney,
		NTotalInMoney,
		NPreferenceMoney,
		NVIPCZMoney,
		billproperty,
		'',
		0,
		--atypeid1,处理系统升级，之前没有启用总账的话，启用后，复制之前的单据，单据中往来科目为空
		ATypeID1=CASE WHEN (ISNULL(ATypeID1,'')='') AND CAST(BillType AS VARCHAR(50)) IN(SELECT BillTypeId FROM BillAtype) 
									THEN (SELECT AtypeId FROM dbo.BillAtype 
														WHERE BillTypeId=CAST(dbo.BillIndex.BillType AS VARCHAR(50)) 
																		AND dbo.BillIndex.Stypeid=dbo.BillAtype.StypeId) ELSE ATypeID1 END,
		IfCargo,
		prepricenum,
		0,
		0,
		AssetBusinessTypeId,
		IsYapi,
		YapiOrderID,
		0,--IfConfirm,9.4BUG 3133 取消复制时将是否确认也复制了
		TransferType,
		DeliveryAddress,
		discount,
		AdPriceType,
		--CASE WHEN BillType=11 OR BillType=34 THEN IsLend ELSE 0 END,
		0,--不用复制过去
		ChargeOffBtypeid,
		ChargeOffType,
		0,
		0 ,
		iscombinationstyle,
		IsNeedTransport,
		isByBrandarType 
FROM 	BillIndex
WHERE 	[BillNumberId] = @BillNumberId

IF @@error<>0 
BEGIN 
   SELECT @RetVal = -2 
   GOTO Error 
END
SELECT @Cur_BillNumberId = SCOPE_IDENTITY();

--处理多账户的复制
IF EXISTS(SELECT TOP 1 1 FROM BillMulAccount WHERE BillNumberId = @BillNumberId AND  BILLTYPE =@BillType)
BEGIN
	INSERT INTO BillMulAccount(ATypeID,BillNumberId,Comment,Total,VipCardID,NTotalMoney,BillType,yhType,CouponCode,viptotal)
	SELECT	ATypeID,@Cur_BillNumberId AS BillNumberId,Comment,Total,VipCardID,NTotalMoney,BillType,yhType,CouponCode,viptotal
	FROM	BillMulAccount
	WHERE	BillNumberId = @BillNumberId AND  BILLTYPE =@BillType 
END

--处理品牌多账户的复制：判断如果没有多账号，则需要修改多账户标识IfMulAccount
IF EXISTS (SELECT TOP 1 1 FROM BillMulBrand WHERE BillNumberId = @BillNumberId AND BillType =@BillType)
	BEGIN
		INSERT INTO BillMulBrand(STypeID,BTypeID,BrandarTypeID,BillNumberId,BillType,Cid,Rate,TaxTotal,NTaxTotal,PreferenceMoney,NPreferenceMoney,TotalInMoney,NTotalInMoney,TheOrderARTotal,NTheOrderARTotal,YSTotalInMoney,NYSTotalInMoney,isIni)
		SELECT STypeID,BTypeID,BrandarTypeID, @Cur_BillNumberId BillNumberId,BillType,Cid,Rate,TaxTotal,NTaxTotal,PreferenceMoney,NPreferenceMoney,TotalInMoney,NTotalInMoney,TheOrderARTotal,NTheOrderARTotal,YSTotalInMoney,NYSTotalInMoney,isIni FROM BillMulBrand WHERE BillNumberId=@BillNumberId AND  BILLTYPE =@BillType
	END

--当新单据多账户信息中存在会员卡信息，则不复制多账户信息并且清空收款金额
IF EXISTS(SELECT TOP 1 1 FROM BillMulAccount WHERE BillNumberId = @Cur_BillNumberId  AND  BILLTYPE =@BillType AND VipCardID <> -1)
BEGIN
	DELETE FROM BillMulAccount WHERE BillNumberId = @Cur_BillNumberId AND  BILLTYPE =@BillType	
	UPDATE BillIndex SET totalinmoney = 0,NTotalInMoney=0,atypeid='' WHERE BillNumberId = @Cur_BillNumberId AND  BILLTYPE =@BillType
	
	DELETE FROM dbo.BillMulBrand WHERE BillNumberId = @Cur_BillNumberId AND BillType = @BillType
	UPDATE	BillIndex SET IfMulAccount =0 WHERE BillNumberId = @Cur_BillNumberId  AND billtype=@BillType
END
--当新单据多账户信息中存在优惠券信息，则不复制多账户信息并且清空收款金额
IF EXISTS(SELECT TOP 1 1 FROM BillMulAccount WHERE BillNumberId = @Cur_BillNumberId AND  BILLTYPE =@BillType AND yhtype IN (1,2))
BEGIN
	DELETE FROM BillMulAccount WHERE BillNumberId = @Cur_BillNumberId AND  BILLTYPE =@BillType	
	UPDATE dbo.BillIndex SET totalinmoney = 0,NTotalInMoney=0,atypeid='' WHERE BillNumberId = @Cur_BillNumberId AND  BILLTYPE =@BillType
	
	DELETE FROM dbo.BillMulBrand WHERE BillNumberId = @Cur_BillNumberId AND BillType = @BillType
	UPDATE	BillIndex SET IfMulAccount =0 WHERE BillNumberId = @Cur_BillNumberId  AND billtype=@BillType
END
----支付宝、微信支付的单据清空多账户表并且清空收款金额
DECLARE @PayType INT=0
IF EXISTS(SELECT 1 FROM dbo.BillMulAccount WHERE BillNumberId=@BillNumberId AND  BILLTYPE =@BillType)
BEGIN
	SELECT @PayType=PayType FROM dbo.BillMulAccount WHERE BillNumberId=@BillNumberId AND  BILLTYPE =@BillType
END 
IF (@PayType<>0)
BEGIN
	--DELETE FROM BillMulAccount WHERE BillNumberId = @Cur_BillNumberId	
	--UPDATE BillIndex SET totalinmoney = 0,NTotalInMoney=0,atypeid='' WHERE BillNumberId = @Cur_BillNumberId
	UPDATE dbo.BillMulAccount SET TradeNo ='',PayType = 0 WHERE BillNumberId = @Cur_BillNumberId AND  BILLTYPE =@BillType
END

--如果是零售单，实收金额是另外一个字段
IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @Cur_BillNumberId AND BillType = 305 AND ISNULL(ATypeId,'')='') AND EXISTS(SELECT TOP 1 1 FROM BillMulAccount WHERE BillNumberId = @Cur_BillNumberId AND  BILLTYPE =@BillType AND VipCardID <> -1)
BEGIN	
	UPDATE BillIndex SET PackWay = 0 WHERE BillNumberId = @Cur_BillNumberId
END

--汽配类单据需要插入另外一张表 快修单、洗车结算单、保险理赔单
/*
	195	维修结算单	       汽配维修类
	191	领料出库单	       汽配维修类
	197	领料退回单	       汽配维修类
	200	三包索赔单	       汽配维修类
	196	救援单	         	汽配维修类
	SELECT * FROM BillName WHERE BillType IN (178,179,196)
*/	
IF @BillType IN (178,179,196)
	BEGIN
		INSERT INTO Billindex_CarRepair (InsuranceStatus,BillNumberId, BillDate, BillType, RATypeID, OperationSort, RepairMode, Oil, Mileage, EpibolyItem, OtherItem, Status, ManHourTotal, ManHourTax, ManHourTaxTotal, PTypeTotal, PTypeTax, PTypeTaxTotal, EpibolyTotal, OtherTotal, InPriceType, BTypeID1, QuickRepairBillID, ManHourInsuranceTotal, PTypeInsuranceTotal, InvoiceMode, InvoiceCode,RepairType, BespokeDate, ReceptionDate, CompleteDate, InFactoryDate, FactCompleteDate, ReceptionId, UnitSatrap, SendPerson, ErrDescription, EpibolyCostTotal, PreferenceReason, BalanceDate, ItemPrincipal, MonitorPrincipal, BillState, BackTypeId, IntendingTalkBackDate, IsTalkBackOver, IntendingKickback, SettlementKickback,RepairAutoTypeId)
		SELECT	(CASE WHEN InsuranceStatus=2 THEN 1 ELSE InsuranceStatus END ) as InsuranceStatus ,@Cur_BillNumberId, BillDate, BillType, RATypeID, OperationSort, RepairMode, Oil, Mileage, EpibolyItem, OtherItem, 0 AS Status, ManHourTotal, ManHourTax, ManHourTaxTotal, PTypeTotal, PTypeTax, PTypeTaxTotal, EpibolyTotal, OtherTotal, InPriceType, BTypeID1, QuickRepairBillID, ManHourInsuranceTotal, PTypeInsuranceTotal, InvoiceMode, InvoiceCode,RepairType, BespokeDate, ReceptionDate, CompleteDate, InFactoryDate, FactCompleteDate, ReceptionId, UnitSatrap, SendPerson, ErrDescription, EpibolyCostTotal, PreferenceReason, '9999-12-31 23:59:59.997' AS BalanceDate, ItemPrincipal, MonitorPrincipal, BillState, BackTypeId, IntendingTalkBackDate, IsTalkBackOver, IntendingKickback, SettlementKickback,RepairAutoTypeId
		FROM	Billindex_CarRepair
		WHERE	BillNumberId = @BillNumberId	
	END

CREATE TABLE #OLDbILLID(ID int IDENTITY(1,1), detailID int)

CREATE TABLE #NewbILLID(ID int IDENTITY(1,1), detailID int)


CREATE TABLE #NewbILLID1(ID int IDENTITY(1,1), detailID int)
------------------------------------ 插入 明细  记录--------------------------------------------------------------------------------
----------------------------------以下为处理pos终端上传上来的单据需要单独处理-提取主表数据--------------
CREATE TABLE #TEMP_INDEX
(
	BILLNUMBERID VARCHAR(50),
	NEWPOSBILL	VARCHAR(2)--1：pos终端上传；0：非pos终端上传
)
INSERT INTO #TEMP_INDEX SELECT BILLNUMBERID,NEWPOSBILL FROM BillIndex WHERE BillType IN (305,215)

-----处理是否复制序列号
IF @copySerial='TRUE'
BEGIN
IF @BillType = 305 --------零售单-----------
BEGIN
	INSERT INTO dbo.retailBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          SaleTotal ,
	          Tax ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          pricedetailid,
	          priceRuleid,
	          PriceSource,
	          ETypeID,
	          ShowOrder,
	          iscombination,
	          combinationptypeid,
	          pindexid,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			  PtypeId ,
			  Qty ,
			  SalePrice ,
			  discount ,
			  DiscountPrice ,
			  costprice ,
			  jobnumber ,
			  goodsno ,
			  total ,
			  OutFactoryDate ,
			  TaxPrice ,
			  TaxTotal ,
			  CASE NEWPOSBILL WHEN 0 THEN comment WHEN 1 THEN '' END AS COMMENT ,
			  OrderID ,
			  TeamNo ,
			  TeamNO1 ,
			  IsUnit2 ,
			  GoodsOrder ,
			  GoodsNumber ,
			  ProduceDate ,
			  ValidDate ,
			  GoodsBTypeID ,
			  GoodsCostPrice ,
			  GoodsCostTotal ,
			  SaleTotal ,
			  Tax ,
			  Stypeid ,
			  TaxMoney ,
			  NSalePrice ,
			  NSaleTotal ,
			  NDiscountPrice ,
			  NTotal ,
			  NTaxPrice ,
			  NTaxTotal ,
			  NTaxMoney ,
			  UnitID ,
			  NUnitID ,
			  NQty ,
			  UnitRate ,
			  NUnitMsg ,
			  MUnitID ,
			  MQty ,
			  MUnitRate ,
			  MUnitMsg ,
			  MSalePrice ,
			  MDiscountPrice ,
			  MTaxPrice ,
			  CurMSalePrice ,
			  CurMDiscountPrice ,
			  CurMTaxPrice ,
			  CargoID ,
			  ItemID ,
			  IsCombined,
			  Serial,
			  0,
	          0,
	          '通过单据复制',
	          ETypeID,
	          ShowOrder,
	          iscombination,
	          combinationptypeid,
	          pindexid,
	          KTypeId
	FROM retailbill INNER JOIN #TEMP_INDEX ON retailBill.BillNumberId=#TEMP_INDEX.BILLNUMBERID
	WHERE RETAILBILL.[BillNumberId] = @BillNumberId ORDER BY ID
	INSERT INTO RetailCombinationBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,
		OutFactoryDate,TaxPrice,TaxTotal,IsUnit2,BackQTY,SaleTotal,Tax,Stypeid,TaxMoney,NSalePrice,
		NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,
		CurMDiscountPrice,CurMTaxPrice,CargoID,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,PosId,
		BeforePromoID,PriceDetailId,PriceRuleId,PriceSource,PriceStyle,PromoType,pindexid,comment,ETypeID,itemid,iscombined)
	SELECT 
			@Cur_BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,
		OutFactoryDate,TaxPrice,TaxTotal,IsUnit2,BackQTY,SaleTotal,Tax,Stypeid,TaxMoney,NSalePrice,
		NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,
		CurMDiscountPrice,CurMTaxPrice,CargoID,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,PosId,
		BeforePromoID,PriceDetailId,PriceRuleId, '通过单据复制',PriceStyle,PromoType,pindexid,comment,ETypeID,itemid,iscombined
		FROM RetailCombinationBill WHERE BillNumberId=@BillNumberId
END
ELSE IF @BillType = 11 ---------------销售单-----
	BEGIN
		INSERT INTO dbo.SaleBill
		        ( BillNumberId ,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          GoodsOrder ,
		          BackQty ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined,
		          entryCode,
		          pricesource,
		          Serial,
		          ShowOrder,
		          ETypeID
		          --IsGift
		        )
		output inserted.ID INTO #NewbILLID
		SELECT @Cur_BillNumberId,
				PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          GoodsOrder ,
		          0 ,--backqty不复制
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          0 AS CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined,
		          entryCode,
		          '通过单据复制',
		          Serial,
		          ShowOrder,
		          ETypeID
		          --IsGift
		FROM salebill
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
----------这个是啥
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND CostSale = 1)
			BEGIN
				UPDATE	SaleBill
				SET		SalePrice = 0,
						DiscountPrice = 0,
						total = 0,
						TaxPrice = 0,
						TaxTotal = 0,
						SaleTotal = 0,
						NSalePrice = 0,
						NDiscountPrice = 0,
						NTotal = 0,
						NTaxPrice = 0,
						NTaxTotal = 0,
						NSaleTotal = 0,
						CurMSalePrice = 0,
						CurMDiscountPrice = 0,
						CurMTaxPrice = 0,
						TaxMoney=0,
						NTaxMoney=0
				WHERE	BillNumberId = @Cur_BillNumberId
				
				UPDATE BillIndex SET totalmoney = 0,NTotalMoney = 0 WHERE BillNumberId = @Cur_BillNumberId
			END
		--处理销售订单的代发货数量
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM SaleBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
	END
ELSE IF @BillType = 45 -------------------销售退货单
BEGIN
	INSERT INTO dbo.saleBackBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          CostPrice ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          FromBillNumberID ,
	          FromBillID ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          IsGift,
	          ShowOrder,
	          ETypeID
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          CostPrice ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          FromBillNumberID ,
	          FromBillID ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          IsGift,
	          ShowOrder,
	          ETypeID
	FROM salebackbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
END
ELSE IF @BillType = 4 ------------收款单
    BEGIN
		INSERT INTO dbo.gatheringBill
		        ( BillNumberId ,
		          AtypeId ,
		          total ,
		          Comment ,
		          TeamNo ,
		          TeamNO1 ,
		          Stypeid ,
		          ntotal ,
		          VipCardID,
		          ShowOrder,
		          RelevanceBillId,
		          BrandarTypeID,
		          PreferenceMoney,
		          NPreferenceMoney
		        )
		 OUTPUT inserted.ID INTO #NewbILLID
		SELECT  @Cur_BillNumberId,
				AtypeId ,
		          total ,
		          Comment ,
		          TeamNo ,
		          TeamNO1 ,
		          Stypeid ,
		          ntotal ,
		          VipCardID,
		          ShowOrder,
		          RelevanceBillId,
		          BrandarTypeID,
		          PreferenceMoney,
		          NPreferenceMoney
		FROM	gatheringbill		
		WHERE	[BillNumberId] = @BillNumberId 
				AND (VipCardID = -1 OR vipcardid IS NULL) 
		ORDER BY ID
		--收款单如果有会员储值，则删除会员储值 
		DECLARE @GatherTotalMoney  NUMERIC(24, 10) ,@GatherNTotalMoney	 NUMERIC(24, 10) 		
		SELECT @GatherTotalMoney = ISNULL(SUM(Total),0) FROM gatheringBill WHERE BillNumberId = @Cur_BillNumberId
		SELECT @GatherNTotalMoney = ISNULL(SUM(NTotal),0) FROM gatheringBill WHERE BillNumberId = @Cur_BillNumberId
		
		UPDATE BillIndex SET totalmoney = @GatherTotalMoney,totalinmoney = @GatherTotalMoney,
						    NTotalMoney=@GatherNTotalMoney,NTotalInMoney=@GatherNTotalMoney,IfMulAccount = 0 
						    WHERE BillNumberId = @Cur_BillNumberId
	END
ELSE IF @BillType = 34 --进货单
BEGIN
	INSERT INTO dbo.BuyBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          jobnumber ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo1 ,
	          TeamNo ,
	          orderid ,
	          IsUnit2 ,
	          GoodsOrder ,
	          BackQty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          CompleteQTY ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          FromBillNumberID ,
	          FromBillID ,
	          ShareFee ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          entryCode,
	          InvoiceMoney,
	          InvoiceQty,
	          Serial,
	          IsGift,
	          ShowOrder
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          jobnumber ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo1 ,
	          TeamNo ,
	          orderid ,
	          IsUnit2 ,
	          GoodsOrder ,
	          BackQty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          0 AS CompleteQTY ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          FromBillNumberID ,
	          FromBillID ,
	          ShareFee ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          entryCode,
	          0 AS InvoiceMoney,
	          0 AS InvoiceQty,
	          Serial,
	          IsGift,
	          ShowOrder
	FROM buybill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM BuyBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
END
ELSE IF @BillType = 6 --进货退货单
BEGIN
	INSERT INTO dbo.BuyBackBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          IsGift,
	          ShowOrder
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          IsGift,
	          ShowOrder
	FROM buybackbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
END
ELSE IF @BillType = 66 --付款单
	BEGIN
		INSERT INTO dbo.PayBill
		        ( BillNumberId ,
		          AtypeId ,
		          total ,
		          Comment ,
		          TeamNo ,
		          TeamNO1 ,
		          Stypeid ,
		          ntotal ,
		          VipCardID,
		          ShowOrder
		        )
		SELECT @Cur_BillNumberId,
				 AtypeId ,
		          total ,
		          Comment ,
		          TeamNo ,
		          TeamNO1 ,
		          Stypeid ,
		          ntotal ,
		          VipCardID,
		          ShowOrder
		FROM paybill
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	END
ELSE IF @BillType = 21 --变价调拨单
	INSERT INTO dbo.MoveBjBill
	        ( BillNumberId ,
	          Comment ,
	          PtypeId ,
	          Qty ,
	          price ,
	          total ,
	          Jobnumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          InCargoID ,
	          OutCargoID ,
	          ItemID ,
	          IsCombined ,
	          KTypeId ,
	          KTypeId2,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			Comment ,
	          PtypeId ,
	          Qty ,
	          price ,
	          total ,
	          Jobnumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          InCargoID ,
	          OutCargoID ,
	          ItemID ,
	          IsCombined ,
	          KTypeId ,
	          KTypeId2,
	          Serial,
	          ShowOrder
	FROM movebjbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 17 --同价调拨单
	INSERT INTO dbo.MoveBill
	        ( BillNumberId ,
	          Comment ,
	          PtypeId ,
	          Qty ,
	          Price ,
	          Total ,
	          Jobnumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          InCargoID ,
	          OutCargoID ,
	          ItemID ,
	          IsCombined ,
	          KTypeId ,
	          KTypeId2,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
		Comment ,
	          PtypeId ,
	          Qty ,
	          Price ,
	          Total ,
	          Jobnumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          InCargoID ,
	          OutCargoID ,
	          ItemID ,
	          IsCombined ,
	          KTypeId ,
	          KTypeId2,
	          Serial,
	          ShowOrder
	FROM movebill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 57 --调价单
	INSERT INTO dbo.AdPriceBill
	        ( BillNumberId ,
	          Comment ,
	          PtypeId ,
	          Qty ,
	          BeforePrice ,
	          BeforeTotal ,
	          Rate ,
	          Price ,
	          total ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          ChangeAllStock ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          NQty ,
	          UnitRate ,
	          ItemID ,
	          IsCombined ,
	          cargoID,
	          ktypeid,
	          FromBillID,
	          Serial,
	          ShowOrder,
	          ChangeTotal,
	          Type,
	          NPrice,NTotal
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId,
			Comment ,
	          PtypeId ,
	          Qty ,
	          BeforePrice ,
	          BeforeTotal ,
	          Rate ,
	          Price ,
	          total ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          ChangeAllStock ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          NQty ,
	          UnitRate ,
	          ItemID ,
	          IsCombined ,
	          cargoID,
	          ktypeid,
	          FromBillID,
	          Serial,
	          ShowOrder,
	          ChangeTotal,
	          Type,
	          NPrice,NTotal
	FROM	adpricebill
	WHERE	[BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 9 --报损单
	INSERT INTO dbo.LoseBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			  PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder,
	          KTypeId
	FROM losebill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 14 --报溢单
	INSERT INTO dbo.overflowBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          Comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          Comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder,
	          KTypeId
	FROM overflowbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID

ELSE IF @BillType IN(36,93,84,85,78,5,10,158) -- 费用，其他收入   固定资产购买、变卖、折旧、待摊费用发生、摊销 ,158为现金费用单为2002-11-6吴德水添加
	INSERT INTO dbo.MoneyBill
	        ( BillNumberId ,
	          AtypeId ,
	          total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          NTotal,
	          DTypeId,
	          ETypeId,
	          ShowOrder,
	          BrandarTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			AtypeId ,
	          total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          NTotal,
	          DTypeId,
	          ETypeId ,
	          ShowOrder,
	          BrandarTypeId
	FROM moneybill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType=77 -- 转款单
	INSERT INTO dbo.MoveMoneyBill
	        ( BillNumberId ,
	          Comment ,
	          AtypeId ,
	          total ,
	          Stypeid,
			  ntotal,
			  ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			Comment ,
	          AtypeId ,
	          total ,
	          Stypeid,
	          ntotal,
	          ShowOrder
	FROM MoveMoneyBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType IN(115,116,128,129) -- 调帐单
	INSERT INTO dbo.AdDebtBill
	        ( BillNumberId ,
	          Comment ,
	          BtypeId ,
	          total ,
	          TeamNo ,
	          TeamNO1 ,
	          CompleteTotal ,
	          Stypeid ,
	          NTotal ,
	          NCompleteTotal,
	          ShowOrder,
	          BrandarTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			Comment ,
	          BtypeId ,
	          total ,
	          TeamNo ,
	          TeamNO1 ,
	          0 ,
	          Stypeid ,
	          NTotal ,
	          0,
	          ShowOrder,
	          BrandarTypeId
	FROM addebtbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 16 --拆装单
	INSERT INTO dbo.DisassembleBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          costprice ,
	          jobnumber ,
	          total ,
	          inorout ,
	          outfactorydate ,
	          comment ,
	          goodsno ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          KTypeID ,
	          Stypeid ,
	          NQty ,
	          UnitRate ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          IsUnit2,
	          Serial,
	          MUnitId,
	          MUnitRate,
	          MQty,
	          CurMSalePrice ,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          costprice ,
	          jobnumber ,
	          total ,
	          inorout ,
	          outfactorydate ,
	          comment ,
	          goodsno ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          KTypeID ,
	          Stypeid ,
	          NQty ,
	          UnitRate ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          IsUnit2,
	          Serial,
	          MUnitId,
	          MUnitRate,
	          MQty,
	          CurMSalePrice ,
	          ShowOrder
	FROM DisassembleBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 126 --获赠单  2002-11-6吴德水添加
	INSERT INTO dbo.GivemeBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          KTypeId,
	          ShowOrder
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          KTypeId,
	          ShowOrder
	FROM GivemeBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 139 --赠送单 2002-11-6吴德水添加
	INSERT INTO dbo.GiveBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          KTypeId,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          KTypeId,
	          ShowOrder
	FROM GiveBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType IN (140,141,142,143,144,145,146,147) --代销单据 2003-04-20肖伟添加
BEGIN
	INSERT INTO dbo.CommissionBill
	        ( BillNumberId ,
	          Type ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          Discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          Goodsno ,
	          Total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          OldID ,
	          OldBillNumberID ,
	          BackQty ,
	          CompleteQTY ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          BQTY ,
	          OldBillid ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			Type ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          Discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          Goodsno ,
	          Total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          OldID ,
	          OldBillNumberID ,
	          BackQty ,
	          0 AS CompleteQTY ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          BQTY ,
	          OldBillid ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder
	FROM CommissionBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND BillType=144 AND CostSale = 1)
			BEGIN
				UPDATE	CommissionBill
				SET		SalePrice = 0,
						DiscountPrice = 0,
						total = 0,
						TaxPrice = 0,
						TaxTotal = 0,
						SaleTotal = 0,
						NSalePrice = 0,
						NDiscountPrice = 0,
						NTotal = 0,
						NTaxPrice = 0,
						NTaxTotal = 0,
						NSaleTotal = 0,
						CurMSalePrice = 0,
						CurMDiscountPrice = 0,
						CurMTaxPrice = 0,
						TaxMoney=0,
						NTaxMoney=0
				WHERE	BillNumberId = @Cur_BillNumberId
				
				UPDATE BillIndex SET totalmoney = 0,NTotalMoney = 0 WHERE BillNumberId = @Cur_BillNumberId
			END
	IF @BILLTYPE IN (140,144)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM CommissionBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
	END
END	
ELSE IF @BillType = 148 --返利执行单
	INSERT INTO dbo.Advantage
	        ( BillNumberId ,
	          Ptypeid ,
	          StartDate ,
	          EndDate ,
	          StandardCode ,
	          Type ,
	          Qty ,
	          Total ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber,
	          Serial
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
	          Ptypeid ,
	          StartDate ,
	          EndDate ,
	          StandardCode ,
	          Type ,
	          Qty ,
	          Total ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber,
	          Serial
	FROM Advantage
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType IN( 149,151) --价保执行单
	INSERT INTO dbo.PriceProtectBill
	        ( BillNumberid ,
	          Serial ,
	          Ptypeid ,
	          OldTotal ,
	          OldPrice ,
	          Qty ,
	          NewPrice ,
	          Total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			  '',
	          Ptypeid ,
	          OldTotal ,
	          OldPrice ,
	          Qty ,
	          NewPrice ,
	          Total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber
	FROM PriceProtectBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 150 --获利执行单
	INSERT INTO dbo.Advantage
	        ( BillNumberId ,
	          Ptypeid ,
	          StartDate ,
	          EndDate ,
	          StandardCode ,
	          Type ,
	          Qty ,
	          Total ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber,
	          Serial
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
	          Ptypeid ,
	          StartDate ,
	          EndDate ,
	          StandardCode ,
	          Type ,
	          Qty ,
	          Total ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber,
	          Serial
	FROM Advantage
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 155	-- 商品换货单
	INSERT INTO dbo.GoodsExchangeBill
	        ( BillNumberId ,
	          InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder,
	          Serial
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder,
	          Serial
	FROM GoodsExchangeBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 157	-- 维修受理单
BEGIN
	INSERT INTO dbo.RepairDealDetail
	        ( BillNumberId ,
	          InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal,
	          Serial
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Serial
	FROM RepairDealDetail
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	
	INSERT INTO dbo.RepairDeal
	        ( BillNumberID ,
	          EngageBillID ,
	          BillDate ,
	          BillCode ,
	          BillType ,
	          PTypeID ,
	          ETypeID ,
	          IfCheck ,
	          Checke ,
	          RedWord ,
	          Draft ,
	          Stat ,
	          Fault ,
	          Comment ,
	          Method ,
	          KTypeID1 ,
	          KTypeID2 ,
	          MoneyChange ,
	          MoneyRepair ,
	          TotalMoney ,
	          TotalInMoney ,
	          BTypeID ,
	          ATypeID ,
	          Brief ,
	          NotFree ,
	          FreeMemo ,
	          ETypeID1 ,
	          ETypeID2 ,
	          PayDate ,
	          IfPay ,
	          IDCard ,
	          TeamNo
	        )
	SELECT @Cur_BillNumberId,
			EngageBillID ,
	          BillDate ,
	          BillCode ,
	          BillType ,
	          PTypeID ,
	          ETypeID ,
	          'f' ,
	          Checke ,
	          RedWord ,
	          '1' ,
	          Stat ,
	          Fault ,
	          Comment ,
	          Method ,
	          KTypeID1 ,
	          KTypeID2 ,
	          MoneyChange ,
	          MoneyRepair ,
	          TotalMoney ,
	          TotalInMoney ,
	          BTypeID ,
	          ATypeID ,
	          Brief ,
	          NotFree ,
	          FreeMemo ,
	          ETypeID1 ,
	          ETypeID2 ,
	          PayDate ,
	          IfPay ,
	          IDCard ,
	          TeamNo
	FROM RepairDeal
	WHERE [BillNumberId] = @BillNumberId
END
ELSE IF @BillType = 159	-- 会计凭证
BEGIN
	INSERT INTO dbo.AccountCredence
	        ( BillNumberID ,
	          TypeATypeID ,
	          ATypeID ,
	          J_Total ,
	          D_Total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          NJ_Total ,
	          ND_Total,
	          CID,
	          Rate,
	          BrandarTypeId,
	          ETypeId,
	          DTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberID,
			TypeATypeID ,
	          ATypeID ,
	          dbo.F_RoundTotal(J_Total),
	          dbo.F_RoundTotal(D_Total) ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          dbo.F_RoundTotal(NJ_Total) ,
	          dbo.F_RoundTotal(ND_Total),
	          CID,
	          dbo.F_RoundExchangeRate(Rate),
	          BrandarTypeId,
	          ETypeId,
	          DTypeId
	FROM AccountCredence
	WHERE [BillNumberId] = @BillNumberID ORDER BY ID
END
ELSE IF @BillType = 160	-- 销售换货单
	INSERT INTO dbo.SaleGoodsExchangeBill
	        ( BillNumberId ,
	          InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          KTypeID2 ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          IsGift,
	          ShowOrder,
	          ETypeID
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          KTypeID2 ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          IsGift,
	          ShowOrder,
	          ETypeID
	FROM SaleGoodsExchangeBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 161	-- 采购换货单
	INSERT INTO dbo.BuyGoodsExchangeBill
	        ( BillNumberId ,
	          InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          KTypeID2 ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          IsGift,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          KTypeID2 ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          IsGift,
	          ShowOrder
	FROM BuyGoodsExchangeBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
-- 新维修相关单据
ELSE IF @BillType = 165	-- 新维修 - 接件单
	INSERT INTO dbo.wx_Bill_JieJian
	        ( BillNumberId ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          BuyDate ,
	          ErrDes ,
	          Total ,
	          AddTotal ,
	          ErrDeal ,
	          RepairMode ,
	          ETypeID ,
	          BaoXiu ,
	          Comment ,
	          State ,
	          SendBackPTypeID ,
	          SendBackSerial ,
	          OutFactoryDate ,
	          ifYearBillDisplay ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          BuyDate ,
	          ErrDes ,
	          Total ,
	          AddTotal ,
	          ErrDeal ,
	          RepairMode ,
	          ETypeID ,
	          BaoXiu ,
	          Comment ,
	          0 ,
	          SendBackPTypeID ,
	          SendBackSerial ,
	          OutFactoryDate ,
	          ifYearBillDisplay ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	FROM wx_Bill_JieJian
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 166	-- 新维修 - 维修单
	INSERT INTO dbo.wx_Bill_Self
	        ( BillNumberiD ,
	          InOrOut ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          wxProperty ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          wxProperty ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_Self
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 167	-- 新维修 - 取件单
	INSERT INTO dbo.wx_Bill_GetBack
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          Total ,
	          CompleteQTY ,
	          OutFactoryDate ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          Total ,
	          0 AS CompleteQTY ,
	          OutFactoryDate ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	FROM wx_Bill_GetBack
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 168	-- 新维修 - 整机更换单
	INSERT INTO dbo.wx_Bill_Replace
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Total ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          OutFactoryDate ,
	          wxProperty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Total ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          OutFactoryDate ,
	          wxProperty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_Replace
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 169	-- 新维修 - 送修单
	INSERT INTO dbo.wx_Bill_Send
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          SendBackQty ,
	          Total ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          OutFactoryDate ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          0 ,
	          Total ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          OutFactoryDate ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	FROM wx_Bill_Send
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 170	-- 新维修 - 送修返回单
	INSERT INTO dbo.wx_Bill_SendBack
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Total ,
	          Comment ,
	          SendBillNumberID ,
	          SendID ,
	          SendPTypeID ,
	          CompleteQTY ,
	          OutFactoryDate ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Total ,
	          Comment ,
	          SendBillNumberID ,
	          SendID ,
	          SendPTypeID ,
	          0 AS CompleteQTY ,
	          OutFactoryDate ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	FROM wx_Bill_SendBack
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 171	-- 新维修 - 报修单
	INSERT INTO dbo.wx_Bill_Call
	        ( BillNumberId ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          BuyDate ,
	          ErrDes ,
	          Total ,
	          ErrDeal ,
	          ETypeID ,
	          BaoXiu ,
	          Comment ,
	          OutFactoryDate ,
	          State ,
	          ifYearBillDisplay ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          BuyDate ,
	          ErrDes ,
	          Total ,
	          ErrDeal ,
	          ETypeID ,
	          BaoXiu ,
	          Comment ,
	          OutFactoryDate ,
	          0 ,
	          ifYearBillDisplay ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	FROM wx_Bill_Call
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 172	-- 新维修 - 上门维修单
	INSERT INTO dbo.wx_Bill_Goto
	        ( BillNumberiD ,
	          InOrOut ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          wxProperty ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          wxProperty ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_Goto
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 173	-- 新维修 - 维修品调入单
	INSERT INTO dbo.wx_Bill_In
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_In
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 174	-- 新维修 - 维修品调出单
	INSERT INTO dbo.wx_Bill_Out
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_Out
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 175	-- 新维修 - 维修品调拨单
	INSERT INTO dbo.wx_Bill_Move
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Comment ,
	          OutFactoryDate ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Comment ,
	          OutFactoryDate ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          Serial,
	          ShowOrder
	FROM 	wx_Bill_Move
	WHERE 	[BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 183	-- 积分兑换单
	INSERT INTO dbo.IntegralExchangeBill
	        ( BillNumberId ,
	          KTypeID ,
	          PTypeID ,
	          Qty ,
	          Price ,
	          total ,
	          Comment ,
	          IsUnit2 ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          NQty ,
	          UnitRate ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId, 
			KTypeID ,
	          PTypeID ,
	          Qty ,
	          Price ,
	          total ,
	          Comment ,
	          IsUnit2 ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          NQty ,
	          UnitRate ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder
	FROM	IntegralExchangeBill
	WHERE 	[BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType IN (187,188)	--分支机构调拨单------------------------
	BEGIN
		INSERT INTO dbo.STypeMoveBill
		        ( BillNumberId ,
		          BillType ,
		          Comment ,
		          PtypeId ,
		          Qty ,
		          Price ,
		          Total ,
		          Jobnumber ,
		          GoodsNo ,
		          OutFactoryDate ,
		          IsUnit2 ,
		          GoodsOrder ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          Stypeid ,
		          Ktypeid ,
		          Ktypeid2 ,
		          FromBillNumberID ,
		          FromBillID ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MPrice ,
		          InCargoID ,
		          OutCargoID ,
		          ItemID ,
		          IsCombined,
		          Serial,
		          ShowOrder
		        )
		OUTPUT inserted.ID INTO #NewbILLID
		SELECT @Cur_BillNumberId, 
				BillType ,
		          Comment ,
		          PtypeId ,
		          Qty ,
		          Price ,
		          Total ,
		          Jobnumber ,
		          GoodsNo ,
		          OutFactoryDate ,
		          IsUnit2 ,
		          GoodsOrder ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          Stypeid ,
		          Ktypeid ,
		          Ktypeid2 ,
		          FromBillNumberID ,
		          FromBillID ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MPrice ,
		          InCargoID ,
		          OutCargoID ,
		          ItemID ,
		          IsCombined,
		          Serial,
		          ShowOrder
		FROM   STypeMoveBill
		WHERE  BillNumberId = @BillNumberId ORDER BY ID
		
		IF @BillType = 187
			BEGIN				
				IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND CostSale = 1)
					BEGIN
						UPDATE	STypeMoveBill
						SET		Price = 0,								
								total = 0
						WHERE	BillNumberId = @Cur_BillNumberId
						
						UPDATE BillIndex SET totalmoney = 0,NTotalMoney=0 WHERE BillNumberId = @Cur_BillNumberId
					END			
			END
	END
ELSE IF @BillType IN (189,190)  --预收款单，预付款单
BEGIN
	INSERT INTO dbo.PreBill
	        ( BillNumberId ,
	          BillType ,
	          Comment ,
	          AtypeId ,
	          total ,
	          TeamNo ,
	          TeamNO1 ,
	          Stypeid ,
	          ntotal ,
	          vipcardid,
	          ShowOrder,
	          RelevanceBillId,
	          BrandarTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT  @Cur_BillNumberId, 
			BillType ,
	          Comment ,
	          AtypeId ,
	          total ,
	          TeamNo ,
	          TeamNO1 ,
	          Stypeid ,
	          ntotal ,
	          vipcardid,
	          ShowOrder,
	          RelevanceBillId,
	          BrandarTypeId
	FROM	PreBill 
	WHERE	BillNumberId = @BillNumberId 
			AND (VipCardID = -1 OR vipcardid IS NULL) 
	ORDER BY ID
	
	--预收款单如果有会员储值，则删除会员储值 
	DECLARE @PreTotalMoney  NUMERIC(24, 10) ,@nPreTotalMoney  NUMERIC(24, 10) 			
	SELECT @PreTotalMoney = ISNULL(SUM(Total),0),@nPreTotalMoney= ISNULL(SUM(nTotal),0) FROM PreBill WHERE BillNumberId = @Cur_BillNumberId
	UPDATE BillIndex SET totalmoney = @PreTotalMoney,ntotalmoney=@nPreTotalMoney,IfMulAccount = 0 WHERE BillNumberId = @Cur_BillNumberId
END
	
ELSE IF @BillType IN (201,202)	--其他出入库单
BEGIN
	INSERT INTO dbo.OtherInOutBill
	        ( BillNumberId ,
	          BillType ,
	          PtypeId ,
	          KtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			BillType ,
	          PtypeId ,
	          KtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          Serial,
	          ShowOrder
	FROM	OtherInOutBill
	WHERE	BillNumberId = @BillNumberId
END

ELSE IF @BillType IN (212,213)	--固定资产减少、固定资产增加
BEGIN
	INSERT INTO dbo.AssetIncDecBill
	        ( BillNumberId ,
	          AssetCardId,
	          BillType,
	          NTotal,
	          Total,
	          Tax,
	          NTaxMoney,
	          TaxMoney,
	          NTaxTotal,
	          TaxTotal,
	          NDepTotal,
	          DepTotal,
	          NNetValue,
	          NetValue,
	          Comment
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			AssetCardId,
	          BillType,
	          NTotal,
	          Total,
	          Tax,
	          NTaxMoney,
	          TaxMoney,
	          NTaxTotal,
	          TaxTotal,
	          NDepTotal,
	          DepTotal,
	          NNetValue,
	          NetValue,
	          Comment
	FROM	AssetIncDecBill
	WHERE	BillNumberId = @BillNumberId
END
	
ELSE IF @BillType IN (214)	--固定资产折旧(新)
BEGIN
	INSERT INTO dbo.DepBill
	        ( BillNumberId,
	        AssetCardId,
	        Depreciation,
	        Comment,
	        WorkTime,
	        WorkUnit,
	        DTYPEID
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			AssetCardId,
	        Depreciation,
	        Comment,
	        WorkTime,
	        WorkUnit,
	        DTYPEID
	FROM	DepBill
	WHERE	BillNumberId = @BillNumberId
END
	
ELSE IF @BillType IN (215)	--零售退货单
BEGIN
	INSERT INTO dbo.RetailBackBill
	        ( BillNumberId,
			PtypeId,
			Qty,
			SalePrice,
			discount,
			DiscountPrice,
			costprice,
			jobnumber,
			goodsno,
			total,
			OutFactoryDate,
			TaxPrice,
			TaxTotal,
			comment,
			TeamNo,
			TeamNO1,
			IsUnit2,
			Serial,
			GoodsOrder,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			GoodsCostTotal,
			SaleTotal,
			Tax,
			Stypeid,
			TaxMoney,
			NSalePrice,
			NSaleTotal,
			NDiscountPrice,
			NTotal,
			NTaxPrice,
			NTaxTotal,
			NTaxMoney,
			UnitID,
			NUnitID,
			NQty,
			UnitRate,
			NUnitMsg,
			MUnitID,
			MQty,
			MUnitRate,
			MUnitMsg,
			MSalePrice,
			MDiscountPrice,
			MTaxPrice,
			CurMSalePrice,
			CurMDiscountPrice,
			CurMTaxPrice,
			CargoID,
			ItemID,
			IsCombined,
			InvoiceQty,
			InvoiceMoney,
			NInvoiceMoney,
			IsGift,
			OldId,
			CompleteQty,
			ETypeID,
			ShowOrder,
			KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			PtypeId,
			Qty,
			SalePrice,
			discount,
			DiscountPrice,
			costprice,
			jobnumber,
			goodsno,
			total,
			OutFactoryDate,
			TaxPrice,
			TaxTotal,
			COMMENT ,
			TeamNo,
			TeamNO1,
			IsUnit2,
			Serial,
			GoodsOrder,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			GoodsCostTotal,
			SaleTotal,
			Tax,
			Stypeid,
			TaxMoney,
			NSalePrice,
			NSaleTotal,
			NDiscountPrice,
			NTotal,
			NTaxPrice,
			NTaxTotal,
			NTaxMoney,
			UnitID,
			NUnitID,
			NQty,
			UnitRate,
			NUnitMsg,
			MUnitID,
			MQty,
			MUnitRate,
			MUnitMsg,
			MSalePrice,
			MDiscountPrice,
			MTaxPrice,
			CurMSalePrice,
			CurMDiscountPrice,
			CurMTaxPrice,
			CargoID,
			ItemID,
			IsCombined,
			InvoiceQty,
			InvoiceMoney,
			NInvoiceMoney,
			IsGift,
			OldId,
			CompleteQty,
			ETypeID,
			ShowOrder,
			KTypeId
	FROM	RetailBackBill 
	WHERE	RetailBackBill.BillNumberId = @BillNumberId
END
ELSE IF @BillType IN (400)	--暂估入库单
BEGIN
	INSERT INTO dbo.AppraisalBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          total ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo1 ,
	          TeamNo ,
	          orderid ,
	          Serial ,
	          InputCostPrice ,
	          GoodsOrder ,
	          BackQty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsCostPrice ,
	          HandZeroCost ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          entryCode ,
	          InvoiceQty ,
	          InvoiceMoney ,
	          NInvoiceMoney ,
	          IsGift ,
	          InvoiceMoneyEX ,
	          NInvoiceMoneyEX ,
	          InvoiceCostTotal ,
	          OldID ,
	          OldBillNumberID ,
	          InvoiceNQty ,
	          InvoiceSaleMoney ,
	          NInvoiceSaleMoney ,
	          ShareFee,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			PtypeId ,
			Qty ,
			SalePrice ,
			discount ,
			DiscountPrice ,
			total ,
			TaxPrice ,
			TaxTotal ,
			comment ,
			TeamNo1 ,
			TeamNo ,
			orderid ,
			Serial ,
			InputCostPrice ,
			GoodsOrder ,
			BackQty ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsCostPrice ,
			HandZeroCost ,
			SaleTotal ,
			Tax ,
			KTypeID ,
			Stypeid ,
			TaxMoney ,
			NSalePrice ,
			NSaleTotal ,
			NDiscountPrice ,
			NTotal ,
			NTaxPrice ,
			NTaxTotal ,
			NTaxMoney ,
			UnitID ,
			NUnitID ,
			NQty ,
			UnitRate ,
			NUnitMsg ,
			MUnitID ,
			MQty ,
			MUnitRate ,
			MUnitMsg ,
			MSalePrice ,
			MDiscountPrice ,
			MTaxPrice ,
			CurMSalePrice ,
			CurMDiscountPrice ,
			CurMTaxPrice ,
			CargoID ,
			ItemID ,
			IsCombined ,
			entryCode ,
			0,--InvoiceQty ,
			0,--InvoiceMoney ,
			0,--NInvoiceMoney ,
			IsGift ,
			0,--InvoiceMoneyEX ,
			0,--NInvoiceMoneyEX ,
			0,--InvoiceCostTotal ,
			OldID ,
			OldBillNumberID ,
			0,--InvoiceNQty ,
			0,--InvoiceSaleMoney ,
			0,--NInvoiceSaleMoney ,
			ShareFee,
			ShowOrder
	FROM	AppraisalBill
	WHERE	BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM AppraisalBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
END
ELSE IF @BillType IN (402)	--发出商品出库单
BEGIN
	INSERT INTO dbo.SendBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          total ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          Serial ,
	          InputCostPrice ,
	          GoodsOrder ,
	          BackQty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsCostPrice ,
	          HandZeroCost ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          ShareFee ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          entryCode ,
	          InvoiceQty ,
	          InvoiceMoney ,
	          NInvoiceMoney ,
	          PriceSource ,
	          IsGift ,
	          ReferPrice ,
	          PriceStyle ,
	          InvoiceMoneyEX ,
	          NInvoiceMoneyEX ,
	          InvoiceCostTotal ,
	          OldID ,
	          OldBillNumberID ,
	          InvoiceNQty ,
	          CostTotal ,
	          InvoiceSaleMoney ,
	          NInvoiceSaleMoney,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			PtypeId ,
			Qty ,
			SalePrice ,
			discount ,
			DiscountPrice ,
			costprice ,
			total ,
			TaxPrice ,
			TaxTotal ,
			comment ,
			OrderID ,
			TeamNo ,
			TeamNO1 ,
			Serial ,
			InputCostPrice ,
			GoodsOrder ,
			BackQty ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsCostPrice ,
			HandZeroCost ,
			SaleTotal ,
			Tax ,
			KTypeID ,
			Stypeid ,
			ShareFee ,
			TaxMoney ,
			NSalePrice ,
			NSaleTotal ,
			NDiscountPrice ,
			NTotal ,
			NTaxPrice ,
			NTaxTotal ,
			NTaxMoney ,
			UnitID ,
			NUnitID ,
			NQty ,
			UnitRate ,
			NUnitMsg ,
			MUnitID ,
			MQty ,
			MUnitRate ,
			MUnitMsg ,
			MSalePrice ,
			MDiscountPrice ,
			MTaxPrice ,
			CurMSalePrice ,
			CurMDiscountPrice ,
			CurMTaxPrice ,
			CargoID ,
			ItemID ,
			IsCombined ,
			entryCode ,
			0,--InvoiceQty ,
			0,--InvoiceMoney ,
			0,--NInvoiceMoney ,
			'通过单据复制' ,
			IsGift ,
			ReferPrice ,
			PriceStyle ,
			0,--InvoiceMoneyEX ,
			0,--NInvoiceMoneyEX ,
			0,--InvoiceCostTotal ,
			OldID ,
			OldBillNumberID ,
			0,--InvoiceNQty ,
			CostTotal ,
			0,--InvoiceSaleMoney ,
			0,--NInvoiceSaleMoney
			ShowOrder
	FROM	SendBill
	WHERE	BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM SendBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
	
END
END
ELSE-----------------------------------------------一下不复制序列号-----------------------------------------------------------------------
BEGIN
	IF @BillType = 305 --------零售单-----------
	BEGIN
	INSERT INTO dbo.retailBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          SaleTotal ,
	          Tax ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          pricedetailid,
	          priceRuleid,
	          PriceSource,
	          ETypeID,
	          ShowOrder,
	          iscombination,
	          combinationptypeid,
	          pindexid,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			  PtypeId ,
			  Qty ,
			  SalePrice ,
			  discount ,
			  DiscountPrice ,
			  costprice ,
			  jobnumber ,
			  goodsno ,
			  total ,
			  OutFactoryDate ,
			  TaxPrice ,
			  TaxTotal ,
			  COMMENT ,
			  OrderID ,
			  TeamNo ,
			  TeamNO1 ,
			  IsUnit2 ,
			  GoodsOrder ,
			  GoodsNumber ,
			  ProduceDate ,
			  ValidDate ,
			  GoodsBTypeID ,
			  GoodsCostPrice ,
			  GoodsCostTotal ,
			  SaleTotal ,
			  Tax ,
			  Stypeid ,
			  TaxMoney ,
			  NSalePrice ,
			  NSaleTotal ,
			  NDiscountPrice ,
			  NTotal ,
			  NTaxPrice ,
			  NTaxTotal ,
			  NTaxMoney ,
			  UnitID ,
			  NUnitID ,
			  NQty ,
			  UnitRate ,
			  NUnitMsg ,
			  MUnitID ,
			  MQty ,
			  MUnitRate ,
			  MUnitMsg ,
			  MSalePrice ,
			  MDiscountPrice ,
			  MTaxPrice ,
			  CurMSalePrice ,
			  CurMDiscountPrice ,
			  CurMTaxPrice ,
			  CargoID ,
			  ItemID ,
			  IsCombined,
			  0,
	          0,
	          '通过单据复制',
	          ETypeID,
	          ShowOrder,
	          iscombination,
	          combinationptypeid,
	          pindexid,
	          KTypeId
	FROM retailbill 
	WHERE retailbill.[BillNumberId] = @BillNumberId ORDER BY ID
	
	INSERT INTO RetailCombinationBill(BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,
		OutFactoryDate,TaxPrice,TaxTotal,IsUnit2,BackQTY,SaleTotal,Tax,Stypeid,TaxMoney,NSalePrice,
		NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,
		CurMDiscountPrice,CurMTaxPrice,CargoID,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,PosId,
		BeforePromoID,PriceDetailId,PriceRuleId,PriceSource,PriceStyle,PromoType,pindexid,comment,ETypeID,itemid,iscombined)
	SELECT 
			@Cur_BillNumberId,PtypeId,Qty,SalePrice,discount,DiscountPrice,total,
		OutFactoryDate,TaxPrice,TaxTotal,IsUnit2,BackQTY,SaleTotal,Tax,Stypeid,TaxMoney,NSalePrice,
		NSaleTotal,NDiscountPrice,NTotal,NTaxPrice,NTaxTotal,NTaxMoney,UnitID,NUnitID,NQty,UnitRate,
		NUnitMsg,MUnitID,MQty,MUnitRate,MUnitMsg,MSalePrice,MDiscountPrice,MTaxPrice,CurMSalePrice,
		CurMDiscountPrice,CurMTaxPrice,CargoID,InvoiceQty,InvoiceMoney,NInvoiceMoney,IsGift,PosId,
		BeforePromoID,PriceDetailId,PriceRuleId, '通过单据复制',PriceStyle,PromoType,pindexid,comment,ETypeID,itemid,iscombined
		FROM RetailCombinationBill WHERE BillNumberId=@BillNumberId
END
ELSE IF @BillType = 11 ---------------销售单-----
	BEGIN
		INSERT INTO dbo.SaleBill
		        ( BillNumberId ,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          GoodsOrder ,
		          BackQty ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined,
		          entryCode,
		          pricesource,
		          ShowOrder,
		          ETypeID
		          --IsGift
		        )
		output inserted.ID INTO #NewbILLID
		SELECT @Cur_BillNumberId,
				PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          GoodsOrder ,
		          0  ,--backqty不复制，改成0
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          0 AS CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined,
		          entryCode,
		          '通过单据复制',
		          ShowOrder,
		          ETypeID
		          --IsGift
		FROM salebill
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
----------这个是啥
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND CostSale = 1)
			BEGIN
				UPDATE	SaleBill
				SET		SalePrice = 0,
						DiscountPrice = 0,
						total = 0,
						TaxPrice = 0,
						TaxTotal = 0,
						SaleTotal = 0,
						NSalePrice = 0,
						NDiscountPrice = 0,
						NTotal = 0,
						NTaxPrice = 0,
						NTaxTotal = 0,
						NSaleTotal = 0,
						CurMSalePrice = 0,
						CurMDiscountPrice = 0,
						CurMTaxPrice = 0,
						TaxMoney=0,
						NTaxMoney=0
				WHERE	BillNumberId = @Cur_BillNumberId
				
				UPDATE BillIndex SET totalmoney = 0,NTotalMoney = 0 WHERE BillNumberId = @Cur_BillNumberId
			END
		--处理销售订单的代发货数量
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM SaleBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
	END
ELSE IF @BillType = 45 -------------------销售退货单
BEGIN
	INSERT INTO dbo.saleBackBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          CostPrice ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          FromBillNumberID ,
	          FromBillID ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          IsGift,
	          ShowOrder,
		      ETypeID
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          CostPrice ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          FromBillNumberID ,
	          FromBillID ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          IsGift,
	          ShowOrder,
		      ETypeID
	FROM salebackbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
END
ELSE IF @BillType = 4 ------------收款单
    BEGIN
		INSERT INTO dbo.gatheringBill
		        ( BillNumberId ,
		          AtypeId ,
		          total ,
		          Comment ,
		          TeamNo ,
		          TeamNO1 ,
		          Stypeid ,
		          ntotal ,
		          VipCardID,
		          ShowOrder,
		          RelevanceBillId,
		          BrandarTypeID,
		          PreferenceMoney,
		          nPreferenceMoney
		        )
		 OUTPUT inserted.ID INTO #NewbILLID
		SELECT  @Cur_BillNumberId,
				AtypeId ,
		          total ,
		          Comment ,
		          TeamNo ,
		          TeamNO1 ,
		          Stypeid ,
		          ntotal ,
		          VipCardID,
		          ShowOrder,
		          RelevanceBillId,
		          BrandarTypeID,
		          PreferenceMoney,
		          nPreferenceMoney
		FROM	gatheringbill		
		WHERE	[BillNumberId] = @BillNumberId 
				AND (VipCardID = -1 OR vipcardid IS NULL) 
		ORDER BY ID
		--收款单如果有会员储值，则删除会员储值 
		DECLARE @GatherTotal  NUMERIC(24, 10) ,	@GatherNTotal  NUMERIC(24, 10) 		
		SELECT @GatherTotal = ISNULL(SUM(Total),0) FROM gatheringBill WHERE BillNumberId = @Cur_BillNumberId
		SELECT @GatherNTotal = ISNULL(SUM(NTotal),0) FROM gatheringBill WHERE BillNumberId = @Cur_BillNumberId
		UPDATE BillIndex SET totalmoney = @GatherTotal,totalinmoney = @GatherTotal,IfMulAccount = 0,
								 Ntotalmoney = @GatherNTotal,Ntotalinmoney = @GatherNTotal
		WHERE BillNumberId = @Cur_BillNumberId
		
	END
ELSE IF @BillType = 34 --进货单
BEGIN
	INSERT INTO dbo.BuyBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          jobnumber ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo1 ,
	          TeamNo ,
	          orderid ,
	          IsUnit2 ,
	          GoodsOrder ,
	          BackQty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          CompleteQTY ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          FromBillNumberID ,
	          FromBillID ,
	          ShareFee ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          entryCode,
	          InvoiceMoney,
	          InvoiceQty,
	          IsGift,
	          ShowOrder
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          jobnumber ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo1 ,
	          TeamNo ,
	          orderid ,
	          IsUnit2 ,
	          GoodsOrder ,
	          BackQty,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          0 AS CompleteQTY ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          FromBillNumberID ,
	          FromBillID ,
	          ShareFee ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          entryCode,
	          0 AS InvoiceMoney,
	          0 AS InvoiceQty,
	          IsGift,
	          ShowOrder
	FROM buybill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM BUYBILL b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
END
ELSE IF @BillType = 6 --进货退货单
BEGIN
	INSERT INTO dbo.BuyBackBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          IsGift,
	          ShowOrder
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          IsGift,
	          ShowOrder
	FROM buybackbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
END
ELSE IF @BillType = 66 --付款单
	BEGIN
		INSERT INTO dbo.PayBill
		        ( BillNumberId ,
		          AtypeId ,
		          total ,
		          Comment ,
		          TeamNo ,
		          TeamNO1 ,
		          Stypeid ,
		          ntotal ,
		          VipCardID,
		          ShowOrder
		        )
		SELECT @Cur_BillNumberId,
				 AtypeId ,
		          total ,
		          Comment ,
		          TeamNo ,
		          TeamNO1 ,
		          Stypeid ,
		          ntotal ,
		          VipCardID,
		          ShowOrder
		FROM paybill
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	END
ELSE IF @BillType = 21 --变价调拨单
	INSERT INTO dbo.MoveBjBill
	        ( BillNumberId ,
	          Comment ,
	          PtypeId ,
	          Qty ,
	          price ,
	          total ,
	          Jobnumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          InCargoID ,
	          OutCargoID ,
	          ItemID ,
	          IsCombined ,
	          KTypeId ,
	          KTypeId2,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			Comment ,
	          PtypeId ,
	          Qty ,
	          price ,
	          total ,
	          Jobnumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          InCargoID ,
	          OutCargoID ,
	          ItemID ,
	          IsCombined ,
	          KTypeId ,
	          KTypeId2,
	          ShowOrder
	FROM movebjbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 17 --同价调拨单
	INSERT INTO dbo.MoveBill
	        ( BillNumberId ,
	          Comment ,
	          PtypeId ,
	          Qty ,
	          Price ,
	          Total ,
	          Jobnumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          InCargoID ,
	          OutCargoID ,
	          ItemID ,
	          IsCombined ,
	          KTypeId ,
	          KTypeId2,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
		Comment ,
	          PtypeId ,
	          Qty ,
	          Price ,
	          Total ,
	          Jobnumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          InCargoID ,
	          OutCargoID ,
	          ItemID ,
	          IsCombined ,
	          KTypeId ,
	          KTypeId2,
	          ShowOrder
	FROM movebill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 57 --调价单
	INSERT INTO dbo.AdPriceBill
	        ( BillNumberId ,
	          Comment ,
	          PtypeId ,
	          Qty ,
	          BeforePrice ,
	          BeforeTotal ,
	          Rate ,
	          Price ,
	          total ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          ChangeAllStock ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          NQty ,
	          UnitRate ,
	          ItemID ,
	          IsCombined ,
	          cargoID,
	          ktypeid,
	          FromBillID,
	          ShowOrder,
	          ChangeTotal,
	          Type,
	          NPrice,NTotal
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId,
			Comment ,
	          PtypeId ,
	          Qty ,
	          BeforePrice ,
	          BeforeTotal ,
	          Rate ,
	          Price ,
	          total ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          IsUnit2 ,
	          ChangeAllStock ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          NQty ,
	          UnitRate ,
	          ItemID ,
	          IsCombined ,
	          cargoID,
	          ktypeid,
	          FromBillID,
	          ShowOrder,
	          ChangeTotal,
	          Type,
	          NPrice,NTotal
	FROM	adpricebill
	WHERE	[BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 9 --报损单
	INSERT INTO dbo.LoseBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			  PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder,
	          KTypeId
	FROM losebill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 14 --报溢单
	INSERT INTO dbo.overflowBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          Comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          Comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder,
	          KTypeId
	FROM overflowbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	
ELSE IF @BillType IN(36,93,84,85,78,5,10,158) -- 费用，其他收入   固定资产购买、变卖、折旧、待摊费用发生、摊销 ,158为现金费用单为2002-11-6吴德水添加
	INSERT INTO dbo.MoneyBill
	        ( BillNumberId ,
	          AtypeId ,
	          total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          NTotal,
	          DTypeId,
	          ETypeId ,
	          ShowOrder,
	          BrandarTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			AtypeId ,
	          total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          NTotal,
	          DTypeId,
	          ETypeId ,
	          ShowOrder,
	          BrandarTypeId
	FROM moneybill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType=77 -- 转款单
	INSERT INTO dbo.MoveMoneyBill
	        ( BillNumberId ,
	          Comment ,
	          AtypeId ,
	          total ,
	          Stypeid,
			  ntotal,
			  ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			Comment ,
	          AtypeId ,
	          total ,
	          Stypeid,
	          ntotal,
	          ShowOrder
	FROM MoveMoneyBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType IN(115,116,128,129) -- 调帐单
	INSERT INTO dbo.AdDebtBill
	        ( BillNumberId ,
	          Comment ,
	          BtypeId ,
	          total ,
	          TeamNo ,
	          TeamNO1 ,
	          CompleteTotal ,
	          Stypeid ,
	          NTotal ,
	          NCompleteTotal,
	          ShowOrder,
	          BrandarTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			Comment ,
	          BtypeId ,
	          total ,
	          TeamNo ,
	          TeamNO1 ,
	          0 ,
	          Stypeid ,
	          NTotal ,
	          0,
	          ShowOrder,
	          BrandarTypeId
	FROM addebtbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 16 --拆装单
	INSERT INTO dbo.DisassembleBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          costprice ,
	          jobnumber ,
	          total ,
	          inorout ,
	          outfactorydate ,
	          comment ,
	          goodsno ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          KTypeID ,
	          Stypeid ,
	          NQty ,
	          UnitRate ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          IsUnit2,
	          MUnitId,
	          MUnitRate,
	          MQty,
	          CurMSalePrice,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          costprice ,
	          jobnumber ,
	          total ,
	          inorout ,
	          outfactorydate ,
	          comment ,
	          goodsno ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          KTypeID ,
	          Stypeid ,
	          NQty ,
	          UnitRate ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          IsUnit2,
	          MUnitId,
	          MUnitRate,
	          MQty,
	          CurMSalePrice ,
	          ShowOrder
	FROM DisassembleBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 126 --获赠单  2002-11-6吴德水添加
	INSERT INTO dbo.GivemeBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          KTypeId,
	          ShowOrder
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          KTypeId,
	          ShowOrder
	FROM GivemeBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 139 --赠送单 2002-11-6吴德水添加
	INSERT INTO dbo.GiveBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          KTypeId,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          KTypeId,
	          ShowOrder
	FROM GiveBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType IN (140,141,142,143,144,145,146,147) --代销单据 2003-04-20肖伟添加
BEGIN
	INSERT INTO dbo.CommissionBill
	        ( BillNumberId ,
	          Type ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          Discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          Goodsno ,
	          Total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          OldID ,
	          OldBillNumberID ,
	          BackQty ,
	          CompleteQTY ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          BQTY ,
	          OldBillid ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			Type ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          Discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          Goodsno ,
	          Total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          OldID ,
	          OldBillNumberID ,
	          BackQty ,
	          0 AS CompleteQTY ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          BQTY ,
	          OldBillid ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder
	FROM CommissionBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND BillType=144 AND CostSale = 1)
			BEGIN
				UPDATE	CommissionBill
				SET		SalePrice = 0,
						DiscountPrice = 0,
						total = 0,
						TaxPrice = 0,
						TaxTotal = 0,
						SaleTotal = 0,
						NSalePrice = 0,
						NDiscountPrice = 0,
						NTotal = 0,
						NTaxPrice = 0,
						NTaxTotal = 0,
						NSaleTotal = 0,
						CurMSalePrice = 0,
						CurMDiscountPrice = 0,
						CurMTaxPrice = 0,
						TaxMoney=0,
						NTaxMoney=0
				WHERE	BillNumberId = @Cur_BillNumberId
				
				UPDATE BillIndex SET totalmoney = 0,NTotalMoney = 0 WHERE BillNumberId = @Cur_BillNumberId
			END
			
	IF @BILLTYPE IN (140,144)
	BEGIN
		
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM CommissionBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
	END
END
	
ELSE IF @BillType = 148 --返利执行单
	INSERT INTO dbo.Advantage
	        ( BillNumberId ,
	          Ptypeid ,
	          StartDate ,
	          EndDate ,
	          StandardCode ,
	          Type ,
	          Qty ,
	          Total ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
	          Ptypeid ,
	          StartDate ,
	          EndDate ,
	          StandardCode ,
	          Type ,
	          Qty ,
	          Total ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber
	FROM Advantage
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType IN( 149,151) --价保执行单
	INSERT INTO dbo.PriceProtectBill
	        ( BillNumberid ,
	          Serial,
	          Ptypeid ,
	          OldTotal ,
	          OldPrice ,
	          Qty ,
	          NewPrice ,
	          Total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			  '' AS SERIAL,
	          Ptypeid ,
	          OldTotal ,
	          OldPrice ,
	          Qty ,
	          NewPrice ,
	          Total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber
	FROM PriceProtectBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 150 --获利执行单
	INSERT INTO dbo.Advantage
	        ( BillNumberId ,
	          Ptypeid ,
	          StartDate ,
	          EndDate ,
	          StandardCode ,
	          Type ,
	          Qty ,
	          Total ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
	          Ptypeid ,
	          StartDate ,
	          EndDate ,
	          StandardCode ,
	          Type ,
	          Qty ,
	          Total ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          BillType ,
	          Stypeid ,
	          ItemID ,
	          IsCombined,
	          GoodsNumber
	FROM Advantage
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 155	-- 商品换货单
	INSERT INTO dbo.GoodsExchangeBill
	        ( BillNumberId ,
	          InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder
	FROM GoodsExchangeBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 157	-- 维修受理单
BEGIN
	INSERT INTO dbo.RepairDealDetail
	        ( BillNumberId ,
	          InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal 
	FROM RepairDealDetail
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	
	INSERT INTO dbo.RepairDeal
	        ( BillNumberID ,
	          EngageBillID ,
	          BillDate ,
	          BillCode ,
	          BillType ,
	          PTypeID ,
	          ETypeID ,
	          IfCheck ,
	          Checke ,
	          RedWord ,
	          Draft ,
	          Stat ,
	          Fault ,
	          Comment ,
	          Method ,
	          KTypeID1 ,
	          KTypeID2 ,
	          MoneyChange ,
	          MoneyRepair ,
	          TotalMoney ,
	          TotalInMoney ,
	          BTypeID ,
	          ATypeID ,
	          Brief ,
	          NotFree ,
	          FreeMemo ,
	          ETypeID1 ,
	          ETypeID2 ,
	          PayDate ,
	          IfPay ,
	          IDCard ,
	          TeamNo
	        )
	SELECT @Cur_BillNumberId,
			EngageBillID ,
	          BillDate ,
	          BillCode ,
	          BillType ,
	          PTypeID ,
	          ETypeID ,
	          'f' ,
	          Checke ,
	          RedWord ,
	          '1' ,
	          Stat ,
	          Fault ,
	          Comment ,
	          Method ,
	          KTypeID1 ,
	          KTypeID2 ,
	          MoneyChange ,
	          MoneyRepair ,
	          TotalMoney ,
	          TotalInMoney ,
	          BTypeID ,
	          ATypeID ,
	          Brief ,
	          NotFree ,
	          FreeMemo ,
	          ETypeID1 ,
	          ETypeID2 ,
	          PayDate ,
	          IfPay ,
	          IDCard ,
	          TeamNo
	FROM RepairDeal
	WHERE [BillNumberId] = @BillNumberId
END
ELSE IF @BillType = 159	-- 会计凭证
BEGIN
	INSERT INTO dbo.AccountCredence
	        ( BillNumberID ,
	          TypeATypeID ,
	          ATypeID ,
	          J_Total ,
	          D_Total ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          NJ_Total ,
	          ND_Total,
	          CID,
	          Rate,
	          BrandarTypeId,
	          ETypeId,
	          DTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberID,
			TypeATypeID ,
	          ATypeID ,
	          dbo.F_RoundTotal(J_Total) ,
	          dbo.F_RoundTotal(D_Total) ,
	          Comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          dbo.F_RoundTotal(NJ_Total) ,
	          dbo.F_RoundTotal(ND_Total),
	          CID,
	          dbo.F_RoundExchangeRate(Rate),
	          BrandarTypeId,
	          ETypeId,
	          DTypeId
	FROM AccountCredence
	WHERE [BillNumberId] = @BillNumberID ORDER BY ID
END
ELSE IF @BillType = 160	-- 销售换货单
	INSERT INTO dbo.SaleGoodsExchangeBill
	        ( BillNumberId ,
	          InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          KTypeID2 ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          IsGift,
	          ShowOrder,
	          etypeid
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          KTypeID2 ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          IsGift,
	          ShowOrder,
	          etypeid
	FROM SaleGoodsExchangeBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 161	-- 采购换货单
	INSERT INTO dbo.BuyGoodsExchangeBill
	        ( BillNumberId ,
	          InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          KTypeID2 ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          IsGift,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          jobnumber ,
	          goodsno ,
	          total ,
	          OutFactoryDate ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          KTypeID2 ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          IsGift,
	          ShowOrder
	FROM BuyGoodsExchangeBill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
-- 新维修相关单据
ELSE IF @BillType = 165	-- 新维修 - 接件单
	INSERT INTO dbo.wx_Bill_JieJian
	        ( BillNumberId ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          BuyDate ,
	          ErrDes ,
	          Total ,
	          AddTotal ,
	          ErrDeal ,
	          RepairMode ,
	          ETypeID ,
	          BaoXiu ,
	          Comment ,
	          State ,
	          SendBackPTypeID ,
	          SendBackSerial ,
	          OutFactoryDate ,
	          ifYearBillDisplay ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          BuyDate ,
	          ErrDes ,
	          Total ,
	          AddTotal ,
	          ErrDeal ,
	          RepairMode ,
	          ETypeID ,
	          BaoXiu ,
	          Comment ,
	          0 ,
	          SendBackPTypeID ,
	          SendBackSerial ,
	          OutFactoryDate ,
	          ifYearBillDisplay ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	FROM wx_Bill_JieJian
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 166	-- 新维修 - 维修单
	INSERT INTO dbo.wx_Bill_Self
	        ( BillNumberiD ,
	          InOrOut ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          wxProperty ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          wxProperty ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_Self
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 167	-- 新维修 - 取件单
	INSERT INTO dbo.wx_Bill_GetBack
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          Total ,
	          CompleteQTY ,
	          OutFactoryDate ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          Total ,
	          0 AS CompleteQTY ,
	          OutFactoryDate ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	FROM wx_Bill_GetBack
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 168	-- 新维修 - 整机更换单
	INSERT INTO dbo.wx_Bill_Replace
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Total ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          OutFactoryDate ,
	          wxProperty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          CompleteQTY ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Total ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          OutFactoryDate ,
	          wxProperty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          0 AS CompleteQTY ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_Replace
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 169	-- 新维修 - 送修单
	INSERT INTO dbo.wx_Bill_Send
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          SendBackQty ,
	          Total ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          OutFactoryDate ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          0 ,
	          Total ,
	          Comment ,
	          JieJianBillNumberID ,
	          JieJianID ,
	          JieJianPTypeID ,
	          JieJianState ,
	          OutFactoryDate ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	FROM wx_Bill_Send
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 170	-- 新维修 - 送修返回单
	INSERT INTO dbo.wx_Bill_SendBack
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Total ,
	          Comment ,
	          SendBillNumberID ,
	          SendID ,
	          SendPTypeID ,
	          CompleteQTY ,
	          OutFactoryDate ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Total ,
	          Comment ,
	          SendBillNumberID ,
	          SendID ,
	          SendPTypeID ,
	          0 AS CompleteQTY ,
	          OutFactoryDate ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	FROM wx_Bill_SendBack
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 171	-- 新维修 - 报修单
	INSERT INTO dbo.wx_Bill_Call
	        ( BillNumberId ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          BuyDate ,
	          ErrDes ,
	          Total ,
	          ErrDeal ,
	          ETypeID ,
	          BaoXiu ,
	          Comment ,
	          OutFactoryDate ,
	          State ,
	          ifYearBillDisplay ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          BuyDate ,
	          ErrDes ,
	          Total ,
	          ErrDeal ,
	          ETypeID ,
	          BaoXiu ,
	          Comment ,
	          OutFactoryDate ,
	          0 ,
	          ifYearBillDisplay ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	FROM wx_Bill_Call
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 172	-- 新维修 - 上门维修单
	INSERT INTO dbo.wx_Bill_Goto
	        ( BillNumberiD ,
	          InOrOut ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          wxProperty ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			InOrOut ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          wxProperty ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          TeamNo ,
	          TeamNo1 ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_Goto
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 173	-- 新维修 - 维修品调入单
	INSERT INTO dbo.wx_Bill_In
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_In
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 174	-- 新维修 - 维修品调出单
	INSERT INTO dbo.wx_Bill_Out
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Price ,
	          Total ,
	          Comment ,
	          OutFactoryDate ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder,
	          KTypeId
	FROM wx_Bill_Out
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 175	-- 新维修 - 维修品调拨单
	INSERT INTO dbo.wx_Bill_Move
	        ( BillNumberID ,
	          PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Comment ,
	          OutFactoryDate ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId,
			PTypeID ,
	          Qty ,
	          IsUnit2 ,
	          Comment ,
	          OutFactoryDate ,
	          Stypeid ,
	          ItemID ,
	          IsCombined ,
	          GoodsNumber ,
	          CargoID ,
	          NQty ,
	          UnitRate,
	          ShowOrder
	FROM 	wx_Bill_Move
	WHERE 	[BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType = 183	-- 积分兑换单
	INSERT INTO dbo.IntegralExchangeBill
	        ( BillNumberId ,
	          KTypeID ,
	          PTypeID ,
	          Qty ,
	          Price ,
	          total ,
	          Comment ,
	          IsUnit2 ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          NQty ,
	          UnitRate ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId, 
			KTypeID ,
	          PTypeID ,
	          Qty ,
	          Price ,
	          total ,
	          Comment ,
	          IsUnit2 ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Stypeid ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          NQty ,
	          UnitRate ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder
	FROM	IntegralExchangeBill
	WHERE 	[BillNumberId] = @BillNumberId ORDER BY ID
ELSE IF @BillType IN (187,188)	--分支机构调拨单------------------------
	BEGIN
		INSERT INTO dbo.STypeMoveBill
		        ( BillNumberId ,
		          BillType ,
		          Comment ,
		          PtypeId ,
		          Qty ,
		          Price ,
		          Total ,
		          Jobnumber ,
		          GoodsNo ,
		          OutFactoryDate ,
		          IsUnit2 ,
		          GoodsOrder ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          Stypeid ,
		          Ktypeid ,
		          Ktypeid2 ,
		          FromBillNumberID ,
		          FromBillID ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MPrice ,
		          InCargoID ,
		          OutCargoID ,
		          ItemID ,
		          IsCombined,
				  ShowOrder
		        )
		OUTPUT inserted.ID INTO #NewbILLID
		SELECT @Cur_BillNumberId, 
				BillType ,
		          Comment ,
		          PtypeId ,
		          Qty ,
		          Price ,
		          Total ,
		          Jobnumber ,
		          GoodsNo ,
		          OutFactoryDate ,
		          IsUnit2 ,
		          GoodsOrder ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          Stypeid ,
		          Ktypeid ,
		          Ktypeid2 ,
		          FromBillNumberID ,
		          FromBillID ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MPrice ,
		          InCargoID ,
		          OutCargoID ,
		          ItemID ,
		          IsCombined,
				  ShowOrder
		FROM   STypeMoveBill
		WHERE  BillNumberId = @BillNumberId ORDER BY ID
		
		IF @BillType = 187
			BEGIN				
				IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND CostSale = 1)
					BEGIN
						UPDATE	STypeMoveBill
						SET		Price = 0,								
								total = 0
						WHERE	BillNumberId = @Cur_BillNumberId
						
						UPDATE BillIndex SET totalmoney = 0 WHERE BillNumberId = @Cur_BillNumberId
					END			
			END
	END
ELSE IF @BillType IN (189,190)  --预收款单，预付款单
BEGIN
	INSERT INTO dbo.PreBill
	        ( BillNumberId ,
	          BillType ,
	          Comment ,
	          AtypeId ,
	          total ,
	          TeamNo ,
	          TeamNO1 ,
	          Stypeid ,
	          ntotal ,
	          vipcardid,
	          ShowOrder,
	          RelevanceBillId,
	          BrandarTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT  @Cur_BillNumberId, 
			BillType ,
	          Comment ,
	          AtypeId ,
	          total ,
	          TeamNo ,
	          TeamNO1 ,
	          Stypeid ,
	          ntotal ,
	          vipcardid,
	          ShowOrder,
	          RelevanceBillId,
	          BrandarTypeId
	FROM	PreBill 
	WHERE	BillNumberId = @BillNumberId 
			AND (VipCardID = -1 OR vipcardid IS NULL)  
	ORDER BY ID
	
	--预收款单如果有会员储值，则删除会员储值 
	DECLARE @PreTotal  NUMERIC(24, 10) ,@nPreTotal  NUMERIC(24, 10) 			
	SELECT @PreTotal = ISNULL(SUM(Total),0),@nPreTotal= ISNULL(SUM(nTotal),0) FROM PreBill WHERE BillNumberId = @Cur_BillNumberId
	UPDATE BillIndex SET totalmoney = @PreTotal,ntotalmoney=@nPreTotal,IfMulAccount = 0 WHERE BillNumberId = @Cur_BillNumberId
END
	
ELSE IF @BillType IN (201,202)	--其他出入库单
BEGIN
	INSERT INTO dbo.OtherInOutBill
	        ( BillNumberId ,
	          BillType ,
	          PtypeId ,
	          KtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			BillType ,
	          PtypeId ,
	          KtypeId ,
	          Qty ,
	          JobNumber ,
	          GoodsNo ,
	          OutFactoryDate ,
	          comment ,
	          IsUnit2 ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsBTypeID ,
	          GoodsCostPrice ,
	          GoodsCostTotal ,
	          Price ,
	          Total ,
	          Stypeid ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined,
	          ShowOrder
	FROM	OtherInOutBill
	WHERE	BillNumberId = @BillNumberId
END

ELSE IF @BillType IN (212,213)	--固定资产减少、固定资产增加
BEGIN
	INSERT INTO dbo.AssetIncDecBill
	        ( BillNumberId ,
	          AssetCardId,
	          BillType,
	          NTotal,
	          Total,
	          Tax,
	          NTaxMoney,
	          TaxMoney,
	          NTaxTotal,
	          TaxTotal,
	          NDepTotal,
	          DepTotal,
	          NNetValue,
	          NetValue,
	          Comment
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			AssetCardId,
	          BillType,
	          NTotal,
	          Total,
	          Tax,
	          NTaxMoney,
	          TaxMoney,
	          NTaxTotal,
	          TaxTotal,
	          NDepTotal,
	          DepTotal,
	          NNetValue,
	          NetValue,
	          Comment
	FROM	AssetIncDecBill
	WHERE	BillNumberId = @BillNumberId
END
	
ELSE IF @BillType IN (214)	--固定资产折旧(新)
BEGIN
	INSERT INTO dbo.DepBill
	        ( BillNumberId,
	        AssetCardId,
	        Depreciation,
	        Comment,
	        WorkTime,
	        WorkUnit,
	        DTYPEID
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			AssetCardId,
	        Depreciation,
	        Comment,
	        WorkTime,
	        WorkUnit,
	        DTYPEID
	FROM	DepBill
	WHERE	BillNumberId = @BillNumberId
END
	
ELSE IF @BillType IN (215)	--零售退货单
BEGIN
	INSERT INTO dbo.RetailBackBill
	        ( BillNumberId,
			PtypeId,
			Qty,
			SalePrice,
			discount,
			DiscountPrice,
			costprice,
			jobnumber,
			goodsno,
			total,
			OutFactoryDate,
			TaxPrice,
			TaxTotal,
			comment,
			TeamNo,
			TeamNO1,
			IsUnit2,
			GoodsOrder,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			GoodsCostTotal,
			SaleTotal,
			Tax,
			Stypeid,
			TaxMoney,
			NSalePrice,
			NSaleTotal,
			NDiscountPrice,
			NTotal,
			NTaxPrice,
			NTaxTotal,
			NTaxMoney,
			UnitID,
			NUnitID,
			NQty,
			UnitRate,
			NUnitMsg,
			MUnitID,
			MQty,
			MUnitRate,
			MUnitMsg,
			MSalePrice,
			MDiscountPrice,
			MTaxPrice,
			CurMSalePrice,
			CurMDiscountPrice,
			CurMTaxPrice,
			CargoID,
			ItemID,
			IsCombined,
			InvoiceQty,
			InvoiceMoney,
			NInvoiceMoney,
			IsGift,
			OldId,
			CompleteQty,
			ETypeID,
	          ShowOrder,
	          KTypeId
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			PtypeId,
			Qty,
			SalePrice,
			discount,
			DiscountPrice,
			costprice,
			jobnumber,
			goodsno,
			total,
			OutFactoryDate,
			TaxPrice,
			TaxTotal,
			COMMENT ,
			TeamNo,
			TeamNO1,
			IsUnit2,
			GoodsOrder,
			GoodsNumber,
			ProduceDate,
			ValidDate,
			GoodsBTypeID,
			GoodsCostPrice,
			GoodsCostTotal,
			SaleTotal,
			Tax,
			Stypeid,
			TaxMoney,
			NSalePrice,
			NSaleTotal,
			NDiscountPrice,
			NTotal,
			NTaxPrice,
			NTaxTotal,
			NTaxMoney,
			UnitID,
			NUnitID,
			NQty,
			UnitRate,
			NUnitMsg,
			MUnitID,
			MQty,
			MUnitRate,
			MUnitMsg,
			MSalePrice,
			MDiscountPrice,
			MTaxPrice,
			CurMSalePrice,
			CurMDiscountPrice,
			CurMTaxPrice,
			CargoID,
			ItemID,
			IsCombined,
			InvoiceQty,
			InvoiceMoney,
			NInvoiceMoney,
			IsGift,
			OldId,
			CompleteQty,
			ETypeID,
	        ShowOrder,
	        KTypeId
	FROM	RetailBackBill 
	WHERE	RetailBackBill.BillNumberId = @BillNumberId
END
ELSE IF @BillType IN (310)	--资金调拨单
BEGIN
			INSERT INTO dbo.CapitalTransfer_Bill
	        ( BillNumberId,
	        BankAccountOut,
	        BankAccountIn,
	        TransferPrice,
	        DeductPrice,
	        NTransferPrice,
	        NDeductPrice,
	        Comment
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			BankAccountOut,
	        BankAccountIn,
	        TransferPrice,
	        DeductPrice,
	        NTransferPrice,
	        NDeductPrice,
	        Comment
	FROM	CapitalTransfer_Bill
	WHERE	CapitalTransfer_Bill.BillNumberId = @BillNumberId
END
ELSE IF @BillType IN (400)	--暂估入库单
BEGIN
	INSERT INTO dbo.AppraisalBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          total ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo1 ,
	          TeamNo ,
	          orderid ,
	          InputCostPrice ,
	          GoodsOrder ,
	          BackQty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsCostPrice ,
	          HandZeroCost ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          entryCode ,
	          InvoiceQty ,
	          InvoiceMoney ,
	          NInvoiceMoney ,
	          IsGift ,
	          InvoiceMoneyEX ,
	          NInvoiceMoneyEX ,
	          InvoiceCostTotal ,
	          OldID ,
	          OldBillNumberID ,
	          InvoiceNQty ,
	          InvoiceSaleMoney ,
	          NInvoiceSaleMoney ,
	          ShareFee,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			PtypeId ,
			Qty ,
			SalePrice ,
			discount ,
			DiscountPrice ,
			total ,
			TaxPrice ,
			TaxTotal ,
			comment ,
			TeamNo1 ,
			TeamNo ,
			orderid ,
			InputCostPrice ,
			GoodsOrder ,
			BackQty ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsCostPrice ,
			HandZeroCost ,
			SaleTotal ,
			Tax ,
			KTypeID ,
			Stypeid ,
			TaxMoney ,
			NSalePrice ,
			NSaleTotal ,
			NDiscountPrice ,
			NTotal ,
			NTaxPrice ,
			NTaxTotal ,
			NTaxMoney ,
			UnitID ,
			NUnitID ,
			NQty ,
			UnitRate ,
			NUnitMsg ,
			MUnitID ,
			MQty ,
			MUnitRate ,
			MUnitMsg ,
			MSalePrice ,
			MDiscountPrice ,
			MTaxPrice ,
			CurMSalePrice ,
			CurMDiscountPrice ,
			CurMTaxPrice ,
			CargoID ,
			ItemID ,
			IsCombined ,
			entryCode ,
			0,--InvoiceQty ,
			0,--InvoiceMoney ,
			0,--NInvoiceMoney ,
			IsGift ,
			0,--InvoiceMoneyEX ,
			0,--NInvoiceMoneyEX ,
			0,--InvoiceCostTotal ,
			OldID ,
			OldBillNumberID ,
			0,--InvoiceNQty ,
			0,--InvoiceSaleMoney ,
			0,--NInvoiceSaleMoney ,
			ShareFee,
	        ShowOrder
	FROM	AppraisalBill
	WHERE	BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM AppraisalBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
END
ELSE IF @BillType IN (401)	--暂估退货单
BEGIN
		INSERT INTO dbo.AppraisalBackBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          total ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNo1 ,
	          Serial ,
	          OldID ,
	          OldBillNumberID ,
	          InputCostPrice ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsCostPrice ,
	          HandZeroCost ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          InvoiceQty ,
	          InvoiceMoney ,
	          NInvoiceMoney ,
	          IsGift ,
	          PriceStyle ,
	          InvoiceCostTotal ,
	          InvoiceMoneyEX ,
	          NInvoiceMoneyEX ,
	          InvoiceNQty ,
	          CostTotal ,
	          InvoiceSaleMoney ,
	          NInvoiceSaleMoney ,
	          ShowOrder ,
	          ShareFee ,
	          PickedQty ,
	          OutFactQty ,
	          SendedQty ,
	          DraftFlag ,
	          IsIniFlag
	        )
	    OUTPUT inserted.ID  INTO #NewbILLID
		SELECT	@Cur_BillNumberId AS BillNumberId ,
                PtypeId ,
                Qty ,
                SalePrice ,
                discount ,
                DiscountPrice ,
                costprice ,
                total ,
                TaxPrice ,
                TaxTotal ,
                comment ,
                TeamNo ,
                TeamNo1 ,
                --ID ,
                Serial ,
                OldID ,
                OldBillNumberID ,
                InputCostPrice ,
                GoodsOrder ,
                GoodsNumber ,
                ProduceDate ,
                ValidDate ,
                GoodsCostPrice ,
                HandZeroCost ,
                SaleTotal ,
                Tax ,
                KTypeID ,
                Stypeid ,
                TaxMoney ,
                NSalePrice ,
                NSaleTotal ,
                NDiscountPrice ,
                NTotal ,
                NTaxPrice ,
                NTaxTotal ,
                NTaxMoney ,
                UnitID ,
                NUnitID ,
                NQty ,
                UnitRate ,
                NUnitMsg ,
                MUnitID ,
                MQty ,
                MUnitRate ,
                MUnitMsg ,
                MSalePrice ,
                MDiscountPrice ,
                MTaxPrice ,
                CurMSalePrice ,
                CurMDiscountPrice ,
                CurMTaxPrice ,
                CargoID ,
                ItemID ,
                IsCombined ,
                0 ,
                0 ,
                0 ,
                IsGift ,
                PriceStyle ,
                0 ,
                0 ,
                0 ,
                0 ,
                CostTotal ,
                0 ,
                0 ,
                ShowOrder ,
                ShareFee ,
                PickedQty ,
                OutFactQty ,
                SendedQty ,
                DraftFlag ,
                IsIniFlag
	FROM	dbo.AppraisalBackBill
	WHERE	BillNumberId = @BillNumberId
END
ELSE IF @BillType IN (402)	--发出商品出库单
BEGIN
	INSERT INTO dbo.SendBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          costprice ,
	          total ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          OrderID ,
	          TeamNo ,
	          TeamNO1 ,
	          InputCostPrice ,
	          GoodsOrder ,
	          BackQty ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsCostPrice ,
	          HandZeroCost ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          ShareFee ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          entryCode ,
	          InvoiceQty ,
	          InvoiceMoney ,
	          NInvoiceMoney ,
	          PriceSource ,
	          IsGift ,
	          ReferPrice ,
	          PriceStyle ,
	          InvoiceMoneyEX ,
	          NInvoiceMoneyEX ,
	          InvoiceCostTotal ,
	          OldID ,
	          OldBillNumberID ,
	          InvoiceNQty ,
	          CostTotal ,
	          InvoiceSaleMoney ,
	          NInvoiceSaleMoney,
	          ShowOrder
	        )
	OUTPUT inserted.ID INTO #NewbILLID
	SELECT	@Cur_BillNumberId AS BillNumberId,
			PtypeId ,
			Qty ,
			SalePrice ,
			discount ,
			DiscountPrice ,
			costprice ,
			total ,
			TaxPrice ,
			TaxTotal ,
			comment ,
			OrderID ,
			TeamNo ,
			TeamNO1 ,
			InputCostPrice ,
			GoodsOrder ,
			BackQty ,
			GoodsNumber ,
			ProduceDate ,
			ValidDate ,
			GoodsCostPrice ,
			HandZeroCost ,
			SaleTotal ,
			Tax ,
			KTypeID ,
			Stypeid ,
			ShareFee ,
			TaxMoney ,
			NSalePrice ,
			NSaleTotal ,
			NDiscountPrice ,
			NTotal ,
			NTaxPrice ,
			NTaxTotal ,
			NTaxMoney ,
			UnitID ,
			NUnitID ,
			NQty ,
			UnitRate ,
			NUnitMsg ,
			MUnitID ,
			MQty ,
			MUnitRate ,
			MUnitMsg ,
			MSalePrice ,
			MDiscountPrice ,
			MTaxPrice ,
			CurMSalePrice ,
			CurMDiscountPrice ,
			CurMTaxPrice ,
			CargoID ,
			ItemID ,
			IsCombined ,
			entryCode ,
			0,--InvoiceQty ,
			0,--InvoiceMoney ,
			0,--NInvoiceMoney ,
			'通过单据复制' ,
			IsGift ,
			ReferPrice ,
			PriceStyle ,
			0,--InvoiceMoneyEX ,
			0,--NInvoiceMoneyEX ,
			0,--InvoiceCostTotal ,
			OldID ,
			OldBillNumberID ,
			0,--InvoiceNQty ,
			CostTotal ,
			0,--InvoiceSaleMoney ,
			0--NInvoiceSaleMoney
			,ShowOrder
	FROM	SendBill
	WHERE	BillNumberId = @BillNumberId
	
	IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM SendBILL b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
	
	END
	ELSE IF @BillType IN (403)	--发出商品退货单
	BEGIN
	INSERT INTO dbo.SendBackBill
	        ( BillNumberId ,
	          PtypeId ,
	          Qty ,
	          SalePrice ,
	          discount ,
	          DiscountPrice ,
	          total ,
	          TaxPrice ,
	          TaxTotal ,
	          comment ,
	          TeamNo ,
	          TeamNO1 ,
	          Serial ,
	          OldID ,
	          CostPrice ,
	          OldBillNumberID ,
	          InputCostPrice ,
	          GoodsOrder ,
	          GoodsNumber ,
	          ProduceDate ,
	          ValidDate ,
	          GoodsCostPrice ,
	          HandZeroCost ,
	          SaleTotal ,
	          Tax ,
	          KTypeID ,
	          Stypeid ,
	          TaxMoney ,
	          NSalePrice ,
	          NSaleTotal ,
	          NDiscountPrice ,
	          NTotal ,
	          NTaxPrice ,
	          NTaxTotal ,
	          NTaxMoney ,
	          UnitID ,
	          NUnitID ,
	          NQty ,
	          UnitRate ,
	          NUnitMsg ,
	          MUnitID ,
	          MQty ,
	          MUnitRate ,
	          MUnitMsg ,
	          MSalePrice ,
	          MDiscountPrice ,
	          MTaxPrice ,
	          CurMSalePrice ,
	          CurMDiscountPrice ,
	          CurMTaxPrice ,
	          CargoID ,
	          ItemID ,
	          IsCombined ,
	          InvoiceQty ,
	          InvoiceMoney ,
	          NInvoiceMoney ,
	          IsGift ,
	          ReferPrice ,
	          PriceStyle ,
	          InvoiceMoneyEX ,
	          NInvoiceMoneyEX ,
	          InvoiceCostTotal ,
	          InvoiceNQty ,
	          CostTotal ,
	          InvoiceSaleMoney ,
	          NInvoiceSaleMoney ,
	          ShowOrder ,
	          InflowQty ,
	          DraftFlag ,
	          IsIniFlag ,
	          InFactQty ,
	          ShareFee
	        )
	SELECT @Cur_BillNumberId AS BillNumberId,
           PtypeId ,
           Qty ,
           SalePrice ,
           discount ,
           DiscountPrice ,
           total ,
           TaxPrice ,
           TaxTotal ,
           comment ,
           TeamNo ,
           --ID ,
           TeamNO1 ,
           Serial ,
           OldID ,
           CostPrice ,
           OldBillNumberID ,
           InputCostPrice ,
           GoodsOrder ,
           GoodsNumber ,
           ProduceDate ,
           ValidDate ,
           GoodsCostPrice ,
           HandZeroCost ,
           SaleTotal ,
           Tax ,
           KTypeID ,
           Stypeid ,
           TaxMoney ,
           NSalePrice ,
           NSaleTotal ,
           NDiscountPrice ,
           NTotal ,
           NTaxPrice ,
           NTaxTotal ,
           NTaxMoney ,
           UnitID ,
           NUnitID ,
           NQty ,
           UnitRate ,
           NUnitMsg ,
           MUnitID ,
           MQty ,
           MUnitRate ,
           MUnitMsg ,
           MSalePrice ,
           MDiscountPrice ,
           MTaxPrice ,
           CurMSalePrice ,
           CurMDiscountPrice ,
           CurMTaxPrice ,
           CargoID ,
           ItemID ,
           IsCombined ,
           0 ,
           0 ,
           0 ,
           IsGift ,
           ReferPrice ,
           PriceStyle ,
           0 ,
           0 ,
           0 ,
           0 ,
           CostTotal ,
           0 ,
           0 ,
           ShowOrder ,
           InflowQty ,
           DraftFlag ,
           IsIniFlag ,
           InFactQty ,
           ShareFee
	FROM SendBackBill 
	WHERE	BillNumberId = @BillNumberId
	END
END
--往来核销单（与序列号无关）
IF	@BillType=450
BEGIN
	 INSERT INTO dbo.ChargeOffBill
	         ( BillNumberId ,
	           FromBillNumberid ,
	           ChargeOffType ,
	           IsCharged ,
	           BTypeID ,
	           ChargeOffValue ,
	           NChargeOffValue ,
	           FromBillType ,
	           FromBillID ,
	           TeamNo ,
	           Comment,
	           ShowOrder
	         )
		SELECT @Cur_BillNumberId,
			   FromBillNumberid ,
	           ChargeOffType ,
	           IsCharged ,
	           BTypeID ,
	           ChargeOffValue ,
	           NChargeOffValue ,
	           FromBillType ,
	           FromBillID ,
	           TeamNo ,
	           Comment,
	          ShowOrder
		FROM ChargeOffBill
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
END
IF @BillType = 12 ---------------组合品销售单-----序列号复制根本不需要所有代码重复写两次(CASE WHEN就解决了)，以后考虑优化 9.8发版在即先把新单直接放后面了
	BEGIN
		INSERT INTO dbo.PT_Combin_Salebill
		        ( BillNumberId ,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          GoodsOrder ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          HandZeroCost ,
		          CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		          entryCode ,
		         -- InvoiceQty ,
		         -- InvoiceMoney ,
		         -- NInvoiceMoney ,
		        -- IsGift ,
		          BeforePromoID ,
		          ReferPrice ,
		          PriceStyle ,
		          PriceSource ,
		          PromoType ,
		        --  CompleteTotal ,
		         -- NCompleteTotal ,
		       --   LendBillID ,
		         -- LendBillNumberID ,
		          ShowOrder ,
		          DiyID ,
		          pindexid
		        )
		       
		output inserted.ID INTO #NewbILLID
		SELECT @Cur_BillNumberId,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          GoodsOrder ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          HandZeroCost ,
		          0 AS CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		          entryCode ,
		         -- InvoiceQty ,
		         -- InvoiceMoney ,
		         -- NInvoiceMoney ,
		        --  IsGift ,
		          BeforePromoID ,
		          ReferPrice ,
		          PriceStyle ,
		         '通过单据复制' as PriceSource ,
		          PromoType ,
		         -- CompleteTotal ,
		          --NCompleteTotal ,
		          --LendBillID ,
		         -- LendBillNumberID ,
		          ShowOrder ,
		          DiyID ,
		          pindexid
		FROM PT_Combin_Salebill
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
		
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	PT_Combin_OrderBill  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	PT_Combin_OrderBill O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM PT_Combin_SaleBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
		
		INSERT INTO dbo.PT_Combin_SaleBillDetail
		        ( BillNumberId ,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          Serial ,
		         -- InputCostPrice ,
		          GoodsOrder ,
		         -- BackQty ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		         -- HandZeroCost ,
		         -- CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          --ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		          entryCode ,
		         -- InvoiceQty ,
		         -- InvoiceMoney ,
		         -- NInvoiceMoney ,
		         -- IsGift ,
		          BeforePromoID ,
		          ReferPrice ,
		          PriceStyle ,
		          PriceSource ,
		          PromoType ,
		         -- CompleteTotal ,
		         -- NCompleteTotal ,
		         -- LendBillID ,
		         -- LendBillNumberID ,
		          ShowOrder ,
		          DiyID ,
		          pindexid ,
		          combinationptypeid 
		        --  SendedQty ,
		         -- PickedQty ,
		        --  ClearQty
		        )
	    output inserted.ID INTO #NewbILLID1
		SELECT @Cur_BillNumberId,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          CASE WHEN @copySerial='TRUE' THEN Serial ELSE '' END ,
		         -- InputCostPrice ,
		          GoodsOrder ,
		         -- BackQty ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		         -- HandZeroCost ,
		         -- CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		         -- ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		          entryCode ,
		         -- InvoiceQty ,
		         -- InvoiceMoney ,
		         -- NInvoiceMoney ,
		          --IsGift ,
		          BeforePromoID ,
		          ReferPrice ,
		          PriceStyle ,
		          '通过单据复制' as PriceSource  ,
		          PromoType ,
		         -- CompleteTotal ,
		         -- NCompleteTotal ,
		         -- LendBillID ,
		         -- LendBillNumberID ,
		          ShowOrder ,
		          DiyID ,
		          pindexid ,
		          combinationptypeid 
		        --  SendedQty ,
		         -- PickedQty ,
		        --  ClearQty
	    FROM PT_Combin_SaleBillDetail
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
		
		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillNumberId = @BillNumberId AND OrderID <> -1)
			UPDATE	PT_Combin_OrderBillDetail  
			SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
			FROM	PT_Combin_OrderBillDetail O
			JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM PT_Combin_SaleBillDetail b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
	END
	IF @BillType = 46 ---------------组合品销售退货单-----序列号复制根本不需要所有代码重复写两次(CASE WHEN就解决了)，以后考虑优化 9.8发版在即先把新单直接放后面了
	BEGIN
		INSERT INTO dbo.PT_Combin_SaleBackBill
		        ( BillNumberId ,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          --OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          GoodsOrder ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          HandZeroCost ,
		          CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          --ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		         -- entryCode ,
		         -- InvoiceQty ,
		         -- InvoiceMoney ,
		         -- NInvoiceMoney ,
		         IsGift ,
		          --BeforePromoID ,
		          ReferPrice ,
		          PriceStyle ,
		          --PriceSource ,
		          PromoType ,
		        --  CompleteTotal ,
		         -- NCompleteTotal ,
		       --   LendBillID ,
		         -- LendBillNumberID ,
		          ShowOrder ,
		          --DiyID ,
		          pindexid
		        )
		       
		output inserted.ID INTO #NewbILLID
		SELECT @Cur_BillNumberId,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          --OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          GoodsOrder ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		          HandZeroCost ,
		          0 AS CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          --ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		          --entryCode ,
		         -- InvoiceQty ,
		         -- InvoiceMoney ,
		         -- NInvoiceMoney ,
		          IsGift ,
		          --BeforePromoID ,
		          ReferPrice ,
		          PriceStyle ,
		         --'通过单据复制' as PriceSource ,
		          PromoType ,
		         -- CompleteTotal ,
		          --NCompleteTotal ,
		          --LendBillID ,
		         -- LendBillNumberID ,
		          ShowOrder ,
		          --DiyID ,
		          pindexid
		FROM PT_Combin_SaleBackBill
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
		
		INSERT INTO dbo.PT_Combin_SaleBackBillDetail
		        ( BillNumberId ,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          --OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          Serial ,
		         -- InputCostPrice ,
		          GoodsOrder ,
		         -- BackQty ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		         -- HandZeroCost ,
		         -- CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		         -- ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		          --entryCode ,
		         -- InvoiceQty ,
		         -- InvoiceMoney ,
		         -- NInvoiceMoney ,
		          IsGift ,
		          --BeforePromoID ,
		          ReferPrice ,
		          PriceStyle ,
		         -- PriceSource ,
		          PromoType ,
		         -- CompleteTotal ,
		         -- NCompleteTotal ,
		         -- LendBillID ,
		         -- LendBillNumberID ,
		          ShowOrder ,
		          --DiyID ,
		          pindexid ,
		          combinationptypeid 
		        --  SendedQty ,
		         -- PickedQty ,
		        --  ClearQty
		        )
	    output inserted.ID INTO #NewbILLID1
		SELECT @Cur_BillNumberId,
		          PtypeId ,
		          Qty ,
		          SalePrice ,
		          discount ,
		          DiscountPrice ,
		          costprice ,
		          jobnumber ,
		          goodsno ,
		          total ,
		          OutFactoryDate ,
		          TaxPrice ,
		          TaxTotal ,
		          comment ,
		          --OrderID ,
		          TeamNo ,
		          TeamNO1 ,
		          IsUnit2 ,
		          CASE WHEN @copySerial='TRUE' THEN Serial ELSE '' END ,
		         -- InputCostPrice ,
		          GoodsOrder ,
		         -- BackQty ,
		          GoodsNumber ,
		          ProduceDate ,
		          ValidDate ,
		          GoodsBTypeID ,
		          GoodsCostPrice ,
		          GoodsCostTotal ,
		         -- HandZeroCost ,
		         -- CompleteQTY ,
		          SaleTotal ,
		          Tax ,
		          KTypeID ,
		          Stypeid ,
		          --ShareFee ,
		          TaxMoney ,
		          NSalePrice ,
		          NSaleTotal ,
		          NDiscountPrice ,
		          NTotal ,
		          NTaxPrice ,
		          NTaxTotal ,
		          NTaxMoney ,
		          UnitID ,
		          NUnitID ,
		          NQty ,
		          UnitRate ,
		          NUnitMsg ,
		          MUnitID ,
		          MQty ,
		          MUnitRate ,
		          MUnitMsg ,
		          MSalePrice ,
		          MDiscountPrice ,
		          MTaxPrice ,
		          CurMSalePrice ,
		          CurMDiscountPrice ,
		          CurMTaxPrice ,
		          CargoID ,
		          ItemID ,
		          IsCombined ,
		          --entryCode ,
		         -- InvoiceQty ,
		         -- InvoiceMoney ,
		         -- NInvoiceMoney ,
		          IsGift ,
		         -- BeforePromoID ,
		          ReferPrice ,
		          PriceStyle ,
		          --PriceSource ,
		          PromoType ,
		         -- CompleteTotal ,
		         -- NCompleteTotal ,
		         -- LendBillID ,
		         -- LendBillNumberID ,
		          ShowOrder ,
		          --DiyID ,
		          pindexid ,
		          combinationptypeid 
		        --  SendedQty ,
		         -- PickedQty ,
		        --  ClearQty
	    FROM PT_Combin_SaleBackBillDetail
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	END


IF @@error<>0 
BEGIN
	SELECT @RetVal=-3
	GOTO Error
END 

-- 自动生成或复制草稿的单据会影响草稿库存
EXECUTE GP_CopyOrCreateBill_DraftQTY @Cur_BillNumberId,@BillType

--复制自定义字段----
--主表

INSERT	Custom_BillIndex
( 
	BillId ,
	BillType ,
	SysDiy1_head ,SysDiy2_head ,SysDiy3_head ,SysDiy4_head ,SysDiy5_head ,SysDiy6_head ,SysDiy7_head ,SysDiy8_head ,SysDiy9_head ,SysDiy10_head ,SysDiy11_head ,SysDiy12_head ,SysDiy13_head ,SysDiy14_head ,SysDiy15_head ,SysDiy16_head,
	SysDiy17_head ,SysDiy18_head ,SysDiy19_head ,SysDiy20_head ,SysDiy21_head ,SysDiy22_head ,SysDiy23_head ,SysDiy24_head ,SysDiy25_head ,SysDiy26_head ,
	SysDiy27_head ,SysDiy28_head ,SysDiy29_head ,SysDiy30_head ,SysDiy31_head ,SysDiy32_head,SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head
)
SELECT  @Cur_BillNumberId ,BillType ,SysDiy1_head ,SysDiy2_head ,SysDiy3_head ,SysDiy4_head ,SysDiy5_head ,SysDiy6_head ,SysDiy7_head ,SysDiy8_head ,SysDiy9_head ,SysDiy10_head ,SysDiy11_head ,SysDiy12_head ,SysDiy13_head ,SysDiy14_head ,SysDiy15_head ,SysDiy16_head,
		SysDiy17_head ,SysDiy18_head ,SysDiy19_head ,SysDiy20_head ,SysDiy21_head ,SysDiy22_head ,SysDiy23_head ,SysDiy24_head ,SysDiy25_head ,SysDiy26_head ,
		SysDiy27_head ,SysDiy28_head ,SysDiy29_head ,SysDiy30_head ,SysDiy31_head ,SysDiy32_head,SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head
FROM	Custom_billindex a
WHERE	BillId = @BillNumberId
		AND billtype = @BillType
--明细
DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(50)

SELECT  @TableName=DBO.F_BillTableName(@BillType)
SET @SQL=' INSERT INTO #OLDbILLID SELECT ID FROM '+@TableName+' WHERE billnumberid='+CAST(@BillNumberId AS VARCHAR(50))+' ORDER BY ID '
EXEC(@SQL)

IF @BillType NOT IN (12,46)
BEGIN
	INSERT Custom_BillDetails
	(
		BillId ,Detailid ,BillType ,SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16,
		SysDiy17 ,SysDiy18 ,SysDiy19 ,SysDiy20 ,SysDiy21 ,SysDiy22 ,SysDiy23 ,SysDiy24 ,SysDiy25 ,SysDiy26 ,SysDiy27 ,SysDiy28 ,SysDiy29 ,SysDiy30 ,SysDiy31 ,SysDiy32,SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40
	)
	SELECT @Cur_BillNumberId,N.detailID,billtype,SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16,
			SysDiy17 ,SysDiy18 ,SysDiy19 ,SysDiy20 ,SysDiy21 ,SysDiy22 ,SysDiy23 ,SysDiy24 ,SysDiy25 ,SysDiy26 ,SysDiy27 ,SysDiy28 ,SysDiy29 ,SysDiy30 ,SysDiy31 ,SysDiy32,SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40
	FROM  dbo.Custom_BillDetails a																																																																																																																																											  
	INNER JOIN #OLDbILLID O ON A.Detailid = O.detailID
	INNER JOIN #NewbILLID N ON O.ID = N.ID
	WHERE	a.BillId = @BillNumberId
			AND a.billtype = @BillType
END
ELSE
BEGIN
	INSERT Custom_BillDetails(BillId ,Detailid ,BillType ,SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16,
								 SysDiy17 ,SysDiy18 ,SysDiy19 ,SysDiy20 ,SysDiy21 ,SysDiy22 ,SysDiy23 ,SysDiy24 ,SysDiy25 ,SysDiy26 ,SysDiy27 ,SysDiy28 ,SysDiy29 ,SysDiy30 ,SysDiy31 ,SysDiy32)
	SELECT @Cur_BillNumberId,N.detailID,billtype,SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16,
							SysDiy17 ,SysDiy18 ,SysDiy19 ,SysDiy20 ,SysDiy21 ,SysDiy22 ,SysDiy23 ,SysDiy24 ,SysDiy25 ,SysDiy26 ,SysDiy27 ,SysDiy28 ,SysDiy29 ,SysDiy30 ,SysDiy31 ,SysDiy32
	FROM  dbo.Custom_BillDetails a																																																																																																																																											  
	INNER JOIN #OLDbILLID O ON A.Detailid = O.detailID
	INNER JOIN #NewbILLID1 N ON O.ID = N.ID
	WHERE	a.BillId = @BillNumberId
			AND a.billtype = @BillType
END

------------------

SELECT @CUR_ID = @Cur_BillNumberId

    
--修改制单人和制单时间 制单时间默认当前操作员 制单人复制成当前操作员
UPDATE BillIndex SET checke = @OperatorId,checkTime = GETDATE(),LastUpdateTime = NULL WHERE BillNumberId = @CUR_ID

--写入一条复制日志
INSERT INTO BillOperateLog (BillnumberID, OperateType, EtypeID, OperateTime, IP)VALUES (@CUR_ID, '制单', @OperatorId, GETDATE(), @Ip)
COMMIT Tran _CopyBillToDraft
RETURN 0
Error:
  ROLLBACK Tran _CopyBillToDraft 
  RETURN @RetVal

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CopyBillToDraftAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CopyBillToDraftAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-08-08
	描述：复制草稿的时候没有复制优惠金额	
*/
CREATE PROCEDURE Web_CopyBillToDraftAll 
(
	@OperatorId			VARCHAR(MAX),
	@BillNumberId  		VARCHAR(8000),
	@Ip					VARCHAR(MAX),
	@copySerial			bit
 )
--@encode$--
AS
SET NOCOUNT ON

DECLARE @RE			INT,
		@nBillId	NUMERIC(18,0)
		
EXEC @RE = Gp_Fz_Base '',2
IF @RE <> 0 RETURN -2		

BEGIN TRAN _CopyBill

DECLARE DraftCursor CURSOR FOR
	SELECT * FROM DBO.F_SPLIT(@BillNumberId,',')
	
OPEN DraftCursor 

FETCH NEXT FROM DraftCursor INTO @nBillId

WHILE @@FETCH_STATUS = 0
BEGIN
	EXEC @RE = Web_CopyBillToDraft @OperatorId,@nBillId,@Ip,@copySerial,0
	IF @RE <> 0
	BEGIN
		ROLLBACK TRAN _CopyBill
		RETURN @RE
		BREAK
	END
	FETCH NEXT FROM DraftCursor INTO @nBillId
END

CLOSE DraftCursor
DEALLOCATE DraftCursor

COMMIT TRAN _CopyBill

GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CopyFactBillToDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CopyFactBillToDraft]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：魏伟
	日期：2016-07-15
	描述：复制草稿的时候没有复制优惠金额	
	 
*/
CREATE PROCEDURE Web_CopyFactBillToDraft
(
	@OperatorId			VARCHAR(MAX),
	@BillNumberId  		NUMERIC(10,0),
	@Ip					VARCHAR(MAX),
	@copySerial			bit,--是否复制序列号
	@CUR_ID          	NUMERIC(10,0) OUTPUT
 )
--@encode$--
AS
SET NOCOUNT ON

DECLARE @BillType		[int]
DECLARE @Cur_BillNumberId	[numeric](10,0)

DECLARE @RetVal			[int],
		@VIP_ID			INT

SELECT @VIP_ID=NID FROM Ac_Items WHERE UserCode = '2181'
SELECT @CUR_ID = -1

-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4

DECLARE @intBit int, @intMask int
SELECT @intBit = @N & 15
SELECT @intMask = POWER(2,@intBit) ^ POWER(2,@intBit+1) ^ POWER(2,@intBit+2) ^ POWER(2,@intBit+3) ^ POWER(2,@intBit+4) ^ POWER(2,@intBit+5)
SELECT @intVersion = ( @intMask & @N ) / POWER(2,@intBit)

IF @intVersion IN (2,3,5,7,9,11,13,15)  --试用版
BEGIN
	DECLARE @intbillnumberid int
	SELECT @intbillnumberid=ISNULL(COUNT(billnumberid),0) FROM billindex
	
	IF @intbillnumberid >= 200
	BEGIN
		--RAISERROR('试用版 ！',16,1) 
		RETURN -5
	END
END  

-- ********	判断是否试用版 - END	********

-- 判断是否存在单据
SELECT 	@Cur_BillNumberId=[BillNumberId], 
		@BillType=[BillType]
FROM 	[factIndex]
WHERE 	[BillNumberId] = @BillNumberId
IF @@ROWCOUNT = 0 RETURN -1

--如果是会计凭证，则判断是否是VIP充值卡自动生成的，如果是，则不允许复制 谢吉康 2009-01-12
IF @BillType = 159
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM AccountCredence WHERE ATypeId = @VIP_ID AND BillNumberId = @BillNumberId AND TypeATypeId IN ('00002'))
			BEGIN
				RETURN -159
			END
	END
	
----调价全部仓库的草稿不允许复制单据 谢吉康 2011-04-15
--IF EXISTS(SELECT TOP 1 1 FROM AdPriceBill WHERE BillNumberId = @BillNumberId AND ChangeAllStock = 1)
--	RETURN -57
	
----收款单如果只有会员储值，则不允许复制草稿 
--IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillType = 4 AND BillNumberId = @BillNumberId)
--BEGIN
--	IF NOT EXISTS(SELECT TOP 1 1 FROM gatheringBill WHERE BillNumberId = @BillNumberId AND (VipCardID = -1 OR vipcardid IS NULL) )
--		RETURN -58
--END

----预收款单如果只有会员储值，则不允许复制草稿 
--IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE BillType = 189 AND BillNumberId = @BillNumberId)
--BEGIN
--	IF NOT EXISTS(SELECT TOP 1 1 FROM PreBill WHERE BillNumberId = @BillNumberId AND (VipCardID = -1 OR vipcardid IS NULL) )
--		RETURN -59
--END
----店账通单据不允许复制
--IF EXISTS(SELECT TOP 1 1 FROM dbo.EshopBillRelation WHERE Billnumberid=@BillNumberId)
--BEGIN
--	RETURN -60
--END

BEGIN Tran _CopyBillToDraft
 
---------------------------------------- 插入INDEX 记录---------------------------------------------------------------------------
INSERT INTO FactIndex ( 
						  BillDate ,
						  BillCode ,
						  OtherType ,
						  BillType ,
						  Stypeid ,
						  dtypeId ,
						  etypeid ,
						  ktypeid ,
						  ktypeid2 ,
						  ifcheck ,
						  checke ,
						  checkTime ,
						  RedWord ,
						  RedReason ,
						  draft ,
						  totalqty ,
						  IsIni ,
						  EntryCode ,
						  Comment ,
						  explain ,
						  --updateE ,
						  DealBTypeID ,
						  LastUpdateTime ,
						  Poster ,
						  PostTime ,
						  FromBillType ,
						  ifcargo                        
			)
                SELECT  
                          BillDate ,
						  BillCode ,
						  OtherType ,
						  BillType ,
						  Stypeid ,
						  dtypeId ,
						  etypeid ,
						  ktypeid ,
						  ktypeid2 ,
						  'f' ,
						  checke ,
						  checkTime ,
						  0 ,
						  RedReason ,
						  1 ,
						  totalqty ,
						  IsIni ,
						  EntryCode ,
						  Comment ,
						  explain ,
						 -- updateE ,
						  DealBTypeID ,
						  LastUpdateTime ,
						  Poster ,
						  PostTime ,
						  FromBillType ,
						  ifcargo
FROM 	FactIndex
WHERE 	[BillNumberId] = @BillNumberId

IF @@error<>0 
BEGIN 
   SELECT @RetVal = -2 
   GOTO Error 
END
SELECT @Cur_BillNumberId = SCOPE_IDENTITY(); 

CREATE TABLE #OLDbILLID(ID int IDENTITY(1,1), detailID int)

CREATE TABLE #NewbILLID(ID int IDENTITY(1,1), detailID int)
------------------------------------ 插入 明细  记录--------------------------------------------------------------------------------
  
-----处理是否复制序列号
--IF @copySerial='TRUE'
--BEGIN

 
  IF @BillType in (418,419)     ---------------仓库入库单  仓库出库单-----
	BEGIN
		INSERT INTO dbo.FactDepotInOut
		        (  
		       billNumberID,
		       PtypeId ,
	           Qty ,
	           BillType,
	           comment,
	          -- Id,
	           Serial,
	           GoodsOrder,
	           GoodsNumber,
	           ProduceDate,
	           ValidDate,
	           ktypeid,
	           UnitID,
	           NUnitID,
	           NQty,
	           UnitRate,
	           NUnitMsg,
	           MUnitID,
	           MQty,
	           MUnitRate,
	           MUnitMsg,    
	           CargoID,
	           ItemID,
	           IsCombined,
	          -- entrycode,
	           FromBillNumberID,
	           FromBillID,
	           FromBillType,
	           BillDate,
	           STypeID
		        )
		output inserted.ID INTO #NewbILLID
		SELECT @Cur_BillNumberId,
			   PtypeId ,
	           Qty ,
	           BillType,
	           comment,
	           --Id,
	          CASE WHEN @copySerial='TRUE' THEN Serial ELSE '' END ,
	           GoodsOrder,
	           GoodsNumber,
	           ProduceDate,
	           ValidDate,
	           ktypeid,
	           UnitID,
	           NUnitID,
	           NQty,
	           UnitRate,
	           NUnitMsg,
	           MUnitID,
	           MQty,
	           MUnitRate,
	           MUnitMsg,    
	           CargoID,
	           ItemID,
	           IsCombined,
	          -- entrycode,
	           FromBillNumberID,
	           FromBillID,
	           FromBillType ,
	           BillDate,
	           STypeID
		FROM FactDepotInOut
		WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	
	END
ELSE IF @BillType = 420 -------------------销售退货单
BEGIN
	INSERT INTO dbo.FactDepotAllot 
	        (  billNumberID,
	           comment,
		       PtypeId ,
	           Qty ,
	           Jobnumber,
	           GoodsNo,
	           OutFactoryDate,
	           IsUnit2,
	          -- Id,
	           Serial,
	           GoodsOrder,
	           GoodsNumber,
	           ProduceDate,
	           ValidDate, 
	           UnitID,
	           NUnitID,
	           NQty,
	           UnitRate,
	           NUnitMsg,
	           MUnitID,
	           MQty,
	           MUnitRate,
	           MUnitMsg,    
	           InCargoID,
	           OutCargoID,
	           ItemID,
	           IsCombined,
	           KTypeId,
	           KTypeId2
	        )
	 OUTPUT inserted.ID INTO #NewbILLID
	SELECT @Cur_BillNumberId,  
	           comment,
		       PtypeId ,
	           Qty ,
	           Jobnumber,
	           GoodsNo,
	           OutFactoryDate,
	           IsUnit2,
	          --Id,
	           CASE WHEN @copySerial='TRUE' THEN Serial ELSE '' END ,
	           GoodsOrder,
	           GoodsNumber,
	           ProduceDate,
	           ValidDate, 
	           UnitID,
	           NUnitID,
	           NQty,
	           UnitRate,
	           NUnitMsg,
	           MUnitID,
	           MQty,
	           MUnitRate,
	           MUnitMsg,    
	           InCargoID,
	           OutCargoID,
	           ItemID,
	           IsCombined,
	           KTypeId,
	           KTypeId2
	FROM FactDepotAllot 
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
END
 

--END  
IF @@error<>0 
BEGIN
	SELECT @RetVal=-3
	GOTO Error
END 


--复制自定义字段----
--主表

INSERT Custom_BillIndex( BillId ,BillType ,SysDiy1_head ,SysDiy2_head ,SysDiy3_head ,SysDiy4_head ,SysDiy5_head ,SysDiy6_head ,SysDiy7_head ,SysDiy8_head ,SysDiy9_head ,SysDiy10_head ,SysDiy11_head ,SysDiy12_head ,SysDiy13_head ,SysDiy14_head ,SysDiy15_head ,SysDiy16_head)
SELECT  @Cur_BillNumberId ,BillType ,SysDiy1_head ,SysDiy2_head ,SysDiy3_head ,SysDiy4_head ,SysDiy5_head ,SysDiy6_head ,SysDiy7_head ,SysDiy8_head ,SysDiy9_head ,SysDiy10_head ,SysDiy11_head ,SysDiy12_head ,SysDiy13_head ,SysDiy14_head ,SysDiy15_head ,SysDiy16_head
FROM Custom_billindex a
WHERE BillId = @BillNumberId
--明细
DECLARE @SQL VARCHAR(8000),
		@TableName VARCHAR(50)

SELECT  @TableName=DBO.F_BillTableName(@BillType)
SET @SQL=' INSERT INTO #OLDbILLID SELECT ID FROM '+@TableName+' WHERE billnumberid='+CAST(@BillNumberId AS VARCHAR(50))+' ORDER BY ID '
EXEC(@SQL)
INSERT Custom_BillDetails(BillId ,Detailid ,BillType ,SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16)
SELECT @Cur_BillNumberId,N.detailID,billtype,SysDiy1 ,SysDiy2 ,SysDiy3 ,SysDiy4 ,SysDiy5 ,SysDiy6 ,SysDiy7 ,SysDiy8 ,SysDiy9 ,SysDiy10 ,SysDiy11 ,SysDiy12 ,SysDiy13 ,SysDiy14 ,SysDiy15 ,SysDiy16
FROM  dbo.Custom_BillDetails a																																																																																																																																											  
INNER JOIN #OLDbILLID O ON A.Detailid = O.detailID
INNER JOIN #NewbILLID N ON O.ID = N.ID
WHERE a.BillId = @BillNumberId
------------------

SELECT @CUR_ID = @Cur_BillNumberId

    
--修改制单人和制单时间 制单时间默认当前操作员 制单人复制成当前操作员
UPDATE factindex SET checke = @OperatorId,checkTime = GETDATE(),LastUpdateTime = NULL WHERE BillNumberId = @CUR_ID

--写入一条复制日志
INSERT INTO BillOperateLog (BillnumberID, OperateType, EtypeID, OperateTime, IP)VALUES (@CUR_ID, '制单', @OperatorId, GETDATE(), @Ip)
COMMIT Tran _CopyBillToDraft
RETURN 0
Error:
  ROLLBACK Tran _CopyBillToDraft 
  RETURN @RetVal

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CopyFactBillToDraftAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CopyFactBillToDraftAll]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-08-08
	描述：复制草稿的时候没有复制优惠金额	
*/
CREATE PROCEDURE Web_CopyFactBillToDraftAll 
(
	@OperatorId			VARCHAR(MAX),
	@BillNumberId  		VARCHAR(8000),
	@Ip					VARCHAR(MAX),
	@copySerial			bit
 )
--@encode$--
AS
SET NOCOUNT ON

DECLARE @RE			INT,
		@nBillId	NUMERIC(18,0)
		
EXEC @RE = Gp_Fz_Base '',2
IF @RE <> 0 RETURN -2		

BEGIN TRAN _CopyBill

DECLARE DraftCursor CURSOR FOR
	SELECT * FROM DBO.F_SPLIT(@BillNumberId,',')
	
OPEN DraftCursor 

FETCH NEXT FROM DraftCursor INTO @nBillId

WHILE @@FETCH_STATUS = 0
BEGIN
	EXEC @RE = Web_CopyFactBillToDraft @OperatorId,@nBillId,@Ip,@copySerial,0
	IF @RE <> 0
	BEGIN
		ROLLBACK TRAN _CopyBill
		RETURN @RE
		BREAK
	END
	FETCH NEXT FROM DraftCursor INTO @nBillId
END

CLOSE DraftCursor
DEALLOCATE DraftCursor

COMMIT TRAN _CopyBill



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CopyOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CopyOrderBill]
GO















/*

	作者：陈启华
	日期：2006-05-18
	描述：订单复制
*/
CREATE PROCEDURE Web_CopyOrderBill
(
	@Operator      	varchar(100),
	@BillNumberId  	[numeric](10,0),
	@BillTypes      int,
	@CUR_ID         [numeric](10,0) OUTPUT
 )
--@encode$--
AS
SET NOCOUNT ON


DECLARE @Billtype int
DECLARE @Cur_BillNumberId	[numeric](10,0)


DECLARE @RetVal			[int]
SELECT @CUR_ID = -1


-- ********	判断是否试用版 - Start	********

DECLARE @N int, @intVersion int

-- 判断版本号，是否试用版
SELECT	@N = CAST(SubValue AS int)
FROM	SysData1
WHERE	SubNo = 2	-- 版本号

IF @N IS NULL RETURN -4 -- 版本号读取错误

-- ********	判断是否试用版 -end	********

DECLARE @BillCodeConfig varchar(1)
SELECT @BillCodeConfig=Value FROM UserConfig WHERE ConfigName='BillCodeConfig' --读取系统单据自定义配置
DECLARE @BillCode varchar(200)
DECLARE @BillCodeQty int  -- 单据编号的个数，看是否有重单的
DECLARE @EtypeID  varchar(50)
DECLARE @KtypeID  varchar(50)
DECLARE @Month    varchar(10)
DECLARE @Day    varchar(10)
DECLARE @BillFlag varchar(10)
SET @Month = Month(getDate())
SET @Day   = Day(getDate())
DECLARE @Comment varchar(300)

DECLARE 	@ceDtypeid			VARCHAR(100),
			@cefullname			VARCHAR(500)='',		--制单人
			@cdfullname			VARCHAR(500)=''			--部门


DECLARE @TotalMoney  NUMERIC(24, 10)  --单据总的金额，如果系统配置变化后，此金额需要返算

-- 系统配置
DECLARE @Gridtype varchar(10) -- 单据格式
select @Gridtype=Value from userconfig where configName ='Gridtype'
--DECLARE @TaxRate  NUMERIC(24, 10)   -- 税率

-- 判断是否存在单据
SELECT @Cur_BillNumberId=[BillNumberId], @BillType=[BillType],@EtypeID =EtypeID,@KtypeID=KtypeID,@ceDtypeid=DtypeId, --@TaxRate =Tax,
@Comment=Comment
FROM [OrderIndex]
WHERE [BillNumberId] = @BillNumberId
IF @@ROWCOUNT = 0 RETURN -1

DECLARE @EUserCode varchar(50)
DECLARE @KUserCode varchar(50)

SELECT @EUserCode =ISNULL(typeid,'') FROM Employee WHERE TypeID =@EtypeID
SELECT @cefullname = E.FullName FROM Employee E WHERE E.TypeId = @Operator
SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @ceDtypeid

IF @KTypeID=''
BEGIN
	SELECT @KUserCode=''
END
ELSE
BEGIN
	SELECT @KUserCode =ISNULL(FullName,'') FROM STOCK WHERE TypeID =@KtypeID
END

DECLARE
	@NowDate	DATETIME

SELECT @NowDate=GETDATE()

-- 目标单据类型是否有审核,有审核时置 ifAudit =0 ,无审核时置 ifAudit = 1
DECLARE @IfAudit int 
IF EXISTS (SELECT * FROM AuditingFlowSet WHERE Billtype = @BillTypes AND IfUse ='1'  AND substring(AuditingReason,1,1)<>'1')
	SET @IfAudit = 0
ELSE 
	SET @IfAudit = 1

BEGIN Tran --_CopyOrderBill

IF @BillType =301  -- 采购订单复制
BEGIN
	IF @BillTypes =301
	BEGIN
		SET @BillFlag ='JD'
		--单据采用自定义编号 #02
		IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@BillTypes ) AND @BillCodeConfig='1'
			exec Gp_GetBillCode @BillTypes,@EUserCode,@KUserCode,@BillFlag,@NowDate,@BillCode OUTPUT,@cdfullname,@cefullname
		ELSE
			exec Gp_GetBillCode @BillTypes,@Month,@Day,@BillFlag,@NowDate,@BillCode Output,@cdfullname,@cefullname


		INSERT INTO OrderIndex (BillDate,BillCode,Billtype,etypeid,btypeid,ktypeid,Dtypeid,explain,comment,ReachDate,TEL,GoodsNumber,PackWay,WayBillCode,checke,TotalQty,TotalMoney,Period,IfAudit,EtypeID2,WayMode,Tax,STypeID)
		SELECT 	BillDate,@BillCode,@BillTypes,etypeid,btypeid,ktypeid,Dtypeid,explain,comment,ReachDate,TEL,GoodsNumber,PackWay,WayBillCode,@Operator,TotalQty,TotalMoney,Period,@IfAudit,'','',tax,STypeID
		FROM 	OrderIndex
		WHERE 	[BillNumberId] = @BillNumberId
	END

	IF @BillTypes =300
	BEGIN
		SET @Comment ='' -- 不同订单类型复制时，将摘要置成空
		SET @BillFlag ='XD'
		--单据采用自定义编号 #02
		IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@BillTypes ) AND @BillCodeConfig='1'
			exec Gp_GetBillCode @BillTypes,@EUserCode,@KUserCode,@BillFlag,@NowDate,@BillCode Output,@cdfullname,@cefullname
		ELSE
			exec Gp_GetBillCode @BillTypes,@Month,@Day,@BillFlag,@NowDate,@BillCode Output,@cdfullname,@cefullname
		
		IF EXISTS(select EtypeID from loginuser where substring(lim,166,1) =1 AND EtypeID =@Operator) -- 有成本查看权限
			INSERT INTO OrderIndex (BillDate,BillCode,Billtype,etypeid,ktypeid,Dtypeid,explain,comment,GoodsNumber,PackWay,checke,TotalQty,TotalMoney,period,TEL,IfAudit,Tax,EtypeID2,WayMode,WayBillCode,STypeID)
			SELECT 	BillDate,@BillCode,@BillTypes,etypeid,ktypeid,Dtypeid,explain,@comment,GoodsNumber,PackWay,@Operator,TotalQty,TotalMoney,Period,'',@IfAudit,tax,'','','',STypeID
			FROM 	OrderIndex
			WHERE 	[BillNumberId] = @BillNumberId
		ELSE
			INSERT INTO OrderIndex (BillDate,BillCode,Billtype,etypeid,ktypeid,Dtypeid,explain,comment,GoodsNumber,PackWay,checke,TotalQty,TotalMoney,period,TEL,IfAudit,Tax,EtypeID2,WayMode,WayBillCode,STypeID)
			SELECT 	BillDate,@BillCode,@BillTypes,etypeid,ktypeid,Dtypeid,explain,@comment,GoodsNumber,PackWay,@Operator,TotalQty,0,Period,'',@IfAudit,tax,'','','',STypeID
			FROM 	OrderIndex
			WHERE 	[BillNumberId] = @BillNumberId			
	END

	IF @@error<>0 
	BEGIN 
	   SELECT @RetVal = -2 
	   GOTO Error 
	END

	SELECT @Cur_BillNumberId = SCOPE_IDENTITY();
	SELECT @BillCodeQty =Count(*) FROM OrderIndex WHERE BillCode =@BillCode


	IF @BillCodeQty>1
		BEGIN
		   SELECT @RetVal = -5
		   GOTO Error 
		END	
	--UPDATE OrderIndex  SET BillCode =@BillCode WHERE BillNumberID =@Cur_BillNumberId
	-- 复制明细，销售订单与采购订单一致 -- 后来有点不致了
	IF (EXISTS(select EtypeID from loginuser where substring(lim,166,1) =0 AND EtypeID =@Operator) AND @BillTypes =300) OR (@BillTypes =300) -- 无有成本查看权限且是采购订单复制成销售订单,不复制单价 或复制成销售订单
	BEGIN
		INSERT INTO OrderBill(BillNumberId,ptypeid,qty,price,total,Discount,DisCountPrice,TaxPrice,TaxTotal,comment,isUnit2,KTypeID,STypeID,ShowOrder)
		SELECT @Cur_BillNumberId,ptypeid,qty,0,0,Discount,0,0,0,comment,isUnit2,KTypeID,STypeID,ShowOrder
		FROM OrderBill
		WHERE [BillNumberId] = @BillNumberId ORDER BY OrderID
		-- 单据格式变化后，反算总金额 
		SELECT @TotalMoney =SUM(isNULL(TaxTotal,0)) FROM OrderBill WHERE [BillNumberId] = @Cur_BillNumberId 
		UPDATE OrderIndex Set TotalMoney = @TotalMoney WHERE  [BillNumberId] = @Cur_BillNumberId
	END
	ELSE
	BEGIN
		INSERT INTO OrderBill(BillNumberId,ptypeid,qty,price,total,Discount,DisCountPrice,TaxPrice,TaxTotal,comment,isUnit2,SaleTotal,Tax,KTypeID,STypeID,ShowOrder)
		SELECT @Cur_BillNumberId,ptypeid,qty,price,total,Discount,DisCountPrice,TaxPrice,TaxTotal,comment,isUnit2,SaleTotal,Tax,KTypeID,STypeID,ShowOrder
		FROM OrderBill
		WHERE [BillNumberId] = @BillNumberId ORDER BY OrderID
		-- 单据格式变化后，反算总金额 
		SELECT @TotalMoney =SUM(isNULL(TaxTotal,0)) FROM OrderBill WHERE [BillNumberId] = @Cur_BillNumberId 
		UPDATE OrderIndex Set TotalMoney = @TotalMoney WHERE  [BillNumberId] = @Cur_BillNumberId
	END
	
	--影响订单库存
	EXEC GP_Deal_OrderQTY @Cur_BillNumberId,@BillTypes,'+'
END



IF @BillType =300 -- 销售订单复制
BEGIN
	IF @BillTypes =301
	BEGIN
		SET @Comment ='' -- 不同订单类型复制时，将摘要置成空
		SET @BillFlag ='JD'
		--单据采用自定义编号 #02
		IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@BillTypes ) AND @BillCodeConfig='1'
			exec Gp_GetBillCode @BillTypes,@EUserCode,@KUserCode,@BillFlag,@NowDate,@BillCode Output,@cdfullname,@cefullname
		ELSE
			exec Gp_GetBillCode @BillTypes,@Month,@Day,@BillFlag,@NowDate,@BillCode Output,@cdfullname,@cefullname

		INSERT INTO OrderIndex (BillDate,BillCode,Billtype,etypeid,ktypeid,Dtypeid,explain,comment,GoodsNumber,PackWay,checke,TotalQty,TotalMoney,period,TEL,IfAudit,Tax,EtypeID2,WayMode,WayBillCode,STypeID)
		SELECT 	BillDate,@BillCode,@BillTypes,etypeid,ktypeid,Dtypeid,explain,@comment,GoodsNumber,PackWay,@Operator,TotalQty,TotalMoney,Period,'',@IfAudit,tax,'','','',STypeID
		FROM 	OrderIndex
		WHERE 	[BillNumberId] = @BillNumberId
	END

	IF @BillTypes =300
	BEGIN
		SET @BillFlag ='XD'
		--单据采用自定义编号 #02
		IF EXISTS(SELECT * FROM CodeConfig WHERE BillType =@BillTypes ) AND @BillCodeConfig='1'

			exec Gp_GetBillCode @BillTypes,@EUserCode,@KUserCode,@BillFlag,@NowDate,@BillCode Output,@cdfullname,@cefullname
		ELSE
			exec Gp_GetBillCode @BillTypes,@Month,@Day,@BillFlag,@NowDate,@BillCode Output,@cdfullname,@cefullname
		INSERT INTO OrderIndex (BillDate,BillCode,Billtype,etypeid,btypeid,ktypeid,Dtypeid,explain,comment,ReachDate,TEL,GoodsNumber,PackWay,WayBillCode,checke,TotalQty,TotalMoney,Period,IfAudit,EtypeID2,WayMode,Tax,STypeID)
		SELECT 	BillDate,@BillCode,@BillTypes,etypeid,btypeid,ktypeid,Dtypeid,explain,comment,ReachDate,TEL,GoodsNumber,PackWay,WayBillCode,@Operator,TotalQty,TotalMoney,Period,@IfAudit,'','',tax,STypeID
		FROM 	OrderIndex
		WHERE 	[BillNumberId] = @BillNumberId

	END

	IF @@error<>0 
		BEGIN 
		   SELECT @RetVal = -2 
		   GOTO Error 
		END

	SELECT @Cur_BillNumberId = SCOPE_IDENTITY();
	SELECT @BillCodeQty =Count(*) FROM OrderIndex WHERE BillCode =@BillCode
	IF @BillCodeQty>1
		BEGIN
		   SELECT @RetVal = -5
		   GOTO Error 
		END	
		
	-- 复制明细，销售订单与采购订单复制内容一样
	INSERT INTO OrderBill(BillNumberId,ptypeid,qty,price,total,Discount,DisCountPrice,TaxPrice,TaxTotal,comment,isUnit2,SaleTotal,Tax,KTypeID,STypeID,ShowOrder)
	SELECT 	@Cur_BillNumberId,ptypeid,qty,price,total,Discount,DisCountPrice,TaxPrice,TaxTotal,comment,isUnit2,SaleTotal,Tax,KTypeID,STypeID,ShowOrder
	FROM 	OrderBill
	WHERE 	[BillNumberId] = @BillNumberId ORDER BY OrderID

	-- 单据格式变化后，反算总金额 
	SELECT @TotalMoney =SUM(isNULL(TaxTotal,0)) FROM OrderBill WHERE [BillNumberId] = @Cur_BillNumberId 
	UPDATE OrderIndex Set TotalMoney = @TotalMoney WHERE  [BillNumberId] = @Cur_BillNumberId

	--影响订单库存
	EXEC GP_Deal_OrderQTY @Cur_BillNumberId,@BillTypes,'+'
END

--修改日期成当前服务器日期
UPDATE OrderIndex SET BillDate = CONVERT(varchar(10),GetDate(),120) WHERE BillNumberId = @Cur_BillNumberId

IF @@error<>0 
	BEGIN
		SELECT @RetVal=-3
		GOTO Error
	END 



IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed	@Cur_BillNumberId,@NowDate,@BillTypes,@BillCode
END

IF @@error<>0 
	BEGIN
		SELECT @RetVal=-3
		GOTO Error
	END 


SELECT @CUR_ID = @Cur_BillNumberId

COMMIT Tran --_CopyOrderBill
RETURN 0
Error:
  ROLLBACK Tran --_CopyOrderBill 
  RETURN @RetVal

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CopyOtherBillToDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CopyOtherBillToDraft]
GO



CREATE     PROCEDURE Web_CopyOtherBillToDraft (
	@BillNumberID	int
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @BillType		[int]
DECLARE @Cur_BillNumberId	[numeric](10,0)
DECLARE @datBillDate	DATETIME

DECLARE @RetVal			[int]
-- 判断是否存在单据
SELECT @Cur_BillNumberId=[BillNumberId], @BillType=[BillType],@datBillDate=BillDate
FROM [BillIndex]
WHERE [BillNumberId] = @BillNumberId
IF @@ROWCOUNT = 0 RETURN -1
BEGIN Tran _CopyBillToDraft
-- 插入 INDEX 记录
declare @MONTH VARCHAR(50),@DAY VARCHAR(50)
set @MONTH = month(getdate())
set @DAY = day(getdate())

declare @Re int,@bCode varchar(50)
EXEC @Re=Gp_GetBillCode 34, @MONTH,@DAY,'JK',@datBillDate,@bCode output

IF @Re<>0
begin
   SELECT @RetVal = -2 
   GOTO Error 
end

INSERT INTO BillIndex (AlertDay,BillDate,BillCode,BillType,Comment,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,explain,RedWord,draft,OrderId,waybillcode,goodsnumber,packway,TEL,IfAudit,preferencemoney,DTypeId,Stypeid)
SELECT AlertDay,BillDate,BillCode = @bCode,BillType = 34,Comment,atypeid='',ptypeid,btypeid='',etypeid,ktypeid,ktypeid2,'f',checke,totalmoney=0,totalinmoney=0,totalqty,tax,period,explain,0,1,OrderId,waybillcode,goodsnumber,packway,TEL,'3',preferencemoney,DTypeId,Stypeid
FROM BillIndex
WHERE [BillNumberId] = @BillNumberId
IF @@error<>0 
BEGIN 
   SELECT @RetVal = -2 
   GOTO Error 
END
SELECT @Cur_BillNumberId = SCOPE_IDENTITY();

IF NOT EXISTS(
	SELECT ConfigNo
	FROM Userconfig
	WHERE ConfigName='BillcodeCreateTime'
	AND Value=2
)
BEGIN
	EXEC GP_SaveBillCode_Seed
		@Cur_BillNumberId,
		@datBillDate,
		34,
		@bCode
END	
	
-- 插入 明细  记录

	INSERT INTO buybill(BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Stypeid,ShowOrder)
	SELECT @Cur_BillNumberId,comment,PtypeId,Qty,DiscountPrice,discount=1,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,TeamNO1,Stypeid ,ShowOrder
	FROM retailbill
	WHERE [BillNumberId] = @BillNumberId ORDER BY ID
	--代发货数量
	UPDATE	OrderBill  
	SET		WaitQty = ISNULL(O.WaitQty,0) + ISNULL(B.Qty,0) 
	FROM	OrderBill O
	JOIN (SELECT orderid,sum(isnull(b.qty,0)) as qty FROM BuyBill b WHERE b.OrderId<>-1 AND B.BillNumberId=@BillNumberId GROUP BY orderid)b ON b.orderid=O.OrderID
 
	-- 自动生成或复制草稿的单据会影响草稿库存
	EXECUTE GP_CopyOrCreateBill_DraftQTY @BillNumberId,34
IF @@error<>0 
--OR @@rowcount<=0
BEGIN
	SELECT @RetVal=-3
	GOTO Error
END 
COMMIT Tran _CopyBillToDraft
RETURN 0

Error:
  ROLLBACK Tran _CopyBillToDraft 
  RETURN @RetVal



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CouponStypeAllotDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_CouponStypeAllotDetail
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：祁丹
	日期：2019-12-12
	描述：优惠券分支机构调拨优惠券明细
*/


CREATE PROCEDURE Web_CouponStypeAllotDetail
(
	@OperatorId		varchar(200),
	--@ptypeid		varchar(100) = '',
	@stypeid		VARCHAR(8000),
	@stypeid1		VARCHAR(8000),
	@ktypeid		varchar(8000),	--发货
	@ktypeid1		varchar(8000),	--收货
	@startdate		varchar(100),
	@enddate		varchar(100),
	@couponid		varchar(200),	--优惠券
	@type			int=0,		--0为发货，1为收货
	@usercode		varchar(100)	--优惠券编码
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON;

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

create table #stype(typeid varchar(100),fullname varchar(200))		--发货分支机构
create table #stype1(typeid varchar(100),fullname varchar(200))		--收货分支机构
create table #ktype(typeid varchar(100),stypeid	varchar(100))		--发货仓库
create table #ktype1(typeid varchar(100),stypeid varchar(100))		--收货仓库
create table #ptype(typeid varchar(100))
create table #Coupon(CouponId int)

IF @type=0
BEGIN
	IF @stypeid1<>''
	BEGIN
		INSERT INTO #stype1(typeid,fullname) 
				SELECT a.typeid,a.fullname from stype a, 
				(SELECT A FROM dbo.F_Split(@stypeid1,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END 
	ELSE
	BEGIN
		INSERT INTO #stype1(typeid,fullname) 
				SELECT typeid,fullname from stype 
				WHERE  sonnum=0
	END

	IF @ktypeid1<>''
	BEGIN		
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT a.typeid,a.stypeid from stock a, 
				(SELECT A FROM dbo.F_Split(@ktypeid1,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END
	ELSE
	BEGIN
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT typeid,stypeid from Stock
				WHERE  sonnum=0
	END
END
ELSE
BEGIN
	IF @stypeid<>''
	BEGIN
		INSERT INTO #stype1(typeid,fullname) 
				SELECT a.typeid,a.fullname from stype a, 
				(SELECT A FROM dbo.F_Split(@stypeid,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END 
	ELSE
	BEGIN
		INSERT INTO #stype1(typeid,fullname) 
				SELECT typeid,fullname from stype 
				WHERE  sonnum=0
	END

	IF @ktypeid<>''
	BEGIN		
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT a.typeid,a.stypeid from stock a, 
				(SELECT A FROM dbo.F_Split(@ktypeid,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END
	ELSE
	BEGIN
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT typeid,stypeid from Stock
				WHERE  sonnum=0
	END
END


--INSERT INTO #ptype(typeid) SELECT a.typeid FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID)a
--INNER JOIN dbo.ptype p  ON a.TypeId = p.typeId WHERE p.IsService=0

IF @type=0
begin

	INSERT INTO #stype(typeid,fullname) 
		SELECT 	A.TypeId ,a.FullName
		FROM 	stype A, 
				F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorId) B 
		WHERE 	A.Typeid=B.TypeId
		
	INSERT INTO #ktype(typeid,stypeid) 
		SELECT a.typeId,a.STypeId
		FROM  STOCK A, 
				F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) B 
		WHERE 	A.Typeid=B.TypeId
end
else
begin
	INSERT INTO #stype(typeid,fullname) 
		SELECT 	A.TypeId ,a.FullName
		FROM 	stype A, 
				F_GetAllManagerBaseTypeId(@stypeid1,11,@OperatorId) B 
		WHERE 	A.typeid=B.TypeId
		
	INSERT INTO #ktype(typeid,stypeid) 
		SELECT a.typeId,a.STypeId
		FROM  STOCK A, 
				F_GetAllManagerBaseTypeId(@ktypeid1,4,@OperatorId) B 
		WHERE 	A.Typeid=B.TypeId
end


insert into #Coupon select a from dbo.f_split(@couponid,',')

create table #result
(
	stypeid		varchar(100),
	sfullname	varchar(200),
	stypeid1	varchar(100),
	sfullname1	varchar(200),
	sendqty		 NUMERIC(24, 10) ,
	sendtotal	 NUMERIC(24, 10) ,
	recqty		 NUMERIC(24, 10) ,
	rectotal	 NUMERIC(24, 10) ,
	usercode	 varchar(200),
	fullname	 varchar(200),
	couponid	 varchar(50)
)
declare @sql varchar(max)

set @sql='
	insert into #result
		select	k.stypeid,
				s.fullname,
				k1.STypeID,
				s1.fullname,
				a.sendqty,
				a.sendtotal,
				a.recqty,
				a.rectotal,
				a.usercode,
				a.fullname,
				a.couponid
		from 
			(select
					bi.OutKTypeId,
					bi.InKTypeId,
					si.qty as sendqty,
					si.Total as sendtotal,
					0 as recqty,
					0 as rectotal,
					bi.billdate,
					si.CouponId,
					coupon.usercode,
					coupon.fullname
			from  Coupon_AllotBillStype si
			inner join Coupon_BillIndex bi on si.billnumberid=bi.billnumberid 
			inner join Coupon_TypeInfo coupon on si.CouponId=coupon.CouponId
			where bi.billtype=429 and bi.ifcheck=''t'' and bi.redword=0 and bi.draft=0
			AND bi.ifYearBill=0
			union all
			select	
					bi.OutKTypeId,
					bi.InKTypeId,
					0 as sendqty,
					0 as sendtotal,
					si.qty as recqty,
					si.Total as rectotal,
					bi.billdate,
					si.CouponId,
					coupon.usercode,
					coupon.fullname
			from  Coupon_AllotBillStype si
			inner join Coupon_BillIndex bi on si.billnumberid=bi.billnumberid  
			inner join Coupon_TypeInfo coupon on si.CouponId=coupon.CouponId
			where bi.billtype=428 and bi.ifcheck=''t'' and bi.redword=0 and bi.draft=0 AND bi.ifYearBill=0	) a'
IF @type=0
begin
	set @sql=@sql+' inner join #ktype k on a.OutKTypeId=k.typeid 
					inner join #stype s on s.typeid=k.stypeid 
					inner join #ktype1 k1 on k1.typeId=a.InKTypeId 
					inner join #stype1 s1 on k1.stypeid=s1.typeid '
				
end
ELSE
BEGIN
	set @sql=@sql+' inner join #ktype k1 on a.InKTypeId=k1.typeid 
					inner join #stype s1 on s1.typeid=k1.stypeid 
					inner join #ktype1 k on k.typeId=a.OutKTypeId 
					inner join #stype1 s on k.stypeid=s.typeid '
END

if @couponid<>''
	set @sql+=' inner join #Coupon c on c.CouponId=a.CouponId'
--IF @ptypeid<>'' OR @MPtypeid<>'00000'
--	set @sql=@sql+'	inner join #ptype p on p.typeid=a.PtypeId '

IF @type=0
	set @sql=@sql+'	where a.billDate>='''+@startdate+'''
				and a.billDate<='''+@enddate+''' '
Else
	set @sql=@sql+'	where a.billDate>='''+@startdate+'''
				and a.billDate<='''+@enddate+''''
				
IF ISNULL(@usercode,'')<>''				
	set @sql=@sql+' and coupon.CouponId='''+@usercode+'''		
				order by s.fullname,s1.fullname'
				
--print(@sql)
exec(@sql)

select
	stypeid,
	stypeid1,
	usercode,
	fullname,
	sfullname,
	sfullname1,
	SUM(isnull(sendqty,0)) as sendqty,
    SUM(ISNULL(sendtotal,0)) as sendtotal,
    SUM(isnull(recqty,0)) as recqty,
    SUM(isnull(rectotal,0)) as rectotal,
    SUM(isnull(sendqty,0)-isnull(recqty,0)) as missqty,
    SUM(ISNULL(sendtotal,0)-isnull(rectotal,0)) as misstotal
from #result
group by stypeid,stypeid1,usercode,fullname,sfullname,sfullname1
order by sfullname,sfullname1

drop table #stype,#ptype,#ktype,#result,#ktype1,#stype1
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CouponStypeAllotFhList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_CouponStypeAllotFhList
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	作者：谢吉康
	日期：2019-11-08
	描述：优惠券分支机构调拨发货查询
*/


CREATE PROCEDURE Web_CouponStypeAllotFhList
(
	@OperatorId		varchar(200),
	--@ptypeid		varchar(100) = '',
	@stypeid		VARCHAR(8000),
	@stypeid1		VARCHAR(8000),
	@ktypeid		varchar(8000),	--发货
	@ktypeid1		varchar(8000),	--收货
	@startdate		varchar(100),
	@enddate		varchar(100),
	@couponid		varchar(200),	--优惠券
	@type			int=0		--0为发货，1为收货
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON;

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

create table #stype(typeid varchar(100),fullname varchar(200))		--发货分支机构
create table #stype1(typeid varchar(100),fullname varchar(200))		--收货分支机构
create table #ktype(typeid varchar(100),stypeid	varchar(100))		--发货仓库
create table #ktype1(typeid varchar(100),stypeid varchar(100))		--收货仓库
create table #ptype(typeid varchar(100))
create table #Coupon(CouponId int)

IF @type=0
BEGIN
	IF @stypeid1<>''
	BEGIN
		INSERT INTO #stype1(typeid,fullname) 
				SELECT a.typeid,a.fullname from stype a, 
				(SELECT A FROM dbo.F_Split(@stypeid1,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END 
	ELSE
	BEGIN
		INSERT INTO #stype1(typeid,fullname) 
				SELECT typeid,fullname from stype 
				WHERE  sonnum=0
	END

	IF @ktypeid1<>''
	BEGIN		
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT a.typeid,a.stypeid from stock a, 
				(SELECT A FROM dbo.F_Split(@ktypeid1,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END
	ELSE
	BEGIN
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT typeid,stypeid from Stock
				WHERE  sonnum=0
	END
END
ELSE
BEGIN
	IF @stypeid<>''
	BEGIN
		INSERT INTO #stype1(typeid,fullname) 
				SELECT a.typeid,a.fullname from stype a, 
				(SELECT A FROM dbo.F_Split(@stypeid,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END 
	ELSE
	BEGIN
		INSERT INTO #stype1(typeid,fullname) 
				SELECT typeid,fullname from stype 
				WHERE  sonnum=0
	END

	IF @ktypeid<>''
	BEGIN		
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT a.typeid,a.stypeid from stock a, 
				(SELECT A FROM dbo.F_Split(@ktypeid,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END
	ELSE
	BEGIN
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT typeid,stypeid from Stock
				WHERE  sonnum=0
	END
END


--INSERT INTO #ptype(typeid) SELECT a.typeid FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID)a
--INNER JOIN dbo.ptype p  ON a.TypeId = p.typeId WHERE p.IsService=0

IF @type=0
begin

	INSERT INTO #stype(typeid,fullname) 
		SELECT 	A.TypeId ,a.FullName
		FROM 	stype A, 
				F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorId) B 
		WHERE 	A.Typeid=B.TypeId
		
	INSERT INTO #ktype(typeid,stypeid) 
		SELECT a.typeId,a.STypeId
		FROM  STOCK A, 
				F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) B 
		WHERE 	A.Typeid=B.TypeId
end
else
begin
	INSERT INTO #stype(typeid,fullname) 
		SELECT 	A.TypeId ,a.FullName
		FROM 	stype A, 
				F_GetAllManagerBaseTypeId(@stypeid1,11,@OperatorId) B 
		WHERE 	A.typeid=B.TypeId
		
	INSERT INTO #ktype(typeid,stypeid) 
		SELECT a.typeId,a.STypeId
		FROM  STOCK A, 
				F_GetAllManagerBaseTypeId(@ktypeid1,4,@OperatorId) B 
		WHERE 	A.Typeid=B.TypeId
end


insert into #Coupon select a from dbo.f_split(@couponid,',')

create table #result
(
	stypeid		varchar(100),
	sfullname	varchar(200),
	stypeid1	varchar(100),
	sfullname1	varchar(200),
	sendqty		 NUMERIC(24, 10) ,
	sendtotal	 NUMERIC(24, 10) ,
	recqty		 NUMERIC(24, 10) ,
	rectotal	 NUMERIC(24, 10) 
)
declare @sql varchar(max)

set @sql='
	insert into #result
		select	k.stypeid,
				s.fullname,
				k1.STypeID,
				s1.fullname,
				a.sendqty,
				a.sendtotal,
				a.recqty,
				a.rectotal
		from 
			(select
					bi.OutKTypeId,
					bi.InKTypeId,
					si.qty as sendqty,
					si.Total as sendtotal,
					0 as recqty,
					0 as rectotal,
					bi.billdate,
					si.CouponId
			from  Coupon_AllotBillStype si
			inner join Coupon_BillIndex bi on si.billnumberid=bi.billnumberid  
			where bi.billtype=429 and bi.ifcheck=''t'' and bi.redword=0 and bi.draft=0
			AND bi.ifYearBill=0
			union all
			select	
					bi.OutKTypeId,
					bi.InKTypeId,
					0 as sendqty,
					0 as sendtotal,
					si.qty as recqty,
					si.Total as rectotal,
					bi.billdate,
					si.CouponId
			from  Coupon_AllotBillStype si
			inner join Coupon_BillIndex bi on si.billnumberid=bi.billnumberid  
			where bi.billtype=428 and bi.ifcheck=''t'' and bi.redword=0 and bi.draft=0 AND bi.ifYearBill=0	) a'
IF @type=0
begin
	set @sql=@sql+' inner join #ktype k on a.OutKTypeId=k.typeid 
					inner join #stype s on s.typeid=k.stypeid 
					inner join #ktype1 k1 on k1.typeId=a.InKTypeId 
					inner join #stype1 s1 on k1.stypeid=s1.typeid '
				
end
ELSE
BEGIN
	set @sql=@sql+' inner join #ktype k1 on a.InKTypeId=k1.typeid 
					inner join #stype s1 on s1.typeid=k1.stypeid 
					inner join #ktype1 k on k.typeId=a.OutKTypeId 
					inner join #stype1 s on k.stypeid=s.typeid '
END

if @couponid<>''
	set @sql+=' inner join #Coupon c on c.CouponId=a.CouponId'
--IF @ptypeid<>'' OR @MPtypeid<>'00000'
--	set @sql=@sql+'	inner join #ptype p on p.typeid=a.PtypeId '

IF @type=0
	set @sql=@sql+'	where a.billDate>='''+@startdate+'''
				and a.billDate<='''+@enddate+'''
				order by s.fullname,s1.fullname'
Else
	set @sql=@sql+'	where a.billDate>='''+@startdate+'''
				and a.billDate<='''+@enddate+'''
				order by s1.fullname,s.fullname'
				
print(@sql)
exec(@sql)

select
	stypeid,
	stypeid1,
	SUM(isnull(sendqty,0)) as sendqty,
    SUM(ISNULL(sendtotal,0)) as sendtotal,
    SUM(isnull(recqty,0)) as recqty,
    SUM(isnull(rectotal,0)) as rectotal,
    SUM(isnull(sendqty,0))-SUM(isnull(recqty,0)) as missqty,
    SUM(ISNULL(sendtotal,0))-SUM(isnull(rectotal,0)) as misstotal
from #result
group by stypeid,stypeid1,sfullname,sfullname1
order by sfullname,sfullname1

drop table #stype,#ptype,#ktype,#result,#ktype1,#stype1
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CouponStypeMoveInOutDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_CouponStypeMoveInOutDetail
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		qidan
-- Create date: 2019-12-12
-- Description: 优惠券分支机构调拨查询-出入库明细
-- =============================================
CREATE PROCEDURE Web_CouponStypeMoveInOutDetail
(
	@OperatorId		varchar(200),
	@stypeid		VARCHAR(8000),
	@stypeid1		VARCHAR(8000),
	@ktypeid		varchar(8000),
	@ktypeid1		varchar(8000),
	@startdate		varchar(100),
	@enddate		varchar(100),
	@type			int=0,		--0为发货，1为收货
	@IsReporting	INT,				--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@usercode		varchar(100)	--优惠券编码
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON;

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

create table #stype(typeid varchar(100))		
create table #ktype(typeid varchar(100),stypeid	varchar(100))	
create table #stype1(typeid varchar(100))		
create table #ktype1(typeid varchar(100),stypeid	varchar(100))		
create table #ptype(typeid varchar(100))


IF @type=0
BEGIN
	INSERT INTO #ktype(typeid,stypeid) 
		SELECT s.typeid,s.STypeID FROM STOCK s inner join  F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID) b on s.typeId=b.TypeId
	INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	IF @stypeid1<>''
	BEGIN
		INSERT INTO #stype1(typeid) 
				SELECT a.typeid from stype a, 
				(SELECT A FROM dbo.F_Split(@stypeid1,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END 
	ELSE
	BEGIN
		INSERT INTO #stype1(typeid) 
				SELECT typeid from stype 
				WHERE  sonnum=0
	END

	IF @ktypeid1<>''
	BEGIN		
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT a.typeid,a.stypeid from stock a, 
				(SELECT A FROM dbo.F_Split(@ktypeid1,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END
	ELSE
	BEGIN
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT typeid,stypeid from Stock
				WHERE  sonnum=0
	END
END
ELSE
BEGIN
	INSERT INTO #ktype(typeid,stypeid) 
		SELECT s.typeid,s.STypeID FROM STOCK s inner join  F_GetAllManagerBaseTypeId(@ktypeid1,4,@OperatorID) b on s.typeId=b.TypeId
	INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid1,11,@OperatorID)
	IF @stypeid<>''
	BEGIN
		INSERT INTO #stype1(typeid) 
				SELECT a.typeid from stype a, 
				(SELECT A FROM dbo.F_Split(@stypeid,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END 
	ELSE
	BEGIN
		INSERT INTO #stype1(typeid) 
				SELECT typeid from stype 
				WHERE  sonnum=0
	END

	IF @ktypeid<>''
	BEGIN		
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT a.typeid,a.stypeid from stock a, 
				(SELECT A FROM dbo.F_Split(@ktypeid,',')) b
				WHERE LEFT(A.TypeId,LEN(B.A))=B.A
	END
	ELSE
	BEGIN
		INSERT INTO #Ktype1(typeid,stypeid) 
				SELECT typeid,stypeid from Stock
				WHERE  sonnum=0
	END
END
		
		

declare @sql varchar(max)
set @sql='select
				row_number() over (order by bi.BillnumberID) as row_id,
				bi.BillNumberId,
				bi.BillType,
				bi.BillCode,
				bi.BillDate,
				bi.DTypeId,
				bi.etypeid,
				bi.RedWord,
				si.id AS CustomdetailID,'
IF @type=0
	SET @sql=@sql+' bi.OutKTypeId , '
ELSE
	SET @sql=@sql+' bi.InKTypeId , '

set @sql=@sql+'	sum(iSnull(si.Qty,0)) as qty,
				sum(isnull(si.Total,0)) as total,
				si.Price,
				coupon.usercode,
				coupon.fullname
		from Coupon_BillIndex bi
		inner join Coupon_AllotBillStype si on bi.BillNumberId=si.BillNumberId 
		inner join Coupon_TypeInfo coupon on si.CouponId=coupon.CouponId
		'


IF @type=0
begin
	set @sql=@sql+' inner join #ktype k on bi.OutKTypeId=k.typeid 
					inner join #stype s on s.typeid=k.stypeid 
					inner join #ktype1 k1 on k1.typeId=bi.InKTypeId 
					inner join #stype1 s1 on k1.stypeid=s1.typeid  '
				
end
ELSE
BEGIN
	set @sql=@sql+' inner join #ktype k1 on bi.InKTypeId=k1.typeid 
					inner join #stype s1 on s1.typeid=k1.stypeid 
					inner join #ktype1 k on k.typeId=bi.OutKTypeId  
					inner join #stype1 s on k.stypeid=s.typeid '
END


set @sql=@sql+'	where bi.billdate>='''+@startdate+'''
				and bi.billdate<='''+@enddate+'''
				and bi.ifcheck=''t''
				and bi.redword=0 
				AND bi.ifYearBill=0'		--年节存标志
				
IF ISNULL(@usercode,'')<>''				
		set @sql=@sql+' and coupon.CouponId='''+@usercode+''''	
IF @type=0
	SET @sql=@sql+' and bi.BillType=429 '
ELSE
	SET @sql=@sql+' and bi.BillType=428 '
set @sql=@sql+' group by 
						bi.BillNumberId,
						bi.BillType,
						bi.BillCode,
						bi.BillDate,
						bi.DTypeId,
						bi.etypeid,
						bi.RedWord,
						si.Price,
						si.id, 
						coupon.usercode,
						coupon.fullname, '
IF @type=0
	SET @sql=@sql+' bi.OutKTypeId '
ELSE
	SET @sql=@sql+' bi.InKTypeId '
--set @sql=@sql+' order by bi.billdate,bi.billcode'

--exec(@sql)
--print(@sql)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
--	SET @SQL=@SQL+' ORDER BY bi.billdate,bi.billcode'
--	--PRINT @SQL
--	EXEC(@SQL)
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
	--CREATE TABLE #CustomData
	--(
	--	Costom1		varchar(max),
	--	Costom2		varchar(max),
	--	Costom3		varchar(max),
	--	Costom4		varchar(max),
	--	Costom5		varchar(max),
	--	Costom6		varchar(max),
	--	Costom7		varchar(max),
	--	Costom8		varchar(max),
	--	Costom9		varchar(max),
	--	Costom10		varchar(max),
	--	Costom11		varchar(max),
	--	Costom12		varchar(max),
	--	Costom13		varchar(max),
	--	Costom14		varchar(max),
	--	Costom15		varchar(max),
	--	Costom16		varchar(max),
	--	Costom1detail		varchar(max),
	--	Costom2detail		varchar(max),
	--	Costom3detail		varchar(max),
	--	Costom4detail		varchar(max),
	--	Costom5detail		varchar(max),
	--	Costom6detail		varchar(max),
	--	Costom7detail		varchar(max),
	--	Costom8detail		varchar(max),
	--	Costom9detail		varchar(max),
	--	Costom10detail		varchar(max),
	--	Costom11detail		varchar(max),
	--	Costom12detail		varchar(max),
	--	Costom13detail		varchar(max),
	--	Costom14detail		varchar(max),
	--	Costom15detail		varchar(max),
	--	Costom16detail		varchar(max),
	--	row_id				varchar(100)
	--)

	SET @SQL ='SELECT * INTO #Result FROM (' + @Sql + ') AS bi ORDER BY bi.billdate,bi.billcode' + 
			  ' 
			  	SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
					  FROM #Result a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid
				
				DROP TABLE #Result
			   '
	EXEC (@SQL)

----------------------------------------------------------

drop table #stype,#ptype,#ktype,#ktype1,#stype1
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CurDayNotes]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CurDayNotes]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2011-8-26
	描述：查询当天记事本(初次打开开始页面使用)
-------------------------------------------*/
CREATE PROCEDURE Web_CurDayNotes
(
	@CurDate	    VARCHAR(MAX),
	@OperatorID		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'SELECT	ID,					
					AlertTime,
					CASE	WHEN LEN(Content) > 30
							THEN LEFT(REPLACE(Content, CHAR(13), '' ''),30) + ''......''
							ELSE REPLACE(Content, CHAR(13), '' '') 
					END AS content,	 					
					UserId
			FROM	NotePad
			WHERE	AlertTime >= '''+@CurDate+'''
					AND AlertTime < CONVERT(DATE, DATEADD(DAY,1,'''+@CurDate+'''))
					AND UserId = '''+@OperatorID+'''
					AND Flag = 0
					AND ScanTimes = 0'
					
					
--PRINT(@SQL)
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[WEB_CustomerSellStat]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].WEB_CustomerSellStat
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*------------------------------------------
 作者：蒋奎
 日期：2014-6-17
 描述：跨帐套查询-客户销售统计-查询
 思路: 从GP_GoodsSellStat存储过程里面sum合计出数据
-------------------------------------------*/
CREATE PROCEDURE WEB_CustomerSellStat
(
	@dealbtypeid VARCHAR(max)='',
	@startdate  VARCHAR(30),
	@enddate	VARCHAR(30),
	@tbName		VARCHAR(100), --临时表名
	@defaultaccount  VARCHAR(1000),
	@flag		VARCHAR(30)='False',--显示为0
	@ruletype		INT,			--规则类型: 0=系统规则,1=自定义规则的编码, 2=自定义规则的名称 , 3=自定义规则的编码和名称
	@showway			VARCHAR(30)	--统计方式 full全部，season 按季度 year 按年度
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON;
	
	DECLARE @chvLen VARCHAR(10)
	DECLARE @SQL VARCHAR(max)=''
	DECLARE @configSQL VARCHAR(max)
	DECLARE @config int=0
	--SELECT @configSQL= 'SELECT @config=Value FROM '+@defaultaccount+'.dbo.Userconfig WHERE ConfigName=''sharefee'''
	--EXEC (@configSQL)
	SET @config=0
	
	--构造最后出数据要用的@SqlWhere
	DECLARE @sonnum INT	,@SqlWhere VARCHAR(200)
	DECLARE @tmpsql NVARCHAR(1000)
	
	IF @dealbtypeid=''
		SET @dealbtypeid='00000'
		
	SET @tmpsql='select @sonnum=sonnum from '+@defaultaccount+'.dbo.btype where typeid='''+@dealbtypeid+''''
	exec sp_executesql @tmpsql,N'@sonnum int output',@sonnum output
 
	IF @sonnum>0
		SET @SqlWhere=' WHERE b.parid= '''+@dealbtypeid	 +''''
	ELSE 
		SET @SqlWhere=' WHERE b.typeid= '''+@dealbtypeid+''''
	
	--将默认帐套btype的数据存到#btype
	CREATE TABLE #btype 
	(
		TypeID varchar(50),
		usercode VARCHAR(200),
		fullname VARCHAR(200),
		parid  VARCHAR(50),
		sonnum	INT,
		bid INT
	)
	
	DECLARE @tmp  VARCHAR(8000)
		SELECT @tmp='	INSERT INTO #btype(typeid,usercode,fullname,parid,sonnum,bid)
							SELECT b.typeid,b.usercode,b.fullname,b.parid,b.sonnum,b.bid 
							FROM '+@defaultaccount+'.dbo.btype b '	
		EXEC(@tmp)
		--PRINT (@tmp)
	--构造截取变量@chvLen
	IF @dealbtypeid='00000'  OR @dealbtypeid = ''
			SET @chvLen='5'
	ELSE
			SET @chvLen=CAST(LEN(@dealbtypeid)+5 AS varchar(20))
			
	SELECT @SQL = 'SELECT SUBSTRING(a.TypeID, 1,'+ @chvLen + ') AS typeID'	
	

	--按季度展示
	IF @showway = 'season'
	BEGIN
		CREATE TABLE #columnName
		(	
			id  INT IDENTITY(1,1),	    
			columnName	VARCHAR(50),
			SeasonFullName    VARCHAR(10)
		)
		INSERT INTO #columnName
		SELECT * FROM
		(
			SELECT YearFullName+'年-'+SeasonFullName+'季度' AS columnName,YearFullName+SeasonFullName AS SeasonFullName--CONVERT(VARCHAR(10),StartDate,120) AS StartDate,CONVERT(VARCHAR(10),EndDate,120) AS EndDate
			FROM dbo.F_GetTwoDate(@startdate,@enddate,2)
			UNION ALL
			SELECT YearFullName+'年-合计数' AS columnName, YearFullName AS SeasonFullName--CONVERT(VARCHAR(10),StartDate,120) AS StartDate,CONVERT(VARCHAR(10),EndDate,120) AS EndDate  
			FROM dbo.F_GetTwoDate(@startdate,@enddate,3)
		)a ORDER BY columnName
		--根据时间临时表#columnName动态拼接季度列
		SELECT @SQL=@SQL+',SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN qty END) ['+S.columnName+'销售数量]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN SaleTotal END) ['+S.columnName+'折前销售金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN total END) ['+S.columnName+'销售金额]
  						 				  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN TaxTotal END)-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN total END)['+S.columnName+'税额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN TaxTotal END) ['+S.columnName+'价税合计]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN CostTotal END) ['+S.columnName+'成本金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN ProtectTotal END) ['+S.columnName+'价保金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN Advantagetotal END) ['+S.columnName+'返利金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN Total END)
						  -SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN CostTotal END)'+
								CASE WHEN @config=1 THEN '-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN sharefee END)' ELSE '' END+
								'-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +'THEN Advantagetotal END)
								- SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN ProtectTotal END) 
								as ['+S.columnName+'毛利]

						  '
		FROM (SELECT  columnName,SeasonFullName --AS Season,CONVERT(VARCHAR(10),StartDate,120) AS StartDate,CONVERT(VARCHAR(10),EndDate,120) AS EndDate
			  FROM #columnName) s
			  
		DROP TABLE #columnName
		
	END
	--按年展示
	IF @showway = 'year'
	BEGIN
		SELECT @SQL=@SQL+',SUM(CASE WHEN timeType = '+YearFullName+' THEN qty END) ['+S.columnName+'销售数量]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN SaleTotal END) ['+S.columnName+'折前销售金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN total END) ['+S.columnName+'销售金额]
  						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN TaxTotal END)-SUM(CASE WHEN timeType = '+YearFullName+' THEN total END)['+S.columnName+'税额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN TaxTotal END) ['+S.columnName+'价税合计]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN CostTotal END) ['+S.columnName+'成本金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN ProtectTotal END) ['+S.columnName+'价保金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN Advantagetotal END) ['+S.columnName+'返利金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN Total END)-SUM(CASE WHEN timeType = '+YearFullName+' THEN CostTotal END)'+
								CASE WHEN @config=1 THEN '-SUM(CASE WHEN timeType = '+YearFullName+' THEN sharefee END)' ELSE '' END+
								'-SUM(CASE WHEN timeType = '+YearFullName+' THEN Advantagetotal END)- SUM(CASE WHEN timeType = '+YearFullName+' THEN ProtectTotal END) 
								as ['+S.columnName+'毛利]
						
						  '
		FROM (SELECT  YearFullName+'年' AS columnName,YearFullName
					FROM dbo.F_GetTwoDate(@startdate,@enddate,3)) s
		
	END
	--展示所有
	IF @showway = 'full'
	BEGIN
		--这个SQL体现了清晰的算法
		
		SELECT @SQL=@SQL+',SUM(qty ) [SUM_Qty]
						  ,SUM(SaleTotal) [SUM_DiscountTotal]
						  ,SUM(total) [SUM_Total]
						  ,SUM(TaxTotal ) [SUM_TaxTotal]
						  ,SUM(TaxTotal)-SUM(total)[TaxGe]
						  ,SUM(CostTotal) [SUM_CostTotal]
						  ,SUM(ProtectTotal) [ProtectTotal]
						  ,SUM(Advantagetotal) [Advantagetotal]
						  ,SUM(Total)-SUM(CostTotal)'+
								CASE WHEN @config=1 THEN '-SUM(sharefee)' ELSE '' END+
								'-SUM(Advantagetotal)- SUM(ProtectTotal) 
								as [SUM_MaoLi]
						  
						  '
	END
	
	--合并规则
	DECLARE @joinwhere VARCHAR(100)=''
	
	IF @ruletype=0
	BEGIN
		SET @joinwhere=' a.xid=b.Bid '
	END
	IF @ruletype=1
	BEGIN
		 SET @joinwhere=' a.usercode=b.usercode '
	END
	IF @ruletype=2
	BEGIN
		SET @joinwhere=' a.fullname=b.fullname '
	END
	IF @ruletype=3
	BEGIN
		SET @joinwhere=' a.usercode=b.usercode  and a.fullname=b.fullname'
	END
	
	--将@tbName里面的销售明细数据和默认帐套的btype表数据进行合并(根据合并规则)
	SELECT @SQL = @SQL+ ' FROM  ['+@tbName+']  A
							  INNER JOIN #btype b ON '+@joinwhere+'
							  GROUP BY SUBSTRING(a.TypeID, 1,'+ @chvLen + ')'

	--最后将sum好的数据@SQL和#btype INNER JOIN	(不显示为零)  LEFT JOIN(显示为零) 出数据
	IF @flag='False'
	BEGIN
		--不显示为零
		SELECT  @SQL = '  SELECT b.typeid ,b.usercode,b.fullname,b.parid,b.sonnum, bi.* 
						  FROM #btype b
						  INNER JOIN ('+@SQL+')bi ON bi.typeid=b.typeid
						  '+@SqlWhere+'
						  order by b.usercode '
		

	END
	ELSE
	BEGIN
		--显示为零
		SELECT  @SQL = '  SELECT b.typeid ,b.usercode,b.fullname,b.parid,b.sonnum,bi.* 
						  FROM #btype b
						  LEFT JOIN ('+@SQL+')bi ON bi.typeid=b.typeid
						   '+@SqlWhere+'
						  order by b.usercode '
	END
	
	--select * from #btype			       
	--PRINT (@sql)
	EXEC (@SQL)
	
	DROP TABLE #btype
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_CustomLoadDisplayField]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_CustomLoadDisplayField]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：Awu
	日期：2015.10.14
	描述：读取自定义显示字段的数据
*/
CREATE PROCEDURE Web_CustomLoadDisplayField
(
	@typeid	VARCHAR(50),
	@type	VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON

IF @type = 'stype'
	SELECT  UserCode AS ds_usercode,
			tel AS ds_tel,
			LinkMan AS ds_linkman,
			CASE PriceType WHEN 0 THEN '商品物价信息'
				ELSE '分支机构物价信息' END AS ds_pricetype 
	FROM dbo.SType 
	WHERE TypeId = @typeid
	
ELSE IF @type = 'dbtype'
	SELECT	Tel1  AS ddb_tel1,
			T1.tel2 AS ddb_tel2,
			tel3  AS ddb_tel3,
			TelAndAddress  AS ddb_TelAndAddress,
			WWW  AS ddb_www,
			T1.Email  AS ddb_email,
			fax  AS ddb_fax,
			T2.FullName AS ddb_afullname,
			TaxNumber  AS ddb_TaxNumber,
			Bank  AS ddb_Bank,
			BankName  AS ddb_BankName,
			BankAndAcount  AS ddb_BankAndAcount,
			LinkMan1  AS ddb_LinkMan1, 
			LinkTel1  AS ddb_LinkTel1,
			LinkMobile1  AS ddb_LinkMobile1,
			LinkMan2  AS ddb_LinkMan2,
			LinkTel2  AS ddb_LinkTel2,
			LinkMobile2  AS ddb_LinkMobile2,
			T1.PyCode  AS ddb_PyCode,
			CASE WHEN ARLimitTime < 9999 THEN CAST(ARLimitTime AS INT) ELSE NULL END  AS ddb_ARLimitTime,
			CASE WHEN paymentLTime < 9999 THEN CAST(paymentLTime AS INT) ELSE NULL END  AS ddb_paymentLTime,
			CAST(SaleZekou AS FLOAT)  AS ddb_SaleZekou,
			CAST(BuyZekou AS FLOAT)  AS ddb_BuyZekou,
			T3.FullName AS ddb_efullname,
			T1.Comment  AS ddb_Comment
	FROM dbo.btype T1
		LEFT JOIN dbo.AreaType T2 ON T1.AreaTypeID = T2.typeid
		LEFT JOIN dbo.employee T3 ON T1.etypeid = T3.typeId
	WHERE T1.TypeId = @typeid	
	
ELSE IF @type ='btype'
		SELECT Tel1  AS db_tel1,
			T1.tel2 AS db_tel2,
			tel3  AS db_tel3,
			TelAndAddress  AS db_TelAndAddress,
			WWW  AS db_www,
			T1.Email  AS db_email,
			fax  AS db_fax,
			T2.FullName AS db_afullname,
			TaxNumber  AS db_TaxNumber,
			Bank  AS db_Bank,
			BankName  AS db_BankName,
			BankAndAcount  AS db_BankAndAcount,
			LinkMan1  AS db_LinkMan1, 
			LinkTel1  AS db_LinkTel1,
			LinkMobile1  AS db_LinkMobile1,
			LinkMan2  AS db_LinkMan2,
			LinkTel2  AS db_LinkTel2,
			LinkMobile2  AS db_LinkMobile2,
			T1.PyCode  AS db_PyCode,
			CASE WHEN ARLimitTime < 9999 THEN CAST(ARLimitTime AS INT) ELSE NULL END  AS db_ARLimitTime,
			CASE WHEN paymentLTime < 9999 THEN CAST(paymentLTime AS INT) ELSE NULL END  AS db_paymentLTime,
			CAST(SaleZekou AS FLOAT)  AS db_SaleZekou,
			CAST(BuyZekou AS FLOAT)  AS db_BuyZekou,
			T3.FullName AS db_efullname,
			T1.Comment  AS db_Comment
	FROM dbo.btype T1
		LEFT JOIN dbo.AreaType T2 ON T1.AreaTypeID = T2.typeid
		LEFT JOIN dbo.employee T3 ON T1.etypeid = T3.typeId		
	WHERE T1.TypeId = @typeid	

ELSE IF @type = 'etype'
	SELECT T1.usercode AS de_usercode,
			CASE WHEN Birthday = '2050-01-01' OR Birthday = '1900-01-01' THEN NULL ELSE CONVERT(varchar(100),Birthday,23) END  AS de_birthday,
			T1.tel AS de_tel,
			Mob AS de_mob,
			mail AS de_mail,
			job AS de_job,
			T1.Address AS de_address,
			T1.PyCode AS de_pycode,
			T1.Comment AS de_comment,
			CASE WHEN MaxPre < 0 THEN NULL ELSE CAST(MaxPre AS FLOAT) END AS de_maxpre,
			CAST(tichengRate AS FLOAT) AS de_tichengRate,
			T2.FullName AS de_sfullname
	FROM dbo.employee T1
		INNER JOIN dbo.SType T2 ON T1.STypeID = T2.TypeId
	WHERE T1.TypeId = @typeid	

ELSE IF @type = 'department'
	SELECT usercode AS dd_usercode,
			Name AS dd_name,
			Tel AS dd_tel,
			fax AS dd_fax,
			LinkMan AS dd_linkman,
			Comment AS dd_comment,
			PyCode AS dd_pycode
	FROM dbo.Department
	WHERE typeid = @typeid

ELSE IF @type = 'stock'
	SELECT T1.UserCode AS dst_usercode,
			T1.name AS dst_name,
			[add] AS dst_add,
			T1.Tel AS dst_tel,
			T1.LinkMan AS dst_linkman,
			T1.PyCode AS dst_pycode,
			T1.Comment AS dst_comment,
			T2.FullName AS dst_sfullname
	FROM dbo.Stock T1
		INNER JOIN dbo.SType T2 ON t1.STypeID = T2.TypeId
	WHERE T1.TypeId = @typeid	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_DefaultStock]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].Web_DefaultStock
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*------------------------------------------
 作者：蒋奎
 日期：2014-11-12
 描述：默认仓库
-------------------------------------------*/
CREATE PROCEDURE Web_DefaultStock
    (
		@OperateType VARCHAR(100),	--操作类型
		@OperatorId  VARCHAR(100),	--操作人员ID
		@STypeID     VARCHAR(100),	--选择行分支机构ID
		@IsNext				  INT,	--上下层标识
		@Filter		 VARCHAR(256),  --查找的值
		@TypeId		 VARCHAR(100)	--基本信息Id

    )
--@encode$--    
AS
SET NOCOUNT ON

BEGIN
 DECLARE @SQL VARCHAR(max) =''

 IF	@OperateType='getstype'		--添加时-获取分支机构列表 (父节点不出)
 BEGIN	
	 SET @SQL=' SELECT TypeId as stypeid,FullName as sfullname FROM F_GetManSTypeAll('''+@OperatorId+''') WHERE sonnum=0 ORDER BY usercode' 
	 EXEC (@SQL)
 END
  
  
 IF	@OperateType='getstock'		--修改时-获取分支机构的默认仓库列表(在DefaultStock表已有的+新添加的分支机构)
 BEGIN	
		CREATE TABLE #Stock
		(
			Stypeid		VARCHAR(100),					
			Sfullname	VARCHAR(256),
			Ktypeid		VARCHAR(100),					
			Kfullname	VARCHAR(256),
			usercode    VARCHAR(256),					
			CargoId		INT,
			CargoFullName  VARCHAR(200) 
		)
		 SET @SQL=' INSERT INTO  #Stock
					SELECT 
						a.Stypeid,
						b.fullname as Sfullname,
						a.Ktypeid,
						c.fullname as Kfullname,
						b.usercode,
						a.CargoId,
						CT.fullname as cargofullname
					FROM DefaultStock a
					INNER JOIN F_GetManSTypeAll ('''+@OperatorId+''') b ON a.Stypeid=b.typeid AND b.sonnum=0
					LEFT JOIN Stock c ON a.Ktypeid=c.typeid
					LEFT JOIN CargoType CT ON a.CargoId=CT.CargoId
					WHERE a.Ptypeid='''+@TypeId+'''  
					UNION /*合并新添加的分支机构*/
					SELECT 
						TypeId as Stypeid,
						FullName as Sfullname,
						'' '' as Ktypeid,
						'' '' as Kfullname,
						usercode,
						'''' cargoid,
						'''' cargofullname
					FROM F_GetManSTypeAll('''+@OperatorId+''')  
					WHERE sonnum=0 AND Typeid NOT IN (
						SELECT Stypeid FROM DefaultStock WHERE Ptypeid='''+@TypeId+'''
					)
					/*不在权限范围内的仓库,星号处理,不予与查看*/
					UPDATE #Stock SET Kfullname=''******'',cargofullname=''******'' WHERE Ktypeid NOT IN ( SELECT TypeId FROM F_GetManKTypeAll('''+@OperatorId+''') UNION SELECT  '' '')  
					/*出数据*/
					SELECT * FROM #Stock 
							 ORDER BY usercode
				  ' 
		 EXEC (@SQL)
 END
  
  
  
------------------------------------------------------默认仓库Selector--根据分支机构出树形的仓库-开始-------------------------------------------------------
 IF @OperateType='stockselecter' 
 BEGIN
		    CREATE TABLE #BaseInfo
			(
				TypeID		VARCHAR(100),
				ParId		VARCHAR(100),
				SonNum		INT,
				deleted		INT,			
				UserCode	VARCHAR(256),
				FullName	VARCHAR(256),
				PyCode		VARCHAR(256),
			)

			SET @SQL='  INSERT INTO #BaseInfo(TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode) 
						SELECT TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode 
						FROM  F_AllTreeK('''+@OperatorId+''')
						WHERE deleted = 0  AND STypeID = '''+@STypeID+''''
			EXEC (@SQL)


			DECLARE @SonNum INT
			DECLARE @ParId	VARCHAR(100)

			SELECT @SonNum = SonNum,@ParId=ParId FROM #BaseInfo WHERE TypeId = @TypeId
			DELETE #BaseInfo WHERE TypeID = '00000'  --剔除无用的根记录
				
			IF @Filter = ''
			BEGIN
					IF @IsNext = '0' --上一层(用传来的@TypeID的ParID去匹配表中的ParId)
						BEGIN
							SELECT * FROM #BaseInfo WHERE ParId = @ParId ORDER BY UserCode
						END
					ELSE			 --下一层(用传来的@TypeID直接去匹配表中的ParId)
						BEGIN			
							IF @SonNum = 0
								SELECT * FROM #BaseInfo WHERE SonNum = 0 AND TypeId = @TypeId ORDER BY UserCode
							ELSE
								SELECT * FROM #BaseInfo WHERE ParId = @TypeId ORDER BY UserCode		
						END
					
			END
			ELSE
			BEGIN
				DECLARE @FilterSQL VARCHAR(max)=''
				SET @FilterSQL = '
						SELECT * FROM #BaseInfo
						WHERE	SonNum = 0 
								AND (UserCode LIKE ''%'+@Filter+'%'' OR FullName LIKE ''%'+@Filter+'%'' OR PyCode LIKE ''%'+@Filter+'%'')'
				EXEC(@FilterSQL)
			END
			DROP TABLE #BaseInfo	
	END
----------------------------------------------------默认仓库Selector--根据分支机构出树形的仓库-结束-------------------------------------------------------

	
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DelBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DelBill]
GO














/****** Object:  Stored PROCEDURE dbo.Web_DelBill    Script Date: 2002-6-20 10:14:54 ******/
/*
  -1 : 没有这张单据
  -2 : 本张单据已做过月结存，不允许修改或删除！
  -3 : 本张单据是红冲单据，不允许修改或删除！

  作者：谢吉康
  日期：2004-09-23
  描述：在Gp_Zc_RedWord增加了新的参数，所以本地需要增加
*/
CREATE   PROCEDURE Web_DelBill 
( 
	@nBillId [NUMERIC](10, 0),					-- 1. 单据编号Id
	@EtypeID        	varchar(30) = '00001',	-- 2. 红冲单据的操作员ID
	@strPTypeIDOutPut	varchar(50) output		-- 3. 返回出错商品 ID 值
)
--@encode$--
AS
SET NOCOUNT ON
-- 是否存在单据
IF NOT EXISTS(SELECT * FROM billindex WHERE ifcheck='t' AND billnumberid=@nBillId)
	BEGIN 
		--RAISERROR('本张单据不存在！',16,1) 
	 	RETURN -1
	END

-- 判断时间是否是本期的
DECLARE @BeginDate DATETIME
DECLARE @szPeriod  VARCHAR(20)
DECLARE @BillDate  DATETIME
DECLARE @redword   INT
DECLARE @BillCode  VARCHAR(200)

EXEC Gp_GetSubValue 'period',@szPeriod out
SELECT @BeginDate=startdate FROM monthproc WHERE period=@szPeriod
SELECT @BillDate=BillDate,@redword=redword,@BillCode=BillCode FROM billindex WHERE ifcheck='t' AND billnumberid=@nBillId

IF @BillDate<@BeginDate 
	BEGIN 
		--RAISERROR('本张单据已做过月结存，不允许修改或删除！',16,1) 
	 	RETURN -2
	END

IF @redword <> 0 
	BEGIN 
		--RAISERROR('本张单据是红冲单据，不允许修改或删除！',16,1) 
	 	RETURN -3
	END

-- 执行红冲
DECLARE @ret INT
EXEC @ret=Gp_Zc_RedWord @nBillId,@ETypeId,@strPTypeIDOutPut
IF @ret<>0
	BEGIN 
		--RAISERROR('反向过帐不成功！',16,1) 
		RETURN -4
	END
-- 删除两张单据
IF EXISTS(SELECT * FROM billindex WHERE redword=2 AND billcode=@BillCode)
	DELETE FROM billindex WHERE billcode=@BillCode AND ifcheck='t'
IF @@ROWCOUNT <> 2
	BEGIN 
		--RAISERROR('删除单据不成功！',16,1) 
		RETURN -5
	END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DeleteOtherInOutType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DeleteOtherInOutType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2010-07-28
	描述：删除业务类别
*/
CREATE PROCEDURE Web_DeleteOtherInOutType
(
	@TypeId					int
)
--@encode$--
AS
SET NOCOUNT ON

		IF EXISTS(SELECT TOP 1 1 FROM BillIndex WHERE OtherInOutType = @TypeId)
			RETURN -1
		DELETE FROM OtherInOutType WHERE ID = @TypeId

RETURN 0
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DelLendBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DelLendBill]
GO















/*
  删除借欠单据
  -1 : 没有这张单据
*/
CREATE   PROCEDURE Web_DelLendBill
( @nBillId [numeric](10, 0),
 @nBillType VARCHAR(10) 
)
--@encode$--
AS
SET NOCOUNT ON
-- 是否存在单据
if not Exists(Select * from lendindex where billnumberid=@nBillId)
begin 
 --RAISERROR('本张单据不存在！',16,1) 
 return -1
end
else
BEGIN

	IF EXISTS(SELECT TOP 1 1 FROM dbo.LendIndex WHERE BillNumberId=@nBillID AND BillType=@nBillType AND ifcheck='t' AND draft=0
			  UNION ALL 
			  SELECT TOP 1 1 FROM dbo.ListTable WHERE BillNumberId=@nBillId AND BillType=@nBillType
			  UNION ALL
			  SELECT TOP 1 1 FROM dbo.InOutstocktable WHERE BillNumberId=@nBillId AND BillType=@nBillType)
		RETURN -2
		
	DELETE from lendindex where billnumberid= @nBillId
	DELETE from lendbill where billnumberid= @nBillId
	DELETE FROM Gp_InOutPTypeSerial WHERE BillNumberId=@nBillId AND BillType IN (71,72,87,88)
	  --删除打印记录
	DELETE FROM dbo.PrintRecord WHERE BillNumberId = @nBillId AND BillType = @nBillType
	   --删除增加的打印次数记录
	DELETE FROM dbo.PrintRecord WHERE BillNumberId = @nBillId AND BillType = @nBillType

end














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DelOnShelvesBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DelOnShelvesBill]
GO




/*
	作者：舒珊
	日期：2016-07-04
	描述：批量删除上架单草稿 直接删单
*/
CREATE    PROCEDURE Web_DelOnShelvesBill
(
	@BillNumberId  numeric(18,0)
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM onShelvespickIndex WHERE ifcheck='t' and [BillNumberId]  = @BillNumberId)
	RETURN -1

ELSE
	BEGIN
	-------------------------------草稿不在更改引用状态-------------------------------------------------------------
		CREATE TABLE #InStockBill( InStockNumId Numeric(10,0))
		
		insert into  #InStockBill( InStockNumId)
		select bix.billNumberID
		from billindex bix
		inner join onShelvesbill osb on osb.GoodsBillNumberID=bix.billnumberid
		inner join onShelvespickIndex ox on ox.BillNumberId=osb.BILLNUMBERID
		where ox.billnumberid=@BillNumberId
		--对应多个出库单
		
------------------------------------------------------入库单--------------------------------------------------
		
		--其它上架单未引用 回写 入库单未引用，未开单
		
		--删除被其他上架单引用的出库单 状态不改变
		delete from #InStockBill where InStockNumId in(
			select isb.InStockNumId 
			from #InStockBill isb
			inner join onShelvesbill osb on osb.GoodsBillNumberID=isb.InStockNumId
			where osb.billnumberid<>@BillNumberId
		)
	
		--update billindex 
		--set ShelveRefState=0,ShelveState=0
		--from billindex bix inner join #InStockBill isb on isb.InStockNumId=bix.billnumberid
		
		--只回写引用状态
		update billindex 
		set ShelveRefState=0
		from billindex bix inner join #InStockBill isb on isb.InStockNumId=bix.billnumberid
		

---------------------------------------------------------删除草稿--------------------------------------------------
		
		--删除表明细
		delete onShelvesbill where billnumberid=@BillNumberId 
		
		--删除表头	
		delete onShelvespickIndex  where billnumberid=@BillNumberId and  ifcheck = 'f'
		
		DROP TABLE #InStockBill
		
		IF @@error <> 0 
			RETURN -2
		ELSE 
			RETURN 0
			

	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DelPickBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DelPickBill]
GO




/*
	作者：舒珊
	日期：2016-07-04
	描述：批量删除拣货单草稿 直接删单
*/
CREATE    PROCEDURE Web_DelPickBill
(
	@BillNumberId  numeric(18,0)
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM onShelvespickIndex WHERE ifcheck='t' and [BillNumberId]  = @BillNumberId)
	RETURN -1

ELSE
	BEGIN
		CREATE TABLE #OutStockBill( OutStockNumId Numeric(10,0))
		
		insert into  #OutStockBill( OutStockNumId)
		select bix.billnumberid
		from billindex bix
		inner join pickbill pb on pb.GoodsBillNumberID=bix.billnumberid
		where pb.billnumberid=@BillNumberId
		--对应多个出库单
		
------------------------------------------------------出库单--------------------------------------------------
		
		--删除被其他拣货单引用的出库单 状态不改变
		delete from #OutStockBill where OutStockNumId in(
			select osb.OutStockNumId 
			from #OutStockBill osb
			inner join pickbill pb on pb.GoodsBillNumberID=osb.OutStockNumId
			where pb.billnumberid<>@BillNumberId
		)

		--其它拣货单未引用 回写 出库单未引用，只回写引用状态
		update billindex 
		set citestate=0
		from billindex bix inner join #OutStockBill osb on osb.OutStockNumId=bix.billnumberid
		

---------------------------------------------------------删除草稿--------------------------------------------------
		
		--删除表明细
		delete pickbill where billnumberid=@BillNumberId 
		
		--删除表头	
		delete onShelvespickIndex  where billnumberid=@BillNumberId and  ifcheck = 'f'
		
		DROP TABLE #OutStockBill
		
		IF @@error <> 0 
			RETURN -2
		ELSE 
			RETURN 0
			

	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DelRepairEngageBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DelRepairEngageBill]
GO





/*
  -1 : 没有这张单据
  -2 : 本张单据已经调入维修受理单，不能删除
*/
CREATE     PROCEDURE Web_DelRepairEngageBill 
( 
	@nBillId [NUMERIC](10, 0)
)
--@encode$--
AS
SET NOCOUNT ON
-- 是否存在单据
IF NOT EXISTS(SELECT * FROM RepairEngage WHERE  billnumberid=@nBillId)
	BEGIN 
		--RAISERROR('本张单据不存在！',16,1) 
	 	RETURN -1
	END

/*
IF exists (SELECT * FROM Repairdeal where EngageBillID =@nBillId )
	BEGIN
		--如果受进单被红冲，那么原来的接件单可以被删除  chen_qihua 2004-08-23
		--IF exists(select * from billindex where billnumberid in (select billnumberid from Repairdeal where EngageBillID =@nBillId ))
		IF exists(select * from billindex where billnumberid in (select billnumberid from Repairdeal where EngageBillID =@nBillId  AND BillNumberID not in(Select BillnumberID From BillIndex where redword<>0)))
			BEGIN				
				RETURN -2
			END
	END
*/

IF EXISTS(SELECT TOP 1 1 FROM Repairdeal WHERE EngageBillId = @nBillId)
	RETURN -2
	

IF EXISTS (SELECT * FROM RepairEngage WHERE  billnumberid=@nBillId)
	DELETE FROM RepairEngage where billnumberid=@nBillId













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DelStockTransportBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DelStockTransportBill]
GO




/*
	作者：舒珊
	日期：2016-07-04
	描述：批量删除运输配送单草稿 直接删单
*/ 
CREATE    PROCEDURE Web_DelStockTransportBill
(
	@BillNumberId  numeric(18,0)
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT TOP 1 1 FROM billindex WHERE ifcheck='t' and [BillNumberId]  = @BillNumberId)
	RETURN -1 

ELSE
	BEGIN
		--出库单
		--CREATE TABLE #OutStockBill( OutStockNumId Numeric(10,0))
		--insert into  #OutStockBill( OutStockNumId)
		--select bix.billNumberID
		--from billindex bix
		--inner join pickbill pb on bix.BillNumberId=pb.GoodsBillNumberID
		--inner join Transportbill tb on tb.GoodsBillID=pb.ID and tb.GoodsBillNumberID=pb.BillNumberID
		--where tb.billnumberid=@BillNumberId
		
		--拣货单
		CREATE TABLE #PickBill(PickNumId Numeric(10,0),ID int,GoodsBillNumberID [numeric](10, 0))
		insert into #PickBill(PickNumId,ID,GoodsBillNumberID)
		select pb.BillNumberID,pb.id,pb.GoodsBillNumberID
		from PickBill pb
		inner join Transportbill tb on tb.GoodsBillNumberID=pb.BillNumberID and tb.GoodsBillID=pb.ID 
		where tb.billnumberid=@BillNumberId
		
		
------------------------------------------------------配送单 拣货单----------------------------------------------------------------------------------------------

	--更新只有该配送单引用的拣货单,设置为 未引用
	
	update onShelvespickIndex set citestate=0  
	from onShelvespickIndex osb,
	(  select PickNumId from  #PickBill where PickNumId not in
		(select PickNumId from #PickBill pb 
			inner join Transportbill tb on tb.GoodsBillNumberID=pb.PickNumId and tb.GoodsBillID=pb.ID 
			where tb.billnumberid<>@BillNumberId)
	)pb where osb.billnumberid=pb.PickNumId and osb.citestate=1 
	
	
	--更新出库单
	--Declare @OutStockNumId Numeric(10,0)
	--Declare @citestate int=0
	--DECLARE  OutStock_Cursor Cursor FOR select OutStockNumId from #OutStockBill
	--OPEN OutStock_Cursor            --打开游标
        
	--FETCH NEXT FROM OutStock_Cursor INTO @OutStockNumId

	--WHILE @@FETCH_STATUS = 0    --循环写入变量
	--	begin
	--		select  @citestate=citestate from billindex where billnumberid=@OutStockNumId and progressstate=3
			
	--		--如果是 拣货引用状态 citestate =2 已完成，则发运中更新为 progressstate=2已出库 
			
	--		if @citestate=2
	--			update billindex set progressstate=2 where  billnumberid=@OutStockNumId and progressstate=3
		
	--		--如果是 拣货引用状态 citestate =1 已引用未完成，则发运中更新为 progressstate=1拣货中
	--		else if @citestate=1
	--			update billindex set progressstate=1 where  billnumberid=@OutStockNumId and progressstate=3
			
	--		FETCH NEXT FROM OutStock_Cursor INTO @OutStockNumId    
	--		IF @@ERROR <> 0     --错误处理
	--			BEGIN
	--				CLOSE OutStock_Cursor
	--				DEALLOCATE OutStock_Cursor                                
	--			END 
	--	END
	
	--CLOSE OutStock_Cursor            --关闭游标
	--DEALLOCATE OutStock_Cursor        --释放游标资源
	
---------------------------------------------------------删除草稿----------------------------------------------------------------------------------------------
		
		--删除表明细
		delete Transportbill where billnumberid=@BillNumberId 
		
		--删除表头	
		delete billindex  where billnumberid=@BillNumberId and  ifcheck = 'f'
		
		--DROP TABLE #OutStockBill,#PickBill
		DROP TABLE #PickBill
		
		IF @@error <> 0 
			RETURN -2 
		ELSE 
			RETURN 0
			

	END
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[web_DepartGainReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[web_DepartGainReport]
GO



/*
	--作者：徐辉
	--时间：v4.1 2009-01-15
	--功能：部门损益表

	--修改记录#01--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修科目(qp1.0)
	2013-08-14 周华 调整数据问题 
*/

CREATE                 PROCEDURE web_DepartGainReport 
(
 --@Period 		varchar(2)='',
 @stypeid		varchar(max),
 @dtypeid		varchar(max),		--部门id
 @intBpageNo 	int,
 @OperatorID	varchar(50),
 @Flag	INT,
 @startdate     DATETIME='',
 @enddate       DATETIME=''
)
--@encode$--
AS
set nocount on

DECLARE @ALL_INCOME_ID varchar(50),       
   	@ALL_EXPENSE_ID varchar(50)   
SELECT @ALL_INCOME_ID='00003' --          【收入类】
SELECT @ALL_EXPENSE_ID='00004'--          【支出类】

--DECLARE @begindate datetime,@enddate datetime
/*IF @Period = ''
	SELECT @begindate=startdate,@enddate=GETDATE() FROM monthproc WHERE monthno like '本期'
ELSE
	SELECT @begindate=startdate,@enddate=EndDate FROM monthproc WHERE period=@Period */

CREATE TABLE #Stype (TypeID varchar(50))
IF @STypeID=''
	INSERT INTO #Stype(typeid)  SELECT typeid FROM F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  SELECT a.typeid FROM F_BaseGetManDetailSType(@OperatorID) a, (SELECT * FROM  dbo.f_split(@StypeID,',')) b WHERE left(a.typeid,len(b.a))=b.a

--部门权限表
CREATE TABLE #dtype (TypeID varchar(50), usercode VARCHAR(500),fullname VARCHAR(500))
IF @DTypeID=''
	INSERT INTO #dtype(typeid,usercode,fullname)  SELECT typeid,usercode,fullname FROM F_BaseGetManDType(@OperatorID) WHERE sonnum=0 AND typeid<>'00000'
ELSE
	INSERT INTO #dtype(typeid,usercode,fullname)  SELECT typeid,usercode,fullname FROM F_BaseGetManDType(@OperatorID) a, (SELECT * FROM  dbo.f_split(@DTypeID,',')) b WHERE left(a.typeid,len(b.a))=b.a AND a.sonnum=0  AND a.typeid<>'00000'
	
--管辖费用、管辖其他收入	
CREATE TABLE #DetailATypeSr (nid varchar(50))
CREATE TABLE #DetailATypeFy (nid varchar(50))

--INSERT INTO #DetailATypeSr select a.nid AS nid from F_BaseGetManDetailATypeSr(@OperatorID) a
--INSERT INTO #DetailATypeFy select a.nid AS nid from F_BaseGetManDetailATypeFy(@OperatorID) a

INSERT INTO #DetailATypeSr select a.nid AS nid from dbo.F_TreeIncomeC(@OperatorID) a
INSERT INTO #DetailATypeFy select a.nid AS nid from /*dbo.F_TreeExpense*/dbo.F_TreeExpenseC(@OperatorID) a
		
SELECT 
	n.nTypeId AS atypeId,
	n.DtypeId,
	SUM(n.total) AS total
INTO
	#ListtableBq
FROM
	(
		--SELECT 
		--	l.BillDate,ac.nTypeId,l.total,l.DtypeId
		--FROM
		--	listtable l
		--INNER JOIN dbo.Ac_Items ac ON l.AtypeId=ac.nId
		--LEFT JOIN 
		--	BillIndex b ON l.billnumberId = b.billnumberId
		--WHERE 
		--	ac.TypeName IN('G','E')
		--	AND l.DTypeID IN(SELECT typeid FROM #dtype)
		--	AND	l.STypeID IN(SELECT typeid FROM #Stype)
		--	AND l.BillDate BETWEEN @startdate AND @enddate
		--	AND b.ifYearBill=0	 --年节存标志
		
		SELECT 
			l.BillDate,ac.nTypeId,l.total,l.DtypeId
		FROM
			listtable l
		INNER JOIN dbo.Ac_Items ac ON l.AtypeId=CAST(ac.nId AS VARCHAR)
		LEFT JOIN 
		(
			SELECT BillNumberId,BillType,ifYearBill FROM BillIndex 
			UNION ALL
			SELECT BillNumberId,BillType,ifYearBill FROM ReceiptBillIndex
			UNION ALL
			SELECT BillNumberId,BillType,ifYearBill FROM dbo.Coupon_BillIndex
		) AS b ON l.billnumberId = b.billnumberId AND l.BillType = b.BillType
		WHERE 
			ac.TypeName IN('G','E')
			AND l.DTypeID IN(SELECT typeid FROM #dtype)
			AND	l.STypeID IN(SELECT typeid FROM #Stype)
			AND l.BillDate BETWEEN @startdate AND @enddate
			AND l.BillType NOT IN(214,78)
			AND b.ifYearBill=0	 --年节存标志
		UNION ALL 
		SELECT CBN.BillDate,(SELECT TOP 1 nTypeId FROM Ac_Items WHERE FullName = '业务提成') AS nTypeId,
		ISNULL(CBND.CommissionTotal,0) AS Total,CBND.DtypeId 
		FROM CommissionBillNew AS CBN
		INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
		WHERE CBN.ifcheck = 't'
			AND CBN.BillDate BETWEEN @startdate AND @enddate
			AND CBND.DTypeID IN(SELECT typeid FROM #dtype)
			AND	CBN.STypeID IN(SELECT typeid FROM #Stype)
		UNION ALL
		SELECT b.BillDate,'000040000300002',d.Depreciation,d.DTypeId 
		FROM dbo.DepBill d INNER JOIN dbo.BillIndex b ON b.BillNumberId = d.BillNumberId 
		WHERE 
			--ac.TypeName IN('G','E')
			d.DTypeID IN(SELECT typeid FROM #dtype)
			AND	b.STypeID IN(SELECT typeid FROM #Stype)
			AND b.BillDate BETWEEN @startdate AND @enddate
			AND b.ifYearBill=0
			AND b.RedWord = 0
			AND b.BillType = 214
			AND b.ifcheck = 't'
		UNION ALL
		SELECT b.BillDate,'000040000300002',d.Total,d.DTypeId 
		FROM dbo.MoneyBill d INNER JOIN dbo.BillIndex b ON b.BillNumberId = d.BillNumberId 
		WHERE 
			--ac.TypeName IN('G','E')
			d.DTypeID IN(SELECT typeid FROM #dtype)
			AND	b.STypeID IN(SELECT typeid FROM #Stype)
			AND b.BillDate BETWEEN @startdate AND @enddate
			AND b.ifYearBill=0
			AND b.RedWord = 0
			AND b.BillType = 78
			AND b.ifcheck = 't'
        --Union all
		--SELECT a.BillDate,(SELECT TOP 1 nTypeId FROM Ac_Items WHERE FullName = '业务提成') AS nTypeId,
		--ISNULL(a.TotalMoney,0) AS Total,a.DtypeId 
		--FROM dbo.ReceiptBillIndex AS a 
		--WHERE BillType = 405 
		--	AND Draft = 0 
		--	AND ifYearBill = 0 
		--	AND RedWord = 0 
		--	AND ifcheck = 1
		--	AND BillDate BETWEEN @startdate AND @enddate
		--	AND DTypeID IN(SELECT typeid FROM #dtype)
		--	AND	STypeID IN(SELECT typeid FROM #Stype)
	) AS n
GROUP BY n.nTypeId,n.DtypeId

--SELECT * FROM #ListtableBq
--查询period会计区间期末金额
--period会计区间发生额
SELECT 
	n.nTypeId AS atypeId,
	n.DtypeId,
	SUM(n.total) AS total
INTO
	#ListtableQm
FROM
	(
	SELECT 
		l.BillDate,ac.ntypeid,l.total,l.DtypeId
	FROM
		listtable l
	INNER JOIN dbo.Ac_Items ac ON l.AtypeId=ac.nId
	LEFT JOIN 
	(
		SELECT BillNumberId,BillType,ifYearBill FROM BillIndex
		UNION ALL
		SELECT BillNumberId,BillType,ifYearBill FROM ReceiptBillIndex
		UNION ALL
		SELECT BillNumberId,BillType,ifYearBill FROM dbo.Coupon_BillIndex
	) AS b ON l.billnumberId = b.billnumberId AND l.BillType = b.BillType
	WHERE 
		ac.TypeName IN('G','E')
		AND l.DTypeID IN(SELECT typeid FROM #dtype)
		AND	l.STypeID IN(SELECT typeid FROM #Stype)
		AND l.BillDate<=@enddate
		AND b.ifYearBill=0 --年节存标志
		AND l.BillType NOT IN (214,78)	 
	UNION ALL 
	SELECT CBN.BillDate,(SELECT TOP 1 nTypeId FROM Ac_Items WHERE FullName = '业务提成') AS nTypeId,
	ISNULL(CBND.CommissionTotal,0) AS Total,CBND.DtypeId 
	FROM CommissionBillNew AS CBN
	INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
	WHERE CBN.ifcheck = 't'
		AND CBN.BillDate <= @enddate
		AND CBND.DTypeID IN(SELECT typeid FROM #dtype)
		AND	CBN.STypeID IN(SELECT typeid FROM #Stype)
	UNION ALL
		SELECT b.BillDate,'000040000300002',d.Depreciation,d.DTypeId 
		FROM dbo.DepBill d INNER JOIN dbo.BillIndex b ON b.BillNumberId = d.BillNumberId 
        --INNER JOIN dbo.Ac_Items ac ON l.AtypeId=ac.nId
		WHERE 
			--ac.TypeName IN('G','E')
		    d.DTypeID IN(SELECT typeid FROM #dtype)
			AND	b.STypeID IN(SELECT typeid FROM #Stype)
			AND b.BillDate <=@enddate
			AND b.ifYearBill=0
			AND b.RedWord = 0
			AND b.BillType = 214 
			AND b.ifcheck = 't'
	UNION ALL
		SELECT b.BillDate,'000040000300002',d.total,d.DTypeId 
		FROM dbo.MoneyBill d INNER JOIN dbo.BillIndex b ON b.BillNumberId = d.BillNumberId 
		WHERE 
			--ac.TypeName IN('G','E')
			d.DTypeID IN(SELECT typeid FROM #dtype)
			AND	b.STypeID IN(SELECT typeid FROM #Stype)
			AND b.BillDate <= @enddate
			AND b.ifYearBill=0
			AND b.BillType = 78
			AND b.RedWord = 0
			AND b.ifcheck = 't'
	--UNION ALL
	--SELECT a.BillDate,(SELECT TOP 1 nTypeId FROM Ac_Items WHERE FullName = '业务提成') AS nTypeId,
	--ISNULL(a.TotalMoney,0) AS Total,a.DtypeId 
	--FROM dbo.ReceiptBillIndex AS a 
	----INNER JOIN dbo.ReceiptBill AS b ON(a.BillNumberID = b.BillNumberID)
	--WHERE BillType = 405 
	--	AND Draft = 0 
	--	AND ifYearBill = 0 
	--	AND RedWord = 0 
	--	AND ifcheck = 1
	--	AND BillDate <= @enddate
	--	AND DTypeID IN(SELECT typeid FROM #dtype)
	--	AND	STypeID IN(SELECT typeid FROM #Stype)
	) AS n
GROUP BY n.nTypeId,n.DtypeId
--****************************************************************************--

--得到科目，部门本期，期末数据
SELECT 
	a.*
INTO
	#AtypeDtypeTotal
FROM
	(
	--有些期末有数据但本期没数据所以使用两个left join，在union
	SELECT
		Qm.atypeId,
		Qm.DtypeId,
		ISNULL(Qm.total,0) AS QmTotal,
		ISNULL(Bq.total,0) AS BqTotal
	FROM
		#ListtableQm Qm
	LEFT JOIN
		#ListtableBq Bq ON Qm.atypeId = Bq.atypeId AND Qm.DtypeId = Bq.DtypeId
	UNION
	SELECT
		Qm.atypeId,
		Qm.DtypeId,
		ISNULL(Qm.total,0) AS QmTotal,
		ISNULL(Bq.total,0) AS BqTotal
	FROM
		#ListtableBq Bq
	LEFT JOIN
		#ListtableQm Qm ON Qm.atypeId = Bq.atypeId AND Qm.DtypeId = Bq.DtypeId
	) AS a 
	INNER JOIN dbo.Ac_Items b ON a.AtypeId=b.nTypeId
	

--删除临时表
DROP TABLE #ListtableBq, #ListtableQm, #Stype

--生成结果表
CREATE TABLE #Department
(
	typeId 	varchar(50),
	usercode	varchar(300),
	fullname	varchar(300),
	leveal		int,
	sonnum		int,
	parid		varchar(50),
	[期末金额合计|]	 NUMERIC(24, 10) ,
	[本期发生额合计|]	 NUMERIC(24, 10) 
)

DECLARE @typeId 	varchar(100),
	@usercode	varchar(300),
	@fullname	varchar(300),
	@leveal		varchar(5),
	@sonnum		varchar(5),
	@parid		varchar(50),
	@cursorSql	varchar(1000)

DECLARE @proinfo varchar(5)
SELECT @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'



--SELECT nTypeId AS typeid,UserCode,FullName,Leveal,SonNum,nParId AS parid
--INTO #atype 
--FROM dbo.Ac_Items 
--WHERE (LEFT(ntypeid,5)=@ALL_INCOME_ID or LEFT(ntypeid,5)=@ALL_EXPENSE_ID)

SELECT nTypeId AS typeid,UserCode,FullName,Leveal,SonNum,nParId AS parid
INTO #atype 
FROM 
	(
	SELECT nTypeId ,UserCode,FullName,Leveal,SonNum,nParId
	FROM dbo.Ac_Items A
	INNER JOIN #DetailATypeSr SR ON A.nID=SR.nid 
	UNION ALL
	SELECT nTypeId ,UserCode,FullName,Leveal,SonNum,nParId
	FROM dbo.Ac_Items B
	INNER JOIN #DetailATypeFy fy ON B.nID=fy.nid 
	) t
WHERE (LEFT(ntypeid,5)=@ALL_INCOME_ID or LEFT(ntypeid,5)=@ALL_EXPENSE_ID)


--IF @proinfo='3' --汽配版本
--	DELETE FROM #Atype WHERE 
--	typeid IN('000030000200007','000040000200004')-- 去掉借转采购结算与成本差‘商品送修	科目
--ELSE
--	DELETE FROM #Atype WHERE 
--	typeid = '000030000200007'-- 去掉         借转采购结算与成本差 科目

--插入支出收入科目
DECLARE cursor_atype CURSOR
FOR
SELECT typeId,usercode,fullname,leveal,sonnum,parid FROM #atype ORDER BY typeid


OPEN cursor_atype

FETCH NEXT FROM cursor_atype
INTO @typeId,@usercode,@fullname,@leveal,@sonnum,@parid


WHILE @@FETCH_STATUS = 0
BEGIN
	SET @cursorSql='
			INSERT INTO 
			#Department (typeId,usercode,fullname,leveal,sonnum,parid) 
			VALUES('''+@typeId+''','''+@usercode+''','''+@fullname+''','+@leveal+','+@sonnum+','''+@parid+''')'
	EXEC(@cursorSql)
	FETCH NEXT FROM cursor_atype INTO @typeId,@usercode,@fullname,@leveal,@sonnum,@parid
END

CLOSE cursor_atype
DEALLOCATE cursor_atype

DECLARE @Sum_SQL varchar(8000)
SET @Sum_SQL = ''

;WITH c1 AS (
SELECT * FROM #Department a LEFT JOIN #AtypeDtypeTotal b ON a.typeid=b.atypeId
),c2 AS (
	SELECT typeid,(SELECT ISNULL(SUM(qmtotal),0) FROM c1 b WHERE b.typeid LIKE a.typeid+'%' ) AS qmtotal
	,(SELECT ISNULL(SUM(BqTotal),0) FROM c1 b WHERE b.typeid LIKE a.typeid+'%') AS BqTotal FROM c1 a
)
UPDATE a SET [期末金额合计|]= b.qmtotal
,[本期发生额合计|]=b.BqTotal
FROM #Department a JOIN c2 b ON a.typeid=b.typeid



--更新合计期末，本期金额
--UPDATE #Department  SET [期末金额合计|]=(SELECT ISNULL(SUM(QmTotal),0) FROM #AtypeDtypeTotal WHERE  LEFT(AtypeId,LEN(#Department.typeId))=#Department.typeId)
--UPDATE #Department  SET [本期发生额合计|]=(SELECT ISNULL(SUM(BqTotal),0) FROM #AtypeDtypeTotal WHERE  LEFT(AtypeId,LEN(#Department.typeId))=#Department.typeId)

EXEC('INSERT INTO #DepartMent(typeid,usercode,fullname,leveal,sonnum,parid)
SELECT ''0000500004'' as typeid,''3131'' as usercode,''利润'' as fullname,1 as leveal,1 as sonnum,''00005'' as parid')


SET @Sum_SQL=' [期末金额合计|]=(select SUM(case when typeid=''00003'' then [期末金额合计|] else -[期末金额合计|] end) '
EXEC ('UPDATE  #Department SET '+@Sum_SQL+' FROM #Department  where typeid in (''00003'',''00004'')) where typeid =''0000500004''')
SET @Sum_SQL=' [本期发生额合计|]=(select SUM(case when typeid=''00003'' then [本期发生额合计|] else -[本期发生额合计|] end)'
EXEC ('UPDATE  #Department SET '+@Sum_SQL+' FROM #Department  where typeid in (''00003'',''00004'')) where typeid =''0000500004''')



--动态生成部门列
IF @Flag = 1 --打印全部
	SET @cursorSql='
	DECLARE cursor_department CURSOR 
	FOR
		SELECT  typeid,usercode,fullname FROM #dtype ORDER BY typeId
	'
Else
BEGIN
	SET @cursorSql='
	DECLARE cursor_department CURSOR 
	FOR
		SELECT TOP 10 typeid,usercode,fullname FROM #dtype WHERE typeId NOT IN(SELECT TOP '+CAST((@intBpageNo-1)*10 AS varchar(50))+' typeid FROM #dtype ORDER BY typeId) ORDER BY typeId
	'
END
EXEC(@cursorSql)



OPEN cursor_department

FETCH NEXT FROM cursor_department
INTO @typeId,@usercode,@fullname

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @cursorSql='ALTER TABLE #Department ADD [期末金额'+@fullname+'|'+@typeId+']  NUMERIC(24, 10)  DEFAULT 0
			ALTER TABLE #Department ADD [本期发生额'+@fullname+'|'+@typeId+']  NUMERIC(24, 10)  DEFAULT 0'
	EXEC(@cursorSql)

	--更新列值
	--SET @cursorSql='
	--		UPDATE #Department  SET [期末金额'+@fullname+'|'+@typeId+']=(SELECT ISNULL(SUM(QmTotal),0) FROM #AtypeDtypeTotal WHERE DtypeId='''+@typeId+''' AND LEFT(AtypeId,LEN(#Department.typeId))=#Department.typeId)
	--		UPDATE #Department  SET [本期发生额'+@fullname+'|'+@typeId+']=(SELECT ISNULL(SUM(BqTotal),0) FROM #AtypeDtypeTotal WHERE DtypeId='''+@typeId+''' AND LEFT(AtypeId,LEN(#Department.typeId))=#Department.typeId)'
	SET @cursorSql='
		;WITH c1 AS (
	SELECT * FROM #Department a LEFT JOIN #AtypeDtypeTotal b ON a.typeid=b.atypeId and b.DtypeId='''+@typeId+'''
	),c2 AS (
		SELECT typeid,(SELECT ISNULL(SUM(qmtotal),0) FROM c1 b WHERE b.typeid LIKE a.typeid+''%'' ) AS qmtotal
		,(SELECT ISNULL(SUM(BqTotal),0) FROM c1 b WHERE b.typeid LIKE a.typeid+''%'') AS BqTotal FROM c1 a
	) update a set [期末金额'+@fullname+'|'+@typeId+']=b.qmtotal
	,[本期发生额'+@fullname+'|'+@typeId+']=b.BqTotal
	FROM #Department a JOIN c2 b ON a.typeid=b.typeid 
	'

	EXEC(@cursorSql)

	SET @Sum_SQL='[期末金额'+@fullname+'|'+@typeId+']=(select SUM(case when typeid=''00003'' then [期末金额'+@fullname+'|'+@typeId+'] else -[期末金额'+@fullname+'|'+@typeId+'] end)'
	EXEC ('UPDATE  #Department SET '+@Sum_SQL+' FROM #Department  where typeid in (''00003'',''00004'')) where typeid =''0000500004''')
	SET @Sum_SQL='[本期发生额'+@fullname+'|'+@typeId+']=(select SUM(case when typeid=''00003'' then [本期发生额'+@fullname+'|'+@typeId+'] else -[本期发生额'+@fullname+'|'+@typeId+'] end)'
	EXEC ('UPDATE  #Department SET '+@Sum_SQL+' FROM #Department  where typeid in (''00003'',''00004'')) where typeid =''0000500004''')

	FETCH NEXT FROM cursor_department INTO @typeId,@usercode,@fullname
END

CLOSE cursor_department
DEALLOCATE cursor_department

update #Department SET fullname ='    '+fullname where LEVEAL =2
update #Department SET fullname ='        '+fullname  where  LEVEAL =3
update #Department SET fullname ='            '+fullname  where  LEVEAL =4
update #Department SET fullname ='                '+fullname  where  LEVEAL =5
update #Department SET fullname ='                    '+fullname  where  LEVEAL =6
update #Department SET fullname ='                        '+fullname  where  LEVEAL =7
update #Department SET fullname ='                            '+fullname  where  LEVEAL =8
update #Department SET fullname ='                                '+fullname  where  LEVEAL =9
update #Department SET fullname ='                                    '+fullname  where  LEVEAL =10


SELECT * FROM #Department

--删除临时表
DROP TABLE #AtypeDtypeTotal
DROP TABLE #Department
DROP TABLE #atype
DROP TABLE #dtype



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DepartGainReportMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DepartGainReportMonth]
GO

/*
	作者:武智均
	日期:2019-09-06
	描述:部门收支表按月比较
*/

CREATE   PROCEDURE Web_DepartGainReportMonth
(
	@OperatorID	VARCHAR(50),		--操作员ID
	@StypeId	VARCHAR(max),		--分支机构id
	@DtypeId	VARCHAR(max)		--部门id
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(MAX),
		@ALL_INCOME_ID varchar(50) ='00003', --【收入类】      
		@ALL_EXPENSE_ID varchar(50)='00004' -- 【支出类】         

-- 分支机构 - 月结开始时间和结束时间
CREATE TABLE #Stype (TypeID varchar(50))

-- 月结
CREATE TABLE #Months
(	
	StartDate	DATETIME,
	EndDate		DATETIME,
	MonthNo		VARCHAR(200),
	Period		VARCHAR(200)
)

-- 临时存放结果集
CREATE TABLE #TEMP (
	USERCODE VARCHAR(200),
	FULLNAME VARCHAR(200),
	LEVEAL INT,
	NTYPEID VARCHAR(200),
	NPARID VARCHAR(200),
	SONNUM VARCHAR(200),
	MONTHNO VARCHAR(200),
	TOTAL NUMERIC(24, 10),
	CURRENTTOTAL NUMERIC(24, 10)
)

-- 部门权限表
CREATE TABLE #Dtype (TypeID varchar(50), usercode VARCHAR(500),fullname VARCHAR(500))

-- INSERT INTO #Dtype
IF @DTypeID=''
	INSERT INTO #dtype(typeid,usercode,fullname)  
	SELECT typeid,usercode,fullname FROM F_BaseGetManDType(@OperatorID) WHERE sonnum=0 AND typeid<>'00000'
ELSE
	INSERT INTO #dtype(typeid,usercode,fullname)  
	SELECT typeid,usercode,fullname FROM F_BaseGetManDType(@OperatorID) a, 
	(SELECT * FROM  dbo.f_split(@DTypeID,',')) b 
	WHERE left(a.typeid,len(b.a))=b.a AND a.sonnum=0  AND a.typeid<>'00000'
	
-- INSERT INTO #Stype	
INSERT INTO #Stype(TypeID)
SELECT TypeId FROM dbo.F_BaseGetAllManagerBaseTypeId(@StypeId,11,@OperatorID)

IF NOT EXISTS (SELECT TOP 1 1 fROM #Stype)
BEGIN
	RETURN -1
END

-- INSERT INTO #Months
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'stypeindependentopen' AND SubValue = 1)  -- 启用分支机构独立
	 INSERT INTO #Months
	 SELECT StartDate,EndDate,MonthNo,Period 
	 FROM 
		(SELECT MonthNo,StartDate, EndDate,Period,STypeID from monthproc
		 INNER JOIN #Stype S on STypeID=S.TypeID )M 
	 GROUP BY StartDate,EndDate,MonthNo,Period 
	 ORDER BY Period
ELSE
	 INSERT INTO #Months
	 SELECT StartDate,EndDate,MonthNo,Period
	 FROM MonthProc
	 WHERE STypeID IN 
		 (SELECT TOP 1 s1.typeid FROM #Stype s1 
		 INNER JOIN stype s ON s1.TypeID=s.TypeID WHERE s.sonnum=0 )
	 ORDER BY period

UPDATE #Months SET EndDate = '2099-01-01'  WHERE EndDate IS NULL


INSERT INTO #TEMP
SELECT	A.UserCode,
		A.FullName,
		A.Leveal,
		A.NTypeId,
		A.NParId,
		A.SonNum,
		tmp.MonthNo,
		SUM(ISNULL(tmp.Total,0))Total,
		SUM(ISNULL(tmp.CurrentTotal,0))CurrentTotal
FROM Ac_Items A
LEFT JOIN (
	SELECT	A1.nTypeId,
			L.MonthNo,
			0 TOTAL, 
			SUM(ISNULL(L.Total,0)) CurrentTotal
	FROM Ac_Items A1
	LEFT JOIN (SELECT	B.MonthNo,
						LT.Total,
						LT.AtypeId,
						LT.CID,
						LT.STypeID
				FROM ListTable LT
				INNER JOIN #Stype s on s.TypeID=LT.STypeID
				INNER JOIN #Dtype d on d.TypeID=LT.DTypeID
				LEFT JOIN #Months B on LT.BillDate BETWEEN B.StartDate AND B.EndDate
				LEFT JOIN AType_Total AT ON AT.CID = LT.CID AND AT.STypeID = LT.STypeID AND AT.ATypeID = LT.AtypeId
				WHERE LT.BillType NOT IN(214,78) 
				) L ON L.AtypeId = A1.nId
	WHERE  A1.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A1.nTypeId LIKE @ALL_EXPENSE_ID+'%'
	GROUP BY A1.nTypeId,L.MonthNo
	UNION ALL
	SELECT	A1.nTypeId,
			L.MonthNo,
			SUM(ISNULL(L.Total,0)) TOTAL, 
			0 CurrentTotal
	FROM Ac_Items A1
	LEFT JOIN (SELECT	B.MonthNo,
						LT.Total,
						LT.AtypeId,
						LT.CID,
						LT.STypeID
				FROM ListTable LT
				INNER JOIN #Stype s on s.TypeID=LT.STypeID
				INNER JOIN #Dtype d on d.TypeID=LT.DTypeID
				LEFT JOIN #Months B on LT.BillDate <=B.EndDate
				LEFT JOIN AType_Total AT ON AT.CID = LT.CID AND AT.STypeID = LT.STypeID AND AT.ATypeID = LT.AtypeId
				WHERE LT.BillType NOT IN(214,78) 
				) L ON L.AtypeId = A1.nId
	WHERE  A1.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A1.nTypeId LIKE @ALL_EXPENSE_ID+'%'
	GROUP BY A1.nTypeId,L.MonthNo
	--查询 固定资产 
	UNION ALL
	SELECT	A1.nTypeId,
			L.MonthNo,
			0 TOTAL, 
			SUM(ISNULL(L.Total,0)) CurrentTotal
	FROM Ac_Items A1
	LEFT JOIN(SELECT	B.MonthNo,
						D.Depreciation AS total,
						LT.AtypeId,
						Lt.CID,
						Lt.Stypeid
			   FROM  DepBill D
			   INNER JOIN dbo.BillIndex bx ON bx.BillNumberId = d.BillNumberId 
			   INNER JOIN ListTable lt ON lt.billnumberid=bx.billnumberid
			   INNER JOIN #Stype s on s.TypeID=bx.STypeID
			   INNER JOIN #Dtype de on de.TypeID=D.DTypeID
			   LEFT JOIN #Months B on bx.BillDate BETWEEN B.StartDate AND B.EndDate
			   LEFT JOIN AType_Total AT ON AT.CID = LT.CID AND AT.STypeID = LT.STypeID AND AT.ATypeID = LT.AtypeId
			   WHERE bx.ifYearBill=0 AND bx.RedWord = 0 AND bx.BillType = 214 AND bx.ifcheck = 't'
	) L ON L.AtypeId = A1.nId
	WHERE  A1.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A1.nTypeId LIKE @ALL_EXPENSE_ID+'%'
	GROUP BY A1.nTypeId,L.MonthNo
	UNION ALL
	SELECT	A1.nTypeId,
			L.MonthNo,
			0 TOTAL, 
			SUM(ISNULL(L.Total,0)) CurrentTotal
	FROM Ac_Items A1
	LEFT JOIN(SELECT	B.MonthNo,
						D.total AS total,
						LT.AtypeId,
						Lt.CID,
						Lt.Stypeid
			   FROM  MoneyBill D
			   INNER JOIN dbo.BillIndex bx ON bx.BillNumberId = d.BillNumberId 
			   INNER JOIN ListTable lt ON lt.billnumberid=bx.billnumberid
			   INNER JOIN #Stype s on s.TypeID=bx.STypeID
			   INNER JOIN #Dtype de on de.TypeID=D.DTypeID
			   LEFT JOIN #Months B on bx.BillDate BETWEEN B.StartDate AND B.EndDate
			   LEFT JOIN AType_Total AT ON AT.CID = LT.CID AND AT.STypeID = LT.STypeID AND AT.ATypeID = LT.AtypeId
			   WHERE bx.ifYearBill=0 AND bx.RedWord = 0 AND bx.BillType = 78 AND bx.ifcheck = 't'
	) L ON L.AtypeId = A1.nId
	WHERE  A1.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A1.nTypeId LIKE @ALL_EXPENSE_ID+'%'
	GROUP BY A1.nTypeId,L.MonthNo
		
	UNION ALL
	SELECT	A1.nTypeId,
			L.MonthNo,
			SUM(ISNULL(L.Total,0)) TOTAL, 
			0 CurrentTotal
	FROM Ac_Items A1
	LEFT JOIN(SELECT	B.MonthNo,
						D.Depreciation AS total,
						LT.AtypeId,
						Lt.CID,
						Lt.Stypeid
			   FROM  DepBill D
			   INNER JOIN dbo.BillIndex bx ON bx.BillNumberId = d.BillNumberId 
			   INNER JOIN ListTable lt ON lt.billnumberid=bx.billnumberid
			   INNER JOIN #Stype s on s.TypeID=bx.STypeID
			   INNER JOIN #Dtype de on de.TypeID=D.DTypeID
			   LEFT JOIN #Months B on bx.BillDate <=B.EndDate
			   LEFT JOIN AType_Total AT ON AT.CID = LT.CID AND AT.STypeID = LT.STypeID AND AT.ATypeID = LT.AtypeId
			   WHERE bx.ifYearBill=0 AND bx.RedWord = 0 AND bx.BillType = 214 AND bx.ifcheck = 't'
	) L ON L.AtypeId = A1.nId
	WHERE  A1.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A1.nTypeId LIKE @ALL_EXPENSE_ID+'%'
	GROUP BY A1.nTypeId,L.MonthNo
	UNION ALL
	SELECT	A1.nTypeId,
			L.MonthNo,
			SUM(ISNULL(L.Total,0)) TOTAL, 
			0 CurrentTotal
	FROM Ac_Items A1
	LEFT JOIN(SELECT	B.MonthNo,
						D.total AS total,
						LT.AtypeId,
						Lt.CID,
						Lt.Stypeid
			   FROM  MoneyBill D
			   INNER JOIN dbo.BillIndex bx ON bx.BillNumberId = d.BillNumberId 
			   INNER JOIN ListTable lt ON lt.billnumberid=bx.billnumberid
			   INNER JOIN #Stype s on s.TypeID=bx.STypeID
			   INNER JOIN #Dtype de on de.TypeID=D.DTypeID
			   LEFT JOIN #Months B on bx.BillDate <=B.EndDate
			   LEFT JOIN AType_Total AT ON AT.CID = LT.CID AND AT.STypeID = LT.STypeID AND AT.ATypeID = LT.AtypeId
			   WHERE bx.ifYearBill=0 AND bx.RedWord = 0 AND bx.BillType = 78 AND bx.ifcheck = 't'
	) L ON L.AtypeId = A1.nId
	WHERE  A1.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A1.nTypeId LIKE @ALL_EXPENSE_ID+'%'
	GROUP BY A1.nTypeId,L.MonthNo
)tmp ON tmp.nTypeId like A.nTypeId + '%'
INNER JOIN (
		SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出）	
) opera ON opera.nTypeId=A.nTypeId
WHERE  A.ntypeId <> '00000' AND (A.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A.nTypeId LIKE @ALL_EXPENSE_ID+'%')
GROUP BY A.UserCode,A.FullName,A.Leveal,A.ntypeId,A.NParId,A.SonNum,tmp.MonthNo


--判断损益表的权限
--DECLARE @re INT 
--EXEC @re = GP_CheckLimit @OperatorID,4225
--IF @re =1	--没有查看损益表所有项目的权限
--BEGIN
--	DELETE 
--	FROM	#TEMP 
--	WHERE	NTypeId NOT IN (
--		SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
--		UNION ALL
--		SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出）	
--	)
--END

-- 修改显示格式
UPDATE #TEMP SET FullName ='    '+FullName WHERE Leveal =2
UPDATE #TEMP SET FullName ='        '+FullName WHERE Leveal =3
UPDATE #TEMP SET FullName ='            '+FullName WHERE Leveal =4
UPDATE #TEMP SET FullName ='                '+FullName WHERE Leveal =5
UPDATE #TEMP SET FullName ='                    '+FullName WHERE Leveal =6
UPDATE #TEMP SET FullName ='                        '+FullName WHERE Leveal =7
UPDATE #TEMP SET FullName ='                            '+FullName WHERE Leveal =8
UPDATE #TEMP SET FullName ='                                '+FullName WHERE Leveal =9
UPDATE #TEMP SET FullName ='                                    '+FullName WHERE Leveal =10		

		
SET @SQL = 'SELECT * FROM (SELECT A.UserCode,A.FullName,A.Leveal,A.ntypeId,A.NParId,A.SonNum' 
SELECT @SQL = @SQL + ',SUM(CASE WHEN A.MONTHNO = '''+MONTHNO+''' THEN TOTAL ELSE 0 END) ['+MonthNo + '期末金额],
					  SUM(CASE WHEN A.MONTHNO = '''+MONTHNO+''' THEN CURRENTTOTAL ELSE 0 END) ['+MonthNo+'本期发生额] ' FROM #Months
SET @SQL += 'FROM #TEMP A 
			 GROUP BY A.UserCode,A.FullName,A.Leveal,A.ntypeId,A.NParId,A.SonNum 
			 UNION ALL SELECT '''',''【利    润】'',1,''999999999999999'','''',0  '
SELECT @SQL = @SQL + ',(SELECT SUM(CASE WHEN ntypeId = ''00004'' THEN -TOTAL ELSE TOTAL END)
			 FROM #TEMP WHERE MONTHNO = '''+MONTHNO+''' AND LEVEAL = 1 ),
			 (SELECT SUM(CASE WHEN ntypeId = ''00004'' THEN -CURRENTTOTAL ELSE CURRENTTOTAL END) 
			 FROM #TEMP WHERE MONTHNO = '''+MONTHNO+''' AND LEVEAL = 1 ) ' FROM #Months
SET @SQL += ')X ORDER BY X.NTYPEID'
--print @sql
EXEC (@SQL)

DROP TABLE #TEMP,#Months,#Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DepartmentCGTJdetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DepartmentCGTJdetailQuery]
GO






-------------------------------------------------------------------------
--部门采购统计明细表
--作者：徐辉
--日期：2009-01-14
--引用：GP_CheckOperatorRight23

/*
  修改：添加批号 自由项，币种信息
  作者：彭勇
  日期：2012-05-25
*/
/*
  修改：添加批号 自由项，币种，汇率 基本计量单位 相关的原币等信息
  作者：彭勇
  日期：2012-05-27
*/
/*
  修改： 魏伟
  日期： 2016-06-06
  描述： 添加 换算率变更前采购单位数量 查询

*/

-------------------------------------------------------------------------
CREATE  PROCEDURE Web_DepartmentCGTJdetailQuery  
(
	@DTypeID			VARCHAR(50),	--要查询明细的部门Id
	@StartDate			VARCHAR(10),
	@EndDate			VARCHAR(10),
	@ETypeID			VARCHAR(1550),	--经手人
	@BTypeID			VARCHAR(1550),	--结算单位
	@dealBTypeID		VARCHAR(1550),	--往来单位
	@KTypeID			VARCHAR(1550),	--仓库
	@PTypeID			VARCHAR(1550),	--商品
	@BillType			VARCHAR(100),	--单据类型
	@StypeID			VARCHAR(max),	--分支机构
	@OperatorID 		VARCHAR(50),	--操作员ID号
	@IsReporting		INT	,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@ptypecategoryid VARCHAR(MAX) ,      -- 商品类别
	@IsShowReconciliation	BIT--是否对账信息1：显示对账过数据 0 隐藏对账过数据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL varchar(max)

IF @ETypeID = '00001' --全部经手人
	SET @ETypeID = ''
IF @KTypeID = '00000' --全部仓库
	SET @KTypeID = ''
IF @PTypeID = '00000' --全部商品
	SET @PTypeID = ''
IF @BTypeID = '00000' --全部结算单位
	SET @BTypeID = ''
IF @dealBTypeID='00000'--全部往来单位	
    SET @dealBTypeID=''

CREATE TABLE #Ptype (TypeID varchar(50),usercode varchar(200),fullname varchar(200),unit1 varchar(8))
CREATE TABLE #Btype (TypeID varchar(50),fullname varchar(200))
CREATE TABLE #dealBtype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50),fullname varchar(200))
CREATE TABLE #Ktype (TypeID varchar(50),fullname varchar(200))
CREATE TABLE #Stype (TypeID varchar(50))
--最近使用的换算率
--CREATE TABLE #Rate
--(
--	ptypeid VARCHAR(50),
--	rate numeric(24, 10),
--	unitid int
--)
--INSERT INTO #Rate
--        (unitid ,ptypeid,rate)
--SELECT   pt.UnitId ,pt.PtypeId ,TranslateRate FROM dbo.PType_TranslateRates pt INNER JOIN dbo.F_BaseGetAllManagerBaseTypeId(@PTypeID,1,@OperatorID) f ON f.TypeId=PtypeId   INNER JOIN (SELECT PtypeId,UnitId, MAX(LastUseDate)AS LastUseDate FROM PType_TranslateRates GROUP BY PtypeId,UnitId) t ON pt.PtypeId=t.PtypeId AND  pt.LastUseDate=t.LastUseDate  AND pt.UnitId=t.UnitId INNER JOIN dbo.ptype p ON p.typeId=pt.PtypeId AND pt.UnitId=p.BuyUnitId

IF @PTypeID =''
	INSERT INTO #Ptype(typeid,usercode,fullname,unit1) select typeid,usercode,fullname,unit1 from ptype where typeid in (  select typeid from dbo.F_LinePC(@OperatorID,@ptypecategoryid))
ELSE
	INSERT INTO #Ptype(typeid,usercode,fullname,unit1) select typeid,usercode,fullname,unit1 from ptype where typeid in (  select a.typeid from F_ManPTypeInCategoryID(@OperatorID,@PTypeID,@ptypecategoryid) a)

--结算单位
IF @BTypeID =''
	INSERT INTO #Btype(typeid,fullname) select typeid,fullname from btype where typeid in (  select a.typeid from F_GetManDetailBType(@OperatorID) a)
ELSE
	INSERT INTO #Btype(typeid,fullname) select typeid,fullname from btype where typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BTypeID,',')) b where left(a.typeid,len(b.a))=b.a)
--往来单位
INSERT INTO #dealBtype (TypeID) SELECT TypeID FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)

IF @ETypeID=''
	INSERT INTO #Etype(typeid,fullname) select typeid,fullname from employee where typeid in ( select typeid from F_GetManDetailEType(@OperatorID))
ELSE
	INSERT INTO #Etype(typeid,fullname) select typeid,fullname from employee where typeid in ( select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@ETypeID,',')) b where left(a.typeid,len(b.a))=b.a)

IF @KTypeID=''
BEGIN
	INSERT INTO #Ktype(typeid,fullname) select typeid,fullname from stock where typeid in ( select typeid from F_GetManDetailKType(@OperatorID))
	insert into #Ktype select '10000','代销库'
END
ELSE
	INSERT INTO #Ktype(typeid,fullname) select typeid,fullname from stock where typeid in ( select a.typeid from F_GetManDetailKType(@OperatorID) a,  (select * from  dbo.f_split(@KTypeID,',')) b where left(a.typeid,len(b.a))=b.a)

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a


CREATE TABLE #BillName  (Billtype INT)
INSERT INTO #BillName SELECT A FROM DBO.f_split(@BillType,',')

CREATE TABLE #Billnum
(
 BillNumberID         int,
 billtype             INT,
 BillDate			  datetime,
 BillCode			  varchar(200),
 btypeid			  varchar(50),
 currate			   NUMERIC(24, 10) ,
 dealBtypeId		  varchar(50),
 etypeid			  varchar(50),
 CID				  int
)

CREATE TABLE #ZGKPBillnum
(
 BillNumberID         int,
 billtype             INT,
 BillDate			  datetime,
 BillCode			  varchar(200),
 btypeid			  varchar(50),
 currate			   NUMERIC(24, 10) ,
 dealBtypeId		  varchar(50),
 etypeid			  varchar(50),
 CID				  int
)
DECLARE @SQLWHERE VARCHAR(2000)=''
SET @SQLWHERE = @SQLWHERE + '
		WHERE bil.BillDate >= '''+@StartDate+''' 
		AND bil.BillDate <= '''+@EndDate+'''
		AND bil.BillType IN ('+@BillType+')
		AND bil.ifYearBill=0 
		AND BIL.draft=0 AND BIL.ifcheck=''t'' AND BIL.RedWord=0'
IF @DTypeID = '99999' --其他部门
	SET @SQLWHERE=@SQLWHERE+'
		AND (bil.DtypeId='''' OR bil.DtypeId is null)'
ELSE
	SET @SQLWHERE=@SQLWHERE+'
		AND bil.DtypeId LIKE '''+@DTypeID+'%'''
		
DECLARE @sqltemp VARCHAR(8000)=''
SET @sqltemp ='INSERT INTO #Billnum 
SELECT BillNumberId,BillType,BillDate,BillCode,btypeid,rate,dealBtypeId,etypeid,CID	
FROM BillIndex bil			 	
INNER JOIN
#stype st ON BIL.stypeId = st.typeId
		' + @SQLWHERE
EXEC (@sqltemp)
-----------------------------------处理暂估开票单据-----------------------开始
DECLARE @sqlZGKP VARCHAR(8000)=''
SET @sqlZGKP ='INSERT INTO #ZGKPBillnum 
SELECT BillNumberId,BillType,BillDate,BillCode,btypeid,rate,dealBtypeId,etypeid,CID	
FROM ReceiptBillIndex bil			 	
INNER JOIN
#stype st ON BIL.stypeId = st.typeId
		' + @SQLWHERE
EXEC (@sqlZGKP)
-----------------------------------处理暂估开票单据-----------------------结束

CREATE TABLE #BillDetails
(
 BillNumberID         int ,
 CustomdetailID       int,
 billtype             INT,
 Ktypeid			  varchar(50),
 CargoID              INT,
 GoodsNumber		  varchar(100),
 NQty                  NUMERIC(24, 10) ,
 MQty                  NUMERIC(24, 10) ,
 Qty				   NUMERIC(24, 10) ,
 TaxTotal			   NUMERIC(24, 10) ,
 NTaxTotal			   NUMERIC(24, 10) ,
 Total	               NUMERIC(24, 10) ,
 nTotal	               NUMERIC(24, 10) ,
 TotalTax			   NUMERIC(24, 10) ,
 nTotalTax			   NUMERIC(24, 10) ,
 ptypeid			  varchar(50),
 IsCombined           INT,
 ItemID               BIGINT,
 MUnitID              INT,
 BillDate			  datetime,
 BillCode			  varchar(200),
 btypeid			  varchar(50),
 currate			   NUMERIC(24, 10) ,
 dealBtypeId		  varchar(50),
 etypeid			  varchar(50),
 CID				  INT,
 pretotal			   NUMERIC(24, 10) ,
 npretotal			   NUMERIC(24, 10) ,
 discountge			   NUMERIC(24, 10) ,
 ndiscountge		   NUMERIC(24, 10) ,
 Discount			   NUMERIC(24, 10) ,
 Tax				   NUMERIC(24, 10),
 dComment			   VARCHAR(MAX),
 Reconciliation        VARCHAR(2)
)

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 34)
	INSERT INTO #BillDetails
	SELECT	b.BillNumberID,a.ID AS CustomdetailID,b.billtype,a.KTypeID,a.CargoID,a.GoodsNumber,a.NQty,a.MQty,a.qty,a.TaxTotal,a.NTaxTotal,a.total,a.NTotal,(a.Taxtotal-a.Total),(a.nTaxtotal-a.nTotal),a.PtypeId,IsCombined,ItemID,MUnitID,BillDate,BillCode,btypeid,currate,dealBtypeId,etypeid,CID,
			a.SaleTotal AS pretotal,
			a.nSaleTotal AS npretotal,
		    a.SaleTotal - a.total AS discountge	,
		    a.nSaleTotal - a.ntotal AS ndiscountge	,
		    a.discount,
		    a.tax,
		    A.comment,
		    CASE WHEN A.Reconciliation='T' THEN '√' ELSE '' END Reconciliation
								
	FROM Buybill A
	INNER JOIN #BillNum b
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 34
	      AND  ((@IsShowReconciliation=0 AND a.Reconciliation='F') OR ( @IsShowReconciliation=1 AND 1=1 ))

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 6)
	INSERT INTO #BillDetails
	SELECT	b.BillNumberID,a.ID AS CustomdetailID,b.billtype,a.KTypeID,a.CargoID,a.GoodsNumber,-a.NQty,-a.MQty,-a.qty,-a.TaxTotal,-a.NTaxTotal,-a.total,-a.NTotal,-(a.Taxtotal-a.Total),-(a.nTaxtotal-a.nTotal),a.PtypeId,IsCombined,ItemID,MUnitID,BillDate,BillCode,btypeid,currate,dealBtypeId,etypeid,CID,
			-a.SaleTotal AS pretotal,
			-a.nSaleTotal AS npretotal,
		    a.SaleTotal - a.total AS discountge	,
		    a.nSaleTotal - a.ntotal AS ndiscountge	,
		    a.discount,
		    a.tax,
		    A.comment,
		     CASE WHEN A.Reconciliation='T' THEN '√' ELSE '' END Reconciliation
	FROM buybackbill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 6
	  AND  ((@IsShowReconciliation=0 AND a.Reconciliation='F')  OR ( @IsShowReconciliation=1 AND 1=1 ))
	

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 161)
	INSERT INTO #BillDetails
	SELECT b.BillNumberID,a.ID AS CustomdetailID,b.billtype,a.KTypeID,a.CargoID,a.GoodsNumber,
	CASE WHEN a.InOrOut='O' THEN -a.NQty
		 ELSE a.NQty END AS nqty,
	CASE WHEN a.InOrOut='O' THEN -a.MQty
		 ELSE a.MQty END AS mqty,
	CASE WHEN a.InOrOut='O' THEN -a.qty
		 ELSE a.qty END AS qty,
	CASE WHEN a.InOrOut='O' THEN -a.TaxTotal
		 ELSE a.TaxTotal END AS TaxTotal,
	CASE WHEN a.InOrOut='O' THEN -a.NTaxTotal
		 ELSE a.NTaxTotal END AS NTaxTotal,
	CASE WHEN a.InOrOut='O' THEN -a.total
		 ELSE a.total END AS total,
	CASE WHEN a.InOrOut='O' THEN -a.NTotal
		 ELSE a.NTotal END AS NTotal,
	CASE WHEN a.InOrOut='O' THEN a.Total - a.Taxtotal
		 ELSE a.Taxtotal-a.Total END AS TotalTax,
	CASE WHEN a.InOrOut='O' THEN a.nTotal - a.nTaxtotal
		 ELSE a.nTaxtotal-a.nTotal END AS nTotalTax,
	a.PtypeId,
	IsCombined,
	ItemID,
	MUnitID,BillDate,BillCode,btypeid,currate,dealBtypeId,etypeid,CID,
	
	CASE WHEN a.InOrOut='O' THEN -a.SaleTotal ELSE a.SaleTotal END AS pretotal,
	CASE WHEN a.InOrOut='O' THEN -a.nSaleTotal ELSE a.nSaleTotal END AS npretotal,
	CASE WHEN a.InOrOut='O' THEN -(a.SaleTotal - a.total) ELSE a.SaleTotal - a.total END AS discountge,
	CASE WHEN a.InOrOut='O' THEN -(a.nSaleTotal - a.ntotal) ELSE a.nSaleTotal - a.ntotal END AS ndiscountge,
    a.discount,
    a.tax,
	A.comment,
	 CASE WHEN A.Reconciliation='T' THEN '√' ELSE '' END Reconciliation
	FROM buygoodsexchangebill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 161	
	  AND  ((@IsShowReconciliation=0 AND a.Reconciliation='F')  OR 1=1 )

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 145)
	INSERT INTO #BillDetails
	SELECT	b.BillNumberID,a.ID AS CustomdetailID,b.billtype,10000,a.CargoID,a.GoodsNumber,a.NQty,a.MQty,a.qty,a.TaxTotal,a.NTaxTotal,a.total,a.NTotal,-(a.Total-a.Taxtotal),-(a.nTotal-a.nTaxtotal),a.PtypeId,IsCombined,ItemID,MUnitID,BillDate,BillCode,btypeid,currate,dealBtypeId,etypeid,CID,
			a.SaleTotal AS pretotal,
			a.nSaleTotal AS npretotal,
		    a.SaleTotal - a.total AS discountge	,
		    a.nSaleTotal - a.ntotal AS ndiscountge	,
		    a.discount,
		    a.tax,
		    A.comment,
		    CASE WHEN A.Reconciliation='T' THEN '√' ELSE '' END Reconciliation
	FROM commissionbill A
	INNER JOIN #BillNum b	
	ON A.BillNumberId=B.BillNumberID
	WHERE a.Type='145' AND B.BillType = 145
	  AND  ((@IsShowReconciliation=0 AND a.Reconciliation='F') OR ( @IsShowReconciliation=1 AND 1=1 ) )
--调试SQL 
--SELECT * FROM #Billnum
---------------------------------------------------暂估类单据数据插入--开始--------------------------------------------------------------	

	DECLARE @RKSQL VARCHAR(MAX)=''
	
	SET @RKSQL+='	
		--=======================================================暂估入库单数据==开始==========================
					INSERT INTO #BillDetails 
					SELECT	
							c.BillNumberId ,
							a.id as CustomdetailID,
							c.BillType ,
							a.ktypeid,
							a.cargoid,
							a.goodsnumber,
							mQty=(a.mqty-a.InvoiceNQty),  /*换算率变更前采购单位数量*/
							nQty = (a.nQty-a.InvoiceNQty) ,	/*浮动单位数量*/
							Qty = (a.Qty-a.InvoiceQty), /*基本单位数量 (未开票数量) */ 
							TaxTotal= CASE WHEN a.InvoiceQty=0 THEN a.TaxTotal ELSE (a.Qty-a.InvoiceQty)*a.TaxPrice END,	/*价税合计*/
							nTaxTotal= CASE WHEN a.InvoiceQty=0 THEN a.nTaxTotal ELSE (a.Qty-a.InvoiceQty)*a.nTaxPrice END,	/*价税合计*/
							Total =  CASE WHEN a.InvoiceQty=0 THEN a.Total ELSE  (a.Qty-a.InvoiceQty)*a.DiscountPrice END,	/*折后金额*/
							nTotal =CASE WHEN a.InvoiceQty=0 THEN a.nTotal ELSE  (a.Qty-a.InvoiceQty)*a.nDiscountPrice END,	/*折后金额*/			
							TotalTax=CASE WHEN a.InvoiceQty=0 THEN a.TaxMoney ELSE (a.Qty-a.InvoiceQty)*a.DiscountPrice*(a.Tax/100) END ,	/*税额(折后金额*税率)*/		
							nTotalTax=CASE WHEN a.InvoiceQty=0 THEN a.nTaxMoney ELSE (a.Qty-a.InvoiceQty)*a.nDiscountPrice*(a.Tax/100) END ,	/*税额*/
							a.ptypeid,
							a.IsCombined,
							a.ItemID,
							a.MUnitID,
							c.BillDate,	
							c.Billcode,
							c.btypeid,
							c.rate as  currate ,
							c.dealbtypeid,
							c.etypeid,
							c.CID,
							pretotal = CASE WHEN a.InvoiceQty=0 THEN a.saletotal ELSE (a.Qty-a.InvoiceQty)*SalePrice END,	/*本币采购金额*/
							npretotal = CASE WHEN a.InvoiceQty=0 THEN a.Nsaletotal ELSE (a.Qty-a.InvoiceQty)*NSalePrice END,	/*原币采购金额*/	
							discountge= CASE WHEN a.InvoiceQty=0 THEN (a.saletotal- a.Total) ELSE ( (a.Qty-a.InvoiceQty)*SalePrice - (a.Qty-a.InvoiceQty)*a.DiscountPrice ) END, /*折扣额(采购金额-折后金额)*/
							ndiscountge= CASE WHEN a.InvoiceQty=0 THEN (a.nsaletotal- a.nTotal) ELSE ( (a.Qty-a.InvoiceQty)*NSalePrice - (a.Qty-a.InvoiceQty)*a.nDiscountPrice ) END,	/*折扣额*/ 
							a.Discount,
							a.Tax,
							A.comment,
							 CASE WHEN A.Reconciliation=''T'' THEN ''√'' ELSE '''' END Reconciliation
             		FROM	AppraisalBill a
							INNER JOIN 	BillIndex c ON a.BillNumberId=c.BillNumberId
                            INNER JOIN #Billnum BN  ON BN.BillNumberId=c.BillNumberId
							INNER JOIN ptype p1 on a.ptypeid=p1.typeid
							LEFT JOIN dbo.PType_Units_Ext u6 ON  u6.UnitsId = p1.AssistantUnitId AND u6.PtypeId=p1.typeId/*浮动单位换算率*/
					'
		SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Ptype p  on a.ptypeid=p.typeid '
    
		IF NOT (@BTypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Btype b  on c.btypeid=b.typeid '
		IF NOT (@dealbtypeid = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #dealBtype b4  on c.dealbtypeid=b4.typeid '	    

		IF NOT (@ETypeID = '' AND @METypeId = '00001')
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Etype  e  on c.etypeid=e.typeid '

		IF NOT (@KTypeID = '' AND @MKtypeid = '00000')  
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Ktype k  on a.ktypeid=k.typeid '

		IF NOT (@STypeId = '' )
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Stype s  on c.stypeid=s.typeid'
		SELECT @RKSQL =@RKSQL+'
				WHERE   (('+CAST(@IsShowReconciliation AS VARCHAR(10))+'=0 AND a.Reconciliation=''F'')  OR ('+CAST(@IsShowReconciliation AS VARCHAR(10))+'=1 AND 1=1 ) )
				  
		--=======================================================暂估入库单数据==结束==========================
					' 
					
	DECLARE @THSQL VARCHAR(MAX)=''
	SET @THSQL+='	
		--=======================================================暂估退货单数据==开始==========================
					UNION ALL
					SELECT	
							c.BillNumberId ,
							a.id as CustomdetailID,
							c.BillType ,
							a.ktypeid,
							a.cargoid,
							a.goodsnumber,
							mqty= -(a.mqty-a.InvoiceNQty), /*换算率变更前采购单位数量*/
							nQty = -(a.nQty-a.InvoiceNQty) ,	/*浮动单位数量*/
							Qty = -(a.Qty-a.InvoiceQty), /*基本单位数量 (未开票数量) */ 
							TaxTotal= CASE WHEN a.InvoiceQty=0 THEN -a.TaxTotal ELSE -(a.Qty-a.InvoiceQty)*a.TaxPrice END,	/*价税合计*/
							nTaxTotal= CASE WHEN a.InvoiceQty=0 THEN -a.nTaxTotal ELSE -(a.Qty-a.InvoiceQty)*a.nTaxPrice END,	/*价税合计*/
							Total =  CASE WHEN a.InvoiceQty=0 THEN -a.Total ELSE  -(a.Qty-a.InvoiceQty)*a.DiscountPrice END,	/*折后金额*/
							nTotal =CASE WHEN a.InvoiceQty=0 THEN -a.nTotal ELSE  -(a.Qty-a.InvoiceQty)*a.nDiscountPrice END,	/*折后金额*/			
							TotalTax=CASE WHEN a.InvoiceQty=0 THEN -a.TaxMoney ELSE -(a.Qty-a.InvoiceQty)*a.DiscountPrice*(a.Tax/100) END ,	/*税额(折后金额*税率)*/		
							nTotalTax=CASE WHEN a.InvoiceQty=0 THEN -a.nTaxMoney ELSE -(a.Qty-a.InvoiceQty)*a.nDiscountPrice*(a.Tax/100) END ,	/*税额*/
							a.ptypeid,
							a.IsCombined,
							a.ItemID,
							a.MUnitID,
							c.BillDate,	
							c.Billcode,
							c.btypeid,
							c.rate as  currate ,
							c.dealbtypeid,
							c.etypeid,
							c.CID,
							pretotal = CASE WHEN a.InvoiceQty=0 THEN -a.saletotal ELSE -(a.Qty-a.InvoiceQty)*SalePrice END,	/*本币采购金额*/
							npretotal = CASE WHEN a.InvoiceQty=0 THEN -a.Nsaletotal ELSE -(a.Qty-a.InvoiceQty)*NSalePrice END,	/*原币采购金额*/	
							discountge= CASE WHEN a.InvoiceQty=0 THEN -(a.saletotal- a.Total) ELSE -( (a.Qty-a.InvoiceQty)*SalePrice - (a.Qty-a.InvoiceQty)*a.DiscountPrice ) END, /*折扣额(采购金额-折后金额)*/
							ndiscountge= CASE WHEN a.InvoiceQty=0 THEN -(a.nsaletotal- a.nTotal) ELSE -( (a.Qty-a.InvoiceQty)*NSalePrice - (a.Qty-a.InvoiceQty)*a.nDiscountPrice ) END,	/*折扣额*/ 
							a.Discount,
							a.Tax,
							A.comment,
							CASE WHEN A.Reconciliation=''T'' THEN ''√'' ELSE '''' END Reconciliation
             		FROM	AppraisalBackBill a
							INNER JOIN 	BillIndex c ON a.BillNumberId=c.BillNumberId
                            INNER JOIN #Billnum BN  ON BN.BillNumberId=c.BillNumberId
							INNER JOIN ptype p1 on a.ptypeid=p1.typeid
							LEFT JOIN dbo.PType_Units_Ext u6 ON  u6.UnitsId = p1.AssistantUnitId AND u6.PtypeId=p1.typeId/*浮动单位换算率*/
					'
		SELECT @THSQL =@THSQL+'  INNER JOIN  #Ptype p  on a.ptypeid=p.typeid '
    
		IF NOT (@BTypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Btype b  on c.btypeid=b.typeid '
		IF NOT (@dealbtypeid = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @THSQL =@THSQL+'  INNER JOIN  #dealBtype b4  on c.dealbtypeid=b4.typeid '	    

		IF NOT (@ETypeID = '' AND @METypeId = '00001')
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Etype  e  on c.etypeid=e.typeid '

		IF NOT (@KTypeID = '' AND @MKtypeid = '00000')  
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Ktype k  on a.ktypeid=k.typeid '

		IF NOT (@STypeId = '' )
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Stype s  on c.stypeid=s.typeid '
				SELECT @THSQL =@THSQL+'
				  	WHERE   (('+CAST(@IsShowReconciliation AS VARCHAR(10))+'=0 AND a.Reconciliation=''F'')  OR ('+CAST(@IsShowReconciliation AS VARCHAR(10))+'=1 AND 1=1 ) )
		--=======================================================暂估退货单数据==结束==========================
					' 
		--select * from #BillDetails
		CREATE TABLE #ZGKPBillDetails /*和BillDetails保持一致*/
		(
		 BillNumberID         int ,
		 CustomdetailID       int ,
		 billtype             INT,
		 Ktypeid			  varchar(50),
		 CargoID              INT,
		 GoodsNumber		  varchar(100),
		 NQty                  NUMERIC(24, 10) ,
		 MQty                  NUMERIC(24, 10) ,
		 Qty				   NUMERIC(24, 10) ,
		 Total	               NUMERIC(24, 10) ,
		 nTotal	           NUMERIC(24, 10) ,
		 TaxTotal			   NUMERIC(24, 10) ,
		 NTaxTotal			   NUMERIC(24, 10) ,
		 TotalTax			   NUMERIC(24, 10) ,
		 nTotalTax			   NUMERIC(24, 10) ,
		 ptypeid			  varchar(50),
		 IsCombined           INT,
		 ItemID               BIGINT,
		 MUnitID              INT,
		 BillDate			  datetime,
		 BillCode			  varchar(200),
		 btypeid			  varchar(50),
		 currate			   NUMERIC(24, 10) ,
		 dealBtypeId		  varchar(50),
		 etypeid			  varchar(50),
		 CID				  INT,
		 pretotal			   NUMERIC(24, 10) ,
		 npretotal			   NUMERIC(24, 10) ,
		 discountge			   NUMERIC(24, 10) ,
		 ndiscountge		   NUMERIC(24, 10) ,
		 Discount			   NUMERIC(24, 10) ,
		 Tax				   NUMERIC(24, 10) ,
		 dComment			   VARCHAR(MAX),
		 Reconciliation        VARCHAR(2)
		)
		
	DECLARE @KPSQL VARCHAR(MAX)=''
	
	SET @KPSQL+='	
		--=======================================================采购暂估开票数据==开始==========================
					INSERT INTO #ZGKPBillDetails
					SELECT	
							c.BillNumberId ,
							a.id as CustomdetailID,
							c.BillType ,
							a.ktypeid,
							a.cargoid,
							a.goodsnumber,
							MQty = a.MQty,
							nQty = a.NQty ,	/*浮动单位数量*/
							Qty = a.qty, /*基本单位数量*/
							Total = a.Total ,	/*折后金额*/
							nTotal = a.nTotal,	/*折后金额*/	
							TaxTotal= a.TaxTotal,	/*价税合计*/
							nTaxTotal= a.nTaxTotal,	/*价税合计*/
							TotalTax= a.taxmoney  ,	/*税额*/		
							nTotalTax= a.ntaxmoney,	/*税额*/
							a.ptypeid,
							a.IsCombined,
							a.ItemID,
							a.MUnitID,
							c.BillDate,	
							c.Billcode,
							c.btypeid,
							c.rate as  currate ,
							c.dealbtypeid,
							c.etypeid,
							c.CID,
							pretotal = a.Saletotal  ,	/*采购金额*/
							npretotal = a.nSaletotal  ,	/*采购金额*/	
							discountge= 0, /*折扣额*/
							ndiscountge= 0,	/*折扣额*/ 
							a.Discount,
							a.Tax,
							A.Comment,
							'''' as Reconciliation
             		FROM	ReceiptBill a
							INNER JOIN 	ReceiptBillIndex c ON a.BillNumberId=c.BillNumberId
                            INNER JOIN #ZGKPBillnum BN  ON BN.BillNumberId=c.BillNumberId
							INNER JOIN ptype p1 on a.ptypeid=p1.typeid
							LEFT JOIN dbo.PType_Units_Ext u6 ON  u6.UnitsId = p1.AssistantUnitId AND u6.PtypeId=p1.typeId/*浮动单位换算率*/
					'
		SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Ptype p  on a.ptypeid=p.typeid '
    
		IF NOT (@BTypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Btype b  on c.btypeid=b.typeid '
		IF NOT (@dealbtypeid = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #dealBtype b4  on c.dealbtypeid=b4.typeid '	    

		IF NOT (@ETypeID = '' AND @METypeId = '00001')
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Etype  e  on c.etypeid=e.typeid '

		IF NOT (@KTypeID = '' AND @MKtypeid = '00000')  
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Ktype k  on a.ktypeid=k.typeid '

		IF NOT (@STypeId = '' )
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Stype s  on c.stypeid=s.typeid
				  
		--=======================================================采购暂估开票数据==结束==========================
					' 
					
--有暂估类单据才执行@zgSQL
IF EXISTS(SELECT TOP 1 1 FROM #BillName WHERE Billtype IN ('400','401','404'))
BEGIN
	EXEC(@RKSQL+@THSQL+@KPSQL)
	
	--调试SQL----------------------开始
	--暂估入库SQL
	--EXEC(@RKSQL) PRINT @RKSQL 
	--SELECT * FROM #Billnum
	--开票SQL
	--EXEC(@KPSQL) PRINT @KPSQL 
	--SELECT * FROM #Billnum
	--调试SQL----------------------结束
END
--select * from #ZGKPBillDetails
--SELECT * FROM #BillDetails

---------------------------------------------------暂估类单据数据插入--结束--------------------------------------------------------------	

SET @SQL='
	SELECT 
		i.BillNumberId,
		i.CustomdetailID,
		i.BillDate,
		B.posttime,
		i.BillCode,
		i.billtype,
		bn.BillName,
		pt.UserCode,
		pt.FullName,
		p.typeid as ptypeid,
		pt.Unit1,
		i.dealBtypeId,
		e.typeId As ETypeId,
		i.KtypeId,
		i.cargoid,	
	    b1.fullname as ifullname,
	    d1.fullname as acfullname,
	    i.goodsnumber,
		i.currate,
		i.nQty,
		d.rate,
		e1.fullname as ufullname,
		u5.fullname as assistantfullname,
		u1.fullname as baseunitfullname,
		i.Qty,
		i.Qty/d.rate AS jlqty,
		i.MQTY as brcjlqty,
		i.Total,
	    i.nTotal,
		i.TaxTotal,
		i.NTaxTotal,
		i.TotalTax,
	    i.nTotalTax,
	    i.pretotal,
		i.npretotal,
		i.discountge,
		i.ndiscountge,
		i.Discount,
		i.Tax,
		I.DComment,
		B.explain,
		B.Comment,
		i.Reconciliation
	FROM
		#BillDetails i
	INNER JOIN 
		BILLINDEX  B ON B.BillNumberId = I.BillNumberId 
	INNER JOIN
		Ptype pt ON i.PtypeId = pt.typeId
	INNER JOIN
		#Ptype p ON i.PtypeId = p.typeId
	INNER JOIN
		#Ktype s ON i.KtypeId = s.typeId	
	INNER JOIN
		#Btype bt ON i.BtypeId = bt.typeId
	INNER JOIN
	    #dealBtype bt1 ON i.dealBtypeId = bt1.typeId	
	INNER JOIN
		#Etype e ON i.EtypeId = e.typeId
	LEFT JOIN
		BillName bn ON i.BillType = bn.BillType
	left JOIN 
	    vWeb_ItemIDByIsCombined b1 ON b1.iscombined=i.IsCombined AND b1.id=i.ItemID
	INNER JOIN 
	    Ac_Currency d1 ON i.cid=d1.CId 
    left JOIN 
        PType_Units_Ext d ON  i.PtypeId=d.PtypeID AND i.MUNITID =d.UnitsId
    left JOIN 
        PType_Units e1 on d.UnitsId=e1.UnitsId
    --LEFT JOIN #Rate AS r ON (i.PtypeId =  r.PtypeID )
   '+dbo.F_GetPtypeUnitsAndRates('pt','1,5','')
   +'
	 WHERE i.qty <> 0 
	'
   +'	UNION ALL /*注意: 上面和下面不同点就两个#ZGKPBillDetails和ReceiptBillIndex . 因为暂估开票的主表是ReceiptBillIndex 不得不这样UNION ALL 一哈, 呵呵*/
	   SELECT 
			i.BillNumberId,
			i.CustomdetailID,
			i.BillDate,
			B.posttime,
			i.BillCode,
			i.billtype,
			bn.BillName,
			pt.UserCode,
			pt.FullName,
			p.typeid as ptypeid,
			pt.Unit1,
			i.dealBtypeId,
			e.typeId As ETypeId,
			i.KtypeId,
			i.cargoid,	
			b1.fullname as ifullname,
			d1.fullname as acfullname,
			i.goodsnumber,
			i.currate,
			i.nQty,
			d.rate,
			e1.fullname as ufullname,
			u5.fullname as assistantfullname,
			u1.fullname as baseunitfullname,
			i.Qty,
			i.Qty/d.rate AS jlqty,
			i.MQty AS brcjlqty,
			i.Total,
			i.nTotal,
			i.TaxTotal,
			i.NTaxTotal,
			i.TotalTax,
			i.nTotalTax,
			i.pretotal,
			i.npretotal,
			i.discountge,
			i.ndiscountge,
			i.Discount,
			i.Tax,
			I.DComment,
			B.explain,
			B.Comment,
			i.Reconciliation
		FROM
			#ZGKPBillDetails i
		INNER JOIN 
			ReceiptBillIndex AS B ON(B.BillNumberId = I.BillNumberId)
		INNER JOIN
			Ptype pt ON i.PtypeId = pt.typeId
		INNER JOIN
			#Ptype p ON i.PtypeId = p.typeId
		INNER JOIN
			#Ktype s ON i.KtypeId = s.typeId	
		INNER JOIN
			#Btype bt ON i.BtypeId = bt.typeId
		INNER JOIN
			#dealBtype bt1 ON i.dealBtypeId = bt1.typeId	
		INNER JOIN
			#Etype e ON i.EtypeId = e.typeId
		LEFT JOIN
			BillName bn ON i.BillType = bn.BillType
		left JOIN 
			vWeb_ItemIDByIsCombined b1 ON b1.iscombined=i.IsCombined AND b1.id=i.ItemID
		INNER JOIN 
			Ac_Currency d1 ON i.cid=d1.CId 
		left JOIN 
			PType_Units_Ext d ON  i.PtypeId=d.PtypeID AND i.MUNITID =d.UnitsId
		left JOIN 
			PType_Units e1 on d.UnitsId=e1.UnitsId
		--LEFT JOIN #Rate AS r ON (i.PtypeId =  r.PtypeID )
	   '+dbo.F_GetPtypeUnitsAndRates('pt','1,5','')
		+'
		 WHERE i.qty <> 0 
		'
----------------------------------------------------------
		SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS i ORDER BY i.BillDate,i.BillCode' + 
			  ' 
				--显示最终结果
				SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head, SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,
				SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,SysDiy26,
				SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
				SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40 
					  FROM #temp1 a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid
						  
				DROP TABLE #temp1
			   '   
	EXEC (@SQL)
	

----------------------------------------------------------

DROP TABLE #Ptype ,#Btype,#Etype,#Ktype,#Stype,#dealbtype,#Billnum,#billname,#BillDetails,#ZGKPBillnum,#ZGKPBillDetails
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DepartmentCGTJLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DepartmentCGTJLineQuery]
GO





-------------------------------------------------------------------------
--部门采购统计线性表
--作者：徐辉
--日期：2009-01-14
--引用：GP_CheckOperatorRight23
-------------------------------------------------------------------------


--==========================================
--修改: 魏伟
--日期: 2015-05-24
--描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
--==========================================
CREATE                                  PROCEDURE Web_DepartmentCGTJLineQuery  
(
	@StartDate			VARCHAR(10),
	@EndDate			VARCHAR(10),
	@STypeID			VARCHAR(Max),	--分支机构
	@ETypeID			VARCHAR(Max),	--经手人
	@BTypeID			VARCHAR(Max),	--结算单位
	@KTypeID			VARCHAR(Max),	--仓库
	@DTypeID			VARCHAR(Max),	--部门
	@PTypeID			VARCHAR(Max),	--商品
	@BillType			VARCHAR(Max),	--单据类型
	@OperatorID 		VARCHAR(50),	--操作员ID号
	@DealBTypeID        VARCHAR(MAX),   --往来单位
	@ptypecategoryid    VARCHAR(MAX)    --商品类别ID
	--@unitvalue          INT             --单位选择值：销售单位0，采购单位1，存货单位2，基本单位3
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL varchar(4000)

IF @ETypeID = '00001' --全部经手人
	SET @ETypeID = ''
IF @KTypeID = '00000' --全部仓库
	SET @KTypeID = ''
IF @DTypeID = '00000' --全部部门
	SET @DTypeID = ''
IF @PTypeID = '00000' --全部商品
	SET @PTypeID = ''
IF @BTypeID = '00000' --全部结算单位
	SET @BTypeID = ''
IF @DealBTypeID = '00000' --全部往来单位
	SET @DealBTypeID = ''

--需要查询的部门信息
CREATE TABLE #Department
(
	typeId		VARCHAR(50),
	UserCode	varchar(500),
	FullName	varchar(500)
)
IF @DTypeID = '' --所有部门
BEGIN
	INSERT INTO #Department SELECT typeId,UserCode,FullName FROM F_GetManDTypeAll(@OperatorID) WHERE sonnum=0 AND Deleted=0
	--加入其他部门部门
	--INSERT INTO #Department(typeId,UserCode,FullName) VALUES ('99999','其他部门','其他部门')
END
ELSE
BEGIN
	INSERT INTO #Department SELECT typeId,UserCode,FullName FROM F_GetManDTypeAll(@OperatorID) WHERE sonnum=0 AND Deleted=0 and typeid in (select typeid from F_GetManDTypeAll(@OperatorID) a ,(select * from  dbo.f_split(@DTypeID,',')) b where left(a.typeid,len(b.a))=b.a)
END

CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #DealBTypeID (TypeID varchar(50))

IF @PTypeID =''
	INSERT INTO #Ptype(typeid) select typeid from F_LinePC(@OperatorID,@ptypecategoryid)
ELSE
	INSERT INTO #Ptype(typeid) select a.typeid from  F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PTypeID,',')) b where left(a.typeid,len(b.a))=b.a


IF @BTypeID =''
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BTypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @DealBTypeID =''
	INSERT INTO #DealBTypeID select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #DealBTypeID select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@DealBTypeID,',')) b where left(a.typeid,len(b.a))=b.a	

IF @ETypeID=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@ETypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @KTypeID=''
BEGIN
	INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorID)
	insert into #Ktype select '10000'
END
ELSE
	INSERT INTO #Ktype select a.typeid from F_GetManDetailKType(@OperatorID) a,  (select * from  dbo.f_split(@KTypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a
	


----------------------------------------------
    CREATE TABLE #BillName ( Billtype INT )
    INSERT  INTO #BillName
            SELECT  A
            FROM    DBO.f_split(@BillType, ',')


    CREATE TABLE #Billnum
        (
           BillNumberID          NUMERIC(24, 10) ,
		   billtype             INT,
           dealBTypeId			varchar(50),
           EtypeID				varchar (50),
           DtypeID				varchar(50),
           btypeID				varchar(50)
        )
    
    CREATE TABLE #ZGKPBillnum
    (
       BillNumberID          NUMERIC(24, 10) ,
	   billtype             INT,
       dealBTypeId			varchar(50),
       EtypeID				varchar (50),
       DtypeID				varchar(50),
       btypeID				varchar(50)
    )
    

    CREATE TABLE #BillDetails
        (
          Qty  NUMERIC(24, 10)  ,
          Qty0  NUMERIC(24, 10)  ,
          total  NUMERIC(24, 10)  ,
          NoTaxTotal  NUMERIC(24, 10)  ,
          TotalTax  NUMERIC(24, 10)  ,
          nqty  NUMERIC(24, 10)  ,
          dealBTypeId VARCHAR(50) ,
          EtypeID VARCHAR(50) ,
          DtypeID VARCHAR(50) ,
          KtypeID VARCHAR(50),
          PtypeID VARCHAR(50),
          btypeID varchar(50),
          giftqty  NUMERIC(24, 10) ,
          pretotal  NUMERIC(24, 10) ,
          discountge  NUMERIC(24, 10) 
        )    


	
	SET @sql ='INSERT INTO #Billnum 
					 SELECT BillNumberId,BillType,dealBTypeId,EtypeID,DtypeID,btypeid
					 FROM BillIndex bil'         
     IF NOT (@STypeId = '' AND @MStypeid = '00000') 
        SET @SQL = @SQL + ' INNER JOIN #Stype S ON bil.stypeID =S.typeid '	
    SET @SQL = @SQL + ' WHERE	bil.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
								AND bil.BillType IN ('+@BillType+')
								AND bil.ifYearBill=0
								AND ifcheck=''t'' AND draft=0 AND redword=0'
    EXEC (@sql) 
	--PRINT(@sql)
--------------------------------------------暂估开票单据处理---开始-----------------------------------
	SET @sql ='INSERT INTO #ZGKPBillnum 
					 SELECT BillNumberId,BillType,dealBTypeId,EtypeID,DtypeID,btypeid
					 FROM ReceiptBillIndex bil'         
     IF NOT (@STypeId = '' AND @MStypeid = '00000') 
        SET @SQL = @SQL + ' INNER JOIN #Stype S ON bil.stypeID =S.typeid '	
    SET @SQL = @SQL + ' WHERE	bil.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
								AND bil.BillType IN ('+@BillType+')
								AND bil.ifYearBill=0
								AND ifcheck=''t'' AND draft=0 AND redword=0'
    EXEC (@sql) 
--------------------------------------------暂估开票单据处理---结束-----------------------------------	
	
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 34)
	INSERT INTO #BillDetails
	SELECT a.Qty,
		   CASE WHEN a.total=0 THEN a.Qty ELSE 0 END AS qty0,
		   a.Taxtotal,
		   a.total,
		   (a.TaxTotal-a.total),
		   a.nqty,
		   dealBTypeId,
		   EtypeID,
		   DtypeID,
		   a.KtypeID,
		   a.ptypeid,
		   b.btypeID,
		   CASE WHEN a.IsGift=1 THEN a.Qty ELSE 0 END AS giftqty,
		   a.SaleTotal AS pretotal,
		   a.SaleTotal - a.total AS discountge
	FROM Buybill A
	INNER JOIN #BillNum b
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 34
	
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 6)
	INSERT INTO #BillDetails
	SELECT -a.Qty,
		   CASE WHEN a.total=0 THEN -a.Qty ELSE 0 END AS qty0,
		   -a.Taxtotal,
		   -a.total,
		   -(a.TaxTotal-a.total),
		   -a.nqty,
		   dealBTypeId,
		   EtypeID,
		   DtypeID,
		   a.KtypeID,
		   a.ptypeid,
		   b.btypeID,
		    CASE WHEN a.IsGift=1 THEN -a.Qty ELSE 0 END AS giftqty,
		   -a.SaleTotal AS pretotal,
		   a.SaleTotal - a.total AS discountge
	FROM buybackbill A
	INNER JOIN #BillNum b
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 6	


IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 145)
	INSERT INTO #BillDetails
	SELECT a.Qty,
		   CASE WHEN a.total=0 THEN a.Qty ELSE 0 END AS qty0,
		   a.Taxtotal,
		   a.total,
		   (a.TaxTotal-a.total),
		   a.nqty,
		   dealBTypeId,
		   EtypeID,
		   DtypeID,
		   10000,
		   a.ptypeid,
		   b.btypeID,
		   0,
		   a.SaleTotal AS pretotal,
		   a.SaleTotal - a.total AS discountge
	FROM commissionbill A
	INNER JOIN #BillNum b
	ON A.BillNumberId=B.BillNumberID
	WHERE a.Type='145' AND B.BillType = 145		

	
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 161)
	INSERT INTO #BillDetails
	SELECT 
		   CASE WHEN A.InOrOut='O' THEN -a.Qty
				ELSE a.Qty END ,
		   CASE WHEN a.total=0 AND A.InOrOut='O' THEN -a.Qty
				WHEN a.total=0 AND A.InOrOut='I' THEN a.qty 
				ELSE 0 END AS qty0,
		   CASE WHEN A.InOrOut='O' THEN -a.Taxtotal
				ELSE a.Taxtotal END ,
		   CASE WHEN A.InOrOut='O' THEN -a.total
				ELSE a.total END ,
		   CASE WHEN A.InOrOut='O' THEN -(a.TaxTotal-a.total)
				ELSE (a.TaxTotal-a.total) END ,
		   CASE WHEN A.InOrOut='O' THEN -a.nqty
				ELSE a.nqty END ,								
		   dealBTypeId,
		   EtypeID,
		   DtypeID,
		   a.KtypeID,
		   a.ptypeid,
		   b.btypeID,
		   CASE WHEN a.IsGift=1 AND A.InOrOut='O' THEN -a.Qty 
		        WHEN a.IsGift=1 AND A.InOrOut='I' THEN a.Qty
				
		        ELSE 0 END AS giftqty,
		    
		    CASE WHEN A.InOrOut='O' THEN -a.SaleTotal ELSE a.SaleTotal END AS pretotal,
			CASE WHEN A.InOrOut='O' THEN -(a.SaleTotal - a.total) ELSE a.SaleTotal - a.total END AS discountge
	FROM buygoodsexchangebill A
	INNER JOIN #BillNum b
	ON A.BillNumberId=B.BillNumberID
	WHERE B.BillType = 161		
---------------------------------------------------暂估类单据数据插入--开始--------------------------------------------------------------	
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype IN('400','401','404') )
BEGIN
		INSERT INTO #BillDetails
		SELECT  /*暂估入库单数据*/
				qty=(a.qty-a.InvoiceQty)  ,/*采购数量*/
				qty0=CASE WHEN a.total=0 THEN a.Qty ELSE 0 END   , /*0单价数量*/
				Total=CASE WHEN a.InvoiceQty=0 THEN a.TaxTotal ELSE (a.Qty-a.InvoiceQty)*a.TaxPrice END , /*价税合计*/		   
				NoTaxTotal=CASE WHEN a.InvoiceQty=0 THEN a.Total ELSE  (a.Qty-a.InvoiceQty)*a.DiscountPrice END, /*折后金额*/
				TotalTax=CASE WHEN a.InvoiceQty=0 THEN a.TaxMoney ELSE (a.Qty-a.InvoiceQty)*a.DiscountPrice*(a.Tax/100) END ,/*税额*/
				nQty = (a.nQty-a.InvoiceNQty),	/*浮动单位数量*/ 	
				b.dealBTypeId,
				b.EtypeID,
				b.DtypeID,
				bl.KtypeID,
				a.ptypeid,
				b.btypeID,
				giftqty=CASE when  a.isgift=1 then (a.qty-a.InvoiceQty) else 0  end  , /*单据赠品数量*/
				pretotal = CASE WHEN a.InvoiceQty=0 THEN a.saletotal ELSE (a.Qty-a.InvoiceQty)*SalePrice END,	/*采购金额*/
	   			discountge=  CASE WHEN a.InvoiceQty=0 THEN (a.saletotal- a.Total) ELSE ( (a.Qty-a.InvoiceQty)*SalePrice - (a.Qty-a.InvoiceQty)*a.DiscountPrice ) END /*折扣额(采购金额-折后金额)*/
		FROM AppraisalBill a
		INNER JOIN #BillNum b ON A.BillNumberId=B.BillNumberID
		INNER JOIN dbo.BillIndex bl ON b.BillNumberID=bl.BillNumberId
		INNER JOIN ptype p1 on a.ptypeid=p1.typeid
 		UNION ALL /*暂估退货单数据*/
		SELECT 
				qty=-(a.qty-a.InvoiceQty)  ,/*采购数量*/
				qty0=CASE WHEN a.total=0 THEN -a.Qty ELSE 0 END   , /*0单价数量*/
				Total=CASE WHEN a.InvoiceQty=0 THEN -a.TaxTotal ELSE -(a.Qty-a.InvoiceQty)*a.TaxPrice END , /*价税合计*/		   
				NoTaxTotal=CASE WHEN a.InvoiceQty=0 THEN -a.Total ELSE  -(a.Qty-a.InvoiceQty)*a.DiscountPrice END, /*折后金额*/
				TotalTax=CASE WHEN a.InvoiceQty=0 THEN -a.TaxMoney ELSE -(a.Qty-a.InvoiceQty)*a.DiscountPrice*(a.Tax/100) END ,/*税额*/
				nQty = -(a.nQty-a.InvoiceNQty),	/*浮动单位数量*/ 	
				b.dealBTypeId,
				b.EtypeID,
				b.DtypeID,
				bl.KtypeID,
				a.ptypeid,
				b.btypeID,
				giftqty=CASE when  a.isgift=1 then -(a.qty-a.InvoiceQty) else 0  end  , /*单据赠品数量*/
				pretotal = CASE WHEN a.InvoiceQty=0 THEN -a.saletotal ELSE -(a.Qty-a.InvoiceQty)*SalePrice END,	/*采购金额*/
	   			discountge=  CASE WHEN a.InvoiceQty=0 THEN -(a.saletotal- a.Total) ELSE -( (a.Qty-a.InvoiceQty)*SalePrice - (a.Qty-a.InvoiceQty)*a.DiscountPrice ) END /*折扣额(采购金额-折后金额)*/
		FROM dbo.AppraisalBackBill a
		INNER JOIN #BillNum b ON A.BillNumberId=B.BillNumberID
		INNER JOIN dbo.BillIndex bl ON b.BillNumberID=bl.BillNumberId
		INNER JOIN ptype p1 on a.ptypeid=p1.typeid
 		UNION ALL /*采购暂估开票数据*/
		SELECT 
				qty=a.Qty  ,/*采购数量*/
				qty0=(CASE WHEN a.total=0 THEN a.Qty ELSE 0 END )  , /*0单价数量*/
				Total=a.TaxTotal  , /*价税合计*/		   
				NoTaxTotal=a.Total , /*折后金额*/
				TotalTax=a.taxmoney  ,/*税额*/
				nQty = a.nqty  ,	/*浮动单位数量*/ 	
				b.dealBTypeId,
				b.EtypeID,
				b.DtypeID,
				a.KtypeID,
				a.ptypeid,
				b.btypeID,
				giftqty=CASE when  a.isgift=1 then a.qty ELSE 0  end  , /*单据赠品数量*/
				pretotal = a.saletotal,	/*采购金额*/
	   			discountge= 0 /*折扣额*/
		FROM dbo.ReceiptBill a
		INNER JOIN #ZGKPBillnum b ON A.BillNumberId=B.BillNumberID
		INNER JOIN dbo.ReceiptBillIndex bl ON b.BillNumberID=bl.BillNumberId
		INNER JOIN ptype p1 on a.ptypeid=p1.typeid
 
END 	
---------------------------------------------------暂估类单据数据插入--结束--------------------------------------------------------------	


--从inoutstocktable取需要查询的数据

CREATE TABLE #InoutStockTotal
(
	DtypeId		VARCHAR(50),
	Qty		 NUMERIC(24, 10) ,
	Qty0		 NUMERIC(24, 10) ,
	total		 NUMERIC(24, 10) ,
	NoTaxTotal	 NUMERIC(24, 10) ,
	TotalTax	 NUMERIC(24, 10) ,
	nqty		 NUMERIC(24, 10) ,
	giftqty      NUMERIC(24, 10) ,
	pretotal  NUMERIC(24, 10) ,
    discountge  NUMERIC(24, 10) 
)


SET @SQL='
INSERT INTO #InoutStockTotal
SELECT	  DtypeID,
		  SUM(ISNULL(Qty,0)),
          SUM(ISNULL(Qty0,0)),
          SUM(ISNULL(total,0)),
          SUM(ISNULL(NoTaxTotal,0)),
          SUM(ISNULL(TotalTax,0)),
          SUM(ISNULL(nqty,0)),
          sum(ISNULL(giftqty,0)),
          SUM(ISNULL(pretotal,0)),
          SUM(ISNULL(discountge,0))
FROM	#BillDetails I
INNER   JOIN #Btype B1 ON I.BTYPEID=b1.typeid
INNER   JOIN #Etype e  on i.etypeId=e.typeid
INNER   JOIN #Ktype k  on i.ktypeId=k.typeid
INNER   JOIN #Ptype p  on i.PtypeId=p.typeid
INNER   JOIN #DealBTypeID d  on i.DealBTypeID=d.typeid
'
	
SET @SQL=@SQL+' GROUP BY I.DtypeID'


EXEC(@SQL)




	SELECT 
		d.*, 
		i.Qty  AS qty,
	    i.giftQty  AS gift_qty,
		i.Qty0,
		i.total,
		i.NoTaxTotal,
		CASE 
		WHEN i.Qty <> 0 THEN  i.NoTaxTotal/i.Qty
		ELSE 0 END AS Price,
		i.TotalTax,
		i.nqty,
		i.pretotal,
		I.discountge
	FROM 
		#Department d
	LEFT JOIN #InoutStockTotal i ON d.typeId = i.DtypeId
	WHERE i.Qty<>0 OR i.Qty0<>0 OR i.NoTaxTotal<>0
	ORDER BY d.typeId

DROP TABLE #Department
DROP TABLE #InoutStockTotal
DROP TABLE #Ptype,#Btype,#Etype,#Ktype,#Stype,#DealBTypeID,#Billnum,#billname,#BillDetails



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DepartmentIncExpLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DepartmentIncExpLineQuery]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--部门费用报表线性表
--作者：徐辉
--日期：2005-08-29
--引用：GP_CheckOperatorRight23

	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示

	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome

	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误

	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	

	--修改记录#05--------------------------------------------------------
	--人员：徐辉
	--日期：2005-1-29
	--说明：停用职员也要纳入统计
	
	--修改记录#06--------------------------------------------------------
	--人员：毛欣蓉
	--日期：修改权限检查，优化查询条件	
	
	--修改记录#07--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修科目(qp1.0)
	--修改记录#08--------------------------------------------------------
	--修改作者：俞俊杰
	--修改原因：项目表变更Atype更换为ac_item
	--修改时间：2012-06-12
	
-------------------------------------------------------------------------
CREATE      PROCEDURE Web_DepartmentIncExpLineQuery  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(1550),	--指定要查询的财务科目节点ID
	@StartDate		VARCHAR(20),	--时间范围下限
	@EndDate		VARCHAR(20),	--时间范围上限
	@DtypeID		VARCHAR(50),	--部门编号
	@StypeID		VARCHAR(1550),	--分支机构
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@nPageCol		INT,			--分页会计科目的页码
	@nPageColSize	Int,
	@UserCode		VARCHAR(300)='',	--过滤职员Usercode
	@FullName		VARCHAR(300)='',	--过滤职员姓名
	@Flag           int =0              -- 0 报表 1 打印
)
--@encode$--
AS

SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #AType (TypeID varchar(50),nTypeID varchar(50),usercode varchar(300),fullname varchar(300),sonnum int)
--CREATE TABLE #DType (TypeID varchar(50),usercode varchar(26),fullname varchar(100),sonnum int,Deleted int)
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #DetailATypeSr (TypeID varchar(50),nTypeID varchar(50))
CREATE TABLE #DetailATypeFy (TypeID varchar(50),nTypeID varchar(50))

INSERT INTO #DetailATypeSr select a.typeid AS TypeID,a.nid AS nTypeID  from /*F_BaseGetManDetailATypeSr*/F_LineIncomeC(@OperatorID) a
INSERT INTO #DetailATypeFy select a.typeid AS TypeID,a.nid AS nTypeID  from /*F_BaseGetManDetailATypeFy*/F_LineExpenseC(@OperatorID) a
INSERT INTO #Etype select typeid from F_GetManETypeAll(@OperatorID)
INSERT INTO #Btype SELECT typeid FROM F_GetManBTypeAll(@OperatorID) UNION SELECT '' AS typeid

IF @QueryType=0 -- 收入
	IF @ATypeID=''
	BEGIN
		INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeSr SR ON A.nTypeId=SR.TypeID
	END
	ELSE
	BEGIN
		INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeSr SR ON A.nTypeId=SR.TypeID
		INNER JOIN (select BAC.nTypeId from  dbo.f_split(@AtypeID,',') Asp INNER JOIN dbo.Ac_Items  BAC  ON Asp.a = BAC.nId) b ON SR.TypeID  LIKE b.nTypeId+'%'
	END
ELSE  --费用
	IF @ATypeID=''
	BEGIN
		INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeFy fy ON A.nTypeId=fy.TypeID 
	END
	ELSE
	BEGIN
		INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeFy fy ON A.nTypeId=fy.TypeID 
		INNER JOIN (select BAC.nTypeId from  dbo.f_split(@AtypeID,',') Asp INNER JOIN dbo.Ac_Items  BAC  ON Asp.a = BAC.nId) b ON fy.TypeID  LIKE b.nTypeId+'%'
	END

DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #Atype where typeid='000040000200004'--#07 删除商品送修科目	


IF @DtypeID='00000' --方便后面条件语句使用
	SET @DtypeID =''

IF @STypeID=''
	INSERT INTO #Stype(typeid)  
	select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  
	select a.typeid from F_BaseGetManDetailSType(@OperatorID) a 
	INNER JOIN (select * from  dbo.f_split(@StypeID,',')) b ON a.typeid LIKE b.a+'%'

DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@nPageColSize		
SET @MColCount=0

DECLARE @Point			INT				--用于保存截取子字符串位置的变量
DECLARE @SUBSTRING		VARCHAR(255)	--用于保存子字符串的变量

--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
IF @AtypeID=''
BEGIN
	SET @ATypeID=CASE @QueryType
		WHEN 0 THEN '00003'			--“收入类”科目根节点
		WHEN 1 THEN '00004' --“支出类”科目根节点 #04 添加
	END
END

--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(50),
	ETypeCode	VARCHAR(100),
	ETypeName	VARCHAR(500),
	SonNum		INT,
	ATypeCount	INT,
	RowTotal 	 NUMERIC(24, 10)  DEFAULT 0
)

DECLARE @AtypeName varchar(66)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'

DECLARE @ColName varchar(8000)
SET  @ColName =' EtypeID,EtypeCode,EtypeName+''(''+EtypeCode+'')'' as [部门/'+@AtypeName+'],Sonnum,ATypeCount,RowTotal'
IF @Flag =1
	SET  @ColName =' EtypeID,EtypeName+''(''+EtypeCode+'')'' as [部门/'+@AtypeName+'],RowTotal as RowTotal'	

--对结果集合填充满足条件的部门数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum)
SELECT 
	a.TypeID AS ETypeID,
	a.UserCode AS ETypeCode,
	a.FullName AS ETypeName,
	a.SonNum AS SonNum
FROM F_GetManDTypeAll('''+@OperatorID+''') a 
WHERE Sonnum =0  AND  typeid like '''+@DtypeID+'%''
'



--判断是否显示其他部门时使用
DECLARE @OldFilterCode varchar(500),@OldFilterName varchar(500)
SELECT @OldFilterCode = @UserCode
SELECT @OldFilterName = @FullName

--组织职员编号过滤条件
IF @UserCode<>'' 
BEGIN
	SET @Point=charindex(',',@UserCode)
	WHILE @Point>0
	BEGIN

		SET @SUBSTRING=SUBSTRING(@UserCode,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @SUBSTRING + '%'''
		SET @UserCode=SUBSTRING(@UserCode,@Point+1,len(@UserCode)-@Point)
		SET @Point=charindex(',',@UserCode)
	END 
	IF @UserCode<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @UserCode + '%'''
	END 
END 

--组织职员名称过滤条件
IF @FullName<>'' 
BEGIN
	SET @Point=charindex(',',@FullName)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FullName,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @SUBSTRING + '%'''
		SET @FullName=SUBSTRING(@FullName,@Point+1,len(@FullName)-@Point)
		SET @Point=charindex(',',@FullName)
	END 
	IF @FullName<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @FullName + '%'''
	END	
END 

SET @SQL=@SQL + '
GROUP BY a.TypeID,a.UserCode,a.FullName,a.SonNum
ORDER BY a.UserCode
'

EXECUTE (@SQL)


SELECT ETypeID,ATypeID,ISNULL(SUM(Total),0) AS Total 
INTO #Temp_SubListTable
FROM
(
	SELECT l.DTypeID AS ETypeID,l.ATypeID,ISNULL(l.Total,0) AS Total 
	FROM ListTable l
	--LEFT JOIN Billindex b ON b.BillNumberId = l.BillNumberId
	LEFT JOIN 
	(
		SELECT BillNumberId,BillType,ifYearBill FROM dbo.BillIndex
		UNION ALL
		SELECT BillNumberId,BillType,ifYearBill FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillNumberId,BillType,ifYearBill FROM dbo.Coupon_BillIndex
		UNION ALL
		SELECT BillNumberId,BillType,ifYearBill FROM dbo.PosAllotApplyBillIndex
	) AS b ON(b.BillNumberId = l.BillNumberId AND b.BillType = l.BillType)
	INNER JOIN #Atype A ON A.nTypeID=L.AtypeId
	INNER JOIN #Stype S ON S.TypeID=L.STypeID
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	--INNER JOIN #Btype B1 ON B1.TypeID=L.BtypeId 
	WHERE
		l.Audited=1
		AND l.DTypeID LIKE @DtypeID + '%'
		AND l.BillDate>=@StartDate
		AND l.BillDate<=@EndDate
		AND b.ifYearBill=0	 --年节存标志
		AND b.BillType NOT IN (214,78)
) TEMP 
GROUP BY ETypeID,ATypeID



IF(@QueryType = 1)
BEGIN
	INSERT INTO #Temp_SubListTable
	SELECT CBND.DTypeID AS ETypeID,(SELECT TOP 1 nId FROM Ac_Items WHERE FullName = '业务提成') AS ATypeID,ISNULL(CBND.CommissionTotal,0) AS Total 
	FROM CommissionBillNew AS CBN
	INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
	INNER JOIN #Stype s ON CBN.STypeID=s.TypeID
	INNER JOIN #Etype E ON e.TypeID=CBND.EtypeId
	WHERE CBN.ifcheck = 't'
			AND CBN.BillDate>=@StartDate 
			AND CBN.BillDate<= @EndDate
			AND CBND.DTypeID LIKE @DtypeID + '%'	
	UNION ALL
	SELECT  d.DtypeID AS ETypeID,'25' AS ATypeID,
	d.Depreciation AS Total
	FROM dbo.DepBill d INNER JOIN dbo.BillIndex b ON d.BillNumberId = b.BillNumberId 
	--INNER JOIN #Atype A ON A.nTypeID=b.AtypeId
	INNER JOIN #Stype S ON S.TypeID=b.STypeID
	INNER JOIN #Etype E ON E.TypeID=b.EtypeId
	INNER JOIN #Btype B1 ON B1.TypeID=b.BtypeId 
	WHERE b.BillDate>=@StartDate 
		  AND b.BillDate<= @EndDate
		  AND d.DTypeID LIKE @DtypeID + '%'
		  AND b.BillType = 214
		  AND b.ifcheck = 't'
		  AND b.ifYearBill = 0
		  AND b.RedWord = 0
	UNION ALL
	SELECT  d.DtypeID AS ETypeID,'25' AS ATypeID,
	d.total AS Total
	FROM dbo.MoneyBill d INNER JOIN dbo.BillIndex b ON d.BillNumberId = b.BillNumberId 
	--INNER JOIN #Atype A ON A.nTypeID=b.AtypeId
	INNER JOIN #Stype S ON S.TypeID=b.STypeID
	INNER JOIN #Etype E ON E.TypeID=b.EtypeId
	INNER JOIN #Btype B1 ON B1.TypeID=b.BtypeId 
	WHERE b.BillDate>=@StartDate 
		  AND b.BillDate<= @EndDate
		  AND d.DTypeID LIKE @DtypeID + '%'
		  AND b.BillType = 78
		  AND b.ifcheck = 't'
		  AND b.ifYearBill = 0
		  AND b.RedWord = 0
END
--****************************************************************************--


--其他部门
IF @OldFilterCode='' AND @OldFilterName='' AND @DtypeID=''
BEGIN
	INSERT INTO #Temp_SubListTable SELECT '99999' AS ETypeID,l.ATypeID,ISNULL(SUM(l.Total),0) AS Total
	FROM ListTable l
	LEFT JOIN Billindex b ON b.BillNumberId = l.BillNumberId
	INNER JOIN #Atype A ON A.nTypeID=L.AtypeId
	INNER JOIN #Stype S ON S.TypeID=L.STypeID
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	INNER JOIN #Btype B1 ON B1.TypeID=L.BtypeId 
	WHERE	l.Audited=1
			AND l.BillDate>=@StartDate
			AND l.BillDate<=@EndDate
			AND b.DTypeID=''
			AND b.ifYearBill=0	 --年节存标志
	GROUP BY l.ATypeID
END

--haiquan合计列
SELECT ETypeID,Sum(Total) AS DTotal INTO #Temp_DTotal FROM #Temp_SubListTable GROUP by ETypeID

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(50)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(50)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	

DECLARE MATypeCursor CURSOR STATIC FOR
	SELECT DISTINCT nTypeID,UserCode,FullName FROM #Atype 

OPEN MAtypeCursor

FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName

SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount

WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@nPageCol - 1) * @MColPageNum
	BEGIN
		IF @Flag =0
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + '|' + @MyUserCode + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName + '|' + @MyUserCode + ']'
			
			SET @SQL='	UPDATE	#Temp_Result 
						SET		[' + @MyATypeName + '|' + @MyUserCode + '] = ISNULL(b.Total,0)
						FROM #Temp_Result AS a, 
						(
							select	sum(Total) Total,
									ETypeID,
									AtypeId 
							from	#Temp_SubListTable 
							group by ETypeID,AtypeId
						) b						
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
		END
		ELSE
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName +  ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName + ']'
			
			SET @SQL='	UPDATE	#Temp_Result 
						SET		[' + @MyATypeName + '] = ISNULL(b.Total,0)
						FROM	#Temp_Result AS a, 
						(
							select	sum(Total) Total,
									ETypeID,
									AtypeId 
							from	#Temp_SubListTable 
							group by ETypeID,AtypeId
						) b	
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
		END
	END 
	
	IF @MColCount = @nPageCol * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 



CLOSE MAtypeCursor
deallocate MAtypeCursor

UPDATE #Temp_Result SET RowTotal=A.DTotal FROM #Temp_DTotal A,#Temp_Result B WHERE B.eTypeid=A.EtypeID


--SELECT * FROM #Temp_Result

EXEC('SELECT '+@Colname+' FROM #Temp_Result WHERE RowTotal <> 0 ')

drop table #Temp_Result

DROP TABLE #Atype, #Stype, #Temp_SubListTable,#Temp_DTotal,#Btype,#Etype,#DetailATypeFy,#DetailATypeSr










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DepartmentIncExpLineQueryPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DepartmentIncExpLineQueryPrint]
GO



























-------------------------------------------------------------------------
--部门费用报表线性表
--作者：徐辉
--日期：2005-08-29
--引用：GP_CheckOperatorRight23

	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示

	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome

	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误

	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	

	--修改记录#05--------------------------------------------------------
	--人员：徐辉
	--日期：2005-1-29
	--说明：停用职员也要纳入统计	
-------------------------------------------------------------------------
CREATE                           PROCEDURE Web_DepartmentIncExpLineQueryPrint  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(25),	--指定要查询的财务科目节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@ETypeID		VARCHAR(25),	--职员编号
	@EmployeeName	VARCHAR(66),	--职员姓名
	@OperatorID 	VARCHAR(25),	--操作员ID号
	@ATypePageNo	INT,			--分页会计科目的页码
	@ColPageNum		Int,
	@FilterCode		VARCHAR(25)='',	--过滤职员Usercode
	@FilterName		VARCHAR(25)=''	--过滤职员姓名
)
--@encode$--
AS

SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--徐辉 2005-08-29
--说明：该存储过程是又职员费用，收入报表修改的来，此处EtypeId既指部门Id
IF @ETypeID='00000'
	SET @ETypeID=''
SET @METypeID = '' --部门目前没有权限范围

DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@ColPageNum		
SET @MColCount=0

DECLARE @Point			INT				--用于保存截取子字符串位置的变量
DECLARE @SUBSTRING		VARCHAR(255)	--用于保存子字符串的变量

--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
IF @AtypeID=''
	BEGIN
		SET @ATypeID=CASE @QueryType
			WHEN 0 THEN '00003'			--“收入类”科目根节点
			--WHEN 1 THEN '0000400003'	--“费用合计”科目根节点 --#04 注释了
			WHEN 1 THEN '00004' --“支出类”科目根节点 #04 添加
		END
	END
--目前只有费用报表
--SET @ATypeID='00004'


--#02以下------------------------------------------------------
IF @QueryType=0 SET @MAtypeid=@MIncome
IF @QueryType=1 SET @MAtypeid=@MExpense

--SET @MAtypeid=@MExpense --强行指定为费用权限范围

--#02以上------------------------------------------------------


--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(25),
	ETypeCode	VARCHAR(26),
	ETypeName	VARCHAR(66),
	SonNum		INT,
	ATypeCount	INT,
	RowTotal 	 NUMERIC(24, 10)  DEFAULT 0
)

DECLARE @AtypeName varchar(20)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'

DECLARE @ColName varchar(4000)
SET  @ColName ='EtypeName+''(''+EtypeCode+'')'' as [部门/'+@AtypeName+'],RowTotal as [总计]'

--对结果集合填充满足条件的部门数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum)
SELECT 
	a.TypeID AS ETypeID,
	a.UserCode AS ETypeCode,
	a.FullName AS ETypeName,
	a.SonNum AS SonNum
FROM department a
WHERE 
	--a.Deleted=0 #05
	a.SonNum = 0 AND
	a.TypeID LIKE ''' + @ETypeID + '%''
'
IF @METypeID<>''
	--SET @SQL=@SQL + 'AND ''' + @METypeID + ''' LIKE a.TypeID + ''%'''--#03 新添加---------------------------------
	SET @SQL=@SQL + 'AND a.TypeID LIKE ''' + @METypeID + '%'''--#03 新添加---------------------------------

-- print @SQL 
-- return 0

--判断是否显示其他部门时使用
DECLARE @OldFilterCode varchar(25),@OldFilterName varchar(25)
SELECT @OldFilterCode = @FilterCode
SELECT @OldFilterName = @FilterName

--组织职员编号过滤条件
IF @FilterCode<>'' 
BEGIN
	SET @Point=charindex(',',@FilterCode)
	WHILE @Point>0
	BEGIN

		SET @SUBSTRING=SUBSTRING(@FilterCode,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @SUBSTRING + '%'''
		SET @FilterCode=SUBSTRING(@FilterCode,@Point+1,len(@FilterCode)-@Point)
		SET @Point=charindex(',',@FilterCode)
	END 
	IF @FilterCode<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @FilterCode + '%'''
	END 
END 

--组织职员名称过滤条件
IF @FilterName<>'' 
BEGIN
	SET @Point=charindex(',',@FilterName)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FilterName,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @SUBSTRING + '%'''
		SET @FilterName=SUBSTRING(@FilterName,@Point+1,len(@FilterName)-@Point)
		SET @Point=charindex(',',@FilterName)
	END 
	IF @FilterName<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @FilterName + '%'''
	END	
END 

SET @SQL=@SQL + '
GROUP BY a.TypeID,a.UserCode,a.FullName,a.SonNum
ORDER BY a.UserCode
'

EXECUTE (@SQL)

--其他部门
IF @OldFilterCode = '' AND @OldFilterName = '' AND @ETypeID = ''
BEGIN
	INSERT INTO #Temp_Result(ETypeID,ETypeCode,ETypeName,SonNum) VALUES ('DDDDD','其他部门','其他部门',0)
END

--根据条件筛选职员收入、费用信息到一个临时表
--SELECT top 10 * FROM ListTable
SELECT b.DTypeID AS ETypeID,l.ATypeID,ISNULL(SUM(l.Total),0) AS Total
INTO #Temp_SubListTable
FROM ListTable l
LEFT JOIN Billindex b
ON b.BillNumberId = l.BillNumberId
WHERE
	l.Audited=1
	AND l.BillDate>=@BillDateBegin
	AND l.BillDate<=@BillDateEnd
	AND b.DTypeID LIKE @ETypeID + '%'
	AND b.DTypeID LIKE @MEtypeid + '%'
	AND l.ATypeID LIKE @ATypeID + '%'
	AND l.ATypeID LIKE @MAtypeid + '%'
	AND l.ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
GROUP BY b.DTypeID,l.ATypeID

--其他部门
IF @OldFilterCode='' AND @OldFilterName='' AND @ETypeID=''
BEGIN
	INSERT INTO #Temp_SubListTable SELECT 'DDDDD' AS ETypeID,l.ATypeID,ISNULL(SUM(l.Total),0) AS Total
		FROM ListTable l
		LEFT JOIN Billindex b
		ON b.BillNumberId = l.BillNumberId
		WHERE
			l.Audited=1
			AND l.BillDate>=@BillDateBegin
			AND l.BillDate<=@BillDateEnd
			AND LTRIM(b.DTypeID)=''
			AND RTRIM(b.DTypeID)=''
			AND l.ATypeID LIKE @ATypeID + '%'
			AND l.ATypeID LIKE @MAtypeid + '%'
			AND l.ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
		GROUP BY l.ATypeID
END

--haiquan合计列
SELECT ETypeID,Sum(Total) AS DTotal INTO #Temp_DTotal FROM #Temp_SubListTable GROUP by ETypeID

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(25)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(26)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	

DECLARE MATypeCursor CURSOR STATIC FOR
SELECT TypeID,UserCode,FullName FROM Atype 
WHERE 
	SonNum=0
	AND TypeID LIKE @ATypeID + '%'--#03-------------
	AND TypeID LIKE @MAtypeid + '%'--#03-------------
	AND TypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示

OPEN MAtypeCursor

FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName

SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount

WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@ATypePageNo - 1) * @MColPageNum
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName  + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName  + ']'
			
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName  + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
			
		END 
	
	IF @MColCount = @ATypePageNo * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 



CLOSE MAtypeCursor
deallocate MAtypeCursor

UPDATE #Temp_Result SET RowTotal=A.DTotal FROM #Temp_DTotal A,#Temp_Result B WHERE B.eTypeid=A.EtypeID


--SELECT * FROM #Temp_Result

EXEC('SELECT '+@Colname+' FROM #Temp_Result')

drop table #Temp_Result
--SELECT * FROM employee
--SELECT * FROM listtable
--SELECT col_length('employee','fullname')
--EXECUTE Web_EmployeeIncExpLineQuery 0,'','','','00001','','00001',1
--EXECUTE Web_EmployeeIncExpLineQuery 0,'','2003-6-30','2003-8-29','00001','','00001',1


































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DepartmentIncExpListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DepartmentIncExpListQuery]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



-------------------------------------------------------------------------
--部门费用报表树型表查询
--作者：徐辉
--日期：2005-08-29
--引用：GP_CheckOperatorRight23

	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示

	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome

	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误

	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2003-11-21
	--说明：有错误：当筛选具体的一个职员时，返回空结果结合。

	--修改记录#05--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	

	--修改记录#06--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修科目(qp1.0)
	
	--修改记录#07--------------------------------------------------------
	--人员：glj 
	--日期：2013-03-26
	--说明：项目权限调整[#AType]

	--修改记录#08
	--人员：周华
	--日期：2013-06-09
	--说明：9.2版本调整多级权限函数
	
	--修改记录#09
	--人员：颜熙
	--日期：2017-03-06
	--说明：9.8版本调整固定资产折旧单按表体使用部门汇总
-------------------------------------------------------------------------
CREATE  PROCEDURE Web_DepartmentIncExpListQuery  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(1550),	--指定要查询的财务科目节点ID
	@StartDate		VARCHAR(20),	--时间范围下限
	@EndDate		VARCHAR(20),	--时间范围上限
	@DTypeID		VARCHAR(50),	--部门ID
	@STypeID		VARCHAR(1550),	--分支机构ID
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@nPageCol		INT,			--分页会计科目的页码
	@nPageColSize	int,			--科目页面大小
	@Flag           int=0           -- 0 页面，1 打印
)
--@encode$--
AS


SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE 
	@SQL 			VARCHAR(MAX),	--用于保存动态SQL语句的变量
	@MColPageNum 	INT=@nPageColSize,--定义分页的列上限
	@MColCount		INT=0			--列计数

--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
--此处预留后期可能添加收入报表
CREATE TABLE #AType (TypeID varchar(50),nTypeID varchar(50),usercode varchar(300),fullname varchar(300),sonnum int)
CREATE TABLE #DType (TypeID varchar(50),usercode varchar(300),fullname varchar(300),sonnum int,Deleted int)
CREATE TABLE #Stype (TypeID varchar(50))

CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #DTypeAll (TypeID varchar(50))

INSERT INTO #Etype select typeid from F_GetManETypeAll(@OperatorID)
INSERT INTO #Btype SELECT typeid FROM F_GetManBTypeAll(@OperatorID) UNION SELECT '' AS typeid
INSERT INTO #DTypeAll select typeid from F_GetManDTypeAll(@OperatorID)

--==============================得到有权限的项目[BEGIN]===============================
SET @SQL='
	INSERT INTO #AType(TypeID,NTypeID,usercode,fullname,sonnum)
	SELECT DISTINCT 
		items.nId,
		items.nTypeId,
		items.UserCode,
		items.FullName,
		items.SonNum  
	FROM Ac_Items items
	'+CHAR(13)
	IF ISNULL(@ATypeID,'')<>''--判断科目是否为空
		SET @SQL+='INNER JOIN (SELECT nTypeId FROM Ac_Items ai INNER JOIN DBO.f_split('''+@AtypeID+''','','') F ON F.a=ai.nId) F ON items.nTypeId LIKE  F.nTypeId +''%'''+CHAR(13)

	SET @SQL+='
	INNER JOIN 
	(
		SELECT 
			items.nId
		FROM Ac_Items items '

	IF @QueryType=0 -- 收入
		SET @SQL+='INNER JOIN F_AllTreeIncomeC('''+@OperatorID+''') G ON G.nTypeID=items.nTypeID'+CHAR(13)
	ELSE
		SET @SQL+='INNER JOIN F_AllTreeExpenseC('''+@OperatorID+''') E ON E.nTypeID=items.nTypeID'+CHAR(13)
		
	SET @SQL+='
	WHERE 
		items.SonNum=0
	) A ON items.nId=A.nId'+CHAR(13)

EXEC(@SQL)


--==============================得到有权限的项目[END]===============================
DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #Atype where nTypeID='000040000200004'--#06 删除商品送修科目	
	
DECLARE @sonnum int 
SET @sonnum =0

IF @DtypeID=''
	SET @DtypeID ='00000'
SELECT @sonnum = sonnum FROM DepartMent WHERE Typeid =@DtypeID
IF @sonnum =0 
	INSERT INTO #Dtype(typeid,usercode,fullname,sonnum,deleted) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.deleted 
	FROM Department a
	INNER JOIN F_GetManDTypeAll(@OperatorID)  b ON a.typeid=b.typeid
	WHERE B.typeid =@DtypeID
ELSE
	INSERT INTO #Dtype(typeid,usercode,fullname,sonnum,deleted) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.deleted 
	FROM DepartMent a 
	INNER JOIN F_GetManDTypeAll(@OperatorID)  b ON a.typeid=b.typeid
	WHERE B.parid=@DtypeID


IF @STypeID=''
	INSERT INTO #Stype(typeid)  
	select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  
	select a.typeid from F_BaseGetManDetailSType(@OperatorID) a 
	INNER JOIN(select * from  dbo.f_split(@StypeID,',')) b ON a.typeid LIKE b.a+'%'
	
IF @DtypeID='00000' --方便后面条件语句使用
	SET @DtypeID =''

--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(50),
	ETypeCode	VARCHAR(300),
	ETypeName	VARCHAR(300),
	SonNum		INT,
	ATypeCount	INT,
	[RowTotal] 	 NUMERIC(24, 10)  DEFAULT 0,
	deleted int
)
DECLARE @AtypeName varchar(300)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'

DECLARE @ColName varchar(max)
SET  @ColName =' EtypeID,EtypeCode,EtypeName+''(''+EtypeCode+'')'' as [部门/'+@AtypeName+'],Sonnum,ATypeCount,RowTotal,deleted'
IF @Flag =1
	SET  @ColName ='EtypeID,EtypeName+''(''+EtypeCode+'')'' as [部门/'+@AtypeName+'],RowTotal as RowTotal'
--对结果集合填充满足条件的部门数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum,deleted)
SELECT 
	TypeID AS ETypeID,
	UserCode AS ETypeCode,
	FullName AS ETypeName,
	SonNum AS SonNum
	,deleted
FROM #Dtype
ORDER BY UserCode'
EXECUTE(@SQL)

SELECT ETypeID,ATypeID,SUM(Total) AS Total 
INTO #Temp_SubListTable
FROM 
(
	SELECT case WHEN b.DtypeID='' then '99999' else SUBSTRING(l.DTypeID,1,len(@DTypeID)+5) end AS ETypeID,
	l.ATypeID,
	ISNULL(l.Total,0) AS Total  
	FROM Listtable l
	INNER JOIN 
	(
		SELECT BillNumberId,BillType,DtypeID,BillDate,ifYearBill FROM dbo.BillIndex 
		UNION ALL
		SELECT BillNumberId,BillType,DtypeID,BillDate,ifYearBill FROM dbo.ReceiptBillIndex
		UNION ALL
		SELECT BillNumberId,BillType,DtypeID,BillDate,ifYearBill FROM dbo.Coupon_BillIndex
		UNION ALL
		SELECT BillNumberId,BillType,DtypeID,BillDate,ifYearBill FROM dbo.PosAllotApplyBillIndex
	) AS b ON(b.BillNumberId = l.BillNumberId AND B.BillType = l.BillType)
	INNER JOIN #atype a on l.atypeid=a.TypeID
	INNER JOIN #Stype s ON l.STypeID=s.TypeID
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	--INNER JOIN #Btype B1 ON B1.TypeID=L.BtypeId
	INNER JOIN #DTypeAll D ON D.TypeID=L.DTypeID 
	WHERE	l.Audited=1
			AND b.BillDate>=@StartDate 
			AND b.BillDate<= @EndDate
			AND B.ifYearBill= 0 --年节存标志
			AND b.BillType NOT IN (214,78)	
) AS TEMP
GROUP BY ETypeID,ATypeID

IF(@QueryType = 1)
BEGIN
	INSERT INTO #Temp_SubListTable
	SELECT SUBSTRING(CBND.DTypeID,1,len(@DTypeID)+5) as EtypeID,(SELECT TOP 1 nId FROM Ac_Items WHERE FullName = '业务提成') AS ATypeID,ISNULL(CBND.CommissionTotal,0) AS Total 
	FROM CommissionBillNew AS CBN
	INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
	INNER JOIN #Stype s ON CBN.STypeID=s.TypeID
	INNER JOIN #Etype E ON e.TypeID=CBND.EtypeId
	INNER JOIN #DTypeAll D ON d.TypeID=CBND.DTypeID
	WHERE CBN.ifcheck = 't'
			AND CBN.BillDate>=@StartDate 
			AND CBN.BillDate<= @EndDate
	UNION ALL
	SELECT case WHEN d.DtypeID='' then '99999' else SUBSTRING(d.DTypeID,1,len(@DTypeID)+5) end AS ETypeID,'25' AS ATypeID,
	d.Depreciation
	FROM dbo.DepBill d INNER JOIN dbo.BillIndex b ON d.BillNumberId = b.BillNumberId 
	--INNER JOIN #atype a on d.atypeid=a.TypeID
	INNER JOIN #Stype s ON b.STypeID=s.TypeID
	INNER JOIN #Etype E ON E.TypeID=b.EtypeId
	INNER JOIN #Btype B1 ON B1.TypeID=b.BtypeId
	INNER JOIN #DTypeAll Dd ON Dd.TypeID= d.DTypeID 
	WHERE b.BillDate>=@StartDate 
		  AND b.BillDate<= @EndDate
		  AND B.ifYearBill= 0 --年节存标志
		  AND b.BillType = 214 
		  AND b.ifcheck = 't'
		  AND b.RedWord = 0
	UNION ALL
	SELECT case WHEN d.DtypeID='' then '99999' else SUBSTRING(d.DTypeID,1,len(@DTypeID)+5) end AS ETypeID,'25' AS ATypeID,
	d.total
	FROM dbo.MoneyBill d INNER JOIN dbo.BillIndex b ON d.BillNumberId = b.BillNumberId 
	INNER JOIN #Stype s ON b.STypeID=s.TypeID
	INNER JOIN #Etype E ON E.TypeID=b.EtypeId
	INNER JOIN #Btype B1 ON B1.TypeID=b.BtypeId
	INNER JOIN #DTypeAll Dd ON Dd.TypeID=d.DTypeID 
	WHERE b.BillDate>=@StartDate 
		  AND b.BillDate<= @EndDate
		  AND B.ifYearBill= 0 --年节存标志
		  AND b.BillType = 78
		  AND b.ifcheck = 't'
		  AND b.RedWord = 0

END
--****************************************************************************--
--haiquanRowTotal列
SELECT ETypeID,Sum(Total) AS DTotal INTO #Temp_DTotal FROM #Temp_SubListTable GROUP by ETypeID

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(50)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(300)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(300)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	

--SELECT * FROM #AType
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT DISTINCT TypeID,UserCode,FullName FROM #Atype 
OPEN MAtypeCursor

FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName

SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount

WHILE @@fetch_status=0
BEGIN
	IF @MColCount >= (@nPageCol - 1) * @MColPageNum
	BEGIN
		IF @Flag =0
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + '|' + @MyUserCode + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName + '|' + @MyUserCode + ']'
			
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '|' + @MyUserCode + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, 
					(
						select sum(Total) Total,ETypeID,AtypeId from #Temp_SubListTable group by ETypeID,AtypeId
					) b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
		END
		ELSE -- 打印时，表头不一样
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName +']'
			
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a,
					(
						select sum(Total) Total,ETypeID,AtypeId from #Temp_SubListTable group by ETypeID,AtypeId
					) b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
		END
	END 
	
	IF @MColCount = @nPageCol * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
DEALLOCATE MAtypeCursor

UPDATE #Temp_Result SET [RowTotal]=A.DTotal FROM #Temp_DTotal A,#Temp_Result B WHERE B.eTypeid=A.EtypeID

---------固定资产折旧单按部门汇总--------------------
EXEC('SELECT '+@Colname+' FROM #Temp_Result WHERE RowTotal<>0')

DROP TABLE #Atype,#Dtype, #Btype,#Etype,#Stype,#DTypeAll


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DepartmentIncExpListQueryPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DepartmentIncExpListQueryPrint]
GO





























-------------------------------------------------------------------------
--部门费用报表树型表查询
--作者：徐辉
--日期：2005-08-29
--引用：GP_CheckOperatorRight23

	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示

	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome

	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误

	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2003-11-21
	--说明：有错误：当筛选具体的一个职员时，返回空结果结合。

	--修改记录#05--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
-------------------------------------------------------------------------
CREATE                                     PROCEDURE Web_DepartmentIncExpListQueryPrint  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(50),	--指定要查询的财务科目节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@ETypeID		VARCHAR(256),	--职员编号
	@EmployeeName	VARCHAR(256),	--职员姓名
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@ATypePageNo	INT,				--分页会计科目的页码
	@ColPageNum	    int				--科目页面大小
)
--@encode$--
AS

--徐辉2005-8-29
--说明，此存储过程又职员费用报表修改得到，所有此处的EType都是指部门


SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SET @MEtypeid='' --部门暂时未设权限范围

DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@ColPageNum
SET @MColCount=0

--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
--此处预留后期可能添加收入报表
IF @AtypeID=''
	BEGIN
		SET @ATypeID=CASE @QueryType
			WHEN 0 THEN '00003'			--“收入类”科目根节点
			--WHEN 1 THEN '0000400003'	--“费用合计”科目根节点 --#05 注释了
			WHEN 1 THEN '00004' --“支出类”科目根节点 #05 添加
		END
	END

--#02以下------------------------------------------------------
IF @QueryType=0 SET @MAtypeid=@MIncome
IF @QueryType=1 SET @MAtypeid=@MExpense
--#02以上------------------------------------------------------

IF @ETypeID='' SET @ETypeID='00000'

--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(25),
	ETypeCode	VARCHAR(256),
	ETypeName	VARCHAR(256),
	SonNum		INT,
	ATypeCount	INT,
	[RowTotal] 	 NUMERIC(24, 10)  DEFAULT 0,
	deleted int
)
DECLARE @AtypeName varchar(20)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'

DECLARE @ColName varchar(4000)
SET  @ColName ='EtypeName+''(''+EtypeCode+'')'' as [部门/'+@AtypeName+'],RowTotal as [总计]'

--对结果集合填充满足条件的部门数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum,deleted)
SELECT 
	TypeID AS ETypeID,
	UserCode AS ETypeCode,
	FullName AS ETypeName,
	SonNum AS SonNum
	,deleted
FROM department
WHERE '
--#04 Begin---------------------------------
DECLARE @ETypeSonNum INT
SELECT @ETypeSonNum=SonNum FROM department WHERE Deleted=0 AND TypeID=@ETypeID
--print @ETypeSonNum
IF @ETypeSonNum>0 
	BEGIN
	SET @SQL=@SQL + '
	ParID=''' + @ETypeID +''''
	END
ELSE
	BEGIN
	SET @SQL=@SQL + '
	TypeID=''' + @ETypeID +''''
	END
--#04 End  ---------------------------------
--print @SQL

IF @METypeID<>''
	--SET @SQL=@SQL + 'AND ''' + @METypeID + ''' LIKE TypeID + ''%'''--#03 新添加---------------------------------
	SET @SQL=@SQL + 'AND TypeID LIKE ''' + @METypeID + '%'''--#03 新添加---------------------------------

SET @SQL=@SQL +'	
ORDER BY UserCode'

--print @SQL
EXECUTE(@SQL)

--第一层才显示其他部门
--IF @ETypeID='00000'
--BEGIN
	--记录下没有部门全记录到其他部门
	--INSERT INTO #Temp_Result(ETypeID,ETypeCode,ETypeName,SonNum) VALUES ('DDDDD','其他部门','其他部门',0) 
--END

-- print @ETypeID
-- print @METypeID
-- Print @ATypeID
-- print @MAtypeid
-- return 0

--收缩listtable
IF @ETypeID = '00000' SET @ETypeID = '' --条件筛选变回来 应为此时为全部部门

SELECT * INTO #Listtable FROM ListTable
	WHERE  
		Audited=1
		AND BillDate BETWEEN @BillDateBegin AND @BillDateEnd
		AND ATypeID LIKE @ATypeID + '%'
		AND ATypeID LIKE @MAtypeid + '%'
		AND ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
--收缩billindex
SELECT * INTO #BillIndex FROM BillIndex
	WHERE 
		DTypeID LIKE @ETypeID + '%'
		AND DTypeID LIKE @MEtypeid + '%'

--根据条件筛选部门信息到一个临时表
--SELECT * FROM ListTable
SELECT SUBSTRING(b.DTypeID,1,len(@ETypeID)+5) AS ETypeID,l.ATypeID AS ATypeID,ISNULL(SUM(l.Total),0) AS Total
INTO #Temp_SubListTable
FROM #Listtable l
LEFT JOIN #BillIndex b
ON b.BillNumberId = l.BillNumberId
GROUP BY SUBSTRING(b.DTypeID,1,len(@ETypeID)+5),l.ATypeID


--SELECT * FROM #Temp_SubListTable
--第一层才显示其他部门
IF @ETypeID=''
BEGIN
	--记录下没有部门全记录到其他部门

	--收缩billindex
	SELECT * INTO #BillIndex1 FROM BillIndex
		WHERE 
			BillDate BETWEEN @BillDateBegin AND @BillDateEnd
			AND DTypeID=''
			AND DTypeID=''

	INSERT INTO #Temp_SubListTable SELECT 'DDDDD' AS ETypeID,l.ATypeID AS ATypeID,ISNULL(SUM(l.Total),0) AS Total
	FROM #Listtable l
	INNER JOIN #BillIndex1 b
	ON b.BillNumberId = l.BillNumberId
	GROUP BY l.ATypeID

	DROP TABLE #BillIndex1

END

--haiquanRowTotal列
SELECT ETypeID,Sum(Total) AS DTotal INTO #Temp_DTotal FROM #Temp_SubListTable GROUP by ETypeID

DROP TABLE #Listtable
DROP TABLE #BillIndex
--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(25)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(256)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(256)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	

DECLARE MATypeCursor CURSOR STATIC FOR
SELECT TypeID,UserCode,FullName FROM Atype 
WHERE 
	SonNum=0
	AND TypeID LIKE @ATypeID + '%'--#03-------------
	AND TypeID LIKE @MAtypeid + '%'--#03-------------
	AND TypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示

OPEN MAtypeCursor

FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName

SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount

WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@ATypePageNo - 1) * @MColPageNum
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName  + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName  + ']'
			
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName  + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			--print @SQL
			EXECUTE(@SQL)
			
		END 
	
	IF @MColCount = @ATypePageNo * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 



CLOSE MAtypeCursor
deallocate MAtypeCursor

UPDATE #Temp_Result SET [RowTotal]=A.DTotal FROM #Temp_DTotal A,#Temp_Result B WHERE B.eTypeid=A.EtypeID

EXEC('SELECT '+@Colname+' FROM #Temp_Result')

--SELECT * FROM employee
--SELECT * FROM listtable
--SELECT col_length('employee','fullname')
--EXECUTE Web_EmployeeIncExpListQuery 0,'','','','00001','','00001',1
--EXECUTE Web_EmployeeIncExpListQuery 0,'','2003-6-30','2003-8-29','00001','','00001',1



































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_DepartmentSaleDist]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_DepartmentSaleDist]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-06-25
function:部门销售分布表树形表
*/
CREATE PROCEDURE Web_DepartmentSaleDist
(
	@OperatorId		VARCHAR(50),		--操作员Id
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--结束日期
	@StypeId        VARCHAR(MAX),		--分支机构Id
	@PtypeCategoryId VARCHAR(MAX),		--商品类别ID
	@PTypeId		VARCHAR(MAX),		--商品Id
	@DTypeId		VARCHAR(MAX),		--部门Id
	@nType			VARCHAR(10),		--金额的查询方式
	@BillType		VARCHAR(100),		--单据类型
	@ShowZero		VARCHAR(5),			--0.不显示红冲单据   1.显示红冲单据
	@UnitConvert	INT,				--单位
	@Sort		    NVARCHAR(200),		--排序
	@Ck				INT,				--1：升序 0降序

	@BCount			INT=10,				--基本信息的默认个数
	@BPageNo		INT=0,				--基本信息的页数
	@IsPrint		INT=0				--是否是打印算法
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------

DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================

--根据单位获取相关值
DECLARE
	@TempColumn			VARCHAR(50),
	@TempQty			VARCHAR(1000)='',
	@TempTable			VARCHAR(1000)=''
	
--销售单位		
IF @UnitConvert=0
	BEGIN
		SET @TempColumn='SaleUnitId'
		SET @TempTable='
		LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.SaleUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
		
	END
--采购单位
ELSE IF @UnitConvert=1
	BEGIN
		SET @TempColumn='BuyUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.BuyUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--存货单位
ELSE IF @UnitConvert=2
	BEGIN
		SET @TempColumn='StockUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.StockUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--基本单位
ELSE IF @UnitConvert=3
	BEGIN
		SET @TempColumn='baseUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.baseUnitId = R.UnitsId'
		SET @TempQty='B.Qty'
	END

--商品
IF(ISNULL(@PTypeId,'')='')
	SET @PTypeId='00000'

--父级
CREATE TABLE #ParidPtype(
	RowId				INT,
	TypeID				VARCHAR(50),
	SonNum				INT,
	UserCode			VARCHAR(200),
	AssistUnitFullName	VARCHAR(200),
	UnitFullName		VARCHAR(200),
	Rate				NUMERIC(24,10)
) 
CREATE CLUSTERED INDEX #ParidPtype_P_K ON #ParidPtype(TypeId)

DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,@PTypeId,@PtypeCategoryId)

SET @SQL='
INSERT INTO #ParidPtype(RowId,TypeID,SonNum,UserCode,AssistUnitFullName,UnitFullName,Rate)
SELECT
	ROW_NUMBER()OVER(ORDER BY P.UserCode) RowId,
	P.typeId,
	P.sonnum,
	P.UserCode,
	E.FullName AssistUnitFullName,
	PU.FullName UnitFullName,
	R.Rate
 '+@LinkStr+'
 LEFT JOIN PType_Units E ON P.AssistantUnitId=E.UnitsId
 '+@TempTable+'
 LEFT JOIN PType_Units PU ON PU.UnitsId=P.'+@TempColumn+'
 WHERE
	P.ParId='''+@PTypeId+'''
	AND P.iscombinationproduct=0'

EXEC(@SQL)

--实际查询商品
CREATE TABLE #Ptype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)
INSERT INTO #Ptype(TypeID)
SELECT
	P.typeId
FROM ptype P
INNER JOIN #ParidPtype F ON P.typeId LIKE F.TypeID+'%' AND P.sonnum=0 AND P.iscombinationproduct=0 

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	BEGIN
		INSERT INTO #Stype(typeid) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
	END
	
--往来单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetManDetailBType(@OperatorId)
	END

--职员
CREATE TABLE #Etype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF (@MEtypeid='-99999')
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetManDetailEType(@OperatorId)
	END

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeId)
IF (@MKtypeid='-99999')
	BEGIN
		INSERT INTO #Ktype(TypeID)
		SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
		UNION ALL
		SELECT '10000' TypeId
	END

--部门
CREATE TABLE #Dtype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
IF(ISNULL(@DTypeId,'')='' AND @MDtypeid='00000')--所有权限
	BEGIN
		INSERT INTO #Dtype(RowId,TypeID,UserCode,FullName) 
		SELECT 
			ROW_NUMBER()OVER(ORDER BY usercode) RowId,
			typeid,
			usercode,
			FullName
		FROM Department 
		WHERE sonnum=0
		ORDER BY usercode
	END
ELSE 
	BEGIN
		INSERT INTO #Dtype(RowId,TypeID,UserCode,FullName)
		SELECT 
			ROW_NUMBER()OVER(ORDER BY D.usercode) RowId,
			F.TypeId,
			D.usercode,
			D.FullName
		FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorId) F
		INNER JOIN Department D ON F.TypeId=D.typeid
		ORDER BY usercode
	END
	
--当前页部门
CREATE TABLE #PageDtype(TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #PageDtype(TypeID,UserCode,FullName)
SELECT 
	typeid,
	UserCode,
	FullName 
FROM #Dtype
WHERE RowId BETWEEN (@bPageNo-1)*@bCount AND @bPageNo*@bCount

--=============================基本信息权限范围获取【END】=======================================

--=============================业务处理【BEGIN】=====================================
SET @SQL=''

--BillIndex
CREATE TABLE #BillIndex
(
	BillNumberId 	NUMERIC(18,0),
	DTypeId			VARCHAR(50),
	BillType		INT	
) 
CREATE CLUSTERED INDEX #BillIndex_P_K ON #BillIndex(BillNumberId)

SET @SQL='
INSERT INTO #BillIndex
(
	BillNumberId,
	DTypeId,
	BillType
)
SELECT	
	B.BillNumberId,
	B.DTypeId,
	B.BillType
FROM BillIndex B' +CHAR(13)	

--分支机构
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	SET @SQL+='INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid'+CHAR(13)	
	
--部门
IF NOT(ISNULL(@DTypeId,'')='' AND @MDtypeid='00000')
	SET @SQL+='INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId '+CHAR(13)	
	
--往来单位
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		SET @SQL+='INNER JOIN #Btype B_B ON B_B.TypeID=B.BTypeID'+CHAR(13)
		SET @SQL+='INNER JOIN #Btype B_B1 ON B_B1.TypeID=B.DealBTypeID'+CHAR(13)
	END
	
--职员		
IF (@MEtypeid='-99999')
	SET @SQL+='INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid'+CHAR(13)
	
SET @SQL+='
WHERE 
	B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' 
	AND B.BillType IN ('+@BillType+') 
	AND B.RedWord=0 
	AND B.IfCheck=''t'' 
	AND B.Draft=0 
	AND B.ifYearBill=0'+CHAR(13)
	
EXEC(@SQL)
SET @SQL=''

--数据明细表
CREATE TABLE #SaleBill
(
	PTypeId		VARCHAR(50),
	DTypeId		VARCHAR(50),
	Qty			NUMERIC(24,10),
	NQty        NUMERIC(24,10),
	TaxTotal	NUMERIC(24,10) 
)
CREATE CLUSTERED INDEX #SaleBill_P_K ON #SaleBill(PTypeId)

--零售单
IF CHARINDEX('305',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN retailBill B ON I.BillType=305 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--零售退货单
IF CHARINDEX('215',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN RetailBackBill B ON I.BillType=215 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
	
END

--销售出库单
IF CHARINDEX('11',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN SaleBill B ON I.BillType=11 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--销售退货单
IF CHARINDEX('45',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN saleBackBill B ON I.BillType=45 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--销售换货单
IF CHARINDEX('160',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		CASE WHEN B.InOrOut = ''o'' THEN SUM('+@tempqty+') ELSE -SUM('+@tempqty+') END Qty,
		CASE WHEN B.InOrOut = ''o'' THEN SUM(B.NQty) ELSE -SUM(B.NQty) END NQty,
		CASE WHEN B.InOrOut = ''o'' THEN CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END
			 ELSE CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END
		END TaxTotal 
	FROM #BillIndex I
	INNER JOIN SaleGoodsExchangeBill B ON I.BillType=160 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='WHERE 
		B.InOrOut=''i'' 
		OR B.InOrOut=''o''  
	GROUP BY B.PTypeId,I.DTypeId,B.InOrOut'+CHAR(13)
END

--委托代销结算单
IF CHARINDEX('141',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN CommissionBill B ON I.BillType=141 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--组合品销售出库单
IF CHARINDEX('12',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN PT_Combin_SaleBillDetail B ON I.BillType=12 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--组合品销售退货单
IF CHARINDEX('46',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBackBillDetail B ON I.BillType=46 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

SET @SQL='
INSERT INTO #SaleBill
(
	PTypeId,
	DTypeId,
	Qty,
	NQty,
	TaxTotal
)
SELECT 
	PtypeId,
	DTypeId,
	SUM(ISNULL(F.Qty,0)) Qty,
	SUM(ISNULL(F.NQty,0)) NQty,
	SUM(ISNULL(F.TaxTotal,0)) TaxTotal
 FROM 
('+SUBSTRING(@SQL,10,LEN(@SQL))+'
)F
GROUP BY F.PTypeId,F.DTypeId
'
EXEC(@SQL)

--生成分布表
SET @SQL = '
SELECT
	P.typeid,
	P.SonNum 父节点,
	p.AssistUnitFullName 浮动单位,
	SUM(ISNULL(B.Qty,0)) 总计数量,
	SUM(ISNULL(B.NQty,0)) 总计浮动数量,
	SUM(ISNULL(B.TaxTotal,0)) 总计金额'

IF @bCount='10'
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+FullName+'数量]
						,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+FullName+'浮动数量]
						,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+FullName+'金额]'  
	FROM #PageDtype ORDER BY UserCode
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+FullName+'数量]
						,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+FullName+'浮动数量]
						,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+FullName+'金额]'  
	FROM #Dtype ORDER BY UserCode 
END 
SET @SQL+='
FROM #ParidPtype P
LEFT JOIN #SaleBill B ON B.PTypeId LIKE P.TypeID+''%'''  

SET @SQL+='
GROUP BY
	P.RowId,
	P.TypeID,
	P.SonNum,
	p.AssistUnitFullName
ORDER BY'

IF ISNULL(@sort,'')=''
	SET @SQL+='	p.RowId'   
	 
IF ISNULL(@sort,'')='0'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.Qty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.Qty,0))'  
  END				
IF ISNULL(@sort,'')='1'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.NQty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.NQty,0))'  
  END
IF	ISNULL(@sort,'')='2'
  BEGIN
	IF @ck!=1
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0)) DESC '    
    ELSE
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0))'  
  END
				
EXEC(@SQL)

--=============================业务处理【END】=======================================



--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#Dtype,#Etype,#Ktype,#Ptype,#Stype,#BillIndex,#PageDtype,#SaleBill,#ParidPtype

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_DepartmentSaleDistLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_DepartmentSaleDistLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-06-25
function:部门销售分布线性表
*/
CREATE PROCEDURE Web_DepartmentSaleDistLine
(
	@OperatorId		VARCHAR(50),		--操作员Id
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--结束日期
	@StypeId        VARCHAR(MAX),		--分支机构Id
	@PtypeCategoryId VARCHAR(MAX),		--商品类别ID
	@PTypeId		VARCHAR(MAX),		--商品Id
	@DTypeId		VARCHAR(MAX),		--部门Id
	@nType			VARCHAR(10),		--金额的查询方式
	@BillType		VARCHAR(100),		--单据类型
	@ShowZero		VARCHAR(5),			--0.不显示红冲单据   1.显示红冲单据
	@UnitConvert	INT,				--单位
	@Sort		    NVARCHAR(200),		--排序
	@Ck				INT,				--1：升序 0降序
	
	@BCount			INT=10,				--基本信息的默认个数
	@BPageNo		INT=0				--基本信息的页数
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN --------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE 
	@Re INT,
	@MAtypeid VARCHAR(50), 
	@MBtypeid VARCHAR(50), 
	@MBtypeid2 VARCHAR(50), 
	@MEtypeid VARCHAR(50),
	@MKtypeid VARCHAR(50), 
	@MPtypeid VARCHAR(50), 
	@MExpense VARCHAR(50), 
	@MIncome VARCHAR(50),
	@MCapital VARCHAR(50),
	@MDtypeid VARCHAR(50),
	@MStypeid VARCHAR(50)
	
EXEC @Re=GP_CheckOperatorRight23_Rep 
		@OperatorID,
		@MAtypeid OUTPUT,
		@MBtypeid OUTPUT,
		@MBtypeid2 OUTPUT,
		@MEtypeid OUTPUT,
		@MKtypeid OUTPUT,
		@MPtypeid OUTPUT,
		@MExpense OUTPUT,
		@MIncome OUTPUT,
		@MCapital OUTPUT,
		@MDtypeid OUTPUT,
		@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------
END;
	
DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================

--根据单位获取相关值
DECLARE
	@TempColumn			VARCHAR(50),
	@TempQty			VARCHAR(1000)='',
	@TempTable			VARCHAR(1000)=''
	
--销售单位		
IF @UnitConvert=0
	BEGIN
		SET @TempColumn='SaleUnitId'
		SET @TempTable='
		LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.SaleUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
		
	END
--采购单位
ELSE IF @UnitConvert=1
	BEGIN
		SET @TempColumn='BuyUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.BuyUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--存货单位
ELSE IF @UnitConvert=2
	BEGIN
		SET @TempColumn='StockUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.StockUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--基本单位
ELSE IF @UnitConvert=3
	BEGIN
		SET @TempColumn='baseUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.baseUnitId = R.UnitsId'
		SET @TempQty='B.Qty'
	END

--商品
IF(ISNULL(@PTypeId,'')='')
	SET @PTypeId='00000'

--实际查询商品
CREATE TABLE #Ptype(
	RowId				INT,
	TypeID				VARCHAR(50),
	SonNum				INT,
	UserCode			VARCHAR(200),
	AssistUnitFullName	VARCHAR(200),
	UnitFullName		VARCHAR(200),
	Rate				NUMERIC(24,10)
) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)

DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,@PTypeId,@PtypeCategoryId)

SET @SQL+='
INSERT INTO #Ptype(RowId,TypeID,SonNum,UserCode,AssistUnitFullName,UnitFullName,Rate)
SELECT
	ROW_NUMBER()OVER(ORDER BY P.UserCode) RowId,
	P.typeId,
	P.sonnum,
	P.UserCode,
	E.FullName AssistUnitFullName,
	PU.FullName UnitFullName,
	R.Rate
 '+@LinkStr+'
 LEFT JOIN PType_Units E ON P.AssistantUnitId=E.UnitsId
 '+@TempTable+'
 LEFT JOIN PType_Units PU ON PU.UnitsId=P.'+@TempColumn+'
 WHERE
	P.sonnum=0
	AND P.iscombinationproduct=0'

EXEC(@SQL)


--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	BEGIN
		INSERT INTO #Stype(typeid) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
	END

--部门
CREATE TABLE #Dtype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
IF(ISNULL(@DTypeId,'')='' AND @MDtypeid='00000')--所有权限
	BEGIN
		INSERT INTO #Dtype(RowId,TypeID,UserCode,FullName) 
		SELECT 
			ROW_NUMBER()OVER(ORDER BY usercode) RowId,
			typeid,
			usercode,
			FullName
		FROM Department 
		WHERE sonnum=0
		ORDER BY usercode
	END
ELSE 
	BEGIN
		INSERT INTO #Dtype(RowId,TypeID,UserCode,FullName)
		SELECT 
			ROW_NUMBER()OVER(ORDER BY D.usercode) RowId,
			F.TypeId,
			D.usercode,
			D.FullName
		FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorId) F
		INNER JOIN Department D ON F.TypeId=D.typeid
		ORDER BY usercode
	END
	
--当前页部门
CREATE TABLE #PageDtype(TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #PageDtype(TypeID,UserCode,FullName)
SELECT 
	typeid,
	UserCode,
	FullName 
FROM #Dtype
WHERE RowId BETWEEN (@bPageNo-1)*@bCount AND @bPageNo*@bCount


--往来单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetManDetailBType(@OperatorId)
	END

--职员
CREATE TABLE #Etype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF (@MEtypeid='-99999')
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetManDetailEType(@OperatorId)
	END

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeId)
IF (@MKtypeid='-99999')
	BEGIN
		INSERT INTO #Ktype(TypeID)
		SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
		UNION ALL
		SELECT '10000' TypeId
	END


--=============================基本信息权限范围获取【END】=======================================


--=============================业务处理【BEGIN】=====================================
SET @SQL=''

--BillIndex
CREATE TABLE #BillIndex
(
	BillNumberId 	NUMERIC(18,0),
	DTypeId			VARCHAR(50),
	BillType		INT	
) 
CREATE CLUSTERED INDEX #BillIndex_P_K ON #BillIndex(BillNumberId)

SET @SQL='
INSERT INTO #BillIndex
(
	BillNumberId,
	DTypeId,
	BillType
)
SELECT	
	B.BillNumberId,
	B.DTypeId,
	B.BillType
FROM BillIndex B' +CHAR(13)	

--分支机构
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	SET @SQL+='INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid'+CHAR(13)	
	
--部门
IF NOT(@DTypeId='' AND @MDtypeid='00000')
	SET @SQL+='INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId '+CHAR(13)	
	
--往来单位
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		SET @SQL+='INNER JOIN #Btype B_B ON B_B.TypeID=B.BTypeID'+CHAR(13)
		SET @SQL+='INNER JOIN #Btype B_B1 ON B_B1.TypeID=B.DealBTypeID'+CHAR(13)
	END

--职员		
IF (@MEtypeid='-99999')
	SET @SQL+='INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid'+CHAR(13)
	
SET @SQL+='
WHERE 
	B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' 
	AND B.BillType IN ('+@BillType+') 
	AND B.RedWord=0 
	AND B.IfCheck=''t'' 
	AND B.Draft=0 
	AND B.ifYearBill=0'+CHAR(13)
	
EXEC(@SQL)
SET @SQL=''


--数据明细表
CREATE TABLE #SaleBill
(
	PTypeId		VARCHAR(50),
	DTypeId		VARCHAR(50),
	Qty			NUMERIC(24, 10) ,
	NQty        NUMERIC(24, 10) ,
	TaxTotal	NUMERIC(24, 10) 
)
CREATE CLUSTERED INDEX #SaleBill_P_K ON #SaleBill(PTypeId)

--零售单
IF CHARINDEX('305',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN retailBill B ON I.BillType=305 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--零售退货单
IF CHARINDEX('215',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN RetailBackBill B ON I.BillType=215 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
	
END

--销售出库单
IF CHARINDEX('11',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN SaleBill B ON I.BillType=11 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--销售退货单
IF CHARINDEX('45',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN saleBackBill B ON I.BillType=45 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--销售换货单
IF CHARINDEX('160',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		CASE WHEN B.InOrOut = ''o'' THEN SUM('+@TempQty+') ELSE -SUM('+@TempQty+') END Qty,
		CASE WHEN B.InOrOut = ''o'' THEN SUM(B.NQty) ELSE -SUM(B.NQty) END NQty,
		CASE WHEN B.InOrOut = ''o'' THEN CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END
			 ELSE CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END
		END TaxTotal 
	FROM #BillIndex I
	INNER JOIN SaleGoodsExchangeBill B ON I.BillType=160 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='WHERE 
		B.InOrOut=''i'' 
		OR B.InOrOut=''o''  
	GROUP BY B.PTypeId,I.DTypeId,B.InOrOut'+CHAR(13)
END

--委托代销结算单
IF CHARINDEX('141',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN CommissionBill B ON I.BillType=141 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--组合品销售出库单
IF CHARINDEX('12',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBillDetail B ON I.BillType=12 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

--组合品销售退货单
IF CHARINDEX('46',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.DTypeId,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBackBillDetail B ON I.BillType=46 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.DTypeId'+CHAR(13)
END

SET @SQL='
INSERT INTO #SaleBill
(
	PTypeId,
	DTypeId,
	Qty,
	NQty,
	TaxTotal
)
SELECT 
	PtypeId,
	DTypeId,
	SUM(ISNULL(F.Qty,0)) Qty,
	SUM(ISNULL(F.NQty,0)) NQty,
	SUM(ISNULL(F.TaxTotal,0)) TaxTotal
 FROM 
('+SUBSTRING(@SQL,10,LEN(@SQL))+'
)F
INNER JOIN #Dtype T ON T.TypeID=F.DTypeId
GROUP BY F.PTypeId,F.DTypeId
'
EXEC(@SQL)

--生成分布表
SET @SQL = '
SELECT
	P.typeid,
	p.UserCode,
	P.SonNum 父节点,
	P.AssistUnitFullName 浮动单位,
	P.UnitFullName 计量单位,
	SUM(ISNULL(B.Qty,0)) 总计数量,
	SUM(ISNULL(B.NQty,0)) 总计浮动数量,
	SUM(ISNULL(B.TaxTotal,0)) 总计金额'

IF @bCount='10'
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+FullName+'数量]
						,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+FullName+'浮动数量]
						,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+FullName+'金额]'  
	FROM #PageDtype ORDER BY UserCode 
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+FullName+'数量]
						,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+FullName+'浮动数量]
						,SUM(CASE WHEN B.DTypeId = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+FullName+'金额]'  
	FROM #Dtype ORDER BY UserCode 
END 
SET @SQL+='
FROM #Ptype P
LEFT JOIN #SaleBill B ON B.PTypeId=P.TypeID'  

SET @SQL+='
GROUP BY
	P.RowId,
	P.TypeID,
	P.UserCode,
	P.SonNum,
	P.AssistUnitFullName,
	P.UnitFullName
ORDER BY'

IF ISNULL(@sort,'')=''
	SET @SQL+='	p.RowId'   
	 
IF ISNULL(@sort,'')='0'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.Qty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.Qty,0))'  
  END				
IF ISNULL(@sort,'')='1'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.NQty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.NQty,0))'  
  END
IF	ISNULL(@sort,'')='2'
  BEGIN
	IF @ck!=1
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0)) DESC '    
    ELSE
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0))'  
  END
				
EXEC(@SQL)

--=============================业务处理【END】=======================================



--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#Dtype,#Etype,#Ktype,#Ptype,#Stype,#BillIndex,#PageDtype,#SaleBill

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_DepreciationScheduleMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].WEB_DepreciationScheduleMonth
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2013/05/27
	Description	: 月折旧计划表
*/

CREATE PROCEDURE WEB_DepreciationScheduleMonth 
(
   @Stypeid			VARCHAR(50),
   @Dtypeid			VARCHAR(max),
   @Datestart		VARCHAR(max),          ---入账日期
   @Dateend			VARCHAR(max),          ---入账日期
   @startyear		INT,		   
   @endyear			INT,		   
   @startMonth		INT,
   @endMonth		INT,
   @cardid			VARCHAR(max),  --资产名称
   @categoryid			VARCHAR(max),  --资产类别
   @Status			INT,		   ---折旧状态2全部1已折旧0计划中
   @chvOperatorID	VARCHAR(50)	   ---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	CREATE TABLE #Stype(typeid varchar(50),verifyStypeid varchar(50))
	CREATE TABLE #Dtype(typeid VARCHAR(50))
	CREATE TABLE #Cards(ID INT)
	CREATE TABLE #AssetsType(CategoryId INT)
	
	INSERT INTO #Stype(typeid,verifyStypeid)
	SELECT TypeId
			,VERIFYID
	FROM	SType
	WHERE	TypeId = @Stypeid
	
	INSERT INTO #Dtype(typeid)
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Dtypeid,9,@chvOperatorID)

	IF @cardid<>''
		INSERT INTO #Cards(ID)
		SELECT a FROM dbo.f_split(@cardid,',')
	ELSE 
		INSERT INTO #Cards(ID)
		SELECT Id FROM dbo.Ac_AssetsCards
		
	IF @categoryid<>''
		INSERT INTO #AssetsType(CategoryId)
		SELECT a FROM dbo.f_split(@categoryid,',')
	ELSE 
		INSERT INTO #AssetsType(CategoryId)
		SELECT Id FROM Ac_AssetsCategory WHERE Deleted=0
		          
DECLARE @Fyear INT,@Fperiod INT,@verifyStypeid VARCHAR(50)--独立核算机构
--获取指定分支机构当前年度,财务期间	
SELECT @verifyStypeid=VerifyID FROM dbo.SType WHERE TypeId=@Stypeid

IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @verifyStypeid)
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @verifyStypeid
ELSE 
	BEGIN
		SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName='fyear'
		SELECT @FPeriod=SubValue FROM dbo.sysdata WHERE SubName='fperiod'
	END
	
	SELECT ad.id AS DepPlanId,
		   ac.Id AS cardid,
		   ac.STypeId,
		   ac.DTypeid, --这是卡片上部门的基本信息
		   ac.fullname,
		   ac.UserCode,
		   ac.InAccountDate,
		   ac.CategoryId, 
		   al.Location AS LocationId,
		   ac.Comment,
		   CASE WHEN ad.PlanState=0 THEN '计划中' 
				ELSE '已折旧' END AS planstate,
		   ad.PlanState AS tempPlanState,      --最后查询结果用
		   dd.FullName AS owndepartment,   --所属部门
		   CASE WHEN f.Typeid IS NULL THEN (CASE WHEN ISNULL(ac.DepATypeId,'')='' THEN '' ELSE  '****'  END ) ELSE  aa.FullName END AS depatypeid,  --累计折旧科目
		   CASE WHEN f1.Typeid IS NULL THEN (CASE WHEN ISNULL(ac.DisATypeId,'')='' THEN '' ELSE  '****'  END ) ELSE  aa1.FullName END AS disatypeid, --折旧分配
		  -- CASE WHEN ad.DepreciationMean=0 THEN '不折旧'   
				--WHEN ad.DepreciationMean=1 THEN '手工折旧'   
				--WHEN ad.DepreciationMean=2 THEN '平均年限法'   
				--WHEN ad.DepreciationMean=3 THEN '双倍余额递减法'       --0.不折旧/1.手工折旧/2.平均年限法/3.双倍余额递减法
		  -- END AS depreciationmean,
		   apm.Comment AS depreciationmean,
		   ad.YearOrder,
		   ad.MonthOrder,
		   ad.FYear,
		   ad.fperiod,
		   ad.Depreciation,
		   ad.deptotal,
		   ad.Total,
		   ad.DevalueReady,
		   ad.NetValue,
		   ad.NetSalvage,
		   CASE WHEN PlanState=1 THEN 1
		        WHEN PlanState=0 AND ad.FYear=@Fyear AND ad.fperiod=@FPeriod THEN 2 
		        ELSE 0 END 
		   as flag,  --grid显示颜色用,
		   BillNumberId
	INTO #temp1   
	FROM Ac_DepreciationPlan ad 
	LEFT JOIN Ac_DepreciationMean apm ON apm.Id = ad.DepreciationMean
	JOIN dbo.Ac_AssetsCards ac ON ad.AssetCardId=ac.Id AND (@Datestart IS NULL OR (@Datestart IS NOT NULL  AND  ac.InAccountDate>=@Datestart)) 
														AND (@Dateend IS NULL OR (@Dateend IS NOT NULL AND  ac.InAccountDate<=@Dateend))
	JOIN #Stype s ON ac.stypeid=s.typeid
	JOIN #Dtype d ON ac.dtypeid=d.typeid
	JOIN #Cards c ON ac.id=c.id  
	JOIN #AssetsType a ON ac.CategoryId=a.CategoryId
	LEFT JOIN dbo.Department dd ON ad.DTypeid=dd.typeid
	LEFT JOIN dbo.Ac_Account aa ON ac.DepATypeId=aa.TypeId AND s.verifyStypeid=aa.StypeId
	LEFT JOIN F_LineAccount(@chvOperatorID,@verifyStypeid) F ON F.Typeid = ac.DepATypeId --AND F.Stypeid = aa.StypeId
	LEFT JOIN dbo.Ac_Account aa1 ON ad.DisATypeId=aa1.TypeId AND s.verifyStypeid=aa1.StypeId
	LEFT JOIN F_LineAccount(@chvOperatorID,@verifyStypeid) F1 ON F1.Typeid = ad.DisATypeId --AND F1.Stypeid = aa1.StypeId
	LEFT JOIN dbo.Ac_AssetStorageLocation al ON ad.LocationId=al.Id
 	WHERE ad.FYear>=@startyear AND ad.FYear<=@endyear AND PlanType=1
 	-- AND  ((@Status!=2 AND PlanState=@Status) OR (@Status=2 AND PlanState!=2))   --修复当期初始化，当期未折旧就做减少单的bug，把这个判断条件放到最后
	  
	---剔除多余的数据
	DELETE FROM #temp1 WHERE FYear=@startyear AND fperiod<@startMonth  
	DELETE FROM #temp1 WHERE FYear=@endyear AND fperiod>@endMonth 
	 
	--把期初加上，清理数据加上
	INSERT INTO #temp1 
	SELECT ad.ID,ad.AssetCardId,ad.STypeId, ad.DTypeid, aah.fullname,aah.UserCode,aah.InAccountDate,aah.CategoryId,al.Location AS LocationId,aah.Comment,'',3,
		   dd.FullName AS owndepartment,   --所属部门
		   CASE WHEN f.Typeid IS NULL THEN '****' ELSE  aa.FullName END AS depatypeid,  --累计折旧科目
		   CASE WHEN f1.Typeid IS NULL THEN '****' ELSE  aa1.FullName END AS disatypeid, --折旧分配
		  '',
		   ad.YearOrder,
		   ad.MonthOrder,
		   ap.FYear,
		   ap.FPeriod, 
		   --ad.FYear,
		   --ad.FPeriod,
		   ad.Depreciation,
		   ad.deptotal,
		   ad.Total,
		   ad.DevalueReady,
		   ad.NetValue,
		   ad.NetSalvage,
		   0,0 
	FROM dbo.Ac_DepreciationPlan ad
	LEFT JOIN Ac_AssetsCards_History aah ON ad.AssetCardId=aah.AssertsCardId AND (aah.BillType=0 OR aah.BillType=212)
	LEFT JOIN #Stype S ON S.typeid = aah.STypeId
	LEFT JOIN dbo.Ac_Period ap ON aah.BusinessDate>=ap.FBegin AND aah.BusinessDate<=ap.FEnd
	LEFT JOIN Ac_AssetStorageLocation al ON aah.LocationId=al.Id
	LEFT JOIN dbo.Department dd ON ad.DTypeid=dd.typeid
	LEFT JOIN dbo.Ac_Account aa ON aah.DepATypeId=aa.TypeId AND S.verifyStypeid=aa.StypeId
	LEFT JOIN F_LineAccount(@chvOperatorID,@verifyStypeid) F ON F.Typeid = aa.TypeId --AND F.Stypeid = aa.StypeId
	LEFT JOIN dbo.Ac_Account aa1 ON aah.DisATypeId=aa1.TypeId AND S.verifyStypeid=aa1.StypeId
	LEFT JOIN F_LineAccount(@chvOperatorID,@verifyStypeid) F1 ON F1.Typeid = aa1.TypeId --AND F1.Stypeid = aa1.StypeId
	WHERE ad.PlanType=2 AND ad.AssetCardId IN (SELECT DISTINCT cardid FROM #temp1) AND --把期间的比较转换成日期比较，减少难度
   CONVERT(DATE, cast(ad.FYear as varchar) +'-'+cast(ad.FPeriod as varchar)+'-01')>=CONVERT(DATE,cast(@startyear as varchar)+'-'+cast(@startMonth as varchar)+'-01') AND 
   CONVERT(DATE, cast(ad.FYear as varchar) +'-'+cast(ad.FPeriod as varchar)+'-01')<=CONVERT(DATE,cast(@endyear as varchar)+'-'+cast(@endMonth as varchar)+'-01')     
	ORDER BY aah.BusinessDate 
 
	INSERT INTO #temp1  
	SELECT ad.ID,ad.AssetCardId,ad.STypeId, ad.DTypeid, aah.fullname,aah.UserCode,aah.InAccountDate,aah.CategoryId,al.Location AS LocationId,aah.Comment,'',3,
		   dd.FullName AS owndepartment,   --所属部门
		   CASE WHEN f.Typeid IS NULL THEN (CASE WHEN ISNULL(aah.DepATypeId,'')='' THEN '' ELSE  '****'  END ) ELSE  aa.FullName END AS depatypeid,  --累计折旧科目
		   CASE WHEN f1.Typeid IS NULL THEN  (CASE WHEN ISNULL(aah.DisATypeId,'')='' THEN '' ELSE  '****'  END )  ELSE  aa1.FullName END AS disatypeid, --折旧分配
		  '', 
		   ad.YearOrder,
		   ad.MonthOrder,
		   ad.FYear,
		   ad.FPeriod,
		   ad.Depreciation,
		   ad.deptotal,
		   ad.Total,
		   ad.DevalueReady,
		   ad.NetValue,
		   ad.NetSalvage,
		   0,0 
	FROM dbo.Ac_DepreciationPlan ad
	LEFT JOIN Ac_AssetsCards_History aah ON ad.AssetCardId=aah.AssertsCardId AND aah.BillType=213
	LEFT JOIN #Stype S ON S.typeid = aah.STypeId
	LEFT JOIN Ac_AssetStorageLocation al ON aah.LocationId=al.Id
	LEFT JOIN dbo.Department dd ON ad.DTypeid=dd.typeid
	LEFT JOIN dbo.Ac_Account aa ON aah.DepATypeId=aa.TypeId AND s.verifyStypeid=aa.StypeId
	LEFT JOIN F_LineAccount(@chvOperatorID,@verifyStypeid) F ON F.Typeid = aa.TypeId --AND F.Stypeid = aa.StypeId
	LEFT JOIN dbo.Ac_Account aa1 ON aah.DisATypeId=aa1.TypeId AND s.verifyStypeid=aa1.StypeId
	LEFT JOIN F_LineAccount(@chvOperatorID,@verifyStypeid) F1 ON F1.Typeid = aa1.TypeId --AND F1.Stypeid = aa1.StypeId
	WHERE ad.PlanType=3 AND ad.AssetCardId IN (SELECT DISTINCT cardid FROM #temp1) AND--把期间的比较转换成日期比较，减少难度
   CONVERT(DATE, cast(ad.FYear as varchar) +'-'+cast(ad.FPeriod as varchar)+'-01')>=CONVERT(DATE,cast(@startyear as varchar)+'-'+cast(@startMonth as varchar)+'-01') AND 
   CONVERT(DATE, cast(ad.FYear as varchar) +'-'+cast(ad.FPeriod as varchar)+'-01')<=CONVERT(DATE,cast(@endyear as varchar)+'-'+cast(@endMonth as varchar)+'-01')     
	  
	 
	   
	---查询结果
	SELECT DepPlanId,cardid,214 AS billtype,planstate,owndepartment,depatypeid,disatypeid,depreciationmean,YearOrder,
			FYear,fperiod,Depreciation,deptotal,Total,DevalueReady,NetValue,NetSalvage,flag,BillNumberId,LocationId,
			CASE WHEN YearOrder=0 THEN '初始' WHEN YearOrder=999999 THEN '清理' ELSE CONVERT(varchar(5),YearOrder) END AS yearorder1,
			CASE WHEN MonthOrder=0 THEN '' WHEN MonthOrder=999999 THEN '' ELSE CONVERT(varchar(5),MonthOrder) END AS MonthOrder1
	FROM #temp1 
	WHERE ((@Status!=2 AND (tempPlanState=@Status OR tempPlanState=3)) OR (@Status=2 AND tempPlanState!=2))
	ORDER BY UserCode,YearOrder,FYear,MonthOrder,fperiod
	DROP TABLE #temp1,#Stype,#Dtype,#Cards,#AssetsType
	
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_DepreciationScheduleYear]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].WEB_DepreciationScheduleYear
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2013/05/27
	Description	: 年折旧计划表
*/

CREATE PROCEDURE WEB_DepreciationScheduleYear 
(
   @Stypeid			VARCHAR(50),
   @Dtypeid			VARCHAR(max),
   @Datestart		VARCHAR(max),          ---入账日期
   @Dateend			VARCHAR(max),          ---入账日期
   @startyear		INT,		   
   @endyear			INT,		   
   @cardid			VARCHAR(max),  --资产名称
   @categoryid			VARCHAR(max),  --资产类别
   @chvOperatorID	VARCHAR(50)	   ---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	CREATE TABLE #Stype(typeid varchar(50))
	CREATE TABLE #Dtype(typeid VARCHAR(50))
	CREATE TABLE #Cards(ID INT)
	CREATE TABLE #AssetsType(CategoryId INT)
	
	INSERT INTO #Stype(typeid)
	SELECT @Stypeid
	
	INSERT INTO #Dtype(typeid)
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Dtypeid,9,@chvOperatorID)
	
	IF @cardid<>''
		INSERT INTO #Cards(ID)
		SELECT a FROM dbo.f_split(@cardid,',')
	ELSE 
		INSERT INTO #Cards(ID)
		SELECT Id FROM dbo.Ac_AssetsCards
		
	IF @categoryid<>''
		INSERT INTO #AssetsType(CategoryId)
		SELECT a FROM dbo.f_split(@categoryid,',')
	ELSE 
		INSERT INTO #AssetsType(CategoryId)
		SELECT Id FROM Ac_AssetsCategory  WHERE Deleted=0
		          
	DECLARE @Fyear INT,@Fperiod INT
--获取指定分支机构当前年度,财务期间	
IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Stypeid)
	SELECT @FYear = FYear,@FPeriod = FPeriod FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Stypeid
ELSE 
	BEGIN
		SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName='fyear'
		SELECT @FPeriod=SubValue FROM dbo.sysdata WHERE SubName='fperiod'
	END
	
	SELECT ac.Id AS cardid,
	       ad.usercode,
		  -- CASE WHEN ad.DepreciationMean=0 THEN '不折旧'   
				--WHEN ad.DepreciationMean=1 THEN '手工折旧'   
				--WHEN ad.DepreciationMean=2 THEN '平均年限法'   
				--WHEN ad.DepreciationMean=3 THEN '双倍余额递减法'       --0.不折旧/1.手工折旧/2.平均年限法/3.双倍余额递减法
		  -- END AS depreciationmean,
		   apm.Comment AS depreciationmean,
		   ad.YearOrder,
		   ad.fperiod,
		   ad.FYear,
		   ad.Depreciation,
		   ad.deptotal,
		   ad.Total,
		   ad.DevalueReady,
		   ad.NetValue,
		   ad.NetSalvage,
		   planstate,
		   CASE WHEN PlanState=1 THEN 1
		        WHEN ad.Fyear=@Fyear THEN 2 
		        ELSE 0 END 
		   as flag  --grid显示颜色用  
	INTO #Data 
	FROM Ac_DepreciationPlan ad 
	LEFT JOIN Ac_DepreciationMean apm ON apm.Id = ad.DepreciationMean
	JOIN dbo.Ac_AssetsCards ac ON ad.AssetCardId=ac.Id AND (@Datestart IS NULL OR (@Datestart IS NOT NULL  AND  ac.InAccountDate>=@Datestart)) 
														AND (@Dateend IS NULL OR (@Dateend IS NOT NULL AND  ac.InAccountDate<=@Dateend))
	JOIN #Stype s ON ac.stypeid=s.typeid
	JOIN #Dtype d ON ac.dtypeid=d.typeid
	JOIN #Cards c ON ac.id=c.id  
	JOIN #AssetsType a ON ac.CategoryId=a.CategoryId
	JOIN (
			SELECT AssetCardId,YearOrder FROM dbo.Ac_DepreciationPlan  WHERE PlanType=1 AND FYear>=@startyear AND FYear<=@endyear GROUP BY AssetCardId,YearOrder
	     ) y ON ad.AssetCardId=y.AssetCardId AND  ad.YearOrder=y.YearOrder   --年份查询条件,当年的年份用蓝色
	LEFT JOIN dbo.Department dd ON ad.DTypeid=dd.typeid
 	WHERE  PlanType=0 
 	--AND ad.PlanState<2  --修复当期初始化，当期未折旧就做减少单的bug，把这个判断条件放到最后
	
	---期初数据，清理数据
	INSERT INTO #Data 
	SELECT AssetCardId,UserCode,'',0,null,FYear,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,-1,0 
	FROM dbo.Ac_DepreciationPlan 
	WHERE PlanType=2 AND AssetCardId IN (SELECT DISTINCT cardid FROM #Data ) AND FYear>=@startyear AND FYear<=@endyear
	UNION ALL
	SELECT AssetCardId,UserCode,'',999999,null,FYear,Depreciation,DepTotal,Total,DevalueReady,NetValue,NetSalvage,-1,0 
	FROM dbo.Ac_DepreciationPlan 
	WHERE PlanType=3 AND AssetCardId IN (SELECT DISTINCT cardid FROM #Data ) AND FYear>=@startyear AND FYear<=@endyear
	
	SELECT *,CASE WHEN YearOrder=0 THEN '初始' WHEN YearOrder=999999 THEN '清理' ELSE CONVERT(varchar(5),YearOrder) END AS yearorder1 
	FROM #Data 
	WHERE planstate<2
	ORDER BY UserCode,YearOrder
	
	DROP TABLE #Stype,#Dtype,#Cards,#AssetsType,#Data
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
 




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Diy_FindDiyDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Diy_FindDiyDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：根据所给的BillNumberId查询单据明细
-------------------------------------------*/
CREATE PROCEDURE Web_Diy_FindDiyDetail
(
	@BillNumberId NUMERIC(10,0)   --选择的类型或结构名称
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
  
	SELECT  b.FullName name,
            a.FullName,
            e.SalePrice,
            e.Qty,
		    e.Comment,
            c.EtypeId,
            c.IndexOrderId,
            c.ToTalQty,
            c.TotalMoney,
            d.FullName username 
     FROM   DiyBill e
            inner Join ptype a ON a.typeId = e.PtypeId
            left join  DiyType b ON b.typeId = e.typeId 
            left join DiyIndex c ON c.BillNumberId=e.BillNumberId 
            left join employee d ON d.typeId=c.EtypeId
     WHERE e.BillNumberId =@BillNumberId
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Diy_FindDiyOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Diy_FindDiyOrderBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：导入销售出库单时查询的内容
-------------------------------------------*/
CREATE PROCEDURE Web_Diy_FindDiyOrderBill
(
    @OperatorID  		varchar(50), 
	@BillNumberId NUMERIC(10,0),   --选择的类型或结构名称
	@chvSTypeid varchar(200)=''--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构物价信息
DECLARE @PriceType varchar(5)
SELECT @PriceType=PriceType FROM SType WHERE TypeId=@chvSTypeid

CREATE TABLE #Ptype (TypeID varchar(200))

--商品
INSERT INTO #Ptype select typeid from F_GetAllManagerBaseTypeId('',1,@OperatorID)

BEGIN 
    SELECT  b.*,
            b.Unit1 AS unitone,
			b.Unit2 As unittwo,			
			--b.Unitrate1 As Unitrate,
            --b.FullName,
            b.UserCode usercode,
            b.typeId typeid,
            c.Comment base,
            c.EtypeId,
            a.SalePrice price, 
            c.IndexOrderId,
            c.BillDate,
            a.Comment AS mxcomment,
            a.Qty qty,
            a.SaleTotal AS total,
            d.FullName username,
             0 AS Tax,
             1 AS rate,
			a.SalePrice AS TaxPrice,
			a.SaleTotal AS TaxTotal,
			a.SalePrice AS DiscountPrice,
			a.SaleTotal AS DiscountTotal,
			a.SalePrice AS nsaleprice,
			pt.SaleUnitId  AS munitid,
			pt.nunitid  AS nunitid,
			pt.unitid  AS unitid,
			pt.saleunitname  AS munit,
			pt.nunit  AS nunit,
			pt.unit  AS unit,
			pt.salemunitrate AS munitrate,
			pt.unitrate  AS unitrate,
			pt.ifusegoodsnum,
			(dbo.F_GetAllEntrycode(a.pTypeID,pt.SaleUnitId,2)) AS salemunitcode,
			
            (select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname1,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname2,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname3,
			(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate1,
			(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate2,
			(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate3,
			(select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=a.ptypeid  and STYPEID=@chvSTypeid AND UnitID = b.baseUnitId) AS SReferPrice,
	 		(select ISNULL(ReferPrice,0) from PType_Price where PTypeID=a.ptypeid AND UnitID = b.baseUnitId )  AS PReferPrice,
	 		@PriceType as pricetype,
	 		bc.typeid AS brandartypeid,
	 		bc.UserCode AS brandarusercode,
	 		bc.fullname AS brandarfullname
		FROM DiyBill a
        inner Join Ptype b ON b.typeId = a.PtypeId            
        LEFT JOIN dbo.brandar_Commodity bc ON bc.typeid = b.brandartypeid
        inner Join #Ptype p ON p.typeId = b.typeId
        left join  DiyIndex c ON c.BillNumberId=a.BillNumberId 
        left join employee d ON d.typeId=c.EtypeId
        LEFT JOIN PType_Units u ON u.UnitsId=b.baseUnitId
        LEFT JOIN (SELECT * FROM F_GetPtypeUnitInfo()) pt ON pt.typeId=a.PtypeId         
      WHERE a.BillNumberId =@BillNumberId    
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Diy_FindDiyStruceName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Diy_FindDiyStruceName]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：根据所选类型匹配产品
-------------------------------------------*/
CREATE PROCEDURE Web_Diy_FindDiyStruceName
(
    @OperatorID  		varchar(50),   -- 操作员Id   
	@Name               VARCHAR(max),   --选择的类型或结构名称
	@Structname         VARCHAR(max) 
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype (TypeID varchar(200))

--商品
INSERT INTO #Ptype select typeid from F_GetAllManagerBaseTypeId('',1,@OperatorID)


DECLARE 
		@typeId         VARCHAR(50),
		@structid       VARCHAR(max)

--当前分类下所有品牌时，查出所有品牌
IF @Name = ''
BEGIN
	SELECT @structid = typeId FROM DiyType WHERE FullName=@Structname AND IsSys=1	
END
ELSE
BEGIN
	SELECT @structid = typeId FROM DiyType WHERE FullName=@Name AND IsSys = 0
END

SELECT P.TypeId,P.FullName,t.ImgURL,OrderID,R.RetailPrice FROM PType P 
         INNER JOIN dbo.PType_Price R ON R.PTypeID = P.TypeId
         inner JOIN (DiyTypePTypeID inner JOIN DiyType ON DiyType.typeId=DiyTypePTypeID.Diytypeid)
         ON  P.typeId=DiyTypePTypeID.Ptypeid 
         INNER JOIN #Ptype pty ON pty.TypeID = p.typeId
         LEFT JOIN PType_Picture t ON pty.TypeID = t.PTypeID
         WHERE DiyType.typeId like   @structid  + '%'
         AND P.deleted = 0
         ORDER BY FullName DESC
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_DIY_QUERYDIYBILL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_DIY_QUERYDIYBILL]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-5-13
	描述：配置单详情
-------------------------------------------*/
CREATE PROCEDURE WEB_DIY_QUERYDIYBILL
(
	@indexID		VARCHAR(MAX),
	@BillDate		DATETIME,
	@UserCode		VARCHAR(MAX),
	@IndexOrderId	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

Create table #indexorderid 
(
 ParId varchar(500),
 IndexOrderId  varchar(500)
)


EXEC GP_Diy_GetIndexOrderId @BillDate,@UserCode, @IndexOrderId out


insert into #indexorderid (ParId,IndexOrderId) values ('00000',@IndexOrderId)

SELECT	t.typeId	AS	typeid,
		t.FullName	AS	fullname,
		i.EtypeId,
		i.TotalMoney AS totalprice,
		(SELECT FullName FROM dbo.employee WHERE typeid = i.EtypeId) AS etypefullname,
		(SELECT FullName FROM dbo.employee WHERE typeid = i.Checke) AS Checke,
		ISNULL(p.typeId,'') AS ptypeid,
		ISNULL(p.FullName,'-') AS pfullname,
		ISNULL(b.Qty,0)	AS	qty,
		ISNULL(b.SalePrice,0) AS	saleprice,
		ISNULL(b.Comment,'')	AS	remark,
		ISNULL(i.IndexOrderId,'') AS indexorderid,
		ISNULL(i.ToTalQty,0)	AS	totalqty,
		ISNULL(i.TotalMoney,0) AS	totalmoney,
		ISNULL(i.Comment,'')	AS	billremark,
		#indexorderid.IndexOrderId as orderId
FROM  DiyType	t
LEFT JOIN DiyBill b ON b.typeId=t.typeId AND B.BillNumberId=@indexID
LEFT JOIN PType	P ON P.typeId=b.PtypeId
LEFT JOIN DiyIndex	i ON i.BillNumberId=b.BillNumberId  
inner join #indexorderid on #indexorderid.ParId=t.ParId
WHERE t.ParId='00000'
drop table  #indexorderid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_DIY_QueryDiyType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_DIY_QueryDiyType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-27
	描述：电脑配件分类
-------------------------------------------*/
CREATE PROCEDURE WEB_DIY_QueryDiyType
(
	@OperatorID		VARCHAR(MAX),	--操作员ID
	@ParentId		VARCHAR(MAX),	---父类ID
	@DIYTypeId	    VARCHAR(MAX),
	@TypeLeave		INT	
)
--@encode$--
AS
SET NOCOUNT ON
IF(@TypeLeave=1)
BEGIN
	SELECT	typeId,
			ParId,
			TypeNumber,
			FullName,
			Name,
			sonnum,
			Remark
	FROM	DiyType 
	WHERE	leveal=@TypeLeave
	ORDER BY TypeNumber
RETURN
END

IF(@TypeLeave=2)
BEGIN
	SELECT	typeId,
			ParId,
			TypeNumber,
			FullName,
			Name,
			sonnum,
			Remark
	FROM	DiyType 
	WHERE	ParId=@DIYTypeId
	ORDER BY TypeNumber
RETURN
END
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@OperatorID)

SELECT	b.typeId	ParId,
		b.ParId		typeId,
		c.sonnum	sonnum,
		c.typeId	ptypeid,
		c.UserCode	TypeNumber,
		c.FullName	FullName,
		c.Name		name,
		c.Comment	Remark,
		C.deleted	deleted,
		c.StopBuy	stopbuy
FROM	DiyTypePTypeID a
INNER JOIN DiyType b ON b.typeId=a.Diytypeid
INNER JOIN ptype C ON a.Ptypeid=c.typeId
WHERE	1=1
AND		b.typeId=@DIYTypeId 
AND		C.typeId IN (SELECT TypeId FROM #GetManPTypeId)
ORDER BY C.UserCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_DIY_QueryGoodsList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_DIY_QueryGoodsList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-4-27
	描述：查询商品
-------------------------------------------*/
CREATE PROCEDURE WEB_DIY_QueryGoodsList
(
	@OperatorID	VARCHAR(MAX),	---操作员ID
	@usercode	VARCHAR(MAX),	---编号
	@fullname	VARCHAR(MAX),	---全名	
	@entrycode	VARCHAR(MAX)	---条码
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ptype (TypeID varchar(200))
INSERT INTO #Ptype(typeid) select typeid from F_GetManDetailPType(@OperatorID)

SELECT	P.*,
		UserCode,
		FullName,
		entrycode,
		comment
FROM	ptype P
INNER JOIN #Ptype PP ON PP.TypeID=P.typeId
--INNER JOIN PType_Price pr ON p.typeId=pr.PTypeID 
WHERE	p.IsService = 0
		AND	(UserCode	like '%'+@usercode+'%' OR PyCode like '%'+@usercode+'%')
		AND	(FullName	LIKE '%'+@fullname+'%' OR PyCode like '%'+@fullname+'%')
		AND	EntryCode	LIKE '%'+@entrycode+'%'
		AND	sonnum=0
		AND p.typeId not in (select Ptypeid from DiyTypePTypeID)
		AND deleted='0'
		AND ParId!='root'
		AND iscombinationproduct = 0
ORDER BY P.usercode
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Diy_SerchDiyOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Diy_SerchDiyOrderBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：查询Diy配置单
-------------------------------------------*/
CREATE PROCEDURE Web_Diy_SerchDiyOrderBill
(
   @OperatorId			VARCHAR(MAX),	
   @BeginBillDate  VARCHAR(20),  --开始时期
   @EndBillDate    VARCHAR(20),  --结束时期
   @EtypeId        VARCHAR(50),  ---制单人  
   @IndexOrderId   VARCHAR(500), ---单据编号
   @Comment        VARCHAR(500)  ----说明
)
--@encode$--
AS

SET NOCOUNT ON
BEGIN 
   
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


CREATE TABLE #Etype (TypeID varchar(50))

--职员
INSERT INTO #Etype select typeid from F_GetAllManagerBaseTypeId(@Etypeid,3,@OperatorID)

	DECLARE @str VARCHAR(MAX)
	SET @str='select *,
	                (SELECT FullName from employee WHERE typeid = DiyIndex.checke) as checkename
	          FROM DiyIndex
	          INNER JOIN #Etype e on e.typeid = DiyIndex.etypeid  
	          WHERE BillDate>='''+@BeginBillDate+'''
              AND BillDate<='''+@EndBillDate+'''
              AND IndexOrderId LIKE ''%' + @IndexOrderId + '%'' 
              AND Comment LIKE ''%' + @Comment + '%'''          
IF  @EtypeId <>''  SET @str= @str + 'AND EtypeId=''' + @EtypeId +''''
	
	 --    BEGIN
--		 EXEC (@str)
--		 RETURN
--	 END
 --  ELSE
	-- BEGIN
	--	 SET @typeid=(SELECT (right((SELECT cast((100000+'00001') AS VARCHAR)),5)) AS VARCHAR)
	--	 EXEC (@str+ 'and EtypeId=''' + @typeid +'''')
	--END
 EXEC (@str)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_DTypeGatherDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_DTypeGatherDetailQuery]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：黄飞佳	
	日期：2012-05-24
	描述:部门销售汇总明细
*/
/*
    修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
    
    修改：舒珊
    日期：2015-05-27
    描述： 添加商品类别筛选
    
    修改：舒珊
    日期：2016-06-21
    描述： 换算率变更前销售单位数量统计
*/
/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Web_DTypeGatherDetailQuery
(
	@chvStartDate		VARCHAR(30),			-- 查询起始时间
	@chvENDDate		    VARCHAR(30),			-- 查询结束时间
	@chvPTypeID			VARCHAR(max),			-- 树型表或线性表商品类别查询范围父节点 ID
	@chvBTypeID			VARCHAR(max),			-- 结算单位
	@chvETypeID			VARCHAR(max),			-- 树型表或线性表职员类别查询范围父节点 ID
	@chvKTypeID			VARCHAR(max),			-- 树型表或线性表仓库类别查询范围父节点 ID
	@chvDTypeID			VARCHAR(max),			-- 树型表或线性表部门类别查询范围父节点 ID
	@chvStypeID			VARCHAR(max)='00000',	-- 树型表或线性表分支机构类别查询范围父节点 ID
	@sortfield			VARCHAR(50),			-- 明细表排序方式
	@checkCode			VARCHAR(max)= '',	    -- 制单人编号
	@checkName			VARCHAR(max)= '',	    -- 制单人名称
	@chvOperatorID		VARCHAR(50),			-- 操作员 ID ( 作权限范围检查用 )
	@chkRed        		CHAR(1) ='0',		    -- 显示红冲单据
	@chvBilltype    	VARCHAR(200),           -- 单据类型
	@chvComment     	VARCHAR(200)='',        -- 说明
	@chvZY 				VARCHAR(200)='',        -- 摘要
	@dealbtypeid        VARCHAR(max),           -- 往来单位
	@chvPF        		CHAR(1) ='0'  ,          --价保获利反利等
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON

--------权限检查-Start--------
IF @chvOperatorID is null RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re <> 0 RETURN @Re
--------权限检查-End--------  


--------创建临时表-Start--------
--单据类型
CREATE TABLE #Billtype (BillType VARCHAR(200))
INSERT INTO #Billtype SELECT a AS Billtype FROM dbo.f_split(@chvBilltype,',')

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Ktype SELECT typeid,usercode,fullname FROM Stock WHERE typeId in(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvKTypeID,4,@chvOperatorID))
IF (@chvKTypeID='10000' OR  @chvKTypeID='' OR  @chvKTypeID='00000') AND NOT EXISTS(SELECT * FROM #Ktype WHERE typeid='10000') 
INSERT INTO #Ktype SELECT '10000','10000','代销仓库'

	
--商品
CREATE TABLE #Ptype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Ptype SELECT typeid,usercode,fullname FROM Ptype WHERE typeid IN(SELECT typeid FROM F_ManPTypeInCategoryID ( @chvOperatorID,@chvPTypeID,@ptypecategoryid))

--分支机构
CREATE TABLE #Stype (TypeID VARCHAR(50))
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvSTypeID,11,@chvOperatorID)

--结算单位	
CREATE TABLE #Btype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Btype SELECT typeid,usercode,fullname FROM Btype WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBTypeID,2,@chvOperatorID))

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #DealBtype SELECT typeid,usercode,fullname FROM Btype WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID))
--职员
CREATE TABLE #Etype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Etype SELECT typeid,usercode,fullname FROM Employee WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvETypeID,3,@chvOperatorID))

--部门
CREATE TABLE #Dtype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Dtype SELECT typeid,usercode,fullname FROM Department WHERE typeid IN( SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@chvOperatorID))

--费用分摊设置
DECLARE @config int=0
SELECT	@config=Value FROM Userconfig WHERE ConfigName='sharefee'	

	

--------创建索引Start-------
CREATE CLUSTERED INDEX CIX_GetManKTypeID ON #Ktype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManETypeID ON #Etype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManPTypeID ON #Ptype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManSTypeID ON #Stype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManBTypeID ON #Btype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManDTypeID ON #Dtype(TypeID)
--------创建索引End-------

--单据索引表
	CREATE TABLE #BillIndex
	(
	    BillNumberID NUMERIC(18,0),
	    BillCode VARCHAR(200),
	    BillDate DATETIME,
	    Billtype NUMERIC(10,0),
	    Tax  NUMERIC(24, 10) ,
	    RedWord INT,
		TotalMoney  NUMERIC(24, 10) ,
		TotalInMoney  NUMERIC(24, 10) ,
		CompleteTotal  NUMERIC(24, 10) ,
		BTypeID  VARCHAR (50),
		ETypeID  VARCHAR (50),
		ID			INT,
		PTypeID  VARCHAR (50),
		KTypeID  VARCHAR (50),
		PreferenceMoney  NUMERIC(24, 10) ,
		DtypeID VARCHAR(50),
		Checke  VARCHAR(50),
		Stypeid   VARCHAR(50),
		Draft BIT,
		Posttime DATETIME,
		Dealbtypeid VARCHAR(50),
		CName VARCHAR(200),
		Rate   NUMERIC(24, 10) ,
		Explain VARCHAR(MAX),
		comment	VARCHAR(2000)
	)

	DECLARE	@strBill   VARCHAR(MAX)
	SET @strBill = 
	             'INSERT INTO #BillIndex 
	              SELECT billnumberid,
	                     billcode,
	                     billdate,
	                     a.billtype,
	                     tax,
	                     redword,
	                     totalmoney,
	                     totalinmoney,
	                     completetotal,
	                     a.btypeid,
	                     a.etypeid,
						 A.ID,
	                     a.ptypeid,
	                     a.ktypeid,
	                     preferencemoney,
	                     a.dtypeid,
	                     checke,
	                     a.stypeid,
	                     a.draft,
	                     a.posttime,
	                     a.dealbtypeid,
	                     cu.fullname,
	                     a.rate,
	                     a.Explain,
	                     a.comment
	               FROM dbo.BillIndex a
	               INNER JOIN #Billtype b ON a.BillType = b.Billtype
	               INNER JOIN AC_Currency cu  ON a.cid = cu.cid
	               INNER JOIN #DealBtype dd ON a.dealbtypeid = dd.typeid '
	               IF (@chvBTypeID<>'' OR @MBTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF (@chvDTypeID<>'' OR @MDTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
                   IF (@chvETypeID<>'' OR @METypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Etype e ON a.etypeid = e.TypeID'
	               IF (@chvSTypeID<>'' OR @MSTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0''' 
	               
	               --增加发票立账405
	              SET @strBill += '
					UNION ALL 
					SELECT billnumberid,billcode,billdate,a.billtype,tax,redword,TotalMoney,0 as totalinmoney,completetotal,
					a.btypeid,a.etypeid,1 ID,'''' AS ptypeid,'''' AS ktypeid,TotalMoney AS preferencemoney,a.dtypeid,checke,
					a.stypeid,a.draft, posttime,a.dealbtypeid,cc.fullname,a.rate,
	                a.Explain ,a.comment
					FROM dbo.ReceiptBillIndex AS a 
					INNER JOIN #Billtype b ON a.BillType = b.Billtype
					INNER JOIN AC_Currency cc  ON a.cid = cc.cid 
					INNER JOIN #DealBtype dd ON a.dealbtypeid = dd.typeid '   
				   IF (@chvBTypeID<>'' OR @MBTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF (@chvDTypeID<>'' OR @MDTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
                   IF (@chvETypeID<>'' OR @METypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Etype e ON a.etypeid = e.TypeID'
	               IF (@chvSTypeID<>'' OR @MSTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0''' 
	--PRINT @strBill
	EXEC(@strBill)
--红冲
DECLARE @RED_WHERE varchar(200)
SET @RED_WHERE= ''
IF @chkRed ='0'
	SET @RED_WHERE ='  b.Redword='+char(39)+'0'+char(39)
ELSE
	SET @RED_WHERE =' 1=1 '
	
	
-- 确定查询时间段
DECLARE @SQL_WHERE varchar(2000)
SELECT  @SQL_WHERE = ' AND b.BillDate >= ''' + @chvStartDate + '''' + ' AND b.BillDate <= ''' + @chvENDDate + ''''	
----出入库表
    CREATE TABLE #InoutStockTable
    (
		BillNumberId numeric(18, 0) ,
		BillDate datetime,
		BillType numeric(10,0),
		ID			INT,
		PtypeId varchar (50),
		KtypeId varchar (50),
		Qty  NUMERIC(24, 10) ,
		Price    NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		taxprice  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		tax  NUMERIC(24, 10) ,
		costPrice  NUMERIC(24, 10) ,
		ShareFee  NUMERIC(24, 10) ,
		Cargoid INT,
		NPrice  NUMERIC(24, 10) ,
		NTotal  NUMERIC(24, 10) ,
		NSalePrice  NUMERIC(24, 10) ,
		NSaleTotal  NUMERIC(24, 10) ,
		NTaxPrice   NUMERIC(24, 10) ,
		NTaxTotal   NUMERIC(24, 10) ,
		FullName VARCHAR(2000),
		UserCode VARCHAR(200),
		NQty  NUMERIC(24, 10) ,
		MUnitID INT,
		NumName VARCHAR(200),
		Rate  NUMERIC(24, 10) ,
		nbrcqty  NUMERIC(24, 10) ,
		BaseUnitFullname  VARCHAR(50),
        AssistantFullname VARCHAR(50),
        GoodsNumber VARCHAR(100),
        dfullname		VARCHAR(200),
        saletotal		 NUMERIC(24, 10) ,
        saleprice		 NUMERIC(24, 10) ,
        comment			VARCHAR(1000),
		CustomdetailID int,
		zy  	VARCHAR(2000),
        discount    NUMERIC(24, 10)	
	)
	
	DECLARE @strInOut VARCHAR(MAX)
--**********************增加发票立账单据***********************--
 
	SET @strInOut = 
	         'INSERT INTO #InoutStockTable
				SELECT
				BillnumberID,																														
				BillDate,																														
				BillType,
				ID,																															
				PtypeID,																															
				KtypeID,
				Qty,
				price,
				Total,	  
				CostTotal,
				taxprice,  
				TaxTotal,
				tax,
				costprice,
				sharefee,
				cargoid,
				nprice,
				ntotal,
				nsaleprice,
				nsaletotal,
				ntaxprice,
				ntaxtotal,
				fullname,
				usercode,
				nqty,
				munitid,
				numname,
				rate,
				T.nbrcqty  AS nbrcqty,--换算率变更前销售单位数量
				baseunitfullname,
				assistantfullname,
				goodsnumber,
				dfullname,
				SaleTotal,
				SalePrice,
				comment,
				CustomdetailID,
				zy,
				discount
				FROM 
				(
					SELECT  
					b.BillnumberID,																														
					a.BillDate,																														
					a.BillType,		
					A.ID,																													
					a.PtypeID,																															
					a.KtypeID,
					a.Qty,
					a.price,
					a.Total,	  
					a.CostTotal,
					a.taxprice,  
					a.TaxTotal,
					a.tax,
					a.costprice,
					a.sharefee,
					a.cargoid,
					a.nprice,
					a.ntotal,
					a.nsaleprice,
					a.nsaletotal,
					a.ntaxprice,
					a.ntaxtotal,
					v.fullname,
					d.usercode,
					a.nqty,
					a.munitid,
					pu.fullname AS numname,
					pe.rate AS rate,
					CAST(-a.qty/a.MUnitRate AS  NUMERIC(24, 10) )  AS nbrcqty,--换算率变更前销售单位数量
					fg.baseunitfullname AS baseunitfullname,
					fg.assistantfullname AS assistantfullname,
					a.goodsnumber,
					d.Fullname as dfullname,
					SaleTotal,
					SalePrice,
					a.comment,
					a.id as CustomdetailID,
					b.comment as zy,
					a.discount
					FROM InoutStockTable a 
					INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID AND a.BillType = b.BillType 
					LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = a.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
					left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
					INNER JOIN #PType p ON a.PTypeID=p.typeid
					INNER JOIN #Dtype d ON d.typeid = b.dtypeid'
					
					IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
					  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
					SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
					IF (@checkCode<>'')
					  SET @strInOut = @strInOut + ' AND d.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
					IF (@checkName<>'')
					  SET @strInOut = @strInOut + ' AND d.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
		      
					SET @strInOut += '
					AND A.BillType NOT IN(402,403,405) 
					
					UNION ALL
					--发出商品出库单
					SELECT
					b.BillnumberID,																														
					B.BillDate,																														
					B.BillType,		
					A.ID,																													
					a.PtypeID,																															
					a.KtypeID,
					CASE T.RedWord
						WHEN 2 THEN a.Qty - a.InvoiceQty
						ELSE -(a.Qty - a.InvoiceQty) 
					END AS Qty,
					a.DiscountPrice AS Price,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
					END AS Total,
					CASE T.RedWord
						WHEN 2 THEN a.CostTotal - a.InvoiceCostTotal
						ELSE -(a.CostTotal - a.InvoiceCostTotal)
					END AS CostTotal,
					a.taxprice,  
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
					END AS TaxTotal,
					a.tax,
					a.costprice,
					a.sharefee,
					a.cargoid,
					a.NDiscountPrice AS nprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice)  END
					END AS ntotal,
					a.nsaleprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.nsaletotal ELSE (a.Qty - a.InvoiceQty) * a.NSalePrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.nsaletotal ELSE -((a.Qty - a.InvoiceQty) * a.NSalePrice) END
					END AS nsaletotal,
					a.ntaxprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
					END AS ntaxtotal,
					v.fullname,
					d.usercode,
					CASE T.RedWord
						WHEN 2 THEN a.NQty - a.InvoiceNQty
						ELSE -(a.NQty - a.InvoiceNQty)
					END AS nqty,
					a.munitid,
					pu.fullname AS numname,
					pe.rate AS rate,
					a.Mqty-(a.InvoiceQty*a.MunitRate)  AS nbrcqty,--换算率变更前销售单位数量
					fg.baseunitfullname AS baseunitfullname,
					fg.assistantfullname AS assistantfullname,
					a.goodsnumber,
					d.Fullname as dfullname,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.SaleTotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
						ELSE CASE a.InvoiceQty WHEN 0 THEN -a.SaleTotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
					END AS SaleTotal,
					A.SalePrice,
					a.comment,
					a.id as CustomdetailID,
					t.Comment AS zy,
					a.discount
					FROM SendBill AS A
					INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
					INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
					LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = a.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
					left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
					INNER JOIN #PType p ON a.PTypeID=p.typeid
					INNER JOIN #Dtype d ON d.typeid = b.dtypeid
					'
					IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
					  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
					SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
					IF (@checkCode<>'')
					  SET @strInOut = @strInOut + ' AND d.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
					IF (@checkName<>'')
					  SET @strInOut = @strInOut + ' AND d.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
					SET @strInOut += ' 
					AND T.ifYearBill = 0
					
					UNION ALL
					--发出商品退货单
					SELECT
					b.BillnumberID,																														
					B.BillDate,																														
					B.BillType,			
					A.ID,																															
					a.PtypeID,																															
					a.KtypeID,
					CASE T.RedWord
						WHEN 2 THEN -(a.Qty - a.InvoiceQty)
						ELSE a.Qty - a.InvoiceQty
					END AS Qty,
					a.DiscountPrice AS Price,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
					END AS Total,
					CASE T.RedWord
						WHEN 2 THEN -(a.CostTotal - a.InvoiceCostTotal)
						ELSE a.CostTotal - a.InvoiceCostTotal
					END AS CostTotal,
					a.taxprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
					END AS TaxTotal,
					a.tax,
					a.costprice,
					a.sharefee,
					a.cargoid,
					a.NDiscountPrice AS nprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
					END AS ntotal,
					a.nsaleprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.nsaletotal ELSE -((a.NQty - a.InvoiceNQty) * a.NSalePrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.nsaletotal ELSE (a.NQty - a.InvoiceNQty) * a.NSalePrice END
					END AS nsaletotal,
					a.ntaxprice,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
					END AS ntaxtotal,
					v.fullname,
					d.usercode,
					CASE T.RedWord
						WHEN 2 THEN -(a.NQty - a.InvoiceNQty)
						ELSE a.NQty - a.InvoiceNQty
					END AS nqty,
					a.munitid,
					pu.fullname AS numname,
					pe.rate AS rate,
					a.Mqty-(a.InvoiceQty*a.MunitRate)   AS nbrcqty,--换算率变更前销售单位数量
					fg.baseunitfullname AS baseunitfullname,
					fg.assistantfullname AS assistantfullname,
					a.goodsnumber,
					d.Fullname as dfullname,
					CASE T.RedWord
						WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.SaleTotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
						ELSE CASE a.InvoiceQty WHEN 0 THEN a.SaleTotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
					END AS SaleTotal,
					A.SalePrice,
					a.comment,
					a.id as CustomdetailID   ,
					t.Comment AS zy,
					a.discount
					FROM SendBackBill AS A
					INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
					INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
					LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = a.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
					left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
					INNER JOIN #PType p ON a.PTypeID=p.typeid
					INNER JOIN #Dtype d ON d.typeid = b.dtypeid
					' 
					IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
					  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
					SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
					IF (@checkCode<>'')
					  SET @strInOut = @strInOut + ' AND d.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
					IF (@checkName<>'')
					  SET @strInOut = @strInOut + ' AND d.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
					SET @strInOut += ' 
					AND T.ifYearBill = 0
					
					UNION ALL
					--销售发货开票
					SELECT
					b.BillnumberID,																														
					B.BillDate,																														
					B.BillType,					
					A.ID,																													
					a.PtypeID,																															
					a.KtypeID,
					CASE T.RedWord
						WHEN 2 THEN a.Qty
						ELSE -a.Qty 
					END AS Qty,
					a.Price,
					CASE T.RedWord
						WHEN 2 THEN a.total
						ELSE -a.total 
					END AS total,
					CASE T.RedWord
						WHEN 2 THEN a.InvoiceCostTotal
						ELSE -a.InvoiceCostTotal
					END AS CostTotal,
					a.taxprice,  
					CASE T.RedWord
						WHEN 2 THEN a.TaxTotal
						ELSE -a.TaxTotal
					END AS TaxTotal,
					a.tax,
					a.InvoiceCostPrice AS costprice,
					0 AS sharefee,
					a.cargoid,
					a.NPrice AS nprice,
					CASE T.RedWord
						WHEN 2 THEN a.Ntotal
						ELSE -a.Ntotal
					END AS Ntotal,
					a.nsaleprice,
					CASE T.RedWord
						WHEN 2 THEN a.nsaletotal
						ELSE -a.nsaletotal
					END AS nsaletotal,
					a.ntaxprice,
					CASE T.RedWord
						WHEN 2 THEN a.ntaxtotal
						ELSE -a.ntaxtotal
					END AS ntaxtotal,
					v.fullname,
					d.usercode,
					CASE T.RedWord
						WHEN 2 THEN a.NQty
						ELSE -a.NQty
					END AS nqty,
					a.munitid,
					pu.fullname AS numname,
					pe.rate AS rate,
					a.MQty  AS nbrcqty,--换算率变更前销售单位数量
					fg.baseunitfullname AS baseunitfullname,
					fg.assistantfullname AS assistantfullname,
					a.goodsnumber,
					d.Fullname as dfullname,
					CASE T.RedWord
						WHEN 2 THEN a.SaleTotal
						ELSE -a.SaleTotal
					END AS SaleTotal,
					A.SalePrice,
					a.comment,
					a.id as CustomdetailID,
					t.Comment AS zy,
					a.discount
					FROM ReceiptBill AS A
					INNER JOIN ReceiptBillIndex AS T ON(A.BillnumberID = T.BillnumberID AND A.BillType = T.BillType)
					INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
					LEFT  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					left JOIN PType_Units pu on pu.unitsid = a.munitid
					left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
					left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
					INNER JOIN #PType p ON a.PTypeID=p.typeid
					INNER JOIN #Dtype d ON d.typeid = b.dtypeid
					' 
					IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
					  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
					SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
					IF (@checkCode<>'')
					  SET @strInOut = @strInOut + ' AND d.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
					IF (@checkName<>'')
					  SET @strInOut = @strInOut + ' AND d.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
					SET @strInOut += ' 
					AND T.ifYearBill = 0
					'
										 
		SET @strInOut += '
				) AS T
		'    
--********************************************************--
--print(@strInOut)
--select * from #InoutStockTable
EXEC(@strInOut)   


declare  @insertTemp varchar(max)  
if @chvPF='1'
  begin
   set @insertTemp = 'INSERT INTO #inoutstocktable(usercode,dfullname)
                        SELECT 
                        d1.usercode,
                        d1.fullname
						FROM 	billindex b 
						INNER JOIN PriceProtectBill a ON b.billnumberid = a.billnumberid
						INNER JOIN #Btype bb	On bb.typeid =b.btypeid
						INNER JOIN #DealBtype dd ON b.dealbtypeid = dd.typeid '
		                IF  @chvETypeID<>'' OR @METypeID=-99999 
			                SET @insertTemp=@insertTemp+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)
	    
		                IF  @chvDTypeID<>'' OR @MDTypeID=-99999 
			                SET @insertTemp=@insertTemp+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF  @chvStypeID<>''    OR @MStypeid=-99999 
			                SET @insertTemp=@insertTemp+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

		                    SET @insertTemp=@insertTemp+'	inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 AND '+@RED_WHERE+@SQL_WHERE
									
		                    SET @insertTemp = @insertTemp +' AND b.Billtype =''149'''
		
		                IF (@checkCode<>'')
		                    SET @insertTemp = @insertTemp + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		                IF (@checkName<>'')
		                    SET @insertTemp = @insertTemp + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		                IF(ISNULL(@chvComment,'')!='')
			                SET @insertTemp = @insertTemp +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		                IF(ISNULL(@chvZY,'')!='')
			                SET @insertTemp = @insertTemp +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
		                SET @insertTemp = @insertTemp +' AND b.ifYearBill=''0'' AND b.isini=0'
EXEC(@insertTemp)	
 SET	@insertTemp = 'INSERT INTO #inoutstocktable(usercode,dfullname)  SELECT 	
                        d1.usercode,
                        d1.fullname
					FROM billindex b 
					INNER JOIN Advantage a ON b.billnumberid =a.billnumberid
					INNER JOIN #Btype bb   ON bb.typeid =b.btypeid 
					INNER JOIN #DealBtype dd ON b.dealbtypeid = dd.typeid'
					IF @chvETypeID<>'' OR @METypeID=-99999 
						SET @insertTemp=@insertTemp+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)
	                
					IF @chvDTypeID<>'' OR @MDTypeID=-99999 
						SET @insertTemp=@insertTemp+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	               
					IF @chvStypeID<>'' OR @MStypeid=-99999 
						SET @insertTemp=@insertTemp+' inner Join #Stype ss	On ss.typeid =b.stypeid '+CHAR(13)

					SET @insertTemp=@insertTemp+'	 inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 and  '+@RED_WHERE+@SQL_WHERE
							
			        SET @insertTemp = @insertTemp +' AND b.Billtype =''148'''
			
	                IF (@checkCode<>'')
		                SET @insertTemp = @insertTemp + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		            IF (@checkName<>'')
		                SET @insertTemp = @insertTemp + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		            IF(ISNULL(@chvComment,'')!='')
			            SET @insertTemp = @insertTemp +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		            IF(ISNULL(@chvZY,'')!='')
			            SET @insertTemp = @insertTemp +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
	                SET @insertTemp = @insertTemp +' AND b.ifYearBill=''0'' AND b.isini=0'
	       exec(@insertTemp) 
	       end                
--------创建临时表-End--------

--------价保、返利-Start--------
--print @insertTemp
	
DECLARE @PRICE_SQL varchar(MAX)  --价保
SET     @PRICE_SQL ='
						SELECT 	b.billcode,	
						        b.stypeid,
								b.billtype,
								b.billdate,
								b.billnumberid,	
								b.btypeid,
								b.dealbtypeid,
								b.etypeid,
								b.dtypeid,
								b.ktypeid,
								null,
								A.ID,
								p.typeid  as ptypeid,
								null,
								 null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								v.fullname as itemname,
								b.checke,
								cc.fullname,
								b.rate,
								null,
								null,
								null,
								null,
								null,
								null,
								0 AS antantotal,
							    0 AS aqty,
								CASE WHEN b.redword = 2  THEN (-a.total)
								ELSE a.total
								END AS PriceTotal,
								CASE WHEN b.redword = 2 THEN (-a.qty)
								ELSE a.qty
								END AS pqty,
								null,
								dd.usercode,
								2 AS Flag,
								null,
								null,
								a.goodsnumber,
								''价保执行单'' AS billtypename,
								B.redword,
								null,null,null,null,
								null,null,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
							  NULL,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null
						FROM 	billindex b 
						INNER JOIN PriceProtectBill a ON b.billnumberid = a.billnumberid
						left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
						INNER JOIN #Btype bb	On bb.typeid =b.btypeid
						INNER JOIN #DealBtype dd ON b.dealbtypeid = dd.typeid 
						 INNER JOIN AC_Currency cc  ON b.cid = cc.cid '
		                IF  @chvETypeID<>'' OR @METypeID=-99999 
			                SET @PRICE_SQL=@PRICE_SQL+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)
	    
		                IF  @chvDTypeID<>'' OR @MDTypeID=-99999 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF  @chvStypeID<>''    OR @MStypeid=-99999 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

		                    SET @PRICE_SQL=@PRICE_SQL+'	inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 AND '+@RED_WHERE+@SQL_WHERE
									
		                    SET @PRICE_SQL = @PRICE_SQL +' AND b.Billtype =''149'''
		
		                IF (@checkCode<>'')
		                    SET @PRICE_SQL = @PRICE_SQL + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		                IF (@checkName<>'')
		                    SET @PRICE_SQL = @PRICE_SQL + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		                IF(ISNULL(@chvComment,'')!='')
			                SET @PRICE_SQL = @PRICE_SQL +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		                IF(ISNULL(@chvZY,'')!='')
			                SET @PRICE_SQL = @PRICE_SQL +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
		                SET @PRICE_SQL = @PRICE_SQL +' AND b.ifYearBill=''0'' AND b.isini=0'
		
---------------------------------------------------------------------------------------------------------------------	
		
DECLARE @ADTAN_SQL varchar(MAX)  --返利
SET @ADTAN_SQL ='
					 SELECT 	b.billcode,	
						        b.stypeid,
								b.billtype,
								b.billdate,
								b.billnumberid,	
								b.btypeid,
								b.DealBTypeID,
								b.etypeid,
								b.dtypeid,
								b.ktypeid,
								null,
								A.ID,
								p.typeid  as ptypeid,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								v.fullname as itemname,
								b.checke,
								cc.fullname,
								b.rate,
								null,
								null,
								null,
								null,
								null,
								null,
							    CASE WHEN b.redword = 2 THEN -a.total
								ELSE a.total
								END AS antantotal,
								CASE WHEN b.redword = 2 THEN (-a.qty)
								ELSE a.qty
								END AS aqty,
								0 AS PriceTotal,
								0 AS pqty,
								null,
								d.usercode,
								2 AS Flag,
								null,
								null,
								a.goodsnumber,
								''返利执行单'' as billtypename,
								B.redword,
								null,null,null,null,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
							    null,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
					FROM billindex b 
					INNER JOIN Advantage a ON b.billnumberid =a.billnumberid
					left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					INNER JOIN #Dtype d ON d.typeid = b.dtypeid					
					INNER JOIN #DealBtype dd ON b.dealbtypeid = dd.typeid
						 INNER JOIN AC_Currency cc  ON b.cid = cc.cid  '
					IF @chvETypeID<>'' OR @METypeID=-99999 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)
	                
					IF @chvDTypeID<>'' OR @MDTypeID=-99999 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	               
					IF @chvStypeID<>'' OR @MStypeid=-99999 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Stype ss	On ss.typeid =b.stypeid '+CHAR(13)

					SET @ADTAN_SQL=@ADTAN_SQL+'	 inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 and  '+@RED_WHERE+@SQL_WHERE
							
			        SET @ADTAN_SQL = @ADTAN_SQL +' AND b.Billtype =''148'''
			
	                IF (@checkCode<>'')
		                SET @ADTAN_SQL = @ADTAN_SQL + ' AND bb.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		            IF (@checkName<>'')
		                SET @ADTAN_SQL = @ADTAN_SQL + ' AND bb.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		            IF(ISNULL(@chvComment,'')!='')
			            SET @ADTAN_SQL = @ADTAN_SQL +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		            IF(ISNULL(@chvZY,'')!='')
			            SET @ADTAN_SQL = @ADTAN_SQL +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
	                SET @ADTAN_SQL = @ADTAN_SQL +' AND b.ifYearBill=''0'' AND b.isini=0'
--------价保、返利-End--------


----- 拼接头-商品编号、商品名Start-----
DECLARE  @head  VARCHAR(MAX)
SET @head= 
          'SELECT ''【''+b.usercode+''】''+isnull(b.dfullname,''''),
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
				  1 ID,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  b.usercode,
                  1 AS Flag,
                  NULL,
	     		  NULL,
	     		  NULL,
	     		  NULL,
	     		  NULL,
	     		  NULL,null,null,null,
	     		  null as Explain ,
	     		  null,
	     		NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                null,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
          FROM #InoutStockTable b GROUP BY b.usercode,b.dfullname' 
          
----- 拼接头-商品编号、商品名End-----
		   
-----业务SQL语句-Start-----
DECLARE @strSQL VARCHAR(MAX)
SET @strSQL = 
            'SELECT   b.billcode,
             		  b.stypeid,																																																									
	                  a.billtype,
	                  a.billdate,
                      a.billnumberid,
	                  b.btypeid,
	                  b.dealbtypeid,
	                  b.etypeid,
	                  b.dtypeid,
	                  a.ktypeid,																																																											
	                  a.cargoid,
					  A.ID,
	                  a.ptypeid,
					  MPs.usercode pmulusercode,
	                  -(a.Qty)AS qty,
					  isnull(a.Price,0) AS price,
					  isnull(a.taxPrice,0) AS taxprice,
                      -(a.Total) AS total,
					  -(a.TaxTotal) AS taxtotal, 
					  -(taxtotal)-(-total) AS taxge,
					  isnull((b.Totalinmoney+isnull(b.completeTotal,0)),0) AS totalinmoney,
					  CASE ABS(a.Qty) 
						  WHEN 0 THEN 0
						  ELSE a.costprice
					  END costprice,
					  --a.costprice,
					  -(a.CostTotal) AS costtotal,
					  -(ISNULL(a.sharefee,0)) AS sharefee,
					  -(ISNULL(b.preferencemoney,0)) AS preferencemoney,
					  a.nprice,
					  -(a.ntotal) AS ntotal,
					  a.nsaleprice,
					  -(a.nsaletotal) AS nsaletotal,
					  a.ntaxprice,
					  -(a.ntaxtotal) AS ntaxtotal,
					  a.fullname as itemname,
					  b.checke,
					  b.cname,
					  b.rate,
					  -(a.nqty) AS nqty,
					  a.numname AS munit,
					  -(a.qty/a.rate) AS mqty,
					    CASE a.nbrcqty  WHEN  -(a.qty/a.rate) THEN NULL ELSE a.nbrcqty  END AS nbrcqty,
					  CASE '+CAST( @config AS VARCHAR)+' WHEN 1  THEN -(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0)) ELSE  -(a.Total) - (-a.CostTotal) END AS maoli,
					    CASE a.Total WHEN 0 THEN 0 
					  ELSE 
					  (CASE '+CAST( @config AS VARCHAR)+' 
					  WHEN 1  THEN cast( (-(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0))) as 
NUMERIC(24, 10))/cast( -(a.total) as 
NUMERIC(24, 10))
                      ELSE cast( (-(a.Total) - (-a.CostTotal))as 
NUMERIC(24, 10))/cast(-(a.total)  as NUMERIC(24, 10))
                      END)*100
					  END AS maolilu,
					  
					  CASE WHEN b.billtype IN (148,150) THEN -(a.total)
                      ELSE 0
                      END AS antantotal,
					  CASE WHEN b.billtype IN (148,150) THEN -(a.qty)
					  ELSE 0
					  END AS aqty,
					  CASE WHEN b.billtype IN (149,151) THEN -(a.total)
					  ELSE 0
					  END AS PriceTotal,
					  CASE WHEN b.billtype IN (149,151) THEN -(a.qty)
					  ELSE 0
					  END AS pqty,
					  b.posttime,
					  a.usercode,
					  2 AS Flag,
					  a.baseunitfullname,
					  a.assistantfullname,
					  a.goodsnumber,
					  CASE a.billtype
						WHEN 11		THEN ''销售出库单''
						WHEN 45		THEN ''销售退货单''
						WHEN 215	THEN ''零售退货单''
						WHEN 305	THEN ''零售单''
						WHEN 141	THEN ''委托结算单''
						WHEN 34 	THEN ''采购入库单''
						WHEN 6 		THEN ''采购退货单''
						WHEN 145	THEN ''受托代销结算单''
						WHEN 149	THEN ''价保执行单''
						WHEN 151	THEN ''获得价保执行单''
						WHEN 148	THEN ''返利执行单''
						WHEN 150	THEN ''获利执行单''
						WHEN 160	THEN ''销售换货单''
						WHEN 161	THEN ''采购换货单''
						WHEN 402	THEN ''发出商品出库单''
						WHEN 403	THEN ''发出商品退货单''
						WHEN 405	THEN ''销售发货开票''
						WHEN 12		THEN ''组合品销售出库单''
						WHEN 46		THEN ''组合品销售退货单''
					  END AS billtypename,
					 b.redword AS RedWord,
					 (-A.Ntaxtotal)-(-A.Ntotal) AS ntaxge,
					 -(a.saletotal)as saletotal,
					 a.saleprice,
					 a.comment,
					 b.Explain,
					 (a.nsaleprice * pe.rate) as MunitPrice,  /*销售单位单价*/
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	,
					SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40,
				customassist=dbo.F_GetCustomAssist(a.Ptypeid,-(a.Qty)),
				a.zy,
				a.discount
			  FROM #InoutStockTable a
			  INNER JOIN #BillIndex b ON a.BillNumberId = b.BillNumberID	  and a.billtype=b.billtype			  
			  LEFT JOIN dbo.PType_Units_Ext pe ON a.MUNITID=pe.UnitsId AND a.PtypeId=pe.PtypeID
			  LEFT JOIN PUserCode MPs ON MPs.PTypeID=A.PtypeId AND MPs.btypeid=B.dealbtypeid
			   left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid
			'

			  ---筛选制单人
			  IF @checkCode <> '' OR @checkName <> ''
              IF NOT(@checkCode='10000' OR @checkName = '代销仓库')
                 --加‘10000’是查仓库的时候要包含代销仓库
				 SET @strSQL = @strSQL +' INNER JOIN (SELECT TypeID FROM Department UNION SELECT ''10000'') AS T  ON b.DTypeID = T.TypeID'
-----业务SQL语句-End-----

            IF  @chvPF ='1' 
			    SELECT @strSQL = @strSQL +' UNION ALL ' +@PRICE_SQL +' UNION ALL ' + @ADTAN_SQL 
			    --PRINT @ADTAN_SQL
			--print @PRICE_SQL			
-----拼接尾-商品相关金额小计Start-----
DECLARE @tail VARCHAR(MAX);
SELECT @tail = 
       'WITH strSql AS
        ('+@strSQL+')
        SELECT * FROM strSql
        UNION ALL
        SELECT  NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
				1 ID,
                NULL,
                NULL,
                SUM(strSql.Qty),
                NULL,
                NULL,
                SUM(strSql.Total),
                SUM(strSql.Taxtotal),
                SUM(strSql.Taxge),
                NULL,
                NULL,
                SUM(strSql.CostTotal),
                SUM(strSql.sharefee),
                NULL,
                NULL,
                SUM(strSql.ntotal),
                NULL,
                SUM(strsql.nsaletotal),
                NULL,
                SUM(strSql.ntaxtotal),
                NULL,
                NULL,
                NULL,
                NULL,
                SUM(strSql.nqty),
                NULL,
                SUM(strSql.mqty),
                SUM(strSql.nbrcqty),
                SUM(strSql.maoli),
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                strSql.usercode,
                3 AS Flag,
                NULL,
                NULL,
                NULL,
              ''小计'',
                NULL,
                SUM(strSql.ntaxge),SUM(strsql.saletotal),NULL,NULL,
                null as Explain,
                NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
         FROM strSql
         GROUP BY strSql.usercode
         UNION ALL ' 
         +@head   
-----拼接尾-商品相关金额小计End-----
DECLARE @SQL_ORDER VARCHAR(MAX) 
SELECT  @SQL_ORDER = ' ORDER BY usercode,Flag'
+ CASE @sortfield
			WHEN 'ByDate_a'		THEN ', BillDate,Billcode,ID'	-- 按日期排序
			WHEN 'ByBillNo_a'	THEN ', BillCode'		    -- 按单据编号排序
			WHEN 'ByBillType_a'	THEN ', BillType,BillDate,ID'	-- 按单据类型排序
			WHEN 'ByBillID_a'	THEN ', posttime'			-- 按单据真实过帐顺序排序
			WHEN 'ByDate_d'		THEN ', Billdate DESC,Billcode DESC,ID'
			WHEN 'ByBillNo_d'	THEN ', BillCode DESC'
			WHEN 'ByBillType_d'	THEN ', BillType DESC,BillDate,ID'
			WHEN 'ByBillID_d'	THEN ', posttime DESC,ID '
			ELSE ',posttime DESC,ID '
			END
--print @tail
DECLARE @SQL VARCHAR(MAX)
SET @SQL =@tail + @SQL_ORDER
--print @SQL
EXEC(@SQL)
DROP TABLE #Billtype,#Ptype,#Btype,#Etype,#Ktype,#Dtype,#Stype,#BillIndex,#DealBtype,#InoutStockTable
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmpIncQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmpIncQuery]
GO




-- ========================================================================
-- 功能说明：		职员当月创利报表（树形表和线性表）
-- 最后修改作者：	冯 波
-- 最后修改时间：	2004-03-29
-- ========================================================================
-- ========================================================================
-- 修改说明：		职员当月创利报表（树形表和线性表），收款单可以结算销售出库，
--					销售退货单,故收回收回赊货金额,未收赊货金额统计油误，优惠金额
--                  应去除
-- 最后修改作者：	徐辉
-- 最后修改时间：	2004-09－03
-- ========================================================================
-- ========================================================================
-- 修改说明：		树型表不统计停用职员，线性表也要不统计停用职员
-- 最后修改作者：	徐辉
-- 最后修改时间：	2007-01－30
-- 修改标记：		#01
-- ========================================================================
-- ========================================================================
-- 修改说明：		优化查询速度 －－提高了一倍
-- 最后修改作者：	徐辉
-- 最后修改时间：	2006-04-28
-- 修改标记：		#02
-- ========================================================================

-- ========================================================================
-- 修改说明：		收回赊货金额和未收赊货金额职员权限控制 01
--					将所select typeid from F_GetManETypeAll(@OperatorID)提取到#EType表中
-- 最后修改作者：	WANG WEI
-- 最后修改时间：	2010-7-2
-- 修改标记：		#03
-- ========================================================================
-- ========================================================================
-- 修改说明：		过滤维修类单据
-- 最后修改作者：	WANG WEI
-- 最后修改时间：	2010-9-15
-- 修改标记：		#04
-- ========================================================================

 -- ========================================================================
-- 修改说明：		根据产品判断是否过滤维修类单据，权限调整
-- 最后修改作者：	徐辉
-- 最后修改时间：	2011-04-03
-- ========================================================================

-- 周华 2013.08.12 修改表列数超过限制问题 
-- 周华 2014.01.16 配置项显示问题

CREATE                                  PROCEDURE Web_EmpIncQuery
(
	@StartDate       datetime,             --起始日期
	@EndDate         datetime,             --截止日期
	@ETypeID         varchar(50),          --职员ID
	@STypeID		 varchar(max),			--分支机构ID
	@PageRows        int=14,               --每页的行数
	@PageNo          int=1,                --当前查询的页数
	@OperatorID      varchar(50),          --业务员ID，从EmpIncSet里读取他的选项配置，如果没有，则按默认的显示
	@Condition    varchar(1000),        --查询条件 注意:该参数应该是 LIKE ''п'',存储过程中应该替换回来
	@Order        varchar(1000),        --排序条件
	@PrintFlag       tinyint,              --1表示是页面显示，需要进行分页；2表示是用于打印，不进行分页       
	@IsTree          bit                   --1表示是树形表（显示该@ETypeID下的一级节点的信息），0表示是线形表（显示所有叶子节点的信息），这时@ETypeID传入空值，无效
	
	,@hpage int=1 --分页标识 ，当这个标志启用时，下面参数有效. 1启用，0关闭
	--,@hpagesize int=20	--每页的在小
	--,@hpageindex int=0	--第几页
	,@htotalpage int=0	--取总数，如果为0反回数据，如果1 反回分页的总列数。
	
	,@bCount			int=100			--基本信息的默认个数
	,@bPageNo		int=0			--基本信息的页数
)
--@encode$--
AS

--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50),@MSTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

--------------------------------------------------------------权限检查-------------------------------------------------------
SET ANSI_WARNINGS OFF
SET NOCOUNT ON
DECLARE @ALL_INCOME_ID  varchar(50)
DECLARE @ALL_EXPENSE_ID varchar(50)
SELECT @ALL_INCOME_ID='00003'          --【收入类】
SELECT @ALL_EXPENSE_ID='00004'         --【支出类】
SELECT @Condition = REPLACE(@Condition,'п','%') --注意:该参数应该是 LIKE ''п'',存储过程中应该替换回来 徐辉 2005-4-5
--过滤原始单据(时间范围，职员范围，科目范围(收支类)，红冲标志)
CREATE TABLE #ListTable(ETypeID varchar(50),ATypeID varchar(50),Total  NUMERIC(24, 10) )  --定义一个临时表，记录筛选过的ListTable
DECLARE @SQL varchar(max)
DECLARE @SumSQL varchar(max)  --记录合计字段，用于合计
IF @ETypeID=''  SET @ETypeID='00001'  --如果没有输入职员ID，则自动设置为根节点
CREATE TABLE #Employee(ETypeID varchar(50),NAME varchar(100),SonNum int,UserCode varchar(50) NULL) 
DECLARE @intSonNum int  --判断传入的职员是否为叶子节点

CREATE TABLE #EType(typeid VARCHAR(100),Parid VARCHAR(100),soncount INT)
INSERT #EType
SELECT typeid,Parid,soncount FROM F_GetManETypeAll(@OperatorID)--#03

--版本
DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'

-- 多级权限改变取 #Employee 的值算法
IF @IsTree=1
BEGIN
   --需要判断该职员是否是叶子节点
   SELECT @intSonNum=SonNum FROM employee WHERE TypeID=@ETypeID 
   IF @intSonNum>0
   BEGIN
         --如果@IsTree=1，是树形表，那么我们需要显示的是，该节点的第一级儿子的统计信息
		INSERT INTO #Employee SELECT a.TypeID,FullName,SonNum,UserCode FROM employee a INNER JOIN ( SELECT typeID FROM #EType where parid =@ETypeID) b ON a.typeId=b.typeid ORDER BY UserCode
	
	   
   END
   ELSE
   BEGIN
         --如果是叶子节点，则显示它自己的信息（因为它下面没有子节点了）
		INSERT INTO #Employee SELECT a.TypeID,FullName,SonNum,UserCode FROM employee  a INNER JOIN  ( SELECT typeID FROM #EType where typeid =@ETypeID) b ON a.typeId=b.typeid ORDER BY UserCode
   END
END
ELSE
BEGIN
   --如果@IsTree=0，是线形表，需要显示的是叶子节点的信息（并根据@ETypeID进行过滤）
   INSERT INTO #Employee SELECT a.TypeID,FullName,SonNum,UserCode FROM employee a INNER JOIN  ( select a.typeid from F_GetManDetailEType(@OperatorID) a where typeid like @EtypeID+'%') b ON a.TypeId = b.typeId ORDER BY UserCode
END

DELETE FROM #Employee where ETypeID ='00001' --删除超级用户

CREATE TABLE #DTYPE(TypeID VARCHAR(50))
CREATE TABLE #STYPE (TypeID varchar(50))

DECLARE @sqlman VARCHAR(8000) 
SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',9,@OperatorID,'#DTYPE')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@stypeid,11,@OperatorID,'#STYPE')
--PRINT @sql
EXEC(@sqlman)

--得到AType中的所有收支会计科目(权限范围内)
SELECT
    CAST(nId AS VARCHAR(10)) AS TypeID,
    ParID,
    FullName,
    TypeName,
    nTypeId,
    nParId
INTO
    #OldAType
FROM
    Ac_Items
WHERE
    ( 
       (ntypeid LIKE '00003%'  AND nTypeId NOT LIKE '0000300003%' OR
     nId IN (SELECT typeId FROM F_GetManATypeSrAll(@OperatorID)) AND nTypeId  LIKE '0000300003%') 
     OR(ntypeid LIKE '00004%' AND  nTypeId NOT LIKE '0000400003%' OR
     nid IN (SELECT typeId FROM F_GetManATypeFyAll(@OperatorID)) AND nTypeId  LIKE '0000400003%') 
    )/*AND SonNum=0*/

--UNION SELECT 'Payed','','收回赊货金额','G'
--UNION SELECT 'UnPayed','','未收回赊货金额','E'

SET @SQL='INSERT #ListTable 
			SELECT ETypeID,
					ATypeID,
					SUM(ISNULL(Total,0)) AS Total 
			FROM ListTable inner join #OldAType a on listtable.atypeid=a.typeid ' 
IF @MEtypeId='-99999' OR  @ETypeID<>''
	SET @SQL=@SQL+' INNER JOIN #Etype ON #Etype.typeid=Listtable.EtypeID'
IF @MStypeid = '-99999' OR  @STypeID<>''
	SET @SQL =@SQL+' INNER JOIN #Stype s on (listtable.stypeid=s.typeid) '
IF @MDTypeId = '-99999'
	SET @SQL =@SQL+' INNER JOIN F_BaseGetManDetailDType('''+@OperatorID+''') p on (listtable.dtypeid=p.typeid) '
SET @SQL=@SQL+'
			WHERE  
					/*AND (ATypeID ='+char(39)+@ALL_INCOME_ID+char(39)+' OR ATypeID ='+char(39)+@ALL_EXPENSE_ID+char(39)+')*/ 
					 (BillDate BETWEEN '+char(39)+CAST(@StartDate AS varchar(50))+char(39)+' 
					AND '+char(39)+CAST(@EndDate AS varchar(50))+char(39) + ')
					
					AND Audited=1 '	
SET @SQL=@SQL+'	 GROUP BY EtypeID,ATypeID'

--添加对业务提成的统计
SET @SQL += ' 
			INSERT #ListTable 
			SELECT CBND.EtypeID,
			(SELECT TOP 1 nId FROM Ac_Items WHERE FullName = ''业务提成'') AS ATypeID,
			ISNULL(SUM(CBND.CommissionTotal),0) AS Total 
			FROM CommissionBillNew AS CBN
			INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId) '
IF @MEtypeId='-99999' OR  @ETypeID<>''
	SET @SQL=@SQL+' INNER JOIN #Etype ON #Etype.typeid=CBND.EtypeID'
IF @MStypeid = '-99999' OR  @STypeID<>''
	SET @SQL =@SQL+' INNER JOIN #Stype s on (CBN.stypeid=s.typeid) '
IF @MDTypeId = '-99999'
	SET @SQL =@SQL+' INNER JOIN F_BaseGetManDetailDType('''+@OperatorID+''') p on (CBND.dtypeid=p.typeid) '
			SET @SQL += '
						WHERE CBN.ifcheck = ''t'' 
							AND (CBN.BillDate BETWEEN '+char(39)+CAST(@StartDate AS varchar(50))+char(39)+' 
								AND '+char(39)+CAST(@EndDate AS varchar(50))+char(39) + ')
						GROUP BY CBND.EtypeID '

EXEC(@SQL)
--SELECT * FROM listtable lt JOIN #OldAType a ON lt.atypeid=a.typeid
--JOIN #etype e ON lt.EtypeId=e.typeid
--JOIN #stype s ON lt.STypeID=s.typeid
--WHERE lt.billdate BETWEEN @startDate AND @enddate  
----AND lt.audited=1 

DECLARE @strTempATypeID varchar(50)   --临时使用的会计科目变量 　　
DECLARE @dblTempTotal  NUMERIC(24, 10)   --临时使用的各收支类会计科目的合计
--根据操作员自行选择的项目对收、支项目进行过滤(在EmpIncSet表中收回赊货金额用'Payed'，未收赊货金额用'UnPayed'标志)
DECLARE @intPayed int                --表示是否显示收回赊货金额，1表示要显示，0表示不显示
DECLARE @intUnPayed int              --表示是否显示未收赊货金额，1表示要显示，0表示不显示
DECLARE @intIncomeSumUp int          --表示是否显示收入小计，1表示要显示，0表示不显示
DECLARE @intOutcomeSumUp int         --表示是否显示费用小计，1表示要显示，0表示不显示
DECLARE @Payed varchar(50)           --收回赊货金额的会计科目ID，自定义
DECLARE @UnPayed varchar(50)         --未收赊货金额的会计科目ID，自定义
SET @Payed='Payed'
SET @UnPayed='UnPayed'
DECLARE @PayedName varchar(50)        --收回赊货金额的FullName
DECLARE @UnPayedName varchar(50)      --未收赊货金额的FullName
SET @PayedName='收回赊货金额'
SET @UnPayedName='未收赊货金额'
DECLARE @Income varchar(50)          --收入小计的会计科目ID，自定义
DECLARE @Outcome varchar(50)         --支出小计的会计科目ID，自定义
SET @Income='Income'
SET @Outcome='Outcome'
DECLARE @IncomeName varchar(50)      --收入小计的FullName
DECLARE @OutcomeName varchar(50)     --支出小计的FullName
SET @IncomeName='收入类小计' 
SET @OutcomeName='支出类小计'


--判断用户是否设置了显示选项
--用户配置后的会计科目表，#AType
CREATE TABLE #AType(TypeID varchar(50),ParID varchar(50),FullName varchar(100),TypeName VARCHAR(10),ntypeid VARCHAR(50) DEFAULT(''),nparid VARCHAR(50) DEFAULT(''))

IF EXISTS(SELECT ETypeID FROM EmpIncSet WHERE ETypeID=@OperatorID)
	BEGIN	    
				
			    SELECT @intPayed=COUNT(*) FROM EmpIncSet WHERE ETypeID=@OperatorID AND ATypeID=@Payed
			    
			    SELECT @intUnPayed=COUNT(*) FROM EmpIncSet WHERE ETypeID=@OperatorID AND ATypeID=@UnPayed
			    

		        --得到过滤后的会计科目
			    INSERT #AType SELECT a.TypeID,a.ParID,a.FullName,a.TypeName,a.nTypeId,a.nParId  FROM #OldAType a
			    WHERE EXISTS
			    (
			          SELECT b.ETypeID FROM EmpIncSet b WHERE b.AtypeID=a.TypeID AND b.ETypeID=@OperatorID
			          --SELECT 1 FROM dbo.EmpIncSet b JOIN ac_items c ON b.AtypeID=CAST(c.nId AS VARCHAR(50)) WHERE a.nTypeId LIKE c.nTypeId+'%' AND b.EtypeID=@OperatorID
			    )
	            ORDER BY a.TypeID
	            
	           
	            --如果有收入类的会计科目，则需要显示收入类小计
	            IF EXISTS(SELECT ETypeID FROM EmpIncSet a INNER JOIN(SELECT * FROM Ac_Items) b ON CAST(b.nId AS VARCHAR(10))=a.AtypeID AND b.TypeName='G' WHERE ETypeID=@OperatorID  )
	               SET @intIncomeSumUp=1
	            ELSE
					IF EXISTS(SELECT ETypeID FROM EmpIncSet WHERE ETypeID=@OperatorID AND ATypeID='Payed')
						SET @intIncomeSumUp=1
					ELSE
	               		SET @intIncomeSumUp=0
	            --如果有支出类的会计科目，则需要显示支出类小计
	            IF EXISTS(SELECT ETypeID FROM EmpIncSet a INNER JOIN(SELECT * FROM Ac_Items) b ON CAST(b.nId AS VARCHAR(10))=a.AtypeID AND b.TypeName='E' WHERE ETypeID=@OperatorID  )
	               SET @intOutcomeSumUp=1
	            ELSE
					IF EXISTS(SELECT ETypeID FROM EmpIncSet WHERE ETypeID=@OperatorID AND ATypeID='UnPayed')
						SET @intOutcomeSumUp=1
					ELSE
	               		SET @intOutcomeSumUp=0
	      
	END
ELSE
	BEGIN
	       INSERT INTO #AType ( TypeID, ParID, FullName,TypeName,nTypeid,nparid )
	         SELECT  nId,ParId,FullName,TypeName,nTypeId,nParId FROM Ac_Items 
	        WHERE
    ( 
       (ntypeid LIKE '00003%'  AND nTypeId NOT LIKE '0000300003%' OR
     nid IN (SELECT typeId FROM F_GetManATypeSrAll(@OperatorID)) AND nTypeId  LIKE '0000300003%') 
     OR(ntypeid LIKE '00004%' AND  nTypeId NOT LIKE '0000400003%' OR
     nid IN (SELECT typeId FROM F_GetManATypeFyAll(@OperatorID)) AND nTypeId  LIKE '0000400003%') 
    )AND SonNum=0
			SET @intIncomeSumUp=1
	        SET @intOutcomeSumUp=1
	        SET @intPayed=1
	        SET @intUnPayed=1
	     
	
	END
--根据@intPayed,@intUnPayed来决定是否显示收回赊货金额，未收赊货金额
IF @intPayed=1   INSERT INTO #AType(TypeID,ParID,FullName,TypeName,nparid) VALUES(@Payed,@ALL_INCOME_ID,@PayedName,'',@ALL_INCOME_ID)
IF @intUnPayed=1 INSERT INTO #AType(TypeID,ParID,FullName,TypeName,nparid) VALUES(@UnPayed,@ALL_EXPENSE_ID,@UnPayedName,'',@ALL_EXPENSE_ID)
--根据@intIncome,@intOutcome来决定是否显示收入类小计，支出类小计，利润
IF @intIncomeSumUp=1  INSERT INTO #AType(TypeID,ParID,FullName,TypeName,nparid) VALUES(@Income,@ALL_INCOME_ID,@IncomeName,'',@ALL_INCOME_ID)
IF @intOutcomeSumUp=1 INSERT INTO #AType(TypeID,ParID,FullName,TypeName,nparid) VALUES(@Outcome,@ALL_EXPENSE_ID,@OutcomeName,'',@ALL_EXPENSE_ID)

/*
DECLARE @root varchar(50)         --利润算到根节点下
SET @root='00000'
DECLARE @Profit varchar(50)       --利润的会计科目ID，自定义
SET @Profit='Profit'
DECLARE @ProfitName varchar(66)   --利润的FullName
SET @ProfitName='利润'
IF (@intIncomeSumUp=1) AND (@intOutcomeSumUp=1) INSERT INTO #AType(TypeID,ParID,FullName,TypeName) VALUES(@Profit,@root,@ProfitName,'')
--建立一个动态的临时表来保存结果，包括的字段是：职员ID，各类收入，然后在游标的两层循环都往相应的字段填入值，并计算收入和费用的合计（首先需要计算是否选择了这两项）
*/

delete #AType where typeid in ('Income','Outcome','Profit')


DECLARE @i int
SET @i=0
SET @SumSQL = ''
DECLARE @SumSQL1 varchar(max)
SET @SumSQL1 = ''
SET @SQL='ALTER TABLE #tableResult '
CREATE TABLE #tableResult(ETypeID varchar(50),[Income]  NUMERIC(24, 10)  default(0),[Outcome]  NUMERIC(24, 10)  default(0),[Profit]  NUMERIC(24, 10)  default(0))   

DECLARE @TypeName VARCHAR(10)


IF @hpage<>0 and @htotalpage<>0
BEGIN
		-- 列记录数时不运行下面代码
		SELECT ISNULL(COUNT(1),0) FROM #atype;
		RETURN;
END

--
alter table #AType add rn int ;--identity(1,1);
;with cte as (
	select r=row_number() over(order by CASE WHEN typename='G' THEN 10 WHEN TYPEID IN('payed') THEN 11 WHEN typename='E' THEN 20 WHEN TYPEID IN ('unpayed') THEN 21 ELSE 30 END ASC),* from #atype
)
update a set a.rn=b.r from #atype a join cte b on a.typeid=b.typeid


declare @s int=0,@e int=0;

if @hpage<>0
begin --垂直分页
	select @s=@bCount*(@bPageNo-1)+1,@e=@bCount*@bPageNo;
end
else 
begin
	select @e=max(rn) from #AType;
end


--改成垂直分页的,且必分页
DECLARE AType_Cursor CURSOR
FOR SELECT TypeID,TypeName FROM #AType WHERE rn BETWEEN @s AND @e ORDER BY RN;
OPEN AType_Cursor
FETCH NEXT FROM AType_Cursor INTO @strTempAtypeid,@TypeName
WHILE @@FETCH_STATUS=0
BEGIN
	  IF (LEN(@SQL)<7000)	
	  BEGIN	
	      IF @i=0 
	         SET @SQL=@SQL+' ADD '
	      ELSE
	         SET @SQL=@SQL+' , '
	      SET @i=@i+1

	      SET @SQL=@SQL+' ['+@TypeName+@strTempAtypeid+']'+'  NUMERIC(24, 10)  DEFAULT 0 '
	  END
	  ELSE
	  BEGIN	
	      EXEC(@SQL)
		  SET @i = 0
		  IF @i=0 
		  BEGIN
			 SET @SQL='ALTER TABLE #tableResult '		  
	         SET @SQL=@SQL+' ADD '
		  END
	      ELSE
	         SET @SQL=@SQL+' , '
	      SET @i=@i+1
	      SET @SQL=@SQL+' ['+@TypeName+@strTempAtypeid+']'+'  NUMERIC(24, 10)  DEFAULT 0 '
	  END
	  IF LEN(@SumSQL)<7000
		  SET @SumSQL = @SumSQL + 'ISNULL(SUM(['+@TypeName+@strTempAtypeid+']),0),'
	  ELSE
		  SET @SumSQL1 = @SumSQL1 + 'ISNULL(SUM(['+@TypeName+@strTempAtypeid+']),0),'
      FETCH NEXT FROM AType_Cursor INTO @strTempAtypeid,@TypeName
END


--print(@SQL)

IF( @SQL<>'ALTER TABLE #tableResult ')
  EXEC(@SQL) --执行改表操作
CLOSE AType_Cursor
DEALLOCATE AType_Cursor

--判断用户是否选择了收回赊货金额,未收赊货金额（计算收回赊货金额和未收赊货金额比较耗费资源）
--计算收回赊货金额需要用到的表是：#tableAllGathering,#tableAllPay,#tableAllSale,#tableAllReturn,#tableAllGathering,#tableRangePay,#tableRangeGatheringSumUp,#tableRangePaySumUp
--计算未收回赊货金额需要用到的表是：#tableAllGathering,#tableAllPay,#tableAllSale,#tableAllReturn,#tableAllGatheringSumUp,#tableAllPaySumUp,#tableAllSaleSumUp,#tableAllReturnSumUp
   
--所有的统计以销售出库/销售退货的业务员为主，因此收款单/付款单都不过滤业务员，只需要在销售出库/销售退货中过滤即可；而收款时间则在收款单/付款单中过滤，不在销售出库/销售退货中过滤
--PRINT(@intPayed)
--PRINT(@intUnPayed)

--SELECT * from #tableResult
--RETURN
IF @intPayed=1 OR @intUnPayed=1 
BEGIN

 CREATE TABLE #BillIndexPayUnPay
 (
  BillNumberID INT,
  billtype INT,
  TotalMoney  NUMERIC(24, 10) ,
  EtypeId NVARCHAR(500),
  TotalInMoney  NUMERIC(24, 10) ,
  preferencemoney  NUMERIC(24, 10) ,
  BillDate DATETIME
 )
 
 
 DECLARE @tempsql NVARCHAR(2000)
	--收缩billindex表
SELECT @tempsql=' insert into #BillIndexPayUnPay
                 SELECT B.BillNumberID,B.BillType,B.TotalMoney,B.EtypeId,B.TotalInMoney,B.preferencemoney,B.BillDate 
		FROM BillIndex B'
		IF EXISTS(SELECT 1 FROM #STYPE)
	         SELECT @tempsql+=' INNER JOIN #STYPE S ON B.Stypeid=S.TYPEID '
	   IF EXISTS(SELECT 1 FROM #dTYPE)
		     SELECT @tempsql+=' INNER JOIN #DTYPE D ON B.DTypeId=D.TYPEID '
 SELECT @tempsql+='	WHERE 
		BillType IN(4,11,66,45,141,160)
		--AND EtypeId IN (SELECT typeid FROM dbo.F_GetManETypeAll(@OperatorID))
		AND IfCheck = ''t''
		AND RedWord = 0
		AND BillDate BETWEEN '+char(39)+CAST(@StartDate AS varchar(50))+char(39)+' 
					AND '+char(39)+CAST(@EndDate AS varchar(50))+char(39) + '
		AND ifYearBill=0'	 --年节存标志
		--PRINT @tempsql
		EXEC(@tempsql)
    --得到所有的收款单
    SELECT BillNumberID,TotalMoney,BillDate INTO #tableAllGathering FROM #BillIndexPayUnPay WHERE BillType=4
        
	    
    --得到所有的付款单
    SELECT BillNumberID,TotalMoney,BillDate INTO #tableAllPay FROM #BillIndexPayUnPay WHERE BillType=66
	   
        --得到职员范围内所有的销售出库单（扣除现结的）
        CREATE TABLE #tableAllSale(BillNumberID int,TotalMoney  NUMERIC(24, 10)  NULL,ETypeID varchar(50),BillDate datetime)
        
           SET @SQL='INSERT #tableAllSale SELECT BillNumberID,TotalMoney-TotalInMoney-preferencemoney AS TotalMoney,ETypeID,BillDate FROM #BillIndexPayUnPay '
           --SET @SQL=@SQL+' WHERE BillType IN (11,45) AND IfCheck=''t'' '   --添加销售退货单,减去优惠金额 徐辉 2004.9.3 
		  -- chen_qihua 004-09-02
           SET @SQL=@SQL+'WHERE ETypeID LIKE '+char(39)+@ETypeID+'%'+char(39)
           --SET @SQL=@SQL+'WHERE EtypeId IN (SELECT typeid FROM dbo.F_GetManETypeAll('+@OperatorID+'))'
		   SET @SQL=@SQL+'AND ( BillType=11 OR BillType=141  OR BillType = 160 )' 
		   EXEC(@SQL)
        --得到职员范围内所有的销售退货单（扣除现结的）
        CREATE TABLE #tableAllReturn(BillNumberID int,TotalMoney  NUMERIC(24, 10)  NULL,ETypeID varchar(50),BillDate datetime)
        
           SET @SQL='INSERT #tableAllReturn SELECT BillNumberID,TotalMoney-TotalInMoney-preferencemoney AS TotalMoney,ETypeID,BillDate  FROM #BillIndexPayUnPay '
           SET @SQL=@SQL+'WHERE ETypeID LIKE '+char(39)+@ETypeID+'%'+char(39)     --减去优惠金额 徐辉 2004.9.3 
           --SET @SQL=@SQL+'WHERE EtypeId IN (SELECT typeid FROM dbo.F_GetManETypeAll('+@OperatorID+'))'
		   SET @SQL=@SQL+'AND ( BillType=45 )'     
		   EXEC(@SQL)
       
       
END


IF @intPayed=1
BEGIN
        --得到指定时间范围内所有的收款单
        SELECT BillNumberID,TotalMoney INTO #tableRangeGathering FROM #tableAllGathering
        
        --得到指定时间范围内所有的付款单
        SELECT BillNumberID,TotalMoney INTO #tableRangePay FROM #tableAllPay
       
        --得到指定时间范围内按销售出库单结算的收款单（按销售出库单中的职员来统计，但金额按收款单中的计算，因为可能不是足额支付）
        SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableRangeGatheringSumUp FROM CompleteTotal a
        INNER JOIN #tableRangeGathering b ON a.MoneyBillID=b.BillNumberID  --指定时间的收款单
        INNER JOIN #tableAllSale c ON a.GoodsBillID=c.BillNumberID         --指定职员范围内的销售出库单
        GROUP BY c.ETypeID
	
		--得到指定时间范围内按销售退货单结算的收款单（按销售出库单中的职员来统计，但金额按收款单中的计算，因为可能不是足额支付）
        SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableRangeGatheringSumUpReturn FROM CompleteTotal a
        INNER JOIN #tableRangeGathering b ON a.MoneyBillID=b.BillNumberID  --指定时间的收款单
        INNER JOIN #tableAllReturn c ON a.GoodsBillID=c.BillNumberID         --指定职员范围内的销售退货单   徐辉 2004.9.3
        GROUP BY c.ETypeID
       
        --得到指定时间范围内按销售退货单结算的付款单（按销售退货单中的职员来统计，但金额按付款单中的计算，因为可能不是足额支付）
        SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableRangePaySumUp FROM CompleteTotal a
        INNER JOIN #tableRangePay b ON a.MoneyBillID=b.BillNumberID        --指定时间的付款单
        INNER JOIN #tableAllReturn c ON a.GoodsBillID=c.BillNumberID       --指定职员范围内的销售退货
        GROUP BY c.ETypeID
		
        
END    
IF @intUnPayed=1
BEGIN
	    --得到职员范围内所有按销售出库单结算的收款单（无时间限制）
	    SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableAllGatheringSumUp FROM CompleteTotal a
	    INNER JOIN #tableAllGathering b ON a.MoneyBillID=b.BillNumberID
	    INNER JOIN #tableAllSale c ON a.GoodsBillID=c.BillNumberID
	    GROUP BY c.ETypeID
		 --得到职员范围内所有按销售退货单结算的收款单（无时间限制）徐辉 2004.9.3
	    SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableAllGatheringSumUpReturn FROM CompleteTotal a
	    INNER JOIN #tableAllGathering b ON a.MoneyBillID=b.BillNumberID
	    INNER JOIN #tableAllReturn c ON a.GoodsBillID=c.BillNumberID
	    GROUP BY c.ETypeID
	    
	    --得到职员范围内所有按销售退货结算的付款单（无时间限制）
	    SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableAllPaySumUp FROM CompleteTotal a
	    INNER JOIN #tableAllPay b ON a.MoneyBillID=b.BillNumberID
	    INNER JOIN #tableAllReturn c ON a.GoodsBillID=c.BillNumberID
	    GROUP BY c.ETypeID
	    
	    --得到职员范围所有销售出库单（这些销售出库单，这些单子不一定要跟收款单关联）
	    SELECT ISNULL(SUM(TotalMoney),0) AS TotalMoney,ETypeID INTO #tableAllSaleSumUp FROM #tableAllSale
	    GROUP BY ETypeID
	  
	    --得到职员范围内所有销售退货单（这些销售退货单，这些单子不一定要跟付款单关联）
	    SELECT ISNULL(SUM(TotalMoney),0) AS TotalMoney,ETypeID INTO #tableAllReturnSumUp FROM #tableAllReturn
	    GROUP BY ETypeID
END
IF @intPayed=1 OR @intUnPayed=1
BEGIN
	   DROP TABLE #BillIndexPayUnPay
	   DROP TABLE #tableAllGathering
	   DROP TABLE #tableAllPay
	   DROP TABLE #tableAllSale
	   DROP TABLE #tableAllReturn
END
IF @intPayed=1
BEGIN
       DROP TABLE #tableRangeGathering
       DROP TABLE #tableRangePay
END

CREATE TABLE #OperatorEType(TypeID varchar(100)) --#03


--得到各职员的收回赊货金额和未收赊货金额
DECLARE @strTempETypeID varchar(50)           --用于循环的职员ID
DECLARE @strSonnum INT						 --用于循环当前职员是否有子节点 --#03
DECLARE @dblRangeGathering  NUMERIC(24, 10)       --指定时间范围内的收款
DECLARE @dblRangeGatheringReturn  NUMERIC(24, 10)       --指定时间范围内的收款 徐辉 2004.9.3
DECLARE @dblRangePay  NUMERIC(24, 10)             --指定时间范围内的付款
DECLARE @dblAllGathering  NUMERIC(24, 10)         --所有的收款
DECLARE @dblAllGatheringReturn  NUMERIC(24, 10)         --所有的销售退货收款 徐辉 2004.9.3
DECLARE @dblAllPay  NUMERIC(24, 10)               --所有的付款
DECLARE @dblAllSale  NUMERIC(24, 10)              --所有的销售出库
DECLARE @dblAllReturn  NUMERIC(24, 10)            --所有的销售退货
DECLARE @dblRangeReceiveMoney  NUMERIC(24, 10)    --收回赊货金额
DECLARE @dblAllUnPayedMoney  NUMERIC(24, 10)      --未收赊货金额

CREATE TABLE #tableMoney(ETypeID varchar(50),RangeReceiveMoney  NUMERIC(24, 10) ,AllUnPayedMoney  NUMERIC(24, 10) )

if @istree=1
begin
	DECLARE EType_Cursor CURSOR
	FOR SELECT ETypeID,sonnum FROM #Employee ORDER BY UserCode--#03 sonnum 添加当前职员是否存在子节点
	OPEN EType_Cursor
	FETCH NEXT FROM EType_Cursor INTO @strTempETypeID,@strSonnum --#03 @strSonnum
	WHILE @@FETCH_STATUS=0
	BEGIN
		/* #03 BEGIN */
		IF @strSonnum>0 
		BEGIN
			INSERT INTO #OperatorEType
			SELECT TypeId FROM #EType WHERE Parid LIKE @strTempETypeID+'%' AND soncount=0 		
		END
		ELSE
		BEGIN
			INSERT #OperatorEType VALUES(@strTempETypeID)
		END
		/* #03 END */
		
	      --本期收回赊货金额=本期销售出库收款单金额-本期销售退货付款单金额
	      --总的未收赊货金额=（总的销售出库单金额-总的销售退货单金额）-（总的销售出库收款单金额+总的销售退货单收款单金额-总的销售退货付款单金额）--徐辉 2004.9.3 收款单可以收销售退货单的金额
			IF @intPayed=1   --需要计算收回赊货金额；不需要计算则直接设置为0
			  BEGIN --#03
			         SELECT @dblRangeGathering=ISNULL(SUM(TotalMoney),0) FROM #tableRangeGatheringSumUp WHERE ETypeID IN (SELECT TYPEID FROM #OperatorEType) 
					 SELECT @dblRangeGatheringReturn=ISNULL(SUM(TotalMoney),0) FROM #tableRangeGatheringSumUpReturn WHERE ETypeID IN (SELECT TYPEID FROM #OperatorEType) --本期销售退货单收款金额（实际是退款）
			         SELECT @dblRangePay=ISNULL(SUM(TotalMoney),0) FROM #tableRangePaySumUp WHERE ETypeID IN (SELECT TYPEID FROM #OperatorEType)
			         SET @dblRangeReceiveMoney=@dblRangeGathering+@dblRangeGatheringReturn-@dblRangePay
			  END
			ELSE
			  BEGIN
			         SET @dblRangeReceiveMoney=0
			  END
			
			IF @intUnPayed=1  --需要计算未收回赊货金额；不需要计算则直接设置为0
			  BEGIN --#03
			         SELECT @dblAllGathering=ISNULL(SUM(TotalMoney),0) FROM #tableAllGatheringSumUp WHERE ETypeID IN (SELECT TYPEID FROM #OperatorEType)
						 SELECT @dblAllGatheringReturn=ISNULL(SUM(TotalMoney),0) FROM #tableAllGatheringSumUpReturn WHERE ETypeID IN (SELECT TYPEID FROM #OperatorEType)
			         SELECT @dblAllPay=ISNULL(SUM(TotalMoney),0) FROM #tableAllPaySumUp WHERE ETypeID IN (SELECT TYPEID FROM #OperatorEType)
			         SELECT @dblAllSale=ISNULL(SUM(TotalMoney),0) FROM #tableAllSaleSumUp WHERE ETypeID IN (SELECT TYPEID FROM #OperatorEType)
			         SELECT @dblAllReturn=ISNULL(SUM(TotalMoney),0) FROM #tableAllReturnSumUp WHERE ETypeID IN (SELECT TYPEID FROM #OperatorEType)
			         SET @dblAllUnPayedMoney=(@dblAllSale-@dblAllReturn)-(@dblAllGathering+@dblAllGatheringReturn-@dblAllPay)
			  END
			ELSE
			  BEGIN
			         SET @dblAllUnPayedMoney=0
			  END
			INSERT INTO #tableMoney(ETypeID,RangeReceiveMoney,AllUnPayedMoney) VALUES(@strTempETypeID,@dblRangeReceiveMoney,@dblAllUnPayedMoney)
			FETCH NEXT FROM EType_Cursor INTO @strTempETypeID,@strSonnum
			DELETE FROM #OperatorEType --#03
	END
	CLOSE EType_Cursor
	DEALLOCATE EType_Cursor
end
if @istree=0
begin
	DECLARE EType_Cursor CURSOR
	FOR SELECT ETypeID,sonnum FROM #Employee ORDER BY UserCode--#03 sonnum 添加当前职员是否存在子节点
	OPEN EType_Cursor
	FETCH NEXT FROM EType_Cursor INTO @strTempETypeID,@strSonnum --#03 @strSonnum
	WHILE @@FETCH_STATUS=0
	BEGIN
			IF @intPayed=1   --需要计算收回赊货金额；不需要计算则直接设置为0
			  BEGIN --#03
			         SELECT @dblRangeGathering=ISNULL(SUM(TotalMoney),0) FROM #tableRangeGatheringSumUp WHERE ETypeID=@strTempETypeID
					 SELECT @dblRangeGatheringReturn=ISNULL(SUM(TotalMoney),0) FROM #tableRangeGatheringSumUpReturn WHERE ETypeID=@strTempETypeID --本期销售退货单收款金额（实际是退款）
			         SELECT @dblRangePay=ISNULL(SUM(TotalMoney),0) FROM #tableRangePaySumUp WHERE ETypeID=@strTempETypeID
			         SET @dblRangeReceiveMoney=@dblRangeGathering+@dblRangeGatheringReturn-@dblRangePay
			  END
			ELSE
			  BEGIN
			         SET @dblRangeReceiveMoney=0
			  END
			
			IF @intUnPayed=1  --需要计算未收回赊货金额；不需要计算则直接设置为0
			  BEGIN --#03
			         SELECT @dblAllGathering=ISNULL(SUM(TotalMoney),0) FROM #tableAllGatheringSumUp WHERE ETypeID=@strTempETypeID
						 SELECT @dblAllGatheringReturn=ISNULL(SUM(TotalMoney),0) FROM #tableAllGatheringSumUpReturn WHERE ETypeID=@strTempETypeID
			         SELECT @dblAllPay=ISNULL(SUM(TotalMoney),0) FROM #tableAllPaySumUp WHERE ETypeID=@strTempETypeID
			         SELECT @dblAllSale=ISNULL(SUM(TotalMoney),0) FROM #tableAllSaleSumUp WHERE ETypeID=@strTempETypeID
			         SELECT @dblAllReturn=ISNULL(SUM(TotalMoney),0) FROM #tableAllReturnSumUp WHERE ETypeID=@strTempETypeID
			         SET @dblAllUnPayedMoney=(@dblAllSale-@dblAllReturn)-(@dblAllGathering+@dblAllGatheringReturn-@dblAllPay)
			  END
			ELSE
			  BEGIN
			         SET @dblAllUnPayedMoney=0
			  END
			INSERT INTO #tableMoney(ETypeID,RangeReceiveMoney,AllUnPayedMoney) VALUES(@strTempETypeID,@dblRangeReceiveMoney,@dblAllUnPayedMoney)
			FETCH NEXT FROM EType_Cursor INTO @strTempETypeID,@strSonnum
			DELETE FROM #OperatorEType --#03
	END
	CLOSE EType_Cursor
	DEALLOCATE EType_Cursor
end


	
IF @intPayed=1
	BEGIN
	      DROP TABLE  #tableRangeGatheringSumUp 
		  DROP TABLE  #tableRangeGatheringSumUpReturn
	      DROP TABLE  #tableRangePaySumUp
	END
IF @intUnPayed=1
	BEGIN
	      DROP TABLE  #tableAllGatheringSumUp
		  DROP TABLE  #tableAllGatheringSumUpReturn
	      DROP TABLE  #tableAllPaySumUp
	      DROP TABLE  #tableAllSaleSumUp
	      DROP TABLE  #tableAllReturnSumUp
	END
--通过游标循环得到相关职员，所有收支科目的费用
DECLARE @tempField varchar(4000)
DECLARE @tempFieldValue varchar(4000)
--计算收入类小计，支出类小计，利润
DECLARE @PayedValue  NUMERIC(24, 10) 
DECLARE @UnPayedValue  NUMERIC(24, 10) 
DECLARE @IncomeValue  NUMERIC(24, 10) 
DECLARE @OutcomeValue  NUMERIC(24, 10) 
DECLARE @ProfitValue  NUMERIC(24, 10) 


--徐辉2006-04-28优化，以前是#Employee游标里再嵌套一个#Atype游标
--速度很慢 －－－－－－－－－#02
CREATE TABLE #ListTable1(total  NUMERIC(24, 10) ,etypeid varchar(50),atypeid varchar(50),typeName VARCHAR(2),sonnum int)
CREATE TABLE #ListTable2(total  NUMERIC(24, 10) ,etypeid varchar(50),atypeid varchar(50),typeName VARCHAR(2))

IF @IsTree = 0 --线性表
BEGIN
	--Listtable表中，职员科目金额聚合,限定只聚合科目配置的科目
	SET @SQL='
		INSERT #ListTable2 SELECT ISNULL(SUM(l.Total),0) AS Total,l.etypeid AS etypeid,a.typeid AS atypeid ,A.typeName
		FROM #AType a 
		LEFT JOIN #ListTable l
		ON a.typeid = l.atypeid
				OR EXISTS(
			SELECT nid FROM ac_items x WHERE x.nid=l.atypeid 
				AND EXISTS( SELECT 1 FROM ac_items y WHERE y.nid=a.typeid and a.typeid not in (''payed'',''unpayed'') AND x.ntypeid LIKE y.ntypeid+''%'')
		)
		GROUP BY L.ETypeid,a.Typeid ,A.typeName
		ORDER BY l.etypeid'

END
ELSE 
BEGIN
	--Listtable表中，职员科目金额聚合,限定只聚合科目配置的科目
	SET @SQL='
		INSERT #ListTable2 SELECT ISNULL(SUM(l.Total),0) AS Total,l.ETypeid AS etypeid,a.typeid AS atypeid,A.typeName
		FROM #Atype a 
		JOIN 
		(SELECT ISNULL(SUM(lt.total),0) AS total,e.Etypeid AS Etypeid,lt.Atypeid  AS Atypeid
			FROM #Employee e
			JOIN #ListTable lt
				ON e.Etypeid = LEFT(lt.Etypeid,LEN(e.Etypeid))
			GROUP BY e.Etypeid,lt.Atypeid
		) l
			ON a.typeid = l.atypeid
			OR EXISTS(
				SELECT nid FROM ac_items x WHERE x.nid=l.atypeid 
					AND EXISTS( SELECT 1 FROM ac_items y WHERE y.nid=a.typeid and a.typeid not in (''payed'',''unpayed'') AND x.ntypeid LIKE y.ntypeid+''%'')
			)
		GROUP BY L.ETypeid,a.Typeid,A.typeName
		ORDER BY l.etypeid'
END
EXEC(@SQL)

--
	;WITH cte AS (
		SELECT a.*,b.ntypeid,b.nparid FROM  #ListTable2 a JOIN #atype b ON a.atypeid=b.typeid
	)
	, c AS (
		SELECT u.*,v.etypeid,v.total FROM #atype u JOIN cte v ON v.ntypeid LIKE u.ntypeid+'%' AND u.ntypeid<>''
	)
	INSERT INTO #ListTable1 SELECT SUM(u.total),u.etypeid,u.typeid,u.typeName,v.sonnum FROM c u LEFT JOIN ac_items v ON u.typeid=v.nid GROUP BY u.ntypeid,u.nparid,u.etypeid,u.typeid,u.typeName,v.sonnum
--
--SELECT * FROM #atype;
--SELECT * FROM #ListTable1;
--RETURN;

DECLARE EType_Cursor CURSOR
FOR SELECT ETypeID FROM #Employee ORDER BY UserCode
OPEN EType_Cursor
FETCH NEXT FROM EType_Cursor INTO @strTempETypeID
WHILE @@FETCH_STATUS=0
BEGIN               
		SET @SQL = 'INSERT #tableResult (EtypeId) VALUES('''+@strTempETypeID+''')'
        EXEC(@SQL)
	    FETCH NEXT FROM EType_Cursor INTO @strTempETypeID
END
--整个的还需要加上合计
CLOSE EType_Cursor
DEALLOCATE EType_Cursor



DECLARE @strTempTotal varchar(50)
DECLARE Total_Cursor CURSOR
FOR SELECT l.total,l.etypeid,l.atypeid,L.typename FROM #Listtable1 l
OPEN Total_Cursor
FETCH NEXT FROM Total_Cursor INTO @strTempTotal,@strTempEtypeid,@strTempAtypeid,@TypeName
WHILE @@FETCH_STATUS=0
BEGIN 
	
    SET @IncomeValue=0
    SET @OutcomeValue=0
    SET @ProfitValue=0
	SET @PayedValue=0
	SET @UnPayedValue=0
	
	SET @sql=''
	--IF @strTempAtypeid NOT IN ()
	IF  EXISTS(SELECT 1 FROM tempdb.sys.columns WHERE object_id=object_id('tempdb..#tableResult') AND name=@TypeName+@strTempAtypeid)
		SET @SQL =@sql+ ',['+@TypeName+@strTempAtypeid+']='+@strTempTotal 
   
	
	--收入类小计
	IF @intIncomeSumUp =1 AND EXISTS(SELECT 1 FROM tempdb.sys.columns WHERE object_id=object_id('tempdb..#tableResult') AND name='Income')
	BEGIN		
		SELECT @IncomeValue = ISNULL(SUM(Total),0) FROM #Listtable1 WHERE etypeid = @strTempETypeID AND typeName='G' --AND sonnum=0
		SET @SQL = @SQL + ',[Income]='+CONVERT(varchar(50),@IncomeValue)
	END
	--支出类小计
	IF @intOutcomeSumUp =1 AND EXISTS(SELECT 1 FROM tempdb.sys.columns WHERE object_id=object_id('tempdb..#tableResult') AND name='Outcome')
	BEGIN		
		SELECT @OutcomeValue = ISNULL(SUM(Total),0) FROM #Listtable1 WHERE etypeid = @strTempETypeID  AND typeName='E' --AND sonnum=0
		 SET @SQL = @SQL + ',[Outcome]='+CONVERT(varchar(50),@OutcomeValue)
	END
    --加上利润
    IF (@intIncomeSumUp=1 AND @intOutcomeSumUp=1) AND EXISTS(SELECT 1 FROM tempdb.sys.columns WHERE object_id=object_id('tempdb..#tableResult') AND name='Profit')
    BEGIN
       SET @ProfitValue=@IncomeValue-@OutcomeValue
	   SET @SQL = @SQL + ',[Profit]='+CONVERT(varchar(50),@ProfitValue)
    END 
    
    
	--SET @SQL = @SQL + ',[Income]='+CONVERT(varchar(50),@IncomeValue)+',[Outcome]='+CONVERT(varchar(50),@OutcomeValue)+' WHERE EtypeId='''+@strTempEtypeid+''''
	IF @sql<>''
	begin
		SET @SQL = @SQL + ' WHERE EtypeId='''+@strTempEtypeid+''''
		SET @sql=' UPDATE #tableResult SET '+STUFF(@SQL,1,1,'');
		EXEC(@SQL)
	END
	
	FETCH NEXT FROM Total_Cursor INTO @strTempTotal,@strTempEtypeid,@strTempAtypeid,@TypeName
END
CLOSE Total_Cursor
DEALLOCATE Total_Cursor

--RETURN

--单独加上收回赊货金额,未收赊货金额,用户配置只有收回赊货金额,未收赊货金额时
IF @intPayed=1 OR @intUnPayed=1
BEGIN
	DECLARE @strTempRangeReceiveMoney varchar(50),@strTempAllUnPayedMoney varchar(50)
	DECLARE Total_PayUnpay CURSOR
	FOR SELECT ETypeID,RangeReceiveMoney,AllUnPayedMoney FROM #tableMoney
	OPEN Total_PayUnpay
	FETCH NEXT FROM Total_PayUnpay INTO @strTempEtypeid,@strTempRangeReceiveMoney,@strTempAllUnPayedMoney
	WHILE @@FETCH_STATUS=0
	BEGIN
		--加上收回赊货金额
	    IF @intPayed=1  AND EXISTS(SELECT 1 FROM tempdb.sys.columns WHERE object_id=object_id('tempdb..#tableResult') AND name='Payed')
	    BEGIN
		   SET @SQL='UPDATE #tableResult SET [Payed]='+@strTempRangeReceiveMoney+' WHERE ETypeID='''+@strTempETypeID+''''
		  
		   EXEC(@SQL)
		END
	    --加上未收赊货金额
	    IF @intUnPayed=1 AND EXISTS(SELECT 1 FROM tempdb.sys.columns WHERE object_id=object_id('tempdb..#tableResult') AND name='UnPayed')
	    BEGIN
		   SET @SQL='UPDATE #tableResult SET [UnPayed]='+@strTempAllUnPayedMoney+' WHERE ETypeID='''+@strTempETypeID+''''
		   EXEC(@SQL)
	    END
		FETCH NEXT FROM Total_PayUnpay INTO @strTempEtypeid,@strTempRangeReceiveMoney,@strTempAllUnPayedMoney
	END
	CLOSE Total_PayUnpay
	DEALLOCATE Total_PayUnpay
END

--#tableResult中记录了所有的职员创利表
--复制表结构，用于过滤，排序
SELECT * INTO #tableConResult  FROM #tableResult WHERE 0=1  --永假式，不读入任何记录
--修改表结构，加入姓名字段，儿子字段
ALTER TABLE   #tableConResult ADD NAME varchar(200) NULL,SonNum int,UserCode varchar(200) NULL
--条件过滤，排序（分页是对条件过滤，排序后进行的）
SET @SQL='
		INSERT #tableConResult 
			SELECT a.*,b.NAME,b.SonNum,b.UserCode 
			FROM #tableResult a 
				INNER JOIN #Employee b 
					ON a.ETypeID=b.ETypeID '
IF LTRIM(RTRIM(@Condition))<>'' SET @SQL=@SQL+' '+@Condition
--IF LTRIM(RTRIM(@Order))='' SET @Order=' ORDER BY b.name asc '  --默认按职员姓名排序
SET @SQL=@SQL

EXEC(@SQL)


--计算总的页数，写在合计项的SonNum字段中
DECLARE @PageCount int,@Remain int
DECLARE @RecordCount int
SELECT @RecordCount =Count(EtypeID) FROM #tableConResult
SELECT @PageCount=(@RecordCount/@PageRows),@Remain=(@RecordCount%@PageRows) --FROM #tableConResult  --@PageCount保留整数部分，@Remain表示余数部分
--如果有余数，则页数加1
IF @Remain>0 
BEGIN
   SET @PageCount=@PageCount+1
END

--复制表结构，用于分页（是对过滤，排序后的结果集进行分页）
SELECT * INTO #tablePageResult FROM #tableConResult WHERE 0=1

 IF LTRIM(RTRIM(@Order))='' SET @Order=' ORDER BY name asc '  --默认按职员姓名排序

--
DECLARE @Orderx NVARCHAR(max)='';
SET @orderx=RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(LOWER(@order),'order by',''),'asc',''),'desc','')));
SET @orderx=REPLACE(REPLACE(@orderx,'[',''),']','')
if NOT EXISTS(SELECT 1 FROM tempdb.sys.columns WHERE object_id=object_id('tempdb..#tablePageResult') AND name=@orderx)
	SET @order=REPLACE(@order,@orderx,'income');
--
 
IF @PrintFlag=1
BEGIN  
   --分页控制
   DECLARE @m int
   DECLARE @n int
   SET @m=(@PageNo-1)*@PageRows
   SET @n=@PageNo*@PageRows
   --@PageRows表示每页的行数,@PageNo表示当前查询的页数,需要显示的记录是从(@PageNo-1)*@PageRows,@PageNo*@PageRows
   --显示从m+1，到n的记录
   SET @SQL=' INSERT #tablePageResult SELECT * FROM ( SELECT TOP '+CAST(@n AS varchar(50))+' *  FROM #tableConResult'+ @Order+') a WHERE a.ETypeID NOT IN  (SELECT TOP '+CAST(@m AS varchar(50))+'  ETypeID FROM #tableConResult'+ @Order+') '+@Order 

END
ELSE
BEGIN
   --打印时虽然不分页，但为统一显示，所以仍然把数据读入到#tablePageResult中
   SET @SQL=' INSERT #tablePageResult SELECT * FROM #tableConResult '
END


EXEC(@SQL)
--在最后插入一条总的合计（从#tableConResult中得到）
DECLARE @Total varchar(50)  --合计的会计科目和名称
DECLARE @iop VARCHAR(500)

SET @Total='合计'
SET @iop=',isnull(sum(income),0) as income,isnull(sum(outcome),0) as outcome,isnull(sum(profit),0) as profit ';

--SET @SQL='INSERT #tablePageResult SELECT  '+char(39)+@Total+char(39)+','+@SumSQL
DECLARE @SQLx varchar(8000),@sql1 VARCHAR(8000),@sql2 VARCHAR(8000)
SET @SQLx=@SumSQL1+''+char(39)+@Total+char(39)+','+CAST(@RecordCount AS varchar(50))+','+char(39)+@Total+char(39)+' FROM #tableConResult '

--EXEC(@SQL+@SQL1)

IF @hpage<>0
BEGIN --分页
	IF @htotalpage<>0
	BEGIN
		--SELECT COUNT(1) AS ct FROM tempdb.sys.columns WHERE object_id=object_id('tempdb..#Atype') AND NAME NOT IN ('EtypeId','Name','SonNum','UserCode')
		SELECT ISNULL(COUNT(1),0) FROM #atype;
	END
	ELSE
	BEGIN
	    /*
		;WITH cte AS (
			SELECT name,rn=ROW_NUMBER() over(order BY column_id asc) FROM tempdb.sys.COLUMNS 
			WHERE object_id=object_id('tempdb..#tablePageResult') AND NAME NOT IN ('EtypeId','Name','SonNum','UserCode')
		)
		SELECT @sql1=STUFF((SELECT ','+name FROM cte WHERE rn BETWEEN @bCount*(@bPageNo-1)+1 AND @bCount*@bPageNo FOR XML PATH('')),1,1,'')
		, @sql2=STUFF((SELECT ', ISNULL(SUM('+name+'),0) AS '+name FROM cte WHERE rn BETWEEN @bCount*(@bPageNo-1)+1 AND @bCount*@bPageNo FOR XML PATH('')),1,1,'');
		
		SET @sql=N'select EtypeId,'+CASE WHEN @sql1='' THEN '' ELSE @sql1+',' END +N'Name,SonNum,UserCode from #tablePageResult ';
		
		
		IF @PrintFlag=1
			SET @sql=@sql+' union all select '+char(39)+@Total+char(39)+','+CASE WHEN @sql2='' THEN '' ELSE @sql2+',' END
			+char(39)+@Total+char(39)+','+CAST(@RecordCount AS varchar(50))+','+char(39)+@Total+char(39)+' FROM #tableConResult';
		ELSE
			SET @sql=N'select EtypeId,'+CASE WHEN @sql1='' THEN '' ELSE @sql1+',' END +N'Name,SonNum,UserCode into #tablePageResult1 from #tablePageResult '+@order
			+@sql+' union all select '+char(39)+@Total+char(39)+','+CASE WHEN @sql2='' THEN '' ELSE @sql2+',' END
			+char(39)+@Total+char(39)+','+CAST(@RecordCount AS varchar(50))+','+char(39)+@Total+char(39)+' FROM #tableConResult';
		*/
	
		IF @PrintFlag=1 
			SET @sql=' select * from #tablePageResult union all select '+char(39)+@Total+char(39)+@iop+','+@SumSQL+@sqlx;
		ELSE 
			SET @sql='select * into #tablePageResult1 from #tablePageResult '+@order+'; select * from #tablePageResult1 union all select'+char(39)+@Total+char(39)+@iop+','+@SumSQL+@sqlx;
		EXEC (@sql);
	END
END
ELSE
BEGIN --不垂直分页
	--查询
	IF @PrintFlag=1 
		SET @sql=' select * from #tablePageResult union all select '+char(39)+@Total+char(39)+@iop+','+@SumSQL+@sqlx;
	ELSE 
	SET @sql='select * into #tablePageResult1 from #tablePageResult '+@order+'; select * from #tablePageResult1 union all select'+char(39)+@Total+char(39)+@iop+','+@SumSQL+@sqlx;
	
	EXEC(@sql)
END


 

--IF (@intIncomeSumUp=1) AND (@intOutcomeSumUp=1) INSERT INTO #AType(TypeID,ParID,FullName) VALUES(@Profit,@root,@ProfitName)
DROP TABLE #OldAType
DROP TABLE #Employee
DROP TABLE #Stype
DROP TABLE #tableConResult
DROP TABLE #tablePageResult,#EType
DROP TABLE #tableResult
DROP TABLE #ListTable
DROP TABLE #ListTable1
DROP TABLE #AType
DROP TABLE #tableMoney
DROP TABLE #OperatorEType 


--SELECT Etypeid,G3,G4,E16,E17,Payed,unpayed,income,outcome,profit,name,sonnum,usercode from test

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmpIncQuery_CARERP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmpIncQuery_CARERP]
GO











-- ========================================================================
-- 功能说明：		职员当月创利报表（树形表和线性表）
-- 最后修改作者：	冯 波
-- 最后修改时间：	2004-03-29
-- ========================================================================
-- ========================================================================
-- 修改说明：		职员当月创利报表（树形表和线性表），收款单可以结算销售出库，
--					销售退货单,故收回收回赊货金额,未收赊货金额统计油误，优惠金额
--                  应去除
-- 最后修改作者：	徐辉
-- 最后修改时间：	2004-09－03
-- ========================================================================
-- ========================================================================
-- 修改说明：		树型表不统计停用职员，线性表也要不统计停用职员
-- 最后修改作者：	徐辉
-- 最后修改时间：	2007-01－30
-- 修改标记：		#01
-- ========================================================================
-- ========================================================================
-- 修改说明：		优化查询速度 －－提高了一倍
-- 最后修改作者：	徐辉
-- 最后修改时间：	2006-04-28
-- 修改标记：		#02
-- ========================================================================
CREATE                                PROCEDURE Web_EmpIncQuery_CARERP
(
	@BeginDate       datetime,             --起始日期
	@EndDate         datetime,             --截止日期
	@ETypeID         varchar(25),          --职员ID
	@PageRows        int=14,               --每页的行数
	@PageNo          int=1,                --当前查询的页数
	@OperatorID      varchar(25),          --业务员ID，从EmpIncSet里读取他的选项配置，如果没有，则按默认的显示
	@ConditionStr    varchar(1000),        --查询条件 注意:该参数应该是 LIKE ''п'',存储过程中应该替换回来
	@OrderStr        varchar(1000),        --排序条件
	@PrintFlag       tinyint,              --1表示是页面显示，需要进行分页；2表示是用于打印，不进行分页       
	@IsTree          bit                   --1表示是树形表（显示该@ETypeID下的一级节点的信息），0表示是线形表（显示所有叶子节点的信息），这时@ETypeID传入空值，无效
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SET ANSI_WARNINGS OFF
SET NOCOUNT ON
DECLARE @ALL_INCOME_ID  varchar(25)
DECLARE @ALL_EXPENSE_ID varchar(25)
SELECT @ALL_INCOME_ID='00003'          --【收入类】
SELECT @ALL_EXPENSE_ID='00004'         --【支出类】
SELECT @ConditionStr = REPLACE(@ConditionStr,'п','%') --注意:该参数应该是 LIKE ''п'',存储过程中应该替换回来 徐辉 2005-4-5
--过滤原始单据(时间范围，职员范围，科目范围(收支类)，红冲标志)
CREATE TABLE #ListTable(ETypeID varchar(25),ATypeID varchar(25),Total  NUMERIC(24, 10) )  --定义一个临时表，记录筛选过的ListTable
DECLARE @SQL varchar(8000)
DECLARE @SumSQL varchar(8000)  --记录合计字段，用于合计
IF LTRIM(RTRIM(@ETypeID))=''  SET @ETypeID='00001'  --如果没有输入职员ID，则自动设置为根节点
CREATE TABLE #Employee(ETypeID varchar(25),NAME varchar(100),SonNum int,UserCode varchar(50) NULL) 
DECLARE @intSonNum int  --判断传入的职员是否为叶子节点
IF @IsTree=1
    BEGIN
       --需要判断该职员是否是叶子节点
       SELECT @intSonNum=SonNum FROM employee WHERE TypeID=@ETypeID 
       IF @intSonNum>0
	       BEGIN
	             --如果@IsTree=1，是树形表，那么我们需要显示的是，该节点的第一级儿子的统计信息
	             INSERT #Employee SELECT TypeID,FullName,SonNum,UserCode FROM employee WHERE ParID=@ETypeID  AND TypeId LIKE @METypeId + '%' AND Deleted=0 ORDER BY UserCode  --#01
	       END
       ELSE
	       BEGIN
	             --如果是叶子节点，则显示它自己的信息（因为它下面没有子节点了）
	             INSERT #Employee SELECT TypeID,FullName,SonNum,UserCode FROM employee WHERE TypeID=@ETypeID  AND TypeId LIKE @METypeId + '%' AND Deleted=0 ORDER BY UserCode  --#01
	       END
    END
ELSE
    BEGIN
       --如果@IsTree=0，是线形表，需要显示的是叶子节点的信息（并根据@ETypeID进行过滤）
       INSERT #Employee SELECT TypeID,FullName,SonNum,UserCode FROM employee WHERE SonNum=0  AND TypeId LIKE @METypeId + '%' AND TypeID LIKE @ETypeID+'%'AND Deleted=0 ORDER BY UserCode  --#01
    END
SET @SQL='INSERT #ListTable SELECT ETypeID,ATypeID,SUM(ISNULL(Total,0)) AS Total FROM ListTable  '
SET @SQL=@SQL+'WHERE  Audited=1 '
SET @SQL=@SQL+' AND (LEFT(ATypeID,5)='+char(39)+@ALL_INCOME_ID+char(39)+' OR LEFT(Atypeid,5)='+char(39)+@ALL_EXPENSE_ID+char(39)+')'
SET @SQL=@SQL+' AND (BillDate BETWEEN '+char(39)+CAST(@BeginDate AS varchar(50))+char(39)+' AND '+char(39)+CAST(@EndDate AS varchar(50))+char(39) + ')'
SET @SQL=@SQL+'  AND ETypeID LIKE '+char(39)+@ETypeID+'%'+char(39)
SET @SQL=@SQL+' GROUP BY EtypeID,ATypeID'
EXEC(@SQL)
--得到AType中的所有收支会计科目
SELECT TypeID,ParID,FullName INTO #OldAType FROM AType WHERE ((LEFT(TypeID,5)=@ALL_INCOME_ID) OR (LEFT(Typeid,5)=@ALL_EXPENSE_ID)) AND Deleted=0
DECLARE @strTempATypeID varchar(25)   --临时使用的会计科目变量 　　
DECLARE @dblTempTotal  NUMERIC(24, 10)   --临时使用的各收支类会计科目的合计
--根据操作员自行选择的项目对收、支项目进行过滤(在EmpIncSet表中收回赊货金额用'Payed'，未收赊货金额用'UnPayed'标志)
DECLARE @intPayed int                --表示是否显示收回赊货金额，1表示要显示，0表示不显示
DECLARE @intUnPayed int              --表示是否显示未收赊货金额，1表示要显示，0表示不显示
DECLARE @intIncomeSumUp int          --表示是否显示收入小计，1表示要显示，0表示不显示
DECLARE @intOutcomeSumUp int         --表示是否显示费用小计，1表示要显示，0表示不显示
DECLARE @Payed varchar(25)           --收回赊货金额的会计科目ID，自定义
DECLARE @UnPayed varchar(25)         --未收赊货金额的会计科目ID，自定义
SET @Payed='Payed'
SET @UnPayed='UnPayed'
DECLARE @PayedName varchar(25)        --收回赊货金额的FullName
DECLARE @UnPayedName varchar(25)      --未收赊货金额的FullName
SET @PayedName='收回赊货金额'
SET @UnPayedName='未收赊货金额'
DECLARE @Income varchar(25)          --收入小计的会计科目ID，自定义
DECLARE @Outcome varchar(25)         --支出小计的会计科目ID，自定义
SET @Income='Income'
SET @Outcome='Outcome'
DECLARE @IncomeName varchar(25)      --收入小计的FullName
DECLARE @OutcomeName varchar(25)     --支出小计的FullName
SET @IncomeName='收入类小计' 
SET @OutcomeName='支出类小计'
--判断用户是否设置了显示选项
--用户配置后的会计科目表，#AType
CREATE TABLE #AType(TypeID varchar(25),ParID varchar(25),FullName varchar(100))
IF EXISTS(SELECT ETypeID FROM EmpIncSet WHERE ETypeID=@OperatorID)
	BEGIN	    
			    SELECT @intPayed=COUNT(ATypeID) FROM EmpIncSet WHERE ETypeID=@OperatorID AND ATypeID=@Payed
			    SELECT @intUnPayed=COUNT(ATypeID) FROM EmpIncSet WHERE ETypeID=@OperatorID AND ATypeID=@UnPayed
		            --得到过滤后的会计科目
			    INSERT #AType SELECT a.TypeID,a.ParID,a.FullName  FROM #OldAType a
			    WHERE EXISTS
			    (
			          SELECT b.ETypeID FROM EmpIncSet b WHERE b.ATypeID=a.TypeID AND b.ETypeID=@OperatorID
			    )
	            ORDER BY a.TypeID
	            --如果有收入类的会计科目，则需要显示收入类小计
	            IF EXISTS(SELECT ETypeID FROM EmpIncSet WHERE ETypeID=@OperatorID AND LEFT(ATypeID,5)=@ALL_INCOME_ID)
	               SET @intIncomeSumUp=1
	            ELSE
					IF EXISTS(SELECT ETypeID FROM EmpIncSet WHERE ETypeID=@OperatorID AND ATypeID='Payed')
						SET @intIncomeSumUp=1
					ELSE
	               		SET @intIncomeSumUp=0
	            --如果有支出类的会计科目，则需要显示支出类小计
	            IF EXISTS(SELECT ETypeID FROM EmpIncSet WHERE ETypeID=@OperatorID AND LEFT(ATypeID,5)=@ALL_EXPENSE_ID)
	               SET @intOutcomeSumUp=1
	            ELSE
					IF EXISTS(SELECT ETypeID FROM EmpIncSet WHERE ETypeID=@OperatorID AND ATypeID='UnPayed')
						SET @intOutcomeSumUp=1
					ELSE
	               		SET @intOutcomeSumUp=0
	END
ELSE
	BEGIN
	            --默认要显示收回赊货金额，未收赊货金额，收入小计，费用小计
	            SET @intPayed=1
	            SET @intUnPayed=1
	            SET @intIncomeSumUp=1
	            SET @intOutcomeSumUp=1
	            --默认显示一级节点的收入/支出会计科目
	            SET @SQL='INSERT #AType SELECT TypeID,ParID,FullName FROM #OldAType WHERE ParID='+char(39)+@ALL_INCOME_ID+char(39)+' OR ParID='+char(39)+@ALL_EXPENSE_ID+char(39)+' ORDER BY TypeID '
	            EXEC(@SQL)
	END
--根据@intPayed,@intUnPayed来决定是否显示收回赊货金额，未收赊货金额
IF @intPayed=1   INSERT INTO #AType(TypeID,ParID,FullName) VALUES(@Payed,@ALL_INCOME_ID,@PayedName)
IF @intUnPayed=1 INSERT INTO #AType(TypeID,ParID,FullName) VALUES(@UnPayed,@ALL_EXPENSE_ID,@UnPayedName)
--根据@intIncome,@intOutcome来决定是否显示收入类小计，支出类小计，利润
IF @intIncomeSumUp=1  INSERT INTO #AType(TypeID,ParID,FullName) VALUES(@Income,@ALL_INCOME_ID,@IncomeName)
IF @intOutcomeSumUp=1 INSERT INTO #AType(TypeID,ParID,FullName) VALUES(@Outcome,@ALL_EXPENSE_ID,@OutcomeName)
DECLARE @root varchar(25)         --利润算到根节点下
SET @root='00000'
DECLARE @Profit varchar(25)       --利润的会计科目ID，自定义
SET @Profit='Profit'
DECLARE @ProfitName varchar(25)   --利润的FullName
SET @ProfitName='利润'
IF (@intIncomeSumUp=1) AND (@intOutcomeSumUp=1) INSERT INTO #AType(TypeID,ParID,FullName) VALUES(@Profit,@root,@ProfitName)
DROP TABLE #OldAType
--建立一个动态的临时表来保存结果，包括的字段是：职员ID，各类收入，然后在游标的两层循环都往相应的字段填入值，并计算收入和费用的合计（首先需要计算是否选择了这两项）
DECLARE @i int
SET @i=0
SET @SumSQL = ''
DECLARE @AtypeName varchar(66)
SET @AtypeName =''
DECLARE @ColName varchar(8000)
SET @ColName='R.EtypeID'
SET @SQL='ALTER TABLE #tableResult '
CREATE TABLE #tableResult(ETypeID varchar(25))    
DECLARE AType_Cursor CURSOR
FOR SELECT typeid,fullname FROM #AType
OPEN AType_Cursor
FETCH NEXT FROM AType_Cursor INTO @strTempATypeID,@AtypeName
WHILE @@FETCH_STATUS=0
BEGIN
      IF @i=0 
         SET @SQL=@SQL+' ADD '
      ELSE
         SET @SQL=@SQL+' , '
      SET @i=@i+1
      SET @SQL=@SQL+' ['+@strTempATypeID+']'+'  NUMERIC(24, 10)  DEFAULT 0 '
	  SET @SumSQL = @SumSQL + 'ISNULL(SUM(['+@strTempATypeID+']),0),'
	  SET @ColName = @ColName +',R.['+@strTempATypeID+'] as '+'['+@AtypeName+'|'+@strTempATypeID+']'
      FETCH NEXT FROM AType_Cursor INTO @strTempATypeID,@AtypeName
END
EXEC(@SQL) --执行改表操作
CLOSE AType_Cursor
DEALLOCATE AType_Cursor


--判断用户是否选择了收回赊货金额,未收赊货金额（计算收回赊货金额和未收赊货金额比较耗费资源）
--计算收回赊货金额需要用到的表是：#tableAllGathering,#tableAllPay,#tableAllSale,#tableAllReturn,#tableAllGathering,#tableRangePay,#tableRangeGatheringSumUp,#tableRangePaySumUp
--计算未收回赊货金额需要用到的表是：#tableAllGathering,#tableAllPay,#tableAllSale,#tableAllReturn,#tableAllGatheringSumUp,#tableAllPaySumUp,#tableAllSaleSumUp,#tableAllReturnSumUp
   
--所有的统计以销售出库/销售退货的业务员为主，因此收款单/付款单都不过滤业务员，只需要在销售出库/销售退货中过滤即可；而收款时间则在收款单/付款单中过滤，不在销售出库/销售退货中过滤
IF @intPayed=1 OR @intUnPayed=1 
BEGIN
	--收缩billindex表
	SELECT BillNumberID,BillType,TotalMoney,EtypeId,TotalInMoney,preferencemoney,BillDate INTO #BillIndexPayUnPay 
		FROM BillIndex
	WHERE 
		BillType IN(4,11,66,45,141,160)
		AND IfCheck = 't'
		AND RedWord = 0
		AND BillDate BETWEEN @BeginDate AND @EndDate
    --得到所有的收款单
    SELECT BillNumberID,TotalMoney,BillDate INTO #tableAllGathering FROM #BillIndexPayUnPay WHERE BillType=4
        
	    
    --得到所有的付款单
    SELECT BillNumberID,TotalMoney,BillDate INTO #tableAllPay FROM #BillIndexPayUnPay WHERE BillType=66
	   
        --得到职员范围内所有的销售出库单（扣除现结的）
        CREATE TABLE #tableAllSale(BillNumberID int,TotalMoney  NUMERIC(24, 10)  NULL,ETypeID varchar(25),BillDate datetime)
        
           SET @SQL='INSERT #tableAllSale SELECT BillNumberID,TotalMoney-TotalInMoney-preferencemoney AS TotalMoney,ETypeID,BillDate FROM #BillIndexPayUnPay '
           --SET @SQL=@SQL+' WHERE BillType IN (11,45) AND IfCheck=''t'' '   --添加销售退货单,减去优惠金额 徐辉 2004.9.3 
		  -- chen_qihua 004-09-02
           SET @SQL=@SQL+'WHERE ETypeID LIKE '+char(39)+@ETypeID+'%'+char(39)
		   SET @SQL=@SQL+'AND ( BillType=11 OR BillType=141  OR BillType = 160 )' 
		   EXEC(@SQL)
        --得到职员范围内所有的销售退货单（扣除现结的）
        CREATE TABLE #tableAllReturn(BillNumberID int,TotalMoney  NUMERIC(24, 10)  NULL,ETypeID varchar(25),BillDate datetime)
        
           SET @SQL='INSERT #tableAllReturn SELECT BillNumberID,TotalMoney-TotalInMoney-preferencemoney AS TotalMoney,ETypeID,BillDate  FROM #BillIndexPayUnPay '
           SET @SQL=@SQL+'WHERE ETypeID LIKE '+char(39)+@ETypeID+'%'+char(39)     --减去优惠金额 徐辉 2004.9.3 
		   SET @SQL=@SQL+'AND ( BillType=45 )'     
		   EXEC(@SQL)
       
       
END
IF @intPayed=1
BEGIN
        --得到指定时间范围内所有的收款单
        SELECT BillNumberID,TotalMoney INTO #tableRangeGathering FROM #tableAllGathering
        
        --得到指定时间范围内所有的付款单
        SELECT BillNumberID,TotalMoney INTO #tableRangePay FROM #tableAllPay
       
        --得到指定时间范围内按销售出库单结算的收款单（按销售出库单中的职员来统计，但金额按收款单中的计算，因为可能不是足额支付）
        SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableRangeGatheringSumUp FROM CompleteTotal a
        INNER JOIN #tableRangeGathering b ON a.MoneyBillID=b.BillNumberID  --指定时间的收款单
        INNER JOIN #tableAllSale c ON a.GoodsBillID=c.BillNumberID         --指定职员范围内的销售出库单
        GROUP BY c.ETypeID
	
		--得到指定时间范围内按销售退货单结算的收款单（按销售出库单中的职员来统计，但金额按收款单中的计算，因为可能不是足额支付）
        SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableRangeGatheringSumUpReturn FROM CompleteTotal a
        INNER JOIN #tableRangeGathering b ON a.MoneyBillID=b.BillNumberID  --指定时间的收款单
        INNER JOIN #tableAllReturn c ON a.GoodsBillID=c.BillNumberID         --指定职员范围内的销售退货单   徐辉 2004.9.3
        GROUP BY c.ETypeID
       
        --得到指定时间范围内按销售退货单结算的付款单（按销售退货单中的职员来统计，但金额按付款单中的计算，因为可能不是足额支付）
        SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableRangePaySumUp FROM CompleteTotal a
        INNER JOIN #tableRangePay b ON a.MoneyBillID=b.BillNumberID        --指定时间的付款单
        INNER JOIN #tableAllReturn c ON a.GoodsBillID=c.BillNumberID       --指定职员范围内的销售退货
        GROUP BY c.ETypeID
		
        
END    
IF @intUnPayed=1
BEGIN
	    --得到职员范围内所有按销售出库单结算的收款单（无时间限制）
	    SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableAllGatheringSumUp FROM CompleteTotal a
	    INNER JOIN #tableAllGathering b ON a.MoneyBillID=b.BillNumberID
	    INNER JOIN #tableAllSale c ON a.GoodsBillID=c.BillNumberID
	    GROUP BY c.ETypeID
		 --得到职员范围内所有按销售退货单结算的收款单（无时间限制）徐辉 2004.9.3
	    SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableAllGatheringSumUpReturn FROM CompleteTotal a
	    INNER JOIN #tableAllGathering b ON a.MoneyBillID=b.BillNumberID
	    INNER JOIN #tableAllReturn c ON a.GoodsBillID=c.BillNumberID
	    GROUP BY c.ETypeID
	    
	    --得到职员范围内所有按销售退货结算的付款单（无时间限制）
	    SELECT  ISNULL(SUM(a.CompleteTotal),0) AS TotalMoney,c.ETypeID INTO #tableAllPaySumUp FROM CompleteTotal a
	    INNER JOIN #tableAllPay b ON a.MoneyBillID=b.BillNumberID
	    INNER JOIN #tableAllReturn c ON a.GoodsBillID=c.BillNumberID
	    GROUP BY c.ETypeID
	    
	    --得到职员范围所有销售出库单（这些销售出库单，这些单子不一定要跟收款单关联）
	    SELECT ISNULL(SUM(TotalMoney),0) AS TotalMoney,ETypeID INTO #tableAllSaleSumUp FROM #tableAllSale
	    GROUP BY ETypeID
	  
	    --得到职员范围内所有销售退货单（这些销售退货单，这些单子不一定要跟付款单关联）
	    SELECT ISNULL(SUM(TotalMoney),0) AS TotalMoney,ETypeID INTO #tableAllReturnSumUp FROM #tableAllReturn
	    GROUP BY ETypeID
END
IF @intPayed=1 OR @intUnPayed=1
BEGIN
	   DROP TABLE #BillIndexPayUnPay
	   DROP TABLE #tableAllGathering
	   DROP TABLE #tableAllPay
	   DROP TABLE #tableAllSale
	   DROP TABLE #tableAllReturn
END
IF @intPayed=1
BEGIN
       DROP TABLE #tableRangeGathering
       DROP TABLE #tableRangePay
END
--得到各职员的收回赊货金额和未收赊货金额
DECLARE @strTempETypeID varchar(25)           --用于循环的职员ID
DECLARE @dblRangeGathering  NUMERIC(24, 10)       --指定时间范围内的收款
DECLARE @dblRangeGatheringReturn  NUMERIC(24, 10)       --指定时间范围内的收款 徐辉 2004.9.3
DECLARE @dblRangePay  NUMERIC(24, 10)             --指定时间范围内的付款
DECLARE @dblAllGathering  NUMERIC(24, 10)         --所有的收款
DECLARE @dblAllGatheringReturn  NUMERIC(24, 10)         --所有的销售退货收款 徐辉 2004.9.3
DECLARE @dblAllPay  NUMERIC(24, 10)               --所有的付款
DECLARE @dblAllSale  NUMERIC(24, 10)              --所有的销售出库
DECLARE @dblAllReturn  NUMERIC(24, 10)            --所有的销售退货
DECLARE @dblRangeReceiveMoney  NUMERIC(24, 10)    --收回赊货金额
DECLARE @dblAllUnPayedMoney  NUMERIC(24, 10)      --未收赊货金额
CREATE TABLE #tableMoney(ETypeID varchar(25),RangeReceiveMoney  NUMERIC(24, 10) ,AllUnPayedMoney  NUMERIC(24, 10) )
DECLARE EType_Cursor CURSOR
FOR SELECT ETypeID FROM #Employee ORDER BY UserCode
OPEN EType_Cursor
FETCH NEXT FROM EType_Cursor INTO @strTempETypeID
WHILE @@FETCH_STATUS=0
BEGIN
      --本期收回赊货金额=本期销售出库收款单金额-本期销售退货付款单金额
      --总的未收赊货金额=（总的销售出库单金额-总的销售退货单金额）-（总的销售出库收款单金额+总的销售退货单收款单金额-总的销售退货付款单金额）--徐辉 2004.9.3 收款单可以收销售退货单的金额
      IF @intPayed=1   --需要计算收回赊货金额；不需要计算则直接设置为0
	      BEGIN
	             SELECT @dblRangeGathering=ISNULL(SUM(TotalMoney),0) FROM #tableRangeGatheringSumUp WHERE ETypeID LIKE @strTempETypeID+'%'
				 SELECT @dblRangeGatheringReturn=ISNULL(SUM(TotalMoney),0) FROM #tableRangeGatheringSumUpReturn WHERE ETypeID LIKE @strTempETypeID+'%' --本期销售退货单收款金额（实际是退款）
	             SELECT @dblRangePay=ISNULL(SUM(TotalMoney),0) FROM #tableRangePaySumUp WHERE ETypeID LIKE @strTempETypeID+'%'
	             SET @dblRangeReceiveMoney=@dblRangeGathering+@dblRangeGatheringReturn-@dblRangePay
	      END
      ELSE
	      BEGIN
	             SET @dblRangeReceiveMoney=0
	      END
      
      IF @intUnPayed=1  --需要计算未收回赊货金额；不需要计算则直接设置为0
	      BEGIN
	             SELECT @dblAllGathering=ISNULL(SUM(TotalMoney),0) FROM #tableAllGatheringSumUp WHERE ETypeID LIKE @strTempETypeID+'%'
					 SELECT @dblAllGatheringReturn=ISNULL(SUM(TotalMoney),0) FROM #tableAllGatheringSumUpReturn WHERE ETypeID LIKE @strTempETypeID+'%'
	             SELECT @dblAllPay=ISNULL(SUM(TotalMoney),0) FROM #tableAllPaySumUp WHERE ETypeID LIKE @strTempETypeID+'%'
	             SELECT @dblAllSale=ISNULL(SUM(TotalMoney),0) FROM #tableAllSaleSumUp WHERE ETypeID LIKE @strTempETypeID+'%'
	             SELECT @dblAllReturn=ISNULL(SUM(TotalMoney),0) FROM #tableAllReturnSumUp WHERE ETypeID LIKE @strTempETypeID+'%'
	             SET @dblAllUnPayedMoney=(@dblAllSale-@dblAllReturn)-(@dblAllGathering+@dblAllGatheringReturn-@dblAllPay)
	      END
      ELSE
	      BEGIN
	             SET @dblAllUnPayedMoney=0
	      END
      INSERT INTO #tableMoney(ETypeID,RangeReceiveMoney,AllUnPayedMoney) VALUES(@strTempETypeID,@dblRangeReceiveMoney,@dblAllUnPayedMoney)
      FETCH NEXT FROM EType_Cursor INTO @strTempETypeID
END
CLOSE EType_Cursor
DEALLOCATE EType_Cursor
IF @intPayed=1
	BEGIN
	      DROP TABLE  #tableRangeGatheringSumUp 
		  DROP TABLE  #tableRangeGatheringSumUpReturn
	      DROP TABLE  #tableRangePaySumUp
	END
IF @intUnPayed=1
	BEGIN
	      DROP TABLE  #tableAllGatheringSumUp
		  DROP TABLE  #tableAllGatheringSumUpReturn
	      DROP TABLE  #tableAllPaySumUp
	      DROP TABLE  #tableAllSaleSumUp
	      DROP TABLE  #tableAllReturnSumUp
	END
--通过游标循环得到相关职员，所有收支科目的费用
DECLARE @tempField varchar(4000)
DECLARE @tempFieldValue varchar(4000)
--计算收入类小计，支出类小计，利润
DECLARE @PayedValue  NUMERIC(24, 10) 
DECLARE @UnPayedValue  NUMERIC(24, 10) 
DECLARE @IncomeValue  NUMERIC(24, 10) 
DECLARE @OutcomeValue  NUMERIC(24, 10) 
DECLARE @ProfitValue  NUMERIC(24, 10) 
--徐辉2006-04-28优化，以前是#Employee游标里再嵌套一个#Atype游标
--速度很慢 －－－－－－－－－#02
CREATE TABLE #ListTable1(total  NUMERIC(24, 10) ,etypeid varchar(25),atypeid varchar(25))
IF @IsTree = 0 --线性表
BEGIN
	--Listtable表中，职员科目金额聚合,限定只聚合科目配置的科目
	SET @SQL='
		INSERT #ListTable1 SELECT ISNULL(SUM(l.Total),0) AS Total,l.etypeid AS etypeid,a.typeid AS atypeid 
		FROM #AType a 
		LEFT JOIN #ListTable l
		ON a.typeid = LEFT(l.atypeid,LEN(a.typeid))
		GROUP BY L.ETypeid,a.Typeid 
		ORDER BY l.etypeid'
	EXEC(@SQL)
END
ELSE 
BEGIN
	--Listtable表中，职员科目金额聚合,限定只聚合科目配置的科目
	SET @SQL='
		INSERT #ListTable1 SELECT ISNULL(SUM(l.Total),0) AS Total,l.ETypeid AS etypeid,a.typeid AS atypeid  
		FROM #Atype a 
		LEFT JOIN 
		(SELECT ISNULL(SUM(lt.total),0) AS total,e.Etypeid AS Etypeid,lt.Atypeid  AS Atypeid
			FROM #Employee e
			LEFT JOIN #ListTable lt
				ON e.Etypeid = LEFT(lt.Etypeid,LEN(e.Etypeid))
			GROUP BY e.Etypeid,lt.Atypeid
		) l
			ON a.typeid = LEFT(l.atypeid,LEN(a.typeid))
		GROUP BY L.ETypeid,a.Typeid
		ORDER BY E.etypeid'
	EXEC(@SQL)
	
END


DECLARE EType_Cursor CURSOR
FOR SELECT ETypeID FROM #Employee ORDER BY UserCode
OPEN EType_Cursor
FETCH NEXT FROM EType_Cursor INTO @strTempETypeID
WHILE @@FETCH_STATUS=0
BEGIN               
		SET @SQL = 'INSERT #tableResult (EtypeId) VALUES('''+@strTempETypeID+''')'
        EXEC(@SQL)
	    FETCH NEXT FROM EType_Cursor INTO @strTempETypeID
END
--整个的还需要加上合计
CLOSE EType_Cursor
DEALLOCATE EType_Cursor
DECLARE @strTempTotal varchar(50)
DECLARE Total_Cursor CURSOR
FOR SELECT total,etypeid,atypeid FROM #Listtable1
OPEN Total_Cursor
FETCH NEXT FROM Total_Cursor INTO @strTempTotal,@strTempEtypeid,@strTempAtypeid
WHILE @@FETCH_STATUS=0
BEGIN 
	
    SET @IncomeValue=0
    SET @OutcomeValue=0
    SET @ProfitValue=0
	SET @PayedValue=0
	SET @UnPayedValue=0
	
	SET @SQL = 'UPDATE #tableResult SET ['+@strTempAtypeid+']='+@strTempTotal 
   
	--收入类小计
	IF @intIncomeSumUp =1
	BEGIN		
		SELECT @IncomeValue = ISNULL(SUM(Total),0) FROM #Listtable1 WHERE etypeid = @strTempETypeID AND LEFT(atypeid,5) = @ALL_INCOME_ID
	END
	--支出类小计
	IF @intOutcomeSumUp =1
	BEGIN		
		SELECT @OutcomeValue = ISNULL(SUM(Total),0) FROM #Listtable1 WHERE etypeid = @strTempETypeID AND LEFT(atypeid,5) = @ALL_EXPENSE_ID
	END
    --加上利润
    IF (@intIncomeSumUp=1 AND @intOutcomeSumUp=1)
    BEGIN
       SET @ProfitValue=@IncomeValue-@OutcomeValue
	   SET @SQL = @SQL + ',[Profit]='+CONVERT(varchar(50),@ProfitValue)
    END 
	SET @SQL = @SQL + ',[Income]='+CONVERT(varchar(50),@IncomeValue)+',[Outcome]='+CONVERT(varchar(50),@OutcomeValue)+' WHERE EtypeId='''+@strTempEtypeid+''''
	EXEC(@SQL)
	FETCH NEXT FROM Total_Cursor INTO @strTempTotal,@strTempEtypeid,@strTempAtypeid
END
CLOSE Total_Cursor
DEALLOCATE Total_Cursor


--单独加上收回赊货金额,未收赊货金额,用户配置只有收回赊货金额,未收赊货金额时
IF @intPayed=1 OR @intUnPayed=1
BEGIN
	DECLARE @strTempRangeReceiveMoney varchar(50),@strTempAllUnPayedMoney varchar(50)
	DECLARE Total_PayUnpay CURSOR
	FOR SELECT ETypeID,RangeReceiveMoney,AllUnPayedMoney FROM #tableMoney
	OPEN Total_PayUnpay
	FETCH NEXT FROM Total_PayUnpay INTO @strTempEtypeid,@strTempRangeReceiveMoney,@strTempAllUnPayedMoney
	WHILE @@FETCH_STATUS=0
	BEGIN
		--加上收回赊货金额
	    IF @intPayed=1 
	    BEGIN
		   SET @SQL='UPDATE #tableResult SET [Payed]='+@strTempRangeReceiveMoney+' WHERE ETypeID='''+@strTempETypeID+''''
		   EXEC(@SQL)
		END
	    --加上未收赊货金额
	    IF @intUnPayed=1
	    BEGIN
		   SET @SQL='UPDATE #tableResult SET [UnPayed]='+@strTempAllUnPayedMoney+' WHERE ETypeID='''+@strTempETypeID+''''
		   EXEC(@SQL)
	    END
		FETCH NEXT FROM Total_PayUnpay INTO @strTempEtypeid,@strTempRangeReceiveMoney,@strTempAllUnPayedMoney
	END
	CLOSE Total_PayUnpay
	DEALLOCATE Total_PayUnpay
END
DROP TABLE #ListTable
DROP TABLE #ListTable1
DROP TABLE #AType
DROP TABLE #tableMoney
--#tableResult中记录了所有的职员创利表
--复制表结构，用于过滤，排序
SELECT * INTO #tableConResult  FROM #tableResult WHERE 0=1  --永假式，不读入任何记录
--修改表结构，加入姓名字段，儿子字段
ALTER TABLE   #tableConResult ADD NAME varchar(200) NULL,SonNum int,UserCode varchar(200) NULL
--条件过滤，排序（分页是对条件过滤，排序后进行的）
SET @SQL='INSERT #tableConResult SELECT a.*,b.NAME,b.SonNum,b.UserCode FROM #tableResult a INNER JOIN #Employee b ON a.ETypeID=b.ETypeID '
IF LTRIM(RTRIM(@ConditionStr))<>'' SET @SQL=@SQL+' '+@ConditionStr
IF LTRIM(RTRIM(@OrderStr))='' SET @OrderStr=' ORDER BY b.UserCode '  --默认按职员姓名排序
SET @SQL=@SQL+' '+@OrderStr
EXEC(@SQL)
--计算总的页数，写在合计项的SonNum字段中
DECLARE @RecordCount int
DECLARE @PageCount int,@Remain int
SELECT @PageCount=(COUNT(ETypeID)/@PageRows),@Remain=(COUNT(ETypeID)%@PageRows),@RecordCount=count(etypeid) FROM #tableConResult  --@PageCount保留整数部分，@Remain表示余数部分
--如果有余数，则页数加1
IF @Remain>0 
BEGIN
   SET @PageCount=@PageCount+1
END
DROP TABLE #tableResult
--复制表结构，用于分页（是对过滤，排序后的结果集进行分页）
SELECT * INTO #tablePageResult FROM #tableConResult WHERE 0=1
IF @PrintFlag=1
BEGIN  
   --分页控制
   DECLARE @m int
   DECLARE @n int
   SET @m=(@PageNo-1)*@PageRows
   SET @n=@PageNo*@PageRows
   --@PageRows表示每页的行数,@PageNo表示当前查询的页数,需要显示的记录是从(@PageNo-1)*@PageRows,@PageNo*@PageRows
   --显示从m+1，到n的记录
   SET @SQL=' INSERT #tablePageResult SELECT * FROM ( SELECT TOP '+CAST(@n AS varchar(50))+' *  FROM #tableConResult ) a WHERE a.ETypeID NOT IN  (SELECT TOP '+CAST(@m AS varchar(50))+'  ETypeID FROM #tableConResult)'

END
ELSE
BEGIN
   --打印时虽然不分页，但为统一显示，所以仍然把数据读入到#tablePageResult中
   SET @SQL=' INSERT #tablePageResult SELECT * FROM #tableConResult '
END
EXEC(@SQL)
--在最后插入一条总的合计（从#tableConResult中得到）
DECLARE @Total varchar(25)  --合计的会计科目和名称
SET @Total='合计'
SET @SQL='INSERT #tablePageResult SELECT  '+char(39)+@Total+char(39)+','+@SumSQL+''+char(39)+@Total+char(39)+','+CAST(@PageCount AS varchar(50))+','+char(39)+@Total+char(39)+' FROM #tableConResult '
EXEC(@SQL)
DROP TABLE #Employee
DROP TABLE #tableConResult
EXEC('SELECT '+@colName+',R.Name as fullname ,R.sonnum,R.usercode,'+@RecordCount+' as recordcount FROM #tablePageResult R')
DROP TABLE #tablePageResult
 











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmpIncQueryDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmpIncQueryDetail]
GO













-- ========================================================================
-- 功能说明：		职员当月创利报表明细
-- 最后修改作者：	冯 波
-- 最后修改时间：	2004-03-29
-- ========================================================================
-- ========================================================================
-- 功能说明：		过滤维修相关的单据  #01
-- 最后修改作者：	WANG WEI 
-- 最后修改时间：	2010-09-15
-- ========================================================================

-- ========================================================================
-- 功能说明：		调整权限、调整版本
-- 最后修改作者：	徐辉 
-- 最后修改时间：	2011-03-15
-- ========================================================================


CREATE  PROCEDURE Web_EmpIncQueryDetail
(
	@OperatorId		 varchar(100),		   --操作员Id
	@StartDate       datetime,             --起始日期
    @EndDate         datetime,             --截止日期
    @ETypeID         varchar(1000),          --职员ID															  #tableBillNumberID
    @STypeID         varchar(max),         --分支机构ID
    @ATypeID         varchar(500)='',       --会计科目
    @PageRows        int=14,               --每页的行数
    @PageNo          int=1,                --当前查询的页数
    @Condition		varchar(1000),        --查询条件 注意:该参数应该是 LIKE ''п'',存储过程中应该替换回来 徐辉 2005-4-5
    @Order			varchar(1000),        --排序条件
    @PrintFlag       tinyint               --1表示是页面显示，需要进行分页；2表示是用于打印，不进行分页             
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50),@MSTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SELECT @Condition = REPLACE(@Condition,'п','%') --注意:该参数应该是 LIKE ''п'',存储过程中应该替换回来 徐辉 2005-4-5


IF LTRIM(RTRIM(@ETypeID))='' SET @ETypeID='00001'  --如果没有输入职员ID，则自动设置为根节点

SELECT  * INTO #Etype FROM F_GetManDetailEType(@OperatorId) 
WHERE typeid IN(SELECT * FROM dbo.F_BaseGetAllBaseTypeId(@ETypeID,3))



CREATE TABLE #Stype (TypeID varchar(50))

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a

--得到AType中的所有收支会计科目(权限范围内)

DECLARE @SQLTMP VARCHAR(MAX)

CREATE TABLE #AType
(
	typeid VARCHAR(500),
	ParID  VARCHAR(500),
	fullname	VARCHAR(500),
	typeName  VARCHAR(20)
)

DECLARE @NTypeID VARCHAR(50)=''
IF ISNULL(@ATypeID,'')<>'' AND @ATypeID NOT IN('UNPAYED','PAYED') AND @ATypeID NOT IN('00003','00004')
	SELECT @NTypeID=nTypeId FROM Ac_Items WHERE nId=CAST(@ATypeID AS VARCHAR(50))
SET @SQLTMP='INSERT INTO #AType(TypeID) 
			SELECT DISTINCT nid
			FROM 
				( '+CHAR(13)
IF (@NTypeID<>'' AND LEFT(@NTypeID,5)= '00003') OR @ATypeID='00003'
	BEGIN
		SET @SQLTMP+='
						SELECT nId FROM Ac_Items WHERE nTypeId LIKE ''00003%'' AND nTypeId NOT LIKE ''0000300003%'' AND SonNum=0 
						UNION ALL 
						SELECT item.nId FROM Ac_Items item INNER JOIN F_AllTreeIncomeC('''+@OperatorId+''') B ON B.nTypeID=item.nTypeID  AND item.SonNum=0 
					'+CHAR(13)

	END
IF (@NTypeID<>'' AND LEFT(@NTypeID,5)= '00004') OR @ATypeID='00004'
	BEGIN
		SET @SQLTMP+='
						SELECT nId FROM Ac_Items WHERE nTypeId LIKE ''00004%'' AND nTypeId  NOT LIKE ''0000400003%'' AND SonNum=0 
						UNION ALL 
						SELECT item.nId FROM Ac_Items item INNER JOIN F_AllTreeExpenseC('''+@OperatorId+''') B ON B.nTypeID=item.nTypeID  AND item.SonNum=0 
					'+CHAR(13)
	END
	
IF(@ATypeID IN('UNPAYED','PAYED') OR ISNULL(@ATypeID,'')='')
	BEGIN
		SET @SQLTMP+='
						SELECT nId FROM Ac_Items WHERE nTypeId LIKE ''00003%'' AND nTypeId NOT LIKE ''0000300003%'' AND SonNum=0 
						UNION ALL 
						SELECT item.nId FROM Ac_Items item INNER JOIN F_AllTreeIncomeC('''+@OperatorId+''') B ON B.nTypeID=item.nTypeID  AND item.SonNum=0 
						UNION ALL
						SELECT nId FROM Ac_Items WHERE nTypeId LIKE ''00004%'' AND nTypeId  NOT LIKE ''0000400003%'' AND SonNum=0 
						UNION ALL 
						SELECT item.nId FROM Ac_Items item INNER JOIN F_AllTreeExpenseC('''+@OperatorId+''') B ON B.nTypeID=item.nTypeID  AND item.SonNum=0 
					'+CHAR(13)
	END
	
SET @SQLTMP+= ') A '+CHAR(13)

IF EXISTS(SELECT TOP 1 1 FROM EmpIncSet WHERE EtypeID=@OperatorId AND AtypeID NOT IN('UNPAYED','PAYED'))
	SET @SQLTMP+='INNER JOIN EmpIncSet es ON  es.EtypeID='''+@OperatorId+''' AND (es.AtypeID=cast(A.nid as varchar(50)) OR a.nid in (
		SELECT nid FROM ac_items w WHERE EXISTS(SELECT 1 FROM (
			SELECT x.*,y.SonNum,y.nTypeId FROM EmpIncSet x JOIN ac_items y ON x.AtypeID NOT IN(''UNPAYED'',''PAYED'') and x.AtypeID=cast(y.nid as varchar(50))
			WHERE y.SonNum<>0
		) v WHERE w.nTypeId LIKE v.nTypeId+''%'' AND w.SonNum=0))
	) AND es.AtypeID NOT IN(''UNPAYED'',''PAYED'')'+CHAR(13)

IF @ATypeID <>'' AND @ATypeID NOT IN('UNPAYED','PAYED','00003','00004')
	--SET @SQLTMP+= ' WHERE a.NID = ' + @ATypeID
	SET @sqltmp+=' WHERE a.nid in (SELECT x.nid FROM ac_items x WHERE EXISTS(SELECT 1 FROM dbo.Ac_Items WHERE nid='+@AtypeId+' AND x.nTypeId LIKE nTypeId+''%'') AND x.SonNum=0) '
	
EXEC(@SQLTMP)
PRINT @SQLTMP;
--select * from #AType
--RETURN;

--版本
DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
CREATE TABLE #billname(billtype int)
--汽配
IF @proinfo='3'
	INSERT INTO #billname SELECT  billtype  FROM billname WHERE billtype IN(178,179,181,182,186,191,197,198,200,196,192,195)

--从BillIndex或ListTable得到关联的单据号
DECLARE @SQL varchar(MAX)

CREATE TABLE #tableBillNumberID2(BillNumberID int)

IF UPPER(@ATypeID)='PAYED'  --显示收回赊货利润所关联的单据
	BEGIN
		--先得到指定时段内的收/付款单
		SELECT BillNumberID 
		INTO #tmpPayementBill  
		FROM BillIndex 
		INNER JOIN #Stype  ON #Stype.TypeID=BillIndex.Stypeid
		WHERE 
			BillType IN(4,66) 
			AND BillDate BETWEEN @StartDate AND @EndDate
			AND IfCheck='t'  
			AND RedWord=0
			AND ifYearBill=0	 --年节存标志
			
		--得到指定人员的销售类单据
		SELECT BillNumberID 
		INTO #tmpSaleBill  
		FROM BillIndex I
		INNER JOIN #Etype e ON E.TypeId=I.etypeid
		INNER JOIN #Stype S ON S.TypeID=I.Stypeid
		INNER JOIN F_BaseGetManDetailDType(@OperatorID) F ON F.TypeId=I.DTypeId
		WHERE 
			BillType IN(11,45,141,160) 
			AND IfCheck='t' 
			AND RedWord=0 
			AND ifYearBill=0	 --年节存标志
			
		--得到按单结算的收/付款单，这些单据对应相关人员的销售类单据
		SET @SQL='INSERT #tableBillNumberID2 SELECT DISTINCT a.MoneyBillID FROM CompleteTotal a '
		SET @SQL=@SQL+'  INNER JOIN #tmpPayementBill b ON a.MoneyBillID=b.BillNumberID '
		SET @SQL=@SQL+'  INNER JOIN #tmpSaleBill c ON a.GoodsBillID=c.BillNumberID '
		EXEC(@SQL)

		--删除几个使用过的临时表
		DROP TABLE #tmpPayementBill
		DROP TABLE #tmpSaleBill
	END
ELSE
	BEGIN
		IF UPPER(@ATypeID)='UNPAYED'  --显示未收回赊货利润所关联的单据
			BEGIN
				--得到所有未结算完毕的销售类单据
				SET @SQL='INSERT #tableBillNumberID2 
						SELECT  BillNumberID 
						FROM BillIndex I
						INNER JOIN #Etype e ON E.TypeId=I.etypeid
						INNER JOIN #Stype S ON S.TypeID=I.Stypeid
						INNER JOIN F_BaseGetManDetailDType('''+@OperatorID+''') F ON F.TypeId=I.DTypeId
						WHERE 
							I.BillType IN(11,45,141,160)
							AND ( TotalMoney <> TotalInMoney + ISNULL(CompleteTotal,0) + preferencemoney ) 
							AND IfCheck=''t'' 
							AND RedWord=0  
							AND ifYearBill= 0
							
						'
				EXEC(@SQL)
				
				--优惠券
				SET @SQL='INSERT #tableBillNumberID2 
						SELECT  BillNumberID 
						FROM Coupon_BillIndex I
						INNER JOIN #Etype e ON E.TypeId=I.etypeid
						INNER JOIN #Stype S ON S.TypeID=I.Stypeid
						INNER JOIN F_BaseGetManDetailDType('''+@OperatorID+''') F ON F.TypeId=I.DTypeId
						WHERE 
							I.BillType IN(424,426)
							AND ( TotalMoney <> TotalInMoney + ISNULL(CompleteTotal,0) + preferencemoney ) 
							AND IfCheck=''t'' 
							AND RedWord=0  
							AND ifYearBill= 0
							
						'
				EXEC(@SQL)
			END
		ELSE
			BEGIN
				--其他科目所关联的单据
				SELECT DISTINCT 
					b.Stypeid,
					l.BillNumberID,
					b.billcode,
					b.BillType,
					b.BillDate,
					b.BTypeID,
					l.ETypeID,
					b.TotalMoney,
					b.TotalInMoney,
					b.TotalQty,
					b.CompleteTotal,
					b.Checke,
					b.comment
				INTO #tableBillNumberID 
				FROM ListTable l 
				--INNER JOIN BillIndex b ON l.BillNumberID=b.BillNumberID
				--增加开票单据显示
				INNER JOIN 
				(
					SELECT BillNumberID,BillType,Stypeid,BillCode,BillDate,btypeid,TotalMoney,TotalInMoney,TotalQty,
					CompleteTotal,Checke,comment,ifYearBill 
					FROM dbo.Coupon_BillIndex
					UNION ALL 
					SELECT BillNumberID,BillType,Stypeid,BillCode,BillDate,btypeid,TotalMoney,TotalInMoney,TotalQty,
					CompleteTotal,Checke,comment,ifYearBill 
					FROM dbo.BillIndex
					UNION ALL 
					SELECT BillNumberID,BillType,Stypeid,BillCode,BillDate,btypeid,TotalMoney,0 AS TotalInMoney,TotalQty,
					CompleteTotal,Checke,comment,ifYearBill 
					FROM ReceiptBillIndex
					UNION ALL 
					--添加业务提成
					SELECT BillNumberID,BillType,Stypeid,BillCode,BillDate,'' AS btypeid,CommissionTotal AS TotalMoney,0 AS TotalInMoney,Qty AS TotalQty,
					0 AS CompleteTotal,Checke,comment,0 AS ifYearBill 
					FROM dbo.CommissionBillNew
					UNION ALL 
					--门店配送单
					SELECT BillNumberID,BillType,Stypeid,BillCode,BillDate,'' as btypeid,total TotalMoney,0 TotalInMoney,qty TotalQty,
					0 AS CompleteTotal,Checke,comment,ifYearBill 
					FROM dbo.PosAllotApplyBillIndex
				) AS b ON(l.BillNumberID = b.BillNumberID AND L.BillType = B.BillType)
				INNER JOIN #AType a ON l.AtypeId=a.TypeID
				INNER JOIN #Etype e ON E.TypeId=l.etypeid
				INNER JOIN #Stype S ON S.TypeID=l.Stypeid
				INNER JOIN F_BaseGetManDetailDType(@OperatorID) F ON F.TypeId=l.DTypeId
				WHERE 
					l.BillType NOT IN(SELECT billtype FROM #billname)
					AND l.Audited=1 
					AND l.BillDate BETWEEN CAST(@StartDate AS varchar(50)) AND CAST(@EndDate AS varchar(50))
					AND b.ifYearBill= 0     --年节存标志
			END
	END

IF UPPER(@ATypeID)='UNPAYED'  OR  UPPER(@ATypeID)='PAYED'
	BEGIN 
		SELECT 	
			RecId = IDENTITY(int, 1, 1), 
			b.Stypeid,
			b.BillNumberID,
			b.BillType,
			b.BillDate,
			b.BillCode,
			b.BTypeID,
			b.ETypeID,
			' ' AS atypeid,
			b.TotalMoney,
			b.TotalInMoney,
			b.TotalQty,
			b.CompleteTotal,
			b.Checke,
			--d.FullName AS BTypeName,
			g.FullName AS CheckeName,
			Left(b.Comment,256) AS Comment,
			e.UserCode,
			e.FullName AS ETypeName
			--' ' AS FullName
		INTO #tableResultNew2
		FROM #tableBillNumberID2 a
		INNER JOIN BillIndex b ON a.BillNumberID=b.BillNumberID
		LEFT JOIN Employee e ON b.ETypeID=e.TypeID
		LEFT JOIN Employee g ON b.Checke=g.TypeID
		WHERE b.ifYearBill=0	 --年节存标志
		DROP TABLE #tableBillNumberID2

	END
ELSE
	BEGIN
		SELECT 	
			RecId = IDENTITY(int, 1, 1),
			a.Stypeid, 
			a.BillNumberID,
			a.BillType,
			a.BillDate,
			a.BillCode,
			a.BTypeID,
			l.ETypeID,
			l.atypeid,
			l.total AS TotalMoney,
			a.TotalInMoney,
			a.TotalQty,
			a.CompleteTotal,
			a.Checke,
			g.FullName AS CheckeName,
			Left(a.Comment,256) AS Comment,
			e.UserCode,
			e.FullName AS ETypeName
		INTO #tableResultNew1
		FROM 	#tableBillNumberID a
		INNER JOIN ListTable l ON a.BillNumberID = l.BillNumberID AND a.BillType = l.BillType
		INNER JOIN #AType ON #AType.typeid=L.AtypeId
		INNER JOIN #Etype et on et.typeid=l.etypeid
		LEFT JOIN Employee e ON l.ETypeID=e.TypeID
		LEFT JOIN Employee g ON a.Checke=g.TypeID
		
		--增加提成单显示
		INSERT INTO #tableResultNew1
		SELECT 
		CBN.StypeID,
		CBN.BillNumberId,
		'311' AS BillType,
		CBN.BillDate,
		CBN.BillCode,
		'' AS BTypeID,
		CBND.EtypeID,
		(SELECT TOP 1 nId FROM Ac_Items WHERE FullName = '业务提成') AS ATypeID,
		ISNULL(CBND.CommissionTotal,0) AS TotalMoney,
		0 AS TotalInMoney,
		CBND.Qty AS TotalQty,
		0 AS CompleteTotal,
		CBN.Checke,
		g.FullName AS CheckeName,
		Left(CBN.Comment,256) AS Comment,
		e.UserCode,
		e.FullName AS ETypeName 
		FROM CommissionBillNew AS CBN
		INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
		INNER JOIN #AType ON #AType.typeid='55'
		LEFT JOIN Employee e ON CBND.ETypeID=e.TypeID
		LEFT JOIN Employee g ON CBN.Checke=g.TypeID
		--**********--
		
		DROP TABLE #tableBillNumberID
	END
	
--分页控制，写入表#tablePageResult
CREATE TABLE #tablePageResult
(
	RecId numeric(18,0),
	stypeid VARCHAR(50),
	BillNumberID numeric(18, 0),
	BillType numeric(18, 0),
	BillDate datetime,
	BillCode varchar(200),
	BTypeID varchar(50),
	ETypeID varchar(50),
	ATypeID varchar(50),
	TotalMoney  NUMERIC(24, 10) ,
	TotalInMoney  NUMERIC(24, 10) ,
	TotalQty  NUMERIC(24, 10) ,
	CompleteTotal  NUMERIC(24, 10) ,
	Checke varchar(50),
	--BTypeName varchar(250),
	--ETypeName varchar(250),
	CheckeName varchar(250),
	Comment varchar(max),
	UserCode varchar(250),
	FullName varchar(100)
)


--过滤，排序（是对过滤，排序后的分页）
SELECT * INTO #Temp_tablePageResult FROM #tablePageResult WHERE 1=2  --复制表结构

IF UPPER(@ATypeID)='UNPAYED'  OR  UPPER(@ATypeID)='PAYED'
	BEGIN
		SET @SQL=' INSERT INTO #Temp_tablePageResult SELECT * FROM #tableResultNew2'
		
		IF LTRIM(RTRIM(@Condition))<>''
			BEGIN
				SET @SQL=@SQL+' '+@Condition
				IF(UPPER(@ATypeID)='UNPAYED')
					SET @SQL=@SQL+' AND BillDate>='''+CAST(@StartDate AS VARCHAR(50))+''' AND BillDate<='''+CAST(@EndDate AS VARCHAR(50))+''' '--BillDate
			END
		ELSE
		   BEGIN
				IF(UPPER(@ATypeID)='UNPAYED')
					SET @SQL=@SQL+' WHERE BillDate>='''+CAST(@StartDate AS VARCHAR(50))+''' AND BillDate<='''+CAST(@EndDate AS VARCHAR(50))+''' '--BillDate
		   END
		
		IF LTRIM(RTRIM(@Order))='' SET @Order=' ORDER BY BillDate DESC'  --默认按日期倒排序
		SET @SQL=@SQL+''+@Order
		EXEC(@SQL)
		DROP TABLE #tableResultNew2
	END
ELSE
	BEGIN
		DECLARE @TRusult VARCHAR(MAX)
		SELECT @TRusult=' INSERT INTO #Temp_tablePageResult(RecId,stypeid,BillNumberID,BillType,BillDate,BillCode,BTypeID,ETypeID,ATypeID,TotalMoney,TotalInMoney,TotalQty,CompleteTotal,Checke,CheckeName,Comment,UserCode,FullName) SELECT RecId,stypeid,BillNumberID,BillType,BillDate,BillCode,BTypeID,ETypeID,ATypeID,TotalMoney,TotalInMoney,TotalQty,CompleteTotal,Checke,CheckeName,Comment,UserCode,ETypeName FROM #tableResultNew1'
		IF ISNULL(@Condition,'')<>'' 
			SELECT @TRusult+=@Condition
		IF ISNULL(@Order,'')='' 
			SELECT @Order=' ORDER BY BillDate DESC'  --默认按日期倒排序
		SELECT @TRusult+=@Order
		EXEC(@TRusult)
		DROP TABLE #tableResultNew1
	END
	


IF @PrintFlag=1
	BEGIN  
	   --分页控制
	   DECLARE @m numeric(18,0)
	   DECLARE @n numeric(18,0)
	   SET @m=(@PageNo-1)*@PageRows
	   SET @n=@PageNo*@PageRows
	   --@PageRows表示每页的行数,@PageNo表示当前查询的页数,需要显示的记录是从(@PageNo-1)*@PageRows,@PageNo*@PageRows
	   --显示从m+1，到n的记录
	   SET @SQL=' INSERT #tablePageResult SELECT * FROM ( SELECT TOP '+CAST(@n AS varchar(50))+' *  FROM #Temp_tablePageResult '+ @Order + ' ) a WHERE a.RecId NOT IN  (SELECT TOP '+CAST(@m AS varchar(50))+'  RecId FROM #Temp_tablePageResult ' + @Order + ')'
	   EXEC(@SQL)
	END

ELSE
	BEGIN
	   --打印时虽然不分页，但为统一显示，所以仍然把数据读入到#tablePageResult中
	   IF UPPER(@ATypeID)='UNPAYED'  OR  UPPER(@ATypeID)='PAYED'
			BEGIN
				SET @SQL = 'SELECT *,(SELECT nTypeId FROM Ac_Items WHERE nId=ATypeID) AS nTypeId FROM #Temp_tablePageResult '+ @Order
				EXEC(@SQL)
				DROP TABLE #Temp_tablePageResult
				DROP TABLE #tablePageResult
				RETURN
			END
		ELSE
			BEGIN
				SET @SQL = 'SELECT *,(SELECT nTypeId FROM Ac_Items WHERE nId=ATypeID) AS nTypeId FROM #Temp_tablePageResult '+ @Order
				EXEC(@SQL)
				DROP TABLE #Temp_tablePageResult
				DROP TABLE #tablePageResult
				RETURN
			END
	END




--计算页数，并写入合计项的BillType字段
DECLARE @PageCount numeric(18,0),@Remain numeric(18,0) 
DECLARE @RowCount  numeric(18,0)
SELECT @PageCount=(COUNT(BillNumberID)/@PageRows),@Remain=(COUNT(BillNumberID)%@PageRows),@RowCount=count(billnumberID) FROM #Temp_tablePageResult  --@PageCount保存整数部分,@Remain保留余数
--如果有余数，则页数加1
IF @Remain>0
	BEGIN
	   SET @PageCount=@PageCount+1
	END

--加上合计项，对不能为空的BillDate,BillType（写入总的页数）,BillNumberID（为0表示是合计项）作了特殊处理

INSERT #tablePageResult(BillCode,TotalMoney,TotalInMoney,TotalQty,CompleteTotal,BillDate,BillType,BillNumberID) 
SELECT '合计' AS BillCode,ISNULL(SUM(TotalMoney),0) AS TotalMoney,ISNULL(SUM(TotalInMoney),0) AS TotalInMoney,
ISNULL(SUM(TotalQty),0) AS TotalQty,ISNULL(SUM(CompleteTotal),0) AS CompleteTotal,GETDATE() AS BillDate,@PageCount AS BillTye,0 AS BillNumberID
FROM #Temp_tablePageResult


DROP TABLE #Temp_tablePageResult

SELECT *,@RowCount as 'recordcount',(SELECT nTypeId FROM Ac_Items WHERE nId=ATypeID) AS nTypeId  FROM #TablePageResult

DROP TABLE #tablePageResult,#Stype,#billname








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeIncExpDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeIncExpDetailQuery]
GO

-------------------------------------------------------------------------
--职员收入报表、职员费用报表明细表
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23

	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	

	--修改记录#04--------------------------------------------------------
	--人员：Wang Wei
	--日期：2010-04-28
	--说明：把费用类科目扩大到支出类	
	--e2.FullName as EfullName,替换成
	--ISNULL(b1.FullName,'''') as BfullName,

-------------------------------------------------------------------------
CREATE               PROCEDURE Web_EmployeeIncExpDetailQuery
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(1550),	--指定要查询的节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@BTypeID		VARCHAR(50),	--往来单位编号
	@ETypeID		VARCHAR(50),	--经手人编号
	@STypeID		VARCHAR(1550),	--分支机构
	@OperatorID 	VARCHAR(50)		--操作员ID号
)
--@encode$--
AS

SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL 			VARCHAR(max)	--用于保存动态SQL语句的变量
DECLARE @intBtypeAll	INT				--用于保存客户与供货商是否统一的变量

--判断客户与供货商是否统一，0不统一，1统一
SELECT @intBtypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeALL'
DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'


CREATE TABLE #AType (TypeID varchar(50),nTypeID varchar(50),usercode varchar(300),fullname varchar(300),sonnum int)
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))


IF @QueryType=0 -- 收入
BEGIN
		IF @ATypeID=''
		BEGIN
			IF @MIncome='-99999' --收入权限受控制
			BEGIN
				INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum FROM Ac_Items where ntypeid in ( select a.typeid AS ntypeid from /*F_BaseGetManDetailATypeSr*/F_LineIncomeC(@OperatorID) a)
				--INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) SELECT ntypeid,nid,usercode,fullname,sonnum from Ac_Items where sonnum=0 and ntypeid LIKE '00003%' AND NOT ntypeid like '0000300003%'
			END
			ELSE
			BEGIN
				INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.typeid AS ntypeid from /*F_BaseGetManDetailATypeSR*/F_LineIncomeC(@OperatorID) a)	
			END
		END
		ELSE
		BEGIN
			IF @MIncome='-99999' --收入权限受控制
			BEGIN
				INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.typeid AS ntypeid from /*F_BaseGetManDetailATypeSr*/F_LineIncomeC(@OperatorID) a, (SELECT ASPS.nTypeId from  dbo.f_split(@AtypeID,',') ASP LEFT JOIN dbo.Ac_Items ASPS ON ASP.a = ASPS.nId) b where left(a.typeid,len(b.nTypeId))=b.nTypeId)
				--INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) 
				--select ntypeid,nid,usercode,fullname,sonnum from Ac_Items 
				--where ntypeid in ( 
				--			select a.ntypeid from (select ntypeid from Ac_Items where sonnum=0 and ntypeid LIKE '00003%' AND NOT ntypeid like '0000300003%') a, 
				--			(SELECT ASPS.nTypeId from  dbo.f_split(@AtypeID,',') ASP LEFT JOIN dbo.Ac_Items ASPS ON ASP.a = ASPS.nId) b where left(a.ntypeid,len(b.nTypeId))=b.nTypeId
				--)
			END
			ELSE
			BEGIN
				INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.typeid AS ntypeid from /*F_BaseGetManDetailATypeSR*/F_LineIncomeC(@OperatorID) a, (SELECT ASPS.nTypeId from  dbo.f_split(@AtypeID,',') ASP LEFT JOIN dbo.Ac_Items ASPS ON ASP.a = ASPS.nId) b where left(a.typeid,len(b.nTypeId))=b.nTypeId)
			END
		END
END
ELSE  --费用
BEGIN
	IF @ATypeID=''
	BEGIN
		IF @MExpense='-99999' --费用权限受控制
		BEGIN
			INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum FROM Ac_Items where ntypeid in ( select a.typeid AS ntypeid from /*F_BaseGetManDetailATypeFy*/F_LineExpenseC(@OperatorID) a)
			--INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) SELECT ntypeid,nid,usercode,fullname,sonnum from Ac_Items where sonnum=0 and ntypeid LIKE '00004%' AND NOT ntypeid like '0000400003%'
		END
		ELSE
		BEGIN
			INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.typeid AS ntypeid from /*F_BaseGetManDetailATypeFy*/F_LineExpenseC(@OperatorID) a)	
		END
	END
	ELSE
	BEGIN
		IF @MExpense='-99999' --费用权限受控制
		BEGIN
		INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.typeid AS ntypeid from /*F_BaseGetManDetailATypeFy*/F_LineExpenseC(@OperatorID) a, (SELECT ASPS.nTypeId from  dbo.f_split(@AtypeID,',') ASP LEFT JOIN dbo.Ac_Items ASPS ON ASP.a = ASPS.nId) b where left(a.typeid,len(b.nTypeId))=b.nTypeId)
		--INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) 
		--		select ntypeid,nid,usercode,fullname,sonnum from Ac_Items 
		--		where ntypeid in ( 
		--					select a.ntypeid from (select ntypeid from Ac_Items where sonnum=0 and ntypeid LIKE '00004%' AND NOT ntypeid like '0000400003%') a, 
		--					(SELECT ASPS.nTypeId from  dbo.f_split(@AtypeID,',') ASP LEFT JOIN dbo.Ac_Items ASPS ON ASP.a = ASPS.nId) b where left(a.ntypeid,len(b.nTypeId))=b.nTypeId
		--		)
		END
		ELSE
		BEGIN
			INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.typeid AS ntypeid from /*F_BaseGetManDetailATypeFy*/F_LineExpenseC(@OperatorID) a, (SELECT ASPS.nTypeId from  dbo.f_split(@AtypeID,',') ASP LEFT JOIN dbo.Ac_Items ASPS ON ASP.a = ASPS.nId) b where left(a.typeid,len(b.nTypeId))=b.nTypeId)
		END
	END
END

IF @EtypeID=''
	INSERT INTO #Etype(typeid)  select typeid from F_BaseGetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype(typeid)  select a.typeid from F_BaseGetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@EtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@STypeID,',')) b where left(a.typeid,len(b.a))=b.a


--****9.6需求修改 杨俊2015-04-16，因为这改动有点大还是保留原代码****
--3.15.2、职员部门费用表及部门收支表统计提成单 ,关联9.4BUG:4395
--SET @SQL='
--		SELECT 
--			l.atypeid,
--			l.BillNumberID,
--			l.BillDate,
--			b.BillCode,
--			l.BillType,
--			b.RedWord,
--			e1.FullName as echecke,
--			l. etypeid,
--			b.btypeid as btypeid,
--			b.stypeid as stypeid,
--			ISNULL(l.Total,0) AS Total,
--			b.Comment,
--			billname=isnull((select top 1 billname from billname where billtype =b.billtype),'''')
--		FROM 
--			ListTable l'
--IF NOT (@ETypeID= '' AND @METypeId = '00001')
--	SET @SQL =@SQL+' INNER JOIN #etype e on (l.etypeid=e.typeid) '
--IF NOT (@STypeID= '' AND @MStypeid = '00000')
--	SET @SQL =@SQL+' INNER JOIN #stype s on (l.stypeid=s.typeid) '
--IF @MDtypeid = '-99999'
--	SET @SQL =@SQL+' INNER JOIN F_GetManDetailDtype('''+@OperatorID+''') de on (l.dtypeid=de.typeid) '	
--IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
--	SET @SQL =@SQL+' INNER JOIN (SELECT TypeID FROM F_GetManDetailBtype('''+@OperatorID+''') UNION SELECT '''' AS TypeID) bt on (l.btypeid=bt.typeid) '

--SET @SQL=@SQL+
--		'
--			inner join #atype a On a.ntypeid=l.atypeid,
--			BillIndex b
--			INNER JOIN Employee e1  ON e1.TypeID=b.checke	


--		WHERE 
--			l.BillNumberID=b.BillNumberID
--			AND l.Audited = 1'
			
--IF @proinfo='3' --汽配版本
--		SET @SQL=@SQL+'	AND l.billtype NOT IN(178,179,181,182,186,191,197,198,200,196,192,195)'
			
----组织日期下限条件语句
--IF @BillDateBegin<>'' 
--	SET @SQL=@SQL + '
--			AND l.BillDate>=''' + @BillDateBegin + ''''

----组织日期上限条件语句
--IF @BillDateEnd<>'' 
--	SET @SQL=@SQL + '
--			AND l.BillDate<=''' + @BillDateEnd + ''''

--SET @SQL=@SQL + '
--		ORDER BY l.BillDate'

SET @SQL='
	SELECT * 
	FROM 
	(
		SELECT 
			l.atypeid,
			l.BillNumberID,
			l.BillDate,
			b.BillCode,
			l.BillType,
			b.RedWord,
			e1.FullName as echecke,
			l. etypeid,
			b.btypeid as btypeid,
			b.stypeid as stypeid,
			ISNULL(l.Total,0) AS Total,
			b.Comment,
			billname=isnull((select top 1 billname from billname where billtype =b.billtype),''''),
			a.fullname as afullname
		FROM 
			ListTable l 
			INNER JOIN 
			(
				SELECT BillNumberID,BillCode,RedWord,btypeid,stypeid,Comment,billtype,checke FROM BillIndex
				UNION ALL 
				SELECT BillNumberID,BillCode,RedWord,btypeid,stypeid,Comment,billtype,checke FROM ReceiptBillIndex
				UNION ALL 
				SELECT BillNumberID,BillCode,RedWord,btypeid,stypeid,Comment,billtype,checke FROM Coupon_BillIndex
				UNION ALL 
				SELECT BillNumberID,BillCode,RedWord,'''' btypeid,stypeid,Comment,billtype,checke FROM PosAllotApplyBillIndex
			) AS B ON(B.BillNumberID = L.BillNumberID AND B.billtype = L.billtype)
			'
IF NOT (@ETypeID= '' AND @METypeId = '00001')
	SET @SQL =@SQL+' INNER JOIN #etype e on (l.etypeid=e.typeid) '
IF NOT (@STypeID= '' AND @MStypeid = '00000')
	SET @SQL =@SQL+' INNER JOIN #stype s on (l.stypeid=s.typeid) '
IF @MDtypeid = '-99999'
	SET @SQL =@SQL+' INNER JOIN F_GetManDetailDtype('''+@OperatorID+''') de on (l.dtypeid=de.typeid) '	
IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
	SET @SQL =@SQL+' INNER JOIN (SELECT TypeID FROM F_GetManDetailBtype('''+@OperatorID+''') UNION SELECT '''' AS TypeID) bt on (l.btypeid=bt.typeid) '

SET @SQL=@SQL+
		'
			inner join #atype a On a.ntypeid=l.atypeid 
			INNER JOIN Employee e1  ON e1.TypeID=b.checke	
		WHERE 
			l.BillNumberID=b.BillNumberID
			AND l.Audited = 1'
			
IF @proinfo='3' --汽配版本
		SET @SQL=@SQL+'	AND l.billtype NOT IN(178,179,181,182,186,191,197,198,200,196,192,195)'
			
IF @BillDateBegin<>'' 
	SET @SQL=@SQL + '
			AND l.BillDate>=''' + @BillDateBegin + ''''
IF @BillDateEnd<>'' 
	SET @SQL=@SQL + '
			AND l.BillDate<=''' + @BillDateEnd + ''''
IF(@QueryType = 1)
BEGIN
	SET @SQL +=' 
				UNION ALL 
				SELECT (SELECT TOP 1 nId FROM Ac_Items WHERE FullName = ''业务提成'') AS ATypeID,CBN.BillNumberId,CBN.BillDate,CBN.BillCode,''311'' AS BillType,CBN.RedWord,
				(SELECT FullName FROM dbo.employee WHERE typeId = CBN.checke) AS echecke,
				CBND.EtypeID,'''' AS btypeid,CBN.StypeID,ISNULL(CBND.CommissionTotal,0) AS Total,CBN.Comment,''提成单'' AS billname,
				'''' as afullname 
				FROM CommissionBillNew AS CBN
				INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
				'		
	IF NOT (@ETypeID= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' INNER JOIN #etype e on (CBND.etypeid=e.typeid) '
	IF NOT (@STypeID= '' AND @MStypeid = '00000')
		SET @SQL =@SQL+' INNER JOIN #stype s on (CBN.stypeid=s.typeid) '
	IF @MDtypeid = '-99999'
		SET @SQL =@SQL+' INNER JOIN F_GetManDetailDtype('''+@OperatorID+''') de on (CBND.dtypeid=de.typeid) '

	SET @SQL += '	
					WHERE CBN.ifcheck = ''t'' '
	IF @BillDateBegin<>'' 
		SET @SQL=@SQL + '
				AND CBN.BillDate>=''' + @BillDateBegin + ''''
	IF @BillDateEnd<>'' 
		SET @SQL=@SQL + '
				AND CBN.BillDate<=''' + @BillDateEnd + ''''
END	

SET @SQL=@SQL + '
	) AS TEMP 
		ORDER BY BillDate'
--****************************************************************************--
--print @SQL
EXECUTE(@SQL)

DROP TABLE #Atype
DROP TABLE #Etype
DROP TABLE #Stype

--Web_EmployeeIncExpDetailQuery 0,'','2003-1-1','2003-9-17','','0000100033','00001'







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeIncExpLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeIncExpLineQuery]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--职员收入报表、职员费用报表线性表
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示
	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
	--修改记录#05--------------------------------------------------------
	--人员：徐辉
	--日期：2005-1-29
	--说明：停用职员也要纳入统计
	--修改记录#06--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-09
	--说明：添加行合计（v3.9）
-------------------------------------------------------------------------
	--修改记录#07--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修支出（qp1.0）
-------------------------------------------------------------------------
CREATE                         PROCEDURE Web_EmployeeIncExpLineQuery  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(1550),	--指定要查询的财务科目节点ID
	@StartDate		VARCHAR(20),	--时间范围下限
	@EndDate		VARCHAR(20),	--时间范围上限
	@ETypeID		VARCHAR(50),	--职员编号
	@STypeID		VARCHAR(1550),	--分支机构
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@nPageCol		INT,			--分页会计科目的页码
	@nPageColSize	INT,
	@UserCode		VARCHAR(100)='',	--过滤职员Usercode
	@FullName		VARCHAR(100)='',	--过滤职员姓名
	@Flag           int =0
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@nPageColSize	
SET @MColCount=0
DECLARE @Point			INT				--用于保存截取子字符串位置的变量
DECLARE @SUBSTRING		VARCHAR(255)	--用于保存子字符串的变量
DECLARE @AtypeName varchar(66)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'

CREATE TABLE #AType (TypeID varchar(50),nTypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #EType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #SType (TypeID varchar(50))
CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,Deleted int)

CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #DetailATypeSr (TypeID varchar(50),nTypeID varchar(50))
CREATE TABLE #DetailATypeFy (TypeID varchar(50),nTypeID varchar(50))

INSERT INTO #DetailATypeSr select a.typeid AS TypeID,a.nid AS nTypeID  from /*F_BaseGetManDetailATypeSr*/F_LineIncomeC(@OperatorID) a
INSERT INTO #DetailATypeFy select a.typeid AS TypeID,a.nid AS nTypeID  from /*(F_BaseGetManDetailATypeFy*/F_LineExpenseC(@OperatorID) a
INSERT INTO #Btype select typeid from F_GetManDetailBtype(@OperatorID) UNION SELECT '' AS typeid
INSERT INTO #Dtype select typeid from F_GetManDetailDtype(@OperatorID)

IF @QueryType=0 -- 收入
	IF @ATypeID=''
	BEGIN
		INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeSr SR ON A.nTypeId=SR.TypeID

		----IF NOT EXISTS(select * from #Atype) --无管辖其他收入时，临时表为空,插入收入类科目（不包含其他收入类科目）
		--INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		--select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		--from dbo.Ac_Items A
		--LEFT JOIN #AType A1 ON A1.typeid=A.nTypeId 
		--where A.sonnum=0 and A.nTypeId LIKE '00003%' AND A.nTypeId NOT like '0000300003%' 
		--		AND A1.typeid IS NULL
	END
	ELSE
	BEGIN
		INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeSr SR ON A.nTypeId=SR.TypeID
		INNER JOIN (select BAC.nTypeId from  dbo.f_split(@AtypeID,',') Asp INNER JOIN dbo.Ac_Items  BAC  ON Asp.a = BAC.nId) b ON SR.TypeID  LIKE b.nTypeId+'%'
		
		--IF NOT EXISTS(select * from #Atype) --无管辖其他收入，临时表为空,插入收入类科目（不包含其他收入类科目）
		--INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		--select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		--from dbo.Ac_Items A
		--LEFT JOIN #AType A1 ON A1.TypeID=A.nTypeId 
		--INNER JOIN (select BAC.nTypeId from  dbo.f_split(@AtypeID,',') Asp INNER JOIN dbo.Ac_Items  BAC  ON Asp.a = BAC.nId) b ON a.ntypeid LIKE b.nTypeId+'%'
		--where A.sonnum=0 and A.nTypeId LIKE '00003%' AND a.nTypeId not like '0000300003%' AND A1.TypeID is null
	END
ELSE  --费用
	IF @ATypeID=''
	BEGIN
		INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeFy fy ON A.nTypeId=fy.TypeID 
		----IF NOT EXISTS(select * from #Atype) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		--select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		--from dbo.Ac_Items A
		--LEFT JOIN #AType A1 ON A1.TypeID=A.nTypeId  
		--where a.sonnum=0 and a.nTypeId LIKE '00004%' AND a.nTypeId NOT like '0000400003%' AND a1.typeid is null
	END
	ELSE
	BEGIN
		INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeFy fy ON A.nTypeId=fy.TypeID 
		INNER JOIN (select BAC.nTypeId from  dbo.f_split(@AtypeID,',') Asp INNER JOIN dbo.Ac_Items  BAC  ON Asp.a = BAC.nId) b ON fy.TypeID  LIKE b.nTypeId+'%'

		----IF NOT EXISTS(select * from #Atype) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #Atype(typeid,ntypeid,usercode,fullname,sonnum) 
		--select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		--from dbo.Ac_Items A
		--INNER JOIN (select BAC.nTypeId from  dbo.f_split(@AtypeID,',') Asp INNER JOIN dbo.Ac_Items  BAC  ON Asp.a = BAC.nId) b ON a.ntypeid LIKE b.nTypeId+'%'
		--LEFT JOIN #AType A1 ON A1.TypeID=A.nTypeId  
		--where a.sonnum=0 and a.nTypeId LIKE '00004%' AND a.nTypeId NOT like '0000400003%' AND a1.typeid is null
	END

IF @EtypeID='00001'
	INSERT INTO #Etype(typeid,usercode,fullname,sonnum) 
	select e.typeid,e.usercode,e.fullname,e.sonnum from employee e 
	inner join (select typeid from F_GetManDetailEType(@OperatorID)) e1 on e.typeId=e1.TypeId
ELSE
	INSERT INTO #Etype(typeid,usercode,fullname,sonnum) 
	select e.typeid,e.usercode,e.fullname,e.sonnum from employee e 
	inner join (select typeid from F_GetManDetailEType(@OperatorID)) e1 on e.typeId=e1.TypeId
	inner join (select * from  dbo.f_split(@EtypeID,',')) b on e1.typeid LIKE b.a+'%'
		
IF @STypeID=''
	INSERT INTO #Stype(typeid)  
	select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  
	select a.typeid from F_BaseGetManDetailSType(@OperatorID) a
	inner join (select * from  dbo.f_split(@StypeID,',')) b on a.typeid LIKE b.a+'%'


DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #Atype where typeid='000040000200004'--#07 删除商品送修科目	
	


DECLARE @ColName varchar(4000)
SET  @ColName =' EtypeID,EtypeCode,EtypeName+''(''+EtypeCode+'')'' as [职员/'+@AtypeName+'],Sonnum,ATypeCount,RowTotal'
IF @Flag=1
	SET  @ColName =' EtypeID,EtypeName+''(''+EtypeCode+'')'' as [职员/'+@AtypeName+'],RowTotal as RowTotal'

--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(50),
	ETypeCode	VARCHAR(50),
	ETypeName	VARCHAR(66),
	SonNum		INT,
	ATypeCount	INT
)

--对结果集合填充满足条件的员工数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum)
SELECT 
	a.TypeID AS ETypeID,
	a.UserCode AS ETypeCode,
	a.FullName AS ETypeName,
	a.SonNum AS SonNum
FROM #Etype a
--inner join listtable b on a.TypeID=b.ETypeID
--添加提成单55科目的统计
INNER JOIN 
(
	SELECT EtypeId,AtypeId,BillDate FROM dbo.ListTable WHERE BillType <> 311
	UNION ALL 
	SELECT EtypeID,''55'' AS AtypeId,BillDate 
	FROM dbo.CommissionBillNewDetail AS CBND
	INNER JOIN dbo.CommissionBillNew AS CBN ON(CBN.BillNumberId = CBND.BillNumberId)
) AS b ON(A.TypeID = B.EtypeId)
inner join #Atype a1 on a1.ntypeid=b.atypeid
WHERE	a.sonnum =0
		AND b.BillDate>=''' + @StartDate +''' 
		AND b.BillDate<=''' + @EndDate + ''''
			
IF @proinfo='3' --汽配版本
	SET @SQL=@SQL + '
		AND b.billtype NOT IN(178,179,181,182,186,191,197,198,200,196,192,195) '
--print @SQL 
-- return 0
--组织职员编号过滤条件
IF @UserCode<>'' 
BEGIN
	SET @Point=charindex(',',@UserCode)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@UserCode,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @SUBSTRING + '%'''
		SET @UserCode=SUBSTRING(@UserCode,@Point+1,len(@UserCode)-@Point)
		SET @Point=charindex(',',@UserCode)
	END 
	IF @UserCode<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @UserCode + '%'''
	END 
END 
--组织职员名称过滤条件
IF @FullName<>'' 
BEGIN
	SET @Point=charindex(',',@FullName)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FullName,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @SUBSTRING + '%'''
		SET @FullName=SUBSTRING(@FullName,@Point+1,len(@FullName)-@Point)
		SET @Point=charindex(',',@FullName)
	END 
	IF @FullName<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @FullName + '%'''
	END	
END 
SET @SQL=@SQL + '
GROUP BY a.TypeID,a.UserCode,a.FullName,a.SonNum
ORDER BY a.UserCode
'
EXECUTE (@SQL)

--#06
--添加行合计值
ALTER TABLE #Temp_Result ADD RowTotal  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES

CREATE TABLE #Temp_SubListTable
(
	etypeid varchar(50),
	atypeid varchar(50),
	total  NUMERIC(24, 10) 
)

--****9.6需求修改 杨俊2015-04-16，因为这改动有点大还是保留原代码****
--3.15.2、职员部门费用表及部门收支表统计提成单 ,关联9.4BUG:4395

----根据条件筛选职员收入、费用信息到一个临时表
----SELECT top 10 * FROM ListTable
--SET @SQL= '	INSERT INTO #Temp_SubListTable 
--			SELECT ETypeID,ATypeID,ISNULL(SUM(Total),0) AS Total
--			FROM ListTable l
--			'
--IF NOT (@ETypeID= '00001' AND @METypeId = '00001')
--	SET @SQL =@SQL+' 
--			INNER JOIN #etype e on (l.etypeid=e.typeid) '
--IF NOT (@STypeID = '' AND @MStypeid = '00000')
--	SET @SQL =@SQL+' 
--			INNER JOIN #Stype s on (l.stypeid=s.typeid) '
--IF @MDtypeid = '-99999'
--	SET @SQL =@SQL+' 
--			INNER JOIN #dtype de on (l.dtypeid=de.typeid) '
--IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
--	SET @SQL =@SQL+' 
--			INNER JOIN #btype bt on (l.btypeid=bt.typeid) '
--SET @SQL=@SQL+'
--			INNER JOIN #atype a on l.atypeid= a.ntypeid
--			WHERE	Audited=1'
--IF @proinfo='3' --汽配版本
--	SET @SQL=@SQL+'	AND billtype NOT IN(178,179,181,182,186,191,197,198,200,196,192,195)'
	
--SET @SQL=@SQL+'		AND BillDate>='''+@StartDate+'''
--					AND BillDate<='''+@EndDate+'''
--				GROUP BY ETypeID,ATypeID'
SET @SQL= '	INSERT INTO #Temp_SubListTable 
			SELECT ETypeID,ATypeID,ISNULL(SUM(Total),0) AS Total 
			FROM 
			(
				SELECT ETypeID,ATypeID,Total 
				FROM ListTable l
				'
	IF NOT (@ETypeID= '00001' AND @METypeId = '00001')
		SET @SQL =@SQL+' 
				INNER JOIN #etype e on (l.etypeid=e.typeid) '
	IF NOT (@STypeID = '' AND @MStypeid = '00000')
		SET @SQL =@SQL+' 
				INNER JOIN #Stype s on (l.stypeid=s.typeid) '
	IF @MDtypeid = '-99999'
		SET @SQL =@SQL+' 
				INNER JOIN #dtype de on (l.dtypeid=de.typeid) '
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL =@SQL+' 
				INNER JOIN #btype bt on (l.btypeid=bt.typeid) '
	SET @SQL=@SQL+'
				INNER JOIN #atype a on l.atypeid= a.ntypeid
				WHERE	Audited=1
					AND billtype <> 311
					'
	IF @proinfo='3' --汽配版本
		SET @SQL=@SQL+'	AND billtype NOT IN(178,179,181,182,186,191,197,198,200,196,192,195)'
		
	SET @SQL=@SQL+'		AND BillDate>='''+@StartDate+'''
						AND BillDate<='''+@EndDate+'''  '
	IF(@QueryType = 1)
	BEGIN
		SET @SQL += '
				UNION ALL
				SELECT CBND.EtypeID,(SELECT TOP 1 nId FROM Ac_Items WHERE FullName = ''业务提成'') AS ATypeID,ISNULL(SUM(CBND.CommissionTotal),0) AS Total 
				FROM CommissionBillNew AS CBN
				INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
			'
	IF NOT (@ETypeID= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' INNER JOIN #etype e on (CBND.etypeid=e.typeid) '
	IF NOT (@STypeID = '' AND @MStypeid = '00000')
		SET @SQL =@SQL+' INNER JOIN #Stype s on (CBN.stypeid=s.typeid) '
	IF @MDtypeid = '-99999'
		SET @SQL =@SQL+' INNER JOIN #dtype de on (CBND.dtypeid=de.typeid) '
		SET @SQL += '	
						WHERE CBN.ifcheck = ''t'' 
								AND CBN.BillDate>='''+@StartDate+'''
								AND CBN.BillDate<='''+@EndDate+'''
							GROUP BY CBND.EtypeID '
	END
	SET @SQL += '	
					) AS TEMP 
					GROUP BY ETypeID,ATypeID'
--****************************************************************************--
EXEC(@SQL)

--#06 行合计
SELECT EtypeID, SUM(total) AS Total
INTO #Temp_RowSumSubListTable
FROM #Temp_SubListTable
GROUP BY
	EtypeID
	
--#06 行合计
UPDATE #Temp_Result SET RowTotal = b.Total
FROM #Temp_Result AS a, #Temp_RowSumSubListTable b
WHERE a.ETypeID=b.ETypeID

DROP TABLE #Temp_RowSumSubListTable

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(50)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(50)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT nTypeID,UserCode,FullName FROM #Atype 
OPEN MAtypeCursor
FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount
WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@nPageCol - 1) * @MColPageNum
	BEGIN
		IF @Flag =0
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + '|' + @MyUserCode + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName + '|' + @MyUserCode + ']'
	
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '|' + @MyUserCode + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
		END
		ELSE  -- 打印
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName + ']'
	
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
		END
	END 
	
	IF @MColCount = @nPageCol * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
deallocate MAtypeCursor
--SELECT * FROM #Temp_Result
EXEC('SELECT '+@Colname+' FROM #Temp_Result  WHERE RowTotal<>0')

DROP TABLE #Temp_Result,#Temp_SubListTable,#EType,#AType,#SType,#MainType,#Btype,#DetailATypeFy,#DetailATypeSr,#Dtype




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeIncExpLineQueryPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeIncExpLineQueryPrint]
GO








-------------------------------------------------------------------------
--职员收入报表、职员费用报表线性表
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示
	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
	--修改记录#05--------------------------------------------------------
	--人员：徐辉
	--日期：2005-1-29
	--说明：停用职员也要纳入统计
	--修改记录#06--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-09
	--说明：添加行合计（v3.9）
-------------------------------------------------------------------------
CREATE                     PROCEDURE Web_EmployeeIncExpLineQueryPrint  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(25),	--指定要查询的财务科目节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@ETypeID		VARCHAR(25),	--职员编号
	@EmployeeName	VARCHAR(66),	--职员姓名
	@OperatorID 	VARCHAR(25),	--操作员ID号
	@ATypePageNo	INT,			--分页会计科目的页码
	@ColPageNum	INT,
	@FilterCode		VARCHAR(25)='',	--过滤职员Usercode
	@FilterName		VARCHAR(25)=''	--过滤职员姓名
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@ColPageNum	
SET @MColCount=0
DECLARE @Point			INT				--用于保存截取子字符串位置的变量
DECLARE @SUBSTRING		VARCHAR(255)	--用于保存子字符串的变量
DECLARE @AtypeName varchar(20)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'
--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
IF @AtypeID=''
	BEGIN
		SET @ATypeID=CASE @QueryType
			WHEN 0 THEN '00003'			--“收入类”科目根节点
			--WHEN 1 THEN '0000400003'	--“费用合计”科目根节点 --#04 注释了
			WHEN 1 THEN '00004' --“支出类”科目根节点 #04 添加
		END
	END
--#02以下------------------------------------------------------
IF @QueryType=0 SET @MAtypeid=@MIncome
IF @QueryType=1 SET @MAtypeid=@MExpense
--#02以上------------------------------------------------------
DECLARE @sonnum int
IF @ETypeID='' 
BEGIN
	SELECT @sonnum = sonnum FROM employee WHERE typeid=@MEtypeid
	IF @sonnum = 0
	BEGIN
		SET @ETypeID=@MEtypeid
	END
	ELSE
	BEGIN
		IF @MEtypeid = '00001' OR @MEtypeid = ''
			SET @ETypeID='00001'
		ELSE
			SET @ETypeID=@MEtypeid
	END
END
--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(25),
	ETypeCode	VARCHAR(26),
	ETypeName	VARCHAR(66),
	SonNum		INT,
	ATypeCount	INT
)
--对结果集合填充满足条件的员工数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum)
SELECT 
	a.TypeID AS ETypeID,
	a.UserCode AS ETypeCode,
	a.FullName AS ETypeName,
	a.SonNum AS SonNum
FROM employee a,listtable b
WHERE 
	--a.Deleted=0 #05
	a.TypeID LIKE ''' + @ETypeID + '%''
'

DECLARE @ColName varchar(4000)
SET  @ColName ='EtypeName+''(''+EtypeCode+'')'' as [职员/'+@AtypeName+'],RowTotal as [总计]'


IF @METypeID<>''
	--SET @SQL=@SQL + 'AND ''' + @METypeID + ''' LIKE a.TypeID + ''%'''--#03 新添加---------------------------------
	SET @SQL=@SQL + 'AND a.TypeID LIKE ''' + @METypeID + '%'''--#03 新添加---------------------------------
SET @SQL=@SQL + '
	AND a.TypeID=b.ETypeID
	AND b.ATypeID LIKE ''' + @ATypeID + '%''
	AND b.ATypeID LIKE ''' + @MAtypeid + '%''
	AND b.BillDate>=''' + @BillDateBegin +
	''' AND b.BillDate<=''' + @BillDateEnd + ''''
--print @SQL 
-- return 0
--组织职员编号过滤条件
IF @FilterCode<>'' 
BEGIN
	SET @Point=charindex(',',@FilterCode)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FilterCode,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @SUBSTRING + '%'''
		SET @FilterCode=SUBSTRING(@FilterCode,@Point+1,len(@FilterCode)-@Point)
		SET @Point=charindex(',',@FilterCode)
	END 
	IF @FilterCode<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @FilterCode + '%'''
	END 
END 
--组织职员名称过滤条件
IF @FilterName<>'' 
BEGIN
	SET @Point=charindex(',',@FilterName)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FilterName,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @SUBSTRING + '%'''
		SET @FilterName=SUBSTRING(@FilterName,@Point+1,len(@FilterName)-@Point)
		SET @Point=charindex(',',@FilterName)
	END 
	IF @FilterName<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @FilterName + '%'''
	END	
END 
SET @SQL=@SQL + '
GROUP BY a.TypeID,a.UserCode,a.FullName,a.SonNum
ORDER BY a.UserCode
'
EXECUTE (@SQL)

--#06
--添加行合计值
ALTER TABLE #Temp_Result ADD RowTotal  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES

--SELECT * FROM #Temp_Result
--根据条件筛选职员收入、费用信息到一个临时表
--SELECT top 10 * FROM ListTable
SELECT ETypeID,ATypeID,ISNULL(SUM(Total),0) AS Total
INTO #Temp_SubListTable
FROM ListTable
WHERE 
	Audited=1
	AND BillDate>=@BillDateBegin
	AND BillDate<=@BillDateEnd
	AND ETypeID LIKE @ETypeID + '%'
	AND ETypeID LIKE @MEtypeid + '%'
	AND ATypeID LIKE @ATypeID + '%'
	AND ATypeID LIKE @MAtypeid + '%'
	AND ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
GROUP BY ETypeID,ATypeID

--#06 行合计
SELECT EtypeID, SUM(total) AS Total
INTO #Temp_RowSumSubListTable
FROM #Temp_SubListTable
GROUP BY
	EtypeID

--#06 行合计
UPDATE #Temp_Result SET RowTotal = b.Total
FROM #Temp_Result AS a, #Temp_RowSumSubListTable b
WHERE a.ETypeID=b.ETypeID

DROP TABLE #Temp_RowSumSubListTable

--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(25)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(26)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT TypeID,UserCode,FullName FROM Atype 
WHERE 
	SonNum=0
	AND TypeID LIKE @ATypeID + '%'--#03-------------
	AND TypeID LIKE @MAtypeid + '%'--#03-------------
	AND TypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
OPEN MAtypeCursor
FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount
WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@ATypePageNo - 1) * @MColPageNum
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName+ ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			SET  @ColName= @ColName+',[' + @MyATypeName + ']'

			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			EXECUTE(@SQL)
			
		END 
	
	IF @MColCount = @ATypePageNo * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
deallocate MAtypeCursor
--SELECT * FROM #Temp_Result
EXEC('SELECT '+@Colname+' FROM #Temp_Result')
DROP TABLE #Temp_Result
DROP TABLE #Temp_SubListTable
--SELECT * FROM employee
--SELECT * FROM listtable
--SELECT col_length('employee','fullname')
--EXECUTE Web_EmployeeIncExpLineQuery 0,'','','','00001','','00001',1
--EXECUTE Web_EmployeeIncExpLineQuery 0,'','2003-6-30','2003-8-29','00001','','00001',1








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeIncExpListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeIncExpListQuery]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-------------------------------------------------------------------------
--职员收入报表、职员费用报表树型表查询
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示
	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2003-11-21
	--说明：有错误：当筛选具体的一个职员时，返回空结果结合。
	--修改记录#05--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
	--修改记录#06--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-09
	--说明：添加行合计（v3.9）
	--修改记录#07--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修支出（qp1.0）
	--修改记录#08--------------------------------------------------------
	--人员： glj 
	--日期：2013-03-26
	--说明：项目权限调整[#AType]
	-------------------------------------------------------------------------
	--修改记录#09
	--人员：周华
	--日期：2013-06-09
	--说明：9.2版本调整多级权限函数
-------------------------------------------------------------------------


CREATE     PROCEDURE Web_EmployeeIncExpListQuery  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(1550),	--指定要查询的财务科目节点ID
	@StartDate		VARCHAR(20),	--时间范围下限
	@EndDate		VARCHAR(20),	--时间范围上限
	@ETypeID		VARCHAR(50),	--职员编号
	@STypeID		VARCHAR(1550),	--分支机构
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@nPageCol		INT,			--分页会计科目的页码
	@nPageColSize 	int,
	@Flag           int =0         -- 0 报表显示，1 打印（主要是表头字段显示要少,Sonnum,ATypeCount,RowTotal,deleted，另外科目表头只有名称）
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL 			VARCHAR(max)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@nPageColSize
SET @MColCount=0
--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
DECLARE @AtypeName varchar(66)
SET @AtypeName=''
IF @QueryType =0
	SET @AtypeName='收入'
ELSE
	SET @AtypeName='费用支出'


CREATE TABLE #AType (TypeID varchar(50),NTypeID VARCHAR(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(26),fullname varchar(100),sonnum int,Deleted int)
CREATE TABLE #Stype (TypeID varchar(50))

CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
INSERT INTO #Btype select typeid from F_GetManDetailBtype(@OperatorID) UNION SELECT '' AS typeid
INSERT INTO #Dtype select typeid from F_GetManDetailDtype(@OperatorID)

--==============================得到有权限的项目[BEGIN]===============================
SET @SQL='
	INSERT INTO #AType(TypeID,NTypeID,usercode,fullname,sonnum)
	SELECT DISTINCT 
		items.nId,
		items.nTypeId,
		items.UserCode,
		items.FullName,
		items.SonNum  
	FROM Ac_Items items
	'+CHAR(13)
	IF ISNULL(@ATypeID,'')<>''--判断科目是否为空
		SET @SQL+='INNER JOIN (SELECT nTypeId FROM Ac_Items ai INNER JOIN DBO.f_split('''+@AtypeID+''','','') F ON F.a=ai.nId) F ON items.nTypeId LIKE  F.nTypeId +''%'''+CHAR(13)

	SET @SQL+='
	INNER JOIN 
	(
		/*SELECT 
		items.nId
		FROM Ac_Items items '+CHAR(13)
		/*
		IF @QueryType=0 -- 收入
			SET @SQL+='
			WHERE 
			items.nTypeId LIKE ''00003%''
			AND items.nTypeId NOT LIKE ''0000300003%'' '+CHAR(13)

		ELSE 
			SET @SQL+='
			WHERE 
			nTypeId LIKE ''00004%''
			AND nTypeId NOT LIKE ''0000400003%'' '+CHAR(13)
		*/
		SET @SQL+='
		AND	items.SonNum=0
		
		UNION ALL*/

		SELECT 
			items.nId
		FROM Ac_Items items '

	IF @QueryType=0 -- 收入
		SET @SQL+='INNER JOIN /*F_GetManATypeSrAll*/F_AllTreeIncomeC('''+@OperatorID+''') G ON G.nTypeID=items.nTypeID'+CHAR(13)
	ELSE
		SET @SQL+='INNER JOIN F_LineExpenseC('''+@OperatorID+''') E ON E.TypeID=items.nTypeID'+CHAR(13)
		
	SET @SQL+='
	WHERE 
		items.SonNum=0
	) A ON items.nId=A.nId'+CHAR(13)

EXEC(@SQL)

--==============================得到有权限的项目[END]===============================
--职员
IF @EtypeID=''
	INSERT INTO #Etype(typeid)  
	select typeid from F_BaseGetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype(typeid)  
	select a.typeid from F_BaseGetManDetailEType(@OperatorID) a 
	inner join(select * from  dbo.f_split(@EtypeID,',')) b on a.typeid LIKE b.a+'%'

--分支机构	
IF @STypeID=''
	INSERT INTO #Stype(typeid)  
	select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  
	select a.typeid from F_BaseGetManDetailSType(@OperatorID) a 
	inner join(select * from  dbo.f_split(@StypeID,',')) b on a.typeid LIKE b.a+'%'

DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #Atype where NTypeID='000040000200004'--#07 删除商品送修科目	


DECLARE @sonnum int 
SET @sonnum =0
IF @EtypeID =''
	SET @EtypeID='00001'

SELECT @sonnum = sonnum FROM Employee WHERE Typeid =@EtypeID
IF @sonnum =0 
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.deleted FROM Employee a
		,(select * from F_GetManETypeAll(@OperatorID) where typeid =@EtypeID) b where a.typeid=b.typeid
ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.deleted FROM employee a
		,(select * from F_GetManETypeAll(@OperatorID) where parid=@EtypeID and typeid LIKE @EtypeID+'%' ) b where a.typeid=b.typeid



--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	etypeid		VARCHAR(50),
	ETypeCode	VARCHAR(26),
	ETypeName	VARCHAR(66),
	SonNum		INT,
	ATypeCount	INT,
	deleted int
)
--对结果集合填充满足条件的员工数据
SET @SQL='
INSERT INTO #Temp_Result (etypeid,ETypeCode,ETypeName,SonNum,deleted)
SELECT 
	TypeID AS etypeid,
	UserCode AS ETypeCode,
	FullName AS ETypeName,
	SonNum AS SonNum,
	deleted
FROM #MainType
ORDER BY UserCode'
EXECUTE(@SQL)

DECLARE @ColName varchar(max)
SET  @ColName =' etypeid,EtypeCode,EtypeName+''(''+EtypeCode+'')'' as [职员/'+@AtypeName+'],Sonnum,ATypeCount,RowTotal,deleted'
IF @Flag =1
BEGIN
	IF @QueryType =0
		SET @ColName =' etypeid,EtypeName+''(''+EtypeCode+'')'' as [职员/收入],RowTotal as RowTotal'
	ELSE
		SET @ColName =' etypeid,EtypeName+''(''+EtypeCode+'')'' as [职员/费用支出],RowTotal as RowTotal'
END
--#06
--添加行合计值
ALTER TABLE #Temp_Result ADD RowTotal  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES

CREATE TABLE #Temp_SubListTable
(
	etypeid varchar(50),
	atypeid varchar(50),
	total  NUMERIC(24, 10) 
)

--****9.6需求修改 杨俊2015-04-16，因为这改动有点大还是保留原代码****
--3.15.2、职员部门费用表及部门收支表统计提成单 ,关联9.4BUG:4395
--SET @SQL='
--		INSERT INTO #Temp_SubListTable
--			SELECT SUBSTRING(etypeid,1,len('''+@ETypeID+''')+5) AS etypeid,ATypeID,ISNULL(SUM(Total),0) AS Total 
--			FROM ListTable l
--		'
--IF NOT (@ETypeID= '' AND @METypeId = '00001')
--	SET @SQL =@SQL+' INNER JOIN #etype e on (l.etypeid=e.typeid) '
--IF NOT (@STypeID = '' AND @MStypeid = '00000')
--	SET @SQL =@SQL+' INNER JOIN #Stype s on (l.stypeid=s.typeid) '
--IF @MDtypeid = '-99999'
--	SET @SQL =@SQL+' INNER JOIN #dtype de on (l.dtypeid=de.typeid) '
--IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
--	SET @SQL =@SQL+' INNER JOIN #btype bt on (l.btypeid=bt.typeid) '

--SET @SQL=@SQL+'
--				INNER JOIN #atype a on (l.atypeid=a.Typeid) 
--				WHERE	Audited=1
--					'
--IF @proinfo='3' --汽配版本
--	SET @SQL=@SQL+'	AND billtype NOT IN(178,179,181,182,186,191,197,198,200,196,192,195)'
	
--SET @SQL=@SQL+'
--					AND BillDate>='''+@StartDate+'''
--					AND BillDate<='''+@EndDate+'''
--				GROUP BY SUBSTRING(etypeid,1,len('''+@ETypeID+''')+5),ATypeID
--			  '
SET @SQL='
		INSERT INTO #Temp_SubListTable
			SELECT SUBSTRING(etypeid,1,len('''+@ETypeID+''')+5) AS etypeid,ATypeID,ISNULL(SUM(Total),0) AS Total 
			FROM 
			(
				SELECT etypeid,ATypeID,Total 
				FROM ListTable l
			'
	IF NOT (@ETypeID= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' INNER JOIN #etype e on (l.etypeid=e.typeid) '
	IF NOT (@STypeID = '' AND @MStypeid = '00000')
		SET @SQL =@SQL+' INNER JOIN #Stype s on (l.stypeid=s.typeid) '
	IF @MDtypeid = '-99999'
		SET @SQL =@SQL+' INNER JOIN #dtype de on (l.dtypeid=de.typeid) '
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL =@SQL+' INNER JOIN #btype bt on (l.btypeid=bt.typeid) '

	SET @SQL=@SQL+'
					INNER JOIN #atype a on (l.atypeid=a.Typeid) 
					WHERE	Audited=1
						'
	IF @proinfo='3' --汽配版本
		SET @SQL=@SQL+'	AND billtype NOT IN(178,179,181,182,186,191,197,198,200,196,192,195)'
		
	SET @SQL=@SQL+'
						AND BillDate>='''+@StartDate+'''
						AND BillDate<='''+@EndDate+''' '
	IF(@QueryType = 1)
	BEGIN
		SET @SQL += '
				UNION ALL	
				SELECT CBND.EtypeID,(SELECT TOP 1 nId FROM Ac_Items WHERE FullName = ''业务提成'') AS ATypeID,ISNULL(SUM(CBND.CommissionTotal),0) AS Total 
				FROM CommissionBillNew AS CBN
				INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
				  '
	IF NOT (@ETypeID= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' INNER JOIN #etype e on (CBND.etypeid=e.typeid) '
	IF NOT (@STypeID = '' AND @MStypeid = '00000')
		SET @SQL =@SQL+' INNER JOIN #Stype s on (CBN.stypeid=s.typeid) '
	IF @MDtypeid = '-99999'
		SET @SQL =@SQL+' INNER JOIN #dtype de on (CBND.dtypeid=de.typeid) '
		SET @SQL += '
						WHERE CBN.ifcheck = ''t'' 
							AND CBN.BillDate>='''+@StartDate+'''
							AND CBN.BillDate<='''+@EndDate+'''
						GROUP BY CBND.EtypeID '
	END
	SET @SQL += '
			) AS TEMP
			GROUP BY SUBSTRING(etypeid,1,len('''+@ETypeID+''')+5),ATypeID'
--****************************************************************************--
EXEC(@SQL)
--PRINT @SQL


--#06 行合计
SELECT etypeid, SUM(total) AS Total
INTO #Temp_RowSumSubListTable
FROM #Temp_SubListTable
GROUP BY
	etypeid

--#06 行合计
UPDATE #Temp_Result SET RowTotal = b.Total
FROM #Temp_Result AS a, #Temp_RowSumSubListTable b
WHERE a.etypeid=b.etypeid

DROP TABLE #Temp_RowSumSubListTable

--select * from #Atype

--SELECT * FROM #Temp_SubListTable where etypeid='0000100066'
--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(50)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(26)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT Typeid,UserCode,FullName FROM #Atype 
OPEN MAtypeCursor
FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount
WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@nPageCol - 1) * @MColPageNum
		BEGIN
			IF @Flag =0
			BEGIN	
				--更新临时结果表的结构
				SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName + '|' + @MyUserCode + ']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
				EXECUTE(@SQL)
				SET  @ColName= @ColName+',[' + @MyATypeName + '|' + @MyUserCode + ']'
				SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '|' + @MyUserCode + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable b
					WHERE a.etypeid=b.etypeid AND b.AtypeID=''' + @MyATypeID + ''''
			END
			ELSE
			BEGIN
				--更新临时结果表的结构
				SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName +']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
				EXECUTE(@SQL)
				SET  @ColName= @ColName+',[' + @MyATypeName +']'			
				SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable b
					WHERE a.etypeid=b.etypeid AND b.AtypeID=''' + @MyATypeID + ''''
			END
			--print @SQL
			EXECUTE(@SQL)
			
		END 
	
	IF @MColCount = @nPageCol * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
deallocate MAtypeCursor
EXEC('SELECT '+@Colname+' FROM #Temp_Result WHERE RowTotal<>0')

DROP TABLE #Temp_Result,#Temp_SubListTable, #Atype,#Etype,#Stype,#MainType,#Btype,#Dtype



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeIncExpListQueryPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeIncExpListQueryPrint]
GO











-------------------------------------------------------------------------
--职员收入报表、职员费用报表树型表查询
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23
	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在报表中的显示
	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：修改职员显示权限范围不正确的错误
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2003-11-21
	--说明：有错误：当筛选具体的一个职员时，返回空结果结合。
	--修改记录#05--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	
	--修改记录#06--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-09
	--说明：添加行合计（v3.9）
-------------------------------------------------------------------------
CREATE                            PROCEDURE Web_EmployeeIncExpListQueryPrint  
(
	@QueryType 		INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(50),	--指定要查询的财务科目节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@ETypeID		VARCHAR(50),	--职员编号
	@EmployeeName	VARCHAR(66),	--职员姓名
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@ATypePageNo	INT,				--分页会计科目的页码
	@ColPageNum 	int
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 			VARCHAR(8000)	--用于保存动态SQL语句的变量
DECLARE @MColPageNum 	INT				--定义分页的列上限
DECLARE @MColCount		INT				--列计数
SET @MColPageNum=@ColPageNum
SET @MColCount=0
--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
IF @AtypeID=''
	BEGIN
		SET @ATypeID=CASE @QueryType
			WHEN 0 THEN '00003'			--“收入类”科目根节点
			--WHEN 1 THEN '0000400003'	--“费用合计”科目根节点 --#05 注释了
			WHEN 1 THEN '00004' --“支出类”科目根节点 #05 添加
		END
	END
--#02以下------------------------------------------------------
IF @QueryType=0 SET @MAtypeid=@MIncome
IF @QueryType=1 SET @MAtypeid=@MExpense
--#02以上------------------------------------------------------
DECLARE @sonnum int
IF @ETypeID='' 
BEGIN
	SELECT @sonnum = sonnum FROM employee WHERE typeid=@MEtypeid
	IF @sonnum = 0
	BEGIN
		SET @ETypeID=@MEtypeid
	END
	ELSE
	BEGIN
		IF @MEtypeid = '00001' OR @MEtypeid = ''
			SET @ETypeID='00001'
		ELSE
			SET @ETypeID=@MEtypeid
	END
END
--创建结果集合临时表
CREATE TABLE #Temp_Result
(
	ETypeID		VARCHAR(25),
	ETypeCode	VARCHAR(26),
	ETypeName	VARCHAR(66),
	SonNum		INT,
	ATypeCount	INT
	,deleted int
)
--对结果集合填充满足条件的员工数据
SET @SQL='
INSERT INTO #Temp_Result (ETypeID,ETypeCode,ETypeName,SonNum,deleted)
SELECT 
	TypeID AS ETypeID,
	UserCode AS ETypeCode,
	FullName AS ETypeName,
	SonNum AS SonNum
	,deleted
FROM employee
WHERE '

DECLARE @ColName varchar(4000)
-- SET  @ColName =' EtypeID,EtypeCode,EtypeName+''(''+EtypeCode+'')'' as EtypeName,Sonnum,ATypeCount,RowTotal,deleted' 打印时专门去掉
IF @QueryType =0
	SET @ColName =' EtypeName+''(''+EtypeCode+'')'' as [职员/收入],RowTotal as [总计]'
ELSE
	SET @ColName =' EtypeName+''(''+EtypeCode+'')'' as [职员/费用支出],RowTotal as [总计]'


--#04 Begin---------------------------------
DECLARE @ETypeSonNum INT
SELECT @ETypeSonNum=SonNum FROM Employee WHERE Deleted=0 AND TypeID=@ETypeID
--print @ETypeSonNum
IF @ETypeSonNum>0 
	BEGIN
	SET @SQL=@SQL + '
	ParID=''' + @ETypeID +''''
	END
ELSE
	BEGIN
	SET @SQL=@SQL + '
	TypeID=''' + @ETypeID +''''
	END
--#04 End  ---------------------------------
--print @SQL
--select * from #Temp_Result
IF @METypeID<>''
	--SET @SQL=@SQL + 'AND ''' + @METypeID + ''' LIKE TypeID + ''%'''--#03 新添加---------------------------------
	SET @SQL=@SQL + 'AND TypeID LIKE ''' + @METypeID + '%'''--#03 新添加---------------------------------
SET @SQL=@SQL +'	
ORDER BY UserCode'
--print @SQL
EXECUTE(@SQL)
--#06
--添加行合计值
ALTER TABLE #Temp_Result ADD RowTotal  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES

--SELECT * FROM #Temp_Result
-- print @ETypeID
-- print @METypeID
-- Print @ATypeID
-- print @MAtypeid
-- return 0
--根据条件筛选职员收入、费用信息到一个临时表
--SELECT * FROM ListTable
SELECT SUBSTRING(ETypeID,1,len(@ETypeID)+5) AS ETypeID,ATypeID,ISNULL(SUM(Total),0) AS Total
INTO #Temp_SubListTable
FROM ListTable
WHERE 
	Audited=1
	AND BillDate>=@BillDateBegin
	AND BillDate<=@BillDateEnd
	AND ETypeID LIKE @ETypeID + '%'
	AND ETypeID LIKE @MEtypeid + '%'
	AND ATypeID LIKE @ATypeID + '%'
	AND ATypeID LIKE @MAtypeid + '%'
	AND ATypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
GROUP BY SUBSTRING(ETypeID,1,len(@ETypeID)+5),ATypeID

--#06 行合计
SELECT EtypeID, SUM(total) AS Total
INTO #Temp_RowSumSubListTable
FROM #Temp_SubListTable
GROUP BY
	EtypeID

--#06 行合计
UPDATE #Temp_Result SET RowTotal = b.Total
FROM #Temp_Result AS a, #Temp_RowSumSubListTable b
WHERE a.ETypeID=b.ETypeID

DROP TABLE #Temp_RowSumSubListTable

--SELECT * FROM #Temp_SubListTable
--以下是生成对会计科目列进行分页的处理
DECLARE @MyATypeID 		VARCHAR(25)		--用于保存科目编号的变量
DECLARE @MyUserCode		VARCHAR(26)		--用于保存用户定义的会计代码的变量
DECLARE @MyATypeName 	VARCHAR(66)		--用于保存科目名称的变量
DECLARE @ATypeCount		INT				--用于保存科目的总数量，用于列分页处理	
DECLARE MATypeCursor CURSOR STATIC FOR
SELECT TypeID,UserCode,FullName FROM Atype 
WHERE 
	SonNum=0
	AND TypeID LIKE @ATypeID + '%'--#03-------------
	AND TypeID LIKE @MAtypeid + '%'--#03-------------
	AND TypeID <> '000030000200007'--#01---该条语句屏蔽“借转进货结算与成本差”在报表中的显示
OPEN MAtypeCursor
FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
SET @ATypeCount=@@CURSOR_ROWS
UPDATE #Temp_Result SET AtypeCount=@ATypeCount
WHILE @@fetch_status=0
BEGIN
	
	IF @MColCount >= (@ATypePageNo - 1) * @MColPageNum
		BEGIN
			--更新临时结果表的结构
			SET @SQL='ALTER TABLE #Temp_Result ADD [' + @MyATypeName+']  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
			--print @SQL
			EXECUTE(@SQL)
			--SET  @ColName= @ColName+',[' + @MyATypeName + '|' + @MyUserCode + ']'
			SET  @ColName= @ColName+',[' + @MyATypeName +']'
			
			SET @SQL='UPDATE #Temp_Result SET [' + @MyATypeName  + '] = ISNULL(b.Total,0)
					FROM #Temp_Result AS a, #Temp_SubListTable b
					WHERE a.ETypeID=b.ETypeID AND b.AtypeID=''' + @MyATypeID + ''''
			--print @SQL
			EXECUTE(@SQL)
			
		END 
	
	IF @MColCount = @ATypePageNo * @MColPageNum -1 break
	
	SET @MColCount=@MColCount+1
	FETCH NEXT FROM MAtypeCursor INTO @MyATypeID,@MyUserCode,@MyATypeName
END 
CLOSE MAtypeCursor
deallocate MAtypeCursor
EXEC('SELECT '+@Colname+' FROM #Temp_Result')
DROP TABLE #Temp_Result
DROP TABLE #Temp_SubListTable
--SELECT * FROM employee
--SELECT * FROM listtable
--SELECT col_length('employee','fullname')
--EXECUTE Web_EmployeeIncExpListQuery 0,'','','','00001','','00001',1
--EXECUTE Web_EmployeeIncExpListQuery 0,'','2003-6-30','2003-8-29','00001','','00001',1











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeLift]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeLift]
GO


CREATE   PROCEDURE  Web_EmployeeLift  
(
	@OperatorID		varchar(50),	--  1、操作员 ID（作权限范围检查用）
	@StartDate		varchar(30),	--  2、查询起始时间
	@ENDDate		varchar(30),	--  3、查询结束时间
	@PTypeID		varchar(1550),	--  4、商品ID
	@BTypeID		varchar(1550),	--  5、客户ID
	@ETypeID		varchar(1550),	--  6、职员ID
	@DTypeID		varchar(1550),	--  7、部门ID
	@Billtype      varchar(100)=''    --  8、单据
)
--@encode$--
AS
SET NOCOUNT  ON
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
SET ARITHIGNORE ON
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------


CREATE TABLE #Ptype1 (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))


IF @PTypeID =''
	INSERT INTO #Ptype1(typeid)
		 select typeid from ptype where Typeid in (select typeid from  F_GetManDetailPType(@OperatorID))and iscombinationproduct=0
ELSE
	INSERT INTO #Ptype1(typeid) 
	select typeid FROM Ptype WHERE Typeid in 
	(	
		select a.typeid from F_GetManPTypeAll(@OperatorID) a,
		(select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a
	)and iscombinationproduct=0
	
	--select a.typeid from F_GetManDetailPType(@OperatorID) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a

CREATE CLUSTERED INDEX IX_#Ptype1_typeid ON #Ptype1(typeid)

IF @BtypeID =''
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @ETypeID=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@EtypeID,',')) b where left(a.typeid,len(b.a))=b.a

/*
IF @DtypeID=''
BEGIN
	INSERT INTO #Dtype select typeid from DepartMent where Sonnum =0
	INSERT INTO #Dtype SELECT ''
END
ELSE
	INSERT INTO #Dtype select typeid from department a ,(select * from  dbo.f_split(@DtypeID,',')) b where left(a.typeid,len(b.a))=b.a
*/
IF @DTypeID=''
	INSERT INTO #dtype SELECT typeid FROM dbo.F_GetManDetailDType(@OperatorID);
ELSE
	INSERT INTO #dtype SELECT a.typeid FROM dbo.F_GetManDetailDType(@OperatorID)a,(SELECT * FROM f_split(@DtypeID,',')) b WHERE left(a.typeid,len(b.a))=b.a


IF @PTypeID='00000'
	SET @PTypeID=''
IF @BTypeID='00000'
	SET @BTypeID=''
IF @DTypeID='00000'
	SET @DTypeID=''
IF @Billtype=''
	BEGIN
		SET @Billtype='11,45,305,141,160,4,215'
		IF EXISTS(SELECT * FROM SysData WHERE SubName='combinationproduct' AND SubValue='1')
			SET @Billtype+=',12,46'
	END
CREATE TABLE [dbo].[#Billtype] (
	[Billtype] varchar(200)
)

INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@Billtype,',')

DECLARE @SQL_WHERE varchar(4000)
DECLARE @SQL_WHERE_Billindex varchar(4000)
DECLARE @SQL varchar(8000)
IF @PTypeID='00000'
	SET @PTypeID=''
IF @MEtypeID=''
	SET @MEtypeID='00001'
-- 主表Billindex 查询条件
SET @SQL_WHERE=' AND 
			b.BillDate>='+char(39)+@StartDate+char(39)+'
			AND b.BillDate<='+char(39)+@EndDate+char(39)



-- 缩小 Billindex 表
CREATE TABLE #Billindex (
	BillnumberID  int,
	BillDate      Datetime,
	Billtype      int,
	EtypeID 	  varchar(50),
	--Qty            NUMERIC(24, 10) ,
--	Tax            NUMERIC(24, 10) ,
	--TotalMoney     NUMERIC(24, 10) ,
	TotalinMoney   NUMERIC(24, 10), 
	--CompleteTotal  NUMERIC(24, 10) ,
	AtypeID       varchar(50)  ,
	preferencemoney	   NUMERIC(24, 10)
)
SET @SQL='	INSERT INTO #Billindex
			SELECT b.BillnumberID,b.BillDate,b.Billtype,b.EtypeID,b.TotalinMoney,b.AtypeID,isnull(b.preferencemoney,0) 
			FROM Billindex b 
'
IF @ETypeID<>'' OR @METypeID=-99999 SET @SQL=@SQL+' INNER JOIN #EType e ON b.etypeid=e.typeid '+CHAR(13)

IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON b.dtypeid=d.typeid '+CHAR(13)

IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON b.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON b.BillType=t.BillType 
			WHERE b.redword=0 AND draft=0 
			'+@SQL_WHERE
--PRINT @SQL
EXEC(@SQL)


	

-- 缩小 Employee 表
CREATE TABLE #Employee (
	TypeID    varchar(50),
	UserCode  varchar(26),
	FullName  varchar(66),
	TCRate     NUMERIC(24, 10) ,
	Qty        NUMERIC(24, 10) ,--销售数量
	Total      NUMERIC(24, 10) ,--销售金额
	CostTotal  NUMERIC(24, 10) ,--成本金额
 	TaxTotal   NUMERIC(24, 10) ,--价税合计
	MaoLi      NUMERIC(24, 10) ,--销售毛利
	JSTAotal    NUMERIC(24, 10) ,-- 结算金额
	SKTBotal    NUMERIC(24, 10) ,--收款金额
	LiftTotal  NUMERIC(24, 10) --提成金额
)






-- 缩小InoutStocktable，因为涉及收款金额时不涉及到具体商品，所以没有对商品进行过滤
--2009-03-17 改成要过滤商品（因为有收款金额时，其他参与运算的字段也要过滤商品）
--cld搜索出商品
CREATE TABLE #InoutStocktable (
	BillnumberID  int,
	billtype		INT,
	BillDate      datetime,
	[ID]		  int,	
	EtypeID       varchar(50),
	PtypeID       varchar(50),
	Qty            NUMERIC(24, 10) ,--销售数量
	Total          NUMERIC(24, 10) ,--销售金额
	CostTotal      NUMERIC(24, 10) ,--成本金额
	TaxTotal       NUMERIC(24, 10) ,--价税合计
	MaoLi          NUMERIC(24, 10) ,--销售毛利
	JSTAotal        NUMERIC(24, 10) , -- 结算金额
	TCRate         NUMERIC(24, 10) --提成规则

)
--数量，金额等取负
SET @SQL='INSERT INTO #InoutStocktable
		SELECT  b.BillnumberID,
				b.billtype,
				b.billdate,
				a.ID,
				a.EtypeID,
				a.PtypeID,
				-a.Qty,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				0,--NULL,取消结算金额，所以变成0
				0
		FROM InoutStockTable a
		INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID 
		
'

IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #PType1 p ON a.PtypeID=p.typeid '

SET @SQL+= '  where   (b.billtype not in(305,215) or (b.billtype in(305,215) and isnull(b.preferencemoney,0)<>0)	)'
 EXEC(@SQL) 

--零售单且无抹零金额按表体统计 
SET @SQL='INSERT INTO #InoutStocktable
		  SELECT  b.BillnumberID,
				 a.billtype,
				b.billdate,
				a.ID,
				r.EtypeID,
				a.PtypeID,
				-a.Qty,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				0,--NULL,取消结算金额，所以变成0
				0
		FROM InoutStockTable a
		INNER JOIN retailbill R ON a.billnumberid=r.billnumberid AND a.id=r.id
		INNER JOIN Billindex b ON a.BillnumberID=b.BillnumberID 
'
IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #PType1 p ON a.PtypeID=p.typeid '
  IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON a.dtypeid=d.typeid '+CHAR(13)
IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON a.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON a.BillType=t.BillType	  '
 SET @SQL+=' where  b.billtype in(305) and isnull(b.preferencemoney,0)=0 and  b.redword=0 AND b.draft=0 '+@SQL_WHERE
EXEC(@SQL) 


--零售退货单且无抹零金额按表体统计 
SET @SQL='INSERT INTO #InoutStocktable
		  SELECT  b.BillnumberID,
				 a.billtype,
				b.billdate,
				a.ID,
				r.EtypeID,
				a.PtypeID,
				-a.Qty,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				0,--NULL,取消结算金额，所以变成0
				0
		FROM InoutStockTable a
		INNER JOIN RetailBackBill R ON a.billnumberid=r.billnumberid AND a.id=r.id
		INNER JOIN Billindex b ON a.BillnumberID=b.BillnumberID 
	
'
IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #PType1 p ON a.PtypeID=p.typeid '
 IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON a.dtypeid=d.typeid '+CHAR(13)
IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON a.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON a.BillType=t.BillType	  '
 SET @SQL+=' where  b.billtype in(215) and isnull(b.preferencemoney,0)=0 and  b.redword=0 AND b.draft=0 '+@SQL_WHERE
EXEC(@SQL) 


SET @SQL='INSERT INTO #Employee SELECT  TypeID,UserCode,FullName,tichengRate,0,0,0,0,0,0,0,0 FROM Employee 
		WHERE Sonnum=0 
		AND TypeID  IN (select typeid from #Etype)
		AND TypeID IN (SELECT EtypeID FROM #InoutStocktable)'
		
EXEC(@SQL)


--更新职员提成比例 
--cld计算成百分比
UPDATE #InoutStocktable
	SET TCRate=e.TCRate/100
FROM #InoutStocktable a
INNER JOIN 
	#Employee e
ON a.EtypeID=e.typeid

CREATE CLUSTERED INDEX IX_#InOutStockTable_BillDate ON #InOutStockTable(BillDate)

  

-- 更新职员 销售数量，销售金额，成本金额，价税合计，毛利,结算金额
--cld统计有业务每个职员的销售数量，销售金额，成本金额，价税合计，毛利,结算金额
UPDATE #Employee SET 
	Qty=a.Qty,Total=a.Total,CostTotal=a.CostTotal,TaxTotal=a.TaxTotal,MaoLi=a.MaoLi,JSTAotal=a.JSTAotal,SKTBotal=a.SKTBotal
FROM #Employee e
INNER JOIN
	(SELECT 
		EtypeID,
		SUM(Qty) as Qty,
		SUM(Total) as Total,
		SUM(CostTotal) as CostTotal,
		SUM(TaxTotal) as TaxTotal,
		SUM(MaoLi) as MaoLi,
		SUM(CASE  WHEN Billtype=305 then TaxTotal  when billtype=215 then -TaxTotal  else 0 end) as SKTBotal,
		0 as JSTAotal--SUM(ISNULL(JSTAotal,0)) as JSTAotal 
	FROM
		#InoutStocktable
	GROUP BY EtypeID
) a
ON e.TypeID=a.EtypeID



-- 更新收款金额，此金额与商品无关，只与单据Billindex有关
--cld统计有业务每个职员收款金额
UPDATE #Employee SET 
	SKTBotal=SKTBotal+TotalinMoney
FROM #Employee e
INNER JOIN
	(SELECT 
		EtypeID,
		SUM(CASE  WHEN Billtype IN (45,46) then -TotalinMoney WHEN Billtype NOT IN(215,305) then TotalinMoney ELSE 0 end) as TotalinMoney
	FROM
		#Billindex
	GROUP BY EtypeID
) a
ON e.TypeID=a.EtypeID

-- ======BEGIN  对提成规则进行筛选   ==============================================================================================
DECLARE @NOW varchar(30)
SET @NOW=Convert(varchar(10),Year(GetDate()))+'-'+Convert(varchar(10),Month(GetDate()))+'-'+Convert(varchar(10),Day(GetDate()))

CREATE TABLE #TCRule(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	Flag         int,    -- 1 含有 收款金额 字段的公式，0 无 
	ConstFlag    int     -- 1 公式中含有常量
)

 
-- 所有提成规则明细写入临时表
INSERT INTO #TCRule (EtypeID,PtypeID,StartDate,EndDate,Sub,ConstFlag)
SELECT	b.EtypeID,
		b.PtypeID,
		a.StartDate,
		a.EndDate,
		replace(replace(replace(replace(replace(replace(replace(replace(replace(b.Sub,'×','*'),'÷','/'),'销售数量','Qty'),'销售金额','Total'),'价税合计','TaxTotal'),'收款金额','SKTBotal'),'结算金额','JSTAotal'),'职员提成比例','TCRate'),'销售毛利','MaoLi'),
		b.ConstFlag
FROM	TCBillindex a,
		TCBill b ,
		#Employee E
WHERE	a.BillnumberID=b.BillnumberID
		AND A.IsUse = 1
		AND a.StartDate<=@NOW --(审核未执行，未审核除外)
		AND ((a.StartDate<= @StartDate AND a.EndDate>=@StartDate) OR (a.StartDate>= @StartDate AND a.StartDate<=@enddate)   )
		AND a.EtypeID<>''
		AND 
		(
			b.EtypeID='00000'  
			OR  LEFT(E.TypeID,LEN(b.EtypeID))=b.EtypeID
		)
ORDER BY a.BillDate,a.BillnumberID ,b.Row 

UPDATE #TCRule SET Row=[ID], Flag=0
UPDATE #TCRule SET Flag=1 WHERE Sub LIKE '%SKTBotal%' --含有 收款金额 字段的公式的提成规则置标志 Flag=1

CREATE CLUSTERED INDEX IX_#TCRule_PTypeID ON #TCRule(PTypeID)  
  
--ISNUMERIC


DECLARE @ConstFlag int --公式中是否含有计算常量
SET @ConstFlag=0
IF EXISTS(SELECT top 1 1 FROM #TCRule WHERE ConstFlag=1)
	SET @ConstFlag=1

DECLARE @RowTemp INT
DECLARE @EtypeIDTemp varchar(50)
DECLARE @PtypeIDTemp varchar(50)
DECLARE @StartDateTemp Datetime
DECLARE @EndDateTemp Datetime
DECLARE @FlagTemp int

CREATE TABLE #DELTCRule
(
	Row int
)

-- BEGIN 删除 职员，商品，起始日期，截止日期都重复且行数小于当前行的记录的提成规则
-- cld保证职员，商品，起始日期，截止日期是一条唯一记录
DECLARE  RuleDelCursor CURSOR FOR 
	SELECT Row,EtypeID,PtypeID,StartDate,EndDate,Flag FROM #TCRule ORDER BY Row DESC
OPEN RuleDelCursor
FETCH NEXT FROM RuleDelCursor  INTO @RowTemp,@EtypeIDTemp,@PtypeIDTemp,@StartDateTemp,@EndDateTemp,@FlagTemp
WHILE @@FETCH_STATUS=0
BEGIN
	INSERT #DELTCRule(ROW) 
	SELECT Row FROM #TCRule 
	WHERE  Row<@RowTemp 
		AND EtypeID=@EtypeIDTemp 
		AND PtypeID=@PtypeIDTemp 
		AND StartDate=@StartDateTemp 
		AND EndDate=@EndDateTemp
		AND Flag=@FlagTemp
	FETCH NEXT FROM RuleDelCursor INTO @RowTemp,@EtypeIDTemp,@PtypeIDTemp,@StartDateTemp,@EndDateTemp,@FlagTemp
END
CLOSE RuleDelCursor
DEALLOCATE RuleDelCursor
DELETE FROM #TCRule WHERE ROW IN (SELECT ROW FROM #DELTCRule)
TRUNCATE TABLE  #DELTCRule
-- END 删除 职员，商品，起始日期，截止日期都重复且行数小于当前行的记录的提成规则


DECLARE @BillnumberID numeric(18,0)
DECLARE @BillDate     datetime
DECLARE @Qty           NUMERIC(24, 10) 
DECLARE @Total         NUMERIC(24, 10) 
DECLARE @TaxTotal      NUMERIC(24, 10) 
DECLARE @MaoLi         NUMERIC(24, 10) 
DECLARE @SKTBotal       NUMERIC(24, 10) 
DECLARE @JSTAotal       NUMERIC(24, 10) 
DECLARE @LiftTotal     NUMERIC(24, 10) 
DECLARE @Sub          varchar(2000)


-- 含有 收款金额 字段的提成规则临时表
CREATE TABLE #TCRuleSK(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	ConstFlag    int
)  
--全部职员换成 00001
UPDATE #TCRule SET EtypeID='00001' WHERE EtypeID='00000' --为什么要替换?(一种收款全部商品-->全部职员,一种非收款全部商品-->全部职员，一种非收款一个商品-->全部职员)

-- 将#TCRuleSK临时表含有 父结点的提成规则全部明细到叶子结点
-- cld针对收款金额提成规则
	INSERT INTO #TCRuleSK
	select e.TypeID,a.PtypeID,a.StartDate,a.EndDate,a.Sub,a.Row,a.ConstFlag
	from #TCRule a 
	inner join Employee e ON a.EtypeID=LEFT(e.typeid,LEN(a.EtypeID))
	WHERE a.Flag=1 AND e.sonnum=0 AND  e.UserCode<>'admin'
	AND e.TypeID IN (SELECT EtypeID FROM #InoutStocktable)
	Order by a.Row

--更新 Row=ID自增字段，这样看起来连续,实际无甚用处
UPDATE #TCRuleSK SET Row=[ID]


-- BEGIN 删除重复的含有收款金额提成规则
-- cld去掉相同含有收款金额职员，起始日期，截止日期的规则
DECLARE  RuleDelCursor CURSOR FOR 
	SELECT Row,EtypeID,StartDate,EndDate FROM #TCRuleSK ORDER BY Row DESC
OPEN RuleDelCursor
FETCH NEXT FROM RuleDelCursor  INTO @RowTemp,@EtypeIDTemp,@StartDateTemp,@EndDateTemp
WHILE @@FETCH_STATUS=0
BEGIN
	INSERT #DELTCRule(ROW) SELECT Row FROM #TCRuleSK 
	WHERE  
		Row<@RowTemp 
		AND EtypeID=@EtypeIDTemp  
		AND StartDate=@StartDateTemp 
		AND EndDate=@EndDateTemp
	FETCH NEXT FROM RuleDelCursor INTO @RowTemp,@EtypeIDTemp,@StartDateTemp,@EndDateTemp
END
CLOSE RuleDelCursor
DEALLOCATE RuleDelCursor

DELETE FROM #TCRuleSK WHERE ROW IN (SELECT ROW FROM #DELTCRule)
-- END 含有收款金额 删除 职员，起始日期，截止日期都重复且行数小于当前行的记录的提成规则
TRUNCATE TABLE #DELTCRule


DECLARE @StartDate2 datetime
DECLARE @EndDate2 datetime

-- 含有 收款金额 字段的分解到具体职员，且时间段分解后的 提成规则,用于最后计算
CREATE TABLE #TCRuleSK2(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	ConstFlag 	 int
)


DECLARE @StartDateMin Datetime
DECLARE @EndDateMax Datetime




DECLARE  RuleFJCursor CURSOR FOR --不考虑商品
	SELECT Row,EtypeID,StartDate,EndDate,Sub,ConstFlag FROM #TCRuleSK ORDER BY Row DESC
OPEN RuleFJCursor
FETCH NEXT FROM RuleFJCursor  INTO @RowTemp,@EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
WHILE @@FETCH_STATUS=0
BEGIN

	IF NOT EXISTS(SELECT top 1 1 FROM #TCRuleSK2 WHERE EtypeID=@EtypeIDTemp)
	BEGIN
		INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
		SELECT @EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag

	END
	ELSE
	BEGIN
		/*
		SELECT TOP 1 @StartDateMin=StartDate FROM #TCRuleSK2 WHERE EtypeID=@EtypeIDTemp   ORDER BY StartDate 
		SELECT TOP 1 @EndDateMax=EndDate FROM #TCRuleSK2 WHERE EtypeID=@EtypeIDTemp   ORDER BY EndDate DESC
		*/
		SELECT @StartDateMin=MIN(StartDate),@EndDateMax=MAX(EndDate) 
		FROM #TCRuleSK2 WHERE EtypeID=@EtypeIDTemp
		
		
		
		IF @StartDateTemp<@StartDateMin --比当前规则更靠前的规则（开始日期）
		BEGIN
			IF @EndDateTemp<@StartDateMin--比当前规则更靠前的规则（开始日期，截止日期）
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
				SELECT @EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
			IF @EndDateTemp>=@StartDateMin AND @EndDateTemp<=@EndDateMax --更靠前的规则截止日期大于等于当前规则的开始日期,同时截止日期小于等于当前规则截止日期
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
				SELECT @EtypeIDTemp,@StartDateTemp,DATEADD(d,-1,@StartDateMin),@Sub,@RowTemp,@ConstFlag

			IF @EndDateTemp>@EndDateMax --比当前规则更靠后的规则（截止日期）日期覆盖整个当前规则
			BEGIN
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
				SELECT @EtypeIDTemp,@StartDateTemp,DATEADD(d,-1,@StartDateMin),@Sub,@RowTemp,@ConstFlag
				
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
				SELECT @EtypeIDTemp,DATEADD(d,1,@EndDateMax),@EndDateTemp,@Sub,@RowTemp,@ConstFlag
			END
 		END	
        --比当前规则更靠后的规则（开始日期)
		IF @StartDateMin<=@StartDateTemp AND @StartDateTemp<=@EndDateMax --比当前规则更靠后的规则（开始日期）,同时更靠后的规则开始日期小于当前规则的截止日期
		BEGIN
			IF @EndDateTemp>@EndDateMax
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
				SELECT @EtypeIDTemp,DATEADD(d,1,@EndDateMax),@EndDateTemp,@Sub,@RowTemp,@ConstFlag
		END				
		IF @StartDateTemp>@EndDateMax
		BEGIN
			INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
			SELECT @EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
		END
	END
	FETCH NEXT FROM RuleFJCursor INTO @RowTemp,@EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
END
CLOSE RuleFJCursor
DEALLOCATE RuleFJCursor

SET @RowTemp=0
SET @EtypeIDTemp=''
SET @Sub=''



-- ======END  对提成规则进行筛选    ===============================================================================================

-- BEGIN 计算收款金额的提成

--select * from #TCRuleSK2
CREATE TABLE #LiftTotal(Total  NUMERIC(24, 10) ) -- 临时表，用于临时存储提成金额，方便公式计算
--select * from #TCRuleSK2
DECLARE @EtypeID2 varchar(50)
DECLARE @PtypeID2 varchar(50)
CREATE TABLE #TEMP(Qty  NUMERIC(24, 10) ,Total  NUMERIC(24, 10) ,TaxTotal  NUMERIC(24, 10) ,MaoLi  NUMERIC(24, 10) ,JSTAotal  NUMERIC(24, 10) ,SKTBotal  NUMERIC(24, 10) ,TCRate  NUMERIC(24, 10) )
DECLARE TT CURSOR  FOR 
SELECT EtypeID,StartDate,EndDate,Sub,ConstFlag FROM #TCRuleSK2 
FOR UPDATE
OPEN TT
FETCH NEXT FROM TT INTO @EtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
WHILE @@FETCH_STATUS=0
BEGIN
	SET @SKTBotal=0
		-- 把零售和零售退后分开
		SELECT @SKTBotal=SUM(case  WHEN Billtype IN(45,46) then -TotalinMoney else TotalinMoney end) 
		FROM #Billindex WHERE billtype NOT IN(305,215,11) AND  (Billtype=4 OR AtypeID<>'') AND EtypeID=@EtypeID2 AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
		  
		
			
		SELECT @SKTBotal=ISNULL(@SKTBotal,0)+SUM(TotalinMoney) 
		FROM #Billindex 
		WHERE billtype IN(11) 
		AND EtypeID=@EtypeID2 
		AND BillDate>=@StartDateTemp 
		AND BillDate<=@EndDateTemp
		
	 
	
		SELECT @SKTBotal=ISNULL(@SKTBotal,0)+ ISNULL(SUM(case  WHEN Billtype IN(215) then -TaxTotal else TaxTotal end),0) 
		FROM #inoutstocktable WHERE billtype  IN(305,215) AND EtypeID=@EtypeID2 AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
		
	
		
	INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
	SELECT ISNULL(SUM(Qty),0) as Qty,ISNULL(SUM(Total),0) as Total,ISNULL(SUM(TaxTotal),0) as TaxTotal,ISNULL(SUM(MaoLi),0) as MaoLi,ISNULL(SUM(ISNULL(JSTAotal,0)),0) as JSTAotal,@SKTBotal,TCRate
	FROM #InoutStocktable WHERE EtypeID=@EtypeID2 AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
						--AND PtypeID LIKE @PtypeID+'%' AND  PtypeID  LIKE @chvMPTypeID+'%' 前面已过滤
	GROUP BY TCRate 
	
	

	-- 这一循环中的提成规则中，如果公式只含有 收款金额+10，则无 收了款（收款单或其他收了钱的单据)的单据时，不计算提成
	-- 这一循环中的提成规则中，如果公式只含有 收款金额*销售数量+10，则有其一时才计算提成
	-- 当收款金额，结算金额，（销售数量、销售金额、价税合计、销售毛利）不为NULL（即有业务发生时），才会加入统计中

	IF @ConstFlag=1  --含有计算常量
	BEGIN
		IF NOT EXISTS(SELECT top 1 1 FROM #TEMP)
		BEGIN
			IF @SKTBotal IS NOT NULL
			BEGIN
				INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
				SELECT 0,0,0,0,0,@SKTBotal,TCRate/100 FROM #Employee WHERE TypeID=@EtypeID2
			END
		END
	
		IF EXISTS(SELECT top 1 1 FROM #TEMP)
		BEGIN
			IF @SKTBotal IS NULL 
			BEGIN
				IF charindex('JSTAotal',@Sub)>0
				BEGIN           
					IF charindex('Qty',@Sub)>0 OR charindex('Total',@Sub)>0 OR charindex('TaxTotal',@Sub)>0 OR charindex('MaoLi',@Sub)>0 
					BEGIN
						UPDATE #TEMP SET SKTBotal=0 WHERE SKTBotal IS NULL	
						UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
					END
					ELSE	
					BEGIN
						IF EXISTS (SELECT TOP 1 1 FROM #InoutStocktable WHERE (JSTAotal IS NOT NULL) AND EtypeID=@EtypeID2 AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp)
						BEGIN
							UPDATE #TEMP SET SKTBotal=0 WHERE SKTBotal IS NULL	
							UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
						END
						ELSE
							DELETE FROM  #TEMP  WHERE SKTBotal IS NULL	
					END
				END				
				ELSE
				BEGIN
					
					IF charindex('Qty',@Sub)>0 OR charindex('Total',@Sub)>0 OR charindex('TaxTotal',@Sub)>0 OR charindex('MaoLi',@Sub)>0 
					BEGIN
						UPDATE #TEMP SET SKTBotal=0 WHERE SKTBotal IS NULL	
						UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
					END
					ELSE
					BEGIN
						DELETE FROM  #TEMP  WHERE SKTBotal IS NULL	
					END

				END
			END 
			ELSE
			BEGIN		--有收款金额
				UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
			END
		END
	END 
	IF (@SKTBotal IS NOT NULL) AND (NOT EXISTS(SELECT top 1 1 FROM #TEMP)) --处理不包含常量
	BEGIN
		INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
		SELECT 0,0,0,0,0,@SKTBotal,TCRate/100 FROM #Employee WHERE TypeID=@EtypeID2
	END	
	
	IF EXISTS(SELECT top 1 1 FROM #TEMP)
	BEGIN
		UPDATE #TEMP SET SKTBotal=0 WHERE SKTBotal IS NULL	
		UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
		EXEC('INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP ')
		--PRINT 'INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP '
		
		SET @LiftTotal=0
		SELECT @LiftTotal=ISNULL(Total,0) FROM #LiftTotal
		DELETE FROM #LiftTotal
		DELETE FROM #TEMP
	
		UPDATE	#Employee
		SET		LiftTotal=LiftTotal+@LiftTotal
		WHERE TypeID=@EtypeID2
	END
	FETCH NEXT FROM TT INTO @EtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
END
CLOSE TT
DEALLOCATE TT
TRUNCATE TABLE #TEMP


-- END 计算收款金额的提成




-- BEGIN **************************************************************** 计算明细到商品的提成
DECLARE @ID int

--具体到商品的提成规则
CREATE TABLE #TCRuleJS(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	ConstFlag    int
)

-- 全部商品 00000 时，更新成 replace(PtypeID,'00000','')


INSERT INTO #TCRuleJS(EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
SELECT DISTINCT T.EtypeID,case T.ptypeid when '00000' then '' else T.ptypeid end as ptypeid,T.StartDate,T.EndDate,T.Sub,T.Row,T.ConstFlag FROM #TCRule T,
#Ptype1 P
WHERE 
	T.Flag=0 
	AND
	(
		T.PtypeID='00000'  
		OR 	LEFT(T.PtypeID,LEN(P.TypeID))=P.TypeID
		OR 	LEFT(P.TypeID,LEN(T.PTypeID))=T.PtypeID
	)

--分解到具体商品，具体职员的提成规则
CREATE TABLE #TCRuleJSEND(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	ConstFlag	 int
)

CREATE INDEX IX_#TCRuleJSEND_PTypeID ON #TCRuleJSEND(PTypeID)

--分解到具体商品，具体职员且时间段分解后提成规则,用于最后计算
CREATE TABLE #TCRuleJSEND2(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	ConstFlag    int
)


CREATE INDEX IX_#TCRuleJSEND2_PTypeID ON #TCRuleJSEND2(PTypeID)  

CREATE CLUSTERED INDEX IX_#TCRuleJS_PTypeID ON #TCRuleJS(PTypeID)
CREATE  INDEX IX_#TCRuleJS_ETypeID ON #TCRuleJS(ETypeID)

--缩小Ptype 表
CREATE TABLE #Ptype(
	TypeID varchar(50),
	UserCode varchar(26),
	FullName  varchar(66)
)	


SET @PtypeID2=''


INSERT INTO #Ptype SELECT  DISTINCT TypeID,UserCode,FullName
FROM Ptype P
INNER JOIN #TCRuleJS A 	 ON   P.typeID LIKE A.PtypeID+'%' OR A.PtypeID=LEFT(P.typeid,LEN(a.PtypeID))
WHERE P.typeID IN (select typeid from #Ptype1)
	AND P.TypeID<>'00000'
AND P.TypeID IN (SELECT PtypeID FROM #InoutStocktable)

DECLARE @StartDateMin2 Datetime
DECLARE @EndDateMax2 Datetime




DECLARE @InFlag int --某一业务员的公式是否存在着商品包含的关系，如先设置一个 全部商品 公式A，再设置某一具体商品 公式B
SET @InFlag=0

CREATE TABLE #Employee1(TypeID varchar(50)) -- 公式中含有常量的操作员

INSERT INTO #Employee1
SELECT Distinct e.TypeID FROM #Employee e
INNER JOIN #TCRuleJS a
	ON a.EtypeID=LEFT(e.TypeID,LEN(a.EtypeID))
WHERE a.ConstFlag=1


DECLARE @TCRate  NUMERIC(24, 10) 


-- 公式 不 存在计算常量，如 销售金额  + 10
-- cld分解到具体商品，具体职员且时间段分解后提成规则
DECLARE @sPtypeID varchar(50) --cld
DECLARE TT CURSOR  FOR 
SELECT Distinct e.TypeID,e.TCRate/100 FROM #Employee e
INNER JOIN #TCRuleJS a
	ON a.EtypeID=LEFT(e.TypeID,LEN(a.EtypeID))
WHERE 
	 e.TypeID NOT IN (SELECT TypeID FROM #Employee1)
OPEN TT
FETCH NEXT FROM TT INTO @EtypeID2,@TCRate
WHILE @@FETCH_STATUS=0
BEGIN
	/*
	INSERT INTO #TCRuleJSEND
	SELECT 
		@EtypeID2 as EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag
	FROM  #TCRuleJS 
	WHERE EtypeID=LEFT(@EtypeID2,LEN(EtypeID))
	--select * from #TCRuleJSEND
	*/
	DECLARE  TCRuleCursor CURSOR FOR 
			--SELECT PtypeID,Row,StartDate,EndDate,Sub,ConstFlag FROM #TCRuleJSEND ORDER BY Row DESC
	SELECT PtypeID,Row,StartDate,EndDate,Sub,ConstFlag 
	FROM  #TCRuleJS 
	WHERE @EtypeID2 LIKE EtypeId+'%'
	ORDER BY Row DESC
		
	OPEN TCRuleCursor
	FETCH NEXT FROM TCRuleCursor  INTO @PtypeID2,@RowTemp,@StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
	WHILE @@FETCH_STATUS=0
	BEGIN
		IF NOT EXISTS(SELECT top 1 1 FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2)
		BEGIN
			IF EXISTS(
					SELECT top 1 1 FROM #TCRuleJSEND2 
					WHERE 	PtypeID LIKE @PtypeID2+'%' 
							AND NOT (@EndDateTemp<StartDate OR EndDate<@StartDateTemp)
					)
			BEGIN
				SET @InFlag=1
				BREAK
			END
            ELSE--cld
            BEGIN
                IF EXISTS(
					SELECT top 1 1 FROM #TCRuleJSEND2 
					WHERE 	LEFT(@PtypeID2,LEN(PtypeID))=PtypeID and len(@PtypeID2)>LEN(PtypeID)
							AND NOT (@EndDateTemp<StartDate OR EndDate<@StartDateTemp)
					)
			    BEGIN
				  SET @InFlag=1
			   	  BREAK
			    END
            END--cld
			INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
			SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
		END
		ELSE
		BEGIN
			/*
			SELECT TOP 1 @StartDateMin2=StartDate FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2  ORDER BY StartDate
			SELECT TOP 1 @EndDateMax2=EndDate FROM #TCRuleJSEND2  WHERE PtypeID=@PtypeID2 ORDER BY EndDate DESC
			*/
			SELECT @StartDateMin2=MIN(StartDate),@EndDateMax2=MAX(EndDate) 
			FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2
			
			
			IF @StartDateTemp<@StartDateMin2
			BEGIN
				IF @EndDateTemp<@StartDateMin2
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
					SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
				IF @EndDateTemp>=@StartDateMin2 AND @EndDateTemp<=@EndDateMax2
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
					SELECT @EtypeID2,@PtypeID2,@StartDateTemp,DATEADD(d,-1,@StartDateMin2),@Sub,@RowTemp,@ConstFlag

				IF @EndDateTemp>@EndDateMax2
				BEGIN
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
					SELECT @EtypeID2,@PtypeID2,@StartDateTemp,DATEADD(d,-1,@StartDateMin2),@Sub,@RowTemp,@ConstFlag
					
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
					SELECT @EtypeID2,@PtypeID2,DATEADD(d,1,@EndDateMax2),@EndDateTemp,@Sub,@RowTemp,@ConstFlag
				END
			END	
			IF @StartDateMin2<=@StartDateTemp AND @StartDateTemp<=@EndDateMax2
			BEGIN
				IF @EndDateTemp>@EndDateMax2
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
					SELECT @EtypeID2,@PtypeID2,DATEADD(d,1,@EndDateMax2),@EndDateTemp,@Sub,@RowTemp,@ConstFlag
			END				
			IF @StartDateTemp>@EndDateMax2
			BEGIN
				INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
				SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
			END
		END
		FETCH NEXT FROM TCRuleCursor INTO @PtypeID2,@RowTemp,@StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
	END
	CLOSE TCRuleCursor
	DEALLOCATE TCRuleCursor
	--select * from #TCRuleJSEND2
	IF @InFlag=0
	BEGIN
		DECLARE UPCurSor CURSOR  FOR 
		SELECT PtypeID,StartDate,EndDate,Sub,ConstFlag FROM #TCRuleJSEND2
		FOR UPDATE
		OPEN UPCurSor
		FETCH NEXT FROM UPCurSor INTO @PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
		WHILE @@FETCH_STATUS=0
		BEGIN
			IF @Sub<>''
			BEGIN
				INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
				SELECT Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate
				FROM (
					SELECT PtypeID,SUM(Qty) as Qty,SUM(Total) as Total,SUM(TaxTotal) as TaxTotal,SUM(MaoLi) as MaoLi,ISNULL(SUM(ISNULL(JSTAotal,0)),0) as JSTAotal,0 as SKTBotal,TCRate
					FROM #InoutStocktable WHERE EtypeID=@EtypeID2 AND PtypeID LIKE @PtypeID2+'%' AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
					GROUP BY PtypeID,TCRate
				) X
					
				EXEC('INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP ')
				--PRINT 'INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP '

				SET @LiftTotal=0
				SELECT @LiftTotal=ISNULL(SUM(Convert( NUMERIC(24, 10) ,ISNULL(Total,0))),0) FROM #LiftTotal
				DELETE FROM #LiftTotal
				DELETE FROM #TEMP
			
				UPDATE	#Employee
				SET		LiftTotal=LiftTotal+@LiftTotal
				WHERE TypeID=@EtypeID2
			END
			FETCH NEXT FROM UPCurSor INTO @PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
		END
		CLOSE UPCurSor
		DEALLOCATE UPCurSor
		TRUNCATE TABLE #TCRuleJSEND2
		TRUNCATE TABLE #TCRuleJSEND
		SET @InFlag=0
		SET @ConstFlag=0
	END
	ELSE --@InFlag=1 存在着包含关系
	BEGIN
		/*
		INSERT INTO #TCRuleJSEND
		SELECT 
			@EtypeID2 as EtypeID,P.TypeID as PtypeID,A.StartDate,A.EndDate,A.Sub,A.Row,A.ConstFlag
		FROM 	#TCRuleJS A
		INNER JOIN #Ptype P ON   P.typeID LIKE A.PtypeID+'%' OR A.PtypeID=LEFT(P.typeid,LEN(a.PtypeID))		WHERE  
			A.EtypeID=LEFT(@EtypeID2,LEN(A.EtypeID))
		*/
		
		DECLARE  TCRuleCursor CURSOR FOR 
			--SELECT Row,StartDate,EndDate,Sub,PtypeID,ConstFlag FROM #TCRuleJSEND ORDER BY Row DESC
		SELECT A.Row,A.StartDate,A.EndDate,A.Sub,P.TypeID,A.ConstFlag
		FROM #TCRuleJS A JOIN #Ptype P ON P.typeID LIKE A.PtypeID+'%'
		WHERE @EtypeID2 LIKE A.EtypeId+'%'
		ORDER BY Row DESC
		
		OPEN TCRuleCursor
		FETCH NEXT FROM TCRuleCursor  INTO @RowTemp,@StartDateTemp,@EndDateTemp,@Sub,@PtypeID2,@ConstFlag
		WHILE @@FETCH_STATUS=0
		BEGIN
			IF NOT EXISTS(SELECT top 1 1 FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2)
			BEGIN
				INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
				SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
			END
			ELSE
			BEGIN
				/*
				SELECT TOP 1 @StartDateMin2=StartDate FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2 ORDER BY StartDate
				SELECT TOP 1 @EndDateMax2=EndDate FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2  ORDER BY EndDate DESC
				*/
				SELECT @StartDateMin2=MIN(StartDate),@EndDateMax2=MAX(EndDate) 
				FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2
				
				
				IF @StartDateTemp<@StartDateMin2
				BEGIN
					IF @EndDateTemp<@StartDateMin2
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
					IF @EndDateTemp>=@StartDateMin2 AND @EndDateTemp<=@EndDateMax2
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,@StartDateTemp,DATEADD(d,-1,@StartDateMin2),@Sub,@RowTemp,@ConstFlag

					IF @EndDateTemp>@EndDateMax2
					BEGIN
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,@StartDateTemp,DATEADD(d,-1,@StartDateMin2),@Sub,@RowTemp,@ConstFlag
						
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,DATEADD(d,1,@EndDateMax2),@EndDateTemp,@Sub,@RowTemp,@ConstFlag
					END
				END	
				IF @StartDateMin2<=@StartDateTemp AND @StartDateTemp<=@EndDateMax2
				BEGIN
					IF @EndDateTemp>@EndDateMax2
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,DATEADD(d,1,@EndDateMax2),@EndDateTemp,@Sub,@RowTemp,@ConstFlag
				END				
				IF @StartDateTemp>@EndDateMax2
				BEGIN
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
					SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
				END
			END
			FETCH NEXT FROM TCRuleCursor INTO @RowTemp,@StartDateTemp,@EndDateTemp,@Sub,@PtypeID2,@ConstFlag
		END

		
		DECLARE UPCurSor CURSOR  FOR 
		SELECT Distinct StartDate,EndDate,Sub FROM #TCRuleJSEND2
		OPEN UPCurSor
		FETCH NEXT FROM UPCurSor INTO @StartDateTemp,@EndDateTemp,@Sub
		WHILE @@FETCH_STATUS=0
		BEGIN
			IF @Sub<>''
			BEGIN
				INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
				SELECT Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate FROM (
				SELECT PtypeID,SUM(Qty) as Qty,SUM(Total) as Total,SUM(TaxTotal) as TaxTotal,SUM(MaoLi) as MaoLi,ISNULL(SUM(ISNULL(JSTAotal,0)),0) as JSTAotal,0 as SKTBotal,TCRate
				FROM #InoutStocktable 
				WHERE EtypeID=@EtypeID2 
				AND BillDate>=@StartDateTemp 
				AND BillDate<=@EndDateTemp	
				AND PtypeID IN (SELECT PTypeID FROM #TCRuleJSEND2 WHERE EtypeID=@EtypeID2 AND StartDate=@StartDateTemp AND EndDate=@EndDateTemp AND Sub=@Sub)
				GROUP BY PtypeID,TCRate
				) X
				
				EXEC('INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP ')
				--PRINT 'INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP '

				SET @LiftTotal=0
				SELECT @LiftTotal=ISNULL(SUM(Convert( NUMERIC(24, 10) ,ISNULL(Total,0))),0) FROM #LiftTotal
				DELETE FROM #LiftTotal
				DELETE FROM #TEMP
			
				UPDATE	#Employee
				SET		LiftTotal=LiftTotal+@LiftTotal
				WHERE TypeID=@EtypeID2
			END
			FETCH NEXT FROM UPCurSor INTO @StartDateTemp,@EndDateTemp,@Sub
		END
		CLOSE UPCurSor
		DEALLOCATE UPCurSor
		
		TRUNCATE TABLE #TCRuleJSEND
		TRUNCATE TABLE #TCRuleJSEND2
		CLOSE TCRuleCursor
		DEALLOCATE TCRuleCursor
	END
	FETCH NEXT FROM TT INTO @EtypeID2,@TCRate
END
CLOSE TT
DEALLOCATE TT


CREATE TABLE #TCRuleJSENDUP(
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Qty  NUMERIC(24, 10) ,
	Total  NUMERIC(24, 10) ,
	TaxTotal  NUMERIC(24, 10) ,
	MaoLi  NUMERIC(24, 10) ,
	JSTAotal  NUMERIC(24, 10) ,
	SKTBotal  NUMERIC(24, 10) ,
	TCRate  NUMERIC(24, 10) 
)

-- 带有计算常量的公式的职员
DECLARE TT CURSOR  FOR 
SELECT Distinct e.TypeID,e.TCRate/100 FROM #Employee e
INNER JOIN #TCRuleJS a
	ON a.EtypeID=LEFT(e.TypeID,LEN(a.EtypeID))
WHERE  e.TypeID IN (SELECT TypeID FROM #Employee1)
OPEN TT
FETCH NEXT FROM TT INTO @EtypeID2,@TCRate
WHILE @@FETCH_STATUS=0
BEGIN
		INSERT INTO #TCRuleJSEND
		SELECT 
			@EtypeID2 as EtypeID,P.TypeID as PtypeID,A.StartDate,A.EndDate,A.Sub,A.Row,A.ConstFlag
		FROM 	#TCRuleJS A
		INNER JOIN #Ptype P ON   P.typeID LIKE A.PtypeID+'%' OR A.PtypeID=LEFT(P.typeid,LEN(a.PtypeID))		WHERE  
			A.EtypeID=LEFT(@EtypeID2,LEN(A.EtypeID))
		
		DECLARE  TCRuleCursor CURSOR FOR 
			SELECT Row,StartDate,EndDate,Sub,PtypeID,ConstFlag FROM #TCRuleJSEND ORDER BY Row DESC
		OPEN TCRuleCursor
		FETCH NEXT FROM TCRuleCursor  INTO @RowTemp,@StartDateTemp,@EndDateTemp,@Sub,@PtypeID2,@ConstFlag
		WHILE @@FETCH_STATUS=0
		BEGIN
			IF NOT EXISTS(SELECT top 1 1 FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2)
			BEGIN
				INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
				SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
			END
			ELSE
			BEGIN
				/*
				SELECT TOP 1 @StartDateMin2=StartDate FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2 ORDER BY StartDate
				SELECT TOP 1 @EndDateMax2=EndDate FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2  ORDER BY EndDate DESC
				*/
				SELECT @StartDateMin2=MIN(StartDate),@EndDateMax2=MAX(EndDate) 
				FROM #TCRuleJSEND2 WHERE PtypeID=@PtypeID2
				
				IF @StartDateTemp<@StartDateMin2
				BEGIN
					IF @EndDateTemp<@StartDateMin2
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
					IF @EndDateTemp>=@StartDateMin2 AND @EndDateTemp<=@EndDateMax2
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,@StartDateTemp,DATEADD(d,-1,@StartDateMin2),@Sub,@RowTemp,@ConstFlag

					IF @EndDateTemp>@EndDateMax2
					BEGIN
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,@StartDateTemp,DATEADD(d,-1,@StartDateMin2),@Sub,@RowTemp,@ConstFlag
						
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,DATEADD(d,1,@EndDateMax2),@EndDateTemp,@Sub,@RowTemp,@ConstFlag
					END
				END	
				IF @StartDateMin2<=@StartDateTemp AND @StartDateTemp<=@EndDateMax2
				BEGIN
					IF @EndDateTemp>@EndDateMax2
						INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
						SELECT @EtypeID2,@PtypeID2,DATEADD(d,1,@EndDateMax2),@EndDateTemp,@Sub,@RowTemp,@ConstFlag
				END				
				IF @StartDateTemp>@EndDateMax2
				BEGIN
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,ConstFlag)
					SELECT @EtypeID2,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@ConstFlag
				END
			END
			FETCH NEXT FROM TCRuleCursor INTO @RowTemp,@StartDateTemp,@EndDateTemp,@Sub,@PtypeID2,@ConstFlag
		END
		
		DECLARE UPCurSor CURSOR  FOR 
		SELECT Distinct StartDate,EndDate,Sub,ConstFlag FROM #TCRuleJSEND2
		OPEN UPCurSor		
		FETCH NEXT FROM UPCurSor INTO @StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
		WHILE @@FETCH_STATUS=0
		BEGIN
			IF @Sub<>''
			BEGIN
				INSERT INTO #TCRuleJSENDUP(PtypeID,EtypeID,StartDate,EndDate,Sub,TCRate,Qty,Total,TaxTotal,MaoLi,JSTAotal) 
				SELECT PtypeID,EtypeID,StartDate,EndDate,Sub,@TCRate,NULL,NULL,NULL,NULL,NULL FROM #TCRuleJSEND2 
				WHERE StartDate=@StartDateTemp AND EndDate=@EndDateTemp AND Sub=@Sub
				--含有计算常量且只含有结算金额字段
				IF @ConstFlag=1 AND charindex('JSTAotal',@Sub)>0 AND NOT(charindex('Qty',@Sub)>0 OR charindex('Total',@Sub)>0 OR charindex('TaxTotal',@Sub)>0 OR charindex('MaoLi',@Sub)>0 )
				BEGIN
					UPDATE #TCRuleJSENDUP SET Qty=ISNULL(B.Qty,0),Total=ISNULL(B.Total,0),TaxTotal=ISNULL(B.TaxTotal,0),MaoLi=ISNULL(B.MaoLi,0),JSTAotal=ISNULL(B.JSTAotal,0)
					FROM #TCRuleJSENDUP A
					INNER JOIN
					(
					SELECT SUM(Qty) as Qty,SUM(Total) as Total,SUM(TaxTotal) as TaxTotal,SUM(MaoLi) as MaoLi,SUM(ISNULL(JSTAotal,0)) as JSTAotal,0 as SKTBotal,TCRate,PtypeID
					FROM #InoutStocktable 
					WHERE (JSTAotal IS NOT NULL) ---过滤掉JSTAotal=NULL
					AND EtypeID=@EtypeID2 
					AND BillDate>=@StartDateTemp 
					AND BillDate<=@EndDateTemp	
					AND PtypeID IN (SELECT PTypeID FROM #TCRuleJSEND2 WHERE EtypeID=@EtypeID2 AND StartDate=@StartDateTemp AND EndDate=@EndDateTemp AND Sub=@Sub)
					GROUP BY TCRate,PtypeID
					) B
					ON A.PtypeID=B.PtypeID
				END
				ELSE
				BEGIN
					UPDATE #TCRuleJSENDUP SET Qty=ISNULL(B.Qty,0),Total=ISNULL(B.Total,0),TaxTotal=ISNULL(B.TaxTotal,0),MaoLi=ISNULL(B.MaoLi,0),JSTAotal=ISNULL(B.JSTAotal,0)
					FROM #TCRuleJSENDUP A
					INNER JOIN
					(
					SELECT SUM(Qty) as Qty,SUM(Total) as Total,SUM(TaxTotal) as TaxTotal,SUM(MaoLi) as MaoLi,SUM(ISNULL(JSTAotal,0)) as JSTAotal,0 as SKTBotal,TCRate,PtypeID
					FROM #InoutStocktable 
					WHERE EtypeID=@EtypeID2 
					AND BillDate>=@StartDateTemp 
					AND BillDate<=@EndDateTemp	
					AND PtypeID IN (SELECT PTypeID FROM #TCRuleJSEND2 WHERE EtypeID=@EtypeID2 AND StartDate=@StartDateTemp AND EndDate=@EndDateTemp AND Sub=@Sub)
					GROUP BY TCRate,PtypeID
					) B
					ON A.PtypeID=B.PtypeID
				END
				DELETE FROM #TCRuleJSENDUP WHERE Qty IS NULL -- 删除本公式时间段内没有经营历程的数据


				--SELECT * FROM #TCRuleJSENDUP
				EXEC('INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TCRuleJSENDUP ')
				--PRINT 'INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP '

				SET @LiftTotal=0
				SELECT @LiftTotal=ISNULL(SUM(Convert( NUMERIC(24, 10) ,ISNULL(Total,0))),0) FROM #LiftTotal
				DELETE FROM #LiftTotal
			
			
				UPDATE	#Employee
				SET		LiftTotal=LiftTotal+@LiftTotal
				WHERE TypeID=@EtypeID2
				DELETE FROM  #TCRuleJSENDUP
			END
			FETCH NEXT FROM UPCurSor INTO @StartDateTemp,@EndDateTemp,@Sub,@ConstFlag
		END
		CLOSE UPCurSor
		DEALLOCATE UPCurSor
		
	

		TRUNCATE TABLE #TCRuleJSEND
		TRUNCATE TABLE #TCRuleJSEND2
		CLOSE TCRuleCursor
		DEALLOCATE TCRuleCursor
	FETCH NEXT FROM TT INTO @EtypeID2,@TCRate

END
CLOSE TT
DEALLOCATE TT

-- END 计算具体商品的提成

-- 得到结果
SELECT 	
	TypeID,
	UserCode,
	FullName,
	TCRate,
	Qty,
	Total,
	CostTotal,
	TaxTotal,
	MaoLi,
	JSTAotal,
	SKTBotal,
	Convert( NUMERIC(24, 10) ,ISNULL(LiftTotal,0)) as LiftTotal
FROM #Employee 
Order by UserCode



DROP TABLE #InoutStockTable
DROP TABLE #Ptype
DROP TABLE #Employee
DROP TABLE #Billindex
DROP TABLE #TCRule
DROP TABLE #TCRuleJS
DROP TABLE #TCRuleSK
DROP TABLE #TCRuleSK2
DROP TABLE #LiftTotal

DROP TABLE #Ptype1
DROP TABLE #Btype
DROP TABLE #Etype
DROP TABLE #Dtype
RETURN 0

SET QUOTED_IDENTIFIER OFF 















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeLiftBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeLiftBillDetail]
GO




CREATE                     PROCEDURE  Web_EmployeeLiftBillDetail 
(
	@OperatorID		varchar(50),	--  1、操作员 ID（作权限范围检查用）
	@StartDate		varchar(30),	--  2、查询起始时间
	@ENDDate		varchar(30),	--  3、查询结束时间
	@PTypeID		varchar(50),	--  4、商品ID
	@BTypeID		varchar(1550),	--  5、客户ID
	@ETypeID		varchar(50),	--  6、职员ID
	@DTypeID		varchar(1550),	--  7、部门ID
	@Billtype      varchar(100)='' --  8、单据

)
--@encode$--
AS
SET NOCOUNT  ON
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
SET ARITHIGNORE ON
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),
@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid 
OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense 
OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------

CREATE TABLE #Ptype1 (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))


IF @PTypeID =''
	INSERT INTO #Ptype1(typeid) select typeid from F_GetManDetailPType(@OperatorID)
ELSE
	INSERT INTO #Ptype1(typeid) select a.typeid from F_GetManDetailPType(@OperatorID) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a


IF @BtypeID =''
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @ETypeID=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@EtypeID,',')) b where left(a.typeid,len(b.a))=b.a
/*
IF @DtypeID=''
BEGIN
	INSERT INTO #Dtype select typeid from DepartMent where Sonnum =0 
	INSERT INTO #Dtype SELECT ''
END
ELSE
	INSERT INTO #Dtype select typeid from department a ,(select * from  dbo.f_split(@DtypeID,',')) b where left(a.typeid,len(b.a))=b.a
*/
IF @DTypeID=''
	INSERT INTO #dtype SELECT typeid FROM dbo.F_GetManDetailDType(@OperatorID);
ELSE
	INSERT INTO #dtype SELECT a.typeid FROM dbo.F_GetManDetailDType(@OperatorID)a,(SELECT * FROM f_split(@DTypeID,',')) b WHERE left(a.typeid,len(b.a))=b.a


IF @PTypeID='00000'
	SET @PTypeID=''
IF @BTypeID='00000'
	SET @BTypeID=''
IF @DTypeID='00000'
	SET @DTypeID=''
IF @Billtype=''
	SET @Billtype='11,45,305,215,141,160,4,12,45'
CREATE TABLE [dbo].[#Billtype] (
	[Billtype] varchar(200)
)
INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@Billtype,',')

DECLARE @SQL_WHERE varchar(4000)
DECLARE @SQL_WHERE_Billindex varchar(4000)
DECLARE @SQL varchar(8000)
IF @PTypeID='00000'
	SET @PTypeID=''
SET @SQL_WHERE=' AND 
			b.BillDate>='+char(39)+@StartDate+char(39)+'
			AND b.BillDate<='+char(39)+@EndDate+char(39)

DECLARE @SQL_P varchar(2000)
SET @SQL_P = ' AND a.PtypeID IN (select typeid from #Ptype1) '




CREATE TABLE #Billindex (
	BillnumberID  int,
	BillDate      Datetime,
	Billtype      int,
	BillCode      varchar(200),
	BtypeID       varchar(50),
	KtypeID       varchar(50),
	KtypeID2       varchar(50),
	checke        varchar(50),
	Comment       varchar(256),
	EtypeID 	  varchar(50),
	Qty            NUMERIC(24, 10) ,
	Tax            NUMERIC(24, 10) ,
	TotalMoney     NUMERIC(24, 10) ,
	TotalinMoney   NUMERIC(24, 10) ,
	CompleteTotal  NUMERIC(24, 10) ,
	dealbtypeid	 VARCHAR(50),
	preferencemoney	   NUMERIC(24, 10)
)


SET @SQL='	INSERT INTO #Billindex
				SELECT b.BillnumberID,b.BillDate,b.Billtype,b.BillCode,b.BtypeID,b.KtypeID,b.Ktypeid2,b.Checke,b.Comment,b.EtypeID,b.TotalQty,b.Tax,b.TotalMoney, case when b.Billtype IN (45,215,46) then -b.totalinmoney else b.totalinmoney end as totalinmoney,b.CompleteTotal ,B.dealbtypeid,b.preferencemoney
				FROM Billindex b 
'
--IF @ETypeID<>'' OR @METypeID=-99999 SET @SQL=@SQL+' INNER JOIN #EType e ON b.etypeid=e.typeid '+CHAR(13)

IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON b.dtypeid=d.typeid '+CHAR(13)

IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON b.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON b.BillType=t.BillType 

				WHERE  b.draft=0 AND b.RedWord =0 '+@SQL_WHERE

--PRINT @SQL
EXEC(@SQL)


--select * from #Billindex order by billCode



-- 缩小InoutStocktable，因为涉及收款金额时不涉及到具体商品，所以没有对商品进行过滤
CREATE TABLE #InoutStocktable (
	BillnumberID  int,
	BillDate      datetime,
	[ID]		  int,	
	EtypeID       varchar(50),
	PtypeID       varchar(50),
	KtypeID       varchar(50),
	Qty            NUMERIC(24, 10) ,
	Price          NUMERIC(24, 10) ,
	TaxPrice       NUMERIC(24, 10) ,
	Total          NUMERIC(24, 10) ,
	CostTotal      NUMERIC(24, 10) ,
	TaxTotal       NUMERIC(24, 10) ,
	MaoLi          NUMERIC(24, 10) ,
	JSTotal        NUMERIC(24, 10)  -- 结算金额

)

SET @SQL='INSERT INTO #InoutStocktable
		SELECT  b.BillnumberID,
				b.billdate,
				a.ID,
				a.EtypeID,
				a.PtypeID,
				a.KtypeID,
				-a.Qty,
				a.Price,
				a.taxprice as TaxPrice,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				0
		FROM InoutStockTable a
		INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID   '
     IF @ETypeID<>'' OR @METypeID=-99999 SET @SQL=@SQL+' INNER JOIN #EType e ON b.etypeid=e.typeid '+CHAR(13)
	IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #PType1 p ON a.PtypeID=p.typeid '
	SET @SQL+= '  where   (b.billtype not in(305,215) or (b.billtype in(305,215) and isnull(b.preferencemoney,0)<>0)	)'
	
	--PRINT @SQL
	
EXEC(@SQL)
  --零售单且无抹零金额按表体统计 
SET @SQL='INSERT INTO #InoutStocktable
		 	SELECT  b.BillnumberID,
				b.billdate,
				a.ID,
				a.EtypeID,
				a.PtypeID,
				a.KtypeID,
				-a.Qty,
				a.Price,
				a.taxprice as TaxPrice,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				0
		FROM InoutStockTable a
		INNER JOIN retailbill R ON a.billnumberid=r.billnumberid AND a.id=r.id
		inner join billindex b on a.billnumberid=b.billnumberid
		
'
IF @ETypeID<>'' OR @METypeID=-99999 SET @SQL=@SQL+' INNER JOIN #EType e ON r.etypeid=e.typeid '+CHAR(13)
IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'   INNER JOIN #PType1 p ON a.PtypeID=p.typeid '
IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON a.dtypeid=d.typeid '+CHAR(13)
IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON a.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON a.BillType=t.BillType	  '

 SET @SQL+=' where  b.billtype in(305) and isnull(b.preferencemoney,0)=0'
EXEC(@SQL) 


--零售退货单且无抹零金额按表体统计 
SET @SQL='INSERT INTO #InoutStocktable
		  	SELECT  b.BillnumberID,
				b.billdate,
				a.ID,
				a.EtypeID,
				a.PtypeID,
				a.KtypeID,
				-a.Qty,
				a.Price,
				a.taxprice as TaxPrice,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				0
		FROM InoutStockTable a
		INNER JOIN RetailBackBill R ON a.billnumberid=r.billnumberid AND a.id=r.id
		inner join billindex b on a.billnumberid=b.billnumberid

		
'
IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #PType1 p ON a.PtypeID=p.typeid '
 IF @ETypeID<>'' OR @METypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #EType e ON r.etypeid=e.typeid '+CHAR(13)
  IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON a.dtypeid=d.typeid '+CHAR(13)
IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON a.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON a.BillType=t.BillType	  '
 SET @SQL+=' where  b.billtype in(215) and isnull(b.preferencemoney,0)=0'
EXEC(@SQL) 
	 
 --SELECT * from #InoutStocktable
IF @PTypeID='0' --直接收款
BEGIN
	IF NOT EXISTS (SELECT * FROM #BillIndex WHERE Billtype=160)
	BEGIN
		SELECT * FROM (
		SELECT 	
			b.BillnumberID,
			b.BillDate,
			b.BillCode,
			BillName=Case b.Billtype when 12 then '组合品销售出库单' when 46 then '组合品销售退货单' when 4 then '收款单' when 305 then '零售单' WHEN 215 THEN '零售退货单' when 11 then '销售出库单' when 45 then '销售退货单' when 160 then '销售换货单' when 141 then '委托代销结算单' end ,
			/*BFullName=b1.Fullname ,
			EFullName=e.FullName,
			KFullName=ISNULL(Case b.billtype when 141 then '代销库' else K.FullName end,''),*/
            btypeid=b1.typeid,
		    etypeid=e.typeid,
		    E1FullName=e1.FullName,
		    ktypeid=Case b.Billtype when 141 then '10000' else K.typeid end,
			--UserCode='',
			--FullName='',
			--Unit1='',
            '' as ptypeid,
			Qty=0,
			Price=0,
			TaxPrice=0,
			Total=0,
			taxTotal=0,
			MaoLi=0,
			MaoLilu=0,
			CostTotal=0,
			JSTotal=0,
			SKTOtal=CASE b.Billtype when 45 then -b.TotalinMoney else b.TotalinMoney end,
			b.Comment,
			b.billType,
			B.dealbtypeid
		FROM #Billindex b
		--INNER JOIN #InoutStocktable i ON b.BillnumberID=i.BillnumberID
		LEFT JOIN Btype B1  ON   b1.TypeID=b.BtypeID
		LEFT JOIN Stock K  ON b.KtypeID=K.TypeID
		LEFT JOIN Employee e ON b.EtypeID=e.TypeID
		LEFT JOIN Employee e1  ON b.checke=e1.TypeID
		WHERE b.TotalinMoney<>0	 AND e.TypeID = @ETypeID
		AND (b.billtype not in(305,215) or (b.billtype in(305,215) and isnull(b.preferencemoney,0)<>0))
		
		UNION ALL
		SELECT 	
			b.BillnumberID,
			b.BillDate,
			b.BillCode,
			BillName=Case b.Billtype when 12 then '组合品销售出库单' when 46 then '组合品销售退货单' when 4 then '收款单' when 305 then '零售单' WHEN 215 THEN '零售退货单' when 11 then '销售出库单' when 45 then '销售退货单' when 160 then '销售换货单' when 141 then '委托代销结算单' end ,
			/*BFullName=b1.Fullname ,
			EFullName=e.FullName,
			KFullName=ISNULL(Case b.billtype when 141 then '代销库' else K.FullName end,''),*/
            btypeid=b1.typeid,
		    etypeid=e.typeid,
		    E1FullName=e1.FullName,
		    ktypeid=Case b.Billtype when 141 then '10000' else K.typeid end,
			--UserCode='',
			--FullName='',
			--Unit1='',
            '' as ptypeid,
			Qty=0,
			Price=0,
			TaxPrice=0,
			Total=0,
			taxTotal=0,
			MaoLi=0,
			MaoLilu=0,
			CostTotal=0,
			JSTotal=0,
			SKTOtal=CASE  WHEN b.billtype=215 AND  isnull(b.preferencemoney,0)=0 THEN -i.TaxTotal  
							WHEN b.billtype=305 AND  isnull(b.preferencemoney,0)=0 THEN i.TaxTotal 
						ELSE b.TotalinMoney end,
			b.Comment,
			b.billType,
			B.dealbtypeid
		FROM #Billindex b
		INNER JOIN #InoutStocktable i ON b.BillnumberID=i.BillnumberID
		LEFT JOIN Btype B1  ON   b1.TypeID=b.BtypeID
		LEFT JOIN Stock K  ON b.KtypeID=K.TypeID
		LEFT JOIN Employee e ON b.EtypeID=e.TypeID
		LEFT JOIN Employee e1  ON b.checke=e1.TypeID
		WHERE b.TotalinMoney<>0	 and b.billtype in(215,305) and isnull(b.preferencemoney,0)=0
		)b
		ORDER BY b.BillDate,b.BillCode
	END	

	ELSE
	BEGIN
		SELECT * FROM (
			SELECT 	
				b.BillnumberID,
				b.BillDate,
				b.BillCode,
				BillName=Case b.Billtype when 12 then '组合品销售出库单' when 46 then '组合品销售退货单' when 4 then '收款单' when 305 then '零售单' WHEN 215 THEN '零售退货单' when 11 then '销售出库单' when 45 then '销售退货单' when 160 then '销售换货单' when 141 then '委托代销结算单' end ,
				/*BFullName=b1.Fullname ,
				EFullName=e.FullName,
				KFullName=ISNULL(Case b.billtype when 141 then '代销库' else K.FullName end,''),*/
                btypeid=b1.typeid,
			    etypeid=e.typeid,
			    E1FullName=e1.FullName,
			    ktypeid=Case b.Billtype when 141 then '10000' else K.typeid end,
				--UserCode='',
				--FullName='',
				--Unit1='',
                '' as ptypeid,
				Qty=0,
				Price=0,
				TaxPrice=0,
				Total=0,
				taxTotal=0,
				MaoLi=0,
				MaoLilu=0,
				CostTotal=0,
				JSTotal=0,
				SKTOtal=CASE b.Billtype when 45 then -b.TotalinMoney else b.TotalinMoney end,
				b.Comment,
				b.billType,
				b.dealbtypeid
			FROM #Billindex b
			--INNER JOIN #InoutStocktable i ON b.BillnumberID=i.BillnumberID
			LEFT JOIN Btype B1 ON   b1.TypeID=b.BtypeID
			LEFT JOIN Stock K ON b.KtypeID=K.TypeID
			LEFT JOIN Employee e ON b.EtypeID=e.TypeID
			LEFT JOIN Employee e1 ON b.checke=e1.TypeID
			WHERE  b.TotalinMoney<>0    AND e.TypeID = @ETypeID
			and b.Billtype<>160     AND (b.billtype not in(305,215) or (b.billtype in(305,215) and isnull(b.preferencemoney,0)<>0))
			UNION ALL
		SELECT 	
			b.BillnumberID,
			b.BillDate,
			b.BillCode,
			BillName=Case b.Billtype when 12 then '组合品销售出库单' when 46 then '组合品销售退货单' when 4 then '收款单' when 305 then '零售单' WHEN 215 THEN '零售退货单' when 11 then '销售出库单' when 45 then '销售退货单' when 160 then '销售换货单' when 141 then '委托代销结算单' end ,
			/*BFullName=b1.Fullname ,
			EFullName=e.FullName,
			KFullName=ISNULL(Case b.billtype when 141 then '代销库' else K.FullName end,''),*/
            btypeid=b1.typeid,
		    etypeid=e.typeid,
		    E1FullName=e1.FullName,
		    ktypeid=Case b.Billtype when 141 then '10000' else K.typeid end,
			--UserCode='',
			--FullName='',
			--Unit1='',
            '' as ptypeid,
			Qty=0,
			Price=0,
			TaxPrice=0,
			Total=0,
			taxTotal=0,
			MaoLi=0,
			MaoLilu=0,
			CostTotal=0,
			JSTotal=0,
			SKTOtal=CASE  WHEN b.billtype=215 AND  isnull(b.preferencemoney,0)=0 THEN -i.TaxTotal  
							WHEN b.billtype=305 AND  isnull(b.preferencemoney,0)=0 THEN i.TaxTotal 
						ELSE b.TotalinMoney end,
			b.Comment,
			b.billType,
			B.dealbtypeid
		FROM #Billindex b
		INNER JOIN #InoutStocktable i ON b.BillnumberID=i.BillnumberID
		LEFT JOIN Btype B1  ON   b1.TypeID=b.BtypeID
		LEFT JOIN Stock K  ON b.KtypeID=K.TypeID
		LEFT JOIN Employee e ON b.EtypeID=e.TypeID
		LEFT JOIN Employee e1  ON b.checke=e1.TypeID
		WHERE b.TotalinMoney<>0	 and b.billtype in(215,305) and isnull(b.preferencemoney,0)=0
		UNION ALL
			SELECT 	
				b.BillnumberID,
				b.BillDate,
				b.BillCode,
				BillName='销售换货单',
				/*BFullName=b1.Fullname ,
				EFullName=e.FullName,
				KFullName=ISNULL(K.FullName,''),*/
                btypeid=b1.typeid,
                etypeid=e.typeid,
                E1FullName=e1.FullName,
                ktypeid=K.typeid ,
				--UserCode='',
				--FullName='',
				--Unit1='',
                '' as ptypeid,
				Qty=0,
				Price=0,
				TaxPrice=0,
				Total=0,
				taxTotal=0,
				MaoLi=0,
				MaoLilu=0,
				CostTotal=0,
				JSTotal=0,
				SKTOtal=b.TotalinMoney,
				b.Comment,
				b.billType,
				b.dealbtypeid
			FROM #Billindex b
			LEFT JOIN Btype B1
			ON   b1.TypeID=b.BtypeID
			LEFT JOIN Stock K
			ON b.KtypeID2=K.TypeID
			LEFT JOIN Employee e
			ON b.EtypeID=e.TypeID
			LEFT JOIN Employee e1
			ON b.checke=e1.TypeID
			WHERE b.Billtype=160  AND b.TotalinMoney<>0   AND e.TypeID = @ETypeID
		) X 
		--WHERE X.SKTotal<>0
		ORDER BY X.BillDate,X.BillCode
	END
	RETURN 
END 

--DELETE FROM #InoutStocktable WHERE PtypeID NOT IN (SELECT TypeID FROM #Ptype1)
--更新按商品结算的结算金额
UPDATE #InoutStocktable
SET JSTotal=b.CompleteGoodTotal 
FROM #InoutStocktable a
INNER JOIN
	CompleteGoodTotal b
ON a.BillnumberID=b.GoodsBillID AND a.[ID]=b.BillID

--SELECT * FROM #InoutStocktable

--除去按商品结算单据，已结算完成单据的结算金额=价税合计
UPDATE #InoutStocktable SET JSTotal=TaxTotal 
WHERE 
		BillnumberID in (
			Select BillnumberID FROM #Billindex WHERE TotalMoney>=0 AND TotalinMoney+CompleteTotal>=TotalMoney
			UNION ALL
			Select BillnumberID FROM #Billindex WHERE TotalMoney<=0 AND TotalinMoney+CompleteTotal<=TotalMoney
			)
		AND BillnumberID not in (Select GoodsBillID FROM CompleteGoodTotal)




SELECT 	
	b.BillnumberID,
	b.BillDate,
	b.BillCode,
	b.Billtype,
	BillName=Case b.Billtype  when 12 then '组合品销售出库单' when 46 then '组合品销售退货单' when 305 then '零售单' WHEN 215 THEN '零售退货单' when 11 then '销售出库单' when 45 then '销售退货单' when 160 then '销售换货单' when 141 then '委托代销结算单' end ,
	/*BFullName=b1.Fullname ,
	EFullName=e.FullName,
	KFullName=Case b.Billtype when 141 then '代销仓库' else K.FullName end,*/
    btypeid=b1.typeid,
    etypeid=e.typeid,
    E1FullName=e1.FullName,
    ktypeid=Case b.Billtype when 141 then '10000' else K.typeid end,
    ptypeid=p.typeid,
--	P.UserCode,
--	P.FullName,
--	P.Unit1,
	Qty=a.Qty,
	a.Price,
	a.TaxPrice,
	a.Total,
	a.TaxTotal,

	a.MaoLi,
	MaoLilu=100*case when ISNULL(a.Total,0) =0 then 0 else a.MaoLi/a.Total end,
	a.CostTotal,
	a.JSTotal,
	SKTOtal=0,-- 明细到商品，收款金额都为0
	b.Comment,
	b.dealbtypeid
FROM #Billindex b
INNER JOIN 
	#InoutStocktable a
ON a.BillnumberID=b.BillnumberID
LEFT JOIN Btype B1
ON   b1.TypeID=b.BtypeID
LEFT JOIN Stock K
ON a.KtypeID=K.TypeID
LEFT JOIN Employee e
ON b.EtypeID=e.TypeID
LEFT JOIN Employee e1
ON b.checke=e1.TypeID
LEFT JOIN Ptype P
ON a.PtypeID=P.TypeID
ORDER BY b.BillDate,b.BillCode

DROP TABLE #InoutStockTable
DROP TABLE #Billindex

DROP TABLE #Ptype1
DROP TABLE #Btype
DROP TABLE #Etype
DROP TABLE #Dtype
RETURN 0

SET QUOTED_IDENTIFIER OFF 





































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeLiftPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeLiftPtype]
GO









CREATE                                          PROCEDURE  Web_EmployeeLiftPtype  
(
	@OperatorID		varchar(50),	--  1、操作员 ID（作权限范围检查用）
	@StartDate		varchar(30),	--  2、查询起始时间
	@ENDDate		varchar(30),	--  3、查询结束时间
	@PTypeID		varchar(1550),	--  4、商品ID
	@BTypeID		varchar(1550),	--  5、客户ID
	@ETypeID		varchar(50),	--  6、职员ID
	@DTypeID		varchar(1550),	--  7、部门ID
	@Billtype      varchar(100)=''    --  8、单据
)
--@encode$--
AS
SET NOCOUNT  ON
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
SET ARITHIGNORE ON
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), 
@MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome 
VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid 
OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense 
OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------


CREATE TABLE #Ptype1 (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))


IF @PTypeID =''
	INSERT INTO #Ptype1(typeid) 
	 select typeid from ptype where Typeid in (select typeid from  F_GetManDetailPType(@OperatorID))and iscombinationproduct=0
	--select typeid from F_GetManDetailPType(@OperatorID)
ELSE
	INSERT INTO #Ptype1(typeid) 
	select typeid FROM Ptype WHERE Typeid in 
	(	
		select a.typeid from F_GetManPTypeAll(@OperatorID) a,
		(select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a
	)and iscombinationproduct=0
	--select a.typeid from F_GetManDetailPType(@OperatorID) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a


IF @BtypeID =''
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @ETypeID=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@EtypeID,',')) b where left(a.typeid,len(b.a))=b.a
/*
IF @DtypeID=''
BEGIN
	INSERT INTO #Dtype select typeid from DepartMent where Sonnum =0 
	INSERT INTO #Dtype SELECT ''
END
ELSE
	INSERT INTO #Dtype select typeid from department a ,(select * from  dbo.f_split(@DtypeID,',')) b where left(a.typeid,len(b.a))=b.a
*/
IF @DTypeID=''
	INSERT INTO #dtype SELECT typeid FROM dbo.F_GetManDetailDType(@OperatorID);
ELSE
	INSERT INTO #dtype SELECT a.typeid FROM dbo.F_GetManDetailDType(@OperatorID)a,(SELECT * FROM f_split(@DTypeID,',')) b WHERE left(a.typeid,len(b.a))=b.a



IF @PTypeID='00000'
	SET @PTypeID=''
IF @BTypeID='00000'
	SET @BTypeID=''
IF @DTypeID='00000'
	SET @DTypeID=''
IF @MEtypeID=''
	SET @MEtypeID='00001'
IF @Billtype=''
	SET @Billtype='11,45,305,215,141,160,4,12,46'
CREATE TABLE [dbo].[#Billtype] (
	[Billtype] varchar(200)
)
INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@Billtype,',')

DECLARE @SQL_WHERE varchar(4000)
DECLARE @SQL_WHERE_Billindex varchar(4000)
DECLARE @SQL varchar(8000)
IF @PTypeID='00000'
	SET @PTypeID=''
SET @SQL_WHERE=' AND 
			b.BillDate>='+char(39)+@StartDate+char(39)+'
			AND b.BillDate<='+char(39)+@EndDate+char(39)


CREATE TABLE #Billindex (
	BillnumberID  int,
	BillDate      Datetime,
	Billtype      int,
	EtypeID 	  varchar(50),
	Qty            NUMERIC(24, 10) ,
	Tax            NUMERIC(24, 10) ,
	TotalMoney     NUMERIC(24, 10) ,
	TotalinMoney   NUMERIC(24, 10) ,
	CompleteTotal  NUMERIC(24, 10) ,
	AtypeID       varchar(50)  ,
	preferencemoney	   NUMERIC(24, 10)
)
SET @SQL='	INSERT INTO #Billindex
			SELECT b.BillnumberID,b.BillDate,b.Billtype,b.EtypeID,b.TotalQty,b.Tax,b.TotalMoney,b.TotalinMoney,b.CompleteTotal,b.AtypeID,b.preferencemoney
			FROM Billindex b 
'
IF @ETypeID<>'' OR @METypeID=-99999 SET @SQL=@SQL+' INNER JOIN #EType e ON b.etypeid=e.typeid '+CHAR(13)

IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON b.dtypeid=d.typeid '+CHAR(13)

IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON b.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON b.BillType=t.BillType 
			WHERE b.redword=0 AND draft=0 '+@SQL_WHERE
--PRINT @SQL
EXEC(@SQL)

-- 缩小InoutStocktable，因为涉及收款金额时不涉及到具体商品，所以没有对商品进行过滤
CREATE TABLE #InoutStocktable (
	BillnumberID  int,
	billtype		INT,
	BillDate      datetime,
	[ID]		  int,	
	EtypeID       varchar(50),
	PtypeID       varchar(50),
	Qty            NUMERIC(24, 10) ,
	Total          NUMERIC(24, 10) ,
	CostTotal      NUMERIC(24, 10) ,
	TaxTotal       NUMERIC(24, 10) ,
	MaoLi          NUMERIC(24, 10) ,
	JSTAotal        NUMERIC(24, 10) , -- 结算金额
	TCRate         NUMERIC(24, 10) 

)
SET @SQL='INSERT INTO #InoutStocktable
		SELECT  b.BillnumberID,	 
				a.billtype,
				b.billdate,
				a.ID,
				a.EtypeID,
				a.PtypeID,
				-a.Qty,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				NULL,0
		FROM InoutStockTable a
		INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID 
'

IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #PType1 p ON a.PtypeID=p.typeid '
SET @SQL+= '  where   (b.billtype not in(305,215) or (b.billtype in(305,215) and isnull(b.preferencemoney,0)<>0)	)'
EXEC(@SQL)


--零售单且无抹零金额按表体统计 
SET @SQL='INSERT INTO #InoutStocktable
		 	SELECT  b.BillnumberID,
		 		a.billtype,
				b.billdate,
				a.ID,
				r.EtypeID,
				a.PtypeID,
				-a.Qty,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				NULL,0
		FROM InoutStockTable a
		INNER JOIN retailbill R ON a.billnumberid=r.billnumberid AND a.id=r.id
		inner join billindex b on a.billnumberid=b.billnumberid
		
'
IF @ETypeID<>'' OR @METypeID=-99999 SET @SQL=@SQL+' INNER JOIN #EType e ON r.etypeid=e.typeid '+CHAR(13)
IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'   INNER JOIN #PType1 p ON a.PtypeID=p.typeid '
IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON a.dtypeid=d.typeid '+CHAR(13)
IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON a.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON a.BillType=t.BillType	  '

 SET @SQL+=' where  b.billtype in(305) and isnull(b.preferencemoney,0)=0 and  b.redword=0 AND b.draft=0 '+@SQL_WHERE
EXEC(@SQL) 


--零售退货单且无抹零金额按表体统计 
SET @SQL='INSERT INTO #InoutStocktable
		  	SELECT  b.BillnumberID,
		 		a.billtype,
				b.billdate,
				a.ID,
				r.EtypeID,
				a.PtypeID,
				-a.Qty,
				-a.Total,
				-a.CostTotal,
				-a.TaxTotal as TaxTotal,
				-(a.Total-a.CostTotal) as MaoLi,
				NULL,0
		FROM InoutStockTable a
		INNER JOIN RetailBackBill R ON a.billnumberid=r.billnumberid AND a.id=r.id
		inner join billindex b on a.billnumberid=b.billnumberid

		
'
IF @PTypeID<>'' OR @MPTypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #PType1 p ON a.PtypeID=p.typeid '
 IF @ETypeID<>'' OR @METypeID=-99999 SET @SQL=@SQL+'  INNER JOIN #EType e ON r.etypeid=e.typeid '+CHAR(13)
  IF @DTypeID<>'' OR @MDTypeID=-99999 SET @SQL=@SQL+' INNER JOIN #DType d ON a.dtypeid=d.typeid '+CHAR(13)
IF @BTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 SET @SQL=@SQL+' INNER JOIN #BType bt ON a.btypeid=bt.typeid '+CHAR(13)

SET @SQL=@SQL+'	INNER JOIN #Billtype t ON a.BillType=t.BillType	  '
 SET @SQL+=' where  b.billtype in(215) and isnull(b.preferencemoney,0)=0 and  b.redword=0 AND b.draft=0 '+@SQL_WHERE
EXEC(@SQL) 

CREATE TABLE #Ptype (
	TypeID    varchar(50),
	UserCode  varchar(26),
	FullName  varchar(66),
	Unit1     varchar(8),
	Standard  varchar(40),
	Type	  varchar(20),	
	Area      varchar(30),
	Qty        NUMERIC(24, 10) ,
	Total      NUMERIC(24, 10) ,
	CostTotal  NUMERIC(24, 10) ,
 	TaxTotal   NUMERIC(24, 10) ,
	MaoLi      NUMERIC(24, 10) ,
	JSTAotal    NUMERIC(24, 10) ,
	SKTBotal    NUMERIC(24, 10) ,
	LiftTotal  NUMERIC(24, 10) ,
	SubStr    varchar(2000)
)


SET @SQL='INSERT INTO #Ptype(TypeID,UserCode,FullName,Unit1,Standard,Type,Area,Qty,Total,CostTotal,TaxTotal,MaoLi,JSTAotal,SKTBotal,LiftTotal,SubStr)
		SELECT TypeID,UserCode,FullName,Unit1,Standard,Type,Area,0,0,0,0,0,0,0,0,'''' FROM Ptype 
		WHERE Sonnum=0 
		AND TypeID IN (Select typeid from #Ptype1)
		AND TypeID IN (SELECT PtypeID FROM #InoutStockTable)'
--PRINT @SQL
EXEC(@SQL)



--更新职员提成比例
UPDATE #InoutStocktable
	SET TCRate=e.TichengRate/100
FROM #InoutStocktable a
INNER JOIN 
	Employee e
ON a.EtypeID=e.typeid

--更新按商品结算的结算金额
UPDATE #InoutStocktable
SET JSTAotal=b.CompleteGoodTotal 
FROM #InoutStocktable a
INNER JOIN
	CompleteGoodTotal b
ON a.BillnumberID=b.GoodsBillID AND a.[ID]=b.BillID

--SELECT * FROM #InoutStocktable

--除去按商品结算单据，已结算完成单据的结算金额=价税合计
UPDATE #InoutStocktable SET JSTAotal=TaxTotal 
WHERE 
		BillnumberID in (
			Select BillnumberID FROM #Billindex WHERE TotalMoney>=0 AND TotalinMoney+CompleteTotal>=TotalMoney
			UNION ALL
			Select BillnumberID FROM #Billindex WHERE TotalMoney<=0 AND TotalinMoney+CompleteTotal<=TotalMoney
			
		)
		AND BillnumberID not in (Select GoodsBillID FROM CompleteGoodTotal)



-- 更新 销售数量，销售金额，成本金额，价税合计，毛利,结算金额
UPDATE #Ptype SET 
	Qty=a.Qty,Total=a.Total,CostTotal=a.CostTotal,TaxTotal=a.TaxTotal,MaoLi=a.MaoLi,JSTAotal=a.JSTAotal,SKTBotal=a.SKTBotal
FROM #Ptype p
INNER JOIN
	(SELECT 
		PtypeID,
		SUM(Qty) as Qty,
		SUM(Total) as Total,
		SUM(CostTotal) as CostTotal,
		SUM(TaxTotal) as TaxTotal,
		SUM(MaoLi) as MaoLi,
		SUM(ISNULL(JSTAotal,0)) as JSTAotal,
		SUM(CASE  WHEN Billtype=305 then TaxTotal  when billtype=215 then -TaxTotal  else 0 end) as SKTBotal 
	FROM
		#InoutStocktable
	WHERE PtypeID IN (Select typeid from #Ptype1)
	GROUP BY PtypeID
) a
ON p.TypeID=a.PtypeID


-- ======BEGIN  对提成规则进行筛选   ==============================================================================================
DECLARE @NOW varchar(30)
SET @NOW=Convert(varchar(10),Year(GetDate()))+'-'+Convert(varchar(10),Month(GetDate()))+'-'+Convert(varchar(10),Day(GetDate()))

CREATE TABLE #TCRule(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	Flag         int,
	BillnumberIDT int,
	RowT		  int,
	ConstFlag    int     -- 1 公式中含有常量
)



INSERT INTO #TCRule (EtypeID,PtypeID,StartDate,EndDate,Sub,BillnumberIDT,RowT,ConstFlag)
SELECT b.EtypeID,b.PtypeID,a.StartDate,a.EndDate,
replace(replace(replace(replace(replace(replace(replace(replace(replace(b.Sub,'×','*'),'÷','/'),'销售数量','Qty'),'销售金额','Total'),'价税合计','TaxTotal'),'收款金额','SKTBotal'),'结算金额','JSTAotal'),'职员提成比例','TCRate'),'销售毛利','MaoLi'),
b.BillnumberID,b.Row,b.ConstFlag
FROM	TCBillindex a,
		TCBill b,#Etype E 
WHERE	a.BillnumberID=b.BillnumberID
		AND a.StartDate<=@NOW --(审核未执行，未审核除外)
		AND ((a.StartDate<= @StartDate AND a.EndDate>=@StartDate) OR (a.StartDate>= @StartDate AND a.StartDate<=@enddate)   )
		AND a.EtypeID<>''
		AND 
			(
			b.EtypeID='00000'  
			OR 	LEFT(b.EtypeID,LEN(E.TypeID))=E.TypeID
			OR  LEFT(E.TypeID,LEN(b.EtypeID))=b.EtypeID
			)
		AND a.IsUse = 1
ORDER BY a.BillDate,a.BillnumberID,b.Row


UPDATE #TCRule SET Row=[ID], Flag=0
UPDATE #TCRule SET Flag=1 WHERE Sub LIKE '%SKTBotal%'



DECLARE @RowTemp INT
DECLARE @EtypeIDTemp varchar(50)
DECLARE @PtypeIDTemp varchar(50)
DECLARE @StartDateTemp Datetime
DECLARE @EndDateTemp Datetime
DECLARE @FlagTemp int

CREATE TABLE #DELTCRule
(
	Row int
)



-- BEGIN 删除 职员，商品，起始日期，截止日期都重复且行数小于当前行的记录的提成规则
DECLARE  TCRuleCursor CURSOR FOR 
	SELECT Row,EtypeID,PtypeID,StartDate,EndDate,Flag FROM #TCRule ORDER BY Row DESC
OPEN TCRuleCursor
FETCH NEXT FROM TCRuleCursor  INTO @RowTemp,@EtypeIDTemp,@PtypeIDTemp,@StartDateTemp,@EndDateTemp,@FlagTemp
WHILE @@FETCH_STATUS=0
BEGIN
	INSERT #DELTCRule(ROW) SELECT Row FROM #TCRule WHERE  Row<@RowTemp AND EtypeID=@EtypeIDTemp AND PtypeID=@PtypeIDTemp AND StartDate=@StartDateTemp AND EndDate=@EndDateTemp AND Flag=@FlagTemp
	FETCH NEXT FROM TCRuleCursor INTO @RowTemp,@EtypeIDTemp,@PtypeIDTemp,@StartDateTemp,@EndDateTemp,@FlagTemp
END
CLOSE TCRuleCursor
DEALLOCATE TCRuleCursor
DELETE FROM #TCRule WHERE ROW IN (SELECT ROW FROM #DELTCRule)
DELETE FROM #DELTCRule
-- END 删除 职员，商品，起始日期，截止日期都重复且行数小于当前行的记录的提成规则

DECLARE @BillnumberID numeric(18,0)
DECLARE @BillDate     datetime
DECLARE @Qty           NUMERIC(24, 10) 
DECLARE @Total         NUMERIC(24, 10) 
DECLARE @TaxTotal      NUMERIC(24, 10) 
DECLARE @MaoLi         NUMERIC(24, 10) 
DECLARE @SKTBotal       NUMERIC(24, 10) 
DECLARE @JSTAotal       NUMERIC(24, 10) 
DECLARE @TCRate        NUMERIC(24, 10) 
DECLARE @LiftTotal     NUMERIC(24, 10) 
DECLARE @Sub          varchar(2000)

SELECT @TCRate=TichengRate/100 FROM Employee WHERE TypeID=@EtypeID


-- 含有 收款金额 字段的提成规则
CREATE TABLE #TCRuleSK(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	BillnumberIDT int,
	RowT	     int,
	ConstFlag    int     -- 1 公式中含有常量
)
--全部职员换成 00001
UPDATE #TCRule SET EtypeID='00001' WHERE EtypeID='00000'

INSERT INTO #TCRuleSK
select e.TypeID,a.PtypeID,a.StartDate,a.EndDate,a.Sub,a.Row,BillnumberIDT,RowT,a.ConstFlag 
from #TCRule a 
inner join Employee e ON a.EtypeID=LEFT(e.typeid,LEN(a.EtypeID))
WHERE a.Flag=1 AND e.sonnum=0 AND e.UserCode<>'admin'
AND e.TypeID=@EtypeID
Order by a.Row


UPDATE #TCRuleSK SET Row=[ID]

-- BEGIN 含有收款金额 删除 职员，起始日期，截止日期都重复且行数小于当前行的记录的提成规则
DECLARE  TCRuleCursor CURSOR FOR 
	SELECT Row,EtypeID,StartDate,EndDate FROM #TCRuleSK ORDER BY Row DESC
OPEN TCRuleCursor
FETCH NEXT FROM TCRuleCursor  INTO @RowTemp,@EtypeIDTemp,@StartDateTemp,@EndDateTemp
WHILE @@FETCH_STATUS=0
BEGIN
	INSERT #DELTCRule(ROW) SELECT Row FROM #TCRuleSK WHERE  Row<@RowTemp AND EtypeID=@EtypeIDTemp  AND StartDate=@StartDateTemp AND EndDate=@EndDateTemp
	FETCH NEXT FROM TCRuleCursor INTO @RowTemp,@EtypeIDTemp,@StartDateTemp,@EndDateTemp
END
CLOSE TCRuleCursor
DEALLOCATE TCRuleCursor
DELETE FROM #TCRuleSK WHERE ROW IN (SELECT ROW FROM #DELTCRule)
-- END 含有收款金额 删除 职员，商品，起始日期，截止日期都重复且行数小于当前行的记录的提成规则

--select * from #TCRuleSK
DECLARE @StartDate2 datetime
DECLARE @EndDate2 datetime
DECLARE @MinRow  int
DECLARE @MaxRow  int
SET @MinRow=0
SET @MaxRow=0

DECLARE @BillnumberIDT int
DECLARE @RowT int
-- 含有 收款金额 字段的提成规则
CREATE TABLE #TCRuleSK2(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID       varchar(50),
	StartDate     datetime,
	EndDate       datetime,
	Sub           varchar(200),
	Row 		  int,
	BillnumberIDT int,
	RowT          int,
	ConstFlag    int     -- 1 公式中含有常量
)

DECLARE @ConstFlag int
SET @ConstFlag=0
DECLARE @StartDateMin datetime
DECLARE @EndDateMax datetime
DECLARE  TCRuleCursor CURSOR FOR 
	SELECT Row,EtypeID,StartDate,EndDate,Sub,BillnumberIDT,RowT,ConstFlag FROM #TCRuleSK ORDER BY Row DESC
OPEN TCRuleCursor
FETCH NEXT FROM TCRuleCursor  INTO @RowTemp,@EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@BillnumberIDT,@RowT,@ConstFlag
WHILE @@FETCH_STATUS=0
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM #TCRuleSK2 WHERE EtypeID=@EtypeIDTemp)
	BEGIN
		INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
		SELECT @EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
	END
	ELSE
	BEGIN
		SELECT TOP 1 @StartDateMin=StartDate FROM #TCRuleSK2 WHERE EtypeID=@EtypeIDTemp   ORDER BY StartDate 
		SELECT TOP 1 @EndDateMax=EndDate FROM #TCRuleSK2 WHERE EtypeID=@EtypeIDTemp   ORDER BY EndDate DESC
		IF @StartDateTemp<@StartDateMin
		BEGIN
			IF @EndDateTemp<@StartDateMin
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
				SELECT @EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
			IF @EndDateTemp>=@StartDateMin AND @EndDateTemp<=@EndDateMax
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
				SELECT @EtypeIDTemp,@StartDateTemp,DATEADD(d,-1,@StartDateMin),@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag

			IF @EndDateTemp>@EndDateMax
			BEGIN
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
				SELECT @EtypeIDTemp,@StartDateTemp,DATEADD(d,-1,@StartDateMin),@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
				
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
				SELECT @EtypeIDTemp,DATEADD(d,1,@EndDateMax),@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
			END
		END	

		IF @StartDateMin<=@StartDateTemp AND @StartDateTemp<=@EndDateMax
		BEGIN
			IF @EndDateTemp>@EndDateMax
				INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
				SELECT @EtypeIDTemp,DATEADD(d,1,@EndDateMax),@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
		END				
		IF @StartDateTemp>@EndDateMax
		BEGIN
			INSERT  INTO #TCRuleSK2 (EtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
			SELECT @EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
		END
	END
	FETCH NEXT FROM TCRuleCursor INTO @RowTemp,@EtypeIDTemp,@StartDateTemp,@EndDateTemp,@Sub,@BillnumberIDT,@RowT,@ConstFlag
END
CLOSE TCRuleCursor
DEALLOCATE TCRuleCursor

-- ======END  对提成规则进行筛选    ===============================================================================================

--SELECT * FROM #TCRuleSK2

DECLARE @SubStr varchar(2000)
SET @SubStr=''

CREATE TABLE #LiftTotal(Total  NUMERIC(24, 10) )

DECLARE @PtypeID2 varchar(50)
-- 更新关于收款金额的提成



CREATE TABLE #TEMP(Qty  NUMERIC(24, 10) ,Total  NUMERIC(24, 10) ,TaxTotal  NUMERIC(24, 10) ,MaoLi  NUMERIC(24, 10) ,JSTAotal  NUMERIC(24, 10) ,SKTBotal  NUMERIC(24, 10) ,TCRate  NUMERIC(24, 10) )
DECLARE TT CURSOR  FOR 
SELECT EtypeID,StartDate,EndDate,Sub,BillnumberIDT,RowT,ConstFlag FROM #TCRuleSK2
FOR UPDATE
OPEN TT
FETCH NEXT FROM TT INTO @EtypeID,@StartDateTemp,@EndDateTemp,@Sub,@BillnumberIDT,@RowT,@ConstFlag
WHILE @@FETCH_STATUS=0
BEGIN
	SET @SKTBotal=NULL
	IF @Sub<>''
	BEGIN
		-- 把零售和零售退后分开
		SELECT @SKTBotal=SUM(case  WHEN Billtype IN(45,46) then -TotalinMoney else TotalinMoney end) 
		FROM #Billindex WHERE billtype NOT IN(305,215) AND  (Billtype=4 OR AtypeID<>'') AND EtypeID=@EtypeID AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
		
		SELECT @SKTBotal= ISNULL(@SKTBotal,0)+ ISNULL(SUM(case  WHEN Billtype IN(215) then -TaxTotal else TaxTotal end),0) 
		FROM #inoutstocktable WHERE billtype  IN(305,215) AND EtypeID=@EtypeID AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
		
		
		INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
		SELECT ISNULL(SUM(Qty),0) as Qty,ISNULL(SUM(Total),0) as Total,ISNULL(SUM(TaxTotal),0) as TaxTotal,ISNULL(SUM(MaoLi),0) as MaoLi,ISNULL(SUM(ISNULL(JSTAotal,0)),0) as JSTAotal,@SKTBotal,TCRate
		FROM #InoutStocktable WHERE EtypeID=@EtypeID AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
							--AND PtypeID LIKE @PtypeID+'%' AND  PtypeID  LIKE @chvMPTypeID+'%' --前面已经过滤了
		GROUP BY TCRate

		 
		--SELECT * FROM #TEMP
		IF @ConstFlag=1  --含有计算常量
		BEGIN
			IF NOT EXISTS(SELECT top 1 1 FROM #TEMP)
			BEGIN
				IF @SKTBotal IS NOT NULL
				BEGIN
					INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
					SELECT 0,0,0,0,0,@SKTBotal,@TCRate FROM Employee WHERE TypeID=@EtypeID
				END
			END
		
			IF EXISTS(SELECT top 1 1 FROM #TEMP)
			BEGIN
				IF @SKTBotal IS NULL 
				BEGIN
					IF charindex('JSTAotal',@Sub)>0
					BEGIN
						IF charindex('Qty',@Sub)>0 OR charindex('Total',@Sub)>0 OR charindex('TaxTotal',@Sub)>0 OR charindex('MaoLi',@Sub)>0 
						BEGIN
							UPDATE #TEMP SET SKTBotal=0 WHERE SKTBotal IS NULL	
							UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
						END
						ELSE	
						BEGIN
							IF EXISTS (SELECT TOP 1 1 FROM #InoutStocktable WHERE (JSTAotal IS NOT NULL) AND EtypeID=@EtypeID AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp)
							BEGIN
								UPDATE #TEMP SET SKTBotal=0 WHERE SKTBotal IS NULL	
								UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
							END
							ELSE
								DELETE FROM  #TEMP  WHERE SKTBotal IS NULL	
						END
					END				
					ELSE
						IF charindex('Qty',@Sub)>0 OR charindex('Total',@Sub)>0 OR charindex('TaxTotal',@Sub)>0 OR charindex('MaoLi',@Sub)>0 
						BEGIN
							UPDATE #TEMP SET SKTBotal=0 WHERE SKTBotal IS NULL	
							UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
						END
						ELSE
							DELETE FROM  #TEMP  WHERE SKTBotal IS NULL	
				END 
				ELSE
				BEGIN		--有收款金额
					UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
				END
			END
		END
		IF (@SKTBotal IS NOT NULL) AND (NOT EXISTS(SELECT top 1 1 FROM #TEMP)) 
		BEGIN
			INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
			SELECT 0,0,0,0,0,@SKTBotal,@TCRate FROM Employee WHERE TypeID=@EtypeID
		END	
		IF EXISTS(SELECT TOP 1 1 FROM #TEMP)
		BEGIN
			UPDATE #TEMP SET SKTBotal=0 WHERE SKTBotal IS NULL	
			UPDATE #TEMP SET JSTAotal=0 WHERE JSTAotal IS NULL	
			EXEC('INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP ')
			DELETE FROM #TEMP
			IF @SubStr=''
				SET @SubStr=Convert(varchar(10),@BillnumberIDT)+'@'+Convert(varchar(10),@RowT)
			ELSE
				SET @SubStr=@SubStr+','+Convert(varchar(10),@BillnumberIDT)+'@'+Convert(varchar(10),@RowT)
		END
	END
	FETCH NEXT FROM TT INTO @EtypeID,@StartDateTemp,@EndDateTemp,@Sub,@BillnumberIDT,@RowT,@ConstFlag
	SET @ConstFlag=0
END
CLOSE TT
DEALLOCATE TT
TRUNCATE TABLE #TEMP


SET @LiftTotal=0
SELECT @LiftTotal=ISNULL(SUM(ISNULL(Total,0)),0) FROM #LiftTotal
DELETE FROM #LiftTotal

SELECT @SKTBotal=ISNULL(SUM(case WHEN Billtype IN(45,46) then -TotalinMoney else TotalinMoney end),0) FROM #Billindex   WHERE billtype NOT IN (215,305)
SELECT @SKTBotal=ISNULL(@SKTBotal,0)+ISNULL(SUM(case WHEN Billtype IN(215) then -TaxTotal else TaxTotal end),0) FROM #InoutStocktable   WHERE billtype  IN (215,305)


INSERT INTO #Ptype(TypeID,UserCode,FullName,Unit1,Standard,Type,Area,Qty,Total,CostTotal,TaxTotal,MaoLi,JSTAotal,SKTBotal,LiftTotal,SubStr)
SELECT 'TCDSP','','直接收款','','','','',0,0,0,0,0,0,@SKTBotal,@LiftTotal,@SubStr
SET @SubStr=''



DECLARE @ID int


CREATE TABLE #TCRuleJS(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	BillnumberIDT int,
	RowT          int,
	ConstFlag	  int
)

-- 全部商品 00000 时，更新成 replace(PtypeID,'00000','')
INSERT INTO #TCRuleJS(EtypeID,PtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
SELECT T.EtypeID,case T.ptypeid when '00000' then '' else T.ptypeid end as ptypeid,T.StartDate,T.EndDate,T.Sub,T.Row,T.BillnumberIDT,T.RowT,T.ConstFlag FROM #TCRule T,
#Ptype1 P
WHERE 
	Flag=0 
	AND
	(
		T.PtypeID='00000'  
		OR 	LEFT(T.PtypeID,LEN(P.TypeID))=P.TypeID
		OR 	LEFT(P.TypeID,LEN(T.PTypeID))=T.PtypeID
	)



--SELECT * FROM #TCRuleJS
CREATE TABLE #TCRuleJSEND(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	BillnumberIDT int,
	RowT          int,
	ConstFlag     int
)

CREATE TABLE #TCRuleJSEND2(
	[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
	EtypeID      varchar(50),
	PtypeID      varchar(50),
	StartDate    datetime,
	EndDate      datetime,
	Sub          varchar(200),
	Row 		 int,
	BillnumberIDT int,
	RowT          int,
	ConstFlag     int
)

CREATE TABLE #Employee(
	TypeID varchar(50),
	UserCode varchar(26),
	FullName  varchar(66)
)	


--select * from #TCRuleJS

DECLARE @StartDateMin2 Datetime
DECLARE @EndDateMax2 Datetime
SET @PtypeID2=''
DECLARE PCurSor CURSOR  FOR 
SELECT TypeID FROM #Ptype WHERE TypeID<>'0'
FOR UPDATE
OPEN PCurSor
FETCH NEXT FROM PCurSor INTO @PtypeID2
WHILE @@FETCH_STATUS=0
BEGIN
	SET @SubStr=''

	INSERT INTO #TCRuleJSEND
	SELECT 
		@EtypeID as EtypeID	,P.TypeID as PtypeID,A.StartDate,A.EndDate,A.Sub,A.Row,A.BillnumberIDT,A.RowT,A.ConstFlag
	FROM 	#TCRuleJS A
	INNER JOIN #Ptype P ON   P.typeID LIKE A.PtypeID+'%' OR A.PtypeID=LEFT(P.typeid,LEN(a.PtypeID))
	WHERE  P.typeID=@PtypeID2
		  AND a.EtypeID=LEFT(@EtypeID,LEN(a.EtypeID))

	--BEGIN分解提成规则
	DECLARE  TCRuleCursor CURSOR FOR 
		SELECT Row,StartDate,EndDate,Sub,BillnumberIDT,RowT,ConstFlag FROM #TCRuleJSEND ORDER BY Row DESC
	OPEN TCRuleCursor
	FETCH NEXT FROM TCRuleCursor  INTO @RowTemp,@StartDateTemp,@EndDateTemp,@Sub,@BillnumberIDT,@RowT,@ConstFlag
	WHILE @@FETCH_STATUS=0
	BEGIN
		IF NOT EXISTS(SELECT * FROM #TCRuleJSEND2)
		BEGIN
			INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
			SELECT @EtypeID,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
		END
		ELSE
		BEGIN
			SELECT TOP 1 @StartDateMin2=StartDate FROM #TCRuleJSEND2  ORDER BY StartDate
			SELECT TOP 1 @EndDateMax2=EndDate FROM #TCRuleJSEND2  ORDER BY EndDate DESC

			IF @StartDateTemp<@StartDateMin2
			BEGIN
				IF @EndDateTemp<@StartDateMin2
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
					SELECT @EtypeID,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
				IF @EndDateTemp>=@StartDateMin2 AND @EndDateTemp<=@EndDateMax2
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
					SELECT @EtypeID,@PtypeID2,@StartDateTemp,DATEADD(d,-1,@StartDateMin2),@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag

				IF @EndDateTemp>@EndDateMax2
				BEGIN
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
					SELECT @EtypeID,@PtypeID2,@StartDateTemp,DATEADD(d,-1,@StartDateMin2),@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
					
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
					SELECT @EtypeID,@PtypeID2,DATEADD(d,1,@EndDateMax2),@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
				END
			END	
			IF @StartDateMin2<=@StartDateTemp AND @StartDateTemp<=@EndDateMax2
			BEGIN
				IF @EndDateTemp>@EndDateMax2
					INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
					SELECT @EtypeID,@PtypeID2,DATEADD(d,1,@EndDateMax2),@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
			END				
			IF @StartDateTemp>@EndDateMax2
			BEGIN
				INSERT  INTO #TCRuleJSEND2 (EtypeID,PtypeID,StartDate,EndDate,Sub,Row,BillnumberIDT,RowT,ConstFlag)
				SELECT @EtypeID,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@RowTemp,@BillnumberIDT,@RowT,@ConstFlag
			END
		END
		FETCH NEXT FROM TCRuleCursor INTO @RowTemp,@StartDateTemp,@EndDateTemp,@Sub,@BillnumberIDT,@RowT,@ConstFlag
	END

	--END 分解提成规则
	DECLARE UPCurSor CURSOR  FOR 
	SELECT EtypeID,PtypeID,StartDate,EndDate,Sub,BillnumberIDT,RowT,ConstFlag FROM #TCRuleJSEND2
	FOR UPDATE
	OPEN UPCurSor
	FETCH NEXT FROM UPCurSor INTO @EtypeID,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@BillnumberIDT,@RowT,@ConstFlag
	WHILE @@FETCH_STATUS=0
	BEGIN
		IF @Sub<>''
		BEGIN
			--含有计算常量且只含有结算金额字段
			IF @ConstFlag=1 AND charindex('JSTAotal',@Sub)>0 AND NOT(charindex('Qty',@Sub)>0 OR charindex('Total',@Sub)>0 OR charindex('TaxTotal',@Sub)>0 OR charindex('MaoLi',@Sub)>0 )
				INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
				SELECT ISNULL(SUM(Qty),0) as Qty,ISNULL(SUM(Total),0) as Total,ISNULL(SUM(TaxTotal),0) as TaxTotal,ISNULL(SUM(MaoLi),0) as MaoLi,ISNULL(SUM(JSTAotal),0) as JSTAotal,0,TCRate
				FROM #InoutStocktable WHERE  (JSTAotal IS NOT NULL) AND EtypeID=@EtypeID AND PtypeID=@PtypeID2 AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
				GROUP BY TCRate
			ELSE
				INSERT INTO #TEMP(Qty,Total,TaxTotal,MaoLi,JSTAotal,SKTBotal,TCRate)
				SELECT ISNULL(SUM(Qty),0) as Qty,ISNULL(SUM(Total),0) as Total,ISNULL(SUM(TaxTotal),0) as TaxTotal,ISNULL(SUM(MaoLi),0) as MaoLi,ISNULL(SUM(JSTAotal),0) as JSTAotal,0,TCRate
				FROM #InoutStocktable WHERE EtypeID=@EtypeID AND PtypeID=@PtypeID2 AND BillDate>=@StartDateTemp AND BillDate<=@EndDateTemp
				GROUP BY TCRate
			
			IF EXISTS(SELECT * FROM #TEMP)
			BEGIN
				EXEC('INSERT INTO #LiftTotal SELECT  '+@Sub+' FROM #TEMP ')
				SET @LiftTotal=0
				SELECT @LiftTotal=ISNULL(SUM(Convert( NUMERIC(24, 10) ,ISNULL(Total,0))),0) FROM #LiftTotal
				DELETE FROM #LiftTotal
				DELETE FROM #TEMP
				--PRINT @LiftTotal
				SET @SubStr=Convert(varchar(10),@BillnumberIDT)+'@'+Convert(varchar(10),@RowT)
					
			
				UPDATE	#Ptype
				SET		LiftTotal=LiftTotal+@LiftTotal,SubStr=SubStr+','+@SubStr
				WHERE TypeID=@PtypeID2
			END
			SET @SubStr=''
		END
		FETCH NEXT FROM UPCurSor INTO @EtypeID,@PtypeID2,@StartDateTemp,@EndDateTemp,@Sub,@BillnumberIDT,@RowT,@ConstFlag
	END
	CLOSE UPCurSor
	DEALLOCATE UPCurSor

	TRUNCATE TABLE #TCRuleJSEND
	TRUNCATE TABLE #TCRuleJSEND2
	CLOSE TCRuleCursor
	DEALLOCATE TCRuleCursor


	FETCH NEXT FROM PCurSor INTO @PtypeID2
END
CLOSE PCurSor
DEALLOCATE PCurSor


SELECT 	
	TypeID,
	UserCode,
	FullName,
	Unit1,
	Standard,
	Type,
	Area,
	Qty,
	Total,
	CostTotal,
	TaxTotal,
	MaoLi,
	ISNULL(JSTAotal,0) as JSTAotal,
	ISNULL(SKTBotal,0) as SKTBotal,
	Convert( NUMERIC(24, 10) ,LiftTotal) as LiftTotal,
	ISNULL(SubStr,'') as SubStr
FROM #Ptype 
WHERE TypeID='0' AND (ISNULL(SKTBotal,0)<>0 OR LiftTotal<>0)
--ORDER BY UserCode
UNION ALL
SELECT 	
	TypeID,
	UserCode,
	FullName,
	Unit1,
	Standard,
	Type,
	Area,
	Qty,
	Total,
	CostTotal,
	TaxTotal,
	MaoLi,	ISNULL(JSTAotal,0) as JSTAotal,
	ISNULL(SKTBotal,0) as SKTBotal,
	LiftTotal,
	ISNULL(SubStr,'') as SubStr
FROM #Ptype 
WHERE TypeID<>'0' AND
(	ISNULL(Qty,0)<>0 OR
	ISNULL(Total,0)<>0 OR 
	ISNULL(CostTotal,0)<>0 OR 
	ISNULL(TaxTotal,0)<>0 OR 
	ISNULL(MaoLi,0)<>0 OR 	ISNULL(JSTAotal,0)<>0 OR 
	ISNULL(SKTBotal,0)<>0 OR 
	ISNULL(LiftTotal,0)<>0 )
ORDER BY UserCode


DROP TABLE #InoutStockTable
DROP TABLE #Ptype
DROP TABLE #Billindex
DROP TABLE #TCRule
DROP TABLE #TCRuleJS
DROP TABLE #TCRuleSK
DROP TABLE #TCRuleSK2
DROP TABLE #LiftTotal

DROP TABLE #Btype
DROP TABLE #Etype
DROP TABLE #Dtype
RETURN 0

SET QUOTED_IDENTIFIER OFF 









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeLiftSub]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeLiftSub]
GO

CREATE               PROCEDURE  Web_EmployeeLiftSub  
(
	@SubStr varchar(2000)
)
--@encode$--
AS
SET NOCOUNT  ON
SET ANSI_WARNINGS OFF

DECLARE @SQL_WHERE varchar(2000)
DECLARE @i int
DECLARE @j int
DECLARE @BillnumberID varchar(20)
DECLARE @Row varchar(20)
DECLARE @TempSub varchar(1000)

SET @i=0 
SET @j=0 
SET @BillnumberID='0'
SET @Row='0'
SET @TempSub=''

--去掉开头的 ,
IF LEFT(@SubStr,1)=','
	SET @SubStr=RIGHT(@SubStr,LEN(@SubStr)-1)


SET @SQL_WHERE=''
SET @i=charindex(',',@SubStr)  -- 取得'，'的位置常量
WHILE @i>=1
BEGIN
	IF @SQL_WHERE=''
	BEGIN

		SET @TempSub= LEFT(@SubStr,@i-1)
		SET @BillnumberID=LEFT(@TempSub,charindex('@',@TempSub)-1)
		SET @Row=RIGHT(@TempSub,LEN(@TempSub)-charindex('@',@TempSub))

		SET @SQL_WHERE = ' (b.BillnumberID='+@BillnumberID+' AND a.Row='+@Row+')'
	END
	ELSE
	BEGIN
		SET @TempSub= LEFT(@SubStr,@i-1)
		SET @BillnumberID=LEFT(@TempSub,charindex('@',@TempSub)-1)
		SET @Row=RIGHT(@TempSub,LEN(@TempSub)-charindex('@',@TempSub))

		SET @SQL_WHERE = @SQL_WHERE+ ' OR (b.BillnumberID='+@BillnumberID+' AND a.Row='+@Row+')'
	END
	SET @SubStr=SUBSTRING(@SubStr,@i+1,len(@SubStr)-@i)
    SET @i=charindex(',',@SubStr)
END

IF @SubStr<>''
BEGIN
	IF @SQL_WHERE =''
	BEGIN
		SET @TempSub= @SubStr
		SET @BillnumberID=LEFT(@TempSub,charindex('@',@TempSub)-1)
		SET @Row=RIGHT(@TempSub,LEN(@TempSub)-charindex('@',@TempSub))

		SET @SQL_WHERE = ' (b.BillnumberID='+@BillnumberID+' AND a.Row='+@Row+')'
	END
	ELSE
		BEGIN
		SET @TempSub= @SubStr
		SET @BillnumberID=LEFT(@TempSub,charindex('@',@TempSub)-1)
		SET @Row=RIGHT(@TempSub,LEN(@TempSub)-charindex('@',@TempSub))

		SET @SQL_WHERE = @SQL_WHERE+ ' OR (b.BillnumberID='+@BillnumberID+' AND a.Row='+@Row+')'
	END
END

-- nothing
IF @SubStr=''
	SET @SQL_WHERE=' b.BillnumberID=0 '

IF @SQL_WHERE<>''
	SET @SQL_WHERE=' WHERE '+ @SQL_WHERE
SET @SQL_WHERE=@SQL_WHERE+ ' ORDER BY b.BillnumberID'

DECLARE @SQL varchar(8000)
SET @SQL='
	SELECT	b.BillnumberID,
			b.BillCode,
			b.StartDate,
			b.EndDate,
			a.PtypeID,
			a.EtypeID,			
			a.SubName,
			a.Sub
	FROM	TcBillindex b
	INNER JOIN TCBill a ON a.BillnumberID=b.BillnumberID
	LEFT JOIN Ptype P ON a.PtypeID=P.TypeID
	LEFT JOIN Employee e ON a.EtypeID=e.TypeID
'
IF @SQL_WHERE<>''
	SET @SQL=@SQL+ @SQL_WHERE
	
--PRINT @SQL
EXEC(@SQL)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EmployeeRule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_EmployeeRule]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


/*
作者：徐辉
时间：2011-04-11
功能：提成规则单查询

修改：黄清
时间：2012-02-02
描述：增加隐藏单据功能
*/



CREATE   PROCEDURE  Web_EmployeeRule  
(
	@OperatorID		VARCHAR(50),	--  1、操作员 ID（作权限范围检查用）
	@StartDate		VARCHAR(30),	--  2、查询起始时间
	@ENDDate		VARCHAR(30),	--  3、查询结束时间
	@BillStatus		CHAR(1),		--  4、单据状态
	@BillCode 		VARCHAR(200),   --  5、单据编号
	@PTypeID		VARCHAR(1550),	--  6、商品ID
	@ETypeIDZ		VARCHAR(1550),	--  7、制单人ID
	@ETypeIDA		VARCHAR(1550),	--  8、审核人ID
	@Comment		VARCHAR(256),
	@ifhidebill		CHAR(1) 		--是否隐藏单据，1.隐藏 0.不隐藏
)
--@encode$--
AS
SET NOCOUNT  ON
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID VARCHAR(50), @chvMBTypeID VARCHAR(50), @chvMBTypeID2 VARCHAR(50), @chvMETypeID VARCHAR(50), @chvMKTypeID VARCHAR(50), @chvMPTypeID VARCHAR(50), @chvMExpense VARCHAR(50), @chvMIncome VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23 @OperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------

CREATE TABLE #Ptype (TypeID VARCHAR(50),UserCode VARCHAR(500),FullName VARCHAR(500))
CREATE TABLE #Etype (TypeID VARCHAR(50),UserCode VARCHAR(500),FullName VARCHAR(500)) -- 制单人
CREATE TABLE #Etype1 (TypeID VARCHAR(50),UserCode VARCHAR(500),FullName VARCHAR(500))-- 审核人 



IF @PTypeID =''
	INSERT INTO #Ptype(typeid,UserCode,FullName) 
	select typeid,UserCode,FullName FROM Ptype WHERE Typeid in (select typeid from F_GetManPTypeAll(@OperatorId)) and iscombinationproduct=0
ELSE
	INSERT INTO #Ptype(typeid,UserCode,FullName) 
	select typeid,UserCode,FullName FROM Ptype WHERE Typeid in 
	(	
		select a.typeid from F_GetManPTypeAll(@OperatorID) a,
		(select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a
	)and iscombinationproduct=0

IF EXISTS(select * from loginuser where mangerPtypeid='00000' and etypeid =@OperatorID) -- 拥有全部商品权限，才能添加 ‘全部商品’
	INSERT INTO #Ptype(typeid,UserCode,FullName) SELECT '00000','0','全部商品'

IF @ETypeIDZ =''
BEGIN
	INSERT INTO #Etype(typeid,UserCode,FullName) 
	select typeid,UserCode,FullName FROM Employee WHERE Typeid in (select typeid from F_GetManDetailEType(@OperatorId))
END
ELSE
	INSERT INTO #Etype(typeid,UserCode,FullName) 
	select typeid,UserCode,FullName FROM Employee WHERE Typeid in 
	(	
		select a.typeid from F_GetManDetailEType(@OperatorID) a,
		(select * from  dbo.f_split(@EtypeIDZ,',')) b where left(a.typeid,len(b.a))=b.a
	)


IF @ETypeIDA =''
BEGIN
	INSERT INTO #Etype1(typeid,UserCode,FullName) 
	select typeid,UserCode,FullName FROM Employee WHERE Typeid in (select typeid from F_GetManDetailEType(@OperatorId))
	INSERT INTO #Etype1(Typeid,UserCode,FullName) SELECT '','','' -- 审核人为空
END
ELSE
	INSERT INTO #Etype1(typeid,UserCode,FullName) 
	select typeid,UserCode,FullName FROM Employee WHERE Typeid in 
	(	
		select a.typeid from F_GetManDetailEType(@OperatorID) a,
		(select * from  dbo.f_split(@EtypeIDA,',')) b where left(a.typeid,len(b.a))=b.a
	)



DECLARE @SQL_WHERE VARCHAR(4000)
DECLARE @SQL VARCHAR(8000)

SET @SQL_WHERE=' WHERE 
			b.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
			AND b.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
			AND b.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
			AND b.Comment LIKE '+CHAR(39)+'%'+@Comment+'%'+CHAR(39)



DECLARE @NOW VARCHAR(30)
SET @NOW=Convert(VARCHAR(10),Year(GetDate()))+'-'+Convert(VARCHAR(10),Month(GetDate()))+'-'+Convert(VARCHAR(10),Day(GetDate()))


IF @BillStatus='1' 					--未审核,即审核人为空的单据
	SET @SQL_WHERE=@SQL_WHERE+' AND b.EtypeID='''''
IF @BillStatus='2' 					--审核未执行,有审核人并且[当前系统日期]＜[执行开始日期]
	SET @SQL_WHERE=@SQL_WHERE+' AND b.EtypeID<>'''''+'
			AND b.StartDate>'+CHAR(39)+@NOW+CHAR(39)
IF @BillStatus='3'					--正在执行,有审核人并且[执行开始日期]≤[当前系统日期]≤[执行截止日期]
	SET @SQL_WHERE=@SQL_WHERE+' AND b.EtypeID<>'''''+'
			AND b.StartDate<='+CHAR(39)+@NOW+CHAR(39)+'
			AND b.EndDate>='+CHAR(39)+@NOW+CHAR(39)
IF @BillStatus='4'					--执行完成,有审核人并且[当前系统日期]＞[执行截止日期]
	SET @SQL_WHERE=@SQL_WHERE+' AND b.EtypeID<>'''''+'
			AND b.EndDate<'+CHAR(39)+@NOW+CHAR(39)	
IF @ifhidebill='1'
		SET @SQL_WHERE=@SQL_WHERE+' AND b.EndDate>='''+@NOW+''''		


SET @SQL='SELECT	b.BillnumberID,
					b.BillDate,
					b.StartDate,
					b.EndDate,
					b.BillCode,
					e4.fullname as uncheckename,
					b.unchecktime,
       				P.TypeID,
       				''164'' as  billtype,
					ISNULL(E1.FullName,'''') as EFullName1,
					ISNULL(E2.FullName,'''') as EFullName2,
					E3.TypeID as etypeid,
					a.Sub,
					a.SubName,	
					BillStatus=case when isnull(b.etypeid,'''')='''' then ''未审核''	
						else  
							case WHEN b.StartDate>'+CHAR(39)+@NOW+CHAR(39)+' then ''审核未执行''
								 WHEN b.StartDate<='+CHAR(39)+@NOW+CHAR(39)+' AND b.EndDate>='+CHAR(39)+@NOW+CHAR(39)+' then ''正在执行''
								 WHEN b.EndDate<'+CHAR(39)+@NOW+CHAR(39)+' then ''执行完成''
							else ''''
							end			   	
						end,
					b.isuse,
					usestate = CASE WHEN b.isuse = 1 THEN ''启用'' ELSE ''停用'' END
		FROM		TCBillindex b 
		INNER JOIN TCBill a ON b.BillnumberID=a.BillnumberID
		INNER JOIN 	#Ptype p  ON a.PtypeID=P.TypeID
        INNER JOIN 	#Etype e1 ON b.checke=e1.TypeID
		LEFT JOIN 	#Etype1 e2 ON b.EtypeID=e2.TypeID
		LEFT JOIN 	Employee e3 ON a.EtypeID=e3.TypeID
		LEFT JOIN 	Employee e4 ON b.unchecke=e4.TypeID
		'+@SQL_WHERE+'
	ORDER BY b.billnumberid DESC, b.BillDate DESC,b.BillCode DESC,a.Row Desc
	'
PRINT @SQL
EXEC(@SQL)

DROP TABLE #Etype,#Etype1,#Ptype

RETURN 0

SET QUOTED_IDENTIFIER OFF 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_EmployeeSaleDist]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_EmployeeSaleDist]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-06-25
function:职员销售分布表树形表
*/
CREATE PROCEDURE Web_EmployeeSaleDist
(
	@OperatorId		VARCHAR(50),		--操作员Id
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--结束日期
	@StypeId        VARCHAR(MAX),		--分支机构Id
	@PtypeCategoryId VARCHAR(MAX),		--商品类别ID
	@PTypeId		VARCHAR(MAX),		--商品Id
	@ETypeId		VARCHAR(MAX),		--部门Id
	@nType			VARCHAR(10),		--金额的查询方式
	@BillType		VARCHAR(100),		--单据类型
	@ShowZero		VARCHAR(5),			--0.不显示红冲单据   1.显示红冲单据
	@UnitConvert	INT,				--单位
	@Sort		    NVARCHAR(200),		--排序
	@Ck				INT,				--1：升序 0降序
	
	@BCount			INT=10,				--基本信息的默认个数
	@BPageNo		INT=0,				--基本信息的页数
	@IsPrint		INT=0				--是否是打印算法
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------

DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================

--根据单位获取相关值
DECLARE
	@TempColumn			VARCHAR(50),
	@TempQty			VARCHAR(1000)='',
	@TempTable			VARCHAR(1000)=''
	
--销售单位		
IF @UnitConvert=0
	BEGIN
		SET @TempColumn='SaleUnitId'
		SET @TempTable='
		LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.SaleUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
		
	END
--采购单位
ELSE IF @UnitConvert=1
	BEGIN
		SET @TempColumn='BuyUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.BuyUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--存货单位
ELSE IF @UnitConvert=2
	BEGIN
		SET @TempColumn='StockUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.StockUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--基本单位
ELSE IF @UnitConvert=3
	BEGIN
		SET @TempColumn='baseUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.baseUnitId = R.UnitsId'
		SET @TempQty='B.Qty'
	END

--商品
IF(ISNULL(@PTypeId,'')='')
	SET @PTypeId='00000'

--父级
CREATE TABLE #ParidPtype(
	RowId				INT,
	TypeID				VARCHAR(50),
	SonNum				INT,
	UserCode			VARCHAR(200),
	AssistUnitFullName	VARCHAR(200),
	UnitFullName		VARCHAR(200),
	Rate				NUMERIC(24,10)
) 
CREATE CLUSTERED INDEX #ParidPtype_P_K ON #ParidPtype(TypeId)

DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,@PTypeId,@PtypeCategoryId)

SET @SQL='
INSERT INTO #ParidPtype(RowId,TypeID,SonNum,UserCode,AssistUnitFullName,UnitFullName,Rate)
SELECT
	ROW_NUMBER()OVER(ORDER BY P.UserCode) RowId,
	P.typeId,
	P.sonnum,
	P.UserCode,
	E.FullName AssistUnitFullName,
	PU.FullName UnitFullName,
	R.Rate
 '+@LinkStr+'
 LEFT JOIN PType_Units E ON P.AssistantUnitId=E.UnitsId
 '+@TempTable+'
 LEFT JOIN PType_Units PU ON PU.UnitsId=P.'+@TempColumn+'
 WHERE
	P.ParId='''+@PTypeId+'''
	AND P.iscombinationproduct=0'

EXEC(@SQL)

--实际查询商品
CREATE TABLE #Ptype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)
INSERT INTO #Ptype(TypeID)
SELECT
	P.typeId
FROM ptype P
INNER JOIN #ParidPtype F ON P.typeId LIKE F.TypeID+'%' AND P.sonnum=0 AND P.iscombinationproduct=0 

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	BEGIN
		INSERT INTO #Stype(typeid) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
	END

--部门
CREATE TABLE #Dtype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
IF (@MDtypeid='-99999')
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetManDetailDType(@OperatorId)
	END

--往来单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetManDetailBType(@OperatorId)
	END

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeId)
IF (@MKtypeid='-99999')
	BEGIN
		INSERT INTO #Ktype(TypeID)
		SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
		UNION ALL
		SELECT '10000' TypeId
	END

--职员
CREATE TABLE #Etype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF(ISNULL(@ETypeId,'')='' AND @MEtypeid='00000')--所有权限
	BEGIN
		INSERT INTO #Etype(RowId,TypeID,UserCode,FullName) 
		SELECT 
			ROW_NUMBER()OVER(ORDER BY usercode) RowId,
			typeId,
			UserCode,
			FullName
		FROM employee 
		WHERE sonnum=0 AND typeId<>'00000'
		ORDER BY UserCode
	END
ELSE 
	BEGIN
		INSERT INTO #Etype(RowId,TypeID,UserCode,FullName) 
		SELECT 
			ROW_NUMBER()OVER(ORDER BY D.UserCode) RowId,
			F.TypeId,
			D.UserCode,
			D.FullName
		FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorId) F
		INNER JOIN employee D ON F.TypeId=D.typeid AND sonnum=0
		ORDER BY UserCode
	END
	
--当前页职员
CREATE TABLE #PageEtype(TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #PageEtype(TypeID,UserCode,FullName)
SELECT 
	typeid,
	UserCode,
	FullName 
FROM #Etype
WHERE RowId BETWEEN (@bPageNo-1)*@bCount AND @bPageNo*@bCount

--=============================基本信息权限范围获取【END】=======================================

--=============================业务处理【BEGIN】=====================================
SET @SQL=''

--BillIndex
CREATE TABLE #BillIndex
(
	BillNumberId 	NUMERIC(18,0),
	ETypeId			VARCHAR(50),
	BillType		INT	
) 
CREATE CLUSTERED INDEX #BillIndex_P_K ON #BillIndex(BillNumberId)

SET @SQL='
INSERT INTO #BillIndex
(
	BillNumberId,
	ETypeId,
	BillType
)
SELECT	
	B.BillNumberId,
	B.ETypeId,
	B.BillType
FROM BillIndex B' +CHAR(13)	

--分支机构
IF NOT(ISNULL(@StypeId,'')='' AND @MStypeid='00000')
	SET @SQL+='INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid'+CHAR(13)		
	
--职员
IF NOT(ISNULL(@ETypeID,'')='' OR @METypeID='00000' )
	SET @SQL+='INNER JOIN #Etype B_E ON  B_E.TypeID=B.etypeid '+CHAR(13);
	
--往来单位
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		SET @SQL+='INNER JOIN #Btype B_B ON B_B.TypeID=B.BTypeID'+CHAR(13)
		SET @SQL+='INNER JOIN #Btype B_B1 ON B_B1.TypeID=B.DealBTypeID'+CHAR(13)
	END

--部门
IF(@MDtypeid='-99999')
	SET @SQL+='INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId'+CHAR(13)
	
SET @SQL+='
WHERE 
	B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
	AND B.BillType IN ('+@BillType+') 
	AND B.IfCheck=''t'' 
	AND B.RedWord=0 
	AND B.Draft=0 
	AND B.ifYearBill=0'+CHAR(13)
	
EXEC(@SQL)
SET @SQL=''

--数据明细表
CREATE TABLE #SaleBill
(
	PTypeId		VARCHAR(100),
	ETypeId		VARCHAR(100),
	Qty			NUMERIC(24, 10) ,
	NQty        NUMERIC(24, 10) ,
	TaxTotal	NUMERIC(24, 10) 
)
CREATE CLUSTERED INDEX #SaleBill_P_K ON #SaleBill(PTypeId)

--零售单
IF CHARINDEX('305',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN retailBill B ON I.BillType=305 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--零售退货单
IF CHARINDEX('215',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN RetailBackBill B ON I.BillType=215 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
	
END

--销售出库单
IF CHARINDEX('11',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I 
	INNER JOIN SaleBill B ON I.BillType=11 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--销售退货单
IF CHARINDEX('45',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN saleBackBill B ON I.BillType=45 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--销售换货单
IF CHARINDEX('160',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		CASE WHEN B.InOrOut = ''o'' THEN SUM('+@tempqty+') ELSE -SUM('+@tempqty+') END Qty,
		CASE WHEN B.InOrOut = ''o'' THEN SUM(B.NQty) ELSE -SUM(B.NQty) END NQty,
		CASE WHEN B.InOrOut = ''o'' THEN CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END
			 ELSE CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END
		END TaxTotal 
	FROM #BillIndex I
	INNER JOIN SaleGoodsExchangeBill B ON I.BillType=160 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='WHERE 
		B.InOrOut=''i'' 
		OR B.InOrOut=''o''  
	GROUP BY B.PTypeId,I.ETypeId,B.InOrOut'+CHAR(13)
END

--委托代销结算单
IF CHARINDEX('141',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN CommissionBill B ON I.BillType=141 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--组合品销售出库单
IF CHARINDEX('12',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		SUM('+@tempqty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBillDetail B ON I.BillType=12 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--组合品销售退货单
IF CHARINDEX('46',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		-SUM('+@tempqty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBackBillDetail B ON I.BillType=46 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

SET @SQL='
INSERT INTO #SaleBill
(
	PTypeId,
	ETypeId,
	Qty,
	NQty,
	TaxTotal
)
SELECT 
	PtypeId,
	ETypeId,
	SUM(ISNULL(F.Qty,0)) Qty,
	SUM(ISNULL(F.NQty,0)) NQty,
	SUM(ISNULL(F.TaxTotal,0)) TaxTotal
 FROM 
('+SUBSTRING(@SQL,10,LEN(@SQL))+'
)F
GROUP BY F.PTypeId,F.ETypeId
'
EXEC(@SQL)

--生成分布表
SET @SQL = '
SELECT
	P.typeid,
	P.SonNum 父节点,
	p.AssistUnitFullName 浮动单位,
	SUM(ISNULL(B.Qty,0)) 总计数量,
	SUM(ISNULL(B.NQty,0)) 总计浮动数量,
	SUM(ISNULL(B.TaxTotal,0)) 总计金额'

IF @bCount='10'
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'数量]
						,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'浮动数量]
						,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'金额]'  
	FROM #PageEtype ORDER BY UserCode    
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'数量]
						,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'浮动数量]
						,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'金额]'  
	FROM #Etype ORDER BY UserCode    
END 
SET @SQL+='
FROM #ParidPtype P
LEFT JOIN #SaleBill B ON B.PTypeId LIKE P.TypeID+''%'''  

SET @SQL+='
GROUP BY
	P.RowId,
	P.TypeID,
	P.SonNum,
	p.AssistUnitFullName
ORDER BY'

IF ISNULL(@sort,'')=''
	SET @SQL+='	p.RowId'   
	 
IF ISNULL(@sort,'')='0'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.Qty,0)) desc '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.Qty,0))'  
  END				
IF ISNULL(@sort,'')='1'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.NQty,0)) desc '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.NQty,0))'  
  END
IF	ISNULL(@sort,'')='2'
  BEGIN
	IF @ck!=1
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0)) desc '    
    ELSE
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0))'  
  END
				
EXEC(@SQL)
--=============================业务处理【END】=======================================



--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#Dtype,#Etype,#Ktype,#Ptype,#Stype,#BillIndex,#PageEtype,#SaleBill,#ParidPtype

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_EmployeeSaleDistLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_EmployeeSaleDistLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-06-25
function:职员销售分布线性表
*/
CREATE PROCEDURE Web_EmployeeSaleDistLine
(
	@OperatorId		VARCHAR(50),		--操作员Id
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--结束日期
	@StypeId        VARCHAR(MAX),		--分支机构Id
	@PtypeCategoryId VARCHAR(MAX),		--商品类别ID
	@PTypeId		VARCHAR(MAX),		--商品Id
	@ETypeId		VARCHAR(MAX),		--职员Id
	@nType			VARCHAR(10),		--金额的查询方式
	@BillType		VARCHAR(100),		--单据类型
	@ShowZero		VARCHAR(5),			--0.不显示红冲单据   1.显示红冲单据
	@UnitConvert	INT,				--单位
	@Sort		    NVARCHAR(200),		--排序
	@Ck				INT,				--1：升序 0降序

	@BCount			INT=10,				--基本信息的默认个数
	@BPageNo		INT=0				--基本信息的页数
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN --------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE 
	@Re INT,
	@MAtypeid VARCHAR(50), 
	@MBtypeid VARCHAR(50), 
	@MBtypeid2 VARCHAR(50), 
	@MEtypeid VARCHAR(50),
	@MKtypeid VARCHAR(50), 
	@MPtypeid VARCHAR(50), 
	@MExpense VARCHAR(50), 
	@MIncome VARCHAR(50),
	@MCapital VARCHAR(50),
	@MDtypeid VARCHAR(50),
	@MStypeid VARCHAR(50)
	
EXEC @Re=GP_CheckOperatorRight23_Rep 
		@OperatorID,
		@MAtypeid OUTPUT,
		@MBtypeid OUTPUT,
		@MBtypeid2 OUTPUT,
		@MEtypeid OUTPUT,
		@MKtypeid OUTPUT,
		@MPtypeid OUTPUT,
		@MExpense OUTPUT,
		@MIncome OUTPUT,
		@MCapital OUTPUT,
		@MDtypeid OUTPUT,
		@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------
END;
	
DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================

--根据单位获取相关值
DECLARE
	@TempColumn			VARCHAR(50),
	@TempQty			VARCHAR(1000)='',
	@TempTable			VARCHAR(1000)=''
	
--销售单位		
IF @UnitConvert=0
	BEGIN
		SET @TempColumn='SaleUnitId'
		SET @TempTable='
		LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.SaleUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
		
	END
--采购单位
ELSE IF @UnitConvert=1
	BEGIN
		SET @TempColumn='BuyUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.BuyUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--存货单位
ELSE IF @UnitConvert=2
	BEGIN
		SET @TempColumn='StockUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.StockUnitId = R.UnitsId'
		SET @TempQty='B.Qty/ISNULL(B_P.rate,1)'
	END
--基本单位
ELSE IF @UnitConvert=3
	BEGIN
		SET @TempColumn='baseUnitId'
		SET @TempTable='LEFT JOIN PType_Units_Ext R ON R.PTypeId = P.TypeId AND P.baseUnitId = R.UnitsId'
		SET @TempQty='B.Qty'
	END

--商品
IF(ISNULL(@PTypeId,'')='')
	SET @PTypeId='00000'

--实际查询商品
CREATE TABLE #Ptype(
	RowId				INT,
	TypeID				VARCHAR(50),
	SonNum				INT,
	UserCode			VARCHAR(200),
	AssistUnitFullName	VARCHAR(200),
	UnitFullName		VARCHAR(200),
	Rate				NUMERIC(24,10)
) CREATE CLUSTERED INDEX #Ptype_P_K ON #Ptype(TypeId)

DECLARE @LinkStr VARCHAR(MAX)=''
SELECT @LinkStr=dbo.F_GetPTypeInCategoryIDStr(@OperatorId,@PTypeId,@PtypeCategoryId)

SET @SQL+='
INSERT INTO #Ptype(RowId,TypeID,SonNum,UserCode,AssistUnitFullName,UnitFullName,Rate)
SELECT
	ROW_NUMBER()OVER(ORDER BY P.UserCode) RowId,
	P.typeId,
	P.sonnum,
	P.UserCode,
	E.FullName AssistUnitFullName,
	PU.FullName UnitFullName,
	R.Rate
 '+@LinkStr+'
 LEFT JOIN PType_Units E ON P.AssistantUnitId=E.UnitsId
 '+@TempTable+'
 LEFT JOIN PType_Units PU ON PU.UnitsId=P.'+@TempColumn+'
 WHERE
	P.sonnum=0
	AND P.iscombinationproduct=0'

EXEC(@SQL)

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	BEGIN
		INSERT INTO #Stype(typeid) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
	END

--部门
CREATE TABLE #Dtype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
IF (@MDtypeid='-99999')
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetManDetailDType(@OperatorId)
	END

--往来单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetManDetailBType(@OperatorId)
	END

--职员
CREATE TABLE #Etype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF(ISNULL(@ETypeId,'')='' AND @MEtypeid='00000')--所有权限
	BEGIN
		INSERT INTO #Etype(RowId,TypeID,UserCode,FullName) 
		SELECT 
			ROW_NUMBER()OVER(ORDER BY usercode) RowId,
			typeId,
			UserCode,
			FullName
		FROM employee 
		WHERE sonnum=0 AND typeId<>'00000'
		ORDER BY UserCode
	END
ELSE 
	BEGIN
		INSERT INTO #Etype(RowId,TypeID,UserCode,FullName) 
		SELECT 
			ROW_NUMBER()OVER(ORDER BY D.UserCode) RowId,
			F.TypeId,
			D.UserCode,
			D.FullName
		FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorId) F
		INNER JOIN employee D ON F.TypeId=D.typeid AND sonnum=0
		ORDER BY UserCode
	END
	
--当前页部门
CREATE TABLE #PageEtype(TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #PageEtype(TypeID,UserCode,FullName)
SELECT 
	typeid,
	UserCode,
	FullName 
FROM #Etype
WHERE RowId BETWEEN (@bPageNo-1)*@bCount AND @bPageNo*@bCount

--仓库
CREATE TABLE #Ktype(RowId INT,TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #Ktype_P_K ON #Ktype(TypeId)
IF (@MKtypeid='-99999')
	BEGIN
		INSERT INTO #Ktype(TypeID)
		SELECT TypeId FROM F_GetManDetailKType(@OperatorId)
		UNION ALL
		SELECT '10000' TypeId
	END

--=============================基本信息权限范围获取【END】=======================================


--=============================业务处理【BEGIN】=====================================
SET @SQL=''

--BillIndex
CREATE TABLE #BillIndex
(
	BillNumberId 	NUMERIC(18,0),
	ETypeId			VARCHAR(50),
	BillType		INT	
) 
CREATE CLUSTERED INDEX #BillIndex_P_K ON #BillIndex(BillNumberId)

SET @SQL='
INSERT INTO #BillIndex
(
	BillNumberId,
	ETypeId,
	BillType
)
SELECT	
	B.BillNumberId,
	B.ETypeId,
	B.BillType
FROM BillIndex B' +CHAR(13)	

--分支机构
IF NOT(ISNULL(@Stypeid,'')='' AND @MStypeid='00000')
	SET @SQL+='INNER JOIN #Stype B_S ON B_S.TypeID=B.Stypeid'+CHAR(13)	
	
--部门
IF(@MDtypeid='-99999')
	SET @SQL+='INNER JOIN #Dtype B_D ON B_D.TypeID=B.DTypeId '+CHAR(13)	
	
--往来单位
IF(@MBTypeID='-99999' OR @MBTypeID2='-99999')
	BEGIN
		SET @SQL+='INNER JOIN #Btype B_B ON B_B.TypeID=B.BTypeID'+CHAR(13)
		SET @SQL+='INNER JOIN #Btype B_B1 ON B_B1.TypeID=B.DealBTypeID'+CHAR(13)
	END

--职员		
IF (@MEtypeid='-99999')
	SET @SQL+='INNER JOIN #Etype B_E ON B_E.TypeID=B.etypeid'+CHAR(13)
	
SET @SQL+='
WHERE 
	B.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' 
	AND B.BillType IN ('+@BillType+') 
	AND B.RedWord=0 
	AND B.IfCheck=''t'' 
	AND B.Draft=0 
	AND B.ifYearBill=0'+CHAR(13)
	
EXEC(@SQL)
SET @SQL=''


--数据明细表
CREATE TABLE #SaleBill
(
	PTypeId		VARCHAR(50),
	ETypeId		VARCHAR(50),
	Qty			NUMERIC(24,10),
	NQty        NUMERIC(24,10),
	TaxTotal	NUMERIC(24,10) 
)
CREATE CLUSTERED INDEX #SaleBill_P_K ON #SaleBill(PTypeId)

--零售单
IF CHARINDEX('305',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN retailBill B ON I.BillType=305 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--零售退货单
IF CHARINDEX('215',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN RetailBackBill B ON I.BillType=215 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
	
END

--销售出库单
IF CHARINDEX('11',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN SaleBill B ON I.BillType=11 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--销售退货单
IF CHARINDEX('45',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN saleBackBill B ON I.BillType=45 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--销售换货单
IF CHARINDEX('160',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		CASE WHEN B.InOrOut = ''o'' THEN SUM('+@TempQty+') ELSE -SUM('+@TempQty+') END Qty,
		CASE WHEN B.InOrOut = ''o'' THEN SUM(B.NQty) ELSE -SUM(B.NQty) END NQty,
		CASE WHEN B.InOrOut = ''o'' THEN CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END
			 ELSE CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END
		END TaxTotal 
	FROM #BillIndex I
	INNER JOIN SaleGoodsExchangeBill B ON I.BillType=160 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)	
		
	SET @SQL+='WHERE 
		B.InOrOut=''i'' 
		OR B.InOrOut=''o''  
	GROUP BY B.PTypeId,I.ETypeId,B.InOrOut'+CHAR(13)
END

--委托代销结算单
IF CHARINDEX('141',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN CommissionBill B ON I.BillType=141 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--组合品销售出库单
IF CHARINDEX('12',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		SUM('+@TempQty+') Qty,
		SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN SUM(B.TaxTotal) ELSE SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBillDetail B ON I.BillType=12 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

--组合品销售退货单
IF CHARINDEX('46',@BillType)<>0
BEGIN
	SET @SQL+='UNION ALL
	SELECT
		B.PtypeId,
		I.ETypeId,
		-SUM('+@TempQty+') Qty,
		-SUM(B.NQty) NQty,
		CASE WHEN '+@nType+'=0 THEN -SUM(B.TaxTotal) ELSE -SUM(B.total) END TaxTotal		 
	FROM #BillIndex I
	INNER JOIN PT_Combin_SaleBackBillDetail B ON I.BillType=46 AND B.BillNumberId=I.BillNumberId
	INNER JOIN #Ptype B_P ON B_P.TypeID=B.PtypeId'+CHAR(13)
	
	IF @MKTypeID = -99999 
		SET @SQL+='INNER JOIN #Ktype B_K ON B_K.TypeID=B.KTypeID'+CHAR(13)
		
	SET @SQL+='GROUP BY B.PTypeId,I.ETypeId'+CHAR(13)
END

SET @SQL='
INSERT INTO #SaleBill
(
	PTypeId,
	ETypeId,
	Qty,
	NQty,
	TaxTotal
)
SELECT 
	PtypeId,
	ETypeId,
	SUM(ISNULL(F.Qty,0)) Qty,
	SUM(ISNULL(F.NQty,0)) NQty,
	SUM(ISNULL(F.TaxTotal,0)) TaxTotal
 FROM 
('+SUBSTRING(@SQL,10,LEN(@SQL))+'
)F
INNER JOIN #Etype T ON T.TypeId=F.ETypeId
GROUP BY F.PTypeId,F.ETypeId
'
EXEC(@SQL)

--生成分布表
SET @SQL = '
SELECT
	P.typeid,
	P.SonNum,
	P.AssistUnitFullName 浮动单位,
	P.UnitFullName 计量单位,
	SUM(ISNULL(B.Qty,0)) 总计数量,
	SUM(ISNULL(B.NQty,0)) 总计浮动数量,
	SUM(ISNULL(B.TaxTotal,0)) 总计金额'

IF @bCount='10'
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'数量]
						,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'浮动数量]
						,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'金额]'  
	FROM #PageEtype ORDER BY UserCode 
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.Qty,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'数量]
						,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.NQty,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'浮动数量]
						,SUM(CASE WHEN B.ETypeId = '''+TypeId+'''  THEN ISNULL(B.TaxTotal,0) ELSE 0 END) ['+'('+UserCode+')'+FullName+'金额]'  
	FROM #Etype ORDER BY UserCode 
END 
SET @SQL+='
FROM #Ptype P
LEFT JOIN #SaleBill B ON B.PTypeId=P.TypeID'  

SET @SQL+='
GROUP BY
	P.RowId,
	P.TypeID,
	P.SonNum,
	P.AssistUnitFullName,
	P.UnitFullName
ORDER BY'

IF ISNULL(@sort,'')=''
	SET @SQL+='	p.RowId'   
	 
IF ISNULL(@sort,'')='0'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.Qty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.Qty,0))'  
  END				
IF ISNULL(@sort,'')='1'
  BEGIN
	IF @ck!=1
		SET @SQL+='	SUM(ISNULL(B.NQty,0)) DESC '    
    ELSE
		SET @SQL+='	SUM(ISNULL(B.NQty,0))'  
  END
IF	ISNULL(@sort,'')='2'
  BEGIN
	IF @ck!=1
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0)) DESC '    
    ELSE
		SET @SQL+=' SUM(ISNULL(B.TaxTotal,0))'  
  END
				
EXEC(@SQL)

--=============================业务处理【END】=======================================



--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#Dtype,#Etype,#Ktype,#Ptype,#Stype,#BillIndex,#PageEtype,#SaleBill

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_EmployerSaletypeAnalysis_List]') and OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].Web_EmployerSaletypeAnalysis_List
GO




/*
职员销售类型分析
李灏龙 2011-12-15
*/

/*
修改：黄清 2012-04-05
描述：增加分支机构查询条件
*/

/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Web_EmployerSaletypeAnalysis_List
(
	@opratorid	VARCHAR(100),
	@stypeid	VARCHAR(50)='00001',
	@ptypeid	VARCHAR(50),
	@btypeid	VARCHAR(50),
	@ktypeid	VARCHAR(50),
	@startdate	VARCHAR(50),
	@enddate	VARCHAR(50),
	@typeid		VARCHAR(50),		--经手人名称
	@flag		VARCHAR(1),
	@dtypeid	VARCHAR(100),
	@isshowzero	VARCHAR(10)='1'	--线性表是否显示为0的数据
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------

----商品权限----
CREATE TABLE #ptype
(
	ptypeid VARCHAR(50)
)
INSERT INTO #ptype 
SELECT TypeId AS ptypeid
FROM F_GetAllManagerBASeTypeId(@ptypeid,1,@opratorid)  

----分支机构权限----
CREATE TABLE #stype
(
	stypeid VARCHAR(50)
)
INSERT INTO #stype 
SELECT TypeId AS stypeid
FROM F_GetAllManagerBASeTypeId(@stypeid,11,@opratorid)  


----往来权限----	 
CREATE TABLE #btype
(	
	btypeid VARCHAR(50)
)
INSERT INTO #btype 
SELECT TypeId AS btypeid
FROM F_GetAllManagerBASeTypeId(@btypeid,2,@opratorid) 


IF @typeid='00000'
	SET @typeid=''
----职员权限----	 
CREATE TABLE #etype
(
	etypeid VARCHAR(50)	
)
INSERT INTO #etype
SELECT TypeId AS etypeid
FROM F_GetAllManagerBASeTypeId(@typeid,3,@opratorid)
--加入父节点职员ID
INSERT INTO #etype
SELECT typeId AS etypeid FROM employee WHERE sonnum != 0 




----仓库权限----	 
CREATE TABLE #ktype
(	
	ktypeid VARCHAR(50)
)
INSERT INTO #ktype
SELECT TypeId AS ktypeid
FROM F_GetAllManagerBASeTypeId(@ktypeid,4,@opratorid)
----在仓库权限中加入不受管制的代销仓库
IF @ktypeid = ''
	INSERT INTO #ktype(ktypeid) VALUES('10000')


----部门权限
CREATE TABLE #dtype
(
	dtypeid VARCHAR(50)
)
INSERT INTO #dtype
SELECT TypeId AS dtypeid
FROM F_GetAllManagerBASeTypeId('',9,@opratorid)


--------------------------------------------------------------权限检查-------------------------------------------------------


----@sonnum 用于记录子节点数
----@SQL 用于存储查询语句
----@MSQL 用于存储查询条件
DECLARE		@sonnum INT,
			@SQL VARCHAR(MAX)

SELECT	c.etypeid,
		ISNULL(SUM(lsj ), 0)-ISNULL(SUM(lsth),0) AS lsj,
		ISNULL(SUM(wtdx), 0) AS wtdxj,
		ISNULL(SUM(xscd), 0) - ISNULL(SUM(xsth), 0) - ISNULL(SUM(xshh), 0) AS pfj,
		ISNULL(SUM(xscd), 0) - ISNULL(SUM(xsth), 0)-ISNULL(SUM(lsth),0) - ISNULL(SUM(xshh), 0) + ISNULL(SUM(lsj), 0) + ISNULL(SUM(wtdx), 0) AS jshj,
		ISNULL(SUM(zsl ), 0) AS zsl 
INTO #Result
					FROM
					(		SELECT  i.etypeid,
										lsj =	 CASE WHEN i.BillType = 305 THEN -SUM(i.Total) END,
										xscd = CASE WHEN i.BillType in( 11,12)	THEN -SUM(i.Total) END,
										xsth = CASE WHEN i.BillType in (45,46)	THEN  SUM(i.Total) END,
										lsth = CASE WHEN i.BillType = 215	THEN  SUM(i.Total) END,
										xshh = CASE WHEN i.BillType = 160 THEN  SUM(i.Total) END,
										zsl =  CASE WHEN i.BillType = 139 THEN -SUM(i.qty)   END,
										wtdx = CASE WHEN i.BillType = 141 THEN -SUM(i.Total) END	
							FROM InOutstocktable i
							INNER JOIN #ktype k ON k.ktypeid = i.ktypeid
							INNER JOIN #dtype d ON d.dtypeid = i.dtypeid
							INNER JOIN #ptype p ON p.ptypeid = i.ptypeid
							INNER JOIN #btype b ON b.btypeid = i.btypeid
							INNER JOIN #stype s ON s.stypeid = i.stypeid
							INNER JOIN #Etype E ON E.Etypeid = i.Etypeid
							WHERE BillType IN (141,305,139,45,160,11,215,12,46) 
								AND BillDate >= @startdate
								AND BillDate <= @enddate
							GROUP BY i.etypeid,BillType
					) c 
					GROUP BY c.etypeId


----@flag为0时执行树形查找	
IF @flag = '0'
BEGIN
	
----第一次查询时@typeid参数为空，所以要赋值为00001以便后面查询
		IF @typeid = ''
			SET @typeid = '00001'

		SELECT @sonnum = sonnum FROM employee WHERE typeId = @typeid

		SELECT e.Parid,e.sonnum,e.typeid,
				SUM(ISNULL(x.lsj,0)) AS lsj,		--零售
				SUM(ISNULL(x.wtdxj,0)) AS wtdxj,	--委托
				SUM(ISNULL(x.pfj,0)) AS pfj,		--批发
				SUM(ISNULL(x.jshj,0)) AS jshj,		--销售
				SUM(ISNULL(x.zsl,0)) AS zsl			--赠送
		FROM employee e
		LEFT JOIN #Result x	
			ON x.etypeid LIKE e.typeid + '%'
		INNER JOIN #etype et ON et.etypeid = e.typeid 
		WHERE	(@sonnum <> 0 OR E.typeId = @typeid)
			AND (@sonnum = 0 OR E.Parid = @typeid)
		GROUP BY e.Typeid,e.Parid,e.sonnum,e.usercode 
		ORDER BY E.USERCODE

END

----@flag为1时执行线性查找
ELSE IF @flag = '1'
BEGIN
	--SET @SQL = 
	SELECT e.typeid,
					ISNULL(x.lsj,0) AS lsj,
					ISNULL(x.wtdxj,0) AS wtdxj,
					ISNULL(x.pfj,0) AS pfj,
					ISNULL(x.jshj,0) AS jshj, 
					ISNULL(x.zsl,0) AS zsl 
	FROM employee e
	LEFT JOIN #Result x	
		ON x.etypeid = e.typeid
	INNER JOIN #etype et ON et.etypeid = e.typeid
	WHERE 1 = 1
		AND (@typeid = '00000' OR e.typeid LIKE @typeid + '%')
		AND (@isshowzero <> '0' OR (X.lsj<>0 OR X.jshj<>0 OR X.pfj<>0 OR X.wtdxj<>0 OR X.zsl<>0) )
		AND e.sonnum = 0 
	ORDER BY E.USERCODE
END

DROP TABLE #ptype,#btype,#etype,#ktype,#dtype,#stype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
    作者：董湛
	日期：2013-08-16
	描述：店帐通-本地商品选择
-------------------------------------------*/

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EshopLocalGoodsSelectorQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].Web_EshopLocalGoodsSelectorQuery
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE Web_EshopLocalGoodsSelectorQuery
(
	@Query		   VARCHAR(100)---查询参数
)
--@encode$--
AS 
SET NOCOUNT ON
BEGIN
	IF(@Query='')--不为空则进行过滤查询
		BEGIN
			SELECT	typeId,
					UserCode,
					FullName,
				    customitemid,
				    customitemname,
				    customitemfrom,
				    customitemrefid
			FROM	F_GetManPType('00001')
			WHERE	sonnum=0 AND deleted=0
			ORDER BY UserCode
		END
	ELSE
		BEGIN
			SET @Query = '%'+@Query+'%'
			SELECT	typeId,
					UserCode,
					FullName,
					customitemid,
				    customitemname,
				    customitemfrom,
				    customitemrefid 
			FROM	F_GetManPType('00001') 
			WHERE	sonnum=0 AND  (UserCode LIKE @Query OR FullName LIKE @Query) AND deleted=0
			ORDER BY UserCode
		END
END 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_eshopQuerySaleBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_eshopQuerySaleBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康	
	日期：2018-03-27
	描述：网店结存订单查询
*/
CREATE PROCEDURE Web_eshopQuerySaleBill
(
	@operatorid			VARCHAR(50),
	@startdate			VARCHAR(100),	--开始日期
	@enddate			VARCHAR(100),	--截止日期
	@ptypeid			VARCHAR(MAX),	--商品ID
	@xsbillcode			VARCHAR(500),	--销售单号
	@yddbillcode		VARCHAR(500),	--预订单单号
	@spglzt				VARCHAR(10),	--商品关联状态
	@sczt				VARCHAR(10),	--上传状态
	@sfdmf				VARCHAR(10),	--是否当面付
	@dmzfzt				VARCHAR(10)		--当面支付状态
)
AS
SET NOCOUNT ON

DECLARE @sql VARCHAR(MAX)

--构造SQL语句
SET @sql = 'SELECT	Bi.BillNumberId,
					Bi.BillDate,
					Bi.BillCode,
					Bi.BillType,
					Bi.BTypeId,
					S.PTypeId,
					unitName = (SELECT TOP 1 fullname FROM PType_Units WHERE UnitsId = s.UnitID),		
					munitName = (SELECT TOP 1 fullname FROM PType_Units WHERE UnitsId = s.MUnitID),
					S.Qty,
					S.NQty,
					S.MQty,
					CASE
						WHEN Bi.uploadpreorder = 0 THEN ''未上传''				
						ELSE ''已上传''
					END AS uploadproordername,
					CASE
						WHEN payonthespot = 0 THEN ''否''
						ELSE ''是''
					END AS payonthespotname,
					CASE
						WHEN PreOrderStatus = 2 THEN ''已支付''
						ELSE ''未支付''
					END AS payonthespotstate,
					CASE
						WHEN bp.WdSyncFlag = ''1'' THEN ''已上传''
						ELSE ''未上传''
					END AS syncflag,
					Bi.PayOnTheSpot,
					Bi.UploadPreOrder,
					Bi.PreOrderStatus,
					Bi.PreOrderId
			FROM	BillIndex Bi
			INNER JOIN SaleBill S ON bi.billnumberid = s.BillNumberId
			INNER JOIN (SELECT TypeId FROM F_GetManDetailPType('''+@OperatorID+''')) P ON S.PtypeId = p.TypeId
			INNER JOIN (SELECT TypeId FROM F_GetManDetailBType('''+@OperatorID+''')) B ON Bi.BtypeId = B.TypeId
			INNER JOIN (SELECT Typeid FROM F_GetAllBaseTypeId('''+@ptypeid+''',1)) MP ON Mp.TypeId = S.PTypeId
			INNER JOIN PType_Units Pu ON pu.UnitsId = S.UnitID
			INNER JOIN ptype bp ON bp.typeid = s.PtypeId
			WHERE	Bi.BillDate>='''+@startdate+'''
					AND Bi.BillDate<='''+@enddate+'''
					AND Bi.BillType = 11
					AND Bi.IfCheck = ''t''
					AND Bi.RedWord = 0
					AND bi.BillCode LIKE ''%' + @xsbillcode + '%''
					AND NOT EXISTS(SELECT TOP 1 1 FROM WdShopBillRelation WHERE billnumberid = Bi.BillnumberId) '
					
--是否当面付
IF @sfdmf = 9
	SET @sql = @sql + ' AND bi.payonthespot IN (0,1) '
ELSE
	SET @sql = @sql + ' AND bi.payonthespot IN ('+@sfdmf+') '	
	
--单据上传状态	
IF @sczt = 9
	SET @sql = @sql + ' AND bi.uploadpreorder IN (0,1) '
ELSE
	SET @sql = @sql + ' AND bi.uploadpreorder IN ('+@sczt+') '		
	
--商品关联状态
IF @spglzt = 9
	SET @sql = @sql + ' AND bp.WdSyncFlag IN (0,1) '	
ELSE	
	SET @sql = @sql + ' AND bp.WdSyncFlag IN ('+@spglzt+') '	
	
--支付状态
IF @dmzfzt = 9
	SET @sql = @sql + ' AND 1 = 1 '
ELSE IF @dmzfzt = 2	
	SET @sql = @sql + ' AND bi.PreOrderStatus IN (2)  '	
ELSE	
	SET @sql = @sql + ' AND bi.PreOrderStatus <> 2 '	
	
--预订单单号
IF(ISNULL(@yddbillcode,'')<>'')
	SET @sql+='	AND BI.PreOrderId LIKE ''%'+@yddbillcode+'%'''
						
SET @sql = @sql + '	ORDER BY Bi.BillDate DESC '

EXEC(@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
	作者:董湛
	日期:2013-03-22
	描述：商品数量上传，获取商品对应的虚拟库存
-------------------------------------------*/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EshopVirtualStock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].[Web_EshopVirtualStock]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  PROCEDURE Web_EshopVirtualStock
( 
	@Ktypeid	VARCHAR(max),
	@UserCode	VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @StypeID VARCHAR(50)    SET @StypeID=(SELECT Value FROM dbo.EshopBaseInfo WHERE Field='StypeItem')     						--分支机构 V3为00001
	IF @StypeID='' OR @StypeID IS NULL
		BEGIN
			RAISERROR('过账配置未配置，请配置',16,1)
			RETURN
		END
	DECLARE @Type VARCHAR(50)       SET @Type=(SELECT Value FROM dbo.EshopBaseInfo WHERE Field='StockItem') 
	IF @Type='' OR @Type IS NULL
		BEGIN
			RAISERROR('请配置商品数量更新方式',16,1)
			RETURN
		END
	------要查询的仓库
	CREATE TABLE #tempKtype
	(
		typeid VARCHAR(50)
	)
	IF @Ktypeid=''    
		INSERT INTO #tempKtype (typeid) SELECT typeId FROM Stock WHERE deleted=0 AND sonnum=0 AND typeid<>'00000' AND STypeID=@StypeID
	ELSE 
		INSERT INTO #tempKtype  (typeid) 
		SELECT DISTINCT s.typeId
		FROM dbo.f_split(@Ktypeid,',') f 
		JOIN dbo.Stock s ON s.TYPEID LIKE f.a+'%' AND s.SONNUM=0 AND s.DELETED=0 
     
	----要查询的商品
	CREATE TABLE #tempPtype
	(
		typeid varchar(50)
	)
	IF @UserCode=''
		INSERT INTO #tempPtype (typeid) SELECT typeid FROM ptype WHERE sonnum=0 AND deleted=0
    ELSE 
		INSERT INTO #tempPtype (typeid) SELECT typeid FROM ptype WHERE sonnum=0 AND deleted=0 AND UserCode=@UserCode
  
    IF @Type='stock'    ---实际库存
		BEGIN
			SELECT p.typeId AS TypeId,UserCode,FullName,p.customitemid,p.customitemfrom,p.customitemname,p.customitemrefid,
				 CASE WHEN  Qty<0 THEN 0 
					  WHEN Qty IS NULL THEN 0
				 ELSE floor(Qty) END AS Qty 
			FROM #tempPtype t LEFT JOIN 
			(
				SELECT p.typeid AS typeid,ISNULL(SUM(Qty),0) AS Qty  
				FROM #tempPtype p
				JOIN  dbo.GoodsStocks gs ON gs.PtypeId=p.typeid
				JOIN #tempKtype k ON gs.KtypeId=k.typeid
				GROUP BY p.typeid
			) a
			ON a.typeid=t.typeId
			JOIN ptype p ON t.typeid=p.typeId
		END
    ELSE                ---虚拟库存
		BEGIN
			--计算普通单据草稿库存
			SELECT	BillNumberId,
					BillType,
					KTypeId,
					KTypeId2
			INTO	#BillIndex
			FROM	BillIndex
			WHERE	BillType IN (34,6,161,11,45,160,17,21,16,9,14,144,146,140,142,305,126,139,183,187,188,201,202)
					AND Draft = 1
					AND IfWx = 0


			--维修单据草稿库存
			SELECT	BillNumberId,
					BillType,
					KTypeId,
					KTypeId2
			INTO	#WxBillIndex
			FROM	BillIndex
			WHERE	BillType IN (166,168,172,173,174,178,191,196,197)
					AND Draft = 1
				--数据临时表
			CREATE TABLE #DGS
			(
				PTypeId		varchar(100),
				RQty		 NUMERIC(24, 10) ,
				CQty		 NUMERIC(24, 10) 
			)


			INSERT INTO #DGS
			(
				PTypeId,
				RQty,
				CQty
			)
			SELECT	B.PTypeId,
					ISNULL(SUM(B.RQty),0) AS RQty,
					ISNULL(SUM(B.CQty),0) AS CQty
			FROM GoodsStocks_Draft B INNER JOIN #tempPtype P ON P.TypeId=B.PtypeId  
				INNER JOIN #tempKtype K	ON K.TypeId=B.KTypeID
			GROUP BY B.PtypeId
					
				---统计数据临时表
				CREATE TABLE #LeftJoinTable
			(
				TypeId			 VARCHAR(50),
				RQty			 NUMERIC(24, 10) ,
				CQty			 NUMERIC(24, 10) ,
				Qty				 NUMERIC(24, 10) ,
				Lendqty			 NUMERIC(24, 10) ,
				Borrowqty		 NUMERIC(24, 10) ,
				SaleOrderQty	 NUMERIC(24, 10) ,
				BuyOrderQty		 NUMERIC(24, 10) ,
				SaleReachQty	 NUMERIC(24, 10) ,
				BuyReachQty		 NUMERIC(24, 10) 
			)
			
			-----1
			INSERT INTO #LeftJoinTable (
			TypeId,
			RQty,
			CQty,
			Qty,
			Lendqty,
			Borrowqty,
			SaleOrderQty,
			BuyOrderQty,
			SaleReachQty,
			BuyReachQty
			)
				SELECT	s.PTypeId AS TypeId,
						RQty,
						CQty,
						0 AS Qty,
						0 AS Lendqty,
						0 AS Borrowqty,
						0 AS SaleOrderQty,
						0 AS BuyOrderQty,
						0 AS SaleReachQty,
						0 AS BuyReachQty
				FROM	#DGS s
				
			-----2
			INSERT INTO #LeftJoinTable (
			TypeId,
			RQty,
			CQty,
			Qty,
			Lendqty,
			Borrowqty,
			SaleOrderQty,
			BuyOrderQty,
			SaleReachQty,
			BuyReachQty
			)		
				SELECT 	p.typeid,
						0 AS RQty,
						0 AS CQty,
						SUM(g.qty) AS qty,
						0 AS Lendqty,
						0 AS Borrowqty,
						0 AS SaleOrderQty,
						0 AS BuyOrderQty,
						0 AS SaleReachQty,
						0 AS BuyReachQty
				FROM 	goodsstocks g 
						inner join #tempPtype p on p.typeid=g.ptypeid
						inner join #tempKtype k on g.KTypeId=k.TypeId
			   GROUP BY p.typeid

			 ------3
			 INSERT INTO #LeftJoinTable (
			TypeId,
			RQty,
			CQty,
			Qty,
			Lendqty,
			Borrowqty,
			SaleOrderQty,
			BuyOrderQty,
			SaleReachQty,
			BuyReachQty
				)					
				SELECT 	a.typeid,
						0 AS RQty,
						0 AS CQty,
						0 AS qty,
						SUM(l.Lend-l.LendBack) AS Lendqty,
						SUM(l.Borrow-l.BorrowBack) AS  Borrowqty,
						0 AS SaleOrderQty,
						0 AS BuyOrderQty,
						0 AS SaleReachQty,
						0 AS BuyReachQty
				FROM 	V_LendStatus l 
					   inner join #tempPtype a on a.typeid=l.ptypeid
					   inner join #tempKtype k on l.ktypeid=k.typeid 
						GROUP BY a.typeid
				   
				-------4
				INSERT INTO #LeftJoinTable (
			TypeId,
			RQty,
			CQty,
			Qty,
			Lendqty,
			Borrowqty,
			SaleOrderQty,
			BuyOrderQty,
			SaleReachQty,
			BuyReachQty
		)	
				SELECT 	a.typeid,
						0 AS RQty,
						0 AS CQty,
						0 AS qty,
						0 AS LendQty,
						0 AS BorrowQty,
						CASE 
							WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN ISNULL(SUM(o.SaleOrderQty),0) 
							ELSE 0
						END AS SaleOrderQty,
						CASE
							WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN ISNULL(SUM(o.BuyOrderQty),0)
							ELSE 0
						END AS BuyOrderQty,
						CASE 
							WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN SUM(o.SaleReachQty) 
							ELSE 0
						END AS SaleReachQty,
						CASE
							WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN SUM(o.BuyReachQty)
							ELSE 0
						END AS BuyReachQty				 
				FROM 	v_VirtualStockOrderStatus o
						inner join #tempPtype a on a.typeid=o.ptypeid
						inner join #tempKtype k on o.KTypeId=k.typeid GROUP BY a.typeid
						
			  ------统计
			  SELECT	a.typeid,
					ISNULL(SUM(o.qty),0) AS qty,
					ISNULL(SUM(o.Lendqty),0) AS Lendqty,
					ISNULL(SUM(o.Borrowqty),0) AS Borrowqty,
					ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.Borrowqty),0)-ISNULL(SUM(o.Lendqty),0) AS FactQty,
					ISNULL(SUM(o.RQty),0) AS RQty,
					ISNULL(SUM(o.CQty),0) AS CQty,
					ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.RQty),0)-ISNULL(SUM(o.CQty),0) AS KFHQty,
					CASE
						WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
						ELSE 0
					END AS BuyOrderQty,
					CASE 
						WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0) 
						ELSE 0
					END AS SaleOrderQty,
					CASE 
						WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0) 
						     THEN  ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
						WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  
							 THEN ISNULL(SUM(o.qty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
						WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0)  
							 THEN ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
						WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  
							 THEN ISNULL(SUM(o.qty),0)
					END AS SaleCanQty	
			INTO #result			
			FROM #tempPtype a 
			LEFT JOIN #LeftJoinTable o ON LEFT(o.typeid,LEN(a.typeid))=a.typeid
			GROUP BY a.typeid
			
			---选择结果
			SELECT p.typeId AS TypeId,UserCode,FullName,p.customitemid,p.customitemfrom,p.customitemname,p.customitemrefid,
				 CASE WHEN  Qty<0 THEN 0 
					  WHEN Qty IS NULL THEN 0
				 ELSE floor(Qty) END AS Qty 
			FROM 
			(
			SELECT typeid,isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0) as Qty 
			FROM #result
			) a 
			JOIN ptype p ON a.typeid=p.typeId
		END
	
END 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (SELECT * from dbo.sysobjects where id = object_id(N'[dbo].[EshopVirtualStockByItem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].EshopVirtualStockByItem
GO


/*
	作者：吕文琪
	日期：2013-08-28
	描述：单据库存分布表(不需要判断商品和仓库的权限范围) 从Web_BillStockDistributing上搬移
*/

CREATE    PROCEDURE EshopVirtualStockByItem
(
	@OperatorID 	varchar(100),   --操作员id
	@usercode		varchar(8000),	--商品code
	@Ktypeid	    VARCHAR(max),
	@Parid   			varchar(100)='00000',    --商品的父节点号
	@szKtypeId  		varchar(8000)='',         --仓库id号
	@sortfield 			varchar(20),            --按何种方式排序
	@EntryCode			varchar(200),			--商品条码
	@Standard			varchar(200),			--商品规格
	@Type				varchar(200),			--商品型号
	@Area				varchar(200),			--商品产地
	@virtualqtysql  VARCHAR(max)='isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0)',
	@ItemID  VARCHAR(50) ='',
	@IsCombined  VARCHAR(50) =''
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

DECLARE @PTypeId varchar(100)
select @PTypeId=typeid from ptype where UserCode=@usercode


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------



DECLARE @SQL varchar(MAX)  

--- 虚拟库存

--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
        @Lendqty NVARCHAR(2000),
        @Borrowqty NVARCHAR(2000),
		@RQty NVARCHAR(2000),
		@CQty NVARCHAR(2000),
		@BuyOrderQty NVARCHAR(2000),
		@BuyReachQty NVARCHAR(2000),
		@SaleOrderQty NVARCHAR(2000),
		@SaleReachQty NVARCHAR(2000),
		@UnitRate NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
		@BaseUnitName NVARCHAR(2000),
        @temptable  NVARCHAR(2000),
         @temptable1 NVARCHAR(2000)
SET @temptable=' inner JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') c ON o.ptypeID=c.typeID'
SET @temptable1=' LEFT JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') c ON a.typeID=c.typeID'

SELECT  @Qty='o.Qty',
		@Lendqty='o.Lendqty',
		@Borrowqty='o.Borrowqty',   
		@BuyReachQty='o.BuyReachQty', 
		@RQty='o.RQty',        
		@CQty='o.CQty',        
		@BuyOrderQty='o.BuyOrderQty', 
		@BuyReachQty='o.BuyReachQty', 
		@SaleOrderQty='o.SaleOrderQty',
		@SaleReachQty='o.SaleReachQty',
		@UnitRate = 'c.baseUnitRate',
		@UnitName = 'c.baseunitfullname',
		@BaseUnitName = 'c.baseunitfullname'

--------多单位计算End---------
-----------------------------------------------------------------------------------------------------------------------------


--商品
CREATE TABLE #GetManPTypeId
(
	TypeId			varchar(100)
)
CREATE UNIQUE CLUSTERED INDEX [Ptypeidx] ON [dbo].[#GetManPTypeId] 
(
	[typeId]
)

SELECT @SQL='INSERT INTO #GetManPTypeId SELECT p.typeId FROM 
             ptype p INNER JOIN F_GetManDetailPType('''+@OperatorID+''') mp	ON mp.TypeId=p.typeId WHERE 1=1 and p.typeid<>''0000'''
        
        IF @EntryCode<>''
		SELECT @SQL = @SQL +'   AND ISNULL(p.EntryCode,'''') LIKE '+CHAR(39)+'%'+@EntryCode+'%'+CHAR(39)+''		
		IF @Standard<>''
		SELECT @SQL = @SQL +' AND ISNULL(p.Standard,'''')  LIKE '+CHAR(39)+'%'+@Standard+'%'+CHAR(39)+''
		IF @Type<>''
		SELECT @SQL = @SQL +' AND ISNULL(p.[Type],'''')  LIKE '+CHAR(39)+'%'+@Type+'%'+CHAR(39)+''
		IF @Area<>''
		SELECT @SQL = @SQL +' AND ISNULL(p.Area,'''')  LIKE '+CHAR(39)+'%'+@Area+'%'+CHAR(39)+''
EXEC(@SQL)			


--仓库
DECLARE @StypeID VARCHAR(50)    SET @StypeID=(SELECT Value FROM dbo.EshopBaseInfo WHERE Field='StypeItem')     						--分支机构 V3为00001
	IF @StypeID='' OR @StypeID IS NULL
		BEGIN
			RAISERROR('请配置分支机构',16,1)
			RETURN
		END
	DECLARE @Type1 VARCHAR(50)       SET @Type1=(SELECT Value FROM dbo.EshopBaseInfo WHERE Field='StockItem') 
	IF @Type1='' OR @Type1 IS NULL
		BEGIN
			RAISERROR('请配置商品数量更新方式',16,1)
			RETURN
		END
	------要查询的仓库
	CREATE TABLE #GetManKTypeId
	(
		typeid VARCHAR(50)
	)
	IF @Ktypeid=''    
		INSERT INTO #GetManKTypeId (typeid) SELECT typeId FROM Stock WHERE deleted=0 AND sonnum=0 AND typeid<>'00000' AND STypeID=@StypeID
	ELSE 
		INSERT INTO #GetManKTypeId  (typeid) 
		SELECT DISTINCT s.typeId
		FROM dbo.f_split(@Ktypeid,',') f 
		JOIN dbo.Stock s ON s.TYPEID LIKE f.a+'%' AND s.SONNUM=0 AND s.DELETED=0 
     



--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)



CREATE TABLE #GetManPTypeAll
(
	TypeId			varchar(100),
	FullName        varchar(200),
	UserCode        varchar(100),
	EntryCode		varchar(100),
	[Standard]		varchar(100),
	[Type]			varchar(20),
	Area			varchar(30),
	Sonnum          int,
	Leveal          int,
	Parid           varchar(200),
	unit1           varchar(100),
	unit2           varchar(100),
	unitrate1       varchar(100)
)

CREATE UNIQUE CLUSTERED INDEX [PtypeAllidx] ON [dbo].[#GetManPTypeAll] 
(
	[typeId]
)

SET @SQL='INSERT INTO #GetManPTypeAll SELECT P.TypeId,P.FullName,P.UserCode,P.EntryCode,P.Standard,P.Type,P.Area,P.Sonnum,P.Leveal,
         P.Parid,P.unit1,P.unit2,P.unitrate1 FROM F_GetManPTypeAll('''+@OperatorID+''') P --;SELECT * FROM #GetManPTypeAll'

--SELECT * INTO #GetManPTypeAll FROM F_GetManPTypeAll(@OperatorID)
EXEC(@SQL)

--RETURN

DECLARE @MMPtypeid VARCHAR(100)
SET @MMPtypeid=''

IF LEFT(@parid,len(@MMPtypeid))<>@MMPtypeid SET @parid=LEFT(@MMPtypeid,len(@MMPtypeid)-5)
IF @Parid='' SET @Parid='00000'   ---肖伟 2002-06-27加速库存状况查询,并补漏:
                                  ---如果某操作员设置了权限,并浏览第一层,那么此时的Parid='',什么商品都看不到

IF @szKtypeId='' OR @szKtypeId='00000'   SELECT @szKtypeId='%'	-- 全部仓库
		
CREATE TABLE #DGS
(
	PTypeId		varchar(100),
	RQty		 NUMERIC(24, 10) ,
	CQty		 NUMERIC(24, 10) ,
	TypeId      varchar(100)
)


--草稿库存

--计算普通单据草稿库存
SELECT	BillNumberId,
		BillType,
		KTypeId,
		KTypeId2
INTO	#BillIndex
FROM	BillIndex
WHERE	BillType IN (34,6,161,11,45,160,17,21,16,9,14,144,146,140,142,305,126,139,183,187,188,201,202)
		AND Draft = 1
		AND IfWx = 0


--维修单据草稿库存
SELECT	BillNumberId,
		BillType,
		KTypeId,
		KTypeId2
INTO	#WxBillIndex
FROM	BillIndex
WHERE	BillType IN (166,168,172,173,174,178,191,196,197)
		AND Draft = 1

INSERT INTO #DGS
(
	PTypeId,
	RQty,
	CQty,
	TypeId
)
SELECT	B.PTypeId,
		ISNULL(SUM(B.RQty),0) AS RQty,
		ISNULL(SUM(B.CQty),0) AS CQty,
		B.TypeId
FROM	
(
	SELECT PTypeId,RQty,CQty,KTypeId FROM GoodsStocks_Draft WHERE PtypeId=@PTypeId AND ItemID=@ItemID AND IsCombined=@IsCombined
)B INNER JOIN #GetManPTypeId P ON P.TypeId=B.PtypeId
INNER JOIN #GetManKTypeId K ON B.TypeId = K.TypeId
GROUP BY B.PTypeId,B.TypeId

CREATE TABLE #LeftJoinTable
(
	TypeId			 VARCHAR(50),
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	Qty				 NUMERIC(24, 10) ,
	Lendqty			 NUMERIC(24, 10) ,
	Borrowqty		 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) ,
	SaleReachQty	 NUMERIC(24, 10) ,
	BuyReachQty		 NUMERIC(24, 10) ,
	KTypeId         VARCHAR(50)
)

SELECT @SQL='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	KTypeId
	
)
		SELECT	o.PTypeId AS TypeId,
				'+@RQty+',
				'+@CQty+',
				0 AS Qty,
				0 AS Lendqty,
				0 AS Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty,
				0 AS SaleReachQty,
				0 AS BuyReachQty,
				o.TypeId AS KTypeId
		FROM	#DGS o'+ @temptable	
EXEC (@SQL)
		
SELECT @sql ='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	KTypeId
)		
		
		SELECT 	p.typeid,
				0 AS RQty,
				0 AS CQty,
				SUM('+@qty+') AS qty,
				0 AS Lendqty,
				0 AS Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty,
				0 AS SaleReachQty,
				0 AS BuyReachQty,
				k.TypeId
        FROM 	GOODSSTOCKS_QTY o 
                inner join #GetManPTypeID p on p.typeid=o.ptypeid and o.ptypeid='''+@PTypeId+''' and o.itemid='''+@ItemID+''' and o.IsCombined='''+@IsCombined+'''
				inner join #GetManKTypeId k on o.KTypeId=k.TypeId'+ @temptable
		IF @parid = '00000'
			SELECT @SQL = @SQL +' WHERE 1=1'
		ELSE
			SELECT @SQL = @SQL +' WHERE o.ptypeid LIKE '''+@parid+'%'''
			
		SELECT @SQL=@SQL+' GROUP BY p.typeid,k.TypeId'
EXEC (@SQL)		
		
SELECT @sql ='		
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	KTypeId
)					
        SELECT 	a.typeid,
				0 AS RQty,
				0 AS CQty,
				0 AS qty,
				SUM(o.Lend-o.LendBack)/'+@UnitRate+' AS Lendqty,
				SUM(o.Borrow-o.BorrowBack)/'+@UnitRate+' AS  Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty,
				0 AS SaleReachQty,
				0 AS BuyReachQty,
				k.typeid
		FROM 	V_LendStatus o 
		       inner join #GetManPTypeID a on a.typeid=o.ptypeid and o.ptypeid='''+@PTypeId+''' and o.itemid='''+@ItemID+''' and o.IsCombined='''+@IsCombined+'''
		       inner join #GetManKTypeId k on o.ktypeid=k.typeid' + @temptable+'
				 GROUP BY a.typeid,k.TypeId,'+@UnitRate
EXEC (@SQL)		
				
SELECT @sql ='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty,
	SaleReachQty,
	BuyReachQty,
	KTypeId
)	
        SELECT 	a.typeid,
				0 AS RQty,
				0 AS CQty,
				0 AS qty,
				0 AS LendQty,
				0 AS BorrowQty,
				CASE 
					WHEN ISNULL(SUM('+@SaleOrderQty+'),0)-ISNULL(SUM('+@SaleReachQty+'),0)>=0 THEN ISNULL(SUM('+@SaleOrderQty+'),0) 
					ELSE 0
				END AS SaleOrderQty,
				CASE
					WHEN ISNULL(SUM('+@BuyOrderQty+'),0)-ISNULL(SUM('+@BuyReachQty+'),0)>=0 THEN ISNULL(SUM('+@BuyOrderQty+'),0)
					ELSE 0
				END AS BuyOrderQty,
				CASE 
					WHEN ISNULL(SUM('+@SaleOrderQty+'),0)-ISNULL(SUM('+@SaleReachQty+'),0)>=0 THEN SUM('+@SaleReachQty+') 
					ELSE 0
				END AS SaleReachQty,
				CASE
					WHEN ISNULL(SUM('+@BuyOrderQty+'),0)-ISNULL(SUM('+@BuyReachQty+'),0)>=0 THEN SUM('+@BuyReachQty+')
					ELSE 0
				END AS BuyReachQty,
				k.typeid		 
        FROM 	v_VirtualStockOrderStatus o
				inner join #GetManPTypeID a on a.typeid=o.ptypeid and o.ptypeid='''+@PTypeId+''' and o.itemid='''+@ItemID+''' and o.IsCombined='''+@IsCombined+'''
				inner join #GetManKTypeId k on o.KTypeId=k.typeid '+ @temptable
					

	SELECT @SQL=@SQL+' GROUP BY a.typeid,k.TypeId'
--print(@SQL)
EXEC(@SQL)

SELECT @SQL='
	SELECT	a.typeid,
			a.fullname,
			a.usercode,
			a.EntryCode,
			a.Standard,
			a.Type,
			a.Area,
			a.sONnum,
			a.leveal,
			a.parid,
			a.unit1,
			a.unit2,
			a.unitrate1,
			ISNULL(SUM(o.qty),0) AS qty,
			ISNULL(SUM(o.Lendqty),0) AS Lendqty,
			ISNULL(SUM(o.borrowqty),0) AS Borrowqty,
			ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.borrowqty),0)-ISNULL(SUM(o.lendqty),0) AS FactQty,
			ISNULL(SUM(o.rqty),0) AS RQty,
			ISNULL(SUM(o.cqty),0) AS CQty,
			ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.rqty),0)-ISNULL(SUM(o.cqty),0) AS KFHQty,
			CASE
				WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
				ELSE 0
			END AS BuyOrderQty,
			CASE 
				WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0) 
				ELSE 0
			END AS SaleOrderQty,
			CASE 
				WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0) THEN  ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
				WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  THEN ISNULL(SUM(o.qty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
				WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0)  THEN ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
				WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  THEN ISNULL(SUM(o.qty),0)
			END AS SaleCanQty,
			case when a.Sonnum>0 then null else   '+@UnitName+' end AS unitname,
			case when a.Sonnum>0 then null else   '+@BaseUnitName+' end AS baseunitname,
			case when a.Sonnum>0 then null else  '+@UnitRate+' end AS unitrate,
			o.KTypeId
	INTO #result			
	FROM #GetManPTypeAll a 
	LEFT JOIN #LeftJoinTable o ON LEFT(o.typeid,LEN(a.typeid))=a.typeid '+ @temptable1
	+	
	' where	a.typeid= '''+@PTypeId+''''			

SELECT @SQL = @SQL +' 
	GROUP BY	a.typeid,
				a.fullname,
				a.usercode,
				a.EntryCode,
				a.Standard,
				a.Type,
				a.Area,
				a.sONnum,
				a.leveal,
				a.parid,
				a.unit1,
				a.unitrate1,
				a.unit2,
				o.KTypeId,	
			case when a.Sonnum>0 then null else '+@UnitName+' end,
			case when a.Sonnum>0 then null else	 '+@BaseUnitName+' END,
			case when a.Sonnum>0 then null else '+@UnitRate+' END '
IF @sortfield<>'' SELECT @SQL=@SQL+' ORDER BY a.fullname' ELSE SELECT @SQL=@SQL+' ORDER BY a.usercode'




--PRINT @sql
EXEC(@SQL)



--SET @SQL=@SQL+'
--		SELECT
--			*,
--			'+@virtualqtysql+' as virtualqty 
--		FROM
--			#result
		
--		'	
--EXEC(@SQL)




--  虚拟库存




CREATE TABLE #TempPType
(
	PTypeID 	VARCHAR(50),
	配件编号		VARCHAR(100)	DEFAULT '',
	配件名称		VARCHAR(100)	DEFAULT '',
	图号			VARCHAR(100)	DEFAULT '',
	AutoID		INT IDENTITY (1, 1) NOT NULL
)

--处理商品
DECLARE 
		@PTypeIds 		varchar(8000),
		@x				INT

SET @PTypeID = RTRIM(LTRIM(@PTypeID))
SET @x = charindex('|',@PTypeID)

IF @x=0
BEGIN
	INSERT #TempPType(PTypeID)
	SELECT @PTypeID
END
ELSE
BEGIN
	WHILE @x>=1
	BEGIN
		SET @PTypeIds = LEFT(@PTypeID,@x-1)
		IF NOT EXISTS(SELECT PTypeID FROM #TempPType WHERE PTypeID=@PTypeIDs)
		BEGIN
			INSERT #TempPType(PTypeID)		
			SELECT @PTypeIDs
		END
		
		SET @PTypeID=SUBSTRING(@PTypeID,@x+1,LEN(@PTypeID)-@x)

		SET @x=charindex('|',@PTypeID)
		
		IF @x=0
		BEGIN
			IF NOT EXISTS(SELECT PTypeID FROM #TempPType WHERE PTypeID=@PTypeID)
			BEGIN
				INSERT #TempPType(PTypeID)		
				SELECT @PTypeID
			END
		END
	END
END



UPDATE	#TempPType
SET		配件名称=b.FullName,配件编号=b.UserCode,图号=b.DwgNo
FROM	PType b
WHERE #TempPType.PTypeID=b.TypeID


DECLARE 
		@resSql		varchar(MAX)
		


	
SET @SQL=@SQL+'
SELECT c.TypeID,c.FullName,c.UserCode,SUM(gq.Qty) AS Qty,
 (select  '+@virtualqtysql+'  from #result where typeid=a.PTypeID and KTypeId=b.KTypeID) AS virtualqtysql
FROM  #TempPType a
INNER JOIN  vWeb_StockDistributing_1 b ON a.PTypeID=b.PTypeID
INNER JOIN Stock c	ON b.KTypeID=c.TypeID AND a.PTypeID=b.PTypeID
INNER JOIN #GetManKTypeId k on k.TypeID=c.TypeID
INNER JOIN #GetSelectSTypeId ss ON c.STypeID=ss.TypeId
LEFT JOIN GOODSSTOCKS_QTY gq ON a.PTypeID=gq.PTypeID AND gq.itemid='''+@ItemID+''' and gq.IsCombined='''+@IsCombined+'''
' + CASE WHEN @Ktypeid <> '' THEN ' and gq.KTypeID = '''+ @Ktypeid + '''' ELSE '' END + '
WHERE	c.SonNum=0 
		--AND c.STypeID=@stypeid
GROUP BY a.PTypeID,c.TypeID,c.FullName,c.UserCode,b.KTypeID
HAVING SUM(b.Qty)<>0
ORDER BY c.UserCode'


print(@SQL)
EXEC(@SQL)



DROP TABLE #GetSelectSTypeId
DROP TABLE #DGS,#GetManKTypeId,#GetManPTypeId,#GetManPTypeAll,#LeftJoinTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/*------------------------------------------
	作者:董湛
	日期:2013-03-22
	描述：商品数量上传，根据仓库分布，获取商品对应的虚拟库存
-------------------------------------------*/

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_EshopVirtualStockByKtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [dbo].[Web_EshopVirtualStockByKtype]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE Web_EshopVirtualStockByKtype
--@encode$--
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @StypeID VARCHAR(50)    SET @StypeID=(SELECT Value FROM dbo.EshopBaseInfo WHERE Field='StypeItem')     						--分支机构 V3为00001
	IF @StypeID='' OR @StypeID IS NULL
		BEGIN
			RAISERROR('请配置分支机构',16,1)
			RETURN
		END
	DECLARE @Type VARCHAR(50)       SET @Type=(SELECT Value FROM dbo.EshopBaseInfo WHERE Field='StockItem') 
	IF @Type='' OR @Type IS NULL
		BEGIN
			RAISERROR('请配置商品数量更新方式',16,1)
			RETURN
		END
	------要查询的仓库
	CREATE TABLE #tempKtype
	(
		typeid VARCHAR(50)
	)
	INSERT INTO #tempKtype (typeid) SELECT typeId FROM Stock WHERE deleted=0 AND sonnum=0 AND typeid<>'00000' AND STypeID=@StypeID
		
		
	----要查询的商品
	CREATE TABLE #tempPtype
	(
		typeid varchar(50)
	)
	INSERT INTO #tempPtype (typeid) SELECT typeid FROM ptype WHERE sonnum=0 AND deleted=0

    IF @Type='stock'    ---实际库存
		BEGIN
			SELECT p.typeId AS TypeId,UserCode,FullName,Ktypeid,
				 CASE WHEN  Qty<0 THEN 0 
					  WHEN Qty IS NULL THEN 0
				 ELSE floor(Qty) END AS Qty 
			FROM #tempPtype t LEFT JOIN 
			(
			    SELECT p.typeid AS typeid,k.typeid AS ktypeid, ISNULL(SUM(Qty),0) AS Qty  
				FROM #tempPtype p
				JOIN  dbo.GoodsStocks gs ON gs.PtypeId=p.typeid
				JOIN #tempKtype k ON gs.KtypeId=k.typeid
				GROUP BY p.typeid,k.typeid
			) a 
			ON a.typeid=t.typeId
			JOIN ptype p ON t.typeid=p.typeId
		END
    ELSE                ---虚拟库存
		BEGIN
			--计算普通单据草稿库存
			SELECT	BillNumberId,
					BillType,
					KTypeId,
					KTypeId2
			INTO	#BillIndex
			FROM	BillIndex
			WHERE	BillType IN (34,6,161,11,45,160,17,21,16,9,14,144,146,140,142,305,126,139,183,187,188,201,202)
					AND Draft = 1
					AND IfWx = 0


			--维修单据草稿库存
			SELECT	BillNumberId,
					BillType,
					KTypeId,
					KTypeId2
			INTO	#WxBillIndex
			FROM	BillIndex
			WHERE	BillType IN (166,168,172,173,174,178,191,196,197)
					AND Draft = 1
				--数据临时表
			CREATE TABLE #DGS
			(
				PTypeId		varchar(100),
				ktypeid		VARCHAR(50),
				RQty		 NUMERIC(24, 10) ,
				CQty		 NUMERIC(24, 10) 
			)


			INSERT INTO #DGS
			(
				PTypeId,
				Ktypeid,
				RQty,
				CQty
			)
			SELECT	B.PTypeId,
					B.Ktypeid,
					ISNULL(SUM(B.RQty),0) AS RQty,
					ISNULL(SUM(B.CQty),0) AS CQty
			FROM dbo.GoodsStocks_Draft B JOIN #tempPtype P ON P.TypeId=B.PtypeId  
			INNER JOIN #tempKtype K ON K.TypeId=B.KtypeId
			GROUP BY B.PtypeId,B.KTypeID
					
				
				---统计数据临时表
				CREATE TABLE #LeftJoinTable
			(
				TypeId			 VARCHAR(50),
				KTypeId			 VARCHAR(50),
				RQty			 NUMERIC(24, 10) ,
				CQty			 NUMERIC(24, 10) ,
				Qty				 NUMERIC(24, 10) ,
				Lendqty			 NUMERIC(24, 10) ,
				Borrowqty		 NUMERIC(24, 10) ,
				SaleOrderQty	 NUMERIC(24, 10) ,
				BuyOrderQty		 NUMERIC(24, 10) ,
				SaleReachQty	 NUMERIC(24, 10) ,
				BuyReachQty		 NUMERIC(24, 10) 
			)
			
			-----1
			INSERT INTO #LeftJoinTable (
			TypeId,
			KTypeId,
			RQty,
			CQty,
			Qty,
			Lendqty,
			Borrowqty,
			SaleOrderQty,
			BuyOrderQty,
			SaleReachQty,
			BuyReachQty
			)
				SELECT	s.PTypeId AS TypeId,
						s.Ktypeid,
						RQty,
						CQty,
						0 AS Qty,
						0 AS Lendqty,
						0 AS Borrowqty,
						0 AS SaleOrderQty,
						0 AS BuyOrderQty,
						0 AS SaleReachQty,
						0 AS BuyReachQty
				FROM	#DGS s
				
			-----2
			INSERT INTO #LeftJoinTable (
			TypeId,
			KTypeId,
			RQty,
			CQty,
			Qty,
			Lendqty,
			Borrowqty,
			SaleOrderQty,
			BuyOrderQty,
			SaleReachQty,
			BuyReachQty
			)		
				SELECT 	p.typeid,
						g.KtypeId,
						0 AS RQty,
						0 AS CQty,
						SUM(g.qty) AS qty,
						0 AS Lendqty,
						0 AS Borrowqty,
						0 AS SaleOrderQty,
						0 AS BuyOrderQty,
						0 AS SaleReachQty,
						0 AS BuyReachQty
				FROM 	goodsstocks g 
						inner join #tempPtype p on p.typeid=g.ptypeid
						inner join #tempKtype k on g.KTypeId=k.TypeId
			   GROUP BY p.typeid,g.KtypeId

			 ------3
			 INSERT INTO #LeftJoinTable (
			TypeId,
			KTypeId,
			RQty,
			CQty,
			Qty,
			Lendqty,
			Borrowqty,
			SaleOrderQty,
			BuyOrderQty,
			SaleReachQty,
			BuyReachQty
				)					
				SELECT 	a.typeid,
						l.kTypeID,
						0 AS RQty,
						0 AS CQty,
						0 AS qty,
						SUM(l.Lend-l.LendBack) AS Lendqty,
						SUM(l.Borrow-l.BorrowBack) AS  Borrowqty,
						0 AS SaleOrderQty,
						0 AS BuyOrderQty,
						0 AS SaleReachQty,
						0 AS BuyReachQty
				FROM 	V_LendStatus l 
					   inner join #tempPtype a on a.typeid=l.ptypeid
					   inner join #tempKtype k on l.ktypeid=k.typeid 
						GROUP BY a.typeid,l.kTypeID
				   
				-------4
				INSERT INTO #LeftJoinTable (
			TypeId,
			KTypeId,
			RQty,
			CQty,
			Qty,
			Lendqty,
			Borrowqty,
			SaleOrderQty,
			BuyOrderQty,
			SaleReachQty,
			BuyReachQty
		)	
				SELECT 	a.typeid,
						k.typeid,
						0 AS RQty,
						0 AS CQty,
						0 AS qty,
						0 AS LendQty,
						0 AS BorrowQty,
						CASE 
							WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN ISNULL(SUM(o.SaleOrderQty),0) 
							ELSE 0
						END AS SaleOrderQty,
						CASE
							WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN ISNULL(SUM(o.BuyOrderQty),0)
							ELSE 0
						END AS BuyOrderQty,
						CASE 
							WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN SUM(o.SaleReachQty) 
							ELSE 0
						END AS SaleReachQty,
						CASE
							WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN SUM(o.BuyReachQty)
							ELSE 0
						END AS BuyReachQty				 
				FROM 	v_VirtualStockOrderStatus o
						inner join #tempPtype a on a.typeid=o.ptypeid
						inner join #tempKtype k on o.KTypeId=k.typeid GROUP BY a.typeid,k.typeid
						
			  ------统计
			  SELECT	a.typeid,
						o.ktypeid,
					ISNULL(SUM(o.qty),0) AS qty,
					ISNULL(SUM(o.Lendqty),0) AS Lendqty,
					ISNULL(SUM(o.Borrowqty),0) AS Borrowqty,
					ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.Borrowqty),0)-ISNULL(SUM(o.Lendqty),0) AS FactQty,
					ISNULL(SUM(o.RQty),0) AS RQty,
					ISNULL(SUM(o.CQty),0) AS CQty,
					ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.RQty),0)-ISNULL(SUM(o.CQty),0) AS KFHQty,
					CASE
						WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
						ELSE 0
					END AS BuyOrderQty,
					CASE 
						WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0) 
						ELSE 0
					END AS SaleOrderQty,
					CASE 
						WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0) 
							THEN  ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
						WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  
							THEN ISNULL(SUM(o.qty),0)-ISNULL(SUM(o.SaleOrderQty),0)+ISNULL(SUM(o.SaleReachQty),0)
						WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0)  
							THEN ISNULL(SUM(o.qty),0)+ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)
						WHEN (ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)<0 AND ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)<0)  
							THEN ISNULL(SUM(o.qty),0)
					END AS SaleCanQty	
			INTO #result			
			FROM #tempPtype a 
			LEFT JOIN #LeftJoinTable o ON LEFT(o.typeid,LEN(a.typeid))=a.typeid
			GROUP BY a.typeid,o.KTypeId
			
			
			---选择结果
			SELECT p.typeId AS TypeId,UserCode,FullName,Ktypeid,
				 CASE WHEN  Qty<0 THEN 0 
					  WHEN Qty IS NULL THEN 0
				 ELSE floor(Qty) END AS Qty 
			FROM 
			(
			SELECT typeid,ktypeid,isnull(qty,0)+isnull(buyorderqty,0)-isnull(saleorderqty,0)+isnull(rqty,0)-isnull(cqty,0) as Qty 
			FROM #result
			) a 
			JOIN ptype p ON a.typeid=p.typeId
		END
    
END 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ETypeGatherDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_ETypeGatherDetailQuery]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：黄飞佳	
	日期：2012-05-24
	描述：职员销售汇总明细
*/
/*
    修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
    
    修改：舒珊
    日期：2015-05-27
    描述： 添加商品类别筛选
    
    修改：舒珊
    日期：2016-06-21
    描述： 换算率变更前销售单位数量统计
*/
/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Web_ETypeGatherDetailQuery
(
	@chvStartDate		VARCHAR(30),			-- 查询起始时间
	@chvENDDate		    VARCHAR(30),			-- 查询结束时间
	@chvPTypeID			VARCHAR(max),			-- 树型表或线性表商品类别查询范围父节点 ID
	@chvBTypeID			VARCHAR(max),			-- 结算单位
	@chvETypeID			VARCHAR(max),			-- 树型表或线性表职员类别查询范围父节点 ID
	@chvKTypeID			VARCHAR(max),			-- 树型表或线性表仓库类别查询范围父节点 ID
	@chvDTypeID			VARCHAR(max),			-- 树型表或线性表部门类别查询范围父节点 ID
	@chvStypeID			VARCHAR(max)='00000',	-- 树型表或线性表分支机构类别查询范围父节点 ID
	@sortfield			VARCHAR(50),			-- 明细表排序方式
	@checkCode			VARCHAR(max)= '',	    -- 制单人编号
	@checkName			VARCHAR(max)= '',	    -- 制单人名称
	@chvOperatorID		VARCHAR(50),			-- 操作员 ID ( 作权限范围检查用 )
	@chkRed        		CHAR(1) ='0',		    -- 显示红冲单据
	@chvBilltype    	VARCHAR(200),           -- 单据类型
	@chvComment     	VARCHAR(200)='',        -- 说明
	@chvZY 				VARCHAR(200)='',        -- 摘要
	@dealbtypeid        VARCHAR(max),           -- 往来单位
	@chvPF        		CHAR(1) ='0'  ,          --价保获利反利等
	@ptypecategoryid VARCHAR(MAX)				 --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON

--------权限检查-Start--------
IF @chvOperatorID is null RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re <> 0 RETURN @Re
--------权限检查-End--------  


--------创建临时表-Start--------
--单据类型
CREATE TABLE #Billtype (BillType VARCHAR(200))
INSERT INTO #Billtype SELECT a AS Billtype FROM dbo.f_split(@chvBilltype,',')

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Ktype SELECT typeid,usercode,fullname FROM Stock WHERE  typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvKTypeID,4,@chvOperatorID))
IF (@chvKTypeID='10000' OR  @chvKTypeID='' OR  @chvKTypeID='00000') AND NOT EXISTS(SELECT * FROM #Ktype WHERE typeid='10000') 
INSERT INTO #Ktype SELECT '10000','10000','代销仓库'
	
--商品
CREATE TABLE #Ptype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200),SaleUnitId int)
INSERT INTO #Ptype SELECT typeid,usercode,fullname ,SaleUnitId FROM Ptype WHERE  typeid IN(SELECT typeid FROM  F_ManPTypeInCategoryID ( @chvOperatorID,@chvPTypeID,@ptypecategoryid))

--分支机构
CREATE TABLE #Stype (TypeID VARCHAR(50))
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvSTypeID,11,@chvOperatorID)

--结算单位	
CREATE TABLE #Btype (TypeID VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Btype SELECT typeid,usercode,fullname FROM Btype WHERE  typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBTypeID,2,@chvOperatorID))

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50))
INSERT INTO #DealBtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID)

--职员
CREATE TABLE #Etype (TypeID VARCHAR(50),UserCode VARCHAR(500),FullName VARCHAR(500))
INSERT INTO #Etype SELECT typeid,usercode,fullname FROM Employee WHERE  typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvETypeID,3,@chvOperatorID))

--部门
CREATE TABLE #Dtype (TypeID VARCHAR(50))
INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@chvOperatorID)

--费用分摊设置
DECLARE @config int=0
SELECT	@config=Value FROM Userconfig WHERE ConfigName='sharefee'	


--------创建索引Start-------
CREATE CLUSTERED INDEX CIX_GetManKTypeID ON #Ktype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManETypeID ON #Etype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManPTypeID ON #Ptype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManSTypeID ON #Stype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManBTypeID ON #Btype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManDTypeID ON #Dtype(TypeID)
--------创建索引End-------

--单据索引表
	CREATE TABLE #BillIndex
	(
	    BillNumberID NUMERIC(18,0),
	    BillCode VARCHAR(200),
	    BillDate DATETIME,
	    Billtype NUMERIC(10,0),
	    Tax  NUMERIC(24, 10) ,
	    RedWord INT,
		TotalMoney  NUMERIC(24, 10) ,
		TotalInMoney  NUMERIC(24, 10) ,
		CompleteTotal  NUMERIC(24, 10) ,
		BTypeID  VARCHAR (50),
		ETypeID  VARCHAR (50),
		PTypeID  VARCHAR (50),
		KTypeID  VARCHAR (50),
		PreferenceMoney  NUMERIC(24, 10) ,
		DtypeID VARCHAR(50),
		Checke  VARCHAR(50),
		Stypeid   VARCHAR(50),
		Draft BIT,
		Posttime DATETIME,
		Dealbtypeid VARCHAR(50),
		CName VARCHAR(200),
		Rate   NUMERIC(24, 10),
		Explain VARCHAR(MAX),
		comment VARCHAR(2000) 
	)

	DECLARE	@strBill   VARCHAR(MAX)
	SET @strBill = 
	             'INSERT INTO #BillIndex 
	              SELECT billnumberid,
	                     billcode,
	                     billdate,
	                     a.billtype,
	                     tax,
	                     redword,
	                     totalmoney,
	                     totalinmoney,
	                     completetotal,
	                     a.btypeid,
	                     a.etypeid,
	                     a.ptypeid,
	                     a.ktypeid,
	                     preferencemoney,
	                     a.dtypeid,
	                     checke,
	                     a.stypeid,
	                     a.draft,
	                     a.posttime,
	                     a.dealbtypeid,
	                     cc.fullname,
	                     a.rate,
	                     a.Explain,
	                     a.comment
	               FROM dbo.BillIndex a
	               INNER JOIN #Billtype b ON a.BillType = b.Billtype
	               INNER JOIN AC_Currency cc  ON a.cid = cc.cid
	               INNER JOIN #Etype e ON a.etypeid = e.TypeID
	               INNER JOIN #DealBtype dd ON a.dealbtypeid = dd.typeid'
	               IF (@chvBTypeID<>'' OR @MBTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF (@chvDTypeID<>'' OR @MDTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
	               IF (@chvSTypeID<>'' OR @MSTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0'''    
	               
	                --增加发票立账405
	              SET @strBill += '
					UNION ALL 
					SELECT billnumberid,billcode,billdate,a.billtype,tax,redword,TotalMoney,TotalMoney,completetotal,
					a.btypeid,a.etypeid,'''' AS ptypeid,'''' AS ktypeid,TotalMoney AS preferencemoney,a.dtypeid,checke,
					a.stypeid,a.draft,posttime,a.dealbtypeid,cc.fullname,a.rate,a.Explain,a.comment 
					FROM dbo.ReceiptBillIndex AS a 
					INNER JOIN #Billtype b ON a.BillType = b.Billtype
					INNER JOIN AC_Currency cc  ON a.cid = cc.cid 
					INNER JOIN #Etype e ON a.etypeid = e.TypeID
					INNER JOIN #DealBtype dd ON a.dealbtypeid = dd.typeid '   
				   IF (@chvBTypeID<>'' OR @MBTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF (@chvDTypeID<>'' OR @MDTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
	               IF (@chvSTypeID<>'' OR @MSTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0'''   
	EXEC(@strBill)
--红冲
DECLARE @RED_WHERE varchar(200)
SET @RED_WHERE= ''
IF @chkRed ='0'
	SET @RED_WHERE ='  b.Redword='+char(39)+'0'+char(39)
ELSE
	SET @RED_WHERE =' 1=1 '
	
-- 确定查询时间段
DECLARE @SQL_WHERE varchar(2000)
SELECT  @SQL_WHERE = ' AND b.BillDate >= ''' + @chvStartDate + '''' + ' AND b.BillDate <= ''' + @chvENDDate + ''''	
----出入库表
    CREATE TABLE #InoutStockTable
    (
		BillNumberId numeric(18, 0) ,
		BillDate datetime,
		BillType numeric(10,0),
		PtypeId varchar (50),
		KtypeId varchar (50),
		Qty  NUMERIC(24, 10) ,
		Price    NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		taxprice  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		tax  NUMERIC(24, 10) ,
		costPrice  NUMERIC(24, 10) ,
		ShareFee  NUMERIC(24, 10) ,
		Cargoid INT,
		NPrice  NUMERIC(24, 10) ,
		NTotal  NUMERIC(24, 10) ,
		SalePrice  NUMERIC(24, 10) ,
		NSalePrice  NUMERIC(24, 10) ,
		SaleTotal NUMERIC(24, 10) ,	
		NSaleTotal  NUMERIC(24, 10) ,
		NTaxPrice   NUMERIC(24, 10) ,
		NTaxTotal   NUMERIC(24, 10) ,
		FullName VARCHAR(MAX),
		UserCode VARCHAR(MAX),
		NQty  NUMERIC(24, 10) ,
		MUnitID INT,
		NumName VARCHAR(200),
		Rate  NUMERIC(24, 10) ,
		nbrcqty  NUMERIC(24, 10) ,
		BaseUnitFullname VARCHAR(MAX),
        AssistantFullname VARCHAR(MAX),
        GoodsNumber VARCHAR(100),
        efullname	VARCHAR(500),
        comment		VARCHAR(2000),
        CustomdetailID int ,
        zy    varchar (2000),
        DisCount    NUMERIC(24, 10)		
	)
	
DECLARE @strInOut VARCHAR(MAX)='
INSERT INTO #InoutStockTable
SELECT
BillnumberID,
BillDate,
BillType,
PtypeID,
KtypeID,
Qty,
price,
Total,
CostTotal,
taxprice,
TaxTotal,
tax,
costprice,
sharefee,
cargoid,
nprice,
ntotal,
SalePrice,
nsaleprice,
SaleTotal,	
nsaletotal,
ntaxprice,
ntaxtotal,
fullname,
usercode,
nqty,
munitid,
numname,
rate,
T.nbrcqty  AS nbrcqty,--换算率变更前销售单位数量
baseunitfullname,
assistantfullname,
goodsnumber,
efullname,
comment,
 CustomdetailID,
 zy, 
DisCount
FROM
(
	SELECT 
	a.BillnumberID,																														
	a.BillDate,																														
	a.BillType,																															
	a.PtypeID,																															
	a.KtypeID,
	a.Qty,
	a.price,
	a.Total,	  
	a.CostTotal,
	a.taxprice,  
	a.TaxTotal,
	a.tax,
	a.costprice,
	a.sharefee,
	a.cargoid,
	a.nprice,
	a.ntotal,
	a.SalePrice,
	a.nsaleprice,
	a.saletotal,
	a.nsaletotal,
	a.ntaxprice,
	a.ntaxtotal,
	v.fullname,
	e.usercode,
	a.nqty,
	a.munitid,
	pu.fullname AS numname,
	pe.rate AS rate,
	CAST(-a.qty/a.MUnitRate AS  NUMERIC(24, 10) )  AS nbrcqty,--换算率变更前销售单位数量
	fg.baseunitfullname AS baseunitfullname,
	fg.assistantfullname AS assistantfullname,
	a.goodsnumber,
	E.fullname as efullname,
	a.comment,
	a.id as CustomdetailID,
	b.comment as zy,
	a.DisCount
	FROM InoutStockTable a 
	INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID AND a.BillType = b.BillType 
	LEFT JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	left JOIN Ptype_units pu on pu.unitsid = a.munitid
	left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND pe.ptypeid = a.ptypeid
	left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	INNER JOIN #PType p ON a.PTypeID=p.typeid
	INNER JOIN #EType e ON e.typeid = b.etypeid'
	
	IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
	  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
	SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	IF (@checkCode<>'')
	  SET @strInOut = @strInOut + ' AND e.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	IF (@checkName<>'')
	  SET @strInOut = @strInOut + ' AND e.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	
	SET @strInOut += '
	AND A.BillType NOT IN(402,403,405) 
	
	UNION ALL
	--发出商品出库单
	SELECT
	a.BillnumberID,																														
	b.BillDate,																														
	b.BillType,																															
	a.PtypeID,																															
	a.KtypeID,
	CASE T.RedWord
		WHEN 2 THEN a.Qty - a.InvoiceQty
		ELSE -(a.Qty - a.InvoiceQty) 
	END AS Qty,
	a.DiscountPrice AS Price,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
	END AS Total,
	
	CASE T.RedWord
		WHEN 2 THEN a.CostTotal - a.InvoiceCostTotal
		ELSE -(a.CostTotal - a.InvoiceCostTotal)
	END AS CostTotal,
	a.taxprice,  

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
	END AS TaxTotal,
	
	a.tax,
	a.costprice,
	a.sharefee,
	a.cargoid,
	a.NDiscountPrice AS nprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice)  END
	END AS ntotal,
	a.SalePrice,
	a.nsaleprice,
	
	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.saletotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.saletotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
	END AS SaleTotal,
	
	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceNQty WHEN 0 THEN a.nsaletotal ELSE (a.NQty - a.InvoiceNQty) * a.NSalePrice END
		ELSE CASE a.InvoiceNQty WHEN 0 THEN -a.nsaletotal ELSE -((a.NQty - a.InvoiceNQty) * a.NSalePrice) END
	END AS nsaletotal,

	a.ntaxprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
	END AS ntaxtotal,
	
	v.fullname,
	e.usercode,
	CASE T.RedWord
		WHEN 2 THEN a.NQty - a.InvoiceNQty
		ELSE -(a.NQty - a.InvoiceNQty)
	END AS nqty,
	a.munitid,
	pu.fullname AS numname,
	pe.rate AS rate,
	a.Mqty-(a.InvoiceQty*a.MunitRate)  AS nbrcqty,--换算率变更前销售单位数量
	fg.baseunitfullname AS baseunitfullname,
	fg.assistantfullname AS assistantfullname,
	a.goodsnumber,
	E.fullname as efullname,
	a.comment,
	a.id as CustomdetailID,
	t.comment as zy,
	a.DisCount
	FROM SendBill AS A
	INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
	INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
	LEFT JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	left JOIN Ptype_units pu on pu.unitsid = a.munitid
	left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND pe.ptypeid = a.ptypeid
	left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	INNER JOIN #PType p ON a.PTypeID=p.typeid
	INNER JOIN #EType e ON e.typeid = b.etypeid
	'
	IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
	  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
	SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND b.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND b.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	IF (@checkCode<>'')
	  SET @strInOut = @strInOut + ' AND e.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	IF (@checkName<>'')
	  SET @strInOut = @strInOut + ' AND e.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
	SET @strInOut += ' 
	AND T.ifYearBill = 0
	
	UNION ALL
	--发出商品退货单
	SELECT
	a.BillnumberID,																														
	b.BillDate,																														
	b.BillType,																															
	a.PtypeID,																															
	a.KtypeID,
	CASE T.RedWord
		WHEN 2 THEN -(a.Qty - a.InvoiceQty)
		ELSE a.Qty - a.InvoiceQty
	END AS Qty,
	a.DiscountPrice AS Price,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
	END AS Total,
	
	CASE T.RedWord
		WHEN 2 THEN -(a.CostTotal - a.InvoiceCostTotal)
		ELSE a.CostTotal - a.InvoiceCostTotal
	END AS CostTotal,
	a.taxprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
	END AS TaxTotal,
	
	a.tax,
	a.costprice,
	a.sharefee,
	a.cargoid,
	a.NDiscountPrice AS nprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
	END AS ntotal,
	a.SalePrice,
	a.nsaleprice,
	
	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.saletotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.saletotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
	END AS saletotal,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceNQty WHEN 0 THEN -a.nsaletotal ELSE -((a.NQty - a.InvoiceNQty) * a.NSalePrice) END
		ELSE CASE a.InvoiceNQty WHEN 0 THEN a.nsaletotal ELSE (a.NQty - a.InvoiceNQty) * a.NSalePrice END
	END AS nsaletotal,
	
	a.ntaxprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
	END AS ntaxtotal,
	
	v.fullname,
	e.usercode,
	CASE T.RedWord
		WHEN 2 THEN -(a.NQty - a.InvoiceNQty)
		ELSE a.NQty - a.InvoiceNQty
	END AS nqty,
	a.munitid,
	pu.fullname AS numname,
	pe.rate AS rate,
	a.Mqty-(a.InvoiceQty*a.MunitRate) AS nbrcqty,--换算率变更前销售单位数量
	fg.baseunitfullname AS baseunitfullname,
	fg.assistantfullname AS assistantfullname,
	a.goodsnumber,
	E.fullname as efullname,
	a.comment,
	a.id as CustomdetailID   ,
	t.comment as zy,
	a.DisCount
	FROM SendBackBill AS A
	INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
	INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
	LEFT JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	left JOIN Ptype_units pu on pu.unitsid = a.munitid
	left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND pe.ptypeid = a.ptypeid
	left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	INNER JOIN #PType p ON a.PTypeID=p.typeid
	INNER JOIN #EType e ON e.typeid = b.etypeid
	'
	IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
	  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
	SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND b.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND b.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	IF (@checkCode<>'')
	  SET @strInOut = @strInOut + ' AND e.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	IF (@checkName<>'')
	  SET @strInOut = @strInOut + ' AND e.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
	SET @strInOut += ' 
	AND T.ifYearBill = 0
	
	UNION ALL
	--销售发货开票
	SELECT
	a.BillnumberID,																														
	b.BillDate,																														
	b.BillType,																															
	a.PtypeID,																															
	a.KtypeID,
	CASE T.RedWord
		WHEN 2 THEN a.Qty
		ELSE -a.Qty 
	END AS Qty,
	a.Price,
	CASE T.RedWord
		WHEN 2 THEN a.total
		ELSE -a.total 
	END AS total,
	CASE T.RedWord
		WHEN 2 THEN a.InvoiceCostTotal
		ELSE -a.InvoiceCostTotal
	END AS CostTotal,
	a.taxprice,  
	CASE T.RedWord
		WHEN 2 THEN a.TaxTotal
		ELSE -a.TaxTotal
	END AS TaxTotal,
	a.tax,
	a.InvoiceCostPrice AS costprice,
	0 AS sharefee,
	a.cargoid,
	a.NPrice AS nprice,
	CASE T.RedWord
		WHEN 2 THEN a.Ntotal
		ELSE -a.Ntotal
	END AS Ntotal,
	a.SalePrice,
	a.nsaleprice,
	
	CASE T.RedWord WHEN 2 THEN a.saletotal ELSE -a.saletotal END AS saletotal,
	CASE T.RedWord WHEN 2 THEN a.nsaletotal ELSE -a.nsaletotal END AS nsaletotal,
	a.ntaxprice,
	CASE T.RedWord
		WHEN 2 THEN a.ntaxtotal
		ELSE -a.ntaxtotal
	END AS ntaxtotal,
	v.fullname,
	e.usercode,
	CASE T.RedWord
		WHEN 2 THEN a.NQty
		ELSE -a.NQty
	END AS nqty,
	a.munitid,
	pu.fullname AS numname,
	pe.rate AS rate,
	a.MQty  AS nbrcqty,--换算率变更前销售单位数量
	fg.baseunitfullname AS baseunitfullname,
	fg.assistantfullname AS assistantfullname,
	a.goodsnumber,
	E.fullname as efullname,
	a.comment,
	a.id as CustomdetailID,
	t.comment as zy,
	a.DisCount
	FROM ReceiptBill AS A
	INNER JOIN ReceiptBillIndex AS T ON(A.BillnumberID = T.BillnumberID AND A.BillType = T.BillType)
	INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
	LEFT JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	left JOIN Ptype_units pu on pu.unitsid = a.munitid
	left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND pe.ptypeid = a.ptypeid
	left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	INNER JOIN #PType p ON a.PTypeID=p.typeid
	INNER JOIN #EType e ON e.typeid = b.etypeid
	'
	IF (@chvKTypeID<>'' OR @MKTypeID=-99999) 
	  SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid'
	SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND b.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND b.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	IF (@checkCode<>'')
	  SET @strInOut = @strInOut + ' AND e.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	IF (@checkName<>'')
	  SET @strInOut = @strInOut + ' AND e.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
	SET @strInOut += ' 
	AND T.ifYearBill = 0
	'
	  
SET @strInOut += '
) AS T '            
--********************************************************--
EXEC(@strInOut) 
declare  @insertTemp varchar(max)  
if @chvPF=1
begin 
   set @insertTemp = 'INSERT INTO #inoutstocktable(usercode,eFullName) 	SELECT 	
                                e.usercode,
                                e.fullname
						FROM 	billindex b 
						INNER JOIN PriceProtectBill a ON b.billnumberid = a.billnumberid
						INNER JOIN #Etype e On b.etypeid =e.typeid
						INNER JOIN #DealBtype dd ON B.dealbtypeid = dd.typeid'
		                IF  @chvBTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999  OR  @checkCode<>'' OR @checkName<>'' 
			                SET @insertTemp=@insertTemp+' inner Join #Btype bb	On bb.typeid =b.btypeid '+CHAR(13)
	    
		                IF  @chvDTypeID<>'' OR @MDTypeID=-99999 
			                SET @insertTemp=@insertTemp+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF  @chvStypeID<>''    OR @MStypeid=-99999 
			                SET @insertTemp=@insertTemp+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

		                    SET @insertTemp=@insertTemp+'	inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 AND '+@RED_WHERE+@SQL_WHERE
									
		                    SET @insertTemp = @insertTemp +' AND b.Billtype =''149'''
		
		                IF (@checkCode<>'')
		                    SET @insertTemp = @insertTemp + ' AND e.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		                IF (@checkName<>'')
		                    SET @insertTemp = @insertTemp + ' AND e.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		                IF(ISNULL(@chvComment,'')!='')
			                SET @insertTemp = @insertTemp +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		                IF(ISNULL(@chvZY,'')!='')
			                SET @insertTemp = @insertTemp +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
		                SET @insertTemp = @insertTemp +' AND b.ifYearBill=''0'' AND b.isini=0'
   EXEC(@insertTemp)
 set @insertTemp = 'INSERT INTO #inoutstocktable(usercode,eFullName) 	SELECT 	
                                e.usercode,
                                e.fullname
						FROM 	billindex b    
					INNER JOIN Advantage a ON b.billnumberid =a.billnumberid
					INNER JOIN #Etype e On b.etypeid =e.typeid'
					
					IF @chvBTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 OR  @checkCode<>'' OR @checkName<>'' 
						SET @insertTemp=@insertTemp+' inner Join #Btype bb	On bb.typeid =b.btypeid '+CHAR(13)
	                
					IF @chvDTypeID<>'' OR @MDTypeID=-99999 
						SET @insertTemp=@insertTemp+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	               
					IF @chvStypeID<>'' OR @MStypeid=-99999 
						SET @insertTemp=@insertTemp+' inner Join #Stype ss	On ss.typeid =b.stypeid '+CHAR(13)

					SET @insertTemp=@insertTemp+'	 inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 and  '+@RED_WHERE+@SQL_WHERE
							
			        SET @insertTemp = @insertTemp +' AND b.Billtype =''148'''
			
	                IF (@checkCode<>'')
		                SET @insertTemp = @insertTemp + ' AND e.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		            IF (@checkName<>'')
		                SET @insertTemp = @insertTemp + ' AND e.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		            IF(ISNULL(@chvComment,'')!='')
			            SET @insertTemp = @insertTemp +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		            IF(ISNULL(@chvZY,'')!='')
			            SET @insertTemp = @insertTemp +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
	                SET @insertTemp = @insertTemp +' AND b.ifYearBill=''0'' AND b.isini=0'
	                exec(@insertTemp)
   END             
--------创建临时表-End--------

--------价保、返利-Start--------

	
DECLARE @PRICE_SQL varchar(MAX)  --价保
SET     @PRICE_SQL ='
						SELECT 	b.billcode,	
						        b.stypeid,
								b.billtype,
								b.billdate,
								b.billnumberid,	
								b.btypeid,
								b.DealBTypeID,
								b.etypeid,
								b.dtypeid,
								b.ktypeid,
								null,
								p.typeid  as ptypeid,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								v.fullname as itemname,
								b.checke,
								cc.fullname,
								b.rate,
								null,
								null,
								null,
								null,
								null,
								null,
								0 AS antantotal,
								0 AS aqty,
								CASE WHEN b.redword = 2  THEN (-a.total)
								ELSE a.total
								END AS PriceTotal,
								CASE WHEN b.redword = 2 THEN (-a.qty)
								ELSE a.qty
								END AS pqty,
								null,
	                            e.usercode,
								2 AS Flag,
								null,
								null,
								a.goodsnumber,
								''价保执行单'' AS billtypename,
								b.redword,
								null,null,null,				
								 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null
						FROM 	billindex b 
						INNER JOIN PriceProtectBill a ON b.billnumberid = a.billnumberid
						left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
						INNER JOIN #Etype e On b.etypeid =e.typeid
						INNER JOIN #DealBtype dd ON B.dealbtypeid = dd.typeid  
						INNER JOIN AC_Currency cc  ON b.cid = cc.cid '

		                IF  @chvBTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999  OR  @checkCode<>'' OR @checkName<>'' 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Btype bb	On bb.typeid =b.btypeid '+CHAR(13)
	    
		                IF  @chvDTypeID<>'' OR @MDTypeID=-99999 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF  @chvStypeID<>''    OR @MStypeid=-99999 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

		                    SET @PRICE_SQL=@PRICE_SQL+'	inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 AND '+@RED_WHERE+@SQL_WHERE
									
		                    SET @PRICE_SQL = @PRICE_SQL +' AND b.Billtype =''149'''
		
		                IF (@checkCode<>'')
		                    SET @PRICE_SQL = @PRICE_SQL + ' AND e.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		                IF (@checkName<>'')
		                    SET @PRICE_SQL = @PRICE_SQL + ' AND e.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		                IF(ISNULL(@chvComment,'')!='')
			                SET @PRICE_SQL = @PRICE_SQL +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		                IF(ISNULL(@chvZY,'')!='')
			                SET @PRICE_SQL = @PRICE_SQL +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
		                SET @PRICE_SQL = @PRICE_SQL +' AND b.ifYearBill=''0'' AND b.isini=0'
		
---------------------------------------------------------------------------------------------------------------------	
		
DECLARE @ADTAN_SQL varchar(MAX)  --返利
SET @ADTAN_SQL ='
					 SELECT 	b.billcode,	
						        b.stypeid,
								b.billtype,
								b.billdate,
								b.billnumberid,	
								b.btypeid,
								b.DealBTypeID,
								b.etypeid,
								b.dtypeid,
								b.ktypeid,
								null,
								p.typeid  as ptypeid,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								v.fullname as itemname,
								b.checke,
								cc.fullname,
								b.rate,
								null,
								null,
								null,
								null,
								null,
								null,
							    CASE WHEN b.redword = 2 THEN -a.total
								ELSE a.total
								END AS antantotal,
								CASE WHEN b.redword = 2 THEN (-a.qty)
								ELSE a.qty
								END AS aqty,
								0 AS PriceTotal,
								0 AS pqty,
								null,
								e.usercode,
								2 AS Flag,
								null,
								null,
								a.goodsnumber,
								''返利执行单'' as billtypename,
								b.redword,
								null,null,null,				
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null
					FROM billindex b 
					INNER JOIN Advantage a ON b.billnumberid =a.billnumberid
					left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					INNER JOIN #Etype e On b.etypeid =e.typeid
						INNER JOIN #DealBtype dd ON B.dealbtypeid = dd.typeid  
					 INNER JOIN AC_Currency cc  ON b.cid = cc.cid  '
					
					IF @chvBTypeID<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999 OR  @checkCode<>'' OR @checkName<>'' 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Btype bb	On bb.typeid =b.btypeid '+CHAR(13)
	                
					IF @chvDTypeID<>'' OR @MDTypeID=-99999 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	               
					IF @chvStypeID<>'' OR @MStypeid=-99999 
						SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Stype ss	On ss.typeid =b.stypeid '+CHAR(13)

					SET @ADTAN_SQL=@ADTAN_SQL+'	 inner join #Ptype p On a.ptypeid =p.typeid WHERE  b.draft=0 and  '+@RED_WHERE+@SQL_WHERE
							
			        SET @ADTAN_SQL = @ADTAN_SQL +' AND b.Billtype =''148'''
			
	                IF (@checkCode<>'')
		                SET @ADTAN_SQL = @ADTAN_SQL + ' AND e.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		            IF (@checkName<>'')
		                SET @ADTAN_SQL = @ADTAN_SQL + ' AND e.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		            IF(ISNULL(@chvComment,'')!='')
			            SET @ADTAN_SQL = @ADTAN_SQL +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		            IF(ISNULL(@chvZY,'')!='')
			            SET @ADTAN_SQL = @ADTAN_SQL +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
	                SET @ADTAN_SQL = @ADTAN_SQL +' AND b.ifYearBill=''0'' AND b.isini=0'
--------价保、返利-End--------


----- 拼接头-商品编号、商品名Start-----
DECLARE  @head  VARCHAR(MAX)
SET @head= 
          'SELECT ''【''+a.usercode+''】''+isnull(a.efullname,''''),
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  a.usercode,
                  1 AS Flag,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  null,
                  NULL,
                  NULL,null,
                 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
				 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
				 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
				 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null
          FROM  #InoutstockTable a GROUP BY a.usercode,a.efullname' 
          
----- 拼接头-商品编号、商品名End-----
		   
-----业务SQL语句-Start-----
DECLARE @strSQL VARCHAR(MAX)
SET @strSQL = 
             'SELECT  b.billcode,
             		  b.stypeid,																	
	                  a.billtype,
	                  a.billdate,
                      a.billnumberid,
	                  b.btypeid,
	                  b.dealbtypeid,
	                  b.etypeid,
	                  b.dtypeid,
	                  a.ktypeid,																		
	                  a.cargoid,
	                  a.ptypeid,
	                  -(a.Qty)AS qty,
					  isnull(a.Price,0) AS price,
					  isnull(a.taxPrice,0) AS taxprice,
                      -(a.Total) AS total,
					  -(a.TaxTotal) AS taxtotal, 
					  -(taxtotal)-(-total) AS taxge,
					  isnull((b.Totalinmoney+isnull(b.completeTotal,0)),0) AS totalinmoney,
					  CASE ABS(a.Qty) 
						  WHEN 0 THEN 0
						  ELSE a.costprice
					  END costprice,
					  -(a.CostTotal) AS costtotal,
					  -(ISNULL(a.sharefee,0)) AS sharefee,
					  -(ISNULL(b.preferencemoney,0)) AS preferencemoney,
					  a.nprice,
					  -(a.ntotal) AS ntotal,
					  a.SalePrice,
					  a.nsaleprice,
					  -(a.saletotal) AS saletotal,
					  -(a.nsaletotal) AS nsaletotal,
					  a.ntaxprice,
					  -(a.ntaxtotal) AS ntaxtotal,
					  a.fullname as itemname,
					  b.checke,
					  b.cname,
					  b.rate,
					  -(a.nqty) AS nqty,
					  a.numname AS munit,
					  -(a.qty/a.rate) AS mqty,
					  CASE a.nbrcqty  WHEN  -(a.qty/a.rate) THEN NULL ELSE a.nbrcqty  END AS nbrcqty,
					  CASE '+CAST( @config AS VARCHAR)+' WHEN 1  THEN -(a.Total) - (-a.CostTotal) - (ISNULL(-a.sharefee,0)) ELSE  (-a.Total) - (-a.CostTotal) END AS maoli,
					    CASE a.Total WHEN 0 THEN 0 
					  ELSE 
					  (CASE '+CAST( @config AS VARCHAR)+' 
					  WHEN 1  THEN cast( (-(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0))) as 
NUMERIC(24, 10))/cast( -(a.total) as 
NUMERIC(24, 10))
                      ELSE cast( (-(a.Total) - (-a.CostTotal))as 
NUMERIC(24, 10))/cast(-(a.total)  as NUMERIC(24, 10))
                      END)*100
					  END AS maolilu,
					  CASE WHEN b.billtype IN (148,150) THEN -(a.total)
                      ELSE 0
                      END AS antantotal,
					  CASE WHEN b.billtype IN (148,150) THEN -(a.qty)
					  ELSE 0
					  END AS aqty,
					  CASE WHEN b.billtype IN (149,151) THEN -(a.total)
					  ELSE 0
					  END AS PriceTotal,
					  CASE WHEN b.billtype IN (149,151) THEN -(a.qty)
					  ELSE 0
					  END AS pqty,
					  b.posttime,
					  a.usercode,
					  2 AS Flag,
					  a.baseunitfullname,
					  a.assistantfullname,
					  a.goodsnumber,
					  CASE a.billtype
						WHEN 11		THEN ''销售出库单''
						WHEN 45		THEN ''销售退货单''
						WHEN 215	THEN ''零售退货单''
						WHEN 305	THEN ''零售单''
						WHEN 141	THEN ''委托结算单''
						WHEN 34 	THEN ''采购入库单''
						WHEN 6 		THEN ''采购退货单''
						WHEN 145	THEN ''受托代销结算单''
						WHEN 149	THEN ''价保执行单''
						WHEN 151	THEN ''获得价保执行单''
						WHEN 148	THEN ''返利执行单''
						WHEN 150	THEN ''获利执行单''
						WHEN 160	THEN ''销售换货单''
						WHEN 161	THEN ''采购换货单''
						WHEN 402	THEN ''发出商品出库单''
						WHEN 403	THEN ''发出商品退货单''
						WHEN 405	THEN ''销售发货开票''
						WHEN 12		THEN ''组合品销售出库单''
						WHEN 46		THEN ''组合品销售退货单''
					  END AS billtypename,
					  b.redword AS RedWord,
					  (-A.Ntaxtotal)-(-A.Ntotal) AS ntaxge,
					  a.comment,
					  b.Explain,
					  SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	,
					SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40,
				a.zy,
				a.DisCount
			  FROM #InoutStockTable a
			  INNER JOIN #BillIndex b ON a.BillNumberId = b.BillNumberID
			   left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid
			  '
			  ---筛选制单人
			  IF @checkCode <> '' OR @checkName <> ''
              IF NOT(@checkCode='10000' OR @checkName = '代销仓库')
                 --加‘10000’是查仓库的时候要包含代销仓库
				 SET @strSQL = @strSQL +' INNER JOIN (SELECT TypeID FROM Employee UNION SELECT ''10000'') AS T  ON b.Etypeid = T.TypeID'    
-----业务SQL语句-End-----
		 IF  @chvPF ='1' 
			    SELECT @strSQL = @strSQL +' UNION ALL ' +@PRICE_SQL +' UNION ALL ' + @ADTAN_SQL 
-----拼接尾-商品相关金额小计Start-----
DECLARE @tail VARCHAR(MAX);
SELECT @tail = 
       'WITH strSql AS
        ('+@strSQL+')
        SELECT * FROM strSql
        UNION ALL
        SELECT  NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                SUM(strSql.Qty),
                NULL,
                NULL,
                SUM(strSql.Total),
                SUM(strSql.Taxtotal),
                SUM(strSql.Taxge),
                NULL,
                NULL,
                SUM(strSql.CostTotal),
                SUM(strSql.sharefee),
                NULL,
                NULL,
                SUM(strSql.ntotal),
                NULL,
                NULL,
                SUM(strSql.saletotal),
                SUM(strSql.nsaletotal),
                NULL,
                SUM(strSql.ntaxtotal),
                NULL,
                NULL,
                NULL,
                NULL,
                SUM(strSql.nqty),
                NULL,
                SUM(strSql.mqty),
                SUM(strSql.nbrcqty),
                SUM(strSql.maoli),
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                strSql.usercode,
                3 AS Flag,
                NULL,
                NULL,
                NULL,
              ''小计'',
                NULL,
                SUM(strSql.ntaxge),NULL,
                NULL,
                 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                 NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,null
         FROM strSql
         GROUP BY strSql.usercode
         UNION ALL ' 
         +@head   
-----拼接尾-商品相关金额小计End-----
DECLARE @SQL_ORDER VARCHAR(MAX) 
SELECT  @SQL_ORDER = ' ORDER BY usercode,Flag'
+ CASE @sortfield
			WHEN 'ByDate_a'		THEN ', BillDate,Billcode'	-- 按日期排序
			WHEN 'ByBillNo_a'	THEN ', BillCode'		    -- 按单据编号排序
			WHEN 'ByBillType_a'	THEN ', BillType,BillDate'	-- 按单据类型排序
			WHEN 'ByBillID_a'	THEN ', posttime'			-- 按单据真实过帐顺序排序
			WHEN 'ByDate_d'		THEN ', Billdate DESC,Billcode DESC'
			WHEN 'ByBillNo_d'	THEN ', BillCode DESC'
			WHEN 'ByBillType_d'	THEN ', BillType DESC,BillDate'
			WHEN 'ByBillID_d'	THEN ', posttime DESC '
			ELSE ',posttime DESC '
			END
DECLARE @SQL VARCHAR(MAX)
SET @SQL =@tail + @SQL_ORDER
--IF  @chvPF ='1' 
--	SET @SQL =@SQL + ' UNION ALL ' +@PRICE_SQL+ ' UNION ALL' +@ADTAN_SQL 
--SET @SQL = @SQL + @SQL_ORDER
EXEC(@SQL)

DROP TABLE #Billtype,#Ptype,#Btype,#Etype,#Ktype,#Dtype,#Stype,#BillIndex,#DealBtype,#InoutStockTable	
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--exec Web_PTypeGatherDetailQuery @chvStartDate='2012-02-26',@chvENDDate='2012-10-12',@chvPTypeID='00000',@chvBTypeID='',@chvETypeID='',@chvKTypeID='',@chvDTypeID='',@chvStypeID='',@sortfield='',@checkCode='',@checkName='',@chvOperatorID='00001',@chkRed=0,@chvBilltype='11,45,305,141,160',@chvComment='',@chvZY='',@dealbtypeid=''






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_ExchangeDeal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_ExchangeDeal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2014-4-23
	描述：期末调率处理--需求虐我千百遍 最后SQL还是我初恋
-------------------------------------------*/
CREATE PROCEDURE Web_ExchangeDeal
(
	@StypeID		VARCHAR(50),
	@YingS			INT, --统计应收
	@YuS			INT, --统计应付
	@Currency		INT, --现金银行
	@IsZero			INT, --统计为0的
	@IsNoZero		INT, --统计不为0的
	@EtypeID		VARCHAR(50),
	@clientip		VARCHAR(200)='', --客户端IP
	@OperatorID		VARCHAR(50),
	@BillCode		VARCHAR(500) OUT
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


--检查是否有自动生成的凭证，且没有过账的，有则给出提示
IF EXISTS ( SELECT TOP 1 1 FROM BillIndex WHERE IsAuto = 1 AND BillType = 159 AND draft = 1 AND Stypeid = @StypeID)
BEGIN
	DECLARE @FullName VARCHAR(200)
	SELECT TOP 1 @FullName = FullName FROM SType WHERE TypeId = @StypeID
	IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
		RAISERROR('请先将分支机构【%s】以前系统生成的调汇业务凭证审核过账或删除，再进行本次调汇！',16,1,@FullName)
	ELSE	
		RAISERROR('请先将以前系统生成的调汇业务凭证审核过账或删除，再进行本次调汇！',16,1,@FullName)
		
	RETURN
END

--检查职员是否存在且没有停用
IF NOT EXISTS ( SELECT TOP 1 1 FROM dbo.employee WHERE typeId=@EtypeID AND deleted=0)
BEGIN
	RAISERROR('你选择的经手人不存在或者已停用！',16,1)
	RETURN
END
--检查分支机构是否存在且没有停用
IF NOT EXISTS ( SELECT TOP 1 1 FROM dbo.SType WHERE typeId=@stypeID AND deleted=0)
BEGIN
	RAISERROR('你选择的分支机构不存在或者已停用！',16,1)
	RETURN
END


--货币，收付存数据的地方
CREATE TABLE #ResultDeatil
(
	ID				INT IDENTITY(1,1),
	TypeATypeID		VARCHAR(50),
	ATypeID			VARCHAR(50),
	ExTotal			 NUMERIC(24, 10) ,
	CID				NUMERIC(18,0),
	Rate			 NUMERIC(24, 10) ,
	Flag			INT		--1=货币资金,2=预收39 预付27  3=应收33 应付35
)

--最后存数据的地方
CREATE TABLE #ResultSumData
(
	ID				INT IDENTITY(1,1),
	TypeATypeID		VARCHAR(50),
	ATypeID			VARCHAR(50),
	ExTotal			 NUMERIC(24, 10) ,
	CID				NUMERIC(18,0),
	Rate			 NUMERIC(24, 10) ,
	Flag			INT		--1=货币资金,2=预收39 预付27  3=应收33 应付35
)

IF @Currency = 1 --货币资金
BEGIN
	INSERT #ResultDeatil(TypeATypeID,ATypeID,ExTotal,CID,Flag)
	SELECT T.ATypeID ,T.ATypeID, ISNULL(SUM(T.ExTotal),0), T.CID, 1 AS Flag
	FROM
	(
		SELECT	A.ATypeID,
				CASE WHEN AC.BasisType=0 
						THEN CAST(A.Ntotal*AC.Rate AS  NUMERIC(24, 10) ) - A.Total
					 ELSE CAST(A.Ntotal/AC.Rate AS  NUMERIC(24, 10) ) - A.Total
				END AS ExTotal,
				A.CID
		FROM AType_Total A
		INNER JOIN Ac_Currency AC ON AC.CId = A.CID
		INNER JOIN Ac_Items I ON I.nId = A.ATypeID
		WHERE	A.STypeID = @StypeID
				AND I.TypeName = 'B' 
				AND I.SonNum = 0
				AND AC.Sysrow = 0
	) T
	GROUP BY T.ATypeID,T.CID
END

--预收39 预付27
IF @YuS = 1
BEGIN
	INSERT #ResultDeatil(TypeATypeID,ATypeID,ExTotal,CID,Flag)
	SELECT  T.TypeATypeID,
			T.BTypeID,
			SUM(CASE WHEN AC.BasisType=0 
					THEN CAST(T.nExTotal*AC.Rate AS  NUMERIC(24, 10) ) - T.ExTotal
				  ELSE CAST(T.nExTotal/AC.Rate AS  NUMERIC(24, 10) ) - T.ExTotal END) 
			AS ExTotal,
			T.CID,
			2 AS Flag
	FROM
	(
		SELECT 39 AS TypeATypeID,BTypeID,CID,YSTotal AS ExTotal,nYSTotal AS nExTotal
		FROM BType_ArApTotal
		WHERE STypeID = @StypeID
		UNION ALL
		SELECT 27 AS TypeATypeID,BTypeID,CID,YFTotal AS ExTotal,nYFTotal AS nExTotal
		FROM BType_ArApTotal
		WHERE STypeID = @StypeID
	) T
	INNER JOIN Ac_Currency AC ON AC.CId = T.CID
	WHERE AC.Sysrow = 0 AND (@IsZero*@IsNoZero=1 OR @IsZero=1 AND T.nExTotal=0 OR @IsNoZero=1 AND T.nExTotal <> 0)
	GROUP BY T.TypeATypeID,T.BTypeID,T.CID
END

--应收33 应付35
IF @YingS = 1
BEGIN
	INSERT #ResultDeatil(TypeATypeID,ATypeID,ExTotal,CID,Flag)
	SELECT  T.TypeATypeID,
			T.BTypeID,
			--CAST(T.nExTotal*AC.Rate AS  NUMERIC(24, 10) )
			SUM(CASE WHEN AC.BasisType=0 
					THEN CAST(T.nExTotal*AC.Rate AS  NUMERIC(24, 10) ) - T.ExTotal
				  ELSE CAST(T.nExTotal/AC.Rate AS  NUMERIC(24, 10) ) - T.ExTotal END) 
			AS ExTotal,
			T.CID,
			3 AS Flag
	FROM
	(
		SELECT 33 AS TypeATypeID,BTypeID,CID,ARTotal AS ExTotal,nARTotal AS nExTotal
		FROM BType_ArApTotal
		WHERE STypeID = @StypeID
		UNION ALL
		SELECT 35 AS TypeATypeID,BTypeID,CID,APTotal AS ExTotal,nAPTotal AS nExTotal
		FROM BType_ArApTotal
		WHERE STypeID = @StypeID
	) T
	INNER JOIN Ac_Currency AC ON AC.CId = T.CID
	WHERE AC.Sysrow = 0 AND (@IsZero*@IsNoZero=1 OR @IsZero=1 AND T.nExTotal=0 OR @IsNoZero=1 AND T.nExTotal <> 0)
	GROUP BY T.TypeATypeID,T.BTypeID,T.CID
END


--合并数据
INSERT #ResultSumData(TypeATypeID, ATypeID, ExTotal,CID, Flag)
SELECT TypeATypeID, ATypeID, dbo.F_RoundTotal(CAST(ISNULL(SUM(ExTotal),0) AS  NUMERIC(24, 10) )), CID, Flag
FROM #ResultDeatil
GROUP BY TypeATypeID, ATypeID,CID, Flag

DELETE #ResultSumData WHERE ExTotal = 0 OR ExTotal IS NULL

IF @MBtypeid = '-99999' 
	AND  EXISTS(  SELECT TOP 1 1
				  FROM #ResultSumData R 
				  WHERE R.Flag <> 1 AND NOT EXISTS(SELECT TOP 1 1 FROM DBO.F_LineB(@OperatorID) F WHERE F.TypeId=R.ATypeID ))
BEGIN
	RAISERROR('生成业务凭证中的辅助核算项目明细，在你的多级权限范围中无权限，请分配权限或让有权限的操作员操作此业务！',16,1)
	RETURN	
END

IF NOT EXISTS(SELECT TOP 1 1 FROM #ResultSumData WHERE ExTotal<> 0)
BEGIN
	RAISERROR('没有数据需要处理！',16,1)
	RETURN
END

DECLARE @Total	 NUMERIC(24, 10) ,
		@CID	INT,
		@nID	NUMERIC(18,0)=0

SELECT @CID= CID FROM Ac_Currency WHERE Sysrow = 1

SELECT TOP 1 @nID=nId FROM Ac_Items WHERE UserCode='043599'

SELECT @Total =  SUM(CASE WHEN TypeATypeID IN (35,39) THEN -ExTotal ELSE ExTotal END ) 
FROM #ResultSumData

--汇率损益
IF @Total <> 0
	INSERT #ResultSumData(TypeATypeID,ATypeID,CId,ExTotal) VALUES(@nID,@nID,@CID,-@Total)  --	负数就插入到贷方 正数插入到借方


--处理汇率
UPDATE  #ResultSumData SET Rate = A.Rate
FROM #ResultSumData R
INNER JOIN Ac_Currency A ON A.CId = R.CID 

DECLARE @DtypeID		VARCHAR(50)
SELECT  @DtypeID = DtypeID FROM employee WHERE typeId = @EtypeID

--生成单据开始
DECLARE @BillDate	DATETIME,
		@DAY		VARCHAR(200),
		@MONTH		VARCHAR(200),
		@BillNumberId  NUMERIC(24, 10) ,
		@BillType	INT,
		@cefullname			VARCHAR(500)='',
		@cdfullname			VARCHAR(500)=''
		

--取当前时间
SET @BillDate=GETDATE()
SET @DAY=DAY(@BillDate)
SET @MONTH=MONTH(@BillDate)
SET @BillDate=(SELECT CONVERT (VARCHAR(10),@BillDate,120))
SET @BillType = 159

--是否自定义单据编号
IF EXISTS(SELECT TOP 1 1 FROM CodeConfig WHERE Billtype =159)
BEGIN
	SELECT @MONTH = typeid  FROM employee WHERE typeId=@OperatorID
	SELECT @DAY = ''
	SELECT @cefullname = E.fullname FROM Employee E WHERE E.TypeId = @OperatorID
	SELECT @cdfullname = D.FullName FROM dbo.Department D WHERE D.TypeId = @DtypeID
END

--生成单据编号
EXEC Gp_GetBillCode @BillType,@MONTH,@DAY,'KP',@BillDate,@STypeId,@BillCode OUT,@cdfullname,@cefullname

DECLARE @recvalue INT=0		
EXEC @recvalue=Gp_InsertBillIndex 
			@BillDate=@BillDate,
			@BillCode=@BillCode,
			@BillType=@BillType,
			@Comment='',
			@ATypeID='',
			@PTypeID='',
			@BTypeID='',
			@ETypeID=@etypeid,
			@KTypeID='',
			@KTypeID2='',
			@IfCheck='f',
			@CheckE=@OperatorID,
			@TotalMoney=0,
			@TotalQty=0,
			@TotalInMoney=0,
			@Tax='0',
			@szPeriod=1,
			@Explain='默认期末汇差处理，不允许修改',
			@Draft='True',
			@RedWord='False',
			@OrderID=0,
			@WayBillCode='',
			@Goodsnumber='',
			@PackWay='',
			@Tel='',
			@preferencemoney=0,
			@AlertDay=9999,
			@Assessor='',
			@IfAudit='',
			@Audit_Explain='',
			@Dtypeid=@DtypeID,
			@VipCardID=-1,
			@KTypeID3='',
			@LinkMan='',
			@LinkTel='',
			@LinkAddr='',
			@wxManID='',
			@JieJianBillNumberID=-1,
			@JieJianID=-1,
			@BaoXiuBillNumberID=-1,
			@BaoXiuID=-1,
			@BuyDate='',
			@Serial='',
			@wxTotal=0,
			@ErrDes='',
			@ifHideJieJian=0,
			@ifWX=0,
			@IfBargainOn=0,
			@STypeID=@stypeid,
			@FromBillNumberID=0,
			@CostSale=0,
			@completedate='9999-12-31 23:59:59',
			@billstate=1,
			@ifmulaccount=0,
			@vipczmoney=0,
			@otherinouttype=-1,
			@czbeforetimes=0,
			@posbilltype=0,
			@TransportId=0,
			@IsFreightMoney=0,
			@FreightAddr=NULL,
			@freightperson=NULL,
			@freighttel=NULL,
			@ShareMode=0,
			@uf1='',
			@uf2='',
			@uf3='',
			@uf4='',
			@uf5='',
			--9.0新字段
			@dealbtypeid='',		--结算单位
			@cid=@CID,			--外币币种id
			@rate=1,			--汇率
			@ntotalmoney=0,		--原币种金额
			@ntotalinmoney=0,	--原币收现金额
			@npreferencemoney=0,	--原币优惠金额
			@nvipczmoney=0,		--原币会员卡充值金额
			@atypeid1='',
			@billproperty=-1,					--单据属性
			@ncompletetotal	=0,		--原币结算金额
			@isini=0,
			@ATID=0,					--过账模板
			@CompleteTotal=0,
			@IfCargo=0,
			@IfInvoice=0,
			@promoruleid=0,
			@beforepromobillnumberid=0,
			@promotionmsg='',
			@isyapi=0,
			@yapiorderid=0,
			@checkSave='bill_allow_save'	

IF @recvalue = -1 
    BEGIN
        RAISERROR('试用版最多录200条单据！',16,1)
        RETURN
    END
IF @recvalue = -2 
	BEGIN
		RAISERROR('录单日期小于本期开始日期！',16,1)
		RETURN
	END
IF @recvalue = -3 
	BEGIN
		RAISERROR('校验错误 ！',16,1)
		RETURN
	END
IF @recvalue = -4
BEGIN
    RAISERROR('录单日期必须与当前日期一致！',16,1)
    RETURN
END
IF @recvalue = -5 
	BEGIN
		RAISERROR('更新单据发生错误！',16,1)
		RETURN
	END

SET @BillNumberId = @@IDENTITY	

IF @BillNumberId IS NULL
RETURN -10

UPDATE BillIndex SET IsAuto = 1 WHERE BillNumberId = @BillNumberId

 --写单据操作日志
INSERT INTO BillOperateLog(billnumberid,operatetype,etypeid,OperateTime,ip) VALUES(@BillNumberId,'制单',@OperatorID,GETDATE(),@clientip)

--保存单据编号的种子数
EXEC GP_SaveBillCode_Seed @BillNumberId,@billdate,@BillType,@billcode

INSERT AccountCredence(BillNumberID,TypeATypeID,ATypeID,J_Total,D_Total,Comment,TeamNo,TeamNo1,Stypeid,NJ_Total,ND_Total,CID,Rate,ETypeId,DTypeId)
SELECT	@BillNumberId,
		TypeATypeID,
		ATypeID,
		dbo.F_RoundTotal(CASE WHEN TypeATypeID IN (35,39) AND ExTotal < 0 THEN -ExTotal
			 WHEN TypeATypeID NOT IN (35,39) AND ExTotal > 0 THEN ExTotal 
			 ELSE 0 
			 END) AS J_Total,
			 
		dbo.F_RoundTotal(CASE WHEN TypeATypeID IN (35,39) AND ExTotal > 0 THEN ExTotal
			 WHEN TypeATypeID NOT IN (35,39) AND ExTotal < 0 THEN -ExTotal
			 ELSE 0  
			 END)  AS D_Total,
		'',
		NULL,
		NULL,
		@StypeID,
		
		dbo.F_RoundTotal(CASE WHEN TypeATypeID = @nID AND ExTotal > 0 THEN ExTotal  --NJ_Total
			 ELSE 0 END),
		
		dbo.F_RoundTotal(CASE WHEN TypeATypeID = @nID AND ExTotal < 0 THEN -ExTotal --ND_Total
			 ELSE 0 END),	 
		CID,
		dbo.F_RoundExchangeRate(Rate),
		@EtypeID,
		@DtypeID
FROM #ResultSumData
ORDER BY ID ASC



DROP TABLE #ResultDeatil,#ResultSumData


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ExportUploadData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_ExportUploadData]
GO















/****** Object:  Stored Procedure dbo.Web_ExportUploadData    Script Date: 2002-6-20 10:14:54 ******/


--导出需要上传的单据数据
--author:王跃
--last modified:2001-10-30
CREATE  PROCEDURE Web_ExportUploadData
(
 @startdate smalldatetime=null,
 @enddate smalldatetime=null 
)
--@encode$--
 AS
SET NOCOUNT ON 
if not exists(select * from sysdata1 where SubNo=1 and SubValue IN('1','3')) return -3 --不是离线版
  declare @sn varchar(66),@StockId VARCHAR(25) --得到数据
  select @sn=FLAG,@StockId=StockId from DBCONFIG
  declare @TaskId int,@RC int
  select @TaskId=isnull(max(TaskId),0)+1 from Offline_BillIndex --得到新的任务号
  if @startdate is null or @enddate is null
    declare UploadData cursor
     for select BillNumberid,BillType from Billindex where Uploaded=0 and RedWord=0 and ifcheck='t' and draft=0
  else
    declare UploadData cursor
     for select BillNumberid,BillType from Billindex where Uploaded=0 and RedWord=0 and ifcheck='t' and draft=0 and BillDate>=@StartDate and BillDate<=@EndDate
 declare @BillNumberId int ,@BillType int,@id uniqueidentifier
 open UploadData  
 fetch next from UploadData into @BillNumberId,@BillType
 if @@Fetch_Status<>0 
  begin
   close UploadData
   deallocate UpLoadData
  --检查是否有旧的数据需要
  select @rc=isnull(Count(*),0) from OFFLINE_TASK where Status=0
  if @Rc=0 
   return -1 --没有新的数据需要上传
  else if @Rc=1
  begin
   select @rc=TaskID from OFFLINE_TASK where Status=0
   return @rc
  end
  else
    return -4 --有多项任务没有上传
  end
 begin tran
 while @@Fetch_Status=0
 begin
    select @id=NewID()    
      insert into Offline_BillIndex(OFF_ID,StockName,BillNumberId,BillDate,BillCode,BillType,Comment,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,explain,RedWord,draft,OrderId,waybillcode,goodsnumber,packway,TEL,AlertDay,CompleteTotal,TaskId,StockID,Assessor,IfAudit,Audit_explain,[ID],import) 
                            select @id,@sn,BillNumberId,BillDate,BillCode,BillType,Comment,atypeid,ptypeid,btypeid,etypeid,ktypeid,ktypeid2,ifcheck,checke,totalmoney,totalinmoney,totalqty,tax,period,explain,RedWord,draft,OrderId,waybillcode,goodsnumber,packway,TEL,isnull(AlertDay,9999),CompleteTotal,@TaskId,@StockId,Assessor,IfAudit,Audit_explain,[ID],0 from Billindex where BillNumberid=@BillNumberId
     if @@error<>0 goto Error
      if @BillType=11 --销售单
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,JobNumber,GoodsNo,OutFactoryDate,TaxPrice,TaxTotal,total,OrderId,TeamNo,ID,TeamNO1,IsUnit2) 
                        select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,ID,TeamNO1,isnull(IsUnit2,0) from salebill where billnumberid=@billnumberid 
      else if @BillTYpe=45 --销售退货单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,JobNumber,GoodsNo,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,ID,TeamNO1,IsUnit2) 
                        select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,ID,TeamNO1,isnull(IsUnit2,0) from salebackbill where billnumberid=@billnumberid 
      else if @BillTYpe=4 --收款单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,AtypeId,total,Comment,TeamNo,ID,TeamNO1) 
                        select @Taskid,@id,BillNumberId,AtypeId,total,Comment,TeamNo,ID,TeamNO1 from gatheringbill where billnumberid=@billnumberid 
      else if @BillType=34 --进货单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,JobNumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,ID,TeamNO1,IsUnit2) 
                        select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,ID,TeamNo1,isnull(IsUnit2,0) from buybill where billnumberid=@billnumberid 
      else if @BillType=6 --进货退货单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,JobNumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,ID,TeamNO1,IsUnit2) 
                        select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,jobnumber,OutFactoryDate,TaxPrice,TaxTotal,total,TeamNo,ID,TeamNo1,isnull(IsUnit2,0) from buybackbill where billnumberid=@billnumberid 
      else if @BillType=66 --付款单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,AtypeId,total,Comment,TeamNo,ID,TeamNO1) 
                        select @Taskid,@id,BillNumberId,AtypeId,total,Comment,TeamNo,ID,TeamNO1 from paybill where billnumberid=@billnumberid 
      else if @BillType=21 --变价调拨单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,PtypeId,Qty,price,total,JobNumber,GoodsNo,OutFactoryDate) 
                        select @Taskid,@id,BillNumberId,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate from movebjbill where billnumberid=@billnumberid 
      else if @BillType=17 --同价调拨单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate) 
                        select @Taskid,@id,BillNumberId,Comment,PtypeId,Qty,Jobnumber,GoodsNo,OutFactoryDate from movebill where billnumberid=@billnumberid 
      else if @BillType=57 --调价单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,PtypeId,Qty,price,total,JobNumber,GoodsNo,OutFactoryDate) 
                        select @Taskid,@id,BillNumberId,Comment,PtypeId,Qty,price,total,Jobnumber,GoodsNo,OutFactoryDate from adpricebill where billnumberid=@billnumberid 
      else if @BillType=9 --报损单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,IsUnit2) 
                           select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,isnull(IsUnit2,0) from losebill where billnumberid=@billnumberid              
      else if @BillType=14 --报溢单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,IsUnit2) 
                           select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,isnull(IsUnit2,0) from overflowbill where billnumberid=@billnumberid              
      else if @BillType in(36,93) --费用单，其他收入
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,AtypeId,total,Comment,TeamNo,ID,TeamNO1) 
                           select @Taskid,@id,BillNumberId,AtypeId,total,Comment,TeamNo,ID,TeamNO1 from moneybill where billnumberid=@billnumberid              
      else if @BillType in(115,116,128,129) --
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,Comment,BtypeId,total,TeamNo,ID,TeamNO1) 
                           select @Taskid,@id,BillNumberId,Comment,BtypeId,total,TeamNo,ID,TeamNO1 from addebtbill where billnumberid=@billnumberid
      else if @BillType=16 --拆装单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,PtypeId,Qty,costprice,jobnumber,total,inorout,outfactorydate,comment,goodsno) 
                           select @Taskid,@id,BillNumberId,PtypeId,Qty,costprice,jobnumber,total,inorout,outfactorydate,comment,goodsno from DisassembleBill where billnumberid=@billnumberid              
      else if @BillType=77 --转款单
      insert into Offline_Bill(TaskId,OFF_ID,BillNumberId,AtypeId,total,Comment) 
                           select @Taskid,@id,BillNumberId,AtypeId,total,Comment from movemoneybill where billnumberid=@billnumberid              
      else if @BillType=305 --零售单
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,JobNumber,GoodsNo,OutFactoryDate,TaxPrice,TaxTotal,total,OrderId,TeamNo,ID,TeamNO1,IsUnit2) 
                        select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,SalePrice,discount,DiscountPrice,costprice,jobnumber,goodsno,OutFactoryDate,TaxPrice,TaxTotal,total,OrderID,TeamNo,ID,TeamNO1,isnull(IsUnit2,0) from retailbill where billnumberid=@billnumberid 
      else if @BillType=139 --赠送单
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,ID,IsUnit2) 
                        select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,jobnumber,goodsno,OutFactoryDate,ID,isnull(IsUnit2,0) from GiveBill where billnumberid=@billnumberid 
      else if @BillType=126 --获增单
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,PtypeId,Qty,JobNumber,GoodsNo,OutFactoryDate,ID,IsUnit2)
                        select @Taskid,@id,BillNumberId,comment,PtypeId,Qty,jobnumber,goodsno,OutFactoryDate,ID,isnull(IsUnit2,0) from givemebill where billnumberid=@billnumberid 
      else if @BillType=84 --固定资产购买
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,AtypeId,TeamNo,ID,TeamNO1,total) 
                        select @Taskid,@id,BillNumberId,comment,AtypeId,TeamNo,ID,TeamNO1,total from MoneyBill where billnumberid=@billnumberid 
      else if @BillType=85 --固定资产变卖
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,AtypeId,TeamNo,ID,TeamNO1,total) 
                        select @Taskid,@id,BillNumberId,comment,AtypeId,TeamNo,ID,TeamNO1,total from MoneyBill where billnumberid=@billnumberid 
      else if @BillType=78 --固定资产折旧
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,AtypeId,TeamNo,ID,TeamNO1,total) 
                        select @Taskid,@id,BillNumberId,comment,AtypeId,TeamNo,ID,TeamNO1,total from MoneyBill where billnumberid=@billnumberid 
      else if @BillType=5 --待摊费用发生
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,AtypeId,TeamNo,ID,TeamNO1,total) 
                        select @Taskid,@id,BillNumberId,comment,AtypeId,TeamNo,ID,TeamNO1,total from MoneyBill where billnumberid=@billnumberid 
      else if @BillType=10 --待摊费用摊销
      insert into Offline_Bill(TASKID,OFF_ID,BillNumberId,Comment,AtypeId,TeamNo,ID,TeamNO1,total) 
                        select @Taskid,@id,BillNumberId,comment,AtypeId,TeamNo,ID,TeamNO1,total from MoneyBill where billnumberid=@billnumberid 
     if @@error<>0 goto Error
     update BillIndex set UpLoaded=1 WHERE BillNumberid=@BillNumberid
     if @@error<>0 goto Error
   fetch next from UploadData into @BillNumberId,@BillType
  
  end
  --记录导出单据的任务号
 insert Offline_Task([Filename],[DATE],FLAG,TASKID,StockID) values('Bill'+cast(@TaskId as varchar(15))+'.Dat',GetDate(),@sn,@TaskID,@StockID)
 if @@error<>0 goto Error
  commit tran
  Close UploadData  
  deallocate UploadData  
  return @TaskId
 Error:
  rollback tran
  Close UploadData  
  deallocate UploadData  
  return -2 --发生错误














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_FactAccountStockDifference_List]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Web_FactAccountStockDifference_List
GO

 --	===========================================
 --	描述:仓库账面实物差异表
 --	时间:2016-07-19
 --	作者:寇晨
 --	===========================================
 
 CREATE PROCEDURE Web_FactAccountStockDifference_List
(
	@OperatorId VARCHAR(100)='' --操作员id
	,@Parid VARCHAR(200)='' --父类id
	,@StypeIds VARCHAR(100)='' --分支机构id
	,@KtypeIds VARCHAR(max)='' --仓库ids
	,@PtypeIds VARCHAR(max)='' --商品ids
	,@DisplayStop INT --是否显示停用商品   1 显示 0不显示
	,@DisplayZero INT =1 --是否显示为0的数据 1显示 0不显示
	,@Date DATETIME
)
--@encode$--	
AS
BEGIN
 
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
			   @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------

    IF (@Parid='' OR @Parid='00000' OR @Parid=NULL)
	    SET @Parid='00000';
	DECLARE @sonnum INT;
	DECLARE @innerPtypeId VARCHAR(100)='';
	IF @Parid='00000' AND @MPtypeid<>'-99999'
		SET @Parid=@MPtypeid;
	SELECT @sonnum=sonnum FROM ptype WHERE typeid=@Parid;
	IF @Parid<>'00000'
		SET @innerPtypeId=@Parid;
	DECLARE @DisplayActual INT;
	SET @DisplayActual=0;
	DECLARE @PriceType INT;
	SET @PriceType=0;
	DECLARE @showstockstop INT;
	SET @showstockstop=0;
	DECLARE @ptypeCategoryid VARCHAR(MAX);
	SET @ptypeCategoryid='';
	
--把权限函数提出来
	--仓库（带分支id）
	CREATE TABLE #KStype(TypeId VARCHAR(50),STypeId VARCHAR(50));
	--分支机构
	CREATE TABLE #BTType(TypeId VARCHAR(50));
	
	CREATE CLUSTERED INDEX #KStype_t ON #KStype(TypeId);
	CREATE CLUSTERED INDEX #BTType_t ON #BTType(TypeId);
	
	INSERT INTO #KStype SELECT TypeId,STypeId  FROM F_GetManDetailKTypeSType(@OperatorId);
	
	IF @StypeIds<>''
	BEGIN
	INSERT INTO #BTType SELECT TypeId FROM F_GetAllManagerBaseTypeId(@StypeIds,11,@OperatorID);
	END
	ELSE
	BEGIN
	INSERT INTO #BTType SELECT TypeId FROM dbo.F_GetManSTypeAll(@OperatorId);
	END
	
	--仓库
	CREATE TABLE #Ktype(TypeId VARCHAR(50));
	CREATE CLUSTERED INDEX #Ktype_t ON #Ktype(TypeId);
	IF @KtypeIds<>''
	BEGIN
	IF  @showstockstop=0
		INSERT INTO #KType SELECT TypeId FROM F_GetAllBaseTypeId(@KtypeIds,4) 
	ELSE
		INSERT INTO #KType SELECT a.TypeId FROM F_GetAllBaseTypeId(@KtypeIds,4)a INNER JOIN dbo.Stock s ON a.TypeId=s.typeId  WHERE  s.deleted=0
    END
    ELSE
    BEGIN 
    INSERT INTO #KType SELECT TypeId FROM #KStype
    END

	--权限范围内的商品线性表
	CREATE TABLE #ptype(TypeId	varchar(100))
	INSERT INTO #ptype(TypeId) SELECT a.TypeId FROM dbo.F_LinePC(@OperatorID,@ptypeCategoryid) a 
	
	--临时表
	CREATE TABLE #t(	
		PtypeId VARCHAR(50),
		qty  NUMERIC(24, 10) ,
		qty1  NUMERIC(24, 10)  ,
		nqty  NUMERIC(24, 10) ,
		total  NUMERIC(24, 10) ,
		lendqty  NUMERIC(24, 10) ,
		borrowqty  NUMERIC(24, 10) ,
		wtqty  NUMERIC(24, 10) ,
		stqty  NUMERIC(24, 10),
		lockqty NUMERIC(24, 10) )
	CREATE CLUSTERED INDEX #t_p ON #t(ptypeid);
	
	--临时表
	CREATE TABLE #tf(	
		PtypeId VARCHAR(50),
		qty  NUMERIC(24, 10) ,
		qty1  NUMERIC(24, 10)  ,
		nqty  NUMERIC(24, 10)
		)
	CREATE CLUSTERED INDEX #tf_p ON #tf(ptypeid);
	
	--   库存
	CREATE TABLE #goods
	(
		PtypeId VARCHAR(50),
		KtypeId VARCHAR(50),
		total  NUMERIC(24, 10) 
	);
	CREATE CLUSTERED INDEX #goods_p_k ON #goods(PTypeId,KtypeId)
	--期初库存
	CREATE TABLE #inigoods(
		PtypeId VARCHAR(50),
		KtypeId VARCHAR(50),
		total  NUMERIC(24, 10) 
	);
	CREATE CLUSTERED INDEX #inigoods_p_k ON #inigoods(PTypeId,KtypeId)
	
	--   库存
	CREATE TABLE #goodsf
	(
		PtypeId VARCHAR(50),
		KtypeId VARCHAR(50)
	);
	CREATE CLUSTERED INDEX #goodsf_p_k ON #goodsf(PTypeId,KtypeId)
	--期初库存
	CREATE TABLE #inigoodsf(
		PtypeId VARCHAR(50),
		KtypeId VARCHAR(50)
	);
	CREATE CLUSTERED INDEX #inigoodsf_p_k ON #inigoodsf(PTypeId,KtypeId)

	IF @Date IS NULL
	BEGIN
		INSERT INTO #goods 
			SELECT PtypeId,KtypeId,SUM(Total) AS total
			FROM dbo.GoodsStocks
			INNER JOIN #ptype p ON PtypeId=p.TypeId
			WHERE PtypeId LIKE @innerPtypeId+'%'
			AND KtypeId IN (SELECT TypeId FROM #Ktype)
			AND KtypeId IN (
					SELECT u.TypeId FROM #KStype u
						JOIN #BTType v ON u.STypeId=v.TypeId
				) --操作员仓库权限
			GROUP BY PtypeId,KtypeId
	END
	
	IF @Date IS NOT NULL
	BEGIN
		INSERT INTO #inigoods
			SELECT PtypeId,KtypeId,SUM(Total) AS total
			FROM dbo.IniGoodsStocks
			INNER JOIN #ptype p ON PtypeId=p.TypeId
			WHERE KtypeId IN (
					SELECT u.TypeId FROM #KStype u
						JOIN #BTType v ON u.STypeId=v.TypeId
				) --操作员仓库权限
				AND KtypeId IN (SELECT TypeId FROM #Ktype)				
			AND PtypeId LIKE @innerPtypeId+'%'
			GROUP BY PtypeId,KtypeId
	END
	--
	
	IF (@Date IS NULL OR @date='')
	BEGIN
		INSERT INTO #goodsf
			SELECT PtypeId,KtypeId
			FROM dbo.FactStocks
			INNER JOIN #ptype p ON PtypeId=p.TypeId
			WHERE PtypeId LIKE @innerPtypeId+'%'
			AND KtypeId IN (SELECT TypeId FROM #Ktype)
			AND KtypeId IN (
					SELECT u.TypeId FROM #KStype u
						JOIN #BTType v ON u.STypeId=v.TypeId
				) --操作员仓库权限
			GROUP BY PtypeId,KtypeId
	END

	IF @Date IS NOT NULL
	BEGIN
		INSERT INTO #inigoodsf
			SELECT PtypeId,KtypeId
			FROM dbo.IniFactStocks
			INNER JOIN #ptype p ON PtypeId=p.TypeId
			WHERE KtypeId IN (
					SELECT u.TypeId FROM #KStype u
						JOIN #BTType v ON u.STypeId=v.TypeId
				) --操作员仓库权限
				AND KtypeId IN (SELECT TypeId FROM #Ktype)				
			AND PtypeId LIKE @innerPtypeId+'%'
			GROUP BY PtypeId,KtypeId
	END
	--

	CREATE TABLE #cte(
		PtypeId VARCHAR(50),
		qty  NUMERIC(24, 10) ,
		nqty  NUMERIC(24, 10) ,
		total  NUMERIC(24, 10) ,
		lend  NUMERIC(24, 10) ,
		borrow  NUMERIC(24, 10) ,
		wt  NUMERIC(24, 10) ,
		st  NUMERIC(24, 10),
		lockqty NUMERIC(24, 10)  
	);
	CREATE CLUSTERED INDEX #cte_p ON #cte(PtypeId);
	
	CREATE TABLE #ctef(
		PtypeId VARCHAR(50),
		qty  NUMERIC(24, 10) ,
		nqty  NUMERIC(24, 10)
	);
	CREATE CLUSTERED INDEX #ctef_p ON #ctef(PtypeId);
	
	--库存
	INSERT INTO #cte
		SELECT 
				a.PtypeId,SUM(b.Qty) AS qty,SUM(b.NQty) AS nqty,MAX(a.total) AS total,0 AS lend,0 AS borrow,0 AS wt,0 AS st,0
		FROM #goods a 
		LEFT JOIN dbo.GOODSSTOCKS_QTY b ON a.Ptypeid=b.PTypeID AND a.KtypeId=b.KTypeID
		WHERE @Date IS NULL
		GROUP BY a.PtypeId,a.KtypeId
		
	--库存
	INSERT INTO #ctef
		SELECT 
				a.PtypeId,SUM(b.Qty) AS qty,SUM(b.NQty) AS nqty
		FROM #goodsf a 
		LEFT JOIN dbo.FactStocks_Qty b ON a.Ptypeid=b.PTypeID AND a.KtypeId=b.KTypeID
		WHERE (@Date IS NULL OR @Date='')
		GROUP BY a.PtypeId,a.KtypeId

	--UNION ALL
	--期初数据
	INSERT INTO #cte
	SELECT a.PtypeId,SUM(b.qty) AS qty,SUM(b.nqty) AS nqty,MAX(a.total) AS total
	,0 AS lend,0 AS borrow,0 AS wt,0 AS st,0
	FROM #inigoods a 
	LEFT JOIN dbo.Ini_GOODSSTOCKS_QTY b ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
	WHERE @Date IS NOT NULL 	
	GROUP BY a.PtypeId,a.KtypeId
	
	--UNION ALL
	--期初数据
	INSERT INTO #ctef
	SELECT a.PtypeId,SUM(b.qty) AS qty,SUM(b.nqty) AS nqty
	FROM #inigoodsf a 
	LEFT JOIN dbo.IniFactStocks_Qty b ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
	WHERE @Date IS NOT NULL 	
	GROUP BY a.PtypeId,a.KtypeId
	
	--UNION ALL
	--出入库数据 
	INSERT INTO #cte
	SELECT PtypeId,CASE WHEN BillType=57 THEN 0 ELSE qty END qty,NQty,CostTotal AS total,0,0,0,0,0
	FROM dbo.InOutstocktable 
	INNER JOIN #ptype p ON PtypeId=p.TypeId
	WHERE @Date IS NOT NULL AND BillDate<=@Date --时间条件
	AND KtypeId IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
		AND KtypeId IN (SELECT TypeId FROM #Ktype)
	AND KtypeId <>'10000' --排除受托委托库
	AND STypeID IN (SELECT TypeId FROM #BTType) 
	AND PtypeId LIKE @innerPtypeId+'%'
	
	--UNION ALL
	--出入库数据 
	INSERT INTO #ctef
	SELECT PtypeId,CASE WHEN BillType=57 THEN 0 ELSE qty END qty,NQty
	FROM dbo.Fact_InOutstocktable 
	INNER JOIN #ptype p ON PtypeId=p.TypeId
	WHERE @Date IS NOT NULL AND BillDate<=@Date --时间条件
	AND KtypeId IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
		AND KtypeId IN (SELECT TypeId FROM #Ktype)
	AND STypeID IN (SELECT TypeId FROM #BTType) 
	AND PtypeId LIKE @innerPtypeId+'%'
	

	--显示实际的情况
	--UNION ALL
	
	-- 借欠
	INSERT INTO #cte
	SELECT vls.pTypeID,0,0,0
	,vls.Lend-vls.LendBack-vls.saleqty AS lendQty
	,vls.Borrow-vls.BorrowBack-vls.buyqty AS borrowQty
	,0,0,0 
	FROM V_LendStatus vls
	INNER JOIN #ptype p ON vls.PtypeId=p.TypeId
	WHERE vls.KtypeId IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
		AND KtypeId IN (SELECT TypeId FROM #Ktype)	
	AND vls.PtypeId LIKE @innerPtypeId+'%'
	AND @DisplayActual=1 --查询启用才显示	
	
	
	--UNION ALL
	--受托,委托
	INSERT INTO #cte
	SELECT PtypeId,0,0,0
	,0,0
	,ABS(SUM(wtst.wtf))-ABS(SUM(wtst.wtj))-ABS(SUM(wtst.wtt))
	,ABS(SUM(wtst.stf))-ABS(SUM(wtst.stj))-ABS(SUM(wtst.stt)),
	0
	FROM 
	(
		SELECT PtypeId
		,CASE WHEN billtype=140 THEN qty ELSE 0 END AS wtf
		,CASE WHEN BillType=141 THEN qty ELSE 0 END AS wtj
		,CASE WHEN Billtype=142 THEN qty ELSE 0 END AS wtt
		,CASE WHEN BillType=144 THEN qty ELSE 0 END AS stf
		,CASE WHEN BillType=145 THEN qty ELSE 0 END AS stj
		,CASE WHEN billType=146 THEN qty ELSE 0 END AS stt
		FROM InOutStockTable
		INNER JOIN #ptype p ON PtypeId=p.TypeId
		WHERE Audited=1 AND KtypeId='10000'
		AND BillType IN (140,141,142,144,145,146)
		AND STypeID IN (SELECT TypeId FROM #BTType) 
		AND PtypeId LIKE @innerPtypeId+'%'
		
		UNION ALL 
		SELECT PTypeID,
			CASE WHEN type=140 THEN qty ELSE 0 END AS wtf,0,0,
			CASE WHEN type=144 THEN qty ELSE 0 END AS stf,0,0
		FROM dbo.IniCommissionStock a 
		INNER JOIN #ptype p ON PtypeId=p.TypeId
		WHERE a.type IN (140,144)
		AND a.KtypeId='10000'
		AND a.STypeID IN (SELECT TypeId FROM #BTType)				
		AND a.PtypeId LIKE @innerPtypeId+'%'
	) as wtst
	WHERE @DisplayActual=1 --查询启用才显示
	GROUP BY wtst.Ptypeid

	INSERT INTO #cte
	SELECT o.PtypeId,0,0,0,0,0,0,0,SUM(o.LockNumber)
	FROM dbo.OrderBill o
	INNER JOIN dbo.OrderIndex i ON o.billNumberID=i.billNumberId
	INNER JOIN #ptype p ON o.PtypeId=p.TypeId
	WHERE	o.KTypeID IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
		AND o.KtypeId IN (SELECT TypeId FROM #Ktype)	
		AND i.BillOver=0 AND i.IsFinished<>1
	GROUP BY o.ptypeid


	INSERT INTO #T 
	SELECT 
		w.PtypeId,
		SUM(qty) AS qty,
		SUM(ISNULL(qty,0.0)/ISNULL(U.rate,1.0)) AS qty1,
		SUM(nqty) AS nqty,
		SUM(total) AS total,
		SUM(w.lend) AS lendqty,
		SUM(w.borrow)AS borrowqty,
		SUM(wt) AS wtqty,
		SUM(st) AS stqty,
		SUM(ISNULL(lockqty,0)) AS lockqty
	FROM #cte w  
	INNER JOIN dbo.ptype p ON p.typeId =w.PtypeId AND (@DisplayStop=0 AND p.deleted=0 OR @DisplayStop=1)
	INNER JOIN dbo.PType_Units_Ext u ON U.PtypeID=P.typeId AND U.UnitsId=P.StockUnitId
	INNER JOIN dbo.PType_Units v ON v.UnitsId=u.UnitsId
	GROUP BY w.PtypeId
	
	INSERT INTO #tf
	SELECT
	    w.PtypeId,
	    SUM(qty) AS qty,
	    SUM(ISNULL(qty,0.0)/ISNULL(U.rate,1.0)) AS qty1,
	    SUM(nqty) AS nqty
	FROM #ctef w
	INNER JOIN dbo.ptype p ON p.typeId =w.PtypeId AND (@DisplayStop=0 AND p.deleted=0 OR @DisplayStop=1)
	INNER JOIN dbo.PType_Units_Ext u ON U.PtypeID=P.typeId AND U.UnitsId=P.StockUnitId
	INNER JOIN dbo.PType_Units v ON v.UnitsId=u.UnitsId
	GROUP BY w.PtypeId

	CREATE TABLE #displayptype(
	    typeid VARCHAR(50))
	CREATE TABLE #displayptypetemp(
	    typeid VARCHAR(50))    
	    
	IF @PtypeIds<>''
	BEGIN
	INSERT INTO #displayptype
	SELECT a AS typeid FROM dbo.f_split(@PtypeIds,',')
	DECLARE @ptypesonnum INT=100
	WHILE @ptypesonnum<>0
	BEGIN
	INSERT INTO #displayptypetemp(typeid)
	SELECT typeid FROM #displayptype
	INSERT INTO #displayptype(typeid)
	SELECT typeid FROM dbo.ptype WHERE ParId IN (SELECT typeid FROM #displayptypetemp)
	SET @ptypesonnum=(SELECT SUM(sonnum) FROM dbo.ptype WHERE typeId IN (SELECT typeid FROM #displayptype) AND typeId NOT IN (SELECT typeid FROM #displayptypetemp))
	END
	END
	ELSE
	BEGIN
	INSERT INTO #displayptype
	SELECT typeid FROM #ptype
	END

		
	-- 不显示借欠受托,委托情况
	SELECT b.typeid,b.FullName,b.UserCode,b.sonnum,b.leveal,b.deleted,b.ParId,b.IfSerial,b.EntryCode
		,ISNULL(SUM(a.qty),0) AS Qty --数量
		,ISNULL(MAX(bu.fullname),'') AS bufullname --基本单位
		,ISNULL(SUM(a.Nqty),0) AS NQty --浮动数量
		,ISNULL(MAX(ku.rate),1) AS Rate -- 库存单位换算率
		--为父类的情况下kqty=qty
		,ISNULL(SUM(a.qty1),0) AS  KQty --库存数量
		,ISNULL(MAX(ku.fullname),'') AS kufullname --库存单位
		,ISNULL(MAX(asu.fullname),'') AS asufullname --辅助单位
		,ISNULL(SUM(tf.qty),0) AS fQty --数量
		,ISNULL(MAX(bu.fullname),'') AS fbufullname --基本单位
		,ISNULL(SUM(tf.Nqty),0) AS fNQty --浮动数量
		--为父类的情况下kqty=qty
		,ISNULL(SUM(tf.qty1),0) AS  fKQty --库存数量
		,ISNULL(MAX(ku.fullname),'') AS fkufullname --库存单位
		,ISNULL(MAX(asu.fullname),'') AS fasufullname --辅助单位
			,customassist=dbo.F_GetCustomAssist(b.typeid,ISNULL(SUM(a.qty),0)),
			e.btypeid,
			b1.fullname as btypefullname
	FROM #t a 
		RIGHT JOIN dbo.ptype b ON a.PtypeId LIKE b.typeId+'%' 
		RIGHT JOIN #ptype p ON  p.typeid = b.typeId
		LEFT JOIN dbo.PType_Price pr ON b.typeid=pr.PTypeID AND pr.UnitID=b.baseUnitId
		LEFT JOIN QP_PType_Ext e ON b.typeid= e.ptypeid
		LEFT JOIN dbo.btype b1 ON e.BTypeID= b1.typeid  	
		LEFT JOIN (
			SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
				JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
				WHERE u.PtypeID LIKE @innerPtypeId+'%'
		) ku ON b.typeId=ku.PtypeID AND b.StockUnitId=ku.UnitsId
		LEFT JOIN (
			SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
				JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
				WHERE u.PtypeID LIKE @innerPtypeId+'%'
		) bu ON b.typeId=bu.PtypeID AND b.baseUnitId=bu.UnitsId
		LEFT JOIN (
			SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
				JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
				WHERE u.PtypeID LIKE @innerPtypeId+'%'
		) asu ON b.typeid=asu.PtypeID AND b.AssistantUnitId=asu.UnitsId
		LEFT JOIN #tf tf ON tf.PtypeId=b.typeId
	WHERE (@DisplayStop=0 AND b.deleted=0 OR @DisplayStop=1) --是否显示停用商品
--	AND b.typeId IN (SELECT typeid FROM dbo.F_GetManPType(@OperatorID))
	AND b.sonnum=0
	AND b.typeId IN (SELECT typeId FROM #displayptype)
	AND b.typeId NOT IN (SELECT typeid FROM ptype WHERE IsService=1) --9.4服务商品不显示
	AND b.typeId NOT IN (SELECT typeid FROM ptype WHERE iscombinationproduct=1)
	GROUP BY b.typeid,b.FullName,b.UserCode,b.sonnum,b.leveal,b.deleted,b.ParId,b.IfSerial,b.EntryCode,b.SortID,e.btypeid,b1.fullname
	--显示、隐藏为零的项目
	HAVING @DisplayZero=1 OR @DisplayZero=0 AND ISNULL(SUM(a.qty),0)<>0
	ORDER BY b.SortID;

	DROP TABLE #BTType,#KStype,#Ktype,#cte,#goods,#inigoods,#t,#tf,#displayptype,#displayptypetemp
	
END
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_FaPiaoDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_FaPiaoDetail
GO

/*
	作者：蒋奎
	日期：2015-06-17
	描述：统计暂估类发票明细
*/
CREATE   PROCEDURE Web_FaPiaoDetail
(
	@chvOperator		varchar(100),	
	@BillNumberId		numeric(18,0),
	@KTypeId			varchar(1550),
	@STypeId			varchar(max),
	@PTypeId			varchar(MAX)
)
--@encode$--
AS
SET NOCOUNT ON 

Create table #Ktype(typeid varchar(50))

--仓库
INSERT INTO #Ktype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@chvOperator)	

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperator)	
--删除仓库中的对于STypeId
DELETE FROM #Ktype WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))	

 
 --最终数据 
	SELECT	Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillCode,
			Bil.FaPiaoCode,
			CASE Bil.FaPiaoType
				WHEN 1 THEN '增值税发票'
				WHEN 2 THEN '普通发票'
				ELSE '收据'
			END AS FaPiaoType,
			SUM(F.TaxTotal) AS TaxTotal,
			Bil.Billtype,
			ac.FullName AS cname,
			SUM(F.nTaxTotal) AS nTaxTotal
	FROM	ReceiptBillIndex Bil 
			INNER JOIN  ReceiptBill F ON Bil.BillNumberId = F.BillNumberId
			INNER JOIN #GetManSTypeId S ON Bil.STypeID = S.TypeId
			INNER JOIN dbo.Ac_Currency ac ON ac.CId= bil.CID
			
	WHERE	
			F.MainBillNumberID= @BillNumberId
			AND F.PTypeId = @PTypeId
			AND F.KTypeId IN (select typeid from #Ktype)
			AND Bil.ifcheck='t' AND Bil.RedWord=0
	GROUP BY
			Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillCode,
			Bil.FaPiaoCode,
			Bil.FaPiaoType,Bil.Billtype,ac.FullName
	ORDER BY Bil.BillDate DESC,Bil.BillCode DESC
	 


DROP TABLE #Ktype,#GetManSTypeId















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_FaPiaoHKDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_FaPiaoHKDetail
GO

/*
	作者：蒋奎
	日期：2015-06-17
	描述：统计回款付款发票明细
*/
CREATE   PROCEDURE Web_FaPiaoHKDetail
(
	@chvOperator		varchar(100),	
	@BillNumberId		numeric(18,0),
	@KTypeId			varchar(1550),
	@STypeId			varchar(max),
	@nType				varchar(20)
)
--@encode$--
AS
SET NOCOUNT ON 

Create table #Ktype(typeid varchar(50))

--仓库
INSERT INTO #Ktype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@chvOperator)	

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperator)	
--删除仓库中的对于STypeId
DELETE FROM #Ktype WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))	

IF @KTypeID=''
	insert into #Ktype select '10000'

IF @nType = 'buy'
	BEGIN
	SELECT	Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillCode,
			Bil.FaPiaoCode,
			CASE Bil.FaPiaoType
				WHEN 1 THEN '增值税发票'
				WHEN 2 THEN '普通发票'
				ELSE '收据'
			END AS FaPiaoType,
			SUM(F.TaxTotal) AS TaxTotal,
			Bil.Billtype,
			ac.FullName AS cname,
			SUM(F.nTaxTotal) AS nTaxTotal
	FROM	ReceiptBillIndex Bil,
			ReceiptBill F,
			#GetManSTypeId S,
			dbo.Ac_Currency ac
	WHERE	Bil.BillNumberId = F.BillNumberId
			AND Bil.STypeID = S.TypeId
			AND ac.CId= bil.CID
			AND Bil.RedWord=0
			AND Bil.Draft=0
			AND F.MainBillNumberId = @BillNumberId
			AND F.KTypeId IN (select typeid from #Ktype)
	GROUP BY
			Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillCode,
			Bil.FaPiaoCode,
			Bil.FaPiaoType,Bil.Billtype,ac.FullName
	ORDER BY Bil.BillDate DESC,Bil.BillCode DESC
	END 
ELSE
	BEGIN
	SELECT	Bil.BillNumberId,
					Bil.BillDate,
					Bil.BillCode,
					Bil.FaPiaoCode,
					CASE Bil.FaPiaoType
						WHEN 1 THEN '增值税发票'
						WHEN 2 THEN '普通发票'
						ELSE '收据'
					END AS FaPiaoType,
					SUM(T.TaxTotal) AS TaxTotal,
					Bil.Billtype,
					ac.FullName AS cname,
					SUM(T.NTaxTotal) AS nTaxTotal
			FROM	(
					SELECT	BillNumberID,
							TaxTotal,
							NTaxTotal
					FROM	ReceiptBill
					WHERE	MainBillNumberID = @BillNumberId
					
			) T
			INNER JOIN ReceiptBillIndex Bil ON T.BillNumberID = Bil.BillNumberID  
			INNER JOIN #GetManSTypeId S ON S.TypeId = Bil.Stypeid
			INNER JOIN dbo.Ac_Currency ac ON ac.CId = Bil.CID
			WHERE	Bil.RedWord=0
					AND Bil.Draft=0
			GROUP BY
			Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillCode,
			Bil.FaPiaoCode,
			Bil.FaPiaoType,
			Bil.Billtype,
			ac.FullName
			ORDER BY Bil.BillDate DESC,Bil.BillCode DESC
	END


DROP TABLE #Ktype,#GetManSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_FixedAssetsMonthProcCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_FixedAssetsMonthProcCheck]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.04.11
	描述：固定资产期末结账 “工作量法”的资产本期内未折旧数据
*/
CREATE PROCEDURE Web_FixedAssetsMonthProcCheck
(
	@Stypeid			VARCHAR(50)		-- 分支机构id
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @FYear			INT,	--年度
		@FPeriod		INT,	--期间
		@AssetStart		DATETIME,
		@AssetEnd		DATETIME


--开账后，获取指定分支机构当前财务期间		
SELECT @FPeriod = FPeriod,@FYear = FYear
FROM dbo.Ac_AccountsPeroid_Stype
WHERE Stypeid = @stypeid

--结账的分支机构及挂靠它的机构
CREATE TABLE #tempStype
(
	typeid VARCHAR(50)
)
INSERT INTO #tempStype(typeid)
SELECT typeid FROM stype WHERE VerifyID=@Stypeid

--获取固定资产当前期间开始时间
SELECT @AssetStart=FBegin,@AssetEnd=FEnd FROM dbo.Ac_Period WHERE FYear=@FYear AND FPeriod=@FPeriod

SELECT T1.usercode,T1.fullname FROM dbo.Ac_AssetsCards T1
INNER JOIN #tempStype T4 ON T4.typeid = T1.STypeId
INNER JOIN dbo.Ac_FixedAssetsInit_Stype T2 ON T1.STypeId = t2.StypeId
INNER JOIN dbo.Ac_AccountsPeroid_Stype T3 ON T2.StypeId = T3.Stypeid
WHERE T1.DepreciationMean = 5 
	AND T1.InAccountDate < @AssetStart
	AND T1.AssetsState NOT IN (2,5)
	AND NOT EXISTS
	(
		SELECT TT3.AssetCardId 
		FROM dbo.BillIndex TT1
		INNER JOIN #tempStype s ON TT1.Stypeid=s.typeid 
		INNER JOIN dbo.DepBill TT3 ON TT1.BillNumberId = TT3.BillNumberId
		WHERE TT1.BillDate >= @AssetStart AND TT1.BillDate <= @AssetEnd  
			AND TT1.BillType = 214 AND TT1.RedWord=0 AND TT1.ifcheck = 't' 
			AND TT3.AssetCardId = T1.ID
	)
	
DROP TABLE #tempStype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Format_PType_AuxiliaryUnits_Ext]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Format_PType_AuxiliaryUnits_Ext]
GO

CREATE PROCEDURE Web_Format_PType_AuxiliaryUnits_Ext
(
	@PTypeId		VARCHAR(50)	--商品ID
)
AS
SET NOCOUNT ON

DECLARE	@U1Name		VARCHAR(500),
		@U1Value	NUMERIC(24,10),
		@U2Name		VARCHAR(500),
		@U2Value	NUMERIC(24,10),
		@U3Name		VARCHAR(500),
		@U3Value	NUMERIC(24,10)

SELECT	@U1Name = ISNULL(SaleUnitID1,''),
		@U1Value = ISNULL(SaleUnitRate1,0), 
		@U2Name = ISNULL(SaleUnitID2,''),
		@U2Value = ISNULL(SaleUnitRate2,0),
		@U3Name = ISNULL(SaleUnitID3,''),
		@U3Value = ISNULL(SaleUnitRate3,0)
FROM	PType_AuxiliaryUnits_Ext 
WHERE	PtypeID = @PTypeId

CREATE TABLE #TempTable
(
	UnitName		VARCHAR(200),
	UnitValue		NUMERIC(24,10)
)

CREATE TABLE #Result
(
	nid				INT IDENTITY(1,1),
	UnitName		VARCHAR(200),
	UnitValue		NUMERIC(24,10)
)

INSERT INTO #TempTable(UnitName,UnitValue )VALUES(@U1Name,@U1Value)
INSERT INTO #TempTable(UnitName,UnitValue )VALUES(@U2Name,@U2Value)
INSERT INTO #TempTable(UnitName,UnitValue )VALUES(@U3Name,@U3Value)

INSERT INTO #Result(UnitName, UnitValue )
SELECT	UnitName, 
		UnitValue
FROM	#TempTable
ORDER BY UnitValue DESC

DECLARE @UnitName1		VARCHAR(500),
		@UnitValue1		NUMERIC(24,10),
		@UnitName2		VARCHAR(500),
		@UnitValue2		NUMERIC(24,10),
		@UnitName3		VARCHAR(500),
		@UnitValue3		NUMERIC(24,10)
		
SELECT 	@UnitName1 = UnitName,	@UnitValue1 = UnitValue FROM #Result WHERE nid = 1
SELECT 	@UnitName2 = UnitName,	@UnitValue2 = UnitValue FROM #Result WHERE nid = 2
SELECT 	@UnitName3 = UnitName,	@UnitValue3 = UnitValue FROM #Result WHERE nid = 3

UPDATE	PType_AuxiliaryUnits_Ext
SET		SaleUnitID1		= CASE WHEN @UnitName1 = '0' THEN NULL ELSE @UnitName1 END,
		SaleUnitRate1	= CASE WHEN @UnitValue1 = 0 THEN NULL ELSE @UnitValue1 END,
		SaleUnitID2		= CASE WHEN @UnitName2 = '0' THEN NULL ELSE @UnitName2 END,
		SaleUnitRate2	= CASE WHEN @UnitValue2 = 0 THEN NULL ELSE @UnitValue2 END,
		SaleUnitID3		= CASE WHEN @UnitName3 = '0' THEN NULL ELSE @UnitName3 END,
		SaleUnitRate3	= CASE WHEN @UnitValue3 = 0 THEN NULL ELSE @UnitValue3 END
WHERE	PtypeID			= @PTypeId		


DROP TABLE #TempTable,#Result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_FPeriodStartSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_FPeriodStartSet
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：lxl
	日期：2016.06.16
	描述：查询系统启用期间设置
*/
CREATE PROCEDURE Web_FPeriodStartSet
(
	@OperatorId		VARCHAR(50)	-- 当前操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

SELECT
	S.TypeId STypeId,
	S.FullName SFullName,
	--总账
	PS.SFYear ASFYear,
	PS.SFPeriod ASFPeriod,
	CASE WHEN ISNULL(PS.SFYear,0)=0 THEN NULL 
		 ELSE CAST(PS.SFYear AS VARCHAR(4))+'年'+CAST(PS.SFPeriod AS VARCHAR(2))+'期'
	END AStartText,
	PS.FYear AFYear,
	PS.FPeriod AFPeriod,
	CASE WHEN ISNULL(PS.FYear,0)=0 THEN NULL
		 ELSE CAST(PS.FYear AS VARCHAR(4))+'年'+CAST(PS.FPeriod AS VARCHAR(2))+'期' 
	END ACurrentText,
	ISNULL(PS.IsUse,0) AIsUse,
	CASE WHEN ISNULL(PS.IsUse,0)=1 THEN '√' ELSE '' END AIsUsedName,
	0 AIsEdit,
	--业务
	SU.SFYear BSFYear,
	SU.SFPeriod BSFPeriod,
	CASE WHEN ISNULL(SU.SFYear,0)=0 THEN NULL  
		  ELSE CAST(SU.SFYear AS VARCHAR(4))+'年'+CAST(SU.SFPeriod AS VARCHAR(2))+'期' end as BStartText,
	MP.[Year] BFYear,
	MP.period BFperiod,
	CASE WHEN ISNULL(MP.[Year],0)=0 THEN NULL  
		  ELSE CAST(MP.[Year] AS VARCHAR(4))+'年'+CAST(MP.period AS VARCHAR(2))+'期' end as BCurrentText,
	ISNULL(SU.Value,0) BIsUse,
	CASE WHEN ISNULL(SU.Value,0)=1 THEN '√' ELSE '' END BIsUsedName,
	0 BIsEdit,
	S.IsSelfVerify,
	S.VerifyID,
	VF.VerifyCount
FROM SType S 
INNER JOIN dbo.F_GetAllManagerBaseTypeId('',11,@OperatorId) F ON F.TypeId=S.TypeId
LEFT JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=S.VerifyID
LEFT JOIN (
	SELECT COUNT(*) VerifyCount,VerifyID FROM SType GROUP BY VerifyID
) VF ON VF.VerifyID=PS.Stypeid
LEFT JOIN SType_UserConfig SU ON SU.StypeId=S.TypeId 
LEFT JOIN MonthProc MP ON MP.STypeID=S.TypeId AND MP.MonthNo='本期'
WHERE 
	--S.IsSelfVerify=1 AND 
	S.sonnum=0 
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GainReportMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GainReportMonth]
GO

/*
	作者:武智均
	日期:2019-09-06
	描述:损益表按月比较
*/

CREATE   PROCEDURE Web_GainReportMonth
(
	@OperatorID	VARCHAR(50),		--操作员ID
	@StypeId	VARCHAR(max),		--分支机构id
	@HideZero	INT = 0,	-- 0显示，1隐藏
	@Leveal 	INT = 10    --项目级次
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @SQL VARCHAR(MAX),
		@ALL_INCOME_ID varchar(50) ='00003', --【收入类】      
		@ALL_EXPENSE_ID varchar(50)='00004' -- 【支出类】         
SET @Leveal = @Leveal + 1

-- 分支机构 - 月结开始时间和结束时间
CREATE TABLE #Stype (TypeID varchar(50))

-- 月结
CREATE TABLE #Months
(	
	StartDate	DATETIME,
	EndDate		DATETIME,
	MonthNo		VARCHAR(200),
	Period		VARCHAR(200),
	StypeId		VARCHAR(100),
	YEAR		INT
)

-- 临时存放结果集
CREATE TABLE #TEMP 
(
	USERCODE	VARCHAR(200),
	FULLNAME	VARCHAR(200),
	LEVEAL		INT,
	NTYPEID		VARCHAR(200),
	NPARID		VARCHAR(200),
	SONNUM		VARCHAR(200),
	MONTHNO		VARCHAR(200),
	TOTAL		NUMERIC(24, 10),
	CURRENTTOTAL NUMERIC(24, 10)
)

INSERT INTO #Stype(TypeID)
SELECT TypeId FROM dbo.F_BaseGetAllManagerBaseTypeId(@StypeId,11,@OperatorID)

IF NOT EXISTS (SELECT TOP 1 1 fROM #Stype)
BEGIN
	RETURN -1
END

-- INSERT INTO 	#Months
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'stypeindependentopen' AND SubValue = 1)  -- 启用分支机构独立
	 INSERT INTO #Months
	 SELECT	StartDate,
			EndDate,
			MonthNo,
			Period,
			STypeID,
			YEAR 
	 FROM 
		(
			SELECT	MonthNo,
					StartDate, 
					EndDate,
					Period,
					STypeID,
					Year 
			FROM	monthproc
			INNER JOIN #Stype S on STypeID=S.TypeID 
		)M 
			GROUP BY StartDate,EndDate,MonthNo,M.Year,Period,M.STypeID 
			ORDER BY Stypeid,M.Year,Period
ELSE
	 INSERT INTO #Months
	 SELECT	StartDate,
			EndDate,
			MonthNo,
			Period,
			STypeID,
			Year
	 FROM	MonthProc
	 WHERE	STypeID IN (SELECT TOP 1 s1.typeid FROM #Stype s1 
	 INNER JOIN stype s ON s1.TypeID=s.TypeID WHERE s.sonnum=0 )
	 ORDER BY Year,period

UPDATE #Months SET EndDate = '2099-01-01' WHERE EndDate IS NULL

DELETE #Months WHERE monthno='本期' AND StartDate<(SELECT MAX(StartDate) FROM #Months WHERE monthno='本期' )
--SELECT * FROM #Months


INSERT INTO #TEMP
SELECT  A.UserCode,
		A.FullName,
		A.Leveal,
		A.NTypeId,
		A.NParId,
		A.SonNum,
		tmp.MonthNo,
		SUM(ISNULL(tmp.Total,0))Total,
		SUM(ISNULL(tmp.CurrentTotal,0))CurrentTotal
FROM Ac_Items A
LEFT JOIN (
	SELECT	A1.nTypeId,
			L.MonthNo,
			0 TOTAL, 
			SUM(ISNULL(L.Total,0)) CurrentTotal
	FROM Ac_Items A1
	INNER JOIN (
		SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出）	
	) opera ON opera.ntypeid=A1.nTypeId
	LEFT JOIN (
			SELECT	B.MonthNo,
					LT.Total,
					LT.AtypeId,
					LT.CID,
					LT.STypeID 
			FROM	ListTable LT
			LEFT JOIN #Months B on LT.BillDate BETWEEN B.StartDate AND B.EndDate    
			) L ON L.AtypeId = A1.nId
	WHERE L.STypeID IN (SELECT * FROM #Stype) AND (A1.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A1.nTypeId LIKE @ALL_EXPENSE_ID+'%')
	GROUP BY A1.nTypeId,L.MonthNo
	UNION ALL
    SELECT	A1.nTypeId,
			L.MonthNo,
			SUM(ISNULL(L.Total,0)) TOTAL, 
			0 CurrentTotal
	FROM Ac_Items A1
	INNER JOIN (
		SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出）	
	) opera ON opera.ntypeid=A1.nTypeId
	LEFT JOIN (
			SELECT	B.MonthNo,
					LT.Total,
					LT.AtypeId,
					LT.CID,
					LT.STypeID 
			FROM ListTable LT
			LEFT JOIN #Months B on LT.BillDate<= B.EndDate    
			) L ON L.AtypeId = A1.nId
	WHERE L.STypeID IN (SELECT * FROM #Stype) AND (A1.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A1.nTypeId LIKE @ALL_EXPENSE_ID+'%')
	GROUP BY A1.nTypeId,L.MonthNo
)tmp ON tmp.nTypeId like A.nTypeId + '%' 
WHERE  A.ntypeId <> '00000' AND (A.nTypeId LIKE @ALL_INCOME_ID+'%'  OR  A.nTypeId LIKE @ALL_EXPENSE_ID+'%') AND A.Leveal <= @Leveal
GROUP BY A.UserCode,A.FullName,A.Leveal,A.ntypeId,A.NParId,A.SonNum,tmp.MonthNo

--判断损益表的权限
DECLARE @re INT 
EXEC @re = GP_CheckLimit @OperatorID,4225
IF @re =1	--没有查看损益表所有项目的权限
BEGIN
	DELETE 
	FROM	#TEMP 
	WHERE	NTypeId NOT IN (
		SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出）	
	)
END

-- 隐藏为0的数据
DELETE #TEMP WHERE @HideZero =1 AND TOTAL = 0 AND CURRENTTOTAL = 0

-- 修改显示格式
UPDATE #TEMP SET FullName ='    '+FullName WHERE Leveal =2
UPDATE #TEMP SET FullName ='        '+FullName WHERE Leveal =3
UPDATE #TEMP SET FullName ='            '+FullName WHERE Leveal =4
UPDATE #TEMP SET FullName ='                '+FullName WHERE Leveal =5
UPDATE #TEMP SET FullName ='                    '+FullName WHERE Leveal =6
UPDATE #TEMP SET FullName ='                        '+FullName WHERE Leveal =7
UPDATE #TEMP SET FullName ='                            '+FullName WHERE Leveal =8
UPDATE #TEMP SET FullName ='                                '+FullName WHERE Leveal =9
UPDATE #TEMP SET FullName ='                                    '+FullName WHERE Leveal =10		
		
SET @SQL = '	SELECT * FROM (
						SELECT	A.UserCode,
								A.FullName,
								A.Leveal,
								A.ntypeId,
								A.NParId,
								A.SonNum' 
SELECT @SQL = @SQL + ',SUM(CASE WHEN A.MONTHNO = '''+MONTHNO+''' THEN TOTAL ELSE 0 END) 
						 ['+MonthNo + '期末金额],SUM(CASE WHEN A.MONTHNO = '''+MONTHNO+''' THEN CURRENTTOTAL ELSE 0 END) 
						 ['+MonthNo+'本期发生额] ' FROM #Months
						 
SET @SQL += '	FROM #TEMP A 
				GROUP BY A.UserCode,A.FullName,A.Leveal,A.ntypeId,A.NParId,A.SonNum 
				
				UNION ALL 
				SELECT	'''',
				''【利    润】'',
				1,
				''999999999999999'',
				'''',
				0  '
SELECT @SQL = @SQL + ',(SELECT SUM(CASE WHEN ntypeId = ''00004'' THEN -TOTAL ELSE TOTAL END) 
				FROM #TEMP WHERE MONTHNO = '''+MONTHNO+''' AND LEVEAL = 1 ),
				(SELECT SUM(CASE WHEN ntypeId = ''00004'' THEN -CURRENTTOTAL ELSE CURRENTTOTAL END)
				 FROM #TEMP WHERE MONTHNO = '''+MONTHNO+''' AND LEVEAL = 1 ) ' FROM #Months
				 
SET @SQL += ')X ORDER BY X.NTYPEID'
EXEC (@SQL)

DROP TABLE #TEMP,#Months,#Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetAcAccountSetDetail]') and OBJECTPROPERTY(id,
		 N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetAcAccountSetDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/31
	Description	:	获取系统预置科目表
*/

CREATE PROCEDURE Web_GetAcAccountSetDetail
(
	@SubID int,
	@ParID varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON


declare @level int;

SET @ParID = LTRIM(RTRIM(@ParID));

set @level = case @ParID 
				when '' then 0
				else 1
			end;

select 
		DtId,
		d.SubId,
		l.fullname AS SubName,
		[Group],
		TypeId,
		ParId,
		Leveal,
		SonNum,
		SonCount,
		case Leveal 
			when 3 then '    ' 
			when 4 then '        ' 
			else '' 
		end + UserCode as usercode,
		d.FullName,
		Name,
		Fdc,
		IsCash,
		IsBank,
		d.Comment,
		PyCode,
		CASE d.Fdc
			WHEN 1 THEN '借'
			WHEN -1 THEN '贷' 
			ELSE ''
		END AS fdcname
FROM Ac_Account_Set_Detail d
JOIN Ac_Account_Set_List l ON l.SubId = @SubID
	WHERE ParId LIKE @ParID + '%' 
	AND	d.SubId = @SubID
	AND	Leveal > @level 
	AND usercode > ''	--其实这个地方本意是应该 usercode <> ''，
						--但是对于空字符串 usercode <> '' 等效于 usercode > ''
						--并且usercode > ''能利用索引,而usercode <> ''不能
		order by d.UserCode 


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetAccontInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetAccontInfo
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2013-02-28
-- Description: 得到帐套的操作员个数，单据量等信息
-- =============================================
CREATE PROCEDURE Web_GetAccontInfo
(
	@flag INT, --0 表示只读当前帐套，1 表示读所有帐套
	@version VARCHAR(200),  --当前版本
	@zttablename VARCHAR(200),
	@databaseName VARCHAR(max)
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
	CREATE TABLE #result(databasename VARCHAR(200))
	INSERT INTO #result SELECT a FROM dbo.f_split(@databaseName,',')


	DECLARE @usercount INT=0,
			@billcount INT=0,
			@strSql NVARCHAR(2000),
			@tablename  VARCHAR(200),
			@intexists TINYINT,
			@isActived TINYINT,
			@isVerisonData TINYINT,
			@tmpusercount INT,
			@tmpbillcount INT

	IF @flag = 0
	BEGIN
		SELECT @usercount= COUNT(1) FROM loginuser
		SELECT @billcount = COUNT(1) FROM BillIndex
	END
	IF @flag = 1
	BEGIN
		declare cursorname cursor  
		local scroll static 
		  for  select databasename FROM #result
		open cursorname
		fetch next from cursorname
			into @tablename  
		while @@FETCH_STATUS=0
		begin
			set @strSql='use ['+@tablename+']'+CHAR(13)
			set @strSql=@strsql+'if exists(select 1 from dbo.sysobjects where id = object_id(N''[dbo].['+@zttablename+']'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1) set @intexists=1 else set @intexists=0 '	
			EXECUTE sp_executesql @strSql,N'@intexists tinyint OUTPUT',@intexists OUTPUT
			--PRINT @strSql
			--IF @intexists=1
			--BEGIN
			--	set @strSql='use ['+@tablename+']'+CHAR(13)
			--	set @strSql=@strsql+'SELECT @isActived=Actived FROM '+@zttablename
			--	EXECUTE sp_executesql @strSql,N'@isActived tinyint OUTPUT',@isActived OUTPUT
			--END
			IF @intexists = 1
			BEGIN
				set @strSql='use ['+@tablename+']'+CHAR(13)
				set @strSql=@strsql+'if exists(SELECT 1 FROM sysdata WHERE SubName=''Version'' AND SubValue='''+@version+''') set @isVerisonData=1 else set @isVerisonData=0 '	
				EXECUTE sp_executesql @strSql,N'@isVerisonData tinyint OUTPUT',@isVerisonData OUTPUT
				--PRINT (@strSql)
			END
			if @intexists=1  AND @isVerisonData=1 --AND @isActived = 1
			BEGIN
				set @strSql='use ['+@tablename+']'+CHAR(13)
				set @strSql=@strsql+' SELECT @tmpusercount= COUNT(1) FROM loginuser ; SELECT @tmpbillcount = COUNT(1) FROM BillIndex '	
				EXECUTE sp_executesql @strSql,N'@tmpusercount INT OUTPUT,@tmpbillcount INT OUTPUT',@tmpusercount OUTPUT,@tmpbillcount OUTPUT
				PRINT @tablename
				SELECT @usercount=@usercount+@tmpusercount
				SELECT @billcount=@billcount+@tmpbillcount
			END
			SELECT @intexists=0,@isActived=0,@isVerisonData=0
			
		fetch next from cursorname
		into @tablename
		END
		CLOSE cursorname
		DEALLOCATE cursorname
	END
	SELECT ISNULL(@usercount,0) AS usercount,ISNULL(@billcount,0) AS billcount
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetAcItemsWithLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetAcItemsWithLimit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.12.27
	描述：获取权限范围内的所有项目
*/
CREATE PROCEDURE Web_GetAcItemsWithLimit
(
	@OperatorId			VARCHAR(50)		-- 当前操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @sql VARCHAR(MAX)

SET @sql='SELECT * FROM
			(SELECT 
				item.nId, 
				item.UserCode, 
				item.FullName,
				item.comment,
				item.deleted
		 FROM Ac_Items item'+CHAR(13)
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeID = @OperatorID AND MangerATypeID='-99999')
		SET @sql+= '	INNER JOIN AType_L a ON a.ETypeID = '''+@OperatorID+''' AND a.Flag = ''1'' AND a.TypeID = item.nId '+CHAR(13)
SET @sql+='	WHERE  TypeName=''B'''+CHAR(13)

SET @SQL+=' UNION ALL
			SELECT
				item.nId,
				item.UserCode,
				item.FullName,
				item.comment,
				item.deleted
			FROM Ac_Items item 
		 WHERE  item.TypeName=''G'''
IF(@OperatorID NOT IN('00000','00001') AND (SELECT TOP 1 1 FROM LoginUser WHERE ETypeID =@OperatorID AND MangerIncome<>'0000')=1)	
	BEGIN
		SET @SQL+=' AND (UserCode NOT IN(''0332'',''0333'',''03333'') AND Sysrow=1)'+CHAR(13)
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeID =@OperatorID AND MangerIncome='-99999')
			SET @SQL+= '	OR  (item.nId IN (SELECT TypeID FROM AType_L  WHERE ETypeID = '''+@OperatorID+''' AND Flag = ''1'') AND item.TypeName=''G'') '
	END
SET @Sql += ' UNION ALL
			 SELECT
				item.nId,
				item.UserCode,
				item.FullName,
				item.comment,
				item.deleted
				FROM Ac_Items item 
			 WHERE  item.TypeName=''E'''
			 
IF(@OperatorID NOT IN('00000','00001')AND (SELECT TOP 1 1 FROM LoginUser WHERE ETypeID =@OperatorID AND MangerExpense<>'0000')=1)
	BEGIN
		SET @SQL+= ' AND (UserCode IN(''0404'',''0421'',''0422'',''0423'',''0424'',''5401'')  AND Sysrow=1)'+CHAR(13)
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeID =@OperatorID AND MangerExpense='-99999')
				SET @SQL+= '	OR  (item.nId IN (SELECT TypeID FROM AType_L WHERE ETypeID = '''+@OperatorID+''' AND Flag = ''1'') AND item.TypeName=''E'')'
	END	

SET @sql+=' UNION ALL
		 SELECT 
			item.nId,
			item.UserCode, 
			item.FullName,
			item.comment,
			item.deleted
		 FROM Ac_Items item'+CHAR(13)
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeID = @OperatorID AND MangerCpaital='-99999')
		SET @sql+= '	INNER JOIN AType_L a ON a.ETypeID = '''+@OperatorID+''' AND a.Flag = ''1'' AND a.TypeID = item.nId '+CHAR(13)
SET @sql+='	WHERE  TypeName=''F'''+CHAR(13)

SET @SQL+=' UNION ALL
			SELECT
				item.nId,
				item.UserCode,
				item.FullName,
				item.comment,
				item.deleted 
				FROM Ac_Items item 
		 WHERE  item.TypeName IN (''C'',''L'')  )T'
SET @sql+=' ORDER BY UserCode'
EXEC (@sql)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetAcPeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetAcPeriod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.4.24
	描述：获取当前年度所有会计期间
*/
CREATE PROCEDURE Web_GetAcPeriod
(
	@OperatorId			VARCHAR(50),	-- 当前操作员ID
	@STypeId			VARCHAR(50)		-- 分支机构
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @FYear INT

--存在多个年度
IF (select count(*) from (select distinct Fyear from Ac_Period) t1) >1
BEGIN	
	SELECT FYear,FPeriod,FBegin,FEnd FROM dbo.Ac_Period WHERE FYear in ((select distinct Fyear from Ac_Period)
	) order by FYear desc,FPeriod asc
END
ELSE --只有一个年度
BEGIN
	--获取年度
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @STypeId)
	BEGIN
		SELECT @FYear = SubValue FROM dbo.sysdata WHERE SubName = 'fyear'
	END
	ELSE
	BEGIN
		SELECT @FYear = FYear FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @STypeId
	END
	--如果存在没有的年度
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FYear = @FYear)
	BEGIN
		SELECT FYear,FPeriod,FBegin,FEnd FROM dbo.Ac_Period WHERE FYear=(select top 1 FYear from Ac_Period group by FYear order by FYear desc)
	END
	ELSE
	BEGIN
		SELECT FYear,FPeriod,FBegin,FEnd FROM dbo.Ac_Period WHERE FYear = @FYear
	END
	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetAddItemDetailsStypeList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_GetAddItemDetailsStypeList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	新增项目Ac_Items_Detail显示列表
-- 时间：	2013-02-06
-- 作者：	古丽娟

-- ========================================================================
CREATE PROC Web_GetAddItemDetailsStypeList
(
    @OperatorID	VARCHAR(50)		-- 操作员
)

--@encode$--

AS
SET NOCOUNT ON 
DECLARE @SQL VARCHAR(MAX)='
SELECT 
	distinct
	0 DId,
	0 nid,
	s.TypeId STypeId,
	s.FullName sfullname,
	'''' ATypeId,
	'''' afullname,
	'''' DepATypeId,
	'''' depfullname,
	'''' DisATypeId,
	'''' disfullname
FROM SType s
INNER JOIN dbo.F_GetAllManagerBaseTypeId('''',11,'''+@OperatorID+''') F ON F.TypeId=s.TypeId'+CHAR(13)

SET @SQL+='
WHERE 
	s.deleted=0 AND
	s.sonnum=0'
--PRINT @SQL
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetAllItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetAllItems
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2012-07-23
-- Description: 查询所有项目并加入大类
-- 2014-01-21 周华 开放权益类
-- =============================================
CREATE PROCEDURE Web_GetAllItems
(
	@softType VARCHAR(200)
)
--@encode$--
AS	
SET NOCOUNT ON
	
SELECT	a.nid as TypeID,
		nTypeId, 
		a.UserCode, 
		a.FullName, 
		ISNULL(b.SubjectCode, '') AS SubjectCode,
		case 
		when b.J_D is null 
			then case 
				when a.TypeName IN('B','F','C','E') 
					then '1' 
				else 
					'0' 
					end  
		else b.J_D end as J_D  
		FROM AC_items a 
		LEFT JOIN AccountSubjectSet b ON a.nId = b.ATypeID AND SoftType = @softType 
		WHERE nTypeId <> '00000' 
			--AND nTypeId <> '00005' 
			--AND nParID <> '00005' 
			AND a.FullName <> '借转采购结算与成本差'  
			AND a.FullName <>'『借入商品』' 
			AND a.FullName <>'『借出商品』' 
			AND a.FullName <> '借转进货结算与成本差' 
		ORDER BY nTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetAtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_GetAtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--作    者：胡小科 
--日    期：2012-06-18  
--作    用：插入单据往来科目 


CREATE     PROCEDURE [dbo].[Web_GetAtype]
(
	@billtypeid			[varchar](50),
	@stypeid			[varchar](50),
	@OperatorId			VARCHAR(50)=''
)
--@encode$--
AS
SET NOCOUNT ON 

SELECT @stypeid = VerifyID FROM dbo.SType WHERE TypeId = @stypeid

CREATE TABLE #TmpAccount
(
	TypeId	VARCHAR(50),
	Stypeid	VARCHAR(50)
)
IF @OperatorId <> '00001'
	INSERT INTO #TmpAccount
			( TypeId, Stypeid )
	SELECT Typeid,Stypeid
	FROM dbo.F_LineAccount(@OperatorId,@stypeid)
ELSE
	INSERT INTO #TmpAccount
			( TypeId, Stypeid )
	SELECT TypeId,StypeId
	FROM dbo.Ac_Account
	WHERE StypeId = @stypeid

IF EXISTS(SELECT * FROM [SType] WHERE [TypeId]=@stypeid AND IsSelfVerify=1)
BEGIN
	IF @billtypeid = '404'--404同时具有两个往来科目
	BEGIN
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
				ELSE
					CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
			END AS atypeid1name,
			'jie' AS flag 
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
			ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId=@stypeid AND a.BillTypeId=@billtypeid + '_jie'
		
		UNION ALL
		
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
				ELSE
					CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
			END AS atypeid1name,
			'dai' AS flag 
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
			ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId=@stypeid AND a.BillTypeId=@billtypeid + '_dai'
		
	END
	ELSE IF @billtypeid = '36'
	BEGIN
		SELECT a.AtypeId AS atypeid1,
		CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
			ELSE
				CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
		END AS atypeid1name,
		'server' AS flag 
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
			ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId=@stypeid AND a.BillTypeId=@billtypeid + '_server'
		
		UNION ALL
		
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
				ELSE
					CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
			END AS atypeid1name,
			'client' AS flag 
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
			ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId=@stypeid AND a.BillTypeId=@billtypeid + '_client'
	END 
	ELSE
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
				ELSE
					CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
			END AS atypeid1name,
			'' AS flag
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
			ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId=@stypeid AND a.BillTypeId=@billtypeid
	
	DROP TABLE #TmpAccount
	RETURN 0--分支机构是独立核算
END
ELSE IF EXISTS(SELECT * FROM [SType] WHERE [TypeId]=@stypeid AND VerifyID IS NOT NULL)
BEGIN
	IF @billtypeid = '404'--404同时具有两个往来科目
	BEGIN
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
					ELSE
						CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
				END AS atypeid1name,
			'jie' AS flag 
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
		ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId IN(SELECT VerifyID FROM [SType] WHERE [TypeId]=@stypeid) AND a.BillTypeId=@billtypeid + '_jie'
		
		UNION ALL
		
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
					ELSE
						CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
				END AS atypeid1name,
			'dai' AS flag
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
		ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId IN(SELECT VerifyID FROM [SType] WHERE [TypeId]=@stypeid) AND a.BillTypeId=@billtypeid + '_dai'
	END
	ELSE IF @billtypeid = '36'
	BEGIN
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
					ELSE
						CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
				END AS atypeid1name,
			'server' AS flag 
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
		ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId IN(SELECT VerifyID FROM [SType] WHERE [TypeId]=@stypeid) AND a.BillTypeId=@billtypeid + '_server'
		
		UNION ALL
		
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
					ELSE
						CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
				END AS atypeid1name,
			'client' AS flag
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
		ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId IN(SELECT VerifyID FROM [SType] WHERE [TypeId]=@stypeid) AND a.BillTypeId=@billtypeid + '_client'
	END 
	ELSE
		SELECT a.AtypeId AS atypeid1,
			CASE WHEN ISNULL(a.ATypeId,'') = '' THEN ''
					ELSE
						CASE WHEN ISNULL(c.Typeid,'') = '' THEN '****' ELSE b.FullName END
				END AS atypeid1name,
			'' AS flag 
		FROM [BillAtype] a  
		LEFT JOIN  dbo.Ac_Account b
		ON a.AtypeId=b.typeId AND a.StypeId=b.StypeId 
		LEFT JOIN #TmpAccount c 
			ON a.AtypeId = c.Typeid AND a.StypeId = c.Stypeid
		WHERE a.StypeId IN(SELECT VerifyID FROM [SType] WHERE [TypeId]=@stypeid) AND a.BillTypeId=@billtypeid
	
	DROP TABLE #TmpAccount
	RETURN 1--分支机构是非独立核算
END
ELSE
BEGIN
RETURN 2 --分支机构是非独立核算，没有选择非独立核算的记账单位
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
















if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetAuditingBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetAuditingBillDetail]
GO

/*
作者：谢吉康
日期：2004-10-11
描述：拆分单据审核历史

2013-04-12 周华 修改 审核步骤中，只要没有权限的操作员就不显示出来
*/

/*
	修改者：杨俊
	日期：2014-11-28
	描述：增加对 已审核列表 的支持   @IfAudit = 0 查询待审核，@IfAudit = 1 查询已审核
*/
CREATE PROCEDURE Web_GetAuditingBillDetail
(
	@OperatorId		VARCHAR(MAX),	--操作员ID
	@BillNumberId	VARCHAR(MAX),	--单据ID
	@BillIndexType	VARCHAR(MAX),	--单据类型  0.订单  2.普通单据
	@IfAudit		INT,			--0为待审核列表查询，1为已审核列表查询
	@IsPlateAlready INT				--是否为已审核列表
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Detail		VARCHAR(MAX),
		@A			VARCHAR(MAX),
		@ETypeId	VARCHAR(MAX),
		@BillDate	VARCHAR(20),
		@Step1		VARCHAR(255),
		@FullName	VARCHAR(300),
		@AudState	VARCHAR(300),	
		@AudExp		VARCHAR(1000),
		@AudType	VARCHAR(20),
		@Step2		VARCHAR(255),
		@BillType	VARCHAR(20),
		@STypeId	VARCHAR(MAX),
		@AuditingId INT;
		
--分支机构
IF @BillIndexType='4'
	SELECT @STypeId=stypeid FROM dbo.CommissionBillNew WHERE BillNumberId=@BillNumberId
ELSE
IF @BillIndexType='3'
	SELECT @STypeId=stypeid FROM dbo.RequestIndex WHERE BillNumberId=@BillNumberId
ELSE IF @BillIndexType = '2'
	SELECT @STypeId = STypeId FROM BillIndex WHERE BillNumberId = @BillNumberId
ELSE IF @BillIndexType = '1'
	SELECT @STypeId = STypeId FROM LendIndex WHERE BillNumberId = @BillNumberId
ELSE IF @BillIndexType = '5'
	SELECT @STypeId = STypeId FROM dbo.ReceiptBillIndex WHERE BillNumberId = @BillNumberId
ELSE IF @BillIndexType = '7'
	SELECT @STypeId = STypeId FROM dbo.FactIndex WHERE BillNumberId = @BillNumberId
ELSE IF @BillIndexType = '9'
	SELECT @STypeId = STypeId FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId = @BillNumberId	
ELSE
	SELECT @STypeId = STypeId FROM OrderIndex WHERE BillNumberId = @BillNumberId

--SET @Detail='2011-02-14ж1ж小刘ж1ж001ж1ж1жи2011-02-14ж2ж经理ж1ж002ж1ж2жи'
SELECT @Detail = BillDetail,@AuditingId=AuditingID FROM AuditingBill WHERE BillNumberID = @BillNumberId AND BillIndexType = @BillIndexType

CREATE TABLE #Detail
(
	nid		int identity(1,1),
	Value	VARCHAR(MAX)
)

CREATE TABLE #BillDetail
(
	BillDate	VARCHAR(20),
	Step1		VARCHAR(255),
	ETypeId		VARCHAR(100),
	FullName	VARCHAR(300),
	AudState	VARCHAR(300),	
	AudExp		VARCHAR(1000),
	AudType		VARCHAR(20),
	Step2		VARCHAR(255)
)

CREATE TABLE #Employee
(
	ETypeId				VARCHAR(MAX),
	Step				VARCHAR(MAX),
	AuditingDescription	VARCHAR(MAX),
	AuditFs				VARCHAR(MAX)
)


-------------审核类型-------------
SELECT TOP 1 @AudType= CASE WHEN AuditingType = '1' THEN '顺序' WHEN AuditingType = '2' THEN '任意' ELSE '会签' END  FROM AuditingFlowSet WHERE AuditingID=@AuditingId;
-------------审核类型-------------

-------------从AuditingBillDetail取审核明细--------
INSERT INTO #BillDetail
	(
		BillDate,
		Step1,
		ETypeId,
		FullName,
		AudState,	
		AudExp,
		AudType,
		Step2
	)

--SELECT	  CONVERT(VARCHAR(20),A.AuditingDate,120),
--		   B.AuditingDescription,
--		   A.ETypeID,
--		   C.FullName,
--		   A.AuditingFlag,
--		   A.AuditingExplain,
--		   @AudType,
--		   A.AuditingStep
--	FROM AuditingBillDetail A 
--	INNER JOIN AuditingFlowDetail B ON A.BillNumberID=@BillNumberId AND B.AuditingID=@AuditingId AND A.AuditingStep=B.AuditingStep
--	INNER JOIN employee C ON A.ETypeID=C.typeId
SELECT 
CONVERT(VARCHAR(20),A.AuditingDate,120),
C.AuditingDescription,
A.ETypeID,
D.FullName,
A.AuditingFlag,
A.AuditingExplain,
@AudType,
A.AuditingStep 
FROM AuditingBillDetail AS A 
INNER JOIN AuditingBill AS B ON(A.BillNumberID = B.BillNumberID AND A.BillIndexType = B.BillIndexType)
INNER JOIN AuditingFlowDetail AS C ON(C.AuditingID = B.AuditingID AND C.AuditingStep = A.AuditingStep)
INNER JOIN employee AS D ON(D.typeId = A.ETypeID)
WHERE B.BillNumberID = @BillNumberId AND B.BillIndexType = @BillIndexType AND B.AuditingID = @AuditingId
-------------------------------------------------------

IF @Detail <> ''
	BEGIN
		INSERT INTO #Employee
		SELECT	D.ETypeId,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingBill B,
				AuditingFlowSet F,
				AuditingFlowDetail D
		WHERE	B.AuditingID = D.AuditingID
				AND F.AuditingID = d.AuditingID
				AND B.BillNumberID = @BillNumberId
				AND B.BillIndexType = @BillIndexType		
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
		IF EXISTS(SELECT TOP 1 1 FROM #BillDetail WHERE ETypeId = '00001')
			INSERT INTO #Employee(ETypeId)VALUES('00001')
	END
ELSE IF @BillIndexType = '1'	--借欠类单据
BEGIN
		SELECT @BillType = BillType FROM LendIndex WHERE BillNumberId = @BillNumberId 
		
		INSERT INTO #Employee
		SELECT	D.ETypeID,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingFlowDetail D,
				AuditingFlowSet F
		WHERE	F.AuditingID = D.AuditingID
				AND D.BillType = @BillType 
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
END
ELSE IF @BillIndexType = '2'
	BEGIN
		SELECT @BillType = BillType FROM BillIndex WHERE BillNumberId = @BillNumberId 
		
		INSERT INTO #Employee
		SELECT	D.ETypeID,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingFlowDetail D,
				AuditingFlowSet F
		WHERE	F.AuditingID = D.AuditingID
				AND D.BillType = @BillType 
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
	END	
ELSE IF @BillIndextype='3' --请购单
BEGIN
		SELECT @BillType = BillType FROM dbo.RequestIndex WHERE BillNumberId = @BillNumberId 
		
		INSERT INTO #Employee
		SELECT	D.ETypeID,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingFlowDetail D,
				AuditingFlowSet F
		WHERE	F.AuditingID = D.AuditingID
				AND D.BillType = @BillType 
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
END
ELSE IF @BillIndextype='4' --提成单
BEGIN
		SET @BillType = 311		
		INSERT INTO #Employee
		SELECT	D.ETypeID,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingFlowDetail D,
				AuditingFlowSet F
		WHERE	F.AuditingID = D.AuditingID
				AND D.BillType = @BillType 
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
END
ELSE IF @BillIndextype='5' --发票类单据
BEGIN
		SELECT @BillType = BillType FROM dbo.ReceiptBillIndex WHERE BillNumberId = @BillNumberId 
		
		INSERT INTO #Employee
		SELECT	D.ETypeID,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingFlowDetail D,
				AuditingFlowSet F
		WHERE	F.AuditingID = D.AuditingID
				AND D.BillType = @BillType 
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
END
ELSE IF @BillIndextype='7' --仓库
BEGIN
		SELECT @BillType = BillType FROM dbo.FactIndex WHERE BillNumberId = @BillNumberId 
		
		INSERT INTO #Employee
		SELECT	D.ETypeID,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingFlowDetail D,
				AuditingFlowSet F
		WHERE	F.AuditingID = D.AuditingID
				AND D.BillType = @BillType 
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
END
ELSE IF @BillIndextype='9' --门店配送类的单据
BEGIN
		SELECT @BillType = BillType FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId = @BillNumberId 
		
		INSERT INTO #Employee
		SELECT	D.ETypeID,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingFlowDetail D,
				AuditingFlowSet F
		WHERE	F.AuditingID = D.AuditingID
				AND D.BillType = @BillType 
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
END
ELSE
	BEGIN
		SELECT @BillType = BillType FROM OrderIndex WHERE BillNumberId = @BillNumberId 
		
		INSERT INTO #Employee
		SELECT	D.ETypeID,
				D.AuditingStep,
				D.AuditingDescription,
				F.AuditingType
		FROM	AuditingFlowDetail D,
				AuditingFlowSet F
		WHERE	F.AuditingID = D.AuditingID
				AND D.BillType = @BillType 
				AND F.STypeID = @STypeId
				AND D.ETypeID<>''
	END		
	
--审核原因，带步骤的
CREATE TABLE #Reason
(
	nID				INT IDENTITY(1,1),
	BillNumberId	VARCHAR(MAX),
	BillType		VARCHAR(MAX),
	PassFlag		VARCHAR(MAX),
	Reason			VARCHAR(MAX),
	Value			VARCHAR(MAX),
	AuditingStep	VARCHAR(MAX)
)

INSERT INTO #Reason EXEC GP_BillAudtingCheckReason @BillNumberId,@OperatorId,@BillIndexType,'需要审核原因',-1,1,@IsPlateAlready  
--SELECT * FROM #Reason
--处理#Reason里面的值
DECLARE @Reason VARCHAR(MAX),
		@ResId	INT

DECLARE Reason_Cursor CURSOR FOR
	SELECT nId,Reason FROM #Reason
	
OPEN Reason_Cursor

FETCH NEXT FROM Reason_Cursor INTO @ResId,@Reason

WHILE @@FETCH_STATUS = 0
	BEGIN
		--单独处理预设进价
		IF LEFT(RIGHT(@Reason,6),4) = '预设进价'
			SET @Reason = RIGHT(@Reason,6)
		
		--单独处理预设售价
		IF LEFT(RIGHT(@Reason,6),4) = '预设售价'	
			SET @Reason = LEFT(RIGHT(@Reason,6),5)
			
		--出入库审核
		IF RIGHT(@Reason,6) = '必须全部审核'
			SET @Reason = RIGHT(@Reason,6)
			
		--商品售价小于等于成本价审核
		IF LEFT(@Reason,15) = '商品售价小于等于成本价均价审核'
			SET @Reason = LEFT(@Reason,15)	
		--比成本价低__%销售审核			
		IF LEFT(@Reason,5) = '比成本价低'	
			SET @Reason = LEFT(@Reason,CHARINDEX('审核',@reason)+1)	
		--比成本价低__%销售审核			
		IF LEFT(@Reason,5) = '毛利总额从'	
			SET @Reason = '毛利总额从'	
		--商品售价低于最低售价审核	
		IF LEFT(@Reason,12) = '商品售价低于最低售价审核'	
			SET @Reason = '商品售价低于最低售价审核'		
		/*
		IF NOT EXISTS(SELECT * FROM AuditingBill WHERE BillNumberID = @BillNumberId AND BillIndexType = @BillIndexType AND CHARINDEX(@Reason,StepReasons)>0)
	
			DELETE FROM #Reason WHERE nID = @ResId--暂时屏蔽
		*/	
		FETCH NEXT FROM Reason_Cursor INTO @ResId,@Reason
	END
	
CLOSE Reason_Cursor
DEALLOCATE Reason_Cursor	
--SELECT * FROM #Reason
--保存结果
CREATE TABLE #Result
(
	BillDate			VARCHAR(20),
	Step				INT,--VARCHAR(20),
	AuditingDescription	VARCHAR(MAX),
	Step1				VARCHAR(255),
	ETypeId				VARCHAR(100),
	FullName			VARCHAR(300),
	AudState			int,	
	AudExp				VARCHAR(MAX),
	AudType				VARCHAR(20),
	Step2				VARCHAR(255),
	AuditFs				VARCHAR(MAX)
)

INSERT INTO #Result
SELECT	B.BillDate,
		CAST(CASE WHEN ISNULL(B.Step,'')='' THEN B.Step2 ELSE B.Step END AS INT) AS Step,
		B.AuditingDescription,
		B.Step1,
		B.ETypeId,
		B.FullName,
		isnull(B.AudState,0),	
		B.AudExp,
		B.AudType,
		B.Step2,
		B.AuditFs
FROM	(	
			SELECT	E.ETypeId,
					E.Step,
					E.AuditingDescription,
					M.BillDate,
					M.Step1,					
					M.FullName,
					M.AudState,	
					M.AudExp,
					M.AudType,
					M.Step2,
					E.AuditFs
			FROM	#Employee E
			LEFT JOIN (
				SELECT	*
				FROM	#BillDetail
			)M ON E.ETypeId = M.ETypeId AND E.Step = M.Step2
)B 

-- // 搬敏捷
IF EXISTS(SELECT 1 FROM dbo.BillIndex WHERE BillNumberId=@BillNumberId AND billtype IN (17,21)) AND @BillIndexType=2

BEGIN
		SELECT	DISTINCT
			T.*,
			CASE WHEN T.AuditFs = '1' THEN '顺序审核' WHEN T.AuditFs = '2' THEN '任意审核' ELSE '会签审核' END AS AuditTypeName,
			R.Reason,
			--R.Value AS ReasonValue,
			CASE WHEN T.Step = '0' THEN '特审' ELSE '正常审核' END AS StepName,
			CAST(T.Step AS VARCHAR(20)) + '级审核人' AS StepPerson,
			R.PassFlag --0.需要审核 1.无需审核		
	FROM	#Result T
	LEFT JOIN (
		--SELECT	*
		--FROM	#Reason		
		SELECT a.*,CASE c.OutKty WHEN 'o' THEN d.ktypeid WHEN 'i' THEN d.ktypeid2 END AS ktypeid  
		FROM #Reason a
			JOIN AuditingFlowSet b  ON a.billtype =b.billType
			JOIN AuditingStepReason c ON b.AuditingID=c.AuditingID AND c.AuditingStep=a.AuditingStep
			JOIN dbo.BillIndex d ON a.BillNumberId=d.BillNumberId
	) R ON T.Step = R.AuditingStep 
		AND (
			EXISTS(SELECT 1 FROM LoginUser WHERE ETypeId=t.ETypeId AND MangerKTypeId<>-99999)
			AND EXISTS(SELECT 1 FROM dbo.Stock WHERE typeId=r.ktypeid AND deleted=0 AND sonnum=0)
			OR 
			EXISTS (SELECT 1 FROM dbo.ktype_l WHERE  etypeid = t.ETypeId AND r.ktypeid LIKE typeid + '%' AND flag = 1)
			)
	WHERE R.PassFlag = '0' /*(NOT(@IfAudit = 0) AND r.PassFlag IS NOT NULL
		OR (@IfAudit = 0) AND (R.PassFlag = '0'))  */
		
	ORDER BY T.Step ASC
END
ELSE
BEGIN
SELECT	DISTINCT
		T.*,
		CASE WHEN T.AuditFs = '1' THEN '顺序审核' WHEN T.AuditFs = '2' THEN '任意审核' ELSE '会签审核' END AS AuditTypeName,
		R.Reason,
		--R.Value AS ReasonValue,
		CASE WHEN T.Step = '0' THEN '特审' ELSE '正常审核' END AS StepName,
		CAST(T.Step AS VARCHAR(20)) + '级审核人' AS StepPerson,
		R.PassFlag --0.需要审核 1.无需审核		
FROM	#Result T
LEFT JOIN (
	SELECT	*
	FROM	#Reason		
)R ON T.Step = R.AuditingStep
WHERE R.PassFlag = '0'/*(NOT(@IfAudit = 0)  AND r.PassFlag IS NOT NULL
		OR (@IfAudit = 0) AND (R.PassFlag = '0'))   */
ORDER BY T.Step ASC

END
-- //

DROP TABLE #Detail,#BillDetail,#Employee,#Result,#Reason





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBalanceGood]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBalanceGood]
GO


/*
	作者：HAIQUAN
	日期：2007-4-9
	描述：按商品结算时，查询被结算单据的商品信息和结算情况
*/
CREATE                          PROCEDURE Web_GetBalanceGood
(
	@BillNumberID		varchar(20), 	--被结算的单据的Id
	@InOrOut		varchar(1)='',
	@MBillNumberId		int=-1,  	--收付款单单据id
	@Billtype int=-1	--单据类型
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @BillTable varchar(60),@chvIndexTable VARCHAR(100)
SET @chvIndexTable = ' BillIndex '
IF @Billtype = -1
BEGIN
	SELECT @Billtype=Billtype FROM BillIndex WHERE BillNumberId=@BillNumberID
END
ELSE IF @Billtype=405 OR @BillType=404
BEGIN
	SET @chvIndexTable = ' ReceiptBillIndex '
END

SELECT @BillTable=
		CASE @BillType
		         WHEN 34
		         	THEN 'buybill' --采购单
		         WHEN 6 
					THEN 'BuyBackBill' --采购退货单
		         WHEN 161 
					THEN 'BuyGoodsExchangeBill'--采购换货单
		         WHEN 145 
					THEN 'CommissionBill'--受托代销结算单，代销单还要特殊处理
--以下是销售类单据
		         WHEN 11 
					THEN 'saleBill' --销售出库单
				 WHEN 12
					THEN 'PT_Combin_SaleBill'
				 WHEN 45
					THEN 'saleBackBill' --销售退货单
				 WHEN 46
					THEN 'PT_Combin_SaleBackBill'
				 WHEN 160
					THEN 'SaleGoodsExchangeBill' --销售换货单
				 WHEN 157
					THEN 'RepairDeal' --维修受理单
				 WHEN 141
					THEN 'CommissionBill' --委托代销结算单
				 WHEN 167
					THEN 'wx_Bill_GetBack'	-- 新维修 - 取件单
				 WHEN 168
					THEN 'wx_Bill_Replace'	-- 新维修 - 整机更换单
				 WHEN 170
					THEN 'wx_Bill_SendBack'	-- 新维修 - 送修返回单
			     WHEN 172
				     THEN 'wx_bill_goto' 
				 WHEN 405					--销售发货开票
					THEN 'ReceiptBill'
				 WHEN 404
					THEN 'ReceiptBill'
				 ELSE '0'
		END

IF @BillTable='0'
RETURN

DECLARE @sPTypeIDName varchar(20),@sTaxPriceName varchar(20),@sTaxTotalName varchar(20)
IF @BillType IN (167,168,170,172)
BEGIN
	SET @sPTypeIDName = 'S.JieJianPTypeID'
	SET @sTaxPriceName = 's.Total'
	SET @sTaxTotalName = 'S.Total'
	IF @BillType = 170
	BEGIN
		SET @sPTypeIDName = 'S.SendPTypeID'
		SET @sTaxPriceName = 's.Total/s.Qty'
	END
	IF @BillType = 172
	BEGIN
		SET @sPTypeIDName = 'S.PTypeID'
	END
END
ELSE
BEGIN
	SET @sPTypeIDName = 'S.PTypeID'
	SET @sTaxPriceName = 's.nTaxPrice'
	SET @sTaxTotalName = 's.ntaxtotal'
END
DECLARE @ReceiptBillQtySQL VARCHAR(2000)
DECLARE @ReceiptBillMoneySQL VARCHAR(2000)
SET @ReceiptBillQtySQL = ''
SET @ReceiptBillMoneySQL = ''
IF @BillTable='ReceiptBill'
BEGIN
	SET @ReceiptBillQtySQL=' WHEN '''+@BillTable+'''=''ReceiptBill'' AND bi.isini=1
						 THEN ISNULL(S.Qty,0)-ISNULL(S.CompleteQTY,0)
						 WHEN '''+@BillTable+'''=''ReceiptBill'' 
						 THEN ISNULL(S.Qty,0)-ISNULL(C.CompleteQTY,0)'
	SET @ReceiptBillMoneySQL=' WHEN '''+@BillTable+'''=''ReceiptBill'' AND bi.isini=1
						 THEN '+@sTaxTotalName+'-ISNULL(S.nCompleteTotal,0)
						 WHEN '''+@BillTable+'''=''ReceiptBill'' 
						 THEN '+@sTaxTotalName+'-ISNULL(C.nCompleteGoodTotal,0)'
END

DECLARE @qtySql VARCHAR(MAX)
SELECT @qtySql = 'S.CompleteQTY';

IF(@BillType = 172)					
BEGIN
    SELECT @qtySql = 'S.Qty'
END

DECLARE @SQL VARCHAR(MAX)
SELECT @SQL='
			
			SELECT  S.BillNumberid,
				BillType=(select BillType from '+@chvIndexTable+' WHERE BillNumberID='+@BillNumberid+'),
					P.FullName AS FullName,
					ISNULL(S.Qty,0) AS QTY,
					ISNULL('+@sTaxPriceName+',0) AS nTaxPrice,
					ISNULL('+@sTaxTotalName+',0) AS nTotalMoney,
					CASE WHEN bi.isini=1 AND '''+@BillTable+'''<>''ReceiptBill''
						 THEN ISNULL(S.Qty,0)-ABS(ISNULL(' + @qtySql + ',0))
					'+@ReceiptBillQtySQL+'
					ELSE 
						ISNULL(S.Qty,0)-ABS(ISNULL(C.CompleteQTY,0)) 
					END AS UnCompleteQTY,
					CASE WHEN bi.isini=1 AND '''+@BillTable+'''<>''ReceiptBill''
						 THEN '+@sTaxTotalName+'-dbo.F_RoundTotal(ABS(ISNULL(' + @qtySql + ',0)*ISNULL('+@sTaxPriceName+',0))) 
					'+@ReceiptBillMoneySQL+'
					ELSE
					     '+@sTaxTotalName+'-ABS(ISNULL(C.nCompleteGoodTotal,0)) 
					END AS nUnCompleteTotal,
					ISNULL(' + @qtySql + ',0) AS CompleteQTY,
					'+@sPTypeIDName+' AS Ptypeid,
					S.[ID] AS id,
					S.comment AS base								
					FROM 
                       Ptype P inner join '+@BillTable+' S 
					   ON P.Typeid='+@sPTypeIDName+'
					   LEFT JOIN '+@chvIndexTable+' bi ON bi.billnumberid=S.billnumberid   
					   LEFT join (
						SELECT GoodsBillid,
							   Billid,
							   Billtype,
							   SUM(CompleteGoodQTY) AS CompleteQTY,
							   SUM(nCompleteGoodTotal) AS nCompleteGoodTotal
						FROM completegoodtotal 
						WHERE draft=0
						GROUP BY GoodsBillid,
								 Billid,Billtype
					) C
					   ON (S.BillNumberID=C.GoodsBillid AND S.[id]=C.BillId)
					   AND C.BillType = bi.Billtype
					WHERE S.BillNumberID='+@BillNumberID+'					
					--AND ISNULL(S.QTY,0)-ABS(ISNULL(C.CompleteQTY,0))<>0
                   '

IF @BillType=160 OR @BillType=161
 BEGIN
   IF @InOrOut='O'
   	SELECT @SQL=@SQL+' AND S.InOrOut=''O'''
   ELSE
	SELECT @SQL=@SQL+' AND S.InOrOut=''I'''
 END

DECLARE @newSQL varchar(8000)
SET  @newSQL = '
		SELECT A.*, 
		B.IsSelect,
		CASE WHEN i.isini=1
			 THEN NULL--A.CompleteQTY
		ELSE 
			 B.CompleteGoodQTY END AS CompleteGoodQTY, 
		CASE WHEN i.isini=1
			 THEN NULL--i.NCompleteTotal
		ELSE B.NCompleteGoodTotal END AS NCompleteGoodTotal		
		FROM (
			'+@SQL+'
		) AS A 
		LEFT JOIN CompleteGoodTotal AS B ON  B.GoodsBillID=A.BillNumberId AND B.Billid=A.id AND B.MoneyBillID='+CAST(@MBillNumberId AS varchar(50)) + '
		LEFT JOIN '+@chvIndexTable+' i ON i.billnumberid=A.BillNumberId '
--print @newSQL
EXEC (@newSQL)
--DROP Table #CompleteGoodTotal


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBalanceGoodRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBalanceGoodRead]
GO

/*
	作者：HAIQUAN
	日期：2007-4-9
	描述：按商品结算时，查询被结算单据的商品信息和结算情况
*/
CREATE                         PROCEDURE Web_GetBalanceGoodRead 
(
	@BillNumberID		varchar(20),
	@MBillNumberID		varchar(20),
	@InOrOut		char(1)='',
	@pagebilltype	int =-999
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @BillTable varchar(60),
		@BillType int
DECLARE @BillIndexTable varchar(60)
SET @BillIndexTable='BillIndex'
IF @pagebilltype = 404 OR @pagebilltype=405
BEGIN
	SET @Billtype = @pagebilltype
END
ELSE
BEGIN
	SELECT @Billtype=Billtype FROM BillIndex WHERE BillNumberId=@BillNumberID
END

SELECT @BillTable=
		CASE @BillType
		         WHEN 34
		         	THEN 'buybill' --采购单
		         WHEN 6 
					THEN 'BuyBackBill' --采购退货单
		         WHEN 161 
					THEN 'BuyGoodsExchangeBill'--采购换货单
		         WHEN 145 
					THEN 'CommissionBill'--受托代销结算单，代销单还要特殊处理
--以下是销售类单据
		         WHEN 11 
					THEN 'saleBill' --销售出库单
				 WHEN 12 
					THEN 'PT_Combin_SaleBill'
				 WHEN 45
					THEN 'saleBackBill' --销售退货单
				WHEN 46
					THEN 'PT_Combin_SaleBackBill'
				 WHEN 160
					THEN 'SaleGoodsExchangeBill' --销售换货单
				 WHEN 157
					THEN 'RepairDeal' --维修受理单
				 WHEN 141
					THEN 'CommissionBill' --委托代销结算单
				 WHEN 167
					THEN 'wx_Bill_GetBack'	-- 新维修 - 取件单
				 WHEN 168
					THEN 'wx_Bill_Replace'	-- 新维修 - 整机更换单
				 WHEN 170
					THEN 'wx_Bill_SendBack'	-- 新维修 - 送修返回单
				WHEN 404
					THEN 'ReceiptBill'
				WHEN 405
					THEN 'ReceiptBill'
		  		 ELSE '0'
						END

IF @BillTable='0'
RETURN

DECLARE @sPTypeIDName varchar(20),@sTaxPriceName varchar(20),@sTaxTotalName varchar(20),@ifABSTotal varchar(50)
SET @ifABSTotal = 'ABS(ISNULL(C.CompleteGoodTotal,0))'
IF @BillType IN (404,405)
BEGIN
	SET @ifABSTotal = 'ISNULL(C.CompleteGoodTotal,0)'
	SET @BillIndexTable='ReceiptBillIndex'
END
IF @BillType IN (167,168,170)
BEGIN
	SET @sPTypeIDName = 'S.JieJianPTypeID'
	SET @sTaxPriceName = 's.Total'
	SET @sTaxTotalName = 'S.Total'
	IF @BillType = 170
	BEGIN
		SET @sPTypeIDName = 'S.SendPTypeID'
		SET @sTaxPriceName = 's.Total/s.Qty'
	END
	IF @BillType IN (167,168) SET @ifABSTotal = 'ISNULL(C.CompleteGoodTotal,0)'
END
ELSE
BEGIN
	SET @sPTypeIDName = 'S.PTypeID'
	SET @sTaxPriceName = 's.nTaxPrice'
	SET @sTaxTotalName = 's.nTaxTotal'
END

DECLARE @SQL VARCHAR(2000)
SELECT @SQL='
			
			SELECT  BillNumberid,
					BillType=(select BillType from '+@BillIndexTable+' WHERE BillNumberID='+@BillNumberid+'),
					P.FullName AS FullName,
					ISNULL(s.QTY,0) AS QTY,
					ISNULL('+@sTaxPriceName+',0) AS TaxPrice,
					ISNULL('+@sTaxTotalName+',0) AS TotalMoney,
					CASE WHEN '''+@BillTable+'''=''ReceiptBill'' 
					THEN ISNULL(C.CompleteQTY,0)
					ELSE
					ABS(ISNULL(C.CompleteQTY,0)) END AS CompleteQTY,
					'+@ifABSTotal+' AS CompleteTotal,
					'+@sPTypeIDName+' AS Ptypeid,
					S.[ID] AS id				
					FROM 
                    	  Ptype P Inner JOIN '+@BillTable+' S 
					   ON P.Typeid='+@sPTypeIDName+'
						LEFT Join 
					(
						SELECT GoodsBillid,
							   MoneyBillID,
							   Billid,
							   InOrOut,
							   BillType,
							   SUM(CompleteGoodQTY) AS CompleteQTY,
							   SUM(nCompleteGoodTotal) AS CompleteGoodTotal
						FROM completegoodtotal 
						--WHERE draft=0
						GROUP BY GoodsBillid,
								 MoneyBillID,
								 InOrOut,
								 Billid,
								 BillType
					) C
					   ON (C.BillID=S.[ID] AND C.GoodsBillid=S.BillNumberID AND C.BillType='''+CAST(@BillType AS VARCHAR)+''')
						WHERE 
						BillNumberID='+@BillNumberID+'
						AND c.GoodsBillID='+@BillNumberID+'
						AND c.MoneyBillID='+@MBillNumberID+'
' 
                  
IF @InOrOut<>''
   SELECT @SQL=@SQL + ' AND C.InOrOut='''+@InOrOut+''' AND S.InOrOut='''+@InOrOut+''' '
print @sql
EXEC (@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBalanceGoodReadCg]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBalanceGoodReadCg]
GO




/*
	作者：谢吉康
	日期：2009-06-22
	描述：按商品结算时，查询被结算单据的商品信息和结算情况【换货单】
*/
CREATE                     PROCEDURE Web_GetBalanceGoodReadCg 
(
	@BillNumberID		varchar(20),
	@MBillNumberID		varchar(20),
	@InOrOut		char(1)=''
)
--@encode$--
AS
DECLARE @BillTable varchar(60),
		@BillType int

SELECT @Billtype=Billtype FROM BillIndex WHERE BillNumberId=@BillNumberID


SELECT @BillTable=
		CASE @BillType
		         WHEN 161 
					THEN 'BuyGoodsExchangeBill'--采购换货单
				 ELSE '0'
						END



IF @BillTable='0'
RETURN

DECLARE @SQL VARCHAR(2000)
SELECT @SQL='
	SELECT  BillNumberid,
			BillType=(select BillType from BillIndex WHERE BillNumberID='+@BillNumberid+'),
			P.FullName AS FullName,
			CASE 
				WHEN S.InOrOut=''O'' THEN -1*ISNULL(s.QTY,0)
				ELSE ISNULL(s.QTY,0)
			END AS Qty,
			ISNULL(S.TaxPrice,0) AS TaxPrice,
			CASE
				WHEN S.InOrOut=''O'' THEN -1*ISNULL(S.TaxTotal,0)
				ELSE ISNULL(S.TaxTotal,0)
			END AS TotalMoney,
			ISNULL(C.CompleteQTY,0) AS CompleteQTY,			
			ISNULL(C.CompleteGoodTotal,0) AS CompleteTotal,
			S.Ptypeid AS Ptypeid,
			S.[ID] AS id
	FROM 	Ptype P Inner JOIN '+@BillTable+' S ON P.Typeid=S.Ptypeid 
	LEFT Join (
				SELECT GoodsBillid,
					   MoneyBillID,
					   Billid,
					   InOrOut,
					   SUM(CompleteGoodQTY) AS CompleteQTY,
					   SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM completegoodtotal 
				GROUP BY GoodsBillid,
						 MoneyBillID,
						 InOrOut,
						 Billid
				) C ON (C.BillID=S.[ID] AND C.GoodsBillid=S.BillNumberID)
	WHERE 	BillNumberID='+@BillNumberID+'
			AND c.GoodsBillID='+@BillNumberID+'
			AND c.MoneyBillID='+@MBillNumberID+'' 

                  
IF @InOrOut<>''
   SELECT @SQL=@SQL + ' AND C.InOrOut='''+@InOrOut+''' AND S.InOrOut='''+@InOrOut+''' '

--PRINT (@SQL)
EXEC (@SQL)
			       







































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBalanceGoodReadXs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBalanceGoodReadXs]
GO




/*
	作者：谢吉康
	日期：2009-06-22
	描述：按商品结算时，查询被结算单据的商品信息和结算情况【换货单】
*/
CREATE                     PROCEDURE Web_GetBalanceGoodReadXs 
(
	@BillNumberID		varchar(20),
	@MBillNumberID		varchar(20),
	@InOrOut			char(1)=''
)
--@encode$--
AS
DECLARE @BillTable varchar(60),
		@BillType int

SELECT @Billtype=Billtype FROM BillIndex WHERE BillNumberId=@BillNumberID


SELECT @BillTable=
		CASE @BillType
				 WHEN 160
					THEN 'SaleGoodsExchangeBill' --销售换货单
				 ELSE '0'
						END



IF @BillTable='0'
RETURN

DECLARE @SQL VARCHAR(2000)
SELECT @SQL='
	SELECT  BillNumberid,
			BillType=(select BillType from BillIndex WHERE BillNumberID='+@BillNumberid+'),
			P.FullName AS FullName,
			CASE 
				WHEN S.InOrOut=''I'' THEN -1*ISNULL(s.QTY,0)
				ELSE ISNULL(s.QTY,0)
			END AS QTY,
			ISNULL(S.TaxPrice,0) AS TaxPrice,
			CASE 
				WHEN S.InOrOut=''I'' THEN -1*ISNULL(s.TaxTotal,0)
				ELSE ISNULL(s.TaxTotal,0)
			END AS TotalMoney,
			ISNULL(C.CompleteQTY,0) AS CompleteQTY,
			ISNULL(C.CompleteGoodTotal,0) AS CompleteTotal,
			S.Ptypeid AS Ptypeid,
			S.[ID] AS id
	FROM 	Ptype P Inner JOIN '+@BillTable+' S ON P.Typeid=S.Ptypeid 
	LEFT Join (
				SELECT GoodsBillid,
					   MoneyBillID,
					   Billid,
					   InOrOut,
					   SUM(CompleteGoodQTY) AS CompleteQTY,
					   SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM completegoodtotal 
				GROUP BY GoodsBillid,
						 MoneyBillID,
						 InOrOut,
						 Billid
				) C ON (C.BillID=S.[ID] AND C.GoodsBillid=S.BillNumberID)
	WHERE 	BillNumberID='+@BillNumberID+'
			AND c.GoodsBillID='+@BillNumberID+'
			AND c.MoneyBillID='+@MBillNumberID+'' 

                  
IF @InOrOut<>''
   SELECT @SQL=@SQL + ' AND C.InOrOut='''+@InOrOut+''' AND S.InOrOut='''+@InOrOut+''' '

--PRINT (@SQL)
EXEC (@SQL)
			       







































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBeforeDateAPBalance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBeforeDateAPBalance]
GO















/****** Object:  Stored Procedure dbo.Web_GetBeforeDateAPBalance    Script Date: 2002-6-20 10:14:54 ******/

CREATE  PROCEDURE [dbo].[Web_GetBeforeDateAPBalance]
( @StartDate SmallDatetime,
  @BtypeID Varchar(100),
  @PreTotal  NUMERIC(24, 10)  output
)
--@encode$--
AS
SET NOCOUNT ON 
declare @CurToal  NUMERIC(24, 10) ,@SumARTotal  NUMERIC(24, 10) ,@SumAPTotal  NUMERIC(24, 10) 
Select @CurToal=APTotal00-ARTotal00 From Btype Where TypeID=@BtypeID --期初应付余额
if @@RowCount=0  return 1 --没有客户
Select @SumARTotal=Sum(ApAdd)-Sum(ApReduce) from vweb_guestwldz Where BtypeID=@BtypeID and BDate<@StartDate
Select @PreTotal=@CurToal+isnull(@SumARTotal,0)---期初应收余额+(这段日期的应收变化量)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBeforeDateARBalance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBeforeDateARBalance]
GO















/****** Object:  Stored Procedure dbo.Web_GetBeforeDateARBalance    Script Date: 2002-6-20 10:14:54 ******/

--得到某日期之前的应收余额
CREATE  PROCEDURE [dbo].[Web_GetBeforeDateARBalance]
( @StartDate SmallDatetime,
  @BtypeID Varchar(100),
  @PreTotal  NUMERIC(24, 10)  output
)
--@encode$--
AS
SET NOCOUNT ON 
declare @CurToal  NUMERIC(24, 10) ,@SumARTotal  NUMERIC(24, 10) ,@SumAPTotal  NUMERIC(24, 10) 
--Select @CurToal=ARTotal+ArTotal00-ApTotal-ApTotal00 From Btype Where TypeID=@BtypeID
Select @CurToal=ARTotal00-ApTotal00 From Btype Where TypeID=@BtypeID --期初应收余额
if @@RowCount=0  return 1 --没有客户
Select @SumARTotal=Sum(Total) from ListTable Where BtypeID=@BtypeID and BillDate<@StartDate and ATypeID='0000100005' -- AR_ID
Select @SumAPTotal=Sum(Total) from ListTable Where BtypeID=@BtypeID and BillDate<@StartDate and ATypeID='0000200001' -- AP_ID
Select @PreTotal=@CurToal+isnull(@SumARTotal,0)-isnull(@SumAPTotal,0)---期初应收余额+(这段日期的应收变化量)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_GetBillDetailAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].WEB_GetBillDetailAll
GO
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2010-12-27
-- Description: 往来管理获取单据明细汇总情况
-- =============================================
CREATE PROC WEB_GetBillDetailAll
(
	@billtype	VARCHAR(2000)
)
--@encode$--
AS
	SET NOCOUNT ON
	
	DECLARE @SQL	VARCHAR(MAX)='',
			@Union	VARCHAR(200)=''
	DECLARE @BillName TABLE (Billtype INT)
	INSERT INTO @BillName SELECT A FROM DBO.f_split(@billtype,',')
	SET @SQL='  SELECT top 1 billnumberid,0 as BillType,PtypeID,KtypeId,Qty,TaxTotal,NTaxTotal,taxPrice,NtaxPrice,CompleteQTY  FROM  Buybill WHERE billnumberid=-1  '
	SELECT  @SQL=@SQL+' UNION ALL
					    SELECT billnumberid, '+CAST(Billtype AS VARCHAR)+' AS BillType,PtypeID,KtypeId,Qty,TaxTotal,NTaxTotal,taxPrice,NtaxPrice,CompleteQTY FROM '+detailTable
	FROM BillName
	WHERE Billtype IN  ( SELECT Billtype FROM @BillName) AND Billtype IN(34,11)
	IF EXISTS(SELECT 1 FROM @BillName WHERE Billtype in( 6,45))		
	SELECT  @SQL=@SQL+' UNION ALL
						SELECT billnumberid, '+CAST(Billtype AS VARCHAR)+' AS BillType,PtypeID,KtypeId,
									  -Qty,-TaxTotal,-NTaxTotal,taxPrice,NtaxPrice,-CompleteQTY 
								FROM '+detailTable
	FROM BillName
	WHERE Billtype IN  ( SELECT Billtype FROM @BillName) AND Billtype IN( 6,45)
	IF EXISTS(SELECT 1 FROM @BillName WHERE Billtype in( 161,160))
	BEGIN
		SELECT  @SQL=@SQL+' UNION ALL
						    SELECT billnumberid, '+CAST(Billtype AS VARCHAR)+' AS BillType,PtypeID,KtypeId,
									  Qty,TaxTotal,NTaxTotal ,taxPrice,NtaxPrice,CompleteQTY
									FROM '+detailTable +' 
									WHERE (InOrOut=''I'' AND '+CAST(Billtype AS VARCHAR)+ '=161) OR (InOrOut=''O'' AND '+CAST(Billtype AS VARCHAR)+ '=160)'
		FROM BillName
		WHERE Billtype IN  ( SELECT Billtype FROM @BillName) AND Billtype IN(161,160)
		SELECT  @SQL=@SQL+' UNION ALL
							SELECT billnumberid, '+CAST(Billtype AS VARCHAR)+' AS BillType,PtypeID,KtypeId,
									 - Qty,-TaxTotal,-NTaxTotal,taxPrice,NtaxPrice,-CompleteQTY
									FROM '+detailTable+' 
									WHERE (InOrOut=''O'' AND '+CAST(Billtype AS VARCHAR)+ '=161) OR (InOrOut=''I'' AND '+CAST(Billtype AS VARCHAR)+ '=160)'
		FROM BillName
		WHERE Billtype IN  ( SELECT Billtype FROM @BillName) AND Billtype IN(161,160)
	END
	IF EXISTS(SELECT 1 FROM @BillName WHERE Billtype IN( 141,145))
		SET @SQL = @SQL +'  UNION ALL 
							SELECT  a.billnumberid,B.billtype AS billtype,a.ptypeid,b.ktypeid,a.qty,a.taxtotal,a.ntaxtotal,taxPrice,NtaxPrice,CompleteQTY
							FROM CommissionBill A
							INNER JOIN billIndex b ON A.billnumberid =  b.billnumberid 
							WHERE   B.billtype IN( 141,145) AND  B.Billtype IN  ('+@billtype+') '
	IF EXISTS(SELECT 1 FROM @BillName WHERE Billtype = 305)
		SET @SQL = @SQL +'  UNION ALL 
							SELECT  a.billnumberid,305 AS billtype,a.ptypeid,b.ktypeid,a.qty,a.taxtotal,a.ntaxtotal,taxPrice,NtaxPrice,0 as CompleteQTY 
							FROM retailBill A
							INNER JOIN billIndex b ON A.billnumberid =  b.billnumberid 
							WHERE  B.billtype = 305 ' 
	EXEC(@SQL)
	--print @SQL
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_GetBillDetailAllInvoice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].WEB_GetBillDetailAllInvoice
GO
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2010-12-27
-- Description: 往来管理获取单据明细汇总情况
-- =============================================
CREATE PROC WEB_GetBillDetailAllInvoice
(
	@billtype	VARCHAR(2000)
)
--@encode$--
AS
	SET NOCOUNT ON
	
	DECLARE @SQL	VARCHAR(MAX)='',
			@Union	VARCHAR(200)=' UNION ALL '
	DECLARE @BillName TABLE (Billtype INT)
	INSERT INTO @BillName SELECT A FROM DBO.f_split(@billtype,',')
			
	SET @SQL='  SELECT top 1 billnumberid,0 as BillType,PtypeID,KtypeId,Qty,TaxTotal,NTaxTotal,InvoiceQty,InvoiceMoney,NInvoiceMoney  FROM  Buybill WHERE billnumberid=-1  '
	
	SELECT  @SQL=@SQL+@Union+' SELECT billnumberid, '+CAST(Billtype AS VARCHAR)+' AS BillType,PtypeID,KtypeId,
									  Qty,TaxTotal,NTaxTotal,InvoiceQty,InvoiceMoney,NInvoiceMoney 
								FROM '+detailTable
	FROM BillName
	WHERE Billtype IN  ( SELECT Billtype FROM @BillName) AND Billtype IN(34,11)
	
	IF EXISTS(SELECT 1 FROM @BillName WHERE Billtype in( 6,45))
					
	SELECT  @SQL=@SQL+@Union+' SELECT billnumberid, '+CAST(Billtype AS VARCHAR)+' AS BillType,PtypeID,KtypeId,
									  -Qty,-TaxTotal,-NTaxTotal,-InvoiceQty,-InvoiceMoney,-NInvoiceMoney 
								FROM '+detailTable
	FROM BillName
	WHERE Billtype IN  ( SELECT Billtype FROM @BillName) AND Billtype IN( 6,45)
	IF EXISTS(SELECT 1 FROM @BillName WHERE Billtype in( 161,160))
	BEGIN
		SELECT  @SQL=@SQL+@Union+' SELECT billnumberid, '+CAST(Billtype AS VARCHAR)+' AS BillType,PtypeID,KtypeId,
									  Qty,TaxTotal,NTaxTotal,InvoiceQty,InvoiceMoney,NInvoiceMoney 
									FROM '+detailTable +' 
									WHERE (InOrOut=''I'' AND '+CAST(Billtype AS VARCHAR)+ '=161) OR (InOrOut=''O'' AND '+CAST(Billtype AS VARCHAR)+ '=160)'
		FROM BillName
		WHERE Billtype IN  ( SELECT Billtype FROM @BillName) AND Billtype IN(161,160)
		SELECT  @SQL=@SQL+@Union+' SELECT billnumberid, '+CAST(Billtype AS VARCHAR)+' AS BillType,PtypeID,KtypeId,
									 - Qty,-TaxTotal,-NTaxTotal,-InvoiceQty,-InvoiceMoney,-NInvoiceMoney 
									FROM '+detailTable+' 
								WHERE (InOrOut=''O'' AND '+CAST(Billtype AS VARCHAR)+ '=161) OR (InOrOut=''I'' AND '+CAST(Billtype AS VARCHAR)+ '=160)'
		FROM BillName
		WHERE Billtype IN  ( SELECT Billtype FROM @BillName) AND Billtype IN(161,160)
	END
	IF EXISTS(SELECT 1 FROM @BillName WHERE Billtype in( 141,145))
		SET @SQL = @SQL +'  UNION ALL 
							SELECT  a.billnumberid,b.billtype AS billtype,a.ptypeid,b.ktypeid,a.qty,a.taxtotal,a.ntaxtotal,a.InvoiceQty,a.InvoiceMoney,a.NInvoiceMoney 
							FROM CommissionBill A
							INNER JOIN billIndex b ON A.billnumberid =  b.billnumberid 
							WHERE  B.billtype IN( 141,145) AND  B.Billtype IN  ('+@billtype+') '
	IF EXISTS(SELECT 1 FROM @BillName WHERE Billtype = 305)
		SET @SQL = @SQL +'  UNION ALL 
							SELECT  a.billnumberid,305 AS billtype,a.ptypeid,b.ktypeid,a.qty,a.taxtotal,a.ntaxtotal,a.InvoiceQty,a.InvoiceMoney,a.NInvoiceMoney
							FROM retailBill A
							INNER JOIN billIndex b ON A.billnumberid =  b.billnumberid 
							WHERE  B.billtype = 305 ' 
	EXEC(@SQL)
	print @SQL
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBillsByAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetBillsByAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/22
	Description	: 根据科目id查出期初单据
*/
CREATE PROCEDURE Web_GetBillsByAccount
(
	@STypeId	VARCHAR(50),
	@Cid		INT,
	@TypeId		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN
	/*
	    应付：期初未结算销售退货单 45，期初返利执行单 148、期初价保执行单 149，应付129 发出商品退货单403
	    应收：期初未结算采购退货单 6 ，期初获得价保151、期初获利执行 150, 应收减少115,暂估退货单401
	    费用单：36
	*/
    -----查询挂靠在此分支机构下的非独立核算机构（包含它自己）
	CREATE TABLE #tempStypes
	(
	  STYPEID	VARCHAR(50),
	  FULLNAME	VARCHAR(100)
	)
	INSERT INTO #tempStypes
	SELECT TYPEID,
		   FullName
	FROM SType 
	WHERE VerifyID=@STypeId AND DELETED=0
	
   ----查询数据
   CREATE TABLE #temp
   (
      BILLNUMBERID  NUMERIC(10,0),   ---单据id
      BILLDATE		DATE,	         ---单据日期
      BILLCODE	    VARCHAR(200),	 ---单据编号
      BILLTYPE	    VARCHAR(500),	---单据类型
      STypeId		VARCHAR(50),   ---分支机构ID
      EtypeID		VARCHAR(50),   ---职员名称ID
      DTYPEID		VARCHAR(50),	---部门名称ID
      BTYPEID		VARCHAR(50),   ---往来单位ID
      STYPENAME		VARCHAR(500),   ---分支机构名称
      ETYPENAME		VARCHAR(500),   ---职员名称(经手人名字)
      DTYPENAME		VARCHAR(500),	---部门名称
      BTYPENAME		VARCHAR(500),   ---往来单位(结算单位)
      BILLTOTAL	     NUMERIC(24, 10) ,
      BILLTOTALFOR	 NUMERIC(24, 10) 
   )
 
    INSERT INTO #temp (BILLNUMBERID,BILLDATE,BILLCODE,BILLTYPE,STypeId,EtypeID,DTYPEID,BTYPEID,STYPENAME,ETYPENAME,DTYPENAME,BTYPENAME,BILLTOTAL,BILLTOTALFOR)
	SELECT a.BILLNUMBERID,																	---单据id
		   a.BILLDATE,																		---单据日期
		   a.BILLCODE,																		---单据编号
		   d.BILLNAME AS BILLTYPE,															---单据类型
		   a.STYPEID AS STYPEID,
		   a.etypeid AS ETYPEID,
		   a.DTypeId AS Dtypeid,
		   a.btypeid AS btypeid,
		   e.FULLNAME AS STYPENAME,															---分支机构
		   b.FULLNAME AS EMPLOYEENAME,														---职员名称(经手人名字)
		   f.FULLNAME AS DTYPENAME,															---部门名称
		   c.FULLNAME AS BTYPENAME,															---往来单位(结算单位)
		   CASE 
				WHEN a.BillType IN(45,6,148,149,150,151)
				THEN -(ISNULL(a.TOTALMONEY,0)-ISNULL(a.PREFERENCEMONEY,0)-ISNULL(a.COMPLETETOTAL,0)-ISNULL(TOTALINMONEY,0)-ISNULL(A.ChargeOffTotal,0))   
				ELSE ISNULL(a.TOTALMONEY,0)-ISNULL(a.PREFERENCEMONEY,0)-ISNULL(a.COMPLETETOTAL,0)-ISNULL(TOTALINMONEY,0)-ISNULL(A.ChargeOffTotal,0)
		   END AS BILLTOTAL,		                                                            ---金额本币
		   CASE 
				WHEN a.BillType IN(45,6,148,149,150,151) 
				THEN -(ISNULL(a.NTOTALMONEY,0)-ISNULL(a.NPREFERENCEMONEY,0)-ISNULL(a.NCOMPLETETOTAL,0)-ISNULL(NTOTALINMONEY,0)-ISNULL(A.NChargeOffTotal,0))         
				ELSE (ISNULL(a.NTOTALMONEY,0)-ISNULL(a.NPREFERENCEMONEY,0)-ISNULL(a.NCOMPLETETOTAL,0)-ISNULL(NTOTALINMONEY,0))-ISNULL(A.NChargeOffTotal,0)                             
		   END AS BILLTOTALFOR																	---金额原币
	FROM BillIndex a
	LEFT JOIN EMPLOYEE b	 ON a.ETYPEID=b.TYPEID
	LEFT JOIN BTYPE c        ON a.BTYPEID=c.TYPEID  
	LEFT JOIN BILLNAME d     ON a.BILLTYPE=d.BILLTYPE
	JOIN #tempStypes e  ON a.STYPEID=e.STYPEID
	LEFT JOIN DEPARTMENT f	ON a.DTYPEID=f.TYPEID
	WHERE a.ISINI=1 AND 
	      ATYPEID1=@TypeId AND 
	      a.CID=@Cid AND 
	      a.BILLTYPE NOT IN (116,115,128,129,36,400,401,404,405)
	 UNION ALL--暂估入库单
	 SELECT 
		a.BILLNUMBERID,																	---单据id
		a.BILLDATE,																		---单据日期
		a.BILLCODE,																		---单据编号
		d.BILLNAME AS BILLTYPE,															---单据类型
		a.STYPEID AS STYPEID,
		a.etypeid AS ETYPEID,
		a.DTypeId AS Dtypeid,
		a.btypeid AS btypeid,
		e.FULLNAME AS STYPENAME,															---分支机构
		b.FULLNAME AS EMPLOYEENAME,														---职员名称(经手人名字)
		f.FULLNAME AS DTYPENAME,															---部门名称
		c.FULLNAME AS BTYPENAME,															---往来单位(结算单位)
		AB.total BILLTOTAL,		                            ---金额本币
		AB.NTotal BILLTOTALFOR 
	 FROM BillIndex A
	 INNER JOIN AppraisalBill AB ON AB.BillNumberId=A.BillNumberId AND A.IsIni=1 AND A.ATypeID1=@TypeId AND A.CID=@Cid AND A.BillType=400
	 INNER JOIN #tempStypes E ON E.STYPEID=A.Stypeid 
	 LEFT JOIN employee B ON B.typeId=A.ETypeID
	 LEFT JOIN btype C ON C.typeId=A.BTypeID
	 LEFT JOIN BillName D ON D.Billtype=A.BillType
	 LEFT JOIN Department F ON F.typeid=A.DTypeID
	 UNION ALL --暂估退货单
	 SELECT 
		a.BILLNUMBERID,																	---单据id
		a.BILLDATE,																		---单据日期
		a.BILLCODE,																		---单据编号
		d.BILLNAME AS BILLTYPE,															---单据类型
		a.STYPEID AS STYPEID,
		a.etypeid AS ETYPEID,
		a.DTypeId AS Dtypeid,
		a.btypeid AS btypeid,
		e.FULLNAME AS STYPENAME,															---分支机构
		b.FULLNAME AS EMPLOYEENAME,														---职员名称(经手人名字)
		f.FULLNAME AS DTYPENAME,															---部门名称
		c.FULLNAME AS BTYPENAME,															---往来单位(结算单位)
		-AB.total BILLTOTAL,		                            ---金额本币
		-AB.NTotal BILLTOTALFOR 
	 FROM BillIndex A
	 INNER JOIN AppraisalBackBill AB ON AB.BillNumberId=A.BillNumberId AND A.IsIni=1 AND A.ATypeID1=@TypeId AND A.CID=@Cid AND A.BillType=401
	 INNER JOIN #tempStypes E ON E.STYPEID=A.Stypeid 
	 LEFT JOIN employee B ON B.typeId=A.ETypeID
	 LEFT JOIN btype C ON C.typeId=A.BTypeID
	 LEFT JOIN BillName D ON D.Billtype=A.BillType
	 LEFT JOIN Department F ON F.typeid=A.DTypeID
	 UNION ALL --(404采购暂估开票 405销售发货开票)
	 SELECT 
		a.BILLNUMBERID,																	---单据id
		a.BILLDATE,																		---单据日期
		a.BILLCODE,																		---单据编号
		d.BILLNAME AS BILLTYPE,															---单据类型
		a.STYPEID AS STYPEID,
		a.etypeid AS ETYPEID,
		a.DTypeId AS Dtypeid,
		a.btypeid AS btypeid,
		e.FULLNAME AS STYPENAME,															---分支机构
		b.FULLNAME AS EMPLOYEENAME,														---职员名称(经手人名字)
		f.FULLNAME AS DTYPENAME,															---部门名称
		c.FULLNAME AS BTYPENAME,															---往来单位(结算单位)
		AB.TaxTotal-A.CompleteTotal-A.ChargeOffTotal BILLTOTAL,		                            ---金额本币
		AB.NTaxTotal-A.NCompleteTotal-A.NChargeOffTotal BILLTOTALFOR 
	 FROM ReceiptBillIndex A
	 INNER JOIN ReceiptBill AB ON AB.BillNumberId=A.BillNumberId AND A.IsIni=1 AND ((A.BillType=405 AND A.ATypeID1=@TypeId) OR (A.BillType=404 AND A.ATypeID2=@TypeId)) AND A.CID=@Cid
	 INNER JOIN #tempStypes E ON E.STYPEID=A.Stypeid 
	 LEFT JOIN employee B ON B.typeId=A.ETypeID
	 LEFT JOIN btype C ON C.typeId=A.BTypeID
	 LEFT JOIN BillName D ON D.Billtype=A.BillType
	 LEFT JOIN Department F ON F.typeid=A.DTypeID
	 
	-------提取应收应付的增加，减少单
	INSERT INTO #temp  (BILLNUMBERID,BILLDATE,BILLCODE,BILLTYPE,STypeId,EtypeID,DTYPEID,BTYPEID,STYPENAME,ETYPENAME,DTYPENAME,BTYPENAME,BILLTOTAL,BILLTOTALFOR)
	SELECT a.BILLNUMBERID,																	---单据id
		   a.BILLDATE,																		---单据日期
		   a.BILLCODE,																		---单据编号
		   d.BILLNAME AS BILLTYPE,															--单据类型
		   a.STYPEID AS STYPEID,
		   a.etypeid AS ETYPEID,
		   a.DTypeId AS Dtypeid,
		   c.BTYPEID AS btypeid,
		   e.FULLNAME AS STYPEName,															---分支机构
		   b.FULLNAME AS EMPLOYEENAME,														---职员名称(经手人名字)
		   g.FULLNAME AS DTYPEName,
		   f.FULLNAME AS BTYPEName,															---往来单位(结算单位)
		   CASE 
		    	WHEN a.BILLTYPE=129 OR a.BILLTYPE=115 THEN -(ISNULL(c.TOTAL,0)-ISNULL(a.PREFERENCEMONEY,0)-ISNULL(c.COMPLETETOTAL,0)-ISNULL(a.TOTALINMONEY,0)-ISNULL(A.ChargeOffTotal,0))
		    	ELSE ISNULL(c.TOTAL,0)-ISNULL(a.PREFERENCEMONEY,0)-ISNULL(c.COMPLETETOTAL,0)-ISNULL(a.TOTALINMONEY,0)-ISNULL(A.ChargeOffTotal,0)
		   END AS BILLTOTAL,																 ---金额本币
		   CASE
			    WHEN a.BILLTYPE=129 OR a.BILLTYPE=115 THEN -(ISNULL(c.NTOTAL,0)-ISNULL(a.NPREFERENCEMONEY,0)-ISNULL(c.NCOMPLETETOTAL,0)-ISNULL(a.NTOTALINMONEY,0)-ISNULL(A.NChargeOffTotal,0))
			    ELSE ISNULL(c.NTOTAL,0)-ISNULL(a.NPREFERENCEMONEY,0)-ISNULL(c.NCOMPLETETOTAL,0)-ISNULL(a.NTOTALINMONEY,0)-ISNULL(A.NChargeOffTotal,0)
		   END AS BILLTOTALFOR																---金额原币
	FROM BillIndex a
	LEFT JOIN EMPLOYEE b	 ON a.ETYPEID=b.TYPEID
	LEFT JOIN AdDebtBill c   ON a.BILLNUMBERID=c.BILLNUMBERID  
	LEFT JOIN BTYPE f	     ON c.BTYPEID=f.TYPEID
	LEFT JOIN BILLNAME d     ON a.BILLTYPE=d.BILLTYPE
	JOIN #tempStypes e  ON a.STYPEID=e.STYPEID
	LEFT JOIN DEPARTMENT g	 ON a.DTYPEID=g.TYPEID
	WHERE a.ISINI=1 AND 
	      ATYPEID1=@TypeId AND 
	      a.CID=@Cid AND 
	      a.BILLTYPE IN (116,115,128,129)
	 
	--------提取费用单
	DECLARE @Expensetoar INT
	SELECT @Expensetoar=SUBVALUE FROM dbo.sysdata WHERE SubName='expensetoar'
	
    INSERT INTO #temp   (BILLNUMBERID,BILLDATE,BILLCODE,BILLTYPE,STypeId,EtypeID,DTYPEID,BTYPEID,STYPENAME,ETYPENAME,DTYPENAME,BTYPENAME,BILLTOTAL,BILLTOTALFOR)
	SELECT a.BILLNUMBERID,																	---单据id
		   a.BILLDATE,																		---单据日期
		   a.BILLCODE,																		---单据编号
		   d.BILLNAME AS BILLTYPE,															---单据类型
		    a.STYPEID AS STYPEID,
		   a.etypeid AS ETYPEID,
		   a.DTypeId AS Dtypeid,
		   a.btypeid AS btypeid,
		   e.FULLNAME AS STYPEName,															---分支机构
		   b.FULLNAME AS EMPLOYEENAME,														---职员名称(经手人名字)
		   f.FULLNAME AS DTYPEName,															---部门名称
		   c.FULLNAME AS BTYPEName,															---往来单位(结算单位)
		   CASE 
				WHEN @Expensetoar=1 AND SUBSTRING(DEALBTYPEID,1,5)='00001'
				THEN -(ISNULL(a.TOTALMONEY,0)-ISNULL(a.PREFERENCEMONEY,0)-ISNULL(a.COMPLETETOTAL,0)-ISNULL(TOTALINMONEY,0)-ISNULL(A.ChargeOffTotal,0))   
				ELSE ISNULL(a.TOTALMONEY,0)-ISNULL(a.PREFERENCEMONEY,0)-ISNULL(a.COMPLETETOTAL,0)-ISNULL(TOTALINMONEY,0)-ISNULL(A.ChargeOffTotal,0)
		   END AS BILLTOTAL,		                                                            ---金额本币
		   CASE 
				WHEN @Expensetoar=1 AND SUBSTRING(DEALBTYPEID,1,5)='00001'
				THEN -(ISNULL(a.NTOTALMONEY,0)-ISNULL(a.NPREFERENCEMONEY,0)-ISNULL(a.NCOMPLETETOTAL,0)-ISNULL(NTOTALINMONEY,0)-ISNULL(A.NChargeOffTotal,0))         
				ELSE (ISNULL(a.NTOTALMONEY,0)-ISNULL(a.NPREFERENCEMONEY,0)-ISNULL(a.NCOMPLETETOTAL,0)-ISNULL(NTOTALINMONEY,0)-ISNULL(A.NChargeOffTotal,0))                             
		   END AS BILLTOTALFOR																	---金额原币
	FROM BillIndex a
	LEFT JOIN EMPLOYEE b	 ON a.ETYPEID=b.TYPEID
	LEFT JOIN BTYPE c        ON a.BTYPEID=c.TYPEID  
	LEFT JOIN BILLNAME d     ON a.BILLTYPE=d.BILLTYPE
	JOIN #tempStypes e  ON a.STYPEID=e.STYPEID
	LEFT JOIN DEPARTMENT f	ON a.DTYPEID=f.TYPEID
	WHERE a.ISINI=1 AND 
	      ATYPEID1=@TypeId AND 
	      a.CID=@Cid AND 
	      a.BILLTYPE =36
	
	---查出单据
	SELECT * FROM #temp WHERE BILLTOTALFOR!=0 OR BILLTOTAL!=0
	---求出金额合计
	SELECT SUM(BILLTOTAL) AS TOTAL,
		   SUM(BILLTOTALFOR) AS TOTALFOR
	FROM #temp
	WHERE BILLTOTALFOR!=0 OR BILLTOTAL!=0
	
	DROP TABLE #tempStypes,#temp
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBillSign]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBillSign]
GO


/*
	作者：王伟
	日期：2011-4-25 code   
	描述：获取相应单据的标识
	
	--2017-03-24 梁晰 增加实物类单据
*/
CREATE	PROCEDURE Web_GetBillSign
( 
	 @OperatorId    varchar(100),      --操作员ID
	 @BillType		VARCHAR(100),
	 @BillNumberid	VARCHAR(100)
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------

IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @isOrder INT

SET @isOrder=0 --是否订单

IF(@BillType='300' OR @BillType='301' OR @BillType='313')
BEGIN
	SET	@isOrder=1
END

CREATE TABLE #ResultData
(
	ifaudit	INT,
	draft	INT,
	ifcheck	VARCHAR(100),
	redword	INT,
	billover INT,--订单终止
	orderstate	INT,--订单状态（0=未完成，1=完成）
	createsale  INT,
	isusing		INT
)

DECLARE @SQL VARCHAR(MAX)
DECLARE @OrderDetailTable VARCHAR(30)
SET @OrderDetailTable=' orderbill '
if @BillType in('327','328','329')
begin
	INSERT INTO #ResultData(ifaudit,draft,ifcheck,redword)
	SELECT
			IsNULL(a.IfAudit,-9),					
			b.draft,
			b.ifcheck,
			b.RedWord
	FROM PosAllotApplyBillIndex b  
		LEFT JOIN AuditingBill a ON b.BillNumberId=a.BillNumberID   AND (a.BillIndexType=13)
	WHERE b.BillNumberID=@BillNumberid AND b.billtype=@billtype
end
else IF(@isOrder='0' AND @BillType NOT IN ('203','204','413'))
BEGIN
	SET @SQL='
			INSERT INTO #ResultData(ifaudit,draft,ifcheck,redword)
			SELECT
					IsNULL(a.IfAudit,-9),					
					b.draft,
					b.ifcheck,
					b.RedWord
			FROM BillIndex b  
				LEFT JOIN AuditingBill a ON b.BillNumberId=a.BillNumberID   AND (a.BillIndexType=2)
			WHERE b.BillNumberID='+@BillNumberid+' AND b.billtype='+@billtype
	EXEC(@SQL)		
END

ELSE IF @BillType='413'
BEGIN
 SET @SQL='
			INSERT INTO #ResultData(ifaudit,draft,ifcheck,redword)
			SELECT
					IsNULL(a.IfAudit,-9),					
					b.draft,
					b.ifcheck,
					b.RedWord
			FROM onShelvespickIndex b  
				LEFT JOIN AuditingBill a ON b.BillNumberId=a.BillNumberID   AND (a.BillIndexType=2)
			WHERE b.BillNumberID='+@BillNumberid+' AND b.billtype='+@billtype
	EXEC(@SQL)	
END
ELSE IF @BillType='203'
BEGIN
 SET @SQL='
			INSERT INTO #ResultData(draft,ifcheck,redword)
			SELECT				
					b.draft,
					b.ifcheck,
					b.RedWord
			FROM serialadjustindex b 
			WHERE b.BillNumberID='+@BillNumberid+' AND b.billtype='+@billtype
	EXEC(@SQL)	
END
ELSE IF @BillType='204'
BEGIN
 SET @SQL='
			INSERT INTO #ResultData(ifaudit,draft,ifcheck,redword)
			SELECT
					IsNULL(a.IfAudit,-9),					
					0 as  draft,
					0 as ifcheck,
					0 as RedWord
			FROM RequestIndex b  
				LEFT JOIN AuditingBill a ON b.BillNumberId=a.BillNumberID   AND  a.BillIndexType=3
			WHERE b.BillNumberID='+@BillNumberid+' AND b.billtype='+@billtype
	EXEC(@SQL)	
END
ELSE
BEGIN

	--DECLARE @TableName VARCHAR(100)--根据订单判断表名 
	DECLARE @OrderBillSql VARCHAR(3000)
	IF @BillType='300'
	BEGIN
		--SET @TableName='SaleBill'
		SET @OrderBillSql = 'SELECT tb.orderid FROM BillIndex b
							 INNER JOIN SaleBill tb ON b.BillNumberId=tb.BillNumberId 
							 WHERE b.redword=0 and tb.orderid<>-1
							 UNION ALL
							 SELECT tb.orderid FROM BillIndex b
							 INNER JOIN SendBill tb ON b.BillNumberId=tb.BillNumberId 
							 WHERE b.redword=0 and tb.orderid<>-1
							 UNION ALL
							 SELECT tb.orderid FROM BillIndex b
							 INNER JOIN commissionbill tb ON b.BillNumberId=tb.BillNumberId 
							 WHERE b.redword=0 and tb.orderid<>-1 and tb.[Type]=140
							 '
	END
	ELSE IF @BillType='313'
	BEGIN
		SET @OrderDetailTable=' PT_Combin_OrderBill '
		SET @OrderBillSql='SELECT tb.orderid FROM BillIndex b
							 INNER JOIN PT_Combin_SaleBill tb ON b.BillNumberId=tb.BillNumberId 
							 WHERE b.redword=0 and tb.orderid<>-1'
	END
	ELSE
	BEGIN
		--SET @TableName='BuyBill'
		SET @OrderBillSql = 'SELECT tb.orderid FROM BillIndex b
							 INNER JOIN BuyBill tb ON b.BillNumberId=tb.BillNumberId 
							 WHERE b.redword=0 and tb.orderid<>-1
							 UNION ALL
							 SELECT tb.orderid FROM BillIndex b
							 INNER JOIN AppraisalBill tb ON b.BillNumberId=tb.BillNumberId 
							 WHERE b.redword=0 and tb.orderid<>-1
							 UNION ALL
							 SELECT tb.orderid FROM BillIndex b
							 INNER JOIN commissionbill tb ON b.BillNumberId=tb.BillNumberId 
							 WHERE b.redword=0 and tb.orderid<>-1 and tb.[Type]=144
							 '
	END
	SET @SQL='
		INSERT INTO #ResultData(billover,orderstate,ifaudit,createsale,isusing)	
		SELECT  BillOver, 
				OrderState,
				IsNULL(a.IfAudit,-9) as ifaudit,
				(
					SELECT COUNT(1) as iscreate 
					FROM OrderBill i
					WHERE i.FromBillNumberID=b.billNumberId
				) as iscreate,--采购订单是否生成销售订单
				(
					SELECT TOP 1  COUNT(1) as isusing 
					FROM  '+ @OrderDetailTable +' details 
						  INNER  JOIN (
								'+@OrderBillSql+'
						  ) tbName ON details.OrderID=tbName.OrderID 
					WHERE details.billNumberId=b.billNumberId
				) as isusing --订单是否被调用
		FROM OrderIndex b  
			LEFT JOIN AuditingBill a ON b.BillNumberId=a.BillNumberID AND a.BillIndexType=0 
		WHERE b.BillNumberID='+@BillNumberid+' AND b.billtype='+@billtype
		--print(@SQL)
	EXEC(@SQL)	
END
--借欠类单据
IF @BillType='71' OR @BillType='72' OR @BillType='87' OR @BillType='88'
BEGIN
	 SET @SQL='
			INSERT INTO #ResultData(ifaudit,draft,ifcheck,redword)
			SELECT
					IsNULL(a.IfAudit,-9),					
					b.draft,
					b.ifcheck,
					b.RedWord
			FROM LendIndex b  
				LEFT JOIN AuditingBill a ON b.BillNumberId=a.BillNumberID   AND  a.BillIndexType=1
			WHERE b.BillNumberID='+@BillNumberid+' AND b.billtype='+@billtype
	EXEC(@SQL)	
END
--暂估类发票
IF @BillType = '404' OR @BillType = '405'
BEGIN
	SET @SQL='
			INSERT INTO #ResultData(ifaudit,draft,ifcheck,redword)
			SELECT
					IsNULL(a.IfAudit,-9),					
					b.draft,
					b.ifcheck,
					b.RedWord
			FROM ReceiptBillIndex b  
				LEFT JOIN AuditingBill a ON b.BillNumberId=a.BillNumberID   AND  a.BillIndexType=5
			WHERE b.BillNumberID='+@BillNumberid+' AND b.billtype='+@billtype
	EXEC(@SQL)
END

--上架单
IF @BillType = '412'
BEGIN
	SET @SQL='
			INSERT INTO #ResultData(ifaudit,draft,ifcheck,redword)
			SELECT
					IsNULL(b.IfAudit,-9),					
					b.draft,
					b.ifcheck,
					b.RedWord
			FROM onShelvespickIndex b  
			WHERE b.BillNumberID='+@BillNumberid+' AND b.billtype='+@billtype
	EXEC(@SQL)
END

--实物单据
IF @billType = '418' OR @billType = '419' OR @billType = '420'
BEGIN
  SET @SQL = 'INSERT INTO #ResultData(ifaudit,draft,ifcheck,redword)
			SELECT 
			        IsNULL(a.IfAudit,-9),			
					f.draft,
					f.ifcheck,
					f.RedWord
					from factindex f 
					LEFT JOIN AuditingBill a ON f.BillNumberId=a.BillNumberID   AND (a.BillIndexType= 7)
					WHERE f.BillNumberId = '+@BillNumberid+' AND f.BillType = ' + @billtype
	exec(@Sql)
END

SELECT 	ISNULL(ifaudit,-9) as ifaudit,
		ISNULL(draft,-9) as draft	,
		ISNULL(ifcheck,'') as ifcheck,	
		ISNULL(redword,-9) as redword	,
		ISNULL(billover,-9) as billover,
		ISNULL(orderstate,-9) as orderstate	,
		ISNULL(createsale  ,-9) as createsale,
		ISNULL(isusing	,-9) as isusing
FROM #ResultData
DROP TABLE #ResultData

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBillsTotalByAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetBillsTotalByAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/23
	Description	: 根据单据ids统计他们的金额
*/
CREATE PROCEDURE Web_GetBillsTotalByAccount
(
	@STypeId						VARCHAR(50),
	@ATypeId						VARCHAR(50),
	@Cid							INT,
	@AllData     Type_CGInsert  	READONLY
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @INSERTSQL		VARCHAR(MAX)='INSERT INTO #temp(',
			@SELECTSQL		VARCHAR(MAX)=' SELECT ',
			@GROUPBYSQL		VARCHAR(MAX)=' GROUP BY ',
			@tempFullName   VARCHAR(66),
			@tempColName	VARCHAR(50),
			@SQL			NVARCHAR(MAX)

	-----该科目有哪些辅助核算项		 
	CREATE TABLE #AssistInfo
	(
	    USERCODE	VARCHAR(200),
	    FULLNAME	VARCHAR(200),
	    COLNAME		VARCHAR(50)     ---动态列的列名
	)			 
	INSERT INTO #AssistInfo
	SELECT USERCODE,
		   FULLNAME,
		   CASE WHEN USERCODE='01' THEN 'selectstypeid'
				WHEN USERCODE='02' THEN 'selectdtypeid'
				WHEN USERCODE='03' THEN 'selectetypeid'
				WHEN USERCODE='04' THEN 'selectbtypeid' 
		   END 
	FROM Ac_Account_Assist_CheckItems a 
	JOIN Ac_Assist_CheckItems b ON a.ASCIDS=b.ASCIDS  
	WHERE STYPEID=@STypeId AND ATYPEID=@ATypeId AND CID=@Cid
   
	-----结果临时表
    CREATE TABLE #temp
	(
	   BILLTOTAL	 NUMERIC(24, 10) ,
	   BILLTOTALFOR  NUMERIC(24, 10) 
	)
    
    ----给结果临时表动态添加辅助核算列
	DECLARE @DynCol VARCHAR(MAX)
	SELECT @DynCol=(ISNULL(@DynCol+'] VARCHAR(66),[','') +  FULLNAME) 
	FROM #AssistInfo GROUP BY FULLNAME 
	SET @DynCol='ALTER TABLE #temp ADD ['+@DynCol+'] VARCHAR(66)'
	
	EXEC(@DynCol)
	
	DECLARE @DynColID VARCHAR(MAX)
	SELECT @DynColID=(ISNULL(@DynColID+'] VARCHAR(66),[','') +  COLNAME) 
	FROM #AssistInfo GROUP BY COLNAME 
	SET @DynColID='ALTER TABLE #temp ADD ['+@DynColID+'] VARCHAR(66)'
	
	EXEC(@DynColID)
	

    --分支机构
    IF (SELECT TOP 1 1 FROM #AssistInfo WHERE USERCODE='01')=1
		BEGIN
		   SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='01'
		   SET @INSERTSQL+=@tempFullName+','
		   SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='01'
		   SET @INSERTSQL+=@tempColName+','
		   SET @SELECTSQL+='STYPENAME,STYPEID,'
		   SET @GROUPBYSQL+='STYPENAME,STYPEID,'
		END
	
	--部门
	IF(SELECT TOP 1 1 FROM #AssistInfo WHERE USERCODE='02')=1
		BEGIN
		    SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='02'
		    SET @INSERTSQL+=@tempFullName+','
		    SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='02'
		    SET @INSERTSQL+=@tempColName+','
		    SET @SELECTSQL+='DTYPENAME,DTYPEID,'
		    SET @GROUPBYSQL+='DTYPENAME,DTYPEID,'
		END	
    
    --职员
    IF (SELECT TOP 1 1 FROM #AssistInfo WHERE USERCODE='03')=1
		BEGIN
		    SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='03'
		    SET @INSERTSQL+=@tempFullName+','
		    SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='03'
		    SET @INSERTSQL+=@tempColName+','
		    SET @SELECTSQL+='ETYPENAME,ETYPEID,'
		    SET @GROUPBYSQL+='ETYPENAME,ETYPEID,'
		END
		
	--往来单位
	IF(SELECT TOP 1 1 FROM #AssistInfo WHERE USERCODE='04')=1
		BEGIN
		    SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='04'
		    SET @INSERTSQL+=@tempFullName+','
		    SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='04'
		    SET @INSERTSQL+=@tempColName+','
		    SET @SELECTSQL+='BTYPENAME,BTYPEID,'
		    SET @GROUPBYSQL+='BTYPENAME,BTYPEID,'
		END
		
    SET @INSERTSQL+='BILLTOTAL,BILLTOTALFOR)'
    SET @SELECTSQL+='SUM(TOTAL),SUM(TOTALFOR) FROM @AllData '
    
    IF(@GROUPBYSQL=' GROUP BY ')        
		SET @SQL=@INSERTSQL+@SELECTSQL
	ELSE
		SET @SQL=@INSERTSQL+@SELECTSQL+@GROUPBYSQL
	
	----@SQL以，结尾，把，去掉
	IF(RIGHT(@SQL,1)=',')
		SET @SQL=LEFT(@SQL,LEN(@SQL)-1)
		
	  PRINT @SQL
	EXEC sp_executesql @SQL,N'@AllData Type_CGInsert READONLY',@AllData
	
	--查询符合格式的数据   
	SELECT * FROM #temp     
	     
	--查询金额总数
	SELECT SUM(ISNULL(TOTAL,0)) AS TOTAL,
		   SUM(ISNULL(TOTALFOR,0)) AS TOTALFOR
	FROM @AllData
	
	--动态列
	SELECT COLNAME 
	FROM #AssistInfo
	
	
	DROP TABLE #AssistInfo,#temp                                                                      
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBranchInfoForSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBranchInfoForSelector]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则的价格表选择
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetBranchInfoForSelector
(
	@usercode varchar(max),
	@username varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 

declare @sql varchar(max);
set @sql='select UserCode as branchusercode  ,FullName as branchname,Branchid as branchuserid from BranchInfo where 1=1 ';

if(ISNULL(@usercode,'')<>'')
set @sql=@sql+' and UserCode like ''%'+@usercode+'%''' ;
if(ISNULL(@username,'')<>'')
set @sql=@sql+'and FullName like ''%'+@username+'%''';

exec(@sql);



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBrandBtypeCredit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetBrandBtypeCredit
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		
-- Create date: 2019-05-31
-- Description: 按品牌设置往来单位信用额度
-- =============================================
CREATE PROCEDURE Web_GetBrandBtypeCredit
(
	@STypeId		VARCHAR(50),
	@BTypeId		VARCHAR(MAX),
	@BrandTypeId	VARCHAR(MAX),
	@OperatorId		VARCHAR(50),
	@PageNo			INT,
	@PageSize		INT=14,
	@IsPrintAll		INT=0,
	@colCount		INT=0 OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @IsUseBrandarType INT=0--是否启用品牌

IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND SubValue=1)
	AND EXISTS(SELECT SubValue FROM SysData WHERE SubName='brandarcontrollineofcredit' AND SubValue=0)
	SET @IsUseBrandarType=1
	
--往来单位
CREATE TABLE #BType(TypeId VARCHAR(50),SonNum INT)
IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value=1)-- 客户供货商统一  
	BEGIN
		INSERT INTO #BType(TypeId,SonNum) 
		SELECT b.typeId,B.sonnum
		FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND @IsUseBrandarType=1 AND B.IsUseBrandarType=1
	END
ELSE --不统一，只需客户
	BEGIN
		INSERT INTO #BType(TypeId,SonNum) 
		SELECT b.typeId,B.sonnum
		FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND b.typeId LIKE '00001%' AND @IsUseBrandarType=1 AND B.IsUseBrandarType=1
	END
		
--分支机构
CREATE TABLE #SType(RowId INT,TypeId VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #SType_P_K ON #SType(TypeId)
INSERT INTO #SType(RowId,TypeId,FullName)
SELECT
	ROW_NUMBER()OVER(ORDER BY S.UserCode) RowId,
	F.TypeId,
	S.FullName
FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) F
INNER JOIN SType S ON S.TypeId=F.TypeId AND sonnum=0

--品牌
CREATE TABLE #Brandar(BrandTypeId VARCHAR(50),BrandUserCode VARCHAR(200),BrandFullName VARCHAR(200))
IF(ISNULL(@BrandTypeId,'')='')
	BEGIN
		INSERT INTO #Brandar(BrandTypeId,BrandUserCode,BrandFullName)
		SELECT C.TypeId,C.UserCode,C.FullName
		FROM brandar_Commodity C
		WHERE C.SonNum=0
	END
ELSE 
	BEGIN
		INSERT INTO #Brandar(BrandTypeId,BrandUserCode,BrandFullName)
		SELECT C.TypeId,C.UserCode,C.FullName
		FROM brandar_Commodity C
		INNER JOIN f_split(@brandtypeid,',') F ON C.TypeId LIKE F.a+'%' AND C.SonNum=0
	END

DECLARE @SQL VARCHAR(MAX)='
SELECT
	C.BtypeId,
	Br.BrandTypeId,
	Br.BrandUserCode,
	Br.BrandFullName,
	SUM(SUM(ISNULL(C.Credit,0))) OVER(PARTITION BY C.BtypeId ) CustomTotalCredit,
	SUM(ISNULL(C.Credit,0)) STypeTotalCredit'

IF(@IsPrintAll=1)--打印所有
	BEGIN	
	
		SELECT 
			@SQL=@SQL +'	,SUM(CASE WHEN C.StypeId='''+TypeID+''' THEN ISNULL(C.Credit,0) ELSE NULL END) ['+TypeId+'_'+Fullname+']',
			@ColCount+=1
		FROM #SType
		ORDER BY RowId
		
	END
ELSE 
	BEGIN
	
		SELECT 
			@SQL=@SQL +'	,SUM(CASE WHEN C.StypeId='''+TypeID+''' THEN ISNULL(C.Credit,0) ELSE NULL END) ['+TypeId+'_'+Fullname+']',
			@ColCount+=1
		FROM #SType
		WHERE RowId BETWEEN (@PageNo-1)*@PageSize+1 AND @PageNo*@PageSize
		ORDER BY RowId
		
	END

SET @SQL+='
FROM #BType B
INNER JOIN BrandBtype_Credit C ON C.BtypeId=B.TypeId
INNER JOIN #SType S ON S.TypeId=C.StypeId
INNER JOIN #Brandar Br ON Br.BrandTypeId=C.BrandarTypeId
GROUP BY 
	C.BtypeId,
	Br.BrandTypeId,
	Br.BrandUserCode,
	Br.BrandFullName
ORDER BY 
	C.BtypeId,
	Br.BrandTypeId'

EXEC(@SQL)

----删除临时表
DROP TABLE #BType,#SType,#Brandar



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBtypeCredit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetBtypeCredit
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2010-12-27
-- Description: 信用额度管理
-- =============================================
CREATE PROCEDURE Web_GetBtypeCredit
(
	@STypeId		VARCHAR(50),
	@BTypeId		VARCHAR(MAX),
	@OperatorId		VARCHAR(50),
	@PageNo			INT,
	@PageSize		INT=14,
	@IsPrintAll		INT=0,
	@colCount		INT=0 OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @IsUseBrandarType INT=0--是否启用品牌

IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND SubValue=1)
	AND EXISTS(SELECT SubValue FROM SysData WHERE SubName='brandarcontrollineofcredit' AND SubValue=0)
	SET @IsUseBrandarType=1
	
--往来单位
CREATE TABLE #BType(TypeId VARCHAR(50),SonNum INT)
IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value=1)-- 客户供货商统一  
	BEGIN
		INSERT INTO #BType(TypeId,SonNum) 
		SELECT b.typeId,B.sonnum
		FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND (@IsUseBrandarType=0 OR (@IsUseBrandarType=1 AND B.IsUseBrandarType<>1))
	END
ELSE --不统一，只需客户
	BEGIN
		INSERT INTO #BType(TypeId,SonNum) 
		SELECT b.typeId,B.sonnum
		FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F
		INNER JOIN btype B ON B.typeId=F.TypeId AND b.typeId LIKE '00001%' AND (@IsUseBrandarType=0 OR (@IsUseBrandarType=1 AND B.IsUseBrandarType<>1))
	END
		
--分支机构
CREATE TABLE #SType(RowId INT,TypeId VARCHAR(50),FullName VARCHAR(200)) CREATE CLUSTERED INDEX #SType_P_K ON #SType(TypeId)
INSERT INTO #SType(RowId,TypeId,FullName)
SELECT
	ROW_NUMBER()OVER(ORDER BY S.UserCode) RowId,
	F.TypeId,
	S.FullName
FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) F
INNER JOIN SType S ON S.TypeId=F.TypeId AND sonnum=0

DECLARE @SQL VARCHAR(MAX)='
SELECT
	C.BtypeId,
	SUM(ISNULL(C.Credit,0)) TotalCredit'

IF(@IsPrintAll=1)--打印所有
	BEGIN	
	
		SELECT 
			@SQL=@SQL +'	,SUM(CASE WHEN C.StypeId='''+TypeID+''' THEN ISNULL(C.Credit,0) ELSE NULL END) ['+TypeId+'_'+Fullname+']',
			@ColCount+=1
		FROM #SType
		ORDER BY RowId
		
	END
ELSE 
	BEGIN
	
		SELECT 
			@SQL=@SQL +'	,SUM(CASE WHEN C.StypeId='''+TypeID+''' THEN ISNULL(C.Credit,0) ELSE NULL END) ['+TypeId+'_'+Fullname+']',
			@ColCount+=1
		FROM #SType
		WHERE RowId BETWEEN (@PageNo-1)*@PageSize+1 AND @PageNo*@PageSize
		ORDER BY RowId
		
	END

SET @SQL+='
FROM #BType B
INNER JOIN btype_credit C ON C.BtypeId=B.TypeId
INNER JOIN #SType s on s.typeid=c.StypeId
GROUP BY C.BtypeId'

EXEC(@SQL) --PRINT @SQL

--删除临时表
DROP TABLE #BType,#SType


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetBtypeInfoForPriceRule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetBtypeInfoForPriceRule]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则的价格表选择
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetBtypeInfoForPriceRule
(
	@filterstr		VARCHAR(max),
	@OperatorID		VARCHAR(50)   --当前操作员
)
--@encode$--
AS

--权限
CREATE TABLE #BTYPE(typeid varchar(50))
INSERT INTO #BTYPE (typeid) SELECT DISTINCT typeid from F_GetAllManagerBaseTypeId('',2,@OperatorID) 

SET NOCOUNT ON 
 declare @sql varchar(max);
 set @sql=' SELECT a.typeid AS dobtypeid,a.usercode AS dobtypecode,a.fullname AS dobtypename FROM btype a 
			INNER JOIN #BTYPE b ON a.typeid = b.typeid
			WHERE a.soncount=0 and deleted = 0 '
if(ISNULL(@filterstr,'')<>'')
set @sql=@sql+'AND( a.UserCode LIKE ''%'+@filterstr+'%'' OR a.FullName LIKE ''%'+@filterstr+'%'' )   '

exec(@sql)
DROP TABLE #BTYPE
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetCardsByAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetCardsByAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2013/05/14
	Description	: 根据科目id查出卡片
*/
CREATE PROCEDURE Web_GetCardsByAccount
(
	@STypeId	VARCHAR(50),
	@Cid		INT,
	@TypeId		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @AtypeName VARCHAR(200)
	SELECT @AtypeName=FullName FROM dbo.Ac_Account WHERE TypeId=@TypeId
	
	SELECT  ac.UserCode,
			ac.FULLNAME,
			InAccountDate,
			ac.STYPEID,
			s.FullName AS stypename,
			DTypeid,
			d.FullName AS dtypename,
			CASE WHEN  ac.AssertATypeId=@TypeId THEN '固定资产科目'
				 WHEN  ac.DepATypeId=@TypeId THEN '固定资产折旧科目' 
			     WHEN  ac.DevalueATypeId=@TypeId THEN '固定资产减值准备科目' 
			END AS atypetype,
			CASE WHEN ac.AssertATypeId=@TypeId THEN Total --入账原值 
			     WHEN ac.DepATypeId=@TypeId THEN DepTotal
			     WHEN ac.DevalueATypeId=@TypeId THEN DevalueReady
			END AS total      			  
	INTO #temp                                                                       
	FROM  dbo.Ac_AssetsCards ac 
	JOIN Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STypeId
	JOIN dbo.SType s ON ac.STypeId=s.TypeId 
	JOIN dbo.Department d ON ac.DTypeid=d.typeid
	WHERE (ac.AssertATypeId=@TypeId OR ac.DepATypeId=@TypeId OR ac.DevalueATypeId=@TypeId) AND AssetsState != 2 AND AssetsState!=5
	 
	SELECT * FROM #temp
	SELECT ISNULL(SUM(ISNULL(total,0)),0) AS total FROM #temp 
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetCardsTotalByAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetCardsTotalByAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2013/05/16
	Description	: 根据卡片统计他们的金额
*/
CREATE PROCEDURE Web_GetCardsTotalByAccount
(
	@STypeId						VARCHAR(50),
	@ATypeId						VARCHAR(50),
	@Cid							INT,
	@AllData     Type_CardInsert  	READONLY
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @INSERTSQL		VARCHAR(MAX)='INSERT INTO #temp(',
			@SELECTSQL		VARCHAR(MAX)=' SELECT ',
			@GROUPBYSQL		VARCHAR(MAX)=' GROUP BY ',
			@tempFullName   VARCHAR(66),
			@tempColName	VARCHAR(50),
			@SQL			NVARCHAR(MAX)

	-----该科目有哪些辅助核算项		 
	CREATE TABLE #AssistInfo
	(
	    USERCODE	VARCHAR(200),
	    FULLNAME	VARCHAR(200),
	    COLNAME		VARCHAR(50)     ---动态列的列名
	)			 
	INSERT INTO #AssistInfo
	SELECT USERCODE,
		   FULLNAME,
		   CASE WHEN USERCODE='01' THEN 'selectstypeid'
				WHEN USERCODE='02' THEN 'selectdtypeid'
				WHEN USERCODE='03' THEN 'selectetypeid'
				WHEN USERCODE='04' THEN 'selectbtypeid' 
		   END 
	FROM Ac_Account_Assist_CheckItems a 
	JOIN Ac_Assist_CheckItems b ON a.ASCIDS=b.ASCIDS  
	WHERE STYPEID=@STypeId AND ATYPEID=@ATypeId AND CID=@Cid
   
	-----结果临时表
    CREATE TABLE #temp
	(
	   TOTAL	 NUMERIC(24, 10) 
	)
    
    ----给结果临时表动态添加辅助核算列
	DECLARE @DynCol VARCHAR(MAX)
	SELECT @DynCol=(ISNULL(@DynCol+'] VARCHAR(66),[','') +  FULLNAME) 
	FROM #AssistInfo GROUP BY FULLNAME 
	SET @DynCol='ALTER TABLE #temp ADD ['+@DynCol+'] VARCHAR(66)'
	
	EXEC(@DynCol)
	
	DECLARE @DynColID VARCHAR(MAX)
	SELECT @DynColID=(ISNULL(@DynColID+'] VARCHAR(66),[','') +  COLNAME) 
	FROM #AssistInfo GROUP BY COLNAME 
	SET @DynColID='ALTER TABLE #temp ADD ['+@DynColID+'] VARCHAR(66)'
	
	EXEC(@DynColID)
	

    --分支机构
    IF (SELECT TOP 1 1 FROM #AssistInfo WHERE USERCODE='01')=1
		BEGIN
		   SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='01'
		   SET @INSERTSQL+=@tempFullName+','
		   SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='01'
		   SET @INSERTSQL+=@tempColName+','
		   SET @SELECTSQL+='STYPENAME,STYPEID,'
		   SET @GROUPBYSQL+='STYPENAME,STYPEID,'
		END
	
	--部门
	IF(SELECT TOP 1 1 FROM #AssistInfo WHERE USERCODE='02')=1
		BEGIN
		    SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='02'
		    SET @INSERTSQL+=@tempFullName+','
		    SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='02'
		    SET @INSERTSQL+=@tempColName+','
		    SET @SELECTSQL+='DTYPENAME,DTYPEID,'
		    SET @GROUPBYSQL+='DTYPENAME,DTYPEID,'
		END	
    
    --职员
    IF (SELECT TOP 1 1 FROM #AssistInfo WHERE USERCODE='03')=1
		BEGIN
		    SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='03'
		    SET @INSERTSQL+=@tempFullName+','
		    SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='03'
		    SET @INSERTSQL+=@tempColName+','
		    SET @SELECTSQL+='ETYPENAME,ETYPEID,'
		    SET @GROUPBYSQL+='ETYPENAME,ETYPEID,'
		END
		
	--往来单位
	IF(SELECT TOP 1 1 FROM #AssistInfo WHERE USERCODE='04')=1
		BEGIN
		    SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='04'
		    SET @INSERTSQL+=@tempFullName+','
		    SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='04'
		    SET @INSERTSQL+=@tempColName+','
		    SET @SELECTSQL+='BTYPENAME,BTYPEID,'
		    SET @GROUPBYSQL+='BTYPENAME,BTYPEID,'
		END
		
    SET @INSERTSQL+='TOTAL)'
    SET @SELECTSQL+='SUM(TOTAL) FROM @AllData '
    
    IF(@GROUPBYSQL=' GROUP BY ')        
		SET @SQL=@INSERTSQL+@SELECTSQL
	ELSE
		SET @SQL=@INSERTSQL+@SELECTSQL+@GROUPBYSQL
	
	----@SQL以，结尾，把，去掉
	IF(RIGHT(@SQL,1)=',')
		SET @SQL=LEFT(@SQL,LEN(@SQL)-1)
		
	  PRINT @SQL
	EXEC sp_executesql @SQL,N'@AllData Type_CardInsert READONLY',@AllData
	
	--查询符合格式的数据   
	SELECT * FROM #temp     
	     
	--查询金额总数
	SELECT SUM(ISNULL(TOTAL,0)) AS TOTAL
	FROM @AllData
	
	--动态列
	SELECT COLNAME 
	FROM #AssistInfo
	
	
	DROP TABLE #AssistInfo,#temp                                                                      
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================    
-- 功能说明： 查询货位信息  
-- 作者：  冯娅    
-- 最后修改时间： 2012-04-16   
-- ======================================================================== 

IF EXISTS(SELECT * FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetCargoTypeInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	BEGIN
		DROP PROCEDURE Web_GetCargoTypeInfo
	END

GO
	
CREATE PROCEDURE Web_GetCargoTypeInfo
(
	@OperatorID		VARCHAR(100),
	@usercode		VARCHAR(200),
	@fullname		VARCHAR(200),
	@ifDeleted		INT = 0   --是否显示停用信息  
)
--@encode$--
AS

SET NOCOUNT ON

DECLARE @SqlString NVARCHAR(2000)

SET @SqlString = 'SELECT
							C.CargoID,
							C.UserCode,					--货位编号
							C.FullName,					--货位名称
							C.KtypeID,					--仓库ID
							S.FullName AS kfullName,	--仓库名称
							C.Comment,
							T.typeid AS stypeid,		--分支机构ID
							T.FullName AS sfullname,	--分支机构名称
							C.XiWaMaxNumber,
							C.deleted,
							C.IsDefault,
							isnull(C.PathNo	,0) as 	PathNo			--货位路径号 默认为0 
					FROM 	CargoType C
					INNER JOIN Stock S ON S.typeId = C.KtypeID
					INNER JOIN F_BaseGetManDetailKType('''+@OperatorID+''') k on k.typeId = s.typeId
					INNER JOIN stype T ON T.TypeID = S.STypeID
					WHERE C.usercode LIKE ''%'+@usercode+'%''
						  AND C.FullName LIKE ''%'+@fullname+'%'''
 			 
--当该参数为0时，显示所有未被停用的信息，否则显示所有
IF 	@ifDeleted = 0
	SET @SqlString = @SqlString + 'AND C.deleted = 0'

SET @SqlString += 'ORDER BY C.usercode, C.PathNo'--0的优先级高 排最前面

EXEC(@SqlString)
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetCarInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetCarInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-15
	描述：取得车辆信息
*/
CREATE PROCEDURE Web_GetCarInfo
(
	@filter varchar(50)=''
)	
--@encode$--
AS
SET NOCOUNT ON;
	DECLARE @sql varchar(1000)
	DECLARE @WHERE_SQL VARCHAR(500)=''
	SET NOCOUNT ON;
	IF @filter<>'' SET @WHERE_SQL=' WHERE c.Platenumber LIKE ''%' + @filter + '%'''+' ' 
	SET @sql='select c.typeid, c.Platenumber,c.Cartype,c.Receptiondate,e.FullName as Driver
		from CM_CarInfo as c left join employee as e on e.typeId=c.Driver '+@WHERE_SQL
	EXEC(@sql)

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetClearMenuId]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetClearMenuId]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2017-10-30
	描述：根据模块配置，获取不需要的菜单ID
*/
CREATE PROCEDURE Web_GetClearMenuId
AS
SET NOCOUNT ON

DECLARE @ExcMenuId			VARCHAR(100),
		@ExcIsSubMenu		INT,
		@ExcSubMenuId		VARCHAR(100),
		@ExcSubIsSubMenu	INT,
		@ExcSubMenuId01		VARCHAR(100),
		@ExcSubIsSubMenu01	INT
		
DECLARE @ExcludeMenuId TABLE
(
	MenuId		VARCHAR(100)
)

DECLARE ExcludeCursor CURSOR FOR
	SELECT M.MenuId,M.IsSubMenu FROM MenuTemplateConfig C,WebMenu M WHERE C.MenuID = M.ParentID AND C.IsChecked = 0
	
OPEN ExcludeCursor

FETCH NEXT FROM ExcludeCursor INTO @ExcMenuId,@ExcIsSubMenu

WHILE @@FETCH_STATUS = 0
BEGIN
	IF @ExcIsSubMenu = 1
		BEGIN
			DECLARE ExcludeSubCursor CURSOR FOR
				SELECT M.MenuId,M.IsSubMenu FROM MenuTemplateConfig C,WebMenu M WHERE C.MenuID = M.MenuID AND C.IsChecked = 0
				
			OPEN ExcludeSubCursor
			
			FETCH NEXT FROM ExcludeSubCursor INTO @ExcSubMenuId,@ExcSubIsSubMenu
			
			WHILE @@FETCH_STATUS = 0
			BEGIN
				IF @ExcIsSubMenu = 1
					BEGIN
						DECLARE ExcludeSubCursor01 CURSOR FOR
							SELECT M.MenuId,M.IsSubMenu FROM MenuTemplateConfig C,WebMenu M WHERE C.MenuID = M.MenuID AND C.IsChecked = 0
						
						OPEN ExcludeSubCursor01
			
						FETCH NEXT FROM ExcludeSubCursor01 INTO @ExcSubMenuId01,@ExcSubIsSubMenu01
						
						WHILE @@FETCH_STATUS = 0
						BEGIN
							INSERT INTO @ExcludeMenuId(MenuId)VALUES(@ExcSubMenuId01)
							FETCH NEXT FROM ExcludeSubCursor01 INTO @ExcSubMenuId01,@ExcSubIsSubMenu01
						END
						
						CLOSE ExcludeSubCursor01
						DEALLOCATE ExcludeSubCursor01
					END										
				ELSE
					BEGIN
						INSERT INTO @ExcludeMenuId(MenuId)VALUES(@ExcMenuId)		
					END
					
				FETCH NEXT FROM ExcludeSubCursor INTO @ExcSubMenuId,@ExcSubIsSubMenu
			END
			
			CLOSE ExcludeSubCursor
			DEALLOCATE ExcludeSubCursor			
		END
	ELSE
		BEGIN
			INSERT INTO @ExcludeMenuId(MenuId)VALUES(@ExcMenuId)		
		END
		
	FETCH NEXT FROM ExcludeCursor INTO @ExcMenuId,@ExcIsSubMenu
END

CLOSE ExcludeCursor
DEALLOCATE ExcludeCursor

SELECT * FROM @ExcludeMenuId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetCombinationOrderbill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetCombinationOrderbill
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		罗淮文
-- Create date: 2016-07-15
-- Description:  调组合品销售订单明细
-- =============================================
CREATE PROCEDURE Web_GetCombinationOrderbill
(
	@billnumberid INT,
	@pindexids	varchar(max)='',
	@flag		INT		--0:订单调订单，1:出库单调订单
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
DECLARE @IsCombined INT,@BillType INT
SELECT @BillType = billtype FROM dbo.OrderIndex WHERE billNumberId = @billnumberid
SELECT @IsCombined=IsCombined FROM PT_Combin_OrderBill WHERE billNumberID=@billnumberid

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId=@billnumberid AND cbd.BillType=@BillType
AND cbd.InOrOut='I'

CREATE TABLE #TmpOrder(
	[billNumberID] [numeric](18, 0) NOT NULL,
	[ptypeid] [varchar](50) NULL,
	[qty] [numeric](24, 10) NOT NULL,
	[price] [numeric](24, 10) NULL,
	[total] [numeric](24, 10) NULL,
	[ReachQty] [numeric](24, 10) NOT NULL,
	[comment] [varchar](255) NULL,
	[OrderID] [int] NOT NULL,
	[Checked] [bit] NOT NULL,
	[TeamNO1] [int] NULL,
	[PassQty] [numeric](24, 10) NOT NULL,
	[IsUnit2] [bit] NOT NULL,
	[Discount] [numeric](24, 10) NULL,
	[DiscountPrice] [numeric](24, 10) NULL,
	[TaxPrice] [numeric](24, 10) NULL,
	[TaxTotal] [numeric](24, 10) NULL,
	[SaleTotal] [numeric](24, 10) NULL,
	[Tax] [numeric](24, 10) NULL,
	[KTypeID] [varchar](50) NULL,
	[Stypeid] [varchar](50) NULL,
	[FromBillNumberID] [numeric](10, 0) NULL,
	[entrycode] [varchar](max) NULL,
	[FromBillID] [numeric](10, 0) NULL,
	[ReachTotal] [numeric](24, 10) NULL,
	[ReachTaxTotal] [numeric](24, 10) NULL,
	[RequestBillNumberID] [numeric](10, 0) NULL,
	[RequestBillID] [numeric](10, 0) NULL,
	[AskBillNumberID] [numeric](10, 0) NULL,
	[AskBillID] [numeric](10, 0) NULL,
	[TaxMoney] [numeric](24, 10) NULL,
	[NSalePrice] [numeric](24, 10) NULL,
	[NSaleTotal] [numeric](24, 10) NULL,
	[NDiscountPrice] [numeric](24, 10) NULL,
	[NTotal] [numeric](24, 10) NULL,
	[NTaxPrice] [numeric](24, 10) NULL,
	[NTaxTotal] [numeric](24, 10) NULL,
	[NTaxMoney] [numeric](24, 10) NULL,
	[UnitID] [int] NULL,
	[NUnitID] [int] NULL,
	[NQty] [numeric](24, 10) NULL,
	[UnitRate] [numeric](24, 10) NULL,
	[NUnitMsg] [varchar](50) NULL,
	[MUnitID] [int] NULL,
	[MQty] [numeric](24, 10) NULL,
	[MUnitRate] [numeric](24, 10) NULL,
	[MUnitMsg] [varchar](50) NULL,
	[MSalePrice] [numeric](24, 10) NULL,
	[MDiscountPrice] [numeric](24, 10) NULL,
	[MTaxPrice] [numeric](24, 10) NULL,
	[CurMSalePrice] [numeric](24, 10) NULL,
	[CurMDiscountPrice] [numeric](24, 10) NULL,
	[CurMTaxPrice] [numeric](24, 10) NULL,
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[GoodsCostPrice] [numeric](24, 10) NULL,
	[GoodsOrder] [int] NULL,
	[IsGift] [int] NOT NULL,
	[YapiID] [varchar](20) NULL,
	[WaitQty] [numeric](24, 10) NULL,
	[BillOver] [bit] NULL,
	[CargoID] [int] NULL,
	[PriceSource] [varchar](200) NOT NULL,
	[PromoType] [int] NOT NULL,
	[ShowOrder] [int] NULL,
	[stopreason] [varchar](max) NULL,
	[pindexid] [varchar](300) NULL
)

if(@flag=1)
BEGIN
	INSERT INTO #TmpOrder
	SELECT [billNumberID]
      ,[ptypeid]
      ,[qty]
      ,[price]
      ,[total]
      ,[ReachQty]
      ,[comment]
      ,[OrderID]
      ,[Checked]
      ,[TeamNO1]
      ,[PassQty]
      ,[IsUnit2]
      ,[Discount]
      ,[DiscountPrice]
      ,[TaxPrice]
      ,[TaxTotal]
      ,[SaleTotal]
      ,[Tax]
      ,[KTypeID]
      ,[Stypeid]
      ,[FromBillNumberID]
      ,[entrycode]
      ,[FromBillID]
      ,[ReachTotal]
      ,[ReachTaxTotal]
      ,[RequestBillNumberID]
      ,[RequestBillID]
      ,[AskBillNumberID]
      ,[AskBillID]
      ,[TaxMoney]
      ,[NSalePrice]
      ,[NSaleTotal]
      ,[NDiscountPrice]
      ,[NTotal]
      ,[NTaxPrice]
      ,[NTaxTotal]
      ,[NTaxMoney]
      ,[UnitID]
      ,[NUnitID]
      ,[NQty]
      ,[UnitRate]
      ,[NUnitMsg]
      ,[MUnitID]
      ,[MQty]
      ,[MUnitRate]
      ,[MUnitMsg]
      ,[MSalePrice]
      ,[MDiscountPrice]
      ,[MTaxPrice]
      ,[CurMSalePrice]
      ,[CurMDiscountPrice]
      ,[CurMTaxPrice]
      ,[ItemID]
      ,[IsCombined]
      ,[GoodsCostPrice]
      ,[GoodsOrder]
      ,[IsGift]
      ,[YapiID]
      ,[WaitQty]
      ,[BillOver]
      ,[CargoID]
      ,[PriceSource]
      ,[PromoType]
      ,[ShowOrder]
      ,[stopreason]
      ,[pindexid]
  FROM [dbo].[PT_Combin_OrderBill] po
	INNER JOIN dbo.f_split(@pindexids,',') s ON po.pindexid=s.a 
END
ELSE
BEGIN
	INSERT INTO #TmpOrder
	SELECT [billNumberID]
      ,[ptypeid]
      ,[qty]
      ,[price]
      ,[total]
      ,[ReachQty]
      ,[comment]
      ,[OrderID]
      ,[Checked]
      ,[TeamNO1]
      ,[PassQty]
      ,[IsUnit2]
      ,[Discount]
      ,[DiscountPrice]
      ,[TaxPrice]
      ,[TaxTotal]
      ,[SaleTotal]
      ,[Tax]
      ,[KTypeID]
      ,[Stypeid]
      ,[FromBillNumberID]
      ,[entrycode]
      ,[FromBillID]
      ,[ReachTotal]
      ,[ReachTaxTotal]
      ,[RequestBillNumberID]
      ,[RequestBillID]
      ,[AskBillNumberID]
      ,[AskBillID]
      ,[TaxMoney]
      ,[NSalePrice]
      ,[NSaleTotal]
      ,[NDiscountPrice]
      ,[NTotal]
      ,[NTaxPrice]
      ,[NTaxTotal]
      ,[NTaxMoney]
      ,[UnitID]
      ,[NUnitID]
      ,[NQty]
      ,[UnitRate]
      ,[NUnitMsg]
      ,[MUnitID]
      ,[MQty]
      ,[MUnitRate]
      ,[MUnitMsg]
      ,[MSalePrice]
      ,[MDiscountPrice]
      ,[MTaxPrice]
      ,[CurMSalePrice]
      ,[CurMDiscountPrice]
      ,[CurMTaxPrice]
      ,[ItemID]
      ,[IsCombined]
      ,[GoodsCostPrice]
      ,[GoodsOrder]
      ,[IsGift]
      ,[YapiID]
      ,[WaitQty]
      ,[BillOver]
      ,[CargoID]
      ,[PriceSource]
      ,[PromoType]
      ,[ShowOrder]
      ,[stopreason]
      ,[pindexid] 
    FROM dbo.PT_Combin_OrderBill
	WHERE billNumberID = @billnumberid
END

--和此订单有关的单据
CREATE TABLE #TmpBill
(
	OrderId	INT,
	BillDetailId	INT
)

--组合品销售订单关联的组合品销售出库
IF @BillType = 313
	INSERT INTO #TmpBill( OrderId, BillDetailId )
	SELECT  T3.OrderID,T2.ID
	FROM dbo.BillIndex T1
		INNER JOIN dbo.PT_Combin_SaleBill T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN PT_Combin_OrderBill T3 ON T2.OrderID = T3.OrderID
	WHERE T1.BillType = 12 AND T1.RedWord = 0
	
	
SELECT DISTINCT OrderIndex.billNumberId,
	btype.FullName AS fhdw,
	T1.OrderID,
	qty = T1.Qty,
	Price = T1.Price,
    T1.Discount,
	T1.Tax,
	TaxPrice = T1.TaxPrice,
	DiscountPrice = T1.DiscountPrice,
	T1.TaxTotal,
	BigQty =
		CASE WHEN dbo.ptype.UnitRate1 = 0 THEN
			T1.Qty
		ELSE CAST(T1.Qty/dbo.ptype.UnitRate1 AS  NUMERIC(24, 10) ) END,
	T1.total as discounttotal,
	ReachQty = T1.ReachQty,
	T1.PassQty, 
	T1.SaleTotal as total,
	T1.Ktypeid,
	T1.frombillnumberid,
	T1.frombillid,
	T1.RequestBillNumberID,
	T1.RequestBillID,
	ptype.typeid,
	ptype.UserCode,
	ptype.FullName,
	CASE WHEN ISNULL(T1.entrycode,'')='' then ptype.EntryCode
	else T1.entrycode end as entrycode,
	ptype.Standard,
	ptype.Type,
	ptype.Area,
	ptype.Unit1 as unitone,
	ptype.Unit2 as unittwo,
	0 as UnitRate1,
	0 as UnitRate2,
	ptype.IfSerial,
	ptype.serialcount,
	ptype.validdays,
	ptype.usefullifeday,
	T1.comment as base,
	Stock.UserCode AS KUserCode,
	Stock.FullName AS KFullName,
	CustomerCode = (SELECT UserCode FROM PuserCode WHERE PtypeId = T1.PtypeId AND BtypeId = OrderIndex.DealBTypeID),
	IsUnit2 = 0,
	accountqty=(select  isnull(SUM(qty),0) from GoodsStocks where T1.ptypeid=ptypeid AND T1.ktypeid=ktypeid) ,
	T1.AskBillID as askbillid,   
	T1.AskBillNumberID as AskBillNumberID, 
	T1.requestbillid as requestbillid, 
	T1.RequestBillNumberID as requestbillnumberid,
	U.FullName AS munit ,							
	V.FullName AS nunit,
	W.FullName AS unit,
	T1.MUnitID, 							
	T1.NUnitID,
	T1.UnitID,
	T1.MQty,
	T1.MUnitRate,
	T1.curmsaleprice,		 
	T1.nsaletotal,		 
	T1.nsaleprice,
	CASE WHEN ISNULL(T1.NUnitID,0) = 0 THEN NULL
	ELSE T1.unitrate END AS unitrate,
	CASE WHEN ISNULL(T1.NUnitID,0) = 0 THEN NULL
	ELSE T1.nqty END AS nqty,
	T1.curmdiscountprice,
	T1.ntotal,	
	T1.curmtaxprice,
	T1.ntaxmoney,
	T1.ntaxtotal,		 
	T1.taxmoney,
	T1.ItemID,
	T1.IsCombined,
	T1.NDiscountPrice,
	T1.NTaxPrice,
	T1.MSalePrice,
	T1.MDiscountPrice,
	T1.MTaxPrice,
	T1.GoodsCostPrice,
	T1.GoodsCostPrice AS GOODSNUMBERPRICE,
	T1.GoodsOrder,
	T1.isgift,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname1,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname2,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname3,
	(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate1,
	(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate2,
	(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate3,
	ptype.unitstype,
	ptype.customitemid,
	ptype.customitemfrom,
	ptype.customitemname,
	ptype.customitemrefid,
	itemname= CASE WHEN T1.IsCombined = 0  THEN
						    (SELECT FullName FROM xw_SelfData WHERE _Id= T1.ItemId)
					        ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= T1.ItemId ) END,
	T1.cargoid,	
	ct.fullname as cargofullname,
	T1.OrderID,		        
	T1.BillOver,
	T1.YapiID,
	CAST(ptype.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
	CASE WHEN st.pricetype=0 THEN pp.ReferPrice
	WHEN st.pricetype=1 THEN 
		CASE WHEN ISNULL(sp.Referprice,0)=0 THEN pp.ReferPrice
		ELSE sp.Referprice END
	END AS ReferPrice,
	ptype.IsService,
	T1.pricesource,
	CASE WHEN ISNULL(T2.BillDetailId,0) > 0 THEN 1
		 WHEN T1.ReachQty>0 THEN 1 
		 ELSE 0 END AS isref,
	promotype,
	(dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2)) AS salemunitcode,
	(dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2)) AS buymunitcode,
	(dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2)) AS stockmunitcode,
	T1.stopreason,
	cbd.*,T1.pindexid,ptype.iscombinationproduct,
	bc.typeid AS brandartypeid,
	bc.fullname AS brandarfullname,
	ptype.MultEntryCode,
	(SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks g WHERE g.PtypeId = T1.pTypeID AND g.KtypeId = T1.ktypeid  ) AS showcostprice
FROM OrderIndex 
LEFT JOIN btype ON OrderIndex.btypeid = btype.typeId     
INNER JOIN #TmpOrder T1 ON OrderIndex.billNumberId = T1.billNumberID 
INNER JOIN ptype ON T1.ptypeid = ptype.typeId
LEFT JOIN dbo.brandar_Commodity bc ON bc.typeid = ptype.brandartypeid
LEFT JOIN PType_StypePrice sp ON sp.ptypeid=ptype.typeid AND sp.stypeid=OrderIndex.stypeid AND sp.UnitID=T1.MunitID
INNER JOIN stype st ON st.typeid=Orderindex.stypeid
LEFT JOIN PType_Price pp ON pp.PTypeID = ptype.TypeID AND pp.UnitID=T1.MUnitID 
LEFT JOIN Stock ON T1.KtypeId=Stock.typeId
LEFT JOIN xw_SelfData ON T1.ptypeid=xw_SelfData.typeId AND T1.ItemID=xw_SelfData._Id
LEFT JOIN CustomReferenceValue  ON T1.ItemID=CustomReferenceValue.id
LEFT JOIN PType_Units U ON U.UnitsId=T1.MUnitID 
LEFT  JOIN PType_Units V ON V.UnitsId=T1.NUnitID
LEFT  JOIN PType_Units W ON W.UnitsId=T1.UnitID
LEFT  JOIN CargoType ct ON T1.CargoID = ct.CargoID
LEFT JOIN #TmpBill T2 ON T1.orderid = T2.orderid
LEFT JOIN #Custom_T cbd ON cbd.billid=OrderIndex.billnumberid AND cbd.detailid=T1.orderid
WHERE (OrderIndex.checked = 0 and OrderIndex.billNumberId=@billnumberid) 
ORDER BY dbo.OrderIndex.billNumberId ASC,T1.OrderID ASC

DROP TABLE #TmpOrder,#TmpBill

END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetCombinationOrderbillDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetCombinationOrderbillDetails
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		罗淮文
-- Create date: 2016-07-15
-- Description:  调组合品销售订单配料明细
-- =============================================
CREATE PROCEDURE Web_GetCombinationOrderbillDetails
(
	@billnumberid		INT,
	@pindexids			varchar(max)='',
	@flag				INT,			--0:订单调订单，1:出库单调订单
	@chvoperatorid 		varchar(50)='' 	-- 操作员 ID（作权限范围检查用）
)
--@encode$--
AS
BEGIN
SET NOCOUNT ON

-------- 权限检查 - Start --------
DECLARE @intRe int, 
		@chvMATypeID varchar(50), 
		@chvMBTypeID varchar(50), 
		@chvMBTypeID2 varchar(50), 
		@chvMETypeID varchar(50), 
		@chvMKTypeID varchar(50), 
		@chvMPTypeID varchar(50), 
		@chvMExpense varchar(50), 
		@chvMIncome varchar(50), 
		@chvMCapital varchar(50), 
		@chvMDtypeid varchar(50), 
		@chvMStypeid varchar(50)

EXEC @intRe = GP_CheckOperatorRight23_Rep 
	@chvoperatorid, 
	@chvMATypeID output, 
	@chvMBTypeID output, 
	@chvMBTypeID2 output, 
	@chvMETypeID output, 
	@chvMKTypeID output, 
	@chvMPTypeID output, 
	@chvMExpense output, 
	@chvMIncome output, 
	@chvMCapital output, 
	@chvMDtypeid output, 
	@chvMStypeid output

--拥有查询所有商品的权限（MangerPTypeID = '00000'）
--（MangerPTypeID = '-99999'并且ptype_l没有记录，表示没有权限)
--（MangerPTypeID = '-99999'并且ptype_l有记录，表示拥有部分权限)
CREATE TABLE #temp_PtypeId
(
	Typeid	VARCHAR(50)
)
CREATE CLUSTERED INDEX CIX_PTYPE_typeid ON #temp_PtypeId(Typeid) 
IF @intRe = 0 AND @chvMPTypeID = '-99999'
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM PType_L WHERE ETypeId = @chvoperatorid)
	BEGIN
		insert into #temp_PtypeId (Typeid)	
		SELECT 	M.typeId
		FROM 	(
				SELECT	DISTINCT P.TypeId 
				FROM	PType_L L
				INNER JOIN PType  P ON (L.etypeid = @chvoperatorid 
										AND L.Flag=1 
										--AND P.deleted = 0
										AND P.TypeId LIKE L.TypeId + '%' )
				UNION
				SELECT	L.TypeID
				FROM	ptype_l L
				WHERE	L.etypeid = @chvoperatorid
						AND L.flag=0
			) M
	END
END
ELSE IF @intRe = 0 AND @chvMPTypeID = '00000'
BEGIN
	insert into #temp_PtypeId (Typeid)	
	SELECT DISTINCT typeId FROM PType 
	WHERE	sonnum = 0 
			--AND deleted = 0 
END
	
DECLARE @IsCombined INT,@BillType INT
SELECT @BillType = billtype FROM dbo.OrderIndex WHERE billNumberId = @billnumberid
SELECT @IsCombined=IsCombined FROM PT_Combin_OrderBillDetail WHERE billNumberID=@billnumberid

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId=@billnumberid AND cbd.BillType=@BillType
AND cbd.InOrOut='O'

CREATE TABLE #TmpOrder(
	[billNumberID] [numeric](18, 0) NOT NULL,
	[ptypeid] [varchar](50) NULL,
	[qty] [numeric](24, 10) NOT NULL,
	[price] [numeric](24, 10) NULL,
	[total] [numeric](24, 10) NULL,
	[ReachQty] [numeric](24, 10) NOT NULL,
	[comment] [varchar](255) NULL,
	[OrderID] [int] NOT NULL,
	[Checked] [bit] NOT NULL,
	[TeamNO1] [int] NULL,
	[PassQty] [numeric](24, 10) NOT NULL,
	[IsUnit2] [bit] NOT NULL,
	[Discount] [numeric](24, 10) NULL,
	[DiscountPrice] [numeric](24, 10) NULL,
	[TaxPrice] [numeric](24, 10) NULL,
	[TaxTotal] [numeric](24, 10) NULL,
	[SaleTotal] [numeric](24, 10) NULL,
	[Tax] [numeric](24, 10) NULL,
	[KTypeID] [varchar](50) NULL,
	[Stypeid] [varchar](50) NULL,
	[FromBillNumberID] [numeric](10, 0) NULL,
	[entrycode] [varchar](max) NULL,
	[FromBillID] [numeric](10, 0) NULL,
	[ReachTotal] [numeric](24, 10) NULL,
	[ReachTaxTotal] [numeric](24, 10) NULL,
	[RequestBillNumberID] [numeric](10, 0) NULL,
	[RequestBillID] [numeric](10, 0) NULL,
	[AskBillNumberID] [numeric](10, 0) NULL,
	[AskBillID] [numeric](10, 0) NULL,
	[TaxMoney] [numeric](24, 10) NULL,
	[NSalePrice] [numeric](24, 10) NULL,
	[NSaleTotal] [numeric](24, 10) NULL,
	[NDiscountPrice] [numeric](24, 10) NULL,
	[NTotal] [numeric](24, 10) NULL,
	[NTaxPrice] [numeric](24, 10) NULL,
	[NTaxTotal] [numeric](24, 10) NULL,
	[NTaxMoney] [numeric](24, 10) NULL,
	[UnitID] [int] NULL,
	[NUnitID] [int] NULL,
	[NQty] [numeric](24, 10) NULL,
	[UnitRate] [numeric](24, 10) NULL,
	[NUnitMsg] [varchar](50) NULL,
	[MUnitID] [int] NULL,
	[MQty] [numeric](24, 10) NULL,
	[MUnitRate] [numeric](24, 10) NULL,
	[MUnitMsg] [varchar](50) NULL,
	[MSalePrice] [numeric](24, 10) NULL,
	[MDiscountPrice] [numeric](24, 10) NULL,
	[MTaxPrice] [numeric](24, 10) NULL,
	[CurMSalePrice] [numeric](24, 10) NULL,
	[CurMDiscountPrice] [numeric](24, 10) NULL,
	[CurMTaxPrice] [numeric](24, 10) NULL,
	[ItemID] [bigint] NULL,
	[IsCombined] [int] NULL,
	[GoodsCostPrice] [numeric](24, 10) NULL,
	[GoodsOrder] [int] NULL,
	[ProduceDate] [varchar](50) NULL,
	[ValidDate] [varchar](50) NULL,
	[IsGift] [int] NOT NULL,
	[YapiID] [varchar](20) NULL,
	[WaitQty] [numeric](24, 10) NULL,
	[BillOver] [bit] NULL,
	[GoodsNumber] [varchar](100) NULL,
	[CargoID] [int] NULL,
	[PriceSource] [varchar](200) NOT NULL,
	[PromoType] [int] NOT NULL,
	[ShowOrder] [int] NULL,
	[stopreason] [varchar](max) NULL,
	[pindexid] [varchar](300) NULL,
	[combinationptypeid] [varchar](200) NULL,
	LockNumber	numeric(24,10) NULL
)

if(@flag=1)
BEGIN
	INSERT INTO #TmpOrder
	SELECT [billNumberID]
      ,[ptypeid]
      ,[qty]
      ,[price]
      ,[total]
      ,[ReachQty]
      ,[comment]
      ,[OrderID]
      ,[Checked]
      ,[TeamNO1]
      ,[PassQty]
      ,[IsUnit2]
      ,[Discount]
      ,[DiscountPrice]
      ,[TaxPrice]
      ,[TaxTotal]
      ,[SaleTotal]
      ,[Tax]
      ,[KTypeID]
      ,[Stypeid]
      ,[FromBillNumberID]
      ,[entrycode]
      ,[FromBillID]
      ,[ReachTotal]
      ,[ReachTaxTotal]
      ,[RequestBillNumberID]
      ,[RequestBillID]
      ,[AskBillNumberID]
      ,[AskBillID]
      ,[TaxMoney]
      ,[NSalePrice]
      ,[NSaleTotal]
      ,[NDiscountPrice]
      ,[NTotal]
      ,[NTaxPrice]
      ,[NTaxTotal]
      ,[NTaxMoney]
      ,[UnitID]
      ,[NUnitID]
      ,[NQty]
      ,[UnitRate]
      ,[NUnitMsg]
      ,[MUnitID]
      ,[MQty]
      ,[MUnitRate]
      ,[MUnitMsg]
      ,[MSalePrice]
      ,[MDiscountPrice]
      ,[MTaxPrice]
      ,[CurMSalePrice]
      ,[CurMDiscountPrice]
      ,[CurMTaxPrice]
      ,[ItemID]
      ,[IsCombined]
      ,[GoodsCostPrice]
      ,[GoodsOrder]
      ,[ProduceDate]
      ,[ValidDate]
      ,[IsGift]
      ,[YapiID]
      ,[WaitQty]
      ,[BillOver]
      ,[GoodsNumber]
      ,[CargoID]
      ,[PriceSource]
      ,[PromoType]
      ,[ShowOrder]
      ,[stopreason]
      ,[pindexid]
      ,[combinationptypeid]
      ,[LockNumber]
  FROM [dbo].[PT_Combin_OrderBillDetail]  po
	INNER JOIN dbo.f_split(@pindexids,',') s ON po.pindexid=s.a 
END
ELSE
BEGIN
	INSERT INTO #TmpOrder
	SELECT [billNumberID]
      ,[ptypeid]
      ,[qty]
      ,[price]
      ,[total]
      ,[ReachQty]
      ,[comment]
      ,[OrderID]
      ,[Checked]
      ,[TeamNO1]
      ,[PassQty]
      ,[IsUnit2]
      ,[Discount]
      ,[DiscountPrice]
      ,[TaxPrice]
      ,[TaxTotal]
      ,[SaleTotal]
      ,[Tax]
      ,[KTypeID]
      ,[Stypeid]
      ,[FromBillNumberID]
      ,[entrycode]
      ,[FromBillID]
      ,[ReachTotal]
      ,[ReachTaxTotal]
      ,[RequestBillNumberID]
      ,[RequestBillID]
      ,[AskBillNumberID]
      ,[AskBillID]
      ,[TaxMoney]
      ,[NSalePrice]
      ,[NSaleTotal]
      ,[NDiscountPrice]
      ,[NTotal]
      ,[NTaxPrice]
      ,[NTaxTotal]
      ,[NTaxMoney]
      ,[UnitID]
      ,[NUnitID]
      ,[NQty]
      ,[UnitRate]
      ,[NUnitMsg]
      ,[MUnitID]
      ,[MQty]
      ,[MUnitRate]
      ,[MUnitMsg]
      ,[MSalePrice]
      ,[MDiscountPrice]
      ,[MTaxPrice]
      ,[CurMSalePrice]
      ,[CurMDiscountPrice]
      ,[CurMTaxPrice]
      ,[ItemID]
      ,[IsCombined]
      ,[GoodsCostPrice]
      ,[GoodsOrder]
      ,[ProduceDate]
      ,[ValidDate]
      ,[IsGift]
      ,[YapiID]
      ,[WaitQty]
      ,[BillOver]
      ,[GoodsNumber]
      ,[CargoID]
      ,[PriceSource]
      ,[PromoType]
      ,[ShowOrder]
      ,[stopreason]
      ,[pindexid]
      ,[combinationptypeid]
      ,[LockNumber]
  FROM [dbo].[PT_Combin_OrderBillDetail] 
  WHERE billNumberID = @billnumberid
END

--和此订单有关的单据
CREATE TABLE #TmpBill
(
	OrderId	INT,
	BillDetailId	INT
)

--组合品销售订单关联的组合品销售出库
IF @BillType = 313
	INSERT INTO #TmpBill( OrderId, BillDetailId )
	SELECT  T3.OrderID,T2.ID
	FROM dbo.BillIndex T1
		INNER JOIN dbo.PT_Combin_SaleBillDetail T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN #TmpOrder T3 ON T2.OrderID = T3.OrderID
	WHERE T1.BillType = 12 AND T1.RedWord = 0
	
SELECT DISTINCT OrderIndex.billNumberId,
	btype.FullName AS fhdw,
	T1.OrderID,
	qty = T1.Qty,
	Price = T1.Price,
    T1.Discount,
	T1.Tax,
	TaxPrice = T1.TaxPrice,
	DiscountPrice = T1.DiscountPrice,
	T1.TaxTotal,
	BigQty =
		CASE WHEN dbo.ptype.UnitRate1 = 0 THEN
			T1.Qty
		ELSE CAST(T1.Qty/dbo.ptype.UnitRate1 AS  NUMERIC(24, 10) ) END,
	T1.total as discounttotal,
	ReachQty = T1.ReachQty,
	T1.PassQty, 
	T1.SaleTotal as total,
	T1.Ktypeid,
	T1.frombillnumberid,
	T1.frombillid,
	T1.RequestBillNumberID,
	T1.RequestBillID,
	ptype.typeid,
	ptype.UserCode,
	ptype.FullName,
	CASE WHEN ISNULL(T1.entrycode,'')='' then ptype.EntryCode
	else T1.entrycode end as entrycode,
	ptype.Standard,
	ptype.Type,
	ptype.Area,
	ptype.Unit1 as unitone,
	ptype.Unit2 as unittwo,
	0 as UnitRate1,
	0 as UnitRate2,
	ptype.IfSerial,
	ptype.serialcount,
	ptype.validdays,
	ptype.usefullifeday,
	T1.comment as base,
	Stock.UserCode AS KUserCode,
	Stock.FullName AS KFullName,
	CustomerCode = (SELECT UserCode FROM PuserCode WHERE PtypeId = T1.PtypeId AND BtypeId = OrderIndex.DealBTypeID),
	IsUnit2 = 0,
	accountqty=(select  isnull(SUM(qty),0) from GoodsStocks where T1.ptypeid=ptypeid AND T1.ktypeid=ktypeid) ,
	T1.AskBillID as askbillid,   
	T1.AskBillNumberID as AskBillNumberID, 
	T1.requestbillid as requestbillid, 
	T1.RequestBillNumberID as requestbillnumberid,
	U.FullName AS munit ,							
	V.FullName AS nunit,
	W.FullName AS unit,
	T1.MUnitID, 							
	T1.NUnitID,
	T1.UnitID,
	T1.GoodsNumber,
	T1.MQty,
	T1.MUnitRate,
	T1.curmsaleprice,		 
	T1.nsaletotal,		 
	T1.nsaleprice,
	CASE WHEN ISNULL(T1.NUnitID,0) = 0 THEN NULL
	ELSE T1.unitrate END AS unitrate,
	CASE WHEN ISNULL(T1.NUnitID,0) = 0 THEN NULL
	ELSE T1.nqty END AS nqty,
	T1.curmdiscountprice,
	T1.ntotal,	
	T1.curmtaxprice,
	T1.ntaxmoney,
	T1.ntaxtotal,		 
	T1.taxmoney,
	T1.ItemID,
	T1.IsCombined,
	T1.NDiscountPrice,
	T1.NTaxPrice,
	T1.MSalePrice,
	T1.MDiscountPrice,
	T1.MTaxPrice,
	T1.GoodsCostPrice,
	T1.GoodsCostPrice AS GOODSNUMBERPRICE,
	T1.GoodsOrder,
	T1.ProduceDate,
	T1.ValidDate,
	T1.isgift,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname1,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname2,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname3,
	(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate1,
	(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate2,
	(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate3,
	ptype.unitstype,
	ptype.customitemid,
	ptype.customitemfrom,
	ptype.customitemname,
	ptype.customitemrefid,
	itemname= CASE WHEN T1.IsCombined = 0  THEN
						    (SELECT FullName FROM xw_SelfData WHERE _Id= T1.ItemId)
					        ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= T1.ItemId ) END,
	T1.cargoid,	
	ct.fullname as cargofullname,
	T1.OrderID,		        
	T1.BillOver,
	T1.YapiID,
	CAST(ptype.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
	CASE WHEN st.pricetype=0 THEN pp.ReferPrice
	WHEN st.pricetype=1 THEN 
		CASE WHEN ISNULL(sp.Referprice,0)=0 THEN pp.ReferPrice
		ELSE sp.Referprice END
	END AS ReferPrice,
	ptype.IsService,
	T1.pricesource,
	CASE WHEN ISNULL(T2.BillDetailId,0) > 0 THEN 1
		 WHEN T1.ReachQty>0 THEN 1 
		 ELSE 0 END AS isref,
	promotype,
	(dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2)) AS salemunitcode,
	(dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2)) AS buymunitcode,
	(dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2)) AS stockmunitcode,
	T1.stopreason,
	cbd.*,T1.pindexid,T1.combinationptypeid,cpi.combinationproductfullname as combinationpfullname,ptype.iscombinationproduct,
	cp.combinationqty,cp.combinationprice,  
	T1.LockNumber,
	ptype.MultEntryCode,
	(SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks g WHERE g.PtypeId = T1.pTypeID AND g.KtypeId = T1.ktypeid  ) AS showcostprice,
case when exists(select 1 from orderbill where PTCombinOrderBillDetailID=T1.orderid) then 1 else 0 end as ifused --明细行被采购订单调用	
FROM OrderIndex 
    LEFT JOIN
		btype ON OrderIndex.btypeid = btype.typeId     
    INNER JOIN
		#TmpOrder T1 ON OrderIndex.billNumberId = T1.billNumberID 
    INNER JOIN
		ptype ON T1.ptypeid = ptype.typeId 
    INNER JOIN 
		#temp_PtypeId TPID ON T1.ptypeid=TPID.typeId
    LEFT JOIN 
	(
		SELECT cp1.combinationproductptyPeid,cp1.combinationproductfullname,cpd.qty as combinationqty,
		cpd.price as combinationprice,cpd.ptypeid 
		FROM combinationproductindex cp1 
		INNER JOIN  combinationproductdetail cpd ON cp1.combinationproductid=cpd.combinationproductid 
		WHERE cp1.IsCheck = 1
	 )cp ON T1.combinationptypeid=cp.combinationproductptypeid AND T1.ptypeid=cp.ptypeid 
	LEFT JOIN 
	(
		SELECT cpi.combinationproductfullname,pco.pindexid FROM dbo.PT_Combin_OrderBill pco
		INNER JOIN combinationproductindex cpi ON pco.ptypeid = cpi.CombinationProductPtypeId
		WHERE billNumberID=@billnumberid
	) cpi ON T1.pindexid = cpi.pindexid
    LEFT JOIN 
	  PType_StypePrice sp ON sp.ptypeid=ptype.typeid AND sp.stypeid=OrderIndex.stypeid AND T1.MunitID=sp.UnitID
	INNER JOIN 
	  stype st ON st.typeid=Orderindex.stypeid
    LEFT JOIN	
	  PType_Price pp ON pp.PTypeID = ptype.TypeID  AND t1.MunitID=pp.UnitID
    LEFT JOIN
      Stock ON T1.KtypeId=Stock.typeId
    LEFT JOIN
      xw_SelfData ON T1.ptypeid=xw_SelfData.typeId AND T1.ItemID=xw_SelfData._Id
    LEFT JOIN
      CustomReferenceValue  ON T1.ItemID=CustomReferenceValue.id
    LEFT JOIN  
      PType_Units U ON U.UnitsId=T1.MUnitID 
	LEFT  JOIN  
	  PType_Units V ON V.UnitsId=T1.NUnitID
    LEFT  JOIN  
	  PType_Units W ON W.UnitsId=T1.UnitID
	LEFT  JOIN  
	  CargoType ct ON T1.CargoID = ct.CargoID
	LEFT JOIN #TmpBill T2 ON T1.orderid = T2.orderid
	LEFT JOIN #Custom_T cbd ON cbd.billid=OrderIndex.billnumberid AND cbd.detailid=T1.orderid
WHERE (OrderIndex.checked = 0 and OrderIndex.billNumberId=@billnumberid) 
ORDER BY dbo.OrderIndex.billNumberId ASC,T1.OrderID ASC

DROP TABLE #TmpOrder,#TmpBill

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetCombinationPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetCombinationPtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
作者：罗淮文
日期：2016-04-12
描述：获取组合品
*/
/*
修改：田小波
日期：2016-11-28
描述：总条数错误
*/
CREATE PROCEDURE Web_GetCombinationPtype
(
	@combinationptypeidstr		VARCHAR(MAX),
	@operator					VARCHAR(200),
	@UserCode					VARCHAR(100)='',
	@intPageNo					INT,
	@intPageSize				INT,
	@intRowCount 				int output
)
--@encode$--
AS
SET NOCOUNT ON
	DECLARE @StartLine int, @EndLine int
	SET @StartLine = @intPageSize*(@intPageNo - 1) + 1;
	SET @EndLine = @intPageSize*@intPageNo;
	IF EXISTS (SELECT * FROM tempdb.dbo.SYSOBJECTS WHERE id = OBJECT_ID(N'tempdb..#tem_retData') AND TYPE='U')
	BEGIN
		DROP TABLE #tem_retData
	END
	CREATE TABLE #tem_retData
	(
		rowno					INT,
		combinationptypeid		VARCHAR(200),
		combinationpusercode	VARCHAR(200),
		combinationpfullname	VARCHAR(200),
		[standard]				VARCHAR(200),
		baseunitid				INT,
		baseunitfullname		VARCHAR(200),
		entrycode				VARCHAR(200)
	)
	IF(ISNULL(@combinationptypeidstr,'')='')
	BEGIN
		INSERT INTO #tem_retData
		SELECT ROW_NUMBER()OVER(ORDER BY p.sortid) AS rowno,p.typeid as combinationptypeid,p.usercode as combinationpusercode,p.fullname as combinationpfullname,
		p.[standard],p.baseunitid,pu.fullname as baseunitfullname,p.MultEntryCode as entrycode
		FROM ptype p LEFT JOIN PType_Units pu ON p.baseunitid=pu.unitsid 
		WHERE 	EXISTS(SELECT TypeId FROM F_GetManDetailPTypeIncludeCombination(@operator) M WHERE M.TypeId=P.typeId)
		AND TypeId <> '00000' AND deleted=0 AND iscombinationproduct=1
		AND (p.UserCode LIKE '%'+@UserCode+'%'   OR P.FullName LIKE '%'+@UserCode+'%' OR P.PyCode LIKE '%'+@UserCode+'%' OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@UserCode,2))) 
		SET @intRowCount=@@rowcount
	END
	ELSE
	BEGIN
		INSERT INTO #tem_retData
		SELECT ROW_NUMBER()OVER(ORDER BY p.sortid) AS rowno,p.typeid as combinationptypeid,p.usercode as combinationpusercode,p.fullname as combinationpfullname,
		p.[standard],p.baseunitid,pu.fullname as baseunitfullname,p.MultEntryCode as entrycode
		FROM ptype p 
		INNER JOIN dbo.f_split(@combinationptypeidstr,',') f ON p.typeid=f.a 
		INNER JOIN dbo.CombinationProductIndex CP ON cp.CombinationProductPtypeId=p.typeId AND cp.IsCheck=1 AND IsStop=0
		LEFT JOIN PType_Units pu ON p.baseunitid=pu.unitsid 
		WHERE 	EXISTS(SELECT TypeId FROM F_GetManDetailPTypeIncludeCombination(@operator) M WHERE M.TypeId=P.typeId)
		AND p.TypeId <> '00000' AND p.deleted=0 
		AND (p.UserCode LIKE '%'+@UserCode+'%'   OR P.FullName LIKE '%'+@UserCode+'%' OR P.PyCode LIKE '%'+@UserCode+'%' OR p.TypeID IN (SELECT Ptypeid FROM F_GetPtypeIdsByEntrycode(@UserCode,2))) 
		SET @intRowCount=@@rowcount
	END
	SELECT * FROM #tem_retData WHERE rowno BETWEEN @StartLine AND @EndLine
	--SET @intRowCount=@@rowcount
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetCommissinIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetCommissinIni]
GO


/*
== 委托、受托客户、库存查询 明细表的表头 期初数量，未结算金额
*/
/* 
    修改: 舒珊
    日期: 2015-05-27
    描述: 增加查询参数@ptypecategoryid 商品类别ID 
*/

CREATE PROCEDURE Web_GetCommissinIni 

(
	@OperatorID varchar(1550),
	@ptypeid varchar(1550),
	@btypeid varchar(1550),
	@type    int ,
	@stypeid varchar(1550)='00001',
	@ptypecategoryid    VARCHAR(MAX )     --商品类别ID	
)
--@encode$--
AS
 SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))

IF @Btypeid='00000'
	SET @Btypeid=''

if @ptypeid='00000' or @ptypeid=''
	INSERT INTO #Ptype(typeid) select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a
else
	INSERT INTO #Ptype(typeid) select a.typeid from  F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid)  a, (select * from  dbo.f_split(@ptypeid,',')) b where left(a.typeid,len(b.a))=b.a

if @Btypeid=''
	INSERT INTO #Btype(typeid) select a.typeid from F_GetManDetailBType(@OperatorID) a
else
	INSERT INTO #Btype(typeid) select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@btypeid,',')) b where left(a.typeid,len(b.a))=b.a

IF @stypeid<>'' OR @MStypeid='-99999' 
   INSERT INTO #stype SELECT TypeId FROM  F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)  


--SELECT  * FROM #Btype
--SELECT  * FROM  #Btype
--SELECT  * FROM  #Stype



DECLARE @SQL 		varchar(8000)

set @SQL=' SELECT 
			    IniQty=isnull(sum(isnull(i.qty,0)),0),
			    IniTotal=isnull(sum(isnull(I.total,0)),0),
				IniCostTotal=isnull(sum(isnull(I.CostTotal,0)),0),
				IniNqty = ISNULL(SUM(ISNULL(a.nqty,0)),0)
				FROM IniCommissionStock I 
				INNER JOIN (SELECT SUM(Nqty) as nqty,btypeid,ptypeid,stypeid from IniCommissionStock_Qty WHERE Type='+ Convert(varchar(20),@type)+' GROUP BY btypeid,ptypeid,stypeid ) A  --,ItemID,Iscombined,GoodsNumber
					ON I.Ptypeid = a.ptypeid AND I.Btypeid= A.btypeid AND I.Stypeid = A.Stypeid
				INNER JOIN #Ptype  P ON I.Ptypeid=p.TypeID
				INNER JOIN #Btype  B ON I.Btypeid=B.TypeID '

IF @stypeid<>'' OR @MStypeid='-99999' 		
set @SQL=@SQL+' INNER JOIN #Stype  S ON I.Stypeid=S.TypeID '
set @SQL=@SQL+' WHERE Type='+ Convert(varchar(20),@type)
exec(@SQL)
PRINT @SQL
DROP TABLE #Ptype
DROP TABLE #Btype
DROP TABLE #Stype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE  id=OBJECT_ID(N'[dbo].[Web_getCurrencyAll]') AND OBJECTPROPERTY(id,N'IsProcedure')=1 ) 
   DROP PROCEDURE [dbo].[Web_getCurrencyAll]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- =============================================
-- Author:		彭勇	
-- Create date: 2012-04-01
-- Description:	获取币种信息
-- =============================================
CREATE PROCEDURE [dbo].[Web_getCurrencyAll]
(
	 @Deleted INT --是否删除
 )
 --@encode$--
AS 
DECLARE @SQL VARCHAR(4000)='
	SELECT
	   CId,
	   UserCode,
	   FullName,
	   Rate,
	   BasisType,
	   BasisType1 = CASE 
	   WHEN
	   BasisType=0 
	   THEN ''原币 × 汇率 = 本位币''
	   ELSE ''原币 ÷ 汇率 = 本位币''
	   END,
	   PyCode,
	   Deleted,
	   Sysrow,
	   dbo.Fn_GetIsUse_Items(CId,1) isuse
	FROM dbo.Ac_Currency 
	WHERE 1=1'
IF(@Deleted=0)
	SET @SQL+='	AND Deleted=0'
	
SET @SQL+='	ORDER BY UserCode'

EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetCustomControlList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetCustomControlList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：Awu
	日期：2015-10-09
	描述：自定义配置读取
*/
CREATE PROCEDURE Web_GetCustomControlList
(
	@BillType INT	--单据类型
)
--@encode$--
AS
SET NOCOUNT ON

SELECT BillType,ColumnName,CustomColumnId,Label,IsVisible,IsRequired,ColumnType 
FROM dbo.Custom_Column_BillIndex T1
	INNER JOIN Custom_Column T2 ON T1.CustomColumnId = T2.id
WHERE BillType = @BillType AND IsVisible = 1

SELECT BillType,ColumnName,CustomColumnId,Label,IsVisible,IsRequired,ColumnType,InOut
FROM dbo.Custom_Column_BillDetail T1
	INNER JOIN Custom_Column T2 ON T1.CustomColumnId = T2.id
WHERE BillType = @BillType AND IsVisible = 1

SELECT BillType,T1.CustomDisColumnId,DataField,BaseInfo,Label
FROM dbo.Custom_DisplayColumn_BillIndex T1
	INNER JOIN dbo.Custom_DisplayColumn T2 ON T1.CustomDisColumnId = T2.id
WHERE BillType = @BillType AND IsVisible = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetDepartmentInformationByID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_GetDepartmentInformationByID
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-指定ID部门转移详细信息
-- 时间：2013-05-24
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_GetDepartmentInformationByID
(
	@ID			INT,		--部门转移表ID
	@OperatorID VARCHAR(50)	--操作员ID
)
--@encode$--

AS
SET NOCOUNT ON 

--多级权限标准显示格式 date:2014-11-14 【9.5/3.5.1】
DECLARE @STypeId VARCHAR(50)=''--分支机构
SELECT @STypeId=S.VerifyID 
FROM Ac_AssetsModifyRecords AD
INNER JOIN Ac_AssetsCards AC ON AC.Id=AD.CardId
INNER JOIN SType S ON S.TypeId=AC.STypeId AND AD.Id=@ID

SELECT 
	AD.Id,
	AD.CardId cid,
	AD.CardId,
	AC.STypeId,
	S.FullName stypefullname,
	AC.UserCode,
	AC.FullName,
	AD.OldDTypeId,
	D.FullName OldDtypeFullName,
	AD.OldLocationId,
	L.Location OldLocationFullName,
	AD.OldDisATypeId,
	CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE A.FullName END OldDisAtypeFullName,
	AD.DTypeId,
	D1.FullName DtypeFullName,
	AD.LocationId,
	L1.Location LocationFullName,
	AD.DisATypeId,
	CASE WHEN ISNULL(F1.TypeId,'')='' THEN '****' ELSE A1.FullName END DisAtypeFullName,
	AD.BusinessDate,
	pv.VoucherId
FROM Ac_AssetsModifyRecords AD 
LEFT JOIN Ac_Provision_Voucher pv ON pv.SourceType=2 AND pv.SourceId=AD.Id
INNER JOIN Ac_AssetsCards AC ON AC.Id=AD.CardId
INNER JOIN SType S ON S.TypeId=AC.STypeId
INNER JOIN Department D ON D.typeid=AD.OldDTypeId
LEFT JOIN Ac_AssetStorageLocation L ON L.Id=AD.OldLocationId
LEFT JOIN Ac_Account A ON A.TypeId=AD.OldDisATypeId AND A.StypeId=@STypeId
LEFT JOIN F_LineAccount(@OperatorID,@STypeId) F ON F.Typeid=A.TypeId AND F.Stypeid=A.StypeId
INNER JOIN Department D1 ON D1.typeid=AD.DTypeid
LEFT JOIN Ac_AssetStorageLocation L1 ON L1.Id=AD.LocationId
LEFT JOIN Ac_Account A1 ON A1.TypeId=AD.DisATypeId AND A1.StypeId=@STypeId
LEFT JOIN F_LineAccount(@OperatorID,@STypeId) F1 ON F1.Typeid=A1.TypeId AND F1.Stypeid=A1.StypeId
WHERE AD.Id=@ID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetDraftAcVoucherBillData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetDraftAcVoucherBillData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-05-23
	描述：获取未记账凭证数据
	EXEC Web_GetDraftAcVoucherBillData
*/
CREATE PROCEDURE Web_GetDraftAcVoucherBillData
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Cid INT

--获取本币ID
SELECT	TOP 1 
		@Cid = Cid
FROM	Ac_Currency
WHERE	Sysrow = 1

--本币，原币金额
SELECT	B.STypeId,
		B.ATypeId,
		FDebit = SUM(
						CASE 
							WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) <> 0 THEN ISNULL(B.FDebitTotal,0)
							WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) = 0 THEN  -1*ISNULL(B.FCreditTotal,0)
							ELSE 0
						END
					),
		FDebitFor = SUM(
						CASE 
							WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) <> 0 THEN ISNULL(B.FDebitTotalFor,0) 							
							WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) = 0  THEN -1*ISNULL(B.FCreditTotalFor,0)							
							ELSE 0 
						END
					   ),
		FCredit = SUM(
						CASE 
							WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) <> 0 THEN ISNULL(B.FCreditTotal,0)
							WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) = 0  THEN -1*ISNULL(B.FDebitTotal,0)
							ELSE 0
						END
					 ),
		FCreditFor = SUM(
						CASE 
							WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) <> 0 THEN ISNULL(B.FCreditTotalFor,0)
							WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) = 0  THEN -1*ISNULL(B.FDebitTotalFor,0)							
							ELSE 0 
						END
						),		
		B.Cid,
		B.FYear,
		B.FPeriod
FROM	Ac_Voucher_Bill B
INNER JOIN Ac_Voucher V ON B.BillNumberId = V.BillNumberId
WHERE	V.IfCheck = 'f'	
		AND V.FChecked <> -1	
GROUP BY B.STypeId,
		 B.ATypeId,
		 B.Cid,
		 B.FYear,
		 B.FPeriod
UNION ALL		 
--本币、原币对应的综合本位币
SELECT	B.STypeId,
		B.ATypeId,
		FDebit = SUM(
						CASE 
							WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) <> 0 THEN ISNULL(B.FDebitTotal,0)
							WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) = 0 THEN  -1*ISNULL(B.FCreditTotal,0)
							ELSE 0
						END
					),
		FDebitFor = SUM(
						CASE 
							WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) <> 0 THEN ISNULL(B.FDebitTotalFor,0) 							
							WHEN B.FDc = 1  AND ISNULL(B.FDebitTotal,0) = 0  THEN -1*ISNULL(B.FCreditTotalFor,0)														
							ELSE 0 
						END
						),
		FCredit = SUM(
						CASE 
							WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) <> 0 THEN ISNULL(B.FCreditTotal,0)
							WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) = 0  THEN -1*ISNULL(B.FDebitTotal,0)
							ELSE 0
						END
					 ),
		FCreditFor = SUM(
						CASE 
							WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) <> 0 THEN ISNULL(B.FCreditTotalFor,0)
							WHEN B.FDc = -1 AND ISNULL(B.FCreditTotal,0) = 0  THEN -1*ISNULL(B.FDebitTotalFor,0)							
							ELSE 0 
						END
						),	
		0 AS Cid,
		B.FYear,
		B.FPeriod
FROM	Ac_Voucher_Bill B
INNER JOIN Ac_Voucher V ON B.BillNumberId = V.BillNumberId
WHERE	V.IfCheck = 'f'		
		AND V.FChecked <> -1
GROUP BY B.STypeId,
		 B.ATypeId,
		 B.Cid,
		 B.FYear,
		 B.FPeriod

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_GetDraftAssistantAccountData]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_GetDraftAssistantAccountData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：俞俊杰
	日期：2012-06-06
	描述：获取未记账凭证的辅助核算数据
	EXEC Web_GetDraftAssistantAccountData
*/
CREATE PROCEDURE Web_GetDraftAssistantAccountData
--@encode$--
AS 
    SET NOCOUNT ON
---单币别本位币与外币
    SELECT  STypeId,    --分支机构ID
            ATypeId,	--科目ID
            TypeId,		--辅助核算明细ID
            typeName,	--辅助核算项目
            CASE WHEN Fdc = 1 THEN SUM(ISNULL(debit, 0) - ISNULL(credit, 0))
                 WHEN Fdc = -1 THEN SUM(ISNULL(credit, 0) - ISNULL(debit, 0))
            END AS AssistantAccount,		--辅助核算本位币
            CASE WHEN Fdc = 1
                 THEN SUM(ISNULL(debitFor, 0) - ISNULL(creditFor, 0))
                 WHEN Fdc = -1
                 THEN SUM(ISNULL(creditFor, 0) - ISNULL(debitFor, 0))
            END AS AssistantAccountFor,		--辅助核算原币
            Cid,		--币别ID
            FYear,		--年度
            FPeriod		--期间
    FROM    ( SELECT    t1.STypeId,
                        t1.ATypeId,
                        t3.TypeId,
                        t3.typeName,
                        t1.FDebitTotalFor AS debitFor,
                        t1.FDebitTotal AS debit,
                        t1.FCreditTotal AS credit,
                        t1.FCreditTotalFor AS creditFor,
                        t1.Cid,
                        t1.FYear,
                        t1.FPeriod,
                        t4.fdc
              FROM      Ac_Voucher_Bill t1
                        INNER JOIN Ac_Voucher t2 ON t2.BillNumberId = t1.BillNumberId
                        INNER JOIN Ac_Voucher_Bill_Assist_CheckItems t3 ON t1.ID = t3.vBId
                        INNER JOIN dbo.Ac_Account t4 ON t1.stypeid = t4.stypeid
                                                        AND t1.atypeid = t4.typeid
              WHERE     t2.IfCheck = 'f'
            ) AS a
    GROUP BY STypeId,
            ATypeId,
            TypeId,
            typeName,
            fdc,
            cid,
            FYear,
            FPeriod
    UNION ALL
----所有币别的本位币
    SELECT  STypeId,
            ATypeId,
            TypeId,
            typeName,
            SUM(AssistantAccount),
            0 AS AssistantAccountFor,
            0 AS cid,
            FYear,
            FPeriod
    FROM    ( SELECT    STypeId,
                        ATypeId,
                        TypeId,
                        typeName,
                        CASE WHEN Fdc = 1
                             THEN SUM(ISNULL(debit, 0) - ISNULL(credit, 0))
                             WHEN Fdc = -1
                             THEN SUM(ISNULL(credit, 0) - ISNULL(debit, 0))
                        END AS AssistantAccount,
                        CASE WHEN Fdc = 1
                             THEN SUM(ISNULL(debitFor, 0) - ISNULL(creditFor, 0))
                             WHEN Fdc = -1
                             THEN SUM(ISNULL(creditFor, 0) - ISNULL(debitFor, 0))
                        END AS AssistantAccountFor,
                        Cid,
                        FYear,
                        FPeriod
              FROM      ( SELECT    t1.STypeId,
                                    t1.ATypeId,
                                    t3.TypeId,
                                    t3.typeName,
                                    t1.FDebitTotalFor AS debitFor,
                                    t1.FDebitTotal AS debit,
                                    t1.FCreditTotal AS credit,
                                    t1.FCreditTotalFor AS creditFor,
                                    t1.Cid,
                                    t1.FYear,
                                    t1.FPeriod,
                                    t4.fdc
                          FROM      Ac_Voucher_Bill t1
                                    INNER JOIN Ac_Voucher t2 ON t2.BillNumberId = t1.BillNumberId
                                    INNER JOIN Ac_Voucher_Bill_Assist_CheckItems t3 ON t1.ID = t3.vBId
                                    INNER JOIN dbo.Ac_Account t4 ON t1.stypeid = t4.stypeid
                                                                    AND t1.atypeid = t4.typeid
                          WHERE     t2.IfCheck = 'f'
                        ) AS a
              GROUP BY  STypeId,
                        ATypeId,
                        TypeId,
                        typeName,
                        fdc,
                        cid,
                        FYear,
                        FPeriod
            ) AS b
    GROUP BY STypeId,
            ATypeId,
            TypeId,
            typeName,
            FYear,
            FPeriod

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetEmployeeInfoForPriceRule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetEmployeeInfoForPriceRule]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则的价格表选择
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetEmployeeInfoForPriceRule
(
	@filterstr varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 
 declare @sql varchar(max);
 set @sql=' select UserCode as dousercode,FullName as dousername,a.etypeid as douserid from loginuser a inner  join employee  b on a.etypeid=b.typeId where 1=1 '
if(ISNULL(@filterstr,'')<>'')
set @sql=@sql+'and( UserCode like ''%'+@filterstr+'%'' or FullName like ''%'+@filterstr+'%'' )   '

exec(@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetFactGoodsStocksQTY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetFactGoodsStocksQTY]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--查询实物库存数量
CREATE	PROCEDURE Web_GetFactGoodsStocksQTY
(
    @PTypeID			VARCHAR(50),		--商品ID
	@KTypeID			VARCHAR(50),		--仓库ID	
	@ItemID				INT,				--自由项ID
	@GoodsNumber		VARCHAR(100),		--批号	
	@CargoID			INT=0,				--货位ID
	@IfUseCargo         INT=0,				--是否启用货位:1启用，0未启用
	@ifcommission		INT=0,				--是否是受托委托单据
	@producedate		VARCHAR(50)='',		--生产日期
	@validdate			VARCHAR(50)='',		--效期至
	@isSelectedGoodsNo  VARCHAR(3)='0'
)
AS

IF @IfUseCargo=1 AND @CargoID=0
BEGIN
    SELECT 0 AS factQty;
END
ELSE 
BEGIN

Declare @costing int 

SELECT @costing=subvalue FROM sysdata where subname='costing';

		DECLARE @SQL NVARCHAR(max);
		
		SET @SQL = ' SELECT CAST(ISNULL(SUM(a.Qty),0) AS  NUMERIC(24, 10) ) as factqty
						          FROM  FactStocks_Qty a 
						          WHERE  a.KTypeID=@KTypeID AND a.PTypeID=@PTypeID';
 						          
         IF  @CargoID <> 0	
        BEGIN
            SET @SQL = @SQL + ' AND a.CargoID=' + CAST(@CargoID AS VARCHAR)
        END 			
		IF  @ItemID <> 0	
		BEGIN
		    SET @SQL = @SQL + ' AND a.ItemID=' + CAST(@ItemID AS VARCHAR)
		END			
      
        IF  @GoodsNumber <> ''	
		BEGIN
			SET @SQL = @SQL + ' AND a.GoodsNumber=''' + @GoodsNumber + ''''
			SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''	
			SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
		END		
		ELSE IF @isSelectedGoodsNo = '1'
		BEGIN
			IF @costing = '3'
			BEGIN
				IF @producedate<>''
					SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''	
				IF @validdate<>''
					SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
			END
			ELSE
			BEGIN
				SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''	
				SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
			END
		END
		ELSE
		BEGIN
			IF  @producedate <> ''
			    SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''
			    	
			IF  @validdate <> ''
			    SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
		END  
		
		SET @SQL = @SQL + ' GROUP BY a.KTypeID,a.PTypeID';		
		
		IF  @CargoID <> 0	
		     SET @SQL = @SQL + ',a.CargoID'
		     
		IF  @ItemID <> 0	
		     SET @SQL = @SQL + ',a.ItemID'
		     
		IF  @GoodsNumber <> ''	
		BEGIN
			SET @SQL = @SQL + ',a.GoodsNumber'
		END
		
		IF  @producedate <> ''
		    SET @SQL = @SQL + ',a.producedate'	
		IF @validdate <> ''
		    SET @SQL = @SQL + ',a.validdate'

		
		--PRINT @SQL
		EXEC sp_executesql @SQL ,N'@KTypeID VARCHAR(50),@PTypeID VARCHAR(50)', @KTypeID,@PTypeID
END


--EXEC Web_GetFactGoodsStocksQTY '00001000010000100001000010000100001000010000100001'
--,'00001000010000100001000010000100001000010000100001',0,'',28,1,0,'','',1
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetFactPrintCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetFactPrintCount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	修改者：韩林
	日期：2012-02-01
	描述：连续打印查询明细
*/

CREATE PROCEDURE Web_GetFactPrintCount
(
	@billnumberids varchar(max),
	@operatorid varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON
	
SELECT	SUM(A.PrintCount) AS printcount,
		ISNULL(SUM(AC.addprintcount),0) AS addprintcount,
		A.billnumberid,
		B.BillCode 
FROM	PrintRecord A
INNER JOIN FactIndex B ON A.BillNumberId=B.BillNumberId AND a.BillType=b.BillType
LEFT JOIN AddPrintCountRecord AC ON a.BillNumberId=ac.BillNumberId AND AC.BillType=A.BillType  AND ac.etypeid=@operatorid
WHERE a.BillNumberId IN (select * from f_split(@billnumberids,','))
GROUP BY A.billnumberid,B.BillCode
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetFaPiaoOtherTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetFaPiaoOtherTotal]
GO




/*
	作者：王刚
	日期：2011-11-14
	描述：发票其他费用合计,开票金额合计
*/
CREATE  PROCEDURE Web_GetFaPiaoOtherTotal
(
	@OperatorId		varchar(50),	--操作员ID
	@PTypeId		varchar(1550),	--商品ID
	@ETypeId		varchar(1550),	--职员ID
	@BTypeId		varchar(1550),	--往来单位ID
	@KTypeId		varchar(1550),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@Comment		varchar(300)='',--备注
	@BillType		varchar(100),	--单据类型
	@STypeId		varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------
DECLARE @SQL 		varchar(8000)

CREATE TABLE #FaPiaoId
(
	BillNumberId	numeric(18,0),
	BTypeId			varchar(100)
)

CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype 
(
	TypeID varchar(50),
	UserCode varchar(200),
	fullname varchar(200)
)
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))

IF @PTypeID =''
	INSERT INTO #Ptype(typeid) 
		select typeid 
		from F_GetManDetailPType(@OperatorID)
ELSE
	INSERT INTO #Ptype(typeid) 
		select a.typeid 
		from F_GetManDetailPType(@OperatorID) a, 
			(select a from  dbo.f_split(@PTypeID,',')) b 
		where left(a.typeid,len(b.a))=b.a


IF @BTypeID =''
	INSERT INTO #Btype(typeid,usercode,fullname) 
		select typeid,usercode,fullname 
		from btype 
		where typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
ELSE
	INSERT INTO #Btype(typeid,usercode,fullname) 
		select typeid,usercode,fullname 
		from btype 
		where typeid in ( 
							select a.typeid 
							from F_GetManDetailBType(@OperatorID) a, 
								(select a from  dbo.f_split(@BTypeID,',')) b 
							where left(a.typeid,len(b.a))=b.a
						)
						
IF @ETypeID=''
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
ELSE
	INSERT INTO #Etype 
		select a.typeid 
		from F_GetManDetailEType(@OperatorID) a, 
			(select a from  dbo.f_split(@ETypeID,',')) b 
		where left(a.typeid,len(b.a))=b.a
		
--仓库
INSERT INTO #Ktype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeID,4,@OperatorID)		

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #Ktype WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END

IF @KTypeID = ''	
	insert into #Ktype select '10000'	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	


SET @SQL = '
	INSERT INTO #FaPiaoId(BillNumberId)
	SELECT  DISTINCT B.BillNumberId			
	FROM	(
				SELECT 	I.BillNumberId						
				FROM 	InOutStockTable I
				INNER JOIN #GetManDTypeId D ON D.TypeId = I.DTypeId '
IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL =@SQL+' INNER JOIN #Btype ON I.Btypeid=#Btype.typeid '

IF NOT (@ETypeId= '' AND @METypeId = '00001')
	SET @SQL =@SQL+' INNER JOIN #Etype ON I.Etypeid=#Etype.typeid '

IF NOT (@KTypeId = '' AND @MKTypeId = '00000')
	SET @SQL =@SQL+' INNER JOIN #Ktype ON I.Ktypeid=#Ktype.typeid '

IF NOT (@PTypeId='' AND @MPTypeId='00000')
	SET @SQL=@SQL+' INNER JOIN #Ptype ON I.Ptypeid=#Ptype.typeid'

IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON I.STypeId = S.TypeId '		

SET @SQL=@SQL+'			,
						BillIndex Bil
				WHERE	Bil.BillNumberId = I.BillNumberId
						AND I.Audited = 1 
						AND I.BillType <> 178
						AND I.BillType <> 195
						AND I.BillType IN ('+@BillType+')
						AND I.BillDate>='''+@StartDate+'''
						AND I.BillDate<='''+@EndDate+'''
						AND Bil.Comment LIKE ''%'+@Comment+'%''
				GROUP BY	I.BillNumberId '
	
SET @SQL = @SQL + '
		--178
		UNION ALL
		SELECT	B.BillNumberId
		FROM	Billindex_CarRepair BC
		INNER JOIN	BillIndex B ON B.BillNumberId = BC.BillNumberId
		LEFT JOIN	QP_QuickRepairBill_PType Q ON Q.BillNumberId = BC.BillNumberId
		INNER JOIN	#GetManDTypeId D ON D.TypeId = B.DTypeId '
					
			IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SET @SQL =@SQL+' INNER JOIN #Btype ON B.Btypeid=#Btype.typeid '
			
			IF NOT (@ETypeId= '' AND @METypeId = '00001')
				SET @SQL =@SQL+' INNER JOIN #Etype ON B.Etypeid=#Etype.typeid '
			
			IF NOT (@KTypeId = '' AND @MKTypeId = '00000')
				SET @SQL =@SQL+' INNER JOIN #Ktype ON B.Ktypeid=#Ktype.typeid '
	
			IF NOT (@PTypeId='' AND @MPTypeId='00000')
				SET @SQL=@SQL+'  LEFT JOIN #Ptype ON Q.Ptypeid=#Ptype.typeid'
				
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '	
					
			SET @SQL += '
					WHERE	BC.BillType = 178 
							AND B.BillType IN ('+@BillType+')
							AND B.RedWord = 0
							AND B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
							AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
							AND B.Comment LIKE '+char(39)+'%'+@Comment+'%'+char(39)+'
							AND B.ifcheck = ''t''
							AND B.draft = 0
							AND B.ifYearBill= 0     --年节存标志
						'
	
SET @SQL= @SQL+ '
		--195
		UNION ALL
		SELECT	BC.BillNumberId
		FROM Billindex_CarRepair BC
		INNER JOIN BillIndex B ON B.BillNumberId = BC.BillNumberId
		LEFT JOIN (
						SELECT	F.ReceptionBillnumberId,
								F.PTypeID,
								F.Qty,
								F.DiscountTotal,
								B.ktypeid
						FROM	Qp_ReceptionBill_FactUsePType F
						INNER JOIN	BillIndex B ON B.BillNumberId = F.ReceptionBillnumberId
					) Q ON Q.ReceptionBillnumberId = BC.BillNumberId
		INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId '	
					
			IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SET @SQL =@SQL+' INNER JOIN #Btype ON B.Btypeid=#Btype.typeid '
			
			IF NOT (@ETypeId= '' AND @METypeId = '00001')
				SET @SQL =@SQL+' INNER JOIN #Etype ON B.Etypeid=#Etype.typeid '
			
			IF NOT (@KTypeId = '' AND @MKTypeId = '00000')
				SET @SQL =@SQL+' INNER JOIN #Ktype ON Q.Ktypeid=#Ktype.typeid '
	
			IF NOT (@PTypeId='' AND @MPTypeId='00000')
				SET @SQL=@SQL+'  INNER JOIN #Ptype ON Q.Ptypeid=#Ptype.typeid'
				
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '
				
			SET @SQL += '
					WHERE	BC.BillType = 195
							AND B.BillType IN ('+@BillType+')
							AND BC.BillState = 4
							AND B.RedWord = 0
							AND B.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
							AND B.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
							AND B.Comment LIKE '+char(39)+'%'+@Comment+'%'+char(39)+'
							AND B.ifcheck = ''t''
							AND B.draft = 0
					GROUP BY	BC.BillNumberId  	
	)B'

--PRINT(@SQL)
EXEC(@SQL)

SELECT	CONVERT( NUMERIC(24, 10) ,ISNULL(SUM(A.kaipiaototal),0)) AS kaipiaototal,
		CONVERT( NUMERIC(24, 10) ,ISNULL(SUM(A.total),0)) AS total
FROM (
		SELECT	B.BillNumberId,
				Q.MainBillNumberID,
				CONVERT( NUMERIC(24, 10) , ISNULL(Q.Total,0)) AS kaipiaototal,
				0 AS total
		FROM Billindex_CarRepair B
		LEFT JOIN 	(
						SELECT	MainBillNumberID,
								Total
						FROM	QP_InvoiceOtherTotalDetails
						WHERE	@KTypeId = '' 
								AND @PTypeId = ''
								AND MainBillNumberID IN (SELECT DISTINCT BillNumberId FROM #FaPiaoId)
						UNION ALL
						SELECT	Q.MainBillNumberID,
								Q.Total
						FROM	QP_InvoiceOtherTotalDetails Q
						INNER JOIN	FaPiaoBill F ON F.BillNumberID = Q.BillNumberID
						WHERE	(@PTypeId <> '' OR @KTypeId <> '')
					) Q ON Q.MainBillNumberID = B.BillNumberId
		WHERE	B.BillType IN (178,195,196)
				AND B.BillNumberId IN (SELECT DISTINCT BillNumberId FROM #FaPiaoId)	
		UNION ALL
		SELECT	DISTINCT
				B.BillNumberId,
				Q.MainBillNumberID,
				0 AS kaipiaototal,
				(B.OtherTotal + B.EpibolyTotal) AS total
		FROM Billindex_CarRepair B
		LEFT JOIN 	(
						SELECT	MainBillNumberID,
								Total
						FROM	QP_InvoiceOtherTotalDetails
						WHERE	MainBillNumberID IN (SELECT DISTINCT BillNumberId FROM #FaPiaoId)
					) Q ON Q.MainBillNumberID = B.BillNumberId
		WHERE	B.BillType IN (178,195,196)
				AND B.BillNumberId IN (SELECT DISTINCT BillNumberId FROM #FaPiaoId)
	) A 
		
DROP TABLE #Ptype, #Btype, #Etype, #Ktype, #GetManSTypeId, #GetManDTypeId, #FaPiaoId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetFeeType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetFeeType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-15
	描述：取得费用信息
*/
CREATE PROCEDURE [dbo].[Web_GetFeeType]
(
	@filter varchar(50)=''
)	
--@encode$--
AS
SET NOCOUNT ON;
	DECLARE @sql varchar(1000)
	DECLARE @WHERE_SQL VARCHAR(500)=''
	SET NOCOUNT ON;
	IF @filter<>'' SET @WHERE_SQL=' WHERE fullname LIKE ''%' + @filter + '%'''+' OR usercode LIKE ''%' + @filter + '%'''
	SET @sql='select feetypeid,usercode,fullname,comment from CM_FeeType'+@WHERE_SQL+' order by usercode asc'
	EXEC(@sql)

	-- 操作返回值
	IF @@ROWCOUNT = 0
		RETURN -1	-- 失败
	ELSE
		RETURN 0	-- 成功

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetFixedCardIndexInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetFixedCardIndexInfo]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 作者：	黄清
-- 时间：	2013-05-21
-- 描述：	固定资产卡片主表信息查询

-- 修改：Hqing 增加会计科目多级权限控制
-- ========================================================================
CREATE         PROCEDURE Web_GetFixedCardIndexInfo
(
	@cardid		VARCHAR(50),
	@OperatorId VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON 

BEGIN--处理会计科目多级权限
	DECLARE @STYPEID VARCHAR(50)
	SELECT @STYPEID=STYPEID FROM Ac_AssetsCards WHERE ID=@cardid
	
	SELECT @STYPEID=VerifyID FROM SType WHERE TypeId=@STYPEID
	
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200))
	INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName) 
	SELECT L.Typeid,L.Stypeid,A.FullName FROM F_LineAccount(@OperatorID,@STYPEID) L
	INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId

	--处理会计科目为空的情况 在权限表里写入空记录
	INSERT INTO #Ac_Account_L(Typeid,StypeId,FullName) VALUES('',@STYPEID,'')
END;


SELECT	a.Id,
		A.UserCode,
		A.FullName,
		a.STypeId,
		S.FullName AS sfullname,
		AssertATypeId,
		ISNULL(ass.FullName,'****') assertfullname,
		DepATypeId,
		ISNULL(dep.FullName,'****') depfullname,
		DisATypeId,
		ISNULL(dis.FullName,'****') disfullname,
		DevalueATypeId,
		ISNULL(dev.FullName,'****') devaluefullname,
		CategoryId,
		(SELECT FullName FROM Ac_AssetsCategory WHERE id=CategoryId) AS categoryfullname,
		LocationId,
		(SELECT Location FROM Ac_AssetStorageLocation WHERE id=LocationId) AS locationfullname,
		ConditionId,
		(SELECT Comment FROM Ac_AssetWorkingCondition WHERE id=ConditionId) AS conditionfullname,
		Size,
		a.DTypeid,
		D.FullName AS dfullname,
		InAccountDate,
		BusinessTypeId,
		(SELECT FullName FROM Ac_AssetBusinessType WHERE id=BusinessTypeId) AS businesstypefullname,
		Total,
		A.Cid,
		C.FullName AS cfullname,
		C.Sysrow AS sysrow,
		F_Total as ftotal,
		A.Rate,
		DepTotal,
		DevalueReady,
		NetValue,
		NetSalvage,
		NetSalvageRate,
		DepreciationMean,
		DurYear,
		durmonth,
		DepreciationMonth,
		A.Comment,
		AssetsState,
		acs.Comment AS assetsstatename,
		a.Units,
		a.operationdate,
		E.FullName AS efullname,
		a.barcode,
		a.Qty,
		a.expectwork,
		a.finishwork,
		a.workunit,
		c.BasisType,
		CASE WHEN S.IfAssetsIni=0 THEN 1 ELSE 0 END ini
FROM Ac_AssetsCards A
INNER JOIN SType S ON S.TypeId=A.STypeId
INNER JOIN Department d ON D.typeid=A.DTypeid
INNER JOIN Ac_Currency C ON C.CId=A.Cid
INNER JOIN employee E ON A.ETypeId=E.typeId
INNER JOIN Ac_AssetsCardsState acs on acs.Id=a.AssetsState
LEFT JOIN #Ac_Account_L dep ON dep.TypeId=A.DepATypeId  
LEFT JOIN #Ac_Account_L dis ON dis.TypeId=A.DisATypeId
LEFT JOIN #Ac_Account_L ass ON ass.TypeId=A.AssertATypeId 
LEFT JOIN #Ac_Account_L dev ON dev.TypeId=A.DevalueATypeId

WHERE a.Id=@cardid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetFundAccountIsRed]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_GetFundAccountIsRed]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- date:	2016-05-10
-- by：		GLJ
-- function：账务期初及凭证保存时现金银行科目出现赤字：【现金、银行存款、其他货币资金】三类科目当前余额（科目当前期间余额表余额+当前所有未记账凭证）都必须≥0，否则提示：【XX】科目余额已经出现赤字，无法启用此配置！
-- ========================================================================
CREATE PROCEDURE Web_GetFundAccountIsRed
(
	@Type			INT,			--1：系统配置 2:凭证
	@BillNumberId	VARCHAR(MAX)	--凭证ID
)
--@encode$--
AS
SET NOCOUNT ON

--获取所有赤字科目名称
DECLARE @FullName VARCHAR(MAX)=''
	
CREATE TABLE #ResultTable
(
	STypeID		VARCHAR(50),
	TypeID		VARCHAR(50),
	FullName	VARCHAR(100),
	Total		NUMERIC(22,2) NOT NULL DEFAULT(0)
)
--系统配置判断
IF(@Type=1)
	BEGIN
		INSERT INTO #ResultTable(STypeID,TypeID,FullName,Total)
		SELECT
			STypeID,
			TypeID, 
			FullName,
			SUM(Total) Total
		FROM 
		(
			SELECT
				I.STypeID,
				I.ATypeId TypeID,
				A.FullName,
				SUM(I.iniTotal) Total
			FROM Ac_IniAccount I
			INNER JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=I.STypeId AND PS.IsUse=0
			INNER JOIN Ac_Account A ON A.StypeId=I.STypeId AND A.TypeId=I.ATypeId AND (IsCash=1 OR IsBank=1 OR IsOther=1) AND SonNum=0
			GROUP BY I.ATypeId,A.FullName,I.STypeId	
			
			UNION ALL

			SELECT
				T.STypeId,
				T.ATypeId TypeID,
				A.FullName,
				SUM(T.FEndBalance) Total
			FROM Ac_Balance T
			INNER JOIN Ac_AccountsPeroid_Stype P ON P.Stypeid=T.STypeId  AND P.FYear=T.FYear AND P.FPeriod=T.FPeriod AND T.Cid=0
			INNER JOIN Ac_Account A ON A.StypeId=T.STypeId AND A.TypeId=T.ATypeId AND (IsCash=1 OR IsBank=1 OR IsOther=1) AND SonNum=0
			GROUP BY T.ATypeId,A.FullName,T.STypeId
				
			UNION ALL
				
			SELECT
				V.STypeId,
				T.ATypeId TypeID,
				A.FullName,
				SUM(CASE WHEN A.Fdc=1 THEN T.FDebitTotal-T.FCreditTotal ELSE T.FCreditTotal-T.FDebitTotal END) Total
			FROM Ac_Voucher V
			INNER JOIN Ac_Voucher_Bill T ON T.BillNumberId=V.BillNumberId AND V.IfCheck='F'
			INNER JOIN Ac_Account A ON A.StypeId=T.STypeId AND A.TypeId=T.ATypeId AND (IsCash=1 OR IsBank=1 OR IsOther=1) AND SonNum=0	
			GROUP BY 
				V.STypeId,
				T.ATypeId,
				A.FullName,
				A.Fdc
		) F	
		GROUP BY 
			STypeId,
			TypeID,
			FullName
	END
ELSE --凭证判断
	BEGIN
		--选中凭证的现金科目
		CREATE TABLE #AccountTemp
		(
			STypeID		VARCHAR(50),
			ATypeID		VARCHAR(50),
			FullName	VARCHAR(100),
			Fdc			INT
		)
		INSERT INTO #AccountTemp(STypeID,ATypeID,FullName,Fdc)
		SELECT
			B.STypeId,
			B.ATypeId,
			A.FullName,
			A.Fdc
		FROM Ac_Voucher_Bill B
		INNER JOIN f_split(@BillNumberId,',') F ON F.a=B.BillNumberId
		INNER JOIN Ac_Account A ON A.StypeId=B.STypeId AND A.TypeId=B.ATypeId AND (IsCash=1 OR IsBank=1 OR IsOther=1)
		GROUP BY B.STypeId,B.ATypeId,A.FullName,A.Fdc
		--如果没有现金科目，则不判断金额
		IF EXISTS(SELECT TOP 1 1 FROM #AccountTemp)
			BEGIN
				INSERT INTO #ResultTable(STypeID,TypeID,FullName,Total)
				SELECT
					STypeID,
					ATypeId, 
					FullName,
					SUM(Total) Total
				FROM 
				(
					SELECT
						T.STypeId,
						T.ATypeId,
						A.FullName,
						-SUM(CASE WHEN A.Fdc=1 THEN T.FDebitTotal-T.FCreditTotal ELSE T.FCreditTotal-T.FDebitTotal END) Total
					FROM Ac_Voucher_Bill T 
					INNER JOIN f_split(@BillNumberId,',') F ON F.a=T.BillNumberId
					INNER JOIN #AccountTemp A ON A.StypeId=T.STypeId AND A.ATypeID=T.ATypeId
					GROUP BY 
						T.STypeId,
						T.ATypeId,
						A.FullName
						
					UNION ALL
					
					SELECT
						T.STypeId,
						T.ATypeId,
						A.FullName,
						SUM(T.FEndBalance) Total
					FROM Ac_Balance T
					INNER JOIN #AccountTemp A ON A.StypeId=T.STypeId AND A.ATypeID=T.ATypeId
					INNER JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=T.STypeId AND PS.FYear=T.FYear AND PS.FPeriod=T.FPeriod AND Cid=0
					GROUP BY T.ATypeId,A.FullName,T.STypeId
						
					UNION ALL
						
					SELECT
						V.STypeId,
						T.ATypeId,
						A.FullName,
						SUM(CASE WHEN A.Fdc=1 THEN T.FDebitTotal-T.FCreditTotal ELSE T.FCreditTotal-T.FDebitTotal END) Total
					FROM Ac_Voucher_Bill T 
					INNER JOIN #AccountTemp A ON A.StypeId=T.STypeId AND A.ATypeID=T.ATypeId
					INNER JOIN Ac_Voucher V ON V.BillNumberId=T.BillNumberId AND V.IfCheck='F'
					GROUP BY 
						V.STypeId,
						T.ATypeId,
						A.FullName
				) F 
				GROUP BY 
					STypeId,
					ATypeId,
					FullName
			END
		DROP TABLE #AccountTemp
	END	
--获取出现赤字的现金银行科目
SELECT @FullName+=FullName+',' FROM #ResultTable WHERE Total<0
IF(ISNULL(@FullName,'')<>'')
	SET @FullName=SUBSTRING(@FullName,1,LEN(@FullName)-1)
	
SELECT @FullName

DROP TABLE #ResultTable


go
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetGoodsNumber]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetGoodsNumber]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：刘飞
	日期：2017-09-14
	描述：根据货位，批号，自由项，仓库，商品获取商品库存批号	
*/
CREATE	PROCEDURE	Web_GetGoodsNumber
(
	@PTypeID			VARCHAR(50),		--商品ID
	@KTypeID			VARCHAR(50),		--仓库ID	
	@ItemID				INT,				--自由项ID
	@GoodsNumber		VARCHAR(100),		--批号	
	@CargoID			INT=0,				--货位ID
	@IfUseCargo         INT=0,				--是否启用货位:1启用，0未启用
	@ifwx				INT=0,				--是否是维修 0：否    1：是
	@GoodsCostPrice		VARCHAR(50)='',		--成本价
	@ifcommission		INT=0,				--是否是受托委托单据
	@producedate		VARCHAR(50)='',		--生产日期
	@validdate			VARCHAR(50)='',		--效期至
	@isSelectedGoodsNo  VARCHAR(3)='0'
)
--@encode$--
AS
SET NOCOUNT ON

Declare @costing int 

SELECT @costing=subvalue FROM sysdata where subname='costing'


DECLARE @talbename  VARCHAR(50)
IF @ifwx = 1
	SET @talbename = 'wx_GoodsStocks'
ELSE IF @ifcommission=1
	SET @talbename='CommissionStock_Qty'
ELSE
	SET @talbename = 'GOODSSTOCKS_QTY'
	
IF @IfUseCargo=1 AND @CargoID=0 AND @ifwx = 0
	SELECT 0 as accountqty,0 as saleunitqty,0 as buyunitqty,0 as stockunitqty 
ELSE
	BEGIN			
		DECLARE @SQL NVARCHAR(max)
		
		SET @SQL = '
					SELECT TOP 1 1 AS hasgoodsnumber
					FROM   '+@talbename + ' 
					WHERE PTypeID='''+@PTypeID+''' '
					
		IF @talbename!='CommissionStock_Qty' AND @KTypeID <> ''
		BEGIN
			SET @SQL = @SQL +' 
					AND KTypeID='''+@KTypeID+''' '
		END
					
		IF  @CargoID <> 0	
			SET @SQL = @SQL + ' AND CargoID=' + CAST(@CargoID AS VARCHAR)
		IF  @ItemID <> 0	
			SET @SQL = @SQL + ' AND ItemID=' + CAST(@ItemID AS VARCHAR)
		IF  @ifwx <> 1 AND @GoodsCostPrice <> '' AND CAST(@GoodsCostPrice AS NUMERIC) >= 0 AND @costing<>0 AND @talbename!='CommissionStock_Qty'
			SET @SQL = @SQL + ' AND GoodsCostPrice=' + CAST(@GoodsCostPrice AS VARCHAR)
		IF  @GoodsNumber <> ''	
		BEGIN
			SET @SQL = @SQL + ' AND GoodsNumber=''' + @GoodsNumber + ''''
			SET @SQL = @SQL + ' AND producedate=''' + @producedate + ''''	
			SET @SQL = @SQL + ' AND validdate=''' + @validdate + ''''
		END
		ELSE IF @GoodsCostPrice <> '' AND CAST(@GoodsCostPrice AS NUMERIC) >= 0	
		BEGIN
			SET @SQL = @SQL + ' AND producedate=''' + @producedate + ''''	
			SET @SQL = @SQL + ' AND validdate=''' + @validdate + ''''
		END
		ELSE IF @isSelectedGoodsNo = '1'
		BEGIN
			IF @costing = '3'
			BEGIN
				IF @producedate<>''
					SET @SQL = @SQL + ' AND producedate=''' + @producedate + ''''	
				IF @validdate<>''
					SET @SQL = @SQL + ' AND validdate=''' + @validdate + ''''
			END
			ELSE
			BEGIN
				SET @SQL = @SQL + ' AND producedate=''' + @producedate + ''''	
				SET @SQL = @SQL + ' AND validdate=''' + @validdate + ''''
			END
		END
		ELSE
		BEGIN
			IF  @ifwx <> 1 AND @producedate <> ''
			SET @SQL = @SQL + ' AND producedate=''' + @producedate + ''''	
			IF  @ifwx <> 1 AND @validdate <> ''
			SET @SQL = @SQL + ' AND validdate=''' + @validdate + ''''
		END
		
		--print @sql
		--SELECT @SQL FOR XML PATH('')
		EXEC sp_executesql @SQL
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetGoodsStocksQTY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetGoodsStocksQTY]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王珏
	日期：2012-05-21
	描述：根据货位，批号，自由项，仓库，商品获取账面库存
	----------------------------------------------------------
	OneV 2016-09-18 手工指定法下面，库存不应该关联@GoodsCostPrice
	
*/
CREATE	PROCEDURE	Web_GetGoodsStocksQTY
(
	@PTypeID			VARCHAR(50),		--商品ID
	@KTypeID			VARCHAR(50),		--仓库ID	
	@ItemID				INT,				--自由项ID
	@GoodsNumber		VARCHAR(100),		--批号	
	@CargoID			INT=0,				--货位ID
	@IfUseCargo         INT=0,				--是否启用货位:1启用，0未启用
	@ifwx				INT=0,				--是否是维修 0：否    1：是
	@GoodsCostPrice		VARCHAR(50)='',		--成本价
	@ifcommission		INT=0,				--是否是受托委托单据
	@producedate		VARCHAR(50)='',		--生产日期
	@validdate			VARCHAR(50)='',		--效期至
	@baseunitid			VARCHAR(10)='',		--基本单位
	@munitid			VARCHAR(10)='',		--销售单位
	@isSelectedGoodsNo  VARCHAR(3)='0'
)
--@encode$--
AS
SET NOCOUNT ON

Declare @costing int 

SELECT @costing=subvalue FROM sysdata where subname='costing'


DECLARE @talbename  VARCHAR(50)
IF @ifwx = 1
	SET @talbename = 'wx_GoodsStocks'
ELSE IF @ifcommission=1
	SET @talbename='CommissionStock_Qty'
ELSE
	SET @talbename = 'GOODSSTOCKS_QTY'
IF @GoodsCostPrice = '0'
	SET @GoodsCostPrice = ''
	
IF @IfUseCargo=1 AND @CargoID=0 AND @ifwx = 0
	SELECT 0 as accountqty,0 as saleunitqty,0 as buyunitqty,0 as stockunitqty 
ELSE
	BEGIN	
		--处理多单位库存
		Create table #PtypeUnitTable
		(
			PtypeId nvarchar(200),
			SaleUnitRate decimal(18,4),
			SaleUnitName varchar(200),
			BuyUnitRate decimal(18,4),
			BuyUnitName varchar(200),
			StockUnitRate decimal(18,4),
			StockUnitName varchar(200),
			BaseUnitName varchar(200)
		)
		CREATE NONCLUSTERED INDEX PtypeUnitTableIndex ON #PtypeUnitTable(PTypeid)
		
		IF @baseunitid<>'' AND @munitid<>'' AND @munitid<>'0'
		BEGIN
			INSERT INTO #PtypeUnitTable
			SELECT p.typeid AS ptypeid,sale.saleunitrate,sale.saleunitname,
			buy.buyunitrate,buy.buyunitname,stock.stockunitrate,stock.stockunitname,base.baseunitname
			FROM ptype p
			INNER JOIN 
			(
				SELECT pue.ptypeid,pue.rate AS saleunitrate,pu.fullname AS saleunitname
				FROM PType_Units_Ext pue
				INNER JOIN PType_Units pu ON pue.unitsid=pu.unitsid
				WHERE pue.ptypeid=@PTypeID AND pue.unitsid=@munitid
			) sale on sale.ptypeid=p.typeid
			INNER JOIN 
			(
				SELECT pue.Ptypeid,pue.rate AS buyunitrate,pu.fullname AS buyunitname
				FROM PType_Units_Ext pue
				INNER JOIN PType_Units pu ON pue.unitsid=pu.unitsid
				WHERE pue.ptypeid=@PTypeID AND pue.unitsid=@munitid
			) buy on buy.ptypeid=p.typeid
			INNER JOIN 
			(
				SELECT pue.Ptypeid,pue.rate AS stockunitrate,pu.fullname AS stockunitname
				FROM PType_Units_Ext pue 
				INNER JOIN PType_Units pu ON pue.unitsid=pu.unitsid
				WHERE pue.ptypeid=@PTypeID AND pue.unitsid=@munitid
			) stock ON stock.ptypeid=p.typeid
			INNER JOIN 
			(
				SELECT pue.Ptypeid,pue.rate AS baseunitrate,pu.fullname AS baseunitname
				FROM PType_Units_Ext pue
				INNER JOIN PType_Units pu ON pue.unitsid=pu.unitsid
				WHERE pue.ptypeid=@PTypeID AND pue.unitsid=@baseunitid
			) base ON base.ptypeid=p.typeid
			WHERE p.typeid=@PTypeID
		END
		ELSE
		BEGIN
			INSERT INTO #PtypeUnitTable
			SELECT 
			p.typeid AS ptypeid,
			sale.saleunitrate,sale.saleunitname,
			buy.buyunitrate,buy.buyunitname,
			stock.stockunitrate,stock.stockunitname,
			base.baseunitname
			FROM ptype p
			INNER JOIN 
			(
				SELECT p.typeid AS PtypeId,pue.rate AS saleunitrate,pu.fullname AS saleunitname
				FROM ptype p 
				INNER JOIN PType_Units_Ext pue ON p.typeid=pue.ptypeid
				AND p.saleunitid=pue.unitsid
				INNER JOIN PType_Units pu ON pue.unitsid=pu.unitsid
				WHERE p.typeid=@PTypeID
			) sale on sale.ptypeid=p.typeid
			INNER JOIN 
			(
				SELECT p.typeid AS PtypeId,pue.rate AS buyunitrate,pu.fullname AS buyunitname
				FROM ptype p 
				INNER JOIN PType_Units_Ext pue ON p.typeid=pue.ptypeid
				AND p.buyunitid=pue.unitsid
				INNER JOIN PType_Units pu ON pue.unitsid=pu.unitsid
				WHERE p.typeid=@PTypeID
			) buy on buy.ptypeid=p.typeid
			INNER JOIN 
			(
				SELECT p.typeid AS PtypeId,pue.rate AS stockunitrate,pu.fullname AS stockunitname
				FROM ptype p 
				INNER JOIN PType_Units_Ext pue ON p.typeid=pue.ptypeid
				AND p.stockunitid=pue.unitsid
				INNER JOIN PType_Units pu ON pue.unitsid=pu.unitsid
				WHERE p.typeid=@PTypeID
			) stock ON stock.ptypeid=p.typeid
			INNER JOIN 
			(
				SELECT p.typeid AS PtypeId,pue.rate AS baseunitrate,pu.fullname AS baseunitname
				FROM ptype p 
				INNER JOIN PType_Units_Ext pue ON p.typeid=pue.ptypeid
				AND p.baseunitid=pue.unitsid
				INNER JOIN PType_Units pu ON pue.unitsid=pu.unitsid
				WHERE p.typeid=@PTypeID
			) base ON base.ptypeid=p.typeid
			WHERE p.typeid=@PTypeID
		END
		DECLARE @SaleUnitQtySQL VARCHAR(1000)
		DECLARE @BuyUnitQtySQL VARCHAR(1000)
		DECLARE @StockUnitQtySQL VARCHAR(1000)
		
		SET @SaleUnitQtySQL = 'a.qty % pu.saleunitrate'
		SET @BuyUnitQtySQL = 'a.qty % pu.buyunitrate'
		SET @StockUnitQtySQL = 'a.qty % pu.stockunitrate'
		
		DECLARE @SQL NVARCHAR(max)
		
		DECLARE @QtyDecimal INT
		
		SELECT @QtyDecimal=DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName='qty'

		SET @SQL = '
					SELECT a.qty as accountqty,
					CASE WHEN pu.saleunitrate = 1 THEN dbo.F_ClearInvalidDecimal(CAST(a.qty AS NVARCHAR)) + pu.saleunitname
					ELSE
						CASE WHEN (SELECT TOP 1 * FROM dbo.f_split(a.qty/pu.saleunitrate,''.''))=''0'' THEN dbo.F_ClearInvalidDecimal(CAST(round('+@SaleUnitQtySQL+','+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + 
							pu.baseunitname 
						ELSE
						(
							CAST((SELECT TOP 1 * FROM dbo.f_split(a.qty/pu.saleunitrate,''.'')) AS NVARCHAR)+ pu.saleunitname +
							CASE WHEN ('+@SaleUnitQtySQL+') > 0 THEN dbo.F_ClearInvalidDecimal(CAST(round('+@SaleUnitQtySQL+','+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + 
							pu.baseunitname 
							ELSE '''' END
						) END
					END AS saleunitqty,
					
					CASE WHEN pu.buyunitrate = 1 THEN dbo.F_ClearInvalidDecimal(CAST(a.qty AS NVARCHAR)) + pu.buyunitname
					ELSE
						CASE WHEN (SELECT TOP 1 * FROM dbo.f_split(a.qty/pu.buyunitrate,''.''))=''0'' THEN dbo.F_ClearInvalidDecimal(CAST(round('+@BuyUnitQtySQL+','+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + pu.baseunitname  
						ELSE
						(
							CAST((SELECT TOP 1 * FROM dbo.f_split(a.qty/pu.buyunitrate,''.'')) AS NVARCHAR)+ pu.buyunitname+
							CASE WHEN ('+@BuyUnitQtySQL+') > 0 THEN dbo.F_ClearInvalidDecimal(CAST(round('+@BuyUnitQtySQL+','+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + pu.baseunitname 
							ELSE '''' END
						) END
					END AS buyunitqty,
					
					CASE WHEN pu.stockunitrate = 1 THEN dbo.F_ClearInvalidDecimal(CAST(a.qty AS NVARCHAR)) + pu.stockunitname
					ELSE
						CASE WHEN (SELECT TOP 1 * FROM dbo.f_split(a.qty/pu.stockunitrate,''.''))=''0'' THEN dbo.F_ClearInvalidDecimal(CAST(round('+@StockUnitQtySQL+','+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + pu.baseunitname 
						ELSE
						(
							CAST((SELECT TOP 1 * FROM dbo.f_split(a.qty/pu.stockunitrate,''.'')) AS NVARCHAR)+ pu.stockunitname+
							CASE WHEN ('+@StockUnitQtySQL+') > 0 THEN dbo.F_ClearInvalidDecimal(CAST(round('+@StockUnitQtySQL+','+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + pu.baseunitname
							ELSE '''' END
						) END
					END AS stockunitqty
					FROM
					(
						SELECT a.ptypeid, CAST(ISNULL(SUM(a.Qty),0) AS  NUMERIC(24, 10) ) as qty
						FROM   '+@talbename + ' a '		
		IF @talbename!='CommissionStock_Qty'
		BEGIN
			SET @SQL = @SQL +' WHERE  a.KTypeID=@KTypeID AND a.PTypeID=@PTypeID '		
		END
		ELSE
		BEGIN
			SET @SQL = @SQL +' WHERE a.PTypeID=@PTypeID '
		END
		IF  @CargoID <> 0	
			SET @SQL = @SQL + ' AND a.CargoID=' + CAST(@CargoID AS VARCHAR)
		IF  @ItemID <> 0	
			SET @SQL = @SQL + ' AND a.ItemID=' + CAST(@ItemID AS VARCHAR)
		IF  @ifwx <> 1 AND @GoodsCostPrice <> '' AND CAST(@GoodsCostPrice AS NUMERIC) >= 0 AND @costing<>0 AND @talbename!='CommissionStock_Qty'
			SET @SQL = @SQL + ' AND a.GoodsCostPrice=' + CAST(@GoodsCostPrice AS VARCHAR)
		IF  @GoodsNumber <> ''	
		BEGIN
			SET @SQL = @SQL + ' AND a.GoodsNumber=''' + @GoodsNumber + ''''
			SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''	
			SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
		END
		ELSE IF @GoodsCostPrice <> '' AND CAST(@GoodsCostPrice AS NUMERIC) >= 0	
		BEGIN
			SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''	
			SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
		END
		ELSE IF @isSelectedGoodsNo = '1'
		BEGIN
			IF @costing = '3'
			BEGIN
				IF @producedate<>''
					SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''	
				IF @validdate<>''
					SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
			END
			ELSE
			BEGIN
				SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''	
				SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
			END
		END
		ELSE
		BEGIN
			IF  @ifwx <> 1 AND @producedate <> ''
			SET @SQL = @SQL + ' AND a.producedate=''' + @producedate + ''''	
			IF  @ifwx <> 1 AND @validdate <> ''
			SET @SQL = @SQL + ' AND a.validdate=''' + @validdate + ''''
		END
		IF @talbename!='CommissionStock_Qty'
		SET @SQL = @SQL + ' GROUP BY a.KTypeID,a.PTypeID'
		ELSE
		BEGIN
		SET @SQL = @SQL + ' GROUP BY a.PTypeID'	
		END	  
		IF  @CargoID <> 0	
		SET @SQL = @SQL + ',a.CargoID'
		IF  @ItemID <> 0	
		SET @SQL = @SQL + ',a.ItemID'
		IF  @GoodsNumber <> ''	
		BEGIN
			SET @SQL = @SQL + ',a.GoodsNumber'
		END
		IF  @ifwx <> 1 AND @GoodsCostPrice <> '' AND CAST(@GoodsCostPrice AS NUMERIC) >= 0 AND @talbename!='CommissionStock_Qty'
			SET @SQL = @SQL + ',a.GoodsCostPrice'
		IF  @ifwx <> 1 AND @producedate <> ''
		SET @SQL = @SQL + ',a.producedate'	
		IF  @ifwx <> 1 AND @validdate <> ''
		SET @SQL = @SQL + ',a.validdate'
		
		SET @SQL =@SQL+') a INNER JOIN #PtypeUnitTable pu ON a.PtypeId=pu.PtypeId'
		--print @sql
		--SELECT @SQL FOR XML PATH('')
		EXEC sp_executesql @SQL ,N'@KTypeID VARCHAR(50),@PTypeID VARCHAR(50)', @KTypeID,@PTypeID
		DROP TABLE #PtypeUnitTable
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetGuestOrderBillQtyAndReachQty]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetGuestOrderBillQtyAndReachQty]
GO














/****** Object:  Stored Procedure dbo.Web_GetGuestOrderBillQtyAndReachQty    Script Date: 2002-6-20 10:14:54 ******/

/*
功能说明：从OrderIndex、OrderBii、ptype表中根据BTypeID取出商品的存货量、发货量以及未发货量
输入参数：BTypeID
          StartDate 开始统计日期
   EndDate 结束统计日期
说明：BTypeID可以为任意一级ID，如00001、0000100001、000010000100001等
调用页面：GuestOrderBillQueryBase.asp
作者：李华
时间：2001-04-25
*/
CREATE  PROCEDURE Web_GetGuestOrderBillQtyAndReachQty
( 
 @BTypeID varchar(25),
 @StartDate datetime,
 @EndDate datetime
)
--@encode$--
AS
SET NOCOUNT ON 
SELECT  
 ptype.UserCode,
 ptype.FullName,
 ptype.Unit1,
 SUM(OrderBill.qty) AS Qty, 
 SUM(OrderBill.total) AS QtyPrice,
 SUM(OrderBill.ReachQty) AS ReachQty, 
       SUM(OrderBill.price * OrderBill.ReachQty) AS ReachQtyPrice, 
       SUM(OrderBill.qty - OrderBill.ReachQty) AS RemainQty, 
       SUM(OrderBill.total - OrderBill.price * OrderBill.ReachQty) AS RemainQtyPrice
FROM
 OrderIndex INNER JOIN OrderBill ON OrderIndex.billNumberId = OrderBill.billNumberID
 INNER JOIN ptype ON OrderBill.ptypeid = ptype.typeId
WHERE 
 OrderIndex.btypeid LIKE @BTypeID + '%' 
 AND OrderIndex.BillDate <= @EndDate 
 AND OrderIndex.BillDate >= @StartDate
GROUP BY ptype.UserCode, ptype.FullName, ptype.Unit1















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetInnerPreTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetInnerPreTotal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-02-24
	描述：获取此前内部应收数据
*/

CREATE PROCEDURE Web_GetInnerPreTotal
(
	@OperatorId		VARCHAR(100),			--操作员ID
	@STypeId		VARCHAR(MAX),			--分支机构
	@DSTypeId		VARCHAR(MAX),			--对方分支机构
	@StartDate		VARCHAR(MAX)			--截止日期	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
IF @STypeId = '00000'
	SET @STypeId = ''
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--对应分支机构
CREATE TABLE #GetManDSTypeId(TypeId	varchar(100))
INSERT INTO #GetManDSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,'00001')	

--分支机构所对应的仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE sonnum = 0 AND typeId In (SELECT typeId FROM F_GetAllManagerBaseTypeId('',4,'00001')) AND STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID))
	
--对应分支机构所对应的仓库
CREATE TABLE #GetManDKTypeId(TypeId	varchar(100))
INSERT INTO #GetManDKTypeId(TypeId) SELECT TypeId FROM Stock WHERE sonnum = 0 AND typeId In (SELECT typeId FROM F_GetAllManagerBaseTypeId('',4,'00001')) AND STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,'00001'))


CREATE TABLE #BillIndex
(
	BillNumberId	NUMERIC(18,0)
)

INSERT INTO #BillIndex(BillNumberId) 
SELECT	Bil.BillNumberId 
FROM	BillIndex Bil
WHERE	Bil.BillType IN (187,188) 
		AND Bil.ifcheck = 't' 
		AND Bil.RedWord = 0 
		AND Bil.ifYearBill = 0
		AND Bil.BillDate<@StartDate

DECLARE @SQL VARCHAR(MAX)


SET @SQL = 'SELECT	ISNULL(SUM(B.Total),0) AS Total
			FROM	(
						SELECT	ISNULL(SUM(M.InnerArTotal00),0) AS Total
						FROM	SType_InnerARTotal M
						INNER JOIN #GetManSTypeId S ON S.TypeId = M.STypeId
						INNER JOIN #GetManDSTypeId D ON D.TypeId = M.STypeId2
						UNION ALL
						SELECT	ISNULL(SUM(M.ArAdd),0) - ISNULL(SUM(M.ArReduce),0) AS Total
						FROM	BillIndex B
						INNER JOIN (
										SELECT	S.BillNumberId,
												CASE WHEN S.BillType = 187 THEN S.Total ELSE 0 END AS ArAdd,
												0 AS ArReduce
										FROM	STypeMoveBill S
										INNER JOIN #BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
										WHERE	(S.KTypeId IN (SELECT TypeId FROM #GetManKTypeId) AND S.KTypeId2 IN (SELECT TypeId FROM #GetManDKTypeId))
										UNION ALL
										SELECT	S.BillNumberId,			
												0 AS ArAdd,						
												CASE WHEN S.BillType = 188 THEN ISNULL(I.CostTotal,0) ELSE 0 END AS ArReduce
										FROM InOutStockTable I
										INNER JOIN STypeMoveBill S ON I.BillNumberID=S.BillNumberID AND I.id=S.id
										INNER JOIN #BillIndex Bil ON Bil.BillNumberId = S.BillNumberId
										WHERE	(S.KTypeId2 IN (SELECT TypeId FROM #GetManKTypeId) AND S.KTypeId IN (SELECT TypeId FROM #GetManDKTypeId))	
										UNION ALL
									    SELECT	M.BillNumberId,
									    CASE WHEN Total>0 AND M.Audited=1 THEN abs(TOTAL) WHEN Total>0 AND M.Audited=0 THEN TOTAL ELSE 0 END AS ArAdd,
									    CASE WHEN Total<0 AND M.Audited=1 THEN abs(TOTAL) WHEN Total<0 AND M.Audited=0 THEN TOTAL ELSE 0 END AS ArReduce
							FROM	ListTable M
						    INNER JOIN    AC_Items AC ON M.atypeid=AC.nid			
							WHERE	m.STypeId IN (SELECT TypeId FROM #GetManSTypeId) AND m.STypeId2 IN (SELECT TypeId FROM #GetManDSTypeId)
									AND AC.UserCode = ''1132''			
									AND M.BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 159 AND IfCheck = ''t'' AND Draft = 0)										
						)M ON B.BillNumberId = M.BillNumberId
						WHERE	B.BillDate<'''+@StartDate+'''					
								AND B.IfCheck = ''t''
								AND B.RedWord = 0
								AND B.IfYearBill = 0
								AND B.BillType IN (187,188,159)
						)B '

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManDSTypeId,#BillIndex,#GetManKTypeId,#GetManDKTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetIntercourseSetting]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetIntercourseSetting]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
作者：ludalin
时间：2012-10-24
描述:往来单位报警
*/
CREATE PROCEDURE Web_GetIntercourseSetting
(
	@OperatorId varchar(1000),--操作员id
	@ifstype	VARCHAR(50),
	@isLoginHit	INT	
)

--@encode$--
AS
SET NOCOUNT ON 
IF @ifstype='true'
BEGIN
	CREATE TABLE #tem_a(posttime varchar(100),btypeid varchar(100),stypeid varchar(100))

	INSERT INTO #tem_a(posttime,btypeid,stypeid) 
	SELECT  t.posttime,T.dealbtypeid,T.stypeid 
	FROM (
		SELECT b.posttime,b.DealBTypeID,b.Stypeid 
		FROM (
				SELECT max(d.BillDate) as posttime,d.dealbtypeid,d.stypeid,d.LimitDay--调整，取单据日期，并非过账日期，需求：张玲慧
				FROM(
						SELECT b.BillDate,b.dealbtypeid,b.Stypeid,c.LimitDay
						FROM listtable a INNER JOIN billindex b ON a.billnumberid=b.billnumberid 
								INNER JOIN intercoursesetting c ON b.dealbtypeid=c.btypeid AND b.stypeid=c.stypeid
								INNER JOIN (SELECT typeid FROM F_GetManDetailBType(@OperatorId)) a1 ON a1.typeid=b.dealBtypeId 
								INNER JOIN (SELECT TypeId FROM F_GetManDetailSType(@OperatorId)) c1 ON c1.typeid=b.StypeId	
						WHERE b.RedWord=0 AND b.billtype NOT IN ('148','149','150','151')
						UNION ALL--应收增加应收减少干掉
						SELECT b.BillDate,a.btypeid,b.Stypeid,c.LimitDay
						FROM addebtbill a INNER JOIN billindex b ON a.billnumberid=b.billnumberid 
							INNER JOIN intercoursesetting c ON a.btypeid=c.btypeid AND b.stypeid=c.stypeid
							INNER JOIN (SELECT typeid FROM F_GetManDetailBType(@OperatorId)) a1 ON a1.typeid=a.BtypeId 
							INNER JOIN (SELECT TypeId FROM F_GetManDetailSType(@OperatorId)) c1 ON c1.typeid=b.StypeId
						WHERE b.RedWord=0
						UNION ALL
						SELECT b.BillDate,b.dealbtypeid,b.Stypeid,c.LimitDay
						FROM dbo.LendBill a INNER JOIN dbo.LendIndex b ON a.billnumberid=b.BillNumberId
							INNER JOIN dbo.IntercourseSetting c ON b.dealbtypeid=c.BtypeId AND b.Stypeid=c.StypeId
							INNER JOIN (SELECT typeid FROM F_GetManDetailBType(@OperatorId)) a1 ON a1.typeid=b.dealBtypeId 
							INNER JOIN (SELECT TypeId FROM F_GetManDetailSType(@OperatorId)) c1 ON c1.typeid=b.StypeId
						UNION ALL 
						SELECT b.BillDate,b.dealbtypeid,b.Stypeid,c.LimitDay
						FROM dbo.OrderBill a INNER JOIN dbo.OrderIndex b ON a.billnumberid=b.BillNumberId
							INNER JOIN dbo.IntercourseSetting c ON b.DealBTypeID=c.BtypeId AND b.Stypeid=c.StypeId
							INNER JOIN (SELECT typeid FROM F_GetManDetailBType(@OperatorId)) a1 ON a1.typeid=b.dealBtypeId 
							INNER JOIN (SELECT TypeId FROM F_GetManDetailSType(@OperatorId)) c1 ON c1.typeid=b.StypeId
				) d GROUP BY d.dealbtypeid,d.stypeid,d.LimitDay
			) b 
		WHERE GETDATE()>=b.LimitDay+b.posttime
		) t
	IF  @isLoginHit=1
		SELECT TOP 1  'btypealarmhit',1	FROM #tem_a
	ELSE
	BEGIN
		SELECT CONVERT(varchar(10),datediff(day,t1.posttime,getdate()))+'天' AS limittime,t4.FullName AS sfullname,t3.typeId AS btypeid,t3.FullName AS bfullname,t3.usercode AS busercode
		FROM #tem_a t1 LEFT JOIN intercoursesetting t2 ON t1.stypeid=t2.stypeid AND t1.btypeid=t2.btypeid
		INNER JOIN dbo.btype t3 ON t1.btypeid=t3.typeId
		INNER JOIN dbo.SType t4 ON t1.stypeid=t4.TypeId
	END
	DROP TABLE #tem_a
END
ELSE
BEGIN
	CREATE TABLE #tem_b(posttime varchar(100),btypeid varchar(100))

	INSERT INTO #tem_b(posttime,btypeid) 
	SELECT  t.posttime,T.dealbtypeid
	FROM (
		SELECT b.posttime,b.DealBTypeID 
		FROM (
				SELECT max(BillDate) as posttime,dealbtypeid,LimitDay--调整，取单据日期，并非过账日期，需求：张玲慧
				FROM(
						SELECT b.BillDate,b.dealbtypeid,c.LimitDay
						FROM listtable a INNER JOIN billindex b ON a.billnumberid=b.billnumberid 
								INNER JOIN intercoursesetting c ON b.dealbtypeid=c.btypeid
								INNER JOIN (SELECT typeid FROM F_GetManDetailBType(@OperatorId)) a1 ON a1.typeid=b.dealBtypeId 
						WHERE b.RedWord=0 AND b.billtype NOT IN ('148','149','150','151')
						UNION ALL--应收增加应收减少干掉
						SELECT b.BillDate,a.btypeid,c.LimitDay
						FROM addebtbill a INNER JOIN billindex b ON a.billnumberid=b.billnumberid 
							INNER JOIN intercoursesetting c ON a.btypeid=c.btypeid
							INNER JOIN (SELECT typeid FROM F_GetManDetailBType(@OperatorId)) a1 ON a1.typeid=a.BtypeId
						WHERE b.RedWord=0
						UNION ALL
						SELECT b.BillDate,b.dealbtypeid,c.LimitDay
						FROM dbo.LendBill a INNER JOIN dbo.LendIndex b ON a.billnumberid=b.BillNumberId
							INNER JOIN dbo.IntercourseSetting c ON b.dealbtypeid=c.BtypeId
							INNER JOIN (SELECT typeid FROM F_GetManDetailBType(@OperatorId)) a1 ON a1.typeid=b.dealBtypeId
						UNION ALL 
						SELECT b.BillDate,b.dealbtypeid,c.LimitDay
						FROM dbo.OrderBill a INNER JOIN dbo.OrderIndex b ON a.billnumberid=b.BillNumberId
							INNER JOIN dbo.IntercourseSetting c ON b.DealBTypeID=c.BtypeId
							INNER JOIN (SELECT typeid FROM F_GetManDetailBType(@OperatorId)) a1 ON a1.typeid=b.dealBtypeId
				) a GROUP BY dealbtypeid,LimitDay
			)  b 
			WHERE GETDATE()>=b.LimitDay+b.posttime
		) t
	IF  @isLoginHit=1
		SELECT TOP 1  'btypealarmhit',1	FROM #tem_b
	ELSE
	BEGIN
		SELECT CONVERT(varchar(10),datediff(day,t1.posttime,getdate()))+'天' AS limittime,NULL AS sfullname,t3.typeId AS btypeid,t3.FullName AS bfullname,t3.usercode AS busercode
		FROM #tem_b t1 LEFT JOIN intercoursesetting t2 ON  t1.btypeid=t2.btypeid
		INNER JOIN dbo.btype t3 ON t1.btypeid=t3.typeId
	END
	
	DROP TABLE #tem_b
END	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetItemLists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetItemLists]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.11.23
	描述：获取未关联的项目
*/
CREATE PROCEDURE Web_GetItemLists
(
	@Operatorid	VARCHAR(50),
	@typeid		VARCHAR(50),
	@stypeid	VARCHAR(50),
	@listall	INT,			-- 0.获取未关联项目 1. 列出分类下关联项目，分类为空，列出所有关联的2.列出所有项目
	@Filter		VARCHAR(300)= '',
	@ptypeid	VARCHAR(50) = ''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS null RETURN 1

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #TempItem
(
	nId			VARCHAR(50),
	usercode	VARCHAR(200),
	FullName	VARCHAR(200),
	comment		VARCHAR(400),
	DELETED		INT
)


INSERT INTO #TempItem( nId, usercode, FullName,comment,DELETED )
EXEC dbo.Web_GetAcItemsWithLimit @OperatorId

IF @listall = 0
	SELECT * 
	FROM #TempItem M
		INNER JOIN dbo.Ac_Items_Detail b ON M.nId = b.nId AND b.stypeid = @stypeid
	WHERE NOT EXISTS(
		SELECT c.nid
		FROM dbo.ItemType a
			INNER JOIN dbo.ItemType_Item b ON a.nId = b.itemTypeId
			INNER JOIN #TempItem c ON b.itemId = c.nId
		WHERE LEFT(a.ParId,5) = LEFT(@typeid,5) AND a.STypeid = @stypeid 
			AND a.Attribute = 2
			AND M.nId = c.nId 
	)
	AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%')
	ORDER BY M.usercode
ELSE IF @listall = 1
	SELECT c.* 
	FROM dbo.ItemType a
		INNER JOIN dbo.ItemType_Item b ON a.nId = b.itemTypeId 
		INNER JOIN #TempItem c ON b.itemId = c.nId  AND (c.UserCode LIKE '%'+@Filter+'%' OR c.FullName LIKE '%'+@Filter+'%')
	WHERE a.STypeid = @stypeid AND (@ptypeid <> '' AND LEFT(a.TypeId,5) = @ptypeid OR @ptypeid = '')
	ORDER BY usercode
ELSE
	SELECT * FROM #TempItem
	WHERE UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%'
	ORDER BY usercode

DROP TABLE #TempItem

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.11.23
	描述：获取项目分类关联的项目
*/
CREATE PROCEDURE Web_GetItems
(
	@OperatorId	VARCHAR(50),
	@typeid		VARCHAR(50),
	@attribute	INT,
	@stypeid	VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON


CREATE TABLE #TempItem
(
	nId			VARCHAR(50),
	usercode	VARCHAR(200),
	FullName	VARCHAR(200),
	comment		VARCHAR(400),
	DELETED		INT
)


INSERT INTO #TempItem( nId, usercode, FullName,comment,DELETED )
EXEC dbo.Web_GetAcItemsWithLimit @OperatorId

IF @attribute = 0
BEGIN
	SELECT c.nId,c.usercode,c.FullName,c.comment,c.deleted,CASE c.DELETED WHEN 0 THEN '' ELSE '√' END AS deletedtxt
	FROM dbo.ItemType a
		INNER JOIN dbo.ItemType_Item b ON a.nId = b.itemTypeId
		INNER JOIN #TempItem c ON b.itemId = c.nId
	WHERE LEFT(a.ParId,5) = LEFT(@typeid,5) AND a.STypeid = @stypeid AND a.Attribute = 2
END
ELSE IF @attribute = 1
BEGIN
	SELECT c.nId,c.usercode,c.FullName,c.comment,c.deleted,CASE c.DELETED WHEN 0 THEN '' ELSE '√' END AS deletedtxt
	FROM dbo.ItemType a
		INNER JOIN dbo.ItemType_Item b ON a.nId = b.itemTypeId
		INNER JOIN #TempItem c ON b.itemId = c.nId
	WHERE a.ParId LIKE N'' + @typeid + N'%'  AND a.STypeid = @stypeid AND a.Attribute = 2
END
ELSE IF @attribute = 2
BEGIN
	SELECT c.nId,c.usercode,c.FullName,c.comment,c.deleted,CASE c.DELETED WHEN 0 THEN '' ELSE '√' END AS deletedtxt
	FROM dbo.ItemType a
		INNER JOIN dbo.ItemType_Item b ON a.nId = b.itemTypeId
		INNER JOIN #TempItem c ON b.itemId = c.nId
	WHERE a.typeId = @typeid AND a.STypeid = @stypeid
END

DROP TABLE #TempItem

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetItemsIni]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_GetItemsIni]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
--================================================================
-----------------功能：项目期初的查询----------
-----------------作者：韩林			 ----------
-----------------日期：2012-06-07    ----------
-- 2013.01.06 周华 敏捷开发，添加了资产负债用户新增项
-- 2013.02.01 周华 过程修改成层级的
-- 2013.02.17 周华 修改现金银行期初，单独处理现金
-- 2013.02.22 周华 调整其它业务期初问题 atype_l里存储的ntypeid
-- 2013.02.25 周华 修改项目期初 排序，有权限项目只显示叶子节点问题
-- 2013.04.01 周华 修改usercode,fullname长度问题
--================================================================

CREATE    PROC Web_GetItemsIni
( 
	@OperatorID	VARCHAR(50),	-- 操作员的ID号
	@Type	  		VARCHAR(20),
	@STypeId		VARCHAR(MAX),
	@Parid			VARCHAR(50)='' --父级id ，也就是选这个parid下面一层的数据，当为空时，先第一级
)
--@encode$--
AS
SET NOCOUNT ON

--分支机构
CREATE TABLE #SType(TypeId VARCHAR(50))
INSERT INTO #SType(TypeId) 
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) 

--分支机构权限范围内的项目
CREATE TABLE #Item(NId INT)
INSERT INTO #Item(NId) 
SELECT DISTINCT D.nId
FROM Ac_Items_Detail D
INNER JOIN  F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) S ON S.typeid=D.STypeId
GROUP BY D.nId

--数据表
CREATE TABLE #Tdata
(
	NId			INT,
	NTypeId		VARCHAR(50),
	NParId		VARCHAR(50),
	UserCode	VARCHAR(200),
	FullName	VARCHAR(200),
	Total			NUMERIC(24, 10) 
)
	
IF @type = 'others' --其它应收期初
	BEGIN 
		INSERT INTO #TData
			(
				NId,
				NTypeId,
				NParId,
				UserCode,
				FullName,
				Total
			)
		SELECT	
			A.nId,
			A.nTypeId,
			A.nParId,
			A.UserCode,
			A.FullName,
			ISNULL(SUM(total.Total00),0) Total
		FROM dbo.Ac_Items A
		INNER JOIN #Item Details ON Details.NId=A.nId
		LEFT JOIN 
			(
				SELECT	
						A.ATypeID,
						SUM(ISNULL(a.Total00,0)) Total00
				FROM AType_Total A 
				INNER join #SType S ON S.Typeid=A.STypeID
				GROUP BY A.ATypeID
			) Total ON Total.ATypeID=A.nId
		WHERE  --操作员的对收入、支出、权益类项目的多级权限范围在其它业务期初中要生效控制 资产合计 负责合计不控制
			A.nId IN(
					SELECT NId FROM  dbo.F_TreeInDebtT(@OperatorID)--负债
					UNION ALL
					SELECT NId FROM  dbo.F_TreeAssetsT(@OperatorID)--资产
					UNION ALL
					SELECT NId FROM  dbo.F_AllTreeOwnerEquityT(@OperatorID)--所有者权益
			)
		AND a.SonNum=0
		GROUP BY  
			A.nId,
			A.nTypeId,
			A.nParId,
			A.UserCode,
			A.FullName
		ORDER BY usercode
	END
ELSE IF(@type='cashbank')--现金银行
	BEGIN
		INSERT INTO #TData
			(
				NId,
				NTypeId,
				NParId,
				UserCode,
				FullName,
				Total
			)
		SELECT	
			A.nId,
			A.nTypeId,
			A.nParId,
			A.UserCode,
			A.FullName,
			ISNULL(SUM(total.Total00),0) Total
		FROM dbo.Ac_Items A
		INNER JOIN F_LineA(@OperatorID) F ON F.nid=A.nId AND A.TypeName='B'
		INNER JOIN #Item Details ON Details.NId=A.nId
		LEFT JOIN 
			(
				SELECT	
						A.ATypeID,
						SUM(ISNULL(a.Total00,0)) Total00
				FROM AType_Total A 
				INNER join #SType S ON S.Typeid=A.STypeID
				GROUP BY A.ATypeID
			) Total ON Total.ATypeID=A.nId
		WHERE a.SonNum=0
		GROUP BY  
			A.nId,
			A.nTypeId,
			A.nParId,
			A.UserCode,
			A.FullName
		ORDER BY usercode
	END
ELSE IF (@type='FIXED')--固定资产
	BEGIN
		INSERT INTO #TData
			(
				NId,
				NTypeId,
				NParId,
				UserCode,
				FullName,
				Total
			)
		SELECT	
			A.nId,
			A.nTypeId,
			A.nParId,
			A.UserCode,
			A.FullName,
			ISNULL(SUM(total.Total00),0) Total
		FROM dbo.Ac_Items A
		INNER JOIN F_AllTreeC(@OperatorID) F ON F.nid=A.nId AND A.SonNum=0
		INNER JOIN #Item Details ON Details.NId=A.nId
		LEFT JOIN 
			(
				SELECT	
						A.ATypeID,
						SUM(ISNULL(a.Total00,0)) Total00
				FROM AType_Total A 
				INNER join #SType S ON S.Typeid=A.STypeID
				GROUP BY A.ATypeID
			) Total ON Total.ATypeID=A.nId
		WHERE a.SonNum=0
		GROUP BY  
			A.nId,
			A.nTypeId,
			A.nParId,
			A.UserCode,
			A.FullName
		ORDER BY usercode
	END
	
--========================特殊处理值【BEGIN】============================
-- 修改代销商品期初
UPDATE #TData SET total=(SELECT sum(isnull(Total,0)) as total FROM inicommissionstock WHERE type=144 and STypeID in (select typeid from #Stype)) WHERE ntypeid='0000200003'
	
-- 修改委托代销期初
UPDATE #TData SET total=(SELECT sum(isnull(CostTotal,0)) as total FROM inicommissionstock WHERE type=140 and STypeID in (select typeid from #Stype) ) WHERE ntypeid='0000100008'

--内部应收----------
UPDATE #TData 
SET total=ISNULL((
							SELECT SUM(a.innerartotal00) 
							FROM SType_InnerARTotal a 
							INNER JOIN #SType b ON a.STypeID=b.TypeId
						),0)
WHERE nid=28
		
--库存商品总值
UPDATE #TData SET total=(
									SELECT ISNULL(SUM(Total),0) 
									FROM dbo.IniGoodsStocks  G
									INNER JOIN Stock S ON S.typeId=G.KtypeId
									INNER JOIN #SType ST ON ST.TypeId=S.STypeID
									)
WHERE nid=30
--========================特殊处理值【BEGIN】============================
			
--设置父节点
SELECT @Parid=CASE @type WHEN 'others' THEN '00000' 
										   WHEN 'cashbank' THEN '00001' 
										   WHEN 'FIXED' THEN '0000100002' END 
WHERE @Parid=''; 

SELECT
	A.nId,
	A.nTypeId TypeId,
	A.nParId,
	A.UserCode,
	A.FullName,
	A.SonNum,
	ISNULL(SUM(T.total),0) Total
FROM Ac_Items A
INNER JOIN #TData T ON T.NTypeId LIKE A.nTypeId+'%'
WHERE 
	A.nParId=@Parid
	AND T.total IS NOT NULL
GROUP BY 
	A.nId,
	A.nTypeId,
	A.nParId,
	A.UserCode,
	A.FullName,
	A.SonNum
ORDER BY A.UserCode

--=============================删除临时表【BEGIN】=============================
DROP TABLE #SType,#Item,#TData
--=============================删除临时表【END】=============================
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetItemsIniV3]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetItemsIniV3
GO

--================================================================
-----------------功能：项目期初的查询 V3版本----------
-----------------作者：韩林					----------
-----------------日期：2012-06-07			----------
-- 2013.01.17 周华 敏捷开发V3，添加了资产负债用户新增项
-- 2013.02.01 周华 过程修改成层级的
-- 2013.02.17 周华 修改现金银行期初，单独处理现金
-- 2013.02.22 周华 调整其它业务期初问题 atype_l里存储的ntypeid
-- 2013.02.25 周华 修改项目期初 排序，有权限项目只显示叶子节点问题
-- 2013.04.01 周华 修改usercode,fullname 长度问题
--================================================================

CREATE    PROC Web_GetItemsIniV3
( 
	@OperatorID	VARCHAR(50),	-- 操作员的ID号
	@type	  	VARCHAR(20),
	@Parid varchar(50)='' --父级id，也就是点击行id
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #tdata(UserCode NVARCHAR(400),FullName NVARCHAR(400),nTypeId NVARCHAR(100),nparid NVARCHAR(100),nid int,total  NUMERIC(24, 10) );

IF @type = 'others'
BEGIN
	INSERT INTO #tdata
	SELECT	a.UserCode,
			a.FullName,
			--a.nid AS typeid,
			a.nTypeId,
			a.nparid,
			a.nid AS nid,
			ISNULL(total.total00,0) AS total
	FROM dbo.Ac_Items a
	LEFT JOIN
	(
		SELECT	A.ATypeID,
				sum(isnull(a.Total00,0)) AS total00
		FROM	AType_Total A 
		group by a.ATypeID

	) total ON total.ATypeId=a.nid 
	WHERE  a.UserCode <>'1132' AND 
	--usercode in ('1301','2171','1133','2132')
	--操作员的对收入、支出、权益类项目的多级权限范围在其它业务期初中要生效控制 资产合计 负责合计不控制
		  (a.nid IN (     SELECT nid FROM  dbo.F_TreeInDebtT('00001')) 
		  or a.nid IN (   SELECT nid FROM  dbo.F_TreeAssetsT('00001'))
		   --or  a.nid IN ( SELECT nid FROM  dbo.F_AllTreeIncomeC(@OperatorID)) --F_AllTreeGxIncome 收入
		    --OR a.nid IN ( SELECT nid FROM  dbo.F_TreeExpenseC (@OperatorID))  -- F_AllTreeGxExpense 支出
		    OR a.nid IN ( SELECT nid FROM  dbo.F_AllTreeOwnerEquityT(@OperatorID)) --所有者权益
		    )
	OR a.usercode IN (SELECT usercode FROM Ac_Items WHERE TypeName IN ('C','L') AND Sysrow=0) --这一行为敏捷 客户要求显示资产负债 新增的项

	ORDER BY usercode
	
	-- 修改委托代销期初
	UPDATE #tdata SET total=(SELECT sum(isnull(CostTotal,0)) as total FROM inicommissionstock WHERE type=140) WHERE nTypeId='0000100008'
		
	-- 修改代销商品期初
	UPDATE #tdata SET total=(SELECT sum(isnull(Total,0)) as total FROM inicommissionstock WHERE type=144)  WHERE nTypeId='0000200003'
	
END
ELSE
BEGIN
	DECLARE @sql VARCHAR(max)
	DECLARE @Manger VARCHAR(max)='0000'
	IF @type='cashbank'
		SELECT @Manger=MangerATypeID FROM dbo.loginuser WHERE etypeid=@OperatorID
	IF @type='FIXED'
		SELECT @Manger=MangerCpaital FROM dbo.loginuser WHERE etypeid=@OperatorID
	IF @Manger='0000'	--有所有权限范围
	BEGIN
		
		INSERT INTO #tdata
		SELECT	a.UserCode,
				a.FullName,
				--a.nid AS typeid,
				a.nTypeId,
				a.nparid,
				a.nid AS nid,
				ISNULL(total.total00,0) AS total
		FROM dbo.Ac_Items a
		LEFT JOIN
		(
			SELECT	A.ATypeID,
					sum(isnull(a.Total00,0)) AS total00
			FROM	AType_Total A 
			group by a.ATypeID

		) total ON total.ATypeId=a.nid 
		WHERE a.UserCode <>'1132' AND   
		TypeName = CASE WHEN @type ='fixed'
								THEN 'F'	
							WHEN  @type = 'cashbank'
								THEN 'B'
						END
		ORDER BY usercode 
	END
	ELSE
	BEGIN
		INSERT INTO #tdata
		SELECT	b.UserCode,
				b.FullName,
				--b.nid AS typeid,
				b.nTypeId,
				b.nparid,
				b.nid AS nid,
				ISNULL(total.total00,0) AS total
		FROM	atype_l a
		INNER JOIN Ac_Items b ON b.nTypeId LIKE a.typeId+'%' --ON a.TypeID =b.ntypeid -- b.nId --这里atype_l里修改了，存的ntypeid
		LEFT JOIN
		(
			SELECT	A.ATypeID,
					sum(isnull(a.Total00,0)) AS total00
			FROM	AType_Total A 
			group by a.ATypeID

		) total ON total.ATypeId=b.nid 
		WHERE b.UserCode <>'1132' AND  
		a.ETypeID =@operatorid 
		AND a.Flag = 1
		AND a.type = CASE WHEN @Type = 'cashbank' 
							THEN  '0'
						  WHEN @Type = 'fixed' 
							THEN  '3'
					 END
		ORDER BY usercode 
	END	
END

	SELECT @Parid=CASE @type WHEN 'others' THEN '00000' WHEN 'cashbank' THEN '00001' WHEN 'FIXED' THEN '0000100002' END WHERE @Parid=''; 
	-- 只要叶子节点
	DELETE a FROM #tdata a WHERE EXISTS (SELECT 1 FROM #tdata b WHERE b.ntypeid<>a.ntypeid AND b.ntypeid LIKE a.ntypeid+'%')

	--IF  @type <>'others'
	--BEGIN
	--	;WITH cte AS (
	--		SELECT * FROM #tdata a WHERE @ParId<>'' AND a.nTypeId<>@Parid AND a.nTypeId LIKE @ParId+'%' OR @ParId=''
	--	)
		
	--	SELECT a.UserCode,a.FullName,a.nTypeId AS typeid,a.nParId,a.nid
	--	,(SELECT ISNULL(SUM(total),0) FROM cte x WHERE x.nTypeId LIKE a.ntypeid+'%') AS total
	--	,(SELECT COUNT(1) FROM cte x WHERE x.ntypeid<>a.ntypeid AND x.nTypeId LIKE a.ntypeid+'%') AS sonnum
	--	FROM cte a 
	--	WHERE NOT EXISTS(SELECT 1 FROM cte b WHERE b.nTypeId<>a.nTypeId AND a.nTypeId LIKE b.nTypeId +'%' )
	--END
	--ELSE 
	--BEGIN --其它业务期初 ,因为期它业务期初是以 usercode 找出来的，所以要单独用一种方式处理才行
		;WITH cte AS (
			SELECT * FROM ac_items WHERE nParId=@Parid 
			--OR @type='cashbank' AND (usercode IN ('1001') AND @Parid='00001') --单独处理现金
		)
		SELECT * FROM (
		SELECT a.usercode,a.fullname,a.ntypeid AS typeid,a.nparId,SUM(b.total) AS total,CASE WHEN a.SonNum=0 THEN 0 ELSE COUNT(1) END AS sonnum ,a.nid
		FROM cte a LEFT JOIN #tdata b ON b.ntypeid LIKE a.nTypeId+'%'
		GROUP BY a.nTypeId,a.UserCode,a.FullName,a.ntypeid,a.nparId,a.SonNum,a.nid ) w WHERE w.total IS NOT NULL
		ORDER BY w.usercode;
	--END

DROP TABLE #tdata;

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetJudgeUseBrandarTypeBillData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_GetJudgeUseBrandarTypeBillData
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	判断启用品牌应收功能是否满足条件
-- 时间：	2017-11-28
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_GetJudgeUseBrandarTypeBillData
(
	@Type	INT--1启用品牌 2：取消品牌或者是否只读
)

--@encode$--
AS
SET NOCOUNT ON

IF(@Type=1)
	BEGIN
		--POS终端管理已启用 前台挂往来功能 选项
		IF EXISTS(SELECT TOP 1 1 FROM PosInfo WHERE enablebtype=1)
			RETURN 1
	END
ELSE 
	BEGIN
		IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND SubValue=1) AND EXISTS(SELECT TOP 1 1 FROM btype where IsUseBrandarType=1)
			RETURN 1
	/*
		DECLARE @IsUseBrandarType	INT=0--是否启用品牌

		IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND SubValue=1)
			SET @IsUseBrandarType=1

		--往来单位
		CREATE TABLE #BType(TypeId VARCHAR(50))

		IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value=1)-- 客户供货商统一  
			BEGIN
				INSERT INTO #BType(TypeId)
				SELECT B.typeId
				FROM F_GetAllManagerBaseTypeId('',2,'00001') F
				INNER JOIN btype B ON B.typeId=F.TypeId  AND B.sonnum=0 AND (@IsUseBrandarType=1 AND B.IsUseBrandarType=1)
			END
		ELSE --不统一，只需客户
			BEGIN
				INSERT INTO #BType(TypeId)
				SELECT B.typeId
				FROM F_GetAllManagerBaseTypeId('',2,'00001') F
				INNER JOIN btype B ON B.typeId=F.TypeId AND b.typeId LIKE '00001%'  AND B.sonnum=0 AND (@IsUseBrandarType=1 AND B.IsUseBrandarType=1)
			END
		--========================判断期初单据================
		--189 预收款单 BillIndex
		--116 应收增加单 BillIndex
		--115 应收减少单 BillIndex
		--36 费用单 BillIndex
		--93 其他收入单 BillIndex
		--11 销售出库单 BillIndex
		--45 销售退货单 BillIndex
		--160 销售换货单 BillIndex
		--141 委托代销结算单 BillIndex
		--402 发出商品出库单 BillIndex
		--403 发出商品退货单 BillIndex
		--12 组合品销售出库单 BillIndex
		--46 组合品销售退货单 BillIndex
		--46 组合品销售退货单 BillIndex
		IF EXISTS(SELECT TOP 1 1 
					FROM BillIndex I
					INNER JOIN #BType B ON B.TypeId=I.btypeid OR B.TypeId=I.DealBTypeID 
					WHERE 
						BillType IN(189,116,115,11,45,160,141,402,403,12,46,36,93) 
						AND ((I.RedWord=0 AND I.ifcheck='T') OR (I.IsIni=1 AND I.RedWord=0))
				)
			RETURN 1
			
		--405 销售发货开票 ReceiptBillIndex
		IF EXISTS(SELECT TOP 1 1 
					FROM ReceiptBillIndex I
					INNER JOIN #BType B ON B.TypeId=I.btypeid OR B.TypeId=I.DealBTypeID 
					WHERE 
						BillType=405
						AND ((I.RedWord=0 AND I.ifcheck='T') OR (I.IsIni=1 AND I.RedWord=0))
				)
			RETURN 1
			
			
		--159  业务凭证 accountcredence
		IF EXISTS(SELECT TOP 1 1 
					FROM AccountCredence I
					INNER JOIN #BType B ON B.TypeId=I.ATypeID 
					INNER JOIN (
						SELECT C.nId
						FROM Ac_Items C 
						INNER JOIN Ac_Items IC ON C.UserCode IN('987','2131','043') AND IC.nTypeId LIKE C.TypeId+'%'
						) F ON  I.TypeATypeID = F.nId
					INNER JOIN BillIndex BI ON BI.BillType=159 AND BI.BillNumberId=I.BillNumberID 
					WHERE 
						RedWord=0 
						AND BI.ifcheck='T'
				)
			RETURN 1
			*/
			
	END
RETURN 0
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetLoginUserManBaseInfoForInput]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetLoginUserManBaseInfoForInput]
GO





/*
	描述：获取基本信息的资料
	作者：谢吉康
	日期：2009-8-15

	Web_GetLoginUserManBaseInfoForInput 'ptype','00000','0000100046',''
*/

CREATE PROCEDURE Web_GetLoginUserManBaseInfoForInput
(
	@dbName		varchar(200),
	@TypeId		varchar(8000),
	@ETypeId	varchar(100),
	@nFlag		varchar(10),	--0.上一层  1.下一层
	@Filter		varchar(1000)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @pSonNum 	int,
		@pParId		varchar(100),
		@MPTypeId	varchar(100)

SELECT @pSonNum = SonNum,@pParId = ParId FROM PType WHERE TypeId = @TypeId

IF @Filter = ''
	BEGIN
		IF @TypeId = '00000'
			SELECT 	TypeId,SonNum,Unit1,UserCode,FullName,[Name],EntryCode,Standard,Type,Area 
			FROM 	PType 
			WHERE	Deleted = 0
					AND ParId = '00000' 
					AND TypeId <> '00000'
			ORDER BY UserCode	
		ELSE IF @TypeId = '99999'
			SELECT 	TypeId,SonNum,Unit1,UserCode,FullName,[Name],EntryCode,Standard,Type,Area 
			FROM 	PType 
			WHERE	Deleted = 0
					AND TypeId <> '00000' 
					AND TypeId IN (SELECT * FROM F_GetUserManInfoForInput(@dbName,@TypeId,@ETypeId,'0'))
			ORDER BY UserCode	
		ELSE IF @nFlag = '1'
			SELECT 	TypeId,SonNum,Unit1,UserCode,FullName,[Name],EntryCode,Standard,Type,Area 
			FROM 	PType 
			WHERE	Deleted = 0
					AND ParId = @TypeId
					AND TypeId <> '00000' 
					AND TypeId IN (SELECT * FROM F_GetUserManInfoForInput(@dbName,@TypeId,@ETypeId,'1'))
			ORDER BY UserCode
		ELSE
			SELECT 	TypeId,SonNum,Unit1,UserCode,FullName,[Name],EntryCode,Standard,Type,Area 
			FROM 	PType 
			WHERE	Deleted = 0
					AND ParId = @pParId
					AND TypeId <> '00000' 
					AND TypeId IN (SELECT * FROM F_GetUserManInfoForInput(@dbName,@TypeId,@ETypeId,'2'))
			ORDER BY UserCode
	END
ELSE
	BEGIN
		SELECT 	* 
		FROM 	dbo.F_Split(@TypeId,',') 
	END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetLoginUserManBaseInfoForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetLoginUserManBaseInfoForReport]
GO






/*
	描述：获取基本信息的资料
	作者：谢吉康
	日期：2009-8-15

	Web_GetLoginUserManBaseInfoForReport 'ptype','0000900007,000100000100001','0000100046'
*/

CREATE PROCEDURE Web_GetLoginUserManBaseInfoForReport
(
	@dbName		varchar(200),
	@TypeId		varchar(100),
	@IdList		varchar(8000),
	@ETypeId	varchar(100),
	@nFlag		varchar(10)			--0.上一层  1.下一层
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@pSonNum	int,
		@pParId		varchar(100)

SET @pSonNum = 0

SELECT @pSonNum = SonNum,@pParId = ParId FROM PType WHERE Deleted = 0 AND TypeId = @TypeId

IF @TypeId = '00000' OR @TypeId = '99999'
	SELECT 	DISTINCT P.TypeId,P.ParId,P.SonNum,P.UserCode,P.FullName
	FROM 	PType P
	LEFT JOIN (
		SELECT  * 
		FROM 	F_GetUserManInfoForReport(@dbName,@IdList)
	)M ON LEFT(M.A,LEN(P.TypeID)) = P.TypeId
	WHERE	Deleted = 0			
			AND ParId = '00000'
			AND TypeId <> '00000'
			AND TypeID IN (SELECT * FROM F_GetUserManInfoForReport(@dbName,@IdList))
	ORDER BY UserCode				
ELSE
	BEGIN
		IF @nFlag = '1'
			SELECT 	DISTINCT P.TypeId,P.ParId,P.SonNum,P.UserCode,P.FullName
			FROM 	PType P
			LEFT JOIN (
				SELECT  * 
				FROM 	F_GetUserManInfoForReport(@dbName,@IdList)
			)M ON LEFT(M.A,LEN(P.TypeID)) = P.TypeId
			WHERE	Deleted = 0			
					AND ParId = @TypeId
					AND TypeId <> '00000'
					AND TypeID IN (SELECT * FROM F_GetUserManInfoForReport(@dbName,@IdList))
			ORDER BY UserCode	
		ELSE
			SELECT 	DISTINCT P.TypeId,P.ParId,P.SonNum,P.UserCode,P.FullName
			FROM 	PType P
			LEFT JOIN (
				SELECT  * 
				FROM 	F_GetUserManInfoForReport(@dbName,@IdList)
			)M ON LEFT(M.A,LEN(P.TypeID)) = P.TypeId
			WHERE	Deleted = 0			
					AND ParId = @pParId
					AND TypeId <> '00000'
					AND TypeID IN (SELECT * FROM F_GetUserManInfoForReport(@dbName,@IdList))
			ORDER BY UserCode	
	END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'Web_GetMothProcInfos',N'P'))
BEGIN
	DROP PROC Web_GetMothProcInfos
END
GO
CREATE PROC Web_GetMothProcInfos
(
	@STypeID    VARCHAR(MAX),
	@OperatorID VARCHAR(50)
)
AS
BEGIN 
	DECLARE @IndependentOpen INT	--分支机构独立开账
	SELECT  @IndependentOpen=SubValue FROM SysData WHERE SubName='stypeindependentopen'

	SELECT A.STypeID,
		   C.FullName AS SFullName,
		   A.MonthNo,
		   A.StartDate,
		   A.EndDate,
		   A.comment,
		   A.period,
		   A.Year,
		   B.SFYear,
		   B.SFPeriod
	INTO #Tmp
	FROM dbo.MonthProc A 
	INNER JOIN (
		SELECT TypeID FROM dbo.F_AllTreeS(@OperatorID) A 
		INNER JOIN dbo.f_split(@STypeID,',') B ON A.TypeId LIKE b.a+'%' OR @STypeID='00000'
		WHERE sonnum=0 AND @IndependentOpen=1										--独立开账
		UNION ALL
		SELECT CASE WHEN @IndependentOpen=0 THEN '00000' ELSE '' END				--非独立开账
	) S 
	ON A.STypeID=S.TypeID 
	OR @IndependentOpen=0
	LEFT JOIN dbo.SType_UserConfig B ON A.STypeID=B.Stypeid
	LEFT JOIN dbo.SType C			 ON A.STypeID=C.TypeId
	WHERE @IndependentOpen=1 AND MonthNo='本期'
	 OR @IndependentOpen=0  --独立开账每个分支机构只查出一条显示
		
	DELETE A FROM #Tmp A,dbo.SType B WHERE A.STypeID=B.TypeId AND B.sonnum>0
	IF @IndependentOpen=1
	BEGIN
		UPDATE #Tmp SET SFYear=Year,SFPeriod=period FROM #Tmp A WHERE SFYear IS NULL OR SFPeriod IS NULL
		UPDATE #Tmp SET EndDate=FEnd FROM #Tmp A,dbo.Ac_Period B WHERE A.period=b.FPeriod AND a.Year=b.FYear
		UPDATE #Tmp SET period=sfperiod,Year=SFYear FROM #Tmp WHERE Year<SFYear OR (Year=SFYear AND period<SFPeriod)
		
			SELECT  *FROM #Tmp  GROUP BY STypeID,
							     SFullName,
							     MonthNo,
							     StartDate,
							     EndDate,
							     comment,
							     period,
							     Year,
							     SFYear,
							     SFPeriod
					    ORDER BY StartDate DESC
	END
	ELSE
	BEGIN
		--select monthno ,startdate,enddate,[year],period  from #Tmp group by monthno ,startdate,period,enddate,[year]
		--UPDATE #Tmp SET STypeID='00000',SFullName=''
		--UPDATE #Tmp SET comment='' WHERE comment IS NULL
		--UPDATE #Tmp SET comment='月结存' WHERE monthNo<>'本期'
		
		--DECLARE @StartDate DATETIME
		--SELECT @StartDate=MAX(StartDate) FROM #Tmp WHERE MonthNo='本期'
		--DELETE FROM #Tmp WHERE StartDate<>@StartDate AND MonthNo='本期'
		
		SELECT '00000' AS STYPEID,
			  '' AS SFullName,
			   A.MonthNo,
			   A.StartDate,
			   A.EndDate,
			   A.comment,
			   A.period,
			   A.[Year],
			   A.SFYear,
			   A.SFPeriod

		FROM (SELECT		 '00000'  as STYPEID,
							'' AS SFullName,
							a.MonthNo,
							a.StartDate,
							a.EndDate,
							CASE WHEN a.monthNo<>'本期' then '月结存' else ISNULL(a.comment,'') end as comment,
							A.period,
							a.[Year],
							a.[Year] AS SFYear,
							A.period AS SFPeriod
						FROM MonthProc A
						
						
			) A 
			group by A.monthno ,A.startdate,A.enddate,A.COMMENT,A.period,A.[year],A.SFYear,A.SFPeriod
			order by A.StartDate DESC
	END
	

							    
	DROP TABLE #Tmp
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetMultGoodsStocksQTY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetMultGoodsStocksQTY]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：王珏
	日期：2012-05-21
	描述：根据货位，批号，自由项，仓库，商品获取账面库存
	----------------------------------------------------------
	OneV 2016-09-18 手工指定法下面，库存不应该关联@GoodsCostPrice
	
*/
CREATE	PROCEDURE	Web_GetMultGoodsStocksQTY
(
	@ptypes	Tb_GoodsStocksQTY READONLY,
	@IfUseCargo         INT=0,				--是否启用货位:1启用，0未启用
	@ifwx				INT=0,				--是否是维修 0：否    1：是
	@ifcommission		INT=0				--是否是受托委托单据
)
--@encode$--
AS
SET NOCOUNT ON

Declare @costing int 

SELECT @costing=subvalue FROM sysdata where subname='costing'


DECLARE @talbename  VARCHAR(50)
IF @ifwx = 1
	SET @talbename = 'wx_GoodsStocks'
ELSE IF @ifcommission=1
	SET @talbename='CommissionStock_Qty'
ELSE
	SET @talbename = 'GOODSSTOCKS_QTY'

--IDENTITY(int,1,1) as Nid

--select IDENTITY(int,1,1) as nid
--		,* 
--into #ptypes
--from  @ptypes

declare @PTypeID			VARCHAR(50),		--商品ID
	@KTypeID			VARCHAR(50),		--仓库ID	
	@ItemID				INT,				--自由项ID
	@GoodsNumber		VARCHAR(100),		--批号	
	@CargoID			INT,				--货位ID
	@GoodsCostPrice		VARCHAR(50),		--成本价
	@producedate		VARCHAR(50),		--生产日期
	@validdate			VARCHAR(50),		--效期至
	@baseunitid			VARCHAR(10),		--基本单位
	@munitid			VARCHAR(10),		--销售单位
	@isSelectedGoodsNo  VARCHAR(3),
	@QtyDecimal			INT,
	@headSql			NVARCHAR(2000),
	@SQL				NVARCHAR(max),
	@nid				int,
	@maxnid				INT
	
select @maxnid = MAX(nid) from @ptypes
set @nid = 1
SELECT @QtyDecimal=DecimalDigit FROM dbo.DigitConfiguration WHERE ItemName='qty'

CREATE TABLE #result
(
	nid			INT,
	accountqty NUMERIC(24,10),
	saleunitqty	VARCHAR(200),
	buyunitqty	VARCHAR(200),
	stockunitqty	VARCHAR(200) 
)

set @headSql = '
	INSERT INTO #result ( nid,accountqty ,saleunitqty ,buyunitqty ,stockunitqty)
	SELECT @nid,
	a.qty as accountqty,
	CASE WHEN pu.saleunitrate = 1 THEN dbo.F_ClearInvalidDecimal(a.qty) + pu.saleunitname WHEN FLOOR(a.qty/pu.saleunitrate) > 0 THEN CAST(FLOOR(a.qty/pu.saleunitrate) AS VARCHAR) + pu.saleunitname ELSE '''' END +
	CASE WHEN pu.saleunitrate = 1 OR (a.qty % pu.saleunitrate) = 0 THEN '''' ELSE  dbo.F_ClearInvalidDecimal(CAST(round(a.qty % pu.saleunitrate,'+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + pu.baseunitname  END
	AS saleunitqty,
	
	CASE WHEN pu.buyunitrate = 1 THEN dbo.F_ClearInvalidDecimal(a.qty) + pu.buyunitname WHEN FLOOR(a.qty/pu.buyunitrate) > 0 THEN CAST((FLOOR(a.qty/pu.buyunitrate)) AS VARCHAR) + pu.buyunitname ELSE '''' END +
	CASE WHEN pu.buyunitrate = 1 OR (a.qty % pu.buyunitrate) = 0 THEN '''' ELSE  dbo.F_ClearInvalidDecimal(CAST(round(a.qty % pu.buyunitrate,'+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + pu.baseunitname  END
	AS buyunitqty,
	
	CASE WHEN pu.stockunitrate = 1 THEN dbo.F_ClearInvalidDecimal(a.qty) + pu.stockunitname WHEN FLOOR(a.qty/pu.stockunitrate) > 0 THEN CAST((FLOOR(a.qty/pu.stockunitrate)) AS VARCHAR) + pu.stockunitname ELSE '''' END +
	CASE WHEN pu.stockunitrate = 1 OR (a.qty % pu.stockunitrate) = 0 THEN '''' ELSE  dbo.F_ClearInvalidDecimal(CAST(round(a.qty % pu.stockunitrate,'+CAST(@QtyDecimal AS VARCHAR(10))+') AS VARCHAR)) + pu.baseunitname  END
	AS stockunitqty
	FROM
	(
		SELECT b.ptypeid, CAST(ISNULL(SUM(b.Qty),0) AS  NUMERIC(24, 10) ) as qty
		FROM   '+@talbename + ' b ' + CASE WHEN  @talbename!='CommissionStock_Qty' THEN ' WHERE  b.KTypeID=@KTypeID AND b.PTypeID=@PTypeID ' ELSE ' WHERE b.PTypeID=@PTypeID ' END


Create table #PtypeUnitTable
(
	PtypeId nvarchar(200),
	SaleUnitRate decimal(18,4),
	SaleUnitName varchar(200),
	BuyUnitRate decimal(18,4),
	BuyUnitName varchar(200),
	StockUnitRate decimal(18,4),
	StockUnitName varchar(200),
	BaseUnitName varchar(200)
)

while @nid <= @maxnid
begin
	
	select @PTypeID = ptypeid	
		  ,@KTypeID = ktypeid
		  ,@ItemID = itemid
		  ,@GoodsNumber = goodsnumber
			,@CargoID	= CargoID		
			,@GoodsCostPrice = GoodsCostPrice	
			,@producedate= producedate			
			,@validdate		= validdate		
			,@baseunitid	= baseunitid			
			,@munitid	= munitid			
			,@isSelectedGoodsNo = isSelectedGoodsNo	 
	from @ptypes 
	where nid=@nid
	
	IF ISNULL(@PTypeID,'') = ''
	BEGIN
		SET @nid += 1
		CONTINUE
	END 
	
	IF @GoodsCostPrice = '0'
		SET @GoodsCostPrice = ''
		
	IF @IfUseCargo=1 AND @CargoID=0 AND @ifwx = 0
		INSERT INTO #result( nid,accountqty ,saleunitqty ,buyunitqty ,stockunitqty)
		SELECT @nid, 0 as accountqty,0 as saleunitqty,0 as buyunitqty,0 as stockunitqty 
	ELSE
	BEGIN	
		--处理多单位库存
		--CREATE NONCLUSTERED INDEX PtypeUnitTableIndex ON #PtypeUnitTable(PTypeid)
		TRUNCATE TABLE #PtypeUnitTable
		
		IF @baseunitid<>'' AND @munitid<>'' AND @munitid<>'0'
		BEGIN
			INSERT INTO #PtypeUnitTable
			SELECT p.typeid AS ptypeid,mpue.rate,mpu.fullname,
			mpue.rate,mpu.fullname,mpue.rate,mpu.fullname,pu.FullName
			FROM ptype p
			left JOIN PType_Units_Ext mpue on mpue.ptypeid=p.typeId AND mpue.unitsid=@munitid
			left JOIN PType_Units mpu ON mpue.unitsid=mpu.unitsid 
			left JOIN PType_Units pu ON pu.unitsid  = @baseunitid
			WHERE p.typeid=@PTypeID
		END
		ELSE
		BEGIN
			INSERT INTO #PtypeUnitTable
			SELECT 
			p.typeid AS ptypeid,
			spue.Rate,spu.FullName,
			bpue.Rate,bpu.FullName,
			kpue.Rate,kpu.FullName,
			pu.FullName
			FROM ptype p
			left JOIN PType_Units_Ext spue on spue.ptypeid=p.typeId AND spue.unitsid=p.SaleUnitId
			left JOIN PType_Units spu ON spu.unitsid=p.SaleUnitId 
			left JOIN PType_Units_Ext bpue on bpue.ptypeid=p.typeId AND bpue.unitsid=p.BuyUnitId
			left JOIN PType_Units bpu ON bpu.unitsid=p.BuyUnitId 
			left JOIN PType_Units_Ext kpue on kpue.ptypeid=p.typeId AND kpue.unitsid=p.StockUnitId
			left JOIN PType_Units kpu ON kpu.unitsid=p.StockUnitId 
			left JOIN PType_Units pu ON pu.unitsid  = p.baseunitid
			WHERE p.typeid=@PTypeID
		END					
		
		SET @SQL = @headSql
		
		IF  @CargoID <> 0	
			SET @SQL = @SQL + ' AND b.CargoID=@CargoID '
			
		IF  @ItemID <> 0	
			SET @SQL = @SQL + ' AND b.ItemID=@ItemID' 
			
		IF  @ifwx <> 1 AND @GoodsCostPrice <> '' AND CAST(@GoodsCostPrice AS NUMERIC) >= 0 AND @costing<>0 AND @talbename!='CommissionStock_Qty'
			SET @SQL = @SQL + ' AND b.GoodsCostPrice=@GoodsCostPrice' 
			
		IF  @GoodsNumber <> ''	
		BEGIN
			SET @SQL = @SQL + ' AND b.GoodsNumber=@GoodsNumber'
			SET @SQL = @SQL + ' AND b.producedate=@producedate'	
			SET @SQL = @SQL + ' AND b.validdate=@validdate'
		END
		ELSE IF @GoodsCostPrice <> '' AND CAST(@GoodsCostPrice AS NUMERIC) >= 0	
		BEGIN
			SET @SQL = @SQL + ' AND b.producedate=@producedate '	
			SET @SQL = @SQL + ' AND b.validdate=@validdate '
		END
		ELSE IF @isSelectedGoodsNo = '1'
		BEGIN
			IF @costing = '3'
			BEGIN
				IF @producedate<>''
					SET @SQL = @SQL + ' AND b.producedate=@producedate '	
				IF @validdate<>''
					SET @SQL = @SQL + ' AND b.validdate=@validdate '
			END
			ELSE
			BEGIN
				SET @SQL = @SQL + ' AND b.producedate=@producedate '	
				SET @SQL = @SQL + ' AND b.validdate=@validdate '
			END
		END
		ELSE
		BEGIN
			IF  @ifwx <> 1 AND @producedate <> ''
			SET @SQL = @SQL + ' AND b.producedate=@producedate '	
			IF  @ifwx <> 1 AND @validdate <> ''
			SET @SQL = @SQL + ' AND b.validdate=@validdate '
		END
		
		IF @talbename!='CommissionStock_Qty'
			SET @SQL = @SQL + ' GROUP BY b.KTypeID,b.PTypeID'
		ELSE
			SET @SQL = @SQL + ' GROUP BY b.PTypeID'	
		
		IF  @CargoID <> 0	
			SET @SQL = @SQL + ',b.CargoID'
			
		IF  @ItemID <> 0	
			SET @SQL = @SQL + ',b.ItemID'
			
		IF  @GoodsNumber <> ''	
			SET @SQL = @SQL + ',b.GoodsNumber'
			
		IF  @ifwx <> 1 AND @GoodsCostPrice <> '' AND CAST(@GoodsCostPrice AS NUMERIC) >= 0 AND @talbename!='CommissionStock_Qty'
			SET @SQL = @SQL + ',b.GoodsCostPrice'
			
		IF  @ifwx <> 1 AND @producedate <> ''
			SET @SQL = @SQL + ',b.producedate'	
			
		IF  @ifwx <> 1 AND @validdate <> ''
			SET @SQL = @SQL + ',b.validdate'
		
		SET @SQL =@SQL+') a INNER JOIN #PtypeUnitTable pu ON a.PtypeId=pu.PtypeId'
		--print @sql
		--SELECT @SQL FOR XML PATH('')
		EXEC sp_executesql @SQL ,N'@KTypeID VARCHAR(50),
									@PTypeID VARCHAR(50),
									@ItemID				INT,			
									@GoodsNumber		VARCHAR(100),		
									@CargoID			INT,				
									@GoodsCostPrice		VARCHAR(50),	
									@producedate		VARCHAR(50),		
									@validdate			VARCHAR(50),	
									@nid				INT ', 
									@KTypeID,@PTypeID,@ItemID,@GoodsNumber,@CargoID,@GoodsCostPrice,@producedate,@validdate,@nid

	END						
	
	set @nid += 1																  		
END																					  			
																					  		
SELECT PTypeID,		
	KTypeID,		
	ItemID,				
	GoodsNumber,		
	CargoID,				
	GoodsCostPrice,		
	producedate,		--生产日期
	validdate,		--效期至
	baseunitid,		--基本单位
	munitid,		--销售单位
	isSelectedGoodsNo  ,
	ifwx,				--是否是维修 0：否    1：是
	ifcommission,				--是否是受托委托单据
	outcargoid,
	stypeid,
	orderid,
	p.nid,ISNULL(r.accountqty,0) AS accountqty ,ISNULL(r.saleunitqty ,0) AS saleunitqty,ISNULL(r.buyunitqty,0) AS buyunitqty,ISNULL(r.stockunitqty,0) AS stockunitqty 
FROM @ptypes p
LEFT JOIN  #result r ON r.nid = p.nid
ORDER BY p.nid															  		
																					  			
DROP TABLE #result,#PtypeUnitTable										  			
																					  			
																					    
GO																					  				
SET QUOTED_IDENTIFIER OFF															  		
GO																					  			
SET ANSI_NULLS ON																	  			
GO																					  			



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetOffRight]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetOffRight]
GO














/****** Object:  Stored Procedure dbo.Web_GetOffRight    Script Date: 2002-6-20 10:14:54 ******/

CREATE  PROCEDURE [DBO].[Web_GetOffRight] 
(
@FNum		[varchar](25),
@EtypeID	[varchar](25)='',
@UserCode	[varchar](26)='',
@FullName	[varchar](66)=''
)
--@encode$--
AS
SET NOCOUNT ON  
DECLARE @szSQL		[varchar](2000)
DECLARE @szWhere	[varchar](2000)
IF @FNum = ''  return -1
IF @EtypeID = '' 
BEGIN
Select @szWhere = ''
Select @szSQL='select e.typeid,e.usercode,e.fullname,isnull(f.Num,0)as Num,isnull(f.BarName,0)as BarName
   ,isnull(r.[Right]&1,0) as LRightVal,isnull(r.[Right]&2,0) as ARightVal,isnull(r.[Right]&4,0) as DRightVal,isnull(r.[Right]&8,0) as MRightVal
   from loginuser l inner join employee e on l.etypeid = e.typeid
   left outer join (select * from Off_Right where Ftypeid='''+@FNum+''') r on e.typeid = r.etypeid
   left outer join Off_Ftype f on r.ftypeId = f.Num'
IF @UserCode<>'' 
	Select @szWhere = @szWhere + ' AND e.UserCode like ''%' + @UserCode + '%'' '
IF @FullName<>'' 
	Select @szWhere = @szWhere + ' AND e.FullName like ''%' + @FullName + '%'' '
-- 去掉多余的 AND
IF @szWhere<>''
	SELECT @szWhere=' WHERE ' + Right(@szWhere,LEN(@szWhere)-4)
Select @szSQL= @szSQL + @szWhere +' order by e.typeid'
END
ELSE
BEGIN
-- 取以@FNum为父节点的所有栏目的权限列表
IF @FNum = '0' return -2
DECLARE @levelnum [INT],
 @layer1  [INT],
 @layer2  [INT],
 @layer3  [INT],
 @layer4  [INT],
 @layer5  [INT],
 @layer6  [INT],
 @iLoop  [INT]
Select @szSQL=''
Select @levelnum=[levelnum],@layer1=[layer1],@layer2=[layer2],@layer3=[layer3],@layer4=[layer4],@layer5=[layer5],@layer6=[layer6]
From Off_Ftype
where [Num]=@FNum
Select @iLoop = 0
IF @iLoop < @levelnum BEGIN select @szSQL=@szSQL+' and f.[layer1]='+cast(@layer1 as varchar)+' ' Select @iLoop=@iLoop+1 END
IF @iLoop < @levelnum BEGIN select @szSQL=@szSQL+' and f.[layer2]='+cast(@layer2 as varchar)+' ' Select @iLoop=@iLoop+1 END
IF @iLoop < @levelnum BEGIN select @szSQL=@szSQL+' and f.[layer3]='+cast(@layer3 as varchar)+' ' Select @iLoop=@iLoop+1 END
IF @iLoop < @levelnum BEGIN select @szSQL=@szSQL+' and f.[layer4]='+cast(@layer4 as varchar)+' ' Select @iLoop=@iLoop+1 END
IF @iLoop < @levelnum BEGIN select @szSQL=@szSQL+' and f.[layer5]='+cast(@layer5 as varchar)+' ' Select @iLoop=@iLoop+1 END
IF @iLoop < @levelnum BEGIN select @szSQL=@szSQL+' and f.[layer6]='+cast(@layer6 as varchar)+' ' Select @iLoop=@iLoop+1 END
-- 只显示当前的下一层栏目
Select @szSQL='Select f.*,r.[Right],(Cast([Right]&1 as varchar)+Cast(([Right]&2)/2 as varchar)+Cast(([Right]&4)/4 as varchar)+Cast(([Right]&8)/8 as varchar)) as szRight
  From Off_Right r inner join Off_Ftype f on r.FtypeID=f.Num
  Where f.allsee=0 and f.parent='+@FNum+' and r.EtypeID='''+@ETypeID+''' '
  +@szSQL+
  'union
  Select *,1 as [Right],''1000'' as szRight
  from Off_ftype
  where allsee=1 and parent='+@FNum+'
  Order By f.layer1,f.layer2,f.layer3,f.layer4,f.layer5,f.layer6'
END
--print @szSQL
EXEC(@szSQL)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetOftenMenu]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetOftenMenu]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
查询常用的10个菜单
Wang Wei 
EXEC Web_GetOftenMenu '00001',0
*/
CREATE           PROCEDURE Web_GetOftenMenu
(
	@OperatorID		varchar(50),
	@enablePlug		int  --1启用 0不启用 --插件添加
)
--@encode$--
AS
SET NOCOUNT ON	-- 返回结果不受影响

DECLARE @IsQp		INT,
		@EID		VARCHAR(100),
		@ETypeValue VARCHAR(10),
		@chkNav		VARCHAR(10),
		@chkNavCom	VARCHAR(10),
		@WherStr	VARCHAR(MAX)=''
		
SET @IsQp = 1
SET @EID = '4'
SET @ETypeValue = '0'
SELECT @chkNav = ISNULL(SubValue,''),@chkNavCom = ISNULL(SubComment,'') FROM dbo.sysdata WHERE SubName = 'setsysnavigation'
--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------

--V3、A8 
IF EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND (SubValue = '1' OR SubValue = '2' OR SubValue = '4'))
	SET @IsQp = 0

--V3、A8	
IF EXISTS(SELECT TOP 1 1 FROM dbo.hr_person WHERE [ID] = @EID AND [Password] = '1')
BEGIN	
	DELETE FROM OftenMenu
	DELETE FROM WebMenu
	UPDATE SYSDATA SET SubComment = SubValue WHERE SubName = 'setsysnavigation' AND ISNULL(SubComment,'') = ''
	UPDATE SYSDATA SET SubValue = '0' WHERE SubName = 'setsysnavigation'
END
ELSE
BEGIN
	UPDATE dbo.sysdata SET SubValue = @chkNavCom WHERE SubName = 'setsysnavigation' AND ISNULL(SubComment,'') <> ''
	UPDATE dbo.sysdata SET SubComment = '' WHERE SubName = 'setsysnavigation'
END

--9.2去掉1170年结菜单 1230 公司信息菜单
DELETE FROM OftenMenu WHERE MenuID=1170
DELETE FROM OftenMenu WHERE MenuID=1230
DELETE FROM OftenMenu WHERE MenuId like '170006%'


DECLARE @IsPost INT
SET @IsPost=0
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig  WHERE ConfigName = 'IsPosStart') --当系统配置中POST被关闭时，删除相关菜单
	OR EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName = 'IsPosStart' AND Value = '0')
		BEGIN
			DELETE FROM OftenMenu WHERE MenuID like '51010%'
			SET	@IsPost=1
		END

-- 判断是否启用货位
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'mngcargospace' AND Value = 1)
	DELETE FROM OftenMenu WHERE  MenuId  IN (1238,799,6901304,10102007)

---- 判断是否启用总账系统,非总账,去掉总账固定资产相关菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) 
	DELETE FROM OftenMenu WHERE MenuID IN (SELECT MenuID FROM WebMenu WHERE MenuID LIKE '56050%' )
	
--系统采用序列号严密管理，序列号关联货位，自由项，批次批号时，去掉序列号调整单
IF  EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='mngserial' AND Value = 1)  
		AND	EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='serialrelation' AND Value = 1)  
BEGIN
	DELETE FROM OftenMenu WHERE MenuID =9753
END

--是否启用多单位
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='doubleunit' AND Value=1)
	DELETE FROM OftenMenu WHERE MenuID=10102034

--未启用分支机构独立开账，则关闭启用期间设置这个菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'stypeindependentopen' AND SubValue = '1')
BEGIN
	DELETE FROM OftenMenu WHERE menuid IN (6100102)
END

--是否启用实物库存
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'isphysicalsstock' AND SubValue = '1')
BEGIN
	DELETE FROM OftenMenu WHERE MenuID IN ( SELECT MenuID FROM WebMenu WHERE MenuId IN (53010,1111,10103060) OR ParentId IN (53010,10103060))
	SET @WherStr+=' AND (M.MenuID NOT IN (53010,1111,10103060) AND M.ParentID NOT IN (53010,10103060))'
END

--序列号销售统计
IF NOT EXISTS(SELECT TOP 1 1 FROM Userconfig WHERE ConfigName='mngserial' AND Value = 1) OR EXISTS(SELECT * FROM SysData WHERE SubName='Edition' AND SubValue IN(1,6))
	BEGIN
		DELETE FROM	OftenMenu WHERE MenuID IN(502082)	
	END
--会员期初储值维护 V3/V1不显示此菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM Sysdata WHERE SubName = 'ProInfo' AND SubValue = '2')
	BEGIN
		DELETE FROM	OftenMenu WHERE MenuID IN(5701007)	
	END	
-----检查是否可使用序列号-----
DECLARE @checkSerial INT
IF EXISTS(SELECT SubNo FROM sysdata WHERE SubName='Edition' AND (SubValue=2 OR SubValue=5 OR SubValue=7 OR SubValue = 8))
	SET @checkSerial=1
ELSE
	SET @checkSerial=0
	
IF @checkSerial=1
	IF  EXISTS(SELECT SubNo FROM sysdata1 WHERE SubName='OffLine' AND (SubValue=4 OR SubValue=5 OR SubValue = 6 OR SubValue = 7 OR SubValue=10 OR SubValue=11))
		SET @checkSerial=1
	ELSE
		SET @checkSerial=0
--非序列号版本，删除序列号相关菜单
IF @checkSerial=0
BEGIN
	DELETE FROM OftenMenu WHERE MenuID IN ( SELECT MenuID FROM WebMenu WHERE MenuID = 975 OR ParentID = 975)
END

DECLARE @Assetssql VARCHAR(MAX)
--卡片模式和项目模式菜单处理
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='assets' AND SubValue = 1)
BEGIN
	--卡片模式去掉成本费用里的的固定资产,项目管理里的固定资产,数据搬移里的固定资产，固定资产期初
	DELETE FROM OftenMenu 
	WHERE MenuID IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040) 
	OR MenuID IN (SELECT MenuID FROM WebMenu WHERE ParentID IN(88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040) )
	SET @Assetssql=' AND (M.MenuID NOT IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040) AND M.ParentID NOT IN (88020,911,912,913,11001090,1010200904,1133,1010305030,1010305040))'
	--总账模式且 模板配置-固定资产管理无权限 去掉 一级 固定资产菜单 
	IF (EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig WHERE MenuID=561 AND IsChecked=1) AND EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig WHERE MenuID=560 AND IsChecked=1)) OR EXISTS(SELECT TOP 1 1 FROM MenuTemplateConfig WHERE MenuID=561 AND IsChecked=0)
		SET @Assetssql=' AND M.MENUID NOT LIKE ''561%'''
END
ELSE
BEGIN
	DELETE FROM OftenMenu 
	WHERE MenuID IN (56050) 
	OR MenuID IN (SELECT MenuID FROM WebMenu WHERE ParentID IN(56050))
	OR MenuID IN (SELECT MenuID FROM WebMenu WHERE ParentID IN(561))
	OR MenuID LIKE '56050%' --项目模式去掉总账里的固定资产
	SET @Assetssql=' AND M.MenuID NOT LIKE ''56050%'' AND M.MenuID NOT LIKE ''561%'''
END


DECLARE @invoicesql VARCHAR(MAX)
SET @invoicesql=''
--发票立账相关
IF NOT EXISTS(SELECT *FROM sysdata WHERE SubName='isinvoice' AND SubValue='1')
BEGIN
	DELETE FROM OftenMenu WHERE MenuID IN (52061,51021,8801691,8801792,1010301050,1010301060,1010302050,1010302060,1010304092,1010304093)
	DELETE FROM OftenMenu WHERE MenuID LIKE '52061%' OR MenuID LIKE '51021%'
	SET @invoicesql='AND M.MenuID NOT LIKE ''52061%'' AND M.MenuID NOT LIKE ''51021%'' 
	AND M.MenuID NOT IN (52061,51021,8801691,8801792,1010301050,1010301060,1010302050,1010302060,1010304092,1010304093) 
	'
END

--V1产品集中关闭菜单区域
IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'Proinfo' AND SubValue = '4')
BEGIN
	DELETE FROM	OftenMenu WHERE MenuID IN(10102035,59518,10102036,138040,138050) 
END

--非A8产品集中关闭菜单区域
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'Proinfo' AND SubValue = '2')
BEGIN
	DELETE FROM	OftenMenu WHERE MenuID=5701021
END

DECLARE @IsCombinationProduct INT
SELECT @IsCombinationProduct=SubValue FROM dbo.sysdata WHERE SubName='combinationproduct' 
IF	@IsCombinationProduct=0
BEGIN
	DELETE FROM dbo.OftenMenu WHERE MenuID='511070' OR MenuID='51107001'
END

DECLARE @isom VARCHAR(1) 
SET @isom =(SELECT COUNT(1) FROM sysdata WHERE SubName='IsOM' AND SubValue = 1)
--判断OM
IF @isom='0'
BEGIN
	--删除OM相关菜单
	DELETE FROM OftenMenu WHERE MenuID IN (516,517,1278)
END

--章鱼侠云WMS及网店解决方案  
IF EXISTS(SELECT 1 FROM sysdata WHERE SubName='usewms' AND SubValue = 0)
	BEGIN
		DELETE FROM OftenMenu WHERE MenuID IN (170011,17001101,17001102,17001103,17001104,17001105,17001106)
	END

DECLARE @AcSql VARCHAR(MAX)
SET @AcSql = ''
--非总账时，删除总账时相关菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1)
BEGIN
	DELETE FROM OftenMenu WHERE MenuID LIKE '88050%' OR MenuID IN (10102002,10102004,10102001,10102005,10102006,1096,1238,65589,10102010)
	SET @AcSql += ' AND M.MenuID NOT LIKE ''88050%'' AND MenuID NOT IN (10102002,10102004,10102001,10102005,10102006,1096,1238,65589,10102010) '
END

--没有启用品牌管理，删除菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'usebrandartype' AND SubValue = '1')
	BEGIN
		DELETE FROM OftenMenu WHERE MenuId IN(10102036,138040,138050,880302007,10102026)
	END
ELSE 
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'brandarcontrollineofcredit' AND SubValue = '0')
		BEGIN
			DELETE FROM OftenMenu WHERE MenuId IN(10102026)
		END
	END
--非成本算法去掉采购费用分摊
--9.7.1bug358非移动加权算法不显示成本计算菜单
IF NOT EXISTS(SELECT *FROM sysdata WHERE SubName='costing' AND SubValue='0')
BEGIN
	DELETE FROM OftenMenu WHERE  MenuId  IN (8804010,741,8804040)
	SET @AcSql+=' AND M.MenuID NOT IN (8804010,741,8804040)'
END
SET @AcSql=@AcSql+'  '+@Assetssql+' '+@invoicesql

CREATE  TABLE #webmenu  --插件添加
(
	countName INT,
	menuname VARCHAR(200),
	menuid INT,
	limitname VARCHAR(8000),
	offset INT 
)
--根据版本过滤是否过期 版本验证可能不完善 
DECLARE @currentdbversion VARCHAR(100),@mversion VARCHAR(10)
SELECT @currentdbversion=SubValue FROM dbo.sysdata WHERE SubName='Version'
SELECT @mversion=SubValue FROM dbo.sysdata WHERE subname='mVersion'
SELECT p.* 
INTO #Ord_PopUpPage
FROM dbo.Ord_PopUpPage p INNER JOIN dbo.Ord_Plug i ON p.plugid=i.id
WHERE LEN(i.AppropriateVerSion)<10 
	  OR ( CHARINDEX(@currentdbversion,i.AppropriateVerSion)>0 AND CHARINDEX(@currentdbversion+'*',i.AppropriateVerSion)<=0)
	  OR ( CHARINDEX(@currentdbversion+'*'+@mversion,i.AppropriateVerSion)>0)

--=========================9.7.1新增系统模块配置功能 筛选不在默认的菜单【BEGIN】=======================
DECLARE @ExcludeMenuId TABLE(MenuId		VARCHAR(100))
INSERT INTO @ExcludeMenuId(MenuId) EXEC Web_GetClearMenuId
--删除不在模块中的菜单
DELETE FROM OftenMenu WHERE MenuId IN (SELECT menuId FROM @ExcludeMenuId)
--============================处理期初单据菜单
DECLARE @Limit INT
CREATE TABLE #Temp(MenuId VARCHAR(100))
--销售管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=510
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103010 OR MenuID=10103010
--采购管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=520
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103020 OR MenuID=10103020
--维修管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=580
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103030 OR MenuID=10103030 
--往来管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=540
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103040 OR MenuID=10103040 
--成本费用管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=550
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE ParentID=10103050 OR MenuID=10103050
--会员卡券管理
SELECT @Limit=IsChecked FROM MenuTemplateConfig WHERE MenuID=570
IF(@Limit=0)
	INSERT INTO #Temp(MenuID)
	SELECT MenuID FROM WebMenu WHERE MenuID=501014
	
--=========================9.7.1新增系统模块配置功能 筛选不在默认的菜单【END】=======================

--是否启用账套，未启用的不显示常用菜单
IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='IsInvocation' AND SubValue = 1)
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM OftenMenu WHERE ETypeID=@OperatorID )
	BEGIN
		SELECT	TOP 10 MenuName,MenuID,LimitName 
		FROM	OftenMenu  a
		WHERE	a.ETypeID=@OperatorID
				AND Not EXISTS(SELECT TOP 1 1 FROM #Temp T WHERE T.MenuID=A.MenuID)
		ORDER BY ShowOrder ASC
	END
	ELSE 
	BEGIN
		DECLARE @SQL VARCHAR(MAX)	
		if @enableplug =1
		BEGIN
			
			SET @SQL ='
					select * into  #plugmenu from (
						select Eventid as LimitName,
									count(1) as countName,
									 p.name as MenuName,
									p.replacemenuid replacemenuid,
									-1 as offset
									from plug_EventLog e 
									inner join 
									( 
									   select id,case when isnull(replacemenuid,'''')='''' then ''-1'' else replacemenuid end as replacemenuid, offset,NAME,webmenuname as limitname
									   FROM dbo.Ord_PopUpPage 
									  ) p
									on p.limitname=e.Eventid '
				IF (@OperatorID<>'00001')
					SET @SQL=@SQL+'inner join
									( 
										SELECT DISTINCT c.id FROM [dbo].[Ord_PlugLimitFooting] a 
										INNER JOIN dbo.Ord_LimitList b ON a.LimitId=b.Id
										INNER JOIN dbo.Ord_PopUpPage c ON b.plugmenuid=c.Id and isnull(c.replacemenuid,'''')=''''
										WHERE b.[limittype] IN(1,7,10,19) and a.[Lim]=1 AND etypeid='+CHAR(39)+@OperatorID+CHAR(39)+'
										union all
										SELECT DISTINCT c.id FROM dbo.Ord_LimitList b 
										INNER JOIN dbo.Ord_PopUpPage c ON b.plugmenuid=c.Id and isnull(c.replacemenuid,'''')<>''''
										WHERE b.[limittype] IN(1,7,10,19) 
									)  limt
								    on p.id=limt.id '	
				SET @SQL=@SQL+' WHERE	e.ETypeID='+CHAR(39)+@OperatorID+CHAR(39)+'
					GROUP BY Eventid,p.replacemenuid,p.offset,p.name
					union all 
					select webmenuname as LimitName, 0 as countname, name as MenuName,isnull(replacemenuid,''0'') replacemenuid,
									-1 as offset 
					from Ord_PopUpPage
					WHERE NOT EXISTS (SELECT TOP 1 EventId FROM plug_EventLog WHERE webmenuname=EventId ) ) c
					
						insert into #webmenu(menuname,countName,menuid,limitname,offset)
						SELECT  DISTINCT(ac.menuname),ac.countName,ac.menuid,ac.limitname,ac.offset
						FROM (
									SELECT  
											a.EventID as LimitName,
											COUNT(1) as countName ,
											CASE '+CONVERT( varchar(10), @IsQp) +'
												WHEN 1 THEN REPLACE(m.Caption,''商品'',''配件'')
												ELSE m.Caption
											END as MenuName,
											m.MenuID,m.Offset
									FROM	EventLog a
									INNER JOIN WebMenu m ON a.EventId=m.Name
									WHERE	a.ETypeID='+CHAR(39)+@OperatorID+CHAR(39)+'
											AND a.Deleted=0
											AND M.IsSubMenu = 0'
					IF (@IsPost=1)										
					SET @SQL +='				AND M.MenuID NOT like ''51010%'''
					IF @IsCombinationProduct=0 
					SET @SQL +='                AND M.MenuID NOT LIKE ''511070%'''
					SET @SQL += @AcSql							
					SET @SQL +='			GROUP BY a.EventID,m.Caption, m.MenuID,m.Offset
									union all
									select LimitName,countName,MenuName,replacemenuid, offset from #plugmenu p 
									where replacemenuid='''' or (replacemenuid<>'''' and not exists(select 1 from eventlog where eventid =p.limitname))
									
							) ac  
							INNER JOIN loginuser lc ON  (CASE WHEN ('+CHAR(39)+@OperatorID+CHAR(39)+'=''00001'' OR offset=-1) THEN ''1'' ELSE substring(lc.lim,ac.Offset,1) END )=''1''
						ORDER BY countName desc					
						
						UPDATE #webmenu 
						SET menuname=w2.menuname,limitname=w2.limitname,countname=#webmenu.countname+ w2.countname,
							offset=w2.offset
						FROM #webmenu 
						INNER JOIN #plugmenu w2 ON #webmenu.menuid = w2.replacemenuid 
						where #webmenu.menuid <>''-1''
						

						SELECT top 10 SUM(countname) countname,menuname,menuid,limitname,offset
						FROM #webmenu W
						where 
							countname <>0 
							and ('+@isom+'=''1'' or menuid not in (516,517,1278))
							AND Not EXISTS(SELECT TOP 1 1 FROM #Temp WHERE MenuID=W.MenuID)
						GROUP BY menuname,menuid,limitname,offset
						order by sum(countname) desc
						'
		
			EXEC (@SQL)
		end
		else 
		begin	
			SET @SQL ='
						SELECT DISTINCT TOP 10  ac.* 
						FROM (
									SELECT  COUNT(1) as countName ,
											a.EventID as LimitName,
											CASE '+CONVERT( varchar(10), @IsQp) +'
												WHEN 1 THEN REPLACE(m.Caption,''商品'',''配件'')
												ELSE m.Caption
											END as MenuName,
											m.MenuID,m.Offset
									FROM	EventLog a
									INNER JOIN WebMenu m ON a.EventId=m.Name
									WHERE	a.ETypeID='+CHAR(39)+@OperatorID+CHAR(39)+'
											AND a.Deleted=0
											and ('+@isom+'=''1'' or M.MenuID not in (516,517,1278))
											AND M.IsSubMenu = 0'
			SET @SQL+=@WherStr
			
			IF (@IsPost=1)										
				SET @SQL +='				AND M.MenuID NOT like ''51010%'''
			IF @IsCombinationProduct=0
				SET @SQL +='                AND M.MenuID NOT LIKE ''511070%'''	
			SET @SQL += @AcSql							
			SET @SQL +='			GROUP BY a.EventID,m.Caption, m.MenuID,m.Offset
							) ac  
							INNER JOIN loginuser lc ON  (CASE WHEN '+CHAR(39)+@OperatorID+CHAR(39)+'=''00001'' THEN ''1'' ELSE substring(lc.lim,ac.Offset,1) END )=''1''
							WHERE Not EXISTS(SELECT TOP 1 1 FROM #Temp WHERE MenuID=ac.MenuID)					
						ORDER BY countName desc'
			EXEC (@SQL)
		end 
	END
END  
ELSE
	SELECT TOP 1 1 FROM dbo.OftenMenu WHERE 1 = 0 --空集合
	
DROP TABLE #Ord_PopUpPage,#Temp,#webmenu

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetOldDepInformationByCardID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_GetOldDepInformationByCardID
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-部门转移得到旧信息
-- 时间：2013-05-24
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_GetOldDepInformationByCardID
(
	@CardId			INT,		--固定资产卡片ID
	@OperatorID		VARCHAR(50)	--操作员ID
)
--@encode$--

AS
SET NOCOUNT ON 
--得到指定卡片ID的分支机构
DECLARE @StypeId VARCHAR(50)
SELECT 
	@StypeId=S.VerifyID 
FROM Ac_AssetsCards AC 
INNER JOIN SType S ON S.TypeId=AC.STypeId AND AC.Id=@CardId

SELECT 
	DISTINCT
	AC.Id CardId,
	AC.UserCode,
	AC.FullName,
	AC.DTypeid OldDtypeId,
	D.FullName OldDtypeFullName,
	AC.LocationId OldLocationId,
	S.Location OldLocationFullName,
	AC.LocationId LocationId,
	S.Location LocationFullName,
	AC.DisATypeId OldDisATypeId,
	CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE A.FullName END OldDisAtypeFullName
FROM Ac_AssetsCards AC
INNER JOIN SType ST ON ST.TypeId=AC.STypeId
LEFT JOIN Department D ON D.typeid=AC.DTypeid
LEFT JOIN Ac_AssetStorageLocation S ON S.Id=AC.LocationId
LEFT JOIN Ac_Account A ON A.TypeId=AC.DisATypeId AND A.StypeId=@StypeId
LEFT JOIN F_LineAccount(@OperatorID,@STypeId) F ON F.Typeid=A.TypeId AND F.Stypeid=A.StypeId
WHERE AC.Id=@CardId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetOperator]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetOperator]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2012-02-03
	描述：取得操作员
*/
CREATE PROCEDURE Web_GetOperator
(
	@ugid varchar(10),		--操作员所属用户组
	@filter varchar(50)='', --过滤条件
	@flag	varchar(10),		--查询标识 1.未分组用户 2.已分组用户
	@operatorId  varchar(2000)
)
--@encode$--
AS
SET NOCOUNT ON

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId('',3,@operatorId)

DECLARE @WHERE_SQL VARCHAR(2000)=''
DECLARE @SQL VARCHAR(8000)=''
IF @filter<>''
	SET @WHERE_SQL=' AND (e.FullName LIKE ''%' + @filter + '%'' OR e.UserCode LIKE ''%' + @filter + '%'' OR e.PyCode LIKE ''%' + @filter + '%'')'
--查询未分组用户
IF @flag = 1
BEGIN
	IF @ugid = -2
		SET @SQL='  SELECT	lu.belongToGroup,lu.etypeid,e.usercode,e.fullname 
					FROM	employee e 
					JOIN	loginuser lu ON e.typeid=lu.etypeid 
					inner join #GetManETypeId a on a.typeid = lu.etypeid 
					WHERE	lu.belongToGroup=0
							AND lu.isErp=''1''
							AND e.TypeId <> ''00001'' AND E.TypeId <> '''+@operatorId+''''+@WHERE_SQL
	ELSE
		SET @SQL='  SELECT	lu.belongToGroup,lu.etypeid,e.usercode,e.fullname 
					FROM	employee e 
					JOIN	loginuser lu ON e.typeid=lu.etypeid 
					inner join #GetManETypeId a on a.typeid = lu.etypeid 
					WHERE	e.TypeId <> ''00001'' 
							AND lu.isErp=''1''
							AND E.TypeId <> '''+@operatorId+'''
							AND lu.belongToGroup='+@ugid
END
--查询已分组用户
ELSE
	SET @SQL='      SELECT	lu.belongToGroup,lu.etypeid,e.usercode,e.fullname 
					FROM	employee e 
					JOIN	loginuser lu ON e.typeid=lu.etypeid 
					inner join #GetManETypeId a on a.typeid = lu.etypeid 
					WHERE	e.TypeId <> ''00001'' 
							AND lu.isErp=''1''
							AND lu.belongToGroup='''+@ugid+''' AND E.TypeId <> '''+@operatorId+''''+@WHERE_SQL

--PRINT(@SQL)
EXEC(@SQL)
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetOrderbill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetOrderbill
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2010-01-0-16
-- Description:  调订单明细
-- =============================================
CREATE PROCEDURE Web_GetOrderbill
(
	@billnumberid INT
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
DECLARE @IsCombined INT,@BillType INT
SELECT @BillType = billtype FROM dbo.OrderIndex WHERE billNumberId = @billnumberid
SELECT @IsCombined=IsCombined FROM OrderBill WHERE billNumberID=@billnumberid

--创建临时表，获取自定义字段
SELECT	cbd.*,e.fullname as efullnamecustom,
		p.fullname as pfullnamecustom,
		b.fullname as bfullnamecustom,
		d.fullname as dfullnamecustom,
		k.fullname as kfullnamecustom,
		s.fullname as sfullnamecustom,
		e1.fullname as efullnamecustom33,
		e2.fullname as efullnamecustom34,
		e3.fullname as efullnamecustom35,
		e4.fullname as efullnamecustom36,
		d1.fullname as dfullnamecustom37,
		d2.fullname as dfullnamecustom38,
		d3.fullname as dfullnamecustom39,
		d4.fullname as dfullnamecustom40 
INTO	#Custom_T
FROM	custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
LEFT JOIN employee e1 ON cbd.sysdiy33=e1.typeid
LEFT JOIN employee e2 ON cbd.sysdiy34=e2.typeid
LEFT JOIN employee e3 ON cbd.sysdiy35=e3.typeid
LEFT JOIN employee e4 ON cbd.sysdiy36=e4.typeid
LEFT JOIN department d1 ON cbd.sysdiy37=d1.typeid
LEFT JOIN department d2 ON cbd.sysdiy38=d2.typeid
LEFT JOIN department d3 ON cbd.sysdiy39=d3.typeid
LEFT JOIN department d4 ON cbd.sysdiy40=d4.typeid
WHERE cbd.BillId=@billnumberid AND cbd.BillType=@BillType

--订单临时表
SELECT *
INTO #TmpOrder
FROM dbo.OrderBill
WHERE billNumberID = @billnumberid

--和此订单有关的单据
CREATE TABLE #TmpBill
(
	OrderId	INT,
	BillDetailId	INT
)

--销售订单关联的销售出库、发出商品出库单
IF @BillType = 300
	INSERT INTO #TmpBill( OrderId, BillDetailId )
	SELECT  T3.OrderID,T2.ID
	FROM dbo.BillIndex T1
		INNER JOIN dbo.SaleBill T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN #TmpOrder T3 ON T2.OrderID = T3.OrderID
	WHERE T1.BillType = 11 AND T1.RedWord = 0
	
	UNION ALL
	
	SELECT T3.OrderID ,T2.ID
	FROM dbo.BillIndex T1
		INNER JOIN dbo.SendBill T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN #TmpOrder T3 ON T2.OrderID = T3.OrderID
	WHERE T1.BillType = 402 AND T1.RedWord = 0 
	
	UNION ALL
	
	SELECT T3.OrderID ,T2.ID
	FROM dbo.BillIndex T1
		INNER JOIN dbo.commissionbill T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN #TmpOrder T3 ON T2.OrderID = T3.OrderID
	WHERE T1.BillType = 140 AND T1.RedWord = 0 
	
ELSE--采购订单关联的采购入库、暂估入库
	INSERT INTO #TmpBill( OrderId, BillDetailId )
	SELECT  T3.OrderID,T2.ID
	FROM dbo.BillIndex T1
		INNER JOIN dbo.BuyBill T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN #TmpOrder T3 ON T2.OrderID = T3.OrderID
	WHERE T1.BillType = 34 AND T1.RedWord = 0
	
	UNION ALL
	SELECT  T3.OrderID,T2.ID
	FROM dbo.BillIndex T1
		INNER JOIN dbo.AppraisalBill T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN #TmpOrder T3 ON T2.OrderID = T3.OrderID
	WHERE T1.BillType = 400 AND T1.RedWord = 0
	
	UNION ALL
	
	SELECT T3.OrderID ,T2.ID
	FROM dbo.BillIndex T1
		INNER JOIN dbo.commissionbill T2 ON T1.BillNumberId = T2.BillNumberId
		INNER JOIN #TmpOrder T3 ON T2.OrderID = T3.OrderID
	WHERE T1.BillType = 144 AND T1.RedWord = 0 
	
	
SELECT DISTINCT OrderIndex.billNumberId,
	btype.FullName AS fhdw,
	T1.OrderID,
	qty = T1.Qty,
	Price = T1.Price,
    T1.Discount,
	T1.Tax,
	TaxPrice = T1.TaxPrice,
	DiscountPrice = T1.DiscountPrice,
	T1.TaxTotal,
	BigQty =
		CASE WHEN dbo.ptype.UnitRate1 = 0 THEN
			T1.Qty
		ELSE CAST(T1.Qty/dbo.ptype.UnitRate1 AS  NUMERIC(24, 10) ) END,
	T1.total as discounttotal,
	ReachQty = T1.ReachQty,
	T1.PassQty, 
	T1.SaleTotal as total,
	T1.Ktypeid,
	T1.frombillnumberid,
	T1.frombillid,
	T1.RequestBillNumberID,
	T1.RequestBillID,
	ptype.typeid,
	ptype.UserCode,
	ptype.FullName,
	CASE WHEN ISNULL(T1.entrycode,'')='' then ptype.EntryCode
	else T1.entrycode end as entrycode,
	ptype.Standard,
	ptype.Type,
	ptype.Area,
	ptype.Unit1 as unitone,
	ptype.Unit2 as unittwo,
	0 as UnitRate1,
	0 as UnitRate2,
	ptype.IfSerial,
	ptype.serialcount,
	ptype.validdays,
	ptype.usefullifeday,
	T1.comment as base,
	Stock.UserCode AS KUserCode,
	Stock.FullName AS KFullName,
	--CargoSpace.fullname AS CargoSpace,
	CustomerCode = (SELECT UserCode FROM PuserCode WHERE PtypeId = T1.PtypeId AND BtypeId = OrderIndex.DealBTypeID),
	IsUnit2 = 0,
	accountqty=(select  isnull(SUM(qty),0) from GoodsStocks where T1.ptypeid=ptypeid AND T1.ktypeid=ktypeid) ,
	T1.AskBillID as askbillid,   
	T1.AskBillNumberID as AskBillNumberID, 
	T1.requestbillid as requestbillid, 
	T1.RequestBillNumberID as requestbillnumberid,
	U.FullName AS munit ,							
	V.FullName AS nunit,
	W.FullName AS unit,
	T1.MUnitID, 							
	T1.NUnitID,
	T1.UnitID,
	T1.GoodsNumber,
	T1.MQty,
	T1.MUnitRate,
	T1.curmsaleprice,		 
	T1.nsaletotal,		 
	T1.nsaleprice,
	CASE WHEN ISNULL(T1.NUnitID,0) = 0 THEN NULL
	ELSE T1.unitrate END AS unitrate,
	CASE WHEN ISNULL(T1.NUnitID,0) = 0 THEN NULL
	ELSE T1.nqty END AS nqty,
	T1.curmdiscountprice,
	T1.ntotal,	
	T1.curmtaxprice,
	T1.ntaxmoney,
	T1.ntaxtotal,		 
	T1.taxmoney,
	T1.ItemID,
	T1.IsCombined,
	T1.NDiscountPrice,
	T1.NTaxPrice,
	T1.MSalePrice,
	T1.MDiscountPrice,
	T1.MTaxPrice,
	T1.GoodsCostPrice,
	T1.GoodsCostPrice AS GOODSNUMBERPRICE,
	T1.GoodsOrder,
	T1.ProduceDate,
	T1.ValidDate,
	T1.isgift,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname1,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname2,
	(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid)) as auxfullname3,
	(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate1,
	(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate2,
	(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=T1.ptypeid) as auxrate3,
	ptype.unitstype,
	ptype.customitemid,
	ptype.customitemfrom,
	ptype.customitemname,
	ptype.customitemrefid,
	itemname= CASE WHEN T1.IsCombined = 0  THEN
						    (SELECT FullName FROM xw_SelfData WHERE _Id= T1.ItemId)
					        ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= T1.ItemId ) END,
	T1.cargoid,	
	ct.fullname as cargofullname,
	T1.OrderID,		        
	T1.BillOver,
	T1.YapiID,	
	T1.isrequest,
	T1.oldcurmtaxprice,
	T1.oldqty,
	T1.LockNumber AS locknumber,
	CAST(ptype.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
	ISNULL(CASE WHEN st.pricetype=0 THEN pp.ReferPrice
	WHEN st.pricetype=1 THEN 
		CASE WHEN ISNULL(sp.Referprice,0)=0 THEN pp.ReferPrice
		ELSE sp.Referprice END
	END, 0) AS ReferPrice,
	ptype.IsService,
	T1.pricesource,
	--971 Bug 683
	CASE WHEN ISNULL(T2.BillDetailId,0) > 0 THEN 1
		 WHEN T1.ReachQty>0 THEN 1 
		 ELSE 0 END AS isref,
	T1.Id,
	promotype,
	dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2) AS salemunitcode,
	dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2)  AS buymunitcode,
	dbo.F_GetAllEntrycode(T1.pTypeID,T1.MUnitID,2)  AS stockmunitcode,
	T1.stopreason,
	cbd.*,
	isnull(T1.saleorderid,0) as saleorderid,--销售订单id
	isnull(T1.SaleOrderReachQty,0) AS SaleOrderReachQty,
	case when exists(select top 1 1 saleorderid from orderbill where saleorderid=T1.orderid) then 1 else 0 end as ifused, --明细行被采购订单调用
	bc.typeid AS brandartypeid,
	bc.fullname AS brandarfullname,
	(SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks g WHERE g.PtypeId = T1.pTypeID AND g.KtypeId = T1.ktypeid  ) AS showcostprice,
	isnull(T1.PTCombinOrderBillDetailID,0) as PTCombinOrderBillDetailID  --组合品销售订单id
FROM OrderIndex 
LEFT JOIN btype ON OrderIndex.btypeid = btype.typeId     
INNER JOIN #TmpOrder T1 ON OrderIndex.billNumberId = T1.billNumberID 
INNER JOIN ptype ON T1.ptypeid = ptype.typeId
LEFT JOIN dbo.brandar_Commodity bc ON bc.typeid = ptype.BrandarTypeId
LEFT JOIN PType_StypePrice sp ON sp.ptypeid=ptype.typeid AND sp.stypeid=OrderIndex.stypeid AND sp.UnitID = T1.MUnitID 
INNER JOIN stype st ON st.typeid=Orderindex.stypeid
LEFT JOIN PType_Price pp ON pp.PTypeID = ptype.TypeID AND pp.UnitID = T1.MUnitID 
LEFT JOIN Stock ON T1.KtypeId=Stock.typeId
LEFT JOIN xw_SelfData ON T1.ptypeid=xw_SelfData.typeId AND T1.ItemID=xw_SelfData._Id
LEFT JOIN CustomReferenceValue  ON T1.ItemID=CustomReferenceValue.id
LEFT JOIN PType_Units U ON U.UnitsId=T1.MUnitID 
LEFT  JOIN PType_Units V ON V.UnitsId=T1.NUnitID
LEFT  JOIN PType_Units W ON W.UnitsId=T1.UnitID
LEFT  JOIN CargoType ct ON T1.CargoID = ct.CargoID
LEFT JOIN #TmpBill T2 ON T1.orderid = T2.orderid
LEFT JOIN #Custom_T cbd ON cbd.billid=OrderIndex.billnumberid AND cbd.detailid=T1.orderid        
WHERE (OrderIndex.checked = 0 and OrderIndex.billNumberId=@billnumberid) 
ORDER BY dbo.OrderIndex.billNumberId ASC,T1.Id ASC,T1.OrderID ASC

DROP TABLE #TmpOrder,#TmpBill

END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetOrderbilldetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetOrderbilldetails
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2010-01-0-16
-- Description:  销售采购调订单明细
-- =============================================
CREATE PROCEDURE Web_GetOrderbilldetails
(
	@orderids varchar(max)
)
--@encode$--
AS
BEGIN	
	SET NOCOUNT ON

	DECLARE @IsCombined INT
	SELECT TOP 1 @IsCombined=IsCombined 
	FROM		OrderBill
	INNER JOIN  (select A from f_split(@orderids,',')) ids ON IDS.a=OrderBill.OrderID 
	
	SELECT o.* 
	INTO #orderdetails
	FROM dbo.OrderBill  o
	INNER JOIN (select A from f_split(@orderids,',')) ids ON IDS.a=O.OrderID
	
	SELECT DISTINCT i.* 
	INTO #orderindex
	FROM OrderIndex i 
	INNER JOIN #orderdetails o ON o.billNumberID = i.billNumberId

	--创建临时表，获取自定义字段
	/*
	SELECT	cbd.*,
			e.fullname as efullnamecustom,
			p.fullname as pfullnamecustom,
			b.fullname as bfullnamecustom,
			d.fullname as dfullnamecustom,
			k.fullname as kfullnamecustom,
			s.fullname as sfullnamecustom 
	INTO #Custom_T
	FROM custom_billdetails cbd
	LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
	LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
	LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
	LEFT JOIN department d ON cbd.sysdiy14=d.typeid
	LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
	LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
	*/
	SELECT	cbd.*,
		e.fullname as efullnamecustom,
		p.fullname as pfullnamecustom,
		b.fullname as bfullnamecustom,
		d.fullname as dfullnamecustom,
		k.fullname as kfullnamecustom,
		s.fullname as sfullnamecustom,
		e1.fullname as efullnamecustom33,
		e2.fullname as efullnamecustom34,
		e3.fullname as efullnamecustom35,
		e4.fullname as efullnamecustom36,
		d1.fullname as dfullnamecustom37,
		d2.fullname as dfullnamecustom38,
		d3.fullname as dfullnamecustom39,
		d4.fullname as dfullnamecustom40
	INTO #Custom_T
	FROM custom_billdetails cbd
	INNER JOIN (select A from f_split(@orderids,',')) ids ON IDS.a=cbd.detailid
	LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
	LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
	LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
	LEFT JOIN department d ON cbd.sysdiy14=d.typeid
	LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
	LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
	LEFT JOIN employee e1 ON cbd.sysdiy33=e1.typeid
	LEFT JOIN employee e2 ON cbd.sysdiy34=e2.typeid
	LEFT JOIN employee e3 ON cbd.sysdiy35=e3.typeid
	LEFT JOIN employee e4 ON cbd.sysdiy36=e4.typeid
	LEFT JOIN department d1 ON cbd.sysdiy37=d1.typeid
	LEFT JOIN department d2 ON cbd.sysdiy38=d2.typeid
	LEFT JOIN department d3 ON cbd.sysdiy39=d3.typeid
	LEFT JOIN department d4 ON cbd.sysdiy40=d4.typeid

	SELECT	i.billNumberId,
			o.GoodsNumber,
			o.OrderID,
			CASE WHEN  i.billtype=300 then  isnull(o.orderid,0) else 0 end  as saleorderid,--销售订单id
			isnull(O.SaleOrderReachQty,0) as SaleOrderReachQty,
			O.WaitQty,
			qty = o.Qty,
			Price = o.Price,
			o.Discount,
			o.Tax,
			TaxPrice = o.TaxPrice,
			DiscountPrice = o.DiscountPrice,
			o.TaxTotal,
			BigQty =	CASE WHEN p.UnitRate1 = 0 
								THEN o.Qty
							 ELSE CAST(o.Qty/p.UnitRate1 AS  NUMERIC(24, 10) ) 
						END,
			o.total as discounttotal,
			ReachQty = o.ReachQty,
			o.PassQty, 
			o.SaleTotal as total,
			o.Ktypeid,
			o.frombillnumberid,
			o.frombillid,
			o.RequestBillNumberID,
			o.RequestBillID,
			p.typeid,
			p.UserCode,
			p.FullName,
			CASE WHEN ISNULL(o.entrycode,'')='' then p.entrycode
			else o.entrycode end as entrycode,
			p.MultEntryCode AS multentrycode,
			p.Standard,
			p.Type,
			p.Area,
			p.Unit1 as unitone,
			p.Unit2 as unittwo,
			0 as UnitRate1,
			0 as UnitRate2,
			p.IfSerial,
			p.serialcount,
			p.validdays,
			p.usefullifeday,
			o.comment as base,
			s.UserCode AS KUserCode,
			s.FullName AS KFullName,
			--cs.fullname AS cs,
			PC.UserCode AS CustomerCode,
			IsUnit2 = 0,
			accountqty=(select  isnull(SUM(qty),0) from GoodsStocks where o.ptypeid=ptypeid AND o.ktypeid=ktypeid),
			 U.FullName AS munit,

			 V.FullName AS nunit,
			 W.FullName AS unit,
			 o.MUnitID,
			 o.NUnitID,
			 o.UnitID,
			 o.MQty,
			 o.curmsaleprice,
			 o.nsaletotal,
			 o.nsaleprice,
			 CASE WHEN ISNULL(o.nunitid,0) = 0 THEN NULL
			 ELSE o.unitrate END AS unitrate,
			 CASE WHEN ISNULL(o.nunitid,0) = 0 THEN NULL
			 ELSE o.nqty END AS nqty,
			 o.curmdiscountprice,
			 o.ntotal,
			 o.curmtaxprice,
			 o.ntaxmoney,
			 o.ntaxtotal,
			 o.taxmoney,
			 o.ItemID,
			 o.munitrate,
			 o.IsCombined,
			 p.customitemid,
			 p.customitemfrom,
			 p.customitemname,
			 p.customitemrefid,
			 p.unitstype,
			 o.NDiscountPrice,
			 o.NTaxPrice,
			 o.MSalePrice,
			 o.MDiscountPrice,
			 o.MTaxPrice,
			 o.cargoid,	
			 o.GoodsCostPrice,
			 o.GoodsCostPrice as goodsnumberprice,
			 o.GoodsOrder,
			 o.ProduceDate,
			 o.ValidDate,
			 o.IsGift,
			 (select EntryCode from PType_Units_Ext where PtypeID=o.pTypeID and UnitsId=U.UnitsId) AS munitcode,
			 ct.fullname as cargofullname,
			 CAST(p.IfUseGoodsNum AS INT) AS ifusegoodsnum,
			 itemname= CASE WHEN o.IsCombined = 0  THEN
					  (SELECT FullName FROM xw_SelfData WHERE _Id= o.ItemId)
					   ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= o.ItemId ) END,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId)) as auxfullname1,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId)) as auxfullname2,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId)) as auxfullname3,
			(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId) as auxrate1,
			(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId) as auxrate2,
			(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId) as auxrate3,
			p.IsService,
			CASE WHEN stype.pricetype=0 THEN pp.ReferPrice
			WHEN stype.pricetype=1 THEN 
				CASE WHEN ISNULL(sp.Referprice,0)=0 THEN pp.Referprice 
				ELSE sp.Referprice END
			END AS Referprice,
			o.pricesource,dbo.F_GetAllEntrycode(PUE.PTYPEID,PUE.UNITSID,2) AS salemunitcode,dbo.F_GetAllEntrycode(pu.PTYPEID,pu.UNITSID,2) as buymunitcode,cbd.*,
			p.brandartypeid,
			bc.FullName AS brandarfullname,
			(SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks g WHERE g.PtypeId = o.pTypeID AND g.KtypeId = o.ktypeid  ) AS showcostprice	 	
	FROM #orderindex i 
	LEFT JOIN btype b ON i.btypeid = b.typeId     
	INNER JOIN #orderdetails o ON i.billNumberId = o.billNumberID 	
	LEFT JOIN PuserCode PC ON PC.PtypeId = o.PtypeId AND PC.BtypeId = i.dealbtypeid
	INNER JOIN ptype p ON o.ptypeid = p.typeId
	LEFT JOIN dbo.brandar_Commodity bc ON bc.typeid = p.brandartypeid
	LEFT JOIN PType_Units_Ext pu ON p.typeid=pu.ptypeid AND o.munitid=pu.UnitsId
	INNER JOIN PType_Price pp ON pp.PTypeID = p.TypeID AND o.UnitID = pp.UnitID
	LEFT JOIN PType_StypePrice sp on sp.ptypeid=p.typeid AND sp.stypeid=i.stypeid AND o.UnitID=sp.UnitID
	inner join stype stype on stype.typeid=i.stypeid
	LEFT JOIN stock s ON o.KtypeId=s.typeId
	--LEFT JOIN CargoSpace cs ON o.ptypeid=cs.ptypeid AND o.ktypeid=cs.ktypeid
	--INNER JOIN (select A from f_split(@orderids,',')) ids ON IDS.a=O.OrderID
	LEFT JOIN
	  xw_SelfData ON o.ptypeid=xw_SelfData.typeId AND o.ItemID=xw_SelfData._Id
	LEFT JOIN
	  CustomReferenceValue  ON o.ItemID=CustomReferenceValue.id
	LEFT  JOIN  dbo.PType_Units U ON U.UnitsId=o.MUnitID 
	LEFT  JOIN  dbo.PType_Units V ON V.UnitsId=o.NUnitID
	LEFT  JOIN  dbo.PType_Units W ON W.UnitsId=o.UnitID
	LEFT  JOIN  CargoType ct ON o.CargoID = ct.CargoID
	LEFT JOIN PType_Units_Ext PUE ON PUE.PTYPEID=P.TYPEID AND PUE.UNITSID=o.munitid
	LEFT JOIN #Custom_T cbd ON  cbd.billid=i.billnumberid AND cbd.detailid=o.orderid AND cbd.billtype=i.billtype
	WHERE	i.checked = 0  ORDER BY ShowOrder ASC
	DROP TABLE #Custom_T,#orderdetails,#orderindex
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetOrderBillQtyAndReachQty]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetOrderBillQtyAndReachQty]
GO














/****** Object:  Stored Procedure dbo.Web_GetOrderBillQtyAndReachQty    Script Date: 2002-6-20 10:14:54 ******/

/*
功能说明：从OrderIndex、OrderBii、ptype表中根据BTypeID取出商品的存货量、发货量以及未发货量
输入参数：BTypeID
          StartDate 开始统计日期
   EndDate 结束统计日期
作者：李华
时间：2001-04-24
*/
CREATE  PROCEDURE Web_GetOrderBillQtyAndReachQty
( 
 @BTypeID varchar(25),
 @StartDate datetime,
 @EndDate datetime
)
--@encode$--
AS
SET NOCOUNT ON 
SELECT  
 ptype.UserCode,
 ptype.FullName,
 ptype.Unit1,
 SUM(OrderBill.qty) AS Qty, 
 SUM(OrderBill.total) AS QtyPrice,
 SUM(OrderBill.ReachQty) AS ReachQty, 
       SUM(OrderBill.price * OrderBill.ReachQty) AS ReachQtyPrice, 
       SUM(OrderBill.qty - OrderBill.ReachQty) AS RemainQty, 
       SUM(OrderBill.total - OrderBill.price * OrderBill.ReachQty) AS RemainQtyPrice
FROM
 OrderIndex INNER JOIN OrderBill ON OrderIndex.billNumberId = OrderBill.billNumberID
 INNER JOIN ptype ON OrderBill.ptypeid = ptype.typeId
WHERE 
 OrderIndex.btypeid = @BTypeID
 AND OrderIndex.BillDate <= @EndDate 
 AND OrderIndex.BillDate >= @StartDate
GROUP BY ptype.UserCode, ptype.FullName, ptype.Unit1















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetOrderIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetOrderIndex
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		黄飞佳
-- Create date: 2012-04-09
-- Description: 添加btype.CanNotModifyPrice
-- =============================================

-- =============================================    
-- Author:		毛欣蓉
-- Create date: 2012-01-16
-- Description: 掉订单主表
-- =============================================
-- 2013.05.23 周华 添加prepricenum
CREATE PROCEDURE Web_GetOrderIndex
(
	@billnumberid INT,
	@billtype INT=-1
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	
--创建临时表，获取表头自定义字段
--订单表头自定义,避免和其他单据表头查询重复,需用billtype区分
SELECT cbd.BillId,cbd.BillType,
cbd.SysDiy1_head as 'SysDiy1',cbd.SysDiy2_head as 'SysDiy2',cbd.SysDiy3_head as 'SysDiy3',cbd.SysDiy4_head as 'SysDiy4',
cbd.SysDiy5_head as 'SysDiy5',cbd.SysDiy6_head as 'SysDiy6',cbd.SysDiy7_head as 'SysDiy7',cbd.SysDiy8_head as 'SysDiy8',
cbd.SysDiy9_head as 'SysDiy9',cbd.SysDiy10_head as 'SysDiy10',cbd.SysDiy11_head as 'SysDiy11',cbd.SysDiy12_head as 'SysDiy12',
cbd.SysDiy13_head as 'SysDiy13',cbd.SysDiy14_head as 'SysDiy14',cbd.SysDiy15_head as 'SysDiy15',cbd.SysDiy16_head as 'SysDiy16',
cbd.SysDiy17_head as 'SysDiy17',cbd.SysDiy18_head as 'SysDiy18',cbd.SysDiy19_head as 'SysDiy19',cbd.SysDiy20_head as 'SysDiy20',
cbd.SysDiy21_head as 'SysDiy21',cbd.SysDiy22_head as 'SysDiy22',cbd.SysDiy23_head as 'SysDiy23',cbd.SysDiy24_head as 'SysDiy24',
cbd.SysDiy25_head as 'SysDiy25',cbd.SysDiy26_head as 'SysDiy26',cbd.SysDiy27_head as 'SysDiy27',cbd.SysDiy28_head as 'SysDiy28',
cbd.SysDiy29_head as 'SysDiy29',cbd.SysDiy30_head as 'SysDiy30',cbd.SysDiy31_head as 'SysDiy31',cbd.SysDiy32_head as 'SysDiy32',
cbd.SysDiy33_head as 'SysDiy33',cbd.SysDiy34_head as 'SysDiy34',cbd.SysDiy35_head as 'SysDiy35',cbd.SysDiy36_head as 'SysDiy36',
cbd.SysDiy37_head as 'SysDiy37',cbd.SysDiy38_head as 'SysDiy38',cbd.SysDiy39_head as 'SysDiy39',cbd.SysDiy40_head as 'SysDiy40',
e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_H
FROM Custom_BillIndex cbd
INNER JOIN dbo.OrderIndex oi ON cbd.BillType = oi.billtype AND cbd.BillId=oi.billNumberId
LEFT JOIN employee e ON cbd.sysdiy11_head=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12_head=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13_head=b.typeid
LEFT JOIN department d ON cbd.sysdiy14_head=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15_head=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16_head=s.typeid
WHERE cbd.BillId=@billnumberid
	
DECLARE  @tb as table  (
	billnumberid int,
	qty numeric(24,10),
	ReachQty numeric(24,10)
)	

INSERT INTO @tb(billnumberid,qty,ReachQty)
SELECT 	
		BillNumberID,
		sum(Qty) as Qty,
		sum(ReachQty) as ReachQty 
FROM 	PT_Combin_OrderBill 
WHERE billNumberID=@billnumberid						
GROUP BY BillNumberID
UNION ALL 
SELECT 	
	BillNumberID,
	sum(OrderBill.Qty) as Qty,
	sum(OrderBill.ReachQty) as ReachQty 
FROM 	OrderBill 
WHERE billNumberID=@billnumberid						
GROUP BY BillNumberID

		SELECT	
			Or1.billNumberId,
			btype.FullName AS bfullname, 
			Or1.BillDate, 
      		Or1.Billcode, 
			Or1.totalmoney, 
			Or1.Ntotalmoney,
			Or1.totalqty, 
      		Or1.comment, 
			Or1.IfAudit,
			employee.FullName AS efullname, 
			btype.PostCode, 
      		btype.TelAndAddress, 
			Or1.ReachDate, 
			Or1.WayMode, 
      		CASE Or1.BillStatus 
				WHEN 0 THEN '新增' 
				WHEN 1 THEN '审批中' 
				WHEN 2 THEN '已发货' 	
				WHEN 3 THEN '中止执行' 
			END AS BillStatus, 
      		Stock.FullName AS kfullname,
			Or1.btypeid,
			Or1.etypeid,
			Or1.ktypeid,
			Or1.dtypeid,
			Or1.Tax,
			btype.usercode AS busercode,
			Or1.PrePriceNum AS saleprice,		--ISNULL(btype.price,'0') AS saleprice, --A882 bug 1718
			Or1.PrePriceNum AS buyprice,			--ISNULL(btype.buyprice,'0') AS buyprice,--A882 bug 1718
			employee.usercode AS eusercode,
			stock.usercode AS kusercode,
			department.usercode AS dusercode,
			department.fullname AS dfullname,
			(select fullname from employee where typeid=Or1.checke) AS checke,
			CASE WHEN ISNULL(Or1.FromBillNumberID,0) = 0 THEN '0'
			ELSE (select top 1 oi.checke from orderindex oi where oi.billNumberId=Or1.FromBillNumberID) END AS createid,
			Or1.billtype,
			Or1.explain,
			Or1.WayBillCode,
			Or1.GoodsNumber,
			Or1.PackWay,
			Or1.TEL,
			OrderBill.Qty,
			OrderBill.ReachQty,
			Or1.OrderState,
			ISNULL(BType.ARlimitTime,0) AS ARLimitTime,
			ISNULL(BType.PaymentLTime,0) AS PaymentLTime,
			AuditingBill.BillDetail AS BillDetail,
			Or1.stypeid,
			ISNULL(SType.fullname,'') AS sfullname,
			Or1.CustomerTotal,
			Or1.NCustomerTotal,
			isnull(Or1.frombillnumberid,0) as frombillnumberid,
			ISNULL(btype.Consignee,''),
			ISNULL(btype.ConsigneeAddress,''),
			ISNULL(btype.ConsigneeTel,''),
			btype.CanNotModifyPrice,
			Or1.DealBTypeID,
			b.FullName AS dealbname, 
			CASE WHEN Or1.CID=0 THEN
				(select usercode from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
			ELSE
				(select usercode from Ac_Currency where cid=Or1.CID) END as usercode,
			CASE WHEN Or1.CID=0 THEN
				(select fullname from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
			ELSE
				(select fullname from Ac_Currency where cid=Or1.CID) END as fullname,
			CASE WHEN Or1.CID=0 THEN (SELECT TOP 1 cid FROM Ac_Currency WHERE Sysrow=1) ELSE Or1.CID END  as cid,		
			CASE WHEN Or1.CID=0 THEN
				(select rate from Ac_Currency where cid=(SELECT cid FROM Ac_Currency WHERE Sysrow=1)) 
			ELSE
				Or1.rate 
			END AS rate,
			(SELECT Sysrow FROM Ac_Currency WHERE CID=Or1.cid) as sysrow,
			Or1.prepricenum,
			CAST(Or1.IsYapi AS TINYINT) AS isyapi,
			Or1.YapiOrderID,
			ISNULL(or2.billNumberId,0) AS hassale,
			Or1.Discount,
			Or1.atypeid as nid,ai.usercode as ausercode,ai.fullname as afullname,Or1.totalinmoney,Or1.ntotalinmoney,
			CASE WHEN rbi.RelevanceBillId IS NULL THEN 0 ELSE 1 END AS iscreatepayorpre,
			or1.vipcardid,
			cbd.*
		FROM 	OrderIndex Or1
			LEFT JOIN dbo.OrderIndex Or2 ON or1.billNumberId = ISNULL(or2.FromBillNumberID,0) 
			LEFT JOIN btype ON Or1.btypeid = btype.typeId 
			LEFT JOIN btype b ON Or1.DealBTypeID = b.typeId 
			left JOIN employee ON Or1.etypeid = employee.typeId
     		left JOIN Stock ON Or1.ktypeid = Stock.typeId 
			LEFT JOIN department ON Or1.dtypeid = department.typeId   
			LEFT JOIN SType ON Or1.STypeID=stype.TypeId      
			LEFT JOIN AC_Items ai ON Or1.atypeid=ai.nid
			LEFT JOIN 
			(
				SELECT RelevanceBillId FROM PreBill p INNER JOIN BillIndex bi ON p.BillNumberId=bi.BillNumberId 
				AND bi.redword=0 WHERE RelevanceBillId>0
				UNION
				SELECT RelevanceBillId FROM PayBill p INNER JOIN BillIndex bi ON p.BillNumberId=bi.BillNumberId 
				AND bi.redword=0 WHERE RelevanceBillId>0
				UNION
				SELECT RelevanceBillId FROM GatheringBill p INNER JOIN BillIndex bi ON p.BillNumberId=bi.BillNumberId 
				AND bi.redword=0 WHERE p.RelevanceBillId>0 
			) rbi ON rbi.RelevanceBillId=Or1.billNumberId
			INNER JOIN  @tb as  OrderBill ON (Or1.billNumberID=OrderBill.billnumberid)
			LEFT  JOIN AuditingBill ON ( Or1.billNumberID = AuditingBill.billNumberID AND AuditingBill.BillindexType=0)
			LEFT  JOIN Ac_Currency ac ON ac.CId = Or1.CID
			LEFT JOIN #Custom_H cbd ON cbd.billid=Or1.billnumberid
		WHERE ( Or1.checked = 0  AND Or1.billNumberId=@billnumberid)
DROP TABLE #Custom_H
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_GetParaAssistItem]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].Web_GetParaAssistItem
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2013-07-23
	描述：根据选择的辅助核算项找出它的子类
*/
CREATE PROCEDURE Web_GetParaAssistItem
    (
      @type			INT,
      @paraitemid   VARCHAR(max),
      @usercode		VARCHAR(max)
    )
--@encode$--
AS 
    SET NOCOUNT ON
    DECLARE @result VARCHAR(max),
			@typeid	VARCHAR(50)
	CREATE TABLE #tempItems  --建立勾选的项目  
	(
		typeid   VARCHAR(50)
	)
IF @type=1 --分支机构
	BEGIN
		SELECT @typeid=TypeId FROM dbo.SType WHERE UserCode=@usercode
		IF @paraitemid=''
				INSERT INTO #tempItems 
				SELECT TypeId FROM SType WHERE deleted=0 AND parid<>'root'   AND sonnum=0
		ELSE     
				INSERT INTO #tempItems
				--SELECT b.TypeId FROM dbo.f_getparassistitem(@paraitemid,',') f JOIN dbo.SType b ON f.a=b.typeid
				--UNION 
				SELECT b.TypeId FROM dbo.f_split(@paraitemid,',') f JOIN dbo.SType b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0
	END
IF @type=2 --部门
	BEGIN
		 SELECT @typeid=TypeId FROM dbo.Department WHERE UserCode=@usercode
		 IF @paraitemid=''
				INSERT INTO #tempItems 
				SELECT TypeId FROM Department WHERE deleted=0 AND parid<>'root'   AND sonnum=0
		ELSE     
				INSERT INTO #tempItems
				--SELECT b.typeid FROM dbo.f_getparassistitem(@paraitemid,',') f JOIN dbo.Department b ON f.a=b.typeid
				--UNION 
				SELECT b.typeid FROM dbo.f_split(@paraitemid,',') f JOIN dbo.Department b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0
	END
IF @type=3 --职员
	BEGIN
		 SELECT @typeid=TypeId FROM dbo.employee WHERE UserCode=@usercode
		 IF @paraitemid=''
				INSERT INTO #tempItems 
				SELECT TypeId FROM employee WHERE deleted=0 AND parid<>'root' AND Parid<>'00000'  AND sonnum=0  
		ELSE     
				INSERT INTO #tempItems
				--SELECT b.typeid FROM dbo.f_getparassistitem(@paraitemid,',') f JOIN dbo.employee b ON f.a=b.typeid
				--UNION 
				SELECT b.typeid FROM dbo.f_split(@paraitemid,',') f JOIN dbo.employee b ON b.TypeId LIKE f.a+'%'  AND b.sonnum=0
	END
IF @type=4 --往来单位	
	BEGIN
		SELECT @typeid=TypeId FROM btype WHERE UserCode=@usercode 
		IF @paraitemid=''
				INSERT INTO #tempItems 
				SELECT TypeId FROM btype WHERE deleted=0 AND parid<>'root' AND sonnum=0
		ELSE     
				INSERT INTO #tempItems
				--SELECT b.typeid FROM dbo.f_getparassistitem(@paraitemid,',') f JOIN dbo.btype b ON f.a=b.typeid
				--UNION 
				SELECT b.typeid FROM dbo.f_split(@paraitemid,',') f JOIN dbo.btype b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0
	END
ELSE 
	BEGIN
		SELECT @typeid=TypeId FROM dbo.Ac_Assist_CheckItemsDetail WHERE UserCode=@usercode
		IF @paraitemid=''
				INSERT INTO #tempItems 
				SELECT TypeId FROM Ac_Assist_CheckItemsDetail WHERE AscIds=@type AND SonNum=0
		ELSE     
				INSERT INTO #tempItems
				SELECT b.TypeId FROM dbo.f_split(@paraitemid,',') f JOIN dbo.Ac_Assist_CheckItemsDetail b ON b.TypeId LIKE f.a+'%' AND b.sonnum=0
	END
		
	SELECT @result=(ISNULL(@result+',','') +  typeid) 
	FROM 
	(
		SELECT typeid FROM #tempItems WHERE typeid LIKE @typeid+'%' 
	) t GROUP BY typeid 
	
	SELECT @result AS typeid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetParentPath]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetParentPath]
GO


























/****** Object:  Stored Procedure dbo.Web_GetParentPath    Script Date: 2002-6-20 10:14:54 ******/

--得到某一基础信息的路径
CREATE        PROCEDURE Web_GetParentPath
(
  @operaterid varchar(50),
  @typeid VARCHAR(50),
  @flag int
 )
--@encode$--
AS
 SET NOCOUNT ON 
 if @typeid is null or @flag is null return 1
	DECLARE @type varchar(10)
	DECLARE @DBName varchar(100)
    if @flag=1  --atype
	BEGIN
		IF (LEFT(@TypeID,10) = '0000100003' OR LEFT(@TypeID,10) = '0000100004') AND NOT EXISTS(select * from dbo.F_BaseGetManAType(@operaterid) where typeid=@typeid)
		BEGIN
			select '' as path
			return
		END
		ELSE IF (LEFT(@TypeID,10) = '0000400003') AND NOT EXISTS(select * from dbo.F_BaseGetManATypeFy(@operaterid) where typeid=@typeid)
		BEGIN
			select ''  as path
			return
		END
		ELSE IF (LEFT(@TypeID,10) = '0000300003') AND NOT EXISTS(select * from dbo.F_BaseGetManATypeSr(@operaterid) where typeid=@typeid)
		BEGIN
			select ''  as path
			return
		END
		ELSE IF (LEFT(@TypeID,10) = '0000100002') AND NOT EXISTS(select * from dbo.F_BaseGetManATypeZc(@operaterid) where typeid=@typeid)
		BEGIN
			select ''  as path
			return
		END
	END
    else if @flag=2  --btype
	BEGIN
		IF NOT EXISTS(select * from dbo.F_BaseGetManBType(@operaterid) where typeid=@typeid)
		BEGIN
			select ''  as path
			return
		END
	END
    else if @flag=3  --employee
	BEGIN	
		IF NOT EXISTS(select * from dbo.F_BaseGetManEType(@operaterid) where typeid=@typeid)
		BEGIN
			select ''  as path
			return
		END
	END
    else if @flag=4  --ptype
	begin
		IF @typeid<>'00000' AND  NOT EXISTS(select * from dbo.F_BaseGetManPType(@operaterid) where typeid=@typeid)
		BEGIN
			select ''  as path
			return
		END
	end
    else if @flag=5  --stock
	BEGIN
		IF  @typeid<>'00000' AND  NOT EXISTS(select * from dbo.F_BaseGetManKType(@operaterid) where typeid=@typeid)
		BEGIN
			select ''  as path
			return
		END
	END
    else if @flag=9 --stype
	BEGIN
		IF  @typeid<>'00000' AND  NOT EXISTS(select * from dbo.F_BaseGetManSType(@operaterid) where typeid=@typeid)
		BEGIN
			select ''  as path
			return
		END
	END

	SET @Type = CASE WHEN @DBName = 'PType' THEN '2'
		WHEN @DBName = 'Employee' THEN '4'
		WHEN @DBName = 'BType' AND LEFT(@TypeID,5) = '00001' THEN '0'
		WHEN @DBName = 'BType' AND LEFT(@TypeID,5) = '00002' THEN '1'
		WHEN @DBName = 'Stock' THEN '3'
		WHEN @DBName = 'AType' AND (LEFT(@TypeID,10) = '0000100003' OR LEFT(@TypeID,10) = '0000100004') THEN '5'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000400003' THEN '6'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000300003' THEN '7'
		WHEN @DBName = 'AType' AND LEFT(@TypeID,10) = '0000100002' THEN '8'
		WHEN @DBName = 'SType'  THEN '9'
		END








declare @temp varchar(66),@parid VARCHAR(50),@path varchar(350)
 declare @i int

--判断是否为汽配
declare @ifqp varchar(1)
set @ifqp=(select subvalue from sysdata where subname='ifqp')

 select @typeid=rtrim(@typeid)
 select @path='＼'
 select @i=5
 while 1=1
 begin
  select @parid=Left(@typeid,@i)  
  if len(@parid)<=len(@typeid)
   begin
    if @flag=1  --atype
       select @temp=fullname from atype where typeid=@parid
    else if @flag=2  --btype
       select @temp=fullname from btype where typeid=@parid
    else if @flag=3  --employee
       select @temp=fullname from employee where typeid=@parid
    else if @flag=4  --ptype
       select @temp=fullname from ptype where typeid=@parid
    else if @flag=6  --ltype
       select @temp=fullname from ltype where typeid=@parid
    else if @flag=7  --DepartMent
       select @temp=fullname from DepartMent where typeid=@parid
    else if @flag=8  --ltype
       select @temp=fullname from AreaType where typeid=@parid
	else if @flag=9  --stype
       select @temp=fullname from SType where typeid=@parid  
    ELSE IF @flag=10 --Ac_CashMoneyItems   
	   select @temp=fullname from Ac_CashMoneyItems where typeid=@parid  
    else --stock
       select @temp=fullname from stock where typeid=@parid
if @ifqp='1'
begin
	if @temp='库存配件' select @temp='全部配件'
end
else 
begin
	if @temp='库存商品' select @temp='全部商品'
end
    if @temp='所有客户' select @temp='全部客户'
    if @temp='全部供货商'     select @temp='全部供货商'
    if @temp='超级用户' select @temp='全部职员'
    if @temp='全部仓库' select @temp='全部仓库'
    if @temp='所有部门' select @temp='所有部门'
    IF @temp='所有地区' SELECT @temp='全部地区档案'
    if @temp='root' and @flag=1
	 	select @temp='全部科目'
	if @temp='root' and @flag=6
	 	select @temp='全部货位'
	if @temp='root' and @flag=8
	 	select @temp='全部地区档案'
	if @temp='root' and @flag=9
	 	select @temp='全部分支机构'
	IF @temp='ABC' and @flag=10
		SELECT @temp='全部现金流量项目'
	
	if @flag=1 if @path='＼' and @temp<>'全部科目' select @temp='全部科目＼'+@temp
if @ifqp='1'
begin
	if @flag=4 if @path='＼' and @temp<>'全部配件' select @temp='全部配件＼'+@temp
end
else
begin
    if @flag=4 if @path='＼' and @temp<>'全部商品' select @temp='全部商品＼'+@temp
end
    if @flag=5 IF @path='＼' and @temp<>'全部仓库' select @temp='全部仓库＼'+@temp
    if @flag=6 if @path='＼' and @temp<>'全部货位' select @temp='全部货位＼'+@temp
    if @flag=7 if @path='＼' and @temp<>'所有部门' select @temp='所有部门＼'+@temp
    if @flag=8 if @path='＼' and @temp<>'全部地区档案' select @temp='全部地区档案＼'+@temp
	if @flag=9 
		if @path='＼' and @temp<>'全部分支机构' 
		begin 
			if(@parid='00000') select @temp='全部分支机构'
			else select @temp='全部分支机构＼'+@temp
		end
	IF @flag=10 IF @path='＼' and @temp<>'全部现金流量项目' select @temp='全部现金流量项目＼'+@temp
	
    select @path=@path+@temp+'＼'
    select @i=@i+5
   end
  if len(@parid)=len(@typeid)   break
 end 
 select path=@path


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetParentPath1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetParentPath1]
GO

/*
修改人：毛欣蓉
内容：将存储过程内容提取到函数F_GetPath中
时间：2010-07-27
*/

--得到某一基础信息的路径
CREATE             PROCEDURE Web_GetParentPath1
(
	@typeid 	VARCHAR(50),
	@flag 		INT,
	@szThePath 	VARCHAR(1000) OUTPUT
 )
--@encode$--
AS
SET NOCOUNT ON 

IF @typeid IS NULL OR @flag IS NULL RETURN 1

SET @szThePath=dbo.F_GetPath(@typeid,@flag)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPerformanceDistribute]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPerformanceDistribute]
GO



/*
	作者：谢吉康
	日期：2011-08-10
	描述：业绩分配
*/


CREATE PROCEDURE Web_GetPerformanceDistribute
(
    @OperatorID     VARCHAR(100) = '',
	@billnumberid	NUMERIC(18,0),		--单据ID
	@ntype			VARCHAR(100),		--操作类型 q=查询 m=修改
	@etypeid		VARCHAR(100) = '',	--分配职员
	@proportion		 NUMERIC(24, 10) =0,	--分配比例
	@total			 NUMERIC(24, 10) =0,	--分配金额
	@comment		VARCHAR(MAX) = '',	--备注
	@checke			VARCHAR(MAX) = '',	--制单人,
	@ptypeid		VARCHAR(100) = '',	--商品ID,
	@pid            VARCHAR(100) = '',	--明细ID,
	@discounttotal		 NUMERIC(24, 10) =0,	--折后金额,
	@costtotal			 NUMERIC(24, 10) =0,	--成本金额,
	@isptype            int =1,
	@billcomment		VARCHAR(MAX) = ''	--单据备注
	
)
--@encode$--
AS
SET NOCOUNT ON
--成本算法
DECLARE @costing INT
SELECT @costing=subvalue FROM sysdata where subname='costing'

--查询
IF @ntype = 'q'
BEGIN
	--先删除为0的记录
	--DELETE FROM PerformanceDistribution WHERE BillNumberId = @billnumberid AND Total = 0
	
	--先进先出，后进先出算法下costtal取INOUTSTOCKTABLE
	IF(@costing=1 OR @costing=2)
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM PerformanceDistribution WHERE BillNumberId = @billnumberid)
		BEGIN
			INSERT INTO PerformanceDistribution(BillNumberId,ETypeId,isptype)
			SELECT	BillNumberId,
					ETypeId,
					0 as isptype		
			FROM	BillIndex
			WHERE	BillNumberId = @billnumberid
		
			SELECT	P.BillNumberId, 
					P.pid as id,
					P.PTypeID, 
					P.ETypeID, 
					100 AS Proportion, 
					Bi.TotalMoney - Bi.preferencemoney AS Total, 
					P.CreateDate, 
					P.Checke, 
					P.Comment,
					p.billcomment,
					E.typeId,
					(select ee.UserCode from Employee ee INNER JOIN F_GetManETypeAll(@OperatorID)  fs on fs.typeid=ee.typeId where ee.typeid=E.typeId) as UserCode,
					(select ee.FullName from Employee ee INNER JOIN F_GetManETypeAll(@OperatorID)  fs on fs.typeid=ee.typeId where ee.typeid=E.typeId) as fullname,
					--E.UserCode,
					--E.FullName,
					p.ptypeid,
					p.discounttotal,
					s.costtotal AS inoutcosttotal,
					p.isptype,
					pt.usercode as ptypeusercode,
					pt.fullname as ptypefullname 
			FROM	PerformanceDistribution  P
			INNER JOIN employee E ON P.etypeid = e.typeId
			INNER JOIN BillIndex Bi ON Bi.BillNumberId = P.BillNumberId
			INNER JOIN (SELECT BillNumberId,SUM(CostTotal) AS CostTotal FROM INOUTSTOCKTABLE GROUP BY BillNumberId) s on p.billnumberid=s.billnumberid
			left JOIN ptype pt ON pt.typeid = P.ptypeid
			WHERE	P.BillNumberId = @billnumberid 
			ORDER BY E.UserCode
		END
		ELSE
		BEGIN		
			SELECT	P.BillNumberId, 
					P.pid as id,
					P.PTypeID, 
					P.ETypeID, 
					p.Proportion, 
					p.Total, 
					P.CreateDate, 
					P.Checke, 
					P.Comment,
					p.billcomment,
					E.typeId,
					(select ee.UserCode from Employee ee INNER JOIN F_GetManETypeAll(@OperatorID)  fs on fs.typeid=ee.typeId where ee.typeid=E.typeId) as UserCode,
					(select ee.FullName from Employee ee INNER JOIN F_GetManETypeAll(@OperatorID)  fs on fs.typeid=ee.typeId where ee.typeid=E.typeId) as fullname,
					--E.UserCode,
					--E.FullName,
					p.ptypeid,
					p.discounttotal,
					p.costtotal,
					s.costtotal AS inoutcosttotal,
					p.isptype,
					pt.usercode as ptypeusercode,
					pt.fullname as ptypefullname 
			FROM	PerformanceDistribution  P
			INNER JOIN employee E ON P.etypeid = e.typeId
			INNER JOIN BillIndex Bi ON Bi.BillNumberId = P.BillNumberId
			INNER JOIN (SELECT BillNumberId,SUM(CostTotal) AS CostTotal FROM INOUTSTOCKTABLE GROUP BY BillNumberId) s on p.billnumberid=s.billnumberid
			left JOIN ptype pt ON pt.typeid = P.ptypeid
			WHERE	P.BillNumberId = @billnumberid 
			ORDER BY E.UserCode
		END
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM PerformanceDistribution WHERE BillNumberId = @billnumberid)
		BEGIN
			INSERT INTO PerformanceDistribution(BillNumberId,ETypeId,isptype)
			SELECT	BillNumberId,
					ETypeId,
					0 as isptype		
			FROM	BillIndex
			WHERE	BillNumberId = @billnumberid
		
			SELECT	P.BillNumberId, 
					P.pid as id,
					P.PTypeID, 
					P.ETypeID, 
					100 AS Proportion, 
					Bi.TotalMoney - Bi.preferencemoney AS Total, 
					P.CreateDate, 
					P.Checke, 
					P.Comment,
					p.billcomment,
					E.typeId,
					(select ee.UserCode from Employee ee INNER JOIN F_GetManETypeAll(@OperatorID)  fs on fs.typeid=ee.typeId where ee.typeid=E.typeId) as UserCode,
					(select ee.FullName from Employee ee INNER JOIN F_GetManETypeAll(@OperatorID)  fs on fs.typeid=ee.typeId where ee.typeid=E.typeId) as fullname,
					--E.UserCode,
					--E.FullName,
					p.ptypeid,
					p.discounttotal,
					--s.costtotal AS inoutcosttotal,
					p.isptype,
					pt.usercode as ptypeusercode,
					pt.fullname as ptypefullname 
			FROM	PerformanceDistribution  P
			INNER JOIN employee E ON P.etypeid = e.typeId
			INNER JOIN BillIndex Bi ON Bi.BillNumberId = P.BillNumberId
			--INNER JOIN INOUTSTOCKTABLE s on p.billnumberid=s.billnumberid
			left JOIN ptype pt ON pt.typeid = P.ptypeid
			WHERE	P.BillNumberId = @billnumberid 
			ORDER BY E.UserCode
		END
		ELSE
		BEGIN		
			SELECT	P.BillNumberId, 
					P.pid as id,
					P.PTypeID, 
					P.ETypeID, 
					p.Proportion, 
					p.Total, 
					P.CreateDate, 
					P.Checke, 
					P.Comment,
					p.billcomment,
					E.typeId,
					(select ee.UserCode from Employee ee INNER JOIN F_GetManETypeAll(@OperatorID)  fs on fs.typeid=ee.typeId where ee.typeid=E.typeId) as UserCode,
					(select ee.FullName from Employee ee INNER JOIN F_GetManETypeAll(@OperatorID)  fs on fs.typeid=ee.typeId where ee.typeid=E.typeId) as fullname,
					--E.UserCode,
					--E.FullName,
					p.ptypeid,
					p.discounttotal,
					p.costtotal,
					--s.costtotal AS inoutcosttotal,
					p.isptype,
					pt.usercode as ptypeusercode,
					pt.fullname as ptypefullname 
			FROM	PerformanceDistribution  P
			INNER JOIN employee E ON P.etypeid = e.typeId
			INNER JOIN BillIndex Bi ON Bi.BillNumberId = P.BillNumberId
			--INNER JOIN INOUTSTOCKTABLE s on p.billnumberid=s.billnumberid
			left JOIN ptype pt ON pt.typeid = P.ptypeid
			WHERE	P.BillNumberId = @billnumberid 
			ORDER BY E.UserCode
		END
	END
END

--修改
IF @ntype = 'm'
BEGIN		
	INSERT INTO PerformanceDistribution
	(
		billnumberid,
		etypeid,
		proportion,
		total,
		checke,
		Comment,
		pid,
		ptypeid,
		discounttotal,
		costtotal,
		isptype,
		billcomment
	)VALUES(
		@billnumberid,
		@etypeid,
		@proportion,
		@total,
		@checke,
		@comment,
		@pid,
		@ptypeid,
		@discounttotal,
		@costtotal,
		@isptype,
		@billcomment
	)		
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPmPriceInfoUnits]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetPmPriceInfoUnits
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 

GO
/*
	作者：魏伟
	日期：2016-05-13
	描述：查找分支机构商品对应单位
	
	修改: 刘飞 2017-03-17 增加查找商品多单位ID
*/

CREATE PROCEDURE Web_GetPmPriceInfoUnits
(
	@OperatorId		VARCHAR(100),	--操作员ID 
	@PTypeId		VARCHAR(MAX) 	--商品ID	 
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查------------------------------------------------------------------------------------------------------------------------- 
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT typeid FROM F_GetManDetailPType(@OperatorId)
 
SELECT pu.UnitsId AS unitid,pu.FullName  
FROM PType_Units pu
INNER JOIN dbo.PType_Units_Ext pue ON pu.UnitsId = pue.UnitsId and pue.ratetype=0
INNER JOIN dbo.ptype p ON p.typeId=pue.PtypeID 
INNER JOIN #GetManPTypeId g ON g.TypeId=p.Typeid
WHERE p.typeId = @PTypeId 
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceByPriceRuleID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceByPriceRuleID]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		返回商品对应价格
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetPriceByPriceRuleID
(
	@ptypeid varchar(max),
	@freeid varchar(max),
	@iscombined int ,
	@unitid int,
	@unitrate   NUMERIC(24, 10) ,
	@stypeid varchar(max),
	@cid int,
	@ktypeid varchar(max),
	@etypeid varchar(max),
	@vipcardtypeid varchar(max),
	@dealbtypeid   varchar(max),
	@btypeid   varchar(max),
	@BillType	INT=0
)
--@encode$--
AS
SET NOCOUNT ON 


--取价规则临时表
CREATE TABLE #tempriceruleid
(
	id INT 
)

SET DATEFIRST 1

INSERT INTO  #tempriceruleid(id)
SELECT ID 
FROM PriceRule a
WHERE	
(
	(StartDate IS NULL  
		OR StartDate<=convert(varchar(10),getdate(),120)
	) 
	AND 
	(EndDate>=convert(varchar(10),getdate(),120) 
		OR EndDate is NULL
	)
)
AND		
( 
	( (StartTime='00:00' AND EndTime='00:00')
		OR (StartTime IS NULL AND EndTime IS NULL)
	) 
	OR
	(StartTime<=convert(varchar(10),getdate(),108) 
		AND EndTime>=convert(varchar(10),getdate(),108)
	)
)
AND	State=2
AND	(ISNULL( PriceDay,'')='' 
		OR CHARINDEX( CONVERT(varchar, datepart(weekday, getdate())),PriceDay)>0 
	)
AND	(@etypeid='00001' 
		OR EConfig=0 
		OR (EConfig=1 
				AND EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_EConfig e WHERE a.ID=e.PriceRuleID AND e.Etypeid=@etypeid)
			)
	)
	
AND	(KConfig=0 
		OR(KConfig=1 
			AND EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_KConfig k WHERE a.ID=k.PriceRuleID AND k.Ktypeid=@ktypeid)
		  )
	)
AND	(VipConfig=0 
		OR (VipConfig=1 AND @vipcardtypeid<>'') 
		OR EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_VipConfig v WHERE a.ID=v.PriceRuleID and v.VipTypeID=@vipcardtypeid)
	)
AND	(BConfig=0 
		OR (BConfig=1 AND EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_BConfig b WHERE a.ID=b.PriceRuleID AND b.BTypeID=@dealbtypeid)) 
		OR (BConfig=2 AND EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_BConfig b WHERE a.ID=b.PriceRuleID and b.BTypeID=@btypeid))
		OR (@Billtype IN (305,215) 
				AND EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_BConfig b WHERE a.ID=b.PriceRuleID AND b.BTypeID IN (@dealbtypeid,@btypeid))
			)
	)
	
--临时表
CREATE TABLE #Tem
(
	priceruleid INT,
	PriceBillIndexID INT,
	IsFreePrice	INT,
	IsDiscount	INT,
	IsUnitPrice	INT,
	IsRate		INT,
	pricebillfullname	VARCHAR(200),
	VipEnable	INT,
	BtypeEnable INT,
	VBEnable	INT
)

IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsCombinePrice' AND SubValue=0)
--不合并用临时表
INSERT INTO #Tem
        ( priceruleid ,
          PriceBillIndexID ,
          IsFreePrice ,
          IsDiscount ,
          IsUnitPrice ,
          IsRate ,
          pricebillfullname ,
          VipEnable ,
          BtypeEnable ,
          VBEnable
        )
SELECT TOP 1	a.ID AS priceruleid, 
				b.ID AS PriceBillIndexID,
				b.IsFreePrice,
				b.IsDiscount,
				b.IsUnitPrice,
				b.IsRate,
				b.FullName AS pricebillfullname,
				a.VipEnable,
				a.BtypeEnable,
				a.VBEnable
FROM PriceRule a 
	LEFT JOIN PriceRulePriority c ON a.ID=c.PriceRuleID 
	LEFT JOIN PriceBillIndex b ON a.PriceBillIndexID=b.ID 
WHERE a.ID IN (SELECT ID FROM #tempriceruleid)
	AND a.State=2
	AND CID=@cid
	AND	EXISTS(SELECT TOP 1 1 FROM PriceRule_Stype f WHERE a.ID=f.PriceRuleID AND f.Stypeid=@stypeid)
	AND ( (EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUnifiedPriority' AND SubValue=1) 
				AND c.StypeID='00000'
			)
			OR 
		  (EXISTS(SELECT TOP 1 1 FROM  sysdata WHERE SubName='IsUnifiedPriority' AND SubValue<>1) 
				AND c.StypeID=@stypeid
			)
		)
ORDER BY SortID

ELSE
--合并用临时表
INSERT INTO #Tem
        ( priceruleid ,
          PriceBillIndexID ,
          IsFreePrice ,
          IsDiscount ,
          IsUnitPrice ,
          IsRate ,
          pricebillfullname ,
          VipEnable ,
          BtypeEnable ,
          VBEnable
        )
SELECT  a.ID as priceruleid,
		b.ID as PriceBillIndexID,
		b.IsFreePrice,
		b.IsDiscount,
		b.IsUnitPrice,
		b.IsRate,
		b.FullName as pricebillfullname,
		VipEnable,
		BtypeEnable,
		VBEnable 
FROM PriceRule a  
	LEFT JOIN PriceBillIndex b ON a.PriceBillIndexID=b.ID 
WHERE a.ID IN(SELECT ID FROM #tempriceruleid) 
	AND a.State=2
	AND CID=@cid
	AND	EXISTS(SELECT TOP 1 1 FROM PriceRule_Stype f WHERE a.ID=f.PriceRuleID AND f.Stypeid=@stypeid)
			

----不合并取价
IF EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsCombinePrice' AND SubValue=0)
BEGIN
	SELECT TOP 1	Discount,
					Tax, 
					Price,
					DiscountPrice, 
					TaxPrice,
					IsUnitPrice,
					priceruleid,
					p.id AS pricedetailid ,
					PriceStyle,
					pricebillfullname,
					VipEnable,
					BtypeEnable,
					VBEnable,
					IsDiscount,
					IsRate
	FROM PriceDetail p  
	LEFT JOIN #Tem tem ON p.PriceBillIndexID=tem.PriceBillIndexID 
	WHERE p.Ptypeid =@ptypeid
	AND (IsFreePrice=0 
			OR  
			(IsFreePrice=1 
				AND p.FreeID=ISNULL(@freeid,0) 
				AND (p.IsCombined=@iscombined  OR ISNULL(p.IsCombined,0)=ISNULL(@iscombined,0)) 
			)
			OR
			(IsFreePrice=1 AND ISNULL(p.FreeID,0)=0 )
		)
	AND IsUnitPrice=1
	AND p.UnitId=@unitid
	AND p.State=2

	UNION

	SELECT  Discount,
			Tax,
			p.Price*@unitrate AS Price,
			p.DiscountPrice*@unitrate  AS DiscountPrice,
			p.TaxPrice*@unitrate   AS TaxPrice,
			IsUnitPrice,
			priceruleid,
			p.id AS pricedetailid ,
			PriceStyle,
			pricebillfullname,
			VipEnable,
			BtypeEnable,
			VBEnable,
			IsDiscount,
			IsRate
	FROM PriceDetail p   
	LEFT JOIN #Tem tem ON p.PriceBillIndexID=tem.PriceBillIndexID 
	WHERE p.Ptypeid =@ptypeid
	AND(IsFreePrice=0 
			OR
			(IsFreePrice=1 
				AND p.FreeID=ISNULL(@freeid,0) 
				AND (p.IsCombined=@iscombined  OR ISNULL(p.IsCombined,0)=ISNULL(@iscombined,0)) 
			)
			OR
			(IsFreePrice=1 AND ISNULL(p.FreeID,0)=0)
		)
	AND IsUnitPrice=0
	AND p.State=2
END
--合并取价
ELSE
BEGIN

	SELECT TOP 1	Discount,
					Tax,
					Price,
					DiscountPrice,
					TaxPrice,
					SortID ,
					res.priceruleid, 
					pricedetailid,
					PriceStyle,
					pricebillfullname,
					VipEnable,
					BtypeEnable,
					VBEnable,
					IsDiscount,
					IsRate
	FROM(
		SELECT Discount,
				Tax,
				p.Price,
				p.DiscountPrice,
				p.TaxPrice,
				IsUnitPrice,
				priceruleid,
				p.id AS pricedetailid,
				PriceStyle ,
				pricebillfullname ,
				VipEnable,
				BtypeEnable,
				VBEnable,
				IsDiscount,
				IsRate
		FROM PriceDetail p 
			LEFT JOIN #Tem tem ON p.PriceBillIndexID=tem.PriceBillIndexID 
		WHERE p.Ptypeid =@ptypeid
			AND p.UnitId=@unitid
			AND p.State=2
			AND IsUnitPrice=1
			AND(IsFreePrice=0 
				OR IsFreePrice=1  
						AND p.FreeID=ISNULL(@freeid,0) 
						AND (p.IsCombined=@iscombined  OR ISNULL(p.IsCombined,0)=ISNULL(@iscombined,0))
					
				OR IsFreePrice=1 AND ISNULL(p.FreeID,0)=0
			)
			
		UNION 
		
		SELECT  Discount,
				Tax,
				p.Price*@unitrate AS Price,
				p.DiscountPrice*@unitrate  AS DiscountPrice,
				p.TaxPrice*@unitrate   AS TaxPrice,
				IsUnitPrice,
				priceruleid,
				p.id AS pricedetailid ,
				PriceStyle,
				pricebillfullname,
				VipEnable,
				BtypeEnable,
				VBEnable,
				IsDiscount,
				IsRate
		FROM PriceDetail p 
			INNER JOIN #Tem tem ON p.PriceBillIndexID=tem.PriceBillIndexID 
		WHERE p.Ptypeid =@ptypeid
			AND IsUnitPrice=0
			AND p.State=2
			AND(IsFreePrice=0 
				OR IsFreePrice=1  
						AND p.FreeID=ISNULL(@freeid,0) 
						AND (p.IsCombined=@iscombined  OR ISNULL(p.IsCombined,0)=ISNULL(@iscombined,0))
					
				OR IsFreePrice=1 AND ISNULL(p.FreeID,0)=0
			)
	) res 
	LEFT JOIN PriceRulePriority c ON res.priceruleid=c.PriceRuleID 
	WHERE (EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUnifiedPriority' AND SubValue=1) 
				AND c.StypeID='00000'
		  )
			OR
		  (EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUnifiedPriority' and SubValue<>1) 
				AND c.StypeID=@stypeid
			)
	ORDER BY SortID 

END

DROP TABLE #tempriceruleid,#Tem


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceInfoByVipCard]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceInfoByVipCard]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		根据会员卡信息取出相应商品的商品会员卡信息
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetPriceInfoByVipCard
(
	@vipcardtypeid varchar(max),
	@pid varchar(max),
	@unitid varchar(100)	
)
--@encode$--
AS
SET NOCOUNT ON 


declare @price float 
declare	@discount float 
set @discount=-1;
set @price=-1;


declare 	@discounttype int 
select @DiscountType=DiscountType from nVipCardSet   
where VipCardTypeID=@vipcardtypeid

if(@DiscountType=1)
select @discount=VipDiscount1 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=2)
select @discount=VipDiscount2 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId  where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=3)
select @discount=VipDiscount3 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId  where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=4)
select @discount=VipDiscount4 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId  where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=5)
select @price=VipPrice1 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId  where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=6)
select @price=VipPrice2 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId  where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=7)
select @price=VipPrice3 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId  where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=8)
select @price=VipPrice4 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId  where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=9)
select @price=VipPrice5 from nVipGoodsSign a left join ptype b on a.Ptypeid=b.typeId  where pid=@pid AND a.UnitID=@unitid
else if(@DiscountType=10)
select @discount=CardTypeDiscount from nVipCardSet WHERE VipCardTypeID=(select VipCardTypeID from nVipCardSet   
where VipCardTypeID=@vipcardtypeid)

if(@DiscountType=0  or (@price=-1 and @discount=-1))
	select @discount=CardTypeDiscount from nVipCardSet where VipCardTypeID=@vipcardtypeid

select ISNULL(@discount,-1) as discount,ISNULL(@price,-1) as price
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceInfoByVipCardTable]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceInfoByVipCardTable]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		根据会员卡信息取出相应商品的商品会员卡信息
-- ========================================================================
CREATE  PROCEDURE Web_GetPriceInfoByVipCardTable
(
	@vipcardtypeid varchar(100),
	@ptypeinfo varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @carddiscount FLOAT,
		@DiscountType INT 

SELECT @DiscountType=DiscountType,@carddiscount = ISNULL(CardTypeDiscount,-1) 
FROM nVipCardSet   
WHERE VipCardTypeID=@vipcardtypeid

CREATE TABLE #tmp 
(
	pid INT,
	unitid INT,
	ptypeid	VARCHAR(50)
)
INSERT INTO #tmp( pid, unitid,ptypeid )
SELECT SUBSTRING(a,0,CHARINDEX(',',a)),SUBSTRING(a,CHARINDEX(',',a)+1,LEN(a)) ,p.typeId
FROM dbo.f_split(@ptypeinfo,';') f
INNER JOIN dbo.ptype p ON p.Pid = SUBSTRING(a,0,CHARINDEX(',',a))

CREATE TABLE #tmp2
(
	pid INT,
	unitid INT,
	discount FLOAT,
	price	FLOAT
)

IF @DiscountType=1
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,ISNULL(a.VipDiscount1,-1),-1 FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
ELSE IF(@DiscountType=2)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,ISNULL(a.VipDiscount2,-1),-1 FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
ELSE IF(@DiscountType=3)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,ISNULL(a.VipDiscount3,-1),-1 FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
ELSE IF(@DiscountType=4)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,ISNULL(a.VipDiscount4,-1),-1 FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
else if(@DiscountType=5)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,-1,ISNULL(a.VipPrice1,-1) FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
ELSE IF(@DiscountType=6)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,-1,ISNULL(a.VipPrice2,-1) FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
ELSE IF(@DiscountType=7)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,-1,ISNULL(a.VipPrice3,-1) FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
ELSE IF(@DiscountType=8)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,-1,ISNULL(a.VipPrice4,-1) FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
ELSE IF(@DiscountType=9)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,-1,ISNULL(a.VipPrice5,-1) FROM #tmp t
	LEFT JOIN  nVipGoodsSign a ON a.Ptypeid =t.ptypeid AND a.UnitID = t.unitid
END 
ELSE IF(@DiscountType=10 OR @DiscountType = 0)
BEGIN
	INSERT INTO #tmp2( pid,unitid, discount, price )
	SELECT t.pid,t.unitid,@carddiscount,-1 FROM #tmp t
END 

UPDATE #tmp2 SET discount = @carddiscount WHERE discount = -1 AND price = -1

SELECT CAST(pid AS VARCHAR)+',' +CAST(unitid AS VARCHAR) AS ptypeinfo,
       CAST(discount AS VARCHAR)+','+CAST(price AS VARCHAR) AS priceinfo
FROM #tmp2

DROP TABLE #tmp,#tmp2

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceListByBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceListByBillIndex]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则的价格表选择
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetPriceListByBillIndex
(
	@shusercode varchar(max),
	@shfullname varchar(max),
	@cid varchar(max),
	@stypeid varchar(max),
	@shexplain varchar(max),
	@shcomment varchar(max),
	@OperatorID varchar(max),
	@isAll		VARCHAR(10)		--WG 出所有价格表 1=全部
)
--@encode$--
AS
SET NOCOUNT ON 
declare @countt int ;
declare @sql nvarchar(max);

create table #tempp (stypeid varchar(max))


set @sql='insert into #tempp values('''+REPLACE(@stypeid,',','''),(''')+''')'

exec(@sql)

print @sql

set @sql='';
	set @sql='select @countt=count(*) from PriceBillIndex a
	left join Ac_Currency c on a.CID=c.CId '
	
	IF @isAll = 1
		SET @sql += ' WHERE 1=1 '
	ELSE 
		SET @sql += ' where  (a.state=1 or a.state=0) '

IF @isAll != 1
	set @sql=@sql+' and  a.ID in 
	(select b.PriceBillIndexID as ID from  PriceBillIndex_Stype b where b.stypeid  
	in( select * from   F_GetAllManagerBaseTypeId('''',11,'''+@OperatorID+''')))'

	if(@stypeid<>'')
	set @sql=@sql+ ' and not exists( select stypeid from #tempp where stypeid not in (select Stypeid from PriceBillIndex_Stype where PriceBillIndexID=a.ID ) )'
	
	
	
	if(ISNULL(@shusercode,'')<>'' )
		set @sql=@sql+' and   a.UserCode ='''+@shusercode+''''
	if(ISNULL(@shfullname,'')<>'' )
		set @sql=@sql+' and   a.FullName ='''+@shfullname+''' '
	if(ISNULL(@shexplain,'')<>'' )
		set @sql=@sql+' and   a.Explain ='''+@shexplain+''' '
	if(ISNULL(@shcomment,'')<>'' )
		set @sql=@sql+' and   a.Comment = '''+@shcomment+''' '
	if(ISNULL(@cid,'')<>'' )
		set @sql=@sql+' and   a.CID in ('+@cid+')'

		DECLARE @countt_OUT INT
		exec sp_executesql @sql,N'@countt int OUTPUT',@countt=@countt_OUT OUTPUT


if(@countt_OUT=1)--判断当精确匹配时，是否有数据，如果没有数据模糊匹配
begin--精确匹配
	set @sql='select a.id as pricebillindexid,a.UserCode,a.FullName,a.Explain,a.Comment,c.FullName as cidfullname from PriceBillIndex a
	left join Ac_Currency c on a.CID=c.CId '
	
	IF @isAll = 1
		SET @sql += ' WHERE 1=1 '
	ELSE 
		SET @sql += ' where  (a.state=1 or a.state=0) '
	
	IF @isAll != 1
		set @sql=@sql+' and  a.ID in (select b.PriceBillIndexID as ID from  PriceBillIndex_Stype b where b.stypeid  in( select * from   F_GetAllManagerBaseTypeId('''',11,'''+@OperatorID+''')))'

	if(@stypeid<>'')
	set @sql=@sql+ ' and not exists( select stypeid from #tempp where stypeid not in (select Stypeid from PriceBillIndex_Stype where PriceBillIndexID=a.ID ) )'
	
	
	if(ISNULL(@shusercode,'')<>'' )
		set @sql=@sql+' and   a.UserCode ='''+@shusercode+''''
	if(ISNULL(@shfullname,'')<>'' )
		set @sql=@sql+' and   a.FullName ='''+@shfullname+''' '
	if(ISNULL(@shexplain,'')<>'' )
		set @sql=@sql+' and   a.Explain ='''+@shexplain+''' '
	if(ISNULL(@shcomment,'')<>'' )
		set @sql=@sql+' and   a.Comment = '''+@shcomment+''' '
	if(ISNULL(@cid,'')<>'' )
		set @sql=@sql+' and   a.CID in ('+@cid+')'
end
else
begin--模糊匹配
	set @sql='select a.id as pricebillindexid,a.UserCode,a.FullName,a.Explain,a.Comment,c.FullName as cidfullname from PriceBillIndex a
	left join Ac_Currency c on a.CID=c.CId '
	
	IF @isAll = 1
		SET @sql += ' WHERE 1=1 '
	ELSE 
		SET @sql += ' where  (a.state=1 or a.state=0) '
	
	IF @isAll != 1
		set @sql=@sql+' and  a.ID in (select b.PriceBillIndexID as ID from  PriceBillIndex_Stype b where b.stypeid  in( select * from   F_GetAllManagerBaseTypeId('''',11,'''+@OperatorID+''')))'

	if(@stypeid<>'')
	set @sql=@sql+ ' and not exists( select stypeid from #tempp where stypeid not in (select Stypeid from PriceBillIndex_Stype where PriceBillIndexID=a.ID ) )'
	
	
	if(ISNULL(@shusercode,'')<>'' )
		set @sql=@sql+' and   a.UserCode like ''%'+@shusercode+'%'''
	if(ISNULL(@shfullname,'')<>'' )
		set @sql=@sql+' and   a.FullName like ''%'+@shfullname+'%'' '
	if(ISNULL(@shexplain,'')<>'' )
		set @sql=@sql+' and   a.Explain like ''%'+@shexplain+'%'' '
	if(ISNULL(@shcomment,'')<>'' )
		set @sql=@sql+' and   a.Comment like ''%'+@shcomment+'%'' '
	if(ISNULL(@cid,'')<>'' )
		set @sql=@sql+' and   a.CID in ('+@cid+')'
end
print @sql
exec(@sql);

drop table #tempp

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceRuleByID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceRuleByID]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则的价格表选择
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetPriceRuleByID
(
	@billindex varchar(max)
	
)
--@encode$--
AS
SET NOCOUNT ON 

select 
	ID		as billnumberid ,
	UserCode ,    -- 取价规则编号 
	FullName ,    -- 取价规则名称 
	PriceBillIndexID ,    -- 价格表ID 
	VipConfig ,    -- 规则条件设置之会员卡 0=不区分是否是会员  1=适用全部会员卡类型  2=适用部分会员卡类型  3=不适用部分会员卡类型 
	--StoresConfig ,    -- 门店配置  0=适用全部门店  1=使用部分门店  2=不使用部分门店 
	KConfig ,    -- 仓库配置  0=适用全部仓库  1=适用部分仓库  3=不适用部分仓库 
	DConfig ,    -- 部门设置 0=适用全部部分  1=适用部分部门  2=不适用部分部门 
	EConfig ,    -- 业务员配置  0=适用全部业务员  1=适用部分业务员  3=不适使用部分业务员
	BConfig,	 --适用部分往来单位结算单位 
	convert(varchar(10),StartDate,120) as  StartDate ,    -- 生效时期 
	convert(varchar(10),EndDate,120) as EndDate ,    -- 失效时期 
	StartTime ,    -- 开始时段 
	EndTime ,    -- 结束时段 
	PriceDay ,    -- 取价日设定星期1到7存1234567字符串 
	Comment ,    -- 备注 
	[State] ,    -- 单据状态0=新增 1=待审核  2=执行  3=作废 
	case when [State]=0 then '新增 ' when [State]=1 then '待审核 ' when [State]=2 then '执行 ' when [State]=3 then '作废 ' end  as statefullname ,
(select top 1 FullName from employee where employee.typeId=Checke  ) as 	CheckeName ,    -- 制单人 
Checke,
(select top 1 FullName from employee where employee.typeId=Checker  ) as 	CheckerName ,    -- 审核人 
Checker,
	convert(varchar(10),VaildDate,120) as VaildDate ,    -- 审核时期 
(select top 1 FullName from employee where employee.typeId=DeletedR  ) as 	DeletedRName ,    -- 作废人 
DeletedR,
	convert(varchar(10),DeletedDate,120) as DeletedDate ,    -- 作废时期 
	convert(varchar(10),CreateDate,120) as CreateDate,     -- 制单日期 
	PriceBillIndexID as pricebillindexid
	,
	(select top 1 FullName from PriceBillIndex where ID=PriceBillIndexID) as   pricetablefullname,
	dbo.F_GetPriceBillStypeID(@billindex) as stypeid,
	dbo.F_GetPriceBillStype(@billindex) as sfullname,
	VipEnable,
	BtypeEnable,
	VBEnable
	from pricerule where ID=@billindex
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceRuleDetailsByID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceRuleDetailsByID]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则的价格表选择
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetPriceRuleDetailsByID
(
	@billindex varchar(max),
	@detailstype varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 

if @detailstype='detailsVIP'
begin
select VipTypeID as viptypeid,startcardnum,endcardnum from PriceRule_Detail_VipConfig where PriceRule_Detail_VipConfig.PriceRuleID=@billindex
end
if @detailstype='detailsKT'
begin
select ktypeid,FullName as  kfullname,b.UserCode   as  ktypecode,ktypeid as typeid from PriceRule_Detail_KConfig a 
left join 
stock b on a.Ktypeid=b.typeid where a.PriceRuleID=@billindex
end
if @detailstype='detailsPRE'
begin
select etypeid as douserid,etypeid as typeid,FullName as  dousername,UserCode as  dousercode from PriceRule_Detail_EConfig a 
left join 
employee b on a.Etypeid=b.typeid where a.PriceRuleID=@billindex
end
if @detailstype='detailsBT'
begin
select btypeid as dobtypeid,btypeid as typeid,FullName as  dobtypename,UserCode as  dobtypecode from PriceRule_Detail_BConfig a 
left join 
btype b on a.btypeid=b.typeid  where a.PriceRuleID=@billindex
end



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceRuleList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceRuleList]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		打开零售单，按条件检索符合已经输入条件的价格规则，缓存于客户端
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetPriceRuleList
(
	@ktypeid varchar(max),
	@etypeid varchar(max),
	@stypeid varchar(max),
	@cid    int,
	@vipcardtypeid varchar(max),
	@dealbtypeid	VARCHAR(50) = '',
	@btypeid	VARCHAR(50)='',
	@billtype	INT = 0
)
--@encode$--
AS
SET NOCOUNT ON 

SET DATEFIRST 1-- 设定每周第一天为星期一

SELECT tem.*,pb.FullName AS pricename,pb.UserCode AS pricecode  
FROM 
(
	SELECT ID AS priceruleid,a.FullName AS rulename,a.UserCode AS rulecode,a.PriceBillIndexID 
	FROM PriceRule a
	WHERE	
	(( StartDate IS NULL OR StartDate<=CONVERT(VARCHAR(10),GETDATE(),120)) 
		AND (EndDate>=CONVERT(VARCHAR(10),GETDATE(),120) OR EndDate IS NULL))
	AND	( (StartTime='00:00' and EndTime='00:00' OR StartTime IS NULL AND EndTime IS NULL) 
				OR StartTime<=CONVERT(VARCHAR(10),GETDATE(),108) AND EndTime>=CONVERT(VARCHAR(10),GETDATE(),108))
	AND	State=2	
	AND (ISNULL( PriceDay,'')='' OR CHARINDEX( CONVERT(VARCHAR, DATEPART(weekday, GETDATE())),PriceDay)>0 )
	AND	(@etypeid='00001' or  EConfig=0 or EConfig=1 and  exists(select * from PriceRule_Detail_EConfig e where a.ID=e.PriceRuleID and e.Etypeid=@etypeid)) 
	AND	(KConfig=0 OR KConfig=1 AND EXISTS(SELECT * FROM PriceRule_Detail_KConfig k WHERE a.ID=k.PriceRuleID AND k.Ktypeid=@ktypeid))
	AND (EXISTS(SELECT * FROM PriceRule_Stype s WHERE s.PriceRuleID=a.ID and s.Stypeid=@stypeid))  
	AND (VipConfig=0 OR (VipConfig=1 AND @vipcardtypeid<>'') OR EXISTS(SELECT * FROM PriceRule_Detail_VipConfig v WHERE a.ID=v.PriceRuleID AND v.VipTypeID=@vipcardtypeid))
	AND	(BConfig=0 
			OR (BConfig=1 AND EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_BConfig b WHERE a.ID=b.PriceRuleID AND b.BTypeID=@dealbtypeid)) 
			OR (BConfig=2 AND EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_BConfig b WHERE a.ID=b.PriceRuleID and b.BTypeID=@btypeid))
			OR (@Billtype IN (305,215) 
				AND EXISTS(SELECT TOP 1 1 FROM PriceRule_Detail_BConfig b WHERE a.ID=b.PriceRuleID AND b.BTypeID IN (@dealbtypeid,@btypeid))
			)
	)

) tem left join PriceBillIndex pb on tem.PriceBillIndexID=pb.ID  
left join PriceRulePriority c on tem.priceruleid=c.PriceRuleID 
where pb.CID=@cid and exists(select * from sysdata where SubName='IsUnifiedPriority' and SubValue=1) and c.StypeID='00000'
or exists(select * from sysdata where SubName='IsUnifiedPriority' and SubValue<>1) and c.StypeID=@stypeid
order by SortID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceTableByID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceTableByID]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功能说明：		价格规则的价格表选择
-- 作者：		胡小科
-- 最后修改时间：	2013-05-14
-- ========================================================================
CREATE  PROCEDURE Web_GetPriceTableByID
(
	@pricetableid varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON 

select  
 case when State=0 then '新增' when State=1 then '待审核' when State=2 then '已审核' when State=3 then '作废' else '' end  as detailsstate,
 b.UserCode,
 b.FullName,
 b.typeId,
 c.FullName as munit,
 case when a.PriceStyle=0 then '单价' when a.PriceStyle=1 then '折后单价' when a.PriceStyle=2 then '含税单价' else '' end as PriceStyle,
 a.Price as curmsaleprice,
 a.Discount,
 a.DiscountPrice as curmdiscountprice,
 case when IsPriceControl=0 then '否' else '是' end as IsPriceControl,
 a.Comment as detailsComment,
 (select top 1 FullName from employee where employee.typeId=Checke  )  as detailsChecke ,    -- 制单人
 a.CreateDate as detailsCreateDate,
 (select top 1 FullName from employee where employee.typeId=Checker  ) as Checker ,
 a.VaildDate as detailsVaildDate,
 (select top 1 FullName from employee where employee.typeId=DeletedR  ) as DeletedR,
 a.DeletedDate as DeletedDate
from  PriceDetail a 
left join ptype b
on a.Ptypeid=b.typeId 
left join PType_Units c 
on a.UnitId=c.UnitsId
where a.PriceBillIndexID=@pricetableid
and [State]=2

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceTrackInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceTrackInfo]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE Web_GetPriceTrackInfo
(
	@cid					INT,			--币种
	@stypeid				VARCHAR(200),	--分支机构
	@btypeid				VARCHAR(200),	--结算单位
	@dealbtypeid			VARCHAR(200),	--往来单位
	@intBillType			VARCHAR(10)		--单据类型
)
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @PriceTrackTableName	VARCHAR(50) 					--价格跟踪保存在哪一张表中(普通价格跟踪)
DECLARE @StypePriceTrackTableName	VARCHAR(50) 				--价格跟踪保存在哪一张表中(分支机构价格跟踪)
DECLARE @buysaletype			INT								--单据是采购还是销售类,1=采购，2=销售
DECLARE @buysaleName			VARCHAR(30)='buypricetrack'		--采购或者销售价格跟踪参数名
DECLARE @btypeflag				INT								--跟踪的是往来单位还是结算单位 0结算单位,1往来单位,-1未启用
DECLARE @isBTypeTrack			INT = -1						--查询往来单位是否启用了价格跟踪
DECLARE @stypePriceTrack_buy	INT =0							--采购类单据是否启用了分支机构价格跟踪
DECLARE @stypePriceTrack_sale	INT =0							--销售类单据是否启用了分支机构价格跟踪
DECLARE @IsOrdinaryPriceTrack	INT =0							--是否启用了普通价格跟踪:0未启用，1启用
DECLARE @SQL					VARCHAR(MAX)

----------------------------------初始化相关参数  start ----------------------------------
--普通价格跟踪表
SELECT 
@PriceTrackTableName=tracktablename,
@buysaletype=buysaletype 
FROM PriceTrackNameBillSet 
WHERE billtype=@intBillType and getsettype='2'

--分支机构价格跟踪表
SELECT 
@StypePriceTrackTableName=tracktablename
FROM PriceTrackNameBillSet 
WHERE billtype=@intBillType and getsettype='4'

--如果询价单、采购订单、暂估入库单取价设置为取采购价格，则直接获取采购入库单的价格跟踪表名
DECLARE @isGetBuyPriceTrack INT = 0
SELECT @isGetBuyPriceTrack = [VALUE] FROM PriceTrackConfig WHERE Name=
(
	CASE WHEN @intBillType=185 THEN 'askpricetrack' WHEN @intBillType=301 THEN 'buyorderpricetrack' 
	WHEN @intBillType IN (400,401) THEN 'zangupricetrack' END
)
IF(@isGetBuyPriceTrack = 2 AND @intBillType=185)
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
END
IF(@isGetBuyPriceTrack = 2 AND @intBillType=301)
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
END
IF(@isGetBuyPriceTrack = 2 AND @intBillType IN (400,401))
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
END

--如果报价单、销售订单、发出商品出库单取价设置为取小数价格，则直接获取销售出库单的价格跟踪表名
DECLARE @isGetSalePriceTrack INT = 0
SELECT @isGetSalePriceTrack = [VALUE] FROM PriceTrackConfig WHERE Name=
(
	CASE WHEN @intBillType=184 THEN 'quotepricetrack' WHEN (@intBillType=300 OR @intBillType=313) THEN 'saleorderpricetrack' 
	WHEN @intBillType IN(402,403) THEN 'fachupricetrack' END
)
IF(@isGetSalePriceTrack = 2 AND @intBillType=184)
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
END
IF(@isGetSalePriceTrack = 2 AND (@intBillType=300 OR @intBillType=313))
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
END
IF(@isGetSalePriceTrack = 2 AND @intBillType IN(402,403))
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
END

IF @buysaletype =1 
BEGIN
	SET @buysaleName='buypricetrack'
END
ELSE IF @buysaletype = 2
BEGIN
	SET @buysaleName='salepricetrack'
END
SELECT @IsOrdinaryPriceTrack=VALUE FROM PriceTrackConfig WHERE NAME=@buysaleName
SELECT @stypePriceTrack_buy=[value] FROM PriceTrackConfig WHERE NAME='buystypepricetrack'
SELECT @stypePriceTrack_sale=[value] FROM PriceTrackConfig WHERE NAME='salestypepricetrack'

IF @buysaletype=1
BEGIN
	SELECT @btypeflag=value  FROM PriceTrackConfig WHERE name='BuyBtypeFlag'
END
ELSE IF	@buysaletype=2
BEGIN	
	SELECT @btypeflag=value FROM PriceTrackConfig  WHERE name='SaleBtypeFlag'
END

--判断是否启用了结算单位价格跟踪
IF @btypeflag = 0
BEGIN
	SELECT @isBTypeTrack = PriceTrackEnable from BType WHERE typeid=@btypeid
END
--判断是否启用了往来单位价格跟踪
ELSE IF @btypeflag = 1
BEGIN
	SELECT @isBTypeTrack = PriceTrackEnable from BType WHERE typeid=@dealbtypeid
END

----------------------------------初始化相关参数  end -----------------------------------
IF @intBillType IN ('11','12','34','300','313','301','6','45','46','305','140','141','142','160','161','144','145','146','187','188','184','185','215','400','401','402','403')
BEGIN	
	SET @SQL = '
	SELECT	t.PTypeId,
			SUM(t.DiscountRate) AS DiscountRate,
			SUM(t.DiscountPrice) AS DiscountPrice,
			SUM(t.Price) AS Price,
			SUM(t.tax) AS tax,
			SUM(t.TaxPrice) AS TaxPrice,
			SUM(t.DiscountRateStype) AS DiscountRateStype,
			SUM(t.DiscountPriceStype) AS DiscountPriceStype,
			SUM(t.PriceStype) AS PriceStype,
			SUM(t.taxStype) AS taxStype,
			SUM(t.TaxPriceStype) AS TaxPriceStype,
			t.[uid],
			'''+convert(varchar(2),@btypeflag)+''' as isbtypetrack,
			0 AS pricetracksource 
	FROM (
			SELECT 
			pt.PTypeId,'
			+CASE WHEN @isBTypeTrack = 1 THEN '
			pt.DiscountRate,
			pt.DiscountPrice,
			pt.Price,
			pt.tax,
			pt.TaxPrice, '
			ELSE '
			0 as DiscountRate,
			0 as DiscountPrice,
			0 as Price,
			0 as tax,
			0 as TaxPrice,
			' END +'
			pt.[uid],
			0 as DiscountRateStype,
			0 as DiscountPriceStype,
			0 as PriceStype,
			0 as taxStype,
			0 as TaxPriceStype
			FROM '+ @PriceTrackTableName +' pt 
			WHERE 1=1 '+CASE WHEN @btypeflag=0 THEN ' 
			AND pt.BTypeID='''+@btypeid +'''' ELSE ' 
			AND pt.BTypeID='''+@dealbtypeid +'''' END +' 
			AND pt.Stypeid = '''+@stypeid+'''
			AND pt.BtypeFlag='''+CONVERT(VARCHAR(2),@btypeflag)+'''
			AND pt.CID = '+CONVERT(VARCHAR(10),@cid)+'
			UNION ALL
			SELECT 
			pt.PTypeId,
			0, 
			0, 
			0, 
			0, 
			0, 	
			pt.[uid],
			pt.DiscountRate,
			pt.DiscountPrice,
			pt.Price,
			pt.tax,
			pt.TaxPrice
			FROM '+@StypePriceTrackTableName+' pt 
			WHERE 1=1 
			'+CASE WHEN @btypeflag=0 THEN ' 
			AND pt.BTypeID='''+@btypeid +'''' ELSE ' 
			AND pt.BTypeID='''+@dealbtypeid +'''' END +'
			AND pt.CID = '+CONVERT(VARCHAR(10),@cid)+'
			AND pt.BtypeFlag='''+CONVERT(VARCHAR(2),@btypeflag)+''''+
	') T
	GROUP BY t.ptypeid,t.uid'
	
	EXEC(@SQL)	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPriceTrackInfo_InTable]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetPriceTrackInfo_InTable]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE Web_GetPriceTrackInfo_InTable
(
	@cid					INT,			--币种
	@stypeid				VARCHAR(200),	--分支机构
	@btypeid				VARCHAR(200),	--结算单位
	@dealbtypeid			VARCHAR(200),	--往来单位
	@intBillType			VARCHAR(10),	--单据类型
	@combineSQL				NVARCHAR(MAX)=''
)
--@encode$--
AS
SET NOCOUNT ON 


DECLARE @PriceTrackTableName	VARCHAR(50) 					--价格跟踪保存在哪一张表中(普通价格跟踪)
DECLARE @StypePriceTrackTableName	VARCHAR(50) 				--价格跟踪保存在哪一张表中(分支机构价格跟踪)
DECLARE @buysaletype			INT								--单据是采购还是销售类,1=采购，2=销售
DECLARE @buysaleName			VARCHAR(30)='buypricetrack'		--采购或者销售价格跟踪参数名
DECLARE @btypeflag				INT								--跟踪的是往来单位还是结算单位 0结算单位,1往来单位,-1未启用
DECLARE @isBTypeTrack			INT = -1						--查询往来单位是否启用了价格跟踪
DECLARE @stypePriceTrack_buy	INT =0							--采购类单据是否启用了分支机构价格跟踪
DECLARE @stypePriceTrack_sale	INT =0							--销售类单据是否启用了分支机构价格跟踪
DECLARE @IsOrdinaryPriceTrack	INT =0							--是否启用了普通价格跟踪:0未启用，1启用
DECLARE @SQL					VARCHAR(MAX)

----------------------------------初始化相关参数  start ----------------------------------
--普通价格跟踪表
SELECT 
@PriceTrackTableName=tracktablename,
@buysaletype=buysaletype 
FROM PriceTrackNameBillSet 
WHERE billtype=@intBillType and getsettype='2'

--分支机构价格跟踪表
SELECT 
@StypePriceTrackTableName=tracktablename
FROM PriceTrackNameBillSet 
WHERE billtype=@intBillType and getsettype='4'

--如果询价单、采购订单、暂估入库单取价设置为取采购价格，则直接获取采购入库单的价格跟踪表名
DECLARE @isGetBuyPriceTrack INT = 0
SELECT @isGetBuyPriceTrack = [VALUE] FROM PriceTrackConfig WHERE Name=
(
	CASE WHEN @intBillType=185 THEN 'askpricetrack' WHEN @intBillType=301 THEN 'buyorderpricetrack' 
	WHEN @intBillType IN (400,401) THEN 'zangupricetrack' END
)
IF(@isGetBuyPriceTrack = 2 AND @intBillType=185)
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
END
IF(@isGetBuyPriceTrack = 2 AND @intBillType=301)
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
END
IF(@isGetBuyPriceTrack = 2 AND @intBillType IN (400,401))
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
END

--如果报价单、销售订单、发出商品出库单取价设置为取小数价格，则直接获取销售出库单的价格跟踪表名
DECLARE @isGetSalePriceTrack INT = 0
SELECT @isGetSalePriceTrack = [VALUE] FROM PriceTrackConfig WHERE Name=
(
	CASE WHEN @intBillType=184 THEN 'quotepricetrack' WHEN (@intBillType=300 OR @intBillType=313) THEN 'saleorderpricetrack' 
	WHEN @intBillType IN(402,403) THEN 'fachupricetrack' END
)
IF(@isGetSalePriceTrack = 2 AND @intBillType=184)
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
END
IF(@isGetSalePriceTrack = 2 AND (@intBillType=300 OR @intBillType=313))
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
END
IF(@isGetSalePriceTrack = 2 AND @intBillType IN(402,403))
BEGIN
	SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
	SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
END

IF @buysaletype =1 
BEGIN
	SET @buysaleName='buypricetrack'
END
ELSE IF @buysaletype = 2
BEGIN
	SET @buysaleName='salepricetrack'
END
SELECT @IsOrdinaryPriceTrack=VALUE FROM PriceTrackConfig WHERE NAME=@buysaleName
SELECT @stypePriceTrack_buy=[value] FROM PriceTrackConfig WHERE NAME='buystypepricetrack'
SELECT @stypePriceTrack_sale=[value] FROM PriceTrackConfig WHERE NAME='salestypepricetrack'

IF @buysaletype=1
BEGIN
	SELECT @btypeflag=value  FROM PriceTrackConfig WHERE name='BuyBtypeFlag'
END
ELSE IF	@buysaletype=2
BEGIN	
	SELECT @btypeflag=value FROM PriceTrackConfig  WHERE name='SaleBtypeFlag'
END

--判断是否启用了结算单位价格跟踪
IF @btypeflag = 0
BEGIN
	SELECT @isBTypeTrack = PriceTrackEnable from BType WHERE typeid=@btypeid
END
--判断是否启用了往来单位价格跟踪
ELSE IF @btypeflag = 1
BEGIN
	SELECT @isBTypeTrack = PriceTrackEnable from BType WHERE typeid=@dealbtypeid
END

--系统配置是否使用多编码
DECLARE @MultiCode varchar(1)
SET @MultiCode = '0'
SELECT TOP 1 @MultiCode = Value FROM UserConfig WHERE ConfigName = 'IfMultiCode'

----------------------------------初始化相关参数  end -----------------------------------
IF @intBillType IN ('11','12','34','300','313','301','6','45','46','305','140','141','142','160','161','144','145','146','187','188','184','185','215','400','401','402','403')
BEGIN

	SET @SQL = '
	SELECT	t.PTypeId,
			SUM(t.DiscountRate) AS DiscountRate,
			SUM(t.DiscountPrice) AS DiscountPrice,
			SUM(t.Price) AS Price,
			SUM(t.tax) AS tax,
			SUM(t.TaxPrice) AS TaxPrice,
			SUM(t.DiscountRateStype) AS DiscountRateStype,
			SUM(t.DiscountPriceStype) AS DiscountPriceStype,
			SUM(t.PriceStype) AS PriceStype,
			SUM(t.taxStype) AS taxStype,
			SUM(t.TaxPriceStype) AS TaxPriceStype,
			t.[uid],
			'''+convert(varchar(2),@btypeflag)+''' as isbtypetrack,
			0 AS pricetracksource 
	FROM (
			SELECT 
			pt.PTypeId,'
			+CASE WHEN @isBTypeTrack = 1 THEN '
			pt.DiscountRate,
			pt.DiscountPrice,
			pt.Price,
			pt.tax,
			pt.TaxPrice, '
			ELSE '
			0 as DiscountRate,
			0 as DiscountPrice,
			0 as Price,
			0 as tax,
			0 as TaxPrice,
			' END +'
			pt.[uid],
			0 as DiscountRateStype,
			0 as DiscountPriceStype,
			0 as PriceStype,
			0 as taxStype,
			0 as TaxPriceStype
			FROM '+ @PriceTrackTableName +' pt
			INNER JOIN PType P	ON pt.PtypeID=P.TypeID '+CASE WHEN @MultiCode = 1 THEN '
			LEFT JOIN PUserCode u ON u.BTypeID = '''+ @dealbtypeid + ''' AND p.TypeID = u.PTypeID ' ELSE '' END +'
			WHERE 1=1 '+CASE WHEN @btypeflag=0 THEN ' 
			AND pt.BTypeID='''+@btypeid +'''' ELSE ' 
			AND pt.BTypeID='''+@dealbtypeid +'''' END +' 
			AND pt.Stypeid = '''+@stypeid+'''
			AND pt.BtypeFlag='''+CONVERT(VARCHAR(2),@btypeflag)+'''
			AND pt.CID = '+CONVERT(VARCHAR(10),@cid)+
			CASE WHEN @combineSQL <> '' THEN @combineSQL ELSE '' END + '
			UNION ALL
			SELECT 
			pt.PTypeId,
			0, 
			0, 
			0, 
			0, 
			0, 	
			pt.[uid],
			pt.DiscountRate,
			pt.DiscountPrice,
			pt.Price,
			pt.tax,
			pt.TaxPrice
			FROM '+@StypePriceTrackTableName+' pt 
			INNER JOIN PType P	ON pt.PtypeID=P.TypeID '+CASE WHEN @MultiCode = 1 THEN '
			LEFT JOIN PUserCode u ON u.BTypeID = '''+ @dealbtypeid + ''' AND p.TypeID = u.PTypeID ' ELSE '' END +'
			WHERE 1=1 
			'+CASE WHEN @btypeflag=0 THEN ' 
			AND pt.BTypeID='''+@btypeid +'''' ELSE ' 
			AND pt.BTypeID='''+@dealbtypeid +'''' END +'
			AND pt.CID = '+CONVERT(VARCHAR(10),@cid)+'
			AND pt.BtypeFlag='''+CONVERT(VARCHAR(2),@btypeflag)+''''+
			CASE WHEN @combineSQL <> '' THEN @combineSQL ELSE '' END + 
	') T
	GROUP BY t.ptypeid,t.uid'

	EXEC(@SQL)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPrintCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetPrintCount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	修改者：韩林
	日期：2012-02-01
	描述：连续打印查询明细
*/

CREATE PROCEDURE Web_GetPrintCount
(
	@billnumberids varchar(max),
	@operatorid varchar(50),
	@billtype varchar(50) = ''
)
--@encode$--
AS
SET NOCOUNT ON
IF @billtype NOT IN ('300','301')
BEGIN
	SELECT	SUM(A.PrintCount) AS printcount,
			ISNULL(SUM(AC.addprintcount),0) AS addprintcount,
			A.billnumberid,
			B.BillCode 
	FROM	PrintRecord A
	INNER JOIN BillIndex B ON A.BillNumberId=B.BillNumberId AND a.BillType=b.BillType
	LEFT JOIN AddPrintCountRecord AC ON a.BillNumberId=ac.BillNumberId AND AC.BillType=A.BillType  AND ac.etypeid=@operatorid
	WHERE a.BillNumberId IN (select * from f_split(@billnumberids,','))
	GROUP BY A.billnumberid,B.BillCode
END	
ELSE
BEGIN
	SELECT	SUM(A.PrintCount) AS printcount,
			ISNULL(SUM(AC.addprintcount),0) AS addprintcount,
			A.billnumberid,
			B.BillCode 
	FROM	PrintRecord A
	INNER JOIN OrderIndex B ON A.BillNumberId=B.BillNumberId AND a.BillType=b.BillType
	LEFT JOIN AddPrintCountRecord AC ON a.BillNumberId=ac.BillNumberId AND AC.BillType=A.BillType  AND ac.etypeid=@operatorid
	WHERE a.BillNumberId IN (select * from f_split(@billnumberids,','))
	GROUP BY A.billnumberid,B.BillCode
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetPTCombinOrderbilldetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetPTCombinOrderbilldetails
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- =============================================
CREATE PROCEDURE Web_GetPTCombinOrderbilldetails
(
	@orderids varchar(max)
)
--@encode$--
AS
BEGIN	
	SET NOCOUNT ON
	
	SELECT o.* 
	INTO #orderdetails
	FROM dbo.PT_Combin_OrderBillDetail  o
	INNER JOIN (select A from f_split(@orderids,',')) ids ON IDS.a=O.OrderID
	
	SELECT DISTINCT i.* 
	INTO #orderindex
	FROM OrderIndex i 
	INNER JOIN #orderdetails o ON o.billNumberID = i.billNumberId

	--创建临时表，获取自定义字段
	/*
	SELECT	cbd.*,
			e.fullname as efullnamecustom,
			p.fullname as pfullnamecustom,
			b.fullname as bfullnamecustom,
			d.fullname as dfullnamecustom,
			k.fullname as kfullnamecustom,
			s.fullname as sfullnamecustom 
	INTO #Custom_T
	FROM custom_billdetails cbd
	LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
	LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
	LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
	LEFT JOIN department d ON cbd.sysdiy14=d.typeid
	LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
	LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
	*/
	SELECT	cbd.*,
		e.fullname as efullnamecustom,
		p.fullname as pfullnamecustom,
		b.fullname as bfullnamecustom,
		d.fullname as dfullnamecustom,
		k.fullname as kfullnamecustom,
		s.fullname as sfullnamecustom,
		e1.fullname as efullnamecustom33,
		e2.fullname as efullnamecustom34,
		e3.fullname as efullnamecustom35,
		e4.fullname as efullnamecustom36,
		d1.fullname as dfullnamecustom37,
		d2.fullname as dfullnamecustom38,
		d3.fullname as dfullnamecustom39,
		d4.fullname as dfullnamecustom40
	INTO #Custom_T
	FROM custom_billdetails cbd
	INNER JOIN (select A from f_split(@orderids,',')) ids ON IDS.a=cbd.detailid
	LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
	LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
	LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
	LEFT JOIN department d ON cbd.sysdiy14=d.typeid
	LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
	LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
	LEFT JOIN employee e1 ON cbd.sysdiy33=e1.typeid
	LEFT JOIN employee e2 ON cbd.sysdiy34=e2.typeid
	LEFT JOIN employee e3 ON cbd.sysdiy35=e3.typeid
	LEFT JOIN employee e4 ON cbd.sysdiy36=e4.typeid
	LEFT JOIN department d1 ON cbd.sysdiy37=d1.typeid
	LEFT JOIN department d2 ON cbd.sysdiy38=d2.typeid
	LEFT JOIN department d3 ON cbd.sysdiy39=d3.typeid
	LEFT JOIN department d4 ON cbd.sysdiy40=d4.typeid

	SELECT	i.billNumberId,
			o.GoodsNumber,
			o.OrderID,
			o.orderid  as ptcombinorderbilldetailid,--销售订单id
			isnull(O.SaleOrderReachQty,0) as SaleOrderReachQty,
			O.WaitQty,
			qty = o.Qty,
			Price = o.Price,
			o.Discount,
			o.Tax,
			TaxPrice = o.TaxPrice,
			DiscountPrice = o.DiscountPrice,
			o.TaxTotal,
			BigQty =	CASE WHEN p.UnitRate1 = 0 
								THEN o.Qty
							 ELSE CAST(o.Qty/p.UnitRate1 AS  NUMERIC(24, 10) ) 
						END,
			o.total as discounttotal,
			ReachQty = o.ReachQty,
			o.PassQty, 
			o.SaleTotal as total,
			o.Ktypeid,
			o.frombillnumberid,
			o.frombillid,
			o.RequestBillNumberID,
			o.RequestBillID,
			p.typeid,
			p.UserCode,
			p.FullName,
			CASE WHEN ISNULL(o.entrycode,'')='' then p.entrycode
			else o.entrycode end as entrycode,
			p.MultEntryCode AS multentrycode,
			p.Standard,
			p.Type,
			p.Area,
			p.Unit1 as unitone,
			p.Unit2 as unittwo,
			0 as UnitRate1,
			0 as UnitRate2,
			p.IfSerial,
			p.serialcount,
			p.validdays,
			p.usefullifeday,
			o.comment as base,
			s.UserCode AS KUserCode,
			s.FullName AS KFullName,
			--cs.fullname AS cs,
			PC.UserCode AS CustomerCode,
			IsUnit2 = 0,
			accountqty=(select  isnull(SUM(qty),0) from GoodsStocks where o.ptypeid=ptypeid AND o.ktypeid=ktypeid),
			 U.FullName AS munit,

			 V.FullName AS nunit,
			 W.FullName AS unit,
			 o.MUnitID,
			 o.NUnitID,
			 o.UnitID,
			 o.MQty,
			 o.curmsaleprice,
			 o.nsaletotal,
			 o.nsaleprice,
			 CASE WHEN ISNULL(o.nunitid,0) = 0 THEN NULL
			 ELSE o.unitrate END AS unitrate,
			 CASE WHEN ISNULL(o.nunitid,0) = 0 THEN NULL
			 ELSE o.nqty END AS nqty,
			 o.curmdiscountprice,
			 o.ntotal,
			 o.curmtaxprice,
			 o.ntaxmoney,
			 o.ntaxtotal,
			 o.taxmoney,
			 o.ItemID,
			 o.munitrate,
			 o.IsCombined,
			 p.customitemid,
			 p.customitemfrom,
			 p.customitemname,
			 p.customitemrefid,
			 p.unitstype,
			 o.NDiscountPrice,
			 o.NTaxPrice,
			 o.MSalePrice,
			 o.MDiscountPrice,
			 o.MTaxPrice,
			 o.cargoid,	
			 o.GoodsCostPrice,
			 o.GoodsCostPrice as goodsnumberprice,
			 o.GoodsOrder,
			 o.ProduceDate,
			 o.ValidDate,
			 o.IsGift,
			 (select EntryCode from PType_Units_Ext where PtypeID=o.pTypeID and UnitsId=U.UnitsId) AS munitcode,
			 ct.fullname as cargofullname,
			 CAST(p.IfUseGoodsNum AS INT) AS ifusegoodsnum,
			 itemname= CASE WHEN o.IsCombined = 0  THEN
					  (SELECT FullName FROM xw_SelfData WHERE _Id= o.ItemId)
					   ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= o.ItemId ) END,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId)) as auxfullname1,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId)) as auxfullname2,
			(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId)) as auxfullname3,
			(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId) as auxrate1,
			(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId) as auxrate2,
			(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeId) as auxrate3,
			p.IsService,
			CASE WHEN stype.pricetype=0 THEN pp.ReferPrice
			WHEN stype.pricetype=1 THEN 
				CASE WHEN ISNULL(sp.Referprice,0)=0 THEN pp.Referprice 
				ELSE sp.Referprice END
			END AS Referprice,
			o.pricesource,dbo.F_GetAllEntrycode(PUE.PTYPEID,PUE.UNITSID,2) AS salemunitcode,dbo.F_GetAllEntrycode(pu.PTYPEID,pu.UNITSID,2) as buymunitcode,cbd.*,
			p.brandartypeid,
			bc.FullName AS brandarfullname,
			(SELECT ISNULL(CASE WHEN SUM(ISNULL(g.QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(g.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(g.QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks g WHERE g.PtypeId = o.pTypeID AND g.KtypeId = o.ktypeid  ) AS showcostprice	 	
	FROM #orderindex i 
	LEFT JOIN btype b ON i.btypeid = b.typeId     
	INNER JOIN #orderdetails o ON i.billNumberId = o.billNumberID 	
	LEFT JOIN PuserCode PC ON PC.PtypeId = o.PtypeId AND PC.BtypeId = i.dealbtypeid
	INNER JOIN ptype p ON o.ptypeid = p.typeId
	LEFT JOIN dbo.brandar_Commodity bc ON bc.typeid = p.brandartypeid
	LEFT JOIN PType_Units_Ext pu ON p.typeid=pu.ptypeid AND o.munitid=pu.UnitsId
	INNER JOIN PType_Price pp ON pp.PTypeID = p.TypeID AND o.UnitID = pp.UnitID
	LEFT JOIN PType_StypePrice sp on sp.ptypeid=p.typeid AND sp.stypeid=i.stypeid AND o.UnitID=sp.UnitID
	inner join stype stype on stype.typeid=i.stypeid
	LEFT JOIN stock s ON o.KtypeId=s.typeId
	--LEFT JOIN CargoSpace cs ON o.ptypeid=cs.ptypeid AND o.ktypeid=cs.ktypeid
	--INNER JOIN (select A from f_split(@orderids,',')) ids ON IDS.a=O.OrderID
	LEFT JOIN
	  xw_SelfData ON o.ptypeid=xw_SelfData.typeId AND o.ItemID=xw_SelfData._Id
	LEFT JOIN
	  CustomReferenceValue  ON o.ItemID=CustomReferenceValue.id
	LEFT  JOIN  dbo.PType_Units U ON U.UnitsId=o.MUnitID 
	LEFT  JOIN  dbo.PType_Units V ON V.UnitsId=o.NUnitID
	LEFT  JOIN  dbo.PType_Units W ON W.UnitsId=o.UnitID
	LEFT  JOIN  CargoType ct ON o.CargoID = ct.CargoID
	LEFT JOIN PType_Units_Ext PUE ON PUE.PTYPEID=P.TYPEID AND PUE.UNITSID=o.munitid
	LEFT JOIN #Custom_T cbd ON  cbd.billid=i.billnumberid AND cbd.detailid=o.orderid AND cbd.billtype=i.billtype
	WHERE	i.checked = 0  ORDER BY ShowOrder ASC
	DROP TABLE #Custom_T,#orderdetails,#orderindex
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetPtypePriceInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_GetPtypePriceInfo]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 创 建 人：罗淮文
-- 创建日期：2015-10-08
-- 内容描述：商品价格信息
-- ========================================================================
CREATE PROCEDURE Web_GetPtypePriceInfo
(
	@ptypeid			VARCHAR(200),			--商品编号
	@stypeid			VARCHAR(200)='',		--分支结构
	@btypeid			VARCHAR(200)='',		--往来单位
	@denominated		VARCHAR(200)='',		--结算单位
	@operator			VARCHAR(200)='',		--操作员
	@billtype			int,					--单据类型
	@pricescolumnname	VARCHAR(200)			--单据头默认预设价格类型
	
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @unittype VARCHAR(50) 
	SELECT	@unittype = CASE WHEN @billtype IN (11,300,184,305,45,160,140,142,141,215,402) THEN 'SaleUnitId'		--销售单,销售订单,报价单，发出商品出库单等销售类单据
						  WHEN @billtype IN (34,301,185,6,161,144,145,146,400) THEN 'BuyUnitId'		--采购单,采购订单,询价单,暂估入库单等采购类单据
						  ELSE '' END 
	DECLARE @cid VARCHAR(50)=''
	SELECT @cid = cid FROM Ac_Currency WHERE Sysrow = 1
	IF OBJECT_ID('tempdb.dbo.#temp_PriceTrack') IS NOT NULL
	BEGIN
		DROP TABLE #temp_PriceTrack
	END
	
------------------------------------------价格跟踪  start  -----------------------------------
	CREATE TABLE #temp_PriceTrack
	(
		PtypeId				varchar(50),
		DiscountTrack   NUMERIC(24, 10) ,			--价格跟踪扣率跟踪
		DiscountPriceTrack	  NUMERIC(24, 10) ,		--价格跟踪扣率跟踪
		PriceTrack	  NUMERIC(24, 10), 			--价格跟踪扣率跟踪
		TaxTrack	NUMERIC(24,10),				--税率跟踪
		TaxPriceTrack	NUMERIC(24,10),			--含税单价跟踪
		DiscountTrackStype   NUMERIC(24, 10) ,			--分支机构间价格跟踪扣率跟踪
		DiscountPriceTrackStype	  NUMERIC(24, 10) ,		--分支机构间价格跟踪扣率跟踪
		PriceTrackStype	  NUMERIC(24, 10), 			--分支机构间价格跟踪扣率跟踪
		TaxTrackStype	NUMERIC(24,10),				--分支机构间税率跟踪
		TaxPriceTrackStype	NUMERIC(24,10),			--分支机构间含税单价跟踪
		[UID]		INT,
		isbtypetrack	INT,
		pricetracksource INT
	);

	INSERT INTO #temp_PriceTrack
	EXEC Web_GetPriceTrackInfo @cid,@stypeid,@denominated,@btypeid,@billtype
------------------------------------------价格跟踪  End    -----------------------------------

	DECLARE @PriceType VARCHAR(1)
	DECLARE @prepricesql VARCHAR(2000)
	SELECT @PriceType = pricetype FROM dbo.SType WHERE TypeId=@stypeid
	SET @prepricesql=' LEFT JOIN PType_STypePrice C ON C.STypeID='''+@stypeid+''' AND C.PtypeId=B.typeid'
	
	DECLARE @pricescolumnnSql VARCHAR(200)
	IF @pricescolumnname IS NULL OR @pricescolumnname=''
	BEGIN
		SET @pricescolumnnSql = 'NULL AS curmsaleprice2,'
	END
	ELSE
	BEGIN
		SET @pricescolumnnSql = 'B.'+@pricescolumnname+' AS curmsaleprice2,'
	END
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'SELECT 	p.ifusegoodsnum,
			B.typeId,
			B.ParId,
			B.leveal,
			B.sonnum,
			B.customitemid,
			B.customitemfrom,
			B.customitemname,
			B.customitemrefid,
			B.soncount,
			B.CanModify,
			B.UserCode,
			B.FullName,
			B.Name,
			B.[Standard],
			B.[Type],
			B.Area,
			B.BuyUnitId,
			B.SaleUnitId,
			B.StockUnitId,
			B.baseUnitId,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice1 ELSE  B.PreSalePrice1 END AS PrePrice1,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice2 ELSE  B.PreSalePrice2 END AS PrePrice2,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice3 ELSE  B.PreSalePrice3 END AS PrePrice3,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice4 ELSE  B.PreSalePrice4 END AS PrePrice4,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice5 ELSE  B.PreSalePrice5 END AS PrePrice5,
			B.UsefulLifeMonth,
			B.UsefulLifeDay,
			B.Comment,
			B.recPrice,
			C.recprice as styperecbuyprice,
			B.deleted,
			B.ColorGroupID,
			B.SizeGroupID,
			B.IfSerial,
			B.PyCode,
			B.SerialCount,
			B.ValidDays,
			B.DwgNo,
			B.XiWaMaxNumber,
			B.ifuseentrycode,
			B.Brand,
			B.Import,
			B.GeneralType,
			B.GeneralDwgNo,
			B.Property,
			B.PackageQty,
			B.[Weight],
			B.TaxNumber,
			B.BTypeID,
			B.FcUnit,
			B.FcPrice,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreBuyPrice1 ELSE  B.PreBuyPrice1 END AS PreBuyPrice1,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreBuyPrice2 ELSE  B.PreBuyPrice2 END AS PreBuyPrice2,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreBuyPrice3 ELSE  B.PreBuyPrice3 END AS PreBuyPrice3,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreBuyPrice4 ELSE  B.PreBuyPrice4 END AS PreBuyPrice4,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreBuyPrice5 ELSE  B.PreBuyPrice5 END AS PreBuyPrice5,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice1 ELSE  B.PreSalePrice1 END AS PreSalePrice1,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice2 ELSE  B.PreSalePrice2 END AS PreSalePrice2,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice3 ELSE  B.PreSalePrice3 END AS PreSalePrice3,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice4 ELSE  B.PreSalePrice4 END AS PreSalePrice4,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice5 ELSE  B.PreSalePrice5 END AS PreSalePrice5,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice6 ELSE B.PreSalePrice6 END AS PreSalePrice6,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice7 ELSE B.PreSalePrice7 END AS PreSalePrice7,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice8 ELSE B.PreSalePrice8 END AS PreSalePrice8,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice9 ELSE B.PreSalePrice9 END AS PreSalePrice9,
			CASE WHEN '''+@PriceType+'''=''1'' THEN C.PreSalePrice10 ELSE B.PreSalePrice10 END AS PreSalePrice10,
			B.RetailPrice,
			B.TopSalePrice,
			B.LowSalePrice,
			B.stopbuy,
			B.TopBuyPrice,
			B.AssistantUnitId,
			B.ProduceUnitId,
			'+@pricescolumnnSql+'
			pt.* ,
			C.recsaleprice as styperecsaleprice,
			C.recprice as styperecprice,
			ISNULL((SELECT TOP 1 ISNULL(recamgstypebuyprice, 0) FROM ptype_price  WHERE PTypeID = p.TypeID ),0) as amgrecstypebuyprice,
			ISNULL((SELECT TOP 1 ISNULL(recamgstypesaleprice, 0) FROM ptype_price  WHERE PTypeID = p.TypeID ),0) as amgrecstypesaleprice
			--p.recamgstypebuyprice,
			--p.recamgstypesaleprice
		   FROM ptype p 
		   INNER JOIN (SELECT * FROM F_GetManPTypeAll('''+@operator+''')) AS B ON p.typeid=B.typeid
		   '+@prepricesql+'
		   LEFT JOIN #temp_PriceTrack pt on pt.ptypeid=b.typeid
		    WHERE p.typeid='''+@ptypeid+''''
		   PRINT @SQL
		   EXEC(@SQL)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetSaleBackSerQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetSaleBackSerQuery]
GO














/****** Object:  Stored Procedure dbo.Web_GetSaleBackSerQuery    Script Date: 2002-6-20 10:14:54 ******/

/*
调用页面：SaleBackSerQueryBase.asp
对方收货查询统计
列出对方已经收到的每一中种商品的数量总技与金额总技
传入参数：BTypeID
   StartDate
   EndDate
作者：李华
2001－04－27
*/
CREATE  PROCEDURE Web_GetSaleBackSerQuery
( 
 @BTypeID varchar(25),
 @StartDate datetime,
 @EndDate datetime
)
--@encode$--
AS
SET NOCOUNT ON 
SELECT 
 SUM(saleBackBill.Qty) AS Qty,
 SUM(saleBackBill.TaxTotal) AS QtyPrice, 
       ptype.UserCode,
 ptype.FullName,
 ptype.Unit1
FROM 
 BillIndex INNER JOIN saleBackBill ON BillIndex.BillNumberId = saleBackBill.BillNumberId 
 INNER JOIN ptype ON saleBackBill.PtypeId = ptype.typeId
WHERE 
 BillIndex.btypeid = @BTypeID 
 AND BillIndex.ifcheck = 't'
 AND BillIndex.BillDate >= @StartDate 
 AND BillIndex.BillDate <= @EndDate
GROUP BY
 ptype.UserCode, ptype.FullName, ptype.Unit1















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE id = OBJECT_ID(N'[dbo].[Web_GetSaleOrBuyOrderState]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_GetSaleOrBuyOrderState]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：罗淮文
	日期：2015-06-29
	描述：查询某个采购/销售订单的订单状态。-1:未引用;0:已引用未完成;1:已完成
*/
CREATE PROCEDURE Web_GetSaleOrBuyOrderState
(
	@BillNumberId	VARCHAR(200),	--订单编码
	@BillType		INT=0			--订单类型：301，采购订单；300，销售订单 313 组合品销售订单
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	IF @BillType=301
	BEGIN
		SELECT CASE WHEN a.OrderState = 1 THEN 1--'已完成' 
		WHEN BI1.ReachQty=0 AND BI.BID IS NULL THEN -1--'未引用' 
		ELSE 0/*'已引用未完成'*/ END  AS UseMark
		FROM OrderIndex a  
		INNER JOIN (
						SELECT a.BillNumberID,max(a.BID) as BID
						FROM 
						(				
							SELECT distinct detail.BillNumberID,(BB.orderid) as BID FROM OrderBill detail 
							LEFT JOIN 
							(
								SELECT bb.OrderID,bb.BillNumberID FROM 
								(
									SELECT OrderID,BillNumberId FROM buybill 
									UNION ALL 
									SELECT OrderId,BillNumberId FROM AppraisalBill
								) AS bb  
								INNER JOIN BillIndex bi ON bb.billnumberid=bi.billnumberid and bi.redword=0--排除红冲单据
							)bb ON detail.OrderID=bb.orderid
						)a 
						GROUP BY A.billNumberID
					) bi ON A.billNumberId=BI.billNumberID
					INNER JOIN 
					(								
						SELECT B.billNumberID,sum(b.WaitQty) AS WaitQty,sum(b.Qty) AS Qty,sum(b.ReachQty) AS ReachQty FROM
						(								
							SELECT detail.BillNumberID,(detail.WaitQty) AS WaitQty,(detail.Qty) AS Qty,(detail.ReachQty) AS ReachQty
							FROM OrderBill detail
						) b GROUP BY B.billNumberID
					) BI1 ON a.billnumberid=BI1.billnumberid
		WHERE a.BILLNUMBERID=@BillNumberId AND a.BillType=301
	END
	ELSE IF @BillType=300
	BEGIN
		SELECT CASE WHEN a.OrderState = 1 THEN 1--'已完成' 
		WHEN BI1.ReachQty=0 AND BI.BID IS NULL THEN -1--'未引用' 
		ELSE 0/*'已引用未完成'*/ END  AS UseMark
		FROM OrderIndex a  
		INNER JOIN (
						SELECT a.BillNumberID,max(a.BID) as BID
						FROM 
						(				
							SELECT distinct detail.BillNumberID,(BB.orderid) as BID FROM OrderBill detail 
							LEFT JOIN 
							(
								SELECT bb.OrderID,bb.BillNumberID FROM 
								(
									SELECT OrderID,BillNumberId FROM salebill 
									UNION ALL 
									SELECT OrderId,BillNumberId FROM sendbill
								) AS bb  
								INNER JOIN BillIndex bi ON bb.billnumberid=bi.billnumberid and bi.redword=0--排除红冲单据
							)bb ON detail.OrderID=bb.orderid
						)a 
						GROUP BY A.billNumberID
					) bi ON A.billNumberId=BI.billNumberID
					INNER JOIN 
					(								
						SELECT B.billNumberID,sum(b.WaitQty) AS WaitQty,sum(b.Qty) AS Qty,sum(b.ReachQty) AS ReachQty FROM
						(								
							SELECT detail.BillNumberID,(detail.WaitQty) AS WaitQty,(detail.Qty) AS Qty,(detail.ReachQty) AS ReachQty
							FROM OrderBill detail
						) b GROUP BY B.billNumberID
					) BI1 ON a.billnumberid=BI1.billnumberid
		WHERE	a.BILLNUMBERID=@BillNumberId AND a.BillType=300
	END
	ELSE IF @BillType=313
	BEGIN
		SELECT CASE WHEN a.OrderState = 1 THEN 1--'已完成' 
		WHEN BI1.ReachQty=0 AND BI.BID IS NULL THEN -1--'未引用' 
		ELSE 0/*'已引用未完成'*/ END  AS UseMark
		FROM OrderIndex a  
		INNER JOIN (
						SELECT a.BillNumberID,max(a.BID) as BID
						FROM 
						(				
							SELECT distinct detail.BillNumberID,(BB.orderid) as BID FROM dbo.PT_Combin_OrderBill detail 
							LEFT JOIN 
							(
								SELECT bb.OrderID,bb.BillNumberID FROM 
								(
									SELECT OrderID,BillNumberId FROM dbo.PT_Combin_SaleBill 
								) AS bb  
								INNER JOIN BillIndex bi ON bb.billnumberid=bi.billnumberid and bi.redword=0--排除红冲单据
							)bb ON detail.OrderID=bb.orderid
						
						)a 
						GROUP BY A.billNumberID
					) bi ON A.billNumberId=BI.billNumberID
					INNER JOIN 
					(								
						SELECT B.billNumberID,sum(b.WaitQty) AS WaitQty,sum(b.Qty) AS Qty,sum(b.ReachQty) AS ReachQty FROM
						(								
							SELECT detail.BillNumberID,(detail.WaitQty) AS WaitQty,(detail.Qty) AS Qty,(detail.ReachQty) AS ReachQty
							FROM PT_Combin_OrderBill detail
						) b GROUP BY B.billNumberID
					) BI1 ON a.billnumberid=BI1.billnumberid
		WHERE	a.BILLNUMBERID=@BillNumberId AND a.BillType=313
	END
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetStartUsingVisible]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_GetStartUsingVisible
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
--CreatedBy:	glj	
--Date:			2012-11-02	
--Description:	得到当前用户是否有启用总账按钮权限
--RETURN		1:有权限  0:没有权限
-- ========================================================================
CREATE	PROC Web_GetStartUsingVisible 
(
	@UserID		VARCHAR(100)	---当前用户ID 
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @IsSys INT=0,@Pwd VARCHAR(10)=''	
SELECT @IsSys=sysid,@Pwd=[password] FROM LoginUser WHERE etypeid=@UserID

IF(@IsSys<>1 OR ISNULL(@Pwd,'')<>'Va90@ChZt2')
	RETURN 0
IF EXISTS(SELECT 1 FROM Ac_Voucher) OR EXISTS(SELECT 1 FROM Ac_Voucher_Bill)
	RETURN 0
RETURN 1
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetStockBillsByAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetStockBillsByAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/07/03
	Description	: 根据科目id
*/
CREATE PROCEDURE Web_GetStockBillsByAccount
(
	@STypeId	VARCHAR(50),
	@Cid		INT,
	@TypeId		VARCHAR(50),
	@Flag		INT
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @INSERTSQL		VARCHAR(MAX)='INSERT INTO #temp(',
			@SELECTSQL		VARCHAR(MAX)=' SELECT ',
			@GROUPBYSQL		VARCHAR(MAX)=' GROUP BY ',
			@tempFullName   VARCHAR(200),
			@tempColName	VARCHAR(50),
			@SQL			VARCHAR(MAX)
			
	-----查询挂靠在此分支机构下的非独立核算机构（包含它自己）
	CREATE TABLE #tempStypes
	(
	  STYPEID	VARCHAR(50),
	  FULLNAME	VARCHAR(100)
	)
	INSERT INTO #tempStypes
	SELECT TYPEID,
		   FullName
	FROM SType 
	WHERE VerifyID=@STypeId AND DELETED=0

    ---符合条件的数据
    CREATE TABLE #tempBills
    (
		STYPEID					VARCHAR(50),	  ---机构ID
		STYPENAME				VARCHAR(66),	  ---机构名称
		TOTAL					 NUMERIC(24, 10) 	  ---余额本币
    )
    
    INSERT INTO #tempBills
    SELECT a.STYPEID,
		   a.FULLNAME,
		   SUM(ISNULL(c.TOTAL,0))
    FROM #tempStypes a 
    JOIN STOCK b          ON a.STYPEID=b.STYPEID AND b.SONNUM=0
    JOIN INIGOODSSTOCKS c ON b.TYPEID=c.KTYPEID
    GROUP BY a.FULLNAME,a.STYPEID
    
    IF @Flag=0																			----直接保存进
		BEGIN
			SELECT STYPEID AS STYPEID,
				   STYPENAME AS STYPENAME,
				   TOTAL AS BILLTOTAL
			FROM #tempBills
			
			---查询金额总数
			SELECT SUM(ISNULL(TOTAL,0)) AS TOTAL
			FROM #tempBills
		END
	ELSE																				----展现有辅助核算项的
		BEGIN
			-----该科目有哪些辅助核算项		 
			CREATE TABLE #AssistInfo
			(
				USERCODE	VARCHAR(200),
				FULLNAME	VARCHAR(200),
				COLNAME		VARCHAR(50)     ---动态列的列名
			)			 
			INSERT INTO #AssistInfo
			SELECT USERCODE,
				   FULLNAME,
				   CASE WHEN USERCODE='01' THEN 'selectstypeid'
						WHEN USERCODE='02' THEN 'selectdtypeid'
						WHEN USERCODE='03' THEN 'selectetypeid'
						WHEN USERCODE='04' THEN 'selectbtypeid' 
				   END  
			FROM Ac_Account_Assist_CheckItems a 
			JOIN Ac_Assist_CheckItems b ON a.ASCIDS=b.ASCIDS  
			WHERE STYPEID=@STypeId AND ATYPEID=@TypeId AND CID=@Cid
			
			-----结果临时表
			CREATE TABLE #temp
			(
			   BILLTOTAL	 NUMERIC(24, 10) 
			)
			
			----给结果临时表动态添加辅助核算列
			DECLARE @DynCol VARCHAR(MAX)
			--DECLARE @tempCol1 VARCHAR(max)
			--SELECT @tempCol1=(ISNULL(@tempCol1+'],[','') +  FULLNAME) 
			--FROM #AssistInfo GROUP BY FULLNAME 
			SELECT @DynCol=(ISNULL(@DynCol+'] VARCHAR(66),[','') +  FULLNAME) 
			FROM #AssistInfo GROUP BY FULLNAME 
			SET @DynCol='ALTER TABLE #temp ADD ['+@DynCol+'] VARCHAR(66)'
			
			EXEC(@DynCol)
			
			DECLARE @DynColID VARCHAR(MAX)
			--DECLARE @tempCol2 VARCHAR(max)
			--SELECT @tempCol2=(ISNULL(@tempCol2+'],[','') +  COLNAME) 
			--FROM #AssistInfo GROUP BY COLNAME 
			SELECT @DynColID=(ISNULL(@DynColID+'] VARCHAR(66),[','') +  COLNAME) 
			FROM #AssistInfo GROUP BY COLNAME 
			SET @DynColID='ALTER TABLE #temp ADD ['+@DynColID+'] VARCHAR(66)'
			
			EXEC(@DynColID)
			
			 ---是否含有分支机构
			IF (SELECT 1 FROM #AssistInfo WHERE USERCODE='01')=1
				BEGIN
				   SELECT @tempFullName=FULLNAME FROM #AssistInfo WHERE USERCODE='01'
				   SET @INSERTSQL+=@tempFullName+','
				   SELECT @tempColName=COLNAME FROM #AssistInfo WHERE USERCODE='01'
				   SET @INSERTSQL+=@tempColName+','
				   SET @SELECTSQL+='STYPENAME,STYPEID,'
				   SET @GROUPBYSQL+='STYPENAME,STYPEID'
				END
			
			SET @INSERTSQL+='BILLTOTAL)'
			SET @SELECTSQL+='SUM(TOTAL) FROM #tempBills '
			
			IF(@GROUPBYSQL=' GROUP BY ')        
				SET @SQL=@INSERTSQL+@SELECTSQL
			ELSE
				SET @SQL=@INSERTSQL+@SELECTSQL+@GROUPBYSQL
				
			EXEC(@SQL)  
			   
			---查询符合格式的数据   
			--SET @SQL='SELECT ['+@tempCol1+'],['+@tempCol2+'],BILLTOTAL FROM #temp'    
			--EXEC(@SQL)
			SELECT * FROM #temp
			---查询金额总数
			SELECT SUM(ISNULL(TOTAL,0)) AS TOTAL
			FROM #tempBills
			
			DROP TABLE #AssistInfo,#temp   
		END
	DROP TABLE #tempStypes,#tempBills  
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[WEB_GETSTOCKSBYSTYPEIDS]') AND OBJECTPROPERTY(ID, N'ISPROCEDURE') = 1)
	DROP PROCEDURE [DBO].[WEB_GETSTOCKSBYSTYPEIDS]
GO
/*
	作者：周华
	时间：2012-06-20 10:25:11.967
	描述：库存期初添加了先选择分支机构的操作，所以添加一个通过分支机构ids的过程
	从[Web_QuerySearchOneBaseInfo]里的type为'K'的情况分出来的。
	2012-09-21 彭勇 去掉了仓库里deleted=0的条件 
	2012-10-16 周华 修改where处bug 约68行
	2012-12-25 周华 确认先仓库时不显示停用的。添加上deleted=0的条件
*/
CREATE PROCEDURE Web_GetStocksByStypeIds
(
	@OperatorId	varchar(100)		--操作员Id	
	,@TypeId	varchar(100)		--基本信息的Id
	,@Filter	varchar(500)=''	--过滤 1、编号  2、名称  3、拼音码 4、联系电话
	,@nType		varchar(10)='0'
	,@StypeIds  nvarchar(max)=''	--添加一个参数，可以处理特殊情况
)	
--@encode$--
AS
BEGIN
	SET NOCOUNT ON;
	--特殊处理传bool值的情况
	IF LOWER(@nType)='true' OR LOWER(@nType)='false'
		BEGIN
			IF LOWER(@nType)='false'
				SET @nType = '0'
			ELSE
				SET @nType = '1'
		END
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
				@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid varchar(50),@MStypeid varchar(50)
	EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

	IF @Re<>0 RETURN @Re

	IF @TypeId = '' SET @TypeId = '00000'
	DECLARE @kSonNum 	int,
			@kParId		varchar(200)
			,@k_sql NVARCHAR(MAX)=''

	SELECT @kSonNum = SonNum,@kParId=ParId FROM Stock WHERE TypeId = @TypeId

	CREATE TABLE #Stock
	(
		TypeID		varchar(100),
		ParId		varchar(100),
		SonNum		int,
		UserCode	varchar(400),
		FullName	varchar(400),
		PyCode		varchar(400),
		Deleted		int
	)
	IF @StypeIds<>''
		SET @k_sql=N';WITH cte AS(
			SELECT TypeId,parid FROM Stype '+CASE WHEN @stypeIds<>'' THEN 'WHERE Typeid IN ('''+REPLACE(@StypeIds,',',''',''')+''')' ELSE '' END+'
			UNION ALL
			SELECT a.typeId,a.parid FROM  stype a JOIN cte b ON a.parid=b.typeid	
		)';
	--判断权限范围
	IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerKTypeId = '00000')
		SET @k_sql=@k_sql+N' INSERT INTO #Stock(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM F_GetManKTypeAll(@OperatorId) WHERE deleted = 0'
	ELSE
		SET @k_sql=@k_sql+N' INSERT INTO #Stock(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM Stock WHERE deleted = 0 '
	
	IF @StypeIds<>''
		SET @k_sql=@k_sql+' AND ( StypeId IN (SELECT typeid FROM cte) )';
	--print @k_sql;
	
	EXEC SP_EXECUTESQL @k_sql,N'@OperatorId varchar(100)',@OperatorId;

	IF @Filter = ''
		BEGIN
			IF @TypeId = '00000'
				SELECT	TypeId,SonNum,UserCode,FullName FROM #Stock WHERE ParId = '00000' AND TypeId <> '00000' ORDER BY UserCode
			ELSE IF @nType = '0'
				BEGIN
					IF @TypeId = @MATypeId
						SELECT	TypeId,SonNum,UserCode,FullName FROM #Stock WHERE TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
					ELSE
						SELECT	TypeId,SonNum,UserCode,FullName FROM #Stock WHERE ParId = @kParId AND TypeId <> '00000' ORDER BY UserCode
				END
			ELSE
				BEGIN
					IF @kSonNum = 0
						SELECT	TypeId,SonNum,UserCode,FullName FROM #Stock WHERE SonNum = 0 AND TypeId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
					ELSE
						SELECT	TypeId,SonNum,UserCode,FullName FROM #Stock WHERE ParId = @TypeId AND TypeId <> '00000' ORDER BY UserCode
				END
		END
	ELSE
		SELECT	TypeId,SonNum,UserCode,FullName FROM #Stock WHERE SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%') AND TypeId <> '00000'  ORDER BY UserCode

	DROP TABLE #Stock
				
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetStypeAllFperiod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetStypeAllFperiod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013.06.26
	描述：获取指定分支机构的所有期间（显式标明当前期间）
*/
CREATE PROCEDURE Web_GetStypeAllFperiod
(
	@STypeid	VARCHAR(50),
	@Fyear		INT
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @STypeid AND FYear = @Fyear)
BEGIN
	SELECT T1.FPeriod AS SPeriod,T1.FPeriod AS EPeriod,CASE WHEN ISNULL(T2.SubValue,0) <> 0 THEN 1 ELSE 0 END AS isDefault
	FROM dbo.Ac_Period T1
		LEFT JOIN dbo.sysdata T2 ON T1.FPeriod = T2.SubValue AND T2.SubName = 'fmonth'
	WHERE T1.FYear = @Fyear
END
ELSE
BEGIN
	SELECT T1.FPeriod AS SPeriod,T1.FPeriod AS EPeriod,CASE WHEN ISNULL(T2.FPeriod,0) <> 0 THEN 1 ELSE 0 END AS isDefault
	FROM dbo.Ac_Period T1
		LEFT JOIN dbo.Ac_AccountsPeroid_Stype T2 ON T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod AND T2.Stypeid = @STypeid
	WHERE T1.FYear = @Fyear
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetStypeByAcItemsID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_GetStypeByAcItemsID]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	得到指定ac_items nid的分支机构等相关信息
-- 时间：	2012-04-19
-- 作者：	古丽娟

-- 修改: Hqing  增加会计科目多级权限控制
-- ========================================================================
CREATE PROC Web_GetStypeByAcItemsID
(
	@nid			VARCHAR(50),	--ID
    @OperatorID		VARCHAR(50)		-- 操作员
)
--@encode$--

AS
SET NOCOUNT ON 

BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200))
	CREATE CLUSTERED INDEX CIX_Account_TypeId ON #Ac_Account_L(TypeId,StypeId)
	
	INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName) 
	SELECT L.Typeid,L.Stypeid,A.FullName FROM F_LineAccount(@OperatorID,'') L
	INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
	
	--处理为空情况，写入空数据
	INSERT INTO #Ac_Account_L(TypeId,StypeId,FullName)
	SELECT '',TypeId,'' FROM SType WHERE sonnum=0
END;


DECLARE @SQL VARCHAR(MAX)='
SELECT
	distinct
	d.DId,
	d.nId,
	d.STypeId,
	s.FullName sfullname,
	d.ATypeId,
	ISNULL(a.FullName,''****'') afullname,
	d.DepATypeId,
	ISNULL(a1.FullName,''****'') depfullname,
	d.DisATypeId,
	ISNULL(a2.FullName,''****'') disfullname,
	s.deleted
FROM Ac_Items_Detail d
INNER JOIN dbo.F_GetAllManagerBaseTypeId('''',11,'''+@OperatorID+''') F ON F.TypeId=d.STypeId
INNER JOIN SType s ON s.TypeId=d.STypeId AND s.SonNum=0
LEFT JOIN #Ac_Account_L a ON a.typeId=d.ATypeId AND ((a.stypeid=s.TypeId AND s.IsSelfVerify=1) OR (a.stypeid=s.verifyid AND s.IsSelfVerify=0))
LEFT JOIN #Ac_Account_L a1 ON a1.TypeId=d.DepATypeId AND ((a1.stypeid=s.TypeId AND s.IsSelfVerify=1) OR (a1.stypeid=s.verifyid AND s.IsSelfVerify=0))
LEFT JOIN #Ac_Account_L a2 ON a2.TypeId=d.DisATypeId AND ((a2.stypeid=s.TypeId AND s.IsSelfVerify=1)OR (a2.stypeid=s.verifyid AND s.IsSelfVerify=0))

'
SET @SQL+='WHERE s.deleted=0 and d.nId='+@nid

EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetStypeCurrentPeroidDate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetStypeCurrentPeroidDate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2013-05-10
	描述：查找分支机构当前期间日期
*/
CREATE PROCEDURE Web_GetStypeCurrentPeroidDate
(
	@Stypeid	VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @CurrentPeroid INT,--当前期间
		@LastPeriod INT,
		@CurrentYear	INT	--当前年度
SELECT TOP 1 @LastPeriod = FPeriod FROM dbo.Ac_Period WHERE IsCurrent = 1 ORDER BY FPeriod DESC

DECLARE @ifNeedAddPeriod INT
SET @ifNeedAddPeriod = 0

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Stypeid)
BEGIN
	SELECT @CurrentPeroid = SubValue FROM dbo.sysdata WHERE SubName = 'fmonth'
	SELECT @CurrentYear = subvalue FROM dbo.sysdata WHERE SubName = 'fyear'
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FYear = @CurrentYear + 1)
		SET @ifNeedAddPeriod = 1
	
	SELECT  FYear,
			FPeriod,
			@LastPeriod - @CurrentPeroid AS periodvalue,
			CAST(@CurrentYear AS VARCHAR(20)) + '年' + CAST(@CurrentPeroid AS VARCHAR(20)) + '期' AS passperiod,
			FBegin,
			FEnd,
			@ifNeedAddPeriod AS needadd 
	FROM dbo.Ac_Period WHERE FPeriod = @CurrentPeroid AND FYear = @CurrentYear
END
ELSE
BEGIN
	--如果期间没有写入，写一次新年度的期间
	SELECT @CurrentYear = FYear FROM dbo.Ac_AccountsPeroid_Stype WHERE Stypeid = @Stypeid
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FYear = @CurrentYear)
	BEGIN
		EXEC dbo.Web_QueryOrUpdateSetNewAcPeriod @CurrentYear,2
	END
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Period WHERE FYear = @CurrentYear + 1)
		SET @ifNeedAddPeriod = 1

	SELECT  T1.FYear,
			T1.FPeriod,
			@LastPeriod - T1.FPeriod AS periodvalue,
			CAST(T1.FYear AS VARCHAR(20)) + '年' + CAST(T1.FPeriod AS VARCHAR(20)) + '期' AS passperiod,
			FBegin,
			FEnd,
			@ifNeedAddPeriod AS needadd
	FROM dbo.Ac_AccountsPeroid_Stype T1
		INNER JOIN dbo.Ac_Period T2 ON T1.FYear = T2.FYear AND T1.FPeriod = T2.FPeriod
		INNER JOIN dbo.SType T3 ON T1.Stypeid = T3.VerifyID
	WHERE T3.typeid = @Stypeid

END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetStypePUnits]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_GetStypePUnits
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 

GO
/*
	作者：魏伟
	日期：2016-05-13
	描述：查找分支机构商品对应单位
*/

CREATE PROCEDURE Web_GetStypePUnits
(
	@OperatorId		VARCHAR(100),	--操作员ID 
	@PTypeId		VARCHAR(MAX)	--商品ID	 
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

select  ut.FullName ,ut.unitsid,ex.isdefaultunit from ptype_units_ext ex
inner join ptype_units  ut on ex.unitsid=ut.unitsid
where  ex.ptypeid=@PTypeId  and ex.RateType=0 
order by ex.isdefaultunit desc

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetSuccorChargeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetSuccorChargeItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：赵斌
	日期：2011-4-28
	描述：根据条件查询救援收费项目
-------------------------------------------*/
CREATE PROCEDURE Web_GetSuccorChargeItems
(
	@filterstr	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE	@SQL	VARCHAR(MAX)
SET @SQL	=	'SELECT	* 
				 FROM	Qp_SuccorChargeItems 
				 WHERE	FullName LIKE ''%'+@filterstr+'%'' 
					 OR PYCode LIKE ''%'+@filterstr+'%''
				 ORDER	BY FullName'

EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GetTreeViewData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetTreeViewData]
GO

--得到基础信息的树 黄清 2013-05-27
CREATE        PROCEDURE Web_GetTreeViewData
(
  @operaterid	varchar(50),
  @parid		VARCHAR(50),
  @dbname		VARCHAR(50)
 )
 --@encode$--
 AS
 SET NOCOUNT ON 
 
 IF @dbname='btype'
 BEGIN
	SELECT	B.fullname,
			B.typeid,
			B.parid 
	FROM BType B 
    INNER JOIN F_GetManBType(@operaterid) F on F.typeId=B.typeId 
    WHERE B.sonnum<>0 AND B.typeId LIKE @parid+'%'
    RETURN
 END
 
IF @dbname='employee'
BEGIN
	SELECT	CASE WHEN T.FullName='超级用户' THEN '全部职员'
			ELSE T.fullname END AS fullname,
			T.typeid,
			T.parid 
	FROM employee T
	INNER JOIN F_GetManEType(@operaterid) F ON F.typeId=T.typeId
	WHERE T.sonnum<>0
	RETURN
END

IF @dbname='AreaType'
BEGIN
	SELECT	T.fullname,
			T.typeid,
			T.parid 
	FROM AreaType T 
	WHERE T.sonnum<>0
	RETURN
END


IF @dbname='Ac_Items'
BEGIN
	SELECT	T.fullname,
			T.typeid,
			T.parid 
	FROM Ac_Items T 
	WHERE T.sonnum<>0
	RETURN
END

IF @dbname='PTypeCategory'
BEGIN
	SELECT	T.fullname,
			T.typeid,
			T.parid 
	FROM PTypeCategory T 
	--WHERE T.sonnum<>0
	RETURN
END


DECLARE @SQL VARCHAR(MAX)
DECLARE @type VARCHAR(50)
SET @type=@dbname

IF @dbname='Department'
	SET @type='Dtype'
IF @dbname='stock'
	SET @type='Ktype'

SET @SQL='
SELECT	T.fullname,
		T.typeid,
		T.parid 
FROM '+@dbname+' T 
INNER JOIN F_GetMan'+@type+'('''+@operaterid+''') F on F.typeId=T.typeId  WHERE T.sonnum<>0 
UNION ALL 
SELECT T.fullname,T.typeid,T.parid FROM '+@dbname+' T WHERE T.typeId=''00000'''

--print (@sql)
EXEC(@SQL)
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetTwoDateMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetTwoDateMonth]
GO











/*
	作者：谢吉康
	日期：2009-01-07
	描述：月分析
*/
CREATE  PROCEDURE Web_GetTwoDateMonth
(
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@mPageNo		int,
	@rowCount		int  		OUTPUT,
	@sDate			datetime    OUTPUT,
	@eDate			datetime    OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE 
		@intBegin	int,
		@intEnd		int,
		@intBMonth	int,
		@intEMonth	int,
		@i			int

SET @intBegin = LEFT(@StartDate,4)+1
SET @intEnd   = LEFT(@EndDate,4)

SET @intBMonth =Month(@StartDate)-- SUBSTRING(@StartDate,6,2)
SET @intEMonth =Month(@EndDate)-- SUBSTRING(@EndDate,6,2)

CREATE TABLE #dDate
(
	nID			int identity(1,1),
	FullName	varchar(100),
	StartDate	datetime,
	EndDate		datetime
)
--开始年份处理
IF  @intBegin-1<@intEnd
	BEGIN
		IF (@intBegin-1) % 4 = 0
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
		ELSE
			WHILE @intBMonth<=12
				BEGIN
					IF @intBMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intBMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intBMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年0'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-0'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin-1 as varchar(4))+'年'+CAST(@intBMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intBegin-1 as varchar(4))+'-'+CAST(@intBMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intBMonth = @intBMonth + 1
				END
	END

--中间年份数据处理
WHILE @intBegin<@intEnd
	BEGIN
		SET @i = 1
		WHILE @i<=12
			BEGIN
				IF @i = 1
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年01月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-01-31' as varchar(100)))
				ELSE IF @i = 2
					BEGIN
						IF @intBegin % 4 = 0
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-29' as varchar(100)))
						ELSE
							INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年02月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-02-28' as varchar(100)))
					END
				ELSE IF @i = 3
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年03月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-03-31' as varchar(100)))
				ELSE IF @i = 4
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年04月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-04-30' as varchar(100)))
				ELSE IF @i = 5
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年05月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-05-31' as varchar(100)))
				ELSE IF @i = 6
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年06月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-06-30' as varchar(100)))
				ELSE IF @i = 7
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年07月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-07-31' as varchar(100)))
				ELSE IF @i = 8
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年08月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-08-31' as varchar(100)))
				ELSE IF @i = 9
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年09月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-09-30' as varchar(100)))
				ELSE IF @i = 10
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年10月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-10-31' as varchar(100)))
				ELSE IF @i = 11
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年11月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-11-30' as varchar(100)))
				ELSE IF @i = 12
					INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intBegin as varchar(4))+'年12月' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-01' as varchar(100)),CAST(CAST(@intBegin as varchar(4))+'-12-31' as varchar(100)))
				SET @i = @i + 1
			END

		SET @intBegin = @intBegin + 1
	END

--最后数据处理
IF @intBegin-1=@intEnd
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=@intBMonth
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END
ELSE
	BEGIN
		IF (@intEnd) % 4 = 0
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-29' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
		ELSE
			WHILE @intEMonth>=1
				BEGIN
					IF @intEMonth IN (1,3,5,7,8,10,12)
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-31' as varchar(100)))		
						END
					ELSE IF @intEMonth = 2
						INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-28' as varchar(100)))		
					ELSE
						BEGIN
							IF LEN(@intEMonth)=1
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年0'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-0'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
							ELSE
								INSERT INTO #dDate(FullName,StartDate,EndDate)VALUES(CAST(CAST(@intEnd as varchar(4))+'年'+CAST(@intEMonth AS varchar(2))+'月' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-01' as varchar(100)),CAST(CAST(@intEnd as varchar(4))+'-'+CAST(@intEMonth AS varchar(2))+'-30' as varchar(100)))	
						END
		
					SET @intEMonth = @intEMonth - 1
				END
	END

--处理开始日期和截止日期
DECLARE @nID		int,
		@rCount		int

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate ASC
UPDATE #dDate SET StartDate = @StartDate WHERE nID = @nID

SELECT TOP 1 @nID=nID FROM #dDate ORDER BY StartDate DESC
UPDATE #dDate SET EndDate = @EndDate WHERE nID = @nID

SELECT @rCount = COUNT(*) FROM #dDate

--日期所有行数
SET @rowCount = @rCount

--最后得到日期列表
DECLARE @TableHName 	varchar(200),
		@TableDName		varchar(200),
		@SQL 			varchar(8000)
SELECT 	@TableHName='WebH'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT 	@SQL='CREATE TABLE '+N'##'+@TableHName+'
	(
		nID			int identity(1,1),
		FullName	varchar(100),
		StartDate	datetime,
		EndDate		datetime
	)
	INSERT INTO '+N'##'+@TableHName+'(FullName,StartDate,EndDate)
	SELECT 	FullName,
			StartDate,
			EndDate 
	FROM 	#dDate 
	ORDER BY StartDate ASC'
EXEC(@SQL)

SELECT 	@TableDName='WebD'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SET @SQL = 'CREATE TABLE '+N'##'+@TableDName+'
			(
				nID			int identity(1,1),				
				StartDate	datetime,
				EndDate		datetime
			)
			INSERT INTO '+N'##'+@TableDName+'(StartDate,EndDate)
			SELECT	StartDate,
					EndDate
			FROM	'+N'##'+@TableHName+'
			WHERE	nID>'+CAST((@mPageNo-1)*12 as varchar(100))+'
					AND nID<='+CAST(@mPageNo*12 as varchar(100))+'
			ORDER BY nID ASC'
--PRINT(@SQL)
EXEC(@SQL)

DECLARE @sBeginDate 	datetime,
		@sEndDate		datetime

CREATE TABLE #rDate
(
	nID	int identity(1,1),
	dDate	datetime
)

--得到开始日期
SET @SQL = 'INSERT INTO #rDate(dDate)SELECT StartDate FROM '+N'##'+@TableDName+' WHERE nID = 1'
EXEC(@SQL)

--得到结束日期日期
SET @SQL = 'INSERT INTO #rDate(dDate)SELECT EndDate FROM '+N'##'+@TableDName+' WHERE nID = 12'
EXEC(@SQL)

SELECT @sDate = dDate FROM #rDate WHERE nID = 1
SELECT @eDate = dDate FROM #rDate WHERE nID = 2

--删除临时表
EXEC('DROP TABLE #dDate,#rDate,'+N'##'+@TableHName+','+N'##'+@TableDName)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetUserGroup]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetUserGroup]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2012-02-03
	描述：取得用户组
*/
CREATE PROCEDURE Web_GetUserGroup
(
	@etypeid varchar(2000)	--操作员id(操作员权限范围内的分组)
)
--@encode$--
AS
SET NOCOUNT ON;
SET NOCOUNT ON

IF @etypeid = '00001'
BEGIN
	SELECT	ugid,UGName,Comment 
	FROM	UserGroup
	ORDER BY UGName	
END
ELSE
BEGIN
	SELECT	U.UgId,U.ugname,U.Comment 
	FROM UserGroup U,UserGroupManage L
	WHERE	L.ETypeId=@etypeid 
			AND U.UgId = L.UgId
	ORDER BY ugname
	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetUserList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetUserList]
GO














/****** Object:  Stored Procedure dbo.Web_GetUserList    Script Date: 2002-6-20 10:14:54 ******/

CREATE  PROCEDURE [Web_GetUserList] 
(
@ETypeID [Varchar](25)
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @BNAME [Varchar](200)
DECLARE @EID [varchar](25)
SELECT @EID=MangerBTypeID FROM loginuser WHERE etypeid =@ETypeID
exec Web_GetParentPath1 @EID,2,@BNAME output
SELECT employee.FullName as 'fullname', employee.UserCode as 'usercode'
 ,cast(loginuser.password as varchar(10)) as 'password'
 ,loginuser.etypeid, loginuser.lim,loginuser.BtypeId as 'btypeid'
 ,@BNAME as 'btypename' 
FROM employee RIGHT OUTER JOIN  loginuser ON (employee.typeId = loginuser.etypeid) 
where loginuser.etypeid =@ETypeID















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetUserRange]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetUserRange]
GO




CREATE  PROCEDURE [dbo].[Web_GetUserRange]
(
	@etypeID varchar(50), @flag INT
)
--@encode$--	
AS
declare @tableName varchar(10)
declare @sql varchar(300)
if @flag = 0 or @flag = 1
  select @tableName = 'btype_l'
else if @flag = 2
  select @tableName = 'ptype_l'
else if @flag = 3
  select @tableName = 'ktype_l'
else if @flag = 4
  select @tableName = 'etype_l'
else            
  select @tableName = 'atype_l'

--分隔符
declare @splitter char(1)
set @splitter = '/'
--基本信息表名称
declare @infoTable varchar(10)
--根ID号
declare @rootID varchar(200)
--根名称
declare @rootName varchar(200)
--在loginUser中的字段名
declare @filedName varchar(20)
--表示全选的代码
declare @allCode varchar(10)
if @flag = 0          --客户
begin
  set @rootID = ''
  set @rootName = '全部客户'
  set @filedName = 'mangerbtypeid'
  set @infoTable = 'btype'
  set @allCode = '00001'
end
else if @flag = 1     --管辖供应商
begin
  set @rootID = ''
  set @rootName = '全部供应商'
  set @filedName = 'mangerbtypeid2'
  set @infoTable = 'btype'
  set @allCode = '00002'
end
else if @flag = 2     --管辖商品
begin
  set @rootID = ''
  set @rootName = '全部商品'
  set @filedName = 'mangerptypeid'
  set @infoTable = 'ptype'
  set @allCode = '00000'
end
else if @flag = 3     --管辖仓库
begin
  set @rootID = ''
  set @rootName = '全部仓库'
  set @filedName = 'mangerktypeid'
  set @infoTable = 'stock'
  set @allCode = '00000'
end
else if @flag = 4     --管辖职员
begin
  set @rootID = ''
  set @rootName = '全部职员'
  set @filedName = 'mangeretypeid'
  set @infoTable = 'etype'
  set @allCode = '00001'
end
else if @flag = 5     --管辖账户
begin
  set @rootID = ''
  set @rootName = '全部账户'
  set @filedName = 'mangeratypeid'
  set @infoTable = 'atype'
  set @allCode = '0000'
end
else if @flag = 6     --管辖费用 
begin
  set @rootID = ''
  set @rootName = '全部费用'
  set @filedName = 'mangerExpense'
  set @infoTable = 'atype'
  set @allCode = '0000'
end
else if @flag = 7     --管辖其他收入
begin
  set @rootID = ''
  set @rootName = '全部其他收入'
  set @filedName = 'mangerIncome'
  set @infoTable = 'atype'
  set @allCode = '0000'
end
else                  --管辖固定资产
begin
  set @rootID = ''
  set @rootName = '全部固定资产'
  set @filedName = 'mangercpaital'
  set @infoTable = 'atype'
  set @allCode = '0000'
end

declare @fullName varchar(200)

CREATE TABLE #tRange(typeID varchar(200), userCode varchar(200), [name] varchar(200), fullName varchar(200))

--是否用户使用了“全部”
declare @count int
--set @sql = N'select @count = count(*) from loginUser where etypeid = ' + char(39) + @etypeID + char(39) + ' and ' + @filedName + ' = ' + char(39) + '-99999' + char(39)
declare @nSql nvarchar(200)
set @nSql = N'select @count = count(*) from loginUser where etypeid = ' + char(39) + @etypeID + char(39) + ' and ' + @filedName + ' = ' + char(39) + @allCode + char(39)
exec sp_executesql @nSql, N'@count int output', @count output
--print @count
if @count = 1 --用户选择了全部
begin
  select '-99999' as typeID, @splitter + @rootName as fullName
end
else
begin
  declare @curTypeID varchar(200)
  declare @curUserCode varchar(200)
  declare @curFullName varchar(200)
  set @sql = 'select typeid from ' + @tableName + ' where flag = ''1'' and etypeid = ' + char(39) + @etypeID + char(39)
  if @flag = 5
    set @sql = @sql + ' and [type] = ' + char(39) + '0' + char(39)
  else if @flag = 6
    set @sql = @sql + ' and [type] = ' + char(39) + '1' + char(39)
  else if @flag = 7
    set @sql = @sql + ' and [type] = ' + char(39) + '2' + char(39)
  else if @flag = 8
    set @sql = @sql + ' and [type] = ' + char(39) + '3' + char(39)
  CREATE TABLE #t(etypeID varchar(200))
  exec ('insert into #t ' + @sql)
  print 'insert into #t ' + @sql
  declare @pathString varchar(400)  
  declare @times int
  declare @i int
  declare @parentID varchar(200)
  declare cur Cursor for
  select etypeID from #t
  open cur
  fetch next from cur into @curTypeID
  WHILE @@FETCH_STATUS = 0
  begin
    set @pathString = ''

    set @times = len(@curTypeID) / 5  
    set @i = 1
    print @curTypeID
    
    if @flag = 0 
        select @curFullName = fullName, @curUserCode = userCode from btype where deleted = 0 and typeid = @curTypeID and left(typeId, 5) = '00001'
    else if @flag = 1
      select @curFullName = fullName, @curUserCode = userCode from btype where deleted = 0 and typeid = @curTypeID and left(typeId, 5) = '00002'
    else if @flag = 2
      select @curFullName = fullName, @curUserCode = userCode from ptype where deleted = 0 and typeid = @curTypeID
    else if @flag = 3
      select @curFullName = fullName, @curUserCode = userCode from stock where deleted = 0 and typeid = @curTypeID
    else if @flag = 4
      select @curFullName = fullName, @curUserCode = userCode from employee where deleted = 0 and typeid = @curTypeID
    else
      select @curFullName = fullName, @curUserCode = userCode from atype where deleted = 0 and typeid = @curTypeID
    
    
    while @i <= @times
    begin
      set @parentID = left(@curTypeID, @i * 5)
      print @parentID      
      if @flag = 0 
        select @fullName = fullName from btype where deleted = 0 and typeid = @parentID and left(typeId, 5) = '00001'
      else if @flag = 1
        select @fullName = fullName from btype where deleted = 0 and typeid = @parentID and left(typeId, 5) = '00002'
      else if @flag = 2
        select @fullName = fullName from ptype where deleted = 0 and typeid = @parentID
      else if @flag = 3
        select @fullName = fullName from stock where deleted = 0 and typeid = @parentID
      else if @flag = 4
        select @fullName = fullName from employee where deleted = 0 and typeid = @parentID
      else if @flag = 5 --管辖账户
        select @fullName = fullName from atype where deleted = 0 and typeid = @parentID
      else if @flag = 6 --管辖费用           
        select @fullName = fullName from atype where deleted = 0 and typeid = @parentID
      else if @flag = 7 --管辖其他收入                        
        select @fullName = fullName from atype where deleted = 0 and typeid = @parentID
      else if @flag = 8 --管辖其他收入                        
        select @fullName = fullName from atype where deleted = 0 and typeid = @parentID
      if @@rowcount = 0
      begin
        set @pathString = @pathString + @splitter + '已停用'
        break
      end
      set @pathString = @pathString + @splitter + @fullName
      set @i = @i + 1
    end
    insert into #tRange values (@curTypeID, @curUserCode, @curFullName, @pathString)
    --print @times
    
    fetch next from cur into @curTypeID
  end
  close cur
  deallocate cur
  select * from #tRange;
  drop table #tRange
  drop table #t
end



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetUserSelectNameFromId]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetUserSelectNameFromId]
GO




/*
	作者:谢吉康
	日期:2009-10-21
	描述:获取基本信息的名称,从ID来算
	EXEC Web_GetUserSelectNameFromId '00090,00065','stock',''
*/
CREATE PROCEDURE Web_GetUserSelectNameFromId
(
	@typeid			varchar(MAX),
	@tablename		varchar(200),
	@returnstring	varchar(MAX) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL 		varchar(MAX)
DECLARE @rFullName	varchar(400),
		@tFullName	varchar(MAX)

SET @tFullName = ''

CREATE TABLE #Temp
(
	FullName varchar(400)
)

SET @SQL = 'DECLARE @FullName	varchar(400)

			DECLARE Tmp_Cursor CURSOR FOR
				SELECT FullName FROM '+@tablename+' WHERE TypeId IN (SELECT a FROM dbo.F_Split('''+@typeid+''','',''))

			OPEN Tmp_Cursor

			FETCH NEXT FROM Tmp_Cursor INTO @FullName

			WHILE @@FETCH_STATUS = 0
				BEGIN
					INSERT INTO #Temp(FullName)VALUES(@FullName)

					FETCH NEXT FROM Tmp_Cursor INTO @FullName
				END

			CLOSE Tmp_Cursor
			DEALLOCATE Tmp_Cursor'

--PRINT(@SQL)
EXEC(@SQL)

DECLARE Result_Cursor CURSOR FOR
	SELECT FullName FROM #Temp

OPEN Result_Cursor

FETCH NEXT FROM Result_Cursor INTO @rFullName

WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @tFullName = @tFullName + ';' + @rFullName

		FETCH NEXT FROM Result_Cursor INTO @rFullName
	END

CLOSE Result_Cursor
DEALLOCATE Result_Cursor
IF(LEN(@tFullName)<=0)  SET @returnstring=''
ELSE SET @returnstring = RIGHT(@tFullName,LEN(@tFullName)-1)

DROP TABLE #Temp




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetV3BtypeCredit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_GetV3BtypeCredit
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2010-12-27
-- Description: 信用额度管理
-- =============================================
CREATE PROCEDURE Web_GetV3BtypeCredit
(
	@BTypeId	VARCHAR(MAX)='',
	@OperatorId VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE  
	@IsUseBrandarType	INT=0,--是否启用品牌
	@BTypeAll			INT--是否统一客户供货商

IF EXISTS(SELECT * FROM SysData WHERE SubName='usebrandartype' AND SubValue=1)
	AND EXISTS(SELECT SubValue FROM SysData WHERE SubName='brandarcontrollineofcredit' AND SubValue=0)
	SET @IsUseBrandarType=1

SELECT @BTypeAll=Value FROM UserConfig WHERE ConfigName='BTypeAll'

SELECT
	C.BtypeId,
	C.Credit
FROM btype_credit C
INNER JOIN F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) F ON F.TypeId=C.BtypeId
INNER JOIN btype B ON B.typeId=C.BtypeId AND (@BTypeAll=1 OR (@BTypeAll=0 AND b.typeId LIKE '00001%')) AND (@IsUseBrandarType=0 OR (@IsUseBrandarType=1 AND B.IsUseBrandarType=0))
WHERE C.StypeId='00001'





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetVipAdjustData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetVipAdjustData]
GO




/*
	作者：谢吉康
	日期：2009-06-05
	描述：获取VIP调整或者积分单据信息
*/
CREATE PROCEDURE Web_GetVipAdjustData
(
	@cname		varchar(200),
	@nid		varchar(20),
	@ntype		int		--1.消费调整单  2.积分调整单
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @BillCode varchar(200),
		@Date	  varchar(20),
		@Head	  varchar(10)

IF @ntype = 1
	SET @Head = 'XFT'
ELSE
	SET @Head = 'JFC'

SET @Date = CONVERT(varchar(10),GetDate(),120)

EXEC Gp_GetAdjustCode @Head,@Date,@BillCode OUTPUT

DECLARE @OpTypeId	varchar(100),
		@OpName		varchar(300)

SET @OpTypeId = ''
SET @OpName = ''

IF @nid = 0
	BEGIN
		--系统配置，不允许修改经手人
		IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'BillEditEmployee' AND Value = '1') AND @cname <> '超级用户'
			BEGIN
				SELECT @OpTypeId = TypeId FROM Employee WHERE FullName = @cname
				SET @OpName = @cname
			END

		SELECT	@cname AS checke,	
				@BillCode AS billcode,
				@Date AS billdate,
				@OpTypeId as etypeid,
				@OpName as efullname,
				'' as cardno,
				'' as ckr,
				0 as upcost,
				0 as downcost,
				0 as sumcost,
				'' as reason,
				0 as issend
		FROM	Employee E
		WHERE	usercode = 'admin'
	END
ELSE
	SELECT	E.FullName AS checke,	
			n.BillCode AS billcode,
			n.BillDate AS billdate,
			n.etypeid,			
			efullname = (select top 1 fullname from employee where typeid = n.etypeid),
			c.vipcardcode as cardno,
			c.bname as ckr,
			n.upcost,
			n.downcost,
			n.sumcost,
			n.reason,
			n.issend
	FROM	Employee E,
			nVipAdjust n,
			nVipCardSign c
	WHERE	E.TypeId = n.Checke
			AND c.VipCardId = n.VipNo
			AND n.billnumberid = @nid





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_GetVipCardBatchSendSmsData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Web_GetVipCardBatchSendSmsData]
GO

/*
	作者：谢吉康
	日期：2018-11-08
	描述：会员卡批量发送消息获取数据
	EXEC Web_GetVipCardBatchSendSmsData '1,6',2
*/
CREATE PROCEDURE Web_GetVipCardBatchSendSmsData
(
	@vipcardids				VARCHAR(MAX),			--会员卡ID
	@smsid					VARCHAR(10)				--短信模版ID
)
AS
SET NOCOUNT ON

DECLARE @tempContent VARCHAR(MAX)

CREATE TABLE #VipGetDate
(
	vipcardid	VARCHAR(10),
	btel		VARCHAR(200),
	smscontent	VARCHAR(2000),
	senddate	VARCHAR(20)
)

DECLARE  @持卡人			VARCHAR(200),
		 @尾号				VARCHAR(10),
		 @分支机构			VARCHAR(200),
		 @仓库				VARCHAR(200),
		 @门店				VARCHAR(200),
		 @本次储值金额		NUMERIC(22,2), 
		 @储值余额			NUMERIC(22,2),
		 @本次消费金额		NUMERIC(22,2),
		 @本次积分			NUMERIC(22,2),
		 @积分余额			NUMERIC(22,2),
		 @本次储值结算金额	NUMERIC(22,2),
		 @原积分余额		NUMERIC(22,2),
		 @原储值余额		NUMERIC(22,2),
		 @兑换积分			NUMERIC(22,2),
		 @转储值金额		NUMERIC(22,2),
		 @vipcardid			INT,
		 @btel				VARCHAR(200)
		 
DECLARE VtempCursor CURSOR FOR 
	SELECT a FROM DBO.f_split(@vipcardids,',')
	
OPEN VtempCursor 

FETCH NEXT FROM VtempCursor INTO @vipcardid

WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT	@btel = v.btel,
			@持卡人 = V.bname,
			@尾号 = CASE WHEN LEN(v.VipCardCode)>=4 THEN RIGHT(v.VipCardCode,4) ELSE v.VipCardCode END,
			@分支机构 = CASE
							WHEN EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'proinfo' AND SubValue = '2')
								THEN (SELECT fullname FROM stype WHERE typeid = v.jkStypeId)
							ELSE 
								''
						END,
			@仓库 = '',
			@门店 = '',
			@本次储值金额 = 0,
			@储值余额 = V.cZyeMoney,
			@本次消费金额 = 0,
			@本次积分 = 0,
			@积分余额 = V.totalCent,
			@本次储值结算金额 = 0,
			@原积分余额 = v.totalCent,
			@原储值余额 = v.cZyeMoney,
			@兑换积分 = 0,
			@转储值金额 = 0
	FROM	dbo.nVipCardSign V
	WHERE	V.VipCardID = @vipcardid
	
	SELECT @tempContent = tempContent FROM dbo.SMSInfo_Template WHERE smsId = @smsid 
	
	SET @tempContent = REPLACE(@tempContent,'@持卡人',@持卡人)
	SET @tempContent = REPLACE(@tempContent,'@尾号',@尾号)
	SET @tempContent = REPLACE(@tempContent,'@分支机构',@分支机构)
	SET @tempContent = REPLACE(@tempContent,'@仓库',@仓库)
	SET @tempContent = REPLACE(@tempContent,'@门店',@门店)
	SET @tempContent = REPLACE(@tempContent,'@本次储值金额',@本次储值金额)
	SET @tempContent = REPLACE(@tempContent,'@储值余额',@储值余额)
	SET @tempContent = REPLACE(@tempContent,'@本次消费金额',@本次消费金额)	
	SET @tempContent = REPLACE(@tempContent,'@本次积分',@本次积分)
	SET @tempContent = REPLACE(@tempContent,'@积分余额',@积分余额)
	SET @tempContent = REPLACE(@tempContent,'@本次储值结算金额',@本次储值结算金额)
	SET @tempContent = REPLACE(@tempContent,'@原积分余额',@原积分余额)
	SET @tempContent = REPLACE(@tempContent,'@原储值余额',@原储值余额)
	SET @tempContent = REPLACE(@tempContent,'@兑换积分',@兑换积分)
	SET @tempContent = REPLACE(@tempContent,'@转储值金额',@转储值金额)
	SET @tempContent = REPLACE(@tempContent,'@系统时间',CONVERT(VARCHAR(20),GETDATE(),120))
	
	INSERT INTO #VipGetDate(vipcardid,btel,smscontent,senddate)VALUES(@vipcardid,@btel,@tempContent,CONVERT(VARCHAR(10),GETDATE(),120))          
	
	
	FETCH NEXT FROM VtempCursor INTO @vipcardid
END

CLOSE VtempCursor
DEALLOCATE VtempCursor

SELECT * FROM #VipGetDate

DROP TABLE #VipGetDate

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GetVoucherData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GetVoucherData]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：鲁大林
	日期：2012-4-5
	描述：获取凭证字信息
*/
CREATE PROCEDURE [Web_GetVoucherData]

--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Tem_Result
(
	vgid INT,
	fullname VARCHAR(2000),
	atypeid VARCHAR(2000),
	ismulvoulimit VARCHAR(200),
	ismulvoulimitname VARCHAR(2000),
	isdefault VARCHAR(200),
	isdefaultname VARCHAR(100),
	
	isdebit VARCHAR(2000),
	iscredit VARCHAR(2000),
	isdebitorcredit VARCHAR(2000),
	isnodebit VARCHAR(2000),
	isnocredit VARCHAR(2000),
	isnodebitandcredit VARCHAR(2000),
	
	isdebitname VARCHAR(2000),
	iscreditname VARCHAR(2000),
	isdebitorcreditname VARCHAR(2000),
	isnodebitname VARCHAR(2000),
	isnocreditname VARCHAR(2000),
	isnodebitandcreditname VARCHAR(2000),
	isuse	INT
)
CREATE TABLE #Tem_Table
(
	vgid INT,
	fullname VARCHAR(2000),
	atypeid VARCHAR(2000),
	isdebit INT,
	iscredit INT,
	isdebitorcredit INT,
	isnodebit INT,
	isnocredit INT,
	isnodebitandcredit INT
)
INSERT INTO #Tem_Table SELECT 
			A.VgId,
			B.FullName,
			A.ATypeId,
			A.isdebit,
			A.IsCredit,
			A.IsDebitOrCredit,
			A.IsNoCredit,
			A.IsNoDebit,
			A.IsNoDebitAndCredit
FROM Ac_Voucher_Group_Detail A,atype B WHERE A.ATypeId=B.typeId

DECLARE @atypeid VARCHAR(2000)='',
		@iscreditid VARCHAR(8000)='',
		@isdebitid VARCHAR(8000)='',
		@isdebitorcreditid	VARCHAR(8000)='',
		@isnodebitid VARCHAR(8000)='',
		@isnocreditid VARCHAR(8000)='',
		@isnodebitandcreditid VARCHAR(8000)='',
		
		@iscreditname VARCHAR(8000)='',
		@isdebitname VARCHAR(8000)='',
		@isdebitorcreditname VARCHAR(8000)='',
		@isnodebitname VARCHAR(8000)='',
		@isnocreditname VARCHAR(8000)='',
		@isnodebitancreditname VARCHAR(8000)='',
		@Flag VARCHAR(200),
		@fullName VARCHAR(2000),
		@ISMULVOUCHLIMIT VARCHAR(2000),
		@IsDefault VARCHAR(100),
		@IsUse		INT
DECLARE  curr CURSOR FOR
SELECT VgId,FullName,IsMulVourchLimit,IsDefault,dbo.Fn_GetIsUse_Items(VgId,9) isuse FROM Ac_Voucher_Group
OPEN curr
FETCH NEXT FROM curr INTO @Flag,@fullName,@ISMULVOUCHLIMIT,@IsDefault,@IsUse
WHILE @@FETCH_STATUS=0
	BEGIN
			SELECT @atypeid=atypeid FROM #Tem_Table WHERE iscredit=1 and vgid=@Flag
			SELECT @iscreditid=@iscreditid+atypeid+',' FROM #Tem_Table WHERE iscredit=1 and vgid=@Flag
			SELECT @isdebitid=@isdebitid+atypeid+',' FROM #Tem_Table WHERE isdebit=1 and vgid=@Flag
			SELECT @isdebitorcreditid=@isdebitorcreditid+atypeid+',' FROM #Tem_Table WHERE isdebitorcredit=1 and vgid=@Flag
			SELECT @isnodebitid=@isnodebitid+atypeid+',' FROM #Tem_Table WHERE isnodebit=1 and vgid=@Flag
			SELECT @isnocreditid=@isnocreditid+atypeid+',' FROM #Tem_Table WHERE isnocredit=1 and vgid=@Flag
			SELECT @isnodebitandcreditid=@isnodebitandcreditid+atypeid+',' FROM #Tem_Table WHERE isnodebitandcredit=1 and vgid=@Flag

			SELECT @iscreditname=@iscreditname+fullname+';' FROM #Tem_Table WHERE iscredit=1 and vgid=@Flag
			SELECT @isdebitname=@isdebitname+fullname+';' FROM #Tem_Table WHERE isdebit=1 and vgid=@Flag
			SELECT @isdebitorcreditname=@isdebitorcreditname+fullname+';' FROM #Tem_Table WHERE isdebitorcredit=1 and vgid=@Flag
			SELECT @isnodebitname=@isnodebitname+fullname+';' FROM #Tem_Table WHERE isnodebit=1 and vgid=@Flag
			SELECT @isnocreditname=@isnocreditname+fullname+';' FROM #Tem_Table WHERE isnocredit=1 and vgid=@Flag
			SELECT @isnodebitancreditname=@isnodebitancreditname+fullname+';' FROM #Tem_Table WHERE isnodebitandcredit=1 and vgid=@Flag
			
			INSERT	#Tem_Result
			        ( vgid ,
			          fullname ,
			          atypeid ,
			          ismulvoulimit,
					  ismulvoulimitname,
					  isdefault,
					  isdefaultname,
			          isdebit ,
			          iscredit ,
			          isdebitorcredit ,
			          isnodebit ,
			          isnocredit ,
			          isnodebitandcredit ,
			          isdebitname ,
			          iscreditname ,
			          isdebitorcreditname ,
			          isnodebitname ,
			          isnocreditname ,
			          isnodebitandcreditname,
			          isuse
			        )
			VALUES  ( 
						@Flag,
						@fullName,
						@atypeid,
						@ISMULVOUCHLIMIT,
						CASE @ISMULVOUCHLIMIT WHEN '1' THEN '受限' ELSE '不受限' END,
						@IsDefault,
						CASE @IsDefault WHEN '1' THEN '默认' ELSE NULL END,
						SUBSTRING(@iscreditid,0,LEN(@iscreditid)),
						SUBSTRING(@isdebitid,0,LEN(@isdebitid)),
						SUBSTRING(@isdebitorcreditid,0,LEN(@isdebitorcreditid)),
						SUBSTRING(@isnodebitid,0,LEN(@isnodebitid)),
						SUBSTRING(@isnocreditid,0,LEN(@isnocreditid)),
						SUBSTRING(@isnodebitandcreditid,0,LEN(@isnodebitandcreditid)),
						
						SUBSTRING(@iscreditname,0,LEN(@iscreditname)),
						SUBSTRING(@isdebitname,0,LEN(@isdebitname)),
						SUBSTRING(@isdebitorcreditname,0,LEN(@isdebitorcreditname)),
						SUBSTRING(@isnodebitname,0,LEN(@isnodebitname)),
						SUBSTRING(@isnocreditname,0,LEN(@isnocreditname)),
						SUBSTRING(@isnodebitancreditname,0,LEN(@isnodebitancreditname)),
						@IsUse
			        )
			SET	@iscreditid=''
	        SET	@isdebitid=''
	        SET	@isdebitorcreditid=''
	        SET	@isnodebitid=''
	        SET	@isnocreditid=''
	        SET	@isnodebitandcreditid=''
	        SET	@iscreditname=''
	        SET	@isdebitname=''
	        SET	@isdebitorcreditname=''
	        SET @isdebitorcreditname=''
			SET @isnodebitname=''
	        SET @isnocreditname=''
			SET @isnodebitancreditname=''
	FETCH NEXT FROM curr INTO @Flag,@fullName,@ISMULVOUCHLIMIT,@IsDefault,@IsUse;
			
	END
	
CLOSE curr
DEALLOCATE curr

SELECT * FROM #Tem_Result order by fullname
	DROP TABLE #Tem_Result
	DROP TABLE #Tem_Table

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_GetWmsUploadBillData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Web_GetWmsUploadBillData]
GO

/*
	作者：谢吉康
	日期：2018-10-17
	描述：获取WMS选择的单据信息
	EXEC Web_GetWmsUploadBillData '00001','1,301R1,301R2,300R1,34R1,34'
*/
CREATE PROCEDURE Web_GetWmsUploadBillData
(
	@billids			VARCHAR(MAX),			--单据信息
	@autoUpload			INT						--0:手工上传 1:自动上传 
)
AS
SET NOCOUNT ON

DECLARE @orderbill		VARCHAR(5000)='',
		@buybill		VARCHAR(5000)='',
		@buybackbill	VARCHAR(5000)='',
		@salebill		VARCHAR(5000)='',
		@salebackbill	VARCHAR(5000)=''

CREATE TABLE #SourceData
(
	nid		INT IDENTITY(1,1),
	nvalue	VARCHAR(100)
)

CREATE TABLE #BillData
(
	BillNumberid		NUMERIC(18,0),
	BillCode			VARCHAR(500),
	billdate			VARCHAR(20),
	BillType			INT,
	ktypeid				VARCHAR(50),
	ptypeid				VARCHAR(50),
	skuid				VARCHAR(50),
	qty					NUMERIC(24,10),
	detailid			INT,
	draft				INT,
	price				NUMERIC(24,10),
	total				NUMERIC(24,10),
	isgift				INT,
	btypeid				VARCHAR(50)
)

INSERT INTO #SourceData(nvalue)SELECT DISTINCT a FROM dbo.f_split(@billids,'R')

DECLARE @UploadRule INT		--单据上传规则 0=手工上传 1=保存时自动上传 2=过账后自动上传 3=每xx分钟自动上传一次
SELECT @UploadRule = Value FROM dbo.WMSBaseInfo WHERE Field = 'UploadRule'

IF @autoUpload = 0
BEGIN
	SELECT @orderbill += REPLACE(nvalue,',301','')+','  FROM #SourceData WHERE nvalue LIKE '%,301'
	SELECT @orderbill += REPLACE(nvalue,',300','')+','  FROM #SourceData WHERE nvalue LIKE '%,300'
	SELECT @buybill += REPLACE(nvalue,',34','')+','  FROM #SourceData WHERE nvalue LIKE '%,34'
	SELECT @buybackbill += REPLACE(nvalue,',6','')+','  FROM #SourceData WHERE nvalue LIKE '%,6'
	SELECT @salebill += REPLACE(nvalue,',11','')+','  FROM #SourceData WHERE nvalue LIKE '%,11'
	SELECT @salebackbill += REPLACE(nvalue,',45','')+','  FROM #SourceData WHERE nvalue LIKE '%,45'
END
ELSE IF @UploadRule = 1
BEGIN
	SELECT @orderbill += REPLACE(nvalue,',301','')+','  FROM #SourceData WHERE nvalue LIKE '%,301'
	SELECT @orderbill += REPLACE(nvalue,',300','')+','  FROM #SourceData WHERE nvalue LIKE '%,300'
	
	SELECT @buybill += CAST(b.BillNumberId AS VARCHAR)+','  
	FROM #SourceData s
	INNER JOIN dbo.BillIndex b ON b.billNumberId = REPLACE(s.nvalue,',34','') AND b.draft = 1
	WHERE nvalue LIKE '%,34'
	
	SELECT @buybackbill += CAST(b.BillNumberId AS VARCHAR)+','  
	FROM #SourceData s
	INNER JOIN dbo.BillIndex b ON b.billNumberId = REPLACE(s.nvalue,',6','') AND b.draft = 1
	WHERE nvalue LIKE '%,6'
	
	SELECT @salebill += CAST(b.BillNumberId AS VARCHAR)+','  
	FROM #SourceData s
	INNER JOIN dbo.BillIndex b ON b.billNumberId = REPLACE(s.nvalue,',11','') AND b.draft = 1
	WHERE nvalue LIKE '%,11'
	
	SELECT @salebackbill += CAST(b.BillNumberId AS VARCHAR)+','  
	FROM #SourceData s
	INNER JOIN dbo.BillIndex b ON b.billNumberId = REPLACE(s.nvalue,',45','') AND b.draft = 1
	WHERE nvalue LIKE '%,45'
END
ELSE IF @UploadRule = 2
BEGIN
	SELECT @orderbill += REPLACE(nvalue,',301','')+','  FROM #SourceData WHERE nvalue LIKE '%,301'
	SELECT @orderbill += REPLACE(nvalue,',300','')+','  FROM #SourceData WHERE nvalue LIKE '%,300'
	
	SELECT @buybill += CAST(b.BillNumberId AS VARCHAR)+','  
	FROM #SourceData s
	INNER JOIN dbo.BillIndex b ON b.billNumberId = REPLACE(s.nvalue,',34','') AND b.ifcheck = 't' AND b.RedWord =0
	WHERE nvalue LIKE '%,34'
	
	SELECT @buybackbill += CAST(b.BillNumberId AS VARCHAR)+','  
	FROM #SourceData s
	INNER JOIN dbo.BillIndex b ON b.billNumberId = REPLACE(s.nvalue,',6','') AND b.ifcheck = 't' AND b.RedWord =0
	WHERE nvalue LIKE '%,6'
	
	SELECT @salebill += CAST(b.BillNumberId AS VARCHAR)+','  
	FROM #SourceData s
	INNER JOIN dbo.BillIndex b ON b.billNumberId = REPLACE(s.nvalue,',11','') AND b.ifcheck = 't' AND b.RedWord =0
	WHERE nvalue LIKE '%,11'
	
	SELECT @salebackbill += CAST(b.BillNumberId AS VARCHAR)+','  
	FROM #SourceData s
	INNER JOIN dbo.BillIndex b ON b.billNumberId = REPLACE(s.nvalue,',45','') AND b.ifcheck = 't' AND b.RedWord =0
	WHERE nvalue LIKE '%,45'
END
ELSE
BEGIN
	SELECT * FROM #BillData
	DROP TABLE #BillData,#SourceData
	RETURN
END

INSERT INTO #BillData
( 
	BillNumberid, 
	BillCode,
	billdate,
	BillType,
	ktypeid,
	ptypeid,
	skuid,
	qty,
	detailid,
	draft,
	price,
	total,
	isgift,
	btypeid
)
SELECT	i.BillNumberId,
		i.BillCode,
		i.BillDate,
		i.BillType,
		ISNULL(sc.WMS_TypeId,'0') AS ktypeid,
		ISNULL(pc.WMS_TypeId,'0') AS ptypeid,
		ISNULL(pc.WMS_SKUId,'0') AS skuid,
		b.qty,
		b.OrderID,
		1,
		b.price,
		b.total,
		b.IsGift,
		ISNULL(bc.WMS_TypeId,'0') AS btypeid
FROM	dbo.OrderIndex i
INNER JOIN dbo.OrderBill b ON b.billNumberID = i.billNumberId
LEFT JOIN WmsErpPtypeContrastSetting pc ON pc.ERP_TypeId = b.ptypeid AND ISNULL(pc.ERP_CustomItemFrom,0) = b.IsCombined AND ISNULL(pc.ERP_SKUId,0) = b.ItemID
LEFT JOIN WmsErpStockContrastSetting sc ON sc.ERP_TypeId = b.ktypeid
LEFT JOIN WmsErpBTypeContrastSetting bc ON bc.ERP_TypeId=i.btypeid
WHERE	i.BillNumberId IN (SELECT a FROM dbo.f_split(@orderbill,','))
UNION ALL 
SELECT	i.BillNumberId,
		i.BillCode,
		i.BillDate,
		i.BillType,
		ISNULL(sc.WMS_TypeId,'0') AS ktypeid,
		ISNULL(pc.WMS_TypeId,'0') AS ptypeid,
		ISNULL(pc.WMS_SKUId,'0') AS skuid,
		b.qty,
		b.ID,
		i.draft,
		b.TaxPrice,
		b.total,
		b.IsGift,
		ISNULL(bc.WMS_TypeId,'0') AS btypeid
FROM	dbo.BillIndex i
INNER JOIN dbo.BuyBill b ON b.BillNumberId = i.BillNumberId
LEFT JOIN WmsErpPtypeContrastSetting pc ON pc.ERP_TypeId = b.ptypeid AND ISNULL(pc.ERP_CustomItemFrom,0) = b.IsCombined AND ISNULL(pc.ERP_SKUId,0) = b.ItemID
LEFT JOIN WmsErpStockContrastSetting sc ON sc.ERP_TypeId = b.ktypeid
LEFT JOIN WmsErpBTypeContrastSetting bc ON bc.ERP_TypeId=i.btypeid
WHERE	i.BillNumberId IN (SELECT a FROM dbo.f_split(@buybill,','))
UNION ALL
SELECT	i.BillNumberId,
		i.BillCode,
		i.BillDate,
		i.BillType,
		ISNULL(sc.WMS_TypeId,'0') AS ktypeid,
		ISNULL(pc.WMS_TypeId,'0') AS ptypeid,
		ISNULL(pc.WMS_SKUId,'0') AS skuid,
		b.qty,
		b.ID,
		i.draft,
		b.TaxPrice,
		b.total,
		b.IsGift,
		ISNULL(bc.WMS_TypeId,'0') AS btypeid
FROM	dbo.BillIndex i
INNER JOIN dbo.BuyBackBill b ON b.BillNumberId = i.BillNumberId
LEFT JOIN WmsErpPtypeContrastSetting pc ON pc.ERP_TypeId = b.ptypeid AND ISNULL(pc.ERP_CustomItemFrom,0) = b.IsCombined AND ISNULL(pc.ERP_SKUId,0) = b.ItemID
LEFT JOIN WmsErpStockContrastSetting sc ON sc.ERP_TypeId = b.ktypeid
LEFT JOIN WmsErpBTypeContrastSetting bc ON bc.ERP_TypeId=i.btypeid
WHERE	i.BillNumberId IN (SELECT a FROM dbo.f_split(@buybackbill,','))
UNION ALL
SELECT	i.BillNumberId,
		i.BillCode,
		i.BillDate,
		i.BillType,
		ISNULL(sc.WMS_TypeId,'0') AS ktypeid,
		ISNULL(pc.WMS_TypeId,'0') AS ptypeid,
		ISNULL(pc.WMS_SKUId,'0') AS skuid,
		b.qty,
		b.ID,
		i.draft,
		b.TaxPrice,
		b.total,
		b.IsGift,
		ISNULL(bc.WMS_TypeId,'0') AS btypeid
FROM	dbo.BillIndex i
INNER JOIN dbo.SaleBill b ON b.BillNumberId = i.BillNumberId
LEFT JOIN WmsErpPtypeContrastSetting pc ON pc.ERP_TypeId = b.ptypeid AND ISNULL(pc.ERP_CustomItemFrom,0) = b.IsCombined AND ISNULL(pc.ERP_SKUId,0) = b.ItemID
LEFT JOIN WmsErpStockContrastSetting sc ON sc.ERP_TypeId = b.ktypeid
LEFT JOIN WmsErpBTypeContrastSetting bc ON bc.ERP_TypeId=i.btypeid
WHERE	i.BillNumberId IN (SELECT a FROM dbo.f_split(@salebill,','))
UNION ALL
SELECT	i.BillNumberId,
		i.BillCode,
		i.BillDate,
		i.BillType,
		ISNULL(sc.WMS_TypeId,'0') AS ktypeid,
		ISNULL(pc.WMS_TypeId,'0') AS ptypeid,
		ISNULL(pc.WMS_SKUId,'0') AS skuid,
		b.qty,
		b.ID,
		i.draft,
		b.TaxPrice,
		b.total,
		b.IsGift,
		ISNULL(bc.WMS_TypeId,'0') AS btypeid
FROM	dbo.BillIndex i
INNER JOIN dbo.saleBackBill b ON b.BillNumberId = i.BillNumberId
LEFT JOIN WmsErpPtypeContrastSetting pc ON pc.ERP_TypeId = b.ptypeid AND ISNULL(pc.ERP_CustomItemFrom,0) = b.IsCombined AND ISNULL(pc.ERP_SKUId,0) = b.ItemID
LEFT JOIN WmsErpStockContrastSetting sc ON sc.ERP_TypeId = b.ktypeid
LEFT JOIN WmsErpBTypeContrastSetting bc ON bc.ERP_TypeId=i.btypeid
WHERE	i.BillNumberId IN (SELECT a FROM dbo.f_split(@salebackbill,','))

SELECT * FROM #BillData

DROP TABLE #SourceData,#BillData

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_GoodsBigTypeSelect_List]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].Web_GoodsBigTypeSelect_List
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
	作者：蒋奎
	日期：2014-5-20
	描述：打印条码可选商品大类
-------------------------------------------*/
CREATE PROCEDURE Web_GoodsBigTypeSelect_List
  (
	@TypeID		VARCHAR(100),		--商品ID
    @OperatorID varchar(50),		--操作员ID
    @ntype BIT,						--下一步状态
	@usercode		VARCHAR(200),	--编码
	@Fullname		VARCHAR(200),	--名称
	@entrycode		VARCHAR(200),	--条码
	@paridq		VARCHAR(100),		--前台传的父节点ID
	@selectType varchar(50),		--查询类型
	@STypeId		VARCHAR(MAX)	--分支机构ID

  )
--@encode$--
AS
SET NOCOUNT ON

BEGIN

---------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
---------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------



DECLARE @SQLPrice VARCHAR(max)

CREATE TABLE #GoodsInfoPrice
(
	TypeID		VARCHAR(100),
	ParId		VARCHAR(100),
	SonNum		INT,
	deleted		INT,			
	PyCode		VARCHAR(256),
	entrycode	VARCHAR(MAX),
	UserCode	VARCHAR(256),
	FullName	VARCHAR(256),
	name		VARCHAR(256),
	area		VARCHAR(256),
	[standard]	VARCHAR(256),
	[type]		VARCHAR(256),
	BuyUnitId	INT,
	SaleUnitId	INT,
	StockUnitId INT,
	baseunitid	INT,
	IfUseEntryCode INT,
	prebuyprice1  NUMERIC(24, 10) ,
	prebuyprice2  NUMERIC(24, 10) ,
	prebuyprice3  NUMERIC(24, 10) ,
	prebuyprice4  NUMERIC(24, 10) ,
	prebuyprice5  NUMERIC(24, 10) ,
	topbuyprice   NUMERIC(24, 10) ,
	PreSalePrice1  NUMERIC(24, 10) ,
	PreSalePrice2  NUMERIC(24, 10) ,
	PreSalePrice3  NUMERIC(24, 10) ,
	PreSalePrice4  NUMERIC(24, 10) ,
	PreSalePrice5  NUMERIC(24, 10) ,
	PreSalePrice6  NUMERIC(24, 10) ,
	PreSalePrice7  NUMERIC(24, 10) ,
	PreSalePrice8  NUMERIC(24, 10) ,
	PreSalePrice9  NUMERIC(24, 10) ,
	PreSalePrice10  NUMERIC(24, 10) ,
	RetailPrice  NUMERIC(24, 10) ,
	TopSalePrice  NUMERIC(24, 10) ,
	LowSalePrice  NUMERIC(24, 10) ,
	buyunitfullname VARCHAR(200),
	buyunitusercode VARCHAR(200),
	saleunitfullname VARCHAR(200),
	saleunitusercode VARCHAR(200),
	baseunitfullname VARCHAR(200),
	baseunitusercode VARCHAR(200),
	stockunitfullname VARCHAR(200),
	stockunitusercode VARCHAR(200),
	customitemid VARCHAR(20),
	customitemfrom VARCHAR(20),
	customitemname VARCHAR(max),
	sortid INT,
	UsefulLifeDay	INT,	--有效期
	ValidDays		INT		--效期至
)

--根据权限出数据

/*判断有没有启用分支机构价格*/
DECLARE @Type int
set @Type=(select top 1 pricetype from stype where typeid=@stypeid)

IF	@Type=1  --启用了分支机构价格
BEGIN
SET @SQLPrice = '	INSERT INTO #GoodsInfoPrice 
					(
						TypeID		,
						ParId		,
						SonNum		,
						deleted		,		
						PyCode		,
						entrycode	,
						UserCode	,
						FullName	,
						name		,
						area		,
						standard	,
						type		,
						BuyUnitId	,
						SaleUnitId	,
						StockUnitId ,
						baseunitid	,
						IfUseEntryCode ,
						prebuyprice1,
						prebuyprice2,
						prebuyprice3,
						prebuyprice4,
						prebuyprice5,
						topbuyprice,
						PreSalePrice1 ,
						PreSalePrice2 ,
						PreSalePrice3 ,
						PreSalePrice4 ,
						PreSalePrice5 ,
						PreSalePrice6 ,
						PreSalePrice7 ,
						PreSalePrice8 ,
						PreSalePrice9 ,
						PreSalePrice10 ,
						RetailPrice ,
						TopSalePrice ,
						LowSalePrice ,
						buyunitfullname ,
						buyunitusercode ,
						saleunitfullname ,
						saleunitusercode ,
						baseunitfullname ,
						baseunitusercode ,
						stockunitfullname ,
						stockunitusercode ,
						customitemid  ,
						customitemfrom  ,
						customitemname  ,
						sortid,
						UsefulLifeDay,
						ValidDays
					)
					SELECT  a.TypeId,a.ParId,a.SonNum,a.deleted,a.PyCode,
							a.EntryCode,
							a.usercode,
							a.fullname,
							a.name,
							a.area,
							a.Standard,
							a.type,
							a.BuyUnitId,
							a.SaleUnitId,
							a.StockUnitId,
							a.baseunitid,
							a.IfUseEntryCode,
							b.prebuyprice1,
							b.prebuyprice2,
							b.prebuyprice3,
							b.prebuyprice4,
							b.prebuyprice5,
							b.topbuyprice,
							b.PreSalePrice1,
							b.PreSalePrice2,
							b.PreSalePrice3,
							b.PreSalePrice4,
							b.PreSalePrice5,
							b.PreSalePrice6,
							b.PreSalePrice7,
							b.PreSalePrice8,
							b.PreSalePrice9,
							b.PreSalePrice10, 
							b.RetailPrice,
							b.TopSalePrice,
							b.LowSalePrice,
							u1.fullname as buyunitfullname,
							u1.usercode as buyunitusercode,
							u2.fullname as saleunitfullname,
							u2.usercode as saleunitusercode,
							u3.fullname as baseunitfullname,
							u3.usercode as baseunitusercode,
							u4.fullname as stockunitfullname,
							u4.usercode as stockunitusercode,
							a.customitemid ,
							a.customitemfrom ,
							a.customitemname,
							a.sortid,
							a.UsefulLifeDay,
							a.ValidDays
					FROM F_GetManPTypeAll('''+@OperatorId+''')  a 
					LEFT JOIN PType_STypePrice  b on  (a.TypeID=b.PTypeID AND b.STypeID='''+@STypeId+''' AND b.UnitID = a.baseUnitId )
					LEFT join PType_Units u1 on u1.unitsid=a.buyunitid
					LEFT join PType_Units u2 on u2.unitsid=a.saleunitid
					LEFT join PType_Units u3 on u3.unitsid=a.baseunitid
					LEFT join PType_Units u4 on u4.unitsid=a.stockunitid
					
					' 
END
ELSE --没有启用分支机构价格
BEGIN
	 SET @SQLPrice = 'INSERT INTO #GoodsInfoPrice 
					 (	
						TypeID		,
						ParId		,
						SonNum		,
						deleted		,		
						PyCode		,
						entrycode	,
						UserCode	,
						FullName	,
						name		,
						area		,
						standard	,
						type		,
						BuyUnitId	,
						SaleUnitId	,
						StockUnitId ,
						baseunitid	,
						IfUseEntryCode ,
						prebuyprice1,
						prebuyprice2,
						prebuyprice3,
						prebuyprice4,
						prebuyprice5,
						topbuyprice,
						PreSalePrice1 ,
						PreSalePrice2 ,
						PreSalePrice3 ,
						PreSalePrice4 ,
						PreSalePrice5 ,
						PreSalePrice6 ,
						PreSalePrice7 ,
						PreSalePrice8 ,
						PreSalePrice9 ,
						PreSalePrice10 ,
						RetailPrice ,
						TopSalePrice ,
						LowSalePrice ,
						buyunitfullname ,
						buyunitusercode ,
						saleunitfullname ,
						saleunitusercode ,
						baseunitfullname ,
						baseunitusercode ,
						stockunitfullname ,
						stockunitusercode, 
						customitemid  ,
						customitemfrom  ,
						customitemname  ,
						sortid,
						UsefulLifeDay,
						ValidDays
					)
					SELECT  a.TypeId,a.ParId,a.SonNum,a.deleted,a.PyCode,
							a.EntryCode,
							a.usercode,
							a.fullname,
							a.name,
							a.area,
							a.Standard,
							a.type,
							a.BuyUnitId,
							a.SaleUnitId,
							a.StockUnitId,
							a.baseunitid,
							a.IfUseEntryCode,
							a.prebuyprice1,
							a.prebuyprice2,
							a.prebuyprice3,
							a.prebuyprice4,
							a.prebuyprice5,
							a.topbuyprice,
							a.PreSalePrice1,
							a.PreSalePrice2,
							a.PreSalePrice3,
							a.PreSalePrice4,
							a.PreSalePrice5,
							a.PreSalePrice6,
							a.PreSalePrice7,
							a.PreSalePrice8,
							a.PreSalePrice9,
							a.PreSalePrice10, 
							a.RetailPrice,
							a.TopSalePrice,
							a.LowSalePrice,
							u1.fullname as buyunitfullname,
							u1.usercode as buyunitusercode,
							u2.fullname as saleunitfullname,
							u2.usercode as saleunitusercode,
							u3.fullname as baseunitfullname,
							u3.usercode as baseunitusercode,
							u4.fullname as stockunitfullname,
							u4.usercode as stockunitusercode,
							a.customitemid ,
							a.customitemfrom ,
							a.customitemname  ,
							a.sortid,
							a.UsefulLifeDay,
							a.ValidDays
						FROM F_GetManPTypeAll('''+@OperatorId+''')  a 
 						LEFT join PType_Units u1 on u1.unitsid=a.buyunitid
						LEFT join PType_Units u2 on u2.unitsid=a.saleunitid
						LEFT join PType_Units u3 on u3.unitsid=a.baseunitid
						LEFT join PType_Units u4 on u4.unitsid=a.stockunitid '
END
 

	

--初次加载和查询空时事件
IF @TypeID ='' AND @usercode='' AND @Fullname='' AND @entrycode='' AND @selectType=''
	SET @SQLPrice +=' SELECT * FROM #GoodsInfoPrice WHERE ParId =''00000'' ORDER BY sortid '
				
	
--查询有值时事件
IF @usercode <> '' OR @Fullname <> '' OR @entrycode <> ''
BEGIN
	SET @SQLPrice+=' SELECT * FROM #GoodsInfoPrice WHERE 1=1 and sonnum=0 '
	IF @usercode <> ''
		SET @SQLPrice +=' and usercode LIKE ''%'+ @usercode+'%'''
	IF @Fullname <> '' 	
		SET @SQLPrice +=' and Fullname LIKE ''%'+ @Fullname+'%'''	
	IF @entrycode  <> '' 	
		SET @SQLPrice +=' AND EntryCode LIKE ''%'+ @entrycode+'%'''		
END

EXEC (@SQLPrice)

--上一层下一层查询

IF @TypeID <>''
BEGIN
	
	DECLARE @SonNumPrice INT
	DECLARE @ParId	VARCHAR(100)
	SELECT @SonNumPrice = SonNum,@ParId=ParId FROM #GoodsInfoPrice WHERE TypeId = @TypeId
	
	--上一层
	
	IF @ntype='0' 
		SELECT * FROM #GoodsInfoPrice WHERE ParId = @ParId ORDER BY sortid
	--下一层
	
	IF @ntype='1' 
		SELECT * FROM #GoodsInfoPrice WHERE ParId = @TypeId ORDER BY sortid
			
END

-- 选择该类事件
IF @TypeID='' AND @selectType='selectThisType'
BEGIN
	DECLARE @SQLPriceType VARCHAR(max)
	SET @SQLPriceType='
	SELECT  * FROM #GoodsInfoPrice WHERE ParId like '''+@paridq+ '%'' AND sonnum=0 ORDER BY sortid	'
	EXEC(@SQLPriceType)
END

	DROP TABLE #GoodsInfoPrice
	
END

--PRINT(@SQLPrice)

  
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GoodsGetGatherInstat]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GoodsGetGatherInstat]
GO












/****** Object:  Stored Procedure dbo.Web_GoodsGetInstat    Script Date: 2002-6-20 10:14:54 ******/
CREATE        PROCEDURE Web_GoodsGetGatherInstat
(
	@StartDate	varchar(30),
	@EndDate	varchar(30),
	@PTypeId	varchar(25),
	@BTypeId	varchar(25),
	@ETypeId	varchar(25),
	@KTypeId	varchar(25),
	@chvOperatorID	varchar(30)	-- 11、操作员 ID（作权限范围检查用）
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------
-- ********	卢春 2003-03-05	- Start	********
-- 增加客户供货商统一判断
DECLARE @BTypeAll varchar(50)
SELECT @BTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'
-- ********	卢春 2003-03-05	- End	********
DECLARE @sql varchar(2000),@where_sql varchar(2000),@length varchar(2)
SELECT @where_sql=''
SELECT @sql=''
IF (ISDATE(RTRIM(@StartDate))=1)
  SELECT @where_sql=' AND a.BillDate>='+CHAR(39)+@StartDate+CHAR(39)
IF (ISDATE(RTRIM(@EndDate))=1)
  SELECT @where_sql=@where_sql+' AND a.BillDate<='+CHAR(39)+@EndDate+CHAR(39)
IF RTRIM(@PTypeId)=''
  BEGIN
    SELECT @PTypeId='00000'
   -- SELECT @where_sql=@where_sql+' AND a.PtypeId Like '+CHAR(39)+@PTypeId+'%'+CHAR(39)
  END
IF RTRIM(@BTypeId)!=''
	BEGIN
		IF @BTypeAll = '1' AND @BTypeID = '00000'	-- 客户供货商统一，且全选所有供货商
			SELECT @where_sql=@where_sql+' AND ( a.BtypeId Like ''' + @chvMBTypeID + '%'' OR a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'' )'
		ELSE
			SELECT @where_sql=@where_sql+' AND a.BtypeId Like ''' + @BTypeID + '%'' AND a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'''
	END
IF RTRIM(@ETypeId)!=''
  SELECT @where_sql=@where_sql+' AND a.EtypeId Like ''' + @ETypeId + '%'' AND a.ETypeID LIKE ''' + @chvMETypeID + '%'''
IF RTRIM(@KTypeId)!=''
  SELECT @where_sql=@where_sql+' AND ( ( a.KtypeId Like ''' + @KTypeId + '%'' AND a.KTypeID LIKE ''' + @chvMKTypeID + '%'' ) OR a.KTypeID = ''10000'' )'
DECLARE @bIsLeaf bit
SELECT @bIsLeaf=CASE 
                                    WHEN EXISTS((SELECT * FROM PType WHERE TypeID=@PTypeId AND SonNum=0)) THEN 1
                                    ELSE 0
                                END

IF @bIsLeaf=0 
SELECT @sql='
	select 	PtypeNo,
		Usercode,
		Fullname,
		Unit1,
		sonnum,
		isnull(sum(Sum_Qty),0) as Sum_Qty,
		isnull(sum(Sum_Total),0) as Sum_Total,
		isnull(sum(Sum_TaxTotal),0) as Sum_TaxTotal
		parid,
		BillNumberid,
		BtypeId,
		KtypeId,
		EtypeId,
		PtypeId
	from (
		SELECT 	b.parid,
			b.TypeID AS PtypeNo,
			b.UserCode,
			b.FullName AS FullName,
			b.Unit1,
			b.sonnum,
			t.*
 		from 	ptype b 
			left join(
					select 	c.BtypeId,
						c.KtypeId,
						c.EtypeId,
						a.BillNumberId,
						a.PtypeId,
						Sum_Qty= Case c.BillType when 145 Then -1*sum(a.Qty) Else sum(a.Qty) End,					
				             	Sum_Total=Case c.BillType When 145 Then -1*sum(a.Total) Else sum(a.Total) End,
						Sum_TaxTotal=Case c.BillType When 145 Then -1*SUM(a.Total*(100+c.Tax)/100)Else SUM(a.Total*(100+c.Tax)/100) End 
				        FROM 	InOutstocktable a,
						BillIndex c
				        WHERE 	(c.BillType=34 OR c.BillType=6 or c.BillType = 145) 
						AND a.BillNumberId=c.BillNumberId  '+@where_sql+' 
					GROUP BY a.pTypeId,c.BillType,a.BillNumberId,c.BtypeId,c.KtypeId,c.EtypeId
				) t on left(t.PtypeId,LEN(b.TypeId))=b.typeId 
		where 	b.parid='''+@Ptypeid+''' and b.deleted=0) con 
			group by PtypeNo,Usercode,Fullname,Unit1,sonnum,parid,BillNumberid,BtypeId,KtypeId,EtypeId,PtypeId ORDER BY Usercode'

else

SELECT @sql='
		select 	PtypeNo,
			Usercode,
			Fullname,
			Unit1,
			sonnum,
			isnull(sum(Sum_Qty),0) as Sum_Qty,
			isnull(sum(Sum_Total),0) as Sum_Total,
			isnull(sum(Sum_TaxTotal),0) as Sum_TaxTotal
		from (
			SELECT 	b.TypeID AS PtypeNo,
				b.UserCode,
				b.FullName AS FullName,
				b.Unit1,
				b.sonnum,
				t.*
			 from 	ptype b 
				left join(
						select 	a.PtypeId,
							SUM(a.Qty) AS Sum_Qty,
					             	cast(SUM(a.Total) as  NUMERIC(24, 10) ) AS Sum_Total,
							cast(SUM(a.Total*(100+c.Tax)/100) as  NUMERIC(24, 10) ) AS Sum_TaxTotal
					        FROM 	InOutstocktable a,
							BillIndex c
				             	WHERE 	(c.BillType=34 OR c.BillType=6 or c.BillType = 145) 
							AND a.BillNumberId=c.BillNumberId  '+@where_sql+' 
						GROUP BY a.pTypeId
					) t on t.PtypeId=b.typeId 
			where b.Typeid='''+@Ptypeid+''' and b.deleted=0) con 
			group by PtypeNo,Usercode,Fullname,Unit1,sonnum ORDER BY Usercode'
--print @sql
exec(@sql)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GoodsGetInBtypeSale]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GoodsGetInBtypeSale]
GO











/****** Object:  Stored Procedure dbo.Web_GoodsGetInBtypeSale    Script Date: 2002-6-20 10:14:54 ******/
CREATE      PROCEDURE Web_GoodsGetInBtypeSale(
	@StartDate	varchar(30),
	@EndDate	varchar(30),
	@PTypeId	varchar(25),
	@BTypeId	varchar(25),
	@ETypeId	varchar(25),
	@KTypeId	varchar(25),
	@chvOperatorID	varchar(30)	-- 11、操作员 ID（作权限范围检查用）
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------
-- ********	卢春 2003-03-05	- Start	********
-- 增加客户供货商统一判断
DECLARE @BTypeAll varchar(50)
SELECT @BTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'
-- ********	卢春 2003-03-05	- End	********
DECLARE @sql varchar(2000),@where_sql varchar(2000),@length varchar(2)
SELECT @where_sql=''
SELECT @length=''
IF (ISDATE(RTRIM(@StartDate))=1)
  SELECT @where_sql=' AND a.BillDate>='+CHAR(39)+@StartDate+CHAR(39)
IF (ISDATE(RTRIM(@EndDate))=1)
  SELECT @where_sql=@where_sql+' AND a.BillDate<='+CHAR(39)+@EndDate+CHAR(39)
DECLARE @BType_Where varchar(100)
SELECT @BType_Where = ''
IF RTRIM(@BTypeID) != ''
	BEGIN
		IF @BTypeAll = '1' AND @BTypeID <> '00000'	-- 客户供货商统一，且点选了下级目录
			SELECT @BType_Where = 'AND ( b.TypeID LIKE ''' + @chvMBTypeID + '%'' OR b.TypeID LIKE ''' + @chvMBTypeID2 + '%'' )'
		IF @BTypeAll = '1' AND @BTypeID = '00000'	-- 客户供货商统一，且在根目录
			SELECT @where_sql = ' AND ( a.BTypeID LIKE ''' + @chvMBTypeID + '%'' OR a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'' )'
	END
IF RTRIM(@BTypeId)=''
  BEGIN
    SELECT @BtypeID='00000'
   
  END
IF RTRIM(@PTypeId)!=''
  SELECT @where_sql=@where_sql+' AND a.PtypeId Like ''' + @PTypeId + '%'' AND a.PTypeID LIKE ''' + @chvMPTypeID + '%'''
IF RTRIM(@ETypeId)!=''
  SELECT @where_sql=@where_sql+' AND a.EtypeId Like ''' + @ETypeId + '%'' AND a.ETypeID LIKE ''' + @chvMETypeID + '%'''
IF RTRIM(@KTypeId)!=''
  SELECT @where_sql=@where_sql+' AND ( ( a.KtypeId Like ''' + @KTypeId + '%'' AND a.KTypeID LIKE ''' + @chvMKTypeID + '%'' ) OR a.KTypeID = ''10000'' )'
DECLARE @bIsLeaf bit
SELECT @bIsLeaf=CASE 
                                    WHEN EXISTS((SELECT * FROM BType WHERE TypeID=@BTypeId AND SonNum=0)) THEN 1
                                    ELSE 0

                                END

IF @bIsLeaf=0 
SELECT @sql=
'Select BtypeNo,UserCode,FullName,Sonnum,isnull(Sum(Sum_Qty),0) as Sum_Qty,isnull(sum(Sum_Total),0) as Sum_Total ,isnull(sum(Sum_TaxTotal),0) as Sum_TaxTotal
from (
SELECT b.TypeID AS BtypeNo,b.UserCode AS UserCode,b.FullName AS FullName,b.sonnum,t.*
FROM Btype b left join (
			Select 	a.bTypeID,
				Sum_Qty= Case c.BillType when 145 Then -1*sum(a.Qty) Else sum(a.Qty) End,					
			 	Sum_Total=Case c.BillType When 145 Then -1*sum(a.Total) Else sum(a.Total) End,
				Sum_TaxTotal=Case c.BillType When 145 Then -1*SUM(a.Total*(100+c.Tax)/100) Else SUM(a.Total*(100+c.Tax)/100) End 
             FROM  InOutstocktable a  inner join BillIndex c on(a.BillNumberId=c.BillNumberId)
             WHERE (c.BillType=34 OR c.BillType=6 OR c.BillType = 145 )   '+@where_sql+' GROUP BY a.bTypeID,c.BillType
) t  on(LEFT(t.BtypeId,LEN(b.typeID))=b.typeId)
   WHERE  b.parid='''+@btypeid+''' ' + @BType_Where + ' and b.deleted=0) a
 group by BtypeNo,UserCode,FullName,Sonnum ORDER BY Usercode'
else
SELECT @sql=
'Select BtypeNo,UserCode,FullName,Sonnum,isnull(Sum(Sum_Qty),0) as Sum_Qty,isnull(sum(Sum_Total),0) as Sum_Total ,isnull(sum(Sum_TaxTotal),0) as Sum_TaxTotal

from (
SELECT b.TypeID AS BtypeNo,b.UserCode AS UserCode,b.FullName AS FullName,b.sonnum,t.*
FROM Btype b left join (Select a.bTypeID,SUM(a.Qty) AS Sum_Qty,
             Cast(SUM(a.Total) as  NUMERIC(24, 10) ) AS Sum_Total,Cast(SUM(a.Total*(100+c.Tax)/100) as  NUMERIC(24, 10) ) AS Sum_TaxTotal
             FROM  InOutstocktable a  inner join BillIndex c on(a.BillNumberId=c.BillNumberId)
             WHERE (c.BillType=34 OR c.BillType=6 OR c.BillType = 145 )   '+@where_sql+' GROUP BY a.bTypeID
) t  on t.BtypeId=b.typeId
  WHERE  b.Typeid='''+@btypeid+''' and b.deleted=0) a
 group by BtypeNo,UserCode,FullName,Sonnum ORDER BY Usercode'
--print @sql
exec(@sql)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GoodsGetInstat]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GoodsGetInstat]
GO











/****** Object:  Stored Procedure dbo.Web_GoodsGetInstat    Script Date: 2002-6-20 10:14:54 ******/
CREATE       PROCEDURE Web_GoodsGetInstat
(
	@StartDate	varchar(30),
	@EndDate	varchar(30),
	@PTypeId	varchar(25),
	@BTypeId	varchar(25),
	@ETypeId	varchar(25),
	@KTypeId	varchar(25),
	@chvOperatorID	varchar(30)	-- 11、操作员 ID（作权限范围检查用）
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - End		--------
-- ********	卢春 2003-03-05	- Start	********
-- 增加客户供货商统一判断
DECLARE @BTypeAll varchar(50)
SELECT @BTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'
-- ********	卢春 2003-03-05	- End	********
DECLARE @sql varchar(2000),@where_sql varchar(2000),@length varchar(2)
SELECT @where_sql=''
SELECT @sql=''
IF (ISDATE(RTRIM(@StartDate))=1)
  SELECT @where_sql=' AND a.BillDate>='+CHAR(39)+@StartDate+CHAR(39)
IF (ISDATE(RTRIM(@EndDate))=1)
  SELECT @where_sql=@where_sql+' AND a.BillDate<='+CHAR(39)+@EndDate+CHAR(39)
IF RTRIM(@PTypeId)=''
  BEGIN
    SELECT @PTypeId='00000'
    --SELECT @where_sql=@where_sql+' AND a.PtypeId Like '+CHAR(39)+@PTypeId+'%'+CHAR(39)
  END
IF RTRIM(@BTypeId)!=''
	BEGIN
		IF @BTypeAll = '1' AND @BTypeID = '00000'	-- 客户供货商统一，且全选所有供货商
			SELECT @where_sql=@where_sql+' AND ( a.BtypeId Like ''' + @chvMBTypeID + '%'' OR a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'' )'
		ELSE
			SELECT @where_sql=@where_sql+' AND a.BtypeId Like ''' + @BTypeID + '%'' AND a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'''
	END
IF RTRIM(@ETypeId)!=''
  SELECT @where_sql=@where_sql+' AND a.EtypeId Like ''' + @ETypeId + '%'' AND a.ETypeID LIKE ''' + @chvMETypeID + '%'''
IF RTRIM(@KTypeId)!=''
  SELECT @where_sql=@where_sql+' AND ( ( a.KtypeId Like ''' + @KTypeId + '%'' AND a.KTypeID LIKE ''' + @chvMKTypeID + '%'' ) OR a.KTypeID = ''10000'' )'
DECLARE @bIsLeaf bit
SELECT @bIsLeaf=CASE 
                                    WHEN EXISTS((SELECT * FROM PType WHERE TypeID=@PTypeId AND SonNum=0)) THEN 1
                                    ELSE 0
                                END

IF @bIsLeaf=0 
SELECT @sql='
	select 	PtypeNo,
		Usercode,
		Fullname,
		Unit1,
		sonnum,
		isnull(sum(Sum_Qty),0) as Sum_Qty,
		isnull(sum(Sum_Total),0) as Sum_Total,
		isnull(sum(Sum_TaxTotal),0) as Sum_TaxTotal
	from (
		SELECT 	b.TypeID AS PtypeNo,
			b.UserCode,
			b.FullName AS FullName,
			b.Unit1,
			b.sonnum,
			t.*
 		from 	ptype b 
			left join(
					select 	a.PtypeId,
						Sum_Qty= Case c.BillType when 145 Then -1*sum(a.Qty) Else sum(a.Qty) End,					
				             	Sum_Total=Case c.BillType When 145 Then -1*sum(a.Total) Else sum(a.Total) End,
						Sum_TaxTotal=Case c.BillType When 145 Then -1*SUM(a.Total*(100+c.Tax)/100)Else SUM(a.Total*(100+c.Tax)/100) End 
				        FROM 	InOutstocktable a,
						BillIndex c
				        WHERE 	(c.BillType=34 OR c.BillType=6 or c.BillType = 145) 
						AND a.BillNumberId=c.BillNumberId  '+@where_sql+' 
					GROUP BY a.pTypeId,c.BillType
				) t on left(t.PtypeId,LEN(b.TypeId))=b.typeId 
		where 	b.parid='''+@Ptypeid+''' and b.deleted=0) con 
			group by PtypeNo,Usercode,Fullname,Unit1,sonnum ORDER BY Usercode'
else
SELECT @sql='
		select 	PtypeNo,
			Usercode,
			Fullname,
			Unit1,
			sonnum,
			isnull(sum(Sum_Qty),0) as Sum_Qty,
			isnull(sum(Sum_Total),0) as Sum_Total,
			isnull(sum(Sum_TaxTotal),0) as Sum_TaxTotal
		from (
			SELECT 	b.TypeID AS PtypeNo,
				b.UserCode,
				b.FullName AS FullName,
				b.Unit1,
				b.sonnum,
				t.*
			 from 	ptype b 
				left join(
						select 	a.PtypeId,
							SUM(a.Qty) AS Sum_Qty,
					             	cast(SUM(a.Total) as  NUMERIC(24, 10) ) AS Sum_Total,
							cast(SUM(a.Total*(100+c.Tax)/100) as  NUMERIC(24, 10) ) AS Sum_TaxTotal
					        FROM 	InOutstocktable a,
							BillIndex c
				             	WHERE 	(c.BillType=34 OR c.BillType=6 or c.BillType = 145) 
							AND a.BillNumberId=c.BillNumberId  '+@where_sql+' 
						GROUP BY a.pTypeId
					) t on t.PtypeId=b.typeId 
			where b.Typeid='''+@Ptypeid+''' and b.deleted=0) con 
			group by PtypeNo,Usercode,Fullname,Unit1,sonnum ORDER BY Usercode'
--print @sql
exec(@sql)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GoodsGetInStatBtypeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GoodsGetInStatBtypeLine]
GO











/****** Object:  Stored Procedure dbo.Web_GoodsGetInStatBtypeLine    Script Date: 2002-6-20 10:14:54 ******/

CREATE        PROCEDURE Web_GoodsGetInStatBtypeLine(
	@StartDate varchar(30),
	@EndDate varchar(30),
	@PTypeId varchar(25),
	@BTypeId varchar(25),
	@ETypeId varchar(25),
	@KTypeId varchar(25),
	@PTypeCode varchar(200)='',
	@pTypeName varchar(200)='',
	@szOrderBy varchar(50)='',
	@chvOperatorID	varchar(30)	-- 11、操作员 ID（作权限范围检查用）
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------

IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe

--------	权限检查 - End		--------

-- 增加客户供货商统一判断
DECLARE @BTypeAll varchar(50)

SELECT @BTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'

-- ********	卢春 2003-03-05	- End	********

DECLARE @sql varchar(2000),@where_sql varchar(2000),@length varchar(2)
SELECT @where_sql=''
SELECT @sql=''
IF (ISDATE(RTRIM(@StartDate))=1)
  SELECT @where_sql=' AND a.BillDate>='+CHAR(39)+@StartDate+CHAR(39)
IF (ISDATE(RTRIM(@EndDate))=1)
  SELECT @where_sql=@where_sql+' AND a.BillDate<='+CHAR(39)+@EndDate+CHAR(39)
IF RTRIM(@BTypeId)=''
  BEGIN
    SELECT @BTypeId=''
  END

IF RTRIM(@BTypeId)!=''
	BEGIN
		IF @BTypeAll = '1' AND @BTypeID = '00000'	-- 客户供货商统一，且是选择所有
			SELECT @where_sql=@where_sql+' AND ( a.BtypeId Like ''' + @chvMBTypeID + '%'' OR a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'' )'
		ELSE
			SELECT @where_sql=@where_sql+' AND a.BtypeId Like '''+@BTypeId+'%'''
	END

IF RTRIM(@ETypeId)!=''
  SELECT @where_sql=@where_sql+' AND a.EtypeId Like '+char(39)+@chvMETypeID+'%'+char(39)
IF RTRIM(@KTypeId)!=''
  SELECT @where_sql=@where_sql+' AND ( ( a.KtypeId Like '''+@KTypeId+'%'' AND a.KTypeID LIKE ''' + @chvMKTypeID + '%'' ) OR a.KTypeID = ''10000'' )'
IF RTRIM(@PTypeId)!=''
  SELECT @where_sql=@where_sql+' AND b.TypeID Like '''+@BTypeId+'%'+CHAR(39)
IF RTRIM(@PTypeCode)!=''
  SELECT @where_sql=@where_sql+' AND b.UserCode Like ''%'+@PTypeCode+'%'+CHAR(39)
IF RTRIM(@pTypeName)!=''
  SELECT @where_sql=@where_sql+' AND b.FullName Like ''%'+@pTypeName+'%'+CHAR(39)
DECLARE @szOrderSql varchar(100)
SELECT @szOrderSql=''
IF RTRIM(@szOrderBy)!=''
  SELECT @szOrderSql=' ORDER BY '+char(39)+@szOrderBy+char(39)
SELECT @sql='
		SELECT 	b.TypeID AS BtypeNo,
				b.UserCode AS UserCode,
				b.FullName AS FullName,
				SUM(Case WHEN c.BillType=145 Then -1*a.Qty Else a.qty End) AS Sum_Qty,
				SUM(Case WHEN c.BillType=145 Then -1*a.Total Else a.Total End) AS Sum_Total,
				SUM(Case WHEN c.BillType=145 Then -1*(a.Total*(100+c.Tax)/100) Else (a.Total*(100+c.Tax)/100) End) AS Sum_TaxTotal,
				b.sonnum AS SonNum
             		FROM 		InOutstocktable a,
				Btype b,
				BillIndex c
            		 WHERE 	(c.BillType='+CHAR(39)+'34'+CHAR(39)+' OR c.BillType='+CHAR(39)+'6'+CHAR(39)+' OR c.BillType = 145) 
				AND a.BtypeId=b.typeId 
      				AND a.BillNumberId=c.BillNumberId 
      				AND b.sonnum=0'
             		+@where_sql+' GROUP BY b.TypeId,b.UserCode,b.FullName,b.sonnum '
      		+@szOrderSql
--print @sql
exec(@sql)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GoodsGetInstatDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GoodsGetInstatDetail]
GO






















/****** Object:  Stored Procedure dbo.Web_GoodsGetInstatDetail    Script Date: 2002-6-20 10:14:54 ******/

CREATE          PROCEDURE Web_GoodsGetInstatDetail(
	@StartDate	varchar(30),
	@EndDate	varchar(30),
	@PTypeId	varchar(25),
	@BTypeId	varchar(25),
	@ETypeId	varchar(25),
	@KTypeId	varchar(25),
	@OrderBy	varchar(25)	= '',
	@chvOperatorID	varchar(30)		-- 11、操作员 ID（作权限范围检查用）
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------

IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe

--------	权限检查 - End		--------

-- ********	卢春 2003-03-05	- Start	********

-- 增加客户供货商统一判断
DECLARE @BTypeAll varchar(50)

SELECT @BTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'

-- ********	卢春 2003-03-05	- End	********

DECLARE @sql varchar(8000),@where_sql varchar(2000)
SELECT @where_sql=''
IF (ISDATE(RTRIM(@StartDate))=1)
  SELECT @where_sql=' AND a.BillDate>='+CHAR(39)+@StartDate+CHAR(39)
IF (ISDATE(RTRIM(@EndDate))=1)
  SELECT @where_sql=@where_sql+' AND a.BillDate<='+CHAR(39)+@EndDate+CHAR(39)
IF RTRIM(@PTypeId)!=''
  SELECT @where_sql=@where_sql+' AND a.PtypeId Like '+CHAR(39)+@PTypeId+'%'+CHAR(39)
ELSE IF RTRIM(@PTypeId)='00000'
  SELECT @where_sql=@where_sql+' AND a.PtypeId ='''''

IF RTRIM(@BTypeId)!=''
	BEGIN
		IF @BTypeAll = '1' AND @BTypeID = '00000'	-- 客户供货商统一，且全选所有供货商
			SELECT @where_sql=@where_sql+' AND ( a.BtypeId Like ''' + @chvMBTypeID + '%'' OR a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'' )'
		ELSE IF @BTypeAll = '1' AND LEFT( @BTypeID, 5 ) = '00001'	-- 客户供货商统一，且是供货商统计，选中客户目录
			SELECT @where_sql=@where_sql+' AND a.BtypeId Like ''' + @BTypeID + '%'' AND a.BTypeID LIKE ''' + @chvMBTypeID + '%'''
		ELSE
			SELECT @where_sql=@where_sql+' AND a.BtypeId Like ''' + @BTypeID + '%'' AND a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'''
	END

IF RTRIM(@ETypeId)!=''
  SELECT @where_sql=@where_sql+' AND a.EtypeId Like ''' + @ETypeId + '%'' AND a.ETypeID LIKE ''' + @chvMETypeID + '%'''
IF RTRIM(@KTypeId)!=''
  SELECT @where_sql=@where_sql+' AND ( ( a.KtypeId Like ''' + @KTypeId + '%'' AND a.KTypeID LIKE ''' + @chvMKTypeID + '%'' ) OR a.KTypeID = ''10000'' )'

--  OrderBy  --
--  Add by wangfeng  --
DECLARE @SQLOrder	varchar(150)
SELECT @SQLOrder = ''
IF @OrderBy = 'ByDate_a'		--Order by date
    SELECT @SQLOrder = ' ORDER BY c.billdate, a.billtype, c.BillCode'
ELSE IF @OrderBy = 'ByBillNo_a' 	--Order by Bill No.
    SELECT @SQLOrder = ' ORDER BY c.BillCode'
ELSE IF @OrderBy = 'ByBillType_a'	--Order by Bill type
    SELECT @SQLOrder = ' ORDER BY a.billtype, c.billdate, c.BillCode'
ELSE IF @OrderBy = 'ByDate_d'		--Order by date DESC 
    SELECT @SQLOrder = ' ORDER BY c.billdate DESC, a.billtype, c.BillCode'
ELSE IF @OrderBy = 'ByBillNo_d' 	--Order by Bill No. DESC 
    SELECT @SQLOrder = ' ORDER BY c.BillCode DESC'
ELSE IF @OrderBy = 'ByBillType_d'	--Order by Bill type DESC 
    SELECT @SQLOrder = ' ORDER BY a.billtype DESC, c.billdate, c.BillCode'
ELSE
    SELECT @SQLOrder = ' ORDER BY c.billdate'


SELECT @sql='SELECT 	c.redword AS redword,
			a.BillNumberId AS BillNumberID,
			a.BillType AS BillType,
			c.BillDate AS BillDate,
			c.Billcode AS Billcode,
			a.PtypeId AS PtypeID,
			b.UserCode AS UserCode,
			b.FullName AS FullName,
			SUM(a.Qty) AS Qty,
            		SUM(a.Total) AS Total,
			SUM(a.Total) /SUM(a.Qty) AS Price,
			SUM(a.Total*(100+c.Tax)/100) AS TaxTotal,
			d.FullName AS BName,
			e.FullName AS EName, 
			f.FullName AS KName
             FROM 	InOutstocktable a,
			ptype b,
			BillIndex c,
			btype d,
			employee e,
			Stock f
             WHERE 	(c.BillType='+CHAR(39)+'34'+CHAR(39)+' OR c.BillType='+CHAR(39)+'6'+CHAR(39)+' Or c.BillType = 145) 
			AND a.BtypeId=d.typeId 
			AND a.EtypeId=e.typeId 
			AND a.PtypeId=b.typeId 
			AND a.BillNumberId=c.BillNumberId 
			AND c.KTypeID = f.TypeID '+@where_sql + '
	     GROUP BY	c.RedWord,
			a.BillNumberID,
			a.BillType,
			c.BillDate,
			c.BillCode,
			a.PTypeID,
			b.UserCode,
			b.FullName,
			d.FullName,
			e.FullName,
			f.FullName
	     UNION ALL
	     SELECT 	c.redword AS redword,
			a.BillNumberId AS BillNumberID,
			a.BillType AS BillType,
			c.BillDate AS BillDate,
			c.Billcode AS Billcode,
			a.PtypeId AS PtypeID,
			b.UserCode AS UserCode,
			b.FullName AS FullName,
			-1*SUM(a.Qty) AS Qty,
            		-1*SUM(a.Total) AS Total,
			SUM(a.Total) /SUM(a.Qty) AS Price,
			-1*SUM(a.Total*(100+c.Tax)/100) AS TaxTotal,
			d.FullName AS BName,
			e.FullName AS EName, 
			c.KtypeID AS KName
             FROM 	InOutstocktable a,
			ptype b,
			BillIndex c,
			btype d,
			employee e			
             WHERE 	c.BillType = 145 
			AND a.BtypeId=d.typeId 
			AND a.EtypeId=e.typeId 
			AND a.PtypeId=b.typeId 
			AND a.BillNumberId=c.BillNumberId 
			AND c.KTypeID = ''10000'' '+@where_sql + '
	     GROUP BY	c.RedWord,
			a.BillNumberID,
			a.BillType,
			c.BillDate,
			c.BillCode,
			a.PTypeID,
			b.UserCode,
			b.FullName,
			d.FullName,
			e.FullName,
			c.KtypeID
'
+ @SQLOrder
--print @sql
exec(@sql)





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GoodsGetInStatLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GoodsGetInStatLine]
GO












/****** Object:  Stored Procedure dbo.Web_GoodsGetInStatLine    Script Date: 2002-6-20 10:14:54 ******/

CREATE        PROCEDURE Web_GoodsGetInStatLine
(
	@StartDate	varchar(30),
	@EndDate	varchar(30),
	@PTypeId	varchar(25),
	@BTypeId	varchar(25),
	@ETypeId	varchar(25),
	@KTypeId	varchar(25),
	@PTypeCode	varchar(200)	= '',
	@pTypeName	varchar(200)	= '',
	@szOrderBy	varchar(50)	= '',
	@chvOperatorID	varchar(30)		-- 11、操作员 ID（作权限范围检查用）
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------

IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
IF @intRe <> 0 RETURN @intRe

--------	权限检查 - End		--------

-- ********	卢春 2003-03-05	- Start	********

-- 增加客户供货商统一判断
DECLARE @BTypeAll varchar(50)

SELECT @BTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'

-- ********	卢春 2003-03-05	- End	********

DECLARE @sql varchar(2000),@where_sql varchar(2000),@length varchar(2)
SELECT @where_sql=''
SELECT @sql=''
IF (ISDATE(RTRIM(@StartDate))=1)
  SELECT @where_sql=' AND a.BillDate>='+CHAR(39)+@StartDate+CHAR(39)
IF (ISDATE(RTRIM(@EndDate))=1)
  SELECT @where_sql=@where_sql+' AND a.BillDate<='+CHAR(39)+@EndDate+CHAR(39)
IF RTRIM(@PTypeId)=''
  BEGIN
    SELECT @PTypeId=''
  END

IF RTRIM(@BTypeId)!=''
	BEGIN
		IF @BTypeAll = '1' AND @BTypeID = '00000'	-- 客户供货商统一，且全选所有供货商
			SELECT @where_sql=@where_sql+' AND ( a.BtypeId Like ''' + @chvMBTypeID + '%'' OR a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'' )'
		ELSE
			SELECT @where_sql=@where_sql+' AND a.BtypeId Like ''' + @BTypeID + '%'' AND a.BTypeID LIKE ''' + @chvMBTypeID2 + '%'''
	END

IF RTRIM(@ETypeId)!=''
  --作者：谢吉康
  --日期：2003-06-04
  --描述：根据权限判断商品的范围
  --SELECT @where_sql=@where_sql+' AND a.EtypeId Like ''%'+@ETypeId+'%'' AND a.ETypeID LIKE ''%' + @chvMETypeID + '%'''
  SELECT @where_sql=@where_sql+' AND  a.ETypeID LIKE '+char(39)+ @chvMETypeID + '%'+char(39)
IF RTRIM(@KTypeId)!=''
  --SELECT @where_sql=@where_sql+' AND ( ( a.KtypeId Like ''%'+@KTypeId+'%'' AND a.KTypeID LIKE ''%' + @chvMKTypeID + '%'' ) OR a.KTypeID = ''10000'' )'
  SELECT @where_sql=@where_sql+' AND  a.KTypeID LIKE '+char(39) +@chvMKTypeID + '%'+char(39)+' OR a.KTypeID = ''10000'' )'
IF RTRIM(@PTypeId)!=''
  SELECT @where_sql=@where_sql+' AND b.TypeID Like '''+@PTypeId+'%'+CHAR(39)
IF RTRIM(@PTypeCode)!=''
  SELECT @where_sql=@where_sql+' AND b.UserCode Like '''+@PTypeCode+'%'+CHAR(39)
IF RTRIM(@pTypeName)!=''
  SELECT @where_sql=@where_sql+' AND b.FullName Like '''+@pTypeName+'%'+CHAR(39)
DECLARE @szOrderSql varchar(100)
SELECT @szOrderSql=''
IF RTRIM(@szOrderBy)!=''
  SELECT @szOrderSql=' ORDER BY '+char(39)+@szOrderBy+char(39)
SELECT @sql='
		SELECT 					
				b.TypeID AS PtypeNo,
				b.UserCode AS UserCode,
				b.FullName AS FullName,
				b.Unit1 AS Unit1,
				SUM(Case c.BillType when 145 Then -1*a.Qty Else a.Qty end) AS Sum_Qty,
				Sum(Case c.BillType When 145 Then -1*a.Total Else a.Total End) as Sum_Total,
				Sum(Case c.BillType When 145 Then -1*a.Total*(100+c.Tax)/100 Else a.Total*(100+c.Tax)/100 End) as Sum_TaxTotal, 
				b.sonnum				
	        FROM 		InOutstocktable a,
				ptype b,
				BillIndex c
             	WHERE 		(c.BillType='+CHAR(39)+'34'+CHAR(39)+' OR c.BillType='+CHAR(39)+'6'+CHAR(39)+' OR c.BillType = 145) 
				AND a.PtypeId=b.TypeId
				AND a.BillNumberId=c.BillNumberId 
				AND b.sonnum=0'
             +@where_sql+' GROUP BY b.TypeId,b.UserCode,b.FullName,b.sonnum,b.Unit1
'
	     +@szOrderSql
--print @sql
exec(@sql)













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_GoodsSaletypeAnalysis_List]') and OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].Web_GoodsSaletypeAnalysis_List
GO



/*
商品销售类型分析
李灏龙 2011-12-16
*/


/*
修改：黄清 
时间：2012-04-05、
描述：增加分支机构和部门权限控制，时间条件，修改排序

		
修改：舒珊
日期：2015-05-27
描述： 添加商品类别筛选
*/
/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Web_GoodsSaletypeAnalysis_List
(
	@opratorid	VARCHAR(100),
	@stypeid	VARCHAR(50)='00001',
	@btypeid	VARCHAR(MAX),
	@ktypeid	VARCHAR(MAX),
	@etypeid	VARCHAR(MAX),
	@startdate	VARCHAR(50),
	@enddate	VARCHAR(50),
	@typeid		VARCHAR(8000),
	@flag		VARCHAR(1),
	@dtypeid	VARCHAR(MAX),
	@isshowzero	VARCHAR(10)='1'	,--线性表是否显示为0的数据
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------
----商品权限----
CREATE TABLE #pty
(
	ptypeid VARCHAR(8000)
)
INSERT INTO #pty 
SELECT distinct a.TypeId AS ptypeid
FROM F_GetManPType(@opratorid)  a
inner join F_ManPTypeInCategoryID ( @opratorid,@typeid,@ptypecategoryid) pt on pt.typeid LIKE a.typeid + '%'
WHERE a.iscombinationproduct = 0


----分支机构权限----	 
CREATE TABLE #stype
(	
	stypeid VARCHAR(8000)
)
INSERT INTO #stype 
SELECT TypeId AS stypeid
FROM F_GetAllManagerBASeTypeId(@stypeid,11,@opratorid) 

----部门权限----	 
CREATE TABLE #dtype
(	
	dtypeid VARCHAR(8000)
)
INSERT INTO #dtype 
SELECT TypeId AS dtypeid
FROM F_GetAllManagerBASeTypeId(@dtypeid,9,@opratorid) 

----往来权限----	 
CREATE TABLE #btype
(	
	btypeid VARCHAR(8000)
)
INSERT INTO #btype 
SELECT TypeId AS btypeid
FROM F_GetAllManagerBASeTypeId(@btypeid,2,@opratorid) 
	 
----职员权限----	 
CREATE TABLE #etype
(
	etypeid VARCHAR(8000)	
)
INSERT INTO #etype
SELECT TypeId AS etypeid
FROM F_GetAllManagerBASeTypeId(@etypeid,3,@opratorid)
	 
----仓库权限----	 
CREATE TABLE #ktype
(	
	ktypeid VARCHAR(8000)
)
INSERT INTO #ktype
SELECT TypeId AS ktypeid
FROM F_GetAllManagerBASeTypeId(@ktypeid,4,@opratorid)

----在仓库权限中加入不受管制的代销仓库
IF @ktypeid = ''
	INSERT INTO #ktype(ktypeid) VALUES('10000')
--------------------------------------------------------------权限检查-------------------------------------------------------

----@sonnum 用于记录子节点数
----@SQL 用于存储查询语句
----@MSQL 用于存储查询条件
DECLARE		@sonnum INT,
			@SQL VARCHAR(MAX)

----@flag为0时执行树形查找
IF @flag = '0'
BEGIN
----第一次查询时@typeid参数为空，所以要赋值为00000以便后面查询
	IF @typeid = ''
		SET @typeid = '00000'

	SELECT @sonnum = sonnum FROM PType WHERE typeId = @typeid

	SET @SQL = 'SELECT pt.Parid,pt.sonnum,pt.typeid, 
						sum(ISNULL(x.lsl,0)) AS lsl, 
						sum(ISNULL(x.lsj,0)) AS lsj,  
						sum(ISNULL(x.wtdxl,0)) AS wtdxl,
						sum(ISNULL(x.wtdxj,0)) AS wtdxj,  
						sum(ISNULL(x.pfl,0)) AS pfl, 
						sum(ISNULL(x.pfj,0)) AS pfj, 
						sum(ISNULL(x.xsl,0)) AS xsl,  
						sum(ISNULL(x.jshj,0)) as jshj,  
						sum(ISNULL(x.zsl,0)) AS zsl 
				FROM PType pt
				LEFT JOIN 
				(
					SELECT	c.ptypeid,
							SUM(ISNULL(lsl,0))- SUM(ISNULL(lsthl,0)) AS lsl,
							SUM(ISNULL(lsj,0))- SUM(ISNULL(lsth,0)) AS lsj,
							SUM(ISNULL(wtdxl,0)) AS wtdxl,
							SUM(ISNULL(wtdx,0)) AS wtdxj,
							SUM(ISNULL(xscdl,0)) - SUM(ISNULL(xsthl,0))- SUM(ISNULL(xshhl,0)) AS pfl,
							SUM(ISNULL(xscd,0)) - SUM(ISNULL(xsth,0)) - SUM(ISNULL(xshh,0)) AS pfj,
							SUM(ISNULL(xscdl,0)) - SUM(ISNULL(xsthl,0)) - SUM(ISNULL(xshhl,0)) + SUM(ISNULL(lsl,0))- SUM(ISNULL(lsthl,0)) + SUM(ISNULL(wtdxl,0)) AS xsl,
							SUM(ISNULL(xscd,0)) - SUM(ISNULL(xsth,0))- SUM(ISNULL(lsth,0))  - SUM(ISNULL(xshh,0)) + SUM(ISNULL(lsj,0)) + SUM(ISNULL(wtdx,0)) AS jshj,
							SUM(ISNULL(zsl,0)) AS zsl 
					FROM
					(		
						SELECT  a.ptypeid,a.BillNumberId,
												
								lsl = 
								CASE
								WHEN a.BillType = 305 THEN -a.qty
								END,
								
								lsj = 
								CASE
								WHEN a.BillType = 305 THEN -a.total
								END,
													
								xscdl = 
								CASE
								WHEN a.BillType in( 11,12) THEN -a.qty
								END,
								
								xscd = 
								CASE
								WHEN a.BillType in( 11,12) THEN -a.total
								END,
						
								xsthl = 
								CASE
								WHEN a.BillType in(45,46) THEN a.qty
								END,
								
								xsth = 
								CASE
								WHEN a.BillType in(45,46) THEN a.total
								END,
								
								lsthl = 
								CASE
								WHEN a.BillType = 215 THEN a.qty
								END,
								
								lsth = 
								CASE
								WHEN a.BillType = 215 THEN a.total
								END,
								
								
								xshhl = 
								CASE
								WHEN a.BillType = 160 THEN a.qty
								END,
						
								xshh = 
								CASE
								WHEN a.BillType = 160 THEN a.total
								END,
									
								zsl = 
								CASE
								WHEN a.BillType = 139 THEN -a.qty
								END,
								
								wtdxl = 
								CASE
								WHEN (	
										a.BillType = 141 
									 )	
								THEN -a.qty
								END,
								
								wtdx = 
								CASE
								WHEN (	
										a.BillType = 141 
									 )
							    THEN -a.total
								END
						FROM 
							(
								SELECT i.ptypeid,SUM(ISNULL(Total,0)) AS total,SUM(ISNULL(qty,0)) AS qty ,BillType,BillNumberId 
								FROM InOutstocktable i
								INNER JOIN #stype s ON s.stypeid = i.stypeid 
								INNER JOIN #dtype d ON d.dtypeid = i.dtypeid 
								INNER JOIN #btype b ON b.btypeid = i.btypeid 
								INNER JOIN #etype e ON e.etypeid = i.etypeid 
								INNER JOIN #ktype k ON k.ktypeid = i.ktypeid 
								INNER JOIN #pty p on p.ptypeid = i.ptypeid
								WHERE BillType IN (141,305,139,45,160,11,215,12,46) 
									AND BillDate<='''+@enddate+'''
									AND BillDate>='''+@startdate+'''
								GROUP BY i.ptypeid,BillType,BillNumberId
							) a
					) c group by c.PtypeId
				) x	ON LEFT(x.ptypeid,LEN(pt.typeid)) = pt.typeid
				INNER JOIN #pty p ON p.ptypeid = pt.typeid
				WHERE'
----根据子节点数判断是该节点是否是叶子节点
	IF @sonnum=0
		SET @SQL = @SQL+'  pt.Typeid = '''+@typeid
	ELSE 
		SET @SQL = @SQL+'  pt.Parid = '''+@typeid
				
	SET @SQL =  @SQL +'''	GROUP BY pt.Parid,pt.sonnum,pt.Typeid,PT.UserCode ,pt.sortid
							ORDER BY PT.sortid'

	--print(@sql)
	EXEC(@SQL)
END

----@flag为1时执行线性查找
ELSE IF @flag = '1'
BEGIN
	SET @SQL = 'SELECT	pt.typeid,ISNULL(x.lsl,0) AS lsl,ISNULL(x.lsj,0) AS lsj, ISNULL(x.wtdxl,0) AS wtdxl,
						ISNULL(x.wtdxj,0) AS wtdxj, ISNULL(x.pfl,0) AS pfl,ISNULL(x.pfj,0) AS pfj, ISNULL(x.xsl,0) AS xsl,
						ISNULL(x.jshj,0) AS jshj, ISNULL(x.zsl,0) AS zsl 
				FROM PType pt
				LEFT JOIN 
				(
					SELECT	c.ptypeid,
							SUM(ISNULL(lsl,0))- SUM(ISNULL(lsthl,0)) AS lsl,
							SUM(ISNULL(lsj,0))- SUM(ISNULL(lsth,0)) AS lsj,
							SUM(ISNULL(wtdxl,0)) AS wtdxl,
							SUM(ISNULL(wtdx,0)) AS wtdxj,
							SUM(ISNULL(xscdl,0)) - SUM(ISNULL(xsthl,0))  - SUM(ISNULL(xshhl,0)) AS pfl,
							SUM(ISNULL(xscd,0)) - SUM(ISNULL(xsth,0)) - SUM(ISNULL(xshh,0)) AS pfj,
							SUM(ISNULL(xscdl,0)) - SUM(ISNULL(xsthl,0)) - SUM(ISNULL(lsthl,0))- SUM(ISNULL(xshhl,0)) + SUM(ISNULL(lsl,0)) + SUM(ISNULL(wtdxl,0)) AS xsl,
							SUM(ISNULL(xscd,0)) - SUM(ISNULL(xsth,0))- SUM(ISNULL(lsth,0)) - SUM(ISNULL(xshh,0)) + SUM(ISNULL(lsj,0)) + SUM(ISNULL(wtdx,0)) AS jshj,
							SUM(ISNULL(zsl,0)) AS zsl 
					FROM
					(		
						SELECT  a.ptypeid,a.BillNumberId,
												
								lsl = 
								CASE
								WHEN a.BillType = 305 THEN -a.qty
								END,
								
								lsj = 
								CASE
								WHEN a.BillType = 305 THEN -a.total
								END,
													
								xscdl = 
								CASE
								WHEN a.BillType in( 11,12)THEN -a.qty
								END,
								
								xscd = 
								CASE
								WHEN a.BillType in( 11,12) THEN -a.total
								END,
						
								xsthl = 
								CASE
								WHEN a.BillType in(45,46) THEN a.qty
								END,
								
								xsth = 
								CASE
								WHEN a.BillType in(45,46) THEN a.total
								END,
								
								
								lsthl = 
								CASE
								WHEN a.BillType = 215 THEN a.qty
								END,
								
								lsth = 
								CASE
								WHEN a.BillType = 215 THEN a.total
								END,
								
								xshhl = 
								CASE
								WHEN a.BillType = 160 THEN a.qty
								END,
						
								xshh = 
								CASE
								WHEN a.BillType = 160 THEN a.total
								END,
									
								zsl = 
								CASE
								WHEN a.BillType = 139 THEN -a.qty
								END,
								
								wtdxl = 
								CASE
								WHEN (	
										a.BillType = 141 
									 )
							    THEN -a.qty
								END,
								
								wtdx = 
								CASE
								WHEN (	
										a.BillType = 141 
									 )
							    THEN -a.total
								END
						FROM 
							(
								SELECT i.ptypeid,SUM(ISNULL(Total,0)) AS total,SUM(ISNULL(qty,0)) AS qty ,BillType,BillNumberId 
								FROM InOutstocktable i
								INNER JOIN #stype s ON s.stypeid = i.stypeid 
								INNER JOIN #dtype d ON d.dtypeid = i.dtypeid 
								INNER JOIN #btype b ON b.btypeid = i.btypeid
								INNER JOIN #etype e ON e.etypeid = i.etypeid
								INNER JOIN #ktype k ON k.ktypeid = i.ktypeid 
								WHERE BillType IN (141,305,139,45,160,11,215,12,46) 
									AND BillDate<='''+@enddate+'''
									AND BillDate>='''+@startdate+'''
								GROUP BY i.ptypeid,BillType,BillNumberId
							) a
					) c group by c.PtypeId 
				) x	ON x.ptypeid = pt.typeid
				INNER JOIN #pty p ON p.ptypeid = pt.typeid			
				WHERE LEFT(pt.typeid,LEN('''+@typeid+''')) = '''+@typeid +''' AND pt.sonnum = 0  
				'
				IF @isshowzero='0'
					SET @SQL=@SQL+' AND (X.lsj<>0 OR lsl<>0  OR X.jshj<>0 OR xsl<>0  OR pfl<>0  OR X.pfj<>0 OR wtdxl<>0  OR X.wtdxj<>0 OR X.zsl<>0) '
				SET @SQL=@SQL+'
				GROUP BY pt.Parid,pt.sonnum,pt.Typeid,x.lsl,x.lsj, x.wtdxl,x.wtdxj, x.pfl ,x.pfj , x.xsl ,x.jshj , x.zsl,PT.UserCode,pt.sortid
				ORDER BY PT.sortid'
	EXEC(@SQL)
END

DROP TABLE #pty,#btype,#etype,#ktype,#dtype,#stype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[WEB_GoodsSellStat]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].WEB_GoodsSellStat
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*------------------------------------------
 作者：蒋奎
 日期：2014-6-17
 描述：跨帐套查询-商品,客户销售统计-查询
 思路: 从GP_GoodsSellStat存储过程里面sum合计出数据
-------------------------------------------*/
CREATE PROCEDURE WEB_GoodsSellStat
(
	@ptypeid	VARCHAR(MAX)='',
	@startdate  VARCHAR(30),
	@enddate	VARCHAR(30),
	@tbName		VARCHAR(100), --临时表名
	@defaultaccount  VARCHAR(1000),
	@flag		VARCHAR(30)='False',--显示为0
	@ruletype		INT,			--规则类型: 0=系统规则,1=自定义规则的编码, 2=自定义规则的名称 , 3=自定义规则的编码和名称
	@showway			VARCHAR(30)	--统计方式 full全部，season 按季度 year 按年度
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON;
	
	DECLARE @chvLen VARCHAR(10)
	DECLARE @SQL VARCHAR(max)=''
	DECLARE @configSQL VARCHAR(max)
	DECLARE @config int=0
	--SELECT @configSQL= 'SELECT @config=Value FROM '+@defaultaccount+'.dbo.Userconfig WHERE ConfigName=''sharefee'''
	--EXEC (@configSQL)
	SET @config=0
	
	--筛选数据的@SqlWhere(上层下层Selector筛选)
	IF @ptypeid='' 
		SET @ptypeid = '00000'
	
	DECLARE @sonnum INT	,@SqlWhere VARCHAR(200)
	DECLARE @tmpsql NVARCHAR(1000)
	SET @tmpsql='select @sonnum=sonnum from '+@defaultaccount+'.dbo.Ptype where typeid='''+@ptypeid+''''
	exec sp_executesql @tmpsql,N'@sonnum int output',@sonnum output
 
	IF @sonnum>0
		SET @SqlWhere=' WHERE p.parid= ''' +@ptypeid+'''' 
	ELSE 
		SET @SqlWhere=' WHERE p.typeid=''' +@ptypeid+''''
	
	--将默认帐套Ptype的数据存到#Ptype		
	CREATE TABLE #Ptype 
	(
		TypeID varchar(50),
		usercode VARCHAR(200),
		fullname VARCHAR(200),
		parid  VARCHAR(50),
		sonnum	INT,
		unit	VARCHAR(50),
		pid INT
	)	
	DECLARE @tmp  VARCHAR(8000)
		SELECT @tmp='	INSERT INTO #Ptype(typeid,usercode,fullname,parid,sonnum,unit,pid)
							SELECT p.typeid,p.usercode,p.fullname,p.parid,p.sonnum,a.fullname ,p.pid 
							FROM '+@defaultaccount+'.dbo.Ptype p
							INNER JOIN  '+@defaultaccount+'.dbo.PType_Units a ON p.baseUnitId=a.UnitsId	'
		EXEC(@tmp)
		-- PRINT @tmp
	
	--构造截取变量@chvLen(目的是group by出指定层数据)
	IF @ptypeid='00000'  OR @ptypeid = ''
			SET @chvLen='5'
	ELSE
			SET @chvLen=CAST(LEN(@ptypeid)+5 AS varchar(20))
			
	SELECT @SQL = 'SELECT SUBSTRING(a.TypeID, 1,'+ @chvLen + ') AS typeID'	
	
	
	--按季度展示 
	IF @showway = 'season'
	BEGIN
		CREATE TABLE #columnName
		(	
			id  INT IDENTITY(1,1),	    
			columnName	VARCHAR(50),
			SeasonFullName    VARCHAR(10)
		)
		
		INSERT INTO #columnName
		SELECT * FROM
		(
			SELECT YearFullName+'年-'+SeasonFullName+'季度' AS columnName,YearFullName+SeasonFullName AS SeasonFullName--CONVERT(VARCHAR(10),StartDate,120) AS StartDate,CONVERT(VARCHAR(10),EndDate,120) AS EndDate
			FROM dbo.F_GetTwoDate(@startdate,@enddate,2)
			UNION ALL
			SELECT YearFullName+'年-合计数' AS columnName, YearFullName AS SeasonFullName--CONVERT(VARCHAR(10),StartDate,120) AS StartDate,CONVERT(VARCHAR(10),EndDate,120) AS EndDate  
			FROM dbo.F_GetTwoDate(@startdate,@enddate,3)
		)a ORDER BY columnName
		
		
		--根据时间临时表#columnName动态拼接季度列
		
		SELECT @SQL=@SQL+',SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN qty END) ['+S.columnName+'销售数量]
						  /*,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN total END)/SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN qty END) ['+S.columnName+'Price]*/
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN SaleTotal END) ['+S.columnName+'折前销售金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN total END) ['+S.columnName+'销售金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN TaxTotal END)-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN total END)['+S.columnName+'税额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN TaxTotal END) ['+S.columnName+'价税合计]
						  /*,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN CostTotal END)/SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN qty END) ['+S.columnName+'CostPrice]*/
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN CostTotal END) ['+S.columnName+'成本金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN ProtectTotal END) ['+S.columnName+'价保金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN Advantagetotal END) ['+S.columnName+'返利金额]
						  ,SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN Total END)-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN CostTotal END)'+
								CASE WHEN @config=1 THEN '-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN sharefee END)' ELSE '' END+
								'-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN Advantagetotal END)- SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN ProtectTotal END) 
								as ['+S.columnName+'毛利]
						  /*,CASE WHEN SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN Total END)=0 THEN 0 ELSE
								(SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN Total END)-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN CostTotal END)' +
								CASE WHEN @config=1 THEN '-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN sharefee END)'ELSE '' END+
								'-SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN Advantagetotal END)- SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN ProtectTotal END) )
								/SUM(CASE WHEN timeType  ='+SeasonFullName +' OR SUBSTRING(timeType,1,4)='+SeasonFullName +' THEN total END )*100 END
								as ['+S.columnName+'SUM_MaoLiLu] 
						  ,0.00 as ['+S.columnName+'qty_qz]  
						  ,0.00 as ['+S.columnName+'total_qz]   
						  ,0.00 as ['+S.columnName+'maoli_qz]   
						  ,0.00 as ['+S.columnName+'pjlirun]    */

						  '
		FROM (SELECT  columnName,SeasonFullName --AS Season,CONVERT(VARCHAR(10),StartDate,120) AS StartDate,CONVERT(VARCHAR(10),EndDate,120) AS EndDate
			  FROM #columnName) s
			  
		DROP TABLE #columnName
		
	END
	
	--按年展示
	IF @showway = 'year'
	BEGIN
		SELECT @SQL=@SQL+',SUM(CASE WHEN timeType = '+YearFullName+' THEN qty END) ['+S.Season+'销售数量]
						  /*,SUM(CASE WHEN timeType = '+YearFullName+' THEN total END)/SUM(CASE WHEN timeType = '+YearFullName+' THEN qty END) ['+S.Season+'Price]*/
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN SaleTotal END) ['+S.Season+'折前销售金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN total END) ['+S.Season+'销售金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN TaxTotal END)-SUM(CASE WHEN timeType = '+YearFullName+' THEN total END)['+S.Season+'税额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN TaxTotal END) ['+S.Season+'价税合计]
						  /*,SUM(CASE WHEN timeType = '+YearFullName+' THEN CostTotal END)/SUM(CASE WHEN timeType = '+YearFullName+' THEN qty END) ['+S.Season+'CostPrice]*/
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN CostTotal END) ['+S.Season+'成本金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN ProtectTotal END) ['+S.Season+'价保金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN Advantagetotal END) ['+S.Season+'返利金额]
						  ,SUM(CASE WHEN timeType = '+YearFullName+' THEN Total END)-SUM(CASE WHEN timeType = '+YearFullName+' THEN CostTotal END)'+
								CASE WHEN @config=1 THEN '-SUM(CASE WHEN timeType = '+YearFullName+' THEN sharefee END)' ELSE '' END+
								'-SUM(CASE WHEN timeType = '+YearFullName+' THEN Advantagetotal END)- SUM(CASE WHEN timeType = '+YearFullName+' THEN ProtectTotal END) 
								as ['+S.Season+'毛利]
						  /*,CASE WHEN SUM(CASE WHEN timeType = '+YearFullName+' THEN Total END)=0 THEN 0 ELSE
								(SUM(CASE WHEN timeType = '+YearFullName+' THEN Total END)-SUM(CASE WHEN timeType = '+YearFullName+' THEN CostTotal END)' +
								CASE WHEN @config=1 THEN '-SUM(CASE WHEN timeType = '+YearFullName+' THEN sharefee END)'ELSE '' END+
								'-SUM(CASE WHEN timeType = '+YearFullName+' THEN Advantagetotal END)- SUM(CASE WHEN timeType = '+YearFullName+' THEN ProtectTotal END) )
								/SUM(CASE WHEN timeType = '+YearFullName+' THEN total END )*100 END 
								as ['+S.Season+'SUM_MaoLiLu] 
						  --,0.00 as ['+S.Season+'qty_qz]  
						  --,0.00 as ['+S.Season+'total_qz]   
						  --,0.00 as ['+S.Season+'maoli_qz]   
						  --,0.00 as ['+S.Season+'pjlirun] */    
						  '
		FROM (SELECT  YearFullName+'年' AS Season,YearFullName
				FROM dbo.F_GetTwoDate(@startdate,@enddate,3)) s
		
		
		
	END
	
	--展示所有
	IF @showway = 'full'
	BEGIN
		--这个SQL体现了清晰的算法
		
		SELECT @SQL=@SQL+',SUM(qty ) [SUM_Qty]
						  /*,SUM(total)/SUM(qty) [Price]*/
						  ,SUM(SaleTotal) [SUM_DiscountTotal]
						  ,SUM(total) [SUM_Total]
						  ,SUM(TaxTotal ) [SUM_TaxTotal]
						  ,SUM(TaxTotal)-SUM(total)[TaxGe]
						  /*,SUM(CostTotal)/SUM(qty) [CostPrice]*/
						  ,SUM(CostTotal) [SUM_CostTotal]
						  ,SUM(ProtectTotal) [ProtectTotal]
						  ,SUM(Advantagetotal) [Advantagetotal]
						  ,SUM(Total)-SUM(CostTotal)'+
								CASE WHEN @config=1 THEN '-SUM(sharefee)' ELSE '' END+
								'-SUM(Advantagetotal)- SUM(ProtectTotal) 
								as [SUM_MaoLi]
						 /*,CASE WHEN SUM(Total)=0 THEN 0 ELSE
								(SUM(Total)-SUM(CostTotal)' +
								CASE WHEN @config=1 THEN '-SUM(sharefee)'ELSE '' END+
								'-SUM(Advantagetotal)- SUM(ProtectTotal))
								/SUM(total)*100 END
								as [SUM_MaoLiLu]
						  ,0.00 as [qty_qz]  
						  ,0.00 as [total_qz]   
						  ,0.00 as [maoli_qz]   
						  ,0.00 as [pjlirun]  */  
						  '
	END
	
	--合并规则
	DECLARE @joinwhere VARCHAR(100)=''
	
	IF @ruletype=0
	BEGIN
		SET @joinwhere=' a.xid=p.pid '
	END
	IF @ruletype=1
	BEGIN
		 SET @joinwhere=' a.usercode=p.usercode '
	END
	IF @ruletype=2
	BEGIN
		SET @joinwhere=' a.fullname=p.fullname '
	END
	IF @ruletype=3
	BEGIN
		SET @joinwhere=' a.usercode=p.usercode  and a.fullname=p.fullname'
	END
	
	--将@tbName里面的销售明细数据和默认帐套的商品数据进行合并(根据合并规则)
	SELECT @SQL = @SQL+ ' FROM  ['+@tbName+']  A
							  INNER JOIN #ptype /*默认帐套ptype*/ p ON '+@joinwhere+'
							  GROUP BY SUBSTRING(a.TypeID, 1,'+ @chvLen + ')
	
							  '
	--最后将sum好的数据@SQL和#ptype INNER JOIN	(不显示为零)  LEFT JOIN(显示为零) 出数据
	IF @flag='False'
	BEGIN
		--不显示为零	
		SELECT  @SQL = '  SELECT P.typeid ,p.usercode,p.fullname,p.parid,p.sonnum,bi.* 
						  FROM #ptype p
						  INNER JOIN ('+@SQL+')bi ON bi.typeid=p.typeid
						  '+@SqlWhere+'
						  order by p.usercode '
	END
	ELSE
	BEGIN
		--显示为零
		SELECT @SQL = '  SELECT P.typeid ,p.usercode,p.fullname,p.parid,p.sonnum,bi.* 
							FROM  #Ptype p
							LEFT JOIN ('+@SQL+')bi ON bi.typeid=p.typeid
							'+@SqlWhere+'
							order by p.usercode '
		
	END
				    
	--PRINT (@sql)
	EXEC (@SQL)
	
	DROP TABLE #ptype
	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_GuestReceiveQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_GuestReceiveQuery]
GO














/****** Object:  Stored Procedure dbo.Web_GuestReceiveQuery    Script Date: 2002-6-20 10:14:54 ******/

CREATE  PROCEDURE Web_GuestReceiveQuery
(
@BTypeID Varchar(25),
@StartDate VarChar(30),
@EndDate VarChar(30)
)
--@encode$--
AS
SET NOCOUNT ON 
declare @sql Varchar(2000),@Where_BTypeID Varchar(2000),@Where_Date Varchar(200)
--@sql  用于存放整个查询语句
--@Where_BTypeID  用于存放Where条件语句的顾客ID部分
--@Where_Date 用于存放Where条件语句中的日期条件部分
if(rtrim(@StartDate)<>'' and rtrim(@EndDate)<>'')
  select @Where_Date=' and (a.BillDate>='+char(39)+@StartDate+char(39)+' and a.BillDate<='+char(39)+@EndDate+char(39)+')'
if(rtrim(@BTypeId)<>'')
  select @Where_BTypeID=' and (a.btypeid= '+char(39)+@BTypeID+char(39)+')'
select @sql='SELECT c.usercode,c.Fullname,SUM(b.total) AS Sum_Total
             FROM BillIndex a,GatheringBill b,btype c
             WHERE a.BillNumberId=b.BillNumberId and a.btypeId=c.typeId'+@Where_BTypeID+@Where_Date+
             ' GROUP BY c.usercode,c.Fullname'
--print @sql
exec(@sql)
--本存储过程查询某个单位的收款情况，由王浩于2001.5.30改写















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Hr_PersonInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Hr_PersonInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2011-3-25
	描述：人员信息显示
-------------------------------------------*/
CREATE PROCEDURE Web_Hr_PersonInfo
--@encode$--
AS
SET NOCOUNT ON

SELECT	a.ID AS ID,    				--唯一标示符
		a.Name AS name,				--姓名
		a.LoginName,				--登录名
		a.password,					--密码
		a.Phone,					--电话
		a.Remark,					--备注
		b.Limit,					--权限字符串
		c.name	AS position,		--职位名称
		c.ID	AS pos_id,			--职位ID
		d.name	AS depname,			--部门名称
		d.id	AS dep_id,			--部门ID
		CASE Sex WHEN 0 THEN '男' ELSE '女' END AS Sex
FROM HR_Person a
LEFT JOIN HR_PersonLimit  b ON	a.ID			= b.Person_ID
LEFT JOIN HR_Postion      c ON	A.Postion_ID	= c.ID
LEFT JOIN HR_Department	  d ON  c.Department_ID = d.ID
WHERE A.PersonStatus_ID IN (0,1,2)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_HR_PersonTaskInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_HR_PersonTaskInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-24
	描述：个人中心任务信息显示
-------------------------------------------*/
CREATE PROCEDURE WEB_HR_PersonTaskInfo
(
	@personID	int--,	@Identifier	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)
DECLARE @Identifier VARCHAR(MAX)
SET @Identifier=''

SELECT @Identifier=HrPersonStatu FROM employee WHERE typeId=@personID
SET @SQL='
SELECT	b.ID		taskID,
		b.Name		taskname,
		b.Content	content,
		d.ID		personid,
		d.Name		personname,
		a.BeginTime begintime,
		a.DeadTime	endtime,
		c.Name		statusname,
		b.Remark	taskremark
FROM	HR_TaskDistribution a
INNER JOIN HR_TASK b ON a.Task_ID=b.ID 
INNER JOIN HR_TaskStatus c ON c.ID=a.TaskStatus_ID
INNER JOIN employee d ON a.Person_ID=d.typeid
'
IF(@Identifier='3')
BEGIN
	SET @SQL=@SQL+'	WHERE	a.Person_ID='''+@personID+''''
END

EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[web_Hr_QueryAllInterviewEsType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[web_Hr_QueryAllInterviewEsType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：查询所有面试评价类型
*/
CREATE PROC [dbo].[web_Hr_QueryAllInterviewEsType]
--@encode$--
AS
  SELECT * FROM HR_InterviewEsType
  
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HR_QueryAllPersonInfoByPersonStatus_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HR_QueryAllPersonInfoByPersonStatus_ID]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：通过人员状态ID查询所有人员信息
*/

/*
	修改：赵斌
	日期：2011.3.23
	描述：删除因需求变更造成的无用字段
*/

/*
	修改：赵斌
	日期：2011.4.1
	描述：修改表连接方式，删掉无用的字段
*/

CREATE PROC [dbo].[Web_HR_QueryAllPersonInfoByPersonStatus_ID]
(
       @PersonStatus_ID          INT
)
--@encode$--       
AS
  SELECT P.typeId AS personId,
		 P.FullName AS personName,
		 CASE P.Sex WHEN 1 THEN '男' ELSE '女' END AS personSex,
		 HP.Name AS postionName,
		 D.FullName AS deptName,
		 P.Mob AS personPhone
  FROM	employee P 
  INNER JOIN HR_Postion HP ON P.HrpostionId = HP.ID
  INNER JOIN Department D ON HP.Department_ID = D.typeid
  WHERE	P.HrPersonStatu = @PersonStatus_ID
  
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HR_QueryAllTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HR_QueryAllTask]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：查询所有任务
*/
CREATE PROC [dbo].[Web_HR_QueryAllTask]
--@encode$--
AS
SELECT * FROM HR_Task 

SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HR_QueryAllTaskEsType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HR_QueryAllTaskEsType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：查询所有任务评价类型
*/
CREATE PROC [dbo].[Web_HR_QueryAllTaskEsType]
--@encode$--
AS
  SELECT * FROM HR_TaskEsType
SET NOCOUNT ON


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HR_QueryCurTaskByPerson_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HR_QueryCurTaskByPerson_ID]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：通过人员ID查询当前分配给他的任务
*/
CREATE PROC [dbo].[Web_HR_QueryCurTaskByPerson_ID]
(
       @Person_ID         INT
)
--@encode$--       
AS
  SELECT HR_TaskDistribution.ID,
         HR_TaskDistribution.Task_ID,
		 HR_Task.Name							AS taskName,
	     HR_Task.Content						AS taskContent,
	     HR_TaskDistribution.BeginTime			AS taskBegintime,
	     HR_TaskDistribution.EndTime			AS taskEndtime,
	     HR_TaskDistribution.DeadTime			AS taskDeadtime,
	     HR_TaskDistribution.TaskStatus_ID,
	     HR_TaskDistribution.Remark,
	     HR_TaskStatus.Name						AS TaskStatus_Name
  FROM  HR_TaskStatus,HR_TaskDistribution join HR_Task on HR_TaskDistribution.Task_ID=HR_Task.ID
  WHERE HR_TaskDistribution.TaskStatus_ID=HR_TaskStatus.ID and HR_TaskDistribution.Person_ID=@Person_ID
  
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'Web_HR_QueryHRInfoByLoginName') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure Web_HR_QueryHRInfoByLoginName
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-19
	描述：通过HR登陆名查询HR信息
*/

/*
	修改：赵斌
	日期：2011.3.25
	描述：更改表名及字段名
*/
CREATE PROC Web_HR_QueryHRInfoByLoginName
(
       @LoginName      varchar(max)
)
--@encode$--       
AS
  SELECT ID,
         Name,
         LoginName,
         Password,
         Age,
         CASE Sex WHEN 0 THEN '男' ELSE '女' END AS Sex  
  FROM HR_Person WHERE LoginName=@LoginName
SET NOCOUNT ON


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_HR_QueryInterview]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_HR_QueryInterview]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：黄清
	日期：2011-3-26
	描述：查询面试人员信息
-------------------------------------------*/
/*------------------------------------------
	作者：何家福
	日期：2011-6-2
	描述：根据需求修改
-------------------------------------------*/
CREATE PROCEDURE WEB_HR_QueryInterview
--@encode$--
AS
SET NOCOUNT ON

SELECT	b.ID			ID,
		b.Name			Name,
		CASE b.Tall	WHEN 0 THEN '' ELSE CAST(b.Tall AS VARCHAR(3)) END AS Tall,
		b.Hukou			Hukou,
		b.Polity		Polity,
		b.Marriage		Marriage,
		b.Degree		Degree,
		c.Name+'-'+a.Name	Postion,
		b.GraduateDate	GraduateDate,
		c.Name			Department,
		b.Address		Address,
		b.OldMonthlyPay	OldMonthlyPay,
		B.WantPay		WantPay,
		b.University	University,
		b.Speciality	Speciality,
		b.Age			interviewage,
		b.IDCard		IDCard,
		b.Email			Email,
		CONVERT(char(10),b.BirthDay,120) AS BirthDay,
		b.Intro			Intro,
		b.AccessionDate	AccessionDate,
		b.Phone			Phone,
		b.Remark		Remark,
		CASE b.Sex WHEN 0 THEN '男' ELSE '女' END AS Sex
FROM	HR_Postion a
INNER JOIN HR_Person b ON a.ID=b.Postion_ID
INNER JOIN HR_Department c ON a.Department_ID=c.ID 
WHERE	b.PersonStatus_ID IN (1,2)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HR_QueryPostionByID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HR_QueryPostionByID]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：通过职位ID查询职位信息
*/
CREATE PROC [dbo].[Web_HR_QueryPostionByID]
(
         @ID    INT
)
--@encode$--         
AS
  SELECT * FROM HR_Postion WHERE ID=@ID
  
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HR_QueryTaskDist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HR_QueryTaskDist]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：通过任务ID和人员ID查询任务评价信息
*/

/*
*/
CREATE PROC [dbo].[Web_HR_QueryTaskDist]
( 
       @Person_ID    INT
)
--@encode$--       
AS
  SELECT * 
  FROM HR_Task	T 
  INNER JOIN HR_Person P ON P.Postion_ID = T.Postion_ID
  WHERE P.ID = @Person_ID
  AND T.ID 
  NOT IN(
		 SELECT Task_ID 
		 FROM HR_TaskDistribution 
		 WHERE HR_TaskDistribution.Person_ID=@Person_ID
		 )
    
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HR_QueryTaskEsByTask_IDAndPerson_ID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HR_QueryTaskEsByTask_IDAndPerson_ID]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：覃雨翔
	日期：2011-3-17
	描述：通过任务ID和人员ID查询任务评价信息
*/

/*
	修改：赵斌
	日期：2011.3.25
	描述：根据需求调整功能
*/
CREATE PROC [dbo].[Web_HR_QueryTaskEsByTask_IDAndPerson_ID]
(         
         @Task_ID          INT,
         @Person_ID        INT
)
--@encode$--         
AS       
  SELECT t.ID,
         t.Content,
         e.FullName as HR_Name,
         CONVERT(CHAR(10),t.DateTime,120) AS DateTime 
  FROM HR_TaskEstimate t inner join employee e on t.HR_ID = e.typeId
  WHERE t.Task_ID=@Task_ID 
        and t.Person_ID=@Person_ID
    
SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/****** Object:  StoredProcedure [dbo].[Web_HrAdminSearch]    Script Date: 03/16/2011 15:13:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrAdminSearch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrAdminSearch]
GO

/*
	作者：赵斌
	时间：2011.3.15
	描述：列出所有管理员
*/
CREATE PROCEDURE [dbo].[Web_HrAdminSearch]
--@encode$--
AS
SELECT * FROM HR_Administrator

GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER OFF 
GO




SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrEstimateCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_HrEstimateCheck
GO
-- =============================================
-- Author:		韩林
-- Create date: 04/12/2011 
-- Description:	判断是否已经选择了面试项目
-- =============================================
CREATE PROCEDURE [dbo].Web_HrEstimateCheck
(
	
	@tablename VARCHAR(MAX)		--表名
)
--@encode$--
AS	 

IF NOT EXISTS(select top 1 1 from dbo.sysobjects where ID=OBJECT_ID(N''+@tablename) and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
	RETURN 0
ELSE
	RETURN 1
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** Object:  StoredProcedure [dbo].[Web_HrTaskSearch]    Script Date: 03/16/2011 15:05:51 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrEstimateInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrEstimateInfo]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		韩林
-- Create date: 03/23/2011 
-- Description:	面试评价
-- =============================================
CREATE PROCEDURE [dbo].[Web_HrEstimateInfo]
(
	@person_id int
)
--@encode$--
AS

DECLARE @HR varchar(max),
		@times varchar (max)
BEGIN
	SELECT @HR=Name FROM HR_Person
	WHERE  ID=@person_id
	SELECT '第'+CAST(I.Times AS VARCHAR(3))+'轮' AS Times,
		   I.Title,
		   CASE I.Score WHEN 0 THEN '--' ELSE CAST(I.Score AS VARCHAR(1)) END AS Score,
		   I.Content,
		   P.Name AS HR
	FROM   HR_InterviewerEstimate I INNER JOIN HR_Person P ON I.HR_ID=P.ID
	WHERE  I.Person_ID=@person_id
	ORDER BY Times
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrFamily]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrFamily]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		韩林
-- Create date: 03/23/2011 
-- Description:	家庭信息
-- =============================================
CREATE PROCEDURE [dbo].[Web_HrFamily]
(
	@person_id INT
)
--@encode$--	
AS
SELECT ID,
	   Appellation,
	   Name,
	   Company,
	   Phone,
	   Remark
FROM   HR_PersonFamily
WHERE  Person_ID=@person_id
ORDER BY ID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/****** Object:  StoredProcedure [dbo].[Web_HrJobSearch]    Script Date: 03/16/2011 15:05:00 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrGetAllDept]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrGetAllDept]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		赵斌
-- Create date: 03/31/2011 
-- Description:	部门查询
-- =============================================
CREATE PROCEDURE [dbo].[Web_HrGetAllDept]
--@encode$--
AS
SELECT	ID,
		Name,
		Remark,
		userCode
FROM	HR_Department

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrInterviwersPostion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_HrInterviwersPostion
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 03/15/2011 
-- Description:	职位查询
-- =============================================
CREATE PROCEDURE [dbo].[Web_HrInterviwersPostion]
--@encode$--
AS
SELECT P.ID,
	   D.Name+'-'+P.Name AS Name
FROM   HR_Department D INNER JOIN HR_Postion P 
ON     D.ID=P.Department_ID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[Web_HrJobSearch]    Script Date: 03/16/2011 15:05:00 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrJobSearch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrJobSearch]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 03/15/2011 
-- Description:	职位查询
-- =============================================
CREATE PROCEDURE [dbo].[Web_HrJobSearch]
--@encode$--
AS
SELECT HR_Department.Name AS DepartmentName,
	   HR_Postion.Name AS JobName,
	   HR_Postion.Intro AS Intro,
	   HR_Postion.Remark AS Remark
FROM HR_Department,HR_Postion
WHERE HR_Department.ID=HR_Postion.Department_ID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/****** Object:  StoredProcedure [dbo].[Web_HrJobSearch]    Script Date: 03/16/2011 15:05:00 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrJobSearchOnDept]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrJobSearchOnDept]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 03/15/2011 
-- Description:	职位查询
-- =============================================

/*
	修改：赵斌
	日期：2011.4.1
	描述：增加部门条件
*/
/*
	修改：王刚
	日期：2011.12.27
	描述：职位查询
*/
CREATE PROCEDURE [dbo].[Web_HrJobSearchOnDept]
--@encode$--
AS
SELECT H.ID AS JobID,
	   H.Name AS JobName,
	   H.Intro AS Intro,
	   H.Remark AS Remark,
	   D.FullName AS dfullname,
	   h.Department_ID as dtypeid
FROM Department D,HR_Postion H
WHERE D.typeid=H.Department_ID
ORDER BY D.typeid, H.ID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrPersonEdu]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrPersonEdu]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		韩林
-- Create date: 03/23/2011 
-- Description:	教育经历查询
-- =============================================
CREATE PROCEDURE [dbo].[Web_HrPersonEdu]
(
	@person_id INT
)
--@encode$--	
AS
SELECT ID,
	   Date,
	   School,
	   Specialty,
	   Degree
FROM   HR_PersonEdu
WHERE  Person_ID=@person_id
ORDER BY ID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrPersonInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrPersonInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-3-28
	描述：通过人员状态ID查询所有人员信息
*/


CREATE PROC [dbo].[Web_HrPersonInfo]
(
	
	@OperatorId		VARCHAR(MAX),	--操作员ID
	@DTypeId		VARCHAR(MAX),	--部门
    @Status VARCHAR(MAX)='',		--人员状态
    @Name VARCHAR(MAX)=''			--人员名称
)
--@encode$--
AS
SET NOCOUNT ON 

------------------------------------------------------------------------检查权限范围--------------------------------------------------------------------------------

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------检查权限范围结束--------------------------------------------------------------------------	


--部门
CREATE TABLE #GetManDTypeId(TypeID VARCHAR(50))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

DECLARE @SQL VARCHAR(MAX)
SET @SQL='SELECT	p.Name as fullname,
					CONVERT(char(10),p.BirthDay,120) AS BirthDay,
					p.Hukou as nat_place,			--户口
					p.IDCard,
					p.Polity as political,          --政治面貌
					p.Marriage,
					p.Degree as knowledge,
		 			p.University as college,
		 			p.Speciality,
		 			p.GraduateDate,
		 			p.Phone as mob,
		 			p.Email as mail,
		 			s.Name AS Status,      --面试者状态
		 			p.Address,
					p.AccessionDate,	--入职时间
		 			p.OldMonthlyPay,	--原薪酬
		 			p.WantPay,
		 			ps.name as job,
		 			ps.id as jobid,
		 			d.typeid as dtypeid,
		 			d.fullname as dfullname,
		 			d.fullName+''-''+ps.Name AS Postion,
		 			CASE p.BirthDay WHEN '''' THEN '''' ELSE CAST(DATEPART(YYYY, GETDATE())-SUBSTRING(p.BirthDay,1,4) AS VARCHAR(MAX)) END AS AGE, 
		 			CASE p.Tall WHEN 0 THEN '''' ELSE CAST(p.Tall AS VARCHAR(3)) END AS Tall,				--身高
		 			CASE p.Tall WHEN 0 THEN '''' ELSE CAST(p.Tall AS VARCHAR(3)) END AS stature,				--身高
		 			p.* 
		FROM   HR_Person p
		INNER JOIN Hr_Postion ps ON p.Postion_ID = ps.ID 
		INNER JOIN Department d ON d.typeid	=ps.Department_ID
		INNER JOIN #GetManDTypeId gd ON gd.typeid=ps.Department_ID
		INNER JOIN HR_PersonStatus s ON s.ID = p.PersonStatus_ID
		WHERE p.LoginName LIKE ''%'+@name+'%'''
IF @Status=0
	SET @SQL=@SQL+'	AND s.ID IN(1,2,3)'
ELSE
	SET @SQL=@SQL+'	AND s.ID='+@Status
	
SET @SQL=@SQL+'ORDER BY p.ID'
--PRINT(@SQL)
EXEC(@SQL)

SET NOCOUNT ON
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




/****** Object:  StoredProcedure [dbo].[Web_HrAdminSearch]    Script Date: 03/16/2011 15:13:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrPersonSearch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrPersonSearch]
GO

/*
	作者：赵斌
	时间：2011.3.15
	描述：列出所有管理员
*/

/*
	修改：赵斌
	时间：2011.3.23
	描述：修改表
*/
CREATE PROCEDURE [dbo].[Web_HrPersonSearch]
--@encode$--
AS
SELECT * FROM HR_Person

GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER OFF 
GO




/****** Object:  StoredProcedure [dbo].[Web_HrTaskSearch]    Script Date: 03/16/2011 15:05:51 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrTaskSearch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrTaskSearch]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		韩林
-- Create date: 03/15/2011 
-- Description:	任务查询
-- =============================================
/*
	修改：赵斌
	日期：2011.3.31
	描述：连接多表，显示更多信息
*/

/*
	修改：黄清
	时间：2011-4-6
	描述:添加任务查询功能
*/
CREATE PROCEDURE [dbo].[Web_HrTaskSearch]
(
	@departmentid	VARCHAR(MAX) = '',	---部门
	@positionid		VARCHAR(MAX) = ''	---职位
)
--@encode$--
AS
------查询全部任务，没有限制条件
IF(@departmentid='' AND @positionid='')
BEGIN
	SELECT  T.ID AS		taskId,
			T.Name AS	taskName,
			T.Content AS	taskContent,
			T.Remark AS	taskRemark,
			T.StatusID AS taskStatus,
			P.Name	AS	postionName,
			D.Name	AS	deptName,
			D.ID	AS	deptID,
			P.ID	AS	posID
	FROM	HR_Task T 
			INNER JOIN HR_Postion P ON T.Postion_ID = P.ID
			INNER JOIN HR_Department D ON P.Department_ID = D.ID
END

-----根据职位查询任务
IF(@positionid!='' AND @departmentid='')
BEGIN
	SELECT  T.ID		taskId,
			T.Name		taskName,
			T.Content	taskContent,
			T.Remark  AS taskRemark,
			TS.Name   AS     taskStatus,
			P.Name		postionName,
			D.Name		deptName,
			D.ID		deptID,
			P.ID		posID
	FROM	HR_Task T 
			INNER JOIN HR_Postion P ON T.Postion_ID = P.ID
			INNER JOIN HR_Department D ON P.Department_ID = D.ID
			INNER JOIN HR_TaskDistribution TD ON TD.Task_ID = T.ID
			INNER JOIN HR_TaskStatus TS ON TS.ID = TD.TaskStatus_ID
	WHERE	P.ID=@positionid	
END

----根据部门查询任务
IF(@departmentid!='' AND @positionid='')
BEGIN
	SELECT  T.ID	  AS	 taskId,
			T.Name	  AS	 taskName,
			T.Content AS     taskContent,
			T.Remark  AS	 taskRemark,
			TS.Name   AS     taskStatus,
			P.Name	  AS	 postionName,
			D.Name	  AS	 deptName,
			D.ID	  AS	 deptID,
			P.ID	  AS	 posID
	FROM	HR_Task T 
			INNER JOIN HR_Postion P ON T.Postion_ID = P.ID
			INNER JOIN HR_Department D ON P.Department_ID = D.ID
			INNER JOIN HR_TaskDistribution TD ON TD.Task_ID = T.ID
			INNER JOIN HR_TaskStatus TS ON TS.ID = TD.TaskStatus_ID
	WHERE	D.ID=@departmentid	
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_HrWorkExp]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_HrWorkExp]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		韩林
-- Create date: 03/23/2011 
-- Description:	家庭信息
-- =============================================
CREATE PROCEDURE [dbo].[Web_HrWorkExp]
(
	@person_id INT
)
--@encode$--	
AS
SELECT ID,
	   Date,
       Company,
       Department,
       Job,
       DimissionReason,
       ProvePerson,
       CompanyPhone
FROM   HR_PersonWorkExp
WHERE  Person_ID=@person_id
ORDER BY ID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ImportOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_ImportOrderBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
横看成岭侧成峰
*/
CREATE    PROCEDURE Web_ImportOrderBill
(
	@intBillNumberID    VARCHAR(max),
	@loadcomplete		CHAR(1),
	@chvOperatorID      VARCHAR(50),
	@billtype			INT,
	@ptypeid			VARCHAR(MAX)= '',	--商品ID
	@flag				VARCHAR(10),			--出入库单据标记  e.出库单  i.入库单
	@cKtypeID           VARCHAR(50) --仓库ID

)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID VARCHAR(50), @chvMBTypeID VARCHAR(50), @chvMBTypeID2 VARCHAR(50), @chvMETypeID VARCHAR(50), @chvMKTypeID VARCHAR(50), @chvMPTypeID VARCHAR(50), @chvMExpense VARCHAR(50), @chvMIncome VARCHAR(50), @chvMCapital VARCHAR(50), @chvMDtypeid VARCHAR(50), @chvMStypeid VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man VARCHAR(1000)
SET @SQL_Man = ''

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	--SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (a.KtypeID=K.TypeID OR ISNULL(a.KtypeID,'''')='''') '
	--零售零售退货取表头仓库
	IF @billtype IN (305,215,9,14,71,72,87,88,173)
	BEGIN
		SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (a.KtypeID=K.TypeID OR ISNULL(a.KtypeID,'''')='''') '
	END
	--同价，变价、分支机构出/入 调拨 
	ELSE IF @billtype IN (17,21,187,188)
	BEGIN
		-- 取入库仓库
		IF @flag = 'i'
		BEGIN
		SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (b.ktypeid2=K.TypeID OR ISNULL(b.ktypeid2,'''')='''') '
		END

		-- 取出库仓库
		IF @flag = 'e'
		BEGIN
		SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (b.ktypeid=K.TypeID OR ISNULL(b.ktypeid,'''')='''') '	
		END 
	END
	ELSE IF @billtype IN(174)
	BEGIN
		SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (a.ktypeid2=K.TypeID OR ISNULL(a.ktypeid2,'''')='''') '	
	END
	ELSE IF @billtype IN(327,328,329)
	BEGIN
		-- 取入库仓库
		IF @flag = 'i'
		BEGIN
		SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (a.INktypeid=K.TypeID OR ISNULL(a.INktypeid,'''')='''') '
		END

		-- 取出库仓库
		IF @flag = 'e'
		BEGIN
		SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (a.ktypeid=K.TypeID OR ISNULL(a.ktypeid,'''')='''') '		
		END 
	END
	ELSE
	--其他取明细仓库
	BEGIN
		SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (b.ktypeid=K.TypeID OR ISNULL(b.ktypeid,'''')='''') '	
	END
END

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @ptypeid <> ''
BEGIN
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #GetManPTypeId mp ON b.ptypeid = mp.TypeId '
END

-- 商品权限
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
END

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId IN (SELECT * FROM DBO.F_Split(@intBillNumberID,','))

-- ******** 权限范围单独处理 - End ********

DECLARE @tablename	VARCHAR(200)
		--@sqty		NUMERIC(24,10);
		
DECLARE @sql NVARCHAR(MAX);

SELECT @tablename=detailTable FROM dbo.BillName WHERE Billtype=@billtype;

--SELECT @sqty=SUM(ISNULL(qty,0)) FROM dbo.FactDepotInOut WHERE FromBillType=@billtype and frombillnumberid in (SELECT * FROM DBO.F_Split(@intBillNumberID,','))



DECLARE @DBName VARCHAR(500)

IF @billtype IN (71,72,87,88)
	SET @DBName='LendIndex'
ELSE IF @billtype IN (327,328,329)
	SET @DBName='PosAllotApplyBillIndex'
ELSE
	SET @DBName='BillIndex'

SET @sql='SELECT	a.billtype as frombilltype,
					p.typeid,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname1,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname2,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname3,
					(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate1,
					(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate2,
					(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate3,									
					u.fullname AS unit,
					a.BillNumberId,
					(select isnull(SUM(ISNULL(fa.QTY,0)),0) from FactStocks fa  where fa.PtypeId  = p.typeid  AND  fa.KTypeID = ''' + @cKtypeID + ''' AND  fa.KTypeId IN (SELECT TypeId FROM F_GetMANDetailKType('''+@chvOperatorID+'''))) '
					+
					'AS FactQty,	-- 实际数量= 库存量+借出/借进
					 
					'

IF @billtype IN(16,57,71,72,87,88,165,166,167,168,169,170,171,172,173,174,175,183)
BEGIN
     SET @sql = @sql + 'w.FullName AS nunit,
					    w.unitsid AS nunitid,';
END
ELSE BEGIN
     SET @sql = @sql + 'ISNULL((SELECT FullName FROM PType_Units WHERE b.NUnitID = UnitsId), '''') AS nunit,
						b.NUnitID AS nunitid,';
END					

--零售零售退货取表头仓库
IF @billtype IN (305,215,9,14,71,72,87,88,173)
BEGIN
	SET @SQL = @SQL + ' a.ktypeid as ktypeid,
						b.cargoid,
						case when b.cargoid=0
						then ''''
						else (select top 1 fullname from cargotype where cargoid=b.cargoid)
						end as cargofullname,'
END
--同价，变价、分支机构出/入 调拨 
ELSE IF @billtype IN (17,21,187,188)
BEGIN
	-- 取入库仓库
	IF @flag = 'i'
	BEGIN
		SET @SQL = @SQL + ' b.ktypeid2 as ktypeid,b.incargoid as cargoid,
							case when b.incargoid=0
							then ''''
							else (select top 1 fullname from cargotype where cargoid=b.incargoid)
							end as cargofullname,'
	END 
	-- 取出库仓库
	IF @flag = 'e'
	BEGIN
		SET @SQL = @SQL + ' b.ktypeid as ktypeid,b.outcargoid as cargoid,
							case when b.outcargoid=0
							then ''''
							else (select top 1 fullname from cargotype where cargoid=b.outcargoid)
							end as cargofullname,'
	END 
END
ELSE IF @billtype IN(174)
BEGIN
    SET @SQL = @SQL + ' a.ktypeid2 as ktypeid,
						b.cargoid,
						case when b.cargoid=0
						then ''''
						else (select top 1 fullname from cargotype where cargoid=b.cargoid)
						end as cargofullname,'
END
ELSE IF @billtype IN (327)
    SET @SQL = @SQL + ' a.ktypeid as ktypeid,
						b.cargoidout cargoid,
						case when b.cargoidout=0
							then ''''
							else (select top 1 fullname from cargotype where cargoid=b.cargoidout)
						end as cargofullname,'
ELSE IF @billtype IN (328,329)
    SET @SQL = @SQL + ' a.inktypeid as ktypeid,
						b.incargoid cargoid,
						case when b.incargoid=0
							then ''''
							else (select top 1 fullname from cargotype where cargoid=b.incargoid)
						end as cargofullname,'
ELSE
--其他取明细仓库
BEGIN
	SET @SQL = @SQL + ' b.ktypeid as ktypeid,b.cargoid,
						case when b.cargoid=0
						then ''''
						else (select top 1 fullname from cargotype where cargoid=b.cargoid)
						end as cargofullname,'	
END


SET @SQL = @SQL + ' s.usercode as susercode,
					s.FullName as kfullname,
					p.UserCode,
					p.FullName,
					p.FullName as usercodename,
					ABS(b.Qty) AS Qty,					
					itemname= CASE 
								WHEN b.IsCombined = 0  THEN (SELECT FullName FROM xw_SelfData WHERE _Id= b.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= b.ItemId ) 
					END,
					b.ItemId,
					b.IsCombined,
					b.id,
					a.billcode as frombillcode,
					b.comment as base,					
					b.goodsnumber,
					b.serial ,
					p.IfSerial ,
					CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL ELSE ABS(b.nqty) END AS nqty,
					cbd.*,
					p.*
					'
				
	IF @flag = 'e'	--出库类型
	BEGIN
			SET @sql = @sql + ' ,(isnull(ABS(b.Qty),0)-isnull(b.OutFactQty,0)) as incompleteqty '
	END
	ELSE			--入库类型
	BEGIN
			SET @sql = @sql + ' ,(isnull(ABS(b.Qty),0)-isnull(b.InFactQty,0)) as incompleteqty'
	END		
					

--维修接件单
IF @billType NOT IN (165)
BEGIN
	SET @SQL = @SQL + ' ,b.producedate,
						 b.validdate '
END
IF 	@billType NOT IN (87,71,88,72,57,408,165,166,168,172,173,174,183,327,328,329)
BEGIN 
	SET @SQL = @SQL + ' ,b.munitrate'
END 
ELSE
BEGIN
	SET @SQL = @SQL + ' , 1 as munitrate'
END

if @billType NOT IN (87,71,88,72,57,16,165,166,168,172,173,174,183,327,328,329)
BEGIN
	SET @SQL = @SQL + ' ,CASE WHEN ISNULL(b.nunitid,0) = 0 THEN NULL
							ELSE b.UnitRate	END as UnitRate '
END 
ELSE IF @billtype IN (327,328,329)
	SET @SQL = @SQL + ' , 1 AS UnitRate '
ELSE
BEGIN 
  SET @SQL = @SQL + ' , b.UnitRate '
END 
					
					
IF @billType NOT IN (71,72,87,88,172,173,166,165,168,174,183,57)		
BEGIN			
	SET @SQL = @SQL + ',V.FullName AS munit,
	                    v.UnitsId AS munitid,
						dbo.F_GetAllEntrycode(p.typeid,v.UnitsId,2) AS salemunitcode,
						dbo.F_GetAllEntrycode(p.typeid,v.UnitsId,2) AS buymunitcode,
						dbo.F_GetAllEntrycode(p.typeid,v.UnitsId,2) AS stockmunitcode,
						abs(isnull(b.mqty,0)) as mqty
						'
END 
else --没有大单位的表 直接出基本单位
BEGIN 
	SET @SQL = @SQL + ',U.FullName AS munit,
	                    U.UnitsId AS munitid,
	                    U.UnitsId AS unitid,
	                    dbo.F_GetAllEntrycode(p.typeid,U.UnitsId,2) AS salemunitcode,
	                    dbo.F_GetAllEntrycode(p.typeid,U.UnitsId,2) AS buymunitcode,
	                    dbo.F_GetAllEntrycode(p.typeid,U.UnitsId,2) AS stockmunitcode,
						abs(isnull(b.qty,0)) as mqty
						'
END 
	
SET @SQL = @SQL + '					
		  FROM		'+@DBName+' a
		  INNER JOIN '+@tablename+' b ON a.BillNumberId=b.BillNumberId '
		  
if @billtype in(172,166,168)		  
begin
 set @sql = @sql + ' AND b.wxProperty = 0 '
end

		  	
SET @sql = @sql + ' INNER JOIN Ptype p on b.ptypeid=p.typeid 
					LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId 
					LEFT JOIN PType_Units w ON w.UnitsId=p.AssistantUnitId 
					 '	  
IF @chvMPTypeID = '-99999'
BEGIN
SET @sql = @sql + ' INNER JOIN #F_BaseGetManDetailPType Pb ON b.PTypeID = Pb.TypeID '

END		

SET @sql = @sql + 'LEFT JOIN #Custom_T cbd ON cbd.BillId=b.BillNumberId AND cbd.detailid=b.id And cbd.Billtype = ' +CAST(@billtype AS VARCHAR)+ '';

IF @flag = 'i'	--入库类型
BEGIN	
	IF @billtype IN (17,21,187,188)	--同价，变价、分支机构出/入 调拨 
	BEGIN
		SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON b.ktypeid2=s.TypeId 
							LEFT JOIN (SELECT SUM(abs(ISNULL(qty,0)))AS sqty,ptypeid,frombillid,frombillnumberid,A.frombilltype ,A.ktypeid
							FROM dbo.FactDepotInOut A
							INNER JOIN FactIndex B ON A.BillNumberID=B.BillNumberId 
							WHERE	B.RedWord=0 
									AND B.ifcheck=''t'' 
									AND A.FromBillType='+CAST(@billtype AS VARCHAR)+ '
									and frombillnumberid in (SELECT * FROM DBO.F_Split('''+@intBillNumberID+''','','') WHERE ISNULL(A,'''') <> '''')
							group by  ptypeid,frombillid,frombillnumberid,a.frombilltype,A.ktypeid
							) sq on sq.ptypeid=p.typeid and sq.frombillid=b.id and sq.frombillnumberid=b.billnumberid and sq.frombilltype=a.billtype and sq.ktypeid=a.ktypeid2	
							'
	END 
	ELSE IF @billtype IN (328,329)
		SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON b.outktypeid=s.TypeId 
							LEFT JOIN (
										SELECT	SUM(abs(ISNULL(qty,0)))AS sqty,ptypeid,frombillid,frombillnumberid,A.frombilltype ,A.ktypeid
										FROM dbo.FactDepotInOut A
										INNER JOIN FactIndex B ON A.BillNumberID=B.BillNumberId 
										WHERE	B.RedWord=0 
												AND B.ifcheck=''t'' 
												AND A.FromBillType='+CAST(@billtype AS VARCHAR)+ '
												and frombillnumberid in (SELECT * FROM DBO.F_Split('''+@intBillNumberID+''','','') WHERE ISNULL(A,'''') <> '''')
										group by  ptypeid,frombillid,frombillnumberid,a.frombilltype,A.ktypeid
							) sq on sq.ptypeid=p.typeid and sq.frombillid=b.id and sq.frombillnumberid=b.billnumberid and sq.frombilltype=a.billtype and sq.ktypeid=a.inktypeid	'			
	ELSE
	BEGIN 
		IF @billtype IN (305,215,9,14,71,72,87,88,173)
			SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON a.ktypeid=s.TypeId '
		ELSE IF @Billtype in(174)
		BEGIN
		    SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON a.ktypeid2=s.TypeId '
		END
		ELSE
			SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON b.ktypeid=s.TypeId '
			
		SET @SQL = @SQL + ' LEFT JOIN (SELECT SUM(abs(ISNULL(qty,0)))AS sqty,ptypeid,frombillid,frombillnumberid,A.frombilltype ,A.ktypeid
							FROM dbo.FactDepotInOut A
							INNER JOIN FactIndex B ON A.BillNumberID=B.BillNumberId 
							WHERE	B.RedWord=0 
									AND B.ifcheck=''t'' AND
									A.FromBillType='+CAST(@billtype AS VARCHAR)+ '
									and frombillnumberid in (SELECT * FROM DBO.F_Split('''+@intBillNumberID+''','','') WHERE ISNULL(A,'''') <> '''')
							group by  ptypeid,frombillid,frombillnumberid,a.frombilltype,A.ktypeid
							) sq on sq.ptypeid=p.typeid and sq.frombillid=b.id and sq.frombillnumberid=b.billnumberid and sq.frombilltype=a.billtype and sq.ktypeid=a.ktypeid	
							'
	END 
END
ELSE 
BEGIN
	IF @billtype IN (17,21,187,188)	--同价，变价、分支机构出/入 调拨 
	BEGIN
		SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON b.ktypeid=s.TypeId 
							LEFT JOIN (SELECT SUM(abs(ISNULL(qty,0)))AS sqty,ptypeid,frombillid,frombillnumberid,A.frombilltype ,A.ktypeid
							FROM dbo.FactDepotInOut A
							INNER JOIN FactIndex B ON A.BillNumberID=B.BillNumberId 
							WHERE	B.RedWord=0 
									AND B.ifcheck=''t'' 
									AND A.FromBillType='+CAST(@billtype AS VARCHAR)+ '
									and frombillnumberid in (SELECT * FROM DBO.F_Split('''+@intBillNumberID+''','','') WHERE ISNULL(A,'''') <> '''')
							group by  ptypeid,frombillid,frombillnumberid,a.frombilltype,A.ktypeid
							) sq on sq.ptypeid=p.typeid and sq.frombillid=b.id and sq.frombillnumberid=b.billnumberid and sq.frombilltype=a.billtype and sq.ktypeid=a.ktypeid2	
							'
	END 
	ELSE IF @billtype IN (327)
		SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON b.ktypeidout=s.TypeId 
							LEFT JOIN (
										SELECT	SUM(abs(ISNULL(qty,0)))AS sqty,ptypeid,frombillid,frombillnumberid,A.frombilltype ,A.ktypeid
										FROM	dbo.FactDepotInOut A
										INNER JOIN FactIndex B ON A.BillNumberID=B.BillNumberId 
										WHERE	B.RedWord=0 
												AND B.ifcheck=''t'' 
												AND A.FromBillType='+CAST(@billtype AS VARCHAR)+ '
												and frombillnumberid in (SELECT * FROM DBO.F_Split('''+@intBillNumberID+''','','') WHERE ISNULL(A,'''') <> '''')
										group by  ptypeid,frombillid,frombillnumberid,a.frombilltype,A.ktypeid
							) sq on sq.ptypeid=p.typeid and sq.frombillid=b.id and sq.frombillnumberid=b.billnumberid and sq.frombilltype=a.billtype and sq.ktypeid=a.ktypeid	'	
	ELSE
	BEGIN 
		IF @billtype IN (305,215,9,14,71,72,87,88,174,173)
			SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON a.ktypeid=s.TypeId '
		ELSE
			SET @SQL = @SQL + ' LEFT JOIN dbo.Stock s ON b.ktypeid=s.TypeId '
			
		SET @SQL = @SQL + ' LEFT JOIN (SELECT SUM(abs(ISNULL(qty,0)))AS sqty,ptypeid,frombillid,frombillnumberid,A.frombilltype ,A.ktypeid
							FROM dbo.FactDepotInOut A
							INNER JOIN FactIndex B ON A.BillNumberID=B.BillNumberId 
							WHERE	B.RedWord=0 
									AND B.ifcheck=''t'' 
									AND	A.FromBillType='+CAST(@billtype AS VARCHAR)+ '
									and frombillnumberid in (SELECT * FROM DBO.F_Split('''+@intBillNumberID+''','','') WHERE ISNULL(A,'''') <> '''')
							group by  ptypeid,frombillid,frombillnumberid,a.frombilltype,A.ktypeid
							) sq on sq.ptypeid=p.typeid and sq.frombillid=b.id and sq.frombillnumberid=b.billnumberid and sq.frombilltype=a.billtype and sq.ktypeid=a.ktypeid	
							'	
	END 
END
		  

					
IF @flag = 'e' and 	@billtype IN (17,21,187)--出库类型
	SET @sql = @sql + '
						inner join (select BillNumberId ,outcargoid as cargoid,id from '+@tablename+' ) bc on bc.BillNumberId=b.BillNumberId and bc.id=b.id
					'
else if @flag = 'i' and @billtype IN (17,21,188)--入库类型
	SET @sql = @sql + '
						inner join (select BillNumberId ,incargoid as cargoid,id from '+@tablename+' ) bc on bc.BillNumberId=b.BillNumberId  and bc.id=b.id
					'
ELSE IF @billtype IN (327)
	SET @sql = @sql + '
						inner join (select BillNumberId ,cargoidout as cargoid,id from '+@tablename+' ) bc on bc.BillNumberId=b.BillNumberId  and bc.id=b.id
					'
else IF @billtype IN (328,329)
	SET @sql = @sql + '
						inner join (select BillNumberId ,incargoid as cargoid,id from '+@tablename+' ) bc on bc.BillNumberId=b.BillNumberId  and bc.id=b.id
					'
else
	SET @sql = @sql + '
						inner join (select BillNumberId ,cargoid,id from '+@tablename+' ) bc on bc.BillNumberId=b.BillNumberId and bc.id=b.id
					'	
SET @sql = @sql +' left join cargotype ct on ct.cargoid=bc.cargoid ' 	

SET @sql = @sql + '	
			'	


IF @billtype NOT IN (71,72,87,88,172,173,166,165,168,174,183,57)
BEGIN
	SET @SQL = @SQL + 'LEFT JOIN PType_Units v ON v.UnitsId=b.munitid   '
END					
					
SET @sql = @sql + @SQL_Man

SET @sql = @sql + '
	      LEFT JOIN xw_SelfData ON b.ptypeid=xw_SelfData.typeId AND b.ItemID=xw_SelfData._Id
		  LEFT JOIN CustomReferenceValue  ON b.ItemID=CustomReferenceValue.id
		  WHERE		a.BillNumberID IN (SELECT * FROM DBO.F_Split(''' + @intBillNumberID + ''','','') WHERE ISNULL(A,'''') <> '''')
					AND p.isservice = 0
					AND a.billtype='+CAST(@billtype AS VARCHAR)+
					'AND P.Deleted=0 '
					
IF @flag = 'e'	--出库类型
BEGIN
	IF @billtype IN (160,161,16,166,172)	--销售换货单、采购换货单、生产拆装单、上门维修单等双仓库单据
		SET @sql = @sql + ' AND b.InorOut = ''o'''
END
ELSE			--入库类型
BEGIN
	IF @billtype IN (160,161,16,172,166)	--销售换货单、采购换货单、生产拆装单、上门维修单等双仓库单据
		SET @sql = @sql + ' AND b.InorOut = ''i'''
END			

IF @loadcomplete='1'
BEGIN
	IF @Flag='e'
		SET @sql = @sql + ' AND abs(b.qty)-abs(b.outfactqty) > 0'
	ELSE
		SET @sql = @sql + ' AND abs(b.qty)-abs(b.infactqty) > 0'
END

--SELECT @sql FOR XML PATH('')
PRINT @sql
EXEC(@sql)

IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType

DROP TABLE #GetManPTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ImportOrderBillDetail_Qc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_ImportOrderBillDetail_Qc]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2016-09-13
	描述：出入库单据调期初未实物出入库单据
*/
CREATE    PROCEDURE Web_ImportOrderBillDetail_Qc
(
	@intBillNumberID    VARCHAR(max),
	@loadcomplete		CHAR(1),
	@chvOperatorID      VARCHAR(50),
	@billtype			INT,
	@ptypeid			VARCHAR(MAX)= '',	--商品ID
	@flag				VARCHAR(10),			--出入库单据标记  e.出库单  i.入库单,
	@cKtypeID           VARCHAR(50) --仓库ID
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID VARCHAR(50), @chvMBTypeID VARCHAR(50), @chvMBTypeID2 VARCHAR(50), @chvMETypeID VARCHAR(50), @chvMKTypeID VARCHAR(50), @chvMPTypeID VARCHAR(50), @chvMExpense VARCHAR(50), @chvMIncome VARCHAR(50), @chvMCapital VARCHAR(50), @chvMDtypeid VARCHAR(50), @chvMStypeid VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man VARCHAR(1000)
SET @SQL_Man = ''

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON b.KtypeID=K.TypeID '
END

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @ptypeid <> ''
BEGIN
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #GetManPTypeId mp ON b.ptypeid = mp.TypeId '
END

-- ******** 权限范围单独处理 - End ********

--DECLARE @sqty		NUMERIC(24,10);
		
DECLARE @sql NVARCHAR(MAX)
--SELECT @sqty=SUM(ISNULL(qty,0)) FROM dbo.FactDepotInOut WHERE FromBillType=@billtype;


SET @sql='SELECT	a.billtype as frombilltype,
					p.typeid,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname1,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname2,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname3,
					(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate1,
					(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate2,
					(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate3,
					u.FullName AS munit,--期初没得销售单位得 直接取基本单位										
					u.fullname AS unit,
					a.BillNumberId,
					a.ktypeid,
					s.usercode as susercode,
					s.FullName as kfullname,
					p.UserCode,
					p.FullName,
					p.FullName as usercodename,
					ABS(b.Qty) AS Qty,
					(isnull(ABS(b.Qty),0)-isnull(sq.sqty,0)) as incompleteqty,
					itemname= CASE 
								WHEN b.IsCombined = 0  THEN (SELECT FullName FROM xw_SelfData WHERE _Id= b.ItemId)
								ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= b.ItemId ) 
					END,
					b.ItemId,
					b.IsCombined,
					b.id,
					a.billcode as frombillcode,
					b.comment as base,					
					b.goodsnumber,
					b.producedate,
					b.validdate,
					w.FullName AS nunit,
					b.unitid ,
					case when 	b.cargoid=0
				then 
						(select cargoid from cargotype where ktypeid=a.ktypeid )
					else	
						b.cargoid
					end cargoid
					 ,
					case when b.cargoid=0 
					then 
						(select fullname from cargotype where ktypeid=b.ktypeid )
					else	
						ct.fullname 
					end cargofullname,
					b.serial ,
					b.serial as serialsel,
					abs(isnull(b.mqty,0)) as mqty,
					p.IfSerial,
					(select isnull(SUM(ISNULL(fa.QTY,0)),0) from FactStocks fa  where fa.PtypeId  = p.typeid  AND  fa.KTypeID LIKE ''' + @cKtypeID + '%'' AND  fa.KTypeId IN (SELECT TypeId FROM F_GetMANDetailKType('''+@chvOperatorID+'''))) + ( select  isnull(SUM(ISNULL(v.QTY,0)),0) from GoodsLend v where v.PTypeID like p.typeid+''%'' 
					AND v.KTypeID = ''' + @cKtypeID + ''' ) AS FactQty,	-- 实际数量= 库存量+借出/借进
					p.*
							
		  FROM		FactIndex a
		  INNER JOIN FactInOut b ON a.BillNumberId=b.BillNumberId
		  LEFT JOIN dbo.Stock s ON b.ktypeid=s.TypeId
		  INNER JOIN Ptype p on b.ptypeid=p.typeid 
		  LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
		  LEFT JOIN PType_Units w ON w.UnitsId=p.AssistantUnitId
		  LEFT JOIN PType_Units v ON v.UnitsId=b.munitid  
		  left join  cargotype ct on ct.cargoid=b.cargoid '

SET @sql = @sql + '	
			LEFT JOIN (SELECT SUM(abs(ISNULL(qty,0)))AS sqty,ptypeid,frombillid,frombillnumberid,frombilltype ,ktypeid
					FROM dbo.FactDepotInOut 
					WHERE FromBillType='+CAST(@billtype AS VARCHAR)+ '
					and frombillnumberid in (SELECT * FROM DBO.F_Split('''+@intBillNumberID+''','','') WHERE ISNULL(A,'''') <> '''')
					group by  ptypeid,frombillid,frombillnumberid,frombilltype,ktypeid
				) sq on sq.ptypeid=p.typeid and sq.frombillid=b.id and sq.frombillnumberid=b.billnumberid and sq.frombilltype=a.billtype and sq.ktypeid=b.ktypeid	'	

SET @sql = @sql + @SQL_Man

SET @sql = @sql + '
	      LEFT JOIN xw_SelfData ON b.ptypeid=xw_SelfData.typeId AND b.ItemID=xw_SelfData._Id
		  LEFT JOIN CustomReferenceValue  ON b.ItemID=CustomReferenceValue.id
		  WHERE		a.BillNumberID IN (SELECT * FROM DBO.F_Split(''' + @intBillNumberID + ''','','') WHERE ISNULL(A,'''') <> '''')
					AND p.isservice = 0
					AND a.billtype='+CAST(@billtype AS VARCHAR)
					
IF @loadcomplete='1'
BEGIN
	SET @sql = @sql + ' and (isnull(ABS(b.Qty),0)-isnull(sq.sqty,0))>0'
END


--PRINT @sql
EXEC(@sql)

IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType

DROP TABLE #GetManPTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_IncExpDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_IncExpDetailQuery]
GO

-------------------------------------------------------------------------
--收入报表、费用报表明细表查询
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23

	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-09-22
	--说明：取消客户与供货商是否统一的判断以及相应的处理，因为在统计收入
	--与费用的时候，可以通过条件筛选往来单位。

	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-09-23
	--说明：对ListTable中往来单位为空的情况进行处理。
	--原来不能统计出该类单据信息。现强制性增加往来单位为空时的过滤条件。
	
	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome

	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类	


	--修改记录#05--------------------------------------------------------
	--人员：Wang Wei
	--日期：2004-02-19
	--说明：右键支持查询b.EtypeID,b.BtypeID,	

	-- 2013-07-31 周华 修改权限函数 参考列表存储过程

-------------------------------------------------------------------------
CREATE   PROCEDURE Web_IncExpDetailQuery
(
	@QueryType 	INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(50),	--指定要查询的节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@BTypeID		VARCHAR(1550),	--往来单位编号
	@ETypeID		VARCHAR(1550),	--经手人编号
	@STypeID		VARCHAR(MAX),	--分支机构
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@IsShowDetails 	BIT				--是否按项目明细展开 1=是 0=否
	
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


--======================================基本信息【BEGIN】=============================

IF @AtypeID='00000'
	SET @AtypeID=''

--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
IF @AtypeID=''
	BEGIN
		--'00003'	--“收入类”科目根节点 --“支出类”科目根节点 #04 添加
		SET @ATypeID=CASE @QueryType WHEN 0 THEN '00003' WHEN 1 THEN '00004' END
	END

--项目
CREATE TABLE #AType(TypeID VARCHAR(50),NID VARCHAR(50),ItemFullName VARCHAR(200))
IF @QueryType=0 -- 收入
	BEGIN
		INSERT INTO #Atype(TypeID,NID,ItemFullName) 
		SELECT 
			A.TypeId,
			A.nid,
			I.FullName
		FROM F_TreeIncomeC(@OperatorID) A
		INNER JOIN dbo.f_split(@AtypeID,',') B ON LEFT(A.TypeId,LEN(B.a))=B.a
		INNER JOIN Ac_Items I ON I.nId=A.nid
	END
ELSE  --费用
	BEGIN
		INSERT INTO #Atype(TypeID,NID,ItemFullName) 
		SELECT 
			A.nTypeId,
			A.nid,
			I.FullName
		FROM F_LineF(@OperatorID) A
		INNER JOIN dbo.f_split(@AtypeID,',') B ON LEFT(A.nTypeId,len(B.a))=B.a
		INNER JOIN Ac_Items I ON I.nId=A.nid
		
		-- 插入 费用合计 以外的会计科目	
		INSERT INTO #Atype(TypeID,NID,ItemFullName)
		SELECT nTypeId,nId,FullName
		FROM AC_Items 
		WHERE 
			SonNum=0
			AND nTypeId like '00004%' and nTypeId NOT LIKE '0000400003%'  AND nTypeId LIKE @ATypeID+'%'
			AND ntypeid NOT IN (SELECT typeid FROM #atype)
	END

--往来单位
CREATE TABLE #Btype(TypeID VARCHAR(50))
IF @BtypeID =''
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetManDetailBType(@OperatorID) UNION ALL SELECT ''
	END
ELSE
	BEGIN
		INSERT INTO #Btype(TypeID) 
		SELECT a.TypeId 
		FROM F_GetManDetailBType(@OperatorID) A
		INNER JOIN dbo.f_split(@BtypeID,',') B ON LEFT(A.TypeId,len(B.a))=B.a
	END
	
--经手人
CREATE TABLE #EType(TypeID VARCHAR(50))
IF @EtypeID=''
	BEGIN
		INSERT INTO #EType(TypeID)
		SELECT TypeId FROM F_GetManDetailEType(@OperatorID) UNION ALL SELECT '' 
	END
ELSE
	BEGIN
		INSERT INTO #EType(TypeID)
		SELECT a.TypeId 
		FROM F_GetManDetailEType(@OperatorID) A
		INNER JOIN dbo.f_split(@EtypeID,',') B ON LEFT(A.TypeId,LEN(B.a))=B.a
	END

--分支机构
CREATE TABLE #SType(TypeID VARCHAR(50))
IF @StypeID=''
	BEGIN
		INSERT INTO #SType(TypeID) SELECT TypeId FROM F_GetManDetailSType(@OperatorID)
	END
ELSE
	BEGIN
		INSERT INTO #SType(TypeID) 
		SELECT a.typeid FROM F_GetManDetailSType(@OperatorID) A 
		INNER JOIN dbo.f_split(@STypeID,',') B ON LEFT(A.TypeId,LEN(B.a))=B.a	
	END	
		
--部门	
CREATE TABLE #DType(TypeID VARCHAR(50))
INSERT INTO #DType(TypeID)SELECT TypeId FROM F_GetManDetailDType(@OperatorID) UNION ALL SELECT ''


--======================================基本信息【END】=============================



--======================================业务逻辑及结果集【BEGIN】=============================

SELECT 
	L.BillNumberID,
	L.BillDate,
	B.BillCode,
	L.BillType,
	B.RedWord,
	L.EtypeID,
	L.DtypeID,
	L.BtypeId,
	L.STypeID,
	e1.FullName Checke,			
	B.Comment,
	SUM(ISNULL(l.Total,0)) Total,
	0.00 JeTotal,
	isnull(BN.BillName,'''') BillName,
	CASE WHEN @IsShowDetails=1 THEN A.ItemFullName ELSE '' END ItemFullName
FROM ListTable l
INNER JOIN #SType S ON S.TypeID=L.STypeID--分支机构
INNER JOIN(
	SELECT BillNumberID,BillType,BillCode,RedWord,Comment,checke FROM BillIndex WHERE ifYearBill=0
	UNION ALL
	SELECT BillNumberID,BillType,BillCode,RedWord,Comment,checke FROM ReceiptBillIndex WHERE ifYearBill=0
	UNION ALL
	SELECT BillNumberID,BillType,BillCode,RedWord,Comment,checke FROM Coupon_BillIndex WHERE ifYearBill=0
	UNION ALL
	SELECT BillNumberID,BillType,BillCode,RedWord,Comment,checke FROM CommissionBillNew--提成单
) B  ON l.BillNumberID=b.BillNumberID AND L.BillType = B.BillType
INNER JOIN #Btype T ON T.TypeID=L.BtypeId--经手人
INNER JOIN #AType A ON A.NID=L.AtypeId
INNER JOIN #DType D ON D.TypeID=L.DTypeID
INNER JOIN #Etype E ON E.TypeID=L.EtypeId
INNER JOIN BillName BN ON L.BillType=BN.Billtype
INNER JOIN employee E1 ON E1.typeId=B.checke
WHERE 
	L.Audited=1
	AND L.BillDate BETWEEN @BillDateBegin AND @BillDateEnd
GROUP BY 
	L.BillNumberID,
	L.BillDate,
	B.BillCode,
	L.BillType,
	B.RedWord,
	L.EtypeID,
	L.DtypeID,
	L.BtypeId,
	L.STypeID,
	e1.FullName,			
	B.Comment,
	BN.BillName,
	CASE WHEN @IsShowDetails=1 THEN A.ItemFullName ELSE '' END
UNION ALL
SELECT 
	L.BillNumberID,
	L.BillDate,
	B.BillCode,
	L.BillType,
	B.RedWord,
	L.EtypeID,
	L.DtypeID,
	L.BtypeId,
	L.STypeID,
	e1.FullName Checke,			
	B.Comment,
	SUM(ISNULL(l.Total,0)) Total,
	0.00 JeTotal,
	isnull(BN.BillName,'''') BillName,
	CASE WHEN @IsShowDetails=1 THEN A.ItemFullName ELSE '' END ItemFullName
FROM ListTable l
INNER JOIN #SType S ON S.TypeID=L.STypeID--分支机构
INNER JOIN(
	SELECT BillNumberID,BillType,BillCode,RedWord,Comment,checke FROM dbo.PosAllotApplyBillIndex --门店类单据
) B  ON l.BillNumberID=b.BillNumberID AND L.BillType = B.BillType
INNER JOIN #AType A ON A.NID=L.AtypeId
INNER JOIN #DType D ON D.TypeID=L.DTypeID
INNER JOIN #Etype E ON E.TypeID=L.EtypeId
INNER JOIN BillName BN ON L.BillType=BN.Billtype
INNER JOIN employee E1 ON E1.typeId=B.checke
WHERE 
	L.Audited=1
	AND L.BillDate BETWEEN @BillDateBegin AND @BillDateEnd
GROUP BY 
	L.BillNumberID,
	L.BillDate,
	B.BillCode,
	L.BillType,
	B.RedWord,
	L.EtypeID,
	L.DtypeID,
	L.BtypeId,
	L.STypeID,
	e1.FullName,			
	B.Comment,
	BN.BillName,
	CASE WHEN @IsShowDetails=1 THEN A.ItemFullName ELSE '' END
ORDER BY L.BillDate


--======================================业务逻辑及结果集【END】=============================


--======================================删除临时表【BEGIN】=============================

--EXECUTE Web_IncExpDetailQuery 0,'0000300003','2003-1-1','2003-9-12','','','00001',1
DROP TABLE #Atype,#Btype,#Etype,#SType,#DType

--======================================删除临时表【END】=============================


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_IncExpLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_IncExpLineQuery]
GO







-------------------------------------------------------------------------
--收入报表、费用报表线性表查询
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23

	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-09-22
	--说明：取消客户与供货商是否统一的判断以及相应的处理，因为在统计收入
	--与费用的时候，可以通过条件筛选往来单位。

	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-09-23
	--说明：对ListTable中往来单位为空的情况进行处理。
	--原来不能统计出该类单据信息。现强制性增加往来单位为空时的过滤条件。

	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-09-24
	--说明：添加开帐至今的累计余额统计

	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome

	--修改记录#05--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类


	--修改作者：谢吉康
	--修改原因：处理本期发生额(应该不变)
	--修改时间：2004-08-31
	--修改结果：本地测试结果正确
-------------------------------------------------------------------------
CREATE   PROCEDURE Web_IncExpLineQuery 
(
	@QueryType 	INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(100),	--指定要查询的节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@BTypeID		VARCHAR(1550),	--往来单位编号
	@ETypeID		VARCHAR(1550),	--经手人编号
	@STypeID		VARCHAR(MAX),	--经手人编号
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@FilterCode		VARCHAR(100)='',	--过滤科目Usercode
	@FilterName		VARCHAR(100)=''	--过滤科目名称
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @BeginDate 		VARCHAR(20)		--用于保存期初日期的变量
DECLARE @SQL 			VARCHAR(2000)	--用于保存动态SQL语句的变量
DECLARE @Point			INT				--用于保存截取子字符串位置的变量
DECLARE @SUBSTRING		VARCHAR(255)	--用于保存子字符串的变量


IF @AtypeID='00000'
	SET @AtypeID=''
--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
IF @AtypeID=''
BEGIN
	SET @ATypeID=CASE @QueryType
		WHEN 0 THEN '00003'			--“收入类”科目根节点
		WHEN 1 THEN '00004' ----“支出类”科目根节点 #05 添加
	END
END

CREATE TABLE #AType (TypeID varchar(50),NID VARCHAR(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))


IF @QueryType=0 -- 收入
BEGIN
	INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
	select ntypeid,nid,usercode,fullname,sonnum 
		from AC_Items 
		where ntypeid in ( select a.typeid from /*F_GetManDetailATypeSr*/F_TreeIncomeC(@OperatorID) a, (select * from  dbo.f_split(@AtypeID,',')) b 
		where left(a.typeid,len(b.a))=b.a)

	---- 插入 其他收入 以外的会计科目
	--INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum)  
	--	select ntypeid,nid,usercode,fullname,sonnum 
	--	from AC_Items 
	--	where sonnum=0 
	--		and  ntypeid like '00003%' and ntypeid not like '0000300003%' and ntypeid like @atypeid+'%'
	--		AND ntypeid not in (select typeid from #atype)
END
ELSE  --费用
BEGIN
	INSERT INTO #Atype(typeid,nid,usercode,fullname,sonnum) 
		select ntypeid,nid,usercode,fullname,sonnum 
		from AC_Items 
		where ntypeid in ( select a.ntypeid from /*F_GetManDetailATypeFy*/F_AllTreeExpenseC(@OperatorID) a, (select * from  dbo.f_split(@AtypeID,',')) b 
		where left(a.ntypeid,len(b.a))=b.a)
	---- 插入 费用合计 以外的会计科目
	--INSERT INTO #Atype (typeid,nid,usercode,fullname,sonnum) 
	--	select ntypeid,nid,usercode,fullname,sonnum 
	--	from AC_Items 
	--	where sonnum=0 
	--		and  ntypeid like '00004%' and ntypeid not like '0000400003%'  and ntypeid like @atypeid+'%'
	--		AND ntypeid not in (select typeid from #atype)
END


IF @BtypeID =''
BEGIN
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
	INSERT INTO #Btype select ''
END
ELSE
	INSERT INTO #Btype 
		select a.typeid 
		from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b 
		where left(a.typeid,len(b.a))=b.a

IF @EtypeID=''
BEGIN
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
	INSERT INTO #Etype(typeid) select '' --处理为空的经手人
END
ELSE
	INSERT INTO #Etype 
		select a.typeid 
		from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@EtypeID,',')) b 
		where left(a.typeid,len(b.a))=b.a

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a


-- 获得期初日期
SELECT @BeginDate=[StartDate] 
FROM [MonthProc]
WHERE [MonthNo]='本期'
--print @BeginDate

SET @SQL='
	SELECT 
		a.TypeID,
		--a.SonNum,
		--a.UserCode,
		--a.FullName,
		ISNULL(b.BYTotal,0) AS BYTotal,
		ISNULL(b.LJTotal,0) AS LJTotal,
		ISNULL(b.KZTotal,0) AS KZTotal
	FROM #atype a
	LEFT JOIN


	(
		SELECT 
			l.atypeid AS TypeID,
			SUM(
				CASE	--计算本期合计					
					WHEN l.BillDate>=''' + @BeginDate +''' THEN l.total
				ELSE
					0
				END
			) AS BYTotal,
			SUM(
				CASE	--计算选定时段发生额					
					WHEN l.BillDate>=''' + @BillDateBegin +''' AND l.BillDate<='''+@BillDateEnd+''' THEN l.total
				ELSE
					0
				END
			) AS LJTotal,
			SUM(l.total) AS KZTotal  --计算开帐至今累计
		FROM listtable l
	'
IF NOT (@BTypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL =@SQL+' INNER JOIN #btype s on (l.btypeid=s.typeid) '

IF NOT (@ETypeID= '' AND @METypeId = '00001')
	SET @SQL =@SQL+' INNER JOIN #etype e on (l.etypeid=e.typeid) '
IF NOT (@ATypeID = '' AND @MAtypeid = '0000')
	SET @SQL =@SQL+' INNER JOIN #atype a on (l.atypeid=a.nid) '
IF NOT (@STypeID = '' AND @MStypeid = '00000')
	SET @SQL =@SQL+' INNER JOIN #Stype st on (l.stypeid=st.typeid) '
IF @MDtypeid = '-99999'
	SET @SQL =@SQL+' INNER JOIN F_GetManDetailDtype('''+@OperatorID+''') de on (l.dtypeid=de.typeid) '
	
SET @SQl=@SQL+'
				WHERE 
					Audited = 1
			  '

SET @SQL=@SQL + '
		GROUP BY atypeid
	) b
	ON b.typeid = a.nid 
	WHERE sonnum =0 '


--组织科目编号过滤条件
IF @FilterCode<>'' 
BEGIN
	SET @Point=charindex(',',@FilterCode)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FilterCode,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @SUBSTRING + '%'''
		SET @FilterCode=SUBSTRING(@FilterCode,@Point+1,len(@FilterCode)-@Point)
		SET @Point=charindex(',',@FilterCode)
	END 
	IF @FilterCode<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.UserCode LIKE ''%' + @FilterCode + '%'''
	END 
END 

--组织科目名称过滤条件
IF @FilterName<>'' 
BEGIN
	SET @Point=charindex(',',@FilterName)
	WHILE @Point>0
	BEGIN
		SET @SUBSTRING=SUBSTRING(@FilterName,1,@Point-1)
		--Print @SUBSTRING
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @SUBSTRING + '%'''
		SET @FilterName=SUBSTRING(@FilterName,@Point+1,len(@FilterName)-@Point)
		SET @Point=charindex(',',@FilterName)
	END 
	IF @FilterName<>''
	BEGIN
		SET @SQL=@SQL + '
		AND a.FullName LIKE ''%' + @FilterName + '%'''
	END	
END 

SET @SQL=@SQL + '
	ORDER BY usercode
'

--print @SQL
--return
EXECUTE(@SQL)
DROP TABLE #Atype,#Btype,#Etype

--EXECUTE Web_IncExpLineQuery 0,'00003','2003-01-01','2004-01-01','00000','00001','00001'


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_IncExpListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_IncExpListQuery]
GO

-------------------------------------------------------------------------
--收入报表、费用报表树型表查询
--作者：王浩源
--日期：2003-08-26
--引用：GP_CheckOperatorRight23

	--修改记录#01--------------------------------------------------------
	--人员：王浩源
	--日期：2003-09-22
	--说明：取消客户与供货商是否统一的判断以及相应的处理，因为在统计收入
	--与费用的时候，可以通过条件筛选往来单位。

	--修改记录#02--------------------------------------------------------
	--人员：王浩源
	--日期：2003-09-23
	--说明：对ListTable中往来单位为空的情况进行处理。
	--原来不能统计出该类单据信息。现强制性增加往来单位为空时的过滤条件。

	--修改记录#03--------------------------------------------------------
	--人员：王浩源
	--日期：2003-09-24
	--说明：添加开帐至今的累计余额统计
	
	--修改记录#04--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：屏蔽“借转进货结算与成本差”在收入报表中的显示

	--修改记录#05--------------------------------------------------------
	--人员：王浩源
	--日期：2003-10-08
	--说明：原来的会计科目权限限制使用的是@MAtypeid，正确的是使用@MExpense或@MIncome

	--修改记录#06--------------------------------------------------------
	--人员：王浩源
	--日期：2004-01-12
	--说明：实现功能，把操作员不能查询的会计科目名称过滤掉。

	--修改记录#07--------------------------------------------------------
	--人员：王浩源
	--日期：2004-02-19
	--说明：把费用类科目扩大到支出类

	--修改作者：谢吉康
	--修改原因：处理本期发生额(应该不变)
	--修改时间：2004-08-31
	--修改结果：本地测试结果正确

	--修改记录#08--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修科目(qp1.0)
	
	--修改记录#09
	--人员：毛欣蓉
	--日期：2011-1-3
	--说明：增加分支机构查询条件
	
	--修改记录#10
	--人员：周华
	--日期：2013-06-09
	--说明：9.2版本调整多级权限函数
	-- 费用 把以前的 F_GetManDetailATypeFy 改成 F_LineF
	-- F_GetManATypeFyAll 改成 F_AllTreeF
	-- 2013-07-23 修改收入部分 
-------------------------------------------------------------------------

CREATE PROCEDURE Web_IncExpListQuery  
(
	@QueryType 	INT,			--查询类型，0表示收入报表，1表示费用报表
	@ATypeID 		VARCHAR(50),	--指定要查询的节点ID
	@BillDateBegin	VARCHAR(20),	--时间范围下限
	@BillDateEnd	VARCHAR(20),	--时间范围上限
	@BTypeID		VARCHAR(1550),	--往来单位编号
	@ETypeID		VARCHAR(1550),	--经手人编号
	@StypeID		VARCHAR(1550),	--分支机构编号
	@OperatorID 	VARCHAR(50)		--操作员ID号
)
--@encode$--
AS

SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


DECLARE @BeginDate 		VARCHAR(20)		--用于保存期初日期的变量
DECLARE @SQL 			VARCHAR(2000)	--用于保存动态SQL语句的变量


--判断输入的节点ID是否合法，如果输入为空的字符串，那么根据查询类型设置根节点ID
IF @AtypeID=''
BEGIN
	SET @ATypeID=CASE @QueryType
		WHEN 0 THEN '00003'			--“收入类”科目根节点
		WHEN 1 THEN '00004' --“支出类”科目根节点 #07 添加
	END
END

CREATE TABLE #Atype (TypeID varchar(50),NID VARCHAR(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #STYPE	(TypeID varchar(50))
CREATE TABLE #DTYPE (TypeID VARCHAR(50))
CREATE TABLE #MainType (TypeID varchar(50),NID VARCHAR(50),usercode varchar(200),fullname varchar(200),sonnum int)

CREATE CLUSTERED INDEX CIX_TYPEID ON #Btype(TypeID)
CREATE CLUSTERED INDEX CIX_TYPEID ON #Etype(TypeID)
CREATE CLUSTERED INDEX CIX_TYPEID ON #STYPE(TypeID)
CREATE CLUSTERED INDEX CIX_TYPEID ON #DTYPE(TypeID)

IF @QueryType=0 -- 收入
BEGIN	
	-- 收入类
	INSERT INTO #Atype select a.typeid,a.nid from /*F_GetManDetailATypeSr*/F_TreeIncomeC(@OperatorID) a, (select * from  dbo.f_split(@AtypeID,',')) b where left(a.typeid,len(b.a))=b.a	
	
	---- 插入 收入 其他收入 以外的会计科目
	--INSERT INTO #Atype select ntypeid,nid from AC_Items where sonnum=0
	--and  ntypeid like '00003%' and ntypeid not like '0000300003%' and ntypeid like @atypeid+'%'
	--AND ntypeid not in (select typeid from #atype)
	
END
ELSE  --费用
BEGIN
	INSERT INTO #Atype select a.ntypeid,a.nid from /*F_GetManDetailATypeFy*/F_AllTreeExpenseC(@OperatorID) a, (select * from  dbo.f_split(@AtypeID,',')) b where left(a.ntypeid,len(b.a))=b.a
	---- 插入 费用合计 以外的会计科目
	--INSERT INTO #Atype select ntypeid,nid from AC_Items where sonnum=0
	--and  ntypeid like '00004%' and ntypeid not like '0000400003%'  and ntypeid like @atypeid+'%'
	--AND ntypeid not in (select typeid from #atype)
END

IF @MDtypeid = '-99999'
    INSERT INTO #DTYPE SELECT a.typeid FROM F_GetManDetailDtype(@OperatorID) a

IF @BtypeID =''
BEGIN
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
	INSERT INTO #Btype select ''
END
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @EtypeID=''
BEGIN
	INSERT INTO #Etype select typeid from F_GetManDetailEType(@OperatorID)
	INSERT INTO #Etype(typeid) select '' --处理为空的经手人
END
ELSE
	INSERT INTO #Etype select a.typeid from F_GetManDetailEType(@OperatorID) a, (select * from  dbo.f_split(@EtypeID,',')) b where left(a.typeid,len(b.a))=b.a
IF @StypeID=''
BEGIN
	INSERT INTO #STYPE SELECT a.TYPEID FROM F_GetManDetailSType(@OperatorID) a
END
ELSE
	INSERT INTO #STYPE select a.typeid from F_GetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@stypeID,',')) b where left(a.typeid,len(b.a))=b.a
DECLARE @sonnum int 
SET @sonnum =0

SELECT @sonnum = sonnum FROM AC_Items WHERE NTypeid =@AtypeID
IF @sonnum =0 
	IF @QueryType=0 -- 收入
	BEGIN
		INSERT INTO #MainType(typeid,nid,usercode,fullname,sonnum) 
		SELECT a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum FROM ac_items a
		,(select * from /*F_GetManATypeSrAll*/F_AllTreeIncomeC(@OperatorID) where ntypeid =@AtypeID) b where a.ntypeid=b.ntypeid
				
		---- 插入 收入 其他收入 以外的会计科目
		--INSERT INTO #MainType(typeid,nid,usercode,fullname,sonnum) 
		--select ntypeid,nid,usercode,fullname,sonnum from AC_Items where ntypeid=@Atypeid
		--and  ntypeid like '00003%' and ntypeid not like '0000300003%' 
		--AND ntypeid not in (select typeid from #MainType)
	END
	ELSE --费用
	BEGIN
		INSERT INTO #MainType(typeid,nid,usercode,fullname,sonnum) 
		SELECT a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum FROM AC_Items a
		,(select * from /*F_GetManATypeFyAll*/F_AllTreeExpenseC(@OperatorID) where ntypeid =@AtypeID) b where a.ntypeid=b.ntypeid
		
		---- 插入 费用合计 以外的会计科目
		--INSERT INTO #MainType(typeid,nid,usercode,fullname,sonnum) 
		--select ntypeid,nid,usercode,fullname,sonnum from AC_Items WHERE ntypeid=@Atypeid
		--AND ntypeid LIKE '00004%' AND ntypeid NOT LIKE '0000400003%' 
		--AND ntypeid NOT IN (select typeid from #MainType)
	END
ELSE
	IF @QueryType=0 -- 收入
	BEGIN
		-- 收入
		INSERT INTO #MainType(typeid,nid,usercode,fullname,sonnum) 
		SELECT a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum FROM AC_Items a
		,(select * from /*F_GetManATypeSrAll*/F_AllTreeIncomeC(@OperatorID) where nparid=@AtypeID and ntypeid LIKE @AtypeID+'%' ) b where a.ntypeid=b.ntypeid

		---- 插入 收入 其他收入 以外的会计科目
		--INSERT INTO #MainType(typeid,nid,usercode,fullname,sonnum) 
		--select ntypeid,nid,usercode,fullname,sonnum from AC_Items WHERE nparid=@Atypeid
		--and  ntypeid like '00003%' and ntypeid not like '0000300003%' 
		--AND ntypeid not in (select typeid from #MainType)
	END
ELSE
BEGIN
		INSERT INTO #MainType(typeid,nid,usercode,fullname,sonnum) 
		SELECT a.ntypeid,a.nid,a.usercode,a.fullname,a.sonnum FROM AC_Items a
		,(select * from /*F_GetManATypeFyAll*/F_AllTreeExpenseC(@OperatorID) where nparid=@AtypeID and ntypeid LIKE @AtypeID+'%' ) b where a.ntypeid=b.ntypeid
		-- 插入 费用合计 以外的会计科目
		--INSERT INTO #MainType(typeid,nid,usercode,fullname,sonnum) 
		--select ntypeid,nid,usercode,fullname,sonnum from AC_Items where nparid=@Atypeid
		--and  ntypeid like '00004%' and ntypeid not like '0000400003%' 
		--AND ntypeid not in (select typeid from #MainType)
END

				DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #MainType where typeid='000040000200004'--#08 删除商品送修科目			

-- 获得期初日期
SELECT @BeginDate=[StartDate] 
FROM [MonthProc]
WHERE [MonthNo]='本期'

SET @SQL='
	SELECT 
		a.TypeID,
		a.SonNum,
		a.UserCode,
		a.FullName,
		ISNULL(b.BYTotal,0) AS BYTotal,
		ISNULL(b.LJTotal,0) AS LJTotal,
		ISNULL(b.KZTotal,0) AS KZTotal
	FROM #MainType a
	LEFT JOIN
	(
		SELECT 
			SUBSTRING(AC.ntypeid,1,len(''' + @ATypeID + ''') + 5) AS typeid,
			SUM(
				CASE	--计算本期合计
					WHEN L.BillDate>=''' + @BeginDate +''' THEN L.total
				ELSE
					0
				END
			) AS BYTotal,
			SUM(
				CASE	--计算选定时段发生额
					WHEN L.BillDate>=''' + @BillDateBegin +'''AND L.BillDate<='''+@BillDateEnd+''' THEN L.total
				ELSE
					0
				END
			) AS LJTotal,
			SUM(L.total) AS KZTotal  --计算开帐至今累计
		FROM listtable L
  INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
	'
IF NOT (@BTypeID = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL =@SQL+' INNER JOIN #btype s on (L.btypeid=s.typeid) '

IF NOT (@ETypeID= '' AND @METypeId = '00001')
	SET @SQL =@SQL+' INNER JOIN #etype e on (L.etypeid=e.typeid) '
IF NOT (@ATypeID = '' AND @MAtypeid = '0000')
	SET @SQL =@SQL+' INNER JOIN #atype a on (AC.ntypeid=a.typeid) '
IF NOT (@StypeID = '' AND @MStypeid = '00000')
	SET @SQL =@SQL+' INNER JOIN #stype st on (L.stypeid=st.typeid) '
IF @MDtypeid = '-99999'
	SET @SQL =@SQL+' INNER JOIN #DTYPE de on (L.dtypeid=de.typeid) '
SET @SQL=@SQL+'
				WHERE 
				Audited = 1
			'
--由于 借转进货结算与成本差 科目不应该在收入中显示，故添加一个过滤限制

SET @SQL=@SQL + '
		GROUP BY SUBSTRING(AC.ntypeid,1,len(''' + @ATypeID + ''') + 5)
	) b
	ON a.typeid=b.typeid '

SET @SQL=@SQL + '
	ORDER BY usercode
'

--#04 以上新修改的语句-----------------------------------------------------
--select * from #atype
--SELECT * FROM #maintype;
--select * from #STYPE
--PRINT(@SQL)
EXECUTE(@SQL)
DROP TABLE #Atype,#Btype,#Etype,#MainType,#STYPE,#DTYPE
--EXECUTE Web_IncExpListQuery 0,'','2003-01-01','2004-01-01','00000','00001','00001'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_IncomeStatement]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_IncomeStatement
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：收支利润表
	描述：
*/
CREATE PROCEDURE Web_IncomeStatement
(
	@OperatorID VARCHAR(50), --操作员id
	@StypeID	VARCHAR(max),	  --分支机构id,多个以逗号隔开
	@Qtype		 INT,  --查询类型 1=当前，2=本月，3=本年
	@currentmonth VARCHAR(50) --哪一个月
)
--@encode$--
AS
SET NOCOUNT ON
	SELECT @OperatorId = typeId FROM dbo.employee WHERE UserCode = @OperatorId or fullname=@OperatorId
	CREATE TABLE #stype(typeid VARCHAR(50))
	
	--分支权限
	INSERT INTO #stype
	SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeID,11,@OperatorID)
	
	DECLARE @InCome NUMERIC(24,10)	--收入
	DECLARE @Cost	NUMERIC(24,10)  --成本
	DECLARE @Profits NUMERIC(24,10) --利润
	
    
	--结果表	
	CREATE TABLE #Result(Typeid VARCHAR(50),nid INT,fullname VARCHAR(200),Total NUMERIC(24,10))

	IF @Qtype=1--当前
	BEGIN
		--收入
		SELECT @InCome=ISNULL(SUM(A.TOTAL),0)
		FROM dbo.AType_Total A,
			dbo.Ac_Items AC,
			#stype s
		WHERE A.ATypeID=AC.nId
			AND s.typeid=a.STypeID
			AND AC.nTypeId LIKE'00003%' AND AC.SonNum=0
		
		--成本
		SELECT @Cost=ISNULL(SUM(A.TOTAL),0)
		FROM dbo.AType_Total A,
			dbo.Ac_Items AC,
			#stype s
		WHERE A.ATypeID=AC.nId
			AND s.typeid=a.STypeID
			AND AC.nTypeId LIKE'00004%' AND AC.SonNum=0
			
		--利润=收入-成本
	   SET @Profits=@InCome-@Cost
	   
	   INSERT INTO #Result
	   SELECT '00003' AS typeid, 65 AS nid,'收入' AS fullname ,@InCome AS total
	   UNION ALL
	   SELECT '00004' AS typeid, 68 AS nid,'成本' AS fullname ,@Cost AS total
	   UNION ALL
	   SELECT '0000500005' AS typeid, 50 AS nid,'利润' AS fullname ,@Profits AS total
	END
    ELSE  --其他查询本年 本月等
    BEGIN
		DECLARE @StartDate DATETIME,
			@EndDate    DATETIME,
			@currentyear varchar(50)
			
		IF @Qtype = 2 --本月 
		BEGIN
			SET @StartDate = DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)	   --本月第一天
			SET @EndDate = DATEADD(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))    --本月最后一天
		END
		IF @Qtype = 3 --本年 
		BEGIN
			SET @StartDate = DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)		  --本年第一天
			SET @EndDate = DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))	  --本年最后一天
		END
		
		IF @Qtype = 4 --当前月
		BEGIN
		    
		    select @currentyear=cast(year(getdate()) as varchar(100)) + cast(@currentmonth as varchar(50))
		
			SELECT @StartDate = CAST((LEFT(@currentyear,4)+'-'+SUBSTRING(@currentyear,5,LEN('20157'))+'-'+'01') AS DATETIME)		  
			SELECT @EndDate = DATEADD(DAY,-1,DATEADD(MONTH,1,CAST((LEFT(@currentyear,4)+'-'+SUBSTRING(@currentyear,5,LEN(@currentyear))+'-'+'01') AS DATETIME)))
		END
		
		CREATE TABLE #tmpTable(AtypeID INT,NtypeID VARCHAR(50),Total NUMERIC(24,10))
		
		INSERT INTO #tmpTable(AtypeID,NtypeID,Total)
			SELECT l.AtypeID,ac.nTypeId,SUM(l.total)
			FROM dbo.ListTable l,
				dbo.Ac_Items ac,
				 #stype s
			WHERE l.AtypeId=ac.nId
				AND l.STypeID=s.typeid
				AND (AC.nTypeId LIKE '00003%' OR  AC.nTypeId LIKE'00004%') 
				AND AC.SonNum=0
				AND BillDate>@StartDate
				AND BillDate<@EndDate
			GROUP BY l.AtypeId,ac.nTypeId   
		
	    --收入
		SELECT @InCome=ISNULL(SUM(A.TOTAL),0)
		FROM #tmpTable A
	    WHERE a.nTypeId LIKE'00003%'
		
		--成本
		SELECT @Cost=ISNULL(SUM(A.TOTAL),0)
		FROM #tmpTable A
	    WHERE a.nTypeId LIKE'00004%'
			
		--利润=收入-成本
	   SET @Profits=@InCome-@Cost
		 
	   INSERT INTO #Result
	   SELECT '00003' AS typeid, 65 AS nid,'收入' AS fullname ,@InCome AS total
	   UNION ALL
	   SELECT '00004' AS typeid, 68 AS nid,'成本' AS fullname ,@Cost AS total
	   UNION ALL
	   SELECT '0000500005' AS typeid, 50 AS nid,'利润' AS fullname ,@Profits AS total
	   
	   DROP TABLE #tmpTable
    END
    
	SELECT * FROM #Result
	
	
	DROP TABLE #stype,#Result
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_IncomeStatementDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_IncomeStatementDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：收支利润表明细
	描述：
*/
CREATE PROCEDURE Web_IncomeStatementDetail
(
	@OperatorID VARCHAR(50), --操作员id
	@StypeID	VARCHAR(max),	  --分支机构id,多个以逗号隔开
	@Qtype		 INT,  --查询类型 1=当前，2=本月，3=本年 
	@detialType	 VARCHAR(50), --明细类型 '00003'=收入，'00004'=成本
	@currentmonth VARCHAR(50) --哪一个月
)
--@encode$--
AS
SET NOCOUNT ON
	SELECT @OperatorId = typeId FROM dbo.employee WHERE UserCode = @OperatorId or fullname=@OperatorId
	CREATE TABLE #stype(typeid VARCHAR(50))
	
	--分支权限
	INSERT INTO #stype
	SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeID,11,@OperatorID)
	
	DECLARE @InCome NUMERIC(24,10)	--收入
	DECLARE @Cost	NUMERIC(24,10)  --成本
	DECLARE @Profits NUMERIC(24,10) --利润
	
	
	--结果表	
	CREATE TABLE #Result(Typeid VARCHAR(50),nid INT,fullname VARCHAR(200),Total NUMERIC(24,10))
	
	IF @Qtype=1--当前
	BEGIN
		IF @detialType='00003' --收入
		 BEGIN
			INSERT INTO #Result( Typeid, nid, fullname, Total )
			SELECT '0000300002',66 AS AtypeID,'商品类收入',SUM(a.Total) AS total 
			FROM dbo.ListTable a
			INNER JOIN dbo.Ac_Items ac ON a.ATypeID=ac.nId
			INNER JOIN #stype s ON a.STypeID=s.typeid
			WHERE ac.NtypeID LIKE '0000300002%'    AND ac.SonNum=0
			UNION ALL
			SELECT '0000300003',67 AS AtypeID,'其他收入',SUM(a.Total) AS total 
			FROM dbo.ListTable a
			INNER JOIN dbo.Ac_Items ac ON a.ATypeID=ac.nId
			INNER JOIN #stype s ON a.STypeID=s.typeid
			WHERE ac.NtypeID LIKE '0000300003%'    AND ac.SonNum=0
			UNION ALL
			SELECT '0000300004',12 AS AtypeID,'返点获利收入',SUM(a.Total) AS total 
			FROM dbo.ListTable a
			INNER JOIN dbo.Ac_Items ac ON a.ATypeID=ac.nId
			INNER JOIN #stype s ON a.STypeID=s.typeid
			WHERE ac.NtypeID LIKE '0000300004%'    AND ac.SonNum=0
		 END
		 ELSE
		 BEGIN
			INSERT INTO #Result( Typeid, nid, fullname, Total )
			SELECT '0000400002',69 AS AtypeID,'商品类支出',SUM(a.Total) AS total 
			FROM dbo.ListTable a
			INNER JOIN dbo.Ac_Items ac ON a.ATypeID=ac.nId
			INNER JOIN #stype s ON a.STypeID=s.typeid
			WHERE ac.NtypeID LIKE '0000400002%'    AND ac.SonNum=0
			UNION ALL
			SELECT '0000400003',70 AS AtypeID,'费用合计',SUM(a.Total) AS total 
			FROM dbo.ListTable a
			INNER JOIN dbo.Ac_Items ac ON a.ATypeID=ac.nId
			INNER JOIN #stype s ON a.STypeID=s.typeid
			WHERE ac.NtypeID LIKE '0000400003%'    AND ac.SonNum=0
			UNION ALL
			SELECT '0000400004',16 AS AtypeID,'返利支出',SUM(a.Total) AS total 
			FROM dbo.ListTable a
			INNER JOIN dbo.Ac_Items ac ON a.ATypeID=ac.nId
			INNER JOIN #stype s ON a.STypeID=s.typeid
			WHERE ac.NtypeID LIKE '0000400004%'    AND ac.SonNum=0
		 END
	END
    ELSE IF @Qtype<>0 --其他查询本年 本月等
    BEGIN
		DECLARE @StartDate DATETIME,
			@EndDate    DATETIME,
			@currentyear varchar(50)
			
		IF @Qtype = 2 --本月 
		BEGIN
			SET @StartDate = DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)	   --本月第一天
			SET @EndDate = DATEADD(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))    --本月最后一天
		END
		IF @Qtype = 3 --本年 
		BEGIN
			SET @StartDate = DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)		  --本年第一天
			SET @EndDate = DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))	  --本年最后一天
		END
		IF @Qtype = 4 --当前月
		BEGIN
		    
		    select @currentyear=cast(year(getdate()) as varchar(100)) + cast(@currentmonth as varchar(50))
		
			SELECT @StartDate = CAST((LEFT(@currentyear,4)+'-'+SUBSTRING(@currentyear,5,LEN('20157'))+'-'+'01') AS DATETIME)		  
			SELECT @EndDate = DATEADD(DAY,-1,DATEADD(MONTH,1,CAST((LEFT(@currentyear,4)+'-'+SUBSTRING(@currentyear,5,LEN(@currentyear))+'-'+'01') AS DATETIME)))
		END
		
		
		CREATE TABLE #tmpTable(AtypeID INT,NtypeID VARCHAR(50),Total NUMERIC(24,10))
	
		INSERT INTO #tmpTable(AtypeID,NtypeID,Total)
		SELECT l.AtypeID,ac.nTypeId,SUM(l.total)
		FROM dbo.ListTable l,
			dbo.Ac_Items ac,
			 #stype s
		WHERE l.AtypeId=ac.nId
			AND l.STypeID=s.typeid
			AND (AC.nTypeId LIKE '00003%' OR  AC.nTypeId LIKE'00004%') 
			AND AC.SonNum=0
			AND BillDate>@StartDate
			AND BillDate<@EndDate
	    GROUP BY l.AtypeId,ac.nTypeId  
	
		--SELECT @StartDate,@EndDate 
    
	   IF @detialType='00003' --收入
		 BEGIN
			INSERT INTO #Result( Typeid, nid, fullname, Total )
			SELECT '0000300001',11 AS AtypeID,'销售收入',SUM(Total) AS total 
			FROM #tmpTable 
			WHERE NtypeID LIKE '0000300001%'
			UNION ALL
			SELECT '0000300002',66 AS AtypeID,'商品类收入',SUM(Total) AS total 
			FROM #tmpTable 
			WHERE NtypeID LIKE '0000300002%'
			UNION ALL
			SELECT '0000300003',67 AS AtypeID,'其他收入',SUM(Total) AS total 
			FROM #tmpTable 
			WHERE NtypeID LIKE '0000300003%'
			UNION ALL
			SELECT '0000300004',12 AS AtypeID,'返点获利收入',SUM(Total) AS total 
			FROM #tmpTable 
			WHERE NtypeID LIKE '0000300004%'
		 END
		 ELSE
		 BEGIN
			INSERT INTO #Result( Typeid, nid, fullname, Total )
			SELECT '0000400001',21 AS AtypeID,'销售成本',SUM(Total) AS total 
			FROM #tmpTable 
			WHERE NtypeID LIKE '0000400001%'
			UNION ALL
			SELECT '0000400002',69 AS AtypeID,'商品类支出',SUM(Total) AS total 
			FROM #tmpTable 
			WHERE NtypeID LIKE '0000400002%'
			UNION ALL
			SELECT '0000400003',70 AS AtypeID,'费用合计',SUM(Total) AS total 
			FROM #tmpTable 
			WHERE NtypeID LIKE '0000400003%'
			UNION ALL
			SELECT '0000400004',16 AS AtypeID,'返利支出',SUM(Total) AS total 
			FROM #tmpTable 
			WHERE NtypeID LIKE '0000400004%'
		 END
		 DROP TABLE #tmpTable
    END
    
	SELECT Typeid,nid,fullname,ISNULL(Total,0) AS Total FROM #Result
	DROP TABLE #stype,#Result
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_IndexChartData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_IndexChartData
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：
*/
CREATE PROCEDURE Web_IndexChartData
(
	@tag				INT   --1代表销售数据，2为费用情况，3为库存情况，4为资金情况,5为应收，6为超期应收
)
--@encode$--
AS
SET NOCOUNT ON

	IF @tag= 3
		SELECT * FROM IndexChartData WHERE flag=@tag ORDER BY total DESC
	ELSE 
		SELECT * FROM IndexChartData WHERE flag=@tag ORDER BY total ASC
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_IniBalanceSheetQuery]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].Web_IniBalanceSheetQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE  PROCEDURE [dbo].[Web_IniBalanceSheetQuery]
(
	@OperatorID	varchar(50),		--操作员ID
	@hidezero	INT=0,
	@StypeId	varchar(max)		--分支机构id
)
--@encode$--
AS
SET NOCOUNT ON

	DECLARE 
		@ALL_INCOME_ID varchar(50),       
		@ALL_EXPENSE_ID varchar(50),                
		@ASSETS_ID varchar(50),           
		@DEBT_ID varchar(50)             

	SELECT @ALL_INCOME_ID='00003' --          【收入类】
	SELECT @ALL_EXPENSE_ID='00004'--         【支出类】
	SELECT @ASSETS_ID ='00001'  --【资产合计】
	SELECT @DEBT_ID='00002'   --【负债合计】


	CREATE TABLE #Stype (TypeID varchar(50),IfAssetsIni int)

	INSERT INTO #Stype(typeid,IfAssetsIni)  
		select a.typeid,c.IfAssetsIni
			FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) a
			JOIN stype c ON a.typeid=c.TypeId


	--是否启用发票立账
	DECLARE @isinvoice INT
	SET @isinvoice = ISNULL((SELECT SubValue FROM dbo.sysdata WHERE SubName = 'isinvoice'),0)
	
	--2015-05-18 杨俊修改 因需求HH，强烈需要这样干，所以把[发出商品]放在[库存商品总值]下一行、[应付暂估]放在[应付合计]下一行
	SELECT  p.nparid AS parid ,
			p.deleted ,
			p.leveal ,
			p.ntypeId AS typeid,
			CASE FullName
				WHEN '发出商品' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '库存商品总值') + '1'
				WHEN '应付暂估' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '应付合计') + '1'
				ELSE p.ntypeId
			END AS ordertypeid,
			p.UserCode ,
			p.FullName ,
			p.sonnum ,
			ISNULL(s.total00,0) AS total00,
			nId
	INTO    #Atype
	FROM    dbo.Ac_Items p
			LEFT JOIN ( 
				SELECT a.atypeid,SUM(a.Total00) AS total00
				FROM dbo.AType_Total a
				INNER JOIN #Stype s ON a.STypeID=s.typeid
				GROUP BY a.ATypeID
			) s ON s.ATypeID = p.nId
	WHERE   p.ntypeId <> '00000'
		AND (NOT(@isinvoice = 0)--是否启用发票立账
		OR (@isinvoice = 0) AND P.UserCode NOT IN('1251','2122'))
		
	--判断资产负债表的权限
	DECLARE @re INT 
	EXEC @re = GP_CheckLimit @OperatorID,4226
	IF @re =1	--没有查看损益表所有项目的权限
	BEGIN
		DELETE 
		FROM	#Atype 
		WHERE	typeid NOT IN (
			SELECT nTypeId FROM F_AllTreeAssetsT(@OperatorID)--资产合计(固定资产+银行账户+管辖其他资产)
			UNION ALL
			SELECT nTypeId FROM F_AllTreeInDebtT(@OperatorID)--负债合计（管辖负债+账户里面的预收）
			UNION ALL
			SELECT nTypeId FROM F_AllTreeOwnerEquityT(@OperatorID)--所有者权益
			UNION ALL
			SELECT '00001' AS nTypeId
			UNION ALL
			SELECT '00002' AS nTypeId
			UNION ALL
			SELECT '00005' AS nTypeId
		)
	END

		declare @dTotalIncom00  NUMERIC(24, 10) ,@dTotalExpense00  NUMERIC(24, 10) 
		SELECT @dTotalIncom00=isnull(sum(total00),0) FROM #atype WHERE left(typeid,5)=@ALL_INCOME_ID
		SELECT @dTotalExpense00=isnull(sum(total00),0) FROM #atype WHERE left(typeid,5)=@ALL_EXPENSE_ID
		
		
		Create TABLE #Bassert00
		(
		[ID] [numeric](10, 0) IDENTITY (1, 1) NOT NULL ,
		usercode varchar(300),
		fullname varchar(300),
		leveal int,
		typeid varchar(50),
		sonnum int,
		parid varchar(50),
		total  NUMERIC(24, 10) ,
		fullname1 varchar(300),
		leveal1 int,
		total1  NUMERIC(24, 10) ,
		parid1 varchar(50),
		typeid1 varchar(50),
		Sonnum1 int
		)
		DECLARE @MaxID1 int
		SET @MaxID1 =0
		
		DECLARE @year INT
		
		/*SELECT a.* INTO #MonthProc
		FROM MonthProc a
		INNER JOIN(
			SELECT MIN(Year) AS YE,STypeID FROM dbo.MonthProc WHERE period=1 GROUP BY STypeID 
		)B	ON A.Year=B.YE AND A.STypeID=B.STypeID 
		WHERE A.period=1*/
		
		SELECT a.* INTO #MonthProc
		FROM MonthProc a
		INNER JOIN(
			SELECT MIN(Year) AS YE,MIN(period) AS period,STypeID FROM dbo.MonthProc  GROUP BY STypeID 
		)B	ON A.Year=B.YE AND A.STypeID=B.STypeID 
		WHERE A.period=b.period
		
		-- 期初固定资产计算 --
		-- 准备条件数据
		DECLARE @display INT=0;
		DECLARE @stypeinfo TABLE(stypeid VARCHAR(100),ifassetsini INT,ifopen INT,iscard INT,val  NUMERIC(24, 10) );
		INSERT INTO @stypeinfo 
		SELECT	a.typeid,
				a.ifassetsini,
				ISNULL(b.VALUE,0),
				CASE WHEN EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName = 'assets' AND SubValue = '1') THEN 1 ELSE 0 END,
				0.0 
		FROM #stype a 
		LEFT JOIN Stype_UserConfig b ON a.typeid=b.stypeid;


		
		UPDATE @stypeinfo SET iscard=1 
		WHERE ifassetsini=0 AND ifopen=0 AND EXISTS(SELECT 1 FROM dbo.sysdata WHERE SubName='assets' AND SubValue='1')--未开账初始化 看配置
		OR ifopen=0 AND ifassetsini=1; --未开账 初始化
		
		UPDATE a SET a.iscard=1
		FROM @stypeinfo a JOIN 
		(SELECT u.*,v.typeid FROM Ac_FixedAssetsInit_Stype u JOIN stype v ON u.stypeid=v.VerifyID) b --处理非独立核算的
		ON a.stypeid=b.typeid
		INNER JOIN  #MonthProc p ON p.STypeID=a.stypeid 
		WHERE a.ifopen=1 AND ifassetsini=1  AND p.StartDate>=b.InitDate
		--AND (SELECT MIN(startdate) FROM dbo.MonthProc WHERE period=1)>=b.InitDate --未开账,初始化 或 开账 初始化和时间判断
		
		-- 显示
		SELECT @display=1 WHERE EXISTS(SELECT 1 FROM @stypeinfo WHERE iscard=1) --显示为卡片
		
		-- 计算数据 卡片
		UPDATE a SET a.val=b.netvalue FROM @stypeinfo a JOIN (SELECT stypeid,ISNULL(SUM(w.netvalue),0) AS netvalue FROM Ac_AssetsCards w WHERE w.AssetsState IN(1,4) GROUP BY w.STypeId) b ON a.stypeid=b.stypeid
		WHERE a.iscard=1 AND ifassetsini=0; -- 卡片显示,未初始化的情况
							
		;WITH cte AS (
			SELECT rn=ROW_NUMBER() OVER(PARTITION BY AssertsCardId ORDER BY Id desc),* FROM Ac_AssetsCards_History WHERE BillType=0
		)
		UPDATE a SET a.val=b.netvalue FROM @stypeinfo a JOIN (SELECT stypeid,ISNULL(SUM(netvalue),0) AS netvalue FROM cte WHERE rn=1 GROUP BY stypeid) b ON a.stypeid=b.stypeid
		WHERE a.iscard=1 AND ifassetsini=1 -- 卡片显示,初始化的情况	

		-- 计算项目数据
		UPDATE a SET a.val=b.total00 
		FROM @stypeinfo a JOIN (SELECT stypeid,ISNULL(SUM(total00),0) AS total00 FROM dbo.AType_Total  WHERE  atypeid  LIKE '0000100002%' GROUP BY stypeid) b ON a.stypeid=b.stypeid
		WHERE a.iscard=0
		--
		
		INSERT  INTO #Bassert00
				( usercode ,
				  fullname ,
				  leveal ,
				  typeid ,
				  sonnum ,
				  parid ,
				  total
				)
		SELECT  a.usercode ,
				a.fullname ,
				a.leveal ,
				a.typeid ,
				a.sonnum ,
				a.parid ,
				( SELECT    ISNULL(SUM(b.total00), 0)
				  FROM      #Atype b
				  WHERE     LEFT(b.typeid, LEN(a.typeid)) = a.typeid
				) AS 'Total'
		FROM    #Atype a
		WHERE   LEFT(a.typeid, 5) = @ASSETS_ID
				AND a.typeid <> '0000200002'
				AND a.typeid <> '0000100006'
                
				-- 卡片管理 固定资产
				AND (@display=1 
						AND (a.typeid NOT LIKE '0000100002%' OR a.typeid ='0000100002')
					OR @display<>1)
					
				AND a.usercode NOT IN ('SYC-1601','SYC-1602')
		--ORDER BY a.typeid
		ORDER BY a.ordertypeid
		
		SET @MaxID1 =@@Rowcount

		DECLARE @fullname varchar(300)
		DECLARE @leveal int
		DECLARE @Total  NUMERIC(24, 10) 
		DECLARE @typeid varchar(50)
		DECLARE @parid varchar(50)
		DECLARE @sonnum int
		DECLARE @i int
		SET @i =1
		DECLARE BassCurSor CURSOR FOR	
		SELECT  a.fullname ,
				a.leveal ,
				a.typeid ,
				a.parid ,
				a.sonnum ,
				( SELECT    ISNULL(SUM(b.total00), 0)
				  FROM      #Atype b
				  WHERE     LEFT(b.typeid, LEN(a.typeid)) = a.typeid
				) AS 'Total'
		FROM    #atype a
		WHERE   a.typeid <> '0000200002'
				AND a.typeid <> '0000100006'
				AND ( LEFT(a.typeid, 5) = @DEBT_ID
					  OR ( LEFT(a.typeid, 5) = '00005'
						  
						 )
					)
		ORDER BY a.ordertypeid
		OPEN BassCurSor
		FETCH NEXT FROM BassCurSor INTO @fullname,@leveal,@typeid,@parid,@sonnum,@Total
		WHILE @@FETCH_STATUS =0
		BEGIN
		IF @I<=@MaxID1
		BEGIN
			UPDATE #Bassert00 SET fullname1=@fullname,leveal1=@leveal,total1=@Total,typeid1=@typeid,parid1=@parid,sonnum1=@sonnum WHERE [ID]=@i
		END	
		ELSE
		BEGIN
			INSERT INTO #Bassert00(fullname1,leveal1,total1,typeid1,parid1,Sonnum1) VALUES(@fullname,@leveal,@total,@typeid,@parid,@sonnum)
		END
		SET @i = @i + 1
		FETCH NEXT FROM BassCurSor INTO @fullname,@leveal,@typeid,@parid,@sonnum,@Total
		END
		CLOSE BassCurSor
		DEALLOCATE BassCurSor

		-- 修改应收款合计
		--UPDATE #Bassert00 SET total=(SELECT sum(artotal00) FROM BType_ARAPTotal WHERE btypeid like '00001%' and STypeID in(select typeid from #Stype) ) WHERE typeid='0000100005'
		UPDATE #Bassert00 SET total=(SELECT sum(isnull(artotal00,0)) FROM BType_ARAPTotal  where STypeID in(select typeid from #Stype) ) WHERE typeid='0000100005'
		
		-- 内部应收合计
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName = 'Proinfo' AND SubValue = '4')
		BEGIN
			UPDATE #Bassert00 SET total=(SELECT ISNULL(SUM(innerArTotal00),0) FROM dbo.SType_InnerARTotal WHERE stypeid IN (SELECT typeid FROM #stype)) WHERE typeid='0000100010'
		END

		-- 固定资产 卡片管理 更新

		IF(@display=1)
		BEGIN
			UPDATE #Bassert00 SET total=(
				SELECT SUM(val) FROM @stypeinfo
			)
			WHERE typeid='0000100002'
		END
		
		
		-- 修改库存总值
		UPDATE #Bassert00 SET total=ISNULL((SELECT sum(isnull(i.Total,0)) as total FROM inigoodsstocks i inner join stock s on i.KtypeId=s.typeId where s.STypeID in(select typeId from #Stype)),0) WHERE typeid='0000100001'
		-- 修改委托代销期初
		UPDATE #Bassert00 SET total=ISNULL((SELECT sum(isnull(CostTotal,0)) as total FROM inicommissionstock WHERE type=140 and STypeID in (select typeid from #Stype)),0) WHERE typeid='0000100008'
		
		-- 资产合计
		UPDATE #Bassert00 SET total=ISNULL((SELECT sum(isnull(total,0)) FROM #Bassert00 WHERE parid='00001'),0) WHERE typeid='00001'
		
		-- 修改应付款合计
		UPDATE #Bassert00 SET total1=ISNULL((SELECT sum(aptotal00) FROM BType_ARAPTotal WHERE   STypeID in(select typeid from #Stype)),0) WHERE typeid1='0000200001'
		-- 修改代销商品期初
		UPDATE #Bassert00 SET total1=ISNULL((SELECT sum(isnull(Total,0)) as total FROM inicommissionstock WHERE type=144 and STypeID in (select typeid from #Stype)),0) WHERE typeid1='0000200003'
		
		-- 修改负债合计
		UPDATE #Bassert00 SET total1=ISNULL((SELECT sum(isnull(Total1,0)) as total FROM #Bassert00 WHERE  typeid1 NOT in ('0000200001','0000200002','0000200003') AND LEFT(parid1,5)='00002' and sonnum1=0),0) WHERE typeid1='00002'
		UPDATE #Bassert00 SET total1=total1+ISNULL((SELECT sum(isnull(Total1,0)) as total FROM #Bassert00 WHERE  typeid1 ='0000200001'),0) WHERE typeid1='00002' -- +应付
		UPDATE #Bassert00 SET total1=total1+ISNULL((SELECT sum(isnull(Total1,0)) as total FROM #Bassert00 WHERE  typeid1 ='0000200003'),0) WHERE typeid1='00002' -- +代销
		

		
		UPDATE  #Bassert00 SET fullname='    '+isnull(fullname,'') WHERE leveal=2 
		UPDATE  #Bassert00 SET fullname1='    '+isnull(fullname1,'') WHERE leveal1=2
		
		UPDATE  #Bassert00 SET fullname='        '+isnull(fullname,'') WHERE leveal=3
		UPDATE  #Bassert00 SET fullname1='        '+isnull(fullname1,'') WHERE leveal1=3
		
		UPDATE  #Bassert00 SET fullname='            '+isnull(fullname,'') WHERE leveal=4
		UPDATE  #Bassert00 SET fullname1='            '+isnull(fullname1,'') WHERE leveal1=4
		
		UPDATE  #Bassert00 SET fullname='                '+isnull(fullname,'') WHERE leveal=5
		UPDATE  #Bassert00 SET fullname1='                '+isnull(fullname1,'') WHERE leveal1=5

		UPDATE  #Bassert00 SET fullname='                    '+isnull(fullname,'') WHERE leveal=6
		UPDATE  #Bassert00 SET fullname1='                    '+isnull(fullname1,'') WHERE leveal1=6

		UPDATE  #Bassert00 SET fullname='                        '+isnull(fullname,'') WHERE leveal=7
		UPDATE  #Bassert00 SET fullname1='                        '+isnull(fullname1,'') WHERE leveal1=7

		UPDATE  #Bassert00 SET fullname='                            '+isnull(fullname,'') WHERE leveal=8
		UPDATE  #Bassert00 SET fullname1='                            '+isnull(fullname1,'') WHERE leveal1=8

		UPDATE  #Bassert00 SET fullname='                                '+isnull(fullname,'') WHERE leveal=9
		UPDATE  #Bassert00 SET fullname1='                                '+isnull(fullname1,'') WHERE leveal1=9

		UPDATE  #Bassert00 SET fullname='                                    '+isnull(fullname,'') WHERE leveal=10
		UPDATE  #Bassert00 SET fullname1='                                    '+isnull(fullname1,'') WHERE leveal1=10
	
		
		IF @hidezero=1
		BEGIN
			;WITH c1 AS (
				SELECT rn=ROW_NUMBER() OVER(ORDER BY a.id),ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname,ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE ISNULL(a.total,0) END AS total 
				FROM #Bassert00 a WHERE ISNULL(a.total,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #bassert00 b WHERE a.typeid like b.typeid+'%' AND b.total=0 AND b.sonnum<>0 )
			),c2 AS (
				SELECT rn=ROW_NUMBER() OVER(ORDER BY id), ISNULL(a.typeid1,'') AS typeid1,ISNULL(a.parid1,'') AS parid1,ISNULL(a.fullname1,'') AS fullname1,ISNULL(a.sonnum1,0) AS sonnum1,ISNULL(total1,0) AS total1,a.Leveal
				FROM #Bassert00 a WHERE ISNULL(total1,0)<>0
				AND NOT EXISTS(SELECT 1 FROM #bassert00 b WHERE a.typeid1 LIKE b.typeid1+'%' AND b.total1=0 AND b.sonnum<>0 )
			)
			SELECT ISNULL(a.typeid,'') AS typeid,ISNULL(a.parid,'') AS parid,ISNULL(a.usercode,'') AS usercode,ISNULL(a.fullname,'') AS fullname, ISNULL(a.sonnum,0) AS sonnum,CASE WHEN ISNULL(typeid, '') = '' THEN a.total ELSE  ISNULL(a.total,0) END  AS total
			,ISNULL(b.typeid1,'') AS typeid1,ISNULL(b.parid1,'') AS parid1,ISNULL(b.fullname1,'') AS fullname1,ISNULL(b.sonnum1,0) AS sonnum1,CASE WHEN ISNULL(b.typeid1,'')='' THEN b.total1 ELSE  ISNULL(b.total1,0) END AS total1 
			FROM c1 a FULL JOIN c2 b ON a.rn=b.rn;
		END
		ELSE
		BEGIN
			SELECT  ISNULL(typeid, '') AS typeid ,
					ISNULL(parid, '') AS parid ,
					ISNULL(usercode, '') AS usercode ,
					ISNULL(fullname, '') AS fullname ,
					ISNULL(sonnum, 0) AS sonnum ,
					CASE WHEN ISNULL(typeid, '') = '' THEN total
						 ELSE ISNULL(total, 0)
					END AS total ,
					ISNULL(typeid1, '') AS typeid1 ,
					ISNULL(parid1, '') AS parid1 ,
					ISNULL(fullname1, '') AS fullname1 ,
					ISNULL(sonnum1, 0) AS sonnum1 ,
					CASE WHEN ISNULL(typeid1, '') = '' THEN total1
						 ELSE ISNULL(total1, 0)
					END AS total1
			FROM    #Bassert00
		END
		
		DROP TABLE #Bassert00
		
	


DROP TABLE #Atype,#MonthProc



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InitPtypeSerialSelect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InitPtypeSerialSelect]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
受托委托已发货期初序列号选择
李灏龙
时间：2015年5月19日 15:52:06
描述：委托期初录入序列号时进行序列号选择
*/
CREATE   PROCEDURE Web_InitPtypeSerialSelect
(
	@ptypeID	varchar(50),	-- 商品ID
	@stypeID varchar(50),		--分支机构ID
	@serial varchar(1000),
	@itemID int,
	@goodscostprice  NUMERIC(24, 10) ,
	@producedate varchar(50),	--生产日期
	@validdate varchar(50),		--有效日期
	@goodsnumber varchar(50),	--批号
	@intPageNo		int,		-- 当前查询的页码
	@intPageSize	int,		-- 每页的显示记录数
	@intRowCount	int = 0 output		-- 返回总记录数
)
-- ********	数据库游标分页 - Start	********
--@encode$--
-- 建立查询临时表 
AS
CREATE TABLE #initTempSerial
(
	AutoID int NOT NULL IDENTITY (1, 1),
	Serial varchar(1000),
	ItemID int,
	IsCombined int,
	ItemName varchar(500),
	GoodsCostPrice  NUMERIC(24, 10) ,
	PTypeID varchar(50),
	PUserCode varchar(200),
	PFullName varchar(200),
	ProduceDate varchar(50),
	ValidDate varchar(50),
	GoodsNumber varchar(50)
)

DECLARE @chrSQLCursor varchar(2500)
SET @chrSQLCursor='
INSERT INTO #initTempSerial (Serial,ItemID,IsCombined,ItemName,GoodsCostPrice,PTypeID,PUserCode,PFullName,ProduceDate,ValidDate,GoodsNumber)
SELECT 
	S.Serial AS Serial,
	S.ItemID AS ItemID,
	S.IsCombined AS IsCombined,
	V.itemname AS ItemName,
	S.CostPrice AS GoodsCostPrice,
	S.PtypeID AS PTypeID,
	P.UserCode AS PUserCode,
	P.FullName AS PFullName,
	S.ProduceDate AS ProduceDate,
	S.ValidDate AS ValidDate,
	S.GoodsNumber AS GoodsNumber
	
FROM dbo.gp_initPtypeSerial AS S 
LEFT JOIN dbo.ptype AS P 
ON S.PtypeID=P.typeId
LEFT JOIN dbo.V_Item AS V
ON S.ItemID = V.itemid AND S.Iscombined = V.iscombined
WHERE S.PtypeID=''' + @ptypeID +''' AND S.State=32 AND (S.BTypeID1='''' OR S.BTypeID1 is NULL) AND S.STypeId=''' + @stypeID+''''

IF @serial<>''
SET @chrSQLCursor=@chrSQLCursor+' AND S.Serial LIKE ''%'+@serial+'%''';
IF @itemID<>-1
SET @chrSQLCursor=@chrSQLCursor+' AND S.ItemID='+CAST(@itemID AS varchar)
IF @goodscostprice<>-1
SET @chrSQLCursor=@chrSQLCursor+' AND S.CostPrice='+CAST(@goodscostprice AS varchar)
IF @producedate<>''
SET @chrSQLCursor=@chrSQLCursor+' AND S.ProduceDate='''+@producedate+''''
IF @validdate<>''
SET @chrSQLCursor=@chrSQLCursor+' AND S.ValidDate='''+@validdate+''''
IF @goodsnumber<>''
SET @chrSQLCursor=@chrSQLCursor+' AND S.GoodsNumber='''+@goodsnumber+''''

EXEC(@chrSQLCursor)

SET @intRowCount = @@ROWCOUNT

SET @chrSQLCursor = '
	SELECT	
		 Serial,ItemID,IsCombined,ItemName,GoodsCostPrice,PTypeID,PUserCode,PFullName,ProduceDate,ValidDate,GoodsNumber
	FROM #initTempSerial  
	
	WHERE	AutoID > ' + CAST((@intPageNo-1)*@intPageSize AS varchar) +' AND AutoID <= ' + CAST(@intPageNo*@intPageSize AS varchar);

EXEC(@chrSQLCursor)

DROP TABLE #initTempSerial

-- ********	数据库游标分页 - End	********

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InitSerialQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InitSerialQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
受托委托已发货期初序列号选择
李灏龙
时间：2015年5月19日 15:52:06
描述：委托期初录入序列号时进行序列号选择
*/
CREATE   PROCEDURE Web_InitSerialQuery
(
	@ptypeid	varchar(50),	-- 商品ID
	@stypeid varchar(50),		--分支机构ID
	@type	int,		--140:委托期初 144:受托期初
	@state varchar(max),	--状态
	@serial varchar(50),	--序列号
	@ktypeid varchar(max),	--仓库ID
	@cargoid varchar(max),	--货位ID
	@btypeid varchar(max),	--结算单位ID
	@intPageNo		int,		-- 当前查询的页码
	@intPageSize	int,		-- 每页的显示记录数
	@OperatorID	VARCHAR(50) ,	--操作者ID
	@intRowCount	int = 0 output		-- 返回总记录数
)
-- ********	数据库游标分页 - Start	********
--@encode$--
-- 建立查询临时表 
AS
CREATE TABLE #initTempSerial
(
	[AutoID] int NOT NULL IDENTITY (1, 1),
	[Serial] varchar(50),
	[State] int,
	[StateValue] varchar(50),
	[KtypeID] varchar(50),
	[KFullName] varchar(100),
	[BTypeID] varchar(50),
	[BFullName] varchar(100)
)

--结算单位
CREATE TABLE #Btype (TypeID VARCHAR(50))
INSERT  INTO #Btype
            ( typeid
            )
            SELECT  typeid
            FROM    F_GetAllManagerBaseTypeId(@btypeid, 2, @OperatorID)

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50))
INSERT INTO #Ktype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)
	
--货位
CREATE TABLE #CargoID(TypeID INT)
INSERT  INTO #CargoID(typeid) SELECT  typeid FROM F_GetAllManagerBaseTypeId(@cargoid, 17, @OperatorID)

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(200))
INSERT INTO #Stype(TypeID) SELECT TypeID FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DECLARE @chrSQLCursor varchar(2500)
SET @chrSQLCursor='
					INSERT INTO #initTempSerial (Serial,[State],[KtypeID],[KFullName],[BTypeID],[BFullName])
					SELECT	S.Serial AS Serial,
							S.[State] AS [State],
							S.[KtypeID] AS [KtypeID],
							K.FullName AS [KFullName],'
IF @type=140
	SET @chrSQLCursor+=' S.[BTypeID1] AS [BTypeID],'
IF @type=144
	SET @chrSQLCursor+=' S.[BTypeID2] AS [BTypeID],'

SET @chrSQLCursor+='	 B.FullName AS [BFullName]
					FROM dbo.gp_initPtypeSerial AS S 
					LEFT JOIN dbo.Stock AS K ON S.[KtypeID]=K.typeId 
					LEFT JOIN dbo.btype AS B ON '
IF @type=140
	SET @chrSQLCursor+=' S.BTypeID1=B.typeId '
IF @type=144
	SET @chrSQLCursor+=' S.BTypeID2=B.typeId '
--父类商品也要做统计查看
SET @chrSQLCursor+=' WHERE S.PtypeID Like'''+@ptypeid+'%'' AND S.STypeId IN (SELECT TypeID FROM #Stype) and s.State <> 1 ' 
IF @state<>'' AND @state<>'0'
SET @chrSQLCursor+=' AND S.[State] IN  (select * from dbo.F_split('''+@state+''','','')) '
IF @serial<>''
SET @chrSQLCursor+=' AND S.Serial LIKE ''%'+@serial+'%'' '
IF @ktypeid<>''
SET @chrSQLCursor+=' AND S.[KtypeID] IN (SELECT typeid FROM #Ktype) '
IF @cargoid<>''
SET @chrSQLCursor+=' AND S.[CargoID] IN (SELECT typeid FROM #CargoID) '

IF @type=140
BEGIN
	SET @chrSQLCursor+='AND S.BTypeID1 IN (SELECT typeid FROM #Btype) AND s.State IN (13,32) '
END

IF @type=144
BEGIN
	SET @chrSQLCursor+=' AND S.BTypeID2 IN (SELECT typeid FROM #Btype)'
	
	IF @state<>'' AND @state<>'0'
	BEGIN
		SET @chrSQLCursor+=' AND s.State IN (select * from dbo.F_split('''+@state+''','','')) '
	END
END


EXEC(@chrSQLCursor)

SET @intRowCount = @@ROWCOUNT

SET @chrSQLCursor = '
	SELECT	Serial,
			[State],
			[StateValue],
			[KtypeID],
			[KFullName],
			[BTypeID],
			[BFullName]
	FROM	#initTempSerial  	
	WHERE	AutoID > ' + CAST((@intPageNo-1)*@intPageSize AS varchar) +' AND AutoID <= ' + CAST(@intPageNo*@intPageSize AS varchar);

EXEC(@chrSQLCursor)

DROP TABLE #Btype,#initTempSerial

-- ********	数据库游标分页 - End	********

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InOutStockTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InOutStockTotal]
GO






-- ==========================================================================
--作者：谢吉康   
--日期：2003-11-26 
--描述：判断传入的PTypeID


--修改人：黄飞佳   
--日期：2012-06-12 
--描述：添加多单位计算 浮动单位等
-- ==========================================================================
CREATE         PROCEDURE Web_InOutStockTotal
(
 	@chvOperator 		VARCHAR(100),               	--操作员id
	@Startdate 			varchar(25)='',
	@Enddate 			varchar(25)='',
	@ptypeid 			VARCHAR(8000)='',
	@ktypeid 			VARCHAR(8000)='00000',
	@flag 				VARCHAR(10)='1',			--@flag＝0：线型表；@flag＝1：树型表
	@Button 			INT, 						-- @Button＝0:非合计；合计： @Button=1
	@intBpageNo 		INT, 						--分页仓库的页码
	@intPageRow		    INT,						--仓库条数
	@strShowStock		int=1,						--是否显示为0的仓库 1.显示  0.不显示
	@UserCode			varchar(256)='',
	@FullName			varchar(256)='',
	@EntryCode			varchar(256)='',
	@stypeid			varchar(8000),
    @unitconvert    	VARCHAR(10) ,                --多单位种类
    @billtypes      VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperator IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperator,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
				 
--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) 
SELECT F.TypeId 
FROM F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperator) F 

-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty      NVARCHAR(2000),
        @cQty     NVARCHAR(2000),
        @rQty     NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
		@VarName  NVARCHAR(2000),
        @tmptab   NVARCHAR(2000)
SET 	@UnitName = 'u5.fullname'
IF @unitconvert=0
BEGIN

SELECT  @Qty= 't1.CurNum/isnull(r3.rate,1)',
        @cQty='t1.StockCQty/isnull(r3.rate,1)',
        @rQty='t1.StockRQty/isnull(r3.rate,1)',
        @VarName='u3.fullname'
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p','3,5','3')		
END
IF @unitconvert=1
BEGIN	
SELECT  @Qty= 't1.CurNum/isnull(r2.rate,1)',
        @cQty='t1.StockCQty/isnull(r2.rate,1)',
        @rQty='t1.StockRQty/isnull(r2.rate,1)',
        @VarName='u2.fullname'	
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p','2,5','2')
END
IF @unitconvert=2
BEGIN 
SELECT  @Qty= 't1.CurNum/isnull(r4.rate,1)',
        @cQty='t1.StockCQty/isnull(r4.rate,1)',
        @rQty='t1.StockRQty/isnull(r4.rate,1)',
        @VarName='u4.fullname'
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p','4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty= 't1.CurNum',
        @cQty='t1.StockCQty',
        @rQty='t1.StockRQty',
        @VarName='u1.fullname'	
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p','1,5','1')		
END
----------多单位计算End---------
-------------------------------------------------------------------------------------------------------------------------------

--商品
CREATE TABLE #GetManPTypeId(
	TypeId	varchar(200),
	parid   VARCHAR(200),
	sonnum	INT ,
	fullname VARCHAR(200),
	usercode VARCHAR(200),
	varname VARCHAR(200),
	unitname VARCHAR(200)
)
DECLARE @sql varchar(MAX)
SET @sql ='
	INSERT INTO #GetManPTypeId
	(
		typeid,
		parid,
		sonnum,
		fullname,
		usercode,
		varname,
		unitname
	)
	SELECT  t1.typeid,
			p.parid,
			p.sonnum,
			p.fullname,
			p.usercode,	
			'+@VarName+',
			'+@UnitName+'
	FROM 	F_GetManDetailPType('''+@chvOperator+''') t1 
	INNER JOIN ptype p on t1.typeid= p.typeid '+ @tmptab +' where p.IsService=0 and p.iscombinationproduct = 0'

EXEC (@sql)



CREATE TABLE #GetManPTypeId1(
	TypeId	varchar(200),
	parid   VARCHAR(200),
	sonnum	INT ,
	fullname VARCHAR(200),
	usercode VARCHAR(200),
	varname VARCHAR(200),
	unitname VARCHAR(200)
)



------------------------------------------计算出应查询的仓库-----------------------------------------------
CREATE TABLE #PType
(
	TypeId 	varchar(100)
)

INSERT INTO #PType(TypeId) 
SELECT P.typeId 
FROM PType p
INNER JOIN F_GetManDetailPType(@chvOperator) F ON F.TypeId=P.typeId
WHERE 
	 P.sonnum = 0 
	AND  P.IsService=0 
	AND  P.iscombinationproduct = 0
	AND  P.UserCode LIKE '%'+@UserCode+'%' 
	AND  P.FullName LIKE '%'+@FullName+'%'
	AND ((ISNULL(@EntryCode,'')<>'' AND EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid= P.typeId AND E.EntryCode LIKE '%'+@EntryCode+'%')) OR ISNULL(@EntryCode,'')='')

--根据配置获取数据
CREATE TABLE #TempStock (TypeID VARCHAR(100),FullName VARCHAR(200),STypeId VARCHAR(100))
--仓库临时表用于存储页面展示那些仓库
CREATE TABLE #Stock(TypeID VARCHAR(100),FullName VARCHAR(200),STypeId VARCHAR(100))
--显示仓库数量为0  谢吉康  2004-10-09
IF @strShowStock IN (1,4)
	BEGIN
		INSERT INTO #Stock(TypeID,FullName,STypeId)
		SELECT	
			S.typeId,
			S.FullName,
			S.STypeID 
		FROM Stock  S
		INNER JOIN F_GetManDetailKType(@chvOperator) F ON F.TypeId=S.typeId AND S.sonnum=0
		INNER JOIN #GetSelectSTypeId SS ON SS.typeId=S.STypeID
		ORDER BY S.typeId
	END
ELSE IF @strShowStock = 2		--不显示库存为0的仓库
	BEGIN
		INSERT INTO #Stock(TypeID,FullName,STypeId)
		SELECT 	
			DISTINCT k.TypeID,
			k.FullName,
			k.stypeid 
		FROM Stock K
		INNER JOIN GoodsStocks G ON K.typeId=G.KtypeId AND K.sonnum=0 
		INNER JOIN #PType P ON P.TypeId=G.PtypeId AND G.PTypeID LIKE CASE @PTypeId WHEN '00000' THEN '%' ELSE  @PTypeId + '%' END
		INNER JOIN 	F_GetManDetailKType(@chvOperator) F ON F.TypeId=K.typeId AND k.sonnum=0
		INNER JOIN #GetSelectSTypeId S ON S.TypeId=K.STypeID
		ORDER BY K.TypeID
	END
ELSE
	BEGIN
		INSERT INTO #Stock(TypeID,FullName,STypeId)
		SELECT 	
			DISTINCT k.TypeID,
			k.FullName,
			k.stypeid 
		FROM Stock k
		INNER JOIN InOutStockTable I ON I.KTypeId=K.TypeId AND I.Audited =1  AND K.sonnum=0 AND I.BillDate BETWEEN @Startdate AND @Enddate AND I.PTypeID LIKE CASE @PTypeId WHEN '00000' THEN '%' ELSE  @PTypeId + '%' END
		INNER JOIN #GetSelectSTypeId S ON S.TypeId=K.STypeID
		INNER JOIN F_GetManDetailKType(@chvOperator) F ON F.TypeId=K.typeId
		INNER JOIN #PType P ON P.TypeId=I.PtypeId
		ORDER BY K.TypeID 
	END

INSERT INTO #TempStock(TypeID,FullName,STypeId)
SELECT TOP (@intPageRow)
	TypeID,
	FullName,
	STypeId
FROM #Stock
WHERE TypeID NOT IN(
	SELECT TOP ((@intBpageNo-1)*@intPageRow)
		TypeID
	FROM #Stock 
	ORDER BY TypeID
)
ORDER BY TypeID



------------------------------------------上段程序结束-----------------------------------------------

--建立临时表
DECLARE @PTypeIdMx varchar(100)
IF @PTypeId = '00000'
	SET @PTypeIdMx = '%'
ELSE
	SET @PTypeIdMx = @PTypeId

IF @Ktypeid='' SELECT @Ktypeid='00000'

DECLARE @MySQLx0 varchar(max)

CREATE TABLE #TempInOutStockTable
(
	KTypeId		varchar(100),
	PTypeId		varchar(100),
	StockRQty	 NUMERIC(24, 10) ,
	StockCQty	 NUMERIC(24, 10) ,
	CurNum		 NUMERIC(24, 10) ,
	NQty         NUMERIC(24, 10) 
)


CREATE TABLE #TempInOutStockTable1
(
	KTypeId		varchar(100),
	PTypeId		varchar(100),
	StockRQty	 NUMERIC(24, 10) ,
	StockCQty	 NUMERIC(24, 10) ,
	CurNum		 NUMERIC(24, 10) ,
	NQty         NUMERIC(24, 10) 
)

--徐辉2007-03-06添加出入库汇总表不统计成本调价单
--2014-08-29不晓得为啥 子需求又要统计。不明所以。
SET @MySQLx0 = '
		INSERT INTO #TempInOutStockTable 
		SELECT 	I.KTypeId,
				I.PTypeID,
				SUM(
					CASE
						WHEN I.BillDate>='+char(39)+@StartDate+char(39)+' AND ISNULL(I.Qty,0)>=0 THEN ISNULL(I.Qty,0)
						ELSE 0
					END
				) AS StockRQty,
				SUM(
					CASE
						WHEN I.BillDate>='+char(39)+@StartDate+char(39)+' AND ISNULL(I.Qty,0)<0  THEN ISNULL(ABS(I.Qty),0)
						ELSE 0
					END
				) AS StockCQty,
				ISNULL(SUM(I.Qty),0) AS CurNum,
				sum(I.nqty) AS NQty
		FROM 	InOutStockTable I
		INNER JOIN #GetManPTypeId M ON M.TypeId = I.PTypeId
		INNER JOIN #PType P ON P.TypeId = I.PTypeId
		INNER JOIN #TempStock T ON T.TypeId = I.KTypeId
		WHERE 	BillDate<='+char(39)+@EndDate+char(39)+'
				AND PTypeId LIKE '+char(39)+@PTypeIdMx+'%'+char(39)+'
				AND Audited = 1
				AND Qty<>0
				and ((BillType in (select a from f_split('''+@billtypes+''','','')) and Billtype not in (16,17,21,57,161,160))
				        or
						16  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 16 AND QTY > 0
						OR
						-16  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 16 AND QTY < 0
						or
						17  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 17 AND QTY > 0
						OR
						-17  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 17 AND QTY < 0
						or
						21  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 21 AND QTY > 0
						OR
						-21  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 21 AND QTY < 0
						or
						57 in (select a from f_split('''+@billtypes+''','','')) AND BillType = 57 AND BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE AdPriceType=0 AND BillType=57) AND QTY > 0
						OR
						-57  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 57 AND BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE AdPriceType=0 AND BillType=57) AND QTY < 0
						or
						161  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 161 AND QTY > 0
						OR
						-161  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 161 AND QTY < 0
						or
						160  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 160 AND QTY > 0
						OR
						-160  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 160 AND QTY < 0
						or
						-166  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 166 AND QTY< 0
						OR
						-172  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 172 AND QTY < 0
						
						)
				--AND KTypeId IN (SELECT TypeId FROM #TempStock)
				--AND PTypeId IN (SELECT * FROM #GetManPTypeId)
				--AND PTypeId IN (SELECT TypeId FROM #PType)
		GROUP BY I.KTypeId,I.PTypeId '
--PRINT @MySQLx0
EXEC(@MySQLx0)


SET @MySQLx0 = '
		INSERT INTO #TempInOutStockTable1 
		SELECT 	I.KTypeId,
				I.PTypeID,
				SUM(
					CASE
						WHEN I.BillDate>='+char(39)+@StartDate+char(39)+' AND ISNULL(I.Qty,0)>=0 THEN ISNULL(I.Qty,0)
						ELSE 0
					END
				) AS StockRQty,
				SUM(
					CASE
						WHEN I.BillDate>='+char(39)+@StartDate+char(39)+' AND ISNULL(I.Qty,0)<0  THEN ISNULL(ABS(I.Qty),0)
						ELSE 0
					END
				) AS StockCQty,
				ISNULL(SUM(I.Qty),0) AS CurNum,
				sum(I.nqty) AS NQty
		FROM 	InOutStockTable I
		INNER JOIN #GetManPTypeId M ON M.TypeId = I.PTypeId
		INNER JOIN #PType P ON P.TypeId = I.PTypeId
		INNER JOIN #TempStock T ON T.TypeId = I.KTypeId
		WHERE 	BillDate<='+char(39)+@EndDate+char(39)+'
				AND PTypeId LIKE '+char(39)+@PTypeIdMx+'%'+char(39)+'
				AND Audited = 1
				AND Qty<>0
		GROUP BY I.KTypeId,I.PTypeId '
--PRINT @MySQLx0
EXEC(@MySQLx0)

--缩小的IniGoodsStocks表
INSERT INTO #TempInOutStockTable
SELECT 	a.TypeID AS KtypeID,
		b.PTypeID,
		0 AS StockRQty,
		0 AS StockCQty,
		ISNULL(SUM(b.Qty),0) AS CurNum,
			SUM(c.nqty)  AS NQty 
FROM 	#TempStock a
INNER JOIN	(SELECT SUM(qty)qty,PTypeId,KTypeId FROM IniGoodsStocks GROUP BY  PTypeId,KTypeId) b ON  b.KtypeId = a.TypeId
INNER JOIN	#GetManPTypeId M ON M.TypeId = b.PtypeId
INNER JOIN	#PType P ON P.TypeId = B.PtypeId	
 INNER JOIN(SELECT SUM( NQty)AS nqty,KTypeID,PTypeID FROM dbo.Ini_GOODSSTOCKS_QTY  GROUP BY KTypeID,PTypeID)c	ON b.Ptypeid=c.PTypeID AND b.KtypeId=c.KTypeID 
WHERE 	b.PTypeId LIKE @PTypeIdMx + '%'
		AND b.Qty<>0		
		--AND b.Ptypeid IN (SELECT * FROM #GetManPTypeId)
		--AND b.PTypeId IN (SELECT TypeId FROM #PType)
GROUP BY A.TypeId,B.PTypeId

--缩小的IniCommissionStock表
INSERT INTO #TempInOutStockTable
SELECT 	a.TypeID AS KtypeID,
		b.PTypeID,
		0 AS StockRQty,
		0 AS StockCQty,
		ISNULL(SUM(b.Qty),0) AS CurNum,
		SUM(c.nqty)  AS NQty 
FROM 	#TempStock a
INNER JOIN	(SELECT SUM(qty)qty,Btypeid,Ptypeid,type,KtypeId FROM IniCommissionStock GROUP BY Ptypeid,Btypeid,Type,KtypeId) b ON b.KtypeId = a.TypeID
INNER JOIN	#GetManPTypeId M ON M.TypeId = b.Ptypeid
INNER JOIN	#PType P ON P.TypeId = b.Ptypeid
INNER JOIN(SELECT SUM( NQty)AS nqty,KTypeID,PTypeID FROM dbo.Ini_GOODSSTOCKS_QTY  GROUP BY KTypeID,PTypeID)c	ON b.Ptypeid=c.PTypeID AND b.KtypeId=c.KTypeID 
WHERE 	B.Type = 144
		AND B.PTypeId LIKE @PTypeIdMx + '%'
		AND B.Qty<>0
		--AND b.Ptypeid IN (SELECT * FROM #GetManPTypeId)
		--AND b.PTypeId IN (SELECT TypeId FROM #PType)
GROUP BY A.TypeId,B.PTypeId



CREATE TABLE #temp
(
	ktypeid 	VARCHAR(100),
	ptypeid 	VARCHAR(100),
	nqty         NUMERIC(24, 10) ,
	StockQty 	 NUMERIC(24, 10) ,
	StockRQty 	 NUMERIC(24, 10) ,
	StockCQty 	 NUMERIC(24, 10) 
	
) 

CREATE TABLE #temp3
(
	ktypeid 	VARCHAR(100),
	ptypeid 	VARCHAR(100),
	nqty         NUMERIC(24, 10) ,
	StockQty 	 NUMERIC(24, 10) ,
	StockRQty 	 NUMERIC(24, 10) ,
	StockCQty 	 NUMERIC(24, 10) 
	
)
 
DECLARE @MySQLx1 varchar(max) 

--生成临时表
SET @MySQLx1 ='
	INSERT INTO #temp
	(
		ktypeid,
		ptypeid,
		NQty,
		StockQty,
		StockRQty,
		StockCQty
	
	)
	SELECT 	KTypeID,
			t1.PTypeID,
			SUM(t1.nqty),
			SUM('+@Qty+'),
			SUM('+@rQty+'),
			SUM('+@cQty+')
			
	FROM 	#TempInOutStockTable t1 
	INNER JOIN ptype p on t1.ptypeid= p.typeid '+ @tmptab +'
	WHERE	KTypeId IN (SELECT TypeId FROM #TempStock)
	GROUP BY 
			KTypeId,
			t1.PTypeId '
			

EXEC(@MySQLx1)
SET @MySQLx1 ='
	INSERT INTO #temp3
	(
		ktypeid,
		ptypeid,
		NQty,
		StockQty,
		StockRQty,
		StockCQty
	
	)
	SELECT 	KTypeID,
			t1.PTypeID,
			SUM(t1.nqty),
			SUM('+@Qty+'),
			SUM('+@rQty+'),
			SUM('+@cQty+')
			
	FROM 	#TempInOutStockTable1 t1 
	INNER JOIN ptype p on t1.ptypeid= p.typeid '+ @tmptab +'
	WHERE	KTypeId IN (SELECT TypeId FROM #TempStock)
	GROUP BY 
			KTypeId,
			t1.PTypeId '
			

EXEC(@MySQLx1)

--变量申明

DECLARE @i INT,@j INT,@colscount INT
DECLARE @td VARCHAR(100),@StockName VARCHAR(200)
DECLARE @ReSql VARCHAR(max)
DECLARE @ReSql1 VARCHAR(max)
DECLARE @ReSql2 VARCHAR(max)

DECLARE @ReSql2_1 VARCHAR(max)
SELECT @ReSql2_1 = ''

CREATE TABLE #temp2 
(
	sonnum 		VARCHAR(100), 
	ptypeid 	VARCHAR(100),
	[商品名称] 	VARCHAR(200),
	[浮动数量]   NUMERIC(24, 10) ,
	[合计入库] 	 NUMERIC(24, 10) ,
	[合计出库] 	 NUMERIC(24, 10) ,
	[合计库存] 	 NUMERIC(24, 10) 
)
CREATE TABLE #temp4
(
	sonnum 		VARCHAR(100), 
	ptypeid 	VARCHAR(100),
	[商品名称] 	VARCHAR(200),
	[浮动数量]   NUMERIC(24, 10) ,
	[合计入库] 	 NUMERIC(24, 10) ,
	[合计出库] 	 NUMERIC(24, 10) ,
	[合计库存] 	 NUMERIC(24, 10) 
)


	INSERT INTO #temp4
	(
		ptypeid,
		[合计入库],
		[合计出库],
		[合计库存],
		[浮动数量]
	) 
	SELECT 	ptypeid,
			SUM(ISNULL(stockrqty,0)),
			SUM(ISNULL(stockcqty,0)),
			SUM(ISNULL(stockqty,0)),
			SUM(ISNULL(nqty,0))  
	FROM 	#temp3
	WHERE	(ISNULL(stockrqty,0)<>0 OR ISNULL(stockCqty,0)<>0) --【谢吉康 2005-2-2 为孙海港预留 到时后放开就可以了】
	GROUP BY ptypeid




	INSERT INTO #temp2
	(
		ptypeid,
		
		[合计入库],
		[合计出库],
		[合计库存],
		[浮动数量]
	) 
	SELECT 	ptypeid,
	       
			SUM(ISNULL(stockrqty,0)),
			SUM(ISNULL(stockcqty,0)),
			SUM(ISNULL(stockqty,0)),
			SUM(ISNULL(nqty,0)) 
	FROM 	#temp
	GROUP BY ptypeid

UPDATE 	#temp2 
SET 	[sonnum]=p.sonnum,
		[ptypeid]=p.typeid,
		[商品名称]=p.fullname
FROM 	#temp2 t INNER JOIN ptype p ON(t.ptypeid=p.typeid)
WHERE	P.TypeId IN (SELECT TypeId FROM #PType)



	INSERT INTO #GetManPTypeId1
	(
		typeid,
		parid,
		sonnum,
		fullname,
		usercode,
		varname,
		unitname
	)
	SELECT  t1.typeid,
		t1.parid,
		t1.sonnum,
		t1.fullname,
		t1.usercode,
		t1.varname,
		t1.unitname
	FROM 	#GetManPTypeId t1 
	INNER JOIN #temp4 p on t1.typeid= p.ptypeid  group by t1.typeid,t1.parid,
		t1.sonnum,
		t1.fullname,
		t1.usercode,
		t1.varname,
		t1.unitname



--取得仓库
IF ISNULL(@ktypeid,'00000')='00000'
	DECLARE Ktypecur CURSOR FOR
 		SELECT DISTINCT typeid,FullName FROM #TempStock FOR READ ONLY
ELSE
	BEGIN
		SELECT @sql='
			DECLARE Ktypecur CURSOR  FOR
				SELECT  DISTINCT 
						typeid,
						FullName 
				FROM 	stock 
				WHERE 	sonnum = 0 
						AND typeid<>''00000'' 
						AND  LEFT(typeid,len('''+@ktypeid+'''))='''+@ktypeid+''' FOR READ ONLY '

			EXEC(@sql)
		
			IF @@error<>0 RETURN 2
 	END

	OPEN Ktypecur

	FETCH NEXT FROM Ktypecur INTO @td,@StockName

	SELECT @colscount=0
	SELECT @ReSql='[sonnum],[ptypeid],[商品名称],[unitname],[计量单位],[浮动数量],[合计入库],[合计出库],[合计库存]'
	SELECT @ReSql1='''''AS [sonnum],''HAHA ''AS [ptypeid],''合计''AS [商品名称],'''' AS [unitname] ,'''' AS [计量单位],SUM(ISNULL([浮动数量],0)) AS [本页仓库合计数量],SUM(ISNULL([合计入库],0)) AS [本页仓库合计入库],SUM(ISNULL([合计出库],0)) AS [本页仓库合计出库],SUM(ISNULL([合计库存],0)) AS [本页仓库合计库存]'

	SELECT @ReSql2='SELECT p.sonnum AS [sonnum], p.typeid AS [ptypeid],p.fullname AS [商品名称],p.unitname AS [unitname],p.varname AS [计量单位],SUM(ISNULL([浮动数量],0)) AS [本页仓库合计数量],SUM(ISNULL([合计入库],0)) AS [本页仓库合计入库],SUM(ISNULL([合计出库],0)) AS [本页仓库合计出库],SUM(ISNULL([合计库存],0)) AS [本页仓库合计库存]'
------------------------------------------------------------------// 结果过滤结//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	WHILE @@fetch_status=0
		BEGIN  
			IF @colscount>104 BREAK --如果临时表所有的列的长度之和超过限制..haha!

			SELECT @j=0
			SELECT @i=0
			SELECT @i=CharIndex('['+ @StockName + ']',@ReSql,@i) --检查列名是否存在
			
			WHILE @i>0
				BEGIN
					SELECT @i=CharIndex('['+ @StockName + ']',@ReSql,@i+len('['+ @StockName + ']'))
					SELECT @j=@j+1  
					IF @j>0  SELECT @StockName=@StockName+CONVERT(VARCHAR(4),@j)
				END
			SELECT @sql='ALTER TABLE #temp2 ADD ['+@StockName+'数量]  NUMERIC(24, 10) ,['+@StockName+'入库]  NUMERIC(24, 10) ,['+@StockName+'出库]  NUMERIC(24, 10) ,['+@StockName+'库存]  NUMERIC(24, 10) '
			--print @sql
			EXEC(@sql)
		
			IF @@error<>0 
				BEGIN
					CLOSE Ktypecur
					DEALLOCATE Ktypecur
					RETURN 2
				END
			
			SELECT @ReSql=@ReSql+ ',['+@StockName+'数量],['+@StockName+'入库] ,['+@StockName+'出库],['+@StockName+'库存]'
 
 			SELECT @ReSql1=@ReSql1+ ',SUM(ISNULL(['+@StockName+'数量],0)) AS ['+@StockName+'数量],SUM(ISNULL(['+@StockName+'入库],0)) AS ['+@StockName+'入库] ,SUM(ISNULL(['+@StockName+'出库],0)) AS ['+@StockName+'出库],SUM(ISNULL(['+@StockName+'库存],0)) AS ['+@StockName+'库存]'

			IF LEN(@ReSql2+ ',SUM(ISNULL(['+@StockName+'数量],0)) AS ['+@StockName+'数量] ,SUM(ISNULL(['+@StockName+'入库],0)) AS ['+@StockName+'入库] ,SUM(ISNULL(['+@StockName+'出库],0)) AS ['+@StockName+'出库],SUM(ISNULL(['+@StockName+'库存],0)) AS ['+@StockName+'库存]') > 5500
				SELECT @ReSql2_1 = @ReSql2_1 + ',SUM(ISNULL(['+@StockName+'数量],0)) AS ['+@StockName+'数量] ,SUM(ISNULL(['+@StockName+'入库],0)) AS ['+@StockName+'入库] ,SUM(ISNULL(['+@StockName+'出库],0)) AS ['+@StockName+'出库],SUM(ISNULL(['+@StockName+'库存],0)) AS ['+@StockName+'库存]'
			ELSE
				SELECT @ReSql2 = @ReSql2 + ',SUM(ISNULL(['+@StockName+'数量],0)) AS ['+@StockName+'数量] ,SUM(ISNULL(['+@StockName+'入库],0)) AS ['+@StockName+'入库] ,SUM(ISNULL(['+@StockName+'出库],0)) AS ['+@StockName+'出库],SUM(ISNULL(['+@StockName+'库存],0)) AS ['+@StockName+'库存]'

			SELECT @sql='UPDATE #temp2 SET ['+@StockName+'数量]=t1.NQty,['+@StockName+'入库]=t1.stockrqty,['+@StockName+'出库]=t1.stockcqty,['+@StockName+'库存]=t1.stockqty FROM #temp2 t2 ,#temp t1 WHERE (t2.ptypeid=t1.ptypeid) AND t1.ktypeid='''+@td+''''

			EXEC(@sql)

			IF @@error<>0 
				BEGIN
					CLOSE Ktypecur
					DEALLOCATE Ktypecur
					RETURN 2
				END
					
			FETCH NEXT FROM Ktypecur INTO @td,@StockName
			SELECT @colscount=@colscount+1
		END 
CLOSE Ktypecur
DEALLOCATE Ktypecur

SELECT @ReSql='SELECT '+@ReSql+' FROM #temp2'
SELECT @ReSql1='SELECT '+@ReSql1+' FROM #temp2'
---print @ReSql
--print @ReSql1
DECLARE @XJKSQL VARCHAR(max)

IF @Button=0
	IF @flag=0 
		BEGIN
			IF @ptypeid = '' OR @ptypeid = '00000'	--谢吉康   2003-11-26 判断传入的PTypeID
				SELECT @PTypeID = '%'
				IF @strShowStock=4
				 BEGIN
				SELECT @XJKSQL = @ReSql2 + @ReSql2_1 + 'from #GetManPTypeId1 p left JOIN #temp2 t ON t.ptypeid  LIKE p.typeid +''%''  WHERE p.typeid LIKE '''+@ptypeid+'%'+''' AND p.sonnum=0 AND P.TypeId IN (SELECT TypeId FROM #PType) GROUP BY p.typeid,p.fullname,p.sonnum,P.UserCode,p.unitname,p.varname ORDER BY P.UserCode  '
				END
				ELSE
				 BEGIN
				 SELECT @XJKSQL = @ReSql2 + @ReSql2_1 + 'from #GetManPTypeId p left JOIN #temp2 t ON t.ptypeid  LIKE p.typeid +''%''  WHERE p.typeid LIKE '''+@ptypeid+'%'+''' AND p.sonnum=0 AND P.TypeId IN (SELECT TypeId FROM #PType) GROUP BY p.typeid,p.fullname,p.sonnum,P.UserCode,p.unitname,p.varname ORDER BY P.UserCode  '
				 
				 END
				
				EXEC(@XJKSQL)			
		END
  	ELSE
    	EXEC(@ReSql)
ELSE
	EXEC(@ReSql1)

--删除临时表
DROP TABLE #TempStock,#TempInOutStockTable,#temp,#temp2,#PType,#GetManPTypeId,#GetSelectSTypeId,#GetManPTypeId1,#Stock,#TempInOutStockTable1,#temp3,#temp4

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InOutStockTotalBase]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InOutStockTotalBase]
GO











-- ==========================================================================
/*
	作者：谢吉康
	日期：2006-5-31
	描述：大数据量时的提速

	Web_InOutStockTotalBase '00001','2006-1-1','2006-6-5','','','0','0','1','2'
	
	
	修改人：黄飞佳
	日期：2012-06-09
	描述：添加多单位计算  添加浮动单位及数量
*/
-- ==========================================================================
CREATE       PROCEDURE Web_InOutStockTotalBase
(
	@OperatorID 	varchar(100),               --操作员id
	@Startdate 		varchar(25)='',
	@Enddate 		varchar(25)='',
	@ptypeid 		varchar(MAX)='00000',
	@ktypeid 		varchar(MAX)='00000',    	--无用的参数
	@flag 			varchar(10)='1',			--@flag＝0：线型表；@flag＝1：树型表
	@Button 		int, 						-- @Button＝0:非合计；合计： @Button=1
	@PRINT 			int =0,  					--1打印取值  0页面取值
	@intBpageNo 	int, 						--分页仓库的页码
	@intPageRow		INT,						--仓库条数
	@Stypeid		VARCHAR(MAX),
    @unitconvert    VARCHAR(10),                 --多单位种类
	@billtypes      VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) 
SELECT F.TypeId 
FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) F 
INNER JOIN SType S ON S.TypeId=F.TypeId
INNER JOIN Ac_AccountsPeroid_Stype P ON P.Stypeid=F.TypeId
UNION ALL
SELECT F.TypeId 
FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) F 
INNER JOIN SType S ON S.TypeId=F.TypeId AND S.IsSelfVerify=0
-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty      VARCHAR(2000),
        @cQty     VARCHAR(2000),
        @rQty     VARCHAR(2000),
		@UnitName NVARCHAR(200),
		@VarName  NVARCHAR(200),
        @tmptab   NVARCHAR(2000)
--SET @tmptab=' INNER JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') x ON t1.ptypeID=x.typeID'
SET 	@UnitName = 'u5.fullname'
IF @unitconvert=0
BEGIN

SELECT  @Qty= 't1.CurNum/isnull(r3.rate,1)',
        @cQty='t1.StockCQty/isnull(r3.rate,1)',
        @rQty='t1.StockRQty/isnull(r3.rate,1)',
        @VarName='u3.fullname'
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p','3,5','3')		
END
IF @unitconvert=1
BEGIN	
SELECT  @Qty= 't1.CurNum/isnull(r2.rate,1)',
        @cQty='t1.StockCQty/isnull(r2.rate,1)',
        @rQty='t1.StockRQty/isnull(r2.rate,1)',
        @VarName='u2.fullname'	
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p','2,5','2')
END
IF @unitconvert=2
BEGIN 
SELECT  @Qty= 't1.CurNum/isnull(r4.rate,1)',
        @cQty='t1.StockCQty/isnull(r4.rate,1)',
        @rQty='t1.StockRQty/isnull(r4.rate,1)',
        @VarName='u4.fullname'
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p','4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty= 't1.CurNum',
        @cQty='t1.StockCQty',
        @rQty='t1.StockRQty',
        @VarName='u1.fullname'	
SELECT @tmptab=dbo.F_GetPtypeUnitsAndRates('p','1,5','1')		
END
----------多单位计算End---------
--商品
CREATE TABLE #GetManPTypeId(
	TypeId	varchar(200),
	parid   VARCHAR(200),
	sonnum	INT ,
	fullname VARCHAR(200),
	usercode VARCHAR(200),
	varname VARCHAR(200),
	unitname VARCHAR(200),
	sortid INT
)
--以前商品控制了权限但没有使用，这里加上了计量单位
DECLARE @sql varchar(MAX)
SET @sql ='
	INSERT INTO #GetManPTypeId
	(
		typeid,
		parid,
		sonnum,
		fullname,
		usercode,
		varname,
		unitname,sortid
	)
	SELECT  t1.typeid,
			p.parid,
			p.sonnum,
			p.fullname,
			p.usercode,	
			'+@VarName+',
			'+@UnitName+',
			p.sortid
	FROM 	F_GetManPType('''+@OperatorID+''') t1 
	INNER JOIN ptype p on t1.typeid= p.typeid '+ @tmptab +' where p.IsService=0 and p.iscombinationproduct = 0 '

EXEC (@sql)

-------------------------------------------------------------------------------------------------------------------------------

------------------------------------------计算出应查询的仓库-----------------------------------------------
CREATE TABLE #TempStock (TypeID varchar(100),FullName varchar(200))
DECLARE @SortStockCount int
DECLARE @SortStockAddRec int
DECLARE @TempKTypeID varchar(100)
DECLARE @TempKName varchar(200)
SELECT @SortStockCount=1
SELECT @SortStockAddRec=0


--=====WANG WEI 2010-7-15 优化 将查询仓库的游标执行，换成sql查询 BEGIN ================
DECLARE @SQLSTOCK VARCHAR(500)
CREATE TABLE #Stock(TypeID	VARCHAR(100),fullname VARCHAR(200))
INSERT INTO #Stock
SELECT 	s.TypeID,s.FullName 
FROM 	Stock s
		INNER JOIN #GetSelectSTypeId st ON s.STypeID=st.TypeId
		INNER JOIN F_GetManDetailKType(@OperatorID) sk ON s.typeId=sk.TypeId
WHERE 	s.sonnum=0 
ORDER BY s.TypeID

SET @SQLSTOCK='
INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(@intPageRow AS varchar(50)) + ' 
				Typeid,			
				fullname
	    FROM    #Stock 
	    WHERE  	Typeid NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@intBpageNo-1) * @intPageRow AS varchar(50)) + ' Typeid
	                FROM	#Stock
	                ORDER BY
							TypeID
	            ) 
	    ORDER BY TypeID '
EXEC(@SQLSTOCK)
DROP TABLE #Stock   

------------------------------------------上段程序结束-----------------------------------------------
DECLARE @TableName 		varchar(500),
		@SQLX 			varchar(1000),
		@PTypeIdMx 		varchar(100)
		

IF @ptypeid='' 
	BEGIN
		SET @ptypeid='00000'
		SET @PTypeIdMx = '%'
	END
ELSE
	BEGIN
		SET @PTypeIdMx = @PTypeId
	END

DECLARE @MySQLx0 varchar(MAX)

CREATE TABLE #TempInOutStockTable
(
	KTypeId		varchar(100),
	PTypeId		varchar(100),
	StockRQty	 NUMERIC(24, 10) ,
	StockCQty	 NUMERIC(24, 10) ,
	CurNum		 NUMERIC(24, 10) ,
	NQty         NUMERIC(24, 10)    
)




--徐辉2007-03-06添加出入库汇总表不统计成本调价单
--2014-08-29不晓得为啥 子需求又要统计。不明所以。

---9.7.1又取消了成本调价单。。。。。。。。。。。。。。。。。。。。。。。
SET @MySQLx0 = '
		INSERT INTO #TempInOutStockTable 
		SELECT 	KTypeId,
				PTypeID,
				SUM(
					CASE
						WHEN BillDate>='+char(39)+@StartDate+char(39)+' AND ISNULL(Qty,0)>=0  THEN ISNULL(Qty,0)
						ELSE 0
					END
				) AS StockRQty,
				SUM(
					CASE
						WHEN BillDate>='+char(39)+@StartDate+char(39)+' AND ISNULL(Qty,0)<0  THEN ISNULL(ABS(Qty),0)
						ELSE 0
					END
				) AS StockCQty,
				ISNULL(SUM(Qty),0) AS CurNum,
				sum(nqty) AS NQty
		FROM 	InOutStockTable
		WHERE 	Qty<>0
				AND Audited = 1	
				AND KTypeId IN (SELECT TypeId FROM #TempStock)
				AND BillDate<='+char(39)+@EndDate+char(39)+'				
				AND PTypeId LIKE '+char(39)+@PTypeIdMx+'%'+char(39)+'
				AND PTypeId IN (SELECT typeid FROM #GetManPTypeId)
				and ((BillType in (select a from f_split('''+@billtypes+''','','')) and Billtype not in (16,17,21,161,160))
				        or
						16  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 16 AND QTY > 0
						OR
						-16  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 16 AND QTY < 0
						or
						17  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 17 AND QTY > 0
						OR
						-17  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 17 AND QTY < 0
						or
						21  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 21 AND QTY > 0
						OR
						-21  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 21 AND QTY < 0
						--or
						--57 in (select a from f_split('''+@billtypes+''','','')) AND BillType = 57 AND BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE AdPriceType=0 AND BillType=57) AND QTY > 0
						--OR
						---57  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 57 AND BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE AdPriceType=0 AND BillType=57) AND QTY < 0
						or
						161  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 161 AND QTY > 0
						OR
						-161  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 161 AND QTY < 0
						or
						160  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 160 AND QTY > 0
						OR
						-160  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 160 AND QTY < 0
						or
						-166  in (select a from f_split('''+@billtypes+''','','')) AND BillType = 166 AND QTY< 0
						OR
						-172  in (select a from f_split('''+@billtypes+''','',''))AND BillType = 172 AND QTY < 0
						
						)
				
		GROUP BY KTypeId,PTypeId'
		
		
--PRINT @MySQLx0

EXEC(@MySQLx0)


--缩小的IniGoodsStocks表
INSERT INTO #TempInOutStockTable
SELECT 	a.TypeID AS KtypeID,
		b.PTypeID,
		0 AS StockRQty,
		0 AS StockCQty,
		ISNULL(SUM(b.Qty),0) AS CurNum,
	SUM(c.nqty)  AS NQty 
FROM 	#TempStock a,
	   (SELECT SUM(qty)qty,PTypeId,KTypeId FROM IniGoodsStocks GROUP BY  PTypeId,KTypeId) b,
(SELECT SUM( NQty)AS nqty,KTypeID,PTypeID FROM dbo.Ini_GOODSSTOCKS_QTY  GROUP BY KTypeID,PTypeID)c
WHERE 	a.TypeId=b.KtypeId
      AND b.Ptypeid=c.PTypeID AND b.KtypeId=c.KTypeID 
		AND b.Qty<>0
		AND b.PTypeId LIKE @PTypeIdMx + '%'
		AND b.Ptypeid IN (SELECT TypeId FROM #GetManPTypeId)
GROUP BY A.TypeId,B.PTypeId

--缩小的IniCommissionStock表
INSERT INTO #TempInOutStockTable
SELECT 	a.TypeID AS KtypeID,
		b.PTypeID,
		0 AS StockRQty,
		0 AS StockCQty,
		ISNULL(SUM(b.Qty),0) AS CurNum ,
		SUM(c.nqty)  AS NQty 
FROM 	#TempStock a,
	(SELECT SUM(qty)qty,Btypeid,Ptypeid,type,KtypeId FROM IniCommissionStock GROUP BY Ptypeid,Btypeid,Type,KtypeId) b,
(SELECT SUM( NQty)AS nqty,Btypeid,PTypeID FROM dbo.IniCommissionStock_Qty  GROUP BY Btypeid,PTypeID)c
WHERE 	B.Type = 144
          AND b.Ptypeid=c.PTypeID AND b.Btypeid=c.Btypeid 
		AND B.Qty<>0
		AND a.TypeId = B.KTypeId
		AND B.PTypeId LIKE @PTypeIdMx + '%'
		AND b.Ptypeid IN (SELECT TypeId FROM #GetManPTypeId)
GROUP BY A.TypeId,B.PTypeId


CREATE TABLE #temp
(
	ktypeid 	varchar(50),
	ptypeid 	varchar(50),
    nqty         NUMERIC(24, 10) ,
	StockQty 	 NUMERIC(24, 10) ,
	StockRQty 	 NUMERIC(24, 10) ,
	StockCQty    NUMERIC(24, 10) 

	
) 

DECLARE @MySQLx1 varchar(max) 

--生成临时表
SET @MySQLx1 ='
	INSERT INTO #temp
	(
		ktypeid,
		ptypeid,
		NQty,
		StockQty,
		StockRQty,
		StockCQty
		
	)
	SELECT 	KTypeID,
			t1.PTypeID,
			SUM(t1.nqty),
			SUM('+@Qty+'),
			SUM('+@rQty+'),
			SUM('+@cQty+')	
	FROM 	#TempInOutStockTable t1 
	INNER JOIN ptype p on t1.ptypeid= p.typeid '+ @tmptab +'
	WHERE	KTypeId IN (SELECT TypeId FROM #TempStock)
	GROUP BY 
			KTypeId,
			t1.PTypeId '
			
EXEC(@MySQLx1)

--变量申明

DECLARE @i int,@j int,@colscount int
DECLARE @td varchar(100),@StockName varchar(200)
DECLARE @ReSql varchar(MAX)
DECLARE @ReSql1 varchar(MAX)
DECLARE @ReSql2 varchar(MAX)

-- ////////	2002-10-21 卢春修改(声明新的局部varchar变量) - Start	////////
DECLARE @ReSql2_1 varchar(MAX)
SELECT @ReSql2_1 = ''
-- ////////	2002-10-21 卢春修改(声明新的局部varchar变量) - END	////////




CREATE TABLE #temp2 
(
	sonnum 		varchar(100), 
	ptypeid 	varchar(100),
	[商品名称] 	varchar(200),
	[浮动数量]   NUMERIC(24, 10) ,
	[合计入库] 	 NUMERIC(24, 10) ,
	[合计出库] 	 NUMERIC(24, 10) ,
	[合计库存] 	 NUMERIC(24, 10) 
	
)
INSERT INTO #temp2
SELECT	p.sonnum,
		p.TypeId,
		p.FullName,
	
		SUM(t.nqty),
		SUM(t.stockrqty),
		SUM(t.stockcqty),
		SUM(t.stockqty)
FROM	PType p,
		#temp t
WHERE	t.PTypeId = p.TypeId
GROUP BY 
		p.sonnum,
		p.TypeId,
		p.FullName
		
		
		

--取得仓库
IF @ktypeid='00000'    
	BEGIN
    		DECLARE Ktypecur CURSOR  --得到仓库名称
    		FOR
        	SELECT typeid,FullName FROM #TempStock
    		FOR READ ONLY
	END
ELSE
	BEGIN
-- ////////	2002-10-10 卢春修改(加入"sonnum = 0"条件) - Start	////////
		IF @PRINT=1
			SELECT @sql='DECLARE Ktypecur CURSOR  FOR
	  			SELECT DISTINCT typeid,FullName FROM #TempStock  WHERE LEFT(typeid,len('''+@ktypeid+'''))='''+@ktypeid+''' FOR READ ONLY '
		ELSE
			SELECT @sql='DECLARE Ktypecur CURSOR  FOR
	  			SELECT typeid,FullName FROM #TempStock WHERE LEFT(typeid,len('''+@ktypeid+'''))='''+@ktypeid+''' FOR READ ONLY '
-- ////////	2002-10-10 卢春修改(加入"sonnum = 0"条件) - END		////////
	 	EXEC(@sql)
 		IF @@error<>0 RETURN 2
 	END
OPEN Ktypecur

FETCH NEXT FROM Ktypecur INTO @td,@StockName
SELECT @colscount=0
SELECT @ReSql='[sonnum],[ptypeid],[商品名称],[unitname],[计量单位],[浮动数量],[合计入库],[合计出库],[合计库存]'

IF @PRINT=1 
  SELECT @ReSql2='SELECT p.sonnum AS [sonnum], p.typeid AS [ptypeid],p.fullname AS [商品名称],CASE WHEN p.sonnum>0 THEN NULL
         ELSE p.unitname
    END AS [unitname], CASE WHEN p.sonnum>0 THEN NULL
         ELSE p.varname
    END [计量单位],SUM(ISNULL([浮动数量],0)) AS [本页仓库合计数量],SUM(ISNULL([合计入库],0)) AS [本页仓库合计入库],SUM(ISNULL([合计出库],0)) AS [本页仓库合计出库],SUM(ISNULL([合计库存],0)) AS [本页仓库合计库存]'
ELSE
 SELECT @ReSql2='SELECT p.sonnum AS [sonnum], p.typeid AS [ptypeid],p.fullname AS [商品名称],CASE WHEN p.sonnum>0 THEN NULL
         ELSE p.unitname
    END AS [unitname], CASE WHEN p.sonnum>0 THEN NULL
         ELSE p.varname
    END [计量单位],SUM(ISNULL([浮动数量],0)) AS [本页仓库合计数量],SUM(ISNULL([合计入库],0)) AS [本页仓库合计入库],SUM(ISNULL([合计出库],0)) AS [本页仓库合计出库],SUM(ISNULL([合计库存],0)) AS [本页仓库合计库存]'

WHILE @@fetch_status=0
BEGIN
 IF @colscount>104 BREAK --如果临时表所有的列的长度之和超过限制..haha!
 SELECT @j=0
 SELECT @i=0
 SELECT @i=CharIndex('['+ @StockName + ']',@ReSql,@i) --检查列名是否存在
 WHILE @i>0
 BEGIN
       SELECT @i=CharIndex('['+ @StockName + ']',@ReSql,@i+len('['+ @StockName + ']'))
      SELECT @j=@j+1  
      IF @j>0  SELECT @StockName=@StockName+CONVERT(varchar(4),@j)
 END
 SELECT @sql='ALTER TABLE #temp2 ADD ['+@StockName+'数量]  NUMERIC(24, 10) ,['+@StockName+'入库]  NUMERIC(24, 10) ,['+@StockName+'出库]  NUMERIC(24, 10) ,['+@StockName+'库存]  NUMERIC(24, 10) '

 EXEC(@sql)
 IF @@error<>0 
 BEGIN
    CLOSE Ktypecur
    DEALLOCATE Ktypecur
    RETURN 2
 END
 SELECT @ReSql=@ReSql+ ',['+@StockName+'数量],['+@StockName+'入库] ,['+@StockName+'出库],['+@StockName+'库存]'


IF LEN(@ReSql2+ ',SUM(ISNULL(['+@StockName+'数量],0)) AS ['+@StockName+'数量],SUM(ISNULL(['+@StockName+'入库],0)) AS ['+@StockName+'入库] ,SUM(ISNULL(['+@StockName+'出库],0)) AS ['+@StockName+'出库],SUM(ISNULL(['+@StockName+'库存],0)) AS ['+@StockName+'库存]') > 5500
	SELECT @ReSql2_1 = @ReSql2_1 + ',SUM(ISNULL(['+@StockName+'数量],0)) AS ['+@StockName+'数量],SUM(ISNULL(['+@StockName+'入库],0)) AS ['+@StockName+'入库] ,SUM(ISNULL(['+@StockName+'出库],0)) AS ['+@StockName+'出库],SUM(ISNULL(['+@StockName+'库存],0)) AS ['+@StockName+'库存]'
ELSE
	SELECT @ReSql2 = @ReSql2 + ',SUM(ISNULL(['+@StockName+'数量],0)) AS ['+@StockName+'数量],SUM(ISNULL(['+@StockName+'入库],0)) AS ['+@StockName+'入库] ,SUM(ISNULL(['+@StockName+'出库],0)) AS ['+@StockName+'出库],SUM(ISNULL(['+@StockName+'库存],0)) AS ['+@StockName+'库存]'

SELECT @sql='UPDATE #temp2 SET ['+@StockName+'数量]=t1.NQty,['+@StockName+'入库]=StockRQty,['+@StockName+'出库]=StockCQty,['+@StockName+'库存]=StockQty FROM #temp2 t2 ,#temp t1  WHERE (t2.ptypeid=t1.ptypeid) AND t1.ktypeid='''+@td+''''



EXEC(@sql)
IF @@error<>0 
	BEGIN
	    CLOSE Ktypecur
	    DEALLOCATE Ktypecur
	    RETURN 2
	END

	FETCH NEXT FROM Ktypecur INTO @td,@StockName
	SELECT @colscount=@colscount+1
END 

CLOSE Ktypecur
DEALLOCATE Ktypecur



IF @PRINT=1
   SELECT @ReSql='SELECT '+@ReSql+' FROM #temp2 WHERE AND ptypeid LIKE '''+@ptypeid+'%'''
ELSE
   SELECT @ReSql='SELECT '+@ReSql+' FROM #temp2 WHERE AND ptypeid LIKE '''+@ptypeid+'%'''

IF @flag=0 
	BEGIN	    
		--PRINT(@ReSql2 + @ReSql2_1 + ' FROM #GetManPTypeId p left JOIN #temp2 t ON t.ptypeid  LIKE p.typeid +''%'' WHERE p.parid='''+@ptypeid+''' GROUP BY p.typeid,p.fullname,p.sonnum,P.UserCode,p.sortid ORDER BY P.sortid')
		EXEC(@ReSql2 + @ReSql2_1 + ' FROM #GetManPTypeId p left JOIN #temp2 t ON t.ptypeid  LIKE p.typeid +''%'' WHERE p.parid='''+@ptypeid+''' GROUP BY p.sonnum,p.typeid,p.sortid, p.fullname,CASE WHEN p.sonnum>0 THEN NULL
         ELSE p.varname
    END,p.UserCode,CASE WHEN p.sonnum>0 THEN NULL
         ELSE p.unitname
    END ORDER BY P.sortid,P.typeid')	
  	END
ELSE
  	BEGIN
        --PRINT(@ReSql)
        
        EXEC(@ReSql)
  	END


-- 删除临时表
DROP TABLE #TempStock,#TempInOutStockTable,#temp,#temp2,#GetManPTypeId,#GetSelectSTypeId




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--SELECT * FROM dbo.sqlLog ORDER BY id DESC
--exec Web_InOutStockTotalBase @OperatorID='00001',@Startdate='2011-12-25',@Enddate='2012-06-20',@ptypeid='',@ktypeid='',@flag='0',@Button='0',@PRINT='0',@intBpageNo=1,@Stypeid='00001',@unitconvert='1'



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InOutStockTotalCalStock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InOutStockTotalCalStock]
GO






/*
	作者：谢吉康
	日期：2009-06-15
	描述：出入库汇总表显示仓库个数
*/
CREATE PROCEDURE Web_InOutStockTotalCalStock
(
	@chvOperator		varchar(200),
	@Startdate 			varchar(25)='',
	@Enddate 			varchar(25)='',	
	@Ptypeid			varchar(200),
	@strShowStock	int=1,						--是否显示为0的仓库 1.显示  0.不显示
	@UserCode			varchar(256)='',
	@FullName			varchar(256)='',
	@EntryCode		varchar(256)='',
	@ncount				int		output,
	@stypeid		VARCHAR(8000)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperator IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperator,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------				 

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId)
SELECT F.TypeId 
FROM F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperator) F 
INNER JOIN SType S ON S.TypeId=F.TypeId
INNER JOIN Ac_AccountsPeroid_Stype P ON P.Stypeid=F.TypeId
UNION ALL
SELECT F.TypeId 
FROM F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperator) F 
INNER JOIN SType S ON S.TypeId=F.TypeId AND S.IsSelfVerify=0

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@chvOperator)
					
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT * FROM F_GetManDetailPType(@chvOperator)

--
CREATE TABLE #GetManDetailKType(TypeId	varchar(100))
INSERT INTO #GetManDetailKType(TypeId) SELECT * FROM F_GetManDetailKType(@chvOperator)

CREATE TABLE #PType
(
	TypeId 	varchar(100)
)
INSERT INTO #PType(TypeId) 
SELECT P.typeId 
FROM PType p
INNER JOIN F_GetManDetailPType(@chvOperator) F ON F.TypeId=P.typeId
WHERE 
	P.sonnum = 0 
	AND  P.UserCode LIKE '%'+@UserCode+'%' 
	AND  P.FullName LIKE '%'+@FullName+'%'
	AND ((ISNULL(@EntryCode,'')<>'' AND EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid= P.typeId AND E.EntryCode LIKE '%'+@EntryCode+'%')) OR ISNULL(@EntryCode,'')='')

IF @strShowStock IN (1,4)
	SELECT 	@ncount = count(s.typeId)
	FROM	Stock s
	INNER JOIN	#GetSelectSTypeId ss ON s.STypeID=ss.TypeId
	INNER JOIN  #GetManKTypeId k ON s.typeId=k.TypeId
	WHERE sonnum=0
ELSE IF @strShowStock = 2		--不显示库存为0的仓库
	SELECT 	@ncount = count(DISTINCT k.TypeID)
	FROM 	Stock k
			INNER JOIN GoodsStocks G  ON K.TypeId=G.KTypeId 
			INNER JOIN #GetManKTypeId mk ON k.typeId=mk.TypeId
			INNER JOIN #GetSelectSTypeId ss ON k.STypeID=ss.TypeId
			INNER JOIN #PType p ON p.TypeId=G.PtypeId
	WHERE 	K.sonnum=0 
			AND G.PTypeID LIKE 
				CASE @PTypeId
					WHEN '00000' THEN '%'
					ELSE  @PTypeId + '%'
				END
ELSE
	SELECT 	@ncount = count(DISTINCT k.TypeID)
	FROM 	Stock k
	INNER JOIN InOutStockTable I ON I.KtypeId = k.typeId
	INNER JOIN #GetManDetailKType M ON M.TypeId = K.typeId
	WHERE 	I.BillDate>=@Startdate
			AND I.BillDate<=@EndDate
			AND I.PTypeId IN (SELECT TypeId FROM #PType)
			AND K.sonnum=0  
			AND I.Audited =1 
			AND k.STypeID IN(SELECT typeId FROM #GetSelectSTypeId)
			AND I.PTypeID LIKE 
				CASE @PTypeId
					WHEN '00000' THEN '%'
					ELSE  @PTypeId + '%'
				END


DROP TABLE #PType,#GetManPTypeId,#GetSelectSTypeId,#GetManKTypeId,#GetManDetailKType






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InOutStockTotalTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InOutStockTotalTotal]
GO
















-- ==========================================================================
/*
	作者：谢吉康
	日期：2006-5-31
	描述：大数据量时的提速

	Web_InOutStockTotalTotal '00001','2006-1-1','2006-6-1','','','1',1
*/
-- ==========================================================================
CREATE        PROCEDURE Web_InOutStockTotalTotal
 (
	@chvOperator 		varchar(100),               --操作员id
	@Startdate 			smalldatetime='',
	@Enddate 			smalldatetime='',
	@ptypeid 			varchar(100)='',
	@ktypeid 			varchar(100)='00000',  		--无用的参数
	@StockPageNo 		int,  						--分仓库显示的页码
	@Flag 				int, 						--0 线性表 1 树型表
	@isShowZeroStock	int=1						--是否显示为0的仓库 1.显示  0.不显示
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperator IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @chvOperator,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

------------------------------------------计算出应查询的仓库-----------------------------------------------
CREATE TABLE #TempStock (TypeID varchar(100),FullName varchar(66))
DECLARE @SortStockCount int
DECLARE @SortStockAddRec int
DECLARE @TempKTypeID varchar(100)
DECLARE @TempKName varchar(66)
SELECT @SortStockCount=1
SELECT @SortStockAddRec=0
--=======================================谢吉康   2003-07-11   选择出10个仓库===========================
IF @isShowZeroStock = 1
	BEGIN
		DECLARE SortStock_cursor CURSOR FOR 
			SELECT	TypeID,
					FullName 
			FROM	Stock 
			WHERE	TypeID LIKE @MKTypeID+'%' 
					AND sonnum=0 
			ORDER BY TypeID FOR READ ONLY
		OPEN SortStock_cursor
		FETCH NEXT FROM SortStock_cursor INTO @TempKTypeID,@TempKName
		WHILE @@FETCH_STATUS =0
		BEGIN
		     IF @SortStockCount>(@StockPageNo-1)*10
		     BEGIN
		            INSERT INTO #TempStock (TypeID,FullName) VALUES (@TempKTypeID,@TempKName)
		            SELECT @SortStockAddRec = @SortStockAddRec + 1
		     END
		     IF  @SortStockAddRec>=10 BREAK
		     FETCH NEXT FROM SortStock_cursor INTO @TempKTypeID,@TempKName
		     SELECT @SortStockCount = @SortStockCount + 1
		END     
		CLOSE SortStock_cursor
		DEALLOCATE SortStock_cursor
	END
ELSE
	IF @isShowZeroStock = 2		--不显示库存为0的仓库
		BEGIN
			DECLARE SortStock_cursor CURSOR FOR
				SELECT 	DISTINCT k.TypeID,
						k.FullName 
				FROM 	Stock k,						
						GoodsStocks G 
				WHERE 	K.TypeId=G.KTypeId 
						AND K.TypeID LIKE @MKTypeID+'%' 
						AND K.sonnum=0 
						AND G.PTypeID LIKE 
							CASE @PTypeId
								WHEN '00000' THEN '%'
								ELSE  @PTypeId + '%'
							END
				ORDER BY K.TypeID FOR READ ONLY
	
			OPEN SortStock_cursor
			FETCH NEXT FROM SortStock_cursor INTO @TempKTypeID,@TempKName
			WHILE @@FETCH_STATUS =0
				BEGIN
				     IF @SortStockCount>(@StockPageNo-1)*10
				     BEGIN
				            INSERT INTO #TempStock (TypeID,FullName) VALUES (@TempKTypeID,@TempKName)
				            SELECT @SortStockAddRec = @SortStockAddRec + 1
				     END
				     IF  @SortStockAddRec>=10 BREAK
				     FETCH NEXT FROM SortStock_cursor INTO @TempKTypeID,@TempKName
				     SELECT @SortStockCount = @SortStockCount + 1
				END     
			CLOSE SortStock_cursor
			DEALLOCATE SortStock_cursor
		END
	ELSE
		BEGIN
			DECLARE SortStock_cursor CURSOR FOR 
				SELECT	DISTINCT
						k.TypeID,
						k.FullName 
				FROM	Stock k,
						InOutStockTable I
				WHERE	k.TypeId = I.KTypeId
						AND I.Audited = 1

						AND k.TypeID LIKE @MKTypeID+'%' 
						AND I.BillDate>=@Startdate
						AND I.BillDate<=@EndDate
						AND k.sonnum=0 
						AND I.PTypeID LIKE 
							CASE @PTypeId
								WHEN '00000' THEN '%'
								ELSE  @PTypeId + '%'
							END
				ORDER BY k.TypeID FOR READ ONLY
			OPEN SortStock_cursor
			FETCH NEXT FROM SortStock_cursor INTO @TempKTypeID,@TempKName
			WHILE @@FETCH_STATUS =0
			BEGIN
			     IF @SortStockCount>(@StockPageNo-1)*10
			     BEGIN
			            INSERT INTO #TempStock (TypeID,FullName) VALUES (@TempKTypeID,@TempKName)
			            SELECT @SortStockAddRec = @SortStockAddRec + 1
			     END
			     IF  @SortStockAddRec>=10 BREAK
			     FETCH NEXT FROM SortStock_cursor INTO @TempKTypeID,@TempKName
			     SELECT @SortStockCount = @SortStockCount + 1
			END     
			CLOSE SortStock_cursor
			DEALLOCATE SortStock_cursor
		END

--=======================================谢吉康   2003-07-11   选择出10个仓库===========================


------------------------------------------上段程序结束-----------------------------------------------

CREATE TABLE #PType(PTypeId varchar(50))

DECLARE @PTypeIdMx varchar(100)

--建立临时表
IF @ptypeid = ''
	BEGIN 
		SET @ptypeid = '00000'
		SET @PTypeIdMx = '%'
	END
ELSE
	BEGIN
		SET @PTypeIdMx = @PTypeID
	END

IF @isShowZeroStock = 4
	INSERT INTO #PType(PTypeId) SELECT PTypeId FROM InOutStockTable WHERE BillDate>=@StartDate AND BillDate<=@EndDate AND Audited = 1
ELSE
	INSERT INTO #PType(PTypeId) SELECT TypeId FROM PType WHERE SonNum = 0


--InOutStockTable缩小表
SELECT	b.BillDate,
		B.KTypeID,
		B.PTypeId,
		ISNULL(b.Qty,0) AS Qty 
INTO	#InOutStockTable  
FROM	InOutStockTable b,
		#TempStock a
WHERE	b.audited = 1
		AND b.KTypeId <> '10000'
		AND b.Qty<>0
		AND a.typeid=b.ktypeid
		AND b.BillDate<=@EndDate		
		AND b.ptypeid LIKE @PTypeIdMx+'%'
		AND b.Ptypeid LIKE @MPtypeid+'%'


--期初缩小表
SELECT	a.TypeID AS KtypeID,
		ISNULL(SUM(b.Qty),0) AS Qty 
INTO	#IniGoodsStocks 
FROM	#TempStock a,
		IniGoodsStocks b
WHERE	a.typeid=b.ktypeid
		AND b.ptypeid LIKE @PTypeIdMx+'%'
		AND b.Ptypeid LIKE @MPtypeid+'%' 
GROUP BY a.TypeID
 
--生成出入库临时表
SELECT 	B.KTypeID,
		SUM(ISNULL(CASE WHEN ISNULL(b.Qty,0)>=0 THEN b.qty END,0)) AS StockRQty,
		SUM(ISNULL(CASE WHEN ISNULL(b.Qty,0)<0 THEN -1*b.qty END,0)) AS StockCQty
INTO 	#BETotalIO
FROM 	#InOutStockTable b
WHERE 	b.BillDate>=@startdate
GROUP BY B.KTypeID


--生成到现在为止的出入库合计临时表
SELECT	B.KTypeID,
		SUM(b.Qty) AS StockCRQty 
INTO	#ToNowTotalIO
FROM	#InOutStockTable b
GROUP BY B.KTypeId

SELECT	a.TypeID,
		ISNULL(b.StockRQty,0) AS StockRQty,
		ISNULL(b.StockCQty,0) AS StockCQty,
		ISNULL(d.Qty,0)+ISNULL(c.StockCRQty,0) AS StockQty
INTO #LastTable
FROM #TempStock a
LEFT JOIN #BETotalIO b ON (a.TypeID=b.KTypeID)
LEFT JOIN #ToNowTotalIO c ON (a.TypeID=c.KTypeID)
LEFT JOIN #IniGoodsStocks d ON (a.TypeID=d.KTypeID)



DECLARE 	@AllTotalRQty 	 NUMERIC(24, 10) 
DECLARE 	@AllTotalCQty 	 NUMERIC(24, 10) 
DECLARE 	@AllTotalCRQty 	 NUMERIC(24, 10) 
DECLARE 	@AllTotalQty  	 NUMERIC(24, 10) 
DECLARE  	@AllTotalFQty 	 NUMERIC(24, 10) 
DECLARE		@AllTotalSQty	 NUMERIC(24, 10) 

IF @flag='0' --线性表，所有仓库合计
	BEGIN
		SELECT 	@AllTotalCRQty=ISNULL(SUM(Qty),0) 
		FROM	#InOutStockTable 
		WHERE 	BillDate<=@EndDate 
				AND KTypeID LIKE @MKTypeID+'%' 				
				AND PTypeId IN (SELECT PTypeId FROM #PType)


		SELECT 	@AllTotalRQty=ISNULL(SUM(Qty),0) 
		FROM	#InOutStockTable 
		WHERE	Qty>0 
				AND BillDate>=@startdate 				
				AND KTypeID LIKE @MKTypeID+'%' 
				AND PTypeId IN (SELECT PTypeId FROM #PType)
	
		SELECT 	@AllTotalCQty=ISNULL(SUM(Qty),0) 
		FROM	#InOutStockTable 
		WHERE	Qty<0 
				AND BillDate>=@startdate 
				AND KTypeID LIKE @MKTypeID+'%' 				
				AND PTypeId IN (SELECT PTypeId FROM #PType)
	
		SELECT 	@AllTotalFQty=ISNULL(SUM(Qty),0) 
		FROM 	IniGoodsStocks 
		WHERE 	ptypeid LIKE @PTypeId+'%'
				AND Ptypeid LIKE @MPtypeid+'%' 

				AND KTypeID LIKE @MKTypeID+'%'
				AND PTypeId IN (SELECT PTypeId FROM #PType)

		SET	@AllTotalSQty = 0
	END
ELSE  --树型表，本页仓库合计
	BEGIN
		SELECT	@AllTotalCRQty=ISNULL(SUM(Qty),0) 
		FROM	#InOutStockTable 	
	
		SELECT 	@AllTotalRQty=ISNULL(SUM(Qty),0) 
		FROM 	#InOutStockTable 
		WHERE	Qty>0 
				AND BillDate>=@startdate 
	
		SELECT 	@AllTotalCQty=ISNULL(SUM(Qty),0) 
		FROM 	#InOutStockTable 
		WHERE 	Qty>0 
				AND BillDate>=@startdate 
	
		SELECT 	@AllTotalFQty=ISNULL(SUM(Qty),0) 
		FROM 	#IniGoodsStocks 		

		SET	@AllTotalSQty = 0
	END

	SELECT @AllTotalQty = @AllTotalFQty + @AllTotalCRQty + @AllTotalSQty
	
	DECLARE  @TotalStockCount int
	DECLARE  @TotalStockPages int
	DECLARE  @Cur_KTypeId	  varchar(50)

	SET @TotalStockCount = 0

IF @isShowZeroStock = 1
	SELECT 	@TotalStockCount = COUNT(*) 
	FROM 	Stock 
	WHERE 	Sonnum=0 
			AND TypeID LIKE @MKTypeID+'%'
ELSE
	IF @isShowZeroStock = 2
		BEGIN
			DECLARE Temp_Cursor CURSOR FOR
				SELECT 	DISTINCT k.TypeId 
				FROM 	Stock k,
						GoodsStocks I
				WHERE 	K.TypeId = I.KTypeId						
						AND K.Sonnum=0 
						AND I.PTypeId LIKE 
							CASE
								WHEN @ptypeid ='00000' THEN '%'
								ELSE @PTypeId + '%'
							END
						AND K.TypeID LIKE @MKTypeID+'%'
			
			OPEN Temp_Cursor
	
			FETCH NEXT FROM Temp_Cursor INTO @Cur_KTypeId
	
			WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @TotalStockCount = @TotalStockCount + 1
					FETCH NEXT FROM Temp_Cursor INTO @Cur_KTypeId
				END
	
			CLOSE Temp_Cursor
			DEALLOCATE Temp_Cursor
		END
	ELSE
		BEGIN
			DECLARE Tmp_Cursor CURSOR FOR
				SELECT 	DISTINCT k.TypeId 
				FROM 	Stock k,
						InOutStockTable I
				WHERE 	K.TypeId = I.KTypeId
						AND I.Audited = 1
						AND K.Sonnum=0 
						AND I.PTypeId LIKE 
							CASE
								WHEN @ptypeid ='00000' THEN '%'
								ELSE @PTypeId + '%'
							END
						AND K.TypeID LIKE @MKTypeID+'%'
			
			OPEN Tmp_Cursor
	
			FETCH NEXT FROM Tmp_Cursor INTO @Cur_KTypeId
	
			WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @TotalStockCount = @TotalStockCount + 1
					FETCH NEXT FROM Tmp_Cursor INTO @Cur_KTypeId
				END
	
			CLOSE Tmp_Cursor
			DEALLOCATE Tmp_Cursor		
		END

	IF @TotalStockCount%10<>0 
 		SELECT @TotalStockPages=@TotalStockCount/10+1
	ELSE
 		SELECT @TotalStockPages=@TotalStockCount/10

	--变量申明
	DECLARE @td varchar(100),@StockName varchar(60)
	DECLARE @StockRQty  NUMERIC(24, 10) ,@StockCQty  NUMERIC(24, 10) ,@StockQty  NUMERIC(24, 10) 
	DECLARE @ReSql varchar(8000)
	

	DECLARE Ktypecur CURSOR FOR
	    SELECT typeid,FullName FROM #TempStock
	FOR READ ONLY
	OPEN Ktypecur
	FETCH NEXT FROM Ktypecur INTO @td,@StockName
	
	SELECT @ReSql=' SELECT '''' AS [Sonnum],
				''HAHA '' AS [ptypeid],
				''合计'' AS [商品名称],
				' + CONVERT(varchar(20),@TotalStockPages) + ' AS [总仓库页码],
				' + CONVERT(varchar(20),ABS(@AllTotalRQty)) + ' AS [合计入库],
				' + CONVERT(varchar(20),ABS(@AllTotalCQty)) + ' AS [合计出库],
				' + CONVERT(varchar(20),@AllTotalQty) +' AS [合计库存] '
	WHILE @@fetch_status=0
	BEGIN
		SELECT	@StockRQty=ABS(StockRQty),
				@StockCQty=ABS(StockCQty),
				@StockQty=StockQty 
		FROM	#LastTable 
		WHERE	TypeID=@td

		SELECT 	@ReSql = @ReSql +',
			'+CONVERT(varchar(20),@StockRQty) +' AS ['+@StockName+'入库],
			'+CONVERT(varchar(20),@StockCQty) +' AS ['+@StockName+'出库],
			'+CONVERT(varchar(20),@StockQty) +' AS ['+@StockName+'库存]'
	 	FETCH NEXT FROM Ktypecur INTO @td,@StockName
	END 
	CLOSE Ktypecur
	DEALLOCATE Ktypecur

--PRINT(@ReSQL)
EXEC(@ReSQL)


DROP TABLE #PType
































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InterFaceAccountQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InterFaceAccountQuery]
GO



-- ========================================================================
-- 功能说明：	“基本信息选择树型表” 查询结果集返回
-- 作    者：	卢  春



-- 功能说明：合并凭证
-- 作    者：周   勇
-- 时    间：2004-04-12  

-- 作者: 滕强                       
-- 时间: 2004-6-24
-- 修改：#-01
-- 描述: 增加凭证字内型,并支持客户根据不同的需求变化凭证字

-- 作者: 谢吉康                       
-- 时间: 2004-10-27
-- 描述: 修改节点经手人无法查处数据的错误

--修改人：毛欣蓉
--时间：2010-6-21
--描述：添加维修类单据的调阅权限
--时间：2010-7-23
--描述：有全部仓库的管理权限时，增加对仓库为全部仓库的单据的调用权限
--时间：2010-10-14
--描述：添加对汽配新加单据的调阅权限，调整查询条件（查询出洗车结算单）
-- 2013-08-02 周华 添加 零售退货单据 调阅权限
--时间：2014-08-18 12:05:07.853 敏捷817搬迁 唐韬
--描述：成本费用管理-财务接口】下【合并凭证】功能，在原来【单据类型相同、科目相同】的合并基础上，增加【结算单位】维度
-- ========================================================================
CREATE     PROCEDURE Web_InterFaceAccountQuery
(
	@OperatorID				varchar(50),
	@chvSoftType			varchar(50),			-- 1. 财务软件标识
	@chvStartDate			varchar(30)	= '',		-- 2. 筛选开始日期
	@chvEndDate				varchar(30)	= '',		-- 3. 筛选结束日期
	@chvETypename			varchar(1550)	= '',		-- 4. 经手人 ID
	@chvBTypeName			varchar(2010)	= '',		-- 5. 往来单位名称
	@chvKTypeName			varchar(2010)	= '',		-- 6. 仓库名称	
	@chvBillType			varchar(50)	= '',		-- 7. 单据类型
	@chvComment				varchar(300)	= '',		-- 8. 摘要	
	@chvExplain				varchar(300)	= '',		-- 9. 说明
	@chvBillNumberID		int,				--11.单据编号
	@chrJudgeFlag			int,          			--判断不同的凭证类型
	@chvIfOutPutData		char(1),			-- 12. 是否导出数据；0：不导出；1：导出
	@flag					char(1),		-- 13. 是否为合并凭证 0：不是；1是
	--@chrVoucherFlag		char(1) ,		-- 12. 不同的凭证字选项
	@chvPZ					char(1) ='1',		-- 1 导出全部 0 非全部
	@stypeid				VARCHAR(MAX)
)	

--@encode$--
AS
	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

DECLARE @proinfo int
SELECT @proinfo=subvalue FROM sysdata where subname='proinfo'


--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	


	DECLARE	@chvJi	varchar(50)
	-- 游标相关变量
	DECLARE @intBillNumberID int
	DECLARE @chvBillDate datetime
	DECLARE @chvBillCode varchar(200)
	--DECLARE @chvBillType int
	DECLARE @chvATypeID varchar(50)
	DECLARE @chvATypeUserCode varchar(200)
	DECLARE @chvATypeFullName varchar(200)
	DECLARE @chvSubjectCode varchar(100)
	DECLARE @intTotal_J  NUMERIC(24, 10) 
	DECLARE @intTotal_D  NUMERIC(24, 10) 
	DECLARE	@chvCountOut  NUMERIC(24, 10) 
	DECLARE	@chvCountIn  NUMERIC(24, 10) 
	DECLARE @chvETypeFullName varchar(200)
	DECLARE @chvBTypeFullName varchar(200)
	DECLARE @chvBTypeFullName1 varchar(200)
	DECLARE @chvKTypeFullName varchar(200)
	DECLARE @BillCode int
	DECLARE	@intFlag	int
    	DECLARE	@chvVoucherChar  varchar(10)
	DECLARE @chvChecke varchar(200)
	DECLARE @chvCheckName varchar(200)
	DECLARE @chvBtypeID varchar(200)
	DECLARE @chvIfout char(1)
	DECLARE @stypeidTemp VARCHAR(100)
	DECLARE @btypeidTemp VARCHAR(100)


-- -- 游标相关变量 +TEMP "AN"   --当系统采购，销售采用税率格式时，系统的科目会出现不平的现象，这是因为本系统没有应交税金这个科目
--   在此种情况下，科目的差额作为应交税金处理  以下变量缓存临时的应插入应交税金记录时其余相关的字段
	DECLARE @intBillNumberID_AN int
	DECLARE @chvBillDate_AN datetime
	DECLARE @chvBillCode_AN varchar(200)
	DECLARE @chvBillType_AN int
	DECLARE @chvATypeID_AN varchar(50)
	DECLARE @chvATypeUserCode_AN varchar(200)
	DECLARE @chvATypeFullName_AN varchar(200)
	DECLARE @chvSubjectCode_AN varchar(100)
	DECLARE @intTotal_J_AN  NUMERIC(24, 10) 
	DECLARE @intTotal_D_AN  NUMERIC(24, 10) 
	DECLARE	@chvCountOut_AN  NUMERIC(24, 10) 
	DECLARE	@chvCountIn_AN  NUMERIC(24, 10) 
	DECLARE @chvETypeFullName_AN varchar(200)
	DECLARE @chvBTypeFullName_AN varchar(200)
	DECLARE @chvBTypeFullName1_AN varchar(200)
	DECLARE @chvKTypeFullName_AN varchar(200)
	DECLARE @BillCode_AN int
	DECLARE	@intFlag_AN	int
    DECLARE	@chvVoucherChar_AN  varchar(10)
	DECLARE	@chvExplain_AN  varchar(300)
	DECLARE	@chvComment_AN  varchar(300)
	DECLARE @chvChecke_AN varchar(200)
	DECLARE @chvCheckName_AN varchar(200)
	DECLARE @chvBtypeID_AN varchar(200)
	DECLARE @chvIfout_AN char(1)
	DECLARE @stypeidTemp_AN VARCHAR(100)
	DECLARE @btypeidTemp_AN VARCHAR(100)


    -- 库存商品总值合计
	DECLARE @intTotal_KC_AN  NUMERIC(24, 10) 


CREATE TABLE #Btype (TypeID varchar(50),usercode varchar(200),fullname varchar(200))
CREATE TABLE #Etype (TypeID varchar(50),usercode varchar(200),fullname varchar(200))
CREATE TABLE #Ktype (TypeID varchar(50),usercode varchar(200),fullname varchar(200))
CREATE TABLE #Dtype (TypeID varchar(50))

IF @chvBTypeName=''
BEGIN
	INSERT INTO #Btype(typeid,usercode,fullname) 
	select b.typeId,b.UserCode,b.FullName 
	from btype b
	inner join F_GetManDetailBType(@OperatorID) a on a.TypeId = b.typeId

	INSERT INTO #Btype(typeid,usercode,fullname) select '','',''
END
ELSE
	INSERT INTO #Btype(typeid,usercode,fullname) 
	select b.typeId,b.UserCode,b.FullName 
	from btype b
	inner join F_GetManDetailBType(@OperatorID) a on a.TypeId = b.typeId
	inner join dbo.F_GetAllBaseTypeIdFromUOrFLike(@chvBTypeName,2) c on c.TypeId = b.typeId
	
IF @chvETypename=''
	INSERT INTO #Etype(typeid,usercode,fullname) 
	select e.typeId,e.UserCode,e.FullName 
	from Employee e
	inner join F_GetManDetailEType(@OperatorID) f on f.TypeId = e.typeId
ELSE
	INSERT INTO #Etype(typeid,usercode,fullname) 
	SELECT	E.typeId,E.UserCode,E.FullName 
	FROM	Employee E
	INNER JOIN (
			SELECT	F.TypeId
			FROM	F_GetManDetailEType(@OperatorID) F
			INNER JOIN dbo.f_split(@chvETypename,',') T ON F.TypeId LIKE ''+T.a+''+ '%'
		) T ON T.typeid = E.typeId

IF @chvKTypeName=''
BEGIN
	INSERT INTO #Ktype(typeid,usercode,fullname) 
	SELECT	S.typeid,S.UserCode,S.FullName 
	FROM	Stock S
	INNER JOIN F_GetManDetailKType(@OperatorID) F ON F.TypeId = S.typeId

	insert into #Ktype(typeid,usercode,fullname) select '10000','10000','代销库'
	insert into #Ktype(typeid,usercode,fullname) select '','',''
END
ELSE
	INSERT INTO #Ktype(typeid,usercode,fullname) 
	SELECT	S.typeId,S.UserCode,S.FullName 
	FROM	Stock S
	INNER JOIN F_GetManDetailKType(@OperatorID) F ON F.TypeId = S.typeId
	INNER JOIN dbo.F_GetAllBaseTypeIdFromUOrFLike(@chvKTypeName,4) L ON L.TypeId = S.typeId

IF  (@chvKTypeName = '' AND @MKTypeId = '00000')
	INSERT INTO #Ktype (typeid,usercode,fullname) values('00000','root','全部仓库')
	
	
INSERT INTO #Dtype SELECT typeid  FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

DECLARE @ConditionFlag int  -- 是否用往来单位过滤 调账单据及会计凭证单据的 BillnumberID
SET @ConditionFlag = 0
DECLARE @CSQL Varchar(2000)
Create Table #BillnumberID (BillnumberID int)

IF @chvBillType='' or @chvBillType =115  or @chvBillType =116  or @chvBillType =128  or @chvBillType =129
BEGIN
	SET @CSQL='
		INSERT INTO #BillnumberID 
		SELECT A.BillnumberID 
		FROM AdDebtBill A
		INNER JOIN #Btype T ON T.typeid = A.BtypeID '
	EXEC (@CSQL)
	SET @ConditionFlag = 1
END 
IF @chvBillType='' or @chvBillType =159
BEGIN         -- 应收应付才筛选往来单位
	SET @CSQL='
	INSERT INTO #BillnumberID SELECT BillnumberID 
	FROM AccountCredence A
	INNER JOIN Btype B ON B.TypeID= A.AtypeID
	INNER JOIN #Btype T ON T.typeid = A.AtypeID
	WHERE	A.TypeAtypeID=''0000200001'' OR A.TypeAtypeID=''0000100005'''
	EXEC (@CSQL)
	
	SET @CSQL='
	INSERT INTO #BillnumberID 
	SELECT A.BillnumberID FROM AccountCredence A
	WHERE	A.TypeAtypeID<>''0000200001'' AND A.TypeAtypeID<>''0000100005'''
	EXEC (@CSQL)

	SET @ConditionFlag = 1
END

DECLARE @Isinvoice int
SELECT @Isinvoice=SubValue FROM sysdata WHERE SubName='Isinvoice'

DECLARE @Billtypes varchar(2000)
SET @Billtypes ='(9999'
DECLARE @re_re int 
IF @OperatorID<>'00001'  -- 相关单据调阅权限
BEGIN
	EXEC @re_re=GP_CheckLimit @OperatorID,349  -- 零售单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',305'
		
	EXEC @re_re=GP_CheckLimit @OperatorID,2588  -- 零售退货单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',215'
		
	EXEC @re_re=GP_CheckLimit @OperatorID,350  -- 销售出库单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',11'
	EXEC @re_re=GP_CheckLimit @OperatorID,351  -- 销售退货单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',45'
	EXEC @re_re=GP_CheckLimit @OperatorID,352   -- 收款单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',4'
	EXEC @re_re=GP_CheckLimit @OperatorID,353   -- 受托代销收货单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',144'
	EXEC @re_re=GP_CheckLimit @OperatorID,354   -- 托代销结算单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',145'
	EXEC @re_re=GP_CheckLimit @OperatorID,355   -- 受托代销退货单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',146'
	EXEC @re_re=GP_CheckLimit @OperatorID,356   -- 受托代销调价单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',147'
	EXEC @re_re=GP_CheckLimit @OperatorID,357   -- 委托代销发货单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',140'
	EXEC @re_re=GP_CheckLimit @OperatorID,358   -- 委托代销结算单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',141'
	EXEC @re_re=GP_CheckLimit @OperatorID,359   -- 委托代销退货单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',142'
	EXEC @re_re=GP_CheckLimit @OperatorID,360   -- 委托代销调价单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',143'
	EXEC @re_re=GP_CheckLimit @OperatorID,361   -- 采购入库单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',34'
	EXEC @re_re=GP_CheckLimit @OperatorID,362   -- 采购退货单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',6'
	EXEC @re_re=GP_CheckLimit @OperatorID,363   -- 付款单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',66'
	EXEC @re_re=GP_CheckLimit @OperatorID,364   -- 同价调拨
	IF @re_re =0
		SET @Billtypes = @Billtypes +',17'
	EXEC @re_re=GP_CheckLimit @OperatorID,365   -- 变价调拨
	IF @re_re =0
		SET @Billtypes = @Billtypes +',21'
	EXEC @re_re=GP_CheckLimit @OperatorID,366   -- 报损单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',9'
	EXEC @re_re=GP_CheckLimit @OperatorID,367   -- 报溢单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',14'
	EXEC @re_re=GP_CheckLimit @OperatorID,368   -- 赠送单
	IF @re_re =0 and @proinfo <> 4
		SET @Billtypes = @Billtypes +',139'
	EXEC @re_re=GP_CheckLimit @OperatorID,369   -- 获赠单
	IF @re_re =0 and @proinfo <> 4
		SET @Billtypes = @Billtypes +',126'
	EXEC @re_re=GP_CheckLimit @OperatorID,370   -- 成本调价单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',57'
	EXEC @re_re=GP_CheckLimit @OperatorID,371   -- 商品拆装单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',16'
	EXEC @re_re=GP_CheckLimit @OperatorID,372   -- 应收款增加
	IF @re_re =0
		SET @Billtypes = @Billtypes +',116'
	EXEC @re_re=GP_CheckLimit @OperatorID,373   -- 应收款减少
	IF @re_re =0
		SET @Billtypes = @Billtypes +',115'
	EXEC @re_re=GP_CheckLimit @OperatorID,374   -- 应付款增加
	IF @re_re =0
		SET @Billtypes = @Billtypes +',128'
	EXEC @re_re=GP_CheckLimit @OperatorID,375   -- 应付款减少
	IF @re_re =0
		SET @Billtypes = @Billtypes +',129'
	EXEC @re_re=GP_CheckLimit @OperatorID,376   -- 费用单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',36'
	EXEC @re_re=GP_CheckLimit @OperatorID,377   -- 其他收入单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',93'
	EXEC @re_re=GP_CheckLimit @OperatorID,378   -- 转款单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',77'
	EXEC @re_re=GP_CheckLimit @OperatorID,379   -- 固定资产购买
	IF @re_re =0
		SET @Billtypes = @Billtypes +',84'
	EXEC @re_re=GP_CheckLimit @OperatorID,380   -- 固定资产变卖
	IF @re_re =0
		SET @Billtypes = @Billtypes +',85'
	EXEC @re_re=GP_CheckLimit @OperatorID,381   -- 固定资产折旧
	IF @re_re =0
		SET @Billtypes = @Billtypes +',78'
	EXEC @re_re=GP_CheckLimit @OperatorID,382   -- 待摊费用发生
	IF @re_re =0
		SET @Billtypes = @Billtypes +',5'
	EXEC @re_re=GP_CheckLimit @OperatorID,383   -- 待摊费用摊销
	IF @re_re =0
		SET @Billtypes = @Billtypes +',10'
	EXEC @re_re=GP_CheckLimit @OperatorID,384   -- 返利核算执行单
	IF @re_re =0 and @proinfo <> 4
		SET @Billtypes = @Billtypes +',148'
	EXEC @re_re=GP_CheckLimit @OperatorID,385   -- 价保执行单
	IF @re_re =0 and @proinfo <> 4
		SET @Billtypes = @Billtypes +',149'
	EXEC @re_re=GP_CheckLimit @OperatorID,386   -- 获利核算执行单
	IF @re_re =0 and @proinfo <> 4
		SET @Billtypes = @Billtypes +',150'
	EXEC @re_re=GP_CheckLimit @OperatorID,435   -- 换货单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',155'

	EXEC @re_re=GP_CheckLimit @OperatorID,503   -- 维修受理单
	IF @re_re =0
		SET @Billtypes = @Billtypes +',157'
	EXEC @re_re=GP_CheckLimit @OperatorID,502   -- 获得价保
		IF @re_re =0 and @proinfo <> 4
			SET @Billtypes = @Billtypes +',151'
	EXEC @re_re=GP_CheckLimit @OperatorID,501   -- 现金费用单
		IF @re_re =0
			SET @Billtypes = @Billtypes +',158'
	EXEC @re_re=GP_CheckLimit @OperatorID,550   -- 会计凭证
		IF @re_re =0
			SET @Billtypes = @Billtypes +',159'
	EXEC @re_re=GP_CheckLimit @OperatorID,583   -- 销售换货单
		IF @re_re =0
			SET @Billtypes = @Billtypes +',160'
	EXEC @re_re=GP_CheckLimit @OperatorID,585   -- 采购换货单
		IF @re_re =0
			SET @Billtypes = @Billtypes +',161'

---维修类单据的调阅权限
	EXEC @re_re=GP_CheckLimit @OperatorID,679   -- 维修单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',166'
	EXEC @re_re=GP_CheckLimit @OperatorID,680   -- 维修取件单
		IF @re_re =0 and @proinfo <> 4
			SET @BillTypes = @BillTypes +',167'
	EXEC @re_re=GP_CheckLimit @OperatorID,681   -- 整机更换单
		IF @re_re =0 and @proinfo <> 4
			SET @BillTypes = @BillTypes +',168'
	EXEC @re_re=GP_CheckLimit @OperatorID,683   -- 送修返回单
		IF @re_re =0 and @proinfo <> 4
			SET @BillTypes = @BillTypes +',170'
	EXEC @re_re=GP_CheckLimit @OperatorID,685   -- 上门维修单
		IF @re_re =0 and @proinfo <> 4
			SET @BillTypes = @BillTypes +',172'
	EXEC @re_re=GP_CheckLimit @OperatorID,686   -- 维修品调入单
		IF @re_re =0 
			SET @BillTypes = @BillTypes +',173'
	EXEC @re_re=GP_CheckLimit @OperatorID,687   -- 维修品调出单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',174'
	EXEC @re_re=GP_CheckLimit @OperatorID,688   -- 维修品调拨单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',175'
	--SET @Billtypes = @Billtypes +',166,167,168,170,172,173,174,175'	
	--汽配新加单据的调阅权限
	EXEC @re_re=GP_CheckLimit @OperatorID,1377   -- 快修单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',178'	
	EXEC @re_re=GP_CheckLimit @OperatorID,1378   -- 洗车结算单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',179'
	EXEC @re_re=GP_CheckLimit @OperatorID,1379   -- 会员储值充值单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',181'
	EXEC @re_re=GP_CheckLimit @OperatorID,1380   -- 洗车次数充值单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',182'
	EXEC @re_re=GP_CheckLimit @OperatorID,1386   -- 积分兑换单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',183'
	EXEC @re_re=GP_CheckLimit @OperatorID,1375   -- 保险理赔单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',186'
	EXEC @re_re=GP_CheckLimit @OperatorID,1473   -- 领料出库单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',191'
	EXEC @re_re=GP_CheckLimit @OperatorID,1475   -- 领料退回单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',197'
	EXEC @re_re=GP_CheckLimit @OperatorID,1535   -- 救援单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',196'
	EXEC @re_re=GP_CheckLimit @OperatorID,1479   -- 三包索赔单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',200'
	EXEC @re_re=GP_CheckLimit @OperatorID,1533   -- 维修结算单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',195'
	--SET @Billtypes = @Billtypes +',187,188,189,190'	
	--A8新加单据的调阅权限			
	EXEC @re_re=GP_CheckLimit @OperatorID,718   -- 分支机构调拨出库单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',187'
			
	EXEC @re_re=GP_CheckLimit @OperatorID,721   -- 分支机构调拨入库单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',188'
			
	EXEC @re_re=GP_CheckLimit @OperatorID,727   -- 预收款单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',189'

	EXEC @re_re=GP_CheckLimit @OperatorID,730   -- 预付款单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',190'
	--A8 2011R1新加单据的调阅权限		
	EXEC @re_re=GP_CheckLimit @OperatorID,1553   --	其他入库单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',201'
	EXEC @re_re=GP_CheckLimit @OperatorID,1557   --	其他出库单
		IF @re_re =0
			SET @BillTypes = @BillTypes +',202'
	EXEC @re_re=GP_CheckLimit @OperatorID,1941   --	采购费用分摊
		IF @re_re =0
			SET @BillTypes = @BillTypes +',205'
	EXEC @re_re=GP_CheckLimit @OperatorID,1946   --	销售费用分摊
		IF @re_re =0
			SET @BillTypes = @BillTypes +',206'
						
	-- 固定资产卡片
	EXEC @re_re=GP_CheckLimit @OperatorID,2531   --	固定资产增加单
		IF @re_re =0 and @proinfo <> 4
			SET @BillTypes = @BillTypes +',212'	
	EXEC @re_re=GP_CheckLimit @OperatorID,2536   --	固定资产减少单
	IF @re_re =0 and @proinfo <> 4
		SET @BillTypes = @BillTypes +',213'	
	EXEC @re_re=GP_CheckLimit @OperatorID,2541   --	固定资产减少单
	IF @re_re =0 and @proinfo <> 4
		SET @BillTypes = @BillTypes +',214'	
	EXEC @re_re=GP_CheckLimit @OperatorID,4497   --	会员批量充值
	IF @re_re =0
		SET @BillTypes = @BillTypes +',312'	
	
	EXEC @re_re=GP_CheckLimit @OperatorID,2988   --	提成单
		IF @re_re =0 and @proinfo <> 4
			SET @BillTypes = @BillTypes +',311'	
		
	EXEC @re_re=GP_CheckLimit @OperatorID,4576   --	暂估入库
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',400'	
	EXEC @re_re=GP_CheckLimit @OperatorID,4585   --	暂估退货
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',401'
	EXEC @re_re=GP_CheckLimit @OperatorID,4597   --	发出商品
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',402'
	EXEC @re_re=GP_CheckLimit @OperatorID,4606   --	发出商品退货
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',403'
	EXEC @re_re=GP_CheckLimit @OperatorID,4618   --	采购暂估开票
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',404'
	EXEC @re_re=GP_CheckLimit @OperatorID,4626   --	发出商品开票
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',405'
		EXEC @re_re=GP_CheckLimit @OperatorID,4667   --	往来核销
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',450'
	
	EXEC @re_re=GP_CheckLimit @OperatorID,4749   --	组合品销售
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',12'
	EXEC @re_re=GP_CheckLimit @OperatorID,4757   --	组合品销售退货
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',46'
	EXEC @re_re=GP_CheckLimit @OperatorID,4820   --	运输配送
		IF @re_re =0 AND @Isinvoice=1
			SET @BillTypes = @BillTypes +',414'
	--======================优惠券===================
	EXEC @re_re=GP_CheckLimit @OperatorID,5034   --	优惠券入库单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',423'
		
	EXEC @re_re=GP_CheckLimit @OperatorID,5042   --	优惠券出库单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',424'
		
	EXEC @re_re=GP_CheckLimit @OperatorID,5058   --	优惠券退货单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',426'
			
	EXEC @re_re=GP_CheckLimit @OperatorID,5205   --	优惠券分支机构调拨入库单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',428'
				
	EXEC @re_re=GP_CheckLimit @OperatorID,5200   --	优惠券分支机构调拨出库单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',429'
		
	--======================门店配送===================
	EXEC @re_re=GP_CheckLimit @OperatorID,5239   --	门店配送单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',327'
		
	EXEC @re_re=GP_CheckLimit @OperatorID,5248   --	门店配送退货单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',328'
		
	EXEC @re_re=GP_CheckLimit @OperatorID,5257   --	门店验收单
	IF @re_re =0
		SET @BillTypes = @BillTypes +',329'		
END 
SET @Billtypes = @Billtypes +' ) '



SET	@intFlag='20'

--DECLARE @chvExplain varchar(256)
--DECLARE @chvComment varchar(256)
DECLARE @chvSQL_WHERE varchar(MAX)
SET @chvSQL_WHERE = ''
IF @chvStartDate <> ''
	SET @chvSQL_WHERE = ' AND a.BillDate >= ''' + @chvStartDate + ''''
IF @chvEndDate <> ''
	SET @chvSQL_WHERE = @chvSQL_WHERE + ' AND a.BillDate <= ''' + @chvEndDate + ''''

SET @chvSQL_WHERE = @chvSQL_WHERE + ' AND (
											(b.btypeid in (select typeid from #Btype) AND a.Billtype not in (115,116,128,129,159)) 
											OR 
											(a.Billtype in (115,116,128,129,159) AND a.BillnumberID in (SELECT BillnumberID FROM #BillnumberID)
											)
										)'	
SELECT @chvSQL_WHERE = @chvSQL_WHERE + ' AND ( b.EtypeID IN (Select typeid from #Etype) or a.billtype=179 )'
if @chvKTypeName=''
	SELECT @chvSQL_WHERE = @chvSQL_WHERE + ' AND(
 						b.KtypeID IN (Select typeid from #Ktype) 
						OR
						 a.billtype in(179,181,182,404,405,450)
						OR 
						 (a.billtype in (57) and b.ktypeid in(''00000'',''''))
						OR 
						 (a.billtype in (188) and b.ktypeid2 in (Select typeid from #Ktype)  )
					    )	'
else if @chvKTypeName<>''
	SELECT @chvSQL_WHERE = @chvSQL_WHERE + ' AND 
 						      b.KtypeID IN (Select typeid from #Ktype) '
					   
SELECT @chvSQL_WHERE = @chvSQL_WHERE + ' AND 
 						      b.DtypeID IN (Select typeid from #Dtype) '
					   


IF @chvBillType <> ''
	SET @chvSQL_WHERE = @chvSQL_WHERE + ' AND b.BillType = ''' + @chvBillType +''''
IF @chvComment <> ''
	SET @chvSQL_WHERE = @chvSQL_WHERE + ' AND b.Comment like '''+'%' + @chvComment +'%'+''''
IF @chvExplain <> ''
	SET @chvSQL_WHERE = @chvSQL_WHERE + ' AND b.Explain like '''+'%' + @chvExplain +'%'+''''

IF @OperatorID<>'00001'
	SELECT @chvSQL_WHERE = @chvSQL_WHERE + ' AND a.Billtype in ' +@Billtypes

IF @proinfo = 4
SELECT @chvSQL_WHERE = @chvSQL_WHERE + ' AND a.Billtype NOT IN (167, 168, 170, 172, 148, 150, 149, 151, 139, 126, 212, 213, 214) '



--PRINT @chvSQL_WHERE


-- 建立查询临时表 ( 表中的记录条数将为 intPageSize )
CREATE TABLE #AccountTemp (
	BillNumberID	int,		-- 单据 ID 号
	PZH				int,		-- 凭证号
	IfCanOutPut		varchar(10),	-- 凭证是否可以导出标识
	BillDate		datetime,	-- 单据日期
	BillCode		varchar(200),	-- 单据编号
	BillType		int,		-- 单据类型
	ATypeUserCode	varchar(200),	-- 系统科目编号
	ATypeFullName	varchar(200),	-- 系统科目名称
	SubjectCode		varchar(100),	-- 自定义科目编号
	Total_J			 NUMERIC(24, 10) ,	-- 借方金额
	Total_D			 NUMERIC(24, 10) ,	-- 贷方金额
	CheckName		varchar(200),	-- 制单人名称
	ETypeFullName	varchar(200),	-- 经手人名称
	BTypeFullName	varchar(200),	-- 往来单位名称(客户)
	BTypeFullName1	varchar(200),	-- 往来单位名称（供货商）
	KTypeFullName	varchar(200),	-- 仓库名称
	Explain			varchar(256),	-- 说明
	Comment			varchar(256),	-- 摘要
	Ji				varchar(50),	-- 记
    voucherChar		varchar(50),	-- 凭证字
	Ifout			char(1),        -- 是否已导出
	JD              char(1),        -- 借方还是货方
	FENTRYID        numeric(18,0),   -- 分录号（从0开始）
	strOrder        char(10)  null,       -- 排顺序
	stypeid			varchar(100),		--分支机构 
	btypeid         varchar(200)    -- 结算单位
)

CREATE TABLE #TempInfo
(
	nid				INT  IDENTITY(1,1),
	BillNumberId	NUMERIC(24,10),
	BillDate		DATETIME,
	BillCode		VARCHAR(500),
	BillType		INT,
	ATypeID			INT,
	ATypeUserCode	VARCHAR(500),
	ATypeFullName	VARCHAR(500),
	SubjectCode		VARCHAR(500),
	dealbtypeid		VARCHAR(50),
	Total_J			NUMERIC(24,10),
	Total_D			NUMERIC(24,10),
	Checke			VARCHAR(50),
	BtypeID			VARCHAR(500),
	ETypeFullName	VARCHAR(500),
	BTypeFullName	VARCHAR(500),
	KTypeFullName	VARCHAR(500),
	Explain			VARCHAR(2000),
	Comment			VARCHAR(2000),
	voucherChar		VARCHAR(100),
	Ifout			VARCHAR(10),
	stypeid			VARCHAR(50)
)

DECLARE @YSCode varchar(100) -- 应收科目编号
DECLARE @YFCode varchar(100) -- 应付科目编号
DECLARE @YS_TypeID varchar(100) -- 应收对应的财务软件的科目ID
DECLARE @YF_TypeID varchar(100) -- 应付对应的财务软件的科目ID



SELECT @YSCode=UserCode FROM Ac_Items WHERE UserCode ='987'
SELECT @YFCode=UserCode FROM Ac_Items WHERE TypeID ='2121'
SELECT @YS_TypeID=SubjectCode FROM AccountSubjectSet WHERE ATypeID =(SELECT nId FROM Ac_Items WHERE UserCode ='987') AND SoftType=@chvSoftType
SELECT @YF_TypeID=SubjectCode FROM AccountSubjectSet WHERE ATypeID =(SELECT nId FROM Ac_Items WHERE TypeID ='2121') AND SoftType=@chvSoftType

DECLARE @TEMP_BillNumberID int 
DECLARE @TempTotal_J   NUMERIC(24, 10)    
DECLARE @TempTotal_D   NUMERIC(24, 10)   
DECLARE @TempTotal   NUMERIC(24, 10)   
SET @TempTotal_J = 0
SET @TempTotal_D = 0
SET @TempTotal = 0
DECLARE @Tax  NUMERIC(24, 10) 
SET @Tax =0
IF EXISTS(SELECT Value FROM UserConfig where ConfigName ='AllTaxRate' and  CAST(Value AS  NUMERIC(22,10))<>0)
	SELECT @Tax=Value from userconfig where ConfigName ='AllTaxRate' 
DECLARE @GridType varchar(50)
SET @GridType =''
IF EXISTS (SELECT Value from userconfig where ConfigName ='GridType')
	SELECT @GridType=Value from userconfig where ConfigName ='GridType'


	DECLARE @chvSQL varchar(MAX)
	IF	@chrJudgeFlag='20'
	BEGIN
	SET @chvSQL = '
			INSERT INTO #TempInfo
			(
				BillNumberId,
				BillDate,
				BillCode,
				BillType,
				ATypeID,
				ATypeUserCode,
				ATypeFullName,
				SubjectCode,
				dealbtypeid,
				Total_J,
				Total_D,
				Checke,
				BtypeID,
				ETypeFullName,
				BTypeFullName,
				KTypeFullName,
				Explain,
				Comment,
				voucherChar,
				Ifout,
				stypeid
			)
			SELECT	b.BillNumberID,	-- 单据 ID 号
					a.BillDate,	-- 单据日期
					b.BillCode,	-- 单据编号
					b.BillType,	-- 单据类型
					ac.nid AS ATypeID,	-- 系统科目 ID 值
					ac.UserCode AS ATypeUserCode,	-- 系统科目编号
					ac.FullName AS ATypeFullName,	-- 系统科目名称
					g.SubjectCode,	-- 自定义科目编号
					b.btypeid,	-- 结算单位id
					Total_J = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									ELSE -- 没有配置科目时，资产，支出类科目默认为借方，负债，所有者权益，收入类默认为贷方
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then a.total
											else
												0
											end	
										else 
											case 
												when a.Total >0 then 0
											else
												a.total
											end				
										end
											
									END),	-- 借方金额
					Total_D = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									ELSE
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then 0
											else
												a.total
											end
										else
											case 
												when a.Total >0 then a.total
											else
												0
											end
										end
									END),	-- 贷方金额

					b.Checke,
					c.TypeID as BtypeID,

					d.FullName AS ETypeFullName,	-- 经手人名称
					c.FullName AS BTypeFullName,	-- 往来单位名称
					f.FullName AS KTypeFullName,	-- 仓库名称
					REPLACE(b.Explain,'','','';'') AS Explain,	-- 说明

					REPLACE(b.Comment,'','','';'')	AS Comment, -- 备注
					ISNULL(v.voucherChar,0) AS voucherChar,  --凭证字
					a.Ifout --是否为已导出凭证
			FROM	ListTable a
			LEFT JOIN AC_items ac on a.typeid=a.nid
			LEFT JOIN BillIndex b ON a.BillNumberID = b.BillNumberID and a.billtype=b.billtype
			LEFT JOIN BType c ON a.BTypeID = c.TypeID
			LEFT JOIN Employee d ON a.ETypeID = d.TypeID
			--LEFT JOIN AType e ON a.ATypeID = e.TypeID
			LEFT JOIN Stock f ON f.TypeID = b.KTypeID
			LEFT JOIN voucherChar1 v ON v.BillNumberID = a.BillNumberID
			LEFT JOIN AccountSubjectSet g ON g.ATypeID = a.ATypeID AND g.SoftType = ''' + @chvSoftType + '''
			WHERE	a.Audited = ''1''
				' + @chvSQL_WHERE 
		IF @chvETypename=''
			set @chvSQL=@chvSQL+' AND (a.etypeid in (select typeid from #Etype))'
		IF @chvETypename<>''	
			set @chvSQL=@chvSQL+' AND a.etypeid in (select typeid from #Etype)
			ORDER BY a.BillDate, b.BillType, b.BillCode'
			END
	IF	@chrJudgeFlag='30'
		BEGIN
			SET @chvSQL = '
			INSERT INTO #TempInfo
			(
				BillNumberId,
				BillDate,
				BillCode,
				BillType,
				ATypeID,
				ATypeUserCode,
				ATypeFullName,
				SubjectCode,
				dealbtypeid,
				Total_J,
				Total_D,
				Checke,
				BtypeID,
				ETypeFullName,
				BTypeFullName,
				KTypeFullName,
				Explain,
				Comment,
				voucherChar,
				Ifout,
				stypeid
			)
			SELECT	--DISTINCT 
					b.BillNumberID,	-- 单据 ID 号
					a.BillDate,	-- 单据日期
					b.BillCode,	-- 单据编号
					b.BillType,	-- 单据类型
					ac.nid AS ATypeID,	-- 系统科目 ID 值
					ac.UserCode AS ATypeUserCode,	-- 系统科目编号
					ac.FullName AS ATypeFullName,	-- 系统科目名称
					g.SubjectCode,	-- 自定义科目编号
					b.btypeid,	-- 结算单位id

					Total_J = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									ELSE -- 没有配置科目时，资产，支出类科目默认为借方，负债，所有者权益，收入类默认为贷方
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then a.total
											else
												0
											end	
										else 
											case 
												when a.Total >0 then 0
											else
												a.total
											end				
										end
											
									END),	-- 借方金额
					Total_D = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									ELSE
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then 0
											else
												a.total
											end
										else
											case 
												when a.Total >0 then a.total
											else
												0
											end
										end
									END),	-- 贷方金额

					b.Checke,
					c.TypeID as BtypeID,
					d.FullName AS ETypeFullName,	-- 经手人名称
					c.FullName AS BTypeFullName,	-- 往来单位名称
					f.FullName AS KTypeFullName,	-- 仓库名称
					REPLACE(b.Explain,'','','';'') AS Explain,	-- 说明

					REPLACE(b.Comment,'','','';'')	AS Comment, -- 备注
					ISNULL(v.voucherChar,0) AS voucherChar,  --凭证字
					a.Ifout, --是否为已导出凭证
					b.stypeid
			FROM	ListTable a
			LEFT JOIN AC_ITEMS AC ON A.atypeid = AC.nid
			LEFT JOIN BillIndex b ON a.BillNumberID = b.BillNumberID and a.billtype=b.billtype
			LEFT JOIN BType c ON a.BTypeID = c.TypeID
			LEFT JOIN Employee d ON a.ETypeID = d.TypeID
			--LEFT JOIN AType e ON a.ATypeID = e.TypeID
			LEFT JOIN Stock f ON f.TypeID = b.KTypeID
			LEFT JOIN voucherChar2 v ON v.BillNumberID = a.BillNumberID
			LEFT JOIN AccountSubjectSet g ON g.ATypeID = a.ATypeID AND g.SoftType = ''' + @chvSoftType + '''
			WHERE	a.Audited = ''1''
					AND b.stypeid IN(SELECT typeid FROM #GetSelectSTypeId)
				' + @chvSQL_WHERE 
		IF @chvETypename=''
			set @chvSQL=@chvSQL+' AND (a.etypeid in (select typeid from #Etype))'
		IF @chvETypename<>''	
			set @chvSQL=@chvSQL+' AND a.etypeid in (select typeid from #Etype)
			'
				SET @chvSQL=@chvSQL+' ORDER BY a.BillDate, b.BillType, b.BillCode '
			END
	ELSE
		BEGIN
	--9.6在这加了提成单的查询
			SET @chvSQL = '
			INSERT INTO #TempInfo
			(
				BillNumberId,
				BillDate,
				BillCode,
				BillType,
				ATypeID,
				ATypeUserCode,
				ATypeFullName,
				SubjectCode,
				dealbtypeid,
				Total_J,
				Total_D,
				Checke,
				BtypeID,
				ETypeFullName,
				BTypeFullName,
				KTypeFullName,
				Explain,
				Comment,
				voucherChar,
				Ifout,
				stypeid
			)
			SELECT	--DISTINCT 
					b.BillNumberID,	-- 单据 ID 号
					a.BillDate,	-- 单据日期
					b.BillCode,	-- 单据编号
					b.BillType,	-- 单据类型
					ac.nid AS ATypeID,	-- 系统科目 ID 值
					ac.UserCode AS ATypeUserCode,	-- 系统科目编号
					ac.FullName AS ATypeFullName,	-- 系统科目名称
					g.SubjectCode,	-- 自定义科目编号
					b.btypeid,	-- 结算单位id

					Total_J = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									ELSE -- 没有配置科目时，资产，支出类科目默认为借方，负债，所有者权益，收入类默认为贷方
										case when ac.typename in(''B'',''E'',''F'',''C'')then 
											case 
												when a.Total >0 then a.total
											else
												0
											end	
										else 
											case 
												when a.Total >0 then 0
											else
												a.total
											end				
										end
											
									END),	-- 借方金额
					Total_D = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									ELSE
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then 0
											else
												a.total
											end
										else
											case 
												when a.Total >0 then a.total
											else
												0
											end
										end
									END),	-- 贷方金额
					b.Checke,
					c.TypeID as BtypeID,
					d.FullName AS ETypeFullName,	-- 经手人名称
					c.FullName AS BTypeFullName,	-- 往来单位名称
					f.FullName AS KTypeFullName,	-- 仓库名称
					REPLACE(b.Explain,'','','';'') AS Explain,	-- 说明
					REPLACE(b.Comment,'','','';'')	AS Comment, -- 备注
					''记'' AS voucherChar,  --凭证字
					a.Ifout, --是否为已导出凭证
					b.stypeid
			FROM	ListTable a
			LEFT JOIN AC_items ac on a.atypeid= ac.nid
			LEFT JOIN BillIndex b ON a.BillNumberID = b.BillNumberID and a.billtype=b.billtype
			LEFT JOIN BType c ON a.BTypeID = c.TypeID
			LEFT JOIN Employee d ON a.ETypeID = d.TypeID
			--LEFT JOIN AType e ON a.ATypeID = e.TypeID
			LEFT JOIN Stock f ON f.TypeID = b.KTypeID
			LEFT JOIN AccountSubjectSet g ON g.ATypeID = a.ATypeID AND g.SoftType = ''' + @chvSoftType + '''
			WHERE	a.Audited = ''1''
					AND b.stypeid IN(SELECT typeid FROM #GetSelectSTypeId)
				' + @chvSQL_WHERE
		IF @chvETypename=''
			set @chvSQL=@chvSQL+' AND (a.etypeid in (select typeid from #Etype))'
		IF @chvETypename<>''	
			set @chvSQL=@chvSQL+' AND a.etypeid in (select typeid from #Etype)
				'
			

	
		--9.6提成单--V1排除提成单
		IF( (@chvBillType = '' OR @chvBillType = '311') AND @proinfo <> 4 )
		BEGIN
			SET @chvSQL += ' 
						UNION ALL
						SELECT b.BillNumberID,a.BillDate,b.BillCode,A.BillType,ac.nid AS ATypeID,ac.UserCode AS ATypeUserCode,
						ac.FullName AS ATypeFullName,g.SubjectCode,'''' AS btypeid,
						Total_J = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									ELSE -- 没有配置科目时，资产，支出类科目默认为借方，负债，所有者权益，收入类默认为贷方
										case when ac.typename in(''B'',''E'',''F'',''C'')then 
											case 
												when a.Total >0 then a.total
											else
												0
											end	
										else 
											case 
												when a.Total >0 then 0
											else
												a.total
											end				
										end
											
									END),	-- 借方金额
					Total_D = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									ELSE
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then 0
											else
												a.total
											end
										else
											case 
												when a.Total >0 then a.total
											else
												0
											end
										end
									END),
						b.Checke,'''' as BtypeID,'''' AS ETypeFullName,'''' AS BTypeFullName,'''' AS KTypeFullName,REPLACE(b.Explain,'','','';'') AS Explain,
						REPLACE(b.Comment,'','','';'')	AS Comment,''记'' AS voucherChar,a.Ifout,b.stypeid 
						FROM ListTable AS A
						LEFT JOIN CommissionBillNew b ON a.BillNumberID = b.BillNumberID
						LEFT JOIN AC_items ac on A.AtypeId= ac.nid
						LEFT JOIN AccountSubjectSet g ON g.ATypeID = a.ATypeID AND g.SoftType = ''' + @chvSoftType + '''
						WHERE a.Audited = ''1''
								AND A.BillType = 311
								AND b.stypeid IN(SELECT typeid FROM #GetSelectSTypeId)
						'
			IF @chvStartDate <> ''
				SET @chvSQL += '	AND a.BillDate >= ''' + @chvStartDate + ''''
			IF @chvEndDate <> ''
				SET @chvSQL += '	AND a.BillDate <= ''' + @chvEndDate + ''''
			IF @chvComment <> ''
				SET @chvSQL += '	AND b.Comment like '''+'%' + @chvComment +'%'+''''
			IF @chvExplain <> ''
				SET @chvSQL += '	AND b.Explain like '''+'%' + @chvExplain +'%'+''''
			IF @chvETypename<>''	
				SET @chvSQL=@chvSQL+' AND 1 <> 1 '
			IF @chvBTypeName<>''	
				SET @chvSQL=@chvSQL+' AND 1 <> 1 '
			IF @chvKTypeName<>''	
				SET @chvSQL=@chvSQL+' AND 1 <> 1 '
				
		END
		
		IF(@chvBillType = '' OR @chvBillType in(404,405))
		BEGIN
			SET @chvSQL += ' 
						UNION ALL
					SELECT	--DISTINCT 
					b.BillNumberID,	-- 单据 ID 号
					a.BillDate,	-- 单据日期
					b.BillCode,	-- 单据编号
					b.BillType,	-- 单据类型
					ac.nid AS ATypeID,	-- 系统科目 ID 值
					ac.UserCode AS ATypeUserCode,	-- 系统科目编号
					ac.FullName AS ATypeFullName,	-- 系统科目名称
					g.SubjectCode,	-- 自定义科目编号
					b.btypeid,	-- 结算单位id

					Total_J = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									ELSE -- 没有配置科目时，资产，支出类科目默认为借方，负债，所有者权益，收入类默认为贷方
										case when ac.typename in(''B'',''E'',''F'',''C'')then 
											case 
												when a.Total >0 then a.total
											else
												0
											end	
										else 
											case 
												when a.Total >0 then 0
											else
												a.total
											end				
										end
											
									END),	-- 借方金额
					Total_D = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									ELSE
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then 0
											else
												a.total
											end
										else
											case 
												when a.Total >0 then a.total
											else
												0
											end
										end
									END),	-- 贷方金额
					b.Checke,
					c.TypeID as BtypeID,
					d.FullName AS ETypeFullName,	-- 经手人名称
					c.FullName AS BTypeFullName,	-- 往来单位名称
					'''' AS KTypeFullName,	-- 仓库名称
					REPLACE(b.Explain,'','','';'') AS Explain,	-- 说明
					REPLACE(b.Comment,'','','';'')	AS Comment, -- 备注
					''记'' AS voucherChar,  --凭证字
					a.Ifout, --是否为已导出凭证
					b.stypeid
						FROM ListTable AS A
						LEFT JOIN ReceiptBillIndex b ON a.BillNumberID = b.BillNumberID and a.billtype=b.billtype
						LEFT JOIN AC_items ac on A.AtypeId= ac.nid
						LEFT JOIN BType c ON a.BTypeID = c.TypeID
						LEFT JOIN Employee d ON a.ETypeID = d.TypeID
						--LEFT JOIN Stock f ON f.TypeID = b.KTypeID
						LEFT JOIN AccountSubjectSet g ON g.ATypeID = a.ATypeID AND g.SoftType = ''' + @chvSoftType + '''
						WHERE a.Audited = ''1''
								AND b.stypeid IN(SELECT typeid FROM #GetSelectSTypeId)
								'
				IF @chvBillType <> ''
						SET @chvSQL = @chvSQL + ' AND b.BillType = ''' + @chvBillType +''''
						
			IF @chvETypename<>''	
				set @chvSQL=@chvSQL+' AND a.etypeid in (select typeid from #Etype) '
			IF @chvKTypeName<>''	
				set @chvSQL=@chvSQL+' AND a.ktypeid in (select typeid from #Ktype) '
			IF @chvBTypeName<>''	
				set @chvSQL=@chvSQL+' AND a.btypeid in (select typeid from #Btype) '
			IF @chvStartDate <> ''
				SET @chvSQL += '	AND a.BillDate >= ''' + @chvStartDate + ''''
			IF @chvEndDate <> ''
				SET @chvSQL += '	AND a.BillDate <= ''' + @chvEndDate + ''''
			IF @chvComment <> ''
				SET @chvSQL += '	AND b.Comment like '''+'%' + @chvComment +'%'+''''
			IF @chvExplain <> ''
				SET @chvSQL += '	AND b.Explain like '''+'%' + @chvExplain +'%'+''''
			IF @OperatorID<>'00001'
						SELECT @chvSQL = @chvSQL + ' AND a.Billtype in ' +@Billtypes
		END
		
		--=======================优惠券(优惠券入库单=423、优惠券出库单=424、优惠券退货单=426)==============================
		IF(@chvBillType in('',423,424,426,428,429))
		BEGIN
			SET @chvSQL += ' 
				UNION ALL
				SELECT	--DISTINCT 
					b.BillNumberID,	-- 单据 ID 号
					a.BillDate,	-- 单据日期
					b.BillCode,	-- 单据编号
					b.BillType,	-- 单据类型
					ac.nid AS ATypeID,	-- 系统科目 ID 值
					ac.UserCode AS ATypeUserCode,	-- 系统科目编号
					ac.FullName AS ATypeFullName,	-- 系统科目名称
					g.SubjectCode,	-- 自定义科目编号
					b.btypeid,	-- 结算单位id

					Total_J = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									ELSE -- 没有配置科目时，资产，支出类科目默认为借方，负债，所有者权益，收入类默认为贷方
										case when ac.typename in(''B'',''E'',''F'',''C'')then 
											case 
												when a.Total >0 then a.total
											else
												0
											end	
										else 
											case 
												when a.Total >0 then 0
											else
												a.total
											end				
										end
											
									END),	-- 借方金额
					Total_D = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									ELSE
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then 0
											else
												a.total
											end
										else
											case 
												when a.Total >0 then a.total
											else
												0
											end
										end
									END),	-- 贷方金额
					b.Maker Checke,
					c.TypeID as BtypeID,
					d.FullName AS ETypeFullName,	-- 经手人名称
					c.FullName AS BTypeFullName,	-- 往来单位名称
					f.FullName KTypeFullName,	-- 仓库名称
					REPLACE(b.Explain,'','','';'') AS Explain,	-- 说明
					REPLACE(b.Comment,'','','';'')	AS Comment, -- 备注
					''记'' AS voucherChar,  --凭证字
					a.Ifout, --是否为已导出凭证
					b.stypeid
				FROM ListTable AS A
				LEFT JOIN Coupon_BillIndex b ON a.BillNumberID = b.BillNumberID and a.billtype=b.billtype
				LEFT JOIN AC_items ac on A.AtypeId= ac.nid
				LEFT JOIN BType c ON a.BTypeID = c.TypeID
				LEFT JOIN Employee d ON a.ETypeID = d.TypeID
				LEFT JOIN Stock f ON (B.BillType IN(423,426,428) AND f.TypeID = b.InKTypeId) OR (B.BillType in(424,429) AND F.typeId=B.OutKTypeId)
				LEFT JOIN AccountSubjectSet g ON g.ATypeID = a.ATypeID AND g.SoftType = ''' + @chvSoftType + '''
				WHERE a.Audited = ''1''
						AND b.stypeid IN(SELECT typeid FROM #GetSelectSTypeId)
								'
				IF @chvBillType <> ''
						SET @chvSQL = @chvSQL + ' AND b.BillType = ''' + @chvBillType +''''
						
			IF @chvETypename<>''	
				set @chvSQL=@chvSQL+' AND a.etypeid in (select typeid from #Etype) '
			IF @chvKTypeName<>''	
				set @chvSQL=@chvSQL+' AND a.ktypeid in (select typeid from #Ktype) '
			IF @chvBTypeName<>''	
				set @chvSQL=@chvSQL+' AND a.btypeid in (select typeid from #Btype) '
			IF @chvStartDate <> ''
				SET @chvSQL += '	AND a.BillDate >= ''' + @chvStartDate + ''''
			IF @chvEndDate <> ''
				SET @chvSQL += '	AND a.BillDate <= ''' + @chvEndDate + ''''
			IF @chvComment <> ''
				SET @chvSQL += '	AND b.Comment like '''+'%' + @chvComment +'%'+''''
			IF @chvExplain <> ''
				SET @chvSQL += '	AND b.Explain like '''+'%' + @chvExplain +'%'+''''
			IF @OperatorID<>'00001'
						SELECT @chvSQL = @chvSQL + ' AND a.Billtype in ' +@Billtypes
		END
		
		--=======================门店配送单==============================
		IF(@chvBillType in('',327,328,329))
		BEGIN
			SET @chvSQL += ' 
				UNION ALL
				SELECT	--DISTINCT 
					b.BillNumberID,	-- 单据 ID 号
					a.BillDate,	-- 单据日期
					b.BillCode,	-- 单据编号
					b.BillType,	-- 单据类型
					ac.nid AS ATypeID,	-- 系统科目 ID 值
					ac.UserCode AS ATypeUserCode,	-- 系统科目编号
					ac.FullName AS ATypeFullName,	-- 系统科目名称
					g.SubjectCode,	-- 自定义科目编号
					'''' as btypeid,	-- 结算单位id

					Total_J = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									ELSE -- 没有配置科目时，资产，支出类科目默认为借方，负债，所有者权益，收入类默认为贷方
										case when ac.typename in(''B'',''E'',''F'',''C'')then 
											case 
												when a.Total >0 then a.total
											else
												0
											end	
										else 
											case 
												when a.Total >0 then 0
											else
												a.total
											end				
										end
											
									END),	-- 借方金额
					Total_D = abs(CASE 
									WHEN g.J_D = 1 THEN 
										case 
											when a.Total >0 then 0
										else
											a.total
										end
									WHEN g.J_D = 0 THEN 
										case 
											when a.Total >0 then a.total
										else
											0
										end
									ELSE
										case when ac.typename in(''B'',''E'',''F'',''C'') then 
											case 
												when a.Total >0 then 0
											else
												a.total
											end
										else
											case 
												when a.Total >0 then a.total
											else
												0
											end
										end
									END),	-- 贷方金额
					'''' Checke,
					'''' as BtypeID,
					d.FullName AS ETypeFullName,	-- 经手人名称
					'''' AS BTypeFullName,	-- 往来单位名称
					f.FullName KTypeFullName,	-- 仓库名称
					REPLACE(b.Explain,'','','';'') AS Explain,	-- 说明
					REPLACE(b.Comment,'','','';'')	AS Comment, -- 备注
					''记'' AS voucherChar,  --凭证字
					a.Ifout, --是否为已导出凭证
					b.stypeid
				FROM ListTable AS A
				LEFT JOIN PosAllotApplyBillIndex b ON a.BillNumberID = b.BillNumberID and a.billtype=b.billtype
				LEFT JOIN AC_items ac on A.AtypeId= ac.nid
				--LEFT JOIN BType c ON a.BTypeID = c.TypeID
				LEFT JOIN Employee d ON a.ETypeID = d.TypeID
				LEFT JOIN Stock f ON A.KTypeId=f.TypeID
				LEFT JOIN AccountSubjectSet g ON g.ATypeID = a.ATypeID AND g.SoftType = ''' + @chvSoftType + '''
				WHERE a.Audited = ''1''
						AND b.stypeid IN(SELECT typeid FROM #GetSelectSTypeId)
								'
				IF @chvBillType <> ''
						SET @chvSQL = @chvSQL + ' AND b.BillType = ''' + @chvBillType +''''
						
			IF @chvETypename<>''	
				set @chvSQL=@chvSQL+' AND a.etypeid in (select typeid from #Etype) '
			IF @chvKTypeName<>''	
				set @chvSQL=@chvSQL+' AND a.ktypeid in (select typeid from #Ktype) '
			IF @chvBTypeName<>''	
				set @chvSQL=@chvSQL+' AND a.btypeid in (select typeid from #Btype) '
			IF @chvStartDate <> ''
				SET @chvSQL += '	AND a.BillDate >= ''' + @chvStartDate + ''''
			IF @chvEndDate <> ''
				SET @chvSQL += '	AND a.BillDate <= ''' + @chvEndDate + ''''
			IF @chvComment <> ''
				SET @chvSQL += '	AND b.Comment like '''+'%' + @chvComment +'%'+''''
			IF @chvExplain <> ''
				SET @chvSQL += '	AND b.Explain like '''+'%' + @chvExplain +'%'+''''
			IF @OperatorID<>'00001'
						SELECT @chvSQL = @chvSQL + ' AND a.Billtype in ' +@Billtypes
		END
		
	END
	
	--print(@chvSQL)
	EXEC(@chvSQL)	
	
	DECLARE @intPzh int -- 凭证号
	DECLARE @intBillNumberIDTemp int	-- 单据 ID 号临时变量
	DECLARE @chvIfCanOutPut varchar(1)	-- 凭证是否可以导出标识
	SET @intPzh = 1		-- 初始化凭证号
	SET @chvIfCanOutPut = 0		-- 初始化不能导出

	DECLARE @FENTRYID numeric(18,0)
	SET @FENTRYID =0


	DECLARE @intPzh_AN int -- 凭证号
	DECLARE @chvIfCanOutPut_AN varchar(1)	-- 凭证是否可以导出标识
	SET @intPzh_AN = 1		-- 初始化凭证号
	SET @chvIfCanOutPut_AN = 0		-- 初始化不能导出



	DECLARE @first int 
	SET @first =0	
	
DECLARE @i			NUMERIC(18,0),
		@nCount		NUMERIC(18,0)   
		
		
SET @i = 1			
			      
SELECT @nCount = COUNT(*) FROM #TempInfo

CREATE CLUSTERED INDEX CIX_TempInf_Nid ON #TempInfo(nid)

WHILE @i<= @nCount
BEGIN
	SELECT	@intBillNumberID = BillNumberId,
			@chvBillDate = BillDate,
			@chvBillCode = BillCode,
			@chvBillType = BillType,
			@chvATypeID = ATypeID,
			@chvATypeUserCode = ATypeUserCode,
			@chvATypeFullName = ATypeFullName,
			@chvSubjectCode = SubjectCode,
			@btypeidTemp = dealbtypeid,
			@intTotal_J = Total_J,
			@intTotal_D = Total_D,
			@chvchecke = Checke,
			@chvBtypeID = BtypeID,
			@chvETypeFullName = ETypeFullName,
			@chvBTypeFullName = BTypeFullName,
			@chvKTypeFullName = KTypeFullName,
			@chvExplain = Explain,
			@chvComment = Comment,
			@chvvoucherChar = voucherChar,
			@chvIfout = Ifout,
			@stypeidTemp = stypeid
	FROM	#TempInfo
	WHERE	nid = @i
	
	SET @first = @first + 1

	-- 若非同一 BillNumberID 单据号，则凭证号增 1
	IF @intBillNumberID <> @intBillNumberIDTemp
		BEGIN
			SET @intBillNumberIDTemp = @intBillNumberID
			SET @intPzh = @intPzh + 1	--				SET @chvComment = @chvJi + CAST(@intPzh AS varchar(10)) 	
			SET @FENTRYID = 0
		END
	ELSE
	BEGIN
		if  @first =1 
			SET @FENTRYID =0
		else
		BEGIN	
			-- 同一单据里面前后两个科目为应收或应付 表明科目相同，分录号不加1,最后需要聚合的

			IF (@chvATypeUserCode=@YSCode OR @chvATypeUserCode=@YFCode) AND  (@chvATypeUserCode_AN=@YSCode OR @chvATypeUserCode_AN=@YFCode)
				SET @FENTRYID =@FENTRYID 
			ELSE	
				SET @FENTRYID =@FENTRYID  + 1

			SET @FENTRYID =@FENTRYID  + 1
		END
	END

	-- 若科目编号在科目维护表中不存中，则不允许导出凭证
	IF NOT EXISTS(SELECT * FROM AccountSubjectSet WHERE ATypeID = @chvATypeID AND SoftType = @chvSoftType)
		SET @chvIfCanOutPut = 0
	ELSE
		SET @chvIfCanOutPut = 1
		
	
	IF @chvComment = '' 
	BEGIN
			IF	(@chrJudgeFlag='20' or @chrJudgeFlag='30')
				SET @chvComment = CONVERT(varchar(10), @chvBillDate, 126) + '导出凭证'+ @chvVoucherChar+ CAST(@intPzh AS varchar(10)) + '号'				
			ELSE	
				SET @chvComment = CONVERT(varchar(10), @chvBillDate, 126) + '导出凭证' +'记'+ CAST(@intPzh AS varchar(10)) + '号'
	END

	SELECT @chvCheckName=FullName From Employee where typeid=@chvchecke

	IF 	LEFT(@chvBtypeID,5) ='00001'
	BEGIN
		SET @chvBTypeFullName =@chvBTypeFullName
		SET @chvBTypeFullName1 =''
	END
	ELSE
	BEGIN
		SET @chvBTypeFullName1 =@chvBTypeFullName
		SET @chvBTypeFullName =''
	END				

	IF @TEMP_BillNumberID <> @intBillNumberID
	BEGIN
		IF @GridType ='1'
		BEGIN
			IF @TempTotal_J>@TempTotal_D
				INSERT INTO #AccountTemp (
				BillNumberID,
				PZH,
				IfCanOutPut,
				BillDate,
				BillCode,
				BillType,
				ATypeUserCode,

				ATypeFullName,
				SubjectCode,
				btypeid,
				Total_J,
				Total_D,
				CheckName,
				ETypeFullName,
				BTypeFullName,
				BTypeFullName1,
				KTypeFullName,
				Explain,
				Comment,
				voucherChar,
				Ifout,
				FENTRYID,
				stypeid
				
				)
				VALUES (
					@intBillNumberID_AN,
					@intPzh_AN,
					@chvIfCanOutPut_AN,
					@chvBillDate_AN,
					@chvBillCode_AN,
					@chvBillType_AN,
					'应交税金-销项税',
					'应交税金-销项税',
					'应交税金-销项税',
					@btypeidTemp_AN,
					0,
					@TempTotal_J-@TempTotal_D,
					@chvCheckName,
					@chvETypeFullName_AN,
					@chvBTypeFullName_AN,
					@chvBTypeFullName1_AN,
					@chvKTypeFullName_AN,
					@chvExplain_AN,
					@chvComment_AN,
					@chvvoucherChar_AN,
					@chvIfout_AN,
					@FENTRYID,
					@stypeidTemp_AN
					
				)
			IF @TempTotal_J<@TempTotal_D
				INSERT INTO #AccountTemp (
				BillNumberID,
				PZH,
				IfCanOutPut,
				BillDate,
				BillCode,
				BillType,
				ATypeUserCode,
				ATypeFullName,
				SubjectCode,
				btypeid,
				Total_J,
				Total_D,
				CheckName,
				ETypeFullName,
				BTypeFullName,
				BTypeFullName1,
				KTypeFullName,
				Explain,
				Comment,
				voucherChar,
				Ifout,	
				FENTRYID,
				stypeid
				)
				VALUES (
					@intBillNumberID_AN,
					@intPzh_AN,
					@chvIfCanOutPut_AN,
					@chvBillDate_AN,
					@chvBillCode_AN,
					@chvBillType_AN,
					'应交税金-进项税',
					'应交税金-进项税',
					'应交税金-进项税',
					@btypeidTemp_AN,
					@TempTotal_D-@TempTotal_J,
					0,
					
					@chvCheckName,
					@chvETypeFullName_AN,

					@chvBTypeFullName_AN,
					@chvBTypeFullName1_AN,
					@chvKTypeFullName_AN,
					@chvExplain_AN,
					@chvComment_AN,
					@chvvoucherChar_AN,
					@chvIfout_AN,
					@FENTRYID,
					@stypeidTemp_AN
					
				)
		END
	END


	--初始临时表
	INSERT INTO #AccountTemp (
		BillNumberID,
		PZH,
		IfCanOutPut,
		BillDate,
		BillCode,
		BillType,
		ATypeUserCode,
		ATypeFullName,
		SubjectCode,
		Total_J,
		Total_D,
		CheckName,
		ETypeFullName,
		BTypeFullName,
		BTypeFullName1,
		KTypeFullName,
		Explain,
		Comment,
		voucherChar,
		Ifout,
		FENTRYID,
		stypeid,
		btypeid
	)
	VALUES (
		@intBillNumberID,
		@intPzh,
		@chvIfCanOutPut,
		@chvBillDate,
		@chvBillCode,
		@chvBillType,
		@chvATypeUserCode,
		@chvATypeFullName,
		@chvSubjectCode,
		@intTotal_J,
		@intTotal_D,
		@chvCheckName,
		@chvETypeFullName,
		@chvBTypeFullName,
		@chvBTypeFullName1,
		@chvKTypeFullName,
		@chvExplain,
		@chvComment,
		@chvvoucherChar,
		@chvIfout,
		@FENTRYID,
		@stypeidTemp,
		@btypeidTemp
	)

	IF @GridType ='1'
	BEGIN
		IF @TEMP_BillNumberID = @intBillNumberID
		BEGIN
			SET @TempTotal_J = @TempTotal_J + @intTotal_J
			SET @TempTotal_D = @TempTotal_D + @intTotal_D
		END
		ELSE

		BEGIN
			SET @TempTotal_J =  @intTotal_J
			SET @TempTotal_D =  @intTotal_D
		END

		SET @TEMP_BillNumberID = @intBillNumberID
		SET @intBillNumberID_AN = @intBillNumberID
		SET @intPzh_AN = @intPzh
		SET @chvIfCanOutPut_AN =@chvIfCanOutPut
		SET @chvBillDate_AN =@chvBillDate
		SET @chvBillCode_AN =@chvBillCode
		SET @chvBillType_AN =@chvBillType
		SET @chvATypeID_AN =@chvATypeID
		SET @chvATypeUserCode_AN =@chvATypeUserCode
		SET @chvATypeFullName_AN =@chvATypeFullName
		SET @chvSubjectCode_AN =@chvSubjectCode
		SET @intTotal_J_AN =@intTotal_J
		SET @intTotal_D_AN =@intTotal_D
		SET	@chvCountOut_AN =@chvCountOut
		SET	@chvCountIn_AN =@chvCountIn
		SET @chvCheckName_AN =@chvCheckName
		SET	@chvBtypeID_AN = @chvBtypeID
		SET @chvETypeFullName_AN =@chvETypeFullName
		SET @chvBTypeFullName_AN =@chvBTypeFullName
		SET @chvBTypeFullName1_AN =@chvBTypeFullName1
		SET @chvKTypeFullName_AN =@chvKTypeFullName
		SET @BillCode_AN =@BillCode
		SET	@intFlag_AN	=@intFlag
	   	SET	@chvVoucherChar_AN  =@chvVoucherChar
		SET @chvComment_AN =@chvComment
		SET @chvExplain_AN = @chvExplain
		SET	@chvIfout_AN =	@chvIfout
		SET @stypeidTemp_AN=@stypeidTemp
		SET @btypeidTemp_AN=@btypeidTemp
	END

	SET @i = @i + 1
END			      

DROP TABLE #TempInfo			      
	
/*
DECLARE Rows_Cursor CURSOR FOR	
SELECT	b.BillNumberID,	-- 单据 ID 号
		a.BillDate,	-- 单据日期
		b.BillCode,	-- 单据编号
		b.BillType,	-- 单据类型
		ac.nid AS ATypeID,	-- 系统科目 ID 值
		ac.UserCode AS ATypeUserCode,	-- 系统科目编号
		ac.FullName AS ATypeFullName,	-- 系统科目名称
		g.SubjectCode,	-- 自定义科目编号
		b.btypeid,	-- 结算单位id

		Total_J = abs(CASE 
						WHEN g.J_D = 1 THEN 
							case 
								when a.Total >0 then a.total
							else
								0
							end
						WHEN g.J_D = 0 THEN 
							case 
								when a.Total >0 then 0
							else
								a.total
							end
						ELSE -- 没有配置科目时，资产，支出类科目默认为借方，负债，所有者权益，收入类默认为贷方
							case when ac.typename in('B','E','F','C')then 
								case 
									when a.Total >0 then a.total
								else
									0
								end	
							else 
								case 
									when a.Total >0 then 0
								else
									a.total
								end				
							end
								
						END),	-- 借方金额
		Total_D = abs(CASE 
						WHEN g.J_D = 1 THEN 
							case 
								when a.Total >0 then 0
							else
								a.total
							end
						WHEN g.J_D = 0 THEN 
							case 
								when a.Total >0 then a.total
							else
								0
							end
						ELSE
							case when ac.typename in('B','E','F','C') then 
								case 
									when a.Total >0 then 0
								else
									a.total
								end
							else
								case 
									when a.Total >0 then a.total
								else
									0
								end
							end
						END),	-- 贷方金额
		b.Checke,
		c.TypeID as BtypeID,
		d.FullName AS ETypeFullName,	-- 经手人名称
		c.FullName AS BTypeFullName,	-- 往来单位名称
		f.FullName AS KTypeFullName,	-- 仓库名称
		REPLACE(b.Explain,',',';') AS Explain,	-- 说明
		REPLACE(b.Comment,',',';')	AS Comment, -- 备注
		'记' AS voucherChar,  --凭证字
		a.Ifout, --是否为已导出凭证
		b.stypeid
FROM	ListTable a
LEFT JOIN AC_items ac on a.atypeid= ac.nid
LEFT JOIN BillIndex b ON a.BillNumberID = b.BillNumberID and a.billtype=b.billtype
LEFT JOIN BType c ON a.BTypeID = c.TypeID
LEFT JOIN Employee d ON a.ETypeID = d.TypeID
--LEFT JOIN AType e ON a.ATypeID = e.TypeID
LEFT JOIN Stock f ON f.TypeID = b.KTypeID
LEFT JOIN AccountSubjectSet g ON g.ATypeID = a.ATypeID AND g.SoftType = 'GJP_BiaoJunBan'
WHERE	a.Audited = '1'
		AND b.stypeid IN(SELECT typeid FROM #GetSelectSTypeId)
	 AND a.BillDate >= '2021-04-01' AND a.BillDate <= '2021-04-30' AND (
								(b.btypeid in (select typeid from #Btype) AND a.Billtype not in (115,116,128,129,159)) 
								OR 
								(a.Billtype in (115,116,128,129,159) AND a.BillnumberID in (SELECT BillnumberID FROM #BillnumberID)
								)
							) AND ( b.EtypeID IN (Select typeid from #Etype) or a.billtype=179 ) AND(
			b.KtypeID IN (Select typeid from #Ktype) 
			OR
			 a.billtype in(179,181,182,404,405,450)
			OR 
			 (a.billtype in (57) and b.ktypeid in('00000',''))
			OR 
			 (a.billtype in (188) and b.ktypeid2 in (Select typeid from #Ktype)  )
		    )	 AND 
			      b.DtypeID IN (Select typeid from #Dtype)  AND b.BillType = '4' AND (a.etypeid in (select typeid from #Etype))
 	

	OPEN Rows_Cursor

	FETCH NEXT FROM Rows_Cursor INTO	
						@intBillNumberID,
						@chvBillDate,
						@chvBillCode,
						@chvBillType,
						@chvATypeID,
						@chvATypeUserCode,
						@chvATypeFullName,
						@chvSubjectCode,
						@btypeidTemp,
						@intTotal_J,
						@intTotal_D,
						@chvchecke,
						@chvBtypeID,
						@chvETypeFullName,
						@chvBTypeFullName,
						@chvKTypeFullName,
						@chvExplain,
						@chvComment,
						@chvvoucherChar,
						@chvIfout,
						@stypeidTemp
						
	SET @intBillNumberIDTemp = @intBillNumberID
	

	WHILE ( @@FETCH_STATUS = 0 )
		BEGIN
			SET @first = @first + 1

			-- 若非同一 BillNumberID 单据号，则凭证号增 1
			IF @intBillNumberID <> @intBillNumberIDTemp
				BEGIN
					SET @intBillNumberIDTemp = @intBillNumberID
					SET @intPzh = @intPzh + 1	--				SET @chvComment = @chvJi + CAST(@intPzh AS varchar(10)) 	
					SET @FENTRYID = 0
				END
			ELSE
			BEGIN
				if  @first =1 
					SET @FENTRYID =0
				else
				BEGIN	
					-- 同一单据里面前后两个科目为应收或应付 表明科目相同，分录号不加1,最后需要聚合的
					/*
					IF (@chvATypeUserCode=@YSCode OR @chvATypeUserCode=@YFCode) AND  (@chvATypeUserCode_AN=@YSCode OR @chvATypeUserCode_AN=@YFCode)
						SET @FENTRYID =@FENTRYID 
					ELSE	
						SET @FENTRYID =@FENTRYID  + 1
					*/
					SET @FENTRYID =@FENTRYID  + 1
				END
			END

			-- 若科目编号在科目维护表中不存中，则不允许导出凭证
			--IF NOT EXISTS(SELECT * FROM AccountSubjectSet WHERE ATypeID = @chvATypeID AND SoftType = @chvSoftType)
			--	SET @chvIfCanOutPut = 0
			--ELSE
			--	SET @chvIfCanOutPut = 1
				
			
			IF @chvComment = '' 
			BEGIN
					IF	(@chrJudgeFlag='20' or @chrJudgeFlag='30')
						SET @chvComment = CONVERT(varchar(10), @chvBillDate, 126) + '导出凭证'+ @chvVoucherChar+ CAST(@intPzh AS varchar(10)) + '号'
						--SET @chvComment = CONVERT(varchar(10), @chvBillDate, 126) + '导出凭证' + CAST(@intPzh AS varchar(10)) + '号'
					ELSE	
						SET @chvComment = CONVERT(varchar(10), @chvBillDate, 126) + '导出凭证' +'记'+ CAST(@intPzh AS varchar(10)) + '号'
			END

			--SELECT @chvCheckName=FullName From Employee where typeid=@chvchecke

			IF 	LEFT(@chvBtypeID,5) ='00001'
			BEGIN
				SET @chvBTypeFullName =@chvBTypeFullName
				SET @chvBTypeFullName1 =''
			END
			ELSE
			BEGIN
				SET @chvBTypeFullName1 =@chvBTypeFullName
				SET @chvBTypeFullName =''
			END
				

			--IF @TEMP_BillNumberID <> @intBillNumberID
			--BEGIN
			--	IF @GridType ='1'
			--	BEGIN
			--		IF @TempTotal_J>@TempTotal_D
			--			INSERT INTO #AccountTemp (
			--			BillNumberID,
			--			PZH,
			--			IfCanOutPut,
			--			BillDate,
			--			BillCode,
			--			BillType,
			--			ATypeUserCode,

			--			ATypeFullName,
			--			SubjectCode,
			--			btypeid,
			--			Total_J,
			--			Total_D,
			--			CheckName,
			--			ETypeFullName,
			--			BTypeFullName,
			--			BTypeFullName1,
			--			KTypeFullName,
			--			Explain,
			--			Comment,
			--			voucherChar,
			--			Ifout,
			--			FENTRYID,
			--			stypeid
						
			--			)
			--			VALUES (
			--				@intBillNumberID_AN,
			--				@intPzh_AN,
			--				@chvIfCanOutPut_AN,
			--				@chvBillDate_AN,
			--				@chvBillCode_AN,
			--				@chvBillType_AN,
			--				'应交税金-销项税',
			--				'应交税金-销项税',
			--				'应交税金-销项税',
			--				@btypeidTemp_AN,
			--				0,
			--				@TempTotal_J-@TempTotal_D,
			--				@chvCheckName,
			--				@chvETypeFullName_AN,
			--				@chvBTypeFullName_AN,
			--				@chvBTypeFullName1_AN,
			--				@chvKTypeFullName_AN,
			--				@chvExplain_AN,
			--				@chvComment_AN,
			--				@chvvoucherChar_AN,
			--				@chvIfout_AN,
			--				@FENTRYID,
			--				@stypeidTemp_AN
							
			--			)
			--		IF @TempTotal_J<@TempTotal_D
			--			INSERT INTO #AccountTemp (
			--			BillNumberID,
			--			PZH,
			--			IfCanOutPut,
			--			BillDate,
			--			BillCode,
			--			BillType,
			--			ATypeUserCode,
			--			ATypeFullName,
			--			SubjectCode,
			--			btypeid,
			--			Total_J,
			--			Total_D,
			--			CheckName,
			--			ETypeFullName,
			--			BTypeFullName,
			--			BTypeFullName1,
			--			KTypeFullName,
			--			Explain,
			--			Comment,
			--			voucherChar,
			--			Ifout,	
			--			FENTRYID,
			--			stypeid
			--			)
			--			VALUES (
			--				@intBillNumberID_AN,
			--				@intPzh_AN,
			--				@chvIfCanOutPut_AN,
			--				@chvBillDate_AN,
			--				@chvBillCode_AN,
			--				@chvBillType_AN,
			--				'应交税金-进项税',
			--				'应交税金-进项税',
			--				'应交税金-进项税',
			--				@btypeidTemp_AN,
			--				@TempTotal_D-@TempTotal_J,
			--				0,
							
			--				@chvCheckName,
			--				@chvETypeFullName_AN,

			--				@chvBTypeFullName_AN,
			--				@chvBTypeFullName1_AN,
			--				@chvKTypeFullName_AN,
			--				@chvExplain_AN,
			--				@chvComment_AN,
			--				@chvvoucherChar_AN,
			--				@chvIfout_AN,
			--				@FENTRYID,
			--				@stypeidTemp_AN
							
			--			)
			--	END
			--END


			--初始临时表
			--INSERT INTO #AccountTemp (
			--	BillNumberID,
			--	PZH,
			--	IfCanOutPut,
			--	BillDate,
			--	BillCode,
			--	BillType,
			--	ATypeUserCode,
			--	ATypeFullName,
			--	SubjectCode,
			--	Total_J,
			--	Total_D,
			--	CheckName,
			--	ETypeFullName,
			--	BTypeFullName,
			--	BTypeFullName1,
			--	KTypeFullName,
			--	Explain,
			--	Comment,
			--	voucherChar,
			--	Ifout,
			--	FENTRYID,
			--	stypeid,
			--	btypeid
			--)
			--VALUES (
			--	@intBillNumberID,
			--	@intPzh,
			--	@chvIfCanOutPut,
			--	@chvBillDate,
			--	@chvBillCode,
			--	@chvBillType,
			--	@chvATypeUserCode,
			--	@chvATypeFullName,
			--	@chvSubjectCode,
			--	@intTotal_J,
			--	@intTotal_D,
			--	@chvCheckName,
			--	@chvETypeFullName,
			--	@chvBTypeFullName,
			--	@chvBTypeFullName1,
			--	@chvKTypeFullName,
			--	@chvExplain,
			--	@chvComment,
			--	@chvvoucherChar,
			--	@chvIfout,
			--	@FENTRYID,
			--	@stypeidTemp,
			--	@btypeidTemp
			--)

			IF @GridType ='1'
			BEGIN
				IF @TEMP_BillNumberID = @intBillNumberID
				BEGIN
					SET @TempTotal_J = @TempTotal_J + @intTotal_J
					SET @TempTotal_D = @TempTotal_D + @intTotal_D
				END
				ELSE

				BEGIN
					SET @TempTotal_J =  @intTotal_J
					SET @TempTotal_D =  @intTotal_D
				END
	
				SET @TEMP_BillNumberID = @intBillNumberID
				SET @intBillNumberID_AN = @intBillNumberID
				SET @intPzh_AN = @intPzh
				SET @chvIfCanOutPut_AN =@chvIfCanOutPut
				SET @chvBillDate_AN =@chvBillDate
				SET @chvBillCode_AN =@chvBillCode
				SET @chvBillType_AN =@chvBillType
				SET @chvATypeID_AN =@chvATypeID
				SET @chvATypeUserCode_AN =@chvATypeUserCode
				SET @chvATypeFullName_AN =@chvATypeFullName
				SET @chvSubjectCode_AN =@chvSubjectCode
				SET @intTotal_J_AN =@intTotal_J
				SET @intTotal_D_AN =@intTotal_D
				SET	@chvCountOut_AN =@chvCountOut
				SET	@chvCountIn_AN =@chvCountIn
				SET @chvCheckName_AN =@chvCheckName
				SET	@chvBtypeID_AN = @chvBtypeID
				SET @chvETypeFullName_AN =@chvETypeFullName
				SET @chvBTypeFullName_AN =@chvBTypeFullName
				SET @chvBTypeFullName1_AN =@chvBTypeFullName1
				SET @chvKTypeFullName_AN =@chvKTypeFullName
				SET @BillCode_AN =@BillCode
				SET	@intFlag_AN	=@intFlag
			   	SET	@chvVoucherChar_AN  =@chvVoucherChar
				SET @chvComment_AN =@chvComment
				SET @chvExplain_AN = @chvExplain
				SET	@chvIfout_AN =	@chvIfout
				SET @stypeidTemp_AN=@stypeidTemp
				SET @btypeidTemp_AN=@btypeidTemp
			END



		FETCH NEXT FROM Rows_Cursor INTO	@intBillNumberID,
							@chvBillDate,
							@chvBillCode,
							@chvBillType,
							@chvATypeID,
							@chvATypeUserCode,
							@chvATypeFullName,
							@chvSubjectCode,
							@btypeidTemp,
							@intTotal_J,
							@intTotal_D,
							@chvChecke,
							@chvBtypeID,
							@chvETypeFullName,
							@chvBTypeFullName,
							@chvKTypeFullName,
							@chvExplain,
							@chvComment,
							@chvvoucherChar,
							@chvIfout,
							@stypeidTemp
							
		END

	CLOSE Rows_Cursor
	DEALLOCATE Rows_Cursor
*/	
	

	
IF @GridType='1'
BEGIN
	IF @TempTotal_J>@TempTotal_D
			INSERT INTO #AccountTemp (
			BillNumberID,
			PZH,
			IfCanOutPut,
			BillDate,
			BillCode,
			BillType,
			ATypeUserCode,
			ATypeFullName,
			SubjectCode,
			Total_J,
			Total_D,
			CheckName,
			ETypeFullName,
			BTypeFullName,
			BTypeFullName1,
			KTypeFullName,
			Explain,
			Comment,
			voucherChar,
			Ifout,
			FENTRYID,
			stypeid,
			btypeid
			)
			VALUES (
				@intBillNumberID_AN,
				@intPzh_AN,
				@chvIfCanOutPut_AN,
				@chvBillDate_AN,
				@chvBillCode_AN,
				@chvBillType_AN,
				'应交税金-销项税',
				'应交税金-销项税',
				'应交税金-销项税',
				0,
				@TempTotal_J-@TempTotal_D,
				@chvCheckName,
				@chvETypeFullName_AN,
				@chvBTypeFullName_AN,
				@chvBTypeFullName1_AN,
				@chvKTypeFullName_AN,
				@chvExplain_AN,
				@chvComment_AN,
				@chvvoucherChar_AN,
				@chvIfout_AN,
				@FENTRYID,
				@stypeidTemp_AN,
				@btypeidTemp_AN
			)
		IF @TempTotal_J<@TempTotal_D
			INSERT INTO #AccountTemp (
			BillNumberID,
			PZH,
			IfCanOutPut,
			BillDate,
			BillCode,
			BillType,
			ATypeUserCode,
			ATypeFullName,
			SubjectCode,
			Total_J,
			Total_D,
			CheckName,
			ETypeFullName,
			BTypeFullName,
			BTypeFullName1,
			KTypeFullName,
			Explain,
			Comment,
			voucherChar,
			Ifout,
			FENTRYID,
			stypeid,
			btypeid
			)
			VALUES (
				@intBillNumberID_AN,
				@intPzh_AN,
				@chvIfCanOutPut_AN,
				@chvBillDate_AN,
				@chvBillCode_AN,
				@chvBillType_AN,
				'应交税金-进项税',
				'应交税金-进项税',
				'应交税金-进项税',
				@TempTotal_D-@TempTotal_J,
				0,
				@chvCheckName,
				@chvETypeFullName_AN,
				@chvBTypeFullName_AN,
				@chvBTypeFullName1_AN,
				@chvKTypeFullName_AN,
				@chvExplain_AN,
				@chvComment_AN,
				@chvvoucherChar_AN,
				@chvIfout_AN,
				@FENTRYID,
				@stypeidTemp_AN,
				@btypeidTemp_AN
			)
	END
	
-- 置行号数据 - Start
UPDATE	#AccountTemp
SET		IfCanOutPut = 0
WHERE	BillNumberID IN (
	SELECT	BillNumberID
	FROM	#AccountTemp
	WHERE	IfCanOutPut = 0
)

UPDATE	#AccountTemp
SET		IfCanOutPut = 1
WHERE	BillNumberID IN (
	SELECT	BillNumberID
	FROM	#AccountTemp
	WHERE	IfCanOutPut = 1
)
	-- 置行号数据 - End


IF @flag <>1
BEGIN	
	-- 删除已导出凭证
	IF @chvPZ ='0'
	BEGIN
		DELETE FROM #AccountTemp
		WHERE IfOut = '1'
	END

	UPDATE #AccountTemp SET JD='1' where Total_J>0
	UPDATE #AccountTemp SET JD='0' where Total_D>0
	

	
	--SELECT * FROM #AccountTemp
	-- 销售出库单,委托代销结算,维修受理单,应收款增加,其他收入单,固定资产变卖,优惠券出库单 ==== 应收增加，记借方
	UPDATE #AccountTemp SET AtypeUserCode =@YSCode,AtypeFUllName ='『应收款合计』',SubjectCode=@YS_TypeID WHERE AtypeUserCode =@YFCode  AND Billtype in(11,141,157,116,93,85,160,167,168,172,424) --AND JD='1'
	
	-- 销售退货单,收款单,应收款减少,返利核算执行,价保执行,优惠券退货  ==== 应收减少，记贷方
	UPDATE #AccountTemp SET AtypeUserCode =@YSCode,AtypeFUllName ='『应收款合计』',SubjectCode=@YS_TypeID WHERE AtypeUserCode =@YFCode AND Billtype in(4,45,115,148,149,426) --AND JD='0' 
	
	-- 采购入库单,受托代销结算,应付款增加,费用单,固定资产购买,优惠券入库单 ==== 应付增加，记贷方
	UPDATE #AccountTemp SET AtypeUserCode =@YFCode,AtypeFUllName ='『应付账款合计』',SubjectCode=@YF_TypeID WHERE AtypeUserCode =@YSCode  AND Billtype in(34,145,128,36,84,161,170,423) --AND JD='0'
	
	-- 采购退货单,付款单,应付款减少,获得核算执行,获得价保 ==== 应付减少，记借方
	UPDATE #AccountTemp SET AtypeUserCode =@YFCode,AtypeFUllName ='『应付账款合计』',SubjectCode=@YF_TypeID WHERE AtypeUserCode =@YSCode  AND Billtype in(6,66,129,150,151)-- AND JD='1'
	
	
	/*UPDATE #AccountTemp
	SET AtypeUserCode = CASE WHEN AtypeUserCode =@YFCode AND Billtype in(11,141,157,116,93,85,160,167,168,172,  4,45,115,148,149)
								THEN @YSCode
							 WHEN SubjectCode = @YSCode AND Billtype in(34,145,128,36,84,161,170 ,  6,66,129,150,151)
								THEN @YFCode
						END,
		
		AtypeFUllName = CASE WHEN AtypeUserCode =@YFCode AND Billtype in(11,141,157,116,93,85,160,167,168,172,  4,45,115,148,149)
								THEN '『应收款合计』'
							 WHEN SubjectCode = @YSCode AND Billtype in(34,145,128,36,84,161,170 ,  6,66,129,150,151)
								THEN '『应付账款合计』'
						END,
		
		SubjectCode = CASE WHEN AtypeUserCode =@YFCode AND Billtype in(11,141,157,116,93,85,160,167,168,172,  4,45,115,148,149)
								THEN @YS_TypeID
							 WHEN SubjectCode = @YSCode AND Billtype in(34,145,128,36,84,161,170 ,  6,66,129,150,151)
								THEN @YF_TypeID
						END
   */

	-- 上面特殊处理后，需要此处也处理
	UPDATE #AccountTemp SET IfCanOutPut ='0'
	UPDATE #AccountTemp 
	SET IfCanOutPut ='1' 
	WHERE (ATypeUserCode in (Select UserCode FROM Ac_Items WHERE nId in (SELECT AtypeID FROM AccountSubjectSet WHERE SoftType = @chvSoftType))  OR ATypeUserCode='应交税金-销项税' OR ATypeUserCode='应交税金-进项税')
	

	-- 特殊处理相关科目  应收应付的昨界点 ==见测试平台 5876
	UPDATE #AccountTemp SET AtypeUserCode='应交税金-销项税', AtypeFullName ='应交税金-销项税',SubjectCode='应交税金-销项税' where  (Billtype ='11' or Billtype ='45' or Billtype ='305') AND AtypeFullName ='应交税金-进项税'		
	UPDATE #AccountTemp SET AtypeUserCode='应交税金-进项税', AtypeFullName ='应交税金-进项税',SubjectCode='应交税金-进项税' where  (Billtype ='34' or Billtype ='6') AND AtypeFullName ='应交税金-销项税'		


	-- 凭证排序
	UPDATE #AccountTemp SET strOrder ='1'
	UPDATE #AccountTemp SET strOrder ='2' where Billtype in ('11','34') AND AtypeFullName ='『库存商品总值合计』'
	UPDATE #AccountTemp SET strOrder ='3' where (Billtype= '34' AND AtypeFullName ='应交税金-进项税') or (Billtype ='11' AND AtypeFullName='『应收款合计』')
	UPDATE #AccountTemp SET strOrder ='4' where (Billtype= '34' AND AtypeFullName ='『应付账款合计』') or (Billtype ='11' AND AtypeFullName='『销售收入』')
	UPDATE #AccountTemp SET strOrder ='5' where  Billtype ='11' AND AtypeFullName ='应交税金-销项税'		
	UPDATE #AccountTemp SET strOrder ='6' where  Billtype ='11' AND AtypeFullName ='『销售成本』'		


	-- 导出凭证,金碟标准版7.0的应交税金单独处理  2004-12-17 chen_qihua  
	IF @chvSoftType='JD_BiaoJunBanV7.0' and @chvIfOutPutData ='1'
	BEGIN
		UPDATE #AccountTemp SET AtypeUserCode ='2210101',AtypeFullName ='2210101',SubjectCode ='2210101' WHERE 	AtypeFullName ='应交税金-进项税'	
		UPDATE #AccountTemp SET AtypeUserCode ='2210102',AtypeFullName ='2210102',SubjectCode ='2210102' WHERE 	AtypeFullName ='应交税金-销项税'	
	END


	
	-- 因为相同的凭证在聚全，所以再凭证排序

	UPDATE #AccountTemp SET strOrder ='3' where (Billtype= '34' AND AtypeFullName ='应交税金-进项税') or (Billtype ='11' AND AtypeFullName='『应收款合计』')
	UPDATE #AccountTemp SET strOrder ='4' where (Billtype= '34' AND AtypeFullName ='『应付账款合计』') or (Billtype ='11' AND AtypeFullName='『销售收入』')
	
	-- 系统科目没有维护，凭证不能输出 BEGIN
	UPDATE	#AccountTemp
	SET		IfCanOutPut = 0
	WHERE	BillNumberID IN (
		SELECT	BillNumberID
		FROM	#AccountTemp
		WHERE	IfCanOutPut = 0
	)
	
	UPDATE	#AccountTemp
	SET		IfCanOutPut = 1
	WHERE	BillNumberID IN (
		SELECT	BillNumberID
		FROM	#AccountTemp
		WHERE	IfCanOutPut = 1
	)
	--SELECT * FROM #AccountTemp
	------------------------=== END 
	
	-- 删除不可导出的凭证数据
	IF @chvIfOutPutData = '1'
	BEGIN
		DELETE FROM #AccountTemp
		WHERE IfCanOutPut = 0
	END
	IF @chvIfOutPutData ='1' -- 导出凭证时，摘要长度要单独处理
	BEGIN
		IF @chvSoftType='YY_' OR @chvSoftType='GJP_BiaoJunBan1' OR @chvSoftType='JD_BiaoJunBanV7.0'  -- 30个汉字长度
		BEGIN
			UPDATE #AccountTemp SET Comment=left(comment,30) WHERE datalength(comment)>=60
		END
		ELSE IF  @chvSoftType='JD_K3' --255
		BEGIN
			UPDATE #AccountTemp SET Comment=left(comment,127) WHERE datalength(comment)>=255
		END
	END


	-- 因为每种单据的特殊处理，所以凭证需要聚合
	SELECT 
		BillNumberID,PZH,IfCanOutPut,BillDate,BillCode,BillType,ATypeUserCode,ATypeFullName,SubjectCode,sum(Total_J) as Total_J,Sum(Total_D) as Total_D,CheckName,ETypeFullName,BTypeFullName,BTypeFullName1,KTypeFullName,Explain,Comment,Ji,voucherChar,Ifout,JD,strOrder,FENTRYID,stypeid
	FROM
		#AccountTemp  
	GROUP BY 
		BillNumberID,PZH,IfCanOutPut,BillDate,BillCode,BillType,ATypeUserCode,ATypeFullName,SubjectCode,CheckName,ETypeFullName,BTypeFullName,BTypeFullName1,KTypeFullName,Explain,Comment,Ji,voucherChar,Ifout,JD,strOrder,FENTRYID,stypeid
	ORDER BY 
		PZH, BillNumberID ,strOrder asc 

	IF @chvIfOutPutData ='1'
		UPDATE ListTable SET Ifout ='1' where BillnumberID in (SELECT BillnumberID From #AccountTemp)
		
		
	DROP TABLE #AccountTemp		
END
ELSE --以下用于合并凭证
BEGIN
	--SELECT * FROM #AccountTemp

	DECLARE @intPzh1 int
	DECLARE @FENTRYID1 int 
	SET @FENTRYID1 =0 
	DECLARE @FirstHj int 
	SET @FirstHj =0
	
	
	IF @chvPZ ='0'
	BEGIN
		DELETE FROM #AccountTemp
		WHERE IfOut = '1'
	END
	IF @chvIfOutPutData ='1'
		UPDATE ListTable SET Ifout ='1' where BillnumberID in (SELECT BillnumberID From #AccountTemp)
	-- 特殊处理相关科目  应收应付的昨界点 ==见测试平台 5876
	-- 特殊处理相关科目  应收应付的昨界点 ==见测试平台 5876
	UPDATE #AccountTemp SET AtypeUserCode='应交税金-销项税', AtypeFullName ='应交税金-销项税',SubjectCode='应交税金-销项税' where  (Billtype ='11' or Billtype ='45' or Billtype ='305') AND AtypeFullName ='应交税金-进项税'
	UPDATE #AccountTemp SET AtypeUserCode='应交税金-进项税', AtypeFullName ='应交税金-进项税',SubjectCode='应交税金-进项税' where  (Billtype ='34' or Billtype ='6') AND AtypeFullName ='应交税金-销项税'
	-- 导出凭证,金碟标准版7.0的应交税金单独处理  2004-12-17 chen_qihua
	IF @chvSoftType='JD_BiaoJunBanV7.0' and @chvIfOutPutData ='1'
	BEGIN
		UPDATE #AccountTemp SET AtypeUserCode ='2210101',AtypeFullName ='2210101',SubjectCode ='2210101' WHERE 	AtypeFullName ='应交税金-进项税'	
		UPDATE #AccountTemp SET AtypeUserCode ='2210102',AtypeFullName ='2210102',SubjectCode ='2210102' WHERE 	AtypeFullName ='应交税金-销项税'	
	END

	UPDATE #AccountTemp SET JD='1' where Total_J>0
	UPDATE #AccountTemp SET JD='0' where Total_D>0

	
	-- 销售出库单,委托代销结算,维修受理单,应收款增加,其他收入单,固定资产变卖,优惠券出库单==== 应收增加，记借方
	UPDATE #AccountTemp SET AtypeUserCode =@YSCode,AtypeFUllName ='『应收款合计』',SubjectCode=@YS_TypeID WHERE AtypeUserCode =@YFCode  AND Billtype in(11,141,157,116,93,85,424) --AND JD='1'
	
	-- 销售退货单,收款单,应收款减少,返利核算执行,价保执行,优惠券退货单  ==== 应收减少，记贷方
	UPDATE #AccountTemp SET AtypeUserCode =@YSCode,AtypeFUllName ='『应收款合计』',SubjectCode=@YS_TypeID WHERE AtypeUserCode =@YFCode AND Billtype in(4,45,115,148,149,426) --AND JD='0' 
	
	-- 采购入库单,受托代销结算,应付款增加,费用单,固定资产购买,优惠券入库单 ==== 应付增加，记贷方
	UPDATE #AccountTemp SET AtypeUserCode =@YFCode,AtypeFUllName ='『应付账款合计』',SubjectCode=@YF_TypeID WHERE AtypeUserCode =@YSCode  AND Billtype in(34,145,128,36,84,423) --AND JD='0'
	
	-- 采购退货单,付款单,应付款减少,获得核算执行,获得价保 ==== 应付减少，记借方
	UPDATE #AccountTemp SET AtypeUserCode =@YFCode,AtypeFUllName ='『应付账款合计』',SubjectCode=@YF_TypeID WHERE AtypeUserCode =@YSCode  AND Billtype in(6,66,129,150,151)-- AND JD='1'
	
/*
	UPDATE #AccountTemp 
	SET AtypeUserCode = CASE WHEN AtypeUserCode =@YFCode  AND Billtype in(11,141,157,116,93,85,   4,45,115,148,149)
								THEN @YSCode
							 WHEN AtypeUserCode =@YSCode  AND Billtype in(34,145,128,36,84, 6,66,129,150,151)
								THEN @YFCode
						END,
		AtypeFUllName = CASE WHEN AtypeUserCode =@YFCode  AND Billtype in(11,141,157,116,93,85,   4,45,115,148,149)
								THEN '『应收款合计』'
							 WHEN AtypeUserCode =@YSCode  AND Billtype in(34,145,128,36,84, 6,66,129,150,151)
								THEN '『应付账款合计』'
						END,
		SubjectCode = CASE WHEN AtypeUserCode =@YFCode  AND Billtype in(11,141,157,116,93,85,   4,45,115,148,149)
								THEN @YS_TypeID
							 WHEN AtypeUserCode =@YSCode  AND Billtype in(34,145,128,36,84, 6,66,129,150,151)
								THEN @YF_TypeID
						END
		*/
	-- 上面特殊处理后，需要此处也处理
	UPDATE #AccountTemp SET IfCanOutPut ='0'
	UPDATE #AccountTemp SET IfCanOutPut ='1' WHERE (ATypeUserCode in (Select UserCode FROM Ac_Items WHERE nId in (SELECT AtypeID FROM AccountSubjectSet WHERE SoftType = @chvSoftType)) OR ATypeUserCode='应交税金-销项税' OR ATypeUserCode='应交税金-进项税')
	
	-- 系统科目没有维护，凭证不能输出 BEGIN

	UPDATE	#AccountTemp
	SET		IfCanOutPut = 0
	WHERE	BillNumberID IN (
		SELECT	BillNumberID
		FROM	#AccountTemp
		WHERE	IfCanOutPut = 0
	)
	
	UPDATE	#AccountTemp
	SET		IfCanOutPut = 1
	WHERE	BillNumberID IN (
		SELECT	BillNumberID
		FROM	#AccountTemp
		WHERE	IfCanOutPut = 1
	)

	DELETE #AccountTemp WHERE IfCanOutPut = 0

	
	CREATE TABLE #AccountTemp1 

	(
		BillNumberID	int,		-- 单据 ID 号
		PZH		int,		-- 凭证号
		IfCanOutPut	varchar(10),	-- 凭证是否可以导出标识
		BillDate	datetime,	-- 单据日期
		BillCode	varchar(200),	-- 单据编号
		BillType	int,			-- 单据类型
		ATypeUserCode	varchar(200),	-- 系统科目编号
		ATypeFullName	varchar(200),	-- 系统科目名称
		SubjectCode	varchar(100),	-- 自定义科目编号
		Total_J		 NUMERIC(24, 10) ,	-- 借方金额
		Total_D		 NUMERIC(24, 10) ,	-- 贷方金额
		CheckName      varchar(200),
		ETypeFullName	varchar(200),	-- 经手人名称
		BTypeFullName	varchar(200),	-- 往来单位名称
		BTypeFullName1	varchar(200),	-- 往来单位名称
		KTypeFullName	varchar(200),	-- 仓库名称
		Explain		varchar(256),	-- 说明
		Comment		varchar(256),	-- 摘要
		voucherChar varchar(10),--凭证字
		JD              char(1),        -- 借方还是货方
		FENTRYID        numeric(18,0),   -- 分录号（从0开始）
		strOrder    char(10)
	)

	DECLARE @chvBillType1 int -- 为了防止凭证号不等而设置的,如果某单据的会计科目多了科目（如优惠金额），这样会导致 相同单据 凭证号不等
	SET @chvBillType1 = 0
	SET @intPzh = 1
	DECLARE select_cursor CURSOR FAST_FORWARD FOR SELECT BillType,ATypeUserCode,btypeid FROM #AccountTemp GROUP BY BillType,ATypeUserCode,btypeid ORDER BY BillType
	OPEN select_cursor
	FETCH NEXT FROM select_cursor INTO @chvBillType,@chvATypeUserCode,@btypeidTemp
	while @@fetch_status = 0 
	BEGIN
		SELECT  @chvCountOut = sum(Total_J),@chvCountIn = sum(Total_D)FROM #AccountTemp WHERE BillType=@chvBillType AND ATypeUserCode=@chvATypeUserCode AND btypeid = @btypeidTemp
		IF @chvCountOut > @chvCountIn
		BEGIN 
			SET @chvCountOut = @chvCountOut - @chvCountIn
			SET @chvCountIn  = 0
		END
		IF @chvCountOut < @chvCountiN
		BEGIN 
			SET @chvCountIn = @chvCountIn - @chvCountOut
			SET @chvCountOut = 0
		END
		IF @chvCountOut = @chvCountiN
		BEGIN 
			SET @chvCountIn = 0
			SET @chvCountOut = 0
		END
		IF NOT (@chvCountOut=0 AND @chvCountIn=0)-- 当借货两者都为0时不处理
		BEGIN
			SET @intPzh1 = @intPzh
			SET @FirstHj = @FirstHj + 1
			
			SELECT	--@intPzh = PZH ,
				@chvIfCanOutPut = '1',
				@chvBillCode = BillCode,@chvBillType=BillType,
				@chvATypeUserCode = ATypeUserCode ,@chvATypeFullName = ATypeFullName,
				@chvSubjectCode = SubjectCode ,@chvETypeFullName = ETypeFullName,
				@chvBTypeFullName = isnull(BTypeFullName,''), @chvKTypeFullName =isnull(KTypeFullName,''),
				@chvExplain = Explain ,@chvComment = Comment ,
				@chvJi = Ji,@chvvoucherChar=voucherChar,@chvCheckName=CheckName,@chvBTypeFullName1=isnull(BTypeFullName1,'')
			FROM #AccountTemp WHERE BillType=@chvBillType AND ATypeUserCode=@chvATypeUserCode AND btypeid = @btypeidTemp
			
			IF @chvBillType1=0
			BEGIN
				SET @FENTRYID1 = 0
				SELECT @chvBillDate = BillDate FROM #AccountTemp WHERE BillType=@chvBillType AND ATypeUserCode=@chvATypeUserCode AND btypeid = @btypeidTemp--徐辉 同一个凭证号只能相同的日期
			END
			ELSE
			BEGIN
				IF @chvBillType1<>@chvBillType
				BEGIN
					SET @intPzh = @intPzh + 1		
					SET @FENTRYID1 = 0
					SELECT @chvBillDate = BillDate FROM #AccountTemp WHERE BillType=@chvBillType AND ATypeUserCode=@chvATypeUserCode AND btypeid = @btypeidTemp--徐辉 同一个凭证号只能相同的日期
				END
				ELSE
				BEGIN
					SET @FENTRYID1 = @FENTRYID1 + 1
				END
			END	
		
	
			/*IF @intPzh1<>@intPzh
					SET @FENTRYID1 = 0
			ELSE
				SET @FENTRYID1 = @FENTRYID1 + 1
			*/	
			SET @intPzh1 = @intPzh
			SET @chvBillType1 = @chvBillType	
				INSERT INTO #AccountTemp1 (
					BillNumberID,
					PZH,
					IfCanOutPut,
					BillDate,
					BillCode,
					BillType,
					ATypeUserCode,
					ATypeFullName,
					SubjectCode,
					Total_J,
					Total_D,
					CheckName,
					ETypeFullName,
					BTypeFullName,
					BTypeFullName1,
					KTypeFullName,
					Explain,
					Comment,
					FENTRYID,
					voucherChar
				)
				VALUES (
					@intBillNumberID,
					@intPzh,
					@chvIfCanOutPut,
					@chvBillDate,
					@chvBillCode,
					@chvBillType,
					@chvATypeUserCode,
					@chvATypeFullName,
					@chvSubjectCode,
					@chvCountOut,
					@chvCountIn,
					@chvCheckName,
					@chvETypeFullName,
					@chvBTypeFullName,
					@chvBTypeFullName1,
					@chvKTypeFullName,
					@chvExplain,
					@chvComment,
					@FENTRYID1,
					@chvvoucherChar
				)
		END
			FETCH NEXT FROM select_cursor INTO @chvBillType,@chvATypeUserCode,@btypeidTemp
	END
	CLOSE select_cursor
	DEALLOCATE select_cursor



	-- 凭证排序
	UPDATE #AccountTemp1 SET strOrder ='1'
	UPDATE #AccountTemp1 SET strOrder ='2' where Billtype in ('11','34') AND AtypeFullName ='『库存商品总值合计』'
	UPDATE #AccountTemp1 SET strOrder ='3' where (Billtype= '34' AND AtypeFullName ='应交税金-进项税') or (Billtype ='11' AND AtypeFullName='『应收款合计』')
	UPDATE #AccountTemp1 SET strOrder ='4' where (Billtype= '34' AND AtypeFullName ='『应付账款合计』') or (Billtype ='11' AND AtypeFullName='『销售收入』')
	UPDATE #AccountTemp1 SET strOrder ='5' where  Billtype ='11' AND AtypeFullName ='应交税金-销项税'		
	UPDATE #AccountTemp1 SET strOrder ='6' where  Billtype ='11' AND AtypeFullName ='『销售成本』'	



	UPDATE #AccountTemp1 SET JD='1' where Total_J>0
	UPDATE #AccountTemp1 SET JD='0' where Total_D>0


	IF @chvIfOutPutData ='1' -- 导出凭证时，摘要长度要单独处理
	BEGIN
		IF @chvSoftType='YY_' OR @chvSoftType='GJP_BiaoJunBan1' OR @chvSoftType='JD_BiaoJunBanV7.0'  -- 30个汉字长度
		BEGIN
			UPDATE #AccountTemp1 SET Comment=left(comment,30) WHERE datalength(comment)>=60
		END
		ELSE IF  @chvSoftType='JD_K3' --255
		BEGIN
			UPDATE #AccountTemp1 SET Comment=left(comment,127) WHERE datalength(comment)>=255
		END
	END
	--DELETE #AccountTemp1 WHERE Total_J =0 AND Total_D = 0
   
  
		SELECT * FROM #AccountTemp1 
		order by pzh, Billtype,strOrder ASC
	
	
	DROP TABLE #AccountTemp
	DROP TABLE #AccountTemp1
END
		

DROP TABLE #BillnumberID,#GetSelectSTypeId,#Btype,#Etype,#Ktype,#Dtype



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_InventoryStatistics]') and OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].Web_InventoryStatistics
GO



/*
库存积压统计
李灏龙 2011-12-9
增加零售退货单 2013-06-18
*/
CREATE PROCEDURE Web_InventoryStatistics
(
	@stypeid	VARCHAR(50),
	@ktypeid	VARCHAR(50),
	@jstype		INT,
	@enddate	DATE,
	@opratorid	VARCHAR(100),
	@js			 NUMERIC(24, 10) 
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #ptype
(
	typeid VARCHAR(8000)
)
INSERT INTO #ptype 
SELECT typeid 
FROM F_GetAllManagerBASeTypeId('',1,@opratorid)
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ktype(typeid VARCHAR(100))
INSERT INTO #Ktype
SELECT * FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@opratorid)

CREATE TABLE #stype(typeid VARCHAR(100))
INSERT INTO #stype
SELECT * FROM F_GetAllManagerBaseTypeId(@stypeid,11,@opratorid)

CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @opratorid AND MangerPTypeID = '00000')
BEGIN
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeID FROM PType WHERE SonNum = 0
END
ELSE
BEGIN
	INSERT INTO #GetManPTypeId(TypeId)
	SELECT	DISTINCT P.TypeId 
	FROM	PType_L L
	INNER JOIN PType  P ON P.TypeId LIKE L.TypeId + '%'
	WHERE	L.etypeid = @opratorid
			AND L.flag = 1 
			AND P.sonnum = 0
END

CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) 
	SELECT A.Typeid 
	FROM F_GetAllBaseTypeId(@ktypeid,4) AS A  
	INNER JOIN F_GetManDetailKTypeSType(@opratorid) mk  ON A.TypeId=mk.TypeId
	INNER JOIN #stype s ON mk.STypeId=s.TypeId

CREATE TABLE #Price(Ptypeid VARCHAR(100),Price  NUMERIC(24, 10) )
INSERT #Price(Ptypeid,Price)
	SELECT PtypeId,SUM(Total)/SUM(Qty) AS Price
	FROM   GoodsStocks G
	INNER JOIN #GetManPTypeId P ON P.TypeId = G.PtypeId
	INNER JOIN #GetManKTypeId MK ON MK.TypeId = G.KtypeId
	GROUP BY PtypeId
	HAVING SUM(Qty) <> 0

CREATE TABLE #goodsstocks
(
	qty			 NUMERIC(24, 10) ,
	ptypeid		VARCHAR(100)
)

--IF DATEDIFF(DAY,CONVERT(DATE, GETDATE()), @enddate) >= 0
--BEGIN
--	INSERT	#goodsstocks(ptypeid,qty)
--	SELECT	s.PtypeId,
--			ISNULL(SUM(s.qty),0) AS qty
--	FROM	GoodsStocks s
--	INNER JOIN #ptype p on p.typeid = s.PtypeId
--	INNER JOIN #Ktype k on k.typeid = s.KtypeId
--	INNER JOIN (SELECT k.typeId
--						FROM	STOCK k
--						INNER JOIN	#stype G ON G.TypeId = k.STypeID
--						) T ON T.typeId = s.KtypeId
--	GROUP BY s.PtypeId
--	HAVING SUM(s.Qty) <> 0
--END
--ELSE
--BEGIN
--	INSERT #goodsstocks(ptypeid,qty)
--	SELECT A.PtypeId,ISNULL(SUM(a.Qty),0)
--	FROM(
--		SELECT	i.PtypeId,
--				i.Qty
--		FROM	InOutstocktable i
--		INNER JOIN #Ktype k ON k.typeid = i.KtypeId
--		INNER JOIN #ptype p on p.typeid = i.PtypeId
--		INNER JOIN #stype s on s.typeid = i.STypeID
--		WHERE	BillDate <= @enddate
--				AND I.BillType IN (6,9,11,14,16,17,21,34,45,57,126,139,140,142,144,146,160,161,166,168,172,173,174,183,187,188,201,202,305)
--				AND I.Audited = 1
--				AND I.KtypeId <> '10000'
--		UNION ALL
--		SELECT	I.PtypeId,i.Qty
--		FROM	IniGoodsStocks I
--		INNER JOIN #ptype p on p.typeid = I.PtypeId
--		INNER JOIN #Ktype K ON K.typeid = I.KtypeId
--		INNER JOIN (SELECT k.typeId
--						FROM	STOCK k
--						INNER JOIN	#stype G ON G.TypeId = k.STypeID
--						) T ON T.typeId = I.KtypeId
--	)A
--	GROUP BY A.PtypeId
--END

INSERT #goodsstocks(ptypeid,qty)
	SELECT A.PtypeId,ISNULL(SUM(a.Qty),0) as qty
	FROM(
		SELECT	i.PtypeId,
				CASE WHEN i.BillType=57 THEN 0 ELSE i.Qty END Qty
		FROM	InOutstocktable i
		INNER JOIN #Ktype k ON k.typeid = i.KtypeId
		INNER JOIN #ptype p on p.typeid = i.PtypeId
		INNER JOIN #stype s on s.typeid = i.STypeID
		
		WHERE	BillDate <= @enddate
				AND I.BillType IN (6,9,11,14,16,17,21,34,45,57,126,139,140,142,144,146,160,161,166,168,172,173,174,183,187,188,201,202,305,215,400,401,402,403)
				AND I.Audited = 1
				AND I.KtypeId <> '10000'
				AND IsService=0
		UNION ALL
		SELECT	I.PtypeId,i.Qty
		FROM	IniGoodsStocks I
		INNER JOIN #ptype p on p.typeid = I.PtypeId
		INNER JOIN #Ktype K ON K.typeid = I.KtypeId
		INNER JOIN dbo.ptype pp ON pp.typeId=i.PtypeId
		INNER JOIN (SELECT k.typeId
						FROM	STOCK k
						INNER JOIN	#stype G ON G.TypeId = k.STypeID
						) T ON T.typeId = I.KtypeId
						WHERE pp.IsService=0
	)A
	GROUP BY A.PtypeId
	

----以库存上限为基数的统计----
IF @jstype=0
BEGIN
	SELECT S.PTypeId,ISNULL(SUM(S.UpLimitQty),0) AS js 
	INTO #tmp0 
	FROM STOCKALARM s
	INNER JOIN #Ktype k on k.typeid = s.KTypeId
	INNER JOIN (SELECT k.typeId
						FROM	STOCK k
						INNER JOIN	#stype G ON G.TypeId = k.STypeID
						) T ON T.typeId = s.KtypeId 
	GROUP BY S.PTypeId

	SELECT	a.ptypeid,
			a.qty,
			ISNULL(i.js,0) AS jstype,
			a.qty-ISNULL(i.js,0) AS jyl,
			CAST((a.qty-ISNULL(i.js,0))*ISNULL(r.Price,0) AS  NUMERIC(24, 10) ) AS totalcost
	FROM	#goodsstocks a
	LEFT JOIN #Price r ON R.Ptypeid = A.ptypeid
	LEFT JOIN #tmp0 i ON i.PtypeId=a.PtypeId 
	WHERE (a.qty-ISNULL(i.js,0)) > 0
	
	DROP TABLE #tmp0
END

----以库存下限为基数的统计----
ELSE IF @jstype=1
BEGIN
	SELECT ptypeid,SUM(ISNULL(DownLimitQty,0)) AS js INTO #tmp1 
	FROM StockAlarm s
	INNER JOIN #Ktype k on k.typeid = s.KTypeId 
	INNER JOIN (SELECT k.typeId
						FROM	STOCK k
						INNER JOIN	#stype G ON G.TypeId = k.STypeID
						) T ON T.typeId = s.KtypeId
	GROUP BY S.PTypeId

	SELECT	a.ptypeid,a.qty,ISNULL(i.js,0) AS jstype,a.qty-ISNULL(i.js,0) AS jyl,
	CAST((a.qty-ISNULL(i.js,0))*ISNULL(r.Price,0) AS  NUMERIC(24, 10) ) AS totalcost 
	FROM	#goodsstocks a
	LEFT JOIN #Price r ON R.Ptypeid = A.ptypeid
	LEFT JOIN #tmp1 i ON i.PtypeId=a.PtypeId 
	WHERE (a.qty-ISNULL(i.js,0)) > 0
	
	DROP TABLE #tmp1
END

----以销量为基数的统计----
/*
@jstype=2 表示以本月销量为基数（用户选定的截止日期所在月的1日至截止日期间的销量）
@jstype=3 表示以上月销量为基数（用户选定的截止日期的上个月整月的销量）
该统计受@startdate和@enddate两个参数影响，而这两个参数的具体值在传入前已做处理，所以这里合并为一个过程写了
*/
ELSE IF @jstype=2 OR @jstype=3
BEGIN
	DECLARE @startdate DATE --页面传入的没用，重新计算的
	IF @jstype=2
	BEGIN
		SET @startdate = CONVERT(CHAR(8),@enddate,120) + '01'
		SET @enddate = DATEADD(D, -1 ,DATEADD(m,1,@startdate))
	END
	ELSE
	BEGIN
		SET @startdate = CONVERT(CHAR(8),DATEADD(M, -1, @enddate),120) + '01'
		SET @enddate = DATEADD(D, -1 ,DATEADD(m,1,@startdate))
	END
	
	SELECT I.PtypeId,-1*ISNULL(SUM(I.Qty),0) AS js INTO #tmp2 
	FROM InOutstocktable I
	INNER JOIN #Ktype K ON K.typeid = I.KtypeId
	INNER JOIN #stype s ON s.typeid = I.STypeID
	WHERE	I.BillType IN(305,215, 11, 45, 160, 141,402,403) 
			AND BillDATE>=@startdate 
			AND BillDATE<=@enddate 
			AND Audited = 1
	GROUP BY I.PtypeId

	SELECT	a.ptypeid,
			a.qty,ISNULL(i.js,0) AS jstype,
			a.qty-ISNULL(i.js,0) AS jyl,
			CAST((a.qty-ISNULL(i.js,0))*ISNULL(r.Price,0) AS  NUMERIC(24, 10) ) AS totalcost 
	FROM #goodsstocks a
	LEFT JOIN #Price r ON R.Ptypeid = A.ptypeid
	LEFT JOIN #tmp2 i ON i.PtypeId=a.PtypeId 
	WHERE (a.qty-ISNULL(i.js,0)) > 0
	
	DROP TABLE #tmp2
END

----以自定义数值为基数的统计----
ELSE IF @jstype=4
BEGIN
	SELECT a.ptypeid,a.qty,a.qty-ISNULL(@js,0) AS jyl,
	CAST((a.qty-@js)*ISNULL(r.Price,0) AS  NUMERIC(24, 10) ) AS totalcost,
	@js AS jstype 
	FROM #goodsstocks a
	LEFT JOIN #Price r ON R.Ptypeid = A.ptypeid
	WHERE (a.qty-ISNULL(@js,0)) > 0
END


DROP TABLE #ptype,#Ktype,#goodsstocks,#stype,#GetManKTypeId,#GetManPTypeId,#Price

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_InventoryType]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROCEDURE [dbo].Web_InventoryType
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*------------------------------------------
 作者：魏伟
 日期：2016-06-07
 描述：存货类型
-------------------------------------------*/
CREATE PROCEDURE Web_InventoryType
    (
		@OperateType VARCHAR(100),	--操作类型
		@OperatorId  VARCHAR(100),	--操作人员ID
		@STypeID     VARCHAR(100),	--选择行分支机构ID 
		@Filter		 VARCHAR(256),  --查找的值
		@TypeId		 VARCHAR(100)	--基本信息Id

    )
--@encode$--    
AS
SET NOCOUNT ON

BEGIN
 DECLARE @SQL VARCHAR(max) =''
 DECLARE @id INT SET @id=(select NID from dbo.Base_InventoryType WHERE FullName='库存商品')
	
 IF	@OperateType='getstype'		--添加时-获取分支机构列表 (父节点不出)
 BEGIN	
    
     --INSERT INTO dbo.PType_InventoryType
     --        ( Ptypeid, Stypeid, InventoryTypeid )
     --VALUES  ( @TypeId,'',@id )
	 SET @SQL=' SELECT TypeId as stypeid,f.FullName as sfullname,
	 case c.fullname
	 when '''' then ''库存商品'' else c.fullname end as Ifullname,c.nId as itypeid FROM F_GetManSTypeAll('''+@OperatorId+''') f inner join Base_InventoryType c on c.fullname=''库存商品''  WHERE sonnum=0 ORDER BY f.usercode' 
	 EXEC (@SQL)
 END
  
  ---------不要啦！----------------------
 --IF	@OperateType='getInventory'		--修改时-获取分支机构的存货类型列表(在Base_InventoryType表已有的+新添加的分支机构)
 --BEGIN	
	--	CREATE TABLE #Stock
	--	(
	--		Stypeid		VARCHAR(100),					
	--		Sfullname	VARCHAR(256),
	--		Itypeid		VARCHAR(100),					
	--		Ifullname	VARCHAR(256),
	--		usercode    VARCHAR(256)
	--	)
	--	 --SET @SQL=' INSERT INTO  #Stock
	--		--		SELECT 
	--		--			a.Stypeid,
	--		--			b.fullname as Sfullname,
	--		--			a.TID, 
	--		--			c.fullname as Ifullname,
	--		--			b.usercode
	--		--		FROM Base_InventoryTypeDetails a
	--		--		INNER JOIN F_GetManSTypeAll ('''+@OperatorId+''') b ON a.Stypeid=b.typeid AND b.sonnum=0
	--		--		LEFT JOIN Base_InventoryType c ON a.TID=c.nId
	--		--	    INNER JOIN PType_InventoryType p ON p.InventoryTypeID = a.TID  AND a.STypeID=p.Stypeid and p.Ptypeid='''+@TypeId+''' 
	--		--		UNION /*合并新添加的分支机构*/	
	--		--		SELECT 
	--		--			TypeId as Stypeid,
	--		--			FullName as Sfullname,
	--		--			'' '' as Itypeid,
	--		--			'' '' as Ifullname,
	--		--			usercode
	--		--		FROM F_GetManSTypeAll('''+@OperatorId+''')  
	--		--		WHERE sonnum=0 AND Typeid NOT IN (
	--		--			SELECT a.Stypeid FROM Base_InventoryTypeDetails a 
	--		--		   INNER JOIN PType_InventoryType p ON p.InventoryTypeID = a.TID AND a.STypeID=p.Stypeid  and p.Ptypeid='''+@TypeId+''' 
	--		--		) 
	--		--		/*出数据*/
	--		--		SELECT * FROM #Stock 
	--		--				 ORDER BY usercode
	--		--	  ' 
			
	--		SET @SQL=' INSERT INTO  #Stock
	--					SELECT 
	--					p.Stypeid,
	--					b.fullname as Sfullname,
	--					p.InventoryTypeID, 
	--					c.fullname as Ifullname,
	--					b.usercode
	--				FROM  F_GetManSTypeAll ('''+@OperatorId+''') b 
	--				INNER JOIN  PType_InventoryType p ON P.Stypeid=b.TYPEID  
	--				LEFT JOIN Base_InventoryType c ON p.InventoryTypeID=c.nId
	--			    WHERE  p.Ptypeid='''+@TypeId+''' 
	--			      AND  b.sonnum=0 
			
	--		 select * from  #Stock  ORDER BY usercode
	--		'
	--			 -- PRINT @SQL
	--	 EXEC (@SQL)
 --END
  
  
  
------------------------------------------------------存货类型Selector--根据分支机构出树形的存货类型-开始-------------------------------------------------------
 IF @OperateType='Inventoryselecter' 
 BEGIN
 ---------------------如果分支机构对应的没有库存商品的存货类型 增加一条---------------------------
 --PRINT @id
    CREATE TABLE #BaseInfo
			(
				TypeID		VARCHAR(100), 
				UserCode	VARCHAR(256),
				FullName	VARCHAR(256),
				Comment     varchar(1000) 
			)

			--SET @SQL='  INSERT INTO #BaseInfo(TypeId,UserCode,FullName,Comment) 
			--			SELECT DISTINCT a.tid, c.UserCode,c.FullName,c.Comment 
			--			FROM   Base_InventoryTypeDetails a 
			--			inner join Base_InventoryType c ON a.TID=c.nId
			--			inner join F_GetManSTypeAll ('''+@OperatorId+''') b  on b.typeid=a.stypeid
			--			'
			--			IF(@STypeID<>'')
			--			SET @SQL+=
			--			'WHERE   b.TypeID = '''+@STypeID+''''
						--ELSE SET @SQL+= 'WHERE STypeID IN (SELECT typeid  FROM  F_GetManSTypeAll('''+@OperatorId+'''))'
		    --PRINT @SQL
		    
		    --这儿不应该考虑分支机构 
		    SET @SQL='  INSERT INTO #BaseInfo(TypeId,UserCode,FullName,Comment) 
						SELECT DISTINCT a.tid, c.UserCode,c.FullName,c.Comment 
						FROM   Base_InventoryTypeDetails a 
						inner join Base_InventoryType c ON a.TID=c.nId
						'
							
			EXEC (@SQL)

           
			IF @Filter = '' 
			 SELECT * FROM  #BaseInfo 
			ELSE
			BEGIN
				DECLARE @FilterSQL VARCHAR(max)=''
				SET @FilterSQL = '
						SELECT * FROM #BaseInfo
						WHERE (UserCode LIKE ''%'+@Filter+'%'' OR FullName LIKE ''%'+@Filter+'%'')'
				EXEC(@FilterSQL)
			END
			DROP TABLE #BaseInfo	
	END
----------------------------------------------------存货类型Selector--根据分支机构出树形的存货类型-结束-------------------------------------------------------

	
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InvoiceLoadBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InvoiceLoadBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
--========================================================================
--功能说明：		销售，采购发票开单调业务单据明细					
--作   者：		徐辉
--创建时间：		2009-01-07
--========================================================================
--#01  --------------------------------------------------------------------
 	Author: Wang Wei 
	DateTime: 2010-9-6
    DeScription:将调入的明细的仓库从表头改为表体
    
    -- 
    调整：销售发票调原单据明细要求开票以明细为准并显示已开票多少，还有多少没有开票。
		>从9.0上搬移过来的，修改此部分时可能考虑要同时修改9.0上的
		>调整采购发票
    作者：周华
    时间：2012-04-18 15:13:55.563
    --
*/
CREATE                                                         PROCEDURE Web_InvoiceLoadBill
(
	@chvBillNumberID	varchar(8000),	-- 单据编号字串
	@chrQueryType		INT,		-- 销售发票162，采购发票163
	@chvOperatorID varchar(500) --操作员
)
--@encode$--

AS
SET NOCOUNT ON 

IF @chvBillNumberID=''
	SET @chvBillNumberID='0' 

DECLARE @t TABLE(id INT);
INSERT INTO @t SELECT * FROM DBO.f_split(@chvBillNumberID,',')

--创建临时表，获取自定义字段
SELECT cbd.billid,cbd.detailid,cbd.Billtype as cbdbilltype,cbd.sysdiy1,cbd.sysdiy2,cbd.sysdiy3,cbd.sysdiy4,cbd.sysdiy5,cbd.sysdiy6,cbd.sysdiy7,cbd.sysdiy8,cbd.sysdiy9,cbd.sysdiy10,
cbd.sysdiy11,cbd.sysdiy12,cbd.sysdiy13,cbd.sysdiy14,cbd.sysdiy15,cbd.sysdiy16
,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId in (select id FROM @t)

SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)


IF @chrQueryType = 162 --销售发票
BEGIN
	;WITH CTE AS (
		SELECT SaleBill.KTypeID,BillNumberId,PtypeId,Qty AS Qtyx
		--SalePrice AS Price,
		--SaleTotal AS Total,
		,discountprice AS Price
		,Total,
		1 as Discount,
		discountprice,
		NTotal AS nDiscountTotal,
		total AS discounttotal,
		Tax,TaxPrice,TaxTotal,Id AS RecordedItemId,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid,
		itemname= CASE WHEN IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
				ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
		iscombined,
		GoodsNumber,
		MUnitID,
		NUnitID,
		unitid,
		W.FullName AS unit,
		U.FullName AS munit,
		V.FullName AS nunit,
		mqty,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE nqty END AS nqty,
		curmdiscountprice as curmsaleprice,
	    NTotal as nsaletotal,
	    total AS saletotal,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE unitrate END AS unitrate,
		ndiscountprice as nsaleprice,
		curmdiscountprice,
		ntotal,
		curmtaxprice,
		ntaxmoney,
		ntaxtotal,
		ndiscountprice,
		ntaxprice,
		msaleprice,
		mdiscountprice,
		mtaxprice,
		b.UnitsType,
		MUnitRate,
		TaxMoney,
		NInvoiceMoney,
		InvoiceMoney,
		InvoiceQty,
		SaleBill.CargoID,
		ct.fullname as cargofullname,
		SaleBill.isgift,producedate,validdate,
		ct1.*,
	    dbo.SaleBill.ShowOrder,
	    dbo.SaleBill.PromoType
		FROM SaleBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON SaleBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=SaleBill.BillNumberId AND ct1.DetailId=SaleBill.Id AND ct1.cbdbilltype=11
		INNER JOIN #F_BaseGetManDetailPType P ON SaleBill.PTypeID = P.TypeID
		WHERE BillNumberId IN (SELECT id FROM @t) 
		UNION ALL
		SELECT SaleBackBill.ktypeid,BillNumberId,PtypeId,-Qty as qty
				--,SalePrice
				--,-SaleTotal 
				,discountprice AS Price
				,-Total
				,1 as Discount
				,discountprice
				,-NTotal AS nDiscountTotal,
				-total AS discountotal,
				Tax,TaxPrice,-TaxTotal,Id,
				b.customitemid ,
				b.customitemfrom ,
				b.customitemname,
				b.customitemrefid,		        
				itemid,
				itemname= CASE WHEN IsCombined = 0  THEN
						  (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
				iscombined,
				GoodsNumber,
				MUnitID,
				NUnitID,
				unitid,
				W.FullName AS unit,
				U.FullName AS munit,
				V.FullName AS nunit,
				-mqty,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE -nqty END,
				curmdiscountprice as curmsaleprice,
				-NTotal	as nsaletotal,
				-total AS saletotal,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE unitrate END AS unitrate,
				ndiscountprice as nsaleprice,
				curmdiscountprice,
				-ntotal,
				curmtaxprice,
				-ntaxmoney,
				-ntaxtotal,
				ndiscountprice,
				ntaxprice,
				msaleprice,
				mdiscountprice,
				mtaxprice,
				b.UnitsType,
				MUnitRate,
				-TaxMoney,
				-NInvoiceMoney,
				-InvoiceMoney,
				-InvoiceQty,
				SaleBackBill.CargoID,
				ct.fullname as cargofullname,
				SaleBackBill.isgift,producedate,validdate,
				ct1.*,
				dbo.saleBackBill.ShowOrder,
				dbo.saleBackBill.PromoType
		FROM SaleBackBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON SaleBackBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=SaleBackBill.BillNumberId AND ct1.DetailId=SaleBackBill.Id AND ct1.cbdbilltype=45
		INNER JOIN #F_BaseGetManDetailPType P ON SaleBackBill.PTypeID = P.TypeID
		WHERE BillNumberId IN (SELECT id FROM @t) 
		
		UNION ALL
		
		SELECT PT_Combin_SaleBill.KTypeID,BillNumberId,PtypeId,Qty AS Qtyx
		--SalePrice AS Price,
		--SaleTotal AS Total,
		,discountprice AS Price
		,Total,
		1 as Discount,
		discountprice,
		NTotal AS nDiscountTotal,
		total AS discountotal,
		Tax,TaxPrice,TaxTotal,Id AS RecordedItemId,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid,
		itemname= CASE WHEN IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
				ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
		iscombined,
		null as GoodsNumber,
		MUnitID,
		NUnitID,
		unitid,
		W.FullName AS unit,
		U.FullName AS munit,
		V.FullName AS nunit,
		mqty,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE nqty END AS nqty,
		curmdiscountprice as curmsaleprice,
	    NTotal as nsaletotal,
	    total AS saletotal,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE unitrate END AS unitrate,
		ndiscountprice as nsaleprice,
		curmdiscountprice,
		ntotal,
		curmtaxprice,
		ntaxmoney,
		ntaxtotal,
		ndiscountprice,
		ntaxprice,
		msaleprice,
		mdiscountprice,
		mtaxprice,
		b.UnitsType,
		MUnitRate,
		TaxMoney,
		NInvoiceMoney,
		InvoiceMoney,
		InvoiceQty,
		PT_Combin_SaleBill.CargoID,
		ct.fullname as cargofullname,
		PT_Combin_SaleBill.isgift,
		null as producedate,
		null as validdate,
		ct1.*,
		dbo.PT_Combin_SaleBill.ShowOrder,
		dbo.PT_Combin_SaleBill.PromoType
		FROM PT_Combin_SaleBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON PT_Combin_SaleBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=PT_Combin_SaleBill.BillNumberId 
		AND ct1.DetailId=PT_Combin_SaleBill.Id AND ct1.cbdbilltype=12
		INNER JOIN #F_BaseGetManDetailPType P ON PT_Combin_SaleBill.PTypeID = P.TypeID
		WHERE BillNumberId IN (SELECT id FROM @t) 
		UNION ALL
		SELECT PT_Combin_SaleBackBill.ktypeid,BillNumberId,PtypeId,-Qty as qty
				--,SalePrice
				--,-SaleTotal 
				,discountprice AS Price
				,-Total
				,1 as Discount
				,discountprice
				,-NTotal AS nDiscountTotal,
				-total AS discounttotal,
				Tax,TaxPrice,-TaxTotal,Id,
				b.customitemid ,
				b.customitemfrom ,
				b.customitemname,
				b.customitemrefid,		        
				itemid,
				itemname= CASE WHEN IsCombined = 0  THEN
						  (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
				iscombined,
				null as GoodsNumber,
				MUnitID,
				NUnitID,
				unitid,
				W.FullName AS unit,
				U.FullName AS munit,
				V.FullName AS nunit,
				-mqty,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE -nqty END,
				curmdiscountprice as curmsaleprice,
				-NTotal as nsaletotal,
				-Total AS saletotal,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE unitrate END AS unitrate,
				ndiscountprice as nsaleprice,
				curmdiscountprice,
				-ntotal,
				curmtaxprice,
				-ntaxmoney,
				-ntaxtotal,
				ndiscountprice,
				ntaxprice,
				msaleprice,
				mdiscountprice,
				mtaxprice,
				b.UnitsType,
				MUnitRate,
				-TaxMoney,
				-NInvoiceMoney,
				-InvoiceMoney,
				-InvoiceQty,
				PT_Combin_SaleBackBill.CargoID,
				ct.fullname as cargofullname,
				PT_Combin_SaleBackBill.isgift,null as producedate,null as validdate,ct1.*,
				dbo.PT_Combin_SaleBackBill.ShowOrder,
				dbo.PT_Combin_SaleBackBill.PromoType
		FROM PT_Combin_SaleBackBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON PT_Combin_SaleBackBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=PT_Combin_SaleBackBill.BillNumberId 
		AND ct1.DetailId=PT_Combin_SaleBackBill.Id AND ct1.cbdbilltype=46
		INNER JOIN #F_BaseGetManDetailPType P ON PT_Combin_SaleBackBill.PTypeID = P.TypeID
		WHERE BillNumberId IN (SELECT id FROM @t)
		
		UNION ALL
		
		SELECT B.ktypeid,R.BillNumberId,R.PtypeId,R.Qty
				--R.SalePrice,
				--R.SaleTotal 
				,discountprice AS Price
				,total
				,1 as Discount,
				discountprice,
				R.NTotal AS nDiscountTotal,R.total AS discounttotal,R.Tax,R.TaxPrice,R.TaxTotal,R.Id,
				pt.customitemid ,
				pt.customitemfrom ,
				pt.customitemname,
				pt.customitemrefid,		        
				R.itemid,
				itemname= CASE WHEN IsCombined = 0  THEN
						  (SELECT FullName FROM xw_SelfData WHERE _Id= R.ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= R.itemid ) END,
				R.iscombined,
				R.GoodsNumber,
				R.MUnitID,
				R.NUnitID,
				R.unitid,
				W.FullName AS unit,
				U.FullName AS munit,
				V.FullName AS nunit,
				R.mqty,
				CASE WHEN ISNULL(R.NUnitID,0) = 0 THEN NULL
				ELSE R.nqty END AS nqty,
				R.curmdiscountprice as curmsaleprice,
				R.NTotal as nsaletotal,
				R.total AS saletotal,
				CASE WHEN ISNULL(R.NUnitID,0) = 0 THEN NULL
				ELSE R.unitrate END,
				R.ndiscountprice as nsaleprice,
				R.curmdiscountprice,
				R.ntotal,
				R.curmtaxprice,
				R.ntaxmoney,
				R.ntaxtotal,
				R.ndiscountprice,
				R.ntaxprice,
				R.msaleprice,
				R.mdiscountprice,
				R.mtaxprice,
				pt.UnitsType,
				R.MUnitRate,
				TaxMoney,
				R.NInvoiceMoney,
				R.InvoiceMoney,
				R.InvoiceQty,
				R.CargoID,
				ct.fullname as cargofullname,
				R.isgift,producedate,validdate,ct1.*,
				R.ShowOrder,
				R.PromoType
		FROM RetailBill R 
		JOIN BillIndex B ON R.BillNumberId=B.BillNumberId 
		LEFT JOIN dbo.PType pt ON R.PTypeID = pt.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=R.MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=R.NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=R.UnitID
		LEFT JOIN  dbo.CargoType ct ON R.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=R.BillNumberId AND ct1.DetailId=R.Id AND ct1.cbdbilltype=305
		INNER JOIN #F_BaseGetManDetailPType P ON r.PTypeID = P.TypeID
		WHERE R.BillNumberId IN (SELECT id FROM @t) 
		UNION ALL
		SELECT B.ktypeid,R.BillNumberId,R.PtypeId,-R.Qty
				--R.SalePrice,
				--R.SaleTotal 
				,discountprice AS Price
				,-total
				,1 as Discount,
				discountprice				
				,-R.NTotal AS nDiscountTotal,-R.total AS discounttotal,R.Tax,R.TaxPrice,-R.TaxTotal,R.Id,
				pt.customitemid ,
				pt.customitemfrom ,
				pt.customitemname,
				pt.customitemrefid,		        
				R.itemid,
				itemname= CASE WHEN IsCombined = 0  THEN
						  (SELECT FullName FROM xw_SelfData WHERE _Id= R.ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= R.itemid ) END,
				R.iscombined,
				R.GoodsNumber,
				R.MUnitID,
				R.NUnitID,
				R.unitid,
				W.FullName AS unit,
				U.FullName AS munit,
				V.FullName AS nunit,
				-R.mqty,
				CASE WHEN ISNULL(R.NUnitID,0) = 0 THEN NULL
				ELSE -R.nqty END AS nqty,
				R.curmdiscountprice as curmsaleprice,
				-R.NTotal as nsaletotal,
				-R.total AS saletotal,
				CASE WHEN ISNULL(R.NUnitID,0) = 0 THEN NULL
				ELSE R.unitrate END,
				R.ndiscountprice as nsaleprice,
				R.curmdiscountprice,
				-R.ntotal,
				R.curmtaxprice,
				-R.ntaxmoney,
				-R.ntaxtotal,
				R.ndiscountprice,
				R.ntaxprice,
				R.msaleprice,
				R.mdiscountprice,
				R.mtaxprice,
				pt.UnitsType,
				R.MUnitRate,
				-TaxMoney,
				-R.NInvoiceMoney,
				-R.InvoiceMoney,
				-R.InvoiceQty,
				R.CargoID,
				ct.fullname as cargofullname,
				R.isgift,producedate,validdate,ct1.*,
				R.ShowOrder,
				R.PromoType
		FROM RetailBackBill R 
		JOIN BillIndex B ON R.BillNumberId=B.BillNumberId 
		LEFT JOIN dbo.PType pt ON R.PTypeID = pt.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=R.MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=R.NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=R.UnitID
		LEFT JOIN  dbo.CargoType ct ON R.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=R.BillNumberId AND ct1.DetailId=R.Id AND ct1.cbdbilltype=215
		INNER JOIN #F_BaseGetManDetailPType P ON r.PTypeID = P.TypeID
		WHERE R.BillNumberId IN (SELECT id FROM @t)
		UNION ALL
		SELECT CommissionBill.KTypeID,BillNumberId,PtypeId,Qty
				--,SalePrice,SaleTotal ,
				,discountprice AS Price
				,total
				,1 as Discount,
				discountprice
				,NTotal AS nDiscountTotal,total AS discounttotal,Tax,TaxPrice,TaxTotal,Id,
				b.customitemid ,
				b.customitemfrom ,
				b.customitemname,
				b.customitemrefid,		        
				itemid,
				itemname= CASE WHEN IsCombined = 0  THEN
						  (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
				iscombined,
				GoodsNumber,
				MUnitID,
				NUnitID,
				unitid,
				W.FullName AS unit,
				U.FullName AS munit,
				V.FullName AS nunit,
				mqty,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE nqty END AS nqty,
				curmdiscountprice as curmsaleprice,
				NTotal as nsaletotal,
				Total AS saletotal,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE unitrate END,
				ndiscountprice as nsaleprice,
				curmdiscountprice,
				ntotal,
				curmtaxprice,
				ntaxmoney,
				ntaxtotal,
				ndiscountprice,
				ntaxprice,
				msaleprice,
				mdiscountprice,
				mtaxprice,
				b.UnitsType,
				MUnitRate,
				TaxMoney,
				NInvoiceMoney,
				InvoiceMoney,
				InvoiceQty,
				CommissionBill.CargoID,
				ct.fullname as cargofullname,
				0 as isgift,producedate,validdate,ct1.*,
				dbo.CommissionBill.ShowOrder,
				0 as PromoType
		FROM CommissionBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON CommissionBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=CommissionBill.BillNumberId AND ct1.DetailId=CommissionBill.Id AND ct1.cbdbilltype in (140,141,142,143,144,145,146,147)
		INNER JOIN #F_BaseGetManDetailPType P ON CommissionBill.PTypeID = P.TypeID
		WHERE BillNumberId IN (SELECT id FROM @t) 
		UNION ALL
		SELECT 	SaleGoodsExchangeBill.Ktypeid,BillNumberId,PtypeId
			,CASE WHEN InOrOut = 'I' THEN -Qty ELSE Qty END
			--,SalePrice
			--,CASE WHEN InOrOut = 'I' THEN -SaleTotal ELSE SaleTotal END
			,discountprice as price
			,CASE 
					WHEN InOrOut = 'I' THEN 
						-1*total
					ELSE 
						total
				END  AS Total
			,1 as Discount,
			discountprice
			,CASE WHEN InOrOut = 'I' THEN -Ntotal ELSE Ntotal END AS nDiscountTotal,
			CASE WHEN InOrOut='I' THEN -Total ELSE Total END AS discounttotal
			,Tax
			,TaxPrice
			,CASE WHEN InOrOut = 'I' THEN -nTaxTotal ELSE nTaxTotal END AS TaxTotal
			,Id,
			b.customitemid ,
			b.customitemfrom ,
			b.customitemname,
			b.customitemrefid,		        
			itemid,
			itemname= CASE WHEN IsCombined = 0  THEN
					  (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
					  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
			iscombined,
			GoodsNumber,
			MUnitID,
			NUnitID,
			unitid,
			W.FullName AS unit,
			U.FullName AS munit,
			V.FullName AS nunit,
			CASE WHEN InOrOut = 'I' THEN -mqty ELSE mqty END,
			CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
			WHEN InOrOut = 'I' THEN -nqty ELSE nqty END,
			curmdiscountprice as curmsaleprice,
			CASE WHEN InOrOut = 'I' THEN -NTotal ELSE NTotal END AS nsaletotal,
			CASE WHEN InOrOut='I' THEN -Total ELSE Total END AS SaleTotal,
			CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
			ELSE unitrate END,
			ndiscountprice as nsaleprice,
			curmdiscountprice,
			CASE WHEN InOrOut = 'I' THEN -ntotal ELSE ntotal END,
			curmtaxprice,
			CASE WHEN InOrOut = 'I' THEN -ntaxmoney ELSE ntaxmoney END,
			CASE WHEN InOrOut = 'I' THEN -ntaxtotal ELSE ntaxtotal END,
			ndiscountprice,
			ntaxprice,
			msaleprice,
			mdiscountprice,
			mtaxprice,
			b.UnitsType,
			MUnitRate,
			CASE WHEN InOrOut = 'I' THEN -TaxMoney ELSE TaxMoney END,
			CASE WHEN InOrOut = 'I' THEN -NInvoiceMoney ELSE NInvoiceMoney END AS NInvoiceMoney,
			CASE WHEN InOrOut = 'I' THEN -InvoiceMoney ELSE InvoiceMoney END AS InvoiceMoney,
			CASE WHEN InOrOut = 'I' THEN -InvoiceQty ELSE InvoiceQty END AS InvoiceQty,
			SaleGoodsExchangeBill.CargoID,
			ct.fullname as cargofullname,
			SaleGoodsExchangeBill.isgift,producedate,validdate,ct1.*,
			dbo.SaleGoodsExchangeBill.ShowOrder,
			0 as PromoType
		FROM SaleGoodsExchangeBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON SaleGoodsExchangeBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=SaleGoodsExchangeBill.BillNumberId AND ct1.DetailId=SaleGoodsExchangeBill.Id
		 AND ct1.DetailId=SaleGoodsExchangeBill.Id AND ct1.cbdbilltype =160
		INNER JOIN #F_BaseGetManDetailPType P ON SaleGoodsExchangeBill.PTypeID = P.TypeID 
		WHERE BillNumberId IN (SELECT id FROM @t)
	)
	SELECT a.*,p.UserCode,p.FullName,p.TypeId,p.EntryCode,p.[Standard],p.[Type],p.Area,p.Unit1 AS Unit,bi.CID,ac.FullName AS acfullname
	,ISNULL(bi.BillCode,'') AS BillCode,ISNULL(bi.BillType,0) AS BillType,a.taxtotal-a.ndiscounttotal AS totaltax,a.billnumberId AS mainBillNumberId
	,ISNULL(b.qty,0) AS fapiaoqty,a.qtyx-ISNULL(a.InvoiceQty,0) as qty
	--,(a.qtyx-ISNULL(b.qty,0))*ISNULL(discountprice,0) as unrecordedmoney
	--, ISNULL(b.qty,0)*ISNULL(discountprice,0) as recordedmoney
	,ISNULL(s.typeid,'') AS ktypeid,ISNULL(s.fullName,'') AS KFullName
	,ISNULL(b.Ninvoicetotal,0)+((ISNULL(a.NInvoiceMoney,0)-ISNULL(b.NInvoicetotalWithTax,0))/(1+a.Tax/100)) as recordedmoney
	,ISNULL(a.nDiscountTotal,0)-ISNULL(b.Ninvoicetotal,0)-((ISNULL(a.NInvoiceMoney,0)-ISNULL(b.NInvoicetotalWithTax,0))/(1+a.Tax/100)) as unrecordedmoney
	,ISNULL(b.NInvoicetotalWithTax,0)+(ISNULL(a.NInvoiceMoney,0)-ISNULL(b.NInvoicetotalWithTax,0)) as recordedmoneywithtax
	--未开票含税
	--,((a.qtyx-ISNULL(a.InvoiceQty,0)) * a.ndiscountprice) * (1+a.Tax/100) as unrecordedmoneywithtax,
	,ISNULL(a.nTaxTotal,0)-ISNULL(b.NInvoicetotalWithTax,0) as unrecordedmoneywithtax,
	a.CargoID,
	a.cargofullname,
	a.isgift,bi.rate,
	p.brandartypeid,
	brandarfullname = (select top 1 fullname from brandar_Commodity where typeid = p.brandartypeid),
	CASE WHEN a.PromoType<>0 AND a.IsGift=1 THEN 1 ELSE 0 END AS ispromogift
	FROM cte a 
		LEFT JOIN (
					SELECT fp.PTypeID,fp.MainBillNumberId,fp.RecordedItemId,ISNULL(SUM(fp.qty),0) AS qty, ISNULL(SUM(fp.Total),0) AS invoicetotal,ISNULL(SUM(fp.NTotal),0) AS Ninvoicetotal,
					ISNULL(SUM(fp.NTaxTotal),0) AS NInvoicetotalWithTax
					FROM FaPiaoBill fp
					WHERE fp.MainBillNumberId IN (SELECT id FROM @t) 
					GROUP BY fp.MainBillNumberId,fp.RecordedItemId,fp.PTypeID
				) b ON a.BillNumberId=b.MainBillNumberId AND a.RecordedItemId=b.RecordedItemId AND a.PTypeID=b.PTypeID
		LEFT JOIN PType p ON a.PtypeId=p.TypeId
		LEFT JOIN Stock s ON a.KtypeId=s.typeId
		LEFT JOIN BillIndex bi ON a.BillNumberId=bi.BillNumberId
		LEFT JOIN Ac_Currency ac ON bi.CID=AC.CId
	ORDER BY a.ShowOrder
END
IF @chrQueryType = 163--采购发票
BEGIN
	;WITH CTE AS(
		SELECT BuyBill.KTypeID,BillNumberId,PtypeId,Qty AS Qtyx
		--,SalePrice AS Price,
		,discountprice AS Price
		,Total
		--SaleTotal AS Total
		,1 as Discount,
		discountprice
		,NTotal AS nDiscountTotal,total AS discounttotal,Tax,TaxPrice,TaxTotal,Id AS RecordedItemId,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid,
		itemname= CASE WHEN IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
				 ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
		iscombined,
		GoodsNumber,
		MUnitID,
		NUnitID,
		unitid,
		W.FullName AS unit,
		U.FullName AS munit,
		V.FullName AS nunit,
		mqty,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE nqty END AS nqty,
		curmdiscountprice as curmsaleprice,
		NTotal as nsaletotal,
		Total AS SaleTotal,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE unitrate END AS unitrate,
		ndiscountprice as nsaleprice,
		curmdiscountprice,
		ntotal,
		curmtaxprice,
		ntaxmoney,
		ntaxtotal,
		ndiscountprice,
		ntaxprice,
		msaleprice,
		mdiscountprice,
		mtaxprice,
		b.UnitsType,
		MUnitRate,
		TaxMoney,
		NInvoiceMoney,
		InvoiceMoney,
		InvoiceQty,
		BuyBill.CargoID,
		ct.fullname as cargofullname,
		BuyBill.isgift,producedate,validdate,ct1.*,
		dbo.BuyBill.ShowOrder
		FROM BuyBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON BuyBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=BuyBill.BillNumberId AND ct1.DetailId=BuyBill.Id AND ct1.cbdbilltype =34
		INNER JOIN #F_BaseGetManDetailPType P ON BuyBill.PTypeID = P.TypeID 
		WHERE BillNumberId IN (SELECT id FROM @t) UNION ALL
		SELECT BuyBackBill.ktypeid,BillNumberId,PtypeId,-Qty
				--,SalePrice
				,discountprice AS Price
				--,-SaleTotal 
				,-Total
				,1 as Discount,discountprice
				,-NTotal AS nDiscountTotal,-total AS discounttotal,Tax,TaxPrice,-TaxTotal,Id,
				b.customitemid ,
				b.customitemfrom ,
				b.customitemname,
				b.customitemrefid,		        
				itemid,
				itemname= CASE WHEN IsCombined = 0  THEN
						  (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
				iscombined,
				GoodsNumber,
				MUnitID,
				NUnitID,
				unitid,
				W.FullName AS unit,
				U.FullName AS munit,
				V.FullName AS nunit,
				-mqty,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE -nqty END,
				curmdiscountprice as curmsaleprice,
				-NTotal as nsaletotal,
				-Total AS SaleTotal,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE unitrate END,
				ndiscountprice as nsaleprice,
				curmdiscountprice,
				-ntotal,
				curmtaxprice,
				-ntaxmoney,
				-ntaxtotal,
				ndiscountprice,
				ntaxprice,
				msaleprice,
				mdiscountprice,
				mtaxprice,
				b.UnitsType,
				MUnitRate,
				-TaxMoney,
				-NInvoiceMoney,
				-InvoiceMoney,
				-InvoiceQty,
				BuyBackBill.CargoID,
				ct.fullname as cargofullname,
				BuyBackBill.isgift,producedate,validdate,ct1.*,
				dbo.BuyBackBill.ShowOrder
		FROM BuyBackBill
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON BuyBackBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=BuyBackBill.BillNumberId AND ct1.DetailId=BuyBackBill.Id AND ct1.cbdbilltype =6
		INNER JOIN #F_BaseGetManDetailPType P ON BuyBackBill.PTypeID = P.TypeID 
		WHERE BillNumberId IN (SELECT id FROM @t) UNION ALL
		SELECT '10000',BillNumberId,PtypeId,Qty
				--,SalePrice
				--,SaleTotal 
				,discountprice AS Price
				,Total
				,1 as Discount,discountprice
				,NTotal AS nDiscountTotal,total AS discounttotal,Tax,TaxPrice,TaxTotal,Id,
				b.customitemid ,
				b.customitemfrom ,
				b.customitemname,
				b.customitemrefid,		        
				itemid,
				itemname= CASE WHEN IsCombined = 0  THEN
						  (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
				iscombined,
				GoodsNumber,
				MUnitID,
				NUnitID,
				unitid,
				W.FullName AS unit,
				U.FullName AS munit,
				V.FullName AS nunit,
				mqty,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE nqty END,
				curmdiscountprice as curmsaleprice,
				NTotal as nsaletotal,
				Total AS saletotal,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE unitrate END,
				ndiscountprice as nsaleprice,
				curmdiscountprice,
				ntotal,
				curmtaxprice,
				ntaxmoney,
				ntaxtotal,
				ndiscountprice,
				ntaxprice,
				msaleprice,
				mdiscountprice,
				mtaxprice,
				b.UnitsType,
				MUnitRate,
				TaxMoney,
				NInvoiceMoney,
				InvoiceMoney,
				InvoiceQty,
				CommissionBill.CargoID,
				ct.fullname as cargofullname,
				0 as isgift,producedate,validdate,ct1.*,
				dbo.CommissionBill.ShowOrder
		FROM CommissionBill
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID 
		LEFT JOIN  dbo.CargoType ct ON CommissionBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=CommissionBill.BillNumberId AND ct1.DetailId=CommissionBill.Id
		 AND ct1.cbdbilltype in (140,141,142,143,144,145,146,147)
		INNER JOIN #F_BaseGetManDetailPType P ON CommissionBill.PTypeID = P.TypeID  
		WHERE BillNumberId IN (SELECT id FROM @t) UNION ALL
		SELECT 	BuyGoodsExchangeBill.Ktypeid,BillNumberId,PtypeId
			,CASE WHEN InOrOut = 'O' THEN -Qty ELSE Qty END
			--,SalePrice
			--,CASE WHEN InOrOut = 'O' THEN -SaleTotal ELSE SaleTotal END
			,discountprice AS Price
			,CASE 
					WHEN InOrOut = 'O' THEN -1*Total
					ELSE Total
				END AS Total
			,1 as Discount,discountprice
			,CASE WHEN InOrOut = 'O' THEN -Ntotal ELSE Ntotal END AS nDiscountTotal,
			CASE WHEN InOrOut='O' THEN -total ELSE total END AS discounttotal
			,Tax
			,TaxPrice
			,CASE WHEN InOrOut = 'O' THEN -nTaxTotal ELSE nTaxTotal END AS TaxTotal
			,Id,
			b.customitemid ,
				b.customitemfrom ,
				b.customitemname,
				b.customitemrefid,		        
				itemid,
				itemname= CASE WHEN IsCombined = 0  THEN
						  (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
						  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
				iscombined,
				GoodsNumber,
				MUnitID,
				NUnitID,
				unitid,
				W.FullName AS unit,
				U.FullName AS munit,
				V.FullName AS nunit,
				CASE WHEN InOrOut = 'O' THEN -mqty ELSE mqty END  as mqty,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE nqty END,
				curmdiscountprice as curmsaleprice,
				CASE WHEN InOrOut = 'O' THEN -NTotal ELSE NTotal END  as nsaletotal,
				CASE WHEN InOrOut='O' THEN -Total ELSE Total END AS saletotal,
				CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
				ELSE unitrate END,
				ndiscountprice as nsaleprice,
				curmdiscountprice,
				CASE WHEN InOrOut = 'O' THEN -ntotal ELSE ntotal END AS ntotal,
				curmtaxprice,
				CASE WHEN InOrOut = 'O' THEN -ntaxmoney ELSE ntaxmoney END AS ntaxmoney,
				CASE WHEN InOrOut = 'O' THEN -nTaxTotal ELSE nTaxTotal END AS ntaxTotal,
				ndiscountprice,
				ntaxprice,
				msaleprice,
				mdiscountprice,
				mtaxprice,
				b.UnitsType,
				MUnitRate,			
				CASE WHEN InOrOut = 'O' THEN -TaxMoney ELSE TaxMoney END AS TaxMoney,
				CASE WHEN InOrOut = 'O' THEN -NInvoiceMoney ELSE NInvoiceMoney END AS NInvoiceMoney,
				CASE WHEN InOrOut = 'O' THEN -InvoiceMoney ELSE InvoiceMoney END AS InvoiceMoney,
				CASE WHEN InOrOut = 'O' THEN -InvoiceQty ELSE InvoiceQty END AS InvoiceQty,
				BuyGoodsExchangeBill.CargoID,
				ct.fullname as cargofullname,
				BuyGoodsExchangeBill.isgift,producedate,validdate,ct1.*,
				dbo.BuyGoodsExchangeBill.ShowOrder
		FROM BuyGoodsExchangeBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID 
		LEFT JOIN  dbo.CargoType ct ON BuyGoodsExchangeBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=BuyGoodsExchangeBill.BillNumberId AND ct1.DetailId=BuyGoodsExchangeBill.Id
		 AND ct1.cbdbilltype = 161
		INNER JOIN #F_BaseGetManDetailPType P ON BuyGoodsExchangeBill.PTypeID = P.TypeID   
		WHERE BillNumberId IN (SELECT id FROM @t)
	)
	SELECT a.*,p.UserCode,p.FullName,p.TypeId,p.EntryCode,p.[Standard],p.[Type],p.Area,p.Unit1 AS Unit,bi.CID,ac.FullName AS acfullname
	,ISNULL(bi.BillCode,'') AS BillCode,ISNULL(bi.BillType,0) AS BillType,a.taxtotal-a.ndiscounttotal AS totaltax,a.billnumberId AS mainBillNumberId
	,ISNULL(b.qty,0) AS fapiaoqty,a.qtyx-ISNULL(a.InvoiceQty,0) as qty
	--,(a.qtyx-ISNULL(b.qty,0))*ISNULL(discountprice,0) as unrecordedmoney
	--, ISNULL(b.qty,0)*ISNULL(discountprice,0) as recordedmoney
	,ISNULL(s.typeid,'') AS ktypeid,ISNULL(s.fullName,'') AS KFullName
	,ISNULL(b.Ninvoicetotal,0)+((ISNULL(a.NInvoiceMoney,0)-ISNULL(b.NInvoicetotalWithTax,0))/(1+a.Tax/100)) as recordedmoney
	,ISNULL(a.nDiscountTotal,0)-ISNULL(b.Ninvoicetotal,0)-((ISNULL(a.NInvoiceMoney,0)-ISNULL(b.NInvoicetotalWithTax,0))/(1+a.Tax/100)) as unrecordedmoney
	,ISNULL(b.NInvoicetotalWithTax,0)+(ISNULL(a.NInvoiceMoney,0)-ISNULL(b.NInvoicetotalWithTax,0)) as recordedmoneywithtax
	--未开票含税
	--,((a.qtyx-ISNULL(a.InvoiceQty,0)) * a.ndiscountprice) * (1+a.Tax/100) as unrecordedmoneywithtax,
	,ISNULL(a.nTaxTotal,0)-ISNULL(b.NInvoicetotalWithTax,0) as unrecordedmoneywithtax,
	a.CargoID,
	a.cargofullname,
	a.isgift,bi.rate,
	p.brandartypeid,
	brandarfullname = (select top 1 fullname from brandar_Commodity where typeid = p.brandartypeid)
	FROM CTE a 
		LEFT JOIN (
					SELECT fp.PTypeID,fp.MainBillNumberId,fp.RecordedItemId,ISNULL(SUM(fp.qty),0) AS qty, ISNULL(SUM(fp.Total),0) AS invoicetotal,ISNULL(SUM(fp.NTotal),0) AS Ninvoicetotal,
					ISNULL(SUM(fp.NTaxTotal),0) AS NInvoicetotalWithTax
					FROM FaPiaoBill fp
					WHERE fp.MainBillNumberId IN (SELECT id FROM @t) 
					GROUP BY fp.MainBillNumberId,fp.RecordedItemId,fp.PTypeID
				) b ON a.BillNumberId=b.MainBillNumberId AND a.RecordedItemId=b.RecordedItemId AND a.PTypeID=b.PTypeID
		LEFT JOIN PType p ON a.PtypeId=p.TypeId
		LEFT JOIN Stock s ON a.KtypeId=s.typeId
		LEFT JOIN BillIndex bi ON a.BillNumberId=bi.BillNumberId
		LEFT JOIN Ac_Currency ac ON bi.CID=AC.CId
		ORDER BY a.ShowOrder
END
--采购暂估开票
ELSE IF @chrQueryType = 404
BEGIN
	;WITH CTE AS
	(
		SELECT 
		ab.ID,
		ab.KTypeID,BillNumberId,PtypeId,Qty AS Qtyx,
		discountprice AS Price,
		discountprice,
		ntotal AS ndiscounttotal,
		total AS discounttotal,
		inputcostprice as costprice,
		Total,
		1 as Discount,
		Tax,TaxPrice,TaxTotal,Id AS RecordedItemId,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid,
		itemname= CASE WHEN IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
				ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
		iscombined,
		GoodsNumber,
		MUnitID,
		NUnitID,
		unitid,
		W.FullName AS unit,
		U.FullName AS munit,
		V.FullName AS nunit,
		mqty,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE nqty END AS nqty,
		curmdiscountprice as curmsaleprice,
	    NTotal as nsaletotal,
	    total AS SaleTotal,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE unitrate END AS unitrate,
		ndiscountprice as nsaleprice,
		curmdiscountprice,
		ntotal,
		curmtaxprice,
		ntaxmoney,
		ntaxtotal,
		ndiscountprice,
		ntaxprice,
		msaleprice,
		mdiscountprice,
		mtaxprice,
		b.UnitsType,
		MUnitRate,
		TaxMoney,
		ninvoicemoneyex,
		NInvoiceMoney,
		InvoiceMoney,
		InvoiceMoneyex,
		InvoiceQty,
		ab.CargoID,
		ct.fullname as cargofullname,
		400 as billtype,
		ab.isgift,producedate,validdate,ct1.*
		FROM AppraisalBill ab
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON ab.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=ab.BillNumberId AND ct1.DetailId=ab.Id
		 AND ct1.cbdbilltype = 400
		INNER JOIN #F_BaseGetManDetailPType P ON ab.PTypeID = P.TypeID    
		WHERE BillNumberId IN (SELECT id FROM @t)
		UNION ALL
		SELECT 
		ab.ID,
		ab.KTypeID,BillNumberId,PtypeId,-Qty AS Qtyx,
		discountprice AS Price,
		discountprice,
		-ntotal as ndiscounttotal,
		-total AS discounttotal,
		costprice,
		-Total,
		1 as Discount,
		Tax,TaxPrice,-TaxTotal,Id AS RecordedItemId,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid,
		itemname= CASE WHEN IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
				ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
		iscombined,
		GoodsNumber,
		MUnitID,
		NUnitID,
		unitid,
		W.FullName AS unit,
		U.FullName AS munit,
		V.FullName AS nunit,
		mqty,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE nqty END AS nqty,
		curmdiscountprice as curmsaleprice,
	    -NTotal as nsaletotal,
	    -total AS saletotal,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE unitrate END AS unitrate,
		ndiscountprice as nsaleprice,
		curmdiscountprice,
		-ntotal,
		curmtaxprice,
		-ntaxmoney,
		-ntaxtotal,
		ndiscountprice,
		ntaxprice,
		msaleprice,
		mdiscountprice,
		mtaxprice,
		b.UnitsType,
		MUnitRate,
		-TaxMoney,
		-ninvoicemoneyex,
		-NInvoiceMoney,
		-InvoiceMoney,
		-InvoiceMoneyex,
		-InvoiceQty,
		ab.CargoID,
		ct.fullname as cargofullname,
		401 as billtype,
		ab.isgift,producedate,validdate,ct1.*
		FROM AppraisalBackBill ab
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON ab.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=ab.BillNumberId AND ct1.DetailId=ab.Id
		 AND ct1.cbdbilltype = 401
		INNER JOIN #F_BaseGetManDetailPType P ON ab.PTypeID = P.TypeID 
		WHERE BillNumberId IN (SELECT id FROM @t)
	)
	SELECT a.*,p.UserCode,p.FullName,p.TypeId,p.EntryCode,p.[Standard],p.[Type],p.Area,p.Unit1 AS Unit,bi.CID,ac.FullName AS acfullname
	,ISNULL(bi.BillType,0) AS BillType,a.taxtotal-a.ndiscounttotal AS totaltax,a.billnumberId AS mainBillNumberId
	,ISNULL(b.qty,0) AS fapiaoqty,a.qtyx-ISNULL(a.InvoiceQty,0) as qty
	,ISNULL(s.typeid,'') AS ktypeid,ISNULL(s.fullName,'') AS KFullName
	--已开票不含税
	,a.ninvoicemoneyex as recordedmoney,
	--未开票不含税
	--,CASE WHEN ISNULL(a.invoiceqty,0)=0 THEN 
	--	a.ntotal * a.discount - a.ninvoicemoneyex
	--ELSE
	--	(a.qtyx-ISNULL(a.InvoiceQty,0)) * a.ndiscountprice
	--END AS unrecordedmoney
	CASE WHEN a.billtype=401 then (a.Ntotal+a.NInvoiceMoneyEX) else dbo.FN_GetUnNInvoicemoney(a.billtype,a.billnumberid,a.id)  end as unrecordedmoney
	--已开票含税
	,a.ninvoicemoney as recordedmoneywithtax
	--未开票含税
	,CASE WHEN a.InvoiceQty=0 THEN a.ntaxtotal
	ELSE
		((a.qtyx-ISNULL(a.InvoiceQty,0)) * a.ndiscountprice) * (1+a.Tax/100) END as unrecordedmoneywithtax,
	a.CargoID,
	a.cargofullname,
	a.isgift,
	bi.BillCode,bi.rate,
	p.brandartypeid,
	brandarfullname = (select top 1 fullname from brandar_Commodity where typeid = p.brandartypeid)
	FROM CTE a 
		LEFT JOIN (
					SELECT rb.MainBillNumberId,rb.RecordedItemId,ISNULL(SUM(rb.qty),0) AS qty, ISNULL(SUM(rb.Total),0) AS invoicetotal,ISNULL(SUM(rb.NTotal),0) AS Ninvoicetotal,
					ISNULL(SUM(rb.NTaxTotal),0) AS NInvoicetotalWithTax
					FROM ReceiptBill rb
					inner join receiptbillindex rbi on rb.billnumberid=rbi.billnumberid and rbi.draft=0 and rbi.ifcheck='t' and rbi.redword=0
					WHERE rb.MainBillNumberId IN (SELECT id FROM @t) 
					GROUP BY rb.MainBillNumberId,rb.RecordedItemId
				) b ON a.BillNumberId=b.MainBillNumberId AND a.RecordedItemId=b.RecordedItemId
		LEFT JOIN PType p ON a.PtypeId=p.TypeId
		LEFT JOIN Stock s ON a.KtypeId=s.typeId
		LEFT JOIN billindex bi ON a.BillNumberId=bi.BillNumberId
		LEFT JOIN Ac_Currency ac ON bi.CID=AC.CId
		WHERE a.qtyx-ISNULL(a.InvoiceQty,0)<>0
END
--销售暂估开票
ELSE IF @chrQueryType = 405
BEGIN
	;WITH CTE AS
	(
		SELECT 
		SendBill.ID,
		SendBill.KTypeID,BillNumberId,PtypeId,Qty AS Qtyx,
		discountprice AS Price,
		discountprice,
		ntotal as ndiscounttotal,
		total AS discounttotal,
		costprice,
		Total,
		1 as Discount,
		Tax,TaxPrice,TaxTotal,Id AS RecordedItemId,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid,
		itemname= CASE WHEN IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
				ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
		iscombined,
		GoodsNumber,
		MUnitID,
		NUnitID,
		unitid,
		W.FullName AS unit,
		U.FullName AS munit,
		V.FullName AS nunit,
		mqty,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE nqty END AS nqty,
		curmdiscountprice as curmsaleprice,
	    NTotal as nsaletotal,
	    total AS saletotal,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE unitrate END AS unitrate,
		ndiscountprice as nsaleprice,
		curmdiscountprice,
		ntotal,
		curmtaxprice,
		ntaxmoney,
		ntaxtotal,
		ndiscountprice,
		ntaxprice,
		msaleprice,
		mdiscountprice,
		mtaxprice,
		b.UnitsType,
		MUnitRate,
		TaxMoney,
		ninvoicemoneyex,
		NInvoiceMoney,
		InvoiceMoney,
		InvoiceMoneyex,
		InvoiceQty,
		SendBill.CargoID,
		ct.fullname as cargofullname,
		402 as billtype,
		SendBill.isgift,producedate,validdate,ct1.*
		FROM SendBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON SendBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=SendBill.BillNumberId AND ct1.DetailId=SendBill.Id
		 AND ct1.cbdbilltype = 402
		INNER JOIN #F_BaseGetManDetailPType P ON SendBill.PTypeID = P.TypeID  
		WHERE BillNumberId IN (SELECT id FROM @t)
		UNION ALL
		SELECT 
		SendBackBill.ID,
		SendBackBill.KTypeID,BillNumberId,PtypeId,-Qty AS Qtyx,
		discountprice AS Price,
		discountprice,
		-ntotal as ndiscounttotal,
		total AS discounttotal,
		costprice,
		-Total,
		1 as Discount,
		Tax,TaxPrice,-TaxTotal,Id AS RecordedItemId,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid,
		itemname= CASE WHEN IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= ItemId)
				ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= itemid ) END,
		iscombined,
		GoodsNumber,
		MUnitID,
		NUnitID,
		unitid,
		W.FullName AS unit,
		U.FullName AS munit,
		V.FullName AS nunit,
		-mqty,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE nqty END AS nqty,
		curmdiscountprice as curmsaleprice,
	    -NTotal as nsaletotal,
	    -total AS saletotal,
		CASE WHEN ISNULL(NUnitID,0) = 0 THEN NULL
		ELSE unitrate END AS unitrate,
		ndiscountprice as nsaleprice,
		curmdiscountprice,
		-ntotal,
		curmtaxprice,
		-ntaxmoney,
		-ntaxtotal,
		ndiscountprice,
		ntaxprice,
		msaleprice,
		mdiscountprice,
		mtaxprice,
		b.UnitsType,
		MUnitRate,
		-TaxMoney,
		-ninvoicemoneyex,
		-NInvoiceMoney,
		-InvoiceMoney,
		-InvoiceMoneyex,
		-InvoiceQty,
		SendBackBill.CargoID,
		ct.fullname as cargofullname,
		403 as billtype,
		SendBackBill.isgift,producedate,validdate,
		ct1.*
		FROM SendBackBill 
		LEFT JOIN dbo.PType b ON PTypeID = b.TypeID
		LEFT JOIN  dbo.PType_Units U ON U.UnitsId=MUnitID 
		LEFT JOIN  dbo.PType_Units V ON V.UnitsId=NUnitID
		LEFT JOIN  dbo.PType_Units W ON W.UnitsId=UnitID
		LEFT JOIN  dbo.CargoType ct ON SendBackBill.CargoID = ct.CargoID
		LEFT JOIN #Custom_T ct1 ON ct1.BillId=SendBackBill.BillNumberId AND ct1.DetailId=SendBackBill.Id
		 AND ct1.cbdbilltype = 403
		INNER JOIN #F_BaseGetManDetailPType P ON SendBackBill.PTypeID = P.TypeID   
		WHERE BillNumberId IN (SELECT id FROM @t)
	)
	SELECT a.*,p.UserCode,p.FullName,p.TypeId,p.EntryCode,p.[Standard],p.[Type],p.Area,p.Unit1 AS Unit,bi.CID,ac.FullName AS acfullname
	,ISNULL(bi.BillType,0) AS BillType,a.taxtotal-a.ndiscounttotal AS totaltax,a.billnumberId AS mainBillNumberId
	,ISNULL(b.qty,0) AS fapiaoqty,a.qtyx-ISNULL(a.InvoiceQty,0) as qty
	,ISNULL(s.typeid,'') AS ktypeid,ISNULL(s.fullName,'') AS KFullName
	--已开票不含税
	,a.ninvoicemoneyex as recordedmoney
	--未开票不含税
	--,CASE WHEN ISNULL(a.invoiceqty,0)=0 THEN 
	--	a.ntotal * a.discount - a.ninvoicemoneyex
	--ELSE
	--	(a.qtyx-ISNULL(a.InvoiceQty,0)) * a.ndiscountprice
	--END AS unrecordedmoney
	,CASE WHEN a.billtype=403 THEN -(dbo.FN_GetUnNInvoicemoney(a.billtype,a.billnumberid,a.id))
	ELSE dbo.FN_GetUnNInvoicemoney(a.billtype,a.billnumberid,a.id) END as unrecordedmoney
	--已开票含税
	,a.ninvoicemoney as recordedmoneywithtax
	--未开票含税
	,CASE WHEN a.InvoiceQty=0 THEN a.ntaxtotal
	ELSE
		((a.qtyx-ISNULL(a.InvoiceQty,0)) * a.ndiscountprice) * (1+a.Tax/100) END as unrecordedmoneywithtax,
	a.CargoID,
	a.cargofullname,
	a.isgift,
	bi.BillCode,bi.rate,
	p.brandartypeid,
	brandarfullname = (select top 1 fullname from brandar_Commodity where typeid = p.brandartypeid)
	FROM CTE a 
		LEFT JOIN (
					SELECT rb.MainBillNumberId,rb.RecordedItemId,ISNULL(SUM(rb.qty),0) AS qty, ISNULL(SUM(rb.Total),0) AS invoicetotal,ISNULL(SUM(rb.NTotal),0) AS Ninvoicetotal,
					ISNULL(SUM(rb.NTaxTotal),0) AS NInvoicetotalWithTax
					FROM ReceiptBill rb
					inner join receiptbillindex rbi on rb.billnumberid=rbi.billnumberid and rbi.draft=0 and rbi.ifcheck='t' and rbi.redword=0
					WHERE rb.MainBillNumberId IN (SELECT id FROM @t) 
					GROUP BY rb.MainBillNumberId,rb.RecordedItemId
				) b ON a.BillNumberId=b.MainBillNumberId AND a.RecordedItemId=b.RecordedItemId
		LEFT JOIN PType p ON a.PtypeId=p.TypeId
		LEFT JOIN Stock s ON a.KtypeId=s.typeId
		LEFT JOIN billindex bi ON a.BillNumberId=bi.BillNumberId
		LEFT JOIN Ac_Currency ac ON bi.CID=AC.CId
		WHERE a.qtyx-ISNULL(a.InvoiceQty,0)<>0
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_InvoiceQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_InvoiceQuery]
GO






-- ========================================================================
-- 功能说明：		发票统计
-- 作者：		陈启华
-- 最后修改时间：	2003-08-26
-- ========================================================================
CREATE                      PROCEDURE Web_InvoiceQuery
(
	@billType				varchar(25),	--  1、  单据类型 305--零售单,11--销售单,34--采购单,0--所有单据
	@billCode 				varchar(200),	--  2、  单据编号 
	@chvStartDate			varchar(30),	--  3、  单据查询起始时间
	@chvEndDate				varchar(30),	--  4、  单据查询结束时间
	@chvInvoiceStartDate	varchar(30),	--  5、  发票查询起始时间
	@chvInvoiceEndDate		varchar(30),	--  6、  发票查询结束时间
	@chvInvoiceFlag         char(1)    ,    --  7、  末开--'0',已开--'1'，全部--'2'
	@chvInvoiceStyle        char(1)    ,    --  8、  普通--'1'，增值税--'2'，收据--'3',全部--'4'
	@chvBTypeID				varchar(25),	--  9、  往来单位类别查询范围父节点 ID
	@chvETypeID				varchar(25),	--  10、 职员类别查询范围父节点 ID--经手人
	@chvKTypeID				varchar(25),	--  11、 仓库类别查询范围父节点 ID
	@chvInvoiceEtypeID		varchar(25),	--  12、 开发票人
	--@intPageNo			int = 1,	--  13、 前查询的页码
	@intPageSize			int = 14,	--  14、 每页的显示记录数
	@chvOperatorID			varchar(30),	--  15、 操作员 ID（作权限范围检查用）
	@chvNote				varchar(30),	--  17、 备注
	@chvInvoiceNo           varchar(50),
	@chvFlag				char(1) 	--  18、 能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	
)
--@encode$--
AS
SET NOCOUNT ON 
--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50)
EXEC @intRe = GP_CheckOperatorRight23 @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output
--IF @intRe <> 0 RETURN @intRe

DECLARE @BtypeAll int
SELECT @BtypeAll=value FROM UserConfig WHERE ConfigName='BtypeAll'

DECLARE	   @SQL       varchar(4000) -- 主查询Sql
DECLARE    @SQL_WHERE varchar(4000) -- 条件语句
DECLARE	   @SQL_GROUP varchar(4000) -- 分组语句
DECLARE    @SQL_ORDER varchar(4000) -- 排序语句

DECLARE    @SQL_WHERE1 varchar(4000) -- 客户条件语句


SET @SQL_WHERE = ''






-- ================================================================== 过滤仓库

IF @chvKtypeID = '' or @chvKtypeID='00000'   -- 所有仓库
	BEGIN
		SET @SQL_WHERE = ' AND ( b.ktypeid like ' + Char(39) + @chvMKTypeID + '%' + char(39) + ' OR b.KTypeId2 LIKE '+char(39)+@chvMKTypeID+'%'+char(39)+' OR b.KtypeID ='+char(39)+'10000'+char(39)+')'
	END
ELSE
	BEGIN
		SET @SQL_WHERE = ' AND ((b.ktypeid like ' + char(39) + @chvKtypeID + '%' + char(39) + ' AND b.ktypeid like ' + Char(39) + @chvMKTypeID + '%' + char(39)+') OR (b.ktypeid2 like ' + char(39) + @chvKtypeID + '%' + char(39) + ' AND b.ktypeid2 like ' + Char(39) + @chvMKTypeID + '%' + char(39)+') ) '		
	END
-- ==================================================================== 过滤经手人

IF @chvETypeID = '' or @chvETypeID = '00001'  -- 所有经手人
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND b.etypeid like ' + char(39) + @chvMETypeID + '%' + char(39)
	END
ELSE
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND b.etypeid  like ' + char(39) + @chvETypeID + '%' + char(39) +' AND b.etypeid like ' + char(39) + @chvMETypeID + '%' + char(39)
	END

-- ===================================================================== 过滤客户或者供货商

IF @BtypeAll = 1 -- 客户供货商统一
	BEGIN
		IF  @chvBTypeID = '00000' or 	@chvBTypeID = ''  -- 所有客户,供货商
			BEGIN
				SET @SQL_WHERE = @SQL_WHERE + ' AND  (b.btypeid like ' + char(39) + @chvMBTypeID + '%' + char(39) + ' or b.btypeid like ' + char(39) + @chvMBTypeID2 + '%' + char(39)+ ')'				
			END
		ELSE
			BEGIN
				SET @SQL_WHERE = @SQL_WHERE + ' AND  b.btypeid like ' + char(39) + @chvBTypeID + '%' + char(39) + ' AND  (b.btypeid like ' + char(39) + @chvMBTypeID + '%' + char(39) + ' or  b.btypeid  like ' + char(39) + @chvMBTypeID2 + '%' + char(39) +')'				
			END
	END
ELSE	-- 客户供货商不统一
	BEGIN
		IF  @chvBTypeID = '00000' or 	@chvBTypeID = ''  -- 所有客户,供货商
			BEGIN
				SET @SQL_WHERE = @SQL_WHERE + ' AND  (b.btypeid like ' + char(39) + @chvMBTypeID + '%' + char(39) + ' or  b.btypeid like ' + char(39) + @chvMBTypeID2 + '%' + char(39) + ')'				
			END
		IF LEFT(@chvBTypeID,5)='00001'  
			BEGIN
				SET @SQL_WHERE = @SQL_WHERE + ' AND  b.btypeid like ' + char(39) + @chvBTypeID + '%' + char(39) + ' AND  b.btypeid like ' + char(39) + @chvMBTypeID + '%' + char(39)				
			END
		IF LEFT(@chvBTypeID,5)='00002' 
			BEGIN
				SET @SQL_WHERE = @SQL_WHERE + ' AND  b.btypeid like ' + char(39) + @chvBTypeID + '%' + char(39) + ' AND   b.btypeid like ' + char(39) + @chvMBTypeID2 + '%' + char(39)				
			END
	END

-- ==================================================================== 过滤开票人

/*IF @chvETypeID = '' or @chvETypeID = '00001'  -- 所有开票人
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND i.etypeid like ' + char(39) + @chvInvoiceEtypeID + '%' + char(39)
	END
ELSE
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND i.etypeid  like ' + char(39) + @chvInvoiceEtypeID + '%' + char(39) +' AND i.etypeid like ' + char(39) + @chvMETypeID + '%' + char(39)
	END
*/
-- ==================================================================== 过滤开票人

IF @chvInvoiceEtypeID = '' or @chvInvoiceEtypeID = '00001'  -- 所有开票人
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND (i.etypeid like ' + char(39) + @chvInvoiceEtypeID + '%' + char(39)+' or i.etypeid ='''')'
	END
ELSE
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND ((i.etypeid  like ' + char(39) + @chvInvoiceEtypeID + '%' + char(39) +' AND i.etypeid like ' + char(39) + @chvMETypeID + '%' + char(39)+') or i.etypeid='''')'
	END




IF @billType <> '0' 
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND b.billtype = ' +char(39) + @billType +char(39)
	END
ELSE
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND  (b.billtype =''11'' or b.billtype=''305'' or b.billtype=''34'' or b.billtype=''141'' or b.billtype=''145'' OR b.BillType = ''160'' OR b.BillType = ''161'') ' 
	END
IF @billCode <> ''
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND  b.billcode like ' + char(39)+ '%'+ @billCode + '%' +char(39)
	END



IF @chvStartDate <> '' and @chvEndDate <> ''
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND b.billDate >= ' +char(39) + @chvStartDate +char(39) + ' AND b.billDate <= ' +char(39) + @chvEndDate +char(39)
	END

IF @chvInvoiceStartDate <> '' AND @chvInvoiceEndDate <> ''
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND (( i.invoiceDate >= ' +char(39) + @chvInvoiceStartDate +char(39) + ' AND i.invoiceDate <= ' +char(39) + @chvInvoiceEndDate +char(39)+') or i.invoiceDate='+char(39)+'1900-1-1'+char(39)+' )'
	END

IF @chvInvoiceFlag = 2
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND  (i.IfInVoice = '+ char(39)+ '1' + char(39)+' or i.IfInVoice = '+ char(39)+'0' +char(39) +')'
	END
ELSE
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND  i.IfInVoice = ' + char(39) + @chvInvoiceFlag + char(39)
	END
IF @chvInvoiceStyle =4 	
	BEGIN	
		SET @SQL_WHERE = @SQL_WHERE + ' AND  (i.InvoiceStyle = '+char(39)+'1'+char(39)+'  or i.InvoiceStyle = '+char(39)+ '2'+ char(39)+'  or i.InvoiceStyle = '+char(39)+'3'+ char(39)+' )'
	END
ELSE
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND  i.InvoiceStyle = '+ char(39) + @chvInvoiceStyle + char(39)
	END
--print @SQL_WHERE
SET @SQL_WHERE = @SQL_WHERE + ' AND i.Explain  like ' + char(39)+ '%'+@chvNote  + '%' + char(39)
SET @SQL_WHERE = @SQL_WHERE + ' AND i.isDraft = 0'
SET @SQL_WHERE = @SQL_WHERE + ' AND i.InvoiceNo like ' + char(39) + '%'+ @chvInvoiceNo+'%'+char(39)
IF @chvFlag = 1  or @chvFlag = 2
	BEGIN
		SET @SQL = 'SELECT a.*,
				isnull(bt.fullname,'''') as BFullName,
				isnull(e.fullname,'''') as EFullName,
				isnull(k.fullname,'''') as KFullName,
				isnull(ei.fullname,'''') as EIFullName
					 from(
						SELECT
						b.billnumberid as billnumberid,
						b.billCode as billcode,
						b.billDate as billdate,
						b.btypeid as btypeid,
						b.etypeid as etypeid,
						b.ktypeid as ktypeid,
						i.etypeid as ietypeid,
						billName = CASE b.billType 
								WHEN 11  THEN ''销售出库单''
								WHEN 305 THEN ''零售单''
								WHEN 34  THEN ''采购入库单''
								WHEN 141  THEN ''委托代销结算单''
								WHEN 145  THEN ''受托代销结算单''
								WHEN 160  THEN ''销售换货单''
								WHEN 161  THEN ''采购换货单''
							   END,
						Convert( NUMERIC(24, 10) ,isnull(b.totalmoney,0)) as totalmoney,
						Convert( NUMERIC(24, 10) ,isnull(b.totalinmoney,0)) as totalinmoney,
						Convert( NUMERIC(24, 10) ,isnull(i.InvoiceTotal,0)) as InvoiceTotal,
						style = CASE i.InvoiceStyle
								WHEN ''1'' THEN ''普通发票''
								WHEN ''2'' THEN ''增值税发票''
								WHEN ''3'' THEN ''收据''
								END,
						i.IfInVoice as IfInvoice,
						InvoiceDate = CASE i.InvoiceDate  
								   WHEN ''1900-1-1'' THEN Null
								   ELSE i.InvoiceDate
								   END		
							,
						i.InvoiceNo as InvoiceNo,
						i.Explain as Explain
					   FROM billindex b,InvoiceBill i
					   WHERE
						b.billnumberid=i.billnumberid '+@SQL_WHERE +'
					) a left join btype bt on bt.typeid = a.btypeid
					    left join employee e on e.typeid = a.etypeid
					    left join stock k on k.typeid = a.ktypeid
					    left join employee ei on ei.typeid = a.ietypeid
				
					'
		--PRINT(@SQL)
		EXEC(@SQL)
	END
IF @chvFlag = 3
	BEGIN
		SET @SQL = 'SELECT
				
				isnull(sum(Convert( NUMERIC(24, 10) ,isnull(b.totalmoney,0))),0) as sum_Totalmoney,
				isnull(sum(Convert( NUMERIC(24, 10) ,isnull(b.totalinmoney,0))),0) as sum_Totalinmoney,
				isnull(sum(Convert( NUMERIC(24, 10) ,isnull(i.InvoiceTotal,0))),0) as sum_InvoiceTotal
				
			   FROM billindex b,InvoiceBill i
			   WHERE
				b.billnumberid=i.billnumberid 
				
				'
		SET @SQL = @SQL +@SQL_WHERE		
		--PRINT(@SQL)
		EXEC(@SQL)
	END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_IsPeriodBalance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_IsPeriodBalance]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2013/01/06
	Description	: 判断账务期初的试算平衡
*/

CREATE PROCEDURE WEB_IsPeriodBalance
(
	@chvOperatorID	VARCHAR(100),     --操作员id
	@STypeId		VARCHAR(50)		  --独立核算分支机构typeid	
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	---先判断三张表是否平衡
    SELECT STypeId,ATypeId,Cid,
		   SUM(IniTotal) AS IniTotal ,
		   SUM(IniTotalFor) AS IniTotalFor,
		   SUM(FDebit) AS FDebit,
		   SUM(FDebitFor) AS FDebitFor,
		   SUM(FCredit) AS FCredit,
		   SUM(FCreditFor) AS FCreditFor,
		   SUM(IniYTotal) AS IniYTotal,
		   SUM(IniYTotalFor) AS IniYTotalFor
	INTO #tempAIAC
	FROM dbo.Ac_IniAccount_Assist_CheckItems 
	WHERE STypeId=@STypeId
	GROUP BY STypeId,ATypeId,Cid
	
	SELECT STypeId,ATypeId,Cid,
		   SUM(IniTotal) AS IniTotal ,
		   SUM(IniTotalFor) AS IniTotalFor,
		   SUM(FDebit) AS FDebit,
		   SUM(FDebitFor) AS FDebitFor,
		   SUM(FCredit) AS FCredit,
		   SUM(FCreditFor) AS FCreditFor,
		   SUM(IniYTotal) AS IniYTotal,
		   SUM(IniYTotalFor) AS IniYTotalFor
	INTO #tempAIACD
	FROM 
	(
		SELECT STypeId,ATypeId,Cid,GroupId,IniTotal,IniTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniYTotal,IniYTotalFor 
		FROM Ac_IniAccount_Assist_CheckItems_Detail 
		WHERE STypeId=@STypeId
		GROUP BY STypeId,ATypeId,Cid,GroupId,IniTotal,IniTotalFor,FDebit,FDebitFor,FCredit,FCreditFor,IniYTotal,IniYTotalFor 
	) f GROUP BY STypeId,ATypeId,Cid
	
	--存在明细合计为0，而主表没有对应数据的情况，因为在年结的时候，已经将主表中为0的记录全删除了
	DELETE FROM #tempAIAC WHERE  iniYTotal=0 AND iniYTotalFor=0 AND FDebit=0 AND FDebitFor=0 AND FCredit=0 AND FCreditFor=0 AND iniTotal=0 AND iniTotalFor=0 
	DELETE FROM #tempAIACD WHERE  iniYTotal=0 AND iniYTotalFor=0 AND FDebit=0 AND FDebitFor=0 AND FCredit=0 AND FCreditFor=0 AND iniTotal=0 AND iniTotalFor=0 
	
	--比较两辅助表，先排除两表数据条数不一致的情况
	IF EXISTS(SELECT TOP 1 1 FROM #tempAIAC a LEFT JOIN #tempAIACD b ON a.STypeId=b.STypeId AND a.ATypeId=b.ATypeId AND a.CID=b.CID WHERE b.STypeId IS NULL)
		BEGIN
			RETURN -2
		END
	  
	IF EXISTS(SELECT TOP 1 1 FROM #tempAIACD a LEFT JOIN #tempAIAC b ON a.STypeId=b.STypeId AND a.ATypeId=b.ATypeId AND a.CID=b.CID WHERE b.STypeId IS NULL)
		BEGIN
			RETURN -3
		END
	--比较两表值
	IF EXISTS(SELECT TOP 1 1 FROM #tempAIAC a JOIN #tempAIACD b ON a.STypeId=b.STypeId AND a.ATypeId=b.ATypeId AND a.CID=b.CID 
	          AND (a.IniTotal<>b.IniTotal OR a.IniTotalFor<>b.IniTotalFor OR a.FDebit<>b.FDebit OR a.FDebitFor<>b.FDebitFor OR 
				   a.FCredit<>b.FCredit OR a.FCreditFor<>b.FCreditFor OR a.IniYTotal<>a.IniYTotal OR a.IniYTotalFor<>b.IniYTotalFor))
		BEGIN
			RETURN -4
		END
	--辅助表比较主表
	IF EXISTS(SELECT TOP 1 1 FROM #tempAIAC a LEFT JOIN dbo.Ac_IniAccount b ON a.STypeId=b.STypeId AND a.ATypeId=b.ATypeId AND a.CID=b.CID WHERE b.STypeId IS NULL)
		BEGIN
			RETURN -5
		END
		
	--modify bug
	IF EXISTS(SELECT * FROM  dbo.Ac_IniAccount b join (select distinct STypeId, ATypeId  from Ac_Account_Assist_CheckItems) t on b.STypeId=t.STypeId and b.ATypeId=t.ATypeId  LEFT JOIN #tempAIAC a  ON a.STypeId=b.STypeId AND a.ATypeId=b.ATypeId AND a.CID=b.CID 
	where b.STypeId=@STypeId and a.STypeId IS NULL and b.iniTotal<>0 and b.FDebit<>0 and b.FCredit<>0 and b.IniYTotal<>0 )
		BEGIN
			RETURN -6
		END
		
	IF EXISTS(SELECT TOP 1 1 FROM #tempAIAC a JOIN Ac_IniAccount b ON a.STypeId=b.STypeId AND a.ATypeId=b.ATypeId AND a.CID=b.CID 
	          AND (a.IniTotal<>b.IniTotal OR a.IniTotalFor<>b.IniTotalFor OR a.FDebit<>b.FDebit OR a.FDebitFor<>b.FDebitFor OR 
				   a.FCredit<>b.FCredit OR a.FCreditFor<>b.FCreditFor OR a.IniYTotal<>a.IniYTotal OR a.IniYTotalFor<>b.IniYTotalFor))
		BEGIN
			RETURN -7
		END
	
	
	
	
	---------------试算平衡
	DECLARE @FYear			VARCHAR(10),
			@FPeriod		INT
	--SELECT @FYear=SUBVALUE FROM SYSDATA WHERE SUBNAME='fyear'
	--SELECT @FPeriod=SUBVALUE FROM SYSDATA WHERE SUBNAME='fmonth'
	SELECT @FYear = FYear,@FPeriod = FPeriod  FROM Ac_AccountsPeroid_Stype WHERE Stypeid = @STypeId
	---提出该机构所有父节点
	SELECT STYPEID,
		   TYPEID,
		   FDC,
		   SUBSTRING(TYPEID,1,5) AS ACCOUNTTYPE
    INTO #tempFather
    FROM AC_ACCOUNT a
    WHERE
	(
		a.TYPEID LIKE '00001%' OR  --资产
		a.TYPEID LIKE '00002%' OR  --负债
		a.TYPEID LIKE '00003%' OR  --损益
		a.TYPEID LIKE '00004%' OR  --成本
		a.TYPEID LIKE '00005%' OR  --权益
		a.TYPEID LIKE '00006%'     --共同
	)
	AND a.FLeveal=1
	AND a.STYPEID=@STypeId 
	AND a.DELETED=0
	ORDER BY a.TYPEID
    
    ---查询出副科目包含子科目及子科目的值
    CREATE TABLE #tempData
	(
	   FATHERID             VARCHAR(50),
	   FATHERFDC			INT,
	   SONID				VARCHAR(50),
	   SONFDC				INT,        
	   ACCOUNTTYPE			VARCHAR(5),  
	   INITOTAL              NUMERIC(24, 10) ,   --期初本币余额
	   INIYTOTAL			 NUMERIC(24, 10) 	 --年初本币余额
	)
	INSERT INTO #tempData 
	SELECT a.TYPEID AS FATHERID,
		   a.FDC, 
		   b.TYPEID AS SONID,
		   b.FDC,
		   a.ACCOUNTTYPE,
		   ISNULL(INITOTAL,0),
		   ISNULL(INIYTOTAL,0)
	FROM #tempFather a
	JOIN dbo.Ac_Account b         ON a.STYPEID=b.STYPEID AND b.TYPEID LIKE a.TYPEID+'%' AND b.DELETED=0 AND b.SONNUM=0
	LEFT JOIN dbo.Ac_IniAccount c ON b.STYPEID=c.STYPEID AND b.TYPEID=c.ATYPEID AND c.FYEAR=@FYear AND c.FPERIOD=@FPeriod 
    ORDER BY a.TYPEID
    
    ---求出父科目的值
    CREATE TABLE #AC_INIACCOUNT
	(   
	   ATYPEID              VARCHAR(50),  
	   FDC					INT,
	   ACCOUNTTYPE			VARCHAR(50),        
	   INITOTAL              NUMERIC(24, 10) ,
	   INIYTOTAL			 NUMERIC(24, 10) 
	)
	;WITH a AS
	 (
		 SELECT FATHERID,
				FATHERFDC,
				ACCOUNTTYPE,
				SONFDC,
				 CASE 
					WHEN a.FATHERFDC=a.SONFDC THEN SUM(INITOTAL)
					ELSE -SUM(INITOTAL)
				 END AS INITOTAL,
				 CASE 
					WHEN a.FATHERFDC=a.SONFDC THEN SUM(INIYTOTAL)
					ELSE -SUM(INIYTOTAL)
				 END AS INIYTOTAL
		 FROM 
			(     --科目各种币别的年初合
			      SELECT FATHERID,
						 FATHERFDC,
						 ACCOUNTTYPE,
						 SONFDC,
						 SONID,
						 SUM(INITOTAL) AS INITOTAL,
						 SUM(INIYTOTAL) AS INIYTOTAL
			      FROM #tempData
			      GROUP BY FATHERID,FATHERFDC,SONFDC,SONID,ACCOUNTTYPE
			) a
		 GROUP BY FATHERID,FATHERFDC,SONFDC,ACCOUNTTYPE
	 )
	 INSERT INTO #AC_INIACCOUNT
	 SELECT FATHERID,
		    FATHERFDC,
		    ACCOUNTTYPE,
		    SUM(INITOTAL),
		    SUM(INIYTOTAL)
	 FROM a 
	 GROUP BY a.FATHERID,a.FATHERFDC,ACCOUNTTYPE	
	 
    -------------------取出期初数据-----------------------------------------------------------------------------------------------
    CREATE TABLE #temp
    (
       ACCOUNTTYPE VARCHAR(50),		---科目类型
       FDC		   VARCHAR(5),		---余额方向
       FVALUE	    NUMERIC(24, 10) 	---余额值
    )
    
    INSERT INTO #temp
    SELECT ACCOUNTTYPE,
		   CASE 
			   WHEN FDC=1 THEN '借'
			   ELSE '贷'
		   END,
		   SUM(INITOTAL) 
    FROM #AC_INIACCOUNT
    GROUP BY ACCOUNTTYPE,FDC
    
    CREATE TABLE #Result
    (
	   ACCOUNTTYPE VARCHAR(50),		---科目类型
       FDC		   VARCHAR(5),		---余额方向
       FVALUE	    NUMERIC(24, 10) ,	---余额值
       GROUPID	   INT				---合计时使用，【资产，共同，成本】是一组，【负债，权益，损益】是一组
    )
    
    ---资产
	; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC  
       WHERE a.ACCOUNTTYPE='00001'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '资产',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a  
      
    ---共同
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00006'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '共同',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a           
	
	---成本
	; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00004'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '成本',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a    
    
    ---负债
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00002'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '负债',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷'
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
     
    ----权益
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC  
       WHERE a.ACCOUNTTYPE='00005'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '权益',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷' 
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
         
    --损益
     ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp a 
	   LEFT JOIN #temp b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00003'
    )
    INSERT INTO #Result
    SELECT TOP 1
		  '损益',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷'  
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
    
    --------【资产，共同，成本】的合计
    IF (SELECT COUNT(*) FROM #Result WHERE GROUPID=1 AND FDC='平')=3
		INSERT INTO #Result
		SELECT '合计1','平',0,0
    ELSE
		WITH tempA AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					SUM(FVALUE) AS FVALUE
			FROM #Result b 
			WHERE b.GROUPID=1 AND b.FDC='借' 
			GROUP BY b.GROUPID,b.FDC
		)
		INSERT INTO #Result
		SELECT '合计1',
				CASE 
					WHEN FVALUE=0 THEN '平'
					ELSE '借'
				END,
				FVALUE,
				0
		FROM tempA

   --------【负债，权益，损益】的合计
   IF (SELECT COUNT(*) FROM #Result WHERE GROUPID=2 AND FDC='平')=3
		INSERT INTO #Result
		SELECT '合计2','平',0,0
   ELSE
		WITH tempB AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					SUM(FVALUE) AS FVALUE
			FROM #Result b 
			WHERE b.GROUPID=2 AND b.FDC='贷'
			GROUP BY b.GROUPID,b.FDC
		)
		INSERT INTO #Result
		SELECT '合计2',
			   CASE 
					WHEN FVALUE=0 THEN '平'
					ELSE '贷'
			   END,
			   FVALUE,
			   0
	   FROM tempB
  
   ---试算是否平衡
   IF (SELECT COUNT(*) FROM #Result WHERE GROUPID=0 AND FDC='平')=2
		INSERT INTO #Result
		SELECT '试算平衡','平',0,-1
   ELSE
		WITH tempC AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					b.FVALUE
			FROM #Result b 
			WHERE b.GROUPID=0 AND (b.FDC='借' OR b.FDC='贷')
		)
		INSERT INTO #Result
		SELECT TOP 1
			   '试算平衡',
			   CASE 
					WHEN FVALUE1=FVALUE2 THEN '平'
					WHEN FVALUE1>FVALUE2 THEN FDC1
					ELSE FDC2 
			   END,
			   ABS(FVALUE1-FVALUE2),
			   -1
	   FROM
	   ( 
			SELECT a.FDC AS FDC1,
				  a.FVALUE AS FVALUE1,
				  CASE 
					WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
					WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
					ELSE b.FDC
				  END AS FDC2,
				  CASE 
					WHEN b.FVALUE IS NULL THEN 0
					ELSE b.FVALUE
				  END AS FVALUE2
			FROM tempC a   
			LEFT JOIN tempC b ON a.GROUPID=b.GROUPID AND a.FDC!=b.FDC 
	   ) c 
	   
	
    --------------------------------------------------------------------------------------------------------------------------------------------------
    ---------------------------------------------------取出年初数据---------------------------------------------------------------------------------
    CREATE TABLE #temp1
    (
       ACCOUNTTYPE VARCHAR(50),		---科目类型
       FDC		   VARCHAR(5),		---余额方向
       FVALUE	    NUMERIC(24, 10) 	---余额值
    )
    
    INSERT INTO #temp1
    SELECT ACCOUNTTYPE,
		   CASE 
			   WHEN FDC=1 THEN '借'
			   ELSE '贷'
		   END,
		   SUM(INIYTOTAL) 
    FROM #AC_INIACCOUNT
    GROUP BY ACCOUNTTYPE,FDC
    
    CREATE TABLE #Result1
    (
	   ACCOUNTTYPE VARCHAR(50),		---科目类型
       FDC		   VARCHAR(5),		---余额方向
       FVALUE	    NUMERIC(24, 10) ,	---余额值
       GROUPID	   INT				---合计时使用，【资产，共同，成本】是一组，【负债，权益，损益】是一组
    )
    
    ---资产
	; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC  
       WHERE a.ACCOUNTTYPE='00001'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '资产',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a  
      
    ---共同
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00006'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '共同',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借'
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a           
	
	---成本
	; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00004'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '成本',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '借' 
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE1-FVALUE2
			 ELSE FVALUE2-FVALUE1
		  END,
		  1
    FROM a    
    
    ---负债
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00002'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '负债',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷'
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
     
    ----权益
    ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC  
       WHERE a.ACCOUNTTYPE='00005'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '权益',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷' 
		  END,
		  CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
         
    --损益
     ; WITH  a  AS 
	(
	   SELECT a.FDC AS FDC1,
		      a.FVALUE AS FVALUE1,
		      CASE 
				WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
				WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
				ELSE b.FDC
			  END AS FDC2,
			  CASE 
				WHEN b.FVALUE IS NULL THEN 0
				ELSE b.FVALUE
			  END AS FVALUE2
	   FROM #temp1 a 
	   LEFT JOIN #temp1 b ON a.ACCOUNTTYPE=b.ACCOUNTTYPE AND a.FDC!=b.FDC 
       WHERE a.ACCOUNTTYPE='00003'
    )
    INSERT INTO #Result1
    SELECT TOP 1
		  '损益',
		  CASE 
			  WHEN FVALUE1=FVALUE2 THEN '平'
			  ELSE '贷'  
		  END,
		   CASE 
			 WHEN FDC1='借' THEN FVALUE2-FVALUE1
			 ELSE FVALUE1-FVALUE2
		  END,
		  2
    FROM a    
    
    --------【资产，共同，成本】的合计
    IF (SELECT COUNT(*) FROM #Result1 WHERE GROUPID=1 AND FDC='平')=3
		INSERT INTO #Result1
		SELECT '合计1','平',0,0
    ELSE
		WITH tempA AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					SUM(FVALUE) AS FVALUE
			FROM #Result1 b 
			WHERE b.GROUPID=1 AND b.FDC='借' 
			GROUP BY b.GROUPID,b.FDC
		)
		INSERT INTO #Result1
		SELECT TOP 1
			   '合计1',
			   CASE 
					WHEN FVALUE=0 THEN '平'
					ELSE '借'
			   END,
			   FVALUE,
			   0
	   FROM tempA
    
   --------【负债，权益，损益】的合计
   IF (SELECT COUNT(*) FROM #Result1 WHERE GROUPID=2 AND FDC='平')=3
		INSERT INTO #Result1
		SELECT '合计2','平',0,0
   ELSE
		WITH tempB AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					SUM(FVALUE) AS FVALUE
			FROM #Result1 b 
			WHERE b.GROUPID=2 AND  b.FDC='贷'
			GROUP BY b.GROUPID,b.FDC
		)
		INSERT INTO #Result1
		SELECT TOP 1
			   '合计2',
			   CASE 
					WHEN FVALUE=0 THEN '平'
					ELSE '贷'
			   END,
			   FVALUE,
			   0
	   FROM tempB
	  
   ---试算是否平衡
   IF (SELECT COUNT(*) FROM #Result1 WHERE GROUPID=0 AND FDC='平')=2
		INSERT INTO #Result1
		SELECT '试算平衡','平',0,-1
   ELSE
		WITH tempC AS 
		(
			SELECT  b.GROUPID,
					b.FDC,
					b.FVALUE
			FROM #Result1 b 
			WHERE b.GROUPID=0 AND (b.FDC='借' OR b.FDC='贷')
		)
		INSERT INTO #Result1
		SELECT TOP 1
			   '试算平衡',
			   CASE 
					WHEN FVALUE1=FVALUE2 THEN '平'
					WHEN FVALUE1>FVALUE2 THEN FDC1
					ELSE FDC2 
			   END,
			   ABS(FVALUE1-FVALUE2),
			   -1
	   FROM
	   ( 
			SELECT a.FDC AS FDC1,
				  a.FVALUE AS FVALUE1,
				  CASE 
					WHEN b.FDC IS NULL AND a.FDC='借' THEN '贷'
					WHEN b.FDC IS NULL AND a.FDC='贷' THEN '借'
					ELSE b.FDC
				  END AS FDC2,
				  CASE 
					WHEN b.FVALUE IS NULL THEN 0
					ELSE b.FVALUE
				  END AS FVALUE2
			FROM tempC a   
			LEFT JOIN tempC b ON a.GROUPID=b.GROUPID AND a.FDC!=b.FDC 
	   ) c 
	
	
    ---------------------------------------------------判断是否平衡---------------------------------------------------------------------------------
   DECLARE @Result VARCHAR(50)
   SELECT @Result=fdc FROM #Result WHERE GROUPID=-1
   IF @Result!='平'
	BEGIN
	   RETURN -1
	END 
   SELECT @Result=fdc FROM #Result1 WHERE GROUPID=-1
   IF @Result!='平'
	BEGIN
	   RETURN -1
	END 
	
    RETURN 1
    -------------------------------------------------------------------------------------------------------------------------------------------------
  
	
    DROP TABLE #tempFather,#tempData,#AC_INIACCOUNT,#temp,#Result,#temp1,#Result1,#tempAIAC,#tempAIACD
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_IsVerifyStype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_IsVerifyStype
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	from dz
	awu
	2013.6.13
	用于获取线性分支机构，可区分独立核算
*/
CREATE   PROCEDURE Web_IsVerifyStype
(
	@OperatorId		VARCHAR(100),		--操作员Id	
	@Filter			VARCHAR(300)='',	--过滤 1、编号  2、名称  3、拼音码 4、联系电话
	@isverify		INT = 0				--是否独立核算 0.所有 1.独立核算，
)
--@encode$--
AS
SET NOCOUNT ON

--特殊处理[符号
SET @Filter = REPLACE(@Filter,'[','[[]')		
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--************************************************************分支机构基本信息************************************************************

		CREATE TABLE #SFType
		(
			TypeID			VARCHAR(100),
			ParId			VARCHAR(100),
			SonNum			INT,
			UserCode		VARCHAR(400),
			FullName		VARCHAR(400),
			PyCode			VARCHAR(400),
			Deleted			INT,
			isSelfVerify	INT
		)

		--判断权限范围
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerSTypeId = '00000')
			INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,isSelfVerify) 
			SELECT f.TypeId,s.ParId,s.SonNum,s.UserCode,s.FullName,s.PyCode,s.Deleted,s.IsSelfVerify
			FROM dbo.F_GetManDetailSType(@OperatorId) f
					INNER JOIN dbo.SType s ON  s.TypeId=f.TypeId
		ELSE
			INSERT INTO #SFType(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,isSelfVerify) 
			SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted,IsSelfVerify
			FROM SType 
			
		IF @Filter = ''
			BEGIN
				IF @isverify = 0
					SELECT	TypeId,SonNum,UserCode,FullName 
					FROM #SFType 
					WHERE Deleted = 0 AND TypeId <> '00000' AND SonNum = 0
					ORDER BY UserCode
				ELSE
					SELECT	TypeId,SonNum,UserCode,FullName 
					FROM #SFType 
					WHERE Deleted = 0 AND TypeId <> '00000' AND SonNum = 0 AND isSelfVerify = 1
					ORDER BY UserCode
			END
		ELSE
			IF @isverify = 0
				SELECT	TypeId,SonNum,UserCode,FullName 
				FROM #SFType
				WHERE Deleted = 0 AND SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%') AND TypeId <> '00000'  
				ORDER BY UserCode
			ELSE
				SELECT	TypeId,SonNum,UserCode,FullName 
				FROM #SFType
				WHERE Deleted = 0 AND SonNum = 0 AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%') AND TypeId <> '00000'  AND isSelfVerify = 1
				ORDER BY UserCode

		DROP TABLE #SFType			
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ItemBalanceDetailsQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_ItemBalanceDetailsQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012-12-20
	描述：项目明细余额表
*/
CREATE PROCEDURE Web_ItemBalanceDetailsQuery
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@stypeid			VARCHAR(50),
	@itemids			VARCHAR(1000),
	@cid				INT,
	@startDate			DATETIME,
	@endDate			DATETIME,
	@noshowZero			INT,				--不显示为0的
	@from				INT=0				--1.来自分类表时，@itemIds=''表示一个都没有
)
--@encode$--
AS
SET NOCOUNT ON


CREATE TABLE #TempItem
(
	nId			VARCHAR(50),
	usercode	VARCHAR(200),
	FullName	VARCHAR(200),
	comment		VARCHAR(400),
	DELETED		INT
)


INSERT INTO #TempItem( nId, usercode, FullName,comment,DELETED )
EXEC dbo.Web_GetAcItemsWithLimit @OperatorId

IF @from = 1 AND @itemIds = ''
	DELETE FROM #TempItem

SELECT * 
FROM
(
	SELECT UserCode,FullName,SUM(Total00+Total) AS total,SUM(Total00+Total) AS total1,SUM(Ntotal00+Ntotal) AS ntotal 
	FROM
	(
		SELECT a.UserCode,a.FullName,0 AS Total00,ISNULL(b.Total,0) AS total,0 AS NTotal00,ISNULL(b.Ntotal,0) AS NTotal
		FROM #TempItem a
		LEFT JOIN dbo.ListTable b ON a.nId = b.AtypeId 
				AND b.STypeid IN (SELECT * FROM dbo.f_split(@stypeid,',')) 
				AND b.BillDate <= @endDate 
				AND b.CID = @cid
		WHERE(@itemIds <> '' AND a.nId IN (SELECT * FROM dbo.f_split(@itemIds,',')) OR @itemIds = '')
		UNION ALL
		SELECT a.UserCode,a.FullName,c.Total00,0 AS total,c.NTotal00,0 AS ntotal
		FROM #TempItem a
			LEFT JOIN dbo.AType_Total c ON a.nId = c.ATypeID AND c.STypeid IN (SELECT * FROM dbo.f_split(@stypeid,','))  AND c.CID = @cid
		WHERE(@itemIds <> '' AND a.nId IN (SELECT * FROM dbo.f_split(@itemIds,',')) OR @itemIds = '')
	)T
	GROUP BY UserCode,FullName
)TT
WHERE ((total <> 0 AND @noshowZero = 1) OR @noshowZero = 0)

	

DROP TABLE #TempItem

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ItemBalanceQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_ItemBalanceQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012.11.27
	描述：项目余额表
*/
CREATE PROCEDURE Web_ItemBalanceQuery
(
	@OperatorID	VARCHAR(50),	--操作员
	@stypeid	VARCHAR(50),	--分支机构
	@itemIds	VARCHAR(1000),	--项目id串
	@cid		INT,			--币种
	@level		INT,			--层级
	@allLevel	INT,			--所有层级
	@startDate	DATETIME,		--开始日期
	@endDate	DATETIME,		--结束日期
	@noshowZero	INT,			--不显示为0的
	@itemtypeid	VARCHAR(50)		--一级结点typeid
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #TempItem
(
	nId			VARCHAR(50),
	usercode	VARCHAR(200),
	FullName	VARCHAR(200),
	comment		VARCHAR(400),
	DELETED		INT
)


INSERT INTO #TempItem( nId, usercode, FullName,comment,DELETED )
EXEC dbo.Web_GetAcItemsWithLimit @OperatorId


DECLARE @Sql VARCHAR(MAX)


--取结点对应项目数据
SET @Sql = '

SELECT nId,typeId,ParId,leveal,sonnum,FullName,Attribute,itemNid,itemFullName,
		T.total + ISNULL(e.total00,0) AS total,T.total + ISNULL(e.total00,0) AS total1,T.ntotal + ISNULL(e.ntotal00,0) AS ntotal
INTO #tmpData
FROM
(
SELECT a.nId,a.typeId,a.ParId,a.leveal,a.sonnum,a.FullName,a.Attribute,
		c.nId AS itemNid,c.FullName AS itemFullName,
		SUM(ISNULL(d.total,0)) AS total,
		SUM(ISNULL(d.Ntotal,0)) AS ntotal

FROM dbo.ItemType a
	LEFT JOIN dbo.ItemType_Item b ON a.nId = b.itemTypeId
	LEFT JOIN #TempItem c ON b.itemId = c.nId'
SET @Sql +=		
	' LEFT JOIN dbo.ListTable d ON c.nId = d.AtypeId
		AND d.STypeID IN (SELECT a FROM dbo.f_split('''+@stypeid+''','',''))
		AND d.CID = '+CAST(@cid AS VARCHAR(100))+'
		AND BillDate <= '''+CAST(@endDate AS VARCHAR(100))+'''
	WHERE a.STypeid ='''+@stypeid+''' AND a.typeId <> ''00000'' AND LEFT(A.typeid,5) = '''+ @itemtypeid + '''
	GROUP BY a.nId,a.typeId,a.ParId,a.leveal,a.sonnum,a.FullName,a.Attribute,c.nId,c.FullName

)T

LEFT JOIN dbo.AType_Total e ON T.itemNid = e.ATypeID 
	AND e.STypeID IN (SELECT a FROM dbo.f_split('''+@stypeid+''','','')) AND e.cid ='+ CAST(@cid AS VARCHAR(100))


--排除0金额
IF @noshowZero = 1
	SET @sql += ' DELETE FROM #tmpData WHERE total = 0 '

--合计父结点金额,合并子结点数据
SET @sql += '

;WITH Result AS
(
	SELECT a.nId,a.typeId,a.ParId,a.leveal,a.sonnum,a.FullName,a.Attribute,a.itemNid,a.itemFullName,a.total,a.ntotal,b.total AS T,b.ntotal AS NT
	FROM #tmpData a
		LEFT JOIN #tmpData b ON b.parid = a.typeid
	WHERE b.ParId IS NULL
	UNION ALL
	SELECT U.nId,U.typeId,U.ParId,U.leveal,U.sonnum,U.FullName,U.Attribute,U.itemNid,U.itemFullName,U.total,U.ntotal,
			CASE WHEN ISNULL(V.total,0)=0 THEN V.T ELSE V.total END AS T,
			CASE WHEN ISNULL(V.ntotal,0)=0 THEN V.NT ELSE V.ntotal END AS NT
	FROM #tmpData U
		INNER JOIN Result V ON U.typeId = V.ParId
)


SELECT * FROM
(
SELECT typeid,parid,leveal,
		CASE WHEN Attribute = 2 THEN '+'''-'''+' ELSE fullname END AS fullname,Attribute,
		CASE WHEN Attribute = 2 THEN ISNULL(itemnid,-1) ELSE ISNULL(itemnid,0) END AS itemnid,itemfullname, 
		SUM(CASE WHEN T IS NULL THEN ISNULL(total,0) ELSE T END) AS total,
		SUM(CASE WHEN T IS NULL THEN ISNULL(total,0) ELSE T END) AS total1,
		SUM(CASE WHEN NT IS NULL THEN ISNULL(ntotal,0) ELSE NT END) AS ntotal
FROM Result
GROUP BY 
typeid,parid,leveal,fullname,Attribute,itemnid,itemfullname
UNION ALL
SELECT typeId,ParId,leveal,FullName,Attribute,0 AS itemnid,NULL AS itemfullname,
		SUM(ISNULL(total,0)) AS total,
		SUM(ISNULL(total,0)) AS total1,
		SUM(ISNULL(ntotal,0)) AS ntotal
FROM #tmpData a
WHERE attribute = 2
GROUP BY typeId,ParId,leveal,FullName,Attribute
)T
WHERE T.leveal <> 0'

IF @allLevel = 0 --不包含明细
	SET @Sql += ' AND T.leveal <= '+CAST(@level AS VARCHAR(10)) + ' AND T.itemnid = 0'
ELSE
BEGIN
	SET @Sql += ' AND T.leveal > 0'
	IF ISNULL(@itemIds,'') <> ''
		SET @sql = @Sql + ' AND T.itemnid = 0 OR T.itemnid IN (SELECT a FROM dbo.f_split('''+@itemIds+''','','')) '
END

SET @Sql += ' ORDER BY typeid,itemnid'
SET @Sql += ' DROP TABLE #tmpData'
EXEC(@sql)

DROP TABLE #TempItem

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_JCommissionDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_JCommissionDetailQuery]
GO








--==========================================
--作者：谢吉康
--日期：2003-03-18
--描述：代销库存报表，包含委托代销和受托代销
--==========================================
CREATE                                                       PROCEDURE [Web_JCommissionDetailQuery] 
(
	@OperatorID varchar(25),	--操作员ID 
	@startDate     varchar(20),           --开始时间
	@endDate      varchar(20),
	@mType varchar(20),		--查询的小类  WB=委托客户查询	WK=委托仓库查询	WJ=委托结算	 SB=受托客户查询	SK=受托仓库查询	SJ=受托结算	
	@PtypeID varchar(25),		--商品的ID
	@BtypeID varchar(25),		--客户的ID
	@Jtype  int,			--结算类型  0.非结算  1.全部发货        2.已结算             3.未结算
	@sortFild varchar(20),		--排序字段
	@sortType int			--1.升序  0.降序
)
--@encode$--
AS

SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re

DECLARE @CurSonNum int 
DECLARE @CurPSonNum int
DECLARE @isSon int
DECLARE @SortSQL varchar(2000)
DECLARE @SQL varchar(8000)

SET @SortSQL =''


IF @mType='SJ'
BEGIN
SELECT @SQL='	  
	  SELECT 	bil.billdate,
			bil.billcode,
			p.usercode as pusercode,
			p.fullname as pfullname,
			p.standard,
			p.type,
			p.entrycode,

			p.unit1,
			bt.usercode as busercode,
			bt.fullname as bfullname,
		'
IF @Jtype=1
	SELECT @SQL= @SQL +'
			sum(isnull(b.qty,0)) as qty,
			sum(isnull(b.costprice,0)) as costprice,
			sum(isnull(b.costtotal,0)) as costtotal,
			bil.billtype,
			bil.billnumberid,
			sum(isnull(b.price,0)) as price,
			sum(isnull(b.total,0)) as total,
'
IF @Jtype=2
	SELECT @SQL= @SQL +'
			sum(isnull(-b.qty,0)) as qty,
			sum(isnull(b.costprice,0)) as costprice,
			sum(isnull(-b.costtotal,0)) as costtotal,
			bil.billtype,
			bil.billnumberid,
			sum(isnull(b.price,0)) as price,
			sum(isnull(-b.total,0)) as total,
'
IF @Jtype=3
	SELECT @SQL= @SQL +'
			sum(isnull(b.qty,0)) as qty,
			sum(isnull(b.costprice,0)) as costprice,
			sum(isnull(b.costtotal,0)) as costtotal,
			bil.billtype,
			bil.billnumberid,
			sum(isnull(b.price,0)) as price,
			sum(isnull(b.total,0)) as total,
'
SELECT @SQL= @SQL +'
			bil.checke,
			e.fullname as efullname,
			bil.totalmoney,
			bil.comment,
			bil.tax,
			bil.ktypeid,
			bil.etypeid 
	  FROM          InOutStockTable b,
			billindex bil,
			ptype p,
			btype bt,
			employee e
	  WHERE         bil.billnumberid=b.billnumberid
			AND bil.etypeId=e.TypeID
		        AND bil.draft=0
		        AND bil.RedWord=0
			        AND bil.ifcheck=''t''
			AND b.ptypeid=p.typeid
			AND bil.btypeid=bt.typeid	
			AND b.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
			AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+''
			--AND ( bil.KtypeID Like '+char(39)+@MKTypeID+'%'+char(39)+' )'


			IF @Jtype=1
				SELECT @SQL=@SQL+' AND bil.Billtype in (144,146) '+'
				 AND 
					(
						(b.billtype=144 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
						(b.billtype=146 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
					)'
			IF @Jtype=2
				SELECT @SQL=@SQL+' AND bil.ktypeid='+char(39)+'10000'+char(39)+' AND bil.billtype=''145'''								
			IF @Jtype=3
				SELECT @SQL=@SQL+' AND bil.billtype in (144,145,146,147)'+
			    ' AND 
				(
					(b.billtype=144 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
				  	(b.billtype=145 AND b.ktypeid=''10000'' )    OR
					(b.billtype=146 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
					(b.billtype=147 AND b.ktypeid=''10000'')
				)'
				
				-- 受托代销查询增加调价单  2004-08-24  chen_qihua
				-- SELECT @SQL=@SQL+' AND bil.billtype in (144,145,146)'
			SELECT @SQL=@SQL+'
					AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
					AND b.ptypeid like '+char(39)+@ptypeId+'%'+char(39)+'	
					AND (bil.BtypeID like '+char(39)+@MBtypeId+'%'+char(39)+' OR bil.BtypeID like '+char(39)+@MBtypeId2+'%'+char(39)+')'
			IF @bTypeID<>'00000'
				SELECT @SQL = @SQL+'AND bil.BtypeID like '+char(39)+@bTypeId+'%'+char(39)
	

			SELECT @SQL=@SQL+' GROUP BY  
						bil.billdate,
						bil.billcode,
						p.fullname,
						bt.fullname,
						bil.billtype,
						bil.billnumberid,
						bil.checke,
						e.fullname,
						bt.usercode,																										
						p.usercode,
						p.standard,
						p.type,
						p.entrycode,
						p.unit1,
						bil.totalmoney,
						bil.comment,
						bil.tax,
						bil.ktypeid,		
						bil.etypeid,
						b.qty'	

	--=======================================构造排序字段
	SELECT @SortSQL=''
	IF @sortFild='BillDate'    SELECT @SortSQL=' ORDER BY bil.billdate '
	IF @sortFild='BillCode'    SELECT @SortSQL=' ORDER BY  bil.BillCode '
	IF @sortFild='EtypeID'     SELECT @SortSQL=' ORDER BY  bil.EtypeID '
	IF @sortFild='PUserCode'   SELECT @SortSQL=' ORDER BY  p.usercode '
	IF @sortFild='PFullName'   SELECT @SortSQL=' ORDER BY  p.fullname '
	IF @sortFild='Qty'  	   SELECT @SortSQL=' ORDER BY  b.Qty '
	IF @sortFild='Checke'      SELECT @SortSQL=' ORDER BY  bil.Checke '
	IF @sortFild='BillType'    SELECT @SortSQL=' ORDER BY  bil.BillType '
	IF @sortFild='KtypeID'     SELECT @SortSQL=' ORDER BY  bil.KtypeID '
	IF @sortFild='UserCode'    SELECT @SortSQL=' ORDER BY  bil.billdate '
	IF @sortFild='CostTotal'   SELECT @SortSQL=' ORDER BY  b.CostTotal '
	IF @SortSQL ='' 
		SELECT @SortSQL=' ORDER BY  p.usercode '
	IF @sortType=1 
		SET @SortSQL = @SortSQL +' ASC '
	ELSE
		SET @SortSQL = @SortSQL +' DESC '
	SET @SQL = @SQL + @SortSQL



END 


IF @mType='WJ'
BEGIN
	SELECT @SQL='
	  SELECT 	bil.billdate,
			bil.billcode,
			p.usercode as pusercode,
			p.fullname as pfullname,
			p.standard,
			p.type,
			p.entrycode,
			p.unit1,
			bt.usercode as busercode,
			bt.fullname as bfullname,
	'
	IF @Jtype=1
		SELECT @SQL = @SQL +'
				isnull(sum(- b.qty ),0) as qty,
				isnull(sum(b.costprice),0) as costprice,
				isnull(sum( -b.costtotal ),0) as costtotal,
				bil.billtype,
				bil.billnumberid,
				sum(isnull(b.price,0)) as price,
				sum(isnull( -b.total  ,0)) as total,
			'
	IF @Jtype=2
		SELECT @SQL = @SQL +'
				sum(isnull(-b.qty,0)) as qty,
				sum(isnull(b.costprice,0)) as costprice,
				sum(isnull(-b.CostTotal,0)) as costtotal,
				bil.billtype,
				bil.billnumberid,
				sum(isnull(b.price,0)) as price,
				sum(isnull(-b.total,0)) as total,
			'
	IF @Jtype=3
		SELECT @SQL = @SQL +'
				isnull(sum(case b.billtype when 140 then -b.qty when 142 then -b.qty  else b.qty end),0) as qty,
				isnull(sum(b.costprice),0) as costprice,
				isnull(sum(case b.billtype when 140 then -b.costtotal when 142 then -b.CostTotal else b.costtotal end ),0) as costtotal,
				bil.billtype,
				bil.billnumberid,
				sum(isnull(b.price,0)) as price,
				sum(isnull(case b.billtype when 140 then -b.total when 142 then  -b.total else b.total end ,0)) as total,
			'


SELECT @SQL = @SQL +'
			bil.checke,
			e.fullname as efullname,					
			bil.totalmoney,			
			bil.comment,
			bil.tax,
			bil.ktypeid,
			bil.etypeid 
	  FROM          InOutStockTable b,
			billindex bil,
			ptype p,
			btype bt,
			employee e																								
	  WHERE         bil.billnumberid=b.billnumberid
			AND bil.etypeId=e.TypeID						 				
		        AND bil.draft=0
		        AND bil.RedWord=0
			        AND bil.ifcheck=''t''
			AND b.ptypeid=p.typeid
			AND bil.btypeid=bt.typeid								
			AND b.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
			AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+''
			--AND ( bil.KtypeID Like '+char(39)+@MKTypeID+'%'+char(39)+' )'

			IF @Jtype=1
				SELECT @SQL=@SQL+' AND bil.Billtype in (140,142) ' +'
				AND
				(
					(b.billtype=140 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
				  	(b.billtype=142 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
				)'	

			IF @Jtype=2
				SELECT @SQL=@SQL+' AND bil.ktypeid='+char(39)+'10000'+char(39)+' AND bil.billtype=''141'''								
			IF @Jtype=3
				SELECT @SQL=@SQL+' AND bil.billtype in (140,141,142,143)' +'
				AND
				(
					(b.billtype=140 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
				  	(b.billtype=141 AND b.ktypeid=''10000'' )    OR
					(b.billtype=142 AND b.ktypeid<>''10000'' AND b.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
					(b.billtype=143 AND b.ktypeid=''10000'')
				)'	

				-- 委托代销未结算查询增加 调价单  2004-08-24 chen_qihua
				-- SELECT @SQL=@SQL+' AND bil.billtype in (140,141,142)'
			SELECT @SQL=@SQL+'
			AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)+'
			AND b.ptypeid like '+char(39)+@ptypeId+'%'+char(39)+'	
			AND (bil.BtypeID like '+char(39)+@MBtypeId+'%'+char(39)+' OR bil.BtypeID like '+char(39)+@MBtypeId2+'%'+char(39)+')'
	IF @bTypeID<>'00000'
		SELECT @SQL = @SQL+'AND bil.BtypeID like '+char(39)+@bTypeId+'%'+char(39)

	
	SELECT @SQL=@SQL+'GROUP BY  
				bil.billdate,
				bil.billcode,
				p.fullname,
				bt.fullname,
				bil.billtype,
				bil.billnumberid,
				bil.checke,
				e.fullname,
				bt.usercode,															
				p.usercode,
				p.standard,
				p.type,
				p.entrycode,
				p.unit1,
				bil.totalmoney,
				bil.comment,
				bil.tax,
				bil.ktypeid,
				bil.etypeid,
				b.qty'	

	--=======================================构造排序字段
	SELECT @SortSQL=''
	IF @sortFild='BillDate'    SELECT @SortSQL=' ORDER BY bil.billdate '
	IF @sortFild='BillCode'    SELECT @SortSQL=' ORDER BY  bil.BillCode '
	IF @sortFild='EtypeID'     SELECT @SortSQL=' ORDER BY  bil.EtypeID '
	IF @sortFild='PUserCode'   SELECT @SortSQL=' ORDER BY  p.usercode '
	IF @sortFild='PFullName'   SELECT @SortSQL=' ORDER BY  p.fullname '
	IF @sortFild='Qty'  	   SELECT @SortSQL=' ORDER BY  b.Qty '
	IF @sortFild='Checke'      SELECT @SortSQL=' ORDER BY  bil.Checke '
	IF @sortFild='BillType'    SELECT @SortSQL=' ORDER BY  bil.BillType '
	IF @sortFild='KtypeID'     SELECT @SortSQL=' ORDER BY  bil.KtypeID '
	IF @sortFild='UserCode'    SELECT @SortSQL=' ORDER BY  bil.billdate '
	IF @sortFild='CostTotal'   SELECT @SortSQL=' ORDER BY  b.CostTotal '
	IF @SortSQL ='' 
		SELECT @SortSQL=' ORDER BY  p.usercode '
	IF @sortType=1 
		SET @SortSQL = @SortSQL +' ASC '
	ELSE
		SET @SortSQL = @SortSQL +' DESC '
	SET @SQL = @SQL + @SortSQL	

END
--PRINT @SQL
EXEC(@SQL)





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_JCommissionLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_JCommissionLineQuery]
GO







--==========================================
--作者：谢吉康
--日期：2003-03-18
--描述：代销库存报表，包含委托代销和受托代销
--==========================================
CREATE                                                     PROCEDURE [Web_JCommissionLineQuery] 
(
	@OperatorID varchar(25),	--操作员ID 
	@startDate     varchar(20),           --开始时间
	@endDate      varchar(20),
	@mType varchar(20),		--查询的小类  WB=委托客户查询	WK=委托仓库查询	WJ=委托结算	 SB=受托客户查询	SK=受托仓库查询	SJ=受托结算	
	@PtypeID varchar(25),		--商品的ID
	@BtypeID varchar(25),		--客户的ID
	@Jtype  int,			--结算类型  0.非结算  1.全部发货        2.已结算             3.未结算
	@sortFild varchar(20),		--排序字段
	@sortType int			--1.升序  0.降序
)
--@encode$--
AS

SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re

DECLARE @CurSonNum int 
DECLARE @CurPSonNum int
DECLARE @isSon int
DECLARE @SortSQL varchar(2000)
DECLARE @SQL varchar(8000)

SET @SortSQL =''
SET @SQL=''

IF @mType='SJ'
BEGIN

	IF EXISTS (SELECT SonNum FROM Ptype WHERE SonNum>0 AND TypeID=@PtypeID)
		SET @isSon =1
	ELSE
		SET @isSon =0


	SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID	
	SELECT @SQL='
			SELECT  p.usercode,p.fullname,p.sonnum,p.typeid,(sum(isnull(a.qty,0))) as qty,sum(isnull(a.costprice,0)) as costprice,(sum(isnull(a.costtotal,0))) as costtotal	
			FROM Ptype p
				LEFT JOIN
					('
					IF @Jtype=1	
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
								 		BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid		
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			AND bil.BillType in (144,146) AND a.KtypeId<>''10000'''	
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
										IF @pTypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
										IF @bTypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										
									
									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')
												  AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)
					END
					IF @Jtype=2
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(-a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(-a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
			 							BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid	
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
										AND bil.BillType=145' +'
										 AND 
											(
												(a.billtype=145 AND a.ktypeid=''10000'' )    
												
											)'
											
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
										IF @pTypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
										IF @bTypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
			  			
									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)																		


									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

					END
					IF @Jtype=3
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
								 		BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			AND bil.BillType in (144,145,146) '	 +'
			 								AND 
												(
													(a.billtype=144 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
												  	(a.billtype=145 AND a.ktypeid=''10000'' )    OR
													(a.billtype=146 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
												)'
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
										IF @pTypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
										IF @bTypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										

									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												 -- AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

					END	
								
			SELECT @SQL=@SQL+')a
			ON   p.typeid=a.ptypeid
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
	IF @pTypeId='00000'
		SELECT @SQL=@SQL+' AND  p.sonnum=0 AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
	IF @pTypeId<>'00000' AND @isSon=0
		SELECT @SQL=@SQL+' AND  p.typeId='+char(39)+@pTypeId+char(39)+' AND p.deleted=0'		
	IF @pTypeId<>'00000' AND @isSon=1
		SELECT @SQL=@SQL+' AND p.typeid like '+char(39)+@pTypeId+'%'+char(39)+' AND p.deleted=0 AND p.sonnum=0'
	SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'

	IF @sortFild ='qty'
			SELECT @SortSQL=' Order By Qty '					
	IF @sortFild ='CostTotal'
		SELECT @SortSQL=' Order By CostTotal '	
	IF @SortSQL=''
		SELECT @SortSQL=@SortSQL+' Order By P.UserCode'
	IF @sortType=1 
		SELECT @SortSQL=@SortSQL +' ASC '
	ELSE
		SELECT @SortSQL=@SortSQL +' DESC '

	SELECT @SQL = @SQL + @SortSQL

END 

IF @mType='WJ'
BEGIN
	IF EXISTS (SELECT SonNum FROM Ptype WHERE SonNum>0 AND TypeID=@PtypeID)
		SET @isSon =1
	ELSE
		SET @isSon =0

	SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@bTypeID
	SELECT @SQL='
			SELECT  p.usercode,p.fullname,p.sonnum,p.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.costprice,0)) as costprice,sum(isnull(a.costtotal,0)) as costtotal	
			FROM Ptype p
				LEFT JOIN
					('
					IF @Jtype=1	
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(-a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(-a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
								 		BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			   AND bil.BillType in (140,142) '+'	
											AND 
												(
													(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
												  	(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
												)'											
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
										IF @pTypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
										IF @bTypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1

												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										



									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

					END
					IF @Jtype=2
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(-a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(-a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
			 							BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid	
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  			               AND bil.billtype=141' +'
										   AND 
											(
											  	(a.billtype=141 AND a.ktypeid=''10000'' ) 
		
											)'		

										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
										IF @pTypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
										IF @bTypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													
	  			
									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)																		

									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

					END
					IF @Jtype=3
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end,0) as qty,isnull(a.costprice,0) as costprice,isnull(case a.billtype when ''140'' then -a.costtotal when ''142'' then -a.costtotal else a.costtotal end ,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
								 		BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid				
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			AND bil.BillType in (140,141,142) '	+ '
											AND 
											(
												(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
											  	(a.billtype=141 AND a.ktypeid=''10000'' )    OR
												(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
												(a.billtype=143 AND a.ktypeid=''10000'')
											)'	
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@pTypeID
										IF @pTypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@pTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@pTypeID+char(39)
										IF @bTypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@bTypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@bTypeID+char(39)													

									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										

									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

					END	
				SELECT @SQL=@SQL+')a
			ON   p.typeid=a.ptypeid
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
	IF @pTypeId='00000'
		SELECT @SQL=@SQL+' AND  p.sonnum=0 AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 							
	IF @pTypeId<>'00000' AND @isSon=1
		SELECT @SQL=@SQL+' AND p.typeid like '+char(39)+@pTypeId+'%'+char(39)+' AND p.typeId<>'+char(39)+@pTypeId+char(39)+' AND p.deleted=0 AND p.sonnum=0'			
	IF @pTypeId<>'00000' AND @isSon=0
		SELECT @SQL=@SQL+' AND p.typeid ='+char(39)+@pTypeId+char(39)+' AND p.deleted=0'	
	SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'

	IF @sortFild ='qty'
			SELECT @SortSQL=' Order By Qty '					
	IF @sortFild ='CostTotal'
		SELECT @SortSQL=' Order By CostTotal '	
	IF @SortSQL=''
		SELECT @SortSQL=@SortSQL+' Order By P.UserCode'
	IF @sortType=1 
		SELECT @SortSQL=@SortSQL +' ASC '
	ELSE
		SELECT @SortSQL=@SortSQL +' DESC '

	SELECT @SQL = @SQL + @SortSQL

END
-- PRINT @SQL
EXEC(@SQL)




























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_JCommissionListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_JCommissionListQuery]
GO








--==========================================
--作者：谢吉康
--日期：2003-03-18
--描述：代销库存报表，包含委托代销和受托代销
--==========================================
CREATE                                                      PROCEDURE [Web_JCommissionListQuery] 
(
	@OperatorID varchar(25),	--操作员ID 
	@startDate     varchar(20),           --开始时间
	@endDate      varchar(20),
	@mType varchar(20),		--查询的小类  WB=委托客户查询	WK=委托仓库查询	WJ=委托结算	 SB=受托客户查询	SK=受托仓库查询	SJ=受托结算	
	@PtypeID varchar(25),		--商品的ID
	@BtypeID varchar(25),		--客户的ID
	@Jtype  int			--结算类型  0.非结算  1.全部发货        2.已结算             3.未结算
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorID is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re

DECLARE @CurSonNum int 
DECLARE @CurPSonNum int
DECLARE @isSon int
DECLARE @SortSQL varchar(2000)
DECLARE @SQL varchar(8000)
SET @SortSQL=''

IF @mType='SJ'
BEGIN
	SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@BtypeID	
	IF EXISTS (SELECT SonNum FROM Ptype WHERE SonNum>0 AND TypeID=@PtypeID)
		SET @isSon =1
	ELSE
		SET @isSon =0

	SELECT @SQL='
			SELECT  p.usercode,p.fullname,p.sonnum,p.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.costprice,0)) as costprice,sum(isnull(a.costtotal,0)) as costtotal
			FROM Ptype p
				LEFT JOIN
					('

					IF @Jtype=1	
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
								 		BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid		
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			AND bil.BillType in (144,146) AND a.KtypeId<>''10000'''	
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@PtypeID
										IF @PtypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@PtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@PtypeID+char(39)
										IF @BtypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@BtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@BtypeID+char(39)													

									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										
									
									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')
												  AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)
					END
					IF @Jtype=2
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(-a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(-a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
			 							BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid	
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
					  			             		   AND bil.KtypeId=''10000''
										   AND bil.billtype=''145'''			
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@PtypeID
										IF @PtypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@PtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@PtypeID+char(39)
										IF @BtypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@BtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@BtypeID+char(39)													
		  			
									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)																		

									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)


					END
					IF @Jtype=3
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
								 		BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid		
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			AND bil.BillType in (144,145,146) AND a.KtypeId=''10000'''	
				  	   		
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@PtypeID
										IF @PtypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@PtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@PtypeID+char(39)
										IF @BtypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@BtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@BtypeID+char(39)													

									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										
									
									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)
					END	
			SELECT @SQL=@SQL+')a
			ON   p.typeid=left(a.ptypeid,len(p.typeid))
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
			IF @PtypeID='00000'
				SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@PtypeID+char(39)+' AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
			IF @PtypeID<>'00000' AND @isSon=1
				SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@PtypeID+char(39)+' AND p.typeId<>'+char(39)+@PtypeID+char(39)+' AND p.deleted=0 '		
			IF @PtypeID<>'00000' AND @isSon=0
				SELECT @SQL=@SQL+' AND p.typeid ='+char(39)+@PtypeID+char(39)+' AND p.deleted=0'
			
				SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'		
	
				SELECT @SortSQL=@SortSQL+' Order By p.UserCode'
			SELECT @SQL=@SQL+ @SortSQL
				

END 

IF @mType='WJ'
BEGIN
	SELECT @CurSonNum=SonNum FROM Btype WHERE TypeID=@BtypeID	
	IF EXISTS (SELECT SonNum FROM Ptype WHERE SonNum>0 AND TypeID=@PtypeID)
		SET @isSon =1
	ELSE
		SET @isSon =0
	SELECT @SQL='
			SELECT  p.usercode,p.fullname,p.sonnum,p.typeid,sum(isnull(a.qty,0)) as qty,sum(isnull(a.costprice,0)) as costprice,sum(isnull(a.costtotal,0)) as costtotal	
			FROM Ptype p
				LEFT JOIN
					('
					IF @Jtype=1	
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(-a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(-a.costtotal,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
								 		BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			   AND bil.BillType in (140,142) '+'	
											AND 
												(
													(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
												  	(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') 
												)'											
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@PtypeID
										IF @PtypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@PtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@PtypeID+char(39)
										IF @BtypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1

												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@BtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@BtypeID+char(39)													
									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										



									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

					END
					IF @Jtype=2
					BEGIN
						SELECT @SQL=@SQL+'
									SELECT  isnull(-a.qty,0) as qty,isnull(a.costprice,0) as costprice,isnull(-a.costtotal,0) as costtotal,a.ptypeid

									FROM    InOutStockTable a,
			 							BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid										
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  			             		   AND bil.billtype=''141''
										   AND bil.KtypeId=''10000'''		
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@PtypeID
										IF @PtypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1

												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@PtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@PtypeID+char(39)
										IF @BtypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@BtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@BtypeID+char(39)													
										   						  			
									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)																		


									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

					END

					IF @Jtype=3
					BEGIN
						SELECT @SQL=@SQL+'

									SELECT  isnull( case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end,0) as qty,isnull(a.costprice,0) as costprice,isnull(case a.billtype when ''140'' then -a.costtotal when ''142'' then -a.costtotal else a.costtotal end ,0) as costtotal,a.ptypeid
									FROM    InOutStockTable a,
								 		BillIndex bil
									WHERE   a.billnumberid=bil.billnumberid
										   AND bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
										   AND bil.BillType in (140,141,142) '	+'
										   AND 
											(
												(a.billtype=140 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+')  OR
											  	(a.billtype=141 AND a.ktypeid=''10000'' )    OR
												(a.billtype=142 AND a.ktypeid<>''10000'' AND a.ktypeid LIKE '+char(39)+@MKTypeID+'%'+char(39)+') OR
												(a.billtype=143 AND a.ktypeid=''10000'')
											)'												
														
										SELECT @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@PtypeID
										IF @PtypeID='00000'
											SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurPSonNum>=1
												SELECT @SQL=@SQL+' AND a.PtypeID	Like '+char(39)+@PtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND a.PtypeID	= '+char(39)+@PtypeID+char(39)
										IF @BtypeID='00000'
											SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+'%'+char(39)
										ELSE
											IF @CurSonNum>=1
												SELECT @SQL=@SQL+' AND bil.BtypeID	Like '+char(39)+@BtypeID+'%'+char(39)
											Else
												SELECT @SQL=@SQL+' AND bil.BtypeID	= '+char(39)+@BtypeID+char(39)													
									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										



									SELECT @SQL=@SQL+' AND a.PtypeID Like '+char(39)+@MPTypeID+'%'+char(39)+'
												  AND bil.EtypeID Like '+char(39)+@METypeID+'%'+char(39)+'
												  AND (bil.BtypeID Like '+char(39)+@MBtypeID+'%'+char(39)+' Or bil.BtypeID Like '+char(39)+@MBtypeID2+'%'+char(39)+')'
												  --AND bil.KtypeID Like '+char(39)+@MKtypeID+'%'+char(39)

					END										
				SELECT @SQL=@SQL+')a
			ON   p.typeid=left(a.ptypeid,len(p.typeid))
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
	IF @PtypeID='00000'
		SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@PtypeID+char(39)+' AND p.deleted=0 AND p.TypeID Like '+char(39)+@MPTypeID+'%'+char(39) 						
	IF @PtypeID<>'00000' AND @isSon=1
		SELECT @SQL=@SQL+' AND p.parid = '+char(39)+@PtypeID+char(39)+' AND p.typeId<>'+char(39)+@PtypeID+char(39)+' AND p.deleted=0'			
	IF @PtypeID<>'00000' AND @isSon=0
		SELECT @SQL=@SQL+' AND p.typeid ='+char(39)+@PtypeID+char(39)+' AND p.deleted=0'	
	SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'

	SELECT @SortSQL=@SortSQL+' Order By p.UserCode'	
	SELECT @SQL=@SQL+ @SortSQL
END
-- PRINT @SQL
EXEC(@SQL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_JournalDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_JournalDetailQuery]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*------------------------------------------
    作者：李灏龙
	日期：2014年5月4日 15:43:21
	描述：日记账
-------------------------------------------*/
CREATE PROCEDURE Web_JournalDetailQuery 
(
       @STypeId 		VARCHAR(100),	---分支机构ID
       @batypeid		VARCHAR(50),	--现金科目typeid
       @bankaccountid		INT,	--银行账户id
	   @businessdateStart    DATE,			---起始业务日期
	   @businessdateEnd      DATE,			---结束业务日期
	   @tellerid		VARCHAR(MAX),	--出纳ID
	   @vgid			INT,			--凭证字
	   @flownostart		VARCHAR(500),	--凭证号起始
	   @flownoend		VARCHAR(500),	--凭证号结束
	   @billtypename	VARCHAR(500),	--单据类型
	   @billcode		VARCHAR(500),	--单据编号
	   @sourcetype		INT,			--来源类型
	   @DebitOrCredit	INT,			--借贷方向
	   @cid				INT,			--币种
	   @IsCash			INT,			--银行或是现金日记账查询   0：银行   1：现金
	   @FSettleid		INT,
	   @FSettleNo		VARCHAR(500),
	   @isCheckRelevance	INT,
	   @chvOperatorID	VARCHAR(50)		---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON

--如果是现金日记账查询，对传入的现金科目typeid进行权限验证，防止因为查询方案而带入不在权限范围内的科目
IF @IsCash = 1 AND NOT EXISTS (SELECT TOP 1 1 FROM F_LineAccount(@chvOperatorID,@STypeId) WHERE Typeid = @batypeid)
BEGIN
	SELECT ''
	RETURN
END



CREATE TABLE #temp
(
	id		INT,
	businessdate	DATETIME,
	businessdate1	DATE,
	summary		VARCHAR(1000),
	fdebit	 NUMERIC(24, 10) ,
	fcredit	 NUMERIC(24, 10) ,
	fendbalance	 NUMERIC(24, 10) ,
	stypeid	VARCHAR(50),
	sourceid	INT,
	tellerid	VARCHAR(50),
	tellername	VARCHAR(66),
	sfullname	VARCHAR(66),
	sourcename	VARCHAR(66),
	vgflowno	VARCHAR(66),
	voucherid	INT,
	cid			INT,
	FSettleNo	VARCHAR(66),
	FSettlename	VARCHAR(66),
	isCheckRelevance	INT,
	isdaysum		INT,	--是否是本日合计  0：不是  1：是
	issum		INT,   --是否是合计	0：不是   1：是   ps：主要用于排序  合计行isdaysum和issum都为1  本日合计行isdaysum为1，issum为0  其他行两者均为0
	voucherbillnumberid	INT,
	cidfullname	VARCHAR(50),
	goodsbillnumerid	INT
)


DECLARE @SQL NVARCHAR(MAX),
		@FLAG	INT,
		@TeStartPeriod INT,   --出纳启用期间
		@TeStartDate	DATE, --出纳启用日期
		@QueryYear INT,   --查询开始日期所在年份,用于获取上期期末余额
		@QueryPeriod INT,   --查询开始日期所在期间,用于获取上期期末余额
		@QueryFBegin DATE,   --查询开始日期所在期间,用于获取上期期末余额
		@LASTENDBALANCE	 NUMERIC(24, 10) ,
		@BUID	INT


SELECT @TeStartPeriod =	SFPeriod,@TeStartDate = FBegin FROM Te_StartPeriod tsp LEFT JOIN Ac_Period ap ON ap.FYear = tsp.SFYear AND ap.FPeriod = tsp.SFPeriod WHERE STypeId = @STypeId

IF @TeStartPeriod = 0 OR @TeStartDate > @businessdateEnd
BEGIN
	SELECT * FROM #temp
	DROP TABLE #temp
	RETURN
END

IF ISNULL(@batypeid,0) = ''
	SELECT @batypeid =ATypeId  FROM Te_BankAccount WHERE Id = @bankaccountid AND STypeId = @STypeId

-----如果查询起始日期小于出纳启用日期，则将查询起始日期修改为启用日期
IF @TeStartDate > @businessdateStart
	SET @businessdateStart = @TeStartDate

-----获取对应的年份、期间、期间起始日期
IF EXISTS (SELECT TOP 1 1 FROM Ac_Period WHERE FBegin <= @businessdateStart AND FEnd >= @businessdateStart)
	SELECT @QueryPeriod=FPeriod,@QueryYear=FYear,@QueryFBegin=FBegin FROM Ac_Period WHERE FBegin <= @businessdateStart AND FEnd >= @businessdateStart
ELSE
BEGIN
	SET @QueryYear = YEAR(@businessdateStart) -1
	SET @QueryPeriod = 13 
	SET @QueryFBegin = CAST( CAST(YEAR(@businessdateStart) AS VARCHAR) +'-'+ CAST(MONTH(@businessdateStart) AS VARCHAR) + '-1'  AS DATE)
END

SET @BUID = CASE WHEN @IsCash = 1 THEN 1 ELSE 2 END

IF @QueryPeriod = 1 OR NOT EXISTS (SELECT TOP 1 1 FROM Te_Balance WHERE AccountId=@bankaccountid AND ATypeId = @batypeid AND STypeid=@STypeId AND Cid = @cid AND FYear=@QueryYear AND FPeriod<@QueryPeriod AND BUId = @BUID)
BEGIN
	SET @QueryPeriod = 13
	SET @QueryYear = @QueryYear - 1
END

-----从余额表获取上期余额
IF EXISTS(SELECT TOP 1 1 FROM Te_Balance WHERE AccountId=@bankaccountid AND ATypeId = @batypeid AND STypeid=@STypeId AND Cid = @cid AND FYear<=@QueryYear AND FPeriod<@QueryPeriod AND BUId = @BUID)
	SELECT TOP 1 @LASTENDBALANCE=(CASE WHEN @cid = 0 THEN FEndBalance ELSE FEndBalanceFor END) FROM Te_Balance WHERE AccountId=@bankaccountid AND ATypeId = @batypeid AND STypeid=@STypeId AND Cid = @cid AND FYear<=@QueryYear AND FPeriod<@QueryPeriod AND BUId = @BUID ORDER BY FYear DESC,FPeriod DESC
ELSE
	SELECT @LASTENDBALANCE=SUM(CASE	WHEN @cid=0 THEN tjd.FEndBalanceOri ELSE tjd.FEndBalance END) 
	FROM Te_Journal_Detail tjd
	WHERE AccountId=@bankaccountid 
		AND ATypeId = @batypeid 
		AND STypeid=@STypeId 
		AND (tjd.Cid = @cid OR @cid = 0) 
		AND BusinessDate <= DATEADD(DAY,-1,@QueryFBegin)
		
SET @LASTENDBALANCE = ISNULL(@LASTENDBALANCE,0)

-----以上期余额为基础，计算查询日期上日余额
SELECT	 @LASTENDBALANCE = @LASTENDBALANCE + CASE	WHEN @cid=0 THEN tjd.FDebitOri ELSE tjd.FDebit END 
										   - CASE	WHEN @cid=0 THEN tjd.FCreditOri ELSE tjd.FCredit END
			
	FROM	Te_Journal_Detail tjd
	WHERE	tjd.BusinessDate >= @QueryFBegin
		AND tjd.BusinessDate < @businessdateStart 
		AND TJD.ATypeId = @batypeid
		AND TJD.AccountId = @bankaccountid
		AND	tjd.STypeId = @STypeId
		AND tjd.IsCash = @IsCash
		AND (tjd.cid = @cid OR @cid = 0)

------插入上日余额（或是期初）数据
INSERT INTO #temp(id,businessdate,businessdate1,summary,fendbalance,cid,cidfullname) 
VALUES(0,DATEADD(DAY,-1,@businessdateStart),DATEADD(DAY,-1,@businessdateStart),CASE WHEN @businessdateStart=@TeStartDate THEN '期初数据' ELSE '上日余额' END,@LASTENDBALANCE,@cid,CASE WHEN @cid= 0 THEN '综合本位币' ELSE (SELECT TOP 1 FullName FROM Ac_Currency WHERE CId= @cid) END)
--------上日余额部分结束------------------
SET @FLAG = 0		
IF ISNULL(@flownostart,'')='' AND ISNULL(@flownoend,'') = ''
	SET @FLAG = 1

SET @flownostart = ISNULL(@flownostart,'')
SET @flownoend = ISNULL(@flownoend,'')

CREATE TABLE #ETYPEID
(
	etypeid	VARCHAR(500),
	efullname	VARCHAR(500)
)

IF ISNULL(@tellerid,'') = ''
BEGIN
	INSERT INTO #ETYPEID(etypeid,efullname)
	SELECT	 typeId
			,FullName
	FROM	F_AllTreeE(@chvOperatorID)
END
ELSE
BEGIN
	INSERT INTO #ETYPEID(etypeid,efullname)
	SELECT	 typeId
			,FullName
	FROM	F_AllTreeE(@chvOperatorID)
	WHERE	TypeId IN (SELECT * FROM f_split(@tellerid,','))

	INSERT INTO #ETYPEID(etypeid,efullname)
	SELECT	F.TypeId
			,F.FullName
	FROM	F_AllTreeE(@chvOperatorID) F
	INNER JOIN	#ETYPEID T ON F.TypeId != T.etypeid AND F.TypeId LIKE T.etypeid+'%'
END

CREATE TABLE #VOUCHERID
(
	voucherid	INT,
	vgflowno	VARCHAR(500),
	billnumberid	INT
)
SET @SQL = '
INSERT INTO #VOUCHERID(voucherid,vgflowno,billnumberid)
SELECT	 avb.ID
		,vg.FullName+CAST(av.FlowNo AS VARCHAR)
		,avb.billnumberid
FROM	Ac_Voucher av
LEFT JOIN	Ac_Voucher_Bill avb ON avb.BillNumberId = av.BillNumberId
LEFT JOIN Ac_Voucher_Group vg ON vg.VgId = av.VgId
WHERE	1=1
'+CASE WHEN @flownostart <> '' THEN '
	AND av.FlowNo >= @flownostart
' ELSE '' END
+CASE WHEN @flownoend <>'' THEN '
	AND av.FlowNo <= @flownoend
' ELSE '' END
+CASE WHEN ISNULL(@vgid,'') <> '' THEN '
	AND av.VgId = @vgid
' ELSE '' END
--print @sql

EXEC sp_executesql @SQL,N'@flownostart		VARCHAR(500),
	   @flownoend		VARCHAR(500),	
	   @vgid			INT',@flownostart,@flownoend,@vgid
	   
CREATE CLUSTERED INDEX IDX_#temp ON #temp(businessdate1);

SET @SQL = '
INSERT INTO #temp(	 id
					,businessdate
					,businessdate1
					,summary
					,fdebit
					,fcredit
					,stypeid
					,sourceid
					,tellerid
					,tellername
					,sfullname
					,sourcename
					,vgflowno
					,voucherid
					,cid
					,FSettleNo
					,FSettlename
					,isCheckRelevance
					,isdaysum
					,issum
					,voucherbillnumberid
					,cidfullname
					,goodsbillnumerid
				)
SELECT	 tjd.Id
		,tjd.BusinessDate
		,tjd.BusinessDate as BusinessDate1
		,tjd.Summary
		,CASE WHEN @cid=0  THEN tjd.FDebitOri ELSE tjd.FDebit
		 END
		,CASE WHEN @cid=0  THEN tjd.FCreditOri ELSE tjd.FCredit
		 END
		,tjd.STypeId
		,tjd.SourceId
		,tjd.ETypeId as tellerid
		,e.efullname as tellername
		,s.FullName as sfullname
		,tjs.FullName as sourcename
		,av.vgflowno
		,tjd.VoucherId
		,CASE WHEN @cid = 0 THEN 0
		 ELSE tjd.cid
		 END
		,tjd.FSettleNo
		,abt.FullName
		,CASE WHEN EXISTS(SELECT TOP 1 JournalId FROM Te_CheckRelevance WHERE JournalId = tjd.Id) THEN 1
		 ELSE 0
		 END 
		,0
		,0
		,av.billnumberid
		,CASE WHEN @cid=0 THEN ''综合本位币''
		 ELSE ac.fullname
		 END
		,tjd.GoodsBillNumberId
FROM	Te_Journal_Detail tjd
INNER JOIN	#ETYPEID e ON e.etypeid = tjd.ETypeId
'+CASE WHEN ISNULL(@vgid,'') <>'' OR @FLAG = 0 THEN ' INNER JOIN	' 
ELSE ' LEFT JOIN	' 
END + 
'	#VOUCHERID av ON av.voucherid = tjd.VoucherId
LEFT JOIN	SType s ON s.TypeId = tjd.STypeId
LEFT JOIN	Te_Journal_SourceType tjs ON tjs.Id = tjd.SourceId
LEFT JOIN	Ac_Currency ac ON ac.CId = tjd.cid
LEFT JOIN	Ac_BalanceType abt ON abt.BtId = tjd.FSettleId
WHERE	tjd.BusinessDate >= @businessdateStart 
	AND	tjd.BusinessDate <= @businessdateEnd
	AND	tjd.STypeId = @STypeId
	AND (tjd.SourceId = @sourcetype OR @sourcetype = 0)
	AND tjd.IsCash = @IsCash
	AND (tjd.cid = @cid OR @cid = 0)
'+
CASE WHEN @DebitOrCredit = 0 THEN ' AND	tjd.FDebit != 0 '
WHEN @DebitOrCredit = 1 THEN ' AND	tjd.FCredit ! = 0 '
ELSE '' END
+ CASE WHEN @IsCash = 0 THEN ' AND	tjd.AccountId = '+CAST(@bankaccountid AS VARCHAR)
ELSE ' AND tjd.ATypeId = '''+@batypeid+'''' END

IF ISNULL(@FSettleid,0) <>0
	SET @SQL += ' AND tjd.FSettleid = @FSettleid '
IF ISNULL(@FSettleNo,'') <>''
	SET @SQL += ' AND tjd.FSettleNo LIKE ''%''+@FSettleNo+''%'''

SET @SQL +='
ORDER BY	BusinessDate1,id
'

EXEC sp_executesql @SQL,N'@STypeId 		VARCHAR(100),	---分支机构ID
	   @businessdateStart    DATE,			---起始业务日期
	   @businessdateEnd      DATE,			---结束业务日期
	   @sourcetype		INT,			--来源类型
	   @cid				INT,			--币种
	   @IsCash			INT,			--银行或是现金日记账查询   0：银行   1：现金
	   @FSettleid		INT,
	   @FSettleNo		VARCHAR(500)',@STypeId,@businessdateStart, @businessdateEnd,@sourcetype,@cid,@IsCash,@FSettleid,@FSettleNo

UPDATE #temp  SET	@LASTENDBALANCE = @LASTENDBALANCE + fdebit-fcredit
					,fendbalance = @LASTENDBALANCE
WHERE businessdate >= @businessdateStart					


DECLARE	@MAXID	INT
SET @MAXID = 0
SELECT TOP 1 @MAXID = id+1 FROM #temp ORDER BY id DESC

IF EXISTS(SELECT TOP 1 1 FROM #temp)
	INSERT INTO #temp(id,fdebit,fcredit,fendbalance,isCheckRelevance,isdaysum,issum,vgflowno)
	SELECT	 @MAXID+1
			,SUM(fdebit)
			,SUM(fcredit)
			,@LASTENDBALANCE
			,0
			,1
			,1 
			,'合计'
	FROM	#temp T1

--统计本日合计值
SELECT	 @MAXID id
		,T1.businessdate1
		,SUM(fdebit) fdebit
		,SUM(fcredit) fcredit
		,(SELECT TOP 1 fendbalance  FROM #temp T2 WHERE T2.businessdate1 = T1.businessdate1 ORDER BY T2.id DESC,T2.businessdate DESC) fendbalance
		,0 isCheckRelevance
		,1 isdaysum
		,0 issum
		,'本日合计' vgflowno
INTO #Temp1
FROM	#temp T1
WHERE	id < @MAXID
	AND id > 0
GROUP BY T1.businessdate1

INSERT INTO #temp(id,businessdate1,fdebit,fcredit,fendbalance,isCheckRelevance,isdaysum,issum,vgflowno)
SELECT id,businessdate1,fdebit,fcredit,fendbalance,isCheckRelevance,isdaysum,issum,vgflowno FROM #Temp1
DROP TABLE #Temp1

SELECT	 T.id
		,CASE WHEN T.id > @MAXID THEN NULL 
		 WHEN isdaysum = 1 THEN businessdate1
		 ELSE businessdate  END AS businessdate
		,CASE WHEN B.BillType = 310 THEN B.Comment
		ELSE T.summary
		END AS summary
		,fdebit
		,fcredit
		,fendbalance
		,T.stypeid
		,sourceid
		,tellerid
		,tellername
		,sfullname
		,sourcename
		,vgflowno
		,voucherid
		,T.cid
		,FSettleNo
		,FSettlename
		,CASE WHEN isCheckRelevance = 1 THEN '√'
		 ELSE ''
		 END AS isCheckRelevance
		,issum
		,voucherbillnumberid
		,cidfullname
		,isdaysum
		,CASE WHEN B.BillType = 310 THEN '资金调拨单'
		ELSE ''
		END AS billtypename
		,B.BillCode
		,t.goodsbillnumerid
FROM	#temp T
LEFT JOIN	BillIndex B ON B.BillNumberId = T.goodsbillnumerid
WHERE	isCheckRelevance = @isCheckRelevance OR @isCheckRelevance = 2
ORDER BY	issum,T.businessdate1,T.id,isdaysum,T.businessdate	


DROP TABLE #ETYPEID,#VOUCHERID,#temp
			 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_KTypeGatherDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_KTypeGatherDetailQuery]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：黄飞佳	
	日期：2012-05-25
	描述：库存销售汇总明细
*/
/*
    修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
    
     修改：舒珊
    日期：2015-05-27
    描述： 添加商品类别筛选
    
    修改：舒珊
    日期：2016-06-21
    描述： 换算率变更前销售单位数量统计
*/
/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Web_KTypeGatherDetailQuery
(
	@chvStartDate		VARCHAR(30),			-- 查询起始时间
	@chvENDDate		    VARCHAR(30),			-- 查询结束时间
	@chvPTypeID			VARCHAR(max),			-- 树型表或线性表商品类别查询范围父节点 ID
	@chvBTypeID			VARCHAR(max),			-- 结算单位
	@chvETypeID			VARCHAR(max),			-- 树型表或线性表职员类别查询范围父节点 ID
	@chvKTypeID			VARCHAR(max),			-- 树型表或线性表仓库类别查询范围父节点 ID
	@chvDTypeID			VARCHAR(max),			-- 树型表或线性表部门类别查询范围父节点 ID
	@chvStypeID			VARCHAR(max)='00000',	-- 树型表或线性表分支机构类别查询范围父节点 ID
	@sortfield			VARCHAR(50),			-- 明细表排序方式
	@checkCode			VARCHAR(max)= '',	    -- 制单人编号
	@checkName			VARCHAR(max)= '',	    -- 制单人名称
	@chvOperatorID		VARCHAR(50),			-- 操作员 ID ( 作权限范围检查用 )
	--@chvDX			CHAR(1) = '0',	        -- 部分仓库时显示代销数据 0 不显示
	@chkRed        		CHAR(1) ='0',		    -- 显示红冲单据
	@chvBilltype    	VARCHAR(200),           -- 单据类型
	@chvComment     	VARCHAR(200)='',        -- 说明
	@chvZY 				VARCHAR(200)='',        -- 摘要
	@chvParentID	    VARCHAR(50),			-- 当前双击选择的主信息类别查询范围父节点 ID
	@dealbtypeid        VARCHAR(max),	        -- 往来单位
	@chvPF        		CHAR(1) ='0' ,           --价保获利反利等
	@ptypecategoryid VARCHAR(MAX)				 --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON

--------权限检查-Start--------
IF @chvOperatorID is null RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re <> 0 RETURN @Re
--------权限检查-End--------  


--------创建临时表-Start--------
--单据类型
CREATE TABLE #Billtype (BillType VARCHAR(200))
INSERT INTO #Billtype SELECT a AS Billtype FROM dbo.f_split(@chvBilltype,',')

------仓库汇总单据号的过滤操作-Start------
IF(ISNULL(@chvKTypeID,'')='')
    BEGIN
         IF(@chvParentID<>'00000' And @chvParentID<>'10000')  DELETE #Billtype WHERE Billtype=141
    END
    ELSE
    BEGIN
         IF(ISNULL(@chvParentID,'')<>ISNULL(@chvKTypeID,'') AND @chvParentID<>'10000' AND @chvParentID<>'00000') DELETE #Billtype WHERE Billtype=141
    END
------仓库汇总单据号的过滤操作-End------

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(200),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Ktype SELECT typeid,usercode,fullname FROM Stock WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvKTypeID,4,@chvOperatorID))
IF (@chvKTypeID='10000' OR  @chvKTypeID='' OR  @chvKTypeID='00000') AND NOT EXISTS(SELECT * FROM #Ktype WHERE typeid='10000') 
INSERT INTO #Ktype SELECT '10000','10000','代销仓库'

--商品
CREATE TABLE #Ptype (TypeID VARCHAR(200),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Ptype SELECT typeid,usercode,fullname FROM Ptype WHERE typeid IN(SELECT typeid FROM  F_ManPTypeInCategoryID ( @chvOperatorID,@chvPTypeID,@ptypecategoryid))

--分支机构
CREATE TABLE #Stype (TypeID VARCHAR(200))
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvSTypeID,11,@chvOperatorID)

--结算单位	
CREATE TABLE #Btype (TypeID VARCHAR(200),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Btype SELECT typeid,usercode,fullname FROM Btype WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBTypeID,2,@chvOperatorID))

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(200))
INSERT INTO #DealBtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID)

--职员
CREATE TABLE #Etype (TypeID VARCHAR(200),UserCode VARCHAR(200),FullName VARCHAR(200))
INSERT INTO #Etype SELECT typeid,usercode,fullname FROM Employee WHERE typeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvETypeID,3,@chvOperatorID))

--部门
CREATE TABLE #Dtype (TypeID VARCHAR(200))
INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvDtypeID,9,@chvOperatorID)

--费用分摊设置
DECLARE @config int=0
SELECT	@config=Value FROM Userconfig WHERE ConfigName='sharefee'	

	

--------创建索引Start-------
CREATE CLUSTERED INDEX CIX_GetManKTypeID ON #Ktype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManETypeID ON #Etype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManPTypeID ON #Ptype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManSTypeID ON #Stype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManBTypeID ON #Btype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManDTypeID ON #Dtype(TypeID)
--------创建索引End-------

--单据索引表
	CREATE TABLE #BillIndex
	(
	    BillNumberID NUMERIC(18,0),
	    BillCode VARCHAR(200),
	    BillDate DATETIME,
	    Billtype NUMERIC(10,0),
	    Tax  NUMERIC(24, 10) ,
	    RedWord INT,
		TotalMoney  NUMERIC(24, 10) ,
		TotalInMoney  NUMERIC(24, 10) ,
		CompleteTotal  NUMERIC(24, 10) ,
		BTypeID  VARCHAR (200),
		ETypeID  VARCHAR (200),
		PTypeID  VARCHAR (200),
		KTypeID  VARCHAR (200),
		PreferenceMoney  NUMERIC(24, 10) ,
		DtypeID VARCHAR(200),
		Checke  VARCHAR(50),
		Stypeid   VARCHAR(200),
		Draft BIT,
		Posttime DATETIME,
		Dealbtypeid VARCHAR(200),
		CName VARCHAR(200),
		Rate   NUMERIC(24, 10),
		Explain VARCHAR(MAX),
		comment VARCHAR(MAX)
	)

	DECLARE	@strBill   VARCHAR(MAX)
	SET @strBill = 
	             'INSERT INTO #BillIndex 
	              SELECT billnumberid,
	                     billcode,
	                     billdate,
	                     a.billtype,
	                     tax,
	                     redword,
	                     totalmoney,
	                     totalinmoney,
	                     completetotal,
	                     a.btypeid,
	                     a.etypeid,
	                     a.ptypeid,
	                     a.ktypeid,
	                     preferencemoney,
	                     a.dtypeid,
	                     checke,
	                     a.stypeid,
	                     a.draft,
	                     a.posttime,
	                     a.dealbtypeid,
	                     cc.fullname,
	                     a.rate,
	                     a.Explain,
	                     a.comment
	               FROM dbo.BillIndex a
	               INNER JOIN #Billtype b ON a.BillType = b.Billtype
	               INNER JOIN AC_Currency cc  ON a.cid = cc.cid
	               INNER  JOIN #DealBtype dd ON a.dealbtypeid = dd.typeid'
	               IF (@chvBTypeID<>'' OR @MBTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF (@chvDTypeID<>'' OR @MDTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
                   IF (@chvETypeID<>'' OR @METypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Etype e ON a.etypeid = e.TypeID'
	               IF (@chvSTypeID<>'' OR @MSTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0'''   
	               
	               --增加发票立账405
	              SET @strBill += '
					UNION ALL 
					SELECT billnumberid,billcode,billdate,a.billtype,tax,redword,TotalMoney,TotalMoney,completetotal,
					a.btypeid,a.etypeid,'''' AS ptypeid,'''' AS ktypeid,TotalMoney AS preferencemoney,a.dtypeid,checke,
					a.stypeid,a.draft,posttime,a.dealbtypeid,cc.fullname,a.rate,a.Explain,a.comment 
					FROM dbo.ReceiptBillIndex AS a 
					INNER JOIN #Billtype b ON a.BillType = b.Billtype
	               INNER JOIN AC_Currency cc  ON a.cid = cc.cid
	               INNER  JOIN #DealBtype dd ON a.dealbtypeid = dd.typeid ' 
	               IF (@chvBTypeID<>'' OR @MBTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF (@chvDTypeID<>'' OR @MDTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
                   IF (@chvETypeID<>'' OR @METypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Etype e ON a.etypeid = e.TypeID'
	               IF (@chvSTypeID<>'' OR @MSTypeID=-99999) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0'''   
	
	--PRINT(@strBill)	                  
	EXEC(@strBill)

----出入库表
    CREATE TABLE #InoutStockTable
    (
		BillNumberId numeric(18, 0) ,
		BillDate datetime,
		BillType numeric(10,0),
		PtypeId varchar (200),
		KtypeId varchar (200),
		Qty  NUMERIC(24, 10) ,
		Price    NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		taxprice  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		tax  NUMERIC(24, 10) ,
		costPrice  NUMERIC(24, 10) ,
		ShareFee  NUMERIC(24, 10) ,
		Cargoid INT,
		NPrice  NUMERIC(24, 10) ,
		NTotal  NUMERIC(24, 10) ,
		NSalePrice  NUMERIC(24, 10) ,
		SalePrice   NUMERIC(24, 10),
		SaleTotal  NUMERIC(24, 10) ,
		NSaleTotal  NUMERIC(24, 10) ,
		NTaxPrice   NUMERIC(24, 10) ,
		NTaxTotal   NUMERIC(24, 10) ,
		FullName VARCHAR(max),
		UserCode VARCHAR(max),
		NQty  NUMERIC(24, 10) ,
		MUnitID INT,
		NumName VARCHAR(200),
		Rate  NUMERIC(24, 10) ,
		nbrcqty  NUMERIC(24, 10) ,
	    BaseUnitFullname VARCHAR(50),
        AssistantFullname VARCHAR(50),
        GoodsNumber  VARCHAR(100),
        kfullname	VARCHAR(200),
        comment		VARCHAR(2000),
        CustomdetailID int ,
        zy    varchar(2000),
        DisCount    NUMERIC(24, 10)			
	)
	
	DECLARE @strInOut VARCHAR(MAX)='
INSERT INTO #InoutStockTable
SELECT 
BillnumberID,																														
BillDate,																														
BillType,																															
PtypeID,																															
KtypeID,
Qty,
price,
Total,	  
CostTotal,
taxprice,  
TaxTotal,
tax,
costprice,
sharefee,
cargoid,
nprice,
ntotal,
nsaleprice,
SalePrice,
saletotal,
nsaletotal,
ntaxprice,
ntaxtotal,
fullname,
usercode,
nqty,
munitid,
numname,
rate,
T.nbrcqty  AS nbrcqty,--换算率变更前销售单位数量
baseunitfullname,
assistantfullname,
goodsnumber,
kfullname,
comment,
 CustomdetailID ,
 zy,
 DisCount
FROM
(
	SELECT
	a.BillnumberID,																														
	a.BillDate,																														
	a.BillType,																															
	a.PtypeID,																															
	a.KtypeID,
	a.Qty,
	a.price,
	a.Total,	  
	a.CostTotal,
	a.taxprice,  
	a.TaxTotal,
	a.tax,
	a.costprice,
	a.sharefee,
	a.cargoid,
	a.nprice,
	a.ntotal,
	a.nsaleprice,
	a.SalePrice,
	a.saletotal,
	a.nsaletotal,
	a.ntaxprice,
	a.ntaxtotal,
	v.fullname,
	k.usercode,
	a.nqty,
	a.munitid,
	pu.fullname AS numname,
	pe.rate AS rate,
	CAST(-a.qty/a.MUnitRate AS  NUMERIC(24, 10) )  AS nbrcqty,--换算率变更前销售单位数量
	fg.baseunitfullname AS baseunitfullname,
	fg.assistantfullname AS assistantfullname,
	a.goodsnumber,
	k.fullname as kfullname,
	a.comment,
	a.id as   CustomdetailID,
	b.comment as zy,
	a.DisCount
	FROM InoutStockTable a 
	INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID AND a.BillType = b.BillType 
	left  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	left JOIN PType_Units pu on pu.unitsid = a.munitid
	left  JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND pe.ptypeid = a.ptypeid
	left  JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	INNER JOIN #PType p ON a.PTypeID=p.typeid
	INNER JOIN #KType k ON a.KTypeID=k.typeid'
	
	SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	IF (@checkCode<>'')
	  SET @strInOut = @strInOut + ' AND k.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	IF (@checkName<>'')
	  SET @strInOut = @strInOut + ' AND k.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''		
	SET @strInOut += '
	AND A.BillType NOT IN(402,403,405) 
	
	UNION ALL
	--发出商品出库单
	SELECT
	a.BillnumberID,																														
	B.BillDate,																														
	B.BillType,																															
	a.PtypeID,																															
	a.KtypeID,
	CASE T.RedWord
		WHEN 2 THEN a.Qty - a.InvoiceQty
		ELSE -(a.Qty - a.InvoiceQty) 
	END AS Qty,
	a.DiscountPrice AS Price,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
	END AS Total,
	
	CASE T.RedWord
		WHEN 2 THEN a.CostTotal - a.InvoiceCostTotal
		ELSE -(a.CostTotal - a.InvoiceCostTotal)
	END AS CostTotal,
	a.taxprice,  

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
	END AS TaxTotal,
	
	a.tax,
	a.costprice,
	a.sharefee,
	a.cargoid,
	a.NDiscountPrice AS nprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice)  END
	END AS ntotal,
	
	a.nsaleprice,
	a.SalePrice,
	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.saletotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.saletotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
	END AS saletotal,
	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceNQty WHEN 0 THEN a.nsaletotal ELSE (a.NQty - a.InvoiceNQty) * a.NSalePrice END
		ELSE CASE a.InvoiceNQty WHEN 0 THEN -a.nsaletotal ELSE -((a.NQty - a.InvoiceNQty) * a.NSalePrice) END
	END AS nsaletotal,

	a.ntaxprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
		ELSE CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
	END AS ntaxtotal,
	
	v.fullname,
	k.usercode,
	CASE T.RedWord
		WHEN 2 THEN a.NQty - a.InvoiceNQty
		ELSE -(a.NQty - a.InvoiceNQty)
	END AS nqty,
	a.munitid,
	pu.fullname AS numname,
	pe.rate AS rate,
	a.Mqty-(a.InvoiceQty*a.MunitRate)  AS nbrcqty,--换算率变更前销售单位数量
	fg.baseunitfullname AS baseunitfullname,
	fg.assistantfullname AS assistantfullname,
	a.goodsnumber,
	k.fullname as kfullname,
	a.comment,
		a.id as   CustomdetailID,
	t.comment as zy,
	a.DisCount
	FROM SendBill AS A
	INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
	INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
	left  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	left JOIN PType_Units pu on pu.unitsid = a.munitid
	left  JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND pe.ptypeid = a.ptypeid
	left  JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	INNER JOIN #PType p ON a.PTypeID=p.typeid
	INNER JOIN #KType k ON a.KTypeID=k.typeid
	'
	SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	IF (@checkCode<>'')
	  SET @strInOut = @strInOut + ' AND k.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	IF (@checkName<>'')
	  SET @strInOut = @strInOut + ' AND k.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''		
	SET @strInOut += '
	AND T.ifYearBill = 0
	
	UNION ALL
	--发出商品退货单
	SELECT
	a.BillnumberID,																														
	B.BillDate,																														
	B.BillType,																															
	a.PtypeID,																															
	a.KtypeID,
	CASE T.RedWord
		WHEN 2 THEN -(a.Qty - a.InvoiceQty)
		ELSE a.Qty - a.InvoiceQty
	END AS Qty,
	a.DiscountPrice AS Price,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
	END AS Total,
	
	CASE T.RedWord
		WHEN 2 THEN -(a.CostTotal - a.InvoiceCostTotal)
		ELSE a.CostTotal - a.InvoiceCostTotal
	END AS CostTotal,
	a.taxprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
	END AS TaxTotal,
	
	a.tax,
	a.costprice,
	a.sharefee,
	a.cargoid,
	a.NDiscountPrice AS nprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
	END AS ntotal,
	
	a.nsaleprice,
	a.SalePrice,
	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.saletotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.saletotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
	END AS saletotal,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceNQty WHEN 0 THEN -a.nsaletotal ELSE -((a.NQty - a.InvoiceNQty) * a.NSalePrice) END
		ELSE CASE a.InvoiceNQty WHEN 0 THEN a.nsaletotal ELSE (a.NQty - a.InvoiceNQty) * a.NSalePrice END
	END AS nsaletotal,
	
	a.ntaxprice,

	CASE T.RedWord
		WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
		ELSE CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
	END AS ntaxtotal,
	
	v.fullname,
	k.usercode,
	CASE T.RedWord
		WHEN 2 THEN -(a.NQty - a.InvoiceNQty)
		ELSE a.NQty - a.InvoiceNQty
	END AS nqty,
	a.munitid,
	pu.fullname AS numname,
	pe.rate AS rate,
	a.Mqty-(a.InvoiceQty*a.MunitRate)  AS nbrcqty,--换算率变更前销售单位数量
	fg.baseunitfullname AS baseunitfullname,
	fg.assistantfullname AS assistantfullname,
	a.goodsnumber,
	k.fullname as kfullname,
	a.comment,
		a.id as   CustomdetailID ,
		t.comment as zy ,
	a.DisCount
	FROM SendBackBill AS A
	INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
	INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
	left  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	left JOIN PType_Units pu on pu.unitsid = a.munitid
	left  JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND pe.ptypeid = a.ptypeid
	left  JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	INNER JOIN #PType p ON a.PTypeID=p.typeid
	INNER JOIN #KType k ON a.KTypeID=k.typeid
	'
	SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	IF (@checkCode<>'')
	  SET @strInOut = @strInOut + ' AND k.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	IF (@checkName<>'')
	  SET @strInOut = @strInOut + ' AND k.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''		
	SET @strInOut += '
	AND T.ifYearBill = 0
	
	UNION ALL
	--销售发货开票
	SELECT
	a.BillnumberID,																														
	B.BillDate,																														
	B.BillType,																															
	a.PtypeID,																															
	a.KtypeID,
	CASE T.RedWord
		WHEN 2 THEN a.Qty
		ELSE -a.Qty 
	END AS Qty,
	a.Price,
	CASE T.RedWord
		WHEN 2 THEN a.total
		ELSE -a.total 
	END AS total,
	CASE T.RedWord
		WHEN 2 THEN a.InvoiceCostTotal
		ELSE -a.InvoiceCostTotal
	END AS CostTotal,
	a.taxprice,  
	CASE T.RedWord
		WHEN 2 THEN a.TaxTotal
		ELSE -a.TaxTotal
	END AS TaxTotal,
	a.tax,
	a.InvoiceCostPrice AS costprice,
	0 AS sharefee,
	a.cargoid,
	a.NPrice AS nprice,
	CASE T.RedWord
		WHEN 2 THEN a.Ntotal
		ELSE -a.Ntotal
	END AS Ntotal,
	a.nsaleprice,
	a.SalePrice,
	CASE T.RedWord WHEN 2 THEN a.saletotal ELSE -a.saletotal END AS saletotal,
	CASE T.RedWord WHEN 2 THEN a.nsaletotal ELSE -a.nsaletotal END AS nsaletotal,
	a.ntaxprice,
	CASE T.RedWord
		WHEN 2 THEN a.ntaxtotal
		ELSE -a.ntaxtotal
	END AS ntaxtotal,
	v.fullname,
	k.usercode,
	CASE T.RedWord
		WHEN 2 THEN a.NQty
		ELSE -a.NQty
	END AS nqty,
	a.munitid,
	pu.fullname AS numname,
	pe.rate AS rate,
	a.MQty  AS nbrcqty,--换算率变更前销售单位数量
	fg.baseunitfullname AS baseunitfullname,
	fg.assistantfullname AS assistantfullname,
	a.goodsnumber,
	k.fullname as kfullname,
	a.comment,
		a.id as   CustomdetailID,
		t.comment as zy ,
	a.DisCount 
	FROM ReceiptBill AS A
	INNER JOIN ReceiptBillIndex AS T ON(A.BillnumberID = T.BillnumberID AND A.BillType = T.BillType)
	INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
	left  JOIN vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
	left JOIN PType_Units pu on pu.unitsid = a.munitid
	left  JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND pe.ptypeid = a.ptypeid
	left  JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
	INNER JOIN #PType p ON a.PTypeID=p.typeid
	INNER JOIN #KType k ON a.KTypeID=k.typeid
	'
	SET @strInOut = @strInOut + ' WHERE b.Draft =0  AND B.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND B.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	IF (@checkCode<>'')
	  SET @strInOut = @strInOut + ' AND k.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
	IF (@checkName<>'')
	  SET @strInOut = @strInOut + ' AND k.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''		
	SET @strInOut += '
	AND T.ifYearBill = 0
	'

SET @strInOut += '
) AS T '
--********************************************************--
EXEC(@strInOut) 

--------创建临时表-End--------

--------价保、返利-Start--------
--红冲
DECLARE @RED_WHERE varchar(200)
SET @RED_WHERE= ''
IF @chkRed ='0'
	SET @RED_WHERE ='  b.Redword='+char(39)+'0'+char(39)
ELSE
	SET @RED_WHERE =' 1=1 '
	
-- 确定查询时间段
DECLARE @SQL_WHERE varchar(2000)
SELECT  @SQL_WHERE = ' AND b.BillDate >= ''' + @chvStartDate + '''' + ' AND b.BillDate <= ''' + @chvENDDate + ''''
	

----- 拼接头-商品编号、商品名Start-----
DECLARE  @head  VARCHAR(MAX)
SET @head= 
          'SELECT ''【''+a.usercode+''】''+isnull(a.Kfullname,''''),
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  a.usercode,
                  1 AS Flag,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,NULL,
                  
                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
				  null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
          FROM #InoutStockTable a  GROUP BY a.usercode,a.kfullname' 
          
----- 拼接头-商品编号、商品名End-----
		   
-----业务SQL语句-Start-----
DECLARE @strSQL VARCHAR(MAX)
SET @strSQL = 
             'SELECT  b.billcode,
             		  b.stypeid,																																																									
	                  a.billtype,
	                  a.billdate,
                      a.billnumberid,
	                  b.btypeid,
	                  b.dealbtypeid,
	                  b.etypeid,
	                  b.dtypeid,
	                  a.ktypeid,																																																											
	                  a.cargoid,
	                  a.ptypeid,
	                  -(a.Qty)AS qty,
					  isnull(a.Price,0) AS price,
					  isnull(a.taxPrice,0) AS taxprice,
                      -(a.Total) AS total,
					  -(a.TaxTotal) AS taxtotal, 
					  -(taxtotal)-(-total) AS taxge,
					  isnull((b.Totalinmoney+isnull(b.completeTotal,0)),0) AS totalinmoney,
					  CASE ABS(a.Qty) 
						  WHEN 0 THEN 0
						  ELSE a.costprice
					  END costprice,
					  --a.costprice,
					  -(a.CostTotal) AS costtotal,
					  -(ISNULL(a.sharefee,0)) AS sharefee,
					  -(ISNULL(b.preferencemoney,0)) AS preferencemoney,
					  a.nprice,
					  -(a.ntotal) AS ntotal,
					  a.nsaleprice,
					  a.SalePrice,
					  -(a.saletotal) AS saletotal,
					  -(a.nsaletotal) AS nsaletotal,
					  a.ntaxprice,
					  -(a.ntaxtotal) AS ntaxtotal,
					  a.fullname as itemname,
					  b.checke,
					  b.cname,
					  b.rate,
					  -(a.nqty) AS nqty,
					  a.numname AS munit,
					  -(a.qty/a.rate) AS mqty,
					   CASE a.nbrcqty  WHEN  -(a.qty/a.rate) THEN NULL ELSE a.nbrcqty  END AS nbrcqty,
					  CASE '+CAST( @config AS VARCHAR)+' WHEN 1  THEN -(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0)) ELSE  -(a.Total) - (-a.CostTotal) END AS maoli,
					  CASE a.Total WHEN 0 THEN 0 
					  ELSE 
					  (CASE '+CAST( @config AS VARCHAR)+' 
					  WHEN 1  THEN cast( (-(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0))) as 
NUMERIC(24, 10))/cast( -(a.total) as 
NUMERIC(24, 10))
                      ELSE cast( (-(a.Total) - (-a.CostTotal))as 
NUMERIC(24, 10))/cast(-(a.total)  as NUMERIC(24, 10))
                      END)*100
					  END AS maolilu,
					  CASE WHEN b.billtype IN (148,150) THEN -(a.total)
                      ELSE 0
                      END AS antantotal,
					  CASE WHEN b.billtype IN (148,150) THEN -(a.qty)
					  ELSE 0
					  END AS aqty,
					  CASE WHEN b.billtype IN (149,151) THEN -(a.total)
					  ELSE 0
					  END AS PriceTotal,
					  CASE WHEN b.billtype IN (149,151) THEN -(a.qty)
					  ELSE 0
					  END AS pqty,
					  b.posttime,
					  a.usercode,
					  2 AS Flag,
					  a.baseunitfullname,
					  a.assistantfullname,
					  a.goodsnumber,
					  CASE a.billtype
						WHEN 11		THEN ''销售出库单''
						WHEN 45		THEN ''销售退货单''
						WHEN 215	THEN ''零售退货单''
						WHEN 305	THEN ''零售单''
						WHEN 141	THEN ''委托结算单''
						WHEN 34 	THEN ''采购入库单''
						WHEN 6 		THEN ''采购退货单''
						WHEN 145	THEN ''受托代销结算单''
						WHEN 149	THEN ''价保执行单''
						WHEN 151	THEN ''获得价保执行单''
						WHEN 148	THEN ''返利执行单''
						WHEN 150	THEN ''获利执行单''
						WHEN 160	THEN ''销售换货单''
						WHEN 161	THEN ''采购换货单''
						WHEN 402	THEN ''发出商品出库单''
						WHEN 403	THEN ''发出商品退货单''
						WHEN 405	THEN ''销售发货开票''
						WHEN 12		THEN ''组合品销售出库单''
						WHEN 46		THEN ''组合品销售退货单''
					  END AS billtypename,
					  b.redword AS RedWord,
					  (-A.Ntaxtotal)-(-A.Ntotal) AS ntaxge,
					  a.comment,
					  b.Explain,
					  SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	,
					SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40,
					a.zy,
					a.DisCount
			  FROM #InoutStockTable a
			  INNER JOIN #BillIndex b ON a.BillNumberId = b.BillNumberID
			  left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid
			  
			  WHERE 1=1'
			  -- 筛选制单人
			  IF @checkCode <> '' OR @checkName <> ''
			  SET @strSQL = @strSQL + ' or  b.KTypeID = ''10000'' '
-----业务SQL语句-End-----

-----拼接尾-商品相关金额小计Start-----
DECLARE @tail VARCHAR(MAX);
SELECT @tail = 
       'WITH strSql AS
        ('+@strSQL+')
        SELECT * FROM strSql
        UNION ALL
        SELECT  NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                SUM(strSql.Qty),
                NULL,
                NULL,
                SUM(strSql.Total),
                SUM(strSql.Taxtotal),
                SUM(strSql.Taxge),
                NULL,
                NULL,
                SUM(strSql.CostTotal),
                SUM(strSql.sharefee),
                NULL,
                NULL,
                SUM(strSql.ntotal),
                NULL,
                NULL,
                SUM(strSql.saletotal),
                SUM(strSql.nsaletotal),
                NULL,
                SUM(strSql.ntaxtotal),
                NULL,
                NULL,
                NULL,
                NULL,
                SUM(strSql.nqty),
                NULL,
                SUM(strSql.mqty),
                SUM(strSql.nbrcqty),
                SUM(strSql.maoli),
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                strSql.usercode,
                3 AS Flag,
                NULL,
                NULL,
                NULL,
              ''小计'',
                NULL,
                SUM(strSql.ntaxge),NULL,
                NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
         FROM strSql
         GROUP BY strSql.usercode
         UNION ALL ' 
         +@head   
-----拼接尾-商品相关金额小计End-----
DECLARE @SQL_ORDER VARCHAR(MAX) 
SELECT  @SQL_ORDER = ' ORDER BY usercode,Flag'
+ CASE @sortfield
			WHEN 'ByDate_a'		THEN ', BillDate,Billcode'	-- 按日期排序
			WHEN 'ByBillNo_a'	THEN ', BillCode'		    -- 按单据编号排序
			WHEN 'ByBillType_a'	THEN ', BillType,BillDate'	-- 按单据类型排序
			WHEN 'ByBillID_a'	THEN ', posttime'			-- 按单据真实过帐顺序排序
			WHEN 'ByDate_d'		THEN ', Billdate DESC,Billcode DESC'
			WHEN 'ByBillNo_d'	THEN ', BillCode DESC'
			WHEN 'ByBillType_d'	THEN ', BillType DESC,BillDate'
			WHEN 'ByBillID_d'	THEN ', posttime DESC '
			ELSE ',posttime DESC '
			END

DECLARE @SQL VARCHAR(MAX)
SET @SQL =@tail + @SQL_ORDER
EXEC(@SQL)
DROP TABLE #Billtype,#Ptype,#Btype,#Etype,#Ktype,#Dtype,#Stype,#BillIndex,#DealBtype,#InoutStockTable
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_LoadAllotApplyBillDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_LoadAllotApplyBillDetails]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE Web_LoadAllotApplyBillDetails
(
	@billnumberid	INT,
	@stypeid		VARCHAR(200),
	@ktypeidout		VARCHAR(50),
	@chvoperatorid 	varchar(50)='' 	-- 操作员 ID（作权限范围检查用）
)
--@encode$--
AS
SET NOCOUNT ON 
	-------- 权限检查 - Start --------
	DECLARE @intRe int, 
			@chvMATypeID varchar(50), 
			@chvMBTypeID varchar(50), 
			@chvMBTypeID2 varchar(50), 
			@chvMETypeID varchar(50), 
			@chvMKTypeID varchar(50), 
			@chvMPTypeID varchar(50), 
			@chvMExpense varchar(50), 
			@chvMIncome varchar(50), 
			@chvMCapital varchar(50), 
			@chvMDtypeid varchar(50), 
			@chvMStypeid varchar(50)

	EXEC @intRe = GP_CheckOperatorRight23_Rep 
		@chvoperatorid, 
		@chvMATypeID output, 
		@chvMBTypeID output, 
		@chvMBTypeID2 output, 
		@chvMETypeID output, 
		@chvMKTypeID output, 
		@chvMPTypeID output, 
		@chvMExpense output, 
		@chvMIncome output, 
		@chvMCapital output, 
		@chvMDtypeid output, 
		@chvMStypeid output

	--拥有查询所有商品的权限（MangerPTypeID = '00000'）
	--（MangerPTypeID = '-99999'并且ptype_l没有记录，表示没有权限)
	--（MangerPTypeID = '-99999'并且ptype_l有记录，表示拥有部分权限)
	CREATE TABLE #temp_PtypeId
	(
		Typeid	VARCHAR(50)
	)
	CREATE CLUSTERED INDEX CIX_PTYPE_typeid ON #temp_PtypeId(Typeid) 
	IF @intRe = 0 AND @chvMPTypeID = '-99999'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM PType_L WHERE ETypeId = @chvoperatorid)
		BEGIN
			insert into #temp_PtypeId (Typeid)	
			SELECT 	M.typeId
			FROM 	(
					SELECT	DISTINCT P.TypeId 
					FROM	PType_L L
					INNER JOIN PType  P ON (L.etypeid = @chvoperatorid 
											AND L.Flag=1 
											AND P.deleted = 0
											AND P.TypeId LIKE L.TypeId + '%' )
					UNION
					SELECT	L.TypeID
					FROM	ptype_l L
					WHERE	L.etypeid = @chvoperatorid
							AND L.flag=0
				) M
		END
	END
	ELSE IF @intRe = 0 AND @chvMPTypeID = '00000'
	BEGIN
		insert into #temp_PtypeId (Typeid)	
		SELECT DISTINCT typeId FROM PType WHERE sonnum = 0 AND deleted = 0 
	END
	-------- 权限检查 - End --------
	
	DECLARE @SQL VARCHAR(MAX)
	
	--分支机构物价信息
	DECLARE @PriceType varchar(5)
	SELECT @PriceType=PriceType FROM SType WHERE TypeId=@stypeid
	IF ISNULL(@stypeid,'')=''
	BEGIN
		SET @PriceType = '0'
	END
	
	CREATE TABLE #temp_ptype
	(
		ptypeid		varchar(200)
	)
	INSERT INTO #temp_ptype 
	SELECT DISTINCT Ptypeid FROM PosAllotApplyBill WHERE billnumberid=@billnumberid
	
	--处理库存和成本
	CREATE TABLE #temp_Qty
	(
		PtypeId				varchar(50),
		QTY					 NUMERIC(24, 10) ,
		NQTY					 NUMERIC(24, 10) ,
		CostPrice			 NUMERIC(24, 10) 
	);
	SET @SQL = '
		INSERT INTO #temp_Qty(PtypeId,QTY,NQTY,CostPrice)
		SELECT	x.ptypeid,SUM(ISNULL(aq.qty,0)) AS qty,SUM(ISNULL(aq.nqty,0)) AS nqty,y.costprice
		FROM #temp_ptype x
		LEFT JOIN 
		(
			SELECT t.ptypeid,
			CASE WHEN SUM(ISNULL(a.QTY,0)) = 0 THEN NULL ELSE CAST(SUM(ISNULL(a.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(a.QTY,0)) AS NUMERIC(24,10)) END AS CostPrice 
			FROM #temp_ptype t
			LEFT JOIN GoodsStocks a ON a.PTypeID = t.PTypeID AND a.KTypeID = ''' + @ktypeidout + '''
			GROUP BY t.Ptypeid
		) y ON y.ptypeid = x.ptypeid
		LEFT JOIN GoodsStocks_Qty aq ON aq.PTypeID LIKE x.PTypeID 
		AND aq.KTypeID = '''+ @ktypeidout +''' GROUP BY x.ptypeid,y.costprice';
	EXEC(@SQL)
	
	SET @SQL = '
	SELECT id,billnumberid,p.typeid,p.usercode,p.fullname,case when b.CallQty >= b.qty then 0 else b.qty-b.CallQty end as qty,--b.qty,
	ktypeid,s.fullname as kfullname,
	inktypeid as ktypeid2,s1.fullname as kfullname2,
	p.customitemid,p.customitemfrom,p.customitemname,
	p.customitemrefid,p.isservice,p.ifserial,
	itemid,iscombined,p.unit1,p.unit2,p.unitrate1,p.assistantunitid,pu.unitstype,
	pu.unitid,pu.unit,pu.unitrate,pu.nunitid,pu.nunit,pu.rate,pu.stockunitid,pu.stockunitname,pu.stockmunitrate,pu.ifusegoodsnum,
	ISNULL(c.PreSalePrice1,0) AS PrePrice1,
	ISNULL(c.PreSalePrice2,0) AS PrePrice2,
	ISNULL(c.PreSalePrice3,0) AS PrePrice3,
	ISNULL(c.PreSalePrice4,0) AS PrePrice4,
	ISNULL(c.PreSalePrice5,0) AS PrePrice5,
	ISNULL(c.PreSalePrice6,0) AS PrePrice6,
	ISNULL(c.PreSalePrice7,0) AS PrePrice7,
	ISNULL(c.PreSalePrice8,0) AS PrePrice8,
	ISNULL(c.PreSalePrice9,0) AS PrePrice9,
	ISNULL(c.PreSalePrice10,0) AS PrePrice10,
	ISNULL(c.RetailPrice,0) AS PrePrice11,
	ISNULL(c.TopSalePrice,0) AS PrePrice12,
	ISNULL(c.LowSalePrice,0) AS PrePrice13,
	CASE WHEN tq.CostPrice IS NULL THEN 0 ELSE tq.CostPrice END AS CostPrice,
	(dbo.F_GetAllEntrycode(b.ptypeid,pu.StockUnitId,2)) AS stockmunitcode,
	(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname1,
	(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname2,
	(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname3,
	(SELECT SaleUnitRate1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate1,
	(SELECT SaleUnitRate2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate2,
	(SELECT SaleUnitRate3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate3,
	(select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=b.ptypeid  and STYPEID='''+@stypeid+'''  and isdefaultunit = 1) AS SReferPrice,
 	(select ISNULL(ReferPrice,0) from PType_Price where PTypeID=b.ptypeid and isdefaultunit = 1)  AS PReferPrice,
 	(select RecPrice from ptype where typeid=b.ptypeid) as ptyperecprice,
	CASE WHEN b.IsCombined = 0  THEN
	(SELECT FullName FROM xw_SelfData WHERE _Id= b.ItemId) 
	ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= b.ItemId ) END AS itemname,
	b.comment
	from PosAllotApplyBill b
	INNER JOIN #temp_PtypeId TPID ON b.ptypeid=TPID.typeid
	LEFT JOIN ptype p on b.ptypeid=p.typeid
	LEFT JOIN dbo.F_GetPtypeUnitInfo() pu ON b.ptypeid=pu.typeid 
	LEFT JOIN stock s ON s.typeid=b.ktypeid
	LEFT JOIN stock s1 ON s1.typeid=b.inktypeid 
	LEFT JOIN #temp_Qty tq ON tq.ptypeid=b.ptypeid'
	
	--使用分支机构物价信息
	IF @PriceType='1'
	BEGIN
		SET @SQL += ' LEFT JOIN PType_StypePrice c ON c.PTypeID = b.PTypeID AND c.stypeid='''+@stypeid+'''  and p.SaleUnitId=c.UnitID';
	END
	ELSE
	BEGIN
		SET @SQL += ' LEFT JOIN PType_Price c ON c.PTypeID = b.PTypeID  and p.SaleUnitId=c.UnitID';
	END
	SET @SQL += ' WHERE billnumberid='''+CAST(@billnumberid AS VARCHAR(10))+''' '
	SET @SQL += ' AND BillOver=0 '
	EXEC(@SQL)
	
	DROP TABLE #temp_ptype
	DROP TABLE #temp_Qty
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_LoadAllotApplyBillIndex]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_LoadAllotApplyBillIndex]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
CREATE PROCEDURE Web_LoadAllotApplyBillIndex
(
	@startdate	datetime,
	@enddate	datetime,
	@applyetypeid	varchar(200),
	@stypeid		varchar(200),
	@dtypeid		varchar(200),
	@ktypeid		varchar(50),
	@ktypeidin		varchar(50),
	@billcode		varchar(200),
	@billstate		varchar(50),
	@comment		varchar(256),	
	@operator		VARCHAR(50),
	@billtype		VARCHAR(50),
	@isauditbill	int=0,	
	@ptypeid		varchar(50),
	@EprFlag		int=0		--Erp传过来的时候，不显示原始单据(Eprflag = 1)
)
--@encode$--
AS



SET ANSI_WARNINGS OFF
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @operator IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
           @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @operator,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
--部门
Create TABLE  #DType(typeid VARCHAR(100),fullname varchar(100))
INSERT INTO #DType SELECT a.typeid,d.FullName FROM F_GetAllManagerBaseTypeId(@DtypeID,9,@operator) a
INNER JOIN department d ON a.typeid=d.typeid 

--选择分支机构
CREATE TABLE #SType(TypeId	VARCHAR(100),fullname varchar(100))
INSERT INTO #SType(TypeId,fullname) SELECT a.typeid,s.FullName FROM F_GetAllManagerBaseTypeId(@StypeId,11,@operator) a
INNER JOIN stype s ON s.TypeId=a.TypeId


--职员
CREATE TABLE #EType(TypeId	varchar(100),eid varchar(10),fullname varchar(100))
INSERT INTO #EType(TypeId,eid,fullname) SELECT a.Typeid,e.eid,e.fullname FROM (SELECT TypeId
FROM F_GetAllBaseTypeId(@applyetypeid,3) 
WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailEType(@operator))) a
INNER JOIN	employee e ON a.TypeId=e.typeId

--仓库
CREATE TABLE #KTypeId(TypeId	VARCHAR(50))
CREATE TABLE #KTypeIdIn(TypeId	VARCHAR(50))

DECLARE @limt INT ,
		@checkStock VARCHAR(200)
SELECT @limt = Value FROM dbo.Userconfig WHERE ConfigName = 'postransktypelimit'
SET @checkStock = ''

IF @MKtypeid='-99999' AND @operator<>'00001'  AND  @billtype IN(326,327,328,329)
BEGIN
	INSERT INTO #KTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@operator)
	INSERT INTO #KTypeIdIn(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ktypeidin,4,@operator)
	
	IF @limt = 1
		SET @checkStock = ' AND (EXISTS (SELECT TOP 1 1 FROM #KTypeId WHERE TypeId = i.ktypeid) AND EXISTS (SELECT TOP 1 1 FROM #KTypeIdIn WHERE TypeId = i.inktypeid))'
	ELSE
		SET @checkStock = ' AND (EXISTS (SELECT TOP 1 1 FROM #KTypeId WHERE TypeId = i.ktypeid) OR EXISTS (SELECT TOP 1 1 FROM #KTypeIdIn WHERE TypeId = i.inktypeid))'
END

--商品
CREATE TABLE #Ptype(TypeId	varchar(100))
INSERT INTO #Ptype(TypeId) SELECT TypeId FROM F_ManPTypeInCategoryID(@operator,@ptypeid,'')

    create table #billexecstate(execstate int,billnumberid  NUMERIC(10, 0))
    create table #billnumberid(billnumberid  NUMERIC(10, 0))
    set @ptypeid = ISNULL(@ptypeid,'')
    
    if @billtype = 22 --调货申请单
    begin
		insert into #billnumberid(billnumberid)
		select distinct pb.BillNumberId
		from PosAllotApplyBillIndex pb
		where pb.BillType = @billtype and (@ptypeid = '' or exists(select top 1 1 from  PosAllotApplyBill b where b.BillNumberId = pb.billnumberid and b.ptypeid = @ptypeid))
		
		insert into #billexecstate (execstate,billnumberid)
		select case when pb.isdone =1 then 7
					when m.qty>0 and pb.isdone=0 then 6
					else 8 end as execstate,
					pb.billnumberid
		from PosAllotApplyBillIndex pb
		inner join #billnumberid b on b.billnumberid = pb.BillNumberId
		left join 
			(	SELECT ISNULL(SUM(m.qty),0) as qty,pb.billnumberid
					FROM (
						SELECT Qty,AllotID FROM dbo.MoveBill m 
						INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
						WHERE bi.RedWord=0 ----引用要算草稿
						UNION ALL SELECT Qty,AllotID FROM dbo.MoveBjBill m
						INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
						WHERE bi.RedWord=0 ----引用要算草稿 
						UNION ALL SELECT s.Qty,s.AllotID FROM dbo.STypeMoveBill s 
						INNER JOIN dbo.BillIndex bi ON s.BillNumberId=bi.BillNumberId
						 WHERE bi.RedWord=0 ----引用要算草稿 
					) m
					INNER JOIN dbo.PosAllotApplyBill pb ON pb.ID=m.AllotID 
					group by pb.billnumberid
				
			)m on pb.billnumberid=m.billnumberid
	end
	else if @billtype = 326   --要货申请单
	begin
		insert into #billnumberid(billnumberid)
		select distinct pb.BillNumberId
		from PosAllotApplyBillIndex pb
		where pb.BillType = @billtype and (@ptypeid = '' or 
		exists(select top 1 1 from  DeliveryApplyBill b where b.BillNumberId = pb.billnumberid and b.ptypeid = @ptypeid))
		
		insert into #billexecstate (execstate,billnumberid)
		select case when pb.isdone =1 then 7 --已完成
					when m.BillNumberId is null then 8  --未引用
					else 6 end as execstate,  --已引用未完成
					pb.billnumberid
		from PosAllotApplyBillIndex pb
		inner join #billnumberid b on b.billnumberid = pb.BillNumberId
		left join (
			select DISTINCT dab.BillNumberId from DeliveryApplyBill dab    
			inner join DeliveryBill db on dab.ID = db.DeliveryApplyBillId	--门店配送单
			inner join PosAllotApplyBillIndex b on b.BillNumberId = db.BillNumberId and b.RedWord = 0 
		) m on m.BillNumberId = pb.BillNumberId
	end
	else if @billtype = 327  --门店配送单 
	begin	
		insert into #billnumberid(billnumberid)
		select  distinct pb.BillNumberId
		from	PosAllotApplyBillIndex pb
		where	pb.BillType = @billtype 
				and pb.RedWord = 0
				and pb.draft = 0
				and pb.ifcheck = 't'
				and (@ptypeid = '' or exists(select 1 from  DeliveryBill b where b.BillNumberId = pb.billnumberid and b.ptypeid = @ptypeid))
				AND EXISTS
				(
					SELECT	DISTINCT BillNumberId 
					FROM	DeliveryBill
					WHERE	qty > BackQty
							AND BillNumberId = pb.BillNumberId
				)
		
		insert into #billexecstate (execstate,billnumberid)
		select case when pb.Qty = m.gzQty then 10  --验收过账完成
					when pb.Qty = m.yyQty then 9  --验收未过账
					when m.yyQty = 0 or m.BillNumberId IS null then 8		--未引用
					else 6 end as execstate,  --已引用未完成
					pb.billnumberid
		from PosAllotApplyBillIndex pb
		inner join #billnumberid b on b.billnumberid = pb.BillNumberId
		left join (
			select BillNumberId,SUM(gzqty) as gzQty,SUM(yyQty) as yyQty 
			from 
			(
				select db.BillNumberId,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as gzQty,0 as yyQty from DeliveryBill db
				inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
				inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.RedWord = 0 and pabi.draft = 0
				union all
				select db.BillNumberId,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as gzQty,0 as yyQty from DeliveryBill db
				inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
				inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.RedWord = 0 and pabi.draft = 0
				union all 
				select db.BillNumberId, 0 as gzQty,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as yyQty from DeliveryBill db
				inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
				inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.RedWord = 0
				union all
				select db.BillNumberId,0 as gzQty,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as yyQty from DeliveryBill db
				inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
				inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.RedWord = 0
			) x
			group by BillNumberId
		) m on m.BillNumberId = pb.BillNumberId
	end
		
	--SELECT * FROM #billexecstate
		
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = '
	SELECT i.billnumberid,
			i.billcode,
			i.billtype,
			CONVERT(varchar(10),i.billdate, 120) AS billdate,
			i.applyetypeid as etypeid,
			i.applyetypeid,
			i.stypeid,
			i.dtypeid,
			i.ktypeid,
			i.inktypeid as ktypeidin,
			i.qty,
			i.comment,
			i.explain,
			i.checke,
			e.fullname as efullname,
			s.fullname as sfullname,
			d.fullname as dfullname,
			k.fullname as kfullname,
			e.eid as eid,
			k.kid as outkid,
			k1.fullname as kfullnamein,
			k1.kid as inkid,
			e.fullname as checkename,
			i.BillState billstate,
			bs.execstate,
			CASE 
			WHEN bs.execstate=10 THEN ''验收过账完成''  
			WHEN bs.execstate=9 THEN ''验收未过账'' '
			IF ISNULL(@EprFlag,0) <> 0  AND @billtype <> 22
				SET @SQL+='
				WHEN i.BillState=4 AND bs.execstate=8 THEN ''已作废''
				--WHEN bs.execstate=8 THEN  ''未引用''
				WHEN bs.execstate=8 and i.billtype=326  THEN  (
				CASE WHEN i.billstate=0 THEN ''原始单据'' 
					 WHEN i.billstate=1 THEN ''已审核'' 
					 WHEN i.billstate=2 THEN ''已接受'' 
					 WHEN i.billstate=3 THEN ''已拒绝'' 
					 WHEN i.BillState=4 THEN ''已作废'' 
					ELSE ''未引用'' END
				) '
			ELSE
			SET @SQL+='
				WHEN bs.execstate=8 and (i.billtype=326 OR i.billtype=22) THEN  (
				CASE WHEN i.billstate=0 THEN ''原始单据'' 
					 WHEN i.billstate=1 THEN ''已审核'' 
					 WHEN i.billstate=2 THEN ''已接受'' 
					 WHEN i.billstate=3 THEN ''已拒绝'' 
					 WHEN i.BillState=4 THEN ''已作废'' 
					ELSE ''未引用'' END
				)'
			SET @SQL+='
			WHEN i.BillState=4 THEN ''已作废'' 
			WHEN bs.execstate=7 THEN ''已完成'' 
			WHEN bs.execstate=6 THEN ''已引用未完成''
			WHEN bs.execstate=8 THEN ''未引用''
			WHEN i.BillState=0 THEN ''原始单据'' 
			WHEN i.BillState=1 THEN ''已审核''
			WHEN i.BillState=2 THEN ''已接受''
			WHEN i.BillState=3 THEN ''已拒绝''
			ELSE ''未引用'' END  as billstatename
	FROM PosAllotApplyBillIndex i 
	INNER JOIN #billnumberid b on b.billnumberid = i.BillNumberId	
	INNER JOIN #EType e ON i.applyetypeid=e.typeid 
	INNER JOIN #SType s ON i.stypeid=s.typeid 
	INNER JOIN #DType d ON i.dtypeid=d.typeid 
	LEFT JOIN stock k ON i.ktypeid=k.typeid 
	LEFT JOIN stock k1 ON i.inktypeid=k1.typeid
	LEFT join #billexecstate bs on i.billnumberid=bs.billnumberid 
	WHERE i.redword = 0 AND bs.execstate not in(9,10) AND i.billdate between '''+CONVERT(VARCHAR(10),@startdate,120)+''' AND '''+CONVERT(VARCHAR(10),@enddate,120)+''' '
	
	
	IF @billtype NOT IN (327)
	BEGIN
		--只有已接受的单据才能被调用
		SET @SQL += ' 
						and not exists
						(
							select 1 from deliverybackbill a 
							inner join deliverybill b on a.deliveryid=b.id and b.billnumberid=i.billnumberid
							where a.qty=b.qty
						) '
	END
	
	IF ISNULL(@applyetypeid,'')<>''
	BEGIN
		SET @SQL += ' AND i.applyetypeid='''+@applyetypeid+''''
	END
	IF ISNULL(@dtypeid,'')<>''
	BEGIN
		SET @SQL += ' AND i.dtypeid='''+@dtypeid+''''
	END
	IF ISNULL(@ktypeidin,'')<>''
	BEGIN
		SET @SQL += ' AND i.inktypeid='''+@ktypeidin+''''
	END
	IF ISNULL(@ktypeid,'')<>''
	BEGIN
		SET @SQL += ' AND i.ktypeid='''+@ktypeid+''''
	END
	IF ISNULL(@billcode,'')<>''
	BEGIN
		SET @SQL += ' AND i.billcode like ''%'+@billcode+'%'''
	END

	IF ISNULL(@billstate,'') <> ''
	BEGIN
		SET @SQL += ' AND ( CHARINDEX(CONVERT(VARCHAR,bs.execstate),'''+@billstate+''') > 0 OR CHARINDEX(CONVERT(VARCHAR,i.billstate),'''+@billstate+''') > 0 ) '
	END


	IF CHARINDEX('2',@billstate) = 0 AND CHARINDEX('6',@billstate) > 0
	BEGIN
		SET @SQL += ' AND (i.billstate <> 2 OR bs.execstate = 6) ' --不查询接受状态
	END
	IF CHARINDEX('6',@billstate) = 0 AND CHARINDEX('2',@billstate) > 0
	BEGIN
		SET @SQL += ' AND bs.execstate <> 6 ' --不查询已引用未完成状态
	END
	IF CHARINDEX('7',@billstate) = 0 AND CHARINDEX('2',@billstate) > 0 
	BEGIN
		SET @SQL += ' AND bs.execstate <> 7 ' --不查询已完成状态
	END
	IF CHARINDEX('4',@billstate) = 0 AND CHARINDEX('6',@billstate) > 0 
	BEGIN
		SET @SQL += ' AND i.billstate <> 4 ' --不查询作废状态
	END
	IF CHARINDEX('6',@billstate) = 0 AND CHARINDEX('4',@billstate) > 0 
	BEGIN
		SET @SQL += ' AND (bs.execstate <> 6 OR i.billstate = 4) ' --不查询已引用未完成状态
	END
	
	
	IF ISNULL(@comment,'')<>''
	BEGIN
		SET @SQL += ' AND i.comment like ''%'+@comment+'%'''
	END
	IF ISNULL(@stypeid,'')<>''
	BEGIN
		SET @SQL += ' AND i.stypeid='''+@stypeid+''''
	END
	--已引用完成的调货申请单排除(调货申请单单据调阅除外)
	IF(@isauditbill <> 1 and @billtype='22')
	BEGIN
		SET @SQL += ' AND i.Isdone <> 1 '
	END
	
	IF @billtype = '327'
	BEGIN
		SET @SQL += ' AND bs.execstate not in (9,10) '
	END
	
	SET @SQL += @checkStock
	
	SET @SQL += ' ORDER BY i.BillCode '
	
	
	--PRINT @SQL	
	EXEC(@SQL)	

	drop table #billexecstate,#billnumberid,#EType,#SType,#DType,#KTypeId,#KTypeIdIn,#PType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadAuditingTemplate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadAuditingTemplate]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012-04-21
	描述：调取凭证模板表头信息
*/
CREATE PROCEDURE Web_LoadAuditingTemplate
(
	@atid	INT	--模板ID
)
--@encode$--
AS
SET NOCOUNT ON

IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Auditing_Template WHERE atid = @atid)
BEGIN
	RAISERROR('该模板不存在，请确认！',16,1)
	RETURN
END

SELECT	a.atid,
		a.UserCode AS ausercode,
		a.FullName AS afullname,
		a.BillType,
		c.BillName,
		a.IsDefault AS [default],
		a.Sysrow,
		b.VgId,
		a.ETypeId AS edCreator,
		d.FullName AS creatorname,
		explainaudittype,
		explaintext,
		ISNULL(iscombinerow,0) AS iscombinerow,
		a.ChargeOffType
FROM dbo.Ac_Auditing_Template a 
	INNER JOIN dbo.Ac_Voucher_Group b ON a.VgId = b.VgId
	LEFT JOIN dbo.BillName c ON a.BillType = c.Billtype
	INNER JOIN dbo.employee d ON a.ETypeId = d.typeId
WHERE AtId = @atid



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadAuditingTemplate_CostDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadAuditingTemplate_CostDetails]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012-04-23
	描述：调取凭证模板明细信息
*/
CREATE PROCEDURE Web_LoadAuditingTemplate_CostDetails
(
	@atid			INT,			--模板ID
	@stypeid		VARCHAR(50),	--分支机构ID
	@OperatorID		VARCHAR(50),
	@IsCost			INT				--是否成本明细 1:是 0： 否
)
--@encode$--
AS
SET NOCOUNT ON



BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
	INSERT INTO #Ac_Account_L (Typeid,StypeId) 
	SELECT L.Typeid,L.Stypeid
	FROM F_LineAccount(@OperatorID,'') L
	WHERE L.Stypeid=@stypeid
END;

--按分支取科目临时表
SELECT	a.TypeId as typeid,
		a.StypeId as stypeid,
		A.UserCode AS usercode,
		a.FullName as fullname 
INTO #tempAc_account
FROM dbo.Ac_Account A
INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND A.StypeId=L.StypeId
WHERE A.StypeId = @stypeid

INSERT INTO #tempAc_account(Typeid,StypeId,usercode,fullname) VALUES('',@stypeid,'','')
SELECT	
	atdid,
	a.atid,
	Summary,
	AcFrom AS atypefrom,
	isnull(d.UserCode,'****') as usercode,
	isnull(d.FullName,'****') as fullname,
	a.AtypeId AS typeid, 
	a.fdc AS dc,
	c.FullName AS totalfrom,
	a.Express,
	c.content,
	a.SummaryType,
	A.OrderID
FROM dbo.Ac_Auditing_Template_Detail a
INNER JOIN dbo.Ac_Auditing_Template b ON a.AtId = b.Atid AND a.isCost=@IsCost
INNER JOIN Ac_BillMoney_List c ON a.BillMoneyId = c.BillMoneyId
LEFT JOIN #tempAc_account d ON a.AtypeId = d.TypeId
WHERE 
	a.AtId = @atid 
ORDER BY a.AtdId

DROP TABLE #tempAc_account

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadAuditingTemplate_Details]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadAuditingTemplate_Details]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2012-04-23
	描述：调取凭证模板明细信息
*/
CREATE PROCEDURE Web_LoadAuditingTemplate_Details
(
	@atid			INT,			--模板ID
	@stypeid		VARCHAR(50),		--分支机构ID
	@OperatorID		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON



BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
	INSERT INTO #Ac_Account_L (Typeid,StypeId) 
	SELECT L.Typeid,L.Stypeid--,A.FullName 
	FROM F_LineAccount(@OperatorID,'') L
	--INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
	WHERE L.Stypeid=@stypeid

END;

--按分支取科目临时表
SELECT	a.TypeId as typeid,
		a.StypeId as stypeid,
		A.UserCode AS usercode,
		a.FullName as fullname 
INTO #tempAc_account
FROM dbo.Ac_Account A
INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND A.StypeId=L.StypeId
WHERE A.StypeId = @stypeid

--处理会计科目为空的情况 在权限表里写入空记录
INSERT INTO #tempAc_account(Typeid,StypeId,usercode,fullname) VALUES('',@stypeid,'','')

SELECT	atdid,
		a.atid,
		Summary,
		AcFrom AS atypefrom,
		isnull(d.UserCode,'****') as usercode,
		isnull(d.FullName,'****') as fullname,
		a.AtypeId AS typeid, 
		a.fdc AS dc,
		c.FullName AS totalfrom,
		a.Express,
		c.content,
		a.SummaryType,
		A.OrderID
FROM dbo.Ac_Auditing_Template_Detail a
INNER JOIN dbo.Ac_Auditing_Template b ON a.AtId = b.Atid
INNER JOIN Ac_BillMoney_List c ON a.BillMoneyId = c.BillMoneyId
LEFT JOIN #tempAc_account d ON a.AtypeId = d.TypeId
WHERE a.AtId = @atid
ORDER BY a.AtdId


DROP TABLE #tempAc_account

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadBillCustom]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadBillCustom]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：Awu
	日期：20151020
	描述：调单时获取自定义表头及显示字段数据
*/
CREATE PROCEDURE Web_LoadBillCustom
(
	@BillNumberId	INT,			--单据id
	@BillType		INT,			--单据类型
	@stypeid	VARCHAR(50) = '',	--分支机构
	@dbtypeid	VARCHAR(50) = '',	--往来单位
	@btypeid	VARCHAR(50) = '',	--结算单位
	@etypeid	VARCHAR(50) = '',	--经手人
	@dtypeid	VARCHAR(50) = '',	--部门
	@stockid	VARCHAR(50) = ''	--仓库
)
--@encode$--
AS
SET NOCOUNT ON

--获取自定义字段数据
SELECT  T1.SysDiy1_head AS SysDiy1,
		T1.SysDiy2_head AS SysDiy2,
		T1.SysDiy3_head AS SysDiy3,
		T1.SysDiy4_head AS SysDiy4,
		T1.SysDiy5_head AS SysDiy5,
		T1.SysDiy6_head AS SysDiy6,
		T1.SysDiy7_head AS SysDiy7,
		T1.SysDiy8_head AS SysDiy8,
		T1.SysDiy9_head AS SysDiy9,
		T1.SysDiy10_head AS SysDiy10, 		
		T1.SysDiy17_head AS SysDiy17, 
		T1.SysDiy18_head AS SysDiy18, 
		T1.SysDiy19_head AS SysDiy19, 
		T1.SysDiy20_head AS SysDiy20, 
		T1.SysDiy21_head AS SysDiy21, 
		T1.SysDiy22_head AS SysDiy22, 
		T1.SysDiy23_head AS SysDiy23, 
		T1.SysDiy24_head AS SysDiy24, 
		T1.SysDiy25_head AS SysDiy25, 
		T1.SysDiy26_head AS SysDiy26, 
		T1.SysDiy27_head AS SysDiy27, 
		T1.SysDiy28_head AS SysDiy28, 
		T1.SysDiy29_head AS SysDiy29, 
		T1.SysDiy30_head AS SysDiy30, 
		T1.SysDiy31_head AS SysDiy31, 
		T1.SysDiy32_head AS SysDiy32,		
		T1.SysDiy11_head AS SysDiy11,
		T2.FullName AS SysDiy11_fullname,		
		T1.SysDiy12_head AS SysDiy12,
		T3.FullName AS SysDiy12_fullname,		
		T1.SysDiy13_head AS SysDiy13,
		T4.FullName AS SysDiy13_fullname,		
		T1.SysDiy14_head AS SysDiy14,
		T5.FullName AS SysDiy14_fullname,		
		T1.SysDiy15_head AS SysDiy15,
		T6.FullName AS SysDiy15_fullname,		
		T1.SysDiy16_head AS SysDiy16,
		T7.FullName AS SysDiy16_fullname,		
		T1.SysDiy33_head AS SysDiy33,
		T21.FullName AS SysDiy33_fullname,		
		T1.SysDiy34_head AS SysDiy34,
		T22.FullName AS SysDiy34_fullname,		
		T1.SysDiy35_head AS SysDiy35,
		T23.FullName AS SysDiy35_fullname,		
		T1.SysDiy36_head AS SysDiy36,
		T24.FullName AS SysDiy36_fullname,		
		T1.SysDiy37_head AS SysDiy37,
		T51.FullName AS SysDiy37_fullname,		
		T1.SysDiy38_head AS SysDiy38,
		T52.FullName AS SysDiy38_fullname,		
		T1.SysDiy39_head AS SysDiy39,
		T53.FullName AS SysDiy39_fullname,		
		T1.SysDiy40_head AS SysDiy40,
		T54.FullName AS SysDiy40_fullname
FROM	dbo.Custom_BillIndex T1
LEFT JOIN dbo.employee T2 ON T1.SysDiy11_head = T2.typeId 
LEFT JOIN dbo.ptype T3 ON T1.SysDiy12_head = T3.typeId
LEFT JOIN dbo.btype T4 ON T1.SysDiy13_head = T4.typeId
LEFT JOIN dbo.Department T5 ON T1.SysDiy14_head = T5.typeid
LEFT JOIN dbo.Stock T6 ON T1.SysDiy15_head = T6.typeId
LEFT JOIN dbo.SType T7 ON T1.SysDiy16_head = T7.TypeId
LEFT JOIN dbo.employee T21 ON T1.SysDiy33_head = T21.typeId 
LEFT JOIN dbo.employee T22 ON T1.SysDiy34_head = T22.typeId 
LEFT JOIN dbo.employee T23 ON T1.SysDiy35_head = T23.typeId 
LEFT JOIN dbo.employee T24 ON T1.SysDiy36_head = T24.typeId 
LEFT JOIN dbo.Department T51 ON T1.SysDiy37_head = T51.typeid
LEFT JOIN dbo.Department T52 ON T1.SysDiy38_head = T52.typeid
LEFT JOIN dbo.Department T53 ON T1.SysDiy39_head = T53.typeid
LEFT JOIN dbo.Department T54 ON T1.SysDiy40_head = T54.typeid
WHERE T1.BillId = @BillNumberId AND T1.BillType = @BillType


--以下获取自定义显示字段

SELECT  UserCode AS ds_usercode,
		tel AS ds_tel,
		LinkMan AS ds_linkman,
		CASE PriceType WHEN 0 THEN '商品物价信息'
			ELSE '分支机构物价信息' END AS ds_pricetype 
FROM dbo.SType 
WHERE TypeId = @stypeid


SELECT	Tel1  AS ddb_tel1,
		T1.tel2 AS ddb_tel2,
		tel3  AS ddb_tel3,
		TelAndAddress  AS ddb_TelAndAddress,
		WWW  AS ddb_www,
		T1.Email  AS ddb_email,
		fax  AS ddb_fax,
		T2.FullName AS ddb_afullname,
		TaxNumber  AS ddb_TaxNumber,
		Bank  AS ddb_Bank,
		BankName  AS ddb_BankName,
		BankAndAcount  AS ddb_BankAndAcount,
		LinkMan1  AS ddb_LinkMan1, 
		LinkTel1  AS ddb_LinkTel1,
		LinkMobile1  AS ddb_LinkMobile1,
		LinkMan2  AS ddb_LinkMan2,
		LinkTel2  AS ddb_LinkTel2,
		LinkMobile2  AS ddb_LinkMobile2,
		T1.PyCode  AS ddb_PyCode,
		CASE WHEN ARLimitTime < 9999 THEN CAST(ARLimitTime AS INT) ELSE NULL END  AS ddb_ARLimitTime,
		CASE WHEN paymentLTime < 9999 THEN CAST(paymentLTime AS INT) ELSE NULL END  AS ddb_paymentLTime,
		CAST(SaleZekou AS FLOAT)  AS ddb_SaleZekou,
		CAST(BuyZekou AS FLOAT)  AS ddb_BuyZekou,
		T3.FullName AS ddb_efullname,
		T1.Comment  AS ddb_Comment
FROM dbo.btype T1
	LEFT JOIN dbo.AreaType T2 ON T1.AreaTypeID = T2.typeid
	LEFT JOIN dbo.employee T3 ON T1.etypeid = T3.typeId
WHERE T1.TypeId = @dbtypeid	


	SELECT Tel1  AS db_tel1,
		T1.tel2 AS db_tel2,
		tel3  AS db_tel3,
		TelAndAddress  AS db_TelAndAddress,
		WWW  AS db_www,
		T1.Email  AS db_email,
		fax  AS db_fax,
		T2.FullName AS db_afullname,
		TaxNumber  AS db_TaxNumber,
		Bank  AS db_Bank,
		BankName  AS db_BankName,
		BankAndAcount  AS ddb_BankAndAcount,
		LinkMan1  AS db_LinkMan1, 
		LinkTel1  AS db_LinkTel1,
		LinkMobile1  AS db_LinkMobile1,
		LinkMan2  AS db_LinkMan2,
		LinkTel2  AS db_LinkTel2,
		LinkMobile2  AS db_LinkMobile2,
		T1.PyCode  AS db_PyCode,
		CASE WHEN ARLimitTime < 9999 THEN CAST(ARLimitTime AS INT) ELSE NULL END  AS db_ARLimitTime,
		CASE WHEN paymentLTime < 9999 THEN CAST(paymentLTime AS INT) ELSE NULL END  AS db_paymentLTime,
		CAST(SaleZekou AS FLOAT)  AS db_SaleZekou,
		CAST(BuyZekou AS FLOAT)  AS db_BuyZekou,
		T3.FullName AS db_efullname,
		T1.Comment  AS db_Comment
FROM dbo.btype T1
	LEFT JOIN dbo.AreaType T2 ON T1.AreaTypeID = T2.typeid
	LEFT JOIN dbo.employee T3 ON T1.etypeid = T3.typeId		
WHERE T1.TypeId = @btypeid	


SELECT T1.usercode AS de_usercode,
		CASE WHEN Birthday = '2050-01-01' OR Birthday = '1900-01-01' THEN NULL ELSE CONVERT(varchar(100),Birthday,23) END  AS de_Birthday,
		T1.tel AS de_tel,
		Mob AS de_mob,
		mail AS de_mail,
		job AS de_job,
		T1.Address AS de_address,
		T1.PyCode AS de_pycode,
		T1.Comment AS de_comment,
		CASE WHEN maxpre = -999999999918.99 THEN NULL ELSE CAST(MaxPre AS FLOAT)END AS de_maxpre,
		CAST(tichengRate AS FLOAT) AS de_tichengRate,
		T2.FullName AS de_sfullname
FROM dbo.employee T1
	INNER JOIN dbo.SType T2 ON T1.STypeID = T2.TypeId
WHERE T1.TypeId = @etypeid	


SELECT usercode AS dd_usercode,
		Name AS dd_name,
		Tel AS dd_tel,
		fax AS dd_fax,
		LinkMan AS dd_linkman,
		Comment AS dd_comment,
		PyCode AS dd_pycode
FROM dbo.Department
WHERE typeid = @dtypeid


SELECT T1.UserCode AS dst_usercode,
		T1.name AS dst_name,
		[add] AS dst_add,
		T1.Tel AS dst_tel,
		T1.LinkMan AS dst_linkman,
		T1.PyCode AS dst_pycode,
		T1.Comment AS dst_comment,
		T2.FullName AS dst_sfullname
FROM dbo.Stock T1
	INNER JOIN dbo.SType T2 ON t1.STypeID = T2.TypeId
WHERE T1.TypeId = @stockid	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadBillCustomAutoDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadBillCustomAutoDraft]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：Awu
	日期：20151020
	描述：调单时获取自定义表头及显示字段数据
*/
CREATE PROCEDURE Web_LoadBillCustomAutoDraft
(
	@BillGuid	VARCHAR(100),			--单据BillGuid
	@BillType	INT,			--单据类型
	@stypeid	VARCHAR(50) = '',	--分支机构
	@dbtypeid	VARCHAR(50) = '',	--往来单位
	@btypeid	VARCHAR(50) = '',	--结算单位
	@etypeid	VARCHAR(50) = '',	--经手人
	@dtypeid	VARCHAR(50) = '',	--部门
	@stockid	VARCHAR(50) = ''	--仓库
)
--@encode$--
AS
SET NOCOUNT ON

--获取自定义字段数据
SELECT  T1.SysDiy1_head AS SysDiy1,
		T1.SysDiy2_head AS SysDiy2,
		T1.SysDiy3_head AS SysDiy3,
		T1.SysDiy4_head AS SysDiy4,
		T1.SysDiy5_head AS SysDiy5,
		T1.SysDiy6_head AS SysDiy6,
		T1.SysDiy7_head AS SysDiy7,
		T1.SysDiy8_head AS SysDiy8,
		T1.SysDiy9_head AS SysDiy9,
		T1.SysDiy10_head AS SysDiy10, 		
		T1.SysDiy17_head AS SysDiy17, 
		T1.SysDiy18_head AS SysDiy18, 
		T1.SysDiy19_head AS SysDiy19, 
		T1.SysDiy20_head AS SysDiy20, 
		T1.SysDiy21_head AS SysDiy21, 
		T1.SysDiy22_head AS SysDiy22, 
		T1.SysDiy23_head AS SysDiy23, 
		T1.SysDiy24_head AS SysDiy24, 
		T1.SysDiy25_head AS SysDiy25, 
		T1.SysDiy26_head AS SysDiy26, 
		T1.SysDiy27_head AS SysDiy27, 
		T1.SysDiy28_head AS SysDiy28, 
		T1.SysDiy29_head AS SysDiy29, 
		T1.SysDiy30_head AS SysDiy30, 
		T1.SysDiy31_head AS SysDiy31, 
		T1.SysDiy32_head AS SysDiy32,		
		T1.SysDiy11_head AS SysDiy11,
		T2.FullName AS SysDiy11_fullname,		
		T1.SysDiy12_head AS SysDiy12,
		T3.FullName AS SysDiy12_fullname,		
		T1.SysDiy13_head AS SysDiy13,
		T4.FullName AS SysDiy13_fullname,		
		T1.SysDiy14_head AS SysDiy14,
		T5.FullName AS SysDiy14_fullname,		
		T1.SysDiy15_head AS SysDiy15,
		T6.FullName AS SysDiy15_fullname,		
		T1.SysDiy16_head AS SysDiy16,
		T7.FullName AS SysDiy16_fullname,		
		T1.SysDiy33_head AS SysDiy33,
		T21.FullName AS SysDiy33_fullname,		
		T1.SysDiy34_head AS SysDiy34,
		T22.FullName AS SysDiy34_fullname,		
		T1.SysDiy35_head AS SysDiy35,
		T23.FullName AS SysDiy35_fullname,		
		T1.SysDiy36_head AS SysDiy36,
		T24.FullName AS SysDiy36_fullname,		
		T1.SysDiy37_head AS SysDiy37,
		T51.FullName AS SysDiy37_fullname,		
		T1.SysDiy38_head AS SysDiy38,
		T52.FullName AS SysDiy38_fullname,		
		T1.SysDiy39_head AS SysDiy39,
		T53.FullName AS SysDiy39_fullname,		
		T1.SysDiy40_head AS SysDiy40,
		T54.FullName AS SysDiy40_fullname
FROM	dbo.Custom_BillIndexAutoDraft T1
LEFT JOIN dbo.employee T2 ON T1.SysDiy11_head = T2.typeId 
LEFT JOIN dbo.ptype T3 ON T1.SysDiy12_head = T3.typeId
LEFT JOIN dbo.btype T4 ON T1.SysDiy13_head = T4.typeId
LEFT JOIN dbo.Department T5 ON T1.SysDiy14_head = T5.typeid
LEFT JOIN dbo.Stock T6 ON T1.SysDiy15_head = T6.typeId
LEFT JOIN dbo.SType T7 ON T1.SysDiy16_head = T7.TypeId
LEFT JOIN dbo.employee T21 ON T1.SysDiy33_head = T21.typeId 
LEFT JOIN dbo.employee T22 ON T1.SysDiy34_head = T22.typeId 
LEFT JOIN dbo.employee T23 ON T1.SysDiy35_head = T23.typeId 
LEFT JOIN dbo.employee T24 ON T1.SysDiy36_head = T24.typeId 
LEFT JOIN dbo.Department T51 ON T1.SysDiy37_head = T51.typeid
LEFT JOIN dbo.Department T52 ON T1.SysDiy38_head = T52.typeid
LEFT JOIN dbo.Department T53 ON T1.SysDiy39_head = T53.typeid
LEFT JOIN dbo.Department T54 ON T1.SysDiy40_head = T54.typeid
WHERE T1.BillGuid = @BillGuid AND T1.BillType = @BillType


--以下获取自定义显示字段

SELECT  UserCode AS ds_usercode,
		tel AS ds_tel,
		LinkMan AS ds_linkman,
		CASE PriceType WHEN 0 THEN '商品物价信息'
			ELSE '分支机构物价信息' END AS ds_pricetype 
FROM dbo.SType 
WHERE TypeId = @stypeid


SELECT	Tel1  AS ddb_tel1,
		T1.tel2 AS ddb_tel2,
		tel3  AS ddb_tel3,
		TelAndAddress  AS ddb_TelAndAddress,
		WWW  AS ddb_www,
		T1.Email  AS ddb_email,
		fax  AS ddb_fax,
		T2.FullName AS ddb_afullname,
		TaxNumber  AS ddb_TaxNumber,
		Bank  AS ddb_Bank,
		BankName  AS ddb_BankName,
		BankAndAcount  AS ddb_BankAndAcount,
		LinkMan1  AS ddb_LinkMan1, 
		LinkTel1  AS ddb_LinkTel1,
		LinkMobile1  AS ddb_LinkMobile1,
		LinkMan2  AS ddb_LinkMan2,
		LinkTel2  AS ddb_LinkTel2,
		LinkMobile2  AS ddb_LinkMobile2,
		T1.PyCode  AS ddb_PyCode,
		CASE WHEN ARLimitTime < 9999 THEN CAST(ARLimitTime AS INT) ELSE NULL END  AS ddb_ARLimitTime,
		CASE WHEN paymentLTime < 9999 THEN CAST(paymentLTime AS INT) ELSE NULL END  AS ddb_paymentLTime,
		CAST(SaleZekou AS FLOAT)  AS ddb_SaleZekou,
		CAST(BuyZekou AS FLOAT)  AS ddb_BuyZekou,
		T3.FullName AS ddb_efullname,
		T1.Comment  AS ddb_Comment
FROM dbo.btype T1
	LEFT JOIN dbo.AreaType T2 ON T1.AreaTypeID = T2.typeid
	LEFT JOIN dbo.employee T3 ON T1.etypeid = T3.typeId
WHERE T1.TypeId = @dbtypeid	


	SELECT Tel1  AS db_tel1,
		T1.tel2 AS db_tel2,
		tel3  AS db_tel3,
		TelAndAddress  AS db_TelAndAddress,
		WWW  AS db_www,
		T1.Email  AS db_email,
		fax  AS db_fax,
		T2.FullName AS db_afullname,
		TaxNumber  AS db_TaxNumber,
		Bank  AS db_Bank,
		BankName  AS db_BankName,
		BankAndAcount  AS ddb_BankAndAcount,
		LinkMan1  AS db_LinkMan1, 
		LinkTel1  AS db_LinkTel1,
		LinkMobile1  AS db_LinkMobile1,
		LinkMan2  AS db_LinkMan2,
		LinkTel2  AS db_LinkTel2,
		LinkMobile2  AS db_LinkMobile2,
		T1.PyCode  AS db_PyCode,
		CASE WHEN ARLimitTime < 9999 THEN CAST(ARLimitTime AS INT) ELSE NULL END  AS db_ARLimitTime,
		CASE WHEN paymentLTime < 9999 THEN CAST(paymentLTime AS INT) ELSE NULL END  AS db_paymentLTime,
		CAST(SaleZekou AS FLOAT)  AS db_SaleZekou,
		CAST(BuyZekou AS FLOAT)  AS db_BuyZekou,
		T3.FullName AS db_efullname,
		T1.Comment  AS db_Comment
FROM dbo.btype T1
	LEFT JOIN dbo.AreaType T2 ON T1.AreaTypeID = T2.typeid
	LEFT JOIN dbo.employee T3 ON T1.etypeid = T3.typeId		
WHERE T1.TypeId = @btypeid	


SELECT T1.usercode AS de_usercode,
		CASE WHEN Birthday = '2050-01-01' OR Birthday = '1900-01-01' THEN NULL ELSE CONVERT(varchar(100),Birthday,23) END  AS de_Birthday,
		T1.tel AS de_tel,
		Mob AS de_mob,
		mail AS de_mail,
		job AS de_job,
		T1.Address AS de_address,
		T1.PyCode AS de_pycode,
		T1.Comment AS de_comment,
		CASE WHEN maxpre = -999999999918.99 THEN NULL ELSE CAST(MaxPre AS FLOAT)END AS de_maxpre,
		CAST(tichengRate AS FLOAT) AS de_tichengRate,
		T2.FullName AS de_sfullname
FROM dbo.employee T1
	INNER JOIN dbo.SType T2 ON T1.STypeID = T2.TypeId
WHERE T1.TypeId = @etypeid	


SELECT usercode AS dd_usercode,
		Name AS dd_name,
		Tel AS dd_tel,
		fax AS dd_fax,
		LinkMan AS dd_linkman,
		Comment AS dd_comment,
		PyCode AS dd_pycode
FROM dbo.Department
WHERE typeid = @dtypeid


SELECT T1.UserCode AS dst_usercode,
		T1.name AS dst_name,
		[add] AS dst_add,
		T1.Tel AS dst_tel,
		T1.LinkMan AS dst_linkman,
		T1.PyCode AS dst_pycode,
		T1.Comment AS dst_comment,
		T2.FullName AS dst_sfullname
FROM dbo.Stock T1
	INNER JOIN dbo.SType T2 ON t1.STypeID = T2.TypeId
WHERE T1.TypeId = @stockid	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadBillIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadBillIndex]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2012-10-24
	描述：获利，返利调出库单，入库单
-------------------------------------------*/
CREATE PROCEDURE Web_LoadBillIndex
(
	@OperatorID		VARCHAR(50),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@BillType		INT,		--获利返利调出库入库单
	@stypeid		VARCHAR(50),
	@cid			INT,
	@etypeid		VARCHAR(50) = '',
	@dealbtypeid	VARCHAR(50)= '',	--往来单位
	@btypeid		VARCHAR(50)= '',	--结算单位
	@dtypeid		VARCHAR(50)= '',
	@billcode		VARCHAR(100)= ''	
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Stype (typeid VARCHAR(50))
CREATE TABLE #Etype (typeid VARCHAR(50))
CREATE TABLE #Btype (typeid VARCHAR(50))
CREATE TABLE #Dtype (typeid VARCHAR(50))
CREATE TABLE #DealBtype (typeid VARCHAR(50))

IF @stypeid <> '' OR @MStypeid = '-99999'
	INSERT #Stype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	
IF @etypeid <> '' OR @MEtypeid = '-99999'
	INSERT #Etype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)

--结算单位
IF @btypeid <> '' OR @MBtypeid = '-99999'
	INSERT #Btype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)

--往来单位
IF @dealbtypeid <> '' OR @MBtypeid = '-99999'
	INSERT #DealBtype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)

IF @dtypeid <> '' OR @MDtypeid = '-99999'
	INSERT #Dtype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealbtypeid,9,@OperatorID)

DECLARE @SQL VARCHAR(5000)

SET @SQL = ' SELECT A.BillNumberId,N.BillName,A.BillType,A.BillDate,A.BillCode,A.Stypeid,A.etypeid,A.DTypeId,A.DealBTypeID,A.checke,A.explain,A.Comment 
			 FROM BillIndex A '
			 
IF @stypeid <> '' OR @MStypeid = '-99999'
	SET @SQL += ' INNER JOIN #Stype S ON S.typeid = A.Stypeid '

IF @etypeid <> '' OR @MEtypeid = '-99999'
	SET @SQL += ' INNER JOIN #Etype E ON E.typeid = A.etypeid '			 

IF @btypeid <> '' OR @MBtypeid = '-99999'
	SET @SQL += ' INNER JOIN #Btype B ON B.typeid = A.Btypeid '

IF @dealbtypeid <> '' OR @MBtypeid = '-99999'
	SET @SQL += ' INNER JOIN #DealBtype BL ON BL.typeid = A.DealBTypeID '

IF @dtypeid <> '' OR @MDtypeid = '-99999'
	SET @SQL += ' INNER JOIN #Dtype D ON D.typeid = A.dtypeid '
			
SET @SQL += ' 
			  INNER JOIN BillName N ON N.Billtype = A.BillType
			  WHERE A.BillDate >='''+@StartDate+''' AND A.BillDate <= '''+@EndDate+''' AND A.BillType = '''+CONVERT(VARCHAR,@BillType)+'''  '

IF @cid <> ''
	SET @SQL += ' AND A.cid = '+CONVERT(VARCHAR,@cid)+' '

IF @billcode <> ''
	SET @SQL += ' AND A.BillCode LIKE '+ CHAR(39) + '%'+@billcode + '%' + CHAR(39)

SET @SQL += ' AND ifcheck = ''t'' AND RedWord = 0 '

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Btype,#DealBtype,#Dtype,#Etype,#Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_LoadDeliveryBillDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_LoadDeliveryBillDetails]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE Web_LoadDeliveryBillDetails
(
	@billnumberid	varchar(50),
	@billtype		INT,
	@chvoperatorid 	varchar(50)='', 	-- 操作员 ID（作权限范围检查用）
	@detailflag		INT=0,				-- 单据明细 单独使用 
	@draft			INT=0				-- 调草稿 单独使用 
)
--@encode$--
AS
SET NOCOUNT ON 
	-------- 权限检查 - Start --------
	DECLARE @intRe int, 
			@chvMATypeID varchar(50), 
			@chvMBTypeID varchar(50), 
			@chvMBTypeID2 varchar(50), 
			@chvMETypeID varchar(50), 
			@chvMKTypeID varchar(50), 
			@chvMPTypeID varchar(50), 
			@chvMExpense varchar(50), 
			@chvMIncome varchar(50), 
			@chvMCapital varchar(50), 
			@chvMDtypeid varchar(50), 
			@chvMStypeid varchar(50)

	EXEC @intRe = GP_CheckOperatorRight23_Rep 
		@chvoperatorid, 
		@chvMATypeID output, 
		@chvMBTypeID output, 
		@chvMBTypeID2 output, 
		@chvMETypeID output, 
		@chvMKTypeID output, 
		@chvMPTypeID output, 
		@chvMExpense output, 
		@chvMIncome output, 
		@chvMCapital output, 
		@chvMDtypeid output, 
		@chvMStypeid output

	--拥有查询所有商品的权限（MangerPTypeID = '00000'）
	--（MangerPTypeID = '-99999'并且ptype_l没有记录，表示没有权限)
	--（MangerPTypeID = '-99999'并且ptype_l有记录，表示拥有部分权限)
	
	
	--创建临时表，获取自定义字段
	SELECT	cbd.*,
			e.fullname as efullnamecustom,
			p.fullname as pfullnamecustom,
			b.fullname as bfullnamecustom,
			d.fullname as dfullnamecustom,
			k.fullname as kfullnamecustom,
			s.fullname as sfullnamecustom,
			e1.fullname as efullnamecustom33,
			e2.fullname as efullnamecustom34,
			e3.fullname as efullnamecustom35,
			e4.fullname as efullnamecustom36,
			d1.fullname as dfullnamecustom37,
			d2.fullname as dfullnamecustom38,
			d3.fullname as dfullnamecustom39,
			d4.fullname as dfullnamecustom40
	INTO #Custom_T
	FROM custom_billdetails cbd
	LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
	LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
	LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
	LEFT JOIN department d ON cbd.sysdiy14=d.typeid
	LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
	LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
	LEFT JOIN employee e1 ON cbd.sysdiy33=e1.typeid
	LEFT JOIN employee e2 ON cbd.sysdiy34=e2.typeid
	LEFT JOIN employee e3 ON cbd.sysdiy35=e3.typeid
	LEFT JOIN employee e4 ON cbd.sysdiy36=e4.typeid
	LEFT JOIN department d1 ON cbd.sysdiy37=d1.typeid
	LEFT JOIN department d2 ON cbd.sysdiy38=d2.typeid
	LEFT JOIN department d3 ON cbd.sysdiy39=d3.typeid
	LEFT JOIN department d4 ON cbd.sysdiy40=d4.typeid
	WHERE cbd.BillId=@billnumberid and cbd.BillType = @billtype
	
	CREATE TABLE #temp_PtypeId
	(
		Typeid	VARCHAR(50)
	)
	CREATE CLUSTERED INDEX CIX_PTYPE_typeid ON #temp_PtypeId(Typeid) 
	IF @intRe = 0 AND @chvMPTypeID = '-99999'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM PType_L WHERE ETypeId = @chvoperatorid)
		BEGIN
			insert into #temp_PtypeId (Typeid)	
			SELECT 	M.typeId
			FROM 	(
					SELECT	DISTINCT P.TypeId 
					FROM	PType_L L
					INNER JOIN PType  P ON (L.etypeid = @chvoperatorid 
											AND L.Flag=1 
											AND P.deleted = 0
											AND P.TypeId LIKE L.TypeId + '%' )
					UNION
					SELECT	L.TypeID
					FROM	ptype_l L
					WHERE	L.etypeid = @chvoperatorid
							AND L.flag=0
				) M
		END
	END
	ELSE IF @intRe = 0 AND @chvMPTypeID = '00000'
	BEGIN
		insert into #temp_PtypeId (Typeid)	
		SELECT DISTINCT typeId FROM PType WHERE sonnum = 0 AND deleted = 0 
	END
	-------- 权限检查 - End --------
	
	if @billtype = 326 --要货申请单
	begin
		select b.* ,p.FullName,p.UserCode,vi.fullname as itemname,
		p.typeid,p.customitemid,p.customitemfrom,p.customitemname,
		p.customitemrefid,p.isservice,p.ifserial,p.unit1,p.unit2,p.unitrate1,p.assistantunitid,pu.unitstype,
		pu.unitid,pu.unit,pu.unitrate,pu.nunitid,pu.nunit,pu.rate,pu.stockunitid,pu.stockunitname,pu.stockmunitrate,pu.ifusegoodsnum,
		(dbo.F_GetAllEntrycode(b.ptypeid,pu.StockUnitId,2)) AS stockmunitcode,
		(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname1,
		(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname2,
		(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname3,
		(SELECT SaleUnitRate1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate1,
		(SELECT SaleUnitRate2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate2,
		(SELECT SaleUnitRate3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate3,
		case when b.DeliveryQty >= b.qty then 0 else b.qty-b.DeliveryQty end as notcompleteqty,
		puu.FullName as baseunitname,
		puum.FullName as munitname,
		puum.FullName as munit,
		ct.*
		from DeliveryApplyBill b
		inner join #temp_PtypeId p1 on p1.typeid=b.ptypeid 
		left join ptype p on p.typeId = b.PtypeId
		left join vWeb_ItemIDByIsCombined vi on vi.id = b.ItemID and vi.iscombined = b.IsCombined
		LEFT JOIN dbo.F_GetPtypeUnitInfo() pu ON b.ptypeid=pu.typeid 
		left join PType_Units puu on puu.UnitsId = b.UnitID
		left join PType_Units puum on puum.UnitsId = b.MUnitID
		left join #Custom_T ct on ct.Detailid = b.ID
		where BillNumberId = @billnumberid
		
	end
	else if @billtype =327 --门店配送单
	begin
		DECLARE @SQL VARCHAR(MAX)
		SET @SQL='
		with back as
		(
			select	dbb.DeliveryID,
					sum(case when b.draft = 0 then dbb.Qty else 0 end) as thqyt,
					sum(case when b.draft = 1 then dbb.Qty else 0 end) as thwgzqyt
			from	DeliveryBackBill dbb
			inner join PosAllotApplyBillIndex b on b.BillNumberId = dbb.BillNumberId AND b.RedWord=0
			inner join DeliveryBill db on db.ID = dbb.DeliveryID and db.BillNumberId = '+@billnumberid+'
			group by dbb.DeliveryID		
		)
		select	b.* ,p.FullName,p.UserCode,vi.fullname as itemname,
				p.typeid,p.customitemid,p.customitemfrom,p.customitemname,
				p.customitemrefid,p.isservice,p.ifserial,p.unit1,p.unit2,p.unitrate1,p.assistantunitid,pu.unitstype,
				pu.unitid,pu.unit,pu.nunitid,pu.nunit,pu.rate,pu.stockunitid,pu.stockunitname,pu.stockmunitrate,pu.ifusegoodsnum,
				(dbo.F_GetAllEntrycode(b.ptypeid,b.MUnitID,2)) AS stockmunitcode,
				(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname1,
				(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname2,
				(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname3,
				(SELECT SaleUnitRate1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate1,
				(SELECT SaleUnitRate2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate2,
				(SELECT SaleUnitRate3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate3,
				dbo.F_RoundQty(b.CheckQty/b.MUnitRate) as mCheckQty, --验收入库数量				
				dbo.F_RoundQty((b.qty-b.CheckQty-isnull(b.backqty,0)-isnull(back.thwgzqyt,0))/b.MUnitRate) as mnotcheckqty, --未验收数量
				isnull((b.backqty + isnull(back.thwgzqyt,0))/b.MUnitRate,0) as mthqty,
				dbo.F_RoundQty(isnull(back.thwgzqyt/b.MUnitRate,0)) as mthwgzqty, --退货未过账数量
				puu.FullName as baseunitname,
				puum.FullName as munitname,
				puum.FullName as munit,
				b.UnfinishedQty notcompleteqty,
				b.ktypeidout as ktypeid,
				kout.FullName as kfullname,
				b.ktypeidin as ktypeid2,
				kin.FullName as kfullname2,
				b.CargoIDout as outcargoid,
				cout.FullName as cargofullnameout,
				b.CargoIDin as incargoid,
				cin.FullName as cargofullnamein,
				ct.*
		from DeliveryBill b
		--inner join PosAllotApplyBillIndex pb on b.billnumberid = pb.billnumberid and pb.redword = 0
		inner join #temp_PtypeId p1 on p1.typeid=b.ptypeid
		left join ptype p on p.typeId = b.PtypeId
		left join vWeb_ItemIDByIsCombined vi on vi.id = b.ItemID and vi.iscombined = b.IsCombined
		LEFT JOIN dbo.F_GetPtypeUnitInfo() pu ON b.ptypeid=pu.typeid 
		left join PType_Units puu on puu.UnitsId = b.UnitID
		left join PType_Units puum on puum.UnitsId = b.MUnitID
		left join back back on back.DeliveryID = b.ID
		left join stock kout on kout.typeId = b.ktypeidout
		left join stock kin	on kin.typeId = b.ktypeidin
		left join CargoType cout on cout.CargoID = b.CargoIDout
		left join CargoType cin on cin.CargoID = b.CargoIDin
		left join #Custom_T ct on ct.Detailid = b.ID
		where b.BillNumberId = '+@billnumberid 
		IF @detailflag = 0
			SET @SQL +=	'  AND b.qty >  b.BackQty '
		
		EXEC (@SQL)

	end
	else if @billtype =328 --门店配送退货单
	begin
		select b.* ,p.FullName,p.UserCode,vi.fullname as itemname,
		p.typeid,p.customitemid,p.customitemfrom,p.customitemname,
		p.customitemrefid,p.isservice,p.ifserial,p.unit1,p.unit2,p.unitrate1,p.assistantunitid,pu.unitstype,
		pu.unitid,pu.unit,pu.nunitid,pu.nunit,pu.rate,pu.stockunitid,pu.stockunitname,pu.stockmunitrate,pu.ifusegoodsnum,
		(dbo.F_GetAllEntrycode(b.ptypeid,pu.StockUnitId,2)) AS stockmunitcode,
		(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname1,
		(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname2,
		(SELECT fullname FROM PType_Units WHERE UnitsId=(SELECT SaleUnitID3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid)) as auxfullname3,
		(SELECT SaleUnitRate1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate1,
		(SELECT SaleUnitRate2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate2,
		(SELECT SaleUnitRate3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=b.ptypeid) as auxrate3,
		puu.FullName as baseunitname,
		puum.FullName as munitname,
		puum.FullName as munit,
		b.outktypeid as ktypeid,
		kout.FullName as kfullname,
		b.inktypeid as ktypeid2,
		kin.FullName as kfullname2,
		b.outCargoID as outcargoid,
		cout.FullName as cargofullnameout,
		b.inCargoID as incargoid,
		cin.FullName as cargofullnamein,
		ct.*
		from DeliveryBackBill b
		inner join #temp_PtypeId p1 on p1.typeid=b.ptypeid
		left join ptype p on p.typeId = b.PtypeId
		left join vWeb_ItemIDByIsCombined vi on vi.id = b.ItemID and vi.iscombined = b.IsCombined
		LEFT JOIN dbo.F_GetPtypeUnitInfo() pu ON b.ptypeid=pu.typeid 
		left join PType_Units puu on puu.UnitsId = b.UnitID
		left join PType_Units puum on puum.UnitsId = b.MUnitID
		left join stock kout on kout.typeId = b.outktypeid
		left join stock kin	on kin.typeId = b.inktypeid
		left join CargoType cout on cout.CargoID = b.outCargoID
		left join CargoType cin on cin.CargoID = b.inCargoID
		left join #Custom_T ct on ct.Detailid = b.ID
		where BillNumberId = @billnumberid
	end
	else if @billtype =329 --门店配送验收单
	begin
		
		with back as
		(
			select dbb.DeliveryID,sum(case when b.draft = 0 then dbb.Qty else 0 end) as thqyt,sum(case when b.draft = 1 then dbb.Qty else 0 end) as thwgzqyt
			from DeliveryBackBill dbb
			inner join PosAllotApplyBillIndex b on b.BillNumberId = dbb.BillNumberId AND b.RedWord=0 AND b.ifcheck='t'
			inner join DeliveryBill db on db.ID = dbb.DeliveryID and db.BillNumberId = @billnumberid	
			group by dbb.DeliveryID		
		)
		select b.* ,p.FullName,p.UserCode,vi.fullname as itemname,
		p.typeid,p.customitemid,p.customitemfrom,p.customitemname,
		p.customitemrefid,p.isservice,p.ifserial,p.unit1,p.unit2,p.unitrate1,p.assistantunitid,pu.unitstype,
		pu.unitid,pu.unit,pu.nunitid,pu.nunit,pu.rate,pu.stockunitid,pu.stockunitname,pu.stockmunitrate,pu.ifusegoodsnum,
		(dbo.F_GetAllEntrycode(b.ptypeid,b.MUnitID,2)) AS stockmunitcode,
		puum.FullName as munit,
		b.outktypeid as ktypeid,
		kout.FullName as kfullname,
		b.inktypeid as ktypeid2,
		kin.FullName as kfullname2,
		b.outCargoID as outcargoid,
		cout.FullName as cargofullnameout,
		b.inCargoID as incargoid,
		cin.FullName as cargofullnamein,
		ct.*
		from DeliveryCheckBill b
		inner join #temp_PtypeId p1 on p1.typeid=b.ptypeid
		left join ptype p on p.typeId = b.PtypeId
		left join vWeb_ItemIDByIsCombined vi on vi.id = b.ItemID and vi.iscombined = b.IsCombined
		LEFT JOIN dbo.F_GetPtypeUnitInfo() pu ON b.ptypeid=pu.typeid 
		left join PType_Units puu on puu.UnitsId = b.UnitID
		left join PType_Units puum on puum.UnitsId = b.MUnitID
		left join back back on back.DeliveryID = b.ID
		left join stock kout on kout.typeId = b.outktypeid
		left join stock kin	on kin.typeId = b.inktypeid
		left join CargoType cout on cout.CargoID = b.outCargoID
		left join CargoType cin on cin.CargoID = b.inCargoID
		left join #Custom_T ct on ct.Detailid = b.ID
		where BillNumberId = @billnumberid
	end
	
	--select * from vWeb_ItemIDByIsCombined
	--select * from DeliveryApplyBill
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadFactIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_LoadFactIndex
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/*
Mb
*/
CREATE PROCEDURE Web_LoadFactIndex 
( 
	@BillNumberId numeric(10,0)
)

--@encode$--
AS
SET NOCOUNT ON 

/*如果仓库出入库单走此分支*/
--IF ISNULL(@BillNumberId,'') IN (SELECT DISTINCT ISNULL(BillNumberId,'') FROM FactDepotInOut)
IF EXISTS (SELECT TOP 1 1 FROM FactIndex WHERE BillNumberId=@BillNumberId AND BILLTYPE IN ('418','419'))
BEGIN 
		SELECT DISTINCT f.BillNumberId, f.BillType,f.BillDate,f.BillCode,f.Stypeid,st.FullName AS sfullname,inout.FromBillType,bi.BillName AS frombillname,
		f.etypeid,et.FullName AS efullname,f.dtypeId,dt.FullName AS dfullname,f.ktypeid,sk.FullName AS kfullname,f.Comment,f.Comment AS discomment,
		f.explain,f.explain AS disexplain,f.EntryCode ,
		f.checke,
		ISNULL(E1.FullName,'') AS checkman,
	    ISNull(au.BillDetail,'') AS BillDetail,
	    ISNULL(ue.FullName,'') as updateename,
	    f.RedWord AS redword,
	    '' AS bfullname,
	    f.totalqty AS totalqty,
	    0 AS totalmoney,
		0 AS totalinmoney
		FROM dbo.FactIndex f
		LEFT JOIN dbo.FactDepotInOut inout ON inout.billNumberID=f.BillNumberId
		LEFT JOIN employee e1 ON E1.typeId=f.checke 
	    LEFT JOIN AuditingBill au	ON (au.billnumberid=f.billnumberid AND Au.BillIndexType = 7)
		LEFT JOIN dbo.SType  st ON st.TypeId=f.Stypeid
		LEFT JOIN dbo.BillName bi ON bi.Billtype=f.FromBillType
		LEFT JOIN employee et ON et.typeId=f.etypeid
		LEFT JOIN employee ue ON ue.typeId=f.updatee
		LEFT JOIN dbo.Department dt ON dt.typeid=f.dtypeId
		LEFT JOIN dbo.Stock sk ON sk.typeId=f.ktypeid 
		WHERE f.BillNumberId=@BillNumberId
END 
ELSE IF EXISTS (SELECT  TOP 1 1 FROM FactIndex WHERE BillNumberId=@BillNumberId AND BILLTYPE ='420')
/*如果仓库调拨走此分支*/
BEGIN
		DECLARE @kfullname VARCHAR(50),@kfullname2 VARCHAR(50),@ktypeid VARCHAR(50),@ktypeid2 VARCHAR(50);
		SELECT @ktypeid=ktypeid,@ktypeid2=ktypeid2 from dbo.FactIndex WHERE BillNumberId=@BillNumberId
		SELECT @kfullname=fullname FROM dbo.Stock WHERE typeId=@ktypeid
		SELECT @kfullname2=fullname FROM dbo.Stock WHERE typeId=@ktypeid2
		SELECT DISTINCT f.BillNumberId,f.BillType,f.BillDate,f.BillCode,f.Stypeid,st.FullName AS sfullname,f.etypeid,et.FullName AS efullname,
		f.dtypeId,dt.FullName AS dfullname,f.ktypeid,@kfullname AS kfullname,f.ktypeid2,@kfullname2 AS kfullname2,f.Comment,f.Comment AS discomment,
		f.explain,f.explain AS disexplain,f.EntryCode ,
		f.checke,
		ISNULL(E1.FullName,'') AS checkman,
	    ISNull(au.BillDetail,'') AS BillDetail,
	     ISNULL(ue.FullName,'') as updateename,
	    f.RedWord AS redword,
	    '' AS bfullname,
	    f.totalqty AS totalqty,
	    0 AS totalmoney,
		0 AS totalinmoney,
		f.ifcargo
		FROM dbo.FactIndex f
		LEFT JOIN dbo.FactDepotAllot inout ON inout.billNumberID=f.BillNumberId
		LEFT JOIN employee e1 ON E1.typeId=f.checke 
	    LEFT JOIN AuditingBill au	ON (au.billnumberid=f.billnumberid AND Au.BillIndexType = 7)
		LEFT JOIN dbo.SType  st ON st.TypeId=f.Stypeid
		LEFT JOIN employee et ON et.typeId=f.etypeid
		LEFT JOIN employee ue ON ue.typeId=f.updatee
		LEFT JOIN dbo.Department dt ON dt.typeid=f.dtypeId
		WHERE f.BillNumberId=@BillNumberId
END 
ELSE IF EXISTS (SELECT  TOP 1 1 FROM FactIndex WHERE BillNumberId=@BillNumberId AND BILLTYPE in(421,422))
/*如果期初实物未出入库走此分支*/
BEGIN
	--SELECT @ktypeid=ktypeid,@ktypeid2=ktypeid2 from dbo.FactIndex WHERE BillNumberId=@BillNumberId
	--SELECT @kfullname=fullname FROM dbo.Stock WHERE typeId=@ktypeid
	--SELECT @kfullname2=fullname FROM dbo.Stock WHERE typeId=@ktypeid2
	SELECT DISTINCT f.BillNumberId,f.BillType,f.BillDate,f.BillCode,f.Stypeid,st.FullName AS sfullname,f.etypeid,et.FullName AS efullname,
	f.dtypeId,dt.FullName AS dfullname,f.ktypeid,f.ktypeid2,f.Comment,f.Comment AS discomment,
	f.explain,f.explain AS disexplain,f.EntryCode ,
	f.checke,
	ISNULL(E1.FullName,'') AS checkman,
	ISNull(au.BillDetail,'') AS BillDetail,
	ISNULL(ue.FullName,'') as updateename,
	f.RedWord AS redword,
	'' AS bfullname,
	f.totalqty AS totalqty,
	0 AS totalmoney,
	0 AS totalinmoney
	FROM dbo.FactIndex f
	LEFT JOIN employee e1 ON E1.typeId=f.checke 
	LEFT JOIN dbo.SType  st ON st.TypeId=f.Stypeid
	LEFT JOIN employee et ON et.typeId=f.etypeid
	LEFT JOIN dbo.Department dt ON dt.typeid=f.dtypeId
	LEFT JOIN employee ue ON ue.typeId=f.updatee
	LEFT JOIN AuditingBill au	ON (au.billnumberid=f.billnumberid AND Au.BillIndexType = 7)
	WHERE f.BillNumberId=@BillNumberId
END 

--SELECT * FROM dbo.FactDepotInOut
--SELECT * FROM dbo.Stock
--SELECT * FROM dbo.FactIndex
--SELECT * FROM FactDepotAllot

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadOrderBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadOrderBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





/*
销售、采购调入订单明细detail
卢春 2010-07-21
*/
/*
修改：李灏龙
时间：2012年4月19日20:33:23
描述：由于多减了WaitQty字段的值，而WaitQty字段值为负数，导致最终待发数值不对
	  具体修改：zs001
*/
CREATE    PROCEDURE Web_LoadOrderBill
(
	@intBillNumberID        varchar(max),
	@loadcomplete			char(1),
	@chvOperatorID          varchar(50),
	@showServicePtype		char(1)='1',--是否显示服务类商品：0，不显示；1，显示
	@billtype				int=300,
	@oldBillType			INT=0		--调订单查询的单据
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''
DECLARE @SQL_ManKtype varchar(1000)
SET @SQL_ManKtype=''
-- 商品
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
	SET @SQL_Man = ' INNER JOIN #F_BaseGetManDetailPType FP ON a.PTypeID = FP.TypeID '
END

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man  = @SQL_Man+' INNER JOIN #F_BaseGetManDetailKType K ON (a.KtypeID=K.TypeID OR ISNULL(a.KtypeID,'''')='''') '
END
-- ******** 权限范围单独处理 - End ********
DECLARE @detailTable varchar(30)
SET @detailTable='OrderBill'
if @billtype=313
begin
	SET @detailTable='PT_Combin_OrderBillDetail'
end
DECLARE @SQL nvarchar(4000)
SET @SQL = '
	SELECT top 100 percent
			a.KTypeid,
			a.PTypeID,
			a.Qty,
			case when (a.Qty-'+CASE WHEN @billtype=301 THEN 'a.SaleOrderReachQty' ELSE 'a.ReachQty' END + ') < 0
			then 0 else (a.Qty-'+CASE WHEN @billtype=301 THEN 'a.SaleOrderReachQty' ELSE 'a.ReachQty' END +') end AS wwcQty,
			a.WaitQty AS waitqtydetail,
			a.ReachQty,
			a.SaleOrderReachQty,
			a.OrderID,
			a.BillNumberID,
			b.btypeid,
			b.dealbtypeid,p.isservice,
			CASE WHEN a.isgift=0 THEN '' '' ELSE ''赠品'' END AS isgift,
			CASE WHEN a.IsCombined = 0  THEN (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
			ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END AS itemname,
			a.comment,
			p.brandartypeid,
			brandarfullname = (select top 1 fullname from brandar_Commodity where typeid = p.brandartypeid),
			'
IF @billtype=313
BEGIN
	SET @SQL = @SQL + 'a.pindexid '
END
ELSE
BEGIN
	SET @SQL = @SQL + ''''' AS pindexid '
END
SET @SQL = @SQL + '
	FROM	'+@detailTable+' a 
	INNER JOIN Ptype p on a.ptypeid=p.typeid '
	
	SET @SQL = @SQL + 'INNER JOIN OrderIndex b ON a.billnumberid=b.billnumberid ' + @SQL_Man + '
	WHERE	a.BillNumberID IN (SELECT * FROM DBO.F_Split(''' + @intBillNumberID + ''','','') WHERE ISNULL(A,'''') <> '''')
			AND a.BillOver=0 '
			
--完成不引用			
IF (@oldBillType = 301 AND @loadcomplete = '1')
BEGIN
	SET @SQL = @SQL +' AND a.Qty > a.SaleOrderReachQty '
END
ELSE IF @loadcomplete = '1'
BEGIN
	SET @SQL = @SQL +' AND a.Qty > a.ReachQty '
END

--是否显示服务商品
IF @showServicePtype = '0'
	SET @SQL=@SQL+' AND p.isservice = 0 '
	
SET @SQL = @SQL +' ORDER BY a.ShowOrder ASC '

--PRINT(@SQL)
--EXEC (@SQL)

exec sp_executesql @SQL,N'@intBillNumberID varchar(max)',@intBillNumberID

IF @chvMPTypeID = '-99999' DROP TABLE #F_BaseGetManDetailPType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadOrderIndexFromBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadOrderIndexFromBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2007-3-8
	描述：采购入库单、销售出库单调订单
	EXEC Web_LoadOrderIndexFromBill
	2015-06-04 查询引用状态关联  暂估入库单 发出商品退货单
*/
CREATE       PROCEDURE Web_LoadOrderIndexFromBill
(
	@OperatorId		varchar(256),
	@BillType		int,
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@ReachDate		varchar(20),
	@SType			varchar(256),
	@KType			varchar(256),
	@BType			varchar(256),
	@EType			varchar(256),
	@BillCode		varchar(256),
	@PType			varchar(256),
	@Explain		varchar(1000),
	@Comment		varchar(1000),
	@OrderState		int,
	@IfAudit		int,
	@IsIni			int=0,					--1为期初单据，0为非期初单据
	@billproperty	int,						--单据属性：0为普通，1为OM，billtype == 300,2为委托，billtype == 301,2为受托
	@cid            VARCHAR(50) = '',
	@areatypeid		VARCHAR(max)='',		--地区（多选,不确定值的大小所以用max）
	@checkEtypeid	VARCHAR(max)='',		--制单人（多选,不确定值的大小所以用max）
	@loadcomplete	int,
	@oldBillType	INT=0					--调订单查询的单据
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID varchar(50)
SET @chvOperatorID = @OperatorId
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man varchar(1000)
SET @SQL_Man = ''

-- 往来单位
--IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
--BEGIN
	DECLARE @chvBTypeAll char(1)
	SET @chvBTypeAll = '0'
	SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConfigName = 'BtypeALL'
	
	SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)

	
	DECLARE @SQL_ManB varchar(100)
	SET @SQL_ManB = ' INNER JOIN #F_BaseGetManDetailBType B ON a.dealbtypeid = B.TypeID '
	
	IF @chvBTypeAll = '0'
	BEGIN
		IF @BillType = 300 
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND (B.TypeID LIKE ''00001%'') '
	
		IF @BillType = 301 
			SET @SQL_Man = @SQL_Man + @SQL_ManB + ' AND (B.TypeID LIKE ''00002%'') '
	END
	ELSE
	BEGIN
		--IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999'
			SET @SQL_Man = @SQL_Man + @SQL_ManB
	END
--END

-- 职员
	SELECT TypeID INTO #F_BaseGetManDetailEType FROM F_BaseGetManDetailEType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '

-- 商品
DECLARE @SQL_ManP varchar(100)
SET @SQL_ManP = ''
IF @chvMPTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailPType FROM F_BaseGetManDetailPType(@chvOperatorID)
	SET @SQL_ManP = ' INNER JOIN #F_BaseGetManDetailPType P ON detail.PTypeID = P.TypeID '
END

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
END

-- 分支机构
IF @chvMStypeid='-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailSType FROM F_BaseGetManDetailSType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

--部门
IF  @chvMDtypeid<>'00000'
BEGIN
	SELECT typeid INTO #F_BaseGetManDetailDType FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetaildType d ON a.dTypeID = d.TypeID '
END

DECLARE @tbName VARCHAR(100)
DECLARE @orderTable VARCHAR(30)
SET @orderTable=' orderbill '
IF @BillType = 300 
	SET @tbName='salebill'
ELSE IF @BillType=313
BEGIN
	SET @tbName='PT_Combin_SaleBill'
	SET @orderTable=' PT_Combin_OrderBillDetail '
END
ELSE 
	SET @tbName='buybill'


-- ******** 权限范围单独处理 - End ********

DECLARE @SQL varchar(3000)
SET @SQL = '
	SELECT	a.billtype,
			a.BillNumberID,
			a.BillDate,
			a.ReachDate,
			a.BillCode, 
			a.STypeID, 
			a.ETypeID,			
			a.dealbtypeid AS BTypeID,
			a.KTypeID,
			BI1.Qty,
			BI1.WaitQty,		
			BI1.ReachQty,
			a.Comment,
			a.Explain,
			a.CustomerTotal as customertotal,
			a.checktime,'
IF(@oldBillType=301 AND @BillType <> 313)
BEGIN
SET @SQL = @SQL+'
			CASE WHEN bi.billNumberId IS NULL THEN ''未采购''
				 WHEN bi.billNumberId IS NOT NULL AND BI1.SaleOrderReachQty<BI1.Qty THEN ''已采购未完成''
				 WHEN bi.billNumberId IS NOT NULL AND (BI1.SaleOrderReachQty>BI1.Qty OR BI1.SaleOrderReachQty=BI1.Qty) THEN ''已采购完成''
				 END  AS UseMark,'
END
ELSE IF (@oldBillType=301 AND @BillType=313)
BEGIN
SET @SQL = @SQL+'
			CASE WHEN BI1.SaleOrderReachQty = 0 THEN ''未采购''
				 WHEN BI1.SaleOrderReachQty <> 0 AND BI1.SaleOrderReachQty<BI1.Qty THEN ''已采购未完成''
				 WHEN bi.billNumberId IS NOT NULL AND (BI1.SaleOrderReachQty>BI1.Qty OR BI1.SaleOrderReachQty=BI1.Qty) THEN ''已采购完成''
				 END  AS UseMark,'
END
ELSE
BEGIN
SET @SQL = @SQL+'
			BI.BID,
			CASE WHEN	a.OrderState = 1 THEN ''已完成''
				 WHEN	BI1.ReachQty = 0 AND BI1.WaitQty = 0  THEN ''未引用''
				 ELSE ''已引用未完成'' END  AS UseMark,'
END
SET @SQL = @SQL+'
			ISNULL(a.VipCardId,-1) as vipcardid,
			(SELECT VipCardCode FROM dbo.nVipCardSign WHERE VipCardID = ISNULL(a.VipCardId,-1) ) as vipcardcode
	FROM	OrderIndex a ' + @SQL_Man
	
IF(@oldBillType=301 AND @BillType<>313)
BEGIN
	SET @SQL = @SQL + '
		LEFT JOIN (
			SELECT DISTINCT obb.billNumberId FROM OrderIndex oi--采购
			INNER JOIN dbo.OrderBill ob ON oi.billNumberId = ob.billNumberID
			INNER JOIN dbo.OrderBill obb ON ob.SaleOrderID=obb.OrderID
			INNER JOIN dbo.OrderIndex a ON obb.billNumberID = a.billNumberId--销售
			WHERE oi.BillType = 301 AND ob.SaleOrderID<>0
			AND a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
				AND a.Checked = 0 AND a.BillOver = 0
				AND a.BillType = ' + CAST(@BillType AS varchar(10))
	IF @IsIni=1
		SET @SQL+=' AND a.IsIni = 1'
		
	IF @billproperty = 2
		SET @SQL+=' AND a.billproperty = ' + CAST(@billproperty AS varchar(10))
					
	IF @BType <> '' SET @SQL = @SQL + ' AND a.dealbtypeid=''' + @BType + ''''
	IF @EType <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EType + ''''
	IF @KType <> '' SET @SQL = @SQL + ' AND a.KTypeID=''' + @KType + ''''
	IF @SType <> '' SET @SQL = @SQL + ' AND a.STypeID=''' + @SType + ''''
	IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
	IF @Explain <> '' SET @SQL = @SQL + ' AND a.Explain LIKE ''%' + @Explain + '%'''
	IF @Comment <> '' SET @SQL = @SQL + ' AND a.Comment LIKE ''%' + @Comment + '%'''
	IF @ReachDate <> '' SET @SQL = @SQL + ' AND a.ReachDate = ''' + @ReachDate + ''''
	IF @IfAudit = 1 SET @SQL = @SQL + ' AND a.IfAudit = 1'
	IF @areatypeid<>''
	BEGIN
		SET @SQL = @SQL+' AND a.dealbtypeid IN (SELECT typeid FROM btype WHERE areatypeid in ('''+REPLACE(@areatypeid,',',''',''')+'''))'
	END
	IF @checkEtypeid<>''
	BEGIN
		SET @SQL = @SQL+' AND a.CHECKE IN ('''+REPLACE(@checkEtypeid,',',''',''')+''')'
	END
	SET @SQL = @SQL + '
			) bi ON a.billNumberId = bi.billNumberId'
END
ELSE
BEGIN
	SET @SQL = @SQL + '
		INNER JOIN (
					SELECT a.BillNumberID,					
								max(a.BID) as BID
					FROM 
					(				
						SELECT distinct detail.BillNumberID,							
							   (BB.orderid) as BID
						FROM	'+@orderTable+' detail 
					LEFT JOIN 
					(
					SELECT bb.OrderID,bb.BillNumberID FROM  (SELECT OrderID,BillNumberId FROM '+@tbName+
					--调组合品订单不需要关联发出、暂估、委托、受托
					CASE @BillType WHEN 313 THEN '' ELSE 
						' UNION ALL '
						--引用状态增加发出商品出库,暂估入库关联
						+CASE @BillType 
						 WHEN 300 THEN 'SELECT OrderId,BillNumberId FROM SendBill ' 
						 ELSE          'SELECT OrderId,BillNumberId FROM AppraisalBill' END
						+' UNION ALL '
						+CASE @BillType 
						 WHEN 300 THEN 'SELECT OrderId,BillNumberId FROM commissionbill where [Type]=140 ' 
						 ELSE          'SELECT OrderId,BillNumberId FROM commissionbill where [Type]=144 ' END
					 END+
					'
					) AS bb  INNER JOIN BillIndex bi ON bb.billnumberid=bi.billnumberid and bi.redword=0--排除红冲单据
					)bb ON detail.OrderID=bb.orderid
					' + @SQL_ManP + ''
	--983需求,带商品查询时,需查询未中止,且数量未完成的,已完成不引入
	IF @PType <> '' AND @loadcomplete=1
	BEGIN
		SET @SQL = @SQL + ' WHERE detail.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where ptypeid = ''' + @PType + '''
					AND BillOver=0 '
		IF @oldBillType = 301
			SET @SQL = @SQL + ' AND SaleOrderReachQty < QTY ) '
		ELSE
			SET @SQL = @SQL + ' AND ReachQty < QTY ) '
	END
	--未勾选已完成不引入,则不判断完成数量
	ELSE IF @PType <> '' AND @loadcomplete=0
	BEGIN
		SET @SQL = @SQL + ' WHERE detail.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where ptypeid = ''' + @PType + '''
					AND BillOver=0)'
	END
	ELSE IF ISNULL(@PType,'')='' AND  @loadcomplete=1
	BEGIN 
		SET @SQL = @SQL + ' WHERE detail.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where 
					 BillOver=0 '
		IF @oldBillType = 301
			SET @SQL = @SQL + ' AND SaleOrderReachQty < QTY ) '
		ELSE
			SET @SQL = @SQL + ' AND ReachQty < QTY ) '
	END 
	ELSE IF ISNULL(@PType,'')='' AND  @loadcomplete=0
	BEGIN 
		SET @SQL = @SQL + ' WHERE detail.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where 
					BillOver=0 )'
	END 
	
	SET @SQL = @SQL + '
				)a GROUP BY A.billNumberID) bi ON A.billNumberId=BI.billNumberID'

END

DECLARE @SQL1 VARCHAR(MAX)
CREATE TABLE #tempqty
(
	billnumberid			BIGINT,
	WaitQty					NUMERIC(24,10),
	Qty						NUMERIC(24,10),
	ReachQty				NUMERIC(24,10),
	SaleOrderReachQty		NUMERIC(24,10)
)

SET @SQL1 = 'INSERT INTO #tempqty( billnumberid ,WaitQty ,Qty ,ReachQty ,SaleOrderReachQty)
				SELECT B.billNumberID,
				sum(b.WaitQty) AS WaitQty,
							sum(b.Qty) AS Qty,
							sum(b.ReachQty) AS ReachQty'
IF(@oldBillType=301)
	SET @SQL1 = @SQL1 + ',sum(b.SaleOrderReachQty) AS SaleOrderReachQty'
ELSE
	SET @SQL1 = @SQL1 + ',0 AS SaleOrderReachQty'

	
SET @SQL1 = @SQL1 + ' FROM(								
							SELECT detail.BillNumberID,
							CASE WHEN detail.WaitQty > detail.Qty THEN detail.Qty ELSE detail.WaitQty END AS WaitQty,
							(detail.Qty) AS Qty,
							CASE WHEN detail.ReachQty > detail.Qty THEN detail.Qty ELSE detail.ReachQty END AS ReachQty
					'
IF(@oldBillType=301)
	SET @SQL1 = @SQL1 + ',CASE WHEN detail.SaleOrderReachQty > detail.Qty THEN detail.Qty ELSE detail.SaleOrderReachQty END AS SaleOrderReachQty '
ELSE
	SET @SQL1 = @SQL1 + ',0 AS SaleOrderReachQty'

SET @SQL1 = @SQL1 + '
					FROM	'+@orderTable+' detail 
					INNER JOIN orderindex a ON a.billnumberid = detail.billnumberid
					WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			AND a.Checked = 0 AND a.BillOver = 0
			AND a.BillType = ' + CAST(@BillType AS varchar(10))
				

IF @IsIni=1
	SET @SQL1+=' AND a.IsIni = 1'

IF @cid <> '' and @oldBillType<>301
	SET @SQL1 = @SQL1 + ' AND a.cid = ''' + @cid + ''''
	
IF @billproperty = 2
	SET @SQL1+=' AND a.billproperty = ' + CAST(@billproperty AS varchar(10))		

IF @BType <> '' SET @SQL1 = @SQL1 + ' AND a.dealbtypeid=''' + @BType + ''''
IF @EType <> '' SET @SQL1 = @SQL1 + ' AND a.ETypeID=''' + @EType + ''''
IF @KType <> '' SET @SQL1 = @SQL1 + ' AND a.KTypeID=''' + @KType + ''''
IF @SType <> '' SET @SQL1 = @SQL1 + ' AND a.STypeID=''' + @SType + ''''
IF @BillCode <> '' SET @SQL1 = @SQL1 + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @Explain <> '' SET @SQL1 = @SQL1 + ' AND a.Explain LIKE ''%' + @Explain + '%'''
IF @Comment <> '' SET @SQL1 = @SQL1 + ' AND a.Comment LIKE ''%' + @Comment + '%'''
IF @ReachDate <> '' SET @SQL1 = @SQL1 + ' AND a.ReachDate = ''' + @ReachDate + ''''
IF @IfAudit = 1 SET @SQL1 = @SQL1 + ' AND a.IfAudit = 1'
IF @areatypeid<>''
BEGIN
	SET @SQL1 = @SQL1+' AND a.dealbtypeid IN (SELECT typeid FROM btype WHERE areatypeid in ('''+REPLACE(@areatypeid,',',''',''')+'''))'
END
IF @checkEtypeid<>''
BEGIN
	SET @SQL1 = @SQL1+' AND a.CHECKE IN ('''+REPLACE(@checkEtypeid,',',''',''')+''')'
END		

SET @SQL1 += ' 
				) b GROUP BY B.billNumberID '		
--print(@sql1)	
EXEC (@sql1)
--SELECT * FROM #tempqty

SET @SQL = @SQL + ' INNER JOIN #tempqty BI1 ON a.billnumberid=BI1.billnumberid 
	
	WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			AND a.Checked = 0 AND a.BillOver = 0
			AND a.BillType = ' + CAST(@BillType AS varchar(10))
			
/*
SET @SQL = @SQL + '
				INNER JOIN (								
					SELECT B.billNumberID,
				sum(b.WaitQty) AS WaitQty,
							sum(b.Qty) AS Qty,
							sum(b.ReachQty) AS ReachQty'
IF(@oldBillType=301)
	SET @SQL = @SQL + ',sum(b.SaleOrderReachQty) AS SaleOrderReachQty'
	
SET @SQL = @SQL + ' FROM(								
					SELECT detail.BillNumberID,
							(detail.WaitQty) AS WaitQty,
							(detail.Qty) AS Qty,
							(detail.ReachQty) AS ReachQty'
IF(@oldBillType=301)
	SET @SQL = @SQL + ',(detail.SaleOrderReachQty) AS SaleOrderReachQty'
	
SET @SQL = @SQL + '
					FROM	'+@orderTable+' detail
				) b GROUP BY B.billNumberID) BI1 ON a.billnumberid=BI1.billnumberid 
	
	WHERE	a.BillDate >= ''' + @StartDate + ''' AND a.BillDate <= ''' + @EndDate + '''
			AND a.Checked = 0 AND a.BillOver = 0
			AND a.BillType = ' + CAST(@BillType AS varchar(10))
	*/
			
IF @IsIni=1
	SET @SQL+=' AND a.IsIni = 1'

IF @cid <> '' and @oldBillType<>301
	SET @SQL = @SQL + ' AND a.cid = ''' + @cid + ''''
	
IF @billproperty = 2
	SET @SQL+=' AND a.billproperty = ' + CAST(@billproperty AS varchar(10))

--订单状态过滤
IF @oldBillType=301  AND @BillType <> 313
BEGIN
	SET @SQL+= CASE @OrderState WHEN 1 THEN ' AND bi.billNumberId IS NOT NULL AND BI1.SaleOrderReachQty<BI1.Qty' --已采购未完成订单
								WHEN 2 THEN ' AND bi.billNumberId IS NOT NULL AND (BI1.SaleOrderReachQty>BI1.Qty OR BI1.SaleOrderReachQty=BI1.Qty) '  --已采购完成订单
								WHEN 3 THEN ' AND (bi.billNumberId IS NULL OR (bi.billNumberId IS NOT NULL AND BI1.SaleOrderReachQty<BI1.Qty))'  --未完成采购订单
								WHEN 4 THEN ' AND bi.billNumberId IS NULL'--未采购订单
								ELSE '' END --全部订单 								
	-- 如果为组合品，则不根据OrderIndex的OrderState	值来判断				
	IF @BillType = 301 AND @OrderState <> 0
		SET @SQL+=' AND a.OrderState <> 1 '
END
ELSE IF @oldBillType=301 AND @BillType = 313
BEGIN
	SET @SQL+= CASE @OrderState WHEN 1 THEN ' AND BI1.SaleOrderReachQty <> 0 AND BI1.SaleOrderReachQty<BI1.Qty ' --已采购未完成订单
								WHEN 2 THEN ' AND (BI1.SaleOrderReachQty > BI1.Qty OR BI1.SaleOrderReachQty=BI1.Qty) '  --已采购完成订单
								WHEN 3 THEN ' AND (BI1.SaleOrderReachQty = 0 OR BI1.SaleOrderReachQty < BI1.Qty )'  --未完成采购订单
								WHEN 4 THEN ' AND BI1.SaleOrderReachQty = 0'--未采购订单
								ELSE '' END --全部订单 								
END
ELSE
BEGIN		
	SET @SQL+= CASE @OrderState WHEN 1 THEN ' AND (a.OrderState = 0 AND (BI.BID IS NOT NULL OR BI1.ReachQty<>0))' --未完成订单
								WHEN 2 THEN ' AND a.OrderState = 1'  --已完成订单
								WHEN 3 THEN ' AND a.OrderState=0'--未完成订单
								WHEN 4 THEN ' AND BI1.ReachQty=0 AND BI1.WaitQty=0 '--未引用订单
								ELSE ' AND (a.OrderState = 1 OR a.OrderState = 0)' 
								END
END

IF @BType <> '' SET @SQL = @SQL + ' AND a.dealbtypeid=''' + @BType + ''''
IF @EType <> '' SET @SQL = @SQL + ' AND a.ETypeID=''' + @EType + ''''
IF @KType <> '' SET @SQL = @SQL + ' AND a.KTypeID=''' + @KType + ''''
IF @SType <> '' SET @SQL = @SQL + ' AND a.STypeID=''' + @SType + ''''
IF @BillCode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @BillCode + '%'''
IF @Explain <> '' SET @SQL = @SQL + ' AND a.Explain LIKE ''%' + @Explain + '%'''
IF @Comment <> '' SET @SQL = @SQL + ' AND a.Comment LIKE ''%' + @Comment + '%'''
IF @ReachDate <> '' SET @SQL = @SQL + ' AND a.ReachDate = ''' + @ReachDate + ''''
IF @IfAudit = 1 SET @SQL = @SQL + ' AND a.IfAudit = 1'
IF @areatypeid<>''
BEGIN
	SET @SQL = @SQL+' AND a.dealbtypeid IN (SELECT typeid FROM btype WHERE areatypeid in ('''+REPLACE(@areatypeid,',',''',''')+'''))'
END
IF @checkEtypeid<>''
BEGIN
	SET @SQL = @SQL+' AND a.CHECKE IN ('''+REPLACE(@checkEtypeid,',',''',''')+''')'
END

IF @oldBillType=301
BEGIN
	IF @PType <> '' AND @loadcomplete=1
	BEGIN
		SET @SQL = @SQL + ' AND a.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where ptypeid = ''' + @PType + ''' AND BillOver = 0 AND ReachQty < QTY ) '
	END
	--未勾选已完成不引入,则不判断完成数量
	ELSE IF @PType <> '' AND @loadcomplete=0
	BEGIN
		SET @SQL = @SQL + ' AND a.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where ptypeid = ''' + @PType + ''' AND BillOver=0) '
	END
	ELSE IF ISNULL(@PType,'')='' AND @loadcomplete=1
	BEGIN 
		SET @SQL = @SQL + ' AND a.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where  BillOver = 0 AND ReachQty <= QTY ) '

	END 
	ELSE IF ISNULL(@PType,'')='' AND @loadcomplete=0
	BEGIN 
		SET @SQL = @SQL + ' AND a.billnumberid in (SELECT billnumberid from ' + @orderTable + ' where  BillOver=0) '
	END 
END

SET @SQL = @SQL + ' ORDER BY a.BillDate DESC,a.BillCode'

--PRINT(@SQL)
EXEC (@SQL)
IF @chvMBTypeID = '-99999' OR @chvMBTypeID2 = '-99999' DROP TABLE #F_BaseGetManDetailBType
IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
DROP TABLE #F_BaseGetManDetailEType
IF @chvMPTypeID = '-99999' DROP TABLE #F_BaseGetManDetailPType
IF @chvMSTypeID = '-99999' DROP TABLE #F_BaseGetManDetailSType
IF @chvMDtypeid = '-99999' DROP TABLE #F_BaseGetManDetailDType

DROP TABLE #tempqty

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadProduceModel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_LoadProduceModel
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
exec Web_LoadProduceModel @TempName='a',@PtypeId='',@OperatorID='00001'
生产拆装单调生产模板
WangWei 2011-02-12
*/
CREATE    PROCEDURE Web_LoadProduceModel
(
	@TempName		VARCHAR(2000),--模板名称
	@PtypeId		VARCHAR(MAX),--商品ID
	@OperatorID		VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------
CREATE TABLE #PtypeList(TypeId VARCHAR(100))

INSERT INTO #PtypeList(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PtypeId,1,@OperatorID)

SELECT	DISTINCT	
		mi.ProduceModelName,
		mi.ProduceModelID as billnumberid,
		mi.ProduceModelID,
		mi.PtypeID,
		mi.Comment,
		null as num,
		Bp.Unit1,
		Bp.Unit2,
		Bp.UnitRate1,
		Bp.UnitRate2,
		(SELECT TOP 1 FullName FROM PType_Units WHERE UnitsId=Bp.baseUnitId) AS unit,
        Bp.baseUnitId AS unitid,
        CASE WHEN Bp.UnitsType=0 THEN (SELECT TOP 1 FullName FROM PType_Units WHERE UnitsId=Bp.baseUnitId)
        ELSE (SELECT TOP 1 FullName FROM PType_Units WHERE UnitsId=Bp.AssistantUnitId) END AS nunit,
        CASE WHEN Bp.UnitsType=0 THEN Bp.baseUnitId ELSE Bp.AssistantUnitId END AS nunitid,
        (SELECT TOP 1 rate FROM PType_Units_ext WHERE  IsDefaultUnit=1 AND PtypeID=Bp.typeId) AS rate,
        CASE WHEN Bp.UnitsType=0 THEN 0 ELSE  (SELECT TOP 1 rate FROM PType_Units_ext WHERE  RateType=1 AND PtypeID=Bp.typeId) END AS unitrate
FROM	ProduceModelIndex mi
INNER JOIN ProduceModel m ON mi.ProduceModelID=m.ProduceModelID
INNER JOIN #PtypeList p ON mi.PtypeID=p.TypeId
INNER JOIN PType Bp ON Bp.typeId = p.TypeId
WHERE	mi.ProduceModelName like '%'+@TempName+'%'
Order by mi.ProduceModelName
 
DROP TABLE #PtypeList

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadProduceModePtypeList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadProduceModePtypeList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吕文祺
	日期：2014-10-24
	描述：导入生产模板商品数据
	
*/


CREATE PROCEDURE Web_LoadProduceModePtypeList
(
	@OperatorId		VARCHAR(100),
	@nBillIds		VARCHAR(8000)='',
	@chvSTypeid     varchar(500) = '00001', -- 分支机构
	@KTypeId 		varchar(500) = ''-- 查询的仓库id
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @BillIndexTable VARCHAR(100),
		@MxTableName	VARCHAR(100),
		@SQL 			VARCHAR(8000)
		
CREATE TABLE #SplitBillNumberId
(
	BillNumberId		NUMERIC(18,0)
)	   
INSERT INTO #SplitBillNumberId(BillNumberId) SELECT A FROM dbo.f_split(@nBillIds,',') WHERE ISNULL(A,'')<>''

CREATE TABLE #BillIndex
(
	BillNumberId		NUMERIC(18,0)
)		

--分支机构物价信息
DECLARE @PriceType varchar(5)
SELECT @PriceType=PriceType FROM SType WHERE TypeId=@chvSTypeid


if @chvSTypeid = '' OR @chvSTypeid=null OR len(isnull(@chvSTypeid,''))=0
BEGIN
set @PriceType='0'
set @chvSTypeid=''
END


DECLARE @tempSQL nvarchar(max)

CREATE TABLE #tempQty
(
	PtypeId				varchar(50),
	QTY					 NUMERIC(24, 10) 
);

CREATE TABLE #temp_Qty
(
	PtypeId				varchar(50),
	QTY					 NUMERIC(24, 10) ,
);


CREATE TABLE #temp_LendQty
(
	PtypeId				varchar(50),
	LendQty				 NUMERIC(24, 10)  --借进/借出数量
);


SET @tempSQL = '
		INSERT INTO #temp_Qty(PtypeId,QTY)
		SELECT	x.typeid,
				SUM(ISNULL(aq.qty,0)) AS qty
		FROM	ptype x
		LEFT JOIN GoodsStocks_Qty aq ON aq.PTypeID LIKE x.TypeID+''%'' 
										AND aq.KTypeID = '''+ @KTypeId +''''+'
		
		GROUP BY x.typeid';

	EXEC sp_executesql @tempSQL;
	




	--获取借进/借出数量
	SET @tempSQL = '
		INSERT INTO #temp_LendQty(PtypeId,LendQty)
			SELECT t.typeid,
				SUM(ISNULL(v.QTY,0)) AS FactQty -- 借进/借出 ( 合计值 )
		FROM ptype t
		LEFT JOIN GoodsLend v ON v.PTypeID like t.typeid+''%'' 
									AND v.KTypeID = ''' + @KTypeId + '''
		
		GROUP BY t.typeid
	';
			
	EXEC sp_executesql @tempSQL;





-------------------------------------主表-------------------------------------
SET @BillIndexTable = 'ProduceModelIndex'



SET @SQL = 'INSERT INTO #BillIndex
			SELECT	B.ProduceModelID
			FROM	'+@BillIndexTable+' B,
					#SplitBillNumberId S
			WHERE	B.ProduceModelID = S.BillNumberId
					 '

	

		
SET @SQL = @SQL + '					
			ORDER BY B.ProduceModelID DESC '

--PRINT(@SQL)
EXEC(@SQL)



---------------------------------------明细表-------------------------------------
SET @MxTableName = 'ProduceModel'

DECLARE @Ser varchar(max)



SET @SQL = 'SELECT	bc.typeid as brandartypeid,
					bc.usercode as brandarusercode,
					bc.fullname as brandarfullname,
					NULL AS Serial,
					M.PTypeId,
					CASE WHEN q.QTY IS NULL THEN 0 ELSE q.QTY END AS ZMQTY,
		            ISNULL(q.Qty,0) + ISNULL(LendQty,0) AS FactQty,	-- 实际数量= 库存量+借出/借进
					P.*,
					P.Unit1 AS unitone,
					P.Unit2 As unittwo,
					M.Qty,
					M.Qty as oldqty,
				    (dbo.F_GetAllEntrycode(M.Ptypeid,p.SaleUnitId,2)) AS salemunitcode,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname1,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname2,
					(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid)) as auxfullname3,
					(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate1,
					(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate2,
					(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=M.ptypeid) as auxrate3,
					(select isservice from ptype where typeid = m.PTypeID) as isservice,
				    (select referprice from PType_Price where PTypeID = m.PTypeID AND P.SaleUnitid = UnitID) as referprice,
				    M.ID,
				    M.ProduceModelID,
					 '
					 



SET @SQL = @SQL + ' 
                    null as msaleprice,
                    null as curmdiscountprice,
                    null as nsaleprice,
                    null as curmsaleprice,
                    null as price,
                    M.qty as mqty,
                    0 as nqty,
                    null as ntotal,
                    null as nsaletotal,
                    ''1'' as Discount,
                    ''0'' as tax,
                    null as total,
                    null as discountprice,
                    null as discounttotal,
                    null as taxprice,
                    null as taxtotal,
                    (select rate from ptype_units_ext where ptypeid=p.typeid and unitsid=p.SaleUnitId) as munitRate,
                    (select rate from ptype_units_ext where ptypeid=p.typeid and unitsid=p.AssistantUnitId) as UnitRate,
                    null as curmtaxprice,
					null as ntaxmoney,
					null as ntaxtotal,
					null as taxmoney,
					null as NTaxPrice,
					null as NDiscountPrice,
					null as MDiscountPrice,
					null as MTaxPrice,
					p.SaleUnitId as MUnitID,
					p.AssistantUnitId as NUnitID,
					p.baseunitid as UnitID,
                    (select fullname from PType_Units where UnitsId=p.baseunitid) AS unit,
					(select fullname from PType_Units where UnitsId=p.SaleUnitId) AS munit,
					(select fullname from PType_Units where UnitsId=p.AssistantUnitId) AS nunit,	
					pt.ifusegoodsnum,
					'''+@PriceType+''' as PriceType,
					(select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=pt.TypeID  AND P.SaleUnitid = UnitID  and STYPEID='''+@chvSTypeid+''') AS SReferPrice,
	 	            (select ISNULL(ReferPrice,0) from PType_Price where PTypeID=pt.TypeID AND P.SaleUnitid = UnitID  )  AS PReferPrice,
                    '                    


SET @SQL = @SQL + ' pt.unitstype, '						

SET @SQL = @SQL + '
                     
                    pt.customitemid,
					pt.customitemfrom,
					pt.customitemname,
					pt.customitemrefid	        
					
                  '

		


					




SET @SQL = @SQL + '
			FROM	'+@MxTableName+'  M
			INNER JOIN #BillIndex B ON B.BillNumberId = M.ProduceModelID
			INNER JOIN F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') P ON M.PTypeId = P.TypeId
			LEFT JOIN brandar_Commodity bc ON bc.TypeId = p.BrandartypeId
			left join #temp_Qty q on M.ptypeid = q.ptypeid 
	        left join #temp_LendQty lq on M.ptypeid = lq.ptypeid
			
			 ' 

SET @SQL = @SQL + ' INNER JOIN dbo.PType pt ON M.PTypeID = pt.TypeID '


			
SET @SQL = @SQL + '					
			WHERE	1=1			
			'
			




	


SET @SQL=@SQL+' ORDER BY M.ProduceModelID ASC '


PRINT(@SQL)
EXEC(@SQL)			
			

DROP TABLE #BillIndex,#SplitBillNumberId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadPtypeFromBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadPtypeFromBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*	
横看成岭侧成峰20160721

修改人：田小波
修改时间：2016-11-15
修改原因：S 重复定义
*/
CREATE       PROCEDURE Web_LoadPtypeFromBill
(
	@OperatorId		VARCHAR(256),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@frombilltype	VARCHAR(10),		--单据类型
	@frombillcode	VARCHAR(50),
	@SType			VARCHAR(256),
	@KType			VARCHAR(256),
	@EType			VARCHAR(256),
	@Explain		VARCHAR(1000),
	@Comment		VARCHAR(1000),
	@Ifcomplete		INT,				--入库完成是否引入 1为勾选 0为不勾选
	@checke			VARCHAR(MAX)='',	--制单人		
	@ptypeid		VARCHAR(MAX)='',	--商品ID
	@flag			VARCHAR(10),			--出入库单据标记  e.出库单  i.入库单
	@billstate		INT,					--单据引用状态 1=已引用未完成单据,4=未引用单据,3=未完成单据,2=完成单据,0=全部单据
	@btypeid         varchar(1000)    --往来单位
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID VARCHAR(50)
SET @chvOperatorID = @OperatorId
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID VARCHAR(50), @chvMBTypeID VARCHAR(50), @chvMBTypeID2 VARCHAR(50), @chvMETypeID VARCHAR(50), @chvMKTypeID VARCHAR(50), @chvMPTypeID VARCHAR(50), @chvMExpense VARCHAR(50), @chvMIncome VARCHAR(50), @chvMCapital VARCHAR(50), @chvMDtypeid VARCHAR(50), @chvMStypeid VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man VARCHAR(1000)
SET @SQL_Man = ''

-- 经手人
SELECT TypeID INTO #F_BaseGetManDetailEType FROM dbo.F_GetAllManagerBaseByTypeId(@EType,3,@chvOperatorID,@SType)
SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailEType E ON a.ETypeID = E.TypeID '

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	IF @flag = 'i'	--入库单据类型
	BEGIN
		IF @frombilltype IN (16,17,21,160,161,187,188,173,174,175)
		BEGIN
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType sK ON a.KTypeID2 = sK.TypeID '
		END
		ELSE
		BEGIN
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType sK ON a.KTypeID = sK.TypeID '
		END
	END
	ELSE
	BEGIN
		IF @frombilltype IN (16,17,21,160,161,187,188,173,174,175)
		BEGIN
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType sK ON a.KTypeID2 = sK.TypeID '
		END
		ELSE
		BEGIN
			SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType sK ON a.KTypeID = sK.TypeID '
		END
	END
END

-- 分支机构
IF @chvMStypeid='-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailSType FROM F_BaseGetManDetailSType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType st ON a.sTypeID = st.TypeID '--原来 S重复定义
END

--制单人
CREATE TABLE #GetManECheckeTypeId(TypeId	varchar(100))
IF @checke <> ''
BEGIN
	INSERT INTO #GetManECheckeTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@checke,3,@OperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #GetManECheckeTypeId che ON a.checke like '''' + che.TypeId + ''%''';
END

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @ptypeid <> ''
BEGIN
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@chvOperatorID)	
END

IF @frombilltype NOT IN('16','173','174','187','188','17','21','9','14')
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailBType FROM F_BaseGetManDetailBType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailBType Bm ON a.dealbtypeid = Bm.TypeID ';
END

--构造主表明细表数据
DECLARE @DBNameIndex	VARCHAR(500),
		@detailTable	VARCHAR(500)

SELECT @detailTable = detailTable FROM dbo.BillName WHERE billtype = @frombilltype

IF @frombilltype in ('71','72','87','88')
	SET @DbNameIndex='LendIndex'
ELSE IF @frombilltype IN ('327','328','329')
	SET @DbNameIndex='PosAllotApplyBillIndex'
ELSE	
	SET @DbNameIndex='BillIndex'
	

-- ******** 权限范围单独处理 - End ********
DECLARE @SQL			VARCHAR(MAX),
		@SQLPType		VARCHAR(MAX),
		@SQLWXPType		VARCHAR(MAX)='',
		@SQLPTypeDrop	VARCHAR(MAX)

--筛选商品		
SET @SQLPType = 'CREATE TABLE #detailTable(BillNumberId NUMERIC(18,0))
				 INSERT INTO #detailTable(BillNumberId) SELECT BillNumberId FROM '+@detailTable+' WHERE ptypeid IN (SELECT typeid FROM #GetManPTypeId) '
				 
--处理维修单和上门维修单
IF 	@frombilltype IN (166,172)
BEGIN
	SET @SQLWXPType=' AND InOrOut=''O'' AND wxProperty=0 '
END
				 
SET @SQLPTypeDrop = ' DROP TABLE #detailTable'				 
		
SET @SQL = 'SELECT	BillDate,
					BillCode,
					s.FullName as sfullname, 
					a.ktypeid,
					k.FullName as kfullname,
					ee.FullName as efullname,
					a.Stypeid, '
					
--门店配送单据					
IF @frombilltype IN ('327','328','329')						
	SET @SQL += '	a.applyetypeid,
					'''' as DealBTypeID,
					'''' as dealbname,'
ELSE
	SET @SQL += '	a.etypeid,
					a.DealBTypeID,
					b.fullname as dealbname,'	

SET @SQL += '		a.BillNumberId,					
					a.Comment,
					a.explain,					
					a.billtype
			FROM	'+@DBNameIndex+' a
			LEFT JOIN dbo.SType s ON a.Stypeid=s.TypeId '
			
--门店配送单据没有往来单位
IF @frombilltype NOT IN ('327','328','329')			
BEGIN
	SET @SQL += ' LEFT Join btype b on b.typeid = a.dealbtypeid '
END	
			
SET @SQL+='	inner join  (
							select	distinct  
									billnumberid 
							from	'+@detailTable+' d 
							inner join ptype p on d.ptypeid =p.typeid and  p.isservice=0 
			) dt on a.billnumberid =dt.billnumberid and a.billtype =' + @frombilltype+' '
	

IF @flag = 'i'	
BEGIN
	IF @frombilltype IN (161,16,17,21,173,188,174)	--销售换货单、采购换货单、生产拆装单等双仓库单据
		SET @SQL = @SQL + ' LEFT JOIN dbo.Stock k ON a.ktypeid2=k.TypeId '
	ELSE
		SET @SQL = @SQL + ' LEFT JOIN dbo.Stock k ON a.ktypeid=k.TypeId '
END
ELSE
BEGIN
	IF @frombilltype IN (160)	--销售换货单、采购换货单、生产拆装单等双仓库单据
		SET @SQL = @SQL + ' LEFT JOIN dbo.Stock k ON a.ktypeid2=k.TypeId '
	ELSE
		SET @SQL = @SQL + ' LEFT JOIN dbo.Stock k ON a.ktypeid=k.TypeId '
END	
IF @frombilltype IN (166,172)
BEGIN
	IF @frombilltype =166
	BEGIN
		SET @SQL = @SQL + ' INNER JOIN (
			   SELECT BillNumberId FROM wx_bill_self W where W.InOrOut=''O'' AND W.wxProperty=0 GROUP BY w.BillNumberId
			)ww ON ww.BillNumberId = a.BillNumberId '
	END
	IF @frombilltype =172
	BEGIN
		SET @SQL = @SQL + ' INNER JOIN (
			   SELECT BillNumberId FROM wx_bill_goto W where W.InOrOut=''O'' AND W.wxProperty=0 GROUP BY w.BillNumberId
			)ww ON ww.BillNumberId = a.BillNumberId '
	END
END

--门店配送单据					
IF @frombilltype IN ('327','328','329')	
	SET @SQL = @SQL + 'LEFT JOIN dbo.employee ee ON a.applyetypeid=ee.TypeId '
ELSE
	SET @SQL = @SQL + 'LEFT JOIN dbo.employee ee ON a.etypeid=ee.TypeId '+@SQL_Man

SET @SQL = @SQL + 'WHERE	a.redword = 0	
							AND a.IfCheck = ''t''
							AND a.BillDate >= ''' + @StartDate + ''' 
							AND a.BillDate <= ''' + @EndDate + '''
							AND a.IsIni = 0
		                    AND a.BillType = ' + @frombilltype

IF @KType <> '' 
BEGIN
	IF @flag = 'i'
	BEGIN
		IF @frombilltype IN (161,16,17,21,173,188,174)
			SET @SQL = @SQL + ' AND a.KTypeID2=''' + @KType + ''''
		ELSE IF @frombilltype IN (327,328,329)
			SET @SQL = @SQL + ' AND a.InKTypeID=''' + @KType + ''''
		ELSE
			SET @SQL = @SQL + ' AND a.KTypeID=''' + @KType + ''''
		END
	ELSE
	BEGIN
		IF @frombilltype IN (160)
			SET @SQL = @SQL + ' AND a.KTypeID2=''' + @KType + ''''
		ELSE IF @frombilltype IN (327,328,329)
			SET @SQL = @SQL + ' AND a.KTypeID=''' + @KType + ''''
		ELSE
			SET @SQL = @SQL + ' AND a.KTypeID=''' + @KType + ''''
	END
END

IF @frombilltype IN(9,14)
BEGIN
 
   SET @SQL = @SQL + ' AND a.ifwx=0 '

END

IF @Ifcomplete = 1 and @billstate <> 2 and @billstate <> 0	 --出入库完成是否引入 1为勾选
BEGIN
	IF @flag = 'i'
	BEGIN
		
		SET @SQL = @SQL + ' AND a.InFactState <> 2 '
	END
	ELSE
	BEGIN
		
		SET @SQL = @SQL + ' AND a.OutFactState <> 2 '
	END
END

IF @frombilltype in ('34','11')
BEGIN
  SET @SQL = @SQL + ' AND a.islend <> 1 '
END

--单据引用状态 1=已引用未完成单据,4=未引用单据,3=未完成单据,2=完成单据,0=全部单据
IF @billstate<>0
BEGIN
	declare @refstatefield varchar(50),
			@billstatefield varchar(50)
	if @flag = 'i'--入库
	begin
		set @refstatefield='a.InFactRefState'
		set @billstatefield ='a.InFactState'
	end
	else --出库
	begin
		set @refstatefield='a.OutFactRefState'
		set @billstatefield ='a.OutFactState'
	end
	
	if @billstate=1
		set @SQL=@SQL+' and '+@refstatefield+'=1 and '+@billstatefield+'=1 '
	else if @billstate=2
		set @SQL=@SQL+' and '+@billstatefield+' = 2 '
	else if @billstate=3
		 set @SQL=@SQL+' and '+@billstatefield+' <> 2 '
	else if @billstate=4
		set @SQL=@SQL+' and '+@refstatefield+' = 0 '
END

IF @SType <> '' SET @SQL = @SQL + ' AND a.STypeID=''' + @SType + ''''
IF @frombillcode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @frombillcode + '%'''
IF @Explain <> '' SET @SQL = @SQL + ' AND a.Explain LIKE ''%' + @Explain + '%'''
IF @Comment <> '' SET @SQL = @SQL + ' AND a.Comment LIKE ''%' + @Comment + '%'''

IF @btypeid <> ''
BEGIN
SET @sql = @sql + 'AND a.dealBtypeid = ''' + @btypeid + '''';
END

IF @PTypeId <> ''
BEGIN
	SET @SQL = @SQL + ' AND a.BillNumberId IN (SELECT BillNumberId FROM #detailTable)'
	--PRINT(@SQLPType +@SQLWXPType + @SQL + @SQLPTypeDrop)
	EXEC (@SQLPType + @SQLWXPType + @SQL + @SQLPTypeDrop)
END
ELSE
BEGIN
	--PRINT(@SQL)
	EXEC (@SQL)
END




IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMSTypeID = '-99999' DROP TABLE #F_BaseGetManDetailSType

DROP TABLE #F_BaseGetManDetailEType,#GetManECheckeTypeId,#GetManPTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadPtypeFromBillIndex_Qc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadPtypeFromBillIndex_Qc]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*	
	作者：谢吉康
	日期：2016-09-13
	描述：出入库单据调期初未实物出入库单据
*/
CREATE       PROCEDURE Web_LoadPtypeFromBillIndex_Qc
(
	@OperatorId		VARCHAR(256),
	@StartDate		VARCHAR(20),
	@EndDate		VARCHAR(20),
	@frombilltype	VARCHAR(10),		--单据类型
	@frombillcode	VARCHAR(50),
	@SType			VARCHAR(256),
	@KType			VARCHAR(256),
	@EType			VARCHAR(256),
	@Explain		VARCHAR(1000),
	@Comment		VARCHAR(1000),
	@Ifcomplete		INT,				--入库完成是否引入 1为勾选 0为不勾选
	@checke			VARCHAR(MAX)='',	--制单人		
	@ptypeid		VARCHAR(MAX)='',	--商品ID
	@flag			VARCHAR(10),			--出入库单据标记  e.出库单  i.入库单
	@btypeid     VARCHAR(1000)  --往来单位
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @chvOperatorID VARCHAR(50)
SET @chvOperatorID = @OperatorId
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID VARCHAR(50), @chvMBTypeID VARCHAR(50), @chvMBTypeID2 VARCHAR(50), @chvMETypeID VARCHAR(50), @chvMKTypeID VARCHAR(50), @chvMPTypeID VARCHAR(50), @chvMExpense VARCHAR(50), @chvMIncome VARCHAR(50), @chvMCapital VARCHAR(50), @chvMDtypeid VARCHAR(50), @chvMStypeid VARCHAR(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @chvOperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********
DECLARE @SQL_Man VARCHAR(1000)
SET @SQL_Man = ''

-- 仓库
IF @chvMKTypeID = '-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailKType FROM F_BaseGetManDetailKType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailKType K ON a.KTypeID = K.TypeID '
END

-- 分支机构
IF @chvMStypeid='-99999'
BEGIN
	SELECT TypeID INTO #F_BaseGetManDetailSType FROM F_BaseGetManDetailSType(@chvOperatorID)
	SET @SQL_Man = @SQL_Man + ' INNER JOIN #F_BaseGetManDetailSType s ON a.sTypeID = s.TypeID '
END

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @ptypeid <> ''
BEGIN
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@chvOperatorID)	
END

--构造主表明细表数据
DECLARE @detailTable	VARCHAR(500)
SET @detailTable = 'FactInOut'

-- ******** 权限范围单独处理 - End ********
DECLARE @SQL			VARCHAR(MAX),
		@SQLPType		VARCHAR(MAX),
		@SQLPTypeDrop	VARCHAR(MAX)

--筛选商品		
SET @SQLPType = 'CREATE TABLE #detailTable(BillNumberId NUMERIC(18,0))
				 INSERT INTO #detailTable(BillNumberId) SELECT BillNumberId FROM '+@detailTable+' WHERE ptypeid IN (SELECT typeid FROM #GetManPTypeId) '
				 
SET @SQLPTypeDrop = ' DROP TABLE #detailTable'				 
		
SET @SQL = 'SELECT	DISTINCT
					BillDate,
					BillCode,
					s.FullName as sfullname, 
					--f.ktypeid,
					--k.FullName as kfullname,
					'''' as efullname,
					a.Stypeid,
					a.etypeid,					
					a.BillNumberId,
					a.DealBTypeID,
					a.Comment,
					a.explain,
					b.fullname as dealbname,
					a.billtype
			FROM	FactIndex a
			--INNER JOIN FactInOut f ON a.BillNumberId = f.billnumberId
			LEFT JOIN dbo.SType s ON a.Stypeid=s.TypeId
			LEFT Join btype b on b.typeid = a.dealbtypeid 
			--LEFT JOIN dbo.Stock k ON f.ktypeid=k.TypeId
			WHERE	a.redword = 0							
					AND a.BillDate >= ''' + @StartDate + ''' 
					AND a.BillDate <= ''' + @EndDate + '''
                    AND a.BillType = ' + @frombilltype

IF @KType <> '' 
BEGIN
	SET @SQL = @SQL + ' AND a.KTypeID=''' + @KType + ''''
END

IF @SType <> '' SET @SQL = @SQL + ' AND a.STypeID=''' + @SType + ''''
IF @frombillcode <> '' SET @SQL = @SQL + ' AND a.BillCode LIKE ''%' + @frombillcode + '%'''
IF @Explain <> '' SET @SQL = @SQL + ' AND a.Explain LIKE ''%' + @Explain + '%'''
IF @Comment <> '' SET @SQL = @SQL + ' AND a.Comment LIKE ''%' + @Comment + '%'''

IF @btypeid <> ''
BEGIN
SET @sql = @sql + 'AND a.dealBtypeid = ''' + @btypeid + '''';
END

IF @PTypeId <> ''
BEGIN
	SET @SQL = @SQL + ' AND a.BillNumberId IN (SELECT BillNumberId FROM #detailTable)'
	--PRINT(@SQLPType + @SQL + @SQLPTypeDrop)
	EXEC (@SQLPType + @SQL + @SQLPTypeDrop)
END
ELSE
BEGIN
	--PRINT(@SQL)
	EXEC (@SQL)
END



IF @chvMKTypeID = '-99999' DROP TABLE #F_BaseGetManDetailKType
IF @chvMSTypeID = '-99999' DROP TABLE #F_BaseGetManDetailSType

DROP TABLE #GetManPTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadRepairBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadRepairBillDetail]
GO














CREATE                 PROCEDURE Web_LoadRepairBillDetail
(
 	@OperatorId	varchar(50), 	--操作员
	@BillType	int,		--单据类型
	@BillNumberId	int		--单据id
)
--@encode$--
AS
SET NOCOUNT ON 

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId=@BillNumberId AND cbd.BillType=@BillType

IF @BillType = 165 --维修接件单
	SELECT	p.typeid AS typeid, p.usercode, p.fullname, p.unit2 as unittwo, p.unit1 as unitone, 
		p.entrycode, p.standard, p.type, p.area, p.validdays, p.ifserial, p.serialcount,
		a.serial, a.buydate, a.ErrDes, a.total as expense, a.errdeal, a.repairmode, a.etypeid, e.fullname as efullname, a.baoxiu, a.state, a.comment,b.ktypeid,b.ktypeid2,
		a.GoodsNumber,a.CargoID,c.FullName as cargofullname,a.Qty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		p.customitemid ,
		p.customitemfrom ,
		p.customitemname,
		p.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		p.unitstype,
		p.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
		p.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(p.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,cbd.*
	FROM	wx_bill_jiejian a 
		INNER JOIN Billindex b ON a.BillNumberId=b.BillNumberId
		LEFT JOIN ptype p ON a.ptypeid=p.typeid
		LEFT JOIN employee e ON a.etypeid=e.typeid
		LEFT JOIN CargoType c ON b.ktypeid=c.KtypeID and a.CargoID=c.CargoID
		LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
		LEFT JOIN PType_Units v ON v.UnitsId=p.AssistantUnitId		
		LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
	WHERE	a.billnumberid=@billnumberid ORDER BY a.[id]

IF @BillType = 166 --维修单
	SELECT	p.typeid AS typeid, p.usercode, p.fullname,  p.unit2 as unittwo, p.unit1 as unitone,
		p.entrycode, p.standard, p.type, p.area, p.validdays, p.ifserial, p.serialcount,
		a.InOrOut, a.qty, a.price, a.total, 0 AS isunittwo, a.comment, a.serial, a.wxproperty, a.goodsnumber, a.producedate, a.validdate, 
		a.goodsbtypeid, a.goodscostprice AS goodsnumberprice, a.handzerocost,b.ktypeid,b.ktypeid2,a.CargoID,c.FullName as cargofullname,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		a.Price as nsaleprice,
		a.Price as curmsaleprice,
		a.Total as ntotal,
		p.customitemid ,
		p.customitemfrom ,
		p.customitemname,
		p.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		p.unitstype,
		p.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
		p.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(p.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,cbd.*	
	FROM	wx_bill_self a
		INNER JOIN BillIndex b ON a.BillNumberiD=b.BillNumberId
		LEFT JOIN ptype p ON a.ptypeid=p.typeid
		LEFT JOIN CargoType c ON b.ktypeid=c.KtypeID and a.CargoID=c.CargoID
		LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
		LEFT JOIN PType_Units v ON v.UnitsId=p.AssistantUnitId	
		LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
	WHERE	a.billnumberid=@billnumberid ORDER BY a.[id]

IF @BillType = 167 --维修取件单
	SELECT	p.typeid AS typeid, p.usercode, p.fullname, p.unit2 as unittwo, p.unit1 as unitone,
		p.entrycode, p.standard, p.type, p.area, p.validdays, p.ifserial,  p.serialcount,
		a.serial, 0 AS isunittwo, a.total as wxtotal, a.jiejianbillnumberid, a.jiejianid, a.jiejianptypeid, a.Comment, 
		bi.billcode AS jiejiancode,bi.btypeid AS btypeid1,
          	pn.usercode AS jiejianusercode, pn.fullname AS jiejianfullname,
		b.serial as jiejianserial, b.BuyDate AS jiejianbuydate, b.ErrDes AS jiejianErrDes, 
		b.errdeal AS jiejianerrdeal, b.repairmode AS jiejianrepairmode, b.state AS jiejianstate,bi1.ktypeid,bi1.ktypeid2,
		a.GoodsNumber,a.CargoID,c.FullName as cargofullname,a.Qty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		p.customitemid ,
		p.customitemfrom ,
		p.customitemname,
		p.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		p.unitstype,
		p.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
		p.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(p.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,cbd.*		
        FROM 	wx_Bill_GetBack a 
				LEFT JOIN ptype p ON a.ptypeid=p.typeid 
				LEFT JOIN billindex bi ON a.jiejianbillnumberid=bi.billnumberid
				LEFT JOIN billindex bi1 ON a.BillNumberID=bi1.billnumberid
				LEFT JOIN Wx_Bill_Jiejian b ON a.jiejianbillnumberid = b.billnumberid AND a.jiejianid = b.[id]	
				LEFT JOIN ptype pn ON b.ptypeid = pn.typeid
				LEFT JOIN CargoType c ON bi1.ktypeid=c.KtypeID and a.CargoID=c.CargoID
				LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
				LEFT JOIN PType_Units v ON v.UnitsId=p.AssistantUnitId	
				LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
		WHERE	a.BillNumberID=@billnumberid Order by a.[ID]

IF @billType = 168 --整机更换单
	
	SELECT 	p.typeid AS typeid, p.usercode, p.fullname, p.unit2 as unittwo, p.unit1 as unitone,
	       	p.entrycode, p.standard, p.type, p.area, p.validdays, p.ifserial, p.serialcount,
	       	a.serial, 0 AS isunittwo, a.wxProperty, a.total AS wxtotal, a.jiejianbillnumberid, a.jiejianid,
               	a.GoodsNumber, a.ProduceDate, a.ValidDate, a.GoodsBTypeID, a.GoodsCostPrice AS goodsnumberprice, a.handzerocost, a.comment,
               	c.billcode AS jiejiancode,c.btypeid AS btypeid1, b.serial AS jiejianserial, b.ptypeid AS jiejianptypeid, b.buydate AS jiejianbuydate, b.state AS jiejianstate,
	       	b.errdes AS jiejianerrdes, b.repairmode AS jiejianrepairmode, pn.usercode as jiejianusercode, pn.fullname as jiejianfullname,c1.ktypeid,c1.ktypeid2,
	       	a.CargoID,ct.FullName as cargofullname,a.Qty,
	       	CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
			ELSE a.NQty END AS NQty,
			CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
			ELSE a.UnitRate END AS UnitRate,
	       	p.customitemid ,
			p.customitemfrom ,
			p.customitemname,
			p.customitemrefid,		        
			itemid=a.ItemId,
			itemname= CASE WHEN a.IsCombined = 0  THEN
					 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		p.unitstype	,
		p.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
		p.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(p.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,cbd.*	
        FROM 	wx_Bill_Replace a 
				LEFT JOIN ptype p on a.ptypeid=p.typeid 
        		LEFT JOIN wx_Bill_jiejian b ON a.jiejianbillnumberid = b.billnumberid and a.jiejianid = b.[id]
				LEFT JOIN ptype pn ON b.ptypeid = pn.typeid
        		LEFT JOIN billindex c ON a.jiejianbillnumberid = c.billnumberid
        		LEFT JOIN billindex c1 ON a.BillNumberID = c1.billnumberid
        		LEFT JOIN CargoType ct ON c1.ktypeid=ct.KtypeID and a.CargoID=ct.CargoID
        		LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
				LEFT JOIN PType_Units v ON v.UnitsId=p.AssistantUnitId	
				LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
        WHERE a.BillNumberID=@billnumberid ORDER BY a.[id]

IF @BillType = 169 --送修单
	SELECT	p.typeid AS typeid, p.usercode, p.fullname,p.unit2 as unittwo, p.unit1 as unitone,
		p.entrycode, p.standard, p.type, p.area, p.validdays, p.ifserial, p.serialcount,
		a.serial, 0 AS isunittwo, a.qty, (a.qty-a.sendbackqty) as nosendbackqty, a.total as wxtotal, a.jiejianbillnumberid, a.jiejianptypeid, a.jiejianid, a.Comment, 
		bi.billcode AS jiejiancode,
          	pn.usercode AS jiejianusercode, pn.fullname AS jiejianfullname,
		b.serial as jiejianserial, b.BuyDate AS jiejianbuydate, b.ErrDes AS jiejianErrDes, 
		b.errdeal AS jiejianerrdeal, b.repairmode AS jiejianrepairmode, b.state AS jiejianstate,bi1.ktypeid,bi1.ktypeid2,
		a.GoodsNumber,a.CargoID,c.FullName as cargofullname,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		p.customitemid ,
		p.customitemfrom ,
		p.customitemname,
		p.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		p.unitstype,
		p.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
		p.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(p.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,
		Errdes1,cbd.*		
        FROM 	wx_Bill_Send a 
				LEFT JOIN ptype p ON a.ptypeid=p.typeid 
				LEFT JOIN billindex bi ON a.jiejianbillnumberid=bi.billnumberid
				LEFT JOIN billindex bi1 ON a.BillNumberID=bi1.billnumberid
				LEFT JOIN Wx_Bill_Jiejian b ON a.jiejianbillnumberid = b.billnumberid AND a.jiejianid = b.[id]	
				LEFT JOIN ptype pn ON b.ptypeid = pn.typeid
				LEFT JOIN CargoType c ON bi1.ktypeid=c.KtypeID and a.CargoID=c.CargoID
				LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
				LEFT JOIN PType_Units v ON v.UnitsId=p.AssistantUnitId	
				LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
		WHERE	a.BillNumberID=@billnumberid Order by a.[ID]

IF @BillType = 170 --送修返回单
	SELECT	p.typeid AS typeid, p.usercode, p.fullname, p.unit2 as unittwo, p.unit1 as unitone,
		p.entrycode, p.standard, p.type, p.area, p.validdays, p.ifserial, p.serialcount,
		a.serial, 0 AS isunittwo, a.qty, a.total as wxtotal, a.sendbillnumberid, a.sendid, a.sendptypeid, a.Comment, 
		bi.billcode AS sendcode,bi.BillDate AS sendbilldate,
          	pn.usercode AS sendusercode, pn.fullname AS sendfullname,
		b.serial as sendserial, b.qty AS sendqty,b.sendbackqty, (b.qty - b.sendbackqty) AS sendnobackqty, 
		b.jiejianbillnumberid, b.jiejianid, b.jiejianptypeid,
		c.buydate AS jiejianbuydate, 
		CASE WHEN b.JieJianState=-1 THEN b.Errdes1
		ELSE c.ErrDes END AS sendErrDes, 
		c.errdeal AS jiejianerrdeal, c.repairmode AS jiejianrepairmode,c.state AS jiejianstate,bi1.ktypeid,bi1.ktypeid2,
		a.GoodsNumber,a.CargoID,ct.FullName as cargofullname,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		p.customitemid ,
		p.customitemfrom ,
		p.customitemname,
		p.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		p.unitstype,
		p.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
		p.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(p.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,cbd.*		
        FROM 	wx_Bill_SendBack a 
		LEFT JOIN ptype p ON a.ptypeid=p.typeid 
		LEFT JOIN billindex bi ON a.sendbillnumberid=bi.billnumberid
		LEFT JOIN billindex bi1 ON a.BillNumberID=bi1.billnumberid
		LEFT JOIN Wx_Bill_send b ON a.sendbillnumberid = b.billnumberid AND a.sendid = b.[id]
		LEFT JOIN wx_bill_jiejian c ON b.jiejianbillnumberid = c.billnumberid AND b.jiejianid = c.[id]
		LEFT JOIN ptype pn ON b.ptypeid = pn.typeid
		LEFT JOIN CargoType ct ON bi1.ktypeid=ct.KtypeID and a.CargoID=ct.CargoID
		LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
		LEFT JOIN PType_Units v ON v.UnitsId=p.AssistantUnitId	
		LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
	WHERE	a.BillNumberID=@billnumberid Order by a.[ID]

IF @BillType = 171 --报修单
	SELECT	p.typeid AS typeid, p.usercode, p.fullname, p.unit2 as unittwo, p.unit1 as unitone,
		p.entrycode, p.standard, p.type, p.area, p.validdays, p.ifserial, p.serialcount,
		a.serial, a.buydate, a.ErrDes, a.total as expense, a.errdeal, a.etypeid, e.fullname as efullname, a.baoxiu, a.comment,bi.ktypeid,bi.ktypeid2,
		a.GoodsNumber,a.CargoID,c.FullName as cargofullname,a.Qty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		p.customitemid ,
		p.customitemfrom ,
		p.customitemname,
		p.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		p.unitstype,
		p.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
		p.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(p.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,cbd.*			
	FROM	wx_bill_call a
			INNER JOIN billindex bi ON a.BillNumberId=bi.billnumberid
			LEFT JOIN ptype p ON a.ptypeid=p.typeid
			LEFT JOIN employee e on a.etypeid=e.typeid
			LEFT JOIN CargoType c ON bi.ktypeid=c.KtypeID and a.CargoID=c.CargoID
			LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
			LEFT JOIN PType_Units v ON v.UnitsId=p.AssistantUnitId	
			LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
	WHERE	a.billnumberid=@billnumberid ORDER BY a.[id]

IF @BillType = 172 --上门维修单
	SELECT	p.typeid AS typeid, p.usercode, p.fullname, p.unit2 as unittwo, p.unit1 as unitone,
		p.entrycode, p.standard, p.type, p.area, p.validdays, p.ifserial, p.serialcount,
		a.InOrOut, a.qty, a.price, a.total, 0 AS isunittwo, a.comment, a.serial, a.wxproperty, a.goodsnumber, a.producedate, a.validdate, 
		a.goodsbtypeid, a.goodscostprice AS goodsnumberprice, a.handzerocost,bi.ktypeid,bi.ktypeid2,
		a.CargoID,c.FullName as cargofullname,
		a.Price as nsaleprice,
		a.Price as curmsaleprice,
		a.Total as ntotal,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(p.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		p.customitemid ,
		p.customitemfrom ,
		p.customitemname,
		p.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		p.unitstype,
		p.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(p.typeid,p.BaseUnitId,2)) AS basemunitcode,
		p.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(p.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,cbd.*		
	FROM	wx_bill_goto a
			INNER JOIN BillIndex bi ON a.BillNumberiD=bi.BillNumberId
			LEFT JOIN ptype p ON a.ptypeid=p.typeid
			LEFT JOIN CargoType c ON bi.ktypeid=c.KtypeID and a.CargoID=c.CargoID
			LEFT JOIN PType_Units u ON u.UnitsId=p.baseUnitId
			LEFT JOIN PType_Units v ON v.UnitsId=p.AssistantUnitId
			LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
	WHERE	a.billnumberid=@billnumberid ORDER BY a.[id]

IF @BillType = 173 --维修品调入单
	SELECT	Qty =a.Qty,
		a.Comment AS Comment,
		IsUnittwo = 0,
		a.Serial,
		a.Price,
		a.Price as nsaleprice,
		a.Price as curmsaleprice,
		a.Total as ntotal,
		a.Total,
		a.InputCostPrice,
		a.ProduceDate,
		a.ValidDate,
		a.GoodsNumber,
		a.GoodsCostPrice AS GoodsNumberPrice,
		a.HandZeroCost,
		'' AS CustomerCode,
		b.typeid,
		b.UserCode,
		b.FullName,		
		b.Unit1 AS UnitOne,
		b.Unit2 AS UnitTwo,
		CASE WHEN ISNULL(b.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		b.EntryCode,
		b.Standard,
		b.Type,
		b.Area,
		b.SerialCount,
		b.ValidDays,
		b.IfSerial,
		b.usefullifeday,
		bi.ktypeid,
		bi.ktypeid2,
		a.CargoID,
		c.FullName as cargofullname,
		CASE WHEN ISNULL(b.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		b.unitstype,
		b.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(b.typeid,b.BaseUnitId,2)) AS basemunitcode,
		b.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(b.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,
		cbd.*			
	FROM	dbo.Wx_Bill_IN a
		INNER JOIN BillIndex bi ON a.BillNumberID=bi.BillNumberId
		INNER JOIN dbo.PType b ON a.PTypeID = b.TypeID
		LEFT JOIN CargoType c ON bi.ktypeid=c.KtypeID and a.CargoID=c.CargoID
		LEFT JOIN PType_Units u ON u.UnitsId=b.baseUnitId
		LEFT JOIN PType_Units v ON v.UnitsId=b.AssistantUnitId
		LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
	WHERE	a.BillNumberID = @billnumberid
		ORDER BY a.ID
IF @BillType = 174 --维修品调出单
	SELECT	Qty = a.Qty,
		a.Comment AS Comment,
		IsUnittwo = 0,
		a.Serial,
		a.Price,
		a.Price as nsaleprice,
		a.Price as curmsaleprice,
		a.Total as ntotal,
		a.Total,
		a.InputCostPrice,
		a.ProduceDate,
		a.ValidDate,
		a.GoodsNumber,
		a.GoodsCostPrice AS GoodsNumberPrice,
		a.HandZeroCost,
		'' AS CustomerCode,
		b.typeid,
		b.UserCode,
		b.FullName,		
		b.Unit1 AS UnitOne,
		b.Unit2 AS UnitTwo,
		CASE WHEN ISNULL(b.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(b.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		b.EntryCode,
		b.Standard,
		b.Type,
		b.Area,
		b.SerialCount,
		b.ValidDays,
		b.IfSerial,
		b.usefullifeday,
		bi.ktypeid,
		bi.ktypeid2,
		a.CargoID,
		c.FullName as cargofullname,		
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		b.unitstype,
		b.baseUnitId as unitid,
		(dbo.F_GetAllEntrycode(b.typeid,b.BaseUnitId,2)) AS basemunitcode,
		b.AssistantUnitId as nunitid,
		v.FullName as nunit,
		u.FullName as unit,
		a.ID,
		CAST(b.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,	
		cbd.*	
	FROM	dbo.Wx_Bill_Out a
			INNER JOIN BillIndex bi ON a.BillNumberID=bi.BillNumberId
			INNER JOIN dbo.PType b ON a.PTypeID = b.TypeID
			LEFT JOIN CargoType c ON bi.ktypeid=c.KtypeID and a.CargoID=c.CargoID
			LEFT JOIN PType_Units u ON u.UnitsId=b.baseUnitId
			LEFT JOIN PType_Units v ON v.UnitsId=b.AssistantUnitId
			LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
	WHERE	a.BillNumberID = @billnumberid
		ORDER BY a.ID
IF @BillType = 175 --维修品调拨单
	SELECT	Qty = a.Qty,
		a.Comment AS Comment,
		IsUnittwo = 0,
		a.Serial,
		Price = null,
		Total = null,
		InputCostPrice = null,
		ProduceDate = null,
		ValidDate = null,
		a.GoodsNumber,
		GoodsCostPrice = null,'' AS CustomerCode,
		b.typeid,
		b.UserCode,
		b.FullName,		
		b.Unit1 AS UnitOne,
		b.Unit2 AS UnitTwo,		
		b.EntryCode,
		b.Standard,
		b.Type,
		b.Area,
		b.SerialCount,
		b.ValidDays,
		b.IfSerial,
		b.usefullifeday,
		bi.ktypeid,
		bi.ktypeid2,
		a.CargoID,
		c.FullName as cargofullname,
		CASE WHEN ISNULL(b.AssistantUnitId,0)=0 THEN NULL
		ELSE a.NQty END AS NQty,
		CASE WHEN ISNULL(b.AssistantUnitId,0)=0 THEN NULL
		ELSE a.UnitRate END AS UnitRate,
		b.baseUnitId AS unitid,
		(dbo.F_GetAllEntrycode(b.typeid,b.BaseUnitId,2)) AS basemunitcode,
		b.AssistantUnitId AS nunitid,
		u.FullName AS unit,
		v.FullName AS nunit,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,		        
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0  THEN
				 (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
				  ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		b.unitstype,
		a.ID,
		CAST(b.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		1 AS munitrate,cbd.*	
	FROM	dbo.Wx_Bill_Move a
			INNER JOIN BillIndex bi ON a.BillNumberID=bi.BillNumberId
			INNER JOIN dbo.PType b ON a.PTypeID = b.TypeID
			LEFT JOIN CargoType c ON bi.ktypeid=c.KtypeID and a.CargoID=c.CargoID
			LEFT JOIN PType_Units u ON u.UnitsId=b.baseUnitId
			LEFT JOIN PType_Units v ON v.UnitsId=b.AssistantUnitId
			LEFT JOIN #Custom_T cbd ON cbd.detailId=a.id
	WHERE	a.BillNumberID = @billnumberid
		ORDER BY a.ID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadShareFeeBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_LoadShareFeeBill
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-09-06
-- Description: 费用摊销单费用表体加载
-- =============================================
CREATE PROCEDURE Web_LoadShareFeeBill
(
	@billnumberid	INT
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	

SELECT 
	F.Comment as base,
	F.ID,
	F.FromBillID,
	F.FromBillNumberID,
	b.AtypeId,
	b.total,
	b.Stypeid,
	I.BillCode,
	I.Billtype,
	I.BillDate,
	I.DealBTypeID AS btypeid,
	I.etypeid,
	I.dtypeid 
FROM ShareFeeBill F
INNER JOIN MoneyBill B ON F.FromBillID=B.ID
INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
WHERE F.BillNumberId=@billnumberid


END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadShareSourceBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_LoadShareSourceBill
GO

SET ANSI_NULLS ON
GO 
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-09-06
-- Description: 费用摊销单出入库单表体加载
-- =============================================
CREATE PROCEDURE Web_LoadShareSourceBill
(
	@billnumberid	INT,
	@billtype		INT
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
	IF @billtype=205
	BEGIN
		SELECT 
			F.Comment as base,
			F.ID,
			F.FromBillID,
			F.FromBillNumberID,
			F.FromBillType,
			F.ShareFee,
			b.Qty,
			b.total as billtotal,
			b.PtypeId,
			i.Stypeid,
			I.BillCode,
			I.Billtype,
			I.BillDate,
			I.btypeid,
			I.etypeid,
			I.dtypeid,
			B.UnitID,
			u.FullName AS unit,
			B.MUnitRate,
			p.UnitsType
		FROM ShareSourceBill F
		INNER JOIN BuyBill B ON F.FromBillID=B.ID
		INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
		INNER JOIN PType p ON P.typeId=B.PtypeId
		LEFT  JOIN PType_Units u ON u.UnitsId=B.UnitID
		WHERE F.BillNumberId=@billnumberid AND F.FromBillType=34
		--ORDER BY F.ID
		UNION ALL
		SELECT 
			F.Comment as base,
			F.ID,
			F.FromBillID,
			F.FromBillNumberID,
			F.FromBillType,
			F.ShareFee,
			b.Qty,
			b.total as billtotal,
			b.PtypeId,
			i.Stypeid,
			I.BillCode,
			I.Billtype,
			I.BillDate,
			I.btypeid,
			I.etypeid,
			I.dtypeid,
			u.UnitsId,
			u.FullName AS unit,
			B.MUnitRate,
			p.UnitsType
		FROM ShareSourceBill F
		INNER JOIN DisassembleBill B ON F.FromBillID=B.ID
		INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
		INNER JOIN PType p ON P.typeId=B.PtypeId
		LEFT  JOIN PType_Units u ON u.UnitsId=p.baseUnitId
		WHERE F.BillNumberId=@billnumberid AND F.FromBillType=16
		ORDER BY F.ID
	END
	ELSE
	BEGIN
		SELECT 
			F.Comment as base,
			F.ID,
			F.FromBillID,
			F.FromBillNumberID,
			F.FromBillType,
			F.ShareFee,
			b.Qty,
			b.total as billtotal,
			b.PtypeId,
			i.Stypeid,
			I.BillCode,
			I.Billtype,
			I.BillDate,
			I.btypeid,
			I.etypeid,
			I.dtypeid,
			B.UnitID,
			u.FullName AS unit,
			B.MUnitRate,
			p.UnitsType
		FROM ShareSourceBill F
		INNER JOIN SaleBill B ON F.FromBillID=B.ID
		INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
		INNER JOIN PType p ON P.typeId=B.PtypeId
		LEFT  JOIN PType_Units u ON u.UnitsId=B.UnitID
		WHERE F.BillNumberId=@billnumberid AND F.FromBillType=11
		UNION ALL 
		SELECT 
			F.Comment as base,
			F.ID,
			F.FromBillID,
			F.FromBillNumberID,
			F.FromBillType,
			F.ShareFee,
			b.Qty,
			b.total as billtotal,
			b.PtypeId,
			i.Stypeid,
			I.BillCode,
			I.Billtype,
			I.BillDate,
			I.btypeid,
			I.etypeid,
			I.dtypeid,
			B.UnitID,
			u.FullName AS unit,
			B.MUnitRate,
			p.UnitsType
		FROM ShareSourceBill F
		INNER JOIN RetailBill B ON F.FromBillID=B.ID
		INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
		INNER JOIN PType p ON P.typeId=B.PtypeId
		LEFT  JOIN PType_Units u ON u.UnitsId=B.UnitID
		WHERE F.BillNumberId=@billnumberid AND F.FromBillType=305
		UNION ALL
		SELECT 
			F.Comment as base,
			F.ID,
			F.FromBillID,
			F.FromBillNumberID,
			F.FromBillType,
			F.ShareFee,
			b.Qty,
			b.total as billtotal,
			b.PtypeId,
			i.Stypeid,
			I.BillCode,
			I.Billtype,
			I.BillDate,
			I.btypeid,
			I.etypeid,
			I.dtypeid,
			B.UnitID,
			u.FullName AS unit,
			B.MUnitRate,
			p.UnitsType
		FROM ShareSourceBill F
		INNER JOIN PT_Combin_SaleBillDetail B ON F.FromBillID=B.ID
		INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
		INNER JOIN PType p ON P.typeId=B.PtypeId
		LEFT  JOIN PType_Units u ON u.UnitsId=B.UnitID
		WHERE F.BillNumberId=@billnumberid AND F.FromBillType=12
	END


END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadStockCheckDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LoadStockCheckDetails]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：
*/
CREATE PROCEDURE Web_LoadStockCheckDetails
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@billnumberid		NUMERIC(18,0),
	@ifwx				INT,  --1==维修，0==正常
	@ktypeid			VARCHAR(100)=''
)
--@encode$--
AS
SET NOCOUNT ON

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId=@billnumberid AND billtype= 306
DECLARE @SQLString nvarchar(MAX);
SET @SQLString='
				DECLARE @tb table
				(
				 scid INT,
				 id INT,
				 ItemID INT,
				 Fullname VARCHAR(500),
				 UserCode VARCHAR(500),
				 IsCombined INT
				)
				INSERT INTO @tb(scid,id,ItemID,Fullname,UserCode,IsCombined)
				SELECT s.id,r._id, ItemID,r.Fullname,r.UserCode,0
				FROM StockCheck s INNER JOIN xw_SelfData r ON s.ItemID=r._Id
				where IsCombined=0
				UNion ALL 
				SELECT s.id,r.id, ItemID,REPLACE( r.Fullname,''я'',''/''),r.Fullname,1
				FROM StockCheck s INNER JOIN CustomReferenceValue r ON s.ItemID=r.id
				where IsCombined=1'+CHAR(10);

SET @SQLString+='SELECT	a.serial,
						a.stockcheckserial,
						a.ptypeid as typeid,
						p.EntryCode,
						dbo.F_GetAllEntrycode(a.ptypeid,p.StockUnitId,2) AS stockmunitcode,
						a.goodsnumber, 
						a.producedate,
						a.validdate,  
						case when a.goodscostprice = -1 then -1 else a.goodscostprice end as goodsnumberprice, 
						case when a.goodscostprice = -1 then -1 else a.goodscostprice end as goodscostprice, 
						case when a.goodscostprice = -1 then -1 else a.goodscostprice end as costprice, 
						a.qty,
						isnull(a.stockqty,0) as stockqty ,
						
						a.qty-isnull(a.stockqty,0) as countqty,
						(CASE WHEN  pu.nunit IS null THEN NULL ELSE  ISNULL(a.nqty,0) END)  as nqty,
						--isnull(a.stocknqty,0) as stocknqty,
						CASE WHEN pu.nunit IS null THEN null ELSE ISNULL(a.stocknqty,0) END AS stocknqty,
						(CASE WHEN  pu.nunit IS null THEN NULL ELSE  ISNULL(a.nqty,0)-isnull(a.stocknqty,0)  END) as countnqty,
						p.fullname,
						p.usercode,
						p.customitemid,
						p.customitemfrom,
						p.customitemname,
						p.customitemrefid,
						p.BuyUnitId,
						p.SaleUnitId,		
						p.ProduceUnitId,
						p.StockUnitId,	
						p.BaseUnitId,
						pu.*,
						pu.stockunitid as munitid,
						pu.stockunitname as munit,
						pu.stockmunitrate as munitrate,
						(a.stockqty/pu.stockmunitrate) as stockmqty,
						(a.qty/pu.stockmunitrate) as mqty,
						(a.qty/pu.stockmunitrate)-(a.stockqty/pu.stockmunitrate) as countmqty,
						it.fullname AS itemname,
						it.IsCombined AS iscombined,
						it.id as itemid,
						si.ktypeid,
						p.ifserial,
						s.fullname AS kfullname, 
						aux1.fullname AS auxfullname1, 
						aux2.fullname AS auxfullname2, 
						aux3.fullname AS auxfullname3,
						aux.SaleUnitRate1 AS auxrate1,
						aux.SaleUnitRate2 AS auxrate2,
						aux.SaleUnitRate3 AS auxrate3, '
			
IF @ifwx<>1
BEGIN 
	SET @SQLString+='	cg.cargoid as cargoid,cg.fullname as cargofullname,'	
END	
							
SET @SQLString+='a.id,cbd.* 
				 FROM stockcheck a  
				 INNER JOIN ptype p on a.ptypeid = p.typeid 
				 INNER JOIN stockcheckindex SI ON SI.stockcheckid = a.stockcheckid
				 INNER JOIN stock s on s.typeid = SI.ktypeid 
				 LEFT JOIN dbo.PType_AuxiliaryUnits_Ext aux ON aux.ptypeid = a.ptypeid
				 LEFT JOIN dbo.PType_Units aux1 ON aux1.UnitsId = aux.SaleUnitID1
				 LEFT JOIN dbo.PType_Units aux2 ON aux2.UnitsId = aux.SaleUnitID2
				 LEFT JOIN dbo.PType_Units aux3 ON aux3.UnitsId = aux.SaleUnitID3 '
				 
SET	@SQLString+=' LEFT JOIN F_GetPtypeUnitInfo() pu ON p.typeid=pu.typeid'
SET @SQLString+=' LEFT JOIN #Custom_T cbd ON cbd.detailid=a.id '
IF @ifwx <>1
BEGIN
	SET @SQLString+='	LEFT JOIN CargoType cg ON a.cargoid=cg.cargoid' 
END	
SET @SQLString+='	LEFT JOIN @tb  it ON it.scid=a.id' 

SET @SQLString+=' WHERE a.stockcheckid='+CAST(@billnumberid as VARCHAR)
SET @SQLString+='  ORDER BY  a.id'
--print @SQLString
exec sp_executesql  @SQLString
DROP TABLE #Custom_T



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadTransportShareFeeBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_LoadTransportShareFeeBill
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		
-- Create date: 
-- Description: 运输费用摊销单费用表体加载
-- =============================================
CREATE PROCEDURE Web_LoadTransportShareFeeBill
(
	@billnumberid	INT
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	

SELECT 
	F.Comment as base,
	F.ID,
	F.FromBillID,
	F.FromBillNumberID,
	I.BillCode,
	I.Billtype,
	I.BillDate,
	I.DealBTypeID AS btypeid,
	I.etypeid,
	I.dtypeid,
	I.totalfreight 
FROM ShareFeeBill F
INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
WHERE F.BillNumberId=@billnumberid


END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LoadTransportShareSourceBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_LoadTransportShareSourceBill
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-09-06
-- Description: 费用摊销单出入库单表体加载
-- =============================================
CREATE PROCEDURE Web_LoadTransportShareSourceBill
(
	@billnumberid	INT,
	@billtype		INT
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON

			SELECT 
			F.Comment as base,
			F.ID,
			F.FromBillID,
			F.FromBillNumberID,
			F.FromBillType,
			F.ShareFee,
			b.Qty,
			b.[weight],
			b.volume,
			b.PtypeId,
			i.Stypeid,
			I.BillCode,
			I.Billtype,
			I.BillDate,
			I.btypeid,
			I.etypeid,
			I.dtypeid,
			p.UnitsType
		FROM ShareSourceBill F
		INNER JOIN BillIndex I ON i.BillNumberId=f.FromBillNumberID
		INNER JOIN Transportbill B ON F.FromBillID=B.ID
		INNER JOIN PType p ON P.typeId=B.PtypeId
		WHERE F.BillNumberId=@billnumberid

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LockOneUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LockOneUser]
GO








CREATE  PROCEDURE [dbo].[Web_LockOneUser] 
(
	@OperatorID 	VARCHAR(50), 	--操作员ID号
	@ETypeId	VARCHAR(50)	--查询对象的id
)
--@encode$--
AS


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

SELECT employee.usercode,employee.fullname,loginuser.locknum,loginuser.etypeid,loginuser.openlock 
from loginuser 
left join employee 
on loginuser.etypeid = employee.typeid
WHERE loginuser.etypeid = @ETypeId






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LockUserList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LockUserList]
GO














CREATE         PROCEDURE [dbo].[Web_LockUserList] 
(
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@UserCode	VARCHAR(50),
	@FullName	VARCHAR(50),
	@PageSize	INT,
	@PageNum	INT,
	@returnCount 	int output	
)
--@encode$--
AS


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE	@allpage	INT
DECLARE @allnumber	INT


DECLARE @SQL	VARCHAR(8000)

SELECT @allnumber=COUNT(*) FROM loginuser 
left join employee on loginuser.etypeid = employee.typeid
WHERE employee.usercode like ('%'+@UserCode+'%')  AND employee.fullname like ('%'+@FullName+'%')

SET @allpage=((@allnumber-1)/@PageSize)+1


SET @SQL = 'SELECT top '+CONVERT(VARCHAR(50),@PageSize)
		+ '		employee.usercode,employee.fullname,loginuser.*,
				case when loginuser.iserp = 1 then ''是'' else ''否'' end as erp,
				case when loginuser.ismobile = 1 then ''是'' else ''否'' end as mobile,
				case when loginuser.ispos = 1 then ''是'' else ''否'' end as pos,'
		+ CONVERT(VARCHAR(50),@allpage) + ' AS allpagenum ' 
		+ ' from loginuser '
		+ ' inner join employee on loginuser.etypeid = employee.typeid '
		+ ' WHERE employee.usercode like ''%' +@UserCode +'%'''
		+ ' AND employee.fullname like ''%' +@Fullname +'%'''
		+ ' and employee.usercode not in (
				select top '+CONVERT(VARCHAR(50),(@PageSize*(@PageNum-1)))+'
					   usercode
				from   employee e,
					   loginuser l
				where  e.typeid = l.etypeid
					   and e.usercode like ''%' +@UserCode +'%''
					   and e.fullname like ''%' +@Fullname +'%''
				order by l.sysid desc,e.usercode
			)
			AND iserp=1 '
		+ ' ORDER BY loginuser.sysid desc,employee.UserCode '
	
--print @sql
EXEC(@SQL)

set @returnCount = @allnumber












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_LockUserListSearch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_LockUserListSearch]
GO









CREATE    PROCEDURE [dbo].[Web_LockUserListSearch] 
(
	@OperatorID 	VARCHAR(50),	--操作员ID号
	@UserCode	VARCHAR(50),
	@FullName	VARCHAR(50),
	@PageSize	INT,
	@PageNum	INT
)
--@encode$--
AS


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE	@allpage	INT
DECLARE @allnumber	INT


DECLARE @SQL	VARCHAR(8000)

SELECT @allnumber=COUNT(*) FROM loginuser

SET @allpage=((@allnumber-1)/@PageSize)+1


SET @SQL = 'SELECT TOP '+CONVERT(VARCHAR(50),(@PageSize*@PageNum))
		+ ' employee.usercode,employee.fullname,loginuser.locknum,loginuser.etypeid,loginuser.openlock ,'
		+ CONVERT(VARCHAR(50),@allpage) + ' AS allpagenum ' 
		+ ' from loginuser '
		+ ' left join employee on loginuser.etypeid = employee.typeid '
		+ ' WHERE employee.usercode like ''' +@UserCode +'%'''
		+ ' AND employee.fullname like ''' +@Fullname +'%'''
		+ ' ORDER BY loginuser.etypeid '


	
--print @sql
EXEC(@SQL)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ModifyTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_ModifyTask]
GO














/****** Object:  Stored Procedure dbo.Web_ModifyTask    Script Date: 2002-6-20 10:14:54 ******/

CREATE  PROCEDURE Web_ModifyTask
(
 @FILENAME varchar(255),
 @Flag varchar(66),
 @Stockid varchar(25),
 @TaskId int,
 @Op int=0
)
--@encode$--
 AS
SET NOCOUNT ON 
 if @FILENAME is null or  @Flag is null or @TaskId is null return 1
 if @Op=0 
 begin
  if exists(select * from OFFLINE_TASK where taskid=@Taskid and STOCKID=@STOCKID and Status=0)  --检查该任务是否存在，如存在返回0
   update OFFLINE_TASK set [FileName]=@FILENAME,flag=@flag,[date]=GetDate() where taskid=@Taskid and STOCKID=@STOCKID and Status=0
  else
   insert into OFFLINE_TASK([FileName],[DATE],FLAG,TASKID,STOCKID) values(@FILENAME,GetDate(),@Flag,@TaskId,@StockID)
 end
 else
   if exists(select * from OFFLINE_TASK where taskid=@Taskid and STOCKID=@STOCKID and Status=0)
     update  OFFLINE_TASK set Status=1 where taskid=@Taskid and STOCKID=@STOCKID and Status=0
 return @@error 















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MoneyBtypeXiangDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_MoneyBtypeXiangDetail]
GO

/*
	作者：谢吉康
	日期：2004-12-06
	描述：原来的写法不正确，重写
*/
CREATE  PROCEDURE Web_MoneyBtypeXiangDetail
(
	@OperatorID	varchar(100),
	@StartDate 	varchar(30),
	@EndDate 	varchar(30),
	@ETypeId 	varchar(100),
	@STypeId 	varchar(8000),
	@BTypeId 	varchar(100),
	@DTypeId 			VARCHAR(MAX),--部门
	@szOrderBy 	varchar(50)='',
	@BillTypeId	varchar(100),		--单据类型的列表
	@cid		VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--单位：
CREATE TABLE #GetSelBTypeId(TypeId varchar(100))
INSERT INTO #GetSelBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@bTypeId,2,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@eTypeId,3,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)		


DECLARE @SQL VARCHAR(MAX)
SET @SQL=''

SET @SQL=@SQL+'
--处理结果集
SELECT 	B.BillNumberId,
		B.BillDate,
		B.BillCode,
		B.RedWord,
		B.BillType,
		B.Comment,
		B.BTypeId,
		B.ATypeId,
		B.STypeId,
		SUM(ISNULL(B.Sum_Total,0)) AS Sum_Total,
		SUM(ISNULL(B.NSum_Total,0)) AS NSum_Total
FROM	(
			SELECT  bi.BillNumberId,
					bi.BillDate,
					bi.BillCode,
					bi.RedWord,
					L.BillType,
					bi.Comment,
					L.BTypeId,
					CASE
							WHEN bi.IfMulAccount = 1 THEN ''-99999''
							ELSE bi.ATypeId
						END AS ATypeId,
					L.STypeId,
					SUM(
						CASE 
							WHEN (AC.TypeName=''B''  AND AC.UserCode<>''2181'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''1151'')  THEN ISNULL(L.Total,0)
							WHEN (AC.UserCode = ''2131'' AND L.billtype=159) THEN ISNULL(L.Total,0)
							ELSE 0	
							END
						)  AS Sum_Total,
					SUM(
						CASE 
							WHEN (AC.TypeName=''B''  AND AC.UserCode<>''2181'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''1151'')  THEN ISNULL(L.NTotal,0)
							WHEN (AC.UserCode = ''2131'' AND L.billtype=159) THEN ISNULL(L.NTotal,0)
							ELSE 0	
							END
						)  AS NSum_Total					
			FROM   ListTable l 
			        INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
					INNER JOIN BillIndex bi	ON l.billnumberid=bi.billnumberid and l.billtype=bi.billtype 
					INNER JOIN #GetSelBTypeId B ON B.TypeId = L.BTypeId
					INNER JOIN #GetManETypeId E ON E.TypeId = L.ETypeId
					INNER JOIN #GetManSTypeId S ON S.TypeId = L.Stypeid
					INNER JOIN #GetMandTypeId d ON d.TypeId = L.dTypeId
			WHERE	L.BillType IN (SELECT * FROM f_split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
					AND L.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND L.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
					AND L.Audited = 1
'
IF @cid<>0
	SET @SQL=@SQL+' AND L.CID='+CHAR(39)+@cid+CHAR(39)
SET @SQL=@SQL+'
			GROUP BY bi.BillNumberId,
					bi.BillDate,
					bi.BillCode,
					L.BTypeId,
					bi.ATypeId,
					L.STypeId,
					bi.Comment,
					bi.RedWord,
					L.BillType,
					bi.IfMulAccount '
			
SET @SQL=@SQL+'		
        UNION ALL
        SELECT  bi.BillNumberId,
				bi.BillDate,
				bi.BillCode,
				bi.RedWord,
				L.BillType,
				bi.Comment,
				L.BTypeId,
				CASE
						WHEN bi.IfMulAccount = 1 THEN ''-99999''
						ELSE bi.ATypeId
					END AS ATypeId,
				L.STypeId,
				SUM(
					CASE 
						WHEN (AC.TypeName=''B''  AND AC.UserCode<>''2181'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''1151'')  THEN ISNULL(L.Total,0)
						WHEN (AC.UserCode = ''2131'' AND L.billtype=159) THEN ISNULL(L.Total,0)
						ELSE 0	
						END
					)  AS Sum_Total,
				SUM(
					CASE 
						WHEN (AC.TypeName=''B''  AND AC.UserCode<>''2181'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''1151'')  THEN ISNULL(L.NTotal,0)
						WHEN (AC.UserCode = ''2131'' AND L.billtype=159) THEN ISNULL(L.NTotal,0)
						ELSE 0	
						END
					)  AS NSum_Total					
		FROM	ListTable l 
		        INNER JOIN AC_Items AC ON L.AtypeID=AC.nid
				INNER JOIN Coupon_BillIndex bi	ON l.billnumberid=bi.billnumberid and l.billtype=bi.billtype 
				INNER JOIN #GetSelBTypeId B ON B.TypeId = L.BTypeId
				INNER JOIN #GetManETypeId E ON E.TypeId = L.ETypeId
				INNER JOIN #GetManSTypeId S ON S.TypeId = L.Stypeid
				INNER JOIN #GetMandTypeId d ON d.TypeId = L.dTypeId
		WHERE	L.BillType IN (SELECT * FROM f_split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
				AND L.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
				AND L.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
				AND L.Audited = 1
'
IF @cid<>0
	SET @SQL=@SQL+' AND L.CID='+CHAR(39)+@cid+CHAR(39)
SET @SQL=@SQL+'
			GROUP BY bi.BillNumberId,
					bi.BillDate,
					bi.BillCode,
					L.BTypeId,
					bi.ATypeId,
					L.STypeId,
					bi.Comment,
					bi.RedWord,
					L.BillType,
					bi.IfMulAccount 
					
					
		 
)B WHERE ISNULL(B.Sum_Total,0)<>0
	group by
		B.BillNumberId,
		B.BillDate,
		B.BillCode,
		B.RedWord,
		B.BillType,
		B.Comment,
		B.BTypeId,
		B.ATypeId,
		B.STypeId	
'
--PRINT(@SQL)
EXEC(@SQL)
DROP TABLE #GetSelBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MoneyEtypeXiangDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_MoneyEtypeXiangDetail]
GO






/*
	作者：谢吉康
	日期：2004-12-06
	描述：原来的算法不对，重写
	
	
	作者：覃雨翔
	日期：2012-07-12
	描述：9.0版本修改
*/
CREATE   PROCEDURE Web_MoneyEtypeXiangDetail
(
	@OperatorId	varchar(100),
	@StartDate 	varchar(30),
	@EndDate 	varchar(30),
	@BTypeId 	varchar(100),
	@STypeId 	varchar(8000),
	@ETypeId 	varchar(100),
	@DTypeId 			VARCHAR(MAX),--部门
	@szOrderBy 	varchar(50)='',
	@BillTypeId	varchar(100),		--单据类型列表
	@cid		VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--单位：
CREATE TABLE #GetSelBTypeId(TypeId varchar(100))
INSERT INTO #GetSelBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@BTypeId,2) S,F_GetManDetailBType(@OperatorID) M WHERE S.TypeId = M.TypeId

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@ETypeId,3) S,F_GetManDetailEType(@OperatorID) M WHERE S.TypeId = M.TypeId

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

DECLARE @SQL 		varchar(8000),
		@szOrderSql varchar(1000)

SET @SQL = ''
SET @szOrderSql = ''

SET @SQL = '
		SELECT  BillNumberId,
				BillDate,
				BillCode,
				BTypeId,
				ATypeId,
				STypeId,
				Comment,
				RedWord,
				BillType,
				--ATypeName,
				sum(isnull(sum_total,0)) as sum_total
		FROM (
			SELECT 
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						L.BTypeId,
						CASE
							WHEN bi.IfMulAccount = 1 THEN ''-99999''
							ELSE bi.ATypeId
						END AS ATypeId,
						L.STypeId,
						bi.Comment,
						bi.RedWord,
						L.BillType,
						ATypeName = (SELECT FullName FROM AType WHERE TypeId = bi.ATypeId),
						SUM(
								CASE 
									WHEN (AC.TypeName=''B'' AND AC.UserCode<>''2181'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''1151'')  THEN ISNULL(l.Total,0)
									WHEN (AC.UserCode = ''2131'' AND l.billtype=159) THEN ISNULL(l.Total,0)
									ELSE 0	
								END
							)  AS Sum_Total	
			FROM Listtable l
					INNER JOIN Billindex bi ON l.billnumberid=bi.billnumberid and l.billtype=bi.billtype
					INNER JOIN AC_Items AC ON l.AtypeId=AC.nid
					INNER JOIN #GetSelBTypeId B ON B.TypeId = L.BTypeId
					INNER JOIN #GetManETypeId E ON E.TypeId = L.ETypeId
					INNER JOIN #GetManSTypeId S ON S.TypeId = L.STypeId
					INNER JOIN #GetMandTypeId d ON d.TypeId = L.dTypeId
			WHERE	L.BillType IN (SELECT * FROM f_split('''+@BillTypeId+''','',''))
					AND L.BillDate>='+char(39)+@StartDate+char(39)+'
					AND L.BillDate<='+char(39)+@EndDate+char(39)+'
					AND L.Audited = 1
					AND L.total<>0
					AND (((L.BILLTYPE=181 OR L.BILLTYPE=312) and l.btypeid<>'''') or L.BILLTYPE<>181 AND L.BILLTYPE<>312)
'
IF @cid<>0
	SET @SQL=@SQL+' AND L.CID='+CHAR(39)+@cid+CHAR(39)
SET @SQL=@SQL+'
			GROUP BY
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						L.BTypeId,
						bi.ATypeId,
						L.STypeId,
						bi.Comment,
						bi.RedWord,
						L.BillType,
						bi.IfMulAccount'
IF @ETypeId<>'' AND ISNULL(@BTypeId,'1')='1'--处理没有没往来单位的回款问题，例如：会员储值充值单
BEGIN
	SET @SQL='
		SELECT 
			bi.BillNumberId,
			bi.BillDate,
			bi.BillCode,
			L.BTypeId,
			CASE
				WHEN bi.IfMulAccount = 1 THEN ''-99999''
				ELSE bi.ATypeId
			END AS ATypeId,
			L.STypeId,
			bi.Comment,
			bi.RedWord,
			L.BillType,
			--ATypeName = (SELECT FullName FROM AType WHERE TypeId = bi.ATypeId),
			SUM(
					CASE 
						WHEN (AC.TypeName=''B'' AND AC.UserCode<>''2181'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''1151'')  
						THEN ISNULL(l.Total,0)
						WHEN (AC.UserCode = ''2131'' AND l.billtype=159) THEN ISNULL(l.Total,0)
						ELSE 0	
					END
				)  AS Sum_Total	
FROM Listtable l
		INNER JOIN Billindex bi ON l.billnumberid=bi.billnumberid  and l.billtype=bi.billtype
		INNER JOIN AC_Items AC ON l.AtypeId=AC.nid
		INNER JOIN #GetManETypeId E ON E.TypeId = L.ETypeId
		INNER JOIN #GetManSTypeId S ON S.TypeId = L.STypeId
		INNER JOIN #GetMandTypeId d ON d.TypeId = L.dTypeId
WHERE	(((L.BillType =181 OR L.BillType=312) and l.btypeid='''') )
		AND L.BillDate>='+char(39)+@StartDate+char(39)+'
		AND L.BillDate<='+char(39)+@EndDate+char(39)+'
		AND L.Audited = 1
		AND L.total<>0
	'
	IF @cid<>0
	SET @SQL=@SQL+' AND L.CID='+CHAR(39)+@cid+CHAR(39)
end
IF @ETypeId<>'' AND ISNULL(@BTypeId,'1')='1'
SET @SQL=@SQL+'
			GROUP BY
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						L.BTypeId,
						bi.ATypeId,
						L.STypeId,
						bi.Comment,
						bi.RedWord,
						L.BillType,
						bi.IfMulAccount '
IF @ETypeId='' OR ISNULL(@BTypeId,'1')<>'1'
SET @SQL=@SQL+') A 
	WHERE A.sum_total<>0
	 GROUP BY
				BillNumberId,
				BillDate,
				BillCode,
				BTypeId,
				Comment,
				RedWord,
				ATypeId,
				STypeId,				
				BillType
				--,
				--ATypeName '


SET @SQL=@SQL+'       
        UNION ALL
		SELECT  BillNumberId,
				BillDate,
				BillCode,
				BTypeId,
				ATypeId,
				STypeId,
				Comment,
				RedWord,
				BillType,
				--ATypeName,
				sum(isnull(sum_total,0)) as sum_total
		FROM (
			SELECT 
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						L.BTypeId,
						CASE
							WHEN bi.IfMulAccount = 1 THEN ''-99999''
							ELSE ac.nid
						END AS ATypeId,
						L.STypeId,
						bi.Comment,
						bi.RedWord,
						L.BillType,
						ATypeName = (SELECT FullName FROM ac_items WHERE nTypeId = ac.ntypeid),
						SUM(
								CASE 
									WHEN (AC.TypeName=''B'' AND AC.UserCode<>''2181'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''1151'')  THEN ISNULL(l.Total,0)
									WHEN (AC.UserCode = ''2131'' AND l.billtype=159) THEN ISNULL(l.Total,0)
									ELSE 0	
								END
							)  AS Sum_Total	
			FROM Listtable l
			INNER JOIN Coupon_BillIndex bi ON l.billnumberid=bi.billnumberid and l.billtype=bi.billtype
			INNER JOIN AC_Items AC ON l.AtypeId=AC.nid
			INNER JOIN #GetSelBTypeId B ON B.TypeId = L.BTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = L.ETypeId
			INNER JOIN #GetManSTypeId S ON S.TypeId = L.STypeId
			INNER JOIN #GetMandTypeId d ON d.TypeId = L.dTypeId
	WHERE	L.BillType IN (SELECT * FROM f_split('''+@BillTypeId+''','',''))
			AND L.BillDate>='+char(39)+@StartDate+char(39)+'
			AND L.BillDate<='+char(39)+@EndDate+char(39)+'
			AND L.Audited = 1
			AND L.total<>0
'

IF @cid<>0
	SET @SQL=@SQL+' AND L.CID='+CHAR(39)+@cid+CHAR(39)
SET @SQL=@SQL+'
			GROUP BY
						bi.BillNumberId,
						bi.BillDate,
						bi.BillCode,
						L.BTypeId,
						bi.ATypeId,
						L.STypeId,
						bi.Comment,
						bi.RedWord,
						L.BillType,
						bi.IfMulAccount,
						ac.ntypeid,
						ac.nid
						'			
--IF @ETypeId='' OR ISNULL(@BTypeId,'1')<>'1'
SET @SQL=@SQL+') A 
	WHERE A.sum_total<>0
	 GROUP BY
				BillNumberId,
				BillDate,
				BillCode,
				BTypeId,
				Comment,
				RedWord,
				ATypeId,
				STypeId,				
				BillType
				--,
				--ATypeName '							
				


--PRINT(@SQL)
EXEC(@SQL)



DROP TABLE #GetSelBTypeId,#GetManETypeId,#GetManDTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Msg_ConnectServerAndDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Msg_ConnectServerAndDelete]
GO













/****** Object:  Stored Procedure dbo.Web_Msg_ConnectServerAndDelete    Script Date: 2002-6-20 10:14:55 ******/



CREATE PROCEDURE Web_Msg_ConnectServerAndDelete
(
  @szConnectID VARCHAR(30)
)
--@encode$--
AS
UPDATE Msg_Online SET LatestConnectTime = GETDATE() WHERE ConnectID = @szConnectID

DELETE Msg_Online WHERE DATEDIFF(second,LatestConnectTime,GETDATE()) > 120







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Msg_DeleteOnlineUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Msg_DeleteOnlineUser]
GO













/****** Object:  Stored Procedure dbo.Web_Msg_DeleteOnlineUser    Script Date: 2002-6-20 10:14:55 ******/



CREATE PROCEDURE Web_Msg_DeleteOnlineUser
(
  @szConnectID VARCHAR(30)
)
--@encode$--
AS
DELETE Msg_Online WHERE ConnectID = @szConnectID















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Msg_GetMsg]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Msg_GetMsg]
GO













/****** Object:  Stored Procedure dbo.Web_Msg_GetMsg    Script Date: 2002-6-20 10:14:55 ******/



/*
获取消息
*/

CREATE PROCEDURE Web_Msg_GetMsg
(
  @EmployeeID VARCHAR(30)
)
--@encode$--
AS
SELECT * FROM Msg_MessageList WHERE GetEmployeeID = @EmployeeID AND IsRead = 0
UPDATE Msg_MessageList SET IsRead = 1 WHERE GetEmployeeID = @EmployeeID















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Msg_GetOnlineUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Msg_GetOnlineUser]
GO













/****** Object:  Stored Procedure dbo.Web_Msg_GetOnlineUser    Script Date: 2002-6-20 10:14:55 ******/



/*
返回在线用户
*/
CREATE PROCEDURE Web_Msg_GetOnlineUser
(
  @szConnectID VARCHAR(30)
)
--@encode$--
AS
SELECT * FROM Msg_Online















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Msg_RegisterOnlineUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Msg_RegisterOnlineUser]
GO



/*
登记一个新的用户
*/
CREATE  PROCEDURE Web_Msg_RegisterOnlineUser
(
  @szConnectID VARCHAR(30),
  @szUserName VARCHAR(66),
  @szUnit VARCHAR(100),
  @szIP VARCHAR(15)
)
--@encode$--
AS
IF EXISTS(SELECT * FROM Msg_Online WHERE ConnectID = @szConnectID)
  UPDATE Msg_Online SET State='正常',LatestConnectTime = GETDATE(),LoginTime = GETDATE(),UserName = @szUserName,Unit = @szUnit,IP = @szIP WHERE ConnectID = @szConnectID
ELSE
  INSERT INTO Msg_Online (ConnectID,LatestConnectTime,LoginTime,UserName,Unit,IP,State) VALUES(@szConnectID,GETDATE(),GETDATE(),@szUserName,@szUnit,@szIP,'正常')

--清除3分钟30秒内没有连接的用户
DELETE Msg_Online WHERE DATEDIFF(second,LatestConnectTime,GETDATE()) > 120



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Msg_SearchList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Msg_SearchList]
GO













/****** Object:  Stored Procedure dbo.Web_Msg_SearchList    Script Date: 2002-6-20 10:14:55 ******/


CREATE PROCEDURE Web_Msg_SearchList
(
  @szEmployeeID VARCHAR(30),	--员工ID
  @nMode INT			--0表示所有消息，1表示查询接收消息，2表示发出消息 
)
--@encode$--
AS


IF @nMode=0
  BEGIN
    SELECT a.*,'接收发出' AS Status FROM Msg_MessageList AS a WHERE 
      (SendEmployeeID = @szEmployeeID AND IsSendDelete=0)
       OR
      (GetEmployeeID = @szEmployeeID AND IsGetDelete=0)
    ORDER BY MessageDate DESC
  END

IF @nMode=1
  BEGIN
    SELECT TOP 12 a.*,'接收' AS Status FROM Msg_MessageList AS a WHERE GetEmployeeID = @szEmployeeID AND IsGetDelete=0 ORDER BY MessageDate DESC    
  END

IF @nMode=2
  BEGIN
    SELECT TOP 12 a.*,'发出' AS Status FROM Msg_MessageList AS a WHERE SendEmployeeID = @szEmployeeID AND IsSendDelete=0 ORDER BY MessageDate DESC
  END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Msg_SendMsg]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Msg_SendMsg]
GO













/****** Object:  Stored Procedure dbo.Web_Msg_SendMsg    Script Date: 2002-6-20 10:14:55 ******/



CREATE PROCEDURE Web_Msg_SendMsg
(
  @szComment VARCHAR(1000), 
  @szSendEmployeeID VARCHAR(30),
  @szSendEmployeeName VARCHAR(50),
  @szGetEmployeeID VARCHAR(1000),
  @szGetEmployeeName VARCHAR(50)
)
--@encode$--
AS
DECLARE @tempID VARCHAR(30)
DECLARE @tempName VARCHAR(100)

/*删除7天以前的所有信息*/
DELETE FROM Msg_MessageList WHERE DATEDIFF(day,MessageDate,GETDATE()) > 7

IF LTRIM(RTRIM(LEN(LTRIM(RTRIM(@szGetEmployeeID))))) <> 0
BEGIN
  WHILE CHARINDEX(',',@szGetEmployeeID,1) <> 0
  BEGIN
    IF CHARINDEX(',',@szGetEmployeeID,1) > 1
    BEGIN
      SELECT @tempID = LTRIM(RTRIM(LEFT(@szGetEmployeeID, CHARINDEX(',',@szGetEmployeeID,1)-1)))
      SELECT @tempName = (SELECT ISNULL(FullName,'已删除') FROM Employee WHERE typeID = @tempID)
      INSERT INTO Msg_MessageList (MessageDate,Comment,SendEmployeeID,SendEmployeeName,GetEmployeeID,GetEmployeeName)
                  VALUES(GETDATE(),@szComment,@szSendEmployeeID,@szSendEmployeeName,@tempID,@tempName)
      SELECT @szGetEmployeeID = LTRIM(RTRIM(RIGHT(@szGetEmployeeID,LEN(@szGetEmployeeID)-CHARINDEX(',',@szGetEmployeeID,1))))
    END
  END
END



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Msg_ShowMsg]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Msg_ShowMsg]
GO













/****** Object:  Stored Procedure dbo.Web_Msg_ShowMsg    Script Date: 2002-6-20 10:14:55 ******/

CREATE PROCEDURE Web_Msg_ShowMsg
(
  @szUserName VARCHAR(50)
)
--@encode$--
AS

IF @szUserName = 'NULL'
  BEGIN
    SELECT * FROM Msg_MessageList ORDER BY [ID] DESC
  END
ELSE
  BEGIN
    SELECT * FROM Msg_MessageList WHERE SendEmployeeName = @szUserName OR GetEmployeeName = @szUserName ORDER BY [ID] DESC
  END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MulColAccountSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_MulColAccountSelector
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/28
	Description	: 多栏账设计非明细科目selector的选择内容
*/

CREATE PROCEDURE Web_MulColAccountSelector
(
	@STypeId		VARCHAR(50),		--机构id
	@ATypeId		VARCHAR(50),		--科目id
	@Condition		VARCHAR(MAX),		--已选择的科目typeid字符串
	@chvOperatorID	VARCHAR(50)			--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

IF @Condition<>'' 
	SELECT A.UserCode,
		   A.FullName,
		   A.TypeId,
		   0 AS FDC    --分析方向，默认为0，即双向
	FROM AC_ACCOUNT A
	INNER JOIN SType S ON S.TypeId=A.StypeId 
	INNER JOIN F_LineAccount(@chvOperatorID,'') F  ON F.Typeid=A.TypeId AND F.Stypeid=S.VerifyID
	WHERE A.StypeId=@STypeId AND 
		  A.TypeId LIKE @ATypeId+'%' AND 
		  A.SonNum=0 AND
		  A.Deleted=0 AND 
		  NOT EXISTS (SELECT a 
					  FROM (SELECT a FROM F_Split(@Condition,',')) b 
					  WHERE b.a=A.TypeId )
	ORDER BY A.UserCode
ELSE
	SELECT A.UserCode,
		   A.FullName,
		   A.TypeId,
		   0 AS FDC 
	FROM AC_ACCOUNT A
	INNER JOIN SType S ON S.TypeId=A.StypeId 
	INNER JOIN F_LineAccount(@chvOperatorID,'') F  ON F.Typeid=A.TypeId AND F.Stypeid=S.VerifyID
	WHERE A.StypeId=@STypeId AND 
		  A.TypeId LIKE @ATypeId+'%' AND 
		  A.SonNum=0 AND
		  A.Deleted=0
	ORDER BY A.UserCode
		  
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MulColAssistSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_MulColAssistSelector
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/23
	Description	: 多栏账设计非明细科目selector的选择内容
*/

CREATE PROCEDURE Web_MulColAssistSelector
(
    @Ascid			INT,
    @Condition		VARCHAR(MAX),
    @chvOperatorID	VARCHAR(50),
    @Stypeid		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON
 --判断独立分支间只允许存在买卖关系
DECLARE @reStype VARCHAR(10)
SELECT @reStype=SubValue FROM dbo.sysdata WHERE SubName='innerstypesaleralation'

IF(@Ascid=1)--分支机构
	BEGIN
		SELECT
			A.TypeId, 
			A.UserCode,
			A.FullName,
			0 FDC
		FROM SType A
		INNER JOIN F_GetAllManagerBaseTypeId('',11,@chvOperatorID) F ON F.TypeId=A.TypeId AND A.sonnum=0 AND A.deleted=0 AND ((@reStype=1 AND A.VerifyID=@Stypeid) OR (@reStype=0 AND 1=1))
		WHERE A.TypeId NOT IN(SELECT A FROM f_split(@Condition,','))
		ORDER BY A.UserCode
	END
ELSE IF(@Ascid=2)--部门
	BEGIN
		SELECT 
			A.TypeId, 
			A.UserCode,
			A.FullName,
			0 FDC
		FROM Department A
		INNER JOIN F_GetAllManagerBaseTypeId('',9,@chvOperatorID) F ON F.TypeId=A.TypeId AND A.sonnum=0 AND A.deleted=0 
		WHERE A.TypeId NOT IN(SELECT A FROM f_split(@Condition,','))
		ORDER BY A.UserCode
	END
ELSE IF(@Ascid=3)--职员
	BEGIN
		SELECT 
			A.TypeId, 
			A.UserCode,
			A.FullName,
			0 FDC
		FROM employee A
		INNER JOIN F_GetAllManagerBaseTypeId('',3,@chvOperatorID) F ON F.TypeId=A.TypeId AND A.sonnum=0 AND A.deleted=0 
		WHERE A.TypeId NOT IN(SELECT A FROM f_split(@Condition,','))
		ORDER BY A.UserCode
	END
ELSE IF(@Ascid=4)--往来单位
	BEGIN
		SELECT 
			A.TypeId, 
			A.UserCode,
			A.FullName,
			0 FDC
		FROM btype A
		INNER JOIN F_GetAllManagerBaseTypeId('',2,@chvOperatorID) F ON F.TypeId=A.TypeId AND A.sonnum=0 AND A.deleted=0 
		WHERE A.TypeId NOT IN(SELECT A FROM f_split(@Condition,','))
		ORDER BY A.UserCode
	END
ELSE--自定义辅助核算
	BEGIN
		SELECT 
			A.TypeId, 
			A.UserCode,
			A.FullName,
			0 FDC
		FROM Ac_Assist_CheckItemsDetail A
		INNER JOIN F_GetAllAssistCheckItemsDetail('',@Ascid,@chvOperatorID) F ON F.TypeId=A.TypeId AND A.AscIds=@Ascid AND A.SonNum=0
		WHERE A.TypeId NOT IN(SELECT A FROM f_split(@Condition,','))
		ORDER BY A.UserCode
	END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MulColAutoSortAssist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_MulColAutoSortAssist
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/23
	Description	: 多栏账核算辅助项自动排列
*/

CREATE PROCEDURE Web_MulColAutoSortAssist
(
    @Ascid			INT,
    @stypeid		VARCHAR(50),
    @chvOperatorID	VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN
	DECLARE		@AssistCode	VARCHAR(50),
				@SQL		NVARCHAR(MAX)='SELECT TOP 20 USERCODE,0 AS FDC,FULLNAME,a.TYPEID FROM '
			
	SELECT @AssistCode=USERCODE FROM Ac_Assist_CheckItems WHERE ASCIDS=@Ascid
	IF @AssistCode='01'
		BEGIN
			DECLARE @result VARCHAR(5)
			SELECT @result=SubValue FROM dbo.sysdata WHERE SubName='innerstypesaleralation'
			IF @result='0'
				SET @SQL+='STYPE a
	               JOIN 
				   (
					 SELECT TypeId
					 FROM F_GetAllManagerBaseTypeId('''',11,'''+@chvOperatorID+''') 
				   ) c ON a.TypeId=c.TypeId
		           WHERE SONNUM=0 AND DELETED=0'
		    ELSE 
				SET @SQL+='STYPE a
	               JOIN 
				   (
					 SELECT TypeId
					 FROM F_GetAllManagerBaseTypeId('''',11,'''+@chvOperatorID+''') 
				   ) c ON a.TypeId=c.TypeId
		           WHERE SONNUM=0 AND DELETED=0 AND VerifyID='''+@stypeid+''' '
		END
		
	IF @AssistCode='02'
		SET @SQL+='DEPARTMENT a
		           JOIN 
				   (
					 SELECT TypeId
					 FROM F_GetAllManagerBaseTypeId('''',9,'''+@chvOperatorID+''') 
				   ) c ON a.TypeId=c.TypeId
		           WHERE SONNUM=0 AND DELETED=0'
	IF @AssistCode='03'
		SET @SQL+='EMPLOYEE a
				   JOIN 
				   (
					 SELECT TypeId
					 FROM F_GetAllManagerBaseTypeId('''',3,'''+@chvOperatorID+''') 
				   ) c ON a.TypeId=c.TypeId
				   WHERE SONNUM=0 AND DELETED=0'
	IF @AssistCode='04'
		SET @SQL+='BTYPE a
				   JOIN 
				   (
					 SELECT TypeId
					 FROM F_GetAllManagerBaseTypeId('''',2,'''+@chvOperatorID+''') 
				   ) c ON a.TypeId=c.TypeId
				   WHERE  SONNUM=0 AND DELETED=0'
	IF(@Ascid>4)
		BEGIN
			SET @SQL+='Ac_Assist_CheckItemsDetail A
INNER JOIN dbo.F_GetAllAssistCheckItemsDetail('''','+CAST(@Ascid AS VARCHAR)+','''+@chvOperatorID+''') F ON F.TypeId=A.TypeId AND A.SonNum=0'
		END
	SET @SQL+=' ORDER BY USERCODE'
	EXEC (@SQL)
END

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MulColOriAssistQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_MulColOriAssistQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/31
	Description	: 查询费明细科目辅助核算项原币的多栏账
*/
CREATE PROCEDURE Web_MulColOriAssistQuery
(
    @STypeId 			VARCHAR(50),		---分支机构ID
    @AssistId			BIGINT,				---方案id
    @fyear				INT,
	@FPeriodStart		INT,				---起始期间
	@FPeriodEnd			INT,				---结束期间   
	@IsBalanceNull		BIT,				-- 无发生额且无余额不显示 1：是 0：否
	@IsNull				BIT,				---无发生额不显示 1：是 0：否
	@IsPost				BIT,				---是否显示未过账凭证 1：是 0：否
	@chvOperatorID      VARCHAR(50)			---操作员ID
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE 
		@ATypeId			VARCHAR(50),                ---方案查询科目id
		@AssistUserCode		VARCHAR(200),				---方案中核算项的名称
		@Fdc				VARCHAR(5),					---该科目的余额方向
		@iniFYear			VARCHAR(5),				    --启用年度
		@FPeriod			INT,						---启用期间
		@SQL				NVARCHAR(MAX),              ---查询各个期间的动态sql
		@Balance			 NUMERIC(24, 10) ,				---期初余额
		@tempBalance		 NUMERIC(24, 10) ,
		@tempPeriodS		INT=@FPeriodStart,
		@tempPeriodE		INT=@FPeriodEnd,
		@Cids				VARCHAR(MAX),				---要分析的币别
		@Ascid				INT,						 --add by dongzhan 2012.10.30 
		@LimitOwnVoucher	INT=0--仅能查看本人制单的会计凭证
		
	SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@chvOperatorID


	---获取年度和期间
	SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	IF @iniFYear=@Fyear
		SELECT @Fperiod=SFPeriod from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	ELSE 
		SELECT @Fperiod=MIN(CONVERT(INT,FPeriod)) FROM dbo.Ac_Period
	-----------------------------------------该职员权限-----------------------------------------------------------------------------------
	SELECT @Ascid=ASCID FROM Ac_MulColumnAccount WHERE ASSISTID=@AssistId
	CREATE TABLE #tempRight(TYPEID VARCHAR(50))
	DECLARE @sqlman VARCHAR(8000) 
	IF @Ascid=1 ---分支机构
		SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',11,@chvOperatorID,'#tempRight')
	ELSE IF @Ascid=2 ---部门
	   SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',9,@chvOperatorID,'#tempRight')
	ELSE IF @Ascid=3 ---职员
		SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',3,@chvOperatorID,'#tempRight')
	ELSE IF @Ascid=4 ---往来单位
	    SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',2,@chvOperatorID,'#tempRight')
	 ELSE---自定义辅助核算
		BEGIN
			INSERT INTO #tempRight(TYPEID)
			SELECT TypeId FROM dbo.F_GetAllAssistCheckItemsDetail('',@Ascid,@chvOperatorID)
	    END
	EXEC(@sqlman)
	---------------------------------------------------------------------------------------------------------------------------------------
	---获取方案中的科目
	SELECT @ATypeId=ATYPEID FROM dbo.Ac_MulColumnAccount WHERE ASSISTID=@AssistId
	---该科目的方向
	SELECT @Fdc=CASE 
						WHEN FDC=1 THEN '借'
						ELSE '贷'
					END
	 FROM dbo.Ac_Account 
	 WHERE STYPEID=@STypeId AND 
		   TYPEID=@ATypeId
	 ---获取方案中的辅助核算项目usercode
	SELECT @AssistUserCode=b.USERCODE
	FROM dbo.Ac_MulColumnAccount a
	JOIN  Ac_Assist_CheckItems b ON a.ASCID=b.ASCIDS
	WHERE ASSISTID=@AssistId
	
	---要分析的币别
	 SELECT @Cids=CIDS
	 FROM dbo.Ac_MulColumnAccount 
	 WHERE ASSISTID=@AssistId
	
	 CREATE TABLE #MulColCid
	 (
		CID			INT,
		FULLNAME	VARCHAR(200),
		USERCODE	VARCHAR(200)
	 )
	 INSERT INTO #MulColCid
	 SELECT a.CID,
			a.FullName,
			a.USERCODE
	 FROM Ac_Currency a
	 JOIN 
	 (
		SELECT a FROM F_Split(@Cids,',')
	 ) b ON a.CID=b.a
	
	-------------------------------无论选择过账与否,都重新生成一个临时科目余额表,todo 等佘海源的存储过程-----------------------------------------------------------
	 CREATE TABLE  #tempAcBalanceDetail
	(
		STYPEID             VARCHAR(50),       
		ATYPEID             VARCHAR(50),        
		CID                 INT,               
		ASCIDS              INT,                
		FIELDVALUE          VARCHAR(50),        
		FDEBIT				 NUMERIC(24, 10) ,		
		FDEBITFOR			 NUMERIC(24, 10) ,		
		FCREDIT				 NUMERIC(24, 10) ,		
		FCREDITFOR			 NUMERIC(24, 10) ,		
		INITOTAL			 NUMERIC(24, 10) ,	
		INITOTALFOR			 NUMERIC(24, 10) ,		
		FENDBALANCE			 NUMERIC(24, 10) ,		
		FENDBALANCEFOR		 NUMERIC(24, 10) ,		
		FYEAR               VARCHAR(10),       
		FPERIOD             INT          
	)
	INSERT INTO #tempAcBalanceDetail
	EXEC WEB_AcAssistBalanceDetailFromVoucher @IsPost,@FYear,@STypeId
	--权限控制，删除不在权限范围类的数据
	DELETE FROM #tempAcBalanceDetail WHERE ATypeId NOT IN(SELECT Typeid FROM F_LineAccount(@chvOperatorID,@STypeId) )
-----------------------------------------要分析的明细科目及科目要分析的方向--------------------------------------------------------------------
	CREATE TABLE #temp1
	(
	   STYPEID			VARCHAR(50),  --分支机构id
	   ATYPEID			VARCHAR(50),  --科目id
	   ASCID			INT,		  --核算项id
	   ASCIDUSERCODE	VARCHAR(200),  --核算项usercode，关联AC_VOUCHER_BILL_ASSIST_CHECKITEMS用
	   PROTYPEID		VARCHAR(50),  --要分析的项目id
	   PROFDC			INT,		  --要分析的项目的方向
	   PROUSERCODE		VARCHAR(200), --要分析的项目usercode
	   PROFULLNAME		VARCHAR(200)  --要分析的项目fullname
	)
	SET @SQL='INSERT INTO #temp1
			  SELECT a.STYPEID,
					 a.ATYPEID,
					 a.ASCID,
					 @AssistUserCode,
					 d.TYPEID,
					 b.FDC,
					 d.USERCODE,
					 d.FULLNAME 
			  FROM Ac_MulColumnAccount a
			  JOIN AC_MULCOLUMNACCOUNT_ASSIST b ON a.ASSISTID=b.ASSISTID '
	IF EXISTS(SELECT 1 FROM #tempRight)                    --modify by dongzhan 2013.1.28  权限函数改变，权限临时表判断也改变
		SET @SQL+='JOIN #tempRight e ON b.FVALUE=e.TYPEID ' 
	IF @AssistUserCode='01'
		SET @SQL+='JOIN STYPE d ON b.FVALUE=d.TYPEID'
	ELSE IF @AssistUserCode='02'
		SET @SQL+='JOIN DEPARTMENT d ON b.FVALUE=d.TYPEID'
	ELSE IF @AssistUserCode='03'
		SET @SQL+='JOIN EMPLOYEE d ON b.FVALUE=d.TYPEID'
	ELSE IF @AssistUserCode='04'
		SET @SQL+='JOIN BTYPE d ON b.FVALUE=d.TYPEID'
	ELSE 
		SET @SQL+='INNER JOIN Ac_Assist_CheckItemsDetail D ON D.TypeId=b.FVALUE'	
	SET @SQL+=' WHERE a.ASSISTID=@AssistId'
	EXEC sp_executesql @SQL,N'@AssistUserCode VARCHAR(200),@AssistId BIGINT', @AssistUserCode,@AssistId
	-----------------------------------------------------取出凭证，放入临时表----------------------------------------------------------
	CREATE TABLE #tempMulCol
	(
		ID						INT IDENTITY(1,1),		--Modify 12-10-19，原来取的是AC_VOUCHER_BILL的ID，现在为了最后一步排序，重新生成					
		FPERIOD 				INT,					--期间
		VOUCHERTIME				VARCHAR(10),			--记账日期
		FSERIALNAME				VARCHAR(200),			--凭证字号
		SUMMARY					VARCHAR(400),			--摘要				
		FDC						VARCHAR(5),				--方向
		BALANCE					 NUMERIC(24, 10) ,			--本币余额
		PROTYPEID				VARCHAR(50),			--要分析的项目id
		PROFDC					INT,					--要分析的项目方向
		CID						INT,					--币别
		SELFBORROW				 NUMERIC(24, 10) ,
		ORIBORROW				 NUMERIC(24, 10) ,
		SELFLEND				 NUMERIC(24, 10) ,
		ORILEND					 NUMERIC(24, 10),
		ETypeId					VARCHAR(50)	NOT NULL DEFAULT('')--制单人 
	)
	SET @SQL='INSERT INTO #tempMulCol(FPERIOD,VOUCHERTIME,FSERIALNAME,SUMMARY,FDC,PROTYPEID,PROFDC,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND,ETypeId)
			SELECT a.FPERIOD,
				   CONVERT(VARCHAR(10),BILLDATE,120),
				  CASE WHEN @LimitOwnVoucher=1 AND d.ETypeId<>@chvOperatorID THEN ''****'' ELSE e.FULLNAME+''-''+CONVERT(VARCHAR(10),d.FLOWNO) END,
					CASE WHEN @LimitOwnVoucher=1 AND d.ETypeId<>@chvOperatorID THEN ''****'' ELSE dbo.F_GetSummaryByLimit(a.ID,@chvOperatorID,a.STypeID,a.Summary) END SUMMARY,

				   @Fdc,
				   c.PROTYPEID,
				   c.PROFDC,
				   a.CID,
				   a.FDEBITTOTAL,
				   a.FDEBITTOTALFOR,
				   a.FCREDITTOTAL,
				   a.FCREDITTOTALFOR,
				   d.ETypeId
			FROM AC_VOUCHER_BILL a 
			INNER JOIN F_LineAccount('''+@chvOperatorID+''','''+@STypeId+''') F1 ON F1.TypeID=a.ATypeId AND F1.Stypeid=a.STypeId
			JOIN Ac_Voucher_Bill_Assist_CheckItems b ON a.BILLNUMBERID=b.BILLNUMBERID AND a.ID=b.VBID 
			JOIN #temp1 c ON a.ATYPEID=c.ATYPEID AND b.TYPENAME=c.ASCIDUSERCODE AND c.PROTYPEID=b.TYPEID 
			JOIN dbo.Ac_Voucher d ON a.BILLNUMBERID=d.BILLNUMBERID AND d.FYEAR=@FYear AND d.FPERIOD >=@FPeriodStart AND d.FPERIOD<=@FPeriodEnd AND FCHECKED <> -1 '
	IF @IsPost=0
		SET @SQL+=' AND IFCHECK=''t'' '
	SET @SQL+='	JOIN AC_VOUCHER_GROUP e ON d.VGID = e.VGID 
			    JOIN #MulColCid f ON a.CID=f.CID
			    WHERE a.STYPEID=@STypeId
				ORDER BY d.FPERIOD,d.BILLDATE,a.BILLNUMBERID,a.ID'
	EXEC sp_executesql @SQL,N'@FYear VARCHAR(10),@FPeriodStart INT,@FPeriodEnd INT,@Fdc VARCHAR(10),@STypeId VARCHAR(50),@LimitOwnVoucher INT,@chvOperatorID VARCHAR(50)',@FYear,@FPeriodStart,@FPeriodEnd,@Fdc,@STypeId,@LimitOwnVoucher,@chvOperatorID
	------------------根据查询条件剔除不符合的科目 
	IF @IsBalanceNull=1 OR @IsNull=1
		BEGIN
			CREATE TABLE #temp2
			(
			    PROTYPEID		VARCHAR(50),	---分析的辅助核算项的选择值
			    BALANCE			 NUMERIC(24, 10) 	---本期余额
			)
			INSERT INTO #temp2
			SELECT c.PROTYPEID,
				   SUM(ISNULL(FENDBALANCE,0)) AS BALANCE
			FROM 
			(
				SELECT a.STYPEID,
					   a.ATYPEID,
					   a.ASCID,
					   a.PROTYPEID,
					   a.CID,
				   ISNULL(MAX(FPERIOD),@FPeriodEnd) AS FPERIOD
				FROM
				(
				   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.PROTYPEID=b.FIELDVALUE AND a.ASCID=b.ASCIDS AND 
																   b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodEnd AND b.CID=a.CID
				GROUP BY a.STYPEID,a.ATYPEID,a.PROTYPEID,a.CID,a.ASCID	
			) c 
			LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.PROTYPEID=d.FIELDVALUE AND c.ASCID=d.ASCIDS AND 
																   d.FYEAR=@FYear AND c.FPERIOD=d.FPERIOD AND c.CID=d.CID
			GROUP BY c.PROTYPEID
		
		   	CREATE TABLE #temp3
			(
			    PROTYPEID		VARCHAR(50),	---分析的辅助核算项的选择值
			    PERIODCHANGE	 NUMERIC(24, 10) ,	---本期发生额
			    BALANCE			 NUMERIC(24, 10) 	---本期余额
			)
			INSERT INTO #temp3
		    SELECT a.PROTYPEID,
				   ISNULL(b.PERIODCHANGE,0),
				   a.BALANCE
			FROM #temp2 a
			LEFT JOIN 
					(
						SELECT  PROTYPEID,
								SUM(ABS(ISNULL(SELFBORROW,0)))+SUM(ABS(ISNULL(SELFLEND,0))) AS PERIODCHANGE
						FROM #tempMulCol
						GROUP BY PROTYPEID
					) b ON a.PROTYPEID=b.PROTYPEID
		
		    SELECT PROTYPEID
		    INTO #temp4
		    FROM #temp3
		    WHERE	((@IsNull=1 AND PERIODCHANGE>0) OR @IsNull=0) AND
					((@IsBalanceNull=1 AND BALANCE!=0 OR PERIODCHANGE>0) OR @IsBalanceNull=0) 
					
			DELETE FROM #temp1  WHERE NOT EXISTS (SELECT 1 FROM #temp4 b WHERE #temp1.PROTYPEID=b.PROTYPEID)
		END
    ---分析项目与借贷交叉连接，以待后面行转列：还要判断分析方向，控制列的显示列数
    CREATE TABLE #Projects
    (
       STYPEID			VARCHAR(50),  --分支机构id
	   ATYPEID			VARCHAR(50),  --科目id
	   ASCID			INT,		  --核算项id
	   ASCIDUSERCODE	VARCHAR(50),  --核算项usercode，关联AC_VOUCHER_BILL_ASSIST_CHECKITEMS用
	   PROTYPEID		VARCHAR(50),  --要分析的项目id
	   FDC				INT,		  --要分析的项目的方向
	   FLAG				INT,
	   COLNAME			VARCHAR(max),  --行转列的列名
	   CID				INT
    )
     SET @SQL='INSERT INTO #Projects
			  SELECT STYPEID,
					 ATYPEID,
					 ASCID,
					 ASCIDUSERCODE,
					 PROTYPEID,
					 d.FDC,
					 e.FLAG,
					 SUBSTRING(COLNAME+c.PROUSERCODE+e.USERCODE,0,128),
					 e.CID
			  FROM #temp1 c,'
	IF (SELECT COUNT(1) FROM ( SELECT PROFDC FROM #temp1 GROUP BY PROFDC) a)=2 OR (SELECT TOP 1 1 FROM #temp1 WHERE PROFDC=0)=1
		SET @SQL+='( SELECT ''borrow'' AS COLNAME,1 AS FDC 
					UNION ALL
					SELECT ''lend'' AS COLNAME,-1 AS FDC 
					) d,'
	ELSE IF (SELECT TOP 1 1 FROM #temp1 WHERE PROFDC=1)=1
		SET @SQL+='( SELECT ''borrow'' AS COLNAME,1 AS FDC) d,'
	ELSE 
		SET @SQL+='( SELECT ''lend'' AS COLNAME,-1 AS FDC) d,'		
	
	SET @SQL+='( SELECT CID,
						USERCODE,
						FLAG
				 FROM (
						 SELECT CID,
								USERCODE,
								FLAG 
						 FROM 
						 (
							  SELECT CID,
									 SUBSTRING(USERCODE+CODE,0,128) AS USERCODE,
									 FLAG 
							  FROM #MulColCid,
    						 (SELECT ''ben'' AS CODE,-1 AS FLAG
							 UNION 
							 SELECT ''yuan'' AS CODE,1 AS FLAG) a
						 ) c
					 ) b
			   ) e'
	EXEC(@SQL)
	
	----------------------------------------------------凭证表左边的统计信息---------------------------------------------------------------------------
	SELECT COLNAME,
		   FDC 
	INTO #tempColName1 
	FROM 
	(
		  SELECT 'borrow' AS COLNAME,1 AS FDC 
		  UNION ALL
		  SELECT 'lend' AS COLNAME,-1 AS FDC 
	) a
   
	SELECT CID,
		   USERCODE,
		   FLAG
	INTO #tempColName2
	FROM 
	(	SELECT CID,
		       USERCODE,
		       FLAG
		FROM 
		(
		  SELECT CID,
				 USERCODE+CODE AS USERCODE,
				 FLAG
		  FROM #MulColCid,
			(SELECT 'ben' AS CODE,-1 AS FLAG
	         UNION 
	         SELECT 'yuan' AS CODE,1 AS FLAG) a
		) c
		UNION ALL 
		SELECT 0 AS CID,'self' AS USERCODE,0 AS FLAG
	) b
   
	--#temp表中的colname值就是结果表中的列名，即该表有多少条数据，在结果表中就有多少列显示
	SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,
		   FDC,
		   CID,
		   FLAG
	INTO #tempColName
	FROM #tempColName1,#tempColName2
	
	--行转列的时候用
	DECLARE @LeftTurnCol VARCHAR(MAX)
	SELECT @LeftTurnCol=(ISNULL(@LeftTurnCol+'],[','') +  COLNAME) 
	FROM #tempColName GROUP BY COLNAME 
	SET @LeftTurnCol='['+@LeftTurnCol+']'
	
	--动态添加列的时候用
	DECLARE @LeftDynCol VARCHAR(MAX)
	SELECT @LeftDynCol=(ISNULL(@LeftDynCol+']  NUMERIC(24, 10) ,[','') +  COLNAME) 
	FROM #tempColName GROUP BY COLNAME 
	SET @LeftDynCol='ALTER TABLE #MulCol ADD ['+@LeftDynCol+']  NUMERIC(24, 10) '
	
	CREATE TABLE #LeftGetValue
	(
		ID			   INT,					--凭证明细表的ID
		FPERIOD        INT,					--期间
		COLNAME		   VARCHAR(MAX),		--要转列的列名
		FVALUE          NUMERIC(24, 10) 		--列对应的值
	)
	
	INSERT INTO #LeftGetValue
    SELECT b.ID,
		   b.FPERIOD,
		   a.COLNAME,
		  CASE 
				WHEN a.FDC=1  AND a.CID=b.CID AND a.FLAG=1 THEN ORIBORROW			--当前币种对应的原币借
				WHEN a.FDC=-1 AND a.CID=b.CID AND a.FLAG=1 THEN ORILEND				--当前币种对应的原币贷
				WHEN a.FDC=1  AND a.CID=b.CID AND a.FLAG=-1 THEN SELFBORROW			--当前币种对应的本币借
				WHEN a.FDC=-1 AND a.CID=b.CID AND a.FLAG=-1 THEN SELFLEND			--当前币种对应的本币贷
				WHEN a.FDC=1  AND a.CID=0 THEN SELFBORROW							--借综合本位币
				WHEN a.FDC=-1 AND a.CID=0 THEN SELFLEND								--贷综合本位币
		  END 
    FROM #tempColName a,#tempMulCol b
	------------------------------------------凭证表右边的统计信息--------------------------------------------------------------
	--获取待行转列的列对应的值
	CREATE TABLE #RightGetValue
	(
		ID			   INT,
		FPERIOD        INT,					--期间
		COLNAME		   VARCHAR(MAX),		--要转列的列名
		FVALUE          NUMERIC(24, 10) 		--列对应的值
	)
	INSERT INTO #RightGetValue
	SELECT b.ID,
		   b.FPERIOD,
		   a.COLNAME,
		   CASE
				WHEN a.PROTYPEID=b.PROTYPEID AND a.CID=b.CID  AND a.FDC=1 AND FLAG=1 AND (b.PROFDC=0 OR b.PROFDC=1) THEN ORIBORROW
				WHEN a.PROTYPEID=b.PROTYPEID AND a.CID=b.CID  AND a.FDC=-1 AND FLAG=1 AND (b.PROFDC=0 OR b.PROFDC=-1) THEN ORILEND
				WHEN a.PROTYPEID=b.PROTYPEID AND a.CID=b.CID  AND a.FDC=1 AND FLAG=-1 AND (b.PROFDC=0 OR b.PROFDC=1) THEN SELFBORROW
			    WHEN a.PROTYPEID=b.PROTYPEID AND a.CID=b.CID  AND a.FDC=-1 AND FLAG=-1 AND (b.PROFDC=0 OR b.PROFDC=-1) THEN SELFLEND
		   END
	FROM #Projects a,#tempMulCol b

	DECLARE @RightTurnCol VARCHAR(MAX)
	SELECT @RightTurnCol=(ISNULL(@RightTurnCol+'],[','') +  COLNAME) 
	FROM #Projects GROUP BY COLNAME 
	SET @RightTurnCol='['+@RightTurnCol+']'
	
	DECLARE @RightDynCol VARCHAR(MAX)
	SELECT @RightDynCol=(ISNULL(@RightDynCol+']  NUMERIC(24, 10) ,[','') +  COLNAME) 
	FROM #Projects GROUP BY COLNAME 
	SET @RightDynCol='ALTER TABLE #MulCol ADD ['+@RightDynCol+']  NUMERIC(24, 10) '
	
	----将数据插入临时表
	CREATE TABLE #MulCol
	(
		ID						INT,					
		FPERIOD 				INT,					--期间
		BILLDATE				VARCHAR(10),			--记账日期
		FSERIALNAME				VARCHAR(200),			--凭证字号
		SUMMARY					VARCHAR(400),			--摘要				
		FDC						VARCHAR(5),				--方向
		BALANCE					 NUMERIC(24, 10), 			--本币余额
		ETypeId					VARCHAR(50)	NOT NULL DEFAULT('')--制单人
	)
	EXEC(@LeftDynCol)
	EXEC(@RightDynCol)
	----------------------- 更新余额----------------------------------------------------------------------------------------------------------
	-----------求出期初余额
	CREATE TABLE #IniAccountBeginBalance
	(
	     STYPEID	 VARCHAR(50),
	     TYPEID		 VARCHAR(50),		--明细科目的id	
	     FPERIOD	 INT,
	     CID		 INT,					
	     SELFBORROW	  NUMERIC(24, 10) ,
	     ORIBORROW    NUMERIC(24, 10) ,
	     SELFLEND     NUMERIC(24, 10) ,
	     ORILEND	  NUMERIC(24, 10) 
	)
	---插入的是cid=0，即综合本位币的该科目借和贷
	INSERT INTO #IniAccountBeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
	SELECT a.STYPEID,
		   a.ATYPEID,
		   @FPeriod,
		   0,
		   SUM(ISNULL(FDEBIT,0))      AS SELFBORROW,
		   SUM(ISNULL(FDEBITFOR,0))   AS ORIBORROW,
		   SUM(ISNULL(FCREDIT,0))     AS SELFLEND,
		   SUM(ISNULL(FCREDITFOR,0))  AS ORILEND
	FROM 
	(
	  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
	) a
	LEFT JOIN dbo.AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.CID=b.CID AND b.FYEAR=@FYear AND 
														  b.FPERIOD=@FPeriod AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE 
	GROUP BY a.STYPEID,a.ATYPEID
	---插入各个币别的
	INSERT INTO #IniAccountBeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
	SELECT a.STYPEID,
		   a.ATYPEID,
		   @FPeriod,
		   a.CID,
		   SUM(ISNULL(FDEBIT,0))      AS SELFBORROW,
		   SUM(ISNULL(FDEBITFOR,0))   AS ORIBORROW,
		   SUM(ISNULL(FCREDIT,0))     AS SELFLEND,
		   SUM(ISNULL(FCREDITFOR,0))  AS ORILEND
	FROM 
	(
	  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
	) a
	LEFT JOIN dbo.AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.CID=b.CID AND b.FYEAR=@FYear AND 
														  b.FPERIOD=@FPeriod AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE 
	GROUP BY a.STYPEID,a.ATYPEID,a.CID
	
	CREATE TABLE #BeginBalance
	(
	     STYPEID	 VARCHAR(50),
	     TYPEID		 VARCHAR(50),		--明细科目的id	
	     FPERIOD	 INT,
	     CID		 INT,					
	     SELFBORROW	  NUMERIC(24, 10) ,
	     ORIBORROW    NUMERIC(24, 10) ,
	     SELFLEND     NUMERIC(24, 10) ,
	     ORILEND	  NUMERIC(24, 10) ,
	     BALANCE	  NUMERIC(24, 10) 
	)
	IF @FPeriodStart=@FPeriod
		BEGIN
			INSERT INTO #BeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
			SELECT * FROM #IniAccountBeginBalance
		END
	ELSE
		BEGIN
			----插入cid=0的
			INSERT INTO #BeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
			SELECT a.STYPEID,
				   a.ATYPEID,
				   @FPeriodStart AS FPERIOD,
				   0,
				   SUM(ISNULL(FDEBIT,0))+c.SELFBORROW      AS SELFBORROW,
				   SUM(ISNULL(FDEBITFOR,0))+c.ORIBORROW   AS ORIBORROW,
				   SUM(ISNULL(FCREDIT,0))+c.SELFLEND     AS SELFLEND,
				   SUM(ISNULL(FCREDITFOR,0))+c.ORILEND  AS ORILEND
			FROM 
			( 
				 SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			) a
			LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
												a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<@FPeriodStart
			JOIN #IniAccountBeginBalance c ON a.STYPEID=c.STYPEID AND  a.ATYPEID=c.TYPEID AND c.CID=0 
			GROUP BY a.STYPEID,a.ATYPEID,c.SELFBORROW,c.ORIBORROW,c.SELFLEND,c.ORILEND
			---插入各个币别的
			INSERT INTO #BeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
			SELECT a.STYPEID,
				   a.ATYPEID,
				   @FPeriodStart AS FPERIOD,
				   a.CID,
				   SUM(ISNULL(FDEBIT,0))+c.SELFBORROW      AS SELFBORROW,
				   SUM(ISNULL(FDEBITFOR,0))+c.ORIBORROW   AS ORIBORROW,
				   SUM(ISNULL(FCREDIT,0))+c.SELFLEND     AS SELFLEND,
				   SUM(ISNULL(FCREDITFOR,0))+c.ORILEND  AS ORILEND
			FROM 
			( 
				 SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			) a
			LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
												a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<@FPeriodStart
			JOIN #IniAccountBeginBalance c ON a.STYPEID=c.STYPEID AND  a.ATYPEID=c.TYPEID AND a.CID=c.CID
			GROUP BY a.STYPEID,a.ATYPEID,a.CID,c.SELFBORROW,c.ORIBORROW,c.SELFLEND,c.ORILEND
		END
  
	---求出余额    
	SELECT @Balance=SUM(BALANCE)
	FROM 
	(
		SELECT CASE 
				  WHEN e.FPERIOD=@FPeriod AND FLAG=0 THEN ISNULL(INITOTAL,0)
				  ELSE  ISNULL(FENDBALANCE,0)
			   END AS BALANCE  
		FROM
		(
			SELECT c.STYPEID,
				   c.ATYPEID,
				   c.ASCID,
				   c.PROTYPEID,
				   c.CID,
				   CASE 
						WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart AND MAX(FPERIOD)!=@FPeriod THEN @FPeriodStart-1
						ELSE ISNULL(MAX(FPERIOD),@FPeriodStart)
				   END AS FPERIOD,
				   CASE							                                      ----标示取出的的期间到底是该取期初还是期末
						WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart AND ISNULL(MAX(FPERIOD),@FPeriodStart)!=@FPeriod THEN 1
						WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)!=@FPeriodStart AND ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriod AND @FPeriodStart!=@FPeriod THEN 2
						ELSE 0
				   END AS FLAG
			FROM 
			(
			   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			) c 
			LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.ASCID=d.ASCIDS AND c.PROTYPEID=d.FIELDVALUE AND 
												c.CID=d.CID AND d.FYEAR=@FYear AND d.FPERIOD<=@FPeriodStart
			GROUP BY c.STYPEID,c.ATYPEID,c.ASCID,c.PROTYPEID,c.CID
		) e 
		LEFT JOIN #tempAcBalanceDetail f ON e.STYPEID=f.STYPEID AND e.ATYPEID=f.ATYPEID AND e.ASCID=f.ASCIDS AND e.PROTYPEID=f.FIELDVALUE AND 
											e.CID=f.CID AND f.FYEAR=@FYear AND e.FPERIOD=f.FPERIOD
	) f 
 
    
    UPDATE #BeginBalance SET BALANCE=@Balance	
	SET @tempBalance=@BALANCE
			 
	UPDATE #tempMulCol SET @BALANCE+=CASE 
										WHEN @Fdc='借' THEN (ISNULL(BALANCE,0)+ISNULL(SELFBORROW,0)-ISNULL(SELFLEND,0))
										ELSE (ISNULL(BALANCE,0)-ISNULL(SELFBORROW,0)+ISNULL(SELFLEND,0))
									 END,
							BALANCE=@BALANCE,
							FDC=CASE 
									WHEN @Balance=0 THEN '平'
									ELSE @Fdc
								END
	---#MulCol插入数据
	SET @SQL='INSERT INTO #MulCol (ID,FPERIOD,BILLDATE,FSERIALNAME,SUMMARY,FDC,BALANCE,'+@LeftTurnCol+','+@RightTurnCol+',ETypeId)
	      SELECT a.ID,
			     a.FPERIOD,
			     a.VOUCHERTIME,
			     a.FSERIALNAME,
			     a.SUMMARY,
			     a.FDC,
			     a.BALANCE,'
			     +@LeftTurnCol+','
			     +@RightTurnCol+',
			     a.ETypeId
	      FROM #tempMulCol a
	      JOIN
				(
					 SELECT *  FROM  #LeftGetValue  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@LeftTurnCol+')) b
				) b	ON a.ID=b.ID
		  JOIN
				(
				     SELECT *  FROM  #RightGetValue  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@RightTurnCol+')) b
				)c ON a.ID=c.ID'
	EXEC(@SQL)						
	----------------------------------------------期初余额数据插入--------------------------------------------------------------------------------------
	----左边表的期初
	CREATE TABLE #LeftBalance
	(
	   ID		INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	INSERT INTO #LeftBalance
	SELECT -1,
		   a.COLNAME,
		   CASE
			 WHEN a.CID=b.CID AND a.FDC=1 AND a.FLAG=-1  THEN SELFBORROW
			 WHEN a.CID=b.CID AND a.FDC=1 AND a.FLAG=1   THEN ORIBORROW
			 WHEN a.CID=b.CID AND a.FDC=-1 AND a.FLAG=-1 THEN SELFLEND
			 WHEN a.CID=b.CID AND a.FDC=-1 AND a.FLAG=1  THEN ORILEND
			 WHEN a.CID=0 AND a.FDC=1  THEN SELFBORROW
			 WHEN a.CID=0 AND a.FDC=-1 THEN SELFLEND
		   END
	FROM #tempColName a
	LEFT JOIN #BeginBalance b ON a.CID=b.CID 
	
   ---右边表的期初
   ---先获取各分析项目的借贷数据
   CREATE TABLE #IniProjectBegin
   (
       PROTYPEID		VARCHAR(50),
       CID				INT,
       SELFBORROW		 NUMERIC(24, 10) ,
       ORIBORROW		 NUMERIC(24, 10) ,
       SELFLEND			 NUMERIC(24, 10) ,
       ORILEND			 NUMERIC(24, 10) 
   )
    INSERT INTO #IniProjectBegin
	SELECT a.PROTYPEID,
		   a.CID,
	       SUM(ISNULL(FDEBIT,0))      AS SELFBORROW,
		   SUM(ISNULL(FDEBITFOR,0))   AS ORIBORROW,
		   SUM(ISNULL(FCREDIT,0))     AS SELFLEND,
		   SUM(ISNULL(FCREDITFOR,0))  AS ORILEND
	FROM 
	(
	  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
	) a
	LEFT JOIN dbo.AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.CID=b.CID AND b.FYEAR=@FYear AND 
														  b.FPERIOD=@FPeriod AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE 
	GROUP BY a.PROTYPEID,a.CID
   
  
   CREATE TABLE #ProjectBegin
   (
       PROTYPEID		VARCHAR(50),
       CID				INT,
       SELFBORROW		 NUMERIC(24, 10) ,
       ORIBORROW		 NUMERIC(24, 10) ,
       SELFLEND			 NUMERIC(24, 10) ,
       ORILEND			 NUMERIC(24, 10) 
   )
   IF @FPeriodStart=@FPeriod
		INSERT INTO #ProjectBegin
		SELECT * FROM #IniProjectBegin
   ELSE
		INSERT INTO #ProjectBegin
		SELECT a.PROTYPEID,
			   a.CID,
    	       SUM(ISNULL(FDEBIT,0))+c.SELFBORROW      AS SELFBORROW,
			   SUM(ISNULL(FDEBITFOR,0))+c.ORIBORROW   AS ORIBORROW,
			   SUM(ISNULL(FCREDIT,0))+c.SELFLEND     AS SELFLEND,
			   SUM(ISNULL(FCREDITFOR,0))+c.ORILEND  AS ORILEND
		FROM 
		(
		  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
		) a
		LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
											a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<@FPeriodStart
		JOIN #IniProjectBegin c ON a.PROTYPEID=c.PROTYPEID AND a.CID=c.CID
		GROUP BY a.PROTYPEID,a.CID,c.SELFBORROW,c.ORIBORROW,c.SELFLEND,c.ORILEND
   
	CREATE TABLE #RightBalance
	(
	   ID		INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	INSERT INTO #RightBalance
    SELECT -1,
		   a.COLNAME,
		   CASE
			  WHEN a.CID=b.CID AND a.PROTYPEID=b.PROTYPEID AND a.FDC=1 AND FLAG=-1  THEN SELFBORROW
			  WHEN a.CID=b.CID AND a.PROTYPEID=b.PROTYPEID AND a.FDC=1 AND FLAG=1   THEN ORIBORROW
			  WHEN a.CID=b.CID AND a.PROTYPEID=b.PROTYPEID AND a.FDC=-1 AND FLAG=-1 THEN SELFLEND
			  WHEN a.CID=b.CID AND a.PROTYPEID=b.PROTYPEID AND a.FDC=-1 AND FLAG=1  THEN ORILEND
		   END
	FROM #Projects a
	LEFT JOIN #ProjectBegin b ON a.PROTYPEID=b.PROTYPEID AND a.CID=b.CID
	
	----期初数据插入#MulCol
	SET @SQL='INSERT INTO #MulCol (ID,FPERIOD,BILLDATE,FSERIALNAME,SUMMARY,FDC,BALANCE,'+@LeftTurnCol+','+@RightTurnCol+')
			  SELECT -1,
					@FPeriodStart,
					'''',
					'''',
					''期初余额'',
					CASE 
						 WHEN @tempBalance=0 THEN ''平'' 
						 ELSE @Fdc 
				    END,
				    @tempBalance,'
				    +@LeftTurnCol+','
				    +@RightTurnCol+' 
			  FROM 
			  (
				SELECT *  FROM  #LeftBalance  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@LeftTurnCol+')) b
			  ) a
			  JOIN 
			  (
				SELECT *  FROM  #RightBalance  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@RightTurnCol+')) b
			  ) b ON a.ID=b.ID'
	EXEC sp_executesql @SQL,N'@tempBalance  NUMERIC(24, 10) ,@Fdc VARCHAR(5),@FPeriodStart INT',@tempBalance,@Fdc,@FPeriodStart 
	---------------------------------------------------本期合计，本年合计---------------------------------------------------------------------------------------
	------左边的表
	CREATE TABLE #LeftPeriod
	(
	   ID		INT,
	   FPERIOD	INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	CREATE TABLE #LeftYear
	(
	   ID		INT,
	   FPERIOD	INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	CREATE TABLE #tempLeftData
    (  
       TYPEID		  VARCHAR(50),				---明细科目的id
       FPERIOD	      INT,
       CID			  INT,
       SELFBORROW	   NUMERIC(24, 10) ,            ---本期合计本借
       ORIBORROW	   NUMERIC(24, 10) ,			
       SELFLEND		   NUMERIC(24, 10) ,			---本期合计本贷
       ORILEND		   NUMERIC(24, 10) ,
       YSELFBORROW	   NUMERIC(24, 10) ,			---本年累计本借
       YORIBORROW	   NUMERIC(24, 10) ,
       YSELFLEND	   NUMERIC(24, 10) ,			---本年累计本贷
       YORILEND		   NUMERIC(24, 10) ,
       BALANCE		   NUMERIC(24, 10) ,			---本位币期末余额
    )
	------右边的表
	CREATE TABLE #RightPeriod
	(
	   ID		INT,
	   FPeriod	INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	CREATE TABLE #RightYear
	(
	   ID		INT,
	   FPERIOD	INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	CREATE TABLE #tempRightData
    (  
       PROTYPEID	  VARCHAR(50),				---具体辅助核算项的选择值id
       PROFDC		  INT,						--具体辅助核算项的选择值的分析方向
       FPERIOD	      INT,					    
       CID			  INT,
       SELFBORROW	   NUMERIC(24, 10) ,            ---本期合计本借
       ORIBORROW	   NUMERIC(24, 10) ,			
       SELFLEND		   NUMERIC(24, 10) ,			---本期合计本贷
       ORILEND		   NUMERIC(24, 10) ,
       YSELFBORROW	   NUMERIC(24, 10) ,			---本年累计本借
       YORIBORROW	   NUMERIC(24, 10) ,
       YSELFLEND	   NUMERIC(24, 10) ,			---本年累计本贷
       YORILEND		   NUMERIC(24, 10) 
    )
	
	WHILE @tempPeriodS<=@tempPeriodE
		BEGIN
			------------------------------------------左边的表
			----具体币种的值
			INSERT INTO #tempLeftData(TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND,YSELFBORROW,YORIBORROW,YSELFLEND,YORILEND)
			SELECT c.ATYPEID,
				   @tempPeriodS,
				   c.CID,
				   c.SELFBORROW,
				   c.ORIBORROW,
				   c.SELFLEND,
				   c.ORILEND,
				   d.YSELFBORROW,
				   d.YORIBORROW,
				   d.YSELFLEND,
				   d.YORILEND
			FROM 
			(    
				SELECT a.ATYPEID,
					   a.CID,
					   SUM(ISNULL(FDEBIT,0))      AS SELFBORROW,
					   SUM(ISNULL(FDEBITFOR,0))   AS ORIBORROW,
					   SUM(ISNULL(FCREDIT,0))     AS SELFLEND,
					   SUM(ISNULL(FCREDITFOR,0))  AS ORILEND
				FROM 
				(
				  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
													a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS
				GROUP BY a.ATYPEID,a.CID
			) c
			JOIN							
			(    
				SELECT a.ATYPEID,
					   a.CID,
					   SUM(ISNULL(FDEBIT,0))+c.SELFBORROW      AS YSELFBORROW,
					   SUM(ISNULL(FDEBITFOR,0))+c.ORIBORROW   AS YORIBORROW,
					   SUM(ISNULL(FCREDIT,0))+c.SELFLEND     AS YSELFLEND,
					   SUM(ISNULL(FCREDITFOR,0))+c.ORILEND  AS YORILEND
				FROM 
				(
				  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
													a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<=@tempPeriodS
				JOIN #IniAccountBeginBalance c ON a.STYPEID=c.STYPEID AND a.ATYPEID=c.TYPEID AND a.CID=c.CID
				GROUP BY  a.ATYPEID,a.CID,c.SELFBORROW,c.ORIBORROW,c.SELFLEND,c.ORILEND
			) d ON c.ATYPEID=d.ATYPEID AND c.CID=d.CID
	
			
			--左边表币种为0的
			INSERT INTO #tempLeftData
			SELECT c.ATYPEID,
			       @tempPeriodS,
			       0,
				   c.SELFBORROW,
				   c.ORIBORROW,
				   c.SELFLEND,
				   c.ORILEND,
				   d.YSELFBORROW,
				   d.YORIBORROW,
				   d.YSELFLEND,
				   d.YORILEND,
				   e.BALANCE
			FROM 
			(
				SELECT a.ATYPEID,
					   SUM(ISNULL(FDEBIT,0))      AS SELFBORROW,
					   SUM(ISNULL(FDEBITFOR,0))   AS ORIBORROW,
					   SUM(ISNULL(FCREDIT,0))     AS SELFLEND,
					   SUM(ISNULL(FCREDITFOR,0))  AS ORILEND
				FROM 
				(
				  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
													a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS
				GROUP BY a.ATYPEID
			) c
			JOIN 
			(
				SELECT a.ATYPEID,
					   SUM(ISNULL(FDEBIT,0))+c.SELFBORROW      AS YSELFBORROW,
					   SUM(ISNULL(FDEBITFOR,0))+c.ORIBORROW   AS YORIBORROW,
					   SUM(ISNULL(FCREDIT,0))+c.SELFLEND     AS YSELFLEND,
					   SUM(ISNULL(FCREDITFOR,0))+c.ORILEND  AS YORILEND
				FROM 
				(
				  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
													a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<=@tempPeriodS
			    JOIN #IniAccountBeginBalance c ON a.STYPEID=c.STYPEID AND a.ATYPEID=c.TYPEID AND c.CID=0
				GROUP BY  a.ATYPEID,c.SELFBORROW,c.ORIBORROW,c.SELFLEND,c.ORILEND
			) d ON c.ATYPEID=d.ATYPEID
			JOIN 
			(
				SELECT  c.ATYPEID,
						SUM(ISNULL(FENDBALANCE,0)) AS BALANCE 
				FROM
				(
					SELECT a.STYPEID,
						   a.ATYPEID,
						   a.ASCID,
						   a.PROTYPEID,
						   a.CID,
						   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD
					FROM
					(
					  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
					) a
					LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
														a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<=@tempPeriodS
					GROUP BY a.STYPEID,a.ATYPEID,a.ASCID,a.PROTYPEID,a.CID
				) c 
				LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.ASCID=d.ASCIDS AND c.PROTYPEID=d.FIELDVALUE AND 
														c.CID=d.CID AND d.FYEAR=@FYear AND d.FPERIOD=c.FPERIOD 
				GROUP BY c.ATYPEID
			) e ON d.ATYPEID=e.ATYPEID
			-------------右边的表
			INSERT INTO #tempRightData
			SELECT c.PROTYPEID,
				   c.PROFDC,
				   @tempPeriodS,
				   c.CID,
				   c.SELFBORROW,
				   c.ORIBORROW,
				   c.SELFLEND,
				   c.ORILEND,
				   d.YSELFBORROW,
				   d.YORIBORROW,
				   d.YSELFLEND,
				   d.YORILEND
			FROM
			(
				 SELECT a.PROTYPEID,
				        a.PROFDC,
				        a.CID,
				        SUM(ISNULL(FDEBIT,0))      AS SELFBORROW,
					    SUM(ISNULL(FDEBITFOR,0))   AS ORIBORROW,
					    SUM(ISNULL(FCREDIT,0))     AS SELFLEND,
					    SUM(ISNULL(FCREDITFOR,0))  AS ORILEND
				 FROM 
				 (
					SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				 ) a
				 LEFT JOIN  #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
													a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS
				GROUP BY a.PROTYPEID,a.PROFDC,a.CID
			) c
			JOIN 
			(
				SELECT a.PROTYPEID,
					   a.CID,
					   SUM(ISNULL(FDEBIT,0))+c.SELFBORROW      AS YSELFBORROW,
					   SUM(ISNULL(FDEBITFOR,0))+c.ORIBORROW   AS YORIBORROW,
					   SUM(ISNULL(FCREDIT,0))+c.SELFLEND    AS YSELFLEND,
					   SUM(ISNULL(FCREDITFOR,0))+c.ORILEND  AS YORILEND
				FROM 
				(
				  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
													a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<=@tempPeriodS
				JOIN #IniProjectBegin c ON a.PROTYPEID=c.PROTYPEID AND a.CID=c.CID 
				GROUP BY  a.PROTYPEID,a.CID,c.SELFBORROW,c.ORIBORROW,c.SELFLEND,c.ORILEND
			) d ON c.PROTYPEID=d.PROTYPEID AND c.CID=d.CID
			
			SET @tempPeriodS+=1
		END
		
	-----把数据插入行转列的表
	WHILE @FPeriodStart<=@FPeriodEnd
		BEGIN
			 ------插入左表本期数据
			 INSERT INTO #LeftPeriod
			 SELECT 999998,
				    @FPeriodStart,
				    e.COLNAME,
			  CASE
				WHEN d.CID=e.CID AND e.FDC=1  AND FLAG=-1 THEN SELFBORROW 
				WHEN d.CID=e.CID AND e.FDC=1  AND FLAG=1  THEN ORIBORROW  
				WHEN d.CID=e.CID AND e.FDC=-1 AND FLAG=-1 THEN SELFLEND
				WHEN d.CID=e.CID AND e.FDC=-1 AND FLAG=1  THEN ORILEND
				WHEN e.CID=0 AND e.FDC=1   THEN SELFBORROW
				WHEN e.CID=0 AND e.FDC=-1  THEN SELFLEND
			  END
			FROM #tempColName e
			LEFT JOIN #tempLeftData d ON e.CID=d.CID AND d.FPERIOD=@FPeriodStart
			------插入左表本年数据
			INSERT INTO #LeftYear
			SELECT 999999,
				    @FPeriodStart,
				    e.COLNAME,
			  CASE
				WHEN d.CID=e.CID AND e.FDC=1  AND FLAG=-1 THEN YSELFBORROW 
				WHEN d.CID=e.CID AND e.FDC=1  AND FLAG=1  THEN YORIBORROW  
				WHEN d.CID=e.CID AND e.FDC=-1 AND FLAG=-1 THEN YSELFLEND
				WHEN d.CID=e.CID AND e.FDC=-1 AND FLAG=1  THEN YORILEND
				WHEN e.CID=0 AND e.FDC=1    THEN  YSELFBORROW
				WHEN e.CID=0 AND e.FDC=-1   THEN  YSELFLEND
			  END
			FROM #tempColName e
			LEFT JOIN #tempLeftData d ON e.CID=d.CID AND d.FPERIOD=@FPeriodStart
			-----插入右表本期数据
			INSERT INTO #RightPeriod
			 SELECT 999998,
				    @FPeriodStart,
				    e.COLNAME,
			  CASE
				WHEN c.CID=e.CID AND e.FDC=1  AND e.PROTYPEID=c.PROTYPEID AND FLAG=-1 THEN SELFBORROW 
				WHEN c.CID=e.CID AND e.FDC=1  AND e.PROTYPEID=c.PROTYPEID AND FLAG=1 THEN ORIBORROW  
				WHEN c.CID=e.CID AND e.FDC=-1 AND e.PROTYPEID=c.PROTYPEID AND FLAG=-1 THEN SELFLEND
				WHEN c.CID=e.CID AND e.FDC=-1 AND e.PROTYPEID=c.PROTYPEID AND FLAG=1 THEN ORILEND
				WHEN e.CID=0     AND e.FDC=1  AND e.PROTYPEID=c.PROTYPEID THEN SELFBORROW
				WHEN e.CID=0     AND e.FDC=-1 AND e.PROTYPEID=c.PROTYPEID THEN SELFLEND
			  END
			FROM #Projects e
			LEFT JOIN #tempRightData c ON e.PROTYPEID=c.PROTYPEID WHERE c.FPERIOD=@FPeriodStart
			-----插入右表本年数据
			INSERT INTO #RightYear
			 SELECT 999999,
				    @FPeriodStart,
				    e.COLNAME,
					  CASE
						WHEN c.CID=e.CID AND e.FDC=1  AND e.PROTYPEID=c.PROTYPEID AND FLAG=-1 THEN YSELFBORROW 
						WHEN c.CID=e.CID AND e.FDC=1  AND e.PROTYPEID=c.PROTYPEID AND FLAG=1 THEN YORIBORROW  
						WHEN c.CID=e.CID AND e.FDC=-1 AND e.PROTYPEID=c.PROTYPEID AND FLAG=-1 THEN YSELFLEND
						WHEN c.CID=e.CID AND e.FDC=-1 AND e.PROTYPEID=c.PROTYPEID AND FLAG=1 THEN YORILEND
						WHEN e.CID=0     AND e.FDC=1  AND e.PROTYPEID=c.PROTYPEID THEN YSELFBORROW
						WHEN e.CID=0     AND e.FDC=-1 AND e.PROTYPEID=c.PROTYPEID THEN YSELFLEND
					  END
			FROM #Projects e
			LEFT JOIN #tempRightData c ON e.PROTYPEID=c.PROTYPEID WHERE c.FPERIOD=@FPeriodStart
			
			SET @FPeriodStart+=1
		END
		
    -----------------------本期，本年插入#MulCol
     SET @SQL='INSERT INTO #MulCol(ID,FPERIOD,BILLDATE,FSERIALNAME,SUMMARY,FDC,BALANCE,'+@LeftTurnCol+','+@RightTurnCol+')
			  SELECT c.ID,
					 c.FPERIOD,
					 @FYear+''-''+CONVERT(VARCHAR(10),c.FPERIOD),
					 '''',
					 ''本期合计'',
			         CASE 
						WHEN c.BALANCE=0 THEN ''平''
						ELSE @Fdc
					END,
					c.BALANCE,'
					+@LeftTurnCol+','
					+@RightTurnCol+' 
			  FROM 
			  ( 
			    SELECT 999998 AS ID,
					   FPERIOD,
					   BALANCE 
				FROM #tempLeftData 
				WHERE CID=0
			  ) c
			  JOIN 
			  (
				SELECT *  FROM  #LeftPeriod  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@LeftTurnCol+')) b
			  ) a ON c.ID=a.ID AND c.FPERIOD=a.FPERIOD
			  JOIN 
			  (
				SELECT *  FROM  #RightPeriod  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@RightTurnCol+')) b
			  ) b ON a.ID=b.ID AND b.FPERIOD=a.FPERIOD'
   EXEC sp_executesql @SQL,N'@FYear VARCHAR(10),@Fdc VARCHAR(5)', @FYear,@Fdc  
   
   SET @SQL='INSERT INTO #MulCol(ID,FPERIOD,BILLDATE,FSERIALNAME,SUMMARY,FDC,BALANCE,'+@LeftTurnCol+','+@RightTurnCol+')
			 SELECT c.ID,
					c.FPERIOD,
					@FYear+''-''+CONVERT(VARCHAR(10),c.FPERIOD),
					'''',
					''本年累计'',
			        CASE 
						WHEN c.BALANCE=0 THEN ''平''
						ELSE @Fdc
					END,
					c.BALANCE,'
					+@LeftTurnCol+','
					+@RightTurnCol+' 
			  FROM 
			  ( 
			    SELECT 999999 AS ID,
					   FPERIOD,BALANCE 
				FROM #tempLeftData 
				WHERE CID=0
			  ) c
			  JOIN 
			  (
				SELECT *  FROM  #LeftYear  pivot (MAX(FVALUE) FOR COLNAME IN ('+@LeftTurnCol+')) b
			  ) a ON c.ID=a.ID AND c.FPERIOD=a.FPERIOD
			  JOIN 
			  (
				SELECT *  FROM  #RightYear PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@RightTurnCol+')) b
			  ) b ON a.ID=b.ID AND b.FPERIOD=a.FPERIOD'
   EXEC sp_executesql @SQL,N'@FYear VARCHAR(10),@Fdc VARCHAR(5)', @FYear,@Fdc  
   
    ------查询数据
   SELECT * FROM #MulCol ORDER BY FPeriod,ID
   ---动态列
	SELECT PROUSERCODE AS USERCODE,
		   PROFULLNAME AS FULLNAME
	FROM #temp1
	ORDER BY PROUSERCODE
   
   IF @IsBalanceNull=1 OR @IsNull=1
		DROP TABLE #temp2,#temp3,#temp4
   DROP TABLE #tempAcBalanceDetail,#temp1,#Projects,#MulCol,#tempMulCol,#tempColName1,#tempColName2,#tempColName,#MulColCid,
			  #BeginBalance,#RightGetValue,#LeftGetValue,#LeftBalance,#ProjectBegin,#RightBalance,#RightYear,#LeftYear,#RightPeriod,#LeftPeriod,#tempLeftData,#tempRightData,
			  #IniAccountBeginBalance,#tempRight
   
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MulColOriQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_MulColOriQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/08
	Description	: 查询非明细科目原币的多栏账
*/

CREATE PROCEDURE Web_MulColOriQuery
(
    @STypeId 			VARCHAR(50),		---分支机构ID
    @AssistId			BIGINT,				---方案id
    @fyear				INT,
	@FPeriodStart		INT,				---起始期间
	@FPeriodEnd			INT,				---结束期间   
	@IsBalanceNull		BIT,				-- 无发生额且无余额不显示 1：是 0：否
	@IsNull				BIT,				---无发生额不显示 1：是 0：否
	@IsPost				BIT,				---是否显示未过账凭证 1：是 0：否
	@chvOperatorID		VARCHAR(50)			--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE 
		@AtypeId			VARCHAR(50),                ---方案查询科目id
		@FdcId				INT,						---该科目的方向表示值
		@Fdc				VARCHAR(5),					---该科目的方向名称
		@iniFYear			VARCHAR(5),				    --启用年度
		@FPeriod			INT,
		@SQL				NVARCHAR(MAX),              ---查询各个期间的动态sql
		@Balance			 NUMERIC(24, 10) ,				---期初余额，更新凭证余额时使用
		@tempBalance		 NUMERIC(24, 10) ,				---期初余额临时变量，保存期初数据到临时表时判断方向用
		@tempPeriodS		INT=@FPeriodStart,
		@tempPeriodE		INT=@FPeriodEnd,
		@Cids				VARCHAR(MAX),				---要分析的币别
		@LimitOwnVoucher	INT=0	--仅能查看本人制单的会计凭证
		
	SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@chvOperatorID
			
	---获取年度和期间
	SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	IF @iniFYear=@Fyear
	SELECT @Fperiod=SFPeriod from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	ELSE 
		SELECT @Fperiod=MIN(CONVERT(INT,FPeriod)) FROM dbo.Ac_Period
	---获取方案中的科目
	SELECT @AtypeId=ATYPEID FROM dbo.Ac_MulColumnAccount WHERE ASSISTID=@AssistId
	---该科目的方向
	SELECT @FdcId=FDC,
		   @Fdc=CASE 
						WHEN FDC=1 THEN '借'
						ELSE '贷'
					END
	 FROM dbo.Ac_Account 
	 WHERE STYPEID=@STypeId AND 
		   TYPEID=@AtypeId
		   
	 ---要分析的币别
	 SELECT @Cids=CIDS
	 FROM dbo.Ac_MulColumnAccount 
	 WHERE ASSISTID=@AssistId
	
	 CREATE TABLE #MulColCid
	 (
		CID			INT,
		FULLNAME	VARCHAR(200),
		USERCODE	VARCHAR(200)
	 )
	 INSERT INTO #MulColCid
	 SELECT a.CID,
			a.FULLNAME,
			a.USERCODE
	 FROM Ac_Currency a
	 JOIN 
	 (
		SELECT a FROM F_Split(@Cids,',')
	 ) b ON a.CID=b.a
	-------------------------------无论选择过账与否,都重新生成一个临时科目余额表-----------------------------------------------------------
     CREATE TABLE  #tempAcBalance 
	(
		 STYPEID			VARCHAR(50),
		 ATYPEID			VARCHAR(50),
		 FBEGINBALANCE		 NUMERIC(24, 10) ,
		 FBEGINBALANCEFOR	 NUMERIC(24, 10) ,
		 FDEBIT				 NUMERIC(24, 10) ,
		 FDEBITFOR			 NUMERIC(24, 10) ,
		 FCREDIT			 NUMERIC(24, 10) ,
		 FCREDITFOR			 NUMERIC(24, 10) ,
		 CID				INT,
		 FENDBALANCE		 NUMERIC(24, 10) ,
		 FENDBALANCEFOR		 NUMERIC(24, 10) ,
		 FYTDDEBIT			 NUMERIC(24, 10) ,
		 FYTDDEBITFOR		 NUMERIC(24, 10) ,
		 FYTDCREDIT			 NUMERIC(24, 10) ,
		 FYTDCREDITFOR		 NUMERIC(24, 10) ,
		 FYEAR				VARCHAR(10),
		 FPERIOD			INT,
	)
	INSERT INTO #tempAcBalance
	EXEC WEB_AcBalanceQueryFromVoucher @IsPost,@FYear,@STypeId 
	--权限控制，删除不在权限范围类的数据
	DELETE FROM #tempAcBalance WHERE ATypeId NOT IN(SELECT Typeid FROM F_LineAccount(@chvOperatorID,@STypeId) )

	-----------------------------------------要分析的明细科目及科目要分析的方向--------------------------------------------------------------------
	------------该非明细科目下要分析的子科目，存入#temp1
     CREATE TABLE #temp1
    (
	   STYPEID		VARCHAR(50),
	   FATHERID		VARCHAR(50),		---非明细科目
	   SONID		VARCHAR(50),		---要分析的子科目typeid
	   SONFDC		INT,				---要分析的子科目的余额方向
	   FULLNAME		VARCHAR(200),
	   USERCODE		VARCHAR(200),
	   FDC			INT					---要分析的子科目的分析方向	
    )
    INSERT INTO #temp1
	SELECT b.StypeId,
		   @AtypeId,
	       b.TypeId,
	       b.FDC,
	       FULLNAME,
	       USERCODE,
		   a.FDC				   ---科目的分析方向
	FROM AC_MULCOLUMNACCOUNT_ASSIST a
	JOIN dbo.Ac_Account b ON a.FVALUE=b.TYPEID  AND b.STYPEID=@STypeId --AND b.DELETED=0
	INNER JOIN F_LineAccount(@chvOperatorID,@STypeId) F ON F.TypeID=B.TypeId AND F.Stypeid=B.STypeId
	WHERE a.ASSISTID=@AssistID  
	----------------------------------------------------取出凭证放入临时表--------------------------------------------------------------------------
	CREATE TABLE #tempMulCol
	(
		ID						INT IDENTITY(1,1),		--Modify 12-10-19，原来取的是AC_VOUCHER_BILL的ID，现在为了最后一步排序，重新生成
		FPERIOD 				INT,					--期间
		VOUCHERTIME				VARCHAR(10),			--记账日期
		FSERIALNAME				VARCHAR(50),			--凭证字号
		SUMMARY					VARCHAR(500),			--摘要				
		FDC						VARCHAR(5),				--多栏账科目的余额方向
		BALANCE					 NUMERIC(24, 10) ,			--本币余额
		TYPEID					VARCHAR(50),			--要分析的子科目
		TYPEFDC					INT,					--要分析的子科目的方向
		SONFDC					INT,					--要分析的子科目的余额方向
		CID						INT,
		SELFBORROW				 NUMERIC(24, 10) ,
		ORIBORROW				 NUMERIC(24, 10) ,
		SELFLEND				 NUMERIC(24, 10) ,
		ORILEND					 NUMERIC(24, 10),
		ETypeId					VARCHAR(50)	NOT NULL DEFAULT('')--制单人
	)
	SET @SQL='INSERT INTO #tempMulCol(FPERIOD,VOUCHERTIME,FSERIALNAME,SUMMARY,FDC,TYPEID,TYPEFDC,SONFDC,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND,ETypeId)
			   SELECT a.FPERIOD,
					  CONVERT(VARCHAR(10),BILLDATE,120),
					  CASE WHEN @LimitOwnVoucher=1 AND c.ETypeId<>@chvOperatorID THEN ''****'' ELSE d.FULLNAME+''-''+CONVERT(VARCHAR(10),c.FLOWNO) END,
					  CASE WHEN @LimitOwnVoucher=1 AND c.ETypeId<>@chvOperatorID THEN ''****'' ELSE dbo.F_GetSummaryByLimit(a.ID,@chvOperatorID,a.STypeID,a.Summary) END SUMMARY,
					  @Fdc,
					  b.SONID,
					  b.FDC,
					  b.SONFDC,
					  a.CID,
					  a.FDEBITTOTAL,
					  a.FDEBITTOTALFOR,
					  a.FCREDITTOTAL,
					  a.FCREDITTOTALFOR,
					  c.ETypeId
			FROM AC_VOUCHER_BILL a 
			INNER JOIN F_LineAccount('''+@chvOperatorID+''','''+@STypeId+''') F ON F.TypeID=a.ATypeId AND F.Stypeid=a.STypeId
			JOIN  #temp1 b ON a.ATYPEID=b.SONID  
			JOIN dbo.Ac_Voucher c ON a.BILLNUMBERID=c.BILLNUMBERID AND c.FYEAR=@FYear AND c.FPERIOD>=@FPeriodStart AND c.FPERIOD<=@FPeriodEnd AND FCHECKED <> -1 '
	IF @IsPost=0
		SET @SQL+='AND IFCHECK=''t'' '
	SET @SQL+='	JOIN AC_VOUCHER_GROUP d ON c.VGID = d.VGID 
				JOIN #MulColCid e ON a.CID=e.CID
				WHERE a.STYPEID=@STypeId
				ORDER BY c.FPERIOD,c.BILLDATE,a.BILLNUMBERID,a.ID'
	EXEC sp_executesql @SQL,N'@FYear VARCHAR(10),@FPeriodStart INT,@FPeriodEnd INT,@Fdc VARCHAR(10),@STypeId VARCHAR(50),@LimitOwnVoucher INT,@chvOperatorID VARCHAR(50)',@FYear,@FPeriodStart,@FPeriodEnd,@Fdc,@STypeId,@LimitOwnVoucher,@chvOperatorID
	--------------------根据查询条件剔除不符合的科目
	IF @IsBalanceNull=1 OR @IsNull=1
		BEGIN
			CREATE TABLE #temp2
			(
			    TYPEID			VARCHAR(50),	---分析的子科目
			    BALANCE			 NUMERIC(24, 10) 	---本期余额
			)
			INSERT INTO #temp2
			SELECT c.SONID,
				  SUM(ISNULL(FENDBALANCE,0)) AS BALANCE
		    FROM 
		    (
				SELECT a.STYPEID,
					   a.SONID,
					   a.CID,
					   ISNULL(MAX(FPERIOD),@FPeriodEnd) AS FPERIOD
				FROM
					(
					   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
					) a
				LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodEnd AND b.CID=a.CID
				GROUP BY a.STYPEID,a.SONID,a.CID
			) c 
			LEFT JOIN #tempAcBalance d ON d.STYPEID=c.STYPEID AND d.ATYPEID=c.SONID AND d.FPERIOD=c.FPERIOD AND d.CID=c.CID AND d.FYEAR=@FYear
			GROUP BY c.SONID
				
			CREATE TABLE #temp3
			(
			    TYPEID			VARCHAR(50),	---分析的子科目
			    PERIODCHANGE	 NUMERIC(24, 10) ,	---本期发生额
			    BALANCE			 NUMERIC(24, 10) 	---本期余额
			)
		    INSERT INTO #temp3
		    SELECT a.TYPEID,
				   ISNULL(b.PERIODCHANGE,0),
				   a.BALANCE
		    FROM #temp2 a
		    LEFT JOIN (
						   SELECT TYPEID,
						      SUM(ABS(ISNULL(SELFBORROW,0)))+SUM(ABS(ISNULL(SELFLEND,0))) AS PERIODCHANGE
						   FROM #tempMulCol
						   GROUP BY TYPEID
					  ) b ON a.TYPEID=b.TYPEID
				
		    SELECT TYPEID
		    INTO #temp4
		    FROM #temp3 
		    WHERE	((@IsNull=1 AND PERIODCHANGE>0) OR @IsNull=0) AND
					((@IsBalanceNull=1 AND (BALANCE!=0 OR PERIODCHANGE>0)) OR @IsBalanceNull=0) 
			
			DELETE FROM #temp1  WHERE NOT EXISTS (SELECT 1 FROM #temp4 b WHERE #temp1.SONID=b.TYPEID)
		END
		    
    ---科目与借贷交叉连接，以待后面行转列：还要判断分析方向，控制列的显示列数
    CREATE TABLE #Accounts
    (
        STYPEID		VARCHAR(50),		--机构id
        TYPEID		VARCHAR(50),		--科目id
        FULLNAME	VARCHAR(200),		--科目名称
        FDC			INT,				--科目分析方向
        FLAG		INT,				--本位币还是外币
        COLNAME		VARCHAR(150),		--行转列的列名
        CID			INT					--币别
    )
	SET @SQL='  INSERT INTO #Accounts
				SELECT STYPEID,
					   SONID,
					   FULLNAME,
					   d.FDC,
					   e.FLAG,
					   SUBSTRING(COLNAME+c.USERCODE+e.USERCODE,0,128),
					   e.CID
				FROM #temp1 c,'
	IF (SELECT COUNT(1) FROM ( SELECT FDC FROM #temp1 GROUP BY FDC) a)=2 OR (SELECT TOP 1 1 FROM #temp1 WHERE FDC=0)=1
		SET @SQL+='( SELECT ''borrow'' AS COLNAME,1 AS FDC 
				    UNION ALL
				    SELECT ''lend'' AS COLNAME,-1 AS FDC 
				    ) d,'
    ELSE IF (SELECT TOP 1 1 FROM #temp1 WHERE FDC=1)=1
		SET @SQL+='( SELECT ''borrow'' AS COLNAME,1 AS FDC) d,'
	ELSE
		SET @SQL+='( SELECT ''lend'' AS COLNAME,-1 AS FDC) d,'
			
	SET @SQL+='( SELECT CID,
						USERCODE,
						FLAG
				 FROM (
						 SELECT CID,
								USERCODE,
								FLAG 
						 FROM 
						 (
							  SELECT CID,
									 SUBSTRING(USERCODE+CODE,0,128) AS USERCODE,
									 FLAG 
							  FROM #MulColCid,
    						 (SELECT ''ben'' AS CODE,-1 AS FLAG
							 UNION 
							 SELECT ''yuan'' AS CODE,1 AS FLAG) a
						 ) c
					 ) b
			   ) e'
	EXEC(@SQL)
	
	----------------------------------------------------凭证表左边的统计信息---------------------------------------------------------------------------
	SELECT COLNAME,
		   FDC 
	INTO #tempColName1 
	FROM 
	(
	  SELECT 'borrow' AS COLNAME,1 AS FDC 
	  UNION ALL
	  SELECT 'lend' AS COLNAME,-1 AS FDC 
	) a
   
	SELECT CID,
		   USERCODE,
		   FLAG
	INTO #tempColName2
	FROM 
	(	SELECT CID,
			   USERCODE,
			   FLAG
		FROM 
		(
		  SELECT CID,
				 USERCODE+CODE AS USERCODE,
				 FLAG
		  FROM #MulColCid,
			(SELECT 'ben' AS CODE,-1 AS FLAG
	         UNION 
	         SELECT 'yuan' AS CODE,1 AS FLAG) a
		) c
		UNION ALL 
		SELECT 0 AS CID,'self' AS USERCODE,0 AS FLAG
	) b
   
	--#temp表中的colname值就是结果表中的列名，即该表有多少条数据，在结果表中就有多少列显示
	SELECT SUBSTRING(COLNAME+USERCODE,0,128) AS COLNAME,
		   FDC,
		   CID,
		   FLAG
	INTO #tempColName
	FROM #tempColName1,#tempColName2
	
	--行转列的时候用
	DECLARE @LeftTurnCol VARCHAR(MAX)
	SELECT @LeftTurnCol=(ISNULL(@LeftTurnCol+'],[','') +  COLNAME) 
	FROM #tempColName GROUP BY COLNAME 
	SET @LeftTurnCol='['+@LeftTurnCol+']'
	
	--动态添加列的时候用
	DECLARE @LeftDynCol VARCHAR(MAX)
	SELECT @LeftDynCol=(ISNULL(@LeftDynCol+']  NUMERIC(24, 10) ,[','') +  COLNAME) 
	FROM #tempColName GROUP BY COLNAME 
	SET @LeftDynCol='ALTER TABLE #MulCol ADD ['+@LeftDynCol+']  NUMERIC(24, 10) '
	
	CREATE TABLE #LeftGetValue
	(
		FPERIOD        INT,					--期间
		ID			   INT,					--凭证明细表的ID
		COLNAME		   VARCHAR(MAX),		--要转列的列名
		FVALUE          NUMERIC(24, 10) 		--列对应的值
	)
	INSERT INTO #LeftGetValue
	SELECT b.FPERIOD,
		   b.ID,
		   a.COLNAME,
		   CASE
				WHEN a.FDC=1  AND a.CID=b.CID AND a.FLAG=1 THEN ORIBORROW			--当前币种对应的原币借
				WHEN a.FDC=-1 AND a.CID=b.CID AND a.FLAG=1 THEN ORILEND				--当前币种对应的原币贷
				WHEN a.FDC=1  AND a.CID=b.CID AND a.FLAG=-1 THEN SELFBORROW			--当前币种对应的本币借
				WHEN a.FDC=-1 AND a.CID=b.CID AND a.FLAG=-1 THEN SELFLEND			--当前币种对应的本币贷
				WHEN a.FDC=1  AND a.CID=0 THEN SELFBORROW							--借综合本位币
				WHEN a.FDC=-1 AND a.CID=0 THEN SELFLEND								--贷综合本位币
		   END
	FROM #tempColName a,#tempMulCol b
	--------------------------------------------凭证表右边的统计信息--------------------------------------------------------------
	--获取待行转列的列对应的值
	CREATE TABLE #RightGetValue
	(
		ID			   INT,
		FPERIOD        INT,					--期间
		COLNAME		   VARCHAR(MAX),		--要转列的列名
		FVALUE          NUMERIC(24, 10) 		--列对应的值
	)
	INSERT INTO #RightGetValue
	SELECT b.ID,
		   b.FPERIOD,
		   a.COLNAME,
		   CASE
				WHEN a.TYPEID=b.TYPEID AND a.CID=b.CID  AND a.FDC=1 AND FLAG=1 AND (b.TYPEFDC=0 OR b.TYPEFDC=1) THEN ORIBORROW
				WHEN a.TYPEID=b.TYPEID AND a.CID=b.CID  AND a.FDC=-1 AND FLAG=1 AND (b.TYPEFDC=0 OR b.TYPEFDC=-1) THEN ORILEND
				WHEN a.TYPEID=b.TYPEID AND a.CID=b.CID  AND a.FDC=1 AND FLAG=-1 AND (b.TYPEFDC=0 OR b.TYPEFDC=1) THEN SELFBORROW
			    WHEN a.TYPEID=b.TYPEID AND a.CID=b.CID  AND a.FDC=-1 AND FLAG=-1 AND (b.TYPEFDC=0 OR b.TYPEFDC=-1) THEN SELFLEND
		   END
	FROM #Accounts a,#tempMulCol b
	
	DECLARE @RightTurnCol VARCHAR(MAX)
	SELECT @RightTurnCol=(ISNULL(@RightTurnCol+'],[','') +  colname) 
	FROM #Accounts GROUP BY colname 
	SET @RightTurnCol='['+@RightTurnCol+']'
	
	DECLARE @RightDynCol VARCHAR(MAX)
	SELECT @RightDynCol=(ISNULL(@RightDynCol+']  NUMERIC(24, 10) ,[','') +  colname) 
	FROM #Accounts GROUP BY colname 
	SET @RightDynCol='ALTER TABLE #MulCol ADD ['+@RightDynCol+']  NUMERIC(24, 10) '

	CREATE TABLE #MulCol
	(
		ID						INT,					
		FPERIOD 				INT,					--期间
		BILLDATE				VARCHAR(10),			--记账日期
		FSERIALNAME				VARCHAR(200),			--凭证字号
		SUMMARY					VARCHAR(500),			--摘要				
		FDC						VARCHAR(5),				--方向
		BALANCE					 NUMERIC(24, 10),		--本币余额
		ETypeId					VARCHAR(50)	NOT NULL DEFAULT('')--制单人
		
	)
	----#MulCol临时表动态添加列
	EXEC(@LeftDynCol)
	EXEC(@RightDynCol)
    -------------------------获取期初，更新余额---------------------------------------------------------------------------------------
	CREATE TABLE #BeginBalance
	(
	    STYPEID	   VARCHAR(50),
	    TYPEID	   VARCHAR(50),			--非明细科目id
	    FPERIOD	   INT,
	    CID		   INT,					
	    SELFBORROW  NUMERIC(24, 10) ,
	    ORIBORROW   NUMERIC(24, 10) ,
	    SELFLEND    NUMERIC(24, 10) ,
	    ORILEND	    NUMERIC(24, 10) ,
	    BALANCE	    NUMERIC(24, 10) 
	)
	IF @FPeriodStart=@FPeriod
		BEGIN
			---插入的是cid=0，即综合本位币的该科目借和贷
			INSERT INTO #BeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
			SELECT a.STYPEID,
				   a.FATHERID,
				   @FPeriod,
				   0,
				   SUM(ISNULL(FDEBIT,0))  AS SELFBORROW,
				   SUM(ISNULL(FDEBIT,0))  AS ORIBORROW,
				   SUM(ISNULL(FCREDIT,0)) AS SELFLEND,
				   SUM(ISNULL(FCREDIT,0)) AS ORILEND
			FROM 
			(
				   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			) a
			LEFT JOIN dbo.Ac_IniAccount b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@FPeriod AND a.CID=b.CID
			GROUP BY a.STYPEID,a.FATHERID
			---插入具体币种的借和贷
			INSERT INTO #BeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
			SELECT a.STYPEID,
				   a.FATHERID,
				   @FPeriod,
				   a.CID,
				   SUM(ISNULL(FDEBIT,0))     AS SELFBORROW,
				   SUM(ISNULL(FDEBITFOR,0))  AS ORIBORROW,
				   SUM(ISNULL(FCREDIT,0))	 AS SELFLEND,
				   SUM(ISNULL(FCREDITFOR,0)) AS ORIBORROW
			FROM 
				(
					SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) c
				) a
			LEFT JOIN Ac_IniAccount b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@FPeriod AND a.CID=b.CID
			GROUP BY a.STYPEID,a.FATHERID,a.CID
		END
	ELSE
		BEGIN
			----插入cid=0的借和贷
			INSERT INTO #BeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
			SELECT c.STYPEID,
				   c.FATHERID,
				   @FPeriodStart,
				   0,
				   SUM(ISNULL(FYTDDEBIT,0))       AS SELFBORROW,
				   SUM(ISNULL(FYTDDEBITFOR,0))    AS ORIBORROW,
				   SUM(ISNULL(FYTDCREDIT,0))	  AS SELFLEND,
				   SUM(ISNULL(FYTDCREDITFOR,0))   AS ORILEND
			FROM 
			(
			   SELECT a.STYPEID,
					  a.FATHERID,
					  a.SONID,
					  a.CID,
					  CASE
						WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart THEN @FPeriod-1
						ELSE ISNULL(MAX(FPERIOD),@FPeriodStart)
					  END AS FPERIOD
			   FROM 
					(
					   SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) x
					) a
			   LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodStart AND a.CID=b.CID
			   GROUP BY a.STYPEID,a.FATHERID,a.SONID,a.CID
			) c 
			LEFT JOIN #tempAcBalance d ON d.STYPEID=c.STYPEID AND d.ATYPEID=c.SONID AND d.FPERIOD=c.FPERIOD AND d.CID=c.CID
			GROUP BY c.STYPEID,c.FATHERID 	
			----插入具体币种的借和贷
			INSERT INTO #BeginBalance(STYPEID,TYPEID,FPERIOD,CID,SELFBORROW,ORIBORROW,SELFLEND,ORILEND)
			SELECT c.STYPEID,
				   c.FATHERID,
				   @FPeriodStart,
				   c.CID,
				   SUM(ISNULL(FYTDDEBIT,0))       AS SELFBORROW,
				   SUM(ISNULL(FYTDDEBITFOR,0))    AS ORIBORROW,
				   SUM(ISNULL(FYTDCREDIT,0))	  AS SELFLEND,
				   SUM(ISNULL(FYTDCREDITFOR,0))   AS ORILEND
			FROM 
			(
			   SELECT a.STYPEID,
					  a.FATHERID,
					  a.SONID,
					  a.CID,
					  CASE
						WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart THEN @FPeriod-1
						ELSE ISNULL(MAX(FPERIOD),@FPeriodStart)
					  END AS FPERIOD
			   FROM 
					(
					   SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) x
					) a
			   LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodStart AND a.CID=b.CID
			   GROUP BY a.STYPEID,a.FATHERID,a.SONID,a.CID
			) c 
			LEFT JOIN #tempAcBalance d ON d.STYPEID=c.STYPEID AND d.ATYPEID=c.SONID AND d.FPERIOD=c.FPERIOD AND d.CID=c.CID
			GROUP BY c.STYPEID,c.FATHERID,c.CID						
		END
	---求出余额
	SELECT 	@Balance=SUM(ISNULL(BALANCE,0)) 
	FROM 
	(
		SELECT a.STYPEID,
			   a.FATHERID,
			   a.SONFDC,
				CASE 
					WHEN @FdcId=a.SONFDC AND a.FPERIOD=@FPeriod THEN SUM(ISNULL(FBEGINBALANCE,0))
					WHEN @FdcId=-a.SONFDC AND a.FPERIOD=@FPeriod THEN -SUM(ISNULL(FBEGINBALANCE,0))
					WHEN @FdcId=a.SONFDC AND a.FPERIOD!=@FPeriod THEN SUM(ISNULL(FENDBALANCE,0))
					WHEN @FdcId=-a.SONFDC AND a.FPERIOD!=@FPeriod THEN -SUM(ISNULL(FENDBALANCE,0))
				END AS BALANCE
		FROM 
		(	
			SELECT f.STYPEID,
				   f.FATHERID,
				   f.SONID,
				   f.SONFDC,
				   f.CID,
				   CASE
						WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart AND ISNULL(MAX(FPERIOD),@FPeriodStart)!=@FPeriod THEN @FPeriodStart-1
						ELSE ISNULL(MAX(FPERIOD),@FPeriodStart)
				   END AS FPERIOD 
			FROM 
			(
				SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			) f
			LEFT JOIN #tempAcBalance g ON f.STYPEID=g.STYPEID AND f.SONID=g.ATYPEID AND g.FYEAR=@FYear AND g.FPERIOD<=@FPeriodStart AND g.CID=f.CID    
			GROUP BY f.STYPEID,f.FATHERID,f.SONID,f.SONFDC,f.CID
		) a
		LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=a.FPERIOD AND b.CID=a.CID
		GROUP BY a.STYPEID,a.FATHERID,a.SONFDC,a.FPERIOD
	) c GROUP BY c.STYPEID,c.FATHERID
    -----更新#BeginBalance的余额
    UPDATE #BeginBalance SET BALANCE=@Balance	
	SET @tempBalance=@Balance
	-----更新凭证余额
	UPDATE #tempMulCol SET @Balance+=CASE 
										WHEN FDC='借' AND SONFDC=@FdcId THEN (ISNULL(BALANCE,0)+ISNULL(SELFBORROW,0)-ISNULL(SELFLEND,0))
										WHEN FDC='借' AND SONFDC!=@FdcId THEN (ISNULL(BALANCE,0)-ISNULL(SELFBORROW,0)+ISNULL(SELFLEND,0))
										WHEN FDC='贷' AND SONFDC=@FdcId THEN (ISNULL(BALANCE,0)-ISNULL(SELFBORROW,0)+ISNULL(SELFLEND,0))
										WHEN FDC='贷' AND SONFDC!=@FdcId THEN (ISNULL(BALANCE,0)+ISNULL(SELFBORROW,0)-ISNULL(SELFLEND,0))
								     END,
						   BALANCE=@Balance,
						   FDC=CASE 
									WHEN @Balance=0 THEN '平'
									ELSE @Fdc
								END
	---#MulCol插入数据
	SET @SQL='INSERT INTO #MulCol (ID,FPERIOD,BILLDATE,FSERIALNAME,SUMMARY,FDC,BALANCE,'+@LeftTurnCol+','+@RightTurnCol+',ETypeId)
	      SELECT a.ID,
			     a.FPERIOD,
			     a.VOUCHERTIME,
			     a.FSERIALNAME,
			     a.SUMMARY,
			     a.FDC,
			     a.BALANCE,'
			     +@LeftTurnCol+','
			     +@RightTurnCol+',
			     a.ETypeId 
	      FROM #tempMulCol a
	      JOIN
				(
					 SELECT *  FROM  #LeftGetValue  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@LeftTurnCol+')) b
				) b	ON a.ID=b.ID
		  JOIN
				(
				     SELECT *  FROM  #RightGetValue  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@RightTurnCol+')) b
				)c ON a.ID=c.ID'
	EXEC(@SQL)
	------------------------------------------------期初余额数据插入--------------------------------------------------------------------------------------
	------左边表的期初
	CREATE TABLE #LeftBalance
	(
	   ID		INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	INSERT INTO #LeftBalance
	SELECT -1,
		   a.COLNAME,
		   CASE
			 WHEN a.CID=b.CID AND a.FDC=1 AND a.FLAG=-1  THEN SELFBORROW
			 WHEN a.CID=b.CID AND a.FDC=1 AND a.FLAG=1   THEN ORIBORROW
			 WHEN a.CID=b.CID AND a.FDC=-1 AND a.FLAG=-1 THEN SELFLEND
			 WHEN a.CID=b.CID AND a.FDC=-1 AND a.FLAG=1  THEN ORILEND
			 WHEN a.CID=0 AND a.FDC=1  THEN SELFBORROW
			 WHEN a.CID=0 AND a.FDC=-1 THEN ORIBORROW
		   END
	FROM #tempColName a
	LEFT JOIN #BeginBalance b ON a.CID=b.CID 
	
   --------右边表的期初
   ----先获取各分析科目的借贷数据
   CREATE TABLE #AccountBegin
   (
       TYPEID		VARCHAR(50),
       CID			INT,
       SELFBORROW	 NUMERIC(24, 10) ,
       ORIBORROW	 NUMERIC(24, 10) ,
       SELFLEND		 NUMERIC(24, 10) ,
       ORILEND		 NUMERIC(24, 10) 
   )
   IF @FPeriodStart=@FPeriod
		INSERT INTO #AccountBegin
	    SELECT a.SONID,
			   a.CID,
			   ISNULL(FDEBIT,0),
			   ISNULL(FDEBITFOR,0),
			   ISNULL(FCREDIT,0),
			   ISNULL(FCREDITFOR,0)
		FROM 
			(
				SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) c
			) a
		LEFT JOIN Ac_IniAccount b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@FPeriod AND a.CID=b.CID
   ELSE 
		INSERT INTO #AccountBegin
		SELECT c.SONID,
		       c.CID,
		       ISNULL(FYTDDEBIT,0),
		       ISNULL(FYTDDEBITFOR,0),
		       ISNULL(FYTDCREDIT,0),
		       ISNULL(FYTDCREDITFOR,0)
		FROM 
			(
				 SELECT a.STYPEID,
						a.SONID,
					    a.CID,
					     CASE
							WHEN MAX(FPERIOD)=@FPeriodStart THEN @FPeriodStart-1
							ELSE MAX(FPERIOD)
						 END AS FPERIOD
				FROM 
					(
						 SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) x
					) a
				LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodStart AND b.CID=a.CID
				GROUP BY a.STYPEID,a.SONID,a.CID	    
			) c
		LEFT JOIN #tempAcBalance d ON d.STYPEID=c.STYPEID AND d.ATYPEID=c.SONID AND d.FPERIOD=c.FPERIOD AND d.CID=c.CID AND d.FYEAR=@FYear
		       
	CREATE TABLE #RightBalance
	(
	   ID		INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	INSERT INTO #RightBalance
    SELECT -1,
		   a.COLNAME,
		   CASE 
			  WHEN a.CID=b.CID AND a.TYPEID=b.TYPEID AND a.FDC=1 AND FLAG=-1  THEN SELFBORROW
			  WHEN a.CID=b.CID AND a.TYPEID=b.TYPEID AND a.FDC=1 AND FLAG=1   THEN ORIBORROW
			  WHEN a.CID=b.CID AND a.TYPEID=b.TYPEID AND a.FDC=-1 AND FLAG=-1 THEN SELFLEND
			  WHEN a.CID=b.CID AND a.TYPEID=b.TYPEID AND a.FDC=-1 AND FLAG=1  THEN ORILEND
		   END 
	FROM #Accounts a
	LEFT JOIN #AccountBegin b ON a.TYPEID=b.TYPEID AND a.CID=b.CID
	
	----期初数据插入#MulCol
	SET @SQL='INSERT INTO #MulCol(ID,FPERIOD,BILLDATE,FSERIALNAME,SUMMARY,FDC,BALANCE,'+@LeftTurnCol+','+@RightTurnCol+')
			  SELECT -1,
					 @FPeriodStart,
					 '''',
					 '''',
					 ''期初余额'',
					  CASE 
						 WHEN @tempBalance=0 THEN ''平'' 
						 ELSE @Fdc 
					  END,
					  @tempBalance,'
					  +@LeftTurnCol+','
					  +@RightTurnCol+' 
			  FROM 
			  (
				SELECT *  FROM  #LeftBalance  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@LeftTurnCol+')) b
			  ) a
			  JOIN 
			  (
				SELECT *  FROM  #RightBalance  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@RightTurnCol+')) b
			  ) b ON a.ID=b.ID'
	EXEC sp_executesql @SQL,N'@tempBalance  NUMERIC(24, 10) ,@Fdc VARCHAR(5),@FPeriodStart INT',@tempBalance,@Fdc,@FPeriodStart 
	---------------------------------------------------本期合计，本年合计---------------------------------------------------------------------------------------
	------左边的表
	CREATE TABLE #LeftPeriod
	(
	   ID		INT,
	   FPeriod	INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	CREATE TABLE #LeftYear
	(
	   ID		INT,
	   FPeriod	INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	CREATE TABLE #tempLeftData
    (  
       TYPEID		  VARCHAR(50),				---非明细科目的id
       FPERIOD	      INT,
       CID			  INT,
       SELFBORROW	   NUMERIC(24, 10) ,            ---本期合计本借
       ORIBORROW	   NUMERIC(24, 10) ,			
       SELFLEND		   NUMERIC(24, 10) ,			---本期合计本贷
       ORILEND		   NUMERIC(24, 10) ,
       YSELFBORROW	   NUMERIC(24, 10) ,			---本年累计本借
       YORIBORROW	   NUMERIC(24, 10) ,
       YSELFLEND	   NUMERIC(24, 10) ,			---本年累计本贷
       YORILEND		   NUMERIC(24, 10) ,
       BALANCE		   NUMERIC(24, 10) ,			---本位币期末余额
    )
	
	------右边的表
	CREATE TABLE #RightPeriod
	(
	   ID		INT,
	   FPeriod	INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	CREATE TABLE #RightYear
	(
	   ID		INT,
	   FPeriod	INT,
	   COLNAME	VARCHAR(MAX),
	   FVALUE	 NUMERIC(24, 10) 
	)
	CREATE TABLE #tempRightData
    (  
       TYPEID		  VARCHAR(50),				---非明细科目的id
       TYPEFDC		  INT,						---非明细科目的分析方向
       FPERIOD	      INT,
       CID			  INT,
       SELFBORROW	   NUMERIC(24, 10) ,            ---本期合计本借
       ORIBORROW	   NUMERIC(24, 10) ,			
       SELFLEND		   NUMERIC(24, 10) ,			---本期合计本贷
       ORILEND		   NUMERIC(24, 10) ,
       YSELFBORROW	   NUMERIC(24, 10) ,			---本年累计本借
       YORIBORROW	   NUMERIC(24, 10) ,
       YSELFLEND	   NUMERIC(24, 10) ,			---本年累计本贷
       YORILEND		   NUMERIC(24, 10) 
    )
	
	WHILE @tempPeriodS<=@tempPeriodE
		BEGIN
			------------------------------------------左边的表
			----具体币种的值
			INSERT INTO #tempLeftData
			SELECT c.TYPEID,
				   @tempPeriodS,
				   c.CID,
				   c.FDEBIT,
				   c.FDEBITFOR,
				   c.FCREDIT,
				   c.FCREDITFOR,
				   d.FYTDDEBIT,
				   d.FYTDDEBITFOR,
				   d.FYTDCREDIT,
				   d.FYTDCREDITFOR,
				   d.BALANCE
			FROM 
			(
			   SELECT  a.FATHERID					   AS TYPEID,					   
					   a.CID,
				       SUM(ISNULL(FDEBIT,0))		   AS FDEBIT,
					   SUM(ISNULL(FDEBITFOR,0))		   AS FDEBITFOR,
					   SUM(ISNULL(FCREDIT,0))          AS FCREDIT,
					   SUM(ISNULL(FCREDITFOR,0))       AS FCREDITFOR
				FROM 
					(
					   SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) x
					) a
			    LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS AND a.CID=b.CID
			    GROUP BY a.FATHERID,a.CID
			) c
			JOIN 
			(
				SELECT TYPEID,
					   CID,
					   SUM(FYTDDEBIT)      AS FYTDDEBIT,
					   SUM(FYTDDEBITFOR)   AS FYTDDEBITFOR,
					   SUM(FYTDCREDIT)     AS FYTDCREDIT,
					   SUM(FYTDCREDITFOR)  AS FYTDCREDITFOR,
					   SUM(BALANCE)	       AS BALANCE
				FROM 
				(
					SELECT b.FATHERID AS TYPEID,
						   b.SONFDC,
						   a.CID,
						   SUM(FYTDDEBIT)      AS FYTDDEBIT,
						   SUM(FYTDDEBITFOR)   AS FYTDDEBITFOR,
						   SUM(FYTDCREDIT)     AS FYTDCREDIT,
						   SUM(FYTDCREDITFOR)  AS FYTDCREDITFOR,
						   CASE 
								WHEN @FdcId=b.SONFDC THEN SUM(FENDBALANCE)
								ELSE -SUM(FENDBALANCE)
						   END AS BALANCE
					FROM #temp1 b
					JOIN 
					(
						SELECT i.SONID,
							   i.CID,
							   ISNULL(FYTDDEBIT,0)	       AS FYTDDEBIT,
							   ISNULL(FYTDDEBITFOR,0)	   AS FYTDDEBITFOR,
							   ISNULL(FYTDCREDIT,0)        AS FYTDCREDIT,
							   ISNULL(FYTDCREDITFOR,0)     AS FYTDCREDITFOR,
							   ISNULL(FENDBALANCE,0)       AS FENDBALANCE 
						FROM 
						(
							SELECT h.STYPEID,
								   h.SONID,
								   h.CID,
								   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD 
							FROM 
								( 
									SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) x
								) h
							LEFT JOIN #tempAcBalance g ON g.STYPEID=h.STYPEID AND g.ATYPEID=h.SONID AND g.FYEAR=@FYear AND g.CID=h.CID AND g.FPeriod<=@tempPeriodS
							GROUP BY h.STYPEID,h.SONID,h.CID	
						) i 
						LEFT JOIN #tempAcBalance e ON i.STYPEID=e.STYPEID AND i.SONID=e.ATYPEID AND i.FPERIOD=e.FPERIOD AND e.CID=i.CID AND e.FYEAR=@FYear
					) a ON a.SONID=b.SONID
					GROUP BY b.FATHERID,a.CID,b.SONFDC
				) f
				GROUP BY TYPEID,CID
			) d ON c.TYPEID=d.TYPEID AND c.CID=d.CID
			
			----左边的表，cid=0的本位的值
			INSERT INTO #tempLeftData
			SELECT c.TYPEID,
				   @tempPeriodS,
				   0,
				   c.FDEBIT,
				   c.FDEBITFOR,
				   c.FCREDIT,
				   c.FCREDITFOR,
				   d.FYTDDEBIT,
				   d.FYTDDEBITFOR,
				   d.FYTDCREDIT,
				   d.FYTDCREDITFOR,
				   d.BALANCE
			FROM 
			(
			   SELECT  a.FATHERID					   AS TYPEID,					   
				       SUM(ISNULL(FDEBIT,0))		   AS FDEBIT,
					   SUM(ISNULL(FDEBITFOR,0))		   AS FDEBITFOR,
					   SUM(ISNULL(FCREDIT,0))          AS FCREDIT,
					   SUM(ISNULL(FCREDITFOR,0))       AS FCREDITFOR
				FROM 
					(
					   SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) x
					) a
			    LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS AND a.CID=b.CID
			    GROUP BY a.FATHERID
			) c
			JOIN 
			(
				SELECT TYPEID,
					   SUM(FYTDDEBIT)      AS FYTDDEBIT,
					   SUM(FYTDDEBITFOR)   AS FYTDDEBITFOR,
					   SUM(FYTDCREDIT)     AS FYTDCREDIT,
					   SUM(FYTDCREDITFOR)  AS FYTDCREDITFOR,
					   SUM(BALANCE)	       AS BALANCE
				FROM 
				(
					SELECT b.FATHERID AS TYPEID,
						   b.SONFDC,
						   SUM(FYTDDEBIT)      AS FYTDDEBIT,
						   SUM(FYTDDEBITFOR)   AS FYTDDEBITFOR,
						   SUM(FYTDCREDIT)     AS FYTDCREDIT,
						   SUM(FYTDCREDITFOR)  AS FYTDCREDITFOR,
						   CASE 
								WHEN @FdcId=b.SONFDC THEN SUM(FENDBALANCE)
								ELSE -SUM(FENDBALANCE)
						   END AS BALANCE
					FROM 
					( 
						SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) x
					) b
					JOIN 
					(
						SELECT i.SONID,
							   i.CID,
							   ISNULL(FYTDDEBIT,0)	       AS FYTDDEBIT,
							   ISNULL(FYTDDEBITFOR,0)	   AS FYTDDEBITFOR,
							   ISNULL(FYTDCREDIT,0)        AS FYTDCREDIT,
							   ISNULL(FYTDCREDITFOR,0)     AS FYTDCREDITFOR,
							   ISNULL(FENDBALANCE,0)       AS FENDBALANCE 
						FROM 
						(
							SELECT h.STYPEID,
								   h.SONID,
								   h.CID,
								   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD 
							FROM 
								( 
									SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) x
								) h
							LEFT JOIN #tempAcBalance g ON g.STYPEID=h.STYPEID AND g.ATYPEID=h.SONID AND g.FYEAR=@FYear AND g.CID=h.CID AND g.FPeriod<=@tempPeriodS
							GROUP BY h.STYPEID,h.SONID,h.CID	
						) i 
						LEFT JOIN #tempAcBalance e ON i.STYPEID=e.STYPEID AND i.SONID=e.ATYPEID AND i.FPERIOD=e.FPERIOD AND e.CID=i.CID AND e.FYEAR=@FYear
					) a ON a.SONID=b.SONID AND a.CID=b.CID
					GROUP BY b.FATHERID,b.SONFDC
				) f
				GROUP BY TYPEID 
			) d ON c.TYPEID=d.TYPEID  
			
			-----右边的表
			INSERT INTO #tempRightData
		    SELECT c.TYPEID,
				   c.FDC,
				   @tempPeriodS,
				   c.CID,
				   c.FDEBIT,
				   c.FDEBITFOR,
				   c.FCREDIT,
				   c.FCREDITFOR,
				   d.FYTDDEBIT,
				   d.FYTDDEBITFOR,
				   d.FYTDCREDIT,
				   d.FYTDCREDITFOR
		    FROM 
		    (
				SELECT a.SONID					     AS TYPEID,					   
					   a.CID,
					   a.FDC,
				       ISNULL(FDEBIT,0)				 AS FDEBIT,
					   ISNULL(FDEBITFOR,0)			 AS FDEBITFOR,
					   ISNULL(FCREDIT,0)			 AS FCREDIT,
					   ISNULL(FCREDITFOR,0)          AS FCREDITFOR
				FROM 
				(   
					SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) e
				) a 
				LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS AND a.CID=b.CID
		    ) c
		    JOIN 
		    (
				SELECT i.SONID					   AS TYPEID,
					   i.CID,
					   ISNULL(FYTDDEBIT,0)	       AS FYTDDEBIT,
					   ISNULL(FYTDDEBITFOR,0)	   AS FYTDDEBITFOR,
					   ISNULL(FYTDCREDIT,0)        AS FYTDCREDIT,
				       ISNULL(FYTDCREDITFOR,0)     AS FYTDCREDITFOR
			    FROM 
				(
					SELECT h.STYPEID,
						   h.SONID,
						   h.CID,
						   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD 
					FROM 
						( 
							SELECT * FROM #temp1,(SELECT CID FROM #MulColCid) f
						) h
					LEFT JOIN #tempAcBalance g ON g.STYPEID=h.STYPEID AND g.ATYPEID=h.SONID AND g.FYEAR=@FYear AND g.CID=h.CID AND g.FPeriod<=@tempPeriodS
					GROUP BY h.STYPEID,h.SONID,h.CID	
				) i 
				LEFT JOIN #tempAcBalance e ON i.STYPEID=e.STYPEID AND i.SONID=e.ATYPEID AND i.FPERIOD=e.FPERIOD AND e.CID=i.CID AND e.FYEAR=@FYear
		    ) d ON c.TYPEID=d.TYPEID AND c.CID=d.CID
			
			SET @tempPeriodS+=1
		END
	-----把数据插入行专列的表
	WHILE @FPeriodStart<=@FPeriodEnd
		BEGIN
			 ------插入左表本期数据
			 INSERT INTO #LeftPeriod
			 SELECT 999998,
					@FPeriodStart,
					e.COLNAME,
				  CASE
					WHEN d.CID=e.CID AND e.FDC=1  AND FLAG=-1	THEN SELFBORROW 
					WHEN d.CID=e.CID AND e.FDC=1  AND FLAG=1	THEN ORIBORROW  
					WHEN d.CID=e.CID AND e.FDC=-1 AND FLAG=-1	THEN SELFLEND
					WHEN d.CID=e.CID AND e.FDC=-1 AND FLAG=1	THEN ORILEND
					WHEN e.CID=0 AND e.FDC=1					THEN  SELFBORROW
					WHEN e.CID=0 AND e.FDC=-1					THEN SELFLEND
				  END
			FROM #tempColName e
			LEFT JOIN #tempLeftData d ON e.CID=d.CID AND d.FPERIOD=@FPeriodStart
			
			------插入左表本年数据
			INSERT INTO #LeftYear
			 SELECT 999999,
				   @FPeriodStart,
				   e.COLNAME,
				  CASE
					WHEN d.CID=e.CID AND e.FDC=1  AND FLAG=-1	THEN YSELFBORROW 
					WHEN d.CID=e.CID AND e.FDC=1  AND FLAG=1	THEN YORIBORROW  
					WHEN d.CID=e.CID AND e.FDC=-1 AND FLAG=-1	THEN YSELFLEND
					WHEN d.CID=e.CID AND e.FDC=-1 AND FLAG=1	THEN YORILEND
					WHEN e.CID=0 AND e.FDC=1					THEN  YSELFBORROW
					WHEN e.CID=0 AND e.FDC=-1					THEN YSELFLEND
				  END
			FROM #tempColName e
			LEFT JOIN #tempLeftData d ON e.CID=d.CID AND d.FPERIOD=@FPeriodStart
			
			-----插入右表本期数据
			INSERT INTO #RightPeriod
			 SELECT 999998,
					@FPeriodStart,
					e.COLNAME,
				  CASE
					WHEN c.CID=e.CID AND e.FDC=1  AND e.TYPEID=c.TYPEID AND (c.TYPEFDC=0 OR c.TYPEFDC=1) AND FLAG=-1 THEN SELFBORROW 
					WHEN c.CID=e.CID AND e.FDC=1  AND e.TYPEID=c.TYPEID AND (c.TYPEFDC=0 OR c.TYPEFDC=1) AND FLAG=1 THEN ORIBORROW  
					WHEN c.CID=e.CID AND e.FDC=-1 AND e.TYPEID=c.TYPEID AND (c.TYPEFDC=0 OR c.TYPEFDC=-1) AND FLAG=-1 THEN SELFLEND
					WHEN c.CID=e.CID AND e.FDC=-1 AND e.TYPEID=c.TYPEID AND (c.TYPEFDC=0 OR c.TYPEFDC=-1) AND FLAG=1  THEN ORILEND
				  END
			FROM #Accounts e 
			LEFT JOIN #tempRightData c ON e.TYPEID=c.TYPEID AND e.CID=c.CID AND c.FPERIOD=@FPeriodStart
			
			-----插入右表本年数据
			INSERT INTO #Rightyear
			 SELECT 999999,
					@FPeriodStart,
					e.COLNAME,
				  CASE
					WHEN c.CID=e.CID AND e.FDC=1  AND e.TYPEID=c.TYPEID AND (c.TYPEFDC=0 OR c.TYPEFDC=1) AND FLAG=-1 THEN YSELFBORROW 
					WHEN c.CID=e.CID AND e.FDC=1  AND e.TYPEID=c.TYPEID AND (c.TYPEFDC=0 OR c.TYPEFDC=1) AND FLAG=1 THEN YORIBORROW  
					WHEN c.CID=e.CID AND e.FDC=-1 AND e.TYPEID=c.TYPEID AND (c.TYPEFDC=0 OR c.TYPEFDC=-1) AND FLAG=-1 THEN YSELFLEND
					WHEN c.CID=e.CID AND e.FDC=-1 AND e.TYPEID=c.TYPEID AND (c.TYPEFDC=0 OR c.TYPEFDC=-1) AND FLAG=1 THEN YORILEND
				  END
			FROM #Accounts e
			LEFT JOIN #tempRightData c ON e.TYPEID=c.TYPEID AND e.CID=c.CID AND c.FPERIOD=@FPeriodStart
			
			SET @FPeriodStart+=1
		END
    -------------------------本期，本年插入#MulCol
    SET @SQL='INSERT INTO #MulCol(ID,FPERIOD,BILLDATE,FSERIALNAME,SUMMARY,FDC,BALANCE,'+@LeftTurnCol+','+@RightTurnCol+')
			  SELECT c.ID,
					 c.FPERIOD,
					 @FYear+''-''+CONVERT(VARCHAR(10),c.FPERIOD),
					 '''',
					 ''本期合计'',
			         CASE 
						WHEN c.BALANCE=0 THEN ''平''
						ELSE @Fdc
					END,
					c.BALANCE,'
					+@LeftTurnCol+','
					+@RightTurnCol+' 
			  FROM 
			  ( 
			    SELECT 999998 AS ID,
					   FPERIOD,
					   BALANCE 
				FROM #tempLeftData 
				WHERE CID=0
			  ) c
			  JOIN 
			  (
				SELECT *  FROM  #LeftPeriod  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@LeftTurnCol+')) b
			  ) a ON c.ID=a.ID AND c.FPERIOD=a.FPERIOD
			  JOIN 
			  (
				SELECT *  FROM  #RightPeriod  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@RightTurnCol+')) b
			  ) b ON a.ID=b.ID AND b.FPERIOD=a.FPERIOD'
   EXEC sp_executesql @SQL,N'@FYear VARCHAR(10),@Fdc VARCHAR(5)', @FYear,@Fdc  
   
   SET @SQL='INSERT INTO #MulCol(ID,FPERIOD,BILLDATE,FSERIALNAME,SUMMARY,FDC,BALANCE,'+@LeftTurnCol+','+@RightTurnCol+')
			 SELECT c.ID,
					c.FPERIOD,
					@FYear+''-''+CONVERT(VARCHAR(10),c.FPERIOD),
					'''',
					''本年累计'',
			        CASE 
						WHEN c.BALANCE=0 THEN ''平''
						ELSE @Fdc
					END,
					c.BALANCE,'
					+@LeftTurnCol+','
					+@RightTurnCol+' 
			  FROM 
			  ( 
			    SELECT 999999 AS ID,
					   FPERIOD,BALANCE 
				FROM #tempLeftData 
				WHERE CID=0
			  ) c
			  JOIN 
			  (
				SELECT *  FROM  #LeftYear  pivot (MAX(FVALUE) FOR COLNAME IN ('+@LeftTurnCol+')) b
			  ) a ON c.ID=a.ID AND c.FPERIOD=a.FPERIOD
			  JOIN 
			  (
				SELECT *  FROM  #RightYear PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@RightTurnCol+')) b
			  ) b ON a.ID=b.ID AND b.FPERIOD=a.FPERIOD'
   EXEC sp_executesql @SQL,N'@FYear VARCHAR(10),@Fdc VARCHAR(5)', @FYear,@Fdc  
   
   ------查询数据
   SELECT * FROM #MulCol ORDER BY FPeriod,ID
   
	-----获取动态列
	SELECT FULLNAME,
		   USERCODE
	FROM #temp1
	ORDER BY USERCODE
   
   
   IF @IsBalanceNull=1 OR @IsNull=1
		DROP TABLE #temp2,#temp3
   DROP TABLE #tempAcBalance,#temp1,#Accounts,#MulCol,#tempMulCol,#tempColName1,#tempColName2,#tempColName,#MulColCid,
			  #BeginBalance,#RightGetValue,#LeftGetValue,#LeftBalance,#AccountBegin,#RightBalance,#RightYear,#LeftYear,#RightPeriod,#LeftPeriod,#tempLeftData,#tempRightData
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MulColSelfAssistQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_MulColSelfAssistQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/30
	Description	: 查询费明细科目辅助核算项本位币的多栏账
*/
CREATE PROCEDURE Web_MulColSelfAssistQuery
(
    @STypeId 			VARCHAR(50),		---分支机构ID
    @AssistId			BIGINT,				---方案id
    @fyear				INT,
	@FPeriodStart		INT,				---起始期间
	@FPeriodEnd			INT,				---结束期间   
	@IsBalanceNull		BIT,				-- 无发生额且无余额不显示 1：是 0：否
	@IsNull				BIT,				---无发生额不显示 1：是 0：否
	@IsPost				BIT,				---是否显示未过账凭证 1：是 0：否
	@chvOperatorID      VARCHAR(50)			---操作员ID
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE @ATypeId			VARCHAR(50),                ---方案查询科目id
			@Fdc				VARCHAR(5),					---该科目的方向名称
			@AssistUserCode		VARCHAR(200),				---方案中核算项的名称
			@Balance			 NUMERIC(24, 10) ,				---期初余额
			@iniFYear			VARCHAR(5),				    --启用年度
			@FPeriod			INT,						---启用期间
			@SQL				NVARCHAR(MAX),               ---查询各个期间的动态sql
			@tempPeriodS		INT=@FPeriodStart,
		    @tempPeriodE		INT=@FPeriodEnd,
		    @Cids				VARCHAR(MAX),
		    @Ascid				INT,						--add by dongzhan 2012.10.30 
			@LimitOwnVoucher	INT=0	--仅能查看本人制单的会计凭证
		
	SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@chvOperatorID
		
	SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	IF @iniFYear=@Fyear
		SELECT @Fperiod=SFPeriod from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	ELSE 
		SELECT @Fperiod=MIN(CONVERT(INT,FPeriod)) FROM dbo.Ac_Period
	------------------------------------------modify by dongzhan 2012.10.30 权限管理----------------------------------------------------------------------------------------------
	SELECT @Ascid=ASCID FROM Ac_MulColumnAccount WHERE ASSISTID=@AssistId
	CREATE TABLE #tempRight(TYPEID VARCHAR(50))
	DECLARE @sqlman VARCHAR(8000) 
	IF @Ascid=1 ---分支机构
		SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',11,@chvOperatorID,'#tempRight')
	ELSE IF @Ascid=2 ---部门
	   SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',9,@chvOperatorID,'#tempRight')
	ELSE IF @Ascid=3 ---职员
		SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',3,@chvOperatorID,'#tempRight')
	ELSE IF @Ascid=4 ---往来单位
		SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId('',2,@chvOperatorID,'#tempRight')
	 ELSE---自定义辅助核算
		BEGIN
			INSERT INTO #tempRight(TYPEID)
			SELECT TypeId FROM dbo.F_GetAllAssistCheckItemsDetail('',@Ascid,@chvOperatorID)
	    END
	EXEC(@sqlman)
	-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	---获取方案中的科目
	SELECT @ATypeId=ATYPEID FROM dbo.Ac_MulColumnAccount WHERE ASSISTID=@AssistId
	---该科目的方向
	SELECT  @Fdc=CASE 
						WHEN FDC=1 THEN '借'
						ELSE '贷'
					END
	 FROM dbo.Ac_Account 
	 WHERE STYPEID=@STypeId AND 
		   TYPEID=@ATypeId
	---获取方案中的辅助核算项目usercode
	SELECT @AssistUserCode=b.USERCODE
	FROM dbo.Ac_MulColumnAccount a
	JOIN  Ac_Assist_CheckItems b ON a.ASCID=b.ASCIDS
	WHERE ASSISTID=@AssistId
	
	---要分析的币别
	 SELECT @Cids=CIDS
	 FROM dbo.Ac_MulColumnAccount 
	 WHERE ASSISTID=@AssistId
	
	 CREATE TABLE #MulColCid
	 (
		CID			INT,
		FULLNAME	VARCHAR(200),
		USERCODE	VARCHAR(200)
	 )
	 INSERT INTO #MulColCid
	 SELECT a.CID,
			a.FullName,
			a.UserCode
	 FROM Ac_Currency a
	 JOIN 
	 (
		SELECT a FROM F_Split(@Cids,',')
	 ) b ON a.CID=b.a
	-------------------------------无论选择过账与否,都重新生成一个临时科目余额表,todo 等佘海源的存储过程-----------------------------------------------------------
	 CREATE TABLE  #tempAcBalanceDetail
	(
		STYPEID             VARCHAR(50),       
		ATYPEID             VARCHAR(50),        
		CID                 INT,               
		ASCIDS              INT,                
		FIELDVALUE          VARCHAR(50),        
		FDEBIT				 NUMERIC(24, 10) ,		
		FDEBITFOR			 NUMERIC(24, 10) ,		
		FCREDIT				 NUMERIC(24, 10) ,		
		FCREDITFOR			 NUMERIC(24, 10) ,		
		INITOTAL			 NUMERIC(24, 10) ,	
		INITOTALFOR			 NUMERIC(24, 10) ,		
		FENDBALANCE			 NUMERIC(24, 10) ,		
		FENDBALANCEFOR		 NUMERIC(24, 10) ,		
		FYEAR               VARCHAR(10),       
		FPERIOD             INT          
	)
	INSERT INTO #tempAcBalanceDetail
	EXEC WEB_AcAssistBalanceDetailFromVoucher @IsPost,@FYear,@STypeId
--权限控制，删除不在权限范围类的数据
DELETE FROM #tempAcBalanceDetail WHERE ATypeId NOT IN(SELECT Typeid FROM F_LineAccount(@chvOperatorID,@STypeId) )

-----------------------------------------要分析的辅助核算项及核算项要分析的方向--------------------------------------------------------------------
	CREATE TABLE #temp1
	(
	   STYPEID			VARCHAR(50),  --分支机构id
	   ATYPEID			VARCHAR(50),  --科目id
	   ASCID			INT,		  --核算项id
	   ASCIDUSERCODE	VARCHAR(200),  --核算项usercode，关联AC_VOUCHER_BILL_ASSIST_CHECKITEMS用
	   PROTYPEID		VARCHAR(50),  --要分析的项目id
	   PROFDC			INT,		  --要分析的项目的方向
	   PROUSERCODE		VARCHAR(200), --要分析的项目usercode
	   PROFULLNAME		VARCHAR(200)  --要分析的项目fullname
	)
	SET @SQL='INSERT INTO #temp1
			  SELECT a.STYPEID,
					 a.ATYPEID,
					 a.ASCID,
					 @AssistUserCode,
					 d.TYPEID,
					 b.FDC,
					 d.USERCODE,
					 d.FULLNAME 
			  FROM Ac_MulColumnAccount a
			  JOIN AC_MULCOLUMNACCOUNT_ASSIST b ON a.ASSISTID=b.ASSISTID '
	IF EXISTS(SELECT 1 FROM #tempRight)                    --modify by dongzhan 2013.1.28  权限函数改变，权限临时表判断也改变
		SET @SQL+='JOIN #tempRight e ON b.FVALUE=e.TYPEID ' 
	IF @AssistUserCode='01'
		SET @SQL+='JOIN STYPE d ON b.FVALUE=d.TYPEID'
	ELSE IF @AssistUserCode='02'
		SET @SQL+='JOIN DEPARTMENT d ON b.FVALUE=d.TYPEID'
	ELSE IF @AssistUserCode='03'
		SET @SQL+='JOIN EMPLOYEE d ON b.FVALUE=d.TYPEID'
	ELSE IF @AssistUserCode='04'
		SET @SQL+='JOIN BTYPE d ON b.FVALUE=d.TYPEID'
	ELSE 
		SET @SQL+='INNER JOIN Ac_Assist_CheckItemsDetail D ON D.TypeId=b.FVALUE'
	SET @SQL+=' WHERE a.ASSISTID=@AssistId'
	EXEC sp_executesql @SQL,N'@AssistUserCode VARCHAR(200),@AssistId BIGINT', @AssistUserCode,@AssistId
	---------------------------------------------------表左边的统计信息-----------------------------------------------------------------------------
	CREATE TABLE #totalTable
	(
		ID						INT IDENTITY(1,1),      --Modify 12-10-19，原来取的是AC_VOUCHER_BILL的ID，现在为了最后一步排序，重新生成			
		BILLNUMBERID			NUMERIC,			    --凭证ID
		PROTYPEID				VARCHAR(50),			--核算项目选择值的ID
		PROFDC					INT,					--核算项目选择值要分析的方向
		FPERIOD 				INT,					--期间
		BORROW                   NUMERIC(24, 10) ,			--明细科目核算项的借
		LEND                     NUMERIC(24, 10) ,			--明细科目核算项的贷
		SUMMARY					VARCHAR(400),
		FDC						VARCHAR(5),				--方向
		BALANCE					 NUMERIC(24, 10) 			--余额
	)
	SET @SQL='INSERT INTO #totalTable(BILLNUMBERID,PROTYPEID,PROFDC,FPERIOD,BORROW,LEND,SUMMARY,FDC)
			SELECT a.BILLNUMBERID,
				   c.PROTYPEID,
				   c.PROFDC,
				   a.FPERIOD,
				   a.FDEBITTOTAL AS BORROW,
				   a.FCREDITTOTAL AS LEND,
				   a.SUMMARY,
				   @Fdc
			FROM AC_VOUCHER_BILL a
			INNER JOIN F_LineAccount('''+@chvOperatorID+''','''+@STypeId+''') F ON F.TypeID=a.ATypeId AND F.Stypeid=a.STypeId
			JOIN Ac_Voucher_Bill_Assist_CheckItems b ON a.BILLNUMBERID=b.BILLNUMBERID AND a.ID=b.VBID 
			JOIN #temp1 c                            ON a.ATYPEID=c.ATYPEID AND b.TYPENAME=c.ASCIDUSERCODE AND c.PROTYPEID=b.TYPEID 
			JOIN Ac_Voucher d                        ON a.BILLNUMBERID=d.BILLNUMBERID AND d.FYEAR=@FYear AND d.FPERIOD >=@FPeriodStart AND d.FPERIOD<=@FPeriodEnd AND FCHECKED <> -1 '
	IF @IsPost=0
		SET @SQL+='AND IFCHECK=''t'' '
	SET @SQL+=' JOIN #MulColCid e ON a.CID=e.CID  
			 WHERE a.STYPEID=@STypeId
			 ORDER BY a.FPERIOD,d.BILLDATE,a.BILLNUMBERID,a.ID'
	EXEC sp_executesql @SQL,N'@FYear VARCHAR(10),@FPeriodStart INT,@FPeriodEnd INT,@Fdc VARCHAR(10),@STypeId VARCHAR(50)',@FYear,@FPeriodStart,@FPeriodEnd,@Fdc,@STypeId
	
	------------------根据查询条件剔除不符合的科目 
	IF @IsBalanceNull=1 OR @IsNull=1
		BEGIN
			CREATE TABLE #temp2
			(
			    PROTYPEID		VARCHAR(50),	---分析的辅助核算项的选择值
			    BALANCE			 NUMERIC(24, 10) 	---本期余额
			)
			
		    INSERT INTO #temp2
			SELECT c.PROTYPEID,
				   SUM(ISNULL(d.FENDBALANCE,0)) AS BALANCE
			FROM 
			(
				SELECT a.STYPEID,
					   a.ATYPEID,
					   a.ASCID,
					   a.PROTYPEID,
					   a.CID,
				   ISNULL(MAX(FPERIOD),@FPeriodEnd) AS FPERIOD
				FROM
				(
				   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.PROTYPEID=b.FIELDVALUE AND a.ASCID=b.ASCIDS AND 
																   b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodEnd AND b.CID=a.CID
				GROUP BY a.STYPEID,a.ATYPEID,a.PROTYPEID,a.CID,a.ASCID
			) c 
			LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.PROTYPEID=d.FIELDVALUE AND c.ASCID=d.ASCIDS AND 
																   d.FYEAR=@FYear AND c.FPERIOD=d.FPERIOD AND c.CID=d.CID
			GROUP BY c.PROTYPEID
			
			CREATE TABLE #temp3
			(
			    PROTYPEID		VARCHAR(50),	---分析的辅助核算项的选择值
			    PERIODCHANGE	 NUMERIC(24, 10) ,
			    BALANCE			 NUMERIC(24, 10) 	---本期余额
			)
			INSERT INTO #temp3
			SELECT a.PROTYPEID,
				   ISNULL(b.PERIODCHANGE,0),
				   a.BALANCE
			FROM #temp2 a
			LEFT JOIN 
					(
						SELECT  PROTYPEID,
								SUM(ABS(ISNULL(BORROW,0)))+SUM(ABS(ISNULL(LEND,0))) AS PERIODCHANGE
						FROM #totalTable
						GROUP BY PROTYPEID
					) b ON a.PROTYPEID=b.PROTYPEID
					
		    SELECT PROTYPEID
		    INTO #temp4
		    FROM #temp3 
		    WHERE	((@IsNull=1 AND PERIODCHANGE>0) OR @IsNull=0) AND
					((@IsBalanceNull=1 AND BALANCE!=0 OR PERIODCHANGE>0) OR @IsBalanceNull=0) 
				
			DELETE FROM #temp1  WHERE NOT EXISTS (SELECT 1 FROM #temp4 b WHERE #temp1.PROTYPEID=b.PROTYPEID)
		END

	 ---分析项目与借贷交叉连接，以待后面行转列：还要判断分析方向，控制列的显示列数
    CREATE TABLE #Projects
    (
       STYPEID			VARCHAR(50),  --分支机构id
	   ATYPEID			VARCHAR(50),  --科目id
	   ASCID			INT,		  --核算项id
	   ASCIDUSERCODE	VARCHAR(50),  --核算项usercode，关联AC_VOUCHER_BILL_ASSIST_CHECKITEMS用
	   PROTYPEID		VARCHAR(50),  --要分析的项目id
	   FDC				INT,		  --要分析的项目的方向
	   COLNAME			VARCHAR(max)  --行转列的列名
    )
    SET @SQL='INSERT INTO #Projects
			  SELECT STYPEID,
					 ATYPEID,
					 ASCID,
					 ASCIDUSERCODE,
					 PROTYPEID,
					 d.FDC,
					 SUBSTRING(COLNAME+PROUSERCODE,0,128) AS COLNAME
			  FROM #temp1 c,'
	IF (SELECT COUNT(1) FROM ( SELECT PROFDC FROM #temp1 GROUP BY PROFDC) a)=2 OR (SELECT TOP 1 1 FROM #temp1 WHERE PROFDC=0)=1
		SET @SQL+='( SELECT ''borrow'' AS COLNAME,1 AS FDC 
					UNION ALL
					SELECT ''lend'' AS COLNAME,-1 AS FDC 
					) d'
	ELSE IF (SELECT TOP 1 1 FROM #temp1 WHERE PROFDC=1)=1
		SET @SQL+='( SELECT ''borrow'' AS COLNAME,1 AS FDC) d'
	ELSE 
		SET @SQL+='( SELECT ''lend'' AS COLNAME,-1 AS FDC) d'			
	EXEC(@SQL)
	
	-------------------------------------------------更新余额----------------------------------------------------------------------------------------- 
	-------------如果查询期间是第一期，期初的借和贷要到账务期初去查询
	CREATE TABLE #IniAccountBorrowLend
	(
	    STYPEID	   VARCHAR(50),
	    ATYPEID	   VARCHAR(50),			---明细科目的ID			 
	    FPERIOD	   INT,
	    INIBORROW   NUMERIC(24, 10) ,
	    INILEND	    NUMERIC(24, 10) 
	)
	INSERT INTO #IniAccountBorrowLend
	SELECT a.STYPEID,
		   a.ATYPEID,
		   @FPeriod,
		   SUM(ISNULL(FDEBIT,0))  AS BORROW,
		   SUM(ISNULL(FCREDIT,0)) AS LEND
	FROM 
		(
		  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
		) a
	LEFT JOIN dbo.AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.CID=b.CID AND b.FYEAR=@FYear AND 
															  b.FPERIOD=@FPeriod AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE 
	GROUP BY a.STYPEID,a.ATYPEID
	
	
	CREATE TABLE #BeginBorrowLend
	(
	    STYPEID	   VARCHAR(50),
	    ATYPEID	   VARCHAR(50),			---明细科目的ID			 
	    FPERIOD	   INT,
	    BORROW	    NUMERIC(24, 10) ,
	    LEND	    NUMERIC(24, 10) 
	)
	IF @FPeriodStart=@FPeriod
		INSERT INTO #BeginBorrowLend
		SELECT * FROM #IniAccountBorrowLend
	ELSE 
		INSERT INTO #BeginBorrowLend
		SELECT a.STYPEID,
			   a.ATYPEID,
			   @FPeriodStart AS FPERIOD,
			   SUM(ISNULL(FDEBIT,0))+INIBORROW,
			   SUM(ISNULL(FCREDIT,0))+INILEND
		FROM 
		( 
		     SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
		) a
		LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
											a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<@FPeriodStart
		JOIN #IniAccountBorrowLend c ON a.STYPEID=c.STYPEID AND a.ATYPEID=c.ATYPEID
		GROUP BY a.STYPEID,a.ATYPEID,INIBORROW,INILEND
	-------------求出期初
	CREATE TABLE #BeginBalance
	(
	     STYPEID VARCHAR(50),
	     ATYPEID VARCHAR(50),
	     FPERIOD INT,
	     BORROW	  NUMERIC(24, 10) ,
	     LEND	  NUMERIC(24, 10) ,
	     BALANCE  NUMERIC(24, 10) 
	)
	INSERT INTO #BeginBalance
	SELECT a.STYPEID,
		   a.ATYPEID,
		   @FPeriodStart,
		   b.BORROW,
		   b.LEND,
		   a.BALANCE
	FROM 
	(	SELECT f.STYPEID,
			   f.ATYPEID,
			   SUM(BALANCE) AS BALANCE
		FROM 
		(
			SELECT e.STYPEID,
				   e.ATYPEID,
				   CASE 
						WHEN e.FPERIOD=@FPeriod AND FLAG=0 THEN ISNULL(INITOTAL,0)		---查询期初期间是启用期间，直接取它的期初值，否则取上一期的期末余额
						ELSE ISNULL(FENDBALANCE,0)
				   END  AS BALANCE
			FROM
			(
				SELECT c.STYPEID,
					   c.ATYPEID,
					   c.ASCID,
					   c.PROTYPEID,
					   c.CID,
					   CASE 
							WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart AND ISNULL(MAX(FPERIOD),@FPeriodStart)!=@FPeriod THEN @FPeriodStart-1
							ELSE ISNULL(MAX(FPERIOD),@FPeriodStart)
					   END AS FPERIOD,
					  CASE							                                      ----标示取出的的期间到底是该取期初还是期末
						WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart AND ISNULL(MAX(FPERIOD),@FPeriodStart)!=@FPeriod THEN 1                              --取上期期末的情况
					    WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)!=@FPeriodStart AND ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriod AND @FPeriodStart!=@FPeriod THEN 2 --期初是7，查询8期，某币种最大期间是7，该期间取期末的情况
						ELSE 0
					  END AS FLAG
				FROM 
				(
				   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) c 
				LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.ASCID=d.ASCIDS AND c.PROTYPEID=d.FIELDVALUE AND 
													c.CID=d.CID AND d.FYEAR=@FYear AND d.FPERIOD<=@FPeriodStart
				GROUP BY c.STYPEID,c.ATYPEID,c.ASCID,c.PROTYPEID,c.CID
			) e 
			LEFT JOIN #tempAcBalanceDetail f ON e.STYPEID=f.STYPEID AND e.ATYPEID=f.ATYPEID AND e.ASCID=f.ASCIDS AND e.PROTYPEID=f.FIELDVALUE AND 
												e.CID=f.CID AND f.FYEAR=@FYear AND e.FPERIOD=f.FPERIOD
		) f
		GROUP BY f.STYPEID,f.ATYPEID
	) a
	JOIN #BeginBorrowLend b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID
	
	SELECT @Balance=BALANCE FROM #BeginBalance
	UPDATE #totalTable SET @BALANCE+=CASE 
										WHEN @Fdc='借' THEN (ISNULL(BALANCE,0)+ISNULL(BORROW,0)-ISNULL(LEND,0))
										ELSE (ISNULL(BALANCE,0)-ISNULL(BORROW,0)+ISNULL(LEND,0))
									 END,
							BALANCE=@BALANCE,
							FDC=CASE 
									WHEN @Balance=0 THEN '平'
									ELSE @Fdc
								END
	---------------------生成符合查询格式的临时表
	CREATE TABLE #MulCol
	(
	  ID			INT,					---凭证明细表中的的id
	  FPERIOD		INT,
	  PROTYPEID		VARCHAR(50),			---核算项目值的id
	  PROFDC		INT,					---核算项值要分析的方向			 
	  BILLDATE		VARCHAR(10),
	  FSERIALNAME	VARCHAR(200),
	  SUMMARY		VARCHAR(400),
	  FDC			VARCHAR(10),			---明细科目的余额方向
	  BORROW		 NUMERIC(24, 10) ,
	  LEND			 NUMERIC(24, 10) ,
	  BALANCE        NUMERIC(24, 10), 
	  ETypeId		VARCHAR(50)	NOT NULL DEFAULT('')--制单人
	)
	INSERT INTO #MulCol
	SELECT a.ID,
		   a.FPERIOD,
		   a.PROTYPEID,
		   a.PROFDC,
		   CONVERT(VARCHAR(10),BILLDATE,120),
		   CASE WHEN @LimitOwnVoucher=1 AND c.ETypeId<>@chvOperatorID THEN '****' ELSE d.FullName+'-'+CONVERT(VARCHAR(10),c.FlowNo) END ,
		   CASE WHEN @LimitOwnVoucher=1 AND c.ETypeId<>@chvOperatorID THEN '****' ELSE dbo.F_GetSummaryByLimit(a.ID,@chvOperatorID,C.STypeId,a.Summary) END Summary,
		   a.FDC,
		   a.BORROW,
		   a.LEND,
		   a.BALANCE,
		   c.ETypeId
	FROM #totalTable a
	JOIN dbo.Ac_Voucher c ON a.BILLNUMBERID=c.BILLNUMBERID
	JOIN AC_VOUCHER_GROUP d ON c.VGID = d.VGID
	-----------------------------------------------凭证处理右表---------------------------------------------------------------------------------------------
	---获取待行转列的列对应的值
	CREATE TABLE #GetValue
	(
		ID			   INT,					--对应凭证明细表中的ID
		FPERIOD        INT,					--期间
		PROTYPEID	   VARCHAR(50),			--要分析辅助核算项具体值的ID
		COLNAME		   VARCHAR(MAX),		--要转列的列名
		FVALUE          NUMERIC(24, 10) 		--列对应的值
	)
	INSERT INTO #GetValue (ID,FPERIOD,PROTYPEID,COLNAME,FVALUE)
	SELECT b.ID,
		   b.FPERIOD,
		   b.PROTYPEID,
		   a.COLNAME,
		CASE 
			WHEN a.FDC=1  AND a.PROTYPEID=b.PROTYPEID AND (b.PROFDC=0 OR b.PROFDC=1) THEN b.BORROW
			WHEN a.FDC=-1 AND a.PROTYPEID=b.PROTYPEID AND (b.PROFDC=0 OR b.PROFDC=-1) THEN b.LEND 
		END 
	FROM #Projects a,#MulCol b
	-----------------------------------------------获取左表的期初，本期合计，本年累计--------------------------------------------------------------
	----期初
	INSERT INTO #MulCol 
    SELECT -1,
		   FPERIOD,
		   '1',
		   0,
		   '',
		   '',
		   '期初余额',
		   CASE
				WHEN BALANCE=0 THEN '平'
				ELSE @Fdc
		   END  AS FDC,
		   BORROW,
		   LEND,
		   BALANCE,
		   '' ETypeId
	FROM #BeginBalance

	WHILE @tempPeriodS<=@tempPeriodE
		BEGIN
			-----本期合计
			INSERT INTO #MulCol(ID,FPERIOD,PROTYPEID,PROFDC,BILLDATE,FSERIALNAME,SUMMARY,FDC,BORROW,LEND,BALANCE)
			SELECT 999998,
				   @tempPeriodS,
				   '999998',
				   0,
				   CONVERT(VARCHAR(10),@FYear)+'-'+CONVERT(VARCHAR(10),@tempPeriodS),
				    '',
				   '本期合计',
				   CASE
						WHEN ISNULL(BALANCE,0)=0 THEN '平'
						ELSE @Fdc
				   END,
				   ISNULL(BORROW,0),
				   ISNULL(LEND,0),
				   ISNULL(BALANCE,0) 
			FROM 
			(
				SELECT a.ATYPEID,
					   SUM(ISNULL(FDEBIT,0)) AS BORROW,
					   SUM(ISNULL(FCREDIT,0)) AS LEND
				FROM 
				(
				  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
													a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS
				GROUP BY a.ATYPEID
			) e
			JOIN 
			(
				SELECT  c.ATYPEID,
						SUM(ISNULL(FENDBALANCE,0)) AS BALANCE 
				FROM
				(
					SELECT a.STYPEID,
						   a.ATYPEID,
						   a.ASCID,
						   a.PROTYPEID,
						   a.CID,
						   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD
					FROM
					(
					  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
					) a
					LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
														a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<=@tempPeriodS
					GROUP BY a.STYPEID,a.ATYPEID,a.ASCID,a.PROTYPEID,a.CID
				) c 
				LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.ASCID=d.ASCIDS AND c.PROTYPEID=d.FIELDVALUE AND 
														c.CID=d.CID AND d.FYEAR=@FYear AND d.FPERIOD=c.FPERIOD 
				GROUP BY c.ATYPEID
			) f ON e.ATYPEID=f.ATYPEID
			
			------本年累计
			INSERT INTO #MulCol
			SELECT 999999,
				   @tempPeriodS,
				   '999999',
				   0,
				   CONVERT(VARCHAR(10),@FYear)+'-'+CONVERT(VARCHAR(10),@tempPeriodS),
				    '',
				   '本年累计',
				   CASE
						WHEN ISNULL(f.BALANCE,0)=0 THEN '平'
						ELSE @Fdc
				   END,
				   ISNULL(e.BORROW,0)+ISNULL(g.INIBORROW,0),
				   ISNULL(e.LEND,0)+ISNULL(g.INILEND,0),
				   ISNULL(f.BALANCE,0),
				   '' ETypeId
			FROM 
			(
				SELECT a.ATYPEID,
					   SUM(ISNULL(FDEBIT,0)) AS BORROW,
					   SUM(ISNULL(FCREDIT,0)) AS LEND
				FROM 
				(
				  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
				) a
				LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
													a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<=@tempPeriodS
				GROUP BY a.ATYPEID
			) e
			JOIN 
			(
				SELECT  c.ATYPEID,
						SUM(ISNULL(FENDBALANCE,0)) AS BALANCE 
				FROM
				(
					SELECT a.STYPEID,
						   a.ATYPEID,
						   a.ASCID,
						   a.PROTYPEID,
						   a.CID,
						   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD
					FROM
					(
					  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
					) a
					LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
														a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<=@tempPeriodS
					GROUP BY a.STYPEID,a.ATYPEID,a.ASCID,a.PROTYPEID,a.CID
				) c 
				LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.ASCID=d.ASCIDS AND c.PROTYPEID=d.FIELDVALUE AND 
														c.CID=d.CID AND d.FYEAR=@FYear AND d.FPERIOD=c.FPERIOD 
				GROUP BY c.ATYPEID
			) f ON e.ATYPEID=f.ATYPEID
			JOIN  #IniAccountBorrowLend g ON e.ATYPEID=g.ATYPEID                    ----账务期初的借和贷
			
			SET @tempPeriodS+=1   
		END
	---------------------------------------------------------获取右表的期初,本期合计，本年合计-------------------------------------------------------------------------
	-------------------------------期初
	----账务期初
	CREATE TABLE #IniAssistBegin
	(
	   PROTYPEID VARCHAR(50),		--要分析的赋值核算项具体的
	   FPERIOD	 INT,
	   INIBORROW	  NUMERIC(24, 10) ,
	   INILEND		  NUMERIC(24, 10) 
	)
	INSERT INTO #IniAssistBegin
	SELECT a.PROTYPEID,
		   @FPeriod,
		   SUM(ISNULL(FDEBIT,0))  AS BORROW,
		   SUM(ISNULL(FCREDIT,0)) AS LEND
	FROM 
		(
		  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
		) a
	LEFT JOIN dbo.AC_INIACCOUNT_ASSIST_CHECKITEMS_DETAIL b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.CID=b.CID AND b.FYEAR=@FYear AND 
															  b.FPERIOD=@FPeriod AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE 
	GROUP BY a.PROTYPEID
	
	CREATE TABLE #AssistBegin
	(
	   PROTYPEID VARCHAR(50),		--要分析的赋值核算项具体的
	   FPERIOD	 INT,
	   BORROW	  NUMERIC(24, 10) ,
	   LEND		  NUMERIC(24, 10) 
	)
	IF @FPeriodStart=@FPeriod
		INSERT INTO #AssistBegin
		SELECT * FROM #IniAssistBegin
	ELSE 
		INSERT INTO #AssistBegin
		SELECT a.PROTYPEID,
			   @FPeriodStart,
			   SUM(ISNULL(FDEBIT,0))+INIBORROW  AS BORROW,
			   SUM(ISNULL(FCREDIT,0))+INILEND   AS LEND
		FROM 
		( 
		     SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
		) a
		LEFT JOIN #tempAcBalanceDetail b ON a.STYPEID=b.STYPEID AND a.ATYPEID=b.ATYPEID AND a.ASCID=b.ASCIDS AND a.PROTYPEID=b.FIELDVALUE AND 
											a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD<@FPeriodStart
		JOIN #IniAssistBegin c ON a.PROTYPEID=c.PROTYPEID
		GROUP BY a.PROTYPEID,c.INIBORROW,c.INILEND
	
	INSERT INTO #GetValue
    SELECT -1,
		   @FPeriodStart,
		   '1',
		   a.COLNAME,
		   CASE 
				WHEN a.PROTYPEID=b.PROTYPEID AND a.FDC=1 THEN BORROW
				WHEN a.PROTYPEID=b.PROTYPEID AND a.FDC=-1 THEN LEND
		   END
	FROM #Projects a 
	LEFT JOIN #AssistBegin b ON a.PROTYPEID=b.PROTYPEID
     
	WHILE @FPeriodStart <= @FPeriodEnd
		BEGIN
			----本期合计
			INSERT INTO #GetValue
			SELECT 999998,
				   @FPeriodStart,
				   '999998',
				   a.COLNAME,
				   CASE 
						WHEN a.PROTYPEID=b.PROTYPEID AND a.FDC=1 THEN BORROW
						WHEN a.PROTYPEID=b.PROTYPEID AND a.FDC=-1 THEN LEND
				   END
			FROM #Projects a 
			LEFT JOIN 
			(
			    SELECT c.PROTYPEID,
					   SUM(ISNULL(FDEBIT,0)) AS BORROW,
					   SUM(ISNULL(FCREDIT,0)) AS LEND
				FROM
					(
					   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
					) c
				LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.PROTYPEID=d.FIELDVALUE AND c.ASCID=d.ASCIDS AND
													d.FYEAR=@FYear AND d.FPERIOD=@FPeriodStart AND d.CID=c.CID
				GROUP BY c.PROTYPEID
			) b ON a.PROTYPEID=b.PROTYPEID
		
		
			---本年累计
			INSERT INTO #GetValue
			SELECT 999999,
				   @FPeriodStart,
				   '999999',
				   a.COLNAME,
				   CASE 
						WHEN a.PROTYPEID=b.PROTYPEID AND a.FDC=1 THEN b.BORROW
						WHEN a.PROTYPEID=b.PROTYPEID AND a.FDC=-1 THEN b.LEND
				   END
			FROM #Projects a 
			LEFT JOIN 
			(
			    SELECT c.PROTYPEID,
					   SUM(ISNULL(FDEBIT,0))+e.INIBORROW AS BORROW,
					   SUM(ISNULL(FCREDIT,0))+e.INILEND AS LEND
				FROM
					(
					   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
					) c
				LEFT JOIN #tempAcBalanceDetail d ON c.STYPEID=d.STYPEID AND c.ATYPEID=d.ATYPEID AND c.PROTYPEID=d.FIELDVALUE AND c.ASCID=d.ASCIDS AND
													d.FYEAR=@FYear AND d.FPERIOD<=@FPeriodStart AND d.CID=c.CID
				JOIN #IniAssistBegin e ON c.PROTYPEID=e.PROTYPEID
				GROUP BY c.PROTYPEID,e.INIBORROW,e.INILEND
			) b ON a.PROTYPEID=b.PROTYPEID
			
			
			SET @FPeriodStart+=1
		END
		
	----------------#GetValue行专列，与#MulCol关联---------------------------------------------------------------------------------------------------------
	DECLARE @TurnCol VARCHAR(MAX)
	SELECT @TurnCol=(ISNULL(@TurnCol+'],[','') +  COLNAME) 
	FROM #GetValue GROUP BY COLNAME 
	SET @TurnCol='['+@TurnCol+']'
   
   
   IF EXISTS (SELECT TOP 1 1 FROM #temp1)
		BEGIN
			SET @SQL='SELECT * 
					FROM #MulCol a
					JOIN
						(
							 SELECT *  FROM  #GetValue  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) b
						) c	ON a.ID=c.ID AND a.FPERIOD=c.FPERIOD
					ORDER BY a.FPERIOD,a.ID'
			EXEC(@SQL)
			
			---动态列
			SELECT PROUSERCODE AS USERCODE,
				   PROFULLNAME AS FULLNAME
			FROM #temp1
			ORDER BY PROUSERCODE
		END
	ELSE
		BEGIN
			SELECT * FROM #MulCol
			
			---动态列
			SELECT PROUSERCODE AS USERCODE,
				   PROFULLNAME AS FULLNAME
			FROM #temp1
			ORDER BY PROUSERCODE
		END
		
	
	IF @IsBalanceNull=1 OR @IsNull=1
		DROP TABLE #temp2,#temp3,#temp4
	DROP TABLE #temp1,#MulColCid,#tempAcBalanceDetail,#Projects,#totalTable,#BeginBorrowLend,#BeginBalance,#MulCol,#GetValue,#AssistBegin,#IniAssistBegin,#IniAccountBorrowLend,#tempRight
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MulColSelfQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_MulColSelfQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/05/08
	Description	: 查询非明细科目本位币的多栏账
*/

CREATE PROCEDURE Web_MulColSelfQuery
(
    @STypeId 			VARCHAR(50),		---分支机构ID
    @AssistId			BIGINT,				---方案id
    @fyear				INT,
	@FPeriodStart		INT,				---起始期间
	@FPeriodEnd			INT,				---结束期间   
	@IsBalanceNull		BIT,				-- 无发生额且无余额不显示 1：是 0：否
	@IsNull				BIT,				---无发生额不显示 1：是 0：否
	@IsPost				BIT,				---是否显示未过账凭证 1：是 0：否
	@chvOperatorID		VARCHAR(50)			--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE 
		@ATypeId			VARCHAR(50),                ---方案查询科目id
		@FdcId				INT,						---该科目的方向表示值
		@Fdc				VARCHAR(5),					---该科目的方向名称
		@iniFYear			VARCHAR(5),				    --启用年度
		@FPeriod			INT,
		@SQL				NVARCHAR(MAX),              ---查询各个期间的动态sql
		@Balance			 NUMERIC(24, 10) ,
		@tempPeriodS		INT=@FPeriodStart,
		@tempPeriodE		INT=@FPeriodEnd,
		@Cids				VARCHAR(MAX),				---要分析的币别
		@LimitOwnVoucher	VARCHAR(1)=0--仅能查看本人制单的会计凭证

	SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@chvOperatorID

	---获取年度和本位币
	SELECT @iniFYear=SFYear from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	IF @iniFYear=@Fyear
		SELECT @Fperiod=SFPeriod from Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId
	ELSE 
		SELECT @Fperiod=MIN(CONVERT(INT,FPeriod)) FROM dbo.Ac_Period
	---获取方案中的科目
	SELECT @ATypeId=ATYPEID FROM dbo.Ac_MulColumnAccount WHERE ASSISTID=@AssistId
	---该科目的方向
	SELECT @FdcId=FDC,
		   @Fdc=CASE 
					WHEN FDC=1 THEN '借'
					ELSE '贷'
				END
	 FROM dbo.Ac_Account 
	 WHERE STYPEID=@STypeId AND TYPEID=@ATypeId
	 
	 ---要分析的币别
	 SELECT @Cids=CIDS
	 FROM dbo.Ac_MulColumnAccount 
	 WHERE ASSISTID=@AssistId
	
	 CREATE TABLE #MulColCid
	 (
		CID			INT,
		FULLNAME	VARCHAR(200),
		USERCODE	VARCHAR(200)
	 )
	 INSERT INTO #MulColCid
	 SELECT a.CID,
			a.FullName,
			a.UserCode
	 FROM Ac_Currency a
	 JOIN 
	 (
		SELECT a FROM F_Split(@Cids,',')
	 ) b ON a.CID=b.a
	 -------------------------------无论选择过账与否,都重新生成一个临时科目余额表-----------------------------------------------------------
     CREATE TABLE  #tempAcBalance 
	(
		 STYPEID			VARCHAR(50),
		 ATYPEID			VARCHAR(50),
		 FBEGINBALANCE		 NUMERIC(24, 10) ,
		 FBEGINBALANCEFOR	 NUMERIC(24, 10) ,
		 FDEBIT				 NUMERIC(24, 10) ,
		 FDEBITFOR			 NUMERIC(24, 10) ,
		 FCREDIT			 NUMERIC(24, 10) ,
		 FCREDITFOR			 NUMERIC(24, 10) ,
		 CID				INT,
		 FENDBALANCE		 NUMERIC(24, 10) ,
		 FENDBALANCEFOR		 NUMERIC(24, 10) ,
		 FYTDDEBIT			 NUMERIC(24, 10) ,
		 FYTDDEBITFOR		 NUMERIC(24, 10) ,
		 FYTDCREDIT			 NUMERIC(24, 10) ,
		 FYTDCREDITFOR		 NUMERIC(24, 10) ,
		 FYEAR				VARCHAR(10),
		 FPERIOD			INT,
	)
	INSERT INTO #tempAcBalance
	EXEC WEB_AcBalanceQueryFromVoucher @IsPost,@FYear,@STypeId 
	--权限控制，删除不在权限范围类的数据
	DELETE FROM #tempAcBalance WHERE ATypeId NOT IN(SELECT Typeid FROM F_LineAccount(@chvOperatorID,@STypeId) )

   -----------------------------------------要分析的明细科目及科目要分析的方向--------------------------------------------------------------------
    ------------该非明细科目下要分析的子科目，存入#temp1
    CREATE TABLE #temp1
    (
	   STYPEID		VARCHAR(50),
	   FATHERID		VARCHAR(50),		---非明细科目
	   SONID		VARCHAR(50),		---要分析的子科目typeid
	   SONFDC		INT,				---要分析的子科目的方向
	   FULLNAME		VARCHAR(200),
	   USERCODE		VARCHAR(200),
	   FDC			INT					---要分析的子科目的分析方向	
    )
    INSERT INTO #temp1
	SELECT B.StypeId,
		   @ATypeId,
		   B.TypeId,
		   b.FDC,
		   FULLNAME,
		   USERCODE,
		   a.FDC				   ---科目的分析方向
	FROM AC_MULCOLUMNACCOUNT_ASSIST a
	JOIN dbo.Ac_Account b ON a.FVALUE=b.TYPEID  AND b.STYPEID=@STypeId --AND b.DELETED=0			
	INNER JOIN F_LineAccount(@chvOperatorID,@STypeId) F ON F.TypeID=B.TypeId AND F.Stypeid=B.STypeId
	WHERE a.ASSISTID=@AssistID 
	----------------------------------------------------表左边的统计信息---------------------------------------------------------------------------
	CREATE TABLE #totalTable
	(
		ID						INT IDENTITY(1,1),		--Modify 12-10-19，原来取的是AC_VOUCHER_BILL的ID，现在为了最后一步排序，重新生成	
		BILLNUMBERID			NUMERIC,
		TYPEID					VARCHAR(50),			--子科目id
		TYPEFDC                 INT,					--子科目的分析方向，行专列的时候用
		SONFDC					INT,					--子科目的方向，求余额时用
		FPERIOD 				INT,					--期间
		BORROW                   NUMERIC(24, 10) ,			--明细科目的借
		LEND                     NUMERIC(24, 10) ,			--明细科目的贷
		FDC						VARCHAR(5),				--余额方向，显示用
		BALANCE					 NUMERIC(24, 10) ,			--余额
		SUMMARY					VARCHAR(400)			--摘要
	)
	SET @SQL='INSERT INTO #totalTable(BILLNUMBERID,TYPEID,TYPEFDC,SONFDC,FPERIOD,FDC,SUMMARY,BORROW,LEND) 
			  SELECT  a.BILLNUMBERID,
				      b.SONID,
				      b.FDC,
				      b.SONFDC,
				      a.FPERIOD,
				      @Fdc,
				      a.SUMMARY,
					  a.FDEBITTOTAL AS BORROW,
					  a.FCREDITTOTAL AS LEND 
			   FROM AC_VOUCHER_BILL a
			   INNER JOIN F_LineAccount('''+@chvOperatorID+''','''+@STypeId+''') F ON F.TypeID=a.ATypeId AND F.Stypeid=a.STypeId
			   JOIN #temp1 b ON a.ATYPEID=b.SONID
			   JOIN AC_VOUCHER c ON a.BILLNUMBERID=c.BILLNUMBERID AND c.FYEAR=@FYear AND c.FPERIOD >=@FPeriodStart AND c.FPERIOD<=@FPeriodEnd AND FCHECKED <> -1 '
	IF @IsPost=0
		SET @SQL+='AND IFCHECK=''t'' '
	SET @SQL+='JOIN #MulColCid d ON a.CID=d.CID
			   WHERE a.STYPEID=@StypeID
			   ORDER BY a.FPERIOD,c.BILLDATE,a.BILLNUMBERID,a.ID'
	EXEC sp_executesql @SQL,N'@FYear VARCHAR(10),@FPeriodStart INT,@FPeriodEnd INT,@Fdc VARCHAR(10),@StypeID VARCHAR(50)',@FYear,@FPeriodStart,@FPeriodEnd,@Fdc,@StypeID
	--------------------根据查询条件剔除不符合的科目
	IF (@IsBalanceNull=1 OR @IsNull=1)
		BEGIN
			CREATE TABLE #temp2
			(
			    TYPEID			VARCHAR(50),	---分析的子科目
			    BALANCE			 NUMERIC(24, 10) 	---本期余额
			)
			INSERT INTO #temp2
			SELECT c.SONID,
				  SUM(ISNULL(FENDBALANCE,0)) AS BALANCE
		    FROM 
		    (
				SELECT a.STYPEID,
					   a.SONID,
					   a.CID,
					   ISNULL(MAX(FPERIOD),@FPeriodEnd) AS FPERIOD
				FROM
					(
					   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
					) a
				LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodEnd AND b.CID=a.CID
				GROUP BY a.STYPEID,a.SONID,a.CID
			) c 
			LEFT JOIN #tempAcBalance d ON d.STYPEID=c.STYPEID AND d.ATYPEID=c.SONID AND d.FPERIOD=c.FPERIOD AND d.CID=c.CID AND d.FYEAR=@FYear
			GROUP BY c.SONID
				
			CREATE TABLE #temp3
			(
			    TYPEID			VARCHAR(50),	---分析的子科目
			    PERIODCHANGE	 NUMERIC(24, 10) ,	---本期发生额
			    BALANCE			 NUMERIC(24, 10) 	---本期余额
			)	
			INSERT INTO #temp3	
			SELECT a.TYPEID,
				   ISNULL(b.PERIODCHANGE,0),
				   a.BALANCE
			FROM #temp2 a
			LEFT JOIN 
					(
					   SELECT TYPEID,
						      SUM(ABS(ISNULL(BORROW,0)))+SUM(ABS(ISNULL(LEND,0))) AS PERIODCHANGE
					   FROM #totalTable
					   GROUP BY TYPEID
					) b ON a.TYPEID=b.TYPEID
				
		    SELECT TYPEID
		    INTO #temp4
		    FROM #temp3 
		    WHERE	((@IsNull=1 AND PERIODCHANGE>0) OR @IsNull=0) AND
					((@IsBalanceNull=1 AND (BALANCE!=0 OR PERIODCHANGE>0)) OR @IsBalanceNull=0) 
			
			DELETE FROM #temp1  WHERE NOT EXISTS (SELECT 1 FROM #temp4 b WHERE #temp1.SONID=b.TYPEID)
		END
		
    ---科目与借贷交叉连接，以待后面行转列：还要判断分析方向，控制列的显示列数
    CREATE TABLE #Accounts
    (
        STYPEID		VARCHAR(50),		--机构id
        TYPEID		VARCHAR(50),		--科目id
        FULLNAME	VARCHAR(200),		--科目名称
        FDC			INT,				--科目分析方向
        COLNAME		VARCHAR(MAX)		--行转列的列名
    )
	---既有分析方向1又有方向-1的，也是分析借贷两个方向或者分析方向含有0
	SET @SQL='INSERT INTO #Accounts
			SELECT STYPEID,
				     SONID,
				     FULLNAME,
				     d.FDC,
				     SUBSTRING(COLNAME+USERCODE,0,128)   
		       FROM #temp1 c,'
	IF (SELECT COUNT(1) FROM ( SELECT FDC FROM #temp1 GROUP BY FDC) a)=2 OR (SELECT TOP 1 1 FROM #temp1 WHERE FDC=0)=1
		SET @SQL+='( SELECT ''borrow'' AS COLNAME,1 AS FDC 
					UNION ALL
					SELECT ''lend'' AS COLNAME,-1 AS FDC 
					) d'
    ELSE IF (SELECT TOP 1 1 FROM #temp1 WHERE FDC=1)=1								--只有分析方向为1的，只分析借方
		SET @SQL+='( SELECT ''borrow'' AS COLNAME,1 AS FDC) d'
	ELSE			
		SET @SQL+='( SELECT ''lend'' AS COLNAME,-1 AS FDC) d'																              
	EXEC(@SQL)
	
	-------------------------------------------------更新余额----------------------------------------------------------------------------------------- 
	-------------如果查询期间是第一期，期初的借和贷要到账务期初去查询
	CREATE TABLE #BeginBorrowLend
	(
	    STYPEID	   VARCHAR(50),
	    TYPEID	   VARCHAR(50),			--非明细科目id
	    FPERIOD	   INT,
	    BORROW	    NUMERIC(24, 10) ,
	    LEND	    NUMERIC(24, 10) 
	)
	IF @FPeriodStart=@FPeriod
		INSERT INTO #BeginBorrowLend
		SELECT a.STYPEID,
			   a.FATHERID,
			   @FPeriod,
			   SUM(ISNULL(FDEBIT,0))  AS BORROW,
			   SUM(ISNULL(FCREDIT,0)) AS LEND
		FROM 
			(
			  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			)a
		LEFT JOIN dbo.Ac_IniAccount b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND a.CID=b.CID AND b.FYEAR=@FYear AND b.FPERIOD=@FPeriod 
		GROUP BY a.STYPEID,a.FATHERID
	ELSE
		INSERT INTO #BeginBorrowLend
		SELECT c.STYPEID,
			   c.FATHERID,
			   @FPeriodStart,
			   SUM(ISNULL(FYTDDEBIT,0)),
			   SUM(ISNULL(FYTDCREDIT,0))
		FROM 
		(
		   SELECT a.STYPEID,
				  a.FATHERID,
				  a.SONID,
				  a.CID,
				  CASE
					WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart THEN @FPeriodStart-1
					ELSE ISNULL(MAX(FPERIOD),@FPeriodStart)
				  END AS FPERIOD
		   FROM 
		   (
			  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
		   ) a
		   LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodStart AND b.CID=a.CID
		   GROUP BY a.STYPEID,a.FATHERID,a.SONID,a.CID
		) c 
		LEFT JOIN #tempAcBalance d ON d.STYPEID=c.STYPEID AND d.ATYPEID=c.SONID AND d.FPERIOD=c.FPERIOD AND d.CID=c.CID
	    GROUP BY c.STYPEID,c.FATHERID
	------查询期初，数据保存到#BeginBalance
	CREATE TABLE #BeginBalance
	(
	     STYPEID VARCHAR(50),
	     TYPEID	 VARCHAR(50),
	     FPERIOD INT,
	     BORROW	  NUMERIC(24, 10) ,
	     LEND	  NUMERIC(24, 10) ,
	     BALANCE  NUMERIC(24, 10) 
	)	
	INSERT INTO #BeginBalance
	SELECT e.STYPEID,
		   e.TYPEID,
		   @FPeriodStart,
		   e.BORROW,
		   e.LEND,
		   d.BALANCE
	FROM		
	(
		SELECT  c.STYPEID,
				c.FATHERID,
				SUM(ISNULL(BALANCE,0)) AS BALANCE
		FROM 
		(
			SELECT a.STYPEID,
				   a.FATHERID,
				   a.SONFDC,
					CASE 
						WHEN @FdcId=a.SONFDC AND a.FPERIOD=@FPeriodStart THEN SUM(ISNULL(FBEGINBALANCE,0))
						WHEN @FdcId=-a.SONFDC AND a.FPERIOD=@FPeriodStart THEN -SUM(ISNULL(FBEGINBALANCE,0))
						WHEN @FdcId=a.SONFDC AND a.FPERIOD!=@FPeriodStart THEN SUM(ISNULL(FENDBALANCE,0))
						WHEN @FdcId=-a.SONFDC AND a.FPERIOD!=@FPeriodStart THEN -SUM(ISNULL(FENDBALANCE,0))
					END AS BALANCE
			FROM 
			(	
				SELECT f.STYPEID,
					   f.FATHERID,
					   f.SONID,
					   f.SONFDC,
					   f.CID,
					   CASE
							WHEN ISNULL(MAX(FPERIOD),@FPeriodStart)=@FPeriodStart AND MAX(FPERIOD)!=@FPeriod THEN @FPeriodStart-1
							ELSE ISNULL(MAX(FPERIOD),@FPeriodStart)
					   END AS FPERIOD 
				FROM 
					(
					   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
					) f
				LEFT JOIN #tempAcBalance g ON f.STYPEID=g.STYPEID AND f.SONID=g.ATYPEID AND g.FYEAR=@FYear AND g.FPERIOD<=@FPeriodStart AND g.CID=f.CID 
				GROUP BY f.STYPEID,f.FATHERID,f.SONID,f.SONFDC,f.CID
			) a
			LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=a.FPERIOD AND b.CID=a.CID
			GROUP BY a.STYPEID,a.FATHERID,a.SONFDC,a.FPERIOD
		) c GROUP BY c.STYPEID,c.FATHERID
	) d 
	JOIN #BeginBorrowLend e ON d.STYPEID=e.STYPEID AND d.FATHERID=e.TYPEID 

	SELECT @Balance=BALANCE FROM #BeginBalance
	-----------------------更新余额 
	UPDATE #totalTable SET @Balance+=CASE 
										WHEN @FdcId=SONFDC AND @Fdc='借' THEN (ISNULL(BALANCE,0)+ISNULL(BORROW,0)-ISNULL(LEND,0))
										WHEN @FdcId=SONFDC AND @Fdc='贷' THEN (ISNULL(BALANCE,0)-ISNULL(BORROW,0)+ISNULL(LEND,0))
										WHEN @FdcId!=SONFDC AND @Fdc='借' THEN  (ISNULL(BALANCE,0)-ISNULL(BORROW,0)+ISNULL(LEND,0))
										WHEN @FdcId!=SONFDC	AND @Fdc='贷' THEN  (ISNULL(BALANCE,0)+ISNULL(BORROW,0)-ISNULL(LEND,0))
									 END,
							BALANCE=@Balance,
							FDC=CASE 
									WHEN @Balance=0 THEN '平'
									ELSE @Fdc
								END						
	---------------------生成符合查询格式的临时表
	CREATE TABLE #MulCol
	(
	  ID			INT,					---凭证明细表中的的id
	  FPERIOD		INT,
	  TYPEID		VARCHAR(50),			---子科目的TYPEID
	  TYPEFDC	    INT,					---子科目的分析方向
	  BILLDATE		VARCHAR(10),
	  FSERIALNAME	VARCHAR(200),
	  SUMMARY		VARCHAR(400),
	  FDC			VARCHAR(10),
	  BORROW		 NUMERIC(24, 10) ,
	  LEND			 NUMERIC(24, 10) ,
	  BALANCE        NUMERIC(24, 10),
	  ETypeId		VARCHAR(50)	NOT NULL DEFAULT('')--制单人
	)
	INSERT INTO #MulCol
	SELECT a.ID,
		   a.FPERIOD,
		   a.TYPEID,
		   a.TYPEFDC,
		   CONVERT(VARCHAR(10),c.BILLDATE,120),
		   CASE WHEN @LimitOwnVoucher=1 AND c.ETypeId<>@chvOperatorID THEN '****' ELSE d.FullName+'-'+CONVERT(VARCHAR(10),c.FlowNo) END ,
		   CASE WHEN @LimitOwnVoucher=1 AND c.ETypeId<>@chvOperatorID THEN '****' ELSE dbo.F_GetSummaryByLimit(a.ID,@chvOperatorID,c.STypeID,a.Summary) END Summary,
		   a.FDC,
		   a.BORROW,
		   a.LEND,
		   a.BALANCE,
		   c.ETypeId
	FROM #totalTable a
	JOIN dbo.Ac_Voucher c   ON a.BILLNUMBERID=c.BILLNUMBERID AND FYear=@fyear
	JOIN AC_VOUCHER_GROUP d ON c.VGID = d.VGID
	-----------------------------------------------处理右表---------------------------------------------------------------------------------------------
	---获取待行转列的列对应的值
	CREATE TABLE #GetValue
	(
		ID			   INT,					--对应凭证明细表中的id
		FPERIOD        INT,					--期间
		TYPEID		   VARCHAR(50),			--要分析科目的id
		COLNAME		   VARCHAR(MAX),		--要转列的列名
		FVALUE          NUMERIC(24, 10) 		--列对应的值
	)
	INSERT INTO #GetValue (ID,FPERIOD,TYPEID,COLNAME,FVALUE)
	SELECT b.ID,
		   b.FPERIOD,
		   a.TYPEID,
		   a.COLNAME,
		CASE 
			WHEN a.FDC=1  AND a.TYPEID=b.TYPEID AND (b.TYPEFDC=0 OR b.TYPEFDC=1) THEN b.BORROW
			WHEN a.FDC=-1 AND a.TYPEID=b.TYPEID AND (b.TYPEFDC=0 OR b.TYPEFDC=-1) THEN b.LEND 
		END 
	FROM #Accounts a,#MulCol b
	-----------------------------------------------获取左表的期初，本期合计，本年累计-----------------------------------------------------------
	-----期初插入#MulCol
	INSERT INTO #MulCol
	SELECT -1,
		   FPERIOD,
		   '1'   AS TYPEID,
		   0   AS TYPEFDC,
		   ''  AS BILLDATE,
		   ''  AS FSERIALNAME,
		   '期初余额',
		   CASE 
			 WHEN BALANCE=0 THEN '平'
			 ELSE @Fdc
		   END,
		   BORROW,
		   LEND,
		   BALANCE,
		   '' ETypeId
	FROM #BeginBalance 			
	----本期合计，本年累计
	WHILE @tempPeriodS<=@tempPeriodE
		BEGIN
			INSERT INTO #MulCol
			SELECT 999998,
				   @tempPeriodS,
				   '999998',
				   0,
				   CONVERT(VARCHAR(10),@FYear)+'-'+CONVERT(VARCHAR(10),@tempPeriodS),
				   '',
				   '本期合计',
				   CASE
						WHEN ISNULL(BALANCE,0)=0 THEN '平'
						ELSE @Fdc
				   END,
				   BORROW,
				   LEND,
				   ISNULL(BALANCE,0),
				   '' ETypeId
			FROM 
			(
			   SELECT  FATHERID,
					   SUM(ISNULL(FDEBIT,0))      AS BORROW,
					   SUM(ISNULL(FCREDIT,0))     AS LEND
					FROM 
						(
						  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
						) a
					LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@tempPeriodS AND b.CID=a.CID
					GROUP BY a.FATHERID
			) e
			JOIN 
			(
				SELECT FATHERID,
					   SUM(ISNULL(FENDBALANCE,0)) AS BALANCE
				FROM 
				(
					SELECT f.FATHERID,
						   f.SONFDC,
						   CASE 
								WHEN @FdcId=f.SONFDC THEN SUM(ISNULL(FENDBALANCE,0))
								ELSE -SUM(ISNULL(FENDBALANCE,0))
						   END AS FENDBALANCE
					FROM 
					(
					    SELECT a.STYPEID,
					           a.FATHERID,
							   a.SONID,
							   a.SONFDC,
							   a.CID,
							   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD
						FROM 
							(
							   SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
							) a
						LEFT JOIN #tempAcBalance b ON b.STYPEID=a.STYPEID AND b.ATYPEID=a.SONID AND b.FYEAR=@FYear AND b.CID=a.CID AND b.FPeriod<=@tempPeriodS
						GROUP BY a.STYPEID,a.FATHERID,a.SONID,a.SONFDC,a.CID
					) f
					LEFT JOIN  #tempAcBalance c ON f.STYPEID=c.STYPEID AND f.SONID=c.ATYPEID AND f.FPERIOD=c.FPERIOD AND c.CID=f.CID AND c.FYEAR=@FYear
					GROUP BY f.FATHERID,f.SONFDC 
				) h GROUP BY h.FATHERID 
			)  i ON e.FATHERID=i.FATHERID
			
			INSERT INTO #MulCol
			SELECT  999999,
					@tempPeriodS,
					'999999',
					0,
					CONVERT(VARCHAR(10),@FYear)+'-'+CONVERT(VARCHAR(10),@tempPeriodS),
					'',
					'本年累计',
					CASE 
						WHEN ISNULL(BALANCE,0)=0 THEN '平'
						ELSE @Fdc
					END,
					BORROW,
					LEND,
					ISNULL(BALANCE,0),
					'' ETypeId
			FROM
			(
				SELECT FATHERID,
					   SUM(ISNULL(FYTDDEBIT,0))   AS BORROW,
					   SUM(ISNULL(FYTDCREDIT,0))  AS LEND,
					   SUM(ISNULL(FENDBALANCE,0)) AS BALANCE
				FROM 
				(
					SELECT f.FATHERID,
						   f.SONFDC,
						   SUM(ISNULL(FYTDDEBIT,0))  AS FYTDDEBIT,
						   SUM(ISNULL(FYTDCREDIT,0)) AS FYTDCREDIT,
						   CASE 
								WHEN @FdcId=f.SONFDC THEN SUM(ISNULL(FENDBALANCE,0))
								ELSE -SUM(ISNULL(FENDBALANCE,0))
						   END AS FENDBALANCE
					FROM 
					(
					    SELECT a.STYPEID,
					           a.FATHERID,
							   a.SONID,
							   a.SONFDC,
							   a.CID,
							   ISNULL(MAX(FPERIOD),@tempPeriodS) AS FPERIOD
						FROM 
						(
							SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
						) a
						LEFT JOIN #tempAcBalance b ON b.STYPEID=a.STYPEID AND b.ATYPEID=a.SONID AND b.FYEAR=@FYear AND b.CID=a.CID AND b.FPeriod<=@tempPeriodS
						GROUP BY a.STYPEID,a.FATHERID,a.SONID,a.SONFDC,a.CID
					) f
					LEFT JOIN  #tempAcBalance c ON f.STYPEID=c.STYPEID AND f.SONID=c.ATYPEID AND f.FPERIOD=c.FPERIOD AND c.CID=f.CID AND c.FYEAR=@FYear
					GROUP BY f.FATHERID,f.SONFDC 
				) h GROUP BY h.FATHERID 
			) i
			 
			SET @tempPeriodS+=1
		END
	--------------------------------获取右表的期初,本期合计，本年合计---------------------------------------------------------------------------------
	----期初
	CREATE TABLE #AccountBegin
	(
	   TYPEID    VARCHAR(50),		--要分析的子科目id
	   FPERIOD	 INT,
	   BORROW	  NUMERIC(24, 10) ,
	   LEND		  NUMERIC(24, 10) 
	)
	IF @FPeriodStart=@FPeriod
		INSERT INTO #AccountBegin
		SELECT a.SONID,
			   @FPeriodStart,
			   SUM(ISNULL(FDEBIT,0)),
			   SUM(ISNULL(FCREDIT,0))
		FROM 
			(
			  SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			) a
		LEFT JOIN Ac_IniAccount b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD=@FPeriod AND a.CID=b.CID
		GROUP BY a.SONID
	ELSE 
		INSERT INTO #AccountBegin
		SELECT c.SONID,
			   @FPeriodStart,
			   SUM(ISNULL(FYTDDEBIT,0)),
			   SUM(ISNULL(FYTDCREDIT,0))
		FROM 
		(
			SELECT a.STYPEID,
				  a.SONID,
				  a.CID,
				  CASE
					WHEN MAX(FPERIOD)=@FPeriodStart THEN @FPeriodStart-1
					ELSE MAX(FPERIOD)
				  END AS FPERIOD
		   FROM 
		   (
				SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
		   ) a
		   LEFT JOIN #tempAcBalance b ON a.STYPEID=b.STYPEID AND a.SONID=b.ATYPEID AND b.FYEAR=@FYear AND b.FPERIOD<=@FPeriodStart AND b.CID=a.CID
		   GROUP BY a.STYPEID,a.SONID,a.CID
		) c
		LEFT JOIN #tempAcBalance d ON d.STYPEID=c.STYPEID AND d.ATYPEID=c.SONID AND d.FPERIOD=c.FPERIOD AND d.CID=c.CID AND d.FYEAR=@FYear
		GROUP BY c.SONID
		
	INSERT INTO #GetValue
	SELECT -1,
		   @FPeriodStart,
		   1,
		   a.COLNAME,
		   CASE
			WHEN a.TYPEID=b.TYPEID AND a.FDC=1 THEN b.BORROW
			ELSE b.LEND
		   END
	FROM #Accounts a
	LEFT JOIN #AccountBegin b ON a.TYPEID=b.TYPEID
	
	WHILE @FPeriodStart <= @FPeriodEnd
		BEGIN
			---本期合计
		    INSERT INTO #GetValue
		    SELECT 999998,
				   @FPeriodStart,
				   '999998',
				   a.COLNAME,
				   CASE
						WHEN a.TYPEID=d.SONID AND a.FDC=1 THEN BORROW
						ELSE LEND
				   END
			FROM #Accounts a
			LEFT JOIN 
			(
			    SELECT b.SONID,
					  SUM(ISNULL(FDEBIT,0)) AS BORROW,
					  SUM(ISNULL(FCREDIT,0)) AS LEND
			    FROM 
			    (
					SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			    ) b 
			    LEFT JOIN #tempAcBalance c ON b.STYPEID=c.STYPEID AND b.SONID=c.ATYPEID AND c.FYEAR=@FYear AND c.FPERIOD=@FPeriodStart AND c.CID=b.CID
			    GROUP BY b.SONID
			) d ON a.TYPEID=d.SONID
				   
		   ---本年累计
		   INSERT INTO #GetValue
		   SELECT 999999,
				  @FPeriodStart,
				  '999999',
				  a.COLNAME,
				  CASE
						WHEN a.TYPEID=f.SONID AND a.FDC=1 THEN BORROW
						ELSE LEND
				  END
			FROM #Accounts a
			LEFT JOIN 
			(
			   SELECT  d.SONID,
					   SUM(ISNULL(FYTDDEBIT,0)) AS BORROW,
					   SUM(ISNULL(FYTDCREDIT,0)) AS LEND
			   FROM 
			   (
			        SELECT  b.STYPEID,
							b.SONID,
							b.CID,
						    ISNULL(MAX(FPERIOD),@FPeriodStart) AS FPERIOD
			        FROM 
			        (
						SELECT * FROM  #temp1,(SELECT CID FROM #MulColCid) x
			        ) b
			        LEFT JOIN #tempAcBalance c ON b.STYPEID=c.STYPEID AND b.SONID=c.ATYPEID AND c.FYEAR=@FYear AND c.FPERIOD<=@FPeriodStart AND c.CID=b.CID 
			        GROUP BY b.STYPEID,b.SONID,b.CID
			   ) d
			   LEFT JOIN #tempAcBalance e ON d.STYPEID=e.STYPEID AND d.SONID=e.ATYPEID AND e.FYEAR=@FYear AND d.FPERIOD=e.FPERIOD AND e.CID=d.CID
			   GROUP BY d.SONID
			) f ON a.TYPEID=f.SONID
			
			SET @FPeriodStart+=1
		END
	
	----------------#GetValue行专列，与#MulCol关联---------------------------------------------------------------------------------------------------------
	DECLARE @TurnCol VARCHAR(MAX)
	SELECT @TurnCol=(ISNULL(@TurnCol+'],[','') +  colname) 
	FROM #GetValue GROUP BY colname 
	SET @TurnCol='['+@TurnCol+']'
    
    ALTER TABLE #GetValue DROP COLUMN TYPEID
    
    ------#temp1为空，即没有符合条件的科目，因为返回null，为了程序不报错，直接返回#MulCol
	IF EXISTS (SELECT TOP 1 1 FROM #temp1)
		BEGIN
			SET @SQL='SELECT * 
			FROM #MulCol a
			JOIN
				(
					 SELECT *  FROM  #GetValue  PIVOT (MAX(FVALUE) FOR COLNAME IN ('+@TurnCol+')) b
				) c	ON a.ID=c.ID AND a.FPERIOD=c.FPERIOD
			ORDER BY a.FPERIOD,a.ID'
			EXEC(@SQL)
			
			----获取动态列
			SELECT FULLNAME,
				   USERCODE
			FROM #temp1
			ORDER BY USERCODE
		END
	ELSE
		BEGIN
			SELECT * FROM #MulCol
			-----获取动态列
			SELECT FULLNAME,
				   USERCODE
			FROM #temp1
			ORDER BY USERCODE
		END
	IF @IsBalanceNull=1 OR @IsNull=1
		DROP TABLE #temp2,#temp3,#temp4
		
	DROP TABLE #tempAcBalance,#temp1,#Accounts,#totalTable,#BeginBorrowLend,#BeginBalance,#AccountBegin,#MulCol,#GetValue,#MulColCid
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MultAtypeSelect]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_MultAtypeSelect
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/************************************************************
 * 修 改 人：罗淮文
 * 修改时间: 2014/4/18 9:39:44
 * 内容描述：增加对@pretype参数的条件查询，
 *			 如果@pretype=5，则只查询现金，银行
 ************************************************************/

-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-05-27
-- Description: 多账户选择
-- =============================================
CREATE PROCEDURE Web_MultAtypeSelect
(
	@chvPOS				varchar(50)	= '',	-- 从数据表取数据的条件(过滤条件)
	@chvMode			varchar(50)	= '',	-- 查询的是名称( FullName ) 还是 编号( UserCode )，还是二者皆查 ( FullNameOrUserCode )	
	@OperatorID			varchar(50),		-- 操作员 ID（作权限范围检查用）	
	@pretype			INT=0,				--0 不选预收 也不选预付 不选会员  1 预收+会员  2 预付+会员  3 预收 不加会员 4 预付 不加会员
	@ifAtypeAll			int=0,				--是否不控制权限
	@Stypeid			VARCHAR(50),
	@cid				varchar(max),
	@btypeid			varchar(max),
	@billnumberid VARCHAR(50),
	@billtype VARCHAR(50)
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL VARCHAR(MAX) = ''
DECLARE @SQLWHERE VARCHAR(8000) = ''
DECLARE @SQLATYPE VARCHAR(2000) = ''

IF @btypeid IS NULL
	SET @btypeid = ''

SET @SQL=' SELECT	a.nid as nid,
					a.ntypeid,
					a.Usercode,
					a.Fullname as afullname,
					'''' AS tradeno,
					null as ntotalmoney,				
					' + @billtype + ' as billtype,
					0 as paytype,
					case when a.nId=27 or a.nId=39 then	(select top 1 FullName from Ac_Currency where CId='+@cid+') else '''' end as cidfullname,
					case when a.nId=27  then 
					(
					select  YFTotal
					*(select  case when BasisType=1 then rate else 1
					/rate end as rate from Ac_Currency where CId='+@cid+')
					from BType_ArApTotal ba
					where STypeID='''+@Stypeid+''' and BTypeID='''+@btypeid+''' and cid='+@cid+'
					)
					when a.nId=39  then 
					(
					select  YSTotal
					*(select top 1 case when BasisType=1 then rate else 1
					/rate end as rate from Ac_Currency where CId='+@cid+')
					from BType_ArApTotal ba
					where STypeID='''+@Stypeid+''' and BTypeID='''+@btypeid+''' and cid='+@cid+'
					)
					else null end as balance,
					case when a.nid =34 then 0 else -1 end as yhtype
			FROM	Ac_Items a			
			WHERE	A.SonNum = 0 
					AND A.Deleted=0
					AND A.usercode <> ''2191'' '			     


IF @ifAtypeAll=1
	SET @SQLATYPE=' (a.nTypeID LIKE ''0000100003%'' or a.IsBank=1 or a.nid in (27,39)) '
ELSE
	SET @SQLATYPE=' a.ntypeid IN (SELECT nTypeID FROM F_LineA(''' + @OperatorID + '''))'
--F_LineA 现金类和银行
IF @pretype=1
	SET @SQLWHERE=' AND (a.nid in (34,39) OR '+@SQLATYPE+') '
IF @PRETYPE=2
	SET @SQLWHERE=' AND (a.nid in (34,27) OR '+@SQLATYPE+') '
IF @PRETYPE=3
	SET @SQLWHERE=' AND ('+@SQLATYPE+') AND a.nid<> 27 '
IF @PRETYPE=4
	SET @SQLWHERE=' AND ('+@SQLATYPE+') AND a.nid<>39 '
IF @pretype = 5
	    SET @SQLWHERE = ' AND ' + @SQLATYPE + ' AND a.nid NOT IN (27,39) '
IF @ifAtypeAll<>1 AND (@billnumberid='-1')
	SET @SQLWHERE = @SQLWHERE + ' AND a.deleted=0 '
	
IF @billtype = '93'
	SET @SQLWHERE = @SQLWHERE + ' AND a.usercode NOT IN (''1151'')'	
	
IF @chvPOS <> ''
BEGIN
	IF @chvMode = 'fullname'
		SET @SQLWHERE = @SQLWHERE + '
		AND a.FullName LIKE ''%' + @chvPOS + '%'''
	ELSE IF @chvMode = 'usercode'
		SET @SQLWHERE = @SQLWHERE + '
		AND a.UserCode LIKE ''%' + @chvPOS + '%'''
	ELSE IF @chvMode = 'FullNameOrUserCode'
		SET @SQLWHERE = @SQLWHERE + '
		AND (a.FullName LIKE ''%' + @chvPOS + '%'' OR a.UserCode LIKE ''%' + @chvPOS + '%'' OR a.PyCode LIKE ''%' + @chvPOS + '%'')'
END

SET @SQL=@SQL+@SQLWHERE

SET @sql= @SQL + 'UNION all
            SELECT	a.nId,a.ntypeid,a.usercode,a.Fullname as afullname,
					CASE b.PayType WHEN 2 THEN ''微信'' 
					               WHEN 3 THEN ''易支付银行''
					               ELSE ''支付宝'' END + ''-'' + TradeNo AS TradeNo,NTotalMoney,BillType,PayType,
					case when a.nId=27 or a.nId=39 then	(select top 1 FullName from Ac_Currency where CId=1) else '''' end as cidfullname,
					case when a.nId=27  then 
					(
					select  YFTotal
					*(select  case when BasisType=1 then rate else 1
					/rate end as rate from Ac_Currency where CId=1)
					from BType_ArApTotal ba
					where STypeID='''+@Stypeid+''' and BTypeID='''+@btypeid+''' and cid='+@cid+'
					)
					when a.nId=39  then 
					(
					select  YSTotal
					*(select top 1 case when BasisType=1 then rate else 1
					/rate end as rate from Ac_Currency where CId=1)
					from BType_ArApTotal ba
					where STypeID='''+@Stypeid+''' and BTypeID='''+@btypeid+''' and cid='+@cid+'
					)
					else null end as balance,
					b.yhtype
			 FROM	dbo.BillMulAccount b
			 LEFT JOIN Ac_Items a ON b.ATypeID =  a.nId
			 WHERE	b.BillType = ' + @billtype + ' 
					AND b.BillNumberId = ' + @billnumberid + ' 
					AND (b.PayType = 2 OR b.PayType = 1 or b.PayType=3) '

IF @billtype = '93'
	SET @SQL = @SQL + ' AND a.usercode NOT IN (''1151'')'
	
--PRINT(@SQL)
EXEC(@SQL)

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MultFixedBarcodePrintSelectFixed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_MultFixedBarcodePrintSelectFixed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：李灏龙	
	日期：2014年4月17日 15:43:14
	描述：固定资产多条码打印选择器
*/

CREATE PROCEDURE Web_MultFixedBarcodePrintSelectFixed
(
	@OperatorId		VARCHAR(100),	--操作员ID
	@usercode		VARCHAR(200)='',--编码
	@Fullname		VARCHAR(200)='',--名称
	@stypeid		VARCHAR(MAX),	--分支机构ID
	@dtypeid		VARCHAR(MAX),	--部门ID
	@flag			int				--是否过滤条码为空的固定资产，0不过滤，1过滤
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

CREATE TABLE #STYPE (Typeid VARCHAR(50))
CREATE TABLE #DTYPE (Typeid VARCHAR(50))
INSERT INTO #STYPE (Typeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
INSERT INTO #DTYPE (Typeid) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)
--构造SQL语句
DECLARE @SQL VARCHAR(MAX)
SET @SQL='
SELECT	 a.STypeId
		,a.Id AS typeid 
		,a.usercode
		,a.fullname
		,a.BarCode
		,a.DTypeid
		,a.Size    --规格型号
		,a.LocationId  --存放地点id
		,a.ConditionId  --使用状况id
		,a.Units  --计量单位
		,a.Comment --备注
		,s.FullName AS sfullname
		,d.FullName AS dfullname
		,aasl.Location  --存放地点
		,aawc.Comment AS condition  --使用状况		
		,a.BarCode AS printbarcode
FROM Ac_AssetsCards  a
INNER JOIN #STYPE ss ON ss.Typeid = a.STypeId
INNER JOIN #DTYPE dd ON dd.Typeid = a.DTypeid
LEFT JOIN stype s ON s.TypeId = a.STypeId
LEFT JOIN Department d ON d.typeid = a.DTypeid
LEFT JOIN Ac_AssetStorageLocation aasl ON aasl.Id = a.LocationId
LEFT JOIN Ac_AssetWorkingCondition aawc ON aawc.Id = a.ConditionId
WHERE a.FullName LIKE ''%'+@FullName+'%'' 
	AND a.UserCode LIKE ''%'+ @UserCode+'%'' '
IF @flag=1
BEGIN
	SET @SQL=@SQL+' AND  a.BarCode is not Null AND a.BarCode<> '''''
END
SET @SQL=@SQL+' ORDER BY a.USERCODE'
						

--print(@sql)
EXEC(@SQL)

DROP TABLE #DTYPE,#STYPE

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MultiFactStocksDis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_MultiFactStocksDis]
GO



/*
	作者：谢吉康
	日期：2016-08-11
	描述：实物库存多仓库数据分布
*/


CREATE     PROCEDURE Web_MultiFactStocksDis
(
	@OperatorID 	VARCHAR(100) ,		--操作员ID
	@ntype 			INT=1,				--库存分布类别1:期初2:其他
	@parid 			VARCHAR(50),		--商品的父节点
	@EndDatePoint 	VARCHAR(10)='',		--时间点
	@KTypeID		VARCHAR(8000),		--多个仓库
	@STypeID		VARCHAR(MAX),	--分支机构
	@isshowstop     INT,
	@showstockstop  INT =0, --是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid VARCHAR(max)=''
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))

IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN (SELECT Typeid FROM F_GetManDetailSType(@OperatorId)) s
	ON A.TypeId=s.Typeid
	
 	--权限范围内的商品线性表
	CREATE TABLE #ptype(TypeId	varchar(100))
	INSERT INTO #ptype(TypeId) SELECT a.TypeId FROM dbo.F_LinePC(@OperatorID,@ptypeCategoryid) a 

--仓库
IF @KTypeID = ''
	SET @KTypeID ='00000'

CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @KTypeID='00000'
BEGIN
IF @showstockstop=0
	INSERT INTO #GetManKTypeId SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN #GetSelectSTypeId s ON k.STypeId=s.TypeId
	ELSE
	INSERT INTO #GetManKTypeId SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN #GetSelectSTypeId s ON k.STypeId=s.TypeId INNER JOIN   dbo.Stock c ON k.TypeId=c.typeId WHERE c.deleted=0
	
	END
ELSE
BEGIN
 IF @showstockstop=0
	INSERT INTO #GetManKTypeId SELECT k.TypeId 
	FROM F_GetManDetailKTypeSType(@OperatorID) k 
	INNER JOIN #GetSelectSTypeId s ON k.STypeId=s.TypeId
	INNER JOIN (SELECT A FROM f_split(@KTypeID,',')) K1 ON K.TypeId LIKE K1.a + '%'
 ELSE
  	INSERT INTO #GetManKTypeId SELECT k.TypeId 
	FROM F_GetManDetailKTypeSType(@OperatorID) k 
	INNER JOIN #GetSelectSTypeId s ON k.STypeId=s.TypeId
	INNER JOIN (SELECT A FROM f_split(@KTypeID,',')) K1 ON K.TypeId LIKE K1.a + '%'
	INNER JOIN dbo.Stock c ON k.TypeId= c.typeId WHERE c.deleted=0
END	

DECLARE @SQL VARCHAR(MAX)

--===================================================================================查历史库存分布
IF @ntype=2 
	BEGIN
		SELECT @SQL = '
				SELECT 
					S.Fullname AS SFullName, 
					P.FullName AS PFullName, 
					C.PTypeid, C.Ktypeid,
					C.Qty
				FROM (
						SELECT 
							t.PtypeId, 
							t.KtypeId, 
							SUM(t.Qty) AS Qty
				        FROM (								
								SELECT 	ptypeid,
										ktypeid,
										SUM(qty) AS qty
								FROM 	IniFactStocks
								Inner join #GetManKTypeId k1 on (k1.typeid=ktypeid)
								WHERE 	PTypeID LIKE '+CHAR(39)+@parID+'%'+CHAR(39)+'
								GROUP BY
										PTypeID,
										KTypeID
		         				UNION ALL
		 						SELECT 	InOut.ptypeid,
										InOut.ktypeid,
										SUM(ISNULL(CASE 
													WHEN InOut.billtype = 418 THEN InOut.qty 
													ELSE -1*InOut.qty 
													END,0)) AS qty
								FROM 	FactDepotInOut InOut
								INNER JOIN FactIndex Bil ON InOut.BillNumberId = Bil.BillNumberId
								Inner join #GetManKTypeId k1 on (k1.typeid=InOut.ktypeid) 
								WHERE 	InOut.KTypeID<>''10000''  
										and bil.ifcheck=''t'' 
										and bil.redword=0 
										AND Bil.billdate <='+CHAR(39)+@EndDatePoint+CHAR(39)+'
										AND InOut.PTypeID LIKE '+CHAR(39)+@parID+'%'+CHAR(39)+'
								GROUP BY 	InOut.ptypeid,
											InOut.ktypeid
								UNION ALL
		 						SELECT 	InOut.ptypeid,
										InOut.ktypeid2,
										SUM(InOut.qty) AS qty
								FROM 	FactDepotAllot InOut
								INNER JOIN FactIndex Bil ON InOut.BillNumberId = Bil.BillNumberId
								Inner join #GetManKTypeId k1 on (k1.typeid=InOut.ktypeid2) 
								WHERE 	InOut.ktypeid2<>''10000''  
										and bil.ifcheck=''t'' 
										and bil.redword=0 
										AND Bil.billdate <='+CHAR(39)+@EndDatePoint+CHAR(39)+'
										AND InOut.PTypeID LIKE '+CHAR(39)+@parID+'%'+CHAR(39)+'
								GROUP BY 	InOut.ptypeid,
											InOut.ktypeid2
								UNION ALL
		 						SELECT 	InOut.ptypeid,
										InOut.ktypeid,
										SUM(-InOut.qty) AS qty
								FROM 	FactDepotAllot InOut
								INNER JOIN FactIndex Bil ON InOut.BillNumberId = Bil.BillNumberId
								Inner join #GetManKTypeId k1 on (k1.typeid=InOut.ktypeid) 
								WHERE 	InOut.KTypeID<>''10000''  
										and bil.ifcheck=''t'' 
										and bil.redword=0 
										AND Bil.billdate <='+CHAR(39)+@EndDatePoint+CHAR(39)+'
										AND InOut.PTypeID LIKE '+CHAR(39)+@parID+'%'+CHAR(39)+'
								GROUP BY 	InOut.ptypeid,
											InOut.ktypeid
							) t 
							Inner Join F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') p1 on (p1.typeid=t.Ptypeid)
							inner join #ptype pc on p1.typeid=pc.typeid
						WHERE 	t.PtypeId like '+CHAR(39)+@parid+'%'+CHAR(39)+''
						IF @isshowstop=1
						  SELECT @SQL +=' and  p1.deleted=0' 
						 SELECT @SQL +=' GROUP BY t.PtypeId, t.KtypeId
					) C INNER JOIN		dbo.PType P ON (C.PTypeid = P.Typeid ) 
						INNER JOIN		dbo.Stock S ON (C.KTypeid = S.typeid)'
		--PRINT(@SQL)
		EXEC(@SQL)
	END
--============================================================================================当前库存状况表
IF @ntype=3
	BEGIN
		SELECT @SQL = '
				SELECT 
					S.Fullname AS SFullName, 
					P.FullName AS PFullName, 
					C.PTypeid, 
					C.Ktypeid, 
					C.Qty
			     FROM 
			     (
					SELECT	q.PtypeId AS PTypeid, 
							q.KtypeId, 
							SUM(q.Qty) AS Qty
			        FROM 	(SELECT PtypeId,KtypeId FROM dbo.FactStocks GROUP BY PtypeId,KtypeId) g
					INNER JOIN dbo.FactStocks_Qty Q ON  g.KtypeId=q.KTypeID AND g.PtypeId=q.PTypeID			        
			         Inner Join F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') p1 on (p1.typeid=g.Ptypeid)
			         inner join #ptype pc on p1.typeid=pc.typeid
					Inner Join #GetManKTypeId on (#GetManKTypeId.typeid=g.ktypeid) ' + CHAR(10)+'	
             		WHERE g.Ptypeid like ''' + @parid+ '%'' ' + CHAR(10)+''
             		
             			IF @isshowstop=1
						  SELECT @SQL +=' and  p1.deleted=0' 
						 SELECT @SQL +=' GROUP BY q.PtypeId, q.KtypeId
				) C INNER JOIN	dbo.PType P ON (C.PTypeid = P.Typeid ) 
					INNER JOIN	dbo.Stock S ON (C.KTypeid = S.typeid) '
		--PRINT(@SQL)
		EXEC(@SQL)		
	END

DROP TABLE #GetManKTypeId,#GetSelectSTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_MultPrintSelectPtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_MultPrintSelectPtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：毛欣蓉	
	日期：2011-03-24
	描述：多条码打印选商品并带出价格
*/

CREATE PROCEDURE Web_MultPrintSelectPtype
(
	@OperatorId		VARCHAR(100),	--操作员ID
	@usercode		VARCHAR(200)='',--编码
	@Fullname		VARCHAR(200)='',--名称
	@barcode		VARCHAR(200)='',--条码
	@STypeId		VARCHAR(MAX),	--仓库ID
	@flag			int				--是否过滤条码为空的商品
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

/*判断有没有启用分支机构价格*/
DECLARE @Type int
set @Type=(select top 1 pricetype from stype where typeid=@stypeid)

	
--构造SQL语句
DECLARE @SQL VARCHAR(MAX)
IF @Type=1
	BEGIN
		SET @SQL='
			select
				distinct
				a.EntryCode,
				A.usercode,
				A.fullname,
				a.name,
				a.area,
				a.Standard,
				a.TypeID,
				a.ifuseentrycode,
				a.BuyUnitId,
				a.SaleUnitId,
				a.StockUnitId,
				a.baseUnitId,
				CAST(a.IfUseEntryCode AS int) as ifusecode,
				b.prebuyprice1,
				b.prebuyprice2,
				b.prebuyprice3,
				b.prebuyprice4,
				b.prebuyprice5,
				b.topbuyprice,
				b.PreSalePrice1,
				b.PreSalePrice2,
				b.PreSalePrice3,
				b.PreSalePrice4,
				b.PreSalePrice5,
				b.PreSalePrice6,
				b.PreSalePrice7,
				b.PreSalePrice8,
				b.PreSalePrice9,
				b.PreSalePrice10, 
				b.RetailPrice,
				b.TopSalePrice,
				b.LowSalePrice,
				u1.fullname as buyunitfullname,
				u1.usercode as buyunitusercode,
				u2.fullname as saleunitfullname,
				u2.usercode as saleunitusercode,
				u3.fullname as baseunitfullname,
				u3.usercode as baseunitusercode,
				u4.fullname as stockunitfullname,
				u4.usercode as stockunitusercode
			FROM  F_GetManPTypeAll('''+@OperatorId+''') a
		LEFT JOIN PType_STypePrice  b on  (a.TypeID=b.PTypeID AND b.STypeID='''+@STypeId+''' AND b.UnitID = a.baseUnitId)
			LEFT join PType_Units u1 on u1.unitsid=a.buyunitid
			LEFT join PType_Units u2 on u2.unitsid=a.saleunitid
			LEFT join PType_Units u3 on u3.unitsid=a.baseunitid
			LEFT join PType_Units u4 on u4.unitsid=a.stockunitid
			WHERE	
				a.sonnum=0'+CHAR(13)
	END
ELSE
	BEGIN
		SET @SQL='
			SELECT	a.* ,
			        CAST(a.IfUseEntryCode AS int) as ifusecode,
					u1.fullname as buyunitfullname,
					u1.usercode as buyunitusercode,
					u2.fullname as saleunitfullname,
					u2.usercode as saleunitusercode,
					u3.fullname as baseunitfullname,
					u3.usercode as baseunitusercode,
					u4.fullname as stockunitfullname,
					u4.usercode as stockunitusercode
			FROM F_GetManPTypeAll('''+@OperatorId+''')  a
			LEFT join PType_Units u1 on u1.unitsid=a.buyunitid
			LEFT join PType_Units u2 on u2.unitsid=a.saleunitid
			LEFT join PType_Units u3 on u3.unitsid=a.baseunitid
			LEFT join PType_Units u4 on u4.unitsid=a.stockunitid
			WHERE 
				a.sonnum= 0'
	END	
	
--商品编号
IF(ISNULL(@UserCode,'')<>'')
	SET @SQL+='	AND A.UserCode LIKE ''%'+@UserCode+'%'' '+CHAR(13)
--商品名称
IF(ISNULL(@Fullname,'')<>'')
	SET @SQL+='	AND A.FullName LIKE ''%'+@FullName+'%'' '+CHAR(13)
--商品多编码
IF(ISNULL(@barcode,'')<>'')
	SET @SQL+='	AND A.multentrycode LIKE ''%'+ @barcode+'%'''+CHAR(13)
--条码不为空	
IF @flag=1
	BEGIN
		SET @SQL+='	AND A.multentrycode<>'''''
	END
	
SET @SQL+='  ORDER BY A.UserCode '						
PRINT @sql
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_NewAcperiod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_NewAcperiod
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		韩林
-- Create date: 2012-07-31
-- Description: 根据月结信息生成新年度的会计期间
-- =============================================
CREATE PROCEDURE Web_NewAcperiod

--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #ac_perido
(
	   FYear                varchar(10)          not null,
	   FMonth               varchar(10)          not null,
	   IsNature             int                  null,
	   NatureCount          int                  null,
	   FPeriod              int                  null,
	   FBegin               datetime             null,
	   FEnd                 datetime             null,
	   Deleted              int                  NULL,
	   IsDynamic			INT NOT NULL DEFAULT(0)
)
INSERT INTO #ac_perido
( 
		FYear ,
		FMonth ,
		IsNature ,
		NatureCount ,
		FPeriod ,
		FBegin ,
		FEnd ,
		Deleted ,
		IsDynamic
)
SELECT	FYear ,
		FMonth ,
		IsNature ,
		NatureCount ,
		FPeriod ,
		FBegin ,
		FEnd ,
		Deleted ,
		IsDynamic
FROM dbo.Ac_Period

DECLARE @period INT=1,@startdate DATETIME,@fyear DATETIME
--修改会计期间设置
SELECT @period=SubValue FROM dbo.sysdata WHERE SubName='Period'
IF EXISTS(SELECT 1 FROM dbo.Ac_Period WHERE FPeriod=@period)
	SELECT @startdate=FBegin FROM dbo.Ac_Period WHERE FPeriod=@period
ELSE
	SELECT @startdate=DATEADD(day,1,MAX(FBegin)) FROM dbo.Ac_Period
		
UPDATE	#ac_perido
SET		FPeriod=FPeriod-@period+1
WHERE	FPeriod>=@period

IF EXISTS(SELECT 1 FROM #ac_perido WHERE IsDynamic=1)
	DELETE FROM #ac_perido WHERE FPeriod<@period
ELSE
	UPDATE	#ac_perido
	SET		FPeriod=FPeriod+NatureCount-@period+1,
			FBegin=DATEADD(YEAR,1,FBegin),
			FEnd=DATEADD(year,1,FEnd)
	WHERE	FBegin<@startdate

SELECT @fyear=MIN(FBegin) FROM #ac_perido
UPDATE	#ac_perido 
SET		FMonth=1,
		FYear=YEAR(@fyear)

SELECT * FROM #ac_perido ORDER BY FPeriod
DROP TABLE #ac_perido

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_NewJCommissionDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_NewJCommissionDetailQuery]
GO


--==========================================
--作者：谢吉康
--日期：2003-03-18
--描述：代销库存报表，包含委托代销和受托代销
--==========================================
--==========================================
--日期：2010-03-23 Wang Wei Modify
--描述：将@sortType从int类型变成varchar(20)
--==========================================
--修改：鲁大林
--日期：2012-05-09
--描述：添加查询‘货位’cargoid

--==========================================
--日期：2015-05-27 舒珊
--描述：添加商品类别筛选
--==========================================

--==========================================
--日期：2016-05-31 舒珊
--描述：增加表头、表体新增的自定义字段查询
--==========================================

CREATE	PROCEDURE [Web_NewJCommissionDetailQuery] 
(
	@OperatorID 	varchar(50),		--操作员ID 
	@startDate     	varchar(20),        --开始时间
	@endDate      	varchar(20),
	@mType	 		varchar(20),		--查询的小类  WB=委托客户查询	WK=委托仓库查询	WJ=委托结算	 SB=受托客户查询	SK=受托仓库查询	SJ=受托结算	
	@PtypeID 		varchar(50),		--商品的ID
	@BtypeID 		varchar(1550),		--结算的ID
	
	@Jtype  		int,				--结算类型  0.非结算  1.全部发货        2.已结算             3.未结算
	@sortfield 		varchar(20)='',		--排序字段
	@sortType 		varchar(20)='asc',		--排序方式；"asc","desc"
	@Stypeid        varchar(1550)='00001',	--分支机构的ID
	@IsReporting	INT	,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
IF @BtypeID=''
   SET @BtypeID='00000'
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

DECLARE @CurSonNum int 
DECLARE @CurPSonNum int
DECLARE @isSon int
DECLARE @SortSQL varchar(2000)
DECLARE @SQL varchar(8000)

SET @SortSQL =''

CREATE TABLE #Ptype (TypeID varchar(50),usercode varchar(200),fullname varchar(200),standard varchar(200),type varchar(200),entrycode varchar(200),unit1 varchar(8))
CREATE TABLE #Btype (TypeID varchar(50),usercode varchar(200),fullname varchar(200))
CREATE TABLE #Etype (TypeID varchar(50),FullName varchar(200))
CREATE TABLE #Ktype (TypeID varchar(50),FullName varchar(200))
CREATE TABLE #Stype (TypeID varchar(50),FullName varchar(200))


IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #Ptype(typeid,usercode,fullname,standard,type,entrycode,unit1) select typeid,usercode,fullname,standard,type,entrycode,unit1 from ptype where typeid in ( select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a)
ELSE
	INSERT INTO #Ptype(typeid,usercode,fullname,standard,type,entrycode,unit1) select typeid,usercode,fullname,standard,type,entrycode,unit1 from ptype where typeid in ( select a.typeid from  F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a)

IF @BtypeID='' OR @BtypeID ='00000'
	INSERT INTO #btype(typeid,usercode,fullname) select typeid,usercode,fullname from btype where typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
ELSE
	INSERT INTO #btype(typeid,usercode,fullname) select typeid,usercode,fullname from btype where typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a)

----往来单位
--CREATE TABLE #DealBtype (TypeID VARCHAR(50))
--IF @dealBtypeID='' OR @dealBtypeID ='00000'
--	INSERT INTO #dealBtype(typeid) select typeid from btype where typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
--ELSE
--	INSERT INTO #dealBtype(typeid) select typeid from btype where typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@dealbtypeid,',')) b where left(a.typeid,len(b.a))=b.a)

INSERT INTO #Etype(typeid,fullname) select typeid,fullname from Employee --where typeid in ( select a.typeid from F_GetManDetailEType(@OperatorID) a)
--INSERT INTO #Ktype(typeid,fullname) select typeid,fullname from stock where typeid in ( select a.typeid from F_GetManDetailKType(@OperatorID) a)
INSERT INTO #Ktype(typeid,fullname) select typeid,fullname from stock where  Sonnum =0 
INSERT INTO #Ktype(typeid,fullname) select '10000','代销库' -- 加入代销仓库ID
--select * from #ptype
--select * from #btype

IF NOT (@STypeId = '' AND @MStypeid = '00000')
     INSERT INTO #Stype(typeid) select TypeID from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)

IF @mType='SJ'
BEGIN
SELECT @SQL='	  
	  SELECT 	bil.billdate,
			bil.billcode,
			b.id as CustomdetailID,
			p.usercode as pusercode,
			p.fullname as pfullname,
			p.standard,
			p.type,
            p.typeid as ptypeid,
            bil.btypeid,
			p.entrycode,
			p.unit1,
			bt1.usercode as busercode,
			bt1.fullname as bfullname,
			bil.Stypeid,
		'
IF @Jtype=1
	SELECT @SQL= @SQL +'
			sum(isnull(b.qty,0)) as qty,
			sum(isnull(b.costprice,0)) as costprice,
			sum(isnull(b.costtotal,0)) as costtotal,
			bil.billtype,
			bil.billnumberid,
			sum(isnull(b.price,0)) as price,
			sum(isnull(b.total,0)) as total,
'
IF @Jtype=2
	SELECT @SQL= @SQL +'
			sum(isnull(-b.qty,0)) as qty,
			sum(isnull(b.costprice,0)) as costprice,
			sum(isnull(-b.costtotal,0)) as costtotal,
			bil.billtype,
			bil.billnumberid,
			sum(isnull(b.price,0)) as price,
			sum(isnull(-b.total,0)) as total,
'
IF @Jtype=3
	SELECT @SQL= @SQL +'
			sum(isnull(b.qty,0)) as qty,
			sum(isnull(b.costprice,0)) as costprice,
			sum(isnull(b.costtotal,0)) as costtotal,
			bil.billtype,
			bil.billnumberid,
			sum(isnull(b.price,0)) as price,
			sum(isnull(b.total,0)) as total,
'
SELECT @SQL= @SQL +'
			bil.checke,
			e.fullname as efullname,
			bil.totalmoney,
			bil.comment,
			bil.tax,
			b.ktypeid,
			bil.etypeid ,
			kfullname =k.fullname,
			cc.fullname AS cname,
			bil.rate AS rate,
			bil.dealbtypeid,
			SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
			SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
			SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
			SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
			SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
			SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
			SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32
	  FROM  InOutStockTable b 
			INNER JOIN billindex bil ON bil.billnumberid=b.billnumberid
			INNER JOIN AC_Currency cc  ON bil.cid = cc.cid
			 left join Custom_BillIndex csindex on bil.billnumberid=csindex.BillId and bil.billtype=csindex.billtype
left join Custom_BillDetails csdetail on bil.billnumberid=csdetail.BillId and bil.billtype=csdetail.billtype AND bil.id=csdetail.Detailid
			
			'
			
IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')			
	SELECT @SQL= @SQL +' INNER JOIN #ptype p ON b.ptypeid=p.typeid '

IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00002')	
	SELECT @SQL= @SQL +' INNER JOIN #btype bt1 ON bil.btypeid=bt1.typeid '

IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SELECT @SQL= @SQL +' INNER JOIN #stype s ON bil.stypeid=s.typeid '

SELECT @SQL= @SQL +' INNER JOIN #etype e ON bil.etypeId=e.TypeID '
SELECT @SQL= @SQL +' INNER JOIN #ktype k ON b.ktypeid=k.typeid '
SELECT @SQL= @SQL +' WHERE  bil.draft=0
			AND bil.RedWord=0
			AND bil.ifcheck=''t'''

			IF @Jtype=1
				SELECT @SQL=@SQL+' AND bil.Billtype in (144,146) '+'
				 AND 
					(
						(b.billtype=144 AND b.ktypeid<>''10000'')  OR
						(b.billtype=146 AND b.ktypeid<>''10000'') 
					)'
			IF @Jtype=2
				SELECT @SQL=@SQL+' AND b.ktypeid='+char(39)+'10000'+char(39)+' AND bil.billtype=''145'''								
			IF @Jtype=3
				SELECT @SQL=@SQL+' AND bil.billtype in (144,145,146,147)'+
			    ' AND 
				(
					(b.billtype=144 AND b.ktypeid<>''10000'')  OR
				  	(b.billtype=145 AND b.ktypeid=''10000'' )  OR
					(b.billtype=146 AND b.ktypeid<>''10000'')  OR
					(b.billtype=147 AND b.ktypeid=''10000'')
				)'
				
				-- 受托代销查询增加调价单  2004-08-24  chen_qihua
				-- SELECT @SQL=@SQL+' AND bil.billtype in (144,145,146)'
			SELECT @SQL=@SQL+'
					AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)	

			SELECT @SQL=@SQL+' GROUP BY  
						bil.billdate,
						bil.billcode,
						b.id,
						p.fullname,
                        p.typeid,
                        bil.btypeid,
						bt1.fullname,
						bil.billtype,
						bil.billnumberid,
						bil.checke,
						e.fullname,
						bt1.usercode,																										
						p.usercode,
						p.standard,
						p.type,
						p.entrycode,
						p.unit1,
						bil.totalmoney,
						bil.comment,
						bil.tax,
						b.ktypeid,
						k.fullname,		
						bil.etypeid,
						b.qty,
						bil.Stypeid,
						cc.fullname,
			            bil.rate,
			            bil.dealbtypeid,
			            SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
						SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
						SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
						SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
						SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
						SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
						SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32'

	--=======================================构造排序字段
	SELECT @SortSQL=''
	IF @sortfield='BillDate'    SELECT @SortSQL=' ORDER BY billdate '
	IF @sortfield='BillCode'    SELECT @SortSQL=' ORDER BY  BillCode '
	IF @sortfield='EtypeID'     SELECT @SortSQL=' ORDER BY  EtypeID '
	IF @sortfield='PUserCode'   SELECT @SortSQL=' ORDER BY  Pusercode '
	IF @sortfield='PFullName'   SELECT @SortSQL=' ORDER BY  Pfullname '
	IF @sortfield='BFullName'   SELECT @SortSQL=' ORDER BY  Bfullname '
	IF @sortfield='Qty'  	   SELECT @SortSQL=' ORDER BY  Qty '
	IF @sortfield='Total'  	   SELECT @SortSQL=' ORDER BY  Total '
	IF @sortfield='Checke'      SELECT @SortSQL=' ORDER BY  Checke '
	IF @sortfield='BillType'    SELECT @SortSQL=' ORDER BY  BillType '
	IF @sortfield='KtypeID'     SELECT @SortSQL=' ORDER BY  KtypeID '
	IF @sortfield='UserCode'    SELECT @SortSQL=' ORDER BY  billdate '
	IF @sortfield='CostTotal'   SELECT @SortSQL=' ORDER BY  CostTotal '
	IF @SortSQL ='' 
		SELECT @SortSQL=' ORDER BY  Pusercode '

	SET @SortSQL = @SortSQL +@sortType	

	--SET @SQL = 'SELECT Y.* FROM ('+@SQL +') Y ' + @SortSQL



END 


IF @mType='WJ'
BEGIN
	SELECT @SQL='
	  SELECT 	
			bil.billdate,
			b.id as CustomdetailID,
			bil.billcode,
			p.usercode as pusercode,
			p.fullname as pfullname,
			p.standard,
			p.type,
            p.typeid as ptypeid,
            bil.btypeid,
			p.entrycode,
			p.unit1,
			bt1.usercode as busercode,
			bt1.fullname as bfullname,
			bil.Stypeid,
	'

	SELECT @SQL = @SQL +'
			bil.billtype,
			bil.billnumberid,
			isnull(sum(case b.billtype when ''140'' then - b.qty when ''142'' then -b.qty when ''141'' then -b.qty else b.qty end ),0) as qty,
			sum(isnull(case b.billtype when ''140'' then  -b.total when ''142'' then -b.total when ''141'' then -b.total else b.total end ,0)) as total,
			sum(isnull(case b.billtype when ''140'' then  -b.costtotal when ''142'' then -b.costtotal when ''141'' then -b.costtotal else b.costtotal end ,0)) as costtotal,
			'



SELECT @SQL = @SQL +'
			bil.checke,
			e.fullname as efullname,					
			bil.totalmoney,			
			bil.comment,
			bil.tax,
			b.ktypeid,
			bil.etypeid,
			kfullname =k.fullname,
			cc.fullname AS cname,
			bil.rate AS rate,
			bil.dealbtypeid,
			SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
			SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
			SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
			SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
			SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
			SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
			SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32
	  FROM  InOutStockTable b
			INNER JOIN billindex bil ON bil.billnumberid=b.billnumberid
			INNER JOIN AC_Currency cc  ON bil.cid = cc.cid
			 left join Custom_BillIndex csindex on bil.billnumberid=csindex.BillId and bil.billtype=csindex.billtype
left join Custom_BillDetails csdetail on bil.billnumberid=csdetail.BillId and bil.billtype=csdetail.billtype AND bil.id=csdetail.Detailid
			'
			
IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')				
	SELECT @SQL = @SQL +' INNER JOIN #ptype p ON b.ptypeid=p.typeid '

IF NOT(@BtypeID='' AND @MBtypeid='00001'  AND @MBtypeid2='00002')	
	SELECT @SQL = @SQL +' INNER JOIN #btype bt1 ON bil.btypeid=bt1.typeid	'

IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SELECT @SQL = @SQL +' INNER JOIN #stype s ON bil.stypeid=s.typeid '

SELECT @SQL = @SQL +' INNER JOIN #ktype k	ON b.ktypeid=k.typeid '
SELECT @SQL = @SQL +' INNER JOIN #etype e ON bil.etypeId=e.TypeID 
 																						
	  WHERE bil.draft=0
			AND bil.RedWord=0
			AND bil.ifcheck=''t'''

			IF @Jtype=1
				SELECT @SQL=@SQL+' AND bil.Billtype in (140,142) '+'
				 AND 
					(
						(b.billtype=140 AND b.ktypeid<>''10000'')  OR
						(b.billtype=142 AND b.ktypeid<>''10000'') 
					)'
			IF @Jtype=2
				select @sql=@sql+' AND bil.BillType in (141) '+'	
										AND 
										(
											(b.billtype=140 AND b.ktypeid<>''10000'')  OR
											(b.billtype=141 AND b.ktypeid=''10000'')   OR
										  	(b.billtype=142 AND b.ktypeid<>''10000'')  OR
											(b.billtype=143 AND b.ktypeid=''10000'')  
										
										)'
				--SELECT @SQL=@SQL+' AND b.ktypeid='+char(39)+'10000'+char(39)+' AND bil.billtype=''141'''											
			IF @Jtype=3
				SELECT @SQL=@SQL+' AND bil.Billtype in (140,141,142,143) ' +'
						AND 
							(
								(b.billtype=140 AND b.ktypeid<>''10000'')  OR
								(b.billtype=141 AND b.ktypeid=''10000'') OR
							  	(b.billtype=142 AND b.ktypeid<>''10000'')  OR
								(b.billtype=143 AND (b.ktypeid=''10000''))  

							)'	



				-- 委托代销未结算查询增加 调价单  2004-08-24 chen_qihua
				-- SELECT @SQL=@SQL+' AND bil.billtype in (140,141,142)'
			SELECT @SQL=@SQL+'
			AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)	
	SELECT @SQL=@SQL+'GROUP BY  
				b.id,
				bil.billdate,
				bil.billcode,
				p.fullname,
                p.typeid,
                bil.btypeid,
				bt1.fullname,
				bil.billtype,
				bil.billnumberid,
				bil.checke,
				e.fullname,
				bt1.usercode,															
				p.usercode,
				p.standard,
				p.type,
				p.entrycode,
				p.unit1,
				bil.totalmoney,
				bil.comment,
				bil.tax,
				b.ktypeid,
				k.fullname,
				bil.etypeid,
				b.qty,
				bil.Stypeid,
				cc.fullname,
			    bil.rate,
			    bil.dealbtypeid,
			    SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32'	

	--=======================================构造排序字段
	SELECT @SortSQL=''
	IF @sortfield='BillDate'    SELECT @SortSQL=' ORDER BY  billdate '
	IF @sortfield='BillCode'    SELECT @SortSQL=' ORDER BY  BillCode '
	IF @sortfield='EtypeID'     SELECT @SortSQL=' ORDER BY  EtypeID '
	IF @sortfield='PUserCode'   SELECT @SortSQL=' ORDER BY  Pusercode '
	IF @sortfield='PFullName'   SELECT @SortSQL=' ORDER BY  Pfullname '
	IF @sortfield='BFullName'   SELECT @SortSQL=' ORDER BY  Bfullname '
	IF @sortfield='Qty'  	   SELECT @SortSQL=' ORDER BY  Qty '
	IF @sortfield='Total'  	   SELECT @SortSQL=' ORDER BY  Total '
	IF @sortfield='Checke'      SELECT @SortSQL=' ORDER BY  Checke '
	IF @sortfield='BillType'    SELECT @SortSQL=' ORDER BY  BillType '
	IF @sortfield='KtypeID'     SELECT @SortSQL=' ORDER BY  KtypeID '
	IF @sortfield='UserCode'    SELECT @SortSQL=' ORDER BY  billdate '
	IF @sortfield='CostTotal'   SELECT @SortSQL=' ORDER BY  CostTotal '
	IF @SortSQL ='' 
		SELECT @SortSQL=' ORDER BY  Pusercode '
	SET @SortSQL = @SortSQL +@sortType

	--SET @SQL = 'SELECT Y.* FROM ('+@SQL +') Y ' + @SortSQL
END



--PRINT @SQL
--EXEC(@SQL)
----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
	SET @SQL = 'SELECT Y.* FROM ('+@SQL +') Y ' + @SortSQL
	--PRINT @SQL
	EXEC(@SQL)
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
--	--生成rowid
--	SET @SQL = 'SELECT row_number() over (order by bil.BillnumberID) as rowid,' + SUBSTRING(@SQL,CHARINDEX('SELECT',@SQL) + 6,LEN(@SQL))
--	CREATE TABLE #tmp_result
--	(
--		Costom1		VARCHAR(max),
--		Costom2		VARCHAR(max),
--		Costom3		VARCHAR(max),
--		Costom4		VARCHAR(max),
--		Costom5		VARCHAR(max),
--		Costom6		VARCHAR(max),
--		Costom7		VARCHAR(max),
--		Costom8		VARCHAR(max),
--		Costom9		VARCHAR(max),
--		Costom10	VARCHAR(max),
--		Costom11	VARCHAR(max),
--		Costom12	VARCHAR(max),
--		Costom13	VARCHAR(max),
--		Costom14	VARCHAR(max),
--		Costom15	VARCHAR(max),
--		Costom16	VARCHAR(max),
--		Costom1detail		varchar(max),
--		Costom2detail		varchar(max),
--		Costom3detail		varchar(max),
--		Costom4detail		varchar(max),
--		Costom5detail		varchar(max),
--		Costom6detail		varchar(max),
--		Costom7detail		varchar(max),
--		Costom8detail		varchar(max),
--		Costom9detail		varchar(max),
--		Costom10detail		varchar(max),
--		Costom11detail		varchar(max),
--		Costom12detail		varchar(max),
--		Costom13detail		varchar(max),
--		Costom14detail		varchar(max),
--		Costom15detail		varchar(max),
--		Costom16detail		varchar(max),
--		row_id				varchar(100)
--	)

--	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS Y ' + @SortSQL + 
--			  ' 
--			   DECLARE @p1 dbo.Tb_QueryCustom  
--			   INSERT INTO @p1 SELECT billnumberid,billtype,CustomdetailID,row_number() over (order by BillnumberID) from #temp1 
--			   INSERT INTO #tmp_result EXEC Web_QueryCustomData @p1,2 
			  
--				--显示最终结果
--				SELECT DISTINCT a.*,b.* 
--					  FROM #temp1 a 
--					  left join #tmp_result b on a.rowid=b.row_id 
					  
--				DROP TABLE #temp1,#tmp_result
--			   '
--	EXEC (@SQL)
--END
----------------------------------------------------------


DROP TABLE #Ptype,#Etype,#Ktype,#Stype,#btype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_NewJCommissionLineQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_NewJCommissionLineQuery]
GO


--==========================================
--作者：谢吉康
--日期：2003-03-18
--描述：代销库存报表，包含委托代销和受托代销
--==========================================
--==========================================
--日期：2003-04-02 Wang Wei Modify
--描述：将@sortType的类型从int转成varchar
--@sortType int			--1.升序  0.降序   Old
--==========================================
/* 
    修改: 舒珊
    日期: 2015-05-27
    描述: 增加查询参数@ptypecategoryid 商品类别ID 
*/
CREATE                                                          PROCEDURE [Web_NewJCommissionLineQuery] 
(
	@OperatorID varchar(50),	--操作员ID 
	@startDate     varchar(20),           --开始时间
	@endDate      varchar(20),
	@mType varchar(20),		--查询的小类  WB=委托客户查询	WK=委托仓库查询	WJ=委托结算	 SB=受托客户查询	SK=受托仓库查询	SJ=受托结算	
	@PtypeID varchar(50),		--商品的ID
	@BtypeID varchar(1550),		--结算的ID
	@sortFild varchar(20),		--排序字段
	@sortType varchar(20)='asc',	--asc.升序  desc.降序
	@Stypeid  varchar(1550)='00001',	--分支机构的ID
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS

SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

DECLARE @CurSonNum int 
DECLARE @CurPSonNum int
DECLARE @isSon int
DECLARE @SortSQL varchar(2000)
DECLARE @SQL varchar(8000)
DECLARE @SQL1 varchar(8000)
DECLARE @SQL2 varchar(8000)
DECLARE @SQL_WHERE varchar(5000)



CREATE TABLE #Ptype (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))


IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #Ptype(typeid,usercode,fullname,sonnum) 
	select typeid,usercode,fullname,sonnum 
	from ptype 
	where	typeid in ( select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a) 
			AND IsService=0
			AND iscombinationproduct = 0
ELSE
	INSERT INTO #Ptype(typeid,usercode,fullname,sonnum) 
	select typeid,usercode,fullname,sonnum 
	from ptype 
	where typeid in ( select a.typeid from  F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PtypeID,',')) b 
	where	left(a.typeid,len(b.a))=b.a) 
			AND IsService=0
			AND iscombinationproduct = 0

IF @BtypeID='' OR @BtypeID ='00000'
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a	

INSERT INTO #Etype(typeid) select a.typeid from  employee a --F_GetManDetailEType(@OperatorID) a
INSERT INTO #Ktype(typeid) select a.typeid from F_GetManDetailKType(@OperatorID) a
INSERT INTO #Ktype select '10000' -- 加入代销仓库ID

IF NOT (@STypeId = '' AND @MStypeid = '00000')
   INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)

SET @SortSQL =''
SET @SQL=''

IF @mType='SJ'
BEGIN
	SELECT @SQL='
			SELECT  
				p.usercode,
				p.fullname,
				p.sonnum,
				p.typeid,
				sum(isnull(a.sqnojsqty,0)) as sqnojsqty,
				sum(isnull(a.sqnojstotal,0)) as sqnojstotal,
				sum(isnull(a.fhqty,0)) as fhqty,
				sum(isnull(a.fhtotal,0)) as fhtotal,
				sum(isnull(a.thqty,0)) as thqty,
				sum(isnull(a.thtotal,0)) as thtotal,
				sum(isnull(a.jsqty,0)) as jsqty,
				sum(isnull(a.jstotal,0)) as jstotal,
				sum(isnull(a.qmnojsqty,0)) as qmnojsqty,
				sum(isnull(a.qmnojstotal,0)) as qmnojstotal,
				fhprice =case when sum(isnull(a.fhqty,0)) =0 then 0 else  cast( sum(isnull(a.fhtotal,0))as NUMERIC(24, 10))/cast(sum(isnull(a.fhqty,0)) as NUMERIC(24, 10)) end,
				jsprice =case when sum(isnull(a.jsqty,0)) =0 then 0 else  cast( sum(isnull(a.jstotal,0))as NUMERIC(24, 10))/cast(sum(isnull(a.jsqty,0))as NUMERIC(24, 10)) end
			FROM #Ptype p
				LEFT JOIN
					('

						SELECT @SQL=@SQL+'
								SELECT  	a.ptypeid,
											sqnojsqty	  = isnull(case when a.billdate<'''+@startDate+''' then  a.qty else 0 end ,0),
											sqnojstotal   = isnull(case when a.billdate<'''+@startDate+''' then  a.Total else 0 end,0),
											fhqty 	  = isnull(case a.billtype when ''144'' then a.qty else 0 end,0),
											fhtotal   = isnull(case a.billtype when ''144'' then a.Total when ''147'' then a.Total else 0 end,0),
											thqty 	  = isnull(case a.billtype when ''146'' then -a.qty   else 0 end,0),
											thtotal   = isnull(case a.billtype when ''146'' then -a.Total else 0 end,0),
											jsqty 	  = isnull(case a.billtype when ''145'' then -a.qty   else 0 end,0),
											jstotal   = isnull(case a.billtype when ''145'' then -a.Total else 0 end,0),
											qmnojsqty	= isnull(a.qty,0),
											qmnojstotal = isnull(a.Total,0)
				
									FROM    InOutStockTable a
									INNER JOIN BillIndex bil ON a.billnumberid=bil.billnumberid '
									
				 IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')					
					SELECT @SQL=@SQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
				 
				 IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00002')	
					SELECT @SQL=@SQL+' INNER JOIN #Btype b ON bil.btypeid=b.typeid '
					
				 IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SELECT @SQL=@SQL+' INNER JOIN #Stype s ON bil.stypeid=s.typeid '
				 
				 SELECT @SQL=@SQL+' INNER JOIN #Etype e ON bil.etypeid=e.typeid
									WHERE bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			   AND bil.BillType in (144,145,146,147) '+'	
											AND 
												(
													(a.billtype=144 AND a.ktypeid<>''10000'')  OR
													(a.billtype=145 AND a.ktypeid=''10000'')   OR
												  	(a.billtype=146 AND a.ktypeid<>''10000'')  OR
													(a.billtype=147 AND a.ktypeid=''10000'')  

												)'	
								
									SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										
									 -- 上期结余数量单独算
									SELECT @SQL2='
									SELECT  	a.ptypeid,
												sqnojsqty	  = isnull(case when a.billdate<'''+@startDate+''' then  a.qty else 0 end ,0),
												sqnojstotal   = isnull(case when a.billdate<'''+@startDate+''' then  a.Total else 0 end,0),
												fhqty 	  = 0,
												fhtotal   = 0,
												thqty 	  = 0,
												thtotal   = 0,
												jsqty 	  = 0,
												jstotal   = 0,
												qmnojsqty	= isnull(a.qty,0),
												qmnojstotal = isnull(a.Total,0)
					
										FROM    InOutStockTable a
										INNER JOIN BillIndex bil ON a.billnumberid=bil.billnumberid '
										
				   IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')						
					SELECT @SQL2=@SQL2+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
				   
				   IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
					SELECT @SQL2=@SQL2+' INNER JOIN #Btype b ON bil.btypeid=b.typeid '
				   
				   IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SELECT @SQL2=@SQL2+' INNER JOIN #Stype s ON bil.stypeid=s.typeid '
				   
				   SELECT @SQL2=@SQL2+' INNER JOIN #Etype e ON bil.etypeid=e.typeid		
									WHERE bil.draft=0
											   AND bil.RedWord=0
				  							   AND bil.ifcheck=''t''
					  	   		    			   AND bil.BillType in (144,145,146,147) '+'	
												AND 
													(
														(a.billtype=144 AND a.ktypeid<>''10000'')  OR
														(a.billtype=145 AND a.ktypeid=''10000'') OR
													  	(a.billtype=146 AND a.ktypeid<>''10000'')  OR
														(a.billtype=147 AND a.ktypeid=''10000'')  
	
													)'
								SELECT @SQL2=@SQL2+' AND bil.billdate<'+char(39)+@startDate+char(39)
									-- 期初
								SELECT @SQL1 = 'SELECT  ptypeid,
													sqnojsqty	  = qty,
													sqnojstotal   = total,
													fhqty 	  = 0,
													fhtotal   = 0,
													thqty 	  = 0,
													thtotal   = 0,
													jsqty 	  = 0,
													jstotal   = 0,
													qmnojsqty = qty,
													qmnojstotal = total
											from inicommissionStock c '
							
							IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')				
								SELECT @SQL1=@SQL1+' INNER JOIN #Ptype p ON c.ptypeid=p.typeid '
							
							IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
								SELECT @SQL1=@SQL1+' INNER JOIN #Btype b ON c.btypeid=b.typeid '
								
							IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SELECT @SQL1=@SQL1+' INNER JOIN #Stype s ON c.stypeid=s.typeid '
							
							SELECT @SQL1=@SQL1+' WHERE c.Type=144 '
							
							SELECT @SQL =@SQL +'
												 UNION ALL ' +@SQL1+'
												 UNION ALL ' +@SQL2

								
			SELECT @SQL=@SQL+')a
			ON   p.typeid=a.ptypeid
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
	SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'

	IF @sortFild ='qty'
			SELECT @SortSQL=' Order By Qty '					
	IF @sortFild ='CostTotal'
		SELECT @SortSQL=' Order By CostTotal '	
	IF @SortSQL=''
		SELECT @SortSQL=@SortSQL+' Order By P.UserCode'

	SELECT @SortSQL=@SortSQL +' '+@sortType
	SELECT @SQL = @SQL + @SortSQL

END 

IF @mType='WJ'
BEGIN
	SELECT @SQL='
			SELECT  
				p.usercode,
				p.fullname,
				p.sonnum,
				p.typeid,
				sum(isnull(a.sqnojsqty,0)) as sqnojsqty,
				sum(isnull(a.sqnojstotal,0)) as sqnojstotal,
				sum(isnull(a.fhqty,0)) as fhqty,
				sum(isnull(a.fhtotal,0)) as fhtotal,
				sum(isnull(a.thqty,0)) as thqty,
				sum(isnull(a.thtotal,0)) as thtotal,
				sum(isnull(a.jsqty,0)) as jsqty,
				sum(isnull(a.jstotal,0)) as jstotal,
				sum(isnull(a.qmnojsqty,0)) as qmnojsqty,
				sum(isnull(a.qmnojstotal,0)) as qmnojstotal,
			
		fhprice =case when sum(isnull(a.fhqty,0)) =0 then 0 else  cast( sum(isnull(a.fhtotal,0))as NUMERIC(24, 10))/cast(sum(isnull(a.fhqty,0)) as NUMERIC(24, 10)) end,			
				jsprice =case when sum(isnull(a.jsqty,0)) =0 then 0 else cast(  sum(isnull(a.jstotal,0))as NUMERIC(24, 10))/cast(sum(isnull(a.jsqty,0))as NUMERIC(24, 10)) end
			FROM #Ptype p
				LEFT JOIN
					('

						SELECT @SQL=@SQL+'
									SELECT  a.ptypeid,
											sqnojsqty	  = isnull(case a.billtype when ''140'' then  case when a.billdate<'''+@startDate+''' then  -a.qty else 0 end when ''142'' then case when a.billdate<'''+@startDate+''' then  -a.qty else 0 end else case when a.billdate<'''+@startDate+''' then  a.qty else 0 end end,0),
											sqnojstotal   = isnull(case a.billtype when ''140'' then  case when a.billdate<'''+@startDate+''' then  -a.Total else 0 end  when ''142'' then case when a.billdate<'''+@startDate+''' then  -a.Total else 0 end else case when a.billdate<'''+@startDate+''' then  a.Total else 0 end end,0),
											fhqty 	  = isnull(case a.billtype when ''140'' then -a.qty else 0 end,0),
											fhtotal   = isnull(case a.billtype when ''140'' then -a.Total when ''143'' then a.Total else 0 end,0),
											thqty 	  = isnull(case a.billtype when ''142'' then a.qty   else 0 end,0),
											thtotal   = isnull(case a.billtype when ''142'' then a.Total else 0 end,0),
											jsqty 	  = isnull(case a.billtype when ''141'' then -a.qty   else 0 end,0),
											jstotal   = isnull(case a.billtype when ''141'' then -a.Total else 0 end,0),
											qmnojsqty	  = isnull(case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end,0),
											qmnojstotal = isnull(case a.billtype when ''140'' then -a.Total when ''142'' then -a.Total else a.Total end,0)
				
									FROM    InOutStockTable a
									INNER JOIN BillIndex bil ON a.billnumberid=bil.billnumberid '
									
				 IF NOT(@PtypeID='' AND @MPtypeid='00000'AND @ptypecategoryid='')					
					SELECT @SQL=@SQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
				 
				 IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
					SELECT @SQL=@SQL+' INNER JOIN #Btype b ON bil.btypeid=b.typeid '
					
				 
				 IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SELECT @SQL=@SQL+' INNER JOIN #Stype s ON bil.stypeid=s.typeid '
				 
				 SELECT @SQL=@SQL+' INNER JOIN #Etype e ON bil.etypeid=e.typeid
									WHERE bil.draft=0
										   AND bil.RedWord=0
			  							   AND bil.ifcheck=''t''
				  	   		    			   AND bil.BillType in (140,141,142,143) '+'	
											AND 
												(
													(a.billtype=140 AND a.ktypeid<>''10000'')  OR
													(a.billtype=141 AND a.ktypeid=''10000'')   OR
												  	(a.billtype=142 AND a.ktypeid<>''10000'')  OR
													(a.billtype=143 AND a.ktypeid=''10000'')  

												)'											
										SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										
										-- 上期结余数量单独算
										SELECT @SQL2='
											SELECT  a.ptypeid,
													sqnojsqty	  = isnull(case a.billtype when ''140'' then  case when a.billdate<'''+@startDate+''' then  -a.qty else 0 end when ''142'' then case when a.billdate<'''+@startDate+''' then  -a.qty else 0 end else case when a.billdate<'''+@startDate+''' then  a.qty else 0 end end,0),
													sqnojstotal   = isnull(case a.billtype when ''140'' then  case when a.billdate<'''+@startDate+''' then  -a.Total else 0 end  when ''142'' then case when a.billdate<'''+@startDate+''' then  -a.Total else 0 end else case when a.billdate<'''+@startDate+''' then  a.Total else 0 end end,0),
													fhqty 	  = 0,
													fhtotal   = 0,
													thqty 	  = 0,
													thtotal   = 0,
													jsqty 	  = 0,
													jstotal   = 0,
													qmnojsqty = isnull(case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end,0),
													qmnojstotal = isnull(case a.billtype when ''140'' then -a.Total when ''142'' then -a.Total else a.Total end,0)
						
											FROM    InOutStockTable a
											INNER JOIN BillIndex bil ON  a.billnumberid=bil.billnumberid '
											
						 IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')					
							SET @SQL2= @SQL2+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
						 
						 IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
							SET @SQL2= @SQL2+' INNER JOIN #Btype b ON bil.btypeid=b.typeid '
							
						 IF NOT (@STypeId = '' AND @MStypeid = '00000')
							SET @SQL2= @SQL2+' INNER JOIN #Stype s ON bil.stypeid=s.typeid '
						 
						 SET @SQL2= @SQL2+' INNER JOIN #Etype e ON bil.etypeid=e.typeid
											WHERE  bil.draft=0
												   AND bil.RedWord=0
					  							   AND bil.ifcheck=''t''
						  		    			   AND bil.BillType in (140,141,142,143) '+'	
												   AND 
														(
															(a.billtype=140 AND a.ktypeid<>''10000'')  OR
															(a.billtype=141 AND a.ktypeid=''10000'')   OR
														  	(a.billtype=142 AND a.ktypeid<>''10000'')  OR
															(a.billtype=143 AND a.ktypeid=''10000'')  
		
														)'
											SET @SQL2= @SQL2+' AND bil.billdate<'+char(39)+@startDate+char(39)

									-- 期初
									SELECT @SQL1 = 'SELECT  ptypeid,
															sqnojsqty	  = qty,
															sqnojstotal   = total,
															fhqty 	  = 0,
															fhtotal   = 0,
															thqty 	  = 0,
															thtotal   = 0,
															jsqty 	  = 0,
															jstotal   = 0,
															qmnojsqty = qty,
															qmnojstotal = total
													from inicommissionStock c '
													
									IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')				
										SELECT @SQL1=@SQL1+' INNER JOIN #Ptype p ON c.ptypeid=p.typeid '
									
									IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00002')	
										SELECT @SQL1=@SQL1+' INNER JOIN #Btype b ON c.btypeid=b.typeid '
									
									IF NOT (@STypeId = '' AND @MStypeid = '00000')
										SELECT @SQL1=@SQL1+' INNER JOIN #Stype s ON c.stypeid=s.typeid '
									
									SELECT @SQL1=@SQL1+' WHERE  c.Type=140 ' 
									SELECT @SQL =@SQL +'
														 UNION ALL ' +@SQL1+'
														 UNION ALL ' +@SQL2

					
				SELECT @SQL=@SQL+')a
			ON   p.typeid=a.ptypeid
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
	SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'

	IF @sortFild ='qty'
			SELECT @SortSQL=' Order By Qty '					
	IF @sortFild ='CostTotal'
		SELECT @SortSQL=' Order By CostTotal '	
	IF @SortSQL=''
		SELECT @SortSQL=@SortSQL+' Order By P.UserCode'

	SELECT @SortSQL=@SortSQL +' '+@sortType

	SELECT @SQL = @SQL + @SortSQL
END
-- PRINT @SQL
EXEC(@SQL)

DROP TABLE #Ptype,#Etype,#Ktype,#Stype,#Btype






































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_NewJCommissionListQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_NewJCommissionListQuery]
GO





--==========================================
--作者：陈启华
--日期：2005-09-22
--描述：委托、受托代销结算
--==========================================
--==========================================
--修改: 魏伟
--日期: 2015-05-23
--描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
--==========================================
CREATE                                                             PROCEDURE [Web_NewJCommissionListQuery] 
(
	@OperatorID varchar(50),	--操作员ID 
	@startDate     varchar(20),           --开始时间
	@endDate      varchar(20),
	@mType varchar(20),		--查询的小类  WJ=委托结算	 SJ=受托结算	
	@PtypeID varchar(50),		--商品的ID
	@BtypeID varchar(1550),		--客户的ID
	@Stypeid varchar(1550),		--分支机构的ID	
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS

SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

DECLARE @CurSonNum int 
DECLARE @CurPSonNum int
DECLARE @isSon int
DECLARE @SortSQL varchar(2000)
DECLARE @SQL varchar(8000)
DECLARE @SQL1 varchar(8000)
DECLARE @SQL2 varchar(8000)
DECLARE @SQL_WHERE varchar(5000)
SET @SortSQL=''

CREATE TABLE #Ptype (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Ktype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum INT,sortid INT)


IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #Ptype(typeid) select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid)  a
ELSE
	INSERT INTO #Ptype(typeid) select a.typeid from  F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @BtypeID='' OR @BtypeID ='00000'
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a

INSERT INTO #Etype(typeid) select a.typeid from  employee a   --F_GetManDetailEType(@OperatorID) a
INSERT INTO #Ktype(typeid) select a.typeid from F_GetManDetailKType(@OperatorID) a
INSERT INTO #Ktype select '10000' -- 加入代销仓库ID

IF NOT (@Stypeid='' AND @MStypeid='00000')
   INSERT INTO #Stype(typeid) select typeid from  F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)


DECLARE @sonnum int 
SET @sonnum =0

SELECT @sonnum = sonnum FROM Ptype WHERE Typeid =case when @PtypeID='' then '00000' else @PtypeID end
IF @sonnum =0 
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sortid) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.SortID FROM Ptype p
	,(select * from F_GetManPTypeAll(@OperatorID) where typeid =@PtypeID) a 
	where	p.typeid=a.typeid 
			AND p.IsService=0
			AND p.iscombinationproduct = 0
ELSE
	IF @PtypeID ='' OR @PtypeID='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sortid) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.SortID FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid=case  when @PtypeID='' then '00000' else @PtypeID end) a 
			where	p.typeid=a.typeid  
					AND p.IsService=0
					AND p.iscombinationproduct = 0
	ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,sortid) 
		SELECT DISTINCT p.typeid,p.usercode,p.fullname,p.sonnum ,p.SortID 
		FROM Ptype p
		 INNER JOIN F_GetManPTypeAll(@OperatorID) mp ON p.typeid=mp.typeid
		 INNER JOIN #Ptype pt ON pt.typeid LIKE p.typeid + '%'
		where p.parid=(case  when @PtypeID='' then '00000' else @PtypeID end )   and p.typeid LIKE @PtypeID+'%'   AND p.IsService=0


IF @mType='SJ'
BEGIN
	SELECT @SQL='
			SELECT  
				p.usercode,
				p.fullname,
				p.sonnum,
				p.typeid,
				sum(isnull(a.sqnojsqty,0)) as sqnojsqty,
				sum(isnull(a.sqnojstotal,0)) as sqnojstotal,
				sum(isnull(a.fhqty,0)) as fhqty,
				sum(isnull(a.fhtotal,0)) as fhtotal,
				sum(isnull(a.thqty,0)) as thqty,
				sum(isnull(a.thtotal,0)) as thtotal,
				sum(isnull(a.jsqty,0)) as jsqty,
				sum(isnull(a.jstotal,0)) as jstotal,
				sum(isnull(a.qmnojsqty,0)) as qmnojsqty,
				sum(isnull(a.qmnojstotal,0)) as qmnojstotal,
				fhprice =case when sum(isnull(a.fhqty,0)) =0 then 0 else  cast( sum(isnull(a.fhtotal,0))as NUMERIC(24, 10))/cast(sum(isnull(a.fhqty,0)) as NUMERIC(24, 10)) end,
				jsprice =case when sum(isnull(a.jsqty,0)) =0 then 0 else   cast(sum(isnull(a.jstotal,0)) as NUMERIC(24, 10))/cast(sum(isnull(a.jsqty,0))as NUMERIC(24, 10)) end
			FROM #MainType p
				LEFT JOIN
					('
					SELECT @SQL=@SQL+'
								SELECT  	a.ptypeid,
											sqnojsqty	  = 0,
											sqnojstotal   = 0,
											fhqty 	  = isnull(case a.billtype when ''144'' then a.qty else 0 end,0),
											fhtotal   = isnull(case a.billtype when ''144'' then a.Total when ''147'' then a.Total else 0 end,0),
											thqty 	  = isnull(case a.billtype when ''146'' then -a.qty   else 0 end,0),
											thtotal   = isnull(case a.billtype when ''146'' then -a.Total else 0 end,0),
											jsqty 	  = isnull(case a.billtype when ''145'' then -a.qty   else 0 end,0),
											jstotal   = isnull(case a.billtype when ''145'' then -a.Total else 0 end,0),
											qmnojsqty	= isnull(a.qty,0),
											qmnojstotal = isnull(a.Total,0)
				
									FROM    InOutStockTable a 
									INNER JOIN BillIndex bil ON a.billnumberid=bil.billnumberid '
									
				 IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')					
					SELECT @SQL=@SQL+' INNER JOIN #Ptype p ON  a.ptypeid=p.typeid '
				 
				 IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
					SELECT @SQL=@SQL+' INNER JOIN #Btype b ON  bil.btypeid=b.typeid '
				 
				 IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SELECT @SQL=@SQL+' INNER JOIN #Stype s ON  bil.stypeid=s.typeid '
				 
				 SELECT @SQL=@SQL+' INNER JOIN #Etype e ON  bil.etypeid=e.typeid 
								    WHERE bil.draft=0
										AND bil.RedWord=0
										AND bil.ifcheck=''t''
										AND bil.BillType in (144,145,146,147) '+'	
										AND 
												(
													(a.billtype=144 AND a.ktypeid<>''10000'')  OR
													(a.billtype=145 AND a.ktypeid=''10000'') OR
												  	(a.billtype=146 AND a.ktypeid<>''10000'')  OR
													(a.billtype=147 AND a.ktypeid=''10000'')  

												)'	
					
									SET @SQL = @SQL + ' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)	
									-- 单独算上期结余数量
									SET @SQL2 ='
												SELECT  	a.ptypeid,
														sqnojsqty	  = isnull(a.qty ,0),
														sqnojstotal   = isnull(a.Total,0),
														fhqty 	  = 0,
														fhtotal   = 0,
														thqty 	  = 0,
														thtotal   = 0,
														jsqty 	  = 0,
														jstotal   = 0,
														qmnojsqty	= isnull(a.qty,0),
														qmnojstotal = isnull(a.Total,0)
							
												FROM    InOutStockTable a
												INNER JOIN BillIndex bil ON  a.billnumberid=bil.billnumberid '
												
							 IF NOT(@PtypeID='' AND @MPtypeid='00000'AND @ptypecategoryid='')					
								SET @SQL2 =@SQL2+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
							 
							 IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00002')	
								SET @SQL2 =@SQL2+' INNER JOIN #Btype b ON bil.btypeid=b.typeid '
							 
							 IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SET @SQL2 =@SQL2+' INNER JOIN #Stype s ON bil.stypeid=s.typeid '
							 
							 SET @SQL2 =@SQL2+' INNER JOIN #Etype e ON bil.etypeid=e.typeid 
													
							                    WHERE bil.draft=0
													AND bil.RedWord=0
													   AND bil.ifcheck=''t''
														   AND bil.BillType in (144,145,146,147) '+'	
													AND 
														(
															(a.billtype=144 AND a.ktypeid<>''10000'')  OR
															(a.billtype=145 AND a.ktypeid=''10000'')   OR
														  	(a.billtype=146 AND a.ktypeid<>''10000'')  OR
															(a.billtype=147 AND a.ktypeid=''10000'')  
													
														) '	
									SET @SQL2 = @SQL2 +  ' AND bil.billdate <'+char(39)+@startDate+char(39)
									
								-- 期初
								SELECT @SQL1 = 'SELECT  c.ptypeid,
													sqnojsqty	  = qty,
													sqnojstotal   = total,
													fhqty 	  = 0,
													fhtotal   = 0,
													thqty 	  = 0,
													thtotal   = 0,
													jsqty 	  = 0,
													jstotal   = 0,
													qmnojsqty = qty,
													qmnojstotal = total
											from inicommissionStock c '
											
							IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')				
								SELECT @SQL1=@SQL1+' INNER JOIN #Ptype p ON c.ptypeid=p.typeid '
							
							IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')		
								SELECT @SQL1=@SQL1+' INNER JOIN #Btype b ON c.btypeid=b.typeid '

							IF NOT (@STypeId = '' AND @MStypeid = '00000')
								SELECT @SQL1=@SQL1+' INNER JOIN #Stype s ON c.stypeid=s.typeid '
							
							SELECT @SQL1=@SQL1+' WHERE c.Type=144 ' 
							SELECT @SQL =@SQL +'
												 UNION ALL ' +@SQL1+'
												 UNION ALL ' +@SQL2


			SELECT @SQL=@SQL+')a
			ON   p.typeid=left(a.ptypeid,len(p.typeid)) 
			
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
			SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid'		

			SELECT @SortSQL=@SortSQL+' Order By p.UserCode'
			SELECT @SQL=@SQL+ @SortSQL
				

END 

IF @mType='WJ'
BEGIN
	SELECT @SQL='
			SELECT  
				p.usercode,
				p.fullname,
				p.sonnum,
				p.typeid,
				sum(isnull(a.sqnojsqty,0)) as sqnojsqty,
				sum(isnull(a.sqnojstotal,0)) as sqnojstotal,
				sum(isnull(a.fhqty,0)) as fhqty,
				sum(isnull(a.fhtotal,0)) as fhtotal,
				sum(isnull(a.thqty,0)) as thqty,
				sum(isnull(a.thtotal,0)) as thtotal,
				sum(isnull(a.jsqty,0)) as jsqty,
				sum(isnull(a.jstotal,0)) as jstotal,
				sum(isnull(a.qmnojsqty,0)) as qmnojsqty,
				sum(isnull(a.qmnojstotal,0)) as qmnojstotal,
				fhprice =case when sum(isnull(a.fhqty,0)) =0 then 0 else  CAST( sum(isnull(a.fhtotal,0)) AS NUMERIC(24, 10))/CAST(sum(isnull(a.fhqty,0)) AS NUMERIC(24, 10)) end,
				jsprice =case when sum(isnull(a.jsqty,0)) =0 then 0 else  CAST( sum(isnull(a.jstotal,0)) AS NUMERIC(24, 10))/CAST( sum(isnull(a.jsqty,0))AS NUMERIC(24, 10)) end
			FROM #MainType p
				LEFT JOIN
					('
						SELECT @SQL=@SQL+'
									SELECT  a.ptypeid,
											sqnojsqty	  = isnull(case a.billtype when ''140'' then  case when a.billdate<'''+@startDate+''' then  -a.qty else 0 end when ''142'' then case when a.billdate<'''+@startDate+''' then  -a.qty else 0 end else case when a.billdate<'''+@startDate+''' then  a.qty else 0 end end,0),
											sqnojstotal   = isnull(case a.billtype when ''140'' then  case when a.billdate<'''+@startDate+''' then  -a.Total else 0 end  when ''142'' then case when a.billdate<'''+@startDate+''' then  -a.Total else 0 end else case when a.billdate<'''+@startDate+''' then  a.Total else 0 end end,0),
											fhqty 	  = isnull(case a.billtype when ''140'' then -a.qty else 0 end,0),
											fhtotal   = isnull(case a.billtype when ''140'' then -a.Total when ''143'' then a.Total else 0 end,0),
											thqty 	  = isnull(case a.billtype when ''142'' then a.qty   else 0 end,0),
											thtotal   = isnull(case a.billtype when ''142'' then a.Total else 0 end,0),
											jsqty 	  = isnull(case a.billtype when ''141'' then -a.qty   else 0 end,0),
											jstotal   = isnull(case a.billtype when ''141'' then -a.Total else 0 end,0),
											qmnojsqty	  = isnull(case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end,0),
											qmnojstotal = isnull(case a.billtype when ''140'' then -a.Total when ''142'' then -a.Total else a.Total end,0)
				
									FROM    InOutStockTable a
									INNER JOIN BillIndex bil ON a.billnumberid=bil.billnumberid '
									
			     IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')						
					SELECT @SQL=@SQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
				 
				 IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid2='00002')		
					SELECT @SQL=@SQL+' INNER JOIN #Btype b ON bil.btypeid=b.typeid '
				 
				 IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SELECT @SQL=@SQL+' INNER JOIN #Stype S ON bil.stypeid=s.typeid '
				 
				SELECT @SQL=@SQL+'		WHERE bil.draft=0
										AND bil.RedWord=0
										AND bil.ifcheck=''t''
											   AND bil.BillType in (140,141,142,143) '+'	
										AND 
										(
											(a.billtype=140 AND a.ktypeid<>''10000'')  OR
											(a.billtype=141 AND a.ktypeid=''10000'')   OR
										  	(a.billtype=142 AND a.ktypeid<>''10000'')  OR
											(a.billtype=143 AND a.ktypeid=''10000'')  
										
										)'											
							SELECT @SQL=@SQL+' AND bil.billdate>='+char(39)+@startDate+char(39)+' AND bil.billdate<='+char(39)+@endDate+char(39)										



							
							-- 上期结余数量单独算
							SELECT @SQL2='
									SELECT  a.ptypeid,
											sqnojsqty	  = isnull(case a.billtype when ''140'' then  case when a.billdate<'''+@startDate+''' then  -a.qty else 0 end when ''142'' then case when a.billdate<'''+@startDate+''' then  -a.qty else 0 end else case when a.billdate<'''+@startDate+''' then  a.qty else 0 end end,0),
											sqnojstotal   = isnull(case a.billtype when ''140'' then  case when a.billdate<'''+@startDate+''' then  -a.Total else 0 end  when ''142'' then case when a.billdate<'''+@startDate+''' then  -a.Total else 0 end else case when a.billdate<'''+@startDate+''' then  a.Total else 0 end end,0),
											fhqty 	  = 0,
											fhtotal   = 0,
											thqty 	  = 0,
											thtotal   = 0,
											jsqty 	  = 0,
											jstotal   = 0,
											qmnojsqty	  = isnull(case a.billtype when ''140'' then -a.qty when ''142'' then -a.qty else a.qty end,0),
											qmnojstotal = isnull(case a.billtype when ''140'' then -a.Total when ''142'' then -a.Total else a.Total end,0)
				
									FROM    InOutStockTable a
									INNER JOIN BillIndex bil ON a.billnumberid=bil.billnumberid '
									
			IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')						
				SELECT @SQL2= @SQL2 + ' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
			
			IF NOT(@BtypeID='' AND @MBtypeid='00001' AND @MBtypeid='00001')
				SELECT @SQL2= @SQL2 + ' INNER JOIN #Btype b ON bil.btypeid=b.typeid '
			
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SELECT @SQL2= @SQL2 + ' INNER JOIN #Stype s ON bil.stypeid=s.typeid ' 
			
			SELECT @SQL2= @SQL2 + ' WHERE bil.draft=0
										AND bil.RedWord=0
										AND bil.ifcheck=''t''
										AND bil.BillType in (140,141,142,143) '+'	
										AND 
										(
											(a.billtype=140 AND a.ktypeid<>''10000'')  OR
											(a.billtype=141 AND a.ktypeid=''10000'')   OR
											(a.billtype=142 AND a.ktypeid<>''10000'')  OR
											(a.billtype=143 AND a.ktypeid=''10000'')  
											
										)'	
	
							SELECT @SQL2= @SQL2 + ' AND bil.billdate<'+char(39)+@startDate+char(39)
							-- 期初
							SELECT @SQL1 = 'SELECT  ptypeid,
													sqnojsqty	  = qty,
													sqnojstotal   = total,
													fhqty 	  = 0,
													fhtotal   = 0,
													thqty 	  = 0,
													thtotal   = 0,
													jsqty 	  = 0,
													jstotal   = 0,
													qmnojsqty = qty,
													qmnojstotal = total
											from inicommissionStock  c '
											
							IF NOT(@PtypeID='' AND @MPtypeid='00000' AND @ptypecategoryid='')				
							SELECT @SQL1=@SQL1+' INNER JOIN #Ptype p ON c.ptypeid=p.typeid '
							
							IF NOT(@BtypeID='' AND @MBtypeid='00000' AND @MBtypeid2='00000')	
							SELECT @SQL1=@SQL1+' INNER JOIN #Btype b ON c.btypeid=b.typeid '
							
							IF (@Stypeid<>'' or @MStypeid='-99999')			
							SELECT @SQL1=@SQL1+' INNER JOIN #Stype s ON c.stypeid=s.typeid '
							
							SELECT @SQL1=@SQL1+' WHERE c.Type=140 ' 
							SELECT @SQL =@SQL +'
												 UNION ALL ' +@SQL1
												+'
												 UNION ALL ' +@SQL2
				SELECT @SQL=@SQL+')a
			ON   p.typeid=left(a.ptypeid,len(p.typeid))
			--INNER JOIN #Ptype pt ON pt.typeid LIKE p.typeid + ''%''
			WHERE p.typeid<>'+char(39)+'00000'+char(39)
	SELECT @SQL=@SQL+' GROUP BY p.usercode,p.fullname,p.sonnum,p.typeid,p.sortid'

	SELECT @SortSQL=@SortSQL+' Order By p.sortid'	
	SELECT @SQL=@SQL+ @SortSQL
END

--PRINT @SQL
EXEC(@SQL)

DROP TABLE #MainType
DROP TABLE #Ptype
DROP TABLE #Btype
DROP TABLE #Etype
DROP TABLE #Ktype
DROP TABLE #Stype






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_NewQueryCargoDistributeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_NewQueryCargoDistributeLine]
GO

/*
	作者：彭勇	
	日期：2012-06-19
	描述：货位分布线性表
*/
CREATE PROCEDURE Web_NewQueryCargoDistributeLine
(
	@operatorid			 	 NVARCHAR(50),		-- 当前操作员ID
	@stypeid             	 NVARCHAR(200),     --分支机构ID
    @ktypeid             	 NVARCHAR(200),     --仓库ID
    @cargoid             	 NVARCHAR(max),     --货位ID
    @ptypeid 		         NVARCHAR(MAX)='00000', 
	@unitconvert             NVARCHAR(10),    --多单位种类
	@entrycode				 NVARCHAR(200)='',
	@usercode 				 NVARCHAR(200),
	@fullname 				 NVARCHAR(200) ,
	@showzeroqty             INT =0   --是否显示零单据
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql NVARCHAR(max)=''
DECLARE @Condition NVARCHAR(MAX)	
------------------------------------------------------权限检查---------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid NVARCHAR(50), @MBtypeid NVARCHAR(50), @MBtypeid2 NVARCHAR(50), @MEtypeid NVARCHAR(50),
           @MKtypeid NVARCHAR(50), @MPtypeid NVARCHAR(50), @MExpense NVARCHAR(50), @MIncome NVARCHAR(50),@MCapital NVARCHAR(50),@MDtypeid NVARCHAR(50),@MStypeid NVARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
------------------------------------------------------权限检查---------------------------------------------------------------
---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	NVARCHAR(100))
CREATE NONCLUSTERED INDEX CIX_GetSelectSTypeId_TypeId ON #GetSelectSTypeId(TypeId)

INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--仓库
CREATE TABLE #GetManKTypeId(TypeId	NVARCHAR(100))
CREATE NONCLUSTERED INDEX CIX_GetManKTypeId_TypeId ON #GetManKTypeId(TypeId)

INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM  F_GetManDetailKTypeSType(@OperatorID) k 
INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	
	
--货位
CREATE TABLE #GetSelectCargoid(cargoid NVARCHAR(100),typeid NVARCHAR(100))
CREATE NONCLUSTERED INDEX CIX_GetSelectCargoid_CargoId ON #GetSelectCargoid(cargoid)

IF @cargoid = '00000' OR @cargoid = '' OR @cargoid = '%'
				INSERT INTO #GetSelectCargoid(cargoid,typeid) SELECT CargoID,KtypeID FROM CargoType a
				INNER JOIN #GetManKTypeId b ON a.KtypeID=b.TypeId
			ELSE
				INSERT INTO #GetSelectCargoid(cargoid,typeid)
				SELECT 	A.CargoID ,a.KtypeID
				FROM 	CargoType A, 
						(SELECT A FROM dbo.F_Split(@cargoid,',')) B 
						,#GetManKTypeId c 
				WHERE	A.CargoID = B.A AND c.typeid =a.ktypeid
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),
        @temprice   NVARCHAR(2000)
IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/R3.rate',
		@UnitName = 'U3.fullname',
		@temprice='g.price*R3.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/R2.rate',
		@UnitName = 'U2.fullname',
		@temprice='g.price*R2.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/R4.rate',
		@UnitName = 'U4.fullname',
		@temprice='g.price*R4.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'U1.fullname',
		@temprice='g.price',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','5,1','')
END
----------多单位计算End---------
IF @PTypeId = '00000'
	SET @PTypeId = ''
	
CREATE TABLE #ptype
	(
		typeId 		 NVARCHAR (200) NOT NULL,
		sumqty 			 NUMERIC(24, 10) ,
		sumcostprice 	 NUMERIC(24, 10) ,
		sumcosttotal 	 NUMERIC(24, 10) ,
		sumnqty			 NUMERIC(24, 10) ,
		unitname         NVARCHAR(2000),--计量单位
	    assistantname    NVARCHAR(2000),--浮动单位
	    basename		 NVARCHAR(2000)--基本单位	  
	)
CREATE NONCLUSTERED INDEX CIX_PType_TypeId ON #ptype(TypeId)	
	
DECLARE @GsSql NVARCHAR(MAX),@SQLSELECT NVARCHAR(MAX)=''


IF(@PTypeId<>'')
 BEGIN
	SET @SQLSELECT='	INSERT INTO  #ptype
						( 
							typeId ,
							unitname ,
							assistantname ,
							basename
						)
						SELECT	DISTINCT
								q.TypeID,
								'+@UnitName+',
								u5.fullname,
								u1.fullname
						FROM    F_GetManPType('''+@OperatorID+''') q 
						INNER JOIN (SELECT A FROM dbo.F_Split('''+@PTypeId+''','','')) B ON q.TypeId LIKE B.A +''%''
						inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
						where	q.sonnum=0
								AND p1.IsService=0
								AND P1.iscombinationproduct=0
								AND ('''+@usercode+''' ='''' OR p1.UserCode LIKE ''%'+@usercode+'%'')
								AND ('''+@fullname+'''= '''' OR p1.FullName LIKE ''%'+@fullname+'%'')
								AND ('''+@entrycode+''' ='''' OR p1.MultEntryCode LIKE ''%'+@entrycode+'%'')'
 END
ELSE
 BEGIN
	 SET @SQLSELECT='	INSERT INTO  #ptype
						( 
							typeId ,
							unitname ,
							assistantname ,
							basename
						)
						SELECT  DISTINCT
								q.TypeID,
								'+@UnitName+',
								u5.fullname,
								u1.fullname
						FROM    F_GetManPType('''+@OperatorID+''') q 
						inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
						where	q.sonnum=0
								AND p1.IsService=0
								AND P1.iscombinationproduct=0
								AND ('''+@usercode+''' ='''' OR p1.UserCode LIKE ''%'+@usercode+'%'')
								AND ('''+@fullname+'''= '''' OR p1.FullName LIKE ''%'+@fullname+'%'')
								AND ('''+@entrycode+''' ='''' OR p1.MultEntryCode LIKE ''%'+@entrycode+'%'')'
 
 END

--PRINT(@SQLSELECT)
EXEC(@SQLSELECT)

CREATE TABLE #GsStock
(
	PTypeId	NVARCHAR(100),
	Qty	 NUMERIC(24, 10) ,
	price  NUMERIC(24, 10) ,
	total  NUMERIC(24, 10) ,
	KTypeID	NVARCHAR(100),
	NQty  NUMERIC(24, 10) ,
	cargoid int	

)
CREATE NONCLUSTERED INDEX CIX_GsStock_PTypeId ON #GsStock(PTypeId,cargoid)

SET @GsSql='
	INSERT INTO #GsStock
	SELECT	P.TypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,
			ISNULL('+@temprice+',0) as price,
			ISNULL('+@temprice+',0) *ISNULL(SUM('+@Qty+'),0) as total,
			G.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty,
			q.cargoid
	FROM	#ptype p inner join ptype p1 on p1.typeid=p.typeid
	INNER JOIN (select ptypeid,ktypeid,case when sum(qty)=0 then 0 else  sum(total)/sum(qty) end as price FROM GoodsStocks group by ptypeid,ktypeid)
	g  ON g.PTypeId = p.typeid
	INNER JOIN GoodsStocks_Qty Q ON Q.ptypeid = G.ptypeid  and  g.ktypeid=q.ktypeid AND Q.Qty<>0
	inner join #GetSelectCargoid d on q.cargoid=d.cargoid'+ @tmptab
	SET @GsSql = @GsSql + '	GROUP BY P.TypeId,G.KTypeID,q.cargoid,'+@temprice

--PRINT(@GsSql)
EXEC(@GsSql)


CREATE TABLE #result
(	    ID INT IDENTITY(1,1),
	    ptypeId 		 NVARCHAR (200) NOT NULL,
		sumqty 			 NUMERIC(24, 10) ,
		sumcostprice 	 NUMERIC(24, 10) ,
		sumcosttotal 	 NUMERIC(24, 10) ,
		sumnqty			 NUMERIC(24, 10) ,
		unitname         NVARCHAR(2000),--计量单位
	    assistantname    NVARCHAR(2000),--浮动单位
	    basename		 NVARCHAR(2000)--基本单位
	
		
)
CREATE NONCLUSTERED INDEX CIX_Result_PTypeId ON #result(PTypeid)

DECLARE @cargocount int 
DECLARE @j INT SET @j=1

SELECT @cargocount=MAX(num) FROM(
SELECT COUNT(cargoid) AS num FROM #GsStock GROUP BY PTypeId)a


IF @cargocount IS NULL
 ALTER TABLE #result ADD 
	[货位名称1] NVARCHAR(200),
	CargoQty1 NUMERIC(24,10),
	CargonQty1 NUMERIC(24,10),
	CargoPrice1 NUMERIC(24,10),
	CargoTotal1 NUMERIC(24,10)
ELSE

WHILE @j<= @cargocount
	BEGIN
	SET @GsSql='	ALTER TABLE #result ADD 
	[货位名称'+CAST(@j AS NVARCHAR(20))+'] NVARCHAR(200),
	CargoQty'+CAST(@j AS NVARCHAR(20))+' NUMERIC(24,10),
	CargonQty'+CAST(@j AS NVARCHAR(20))+' NUMERIC(24,10),
	CargoPrice'+CAST(@j AS NVARCHAR(20))+' NUMERIC(24,10),
	CargoTotal'+CAST(@j AS NVARCHAR(20))+' NUMERIC(24,10)'
	SET @j=@j+1
		 EXEC(@GsSql)
	END

--是否显示库存为0
IF @showzeroqty = 0
BEGIN
	;WITH tbZero AS 
	(
		SELECT	A.TypeId,
				SUM(ISNULL(G.Qty,0)) AS Qty,
				SUM(ISNULL(G.price,0)) AS price,
				SUM(ISNULL(G.total,0)) AS total,
				sum(isnull(g.nqty,0))as nqty,
				unitname,
				assistantname,
				basename
		FROM 	#ptype A
		INNER JOIN #GsStock G ON  G.PTypeId = A.TypeId
		GROUP BY A.TypeId,unitname,
				assistantname,
				basename
	)
	INSERT  INTO #result
			( PTypeID ,
			  sumqty ,
			  sumcostprice ,
			  sumcosttotal ,
			  sumnqty,
			  unitname,
			  assistantname,
			  basename
			)
	SELECT  TypeId ,
			qty ,
			( CASE ISNULL(Qty, 0)
				WHEN 0 THEN 0
				ELSE ISNULL(total, 0) / ISNULL(Qty, 0)
			  END ) ,
			total ,
			nqty,
			unitname,
			assistantname,
			basename
	FROM    tbZero
END
ELSE
BEGIN
	;WITH tb AS 
	(
		SELECT	A.TypeId,
				SUM(ISNULL(G.Qty,0)) AS Qty,
				SUM(ISNULL(G.price,0)) AS price,
				SUM(ISNULL(G.total,0)) AS total,
				sum(isnull(g.nqty,0))as nqty,
				unitname,
				assistantname,
				basename
		FROM 	#ptype A
		LEFT JOIN #GsStock G ON  G.PTypeId = A.TypeId
		GROUP BY A.TypeId,unitname,
				assistantname,
				basename
	)
	INSERT  INTO #result
			( PTypeID ,
			  sumqty ,
			  sumcostprice ,
			  sumcosttotal ,
			  sumnqty,
			  unitname,
			  assistantname,
			  basename
			)
	SELECT  TypeId ,
			qty ,
			( CASE ISNULL(Qty, 0)
				WHEN 0 THEN 0
				ELSE ISNULL(total, 0) / ISNULL(Qty, 0)
			  END ) ,
			total ,
			nqty,
			unitname,
			assistantname,
			basename
	FROM    tb
END

DECLARE @PID NVARCHAR(50),
		@price NUMERIC(24,10),		
		@cargoname NVARCHAR(200),
		@cargoqty NUMERIC(24,10),
		@cargonqty NUMERIC(24,10),
		@i NVARCHAR(10),
		@total NUMERIC(24,10)


DECLARE pcur CURSOR FOR SELECT PTypeID,sumcostprice FROM #result
						
OPEN pcur
FETCH NEXT FROM pcur INTO @PID,@price
WHILE(@@FETCH_STATUS=0)
BEGIN
	SET @i='1'
	DECLARE gcur CURSOR FOR SELECT c.FullName,SUM(ISNULL(Qty,0)),SUM(ISNULL(nQty,0)),SUM(ISNULL(total,0)) FROM #GsStock g
								INNER JOIN dbo.CargoType c	ON g.CargoID=c.CargoID
									WHERE g.PTypeID=@PID
								GROUP BY g.CargoID,c.FullName
								ORDER BY SUM(ISNULL(Qty,0)) DESC	
	OPEN gcur
	FETCH NEXT FROM gcur INTO @cargoname,@cargoqty,@cargonqty,@total
	WHILE(@@FETCH_STATUS=0)
	BEGIN	
			
		SET @sql='update #result set [货位名称'+@i+']=@pcargoname,CargoQty'+@i+'=@pqty,cargonqty'+@i+'=@pnqty,CargoPrice'+@i+'=@pprice,CargoTotal'+@i+'=@ptotal where ptypeid=@pptypeid'
		EXEC  SP_EXECUTESQL @stmt=@sql,@params=N'@pcargoname NVARCHAR(200),@pqty numeric(24,10),@pnqty numeric(24,10),@pprice numeric(24,10),@ptotal numeric(24,10),@pptypeid NVARCHAR(50)',
			 @pcargoname=@cargoname,@pqty=@cargoqty,@pnqty=@cargonqty,@pprice=@price,@ptotal=@total,@pptypeid=@PID
	
		--PRINT(@sql)			
		SET @i=CAST( CAST(@i AS INT)+1 AS NVARCHAR)
		FETCH NEXT FROM gcur INTO @cargoname,@cargoqty,@cargonqty,@total
	END								
	CLOSE gcur
	DEALLOCATE gcur
		
	FETCH NEXT FROM pcur INTO @PID,@price
END
CLOSE pcur
DEALLOCATE pcur				

SELECT * FROM #result 

DROP TABLE #GetManKTypeId,#GetSelectCargoid,#GetSelectSTypeId,#GsStock,#ptype,#result

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_NewQueryStockDistributingLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_NewQueryStockDistributingLine]
GO

--描述:库存分布表
--作者:彭勇
--日期：2015-10-15


CREATE   PROCEDURE Web_NewQueryStockDistributingLine
(

	@operatorid				NVARCHAR(50),		-- 当前操作员ID
	@stypeid             	NVARCHAR(200),     --分支机构ID
    @ktypeid             	NVARCHAR(MAX),     --仓库ID
    @ptypeid 		        NVARCHAR(MAX)='00000', 
	@unitconvert            NVARCHAR(10),    --多单位种类
	@entrycode				NVARCHAR(200)='',
	@usercode 				NVARCHAR(200),
	@fullname 				NVARCHAR(200) ,
	@showzeroqty            INT =0,   --是否显示零单据
	@sort					NVARCHAR(20),
	@ptypeCategoryid		VARCHAR(max)=''
 )
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid NVARCHAR(50), @MBtypeid NVARCHAR(50), @MBtypeid2 NVARCHAR(50), @MEtypeid NVARCHAR(50),
           @MKtypeid NVARCHAR(50), @MPtypeid NVARCHAR(50), @MExpense NVARCHAR(50), @MIncome NVARCHAR(50),@MCapital NVARCHAR(50),@MDtypeid NVARCHAR(50),@MStypeid NVARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @re_check INT
EXEC @re_check=GP_CheckLimit @OperatorID,453
DECLARE @RS_CHECK INT
EXEC @RS_CHECK=dbo.GP_CheckLimit @OperatorID,2642

---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	NVARCHAR(100))
IF @RS_CHECK=0
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
ELSE 
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,'00001')
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	NVARCHAR(100))
IF @re_check=1--没有效
	BEGIN 
		  INSERT INTO #GetManKTypeId(TypeId) 
		  SELECT	SS.TypeId 
		  FROM	dbo.Stock ss
		  INNER JOIN  #GetSelectSTypeId s ON SS.STypeId=s.TypeId
		  WHERE	
			  deleted=0 
			  AND (ISNULL(@ktypeid,'')='' OR (ISNULL(@ktypeid,'')<>'' AND EXISTS(SELECT * FROM f_split(@ktypeid,',') F WHERE SS.typeId LIKE F.a+'%')))
	END 	
ELSE--有效
	BEGIN
		INSERT INTO #GetManKTypeId(TypeId) 
		SELECT	s.typeid 
		FROM	Stock s,
				#GetSelectSTypeId st,
				F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) GK
		WHERE	S.STypeID = St.typeId 
				AND S.TypeId = GK.TypeId
				AND s.sonnum = 0 
				AND deleted=0	
	END	
--商品
CREATE TABLE #PtypeDetail(TypeId	NVARCHAR(100))
INSERT INTO #PtypeDetail(TypeId) SELECT TypeId FROM dbo.F_ManPTypeInCategoryID(@OperatorID,@ptypeid,@ptypeCategoryid)

-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE
	@SQL		NVARCHAR(MAX)='',
	@Qty		VARCHAR(2000),
	@UnitName	VARCHAR(2000),
	@tmptab		VARCHAR(2000),
	@temprice   VARCHAR(2000)
IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/r3.rate',
		@UnitName = 'u5.fullname',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','3,5','3'),
		@temprice='g.price*R3.rate'
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/r2.rate',
		@UnitName = 'u5.fullname',
		@temprice='g.price*R2.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/r4.rate',
		@UnitName = 'u5.fullname',
		@temprice='g.price*R4.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'u5.fullname',
		@temprice='g.price',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','5','')
END
----------多单位计算End---------
IF @PTypeId = '00000'
	SET @PTypeId = ''
CREATE TABLE #ptype
	(
		typeId 		 NVARCHAR (200) NOT NULL,
		sumqty 			 NUMERIC(24, 10) ,
		sumcostprice 	 NUMERIC(24, 10) ,
		sumcosttotal 	 NUMERIC(24, 10) ,
		sumnqty			 NUMERIC(24, 10) ,
		unitname         NVARCHAR(2000),--计量单位
	    assistantname    NVARCHAR(2000)--浮动单位
	  	  
	)
DECLARE 
	@GsSql NVARCHAR(MAX),
	@SQLSELECT NVARCHAR(MAX)=''

SET @SQLSELECT='
	INSERT INTO #ptype
	(
		typeId,
		unitname,
		assistantname 
	 )
	SELECT  
		q.TypeID,
		'+@UnitName+',
		u5.fullname
	FROM #PtypeDetail q 
	inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
	where 
	p1.sonnum=0
	AND p1.IsService=0
	AND p1.iscombinationproduct=0'+CHAR(13)

 IF(ISNULL(@usercode,'')<>'')
	SET @SQLSELECT+='AND p1.UserCode LIKE ''%'+@usercode+'%'''+CHAR(13)
	
 IF(ISNULL(@fullname,'')<>'')
	SET @SQLSELECT+='AND p1.FullName LIKE ''%'+@fullname+'%'''+CHAR(13)
	
 IF(ISNULL(@entrycode,'')<>'')
	SET @SQLSELECT+='AND p1.MultEntryCode LIKE ''%'+@entrycode+'%'''+CHAR(13)
	
EXEC(@SQLSELECT)

CREATE TABLE #GsStock
(
	PTypeId	NVARCHAR(100),
	Qty	 NUMERIC(24, 10) ,
	price  NUMERIC(24, 10) ,
	total  NUMERIC(24, 10) ,
	KTypeID	NVARCHAR(100),
	NQty  NUMERIC(24, 10) ,


)
SET @GsSql='
	INSERT INTO #GsStock
	SELECT	P.TypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,
			ISNULL('+@temprice+',0) as price,
			ISNULL('+@temprice+',0) *ISNULL(SUM('+@Qty+'),0) as total,
			G.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty		
	FROM	#ptype p 
	inner join ptype p1 on p1.typeid=p.typeid
	INNER JOIN (
					select	ptypeid,
							ktypeid,
							case when sum(qty)=0 then 0 else  sum(total)/sum(qty) end as price 
					FROM	GoodsStocks 					
					group by ptypeid,ktypeid
	)g  ON g.PTypeId=p.TypeId
	INNER JOIN #GetManKTypeId k on g.ktypeid=k.TypeId
	INNER JOIN GoodsStocks_Qty Q ON Q.ptypeid = G.ptypeid  and  g.ktypeid=q.ktypeid'+ @tmptab

SET @GsSql = @GsSql + '	GROUP BY P.TypeId,G.KTypeID,'+@temprice

--PRINT(@GsSql)	
EXEC(@GsSql)

CREATE TABLE #result
(	    
	ID INT IDENTITY(1,1),
    ptypeId 		 NVARCHAR (200) NOT NULL,
	sumqty 			 NUMERIC(24, 10) ,
	sumcostprice 	 NUMERIC(24, 10) ,
	sumcosttotal 	 NUMERIC(24, 10) ,
	sumnqty			 NUMERIC(24, 10) ,
	unitname         NVARCHAR(2000),--计量单位
    assistantname    NVARCHAR(2000),--浮动单位
    basename		 NVARCHAR(2000)--基本单位
)
DECLARE @stockcount int=0 
DECLARE @j INT SET @j=1

SELECT @stockcount=ISNULL(MAX(num),0) FROM(
SELECT COUNT(KTypeID) AS num FROM #GsStock GROUP BY PTypeId)a

IF @stockcount > 100
BEGIN
	RAISERROR('查询的仓库数量太多，已超过数据库能支持的上限！建议查询的仓库数不要超过100个。',16,1)
	RETURN
END

--IF @stockcount=0
--	BEGIN
--		 ALTER TABLE #result ADD 
--			[仓库名称1] NVARCHAR(200),
--			StockQty1 NUMERIC(24,10),
--			StocknQty1 NUMERIC(24,10),
--			StockPrice1 NUMERIC(24,10),
--			StockTotal1 NUMERIC(24,10)
--	END
--ELSE

IF @stockcount>0
	BEGIN
		SET @GsSql='	ALTER TABLE #result ADD '
		WHILE @j<= @stockcount
		BEGIN
			SET @GsSql +='
			[仓库名称'+CAST(@j AS NVARCHAR(20))+'] NVARCHAR(200),
			StockQty'+CAST(@j AS NVARCHAR(20))+' NUMERIC(24,10),
			StocknQty'+CAST(@j AS NVARCHAR(20))+' NUMERIC(24,10),
			StockPrice'+CAST(@j AS NVARCHAR(20))+' NUMERIC(24,10),
			StockTotal'+CAST(@j AS NVARCHAR(20))+' NUMERIC(24,10),
			'
			SET @j=@j+1
		END

		SET @GsSql += ' a int'

		BEGIN TRY
			EXEC(@GsSql)
		END TRY
		BEGIN CATCH
			RAISERROR('查询的仓库数量太多，已超过数据库能支持的上限！建议查询的仓库数不要超过100个。',16,1)
			RETURN
		END CATCH
	END

--显示库存为0 
IF @showzeroqty = 0
BEGIN
	;WITH tbZero AS 
	(
		SELECT	A.TypeId,
				SUM(ISNULL(G.Qty,0)) AS Qty,
				SUM(ISNULL(G.price,0)) AS price,
				SUM(ISNULL(G.total,0)) AS total,
				sum(isnull(g.nqty,0))as nqty
		FROM 	#ptype A
		INNER JOIN #GsStock G ON  G.PTypeId = A.TypeId
		GROUP BY A.TypeId
	)
	INSERT  INTO #result
	( 
		PTypeID ,
		sumqty ,
		sumcostprice ,
		sumcosttotal ,
		sumnqty
	)
	SELECT  TypeId ,
			qty ,
			( CASE ISNULL(Qty, 0)
				WHEN 0 THEN 0
				ELSE ISNULL(total, 0) / ISNULL(Qty, 0)
			  END ) ,
			total ,
			nqty
	FROM    tbZero
END
ELSE
BEGIN	
	;WITH tb AS 
	(
		SELECT	A.TypeId,
				SUM(ISNULL(G.Qty,0)) AS Qty,
				SUM(ISNULL(G.price,0)) AS price,
				SUM(ISNULL(G.total,0)) AS total,
				sum(isnull(g.nqty,0))as nqty
		FROM 	#ptype A
		LEFT JOIN #GsStock G ON  G.PTypeId = A.TypeId
		GROUP BY A.TypeId
	)
	INSERT  INTO #result
	( 
		PTypeID ,
		sumqty ,
		sumcostprice ,
		sumcosttotal ,
		sumnqty
	)
	SELECT  TypeId ,
			qty ,
			( CASE ISNULL(Qty, 0)
				WHEN 0 THEN 0
				ELSE ISNULL(total, 0) / ISNULL(Qty, 0)
			  END ) ,
			total ,
			nqty
	FROM    tb	
END		

DECLARE @PID NVARCHAR(50),
		@price NUMERIC(24,10),	
		@stockname NVARCHAR(200),
		@stockqty NUMERIC(24,10),
		@stocknqty NUMERIC(24,10),
		@i NVARCHAR(10),
		@total NUMERIC(24,10)


DECLARE pcur CURSOR FOR SELECT PTypeID,sumcostprice FROM #result
						
OPEN pcur
FETCH NEXT FROM pcur INTO @PID,@price
WHILE(@@FETCH_STATUS=0)
BEGIN
	SET @i='1'
	DECLARE gcur CURSOR FOR SELECT c.FullName,SUM(ISNULL(Qty,0)),SUM(ISNULL(nQty,0)),SUM(ISNULL(total,0)) FROM #GsStock g
								INNER JOIN dbo.Stock c	ON g.KTypeID=c.typeId
									WHERE g.PTypeID=@PID
								GROUP BY g.KTypeID,c.FullName
								ORDER BY SUM(ISNULL(Qty,0)) DESC	
	OPEN gcur
	FETCH NEXT FROM gcur INTO @stockname,@stockqty,@stocknqty,@total
	WHILE(@@FETCH_STATUS=0)
	BEGIN	
			
		SET @sql='update #result set [仓库名称'+@i+']=@pstockname,StockQty'+@i+'=@pqty,Stocknqty'+@i+'=@pnqty,StockPrice'+@i+'=@pprice,StockTotal'+@i+'=@ptotal where ptypeid=@pptypeid'
		EXEC  SP_EXECUTESQL @stmt=@sql,@params=N'@pstockname NVARCHAR(200),@pqty numeric(24,10),@pnqty numeric(24,10),@pprice numeric(24,10),@ptotal numeric(24,10),@pptypeid NVARCHAR(50)',
			 @pstockname=@stockname,@pqty=@stockqty,@pnqty=@stocknqty,@pprice=@price,@ptotal=@total,@pptypeid=@PID
			
		SET @i=CAST( CAST(@i AS INT)+1 AS NVARCHAR)
		FETCH NEXT FROM gcur INTO @stockname,@stockqty,@stocknqty,@total
	END								
	CLOSE gcur
	DEALLOCATE gcur
		
	FETCH NEXT FROM pcur INTO @PID,@price
END
CLOSE pcur
DEALLOCATE pcur				


update #result set assistantname=p.assistantname  from  #result a inner join #ptype p on a.ptypeid=p.typeid

SELECT * FROM #result 


DROP TABLE #GetManKTypeId,#GetSelectSTypeId,#GsStock,#PtypeDetail,#ptype,#result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_News_QuickSearch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_News_QuickSearch]
GO













/****** Object:  Stored Procedure dbo.Web_News_QuickSearch    Script Date: 2002-6-20 10:14:55 ******/

/*
Alan
2002-02-26
公告板查找
*/


CREATE PROCEDURE Web_News_QuickSearch
(
  @szKeywords VARCHAR(100),	--关键字
  @szScope_Title VARCHAR(5),	--是否查找标题:false true
  @szScope_Author VARCHAR(5),	--是否查找作者:false true
  @szScope_Content VARCHAR(5),	--是否查找内容:false true
  @szDateTime  VARCHAR(10),	--时间范围:7,30,100
  @szCID VARCHAR(10)		--分类ID
)
--@encode$--
AS

DECLARE @SQL VARCHAR(1000),@TEMP VARCHAR(100)
DECLARE @N INT
SELECT @N=0


SELECT @SQL = 'SELECT * FROM News AS a WHERE'

SELECT @szKeywords = @szKeywords + CHAR(32)

WHILE CHARINDEX(CHAR(32),LTRIM(@szKeywords),1) > 0

  BEGIN

    SELECT @szKeywords = LTRIM(@szKeywords)					--去除后空格

    SELECT @TEMP = LEFT(@szKeywords,CHARINDEX(CHAR(32),@szKeywords,1)-1)    	--找到第一个空格前的关键字

    SELECT @szKeywords = RIGHT(@szKeywords,LEN(@szKeywords)-LEN(@TEMP))		--去除第一个关键字后的关键字符串

    --PRINT @TEMP

    IF @N = 0
      BEGIN
        IF @szScope_Title = 'true' AND @szScope_Author = 'true' AND @szScope_Content = 'true'
          BEGIN    
            SELECT @SQL = @SQL + ' strTitle like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strAuthor like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strContent like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'true' AND @szScope_Author = 'true' AND @szScope_Content = 'false'
          BEGIN
            SELECT @SQL = @SQL + ' strTitle like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strAuthor like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'true' AND @szScope_Author = 'false' AND @szScope_Content = 'false'
          BEGIN
            SELECT @SQL = @SQL + ' strTitle like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'false' AND @szScope_Author = 'true' AND @szScope_Content = 'true'
          BEGIN
            SELECT @SQL = @SQL + ' strAuthor like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strContent like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'false' AND @szScope_Author = 'true' AND @szScope_Content = 'false'
          BEGIN
            SELECT @SQL = @SQL + ' strAuthor like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'false' AND @szScope_Author = 'false' AND @szScope_Content = 'true'
          BEGIN
            SELECT @SQL = @SQL + ' strContent like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'true' AND @szScope_Author = 'false' AND @szScope_Content = 'true'
          BEGIN
            SELECT @SQL = @SQL + ' strTitle like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strContent like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END

        SELECT @N = 1
      END
    ELSE
      BEGIN
        IF @szScope_Title = 'true' AND @szScope_Author = 'true' AND @szScope_Content = 'true'
          BEGIN    
            SELECT @SQL = @SQL + ' OR strTitle like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strAuthor like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strContent like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'true' AND @szScope_Author = 'true' AND @szScope_Content = 'false'
          BEGIN
            SELECT @SQL = @SQL + ' OR strTitle like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strAuthor like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'true' AND @szScope_Author = 'false' AND @szScope_Content = 'false'
          BEGIN
            SELECT @SQL = @SQL + ' OR strTitle like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'false' AND @szScope_Author = 'true' AND @szScope_Content = 'true'
          BEGIN
            SELECT @SQL = @SQL + ' OR strAuthor like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strContent like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'false' AND @szScope_Author = 'true' AND @szScope_Content = 'false'
          BEGIN
            SELECT @SQL = @SQL + ' OR strAuthor like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'false' AND @szScope_Author = 'false' AND @szScope_Content = 'true'
          BEGIN
            SELECT @SQL = @SQL + ' OR strContent like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
        IF @szScope_Title = 'true' AND @szScope_Author = 'false' AND @szScope_Content = 'true'
          BEGIN
            SELECT @SQL = @SQL + ' OR strTitle like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
            SELECT @SQL = @SQL + ' OR strContent like ' + CHAR(39) + '%' + @TEMP + '%' + CHAR(39)
          END
    END

  END

SELECT @SQL = @SQL + ' AND DATEDIFF(DY,LEFT(strDateTime,10),GETDATE()) <= ' + @szDateTime

SELECT @SQL = @SQL + ' AND nCatalogID = ' + @szCID

SELECT @SQL = @SQL + ' ORDER BY [ID] DESC'

EXEC(@SQL)

--PRINT @SQL







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_NewStock_Line]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Web_NewStock_Line
GO
 --	=======================================
 --	描述:库存状况线型表
 --	时间:2014-03-20
 --	作者:周华
 -- 2014-7-11 修改除数为0的问题
 -- 2014-7-16 成本均价成倍增加的问题
 -- 2014-8-5 调整成临时表优化性能
 --	修改:杨俊
 -- 2014-11-17 修复期初数据没有分组a.KtypeId，
 -- 导致计算某个商品时SUM了数量没有SUM金额的问题
 --	=======================================
CREATE PROCEDURE Web_NewStock_Line
(
	@OperatorId VARCHAR(100)='' --操作员id
	,@Parid varchar(100)='00000' --父类商品Id,
	,@StypeIds VARCHAR(max)='' --分支机构ids
	,@KtypeIds VARCHAR(max)='' --仓库ids
	,@DisplayActual INT=0 --是否显示实际库存 1显示 0不显示
	,@DisplayStop INT=0 --是否显示停用商品   1 显示 0不显示
	,@PriceType INT=0 --显示价格方式 0~19表示20种不同的价格方式
	,@Date DATETIME=NULL --时间,截止时间,用于历史状况的查询
	
	,@DisplayZero INT =1 --是否显示为0的数据 1显示 0不显示
	,@FilterPtypeFullName VARCHAR(100)='' --筛选 商品名称
	,@FilterPtypeUserCode VARCHAR(100)='' --筛选 商品编号
	,@FilterPtypeEntryCode VARCHAR(100)='' --筛选 商品条码
	,@FilterPtypeArea VARCHAR(100)='' --筛选 商品地域
	,@Type           VARCHAR(200)=''--筛选 商品地域
	,@Standard		 VARCHAR(200)=''	
)
--@encode$--	
AS
BEGIN
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
			   @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------

	DECLARE @sonnum INT;
	DECLARE @innerPtypeId VARCHAR(100)='';
	
	DECLARE @FilterPtypeId VARCHAR(100)='';
	IF @Parid='' 
		SET @Parid='00000';
		
	IF @Parid='00000' AND @MPtypeid<>'-99999'
		SET @Parid=@MPtypeid;
	
	SELECT @sonnum=sonnum FROM ptype WHERE typeid=@Parid;
	IF @Parid<>'00000'
		SET @innerPtypeId=@Parid;
	ELSE
		SET @ParId='';
	
	--把权限函数提出来
	CREATE TABLE #KStype(TypeId VARCHAR(50),STypeId VARCHAR(50));
	CREATE TABLE #BTType(TypeId VARCHAR(50));
	CREATE CLUSTERED INDEX #KStype_t ON #KStype(TypeId);
	CREATE CLUSTERED INDEX #BTType_t ON #BTType(TypeId);
	
	INSERT INTO #KStype SELECT TypeId,STypeId  FROM F_GetManDetailKTypeSType(@OperatorId);
	INSERT INTO #BTType SELECT TypeId  FROM F_GetAllManagerBaseTypeId(@StypeIds,11,@OperatorID);

	CREATE TABLE #Ktype(TypeId VARCHAR(50));
	CREATE CLUSTERED INDEX #Ktype_t ON #Ktype(TypeId);
	
	INSERT INTO #KType SELECT TypeId FROM F_GetAllBaseTypeId(@KtypeIds,4) WHERE @KtypeIds<>''

	--
	CREATE TABLE #goods(PtypeId VARCHAR(50),KtypeId VARCHAR(50),price  NUMERIC(24, 10) );
	CREATE CLUSTERED INDEX #goods_p_k ON #goods(PTypeId,KtypeId)
	CREATE TABLE #inigoods(PtypeId VARCHAR(50),KtypeId VARCHAR(50),price  NUMERIC(24, 10) );
	CREATE CLUSTERED INDEX #inigoods_p_k ON #inigoods(PTypeId,KtypeId)

	IF @Date IS NULL
	BEGIN
		INSERT INTO #goods 
		SELECT PtypeId,KtypeId, case when sum(qty)=0 then 0 else sum(total)/sum(qty) end as price
		FROM dbo.GoodsStocks
		WHERE PtypeId LIKE @innerPtypeId+'%'
		AND (@KtypeIds<>'' AND KtypeId IN (SELECT TypeId FROM #Ktype) OR @KtypeIds='')
		--AND (@KtypeIds<>'' AND ','+@KtypeIds+',' LIKE '%,'+KtypeId+',%' OR @KtypeIds='') --参数范围
		AND KtypeId IN (
				SELECT u.TypeId FROM #KStype u
					JOIN #BTType v ON u.STypeId=v.TypeId
			) --操作员仓库权限
		GROUP BY PtypeId,KtypeId
	END
	
	IF @Date IS NOT NULL
	BEGIN
		INSERT INTO #inigoods
		SELECT PtypeId,KtypeId,case when sum(qty)=0 then 0 else sum(total)/sum(qty) end as price
		FROM dbo.IniGoodsStocks
		WHERE KtypeId IN (
				SELECT u.TypeId FROM #KStype u
					JOIN #BTType v ON u.STypeId=v.TypeId
			) --操作员仓库权限
		AND (@KtypeIds<>'' AND KtypeId IN (SELECT TypeId FROM #Ktype) OR @KtypeIds='')
		--AND (@KtypeIds<>'' AND ','+@KtypeIds+',' LIKE '%,'+KtypeId+',%' OR @KtypeIds='') --参数范围				
		AND PtypeId LIKE @innerPtypeId+'%'
		GROUP BY PtypeId,KtypeId
	END
	--

	CREATE TABLE #cte(PtypeId VARCHAR(50),qty  NUMERIC(24, 10) ,nqty  NUMERIC(24, 10) ,total  NUMERIC(24, 10) 
	,lend  NUMERIC(24, 10) ,borrow  NUMERIC(24, 10) ,wt  NUMERIC(24, 10) ,st  NUMERIC(24, 10),Iscombined INT,ItemID INT   );
	CREATE CLUSTERED INDEX #cte_p ON #cte(PtypeId);

	--库存
	INSERT INTO #cte
	SELECT a.PtypeId,SUM(b.Qty) AS qty,SUM(b.NQty) AS nqty,SUM(b.Qty)*MAX(a.price) AS total
	,0 AS lend,0 AS borrow,0 AS wt,0 AS st,Iscombined,ItemID
	FROM #goods a LEFT JOIN dbo.GOODSSTOCKS_QTY b ON a.Ptypeid=b.PTypeID AND a.KtypeId=b.KTypeID
	WHERE @Date IS NULL
	GROUP BY a.PtypeId,a.KtypeId,Iscombined ,ItemID


	--UNION ALL
	--期初数据
	INSERT INTO #cte
	SELECT a.PtypeId,SUM(b.qty) AS qty,SUM(b.nqty) AS nqty,SUM(b.Qty)*MAX(a.price) AS total
	,0 AS lend,0 AS borrow,0 AS wt,0 AS st,Iscombined,ItemID
	FROM #inigoods a LEFT JOIN dbo.Ini_GOODSSTOCKS_QTY b ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
	WHERE @Date IS NOT NULL 	
	GROUP BY a.PtypeId,a.KtypeId,Iscombined ,ItemID
	
	--UNION ALL
	--出入库数据 
	INSERT INTO #cte
	SELECT PtypeId,CASE WHEN BillType=57 THEN 0 ELSE qty END qty,NQty,CostTotal AS total
	,0,0,0,0,Iscombined,ItemID
	FROM dbo.InOutstocktable 
	WHERE @Date IS NOT NULL AND BillDate<=@Date --时间条件
	AND KtypeId IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
	AND (@KtypeIds<>'' AND KtypeId IN (SELECT TypeId FROM #Ktype) OR @KtypeIds='')
	--AND (@KtypeIds<>'' AND ','+@KtypeIds+',' LIKE '%,'+KtypeId+',%' OR @KtypeIds='') --参数范围
	AND KtypeId <>'10000' --排除受托委托库
	AND STypeID IN (SELECT TypeId FROM #BTType) 
	AND PtypeId LIKE @innerPtypeId+'%'
	
	
	--显示实际的情况
	--UNION ALL
	
	-- 借欠
	INSERT INTO #cte
	SELECT vls.pTypeID,0,0,0
	,vls.Lend-vls.LendBack-vls.saleqty AS lendQty
	,vls.Borrow-vls.BorrowBack-vls.buyqty AS borrowQty
	,0,0,Iscombined,ItemID FROM V_LendStatus vls
	WHERE vls.KtypeId IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
	AND (@KtypeIds<>'' AND KtypeId IN (SELECT TypeId FROM #Ktype) OR @KtypeIds='')
	--AND (@KtypeIds<>'' AND ','+@KtypeIds+',' LIKE '%,'+KtypeId+',%' OR @KtypeIds='') --参数范围	
	AND vls.PtypeId LIKE @innerPtypeId+'%'
	AND @DisplayActual=1 --查询启用才显示		
	
	--UNION ALL
	--受托,委托
	INSERT INTO #cte
	SELECT PtypeId,0,0,0
	,0,0
	,ABS(SUM(wtst.wtf))-ABS(SUM(wtst.wtj))-ABS(SUM(wtst.wtt))
	,ABS(SUM(wtst.stf))-ABS(SUM(wtst.stj))-ABS(SUM(wtst.stt)),
	Iscombined ,ItemID
	FROM 
	(
		SELECT PtypeId
		,CASE WHEN billtype=140 THEN qty ELSE 0 END AS wtf
		,CASE WHEN BillType=141 THEN qty ELSE 0 END AS wtj
		,CASE WHEN Billtype=142 THEN qty ELSE 0 END AS wtt
		,CASE WHEN BillType=144 THEN qty ELSE 0 END AS stf
		,CASE WHEN BillType=145 THEN qty ELSE 0 END AS stj
		,CASE WHEN billType=146 THEN qty ELSE 0 END AS stt
		,Iscombined,ItemID
		FROM InOutStockTable
		WHERE Audited=1 AND KtypeId='10000'
		AND BillType IN (140,141,142,144,145,146)
		AND STypeID IN (SELECT TypeId FROM #BTType) 
		AND PtypeId LIKE @innerPtypeId+'%'
		
		UNION ALL 
		SELECT PTypeID
		,CASE WHEN type=140 THEN qty ELSE 0 END AS wtf,0,0
		,CASE WHEN type=144 THEN qty ELSE 0 END AS stf,0,0
		,'',''
		FROM dbo.IniCommissionStock a 
		WHERE a.type IN (140,144)
		AND a.KtypeId='10000'
		AND a.STypeID IN (SELECT TypeId FROM #BTType)				
		AND a.PtypeId LIKE @innerPtypeId+'%'
	) as wtst
	WHERE @DisplayActual=1 --查询启用才显示
	GROUP BY wtst.Ptypeid,Iscombined ,ItemID



	--临时表
	CREATE TABLE #t(PtypeId VARCHAR(50),qty  NUMERIC(24, 10) ,qty1  NUMERIC(24, 10) ,nqty  NUMERIC(24, 10) ,price  NUMERIC(24, 10) ,total  NUMERIC(24, 10) 
	,lendqty  NUMERIC(24, 10) ,borrowqty  NUMERIC(24, 10) ,wtqty  NUMERIC(24, 10) ,stqty  NUMERIC(24, 10),Iscombined INT,ItemID INT )
	CREATE CLUSTERED INDEX #t_p ON #t(ptypeid);
	
    INSERT  INTO #t
            SELECT  w.PtypeId ,
                    SUM(qty) AS qty ,
                    SUM(ISNULL(qty, 0.0) / ISNULL(U.rate, 1.0)) AS qty1 ,
                    SUM(nqty) AS nqty ,
                     CAST(SUM(total) AS NUMERIC(24,10)) / CASE WHEN SUM(qty) = 0 THEN 1
                                      ELSE CAST(SUM(qty) AS NUMERIC(24,10))
                                 END AS price ,
                    SUM(total) AS total ,
                    SUM(w.lend) AS lendqty ,
                    SUM(w.borrow) AS borrowqty ,
                    SUM(wt) AS wtqty ,
                    SUM(st) AS stqty ,
                    Iscombined ,
                    ItemID
            FROM    #cte w
                    INNER JOIN dbo.ptype p ON p.typeId = w.PtypeId
                    INNER JOIN dbo.PType_Units_Ext u ON U.PtypeID = P.typeId
                                                        AND U.UnitsId = P.StockUnitId
                    INNER JOIN dbo.PType_Units v ON v.UnitsId = u.UnitsId
            GROUP BY w.PtypeId ,
                    Iscombined ,
                    ItemID

	-- 不显示借欠受托,委托情况
	SELECT b.typeid,b.FullName,b.UserCode,b.sonnum,b.leveal,b.DELETED,b.entrycode,b.ParId
		,ISNULL(a.qty,0) AS Qty --数量
		,ISNULL(bu.fullname,'') AS baseunitfullname --基本单位
		,ISNULL(a.Nqty,0) AS NQty --浮动数量
		,ISNULL(ku.rate,1) AS stockUnitRate -- 库存单位换算率
		,ISNULL(a.qty1,0) KQty --库存数量
		,ISNULL(ku.fullname,'') AS stockunitfullname --库存单位
		,ISNULL(asu.fullname,'') AS assistantfullname --辅助单位
		,ISNULL(CASE @PriceType 
			WHEN 0 THEN a.price 
			WHEN 1 THEN pr.PreSalePrice1
			WHEN 2 THEN pr.PreSalePrice2
			WHEN 3 THEN pr.PreSalePrice3
			WHEN 4 THEN pr.PreSalePrice4
			WHEN 5 THEN pr.PreSalePrice5
			WHEN 6 THEN pr.PreSalePrice6
			WHEN 7 THEN pr.PreSalePrice7
			WHEN 8 THEN pr.PreSalePrice8
			WHEN 9 THEN pr.PreSalePrice9
			WHEN 10 THEN pr.PreSalePrice10
			WHEN 11 THEN pr.PreBuyPrice1
			WHEN 12 THEN pr.PreBuyPrice2
			WHEN 13 THEN pr.PreBuyPrice3
			WHEN 14 THEN pr.PreBuyPrice4
			WHEN 15 THEN pr.PreBuyPrice5
			WHEN 16 THEN pr.RetailPrice 
			WHEN 17 THEN pr.TopSalePrice
			WHEN 18 THEN pr.LowSalePrice
			WHEN 19 THEN pr.TopBuyPrice 
		END,0) AS price
		,ISNULL(ROUND(CASE @PriceType 
			WHEN 0 THEN ISNULL(a.total,0)
			WHEN 1 THEN pr.PreSalePrice1*ISNULL(a.Qty,0)
			WHEN 2 THEN pr.PreSalePrice2*ISNULL(a.Qty,0)
			WHEN 3 THEN pr.PreSalePrice3*ISNULL(a.Qty,0)
			WHEN 4 THEN pr.PreSalePrice4*ISNULL(a.Qty,0)
			WHEN 5 THEN pr.PreSalePrice5*ISNULL(a.Qty,0)
			WHEN 6 THEN pr.PreSalePrice6*ISNULL(a.Qty,0)
			WHEN 7 THEN pr.PreSalePrice7*ISNULL(a.Qty,0)
			WHEN 8 THEN pr.PreSalePrice8*ISNULL(a.Qty,0)
			WHEN 9 THEN pr.PreSalePrice9*ISNULL(a.Qty,0)
			WHEN 10 THEN pr.PreSalePrice10*ISNULL(a.Qty,0)
			WHEN 11 THEN pr.PreBuyPrice1*ISNULL(a.Qty,0)
			WHEN 12 THEN pr.PreBuyPrice2*ISNULL(a.Qty,0)
			WHEN 13 THEN pr.PreBuyPrice3*ISNULL(a.Qty,0)
			WHEN 14 THEN pr.PreBuyPrice4*ISNULL(a.Qty,0)
			WHEN 15 THEN pr.PreBuyPrice5*ISNULL(a.Qty,0)
			WHEN 16 THEN pr.RetailPrice	*ISNULL(a.Qty,0)
			WHEN 17 THEN pr.TopSalePrice*ISNULL(a.Qty,0)
			WHEN 18 THEN pr.LowSalePrice*ISNULL(a.Qty,0)
			WHEN 19 THEN pr.TopBuyPrice	*ISNULL(a.Qty,0)
			
		END,2),0) AS total
		--显示实际的
		,ISNULL(a.lendqty,0) AS LendQty
		,ISNULL(a.borrowqty,0) AS BorrowQty
		,ISNULL(a.wtqty,0) AS WnQty
		,ISNULL(a.stqty,0) AS SnQty
		,CASE WHEN @DisplayActual=1 THEN ISNULL(a.qty-a.lendqty+a.borrowqty,0) ELSE 0 END AS sjczqty --实际库存
		,CASE WHEN @DisplayActual=1 THEN ISNULL(a.qty-a.stqty+a.wtqty,0) ELSE 0 END AS sjyyqty --实际拥有
		,g.FullName btypefullname,
		CASE WHEN IfSerial=1 THEN '强制' ELSE '-' END AS IfSerial,
	 customassist=dbo.F_GetCustomAssist(b.typeid,ISNULL(a.qty,0)),
	ee.fullname AS ifullname
	FROM #t a
		RIGHT JOIN dbo.ptype b  ON b.typeId=a.PtypeId
			AND (@DisplayStop=0 AND b.deleted=0 OR @DisplayStop=1) --是否显示停用商品
			AND b.typeId IN (SELECT typeid FROM dbo.F_GetManPType(@OperatorID))
			AND (@sonnum=0 AND b.typeId=@ParId OR @sonnum<>0 AND b.typeId LIKE @Parid+'%' AND b.sonnum=0)
		
		JOIN dbo.PType_Price pr ON b.typeid=pr.PTypeID
		LEFT JOIN QP_PType_Ext e ON b.typeid= e.ptypeid
		LEFT JOIN btype g ON g.typeId=e.BTypeID
		LEFT JOIN (
			SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
				JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
				WHERE u.PtypeID LIKE @innerPtypeId+'%'
		) ku ON b.typeId=ku.PtypeID AND b.StockUnitId=ku.UnitsId
		LEFT JOIN (
			SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
				JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
				WHERE u.PtypeID LIKE @innerPtypeId+'%'
		) bu ON b.typeId=bu.PtypeID AND b.baseUnitId=bu.UnitsId
		LEFT JOIN (
			SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
				JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
				WHERE u.PtypeID LIKE @innerPtypeId+'%'
		) asu ON b.typeid=asu.PtypeID AND b.AssistantUnitId=asu.UnitsId
		LEFT JOIN dbo.vWeb_ItemIDByIsCombined ee ON (a.Iscombined=ee.iscombined AND ee.id=a.ItemID )
	WHERE (@DisplayStop=0 AND b.deleted=0 OR @DisplayStop=1) --是否显示停用商品
	AND b.typeId IN (SELECT typeid FROM dbo.F_GetManPType(@OperatorID))
	AND (@sonnum=0 AND b.typeId=@ParId OR @sonnum<>0 AND b.typeId LIKE @Parid+'%' AND b.sonnum=0)

	AND b.FullName LIKE '%'+@FilterPtypeFullName+'%'
	AND b.UserCode LIKE '%'+@FilterPtypeUserCode+'%'
	AND b.EntryCode LIKE '%'+@FilterPtypeEntryCode+'%'
	AND b.Area LIKE '%'+@FilterPtypeArea+'%'
	AND b.Type LIKE '%'+@Type+'%'
	AND b.Standard LIKE '%'+@Standard+'%'
	AND (@DisplayZero=0 AND (
				ISNULL(a.qty,0)<>0 
				OR CASE WHEN @DisplayActual=1 THEN ISNULL(a.qty-a.lendqty+a.borrowqty,0) ELSE 0 END<>0
				OR CASE WHEN @DisplayActual=1 THEN ISNULL(a.qty-a.stqty+a.wtqty,0) ELSE 0 END<>0
				)
			OR @DisplayZero=1)
	AND b.typeId NOT IN (SELECT typeid FROM ptype WHERE IsService=1) --去掉服务类商品
	ORDER BY b.usercode
	
	DROP TABLE #KStype;
	DROP TABLE #BTType;
	DROP TABLE #KType;
	DROP TABLE #T;
	DROP TABLE #goods,#inigoods;
	DROP TABLE #cte;
END
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_NotePadList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_NotePadList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：王刚
	日期：2011-7-21
	描述：查询记事本
-------------------------------------------*/
CREATE PROCEDURE Web_NotePadList
(
	@CreateTime1	VARCHAR(MAX),
	@AlertTime1		VARCHAR(MAX),
	@CreateTime2	VARCHAR(MAX),
	@AlertTime2		VARCHAR(MAX),
	@Key			VARCHAR(MAX),
	@Flag			INT,			----0表示待处理，1表示完成	,2代表全部
	@OperatorID		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'SELECT	ID,
					CreateTime,
					AlertTime,
					CASE	WHEN LEN(Content) > 30
							THEN LEFT(REPLACE(Content, CHAR(13), '' ''),30) + ''......''
							ELSE REPLACE(Content, CHAR(13), '' '') 
					END AS content,	 					
					CASE Flag WHEN 0 THEN ''待处理'' ELSE ''完成'' END AS Flag ,
					UserId,
					Importance
			FROM	NotePad
			WHERE 1 = 1'
																						
IF @Flag <> -1
BEGIN
	IF @CreateTime1 <> ''
		SET @SQL += 'AND CONVERT(DATE,CreateTime) >= '+CHAR(39)+@CreateTime1+CHAR(39)+''
	IF @CreateTime2 <>''
		SET @SQL += 'AND CONVERT(DATE,CreateTime) <= '+CHAR(39)+@CreateTime2+CHAR(39)+''
	IF @AlertTime1 <>''
		SET @SQL += 'AND CONVERT(DATE,AlertTime) >= '+CHAR(39)+@AlertTime1+CHAR(39)+''
	IF @AlertTime2 <>''
		SET @SQL += 'AND CONVERT(DATE,AlertTime) <= '+CHAR(39)+@AlertTime2+CHAR(39)+''	
END

IF @Flag = 1
	SET @SQL += 'AND Flag = 1'
	
IF @Flag = 0
	SET @SQL += 'AND Flag = 0'
	
IF @Key <> ''
	SET @SQL = @SQL + @Key
		
SET @SQL = @SQL + '
					AND	UserId = '+CHAR(39)+@OperatorID+CHAR(39)+'
					ORDER BY Importance ASC, AlertTime DESC'


--PRINT(@SQL)
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_nVipCardCzQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_nVipCardCzQuery]
GO















/*
	作者：谢吉康
	日期：2009-01-06
	描述：VIP卡充值查询
*/
CREATE PROCEDURE Web_nVipCardCzQuery
(
	@OperatorID			varchar(100),
	@VTypeId			varchar(8000),
	@ATypeId			varchar(8000),
	@ETypeId			varchar(8000),
	@StartDate			varchar(20),
	@EndDate			varchar(20)
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--职员：
CREATE TABLE #GetSelETypeId(TypeId varchar(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT TypeId FROM F_BaseGetAllBaseTypeId(@ETypeId,3)

--账户：
CREATE TABLE #GetSelATypeId(TypeId varchar(100))
INSERT INTO #GetSelATypeId(TypeId) SELECT TypeId FROM F_BaseGetAllBaseTypeId(@ATypeId,5)


DECLARE @SQL varchar(8000)

IF @ATypeId = '0000'
	SEt @ATypeId = '%'

SET @SQL = '
			SELECT	A.BillDate,
					N.VipCardCode,
					N.BName,
					A.aMoney,
					AP.TypeId AS ATypeId,
					E.FullName AS EFullName,
					A.Comment
			FROM 	nVipAddMoney A,
					nVipCardSign N,
					AType AP,
					Employee E
			WHERE	A.CardId = N.VipCardId
					AND A.ATypeId = AP.TypeId
					AND E.TypeId = A.ETypeId
					AND A.BillDate>='+char(39)+@StartDate+char(39)+'
					AND A.BillDate<='+char(39)+@EndDate+char(39)+'
					AND E.TypeId IN (SELECT * FROM #GetSelETypeId)
					AND AP.TypeId IN (SELECT * FROM #GetSelATypeId)
					AND E.TypeId IN (SELECT * FROM F_BaseGetManDetailEType('+char(39)+@OperatorID+char(39)+'))	
					AND AP.TypeId IN (SELECT * FROM F_BaseGetManDetailAType('+char(39)+@OperatorID+char(39)+'))	
					AND N.VipCardCode LIKE '+char(39)+'%'+@VTypeId+'%'+char(39)+'
			ORDER BY A.BillDate DESC,N.VipCardCode '

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetSelATypeId,#GetSelETypeId














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_nVipcardExtend]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_nVipcardExtend]
GO




/*
	描述:查询Vip卡的发卡情况
	作者:谢吉康
	日期:2010-01-09
*/
CREATE              PROCEDURE Web_nVipcardExtend(


	@chvOperatorId		varchar(100),				--操作员Id
	@VipCardCode		varchar(50),				--Vip卡号
	@Bname				varchar(50),				--Vip卡持有者
	@CreateDate			varchar(20),				--签发日期
	@EndDate			varchar(20),				--截止日期
	@EFullName			varchar(256),				--往来单位
	@Cardset			char(10),					--Vip卡状态
	@Comment			varchar(300),				--Vip卡状态
	@chvSortFild		varchar(50),				--排序字段
	@chvSortType		varchar(10)					--排序方式
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvOperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @chvOperatorId,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL varchar(8000)

IF 	@CreateDate = ''
	--SELECT @dtmSignDate = CONVERT(VARCHAR(10),StartDate,120) FROM MonthProc WHERE Period = 1
	SELECT @CreateDate = '1900-01-01'
IF 	@EndDate = ''
    SET @EndDate = '9200-01-01'

IF @chvSortFild = ''
	SET @chvSortFild = 'A.VipCardCode'

IF @chvSortType = ''
	SET @chvSortType = 'ASC'

SELECT @SQL = '
	SELECT	A.VipCardId,
			A.VipCardCode As VipCardCode,
			A.Bname As Bname,
			A.CreateDate As CreateDate,
			A.EndDate AS EndDate,
			A.deleted AS deleted,
			CASE 
				WHEN A.deleted = 0 THEN ''启用''
				WHEN A.deleted = 2 THEN ''停用''
				WHEN A.deleted = 3 THEN ''挂失''
				ELSE ''启用''
			END AS zt,				
			A.Comment AS Comment,
			B.TypeName AS TypeName,
			B.ifjf,
			CASE
				WHEN B.ifJF = ''1'' THEN ''参与积分''
				ELSE ''不参与积分''
			END AS sfjf,
			B.DiscountType,
			B.VipCardTypeid,
			C.FullName as Ename,
			CASE
				WHEN ISNULL(IsCz,'''')=''1'' THEN ''是''
				ELSE ''否''
			END AS IsCz,
			A.qCczMoney,
			A.lJczMoney,
			A.cZyeMoney,
			CASE
				WHEN A.bsex=1 THEN ''男''
				WHEN A.bsex=0 THEN ''女''
				ELSE ''男''
			END AS Sex,
			CASE
				WHEN A.bsex=1 THEN 1
				WHEN A.bsex=0 THEN 0
				ELSE 0
			END AS bsex,
			A.bbirthday,
			A.btel,
			A.baddr,
			a.bpostcode,
			a.btrade,
			a.bidcard,
			a.beginmoney,
			a.begincent,
			a.qcczmoney,a.ljczmoney,a.czyemoney,a.pword,a.canwashtimes,a.iswashtimes
	FROM 	nVipCardSign A,
			nVipCardSet  B,
			Employee		C
	WHERE 	A.VipCardTypeId = B.VipCardTypeId
			AND A.ETypeID = C.TypeID
			AND A.VipCardCode LIKE '+CHAR(39)+'%' + @VipCardCode + '%' + CHAR(39)+'
			AND A.Bname LIKE '+CHAR(39)+'%'+ @BName + '%'+CHAR(39)+'
			AND A.CreateDate >= '+CHAR(39)+@CreateDate+CHAR(39)+'
			AND A.CreateDate <= '+CHAR(39)+@EndDate+CHAR(39)+''
				
IF len(LTRIM(RTRIM(@Cardset))) <> 0   				
	SET @SQL = @SQL + 'AND A.deleted = '+CHAR(39)+@Cardset+CHAR(39)+''
				
SET @SQL = @SQL +'
			AND A.Comment LIKE '+CHAR(39)+'%'+ @Comment +'%'+CHAR(39)+'
			AND C.FullName LIKE '+CHAR(39)+'%' + @EFullName + '%'+CHAR(39)+'
			AND (C.TypeID IN (SELECT * FROM F_BaseGetManDetailEType('+char(39)+@chvOperatorID+char(39)+'))	)
			AND A.deleted<>''1''
	ORDER BY '+' '+@chvSortFild+' '+@chvSortType

	--PRINT(@SQL)
	EXEC(@SQL)






































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_nVipCardset]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_nVipCardset]
GO

/*
	作者:谢吉康
	日期:2004-06-04
	描述:VIP卡类型查询
*/
CREATE  PROCEDURE Web_nVipCardset
--@encode$--
AS
SELECT	* FROM nVipCardSet WHERE deleted<>'1' ORDER BY TypeName 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_nVipGoodsSign]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_nVipGoodsSign]
GO



/****
write:haiquan
time:2007-11-20
content:商品vip信息
***/

CREATE                PROCEDURE Web_nVipGoodsSign
(
	@OperatorID 	varchar(50),
	@ParId 			varchar(50)='',
	@usercode 		varchar(50)='',
	@fullname 		varchar(66)='',
	@queryMode 		int=1
)

--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL varchar(8000),@strSQL varchar(8000)
DECLARE @PTypeid varchar(50)
SELECT @SQL=''

IF @parid='00000'
     SET @PTypeid=''
ELSE
   SET @PTypeid=@parid

----------------创建Vip临时表、VipGoods临时表 (陈强:敏捷4636 性能问题)----------------------------	
CREATE TABLE #VipDisTable1
(
	PTypeId			VARCHAR(50),
	VipDisCount1	numeric(18,4),
	VipDisCount2	numeric(18,4),
	VipDisCount3	numeric(18,4),
	VipDisCount4	numeric(18,4),
	VipPrice1		numeric(18,4),
	VipPrice2		numeric(18,4),
	VipPrice3		numeric(18,4),
	VipPrice4		numeric(18,4),
	VipPrice5		numeric(18,4),
	unitid			int
)
CREATE NONCLUSTERED INDEX IXU_VipDisTable1 ON #VipDisTable1(ptypeid)

INSERT INTO #VipDisTable1 
SELECT  n.PTypeId ,
		n.VipDisCount1 ,
		n.VipDisCount2 ,
		n.VipDisCount3 ,
		n.VipDisCount4 ,
		n.VipPrice1 ,
		n.VipPrice2 ,
		n.VipPrice3 ,
		n.VipPrice4 ,
		n.VipPrice5 ,
		n.unitid 
FROM    nVipGoodsSign n  
LEFT JOIN nVipJfset J ON n.JfId = J.ID 
WHERE   n.ptypeid LIKE @PTypeid + '%'



CREATE TABLE #VipGoodsTable
(
	PTypeId		VARCHAR(50),
	Id			INT,
	Title		VARCHAR(MAX)
)
CREATE NONCLUSTERED INDEX IXU_GoodsTable ON #VipGoodsTable(ptypeid)


INSERT INTO #VipGoodsTable
SELECT  n.pTYPEID ,
		n.JfId AS Id ,
        CASE n.JfId WHEN 0 THEN '按卡类型'
                     WHEN 99999 THEN '不积分'
                     WHEN -1 THEN '不变'
        ELSE J.Title END AS Title 
FROM    nVipGoodsSign n
LEFT JOIN nVipJfset J ON n.JfId = J.ID
WHERE   n.ptypeid LIKE @PTypeid + '%'

-----------------------------------------END-------------------------------------------------

SET @strSQL='
		 SELECT DISTINCT p.Typeid,
				p.UserCode,
				p.FullName,
				p.EnTryCode,
				p.Standard,
				Type,
				Area,
				Unit1,
				isnull(VipDiscount1,-1) AS VipDiscount1,
				isnull(VipDiscount2,-1) AS VipDiscount2,
				isnull(VipDiscount3,-1) AS VipDiscount3,
				isnull(VipDiscount4,-1) AS VipDiscount4,
				isnull(VipPrice1,-1) AS VipPrice1,
				isnull(VipPrice2,-1) AS VipPrice2,
				isnull(VipPrice3,-1) AS VipPrice3,
				isnull(VipPrice4,-1) AS VipPrice4,
				isnull(VipPrice5,-1) AS VipPrice5,
				Case WHEN ISNULL(n.ID,99999)=99999 THEN 99999 ELSE n.ID END AS ID,
				Case WHEN ISNULL(n.Title,'''')='''' THEN '''' ELSE ISNULL(n.Title,'''') END AS Title,
				e.unitsid as unitid,
				case when P.SonNum<>0 then 1 else e.isdefaultunit end as isdefaultunit,
				case when P.SonNum<>0 then '''' else u.fullname end as unitname
		FROM 	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') P 
		left join ptype_units_ext e on p.typeid =e.ptypeid and e.ratetype=0 and p.sonnum=0
		left join ptype_units u on e.unitsid =u.unitsid
		LEFT JOIN #VipDisTable1 B ON P.TypeId = B.PTypeId and e.unitsid=b.unitid
		LEFT JOIN #VipGoodsTable N on p.typeid = n.ptypeid
		Where 	P.sonnum=0'
 				

IF @PTypeid<>''
	SET @strSQL=@strSQL+' AND p.typeid LIKE '''+@PTypeid+'%'''
IF @usercode<>''
	SET @strSQL=@strSQL+' AND p.usercode LIKE ''%'+@usercode+'%'''
IF @fullname<>''
	SET @strSQL=@strSQL+' AND p.fullname LIKE ''%'+@fullname+'%'''
	
SET @strSQL=@strSQL+@SQL+' Order by P.usercode '

--PRINT(@strSQL)
EXEC(@strSQL) 
DROP TABLE #VipDisTable1,#VipGoodsTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_nVipGoodsSignList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_nVipGoodsSignList]
GO

/****
write:haiquan
time:2007-11-20
content:商品vip信息
***/
CREATE         PROCEDURE Web_nVipGoodsSignList
(
	@OperatorID 	varchar(50),
	@ptypeid 		varchar(50)='',
	@usercode 		varchar(50)='',
	@fullname 		varchar(66)=''
)

--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 	varchar(max)

SELECT @SQL=''

BEGIN
	DECLARE @SonNum 	int,			--叶子节点数
			@PTypeMxId	varchar(50),
	        @PTypeIDmx  varchar(50),
	        @SqlWhere	VARCHAR(8000)

	IF @ptypeid = '00000'
		SELECT @PTypeIDmx = '%'
	ELSE
		SELECT @PTypeIDmx = @ptypeid


	SELECT @SonNum = SonNum FROM PType WHERE TypeID = @ptypeid
	
----------------创建Vip临时表、VipGoods临时表 (陈强:敏捷4636 性能问题)----------------------------		
CREATE TABLE #VipDisTable1
(
	PTypeId	VARCHAR(50),
	VipDisCount1	numeric(18,4),
	VipDisCount2	numeric(18,4),
	VipDisCount3	numeric(18,4),
	VipDisCount4	numeric(18,4),
	VipPrice1	numeric(18,4),
	VipPrice2	numeric(18,4),
	VipPrice3	numeric(18,4),
	VipPrice4	numeric(18,4),
	VipPrice5	numeric(18,4),
	unitid int
)
CREATE NONCLUSTERED INDEX IXU_VipDisTable1 ON #VipDisTable1(ptypeid)

INSERT INTO #VipDisTable1 
SELECT  n.PTypeId ,
		n.VipDisCount1 ,
		n.VipDisCount2 ,
		n.VipDisCount3 ,
		n.VipDisCount4 ,
		n.VipPrice1 ,
		n.VipPrice2 ,
		n.VipPrice3 
		,n.VipPrice4 ,
		n.VipPrice5 ,
		n.unitid 
FROM    nVipGoodsSign n  
LEFT JOIN nVipJfset J ON n.JfId = J.ID 
WHERE   n.ptypeid LIKE CASE WHEN @ptypeid = '00000' THEN '' ELSE @ptypeid END + '%'

CREATE TABLE #VipGoodsTable
(
	PTypeId	 VARCHAR(50),
	Id INT,
	Title VARCHAR(256)
)
CREATE NONCLUSTERED INDEX IXU_GoodsTable ON #VipGoodsTable(ptypeid)

INSERT INTO #VipGoodsTable
SELECT  n.pTYPEID ,n.JfId AS Id ,
         CASE n.JfId WHEN 0 THEN '按卡类型'
                     WHEN 99999 THEN '不积分'
                     WHEN -1 THEN '不变'
         ELSE J.Title END AS Title 
FROM    nVipGoodsSign n
LEFT JOIN nVipJfset J ON n.JfId = J.ID
WHERE   n.ptypeid LIKE CASE WHEN @ptypeid = '00000' THEN '' ELSE @ptypeid END + '%'


--------------------------------------END-----------------------------------------------------
	
--select * from nVipGoodsSign
	SET @SQL='SELECT DISTINCT	
							P.TypeId,
							P.SonNum,
							P.UserCode,
							P.FullName,
							P.EntryCode,
							P.Standard,
							P.Type,
							P.Area,
							P.Unit1,
							P.Unit2,
							P.UnitRate2,
							isnull(B.VipDisCount1,-1) AS VipDisCount1,
							isnull(B.VipDisCount2,-1) AS VipDisCount2,
							isnull(B.VipDisCount3,-1) AS VipDisCount3,
							isnull(B.VipDisCount4,-1) AS VipDisCount4,
							isnull(B.VipPrice1,-1) AS VipPrice1,
							isnull(B.VipPrice2,-1) AS VipPrice2,
							isnull(B.VipPrice3,-1) AS VipPrice3,
							isnull(B.VipPrice4,-1) AS VipPrice4,
							isnull(B.VipPrice5,-1) AS VipPrice5,
							Case WHEN ISNULL(N.ID,99999)=99999 THEN 99999 ELSE N.ID END AS ID,
							Case WHEN ISNULL(N.Title,'''')='''' THEN '''' ELSE ISNULL(N.Title,'''') END AS Title,
							e.unitsid as unitid,
							case when P.SonNum<>0 then 1 else e.isdefaultunit end as isdefaultunit,
							case when P.SonNum<>0 then '''' else u.fullname end as unitname
					FROM	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+') P
					left join ptype_units_ext e on p.typeid =e.ptypeid and e.ratetype=0 and p.sonnum=0
					left join ptype_units u on e.unitsid =u.unitsid
					LEFT JOIN #VipDisTable1 B ON  P.TypeId = B.PTypeId and e.unitsid=b.unitid
					left join #VipGoodsTable N on p.typeid = n.pTYPEID'
	
	IF @PTypeIDmx<>''
		SET @SqlWhere=' AND  P.TypeId LIKE '+char(39)+@PTypeIDmx+'%'+char(39)+''
	IF @usercode<>''
		SET @SqlWhere=' AND P.UserCode LIKE '+char(39)+'%'+@usercode+'%'+char(39)+''
	IF @FullName<>''
		SET @SqlWhere=' AND P.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+''		
	IF @SonNum > 0
		SET @SQL = @SQL + ' WHERE p.ParID = '+CHAR(39)+@ptypeid+CHAR(39)
	ELSE
		SET @SQL = @SQL + ' WHERE p.TypeID = '+CHAR(39)+@ptypeid+CHAR(39)
	
	SET @SQL = @SQL +@SqlWhere+ ' ORDER BY P.usercode '

	--PRINT(@SQL)
	EXEC(@SQL) 
	DROP TABLE #VipDisTable1,#VipGoodsTable
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





set ANSI_NULLS ON
go
set QUOTED_IDENTIFIER ON
go


-- =============================================
-- Author:	毛欣蓉
-- ALTER  date: 2010-05-13
-- Description:	发表文章
-- =============================================

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_AddArticle]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_AddArticle]
GO


CREATE PROCEDURE [dbo].[Web_OA_AddArticle]
	-- Add the parameters for the stored procedure here
(
	@isvote int=0, --是否有投票，默认为没有
	
	@id int,
	@catalogid varchar(30), --栏目id
	@title varchar(100),  
	@content varchar(MAX),
	@etypeid_creatortypeid varchar(50),
	@etypeid_modifiertypeid varchar(50),
	@emotionimg varchar(40),
	@htmlcode int,
	@experience int,

--下面是投票相关的

	@votename varchar(50)='',
	@isrefuserepeat int=0,
	@votemode int=0,
	@vote_s1 varchar(50)='',
	@vote_s2 varchar(50)='',
	@vote_s3 varchar(50)='',
	@vote_s4 varchar(50)='',
	@vote_s5 varchar(50)='',
	@vote_s6 varchar(50)='',
	@vote_s7 varchar(50)='',
	@vote_s8 varchar(50)='',
	@vote_s9 varchar(50)='',
	@vote_s10 varchar(50)='',
	@voteenddatetime datetime=''
)
--@encode$--
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
--	DECLARE @id int
--	insert into OA_PublicDB (title) values (@title)
--	SET @id=(select top 1 [ID] from OA_PublicDB where title=@title)
		
		UPDATE OA_PublicDB SET 
			CatalogID=@catalogid,
			Title=@title,
			Content=@content,
			CreateDate=GETDATE(),
			ModifyDate=GETDATE(),
			ETypeID_CreatorTypeID=@etypeid_creatortypeid,
			ETypeID_ModifierTypeID=@etypeid_modifiertypeid,
			ClickNumber=0,
			ReplyNumber=0,
			EmotionImg=@emotionimg,
			HtmlCode=@htmlcode,
			ParentID=0,
			Docking=0,
			Hidden=0,
			SortOrder=0
		WHERE [ID]=@id
	IF @isvote=1
		BEGIN
		UPDATE OA_PublicDB SET
			IsVote = 1,
			VoteName=@votename,
			IsRefuseRepeat=@isrefuserepeat,
			VoteMode=@votemode,
			Vote_S1=@vote_s1,
			Vote_S2=@vote_s2,
			Vote_S3=@vote_s3,
			Vote_S4=@vote_s4,
			Vote_S5=@vote_s5,
			Vote_S6=@vote_s6,
			Vote_S7=@vote_s7,
			Vote_S8=@vote_s8,
			Vote_S9=@vote_s9,
			Vote_S10=@vote_s10,
			VoteEndDateTime=@voteenddatetime,
			IsEnableVote=1,
			IsEnableView=1
		WHERE [ID]=@id
			END

----------用户发表文章数加1----------------

	DECLARE @etypeid_usertypeid varchar(50)
	SET @etypeid_usertypeid=(SELECT top 1 [ETypeID_UserTypeID] FROM OA_UserInformation WHERE [ETypeID_UserTypeID]=@etypeid_creatortypeid)

	IF  ISNULL(@etypeid_usertypeid, '0') = '0'  --没有记录
		BEGIN
		INSERT INTO OA_UserInformation ([ETypeID_UserTypeID],[Experience],[Add],[Reply]) 
 			VALUES(@etypeid_creatortypeid,@experience,1,0)
		END
	ELSE
		BEGIN
			UPDATE OA_UserInformation SET 
				[Add] = [Add] + 1, 
				[Experience] =( [Experience]+@experience)
			WHERE [ETypeID_UserTypeID] =@etypeid_creatortypeid
		END
			
	------------------作者默认订阅此文章--------

	INSERT INTO OA_Subscibe ([ArticleID],[ETypeID_SubsciberTypeID]) 
		VALUES(@id,@etypeid_creatortypeid)
return @id
END






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_CheckNewMsg]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_CheckNewMsg]
GO












CREATE PROCEDURE Web_OA_CheckNewMsg
(
	@chvUserTypeID	VARCHAR(50),
	@intMAXIDLESECOND	INT
)
--@encode$--
AS

SET NOCOUNT ON

--获得最新消息
SELECT TOP 100 [ID],[MessageType] FROM OA_Message WITH (NOLOCK) WHERE [ETypeID_CreatorTypeID] = @chvUserTypeID
		AND [IsRead] = 0 AND [ETypeID_ReceiverTypeID] = @chvUserTypeID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_ColMove]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_ColMove]
GO













/*
搬移规则：
源栏目必须是叶子栏目，即该栏目在OA_Catalog表中的SonNumber字段必须为0
目标栏目理论上应该是非叶子栏目，即该栏目在OA_Catalog表中的SonNumber字段不能为0。但是如果是叶子栏目的情况下，
也能进行搬移，同时将原来属于该叶子栏目的所有文章、附件等信息转入该栏目下的第1个栏目中。
例如：001002001 原来是一个叫“业余生活”的叶子栏目，该栏目下有很多文章
现在，将另外一个栏目"公司内部业余生活"搬移到该栏目下，
则生成001002001001栏目，并且原来属于"业余生活"的文章的CatalogID全部变为001002001001
*/
CREATE PROCEDURE Web_OA_ColMove
(
	@chvSourceTypeID		VARCHAR(30),
	@chvDestinationTypeID		VARCHAR(30)
)
--@encode$--
AS
--如果不存在TypeI为@SourceTypeID的栏目，退出程序
IF NOT EXISTS(SELECT * FROM OA_Catalog WHERE TypeID = @chvSourceTypeID)
	RETURN 0
--如果不存在TypeI为@chvDestionationTypeID的栏目，退出程序
IF NOT EXISTS(SELECT * FROM OA_Catalog WHERE TypeID = @chvDestinationTypeID)
	RETURN 0
--如果源栏目和目标栏目相同，退出程序
IF @chvSourceTypeID = @chvDestinationTypeID
	RETURN 0
--如果源栏目是非叶子栏目，则退出程序
DECLARE @intSonNumber INT
SELECT @intSonNumber = (SELECT [SonNumber] FROM OA_Catalog WHERE [TypeID] = @chvSourceTypeID)
IF @intSonNumber <> 0
	RETURN 0
--检查目标栏目是否叶子栏目
SELECT @intSonNumber = (SELECT [SonNumber] FROM OA_Catalog WHERE [TypeID] = @chvDestinationTypeID)
DECLARE @intSortOrder INT
DECLARE @chvTempTypeID		VARCHAR(30)
IF @intSonNumber <> 0
BEGIN
	--目标栏目为非叶子节点的情况
	--获得下一个栏目的排列顺序
	SELECT @intSortOrder = (SELECT ISNULL(MAX([SortOrder]),0) FROM OA_Catalog WHERE TypeID = @chvDestinationTypeID) + 1
	--生成新的栏目TypeID
	SELECT @chvTempTypeID = LTRIM(RTRIM(CAST((SELECT SONCOUNTER FROM OA_Catalog WHERE TypeID = @chvDestinationTypeID)+1 AS VARCHAR(30))))
	SELECT @chvTempTypeID = CASE LEN(@chvTempTypeID)
					WHEN 3 THEN @chvTempTypeID
					WHEN 2 THEN '0' + @chvTempTypeID
					WHEN 1 THEN '00' + @chvTempTypeID
					END
	
	SELECT @chvTempTypeID = @chvDestinationTypeID + @chvTempTypeID
	
	--修改OA_Catalog表、OA_PublicDB表、OA_Right表、OA_PersonalDesktop表中栏目TypeID等于@chvSourceTypeID的记录
	--为新生成的@chvTempTypeID值
	BEGIN TRAN tran1
	
	UPDATE OA_Catalog SET [TypeID] = @chvTempTypeID,[ParentID] = @chvDestinationTypeID,[SortOrder] = @intSortOrder WHERE [TypeID] = @chvSourceTypeID
	
	UPDATE OA_Catalog SET [SonNumber] = [SonNumber] + 1 ,[SonCounter] = [SonCounter] + 1 WHERE [TypeID] = @chvDestinationTypeID
	
	UPDATE OA_Catalog SET [SonNumber] = [SonNumber] - 1 WHERE [TypeID] = LEFT(@chvSourceTypeID,LEN(@chvSourceTypeID)-3)
	
	UPDATE OA_PublicDB SET [CatalogID] = @chvTempTypeID WHERE [CatalogID] = @chvSourceTypeID
	
	UPDATE OA_Right SET [CatalogID] = @chvTempTypeID WHERE [CatalogID] = @chvSourceTypeID
	UPDATE OA_PersonalDesktop SET [CatalogTypeID] = @chvTempTypeID WHERE [CatalogTypeID] = @chvSourceTypeID
	
	COMMIT TRAN tran1
END
ELSE
BEGIN
	--目标栏目为叶子节点的情况
	--下一个栏目的排列顺序
	SELECT @intSortOrder = 1
	--新的栏目TypeID	
	SELECT @chvTempTypeID = @chvDestinationTypeID + '001'
	IF LEN(@chvTempTypeID) > 27
		BEGIN
			RAISERROR('超出了系统允许的子栏目层数，无法搬移！',16,1)
			RETURN
		END
	--修改OA_Catalog表、OA_PublicDB表、OA_Right表中栏目TypeID等于@chvSourceTypeID的记录
	--为新生成的@chvTempTypeID值
	--同时修改原来属于@chvDestinationTypeID的文章、附件的CatalogID为新的@chvTempTypeID
	BEGIN TRAN tran1
	
	UPDATE OA_Catalog SET [TypeID] = @chvTempTypeID,[ParentID] = @chvDestinationTypeID,[SortOrder] = @intSortOrder WHERE [TypeID] = @chvSourceTypeID
	
	UPDATE OA_Catalog SET [SonNumber] = 1,[SonCounter] = 1 WHERE [TypeID] = @chvDestinationTypeID
	
	UPDATE OA_Catalog SET [SonNumber] = [SonNumber] - 1 WHERE [TypeID] = LEFT(@chvSourceTypeID,LEN(@chvSourceTypeID)-3)
	
	UPDATE OA_PublicDB SET [CatalogID] = @chvTempTypeID WHERE [CatalogID] = @chvSourceTypeID OR [CatalogID] = @chvDestinationTypeID
	
	UPDATE OA_Right SET [CatalogID] = @chvTempTypeID, [ModifyDate] = GETDATE() WHERE [CatalogID] = @chvSourceTypeID
	UPDATE OA_PersonalDesktop SET [CatalogTypeID] = @chvTempTypeID WHERE [CatalogTypeID] = @chvSourceTypeID
	DELETE FROM dbo.OA_PersonalDesktop WHERE [CatalogTypeID] = @chvDestinationTypeID
	
	COMMIT TRAN tran1
END
RETURN 1







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_ColumnAdd]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_ColumnAdd]
GO















/*
添加一个栏目
2002-6-7 Alan
*/
CREATE  PROCEDURE Web_OA_ColumnAdd
(
	@chvParentID		VARCHAR(30),			--父亲节点TypeID
	@chvName		VARCHAR(40),			--栏目名称
	@chvDescription	VARCHAR(400),			--栏目描述
	@chvFontColor		VARCHAR(10),			--字体颜色
	@chvImgFileName	VARCHAR(50),			--栏目图片
	@chvTypeID		VARCHAR(30) OUTPUT		--返回新生成的栏目的TypeID
)
--@encode$--
 AS
DECLARE @chvTempTypeID		VARCHAR(30)
DECLARE @intSortOrder		INT

if len(@chvParentID)>=27
	RETURN -103				--系统允许设置的目录层
--首先检查是否有根节点
IF NOT EXISTS(SELECT * FROM OA_Catalog)
	INSERT INTO OA_Catalog (TypeID,ParentID,[Name],[SonNumber],[SonCounter]) VALUES('001','000','全部',0,0)
--检查是否具有重名
IF EXISTS(SELECT * FROM OA_Catalog WHERE ParentID = @chvParentID AND [Name] = @chvName)
	GOTO REDUPICATE
IF NOT EXISTS(SELECT * FROM OA_Catalog WHERE TypeID = @chvParentID)		--不存在TypeID为@chvParentID的记录
	GOTO NORECORD
--获得下一个栏目的排列顺序
SELECT @intSortOrder = (SELECT ISNULL(MAX([SortOrder]),0) FROM OA_Catalog WHERE ParentID = @chvParentID) + 1
SELECT @chvTempTypeID = LTRIM(RTRIM(CAST((SELECT SONCOUNTER FROM OA_Catalog WHERE TypeID = @chvParentID)+1 AS VARCHAR(30))))
SELECT @chvTempTypeID = CASE LEN(@chvTempTypeID)
				WHEN 3 THEN @chvTempTypeID
				WHEN 2 THEN '0' + @chvTempTypeID
				WHEN 1 THEN '00' + @chvTempTypeID
				END
SELECT @chvTempTypeID = @chvParentID + @chvTempTypeID
BEGIN TRAN
--添加部门信息
INSERT INTO OA_Catalog (TypeID,ParentID,SonNumber,SonCounter,[Name],[Description],[FontColor],[ImgFileName],[SortOrder]) 
VALUES (
		@chvTempTypeID,
		@chvParentID,
		0,
		0,
		@chvName,
		@chvDescription,
		@chvFontColor,
		@chvImgFileName,
		@intSortOrder
	)
--将父亲部门的SonNumber加1
UPDATE OA_Catalog SET SonNumber = SonNumber + 1,SonCounter = SonCounter + 1 WHERE [TypeID] = @chvParentID
COMMIT TRAN
SELECT @chvTypeID = @chvTempTypeID	--返回新增部门的TypeID
RETURN 0
REDUPICATE:
	RETURN -101				--同一ParentID下具有同名的部门
NORECORD:					--没有匹配该ParentID的部门
	RETURN -102









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_DeleteArticle]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_DeleteArticle]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2011.12.20
	描述：删除文章
*/
CREATE PROCEDURE Web_OA_DeleteArticle
(
	@pid int,--文章父id
	@articleid varchar(50), -- 文章id
	@fileid varchar(50),--附件id
	@BBS_ADD_EXP int, --发贴经验值
	@BBS_REPLY_EXP int --回帖经验值
)
--@encode$--
AS
SET NOCOUNT ON

-------------------------层叠控制-----------------------------
	DECLARE	@authorID varchar(50) --作者id
	SET @authorid = (SELECT [ETypeID_CreatorTypeID] 
					FROM OA_PublicDB WHERE [ID] = @articleid)
	IF ISNULL(@authorid, '0') = '0' --若文章已删除
		BEGIN
			RAISERROR('发生错误，该条记录已被删除!',16,1)
			Return
		END
	ELSE
		BEGIN
			DECLARE @value varchar(50)
			---查询层叠控制值
			SET @value = (SELECT ISNULL([IsCascadeCheck],0) AS [IsCascadeCheck] 
							FROM OA_Catalog 
							WHERE [TypeID] = 
								(SELECT [CatalogID] FROM OA_PublicDB WHERE [ID] = @articleid )
						  )
			---层叠控制,将此篇文章的上一篇文章的IsEnableCreatorDel设置为1
			IF @value = '1'
				BEGIN
					DECLARE @preid int
					SET @preid = (
					SELECT top 1 [id] FROM OA_PublicDB 
					WHERE [ParentID] = (SELECT [ParentID] FROM OA_PublicDB WHERE [ID] = @articleid)
							AND [ID] <> @articleid
						 OR [ID] = (SELECT [ParentID] FROM OA_PublicDB WHERE [ID] = @articleid) 
					ORDER BY [ID] DESC)
					---如果存在前文章，则设置前文章的层叠值
					IF ISNULL(@preid,'0') <> '0'
						BEGIN	
							UPDATE OA_PublicDB SET [IsEnableCreatorDel] = 1 WHERE [ID] = @preid
						END
				END
			---非层叠控制
			ELSE
				BEGIN
					DECLARE @rownum int
					SET @rownum = 
						(
						SELECT COUNT(*) FROM OA_PublicDB 
						WHERE [ID] = @articleid 
						OR [ParentID] = (SELECT [ParentID] FROM OA_PublicDB WHERE [ID] = @articleid)
						)
					IF @rownum <= 1
						BEGIN
							UPDATE OA_PublicDB SET [IsEnableCreatorDel] = 1 WHERE [ID] = (SELECT [ParentID] FROM OA_PublicDB WHERE [ID] = @articleid)
						END
				END
		END

-------------删除主文章、回复文章-----------------
	DELETE FROM OA_PublicDB 
		WHERE [ID] = @articleid 
			OR [ParentID] = @articleid

	IF @pid = 0 ---主帖
		BEGIN
			-------扣除发帖经验值和文章篇数
			UPDATE OA_UserInformation SET
				[Add] = [Add] - 1,
                [Experience] = [Experience] - @BBS_ADD_EXP
            WHERE [ETypeID_UserTypeID] = @authorID
            -------删除相关附件
            DELETE FROM OA_Attachment WHERE [ID] = @fileid
            -------删除相关订阅记录
            DELETE OA_Subscibe WHERE [ID] = @articleid
            -------删除相关投票信息
            DELETE OA_Vote_EmployeeVoteInfo WHERE [VoteID] = @articleid
        END
    ELSE  ----回复帖
		BEGIN
			-----将父亲文章的ReplyNumber减少1
			UPDATE OA_PublicDB SET [ReplyNumber]=[ReplyNumber]-1 WHERE [ID]=@pid
			-----扣除回帖经验值和回复数量
			UPDATE OA_UserInformation SET
				[Reply] = [Reply] - 1,
                [Experience] = [Experience] - @BBS_REPLY_EXP
            WHERE [ETypeID_UserTypeID] = @authorID
		END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_EmailMsgSend]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_EmailMsgSend]
GO













/**
发送邮件、消息。
*/
CREATE PROCEDURE Web_OA_EmailMsgSend
(
	@chvCatalogID			VARCHAR(30),		--栏目TypID
	@chvType			VARCHAR(20),		--类型：	Email-信件
								--		Doc-文档资料
								--		Note-记事本/便笺
	@chvSenderTypeID		VARCHAR(50),		--发送人TypeID
	@chvReceiverTypeIDList	VARCHAR(MAX),	--接收人TypeID串，以逗号分隔
	@chvTitle			VARCHAR(100),		--主题
	@chvContent			VARCHAR(8000),	--内容
	@intAttachmentID		INT			--附件ID
)
--@encode$--
AS
--初始化批量接收人TypeID字符串
DECLARE @chvTempStr VARCHAR(50)
DECLARE @nReceiverCount INT
SELECT @nReceiverCount = 0
IF RIGHT(@chvReceiverTypeIDList,1) <> CHAR(44)
	SELECT @chvReceiverTypeIDList = @chvReceiverTypeIDList + CHAR(44)	--CHAR(44) 逗号

WHILE LEN(@chvReceiverTypeIDList) >1
BEGIN
	SELECT @chvTempStr = LTRIM(RTRIM(LEFT(@chvReceiverTypeIDList,CHARINDEX(CHAR(44),@chvReceiverTypeIDList)-1)))
    SELECT @chvReceiverTypeIDList = RIGHT(@chvReceiverTypeIDList,LEN(@chvReceiverTypeIDList)-CHARINDEX(CHAR(44),@chvReceiverTypeIDList))
	
	BEGIN TRAN
	INSERT INTO OA_PrivateDB(CatalogID,Title,Content,CreateDate,ETypeID_SenderTypeID,ETypeID_ReceiverTypeID,ETypeID_CreatorTypeID,AttachmentID,IsRead,Type,Docking,SortOrder) 
	VALUES(
			@chvCatalogID,
			@chvTitle,
			@chvContent,
			GETDATE(),
			@chvSenderTypeID,
			@chvTempStr,
			@chvSenderTypeID,
			@intAttachmentID,
			0,
			@chvType,
			0,
			0
		)
	IF @chvSenderTypeID <> @chvTempStr
	INSERT INTO OA_PrivateDB(CatalogID,Title,Content,CreateDate,ETypeID_SenderTypeID,ETypeID_ReceiverTypeID,ETypeID_CreatorTypeID,AttachmentID,IsRead,Type,Docking,SortOrder) 
	VALUES(
			@chvCatalogID,
			@chvTitle,
			@chvContent,
			GETDATE(),
			@chvSenderTypeID,
			@chvTempStr,
			@chvTempStr,
			@intAttachmentID,
			0,
			@chvType,
			0,
			0
		)
	COMMIT TRAN
	SELECT @nReceiverCount = @nReceiverCount + 1
END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_FullTextSearch]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_FullTextSearch]
GO











CREATE PROCEDURE Web_OA_FullTextSearch
(
	@chvKeywords			VARCHAR(100),
	@chvAuthorOrContent		VARCHAR(20),	--InAuthor		搜索作者
							--InContent		搜索文章
	@chvAuthor			VARCHAR(20),	--TitleAndReply 		包括主题和回复
							--Title			只搜索主题
							--Reply			只搜索回复
	@chvKeyInTitleOrInContent	VARCHAR(20),	--InTitle			只在主题中搜索
							--InContent		只在内容中搜索
							--InTitleAndContent	在主题和内容中搜索
	@intDateLine			INT,		--整数,			0表示所有日期 5表示最近5天，10表示最近10天
	@chvCatalogTypeID		VARCHAR(30),	--All			所有栏目
	@chvSortMode			VARCHAR(20),	--DateTime		按时间排序
							--ClickNumber		按点击次数排序
							--ReplyNumber		按回复次数排序
	@chvSortDirection		VARCHAR(10)	--Up			顺序显示
							--Down			逆序显示
)
--@encode$--
AS

/*初始化传入的参数，如果有些传入参数为空，则为其设置一个初始值*/
IF LTRIM(@chvAuthorOrContent) = ''
	SET @chvAuthorOrContent = 'TitleAndReply'
IF LTRIM(@chvSortMode) = ''
	SET @chvSortMode = 'DateTime'
IF LTRIM(@chvSortDirection) = ''
	SET @chvSortDirection = 'Down'
IF LTRIM(@chvCatalogTypeID) = ''
	SET @chvCatalogTypeID = 'All'
IF LTRIM(@chvKeyInTitleOrInContent) = ''	
	SET @chvKeyInTitleOrInContent = 'InTitle'
IF LTRIM(@chvCatalogTypeID) = ''
	SET @chvCatalogTypeID = 'All'
/*-------------------------------------------------------------------------------------------------------------------------*/


DECLARE @chvKeywordsCopy 		VARCHAR(100)
DECLARE @chvKeywords1		VARCHAR(100)=''
DECLARE @chvKeywords2		VARCHAR(100)=''
DECLARE @chvKeywords3		VARCHAR(100)=''
DECLARE @chvKeywords4		VARCHAR(100)=''
DECLARE @chvKeywords5		VARCHAR(100)=''
DECLARE @chvKeywords6		VARCHAR(100)=''
DECLARE @chvKeywords7		VARCHAR(100)=''
DECLARE @chvKeywords8		VARCHAR(100)=''
DECLARE @chvKeywords9		VARCHAR(100)=''
DECLARE @chvSQL			VARCHAR(5000)

SELECT @chvKeywordsCopy = LTRIM(@chvKeywords) + CHAR(32) + CHAR(32)

SELECT @chvKeywords1 = RTRIM(SUBSTRING(@chvKeywordsCopy,1,CHARINDEX(' ',@chvKeywordsCopy)))
SELECT @chvKeywordsCopy = LTRIM(SUBSTRING(@chvKeywordsCopy,CHARINDEX(' ',@chvKeywordsCopy)+1,LEN(@chvKeywordsCopy)-CHARINDEX('',@chvKeywordsCopy)))

SELECT @chvKeywords2 = RTRIM(SUBSTRING(@chvKeywordsCopy,1,CHARINDEX(' ',@chvKeywordsCopy)))
SELECT @chvKeywordsCopy = LTRIM(SUBSTRING(@chvKeywordsCopy,CHARINDEX(' ',@chvKeywordsCopy)+1,LEN(@chvKeywordsCopy)-CHARINDEX('',@chvKeywordsCopy)))

SELECT @chvKeywords3 = RTRIM(SUBSTRING(@chvKeywordsCopy,1,CHARINDEX(' ',@chvKeywordsCopy)))
SELECT @chvKeywordsCopy = LTRIM(SUBSTRING(@chvKeywordsCopy,CHARINDEX(' ',@chvKeywordsCopy)+1,LEN(@chvKeywordsCopy)-CHARINDEX('',@chvKeywordsCopy)))

SELECT @chvKeywords4 = RTRIM(SUBSTRING(@chvKeywordsCopy,1,CHARINDEX(' ',@chvKeywordsCopy)))
SELECT @chvKeywordsCopy = LTRIM(SUBSTRING(@chvKeywordsCopy,CHARINDEX(' ',@chvKeywordsCopy)+1,LEN(@chvKeywordsCopy)-CHARINDEX('',@chvKeywordsCopy)))

SELECT @chvKeywords5 = RTRIM(SUBSTRING(@chvKeywordsCopy,1,CHARINDEX(' ',@chvKeywordsCopy)))
SELECT @chvKeywordsCopy = LTRIM(SUBSTRING(@chvKeywordsCopy,CHARINDEX(' ',@chvKeywordsCopy)+1,LEN(@chvKeywordsCopy)-CHARINDEX('',@chvKeywordsCopy)))

SELECT @chvKeywords6 = RTRIM(SUBSTRING(@chvKeywordsCopy,1,CHARINDEX(' ',@chvKeywordsCopy)))
SELECT @chvKeywordsCopy = LTRIM(SUBSTRING(@chvKeywordsCopy,CHARINDEX(' ',@chvKeywordsCopy)+1,LEN(@chvKeywordsCopy)-CHARINDEX('',@chvKeywordsCopy)))

SELECT @chvKeywords7 = RTRIM(SUBSTRING(@chvKeywordsCopy,1,CHARINDEX(' ',@chvKeywordsCopy)))
SELECT @chvKeywordsCopy = LTRIM(SUBSTRING(@chvKeywordsCopy,CHARINDEX(' ',@chvKeywordsCopy)+1,LEN(@chvKeywordsCopy)-CHARINDEX('',@chvKeywordsCopy)))

SELECT @chvKeywords8 = RTRIM(SUBSTRING(@chvKeywordsCopy,1,CHARINDEX(' ',@chvKeywordsCopy)))
SELECT @chvKeywordsCopy = LTRIM(SUBSTRING(@chvKeywordsCopy,CHARINDEX(' ',@chvKeywordsCopy)+1,LEN(@chvKeywordsCopy)-CHARINDEX('',@chvKeywordsCopy)))

SELECT @chvKeywords9 = RTRIM(@chvKeywordsCopy)

--IF @chvKeywords1 != ''
--	IF @chvKeywords2 = ''
--		SELECT @chvKeywords2 = '攞麉嫿、良村&alan'	--永远不匹配的字符串
--	IF @chvKeywords3 = ''
--		SELECT @chvKeywords3 = '攞麉嫿、良村&alan'	--永远不匹配的字符串
--	IF @chvKeywords4 = ''
--		SELECT @chvKeywords4 = '攞麉嫿、良村&alan'	--永远不匹配的字符串	IF @chvKeywords5 = ''
--		SELECT @chvKeywords5 = '攞麉嫿、良村&alan'	--永远不匹配的字符串
--	IF @chvKeywords6 = ''
--		SELECT @chvKeywords6 = '攞麉嫿、良村&alan'	--永远不匹配的字符串
--	IF @chvKeywords7 = ''
--		SELECT @chvKeywords7 = '攞麉嫿、良村&alan'	--永远不匹配的字符串
--	IF @chvKeywords8 = ''
--		SELECT @chvKeywords8 = '攞麉嫿、良村&alan'	--永远不匹配的字符串
--	IF @chvKeywords9 = ''
--		SELECT @chvKeywords9 = '攞麉嫿、良村&alan'	--永远不匹配的字符串


SET @chvSQL = 'SELECT A.*,ISNULL(B.[FullName],' + CHAR(39) + '职员名空' + CHAR(39)
		+ ') AS [EmployeeName],ISNULL(C.[Name],' + CHAR(39) + '分类名空' + CHAR(39) 
		+ ') AS [CatalogName] FROM OA_PublicDB AS A LEFT JOIN Employee AS B ON A.[ETypeID_CreatorTypeID] = B.[typeId] '
		+ 'LEFT JOIN OA_Catalog AS C ON A.[CatalogID] = C.[TypeID] '

IF @chvAuthorOrContent = 'InAuthor'
BEGIN
	--搜索作者
	IF @chvKeywords1 <>''
	BEGIN
		SET @chvSQL = @chvSQL + 'WHERE B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords1 + '%' + CHAR(39) + ' '
	END
	IF @chvKeywords2 <>''
	BEGIN
		SET @chvSQL = @chvSQL + ' OR ' + 'B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords2 + '%' + CHAR(39)  + ' '
	END
	IF @chvKeywords3 <>''
	BEGIN
		SET @chvSQL = @chvSQL + ' OR ' + 'B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords3 + '%' + CHAR(39) + ' '
	END
	IF @chvKeywords4 <>''
	BEGIN
		SET @chvSQL = @chvSQL + ' OR ' + 'B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords4 + '%' + CHAR(39) + ' '
	END
	IF @chvKeywords5 <>''
	BEGIN
		SET @chvSQL = @chvSQL + ' OR ' + 'B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords5 + '%' + CHAR(39) + ' '
	END
	IF @chvKeywords6 <>''
	BEGIN
		SET @chvSQL = @chvSQL + ' OR ' + 'B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords6 + '%' + CHAR(39) + ' '
	END
	IF @chvKeywords7 <>''
	BEGIN
		SET @chvSQL = @chvSQL + ' OR ' + 'B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords7 + '%' + CHAR(39) + ' '
	END
	IF @chvKeywords8 <>''
	BEGIN
		SET @chvSQL = @chvSQL + ' OR ' + 'B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords8 + '%' + CHAR(39) + ' '
	END
	IF @chvKeywords9 <>''
	BEGIN
		SET @chvSQL = @chvSQL + ' OR ' + 'B.[FullName] LIKE ' + CHAR(39) + '%' + @chvKeywords9 + '%' + CHAR(39) + ') '
	END
	IF @chvAuthor = 'Title'
		--只在发布中搜索作者
		SET @chvSQL = @chvSQL + ' AND (A.[ParentID] = 0)'
	IF @chvAuthor = 'Reply'
		--只在回复中搜索作者
		SET @chvSQL = @chvSQL + ' AND (A.[ParentID] <> 0)'
END
ELSE
BEGIN
	--搜索内容
	IF @chvKeyInTitleOrInContent = 'InTitle'
	SET @chvSQL = @chvSQL + ' WHERE 1 = 1 '
		
	IF @chvKeywords1 <> ''
		OR @chvKeywords2 <> ''
		OR @chvKeywords3 <> ''
		OR @chvKeywords4 <> ''
		OR @chvKeywords5 <> ''
		OR @chvKeywords6 <> ''
		OR @chvKeywords7 <> ''
		OR @chvKeywords8 <> ''
		OR @chvKeywords9 <> ''
	BEGIN	
		SET @chvSQL = @chvSQL + ' AND ( '
	
		IF @chvKeywords1 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords1 + '%' + CHAR(39) + ' '
		END
		IF @chvKeywords2 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords2 + '%' + CHAR(39)  + ' '
		END
		IF @chvKeywords3 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords3 + '%' + CHAR(39) + ' '
		END
		IF @chvKeywords4 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords4 + '%' + CHAR(39) + ' '
		END
		IF @chvKeywords5 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords5 + '%' + CHAR(39) + ' '
		END
		IF @chvKeywords6 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords6 + '%' + CHAR(39) + ' '
		END
		IF @chvKeywords7 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords7 + '%' + CHAR(39) + ' '
		END
		IF @chvKeywords8 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords8 + '%' + CHAR(39) + ' '
		END
		IF @chvKeywords9 <>''
		BEGIN
			SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords9 + '%' + CHAR(39) + ' '
		END
		SET @chvSQL = @chvSQL + ' ) '
		
		SET @chvSQL = @chvSQL + 'AND (A.[ParentID]=0) '
	END
	IF @chvKeyInTitleOrInContent = 'InContent'
	BEGIN
		SET @chvSQL = @chvSQL + ' WHERE 1 = 1 '
		
		IF @chvKeywords1 <> ''
			OR @chvKeywords2 <> ''
			OR @chvKeywords3 <> ''
			OR @chvKeywords4 <> ''
			OR @chvKeywords5 <> ''
			OR @chvKeywords6 <> ''
			OR @chvKeywords7 <> ''
			OR @chvKeywords8 <> ''
			OR @chvKeywords9 <> ''
		BEGIN	
			SET @chvSQL = @chvSQL + ' AND ( '	
			IF @chvKeywords1 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords1 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords2 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords2 + '%' + CHAR(39)  + ' '
			END
			IF @chvKeywords3 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords3 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords4 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords4 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords5 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords5 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords6 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords6 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords7 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords7 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords8 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords8 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords9 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords9 + '%' + CHAR(39) + ' '
			END
			SET @chvSQL = @chvSQL + ' ) '
		END
	END
	IF @chvKeyInTitleOrInContent = 'InTitleAndContent'
	BEGIN	
		SET @chvSQL = @chvSQL + ' WHERE 1 = 1 '
		
		IF @chvKeywords1 <> ''
			OR @chvKeywords2 <> ''
			OR @chvKeywords3 <> ''
			OR @chvKeywords4 <> ''
			OR @chvKeywords5 <> ''
			OR @chvKeywords6 <> ''
			OR @chvKeywords7 <> ''
			OR @chvKeywords8 <> ''
			OR @chvKeywords9 <> ''
		BEGIN	
			SET @chvSQL = @chvSQL + ' AND ( '
			IF @chvKeywords1 <>''
			BEGIN
				SET @chvSQL = @chvSQL + '  A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords1 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords2 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords2 + '%' + CHAR(39)  + ' '
			END
			IF @chvKeywords3 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords3 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords4 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords4 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords5 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords5 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords6 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords6 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords7 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords7 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords8 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords8 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords9 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Title] LIKE ' + CHAR(39) + '%' + @chvKeywords9 + '%' + CHAR(39)+ ') '
			END
			IF @chvKeywords1 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR  A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords1 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords2 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords2 + '%' + CHAR(39)  + ' '
			END
			IF @chvKeywords3 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords3 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords4 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords4 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords5 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords5 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords6 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords6 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords7 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords7 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords8 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords8 + '%' + CHAR(39) + ' '
			END
			IF @chvKeywords9 <>''
			BEGIN
				SET @chvSQL = @chvSQL + ' OR ' + 'A.[Content] LIKE ' + CHAR(39) + '%' + @chvKeywords9 + '%' + CHAR(39) + ' '
			END
			SET @chvSQL = @chvSQL + ' ) '
		END
	END
END

IF @intDateLine < 0
	SET @intDateLine = 99999
SET @chvSQL = @chvSQL + ' AND (DATEDIFF(day,A.[CreateDate],GETDATE()) < ' + CAST(@intDateLine AS VARCHAR) + ') '
IF @chvCatalogTypeID <> 'All'
	SET @chvSQL = @chvSQL + 'AND (A.[CatalogID] = ' + CHAR(39) + @chvCatalogTypeID + CHAR(39) + ') '
IF @chvSortMode = 'DateTime'
	SET @chvSQL = @chvSQL + 'ORDER BY A.[CreateDate] '
IF @chvSortMode = 'ClickNumber'
	SET @chvSQL = @chvSQL + 'ORDER BY A.[ClickNumber] '
IF @chvSortMode = 'ReplyNumber'
	SET @chvSQL = @chvSQL + 'ORDER BY A.[ReplyNumber] '
IF @chvSortDirection = 'Up'
	SET @chvSQL = @chvSQL + 'ASC, A.[ID] DESC'
IF @chvSortDirection = 'Down'
	SET @chvSQL = @chvSQL + 'DESC, A.[ID] DESC'

SELECT @chvSQL AS [SQL]
--EXEC(@chvSQL)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_GetIPLocal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_GetIPLocal]
GO











CREATE PROCEDURE Web_OA_GetIPLocal
(
	@chvIPAdd		VARCHAR(15),
	@chvIPProvince	VARCHAR(50)	OUTPUT,
	@chvIPLocal		VARCHAR(50)	OUTPUT
)
--@encode$--
AS

DECLARE @chvIP1 	VARCHAR(3)
DECLARE @chvIP2 	VARCHAR(3)
DECLARE @chvIP3 	VARCHAR(3)
DECLARE @chvIP4 	VARCHAR(3)
DECLARE @chvStartIP	VARCHAR(15)
DECLARE @chvEndIP	VARCHAR(15)
DECLARE @chvCOUNTRY	VARCHAR(100)
DECLARE @chvLOCAL	VARCHAR(100)
DECLARE @chvSTR1	VARCHAR(10)
DECLARE @chvSTR2	VARCHAR(10)
DECLARE @intStartPos 	INT
DECLARE @intEndPos	INT
DECLARE @intI		INT
DECLARE @intDATA1	INT
DECLARE @intDATA2	INT
DECLARE @intDATA3	INT
DECLARE @intMID1	INT
DECLARE @intMID2	INT
DECLARE @intMID3	INT
DECLARE @intRetVal	INT

--SET @chvIPAdd = '61.139.50.144'

--IP地址格式化操作，前三位为'XXX.XXX.XXX.'

SET @intI = 1
SET @intStartPos = 0
SET @intEndPos = 0
WHILE @intI <= 4
BEGIN
	SET @intEndPos = CHARINDEX('.',@chvIPAdd,@intStartPos + 1)
	IF @intEndPos = 0 
		SET @intEndPos = LEN(@chvIPAdd) + 1
	IF @intI = 1
	BEGIN
		SET @chvIP1 = SUBSTRING(@chvIPAdd,@intStartPos + 1,@intEndPos - @intStartPos -1)
		IF LEN(@chvIP1) < 3
			SET @chvIP1 = SPACE(3-LEN(@chvIP1)) + @chvIP1
		SET @chvIP1 = REPLACE(@chvIP1,CHAR(32),'0')
	END
	IF @intI = 2
	BEGIN
		SET @chvIP2 = SUBSTRING(@chvIPAdd,@intStartPos + 1,@intEndPos - @intStartPos -1)
		IF LEN(@chvIP2) < 3
			SET @chvIP2 = SPACE(3-LEN(@chvIP2)) + @chvIP2
		SET @chvIP2 = REPLACE(@chvIP2,CHAR(32),'0')
	END
	IF @intI = 3
	BEGIN
		SET @chvIP3 = SUBSTRING(@chvIPAdd,@intStartPos + 1,@intEndPos - @intStartPos -1)
		IF LEN(@chvIP3) < 3
			SET @chvIP3 = SPACE(3-LEN(@chvIP3)) + @chvIP3
		SET @chvIP3 = REPLACE(@chvIP3,CHAR(32),'0')
	END
	IF @intI = 4
	BEGIN
		SET @chvIP4 = SUBSTRING(@chvIPAdd,@intStartPos + 1,@intEndPos - @intStartPos -1)
		IF LEN(@chvIP4) < 3
			SET @chvIP4 = SPACE(3-LEN(@chvIP4)) + @chvIP4
		SET @chvIP4 = REPLACE(@chvIP4,CHAR(32),'0')
	END
	SET @intStartPos = @intEndPos
	SET @intI = @intI + 1
END

SET @chvIPAdd = @chvIP1 + '.' + @chvIP2 + '.' + @chvIP3 + '.' + @chvIP4

--开始查询地址表
DECLARE cur1 CURSOR FOR 
	SELECT [STARTIP],'' AS [ENDIP],[COUNTRY],[LOCAL] FROM OA_IPAddress WHERE LEFT([STARTIP],3) = @chvIP1 ORDER BY [STARTIP] DESC
OPEN cur1

FETCH NEXT FROM cur1 
	INTO @chvStartIP,@chvEndIP,@chvCOUNTRY,@chvLOCAL

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @chvSTR1 = CAST(LEFT(@chvStartIP,8) AS VARCHAR)
	SET @chvSTR2 = CAST(LEFT(@chvIPAdd,8) AS VARCHAR)
	SET @intDATA1 = CAST(@chvIP4 AS INT)
	SET @intDATA2 = CAST(RIGHT(@chvStartIP,3) AS INT)
	SET @intDATA3 = CAST(RIGHT(@chvEndIP,3) AS INT)
	SET @intMID1 = CAST(@chvIP3 AS INT)
	SET @intMID2 = CAST(SUBSTRING(@chvStartIP,9,3) AS INT)
	SET @intMID3 = CAST(SUBSTRING(@chvEndIP,9,3) AS INT)

	IF @chvSTR1 < @chvSTR2
		SET @intRetVal = -1
	IF @chvSTR1 = @chvSTR2
		SET @intRetVal = 0
	IF @chvSTR1 > @chvSTR2
		SET @intRetVal = 1
	IF @intRetVal = 0 AND @intMID1 >= @intMID2 AND @intMID1 <= @intMID3
	BEGIN
		IF @intDATA1 >= @intDATA2 AND @intDATA1 <= @intDATA3
		BEGIN
			SET @chvIPProvince = @chvCOUNTRY
			SET @chvIPLocal = @chvLOCAL
			GOTO lblEND
		END
	END
	FETCH NEXT FROM cur1 
		INTO @chvStartIP,@chvEndIP,@chvCOUNTRY,@chvLOCAL	
END

lblOVER:
	SELECT @chvIPProvince = '未知数据'
	SELECT @chvIPLocal = ''
	GOTO lblEND
lblEND:
	CLOSE cur1
	DEALLOCATE cur1







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_MessageMove]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_MessageMove]
GO










/*
消息搬移
Alan 2003-1-8
传入参数：保留新消息记录数
*/
CREATE PROCEDURE Web_OA_MessageMove 
(
	@chvReserveCount	INT
)
--@encode$--
AS

DECLARE @chvSQL		VARCHAR(1000)
DECLARE @intReserve		INT			--保留消息数
DECLARE @intTotalCount	INT
DECLARE @intXCopyCount	INT

IF @chvReserveCount < 0 OR @chvReserveCount > 2000
	SET @chvReserveCount = 500			--缺省设置最多保留500条消息

SET @intReserve = @chvReserveCount

SET @intTotalCount = (SELECT COUNT(*) AS [TotalCount] FROM OA_Message)

IF @intTotalCount <= @chvReserveCount		--如果最新消息记录少于或等于保留记录数，则不执行任何搬移操作。
	RETURN 0

SET @intXCopyCount = @intTotalCount - @intReserve

SET @chvSQL = 'INSERT INTO OA_Message_Bak SELECT TOP ' + CAST(@intXCopyCount AS VARCHAR) + ' * FROM OA_Message ORDER BY [ID] ASC'

EXEC(@chvSQL)


SET @chvSQL = 'DELETE OA_Message WHERE [ID] IN (SELECT TOP ' + CAST(@intXCopyCount AS VARCHAR) + ' [ID] FROM OA_Message ORDER BY [ID] ASC)'

EXEC(@chvSQL)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_MsgDel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_MsgDel]
GO













/*
删除某人多余的消息记录，发送和接收最大消息数分别定义为2500条
一个人消息合计最多存储5000条
*/
CREATE PROCEDURE Web_OA_MsgDel
(
	@chvTypeID	VARCHAR(30)		--员工TypeID
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @intMaxCount 	INT
DECLARE @intCount		INT
DECLARE @chvSQL		VARCHAR(2000)
SELECT @intMaxCount = 2500									--最大消息数
SELECT @intCount = (SELECT COUNT(*) FROM [OA_Message]					--计算出属于自己的已阅读消息条数 
			WHERE [ETypeID_CreatorTypeID] = @chvTypeID 
			AND [ETypeID_ReceiverTypeID] = @chvTypeID AND [IsRead] = 1)
SELECT @intCount = @intCount - @intMaxCount							--求出应该删除的已阅读消息条数
IF @intCount > 0
BEGIN
	SELECT @chvSQL = 'DELETE [OA_Message] WHERE [ID] IN (SELECT TOP ' + CAST(@intCount AS VARCHAR(10)) + ' [ID] FROM [OA_Message] 
					WHERE [CreatorTypeID] = ' + CHAR(39) + @chvTypeID + CHAR(39) + ' AND [ReceiverTypeID] = '
					+ CHAR(39) + @chvTypeID + CHAR(39) + ' AND [IsRead] = 1 ORDER BY [ID])' 
	EXECUTE(@chvSQL)
END
SELECT @intCount = (SELECT COUNT(*) FROM [OA_Message]					--计算出属于自己的发送的消息条数 
			WHERE [ETypeID_CreatorTypeID] = @chvTypeID 
			AND [ETypeID_SenderTypeID] = @chvTypeID)
SELECT @intCount = @intCount - @intMaxCount							--求出应该删除的发送消息条数
IF @intCount > 0
BEGIN
	SELECT @chvSQL = 'DELETE [OA_Message] WHERE [ID] IN (SELECT TOP ' + CAST(@intCount AS VARCHAR(10)) + ' [ID] FROM [OA_Message] 
					WHERE [CreatorTypeID] = ' + CHAR(39) + @chvTypeID + CHAR(39) + ' AND [SenderTypeID] = '
					+ CHAR(39) + @chvTypeID + CHAR(39) + '  ORDER BY [ID])' 
	EXECUTE(@chvSQL)	
END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_MsgSend]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_MsgSend]
GO

/**
发送邮件、消息。
*/
CREATE  PROCEDURE Web_OA_MsgSend
(
	@chvCatalogID			VARCHAR(30),		--栏目TypID
	@chvType			VARCHAR(20),		--类型：	Message-消息
	@chvSenderTypeID		VARCHAR(50),		--发送人TypeID
	@chvReceiverTypeIDList	VARCHAR(8000),	--接收人TypeID串，以逗号分隔
	@chvTitle			VARCHAR(100),		--主题
	@chvContent			VARCHAR(8000),	--内容
	@intAttachmentID		INT,			--附件ID
	@chvMessageType		VARCHAR(20),		--消息类型：空 	普通消息
								--                    Invite	邀请阅读BBS文章消息
	@chvInviteURL			VARCHAR(500)	
)
--@encode$--
AS

--初始化批量接收人TypeID字符串
DECLARE @chvTempStr VARCHAR(50)
DECLARE @nReceiverCount INT
SET @nReceiverCount = 0

--ALAN 2002-10-14 添加，如去哦@chvMessageType传入值为空，则赋值为“Normal”，表示普通消息
IF RTRIM(@chvMessageType) = ''
	SET @chvMessageType = 'Normal'

IF RIGHT(@chvReceiverTypeIDList,1) <> CHAR(44)
	SET @chvReceiverTypeIDList = @chvReceiverTypeIDList + CHAR(44)	--CHAR(44) 逗号

WHILE LEN(@chvReceiverTypeIDList) >1
BEGIN
	SET @chvTempStr = LTRIM(RTRIM(LEFT(@chvReceiverTypeIDList,CHARINDEX(CHAR(44),@chvReceiverTypeIDList)-1)))
             SET @chvReceiverTypeIDList = RIGHT(@chvReceiverTypeIDList,LEN(@chvReceiverTypeIDList)-CHARINDEX(CHAR(44),@chvReceiverTypeIDList))
	
	BEGIN TRAN
	INSERT INTO OA_Message(CatalogID,Title,Content,CreateDate,ETypeID_SenderTypeID,ETypeID_ReceiverTypeID,ETypeID_CreatorTypeID,AttachmentID,IsRead,Type,Docking,SortOrder,MessageType,InviteURL) 
	VALUES(
			@chvCatalogID,
			@chvTitle,
			@chvContent,
			GETDATE(),
			@chvSenderTypeID,
			@chvTempStr,
			@chvSenderTypeID,
			@intAttachmentID,
			0,
			@chvType,
			0,
			0,
			@chvMessageType,
			@chvInviteURL
		)

	IF @chvSenderTypeID <> @chvTempStr
	INSERT INTO OA_Message(CatalogID,Title,Content,CreateDate,ETypeID_SenderTypeID,ETypeID_ReceiverTypeID,ETypeID_CreatorTypeID,AttachmentID,IsRead,Type,Docking,SortOrder,MessageType,InviteURL) 
	VALUES(
			@chvCatalogID,
			@chvTitle,
			@chvContent,
			GETDATE(),
			@chvSenderTypeID,
			@chvTempStr,
			@chvTempStr,
			@intAttachmentID,
			0,
			@chvType,
			0,
			0,
			@chvMessageType,
			@chvInviteURL
		)
	COMMIT TRAN

	SET @nReceiverCount = @nReceiverCount + 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_ReplyArticle]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_ReplyArticle]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2011.12.20
	描述：回复文章
*/
CREATE PROCEDURE Web_OA_ReplyArticle
(
	@pid int, --父文章ID
	@id  int, --文章ID
	@catalogid varchar(50), --栏目编号
	@title varchar(100), --文章主题
	@content VARCHAR(MAX), --文章正文
	@format int, --文章格式
	@radioimg varchar(40), --文章表情图片
	@userid varchar(50), --用户ID
	@BBS_REPLY_EXP int --回帖经验值
)

--@encode$--
AS
SET NOCOUNT ON

------------------------简单流程控制：回复文章后将父文章IsEnableCreatorDel设置为0-------

	UPDATE OA_PublicDB 
	SET [ReplyNumber] = [ReplyNumber] + 1,[IsEnableCreatorDel] = 0 
	WHERE [ID] = @pid OR [ParentID] = @pid
	
-----------------------获取栏目层叠控制值---------

	DECLARE @casecade int
	SET @casecade = (SELECT [IsCascadeCheck] FROM OA_Catalog WHERE [TypeID] = @catalogid)
	
------------------------添加回复文章信息---------------

	INSERT INTO OA_PublicDB ([CatalogID],[Title],[Content],[CreateDate],[ModifyDate],
						[ETypeID_CreatorTypeID],[ETypeID_ModifierTypeID],[ClickNumber],[ReplyNumber],
						[EmotionImg],[HtmlCode],[ParentID],[Docking],[Hidden],[SortOrder],[IsEnableCreatorDel])
	VALUES(@catalogid,@title,@content,GETDATE(),GETDATE(),
		@userid,@userid,0,0,
		@radioimg,@format,@pid,0,0,0,ISNULL(@casecade,0))
		
-----------------------回复值增加，经验增加------------------
	
	DECLARE @ifexits int --是否表中已有信息
	SET @ifexits = (SELECT COUNT(*) FROM OA_UserInformation WHERE [ETypeID_UserTypeID] = @userid)
	IF ISNULL(@ifexits, 0) = 0 --没有记录,新建记录
		BEGIN
			INSERT INTO OA_UserInformation ([ETypeID_UserTypeID],[Experience],[Add],[Reply])
                   VALUES(@userid, @BBS_REPLY_EXP,0,1)
		END
	ELSE --存在记录，直接更新
		BEGIN
			UPDATE OA_UserInformation SET [Reply] = [Reply] + 1,[Experience] = [Experience] + @BBS_REPLY_EXP
					WHERE [ETypeID_UserTypeID] = @userid
		END
		
------------------------获取文章ID并返回--------------

	DECLARE @articleid int --文章ID
	SET @articleid = (SELECT TOP 1 [ID] FROM OA_PublicDB WHERE [ParentID]= @pid ORDER BY [CreateDate] DESC)
	
RETURN @articleid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OA_ReplyIMNotice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OA_ReplyIMNotice]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2011.12.22
	描述：获取 IM发送“回复通知”的所有操作员
*/
CREATE PROCEDURE Web_OA_ReplyIMNotice
(
	@articleid int, --文章ID
	@id	int, --主帖ID
	@notice int --是否广播通知
)
--@encode$--
AS
SET NOCOUNT ON

-----------------获取回复文章信息---------
DECLARE @catalogid varchar(50) --栏目ID
DECLARE @content varchar(MAX) --文章内容
DECLARE @creatorid varchar(50) --作者ID

SELECT @catalogid = [CatalogID],@content = [Content],@creatorid = [ETypeID_CreatorTypeID] FROM OA_PublicDB WHERE ID = @articleid

IF ISNULL(@catalogid, '0') = '0'
	BEGIN
		RAISERROR('信息获取失败，请重试',16,1)
		RETURN
	END

----------------生成接收者列表-----------

IF @notice = 1 --广播通知
	BEGIN
		SELECT [ETypeID_CreatorTypeID] AS [ETypeID_SubsciberTypeID] 
		,
		(select usercode from employee where typeid=[ETypeID_CreatorTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_CreatorTypeID]) as fullname 
		FROM OA_PersonalDesktop
			WHERE [ReplyNotify] = 1 AND [CatalogTypeID] = @catalogid 
        UNION 
		SELECT [ETypeID_SubsciberTypeID] AS [ETypeID_SubsciberTypeID],
		(select usercode from employee where typeid=[ETypeID_SubsciberTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_SubsciberTypeID]) as fullname 
		 FROM OA_Subscibe WHERE [ArticleID] = @id 
        UNION 
        SELECT A.[ETypeID_CreatorTypeID] AS [ETypeID_SubsciberTypeID],
		(select usercode from employee where typeid=A.ETypeID_CreatorTypeID) as usercode,(select fullname from employee where typeid=A.ETypeID_CreatorTypeID) as fullname 
		 FROM OA_PublicDB AS A 
			INNER JOIN ( 
				SELECT T1.[ETypeID_CreatorTypeID],@catalogid AS [CatalogTypeID],ISNULL(T2.[RefusePassiveReplyNotify],0) AS [RefusePassiveReplyNotify] 
				FROM OA_PublicDB AS T1 
				LEFT JOIN OA_PersonalDesktop AS T2 ON T1.[ETypeID_CreatorTypeID] = T2.[ETypeID_CreatorTypeID] AND T2.[CatalogTypeID] = @catalogid 
				WHERE (T1.[ID] = @id OR T1.[ParentID] = @id)  
				) AS B ON A.[ETypeID_CreatorTypeID] = B.[ETypeID_CreatorTypeID]  
        WHERE (B.[RefusePassiveReplyNotify] = 0 AND B.[CatalogTypeID] = @catalogid) 
			AND (A.[ID] = @id OR A.[ParentID] = @id) 
        UNION 
        SELECT [ETypeID_CreatorTypeID] AS [ETypeID_SubsciberTypeID] 
        ,
		(select usercode from employee where typeid=[ETypeID_CreatorTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_CreatorTypeID]) as fullname 
        FROM OA_PersonalMsgNotify_AND 
        WHERE ([PublisherTypeID] LIKE @creatorid 
			AND CHARINDEX([Content],@content) <> 0) 
			AND [CatalogTypeID] = @catalogid AND [Available] = 1 
        UNION 
        SELECT [ETypeID_CreatorTypeID] AS [ETypeID_SubsciberTypeID]
        ,
		(select usercode from employee where typeid=[ETypeID_CreatorTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_CreatorTypeID]) as fullname 
         FROM OA_PersonalMsgNotify_OR 
		WHERE ([PublisherTypeID] LIKE @creatorid 
			OR CHARINDEX([Content], @content) <> 0) 
			AND [CatalogTypeID] = @catalogid AND [Available] = 1 
        UNION 
        SELECT [ETypeID_CreatorTypeID] AS [ETypeID_SubsciberTypeID] 
        ,
		(select usercode from employee where typeid=[ETypeID_CreatorTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_CreatorTypeID]) as fullname 
        FROM OA_PersonalDesktop 
        WHERE [Notify] = 1 AND [CatalogTypeID] = @catalogid 
	END
ELSE --不广播通知
	BEGIN
		SELECT [ETypeID_CreatorTypeID] AS [ETypeID_SubsciberTypeID] ,
		(select usercode from employee where typeid=[ETypeID_CreatorTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_CreatorTypeID]) as fullname 
		FROM OA_PersonalDesktop WHERE [ReplyNotify] = 1 AND [CatalogTypeID] = @catalogid
		UNION 
		SELECT [ETypeID_SubsciberTypeID] AS [ETypeID_SubsciberTypeID],
		(select usercode from employee where typeid=[ETypeID_SubsciberTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_SubsciberTypeID]) as fullname 
		 FROM OA_Subscibe WHERE [ArticleID] = @id 
		UNION 
		SELECT [ETypeID_CreatorTypeID] AS [ETypeID_SubsciberTypeID],
		(select usercode from employee where typeid=[ETypeID_CreatorTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_CreatorTypeID]) as fullname 
		 FROM OA_PersonalMsgNotify_AND 
		WHERE ([PublisherTypeID] LIKE @creatorid 
			AND CHARINDEX([Content],@content) <> 0) 
			AND [CatalogTypeID] = @catalogid AND [Available] = 1 
		UNION 
		SELECT [ETypeID_CreatorTypeID] AS [ETypeID_SubsciberTypeID] ,
		(select usercode from employee where typeid=[ETypeID_CreatorTypeID]) as usercode,(select fullname from employee where typeid=[ETypeID_CreatorTypeID]) as fullname 
		FROM OA_PersonalMsgNotify_OR 
		WHERE ([PublisherTypeID] LIKE @creatorid 
			OR CHARINDEX([Content],@content) <> 0) 
			AND [CatalogTypeID] = @catalogid AND [Available] = 1 
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OM_Login]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OM_Login]
GO


CREATE PROC Web_OM_Login
(
  @UserCode       VARCHAR(50),
  @Password       VARCHAR(10),
  @BtypeID        VARCHAR(50)      OUT,
  @UserName       VARCHAR(50)      OUT,
  @Date           VARCHAR(50)      OUT,
  @Level          INT              OUT,
  @TelePhone      VARCHAR(50)      OUT,
  @QQ             VARCHAR(50)      OUT,
  @Email          VARCHAR(50)      OUT,
  @Lim            VARCHAR(5000)    OUT,
  @RetValue       INT              OUT         --0,登录失败。1,登陆成功
)
--@encode$--
AS
SET NOCOUNT ON

SELECT @BtypeID=BtypeID,
       @UserName=UserName,
       @Date=Date,
       @Level=Level,
       @TelePhone=TelePhone,
       @QQ=QQ,
       @Email=Email,
       @Lim=Lim
  FROM OM_LoginUsers
  WHERE UserCode=@UserCode AND Password=@Password

IF @@ROWCOUNT!=1
  BEGIN
       SET @RetValue=0
       RETURN
  END

SET @RetValue=1
RETURN

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_OM_QueryArApAuditAccountDetail]') AND OBJECTPROPERTY(ID,N'ISPROCEDURE')=1)
DROP PROCEDURE Web_OM_QueryArApAuditAccountDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：LUDALIN
	日期：2013-11-26
	描述：往来对账明细表
*/
CREATE PROCEDURE Web_OM_QueryArApAuditAccountDetail
(
	@StartDate			VARCHAR(10),	--开始日期
	@EndDate			VARCHAR(10),	--截止日期	
	@BTypeId			VARCHAR(50), --OM登录人员和ERP绑定的客户id
	@page				VARCHAR(10),
	@pagesize			VARCHAR(10),
	@WhichDetail		VARCHAR(10),		--当前查询类型-'P':商品；'A'：账户；'B':单据
	@totalpage  int output
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @stypeid VARCHAR(50),@Cid VARCHAR(10),
		@IsDetail	VARCHAR(10),@billtype VARCHAR(200),@IsShowAll INT

SET @Cid='0' 	--是否按展开明细
SET @BillType='215,11,45,160,141,34,6,161,145,116,115,128,129,4,189,66,190,148,150,149,151,36,93,84,85,159,167,168,170,172,181,312,213,212,305'
SET @IsDetail='True'
SET @IsShowAll=1

--分支机构
SET @STypeId='00000'
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,'00001')

--结算单位

CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,'00001')


-------------单据类型参数处理--------------------
--只有在按照商品明细显示的时候才有全部单据类型，否则，不应该有
IF @WhichDetail='B'
BEGIN
	SET @BillType=REPLACE(@BillType,'126','0')
	SET @BillType=REPLACE(@BillType,'139','0')
END

IF @WhichDetail='A' 
BEGIN
	SET @BillType=REPLACE(@BillType,'126','0')
	SET @BillType=REPLACE(@BillType,'139','0')
END


----------==============================================查询主体=====BEGIN==========================----------------------------
--思路:动态查询方式
--为了显示方便，默认将期初的billtype字段设计为-1，将小计的billtype 字段设计为-10
--
----------==========================================================================================-----------------------------
DECLARE @CREATESQL	VARCHAR(MAX),--表创建语句1
		@CREATESQL2	VARCHAR(MAX),--表创建语句2
				@PTYPEDETAIL VARCHAR(MAX)--商品明细语句


CREATE TABLE #totalpagetable
(
  totalpage INT 
)

CREATE TABLE #BILLINDEX
(
	BILLNUMBERID NUMERIC(18,0),
	BILLCODE			VARCHAR(400),
	BILLDATE			DATETIME,
	BILLTYPE			VARCHAR(20),
	BTYPEID			VARCHAR(50),--单位
	TOTAL				 NUMERIC(24, 10) ,--单据金额
	NTOTAL			 NUMERIC(24, 10) ,--单据金额
	PREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	NPREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	PAYORINMONEY  NUMERIC(24, 10) ,--收或付款金额
	NPAYORINMONEY  NUMERIC(24, 10) ,--收或付款金额
	RECONCILIATION	VARCHAR(4),--对账标志
	Comment			VARCHAR(256),
	BillBtypeID		VARCHAR(50)	-- 单据往来单位
)
-----筛选表数据---------------
SET @CREATESQL='

INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.TOTALMONEY ELSE BI.TOTALMONEY-BI.PREFERENCEMONEY END,--单据金额
			CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.NTOTALMONEY ELSE BI.NTOTALMONEY-BI.NPREFERENCEMONEY END,--单据金额
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			t.total,
			t.ntotal,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID
FROM   BILLINDEX BI 
			LEFT JOIN (SELECT BillNumberId,SUM(NTotalMoney) as ntotal,sum(TOTAL) as total FROM dbo.BillMulAccount  WHERE ATypeID NOT IN (27,39)  GROUP BY BillNumberId) t on bi.billnumberid=t.billnumberid
				INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE 
			 BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE NOT IN (115,116,128,129,126,139,159,161,160)
			AND BI.RedWord=0
			AND BI.IFCHECK=''t'''
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

IF @IsDetail = 'True' AND @IsShowAll = 0
BEGIN
	SET @CREATESQL+=' AND BI.Reconciliation <> ''t'''
END
--PRINT(@createsql)
SET @CREATESQL+=' 
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			0,
			bi.totalmoney,
			BI.ntotalmoney,
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			bi.totalinmoney,
			BI.ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID
FROM   BILLINDEX BI 
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE 
			 BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE IN (115,116,128,129)
			AND BI.RedWord=0
			AND BI.IFCHECK=''t'''
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

IF @IsDetail = 'True' AND @IsShowAll = 0
BEGIN
	SET @CREATESQL+=' AND BI.Reconciliation <> ''t'''
END
		
SET @CREATESQL+='
INSERT INTO #BILLINDEX
SELECT BI.BILLNUMBERID,
			BI.BILLCODE,
			BI.BILLDATE,
			BI.BILLTYPE,
			0,
			0,
			0,
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			0,
			0,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID
FROM BILLINDEX bi
WHERE BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE=159	
			AND BI.IfCheck = ''t''
			AND BI.Draft = 0
			AND BI.RedWord=0'
			
IF @IsDetail = 'True' AND @IsShowAll = 0
BEGIN
	SET @CREATESQL+=' AND BI.Reconciliation <> ''t'''
END			
			
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+' AND bi.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+' AND bi.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)
--业务凭证特殊处理，币种判断表体
--IF @CID<>0 AND ISNULL(@Cid,0)<>0
--BEGIN
--	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
--END
		
SET @CREATESQL+='
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			bi.totalmoney,
			BI.ntotalmoney,
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			bi.totalinmoney,
			BI.ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID
FROM   BILLINDEX BI 
				INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE  BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE =139
			AND BI.RedWord=0
			AND BI.IFCHECK=''t'''
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

IF @IsDetail = 'True' AND @IsShowAll = 0
BEGIN
	SET @CREATESQL+=' AND BI.Reconciliation <> ''t'''
END
		
SET @CREATESQL+='
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			bi.totalmoney,
			BI.ntotalmoney,
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			bi.totalinmoney,
			BI.ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID
FROM   BILLINDEX BI
				INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE  BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE =126
			AND BI.RedWord=0
			AND BI.IFCHECK=''t'''

IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

IF @IsDetail = 'True' AND @IsShowAll = 0
BEGIN
	SET @CREATESQL+=' AND BI.Reconciliation <> ''t'''
END
		
SET @CREATESQL+='
	--特殊处理换货单
INSERT INTO #BILLINDEX
SELECT  BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.TOTALMONEY ELSE BI.TOTALMONEY-BI.PREFERENCEMONEY END,--单据金额
			CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.NTOTALMONEY ELSE BI.NTOTALMONEY-BI.NPREFERENCEMONEY END,--单据金额
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			bi.totalinmoney,
			BI.ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID
FROM BILLINDEX BI
					INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
				WHERE  BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE IN (160,161)
			AND BI.RedWord=0
			AND BI.IFCHECK=''t''
'
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

IF @IsDetail = 'True' AND @IsShowAll = 0
BEGIN
	SET @CREATESQL+=' AND BI.Reconciliation <> ''t'''
END

EXEC(@CREATESQL)

---------------------------计算期初数据-----------------------------
-----统计算法：本来的期初往来余额+本期截至到查询开始时间之前的往来余额
SET @CREATESQL='
CREATE TABLE #TOTAL00
(
	BTYPEID VARCHAR(100),
	ARTOTAL  NUMERIC(24, 10) ,--应收金额
	NARTOTAL  NUMERIC(24, 10) ,
	APTOTAL  NUMERIC(24, 10) ,--应付金额
	NAPTOTAL  NUMERIC(24, 10) ,
	YSTOTAL  NUMERIC(24, 10) ,--预收金额
	NYSTOTAL  NUMERIC(24, 10) ,
	YFTOTAL  NUMERIC(24, 10) ,--预付金额
	NYFTOTAL  NUMERIC(24, 10) ,
	QMTOTAL  NUMERIC(24, 10) ,--往来余额
	NQMTOTAL  NUMERIC(24, 10) 
)

INSERT INTO #TOTAL00
SELECT BTypeID,
			SUM(ARTOTAL),
			SUM(NARTOTAL),
			SUM(APTOTAL),
			SUM(NAPTOTAL),
			SUM(YSTOTAL),
			SUM(NYSTOTAL),
			SUM(YFTOTAL),
			SUM(NYFTOTAL),
			SUM(ARTOTAL)-SUM(APTOTAL)-SUM(YSTOTAL)+SUM(YFTOTAL),
			SUM(NARTOTAL)-SUM(NAPTOTAL)-SUM(NYSTOTAL)+SUM(NYFTOTAL)
FROM  (
			SELECT BTypeID,
						SUM(ISNULL(ARTotal00,0)) AS ARTOTAL,
						SUM(ISNULL(nARTotal00,0)) AS NARTOTAL,
						SUM(ISNULL(APTotal00,0)) AS APTOTAL,
						SUM(ISNULL(nAPTotal00,0)) AS NAPTOTAL,
						SUM(ISNULL(YSTotal00,0)) AS YSTOTAL,
						SUM(ISNULL(nYSTotal00,0)) AS NYSTOTAL,
						SUM(ISNULL(YFTotal00,0)) AS YFTOTAL,
						SUM(ISNULL(nYFTotal00,0)) AS NYFTOTAL
			FROM dbo.BType_ArApTotal A
						INNER JOIN #GetManBTypeId B ON A.BTypeID=B.TypeId
						INNER JOIN #GetManSTypeId S ON S.TypeId=A.STypeID
			WHERE 1=1 '
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' and A.CID LIKE '''+@Cid+''''
END
		
SET @CREATESQL+='
			GROUP BY A.BTypeID
			UNION ALL
			SELECT L.BtypeId,
			 ISNULL(SUM(CASE WHEN L.ATYPEID=33
						THEN Total
						END),0) AS ARTotal,
		   ISNULL(SUM(CASE WHEN L.ATYPEID=33
						THEN NTotal
						END),0) AS NARTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID=35
			THEN Total
			END),0) AS APTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID=35
						THEN NTotal
						END),0) AS NAPTotal,
			 ISNULL(SUM(CASE WHEN L.ATYPEID=39
						THEN Total
						END),0) AS YSTotal,
		   ISNULL(SUM(CASE WHEN L.ATYPEID=39
						THEN NTotal
						END),0) AS NYSTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID=27
						THEN Total
						END),0) AS YFTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID=27
						THEN NTotal
						END),0) AS NYFTotal
		   FROM ListTable L
		   INNER JOIN #GetManBTypeId B ON B.TypeId=L.BtypeId
		   INNER JOIN #GetManSTypeId S ON S.TypeId=L.STypeID
		   WHERE L.BillDate<'+CHAR(39)+@StartDate+CHAR(39)+'
				  AND L.ATYPEID IN (33,35,39,27)
						' 
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND L.CID LIKE '''+@Cid+''''
END
		
SET @CREATESQL+='
						AND L.AtypeId  IN (33,35,39,27)
			GROUP BY L.BtypeId
			) A 
GROUP BY A.BTypeID

--DELETE FROM #TOTAL00 WHERE ARTOTAL=0 AND APTOTAL=0 AND YSTOTAL=0 AND YFTOTAL=0 AND QMTOTAL=0

-------------------统计明细，按照单据类型、单位--------------------
CREATE TABLE #BILLTOTAL
(
	BTYPEID			VARCHAR(50),--单位
	BILLNUMBERID	VARCHAR(20),
	BILLTYPE			VARCHAR(20),
	BILLDATE			DATETIME,
	BILLCODE			VARCHAR(400),
	BILLTOTAL		 NUMERIC(24, 10) ,--	单据金额
	NBILLTOTAL		 NUMERIC(24, 10) ,--	单据金额
	PREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	NPREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	INTOTAL		 NUMERIC(24, 10) ,--实收金额
	NINTOTAL		 NUMERIC(24, 10) ,--实收金额
	ARTOTAL		 NUMERIC(24, 10) ,--应收金额
	NARTOTAL		 NUMERIC(24, 10) ,--应收金额
	PAYTOTAL	 NUMERIC(24, 10) ,--实付金额
	NPAYTOTAL	 NUMERIC(24, 10) ,--实付金额
	APTOTAL		 NUMERIC(24, 10) ,--应付金额
	NAPTOTAL		 NUMERIC(24, 10) ,--应付金额
	YSTOTAL		 NUMERIC(24, 10) ,--预收金额
	NYSTOTAL		 NUMERIC(24, 10) ,--预收金额
	YFTOTAL		 NUMERIC(24, 10) ,--预付金额
	NYFTOTAL		 NUMERIC(24, 10) ,--预付金额
	QMTOTAL	 NUMERIC(24, 10) ,--往来余额
	NQMTOTAL	 NUMERIC(24, 10) ,--往来余额
	RECONCILIATION	VARCHAR(4),--对账标志
	Comment			VARCHAR(256),
	BillBtypeID		VARCHAR(50)	--单据往来单位
)
--特殊处理换货单
INSERT INTO #BILLTOTAL
SELECT DISTINCT A.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			CASE WHEN A.BILLTYPE =160 THEN ISNULL(A.PAYORINMONEY,0) ELSE 0 END,--收款类单据有实收金额
			CASE WHEN A.BILLTYPE =160 THEN ISNULL(A.NPAYORINMONEY,0) ELSE 0 END,--收款类单据有实收金额
			0,--应收
			0,
			CASE WHEN A.BILLTYPE =161 THEN ISNULL(A.PAYORINMONEY,0) ELSE 0 END,--付款类单据有实付金额
			CASE WHEN A.BILLTYPE =161 THEN ISNULL(A.NPAYORINMONEY,0) ELSE 0 END,--付款类单据有实付金额
			0,--应付
			0,
			0,--预收
			0,
			0,--预付
			0,
			0,
			0,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID
FROM #BILLINDEX A 
WHERE A.BILLTYPE IN (160,161) 
			AND A.BILLNUMBERID IN (
													SELECT A.BILLNUMBERID FROM dbo.SaleGoodsExchangeBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId
													WHERE A.BillNumberId NOT IN (SELECT BillNumberId FROM dbo.ListTable)
																AND B.RedWord=0
																AND B.ifcheck=''t''
													UNION ALL
													SELECT A.BILLNUMBERID FROM dbo.BuyGoodsExchangeBill A INNER JOIN dbo.BillIndex B ON A.BillNumberId=B.BillNumberId
													WHERE A.BillNumberId NOT IN (SELECT BILLNUMBERID FROM dbo.ListTable)
																AND B.RedWord=0
																AND B.ifcheck=''t''
													)
AND A.BILLTYPE NOT IN (115,116,128,129)'
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+' AND A.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+' AND A.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)
	
--特殊业务凭证
SET  @CREATESQL=@CREATESQL+
'
INSERT INTO #BILLTOTAL
SELECT L.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			0,--实收
			0,--实收
			CASE WHEN L.AtypeId=33 THEN L.Total END ,--应收
			CASE WHEN L.AtypeId=33 THEN L.NTotal END ,--应收
			0,--实付
			0,--实付
			CASE WHEN L.AtypeId=35 THEN L.Total END ,--应付
			CASE WHEN L.AtypeId=35 THEN L.NTotal END ,--应付
			CASE WHEN L.AtypeId=39 THEN L.Total END ,--预收
			CASE WHEN L.AtypeId=39 THEN L.NTotal END ,--预收
			CASE WHEN L.AtypeId=27 THEN L.Total END ,--预付
			CASE WHEN L.AtypeId=27 THEN L.NTotal END ,--预付
			0,
			0,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID
FROM #BILLINDEX A INNER JOIN dbo.ListTable L ON a.billnumberid=l.BillNumberId
			INNER JOIN #GetManBTypeId B ON B.TypeId=L.BtypeId
		   INNER JOIN #GetManSTypeId S ON S.TypeId=L.STypeID
WHERE A.BILLTYPE =159 AND ISNULL(L.BtypeId,'''')<>''''  '
--业务凭证特殊处理，币种判断表体
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND L.CID LIKE '''+@Cid+''''
END

SET @CREATESQL +=' 
INSERT INTO #BILLTOTAL
SELECT A.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			CASE WHEN A.BILLTYPE IN(11,93,141,85,157,167,168,172,178,186,150,305,195,181,312,182,179,196,200,213,151) THEN ISNULL(A.PAYORINMONEY,0) 
					WHEN A.BILLTYPE =160 THEN ISNULL(A.PAYORINMONEY,0)-ISNULL(-B.YSTOTAL,0)
					WHEN A.BILLTYPE IN (189) THEN ISNULL(A.TOTAL,0)
					WHEN A.BILLTYPE IN (4) THEN ISNULL(A.TOTAL,0)-ISNULL(-B.YSTOTAL,0)
					WHEN A.BILLTYPE IN (6) THEN ISNULL(A.PAYORINMONEY,0)
							ELSE 0 END,--收款类单据有实收金额
		CASE WHEN A.BILLTYPE IN(11,93,141,85,157,167,168,172,178,186,150,305,195,181,312,182,179,196,200,213,151) THEN ISNULL(A.NPAYORINMONEY,0) 
					WHEN A.BILLTYPE =160 THEN ISNULL(A.NPAYORINMONEY,0)-ISNULL(-B.NYSTOTAL,0)--预收预付本来就是负数
					WHEN A.BILLTYPE IN (189) THEN ISNULL(A.nTOTAL,0)
					WHEN A.BILLTYPE IN (4) THEN ISNULL(A.NTOTAL,0)-ISNULL(-B.NYSTOTAL,0)
					WHEN A.BILLTYPE IN (6) THEN ISNULL(A.NPAYORINMONEY,0)-ISNULL(-B.NYFTOTAL,0)
					ELSE 0 END,--收款类单据有实收金额	
			CASE WHEN a.billtype=4 THEN -(A.TOTAL+A.PREFERENCEMONEY) ELSE b.ARTOTAL END,--应收--收款单算法比较变态
			CASE WHEN a.billtype=4 THEN -(A.NTOTAL+A.NPREFERENCEMONEY) ELSE b.NARTOTAL END,--应收
			CASE WHEN A.BILLTYPE IN (34,145,84,170,148,212,45,215,149) THEN ISNULL(A.PAYORINMONEY,0) 
					 WHEN A.BILLTYPE =161 THEN ISNULL(A.PAYORINMONEY,0)-ISNULL(-B.YFTOTAL,0)
					 WHEN A.BILLTYPE IN (190) THEN ISNULL(A.TOTAL,0)
					 WHEN A.BILLTYPE IN (66) THEN ISNULL(A.TOTAL,0)-ISNULL(-B.YFTOTAL,0)
										ELSE 0 END,--付款类单据有实付金额
			CASE WHEN A.BILLTYPE IN (34,145,84,170,148,212,45,215,149) THEN ISNULL(A.NPAYORINMONEY,0) 
					 WHEN A.BILLTYPE =161 THEN ISNULL(A.NPAYORINMONEY,0)-ISNULL(-B.NYFTOTAL,0)
					WHEN A.BILLTYPE  IN (190) THEN ISNULL(A.NTOTAL,0)
					WHEN A.BILLTYPE IN (66) THEN ISNULL(A.NTOTAL,0)-ISNULL(-B.NYFTOTAL,0)
										ELSE 0 END,--付款类单据有实付金额
			CASE WHEN a.billtype=66 THEN b.APTOTAL ELSE B.APTOTAL END,--应付
			CASE WHEN a.billtype=66 THEN b.NAPTOTAL ELSE B.NAPTOTAL END,--应付
			B.YSTOTAL,--预收
			B.NYSTOTAL,--预收
			B.YFTOTAL,--预付
			B.NYFTOTAL,--预付
			B.ARTOTAL-B.APTOTAL-B.YSTOTAL+B.YFTOTAL,
			B.NARTOTAL-B.NAPTOTAL-B.NYSTOTAL+B.NYFTOTAL,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID
FROM #BILLINDEX A INNER JOIN (
															SELECT BillNumberId,
																	SUM(CASE WHEN AtypeId=33 THEN Total END) AS ARTOTAL,
																	SUM(CASE WHEN AtypeId=33 THEN nTotal END) AS NARTOTAL,
																	 SUM(CASE WHEN AtypeId=35 THEN Total END) AS APTOTAL,
																	 SUM(CASE WHEN AtypeId=35 THEN nTotal END) AS NAPTOTAL,
																	 SUM(CASE WHEN AtypeId=39 THEN Total END) AS YSTOTAL,
																	 SUM(CASE WHEN AtypeId=39 THEN nTotal END) AS NYSTOTAL,
																	 SUM(CASE WHEN AtypeId=27 THEN Total END) AS YFTOTAL,
																	 SUM(CASE WHEN AtypeId=27 THEN nTotal END) AS NYFTOTAL
															FROM LISTTABLE 
															--INNER JOIN #GetManBTypeId B ON B.TypeId=LISTTABLE.BtypeId
															--INNER JOIN #GetManSTypeId S ON S.TypeId=LISTTABLE.STypeID
															GROUP BY BillNumberId
														) B ON A.BILLNUMBERID = B.BillNumberId
														INNER JOIN dbo.BillIndex c ON a.billnumberid=c.BillNumberId
WHERE A.BILLTYPE NOT IN (115,116,128,129,36,159) '
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+' AND A.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+' AND A.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)


-------调账类四张单据------
SET @CREATESQL+=' 
INSERT INTO #BILLTOTAL
SELECT L.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			L.TOTAL,
			L.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			0,--收款类单据有实收金额
			0,
			L.ARTOTAL,--应收
			L.NARTOTAL,--应收
			0,--付款类单据有实付金额
			0,
			L.APTOTAL,--应付
			L.NAPTOTAL,--应付
			0,--预收
			0,
			0,--预付
			0,
			0,
			0,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID
FROM #BILLINDEX A INNER JOIN ( select billnumberid,btypeid,STYPEID,ATYPEID,
															SUM(CASE WHEN BTYPEID<>'''' THEN ABS(TOTAL) ELSE 0 END) AS TOTAL,
															SUM(CASE WHEN BTYPEID<>'''' THEN ABS(NTOTAL) ELSE 0 END) AS NTOTAL,
															CASE WHEN ATYPEID=''33'' THEN SUM(total) ELSE 0 END AS ARTOTAL,
															CASE WHEN ATYPEID=''33'' THEN SUM(Ntotal) ELSE 0 END AS NARTOTAL,
															 CASE WHEN ATYPEID=''35'' THEN SUM(total) ELSE 0 END AS APTOTAL,
															CASE WHEN ATYPEID=''35'' THEN SUM(ntotal) ELSE 0 END AS NAPTOTAL 
															 from ListTable WHERE  ATYPEID IN (33,35) AND BILLTYPE IN (115,116,128,129)
															GROUP BY BillNumberId,BtypeId ,BtypeId,STypeID,AtypeId 
															 ) L ON A.BILLNUMBERID = L.BillNumberId 
			INNER JOIN #GetManBTypeId B ON B.TypeId=L.BtypeId
		   INNER JOIN #GetManSTypeId S ON S.TypeId=L.STypeID
WHERE 1=1 
			'
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+' AND A.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+' AND A.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)
--SET @CREATESQL=@CREATESQL+' GROUP BY L.BTYPEID,
--			A.BILLNUMBERID,
--			A.BILLTYPE,
--			A.BILLDATE,
--			A.BILLCODE,
--			A.RECONCILIATION'
	

-------费用单------
SET @CREATESQL+=' 
INSERT INTO #BILLTOTAL
SELECT A.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			0,--收款类单据有实收金额
			0,
			CASE WHEN A.BTYPEID LIKE ''00001%'' THEN -(A.TOTAL-ISNULL(a.PAYORINMONEY,0)-ISNULL(-L.YFTOTAL,0)) ELSE 0 END,--应收
			CASE WHEN A.BTYPEID LIKE ''00001%'' THEN -(A.NTOTAL-ISNULL(a.nPAYORINMONEY,0)-ISNULL(-L.NYFTOTAL,0)) ELSE 0 END,--应收
			A.PAYORINMONEY-L.YFTOTAL,--付款类单据有实付金额
			A.NPAYORINMONEY-L.NYFTOTAL,--付款类单据有实付金额
			CASE WHEN A.BTYPEID LIKE ''00002%'' THEN  L.APTOTAL ELSE 0 END,--应付
			CASE WHEN A.BTYPEID LIKE ''00002%'' THEN  L.NAPTOTAL ELSE 0 END,--应付
			0,--预收
			0,
			L.YFTOTAL,--预付
			L.NYFTOTAL,--预付
			0,
			0,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID
FROM #BILLINDEX A LEFT JOIN (
												SELECT BillNumberId,
															SUM(CASE WHEN AtypeId=33 THEN Total ELSE 0 END) AS ARTOTAL,
															SUM(CASE WHEN AtypeId=33 THEN NTotal ELSE 0 END) AS NARTOTAL,
															SUM(CASE WHEN AtypeId=35 THEN Total ELSE 0 END) AS APTOTAL ,
															SUM(CASE WHEN AtypeId=35 THEN NTotal ELSE 0 END) AS NAPTOTAL,
															SUM(CASE WHEN AtypeId=39 THEN Total ELSE 0 END) AS YSTOTAL,
															SUM(CASE WHEN AtypeId=39 THEN NTotal ELSE 0 END) AS NYSTOTAL,
															SUM(CASE WHEN AtypeId=27 THEN Total ELSE 0 END) AS YFTOTAL,
															SUM(CASE WHEN AtypeId=27 THEN NTotal ELSE 0 END) AS NYFTOTAL
													FROM ListTable L
													--INNER JOIN #GetManBTypeId B ON B.TypeId=L.BtypeId
													--INNER JOIN #GetManSTypeId S ON S.TypeId=L.STypeID
													 WHERE BillType=36
													GROUP BY BillNumberId
												) L ON A.BILLNUMBERID = L.BillNumberId
WHERE A.BILLTYPE =36
			'
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+' AND A.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+' AND A.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)


------------------最终数据临时表------------------------
--特殊处理期初和小计的单据类型--期初：-1，小计：-10.有问题问我----------
SET @CREATESQL+=' 
CREATE TABLE #RESULT
(
	BTYPEID			VARCHAR(50),--单位 
	BILLNUMBERID	VARCHAR(20),'
IF @WhichDetail='A'
	SET @CREATESQL=@CREATESQL+'ATYPEID VARCHAR(100),'
IF @WhichDetail='P'
	SET @CREATESQL=@CREATESQL+'PTYPEID VARCHAR(100),PRICE VARCHAR(20),QTY  NUMERIC(24, 10) ,ufullname varchar(100),'
SET @CREATESQL=@CREATESQL+'
	BILLTYPE			VARCHAR(20),
	BILLDATE			DATETIME,
	BILLCODE			VARCHAR(400),
	BILLTOTAL		VARCHAR(20),--	单据金额
	PREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	INTOTAL		 NUMERIC(24, 10) ,--实收金额
	ARTOTAL		 NUMERIC(24, 10) ,--应收金额
	PAYTOTAL	 NUMERIC(24, 10) ,--实付金额
	APTOTAL		 NUMERIC(24, 10) ,--应付金额
	YSTOTAL		 NUMERIC(24, 10) ,--预收金额
	YFTOTAL		 NUMERIC(24, 10) ,--预付金额
	QMTOTAL	 NUMERIC(24, 10) ,--往来余额
	RECONCILIATION	VARCHAR(4),--对账标志
	SORTID		INT,					--排序id
	PSORTID		INT,					--再来一个排序id,商品或收款账户用
	Comment		VARCHAR(256),
	BillSort	VARCHAR(50), --wg 按照时间排序，同时保持同一单据在一起
	BillBtypeID	VARCHAR(50),--单据往来单位--对应界面的字段名字
	DetailComment VARCHAR(300) default('''') --单据明细
)

INSERT INTO #RESULT
SELECT  BTYPEID,
			 -99999,--期初不写值'
IF @WhichDetail='A'
	SET @CREATESQL=@CREATESQL+' 
															'''','
IF @WhichDetail='P'
	SET @CREATESQL=@CREATESQL+' 
															NULL,0,0,'''', '
SET @CREATESQL=@CREATESQL+' 
			''-1'',--期初强写-1
			NULL,
			'''',
			0,
			0,--优惠金额
			0,
			ISNULL(CASE WHEN '+@CID+'=0 THEN ARTOTAL ELSE NARTOTAL END,0),
			0,
			ISNULL(CASE WHEN '+@CID+'=0 THEN APTOTAL ELSE NAPTOTAL END,0),
			ISNULL(CASE WHEN '+@CID+'=0 THEN YSTOTAL ELSE NYSTOTAL END,0),
			ISNULL(CASE WHEN '+@CID+'=0 THEN YFTOTAL ELSE NYFTOTAL END,0),
			ISNULL(CASE WHEN '+@CID+'=0 THEN QMTOTAL ELSE NQMTOTAL END,0),
			 '''',
			-1,
			0,
			'''',	--期初强写
			'''',
			'''',
			''''
FROM #TOTAL00
--WHERE (ISNULL(ARTOTAL,0)<>0 OR ISNULL(APTOTAL,0)<>0 OR ISNULL(YSTOTAL,0)<>0 OR ISNULL(YFTOTAL,0)<>0 OR ISNULL(QMTOTAL,0)<>0) 
UNION ALL
SELECT A.BTYPEID,
			A.BILLNUMBERID,'
IF @WhichDetail='A'
	SET @CREATESQL=@CREATESQL+' 0,'
IF @WhichDetail='P'
	SET @CREATESQL=@CREATESQL+' 
															NULL,0,0,'''', '
SET @CREATESQL=@CREATESQL+' 
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			CASE WHEN '+@CID+'=0 THEN ISNULL(BILLTOTAL,0) ELSE ISNULL(NBILLTOTAL,0) END,
			CASE WHEN '+@CID+'=0 THEN ISNULL(PREFERENCEMONEY,0) ELSE ISNULL(NPREFERENCEMONEY,0) END,--优惠金额
			CASE WHEN '+@CID+'=0 THEN ISNULL(INTOTAL	,0) 
						ELSE ISNULL(NINTOTAL	,0) END,
			CASE WHEN '+@CID+'=0 THEN ISNULL(ARTOTAL,0) ELSE ISNULL(NARTOTAL,0) END,
			CASE WHEN '+@CID+'=0 THEN ISNULL(PAYTOTAL ,0)
						ELSE ISNULL(NPAYTOTAL ,0) END,
			CASE WHEN '+@CID+'=0 THEN ISNULL(APTOTAL		 ,0) ELSE ISNULL(NAPTOTAL,0) END,
			CASE WHEN '+@CID+'=0 THEN ISNULL(YSTOTAL		 ,0) ELSE ISNULL(NYSTOTAL,0) END,
			CASE WHEN '+@CID+'=0 THEN ISNULL(YFTOTAL		,0) ELSE ISNULL(NYFTOTAL		,0) END,
			CASE WHEN '+@CID+'=0 THEN ISNULL(QMTOTAL	,0) ELSE ISNULL(NQMTOTAL	,0) END,
			A.RECONCILIATION,
			0,
			0,
			A.Comment,
			CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT(''000000000000000000''+A.BILLNUMBERID,18) AS BillSort,
			A.BillBtypeID,
			''''
FROM #BILLTOTAL A  '

SET @CREATESQL=@CREATESQL+' 
----计算合计----
INSERT INTO #RESULT
SELECT BTYPEID,
			0,'
IF @WhichDetail='A'
	SET @CREATESQL=@CREATESQL+' '''','
IF @WhichDetail='P'
	SET @CREATESQL=@CREATESQL+' '''',0,0,'''', '
SET @CREATESQL=@CREATESQL+' 
			-10,--强写-10
			NULL,
			'''',
			0,
			SUM(ISNULL(PREFERENCEMONEY,0)),--优惠金额
			SUM(ISNULL(INTOTAL	,0)),
			SUM(ISNULL(ARTOTAL		,0)),
			SUM(ISNULL(PAYTOTAL ,0)),
			SUM(ISNULL(APTOTAL		 ,0)),
			SUM(ISNULL(YSTOTAL		 ,0)),
			SUM(ISNULL(YFTOTAL		,0)),
			SUM(ISNULL(ARTOTAL,0))-SUM(ISNULL(APTOTAL,0))-SUM(ISNULL(YSTOTAL,0))+SUM(ISNULL(YFTOTAL,0)) ,
			'''',
			1,
			0,
			'''',
			'''',
			'''',
			''''
FROM #RESULT
GROUP BY BTYPEID' 

--处理只有期初和期末并且全部为零的单据不显示问题
--IF @WhichDetail='B'
--BEGIN
SET @CREATESQL=@CREATESQL+' DELETE FROM #RESULT 
															WHERE (ISNULL(CONVERT( NUMERIC(24, 10) , BILLTOTAL),0)=0 
																AND ISNULL(ARTOTAL,0)=0 
																AND ISNULL(APTOTAL,0)=0 
																AND ISNULL(YSTOTAL,0)=0 
																AND ISNULL(YFTOTAL,0)=0 
																AND ISNULL(QMTOTAL,0)=0) AND BTYPEID IN ( SELECT BTYPEID FROM #RESULT GROUP BY BTYPEID HAVING COUNT(BTYPEID)<=2 ) '
--END

--按商品显示明细是个很坑爹的东西---
IF @WhichDetail='P'
	SET @CREATESQL+=' 
		---加入商品明细信息
		INSERT INTO #RESULT
		SELECT A.BTYPEID,
					A.BILLNUMBERID,
					B.PTYPEID,
					--B.MDiscountPrice,
					CASE WHEN '+@CID+'=0 THEN B.MTaxPrice ELSE B.CurMTaxPrice END,	
					B.MQTY,
					PU.FULLNAME,
					case when A.BILLTYPE in (-1,-10) then  A.BILLTYPE else null end billtype,		
					NULL,		
					'''',		
					CASE WHEN '+@CID+'=0 THEN TaxTotal ELSE NTaxTotal END,	
					0,--优惠金额
					0,		
					0,		
					0	,
					0,		
					0,		
					0,		
					0,	
					A.RECONCILIATION,
					0,
					1,
					'''',
					CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT(''000000000000000000''+A.BILLNUMBERID,18) AS BillSort,
					'''',
					B.comment AS detailcomment
		FROM #RESULT A INNER JOIN (
					SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment FROM retailbill
						UNION ALL
						SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment FROM RetailBackBill
						UNION ALL
						SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment FROM salebill
						UNION ALL
						SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment FROM salebackbill
						UNION ALL
						SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,CASE WHEN InOrOut=''O'' THEN MQTY ELSE -MQTY END,
						MUnitID,CASE WHEN InOrOut=''O'' THEN NTaxTotal ELSE -NTaxTotal END,CASE WHEN InOrOut=''O'' THEN TaxTotal ELSE -TaxTotal END,comment FROM salegoodsexchangebill
						UNION ALL
						SELECT BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice, MQty,MUnitID,0,0,comment FROM givebill
						UNION ALL
						SELECT BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,MQty,MUnitID,0,0,comment FROM giveMEbill
						UNION ALL
						SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment FROM commissionbill
						UNION ALL
						SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment FROM buybill
						UNION ALL
						SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment FROM buybackbill
						UNION ALL
						SELECT BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,CASE WHEN InOrOut=''I'' THEN MQTY ELSE -MQTY END,
						MUnitID,CASE WHEN InOrOut=''I'' THEN NTaxTotal ELSE -NTaxTotal END,CASE WHEN InOrOut=''I'' THEN TaxTotal ELSE -TaxTotal END,comment FROM buygoodsexchangebill
						UNION ALL
						SELECT BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0,0 AS NTAXTOTAL,0 AS TAXTOTAL,comment FROM priceprotectbill
						UNION ALL
						SELECT BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0,0 AS NTAXTOTAL,0 AS TAXTOTAL,comment FROM wx_bill_getback
						UNION ALL
						SELECT BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0,0 AS TAXTOTAL,0 AS TAXTOTAL,comment FROM wx_bill_replace 
						UNION ALL
						SELECT BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0,0 AS TAXTOTAL,0 AS TAXTOTAL,comment FROM wx_bill_sendback
						UNION ALL
						SELECT BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,0,0,NTotalMoney AS NTAXTOTAL,totalmoney AS TAXTOTAL,comment FROM  dbo.BillIndex BI
						UNION ALL 
						SELECT BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,0,0,TOTAL AS NTAXTOTAL,TOTAL AS TAXTOTAL,comment FROM advantage 
		) B ON A.BILLNUMBERID=B.BILLNUMBERID
		LEFT JOIN PType_Units PU ON PU.UnitsId=B.MUNITID 
WHERE B.PTYPEID<>''''
		'
--按账户显示明细同样是个很坑爹的东西---
IF @WhichDetail='A'
BEGIN
	SET @CREATESQL+=' 
		---加入账户明细信息
		INSERT INTO #RESULT
		SELECT A.BTYPEID,
					A.BILLNUMBERID,
					b.atypeid,
					A.BILLTYPE,		
					NULL,		
					'''',		
					0,	
					0,--优惠金额
					case WHEN a.billtype not in (84,190,170,161,145,45,148,34,36,66,149,6,4,150,215,151,212) AND b.atypeid<>39 then  CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
							WHEN a.billtype=4 and b.atypeid NOT IN (39,34) then  CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							WHEN a.billtype=4 and b.atypeid IN (34) then  CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							WHEN a.billtype IN (6,150,151) AND b.atypeid<>27 THEN CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
								 else 0  end,		--实收
					0,		--应收
					case when a.billtype in (170,161,145,212) and b.atypeid<>27  then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
							when a.billtype in (149) and b.atypeid NOT IN (27,39)  then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
							WHEN a.billtype IN (215) AND b.atypeid NOT IN (27,39) then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
							when a.billtype in (45,148) and b.atypeid<>39  then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							when a.billtype in (34) and b.atypeid IN (SELECT nId FROM dbo.Ac_Items WHERE TypeName=''B'') then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							WHEN a.billtype=36 and b.atypeid<>27 THEN CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							WHEN a.billtype=66 and b.atypeid<>27 THEN CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							WHEN a.billtype=190 THEN CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							WHEN a.billtype in (84) AND b.atypeid NOT IN (39,27) then  CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
								else 0  end	,--实付
					0,		--应付
					case when b.atypeid=39 AND A.BILLTYPE not in (181,312,305,11,160,141,167,168,172,93,85,213) then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							when b.atypeid=39 AND A.BILLTYPE IN (4,181,312,305,11,160,141,167,168,172,93,85,213) then CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							WHEN b.atypeid=27 AND A.BILLTYPE IN (93,85) THEN  CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							else 0 end,		--预收
					case when b.atypeid=27 AND a.billtype NOT IN (66,150,151,36,6)  then (CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END)	
							when b.atypeid=27 AND a.billtype IN (6)  then (CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END)	
							WHEN a.billtype in (66,150,151) AND b.atypeid=27 then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END	
							WHEN a.billtype in (36) AND b.atypeid=27 
										THEN CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END	
							else 0 end,	--预付
					0,	
					A.RECONCILIATION,
					0,
					1,
					'''',
					CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT(''000000000000000000''+A.BILLNUMBERID,18) AS BillSort,
					'''',
					''''
		FROM #RESULT A INNER JOIN (
															SELECT BILLNUMBERID,ATYPEID,nTOTALmoney as nTOTAL,total AS TOTAL
															FROM BillMulAccount
															UNION ALL
															SELECT BILLNUMBERID,ATYPEID,nTOTAL,TOTAL FROM LISTTABLE WHERE BILLTYPE=4 AND ATYPEID<>33 
															UNION ALL
															SELECT BILLNUMBERID,ATYPEID,nTOTAL,TOTAL FROM LISTTABLE WHERE BILLTYPE=66 AND ATYPEID<>35 
															UNION ALL
															SELECT BILLNUMBERID,ATYPEID,nTOTAL,TOTAL FROM LISTTABLE WHERE BILLTYPE=189 and atypeid<>39
															UNION ALL
															SELECT BILLNUMBERID,ATYPEID,nTOTAL,TOTAL FROM LISTTABLE WHERE BILLTYPE=190 and atypeid<>27
															) B ON A.BILLNUMBERID=B.BILLNUMBERID WHERE B.atypeid<>24
		'
END


--SET @CREATESQL=@CREATESQL+' 
--	--DELETE FROM #RESULT WHERE BTYPEID IN ( SELECT BTYPEID FROM #RESULT GROUP BY BTYPEID HAVING COUNT(BTYPEID)<=2 ) 
--'

--最终查询--临时处理账户和商品基本信息列，右键不支持，所以单独出数据----
SET @CREATESQL=@CREATESQL+'  
;WITH pageresult AS 
(
	SELECT  ROW_NUMBER() OVER(ORDER BY A.btypeid ,A.SORTID,a.billsort,a.billcode DESC ,A.BILLTYPE) AS ID,A.* '
	IF @WhichDetail='P'
		SET @CREATESQL=@CREATESQL+',P.USERCODE AS PUSERCODE,P.FULLNAME AS PFULLNAME'
	IF @WhichDetail='A'
		SET @CREATESQL=@CREATESQL+',AC.FULLNAME AS AFULLNAME '
	SET @CREATESQL=@CREATESQL+'
	FROM #RESULT  A '
	IF @WhichDetail='P'
		SET @CREATESQL=@CREATESQL+' LEFT JOIN PTYPE P ON A.PTYPEID=P.TYPEID '
	IF @WhichDetail='A'
		SET @CREATESQL=@CREATESQL+' LEFT JOIN AC_ITEMS AC ON A.ATYPEID=AC.NID '
	SET @CREATESQL=@CREATESQL+'
	
	WHERE ('''+@IsDetail+'''=''False'' AND A.BILLTYPE IN (-1,-10)) OR '''+@IsDetail+'''=''True'' 
)
select  Convert(varchar(10),p.billdate ,23) as billdate,p.billcode,p.billtotal,
		CASE WHEN  ISNULL(p.BILLTYPE,'''')=''-1'' THEN ''期初''
			 WHEN  ISNULL(p.BILLTYPE,'''')=''-10'' THEN ''期末''
			 ELSE ISNULL(bn.billname,'''') END  AS billtype,'
IF @WhichDetail='P'
		SET @CREATESQL=@CREATESQL+'p.price,p.qty,p.ptypeid,p.ufullname,p.pusercode,p.pfullname,'
SET @CREATESQL=@CREATESQL+'
		p.preferencemoney,p.intotal,p.artotal,p.ystotal,p.qmtotal,p.reconciliation,p.comment,p.aptotal,
		p.paytotal,p.yftotal,p.btypeid,b.FullName AS bfullname,b.usercode AS busercode
FROM pageresult p
INNER JOIN dbo.btype b ON p.btypeid=b.typeId
LEFT JOIN dbo.BillName bn ON p.BILLTYPE=bn.Billtype
ORDER BY p.btypeid ,p.SORTID,p.billsort,p.billcode DESC ,p.BILLTYPE 

insert into #totalpagetable(totalpage )
select count(1) totalcount from #RESULT

--删除临时表
DROP TABLE #BILLINDEX	,#TOTAL00,#BILLTOTAL,#RESULT'
--PRINT(@CREATESQL)

EXEC(@CREATESQL)

select @totalpage=totalpage from #totalpagetable

drop table #totalpagetable

--;WITH pageresult AS 
--(
--	SELECT  ROW_NUMBER() OVER(ORDER BY A.btypeid ,A.SORTID,a.billsort,a.billcode DESC ,A.BILLTYPE) AS ID,A.* '
--	IF @WhichDetail='P'
--		SET @CREATESQL=@CREATESQL+',P.USERCODE AS PUSERCODE,P.FULLNAME AS PFULLNAME'
--	IF @WhichDetail='A'
--		SET @CREATESQL=@CREATESQL+',AC.FULLNAME AS AFULLNAME '
--	SET @CREATESQL=@CREATESQL+'
--	FROM #RESULT  A '
--	IF @WhichDetail='P'
--		SET @CREATESQL=@CREATESQL+' LEFT JOIN PTYPE P ON A.PTYPEID=P.TYPEID '
--	IF @WhichDetail='A'
--		SET @CREATESQL=@CREATESQL+' LEFT JOIN AC_ITEMS AC ON A.ATYPEID=AC.NID '
--	SET @CREATESQL=@CREATESQL+'
	
--	WHERE ('''+@IsDetail+'''=''False'' AND A.BILLTYPE IN (-1,-10)) OR '''+@IsDetail+'''=''True'' 
--)
--select TOP '+@pagesize+'  Convert(varchar(10),p.billdate ,23) as billdate,p.billcode,p.billtotal,
--		CASE WHEN  ISNULL(p.BILLTYPE,'''')=''-1'' THEN ''期初''
--			 WHEN  ISNULL(p.BILLTYPE,'''')=''-10'' THEN ''期末''
--			 ELSE ISNULL(bn.billname,'''') END  AS billtype,'
--IF @WhichDetail='P'
--		SET @CREATESQL=@CREATESQL+'p.price,p.qty,p.ptypeid,p.ufullname,p.pusercode,p.pfullname,'
--SET @CREATESQL=@CREATESQL+'
--		p.preferencemoney,p.intotal,p.artotal,p.ystotal,p.qmtotal,p.reconciliation,p.comment,p.aptotal,
--		p.yftotal,p.btypeid,b.FullName AS bfullname,b.usercode AS busercode
--FROM pageresult p
--INNER JOIN dbo.btype b ON p.btypeid=b.typeId
--LEFT JOIN dbo.BillName bn ON p.BILLTYPE=bn.Billtype
--WHERE P.ID > '+@pagesize+'*('+@page+'-1)

--insert into #totalpagetable(totalpage )
--select count(1) totalcount from #RESULT

----删除临时表
--DROP TABLE #BILLINDEX	,#TOTAL00,#BILLTOTAL,#RESULT'



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OtherBillBusiNessType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OtherBillBusiNessType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：WG
	日期：2014-4-3
	描述：业务类别selector
	
-------------------------------------------*/
CREATE PROCEDURE Web_OtherBillBusiNessType
(
	@Filter		VARCHAR(256),	---输入的条件
	@Flag		VARCHAR(20),  ---单据类型
	@OperatorId VARCHAR(100),
	@TypeName	VARCHAR(50),  --TYPENAME
	@StockIn    INT,
	@StockOut	INT,
	@Stock		INT
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Ac_Items(TypeID	VARCHAR(50))

IF @Flag = 'INTYPE'
BEGIN
	INSERT INTO #Ac_Items(TypeId) 
	SELECT nid FROM F_GetManDetailATypeSr(@OperatorId)
	UNION
	SELECT nId FROM Ac_Items A --WHERE A.nId BETWEEN 3 AND 12
	WHERE nTypeId LIKE '00003%' AND LEFT(nTypeId,10) <> '0000300003'
		  AND SonNum = 0
END
ELSE IF @Flag = 'OUTTYPE'
BEGIN
	INSERT INTO #Ac_Items(TypeId) 
	SELECT nid FROM F_GetManDetailATypeFy(@OperatorId)
	UNION
	SELECT nId FROM Ac_Items 
	WHERE nTypeId LIKE '00004%' AND LEFT(nTypeId,10) <> '0000400003'
		 AND SonNum = 0
END
ELSE 
BEGIN
	INSERT INTO #Ac_Items(TypeId) 
	SELECT nid FROM F_GetManDetailATypeSr(@OperatorId)
	UNION
	SELECT nId FROM Ac_Items A --WHERE A.nId BETWEEN 3 AND 12
	WHERE nTypeId LIKE '00003%' AND LEFT(nTypeId,10) <> '0000300003'
		  AND SonNum = 0
		  
	INSERT INTO #Ac_Items(TypeId) 
	SELECT nid FROM F_GetManDetailATypeFy(@OperatorId)
	UNION
	SELECT nId FROM Ac_Items 
	WHERE nTypeId LIKE '00004%' AND LEFT(nTypeId,10) <> '0000400003'
		 AND SonNum = 0
END

INSERT INTO #Ac_Items(TypeID) VALUES ('')

DECLARE @SQL varchar(max)

SET @SQL= 'SELECT   o.id as typeid,
					o.fullname,
					o.atypeid,
					case when o.InOutType = 0 then ''入库''
						 when o.InOutType = 1 then ''出库''
						 when o.InOutType = 2 then ''出入库''
						 else ''''
						 END AS type
            FROM    OtherInOutType o   
			WHERE o.FullName LIKE ''%' + @Filter + '%'''

IF @Flag='INTYPE'
	SET @SQL += ' and o.atypeid1 IN (SELECT TypeId FROM #Ac_Items)  '
ELSE IF @Flag='OUTTYPE'
	SET @SQL += ' and o.atypeid IN (SELECT TypeId FROM #Ac_Items)  '
ELSE
	 SET @SQL += ' and o.atypeid IN (SELECT TypeId FROM #Ac_Items) and o.atypeid1 IN (SELECT TypeId FROM #Ac_Items) '

IF @Flag='INTYPE'
   SET @SQL = @SQL + ' AND (o.InOutType = 0 OR o.InOutType = 2) '
ELSE IF @Flag='OUTTYPE'
   SET @SQL = @SQL + ' AND (o.InOutType = 1 OR o.InOutType = 2) '

IF @Flag = ''
BEGIN
	IF @Stock = 0
	SET @SQL += ' AND O.InOutType <> 2 '
IF @StockIn = 0
	SET @SQL += ' AND O.InOutType <> 0 '
IF @StockOut = 0
	SET @SQL += ' AND O.InOutType <> 1 '
END

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Ac_Items

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OutDate_Gathering]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OutDate_Gathering]
GO

/*
	作者：谢吉康

	日期：2007-11-29

	描述：超期应收款的查询
	
	修改：舒珊
	日期：2016年2月25日
	描述：增添表头自定义显示字段
*/
CREATE PROCEDURE Web_OutDate_Gathering(
	@OperatorId	VARCHAR(100),		--操作员ID
	@LDDate1	VARCHAR(20),		--录单日期
	@LDDate2	VARCHAR(20),		--录单日期
	@XQDate1	VARCHAR(20),		--限期日期
	@XQDate2	VARCHAR(20),		--限期日期
	@BTypeID	VARCHAR(8000),		--往来单位ID
	@KTypeID	VARCHAR(8000),		--仓库ID
	@ETypeID	VARCHAR(8000),		--经手人ID
	@STypeID	VARCHAR(8000),		--分支机构
	@BillCode	VARCHAR(256),		--单据编号
	@Explain	VARCHAR(256),		--摘要
	@Note		VARCHAR(256),		--说明
	@QueryType	INT,				--查询类别    1.超期应收款  2.临近的超期应收款  3.无收款期限的单据
	@IncludeQc  INT=0,               --是否包含期初单据，默认为0不包含期初单据
	@pageno		INT = -1,	--页码
	@tqyj		VARCHAR(20), --提前报警天数
	@billtype   VARCHAR(1000), --查询的单据类型
	@isLoginHit	INT=0	  --报警簿是否需要红色提示
)
--@encode$--
AS

SET NOCOUNT ON 

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--单位：
CREATE TABLE #GetSelBTypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S

--职员：
CREATE TABLE #GetSelETypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S

--仓库：
CREATE TABLE #GetSelKTypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelKTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
IF NOT @MDTypeId = '00000'
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)		

IF isnull(@XQDate1,'')=''
	SET @XQDate1=''
IF  isnull(@XQDate2,'')=''
	SET @XQDate2=''

	DECLARE	@Condition VARCHAR(8000)=''
	DECLARE @ExpenseToAr VARCHAR(10)='0'
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

-- 获取当前日期
DECLARE @CruDate	VARCHAR(10)
SET @CruDate = CONVERT(VARCHAR(10),GETDATE(),120)

DECLARE @UserDeRowCount	int

IF @billtype='-1'
	SET @billtype=''

SELECT @UserDeRowCount = ISNULL(UserDeRowCount,'0') FROM LoginUser WHERE ETypeId = @OperatorID
IF @UserDeRowCount = 0
	SET @UserDeRowCount = 14

--处理参数变化
IF @BTypeId = '00000'
	SET @BTypeID = '%'
IF @KTypeID = '00000' OR @KTypeID=''
	SET @KTypeID = '%'

IF @QueryType = 1
	BEGIN
		SET @Condition = ' 	AND Bil.AlertDay<>''9999'''
		
		IF @XQDate1<>'' AND @XQDate2<>''
			SET @Condition = @Condition+' 	
								AND DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate), '+CHAR(39)+@CruDate+CHAR(39)+')>='+CHAR(39)+@XQDate1+CHAR(39)+'
								AND DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate), '+CHAR(39)+@CruDate+CHAR(39)+')<='+CHAR(39)+@XQDate2+CHAR(39)
		IF ISNULL(@tqyj,'')<>''
			SET	@Condition=@Condition+' AND DATEDIFF(DAY, '+CHAR(39)+@CruDate+CHAR(39)+',DATEADD(DAY, Bil.alertday, Bil.BillDate))<= bb.cqdays
										AND bb.cqdays<='+CHAR(39)+@tqyj+CHAR(39)
		
		IF @XQDate1='' AND @XQDate2=''   AND ISNULL(@tqyj,'')=''
			SET @Condition = @Condition+' 
								AND DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate), '+CHAR(39)+@CruDate+CHAR(39)+')>=0 '
		
		
	END
ELSE IF @QueryType = 3
		SET @Condition = ' AND ISNULL(Bil.AlertDay,9999)=9999 '
ELSE
	BEGIN
		SET @Condition = ' 	AND Bil.AlertDay<>''9999'''
		IF @XQDate1='' AND @XQDate2=''  -- AND ISNULL(@tqyj,'')=''
			SET @Condition = @Condition+' 	AND DATEDIFF(DAY,DATEADD(DAY,Bil.AlertDay,Bil.BillDate),GETDATE())<=0 
								'
		IF @XQDate1<>'' AND @XQDate2<>''
			SET @Condition = @Condition+' 
								AND DATEDIFF(DAY,DATEADD(DAY,Bil.AlertDay,Bil.BillDate),GETDATE())<=0
								AND ABS(DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate),GetDate()))>='+CHAR(39)+@XQDate1+CHAR(39)+'
								AND ABS(DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate),GetDate()))<='+CHAR(39)+@XQDate2+CHAR(39)
		/*IF ISNULL(@tqyj,'')<>''
			SET	@Condition=@Condition+' AND  ABS(DATEDIFF(DAY, '+CHAR(39)+@CruDate+CHAR(39)+',DATEADD(DAY, Bil.alertday, Bil.BillDate)))<= bb.cqdays
										AND bb.cqdays<='+CHAR(39)+@tqyj+CHAR(39) */
	END
		
DECLARE @Sqlfapiao VARCHAR(MAX)--发票专用
DECLARE @SqlNormal VARCHAR(MAX)--普通单据
DECLARE @SqlArap	VARCHAR(max)--应收增加、减少用

DECLARE @SQL VARCHAR(max)=''
SELECT	@SqlNormal = '
	SELECT	Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillType,'

	IF @QueryType IN (1,2)
		SELECT @SqlNormal = @SqlNormal +' (Bil.BillDate+Bil.AlertDay) AS AlertDay,'
	ELSE
		SELECT @SqlNormal = @SqlNormal +' '''' AS AlertDay,'

	SELECT @SqlNormal = @SqlNormal +' 
			Bil.BillCode,
			Bil.BTypeId,
			Bil.KTypeId,
			Bil.ETypeId,
			Bil.STypeId,
			CASE WHEN bil.billtype IN (11,160,141,93,85,167,168,172,181,213,312,12,424) 
						THEN Bil.nTotalMoney
					 WHEN BillType IN (45,148,149,46,426) 
						THEN -Bil.nTotalMoney
					 WHEN Billtype =36 and Bil.btypeid like ''00001%'' AND '+@ExpenseToAr+'=''1''
						THEN -Bil.nTotalMoney
					 WHEN Billtype= 450 
						THEN Bil.nTotalMoney
					ELSE 0 
			END AS TotalMoney  ,
			--Bil.nTotalMoney as TotalMoney,
			--(Bil.nTotalMoney-ISNULL(Bil.nTotalinMoney,0)-ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.npreferenceMoney,0)-ISNULL(Bil.nChargeOffTotal,0)) AS LeftTotalMoney,
			CASE WHEN bil.billtype IN (11,160,141,93,85,167,168,172,181,213,312,12,424) 
						THEN bil.ntotalmoney-bil.npreferencemoney-bil.nCompleteTotal-bil.ntotalinmoney-isnull(bil.nChargeOffTotal,0) 
					 WHEN BillType IN (45,148,149,46,426) 
						THEN -(bil.ntotalmoney-bil.npreferencemoney-bil.nCompleteTotal-bil.ntotalinmoney-isnull(bil.nChargeOffTotal,0))
					 WHEN Billtype =36 and Bil.btypeid like ''00001%'' AND '+@ExpenseToAr+'=''1''
						THEN -(bil.ntotalmoney-bil.npreferencemoney-bil.nCompleteTotal-bil.ntotalinmoney-isnull(bil.nChargeOffTotal,0))
					 WHEN Billtype= 450 
						THEN  bil.ntotalmoney-isnull(bil.nChargeOffTotal,0)
					ELSE 0 
				END AS LeftTotalMoney  ,
			Bil.Comment,
			Bil.Explain,
			ss.fullname as sfullname, --必须加这些fullname个人首页要用
			emp.fullname as efullname,
			bb.fullname as bfullname,
			stk.fullname as kfullname,
			0 as detailid 
	FROM 	(SELECT BillNumberId,BillType,Stypeid,Comment,BillDate,BillCode,ETypeId,TotalMoney,NTotalMoney,btypeid,ktypeid
			,AlertDay,ifcheck,RedWord,ifYearBill,IsIni,jsState,IfStopMoney,ChargeOffType,
			npreferencemoney,NCompleteTotal,NTotalInMoney,NChargeOffTotal,explain,DTypeId FROM dbo.BillIndex
			UNION ALL 
			SELECT BillNumberId,BillType,STypeId,Comment,BillDate,BillCode,ETypeId,TotalMoney,NTotalMoney,BTypeId,
			CASE WHEN OutKTypeId IS NULL THEN InKTypeId
			ELSE OutKTypeId end AS ktypeid,9999 AlertDay,IfCheck,RedWord,IfYearBill,IsIni,JsState,0 AS IfStopMoney,0 ChargeOffType,
			npreferencemoney,NCompleteTotal,NTotalInMoney,NChargeOffTotal,Explain,DTypeId
			FROM dbo.Coupon_BillIndex ) Bil  '
			
			
SELECT @SqlNormal=@SqlNormal+'	
	INNER JOIN Stype ss ON  ss.typeid=Bil.STypeId
	INNER JOIN Employee emp ON emp.typeid=Bil.ETypeId
	INNER JOIN btype bb ON bb.typeid=Bil.BTypeId
	left JOIN stock stk ON stk.typeid=Bil.KTypeId '

	IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002' AND (@BTypeId = '' OR @BTypeId = '%'))
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetSelBTypeId B ON Bil.BTypeId = B.TypeId '

	IF NOT (@ETypeId = '' AND @METypeId = '00001')
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetSelETypeId E ON Bil.ETypeId = E.TypeId '

	/*IF NOT ((@KTypeId = '00000' OR @KTypeId = '%') AND @MKTypeId = '00000')
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetSelKTypeId K ON Bil.KTypeId = K.TypeId '*/
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '		
		
	IF NOT @MDTypeId = '00000'
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Bil.DTypeId '			

    DECLARE @isiniWhere VARCHAR(100)
        SET @isiniWhere=''
         IF @IncludeQc=1
            BEGIN
                 SET @isiniWhere=' OR Bil.isini=1'
            END
       ELSE
            BEGIN
                 SET @isiniWhere=' AND Bil.isini<>1'
            END
	SET @SqlNormal = @SqlNormal + '
	WHERE	bil.billtype in(11,160,141,93,85,167,168,172,181,213,312,45,148,149,36,450,12,46,424,426) '+@Condition+'
			AND ((Bil.IfCheck = ''t'' AND Bil.RedWord = 0 AND Bil.IfYearBill = 0) '+@isiniWhere+' )
			--AND (Bil.nTotalMoney - ISNULL(Bil.nTotalinMoney,0) - ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.npreferenceMoney,0)-ISNULL(Bil.nChargeOffTotal,0)) <> 0
			AND Bil.jsState<>2
			AND (Bil.ifStopMoney=''0'' or Bil.IfStopMoney IS NULL)
			AND (bil.billtype<>450 OR (bil.billtype=450 AND bil.ChargeOffType in(2,5) ) )'

	IF @ExpenseToAr='0'
	  SET @SqlNormal = @SqlNormal + ' AND bil.billtype<>36  '
	IF ISNULL(@billtype,'')<>''
		SET @SqlNormal = @SqlNormal + ' AND bil.billtype in ('+	@billtype+') '
	 IF NOT ((@KTypeId = '00000' OR @KTypeId = '%') AND @MKTypeId = '00000')
		 SET @SqlNormal = @SqlNormal + ' AND (bil.ktypeid IN(SELECT typeid from #GetSelKTypeId) or bil.billtype=450) '
IF @QueryType IN (1,2)
	SELECT  @SqlNormal = @SqlNormal + ' 
			AND Bil.BillDate>='+CHAR(39)+@LDDate1+CHAR(39)+'
			AND Bil.BillDate<='+CHAR(39)+@LDDate2+CHAR(39)+'
			AND Bil.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
			AND Bil.Comment LIKE '+CHAR(39)+'%'+@Explain+'%'+CHAR(39)+'
			AND Bil.Explain LIKE '+CHAR(39)+'%'+@Note+'%'+CHAR(39)

---------------------发票数据（发票没有主表没有仓库、优惠金额、实收金额）
SELECT	@Sqlfapiao = '
	SELECT	Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillType,'

	IF @QueryType IN (1,2)
		SELECT @Sqlfapiao = @Sqlfapiao +' (Bil.BillDate+Bil.AlertDay) AS AlertDay,'
	ELSE
		SELECT @Sqlfapiao = @Sqlfapiao +' '''' AS AlertDay,'
SELECT @Sqlfapiao = @Sqlfapiao +' 
			Bil.BillCode,
			Bil.BTypeId,
			'''' as ktypeid,
			Bil.ETypeId,
			Bil.STypeId,
			Bil.ntaxTotalMoney AS TotalMoney,
			(Bil.ntaxTotalMoney-ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.nChargeOffTotal,0)) AS LeftTotalMoney,
			Bil.Comment,
			Bil.Explain,
			ss.fullname as sfullname, --必须加这些fullname个人首页要用
			emp.fullname as efullname,
			bb.fullname as bfullname,
			'''' as kfullname ,
			0 AS detailid
			FROM 	ReceiptBillIndex Bil
			 '
			
			
SELECT @Sqlfapiao=@Sqlfapiao+'	
	INNER JOIN Stype ss ON  ss.typeid=Bil.STypeId
	INNER JOIN Employee emp ON emp.typeid=Bil.ETypeId
	INNER JOIN btype bb ON bb.typeid=Bil.BTypeId '

	IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002' AND (@BTypeId = '' OR @BTypeId = '%'))
		SET @Sqlfapiao = @Sqlfapiao + ' INNER JOIN #GetSelBTypeId B ON Bil.BTypeId = B.TypeId '

	IF NOT (@ETypeId = '' AND @METypeId = '00001')
		SET @Sqlfapiao = @Sqlfapiao + ' INNER JOIN #GetSelETypeId E ON Bil.ETypeId = E.TypeId '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @Sqlfapiao = @Sqlfapiao + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '		
		
	IF NOT @MDTypeId = '00000'
		SET @Sqlfapiao = @Sqlfapiao + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Bil.DTypeId '			
	SET @Sqlfapiao = @Sqlfapiao + '
	WHERE	Bil.BillType = 405 '+@Condition+'
			AND ((Bil.IfCheck = ''t'' AND Bil.RedWord = 0 AND Bil.IfYearBill = 0) '+@isiniWhere+' )
			--AND (Bil.nTotalMoney - ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.nChargeOffTotal,0)) > 0
			AND Bil.jsState<>2
			AND (Bil.ifStopMoney=''0'' or Bil.IfStopMoney IS NULL)'
	IF ISNULL(@billtype,'')<>''
		SET @Sqlfapiao = @Sqlfapiao + ' AND bil.billtype in ('+	@billtype+') '
		
IF @QueryType IN (1,2)
	SELECT  @Sqlfapiao = @Sqlfapiao + ' 
			AND Bil.BillDate>='+CHAR(39)+@LDDate1+CHAR(39)+'
			AND Bil.BillDate<='+CHAR(39)+@LDDate2+CHAR(39)+'
			AND Bil.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
			AND Bil.Comment LIKE '+CHAR(39)+'%'+@Explain+'%'+CHAR(39)+'
			AND Bil.Explain LIKE '+CHAR(39)+'%'+@Note+'%'+CHAR(39)

---------------------应收增加单、减少单（主表没有仓库、往来单位、优惠金额、实收金额、没有结算，按明细统计）
SELECT	@SqlArap = '
	SELECT	Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillType,'

	IF @QueryType IN (1,2)
		SELECT @SqlArap = @SqlArap +' (Bil.BillDate+ad.AlertDay) AS AlertDay,'
	ELSE
		SELECT @SqlArap = @SqlArap +' '''' AS AlertDay,'
SELECT @SqlArap = @SqlArap +' 
			Bil.BillCode,
			AD.BTypeId,
			'''' as ktypeid,
			Bil.ETypeId,
			Bil.STypeId,
			CASE WHEN Bil.billtype = 116
					THEN ad.total
				WHEN Bil.billtype = 115
					THEN -ad.total
			ELSE 0
			END AS  TotalMoney,
			CASE WHEN Bil.billtype = 116
				THEN ad.total -ad.CompleteTotal-isnull(ad.ChargeOffTotal,0)
			 WHEN Bil.billtype = 115
				THEN -(ad.total -ad.CompleteTotal -isnull(ad.ChargeOffTotal,0))
			ELSE 0
			END AS LeftTotalMoney,
			--(Bil.ntaxTotalMoney-ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.nChargeOffTotal,0)) AS LeftTotalMoney,
			Bil.Comment,
			Bil.Explain,
			ss.fullname as sfullname, --必须加这些fullname个人首页要用
			emp.fullname as efullname,
			bb.fullname as bfullname,
			'''' as kfullname,
			ad.id as detailid 
	FROM 	BillIndex Bil
	INNER JOIN AdDebtBill AD ON Bil.billnumberid=ad.billnumberid
			 '
SELECT @SqlArap=@SqlArap+'	
	INNER JOIN Stype ss ON  ss.typeid=Bil.STypeId
	INNER JOIN Employee emp ON emp.typeid=Bil.ETypeId
	INNER JOIN btype bb ON bb.typeid=AD.BTypeId '

	IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002' AND (@BTypeId = '' OR @BTypeId = '%'))
		SET @SqlArap = @SqlArap + ' INNER JOIN #GetSelBTypeId B ON AD.BTypeId = B.TypeId '

	IF NOT (@ETypeId = '' AND @METypeId = '00001')
		SET @SqlArap = @SqlArap + ' INNER JOIN #GetSelETypeId E ON Bil.ETypeId = E.TypeId '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SqlArap = @SqlArap + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '		
		
	IF NOT @MDTypeId = '00000'
		SET @SqlArap = @SqlArap + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Bil.DTypeId '			
	SET @SqlArap = @SqlArap + '
	WHERE	Bil.BillType IN(115,116) '+REPLACE(@Condition,'Bil.alertday','ad.alertday')+'
			AND ((Bil.IfCheck = ''t'' AND Bil.RedWord = 0 AND Bil.IfYearBill = 0) '+@isiniWhere+' )
			AND ad.total -ad.CompleteTotal-isnull(ad.ChargeOffTotal,0)>0
			AND (ad.ifStopMoney=''0'' or ad.IfStopMoney IS NULL)'
	IF ISNULL(@billtype,'')<>''
		SET @SqlArap = @SqlArap + ' AND bil.billtype in ('+	@billtype+') '
IF @QueryType IN (1,2)
	SELECT  @SqlArap = @SqlArap + ' 
			AND Bil.BillDate>='+CHAR(39)+@LDDate1+CHAR(39)+'
			AND Bil.BillDate<='+CHAR(39)+@LDDate2+CHAR(39)+'
			AND Bil.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
			AND Bil.Comment LIKE '+CHAR(39)+'%'+@Explain+'%'+CHAR(39)+'
			AND Bil.Explain LIKE '+CHAR(39)+'%'+@Note+'%'+CHAR(39)


			
SELECT @SQL=@SqlNormal+' UNION ALL '+@Sqlfapiao	+ ' UNION ALL '+ @SqlArap

IF @isLoginHit=1
BEGIN
	SET @SQL  =' select top 1 ''gatheringhit'',1 from ('+@SQL+')P '
END

IF @isLoginHit=0 AND @pageno<>-1
BEGIN
	SET @SQL ='SELECT P.*,
					SysDiy1_head,
					SysDiy2_head,
					SysDiy3_head,
					SysDiy4_head, 
					SysDiy5_head,
					SysDiy6_head,
					SysDiy7_head,
					SysDiy8_head,
					SysDiy9_head,
					SysDiy10_head,
					SysDiy11_head,
					SysDiy12_head,
					SysDiy13_head,
					SysDiy14_head,
					SysDiy15_head,
					SysDiy16_head,
					SysDiy17_head,
					SysDiy18_head,
					SysDiy19_head,
					SysDiy20_head,
					SysDiy21_head,
					SysDiy22_head,
					SysDiy23_head,
					SysDiy24_head,
					SysDiy25_head,
					SysDiy26_head,
					SysDiy27_head,
					SysDiy28_head,
					SysDiy29_head,
					SysDiy30_head,
					SysDiy31_head,
					SysDiy32_head
	 FROM ('+@SQL+')P
	 LEFT JOIN Custom_BillIndex csindex on P.billnumberid=csindex.BillId and P.billtype=csindex.billtype
	 ORDER BY p.BillDate,p.BillCode '
END
--PRINT(@SQL1)	
--print @SQL																			   
EXEC(@SQL)


DROP TABLE #GetSelBTypeId,#GetSelETypeId,#GetSelKTypeId,#GetManSTypeId,#GetManDTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OutDate_Pay]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OutDate_Pay]
GO

/*
	作者：谢吉康

	日期：2004-09-15

	描述：超期应付款的查询
	
	修改：舒珊
	日期：2016年2月25日
	描述：增添表头自定义显示字段
*/
CREATE PROCEDURE Web_OutDate_Pay(
	@OperatorId	VARCHAR(50),		--操作员ID
	@LDDate1	VARCHAR(20),		--录单日期
	@LDDate2	VARCHAR(20),		--录单日期
	@XQDate1	VARCHAR(20),		--限期日期
	@XQDate2	VARCHAR(20),		--限期日期
	@BTypeID	VARCHAR(8000),		--往来单位ID
	@KTypeID	VARCHAR(8000),		--仓库ID
	@ETypeID	VARCHAR(8000),		--经手人ID
	@STypeID	VARCHAR(8000),		--分支机构
	@BillCode	VARCHAR(256),		--单据编号
	@Explain	VARCHAR(256),		--摘要
	@Note		VARCHAR(256),		--说明
	@QueryType	INT,				--查询类别    1.超期应付款  2.临近的超期应付款  3.无付款期限的单据
	@IncludeQc  INT=0,               --是否包含期初单据，默认为0不包含期初单据
	@tqyj		VARCHAR(20), --提前报警天数
	@billtype   VARCHAR(1000), --查询的单据类型
	@isLoginHit	INT=0  --报警簿是否需要红色提示
)
--@encode$--
AS

SET NOCOUNT ON 

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @proinfo int

SELECT @proinfo=subvalue FROM sysdata WHERE subname='proinfo' 



--单位：
CREATE TABLE #GetSelBTypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S

--职员：
CREATE TABLE #GetSelETypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S

--仓库：
CREATE TABLE #GetSelKTypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelKTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
IF NOT @MDTypeId = '00000'
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

DECLARE @SQL VARCHAR(max),
		@Condition VARCHAR(8000)

IF @billtype='-1'
	SET @billtype=''
-- 获取当前日期
DECLARE @CruDate	VARCHAR(10)
SET @CruDate = CONVERT(VARCHAR(10),GETDATE(),120)

	DECLARE @ExpenseToAr VARCHAR(10)='0'
	SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

IF isnull(@XQDate1,'')=''
	SET @XQDate1=''
IF  isnull(@XQDate2,'')=''
	SET @XQDate2=''

--处理参数变化
IF @BTypeId = '00000'
	SET @BTypeID = '%'
IF @KTypeID = '00000' OR @KTypeID=''
	SET @KTypeID = '%'

IF @QueryType = 1
	BEGIN
		SET @Condition = ' 	AND Bil.AlertDay<>''9999'''
		IF @XQDate1='' AND @XQDate2=''   AND ISNULL(@tqyj,'')=''
			SET @Condition = @Condition+'
								AND DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate), '+CHAR(39)+@CruDate+CHAR(39)+')>=0 '
		IF @XQDate1<>'' AND @XQDate2<>''
			SET @Condition = @Condition+' 
								AND DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate), '+CHAR(39)+@CruDate+CHAR(39)+')>='+char(39)+@XQDate1+char(39)+'
								AND DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate), '+CHAR(39)+@CruDate+CHAR(39)+')<='+char(39)+@XQDate2+char(39)
			IF ISNULL(@tqyj,'')<>''
			SET	@Condition=@Condition+' AND DATEDIFF(DAY, '+CHAR(39)+@CruDate+CHAR(39)+',DATEADD(DAY, Bil.alertday, Bil.BillDate))<= bb.fkcqdays
										AND bb.fkcqdays<='+CHAR(39)+@tqyj+CHAR(39)
	END
ELSE IF @QueryType = 3
		SET @Condition = ' AND ISNULL(Bil.AlertDay,9999)=9999 '
ELSE
	BEGIN
		IF @XQDate1='' AND @XQDate2=''  -- AND ISNULL(@tqyj,'')=''
			SET @Condition = ' 	AND DATEDIFF(DAY,DATEADD(DAY,Bil.AlertDay,Bil.BillDate),GETDATE())<=0 
								AND Bil.AlertDay<>''9999'''
		IF @XQDate1<>'' AND @XQDate2<>''
			SET @Condition = ' 	AND Bil.AlertDay<>''9999''
								AND DATEDIFF(DAY,DATEADD(DAY,Bil.AlertDay,Bil.BillDate),GETDATE())<=0
								AND ABS(DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate),GetDate()))>='+char(39)+@XQDate1+char(39)+'
								AND ABS(DATEDIFF(DAY, DATEADD(DAY, Bil.alertday, Bil.BillDate),GetDate()))<='+char(39)+@XQDate2+char(39)
		/*IF ISNULL(@tqyj,'')<>''
			SET	@Condition=@Condition+' AND  ABS(DATEDIFF(DAY, '+CHAR(39)+@CruDate+CHAR(39)+',DATEADD(DAY, Bil.alertday, Bil.BillDate)))<= bb.fkcqdays
										AND bb.fkcqdays<='+CHAR(39)+@tqyj+CHAR(39)*/
	END
		
DECLARE @Sqlfapiao VARCHAR(MAX)--发票专用
DECLARE @SqlNormal VARCHAR(MAX)--普通单据
DECLARE @SqlArap	VARCHAR(max)--应付增加、减少用

-------------------------普通单据
SELECT	@SqlNormal = '
	SELECT	Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillType,'

	IF @QueryType IN (1,2)
		SELECT @SqlNormal = @SqlNormal +' (Bil.BillDate+Bil.AlertDay) AS AlertDay,'
	ELSE
		SELECT @SqlNormal = @SqlNormal +' '''' AS AlertDay,'

	SELECT @SqlNormal = @SqlNormal +' 
			Bil.BillCode,
			Bil.BTypeId,
			Bil.KTypeId,
			Bil.ETypeId,
			Bil.STypeId,
			CASE WHEN bil.billtype IN (34,161,145,84,170,212)  
						THEN Bil.nTotalMoney
					 WHEN BillType IN (6,150,151) 
						THEN -Bil.nTotalMoney
					 WHEN Billtype =36 and  (Bil.btypeid like ''00002%'' or '+@ExpenseToAr+'=''0'')
						THEN Bil.nTotalMoney
					 WHEN Billtype= 450 
						THEN Bil.nTotalMoney
					ELSE 0 
			END AS TotalMoney  ,
			--Bil.nTotalMoney as TotalMoney,
			--(Bil.nTotalMoney-ISNULL(Bil.nTotalinMoney,0)-ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.npreferenceMoney,0)-ISNULL(Bil.nChargeOffTotal,0)) AS LeftTotalMoney,
			CASE WHEN bil.billtype IN (34,161,145,84,170,212)  
						THEN bil.ntotalmoney-bil.npreferencemoney-bil.nCompleteTotal-bil.ntotalinmoney-isnull(bil.nChargeOffTotal,0) 
					 WHEN BillType IN (6,150,151) 
						THEN -(bil.ntotalmoney-bil.npreferencemoney-bil.nCompleteTotal-bil.ntotalinmoney-isnull(bil.nChargeOffTotal,0))
					 WHEN Billtype =36 and (Bil.btypeid like ''00002%'' or '+@ExpenseToAr+'=''0'')
						THEN bil.ntotalmoney-bil.npreferencemoney-bil.nCompleteTotal-bil.ntotalinmoney-isnull(bil.nChargeOffTotal,0)
					 WHEN Billtype= 450 
						THEN  bil.ntotalmoney-isnull(bil.nChargeOffTotal,0)
					ELSE 0 
				END AS LeftTotalMoney  ,
			Bil.Comment,
			Bil.Explain,
			ss.fullname as sfullname,
			emp.fullname as efullname,
			bb.fullname as bfullname,
			stk.fullname as kfullname,
			0 as detailid
			
	FROM 	BillIndex Bil
			INNER JOIN Stype ss ON  ss.typeid=Bil.STypeId
			INNER JOIN Employee emp ON emp.typeid=Bil.ETypeId
			INNER JOIN btype bb ON bb.typeid=Bil.BTypeId
			left JOIN stock stk ON stk.typeid=Bil.KTypeId '

	IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002' AND (@BTypeId = '' OR @BTypeId = '%'))
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetSelBTypeId B ON Bil.BTypeId = B.TypeId '

	IF NOT (@ETypeId = '' AND @METypeId = '00001')
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetSelETypeId E ON Bil.ETypeId = E.TypeId '

	/*IF NOT ((@KTypeId = '00000' OR @KTypeId = '%') AND @MKTypeId = '00000')
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetSelKTypeId K ON (Bil.KTypeId = K.TypeId or bil.billtype=450) '   */
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '			
		
	IF NOT @MDTypeId = '00000'
		SET @SqlNormal = @SqlNormal + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Bil.DTypeId '			

    DECLARE @isiniWhere VARCHAR(100)
        SET @isiniWhere=''
         IF @IncludeQc=1
            BEGIN
                 SET @isiniWhere=' OR Bil.isini=1'
            END
       ELSE
            BEGIN
                 SET @isiniWhere=' AND Bil.isini<>1 '
            END
	SET @SqlNormal = @SqlNormal + '
	WHERE	Bil.BillType in(34,6,161,145,151,150,36,84,212,170,128,129,404,450,414) '+@Condition+'
			AND ((Bil.IfCheck = ''t'' AND Bil.RedWord = 0 AND Bil.IfYearBill = 0) '+@isiniWhere+')
			--AND (Bil.nTotalMoney - ISNULL(Bil.nTotalinMoney,0) - ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.npreferenceMoney,0)-ISNULL(Bil.nChargeOffTotal,0)) > 0
			AND Bil.jsState<>2
			AND (Bil.ifStopMoney=''0'' or Bil.IfStopMoney IS NULL)
			AND (bil.billtype<>450 OR (bil.billtype=450 AND bil.ChargeOffType in(3,4) ) ) '
 IF ISNULL(@billtype,'')<>''
		SET @SqlNormal = @SqlNormal + ' AND bil.billtype in ('+	@billtype+') '
 
 IF @proinfo = 4
		SET @SqlNormal = @SqlNormal + ' AND bil.billtype not in (414) '

 IF NOT ((@KTypeId = '00000' OR @KTypeId = '%') AND @MKTypeId = '00000')
		 SET @SqlNormal = @SqlNormal + ' AND (bil.ktypeid IN(SELECT typeid from #GetSelKTypeId) or bil.billtype=450) '
IF @QueryType IN (1,2)
	SELECT  @SqlNormal = @SqlNormal + ' 
			AND Bil.BillDate>='+char(39)+@LDDate1+char(39)+'
			AND Bil.BillDate<='+char(39)+@LDDate2+char(39)+'
			AND Bil.BillCode LIKE '+char(39)+'%'+@BillCode+'%'+char(39)+'
			AND Bil.Comment LIKE '+char(39)+'%'+@Explain+'%'+char(39)+'
			AND Bil.Explain LIKE '+char(39)+'%'+@Note+'%'+char(39)

 -- print @SqlNormal
-------------------------------------------------发票------------------------------------------------
SELECT	@Sqlfapiao = '
	SELECT	Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillType,'

	IF @QueryType IN (1,2)
		SELECT @Sqlfapiao = @Sqlfapiao +' (Bil.BillDate+Bil.AlertDay) AS AlertDay,'
	ELSE
		SELECT @Sqlfapiao = @Sqlfapiao +' '''' AS AlertDay,'

	SELECT @Sqlfapiao = @Sqlfapiao +' 
			Bil.BillCode,
			Bil.BTypeId,
			'''' as KTypeId,
			Bil.ETypeId,
			Bil.STypeId,
			Bil.ntaxTotalMoney as TotalMoney,
			(Bil.ntaxTotalMoney-ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.nChargeOffTotal,0)) AS LeftTotalMoney,
			Bil.Comment,
			Bil.Explain,
			ss.fullname as sfullname,
			emp.fullname as efullname,
			bb.fullname as bfullname,
			'''' as kfullname,
			0 as detailid
	FROM 	ReceiptBillIndex Bil
			INNER JOIN Stype ss ON  ss.typeid=Bil.STypeId
			INNER JOIN Employee emp ON emp.typeid=Bil.ETypeId
			INNER JOIN btype bb ON bb.typeid=Bil.BTypeId'

	IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002' AND (@BTypeId = '' OR @BTypeId = '%'))
		SET @Sqlfapiao = @Sqlfapiao + ' INNER JOIN #GetSelBTypeId B ON Bil.BTypeId = B.TypeId '

	IF NOT (@ETypeId = '' AND @METypeId = '00001')
		SET @Sqlfapiao = @Sqlfapiao + ' INNER JOIN #GetSelETypeId E ON Bil.ETypeId = E.TypeId '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @Sqlfapiao = @Sqlfapiao + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '			
		
	IF NOT @MDTypeId = '00000'
		SET @Sqlfapiao = @Sqlfapiao + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Bil.DTypeId '			
	SET @Sqlfapiao = @Sqlfapiao + '
	WHERE	Bil.BillType = 404 '+@Condition+'
			AND ((Bil.IfCheck = ''t'' AND Bil.RedWord = 0 AND Bil.IfYearBill = 0) '+@isiniWhere+')
			--AND (Bil.nTotalMoney - ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.nChargeOffTotal,0)) > 0
			AND Bil.jsState<>2
			AND (Bil.ifStopMoney=''0'' or Bil.IfStopMoney IS NULL)'
 IF ISNULL(@billtype,'')<>''
		SET @Sqlfapiao = @Sqlfapiao + ' AND bil.billtype in ('+	@billtype+') '
IF @QueryType IN (1,2)
	SELECT  @Sqlfapiao = @Sqlfapiao + ' 
			AND Bil.BillDate>='+char(39)+@LDDate1+char(39)+'
			AND Bil.BillDate<='+char(39)+@LDDate2+char(39)+'
			AND Bil.BillCode LIKE '+char(39)+'%'+@BillCode+'%'+char(39)+'
			AND Bil.Comment LIKE '+char(39)+'%'+@Explain+'%'+char(39)+'
			AND Bil.Explain LIKE '+char(39)+'%'+@Note+'%'+char(39)

---------------------应付增加单、减少单（主表没有仓库、往来单位、优惠金额、实收金额、没有结算，按明细统计）
SELECT	@SqlArap = '
	SELECT	Bil.BillNumberId,
			Bil.BillDate,
			Bil.BillType,'

	IF @QueryType IN (1,2)
		SELECT @SqlArap = @SqlArap +' (Bil.BillDate+AD.AlertDay) AS AlertDay,'
	ELSE
		SELECT @SqlArap = @SqlArap +' '''' AS AlertDay,'
SELECT @SqlArap = @SqlArap +' 
			Bil.BillCode,
			AD.BTypeId,
			'''' as ktypeid,
			Bil.ETypeId,
			Bil.STypeId,
			CASE WHEN Bil.billtype = 128
					THEN ad.total
				WHEN Bil.billtype = 129
					THEN -ad.total
			ELSE 0
			END AS  TotalMoney,
			CASE WHEN Bil.billtype = 128
				THEN ad.total -ad.CompleteTotal-isnull(ad.ChargeOffTotal,0)
			 WHEN Bil.billtype = 129
				THEN -(ad.total -ad.CompleteTotal -isnull(ad.ChargeOffTotal,0))
			ELSE 0
			END AS LeftTotalMoney,
			--(Bil.ntaxTotalMoney-ISNULL(Bil.nCompleteTotal,0)-ISNULL(Bil.nChargeOffTotal,0)) AS LeftTotalMoney,
			Bil.Comment,
			Bil.Explain,
			ss.fullname as sfullname, --必须加这些fullname个人首页要用
			emp.fullname as efullname,
			bb.fullname as bfullname,
			'''' as kfullname,
			ad.id as detailid 
	FROM 	BillIndex Bil
	INNER JOIN AdDebtBill AD ON Bil.billnumberid=ad.billnumberid '
			
SELECT @SqlArap=@SqlArap+'	
	INNER JOIN Stype ss ON  ss.typeid=Bil.STypeId
	INNER JOIN Employee emp ON emp.typeid=Bil.ETypeId
	INNER JOIN btype bb ON bb.typeid=AD.BTypeId '

	IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002' AND (@BTypeId = '' OR @BTypeId = '%'))
		SET @SqlArap = @SqlArap + ' INNER JOIN #GetSelBTypeId B ON AD.BTypeId = B.TypeId '

	IF NOT (@ETypeId = '' AND @METypeId = '00001')
		SET @SqlArap = @SqlArap + ' INNER JOIN #GetSelETypeId E ON Bil.ETypeId = E.TypeId '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SqlArap = @SqlArap + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '		
		
	IF NOT @MDTypeId = '00000'
		SET @SqlArap = @SqlArap + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Bil.DTypeId '			
	SET @SqlArap = @SqlArap + '
	WHERE	Bil.BillType IN(128,129) '+REPLACE(@Condition,'Bil.alertday','ad.alertday')+'
			AND ((Bil.IfCheck = ''t'' AND Bil.RedWord = 0 AND Bil.IfYearBill = 0) '+@isiniWhere+' )
			AND ad.total -ad.CompleteTotal-isnull(ad.ChargeOffTotal,0)>0
			AND (ad.ifStopMoney=''0'' or ad.IfStopMoney IS NULL)'
	 IF ISNULL(@billtype,'')<>''
		SET @SqlArap = @SqlArap + ' AND bil.billtype in ('+	@billtype+') '
IF @QueryType IN (1,2)
	SELECT  @SqlArap = @SqlArap + ' 
			AND Bil.BillDate>='+CHAR(39)+@LDDate1+CHAR(39)+'
			AND Bil.BillDate<='+CHAR(39)+@LDDate2+CHAR(39)+'
			AND Bil.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+'
			AND Bil.Comment LIKE '+CHAR(39)+'%'+@Explain+'%'+CHAR(39)+'
			AND Bil.Explain LIKE '+CHAR(39)+'%'+@Note+'%'+CHAR(39)
			
			
SELECT @SQL=@SqlNormal+' UNION ALL '+@Sqlfapiao	+ ' UNION ALL '+ @SqlArap

IF @isLoginHit=1
BEGIN
	SET @SQL  =' select top 1 ''payhit'',1 from ('+@SQL+')P  '
	
	PRINT(@sql)
	RETURN
END
ELSE
BEGIN
	DECLARE @re_re INT=0
	--EXEC @re_re=GP_CheckLimit @OperatorId,166
	
    
	SET @SQL ='SELECT p.BillNumberId,p.BillDate,p.BillType,p.AlertDay,p.BillCode,p.BTypeId,p.KTypeId,
						p.ETypeId,
						p.STypeId,
					    CASE WHEN P.billtype IN(34,6,145,161,157,404) AND '+cast(@re_re as varchar)+'=1 THEN  ''***'' ELSE  CAST(p.TotalMoney AS varchar) END AS TotalMoney,
						CASE WHEN P.billtype IN(34,6,145,161,157,404) AND '+cast(@re_re as varchar)+'=1 THEN  ''***'' ELSE  CAST(p.LeftTotalMoney AS varchar) END AS LeftTotalMoney,
						--p.LeftTotalMoney,
						p.Comment,p.Explain,p.sfullname,
						p.efullname,p.bfullname,p.kfullname,p.detailid
					SysDiy1_head,
					SysDiy2_head,
					SysDiy3_head,
					SysDiy4_head, 
					SysDiy5_head,
					SysDiy6_head,
					SysDiy7_head,
					SysDiy8_head,
					SysDiy9_head,
					SysDiy10_head,
					SysDiy11_head,
					SysDiy12_head,
					SysDiy13_head,
					SysDiy14_head,
					SysDiy15_head,
					SysDiy16_head
	 FROM ('+@SQL+')P 
	 LEFT JOIN Custom_BillIndex csindex on P.billnumberid=csindex.BillId and P.billtype=csindex.billtype
	 ORDER BY p.BillDate,p.BillCode '


PRINT(@SQL)
	EXEC(@SQL)
END

DROP TABLE #GetSelBTypeId,#GetSelETypeId,#GetSelKTypeId,#GetManSTypeId,#GetManDTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_OutDateStock_Gathering]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_OutDateStock_Gathering]
GO

/*
	作者：舒珊
	日期：2016年7月6日
	描述：超期未入库报警
*/
CREATE PROCEDURE Web_OutDateStock_Gathering(
	@OperatorId	VARCHAR(100),		--操作员ID
	@LDDate1	VARCHAR(20),		--录单日期
	@LDDate2	VARCHAR(20),		--录单日期
	@XQDate1	VARCHAR(20),		--入/出库限期日期
	@XQDate2	VARCHAR(20),		--入/出库限期日期
	@BTypeID	VARCHAR(8000),		--往来单位ID
	@KTypeID	VARCHAR(8000),		--仓库ID
	@ETypeID	VARCHAR(8000),		--经手人ID
	@STypeID	VARCHAR(8000),		--分支机构
	@BillCode	VARCHAR(256),		--单据编号
	@QueryType	INT,				--查询类别    1.超期未入库报警 2.超期未出库报警 
	@billtype   VARCHAR(1000) --查询的单据类型
)
--@encode$--
AS

SET NOCOUNT ON 

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--单位：
CREATE TABLE #GetSelBTypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S

--职员：
CREATE TABLE #GetSelETypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S

--仓库：
CREATE TABLE #GetSelKTypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelKTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
IF NOT @MDTypeId = '00000'
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)		

IF isnull(@XQDate1,'')=''
	SET @XQDate1=''
IF  isnull(@XQDate2,'')=''
	SET @XQDate2=''


DECLARE @SqlNormal VARCHAR(MAX)
DECLARE @SqlFrom VARCHAR(MAX)
DECLARE	@Condition VARCHAR(8000)=''
DECLARE @GROUPBY VARCHAR(MAX)


DECLARE @UserDeRowCount	int

IF @billtype='-1'
	SET @billtype=''

SELECT @UserDeRowCount = ISNULL(UserDeRowCount,'0') FROM LoginUser WHERE ETypeId = @OperatorID
IF @UserDeRowCount = 0
	SET @UserDeRowCount = 14

--处理参数变化
IF @BTypeId = '00000'
	SET @BTypeID = '%'
IF @KTypeID = '00000' OR @KTypeID=''
	SET @KTypeID = '%'

SET	@SqlNormal = '
select	isb.billnumberid,--单据id
		bix.etypeid,--经手人
		bix.billdate,
		bix.billcode,
		bix.billtype,
		-- sum(osi.totalqty) as inOutQty,--已入、出库数量
		sum(isnull(osb.qty,0)) as inOutQty,--已入、出库数量
		bix.dtypeid,
		bix.stypeid,
		isb.ktypeid,
		bn.billname,
		sum( isnull(isb.qty,0) )as inOutallQty,--入、出库数量'	
	
SET @GROUPBY=' GROUP BY isb.billnumberid,
					   bix.etypeid,
					   bix.billdate,
					   bix.billcode,
					   bix.billtype,
					   bix.dtypeid,
					   bix.stypeid,
					   isb.ktypeid,
					   bn.billname, 
					  -- isb.qty,
					   '
	

--1.超期未入库报警
IF @QueryType =1
	BEGIN
		SET @SqlNormal=@SqlNormal+'
							 DATEADD(DAY, convert(int,bix.StockInDeadline), BIX.BillDate) as alertdate'
		
		SET @SqlFrom='
					FROM
					 (
							select	billnumberid,billdate,billtype,ktypeid,sum(abs(qty)) as qty
							from	inoutstocktable 
							where	billtype in  (''17'',''21'',''188'',''142'',''45'',''201'',''144'',''400'',''403'',''34'',''126'',''161'',''160'',''16'',''215'',''46'')		
									and qty>0
							group by billnumberid,billdate,billtype,ktypeid
					)   isb 
					inner join billindex bix on bix.BillNumberId=isb.billnumberid
					inner join billname bn on bn.billtype=isb.billtype
					left join (
								select sum(osb.qty) as qty,osb.GoodsBillNumberID from  onShelvesbill  osb
								inner join onShelvespickIndex osi on osi.billnumberid = osb.billnumberid and osi.ifcheck=''t'' and osi.redword=0
								group by osb.GoodsBillNumberID
					 )osb
					on  osb.GoodsBillNumberID=isb.billnumberid 
					'
		
		--超期未入库 
		SET @Condition='WHERE getdate() > DATEADD(DAY,  convert(int,bix.StockInDeadline),  bix.BillDate)
						and bix.ShelveState<>2
						 
						 '
						 
		
		--入库日期范围
		IF @XQDate1<>'' AND @XQDate2<>''
			SET @Condition = @Condition+' 	
								AND  DATEADD(DAY,  convert(int,bix.StockInDeadline),  bix.BillDate) >='+CHAR(39)+@XQDate1+CHAR(39)+'
								AND  DATEADD(DAY,  convert(int,bix.StockInDeadline),  bix.BillDate) <='+CHAR(39)+@XQDate2+CHAR(39)
								
		SET @GROUPBY+=' bix.StockInDeadline'
	END

--2.超期未出库报警
IF @QueryType = 2
	BEGIN
		SET @SqlNormal=@SqlNormal+' 
							DATEADD(DAY,  convert(int,bix.WarehouseOutDay), BIX.BillDate) as alertdate'
		SET @SqlFrom='
					FROM 
					(
					select billnumberid,billdate,billtype,ktypeid,sum(abs(qty)) as qty
					from inoutstocktable 
					where billtype in  (''11'',''402'',''17'',''21'',''187'',''140'',''6'',''161'',''202'',''146'',''139'',''183'',''160'',''16'',''401'',''12'')		
					 and qty<0
					  group by billnumberid,billdate,billtype,ktypeid
					)   isb 
					inner join billindex bix on bix.BillNumberId=isb.billnumberid
					inner join billname bn on bn.billtype=isb.billtype 
					left join (
						select sum(osb.qty) as qty,osb.GoodsBillNumberID from  pickbill  osb
						 inner join onShelvespickIndex osi 
						 on osi.billnumberid = osb.billnumberid and osi.ifcheck=''t'' and osi.redword=0
						 group by osb.GoodsBillNumberID
					 )osb
					on  osb.GoodsBillNumberID=isb.billnumberid 
					'
		--超期未出库 
		SET @Condition='WHERE getdate() > DATEADD(DAY,  convert(int,bix.warehouseoutday), bix.BillDate) 
							and bix.progressstate<>2
						 
						  '
		
		--出库日期范围
		IF @XQDate1<>'' AND @XQDate2<>''
			SET @Condition = @Condition+' 	
								AND  DATEADD(DAY,  convert(int,bix.warehouseoutday), bix.BillDate) >='+CHAR(39)+@XQDate1+CHAR(39)+'
								AND  DATEADD(DAY,  convert(int,bix.warehouseoutday), bix.BillDate) <='+CHAR(39)+@XQDate2+CHAR(39)
								
		
		SET @GROUPBY+=' bix.WarehouseOutDay '
								
	END

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002' AND (@BTypeId = '' OR @BTypeId = '%'))
	SET @SqlFrom = @SqlFrom + ' INNER JOIN #GetSelBTypeId B ON B.typeid=bix.btypeid '

IF NOT (@ETypeId = '' AND @METypeId = '00001')
	SET @SqlFrom = @SqlFrom + ' INNER JOIN #GetSelETypeId E ON E.typeid=bix.etypeid '

IF NOT ((@KTypeId = '00000' OR @KTypeId = '%') AND @MKTypeId = '00000')
	SET @SqlFrom = @SqlFrom + ' INNER JOIN #GetSelKTypeId K ON  K.TypeId=bix.ktypeid '
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SqlFrom = @SqlFrom + ' INNER JOIN #GetManSTypeId S ON S.TypeId=bix.stypeid '		
	
IF NOT @MDTypeId = '00000'
	SET @SqlFrom = @SqlFrom + ' INNER JOIN #GetManDTypeId D ON D.TypeId=bix.dtypeid '			


--录单日期	
SET @Condition=@Condition+'
					AND isb.billdate>='+CHAR(39)+@LDDate1+CHAR(39)+'
					AND isb.billdate<='+CHAR(39)+@LDDate2+CHAR(39)

--单据类型
IF ISNULL(@billtype,'')<>''
	SET @Condition=@Condition + ' AND isb.billtype in ('+@billtype+') '
	
--单据编号
IF ISNULL(@BillCode,'')<>''
	SET @Condition=@Condition + ' AND bix.billcode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)


					  
					   
SET @SqlNormal=@SqlNormal+@SqlFrom+@Condition+@GROUPBY

--print @SqlNormal
exec (@SqlNormal)


DROP TABLE #GetSelBTypeId,#GetSelETypeId,#GetSelKTypeId,#GetManSTypeId,#GetManDTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_PosAllotApplyQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_PosAllotApplyQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：寇晨
	日期：2016-12-07
	描述：调货申请单查询
*/
CREATE  PROCEDURE Web_PosAllotApplyQuery
(
	@operator		VARCHAR(200),		--操作员id
	@billdatestart	datetime,			--单据创建日期起始
	@billdateend	datetime,			--单据创建日期结束
	@stypeid		varchar(max),		--分支机构id
	@ptypeidstr		varchar(max),		--多商品id
	@etypeid		varchar(max),		--职员id
	@ktypeid		varchar(max),		--出库仓库id
	@ktypeidin		varchar(max),		--入库仓库id
	@billstate		varchar(50),		--单据状态
	@billover		VARCHAR(50),		--单据中止状态
	@billexec		VARCHAR(50)			--单据执行状态
)
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @operator IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @operator,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
	IF ISNULL(@operator,'')=''
	BEGIN
		SET @operator = '00001'
	END

	CREATE TABLE #billnumberidtab
	(
		billnumberid	int
	)
	if(ISNULL(@ptypeidstr,'')='')
	BEGIN
		IF EXISTS(SELECT TOP 1 * FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit' AND Value = '1')
		BEGIN
			INSERT INTO #billnumberidtab
			SELECT i.billnumberid FROM POSALLOTAPPLYBILLINDEX i
			inner join stock fk on i.ktypeid=fk.typeid
			inner join dbo.f_linek(@operator) fkin on i.inktypeid=fkin.typeid 
			inner join dbo.f_lineD(@operator) fd on i.dtypeid=fd.typeid
			inner join dbo.f_linee(@operator) fe on i.applyetypeid=fe.typeid
			inner join dbo.F_GetManDetailSType(@operator) fs on i.stypeid=fs.typeid
		END
		ELSE
		BEGIN
			INSERT INTO #billnumberidtab
			SELECT i.billnumberid FROM POSALLOTAPPLYBILLINDEX i
			inner join stock fk on i.ktypeid=fk.typeid			
			inner join dbo.f_lineD(@operator) fd on i.dtypeid=fd.typeid
			inner join dbo.f_linee(@operator) fe on i.applyetypeid=fe.typeid
			inner join dbo.F_GetManDetailSType(@operator) fs on i.stypeid=fs.typeid
		END
	END
	ELSE
	BEGIN
		INSERT INTO #billnumberidtab
		SELECT i.billnumberid FROM POSALLOTAPPLYBILLINDEX i
		inner join 
		(
			SELECT DISTINCT billnumberid 
			FROM POSALLOTAPPLYBILL b 
			where b.ptypeid in 
			(SELECT typeid FROM dbo.F_LineP(@operator) WHERE typeid like @ptypeidstr+'%')
		) b ON i.billnumberid=b.billnumberid
	END
	
	
	CREATE TABLE #Ktype (TypeID varchar(50))
	
	--启用了配置
	IF EXISTS(SELECT TOP 1 * FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit' AND Value = '1')
	BEGIN
		INSERT INTO #Ktype(typeid) 
		select kb.TypeId  from F_GetAllManagerBaseTypeId(@ktypeid,4,@operator) kb
	END
	ELSE
	BEGIN
		INSERT INTO #Ktype(typeid) 
		select kb.TypeId  from F_GetAllManagerBaseTypeId(@ktypeid,4,'00001') kb
	END
    
    CREATE TABLE #Ktypein (TypeID varchar(50))
    
    IF EXISTS(SELECT TOP 1 * FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit' AND Value = '1')
	BEGIN
		INSERT INTO #Ktypein(typeid) 
		select kb.TypeId  from F_GetAllManagerBaseTypeId(@ktypeidin,4,@operator) kb
	END
	ELSE
	BEGIN
		INSERT INTO #Ktypein(typeid) 
		select kb.TypeId  from F_GetAllManagerBaseTypeId(@ktypeidin,4,'00001') kb
	END	
	
    CREATE TABLE #stype (TypeID varchar(50))
	INSERT INTO #stype(typeid) 
    select sb.TypeId  from F_GetAllManagerBaseTypeId(@stypeid,11,@operator) sb
    
    create table #billexecstate(execstate int,billnumberid  NUMERIC(10, 0))
    
    insert into #billexecstate (execstate,billnumberid)
    select case when pb.isdone =1 then 7 --已完成
				when m.qty>0 and pb.isdone=0 then 6 --已引用未完成
				else 8 end as execstate, --未引用
				pb.billnumberid
    from PosAllotApplyBillIndex pb
    left join 
		(	SELECT ISNULL(SUM(m.qty),0) as qty,pb.billnumberid
				FROM (
					SELECT Qty,AllotID FROM dbo.MoveBill m 
					INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
					WHERE bi.RedWord=0 ----引用要算草稿
					UNION ALL SELECT Qty,AllotID FROM dbo.MoveBjBill m
					INNER JOIN dbo.BillIndex bi ON m.BillNumberId=bi.BillNumberId
					WHERE bi.RedWord=0 ----引用要算草稿 
					UNION ALL SELECT s.Qty,s.AllotID FROM dbo.STypeMoveBill s 
					INNER JOIN dbo.BillIndex bi ON s.BillNumberId=bi.BillNumberId
					 WHERE bi.RedWord=0 ----引用要算草稿 
				) m
				INNER JOIN dbo.PosAllotApplyBill pb ON pb.ID=m.AllotID 
				group by pb.billnumberid
			
		)m on pb.billnumberid=m.billnumberid
	
	create table #notcompleteqty(billnumberid bigint,notcompleteqty numeric(24,10))
	
	insert into #notcompleteqty(billnumberid,notcompleteqty)
	select b.BillNumberId,SUM(case when b.CallQty >= b.qty then 0 else b.qty-b.CallQty end)
	from PosAllotApplyBill b
	inner join #billnumberidtab bi on bi.billnumberid = b.BillNumberId
	group by b.BillNumberId
	
	
	DECLARE @SQL NVARCHAR(MAX)
	SET @SQL = N'
		SELECT	ROW_NUMBER() OVER(ORDER BY i.billnumberid) AS rowNo,
				0 as ischeck,
				i.billnumberid,
				CONVERT(VARCHAR(10),i.BillDate,120) AS BillDate,
				i.checktime,
				i.BillCode,
				i.billstate,
				CASE
				WHEN bs.execstate=7 THEN ''已完成'' 
				WHEN i.BillState=4 THEN ''已作废'' 
				WHEN bs.execstate=6 THEN ''已引用未完成''  
				WHEN i.BillState=0 THEN ''原始单据'' 
				WHEN i.BillState=1 THEN ''已审核''
				WHEN i.BillState=2 THEN ''已接受''
				WHEN i.BillState=3 THEN ''已拒绝''
				ELSE ''未引用'' END AS chvbillstate,
				i.inktypeid,
				kin.fullname as kfullnamein,
				i.applyetypeid,
				e.fullname as applyefullname,
				i.ktypeid,
				k.fullname as kfullname, 
				i.stypeid,
				s.usercode as susercode,
				s.fullname as sfullname,
				i.checke as etypeid,
				e1.fullname as efullname,
				i.dtypeid,
				d.fullname as dfullname,
				i.comment,
				i.BillOver as billover,
				CASE WHEN i.BillOver=0 THEN ''未中止''
				ELSE ''已中止'' END AS isbillstop,
				bs.execstate,
				CASE WHEN bs.execstate=7 THEN ''已完成'' 
					WHEN bs.execstate=6 THEN ''已引用未完成'' 
					WHEN bs.execstate=8 THEN ''未引用''
					ELSE ''''
				END  strbillexec,
				i.qty as billqty,
				nqty.notcompleteqty
				FROM PosAllotApplyBillIndex i 
				INNER JOIN #billnumberidtab ib ON i.billnumberid=ib.billnumberid 
				left join #billexecstate bs on ib.billnumberid=bs.billnumberid
				left join #notcompleteqty nqty on nqty.billnumberid = i.billnumberid
				LEFT JOIN stock k ON i.ktypeid=k.typeid
				LEFT JOIN stock kin ON i.inktypeid=kin.typeid
				LEFT JOIN Employee e ON i.applyetypeid=e.typeid 
				LEFT JOIN Employee e1 ON i.checke=e1.typeid 
				LEFT JOIN stype s ON i.stypeid=s.typeid 
				LEFT JOIN Department d on i.dtypeid=d.typeid
		WHERE	1=1 AND i.BillType = 22 '			
		
	IF @billdatestart IS NOT NULL AND @billdateend IS NOT NULL
	BEGIN
		SET @SQL += N' AND i.billdate BETWEEN @billdatestartparam AND @billdateendparam '
	END
	IF ISNULL(@stypeid,'')<>''
	BEGIN
		SET @SQL += N' AND i.stypeid IN (select typeid from #stype ) '
	END
	IF ISNULL(@etypeid,'')<>''
	BEGIN
		SET @SQL +=N' AND i.applyetypeid IN (SELECT f1.typeid FROM dbo.F_LineE(@operatorparam) f1 INNER JOIN dbo.f_split(@etypeidparam,'','') f2 ON f1.typeid like ''''+f2.a+''%'')'
	END
	IF ISNULL(@ktypeid,'')<>''
	BEGIN
		SET @SQL +=N' AND i.ktypeid IN (select typeid from #ktype) '
	END
	IF ISNULL(@ktypeidin,'')<>''
	BEGIN
		SET @SQL +=N' AND i.inktypeid IN (select typeid from #ktypein)'
	END
	IF ISNULL(@billover,'')<>''
	BEGIN
		SET @SQL += N' AND i.billover in (SELECT * FROM dbo.f_split(@billoverparam,'','')) '
	END
	
	--状态条件
	IF ISNULL(@billexec,'')<>'' AND ISNULL(@billstate,'')<>''
	BEGIN
		SET @SQL += N' AND ( CHARINDEX(CONVERT(VARCHAR,bs.execstate),'''+@billexec+''') > 0 OR CHARINDEX(CONVERT(VARCHAR,i.billstate),'''+@billstate+''') > 0 ) '
	END
	ELSE IF ISNULL(@billexec,'')<>''
	BEGIN
		SET @SQL += N' AND CHARINDEX(CONVERT(VARCHAR,bs.execstate),'''+@billexec+''') > 0 '
	END
	ELSE IF ISNULL(@billstate,'')<>''
	BEGIN
		SET @SQL += N' AND CHARINDEX(CONVERT(VARCHAR,i.billstate),'''+@billstate+''') > 0 '
	END
	
	IF CHARINDEX('6',@billexec) = 0  AND ISNULL(@billexec,'') <> '' 
	BEGIN
		SET @SQL += ' AND bs.execstate <> 6 ' --不查询已引用未完成
	END
	IF CHARINDEX('7',@billexec) = 0  AND ISNULL(@billexec,'') <> '' 
	BEGIN
		SET @SQL += ' AND bs.execstate <> 7 ' --不查询已完成
	END
	IF ISNULL(@billexec,'') = '' AND ISNULL(@billstate,'') <> '' 
	BEGIN
		SET @SQL += ' AND bs.execstate not in (6,7) ' --不查询未引用
	END
		
	SET @SQL += N' ORDER BY i.billdate desc'

	--PRINT(@SQL)
	
	DECLARE @ParameterDefinition NVARCHAR(MAX)
	SET @ParameterDefinition=N'
		@operatorparam		 as	VARCHAR(200),
		@billdatestartparam  as	datetime,
		@billdateendparam	 as datetime,
		@stypeidparam		 as varchar(max),
		@etypeidparam		 as varchar(max),
		@ktypeidparam		 as varchar(max),    
		@ktypeinparam		 as varchar(max),
		@billstateparam		 as varchar(50),
		@billoverparam		 as VARCHAR(50),
		@billexecparam		 as VARCHAR(50)'
	
	EXEC sp_executesql @SQL,@ParameterDefinition,@operator,@billdatestart,@billdateend,@stypeid,@etypeid,@ktypeid,@ktypeidin,@billstate,@billover,@billexec
	
	--EXEC(@SQL)
	
	DROP TABLE #billnumberidtab,#Ktype,#Ktypein,#billexecstate,#notcompleteqty,#stype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PreviewBillCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_PreviewBillCode]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







---------------------------------------------------------------

	--人员：徐辉
	--日期：2011-03-15
	--说明：预览自定义编号
---------------------------------------------------------------
CREATE                           PROCEDURE Web_PreviewBillCode
(
	@Code1 varchar(100),
	@Code2 varchar(100),
	@Code3 varchar(100),
	@Code4 varchar(100),
	@Code5 varchar(100),
	@Code6 varchar(100),
	@Code7 varchar(100),
	@Code8 varchar(100),
	@Code9 varchar(100),
	@Code10 varchar(100),
	@Code11 varchar(100),
	@Code12 varchar(100),
	@Code13 varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON
--单据编号配置
DECLARE @BillcodeDateSeparator varchar(5),@monthSeparator varchar(5),@daySeparator varchar(5),@yearSeparator varchar(5)
SELECT @BillcodeDateSeparator=Value FROM Userconfig WHERE ConfigName='BillcodeDateSeparator' 

IF @BillcodeDateSeparator='0'
	SELECT @monthSeparator='-',@daySeparator='',@yearSeparator='-'
ELSE IF @BillcodeDateSeparator='1'
	SELECT @monthSeparator='.',@daySeparator='',@yearSeparator='.'
ELSE IF @BillcodeDateSeparator='2'
	SELECT @monthSeparator='月',@daySeparator='日',@yearSeparator='年'
ELSE IF @BillcodeDateSeparator='3'
	SELECT @monthSeparator='',@daySeparator='',@yearSeparator=''
ELSE IF @BillcodeDateSeparator='4'
	SELECT @monthSeparator=' ',@daySeparator='',@yearSeparator=' '
DECLARE @BillDate VARCHAR(10)
SELECT @BillDate=CAST(YEAR(GETDATE()) AS VARCHAR(4))+'-'+CAST(MONTH(GETDATE()) AS VARCHAR(2))+'-'+CAST(DAY(GETDATE()) AS VARCHAR(2))

--dbo.F_Get_YMD_NEW为自定义转换函数
SELECT Code1=dbo.F_Get_YMD_NEW(@code1,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code2=dbo.F_Get_YMD_NEW(@code2,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code3=dbo.F_Get_YMD_NEW(@code3,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code4=dbo.F_Get_YMD_NEW(@code4,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code5=dbo.F_Get_YMD_NEW(@code5,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code6=dbo.F_Get_YMD_NEW(@code6,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code7=dbo.F_Get_YMD_NEW(@code7,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code8=dbo.F_Get_YMD_NEW(@code8,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code9=dbo.F_Get_YMD_NEW(@code9,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code10=dbo.F_Get_YMD_NEW(@code10,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code11=dbo.F_Get_YMD_NEW(@code11,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code12=dbo.F_Get_YMD_NEW(@code12,@BillDate,@yearSeparator,@monthSeparator,@daySeparator),
		Code13=dbo.F_Get_YMD_NEW(@code13,@BillDate,@yearSeparator,@monthSeparator,@daySeparator)
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT 1 FROM dbo.sysobjects WHERE id=object_id(N'[dbo].[Web_PrintAcVoucherDetails]')  AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC Web_PrintAcVoucherDetails

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--=========================================
--	CreatedBy：glj
--	Date：2012-11-01
--	Description：会计凭证连续打印查询详细记录
--=========================================

CREATE PROC Web_PrintAcVoucherDetails
(
	@NBillIds		VARCHAR(MAX),	--打印的凭证ID字符串
	@OperatorID		VARCHAR(50)		--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

IF EXISTS(SELECT * FROM sysdata WHERE SubName='voucherreportindex' AND SubValue='1')
	BEGIN
		SELECT
			b.BillNumberId,
			dbo.F_GetSummaryByLimit(b.ID,@OperatorId,b.STypeID,b.Summary) Summary,
			CASE WHEN ISNULL(FA.TypeId,'')='' THEN '****' ELSE A.UserCode END UserCode,
			CASE WHEN ISNULL(FA.TypeId,'')='' THEN '****' ELSE A.FullName END FullName,
			dbo.F_GetAssistCheckItemsName(b.ID,@OperatorID,B.STypeId) AssistName,
			dbo.F_GetAtypeFullNameNew(b.ID,b.ATypeId,B.STypeId,@OperatorID) aFullName,
			b.FDebitTotal,
			b.FCreditTotal,
			c.FullName CFullName,
			CASE WHEN b.FAdc=1 THEN b.FDebitTotalFor ELSE b.FCreditTotalFor END TotalFor,
			bt.FullName SettleFullName,
			b.FSettleNo,
			CONVERT(VARCHAR(10),b.FSettleDate,120) FSettleDate,
			b.Comment,
			c.Rate,
			Com.UserCode,
			Com.FullName,
			Com.person,
			Com.person,
			Com.telandaddress,
			Com.tel1,
			Com.postcode,
			Com.taxnumber,
			Com.bank,
			Com.bankandacount,
			Com.comment,
			V.FComment
		FROM dbo.f_split(@NBillIds,',') f 
		INNER JOIN  Ac_Voucher_Bill b on f.a=b.BillNumberId 
		INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId
		INNER JOIN Ac_Account  A ON A.StypeId=B.STypeId AND A.TypeId=B.ATypeId
		LEFT JOIN F_LineAccount(@OperatorID,'') FA ON FA.StypeId=A.StypeId AND FA.TypeId=A.TypeId 
		LEFT JOIN Ac_Currency C ON C.CId=B.Cid
		LEFT JOIN Ac_BalanceType bt ON bt.BtId=b.FSettleTypeID
		LEFT JOIN btype Com ON Com.typeId='00000'
	END
ELSE 
	BEGIN
		SELECT
			b.BillNumberId,
			dbo.F_GetSummaryByLimit(b.ID,@OperatorId,b.STypeID,b.Summary) Summary,
			CASE WHEN ISNULL(FA.TypeId,'')='' THEN '****' ELSE A.UserCode END UserCode,
			CASE WHEN ISNULL(FA.TypeId,'')='' THEN '****' ELSE A.FullName END FullName,
			dbo.F_GetAssistCheckItemsName(b.ID,@OperatorID,B.STypeId) AssistName,
			dbo.F_GetAtypeFullNameNew(b.ID,b.ATypeId,B.STypeId,@OperatorID) aFullName,
			b.FDebitTotal,
			b.FCreditTotal,
			c.FullName CFullName,
			b.Rate,
			CASE WHEN b.FAdc=1 THEN b.FDebitTotalFor ELSE b.FCreditTotalFor END TotalFor,
			bt.FullName SettleFullName,
			b.FSettleNo,
			CONVERT(VARCHAR(10),b.FSettleDate,120) FSettleDate,
			b.Comment
		FROM dbo.f_split(@NBillIds,',') f 
		INNER JOIN  Ac_Voucher_Bill b on f.a=b.BillNumberId 
		INNER JOIN Ac_Voucher V ON V.BillNumberId=B.BillNumberId
		INNER JOIN Ac_Account  A ON A.StypeId=B.STypeId AND A.TypeId=B.ATypeId
		LEFT JOIN F_LineAccount(@OperatorID,'') FA ON FA.StypeId=A.StypeId AND FA.TypeId=A.TypeId 
		LEFT JOIN Ac_Currency C ON C.CId=B.Cid
		LEFT JOIN Ac_BalanceType bt ON bt.BtId=b.FSettleTypeID
		LEFT JOIN btype Com ON Com.typeId='00000'
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PrintRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_PrintRecord]
GO
/*
	作者：廖晨羽
	日期：2009-10-27
	描述：打印记录
	
	修改: 刘飞 2017-04-05 固定资产盘点单主表不是billindex,是FixedAssetsIndex
*/

CREATE                  PROCEDURE Web_PrintRecord
( 
	@SUMMARY		BIT,			  --是否分组统计
	@billnumberid	NUMERIC(10,0),
	@billtype		NUMERIC(4,0),
	@BillState		VARCHAR(10),
	@BillCode		VARCHAR(256),	--单据编号
	@PrintEtype		VARCHAR(256),	--打印人
	@IPAddress		VARCHAR(256),	--IP
	@BillTypeName	VARCHAR(256)	--单据名字
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--特殊处理维修单
IF @billtype = 195
BEGIN
	IF @BillState = 2
		SET @BillState = 1
		
	IF @BillState = 4
		SET @BillState = 3
END

DECLARE @SQL			VARCHAR(MAX)
--单据打印次数查询
CREATE TABLE #TempTable
(
	BillName		VARCHAR(200),
	BillType		NUMERIC(4,0),
	BillNumberId	NUMERIC(10,0),
	BillCode		VARCHAR(200),
	FullName		VARCHAR(66),
	PrintTime		VARCHAR(200),
	Ip				VARCHAR(50),
	PrintCount		INT,
	RedWord			VARCHAR(50),
	BillState		VARCHAR(10)
)

SET @SQL = 
	'INSERT INTO #TempTable
	 SELECT * 
	 FROM
		(
		SELECT	BillName,
				A.BillType,
				A.BillNumberId,
				D.billcode,
				A.eFullName as fullname,
				CONVERT(VARCHAR, PrintTime, 120) PrintTime,
				Ip,
				PrintCount,
				RedWord,
				A.BillState 
		FROM PrintRecord A 
		LEFT JOIN billname B ON A.BillType = B.Billtype 
		LEFT JOIN employee C ON A.etypeid = C.typeId 
		LEFT JOIN BillIndex d ON a.BillNumberId = d.BillNumberId
		WHERE A.BillType not in (''300'',''301'',''204'',''162'',''163'',''203'',''164'',''87'',''88'',''71'',''72'',''127'',''306'',''193'',''194'',''208'',''209'',''195'',''207'',''198'',''210'',''311'',''418'',''419'',''420'',''307'',''423'',''424'',''425'',''426'')
		UNION ALL
		SELECT	''会计凭证'',
				A.BillType,
				A.BillNumberId,
				billcode=(G.fullname+''-''+cast(d.FLOWNO as varchar)),
				A.eFullName as fullname,
				CONVERT(VARCHAR, PrintTime, 120) PrintTime,
				Ip,
				PrintCount,
				RedWord,
				A.BillState 
		FROM PrintRecord A 
		LEFT JOIN employee C ON A.etypeid = C.typeId 
		LEFT JOIN AC_VOUCHER d ON a.BillNumberId = d.BillNumberId
		LEFT JOIN AC_VOUCHER_GROUP G ON G.VGID = D.VGID
		where a.BillType=210
		
		UNION ALL
		SELECT	BillName,
				A.BillType,
				A.BillNumberId,
				D.billcode,
				A.eFullName as fullname,
				CONVERT(VARCHAR, PrintTime, 120) PrintTime,
				Ip,
				PrintCount,
				RedWord,
				A.BillState 
		FROM PrintRecord A 
		LEFT JOIN billname B ON A.BillType = B.Billtype 
		LEFT JOIN employee C ON A.etypeid = C.typeId 
		LEFT JOIN FactIndex d ON a.BillNumberId = d.BillNumberId
		WHERE A.BillType  in (''418'',''419'',''420'')
		UNION ALL
		SELECT	BillName,
				A.BillType,
				A.BillNumberId,
				D.billcode,
				A.eFullName as fullname,
				CONVERT(VARCHAR, PrintTime, 120) PrintTime,
				Ip,
				PrintCount,
				'''' as RedWord,
				A.BillState 
		FROM PrintRecord A 
		LEFT JOIN billname B ON A.BillType = B.Billtype 
		LEFT JOIN employee C ON A.etypeid = C.typeId 
		LEFT JOIN OrderIndex d ON a.BillNumberId = d.BillNumberId
		WHERE A.BillType in (''300'',''301'')
		UNION ALL
		SELECT	BillName,
				A.BillType,
				A.BillNumberId,
				D.billcode,
				A.eFullName as fullname,
				CONVERT(VARCHAR, PrintTime, 120) PrintTime,
				Ip,
				PrintCount,
				'''' as RedWord,
				A.BillState  
		FROM PrintRecord A 
		LEFT JOIN billname B ON A.BillType = B.Billtype 
		LEFT JOIN employee C ON A.etypeid = C.typeId 
		LEFT JOIN requestindex d ON a.BillNumberId = d.BillNumberId
		WHERE A.BillType = ''204''
		UNION ALL
		SELECT	CASE B.billtype
				WHEN ''162'' THEN ''销售发票''
				WHEN ''163'' THEN ''采购发票''
				WHEN ''207'' THEN ''维修销售发票''
			END AS billname,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join FaPiaoBillIndex B  
			ON A.BillNumberId = B.BillNumberId 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			WHERE A.BillType = ''162'' OR A.BillType = ''163'' OR A.BillType = ''207''
		UNION ALL
		SELECT BillName,
			A.BillType,
			A.BillNumberId,
			D.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A LEFT JOIN billname B  
			ON A.BillType = B.Billtype 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			LEFT JOIN serialadjustindex d 
			ON a.BillNumberId = d.BillNumberId
			WHERE A.BillType = ''203''
		UNION ALL
		SELECT	''提成管理单'' AS billname,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join TCBillindex B  
			ON A.BillNumberId = B.BillNumberId 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			WHERE A.BillType = ''164''
		UNION ALL
		SELECT D.billname,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join LendIndex B  
			ON A.billnumberid = B.billnumberid 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			LEFT JOIN BillName D
			ON A.BillType = D.Billtype
			WHERE A.BillType IN (''87'',''88'',''71'',''72'')
		UNION ALL
		SELECT	''生产模板'' AS billname,
			A.BillType,
			A.BillNumberId,
			B.ProduceModelName,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join producemodelindex B  
			ON A.BillNumberId = B.ProduceModelID 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			WHERE A.BillType = ''127''
		UNION ALL
		SELECT BillName,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join StockCheckIndex B  
			ON A.BillNumberId = b.stockCheckID
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			LEFT JOIN dbo.BillName e
			ON a.BillType = e.Billtype
			WHERE A.BillType = ''306''
		UNION ALL
		SELECT	CASE B.billtype
				WHEN ''193'' THEN ''工具入库台账''
				WHEN ''194'' THEN ''工具出库台账''
			END AS billname,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join toolindex B  
			ON A.BillNumberId = B.BillNumberId 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			WHERE A.BillType IN (''193'',''194'')	
		UNION ALL
		SELECT	''使用登记单''
			AS billname,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join CM_CarUseIndex B  
			ON A.BillNumberId = B.BillNumberId 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			WHERE A.BillType IN (''208'')		
		UNION ALL
		SELECT	''车辆费用单''
			AS billname,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join CM_FeeIndex B  
			ON A.BillNumberId = B.BillNumberId 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			WHERE A.BillType IN (''209'')
			UNION ALL
		SELECT	''提成单''
			AS billname,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join CommissionBillNew B  
			ON A.BillNumberId = B.BillNumberId 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			WHERE A.BillType IN (''311'')			
		UNION ALL
		SELECT	CASE A.BillState
				WHEN 1 THEN ''接待登记单''
				WHEN 3 THEN ''维修结算单''
			END AS billname,
			A.BillType,
			A.BillNumberId,
			B.billcode,
			A.eFullName as fullname,
			CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			Ip,
			PrintCount,
			'''' as RedWord,
			A.BillState  
		FROM PrintRecord 
			A left join BillIndex B  
			ON A.BillNumberId = B.BillNumberId 
			LEFT JOIN employee C 
			ON A.etypeid = C.typeId 
			WHERE A.BillType IN (''195'') AND 	A.BillState IN (1,3)		
			UNION ALL
			SELECT BillName,
				A.BillType,
				A.BillNumberId,
				D.billcode,
				A.eFullName as fullname,
				CONVERT(VARCHAR, PrintTime, 120) PrintTime,
				Ip,
				PrintCount,
				'''' as RedWord,
				''3'' AS BillState  
			FROM PrintRecord A 
			LEFT JOIN billname B ON A.BillType = B.Billtype 
			LEFT JOIN employee C ON A.etypeid = C.typeId 
			LEFT JOIN BillIndex d ON a.BillNumberId = d.BillNumberId
			WHERE A.BillType = ''198''
			UNION ALL
			SELECT BillName,
			    A.BillType,
			    A.BillNumberId,
			    D.billcode,
			    A.eFullName as fullname,
			    CONVERT(VARCHAR, PrintTime, 120) PrintTime,
			    Ip,
			    PrintCount,
			    0 AS RedWord,
			    A.BillState 
		    FROM PrintRecord A 
		    LEFT JOIN billname B ON A.BillType = B.Billtype 
		    LEFT JOIN employee C ON A.etypeid = C.typeId 
		    LEFT JOIN BillIndex d ON a.BillNumberId = d.BillNumberId
		    WHERE A.BillType in (''307'')
		    UNION ALL
		    SELECT	BillName,
					A.BillType,
					A.BillNumberId,
					D.billcode,
					A.eFullName as fullname,
					CONVERT(VARCHAR, PrintTime, 120) PrintTime,
					Ip,
					PrintCount,
					0 AS RedWord,
					A.BillState 
		    FROM PrintRecord A 
		    LEFT JOIN billname B ON A.BillType = B.Billtype 
		    LEFT JOIN employee C ON A.etypeid = C.typeId 
		    LEFT JOIN Coupon_BillIndex d ON a.BillNumberId = d.BillNumberId
		    WHERE A.BillType in (''423'',''424'',''425'',''426'')	
		) AS B
		WHERE 1 = 1 '
		 

IF @BillCode  <> ''
	SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '
IF @BillTypeName <> ''
	SET @SQL += ' AND B.BillName LIKE ''%'+@BillTypeName+'%'' '		
IF @IPAddress <> ''
	SET @SQL += ' AND B.IP LIKE ''%'+@IPAddress+'%'' '
IF @PrintEtype <> ''
	SET @SQL += ' AND B.FullName LIKE ''%'+@PrintEtype+'%'' '
	
SET @SQL += ' ORDER BY PrintTime desc '
	

--PRINT(@SQL)	
EXEC(@SQL)

DECLARE @SQLWHERE	VARCHAR(MAX)
--根据条件查结果集
	IF(@SUMMARY = 1)--分类排序
		BEGIN
			SELECT	BillName,BillType,BillNumberId,billcode,fullname,SUM(PrintCount) PrintCount 
			FROM	#TempTable WHERE BillNumberId <> -1
			GROUP BY BillNumberId,BillType,BillName,billcode,fullname
		END
	ELSE
		BEGIN
			IF @billnumberid <> -1 AND @billtype <> -1
				IF(@BillState IS null)
				BEGIN
					SELECT	* 
					FROM	#TempTable
					WHERE	BillNumberId = @billnumberid AND BillType = @billtype
				END
				ELSE
				BEGIN
					SELECT	* 
					FROM	#TempTable
					WHERE	BillNumberId = @billnumberid AND BillType = @billtype AND BillState=@BillState
				END
			ELSE
				BEGIN
					SELECT	* 
					FROM	#TempTable WHERE BillNumberId <> -1
				END
		END

DROP TABLE #TempTable 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
		
	



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_ProduceModelBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_ProduceModelBillDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO





/*
生产拆装单调生产模板明细
WangWei 2011-02-12
*/
CREATE    PROCEDURE Web_ProduceModelBillDetail
(
	@ktypeid		VARCHAR(100),
	@num			DECIMAL(18,4), --数据
	@modelId		VARCHAR(MAX),--生产模板ID
	@ptypeid		VARCHAR(MAX),--商品ID
	@OperatorID		VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------
Create TABLE #PtypeList(TYPEID VARCHAR(100))
INSERT INTO #PtypeList(TYPEID) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@PtypeId,1,@OperatorID)

-- 判断系统的成本算法；0：移动加权平均；1：先进先出；2：后进先出 3:手工指定法
DECLARE @strCosting char(1)
SELECT TOP 1 @strCosting = SubValue FROM SysData WHERE SubName = 'costing'

DECLARE @TempSql VARCHAR(MAX)
SET @TempSql='	SELECT  pm.ProduceModelID,
						(pm.Qty*'+CONVERT(VARCHAR(100),@num)+') as Qty,
						pm.ID,
						p.usercode,
						p.fullname,
						p.typeid,
						p.Unit1,
						p.Unit2,
						--p.unitrate1,
						p.entrycode,
						p.standard,
						p.type,
						p.area,
						p.serialcount,
						p.validdays,
						p.ifserial,
						p.usefullifeday,
						--p.Unit1 as unit,
						p.Unit1 as unitone,
						p.Unit2 as unittwo,
						--p.unitrate1 as unitrate,
						p.customitemid,
						p.customitemfrom,
						p.customitemname,
						p.customitemrefid,
				        (select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname1,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname2,
						(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid)) as auxfullname3,
						(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate1,
						(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate2,
					   (select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=p.typeid) as auxrate3,
						(SELECT TOP 1 FullName FROM PType_Units WHERE UnitsId=p.baseUnitId) AS unit,
						p.baseUnitId AS unitid,
						CASE WHEN p.UnitsType=0 THEN (SELECT TOP 1 FullName FROM PType_Units WHERE UnitsId=p.baseUnitId)
						ELSE (SELECT TOP 1 FullName FROM PType_Units WHERE UnitsId=p.AssistantUnitId) END AS nunit,
						CASE WHEN p.UnitsType=0 THEN p.baseUnitId ELSE p.AssistantUnitId END AS nunitid,
						(SELECT TOP 1 rate FROM PType_Units_ext WHERE  IsDefaultUnit=1 AND PtypeID=p.typeId) AS rate,
						CASE WHEN p.UnitsType=0 THEN 0 ELSE  (SELECT TOP 1 rate FROM PType_Units_ext WHERE  RateType=1 AND PtypeID=p.typeId) END AS unitrate,
						p.StockUnitId,
						dbo.F_GetAllEntrycode(p.typeId,p.StockUnitId,2) AS stockmunitcode,
						(SELECT TOP 1 FullName FROM PType_Units WHERE UnitsId=p.StockUnitId) AS stcokunitname,
						(SELECT TOP 1 rate FROM PType_Units_ext WHERE UnitsId=p.StockUnitId AND PtypeID=p.typeId) AS stcokmunitrate,
						(SELECT TOP 1 rate FROM PType_Units_ext WHERE UnitsId=p.StockUnitId AND PtypeID=p.typeId) AS munitrate,				
						''''  as serial,
						p.dwgno,
						''0'' as isunit2,
						CAST(p.ifusegoodsnum AS INT) ifusegoodsnum,
						'+CHAR(39)+@ktypeid+CHAR(39)+' as ktypeid,
						'+ CASE WHEN @strCosting = '3' THEN '0' ELSE '
						ISNULL((SELECT SUM(g.Total) / CASE WHEN SUM(g.QTY) = 0 THEN NULL ELSE SUM(g.QTY) END FROM GoodsStocks g WHERE g.ktypeid='+CHAR(39)+@ktypeid+CHAR(39)+' AND g.ptypeid=p.typeid),0)' END + ' as price,
						p.unitstype
				FROM	ProduceModel pm 
						INNER JOIN ptype p ON pm.ptypeid=p.typeid 
						INNER JOIN #PtypeList pl ON p.typeid=pl.typeid 
				WHERE	ProduceModelID='+CHAR(39)+@modelId+CHAR(39)
				
EXEC(@TempSql)

DROP TABLE #PtypeList

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_ProfitandlossReport]')and OBJECTPROPERTY(id, N'IsProcedure') = 1
)
drop Procedure [dbo].[WEB_ProfitandlossReport]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

/*
	作者：
	时间：
	描述：损益表（新写，从资产负债表中搬移出来，之前太乱了,还可以优化）
*/

CREATE       PROCEDURE [dbo].WEB_ProfitandlossReport
(
	@OperatorID	varchar(50),		--操作员ID
	@StypeId	varchar(max),		--分支机构id
	@period		varchar(2)='',
	@year		INT	,
	@startdate	VARCHAR(50)='',	-- 开时日期
	@enddate	varchar(50)='',	-- 结束日期
	@HideZero	int=0,	-- 0显示，1隐藏
	@itemLeveal int = 10    --项目级次
)
--@encode$--
AS

SET NOCOUNT ON

DECLARE @ALL_INCOME_ID varchar(50),       
		@ALL_EXPENSE_ID varchar(50)         

SELECT @ALL_INCOME_ID='00003' --         【收入类】
SELECT @ALL_EXPENSE_ID='00004'--         【支出类】


SET @itemLeveal = @itemLeveal + 1

CREATE TABLE #Stype (TypeID varchar(50),StartDate DATETIME,EndDate DATETIME)
INSERT INTO #Stype(TypeID,StartDate,EndDate)
SELECT 
	F.TypeId,
	CASE WHEN ISNULL(@startdate,'')='' THEN M.StartDate ELSE @startdate END StartDate,
	CASE WHEN ISNULL(@enddate,'')='' THEN CAST('9999-12-31' AS DATE) ELSE @enddate END EndDate
FROM dbo.F_BaseGetAllManagerBaseTypeId(@StypeId,11,@OperatorID) F
LEFT JOIN MonthProc M ON M.STypeID=F.TypeId AND M.MonthNo='本期'


CREATE TABLE #t1(atypeid NVARCHAR(50),stypeid NVARCHAR(1000),total  NUMERIC(24, 10) ,cid INT);
CREATE TABLE #t2(atypeid NVARCHAR(50),stypeid NVARCHAR(1000),total00x  NUMERIC(24, 10) ,cid INT);

INSERT INTO #t1 
SELECT atypeid,stypeid,ISNULL(SUM(total),0) AS total ,cid 
FROM ListTable L
INNER JOIN #Stype S ON S.TypeID=L.STypeID AND L.BillDate BETWEEN S.StartDate AND S.EndDate 
GROUP BY atypeid,stypeid,cid

INSERT INTO #t2	SELECT atypeid,stypeid,ISNULL(SUM(total),0) AS total00x ,cid 
FROM ListTable L
INNER JOIN #Stype S ON S.TypeID=L.STypeID AND L.BillDate<S.StartDate
GROUP BY atypeid,stypeid,cid


SELECT  p.nparid AS parid ,
		p.deleted ,
		p.leveal ,
		p.ntypeId AS typeid,
		CASE FullName
			WHEN '发出商品' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '库存商品总值') + '1'
			WHEN '应付暂估' THEN (SELECT nTypeId FROM dbo.Ac_Items WHERE FullName = '应付合计') + '1'
			ELSE p.ntypeId
		END AS ordertypeid,
		p.Sysrow ,
		p.UserCode ,
		p.FullName ,
		p.sonnum ,
		ISNULL(s.Total,0) AS total ,
		ISNULL(s.Total00,0) AS total00 ,
		nId
INTO    #Atype
FROM    dbo.Ac_Items p
LEFT JOIN
		( 
			SELECT  w.atypeid ,
					ISNULL(SUM(total), 0)+ISNULL(SUM(total00x),0)+ISNULL(SUM(total00), 0) AS total , -- 期末
					ISNULL(SUM(total00x),0)+ISNULL(SUM(total00), 0) AS total00  --期初
			FROM    
			(
				SELECT b.atypeid AS atypeid,ISNULL(a.total,0) AS total,b.STypeID AS stypeid,ISNULL(b.total00,0) AS total00,ISNULL(c.total00x,0) AS total00x 
				FROM dbo.AType_Total b
				LEFT JOIN  #t1 a  ON a.atypeid=b.atypeid AND a.stypeid=b.stypeid AND a.cid=b.cid
				LEFT JOIN #t2 c ON b.atypeid=c.atypeid AND b.STypeID=c.stypeid AND b.cid=c.cid
			) w
			WHERE w.stypeid IN (SELECT typeid FROM #Stype)
			GROUP BY ATypeID
	  ) s ON s.ATypeID = p.nId
WHERE   p.ntypeId <> '00000'
		AND (p.nTypeId LIKE  @ALL_INCOME_ID+'%'  OR  p.nTypeId LIKE @ALL_EXPENSE_ID +'%')
		
--判断损益表的权限
DECLARE @re INT 
EXEC @re = GP_CheckLimit @OperatorID,4225
IF @re =1	--没有查看损益表所有项目的权限
BEGIN
	DELETE 
	FROM	#Atype 
	WHERE	typeid NOT IN (
		SELECT nTypeId FROM F_AllTreeIncomeC(@OperatorID)--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT nTypeId FROM F_AllTreeExpenseC(@OperatorID)--支出类（费用类型+管辖支出）	
	)
END	
		
IF @Period=''
BEGIN
		CREATE TABLE #gain(usercode varchar(300),fullname varchar(300),leveal int,typeid varchar(50),sonnum int,parid varchar(50),total  NUMERIC(24, 10) ,bqtotal  NUMERIC(24, 10) )	

		INSERT INTO #gain
		SELECT a.usercode,a.fullname,a.leveal,a.typeid,a.sonnum,a.parid,
	    ISNULL(a.total,0),
		(
			-- 本期 =期末-期初
			a.total-a.total00
		) as 'BqTotal'
		FROM #Atype a 
		WHERE (left(a.typeid,5)=@ALL_INCOME_ID or left(a.typeid,5)=@ALL_EXPENSE_ID)

		INSERT INTO #gain(usercode,fullname,leveal,typeid,sonnum,parid,total,bqtotal) 
		SELECT '','【利    润】',1,'999999999999999',0,'',(select sum(case when typeid LIKE'00003%' then total else -total end) as total from #gain),(select sum(case when typeid LIKE '00003%' then bqtotal else -bqtotal end) as bqtotal from #gain)
		
		update #gain set fullname ='    '+fullname where leveal =2
		update #gain set fullname ='        '+fullname where leveal =3
		update #gain set fullname ='            '+fullname where leveal =4
		update #gain set fullname ='                '+fullname where leveal =5
		update #gain set fullname ='                    '+fullname where leveal =6
		update #gain set fullname ='                        '+fullname where leveal =7
		update #gain set fullname ='                            '+fullname where leveal =8
		update #gain set fullname ='                                '+fullname where leveal =9
		update #gain set fullname ='                                    '+fullname where leveal =10

	;WITH cte AS
	(
		SELECT usercode,fullname,leveal,typeid,sonnum,parid,total,bqtotal
		FROM #gain		
		UNION ALL
		SELECT c.usercode,c.fullname,c.leveal,c.typeid,c.sonnum,c.parid,d.total,d.bqtotal
		FROM #gain  C  
		INNER JOIN cte  D ON C.typeid=D.parid
	 ),c1 AS (
		SELECT #gain.usercode,#gain.fullname,#gain.leveal,#gain.typeid,#gain.sonnum,#gain.parid,SUM(ISNULL(cte.TOTAL,0)) TOTAL,
		SUM(ISNULL(cte.bqtotal,0)) bqtotal  
		FROM #gain 
		INNER JOIN cte ON #gain.typeid=cte.typeid 
		GROUP BY #gain.usercode,#gain.fullname,#gain.leveal,#gain.typeid,#gain.sonnum,#gain.parid
	)
	SELECT b.usercode,b.fullname,b.leveal,a.typeid,b.sonnum,b.parid,A.TOTAL,a.bqtotal INTO #tempGainTable 
	FROM c1 A 
	LEFT JOIN #gain B ON A.typeid=B.typeid
	WHERE @hidezero=1 AND (a.bqtotal<>0 OR a.TOTAL<>0) 
			AND NOT EXISTS (SELECT 1 FROM c1 b WHERE a.typeid LIKE b.typeid+'%' AND b.bqtotal=0 AND b.total=0 AND b.sonnum<>0)
		OR @hidezero=0 
	ORDER BY A.typeid
	
	SELECT * FROM #tempGainTable WHERE leveal<=@itemLeveal
	
	DROP TABLE #tempGainTable
END
ELSE  --if @Period<>''
BEGIN
	SELECT 
        m.ATypeID ,
        a.typeid,
        SUM(ISNULL(m.total, 0)) AS Total ,
        SUM(ISNULL(m.bqtotal, 0)) AS bqTotal
	INTO    #monthatypehistory
	FROM    monthatypehistory m LEFT JOIN #Atype a ON a.nid=m.ATypeID
	WHERE   StypeId IN ( SELECT typeid
						 FROM   #Stype )
			AND period=@Period
			AND YEAR=@year
	GROUP BY	m.ATypeID,
				a.typeid
				

        
	CREATE TABLE #gainHistory(usercode varchar(300),fullname varchar(300),leveal int,typeid varchar(50),sonnum int,parid varchar(50),total  NUMERIC(24, 10) ,bqtotal  NUMERIC(24, 10) )	


    INSERT  INTO #gainHistory
    SELECT  a.usercode ,
            a.fullname ,
            a.leveal ,
            a.typeid ,
            a.sonnum ,
            a.parid ,
            ( 
				SELECT    ISNULL(SUM(b.total), 0)
				FROM      monthatypehistory b
				INNER JOIN ( SELECT typeId,enddate FROM #Stype )ab ON stypeid=ab.typeId
				WHERE    b.atypeid = a.nid and b.period=@period and  Year=year(ab.enddate)
            ) AS 'Total' ,
            ( 
				SELECT    ISNULL(SUM(b.bqtotal), 0)
				FROM      monthatypehistory b
				INNER JOIN ( SELECT typeId,enddate FROM #Stype )ab ON stypeid=ab.typeId
				WHERE    b.atypeid = a.nid and b.period=@period and Year=year(ab.enddate)      
            ) AS 'BqTotal'
    FROM    #Atype a
    WHERE   ( 
				LEFT(a.typeid, 5) = @ALL_INCOME_ID
				OR LEFT(a.typeid, 5) = @ALL_EXPENSE_ID
            )

	INSERT INTO #gainHistory(usercode,fullname,leveal,typeid,sonnum,parid,total,bqtotal) 
	SELECT '','【利    润】',1,'999999999999999',0,'',(select sum(case when typeid LIKE'00003%' then total else -total end) as total from #gainHistory ),(select sum(case when typeid LIKE'00003%' then bqtotal else -bqtotal end) as bqtotal from #gainHistory)			
	update #gainHistory set fullname ='    '+fullname where leveal =2
	update #gainHistory set fullname ='        '+fullname where leveal =3
	update #gainHistory set fullname ='            '+fullname where leveal =4
	update #gainHistory set fullname ='                '+fullname where leveal =5

	update #gainHistory set fullname ='                    '+fullname where leveal =6
	update #gainHistory set fullname ='                        '+fullname where leveal =7
	update #gainHistory set fullname ='                            '+fullname where leveal =8
	update #gainHistory set fullname ='                                '+fullname where leveal =9
	update #gainHistory set fullname ='                                    '+fullname where leveal =10
	--SELECT '历史损益表'
	;WITH cte AS
	(
		SELECT usercode,fullname,leveal,typeid,sonnum,parid,total,bqtotal
		FROM #gainHistory
		UNION ALL
		SELECT c.usercode,c.fullname,c.leveal,c.typeid,c.sonnum,c.parid,d.total,d.bqtotal
		FROM #gainHistory AS C
		INNER JOIN cte AS D
			ON C.typeid=D.parid
	),c1 AS (
		SELECT #gainHistory.usercode,#gainHistory.fullname,#gainHistory.leveal,#gainHistory.typeid,#gainHistory.sonnum,#gainHistory.parid,SUM(ISNULL(cte.TOTAL,0)) TOTAL,
		SUM(ISNULL(cte.bqtotal,0)) bqtotal  
		FROM #gainHistory INNER JOIN cte ON #gainHistory.typeid=cte.typeid 
		GROUP BY #gainHistory.usercode,#gainHistory.fullname,#gainHistory.leveal,#gainHistory.typeid,#gainHistory.sonnum,#gainHistory.parid
	)		
	SELECT b.usercode,b.fullname,b.leveal,a.typeid,b.sonnum,b.parid,A.TOTAL,a.bqtotal INTO #tempGainTable1 FROM c1 A 
	LEFT JOIN #gainHistory B ON A.typeid=B.typeid
	WHERE @hidezero=1 AND (a.bqtotal<>0 OR a.TOTAL<>0) 
		AND NOT EXISTS (SELECT 1 FROM c1 b WHERE a.typeid LIKE b.typeid+'%' AND b.bqtotal=0 AND b.total=0 AND b.sonnum<>0)
	OR @hidezero=0
	ORDER BY A.typeid
	SELECT * FROM #tempGainTable1 WHERE leveal<=@itemLeveal
	DROP TABLE #tempGainTable1,#monthatypehistory
END



DROP TABLE #Atype
DROP TABLE #t1,#t2;

GO





SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PromoRuleBillindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_PromoRuleBillindex]
GO

-- =============================================
-- Author:		王刚
-- Create date: 05/20/2013 
-- Description:	促销调阅
-- =============================================

CREATE PROCEDURE Web_PromoRuleBillindex
(
	@OperatorID VARCHAR(50),
	@BillCode	VARCHAR(200),	 --单据编号
	@FullName	VARCHAR(200),	 --活动名称
	@BillState	VARCHAR(50),	 --状态
	@ExecState  VARCHAR(50),	 --执行状态
	@promoStylePtype INT,		 --促销模式之商品
	@promoStyleDiscount INT,	 --促销模式之折扣
	@Comment	VARCHAR(200),	 -- 备注
	@EndDate1	VARCHAR(10)='',	 --失效时期
	@EndDate2	VARCHAR(10)='',
	@CreateDate1 VARCHAR(10)='', --编制时期
	@CreateDate2 VARCHAR(10)='',
	@StartDate1 VARCHAR(10)='', --生效时期
	@StartDate2 VARCHAR(10)='',
	@Checke		VARCHAR(MAX)	 --编制人
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

DECLARE @SQL VARCHAR(MAX)

CREATE TABLE #Checke(Typeid VARCHAR(50))
IF @Checke<> '' AND @Checke<>'00000'
	INSERT INTO #Checke(TypeId) SELECT a as typeid FROM dbo.f_split(@Checke,',')

CREATE TABLE #Stype(Typeid VARCHAR(50))
IF @MStypeid = '-99999'
	INSERT INTO #Stype(Typeid)  
	SELECT DISTINCT S.PromoRuleID AS Typeid FROM F_GetAllManagerBaseTypeId('',11,@OperatorID) F INNER JOIN PromoRule_Stype S ON S.StypeID = F.TypeId

DECLARE @CurDate VARCHAR(10)
SET @CurDate = CONVERT(varchar(10),GETDATE(),120)

SET @SQL = '
		SELECT	p.ID AS PromoRuleID,
				p.BillCode,
				P.FullName,
				P.PromoStylePtype,
				P.PromoStyleDiscount,
				P.BillState,
				CASE WHEN P.BillState = 2 AND P.StartDate > '''+@CurDate+''' THEN 1
				     WHEN P.BillState = 2 AND P.StartDate <= '''+@CurDate+''' AND P.EndDate >= '''+@CurDate+'''THEN 2
				     WHEN P.BillState = 2 AND P.EndDate < '''+@CurDate+'''THEN 3
					END AS ExecState, --执行状态
				p.StartDate,
				p.EndDate,
				p.CreateDate,
				p.VaildDate,
				p.DeletedDate,
				p.Checke,
				p.Checker,
				p.DeletedR,
				p.Comment
		FROM PromoRule P '

SET @SQL += ' WHERE 1=1 '

IF @Checke<> '' AND @Checke<>'00000'
	SET @SQL += ' AND P.Checke IN (SELECT TypeId FROM #Checke) '

IF @MStypeid = '-99999'
	SET @SQL += ' AND P.ID IN (SELECT Typeid FROM #Stype) '


IF ISNULL(@EndDate1,'') <> ''
	SET @SQL += ' AND P.EndDate >= '''+@EndDate1+''' '
IF ISNULL(@EndDate2,'') <> ''
	SET @SQL += ' AND P.EndDate <= '''+@EndDate2+''' '
IF ISNULL(@StartDate1,'') <> ''
	SET @SQL += ' AND P.StartDate >= '''+@StartDate1+''' '
IF ISNULL(@StartDate2,'') <> ''
	SET @SQL += ' AND P.StartDate <= '''+@StartDate2+''' '

IF ISNULL(@CreateDate1,'') <> ''
	SET @SQL += ' AND P.CreateDate >= '''+@CreateDate1+''' '
IF ISNULL(@CreateDate2,'') <> ''
	SET @SQL += ' AND P.CreateDate <= '''+@CreateDate2+''' '

IF @promoStylePtype <> -1
	SET @SQL += ' AND P.PromoStylePtype = '+CONVERT(VARCHAR(10),@promoStylePtype)+' '
IF @promoStyleDiscount <> -1
	SET @SQL += ' AND P.PromoStyleDiscount = '+CONVERT(VARCHAR(10),@promoStyleDiscount)+' '
		
IF @BillState <> ''
	SET @SQL += ' AND P.BillState IN('+@BillState+') '

IF @BillCode <> ''
	SET @SQL += ' AND P.BillCode LIKE ''%'+@BillCode+'%'' '
IF @FullName <> ''
	SET @SQL += ' AND P.FullName LIKE ''%'+@FullName+'%'' '
IF @Comment <> ''
	SET @SQL += ' AND P.Comment LIKE ''%'+@Comment+'%'' '

IF @ExecState = ''
	SET @SQL += ' ORDER BY P.BillCode,P.FullName '				
ELSE
	SET @SQL = 'SELECT * FROM ( 
					'+@SQL+' 
				) A 
				WHERE A.ExecState IN ('+@ExecState+') OR A.ExecState IS NULL
				ORDER BY A.BillCode,A.FullName '
	
--PRINT(@SQL)

EXEC(@SQL)

DROP TABLE #Checke

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PtypeBrandarSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_PtypeBrandarSelector
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：谢吉康
	日期：2016-05-09
	描述：商品品牌选择
-------------------------------------------*/
CREATE PROCEDURE Web_PtypeBrandarSelector
(
	@OperatorID			VARCHAR(50),
	@Filter				VARCHAR(256),
	@TypeId				VARCHAR(100),		--基本信息的Id
	@ptypeid			VARCHAR(max),
	@canSelectParId		VARCHAR(10)='0'		--是否能选父节点 1.能 0.不能
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @First    INT=0  --首次进入 对往来单位有用 其他为0

IF @TypeId='00000'
	SET @TypeId=''
IF @Filter IS NULL
	SET @Filter=''

IF ISNULL(@ptypeid,'')<>''
BEGIN
	SELECT typeid,parid,case when @Filter<>'' then 1 else leveal end AS rowlevel,usercode,fullname,comment,sonnum,soncount,issys
	FROM brandar_Commodity a,
	(
		SELECT	BrandarTypeID 
		FROM	dbo.ptype a,
				dbo.F_Split(@ptypeid,',') b
		WHERE a.typeId LIKE b.a+'%'
	)  b
	WHERE	a.typeid=b.BrandarTypeID AND  typeid<>'00000' and typeid like @TypeId+'%' AND (UserCode LIKE '%'+@Filter+'%'   OR fullname LIKE '%'+@Filter+'%') 
			AND (@Filter='' OR sonnum=0)
	ORDER BY typeid ASC
END
ELSE
BEGIN
	IF @canSelectParId = '1'
	BEGIN
		SELECT	typeid,parid,case when @Filter<>'' then 1 else leveal end AS rowlevel,usercode,fullname,comment,sonnum,soncount,issys 
		FROM	brandar_Commodity 
		WHERE   typeid<>'00000' and typeid like @TypeId+'%' AND( UserCode LIKE '%'+@Filter+'%'   OR fullname LIKE '%'+@Filter+'%' )				
		ORDER BY typeid ASC
	END 
	ELSE
	BEGIN
		SELECT	typeid,parid,case when @Filter<>'' then 1 else leveal end AS rowlevel,usercode,fullname,comment,sonnum,soncount,issys 
		FROM	brandar_Commodity 
		WHERE   typeid<>'00000' and typeid like @TypeId+'%' AND( UserCode LIKE '%'+@Filter+'%'   OR fullname LIKE '%'+@Filter+'%' )
				AND (@Filter='' OR sonnum=0)
		ORDER BY typeid ASC
	END 
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_PtypeBuyAnalysis]') and OBJECTPROPERTY(id, N'IsPROCEDURE') = 1)
DROP PROCEDURE [dbo].Web_PtypeBuyAnalysis
GO

/*
功能：单品进货分析
作者：赵和平
时间：2011-12-12

修改
修改人：李灏龙
修改时间：2012年1月9日10:07:49

--wg优化

*/ 

CREATE PROCEDURE Web_PtypeBuyAnalysis
(
	@operatorid VARCHAR(100), --操作员
	@ptypeid	VARCHAR(100), --商品ID
	@pttypeid	VARCHAR(100), --商品类
	@STypeId	VARCHAR(max), --分支机构
	@billtype	VARCHAR(50)   --单据类型
)
--@encode$--
AS

SET NOCOUNT ON

----------------------- 权限控制 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @operatorid IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
		@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @operatorid,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
----------------------- 权限控制end ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF @STypeId <> '' OR @MStypeid = '-99999' OR @MKtypeid = '-99999'
BEGIN
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@operatorid)
	CREATE INDEX GetManSTypeIdTemp_TypeId ON #GetManSTypeId(TypeId)
END

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid = '-99999'
BEGIN
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@operatorid)	
	CREATE INDEX GetManETypeIdTemp_TypeId ON #GetManETypeId(TypeId)
END

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @STypeId <> '' OR @MStypeid = '-99999' OR @MKtypeid = '-99999'
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@operatorid)

--删除仓库中的对于STypeId
IF @STypeId <> '' OR @MStypeid = '-99999' OR @MKtypeid = '-99999'
BEGIN
	DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))	
	INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')
	CREATE INDEX GetManKTypeIdTemp_TypeId ON #GetManKTypeId(TypeId)
END

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @MDtypeid = '-99999'
BEGIN
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@operatorid)	
	CREATE INDEX GetManDTypeIdTemp_TypeId ON #GetManDTypeId(TypeId)
END

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @MBtypeid = '-99999'
BEGIN
	INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@operatorid)
	CREATE INDEX GetManBTypeId_TypeId ON #GetManBTypeId(TypeId)
END


----------------------- 权限控制 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


CREATE TABLE #BillType(BillType  INT)
INSERT #BillType(BillType) SELECT * FROM f_split(@billtype,',')
CREATE INDEX CIX_BillType_TEMP ON #BillType(BillType)

CREATE TABLE #MonthProc(StartDate VARCHAR(10), EndDate VARCHAR(10), Peroid INT,year INT)
INSERT #MonthProc
SELECT CONVERT(VARCHAR(10),StartDate,120) AS StartDate, CONVERT(VARCHAR(10),ISNULL(EndDate, '9999-01-01'),120) AS EndDate, period,year FROM MonthProc where stypeid=@STypeId

INSERT #MonthProc VALUES('1900-01-01','9999-01-01',0,0)

CREATE TABLE #ResultDataTemp
(
	pqty	 NUMERIC(24, 10) , ptotal  NUMERIC(24, 10) ,
	ppqty	 NUMERIC(24, 10) , pptotal  NUMERIC(24, 10) ,
	allqty	 NUMERIC(24, 10) , alltotal  NUMERIC(24, 10) ,--全年数据
	year    INT,
	peroid	INT
)

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = ';WITH InOut AS( 
		SELECT	A.PtypeId, 
				A.BillDate,
				CASE WHEN A.BillType = 145 THEN -A.qty ELSE A.qty END AS qty,
				CASE WHEN A.BillType = 145 THEN -A.total ELSE A.total END AS total
		FROM	InOutstocktable A 
		INNER JOIN #BillType T ON T.BillType = A.BillType '

IF @STypeId <> '' OR @MStypeid = '-99999' OR @MKtypeid = '-99999'
	SET @SQL += ' INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId '
	
IF @STypeId <> '' OR @MStypeid = '-99999' OR @MKtypeid = '-99999'
	SET @SQL += ' INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId '

IF @MEtypeid = '-99999'
	SET @SQL += ' INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId '

IF @MDtypeid = '-99999'
	SET @SQL += ' INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID ' 

IF @MBtypeid = '-99999'
	SET @SQL += ' INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId '

SET @SQL += ' WHERE a.audited = 1  )'

SET @SQL += ' 
	INSERT	#ResultDataTemp
	SELECT	SUM(CASE WHEN ptypeid = '''+@ptypeid+''' THEN qty ELSE 0 END) as pqty,
			SUM(CASE WHEN ptypeid = '''+@ptypeid+''' THEN total ELSE 0 END) as ptotal, '

IF @pttypeid <> ''
	SET @SQL += ' SUM(CASE WHEN ptypeid like '''+@pttypeid+'%'' THEN qty ELSE 0 END) as ppqty,
				  SUM(CASE WHEN ptypeid like '''+@pttypeid+'%'' THEN total ELSE 0 END) as pptotal, '
ELSE
	SET @SQL += ' SUM(qty) as ppqty,
				  SUM(total) as pptotal, '
				  
SET @SQL += ' SUM(qty) as allqty,
			  SUM(total) as alltotal, '

SET @SQL += '
			m.year,
			M.peroid
			FROM InOut I 
			INNER JOIN #MonthProc M ON I.BillDate >= M.StartDate AND I.BillDate <= M.EndDate
			GROUP m.year,BY M.peroid
			ORDER m.year,BY M.peroid '
EXEC (@SQL)

DECLARE @allYearQty_P  NUMERIC(24, 10) , @allYearTotal_P  NUMERIC(24, 10) 	--进货量

SELECT @allYearQty_P = pqty, @allYearTotal_P = ptotal FROM #ResultDataTemp WHERE peroid = 0

SELECT	IDENTITY(INT,1,1) AS AutoID,
		A.pqty,
		A.ptotal,
		CASE WHEN A.ppqty = 0 THEN 0 ELSE CAST(ISNULL(A.pqty/A.ppqty*100, 0) AS  NUMERIC(24, 10) ) END AS PQB,
		CASE WHEN A.ptotal = 0 THEN 0 ELSE CAST(ISNULL(A.ptotal/A.pptotal*100, 0) AS  NUMERIC(24, 10) ) END AS PTB,
		CASE WHEN A.ppqty = 0 THEN 0 ELSE CAST(ISNULL(A.pqty/a.allqty*100, 0) AS  NUMERIC(24, 10) ) END AS PPQB,
		CASE WHEN pptotal = 0 THEN 0 ELSE CAST(ISNULL(A.ptotal/a.alltotal*100, 0) AS  NUMERIC(24, 10) ) END AS PPTB,
		CASE WHEN @allYearQty_P = 0 THEN 0 ELSE CAST(A.pqty/@allYearQty_P*100 AS  NUMERIC(24, 10) ) END AS CQB,
		CASE WHEN @allYearTotal_P = 0 THEN 0 ELSE CAST(A.ptotal/@allYearTotal_P*100 AS  NUMERIC(24, 10) ) END AS CTB,
		ISNULL(M.MonthNo,'YearData') AS YearData
INTO	#temp 
FROM #ResultDataTemp A 
LEFT JOIN MonthProc M ON A.peroid = M.period AND a.year= m.year AND stypeid =@stypeid

CREATE TABLE #Result
(
	Line_No		INT,
	Item		VARCHAR(200)
)
INSERT INTO #Result VALUES(1,'进货数量')
INSERT INTO #Result VALUES(2,'进货金额')
INSERT INTO #Result VALUES(3,'进货数量占本类商品的百分比(%)')
INSERT INTO #Result VALUES(4,'进货金额占本类商品的百分比(%)')
INSERT INTO #Result VALUES(5,'进货数量占全部商品的百分比(%)')
INSERT INTO #Result VALUES(6,'进货金额占全部商品的百分比(%)')
INSERT INTO #Result VALUES(7,'当月进货量占全部进货量的百分比(%)')
INSERT INTO #Result VALUES(8,'当月进货额占全部进货额的百分比(%)')

DECLARE @pqty		 NUMERIC(24, 10) =0,		--进货数量
		@ptotal		 NUMERIC(24, 10) =0,		--进货金额
		@pqb		 NUMERIC(24, 10) =0,		--进货数量占本类商品的百分比
		@ptb		 NUMERIC(24, 10) =0,		--进货金额占本类商品的百分比
		@ppqb		 NUMERIC(24, 10) =0,		--进货数量占全部商品的百分比
		@pptb		 NUMERIC(24, 10) =0,		--进货金额占全部商品的百分比
		@cqb		 NUMERIC(24, 10) =0,		--当月进货量占全部进货量的百分比
		@ctb		 NUMERIC(24, 10) =0			--当月进货量占全部进货量的百分比
		
DECLARE @MonthName		VARCHAR(50),	--列的名称
		@csql			VARCHAR(2000)

DECLARE @RowNum INT
SET @RowNum = 1


DECLARE @ROWCOUNT INT
SELECT @ROWCOUNT = ISNULL(MAX(AutoID),0) FROM #temp

WHILE(@RowNum <= @ROWCOUNT)
BEGIN
	SELECT @pqty=pqty,@ptotal=ptotal,@pqb=PQB,@ptb=PTB,@ppqb=PPQB,@pptb=PPTB,@cqb=CQB,@ctb=CTB,@MonthName=YearData FROM #temp WHERE AutoID = @RowNum
	--增加月结存列
	SET @csql = 'ALTER TABLE #Result ADD ['+ @MonthName +'] VARCHAR(50) NULL '
	EXEC(@csql)
	SET @csql = 'UPDATE #Result SET [' + @MonthName + '] = '+ CAST(@pqty AS VARCHAR(50)) +' WHERE Line_No = 1 '
	SET @csql += 'UPDATE #Result SET [' + @MonthName + '] = ' + CAST(@ptotal AS VARCHAR(50)) + ' WHERE Line_No = 2 '
	SET @csql += 'UPDATE #Result SET [' + @MonthName + '] = ' + CAST(@pqb AS VARCHAR(50)) + ' WHERE Line_No = 3 '
	SET @csql += 'UPDATE #Result SET [' + @MonthName + '] = ' + CAST(@ptb AS VARCHAR(50)) + ' WHERE Line_No = 4 '
	SET @csql += 'UPDATE #Result SET [' + @MonthName + '] = ' + CAST(@ppqb AS VARCHAR(50)) + ' WHERE Line_No = 5 '
	SET @csql += 'UPDATE #Result SET [' + @MonthName + '] = ' + CAST(@pptb AS VARCHAR(50)) + ' WHERE Line_No = 6 '
	SET @csql += 'UPDATE #Result SET [' + @MonthName + '] = ' + CAST(@cqb AS VARCHAR(50)) + ' WHERE Line_No = 7 '
	SET @csql += 'UPDATE #Result SET [' + @MonthName + '] = ' + CAST(@ctb AS VARCHAR(50)) + ' WHERE Line_No = 8 '
	--PRINT(@csql)
	EXEC(@csql)
	SET @RowNum = @RowNum + 1
END

IF @ROWCOUNT = 0
	SELECT Line_No, Item, 0 AS YearData, 0 AS [本期]FROM #Result
ELSE
	SELECT * FROM #Result


DROP TABLE #GetManSTypeId,#GetManETypeId,#GetManKTypeId,#GetManDTypeId,#GetManBTypeId,#BillType,#MonthProc,#ResultDataTemp,#Result,#temp
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO










if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PtypeCategorySelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_PtypeCategorySelector
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：魏伟
	日期：2016-05-09
	描述：商品类别选择
-------------------------------------------*/
CREATE PROCEDURE Web_PtypeCategorySelector
(
	@OperatorID			VARCHAR(50),
	@Filter				VARCHAR(256),
	@TypeId				VARCHAR(100),	--基本信息的Id
	@ptypeid			VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @First    INT=0  --首次进入 对往来单位有用 其他为0

IF @TypeId='00000'
	SET @TypeId=''
IF @Filter IS NULL
	SET @Filter=''

IF ISNULL(@ptypeid,'')<>''
BEGIN
	SELECT typeid,parid,case when @Filter<>'' then 1 else leveal end AS rowlevel,usercode,fullname,comment,sonnum,soncount 
	FROM PTypeCategory a,
	(
	SELECT PtypeCategoryID 
	FROM dbo.ptype a,
	 dbo.F_Split(@ptypeid,',') b
	WHERE a.typeId LIKE b.a+'%'
	)  b
	WHERE  a.typeid=b.PtypeCategoryID AND  typeid<>'00000' and typeid like @TypeId+'%' AND (UserCode LIKE '%'+@Filter+'%'   OR fullname LIKE '%'+@Filter+'%') 
	AND (@Filter='' OR sonnum=0)
END
ELSE
BEGIN
	SELECT typeid,parid,case when @Filter<>'' then 1 else leveal end AS rowlevel,usercode,fullname,comment,sonnum,soncount 
	FROM PTypeCategory 
	WHERE   typeid<>'00000' and typeid like @TypeId+'%' AND( UserCode LIKE '%'+@Filter+'%'   OR fullname LIKE '%'+@Filter+'%' )
	AND (@Filter='' OR sonnum=0)
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PTypeCheckBillUsedWhenModify]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_PTypeCheckBillUsedWhenModify]
GO

/*
*/

CREATE PROCEDURE Web_PTypeCheckBillUsedWhenModify
(
	@TypeId				VARCHAR(50),			--商品ID
	@BrandarTypeId		VARCHAR(50),			--品牌ID
	@errMsg				VARCHAR(500) OUTPUT		--输出消息
)
AS
SET NOCOUNT ON

--判断零售单
IF EXISTS(SELECT TOP 1 1 FROM dbo.retailbill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在零售单中使用，不能更改，请确认！'
	RETURN -1
END

--判断零售退货单
IF EXISTS(SELECT TOP 1 1 FROM dbo.RetailBackBill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在零售退货单中使用，不能更改，请确认！'
	RETURN -1
END

--判断销售订单
IF EXISTS(SELECT TOP 1 1 FROM dbo.orderbill mx,OrderIndex id WHERE mx.PtypeId = @TypeId AND id.billType = 300)
BEGIN
	SET @errMsg = '品牌名称已经在销售订单中使用，不能更改，请确认！'
	RETURN -1
END

--判断销售出库单
IF EXISTS(SELECT TOP 1 1 FROM dbo.SaleBill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在销售出库单中使用，不能更改，请确认！'
	RETURN -1
END

--判断销售退货单
IF EXISTS(SELECT TOP 1 1 FROM dbo.salebackbill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在销售退货单中使用，不能更改，请确认！'
	RETURN -1
END

--判断销售换货单
IF EXISTS(SELECT TOP 1 1 FROM dbo.salegoodsexchangebill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在销售换货单中使用，不能更改，请确认！'
	RETURN -1
END

--判断委托代销发货单
IF EXISTS(SELECT TOP 1 1 FROM dbo.commissionbill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在委托代销单据中使用，不能更改，请确认！'
	RETURN -1
END

--判断组合品销售出库单
IF EXISTS(SELECT TOP 1 1 FROM dbo.PT_Combin_SaleBillDetail WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在组合品销售出库单中使用，不能更改，请确认！'
	RETURN -1
END

--判断发出商品出库单
IF EXISTS(SELECT TOP 1 1 FROM dbo.SendBill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在发出商品出库单中使用，不能更改，请确认！'
	RETURN -1
END

--判断发出商品退货单
IF EXISTS(SELECT TOP 1 1 FROM dbo.SendBackBill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在发出商品退货单中使用，不能更改，请确认！'
	RETURN -1
END

--判断销售发货开票
IF EXISTS(SELECT TOP 1 1 FROM dbo.ReceiptBill WHERE PtypeId = @TypeId)
BEGIN
	SET @errMsg = '品牌名称已经在发出销售发货开票中使用，不能更改，请确认！'
	RETURN -1
END

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PtypeCombinSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_PtypeCombinSelector
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：
	日期：2016-06-16
	描述：组合品选择
-------------------------------------------*/
CREATE PROCEDURE Web_PtypeCombinSelector
(
	@OperatorID			VARCHAR(50),
	@IsStop				INT,
	@IsLimit			INT,
	@Filter				VARCHAR(256)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQL VARCHAR(MAX)

DECLARE @MinSql VARCHAR(500) = ''

SET @MinSql = ' WHERE sonnum = 0 AND iscombinationproduct = 1 '
IF @IsStop = 0
	SET @MinSql += ' AND deleted = 0'


CREATE TABLE #BaseInfo
(
	TypeID		VARCHAR(100),
	ParId		VARCHAR(100),
	SonNum		INT,
	deleted		INT,			
	UserCode	VARCHAR(256),
	FullName	VARCHAR(256),
	PyCode		VARCHAR(256),
	SortID		NUMERIC(10,0) DEFAULT(0),
	EntryCode	VARCHAR(256)
)

	
	--判断权限范围
	IF @IsLimit = 0 OR @MPtypeid = '00000'
		SET @SQL = 'INSERT INTO #BaseInfo(TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID,EntryCode) 
					SELECT TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID,EntryCode 
					FROM PType '
	ELSE
		SET @SQL = 'INSERT INTO #BaseInfo(TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID,EntryCode) 
					SELECT TypeId,ParId,SonNum,deleted,UserCode,FullName,PyCode,SortID,EntryCode FROM F_GetManPTypeAll('''+@OperatorId+''') ' 
		
	SET @SQL += @MinSql
	 
	EXEC(@SQL)
	  

	
IF @Filter = ''
BEGIN
		SELECT * FROM #BaseInfo	ORDER BY UserCode
END
ELSE
BEGIN
	SET @SQL = '
		SELECT * FROM #BaseInfo
		WHERE	SonNum = 0 
				AND (UserCode LIKE ''%'+@Filter+'%'' OR FullName LIKE ''%'+@Filter+'%'' OR PyCode LIKE ''%'+@Filter+'%'' OR EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=TypeId AND EntryCode LIKE ''%'+@Filter+'%'') )'
END
EXEC(@SQL)


DROP TABLE #BaseInfo


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PTypeGatherDetailQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_PTypeGatherDetailQuery]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：黄飞佳	
	日期：2012-05-15
	描述：商品销售汇总明细
*/
/*
    修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
    
    修改：舒珊
    日期：2016-06-21
    描述： 换算率变更前销售单位数量统计
*/

/*
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE Web_PTypeGatherDetailQuery
(
	@chvStartDate		VARCHAR(30),			-- 查询起始时间
	@chvENDDate		    VARCHAR(30),			-- 查询结束时间
	@chvPTypeID			VARCHAR(max),			-- 树型表或线性表商品类别查询范围父节点 ID
	@chvBTypeID			VARCHAR(max),			-- 结算单位
	@chvETypeID			VARCHAR(max),			-- 树型表或线性表职员类别查询范围父节点 ID
	@chvKTypeID			VARCHAR(max),			-- 树型表或线性表仓库类别查询范围父节点 ID
	@chvDTypeID			VARCHAR(max),			-- 树型表或线性表部门类别查询范围父节点 ID
	@chvStypeID			VARCHAR(max)='00000',	-- 树型表或线性表分支机构类别查询范围父节点 ID
	@sortfield			VARCHAR(50),			-- 明细表排序方式
	@checkCode			VARCHAR(max)= '',	    -- 制单人编号
	@checkName			VARCHAR(max)= '',	    -- 制单人名称
	@chvOperatorID		VARCHAR(50),			-- 操作员 ID ( 作权限范围检查用 )
	@chkRed        		CHAR(1) ='0',		    -- 显示红冲单据
	@chvBilltype    	VARCHAR(200),           -- 单据类型
	@chvComment     	VARCHAR(200)='',        -- 说明
	@chvZY 				VARCHAR(200)='',        -- 摘要
	@dealbtypeid        VARCHAR(max),           -- 树型表或线性表往来单位类别查询范围父节点 ID
	@chvPF        		CHAR(1) ='0' ,           --价保获利反利等
	@ptypeproperty      INT=0  ,                  --是否是服务商品 
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON

--------权限检查-Start--------
IF @chvOperatorID is null RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re <> 0 RETURN @Re
--------权限检查-End--------  

--------创建临时表-Start--------
--单据类型
CREATE TABLE #Billtype (BillType VARCHAR(200))
INSERT INTO #Billtype SELECT a AS Billtype FROM dbo.f_split(@chvBilltype,',')


CREATE TABLE #Ptype(TypeID VARCHAR(200))
CREATE TABLE #Stype(TypeID VARCHAR(200))
CREATE TABLE #Btype(TypeID VARCHAR(200))
CREATE TABLE #DealBtype(TypeID VARCHAR(200))
CREATE TABLE #Ktype(TypeID VARCHAR(200))
CREATE TABLE #Etype(TypeID VARCHAR(200))
CREATE TABLE #Dtype(TypeID VARCHAR(200))
DECLARE @sqlman VARCHAR(max) 
SELECT @sqlman=dbo.F_GetAllBaseInfoTypeId(@chvBTypeID,2,@chvOperatorID,'#Btype')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@dealbtypeid,2,@chvOperatorID,'#DealBtype')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@chvKTypeID,4,@chvOperatorID,'#Ktype')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@chvETypeID,3,@chvOperatorID,'#Etype')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@chvDtypeID,9,@chvOperatorID,'#Dtype')
SELECT @sqlman=@sqlman+dbo.F_GetAllBaseInfoTypeId(@chvSTypeID,11,@chvOperatorID,'#Stype')
--PRINT @sqlman
EXEC(@sqlman)

INSERT INTO #Ptype SELECT typeid FROM Ptype p WHERE typeid IN(SELECT typeid FROM F_ManPTypeInCategoryID ( @chvOperatorID,@chvPTypeID,@ptypecategoryid)) AND  ( @ptypeproperty=0 OR (p.IsService=0 AND @ptypeproperty=2)OR (p.IsService=1 AND @ptypeproperty=1)) 	


DECLARE @proxyK VARCHAR(MAX)

SET @proxyK = ''


--#Ktype为空时，代表拥有所有仓库权限，对代销库处理就采用反向、
--join #Ktype时,同时处理代销库
IF NOT (@chvKTypeID='10000' OR  @chvKTypeID='' OR  @chvKTypeID='00000')
	SET @proxyK = ' AND k.typeid <> ''10000'''


IF (@chvKTypeID='10000' OR  @chvKTypeID='' OR  @chvKTypeID='00000' ) AND EXISTS(select TOP 1 TypeID from #Ktype) 
	INSERT INTO	#Ktype select '10000'


--费用分摊设置
DECLARE @config int=0
SELECT	@config=Value FROM Userconfig WHERE ConfigName='sharefee'			

--------创建索引Start-------
CREATE CLUSTERED INDEX CIX_GetManKTypeID ON #Ktype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManETypeID ON #Etype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManPTypeID ON #Ptype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManSTypeID ON #Stype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManBTypeID ON #Btype(TypeID)
CREATE CLUSTERED INDEX CIX_GetManDTypeID ON #Dtype(TypeID)
--------创建索引End-------

--单据索引表
	CREATE TABLE #BillIndex
	(
	    BillNumberID NUMERIC(18,0),
	    BillCode VARCHAR(200),
	    BillDate DATETIME,
	    Billtype NUMERIC(10,0),
	    Tax  NUMERIC(24, 10) ,
	    RedWord INT,
		TotalMoney  NUMERIC(24, 10) ,
		TotalInMoney  NUMERIC(24, 10) ,
		CompleteTotal  NUMERIC(24, 10) ,
		BTypeID  VARCHAR (200),
		ETypeID  VARCHAR (200),
		PTypeID  VARCHAR (200),
		KTypeID  VARCHAR (200),
		PreferenceMoney  NUMERIC(24, 10) ,
		DtypeID VARCHAR(200),
		Checke  VARCHAR(50),
		Stypeid   VARCHAR(200),
		Draft BIT,
		Posttime DATETIME,
		Dealbtypeid VARCHAR(200),
		CName VARCHAR(200),
		Rate   NUMERIC(24, 10),
		Explain VARCHAR(MAX),
		comment VARCHAR(2000) 
	)
	 

	DECLARE	@strBill   VARCHAR(MAX)
	SET @strBill = 
	             'INSERT INTO #BillIndex 
	              SELECT billnumberid,
	                     billcode,
	                     billdate,
	                     a.billtype,
	                     tax,
	                     redword,
	                     totalmoney,
	                     totalinmoney,
	                     completetotal,
	                     a.btypeid,
	                     a.etypeid,
	                     a.ptypeid,
	                     a.ktypeid,
	                     preferencemoney,
	                     a.dtypeid,
	                     checke,
	                     a.stypeid,
	                     a.draft,
	                     a.posttime,
	                     a.dealbtypeid,
	                     cc.fullname,
	                     a.rate,
	                     a.Explain,
	                     a.comment
	               FROM dbo.BillIndex a --WITH(INDEX([NIX_BILLINDEX_INCLUDE]))
	               INNER JOIN #Billtype b ON a.BillType = b.Billtype
	               INNER JOIN AC_Currency cc  ON a.cid = cc.cid'
	               IF EXISTS(SELECT 1 FROM #DealBtype) 	               
                       SET @strBill = @strBill + ' INNER JOIN #DealBtype dd  ON a.dealbtypeid = dd.typeid'
	               IF EXISTS(SELECT 1 FROM #Btype) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID'
                   IF EXISTS(SELECT 1 FROM #Dtype)  	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID'
                   IF EXISTS(SELECT 1 FROM #Etype)	               
                       SET @strBill = @strBill + ' INNER JOIN #Etype e ON a.etypeid = e.TypeID'
	               IF EXISTS(SELECT 1 FROM #Stype) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID'
		           SELECT @strBill = @strBill + ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	               IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0'''   
	               
	               --增加发票立账405
	              SET @strBill += '
					UNION ALL 
					SELECT billnumberid,billcode,billdate,a.billtype,tax,redword,TotalMoney,0 AS totalinmoney,completetotal,
					a.btypeid,a.etypeid,'''' AS ptypeid,'''' AS ktypeid,0 AS preferencemoney,a.dtypeid,checke,
					a.stypeid,a.draft, posttime,a.dealbtypeid,cc.fullname,a.rate,a.Explain,a.comment 
					FROM dbo.ReceiptBillIndex AS a 
					INNER JOIN #Billtype b ON a.BillType = b.Billtype
					INNER JOIN AC_Currency cc  ON a.cid = cc.cid '
				  IF EXISTS(SELECT 1 FROM #DealBtype) 	               
                       SET @strBill = @strBill + ' INNER JOIN #DealBtype dd  ON a.dealbtypeid = dd.typeid '
	              IF EXISTS(SELECT 1 FROM #Btype) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Btype c ON a.btypeid = c.TypeID '
                  IF EXISTS(SELECT 1 FROM #Dtype)  	               
                       SET @strBill = @strBill + ' INNER JOIN #Dtype d ON a.DTypeId = d.TypeID '
                  IF EXISTS(SELECT 1 FROM #Etype)	               
                       SET @strBill = @strBill + ' INNER JOIN #Etype e ON a.etypeid = e.TypeID '
	              IF EXISTS(SELECT 1 FROM #Stype) 	               
                       SET @strBill = @strBill + ' INNER JOIN #Stype s ON a.Stypeid = s.TypeID '
	              SET @strBill += ' WHERE a.Draft =0  AND a.BillDate>='+CHAR(39)+@chvStartDate+CHAR(39)+' AND a.BillDate<='+CHAR(39)+@chvEndDate+CHAR(39)
	              IF @chkRed ='0' 
		               SET @strBill = @strBill + ' AND a.RedWord=0 '
	               IF isnull(@chvComment,'')<>'' 
		               SET @strBill = @strBill + ' AND explain LIKE '+CHAR(39)+'%'+ @chvComment +'%'+CHAR(39)
	               IF isnull(@chvZY,'')<>'' 
		               SET @strBill = @strBill + ' AND Comment LIKE '+CHAR(39)+'%'+ @chvZY +'%'+CHAR(39)
	               SET @strBill = @strBill + ' AND a.ifYearBill=''0'''  
	               
	--PRINT @strBill 
	EXEC(@strBill)
	
	--SELECT  * FROM  #BillIndex 

--红冲

DECLARE @RED_WHERE varchar(200)
SET @RED_WHERE= ''
IF @chkRed ='0'
	SET @RED_WHERE ='  b.Redword='+char(39)+'0'+char(39)
ELSE
	SET @RED_WHERE =' 1=1 '
	
-- 确定查询时间段
DECLARE @SQL_WHERE varchar(2000)
SELECT  @SQL_WHERE = ' AND b.BillDate >= ''' + @chvStartDate + '''' + ' AND b.BillDate <= ''' + @chvENDDate + ''''	
----出入库表
    CREATE TABLE #InoutStockTable
    (
		BillNumberId numeric(18, 0) ,
		BillDate datetime,
		BillType numeric(10,0),
		PtypeId varchar (200),
		KtypeId varchar (200),
		Qty  NUMERIC(24, 10) ,
		SalePrice    NUMERIC(24, 10) ,
		Price    NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		taxprice  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		tax  NUMERIC(24, 10) ,
		costPrice  NUMERIC(24, 10) ,
		ShareFee  NUMERIC(24, 10) ,
		Cargoid INT,
		NPrice  NUMERIC(24, 10) ,
		NTotal  NUMERIC(24, 10) ,
		NSalePrice  NUMERIC(24, 10) ,
		NSaleTotal  NUMERIC(24, 10) ,
		SaleTotal  NUMERIC(24, 10) ,
		NTaxPrice   NUMERIC(24, 10) ,
		NTaxTotal   NUMERIC(24, 10) ,
		FullName VARCHAR(3000),
		UserCode VARCHAR(200),
		NQty  NUMERIC(24, 10) ,
		MUnitID INT,
		NumName VARCHAR(200),
		Rate  NUMERIC(24, 10) ,
		nbrcqty  NUMERIC(24, 10) ,
        BaseUnitFullname VARCHAR(50),
        AssistantFullname VARCHAR(50),
        GoodsNumber VARCHAR(100),
        pfullname	VARCHAR(500),
        comment     VARCHAR(2000),
        CustomdetailID int,
        zy			VARCHAR(2000),
        discount    NUMERIC(24, 10)
	)
	
	DECLARE @strInOut VARCHAR(MAX)
	SET @strInOut = 
	         'INSERT INTO #InoutStockTable
			SELECT 
				BillnumberID,																														
				BillDate,																														
				BillType,																															
				PtypeID,																															
				KtypeID,
				Qty,
				SalePrice,
				price,
				Total,	  
				CostTotal,
				taxprice,  
				TaxTotal,
				tax,
				costprice,
				sharefee,
				cargoid,
				nprice,
				ntotal,
				nsaleprice,
				nsaletotal,
				saletotal,
				ntaxprice,
				ntaxtotal,
				fullname,
				usercode,
				nqty,
				munitid,
				numname,
				rate,
				T.nbrcqty  AS nbrcqty,--换算率变更前销售单位数量
				baseunitfullname,
				assistantfullname,
				goodsnumber,
				pfullname,
				comment,
				CustomdetailID,
				zy,
				discount
	         FROM
	         (
				  SELECT  
				  a.BillnumberID,																														
				  a.BillDate,																														
				  a.BillType,																															
				  a.PtypeID,																															
				  a.KtypeID,
				  a.Qty,
				  a.SalePrice,
				  a.price,
				  a.Total,	  
				  a.CostTotal,
				  a.taxprice,  
				  a.TaxTotal,
				  a.tax,
				  a.costprice,
				  a.sharefee,
				  a.cargoid,
				  a.nprice,
				  a.ntotal,
				  a.nsaleprice,
				  a.nsaletotal,
				  a.saletotal,
				  a.ntaxprice,
				  a.ntaxtotal,
				  v.fullname,
				  pp.usercode,
				  a.nqty,
				  a.munitid,
				  pu.fullname AS numname,
				  pe.rate AS rate,
				  CAST(-a.qty/a.MUnitRate AS  NUMERIC(24, 10) )  AS nbrcqty,--换算率变更前销售单位数量
				  u1.fullname AS baseunitfullname,
				  u5.fullname AS assistantfullname,
				  a.goodsnumber,
				  pp.fullname as pfullname,
				  a.comment,
				  a.id as CustomdetailID,
				  b.comment as zy,
				  a.discount
				  FROM	  InoutStockTable a 
				  INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID AND a.BillType = b.BillType 
				  left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
				  left JOIN PType_Units pu on pu.unitsid = a.munitid
				  left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
				  --left JOIN F_GetManPTypeDetailALL('''+@chvOperatorID+''') fg ON fg.typeid = a.ptypeid
				  INNER JOIN Ptype pp On pp.typeid = a.PtypeId 
			 '    
			 
			 SET @strInOut=@strInOut +' '+dbo.F_GetPtypeUnitsAndRates('pp','1,5','')
		          SET @strInOut=@strInOut + ' INNER JOIN #Ptype p On pp.typeid = p.typeid'	 
		     IF EXISTS(SELECT 1 FROM #KType)
		          SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid' + @proxyK
		          
		     SET @strInOut += '
					WHERE A.BillType NOT IN(402,403,405) '
			IF (@checkCode<>'')
		          SET @strInOut = @strInOut + ' AND pp.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+''
			 IF (@checkName<>'')
		          SET @strInOut = @strInOut + ' AND pp.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''		
			SET @strInOut += '	
				UNION ALL
				--发出商品出库单
				SELECT 
				a.BillnumberID,																														
				b.BillDate,																														
				b.BillType,																															
				a.PtypeID,																															
				a.KtypeID,
				CASE T.RedWord
					WHEN 2 THEN a.Qty - a.InvoiceQty
					ELSE -(a.Qty - a.InvoiceQty) 
				END AS Qty,
				a.SalePrice,
				a.DiscountPrice AS Price,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
					ELSE CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
				END AS Total,
				CASE T.RedWord
					WHEN 2 THEN a.CostTotal - a.InvoiceCostTotal
					ELSE -(a.CostTotal - a.InvoiceCostTotal)
				END AS CostTotal,
				a.taxprice,  
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
					ELSE CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
				END AS TaxTotal,
				a.tax,
				a.costprice,
				a.sharefee,
				a.cargoid,
				a.NDiscountPrice AS nprice,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
					ELSE CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice)  END
				END AS ntotal,
				a.nsaleprice,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.nsaletotal ELSE (a.Qty - a.InvoiceQty) * a.NSalePrice END
					ELSE CASE a.InvoiceQty WHEN 0 THEN -a.nsaletotal ELSE -((a.Qty - a.InvoiceQty) * a.NSalePrice) END
				END AS nsaletotal,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.saletotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
					ELSE CASE a.InvoiceQty WHEN 0 THEN -a.saletotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
				END AS saletotal,
				a.ntaxprice,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
					ELSE CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
				END AS ntaxtotal,
				v.fullname,
				pp.usercode,
				CASE T.RedWord
					WHEN 2 THEN a.NQty - a.InvoiceNQty
					ELSE -(a.NQty - a.InvoiceNQty)
				END AS nqty,
				a.munitid,
				pu.fullname AS numname,
				pe.rate AS rate,
				a.Mqty-(a.InvoiceQty*a.MunitRate)   AS nbrcqty,--换算率变更前销售单位数量
				u1.fullname AS baseunitfullname,
				u5.fullname AS assistantfullname,
				a.goodsnumber,
				pp.fullname as pfullname,
				a.comment,  a.id as CustomdetailID   ,
				t.Comment   AS zy,
				a.discount
				FROM SendBill AS A
				INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
				INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
				INNER JOIN Ptype pp On pp.typeid = a.PtypeId 
				left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
				left JOIN PType_Units pu on pu.unitsid = a.munitid
				left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
		     '  
		    
			 SET @strInOut=@strInOut +' '+dbo.F_GetPtypeUnitsAndRates('pp','1,5','')
		          SET @strInOut=@strInOut + ' INNER JOIN #Ptype p On pp.typeid = p.typeid'	 
		     IF EXISTS(SELECT 1 FROM #KType)
		          SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid' + @proxyK
		      SET @strInOut += '
				WHERE T.ifYearBill = 0 '
			 IF (@checkCode<>'')
		          SET @strInOut = @strInOut + ' AND pp.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+''
			 IF (@checkName<>'')
		          SET @strInOut = @strInOut + ' AND pp.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
				
			 SET @strInOut += '
				UNION ALL
				--发出商品退货单
				SELECT 
				a.BillnumberID,																														
				b.BillDate,																														
				b.BillType,																															
				a.PtypeID,																															
				a.KtypeID,
				CASE T.RedWord
					WHEN 2 THEN -(a.Qty - a.InvoiceQty)
					ELSE a.Qty - a.InvoiceQty
				END AS Qty,
				a.SalePrice,
				a.DiscountPrice AS Price,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.total ELSE -((a.Qty - a.InvoiceQty) * a.DiscountPrice) END
					ELSE CASE a.InvoiceQty WHEN 0 THEN a.total ELSE (a.Qty - a.InvoiceQty) * a.DiscountPrice END
				END AS Total,
				CASE T.RedWord
					WHEN 2 THEN -(a.CostTotal - a.InvoiceCostTotal)
					ELSE a.CostTotal - a.InvoiceCostTotal
				END AS CostTotal,
				a.taxprice,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.TaxTotal ELSE -((a.Qty - a.InvoiceQty) * a.TaxPrice) END
					ELSE CASE a.InvoiceQty WHEN 0 THEN a.TaxTotal ELSE (a.Qty - a.InvoiceQty) * a.TaxPrice END
				END AS TaxTotal,
				a.tax,
				a.costprice,
				a.sharefee,
				a.cargoid,
				a.NDiscountPrice AS nprice,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.Ntotal ELSE -((a.Qty - a.InvoiceQty) * a.NDiscountPrice) END
					ELSE CASE a.InvoiceQty WHEN 0 THEN a.Ntotal ELSE (a.Qty - a.InvoiceQty) * a.NDiscountPrice END
				END AS ntotal,
				a.nsaleprice,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.nsaletotal ELSE -((a.Qty - a.InvoiceQty) * a.NSalePrice) END
					ELSE CASE a.InvoiceQty WHEN 0 THEN a.nsaletotal ELSE (a.Qty - a.InvoiceQty) * a.NSalePrice END
				END AS nsaletotal,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.saletotal ELSE -((a.Qty - a.InvoiceQty) * a.SalePrice) END
					ELSE CASE a.InvoiceQty WHEN 0 THEN a.saletotal ELSE (a.Qty - a.InvoiceQty) * a.SalePrice END
				END AS saletotal,
				a.ntaxprice,
				CASE T.RedWord
					WHEN 2 THEN CASE a.InvoiceQty WHEN 0 THEN -a.ntaxtotal ELSE -((a.Qty - a.InvoiceQty) * a.NTaxPrice) END
					ELSE CASE a.InvoiceQty WHEN 0 THEN a.ntaxtotal ELSE (a.Qty - a.InvoiceQty) * a.NTaxPrice END
				END AS ntaxtotal,
				v.fullname,
				pp.usercode,
				CASE T.RedWord
					WHEN 2 THEN -(a.NQty - a.InvoiceNQty)
					ELSE a.NQty - a.InvoiceNQty
				END AS nqty,
				a.munitid,
				pu.fullname AS numname,
				pe.rate AS rate,
				a.Mqty-(a.InvoiceQty*a.MunitRate)   AS nbrcqty,--换算率变更前销售单位数量
				u1.fullname AS baseunitfullname,
				u5.fullname AS assistantfullname,
				a.goodsnumber,
				pp.fullname as pfullname,		
				a.comment,  a.id as CustomdetailID   ,
				t.Comment AS zy,
				a.discount
				FROM SendBackBill AS A
				INNER JOIN Billindex AS T ON(A.BillnumberID = T.BillnumberID)
				INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
				INNER JOIN Ptype pp On pp.typeid = a.PtypeId 
				left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
				left JOIN PType_Units pu on pu.unitsid = a.munitid
				left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
		     ' 
		     
		    
			 SET @strInOut=@strInOut +' '+dbo.F_GetPtypeUnitsAndRates('pp','1,5','')
		          SET @strInOut=@strInOut + ' INNER JOIN #Ptype p On pp.typeid = p.typeid'	 
		     IF EXISTS(SELECT 1 FROM #KType)
		          SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid' + @proxyK
		      SET @strInOut += '
				WHERE T.ifYearBill = 0 '
				
			 IF (@checkCode<>'')
		          SET @strInOut = @strInOut + ' AND pp.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+''
			 IF (@checkName<>'')
		          SET @strInOut = @strInOut + ' AND pp.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
		          
			 SET @strInOut += '
				UNION ALL
				--销售发货开票
				SELECT 
				a.BillnumberID,																														
				b.BillDate,																														
				b.BillType,																															
				a.PtypeID,																															
				a.KtypeID,
				CASE T.RedWord
					WHEN 2 THEN a.Qty
					ELSE -a.Qty 
				END AS Qty,
				a.SalePrice,
				a.Price,
				CASE T.RedWord
					WHEN 2 THEN a.total
					ELSE -a.total 
				END AS total,
				CASE T.RedWord
					WHEN 2 THEN a.InvoiceCostTotal
					ELSE -a.InvoiceCostTotal
				END AS CostTotal,
				a.taxprice,  
				CASE T.RedWord
					WHEN 2 THEN a.TaxTotal
					ELSE -a.TaxTotal
				END AS TaxTotal,
				a.tax,
				a.InvoiceCostPrice AS costprice,
				0 AS sharefee,
				a.cargoid,
				a.NPrice AS nprice,
				CASE T.RedWord
					WHEN 2 THEN a.Ntotal
					ELSE -a.Ntotal
				END AS Ntotal,
				a.nsaleprice,
				CASE T.RedWord WHEN 2 THEN a.nsaletotal ELSE -a.nsaletotal END AS nsaletotal,
				CASE T.RedWord WHEN 2 THEN a.saletotal ELSE -a.saletotal END AS saletotal,
				a.ntaxprice,
				CASE T.RedWord
					WHEN 2 THEN a.ntaxtotal
					ELSE -a.ntaxtotal
				END AS ntaxtotal,
				v.fullname,
				pp.usercode,
				CASE T.RedWord
					WHEN 2 THEN a.NQty
					ELSE -a.NQty
				END AS nqty,
				a.munitid,
				pu.fullname AS numname,
				pe.rate AS rate,
				a.MQty  AS nbrcqty,--换算率变更前销售单位数量
				u1.fullname AS baseunitfullname,
				u5.fullname AS assistantfullname,
				a.goodsnumber,
				pp.fullname as pfullname,
				a.comment,  a.id as CustomdetailID,
				t.comment as zy,
				a.discount
				FROM ReceiptBill AS A
				INNER JOIN ReceiptBillIndex AS T ON(A.BillnumberID = T.BillnumberID AND A.BillType = T.BillType)
				INNER JOIN #Billindex b ON T.BillnumberID=b.BillnumberID AND T.BillType = b.BillType 
				INNER JOIN Ptype pp On pp.typeid = a.PtypeId 
				left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
				left JOIN PType_Units pu on pu.unitsid = a.munitid
				left JOIN ptype_units_ext pe on pe.unitsid = a.munitid AND a.ptypeid = pe.ptypeid
		     ' 
		    
			 SET @strInOut=@strInOut +' '+dbo.F_GetPtypeUnitsAndRates('pp','1,5','')
		          SET @strInOut=@strInOut + ' INNER JOIN #Ptype p On pp.typeid = p.typeid'	 
		     IF EXISTS(SELECT 1 FROM #KType)
		          SET @strInOut=@strInOut + ' INNER JOIN #KType k ON a.KTypeID=k.typeid' + @proxyK
		      SET @strInOut += '
				WHERE T.ifYearBill = 0
				'
		         IF (@checkCode<>'')
		          SET @strInOut = @strInOut + ' AND pp.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+''
			 IF (@checkName<>'')
		          SET @strInOut = @strInOut + ' AND pp.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
		            
	SET @strInOut += '
			) AS T
	'
--********************************************************--
EXEC(@strInOut)  

declare  @insertTemp varchar(max)  
if @chvPF=1
   set @insertTemp = 'INSERT INTO #inoutstocktable(usercode,PFullName) SELECT
                              pp.usercode,pp.fullname
						FROM 	billindex b 
						INNER JOIN PriceProtectBill a ON b.billnumberid = a.billnumberid
						INNER JOIN Ptype pp On pp.typeid = a.ptypeid 
						
				'
						--IF EXISTS(SELECT 1 FROM #Ptype)  
			                SET @insertTemp=@insertTemp+' inner join #Ptype p On pp.typeid = p.typeid '+CHAR(13)
			            IF EXISTS(SELECT 1 FROM #DealBtype)  
			                SET @insertTemp=@insertTemp+' inner join #DealBtype dd  ON b.dealbtypeid = dd.typeid '+CHAR(13)
			                
		                IF EXISTS(SELECT 1 FROM #Etype)  
			                SET @insertTemp=@insertTemp+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)

		                IF EXISTS(SELECT 1 FROM #Btype)  
			                SET @insertTemp=@insertTemp+' inner Join #Btype bb	On bb.typeid =b.btypeid '+CHAR(13)
	    
		                IF EXISTS(SELECT 1 FROM #Dtype) 
			                SET @insertTemp=@insertTemp+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF EXISTS(SELECT 1 FROM #Stype) 
			                SET @insertTemp=@insertTemp+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

		                    SET @insertTemp=@insertTemp+'	WHERE  b.draft=0 AND '+@RED_WHERE+@SQL_WHERE
									
		                    SET @insertTemp = @insertTemp +' AND b.Billtype =''149'''
		
		                IF (@checkCode<>'')
		                    SET @insertTemp = @insertTemp + ' AND pp.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		                IF (@checkName<>'')
		                    SET @insertTemp = @insertTemp + ' AND pp.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	 
		
		                IF(ISNULL(@chvComment,'')!='')
			                SET @insertTemp = @insertTemp +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		                IF(ISNULL(@chvZY,'')!='')
			                SET @insertTemp = @insertTemp +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
		                SET @insertTemp = @insertTemp +' AND b.ifYearBill=''0'' AND b.isini=0'
EXEC(@insertTemp)	
 SET	@insertTemp = 'INSERT INTO #inoutstocktable(usercode,PFullName) select 
                    pp.usercode,
                    pp.fullname
					FROM billindex b 
					INNER JOIN Advantage a ON b.billnumberid =a.billnumberid
					INNER JOIN Ptype pp On pp.typeid = a.ptypeid 
					'
					IF (@checkCode<>'')
		                SET @insertTemp = @insertTemp + ' AND pp.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		            IF (@checkName<>'')
		                SET @insertTemp = @insertTemp + ' AND pp.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
					
				--	IF EXISTS(SELECT 1 FROM #Ptype)  
			                SET @insertTemp=@insertTemp+' inner join #Ptype p On pp.typeid = p.typeid '+CHAR(13)
			            IF EXISTS(SELECT 1 FROM #DealBtype)  
			                SET @insertTemp=@insertTemp+' inner join #DealBtype dd  ON b.dealbtypeid = dd.typeid '+CHAR(13)
			                
		                IF EXISTS(SELECT 1 FROM #Etype)  
			                SET @insertTemp=@insertTemp+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)

		                IF EXISTS(SELECT 1 FROM #Btype)  
			                SET @insertTemp=@insertTemp+' inner Join #Btype bb	On bb.typeid =b.btypeid '+CHAR(13)
	    
		                IF EXISTS(SELECT 1 FROM #Dtype) 
			                SET @insertTemp=@insertTemp+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF EXISTS(SELECT 1 FROM #Stype) 
			                SET @insertTemp=@insertTemp+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

					SET @insertTemp=@insertTemp+ ' WHERE  b.draft=0 and  '+@RED_WHERE+@SQL_WHERE
							
			        SET @insertTemp = @insertTemp +' AND b.Billtype =''148'''
				 
		
		            IF(ISNULL(@chvComment,'')!='')
			            SET @insertTemp = @insertTemp +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		            IF(ISNULL(@chvZY,'')!='')
			            SET @insertTemp = @insertTemp +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
	                SET @insertTemp = @insertTemp +' AND b.ifYearBill=''0'' AND b.isini=0'
	       exec(@insertTemp) 


--------创建临时表-End--------

--------价保、返利-Start--------

	
DECLARE @PRICE_SQL varchar(MAX)  --价保
SET     @PRICE_SQL ='
						SELECT 	b.billcode,	
						        b.stypeid,
								b.billtype,
								b.billdate,
								b.billnumberid,	
								b.btypeid,
								b.dealbtypeid,
								b.etypeid,
								b.dtypeid,
								b.ktypeid,
								null,
								pp.typeid as ptypeid,
								null,
								null,
								null,
								null,
							    null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								NUll,
								NUll,
								v.fullname as itemname,
								b.checke,
								cc.fullname,
								b.rate,
								null,
								null,
								null,
								null,
								null,
								null,
								0 AS antantotal,
								0 AS aqty,
								CASE WHEN b.redword = 2  THEN (-a.total)
								ELSE a.total
								END AS PriceTotal,
								CASE WHEN b.redword = 2 THEN (-a.qty)
								ELSE a.qty
								END AS pqty,
								null,
								pp.usercode,
								2 AS Flag,
								null,
								null,
								a.goodsnumber,
								''价保执行单'' AS billtypename,
								b.redword,
								null,null,null,NULL,
							    NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
							    NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
							    NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
							    NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
							    null,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
						FROM 	billindex b 
						INNER JOIN PriceProtectBill a ON b.billnumberid = a.billnumberid
						LEFT  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
						INNER JOIN Ptype pp On pp.typeid = a.ptypeid '
						IF (@checkCode<>'')
		                    SET @PRICE_SQL = @PRICE_SQL + ' AND pp.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		                IF (@checkName<>'')
		                    SET @PRICE_SQL = @PRICE_SQL + ' AND pp.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''	
						
						SET @PRICE_SQL = @PRICE_SQL +
						'
						 INNER JOIN AC_Currency cc  ON b.cid = cc.cid '
		                
		               -- IF EXISTS(SELECT 1 FROM #Ptype)  
			                SET @PRICE_SQL=@PRICE_SQL+' inner join #Ptype p On pp.typeid = p.typeid '+CHAR(13)
			            IF EXISTS(SELECT 1 FROM #DealBtype)  
			                SET @PRICE_SQL=@PRICE_SQL+' inner join #DealBtype dd  ON b.dealbtypeid = dd.typeid '+CHAR(13)
			                
		                IF EXISTS(SELECT 1 FROM #Etype)  
			                SET @PRICE_SQL=@PRICE_SQL+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)

		                IF EXISTS(SELECT 1 FROM #Btype)  
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Btype bb	On bb.typeid =b.btypeid '+CHAR(13)
	    
		                IF EXISTS(SELECT 1 FROM #Dtype) 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
	    
		                IF EXISTS(SELECT 1 FROM #Stype) 
			                SET @PRICE_SQL=@PRICE_SQL+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

		                    SET @PRICE_SQL=@PRICE_SQL+'	WHERE  b.draft=0 AND '+@RED_WHERE+@SQL_WHERE
									
		                    SET @PRICE_SQL = @PRICE_SQL +' AND b.Billtype =''149''' 
		
		                IF(ISNULL(@chvComment,'')!='')
			                SET @PRICE_SQL = @PRICE_SQL +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		                IF(ISNULL(@chvZY,'')!='')
			                SET @PRICE_SQL = @PRICE_SQL +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
		                SET @PRICE_SQL = @PRICE_SQL +' AND b.ifYearBill=''0'' AND b.isini=0'
		
---------------------------------------------------------------------------------------------------------------------	
		
DECLARE @ADTAN_SQL varchar(MAX)  --返利
SET @ADTAN_SQL ='
					 SELECT 	b.billcode,	
						        b.stypeid,
								b.billtype,
								b.billdate,
								b.billnumberid,	
								b.btypeid,
								b.dealbtypeid,
								b.etypeid,
								b.dtypeid,
								b.ktypeid,
								null,
								pp.typeid  as ptypeid,
								NULL,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								null,
								NULL,
								NULL,
								v.fullname as itemname,
								b.checke,
								cc.fullname,
								b.rate,
								null,
								null,
								null,
								null,
								null,
								null,
								CASE WHEN b.redword = 2 THEN -a.total
								ELSE a.total
								END AS antantotal,
								CASE WHEN b.redword = 2 THEN (-a.qty)
								ELSE a.qty
								END AS aqty,
								0 AS PriceTotal,
								0 AS pqty,
								null,
								pp.usercode,
								2 AS Flag,
								null,
								null,
								a.goodsnumber,
								''返利执行单'' as billtypename,
								b.redword,
								null,null,null,	NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
								NULL,null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
					FROM billindex b 
					INNER JOIN Advantage a ON b.billnumberid =a.billnumberid
					left  JOIN  vWeb_ItemIDByIsCombined v on a.iscombined = v.iscombined AND a.itemid = v.id
					INNER JOIN Ptype pp On pp.typeid = a.ptypeid '
					IF (@checkCode<>'')
		                SET @ADTAN_SQL = @ADTAN_SQL + ' AND pp.usercode LIKE '+CHAR(39)+'%'+@checkCode+'%'+CHAR(39)+'' 
		            IF (@checkName<>'')
		                SET @ADTAN_SQL = @ADTAN_SQL + ' AND pp.fullname LIKE '+CHAR(39)+'%'+@checkName+'%'+CHAR(39)+''
					SET @ADTAN_SQL = @ADTAN_SQL + 
					' INNER JOIN AC_Currency cc  ON b.cid = cc.cid '
					 
					--IF EXISTS(SELECT 1 FROM #Ptype)  
		                SET @ADTAN_SQL=@ADTAN_SQL+' inner join #Ptype p On pp.typeid = p.typeid '+CHAR(13)
		            IF EXISTS(SELECT 1 FROM #DealBtype)  
		                SET @ADTAN_SQL=@ADTAN_SQL+' inner join #DealBtype dd  ON b.dealbtypeid = dd.typeid '+CHAR(13)
		                
	                IF EXISTS(SELECT 1 FROM #Etype)  
		                SET @ADTAN_SQL=@ADTAN_SQL+' inner join #Etype e     On b.etypeid =e.typeid '+CHAR(13)

	                IF EXISTS(SELECT 1 FROM #Btype)  
		                SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Btype bb	On bb.typeid =b.btypeid '+CHAR(13)
    
	                IF EXISTS(SELECT 1 FROM #Dtype) 
		                SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Dtype d1	On d1.typeid =b.dtypeid '+CHAR(13)
    
	                IF EXISTS(SELECT 1 FROM #Stype) 
		                SET @ADTAN_SQL=@ADTAN_SQL+' inner Join #Stype ss	ON ss.typeid =b.stypeid '+CHAR(13)

					SET @ADTAN_SQL=@ADTAN_SQL+ 'WHERE  b.draft=0 and  '+@RED_WHERE+@SQL_WHERE
							
			        SET @ADTAN_SQL = @ADTAN_SQL +' AND b.Billtype =''148'''	 
		
		            IF(ISNULL(@chvComment,'')!='')
			            SET @ADTAN_SQL = @ADTAN_SQL +'  AND b.explain LIKE ''%' + @chvComment + '%''' 
		            IF(ISNULL(@chvZY,'')!='')
			            SET @ADTAN_SQL = @ADTAN_SQL +'  AND b.Comment LIKE ''%' + @chvZY + '%'''
	                SET @ADTAN_SQL = @ADTAN_SQL +' AND b.ifYearBill=''0'' AND b.isini=0'
--------价保、返利-End--------


----- 拼接头-商品编号、商品名Start-----
DECLARE  @head  VARCHAR(MAX)
SET @head= 
          'SELECT ''【''+a.usercode+''】''+isnull(a.pfullname,''''),
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  NULL,
                  a.usercode,
                  1 AS Flag,
                  NULL,
				  NULL,
				  NULL,
				  NULL,
				  NULL,
				  NULL,
				  null,
				  null as Explain,
				  null,
				NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
          FROM #InoutStockTable a GROUP BY a.usercode,a.pfullname' 
          
----- 拼接头-商品编号、商品名End-----



-----业务SQL语句-Start-----
DECLARE @strSQL VARCHAR(MAX)
SET @strSQL = 
             'SELECT  b.billcode,
             		  b.stypeid,																																																									
	                  a.billtype,
	                  CONVERT(VARCHAR(10),a.billdate,120) AS billdate,
                      a.billnumberid,
	                  b.btypeid,
	                  b.dealbtypeid,
	                  b.etypeid,
	                  b.dtypeid,
	                  a.ktypeid,																			
	                  a.cargoid,
	                  a.ptypeid,
	                 -(a.Qty)AS qty,
					  ISNULL(a.SalePrice,0) SalePrice,
					  isnull(a.Price,0) AS price,
					  isnull(a.taxPrice,0) AS taxprice,
                     -(a.Total) AS total,
					  -(a.TaxTotal) AS taxtotal, 
					  (-taxtotal)-(-total) AS taxge,
					  isnull((b.Totalinmoney+isnull(b.completeTotal,0)),0) AS totalinmoney,
					  CASE ABS(a.Qty) 
						  WHEN 0 THEN 0
						  ELSE a.costprice
					  END costprice,
					  --a.costprice,
					  -(a.CostTotal) AS costtotal,
					  -(ISNULL(a.sharefee,0)) AS sharefee,
					  -(ISNULL(b.preferencemoney,0)) AS preferencemoney,
					  a.nprice,
					  -(a.ntotal) AS ntotal,
					  a.nsaleprice,
					  -(a.nsaletotal) AS nsaletotal,
					  -(a.saletotal) AS saletotal,
					  a.ntaxprice,
					  -(a.ntaxtotal) AS ntaxtotal,
					  a.fullname as itemname,
					  b.checke,
					  b.cname,
					  b.rate,
					  -(a.nqty) AS nqty,
					  a.numname AS munit,
					  -(a.qty/a.rate) AS mqty,
					  CASE a.nbrcqty  WHEN  -(a.qty/a.rate) THEN NULL ELSE a.nbrcqty  END AS nbrcqty,
					  CASE '+CAST( @config AS VARCHAR)+' WHEN 1  THEN -(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0)) ELSE  -(a.Total) - (-a.CostTotal) END AS maoli,
					  CASE a.Total WHEN 0 THEN 0 
					  ELSE 
					  (CASE '+CAST( @config AS VARCHAR)+' 
					  WHEN 1  THEN cast( (-(a.Total) - (-a.CostTotal) - (-ISNULL(a.sharefee,0))) as 
NUMERIC(24, 10))/cast( -(a.total) as 
NUMERIC(24, 10))
                      ELSE cast( (-(a.Total) - (-a.CostTotal))as 
NUMERIC(24, 10))/cast(-(a.total)  as NUMERIC(24, 10))
                      END)*100
					  END AS maolilu,
					  CASE WHEN b.billtype IN (148,150) THEN  (a.total)
                      ELSE 0
                      END AS antantotal,
					  CASE WHEN b.billtype IN (148,150) THEN (a.qty)
					  ELSE 0
					  END AS aqty,
					  CASE WHEN b.billtype IN (149,151) THEN (a.total)
					  ELSE 0
					  END AS PriceTotal,
					  CASE WHEN b.billtype IN (149,151) THEN (a.qty)
					  ELSE 0
					  END AS pqty,
					  b.posttime,
					  a.usercode,
					  2 AS Flag,
					  a.baseunitfullname,
					  a.assistantfullname,
					  a.goodsnumber,
					  CASE a.billtype
						WHEN 11		THEN ''销售出库单''
						WHEN 45		THEN ''销售退货单''
						WHEN 305	THEN ''零售单''
						WHEN 141	THEN ''委托结算单''
						WHEN 34 	THEN ''采购入库单''
						WHEN 6 		THEN ''采购退货单''
						WHEN 145	THEN ''受托代销结算单''
						WHEN 149	THEN ''价保执行单''
						WHEN 151	THEN ''获得价保执行单''
						WHEN 148	THEN ''返利执行单''
						WHEN 150	THEN ''获利执行单''
						WHEN 160	THEN ''销售换货单''
						WHEN 161	THEN ''采购换货单''
						WHEN 215    THEN ''零售退货单''
						WHEN 402	THEN ''发出商品出库单''
						WHEN 403	THEN ''发出商品退货单''
						WHEN 405	THEN ''销售发货开票''
						WHEN 12     THEN ''组合品销售出库单''
						WHEN 46     THEN ''组合品销售退货单''
					  END AS billtypename,
					  b.redword AS RedWord,
					  (-A.Ntaxtotal)-(-A.Ntotal) AS ntaxge,
					  a.comment,
					  b.Explain,
					  (a.nsaleprice * pe.rate) as MunitPrice,  /*销售单位单价*/
					 SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
					SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40,
					customassist=dbo.F_GetCustomAssist(a.Ptypeid,-(a.Qty)),
					a.zy,
					a.discount
			  FROM #InoutStockTable a
			  INNER JOIN #BillIndex b ON a.BillNumberId = b.BillNumberID AND a.billtype = b.billtype
  			  LEFT JOIN dbo.PType_Units_Ext pe ON a.MUNITID=pe.UnitsId AND a.PtypeId=pe.PtypeID
  			  left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid

			  '
			  ---筛选制单人
			  IF @checkCode <> '' OR @checkName <> ''
              IF NOT(@checkCode='10000' OR @checkName = '代销仓库')
                 --加‘10000’是查仓库的时候要包含代销仓库
				 SET @strSQL = @strSQL +' INNER JOIN (SELECT TypeID FROM PType UNION SELECT ''10000'') AS T  ON a.PTypeID = T.TypeID'
				 
				 
		 IF  @chvPF ='1' 
			    SELECT @strSQL = @strSQL +' UNION ALL ' +@PRICE_SQL +' UNION ALL ' + @ADTAN_SQL 
			    
-----业务SQL语句-End-----
-----拼接尾-商品相关金额小计Start-----

DECLARE @tail VARCHAR(MAX);
SELECT @tail = 
       'WITH strSql AS
        ('+@strSQL+')
        SELECT * FROM strSql
        UNION ALL
        SELECT  NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                SUM(strSql.Qty),
                NULL,
                NULL,
                NULL,
                SUM(strSql.Total),
                SUM(strSql.Taxtotal),
                SUM(strSql.Taxge),
                SUM(strSql.totalinmoney),
                NULL,
                SUM(strSql.CostTotal),
                SUM(strSql.sharefee),
                NULL,
                NULL,
                SUM(strSql.ntotal),
                NULL,
                SUM(strSql.nsaletotal), 
                SUM(strSql.saletotal), 
                NULL,
                SUM(strSql.ntaxtotal),
                NULL,
                NULL,
                NULL,
                NULL,
                SUM(strSql.nqty),
                NULL,
                SUM(strSql.mqty),
                SUM(strSql.nbrcqty),
                SUM(strSql.maoli),
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                strSql.usercode,
                3 AS Flag,
                NULL,
                NULL,
                NULL,
              ''小计'',
                NULL,
                SUM(strSql.ntaxge),
                NULL,
                null as Explain,
                null,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
         FROM strSql
         GROUP BY strSql.usercode
         UNION ALL ' 
         +@head   +' '
         
-----拼接尾-商品相关金额小计End-----
DECLARE @SQL_ORDER VARCHAR(MAX) 
SELECT  @SQL_ORDER = ' ORDER BY usercode,Flag'
+ CASE @sortfield
			WHEN 'ByDate_a'		THEN ',BillDate,BillCode'	-- 按日期排序
			WHEN 'ByBillNo_a'	THEN ',BillCode'		    -- 按单据编号排序
			WHEN 'ByBillType_a'	THEN ',BillType,BillDate'	-- 按单据类型排序
			WHEN 'ByBillID_a'	THEN ',posttime'			-- 按单据真实过帐顺序排序
			WHEN 'ByDate_d'		THEN ',Billdate DESC,Billcode DESC'
			WHEN 'ByBillNo_d'	THEN ',BillCode DESC'
			WHEN 'ByBillType_d'	THEN ',BillType DESC,BillDate DESC'
			WHEN 'ByBillID_d'	THEN ',posttime DESC'
			ELSE ',posttime DESC '
			END
DECLARE @SQL VARCHAR(MAX)
	SET @SQL =@tail + @SQL_ORDER
   
                                    
EXEC(@SQL)
DROP TABLE #Billtype,#Ptype,#Btype,#Etype,#Ktype,#Dtype,#Stype,#BillIndex,#DealBtype,#InoutStockTable

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--SELECT * FROM sqllog ORDER BY id desc
--exec Web_PTypeGatherDetailQuery @chvStartDate='2012-02-26',@chvENDDate='2012-10-12',@chvPTypeID='00000',@chvBTypeID='',@chvETypeID='',@chvKTypeID='',@chvDTypeID='',@chvStypeID='',@sortfield='',@checkCode='',@checkName='',@chvOperatorID='00001',@chkRed=0,@chvBilltype='11,45,305,141,160',@chvComment='',@chvZY='',@dealbtypeid=''



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PTypePurcharseSelectorData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_PTypePurcharseSelectorData]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*

创 建 人：罗淮文
创建日期：2014-08-19
内容描述：商品采购数据报表，为获利执行单，批量导入商品提供选择

*/
CREATE PROC Web_PTypePurcharseSelectorData
(
	@stypeid VARCHAR(1550)='00001',	--分支机构查询范围父节点 ID
	@dealbtypeid VARCHAR(1550),		--往来单位
	@chvOperatorID VARCHAR(100),	--职员编号
	@startDate VARCHAR(30),
	@endDate VARCHAR(30),
	@intPageNo INT = 1,				-- 当前查询的页码
	@intPageSize INT = 14,			-- 每页的显示记录数
	@intRowCount INT = 0 OUTPUT		-- 返回总记录数
	
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @chvOperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), 
	@MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------
	DECLARE @chvPTypeId		VARCHAR(1550)		--  4、商品类别查询范围父节点 ID
	DECLARE @chvBTypeId		VARCHAR(1550)		--  5、结算单位类别查询范围父节点 ID
	DECLARE @chvETypeId		VARCHAR(1550)		--  6、职员类别查询范围父节点 ID
	DECLARE @chvKTypeId		VARCHAR(1550)		--  7、仓库类别查询范围父节点 ID
	DECLARE @chvZY	   		varchar(30) = ''	-- 	10、摘要
	DECLARE @chvPF			char(1) ='0'		--  11、是否显示价保、返利数据
	DECLARE @chvDX			CHAR(1) ='0'		--  12、是否显示代销数据
	DECLARE @chvBilltype	varchar(200)='34,6,161,145'		--  13、单据类型
	DECLARE @chvDTypeId		VARCHAR(8000)=''	--  14、部门ID
	DECLARE @chvComment		varchar(30)=''		-- 	9、说明
	SET @chvPtypeID='00000'
	SET @chvBtypeID='00000'
	--SET @dealbtypeid='00000'
	
	CREATE TABLE #Ptype (TypeID varchar(200))
	CREATE TABLE #Btype (TypeID varchar(50))
	CREATE TABLE #DealBtype (TypeID varchar(50))
	CREATE TABLE #Etype (TypeID varchar(50))
	CREATE TABLE #Ktype (TypeID varchar(50))
	CREATE TABLE #Dtype (TypeID varchar(50))
	CREATE TABLE #Stype (TypeID varchar(50))

	CREATE TABLE #MainType 
	(
		TypeID varchar(200),
		usercode varchar(200),
		fullname varchar(200),
		sonnum int,
		deleted int,
		baseunitfullname  VARCHAR(100),
		unitfullname VARCHAR(100),
		assistantfullname VARCHAR(100),
		isservice int
	) --CLD
	
	--商品
	INSERT INTO #Ptype(typeid) SELECT typeid FROM  F_GetAllManagerBaseTypeId(@chvPTypeID,1,@chvOperatorID)
	--结算单位      
	INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID,2,@chvOperatorID)

	--往来单位    
	--INSERT INTO #DealBtype(typeid) select typeid from F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID)
	IF @dealbtypeid =''
		INSERT INTO #DEALBtype SELECT a.typeid FROM  F_GetManDetailBType(@chvOperatorID) a
	ELSE
		INSERT INTO #DEALBtype 
		SELECT a.typeid 
		FROM  F_GetManDetailBType(@chvOperatorID) a, (SELECT * FROM  dbo.f_split(@dealbtypeid,',')) b 
		WHERE A.TypeId LIKE B.a+'%' 
		
	--职员
	INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvEtypeID,3,@chvOperatorID)

	--仓库
	INSERT INTO #Ktype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvKTypeID,4,@chvOperatorID)

	--分支机构
	INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperatorID)

	IF @chvDX='1' OR @chvKTypeID='' -- 全部仓库或部分仓库显示代销数据
		insert into #Ktype select '10000'

	--部门
	INSERT INTO #Dtype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvDtypeID,9,@chvOperatorID)

	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,baseunitfullname,unitfullname,assistantfullname,isservice) 
	SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,c.baseunitfullname,
	c.baseunitfullname,c.assistantfullname,p.isservice FROM Ptype p
    INNER JOIN  F_GetManPTypeDetailALL(@chvOperatorID) c ON p.typeId=c.typeID
	,(select * from F_GetManPTypeAll(@chvOperatorID)) a 
	where p.typeid=a.typeid AND p.IsService=0 AND p.sonnum=0 
	
	CREATE TABLE [dbo].[#Billtype] 
	(
		[Billtype] varchar(200)
	)
	INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@chvBilltype,',')

	CREATE TABLE #BillIndex
	(
		BillNumberId numeric(10, 0) 
	)

	DECLARE @Sql VARCHAR(4000)
	DECLARE @tempSql2 VARCHAR(4000)
	
	SET @Sql=' INSERT INTO #BillIndex(BillnumberID)    
               SELECT b.BillnumberID  
               FROM BillIndex b INNER JOIN  #Billtype n ON b.billtype =n.billtype '

	IF NOT (@chvBtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @Sql=@Sql + ' INNER JOIN  #Btype bt ON b.btypeid=bt.typeid '
		
	--IF NOT (@dealbtypeid = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	IF @dealbtypeid<>'' OR  @MBTypeID=-99999 OR @MBTypeID2=-99999
		SET @Sql=@Sql + ' INNER JOIN  #DealBtype dbt ON b.dealbtypeid=dbt.typeid '

	IF NOT (@chvETypeId = '' AND @METypeId = '00001')
		SET @Sql=@Sql + ' INNER JOIN  #Etype e  ON b.etypeid=e.typeid '

	IF NOT (@chvDTypeId = '' AND @MDtypeid='00000')
		SET @Sql=@Sql + ' INNER JOIN  #Dtype d  ON b.DtypeID=d.typeid '

	IF NOT (@stypeid = '' AND @MStypeid = '00000')
		SET @Sql = @Sql + ' INNER JOIN #SType s ON b.STypeId = s.TypeId '
		
	SET @Sql=@Sql + ' WHERE b.BillDate>='''+@startDate +''' AND b.BillDate<='''+@endDate +''' 
					  AND b.RedWord=0 AND b.Draft =0  
					  AND b.explain   LIKE ''%'+ @chvComment+'%''
					  AND b.Comment  LIKE ''%'+ @chvZY+'%'''
	SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志
	EXEC (@Sql)
	
	CREATE TABLE #InoutStockTable(
		BillNumberId	numeric(10, 0) ,
		BillType		numeric(4,0),
		PtypeId			varchar (50),
		BtypeId			varchar (50),
		Qty				 NUMERIC(24, 10) ,
		Price			 NUMERIC(24, 10) ,
		Total			 NUMERIC(24, 10) ,
		TaxTotal		 NUMERIC(24, 10) ,
		nQty			 NUMERIC(24, 10) ,
		giftqty			 NUMERIC(24, 10) 
	)
	
	SET @SQL='INSERT INTO #InoutStockTable(BillnumberID,BillType,PtypeID,BtypeID,Qty,Price,Total,TaxTotal,nqty,giftqty)
       SELECT a.BillnumberID,
              a.BillType,
              a.PtypeID,
              a.BtypeID,
              a.qty ,
			  price,
              Convert( NUMERIC(24, 10) ,a.Total),
              Convert( NUMERIC(24, 10) ,a.TaxTotal),
              a.nqty,
              case when  a.isgift=1 then a.qty else 0  end
		FROM #Billindex b 
		     INNER JOIN InoutStockTable a ON a.BillnumberID=b.BillnumberID
       		   	inner join ptype p1 on a.ptypeid=  p1.typeid '+dbo.F_GetPtypeUnitsAndRates('p1','1,5','1')
	IF NOT (@chvPTypeID ='00000' AND @MPtypeid = '00000')
		SET @SQL=@SQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
	IF NOT (@chvKTypeID='' AND @MKtypeid='00000')
		SET @SQL=@SQL+' INNER JOIN #Ktype k ON a.ktypeid=k.typeid '
	
	EXEC (@SQL)
	
	-- 客户供货商统一判断
	DECLARE @chvBTypeAll varchar(50)
	SELECT @chvBTypeAll = Value FROM UserConfig WHERE ConFigName = 'BtypeAll'

	DECLARE @chvSql varchar(8000)			--Sql字符串
	SELECT @chvSql = ''

	DECLARE @LEN int
	IF @chvPTypeId='' or @chvPTypeId='00000'
		SET @LEN =5
	ELSE
		SET @LEN =5 +LEN(@chvPTypeId)
		
	ALTER TABLE #MainType ADD AdvantageTotal  NUMERIC(24, 10) 
	ALTER TABLE #MainType ADD PriceTotal  NUMERIC(24, 10) 
	
	DECLARE @SQL1 varchar(1000)
	DECLARE @chvLen varchar(10)
	
	IF @chvPTypeId='00000' 
		SET @chvLen='5'
	ELSE
		SET @chvLen=CAST(LEN(@chvPTypeId)+5 AS varchar(20))
	
	
	CREATE TABLE #resultTable
	(
		AutoID int identity(1,1) primary key not null,
		TypeNo varchar(200),
		usercode varchar(200),
		sonnum int,
		SUM_Qty  NUMERIC(24, 10) ,
		gift_qty  NUMERIC(24, 10) ,
		Sum_Total  NUMERIC(24, 10) ,
		Sum_TaxTotal  NUMERIC(24, 10) ,
		ZeroPriceQty  NUMERIC(24, 10) ,
		AdvantageTotal  NUMERIC(24, 10) ,
		PriceTotal  NUMERIC(24, 10) ,
		price  NUMERIC(24, 10) ,
		taxage  NUMERIC(24, 10) ,
		nqty  NUMERIC(24, 10) ,
		unitfullname varchar(100),
		baseunitfullname varchar(100),
		assistantfullname varchar(200)
	)
								
	SELECT @chvSql='INSERT INTO #resultTable SELECT  a.TypeID as typeid,
					a.UserCode,
					a.sonnum,
					isnull(b.qty,0)  as SUM_Qty,
					isnull(b.giftqty,0)  as gift_qty,
					ISNULL(b.Total,0) AS Sum_Total,
					ISNULL(b.TaxTotal,0) AS Sum_TaxTotal,
					ISNULL(b.ZeroPriceQty,0) AS ZeroPriceQty,
					isnull(a.AdvantageTotal,0) as AdvantageTotal,
					isnull(a.PriceTotal,0) as PriceTotal ,
                    CASE WHEN ISNULL(b.Qty,0)=0 THEN 0 ELSE ISNULL(b.Total,0)/ISNULL(b.Qty,1) END AS price,
                    ISNULL(b.TaxTotal,0)-ISNULL(b.Total,0) AS taxge,
                    ISNULL(b.nqty,0) AS nqty,
                    a.unitfullname,
                    a.baseunitfullname,
                    a.assistantfullname
			FROM #MainType a LEFT JOIN  (SELECT 	a.ptypeid as typeid,
						Qty= SUM(CASE a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-1*a.Qty) Else Convert( NUMERIC(24, 10) ,a.Qty) END),					
						Total=SUM(CASE a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-1*a.Total) Else Convert( NUMERIC(24, 10) ,a.Total) END),
						TaxTotal=SUM(
										CASE 	a.BillType 
												WHEN 145 THEN Convert( NUMERIC(24, 10) ,-a.taxtotal)
		                             			ELSE Convert( NUMERIC(24, 10) ,a.taxtotal) 
										END
									),
						ZeroPriceQty = SUM(
											CASE 
												WHEN a.Price=0 AND a.BillType = 145 THEN ABS(a.Qty)
												WHEN a.Price=0 THEN a.Qty
												ELSE 0
											END
									   ),
						nqty= SUM(CASE a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-1*a.nqty) Else Convert( NUMERIC(24, 10) ,a.nqty) END),
						giftqty= SUM(CASE a.BillType WHEN 145 THEN Convert( NUMERIC(24, 10) ,-1*a.giftqty) Else Convert( NUMERIC(24, 10) ,a.giftqty) END)				              				
				FROM  	#InOutstocktable a '
				
				
	SET @chvSql = @chvSql + ' GROUP BY a.ptypeid
						) b 
					ON b.typeid = a.typeid
				Order by a.UserCode '
	EXEC(@chvSql)
	SELECT @intRowCount = COUNT(r.typeno) FROM #resultTable r inner join ptype p on r.typeno=p.typeid
	 WHERE p.isservice=0 and (r.Sum_Qty<>0 OR r.Sum_Total<>0)
	
	SELECT ROW_NUMBER() over(order by PPD.typeno) as _Index,
			ppd.TypeNo AS typeid,
	           ppd.UserCode,
	           p.FullName,
	           p.EntryCode,
	           ppd.Sum_Qty,
	           ppd.unitfullname,
	           ppd.Sum_Total,
	           ppd.Sum_TaxTotal,
	           p.sonnum,
	           p.customitemid,
	           p.customitemfrom,
	           p.customitemname,
	           p.ifusegoodsnum INTO #TMP
	    FROM   #resultTable ppd
	           inner JOIN ptype p
	                ON  ppd.TypeNo = p.typeId
	    WHERE  p.isservice = 0 
	    AND (ppd.Sum_Qty<>0 OR ppd.Sum_Total<>0)
	    
	    SELECT * FROM #TMP ppd
	    WHERE ppd._Index >= (@intPageNo -1) * @intPageSize
	           AND ppd._Index <= @intPageNo * @intPageSize

	DROP TABLE #TMP,#MainType,#InoutStocktable,#Billindex,#Billtype,#Ptype,#Btype,#DealBtype,#Etype,#Ktype,#Dtype,#Stype,#resultTable
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (
       SELECT *
       FROM   sysobjects s
       WHERE  s.id = OBJECT_ID('[dbo].[Web_PtypePurchaseSelectorData]')
              AND OBJECTPROPERTY(id, N'IsProcedure') = 1
   )
BEGIN
    DROP PROC Web_PtypePurchaseSelectorData
END
GO

/************************************************************
 * 创 建 人：罗淮文
 * 创建时间: 2014/4/16 15:46:05
 * 内容描述：销售/采购 商品信息
 * --EXEC Web_PtypePurchaseSelectorData '0000200001','00001',3,'2014-08-01','2014-08-17',0,1,14
 ************************************************************/
CREATE PROC Web_PtypePurchaseSelectorData
(
     @chvDealBTypeId VARCHAR(1550),	--往来单位
     @chvOperatorID VARCHAR(100),	--职员编号
     @unitconvert INT = 3,	--换算单位
     @chvStartDate VARCHAR(30),
     @chvEndDate VARCHAR(30),
     @issale BIT,
     @intPageNo INT = '',	-- 当前查询的页码
     @intPageSize INT = '',	-- 每页的显示记录数
     @intRowCount INT = 0 OUTPUT -- 返回总记录数
) 
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	IF @issale = 0
	BEGIN
	    exec Web_PTypePurcharseSelectorData 
		@chvOperatorID = @chvOperatorID,
		@chvDealBTypeId = @chvDealBTypeId,
		@STypeId = '',
		@chvStartDate = @chvStartDate,
		@chvEndDate = @chvEndDate,
		@intPageNo = @intPageNo,
		@intPageSize = @intPageSize
	END
	ELSE
	BEGIN
	    exec Web_PtypeSaleSelectorData 
		@stypeid ='',
		@dealbtypeid = @chvDealBTypeId,
		@chvOperatorID =@chvOperatorID,
		@startDate =@chvStartDate,
		@endDate =@chvEndDate,
		@intPageNo = @intPageNo,
		@intPageSize = @intPageSize
	END
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_PtypeSaleAnalysis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_PtypeSaleAnalysis]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
功能：单品销售分析
作者：赵和平
时间：2011-12-12

修改
修改人：李灏龙
修改时间：2012年1月13日8:55:13
*/
CREATE         PROCEDURE Web_PtypeSaleAnalysis
(
@chvPTypeID			VARCHAR(8000),  --商品
@chvOperatorID		VARCHAR(50),
@STypeId			VARCHAR(max),	--分支机构
@billtype           VARCHAR(100),    --单据类
@chvPtTypeID        VARCHAR(8000)   --商品类
)
--@encode$--
AS
SET NOCOUNT ON

----------------------- 权限控制 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
		@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@chvOperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@chvOperatorID)	

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@chvOperatorID)

--删除仓库中的对于STypeId
DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))	
INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@chvOperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@chvOperatorID)	

----------------------- 权限控制 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

/* 取全年相关销售数据 - Start */


--以下变量均根据时间段来统计（分全年和月结时间段）
DECLARE @numQty				 NUMERIC(24, 10)  = 0,	-- 当前商品数量
		@numTotal			 NUMERIC(24, 10)  = 0,	-- 当前商品金额
		@numCostTotal		 NUMERIC(24, 10)  = 0,	-- 当前商品成本
		@numParentQty		 NUMERIC(24, 10)  = 0,	-- 商品类数量
		@numParentTotal		 NUMERIC(24, 10)  = 0,	-- 商品类金额
		@numParentCostTotal	 NUMERIC(24, 10)  = 0,	-- 商品类成本
		@numAllQty			 NUMERIC(24, 10)  = 0,	-- 全部商品数量
		@numAllTotal		 NUMERIC(24, 10)  = 0,	-- 全部商品金额
		@numAllCostTotal	 NUMERIC(24, 10)  = 0	-- 全部商品成本

SELECT	@numQty = CASE WHEN PtypeId=@chvptypeid THEN -CAST(SUM(ISNULL(a.Qty,0)) AS  NUMERIC(24, 10) ) ELSE @numQty END,
		@numTotal = CASE WHEN PtypeId=@chvptypeid THEN -CAST(SUM(ISNULL(a.Total,0)) AS  NUMERIC(24, 10) ) ELSE @numTotal END,
		@numCostTotal = CASE WHEN PtypeId=@chvptypeid THEN -CAST(SUM(ISNULL(a.CostTotal,0)) AS  NUMERIC(24, 10) ) ELSE @numCostTotal END,
		@numParentQty = CASE WHEN LEFT(PtypeId,LEN(@chvPtTypeID))=@chvPtTypeID THEN @numParentQty - CAST(SUM(ISNULL(a.Qty,0)) AS  NUMERIC(24, 10) ) ELSE @numParentQty END,
		@numParentTotal = CASE WHEN LEFT(PtypeId,LEN(@chvPtTypeID))=@chvPtTypeID THEN @numParentTotal - CAST(SUM(ISNULL(a.Total,0)) AS  NUMERIC(24, 10) ) ELSE @numParentTotal END,
		@numParentCostTotal = CASE WHEN LEFT(PtypeId,LEN(@chvPtTypeID))=@chvPtTypeID THEN @numParentCostTotal - CAST(SUM(ISNULL(a.CostTotal,0)) AS  NUMERIC(24, 10) ) ELSE @numParentCostTotal END,
		@numAllQty = @numAllQty - CAST(SUM(ISNULL(a.Qty,0)) AS  NUMERIC(24, 10) ),
		@numAllTotal = @numAllTotal - CAST(SUM(ISNULL(a.Total,0)) AS  NUMERIC(24, 10) ),
		@numAllCostTotal = @numAllCostTotal - CAST(SUM(ISNULL(a.CostTotal,0)) AS  NUMERIC(24, 10) )
FROM	InOutStockTable a
INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId	
INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))
		AND a.audited = 1
GROUP BY a.PtypeId


-- 创建临时报表
CREATE TABLE #TempAnalyse (
Line_No		int,
Item		varchar(200),
YearData	VARCHAR(50)
)

/* 先期导入全年数据 - Start */
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(1,'销售数量',@numQty)
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(2,'销售金额',@numTotal)
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(3,'销售毛利',@numTotal-@numCostTotal)
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(4,'销售毛利率（%）', CASE WHEN @numTotal = 0 THEN 0 ELSE CAST((@numTotal-@numCostTotal)AS NUMERIC(24, 10)) /CAST(@numTotal AS NUMERIC(24, 10))*100  END )
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(5,'销售数量占本类商品的百分比（%）',CASE WHEN @numParentQty = 0 THEN 0 ELSE CAST(@numQty AS NUMERIC(24, 10))/CAST (@numParentQty AS NUMERIC(24, 10))*100 END )
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(6,'销售金额占本类商品的百分比（%）',CASE WHEN @numParentTotal = 0 THEN 0 ELSE CAST(@numTotal AS NUMERIC(24, 10))/CAST(@numParentTotal AS NUMERIC(24, 10))*100  END )
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(7,'销售毛利占本类商品的百分比（%）',CASE WHEN @numParentTotal-@numParentCostTotal = 0 THEN 0 ELSE CAST((@numTotal-@numCostTotal) AS NUMERIC(24, 10))/CAST((@numParentTotal-@numParentCostTotal) AS NUMERIC(24, 10))*100  END )
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(8,'销售数量占全部商品的百分比（%）',CASE WHEN @numAllQty = 0 THEN 0 ELSE CAST(@numQty AS NUMERIC(24, 10))/CAST(@numAllQty AS NUMERIC(24, 10))*100  END)
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(9,'销售金额占全部商品的百分比（%）',CASE WHEN @numAllTotal = 0 THEN 0 ELSE CAST(@numTotal AS NUMERIC(24, 10))/CAST(@numAllTotal AS NUMERIC(24, 10))*100  END  )
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(10,'销售毛利占全部商品的百分比（%）',CASE WHEN @numAllTotal-@numAllCostTotal = 0 THEN 0 ELSE CAST((@numTotal-@numCostTotal) AS NUMERIC(24, 10))/CAST ((@numAllTotal-@numAllCostTotal)AS NUMERIC(24, 10))*100  END )
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(11,'当月销售量占全年销售量的百分比（%）',CASE WHEN @numQty = 0 THEN 0 ELSE 100.00 END)
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(12,'当月销售额占全年销售额的百分比（%）',CASE WHEN @numTotal = 0 THEN 0 ELSE 100.00 END)
INSERT INTO #TempAnalyse(Line_No,Item,YearData) VALUES(13,'当月销售毛利占全年销售毛利的百分比（%）',CASE WHEN @numTotal-@numCostTotal = 0 THEN 0 ELSE 100.00 END)
/* 先期导入全年数据 - End */

--如果MonthProc表中有数据,即有月结存,则在临时表中加入月结存列
IF EXISTS(SELECT * FROM MonthProc where stypeid =@stypeid)
BEGIN
	DECLARE @MonthNo	varchar(50),
			@StartDate	varchar(20),
			@EndDate	varchar(20), 
			@chvSQL		varchar(100),
			@numBuyQty		 NUMERIC(24, 10) ,	--全年进货总数量
			@numBuyTotal	 NUMERIC(24, 10) ,	--全年进货总金额
			@numBuyCost		 NUMERIC(24, 10) 	--全年进货总成本
			
	--保存全年销售总数量、总金额、总成本
	SET @numBuyQty=@numQty
	SET @numBuyTotal=@numTotal
	SET @numBuyCost=@numCostTotal
	
	--定义游标
	DECLARE MONTH_CURSOR CURSOR FOR
	SELECT	MonthNo,StartDate,EndDate  FROM MonthProc where stypeid=@STypeId ORDER BY period

	OPEN MONTH_CURSOR
	FETCH NEXT FROM MONTH_CURSOR INTO	@MonthNo,
										@StartDate,
										@EndDate
	--通过循环将所有月结存取出								
	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- 增加对应的会计期间列
		SET @chvSQL = 'ALTER TABLE #TempAnalyse ADD [' + @MonthNo + '] VARCHAR(50) NULL'
		EXEC(@chvSQL)

		-- 对本期结束时间进行放开
		SET @EndDate = ISNULL(@EndDate,'9999.1.1')
		--将原值清空
		SET	@numQty = 0
		SET	@numTotal = 0
		SET	@numCostTotal = 0
		SET	@numParentQty = 0
		SET	@numParentTotal = 0
		SET	@numParentCostTotal	= 0
		SET	@numAllQty = 0
		SET	@numAllTotal = 0
		SET	@numAllCostTotal = 0

		
		SELECT	@numQty = CASE WHEN a.PtypeId=@chvptypeid THEN -CAST(SUM(ISNULL(a.Qty,0)) AS  NUMERIC(24, 10) ) ELSE @numQty END,
				@numTotal = CASE WHEN a.PtypeId=@chvptypeid THEN -CAST(SUM(ISNULL(a.Total,0)) AS  NUMERIC(24, 10) ) ELSE @numTotal END,
				@numCostTotal = CASE WHEN a.PtypeId=@chvptypeid THEN -CAST(SUM(ISNULL(a.CostTotal,0)) AS  NUMERIC(24, 10) ) ELSE @numCostTotal END,
				@numParentQty = CASE WHEN LEFT(a.PtypeId,LEN(@chvPtTypeID))=@chvPtTypeID THEN @numParentQty - CAST(SUM(ISNULL(a.Qty,0)) AS  NUMERIC(24, 10) ) ELSE @numParentQty END,
				@numParentTotal = CASE WHEN LEFT(a.PtypeId,LEN(@chvPtTypeID))=@chvPtTypeID THEN @numParentTotal - CAST(SUM(ISNULL(a.Total,0)) AS  NUMERIC(24, 10) ) ELSE @numParentTotal END,
				@numParentCostTotal = CASE WHEN LEFT(a.PtypeId,LEN(@chvPtTypeID))=@chvPtTypeID THEN @numParentCostTotal - CAST(SUM(ISNULL(a.CostTotal,0)) AS  NUMERIC(24, 10) ) ELSE @numParentCostTotal END,
				@numAllQty = @numAllQty - CAST(SUM(ISNULL(a.Qty,0)) AS  NUMERIC(24, 10) ),
				@numAllTotal = @numAllTotal - CAST(SUM(ISNULL(a.Total,0)) AS  NUMERIC(24, 10) ),
				@numAllCostTotal = @numAllCostTotal - CAST(SUM(ISNULL(a.CostTotal,0)) AS  NUMERIC(24, 10) )
		FROM	InOutStockTable a
		INNER JOIN #GetManSTypeId S ON A.STypeID = S.TypeId	
		INNER JOIN #GetManKTypeId K ON K.TypeId = A.KtypeId
		INNER JOIN #GetManETypeId E ON E.TypeId = A.EtypeId
		INNER JOIN #GetManDTypeId D ON D.TypeId = A.DTypeID
		INNER JOIN #GetManBTypeId B ON B.TypeId = A.BtypeId
		WHERE	a.BillType IN (SELECT * FROM f_split(@billtype,','))
				AND BillDate >= @StartDate
				AND BillDate <= @EndDate
				AND a.audited = 1
		GROUP BY a.PtypeId

		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(@numQty AS varchar(50)) + ' WHERE Line_No = 1'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(@numTotal AS varchar(50)) + ' WHERE Line_No = 2'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(@numTotal-@numCostTotal AS varchar(50)) + ' WHERE Line_No = 3'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numTotal = 0 THEN 0 ELSE CAST((@numTotal-@numCostTotal) AS NUMERIC(24, 10))/CAST(@numTotal AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 4'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numParentQty = 0 THEN 0 ELSE CAST(@numQty AS NUMERIC(24, 10))/CAST(@numParentQty AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 5'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numParentTotal = 0 THEN 0 ELSE CAST(@numTotal AS NUMERIC(24, 10))/CAST(@numParentTotal AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 6'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numParentTotal-@numParentCostTotal = 0 THEN 0 ELSE CAST((@numTotal-@numCostTotal)AS NUMERIC(24, 10))/CAST((@numParentTotal-@numParentCostTotal) AS NUMERIC(24, 10))*100   END AS varchar(50)) + ' WHERE Line_No = 7'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numAllQty = 0 THEN 0 ELSE CAST(@numQty AS NUMERIC(24, 10))/CAST(@numAllQty AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 8'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numAllTotal = 0 THEN 0 ELSE CAST(@numTotal AS NUMERIC(24, 10))/CAST(@numAllTotal AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 9'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numAllTotal-@numAllCostTotal = 0 THEN 0 ELSE CAST((@numTotal-@numCostTotal) AS NUMERIC(24, 10))/CAST((@numAllTotal-@numAllCostTotal) AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 10'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numBuyQty = 0 THEN 0 ELSE CAST(@numQty AS NUMERIC(24, 10))/CAST( @numBuyQty AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 11'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numBuyTotal = 0 THEN 0 ELSE CAST(@numTotal AS NUMERIC(24, 10))/CAST(@numBuyTotal AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 12'
		EXEC(@chvSQL)
		SET @chvSQL = 'UPDATE #TempAnalyse SET [' + @MonthNo + '] = ' + CAST(CASE WHEN @numBuyTotal-@numBuyCost = 0 THEN 0 ELSE CAST((@numTotal-@numCostTotal) AS NUMERIC(24, 10))/CAST((@numBuyTotal-@numBuyCost ) AS NUMERIC(24, 10))*100  END AS varchar(50)) + ' WHERE Line_No = 13'
		EXEC(@chvSQL)

		FETCH NEXT FROM MONTH_CURSOR INTO	@MonthNo,
											@StartDate,
											@EndDate
											
	END
	CLOSE MONTH_CURSOR
	DEALLOCATE MONTH_CURSOR
END


SELECT * FROM #TempAnalyse ORDER BY Line_No

DROP TABLE #TempAnalyse,#GetManSTypeId,#GetManETypeId,#GetManKTypeId,#GetManDTypeId,#GetManBTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE id = OBJECT_ID(N'[dbo].[Web_PtypeSaleSelectorData]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_PtypeSaleSelectorData]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
/*

创 建 人：罗淮文
创建日期：2014-08-20
内容描述：商品销售数据，为返利执行单，批量导入商品提供选择

*/
CREATE PROC Web_PtypeSaleSelectorData
(
	@stypeid VARCHAR(1550)='00001',	--分支机构查询范围父节点 ID
	@dealbtypeid VARCHAR(1550),		--往来单位
	@chvOperatorID VARCHAR(100),	--职员编号
	@startDate VARCHAR(30),
	@endDate VARCHAR(30),
	@intPageNo INT = 1,				-- 当前查询的页码
	@intPageSize INT = 14,			-- 每页的显示记录数
	@intRowCount INT = 0 OUTPUT -- 返回总记录数
)
--@encode$--
AS
SET NOCOUNT ON
BEGIN
---------------------------------------	权限检查 - Start	---------------------------------------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
---------------------------------------	权限检查 - END		---------------------------------------

-----------------------------------------------------参数定义开始-------------------------------------------------
	DECLARE @inputType		    char(1)					--  1、相应的统计报表功能识别参数
	DECLARE @chkDiscountQuery	char(1)					--  2、折前销售金额查询标识；0：不显示；1：显示；
	DECLARE @parid	           	varchar(50)				--  4、当前双击选择的主信息类别查询范围父节点 ID
	DECLARE @ptypeid			varchar(1550)			--  5、商品类别查询范围父节点 ID
	DECLARE @btypeid			varchar(1550)			--  6、结算单位类别查询范围父节点 ID
	DECLARE @etypeid			varchar(1550)			--  7、职员类别查询范围父节点 ID
	DECLARE @ktypeid			varchar(1550)			--  8、仓库类别查询范围父节点 ID
	DECLARE @delView        	int =1					-- 12. 是否显示已停用数据
	DECLARE @billType		    varchar(200)			-- 16. 单据类型
	DECLARE @dtypeid			varchar(1550)			-- 17、部门ID
	DECLARE @chrFlag			char(1)					-- 18、功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	DECLARE @atypeid	        varchar(1550)=''		--地区
	DECLARE @Explain			VARCHAR(1550)=''		--说明
	DECLARE @Comment			VARCHAR(1550)=''		--摘要
	DECLARE @ptypeproperty      INT=0					--是否是服务商品  
-----------------------------------------------------参数定义结束-------------------------------------------------

-----------------------------------------------------参数初始化开始-------------------------------------------------
	SET @inputType = 'P'
	SET @chkDiscountQuery = 'False'
	SET @parid = '00000'
	SET @ptypeid=''
	SET @btypeid=''
	SET @etypeid=''
	SET @ktypeid=''
	SET @delView = 0
	SET @billType = '11,45,305,141,160,215'
	SET @dtypeid = ''
	SET @chrFlag = 1
	SET @atypeid = ''
	SET @Explain = ''
	SET @Comment = ''
-----------------------------------------------------参数初始化结束-------------------------------------------------

	-- 根据传入的报表类型，确定将要查询的主信息类型表名 及 主信息类型列名
	DECLARE @chvTableName varchar(15), @chvColName varchar(15)
	SET @chvColName = 'PTypeID'
	
----------------------------------------基础数据表结构创建开始-------------------------------------------------------
	CREATE TABLE #Ptype (TypeID varchar(200))
	CREATE TABLE #Btype (TypeID varchar(50))
	CREATE TABLE #DEALBtype (TypeID varchar(50))  --新增的往来单位
	CREATE TABLE #Etype (TypeID varchar(50))
	CREATE TABLE #Ktype (TypeID varchar(50))
	CREATE TABLE #Dtype (TypeID varchar(50))
	CREATE TABLE #Stype (TypeID varchar(50))
	CREATE TABLE #Atype (TypeID varchar(50)) --地区
	CREATE TABLE #MainType 
	(
		TypeID varchar(200),
		usercode varchar(200),
		fullname varchar(200),
		sonnum int,
		deleted int,
		assistantfullname  VARCHAR(100),
		ufullname VARCHAR(100)
	)
----------------------------------------基础数据表结构创建结束-------------------------------------------------------

	IF @ptypeid =''
	INSERT INTO #Ptype(typeid) SELECT typeid FROM F_GetManDetailPType(@chvOperatorID)
	ELSE
		INSERT INTO #Ptype(typeid) 
		SELECT a.typeid 
		FROM F_GetManDetailPType(@chvOperatorID) a,(SELECT * FROM  dbo.f_split(@ptypeid,',')) b 
		WHERE A.TypeId LIKE B.a+'%'

	IF @btypeid =''
		INSERT INTO #Btype SELECT a.typeid FROM  F_GetManDetailBType(@chvOperatorID) a
	ELSE
		INSERT INTO #Btype 
		SELECT a.typeid 
		FROM  F_GetManDetailBType(@chvOperatorID) a, (SELECT * FROM  dbo.f_split(@btypeid,',')) b 
		WHERE A.TypeId LIKE B.a+'%' 
	 
	IF @dealbtypeid =''
		INSERT INTO #DEALBtype SELECT a.typeid FROM  F_GetManDetailBType(@chvOperatorID) a
	ELSE
		INSERT INTO #DEALBtype 
		SELECT a.typeid 
		FROM  F_GetManDetailBType(@chvOperatorID) a, (SELECT * FROM  dbo.f_split(@dealbtypeid,',')) b 
		WHERE A.TypeId LIKE B.a+'%' 
	
	IF @etypeid=''
	INSERT INTO #Etype SELECT typeid FROM F_GetManDetailEType(@chvOperatorID)
	ELSE
		INSERT INTO #Etype 
		SELECT a.typeid 
		FROM F_GetManDetailEType(@chvOperatorID) a, (SELECT * FROM  dbo.f_split(@etypeid,',')) b 
		WHERE A.TypeId LIKE B.a+'%' 

	IF @ktypeid=''
		INSERT INTO #Ktype SELECT typeid  FROM F_GetManDetailKType(@chvOperatorID)
		
	ELSE
		INSERT INTO #Ktype 
		SELECT a.typeid 
		FROM F_GetManDetailKType(@chvOperatorID) a,(SELECT * FROM  dbo.f_split(@ktypeid,',')) b 
		WHERE A.TypeId LIKE B.a+'%' 

	IF @ktypeid=''
		INSERT INTO #Ktype SELECT '10000'
		
	IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'QpEdition' AND (SubValue = '1' OR SubValue = '3'))
	BEGIN
		DELETE #KType WHERE TypeID='10000'
	END

	IF @dtypeid=''
	BEGIN
		INSERT INTO #Dtype SELECT ''
	END

	INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)

	IF NOT(@stypeid='' and @MStypeid='00000')
		INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperatorID)
	
	DECLARE @strTemp	VARCHAR(8000)

	DECLARE @JtParid VARCHAR(50) --具体的parid
	IF @parid=''
		SET @JtParid='00000'
	ELSE
		SET @JtParid=@parid
	
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,assistantfullname,ufullname) 
	SELECT c.typeid,c.usercode,c.fullname,c.sonnum,c.deleted,c.baseunitfullname,c.baseunitfullname
	FROM F_GetManPTypeDetailALL(@chvOperatorID) c 
	WHERE c.isservice=0 AND c.sonnum=0
	
	UPDATE #MainType SET FullName =FullName +'[已停用]' WHERE Deleted =1
	
	CREATE TABLE [dbo].[#Billtype] ([Billtype] varchar(200))
	INSERT INTO #Billtype SELECT a as Billtype FROM dbo.f_split(@billType,',')
	
	DECLARE @SQL_GROUP varchar(8000)  -- Billindex 和 inoutstocktable 显示的聚合
	DECLARE @SQL_GROUP1 varchar(8000) -- Billindex 和 inoutstocktable 聚合时的聚合条件
	DECLARE @Len int = 5
	
	SET @SQL_GROUP = 'substring(a.ptypeid,1,'+cast(@Len as varchar)+') as ptypeid'
	SET @SQL_GROUP1 = 'substring(a.ptypeid,1,'+cast(@Len as varchar)+')'
	
	CREATE TABLE #BillIndex
	(
		BillNumberId numeric(10, 0) ,
		RedWord  int ,
		TypeID	VARCHAR(50),
		preferencemoney  NUMERIC(24, 10) 
	)
	
	SELECT @strTemp=' 
			INSERT INTO #BillIndex(BillnumberID,RedWord,TypeID) 
			SELECT b.BillnumberID,b.RedWord,'''' AS TypeID
     		FROM BillIndex b
			INNER JOIN #Billtype BILL ON b.billtype=BILL.billtype '

    IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
    SET @strTemp=@strTemp+' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '
   
    IF @dealbtypeid<>'' OR  @MBTypeID=-99999 OR @MBTypeID2=-99999
    SET @strTemp=@strTemp+' INNER JOIN #DEALBtype db ON b.dealbtypeid=db.typeid '

    IF @etypeid<>'' OR @METypeID=-99999 
    SET @strTemp=@strTemp+' INNER JOIN #Etype e  ON b.etypeid=e.typeid '

    IF @dtypeid<>'' OR @MDTypeID=-99999
    SET @strTemp=@strTemp+' INNER JOIN #Dtype d  ON  b.DtypeID=d.typeid '
    
    IF NOT(@stypeid='' and @MStypeid='00000')
    SET @strTemp=@strTemp+' INNER JOIN #Stype s  ON  b.stypeID=s.typeid '
       
	SET @strTemp=@strTemp+' WHERE b.RedWord=0 AND b.isini=0 AND b.Draft =0  AND b.BillDate>='+CHAR(39)+@startDate+CHAR(39)+' AND b.BillDate<='+CHAR(39)+@endDate+CHAR(39)+ ' '
	SET @strTemp=@strTemp+' AND b.ifYearBill=''0'''  --年节存标志
    EXEC(@strTemp) 
    
    DECLARE @SQL1 varchar(2000)
    
    CREATE TABLE #InoutStockTable
    (
		BillNumberId numeric(10, 0) ,
		RedWord int ,
		preferencemoney  NUMERIC(24, 10) ,
		BillDate datetime,
		BillType numeric(4,0),
		TypeId varchar (50), --代码仓库 职员 商品 地区等
		Qty  NUMERIC(24, 10) ,
		Price  NUMERIC(24, 10) ,
		Total  NUMERIC(24, 10) ,
		CostTotal  NUMERIC(24, 10) ,
		Tax  NUMERIC(24, 10) ,
		Discount  NUMERIC(24, 10) ,
		SaleTotal  NUMERIC(24, 10) ,
		TaxTotal  NUMERIC(24, 10) ,
		ShareFee  NUMERIC(24, 10) ,
		giftqty   NUMERIC(24, 10)  ,
		nqty      NUMERIC(24, 10) 
	)
	
	SELECT @strTemp='
			INSERT INTO #InoutStockTable(
			BillnumberID,
			RedWord,
			preferencemoney,
			BillDate,
			BillType,
			TypeID,
			Qty,
			Price,
			Total,
			CostTotal,
			Tax,
			Discount,
			SaleTotal,
			TaxTotal,
			sharefee,
			giftqty,
			nqty
			)
		SELECT 
				a.BillnumberID,
				b.RedWord,
				b.preferencemoney,
				a.BillDate,
				a.BillType, '
	SET @strTemp += ' a.ptypeid, '
					
	SET @strTemp += '
					-a.qty,price,		
					-Convert( NUMERIC(24, 10) ,a.Total),
					-Convert( NUMERIC(24, 10) ,a.CostTotal),
					a.Tax,
					a.Discount,
					-Convert( NUMERIC(24, 10) ,a.SaleTotal),
					-Convert( NUMERIC(24, 10) ,a.TaxTotal),
					-Convert( NUMERIC(24, 10) ,a.sharefee),
					case when  a.isgift=1 and a.price=0 then -a.qty else 0  end ,
					-a.nqty
					FROM InoutStockTable a
					INNER JOIN #Billindex b ON a.BillnumberID=b.BillnumberID 
					INNER JOIN ptype p1 on a.ptypeid=  p1.typeid 
					'+dbo.F_GetPtypeUnitsAndRates('p1','1,5','1')
					
	IF @ptypeid<>'' OR @MPTypeID=-99999 
	SET @strTemp=@strTemp+'	INNER JOIN #Ptype p ON a.ptypeid=p.typeid '+CHAR(13)

	IF @ktypeid<>'' OR @MKTypeID=-99999 
	SET @strTemp=@strTemp+'	INNER JOIN #Ktype k ON a.ktypeid=k.typeid '+CHAR(13)

	SELECT @strTemp = @strTemp + ' where  a.BillDate BETWEEN '+CHAR(39)+@startDate+CHAR(39)+' AND '+CHAR(39)+@endDate+CHAR(39)+ ' AND a.Audited=1  '
	
	EXEC(@strTemp)
	
	DECLARE @COL1 varchar(200)
	DECLARE @COL2 varchar(100)
	DECLARE @COL3 varchar(100)
	DECLARE @COL4 varchar(100)

	SET @COL1 =''
	SET @COL2 =''
	SET @COL3 =''
	SET @COL4 =''


	SET @COL1 =@COL1+',ISNULL(SUM(ISNULL(b.SaleTotal,0)),0) as SUM_DiscountTotal'

	DECLARE @SQL varchar(4000),@config int=0
	SELECT @config=Value FROM Userconfig WHERE ConfigName='sharefee'
	
	CREATE TABLE #SalePtypeData
	(
    	AutoID                INT IDENTITY(1, 1) PRIMARY KEY,
    	typeid                VARCHAR(100),
    	usercode              VARCHAR(100),
    	fullname              NVARCHAR(1000),
    	sonnum                 NUMERIC(24, 10) ,
    	DELETED               INT,
    	SUM_DiscountTotal      NUMERIC(24, 10) ,
    	SUM_Qty                NUMERIC(24, 10) ,
    	gift_qty			   NUMERIC(24, 10) ,
    	ZeroPriceQty           NUMERIC(24, 10) ,
    	Price                  NUMERIC(24, 10) ,
    	SUM_Total              NUMERIC(24, 10) ,
    	SUM_TaxTotal           NUMERIC(24, 10) ,
    	TaxGe                  NUMERIC(24, 10) ,
    	CostPrice              NUMERIC(24, 10) ,
    	SUM_CostTotal          NUMERIC(24, 10) ,
    	SUM_MaoLi              NUMERIC(24, 10) ,
    	SUM_MaoLiLu            NUMERIC(24, 10) ,
    	SUM_PEMaoLi            NUMERIC(24, 10) ,
    	SUM_PEMaoLiLu          NUMERIC(24, 10) ,
    	sharefee               NUMERIC(24, 10) ,
    	nqty                   NUMERIC(24, 10) ,
    	assistantfullname     VARCHAR(100),
    	ufullname             VARCHAR(100)
	  )
	  
	SET @SQL = 'INSERT INTO #SalePtypeData
				SELECT case when ('''+@inputType+'''=''A'') AND a.typeid=''''  then ''99999'' else a.typeid end as typeid,
					a.usercode,
					a.fullname,
					a.sonnum,
					a.deleted'+
					@COL1+',
					sum(isnull(b.qty,0))as SUM_Qty,
					sum(isnull(b.giftqty,0)) as gift_qty,
					ISNULL(SUM(CASE WHEN ISNULL(b.Price,0)=0 THEN ISNULL(b.Qty,0)	ELSE 0	END),0) AS ZeroPriceQty,
					Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  ISNULL(SUM(ISNULL(b.total,0)),0)/SUM(ISNULL(b.qty,0)) END) as Price,
					ISNULL(SUM(ISNULL(b.total,0)),0) as SUM_Total,
					ISNULL(SUM(ISNULL(b.TaxTotal,0)),0) as SUM_TaxTotal,
					ISNULL(SUM(ISNULL(b.TaxTotal,0)),0)-ISNULL(SUM(ISNULL(b.total,0)),0) as TaxGe,
					Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  ISNULL(SUM(ISNULL(b.CostTotal,0)),0)/SUM(ISNULL(b.qty,0)) END) as CostPrice,
					ISNULL(SUM(ISNULL(b.CostTotal,0)),0) as SUM_CostTotal,
					ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0)'+CASE @config WHEN 1 THEN '-ISNULL(SUM(ISNULL(b.sharefee,0)),0)'ELSE '' END+@COL2+' as SUM_MaoLi,
					Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.Total,0)),0)=0 THEN 0 ELSE 
						(ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0)'	+
						CASE @config WHEN 1 THEN '-ISNULL(SUM(ISNULL(b.sharefee,0)),0)'ELSE '' END+@COL2+')/SUM(ISNULL(b.Total,0))*100 end) as SUM_MaoLiLu,
					ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0)'+CASE @config WHEN 1 THEN '-ISNULL(SUM(ISNULL(b.sharefee,0)),0)'ELSE '' END+@COL3+' as SUM_PEMaoLi,
					Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.Total,0)),0)=0 THEN 0 ELSE 
						(ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0)'+
						CASE @config WHEN 1 THEN '-ISNULL(SUM(ISNULL(b.sharefee,0)),0)'ELSE '' END+@COL3+')/SUM(ISNULL(b.Total,0))*100 end) as SUM_PEMaoLiLu,
					ISNULL(SUM(ISNULL(b.sharefee,0)),0) as sharefee,
					ISNULL(SUM(ISNULL(b.nqty,0)),0) as nqty,
					a.assistantfullname,
					a.ufullname
			   FROM #MainType a
			   LEFT JOIN #InoutStockTable b ON a.TypeID =  b.typeid
			   GROUP BY 
					a.typeid,
					a.usercode,
					a.fullname,
					a.sonnum,
					a.deleted,
					a.ufullname,	
					a.assistantfullname
					'+@COL4 +'
				ORDER BY a.UserCode '
	
	EXEC(@SQL)
	
	
	SELECT @intRowCount = COUNT(r.typeid) FROM #SalePtypeData r inner join ptype p on r.typeid=p.typeid
	 WHERE p.isservice=0 and (r.Sum_Qty<>0 OR r.Sum_Total<>0)
	
	--数据返回
	SELECT row_number() over(order by ppd.typeid) as _index,
	ppd.typeid,
	           ppd.UserCode,
	           p.FullName,
	           p.EntryCode,
	           ppd.Sum_Qty,
	           ppd.ufullname AS unitfullname,
	           ppd.Sum_Total,
	           ppd.Sum_TaxTotal,
	           p.sonnum,
	           p.customitemid,
	           p.customitemfrom,
	           p.customitemname,
	           p.ifusegoodsnum INTO #TMP
	 FROM   #SalePtypeData ppd
	           INNER JOIN ptype p
	                ON  ppd.typeid = p.typeId
	 WHERE  p.isservice = 0 
	 AND (ppd.Sum_Qty<>0 OR ppd.Sum_Total<>0)
	 
	 SELECT * FROM #TMP ppd
	 WHERE ppd._index > (@intPageNo -1) * @intPageSize
	 AND ppd._index <= @intPageNo * @intPageSize
	           
	DROP TABLE #Ptype
	DROP TABLE #Btype
	DROP TABLE #DEALBtype
	DROP TABLE #Etype
	DROP TABLE #Ktype
	DROP TABLE #Dtype
	DROP TABLE #Maintype
	DROP TABLE #InoutStockTable,#Stype,#SalePtypeData
	DROP TABLE #TMP
			
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_PullSignalQuery]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_PullSignalQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：武智均
	日期：2019-11-18
	描述：要货申请单查询
*/
CREATE  PROCEDURE Web_PullSignalQuery
    (
      @operator VARCHAR(200) ,		--操作员id
      @billdatestart DATETIME ,			--单据创建日期起始
      @billdateend DATETIME ,			--单据创建日期结束
      @billtype VARCHAR(50) ,		--单据类型
      @stypeid VARCHAR(MAX) ,		--分支机构id
      @ptypeidstr VARCHAR(MAX) ,		--多商品id
      @etypeid VARCHAR(MAX) ,		--职员id
      @ktypeid VARCHAR(MAX) ,		--出库仓库id
      @ktypeidin VARCHAR(MAX) ,		--入库仓库id
      @billstate VARCHAR(50) ,		--单据状态
      @billover VARCHAR(50) ,		--单据中止状态
      @billexec VARCHAR(50)			--单据执行状态
    )
AS 
    SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
    IF @operator IS NULL 
        RETURN 1
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @operator, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT
    IF @Re <> 0 
        RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

    IF ISNULL(@operator, '') = '' 
        BEGIN
            SET @operator = '00001'
        END
--权限分支机构
    CREATE TABLE #stype
        (
          TypeID VARCHAR(50) ,
          usercode VARCHAR(50) ,
          fullname VARCHAR(100)
        )
    CREATE CLUSTERED INDEX CIX_Stype ON #Stype(TypeId) 
    SET @stypeid = LTRIM(RTRIM(@stypeid))
    IF NOT ( @stypeid = '' AND @MStypeid = '00000' ) 
        BEGIN
            INSERT  INTO #Stype
                    ( TypeId ,
                      usercode ,
                      fullname
                    )
                    SELECT  a.TypeId ,
                            s.UserCode ,
                            s.FullName
                    FROM    F_GetAllManagerBaseTypeId(@stypeid, 11, @operator) a
                            INNER JOIN SType s ON s.TypeId = a.TypeId		
        END
    ELSE 
        INSERT  INTO #Stype
                ( TypeId ,
                  usercode ,
                  fullname
                )
                SELECT  a.TypeId ,
                        s.UserCode ,
                        s.FullName
                FROM    F_GetAllManagerBaseTypeId(@stypeid, 11, @operator) a
                        INNER JOIN SType s ON s.TypeId = a.TypeId	

--权限经手人(职员) 门店不受 调拨查询中经手人权限有效 控制
    CREATE TABLE #EType
        (
          TypeId VARCHAR(100) ,
          fullname VARCHAR(100)
        )	
    INSERT  INTO #EType
            ( TypeId ,
              fullname
            )
            SELECT  a.Typeid ,
                    e.fullname
            FROM    ( SELECT    TypeId
                      FROM      F_GetAllManagerBaseTypeId(@ETypeId, 3,
                                                          @Operator)
                    ) a
                    INNER JOIN employee e ON a.TypeId = e.typeId

--权限商品
    CREATE TABLE #Ptype ( TypeID VARCHAR(200) )
    IF @ptypeidstr = '' 
        INSERT  INTO #Ptype
                ( typeid
                )
                SELECT  typeid
                FROM    F_LinePC(@operator, '') 
    ELSE 
        INSERT  INTO #Ptype
                ( typeid
                )
                SELECT  a.typeid
                FROM    F_ManPTypeInCategoryID(@operator, @ptypeidstr, '') a ,
                        ( SELECT    *
                          FROM      dbo.f_split(@ptypeidstr, ',')
                        ) b
                WHERE   A.TypeId LIKE B.a + '%'

--权限部门
    CREATE TABLE #Dtype
        (
          TypeID VARCHAR(50) ,
          fullname VARCHAR(100)
        )
    INSERT  INTO #Dtype
            ( TypeID ,
              fullname
            )
            SELECT  a.typeid ,
                    d.FullName
            FROM    F_GetAllManagerBaseTypeId('', 9, @operator) a
                    INNER JOIN Department d ON d.typeid = a.TypeId
	
	
--所有管辖仓库
    CREATE TABLE #KType ( TypeId VARCHAR(100) )

    DECLARE @limt INT 
    SELECT  @limt = Value
    FROM    dbo.Userconfig
    WHERE   ConfigName = 'postransktypelimit'

    IF @MKtypeid = '-99999'
        AND @limt = 1 
        BEGIN
            INSERT  INTO #KType
                    ( TypeId
                    )
                    SELECT  TypeId
                    FROM    F_GetMANDetailKType(@operator)
        END


--入库仓库
    CREATE TABLE #KType1
        (
          TypeId VARCHAR(100) ,
          Fullname VARCHAR(200)
        ) 
    IF @MKtypeid = '-99999' AND @limt = 1 AND @operator <> '00001' 
        BEGIN
            INSERT  INTO #KType1
                    ( TypeId ,
                      Fullname
                    )
                    SELECT  sk.TypeId ,
                            K1.Fullname
                    FROM    F_GetAllBaseTypeId(@ktypeidin, 4) sk
                            INNER JOIN #KType k ON sk.typeid = k.typeid
                            INNER JOIN STOCK K1 ON K1.TYPEID = K.typeid
        END
    ELSE 
        BEGIN
            INSERT  INTO #KType1
                    ( TypeId ,
                      Fullname
                    )
                    SELECT  K.TypeId ,
                            K1.Fullname
                    FROM    F_GetAllBaseTypeId(@ktypeidin, 4) K
                            INNER JOIN STOCK K1 ON K1.TYPEID = K.typeid
        END

--出仓库
    CREATE TABLE #KType2
        (
          TypeId VARCHAR(100) ,
          Fullname VARCHAR(200)
        )
    IF @MKtypeid = '-99999' AND @limt = 1 AND @operator <> '00001' 
        BEGIN
            INSERT  INTO #KType2
                    ( TypeId ,
                      Fullname
                    )
                    SELECT  sk.TypeId ,
                            K1.Fullname
                    FROM    F_GetAllBaseTypeId(@ktypeid, 4) sk
                            INNER JOIN #KType k ON sk.typeid = k.typeid
                            INNER JOIN STOCK K1 ON K.typeid = K1.typeid
        END
    ELSE 
        BEGIN
            INSERT  INTO #KType2
                    ( TypeId ,
                      Fullname
                    )
                    SELECT  K.TypeId ,
                            K1.Fullname
                    FROM    F_GetAllBaseTypeId(@ktypeid, 4) K
                            INNER JOIN STOCK K1 ON K.typeid = K1.typeid
        END	
    CREATE TABLE #billexecstate
        (
          execstate INT ,
          billnumberid NUMERIC(10, 0)
        )

    INSERT  INTO #billexecstate
            ( execstate ,
              billnumberid
            )
            SELECT  CASE WHEN pb.isdone = 1 THEN 7
                         WHEN T.Qty > 0 THEN 6
                         ELSE 0
                    END AS execstate ,
                    pb.billnumberid
            FROM    PosAllotApplyBillIndex pb
                    LEFT JOIN ( SELECT  ISNULL(SUM(db.Qty), 0) Qty ,
                                        da.BillNumberId
                                FROM    dbo.DeliveryBill db
                                        INNER JOIN dbo.DeliveryApplyBill da ON da.ID = db.DeliveryApplyBillId
                                        INNER JOIN PosAllotApplyBillIndex pab ON db.BillNumberId = pab.BillNumberId
                                WHERE   pab.BillType = 327
                                        AND pab.RedWord = 0
                                GROUP BY da.BillNumberId
                              ) T ON T.BillNumberId = pb.BillNumberId
            WHERE   pb.BillType = 326 

--SELECT * FROM #billexecstate

    DECLARE @SQL NVARCHAR(MAX)
    SET @SQL = N'
			SELECT  ROW_NUMBER() OVER ( ORDER BY i.billnumberid ) AS rowNo ,
					0 AS ischeck ,
					i.billnumberid ,
					CONVERT(VARCHAR(10), i.BillDate, 120) AS BillDate ,
					i.checktime ,
					i.BillCode ,
					i.billstate ,
					bs.execstate ,
					CASE WHEN i.BillState = 2
							  AND bs.execstate = 6 THEN ''已引用未完成''
						 WHEN i.BillState = 2
							  AND bs.execstate = 7 THEN ''已完成''
						 WHEN i.BillState = 0 THEN ''原始单据''
						 WHEN i.BillState = 2 THEN ''接受''
						 WHEN i.BillState = 3 THEN ''拒绝''
						 WHEN i.BillState = 4 THEN ''作废''
						 ELSE ''原始单据''
					END AS billstatestr ,
					i.inktypeid ,
					kin.fullname AS kfullnamein ,
					i.applyetypeid ,
					e.fullname AS applyefullname ,
					i.ktypeid ,
					k.fullname AS kfullname ,
					i.stypeid ,
					s.usercode AS susercode ,
					s.fullname AS sfullname ,
					i.checke AS etypeid ,
					e1.fullname AS efullname ,
					i.dtypeid ,
					d.fullname AS dfullname ,
					i.comment ,
					i.explain ,
					checker.fullname checkerfullname ,
					i.checkerTime ,
					updater.fullname updaterfullname ,
					i.updaterTime ,
					i.Qty qty ,		--要货数量（基本
					i.Qty
					- ( SELECT  ISNULL(SUM(a.qty), 0)
						FROM    DeliveryBill a
								INNER JOIN DeliveryApplyBill b ON a.DeliveryApplyBillId = b.ID
								INNER JOIN PosAllotApplyBillIndex c ON a.billnumberid = c.billnumberid
						WHERE   b.BillNumberId = i.billnumberid
								AND c.ifcheck = ''t''
								AND redword = 0
					  ) unfinishedqty ,  --未完成数量（基本
					CASE WHEN ISNULL(i.KtypeId, '''') = ''''
							  OR i.KtypeId IN ( SELECT  TypeId
												FROM    #KType2 )
						 THEN ISNULL(i.KtypeId, '''')
						 ELSE ''****''
					END AS v_outKtypeId ,
					CASE WHEN i.InKtypeId IN ( SELECT  TypeId
											   FROM    #KType1 )
						 THEN i.InKtypeId
						 ELSE ''****''
					END AS v_InKtypeId
			FROM    PosAllotApplyBillIndex i
					INNER JOIN #billexecstate bs ON i.billnumberid = bs.billnumberid
					LEFT JOIN #KType2 k ON i.ktypeid = k.typeid
					INNER JOIN #KType1 kin ON i.inktypeid = kin.typeid
					INNER JOIN #EType e ON i.applyetypeid = e.typeid
					LEFT JOIN Employee e1 ON i.checke = e1.typeid
					LEFT JOIN Employee checker ON i.checker = checker.typeid
					LEFT JOIN Employee updater ON i.updater = updater.typeid
					INNER JOIN #stype s ON i.stypeid = s.typeid
					INNER JOIN #Dtype d ON i.dtypeid = d.typeid
			WHERE   i.billType = ' + @billtype		
    IF @billdatestart IS NOT NULL
        AND @billdateend IS NOT NULL 
        BEGIN	
            SET @SQL += N' AND i.billdate BETWEEN '''
                + CAST(@billdatestart AS VARCHAR) + ''' AND '''
                + CAST(@billdateend AS VARCHAR) + ''' '
        END
    IF ISNULL(@ktypeid, '') <> '' 
        BEGIN
            SET @SQL += N' AND i.ktypeid IN (select typeid from #ktype2) '
        END
    IF ISNULL(@ktypeidin, '') <> '' 
        BEGIN
            SET @SQL += N' AND i.inktypeid IN (select typeid from #KType1)'
        END
    IF ISNULL(@ptypeidstr, '') <> '' 
        BEGIN
            SET @SQL += N' AND EXISTS (SELECT TOP 1 1 FROM DeliveryApplyBill WHERE PtypeId LIKE ''' + @ptypeidstr + '%'') '
        END
	
	-- 状态条件	
    IF ISNULL(@billstate, '') <> ''
        AND ISNULL(@billexec, '') = '' 
        BEGIN
            SET @SQL += ' AND i.billstate in (SELECT * FROM dbo.f_split(''' + @billstate + ''','','')) '
        END
    ELSE 
        IF ISNULL(@billstate, '') = '' AND ISNULL(@billexec, '') <> '' 
            BEGIN
                SET @SQL += ' AND bs.execstate in (SELECT * FROM dbo.f_split(''' + @billexec + ''','','')) '
            END
        ELSE 
            IF ISNULL(@billexec, '') IN ( '6,7', '6', '7' ) AND ISNULL(@billstate, '') <> '' 
                BEGIN
                    SET @SQL += ' AND ( i.billstate in (SELECT * FROM dbo.f_split(''' + @billstate + ''','','')) 
								  OR  (bs.execstate in (SELECT * FROM dbo.f_split(''' + @billexec + ''','','')) ) )'
                END

    IF CHARINDEX('2', @billstate) = 0 AND CHARINDEX('6', @billexec) > 0 
        BEGIN
            SET @SQL += ' AND (i.billstate <> 2 OR bs.execstate = 6 OR bs.execstate = 7) ' --不查询接受状态
        END
    IF CHARINDEX('6', @billexec) = 0 AND CHARINDEX('2', @billstate) > 0 
        BEGIN
            SET @SQL += ' AND bs.execstate <> 6 ' --不查询已引用未完成状态
        END
    IF CHARINDEX('7', @billexec) = 0 AND CHARINDEX('2', @billstate) > 0 
        BEGIN
            SET @SQL += ' AND bs.execstate <> 7 ' --不查询已完成状态
        END
    IF CHARINDEX('4', @billstate) = 0 AND CHARINDEX('6', @billexec) > 0 
        BEGIN
            SET @SQL += ' AND i.billstate <> 4 ' --不查询作废状态
        END
    IF CHARINDEX('6', @billexec) = 0 AND CHARINDEX('4', @billstate) > 0 
        BEGIN
            SET @SQL += ' AND (bs.execstate <> 6 OR i.billstate = 4) ' --不查询已引用未完成状态
        END
	
    SET @SQL += 'AND ( i.ktypeid IN (SELECT typeid FROM #Ktype2) OR ISNULL(i.ktypeid,'''') = ''''  ) '
	
    SET @SQL += N' ORDER BY i.billdate desc '

	
	PRINT(@SQL)
    EXEC(@SQL)

    DROP TABLE #Ktype1,#Ktype2,#stype,#billexecstate,#dtype,#etype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Qp_QueryPicking]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Qp_QueryPicking]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：郑红霞
	日期：2011-4-25
	描述：查看领料详情
-------------------------------------------*/
CREATE PROCEDURE [dbo].[Web_Qp_QueryPicking]
(
    @OperatorID    VARCHAR(50),       
	@Ktypeid       VARCHAR(1550)='',         --仓库
    @stypeid       VARCHAR(1550)='00001',    --分支机构
    @BillCode  VARCHAR(max)              --维修单号
)
--@encode$--
AS

  SET NOCOUNT ON
BEGIN 
declare @Ptypeid  VARCHAR(1550)=''
set @Ptypeid = (select ptypeid from BillIndex where BillCode=@BillCode) 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype (TypeID VARCHAR(200))
CREATE TABLE #Ktype (TypeID VARCHAR(50))
CREATE TABLE #Stype (TypeID VARCHAR(50))

--配件
INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Ptypeid,1,@OperatorID)

--仓库
INSERT INTO #Ktype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Ktypeid,4,@OperatorID)	


--分支机构
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)


DECLARE @SQL VARCHAR(3000)
SET @SQL ='SELECT	R.*,
        F.ETypeID,
        b.BillCode,
        b.BillDate,
        p.UserCode,
        p.FullName pname,
        p.DwgNo,
        s.FullName stockname,
        e.FullName username
        FROM Qp_ReceptionBill_FactUsePType F
        INNER JOIN Qp_ReceptionBill_PType R ON R.ID = F.ReceptionBillPTypeId
        inner join BillIndex b on b.BillNumberId=R.BillNumberId
        inner join ptype p on p.typeId=R.PTypeID
        inner join employee e on e.typeId = F.ETypeID 
        inner join stock s on s.typeId=b.Stypeid
		left join #stype m on m.typeid = b.stypeid
		left join  #ktype k on k.typeid = b.ktypeid
		left join  #ptype ps on ps.typeid = b.ptypeid where b.BillCode='''+@BillCode+'''
	    order by  b.BillDate,p.UserCode asc'  
	  EXEC (@sql)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



GO
/*
*    库存排行查询
*    @PTypeID=''				表示Top5+其他类别
*    @PTypeID='00001'			表示00001类别下明细
*    @PTypeID='00000'			表示其他类别(其他类别PTypeID为00000)
*	 @PageIndex=1				第一页明细数据(查明细时生效)  第一页从1开始
*    @PageSize=5				每页5行明细(查明细时生效)
*	 
*	 SELECT PTypeID,KTypeID,STypeID,FullName,Total
*/
IF EXISTS(SELECT 1 FROM SysObjects WHERE ID=OBJECT_ID(N'Web_Query_Goods_Stock_Rank',N'P'))
BEGIN
	DROP PROC Web_Query_Goods_Stock_Rank
END
GO

CREATE PROC Web_Query_Goods_Stock_Rank
(
	@PTypeID    VARCHAR(100)='',			--商品ID,'' 表示大类,'00000'表示其他,否则表示某一类
	@STypeID    VARCHAR(100)='',			--分支机构ID
	@KTypeID    VARCHAR(100)='',			--仓库ID
	@PTypeName  VARCHAR(500)='',            --商品名称
	@OperatorID VARCHAR(100)='',			--经手人ID 
	@PageIndex	INT=1,						--默认第一页
	@PageSize	INT=5						--默认每页5行
)
AS
BEGIN
	SELECT @OperatorId = typeId FROM dbo.employee WHERE UserCode = @OperatorId or fullname=@OperatorId
	--分支机构
	CREATE TABLE #STypeId(TypeId	VARCHAR(100))
	INSERT INTO #STypeId(TypeId) SELECT TypeID FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

	--商品
	CREATE TABLE #PTypeId(TypeId	VARCHAR(100))
	INSERT INTO #PTypeId(TypeId) SELECT TypeID FROM F_GetAllManagerBaseTypeId('',1,@OperatorID)

	--仓库
	CREATE TABLE #KTypeId(TypeId	VARCHAR(100))
	INSERT INTO  #KTypeId(typeid) SELECT TypeID FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)

	--分类结果
	CREATE TABLE #QueryResult
	(
		PTypeID VARCHAR(100),
		KTypeID VARCHAR(100),
		STypeID VARCHAR(100),
		Total	NUMERIC(24,10),
		FullName VARCHAR(100)
	)
	
	;WITH QueryCTE
	AS
	(
		SELECT  
				LEFT(A.PTypeID, 5) AS PTypeID ,
				@KTypeID  AS KTypeID,
				@STypeID  AS STypeID,
				SUM(ISNULL(A.Total,0)) AS Total
		FROM    dbo.GoodsStocks A
				INNER JOIN dbo.Ptype B ON A.PtypeId = B.TypeID
				INNER JOIN #KTypeId C ON A.KtypeId = C.TypeId
				INNER JOIN #PTypeId D ON A.PTypeID = D.TypeId
				INNER JOIN Stock E ON C.TypeID = E.typeId
				INNER JOIN #STypeId F ON E.STypeID = F.TypeId
		WHERE   LEN(A.PtypeId) > 5
				GROUP BY  LEFT(A.PTypeID,5)
	)
	INSERT INTO #QueryResult
	        ( PTypeID ,
	          KTypeID ,
	          STypeID ,
	          Total 
	        )
	SELECT	  PTypeID ,
			  KTypeID ,
			  STypeID ,
			  Total 
    FROM QueryCTE ORDER BY Total DESC
	UPDATE A SET A.FullName=B.FullName FROM #QueryResult A,PType B WHERE A.PTypeID=B.typeId AND A.FullName IS NULL
	
	--TOP 5 分类+其他
	IF @PTypeID=''
	BEGIN
	
	   --模糊查询明细
	   IF @PTypeName <> '' AND @PTypeName != '' AND len(@PTypeName) >0
	   BEGIN
	      			;WITH QueryCTE
					AS
					(
					  SELECT    A.PTypeID ,
								@KTypeID  AS KTypeID,
								@STypeID AS STypeID,
								SUM(ISNULL(A.Total,0)) AS Total,
								SUM(ISNULL(A.Qty,0)) AS Qty,
								(SELECT fullname FROM PType_Units WHERE UnitsId= B.baseUnitId) AS UnitName
					  FROM      dbo.GoodsStocks A
								INNER JOIN dbo.Ptype B ON A.PtypeId = B.TypeID
								INNER JOIN #KTypeId C ON A.KtypeId = C.TypeId
								INNER JOIN #PTypeId D ON A.PTypeID = D.TypeId
								INNER JOIN Stock E ON C.TypeID = E.typeId
								INNER JOIN #STypeId F ON E.STypeID = F.TypeId
								GROUP BY  A.PTypeID,B.baseUnitId
					)	

					SELECT PTypeID,KTypeID,STypeID,Total,FullName,Qty,UnitName FROM (
						SELECT  A.PTypeID ,
								A.KTypeiD ,
								A.STypeID ,
								A.Total ,
								B.FullName,
								B.UserCode,
								A.Qty,
								A.UnitName,
								ROW_NUMBER() OVER(ORDER BY A.Total DESC) AS RowIndex
						FROM    QueryCTE A
								INNER JOIN PType B ON A.PTypeID = B.TypeID
					) V
					WHERE FullName LIKE  '%'+@PTypeName+'%' OR UserCode LIKE  '%'+@PTypeName+'%'
	   END
	   --模糊查询明细
	   ELSE
	   BEGIN
			IF EXISTS(SELECT 1 FROM #QueryResult)
			BEGIN
				--其他类金额=总金额-TOP5分类金额
				;WITH OtherTotalCTE
				AS
				(
						SELECT  SUM(ISNULL(A.Total, 0)) - ( SELECT  SUM(ISNULL(Total, 0))
															FROM    ( SELECT TOP 5
																		  Total
																	  FROM
																		  #QueryResult
																	  ORDER BY Total DESC
																	) V
														  ) AS Total
						FROM    dbo.GoodsStocks A
								INNER JOIN dbo.Ptype B ON A.PtypeId = B.TypeID
								INNER JOIN #KTypeId C ON A.KtypeId = C.TypeId
								INNER JOIN #PTypeId D ON A.PTypeID = D.TypeId
								INNER JOIN Stock E ON C.TypeID = E.typeId
								INNER JOIN #STypeId F ON E.STypeID = F.TypeId
		            
		            
				)
				
				SELECT TOP 5 PTypeID,KTypeID,STypeID,FullName,Total FROM #QueryResult
				UNION ALL
				SELECT '00000',@KTypeID,@STypeID,'其他',Total FROM OtherTotalCTE
			END
			ELSE
			BEGIN
			   ;WITH OnlyOtherTotalCTE
				AS
				(
						SELECT  SUM(ISNULL(A.Total, 0)) AS Total
						FROM    dbo.GoodsStocks A
								INNER JOIN dbo.Ptype B ON A.PtypeId = B.TypeID
								INNER JOIN #KTypeId C ON A.KtypeId = C.TypeId
								INNER JOIN #PTypeId D ON A.PTypeID = D.TypeId
								INNER JOIN Stock E ON C.TypeID = E.typeId
								INNER JOIN #STypeId F ON E.STypeID = F.TypeId
				)
				SELECT '00000' as PTypeID,@KTypeID as KTypeID,@STypeID as STypeID,'其他' as FullName,Total as Total FROM OnlyOtherTotalCTE
			END
	  END
		
	END
	--其他类别明细
	ELSE IF @PTypeID='00000'
	BEGIN
		;WITH QueryCTE
		AS
		(
		  SELECT    A.PTypeID ,
					@KTypeID  AS KTypeID,
					@STypeID AS STypeID,
					SUM(ISNULL(A.Total,0)) AS Total,
					SUM(ISNULL(A.Qty,0)) AS Qty,
					(SELECT fullname FROM PType_Units WHERE UnitsId= B.baseUnitId) AS UnitName
		  FROM      dbo.GoodsStocks A
					INNER JOIN dbo.Ptype B ON A.PtypeId = B.TypeID
					INNER JOIN #KTypeId C ON A.KtypeId = C.TypeId
					INNER JOIN #PTypeId D ON A.PTypeID = D.TypeId
					INNER JOIN Stock E ON C.TypeID = E.typeId
					INNER JOIN #STypeId F ON E.STypeID = F.TypeId
		  WHERE     LEFT(A.PTypeID,5) NOT IN(SELECT TOP 5 PTypeID FROM #QueryResult ORDER BY Total DESC)
					GROUP BY  A.PTypeID,B.baseUnitId
		)

		SELECT PTypeID,KTypeID,STypeID,Total,FullName,Qty,UnitName FROM (
			SELECT  A.PTypeID ,
					A.KTypeiD ,
					A.STypeID ,
					A.Total ,
					B.FullName,
					A.Qty,
					A.UnitName,
					ROW_NUMBER() OVER(ORDER BY A.Total DESC) AS RowIndex
			FROM    QueryCTE A
					INNER JOIN PType B ON A.PTypeID = B.TypeID
        ) V
       WHERE   RowIndex BETWEEN (@PageIndex-1) * @PageSize + 1 AND @PageSize * @PageIndex
	END
	--某一类明细
	ELSE 
	BEGIN
		;WITH QueryCTE
		AS
		(
		  SELECT    A.PTypeID ,
					@KTypeID  AS KTypeID,
					@STypeID AS STypeID,
					SUM(ISNULL(A.Total,0)) AS Total,
					SUM(ISNULL(A.Qty,0)) AS Qty,
					(SELECT fullname FROM PType_Units WHERE UnitsId= B.baseUnitId) AS UnitName
		  FROM      dbo.GoodsStocks A
					INNER JOIN dbo.Ptype B ON A.PtypeId = B.TypeID
					INNER JOIN #KTypeId C ON A.KtypeId = C.TypeId
					INNER JOIN #PTypeId D ON A.PTypeID = D.TypeId
					INNER JOIN Stock E ON C.TypeID = E.typeId
					INNER JOIN #STypeId F ON E.STypeID = F.TypeId
		  WHERE     LEFT(A.PTypeID,5) = @PTypeID
					GROUP BY  A.PTypeID,B.baseUnitId
		)	

		SELECT PTypeID,KTypeID,STypeID,Total,FullName,Qty,UnitName FROM (
			SELECT  A.PTypeID ,
					A.KTypeiD ,
					A.STypeID ,
					A.Total ,
					B.FullName,
					A.Qty,
					A.UnitName,
					ROW_NUMBER() OVER(ORDER BY A.Total DESC) AS RowIndex
			FROM    QueryCTE A
					INNER JOIN PType B ON A.PTypeID = B.TypeID
        ) V
       WHERE   RowIndex BETWEEN (@PageIndex-1) * @PageSize + 1 AND @PageSize * @PageIndex
	END
	DROP TABLE #KTypeId,#PTypeId,#STypeId,#QueryResult
END
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_Query_Invalid_VoucherBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_Query_Invalid_VoucherBill
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	得到所有作废凭证
-- 时间：	2013-06-26
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_Query_Invalid_VoucherBill
(
	@StypeID		VARCHAR(50),			--分支机构ID
	@OperatorId		VARCHAR(50)				--操作员
)
--@encode$--
AS
SET NOCOUNT ON

--仅能查看本人制单的会计凭证
DECLARE  @LimitOwnVoucher INT=0
IF(@OperatorId<>'00001')
	SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@operatorid

SELECT 
	bill.BillNumberId,
	bill.BillNumberId nid,
	vc.BillDate,
	CONVERT(VARCHAR(4),vc.FYear)+'年第'+ CONVERT(VARCHAR(2),vc.FPeriod) +'期' FPeriodDate,
	vc.FSerialNum,
	gr.FullName+'-'+CONVERT(VARCHAR(10),vc.FlowNo) FullName,
	vc.FlowNo,
	dbo.F_GetSummaryByLimit(bill.ID,@OperatorId,bill.STypeID,bill.Summary) Summary,
	CASE WHEN ISNULL(FA.TypeId,'')='' THEN '****' ELSE at.UserCode END TypeCode,
	CASE WHEN ISNULL(FA.TypeId,'')='' THEN '****' ELSE at.FullName END TypeName,
	cc.fullname currencyName,
	CASE WHEN bill.FAdc=1 THEN bill.FdebitTotalFor ELSE bill.FcreditTotalFor END FAmountFor,
	bill.FDebitTotal,
	bill.FCreditTotal,
	vc.ETypeId,
	abt.fullname fsettletype,
	bill.FSettleNo,
	vc.AttachFileCount,
	bill.Comment,
	vc.FChecked,
	vc.Audited,
	vc.IfCheck,
	bill.Fdc,
	210 AS BillType,
	vc.markerror,
	'作废' billState,
	vc.VoucherType,
	bill.ID,
	VT.FullName vouchertypeName
FROM Ac_Voucher_Bill bill
INNER JOIN Ac_Voucher vc  ON VC.BillNumberId=bill.BillNumberId
INNER JOIN F_GetAllManagerBaseTypeId(@StypeID,11,@OperatorId) F ON F.TypeId=vc.STypeId 
INNER JOIN Ac_Voucher_Group gr on gr.VgId=vc.VgId 
INNER JOIN Ac_Currency cc ON cc.cid=bill.cid
LEFT JOIN Ac_Account at ON at.TypeId=bill.ATypeId AND at.STypeId=bill.STypeId
LEFT JOIN F_LineAccount(@OperatorID,@StypeID) FA ON FA.TypeId=bill.ATypeId AND FA.StypeId=bill.STypeId
INNER JOIN Ac_VoucherType VT ON VT.Id=vc.VoucherType
LEFT JOIN Ac_BalanceType abt on abt.BtId=bill.fsettletypeid
WHERE 
	FChecked=-1
	AND ((@LimitOwnVoucher=1 AND vc.ETypeId=@OperatorId ) OR (@LimitOwnVoucher=0))
ORDER BY vc.FPeriod,vc.FlowNo,vc.BillNumberId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Query_ServerInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Query_ServerInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	EXEC Web_Query_ServerInfo '0','120.26.200.120','A8'
*/
CREATE PROCEDURE Web_Query_ServerInfo
(
	@Flag			VARCHAR(10),	--标识
	@Value			VARCHAR(2000),	--数值
	@ProductName	VARCHAR(10)		--版本
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL  VARCHAR(MAX)
DECLARE @nSQL NVARCHAR(4000),
		@wDefineV VARCHAR(MAX)

IF @Flag = '0'
BEGIN
	IF @Value = ''
	BEGIN
		SET @SQL = 'DECLARE @wsd VARCHAR(1000)
					SELECT @wsd = SubValue FROM sysdata WHERE SubName = ''wsd''
					SELECT ''http://''+@wsd+''/GraspWebServer/GWS.asmx'''
		--PRINT(@SQL)			
		EXEC(@SQL)				
	END
	ELSE
	BEGIN
		SET @nSQL = 'SELECT @wDefine = SubValue FROM sysdata WHERE SubName = ''wsd'''
		EXEC sp_executesql @nSQL, N'@wDefine varchar(max) out', @wDefineV OUT
		
		IF @wDefineV <> @Value
		BEGIN
			SELECT 'http://'+@Value+'/GraspWebServer/GWS.asmx'
		END
		ELSE
		BEGIN
			SET @SQL = 'DECLARE @wsd VARCHAR(1000)
						SELECT @wsd = SubValue FROM sysdata WHERE SubName = ''wsd''
						SELECT ''http://''+@wsd+''/GraspWebServer/GWS.asmx'''
			--PRINT(@SQL)			
			EXEC(@SQL)				
		END
	END
	--调整数据
	--SET @SQL = 'EXEC Gp_UpdateSysdataWsd '''+@Value+''''	
	--EXEC(@SQL)
END
ELSE
BEGIN
	IF @ProductName = 'V3'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM sysdata1 WHERE SubName = 'IsTopDog' AND SubValue = '0')
			UPDATE Userconfig SET Value = @Value WHERE ConfigName = 'EV31'
		ELSE
			UPDATE Userconfig SET Value = @Value WHERE ConfigName = 'EV32'
	END
	IF @ProductName = 'V1'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM sysdata1 WHERE SubName = 'IsTopDog' AND SubValue = '0')
			UPDATE Userconfig SET Value = @Value WHERE ConfigName = 'EV31'
		ELSE
			UPDATE Userconfig SET Value = @Value WHERE ConfigName = 'EV32'
	END
	ELSE IF @ProductName = 'A8'
	BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM sysdata1 WHERE SubName = 'IsTopDog' AND SubValue = '0')
			UPDATE Userconfig SET Value = @Value WHERE ConfigName = 'EA81'
		ELSE
			UPDATE Userconfig SET Value = @Value WHERE ConfigName = 'EA82'
	END
	
	SELECT 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_Query_ServerInfoV2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_Query_ServerInfoV2]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	EXEC Web_Query_ServerInfo '0','120.26.200.120','A8'
*/
CREATE PROCEDURE Web_Query_ServerInfoV2
(
	@Flag			VARCHAR(10),	--标识
	@Value			VARCHAR(2000),	--数值
	@ProductName	VARCHAR(10)		--版本
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL  VARCHAR(MAX)
DECLARE @nSQL NVARCHAR(4000),
		@wDefineV VARCHAR(MAX)

IF @Flag = '0'
BEGIN
	IF @Value = ''
	BEGIN
		SET @SQL = 'DECLARE @wsd VARCHAR(1000)
					SELECT @wsd = SubValue FROM sysdata WHERE SubName = ''wsd''
					SELECT ''http://''+@wsd+''/Api/GWSApi'' '
		--PRINT(@SQL)			
		EXEC(@SQL)				
	END
	ELSE
	BEGIN
		SET @nSQL = 'SELECT @wDefine = SubValue FROM sysdata WHERE SubName = ''wsd'''
		EXEC sp_executesql @nSQL, N'@wDefine varchar(max) out', @wDefineV OUT
		
		IF @wDefineV <> @Value
		BEGIN
			SELECT 'http://'+@Value+'/Api/GWSApi'
		END
		ELSE
		BEGIN
			SET @SQL = 'DECLARE @wsd VARCHAR(1000)
						SELECT @wsd = SubValue FROM sysdata WHERE SubName = ''wsd''
						SELECT ''http://''+@wsd+''/Api/GWSApi'''
			--PRINT(@SQL)			
			EXEC(@SQL)				
		END
	END
	--调整数据
	--SET @SQL = 'EXEC Gp_UpdateSysdataWsd '''+@Value+''''	
	--EXEC(@SQL)
END
ELSE
BEGIN
	UPDATE Userconfig SET Value = @Value WHERE ConfigName = 'EADDR'
	
	SELECT 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryABSENCECX]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryABSENCECX
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-11-4
	描述：缺勤处理查询
*/
CREATE PROCEDURE Web_QueryABSENCECX
(
    @OperatorID 	VARCHAR(100),  	    		--操作员ID号
	@StartDate   	VARCHAR(10),                --起始日期
	@EndDate    	VARCHAR(10),                --截至日期
	@stypeid		VARCHAR(50),
	@etypeid		VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)
	
SELECT	e.typeid,
		A.date,
		--CASE LeaveReasonID WHEN 0 THEN null ELSE 1 END AS leavetime,
		CONVERT(VARCHAR(8),RegistStartTime) as starttime,
		CONVERT(VARCHAR(8),RegistEndTime) as endtime,
		E.STypeID,
		CASE LeaveReasonID WHEN 0 THEN null ELSE A.Comment END AS leavereason,
		CASE LeaveReasonID WHEN 0 THEN null ELSE R.Fullname END AS reasontype,
		M.RegistReason
FROM AttendanceTime A 
LEFT JOIN ManualRegist M ON a.id=M.AttendanceTimeId
INNER JOIN employee E ON E.typeId=a.etypeid
INNER JOIN #GetManSTypeId S ON S.TypeId=E.STypeID
INNER JOIN #GetManETypeId E1 ON E.typeId=E1.TypeId
LEFT JOIN LeaveReason R ON A.LeaveReasonID=R.Id
WHERE	A.date>=@StartDate
		AND A.date<=@EndDate
		AND (A.LeaveReasonID<>0 OR A.Id IN (SELECT AttendanceTimeId FROM ManualRegist))
ORDER BY A.etypeid,A.date
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[web_queryac_account]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[web_queryac_account]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE          PROC [dbo].[web_queryac_account]
(
 @stypeid VARCHAR(500),
 @typeid VARCHAR(500),
 @chvOperatorID VARCHAR(50),
 @showstop		VARCHAR(5)  --0.不显示停用 1.显示停用
)
--@encode$--
AS 
SET NOCOUNT ON 

IF @showstop='1'
	SET @showstop='%'			

	--获取当前分支机构是否为父节点
    --如果为父节点，返回，不获取数据
IF EXISTS ( SELECT TOP 1
                    1
            FROM    SType
            WHERE   parid LIKE @stypeid + '%' ) 
    BEGIN
        SELECT  *
        FROM    dbo.Ac_Account
        WHERE   1 > 1 
        RETURN 
    END	
	
DECLARE @syscid INT
SELECT TOP 1
        @syscid = cid
FROM    Ac_Currency
WHERE   Sysrow = 1
		
		


CREATE TABLE #stype (typeid VARCHAR(50))
INSERT INTO #stype(typeid)
SELECT DISTINCT VerifyID FROM SType WHERE TypeId IN (SELECT *FROM F_GetAllManagerBaseTypeId(@StypeId,11,@chvOperatorID))


BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50))
	INSERT INTO #Ac_Account_L (Typeid,StypeId) 
	SELECT L.Typeid,L.Stypeid--,A.FullName 
	FROM F_TreeAccount(@chvOperatorID,'') L
	INNER JOIN #stype S ON S.typeid=L.Stypeid
	--INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
END;		
		
SELECT  A.*, F.UserCode AS FUserCode,
        CASE LEFT(A.TypeId, 5)
          WHEN '00001' THEN '资产'
          WHEN '00002' THEN '负债'
          WHEN '00003' THEN '损益'
          WHEN '00004' THEN '成本'
          WHEN '00005' THEN '权益'
          WHEN '00006' THEN '共同'
          ELSE '其他'
        END AS GroupName, 
        CASE A.Fdc
          WHEN 1 THEN '借'
          ELSE '贷'
        END AS fdcName, 
        CASE A.IsCash
          WHEN 1 THEN '√'
          ELSE ''
        END AS cashname,
        CASE A.IsBank
          WHEN 1 THEN '√'
          ELSE ''
        END AS bankname, 
        CASE A.IsOther
          WHEN 1 THEN '√'
          ELSE ''
        END AS othername,
        CASE A.cid
          WHEN 0 THEN '所有币种'
          WHEN @syscid THEN '不核算'
          ELSE c.FullName
        END AS cidname, 
        CASE 
          WHEN t.checkitemcount > 0 THEN '√'
          ELSE ''
        END AS ascidname,
        A.FContact,
        CASE A.FContact
          WHEN 1 THEN '√'
          ELSE ''
        END AS fcontactname,
		A.AcId,
		A.AdjustAccounts,
		CASE A.AdjustAccounts
			  WHEN 1 THEN '√'
			  ELSE ''
			END AS AdjustAccountsname
FROM    Ac_Account A
INNER JOIN #Ac_Account_L L ON A.TypeId=L.TypeId AND L.StypeId=A.StypeId
INNER JOIN DBO.F_GetStandard_Ac_Account(@chvOperatorID) F ON F.TypeId = A.TypeId
                                            AND F.StypeId = A.StypeId
LEFT JOIN Ac_Currency c ON c.cid = A.Cid
LEFT JOIN (SELECT   stypeid, ATypeId,
                    COUNT(1) AS checkitemcount
           FROM     Ac_Account_Assist_CheckItems
           GROUP BY STypeId, atypeid) t ON t.stypeid = a.StypeId
                                           AND t.ATypeId = A.TypeId
WHERE   A.TypeId LIKE @typeid + '%'
        AND A.StypeId = @stypeid
        AND A.TypeId > '00000'
        AND A.UserCode > '' ---用 UserCode > '' 代替 usercode <> ''
        AND A.Deleted LIKE @showstop
ORDER BY A.UserCode
    
    
    
    
GO






IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAC_AccountMultiLevel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_QueryAC_AccountMultiLevel]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：杨俊
	日期：2014-11-19
	描述：会计科目多级权限-科目查询
*/ 
CREATE PROCEDURE dbo.Web_QueryAC_AccountMultiLevel
(
	@stypeid VARCHAR(500),			--分支机构
	@typeid VARCHAR(500),			--科目类别
	@etypeid VARCHAR(500),			--职员 
	@chvOperatorID VARCHAR(500),		--操作员
	@type INT						--0为添加,1为查看
)
--@encode$--
AS 
---------------------------------------------------------------------------------------------------------------------------
--币种
DECLARE @syscid INT
SELECT TOP 1
		@syscid = cid
FROM    Ac_Currency
WHERE   Sysrow = 1

--是否拥有所有权限
--拥有全部权限时，不再只存储一条记录，要分别存储各大类的数据。9.5BUG 1255 确认。
DECLARE @FLAG INT,@OperatorAllqx INT
IF((SELECT COUNT(1) FROM Ac_Account_L WHERE stypeid = @stypeid AND etypeid = @etypeid AND typeid = '00000') = 1 
		OR (SELECT COUNT(1) FROM Ac_Account_L WHERE stypeid = '00000' AND etypeid = @etypeid AND typeid = '00000') = 1 
		OR (SELECT COUNT(1) FROM Ac_Account_L WHERE stypeid = @stypeid AND etypeid = @etypeid AND typeid = @typeid) = 1)
	SET @FLAG = 1
ELSE
	SET @FLAG = 0
--SET @FLAG = (SELECT COUNT(1) FROM Ac_Account_L WHERE stypeid = @stypeid AND etypeid = @etypeid AND typeid = @typeid)
IF(@chvOperatorID = '00001')
	SET @OperatorAllqx = 1
ELSE IF((SELECT COUNT(1) FROM Ac_Account_L WHERE stypeid = @stypeid AND etypeid = @chvOperatorID AND typeid = '00000') = 1 
		OR (SELECT COUNT(1) FROM Ac_Account_L WHERE stypeid = '00000' AND etypeid = @chvOperatorID AND typeid = '00000') = 1
		OR (SELECT COUNT(1) FROM Ac_Account_L WHERE stypeid = @stypeid AND etypeid = @chvOperatorID AND typeid = @typeid) = 1)
	--SET @OperatorAllqx = (SELECT COUNT(1) FROM Ac_Account_L WHERE stypeid = @stypeid AND etypeid = @chvOperatorID AND typeid = @typeid)
	SET @OperatorAllqx = 1
ELSE
	SET @OperatorAllqx = 0

--添加
IF(@type = 0)
BEGIN
	----------------------------------------------------------临时表-----------------------------------------------------------
	--已有权限科目
	CREATE TABLE #PresenceAccount
	(
		STypeId VARCHAR(500),  
		TypeId VARCHAR(500),
		UserCode VARCHAR(500),
		SonCount INT,
		flag INT,
		parflag INT
	)
	---------------------------------------------------------------------------------------------------------------------------
	IF(@chvOperatorID <> '00001')
	BEGIN
		--记录当前职员有权限显示的节点
		IF(@OperatorAllqx = 1)   --当前操作员是否有所有权限
		BEGIN
			INSERT INTO #PresenceAccount(STypeId,TypeId,UserCode,SonCount,flag,parflag)
			SELECT A.STypeId,A.TypeId,A.UserCode,C.SonCount,
			(SELECT flag FROM Ac_Account_L WHERE stypeid = A.STypeId AND TypeId = A.TypeId AND ETypeId = @etypeid) AS flag,
			(SELECT flag FROM Ac_Account_L WHERE stypeid = A.STypeId AND TypeId = A.TypeId AND ETypeId = @chvOperatorID) AS parflag  
			FROM F_GetStandard_Ac_Account(@chvOperatorID) AS A
			INNER JOIN Ac_Account AS C ON(A.STypeId = C.StypeId AND A.TypeId = C.TypeId)
			WHERE A.STypeId = @stypeid AND A.TypeId LIKE @typeid + '%'
		END
		ELSE
		BEGIN
			--如果不是记录的当前大类，如“00001”则使用A.TypeId LIKE B.typeid + '%'
			IF((SELECT COUNT(1) FROM Ac_Account_L WHERE etypeid = @chvOperatorID AND STypeId = @stypeid AND typeid = @typeid) = 0)
			BEGIN		 
				--INSERT INTO #PresenceAccount(STypeId,TypeId,UserCode,SonCount,flag,parflag)
				--SELECT DISTINCT A.STypeId,A.TypeId,A.UserCode,C.SonCount,B.flag,
				--(SELECT flag FROM Ac_Account_L WHERE stypeid = A.STypeId AND TypeId = A.TypeId AND ETypeId = @chvOperatorID) AS parflag 
				--FROM F_GetStandard_Ac_Account(@chvOperatorID) AS A
				--INNER JOIN Ac_Account_L AS B ON(A.STypeId = B.stypeid AND B.typeid LIKE A.TypeId + '%' AND B.etypeid = @chvOperatorID AND B.flag = 1)
				--INNER JOIN Ac_Account AS C ON(A.STypeId = C.StypeId AND A.TypeId = C.TypeId)
				--WHERE A.STypeId = @stypeid AND A.TypeId LIKE @typeid + '%'
						 
				INSERT INTO #PresenceAccount(STypeId,TypeId,UserCode,SonCount,flag,parflag)
				SELECT A.STypeId,A.TypeId,A.UserCode,C.SonCount,
				(SELECT flag FROM Ac_Account_L WHERE stypeid = A.STypeId AND TypeId = A.TypeId AND ETypeId = @etypeid) AS flag,
				(SELECT flag FROM Ac_Account_L WHERE stypeid = A.STypeId AND TypeId = A.TypeId AND ETypeId = @chvOperatorID) AS parflag  
				FROM F_GetStandard_Ac_Account(@chvOperatorID) AS A
				INNER JOIN Ac_Account_L AS B ON(A.STypeId = B.stypeid AND A.TypeId = B.typeid AND B.etypeid = @chvOperatorID)
				INNER JOIN Ac_Account AS C ON(A.STypeId = C.StypeId AND A.TypeId = C.TypeId)
				WHERE A.STypeId = @stypeid AND A.TypeId LIKE @typeid + '%'
			END
			ELSE
			BEGIN
				INSERT INTO #PresenceAccount(STypeId,TypeId,UserCode,SonCount,flag,parflag)
				SELECT A.STypeId,A.TypeId,A.UserCode,C.SonCount,
				(SELECT flag FROM Ac_Account_L WHERE stypeid = A.STypeId AND TypeId = A.TypeId AND ETypeId = @etypeid) AS flag,
				(SELECT flag FROM Ac_Account_L WHERE stypeid = A.STypeId AND TypeId = A.TypeId AND ETypeId = @chvOperatorID) AS parflag  
				FROM F_GetStandard_Ac_Account(@chvOperatorID) AS A
				INNER JOIN Ac_Account_L AS B ON(A.STypeId = B.stypeid AND A.TypeId LIKE B.typeid + '%' AND B.etypeid = @chvOperatorID)
				INNER JOIN Ac_Account AS C ON(A.STypeId = C.StypeId AND A.TypeId = C.TypeId)
				WHERE A.STypeId = @stypeid AND A.TypeId LIKE @typeid + '%'
			END
		END

		--如果只勾选了父节点，则将子节点一同显示
		INSERT INTO #PresenceAccount(STypeId,TypeId,UserCode,SonCount,flag)
		SELECT DISTINCT B.stypeid,B.typeid,REPLICATE('    ',FLeveal-1) + B.UserCode AS UserCode,B.SonCount,
		(SELECT flag FROM Ac_Account_L WHERE stypeid = B.STypeId AND TypeId = B.TypeId AND ETypeId = @etypeid) AS flag
		FROM #PresenceAccount AS A 
		INNER JOIN Ac_Account AS B ON(A.STypeId = B.StypeId AND (A.TypeId = B.ParId OR B.ParId LIKE A.TypeId+'%'))
		WHERE A.SonCount > 0 
			AND A.parflag = 1 
			AND NOT EXISTS(SELECT * FROM #PresenceAccount WHERE TypeId = B.TypeId)
	END
	ELSE
	BEGIN
		--超级用户时，要显示所有节点
		INSERT INTO #PresenceAccount(STypeId,TypeId,UserCode,SonCount,flag)
		SELECT DISTINCT A.STypeId,A.TypeId,A.UserCode,C.SonCount,B.flag 
		FROM F_GetStandard_Ac_Account(@chvOperatorID) AS A
		LEFT JOIN Ac_Account_L AS B ON(A.STypeId = B.stypeid AND B.typeid LIKE A.TypeId + '%' AND B.etypeid = @etypeid AND B.flag = 1)
		LEFT JOIN Ac_Account AS C ON(A.STypeId = C.StypeId AND A.TypeId = C.TypeId)
		WHERE A.STypeId = @stypeid AND A.TypeId LIKE @typeid + '%'
	END
	---------------------------------------------------------------------------------------------------------------------------
	--最终数据		
	SELECT (ROW_NUMBER() OVER(ORDER BY A.UserCode) -1) AS Rowid,
			--上级操作员是否有所有权限
			@OperatorAllqx AS allqx,
			CASE @FLAG 
				WHEN 1 THEN 1 --拥有所有权限
				ELSE
				CASE
					WHEN (   --该子节点的父节点是否有权限
							SELECT COUNT(1) 
							FROM Ac_Account_L 
							WHERE (TypeId = A.ParId OR A.ParId LIKE TypeId + '%') 
							AND STypeId = A.StypeId AND ETypeId = @etypeid AND flag = 1
						 ) >= 1 THEN 1
					ELSE ISNULL(AL.flag,0) 
				END
			END AS selected,
			F.UserCode AS FUserCode,
			A.fullname,
			CASE A.Fdc
			  WHEN 1 THEN '借'
			  ELSE '贷'
			END AS fdcName,
			CASE A.cid
			  WHEN 0 THEN '所有币种'
			  WHEN @syscid THEN '不核算'
			  ELSE c.FullName
			END AS cidname, 
			ISNULL(t.FullName,'') AS ascidname,
			A.TypeId,
			A.StypeId,
			A.ParId,
			A.SonCount,
			A.Leveal,
			CASE @FLAG
				WHEN 1 THEN 1
				ELSE CASE ISNULL(F.flag,2)
						WHEN 2 THEN 
						CASE ISNULL(AL.flag,2)
							WHEN 2 THEN 0
							ELSE 1
						END
						ELSE 1 
					 END 
			END AS flag,
			CASE @OperatorAllqx 
				WHEN 1 THEN 1
				ELSE ISNULL(
					(
						SELECT flag FROM Ac_Account_L 
						WHERE stypeid = A.StypeId AND typeid = A.TypeId AND etypeid = @chvOperatorID
					),0)
			END AS ParFlag,
			A.Deleted AS redword 
	FROM Ac_Account A
	INNER JOIN #PresenceAccount F ON(F.TypeId = A.TypeId AND F.StypeId = A.StypeId)
	LEFT JOIN Ac_Currency c ON c.cid = A.Cid
	LEFT JOIN 
	(
		SELECT DISTINCT STypeId,ATypeId,dbo.F_GetAc_Assist_CheckItems_FullName(ATypeId,StypeId) AS FullName 
		FROM Ac_Account_Assist_CheckItems
	) t ON(t.stypeid = a.StypeId AND t.ATypeId = A.TypeId) 
	LEFT JOIN Ac_Account_L AS AL ON(A.StypeId = AL.stypeid AND A.TypeId = AL.typeid AND AL.etypeid = @etypeid)
	WHERE   A.TypeId LIKE @typeid + '%'
			AND A.StypeId = @stypeid
			AND A.TypeId > '00000'
			AND A.UserCode > '' 
			--AND A.Deleted = 0
	ORDER BY A.UserCode
--------------------------------------------------------------------------------------------------------------------------
	DROP TABLE #PresenceAccount
END
--查看
ELSE
BEGIN
	--IF(@typeid = '00000')
	IF(@FLAG = 1)
	BEGIN
		SELECT A.UserCode AS FUserCode,B.FullName,
		CASE B.Fdc 
			WHEN 1 THEN '借' 
			ELSE '贷'
		END AS fdcName,
		CASE B.cid
			  WHEN 0 THEN '所有币种'
			  WHEN @syscid THEN '不核算'
			  ELSE B.FullName
		END AS cidname,
		ISNULL(C.FullName,'') AS ascidname,
		B.Deleted AS redword 
		FROM F_GetStandard_Ac_Account(@etypeid) AS A 
		INNER JOIN Ac_Account AS B ON(A.STypeId = B.StypeId AND A.TypeId = B.TypeId)
		LEFT JOIN 
		(
			SELECT DISTINCT STypeId,ATypeId,dbo.F_GetAc_Assist_CheckItems_FullName(ATypeId,StypeId) AS FullName 
			FROM Ac_Account_Assist_CheckItems
		) C ON(C.stypeid = a.StypeId AND C.ATypeId = A.TypeId)
		WHERE A.StypeId = @stypeid 
				AND (NOT(@typeid = '00000') AND A.TypeId LIKE @typeid + '%'
						OR (@typeid = '00000'))
		ORDER BY A.TypeId
	END
	ELSE
	BEGIN
		SELECT * 
		FROM 
		(
			SELECT C.typeid,REPLICATE('    ',C.FLeveal-1) + C.UserCode AS FUserCode,C.FullName, 
			CASE C.Fdc 
				WHEN 1 THEN '借' 
				ELSE '贷'
			END AS fdcName,
			CASE C.cid
				  WHEN 0 THEN '所有币种'
				  WHEN @syscid THEN '不核算'
				  ELSE C.FullName
			END AS cidname,
			ISNULL(D.FullName,'') AS ascidname,
			C.Deleted AS redword 
			FROM Ac_Account_L AS A 
			INNER JOIN F_GetStandard_Ac_Account(@etypeid) AS B ON(A.stypeid = B.STypeId 
			AND B.TypeId LIKE A.typeid + '%'
			--AND (NOT(@typeid = '00000') AND B.TypeId LIKE A.typeid + '%'
			--		OR(@typeid = '00000') AND B.TypeId LIKE A.typeid + '%')
			)
			INNER JOIN Ac_Account AS C ON(A.stypeid = C.StypeId AND C.TypeId LIKE A.typeid + '%' 
			AND (NOT(@typeid = '00000') 
					OR(@typeid = '00000') AND LEN(C.TypeId) > 5)
			) 
			LEFT JOIN 
			(
				SELECT DISTINCT STypeId,ATypeId,dbo.F_GetAc_Assist_CheckItems_FullName(ATypeId,StypeId) AS FullName 
				FROM Ac_Account_Assist_CheckItems
			) D ON(D.stypeid = C.StypeId AND D.ATypeId = C.TypeId)
			WHERE A.stypeid = @stypeid 
				AND A.etypeid = @etypeid 
				AND A.flag = 1
				AND C.ParId <> '00000'
				AND (NOT(@typeid = '00000') AND A.TypeId LIKE @typeid + '%' 
					OR(@typeid = '00000'))
			GROUP BY C.typeid,C.FLeveal,C.UserCode,C.FullName,C.Fdc,C.cid,D.FullName,C.Deleted
			
			UNION ALL
			
			SELECT C.typeid,REPLICATE('    ',C.FLeveal-1) + C.UserCode AS FUserCode,C.FullName, 
			CASE C.Fdc 
				WHEN 1 THEN '借' 
				ELSE '贷'
			END AS fdcName,
			CASE C.cid
				  WHEN 0 THEN '所有币种'
				  WHEN @syscid THEN '不核算'
				  ELSE C.FullName
			END AS cidname,
			ISNULL(D.FullName,'') AS ascidname,
			C.Deleted AS redword 
			FROM Ac_Account_L AS A 
			INNER JOIN F_GetStandard_Ac_Account(@etypeid) AS B ON(A.stypeid = B.STypeId AND A.typeid = B.TypeId)
			INNER JOIN Ac_Account AS C ON(A.stypeid = C.StypeId AND A.typeid = C.TypeId)
			LEFT JOIN 
			(
				SELECT DISTINCT STypeId,ATypeId,dbo.F_GetAc_Assist_CheckItems_FullName(ATypeId,StypeId) AS FullName 
				FROM Ac_Account_Assist_CheckItems
			) D ON(D.stypeid = C.StypeId AND D.ATypeId = C.TypeId)
			WHERE A.stypeid = @stypeid 
				AND A.etypeid = @etypeid 
				AND A.flag = 0
				AND (NOT(@typeid = '00000') AND A.TypeId LIKE @typeid + '%' 
					OR(@typeid = '00000'))
		) AS A 
		ORDER BY A.typeid
	END
END
--------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAc_Assist_CheckItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Web_QueryAc_Assist_CheckItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_Assist_CheckItems 查询自定义辅助核算类型
-- 时间：	2015-09-29
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryAc_Assist_CheckItems

--@encode$--

AS
SET NOCOUNT ON

SELECT 
	AscIds,
	UserCode,
	FullName
FROM Ac_Assist_CheckItems 
WHERE AscIds>4
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAc_Assist_CheckItemsDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Web_QueryAc_Assist_CheckItemsDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_Assist_CheckItemsDetail 查询指定自定义辅助核算类型明细
-- 时间：	2015-09-29
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryAc_Assist_CheckItemsDetail
(
	@AscIds		INT,			--类型ID
	@ParId		VARCHAR(50),	--父级ID
	@OperatorID	VARCHAR(50)		--操作员ID
)

----@encode$--

AS
SET NOCOUNT ON
--父节点特殊处理
IF(@ParId='root')
	SELECT @ParId=TypeId FROM Ac_Assist_CheckItemsDetail WHERE AscIds=@AscIds AND ParId=@ParId
	
SELECT
	D.TypeId,
	D.ParId,
	D.Leveal,
	D.SonNum,
	D.SonCount,
	D.AscIds,
	C.FullName AscFullName,
	D.UserCode,
	D.FullName,
	D.CreatedBy,
	E.FullName CreatedByFullName,
	CreatedDate, 
	D.Comment
FROM Ac_Assist_CheckItemsDetail D
INNER JOIN Ac_Assist_CheckItems C ON C.AscIds=D.AscIds
INNER JOIN employee E ON E.typeId=D.CreatedBy
WHERE
	D.ParId=@ParId
	AND D.AscIds=@AscIds
ORDER BY D.TypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAc_Items]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_QueryAc_Items]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：Ac_items基本信息列表数据
-- 时间：2012-06-14	
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_QueryAc_Items
(
	@TypeName	VARCHAR(2),			--TypeNAME 类别
	@Deleted	INT,				--是否停用
	@OpertiorId	VARCHAR(50)			--操作人
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @SQL VARCHAR(MAX),@Type VARCHAR(50)=''
SET @SQL='SELECT
				item.nId,
				item.UserCode,
				item.FullName,
				item.Comment,
				item.TypeName,
				item.Deleted,
				item.Sysrow,
				item.IsModify,'
IF(@TypeName='C')
	SET @SQL+='dbo.Fn_GetIsUse_Items(item.nId,7) isuse'
ELSE IF(@TypeName='L')
	SET @SQL+='dbo.Fn_GetIsUse_Items(item.nId,8) isuse'
ELSE IF(@TypeName='G')
	SET @SQL+='dbo.Fn_GetIsUse_Items(item.nId,3) isuse'
ELSE IF(@TypeName='E')
	SET @SQL+='dbo.Fn_GetIsUse_Items(item.nId,5) isuse'
SET @SQL+=char(13)+'FROM Ac_Items item '+CHAR(13)	

SET @SQL+='	WHERE  item.TypeName='''+@TypeName+''''+CHAR(13)
IF @Deleted=0
	SET @SQL+=' AND item.deleted=0'+CHAR(13)
	
IF(@TypeName='G' AND @OpertiorId NOT IN('00000','00001') AND (SELECT TOP 1 1 FROM LoginUser WHERE ETypeID =@OpertiorId AND MangerIncome<>'0000')=1)	
	BEGIN
		SET @SQL+='AND (UserCode NOT IN(''0332'',''0333'',''03333'') AND Sysrow=1)'+CHAR(13)
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeID =@OpertiorId AND MangerIncome='-99999')
			SET @SQL+= '	OR  (item.nId IN (SELECT TypeID FROM AType_L  WHERE ETypeID = '''+@OpertiorId+''' AND Flag = ''1'') AND item.TypeName='''+@TypeName+''')'+CHAR(13)
	END
IF(@TypeName='E' AND @OpertiorId NOT IN('00000','00001')AND (SELECT TOP 1 1 FROM LoginUser WHERE ETypeID =@OpertiorId AND MangerExpense<>'0000')=1)
	BEGIN
		SET @SQL+= 'AND (UserCode IN(''0404'',''0421'',''0422'',''0423'',''0424'',''5401'')  AND Sysrow=1)'+CHAR(13)
		IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeID =@OpertiorId AND MangerExpense='-99999')
				SET @SQL+= '	OR  (item.nId IN (SELECT TypeID FROM AType_L WHERE ETypeID = '''+@OpertiorId+''' AND Flag = ''1'') AND item.TypeName='''+@TypeName+''')'+CHAR(13)
	END
SET @sql+=' ORDER BY item.UserCode'		
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_QueryACAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_QueryACAccount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/30
	Description	: 查询会计科目
*/
CREATE PROCEDURE WEB_QueryACAccount
(
	@ParId varchar(100),
	@StypeId varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

IF @ParId IS NULL
BEGIN
	SET @ParId = ''
END

IF @StypeId IS NULL
BEGIN
	SET @StypeId = ''
END


SELECT	*
FROM	[Ac_Account]
WHERE [TypeId] like @ParId+'%'
	AND [StypeId] like @StypeId+'%'
ORDER BY UserCode


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAcAccountAssistCheckItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryAcAccountAssistCheckItems
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	得到指定带有辅助核算的科目
-- 时间：	2015-06-11
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryAcAccountAssistCheckItems
(
	@STypeId 			VARCHAR(50),    --分支机构
	@ChvOperatorID		VARCHAR(100),   --操作员ID
	@Cid				INT,			--币种
	@AssistCheckItems	VARCHAR(50),	--辅助核算限制
	@AssistCheckItemCount	INT			--辅助核算数目
	
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @SQL VARCHAR(MAX)
SET @SQL = '
SELECT	DISTINCT 
	x.ATypeId,
	a.Fullname,
	x.stypeid,
	a.fdc
FROM Ac_Account_Assist_CheckItems x
INNER JOIN F_TreeAccount('''+@chvOperatorID+''','''+@STypeId+''') L ON X.ATypeId=L.TypeId AND L.StypeId=X.StypeId
INNER JOIN(
	SELECT	 
		ATypeId,
		stypeid,
		COUNT(1) AS counts
	FROM Ac_Account_Assist_CheckItems 
	WHERE
		STypeId = '''+@STypeId+'''
	'+CASE WHEN @cid = 0 THEN '' ELSE '
		AND	Cid = '+CAST(@cid AS VARCHAR)+'
	' END + '
		AND Ascids IN ('+@AssistCheckItems+')
	GROUP BY
		ATypeId,
		stypeid,
		Cid
	) z ON z.ATypeId = x.ATypeId AND z.counts >= '+ CAST(@AssistCheckItemCount AS VARCHAR)+'
LEFT JOIN Ac_Account A ON A.typeid = x.atypeid AND A.stypeid = x.stypeid
WHERE x.Ascids IN ('+@AssistCheckItems+') AND X.STypeId = '''+@STypeId+''''
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAcBalanceAssist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryAcBalanceAssist
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：佘海源
	日期：2012-06-05
	描述：科目辅助余额表-在凭证中未过账查询
	
*/
CREATE PROCEDURE Web_QueryAcBalanceAssist
(
	@IsShowNoAccount INT,	---是否显示未过账
	@Fyear VARCHAR(50),		---年度
	@STypeId VARCHAR(50)	---分支机构
	
)
--@encode$--
AS
SET NOCOUNT ON

IF (@IsShowNoAccount=0)
	BEGIN
		SELECT * FROM AC_BALANCE_ASSIST_CHECKITEMS  WHERE STypeId=@STypeId AND FYear=@Fyear
		RETURN 
	END

CREATE TABLE #tempAcBalanceAssistTable --辅助核算零时表
(
       STypeId              varchar(50)          not null,
	   ATypeId              varchar(50)          not null,
	   Cid                  int                  null default -1,	   
	   IniYTotal             NUMERIC(24, 10)         null default 0,
	   IniYTotalFor          NUMERIC(24, 10)         null default 0,
	   FDebit                NUMERIC(24, 10)         null default 0,
	   FDebitFor             NUMERIC(24, 10)         null default 0,
	   FCredit               NUMERIC(24, 10)         null default 0,
	   FCreditFor            NUMERIC(24, 10)         null default 0,
	   IniTotal              NUMERIC(24, 10)         null default 0,
	   IniTotalFor           NUMERIC(24, 10)         null default 0,
	   Fyear			    VARCHAR(10),
	   Fperiod				VARCHAR(10),
	   Fendbalance           NUMERIC(24, 10) ,
	   Fendbalancefor	     NUMERIC(24, 10) ,
	   Fdc					INT
)


/********************************************获取凭证科目数据（包含过账和未过账）*************************************/
		INSERT INTO	#tempAcBalanceAssistTable
			 SELECT A.STypeId,
					A.ATypeId,
					A.Cid,
					0 AS IniYTotal,
					0 AS IniYTotalFor,
					SUM(A.FDebitTotal) AS FDebit ,
					SUM(A.FDebitTotalFor) AS FDebitFor,
					SUM(A.FCreditTotal) AS FCredit,
					SUM(A.FCreditTotalFor) AS FCreditFor,
					0 AS IniTotal ,
					0 AS IniTotalFor,
					A.FYear,
					CONVERT(varchar(10),A.FPeriod),
					0 AS Fendbalance,
					0 AS Fendbalancefor,
					A.Fdc
			 FROM	Ac_Voucher_Bill A
			 JOIN	Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1
			 JOIN	Ac_Voucher_Bill_Assist_CheckItems C ON A.ID = C.vBId
			 WHERE	A.FYear = @Fyear AND A.STypeId=@STypeId		
			GROUP BY A.FYear,A.FPeriod,A.STypeId,A.ATypeId,A.Cid,A.Fdc 
			/**********根据期初对年初进行赋值******/
			UPDATE  #tempAcBalanceAssistTable
			SET		IniYTotal=B.IniYTotal,
					IniYTotalFor = B.IniYTotalFor
			FROM	#tempAcBalanceAssistTable A
			JOIN	Ac_IniAccount_Assist_CheckItems B ON  B.FYear=@Fyear AND B.STypeId=@STypeId
						AND A.ATypeId = B.ATypeId AND	A.Cid = B.Cid 
			/**********根据期初期间 插入期初科目(交集)******/
			
			INSERT INTO	#tempAcBalanceAssistTable
				 SELECT STypeId,
						ATypeId,
						Cid,
						IniYTotal,
						IniYTotalFor,
						0,0,0,0,
						IniTotal,
						IniTotalFor,
						FYear,
						FPeriod,
						IniTotal,
						IniTotalFor,
						B.Fdc
				 FROM	Ac_IniAccount_Assist_CheckItems A
				 JOIN	(SELECT TypeId,Fdc FROM Ac_Account WHERE StypeId=@STypeId ) B ON A.ATypeId=B.TypeId
				 WHERE A.FYear=@Fyear AND A.STypeId=@STypeId AND NOT EXISTS(
									SELECT * FROM #tempAcBalanceAssistTable WHERE STypeId=@STypeId 
									AND FYear=@Fyear AND CONVERT(INT,FPeriod)=A.FPeriod AND  ATypeId=A.ATypeId 
									AND Cid=A.Cid
									)	
			/*****************计算第一期期末***************/
					UPDATE	#tempAcBalanceAssistTable
					SET		FEndBalance = 
							(CASE	WHEN Fdc=1	THEN FDebit-FCredit+IniTotal
									WHEN Fdc=-1	THEN FCredit-FDebit+IniTotal
							END),
							FEndBalanceFor = 
							(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+IniTotalFor
									WHEN Fdc=-1	THEN FCreditFor-FDebitFor+IniTotalFor
							END)
					FROM	#tempAcBalanceAssistTable
					WHERE	Fperiod=(SELECT MIN(CONVERT(int,FPeriod)) FROM #tempAcBalanceAssistTable)				

			 
/*********************************************************************************************************************/	
/*													按期间循环计算													 */
/* 参数	@MaxFPeriod：最大期间  	@MinFPeriod：初始期间		@FPeriodNum：期间循环参数，初始=@MinFPeriod																										 */
/*********************************************************************************************************************/		 
	DECLARE @MaxFPeriod INT  
	DECLARE @MinFPeriod INT
	DECLARE @MaxFPeriodVocher INT  
	SELECT @MaxFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='FPeriod'
	SELECT @MinFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='fmonth'
	SELECT  @MaxFPeriodVocher=IsNULL(MAX(CONVERT(INT,FPeriod)),0) FROM #tempAcBalanceAssistTable  
	IF @MaxFPeriodVocher>@MaxFPeriod SET @MaxFPeriod=@MaxFPeriodVocher
	DECLARE @FPeriodNum INT SET  @FPeriodNum=@MinFPeriod+1
	WHILE @FPeriodNum<=@MaxFPeriod
	BEGIN
		
	/***********************************根据上一期进行本期计算*********************************
	** 期初=上期期末		期末=期初+本期发生	
	** 本期科目=上一期科目+本期发生科目	
	** 本期有的科目而上期没有的科目	期初默认0 所有只计算期末									
	*******************************************************************************************/

		 /*上期临时表*/
		 SELECT *  INTO #PreAcBalanceTempTable 
		 FROM #tempAcBalanceAssistTable 
		 WHERE FPeriod=CONVERT(VARCHAR(10),@FPeriodNum-1)
		 
		/******************计算期初********************/
		UPDATE	#tempAcBalanceAssistTable
		SET		IniTotal=B.Fendbalance,
				IniTotalFor=B.FendbalanceFor
		FROM	#tempAcBalanceAssistTable A
		JOIN	#PreAcBalanceTempTable B 
		ON		A.ATypeId = B.ATypeId AND A.Cid=B.Cid
		WHERE	CONVERT(INT,A.FPeriod) = @FPeriodNum

		/******************计算期末********************/
		UPDATE	#tempAcBalanceAssistTable
		SET		FEndBalance = 
				(CASE	WHEN Fdc=1	THEN FDebit-FCredit+IniTotal
						WHEN Fdc=-1	THEN FCredit-FDebit+IniTotal
				END),
				FEndBalanceFor = 
				(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+IniTotalFor
						WHEN Fdc=-1	THEN FCreditFor-FDebitFor+IniTotalFor
				END)
	/***********************合并上期科目**********************************************/
	/* 上期科目本期没有发生额，直接复制到本期--本期期初=上期期末=本期期末 本期发生=0 */
	/*********************************************************************************/
		
		 /*本期临时表*/
		SELECT * INTO #CurAcBalanceTempTable 
				FROM  #tempAcBalanceAssistTable 
				WHERE CONVERT(INT,FPeriod) = @FPeriodNum
		
		INSERT INTO	#tempAcBalanceAssistTable 
			 SELECT	A.STypeId,
					A.ATypeId,
					A.Cid,
					A.IniYTotal,
					A.IniYTotalFor,
					0,0,0,0,
					A.Fendbalance,
					A.FendbalanceFor,
					A.FYear,
					CONVERT(VARCHAR(10),@FPeriodNum),
					A.Fendbalance,
					A.FendbalanceFor,
					A.Fdc
			   FROM #PreAcBalanceTempTable A
			  WHERE NOT EXISTS(SELECT * FROM #CurAcBalanceTempTable WHERE ATypeId=A.ATypeId AND Cid=A.Cid)
			  		 	
		DROP TABLE #PreAcBalanceTempTable,#CurAcBalanceTempTable
	--	/*循环下一期间*/
		SET @FPeriodNum=@FPeriodNum+1
	END /*循环结束*/
	
	
	ALTER TABLE #tempAcBalanceAssistTable DROP COLUMN Fdc    /*Fdc不是AC_Balance默认字段 此处作为临时使用，故删除*/
	
/************************************************************************************************/
/*										计算综合本位币											*/
/************************************************************************************************/		
	INSERT INTO #tempAcBalanceAssistTable
		SELECT	STypeId,
				ATypeId,
				0,
				SUM(IniYTotal),
				SUM(IniYTotal),
				SUM(FDebit),
				SUM(FDebit),
				SUM(FCredit),
				SUM(FCredit),
				SUM(IniTotal),
				SUM(IniTotal),
				@Fyear,
				FPeriod,
				SUM(Fendbalance),
				SUM(Fendbalance)
		  FROM	#tempAcBalanceAssistTable
		  GROUP BY STypeId,FPeriod,ATypeId



 SELECT  * FROM #tempAcBalanceAssistTable ORDER BY AtypeId
 DROP TABLE #tempAcBalanceAssistTable


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAcBalanceAssistDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryAcBalanceAssistDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：佘海源
	日期：2012-06-05
	描述：辅助余额表-在凭证中未过账查询
	
*/
CREATE PROCEDURE Web_QueryAcBalanceAssistDetail
(
	@IsShowNoAccount	INT,			---是否显示未过账
	@Fyear				VARCHAR(50),	---年度
	@STypeId			VARCHAR(50)		---分支机构
	
)
--@encode$--
AS
SET NOCOUNT ON


IF (@IsShowNoAccount=0)
	BEGIN
		SELECT * FROM AC_BALANCE_ASSIST_CHECKITEMS_DETAIL  WHERE STypeId=@STypeId AND FYear=@Fyear
		RETURN 
	END

CREATE TABLE #tempAcBalanceAssistDetailTable  ---辅助核算余额明细表临时表
(
   	STypeId             VARCHAR(50),       
	ATypeId             VARCHAR(50),        
	Cid                 INT,           
	AscIds              INT,                
	Fieldvalue           VARCHAR(50),        
	FDebit				 NUMERIC(24, 10) ,		
	FDebitFor			 NUMERIC(24, 10) ,		
	FCredit				 NUMERIC(24, 10) ,		
	FCreditFor			 NUMERIC(24, 10) ,		
	IniTotal			 NUMERIC(24, 10) ,	
	IniTotalFor			 NUMERIC(24, 10) ,		
	Fendbalance			 NUMERIC(24, 10) ,		
	Fendbalancefor		 NUMERIC(24, 10) ,		
	FYear               VARCHAR(10),       
	FPeriod             INT,
	Fdc					INT          
)



/********************************************获取账务数据*************************************/
		SELECT	STypeId,
				ATypeId,
				Cid,
				Ascids,
				FieldValue,
				FYear,
				FPeriod,
				Sum(IniTotal) AS IniTotal ,
				Sum(IniTotalFor) AS IniTotalFor
		 INTO	#Ac_IniAccount_AssistTemp		
		FROM	Ac_IniAccount_Assist_CheckItems_Detail
	GROUP BY	STypeId,ATypeId,Cid,Ascids,FieldValue,FYear,FPeriod

/********************************************获取凭证科目数据（包含过账和未过账）*************************************/
		INSERT INTO	#tempAcBalanceAssistDetailTable
			 SELECT A.STypeId,
					A.ATypeId,
					A.Cid,
					CI.AscIds,
					C.TypeId AS Fieldvalue,
					SUM(A.FDebitTotal) AS FDebit ,
					SUM(A.FDebitTotalFor) AS FDebitFor,
					SUM(A.FCreditTotal) AS FCredit,
					SUM(A.FCreditTotalFor) AS FCreditFor,
					0 AS IniTotal ,
					0 AS IniTotalFor,
					0 AS Fendbalance,
					0 AS Fendbalancefor,
					A.FYear,
					A.FPeriod,
					D.Fdc
			 FROM	Ac_Voucher_Bill A
			 JOIN	Ac_Voucher  B ON A.BillNumberId = B.BillNumberId AND  FChecked<>-1
			 JOIN	Ac_Voucher_Bill_Assist_CheckItems C ON A.ID = C.vBId
			 INNER JOIN Ac_Assist_CheckItems CI ON CI.UserCode=C.typeName
			 JOIN	Ac_Account D ON D.TypeId=A.ATypeId AND D.StypeId=A.STypeId
			 WHERE	A.FYear = @Fyear AND A.STypeId=@STypeId		
			GROUP BY A.FYear,A.FPeriod,A.STypeId,A.ATypeId,C.typeName,C.TypeId,A.Cid,D.Fdc ,CI.AscIds
			
			/**********根据期初赋值第一期期初数据******/
			UPDATE  #tempAcBalanceAssistDetailTable
			SET		IniTotal=B.IniTotal,
					IniTotalFor = B.IniTotalFor
			FROM	#tempAcBalanceAssistDetailTable A
			JOIN	#Ac_IniAccount_AssistTemp B ON B.FYear=@Fyear AND A.FPeriod = B.FPeriod 
					AND B.STypeId=@STypeId AND A.ATypeId = B.ATypeId AND A.AscIds=B.Ascids 
					AND A.Fieldvalue=B.FieldValue AND	A.Cid = B.Cid 
					

			/**********根据期初期间 插入期初辅助明细科目数据(并集)******/
			INSERT INTO	#tempAcBalanceAssistDetailTable
				 SELECT A.STypeId,
						ATypeId,
						A.Cid,
						A.Ascids,
						FieldValue,
						0,0,0,0,
						IniTotal,
						IniTotalFor,
						IniTotal,
						IniTotalFor,
						FYear,
						FPeriod,
						B.Fdc
				 FROM	#Ac_IniAccount_AssistTemp A
				 INNER JOIN Ac_Account B ON B.StypeId=@STypeId AND A.ATypeId=B.TypeId
				 --JOIN	(SELECT TypeId,Fdc FROM Ac_Account WHERE StypeId=@STypeId ) B ON A.ATypeId=B.TypeId
				 WHERE  FYear=@Fyear AND A.STypeId=@STypeId AND	
						NOT EXISTS(SELECT * FROM #tempAcBalanceAssistDetailTable 
									WHERE FYear=@Fyear AND  STypeId=@STypeId  AND Fperiod=A.FPeriod 
									AND  ATypeId=A.ATypeId AND AscIds=A.Ascids AND Fieldvalue= A.FieldValue 
									AND Cid=A.Cid
									)	
			
				/*****************计算第一期期末***************/
					UPDATE	#tempAcBalanceAssistDetailTable
					SET		FEndBalance = 
							(CASE	WHEN Fdc=1	THEN FDebit-FCredit+IniTotal
									WHEN Fdc=-1	THEN FCredit-FDebit+IniTotal
							END),
							FEndBalanceFor = 
							(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+IniTotalFor
									WHEN Fdc=-1	THEN FCreditFor-FDebitFor+IniTotalFor
							END)
					FROM	#tempAcBalanceAssistDetailTable
					WHERE	Fperiod=(SELECT MIN(Fperiod) FROM #tempAcBalanceAssistDetailTable)		

	

		
/*********************************************************************************************************************/	
/*													按期间循环计算													 */
/* 参数	@MaxFPeriod：最大期间  	@MinFPeriod：初始期间		@FPeriodNum：期间循环参数，初始=@MinFPeriod																										 */
/*********************************************************************************************************************/		 
	DECLARE @MaxFPeriod INT  
	DECLARE @MinFPeriod INT
	DECLARE @MaxFPeriodVocher INT  
	SELECT @MaxFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='FPeriod'
	SELECT @MinFPeriod=CONVERT(INT,SubValue)  FROM sysdata WHERE SubName='fmonth'
	SELECT  @MaxFPeriodVocher=IsNULL(MAX(CONVERT(INT,FPeriod)),0) FROM #tempAcBalanceAssistDetailTable  
	IF @MaxFPeriodVocher>@MaxFPeriod SET @MaxFPeriod=@MaxFPeriodVocher
	
	DECLARE @FPeriodNum INT SET  @FPeriodNum=@MinFPeriod+1
	
	WHILE @FPeriodNum<=@MaxFPeriod
	BEGIN
		
	/***********************************根据上一期进行本期计算*********************************
	** 期初=上期期末		期末=期初+本期发生	
	** 本期科目=上一期科目+本期发生科目	
	** 本期有的科目而上期没有的科目	期初默认0 所有只计算期末									
	*******************************************************************************************/

		 /*上期临时表*/
		 SELECT *  INTO #PreDetailTempTable 
		 FROM #tempAcBalanceAssistDetailTable 
		 WHERE FPeriod=@FPeriodNum-1
		 
		/******************计算期初********************/
		UPDATE	#tempAcBalanceAssistDetailTable
		SET		IniTotal=B.Fendbalance,
				IniTotalFor=B.FendbalanceFor
		FROM	#tempAcBalanceAssistDetailTable A
		JOIN	#PreDetailTempTable B 
		ON		A.ATypeId = B.ATypeId AND A.Cid=B.Cid AND A.AscIds=B.AscIds AND A.Fieldvalue = B.Fieldvalue
		WHERE	A.FPeriod = @FPeriodNum

		/******************计算期末********************/
		UPDATE	#tempAcBalanceAssistDetailTable
		SET		FEndBalance = 
				(CASE	WHEN Fdc=1	THEN FDebit-FCredit+IniTotal
						WHEN Fdc=-1	THEN FCredit-FDebit+IniTotal
				END),
				FEndBalanceFor = 
				(CASE	WHEN Fdc=1	THEN FDebitFor-FCreditFor+IniTotalFor
						WHEN Fdc=-1	THEN FCreditFor-FDebitFor+IniTotalFor
				END)
	/***********************合并上期科目**********************************************/
	/* 上期科目本期没有发生额，直接复制到本期--本期期初=上期期末=本期期末 本期发生=0 */
	/*********************************************************************************/
		
		 /*本期临时表*/
		SELECT * INTO #CurDetailTempTable 
				FROM  #tempAcBalanceAssistDetailTable 
				WHERE FPeriod = @FPeriodNum
		
		INSERT INTO	#tempAcBalanceAssistDetailTable 
			 SELECT	A.STypeId,
					A.ATypeId,
					A.Cid,
					A.AscIds,
					A.Fieldvalue,
					0,0,0,0,
					A.Fendbalance,
					A.FendbalanceFor,
					A.Fendbalance,
					A.FendbalanceFor,
					A.FYear,
					@FPeriodNum,
					A.Fdc
			   FROM #PreDetailTempTable A
			  WHERE NOT EXISTS(SELECT * FROM #CurDetailTempTable WHERE ATypeId=A.ATypeId 
								AND AscIds=A.AscIds AND Fieldvalue=A.Fieldvalue  AND Cid=A.Cid  )
			  		 	
		DROP TABLE #PreDetailTempTable,#CurDetailTempTable
	--	/*循环下一期间*/
		SET @FPeriodNum=@FPeriodNum+1
	END /*循环结束*/
	
	
	ALTER TABLE #tempAcBalanceAssistDetailTable DROP COLUMN Fdc    /*Fdc不是AC_Balance默认字段 此处作为临时使用，故删除*/
	
/************************************************************************************************/
/*										计算综合本位币											*/
/************************************************************************************************/		
	INSERT INTO #tempAcBalanceAssistDetailTable
		SELECT	STypeId,
				ATypeId,
				0,
				AscIds,
				Fieldvalue,
				SUM(FDebit),
				SUM(FDebit),
				SUM(FCredit),
				SUM(FCredit),
				SUM(IniTotal),
				SUM(IniTotal),
				SUM(Fendbalance),
				SUM(Fendbalance),
				@Fyear,
				FPeriod
		  FROM	#tempAcBalanceAssistDetailTable
		  GROUP BY STypeId,FPeriod,ATypeId,AscIds,Fieldvalue



 SELECT  * FROM #tempAcBalanceAssistDetailTable ORDER BY AtypeId
 DROP TABLE #Ac_IniAccount_AssistTemp,#tempAcBalanceAssistDetailTable


	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryAcBalanceFromVoucher]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].WEB_QueryAcBalanceFromVoucher
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--==============================================
--	作者:		glj  
--	日期:		2013-10-29
--	描述:		返回科目年度数据 (支持多分支机构)
--==============================================
CREATE PROCEDURE WEB_QueryAcBalanceFromVoucher
(
	@StypeId			VARCHAR(MAX),---分支机构t
	@Fyear				INT,		---年度
	@Cid				INT,		--币种
	@FPeriodStart		INT,		---起始期间
	@FPeriodEnd			INT,		---结束期间
	@IsShowNoAccount	INT,		---是否显示未过账
	@IsShowPL			INT,		--不包含查询期间内结转损益数据
	@chvOperatorID		VARCHAR(50)	---操作员ID
)
--@encode$--
AS 
SET NOCOUNT ON
--========================================定义变量【BEGIN】 =====================================
DECLARE 
	@SQL				VARCHAR(MAX)='',--sql
	@MaxFYear			INT=@FYear,--最大年度值
	@MaxFPeriodStart	INT=@FPeriodStart,--开始期间
	@MaxFPeriodEnd		INT=@FPeriodEnd,--结束期间
	@MinFPeriod			INT,--最大年度值
	@I					INT=1,
	@J					INT
--多分支机构
CREATE TABLE #SType(NID INT IDENTITY(1,1),STypeId VARCHAR(50),IsUse INT)
INSERT INTO #SType(STypeId,IsUse)
SELECT 
	PS.Stypeid,
	PS.IsUse 
FROM f_split(@StypeId,',') F 
INNER JOIN Ac_AccountsPeroid_Stype PS ON PS.Stypeid=F.a
SELECT @J=@@ROWCOUNT

--权限内科目
CREATE TABLE #LineAccount(TypeId VARCHAR(50),STypeId VARCHAR(50),Fdc INT,IsUse INT)
INSERT INTO #LineAccount(TypeId,STypeId,Fdc,IsUse)
SELECT 
	A.TypeId,
	A.StypeId,
	A.Fdc,
	S.IsUse
FROM Ac_Account A
INNER JOIN #SType S ON S.STypeId=A.Stypeid AND A.SonNum=0 AND A.ParId<>'00000'
INNER JOIN F_LineAccount(@chvOperatorID,'') F ON F.Stypeid=A.StypeId AND F.Typeid=A.TypeId

--========================================定义变量【END】  =====================================
	
--========================================业务逻辑处理【BEGIN】  ===============================
CREATE TABLE #Ac_Balance   --返回数据表
(
	 STypeId			VARCHAR(50),							--分支机构
	 ATypeId			VARCHAR(50),							--科目
	 Fdc				INT,									--科目方向
	 Cid				INT,									--币种
	 NCDebitFor			NUMERIC(24, 10)	NOT NULL DEFAULT(0),	--年初借方
	 NCCreditFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--年初贷方
	 FDebitBeginFor		NUMERIC(24, 10)	NOT NULL DEFAULT(0),	--期初借方
	 FCreditBeginFor	NUMERIC(24, 10) NOT NULL DEFAULT(0),	--期初贷方
	 FDebitFor			NUMERIC(24, 10) NOT NULL DEFAULT(0),	--本期借方
	 FCreditFor			NUMERIC(24, 10) NOT NULL DEFAULT(0),	--本期贷方
	 FYtdDebitFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--本年借方
	 FYtdCreditFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--本年贷方
	 FDebitEndFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--期末借方
	 FCreditEndFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--期末贷方
	 NCDebitForQty		NUMERIC(24, 10)	NOT NULL DEFAULT(0),	--年初借方数量
	 NCCreditForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--年初贷方数量
	 FDebitBeginForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),	--期初借方数量
	 FCreditBeginForQty NUMERIC(24, 10) NOT NULL DEFAULT(0),	--期初贷方数量
	 FDebitForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--本期借方数量
	 FCreditForQty		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--本期贷方数量
	 FYtdDebitForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),	--本年借方数量
	 FYtdCreditForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),	--本年贷方数量
	 FDebitEndForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),	--期末借方数量
	 FCreditEndForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0)		--期末贷方数量
)

--插入结果集中
IF(@Cid<>-1)
	BEGIN
		IF @Cid = 0
			INSERT INTO #Ac_Balance(STypeId,ATypeId,Fdc,Cid)
			SELECT A.STypeId,A.TypeId,Fdc,@Cid Cid FROM #LineAccount A GROUP BY A.STypeId,A.TypeId,Fdc
		ELSE 
			INSERT INTO #Ac_Balance(STypeId,ATypeId,Fdc,Cid)
			SELECT A.STypeId,A.TypeId,A.Fdc,@Cid Cid FROM #LineAccount A INNER JOIN dbo.Ac_Account AC ON AC.TypeId = A.TypeId AND (AC.Cid = @Cid OR AC.Cid = 0)
			GROUP BY A.STypeId,A.TypeId,A.Fdc 
	END
ELSE 
	BEGIN
		INSERT INTO #Ac_Balance(STypeId,ATypeId,Fdc,Cid)
		SELECT A.STypeId,A.TypeId,Fdc,C.CId FROM #LineAccount A,Ac_Currency C 
		GROUP BY A.STypeId,A.TypeId,Fdc,C.CId
		UNION ALL
		SELECT A.STypeId,A.TypeId,Fdc,0 Cid FROM #LineAccount A GROUP BY A.STypeId,A.TypeId,Fdc
	END
--分支机构没有开账
IF @Cid IN(0,-1)--综合本位币
	BEGIN
		UPDATE #Ac_Balance
		SET 
			NCDebitFor=A.NCDebitFor,
			NCCreditFor=A.NCCreditFor,
			NCDebitForQty=A.NCDebitForQty,
			NCCreditForQty=A.NCCreditForQty,
			FDebitBeginFor=A.FDebitBeginFor,
			FCreditBeginFor=A.FCreditBeginFor,
			FDebitFor=A.FDebitFor,
			FCreditFor=A.FCreditFor,
			FYtdDebitFor=A.FYtdDebitFor,
			FYtdCreditFor=A.FYtdCreditFor,
			FDebitEndFor=A.FDebitEndFor,
			FCreditEndFor=A.FCreditEndFor,
			FDebitBeginForQty=A.FDebitBeginForQty,
			FCreditBeginForQty=A.FCreditBeginForQty,
			FDebitForQty=A.FDebitForQty,
			FCreditForQty=A.FCreditForQty,
			FYtdDebitForQty=A.FYtdDebitForQty,
			FYtdCreditForQty=A.FYtdCreditForQty,
			FDebitEndForQty=A.FDebitEndForQty,
			FCreditEndForQty=A.FCreditEndForQty
		FROM #Ac_Balance T
		INNER JOIN (
			SELECT
				I.STypeId,
				I.ATypeId,
				0 Cid,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniYTotal) ELSE 0 END NCDebitFor,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniYTotal) ELSE 0 END NCCreditFor,
				CASE WHEN A.Fdc=1 THEN SUM(I.IniYqty) ELSE 0 END NCDebitForQty,
				CASE WHEN A.Fdc=-1 THEN SUM(I.IniYqty) ELSE 0 END NCCreditForQty,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniTotal) ELSE 0 END FDebitBeginFor,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniqty) ELSE 0 END FDebitBeginForQty,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniTotal) ELSE 0 END FCreditBeginFor,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniqty) ELSE 0 END FCreditBeginForQty,
				0 FDebitFor,
				0 FDebitForQty,
				0 FCreditFor,
				0 FCreditForQty,
				SUM(I.FDebit) FYtdDebitFor,
				SUM(I.FDebitqty) FYtdDebitForQty,
				SUM(I.FCredit) FYtdCreditFor,
				SUM(I.FCreditqty) FYtdCreditForQty,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniTotal) ELSE 0 END FDebitEndFor,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniqty) ELSE 0 END FDebitEndForQty,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniTotal) ELSE 0 END FCreditEndFor,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniqty) ELSE 0 END FCreditEndForQty
			FROM Ac_IniAccount I
			INNER JOIN #LineAccount A ON A.StypeId=I.StypeId AND A.TypeId=I.ATypeId AND I.FYear=@Fyear AND IsUse=0
			GROUP BY I.STypeId,I.ATypeId,A.Fdc
		) A ON A.STypeId=T.STypeId AND A.ATypeId=T.ATypeId AND A.Cid=T.Cid 
	END
IF @Cid<>0  --具体币种
	BEGIN
		UPDATE #Ac_Balance
		SET 
			NCDebitFor=A.NCDebitFor,
			NCCreditFor=A.NCCreditFor,
			NCDebitForQty=A.NCDebitForQty,
			NCCreditForQty=A.NCCreditForQty,
			FDebitBeginFor=A.FDebitBeginFor,
			FCreditBeginFor=A.FCreditBeginFor,
			FDebitFor=A.FDebitFor,
			FCreditFor=A.FCreditFor,
			FYtdDebitFor=A.FYtdDebitFor,
			FYtdCreditFor=A.FYtdCreditFor,
			FDebitEndFor=A.FDebitEndFor,
			FCreditEndFor=A.FCreditEndFor,
			FDebitBeginForQty=A.FDebitBeginForQty,
			FCreditBeginForQty=A.FCreditBeginForQty,
			FDebitForQty=A.FDebitForQty,
			FCreditForQty=A.FCreditForQty,
			FYtdDebitForQty=A.FYtdDebitForQty,
			FYtdCreditForQty=A.FYtdCreditForQty,
			FDebitEndForQty=A.FDebitEndForQty,
			FCreditEndForQty=A.FCreditEndForQty
		FROM #Ac_Balance T
		INNER JOIN (
			SELECT
				I.STypeId,
				I.ATypeId,
				I.Cid,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniYTotalFor) ELSE 0 END NCDebitFor,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniYTotalFor) ELSE 0 END NCCreditFor,
				CASE WHEN A.Fdc=1 THEN SUM(I.IniYqty) ELSE 0 END NCDebitForQty,
				CASE WHEN A.Fdc=-1 THEN SUM(I.IniYqty) ELSE 0 END NCCreditForQty,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniTotalFor) ELSE 0 END FDebitBeginFor,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniqty) ELSE 0 END FDebitBeginForQty,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniTotalFor) ELSE 0 END FCreditBeginFor,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniqty) ELSE 0 END FCreditBeginForQty,
				0 FDebitFor,
				0 FDebitForQty,
				0 FCreditFor,
				0 FCreditForQty,
				SUM(I.FDebitFor) FYtdDebitFor,
				SUM(I.FDebitqty) FYtdDebitForQty,
				SUM(I.FCreditFor) FYtdCreditFor,
				SUM(I.FCreditqty) FYtdCreditForQty,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniTotalFor) ELSE 0 END FDebitEndFor,
				CASE WHEN A.Fdc=1 THEN SUM(I.iniqty) ELSE 0 END FDebitEndForQty,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniTotalFor) ELSE 0 END FCreditEndFor,
				CASE WHEN A.Fdc=-1 THEN SUM(I.iniqty) ELSE 0 END FCreditEndForQty
			FROM Ac_IniAccount I
			INNER JOIN #LineAccount A ON A.StypeId=I.StypeId AND A.TypeId=I.ATypeId AND I.FYear=@Fyear AND ((@Cid=-1 AND 1=1) OR I.Cid=@Cid) AND IsUse=0
			GROUP BY I.STypeId,I.ATypeId,A.Fdc,I.Cid
		) A ON A.STypeId=T.STypeId AND A.ATypeId=T.ATypeId AND A.Cid=T.Cid
	END	

--已经记账分支机构
WHILE(@I<=@J)
	BEGIN
		IF EXISTS(SELECT * FROM #SType WHERE NID=@I AND IsUse=0)
			BEGIN
				SET @I+=1
				CONTINUE;
			END
		SELECT @StypeId=STypeId FROM #SType WHERE NID=@I
		--判断科目余额表中指定分支开始期间及年度值
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear>=@FYear AND STypeId=@STypeId)
			BEGIN
				SET @MaxFYear=@Fyear
				IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear=@FYear AND STypeId=@STypeId AND FPeriod>=@FPeriodStart)
					SELECT @MaxFPeriodStart=MAX(FPeriod),@MaxFPeriodEnd=MAX(FPeriod) FROM Ac_Balance WHERE FYear=@FYear AND STypeId=@STypeId
				ELSE 
					BEGIN
						SET @MaxFPeriodStart=@FPeriodStart
						SET @MaxFPeriodEnd=@FPeriodEnd
						IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_Balance WHERE FYear=@FYear AND STypeId=@STypeId AND FPeriod>=@FPeriodEnd)
							SELECT @MaxFPeriodEnd=MAX(FPeriod) FROM Ac_Balance WHERE FYear=@FYear AND STypeId=@STypeId
					END
				END
		ELSE 
			BEGIN
				SELECT @MaxFYear=MAX(FYear) FROM Ac_Balance WHERE STypeId=@STypeId
				SELECT @MaxFPeriodStart=MAX(FPeriod),@MaxFPeriodEnd=MAX(FPeriod) FROM Ac_Balance WHERE FYear=@MaxFYear AND STypeId=@STypeId		
			END
		
		--期初 金额+数量
		UPDATE #Ac_Balance
		SET 
			FDebitBeginFor+=CASE WHEN T.Fdc=1 THEN CASE WHEN @Fyear=@MaxFYear AND @FPeriodStart=@MaxFPeriodStart THEN B.FBeginBalanceFor ELSE B.FEndBalance END ELSE 0 END,
			FCreditBeginFor+=CASE WHEN T.Fdc=-1 THEN CASE WHEN @Fyear=@MaxFYear AND @FPeriodStart=@MaxFPeriodStart THEN B.FBeginBalanceFor ELSE B.FEndBalance END ELSE 0 END,
			FDebitBeginForQty+=CASE WHEN T.Fdc=1 THEN CASE WHEN @Fyear=@MaxFYear AND @FPeriodStart=@MaxFPeriodStart THEN B.FBeginqty ELSE B.FEndqty END ELSE 0 END,
			FCreditBeginForQty+=CASE WHEN T.Fdc=-1 THEN CASE WHEN @Fyear=@MaxFYear AND @FPeriodStart=@MaxFPeriodStart THEN B.FBeginqty ELSE B.FEndqty END ELSE 0 END
			
		FROM #Ac_Balance T
		INNER JOIN Ac_Balance B ON B.STypeId=@StypeId AND B.STypeId=T.STypeId AND B.ATypeId=T.ATypeId AND B.Cid=T.Cid AND B.FYear=@MaxFYear AND B.FPeriod=@MaxFPeriodStart
		
		--期末，本年 金额+数量
		UPDATE #Ac_Balance
		SET 
			FYtdDebitFor+=CASE WHEN @Fyear=@MaxFYear THEN B.FYtdDebitFor ELSE 0 END,
			FYtdCreditFor+=CASE WHEN @Fyear=@MaxFYear THEN B.FYtdCreditFor ELSE 0 END,
			FDebitEndFor+=CASE WHEN T.Fdc=1 THEN B.FEndBalanceFor ELSE 0 END,
			FCreditEndFor+=CASE WHEN T.Fdc=-1 THEN B.FEndBalanceFor ELSE 0 END,
			FYtdDebitForQty+=CASE WHEN @Fyear=@MaxFYear THEN B.FYtdDebitqty ELSE 0 END,
			FYtdCreditForQty+=CASE WHEN @Fyear=@MaxFYear THEN B.FYtdCreditqty ELSE 0 END,
			FDebitEndForQty+=CASE WHEN T.Fdc=1 THEN B.FEndqty ELSE 0 END,
			FCreditEndForQty+=CASE WHEN T.Fdc=-1 THEN B.FEndqty ELSE 0 END
		FROM #Ac_Balance T
		INNER JOIN Ac_Balance B ON B.STypeId=@StypeId AND B.STypeId=T.STypeId AND B.ATypeId=T.ATypeId AND B.Cid=T.Cid AND B.FYear=@MaxFYear AND B.FPeriod=@MaxFPeriodEnd
		
		--本期 金额+数量
		UPDATE #Ac_Balance
		SET 
			FDebitFor+=CASE WHEN @Fyear=@MaxFYear AND @MaxFPeriodEnd>=@FPeriodStart THEN F.FDebitFor ELSE 0 END,
			FCreditFor+=CASE WHEN @Fyear=@MaxFYear AND @MaxFPeriodEnd>=@FPeriodStart THEN F.FCreditFor ELSE 0 END,
			FDebitForQty+=CASE WHEN @Fyear=@MaxFYear AND @MaxFPeriodEnd>=@FPeriodStart THEN F.FDebitForQty ELSE 0 END,
			FCreditForQty+=CASE WHEN @Fyear=@MaxFYear AND @MaxFPeriodEnd>=@FPeriodStart THEN F.FCreditForQty ELSE 0 END
		FROM #Ac_Balance T
		INNER JOIN
		(
			SELECT
				B.STypeId,
				B.ATypeId,
				B.Cid,
				SUM(FDebitFor) FDebitFor,
				SUM(FCreditFor) FCreditFor,
				SUM(FDebitqty) FDebitForQty,
				SUM(FCreditqty) FCreditForQty
			FROM Ac_Balance B 
			INNER JOIN #LineAccount L ON L.STypeId=@StypeId AND L.STypeId=B.STypeId AND L.TypeId=B.ATypeId AND B.FYear=@MaxFYear AND B.FPeriod BETWEEN @MaxFPeriodStart AND @MaxFPeriodEnd
			GROUP BY B.STypeId,B.ATypeId,B.Cid	
		) F ON F.STypeId=T.STypeId AND F.ATypeId=T.ATypeId AND F.Cid=T.Cid
		
		--年初,如果有本年数据取最小期间期初余额，然取最大期间期末余额
		IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeId AND SFYear=@Fyear AND IsUse=1)
			BEGIN
				UPDATE #Ac_Balance
				SET 
					NCDebitFor=A.NCDebitFor,
					NCCreditFor=A.NCCreditFor,
					NCDebitForQty=A.NCDebitForQty,
					NCCreditForQty=A.NCCreditForQty
				FROM #Ac_Balance T
				INNER JOIN (
					SELECT
						I.STypeId,
						I.ATypeId,
						I.Cid,
						CASE WHEN A.Fdc=1 THEN SUM(I.iniYTotalFor) ELSE 0 END NCDebitFor,
						CASE WHEN A.Fdc=-1 THEN SUM(I.iniYTotalFor) ELSE 0 END NCCreditFor,
						CASE WHEN A.Fdc=1 THEN SUM(I.IniYqty) ELSE 0 END NCDebitForQty,
						CASE WHEN A.Fdc=-1 THEN SUM(I.IniYqty) ELSE 0 END NCCreditForQty
					FROM Ac_IniAccount I
					INNER JOIN #LineAccount A ON A.StypeId=I.StypeId AND A.TypeId=I.ATypeId AND ((@Cid=-1 AND 1=1) OR I.Cid=@Cid) AND IsUse=1
					GROUP BY I.STypeId,I.ATypeId,A.Fdc,I.Cid
					UNION ALL
					SELECT
						I.STypeId,
						I.ATypeId,
						0 Cid,
						CASE WHEN A.Fdc=1 THEN SUM(I.iniYTotal) ELSE 0 END NCDebitFor,
						CASE WHEN A.Fdc=-1 THEN SUM(I.iniYTotal) ELSE 0 END NCCreditFor,
						CASE WHEN A.Fdc=1 THEN SUM(I.IniYqty) ELSE 0 END NCDebitForQty,
						CASE WHEN A.Fdc=-1 THEN SUM(I.IniYqty) ELSE 0 END NCCreditForQty
					FROM Ac_IniAccount I
					INNER JOIN #LineAccount A ON A.StypeId=I.StypeId AND A.TypeId=I.ATypeId AND IsUse=1
					GROUP BY I.STypeId,I.ATypeId,A.Fdc
					
				) A ON A.STypeId=T.STypeId AND A.ATypeId=T.ATypeId AND A.Cid=T.Cid
			END
		ELSE IF(@Fyear>@MaxFYear)
			BEGIN
				UPDATE #Ac_Balance
				SET
					NCDebitFor+=B.FYtdDebitFor,
					NCDebitForQty+=B.FYtdDebitqty,
					NCCreditFor+=B.FYtdCreditFor,
					NCCreditForQty+=B.FYtdCreditqty
				FROM #Ac_Balance T
				INNER JOIN Ac_Balance B ON B.STypeId=@StypeId AND B.STypeId=T.STypeId AND B.ATypeId=T.ATypeId AND B.Cid=T.Cid AND B.FYear=@MaxFYear AND B.FPeriod=@MaxFPeriodEnd
			END
		ELSE IF NOT EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeId AND SFYear=@Fyear) AND @MaxFYear=@Fyear
			BEGIN
				SELECT @MinFPeriod=MIN(FPeriod) FROM Ac_Balance WHERE FYear=@MaxFYear AND STypeId=@StypeId
				UPDATE #Ac_Balance
				SET
					NCDebitFor+=CASE WHEN T.Fdc=1 THEN B.FBeginBalanceFor ELSE 0 END ,
					NCDebitForQty+=CASE WHEN T.Fdc=1 THEN B.FBeginqty ELSE 0 END ,
					NCCreditFor+=CASE WHEN T.Fdc=-1 THEN B.FBeginBalanceFor ELSE 0 END ,
					NCCreditForQty+=CASE WHEN T.Fdc=-1 THEN B.FBeginqty ELSE 0 END 
				FROM #Ac_Balance T
				INNER JOIN Ac_Balance B ON B.STypeId=@StypeId AND B.STypeId=T.STypeId AND B.ATypeId=T.ATypeId AND B.Cid=T.Cid AND B.FYear=@MaxFYear AND B.FPeriod=@MinFPeriod
			END
		SET @I+=1
	END

--凭证表临时表
CREATE TABLE #VoucherBill
(
	STypeId			VARCHAR(50),				--分支机构
	ATypeId			VARCHAR(50),				--科目ID
	Cid				INT,						--币种
	FYear			INT,						--年度
	FPeriod			INT,						--期间
	FDebitFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--借方
	FDebitForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),	--借方
	FCreditFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--贷方
	FCreditForQty	NUMERIC(24, 10) NOT NULL DEFAULT(0),	--贷方
	TotalFor		NUMERIC(24, 10) NOT NULL DEFAULT(0),	--余额
	TotalQty		NUMERIC(24, 10) NOT NULL DEFAULT(0)		--余额数量
)
IF @IsShowNoAccount=1--包含未记账凭证
	BEGIN
		IF @Cid=0 OR @Cid=-1--综合本位币
			BEGIN
				INSERT INTO #VoucherBill(STypeId,ATypeId,Cid,FYear,FPeriod,FDebitFor,FDebitForQty,FCreditFor,FCreditForQty,TotalFor,TotalQty)
				SELECT
					B.STypeId,
					B.ATypeId,
					0 Cid,
					B.FYear,
					B.FPeriod,
					SUM(B.FDebitTotal) FDebitFor,
					SUM(FDebitQty) FDebitForQty,
					SUM(B.FCreditTotal) FCreditFor,
					SUM(FCreditQty) FCreditForQty,
					SUM(CASE WHEN A.Fdc=1 THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END) TotalFor,
					SUM(CASE WHEN A.Fdc=1 THEN B.FDebitQty-B.FCreditQty ELSE B.FCreditQty-B.FDebitQty END) TotalQty
				FROM Ac_Voucher V 
				INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
				INNER JOIN #LineAccount A ON A.StypeId=B.StypeId AND A.TypeId=B.ATypeId
				WHERE 
					(B.FYear<@Fyear 
						OR (B.FYear=@Fyear AND B.FPeriod<=@FPeriodEnd))
				GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod,A.Fdc
			END
		IF @Cid<>0  --具体币种
			BEGIN
				INSERT INTO #VoucherBill(STypeId,ATypeId,Cid,FYear,FPeriod,FDebitFor,FDebitForQty,FCreditFor,FCreditForQty,TotalFor,TotalQty)
				SELECT
					B.STypeId,
					B.ATypeId,
					B.Cid,
					B.FYear,
					B.FPeriod,
					SUM(B.FDebitTotalFor) FDebitFor,
					SUM(FDebitQty) FDebitForQty,
					SUM(B.FCreditTotalFor) FCreditFor,
					SUM(FCreditQty) FCreditForQty,
					SUM(CASE WHEN A.Fdc=1 THEN B.FDebitTotalFor-B.FCreditTotalFor ELSE B.FCreditTotalFor-B.FDebitTotalFor END) TotalFor,
					SUM(CASE WHEN A.Fdc=1 THEN B.FDebitQty-B.FCreditQty ELSE B.FCreditQty-B.FDebitQty END) TotalQty
				FROM Ac_Voucher V 
				INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.IfCheck='F' AND V.FChecked<>-1
				INNER JOIN #LineAccount A ON A.StypeId=B.StypeId AND A.TypeId=B.ATypeId
				WHERE 
					(B.FYear<@Fyear 
						OR (B.FYear=@Fyear AND B.FPeriod<=@FPeriodEnd))
					AND ((@Cid NOT IN(0,-1) AND B.Cid=@Cid) OR @Cid IN(0,-1))
				GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod,B.Cid
			END
	END

IF(@IsShowPL=1)--不包含查询期间内结转损益数据
	BEGIN
		IF @Cid=0 OR @Cid=-1--综合本位币
			BEGIN
				INSERT INTO #VoucherBill(STypeId,ATypeId,Cid,FYear,FPeriod,FDebitFor,FDebitForQty,FCreditFor,FCreditForQty,TotalFor,TotalQty)
				SELECT
					B.STypeId,
					B.ATypeId,
					0 Cid,
					B.FYear,
					B.FPeriod,
					-SUM(B.FDebitTotal) FDebitFor,
					-SUM(B.FDebitQty) FDebitForQty,
					-SUM(B.FCreditTotal) FCreditFor,
					-SUM(B.FCreditQty) FCreditForQty,
					-SUM(CASE WHEN A.Fdc=1 THEN B.FDebitTotal-B.FCreditTotal ELSE B.FCreditTotal-B.FDebitTotal END) TotalFor,
					-SUM(CASE WHEN A.Fdc=1 THEN B.FDebitQty-B.FCreditQty ELSE B.FCreditQty-B.FDebitQty END) TotalQty
				FROM Ac_Voucher V 
				INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.FChecked<>-1
				INNER JOIN #LineAccount A ON A.StypeId=B.StypeId AND A.TypeId=B.ATypeId
				WHERE 
					B.FYear=@Fyear
					AND B.FPeriod BETWEEN @FPeriodStart AND @FPeriodEnd
					AND V.VoucherType=2
					AND ((@IsShowNoAccount=0 AND V.IfCheck='T') OR @IsShowNoAccount=1)
				GROUP BY B.STypeId,B.ATypeId,B.FYear,B.FPeriod
			END
		IF @Cid<>0  --具体币种
			BEGIN
				INSERT INTO #VoucherBill(STypeId,ATypeId,Cid,FYear,FPeriod,FDebitFor,FDebitForQty,FCreditFor,FCreditForQty,TotalFor,TotalQty)
				SELECT
					B.STypeId,
					B.ATypeId,
					B.Cid,
					B.FYear,
					B.FPeriod,
					-SUM(FDebitTotalFor) FDebitFor,
					-SUM(FDebitQty) FDebitForQty,
					-SUM(FCreditTotalFor) FCreditFor,
					-SUM(FCreditQty) FCreditForQty,
					-SUM(CASE WHEN A.Fdc=1 THEN B.FDebitTotalFor-B.FCreditTotalFor ELSE B.FCreditTotalFor-B.FDebitTotalFor END) TotalFor,
					-SUM(CASE WHEN A.Fdc=1 THEN B.FDebitQty-B.FCreditQty ELSE B.FCreditQty-B.FDebitQty END) TotalQty
				FROM Ac_Voucher V 
				INNER JOIN Ac_Voucher_Bill B ON B.BillNumberId=V.BillNumberId AND V.FChecked<>-1
				INNER JOIN #LineAccount A ON A.StypeId=B.StypeId AND A.TypeId=B.ATypeId
				WHERE 
					B.FYear=@Fyear
					AND B.FPeriod BETWEEN @FPeriodStart AND @FPeriodEnd
					AND V.VoucherType=2
					AND ((@IsShowNoAccount=0 AND V.IfCheck='T') OR @IsShowNoAccount=1)
					AND ((@Cid NOT IN(0,-1) AND B.Cid=@Cid) OR @Cid IN(0,-1))
				GROUP BY B.STypeId,B.ATypeId,B.Cid,B.FYear,B.FPeriod
			END
	END
--===============================最后统计数据
--期初
UPDATE #Ac_Balance
SET 
	FDebitBeginFor+=CASE WHEN B.Fdc=1 THEN TotalFor ELSE 0 END,
	FDebitBeginForQty+=CASE WHEN B.Fdc=1 THEN TotalQty ELSE 0 END,
	FCreditBeginFor+=CASE WHEN B.Fdc=-1 THEN TotalFor ELSE 0 END,
	FCreditBeginForQty+=CASE WHEN B.Fdc=-1 THEN TotalQty ELSE 0 END
FROM #Ac_Balance B
INNER JOIN (
	SELECT
		STypeId,
		ATypeId,
		Cid,
		SUM(TotalFor) TotalFor,
		SUM(TotalQty) TotalQty
	FROM  #VoucherBill 
	WHERE 
		((FYear<@Fyear) OR (FYear=@Fyear AND FPeriod<@FPeriodStart)) 
	GROUP BY STypeId,ATypeId,Cid
) V ON V.STypeId=B.STypeId AND V.ATypeId=B.ATypeId AND V.Cid=B.Cid 

--本期
UPDATE #Ac_Balance
SET 
	FDebitFor+=ISNULL(V.FDebitFor,0),
	FDebitForQty+=ISNULL(V.FDebitForQty,0),
	FCreditFor+=ISNULL(V.FCreditFor,0),
	FCreditForQty+=ISNULL(V.FCreditForQty,0)
FROM #Ac_Balance B
INNER JOIN (
	SELECT 
		STypeId,
		ATypeId,
		Cid,
		SUM(FDebitFor) FDebitFor,
		SUM(FDebitForQty) FDebitForQty,
		SUM(FCreditFor) FCreditFor,
		SUM(FCreditForQty) FCreditForQty
	FROM  #VoucherBill 
	WHERE 
		FYear=@Fyear
		AND FPeriod BETWEEN @FPeriodStart AND @FPeriodEnd 
	GROUP BY STypeId,ATypeId,Cid
) V ON V.STypeId=B.STypeId AND V.ATypeId=B.ATypeId AND V.Cid=B.Cid 
--本年
UPDATE #Ac_Balance
SET 
	FYtdDebitFor+=ISNULL(V.FDebitFor,0),
	FYtdDebitForQty+=ISNULL(V.FDebitForQty,0),
	FYtdCreditFor+=ISNULL(V.FCreditFor,0),
	FYtdCreditForQty+=ISNULL(V.FCreditForQty,0)
FROM #Ac_Balance B
INNER JOIN (
	SELECT
		STypeId,
		ATypeId,
		Cid,
		SUM(FDebitFor) FDebitFor,
		SUM(FDebitForQty) FDebitForQty,
		SUM(FCreditFor) FCreditFor,
		SUM(FCreditForQty) FCreditForQty
	FROM  #VoucherBill 
	WHERE 
		FYear=@Fyear 
	GROUP BY STypeId,ATypeId,Cid
) V ON V.STypeId=B.STypeId AND V.ATypeId=B.ATypeId AND V.Cid=B.Cid 
--期末
UPDATE #Ac_Balance
SET 
	FDebitEndFor+=CASE WHEN B.Fdc=1 THEN TotalFor ELSE 0 END ,
	FDebitEndForQty+=CASE WHEN B.Fdc=1 THEN TotalQty ELSE 0 END,
	FCreditEndFor+=CASE WHEN B.Fdc=-1 THEN TotalFor ELSE 0 END,
	FCreditEndForQty+=CASE WHEN B.Fdc=-1 THEN TotalQty ELSE 0 END
FROM #Ac_Balance B
INNER JOIN (
	SELECT
		STypeId, 
		ATypeId,
		Cid,
		SUM(TotalFor) TotalFor,
		SUM(TotalQty) TotalQty
	FROM  #VoucherBill
	GROUP BY STypeId,ATypeId,Cid
) V ON V.STypeId=B.STypeId AND V.ATypeId=B.ATypeId AND V.Cid=B.Cid 

--年初
UPDATE #Ac_Balance
SET 
	NCDebitFor+=CASE WHEN B.Fdc=1 THEN TotalFor ELSE 0 END ,
	NCDebitForQty+=CASE WHEN B.Fdc=1 THEN TotalQty ELSE 0 END,
	NCCreditFor+=CASE WHEN B.Fdc=-1 THEN TotalFor ELSE 0 END,
	NCCreditForQty+=CASE WHEN B.Fdc=-1 THEN TotalQty ELSE 0 END
FROM #Ac_Balance B
INNER JOIN (
	SELECT
		STypeId, 
		ATypeId,
		Cid,
		SUM(TotalFor) TotalFor,
		SUM(TotalQty) TotalQty
	FROM  #VoucherBill
	WHERE FYear<@Fyear
	GROUP BY STypeId,ATypeId,Cid
) V ON V.STypeId=B.STypeId AND V.ATypeId=B.ATypeId AND V.Cid=B.Cid 
--========================================业务逻辑处理【BEGIN】  ===============================


--========================返回结果集【BEGIN】===================================
SELECT 
	STypeId,
	ATypeId,
	Fdc,
	Cid,
	SUM(NCDebitFor) NCDebitFor,
	SUM(NCCreditFor) NCCreditFor,
	SUM(FDebitBeginFor) FDebitBeginFor,
	SUM(FCreditBeginFor) FCreditBeginFor,
	SUM(FDebitFor) FDebitFor,
	SUM(FCreditFor) FCreditFor,
	SUM(FYtdDebitFor) FYtdDebitFor,
	SUM(FYtdCreditFor) FYtdCreditFor,
	SUM(FDebitEndFor) FDebitEndFor,
	SUM(FCreditEndFor) FCreditEndFor,
	SUM(NCDebitForQty) NCDebitForQty,
	SUM(NCCreditForQty) NCCreditForQty,
	SUM(FDebitBeginForQty) FDebitBeginForQty,
	SUM(FCreditBeginForQty) FCreditBeginForQty,
	SUM(FDebitForQty) FDebitForQty,
	SUM(FCreditForQty) FCreditForQty,
	SUM(FYtdDebitForQty) FYtdDebitForQty,
	SUM(FYtdCreditForQty) FYtdCreditForQty,
	SUM(FDebitEndForQty) FDebitEndForQty,
	SUM(FCreditEndForQty) FCreditEndForQty
FROM #Ac_Balance 
GROUP BY STypeId,ATypeId,Fdc,Cid
ORDER BY STypeId,ATypeId 
--========================返回结果集【END】	 ===================================


--========================删除临时表【BEGIN】===================================
DROP TABLE #Ac_Balance,#VoucherBill,#LineAccount,#SType
--========================删除临时表【END】  ===================================
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id=object_id(N'Web_QueryAcBalanceType') AND OBJECTPROPERTY(id,N'isProcedure')=1)
	DROP PROC dbo.Web_QueryAcBalanceType
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：查询其他收入信息	
-- 时间：2012-04-18	
-- 作者：古丽娟	
-- 参数:@Deleted是否删除 1：已删除 0 未删除
-- ========================================================================
CREATE PROCEDURE Web_QueryAcBalanceType


--@encode$--
AS
SET NOCOUNT ON 
	SELECT 
		t.BtId,
		t.UserCode,
		t.FullName,
		t.ATypeId,
		'' afullname,
		--a.FullName,
		dbo.Fn_GetIsUse_Items(t.BtId,6) isuse 
	FROM Ac_BalanceType t
	--LEFT JOIN Ac_Account A ON A.TypeId=T.ATypeId
	ORDER BY t.UserCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAcCheckItmes]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAcCheckItmes]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-03-29
	描述：查询辅助核算项目
	EXEC Web_QueryAcCheckItmes
*/
CREATE PROCEDURE Web_QueryAcCheckItmes
(
	@stypeid	VARCHAR(50),
	@atypeid	VARCHAR(50),
	@choice		INT,
	@atid		INT,
	@atdid		INT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @sql VARCHAR(MAX),@V3Flag INT
SET @sql = ''
SET @V3Flag = 2

IF EXISTS(SELECT TOP 1 1  FROM dbo.sysdata WHERE SubName = 'ProInfo' AND SubValue = 1)
	SET @V3Flag = 1

IF @choice = 1--手工选择的科目，按科目自身辅助核算确定
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM dbo.Ac_Account_Assist_CheckItems a INNER JOIN dbo.Ac_Currency b ON a.Cid = b.CId
				 WHERE STypeId = @stypeid AND ATypeId = @atypeid AND b.Sysrow = 1) --如果有本位币的，按本位币取辅助核算
	BEGIN
		SET @sql += ' SELECT	DISTINCT a.AscIds,a.FullName,A.UserCode '
		IF @atdid <> -1
			SET @sql += ',d.nId AS nids,d.FullName AS items '
		SET @sql += ' FROM	Ac_Assist_CheckItems a
					 INNER JOIN Ac_Account_Assist_CheckItems b ON a.AscIds = b.Ascids
					 INNER JOIN dbo.Ac_Currency c ON b.Cid = c.CId '
		IF @atdid <> -1
			SET @sql += 'INNER JOIN dbo.Ac_Assist_CheckItems_BillType d ON a.AscIds = d.AscIds
						INNER JOIN dbo.Ac_Auditing_Template_Detail_Assist_CheckItems e ON d.nId = e.AscIdsDetailId AND e.Atid = '+CAST(@atid AS VARCHAR(1000))+' AND e.AtdId = '+CAST(@atdid AS VARCHAR(1000))
		SET @sql += ' WHERE b.STypeId = '''+@stypeid+''' AND b.ATypeId = '''+@atypeid+''' AND c.Sysrow = 1 AND a.AscIds < 5'
		IF @V3Flag = 1
			SET @sql += 'AND a.AscIds <> 1'
		SET @sql += ' ORDER BY a.UserCode '
		
	END
	ELSE--没有本位币，就只有一种币种的
	BEGIN
		SET @sql += ' SELECT	a.AscIds,a.FullName '
		IF @atdid <> -1
			SET @sql += ',d.nId AS nids,d.FullName AS items '
		SET @sql += ' FROM	Ac_Assist_CheckItems a
					 INNER JOIN Ac_Account_Assist_CheckItems b ON a.AscIds = b.Ascids '
		IF @atdid <> -1
			SET @sql += ' INNER JOIN dbo.Ac_Assist_CheckItems_BillType d ON a.AscIds = d.AscIds
						 INNER JOIN dbo.Ac_Auditing_Template_Detail_Assist_CheckItems e ON d.nId = e.AscIdsDetailId AND e.Atid = '+CAST(@atid AS VARCHAR(1000))+' AND e.AtdId = '+CAST(@atdid AS VARCHAR(1000))
		SET @sql += ' WHERE b.STypeId = '''+@stypeid+''' AND b.ATypeId = '''+@atypeid + ''' AND a.AscIds < 5' 
		IF @V3Flag = 1
			SET @sql += ' AND a.AscIds <> 1 '
		SET @sql += ' ORDER BY a.UserCode '
	END
END
ELSE
BEGIN
	SET @sql += 'SELECT * '
	IF @atdid <> -1
		SET @sql += ',d.nId AS nids,d.FullName AS items '
	SET @sql += ' FROM dbo.Ac_Assist_CheckItems a '
	IF @atdid <> -1
		SET @sql += ' INNER JOIN dbo.Ac_Assist_CheckItems_BillType d ON a.AscIds = d.AscIds
					 INNER JOIN dbo.Ac_Auditing_Template_Detail_Assist_CheckItems e ON d.nId = e.AscIdsDetailId AND e.Atid ='+CAST(@atid AS VARCHAR(1000))+' AND e.AtdId ='+CAST(@atdid AS VARCHAR(1000))
	IF @V3Flag = 1
			SET @sql += 'WHERE a.AscIds <> 1  AND a.AscIds < 5'
	ELSE
		SET @sql += 'WHERE a.AscIds < 5'
	SET @sql += ' ORDER BY UserCode '
END
PRINT @sql
EXEC (@sql)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAcCheckItmes_Mx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAcCheckItmes_Mx]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2012-03-29
	描述：查询辅助核算项目-按单据类型
	DECLARE @F VARCHAR(200),
			@V VARCHAR(200)
			
	EXEC Web_QueryAcCheckItmes_Mx 11,@F OUTPUT,@V OUTPUT
	
	PRINT(@F)
	PRINT(@V)
*/
CREATE PROCEDURE Web_QueryAcCheckItmes_Mx
(
	@ascids			INT,				--辅助核算项目ID
	@BillType		INT,				-- 单据类型
	@inouttype		INT					--资金调拨单特殊处理参数 1.调入 -1.调出 0.其他正常单据
)
--@encode$--
AS
SET NOCOUNT ON
--调拨单分支机构特殊处理，分支机构
IF @ascids='1' AND @BillType='310'
BEGIN
	SELECT	* 
	FROM	Ac_Assist_CheckItems_BillType 
	WHERE	BillType = @BillType 
			AND AscIds = @ascids 
			AND InOutType=@inouttype
	ORDER BY FullName
END
SELECT	* 
FROM	Ac_Assist_CheckItems_BillType 
WHERE	BillType = @BillType 
		AND AscIds = @ascids 
ORDER BY FullName


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAccountAssistItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Web_QueryAccountAssistItems]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	得到当前科目辅助核算列
-- 时间：	2015-10-10
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryAccountAssistItems
(
	@STypeID	VARCHAR(50),	--分支机构
	@ATypeID	VARCHAR(50),	--类型ID
	@IsUsed		BIT				--是否被使用
)

--@encode$--

AS
SET NOCOUNT ON
DECLARE @I	INT=0
	
DECLARE @Temp TABLE(NID INT IDENTITY(1,1),ascids VARCHAR(50),ascidsFullName VARCHAR(200),DefaultTypeId VARCHAR(50),DefaultFullName VARCHAR(50))
--没有使用
IF @IsUsed=0
	BEGIN
		INSERT INTO @Temp(ascids,ascidsFullName,DefaultTypeId,DefaultFullName)
		SELECT 
			I.AscIds,
			I.FullName ascidsFullName,
			'' DefaultTypeId,
			'' DefaultFullName
		FROM Ac_Account_Assist_CheckItems AC
		INNER JOIN Ac_Assist_CheckItems I ON I.AscIds=AC.Ascids AND AC.STypeId=@STypeID AND AC.ATypeId=@ATypeID
		GROUP BY 
			I.AscIds,
			I.FullName
		ORDER BY I.AscIds
		SELECT @I=@@ROWCOUNT
	END
ELSE 
	BEGIN
		SELECT @I=COUNT(*) FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeID AND ATypeId=@ATypeID GROUP BY Cid
	END

WHILE (@I<6)
	BEGIN
		INSERT INTO @Temp(ascids,ascidsFullName,DefaultTypeId,DefaultFullName)
		SELECT 
			'' ascids,
			'' ascidsFullName,
			'' DefaultTypeId,
			'' DefaultFullName
		SET @I+=1
	END
SELECT * FROM @Temp
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_QueryAccountingPeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_QueryAccountingPeriod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/04/19
	Description	: 查询账务期初的科目些
*/

CREATE PROCEDURE WEB_QueryAccountingPeriod
(
	@chvOperatorID	VARCHAR(100),	--操作员id
	@STypeId		VARCHAR(50),	--分支机构id	
	@Cid			INT				--币别id	
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @SelfCid		INT,				--本位币cid
			@SQL            NVARCHAR(MAX),
			@FYear			INT,
			@FPeriod		INT
		
	--如果分支机构未设置启用期间，指定分支机构未00000，出空白数据
	IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND (ISNULL(SFYear,0)=0 OR ISNULL(SFPeriod,0)=0))
		SET @STypeId='0000' 

	SELECT @SelfCid=CID FROM AC_CURRENCY WHERE SYSROW=1 
	SELECT @FYear=SFYear,@FPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId

--========================处理1：往来科目  2：库存科目 3：固定资产科目 ===============================================      
	--最后要查询的临时表
	CREATE TABLE #Account
	(
		STYPEID		VARCHAR(50),     --分支机构ID
		TYPEID		VARCHAR(50),	 --科目ID	
		PARID		VARCHAR(50),	 --父节点ID	
		LEVEAL		INT,			 --层级
		SONNUM		INT,			 --子节点号
		SONCOUNT	INT,			 --子节点数目	
		USERCODE	VARCHAR(200),	 --编码	
		FULLNAME	VARCHAR(200),	 --名称
		FDC			INT,			 --借贷方向
		ACCOUNTCID	INT,			 --该科目在AC_ACCOUNT表中CID的值，如果选择的是“所有币别”，值为0
		ASSISTCID	INT,			 --该科目在AC_ACCOUNT_ASSIST_CHECKITEMS表中CID的值，不可能有为0的情况
		TOTALCOUNT	INT,			 --该科目在AC_ACCOUNT_ASSIST_CHECKITEMS中的数据条数
		ISSUNYI		VARCHAR(10)		 --该科目是否是损益科目
	)
    ---所有符合要求的科目
	CREATE TABLE #temp1
	(
		STYPEID		VARCHAR(50),     --分支机构ID
		TYPEID		VARCHAR(50),	 --科目ID	
		PARID		VARCHAR(50),	 --父节点ID	
		LEVEAL		INT,			 --层级
		SONNUM		INT,			 --子节点号
		SONCOUNT	INT,			 --子节点数目	
		USERCODE	VARCHAR(200),	 --编码	
		FULLNAME	VARCHAR(200),	 --名称
		FDC			INT,			 --借贷方向
		CID		    INT				 --币种
	)

	IF @Cid<>-1                                    
		BEGIN
			SET @SQL=';WITH table1 AS
			(
				SELECT STYPEID,
					   TYPEID,
					   PARID,
					   LEVEAL,
					   SONNUM,
					   SONCOUNT,
					   USERCODE,
					   FULLNAME,
					   FDC,
					   CID  
				FROM Ac_Account 
				WHERE (CID=@Cid OR CID=0 
				'
			IF @SelfCid=@Cid									--本位币
				SET @SQL+=' OR CID=-1)'
			ELSE
				SET @SQL+=')'
			SET @SQL+=   
				' AND SONNUM=0 AND STYPEID=@STypeId AND DELETED=0
				UNION ALL 
				SELECT a.STYPEID,
					   a.TYPEID,
					   a.PARID,
					   a.LEVEAL,
					   a.SONNUM,
					   a.SONCOUNT,
					   a.USERCODE,
					   a.FULLNAME,
					   a.FDC,
					   a.CID  
				FROM Ac_Account a, table1 b
				WHERE a.TYPEID=b.PARID AND 
					  a.STYPEID=b.STYPEID
			)
			INSERT INTO #temp1
			SELECT DISTINCT T.STYPEID,
				   T.TYPEID,
				   PARID,
				   LEVEAL,
				   SONNUM,
				   SONCOUNT,
				   USERCODE,
				   FULLNAME,
				   FDC,
				   CID 
			FROM table1 T
			INNER JOIN F_TreeAccount('''+@chvOperatorID+''','''+@STypeId+''') F ON F.Typeid = T.TYPEID
			WHERE
			(
				T.TYPEID LIKE ''00001%'' OR 
				T.TYPEID LIKE ''00002%'' OR
				T.TYPEID LIKE ''00003%'' OR
				T.TYPEID LIKE ''00004%'' OR
				T.TYPEID LIKE ''00005%'' OR
				T.TYPEID LIKE ''00006%''
			)
			AND T.LEVEAL>1 '
		    
			EXEC sp_executesql @SQL,N'@Cid INT,@STypeId VARCHAR(50)', @Cid,@STypeId
			SET @SQL=''
		
			INSERT INTO #Account
			(
			   STYPEID, 
			   TYPEID, 
			   PARID, 
			   LEVEAL, 
			   SONNUM, 
			   SONCOUNT, 
			   USERCODE, 
			   FULLNAME,
			   FDC,  
			   ACCOUNTCID,
			   ASSISTCID,
			   TOTALCOUNT,
			   ISSUNYI
			)
			SELECT a.STYPEID,
				   a.TYPEID, 
				   PARID, 
				   LEVEAL, 
				   SONNUM, 
				   SONCOUNT, 
				   USERCODE, 
				   FULLNAME,
				   FDC,  
				   a.CID,
				   ASSISTCID,
				   ASSISTCOUNT,
					CASE 
						WHEN SUBSTRING(a.TYPEID,1,5)='00003' THEN 'true' 
						ELSE 'false'
					END
			FROM #temp1 a
			LEFT JOIN 
			(
				SELECT STYPEID, 
					   ATYPEID  AS TYPEID, 
					   CID      AS ASSISTCID, 
					   COUNT(*) AS ASSISTCOUNT 
				FROM Ac_Account_Assist_CheckItems
				WHERE CID=@CID
				GROUP BY STYPEID, ATYPEID, CID
			)	b ON  a.STYPEID=b.STYPEID AND a.TYPEID=b.TYPEID
		END

	----重新生成期初数据表，计算父节点的值
	IF @Cid<>-1
		BEGIN
			CREATE TABLE #AC_INIACCOUNT1
			(
			   STYPEID              VARCHAR(50),          
			   ATYPEID              VARCHAR(50),   
			   INIYTOTAL             NUMERIC(24, 10) ,
			   INIYTOTALFOR          NUMERIC(24, 10) ,
			   FDEBIT                NUMERIC(24, 10) ,
			   FDEBITFOR             NUMERIC(24, 10) ,
			   FCREDIT               NUMERIC(24, 10) ,
			   FCREDITFOR            NUMERIC(24, 10) ,
			   INITOTAL              NUMERIC(24, 10) ,
			   INITOTALFOR           NUMERIC(24, 10) ,
			   FYTOTAL				 NUMERIC(24, 10) ,
			   FYTOTALFOR			 NUMERIC(24, 10) ,
			   CID                  INT,              
			   iniYTotalQty			NUMERIC(24, 10) DEFAULT(0),   
			   FDebitQty			NUMERIC(24, 10) DEFAULT(0),  
			   FCreditQty			NUMERIC(24, 10) DEFAULT(0),  
			   iniTotalQty			NUMERIC(24, 10) DEFAULT(0)
			)

			CREATE TABLE #temp2
			(
			   FATHERID             VARCHAR(50),
			   FATHERFDC			INT,
			   SONID				VARCHAR(50),
			   SONFDC				INT,          
			   INIYTOTAL             NUMERIC(24, 10) ,
			   INIYTOTALFOR          NUMERIC(24, 10) ,
			   FDEBIT                NUMERIC(24, 10) ,
			   FDEBITFOR             NUMERIC(24, 10) ,
			   FCREDIT               NUMERIC(24, 10) ,
			   FCREDITFOR            NUMERIC(24, 10) ,
			   INITOTAL              NUMERIC(24, 10) ,
			   INITOTALFOR           NUMERIC(24, 10) ,
			   FYTOTAL				 NUMERIC(24, 10) ,
			   FYTOTALFOR			 NUMERIC(24, 10) ,
			   CID                  INT,        
			   iniYTotalQty			NUMERIC(24, 10) DEFAULT(0),   
			   FDebitQty			NUMERIC(24, 10) DEFAULT(0),  
			   FCreditQty			NUMERIC(24, 10) DEFAULT(0),  
			   iniTotalQty			NUMERIC(24, 10) DEFAULT(0) 
			)
			INSERT INTO #temp2
			SELECT a.TYPEID AS FATHERID,
				   a.FDC, 
				   b.TYPEID AS SONID,
				   b.FDC,
				   INIYTOTAL,
				   INIYTOTALFOR,
				   FDEBIT,
				   FDEBITFOR,
				   FCREDIT,
				   FCREDITFOR,
				   INITOTAL,
				   INITOTALFOR,
				   FYTOTAL,
				   FYTOTALFOR,
				   @Cid,
				   c.IniYqty iniYTotalQty,
				   c.FDebitqty FDebitQty,
				   c.FCreditqty FCreditQty,
				   c.iniqty iniTotalQty
			FROM #temp1 a
			INNER JOIN dbo.Ac_Account B ON B.StypeId=A.STYPEID AND B.TypeId LIKE A.TYPEID+'%' AND B.Deleted=0 AND B.SonNum=0
			INNER JOIN dbo.Ac_IniAccount C ON C.STypeId=B.StypeId AND C.ATypeId=B.TypeId AND C.FYear=@FYear AND C.FPeriod=@FPeriod AND C.Cid=@Cid
			

			 ;WITH a AS
			 (
				 SELECT FATHERID,
						FATHERFDC,
						SONFDC,
						CID,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INIYTOTAL)
						ELSE -SUM(INIYTOTAL)
					 END AS INIYTOTAL,
					  CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INIYTOTALFOR)
						ELSE -SUM(INIYTOTALFOR)
					 END AS INIYTOTALFOR,
					  CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(iniYTotalQty)
						ELSE -SUM(iniYTotalQty)
					 END AS iniYTotalQty,
					 SUM(FDEBIT)     AS FDEBIT,
					 SUM(FDEBITFOR)  AS FDEBITFOR,
					 SUM(FDebitQty)  AS FDebitQty,
					 SUM(FCREDIT)    AS FCREDIT,
					 SUM(FCREDITFOR) AS FCREDITFOR,
					 SUM(FCreditQty) AS FCreditQty,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INITOTAL)
						ELSE -SUM(INITOTAL)
					 END AS INITOTAL,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INITOTALFOR)
						ELSE -SUM(INITOTALFOR)
					 END AS INITOTALFOR, 
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(iniTotalQty)
						ELSE -SUM(iniTotalQty)
					 END AS iniTotalQty,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(FYTOTAL)
						ELSE -SUM(FYTOTAL)
					 END AS FYTOTAL,
					  CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(FYTOTALFOR)
						ELSE -SUM(FYTOTALFOR)
					 END AS FYTOTALFOR
				 FROM #temp2 a
				 GROUP BY FATHERID,FATHERFDC,SONFDC,cid
			 )
			 INSERT INTO #AC_INIACCOUNT1
			 SELECT @STypeId,
					FATHERID,
					SUM(INIYTOTAL),
					SUM(INIYTOTALFOR),
					SUM(FDEBIT),
					SUM(FDEBITFOR),
					SUM(FCREDIT),
					SUM(FCREDITFOR),
					SUM(INITOTAL),
					SUM(INITOTALFOR),
					SUM(FYTOTAL),
					SUM(FYTOTALFOR),
					CID,
					SUM(iniYTotalQty),
					SUM(FDebitQty),
					SUM(FCreditQty),
					SUM(iniTotalQty)
			 FROM a 
			 GROUP BY a.FATHERID,a.FATHERFDC,a.CID
		 END
		

	----再在临时表中进行查询返回结果
	IF @SelfCid=@Cid  ----记账本位币
		BEGIN    
		SELECT a.STYPEID, 
			   a.TYPEID, 
			   a.PARID, 
			   a.LEVEAL, 
			   a.SONNUM, 
			   a.SONCOUNT, 
			   d.USERCODE, 
			   a.FULLNAME,
			   a.ACCOUNTCID,                                                            --科目cid
			   a.ASSISTCID,																--辅助项目cid
			   a.TOTALCOUNT,															--辅助项目个数
			   a.ISSUNYI,																--该条是否是损益科目
			   b.INIYTOTAL AS nianchu,								     				---年初本币余额
			   b.iniYTotalQty AS nianchuqty,								     		---年初本币数量
			   b.FDEBIT    AS borrow,									         		---本币累计借方数量
			   b.FDebitQty    AS borrowqty,									         	---本币累计借方金额
			   b.FCREDIT   AS lend,								         				---本币累计贷方余额
			   b.FCreditQty   AS lendqty,								         		---本币累计贷方数量
			   b.INITOTAL  AS qichu,											        ---本币期初余额
			   b.iniTotalQty  AS qichuqty,											     ---本币期初数量
			   b.FYTOTAL   AS sunyi,                                                    ---损益类科目本期本币发生额
			   CASE a.FDC 
					WHEN 1 THEN '借' 
					ELSE '贷'
			   END AS NEWFDC,
			CASE WHEN aa.IsBank=1 OR aa.IsCash=1 OR AA.IsOther=1 THEN 1 ELSE 0 END IsBank,
			AA.AdjustAccounts	
		FROM #Account a 
		INNER JOIN Ac_Account AA ON AA.StypeId=A.STYPEID AND AA.TypeId=A.TYPEID
		LEFT JOIN #AC_INIACCOUNT1 b ON a.STYPEID=b.STYPEID AND a.TYPEID=b.ATYPEID AND b.CID=@Cid 
		JOIN F_GetStandard_Ac_Account(@chvOperatorID) d ON a.STYPEID=d.STYPEID AND a.TYPEID=d.TYPEID  
		ORDER BY a.USERCODE
		END
	ELSE IF @Cid=-1                                                                      --综合本位币
		BEGIN
		    -----所有科目保存到#tempFather
			SELECT a.STYPEID,
				   a.TYPEID,
				   FDC
			INTO #tempFather
			FROM AC_ACCOUNT a
			INNER JOIN F_TreeAccount(@chvOperatorID,@STypeId) F ON F.Typeid = A.TypeId
			WHERE
			(
				a.TYPEID LIKE '00001%' OR  --资产
				a.TYPEID LIKE '00002%' OR  --负债
				a.TYPEID LIKE '00003%' OR  --损益
				a.TYPEID LIKE '00004%' OR  --成本
				a.TYPEID LIKE '00005%' OR  --权益
				a.TYPEID LIKE '00006%'     --共同
			)
			AND a.LEVEAL>1
			AND a.STYPEID=@STypeid 
			AND a.DELETED=0
			ORDER BY a.TYPEID
		   
			--取出各个科目对应的数据
			CREATE TABLE #tempData
			(
				FATHERID		VARCHAR(50),
				FATHERFDC		INT,
				SONID			VARCHAR(50),
				SONFDC			INT,          
				INIYTOTAL		NUMERIC(24, 10) ,
				FDEBIT			NUMERIC(24, 10) ,
				FCREDIT			NUMERIC(24, 10) ,
				INITOTAL		NUMERIC(24, 10) ,
				FYTOTAL			NUMERIC(24, 10), 
				iniYTotalQty	NUMERIC(24, 10) DEFAULT(0),   
				FDebitQty		NUMERIC(24, 10) DEFAULT(0),  
				FCreditQty		NUMERIC(24, 10) DEFAULT(0),  
				iniTotalQty		NUMERIC(24, 10) DEFAULT(0) 
			)
			INSERT INTO #tempData 
			SELECT
				a.TYPEID AS FATHERID,
				a.FDC, 
				b.TYPEID AS SONID,
				b.FDC,
				INIYTOTAL,
				FDEBIT,
				FCREDIT,
				INITOTAL,
				FYTOTAL,
				c.IniYqty,
				c.FDebitqty,
				c.FCreditqty,
				c.iniqty
			FROM #tempFather a
			JOIN dbo.Ac_Account b ON a.STYPEID=b.STYPEID AND b.TYPEID LIKE a.TYPEID+'%' AND b.DELETED=0 AND b.SONNUM=0
			LEFT JOIN dbo.Ac_IniAccount c ON b.STYPEID=c.STYPEID AND b.TYPEID=c.ATYPEID AND c.FYEAR=@FYear AND c.FPERIOD=@FPeriod 
		    
		    
		    --统计各个科目的合
			CREATE TABLE #AC_INIACCOUNT2
			(
			   STYPEID              VARCHAR(50),          
			   ATYPEID              VARCHAR(50),          
			   INIYTOTAL             NUMERIC(24, 10) ,
			   FDEBIT                NUMERIC(24, 10) ,
			   FCREDIT               NUMERIC(24, 10) ,
			   INITOTAL              NUMERIC(24, 10) ,
			   FYTOTAL				 NUMERIC(24, 10), 			--损益
			   iniYTotalQty			NUMERIC(24, 10) DEFAULT(0),   
			   FDebitQty			NUMERIC(24, 10) DEFAULT(0),  
			   FCreditQty			NUMERIC(24, 10) DEFAULT(0),  
			   iniTotalQty			NUMERIC(24, 10) DEFAULT(0) 
			)
			 ;WITH a AS
			 (
				 SELECT FATHERID,
						FATHERFDC,
						SONFDC,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INIYTOTAL)
						ELSE -SUM(INIYTOTAL)
					 END AS INIYTOTAL,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(iniYTotalQty)
						ELSE -SUM(iniYTotalQty)
					 END AS iniYTotalQty,
					 SUM(FDEBIT) AS FDEBIT,
					 SUM(FDebitQty) AS FDebitQty,
					 SUM(FCREDIT) AS FCREDIT,
					 SUM(FCreditQty) AS FCreditQty,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INITOTAL)
						ELSE -SUM(INITOTAL)
					 END AS INITOTAL,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(iniTotalQty)
						ELSE -SUM(iniTotalQty)
					 END AS iniTotalQty,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(FYTOTAL)
						ELSE -SUM(FYTOTAL)
					 END AS FYTOTAL 
				 FROM 
					(
						  SELECT FATHERID,
								 FATHERFDC,
								 SONFDC,
								 SONID,
								 SUM(INIYTOTAL) AS INIYTOTAL,
								 SUM(FDEBIT)    AS FDEBIT,
								 SUM(FCREDIT)   AS FCREDIT,
								 SUM(INITOTAL)  AS INITOTAL,
								 SUM(FYTOTAL)   AS FYTOTAL,
								 SUM(iniYTotalQty) iniYTotalQty,
								 SUM(FDebitQty) FDebitQty,
								 SUM(FCreditQty) FCreditQty,
								 SUM(iniTotalQty) iniTotalQty
						  FROM #tempData
						  GROUP BY FATHERID,FATHERFDC,SONFDC,SONID
					) a
				 GROUP BY FATHERID,FATHERFDC,SONFDC
			 )
			 INSERT INTO #AC_INIACCOUNT2(STYPEID,ATYPEID,INIYTOTAL,FDEBIT,FCREDIT,INITOTAL,FYTOTAL,iniYTotalQty,FDebitQty,FCreditQty,iniTotalQty)
			 SELECT @STypeId,
					FATHERID,
					SUM(INIYTOTAL),
					SUM(FDEBIT),
					SUM(FCREDIT),
					SUM(INITOTAL),
					SUM(FYTOTAL),
					SUM(iniYTotalQty),
					SUM(FDebitQty),
					SUM(FCreditQty),
					SUM(iniTotalQty)
			 FROM a 
			 GROUP BY a.FATHERID,a.FATHERFDC
		    
		    
			 ---查询数据
			 SELECT
				A.StypeId,
				A.TypeId,
				A.ParId,
				A.Leveal,
				REPLICATE('    ',A.FLeveal)+A.UserCode UserCode, 
				A.FullName,
				b.INIYTOTAL AS allnianchu,
				b.iniYTotalQty AS allnianchuqty,
				b.FDEBIT    AS allborrow,
				b.FDebitQty    AS allborrowqty,
				b.FCREDIT   AS alllend,
				b.FCreditQty   AS alllendqty,
				b.INITOTAL  AS allqichu,
				b.iniTotalQty  AS allqichuqty,
				b.FYTOTAL   AS allsunyi,
				CASE WHEN a.FDC=1 THEN '借' ELSE '贷' END AS newfdc,
				CASE WHEN a.IsBank=1 OR A.IsCash=1 OR A.IsOther=1 THEN 1 ELSE 0 END IsBank,
				A.AdjustAccounts
			FROM Ac_Account A 
			INNER JOIN #tempFather D ON D.StypeId=A.StypeId AND D.TypeId=A.TypeId
			INNER JOIN #AC_INIACCOUNT2 B ON B.STYPEID=D.StypeId AND B.ATYPEID=D.TypeId
			ORDER BY A.UserCode
		END
	ELSE                                                                              ---按照自己选择的外币来查询
		BEGIN
			SELECT
				a.STYPEID, 
				a.TYPEID, 
				a.PARID, 
				a.LEVEAL, 
				a.SONNUM, 
				a.SONCOUNT, 
				REPLICATE('    ',AA.FLeveal)+A.UserCode UserCode, 
				a.FULLNAME,
				a.ACCOUNTCID,												           
				a.ASSISTCID,     
				a.TOTALCOUNT,
				a.ISSUNYI,
				b.INIYTOTAL    AS selfnianchu,                                    ---年初本币余额
				b.iniYTotalQty AS selfnianchuqty,                              ---年初本币数量
				b.INIYTOTALFOR AS orinianchu,                                     ---年初原币余额
				b.iniYTotalQty AS orinianchuqty,                                     ---年初原币数量
				b.FDEBIT       AS selfborrow,									  ---本币累计借方金额
				b.FDebitQty    AS selfborrowqty,									  ---本币累计借方数量
				b.FDEBITFOR    AS oriborrow,									  ---原币累计借方金额
				b.FDebitQty    AS oriborrowqty,									  ---原币累计借方数量
				b.FCREDIT      AS selflend,							              ---本币累计贷方余额
				b.FCreditQty   AS selflendqty,							              ---本币累计贷方数量
				b.FCREDITFOR   AS orilend,						                  ---原币累计贷方余额
				b.FCreditQty   AS orilendqty,						                  ---原币累计贷方数量
				b.INITOTAL     AS selfqichu,						              ---本币期初余额
				b.iniTotalQty  AS selfqichuqty,						              ---本币期初数量
				b.INITOTALFOR  AS oriqichu,				                		  ---原币期初余额
				b.iniTotalQty  AS oriqichuqty,				                		  ---原币期初数量
				b.FYTOTAL      AS selfsunyi,									  ---损益科目本期本币发生额
				b.FYTOTALFOR   AS orisunyi,
				CASE a.FDC 
				WHEN 1 THEN '借' 
				ELSE '贷'
				END AS NEWFDC,
				CASE WHEN aa.IsBank=1 OR aa.IsCash=1 OR AA.IsOther=1 THEN 1 ELSE 0 END IsBank,
				AA.AdjustAccounts		
			FROM #Account a 
			INNER JOIN Ac_Account AA ON AA.StypeId=A.STYPEID AND AA.TypeId=A.TYPEID
			LEFT JOIN #AC_INIACCOUNT1 b	ON a.STYPEID=b.STYPEID AND a.TYPEID=b.ATYPEID AND b.CID=@Cid 
			ORDER BY a.USERCODE
		END
		
	IF @Cid<>-1
		DROP TABLE #AC_INIACCOUNT1,#temp2
	IF @Cid=-1
		DROP TABLE #tempFather,#tempData,#AC_INIACCOUNT2
	DROP TABLE #Account,#temp1
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_QueryAccountingPeriodAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].WEB_QueryAccountingPeriodAccount
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2013/05/24
	Description	: 查询账务期初的特定科目
*/

CREATE PROCEDURE WEB_QueryAccountingPeriodAccount
(
	@chvOperatorID	VARCHAR(100),     --操作员id
	@STypeId		VARCHAR(50),	  --分支机构id	
	@Cid			INT,			  --币别id	
	@Type			INT
)
--@encode$--
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @SelfCid		INT,				--本位币cid
			@SQL            NVARCHAR(MAX),
			@FYear			VARCHAR(10),
			@FPeriod		VARCHAR(10)
		
	--如果分支机构未设置启用期间，指定分支机构未00000，出空白数据
	IF EXISTS(SELECT TOP 1 1 FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId AND (ISNULL(SFYear,0)=0 OR ISNULL(SFPeriod,0)=0))
		SET @STypeId='0000' 

	SELECT @SelfCid=CID FROM AC_CURRENCY WHERE SYSROW=1 
	SELECT @FYear=SFYear,@FPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId	
	       

	--最后要查询的临时表
	CREATE TABLE #Account
	(
		STYPEID		VARCHAR(50),     --分支机构ID
		TYPEID		VARCHAR(50),	 --科目ID	
		PARID		VARCHAR(50),	 --父节点ID	
		LEVEAL		INT,			 --层级
		SONNUM		INT,			 --子节点号
		SONCOUNT	INT,			 --子节点数目	
		USERCODE	VARCHAR(200),	 --编码	
		FULLNAME	VARCHAR(200),	 --名称
		FDC			INT,			 --借贷方向
		ACCOUNTCID	INT,			 --该科目在AC_ACCOUNT表中CID的值，如果选择的是“所有币别”，值为0
		ASSISTCID	INT,			 --该科目在AC_ACCOUNT_ASSIST_CHECKITEMS表中CID的值，不可能有为0的情况
		TOTALCOUNT	INT,			 --该科目在AC_ACCOUNT_ASSIST_CHECKITEMS中的数据条数
		ISSUNYI		VARCHAR(10)		 --该科目是否是损益科目
	)
    ---所有符合要求的科目
	CREATE TABLE #temp1
	(
		STYPEID		VARCHAR(50),     --分支机构ID
		TYPEID		VARCHAR(50),	 --科目ID	
		PARID		VARCHAR(50),	 --父节点ID	
		LEVEAL		INT,			 --层级
		SONNUM		INT,			 --子节点号
		SONCOUNT	INT,			 --子节点数目	
		USERCODE	VARCHAR(200),	 --编码	
		FULLNAME	VARCHAR(200),	 --名称
		FDC			INT,			 --借贷方向
		CID		    INT				 --币种
	)

	IF @Cid<>-1                                    
		BEGIN
			SET @SQL=';WITH table1 AS
			(
				SELECT STYPEID,
					   TYPEID,
					   PARID,
					   LEVEAL,
					   SONNUM,
					   SONCOUNT,
					   USERCODE,
					   FULLNAME,
					   FDC,
					   CID  
				FROM Ac_Account 
				WHERE (CID=@Cid OR CID=0 
				'
			IF @SelfCid=@Cid									--本位币
				SET @SQL+=' OR CID=-1)'
			ELSE
				SET @SQL+=')'
			SET @SQL+=   
				' AND SONNUM=0 AND STYPEID=@STypeId AND DELETED=0
				UNION ALL 
				SELECT a.STYPEID,
					   a.TYPEID,
					   a.PARID,
					   a.LEVEAL,
					   a.SONNUM,
					   a.SONCOUNT,
					   a.USERCODE,
					   a.FULLNAME,
					   a.FDC,
					   a.CID  
				FROM Ac_Account a, table1 b
				WHERE a.TYPEID=b.PARID AND 
					  a.STYPEID=b.STYPEID
			)
			INSERT INTO #temp1
			SELECT DISTINCT T.STYPEID,
				   T.TYPEID,
				   PARID,
				   LEVEAL,
				   SONNUM,
				   SONCOUNT,
				   USERCODE,
				   FULLNAME,
				   FDC,
				   CID 
			FROM table1 T
			INNER JOIN F_LineAccount('''+@chvOperatorID+''','''+@STypeId+''') F ON F.Typeid = T.TYPEID
			WHERE
			(
				T.TYPEID LIKE ''00001%'' OR 
				T.TYPEID LIKE ''00002%'' OR
				T.TYPEID LIKE ''00003%'' OR
				T.TYPEID LIKE ''00004%'' OR
				T.TYPEID LIKE ''00005%'' OR
				T.TYPEID LIKE ''00006%''
			)
			AND T.LEVEAL>1 '
		    
			EXEC sp_executesql @SQL,N'@Cid INT,@STypeId VARCHAR(50)', @Cid,@STypeId
			SET @SQL=''
		
			INSERT INTO #Account
			(
			   STYPEID, 
			   TYPEID, 
			   PARID, 
			   LEVEAL, 
			   SONNUM, 
			   SONCOUNT, 
			   USERCODE, 
			   FULLNAME,
			   FDC,  
			   ACCOUNTCID,
			   ASSISTCID,
			   TOTALCOUNT,
			   ISSUNYI
			)
			SELECT a.STYPEID,
				   a.TYPEID, 
				   PARID, 
				   LEVEAL, 
				   SONNUM, 
				   SONCOUNT, 
				   USERCODE, 
				   FULLNAME,
				   FDC,  
				   a.CID,
				   ASSISTCID,
				   ASSISTCOUNT,
					CASE 
						WHEN SUBSTRING(a.TYPEID,1,5)='00003' THEN 'true' 
						ELSE 'false'
					END
			FROM #temp1 a
			LEFT JOIN 
			(
				SELECT STYPEID, 
					   ATYPEID  AS TYPEID, 
					   CID      AS ASSISTCID, 
					   COUNT(*) AS ASSISTCOUNT 
				FROM Ac_Account_Assist_CheckItems
				WHERE CID=@CID
				GROUP BY STYPEID, ATYPEID, CID
			)	b ON  a.STYPEID=b.STYPEID AND a.TYPEID=b.TYPEID
		END

	----重新生成期初数据表，计算父节点的值
	IF @Cid<>-1
		BEGIN
			CREATE TABLE #AC_INIACCOUNT1
			(
			   STYPEID              VARCHAR(50),          
			   ATYPEID              VARCHAR(50),          
			   INIYTOTAL             NUMERIC(24, 10) ,
			   INIYTOTALFOR          NUMERIC(24, 10) ,
			   FDEBIT                NUMERIC(24, 10) ,
			   FDEBITFOR             NUMERIC(24, 10) ,
			   FCREDIT               NUMERIC(24, 10) ,
			   FCREDITFOR            NUMERIC(24, 10) ,
			   INITOTAL              NUMERIC(24, 10) ,
			   INITOTALFOR           NUMERIC(24, 10) ,
			   FYTOTAL				 NUMERIC(24, 10) ,
			   FYTOTALFOR			 NUMERIC(24, 10) ,
			   CID                  INT, 
			   iniYTotalQty			NUMERIC(24, 10) DEFAULT(0),   
			   FDebitQty			NUMERIC(24, 10) DEFAULT(0),  
			   FCreditQty			NUMERIC(24, 10) DEFAULT(0),  
			   iniTotalQty			NUMERIC(24, 10) DEFAULT(0)                 
			)

			CREATE TABLE #temp2
			(
			   FATHERID             VARCHAR(50),
			   FATHERFDC			INT,
			   SONID				VARCHAR(50),
			   SONFDC				INT,          
			   INIYTOTAL             NUMERIC(24, 10) ,
			   INIYTOTALFOR          NUMERIC(24, 10) ,
			   FDEBIT                NUMERIC(24, 10) ,
			   FDEBITFOR             NUMERIC(24, 10) ,
			   FCREDIT               NUMERIC(24, 10) ,
			   FCREDITFOR            NUMERIC(24, 10) ,
			   INITOTAL              NUMERIC(24, 10) ,
			   INITOTALFOR           NUMERIC(24, 10) ,
			   FYTOTAL				 NUMERIC(24, 10) ,
			   FYTOTALFOR			 NUMERIC(24, 10) ,
			   CID                  INT, 
			   iniYTotalQty			NUMERIC(24, 10) DEFAULT(0),   
			   FDebitQty			NUMERIC(24, 10) DEFAULT(0),  
			   FCreditQty			NUMERIC(24, 10) DEFAULT(0),  
			   iniTotalQty			NUMERIC(24, 10) DEFAULT(0)        
			)
			INSERT INTO #temp2
			SELECT a.TYPEID AS FATHERID,
				   a.FDC, 
				   b.TYPEID AS SONID,
				   b.FDC,
				   INIYTOTAL,
				   INIYTOTALFOR,
				   FDEBIT,
				   FDEBITFOR,
				   FCREDIT,
				   FCREDITFOR,
				   INITOTAL,
				   INITOTALFOR,
				   FYTOTAL,
				   FYTOTALFOR,
				   @Cid,
				   c.IniYqty iniYTotalQty,
				   c.FDebitqty FDebitQty,
				   c.FCreditqty FCreditQty,
				   c.iniqty iniTotalQty
			FROM #temp1 a
			JOIN dbo.Ac_Account b    ON b.STYPEID=@STypeId AND b.TYPEID LIKE a.TYPEID+'%' AND b.DELETED=0 AND b.SONNUM=0
			JOIN dbo.Ac_IniAccount c ON c.STYPEID=@STypeId AND b.TYPEID=c.ATYPEID AND c.FYEAR=@FYear AND c.FPERIOD=@FPeriod AND c.CID=@Cid

			 ;WITH a AS
			 (
				 SELECT FATHERID,
						FATHERFDC,
						SONFDC,
						CID,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INIYTOTAL)
						ELSE -SUM(INIYTOTAL)
					 END AS INIYTOTAL,
					  CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INIYTOTALFOR)
						ELSE -SUM(INIYTOTALFOR)
					 END AS INIYTOTALFOR,
					  CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(iniYTotalQty)
						ELSE -SUM(iniYTotalQty)
					 END AS iniYTotalQty,
					 SUM(FDEBIT)     AS FDEBIT,
					 SUM(FDEBITFOR)  AS FDEBITFOR,
					 SUM(FDebitQty)  AS FDebitQty,
					 SUM(FCREDIT)    AS FCREDIT,
					 SUM(FCREDITFOR) AS FCREDITFOR,
					 SUM(FCreditQty) AS FCreditQty,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INITOTAL)
						ELSE -SUM(INITOTAL)
					 END AS INITOTAL,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(INITOTALFOR)
						ELSE -SUM(INITOTALFOR)
					 END AS INITOTALFOR,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(iniTotalQty)
						ELSE -SUM(iniTotalQty)
					 END AS iniTotalQty,
					 CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(FYTOTAL)
						ELSE -SUM(FYTOTAL)
					 END AS FYTOTAL,
					  CASE 
						WHEN a.FATHERFDC=a.SONFDC THEN SUM(FYTOTALFOR)
						ELSE -SUM(FYTOTALFOR)
					 END AS FYTOTALFOR
				 FROM #temp2 a
				 GROUP BY FATHERID,FATHERFDC,SONFDC,cid
			 )
			 INSERT INTO #AC_INIACCOUNT1(STYPEID,ATYPEID,INIYTOTAL,INIYTOTALFOR,FDEBIT,FDEBITFOR,FCREDIT,FCREDITFOR,INITOTAL,INITOTALFOR,FYTOTAL,FYTOTALFOR,CID,iniYTotalQty,FDebitQty,FCreditQty,iniTotalQty)
			 SELECT @STypeId,
					FATHERID,
					SUM(INIYTOTAL),
					SUM(INIYTOTALFOR),
					SUM(FDEBIT),
					SUM(FDEBITFOR),
					SUM(FCREDIT),
					SUM(FCREDITFOR),
					SUM(INITOTAL),
					SUM(INITOTALFOR),
					SUM(FYTOTAL),
					SUM(FYTOTALFOR),
					CID,
					SUM(iniYTotalQty),
					SUM(FDebitQty),
					SUM(FCreditQty),
					SUM(iniTotalQty)
			 FROM a 
			 GROUP BY a.FATHERID,a.FATHERFDC,a.CID
		 END
		

	----再在临时表中进行查询返回结果
	IF @SelfCid=@Cid  ----记账本位币
		BEGIN 
			SET @SQL='   
			SELECT a.STYPEID, 
				   a.TYPEID, 
				   a.PARID, 
				   a.LEVEAL, 
				   a.SONNUM, 
				   a.SONCOUNT, 
				   d.USERCODE, 
				   a.FULLNAME,
				   a.ACCOUNTCID,		--科目cid
				   a.ASSISTCID,			--辅助项目cid
				   a.TOTALCOUNT,		--辅助项目个数
				   a.ISSUNYI,			--该条是否是损益科目
				   b.INIYTOTAL AS nianchu,	--年初本币余额
				   b.iniYTotalQty AS nianchuqty,	--年初本币数量
				   b.FDEBIT    AS borrow,	--本币累计借方金额
				   b.FDebitQty    AS borrowqty,	--本币累计借方数量
				   b.FCREDIT   AS lend,	--本币累计贷方余额
				   b.FCreditQty   AS lendqty,	--本币累计贷方数量
				   b.INITOTAL  AS qichu,	--本币期初余额
				   b.iniTotalQty  AS qichuqty,	--本币期初数量
				   b.FYTOTAL   AS sunyi,	--损益类科目本期本币发生额
				   CASE a.FDC 
						WHEN 1 THEN ''借'' 
						ELSE ''贷''
				   END AS NEWFDC,
				   CASE WHEN AA1.IsBank=1 OR AA1.IsCash=1 OR AA1.IsOther=1 THEN 1 ELSE 0 END IsBank		
			FROM #Account a 
			INNER JOIN Ac_Account AA1 ON AA1.StypeId=A.STYPEID AND AA1.TypeId=A.TYPEID
			LEFT JOIN #AC_INIACCOUNT1 b ON a.STYPEID=b.STYPEID AND a.TYPEID=b.ATYPEID AND b.CID=@Cid 
			JOIN (
						SELECT * FROM F_GetStandard_Ac_Account(@chvOperatorID)
					 ) d ON a.STYPEID=d.STYPEID AND a.TYPEID=d.TYPEID'
			IF @Type=1    --gc
				BEGIN
					SET @SQL=@SQL+' JOIN AC_ACCOUNT aa ON a.STYPEID=aa.STYPEID AND a.TYPEID=aa.TYPEID AND aa.FCONTACT=1 ORDER BY a.USERCODE'
					EXEC sp_executesql @SQL,N'@Cid INT,@chvOperatorID VARCHAR(100)', @Cid,@chvOperatorID
				END
			ELSE IF @Type=2   --stock
				BEGIN
					SET @SQL=@SQL+' WHERE a.TYPEID IN (SELECT ATYPEID4 FROM dbo.STYPE WHERE TYPEID=@STYPEID) ORDER BY a.USERCODE'
					EXEC sp_executesql @SQL,N'@Cid INT,@chvOperatorID VARCHAR(100),@STYPEID VARCHAR(50)', @Cid,@chvOperatorID,@STYPEID
				END
			ELSE IF @Type=3   --assets
				BEGIN
					SET @SQL=@SQL+' WHERE a.TYPEID IN (SELECT ac.AssertATypeId FROM AC_ASSETSCARDS ac 
														JOIN Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STYPEID
													  UNION   
													  SELECT ac.DepATypeId FROM AC_ASSETSCARDS ac 
														JOIN Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STYPEID
													  UNION 
													  SELECT ac.DevalueATypeId FROM AC_ASSETSCARDS ac 
														JOIN Ac_AssetsCategory aac ON ac.CategoryId=aac.Id AND aac.StypeId=@STYPEID) 
									ORDER BY a.USERCODE'
					EXEC sp_executesql @SQL,N'@Cid INT,@chvOperatorID VARCHAR(100),@STYPEID VARCHAR(50)', @Cid,@chvOperatorID,@STYPEID
				END
		END
	ELSE                                                                              ---按照自己选择的外币来查询,外币只有gc才有,type=2|3都是多余的
		BEGIN
			SET @SQL='
		   SELECT   a.STYPEID, 
					a.TYPEID, 
					a.PARID, 
					a.LEVEAL, 
					a.SONNUM, 
					a.SONCOUNT, 
					d.USERCODE, 
					a.FULLNAME,
					a.ACCOUNTCID,												           
					a.ASSISTCID,     
					a.TOTALCOUNT,
					a.ISSUNYI,
					b.INIYTOTAL    AS selfnianchu,                                    --年初本币余额
					b.iniYTotalQty AS selfnianchuqty,                                 --年初本币余额
					b.INIYTOTALFOR AS orinianchu,                                     --年初原币余额
					b.iniYTotalQty AS orinianchuqty,                                  --年初原币余额
					b.FDEBIT       AS selfborrow,									  --本币累计借方金额
					b.FDebitQty    AS selfborrowqty,								  --本币累计借方金额
					b.FDEBITFOR    AS oriborrow,									  --原币累计借方金额
					b.FDebitQty    AS oriborrowqty,									  --原币累计借方金额
					b.FCREDIT      AS selflend,							              --本币累计贷方余额
					b.FCreditQty   AS selflendqty,							          --本币累计贷方余额
					b.FCREDITFOR   AS orilend,						                  --原币累计贷方余额
					b.FCreditQty   AS orilendqty,						              --原币累计贷方余额
					b.INITOTAL     AS selfqichu,						              --本币期初余额
					b.iniTotalQty  AS selfqichuqty,						              --本币期初余额
					b.INITOTALFOR  AS oriqichu,				                		  --原币期初余额
					b.iniTotalQty  AS oriqichuqty,				                	   ---原币期初余额
					b.FYTOTAL      AS selfsunyi,									  ---损益科目本期本币发生额
					b.FYTOTALFOR   AS orisunyi,
					CASE a.FDC 
						WHEN 1 THEN ''借'' 
						ELSE ''贷''
					END AS NEWFDC,
					CASE WHEN AA1.IsBank=1 OR AA1.IsCash=1 OR AA1.IsOther=1 THEN 1 ELSE 0 END IsBank	
			FROM #Account a
			INNER JOIN Ac_Account AA1 ON AA1.StypeId=A.STYPEID AND AA1.TypeId=A.TYPEID 
			LEFT JOIN #AC_INIACCOUNT1 b	ON a.STYPEID=b.STYPEID AND a.TYPEID=b.ATYPEID AND b.CID=@Cid 
			JOIN (
					SELECT * FROM F_GetStandard_Ac_Account(@chvOperatorID)
				 ) d ON a.STYPEID=d.STYPEID AND a.TYPEID=d.TYPEID'
			IF @Type=1    --gc
				BEGIN
					SET @SQL=@SQL+' JOIN AC_ACCOUNT aa ON a.STYPEID=aa.STYPEID AND a.TYPEID=aa.TYPEID AND aa.FCONTACT=1 ORDER BY a.USERCODE'
					EXEC sp_executesql @SQL,N'@Cid INT,@chvOperatorID VARCHAR(100)', @Cid,@chvOperatorID
				END
			ELSE IF @Type=2   --stock
				BEGIN
					SET @SQL=@SQL+' WHERE a.TYPEID IN (SELECT ATYPEID4 FROM dbo.STYPE WHERE TYPEID=@STYPEID) ORDER BY a.USERCODE'
					EXEC sp_executesql @SQL,N'@Cid INT,@chvOperatorID VARCHAR(100),@STYPEID VARCHAR(50)', @Cid,@chvOperatorID,@STYPEID
				END
		END
	
	IF @Cid<>-1
		DROP TABLE #AC_INIACCOUNT1,#temp2
	DROP TABLE #Account,#temp1
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAccountSale]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAccountSale]
GO



/*
功能：销售、采购对账单查询
作者：卢春 2009-01-05
*/
CREATE                         PROCEDURE Web_QueryAccountSale (
	@OperatorID	varchar(100),	-- 操作员ID
	@chvStartDate	varchar(50),	-- 开始时间
	@chvEndDate	varchar(50),	-- 结束时间
	@chvBTypeID	varchar(100),	-- 往来单位ID
	@chvETypeID	varchar(100),	-- 职员ID
	@chvDTypeID	varchar(100),	-- 部门ID
	--@chvQueryType	varchar(10),	-- 报表查询方式；Sale - 销售对账，Buy - 采购对账
	@chrjsStyle	char(1),	-- 结算方式；1 - 全部，2 - 无，3 - 按单结算，4 - 按商品结算
	@chrjsState	char(1),	-- 结算状态；1 - 全部，2 - 未结算，3 - 未完成结算，4 - 结算完成
	@chvSelBill	varchar(500)	-- 选择统计的单据类型，BillType由逗号分隔，如：11,305,45
					-- Sale：销售出库、销售退货、销售换货、零售、委托代销结算
					-- Buy：采购入库、采购退货、采购换货、受托代销结算
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId varchar(50), @MBTypeid varchar(50), @MBTypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(100),@MDtypeid varchar(100)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT

IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
--处理部门ID信息
IF @chvDTypeID='00000'
	SET @chvDTypeID = '%'
DECLARE @chvSQL varchar(8000),@chvSQLWhere varchar(2000),@chvSQLWhere1 varchar(2000),@chvSQLBType varchar(600)
IF @chvBTypeID = '00000'	-- 客户供货商统一
	SELECT @chvSQLBType = 'AND (bil.BTypeID LIKE '''+@MBTypeid+'%'' OR bil.BTypeID LIKE '''+@MBTypeid2+'%'')'
ELSE IF LEFT( @chvBTypeID,5) = '00002'	-- 供货商
	SELECT @chvSQLBType = 'AND bil.BTypeID LIKE '''+@chvBTypeID + '%'' AND bil.BTypeID LIKE '''+@MBTypeid2+'%'''
ELSE	-- 客户
	SELECT @chvSQLBType = 'AND bil.BTypeID LIKE '''+@chvBTypeID + '%'' AND bil.BTypeID LIKE '''+@MBTypeid+'%'''

SET @chvSQL = '
SELECT	bil.BillNumberID,
	bil.BillDate,
	bil.BillType,
	bil.BillCode,
	b.FullName AS bFullName,
	e.FullName AS eFullName,
	d.FullName AS dFullName,
	bil.TotalQty,
	bil.TotalMoney,
	bil.Preferencemoney,
	CASE	WHEN bil.CompleteTotal = 0 AND bil.TotalInMoney = 0 AND c.IsGood IS NULL THEN ''无''
		WHEN ((bil.CompleteTotal <> 0 OR bil.TotalInMoney <> 0) AND ISNULL(c.CompleteGoodQty,0) = 0 AND ISNULL(c.IsGood,0) = 0) OR (bil.BillType IN (160,161) AND ISNULL(c.IsGood,0) = 0) THEN ''按单结算''
		WHEN (bil.CompleteTotal <> 0 AND (ISNULL(c.CompleteGoodQty,0) <> 0 OR c.IsGood = 1)) OR (bil.BillType IN (160,161) AND c.IsGood = 1) THEN ''按商品结算''
		ELSE ''''
	END AS jsStyle,
	CASE	WHEN bil.CompleteTotal = 0 AND bil.TotalInMoney = 0 AND ((bil.TotalMoney>=0 AND bil.TotalMoney-bil.Preferencemoney>0) OR (bil.TotalMoney<0 AND bil.TotalMoney-bil.Preferencemoney<0)) AND c.IsGood IS NULL THEN ''未结算''
		WHEN (bil.TotalMoney>=0 AND (bil.TotalMoney-bil.Preferencemoney) > (bil.CompleteTotal+bil.TotalInMoney) AND c.IsGood <> 1) OR (bil.TotalMoney<0 AND (bil.TotalMoney-bil.Preferencemoney) < (bil.CompleteTotal+bil.TotalInMoney) AND c.IsGood <> 1) OR (bil.BillType IN (160,161) AND c.IsGood = 1 AND ISNULL(c.CompleteGoodQty,0) <> bil.TotalQty AND (bil.TotalMoney-bil.Preferencemoney) <> (bil.CompleteTotal+bil.TotalInMoney)) THEN ''未完成结算''
		WHEN (bil.TotalMoney>=0 AND (bil.TotalMoney-bil.Preferencemoney) <= (bil.CompleteTotal+bil.TotalInMoney)) OR (bil.TotalMoney<0 AND (bil.TotalMoney-bil.Preferencemoney) >= (bil.CompleteTotal+bil.TotalInMoney)) THEN ''结算完成''
		ELSE ''''
	END AS jsState,
	bil.CompleteTotal + bil.TotalInMoney AS CompleteTotal,
	ISNULL(c.CompleteGoodQty,0) AS CompleteGoodQty
FROM	BillIndex bil
LEFT JOIN (
	SELECT	a.GoodsBillID,
		SUM(a.CompleteTotal) AS CompleteTotal,
		SUM(b.CompleteGoodQty) AS CompleteGoodQty,
		SUM(ISNULL(b.IsGood,0)) AS IsGood

	FROM	CompleteTotal a
	LEFT JOIN (
		SELECT	GoodsBillID,
			MoneyBillID,
			ISNULL(SUM(CompleteGoodQty),0) AS CompleteGoodQty,
			1 AS IsGood
		FROM	CompleteGoodTotal
		WHERE	Draft = 0
		GROUP BY GoodsBillID,MoneyBillID) b ON a.GoodsBillID = b.GoodsBillID AND a.MoneyBillID = b.MoneyBillID
	WHERE	a.Draft = 0
	GROUP BY a.GoodsBillID
) c ON bil.BillNumberID = c.GoodsBillID
LEFT JOIN BType b ON bil.BTypeID = b.TypeID
LEFT JOIN Employee e ON bil.ETypeID = e.TypeID
LEFT JOIN Department d ON bil.DTypeID = d.TypeID
WHERE	bil.Draft = 0 AND bil.RedWord = 0 AND bil.ifCheck = ''t''
	AND bil.BillDate >= '''+@chvStartDate+''' AND bil.BillDate <= '''+@chvEndDate+'''
	AND bil.BillType IN ('+@chvSelBill+')
	'+@chvSQLBType+'
	AND bil.ETypeID LIKE '''+@chvETypeID+'%'' AND bil.ETypeID LIKE '''+@MEtypeid+'%''
	AND bil.DTypeID LIKE '''+@chvDTypeID+'%'' AND bil.DTypeID LIKE '''+@MDtypeid+'%'''

-- 结算方式
SET @chvSQLWhere = CASE @chrjsStyle WHEN '1' THEN ''	-- 全部
		WHEN '2' THEN ' AND bil.CompleteTotal = 0 AND bil.TotalInMoney = 0 AND c.IsGood IS NULL'	-- 无
		WHEN '3' THEN ' AND (((bil.CompleteTotal <> 0 OR bil.TotalInMoney <> 0) AND ISNULL(c.CompleteGoodQty,0) = 0 AND ISNULL(c.IsGood,0) = 0) OR (bil.BillType IN (160,161) AND c.IsGood = 0))'	-- 按单结算
		WHEN '4' THEN ' AND ((bil.CompleteTotal <> 0 AND (ISNULL(c.CompleteGoodQty,0) <> 0 OR c.IsGood = 1)) OR (bil.BillType IN (160,161) AND c.IsGood = 1))'	-- 按商品结算
		ELSE '' END
-- 结算状态
--IF @chrjsStyle = '2' SET @chrjsState = '1'
SET @chvSQLWhere1 = CASE @chrjsState WHEN '1' THEN ''	-- 全部
		WHEN '2' THEN ' AND bil.CompleteTotal = 0 AND bil.TotalInMoney = 0 AND ((bil.TotalMoney>=0 AND bil.TotalMoney-bil.Preferencemoney>0) OR (bil.TotalMoney<0 AND bil.TotalMoney-bil.Preferencemoney<0)) AND c.IsGood IS NULL'	-- 未结算
		WHEN '3' THEN ' AND ((bil.CompleteTotal+bil.TotalInMoney) <> 0 AND ((bil.TotalMoney>=0 AND (bil.TotalMoney-bil.Preferencemoney) > (bil.CompleteTotal+bil.TotalInMoney)) OR (bil.TotalMoney<0 AND (bil.TotalMoney-bil.Preferencemoney) < (bil.CompleteTotal+bil.TotalInMoney)) OR (bil.BillType IN (160,161) AND ISNULL(c.CompleteGoodQty,0)<>0 AND ISNULL(c.CompleteGoodQty,0) <> bil.TotalQty AND (bil.TotalMoney-bil.Preferencemoney) <> (bil.CompleteTotal+bil.TotalInMoney))) OR (bil.BillType IN (160,161) AND c.IsGood=1 AND (bil.TotalMoney-bil.Preferencemoney)<>(bil.CompleteTotal+bil.TotalInMoney)))'	-- 未完成结算
		WHEN '4' THEN ' AND ((ISNULL(c.IsGood,0) = 0 AND bil.TotalMoney>=0 AND (bil.TotalMoney-bil.Preferencemoney) <= (bil.CompleteTotal+bil.TotalInMoney)) OR (ISNULL(c.IsGood,0) = 0 AND bil.TotalMoney<0 AND (bil.TotalMoney-bil.Preferencemoney) >= (bil.CompleteTotal+bil.TotalInMoney)) OR (ISNULL(c.IsGood,0) <> 0 AND (bil.TotalMoney-bil.Preferencemoney)=(bil.CompleteTotal+bil.TotalInMoney)))'	-- 结算完成
		ELSE '' END

SET @chvSQL = '
SELECT	b.BillNumberID,
		b.BillDate,
		b.BillType,
		b.BillCode,
		b.bFullName,
		b.eFullName,
		b.dFullName,
		CASE WHEN b.BillType IN (45,6) THEN -b.TotalQty ELSE b.TotalQty END AS TotalQty,
		CASE WHEN b.BillType IN (45,6) THEN -b.TotalMoney ELSE b.TotalMoney END AS TotalMoney,
		CASE WHEN b.BillType IN (45,6) THEN -b.Preferencemoney ELSE b.Preferencemoney END AS Preferencemoney,
		b.jsStyle,
		b.jsState,
		CASE WHEN b.BillType IN (45,6) THEN -b.CompleteTotal ELSE b.CompleteTotal END AS CompleteTotal,
		b.CompleteGoodQty,
		CASE WHEN b.BillType IN (45,6) THEN -b.NoCompleteGoodQty ELSE b.NoCompleteGoodQty END AS NoCompleteGoodQty,
		CASE WHEN b.BillType IN (45,6) THEN -b.NoCompleteTotal ELSE b.NoCompleteTotal END AS NoCompleteTotal
FROM (
	SELECT	a.BillNumberID,
			a.BillDate,
			a.BillType,
			a.BillCode,
			a.bFullName,
			a.eFullName,
			a.dFullName,
			a.TotalQty,
			a.TotalMoney,
			a.Preferencemoney,
			a.jsStyle,
			a.jsState,
			a.CompleteTotal,
			CASE WHEN a.jsState = ''结算完成'' THEN CASE WHEN a.BillType IN (45,6) THEN -a.TotalQty ELSE a.TotalQty END
			ELSE a.CompleteGoodQty END AS CompleteGoodQty,
			CASE WHEN a.jsState = ''结算完成'' THEN 0
			WHEN a.BillType IN (45,6) THEN a.TotalQty+a.CompleteGoodQty
			ELSE a.TotalQty-a.CompleteGoodQty END AS NoCompleteGoodQty,
			CASE WHEN a.jsState = ''结算完成'' THEN 0
			ELSE a.TotalMoney-a.Preferencemoney-a.CompleteTotal END AS NoCompleteTotal
	FROM (' + @chvSQL + @chvSQLWhere + @chvSQLWhere1+ ') a
) b ORDER BY b.BillDate DESC,b.BillType,b.BillCode'
--print @chvSQL
EXEC(@chvSQL)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAccountSaleNew]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAccountSaleNew]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
功能：销售、采购对账单查询
作者：卢春 2009-01-05

日期:2012-06-08
作者:覃雨翔
描述:9.0版本修改

修改：舒珊
日期：2016年2月25日
描述：增添表头自定义显示字段
*/
CREATE PROCEDURE Web_QueryAccountSaleNew 
(
	@OperatorID	VARCHAR(100),	-- 操作员ID
	@StartDate	VARCHAR(50),    -- 开始时间
	@EndDate	VARCHAR(50),	-- 结束时间
	@BTypeID	VARCHAR(8000),	-- 往来单位ID
	@ETypeID	VARCHAR(8000),	-- 职员ID
	@DTypeID	VARCHAR(8000),	-- 部门ID
	@STypeID	VARCHAR(8000),	-- 分支机构
	@chrjsStyle	CHAR(1),		-- 结算方式；9 - 全部，0 - 无，1 - 按单结算，2 - 按商品结算，3-按品牌结算
	@chrjsState	CHAR(1),		-- 结算状态；9 - 全部，0 - 未结算，1 - 未完成结算，2 - 结算完成，3-按品牌结算
	@chvSelBill	VARCHAR(500),	-- 选择统计的单据类型，BillType由逗号分隔，如：11,305,45
								-- Sale：销售出库、销售退货、销售换货、零售、委托代销结算
								-- Buy：采购入库、采购退货、采购换货、受托代销结算
	@CID        INT=0,          --币别选择，默认为0表示所有币种
	@IncludeQc  INT=0,           --默认为0表示不包含期初单据
	@IsSale		INT				--0 销售
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--处理部门ID信息
CREATE TABLE #DType(TypeId VARCHAR(100))
INSERT INTO #DType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--单位：
CREATE TABLE #GetSelBTypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S

--职员：
CREATE TABLE #GetSelETypeId(TypeId VARCHAR(100))
INSERT INTO #GetSelETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--仓库：
CREATE TABLE #GetManKTypeId(TypeId VARCHAR(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID) S
DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))	
INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')
INSERT INTO #GetManKTypeId(TypeId)VALUES('')

DECLARE @chvSQL 		VARCHAR(8000),
		@chvSQLWhere 	VARCHAR(2000),
		@chvSQLWhere1 	VARCHAR(2000),
		@chvSQLBType    VARCHAR(600),
		@CIDWhere       VARCHAR(MAX)

IF @CID<>0
  BEGIN
       SET @CIDWhere=' AND bil.CID='+CONVERT(VARCHAR,@CID)
  END
ELSE
  BEGIN
       SET @CIDWhere=''
  END


SET @chvSQL = '
SELECT	bil.BillNumberID,
		bil.BillDate,
		bil.BillType,
		bil.BillCode,
		bil.btypeid AS bFullName,
		bil.etypeid AS eFullName,
		bil.dtypeid AS dFullName,
		bil.dealbtypeid as dealbfullname,
		bil.STypeId,
		CASE 
			WHEN Bil.BillType IN (12,46) THEN C.Qty
			ELSE bil.TotalQty
		END AS TotalQty,
		bil.TotalMoney,
		bil.NTotalMoney,
		bil.Preferencemoney,
		bil.NPreferencemoney,
		CASE WHEN bil.jsStyle = ''0'' THEN ''无''
			WHEN bil.jsStyle = ''1'' THEN ''按单结算''
			WHEN bil.jsStyle = ''2'' THEN ''按商品结算''
			WHEN bil.jsStyle = ''3'' THEN ''按品牌结算''
			ELSE ''''
		END AS jsStyle,
		CASE WHEN bil.jsState = ''0'' THEN ''未结算''
			WHEN bil.jsState = ''1'' THEN ''未完成结算''
			WHEN bil.jsState = ''2'' THEN ''结算完成''
			ELSE ''''
		END AS jsState,
		bil.CompleteTotal + bil.TotalInMoney AS CompleteTotal,
		bil.NCompleteTotal + bil.NTotalInMoney AS NCompleteTotal,
		ISNULL(c.CompleteGoodQty,0) AS CompleteGoodQty,
		bil.comment,
		AC.FullName AS cfullname,
		AC.rate,
		bil.ChargeOffTotal,
		bil.nChargeOffTotal
FROM	BillIndex bil 
INNER JOIN AC_currency AC ON Bil.CID=AC.CID '

IF NOT (@BTypeId = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @chvSQL = @chvSQL + ' INNER JOIN #GetSelBTypeId B ON Bil.BTypeId = B.TypeId'

IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
	SET @chvSQL = @chvSQL + ' INNER JOIN #GetSelETypeId E ON Bil.ETypeId = E.TypeId'

IF NOT @DTypeId = '00000'
	SET @chvSQL = @chvSQL + ' INNER JOIN #DType D ON Bil.DTypeId = D.TypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @chvSQL = @chvSQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '		

DECLARE @isiniWhere VARCHAR(1000)
SET @isiniWhere=''
IF @IncludeQc=1
  BEGIN
       SET @isiniWhere=' OR bil.isini=1 '
  END
ELSE
  BEGIN
       SET @isiniWhere=' AND bil.isini<>1 '
  END

--------------------------

CREATE TABLE #Billnum
(
 BillNumberID         NUMERIC(18,0),
 billtype             INT
)
DECLARE @sqltemp VARCHAR(8000)=''
SET @sqltemp ='INSERT INTO #Billnum 
SELECT BillNumberId,BillType FROM BillIndex bil
WHERE	bil.BillDate >= '''+@StartDate+''' 
		AND bil.BillDate <= '''+@EndDate+'''
		AND bil.BillType IN ('+@chvSelBill+')
		AND ((bil.RedWord = 0 AND bil.Draft=0)'+@isiniWhere+') 
		AND (
				(
					Bil.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bil.BillType NOT IN (160,161)
				)OR(
					(Bil.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bil.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND Bil.BillType IN (160,161)
				)				
			) '+@CIDWhere
EXEC (@sqltemp)
--发票数据
SET @sqltemp ='INSERT INTO #Billnum 
SELECT BillNumberId,BillType FROM ReceiptBillIndex bil
WHERE	bil.BillDate >= '''+@StartDate+''' 
		AND bil.BillDate <= '''+@EndDate+'''
		AND bil.BillType IN ('+@chvSelBill+')
		AND ((bil.RedWord = 0 AND bil.Draft=0)'+@isiniWhere+')  '+@CIDWhere
EXEC (@sqltemp)

CREATE TABLE #BillName  (Billtype INT)
INSERT INTO #BillName SELECT A FROM DBO.f_split(@chvSelBill,',')

CREATE TABLE #BillDetails
(
	 BillNumberID          NUMERIC(24, 0) ,
	 billtype			   INT,
	 Qty				   NUMERIC(24, 10) DEFAULT(0),
	 CompleteGoodQty       NUMERIC(24, 10),
	 InvoiceCostTotal      NUMERIC(24, 10) 
)

INSERT #BillDetails
(
	 BillNumberID,
	 billtype,
	 Qty,
	 CompleteGoodQty
)
SELECT top 1 billnumberid,1,0,CompleteQTY  FROM  Buybill WHERE billnumberid=-1
	
--EXEC WEB_GetBillDetailAll @billtype=@chvSelBill
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 11)
	INSERT INTO #BillDetails
	        ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,11,0,ISNULL(SUM(CompleteQTY),0)
	FROM salebill
	WHERE BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 11 )
	GROUP BY BillNumberID

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 45)
	INSERT INTO #BillDetails
	       ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,45,0,ISNULL(SUM(-CompleteQTY),0)
	FROM salebackbill
	WHERE BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 45 )
	GROUP BY BillNumberID
	

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 12)
	INSERT INTO #BillDetails(BillNumberID,billtype,Qty,CompleteGoodQty)
	SELECT	BillNumberID,
			12,
			ISNULL(SUM(QTY),0) AS QTY,
			ISNULL(SUM(CompleteQTY),0)
	FROM	dbo.PT_Combin_SaleBill
	WHERE	BillNumberId IN (	
								SELECT	BillNumberId
								FROM    #Billnum
								WHERE   BillType = 12 
							)
	GROUP BY BillNumberID

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 46)
	INSERT INTO #BillDetails
	       ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,46,ISNULL(SUM(QTY),0) AS QTY,ISNULL(SUM(-CompleteQTY),0)
	FROM dbo.PT_Combin_SaleBackBill
	WHERE BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 46 )
	GROUP BY BillNumberID

--添加零售退货单,结算数量是0，我也不知道为啥
--改了结算数量,bug2403
IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 215)
	INSERT INTO #BillDetails
	       ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,215,0,ISNULL(SUM(-CompleteQTY),0)
	FROM RetailBackBill
	WHERE BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 215 )
	GROUP BY BillNumberID

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 160)
	INSERT INTO #BillDetails
	         ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,160,0,ISNULL(
	SUM(
			CASE WHEN InOrOut='O' THEN CompleteQTY
				 ELSE -CompleteQTY END
	   )
	,0)
	FROM salegoodsexchangebill
	WHERE  BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 160 )
	GROUP BY BillNumberID

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 141)
	INSERT INTO #BillDetails
	        ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,141,0,ISNULL(SUM(CompleteQTY),0)
	FROM commissionbill
	WHERE Type='141' AND BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 141 )
	GROUP BY BillNumberID

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 305)
	INSERT INTO #BillDetails
	       ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,305,0,0
	FROM retailbill
	WHERE	BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 305 )
	GROUP BY BillNumberID			

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 34)
	INSERT INTO #BillDetails
	       ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,34,0,ISNULL(SUM(CompleteQTY),0)
	FROM Buybill
	WHERE BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 34 )
	GROUP BY BillNumberID

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 6)
	INSERT INTO #BillDetails
	        ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,6,0,ISNULL(SUM(-CompleteQTY),0)
	FROM buybackbill
	WHERE BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 6 )
	GROUP BY BillNumberID


IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 161)
	INSERT INTO #BillDetails
	       ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,161,0,ISNULL(
	SUM(
			CASE WHEN InOrOut='O' THEN -CompleteQTY
				 ELSE CompleteQTY END
	   )
	,0)
	FROM buygoodsexchangebill
	WHERE BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 161 )
	GROUP BY BillNumberID

IF EXISTS (SELECT Billtype FROM #billName WHERE Billtype = 145)
	INSERT INTO #BillDetails
	        ( BillNumberID,billtype,Qty,CompleteGoodQty )
	SELECT BillNumberID,145,0,ISNULL(SUM(CompleteQTY),0)
	FROM commissionbill
	WHERE Type='145' AND BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #Billnum
                                      WHERE     BillType = 145 )
	GROUP BY BillNumberID	

	INSERT INTO #BillDetails
	        ( BillNumberID,billtype, Qty,CompleteGoodQty,InvoiceCostTotal )
	SELECT a.BillNumberID,a.BillType,0,ISNULL(SUM(CompleteQTY),0),SUM( InvoiceCostTotal) AS InvoiceCostTotal
	FROM ReceiptBill a ,#Billnum b
	WHERE  a.BillNumberID=b.BillNumberID  and a.BillType=b.billtype
	GROUP BY a.BillNumberID	,a.billtype

----------------------------------

--数据源需要修改为web_getbilldetialall
SET @chvSQL = @chvSQL+ '
LEFT JOIN #BillDetails c ON bil.BillNumberID = c.BillNumberID and bil.billtype=c.billtype
WHERE	bil.BillDate >= '''+@StartDate+''' 
		AND bil.BillDate <= '''+@EndDate+'''
		AND bil.BillType IN ('+@chvSelBill+')
		AND ((bil.RedWord = 0 AND bil.Draft=0)'+@isiniWhere+') 
		AND (
				(
					Bil.KTypeId IN (SELECT * FROM #GetManKTypeId) AND Bil.BillType NOT IN (160,161)
				)OR(
					(Bil.KTypeId IN (SELECT * FROM #GetManKTypeId) OR Bil.KTypeId2 IN (SELECT * FROM #GetManKTypeId)) AND Bil.BillType IN (160,161)
				)				
			) '+@CIDWhere

-- 结算方式
SET @chvSQLWhere = CASE @chrjsStyle WHEN '9' THEN ''	-- 全部
		WHEN '0' THEN ' AND bil.jsStyle = ''0'''	-- 无
		WHEN '1' THEN ' AND bil.jsStyle = ''1'''	-- 按单结算
		WHEN '2' THEN ' AND bil.jsStyle = ''2'''	-- 按商品结算
		WHEN '3' THEN ' AND bil.jsStyle = ''3'''    --按品牌结算
		ELSE '' END

--SELECT @chvSQLWhere=@chvSQLWhere+@chvSQLWhere1
-- 结算状态
--IF @chrjsStyle = '2' SET @chrjsState = '1'
SET @chvSQLWhere1 = CASE @chrjsState WHEN '9' THEN ''	-- 全部
		WHEN '0' THEN ' AND bil.jsState = ''0'''	-- 未结算
		WHEN '1' THEN ' AND bil.jsState = ''1'''	-- 未完成结算
		WHEN '2' THEN ' AND bil.jsState = ''2'''	-- 结算完成
		ELSE '' END


--SELECT @chvSQLWhere=@chvSQLWhere+@chvSQLWhere1	


SET @chvSQL = '
	SELECT	a.BillNumberID,
			a.BillDate,
			a.BillType,
			a.BillCode,
			a.bFullName,
			a.dealbfullname,
			a.eFullName,
			a.dFullName,
			a.STypeId,
			CASE WHEN a.BillType IN (45,6,215,46) THEN -a.TotalQty ELSE a.TotalQty END AS TotalQty,
			CASE WHEN a.BillType IN (45,6,215,46) THEN -a.TotalMoney ELSE a.TotalMoney END AS TotalMoney,
			CASE WHEN a.BillType IN (45,6,215,46) THEN -a.NTotalMoney ELSE a.NTotalMoney END AS NTotalMoney,
			CASE WHEN a.BillType IN (45,6,215,46) THEN -a.Preferencemoney ELSE a.Preferencemoney END AS Preferencemoney,
			CASE WHEN a.BillType IN (45,6,215,46) THEN -a.NPreferencemoney ELSE a.NPreferencemoney END AS NPreferencemoney,
			a.jsStyle,
			a.jsState,
			CASE WHEN a.BillType IN (45,6,215,46) THEN -a.CompleteTotal ELSE a.CompleteTotal END AS CompleteTotal,
			CASE WHEN a.BillType IN (45,6,215,46) THEN -a.NCompleteTotal ELSE a.NCompleteTotal END AS NCompleteTotal,
			CASE WHEN a.BillType IN (45,6,215,46) THEN  -isnull(a.ChargeOffTotal,0) ELSE isnull(a.ChargeOffTotal,0) end as ChargeOffTotal,
			CASE WHEN a.BillType IN (45,6,215,46) THEN  -isnull(a.nChargeOffTotal,0) ELSE isnull(a.nChargeOffTotal,0) end as nChargeOffTotal,
			CASE WHEN a.jsState = ''结算完成'' THEN CASE WHEN a.BillType IN (45,6,215,46) THEN -a.TotalQty ELSE a.TotalQty END
			ELSE a.CompleteGoodQty END AS CompleteGoodQty,
			
			CASE WHEN a.jsState = ''结算完成'' THEN 0
			WHEN a.BillType IN (45,6,215,46) THEN -(a.TotalQty+a.CompleteGoodQty)
			ELSE a.TotalQty-a.CompleteGoodQty END AS NoCompleteGoodQty,
			
			CASE WHEN a.jsState = ''结算完成'' THEN 0
			WHEN a.BillType IN (45,6,215,46) THEN -(a.TotalMoney-a.Preferencemoney-a.CompleteTotal-a.ChargeOffTotal)
			ELSE a.TotalMoney-a.Preferencemoney-a.CompleteTotal-a.ChargeOffTotal END AS NoCompleteTotal,
			
			CASE WHEN a.jsState = ''结算完成'' THEN 0
			WHEN a.BillType IN (45,6,215,46) THEN -(a.nTotalMoney-a.nPreferencemoney-a.nCompleteTotal-a.nChargeOffTotal)
			ELSE a.NTotalMoney-a.NPreferencemoney-a.NCompleteTotal-a.nChargeOffTotal END AS NNoCompleteTotal,
			a.comment,
			a.cfullname,
			a.rate,
			0 as InvoiceCostTotal
		INTO #Result
	FROM (' + @chvSQL + @chvSQLWhere + @chvSQLWhere1+ ') a ' 

--发票数据

SET @chvSQL = @chvSQL+'
	insert into #Result
	SELECT	bil.BillNumberID,
			bil.BillDate,
			bil.BillType,
			bil.BillCode,
			bil.btypeid AS bFullName,
			bil.dealbtypeid as dealbfullname,
			bil.etypeid AS eFullName,
			bil.dtypeid AS dFullName,			
			bil.STypeId,
			bil.TotalQty,
			bil.TaxTotalMoney,
			bil.NTaxTotalMoney,
			0 as Preferencemoney,
			0 as NPreferencemoney,
			CASE WHEN bil.jsStyle = ''0'' THEN ''无''
				WHEN bil.jsStyle = ''1'' THEN ''按单结算''
				WHEN bil.jsStyle = ''2'' THEN ''按商品结算''
				WHEN bil.jsStyle = ''3'' THEN ''按品牌结算''
				ELSE ''''
			END AS jsStyle,
			CASE WHEN bil.jsState = ''0'' THEN ''未结算''
				WHEN bil.jsState = ''1'' THEN ''未完成结算''
				WHEN bil.jsState = ''2'' THEN ''结算完成''
				ELSE ''''
			END AS jsState,
			bil.CompleteTotal  AS CompleteTotal,
			bil.NCompleteTotal AS NCompleteTotal,
			isnull(bil.ChargeOffTotal,0)  as ChargeOffTotal,
			isnull(bil.nChargeOffTotal,0)  as nChargeOffTotal,
			CASE WHEN   bil.jsState = 2  THEN BIL.TotalQty ELSE ISNULL(c.CompleteGoodQty,0) END AS CompleteGoodQty,
			CASE WHEN   bil.jsState = 2  THEN 0 ELSE BIL.TotalQty-ISNULL(c.CompleteGoodQty,0) END AS  NoCompleteGoodQty,
			CASE WHEN   bil.jsState = 2  THEN 0 ELSE BIL.TaxTotalMoney-ISNULL(Bil.CompleteTotal,0) END AS  NoCompleteTotal,
			CASE WHEN   bil.jsState = 2  THEN 0 ELSE BIL.nTaxTotalMoney-ISNULL(Bil.nCompleteTotal,0) END AS  nNoCompleteTotal,
			bil.comment,
			AC.FullName AS cfullname,
			AC.rate,
			ISNULL(C.InvoiceCostTotal,0)
	FROM	ReceiptBillIndex bil 
	INNER JOIN AC_currency AC ON Bil.CID=AC.CID '

	IF NOT (@BTypeId = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @chvSQL = @chvSQL + ' INNER JOIN #GetSelBTypeId B ON Bil.BTypeId = B.TypeId'

	IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
		SET @chvSQL = @chvSQL + ' INNER JOIN #GetSelETypeId E ON Bil.ETypeId = E.TypeId'

	IF NOT @DTypeId = '00000'
		SET @chvSQL = @chvSQL + ' INNER JOIN #DType D ON Bil.DTypeId = D.TypeId'
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @chvSQL = @chvSQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '	
SET @chvSQL = @chvSQL+ '
LEFT JOIN #BillDetails c ON bil.BillNumberID = c.BillNumberID  and bil.billtype=c.billtype
WHERE	bil.BillDate >= '''+@StartDate+''' 
		AND bil.BillDate <= '''+@EndDate+'''
		AND bil.BillType IN ('+@chvSelBill+')
		AND ((bil.RedWord = 0 AND bil.Draft=0)'+@isiniWhere+') 
	 '+@CIDWhere

SET @chvSQL=@chvSQL+@chvSQLWhere+@chvSQLWhere1
--EXEC(@chvSQL)
--print @chvSQL

IF @IsSale = 0
	SET @chvSQL =@chvSQL+ '
		SELECT b.* ,
			CASE WHEN B.BillType=405 THEN B.InvoiceCostTotal ELSE ISNULL(T.AllCostTotal,0) END AS AllCostTotal,
			SysDiy1_head,
			SysDiy2_head,
			SysDiy3_head,
			SysDiy4_head, 
			SysDiy5_head,
			SysDiy6_head,
			SysDiy7_head,
			SysDiy8_head,
			SysDiy9_head,
			SysDiy10_head,
			SysDiy11_head,
			SysDiy12_head,
			SysDiy13_head,
			SysDiy14_head,
			SysDiy15_head,
			SysDiy16_head,
			SysDiy16_head,
			SysDiy17_head,
			SysDiy18_head,
			SysDiy19_head,
			SysDiy20_head,
			SysDiy21_head,
			SysDiy22_head,
			SysDiy23_head,
			SysDiy24_head,
			SysDiy25_head,
			SysDiy26_head,
			SysDiy27_head,
			SysDiy28_head,
			SysDiy29_head,
			SysDiy30_head,
			SysDiy31_head,
			SysDiy32_head
		FROM #Result b
		LEFT JOIN Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
		LEFT JOIN
		(
			SELECT R.BillNumberID,
				   SUM(-isnull(I.CostTotal,0))  AS AllCostTotal
			FROM #Result R
			INNER JOIN InOutstocktable I ON I.BillNumberId = R.BillNumberID and r.billtype=i.billtype
			GROUP BY R.BillNumberID,I.BillType
		) T ON T.BillNumberID = B.BillNumberID
		ORDER BY b.BillDate DESC,b.BillType,b.BillCode 
		DROP TABLE #Result
		' 
ELSE
	SET @chvSQL += '
		SELECT b.* ,
			0 as AllCostTotal,
			SysDiy1_head,
			SysDiy2_head,
			SysDiy3_head,
			SysDiy4_head, 
			SysDiy5_head,
			SysDiy6_head,
			SysDiy7_head,
			SysDiy8_head,
			SysDiy9_head,
			SysDiy10_head,
			SysDiy11_head,
			SysDiy12_head,
			SysDiy13_head,
			SysDiy14_head,
			SysDiy15_head,
			SysDiy16_head,
			SysDiy16_head,
			SysDiy17_head,
			SysDiy18_head,
			SysDiy19_head,
			SysDiy20_head,
			SysDiy21_head,
			SysDiy22_head,
			SysDiy23_head,
			SysDiy24_head,
			SysDiy25_head,
			SysDiy26_head,
			SysDiy27_head,
			SysDiy28_head,
			SysDiy29_head,
			SysDiy30_head,
			SysDiy31_head,
			SysDiy32_head
			FROM #Result b
		LEFT JOIN Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
		ORDER BY b.BillDate DESC,b.BillType,b.BillCode'

--PRINT(@chvSQL)
EXEC(@chvSQL)

DROP TABLE #DType,#GetSelBTypeId,#GetSelETypeId,#GetManSTypeId,#GetManKTypeId,#BillDetails,#BillName,#Billnum

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAcCurrency]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROC [dbo].Web_QueryAcCurrency
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	查询币别信息
-- 时间：	2012-05-28
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Web_QueryAcCurrency
(
	@Search		VARCHAR(200)	--查询条件
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @SQL VARCHAR(4000)
SET @SQL='SELECT 
					CId, 
					UserCode,
					FullName,
					Rate 
				FROM Ac_Currency
				WHERE Deleted=0 '
--查询条件
IF(ISNULL(@Search,'')<>'')
	BEGIN
		SET @SQL+='AND (UserCode LIKE ''%'+@Search+'%'' 
					OR FullName LIKE ''%'+@Search+'%'')'
	END
	
SET @SQL+='	ORDER BY UserCode'
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_QueryAcCurrencyGroup]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAcCurrencyGroup
GO 
/****** Object:  StoredProcedure [dbo].[Web_QueryAcCurrencyGroup]    Script Date: 05/10/2012 17:41:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- ========================================================================
-- 描述：	查询币别信息
-- 时间：	2012-05-28
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC [dbo].[Web_QueryAcCurrencyGroup]
(
	@vgid		int,				--币别ID
	@Search		VARCHAR(200),		--查询条件
	@Type		INT					--操作类型 0 所有 1指定ID 2指定条件
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE @SQL VARCHAR(4000)
SET @SQL=''
IF(@Type=0)--查询所有
BEGIN
	SET @SQL='SELECT 
					VgId, 
					PyCode,
					FullName 
				FROM Ac_Voucher_Group'
END
ELSE IF(@Type=1)--查询指定ID
BEGIN
	SET @SQL='SELECT 
					VgId, 
					PyCode,
					FullName 
				FROM Ac_Voucher_Group 
				WHERE 
					 Vgid='+@vgid
END
ELSE IF(@Type=2)--查询指定条件
BEGIN
	SET @SQL='SELECT 
					VgId, 
					PyCode,
					FullName 
				FROM Ac_Voucher_Group 
				WHERE FullName LIKE ''%'+@Search+'%'''
END

EXEC(@SQL)

GO







IF EXISTS(select * from dbo.sysobjects where id=object_id(N'Web_QueryAcFixedAssets') and OBJECTPROPERTY(id,N'isProcedure')=1)
	DROP PROC dbo.Web_QueryAcFixedAssets
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：查询固定资产信息	
-- 时间：2012-04-18	
-- 作者：古丽娟	
-- 参数:@Deleted是否删除 1：已删除 0 未删除
-- ========================================================================
CREATE PROCEDURE Web_QueryAcFixedAssets
(	
	@deleted		INT,					--是否删除
	@OpertiorId		VARCHAR(50)=''			--操作人
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @Sql VARCHAR(4000)
Select @sql='SELECT 
			item.nId,
			item.UserCode, 
			item.FullName,
			item.Comment,
			item.Deleted,
			item.Sysrow,
			IsModify,
			dbo.Fn_GetIsUse_Items(item.nId,4) isuse
		 FROM Ac_Items item'+CHAR(13)
IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeID = @OpertiorId AND MangerCpaital='-99999')
		SET @sql+= '	INNER JOIN AType_L a ON a.ETypeID = '''+@OpertiorId+''' AND a.Flag = ''1'' AND a.TypeID = item.nId '+CHAR(13)
SET @sql+='	WHERE  TypeName=''F'''+CHAR(13)
IF @Deleted=0
	SET @sql+=' AND item.deleted=0'+CHAR(13)
SET @sql+=' ORDER BY item.UserCode'
PRINT @sql
EXEC (@sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(select * from dbo.sysobjects where id=object_id(N'Web_QueryAcFixedAssetsLine') and OBJECTPROPERTY(id,N'isProcedure')=1)
DROP PROC dbo.Web_QueryAcFixedAssetsLine
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：查询固定资产信息	
-- 时间：2012-04-18	
-- 作者：古丽娟	
-- 参数:@Deleted是否删除 1：已删除 0 未删除
-- ========================================================================
CREATE PROCEDURE Web_QueryAcFixedAssetsLine
(
	@parid VARCHAR(50)='',		--父级ID
	@deleted INT,				--是否删除
	@operatorid VARCHAR(50)	--操作人
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @Sql VARCHAR(4000)
Select @sql='SELECT 
			Nid,
			TypeId,
			STypeId,
			Parid,
			UserCode, 
			FullName,
			Comment,
			AtypeID,
			DepATypeId,
			DisATypeId,
			Deleted,
			dbo.F_GetPath(TypeId,9) AS VPath  
	FROM Ac_FixedAssets
	WHERE 1=1'
SET @Sql+=' AND typeid like ''%'+@parid+'%'' AND typeid<>''0000100002'' order by usercode'

exec(@Sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO








IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAcItems]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryAcItems
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_items 查询列表(1：树形 2：线性)
-- 时间：	2013-01-30
-- 作者：	GLJ
--TypeName B:现金银行 G：其他收入 E：费用类型 F：固定资产 C：资产项 L:负债项
-- ========================================================================
CREATE PROC Web_QueryAcItems
(
	@TypeName	VARCHAR(5),				--TypeNAME 类别
	@Deleted	INT=0,					--是否停用
	@OpertiorId	VARCHAR(50)='00000',	--操作人
	@ParId		VARCHAR(50)				--父节点
)
--@encode$--
AS
SET NOCOUNT ON
CREATE TABLE #Atype(Typeid	VARCHAR(50))
--IF(@ParId<>'00000')
--	SELECT @TypeName=TypeName FROM Ac_Items WHERE nTypeId=@ParId
DECLARE @SQL VARCHAR(MAX)='
SELECT DISTINCT
	item.nId,
	item.nTypeId TypeID,
	item.nParId	ParId,
	item.UserCode,
	item.FullName,
	item.CreateBank,
	item.BankType,
	item.Comment,
	item.Deleted,
	item.Sysrow,
	item.IsModify,
	item.TypeName,
	item.SonCount,
	item.SonNum,
	item.Name as jmname,
	item.pycode,
	0 AS isuse'+char(13)
	
SET @SQL+='FROM Ac_Items item '+CHAR(13)
	
IF(@TypeName='root')
	BEGIN
		INSERT INTO #Atype
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AlltreeInDebtT(@OpertiorId) B ON B.nTypeID=item.nTypeID			--负债合计（管辖负债）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeIncomeC(@OpertiorId) F ON F.nTypeID=item.nTypeID			--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeExpenseC(@OpertiorId) F ON F.nTypeId=item.nTypeId		--支出类（费用类型+管辖支出）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeAssetsT(@OpertiorId) G ON G.nTypeID=item.nTypeID			--资产合计（固定资产+银行账户+管辖固定资产）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeOwnerEquityT(@OpertiorId) A ON A.nTypeID=item.nTypeID	--所有者权益
			
		SET @SQL+= '	INNER JOIN #Atype F ON F.Typeid=item.nTypeID'+CHAR(13)
	END
ELSE 
	BEGIN
		--判断权限 银行账户	
		/*IF @TypeName='B'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeA('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END	
			
		--判断权限 固定资产
		IF @TypeName='F'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeC('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END	
		
		--管辖资产		
		IF @TypeName='C'
			BEGIN
				SET @SQL+= '	INNER JOIN F_TreeGxAssets('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
			
		--判断权限 其他收入
		IF @TypeName='G'	
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeI('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
			
		--判断权限 费用类型
		IF @TypeName='E'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeF('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
		
		

		IF @TypeName='L'--负债
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeInDebtT('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END	 */
		IF @TypeName='B'   
			BEGIN
				INSERT INTO #Atype
				SELECT ntypeid 
				FROM  F_AllTreeA(@OpertiorId)
				WHERE nTypeId NOT IN('0000100009','0000200006')
			END	
			
		--判断权限 固定资产
		IF @TypeName='F'
			BEGIN
				INSERT INTO #Atype
				SELECT ntypeid 
				FROM  F_AllTreeC(@OpertiorId)
			END	
		
		--管辖资产		
		IF @TypeName='C'    --资产权限范围不包含预付资金的 预付资金在管辖账户
			BEGIN
				INSERT INTO #Atype
				SELECT ntypeid FROM  F_TreeGxAssets(@OpertiorId)
				UNION ALL
				SELECT ntypeid FROM  F_AllTreeA(@OpertiorId) WHERE nTypeId='0000100009'
				
			END
			
		--判断权限 其他收入
		IF @TypeName='G'	
			BEGIN
				INSERT INTO #Atype
				SELECT ntypeid 
				FROM  F_AllTreeI(@OpertiorId)
			END
			
		--判断权限 费用类型
		IF @TypeName='E'
			BEGIN
				INSERT INTO #Atype
				SELECT ntypeid 
				FROM  F_AllTreeF(@OpertiorId)
			END
		
		

		IF @TypeName='L'--负债	  --负债权限范围不包含预收资金的 预收资金在管辖账户
			BEGIN
				INSERT INTO #Atype
				SELECT ntypeid FROM  F_AllTreeInDebtT(@OpertiorId)
				UNION ALL
				SELECT ntypeid FROM  F_AllTreeA(@OpertiorId) WHERE nTypeId='0000200006'
			END
			
	   SET @SQL+= '	INNER JOIN #Atype F ON F.Typeid=item.nTypeID'+CHAR(13)
	END

SET @SQL+='	WHERE 1=1 AND item.UserCode NOT IN(''SYC-1601'',''SYC-1602'')'+CHAR(13)
IF(@TypeName<>'root')
	SET @SQL+='	AND item.TypeName='+char(39)+@TypeName+CHAR(39)+CHAR(13)

IF @Deleted=0
	SET @SQL+='	AND item.deleted=0'+CHAR(13)
	
SET @SQL+='	AND item.nParId='''+@ParId+''''+CHAR(10)

SET @SQL+=' ORDER BY item.UserCode '	
--PRINT @SQL

EXEC(@SQL)
DROP TABLE #Atype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAcItemsLineByParid]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryAcItemsLineByParid
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能说明：得到父级子节点
-- 作者：glj  
-- 时间：2013-02-01
-- ========================================================================
CREATE  PROC  Web_QueryAcItemsLineByParid
(
	@ParID			VARCHAR(50),	--父级ID
	@TypeName		VARCHAR(5),		--项目类型
	@OpertiorId		VARCHAR(50)		--操作员
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Atype(Typeid	VARCHAR(50))
IF(@ParID='C')--资产项
	SET @ParID='00001'
IF(@ParID='L')--负债项
	SET @ParID='00002'
IF(@ParID='G')--其他收入
	SET @ParID='0000300003'
IF(@ParID='E')--费用类型
	SET @ParID='0000400003'
IF(@ParID='F')--固定资产
	SET @ParID='0000100002'
IF(@ParID='B')--银行账户
	SET @ParID='00001'
IF(@ParID='root')--项目汇总
	SET @ParID='00000'

DECLARE @SQL VARCHAR(MAX)='
;With GetItemLine(NId,nTypeId) 
As 
( 
	Select NId,nTypeId From Ac_Items where nTypeId='''+@ParID+'''
	Union All 
	Select item.nId,item.NtypeId From GetItemLine ic
	Inner Join Ac_Items item ON item.nParId=ic.nTypeId
) 

SELECT DISTINCT
	item.nId,
	item.UserCode,
	item.FullName,
	item.CreateBank,
	item.BankType,
	item.Comment,
	item.Deleted,
	item.Sysrow,
	item.TypeName,
	item.name as jmname,
	item.pycode,	
	dbo.F_GetItemsPath(item.nTypeId) itemPath
FROM Ac_Items item
INNER JOIN	GetItemLine line ON line.NId=item.nId'
IF(@TypeName='root')
	BEGIN
		
		INSERT INTO #Atype
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AlltreeInDebtT(@OpertiorId) B ON B.nTypeID=item.nTypeID			--负债合计（管辖负债）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeIncomeC(@OpertiorId) F ON F.nTypeID=item.nTypeID			--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeExpenseC(@OpertiorId) F ON F.nTypeId=item.nTypeId		--支出类（费用类型+管辖支出）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeAssetsT(@OpertiorId) G ON G.nTypeID=item.nTypeID			--资产合计（固定资产+银行账户+管辖固定资产）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeOwnerEquityT(@OpertiorId) A ON A.nTypeID=item.nTypeID			--所有者权益
		
		
		SET @SQL+= '	INNER JOIN #Atype F ON F.Typeid=item.nTypeID'+CHAR(13)
	END
ELSE 
	BEGIN
			
			--判断权限 银行账户	
		IF @TypeName='B'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeA('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END	
			
		--判断权限 固定资产
		IF @TypeName='F'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeC('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END	
		
		--管辖资产		
		IF @TypeName='C'
			BEGIN
				SET @SQL+= '	INNER JOIN F_TreeGxAssets('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
			
		--判断权限 其他收入
		IF @TypeName='G'	
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeI('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
			
		--判断权限 费用类型
		IF @TypeName='E'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeF('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
		IF @TypeName='L'--负债
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeInDebtT('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
			
			
	END
	

SET @SQL+='
WHERE 
	item.SonNum=0 
	AND item.nTypeId<>''00000'' 
	AND item.UserCode NOT IN(''SYC-1601'',''SYC-1602'')'+CHAR(13)
	
IF(@TypeName<>'root')
	SET @SQL+=' AND 
	item.TypeName='''+@TypeName+CHAR(39)+CHAR(13)
	
SET @SQL+=' ORDER BY item.UserCode '	
PRINT @SQL
EXEC(@SQL)

DROP TABLE #Atype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAcItemsQuery]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryAcItemsQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 功能说明：满足查询条件的列表
-- 作者：glj  
-- 时间：2013-02-04
-- ========================================================================
CREATE  PROC  Web_QueryAcItemsQuery
(
	@UserCode		VARCHAR(200),	--项目编号
	@FullName		VARCHAR(200),	--项目名称
	@TypeName		VARCHAR(5),		--项目类型
	@OpertiorId		VARCHAR(50)		--操作员
	
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Atype(Typeid	VARCHAR(50))
DECLARE @SQL VARCHAR(MAX)
SET @SQL=' 
SELECT DISTINCT
	item.nId,
	item.UserCode,
	item.FullName,
	item.CreateBank,
	item.BankType,
	item.Comment,
	item.deleted,
	item.TypeName,
	item.Sysrow,
	item.name as jmname,
	item.pycode,
	dbo.F_GetItemsPath(item.nTypeId) itemPath
FROM Ac_Items item
'+CHAR(13)
IF(@TypeName='root')
	BEGIN
		INSERT INTO #Atype
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AlltreeInDebtT(@OpertiorId) B ON B.nTypeID=item.nTypeID			--负债合计（管辖负债）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeIncomeC(@OpertiorId) F ON F.nTypeID=item.nTypeID			--收入类（管辖收入+管辖其他收入）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeExpenseC(@OpertiorId) F ON F.nTypeId=item.nTypeId		--支出类（费用类型+管辖支出）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeAssetsT(@OpertiorId) G ON G.nTypeID=item.nTypeID			--资产合计（固定资产+银行账户+管辖固定资产）
		UNION ALL
		SELECT item.nTypeId FROM Ac_Items item INNER JOIN F_AllTreeOwnerEquityT(@OpertiorId) A ON A.nTypeID=item.nTypeID			--所有者权益
		
		SET @SQL+= '	INNER JOIN #Atype F ON F.Typeid=item.nTypeID'+CHAR(13)
	END
ELSE 
	BEGIN
		--判断权限 银行账户	
		IF @TypeName='B'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeA('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END	
			
		--判断权限 固定资产
		IF @TypeName='F'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeC('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END	
		
		--管辖资产		
		IF @TypeName='C'
			BEGIN
				SET @SQL+= '	INNER JOIN F_TreeGxAssets('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
			
		--判断权限 其他收入
		IF @TypeName='G'	
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeI('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
			
		--判断权限 费用类型
		IF @TypeName='E'
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeF('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
		
		IF @TypeName='L'--负债
			BEGIN
				SET @SQL+= '	INNER JOIN F_AllTreeInDebtT('''+@OpertiorId+''') F ON F.nTypeID=item.nTypeId'+CHAR(13)
			END
	END
	
--=========================================where 条件 筛选数据【begin】=========================================
SET @SQL+='WHERE 
	item.SonNum=0
	AND item.nTypeId<>''00000''
	AND item.UserCode NOT IN(''SYC-1601'',''SYC-1602'')'+CHAR(13)
	
IF(@TypeName<>'root')
	SET @SQL+='AND
	item.TypeName='''+@TypeName+CHAR(39) +CHAR(13)	
	
--判断UserCode 和FullName
IF(ISNULL(@UserCode,'')<>'')
	BEGIN
		SET @SQL+=' AND item.UserCode like ''%'+@UserCode+'%'''+CHAR(13)
	END
IF(ISNULL(@FullName,'')<>'')
	BEGIN
		SET @SQL+=' AND item.FullName like ''%'+@FullName+'%'''+CHAR(13)
	END

--=========================================where 条件 筛选数据【end】=========================================

SET @SQL+=' ORDER BY item.UserCode '	
--PRINT @SQL
EXEC(@SQL)

DROP TABLE #Atype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAcMulCol]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAcMulCol
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	多栏账设计查询
-- 时间：	2014-11-24
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryAcMulCol
(
	@STypeId	VARCHAR(50),	--操作员所在分支机构
	@OperatorID	VARCHAR(50)		--操作员ID
)

--@encode$--
AS
SET NOCOUNT ON 
SELECT 
	CASE WHEN ISNULL(F.TypeId,'')='' THEN '****' ELSE A.AccountName END AccountName,
	A.Comment,
	A.AssistID,
	A.Creator,
	B.FullName CreatorName,
	a.CreatorStypeId,
	CASE WHEN A.IsPublic=1 THEN '仅自己可见' ELSE '公开' END AS IsPublic
FROM Ac_MulColumnAccount A
LEFT JOIN employee B ON A.CreatorStypeId=B.STypeID AND A.Creator=B.typeId
LEFT JOIN F_TreeAccount(@OperatorID,'') F ON F.TypeId=A.ATypeid AND F.StypeId=A.StypeId
WHERE 
	(CreatorStypeId=@STypeId AND Creator=@OperatorID) 
	OR A.IsPublic=0
ORDER BY AccountName
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAcPeriod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAcPeriod]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：郑红霞
	日期：2012-03-31
	描述：查询会计期间
*/
CREATE PROCEDURE Web_QueryAcPeriod
(
 @dbname VARCHAR(2000)
)
--@encode$--
AS
SET NOCOUNT ON
  SELECT * FROM Ac_Period
 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAcReconciliation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAcReconciliation]
GO

--================================================================
-----------------功能：往来对账查询----------
-----------------作者：韩林			 ----------
-----------------日期：2012-06-07    ----------
-- 2013-08-29 周华 修改将开账后结算的数据加回来
--================================================================

CREATE    PROC Web_QueryAcReconciliation
( 
	@type	  	int,
	@stypeid	varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @ExpenseToAr INT=0
SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'

DECLARE @sql VARCHAR(max)
DECLARE @sqlcomplete VARCHAR(200)=' (SELECT ISNULL(SUM(CompleteTotal),0) FROM CompleteTotal WHERE MoneyBillID<>-1 AND GoodsBillID=B.billNumberId ) ';
DECLARE @sqlcomplete1 VARCHAR(200)=' (SELECT ISNULL(SUM(CompleteTotal),0) FROM CompleteTotal WHERE MoneyBillID<>-1 AND GoodsBillID=B.billNumberId )  ';
DECLARE @adbsqlcomplete VARCHAR(200)=' (SELECT ISNULL(SUM(CompleteTotal),0) FROM CompleteTotal WHERE MoneyBillID<>-1 AND GoodsBillID=B.billNumberId and GoodsBillDetailID=a.ID )';
DECLARE @adbsqlcomplete1 VARCHAR(200)=' (SELECT ISNULL(SUM(CompleteTotal),0) FROM CompleteTotal WHERE MoneyBillID<>-1 AND GoodsBillID=B.billNumberId and GoodsBillDetailID=a.ID ) ';


SET @sql='
SELECT	isnull(arapini.atypeid,acini.atypeid) as typeid,
		a.FullName,
		a.UserCode,
		ac.fullname as cfullname,
		isnull(arapini.arapinitotal,0) as arapinitotal,
		isnull(arapini.arapinintotal,0) as arapinintotal,
		isnull(acini.acinitotal,0) as acinitotal,
		isnull(acini.acinintotal,0) as acinintotal ,
		isnull(arapini.arapinitotal,0)- isnull(acini.acinitotal,0) as difference,
		isnull(arapini.arapinintotal,0)-isnull(acini.acinintotal,0) as ndifference
FROM
(
	select atypeid,cid,sum(arapinitotal) as arapinitotal,sum(arapinintotal) as arapinintotal
	FROM
	(
		SELECT	atypeid1 as atypeid,
			cid,
		'
IF @type=1
	SET @sql =@sql +'
			CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,189,213,312) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(B.ChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(B.ChargeOffTotal,0))
					 WHEN Billtype =36 and btypeid like ''00001%'' AND '+CAST(@ExpenseToAr AS VARCHAR(2))+'=1
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(B.ChargeOffTotal,0))
					ELSE 0 
				END +'+@sqlcomplete+' AS  arapinitotal,
			CASE WHEN billtype IN (11,12,160,141,93,85,167,168,172,181,189,213,312) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(B.ChargeOffTotal,0)
					 WHEN BillType IN (4,45,46,148,149) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(B.ChargeOffTotal,0)) 
					 WHEN Billtype =36 and btypeid like ''00001%''	AND '+CAST(@ExpenseToAr AS VARCHAR(2))+'=1
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(B.ChargeOffTotal,0)) 
					ELSE 0 
				END +'+REPLACE(@sqlcomplete,'SUM(CompleteTotal)','SUM(NCompleteTotal)')+' AS arapinintotal
			'
ELSE
	SET @sql = @sql +'
			CASE WHEN billtype IN (34,161,145,84,170,190,212) 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(B.ChargeOffTotal,0)
					 WHEN Billtype =36 and (btypeid like ''00002%'' OR '+CAST(@ExpenseToAr AS VARCHAR(2))+'=0)
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(B.ChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(B.ChargeOffTotal,0)) 
					ELSE 0 
				END +'+@sqlcomplete+' AS  arapinitotal,
			CASE WHEN billtype IN (34,161,145,84,170,190,212) 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(B.ChargeOffTotal,0) 
					 WHEN Billtype =36 and (btypeid like ''00002%'' OR '+CAST(@ExpenseToAr AS VARCHAR(2))+'=0)
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(B.ChargeOffTotal,0)
					 WHEN BillType IN (66,6,150,151) 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(B.ChargeOffTotal,0)) 
					ELSE 0 
				END +'+REPLACE(@sqlcomplete,'SUM(CompleteTotal)','SUM(NCompleteTotal)')+' AS arapinintotal
			'
SET @sql = @sql +'
	FROM dbo.BillIndex b
	WHERE	(billtype in'+CASE WHEN @type=1 THEN '(4,11,12,160,141,93,85,167,168,172,181,189,45,46,148,149,213,312)' ELSE '(66,34,161,145,84,170,190,6,150,151,212)' END+'
			OR(billtype=36 and '+CASE WHEN @type=1 THEN'btypeid like ''00001%'' AND '+CAST(@ExpenseToAr AS VARCHAR(2))+'=1' ELSE '(btypeid like ''00002%'' OR '+CAST(@ExpenseToAr AS VARCHAR(2))+'=0)' END+'))
			AND b.IsIni=1 
			AND atypeid1 IS NOT NULL
			AND atypeid1 <> ''''
			AND	b.stypeid in (select typeid from stype where verifyid='''+@stypeid+''')
	UNION ALL
	SELECT  atypeid1 as atypeid,
			cid,
			CASE WHEN b.billtype = '+CASE WHEN @type=1 THEN '116' ELSE '128' END+'
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = '+CASE WHEN @type=1 THEN '115'ELSE '129' END+'
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
				END+'+@adbsqlcomplete1+' AS total,
			CASE WHEN b.billtype = '+CASE WHEN @type=1 THEN '116' ELSE '128' END+'
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.nChargeOffTotal,0)
					 WHEN b.billtype = '+CASE WHEN @type=1 THEN '115'ELSE '129' END+'
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.nChargeOffTotal,0))
				END+'+REPLACE(@adbsqlcomplete,'SUM(CompleteTotal)','SUM(NCompleteTotal)')+' AS ntotal
	FROM	AdDebtBill a 
	INNER JOIN billindex b ON a.BillNumberId =b.BillNumberId
	WHERE	b.billtype in('+CASE WHEN @type=1 THEN '115,116' ELSE '128,129' END+')
			AND b.IsIni=1 
			AND atypeid1 IS NOT NULL
			AND atypeid1 <> ''''
			AND	b.stypeid in (select typeid from stype where verifyid='''+@stypeid+''')
	UNION ALL
	SELECT atypeid1 as atypeid,
			cid,
			(TaxTotalMoney-CompleteTotal-ISNULL(ChargeOffTotal,0)) AS arapinitotal,
			(NTaxTotalMoney-nCompleteTotal-ISNULL(ChargeOffTotal,0)) AS arapinintotal
	FROM dbo.ReceiptBillIndex
	WHERE BillType='''+CASE WHEN @type=1 THEN '405' ELSE '404' END+''' AND IsIni=1 AND ATypeID1 IS NOT NULL AND ATypeID1<>'''' AND Stypeid IN (SELECT TypeId FROM dbo.SType WHERE VerifyID='''+@stypeid+''')
	) a
	GROUP BY atypeid,cid
) arapini
FULL OUTER JOIN 
(	
	SELECT	ia.Atypeid,
			ia.cid,
			isnull(SUM(ia.iniTotal),0) AS acinitotal,
			isnull(SUM(ia.iniTotalFor),0) AS acinintotal
	FROM	dbo.Ac_IniAccount ia 
	INNER JOIN AC_account aa on ia.atypeid=aa.typeid and aa.stypeid='''+@stypeid+''' and aa.CHECKTYPE='+CAST(@type AS VARCHAR(2))+'
	WHERE ia.stypeid='''+@stypeid+''' 
	GROUP BY ia.atypeid,ia.cid
) acini ON arapini.atypeid=acini.atypeid and arapini.cid=acini.cid
INNER JOIN dbo.Ac_Account a ON a.TypeId=isnull(arapini.ATypeID,acini.atypeid) and a.stypeid='''+@stypeid+'''
INNER JOIN ac_currency ac on ac.cid=isnull(arapini.cid,acini.cid)
order by a.usercode 
'
--PRINT @sql
EXEC(@sql)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_QueryACTable]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_QueryACTable]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	喻堂
	Date	:	2012/03/30
	Description	: 查询会计科目
*/
CREATE PROCEDURE WEB_QueryACTable
(
	@acid	int
)
--@encode$--
AS
SET NOCOUNT ON
IF(ISNULL(@acid,0)=0)
	BEGIN
		SELECT 
			AcId,
			FullName AFullName,
			FullName,
			IsUsed,
			'' ParId,
			0 [Level]
		FROM Ac_Table
	END
ELSE 
	BEGIN
		SELECT
			t.AcId,
			t.UserCode,
			t.FullName,
			t.Comment,
			t.Len1,
			t.Len2,
			t.Len3,
			t.Len4,
			t.Len5,
			t.Len6,
			t.Len7,
			t.Len8,
			t.Len9,
			t.Len10,
			t.EType,
			t.CreateDateTime,
			t.IsUsed,
			t.SetFullName,
			e.FullName AS eFullName
		FROM	[Ac_Table] t
		LEFT JOIN dbo.employee e ON e.typeId = t.EType
		WHERE t.AcId=@acid
		ORDER BY t.[UserCode]
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryACTree]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[WEB_QueryACTree]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--============================================================
--by:glj
--date 2015-04-23
--function:获取明细分类treelist
--============================================================
CREATE  PROCEDURE [dbo].WEB_QueryACTree
(
	@chvOperatorID	VARCHAR(100),   --操作员id
	@STypeId		VARCHAR(50),	--分支机构
	@ATypeId		VARCHAR(MAX),	--科目ID
	@Leveal			INT,			--科目级别
	@Cid			VARCHAR(5),		--币别
	@Fyear			INT,			--年度
	@FPeriodStart	INT,			--开始期间
	@FPeriodEnd		INT,	        --结束期间  
	@BilldateStart	DATETIME,		--开始时间
	@BilldateEnd	DATETIME,       --结束时间  
	@Flag			INT,			--1 是按期间，2是按时间
	@IsPost			BIT,			--未过账凭证1：是 0：否
	@IsDetail		BIT,			--显示明细1：是 0：否
	@IsPeriodNull   BIT,			--本期无发生额不显示 1：不显示 0：显示
	@IsBalanceNull  BIT,			--包括余额为0的科目 1：包括 1：不包括
	@IsYearNull     BIT			    --本年无发生额不显示 1：不显示 0：显示
)
--@encode$--
AS
SET NOCOUNT ON

BEGIN--===================================基本数据准备【BEGIN】===============================================
--建立临时余额表，所有科目
CREATE TABLE #AcBalanceTable 
(
	STypeId				VARCHAR(50),	--分支机构
	ATypeId				VARCHAR(50),	--科目
	Fdc					INT,			--科目方向
	FYear				VARCHAR(10),	--年度
	FPeriod				VARCHAR(10),	--期间
	Cid					INT,			--币种
	FBeginBalanceFor	NUMERIC(24, 10)  DEFAULT 0,--期初
	FBeginBalanceForQty NUMERIC(24, 10)  DEFAULT 0,--期初数量
	FDebitFor			NUMERIC(24, 10)  DEFAULT 0,--本期借方
	FDebitForQty		NUMERIC(24, 10)  DEFAULT 0,--本期借方数量
	FCreditFor			NUMERIC(24, 10)  DEFAULT 0,--本期贷方
	FCreditForQty		NUMERIC(24, 10)  DEFAULT 0,--本期贷方数量
	FEndBalanceFor		NUMERIC(24, 10)  DEFAULT 0,--期末
	FEndBalanceForQty	NUMERIC(24, 10)  DEFAULT 0,--期末数量
	FYtdDebitFor		NUMERIC(24, 10)  DEFAULT 0,--本年借方
	FYtdDebitForQty		NUMERIC(24, 10)  DEFAULT 0,--本年借方数量
	FYtdCreditFor		NUMERIC(24, 10)  DEFAULT 0,--本年贷方
	FYtdCreditForQty	NUMERIC(24, 10)  DEFAULT 0--本年贷方数量
)
IF @Flag=1--如果选择期间，则转成对应的时间
BEGIN
	SELECT @BilldateStart=FBegin FROM Ac_Period WHERE FYear=@Fyear AND FPeriod=@FPeriodStart
	SELECT @BilldateEnd=FEnd FROM Ac_Period WHERE FYear=@Fyear AND FPeriod=@FPeriodEnd		
END	

--要查询的科目
DECLARE @SQL VARCHAR(MAX)
CREATE TABLE #tempAtype(StypeId VARCHAR(50),TypeId VARCHAR(50),Fdc INT,SonNum INT)
SET @SQL='
INSERT INTO #tempAtype(StypeId,TypeId,Fdc,SonNum)
SELECT 
	A.StypeId,
	A.TypeId,
	A.Fdc,
	A.SonNum
FROM Ac_Account A
INNER JOIN F_TreeAccount('''+@chvOperatorID+''','''+@STypeId+''') F ON F.Stypeid=A.StypeId AND F.Typeid=A.TypeId'+CHAR(13)
IF(ISNULL(@Atypeid,'')<>'')
	SET @SQL+='INNER JOIN f_split('''+@Atypeid+''','','') FA ON FA.a=A.TypeId'
	
EXEC(@SQL)
--符合条件的科目
DECLARE @T_ATypeId VARCHAR(MAX)=''
IF(SELECT COUNT(*) FROM #tempAtype)=1 AND NOT EXISTS(SELECT * FROM #tempAtype WHERE SonNum=0)
	BEGIN
		SELECT @T_ATypeId+=A.TypeId+','  
		FROM Ac_Account A 
		INNER JOIN #tempAtype T ON T.StypeId=A.StypeId AND A.SonNum=0 AND SUBSTRING(A.TypeId,1,LEN(T.TypeId))=T.TypeId
	END
ELSE
	BEGIN 
		SELECT 
			@T_ATypeId+=TypeId+',' 
		FROM #tempAtype 
		WHERE SonNum=0
	END	
IF(ISNULL(@T_ATypeId,'')<>'')
	SET @T_ATypeId=SUBSTRING(@T_ATypeId,1,LEN(@T_ATypeId)-1)

INSERT INTO #AcBalanceTable
EXEC WEB_SubsiAcBalanceQueryFromVoucher @StypeId,@T_ATypeId,@Fyear,@BilldateStart,@BilldateEnd,@Cid,@IsPost,@chvOperatorID

--===================================基本数据准备【END】  ===============================================
END;

BEGIN--===================================返回科目treelist数据集并删除临时表【BEGIN】  =============================
IF(@IsDetail=0)--要统计父类
BEGIN
	--直接 like 父节点太慢，及创建一个WITH
	SELECT 
		ATypeId,
		STypeId 
	INTO #ResultTemp
	FROM #AcBalanceTable
	WHERE 
		((@IsPeriodNull=1 AND (FDebitFor<>0 OR FCreditFor<>0)) OR @IsPeriodNull=0)
		AND ((@IsBalanceNull=0 AND FEndBalanceFor<>0) OR @IsBalanceNull=1)
		AND ((@IsYearNull=1 AND (FYtdCreditFor<>0 OR FYtdDebitFor<>0)) OR @IsYearNull=0)
	GROUP BY 
		ATypeId,
		STypeId
		
	;WITH Temp AS
	(
		SELECT A.StypeId,A.TypeId,A.ParId
		FROM #ResultTemp R
		INNER JOIN Ac_Account A ON A.StypeId=R.STypeId AND A.TypeId=R.ATypeId AND A.TypeId<>'00000'
		UNION ALL
		SELECT A.StypeId,A.TypeId,A.ParId
		FROM Temp T
		INNER JOIN Ac_Account A ON A.StypeId=T.STypeId AND A.TypeId=T.ParId AND A.TypeId<>'00000'
	)
	
	SELECT
		A.TypeId,
		A.ParId,
		A.SonNum,
		A.UserCode+A.FullName FullName
	INTO #Temp
	FROM  Ac_Account A
	INNER JOIN Temp TA ON TA.TypeId=A.TypeId AND TA.StypeId=A.StypeId
	INNER JOIN F_TreeAccount(@chvOperatorID,@STypeId) F ON F.Stypeid=A.StypeId AND F.Typeid=A.TypeId AND A.Leveal>1 AND A.FLeveal<=@Leveal
	GROUP BY 
		A.TypeId,
		A.ParId,
		A.SonNum,
		A.UserCode,
		A.FullName
	ORDER BY A.UserCode 
	
	SELECT TypeId,ParId,SonNum,FullName FROM #Temp
	UNION ALL
	SELECT '00001','00000',10000,'资产'
	UNION ALL 
	SELECT '00002','00000',10000,'负债'
	UNION ALL 
	SELECT '00003','00000',10000,'损益'
	UNION ALL 
	SELECT '00004','00000',10000,'成本'
	UNION ALL 
	SELECT '00005','00000',10000,'权益'
	UNION ALL 
	SELECT '00006','00000',10000,'共同'
	
	DROP TABLE #Temp,#ResultTemp
END
ELSE --只统计子类
BEGIN
	SELECT
		A.TypeId,
		A.ParId,
		A.SonNum,
		A.UserCode+A.FullName FullName
	FROM  Ac_Account A
	INNER JOIN #tempAtype TA ON TA.TypeId=A.TypeId AND TA.StypeId=A.StypeId
	INNER JOIN F_TreeAccount(@chvOperatorID,@STypeId) F ON F.Stypeid=A.StypeId AND F.Typeid=A.TypeId
	INNER JOIN (
		SELECT 
			ATypeId,
			STypeId 
		FROM #AcBalanceTable
		WHERE 
			((@IsPeriodNull=1 AND (FDebitFor<>0 OR FCreditFor<>0)) OR @IsPeriodNull=0)
			AND ((@IsBalanceNull=0 AND FEndBalanceFor<>0) OR @IsBalanceNull=1)
			AND ((@IsYearNull=1 AND (FYtdCreditFor<>0 OR FYtdDebitFor<>0)) OR @IsYearNull=0)
		GROUP BY 
			ATypeId,
			STypeId
	) T ON T.ATypeId=A.TypeId AND T.STypeId=A.StypeId	
	ORDER BY A.UserCode 
END
DROP TABLE 
	#AcBalanceTable,
	#tempAtype
--===================================返回科目treelist数据集并删除临时表【END】    =================================
END;

GO
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAcVoucherCashFlow]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAcVoucherCashFlow
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回指定了现金流量的凭证
-- 时间：	2015-03-27
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryAcVoucherCashFlow
(
	@Stypeid		VARCHAR(400),		--分支结构
	@Fyear			VARCHAR(10),		--年度
	@DateChoose		VARCHAR(1),			--期间选择0 期间 1凭证日期
	@SFperiod		VARCHAR(2),			--开始期间
	@EFperiod		VARCHAR(2),			--截止期间
	@SBillDate		VARCHAR(50),		--凭证开始日期
	@EBillDate		VARCHAR(50),		--凭证截止日期
	@Atypeid		VARCHAR(MAX),		--科目
	@Cid			VARCHAR(MAX),		--币别
	@Appoint		INT,				--流量项目 1：已指定 0：未指定 -1全部
	@ShowNotPost	INT,				--是否包含未记账 1：包含 0不包含
	@OperatorId		VARCHAR(50)			--操作员
)

--@encode$--
AS
SET NOCOUNT ON 

DECLARE 
	@SQL VARCHAR(MAX)='',
	@LimitOwnVoucher INT=0--仅能查看本人制单的会计凭证
	
IF(@OperatorId<>'00001')
	SELECT @LimitOwnVoucher=SUBSTRING(lim,4940,1) FROM LoginUser WHERE etypeid=@operatorid

--由于是否需要指定流量特殊，所以需要单独建立临时表先把数据过滤一遍
CREATE TABLE #Bill(BillNumberId NUMERIC(18,0),NeedCashFlow INT)
SET @SQL+='
INSERT INTO #Bill(BillNumberId,NeedCashFlow)
SELECT 
	DISTINCT 
	B.BillNumberId,
	dbo.F_GetVoucherNeedCashFlow(B.BillNumberId) NeedCashFlow
FROM  Ac_Voucher_Bill B
INNER JOIN F_LineAccount('''+@OperatorId+''','''+@Stypeid+''') Line ON Line.Stypeid=B.STypeId AND Line.Typeid=B.ATypeId
INNER JOIN Ac_Account A ON A.STypeId=B.STypeId AND A.TypeId=B.ATypeId AND (A.IsBank=0 OR A.IsCash=0 OR A.IsOther=0)
INNER JOIN Ac_Voucher V ON B.BillNumberId=V.BillNumberId AND B.STypeId='''+@Stypeid+''' AND  V.FChecked<>-1 AND V.RedWord<>1 AND (('+CAST(@ShowNotPost AS VARCHAR(1))+'=0 AND V.IfCheck=''T'') OR '+CAST(@ShowNotPost AS VARCHAR(1))+'=1) AND V.FYear='+CAST(@Fyear AS VARCHAR(4))

IF(@LimitOwnVoucher=1)--仅能查看本人制单的会计凭证
	SET @SQL+=' AND V.ETypeId='''+@OperatorId+''''

IF(ISNULL(@Cid,0)<>0)
	SET @SQL+=' AND B.Cid='+CAST(@Cid AS VARCHAR)
IF(@DateChoose=0)--期间/期间
	SET @SQL+=' AND V.FPeriod BETWEEN '+CAST(@SFperiod AS VARCHAR(2))+' AND '+CAST(@EFperiod AS VARCHAR(2))+CHAR(13)
ELSE 
	SET @SQL+=' AND V.BillDate BETWEEN '''+CAST(@SBillDate AS VARCHAR(50))+''' AND '''+CAST(@EBillDate AS VARCHAR(50))+''''+CHAR(13)

IF(ISNULL(@Atypeid,'')<>'')
	SET @SQL+='	INNER JOIN f_split('''+@Atypeid+''','','') FA ON FA.a=B.ATypeId'+CHAR(13)
	
SET @SQL+=' GROUP BY B.BillNumberId'
EXEC(@SQL)

SET @SQL='
SELECT 
	DISTINCT
	vc.BillNumberId,
	bill.BillNumberId nid,
	vc.BillDate,
	CONVERT(VARCHAR(4),vc.FYear)+''年第''+ CONVERT(VARCHAR(2),vc.FPeriod) +''期'' FPeriodDate,
	CASE 
		WHEN FChecked=0 AND IfCheck = ''f'' AND ISNULL(MarkError,'''')='''' AND ISNULL(ReCheckId,'''')='''' AND IfCheck = ''f'' THEN ''保存''
		WHEN FChecked=1 AND IfCheck = ''f'' AND ISNULL(ReCheckId,'''')='''' AND ISNULL(ReCheckId,'''')='''' AND IfCheck = ''f''  THEN ''审核''
		WHEN ISNULL(ReCheckId,'''')<>'''' AND IfCheck = ''f'' THEN ''已复核''
		WHEN IfCheck=''t'' THEN ''已记账'' END billState,
	VT.FullName vouchertypename,
	gr.FullName ,
	vc.FlowNo,
	gr.FullName+''-''+CONVERT(VARCHAR(10),vc.FlowNo) GroupFullName,
	dbo.F_GetSummaryByLimit(bill.ID,'''+@OperatorId+''',bill.STypeID,bill.Summary) Summary,
	CASE WHEN ISNULL(bill.ATypeId,'''')<>'''' AND ISNULL(F.TypeId,'''')='''' THEN ''****''
		WHEN ISNULL(bill.ATypeId,'''')='''' THEN '''' 
		ELSE a.UserCode 
	END ATypeUserCode,
	CASE WHEN ISNULL(bill.ATypeId,'''')<>'''' AND ISNULL(F.TypeId,'''')='''' THEN ''****''
		WHEN ISNULL(bill.ATypeId,'''')='''' THEN '''' 
		ELSE A.FullName 
	END ATypeFullName,
	cc.fullname currencyName,
	CASE WHEN bill.FAdc=1 THEN bill.FdebitTotalFor ELSE bill.FcreditTotalFor END FAmountFor,
	bill.FDebitTotal,
	bill.FCreditTotal,
	mitem.FullName MFullName,
	CASE WHEN ISNULL(ci.MATypeId,'''')<>'''' THEN ci.MATotal ELSE NULL END MTotal
FROM #Bill B
INNER JOIN Ac_Voucher VC ON VC.BillNumberId=B.BillNumberId AND (('+CAST(@Appoint AS VARCHAR(2))+'=-1 AND B.NeedCashFlow<>-1) OR('+CAST(@Appoint AS VARCHAR(2))+'<>-1 AND B.NeedCashFlow='+CAST(@Appoint AS VARCHAR(2))+'))
INNER JOIN Ac_Voucher_Bill bill  ON bill.BillNumberId=VC.BillNumberId
LEFT JOIN Ac_Account A ON A.TypeId=bill.ATypeId AND A.STypeId=bill.STypeId
LEFT JOIN F_LineAccount('''+@OperatorId+''','''+@Stypeid+''') F ON F.Typeid=A.TypeId AND F.StypeId=A.StypeId
LEFT JOIN Ac_VoucherType VT ON VT.Id=vc.VoucherType
LEFT JOIN Ac_Voucher_Group gr on gr.VgId=VC.VgId 
LEFT JOIN Ac_Currency cc ON cc.cid=bill.cid	
LEFT JOIN (SELECT 
				C.BillNumberId, 
				SUM(CASE WHEN PMA.FullName LIKE ''%现金流入%'' THEN CASE WHEN C.FDc=C.FAdc THEN C.Total ELSE -C.Total END
						 WHEN PMA.FullName LIKE ''%现金流出%'' THEN CASE WHEN C.FDc=C.FAdc THEN -C.Total ELSE C.Total END
					ELSE C.Total END) MATotal,
				C.MATypeId,
				C.RowNo
			FROM Ac_Voucher_Bill_CashMoneyItems  C
			LEFT JOIN Ac_CashMoneyItems MA ON MA.TypeId=C.MATypeId
			LEFT JOIN Ac_CashMoneyItems PMA ON PMA.Leveal=2 AND MA.TypeId LIKE PMA.TypeId+''%''
			GROUP BY 
				C.BillNumberId,
				C.RowNo,
				C.MATypeId) CI ON CI.BillNumberId=Bill.BillNumberId AND CI.RowNo=Bill.RowNo
LEFT JOIN Ac_CashMoneyItems mitem ON mitem.TypeId=ci.MATypeId
ORDER BY 
	VC.BillDate asc,gr.fullname asc,VC.flowno asc'
EXEC(@SQL)
DROP TABLE #Bill
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAcVoucherExport]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAcVoucherExport
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回凭证查询条件标准凭证导出列表
-- 时间：	2012-11-21
-- 作者：	古丽娟
-- ========================================================================
CREATE PROC Web_QueryAcVoucherExport
(
	@BillNumberID	NVARCHAR(MAX),		--凭证ID字符串
	@OperatorID		VARCHAR(50),		--操作员ID
	@ShowType		INT					--1:凭证分录模式 2：单据格式
)

--@encode$--
AS
SET NOCOUNT ON 
DECLARE 
	@ShowItemsName VARCHAR(5)='',	--是否显示报表辅助核算列
	@AssistLimit	VARCHAR(5)=''	--操作员记忆列显示与否

SELECT @AssistLimit=SUBSTRING(lim,4687,1) FROM LoginUser WHERE etypeid=@operatorid
SELECT @ShowItemsName=ISNULL(Display,'') FROM LoginUserCol WHERE ColDataField='voucherQuery' AND ETypeID=@operatorid

SELECT 
		bill.BillNumberId,
		vc.BillDate,
		CONVERT(VARCHAR(4),vc.FYear)+'年第'+ CONVERT(VARCHAR(2),vc.FPeriod) +'期' FPeriodDate,
		vc.FSerialNum,
		gr.FullName+'-'+CONVERT(VARCHAR(10),vc.FlowNo) FullName,
		bill.RowNo,
		dbo.F_GetSummaryByLimit(bill.ID,@OperatorId,bill.STypeID,bill.Summary) Summary,
		CASE WHEN ISNULL(FA.TypeId,'')='' THEN '****' ELSE at.UserCode END TypeCode,
		CASE WHEN ISNULL(FA.TypeId,'')='' THEN '****' ELSE at.FullName END TypeName,
		cc.fullname currencyName,
		CASE WHEN bill.FAdc=1 THEN bill.FdebitTotalFor ELSE bill.FcreditTotalFor END FAmountFor,
		bill.FDebitTotal,
		bill.FCreditTotal,
		vc.ETypeId,
		CASE WHEN vc.FChecked=1 THEN vc.AuditId ELSE '' END AuditId,
		vc.TallyId,
		vc.recheckId,
		vc.Teller,
		abt.fullname fsettletype,
		bill.FSettleNo,
		vc.AttachFileCount,
		bill.Comment,
		vc.markerror,
		CASE WHEN ISNULL(@ShowItemsName,'')='' AND @AssistLimit=1 AND @ShowType=1 THEN dbo.F_GetAssistCheckItemsName(bill.ID,@OperatorID,bill.STypeId) ELSE '' END checkitemName,
		CASE 
			WHEN FChecked=0 AND IfCheck = 'f' AND ISNULL(MarkError,'')='' AND ISNULL(ReCheckId,'')='' AND IfCheck = 'f' THEN '保存'
			WHEN FChecked=1 AND IfCheck = 'f' AND ISNULL(ReCheckId,'')='' AND ISNULL(ReCheckId,'')='' AND IfCheck = 'f'  THEN '审核'
			WHEN ISNULL(ReCheckId,'')<>'' AND IfCheck = 'f' THEN '已复核'
			WHEN IfCheck='t' THEN '已记账' 
			WHEN FChecked=-1 AND IfCheck = 'f' THEN '作废'
			WHEN ISNULL(MarkError,'')<>'' AND IfCheck = 'f' THEN '标错' END billState,
		VT.FullName vouchertypename
	FROM Ac_Voucher_Bill bill
	LEFT JOIN F_LineAccount(@OperatorID,'') FA ON FA.TypeId=BILL.ATypeId AND FA.StypeId=bill.StypeId
	INNER JOIN f_split(@BillNumberID,',') f ON f.a=bill.BillNumberId
	INNER JOIN Ac_Voucher vc  ON VC.BillNumberId=bill.BillNumberId
	INNER JOIN Ac_Voucher_Group gr on gr.VgId=vc.VgId 
	INNER JOIN Ac_Currency cc ON cc.cid=bill.cid
	INNER JOIN Ac_Account at ON at.TypeId=bill.ATypeId and vc.stypeid=at.stypeid
	INNER JOIN Ac_VoucherType VT ON VT.Id=vc.VoucherType
	LEFT JOIN Ac_BalanceType abt on abt.BtId=bill.fsettletypeid
	ORDER BY vc.FPeriod,bill.BillNumberId,bill.RowNo
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryADistDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryADistDetail]
GO






/*
	作者：谢吉康
	日期：2007-4-5
	描述：调拨分布表
*/
CREATE PROCEDURE Web_QueryADistDetail
(
	@OperatorId		varchar(100),
	@PTypeId		varchar(100),
	@ETypeId		varchar(8000),
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@inKTypeId		varchar(8000),
	@outKTypeId		varchar(8000),
	@aPageNo		int = 1,		-- 仓库信息的翻页
	@bCount			int = 10,
	@strOrderField	varchar(100)='Bil.BillDate',
	@strOrderType   varchar(10)='DESC',
	@stypeid		VARCHAR(8000)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))

IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN (SELECT Typeid FROM F_GetManDetailSType(@OperatorId)) s
	ON A.TypeId=s.Typeid

--部门权限
CREATE TABLE #GetManDTypeID(TYPEID VARCHAR(100))
INSERT INTO #GetManDTypeID(TYPEID) Select TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)


--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT op.typeid FROM dbo.F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID) op --INNER JOIN ptype p ON op.typeid=p.typeid
--职员

DECLARE @Etypelimt INT 
Exec @Etypelimt= GP_CheckLimit @OperatorID,4481
CREATE TABLE #GetManETypeId(TypeId	varchar(100),fullname VARCHAR(100))
IF @Etypelimt=0
	INSERT INTO #GetManETypeId(TypeId,fullname ) 
	SELECT a.TypeId,emp.FullName FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) a 
									INNER JOIN dbo.employee emp ON a.TypeId=emp.typeId
ELSE
	INSERT INTO #GetManETypeId(TypeId,fullname) SELECT a.TypeId,b.FullName FROM F_GetAllBaseTypeId(@ETypeID,3) a INNER JOIN  dbo.employee     b ON a.TypeId=b.typeId

DECLARE @SQL 	varchar(8000),
		@SQL1	varchar(8000)
--处理商品信息
IF @PTypeId = '00000'
	SET @PTypeId = '%'

--仓库权限有效
DECLARE @intRe int
EXEC @intRe=GP_CheckLimit @OperatorID,454

IF @OperatorID = '00001'
	SET @intRe = 1

--处理仓库信息
DECLARE @SonNum int
CREATE TABLE #Stock
(
	TypeId	varchar(100)
)

DECLARE @aFullName 	varchar(256),
		@aPTypeId	varchar(100)

IF @outKTypeId = '00000'
	BEGIN
		IF @intRe = 0
			INSERT INTO #Stock(TypeId)
			SELECT	ka.TypeId	FROM	F_GetManKTypeAll(@OperatorID) ka 
							INNER JOIN  #GetSelectSTypeId ss On ka.STypeId=ss.TypeId
			WHERE	ka.SonNum = 0		AND ka.typeId <> @inKTypeId
		ELSE
			INSERT INTO #Stock(TypeId)
			SELECT	 s.TypeId	FROM	Stock s 
							INNER JOIN  #GetSelectSTypeId ss On s.STypeId=ss.TypeId	
			WHERE	s.SonNum = 0		AND s.typeId <> @inKTypeId
	END
ELSE
	BEGIN
		IF  @intRe = 1	--无效
		BEGIN
			INSERT INTO #Stock(TypeId)
			SELECT s.TypeId	FROM dbo.Stock s
			INNER JOIN  #GetSelectSTypeId ss On s.STypeId=ss.TypeId	
			INNER JOIN 
			(
				SELECT A FROM F_Split(@outKTypeID,',') WHERE A<>@inKTypeId	
			)b
			ON s.typeid LIKE b.A+'%'
			WHERE s.sonnum=0 
				AND s.TypeId <> @inKTypeId	
		END
		ELSE
		BEGIN
			INSERT INTO #Stock(TypeId)
			SELECT S.TypeId	FROM F_GetManKTypeAll(@OperatorID) s
			INNER JOIN (
							SELECT se.typeid FROM stock se INNER JOIN  #GetSelectSTypeId ss On se.STypeId=ss.TypeId	
						) c  ON s.typeid=c.typeid
			INNER JOIN 
			(
				SELECT A FROM F_Split(@outKTypeID,',') WHERE A<>@inKTypeId	
			)b	ON s.typeid LIKE b.A+'%'
			WHERE s.sonnum=0 
				AND s.TypeId <> @inKTypeId	
			
		END	
	END


SET @SQL = '
			SELECT	Bil.BillNumberId,
					Bil.BillDate,
					Bil.BillCode,
					Bil.BillType,
					E.FullName AS EFullName,
					I.ETypeId,
					I.PTypeId,
					Bil.Comment,
					ABS(ISNULL(I.Qty,0)) AS Qty,
					ABS(ISNULL(I.Total,0)) AS Total,
					ABS(CASE
						WHEN ISNULL(I.Qty,0) = 0 THEN 0
						ELSE ISNULL(I.Total,0)/ISNULL(I.Qty,0)		
					END) AS Price,
					0 AS CostTotal,
					0 AS CostPrice,
					Bil.stypeid	,
					i.id as customid		
			FROM 	BillIndex Bil
					inner join MoveBill a  on Bil.BillNumberId = a.BillNumberId
					INNER JOIN InOutStockTable I ON Bil.BillNumberId = I.BillNumberId AND i.PtypeId = a.PtypeId and a.id=i.id
					INNER JOIN #GetSelectSTypeId ss ON Bil.stypeid=ss.typeid 
					INNER JOIN #GetManDTypeID dtype	ON Bil.Dtypeid=dtype.typeid 
					INNER JOIN #GetManPTypeId p  ON I.PTypeId=P.typeid
					INNER JOIN #GetManETypeId e  ON I.ETypeID=e.typeid	
					INNER JOIN #Stock 		  k  ON a.KTypeId2=k.typeid
			WHERE 	I.BillType=17
					AND I.Audited = 1 '
IF @PTypeId = '00000'
	SET @SQL = @SQL + ' AND I.PTypeId LIKE ''%'''
ELSE
	SET @SQL = @SQL + ' AND I.PTypeId LIKE '+char(39)+@PTypeId+'%'+char(39)

	SET @SQL = @SQL + ' AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
						AND Bil.BillDate<='+char(39)+@EndDate+char(39)+' 
						AND a.KTypeId = '+char(39)+@inKTypeId+char(39)+'
						AND I.Qty>=0 '
SET @SQL += ' UNION ALL
			SELECT	Bil.BillNumberId,
					Bil.BillDate,
					Bil.BillCode,
					Bil.BillType,
					E.FullName AS EFullName,
					I.ETypeId,
					I.PTypeId,
					Bil.Comment,
					ABS(ISNULL(I.Qty,0)) AS Qty,
					0 AS Total,
					0 AS Price,
					ABS(ISNULL(I.CostTotal,0)) AS CostTotal,
					ABS(CASE
						WHEN ISNULL(I.Qty,0) = 0 THEN 0
						ELSE ISNULL(I.CostTotal,0)/ISNULL(I.Qty,0)		
					END) AS CostPrice,
					Bil.stypeid	,
					i.id as customid	
			FROM 	BillIndex Bil
					inner join MoveBill a  on Bil.BillNumberId = a.BillNumberId
					INNER JOIN InOutStockTable I ON Bil.BillNumberId = I.BillNumberId AND i.PtypeId = a.PtypeId and a.id=i.id
					INNER JOIN #GetSelectSTypeId ss ON Bil.stypeid=ss.typeid 
					INNER JOIN #GetManDTypeID dtype	ON Bil.Dtypeid=dtype.typeid 
					INNER JOIN #GetManPTypeId p  ON I.PTypeId=P.typeid
					INNER JOIN #GetManETypeId e  ON I.ETypeID=e.typeid	
					INNER JOIN #Stock 		  k  ON a.KTypeId=k.typeid
			WHERE 	I.BillType=17
					AND I.Audited = 1 '
IF @PTypeId = '00000'
	SET @SQL = @SQL + ' AND I.PTypeId LIKE ''%'''
ELSE
	SET @SQL1 = @SQL + ' AND I.PTypeId LIKE '+char(39)+@PTypeId+'%'+char(39)

	SET @SQL = @SQL + ' AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
						AND Bil.BillDate<='+char(39)+@EndDate+char(39)+' 
						AND a.KTypeId2 = '+char(39)+@inKTypeId+char(39)+'
						AND I.Qty<=0 '
SET @SQL1 = ' UNION ALL
			SELECT	Bil.BillNumberId,
					Bil.BillDate,
					Bil.BillCode,
					Bil.BillType,
					E.FullName AS EFullName,
					I.ETypeId,
					I.PTypeId,
					Bil.Comment,
					ABS(ISNULL(I.Qty,0)) AS Qty,
					ABS(ISNULL(I.Total,0)) AS Total,
					ABS(CASE
						WHEN ISNULL(I.Qty,0) = 0 THEN 0
						ELSE ISNULL(I.Total,0)/ISNULL(I.Qty,0)		
					END) AS Price,
					0 AS CostTotal,
					0 AS CostPrice,
					Bil.stypeid	,
					i.id as customid		
			FROM 	BillIndex Bil
					inner join MovebjBill a  on Bil.BillNumberId = a.BillNumberId
					INNER JOIN InOutStockTable I ON Bil.BillNumberId = I.BillNumberId AND i.PtypeId = a.PtypeId and a.id=i.id
					INNER JOIN #GetSelectSTypeId ss ON Bil.stypeid=ss.typeid  
					INNER JOIN #GetManDTypeID dtype	ON Bil.Dtypeid=dtype.typeid 
					INNER JOIN #GetManPTypeId p  ON I.PTypeId=P.typeid
					INNER JOIN #GetManETypeId e  ON I.ETypeID=e.typeid	
					INNER JOIN #Stock 		  k  ON a.KTypeId2=k.typeid
			WHERE 	I.BillType= 21
					AND I.Audited = 1 '
IF @PTypeId = '00000'
	SET @SQL1 = @SQL1 + ' AND I.PTypeId LIKE ''%'''
ELSE
	SET @SQL1 = @SQL1 + ' AND I.PTypeId LIKE '+char(39)+@PTypeId+'%'+char(39)

	SET @SQL1 = @SQL1 + ' AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
						AND Bil.BillDate<='+char(39)+@EndDate+char(39)+' 
						AND a.KTypeId = '+char(39)+@inKTypeId+char(39)+'
						AND I.Qty>=0 '

SET @SQL1 += 'UNION ALL
			SELECT	Bil.BillNumberId,
					Bil.BillDate,
					Bil.BillCode,
					Bil.BillType,
					E.FullName AS EFullName,
					I.ETypeId,
					I.PTypeId,
					Bil.Comment,
					ABS(ISNULL(I.Qty,0)) AS Qty,
					0 AS Total,
					0 AS Price,
					ABS(ISNULL(I.CostTotal,0)) AS CostTotal,
					ABS(CASE
						WHEN ISNULL(I.Qty,0) = 0 THEN 0
						ELSE ISNULL(I.CostTotal,0)/ISNULL(I.Qty,0)		
					END) AS CostPrice,
					Bil.stypeid	,
					i.id as customid	
			FROM 	BillIndex Bil
					inner join MovebjBill a  on Bil.BillNumberId = a.BillNumberId
					INNER JOIN InOutStockTable I ON Bil.BillNumberId = I.BillNumberId AND i.PtypeId = a.PtypeId and a.id=i.id
					INNER JOIN #GetSelectSTypeId ss ON Bil.stypeid=ss.typeid 
					INNER JOIN #GetManDTypeID dtype	ON Bil.Dtypeid=dtype.typeid 
					INNER JOIN #GetManPTypeId p  ON I.PTypeId=P.typeid
					INNER JOIN #GetManETypeId e  ON I.ETypeID=e.typeid	
					INNER JOIN #Stock 		  k  ON a.KTypeId=k.typeid
			WHERE 	I.BillType = 21
					AND I.Audited = 1 '
IF @PTypeId = '00000'
	SET @SQL1 = @SQL1 + ' AND I.PTypeId LIKE ''%'''
ELSE
	SET @SQL1 = @SQL1 + ' AND I.PTypeId LIKE '+char(39)+@PTypeId+'%'+char(39)

	SET @SQL1 = @SQL1 + ' AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
						AND Bil.BillDate<='+char(39)+@EndDate+char(39)+' 
						AND a.KTypeId2 = '+char(39)+@inKTypeId+char(39)+'
						AND I.Qty<=0 '
--PRINT('SELECT B.* FROM ('+@SQL+@SQL1+')B ORDER BY '+@strOrderField+' '+@strOrderType)
--EXEC('SELECT B.* FROM ('+@SQL+@SQL1+')B ORDER BY '+@strOrderField+' '+@strOrderType)


SET @SQL ='SELECT * INTO #Result FROM ('+@SQL+@SQL1+')B ORDER BY '+@strOrderField+' '+@strOrderType +'

			SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
					  FROM #Result a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.customid=csdetail.Detailid
				
				DROP TABLE #Result
			
			   '
	--PRINT (@sql)
	EXEC (@SQL)



DROP TABLE #Stock

DROP TABLE #GetManETypeId,#GetManPTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryADistLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryADistLine]
GO




/*
	作者：谢吉康
	日期：2007-4-5
	描述：调拨分布表
*/
CREATE PROCEDURE Web_QueryADistLine
(
	@OperatorId		varchar(100),
	@PTypeId		varchar(100),
	@ETypeId		varchar(8000),
	@StartDate		datetime,
	@EndDate		datetime,
	@inKTypeId		varchar(8000),
	@outKTypeId		varchar(8000),
	@aPageNo		int = 1,		-- 仓库信息的翻页
	@bCount			int = 10,
	@showTotal		int = 1,
	@showQtyCj		int = 1,
	@stypeid		VARCHAR(8000),
	@ptypeCategoryid VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @stypeid='' 
BEGIN
	SET @stypeid='00000'
END

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))


IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN (SELECT Typeid FROM F_GetManDetailSType(@OperatorId)) s
	ON A.TypeId=s.Typeid

--部门权限
CREATE TABLE #GetManDTypeID(TYPEID VARCHAR(100))
INSERT INTO #GetManDTypeID(TYPEID) Select TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)


--权限范围内的商品线性表
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT a.TypeId FROM dbo.F_LinePC(@OperatorID,@ptypeCategoryid) a 
INNER JOIN dbo.ptype p ON a.TypeId = p.typeId 
WHERE	IsService=0
		AND iscombinationproduct = 0

--权限范围内的职员线性表
DECLARE @Etypelimt INT 
Exec @Etypelimt= GP_CheckLimit @OperatorID,4481
--职员
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
IF @Etypelimt=0
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)
ELSE
		INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeID,3)

--转换时间生成临时表
DECLARE @TableName 	varchar(1000),
		@SQL		varchar(8000)

SET @TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SET @SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		TypeId 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		商品编号 	varchar (200) NULL ,
		商品名称 	varchar (256) NOT NULL
	)'

EXEC(@SQL)

--处理商品信息
IF @PTypeId = '00000'
	SET @PTypeId = '%'

SET @SQL='INSERT '+N'##'+@TableName+'
		SELECT	p.TypeId,
				p.SonNum,
				p.UserCode,
				p.FullName
		FROM	F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+')	p '
IF ISNULL(@ptypeCategoryid,'')<>''
	SET @SQL=@SQL+' inner join #GetManPTypeId b on b.typeid like p.typeid +''%'' '

SET @SQL+='	WHERE 	p.SonNum = 0 
					and p.isservice=0 
					AND p.iscombinationproduct = 0 				
					AND p.TypeId LIKE '+char(39)+@PTypeId+'%'+char(39)+'
		ORDER BY p.UserCode '		
EXEC(@SQL)

--先缩小查询数据的范围
CREATE TABLE #InOutStockTable
(
	PTypeId		varchar(100),
	KTypeId1	varchar(100),
	KTypeId2	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) 
)

DECLARE @StockSQL	VARCHAR(3000)
SET @StockSQL='	
	INSERT INTO #InOutStockTable
	SELECT	I.PTypeId,
			a.KTypeId,
			a.KTypeID2,
			I.Qty,
			I.Total,
			I.CostTotal
	FROM 	InOutStockTable I	
	inner join movebill a on a .BillNumberId=i.BillNumberId AND i.PtypeId = a.PtypeId and a.id=i.id
			INNER JOIN #GetSelectSTypeId ss ON i.stypeid=ss.typeid '
IF @MDtypeid='-99999'
	SET @StockSQL=@StockSQL+' INNER JOIN #GetManDTypeID dtype	ON i.Dtypeid=dtype.typeid  '
	
IF	@MPtypeid='-99999'
	SET @StockSQL=@StockSQL+' INNER JOIN  #GetManPTypeId p	ON 	I.PTypeID=p.typeid '
	
IF	@ETypeId<>'00001' OR @MEtypeid='-99999'	
	SET @StockSQL=@StockSQL+' INNER JOIN #GetManETypeId e	ON 	i.ETypeID=e.typeid '
	
SET @StockSQL=@StockSQL+'
	WHERE 	i.BillDate>='+CHAR(39)+CAST(@StartDate AS VARCHAR(50))+CHAR(39)+'
			AND i.BillDate<='+CHAR(39)+CAST(@EndDate AS VARCHAR(50))+CHAR(39)+'
			AND I.BillType=17
			AND I.Audited = 1 
			AND (a.KTypeId = '+CHAR(39)+@inKTypeId+CHAR(39)+' OR a.KTypeId2 = '+CHAR(39)+@inKTypeId+CHAR(39)+')'
	IF @PTypeID='00000'
	SET @StockSQL=@StockSQL+' AND I.PTypeId LIKE '+CHAR(39)+'%'+CHAR(39)
ELSE
	SET @StockSQL=@StockSQL+' AND I.PTypeId LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)		
SET @StockSQL+=' UNION  ALL		SELECT	I.PTypeId,
			a.KTypeId,
			a.KTypeID2,
			I.Qty,
			I.Total,
			I.CostTotal
	FROM 	
		InOutStockTable I	
	inner join movebjbill a on a .BillNumberId=i.BillNumberId  AND i.PtypeId = i.PtypeId and a.id=i.id
			INNER JOIN #GetSelectSTypeId ss ON i.stypeid=ss.typeid '
IF @MDtypeid='-99999'
	SET @StockSQL=@StockSQL+' INNER JOIN #GetManDTypeID dtype	ON i.Dtypeid=dtype.typeid  '
	
IF	@MPtypeid='-99999'
	SET @StockSQL=@StockSQL+' INNER JOIN  #GetManPTypeId p	ON 	I.PTypeID=p.typeid '
	
IF	@ETypeId<>'00001' OR @MEtypeid='-99999'	
	SET @StockSQL=@StockSQL+' INNER JOIN #GetManETypeId e	ON 	i.ETypeID=e.typeid '
	
SET @StockSQL=@StockSQL+'
	WHERE 	i.BillDate>='+CHAR(39)+CAST(@StartDate AS VARCHAR(50))+CHAR(39)+'
			AND i.BillDate<='+CHAR(39)+CAST(@EndDate AS VARCHAR(50))+CHAR(39)+'
			AND I.BillType=21
			AND I.Audited = 1 
			AND (a.KTypeId = '+CHAR(39)+@inKTypeId+CHAR(39)+' OR a.KTypeId2 = '+CHAR(39)+@inKTypeId+CHAR(39)+')'			

IF @PTypeID='00000'
	SET @StockSQL=@StockSQL+' AND I.PTypeId LIKE '+CHAR(39)+'%'+CHAR(39)
ELSE
	SET @StockSQL=@StockSQL+' AND I.PTypeId LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)
	
--PRINT(@StockSQL)
EXEC(@StockSQL)

--仓库权限有效
DECLARE @intRe int
EXEC @intRe=GP_CheckLimit @OperatorID,454

--处理仓库信息
DECLARE @KTypeId2			varchar(100),
		@KTypeId2FullName	varchar(256)

-- @KTypeId1			varchar(100),		--查询仓库的ID        
--SELECT  @KTypeId1 = TypeId FROM Stock WHERE typeId = @inKTypeId

CREATE TABLE #Stock
(
	TypeId		varchar(100),
	UserCode	varchar(256),
	FullName	varchar(266)
)
IF @outKTypeId = '00000' --全部仓库
	BEGIN
		IF @intRe = 1	--无效
					INSERT INTO #Stock(TypeId,UserCode,FullName)
					SELECT S.TypeId,S.UserCode,S.FullName 
					FROM Stock S	
						INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
					WHERE S.TypeID <> @inKTypeId 
						
						AND S.SonNum = 0 
					ORDER BY S.UserCode
				ELSE
					INSERT INTO #Stock(TypeId,UserCode,FullName)
					SELECT S.TypeId,S.UserCode,S.FullName 
					FROM F_GetManKTypeAll(@OperatorID) S 
							INNER JOIn #GetSelectSTypeId ss ON s.STypeId=ss.TypeId
					WHERE S.TypeID <> @inKTypeId  AND S.SonNum = 0 
					ORDER BY S.UserCode
		END
ELSE
	BEGIN
		SELECT A INTO #SplitKType FROM F_Split(@outKTypeID,',') WHERE A<>@inKTypeId		
		IF  @intRe = 1	--无效
		BEGIN
			INSERT INTO #Stock(TypeId,UserCode,FullName)
			SELECT s.TypeId,s.UserCode,s.FullName 
			FROM dbo.Stock s
			INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
			INNER JOIN #SplitKType b ON s.typeid LIKE b.A+'%'
			WHERE s.sonnum=0 
				AND s.TypeId <> @inKTypeId	
		END
		ELSE
		BEGIN
			INSERT INTO #Stock(TypeId,UserCode,FullName)
			SELECT S.TypeId,S.UserCode,S.FullName 
			FROM F_GetManKTypeAll(@OperatorID) s
			INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
			INNER JOIN  #SplitKType b ON s.typeid LIKE b.A+'%'
			WHERE s.sonnum=0 
				AND s.TypeId <> @inKTypeId	
			
		END
		DROP TABLE #SplitKType	
	END


--运算具体的数据
SET @SQL = '
	DECLARE KCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    #Stock 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@aPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	#Stock
	                ORDER BY UserCode
	            )
	    ORDER BY UserCode '

EXEC(@SQL)

OPEN KCursor

FETCH NEXT FROM KCursor INTO @KTypeId2,@KTypeId2FullName

WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @showTotal = 1
			BEGIN
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '入库数量]  NUMERIC(24, 10)  DEFAULT(''0'') 
							ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '入库金额]  NUMERIC(24, 10)  DEFAULT(''0'') '
				EXEC(@SQL)
				
		
				SET @SQL =' UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'入库数量]= ISNULL(ABS(B.Qty),0),
									['+@KTypeId2FullName+'入库金额]= ISNULL(ABS(B.Total),0)
							FROM	'+N'##'+@TableName+' A
							INNER JOIN (
									SELECT	PTypeId,
											SUM(Qty) AS Qty,
											SUM(Total) AS Total
									FROM	#InOutStockTable
									WHERE	KTypeId1 = '+char(39)+@inKTypeId+char(39)+'
											AND KTypeId2 = '+char(39)+@KTypeId2+char(39)+'
											AND Qty>=0
									GROUP BY PTypeId
							)B ON B.PTypeId=A.TypeId'
				EXEC(@SQL)
				
				--修改表结构
				SET @SQL =' ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '出库数量]  NUMERIC(24, 10)  DEFAULT(''0'')
							ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '出库金额]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)
						
				SET @SQL =' UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'出库数量]= ISNULL(ABS(B.Qty),0),
									['+@KTypeId2FullName+'出库金额]= ISNULL(ABS(B.Total),0)
							FROM	'+N'##'+@TableName+' A
							INNER JOIN (
									SELECT	PTypeId,
											SUM(Qty) AS Qty,
											SUM(CostTotal) AS Total
									FROM	#InOutStockTable
									WHERE	KTypeId1 = '+char(39)+@KTypeId2+char(39)+'
											AND KTypeId2 = '+char(39)+@inKTypeId+char(39)+'
											AND Qty<=0
									GROUP BY PTypeId
							)B ON B.PTypeId=A.TypeId'
				EXEC(@SQL)
						
			END
		ELSE
			BEGIN
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '入库数量]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)
		
				SET @SQL = 'UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'入库数量]= ISNULL(ABS(B.Qty),0)
							FROM	'+N'##'+@TableName+' A
							LEFT JOIN (
									SELECT	PTypeId,
											SUM(Qty) AS Qty,
											SUM(Total) AS Total
									FROM	#InOutStockTable
									WHERE	KTypeId1 = '+char(39)+@inKTypeId+char(39)+'
											AND KTypeId2 = '+char(39)+@KTypeId2+char(39)+'
											AND Qty>=0
									GROUP BY PTypeId
							)B ON LEFT(B.PTypeId,LEN(A.TypeID))=A.TypeId'
				EXEC(@SQL)
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '出库数量]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)
		
				SET @SQL = 'UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'出库数量]= ISNULL(ABS(B.Qty),0)
							FROM	'+N'##'+@TableName+' A
							LEFT JOIN (
									SELECT	PTypeId,
											SUM(Qty) AS Qty,
											SUM(Total) AS Total
									FROM	#InOutStockTable
									WHERE	KTypeId1 = '+char(39)+@KTypeId2+char(39)+'
											AND KTypeId2 = '+char(39)+@inKTypeId+char(39)+'
											AND Qty<=0
									GROUP BY PTypeId
							)B ON LEFT(B.PTypeId,LEN(A.TypeID))=A.TypeId'
				EXEC(@SQL)
			END

		IF @showQtyCj = 1
			BEGIN
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '调数量差]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)
		
				SET @SQL = 'UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'调数量差]= ISNULL(ABS(['+@KTypeId2FullName+'入库数量]),0) - ISNULL(ABS(['+@KTypeId2FullName+'出库数量]),0)
							FROM	'+N'##'+@TableName
		
				EXEC(@SQL)
			END

		FETCH NEXT FROM KCursor INTO @KTypeId2,@KTypeId2FullName
	END

CLOSE KCursor

DEALLOCATE KCursor


EXEC('SELECT * FROM '+N'##'+@TableName)

--删除临时表
SET @SQL = 'DROP TABLE #Stock,#InOutStockTable,'+N'##'+@TableName
EXEC(@SQL)


DROP TABLE #GetManETypeId,#GetManPTypeId,#GetSelectSTypeId,#GetManDTypeID















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryADistList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryADistList]
GO



/*
	作者：谢吉康
	日期：2007-4-5
	描述：调拨分布表
---------------------------------------------------------
	作者：WANG WEI	
	日期：2010-7-9
	描述：重写了调拨分布表的查询仓库 #1
*/
CREATE PROCEDURE Web_QueryADistList
(
	@OperatorId		varchar(100),--用户权限
	@PTypeId		varchar(100),-- 商品ID
	@ETypeId		varchar(8000),-- 职员ID
	@StartDate		datetime,	--开始时间
	@EndDate		datetime,	--结束时间
	@inKTypeId		varchar(8000), --入库仓库
	@outKTypeId		varchar(8000), --出库仓库
	@aPageNo		int = 1,		-- 仓库信息的翻页
	@bCount			int = 10,
	@showTotal		int = 1,
	@showQtyCj		int = 1,
	@stypeid		VARCHAR(8000)  ,
	@ptypeCategoryid VARCHAR(max)
	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------	------------------------------------------
IF @stypeid='' 
BEGIN
	SET @stypeid='00000'
END

--选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))


IF @MStypeid='00000'
	INSERT INTO #GetSelectSTypeId(TypeId) 
		SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A
ELSE
	INSERT INTO #GetSelectSTypeId(TypeId) 
	SELECT A.Typeid FROM F_GetAllBaseTypeId(@stypeid,11) AS A  INNER JOIN (SELECT Typeid FROM F_GetManDetailSType(@OperatorId)) s
	ON A.TypeId=s.Typeid

--部门权限
CREATE TABLE #GetManDTypeID(TYPEID VARCHAR(100))
INSERT INTO #GetManDTypeID(TYPEID) Select TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

--权限范围内的商品线性表
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT a.TypeId FROM dbo.F_LinePC(@OperatorID,@ptypeCategoryid) a 
INNER JOIN dbo.ptype p ON a.TypeId = p.typeId 
WHERE	IsService=0
		AND iscombinationproduct = 0
		




--检测经手人权限是否有效
DECLARE @limt INT 
Exec @limt= GP_CheckLimit @OperatorID,4481

--权限范围内的职员线性表
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @limt=0
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)
ELSE
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeID,3)


--转换时间生成临时表
DECLARE @TableName 	varchar(1000),
		@SQL		varchar(8000),
		@PLen		varchar(100)

IF @PTypeId = '00000'
	SET @PLen = '5'
ELSE
	SET @PLen = LEN(@PTypeId) + 5

SET @TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SET @SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		TypeId 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		商品编号 	varchar (200) NULL ,
		商品名称 	varchar (256) NOT NULL
	)'

EXEC(@SQL)



--处理商品信息
DECLARE @CruSonNum INT --当前商品节点数
SELECT TOP 1 @CruSonNum = SonNum FROM PType WHERE TypeId = @PTypeId

DECLARE @SQLPtype VARCHAR(2000)
SET @SQLPtype='
		INSERT '+N'##'+@TableName+'
		SELECT     DISTINCT
		            a.TypeId,
					a.SonNum,
					a.UserCode,
					a.FullName
		FROM	F_GetManPTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') a
		'
IF ISNULL(@ptypeCategoryid,'')<>''
	SET @SQLPtype=@SQLPtype+' inner join #GetManPTypeId b on b.typeid like a.typeid +''%'' '
SET @SQLPtype= @SQLPtype+' where a.IsService=0 AND a.iscombinationproduct = 0'
IF @CruSonNum = 0
	SET @SQLPtype=@SQLPtype+' and a.SonNum = 0 AND a.iscombinationproduct = 0 AND a.TypeId = '+char(39)+@PTypeId+char(39)+''		
ELSE
	SET @SQLPtype=@SQLPtype+' AND a.iscombinationproduct = 0 and a.ParId = '+char(39)+@PTypeId+char(39)+''

SET @SQLPtype=@SQLPtype+' ORDER BY a.TypeId '		
			
EXEC(@SQLPtype)

--先缩小查询数据的范围
CREATE TABLE #InOutStockTable
(
	PTypeId		varchar(100),
	KTypeId1	varchar(100),
	KTypeId2	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) 
)

CREATE TABLE #TempInOutStockTable
(
	PTypeId		varchar(100),
	KTypeId1	varchar(100),
	KTypeId2	varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) 
)

DECLARE @StockSQL	VARCHAR(3000)
SET @StockSQL='	
	INSERT INTO #InOutStockTable
	SELECT  	
	        I.PTypeId,
			a.ktypeid , 
			a.ktypeid2,
			I.Qty,
			I.Total,
			I.CostTotal
	FROM    InOutStockTable i
			inner join movebill a on a .BillNumberId=i.BillNumberId  AND i.PtypeId = a.PtypeId and a.id=i.id
			INNER JOIN #GetSelectSTypeId ss ON i.stypeid=ss.typeid '
IF	@MPtypeid='-99999'
	SET @StockSQL=@StockSQL+' INNER JOIN  #GetManPTypeId p	ON 	I.PTypeID=p.typeid '
	
IF	@ETypeId<>'00001' OR @MEtypeid='-99999'	
	SET @StockSQL=@StockSQL+' INNER JOIN #GetManETypeId e	ON 	i.ETypeID=e.typeid '
	
SET @StockSQL=@StockSQL+'
	WHERE 	I.BillType =17
			AND I.Audited = 1
			AND i.BillDate>='+CHAR(39)+CAST(@StartDate AS VARCHAR(50))+CHAR(39)+'
			AND i.BillDate<='+CHAR(39)+CAST(@EndDate AS VARCHAR(50))+CHAR(39)

IF @PTypeID='00000'
	SET @StockSQL=@StockSQL+' AND I.PTypeId LIKE '+CHAR(39)+'%'+CHAR(39)
ELSE
	SET @StockSQL=@StockSQL+' AND I.PTypeId LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)
	
	
SET @StockSQL+='	
	 UNION  ALL	
     SELECT  
            I.PTypeId,
			a.ktypeid ,
			a.ktypeid2,
			I.Qty,
			I.Total,
			I.CostTotal
	FROM    InOutStockTable i
			Inner Join MoveBjBill a on a .BillNumberId=i.BillNumberId  AND i.PtypeId = a.PtypeId and a.id=i.id
			INNER JOIN #GetSelectSTypeId ss ON i.stypeid=ss.typeid '
IF	@MPtypeid='-99999'
	SET @StockSQL=@StockSQL+' INNER JOIN  #GetManPTypeId p	ON 	I.PTypeID=p.typeid '
	
IF	@ETypeId<>'00001' OR @MEtypeid='-99999'	
	SET @StockSQL=@StockSQL+' INNER JOIN #GetManETypeId e	ON 	i.ETypeID=e.typeid '
	
SET @StockSQL=@StockSQL+'
	WHERE 	I.BillType =21
			AND I.Audited = 1
			AND i.BillDate>='+CHAR(39)+CAST(@StartDate AS VARCHAR(50))+CHAR(39)+'
			AND i.BillDate<='+CHAR(39)+CAST(@EndDate AS VARCHAR(50))+CHAR(39)

IF @PTypeID='00000'
	SET @StockSQL=@StockSQL+' AND I.PTypeId LIKE '+CHAR(39)+'%'+CHAR(39)
ELSE
	SET @StockSQL=@StockSQL+' AND I.PTypeId LIKE '+CHAR(39)+@PTypeId+'%'+CHAR(39)
	
	
	PRINT @StockSQL
EXEC(@StockSQL)


--INSERT INTO #TempInOutStockTable
--	SELECT  DISTINCT	
--	        PTypeId,
--			ktypeid1 , 
--			ktypeid2,
--			Qty,
--			Total,
--			CostTotal
--	FROM    #InOutStockTable 
--	ORDER By PTypeId

--delete from  #InOutStockTable 

--INSERT INTO #InOutStockTable
--	SELECT  DISTINCT	
--	        PTypeId,
--			ktypeid1 , 
--			ktypeid2,
--			Qty,
--			Total,
--			CostTotal
--	FROM    #TempInOutStockTable 


--select * from #InOutStockTable
--return

--仓库权限有效
DECLARE @intRe int
EXEC @intRe=GP_CheckLimit @OperatorID,454

--处理仓库信息
DECLARE @KTypeId2			varchar(100),
		@KTypeId2FullName	varchar(256)

-- @KTypeId1			varchar(100),		--查询仓库的ID        
--SELECT  @KTypeId1 = TypeId FROM Stock WHERE typeId = @inKTypeId


CREATE TABLE #Stock
(
	TypeId		varchar(100),
	UserCode	varchar(256),
	FullName	varchar(266)
)
IF @outKTypeId = '00000' --全部仓库
	BEGIN
		IF @intRe = 1	--无效
			INSERT INTO #Stock(TypeId,UserCode,FullName)
			SELECT S.TypeId,S.UserCode,S.FullName 
			FROM Stock S	
				INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
			WHERE S.TypeID <> @inKTypeId 
				
				AND S.SonNum = 0 
			ORDER BY S.UserCode
		ELSE
			INSERT INTO #Stock(TypeId,UserCode,FullName)
			SELECT S.TypeId,S.UserCode,S.FullName 
			FROM F_GetManKTypeAll(@OperatorID) S 
					INNER JOIn #GetSelectSTypeId ss ON s.STypeId=ss.TypeId
			WHERE S.TypeID <> @inKTypeId  AND S.SonNum = 0 
			ORDER BY S.UserCode
	END
ELSE
	BEGIN
		SELECT A INTO #SplitKType FROM F_Split(@outKTypeID,',') WHERE A<>@inKTypeId		
		IF  @intRe = 1	--无效
		BEGIN
			INSERT INTO #Stock(TypeId,UserCode,FullName)
			SELECT s.TypeId,s.UserCode,s.FullName 
			FROM dbo.Stock s
			INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
			INNER JOIN #SplitKType b ON s.typeid LIKE b.A+'%'
			WHERE s.sonnum=0 
				AND s.TypeId <> @inKTypeId	
		END
		ELSE
		BEGIN
			INSERT INTO #Stock(TypeId,UserCode,FullName)
			SELECT S.TypeId,S.UserCode,S.FullName 
			FROM F_GetManKTypeAll(@OperatorID) s
			INNER JOIN #GetSelectSTypeId ss ON s.STypeID=ss.TypeId
			INNER JOIN  #SplitKType b ON s.typeid LIKE b.A+'%'
			WHERE s.sonnum=0 
				AND s.TypeId <> @inKTypeId	
			
		END
		DROP TABLE #SplitKType	
	END

--运算具体的数据
SET @SQL = '
	DECLARE KCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    #Stock 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@aPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	#Stock
	                ORDER BY UserCode
	            )
	    ORDER BY UserCode '
--print @sql
EXEC(@SQL)

DECLARE @tempSQL varchar(1000)



OPEN KCursor

FETCH NEXT FROM KCursor INTO @KTypeId2,@KTypeId2FullName


WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @showTotal = 1
			BEGIN
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '入库数量]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)		
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '入库金额]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)	

				SET @SQL = 'UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'入库数量]= ISNULL(ABS(B.Qty),0),
									['+@KTypeId2FullName+'入库金额]= ISNULL(ABS(B.Total),0)
							FROM	'+N'##'+@TableName+' A
							INNER JOIN (
									SELECT	X.TypeId AS PTypeId,
											ISNULL(SUM(M.Qty),0) AS Qty,
											ISNULL(SUM(M.Total),0) AS Total
									FROM	'+N'##'+@TableName+' X
									INNER JOIN (
												SELECT 	SUBSTRING(PTypeId,1,'+@PLen+') AS PTypeId,
														SUM(Qty) AS Qty,
														SUM(Total) AS Total
												FROM	#InOutStockTable
												WHERE	KTypeId1 = '+char(39)+@inKTypeId+char(39)+'
														AND KTypeId2 = '+char(39)+@KTypeId2+char(39)+'
														AND Qty>=0
												GROUP BY SUBSTRING(PTypeId,1,'+@PLen+')
									)M ON M.PTypeId=X.TypeId
									GROUP BY X.TypeId
							)B ON B.PTypeId=A.TypeId'
				EXEC(@SQL)
				
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '出库数量]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '出库金额]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)
		
				SET @SQL = 'UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'出库数量]= ISNULL(ABS(B.Qty),0),
									['+@KTypeId2FullName+'出库金额]= ISNULL(ABS(B.Total),0)
							FROM	'+N'##'+@TableName+' A
							INNER JOIN (
									SELECT	X.TypeId AS PTypeId,
											ISNULL(SUM(M.Qty),0) AS Qty,
											ISNULL(SUM(M.Total),0) AS Total
									FROM	'+N'##'+@TableName+' X
									INNER JOIN (
												SELECT 	SUBSTRING(PTypeId,1,'+@PLen+') AS PTypeId,
														SUM(Qty) AS Qty,
														SUM(CostTotal) AS Total
												FROM	#InOutStockTable
												WHERE	KTypeId1 = '+char(39)+@KTypeId2+char(39)+'
														AND KTypeId2 = '+char(39)+@inKTypeId+char(39)+'
														AND Qty<=0
												GROUP BY SUBSTRING(PTypeId,1,'+@PLen+')
									)M ON M.PTypeId=X.TypeId
									GROUP BY X.TypeId
							)B ON B.PTypeId=A.TypeId'
				EXEC(@SQL)
			END
		ELSE
			BEGIN
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '入库数量]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)	
				SET @SQL = 'UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'入库数量]= ISNULL(ABS(B.Qty),0)							
							FROM	'+N'##'+@TableName+' A
							LEFT JOIN (
									SELECT	X.TypeId AS PTypeId,
											ISNULL(SUM(M.Qty),0) AS Qty,
											ISNULL(SUM(M.Total),0) AS Total
									FROM	'+N'##'+@TableName+' X
									LEFT JOIN (
												SELECT 	PTypeId,
														SUM(Qty) AS Qty,
														SUM(Total) AS Total
												FROM	#InOutStockTable
												WHERE	KTypeId1 = '+char(39)+@inKTypeId+char(39)+'
														AND KTypeId2 = '+char(39)+@KTypeId2+char(39)+'
														AND Qty>=0
												GROUP BY PTypeId
									)M ON LEFT(M.PTypeId,LEN(X.TypeID))=X.TypeId
									GROUP BY X.TypeId
							)B ON LEFT(B.PTypeId,LEN(A.TypeID))=A.TypeId'
				EXEC(@SQL)
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '出库数量]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)
				SET @SQL = 'UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'出库数量]= ISNULL(ABS(B.Qty),0)
							FROM	'+N'##'+@TableName+' A
							LEFT JOIN (
									SELECT	X.TypeId AS PTypeId,
											ISNULL(SUM(M.Qty),0) AS Qty,
											ISNULL(SUM(M.Total),0) AS Total
									FROM	'+N'##'+@TableName+' X
									LEFT JOIN (
												SELECT 	PTypeId,
														SUM(Qty) AS Qty,
														SUM(Total) AS Total
												FROM	#InOutStockTable
												WHERE	KTypeId1 = '+char(39)+@KTypeId2+char(39)+'
														AND KTypeId2 = '+char(39)+@inKTypeId+char(39)+'
														AND Qty<=0
												GROUP BY PTypeId
									)M ON LEFT(M.PTypeId,LEN(X.TypeID))=X.TypeId
									GROUP BY X.TypeId
							)B ON LEFT(B.PTypeId,LEN(A.TypeID))=A.TypeId'
				EXEC(@SQL)
			END
		
		IF @showQtyCj = 1
			BEGIN
				--修改表结构
				SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @KTypeId2FullName + '调数量差]  NUMERIC(24, 10)  DEFAULT(''0'')'
				EXEC(@SQL)
		
				SET @SQL = 'UPDATE	'+N'##'+@TableName+'
							SET		['+@KTypeId2FullName+'调数量差]= CASE when ISNULL(ABS(['+@KTypeId2FullName+'入库数量]),0) - ISNULL(ABS(['+@KTypeId2FullName+'出库数量]),0)=0 then NULL ELSE  ISNULL(ABS(['+@KTypeId2FullName+'入库数量]),0) - ISNULL(ABS(['+@KTypeId2FullName+'出库数量]),0) END 
							FROM	'+N'##'+@TableName
		
				EXEC(@SQL)
			END

		FETCH NEXT FROM KCursor INTO @KTypeId2,@KTypeId2FullName
	END

CLOSE KCursor
DEALLOCATE KCursor

EXEC('SELECT DISTINCT * FROM '+N'##'+@TableName)

--删除临时表
SET @SQL = 'DROP TABLE #Stock,#InOutStockTable,#TempInOutStockTable,'+N'##'+@TableName
EXEC(@SQL)

DROP TABLE #GetManETypeId,#GetManPTypeId,#GetSelectSTypeId,#GetManDTypeID
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAllAssistItemsDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Web_QueryAllAssistItemsDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	查询辅助核算类型明细数据
-- 时间：	2015-10-12
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryAllAssistItemsDetail
(
	@Ascids			INT,			--类别ID
	@ParId			VARCHAR(50),	--父级ID
	@Query			VARCHAR(200),	--查找编号或者名称
	@OperatorID		VARCHAR(50)		--操作员ID
)

--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)=''
IF(@Ascids=1)--分支机构
	BEGIN
		SET @SQL='
		SELECT 
			Detail.TypeId,
			Detail.UserCode,
			Detail.FullName,
			Detail.leveal,
			Detail.sonnum,
			Detail.parid
		FROM SType Detail
		INNER JOIN dbo.F_GetManSTypeAll('''+@operatorid+''') F ON F.typeid=Detail.TypeId'
		
	END
ELSE IF(@Ascids=2)--部门
	BEGIN
		SET @SQL='
		SELECT 
			Detail.TypeId,
			Detail.UserCode,
			Detail.FullName,
			Detail.leveal,
			Detail.sonnum,
			Detail.parid
		FROM Department Detail
		INNER JOIN dbo.F_GetManDTypeAll('''+@operatorid+''') F ON F.typeid=Detail.TypeId'
	END
ELSE IF(@Ascids=3)--职员
	BEGIN
		SET @SQL='
		SELECT 
			Detail.TypeId,
			Detail.UserCode,
			Detail.FullName,
			Detail.leveal,
			Detail.sonnum,
			Detail.parid
		FROM employee Detail
		INNER JOIN dbo.F_GetManETypeAll('''+@operatorid+''') F ON F.typeid=Detail.TypeId'
	END
ELSE IF(@Ascids=4)--往来单位
	BEGIN
		SET @SQL='
		SELECT 
			Detail.TypeId,
			Detail.UserCode,
			Detail.FullName,
			Detail.leveal,
			Detail.sonnum,
			Detail.parid
		FROM BType Detail
		INNER JOIN dbo.F_GetManBTypeAll('''+@operatorid+''') F ON F.typeid=Detail.TypeId'
	END
ELSE --自定义辅助核算
	BEGIN
		SET @SQL='
		SELECT 
			Detail.TypeId,
			Detail.UserCode,
			Detail.FullName,
			Detail.leveal,
			Detail.sonnum,
			Detail.parid
		FROM Ac_Assist_CheckItemsDetail Detail
		INNER JOIN dbo.F_GetAllAssistCheckItemsDetail('''','+CAST(@Ascids AS VARCHAR(5))+','''+@operatorid+''') F ON F.typeid=Detail.TypeId'
	END
IF ISNULL(@ParId,'')<>''
	BEGIN
		SET @SQL+=' AND Detail.parid='''+@ParId+''''
	END
ELSE 
	BEGIN
		IF ISNULL(@Query,'')<>''
			BEGIN
				SET @SQL+=' AND (Detail.UserCode LIKE ''%'+@Query+'%'' OR Detail.FullName LIKE ''%'+@Query+'%'') AND Detail.sonnum=0'
			END
		ELSE 
			BEGIN
				IF ISNULL(@ParId,'')='' AND ISNULL(@Query,'')=''
					BEGIN
						IF(@Ascids=3)
							SET @SQL+=' AND Detail.leveal=2'
						ELSE 
							SET @SQL+=' AND Detail.leveal=1'
					END
			END
	END
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAllotContinuousPrintDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryAllotContinuousPrintDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	修改者：韩林
	日期：2012-02-01
	描述：连续打印查询明细
*/

CREATE PROCEDURE Web_QueryAllotContinuousPrintDetail
(
	@billnumberids varchar(max),
	@BillType	varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON
	
SELECT
        a.ID,
    	a.billnumberid,
		Qty =CASE WHEN a.isUnit2 = 1 THEN
				CASE WHEN b.UnitRate1 <> 0 THEN
					CAST( a.Qty/b.UnitRate1 AS  NUMERIC(24, 10)  ) 
				ELSE a.Qty END 
			 ELSE a.Qty END,
		a.Comment AS base,
		IsUnit2 = CASE WHEN a.IsUnit2 = 1 AND b.UnitRate1 <> 0
							 THEN a.IsUnit2
					ELSE 0 END,
		accountqty=isnull((select sum(qty) from GoodsStocks where ptypeid=a.ptypeid and ktypeid in (select ktypeid from billindex where billnumberid=a.BillNumberId)),0),
		Price = CASE WHEN a.isUnit2 = 1 AND b.UnitRate1 <> 0 THEN
						 CAST(a.Price * b.UnitRate1 AS  NUMERIC(24, 10) ) 
				ELSE a.Price END,
		a.Total,
		a.NQty,
		a.InputCostPrice,
		a.ProduceDate,
		a.ValidDate,
		a.GoodsNumber,		
		b.typeid as ptypeid,
		b.UserCode,
		b.FullName,
		b.Unit1,
		b.UnitRate1,
		b.EntryCode,
		b.Standard,
		b.Type,
		b.Area,
		b.SerialCount,
		b.ValidDays,
		b.IfSerial,
		b.usefullifeday,
	    bindex.billtype,
	    f.UnitsType,
		f.unitid,
		f.unit,
		a.unitrate,
	    (select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname1,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname2,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname3,
		(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate1,
		(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate2,
		(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate3,
		f.nunitid,
	(select FullName from PType_Units where  PType_Units.UnitsId=a.NUnitID) as nunit,
		f.rate,
	    a.munitid,
		(select FullName from PType_Units where  PType_Units.UnitsId=a.munitid) as munit,
		f.stockmunitrate AS munitrate,
		a.mqty,
		(select fullname from STOCK where typeId=a.ktypeid) as kfullname,
		(select fullname from STOCK where typeId=a.ktypeid2) as kfullname2,
	     itemname= CASE WHEN a.IsCombined = 0  THEN
        (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
         ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
	     iscombined=a.IsCombined,
	     (select fullname from CargoType where CargoID=a.InCargoId) as incargospace,
	     (select fullname from CargoType where CargoID=a.OutCargoId) as outcargospace,
		cast('' as varchar(50)) as unitrelation,
		cast('' as varchar(50)) as assistantunit,
		cast('' as varchar(50)) as assistantunit1
FROM MoveBill a
INNER JOIN	dbo.PType b ON a.PTypeID = b.TypeID
INNER JOIN BillIndex bindex ON bindex.BillNumberId=a.BillNumberId
LEFT  JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = b.typeid
WHERE a.BillNumberId IN (select * from f_split(@billnumberids,','))
ORDER BY a.ID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_QueryAllowOrderFiled]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAllowOrderFiled
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	得到凭证查询 可以用来排序的字段
-- 时间：	2013-06-27
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryAllowOrderFiled
--@encode$--
AS
SET NOCOUNT ON 
SELECT 'billdate' typeid  ,'日期'  fullname
UNION ALL
SELECT 'fperioddate' typeid  ,'期间'  fullname
UNION ALL
SELECT 'billstate' typeid  ,'状态'  fullname
UNION ALL
SELECT 'vouchertypename' typeid  ,'凭证类型'  fullname
UNION ALL
SELECT 'fullname' typeid  ,'凭证字号'  fullname
UNION ALL
SELECT 'rowno' typeid  ,'分录号'  fullname
UNION ALL
SELECT 'summary' typeid  ,'摘要'  fullname
UNION ALL
SELECT 'typecode' typeid  ,'科目编号'  fullname
UNION ALL
SELECT 'typename' typeid  ,'科目名称'  fullname
UNION ALL
SELECT 'currencyname' typeid  ,'币种'  fullname
UNION ALL
SELECT 'famountfor' typeid  ,'原币'  fullname
UNION ALL
SELECT 'fdebittotal' typeid  ,'借方'  fullname
UNION ALL
SELECT 'fcredittotal' typeid  ,'贷方'  fullname
UNION ALL
SELECT 'etypeid' typeid  ,'制单'  fullname
UNION ALL
SELECT 'auditid' typeid  ,'审核'  fullname
UNION ALL
SELECT 'recheckid' typeid  ,'复核'  fullname
UNION ALL
SELECT 'tallyid' typeid  ,'记账'  fullname
UNION ALL
SELECT 'fsettletype' typeid  ,'结算方式'  fullname
UNION ALL
SELECT 'fsettleno' typeid  ,'结算号'  fullname
UNION ALL
SELECT 'attachfilecount' typeid  ,'附件数'  fullname
UNION ALL
SELECT 'comment' typeid  ,'备注'  fullname
UNION ALL
SELECT 'markerror' typeid  ,'标错原因'  fullname



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_QueryArApAuditAccountDetail]') AND OBJECTPROPERTY(ID,N'ISPROCEDURE')=1)
DROP PROCEDURE Web_QueryArApAuditAccountDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：LUDALIN
	日期：2013-11-26
	描述：往来对账明细表
*/
CREATE PROCEDURE Web_QueryArApAuditAccountDetail
(
    @OperatorId				VARCHAR(MAX),	--操作员ID
	@StartDate				VARCHAR(10),	--开始日期
	@EndDate				VARCHAR(10),	--截止日期
	@STypeId				VARCHAR(MAX),	--分支机构
	@BTypeId				VARCHAR(MAX),	--结算单位
	@Cid					VARCHAR(10),	--币种
	@IsDetail				VARCHAR(10),	--是否按展开明细
	@BillType				VARCHAR(MAX),	--单据类型
	@WhichDetail			VARCHAR(10),	--当前查询类型-'P':商品；'A'：账户；'B':单据
	@queryinvoice			INT,			--统计应收暂估
	@IsAccountDate			int,			--是否按对账日过滤
	@QueryAccountDate		int,			--报警薄读取对账日期预警
	@isLoginHit				INT=0,			--报警簿是否需要红色提示
	@IsShowReconciliation	BIT=0			--是否对账信息1：显示对账过数据 0 隐藏对账过数据
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--判断版本
DECLARE @proinfo int
SELECT @proinfo=subvalue FROM sysdata where subname='proinfo'

--处理币种
SET @Cid=ISNULL(@Cid,0)

--查询单据类型

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(50))
CREATE CLUSTERED INDEX CIX_STypeId ON #GetManSTypeId(Typeid)

INSERT INTO #GetManSTypeId(TypeId) 
SELECT A.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)a
INNER JOIN SType_UserConfig U ON A.TypeId=U.StypeId 
WHERE U.Value=1

--结算单位
CREATE TABLE #GetManBTypeId
(
	TypeId			VARCHAR(50), 
	dzdays			INT,
	dzwarningdays	INT,
	fkdzdays		INT,
	fkdzwarningdays INT
)
CREATE CLUSTERED INDEX CIX_BTypeId ON #GetManBTypeId(Typeid)

INSERT INTO #GetManBTypeId(TypeId,dzdays,dzwarningdays,fkdzdays,fkdzwarningdays) 
SELECT A.TypeId,b.dzdays,b.dzwarningdays,b.fkdzdays,b.fkdzwarningdays 
FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)  A
INNER JOIN BTYPE B ON A.Typeid=b.typeid
	
	
IF ISNULL(@BillType,'')=''
	SET @BillType='0' 
-------------单据类型参数处理--------------------
--只有在按照商品明细显示的时候才有全部单据类型，否则，不应该有
IF @WhichDetail='B'
BEGIN
	SET @BillType=REPLACE(@BillType,'126','0')
	SET @BillType=REPLACE(@BillType,'139','0')
END

IF @WhichDetail='A' 
BEGIN
	SET @BillType=REPLACE(@BillType,'126','0')
	SET @BillType=REPLACE(@BillType,'139','0')
END

----------==============================================查询主体=====BEGIN==========================----------------------------
--思路:动态查询方式
--为了显示方便，默认将期初的billtype字段设计为-1，将小计的billtype 字段设计为-10
--
----------==========================================================================================-----------------------------
DECLARE @CREATESQL	VARCHAR(MAX),--表创建语句1
		@CREATESQL2	VARCHAR(MAX),--表创建语句2
		@PTYPEDETAIL VARCHAR(MAX),--商品明细语句
		@zgnid		varchar(10)  --应收暂估项目id
	
SElECT @zgnid=NID FROM Ac_Items WHERE UserCode='2122' 
IF @queryinvoice<>1
	SET @zgnid=-1
--统计应收暂估
IF @queryinvoice=1
	SET @BillType=@BillType+',400,401,57'
IF @QueryAccountDate=1
BEGIN
	SET  @IsDetail = 'True'
END

DECLARE @arBillType VARCHAR(1000)='11,12,45,160,148,149,141,93,85,213,167,168,172,116,115,181,405,4,189,414,2,46'
IF EXISTS(SELECT SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr' AND SubValue='1')
BEGIN
	 SET @arBillType+=',36'
END
CREATE TABLE #BillType(BillType INT)INSERT INTO #BillType SELECT a FROM f_split(@BillType,',')

--统计开票
CREATE TABLE #invoiceQty
(
	id	INT,
	ptypeid VARCHAR(50),
	billnumberid NUMERIC(24,10),
	billtype INT,
	uninvoiceqty NUMERIC(24,10),
	uninvoicemoney NUMERIC(24,10)
)
CREATE CLUSTERED INDEX CIX_InVoiceQty_Id ON #invoiceQty(id,ptypeid,billnumberid)

INSERT INTO #invoiceQty
(
	id,
	ptypeid,
	billnumberid,
	billtype,
	uninvoiceqty,
	uninvoicemoney
) 
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
		400,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN  @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
			 ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
			 END  /*本币未开票金额(含税)*/
FROM AppraisalBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    401,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN  @Cid=0 THEN ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
			  ELSE  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
			  END  /*本币未开票金额(含税)*/
		
FROM AppraisalBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    402,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
		END  /*本币未开票金额(含税)*/
FROM SendBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    403,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END   /*本币未开票金额(含税)*/
FROM SendBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	

UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    305,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)   
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)   
		END /*本币未开票金额(含税)*/
FROM retailbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    215,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
		END  /*本币未开票金额(含税)*/
FROM RetailBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    11,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
		END  /*本币未开票金额(含税)*/
FROM salebill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    45,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END   /*本币未开票金额(含税)*/
FROM salebackbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END   /*本币未开票金额(含税)*/
FROM salegoodsexchangebill a
WHERE a.InOrOut='I'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
		ELSE  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
		END  /*本币未开票金额(含税)*/
FROM salegoodsexchangebill a
WHERE a.InOrOut='O'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    141,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END    /*本币未开票金额(含税)*/
FROM commissionbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    12,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END 
		  /*本币未开票金额(含税)*/
FROM PT_Combin_SaleBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    46,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END    /*本币未开票金额(含税)*/
FROM PT_Combin_SaleBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    34,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END   /*本币未开票金额(含税)*/
FROM buybill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id		
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    6,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE  ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END    /*本币未开票金额(含税)*/
FROM buybackbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END    /*本币未开票金额(含税)*/
FROM buygoodsexchangebill a
WHERE A.InOrOut='O'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END    /*本币未开票金额(含税)*/
FROM buygoodsexchangebill a
WHERE A.InOrOut='I'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    145,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END  /*本币未开票金额(含税)*/
FROM commissionbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
CREATE TABLE #BillIndex
(
	BillNumberId		NUMERIC(18,0),
	BillCode			VARCHAR(400),
	BillDate			DATETIME,
	BillType			VARCHAR(20),
	BTypeId				VARCHAR(50),--单位
	Total				NUMERIC(24, 10) ,--单据金额
	NTotal				NUMERIC(24, 10) ,--单据金额
	PreferenceMoney		NUMERIC(24, 10) ,--优惠金额
	NPreferenceMoney	NUMERIC(24, 10) ,--优惠金额
	PayOrInMoney		NUMERIC(24, 10) ,--收或付款金额
	NPayOrInMoney		NUMERIC(24, 10) ,--收或付款金额
	Reconciliation		VARCHAR(4),--对账标志
	Comment				VARCHAR(2000),
	BillBtypeID			VARCHAR(50),	-- 单据往来单位
	Etypeid				VARCHAR(50),   --经手人
	Explain				VARCHAR(2000), --说明
	TotalQty			NUMERIC(24, 10),
	AccountDate			DATETIME,
	DzWarningDays		INT 
)
CREATE CLUSTERED INDEX CIX_BillIndex_BillNumberid ON #BillIndex(BillNumberid)

-----筛选表数据---------------
SET @CREATESQL='
INSERT INTO #BillIndex
SELECT 
	BI.BillNumberId,
	BI.BillCode,
	BI.BillDate,
	BI.BillType,
	BI.btypeid,
	CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.TOTALMONEY ELSE BI.TOTALMONEY-BI.PREFERENCEMONEY END,--单据金额
	CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.NTOTALMONEY ELSE BI.NTOTALMONEY-BI.NPREFERENCEMONEY END,--单据金额
	BI.PREFERENCEMONEY,--优惠金额
	BI.NPREFERENCEMONEY,--优惠金额
	t.total,
	t.ntotal,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end,
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	bi.explain,
	CASE WHEN BI.BILLTYPE IN(148,150) THEN 0 ELSE bi.totalqty   END AS totalqty,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays) ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays ELSE  b.fkdzwarningdays END
FROM BILLINDEX BI 
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
LEFT JOIN (SELECT BillNumberId,BillType, SUM(NTotalMoney) as ntotal,sum(TOTAL) as total FROM dbo.BillMulAccount  WHERE ATypeID NOT IN (27,39)  GROUP BY BillNumberId,billtype) t on bi.billnumberid=t.billnumberid and bi.billtype = t.billtype		
WHERE	
	BI.BILLTYPE NOT IN (115,116,128,129,126,139,159,161,160,57,450)
	AND BI.RedWord=0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.IFCHECK=''t'''+CHAR(13)
		
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+='	AND BI.CID='+@Cid+CHAR(13)
	
IF @proinfo = 4 
	SET @CREATESQL+='	AND BI.BILLTYPE NOT IN (167, 168, 170, 172, 148, 150, 151, 149, 139, 126, 212, 213) '+CHAR(13)

SET @CREATESQL +=' 
UNION ALL
SELECT 
	BI.BillNumberId,
	BI.BillCode,
	BI.BillDate,
	BI.BillType,
	BI.btypeid,
	BI.TOTALMONEY -BI.PREFERENCEMONEY,--单据金额
	BI.NTOTALMONEY -BI.NPREFERENCEMONEY,--单据金额
	PreferenceMoney,--优惠金额
	NPreferenceMoney,--优惠金额
	t.total,
	t.ntotal,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end, 
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	'''' as explain,
	bi.totalqty AS totalqty,
	dbo.F_CalAccountDate(bi.billdate,b.FKdzdays),
	b.fkdzwarningdays
FROM coupon_BillIndex BI 
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
LEFT JOIN(SELECT BillNumberId,billtype,SUM(NTotalMoney) as ntotal,sum(TOTAL) as total FROM dbo.BillMulAccount  WHERE ATypeID NOT IN (27,39)  GROUP BY BillNumberId,billtype) t on bi.billnumberid=t.billnumberid and bi.billtype = t.billtype			
WHERE 
	BI.BILLTYPE  IN (423,424,426)
	AND BI.RedWord=0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.IFCHECK= ''t'''+CHAR(13)
			
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+='	AND BI.CID='+@Cid+CHAR(13)
END

SET @CREATESQL+=' 
UNION ALL
SELECT 
	BI.BillNumberId,
	BI.BillCode,
	BI.BillDate,
	BI.BillType,
	'''' BTypeId,
	bi.totalmoney,
	BI.ntotalmoney,
	BI.PREFERENCEMONEY,--优惠金额
	BI.NPREFERENCEMONEY,--优惠金额
	bi.totalinmoney,
	BI.ntotalinmoney,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end,
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	bi.explain,
	0,
	null,
	null
FROM BILLINDEX BI 
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE 
	BI.BILLTYPE IN (115,116,128,129,450)
	AND BI.RedWord=0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.IFCHECK=''t'''+CHAR(13)
	
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+='	AND BI.CID='+@Cid+CHAR(13)

SET @CREATESQL+='
UNION ALL
SELECT 
	BI.BILLNUMBERID,
	BI.BILLCODE,
	BI.BILLDATE,
	BI.BILLTYPE,
	'''' BTypeId,
	0,
	0,
	BI.PREFERENCEMONEY,--优惠金额
	BI.NPREFERENCEMONEY,--优惠金额
	0,
	0,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end,
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	bi.explain,
	0,
	null ,
	null
FROM BILLINDEX bi
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
WHERE
	BI.BILLTYPE=159	
	AND BI.IfCheck = ''t''
	AND BI.Draft = 0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.RedWord=0'+CHAR(13)
				
SET @CREATESQL+='
UNION ALL
SELECT 
	BI.BillNumberId,
	BI.BillCode,
	BI.BillDate,
	BI.BillType,
	BI.btypeid,
	bi.totalmoney,
	BI.ntotalmoney,
	BI.PREFERENCEMONEY,--优惠金额
	BI.NPREFERENCEMONEY,--优惠金额
	bi.totalinmoney,
	BI.ntotalinmoney,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end,
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	bi.explain,
	bi.totalqty,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays) ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays ELSE  b.fkdzwarningdays	END
FROM BILLINDEX BI 
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE
	BI.BILLTYPE =139
	AND BI.RedWord=0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.IFCHECK=''t'''+CHAR(13)
	
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+='	AND BI.CID='+@Cid+CHAR(13)

SET @CREATESQL+='
UNION ALL
SELECT 
	BI.BillNumberId,
	BI.BillCode,
	BI.BillDate,
	BI.BillType,
	BI.btypeid,
	bi.totalmoney,
	BI.ntotalmoney,
	BI.PREFERENCEMONEY,--优惠金额
	BI.NPREFERENCEMONEY,--优惠金额
	bi.totalinmoney,
	BI.ntotalinmoney,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end,
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	bi.explain,
	bi.totalqty,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays) ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays ELSE  b.fkdzwarningdays	END
FROM BILLINDEX BI
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE
	BI.BILLTYPE =126
	AND BI.RedWord=0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.IFCHECK=''t'''+CHAR(13)

IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+=' AND BI.CID='+@Cid+CHAR(13)

SET @CREATESQL+='
UNION ALL--特殊处理换货单
SELECT  
	BI.BillNumberId,
	BI.BillCode,
	BI.BillDate,
	BI.BillType,
	BI.btypeid,
	CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.TOTALMONEY ELSE BI.TOTALMONEY-BI.PREFERENCEMONEY END,--单据金额
	CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.NTOTALMONEY ELSE BI.NTOTALMONEY-BI.NPREFERENCEMONEY END,--单据金额
	BI.PREFERENCEMONEY,--优惠金额
	BI.NPREFERENCEMONEY,--优惠金额
	bi.totalinmoney,
	BI.ntotalinmoney,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end,
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	bi.explain,
	bi.totalqty,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays) ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays ELSE  b.fkdzwarningdays	END
FROM BILLINDEX BI
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE
	BI.BILLTYPE IN (160,161)
	AND BI.RedWord=0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.IFCHECK=''t'''+CHAR(13)
	
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+=' AND BI.CID='+@Cid+CHAR(13)
	
-- 发票
SET @CREATESQL+='
UNION ALL
SELECT 
	BI.BillNumberId,
	BI.BillCode,
	BI.BillDate,
	BI.BillType,
	bi.btypeid,
	bi.TaxTotalMoney,
	BI.NTaxTotalMoney,
	0 as PREFERENCEMONEY,--优惠金额
	0 as NPREFERENCEMONEY,--优惠金额
	0 as totalinmoney,
	0 as ntotalinmoney,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end,
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	bi.explain,
	bi.totalqty,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays) ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays ELSE  b.fkdzwarningdays	END
FROM ReceiptBillIndex BI 
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE
	BI.BILLTYPE IN (404,405)
	AND BI.RedWord=0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.IFCHECK=''t'''+CHAR(13)
		
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+='	AND BI.CID LIKE '''+@Cid+''''+CHAR(13)

--成本调价单
SET @CREATESQL+=' 
UNION ALL
SELECT 
	BI.BillNumberId,
	BI.BillCode,
	BI.BillDate,
	BI.BillType,
	bi.btypeid,
	bi.totalmoney,
	BI.ntotalmoney,
	0,--优惠金额
	0,--优惠金额
	0,
	0,
	case when BI.Reconciliation=''t'' then ''√'' else '''' end,
	BI.Comment,
	BI.DealBTypeID,
	bi.etypeid,
	bi.explain,
	0  ,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays) ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
	CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays ELSE b.fkdzwarningdays	END
FROM BILLINDEX BI 
INNER JOIN #BillType BT ON BT.BillType=BI.BillType
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
WHERE 
	BI.BILLTYPE=57
	AND BI.RedWord=0
	AND BI.IsIni=0 
	AND bi.ifYearBill = 0
	AND BI.AdPriceType=1
	AND BI.IFCHECK=''t'''+CHAR(13)
	
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+='	AND BI.CID='+@Cid+CHAR(13)

EXEC(@CREATESQL)

---------------------------计算期初数据-----------------------------
-----统计算法：本来的期初往来余额+本期截至到查询开始时间之前的往来余额
CREATE TABLE #Total00
(
	BTypeId		VARCHAR(100),
	ArTotal		NUMERIC(24, 10) ,--应收金额
	NArTotal	NUMERIC(24, 10) ,
	ApTotal		NUMERIC(24, 10) ,--应付金额
	NApTotal	NUMERIC(24, 10) ,
	ZgTotal		NUMERIC(24, 10) ,--应付暂估
	NZgTotal	NUMERIC(24, 10) ,
	YSTotal		NUMERIC(24, 10) ,--预收金额
	NYSTotal	NUMERIC(24, 10) ,
	YFTotal		NUMERIC(24, 10) ,--预付金额
	nYFTotal	NUMERIC(24, 10) ,
	QMTotal		NUMERIC(24, 10) ,--往来余额
	NQMTotal	NUMERIC(24, 10) 
)
CREATE CLUSTERED INDEX CIX_Total00_BTypeId ON #Total00(BTypeId)

SET @CREATESQL='
INSERT INTO #TOTAL00
SELECT 
	BTypeID,
	SUM(ARTOTAL),
	SUM(NARTOTAL),
	SUM(APTOTAL),
	SUM(NAPTOTAL),
	SUM(zgTOTAL),
	SUM(nzgTOTAL),
	SUM(YSTOTAL),
	SUM(NYSTOTAL),
	SUM(YFTOTAL),
	SUM(NYFTOTAL),
	SUM(ARTOTAL)-SUM(APTOTAL)-SUM(YSTOTAL)+SUM(YFTOTAL)-SUM(zgTOTAL),
	SUM(NARTOTAL)-SUM(NAPTOTAL)-SUM(NYSTOTAL)+SUM(NYFTOTAL)-SUM(nzgTOTAL)
FROM  (
	SELECT 
		BTypeID,
		SUM(ISNULL(ARTotal00,0)) AS ARTOTAL,
		SUM(ISNULL(nARTotal00,0)) AS NARTOTAL,
		SUM(ISNULL(APTotal00,0)) AS APTOTAL,
		SUM(ISNULL(nAPTotal00,0)) AS NAPTOTAL,
		CASE WHEN '+CAST(@queryinvoice AS VARCHAR)+'=1 THEN SUM(ISNULL(GRIRTotal00,0)) ELSE 0 END as zgTOTAL,
		CASE WHEN '+CAST(@queryinvoice AS VARCHAR)+'=1 THEN SUM(ISNULL(nGRIRTotal00,0)) ELSE 0 END as nzgTOTAL,
		SUM(ISNULL(YSTotal00,0)) AS YSTOTAL,
		SUM(ISNULL(nYSTotal00,0)) AS NYSTOTAL,
		SUM(ISNULL(YFTotal00,0)) AS YFTOTAL,
		SUM(ISNULL(nYFTotal00,0)) AS NYFTOTAL
	FROM dbo.BType_ArApTotal A
	INNER JOIN #GetManBTypeId B ON A.BTypeID=B.TypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId=A.STypeID
	WHERE 
		1=1 '+CHAR(13)
		
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+='	AND A.CID='+@Cid+CHAR(13)
		
SET @CREATESQL+='
	GROUP BY A.BTypeID
	UNION ALL
	SELECT 
		L.BtypeId,
		ISNULL(SUM(CASE WHEN L.ATYPEID=33 THEN Total END),0) AS ARTotal,
		ISNULL(SUM(CASE WHEN L.ATYPEID=33 THEN NTotal END),0) AS NARTotal,
		ISNULL(SUM(CASE WHEN L.ATYPEID=35 THEN Total END),0) AS APTotal,
		ISNULL(SUM(CASE WHEN L.ATYPEID=35 THEN NTotal END),0) AS NAPTotal,
		ISNULL(SUM(CASE WHEN L.ATYPEID='+@zgnid+' THEN Total END),0) AS zgTOTAL,
		ISNULL(SUM(CASE WHEN L.ATYPEID='+@zgnid+' THEN nTotal END),0) AS nzgTOTAL,
		 ISNULL(SUM(CASE WHEN L.ATYPEID=39 THEN Total END),0) AS YSTotal,
		ISNULL(SUM(CASE WHEN L.ATYPEID=39 THEN NTotal END),0) AS NYSTotal,
		ISNULL(SUM(CASE WHEN L.ATYPEID=27 THEN Total END),0) AS YFTotal,
		ISNULL(SUM(CASE WHEN L.ATYPEID=27 THEN NTotal END),0) AS NYFTotal
	FROM ListTable L
	INNER JOIN #GetManBTypeId B ON B.TypeId=L.BtypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId=L.STypeID
	WHERE 
		L.BillDate<'+CHAR(39)+@StartDate+CHAR(39)+'
		AND L.ATYPEID IN (33,35,39,27,'+@zgnid+')' +CHAR(13)
		
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+='	AND L.CID='+@Cid+CHAR(13)
	
IF @queryinvoice=1
	SET @CREATESQL+='	AND L.ATYPEID IN (33,35,39,27,'+@zgnid+') '+CHAR(13)
ELSE	
	SET @CREATESQL+='	AND L.AtypeId  IN (33,35,39,27) '+CHAR(13)
	
SET @CREATESQL+='
	GROUP BY L.BtypeId
) A 
GROUP BY A.BTypeID '

EXEC(@CREATESQL)

-------------------统计明细，按照单据类型、单位--------------------
CREATE TABLE #BillTotal
(
	BTypeId				VARCHAR(50),--单位
	BillNumberId		VARCHAR(20),
	BillType			VARCHAR(20),
	BillDate			DATETIME,
	BillCode			VARCHAR(400),
	BillTotal			NUMERIC(24, 10) ,--	单据金额
	NBillTotal			NUMERIC(24, 10) ,--	单据金额
	PreferenceMoney		NUMERIC(24, 10) ,--优惠金额
	NPreferenceMoney	NUMERIC(24, 10) ,--优惠金额
	InTotal				NUMERIC(24, 10) ,--实收金额
	NInTotal			NUMERIC(24, 10) ,--实收金额
	ArTotal				NUMERIC(24, 10) ,--应收金额
	NArTotal			NUMERIC(24, 10) ,--应收金额
	PayTotal			NUMERIC(24, 10) ,--实付金额
	nPayTotal			NUMERIC(24, 10) ,--实付金额
	ApTotal				NUMERIC(24, 10) ,--应付金额
	NApTotal			NUMERIC(24, 10) ,--应付金额
	YsTotal				NUMERIC(24, 10) ,--预收金额
	NYsTotal			NUMERIC(24, 10) ,--预收金额
	YfTotal				NUMERIC(24, 10) ,--预付金额
	NYfTotal			NUMERIC(24, 10) ,--预付金额
	QmTotal				NUMERIC(24, 10) ,--往来余额
	NQmTotal			NUMERIC(24, 10) ,--往来余额
	Reconciliation		VARCHAR(4),--对账标志
	Comment				VARCHAR(2000),
	BillBtypeId			VARCHAR(50),	--单据往来单位
	ZgTotal				NUMERIC(24, 10) ,   --应付暂估
	NZgTotal			NUMERIC(24, 10) ,  --应付暂估
	ETypeId				VARCHAR(50),  --经手人
	Explain				VARCHAR(2000), --说明
	TotalQty			NUMERIC(24, 10),
	Accountdate			VARCHAR(10)  
)
CREATE CLUSTERED INDEX CIX_BillTotal_BTypeid_BillNumberid ON #BillTotal(BTypeid,BillNumberid)

DECLARE 
	@SqlWhereDate VARCHAR(500)='',
	@SqlWhereDate1 VARCHAR(500)=''
	
IF(ISNULL(@StartDate,'')<>'')--开始时间
	BEGIN
		SET @SqlWhereDate+='	AND '+CASE WHEN @IsAccountDate=1 THEN 'l.AccountDate' ELSE 'A.BillDate' END +'>='''+@StartDate+''''+CHAR(13)
		SET @SqlWhereDate1+='	AND '+CASE WHEN @IsAccountDate=1 THEN 'A.AccountDate' ELSE 'A.BillDate' END +'>='''+@StartDate+''''+CHAR(13)
	END

IF(ISNULL(@EndDate,'')<>'')--结束时间
	BEGIN
		SET @SqlWhereDate+='	AND '+CASE WHEN @IsAccountDate=1 THEN 'l.AccountDate' ELSE 'A.BillDate' END +'<='''+@EndDate+''''+CHAR(13)
		SET @SqlWhereDate1+='	AND '+CASE WHEN @IsAccountDate=1 THEN 'A.AccountDate' ELSE 'A.BillDate' END +'<='''+@EndDate+''''+CHAR(13)
	END
	
--特殊业务凭证
SET  @CREATESQL='
INSERT INTO #BILLTOTAL
SELECT 
	L.BTYPEID,
	A.BILLNUMBERID,
	A.BILLTYPE,
	A.BILLDATE,
	A.BILLCODE,
	A.TOTAL,
	A.NTOTAL,
	A.PREFERENCEMONEY,--优惠金额
	A.NPREFERENCEMONEY,--优惠金额
	0,--实收
	0,--实收
	CASE WHEN L.AtypeId=33 THEN L.Total END ,--应收
	CASE WHEN L.AtypeId=33 THEN L.NTotal END ,--应收
	0,--实付
	0,--实付
	CASE WHEN L.AtypeId=35 THEN L.Total END ,--应付
	CASE WHEN L.AtypeId=35 THEN L.NTotal END ,--应付
	CASE WHEN L.AtypeId=39 THEN L.Total END ,--预收
	CASE WHEN L.AtypeId=39 THEN L.NTotal END ,--预收
	CASE WHEN L.AtypeId=27 THEN L.Total END ,--预付
	CASE WHEN L.AtypeId=27 THEN L.NTotal END ,--预付
	0,
	0,
	A.RECONCILIATION,
	A.Comment,
	A.BillBtypeID,
	CASE WHEN L.AtypeId='+@zgnid+' THEN L.Total END AS zgtotal,
	CASE WHEN L.AtypeId='+@zgnid+' THEN L.nTotal END AS nzgtotal,
	a.etypeid,
	a.explain,
	a.totalqty,
	convert(nvarchar(10),l.accountdate,120)
FROM #BILLINDEX A 
INNER JOIN(   
	SELECT 
		billnumberid,
		ATYPEID,
		BTYPEID,
		total,
		ntotal,
		cid,
		CASE WHEN BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(billdate,b.dzdays) ELSE dbo.F_CalAccountDate(billdate,b.FKdzdays) END AS accountdate,
		CASE WHEN BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays ELSE  b.fkdzwarningdays END AS dzwarningdays
	from ListTable 
	INNER JOIN #GetManBTypeId B ON B.TypeId=BtypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId=STypeID
	WHERE 
		ATYPEID IN(33,35,27,39,'+@zgnid+') 
		AND BILLTYPE in(159)   
		AND ISNULL(BtypeId,'''')<>''''
) L ON A.BILLNUMBERID = L.BillNumberId 
WHERE A.BILLTYPE in(159) '

--业务凭证特殊处理，币种判断表体
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+=' AND L.CID='+@Cid+CHAR(13)

SET @CREATESQL+=@SqlWhereDate

IF @QueryAccountDate=1
	SET @CREATESQL+='	AND DATEDIFF(DAY,GETDATE(),A.accountdate)<=l.dzwarningdays '+CHAR(13)

EXEC(@CREATESQL)

--特殊处理往来核销单
SET  @CREATESQL='
INSERT INTO #BILLTOTAL
SELECT 
	L.BTYPEID,
	A.BILLNUMBERID,
	A.BILLTYPE,
	A.BILLDATE,
	A.BILLCODE,
	A.TOTAL,
	A.NTOTAL,
	A.PREFERENCEMONEY,--优惠金额
	A.NPREFERENCEMONEY,--优惠金额
	0,--实收
	0,--实收
	SUM(CASE WHEN L.AtypeId=33 THEN L.Total ELSE 0 END) ,--应收
	SUM(CASE WHEN L.AtypeId=33 THEN L.NTotal ELSE 0 END) ,--应收
	0,--实付
	0,--实付
	SUM(CASE WHEN L.AtypeId=35 THEN L.Total ELSE 0 END) ,--应付
	SUM(CASE WHEN L.AtypeId=35 THEN L.NTotal ELSE 0 END) ,--应付
	SUM(CASE WHEN L.AtypeId=39 THEN L.Total ELSE 0 END) ,--预收
	SUM(CASE WHEN L.AtypeId=39 THEN L.NTotal ELSE 0 END) ,--预收
	SUM(CASE WHEN L.AtypeId=27 THEN L.Total ELSE 0 END) ,--预付
	SUM(CASE WHEN L.AtypeId=27 THEN L.NTotal ELSE 0 END) ,--预付
	0,
	0,
	A.RECONCILIATION,
	A.Comment,
	A.BillBtypeID,
	SUM(CASE WHEN L.AtypeId='+@zgnid+' THEN L.Total ELSE 0 END) AS zgtotal,
	SUM(CASE WHEN L.AtypeId='+@zgnid+' THEN L.nTotal ELSE 0 END) AS nzgtotal,
	a.etypeid,
	a.explain,
	a.totalqty,
	convert(nvarchar(10),l.accountdate,120)
FROM #BILLINDEX A 
INNER JOIN(   
	select 
		billnumberid,
		ATYPEID,
		BTYPEID,
		total,
		ntotal,
		cid,
		CASE WHEN AtypeId IN(33,39) THEN dbo.F_CalAccountDate(billdate,b.dzdays) ELSE dbo.F_CalAccountDate(billdate,b.FKdzdays) END AS accountdate,
		CASE WHEN  AtypeId IN(33,39) THEN b.dzwarningdays ELSE  b.fkdzwarningdays END AS dzwarningdays
	from ListTable 
	INNER JOIN #GetManBTypeId B ON B.TypeId=BtypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId=STypeID
	WHERE 
		ATYPEID IN(33,35,27,39,'+@zgnid+') 
		AND BILLTYPE in(450)
		AND ISNULL(BtypeId,'''')<>''''
) L ON A.BILLNUMBERID = L.BillNumberId 
WHERE A.BILLTYPE in(450) '
--业务凭证特殊处理，币种判断表体
IF @CID<>0 AND ISNULL(@Cid,0)<>0
	SET @CREATESQL+=' AND L.CID='+@Cid+CHAR(13)
	
SET @CREATESQL+=@SqlWhereDate

IF @QueryAccountDate=1
	BEGIN
		SET @CREATESQL+='	AND DATEDIFF(DAY,GETDATE(),A.accountdate)<=l.dzwarningdays '+CHAR(13)
	END
	
SET @CREATESQL+='
GROUP BY 
	L.BTYPEID,
	A.BILLNUMBERID,
	A.BILLTYPE,
	A.BILLDATE,
	A.BILLCODE,
	A.TOTAL,
	A.NTOTAL,
	A.PREFERENCEMONEY,--优惠金额
	A.NPREFERENCEMONEY,--优惠金额  
	A.RECONCILIATION,
	A.Comment,
	A.BillBtypeID, 
	a.etypeid,
	a.explain,
	a.totalqty,
	l.accountdate'

EXEC(@CREATESQL)


DECLARE @ZGTYPEID VARCHAR(10)
SELECT @ZGTYPEID=NID FROM Ac_Items WHERE UserCode='2122'

SET @CREATESQL='
INSERT INTO #BILLTOTAL
SELECT 
	A.BTYPEID,
	A.BILLNUMBERID,
	A.BILLTYPE,
	A.BILLDATE,
	A.BILLCODE,
	A.TOTAL,
	A.NTOTAL,
	A.PREFERENCEMONEY,--优惠金额
	A.NPREFERENCEMONEY,--优惠金额
	CASE WHEN A.BILLTYPE IN(11,93,141,85,157,167,168,172,178,186,150,305,195,181,312,182,179,196,200,213,151,424,12) THEN ISNULL(A.PAYORINMONEY,0) 
			WHEN A.BILLTYPE =160 THEN ISNULL(A.PAYORINMONEY,0)-ISNULL(-B.YSTOTAL,0)
			WHEN A.BILLTYPE IN (189) THEN ISNULL(A.TOTAL,0)
			WHEN A.BILLTYPE IN (4) THEN ISNULL(A.TOTAL,0)-ISNULL(-B.YSTOTAL,0)
			WHEN A.BILLTYPE IN (6) THEN ISNULL(A.PAYORINMONEY,0)
					ELSE 0 END,--收款类单据有实收金额
	CASE WHEN A.BILLTYPE IN(11,93,141,85,157,167,168,172,178,186,150,305,195,181,312,182,179,196,200,213,151,424,12) THEN ISNULL(A.NPAYORINMONEY,0) 
			WHEN A.BILLTYPE =160 THEN ISNULL(A.NPAYORINMONEY,0)-ISNULL(-B.NYSTOTAL,0)--预收预付本来就是负数
			WHEN A.BILLTYPE IN (189) THEN ISNULL(A.nTOTAL,0)
			WHEN A.BILLTYPE IN (4) THEN ISNULL(A.NTOTAL,0)-ISNULL(-B.NYSTOTAL,0)
			WHEN A.BILLTYPE IN (6) THEN ISNULL(A.NPAYORINMONEY,0)-ISNULL(-B.NYFTOTAL,0)
			ELSE 0 END,--收款类单据有实收金额	
	CASE WHEN a.billtype=4 THEN -(A.TOTAL+A.PREFERENCEMONEY) ELSE b.ARTOTAL END,--应收--收款单算法比较变态
	CASE WHEN a.billtype=4 THEN -(A.NTOTAL+A.NPREFERENCEMONEY) ELSE b.NARTOTAL END,--应收
	CASE WHEN A.BILLTYPE IN (34,145,84,170,148,212,45,215,149,423,426,46) THEN ISNULL(A.PAYORINMONEY,0) 
			 WHEN A.BILLTYPE =161 THEN ISNULL(A.PAYORINMONEY,0)-ISNULL(-B.YFTOTAL,0)
			 WHEN A.BILLTYPE IN (190) THEN ISNULL(A.TOTAL,0)
			 WHEN A.BILLTYPE IN (66) THEN ISNULL(A.TOTAL,0)-ISNULL(-B.YFTOTAL,0)
								ELSE 0 END,--付款类单据有实付金额
	CASE WHEN A.BILLTYPE IN (34,145,84,170,148,212,45,215,149,423,426,46) THEN ISNULL(A.NPAYORINMONEY,0) 
			 WHEN A.BILLTYPE =161 THEN ISNULL(A.NPAYORINMONEY,0)-ISNULL(-B.NYFTOTAL,0)
			WHEN A.BILLTYPE  IN (190) THEN ISNULL(A.NTOTAL,0)
			WHEN A.BILLTYPE IN (66) THEN ISNULL(A.NTOTAL,0)-ISNULL(-B.NYFTOTAL,0)
								ELSE 0 END,--付款类单据有实付金额
	CASE WHEN a.billtype=66 THEN b.APTOTAL ELSE B.APTOTAL END,--应付
	CASE WHEN a.billtype=66 THEN b.NAPTOTAL ELSE B.NAPTOTAL END,--应付
	B.YSTOTAL,--预收
	B.NYSTOTAL,--预收
	B.YFTOTAL,--预付
	B.NYFTOTAL,--预付
	B.ARTOTAL-B.APTOTAL-B.YSTOTAL+B.YFTOTAL-ISNULL(b.zgtotal,0),
	B.NARTOTAL-B.NAPTOTAL-B.NYSTOTAL+B.NYFTOTAL-ISNULL(b.nzgtotal,0),
	A.RECONCILIATION,
	A.Comment,
	A.BillBtypeID,
	b.zgtotal,
	b.nzgtotal,
	a.etypeid,
	a.explain,
	a.totalqty,
	convert(nvarchar(10),a.accountdate,120)
FROM #BILLINDEX A
LEFT JOIN(
	SELECT 
		BillNumberId,
		BILLTYPE,
		SUM(CASE WHEN AtypeId=33 THEN Total END) AS ARTOTAL,
		SUM(CASE WHEN AtypeId=33 THEN nTotal END) AS NARTOTAL,
		SUM(CASE WHEN AtypeId=35 THEN Total END) AS APTOTAL,
		SUM(CASE WHEN AtypeId=35 THEN nTotal END) AS NAPTOTAL,
		SUM(CASE WHEN AtypeId=39 THEN Total END) AS YSTOTAL,
		SUM(CASE WHEN AtypeId=39 THEN nTotal END) AS NYSTOTAL,
		SUM(CASE WHEN AtypeId=27 THEN Total END) AS YFTOTAL,
		SUM(CASE WHEN AtypeId=27 THEN nTotal END) AS NYFTOTAL,
		SUM(CASE WHEN AtypeId='+@zgnid+' THEN Total END) AS zgtotal,
		SUM(CASE WHEN AtypeId='+@zgnid+' THEN nTotal END) AS nzgtotal
	FROM LISTTABLE 
	WHERE ATYPEID IN(33,35,27,39,'+@zgnid+')
	GROUP BY BillNumberId,BILLTYPE
) B ON A.BILLNUMBERID = B.BillNumberId  and a.BILLTYPE=b.BILLTYPE
WHERE 
	A.BILLTYPE NOT IN (115,116,128,129,36,159,450) '
	
SET @CREATESQL+=@SqlWhereDate1

IF @QueryAccountDate=1
	BEGIN
		SET @CREATESQL+='	AND DATEDIFF(DAY,GETDATE(),A.accountdate)<=A.dzwarningdays '+CHAR(13)
	END
	
IF @WhichDetail<>'p'
	SET  @CREATESQL+='	AND (B.ARTOTAL<>0 OR B.APTOTAL<>0 OR B.YSTOTAL<>0 OR B.zgtotal<>0 OR B.YFTOTAL<>0)  '+CHAR(13)
EXEC(@CREATESQL)

-------调账类四张单据+往来核销单据------
SET @CREATESQL='
INSERT INTO #BILLTOTAL
SELECT 
	L.BTYPEID,
	A.BILLNUMBERID,
	A.BILLTYPE,
	A.BILLDATE,
	A.BILLCODE,
	L.TOTAL,
	L.NTOTAL,
	A.PREFERENCEMONEY,--优惠金额
	A.NPREFERENCEMONEY,--优惠金额
	0,--收款类单据有实收金额
	0,
	L.ARTOTAL,--应收
	L.NARTOTAL,--应收
	0,--付款类单据有实付金额
	0,
	L.APTOTAL,--应付
	L.NAPTOTAL,--应付
	l.ystotal,--预收
	l.nystotal,
	l.yftotal,--预付
	l.nyftotal,
	0,
	0,
	A.RECONCILIATION,
	A.Comment,
	A.BillBtypeID,
	0,
	0,
	a.etypeid,
	a.explain,
	a.totalqty,
	convert(nvarchar(10),l.accountdate,120)
FROM #BILLINDEX A 
INNER JOIN ( 
	SELECT 
		billnumberid,
		btypeid,
		ATYPEID,
		SUM(CASE WHEN BTYPEID<>'''' THEN ABS(TOTAL) ELSE 0 END) AS TOTAL,
		SUM(CASE WHEN BTYPEID<>'''' THEN ABS(NTOTAL) ELSE 0 END) AS NTOTAL,
		CASE WHEN ATYPEID=''33'' THEN SUM(total) ELSE 0 END AS ARTOTAL,
		CASE WHEN ATYPEID=''33'' THEN SUM(Ntotal) ELSE 0 END AS NARTOTAL,
		CASE WHEN ATYPEID=''35'' THEN SUM(total) ELSE 0 END AS APTOTAL,
		CASE WHEN ATYPEID=''35'' THEN SUM(ntotal) ELSE 0 END AS NAPTOTAL,
		--预收
		CASE WHEN ATYPEID=''39'' THEN SUM(total) ELSE 0 END AS ysTOTAL,
		CASE WHEN ATYPEID=''39'' THEN SUM(ntotal) ELSE 0 END AS NysTOTAL,
		--预付
		CASE WHEN ATYPEID=''27'' THEN SUM(total) ELSE 0 END AS yfTOTAL,
		CASE WHEN ATYPEID=''27'' THEN SUM(ntotal) ELSE 0 END AS NyfTOTAL,
		CASE WHEN BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(billdate,b.dzdays) ELSE dbo.F_CalAccountDate(billdate,b.FKdzdays) END AS accountdate,
		CASE WHEN BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays ELSE b.fkdzwarningdays	END	AS dzwarningdays
	from ListTable 
	INNER JOIN #GetManBTypeId B ON B.TypeId=BtypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId=STypeID
	WHERE  ATYPEID IN (33,35) AND BILLTYPE IN (115,116,128,129)
	GROUP BY BillNumberId,billtype,BtypeId,AtypeId,billdate,dzdays,b.dzwarningdays,FKdzdays,fkdzwarningdays 
 ) L ON A.BILLNUMBERID = L.BillNumberId 	  
WHERE 
	A.BILLTYPE IN (115,116,128,129)'+CHAR(13)
	
SET @CREATESQL+=@SqlWhereDate
	
IF @QueryAccountDate=1
	SET @CREATESQL+='	AND DATEDIFF(DAY,GETDATE(),L.accountdate)<=l.dzwarningdays '+CHAR(13)

EXEC(@CREATESQL)

DECLARE @ExpenseToAr VARCHAR(10)='0'
SELECT @ExpenseToAr=ISNULL(SubValue,'0') FROM dbo.sysdata WHERE SubName='ExpenseToAr'
-------费用单------
SET @CREATESQL=' 
INSERT INTO #BILLTOTAL
SELECT 
	A.BTYPEID,
	A.BILLNUMBERID,
	A.BILLTYPE,
	A.BILLDATE,
	A.BILLCODE,
	A.TOTAL,
	A.NTOTAL,
	A.PREFERENCEMONEY,--优惠金额
	A.NPREFERENCEMONEY,--优惠金额
	0,--收款类单据有实收金额
	0,
	CASE WHEN '+@ExpenseToAr+'=''1''  AND LEFT(A.BTYPEID,5)=''00001''  THEN -(A.TOTAL-ISNULL(a.PAYORINMONEY,0)-ISNULL(-L.YFTOTAL,0)) ELSE 0 END,--应收
	CASE WHEN '+@ExpenseToAr+'=''1''  AND LEFT(A.BTYPEID,5)=''00001'' THEN -(A.NTOTAL-ISNULL(a.nPAYORINMONEY,0)-ISNULL(-L.NYFTOTAL,0)) ELSE 0 END,--应收
	A.PAYORINMONEY-L.YFTOTAL,--付款类单据有实付金额
	A.NPAYORINMONEY-L.NYFTOTAL,--付款类单据有实付金额
	CASE WHEN '+@ExpenseToAr+'=''1''  and LEFT(A.BTYPEID,5)=''00001''  THEN  0  ELSE L.APTOTAL END,--应付
	CASE WHEN '+@ExpenseToAr+'=''1''  and  LEFT(A.BTYPEID,5)=''00001''  THEN  0  ELSE L.NAPTOTAL END,--应付
	0,--预收
	0,
	L.YFTOTAL,--预付
	L.NYFTOTAL,--预付
	0,
	0,
	A.RECONCILIATION,
	A.Comment,
	A.BillBtypeID,
	0,
	0,
	a.etypeid,
	a.explain,
	a.totalqty,
	convert(nvarchar(10),a.accountdate,120)
FROM #BILLINDEX A 
LEFT JOIN (
	SELECT 
		BillNumberId,
		SUM(CASE WHEN AtypeId=33 THEN Total ELSE 0 END) AS ARTOTAL,
		SUM(CASE WHEN AtypeId=33 THEN NTotal ELSE 0 END) AS NARTOTAL,
		SUM(CASE WHEN AtypeId=35 THEN Total ELSE 0 END) AS APTOTAL ,
		SUM(CASE WHEN AtypeId=35 THEN NTotal ELSE 0 END) AS NAPTOTAL,
		SUM(CASE WHEN AtypeId=39 THEN Total ELSE 0 END) AS YSTOTAL,
		SUM(CASE WHEN AtypeId=39 THEN NTotal ELSE 0 END) AS NYSTOTAL,
		SUM(CASE WHEN AtypeId=27 THEN Total ELSE 0 END) AS YFTOTAL,
		SUM(CASE WHEN AtypeId=27 THEN NTotal ELSE 0 END) AS NYFTOTAL
	FROM ListTable L
	WHERE 
		BillType=36
	GROUP BY BillNumberId
) L ON A.BILLNUMBERID = L.BillNumberId
WHERE A.BILLTYPE =36'
			
SET @CREATESQL+=@SqlWhereDate1
	
IF @QueryAccountDate=1
	SET @CREATESQL+=' AND DATEDIFF(DAY , GETDATE(), A.accountdate)<=A.dzwarningdays  '
	
EXEC(@CREATESQL)

IF(@QueryAccountDate=1 AND @isLoginHit=1)
	BEGIN
	
		SELECT TOP 1 'arapaccounthit',1 FROM #BillTotal 
		
		DROP TABLE #BillIndex,#Total00,#BillTotal,#BillType,#GetManBTypeId,#GetManSTypeId,#invoiceQty
		 
		RETURN
	END

------------------最终数据临时表------------------------
--特殊处理期初和小计的单据类型--期初：-1，小计：-10.有问题问我----------
--SELECT * FROM #TOTAL00
--SELECT * FROM #BillTotal

CREATE TABLE #Result
(
	BTypeId				VARCHAR(50),--单位 
	BillnumberId		VARCHAR(20)
)	

IF @WhichDetail='A'
	BEGIN
		ALTER TABLE #Result
			ADD ATypeId VARCHAR(100)
	END
	
IF @WhichDetail='P'
BEGIN
	ALTER TABLE #Result
		ADD PTypeId			VARCHAR(100),
			Price			VARCHAR(20),
			Qty				NUMERIC(24, 10) ,
			UfullName		varchar(100),
			Total			NUMERIC(24, 10) ,
			SaleTotal		varChar(24) ,
			BaseQty			NUMERIC(24, 10) ,
			NtaxPrice		VARCHAR(20) ,
			BaseFullName	VARCHAR(200),
			UnitRalation	VARCHAR(200), 
			Discount		NUMERIC(24, 10)
END
	
ALTER TABLE #Result
		ADD BillType			VARCHAR(20),
			BillDate			DATETIME,
			BillCode			VARCHAR(400),
			BillTotal			varchar(100),--	单据金额(没有成本要显示*因此要定义成文本)
			PreferenceMoney		NUMERIC(24, 10) ,--优惠金额
			InTotal				NUMERIC(24, 10) ,--实收金额
			ArTotal				NUMERIC(24, 10) ,--应收金额
			PayTotal			NUMERIC(24, 10) ,--实付金额
			ApTotal				NUMERIC(24, 10) ,--应付金额
			YsTotal				NUMERIC(24, 10) ,--预收金额
			YfTotal				NUMERIC(24, 10) ,--预付金额
			QmTotal				NUMERIC(24, 10) ,--往来余额
			Reconciliation		VARCHAR(4),--对账标志
			Sortid				INT,					--排序id
			Psortid				INT,					--再来一个排序id,商品或收款账户用
			Comment				VARCHAR(2000),
			BillSort			VARCHAR(50), --wg 按照时间排序，同时保持同一单据在一起
			BillBtypeId			VARCHAR(50),--单据往来单位--对应界面的字段名字
			DetailComment		VARCHAR(2000) default(''''), --单据明细
			Explain				VARCHAR(2000), --说明
			ZgTotal				NUMERIC(24, 10) , --应付暂估金额
			ETypeId				VARCHAR(50), --经手人
			FpSort				int,
			AccountDate			VARCHAR(10),
			Id					INT,--明细排序ID
			UninvoiceQty1		NUMERIC(24,10) default(0), --未开票数量
			UninvoiceMoney1		NUMERIC(24,10) default(0) --未开票金额

CREATE CLUSTERED INDEX CIX_Result_BTypeId_BillNumberId ON #Result(BTypeId,BillNumberid)	

SET @CreateSql='
IF NOT EXISTS(SELECT TOP 1 1 FROM #TOTAL00)
	BEGIN
		INSERT INTO #Result
		SELECT  
			TypeID,
			-99999,--期初不写值'+CHAR(13)
					 
		IF @WhichDetail='A'
		SET @CREATESQL+='	'''','+CHAR(13)

		IF @WhichDetail='P'
		SET @CREATESQL+='	NULL,0,0,'''',0,0, 0,0,'''','''',0, '+CHAR(13)

		SET @CREATESQL+=' 
			''-1'',
			NULL,
			'''',
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			 '''',
			-1,
			0,
			'''',	
			'''',
			'''',
			'''',
			'''',
			0,
			'''',
			0  ,
			'''',
			-1,
			0,--未开票数量
			0 --未开票金额
		FROM #GetManBTypeId
	END'
	
SET @CreateSql+='
INSERT INTO #Result
SELECT  
	BTYPEID,
	 -99999,--期初不写值'+CHAR(13)
			 
IF @WhichDetail='A'
	SET @CREATESQL+='	'''','
	
IF @WhichDetail='P'
	SET @CREATESQL+='	NULL,0,0,'''',0,0, 0,0,'''','''',0, '
	
SET @CREATESQL+=' 
	''-1'',--期初强写-1
	NULL,
	'''',
	0,
	0,--优惠金额
	0,
	ISNULL(CASE WHEN '+@CID+'=0 THEN ARTOTAL ELSE NARTOTAL END,0),
	0,
	ISNULL(CASE WHEN '+@CID+'=0 THEN APTOTAL ELSE NAPTOTAL END,0),
	ISNULL(CASE WHEN '+@CID+'=0 THEN YSTOTAL ELSE NYSTOTAL END,0),
	ISNULL(CASE WHEN '+@CID+'=0 THEN YFTOTAL ELSE NYFTOTAL END,0),
	ISNULL(CASE WHEN '+@CID+'=0 THEN QMTOTAL ELSE NQMTOTAL END,0),
	 '''',
	-1,
	0,
	'''',	--期初强写
	'''',
	'''',
	'''',
	'''',
	ISNULL(CASE WHEN '+@CID+'=0 THEN zgtotal ELSE nzgtotal END,0),
	'''',
	0  ,
	'''',
	-1,
	0,--未开票数量
	0 --未开票金额
FROM #TOTAL00
LEFT JOIN  #GetManBTypeId	on Btypeid=TypeID	
UNION ALL
SELECT 
	A.BTYPEID,
	A.BILLNUMBERID,'+CHAR(13)
IF @WhichDetail='A'
	SET @CREATESQL+='	0,'
IF @WhichDetail='P'
	SET @CREATESQL+='	NULL,0,0,'''',0,0,  a.totalqty as baseqty,0,'''','''',0, '
SET @CREATESQL+=' 
	A.BILLTYPE,
	A.BILLDATE,
	A.BILLCODE,
	CASE WHEN '+@CID+'=0 THEN ISNULL(BILLTOTAL,0) ELSE ISNULL(NBILLTOTAL,0) END,
	CASE WHEN '+@CID+'=0 THEN ISNULL(PREFERENCEMONEY,0) ELSE ISNULL(NPREFERENCEMONEY,0) END,--优惠金额
	CASE WHEN '+@CID+'=0 THEN ISNULL(INTOTAL	,0) 
				ELSE ISNULL(NINTOTAL	,0) END,
	CASE WHEN '+@CID+'=0 THEN ISNULL(ARTOTAL,0) ELSE ISNULL(NARTOTAL,0) END,
	CASE WHEN '+@CID+'=0 THEN ISNULL(PAYTOTAL ,0)
				ELSE ISNULL(NPAYTOTAL ,0) END,
	CASE WHEN '+@CID+'=0 THEN ISNULL(APTOTAL		 ,0) ELSE ISNULL(NAPTOTAL,0) END,
	CASE WHEN '+@CID+'=0 THEN ISNULL(YSTOTAL		 ,0) ELSE ISNULL(NYSTOTAL,0) END,
	CASE WHEN '+@CID+'=0 THEN ISNULL(YFTOTAL		,0) ELSE ISNULL(NYFTOTAL		,0) END,
	CASE WHEN '+@CID+'=0 THEN ISNULL(QMTOTAL	,0) ELSE ISNULL(NQMTOTAL	,0) END,
	A.RECONCILIATION,
	0,
	0,
	A.Comment,
	CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT(''000000000000000000''+A.BILLNUMBERID,18) AS BillSort,
	A.BillBtypeID,
	'''',
	a.explain,
	CASE WHEN '+@CID+'=0 THEN ISNULL(zgtotal,0) ELSE ISNULL(Nzgtotal,0) END,
	A.EtypeID,
	CASE WHEN A.BillType in(404,405) THEN 1 ELSE 0 END,
	convert(nvarchar(10),a.accountdate,120),
	0,
	isnull(inv.uninvoiceqty,0),
	isnull(inv.uninvoicemoney,0)
FROM #BILLTOTAL A 
LEFT JOIN(
	select  
		billnumberid, 
		billtype,
		SUM(uninvoiceqty) as uninvoiceqty,
		sum(uninvoicemoney)uninvoicemoney 
	FROM #invoiceQty 
	GROUP by 
		billnumberid,
		billtype  
) inv on a.billtype=inv.billtype and a.BILLNUMBERID=inv.billnumberid
'

SET @CREATESQL+='
----计算合计----
INSERT INTO #Result
SELECT 
	BTYPEID,
	0,'
IF @WhichDetail='A'
	SET @CREATESQL+=' '''','
IF @WhichDetail='P'
	SET @CREATESQL+=' '''',0,0,'''', 0,0, 0,0,'''','''', 0,'
SET @CREATESQL+=' 
	-10,--强写-10
	NULL,
	'''',
	0,
	SUM(ISNULL(PREFERENCEMONEY,0)),--优惠金额
	SUM(ISNULL(INTOTAL	,0)),
	SUM(ISNULL(ARTOTAL		,0)),
	SUM(ISNULL(PAYTOTAL ,0)),
	SUM(ISNULL(APTOTAL		 ,0)),
	SUM(ISNULL(YSTOTAL		 ,0)),
	SUM(ISNULL(YFTOTAL		,0)),
	SUM(ISNULL(ARTOTAL,0))-SUM(ISNULL(APTOTAL,0))-SUM(ISNULL(YSTOTAL,0))+SUM(ISNULL(YFTOTAL,0))-SUM(ISNULL(zgTOTAL,0)) ,
	'''',
	1,
	0,
	'''',
	'''',
	'''',
	'''',
	'''',
	SUM(ISNULL(zgtotal,0)),
	'''',
	0 ,
	'''',
	0,
	SUM(ISNULL(uninvoiceqty1,0)),--未开票数量
	SUM(ISNULL(uninvoicemoney1,0)) --未开票金额	
FROM #Result
GROUP BY BTYPEID'


--处理只有期初和期末并且全部为零的单据不显示问题
SET @CREATESQL+=' 
DELETE FROM #Result 
WHERE 
	(ISNULL(CONVERT( NUMERIC(24, 10) , BILLTOTAL),0)=0 
	AND ISNULL(ARTOTAL,0)=0 
	AND ISNULL(APTOTAL,0)=0 
	AND ISNULL(YSTOTAL,0)=0 
	AND ISNULL(YFTOTAL,0)=0
	AND ISNULL(zgTOTAL,0)=0 
	AND ISNULL(QMTOTAL,0)=0)
	AND BTYPEID IN ( SELECT BTYPEID FROM #Result GROUP BY BTYPEID HAVING COUNT(BTYPEID)<=2 )'
	
EXEC (@CreateSql)

SET @CreateSql=''
--按商品显示明细是个很坑爹的东西---
IF @WhichDetail='P'
	BEGIN
		SET @CREATESQL=' 
		---加入商品明细信息
		INSERT INTO #Result
		SELECT
			A.BTYPEID,
			A.BILLNUMBERID,
			B.PTYPEID,
			CASE WHEN '+@CID+'=0 THEN B.MTaxPrice ELSE B.CurMTaxPrice END,	
			B.MQTY,
			PU.FULLNAME,
			CASE WHEN '+@CID+'=0 THEN b.total ELSE b.ntotal END,
			CASE WHEN '+@CID+'=0 THEN b.saletotal ELSE b.nsaletotal END,
			b.qty,
			b.NTaxPrice,
			u1.fullname as basefullname,
			''1''+PU.fullname+''=''+convert(varchar(200),CAST(b.MUnitRate  AS real))+u1.fullname,
			b.discount,	
			A.BILLTYPE,		
			NULL,		
			'''',		
			CASE WHEN '+@CID+'=0 THEN TaxTotal ELSE NTaxTotal END,	
			0,--优惠金额
			0,		
			0,		
			0	,
			0,		
			0,		
			0,		
			0,	
			CASE WHEN B.Reconciliation=''T'' THEN ''√'' ELSE '''' END Reconciliation,
			0,
			1,
			'''',
			CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT(''000000000000000000''+A.BILLNUMBERID,18) AS BillSort,
			'''',
			B.comment AS detailcomment,
			'''',
			0,
			'''',
			0 ,
			'''',
			B.ID,
			inv.uninvoiceqty,
			inv.uninvoicemoney
		FROM #Result A 
		INNER JOIN (
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM retailbill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM RetailBackBill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM salebill
			UNION ALL
			SELECT ID, BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM salebackbill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM salegoodsexchangebill where InOrOut=''O''
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,-MQty,MUnitID,-NTaxTotal,-TaxTotal,comment,-total,-saletotal,-ntotal,-nsaletotal,UnitID,-qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM salegoodsexchangebill where InOrOut=''I''
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice, MQty,MUnitID,0,0,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,UnitID,qty,null as NTaxPrice,MUnitRate,0 AS discount,Reconciliation FROM givebill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,MQty,MUnitID,0,0,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,UnitID,qty,null as NTaxPrice,MUnitRate,0 AS discount,Reconciliation FROM giveMEbill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM commissionbill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM buybill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM buybackbill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM buygoodsexchangebill where InOrOut=''I''
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,-MQty,MUnitID,-NTaxTotal,-TaxTotal,comment,-total,-saletotal,-ntotal,-nsaletotal,UnitID,-qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM buygoodsexchangebill where InOrOut=''O''
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0,0 AS NTAXTOTAL,0 AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,0,qty,NULL as NTaxPrice,null as MUnitRate,0 AS discount,'''' Reconciliation FROM priceprotectbill
			UNION ALL 
			SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,0,0,TOTAL AS NTAXTOTAL,TOTAL AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,0,null as qty,NULL as NTaxPrice,null as MUnitRate,0 as discount,'''' Reconciliation FROM advantage 
			UNION ALL 
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation  FROM AppraisalBill
			UNION ALL 
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation  FROM AppraisalBackBill
			UNION ALL 
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,'''' Reconciliation  FROM SendBill
			UNION ALL 
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,'''' Reconciliation  FROM SendBackBill	 
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation  FROM PT_Combin_SaleBill
			UNION ALL
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation  FROM PT_Combin_SaleBackBill						
		) B ON A.BILLNUMBERID=B.BILLNUMBERID
		LEFT JOIN #invoiceQty inv on a.billtype=inv.billtype and a.BILLNUMBERID=inv.billnumberid AND INV.PTYPEID=B.PTYPEID AND B.ID=INV.ID
		LEFT JOIN PType_Units PU ON PU.UnitsId=B.MUNITID 
		LEFT JOIN PType_Units u1 ON u1.UnitsId=B.UnitID 
		WHERE B.PTYPEID<>''''  AND A.Billtype not in(404,405,167,168,170,450,423,424,425,426)'
		
		EXEC(@CREATESQL)
		--成本调价单 不出明细行 应付暂估统计在表头一行的数据上的
		SET @CREATESQL=' --加入商品明细信息
		INSERT INTO #Result
		SELECT 
			A.BTYPEID,
			A.BILLNUMBERID,
			B.PTYPEID,
			CASE WHEN '+@CID+'=0 THEN B.MTaxPrice ELSE B.CurMTaxPrice END,	
			B.MQTY,
			PU.FULLNAME,
			CASE WHEN '+@CID+'=0 THEN b.total ELSE b.ntotal END,
			CASE WHEN '+@CID+'=0 THEN b.saletotal ELSE b.nsaletotal END,
			b.qty,
			b.NTaxPrice,
			pu.fullname as basefullname,
			''1''+PU.fullname+''=1''+PU.fullname,
			b.discount,	
			A.BILLTYPE,		
			NULL,		
			'''',		
			CASE WHEN '+@CID+'=0 THEN TaxTotal ELSE NTaxTotal END,	
			0,--优惠金额
			0,		
			0,		
			0	,
			0,		
			0,		
			0,		
			0,	
			'''' Reconciliation,
			0,
			1,
			'''',
			CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT(''000000000000000000''+A.BILLNUMBERID,18) AS BillSort,
			'''',
			B.comment AS detailcomment,
			'''',
			0,
			'''',
			0,
			'''',
			B.ID,
			0,--未开票数量
			0 --未开票金额
		FROM #Result A 
		INNER JOIN (
			SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty AS mqty,0 AS NTAXTOTAL,0 AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,qty,NULL as NTaxPrice,null as MUnitRate,0 AS discount FROM wx_bill_getback
			UNION ALL
			SELECT  ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0 AS TAXTOTAL,0 AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,qty,NULL as NTaxPrice,null as MUnitRate,0 AS discount FROM wx_bill_replace 
			UNION ALL
			SELECT  ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0 AS TAXTOTAL,0 AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,qty,NULL as NTaxPrice,null as MUnitRate,0 AS discount FROM wx_bill_sendback
		) B ON A.BILLNUMBERID=B.BILLNUMBERID
		LEFT JOIN dbo.ptype p ON B.ptypeid=	p.typeId
		LEFT JOIN PType_Units PU ON PU.UnitsId=p.baseUnitId 
		WHERE 
			B.PTYPEID<>''''  
			AND A.Billtype in(167,168,170)'
		
		EXEC(@CREATESQL)
			
		SET @CREATESQL=' --发票单据处理（发票不写billindex)
		INSERT INTO #Result
		SELECT  
			A.BTYPEID,
			A.BILLNUMBERID,
			B.PTYPEID,
			CASE WHEN '+@CID+'=0 THEN B.MTaxPrice ELSE B.CurMTaxPrice END,	
			B.MQTY,
			PU.FULLNAME,
			CASE WHEN '+@CID+'=0 THEN b.total ELSE b.ntotal END,
			CASE WHEN '+@CID+'=0 THEN b.saletotal ELSE b.nsaletotal END,
			b.qty,
			b.NTaxPrice,
			u1.fullname as basefullname,
			''1''+PU.fullname+''=''+convert(varchar(200),CAST(b.MUnitRate  AS real))+u1.fullname,
			b.discount,	
			A.BILLTYPE,		
			NULL,		
			'''',		
			CASE WHEN '+@CID+'=0 THEN TaxTotal ELSE NTaxTotal END,	
			0,--优惠金额
			0,		
			0,		
			0	,
			0,		
			0,		
			0,		
			0,	
			CASE WHEN B.Reconciliation=''T'' THEN ''√'' ELSE '''' END Reconciliation,
			0,
			1,
			'''',
			CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT(''000000000000000000''+A.BILLNUMBERID,18) AS BillSort,
			'''',
			B.comment AS detailcomment,
			'''',
			0,
			'''',
			1,
			'''',
			B.ID,
			0,--未开票数量
			0 --未开票金额
		FROM #Result A 
		INNER JOIN ReceiptBillIndex  RE ON A.BILLNUMBERID=RE.BILLNUMBERID AND A.billtype=re.billtype
		INNER JOIN (  
			SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation FROM ReceiptBill
		) B ON re.BILLNUMBERID=B.BILLNUMBERID  --由于前面插入了发票的数据到result导致会存在billnumberid相同billtype不同的数据
		LEFT JOIN PType_Units PU ON PU.UnitsId=B.MUNITID 
		LEFT JOIN PType_Units u1 ON u1.UnitsId=B.UnitID 
		WHERE 
			B.PTYPEID<>''''  
			AND A.Billtype  in(404,405)'
			
		EXEC(@CREATESQL)
	END

--按账户显示明细同样是个很坑爹的东西---
IF @WhichDetail='A'
BEGIN
	SET @CREATESQL=' 
		---加入账户明细信息
		INSERT INTO #Result
		SELECT A.BTYPEID,
					A.BILLNUMBERID,
					b.atypeid,
					A.BILLTYPE,		
					NULL,		
					'''',		
					0,	
					0,--优惠金额
					case WHEN a.billtype not in (84,190,170,161,145,45,148,34,36,66,149,6,4,150,215,151,212,46,423,426) AND b.atypeid<>39 then  CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
							WHEN a.billtype=4 and b.atypeid NOT IN (39,34,423) then  CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							WHEN a.billtype=4 and b.atypeid IN (34,423) then  CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							WHEN a.billtype IN (6,150,151) AND b.atypeid<>27 THEN CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
								 else 0  end,		--实收
					0,		--应收
					case when a.billtype in (170,161,145,212) and b.atypeid<>27  then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
							when a.billtype in (149) and b.atypeid NOT IN (27,39)  then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
							WHEN a.billtype IN (215) AND b.atypeid NOT IN (27,39) then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
							when a.billtype in (45,148,426) and b.atypeid<>39  then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							when a.billtype in (34,423) and b.atypeid IN (SELECT nId FROM dbo.Ac_Items WHERE TypeName=''B'') then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							WHEN a.billtype=36 and b.atypeid<>27 THEN CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							WHEN a.billtype=66 and b.atypeid<>27 THEN CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							WHEN a.billtype=190 THEN CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							WHEN a.billtype in (84) AND b.atypeid NOT IN (39,27) then  CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END 
								else 0  end	,--实付
					0,		--应付
					case when b.atypeid=39 AND A.BILLTYPE not in (181,312,305,11,160,141,167,168,172,93,85,213,414,12,424) then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END
							when b.atypeid=39 AND A.BILLTYPE IN (4,181,312,305,11,160,141,167,168,172,93,85,213,414,12,424) then CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							WHEN b.atypeid=27 AND A.BILLTYPE IN (93,85) THEN  CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END
							else 0 end,		--预收
					case when b.atypeid=27 AND a.billtype NOT IN (66,150,151,36,6)  then (CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END)	
							when b.atypeid=27 AND a.billtype IN (6)  then (CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END)	
							WHEN a.billtype in (66,150,151) AND b.atypeid=27 then CASE WHEN '+@CID+'=0 THEN B.total ELSE B.NTOTAL END	
							WHEN a.billtype in (36) AND b.atypeid=27 
										THEN CASE WHEN '+@CID+'=0 THEN -B.total ELSE -B.NTOTAL END	
							else 0 end,	--预付
					0,	
					A.RECONCILIATION,
					0,
					1,
					'''',
					CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT(''000000000000000000''+A.BILLNUMBERID,18) AS BillSort,
					'''',
					'''',
					'''',
					0,
					'''',
					0   ,
					'''',
					B.ID,
					0,--未开票数量
					0 --未开票金额
		FROM #Result A 
		INNER JOIN (
			SELECT  ID,BILLNUMBERID,ATYPEID,nTOTALmoney as nTOTAL,total AS TOTAL,BillType
			FROM BillMulAccount
			UNION ALL
			SELECT  ID,BILLNUMBERID,ATYPEID,nTOTAL,TOTAL,BillType FROM LISTTABLE WHERE BILLTYPE=4 AND ATYPEID<>33 
			UNION ALL
			SELECT  ID,BILLNUMBERID,ATYPEID,nTOTAL,TOTAL,BillType FROM LISTTABLE WHERE BILLTYPE=66 AND ATYPEID<>35 
			UNION ALL
			SELECT  ID,BILLNUMBERID,ATYPEID,nTOTAL,TOTAL,BillType FROM LISTTABLE WHERE BILLTYPE=189 and atypeid<>39
			UNION ALL
			SELECT  ID,BILLNUMBERID,ATYPEID,nTOTAL,TOTAL,BillType FROM LISTTABLE WHERE BILLTYPE=190 and atypeid<>27
		) B ON A.BILLNUMBERID=B.BILLNUMBERID AND A.BILLTYPE = B.BILLTYPE WHERE B.atypeid<>24 AND A.BILLTYPE NOT IN(404,405)
'
		EXEC(@CREATESQL)
END 

--SELECT * FROM #Result 
--最终查询--临时处理账户和商品基本信息列，右键不支持，所以单独出数据----
SET @CREATESQL=' SELECT	A.* ,A.BillType BillTypes,'

IF @WhichDetail='P'
	SET @CREATESQL+='
					CASE WHEN A.BILLNUMBERID not in (-99999,0) and  isnull(a.PTYPEID,'''')='''' then 0 else  A.uninvoiceqty1 end  as  uninvoiceqty , 
					CASE WHEN A.BILLNUMBERID  not in (-99999,0) and  isnull(a.PTYPEID,'''')='''' then 0 else A.uninvoicemoney1  end  as  uninvoicemoney,
					customassist=dbo.F_GetCustomAssist(a.Ptypeid,a.baseqty),P.USERCODE AS PUSERCODE,P.FULLNAME AS PFULLNAME,p.name as pname,Ps.usercode pmulusercode '
ELSE
	SET @CREATESQL+=' A.uninvoiceqty1 as uninvoiceqty ,A.uninvoicemoney1  as uninvoicemoney  '
   
IF @WhichDetail='A'
	SET @CREATESQL+=' ,AC.FULLNAME AS AFULLNAME '
SET @CREATESQL+='
	,SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head,SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
	SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40
FROM #Result  A '

IF @WhichDetail='P'
	SET @CREATESQL+='
LEFT JOIN PTYPE P ON A.PTYPEID=P.TYPEID
LEFT JOIN PUserCode Ps ON Ps.PTYPEID=P.TYPEID AND Ps.btypeid=A.btypeid'

IF @WhichDetail='A'
	SET @CREATESQL+='LEFT JOIN AC_ITEMS AC ON A.ATYPEID=AC.NID '
	
SET @CREATESQL+='
LEFT JOIN Custom_BillIndex CB ON CB.BillId=A.BillNumberId and CB.BillType=A.BillType
LEFT JOIN Custom_BillDetails CD ON CD.BillId=A.BillNumberId and CD.BillType=A.BillType AND CD.Detailid=A.ID
WHERE 
	(('''+@IsDetail+'''=''False'' AND A.BILLTYPE IN (-1,-10)) OR '''+@IsDetail+'''=''True'') '+CHAR(13)

--不显示对账信息
IF(@IsShowReconciliation=0)
	SET @CREATESQL+='	AND A.Reconciliation='''''+CHAR(13)
	
SET @CREATESQL+='ORDER BY A.btypeid ,A.SORTID,a.billsort,a.fpsort,a.billcode DESC ,A.BILLTYPE  '

EXEC(@CREATESQL)

--删除临时表
DROP TABLE #BILLINDEX,#BILLTOTAL,#BillType,#GetManBTypeId,#GetManSTypeId,#TOTAL00,#invoiceQty,#Result



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






IF EXISTS(SELECT * FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_QueryArApAuditAccountDetail_ExchangeFormat]') AND OBJECTPROPERTY(ID,N'ISPROCEDURE')=1)
DROP PROCEDURE Web_QueryArApAuditAccountDetail_ExchangeFormat
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：LUDALIN
	日期：2013-11-26
	描述：往来对账明细表
*/
CREATE PROCEDURE Web_QueryArApAuditAccountDetail_ExchangeFormat
(
    @OperatorId			VARCHAR(MAX),	--操作员ID
	@StartDate			VARCHAR(10),	--开始日期
	@EndDate			VARCHAR(10),	--截止日期
	@STypeId			VARCHAR(MAX),	--分支机构
	@BTypeId			VARCHAR(MAX),	--结算单位
	@Cid				VARCHAR(10),	--币种
	@IsDetail			VARCHAR(10),	--是否按展开明细
	@BillType			VARCHAR(MAX),	--单据类型
	@WhichDetail		VARCHAR(10),		--当前查询类型-'P':商品；'A'：账户；'B':单据
	@queryinvoice		INT,  --统计应收暂估
	@IsAccountDate		int, --是否按对账日过滤
	@QueryAccountDate	int,	 --报警薄读取对账日期预警
	@isLoginHit			INT=0,	  --报警簿是否需要红色提示
	@IsShowReconciliation	BIT--是否对账信息1：显示对账过数据 0 隐藏对账过数据
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @proinfo int
SELECT @proinfo=subvalue FROM sysdata where subname='proinfo'

--处理币种
SET @Cid=ISNULL(@Cid,0)
--分支机构
IF @Stypeid=''
	SET @STypeId='00000'
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT A.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)a
INNER JOIN SType_UserConfig U ON A.TypeId=U.StypeId 
WHERE U.Value=1

--结算单位
IF @Btypeid=''
	SET @BTypeId='00000'
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100), dzdays INT,dzwarningdays INT,fkdzdays INT,fkdzwarningdays int)
INSERT INTO #GetManBTypeId(TypeId,dzdays,dzwarningdays,fkdzdays,fkdzwarningdays) 
    SELECT A.TypeId,b.dzdays,b.dzwarningdays,b.fkdzdays,b.fkdzwarningdays FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)  A
    INNER JOIN BTYPE B ON A.Typeid=b.typeid
	
IF ISNULL(@BillType,'')=''
	SET @BillType='0' 


----------==============================================查询主体=====BEGIN==========================----------------------------
--思路:动态查询方式
--为了显示方便，默认将期初的billtype字段设计为-1，将小计的billtype 字段设计为-10
--
----------==========================================================================================-----------------------------
DECLARE @CREATESQL	 VARCHAR(MAX)='',--表创建语句1
		@CREATESQL2	VARCHAR(MAX),--表创建语句2
		@PTYPEDETAIL VARCHAR(MAX),--商品明细语句
		@zgnid		varchar(10)  --应收暂估项目id
	
SElECT @zgnid=NID FROM Ac_Items WHERE UserCode='2122' 
IF @queryinvoice<>1
	SET @zgnid=-1
--统计应收暂估
IF @queryinvoice=1
	SET @BillType=@BillType+',400,401,57'
IF @QueryAccountDate=1
BEGIN
	SET  @IsDetail = 'True' 
END

DECLARE @arBillType VARCHAR(1000)='11,12,45,160,148,149,141,93,85,213,167,168,172,116,115,181,405,4,189,414,2,46'
IF EXISTS(SELECT SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr' AND SubValue='1')
BEGIN
	 SET @arBillType+=',36'
END


--统计开票
CREATE TABLE #invoiceQty
(
	id	INT,
	ptypeid VARCHAR(50),
	billnumberid NUMERIC(24,10),
	billtype INT,
	uninvoiceqty NUMERIC(24,10),
	uninvoicemoney NUMERIC(24,10)
)
INSERT INTO #invoiceQty
(
	id,
	ptypeid,
	billnumberid,
	billtype,
	uninvoiceqty,
	uninvoicemoney
) 
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
		400,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN  @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
			 ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
			 END  /*本币未开票金额(含税)*/
FROM AppraisalBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    401,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN  @Cid=0 THEN ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
			  ELSE  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
			  END  /*本币未开票金额(含税)*/
		
FROM AppraisalBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    402,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
		END  /*本币未开票金额(含税)*/
FROM SendBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    403,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END   /*本币未开票金额(含税)*/
FROM SendBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	

UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    305,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)   
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)   
		END /*本币未开票金额(含税)*/
FROM retailbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    215,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
		END  /*本币未开票金额(含税)*/
FROM RetailBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    11,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
		END  /*本币未开票金额(含税)*/
FROM salebill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    45,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END   /*本币未开票金额(含税)*/
FROM salebackbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END   /*本币未开票金额(含税)*/
FROM salegoodsexchangebill a
WHERE a.InOrOut='I'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)  
		ELSE  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  
		END  /*本币未开票金额(含税)*/
FROM salegoodsexchangebill a
WHERE a.InOrOut='O'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    141,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END    /*本币未开票金额(含税)*/
FROM commissionbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    12,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END 
		  /*本币未开票金额(含税)*/
FROM PT_Combin_SaleBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    46,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE  ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0) 
		END    /*本币未开票金额(含税)*/
FROM PT_Combin_SaleBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    34,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END   /*本币未开票金额(含税)*/
FROM buybill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id		
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    6,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE  ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END    /*本币未开票金额(含税)*/
FROM buybackbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END    /*本币未开票金额(含税)*/
FROM buygoodsexchangebill a
WHERE A.InOrOut='O'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0)
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END    /*本币未开票金额(含税)*/
FROM buygoodsexchangebill a
WHERE A.InOrOut='I'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    145,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		CASE WHEN @cid=0 THEN  ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) 
		ELSE ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)
		END  /*本币未开票金额(含税)*/
FROM commissionbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
--SELECT * FROM #invoiceQty	
	
-----筛选表数据---------------
CREATE TABLE #BILLINDEX
(
	BILLNUMBERID NUMERIC(18,0),
	BILLCODE			VARCHAR(400),
	BILLDATE			DATETIME,
	BILLTYPE			VARCHAR(20),
	BTYPEID			VARCHAR(50),--单位
	TOTAL				 NUMERIC(24, 10) ,--单据金额
	NTOTAL			 NUMERIC(24, 10) ,--单据金额
	PREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	NPREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	PAYORINMONEY  NUMERIC(24, 10) ,--收或付款金额
	NPAYORINMONEY  NUMERIC(24, 10) ,--收或付款金额
	RECONCILIATION	VARCHAR(4),--对账标志
	Comment			VARCHAR(2000),
	BillBtypeID		VARCHAR(50),	-- 单据往来单位
	Etypeid			VARCHAR(50),   --经手人
	explain			VARCHAR(2000), --说明
	totalqty        NUMERIC(24, 10),
	accountdate		DATETIME,
	dzwarningdays	int 
)

SET @CREATESQL='
INSERT INTO #BILLINDEX
SELECT		BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.TOTALMONEY ELSE BI.TOTALMONEY-BI.PREFERENCEMONEY END,--单据金额
			CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.NTOTALMONEY ELSE BI.NTOTALMONEY-BI.NPREFERENCEMONEY END,--单据金额
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			t.total,
			t.ntotal,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			bi.explain,
			CASE WHEN BI.BILLTYPE IN(148,150) THEN 0 ELSE bi.totalqty   END AS totalqty,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays)
				ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays
				ELSE  b.fkdzwarningdays END
FROM   BILLINDEX BI 
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
LEFT JOIN (SELECT BillNumberId,BillType, SUM(NTotalMoney) as ntotal,sum(TOTAL) as total FROM dbo.BillMulAccount GROUP BY BillNumberId,billtype) t on bi.billnumberid=t.billnumberid and bi.billtype = t.billtype		
WHERE	BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
		AND BI.BILLTYPE NOT IN (115,116,128,129,126,139,159,161,160,57,450)
		AND BI.RedWord=0
		AND BI.IsIni=0 
		AND bi.ifYearBill = 0
		AND BI.IFCHECK=''t'''
		
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

IF @proinfo = 4 
BEGIN
	SET @CREATESQL+=' AND BI.BILLTYPE NOT IN (167, 168, 170, 172, 148, 150, 151, 149, 139, 126, 212, 213) '
END

--PRINT(@createsql)
--EXEC (@createsql)
--SELECT * FROM #BILLINDEX
--DROP TABLE  #BILLINDEX
--SELECT * FROM #GetManBTypeId
--SELECT * FROM #GetManSTypeId
--RETURN 

SET @CREATESQL +=' 
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			BI.TOTALMONEY -BI.PREFERENCEMONEY,--单据金额
			BI.NTOTALMONEY -BI.NPREFERENCEMONEY,--单据金额
			PreferenceMoney,--优惠金额
			NPreferenceMoney,--优惠金额
			t.total,
			t.ntotal,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end, 
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			'''' as explain,
			bi.totalqty AS totalqty,
            dbo.F_CalAccountDate(bi.billdate,b.FKdzdays),
			b.fkdzwarningdays
FROM        coupon_BillIndex BI 
			INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
			INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
			LEFT JOIN (SELECT BillNumberId,billtype,SUM(NTotalMoney) as ntotal,sum(TOTAL) as total FROM dbo.BillMulAccount  WHERE ATypeID NOT IN (27,39)  GROUP BY BillNumberId,billtype) t on bi.billnumberid=t.billnumberid and bi.billtype = t.billtype
				
WHERE 
			BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE  IN (423,424,426)
			AND BI.RedWord=0
			AND BI.IsIni=0 
			AND bi.ifYearBill = 0
			AND BI.IFCHECK= ''t'''
			
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

SET @CREATESQL+=' 
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			0,
			bi.totalmoney,
			BI.ntotalmoney,
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			bi.totalinmoney,
			BI.ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			bi.explain,
			0,
			null,
			null
FROM   BILLINDEX BI 
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE 
			 BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE IN (115,116,128,129,450)
			AND BI.RedWord=0
			AND BI.IsIni=0 
			AND bi.ifYearBill = 0
			AND BI.IFCHECK=''t'''
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

		
SET @CREATESQL+='
INSERT INTO #BILLINDEX
SELECT BI.BILLNUMBERID,
			BI.BILLCODE,
			BI.BILLDATE,
			BI.BILLTYPE,
			0,
			0,
			0,
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			0,
			0,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			bi.explain,
			0,
			null ,
			null
FROM BILLINDEX bi
WHERE BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE=159	
			AND BI.IfCheck = ''t''
			AND BI.Draft = 0
			AND BI.IsIni=0 
			AND bi.ifYearBill = 0
			AND BI.RedWord=0'	
			
SET @CREATESQL+='
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			bi.totalmoney,
			BI.ntotalmoney,
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			bi.totalinmoney,
			BI.ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			bi.explain,
			bi.totalqty,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays)
				ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays
				ELSE  b.fkdzwarningdays	END
FROM   BILLINDEX BI 
				INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE  BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE =139
			AND BI.RedWord=0
			AND BI.IsIni=0 
			AND bi.ifYearBill = 0
			AND BI.IFCHECK=''t'''
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

SET @CREATESQL+='
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			bi.totalmoney,
			BI.ntotalmoney,
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			bi.totalinmoney,
			BI.ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			bi.explain,
			bi.totalqty,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays)
				ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays
				ELSE  b.fkdzwarningdays	END
FROM   BILLINDEX BI
				INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE  BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE =126
			AND BI.RedWord=0
			AND BI.IsIni=0 
			AND bi.ifYearBill = 0
			AND BI.IFCHECK=''t'''

IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END
	
SET @CREATESQL+='
	--特殊处理换货单
INSERT INTO #BILLINDEX
SELECT  BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			BI.btypeid,
			CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.TOTALMONEY ELSE BI.TOTALMONEY-BI.PREFERENCEMONEY END,--单据金额
			CASE WHEN BI.BILLTYPE IN (4,66) THEN BI.NTOTALMONEY ELSE BI.NTOTALMONEY-BI.NPREFERENCEMONEY END,--单据金额
			BI.PREFERENCEMONEY,--优惠金额
			BI.NPREFERENCEMONEY,--优惠金额
			bi.totalinmoney,
			BI.ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			bi.explain,
			bi.totalqty,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays)
				ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays
				ELSE  b.fkdzwarningdays	END
FROM BILLINDEX BI
				INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
				LEFT JOIN (SELECT BillNumberId,billtype,SUM(NTotalMoney) as ntotal,sum(TOTAL) as total FROM dbo.BillMulAccount  GROUP BY BillNumberId,billtype) t on bi.billnumberid=t.billnumberid and bi.billtype = t.billtype
		
				WHERE  BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE IN (160,161)
			AND BI.RedWord=0
			AND BI.IsIni=0 
			AND bi.ifYearBill = 0
			AND BI.IFCHECK=''t''
'
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

-- 发票
SET @CREATESQL+=' 
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			bi.btypeid,
			bi.TaxTotalMoney,
			BI.NTaxTotalMoney,
			0 as PREFERENCEMONEY,--优惠金额
			0 as NPREFERENCEMONEY,--优惠金额
			0 as totalinmoney,
			0 as ntotalinmoney,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			bi.explain,
			bi.totalqty,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays)
				ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays
				ELSE  b.fkdzwarningdays	END
FROM   ReceiptBillIndex BI 
INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
WHERE	BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
		AND BI.BILLTYPE IN (404,405)
		AND BI.RedWord=0
		AND BI.IsIni=0 
		AND bi.ifYearBill = 0
		AND BI.IFCHECK=''t'''
		
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

--成本调价单
SET @CREATESQL+=' 
INSERT INTO #BILLINDEX
SELECT BI.BillNumberId,
			BI.BillCode,
			BI.BillDate,
			BI.BillType,
			bi.btypeid,
			bi.totalmoney,
			BI.ntotalmoney,
			0,--优惠金额
			0,--优惠金额
			0,
			0,
			case when BI.Reconciliation=''t'' then ''√'' else '''' end,
			BI.Comment,
			BI.DealBTypeID,
			bi.etypeid,
			bi.explain,
			0  ,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(bi.billdate,b.dzdays)
				ELSE dbo.F_CalAccountDate(bi.billdate,b.FKdzdays) END,
			CASE WHEN BI.BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays
				ELSE  b.fkdzwarningdays	END
FROM   BILLINDEX BI 
				INNER JOIN #GetManSTypeId S ON BI.STYPEID=S.TypeId
				INNER JOIN #GetManBTypeId B ON BI.btypeid=B.TypeId
WHERE 
			 BI.BillType IN (SELECT * FROM dbo.f_split('+CHAR(39)+@BillType+CHAR(39)+','',''))
			AND BI.BILLTYPE=57
			AND BI.RedWord=0
			AND BI.IsIni=0 
			AND bi.ifYearBill = 0
			AND BI.AdPriceType=1
			AND BI.IFCHECK=''t'''
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND BI.CID LIKE '''+@Cid+''''
END

EXEC(@CREATESQL)
--SELECT * FROM #BILLINDEX WHERE billtype IN (400,401)

---------------------------计算期初数据-----------------------------
-----统计算法：本来的期初往来余额+本期截至到查询开始时间之前的往来余额
CREATE TABLE #TOTAL00
(
	BTYPEID VARCHAR(100),
	ARTOTAL  NUMERIC(24, 10) ,--应收金额
	NARTOTAL  NUMERIC(24, 10) ,
	APTOTAL  NUMERIC(24, 10) ,--应付金额
	NAPTOTAL  NUMERIC(24, 10) ,
	zgTOTAL  NUMERIC(24, 10) ,--应付暂估
	NzgTOTAL  NUMERIC(24, 10) ,
	YSTOTAL  NUMERIC(24, 10) ,--预收金额
	NYSTOTAL  NUMERIC(24, 10) ,
	YFTOTAL  NUMERIC(24, 10) ,--预付金额
	NYFTOTAL  NUMERIC(24, 10) ,
	QMTOTAL  NUMERIC(24, 10) ,--往来余额
	NQMTOTAL  NUMERIC(24, 10) 
)

SET @CREATESQL='

INSERT INTO #TOTAL00
SELECT BTypeID,
			SUM(ARTOTAL),
			SUM(NARTOTAL),
			SUM(APTOTAL),
			SUM(NAPTOTAL),
			SUM(zgTOTAL),
			SUM(nzgTOTAL),
			SUM(YSTOTAL),
			SUM(NYSTOTAL),
			SUM(YFTOTAL),
			SUM(NYFTOTAL),
			SUM(ARTOTAL)-SUM(APTOTAL)-SUM(YSTOTAL)+SUM(YFTOTAL)-SUM(zgTOTAL),
			SUM(NARTOTAL)-SUM(NAPTOTAL)-SUM(NYSTOTAL)+SUM(NYFTOTAL)-SUM(nzgTOTAL)
FROM  (
			SELECT  BTypeID,
					SUM(ISNULL(ARTotal00,0)) AS ARTOTAL,
					SUM(ISNULL(nARTotal00,0)) AS NARTOTAL,
					SUM(ISNULL(APTotal00,0)) AS APTOTAL,
					SUM(ISNULL(nAPTotal00,0)) AS NAPTOTAL,
					CASE WHEN '+CAST(@queryinvoice AS VARCHAR)+'=1 THEN SUM(ISNULL(GRIRTotal00,0)) ELSE 0 END as zgTOTAL,
					CASE WHEN '+CAST(@queryinvoice AS VARCHAR)+'=1 THEN SUM(ISNULL(nGRIRTotal00,0)) ELSE 0 END as nzgTOTAL,
					SUM(ISNULL(YSTotal00,0)) AS YSTOTAL,
					SUM(ISNULL(nYSTotal00,0)) AS NYSTOTAL,
					SUM(ISNULL(YFTotal00,0)) AS YFTOTAL,
					SUM(ISNULL(nYFTotal00,0)) AS NYFTOTAL
			FROM dbo.BType_ArApTotal A
						INNER JOIN #GetManBTypeId B ON A.BTypeID=B.TypeId
						INNER JOIN #GetManSTypeId S ON S.TypeId=A.STypeID
			WHERE 1=1 '
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' and A.CID LIKE '''+@Cid+''''
END
		
SET @CREATESQL+='
			GROUP BY A.BTypeID
			UNION ALL
			SELECT L.BtypeId,
			ISNULL(SUM(CASE WHEN L.ATYPEID=33
						THEN Total
						END),0) AS ARTotal,
		    ISNULL(SUM(CASE WHEN L.ATYPEID=33
						THEN NTotal
						END),0) AS NARTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID=35
			THEN Total
			END),0) AS APTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID=35
						THEN NTotal
						END),0) AS NAPTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID='+@zgnid+'
						THEN Total
						END),0) AS zgTOTAL,
			ISNULL(SUM(CASE WHEN L.ATYPEID='+@zgnid+'
						THEN nTotal
						END),0) AS nzgTOTAL,
			 ISNULL(SUM(CASE WHEN L.ATYPEID=39
						THEN Total
						END),0) AS YSTotal,
		   ISNULL(SUM(CASE WHEN L.ATYPEID=39
						THEN NTotal
						END),0) AS NYSTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID=27
						THEN Total
						END),0) AS YFTotal,
			ISNULL(SUM(CASE WHEN L.ATYPEID=27
						THEN NTotal
						END),0) AS NYFTotal
		   FROM ListTable L
		   INNER JOIN #GetManBTypeId B ON B.TypeId=L.BtypeId
		   INNER JOIN #GetManSTypeId S ON S.TypeId=L.STypeID
		   WHERE L.BillDate<'+CHAR(39)+@StartDate+CHAR(39)+'
				  AND L.ATYPEID IN (33,35,39,27,'+@zgnid+')
						' 
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND L.CID LIKE '''+@Cid+''''
END
IF @queryinvoice=1
	SET @CREATESQL+='  AND L.ATYPEID IN (33,35,39,27,'+@zgnid+') '
ELSE	
	SET @CREATESQL+='
						AND L.AtypeId  IN (33,35,39,27) '
SET @CREATESQL+='
			GROUP BY L.BtypeId
			) A 
GROUP BY A.BTypeID '

EXEC(@CREATESQL)

--PRINT @CREATESQL
--DELETE FROM #TOTAL00 WHERE ARTOTAL=0 AND APTOTAL=0 AND YSTOTAL=0 AND YFTOTAL=0 AND QMTOTAL=0
-------------------统计明细，按照单据类型、单位--------------------
CREATE TABLE #BILLTOTAL
(
	BTYPEID			VARCHAR(50),--单位
	BILLNUMBERID	VARCHAR(20),
	BILLTYPE			VARCHAR(20),
	BILLDATE			DATETIME,
	BILLCODE			VARCHAR(400),
	BILLTOTAL		 NUMERIC(24, 10) ,--	单据金额
	NBILLTOTAL		 NUMERIC(24, 10) ,--	单据金额
	PREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	NPREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	INTOTAL		 NUMERIC(24, 10) ,--实收金额
	NINTOTAL		 NUMERIC(24, 10) ,--实收金额
	ARTOTAL		 NUMERIC(24, 10) ,--应收金额
	NARTOTAL		 NUMERIC(24, 10) ,--应收金额
	PAYTOTAL	 NUMERIC(24, 10) ,--实付金额
	NPAYTOTAL	 NUMERIC(24, 10) ,--实付金额
	APTOTAL		 NUMERIC(24, 10) ,--应付金额
	NAPTOTAL		 NUMERIC(24, 10) ,--应付金额
	YSTOTAL		 NUMERIC(24, 10) ,--预收金额
	NYSTOTAL		 NUMERIC(24, 10) ,--预收金额
	YFTOTAL		 NUMERIC(24, 10) ,--预付金额
	NYFTOTAL		 NUMERIC(24, 10) ,--预付金额
	QMTOTAL	 NUMERIC(24, 10) ,--往来余额
	NQMTOTAL	 NUMERIC(24, 10) ,--往来余额
	RECONCILIATION	VARCHAR(4),--对账标志
	Comment			VARCHAR(2000),
	BillBtypeID		VARCHAR(50),	--单据往来单位
	zgtotal		 NUMERIC(24, 10) ,   --应付暂估
	nzgtotal	 NUMERIC(24, 10) ,  --应付暂估
	etypeid		VARCHAR(50),  --经手人
	explain			varchar(2000), --说明
	totalqty    NUMERIC(24, 10),
	accountdate	VARCHAR(10)  
)

DECLARE @Sqlwheredate VARCHAR(500),
	@Sqlwheredate1 VARCHAR(500)
--特殊业务凭证
SET  @CREATESQL='
INSERT INTO #BILLTOTAL
SELECT L.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			0,--实收
			0,--实收
			CASE WHEN L.AtypeId=33 THEN L.Total END ,--应收
			CASE WHEN L.AtypeId=33 THEN L.NTotal END ,--应收
			0,--实付
			0,--实付
			CASE WHEN L.AtypeId=35 THEN L.Total END ,--应付
			CASE WHEN L.AtypeId=35 THEN L.NTotal END ,--应付
			CASE WHEN L.AtypeId=39 THEN L.Total END ,--预收
			CASE WHEN L.AtypeId=39 THEN L.NTotal END ,--预收
			CASE WHEN L.AtypeId=27 THEN L.Total END ,--预付
			CASE WHEN L.AtypeId=27 THEN L.NTotal END ,--预付
			0,
			0,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID,
			CASE WHEN L.AtypeId='+@zgnid+' THEN L.Total END AS zgtotal,
			CASE WHEN L.AtypeId='+@zgnid+' THEN L.nTotal END AS nzgtotal,
			a.etypeid,
			a.explain,
			a.totalqty,
			convert(nvarchar(10),l.accountdate,120)
			FROM #BILLINDEX A 
			 INNER JOIN (   select billnumberid,ATYPEID,BTYPEID,total,ntotal,cid,
							CASE WHEN BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(billdate,b.dzdays)
								ELSE dbo.F_CalAccountDate(billdate,b.FKdzdays) END AS accountdate,
							CASE WHEN BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays
								ELSE  b.fkdzwarningdays	END	 AS dzwarningdays
							from ListTable 
							INNER JOIN #GetManBTypeId B ON B.TypeId=BtypeId
							INNER JOIN #GetManSTypeId S ON S.TypeId=STypeID
							WHERE ATYPEID IN(33,35,27,39,'+@zgnid+') AND BILLTYPE in(159)   AND ISNULL(BtypeId,'''')<>''''
							
						) L ON A.BILLNUMBERID = L.BillNumberId 
WHERE A.BILLTYPE in(159) '
--业务凭证特殊处理，币种判断表体
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND L.CID LIKE '''+@Cid+''''
END
IF (@IsAccountDate=1)
	BEGIN
		SET @Sqlwheredate=' AND l.accountdate>='+CHAR(39)+@STARTDATE+CHAR(39)
	END
ELSE
	BEGIN
		SET @Sqlwheredate=' AND A.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
	END
IF (@IsAccountDate=1)
	BEGIN
		SET @Sqlwheredate1=' AND l.accountdate<='+CHAR(39)+@ENDDATE+CHAR(39)
	END
ELSE
	BEGIN
		SET @Sqlwheredate1=' AND A.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)
	END
	
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+@Sqlwheredate
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+@Sqlwheredate1
	
IF	@QueryAccountDate=1
BEGIN
	SET  @CREATESQL=@CREATESQL+' AND DATEDIFF (DAY , GETDATE(), A.accountdate)<=l.dzwarningdays '
END
--特殊处理往来核销单
SET  @CREATESQL=@CREATESQL+
'
INSERT INTO #BILLTOTAL
SELECT L.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			0,--实收
			0,--实收
			SUM(CASE WHEN L.AtypeId=33 THEN L.Total ELSE 0 END) ,--应收
			SUM(CASE WHEN L.AtypeId=33 THEN L.NTotal ELSE 0 END) ,--应收
			0,--实付
			0,--实付
			SUM(CASE WHEN L.AtypeId=35 THEN L.Total ELSE 0 END) ,--应付
			SUM(CASE WHEN L.AtypeId=35 THEN L.NTotal ELSE 0 END) ,--应付
			SUM(CASE WHEN L.AtypeId=39 THEN L.Total ELSE 0 END) ,--预收
			SUM(CASE WHEN L.AtypeId=39 THEN L.NTotal ELSE 0 END) ,--预收
			SUM(CASE WHEN L.AtypeId=27 THEN L.Total ELSE 0 END) ,--预付
			SUM(CASE WHEN L.AtypeId=27 THEN L.NTotal ELSE 0 END) ,--预付
			0,
			0,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID,
			SUM(CASE WHEN L.AtypeId='+@zgnid+' THEN L.Total ELSE 0 END) AS zgtotal,
			SUM(CASE WHEN L.AtypeId='+@zgnid+' THEN L.nTotal ELSE 0 END) AS nzgtotal,
			a.etypeid,
			a.explain,
			a.totalqty,
			convert(nvarchar(10),l.accountdate,120)
			FROM #BILLINDEX A 
			INNER JOIN (   select billnumberid,ATYPEID,BTYPEID,total,ntotal,cid,
							CASE WHEN AtypeId IN(33,39) THEN dbo.F_CalAccountDate(billdate,b.dzdays)
								ELSE dbo.F_CalAccountDate(billdate,b.FKdzdays) END AS accountdate,
							CASE WHEN  AtypeId IN(33,39) THEN b.dzwarningdays
								ELSE  b.fkdzwarningdays	END	 AS dzwarningdays
							from ListTable 
							INNER JOIN #GetManBTypeId B ON B.TypeId=BtypeId
							INNER JOIN #GetManSTypeId S ON S.TypeId=STypeID
							WHERE ATYPEID IN(33,35,27,39,'+@zgnid+') AND BILLTYPE in(450)   AND ISNULL(BtypeId,'''')<>''''
							
						) L ON A.BILLNUMBERID = L.BillNumberId 
WHERE A.BILLTYPE in(450) '
--业务凭证特殊处理，币种判断表体
IF @CID<>0 AND ISNULL(@Cid,0)<>0
BEGIN
	SET @CREATESQL+=' AND L.CID LIKE '''+@Cid+''''
END
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+@Sqlwheredate
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+@Sqlwheredate1
	
IF	@QueryAccountDate=1
BEGIN
	SET  @CREATESQL=@CREATESQL+' AND DATEDIFF (DAY , GETDATE(), A.accountdate)<=l.dzwarningdays '
END
SET   @CREATESQL=@CREATESQL+' 
		GROUP BY 
			L.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额  
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID, 
			a.etypeid,
			a.explain,
			a.totalqty,
			l.accountdate
		'


DECLARE @ZGTYPEID VARCHAR(10)
SELECT @ZGTYPEID=NID FROM Ac_Items WHERE UserCode='2122'

SET @CREATESQL +='

INSERT INTO #BILLTOTAL
SELECT A.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			CASE WHEN A.BILLTYPE IN(11,93,141,85,157,167,168,172,178,186,150,305,195,181,312,182,179,196,200,213,151,424,12) THEN ISNULL(A.PAYORINMONEY,0) 
					WHEN A.BILLTYPE =160 THEN ISNULL(A.PAYORINMONEY,0)
					WHEN A.BILLTYPE IN (189) THEN ISNULL(A.TOTAL,0)
					WHEN A.BILLTYPE IN (4) THEN ISNULL(A.TOTAL,0)+ISNULL(A.PREFERENCEMONEY,0)+isnull(B.YSTOTAL,0)
					WHEN A.BILLTYPE IN (6) THEN ISNULL(A.PAYORINMONEY,0)
							ELSE 0 END,--收款类单据有实收金额
		CASE WHEN A.BILLTYPE IN(11,93,141,85,157,167,168,172,178,186,150,305,195,181,312,182,179,196,200,213,151,424,12) THEN ISNULL(A.NPAYORINMONEY,0) 
					WHEN A.BILLTYPE =160 THEN ISNULL(A.NPAYORINMONEY,0)--预收预付本来就是负数
					WHEN A.BILLTYPE IN (189) THEN ISNULL(A.nTOTAL,0)
					WHEN A.BILLTYPE IN (4) THEN  ISNULL(A.NTOTAL,0)+ISNULL(A.NPREFERENCEMONEY,0)+isnull(B.NYSTOTAL,0)
					WHEN A.BILLTYPE IN (6) THEN ISNULL(A.NPAYORINMONEY,0) 
					ELSE 0 END,--收款类单据有实收金额	
			CASE WHEN a.billtype=4 THEN -(ISNULL(A.TOTAL,0)+ISNULL(A.PREFERENCEMONEY,0) )
			     ELSE b.ARTOTAL END,--应收--收款单算法比较变态
			CASE WHEN a.billtype=4 THEN -(ISNULL(A.NTOTAL,0)+ISNULL(A.NPREFERENCEMONEY,0))
				 ELSE b.NARTOTAL END,--应收
			CASE WHEN A.BILLTYPE IN (34,145,84,170,148,212,45,215,149,423,426,46) THEN ISNULL(A.PAYORINMONEY,0) 
					 WHEN A.BILLTYPE =161 THEN ISNULL(A.PAYORINMONEY,0)
					 WHEN A.BILLTYPE IN (190) THEN ISNULL(A.TOTAL,0)
					 WHEN A.BILLTYPE IN (66) THEN ISNULL(A.TOTAL,0)+ISNULL(A.PREFERENCEMONEY,0)+isnull(B.YFTOTAL,0)
										ELSE 0 END,--付款类单据有实付金额
			CASE WHEN A.BILLTYPE IN (34,145,84,170,148,212,45,215,149,423,426,46) THEN ISNULL(A.NPAYORINMONEY,0) 
					 WHEN A.BILLTYPE =161 THEN ISNULL(A.NPAYORINMONEY,0)
					WHEN A.BILLTYPE  IN (190) THEN ISNULL(A.NTOTAL,0)
					WHEN A.BILLTYPE IN (66) THEN  ISNULL(A.NTOTAL,0)+ISNULL(A.NPREFERENCEMONEY,0)+isnull(B.NYSTOTAL,0)
										ELSE 0 END,--付款类单据有实付金额
			CASE WHEN a.billtype=66 THEN -(ISNULL(A.TOTAL,0)+ISNULL(A.PREFERENCEMONEY,0)) 
				 ELSE B.APTOTAL END,--应付
			CASE WHEN a.billtype=66 THEN -(ISNULL(A.NTOTAL,0)+ISNULL(A.NPREFERENCEMONEY,0))
				 ELSE B.NAPTOTAL END,--应付
			B.YSTOTAL,--预收
			B.NYSTOTAL,--预收
			B.YFTOTAL,--预付
			B.NYFTOTAL,--预付
			B.ARTOTAL-B.APTOTAL-B.YSTOTAL+B.YFTOTAL-ISNULL(b.zgtotal,0),
			B.NARTOTAL-B.NAPTOTAL-B.NYSTOTAL+B.NYFTOTAL-ISNULL(b.nzgtotal,0),
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID,
			b.zgtotal,
			b.nzgtotal,
			a.etypeid,
			a.explain,
			a.totalqty,
			convert(nvarchar(10),a.accountdate,120)
FROM #BILLINDEX A
		LEFT JOIN (SELECT   BillNumberId,
							BILLTYPE,
							SUM(CASE WHEN AtypeId=33 THEN Total END) AS ARTOTAL,
							SUM(CASE WHEN AtypeId=33 THEN nTotal END) AS NARTOTAL,
							SUM(CASE WHEN AtypeId=35 THEN Total END) AS APTOTAL,
							SUM(CASE WHEN AtypeId=35 THEN nTotal END) AS NAPTOTAL,
							SUM(CASE WHEN AtypeId=39 THEN Total END) AS YSTOTAL,
							SUM(CASE WHEN AtypeId=39 THEN nTotal END) AS NYSTOTAL,
							SUM(CASE WHEN AtypeId=27 THEN Total END) AS YFTOTAL,
							SUM(CASE WHEN AtypeId=27 THEN nTotal END) AS NYFTOTAL,
							SUM(CASE WHEN AtypeId='+@zgnid+' THEN Total END) AS zgtotal,
							SUM(CASE WHEN AtypeId='+@zgnid+' THEN nTotal END) AS nzgtotal
					FROM LISTTABLE 
					WHERE ATYPEID IN(33,35,27,39,'+@zgnid+')
					--INNER JOIN #GetManBTypeId B ON B.TypeId=LISTTABLE.BtypeId
					--INNER JOIN #GetManSTypeId S ON S.TypeId=LISTTABLE.STypeID
					GROUP BY BillNumberId,BILLTYPE
					) B ON A.BILLNUMBERID = B.BillNumberId  and a.BILLTYPE=b.BILLTYPE
														--INNER JOIN dbo.BillIndex c ON a.billnumberid=c.BillNumberId and a.BILLTYPE=c.BILLTYPE
WHERE A.BILLTYPE NOT IN (115,116,128,129,36,159,450) '
IF (@IsAccountDate=1)
	BEGIN
		SET @Sqlwheredate=' AND a.accountdate>='+CHAR(39)+@STARTDATE+CHAR(39)
	END
ELSE
	BEGIN
		SET @Sqlwheredate=' AND A.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
	END
IF (@IsAccountDate=1)
	BEGIN
		SET @Sqlwheredate1=' AND a.accountdate<='+CHAR(39)+@ENDDATE+CHAR(39)
	END
ELSE
	BEGIN
		SET @Sqlwheredate1=' AND A.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)
	END
	
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+@Sqlwheredate
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+@Sqlwheredate1
	
IF	@QueryAccountDate=1
BEGIN
	SET  @CREATESQL=@CREATESQL+' AND DATEDIFF (DAY , GETDATE(), A.accountdate)<=a.dzwarningdays '
END

IF @WhichDetail<>'p'
	SET  @CREATESQL=@CREATESQL+' AND (B.ARTOTAL<>0 OR B.APTOTAL<>0 OR B.YSTOTAL<>0 OR B.zgtotal<>0 OR B.YFTOTAL<>0)  '
	

	
-------调账类四张单据+往来核销单据------
SET @CREATESQL+=' 
INSERT INTO #BILLTOTAL
SELECT L.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			L.TOTAL,
			L.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			0,--收款类单据有实收金额
			0,
			L.ARTOTAL,--应收
			L.NARTOTAL,--应收
			0,--付款类单据有实付金额
			0,
			L.APTOTAL,--应付
			L.NAPTOTAL,--应付
			l.ystotal,--预收
			l.nystotal,
			l.yftotal,--预付
			l.nyftotal,
			0,
			0,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID,
			0,
			0,
			a.etypeid,
			a.explain,
			a.totalqty,
			convert(nvarchar(10),l.accountdate,120)
FROM #BILLINDEX A
INNER JOIN ( select	billnumberid,btypeid,ATYPEID,
					SUM(CASE WHEN BTYPEID<>'''' THEN ABS(TOTAL) ELSE 0 END) AS TOTAL,
					SUM(CASE WHEN BTYPEID<>'''' THEN ABS(NTOTAL) ELSE 0 END) AS NTOTAL,
					CASE WHEN ATYPEID=''33'' THEN SUM(total) ELSE 0 END AS ARTOTAL,
					CASE WHEN ATYPEID=''33'' THEN SUM(Ntotal) ELSE 0 END AS NARTOTAL,
					 CASE WHEN ATYPEID=''35'' THEN SUM(total) ELSE 0 END AS APTOTAL,
					CASE WHEN ATYPEID=''35'' THEN SUM(ntotal) ELSE 0 END AS NAPTOTAL,
					--预收
					 CASE WHEN ATYPEID=''39'' THEN SUM(total) ELSE 0 END AS ysTOTAL,
					CASE WHEN ATYPEID=''39'' THEN SUM(ntotal) ELSE 0 END AS NysTOTAL,
					--预付
					 CASE WHEN ATYPEID=''27'' THEN SUM(total) ELSE 0 END AS yfTOTAL,
					CASE WHEN ATYPEID=''27'' THEN SUM(ntotal) ELSE 0 END AS NyfTOTAL,
					CASE WHEN BILLTYPE IN ('+@arBillType+') THEN dbo.F_CalAccountDate(billdate,b.dzdays)
						ELSE dbo.F_CalAccountDate(billdate,b.FKdzdays) END AS accountdate,
					CASE WHEN BILLTYPE IN ('+@arBillType+') THEN b.dzwarningdays
						ELSE  b.fkdzwarningdays	END	 AS dzwarningdays
					 from ListTable 
					 INNER JOIN #GetManBTypeId B ON B.TypeId=BtypeId
					  INNER JOIN #GetManSTypeId S ON S.TypeId=STypeID
					 WHERE  ATYPEID IN (33,35) AND BILLTYPE IN (115,116,128,129)
					GROUP BY BillNumberId,billtype,BtypeId,AtypeId,billdate,dzdays,b.dzwarningdays,FKdzdays,fkdzwarningdays 
					 ) L ON A.BILLNUMBERID = L.BillNumberId 
WHERE 1=1  AND A.BILLTYPE IN (115,116,128,129)
'
IF (@IsAccountDate=1)
	BEGIN
		SET @Sqlwheredate=' AND l.accountdate>='+CHAR(39)+@STARTDATE+CHAR(39)
	END
ELSE
	BEGIN
		SET @Sqlwheredate=' AND A.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
	END
IF (@IsAccountDate=1)
	BEGIN
		SET @Sqlwheredate1=' AND l.accountdate<='+CHAR(39)+@ENDDATE+CHAR(39)
	END
ELSE
	BEGIN
		SET @Sqlwheredate1=' AND A.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)
	END
	
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+@Sqlwheredate
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+@Sqlwheredate1
	
IF	@QueryAccountDate=1
BEGIN
	SET  @CREATESQL=@CREATESQL+' AND DATEDIFF (DAY , GETDATE(), l.accountdate)<=l.dzwarningdays '
END

DECLARE @ExpenseToAr VARCHAR(10)='0'
SELECT @ExpenseToAr=ISNULL(SubValue,'0') FROM dbo.sysdata WHERE SubName='ExpenseToAr'
-------费用单------
SET @CREATESQL+=' 
INSERT INTO #BILLTOTAL
SELECT A.BTYPEID,
			A.BILLNUMBERID,
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			A.TOTAL,
			A.NTOTAL,
			A.PREFERENCEMONEY,--优惠金额
			A.NPREFERENCEMONEY,--优惠金额
			0,--收款类单据有实收金额
			0,
			CASE WHEN '+@ExpenseToAr+'=''1''  AND LEFT(A.BTYPEID,5)=''00001''  THEN L.ARTOTAL ELSE 0 END,--应收
			CASE WHEN '+@ExpenseToAr+'=''1''  AND LEFT(A.BTYPEID,5)=''00001'' THEN L.ARTOTAL ELSE 0 END,--应收
			
			--CASE WHEN '+@ExpenseToAr+'=''1''  AND LEFT(A.BTYPEID,5)=''00001''  THEN -(A.TOTAL-ISNULL(a.PAYORINMONEY,0)-ISNULL(-L.YFTOTAL,0)) ELSE 0 END,--应收
			--CASE WHEN '+@ExpenseToAr+'=''1''  AND LEFT(A.BTYPEID,5)=''00001'' THEN -(A.NTOTAL-ISNULL(a.nPAYORINMONEY,0)-ISNULL(-L.NYFTOTAL,0)) ELSE 0 END,--应收
			A.PAYORINMONEY,--A.PAYORINMONEY-L.YFTOTAL,--付款类单据有实付金额
			A.NPAYORINMONEY,--A.NPAYORINMONEY-L.NYFTOTAL,--付款类单据有实付金额
			CASE WHEN '+@ExpenseToAr+'=''1''  and LEFT(A.BTYPEID,5)=''00001''  THEN  0  ELSE L.APTOTAL END,--应付
			CASE WHEN '+@ExpenseToAr+'=''1''  and  LEFT(A.BTYPEID,5)=''00001''  THEN  0  ELSE L.NAPTOTAL END,--应付
			0,--预收
			0,
			L.YFTOTAL,--预付
			L.NYFTOTAL,--预付
			0,
			0,
			A.RECONCILIATION,
			A.Comment,
			A.BillBtypeID,
			0,
			0,
			a.etypeid,
			a.explain,
			a.totalqty,
			convert(nvarchar(10),a.accountdate,120)
	FROM #BILLINDEX A LEFT JOIN (
								SELECT BillNumberId,
											SUM(CASE WHEN AtypeId=33 THEN Total ELSE 0 END) AS ARTOTAL,
											SUM(CASE WHEN AtypeId=33 THEN NTotal ELSE 0 END) AS NARTOTAL,
											SUM(CASE WHEN AtypeId=35 THEN Total ELSE 0 END) AS APTOTAL ,
											SUM(CASE WHEN AtypeId=35 THEN NTotal ELSE 0 END) AS NAPTOTAL,
											SUM(CASE WHEN AtypeId=39 THEN Total ELSE 0 END) AS YSTOTAL,
											SUM(CASE WHEN AtypeId=39 THEN NTotal ELSE 0 END) AS NYSTOTAL,
											SUM(CASE WHEN AtypeId=27 THEN Total ELSE 0 END) AS YFTOTAL,
											SUM(CASE WHEN AtypeId=27 THEN NTotal ELSE 0 END) AS NYFTOTAL
									FROM ListTable L
									--INNER JOIN #GetManBTypeId B ON B.TypeId=L.BtypeId
									--INNER JOIN #GetManSTypeId S ON S.TypeId=L.STypeID
									 WHERE BillType=36
									GROUP BY BillNumberId
								) L ON A.BILLNUMBERID = L.BillNumberId
 WHERE A.BILLTYPE =36
'
			
IF (@IsAccountDate=1)
	BEGIN
		SET @Sqlwheredate=' AND a.accountdate>='+CHAR(39)+@STARTDATE+CHAR(39)
	END
ELSE
	BEGIN
		SET @Sqlwheredate=' AND A.BILLDATE>='+CHAR(39)+@STARTDATE+CHAR(39)
	END
IF (@IsAccountDate=1)
	BEGIN
		SET @Sqlwheredate1=' AND a.accountdate<='+CHAR(39)+@ENDDATE+CHAR(39)
	END
ELSE
	BEGIN
		SET @Sqlwheredate1=' AND A.BILLDATE<='+CHAR(39)+@ENDDATE+CHAR(39)
	END
	
IF @STARTDATE<>''
	SET @CREATESQL=@CREATESQL+@Sqlwheredate
IF @ENDDATE<>''
	SET  @CREATESQL=@CREATESQL+@Sqlwheredate1
	
IF	@QueryAccountDate=1
BEGIN
	SET  @CREATESQL=@CREATESQL+' AND DATEDIFF(DAY , GETDATE(), A.accountdate)<=a.dzwarningdays  
	'
END

IF(@QueryAccountDate=1 AND @isLoginHit=1)
BEGIN
	 SET @CREATESQL=@CREATESQL+' select top 1 ''arapaccounthit'',1 from #BILLTOTAL 
						DROP TABLE #BILLINDEX	,#TOTAL00,#BILLTOTAL '
	 EXEC(@CREATESQL)
	 RETURN
END
ELSE
BEGIN 
	EXEC(@CREATESQL)
END 

------------------最终数据临时表------------------------
--特殊处理期初和小计的单据类型--期初：-1，小计：-10.有问题问我----------
CREATE TABLE #RESULT
(
	BTYPEID			VARCHAR(50),--单位 
	BILLNUMBERID	VARCHAR(20),
	PTYPEID			VARCHAR(100),
	PRICE			VARCHAR(20),
	QTY				NUMERIC(24, 10) ,
	UFULLNAME		VARCHAR(100),
	TOTAL			NUMERIC(24, 10) ,
	SALETOTAL		VARCHAR(24) ,
	BASEQTY			NUMERIC(24, 10) ,
	NTAXPRICE		VARCHAR(20) ,
	BASEFULLNAME	VARCHAR(200),
	UNITRALATION	VARCHAR(200), 
	DISCOUNT		NUMERIC(24, 10),
	BILLTYPE			VARCHAR(20),
	BILLDATE			DATETIME,
	BILLCODE			VARCHAR(400),
	BILLTOTAL		  varchar(100),--	单据金额(没有成本要显示*因此要定义成文本)
	PREFERENCEMONEY  NUMERIC(24, 10) ,--优惠金额
	INTOTAL		 NUMERIC(24, 10) ,--实收金额
	ARTOTAL		 NUMERIC(24, 10) ,--应收金额
	PAYTOTAL	 NUMERIC(24, 10) ,--实付金额
	APTOTAL		 NUMERIC(24, 10) ,--应付金额
	YSTOTAL		 NUMERIC(24, 10) ,--预收金额
	YFTOTAL		 NUMERIC(24, 10) ,--预付金额
	QMTOTAL	 NUMERIC(24, 10) ,--往来余额
	RECONCILIATION	VARCHAR(4),--对账标志
	SORTID		INT,					--排序id
	PSORTID		INT,					--再来一个排序id,商品或收款账户用
	Comment		VARCHAR(2000),
	BillSort	VARCHAR(50), --wg 按照时间排序，同时保持同一单据在一起
	BillBtypeID	VARCHAR(50),--单据往来单位--对应界面的字段名字
	DetailComment VARCHAR(2000) default(''''), --单据明细
	explain		VARCHAR(2000), --说明
	zgtotal    NUMERIC(24, 10) , --应付暂估金额
	etypeid		VARCHAR(50), --经手人
	fpsort		int,
	AccountDate  VARCHAR(10),
	ID INT,--明细排序ID
	uninvoiceqty NUMERIC(24,10) default(0), --未开票数量
	uninvoicemoney NUMERIC(24,10) default(0) --未开票金额
)

IF NOT EXISTS(select * from #TOTAL00)
BEGIN

INSERT INTO #RESULT
SELECT  TypeID,
		-99999,--期初不写值
		NULL,
		0,
		0,
		'',
		0,
		0,
		0,
		0,
		'',
		'',
		0, 
		'-1',
		NULL,
		'',
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		'',
		-1,
		0,
		'',	
		'',
		'',
		'',
		'',
		0,
		'',
		0  ,
		'',
		-1,
		0,--未开票数量
		0 --未开票金额
FROM #GetManBTypeId

END


INSERT INTO #RESULT
SELECT  BTYPEID,
			 -99999,--期初不写值
			NULL,
			0,
			0,
			'',
			0,
			0,
			0,
			0,
			'',
			'',
			0, 
			'-1',--期初强写-1
			NULL,
			'',
			0,
			0,--优惠金额
			0,
			ISNULL(CASE WHEN @CID='0' THEN ARTOTAL ELSE NARTOTAL END,0),
			0,
			ISNULL(CASE WHEN @CID='0' THEN APTOTAL ELSE NAPTOTAL END,0),
			ISNULL(CASE WHEN @CID='0' THEN YSTOTAL ELSE NYSTOTAL END,0),
			ISNULL(CASE WHEN @CID='0' THEN YFTOTAL ELSE NYFTOTAL END,0),
			ISNULL(CASE WHEN @CID='0'THEN QMTOTAL ELSE NQMTOTAL END,0),
			 '',
			-1,
			0,
			'',	--期初强写
			'',
			'',
			'',
			'',
			ISNULL(CASE WHEN @CID='0' THEN zgtotal ELSE nzgtotal END,0),
			'''',
			0  ,
			'',
			-1,
			0,--未开票数量
			0 --未开票金额
		
FROM #TOTAL00
LEFT JOIN   #GetManBTypeId	on Btypeid=TypeID	
UNION ALL
SELECT A.BTYPEID,
			A.BILLNUMBERID,
			NULL,
			0,
			0,
			'',
			0,
			0,
			a.totalqty as baseqty,
			0,
			'',
			'',
			0, 
			A.BILLTYPE,
			A.BILLDATE,
			A.BILLCODE,
			CASE WHEN @CID='0' THEN ISNULL(BILLTOTAL,0) ELSE ISNULL(NBILLTOTAL,0) END,
			CASE WHEN @CID='0' THEN ISNULL(PREFERENCEMONEY,0) ELSE ISNULL(NPREFERENCEMONEY,0) END,--优惠金额
			CASE WHEN @CID='0' THEN ISNULL(INTOTAL	,0) 
						ELSE ISNULL(NINTOTAL	,0) END,
			CASE WHEN @CID='0' THEN ISNULL(ARTOTAL,0) ELSE ISNULL(NARTOTAL,0) END,
			CASE WHEN @CID='0' THEN ISNULL(PAYTOTAL ,0)
						ELSE ISNULL(NPAYTOTAL ,0) END,
			CASE WHEN @CID='0' THEN ISNULL(APTOTAL		 ,0) ELSE ISNULL(NAPTOTAL,0) END,
			CASE WHEN @CID='0' THEN ISNULL(YSTOTAL		 ,0) ELSE ISNULL(NYSTOTAL,0) END,
			CASE WHEN @CID='0' THEN ISNULL(YFTOTAL		,0) ELSE ISNULL(NYFTOTAL		,0) END,
			CASE WHEN @CID='0' THEN ISNULL(QMTOTAL	,0) ELSE ISNULL(NQMTOTAL	,0) END,
			A.RECONCILIATION,
			0,
			0,
			A.Comment,
			CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT('000000000000000000'+A.BILLNUMBERID,18) AS BillSort,
			A.BillBtypeID,
			'',
			a.explain,
			CASE WHEN @CID='0' THEN ISNULL(zgtotal,0) ELSE ISNULL(Nzgtotal,0) END,
			A.EtypeID,
			CASE WHEN A.BillType in(404,405) THEN 1 ELSE 0 END,
			convert(nvarchar(10),a.accountdate,120),
			0,
			isnull(inv.uninvoiceqty,0),
			isnull(inv.uninvoicemoney,0)
FROM #BILLTOTAL A 
left join  (select  billnumberid, 
					billtype,
					SUM(uninvoiceqty) as uninvoiceqty,
					sum(uninvoicemoney)uninvoicemoney 
			FROM #invoiceQty 
			GROUP by billnumberid,billtype  
			) inv on a.billtype=inv.billtype and a.BILLNUMBERID=inv.billnumberid
		
 ----计算合计----
INSERT INTO #RESULT
SELECT BTYPEID,
			0,
			'',
			0,
			0,
			'', 
			0,
			0,
			0,
			0,
			'',
			'',
			0,
			-10,--强写-10
			NULL,
			'',
			0,
			SUM(ISNULL(PREFERENCEMONEY,0)),--优惠金额
			SUM(ISNULL(INTOTAL,0)),
			SUM(ISNULL(ARTOTAL,0)),
			SUM(ISNULL(PAYTOTAL ,0)),
			SUM(ISNULL(APTOTAL ,0)) ,
			SUM(ISNULL(YSTOTAL,0)),
			SUM(ISNULL(YFTOTAL,0)),
			SUM(ISNULL(ARTOTAL,0))-SUM(ISNULL(APTOTAL,0))-SUM(ISNULL(YSTOTAL,0))+SUM(ISNULL(YFTOTAL,0))-SUM(ISNULL(zgTOTAL,0)) ,
			'',
			1,
			0,
			'',
			'',
			'',
			'',
			'',
			SUM(ISNULL(zgtotal,0)),
			'',
			0 ,
			'',
			0,
			SUM(ISNULL(uninvoiceqty,0)),--未开票数量
			SUM(ISNULL(uninvoicemoney,0)) --未开票金额
		
FROM #RESULT
GROUP BY BTYPEID 

--处理只有期初和期末并且全部为零的单据不显示问题
DELETE FROM #RESULT WHERE (ISNULL(CONVERT( NUMERIC(24, 10) , BILLTOTAL),0)=0 
							AND ISNULL(ARTOTAL,0)=0 
							AND ISNULL(APTOTAL,0)=0 
							AND ISNULL(YSTOTAL,0)=0 
							AND ISNULL(YFTOTAL,0)=0
							AND ISNULL(zgTOTAL,0)=0 
							AND ISNULL(QMTOTAL,0)=0)
							AND BTYPEID IN ( SELECT BTYPEID FROM #RESULT GROUP BY BTYPEID HAVING COUNT(BTYPEID)<=2 ) 

	---加入商品明细信息
	INSERT INTO #RESULT
	SELECT A.BTYPEID,
				A.BILLNUMBERID,
				B.PTYPEID,
				--B.MDiscountPrice,
				CASE WHEN @CID='0' THEN B.MTaxPrice ELSE B.CurMTaxPrice END,	
				B.MQTY,
				PU.FULLNAME,
				CASE WHEN @CID='0' THEN b.total ELSE b.ntotal END,
				CASE WHEN @CID='0' THEN b.saletotal ELSE b.nsaletotal END,
				b.qty,
				b.NTaxPrice,
				u1.fullname as basefullname,
				'1'+PU.fullname+'='+convert(varchar(200),CAST(b.MUnitRate  AS real))+u1.fullname,
				b.discount,	
				A.BILLTYPE,		
				a.billdate,		
				a.billcode,		
				CASE WHEN @CID='0' THEN TaxTotal ELSE NTaxTotal END,	
				0,--优惠金额
				0,--实收金额
				CASE WHEN @CID='0' THEN ISNULL(B.ARTOTAL,0) ELSE  ISNULL(B.NARTOTAL,0) END,--应收金额	
				0,--实付金额
				CASE WHEN @CID='0' THEN ISNULL(B.APTOTAL,0) ELSE  ISNULL(B.NAPTOTAL,0) END,--应付金额	
				0,--预收金额		
				0,--预付金额		
				CASE WHEN @CID='0' THEN  ISNULL(B.ARTOTAL,0)-ISNULL(B.APTOTAL,0)-0-ISNULL(B.ZGTOTAL,0)
				      ELSE ISNULL(B.NARTOTAL,0)-ISNULL(B.NAPTOTAL,0)-0-ISNULL(B.NZGTOTAL,0)
				      END ,--往来余额	
				CASE WHEN B.Reconciliation='T' THEN '√' ELSE '' END Reconciliation,
				0,
				1,
				'',
				CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT('000000000000000000'+A.BILLNUMBERID,18) AS BillSort,
				A.BillBtypeID,
				B.comment AS detailcomment,
				'',
				--CASE WHEN @CID='0' THEN ISNULL(B.Total,0) ELSE  ISNULL(B.NZGTOTAL,0) END  ,--暂估金额
				--2019-08-23 陈强  bug 1301 
				CASE
				WHEN @cid = '0' THEN
					CASE						
						WHEN A.BillType IN (400,401,404) THEN ISNULL(B.Total,0)						
						ELSE ISNULL(B.NZGTOTAL,0) 
					END					
				ELSE
					CASE						
						WHEN A.BillType IN (400,401,404) THEN ISNULL(B.NTotal,0)						
						ELSE ISNULL(B.NZGTOTAL,0) 
					END													 
			END ,
				a.etypeid,
				0 ,
				'',
				B.ID,
				inv.uninvoiceqty  ,
				inv.uninvoicemoney
				
	FROM #RESULT A INNER JOIN (
				SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,TaxTotal AS ARTOTAL,NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM retailbill
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation ,-1*TaxTotal AS ARTOTAL,-1*NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM RetailBackBill
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,TaxTotal AS ARTOTAL,NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL ,0 AS ZGTOTAL,0 AS NZGTOTAL FROM salebill
					UNION ALL
					SELECT ID, BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation ,-1*TaxTotal AS ARTOTAL,-1*NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM salebackbill
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,TaxTotal AS ARTOTAL,NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM salegoodsexchangebill where InOrOut='O'
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,-MQty,MUnitID,-NTaxTotal,-TaxTotal,comment,-total,-saletotal,-ntotal,-nsaletotal,UnitID,-qty,NTaxPrice,MUnitRate,discount,Reconciliation,-1*TaxTotal AS ARTOTAL,-1*NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL  FROM salegoodsexchangebill where InOrOut='I'
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice, MQty,MUnitID,0,0,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,UnitID,qty,null as NTaxPrice,MUnitRate,0 AS discount,Reconciliation,0 AS ARTOTAL,0 AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM givebill
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,MQty,MUnitID,0,0,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,UnitID,qty,null as NTaxPrice,MUnitRate,0 AS discount,Reconciliation,0 AS ARTOTAL,0 AS NARTOTAL ,0 AS APTOTAL,0 AS NAPTOTAL ,0 AS ZGTOTAL,0 AS NZGTOTAL FROM giveMEbill
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,TaxTotal AS ARTOTAL,NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL ,0 AS ZGTOTAL,0 AS NZGTOTAL FROM commissionbill WHERE [TYPE]=141
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount, Reconciliation ,TaxTotal AS ARTOTAL,NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM PT_Combin_SaleBill
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,-1*TaxTotal AS ARTOTAL,-1*NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL  FROM PT_Combin_SaleBackBill	
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,0 AS ARTOTAL, 0 AS NARTOTAL,TaxTotal AS APTOTAL,NTaxTotal AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM buybill
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,0 AS ARTOTAL, 0 AS NARTOTAL,-1*TaxTotal AS APTOTAL,-1*NTaxTotal AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM buybackbill
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,0 AS ARTOTAL, 0 AS NARTOTAL,TaxTotal AS APTOTAL,NTaxTotal AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM buygoodsexchangebill where InOrOut='I'
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,-MQty,MUnitID,-NTaxTotal,-TaxTotal,comment,-total,-saletotal,-ntotal,-nsaletotal,UnitID,-qty,NTaxPrice,MUnitRate,discount,Reconciliation,0 AS ARTOTAL, 0 AS NARTOTAL,-1*TaxTotal AS APTOTAL,-1*NTaxTotal AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM buygoodsexchangebill where InOrOut='O'
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0,0 AS NTAXTOTAL,0 AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,0,qty,NULL as NTaxPrice,null as MUnitRate,0 AS discount,'' Reconciliation,0 AS ARTOTAL,0 AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM priceprotectbill
					UNION ALL 
					SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,0,0,TOTAL AS NTAXTOTAL,TOTAL AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,0,null as qty,NULL as NTaxPrice,null as MUnitRate,0 as discount,'' Reconciliation ,0 AS ARTOTAL,0 AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL FROM advantage 
					UNION ALL 
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,0 AS ARTOTAL,0 AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,TaxTotal AS ZGTOTAL,NTaxTotal AS NZGTOTAL  FROM AppraisalBill
					UNION ALL 
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,0 AS ARTOTAL,0 AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL ,-1*TaxTotal AS ZGTOTAL,-1*NTaxTotal AS NZGTOTAL FROM AppraisalBackBill
					UNION ALL 
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,'' Reconciliation,TaxTotal AS ARTOTAL,NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL ,0 AS ZGTOTAL,0 AS NZGTOTAL    FROM SendBill
					UNION ALL 
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,'' Reconciliation,-1*TaxTotal AS ARTOTAL,-1*NTAXTOTAL AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL    FROM SendBackBill	 
					UNION ALL
					SELECT ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,0 AS ARTOTAL,0 AS NARTOTAL,TaxTotal AS APTOTAL, NTaxTotal AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL  FROM commissionbill WHERE [TYPE]=145
					UNION ALL
					SELECT ad.ID,ad.BillNumberId,ad.PtypeId,0 AS Pirce,0 AS Price,0 AS Qty,0 AS MUnitID,0 AS NTaxTotal,
					0 AS TaxTotal,ad.comment,0 AS total,0 AS saletotal,0 AS ntotal,0 AS nsaletotal,0 AS UnitID,
					0 AS qty,0 AS NTaxPrice,0 AS MUnitRate,0 AS discount,'' AS Reconciliation,0 AS ARTOTAL,
					0 AS NARTOTAL,0 AS APTOTAL, 0 AS NAPTOTAL,ad.changetotal AS ZGTOTAL,ad.changetotal AS NZGTOTAL  FROM adpricebill Ad
					INNER JOIN billindex bil ON bil.BillNumberId = Ad.BillNumberId
					 WHERE bil.BillType=57 AND bil.AdPriceType=1
	
	
	) B ON A.BILLNUMBERID=B.BILLNUMBERID
	LEFT JOIN #invoiceQty inv on a.billtype=inv.billtype and a.BILLNUMBERID=inv.billnumberid AND INV.PTYPEID=B.PTYPEID AND B.ID=INV.ID
	LEFT JOIN PType_Units PU ON PU.UnitsId=B.MUNITID 
	LEFT JOIN PType_Units u1 ON u1.UnitsId=B.UnitID 
	 WHERE B.PTYPEID<>''  AND A.Billtype not in(404,405,167,168,170,450,423,424,425,426)



	---加入商品明细信息
	INSERT INTO #RESULT
	SELECT A.BTYPEID,
				A.BILLNUMBERID,
				B.PTYPEID,
				--B.MDiscountPrice,
				CASE WHEN @CID='0' THEN B.MTaxPrice ELSE B.CurMTaxPrice END,	
				B.MQTY,
				PU.FULLNAME,
				CASE WHEN @CID='0' THEN b.total ELSE b.ntotal END,
				CASE WHEN @CID='0' THEN b.saletotal ELSE b.nsaletotal END,
				b.qty,
				b.NTaxPrice,
				pu.fullname as basefullname,
				'1'+PU.fullname+'=1'+PU.fullname,
				b.discount,	
				A.BILLTYPE,		
				a.billdate,		
				a.billcode,		
				CASE WHEN @CID='0' THEN TaxTotal ELSE NTaxTotal END,	
				0,--优惠金额
				0,		
				0,		
				0	,
				0,		
				0,		
				0,		
				0,	
				'' RECONCILIATION,
				0,
				1,
				'',
				CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT('000000000000000000'+A.BILLNUMBERID,18) AS BillSort,
				A.BillBtypeID,
				B.comment AS detailcomment,
				'',
				0,
				a.etypeid,
				0,
				'',
				B.ID,
				0,--未开票数量
				0 --未开票金额
	FROM #RESULT A INNER JOIN (
					SELECT ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty AS mqty,0 AS NTAXTOTAL,0 AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,qty,NULL as NTaxPrice,null as MUnitRate,0 AS discount FROM wx_bill_getback
					UNION ALL
					SELECT  ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0 AS TAXTOTAL,0 AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,qty,NULL as NTaxPrice,null as MUnitRate,0 AS discount FROM wx_bill_replace 
					UNION ALL
					SELECT  ID,BillNumberId,PtypeId,NULL AS MTaxPrice,NULL AS CurMTaxPrice,Qty,0 AS TAXTOTAL,0 AS TAXTOTAL,comment,0 as total,0 as saletotal,0 as ntotal,0 as nsaletotal,qty,NULL as NTaxPrice,null as MUnitRate,0 AS discount FROM wx_bill_sendback

	) B ON A.BILLNUMBERID=B.BILLNUMBERID
	LEFT JOIN dbo.ptype p ON B.ptypeid=	p.typeId
	LEFT JOIN PType_Units PU ON PU.UnitsId=p.baseUnitId 

	WHERE B.PTYPEID<>''  AND A.Billtype  in(167,168,170)
		
		
--发票单据处理（发票不写billindex）

	---加入商品明细信息
	INSERT INTO #RESULT
	SELECT  A.BTYPEID,
			A.BILLNUMBERID,
			B.PTYPEID,
			--B.MDiscountPrice,
			CASE WHEN @CID='0' THEN B.MTaxPrice ELSE B.CurMTaxPrice END,	
			B.MQTY,
			PU.FULLNAME,
			CASE WHEN @CID='0' THEN b.total ELSE b.ntotal END,
			CASE WHEN @CID='0' THEN b.saletotal ELSE b.nsaletotal END,
			b.qty,
			b.NTaxPrice,
			u1.fullname as basefullname,
			'1'+PU.fullname+'='+convert(varchar(200),CAST(b.MUnitRate  AS real))+u1.fullname,
			b.discount,	
			A.BILLTYPE,		
			a.billdate,		
			a.billcode,		
			CASE WHEN @CID='0' THEN TaxTotal ELSE NTaxTotal END,	
			0,--优惠金额
			0,		
			CASE WHEN @Cid='0' THEN B.ARTOTAL ELSE B.NARTOTAL END ,		
			0	,
			CASE WHEN @Cid='0' THEN B.APTOTAL ELSE B.NAPTOTAL END ,		
			0,		
			0,	
				
			CASE WHEN @Cid='0' THEN ISNULL(B.ARTOTAL,0)-ISNULL(B.APTOTAL,0)-0-ISNULL(B.ZGTOTAL,0) ELSE ISNULL(B.NARTOTAL,0)-ISNULL(B.NAPTOTAL,0)-0-ISNULL(B.NZGTOTAL,0) END,	
			CASE WHEN B.Reconciliation='T' THEN '√' ELSE '' END Reconciliation,
			0,
			1,
			'',
			CONVERT(VARCHAR(10),A.BILLDATE,120) + RIGHT('000000000000000000'+A.BILLNUMBERID,18) AS BillSort,
			A.BillBtypeID,
			B.comment AS detailcomment,
			'',
			--CASE WHEN @Cid='0' THEN B.ZGTOTAL ELSE B.NZGTOTAL END
			--2019-08-23 陈强  bug 1301 
			CASE
				WHEN @cid = '0' THEN
					CASE						
						WHEN A.BillType IN (400,401,404) THEN -1*B.TOTAL						
						ELSE B.ZGTOTAL 
					END					
				ELSE
					CASE						
						WHEN A.BillType IN (400,401,404) THEN -1*B.NTOTAL 						
						ELSE B.NZGTOTAL 
					END													 
			END AS zgtotal,
			a.etypeid,
			1,
			'',
			B.ID,
			0,--未开票数量
			0 --未开票金额
	FROM #RESULT A 
	INNER JOIN ReceiptBillIndex  RE ON A.BILLNUMBERID=RE.BILLNUMBERID AND A.billtype=re.billtype
	INNER JOIN (  
		SELECT  ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,0 AS ARTOTAL,0 AS NARTOTAL,TAXTOTAL AS APTOTAL,NTAXTOTAL AS NAPTOTAL, -1*TaxTotal AS ZGTOTAL ,-1*NTaxTotal AS NZGTOTAL FROM ReceiptBill WHERE BILLTYPE = 404
		UNION ALL 
		SELECT  ID,BillNumberId,PtypeId,MTaxPrice,CurMTaxPrice,MQty,MUnitID,NTaxTotal,TaxTotal,comment,total,saletotal,ntotal,nsaletotal,UnitID,qty,NTaxPrice,MUnitRate,discount,Reconciliation,TaxTotal AS ARTOTAL,NTaxTotal AS NARTOTAL,0 AS APTOTAL,0 AS NAPTOTAL,0 AS ZGTOTAL,0 AS NZGTOTAL  FROM ReceiptBill WHERE BILLTYPE=405

	) B ON re.BILLNUMBERID=B.BILLNUMBERID  --由于前面插入了发票的数据到result导致会存在billnumberid相同billtype不同的数据
	LEFT JOIN PType_Units PU ON PU.UnitsId=B.MUNITID 
	LEFT JOIN PType_Units u1 ON u1.UnitsId=B.UnitID 
	WHERE	ISNULL(B.PTYPEID,'')<>''  
			AND A.Billtype  in(404,401,405) 
	

UPDATE #RESULT 
SET    ARTOTAL=CASE WHEN billtype IN(305,11,12,405,160) THEN  -1*PREFERENCEMONEY
					WHEN billtype IN(215,45,46) THEN  PREFERENCEMONEY
				    ELSE 0 
				    END,
	   APTOTAL=CASE WHEN billtype IN(34,404,161) THEN  -1*PREFERENCEMONEY 
					WHEN billtype IN(6) THEN PREFERENCEMONEY
					ELSE 0
					END ,
	  BILLTOTAL=0			
	
	   
WHERE  SORTID=0 AND PSORTID=0 AND billtype IN (
305,11,12,215,45,160,46,34,161,6,404,405,141,145) AND isnull(PTYPEID,0)=0



DELETE #RESULT WHERE SORTID=0 AND PSORTID=0 AND PREFERENCEMONEY=0 AND ARTOTAL=0 AND APTOTAL=0 AND YSTOTAL=0 AND APTOTAL=0 AND INTOTAL=0 AND PAYTOTAL=0 

--select * from #RESULT

--最终查询--临时处理账户和商品基本信息列，右键不支持，所以单独出数据----
SET @CREATESQL='  
SELECT	A.BTYPEID		,
		A.BILLNUMBERID	,
		A.PTYPEID		,
		A.PRICE			,
		A.QTY			,
		A.UFULLNAME		,
		A.TOTAL			,
		A.SALETOTAL		,
		A.BASEQTY		,
		A.NTAXPRICE		,
		A.BASEFULLNAME	,
		A.UNITRALATION	,
		A.DISCOUNT		,
		A.BILLTYPE		,
		A.BillType BillTypes,
		A.BILLDATE		,
		A.BILLCODE		,
		A.BILLTOTAL		 ,
		A.PREFERENCEMONEY  ,
		A.INTOTAL		 ,
		A.ARTOTAL		 ,
		A.PAYTOTAL	 ,
		A.APTOTAL		 ,
		A.YSTOTAL		 ,
		A.YFTOTAL		 ,
		A.QMTOTAL	 ,
		A.RECONCILIATION	,
		A.SORTID		,		
		A.PSORTID		,			
		A.Comment		,
		A.BillSort	, 
		A.BillBtypeID	,
		A.DetailComment , 
		A.explain		, 
		CASE 
			WHEN  A.BILLTYPE  in(401)  THEN -1*A.zgtotal 			
			WHEN  A.BILLTYPE  in(400,404)  THEN A.zgtotal 			
			ELSE 0 
		END as zgtotal,
		A.etypeid		, 
		A.fpsort		,
		A.AccountDate,
		A.ID,
		CASE WHEN A.BILLNUMBERID not in (-99999,0) and  isnull(a.PTYPEID,'''')='''' then 0 else  A.uninvoiceqty end  as  uninvoiceqty , 
		CASE WHEN A.BILLNUMBERID  not in (-99999,0) and  isnull(a.PTYPEID,'''')='''' then 0 else A.uninvoicemoney  end  as  uninvoicemoney
		, customassist=dbo.F_GetCustomAssist(a.Ptypeid,a.baseqty)
		,P.USERCODE AS PUSERCODE
		,P.FULLNAME AS PFULLNAME
		,p.name as pname
		,Ps.usercode pmulusercode
	   ,SysDiy1_head,SysDiy2_head,
	   SysDiy3_head,SysDiy4_head,
	   SysDiy5_head,SysDiy6_head,
	   SysDiy7_head,SysDiy8_head,
	   SysDiy9_head,SysDiy10_head,
	   SysDiy11_head,SysDiy12_head,
	   SysDiy13_head,SysDiy14_head,
	   SysDiy15_head,SysDiy16_head,
	   SysDiy17_head,SysDiy18_head,
	   SysDiy19_head,SysDiy20_head,SysDiy21_head,
	   SysDiy22_head,SysDiy23_head,SysDiy24_head,
	   SysDiy25_head,SysDiy26_head,SysDiy27_head,
	   SysDiy28_head,SysDiy29_head,SysDiy30_head,
	   SysDiy31_head,SysDiy32_head,SysDiy33_head,
	   SysDiy34_head,SysDiy35_head,SysDiy36_head,
	   SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
	   SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,
	   SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
	   SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,
	   SysDiy16,SysDiy17,SysDiy18,SysDiy19,SysDiy20,
	   SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,
	   SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,
	   SysDiy31,SysDiy32,SysDiy33,SysDiy34,SysDiy35,
	   SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40
FROM #RESULT  A 
 LEFT JOIN PTYPE P ON A.PTYPEID=P.TYPEID
LEFT JOIN PUserCode Ps ON Ps.PTYPEID=P.TYPEID AND Ps.btypeid=A.btypeid
LEFT JOIN Custom_BillIndex CB ON CB.BillId=A.BillNumberId and CB.BillType=A.BillType
LEFT JOIN Custom_BillDetails CD ON CD.BillId=A.BillNumberId and CD.BillType=A.BillType AND CD.Detailid=A.ID
WHERE (('''+@IsDetail+'''=''False'' AND A.BILLTYPE IN (-1,-10)) OR '''+@IsDetail+'''=''True'')  '+CHAR(13)

--不显示对账信息
IF(@IsShowReconciliation=0)
	SET @CREATESQL+='	AND A.Reconciliation='''''+CHAR(13)
	
SET @CREATESQL+='
ORDER BY A.btypeid ,A.SORTID,a.billsort,a.billcode DESC ,a.billnumberid,A.BILLTYPE,a.PSORTID desc ,a.fpsort


--删除临时表
DROP TABLE #BILLINDEX	,#TOTAL00,#BILLTOTAL , #invoiceQty ,#RESULT'

--PRINT(@CREATESQL)
EXEC(@CREATESQL)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







IF EXISTS(SELECT * FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_QueryArApAuditAccountLine]') AND OBJECTPROPERTY(ID,N'ISPROCEDURE')=1)
DROP PROCEDURE Web_QueryArApAuditAccountLine
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：LUDALIN
	日期：2013-11-26
	描述：往来对账线性表
*/
CREATE PROCEDURE Web_QueryArApAuditAccountLine
(
    @OperatorId			VARCHAR(MAX),	--操作员ID
	@StartDate			VARCHAR(30),	--开始日期
	@EndDate			VARCHAR(30),	--截止日期
	@STypeId			VARCHAR(MAX),	--分支机构
	@BTypeId			VARCHAR(MAX),	--结算单位
	@Cid				VARCHAR(10),	--币种
	@IfShowZero	VARCHAR(1),	--是否显示全为零项
	@queryinvoice			int
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
------------------------------------------------------------------------检查权限范围--------------------------------------------------------------------------------

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------检查权限范围结束--------------------------------------------------------------------------	
--处理币种
SET @Cid=ISNULL(@Cid,0)

--往来单位
CREATE TABLE #GetManBTypeId(TypeID VARCHAR(50))
INSERT INTO #GetManBTypeId(TypeId) SELECT a.TypeId FROM F_GetAllManagerBASeTypeId(@BTypeId,2,@OperatorID) a 

--分支机构
CREATE TABLE #GetManSTypeId(TypeID VARCHAR(50))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBASeTypeId(@STypeId,11,@OperatorID)	
---判断操作员如果没有当前选择的分支机构权限，赋值一个不存在的分支机构
DECLARE @MANSTYPEID VARCHAR(50)
SELECT @MANSTYPEID=TypeID FROM #GetManSTypeId WHERE TypeID=@STypeId
IF ISNULL(@MANSTYPEID,'')=''
	SET @STypeId='XXXXX'

DECLARE @CIDWhere VARCHAR(100)
IF @CID<>0
  BEGIN
       SET @CIDWhere=' AND CID='+CONVERT(VARCHAR, @CID)
  END
ELSE
  BEGIN
       SET @CIDWhere=' '
  END
  
 DECLARE @isInvoice int,
		@sqlinvoicewhere VARCHAR(200)=''
SELECT @isInvoice=Subvalue FROM sysdata WHERE SubName='Isinvoice'
IF @isInvoice<>1 OR @queryinvoice<>1
BEGIN
	SET @sqlinvoicewhere=' AND UserCode NOT IN(''2122'') '
END


--应收和应付
CREATE TABLE #RESULT_ARAP(
                          BTypeId VARCHAR(50),
						  qcartotal  NUMERIC(24, 10) ,
						  nqcartotal  NUMERIC(24, 10) ,
						  arretotal  NUMERIC(24, 10) ,
						  narretotal  NUMERIC(24, 10) ,
						  ARTotal  NUMERIC(24, 10) ,
						  NARTotal  NUMERIC(24, 10) ,					  
						  qcaptotal  NUMERIC(24, 10) ,
						  nqcaptotal  NUMERIC(24, 10) ,
						  apretotal  NUMERIC(24, 10) ,
						  napretotal  NUMERIC(24, 10) ,
					      APTotal  NUMERIC(24, 10) ,
					      NAPTotal  NUMERIC(24, 10) ,
					        QCGRIRTotal    NUMERIC(24, 10) ,
					      qcNGRIRTotal   NUMERIC(24, 10) , --应付暂估期初
						  addGRIRTotal  NUMERIC(24, 10) ,
						  addNGRIRTotal  NUMERIC(24, 10) ,
						  GRIRTotal     NUMERIC(24, 10) ,
						  NGRIRTotal	 NUMERIC(24, 10) 
					      )
						  
DECLARE @SQL1 VARCHAR(MAX)								 
					
-------------------------------------------应收应付金额---------------------------------------------------
SET @SQL1 = '
				INSERT INTO #RESULT_ARAP
					SELECT  R.BTypeId,
							ISNULL(SUM(R.qcartotal),0) AS qcartotal,
							ISNULL(SUM(R.nqcartotal),0) AS nqcartotal,
							ISNULL(SUM(R.arretotal),0) AS arretotal,
							ISNULL(SUM(R.narretotal),0) AS narretotal,
							ISNULL(SUM(R.ARTotal),0) AS ARTotal,
							ISNULL(SUM(R.NARTotal),0) AS NARTotal,
							ISNULL(SUM(R.qcaptotal),0) AS qcaptotal,
							ISNULL(SUM(R.nqcaptotal),0) AS nqcaptotal,
							ISNULL(SUM(R.apretotal),0) AS apretotal,
							ISNULL(SUM(R.napretotal),0) AS napretotal,
							ISNULL(SUM(R.APTotal),0) AS APTotal,
							ISNULL(SUM(R.NAPTotal),0) AS NAPTotal,
							ISNULL(SUM(R.QCGRIRTotal),0) AS QCGRIRTotal,
							ISNULL(SUM(R.qcNGRIRTotal),0) AS qcNGRIRTotal,
							ISNULL(SUM(R.addGRIRTotal),0) AS addGRIRTotal,
							ISNULL(SUM(R.addNGRIRTotal),0) AS addNGRIRTotal,
							ISNULL(SUM(R.GRIRTotal),0) AS GRIRTotal,
							ISNULL(SUM(R.NGRIRTotal),0) AS NGRIRTotal
					FROM(
							SELECT	T.TypeID BTypeID,
							(ISNULL(L.ARTotal,0) - ISNULL(L.YSTotal,0)) - (ISNULL(B.ARTotal,0) - ISNULL(B.YSTotal,0)) - (ISNULL(R.ARTotal,0) - ISNULL(R.YSTotal,0)) AS qcartotal,	--期初
				            (ISNULL(L.NARTotal,0) - ISNULL(L.NYSTotal,0)) - (ISNULL(B.NARTotal,0) - ISNULL(B.NYSTotal,0)) - (ISNULL(R.NARTotal,0) - ISNULL(R.NYSTotal,0)) AS nqcartotal,	--期初					
							ISNULL(R.ARTotal,0) - ISNULL(R.YSTotal,0) AS arretotal,										--发生额
							ISNULL(R.NARTotal,0) - ISNULL(R.NYSTotal,0) AS narretotal,										--发生额
							((ISNULL(L.ARTotal,0) - ISNULL(L.YSTotal,0)) - (ISNULL(B.ARTotal,0) - ISNULL(B.YSTotal,0))) AS ARTotal,		--期末
							((ISNULL(L.NARTotal,0) - ISNULL(L.NYSTotal,0)) - (ISNULL(B.NARTotal,0) - ISNULL(B.NYSTotal,0))) AS NARTotal,		--期末
							(ISNULL(L.APTotal,0) - ISNULL(L.YFTotal,0)) - (ISNULL(B.APTotal,0) - ISNULL(B.YFTotal,0)) - (ISNULL(R.APTotal,0) - ISNULL(R.YFTotal,0)) AS qcaptotal,	--期初
				            (ISNULL(L.NAPTotal,0) - ISNULL(L.NYFTotal,0)) - (ISNULL(B.NAPTotal,0) - ISNULL(B.NYFTotal,0)) - (ISNULL(R.NAPTotal,0) - ISNULL(R.NYFTotal,0)) AS nqcaptotal,	--期初					
							ISNULL(R.APTotal,0) - ISNULL(R.YFTotal,0) AS apretotal,										--发生额
							ISNULL(R.NAPTotal,0) - ISNULL(R.NYFTotal,0) AS napretotal,										--发生额		
							((ISNULL(L.APTotal,0) - ISNULL(L.YFTotal,0)) - (ISNULL(B.APTotal,0) - ISNULL(B.YFTotal,0))) AS APTotal,
							((ISNULL(L.NAPTotal,0) - ISNULL(L.NYFTotal,0)) - (ISNULL(B.NAPTotal,0) - ISNULL(B.NYFTotal,0))) AS NAPTotal,
							ISNULL(L.GRIRTotal,0)-ISNULL(B.GRIRTotal,0)-ISNULL(R.GRIRTotal,0) as QCGRIRTotal, --应付暂估期初
							ISNULL(L.NGRIRTotal,0)-ISNULL(B.NGRIRTotal,0)-ISNULL(R.NGRIRTotal,0) as qcNGRIRTotal,
							ISNULL(r.GRIRTotal,0) as addGRIRTotal, --应付暂估本期增加
							ISNULL(r.nGRIRTotal,0) as addNGRIRTotal,
							ISNULL(L.GRIRTotal,0)-ISNULL(B.GRIRTotal,0) as GRIRTotal, --应付暂估期末
							ISNULL(L.NGRIRTotal,0)-ISNULL(B.NGRIRTotal,0) as NGRIRTotal	'
						
DECLARE @Where VARCHAR(100)
IF @CID<>0
  BEGIN
       SET @Where='  WHERE B.CID= '+CONVERT(VARCHAR,@CID)
  END
ELSE
  BEGIN
       SET @Where=' '
  END
SET @SQL1 = @SQL1 + '									
							FROM #GetManBTypeId T
							LEFT JOIN (
									--现在时间应收余额	
									SELECT  B.BTypeID,
											SUM(B.ARTotal) AS ARTotal,
											SUM(B.NARTotal) AS NARTotal,
											SUM(B.YSTotal) AS YSTotal,
											SUM(B.NYSTotal) AS NYSTotal,
											SUM(B.APTotal) AS APTotal,
											SUM(B.NAPTotal) AS NAPTotal,
											SUM(B.YFTotal) AS YFTotal,
											SUM(B.NYFTotal) AS NYFTotal,
											CASE WHEN '+CAST(@queryinvoice AS VARCHAR)+'=1 THEN SUM(B.GRIRTotal) ELSE 0 END  AS GRIRTotal,
											CASE WHEN '+CAST(@queryinvoice AS VARCHAR)+'=1 THEN SUM(B.NGRIRTotal) ELSE 0 END  AS NGRIRTotal
									FROM BType_ArApTotal B
									'
IF @STypeId <> '' OR @MStypeid <> '00000'
	SET @SQL1 = @SQL1+' INNER JOIN #GetManSTypeId S ON S.typeid=B.Stypeid '
IF @BTypeId <> '' OR @MBtypeid <> '00000'
	SET @SQL1 = @SQL1+' INNER JOIN #GetManBTypeId BT ON B.btypeid = BT.TypeID '
SET @SQL1=@SQL1+@Where

SET @SQL1 = @SQL1 + '	GROUP BY B.BTypeID
							)L ON L.BTypeID=T.TypeID
								LEFT JOIN	  
								(
									
									--结束时间到今天应收发生额
									SELECT L.BtypeId,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''987''
														THEN Total
														END),0) AS ARTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''987''
														THEN NTotal
														END),0) AS NARTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''2131''
														THEN Total
														END),0) AS YSTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''2131''
														THEN NTotal
														END),0) AS NYSTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''2121''
														THEN Total
														END),0) AS APTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''2121''
														THEN NTotal
														END),0) AS NAPTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''1151''
														THEN Total
														END),0) AS YFTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''1151''
														THEN NTotal
														END),0) AS NYFTotal,
											ISNULL(SUM(CASE WHEN AC.UserCode = ''2122'' --应付暂估
														THEN Total
														END),0) AS GRIRTotal,
											ISNULL(SUM(CASE WHEN AC.UserCode = ''2122''
														THEN NTotal
														END),0) AS NGRIRTotal
										   FROM ListTable L
										   INNER JOIN AC_Items AC ON L.AtypeId=AC.nid
									'									
IF @STypeId <> '' OR @MStypeid <> '00000'
	SET @SQL1 = @SQL1+' INNER JOIN #GetManSTypeId S ON S.typeid=L.Stypeid '
IF @BTypeId <> '' OR @MBtypeid <> '00000'
	SET @SQL1 = @SQL1+' INNER JOIN #GetManBTypeId BT ON L.btypeid = BT.TypeID '
SET @SQL1 = @SQL1 + '
										   WHERE L.BillDate >'+CHAR(39)+@EndDate+CHAR(39)+'
												-- and L.sTypeID = '+CHAR(39)+@STypeId+CHAR(39)+'
												 AND AC.UserCode IN (''987'',''2131'',''2121'',''1151'',''2122'')'+@CIDWhere+@sqlinvoicewhere+'
										   GROUP BY L.BtypeId
								)B ON B.BTypeID=T.TypeID
								LEFT JOIN
								(
									--开始时间到结束时间应收发生额
									SELECT L.BtypeId,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''987''
														THEN Total
														END),0) AS ARTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''987''
														THEN NTotal
														END),0) AS NARTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''2131''
														THEN Total
														END),0) AS YSTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''2131''
														THEN NTotal
														END),0) AS NYSTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''2121''
														THEN Total
														END),0) AS APTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''2121''
														THEN NTotal
														END),0) AS NAPTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''1151''
														THEN Total
														END),0) AS YFTotal,
										   ISNULL(SUM(CASE WHEN AC.UserCode = ''1151''
														THEN NTotal
														END),0) AS NYFTotal,
											ISNULL(SUM(CASE WHEN AC.UserCode = ''2122'' --应付暂估
														THEN Total
														END),0) AS GRIRTotal,
											ISNULL(SUM(CASE WHEN AC.UserCode = ''2122''
														THEN NTotal
														END),0) AS NGRIRTotal
										   FROM ListTable L
										   INNER JOIN AC_Items AC ON L.AtypeId=AC.nid
									'								
IF @STypeId <> '' OR @MStypeid <> '00000'
	SET @SQL1 = @SQL1+' INNER JOIN #GetManSTypeId S ON S.typeid=L.Stypeid '
IF @BTypeId <> '' OR @MBtypeid <> '00000'
	SET @SQL1 = @SQL1+' INNER JOIN #GetManBTypeId BT ON L.btypeid = BT.TypeID '
SET @SQL1 = @SQL1 + '
										   WHERE L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+'
												 AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'
												  --and L.sTypeID = '+CHAR(39)+@STypeId+CHAR(39)+'
												 AND AC.UserCode IN (''987'',''2131'',''2121'',''1151'',''2122'')'+@CIDWhere+@sqlinvoicewhere+'
										   GROUP BY L.BtypeId
							)R ON R.BTypeID=T.TypeID			
								
						)R
						GROUP BY R.BtypeId
						'


EXEC(@SQL1)


DECLARE @SQL2 VARCHAR(MAX)																			
SET @SQL2 = + '  
							  
						SELECT G.TypeId AS typeid,
							   ISNULL(CASE WHEN '+@cid+'=0 THEN A.qcartotal ELSE A.nqcartotal END,0)
							   -ISNULL(CASE WHEN '+@cid+'=0 THEN A.qcaptotal ELSE A.nqcaptotal END,0) 
							   -ISNULL(CASE WHEN '+@cid+'=0 THEN A.qcGRIRTotal ELSE A.qcNGRIRTotal END,0) 
							   AS total00,
							  ISNULL(CASE WHEN '+@cid+'=0 THEN A.arretotal ELSE A.narretotal END,0)
							  - ISNULL(CASE WHEN '+@cid+'=0 THEN A.apretotal ELSE A.napretotal END,0)
							  - ISNULL(CASE WHEN '+@cid+'=0 THEN A.addGRIRTotal ELSE A.addNGRIRTotal END,0) 
							  AS total,
							   ISNULL(CASE WHEN '+@cid+'=0 THEN A.artotal ELSE A.nartotal END,0)
							   -ISNULL(CASE WHEN '+@cid+'=0 THEN A.aptotal ELSE A.naptotal END,0)
							   -ISNULL(CASE WHEN '+@cid+'=0 THEN A.GRIRTotal ELSE A.NGRIRTotal END,0)
							    AS qmtotal
						from #GetManBTypeId G
						inner join btype b on g.typeid = b.typeid
						left join #RESULT_ARAP A on A.BTypeId = G.TypeId	
						where
							   b.typeId <> ''00001'' 
							  and b.typeId <> ''00002''
					'
if @IfShowZero = '1'
		SET @SQL2 =  @SQL2 + 'and  (ISNULL(A.nqcartotal,0)-ISNULL(A.nqcaptotal,0)-ISNULL(A.qcGRIRTotal,0)<>0 OR  
								    ISNULL(A.narretotal,0)-ISNULL(A.napretotal,0)-ISNULL(A.addNGRIRTotal,0)<>0 OR  
								    ISNULL(A.nARTotal,0)-ISNULL(A.nAPTotal,0)-ISNULL(A.NGRIRTotal,0)<>0)'
SET @SQL2 =  @SQL2 +' ORDER BY B.usercode'
EXEC(@SQL2)

--SELECT * FROM #RESULT_ARAP
--PRINT @SQL2
DROP TABLE #GetManBTypeId,#RESULT_ARAP
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_QueryArApAuditAccountTree]') AND OBJECTPROPERTY(ID,N'ISPROCEDURE')=1)
DROP PROCEDURE Web_QueryArApAuditAccountTree
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：LUDALIN
	日期：2013-11-26
	描述：往来对账树形表
*/
CREATE PROCEDURE Web_QueryArApAuditAccountTree
(
    @OperatorId			VARCHAR(MAX),	--操作员ID
	@StartDate			VARCHAR(30),	--开始日期
	@EndDate			VARCHAR(30),	--截止日期
	@STypeId			VARCHAR(MAX),	--分支机构
	@BTypeId			VARCHAR(MAX),	--结算单位
	@queryinvoice			int,
	@Cid				VARCHAR(10)	--币种
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------检查权限范围结束--------------------------------------------------------------------------	
DECLARE 
	@SonNum	INT=0,
	@SQL	VARCHAR(MAX)='',
	@isInvoice INT=0,
	@SqlInvoiceWhere VARCHAR(200)=''

--处理币种
SET @Cid=ISNULL(@Cid,0)

--处理基本信息ID
IF @BTypeId = ''
	SET @BTypeId = '00000'

SELECT @isInvoice=Subvalue FROM sysdata WHERE SubName='Isinvoice'
IF @isInvoice<>1 OR @queryinvoice<>1
	SET @SqlInvoiceWhere=' AND UserCode NOT IN(''2122'') '
	
--往来单位
CREATE TABLE #BType(TypeID VARCHAR(50)) CREATE UNIQUE INDEX #BType_TypeId ON #BType(TypeID) 
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId

--最后返回结果
CREATE TABLE #BTypePar(TypeID VARCHAR(50),SonNum INT,UserCode VARCHAR(200)) CREATE UNIQUE INDEX #BTypePar_TypeId ON #BTypePar(TypeID) 
IF @SonNum = 0 
	BEGIN
		INSERT INTO #BTypePar(TypeID,SonNum,UserCode)
		SELECT 
			typeId,
			sonnum,
			UserCode
		FROM F_GetManBTypeAll(@OperatorId) 
		WHERE 
			TypeId = @BTypeId
	END
ELSE
	BEGIN
		INSERT INTO #BTypePar(TypeID,SonNum,UserCode)
		SELECT 
			typeId,
			sonnum,
			UserCode
		FROM F_GetManBTypeAll(@OperatorId) 
		WHERE 
			parid = @BTypeId
	END

--分支机构
CREATE TABLE #SType(TypeID VARCHAR(50)) CREATE UNIQUE INDEX #SType_TypeId ON #SType(TypeID) 
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)		
			  
--应收和应付
CREATE TABLE #RESULT_ARAP
(
	BTypeId      VARCHAR(50),
	qcartotal     NUMERIC(24, 10) ,
	nqcartotal    NUMERIC(24, 10) ,
	arretotal     NUMERIC(24, 10) ,
	narretotal    NUMERIC(24, 10) ,
	ARTotal       NUMERIC(24, 10) ,
	NARTotal      NUMERIC(24, 10) ,					 
	qcaptotal     NUMERIC(24, 10) ,
	nqcaptotal    NUMERIC(24, 10) ,
	apretotal     NUMERIC(24, 10) ,
	napretotal    NUMERIC(24, 10) ,
	APTotal       NUMERIC(24, 10) ,
	NAPTotal      NUMERIC(24, 10) ,
	QCGRIRTotal    NUMERIC(24, 10) ,
	qcNGRIRTotal   NUMERIC(24, 10) , --应付暂估期初
	addGRIRTotal  NUMERIC(24, 10) ,
	addNGRIRTotal  NUMERIC(24, 10) ,
	GRIRTotal     NUMERIC(24, 10) ,
	NGRIRTotal	 NUMERIC(24, 10) 
)
CREATE UNIQUE INDEX #RESULT_ARAP_BTypeId ON #RESULT_ARAP(BTypeId) 
-------------------------------------------应收应付金额---------------------------------------------------
SET @SQL='
INSERT INTO #RESULT_ARAP
SELECT	
	T.TypeID BTypeID,
	(ISNULL(L.ARTotal,0) - ISNULL(L.YSTotal,0)) - (ISNULL(B.ARTotal,0) - ISNULL(B.YSTotal,0)) - (ISNULL(R.ARTotal,0) - ISNULL(R.YSTotal,0)) AS qcartotal,
	(ISNULL(L.NARTotal,0) - ISNULL(L.NYSTotal,0)) - (ISNULL(B.NARTotal,0) - ISNULL(B.NYSTotal,0)) - (ISNULL(R.NARTotal,0) - ISNULL(R.NYSTotal,0)) AS nqcartotal, 
	ISNULL(R.ARTotal,0) - ISNULL(R.YSTotal,0) AS arretotal,		                       --应收本期发生								
	ISNULL(R.NARTotal,0) - ISNULL(R.NYSTotal,0) AS narretotal,	
	((ISNULL(L.ARTotal,0) - ISNULL(L.YSTotal,0)) - (ISNULL(B.ARTotal,0) - ISNULL(B.YSTotal,0))) AS ARTotal,		
	((ISNULL(L.NARTotal,0) - ISNULL(L.NYSTotal,0)) - (ISNULL(B.NARTotal,0) - ISNULL(B.NYSTotal,0))) AS NARTotal,	
	(ISNULL(L.APTotal,0) - ISNULL(L.YFTotal,0)) - (ISNULL(B.APTotal,0) - ISNULL(B.YFTotal,0)) - (ISNULL(R.APTotal,0) - ISNULL(R.YFTotal,0)) AS qcaptotal,  
	(ISNULL(L.NAPTotal,0) - ISNULL(L.NYFTotal,0)) - (ISNULL(B.NAPTotal,0) - ISNULL(B.NYFTotal,0)) - (ISNULL(R.NAPTotal,0) - ISNULL(R.NYFTotal,0)) AS nqcaptotal,
	ISNULL(R.APTotal,0) - ISNULL(R.YFTotal,0) AS apretotal,										
	ISNULL(R.NAPTotal,0) - ISNULL(R.NYFTotal,0) AS napretotal,
	((ISNULL(L.APTotal,0) - ISNULL(L.YFTotal,0)) - (ISNULL(B.APTotal,0) - ISNULL(B.YFTotal,0))) AS APTotal,
	((ISNULL(L.NAPTotal,0) - ISNULL(L.NYFTotal,0)) - (ISNULL(B.NAPTotal,0) - ISNULL(B.NYFTotal,0))) AS NAPTotal,
	ISNULL(L.GRIRTotal,0)-ISNULL(B.GRIRTotal,0)-ISNULL(R.GRIRTotal,0) as QCGRIRTotal, --应付暂估期初
	ISNULL(L.NGRIRTotal,0)-ISNULL(B.NGRIRTotal,0)-ISNULL(R.NGRIRTotal,0) as qcNGRIRTotal,
	ISNULL(r.GRIRTotal,0) as addGRIRTotal, --应付暂估本期增加
	ISNULL(r.nGRIRTotal,0) as addNGRIRTotal,
	ISNULL(L.GRIRTotal,0)-ISNULL(B.GRIRTotal,0) as GRIRTotal, --应付暂估期末
	ISNULL(L.NGRIRTotal,0)-ISNULL(B.NGRIRTotal,0) as NGRIRTotal
FROM #BType T
LEFT JOIN (
	--现在时间应收余额	
	SELECT  
		B.BTypeID,
		ISNULL(SUM(B.ARTotal),0) AS ARTotal,
		ISNULL(SUM(B.NARTotal),0) AS NARTotal,
		ISNULL(SUM(B.YSTotal),0) AS YSTotal,
		ISNULL(SUM(B.NYSTotal),0) AS NYSTotal,
		ISNULL(SUM(B.APTotal),0) AS APTotal,
		ISNULL(SUM(B.NAPTotal),0) AS NAPTotal,
		ISNULL(SUM(B.YFTotal),0) AS YFTotal,
		ISNULL(SUM(B.NYFTotal),0) AS NYFTotal,
		CASE WHEN '+CAST(@queryinvoice AS VARCHAR)+'=1 THEN SUM(GRIRTotal) ELSE 0 END  AS GRIRTotal,
		CASE WHEN '+CAST(@queryinvoice AS VARCHAR)+'=1 THEN SUM(NGRIRTotal) ELSE 0 END  AS NGRIRTotal
	FROM #BType BT
	INNER JOIN BType_ArApTotal B ON B.btypeid = BT.TypeID 
	INNER JOIN #SType S ON S.typeid=B.Stypeid'+CHAR(13)
IF @CID<>0
	SET @SQL+='WHERE B.CID='+CONVERT(VARCHAR, @CID)

DECLARE @CIDWhereL VARCHAR(100)
IF @CID<>0
	SET @SQL+=' and B.CID='+CONVERT(VARCHAR, @CID)

SET @SQL+='GROUP BY B.BTypeID
)L ON L.BTypeID=T.TypeID
LEFT JOIN(--结束时间到今天应收发生额
	SELECT 
		L.BtypeId,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''987'' THEN Total END),0) AS ARTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''987'' THEN NTotal END),0) AS NARTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''2131'' THEN Total END),0) AS YSTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''2131'' THEN NTotal END),0) AS NYSTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''2121'' THEN Total END),0) AS APTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''2121'' THEN NTotal END),0) AS NAPTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''1151'' THEN Total END),0) AS YFTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''1151'' THEN NTotal END),0) AS NYFTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''2122'' THEN Total END),0) AS GRIRTotal,
		ISNULL(SUM(CASE WHEN AC.UserCode = ''2122'' THEN NTotal END),0) AS NGRIRTotal
	FROM #BType BT
	INNER JOIN ListTable L ON L.btypeid = BT.TypeID 
	INNER JOIN #SType S ON S.typeid=L.Stypeid
	INNER JOIN AC_Items AC ON L.AtypeId=AC.nid
	WHERE 
		L.BillDate >'+CHAR(39)+@EndDate+CHAR(39)+'
		AND AC.UserCode IN (''987'',''2131'',''2121'',''1151'',''2122'') '+@sqlinvoicewhere+CHAR(13)
IF @CID<>0
	SET @SQL+=' and l.CID='+CONVERT(VARCHAR, @CID)+CHAR(13)
SET @SQL+='
		GROUP BY L.BtypeId
)B ON B.BTypeID=T.TypeID	
LEFT JOIN(--开始时间到结束时间应收发生额
	SELECT 
		L.BtypeId,
		ISNULL(SUM(CASE WHEN A.UserCode = ''987'' THEN Total END),0) AS ARTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''987'' THEN NTotal END),0) AS NARTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''2131'' THEN Total END),0) AS YSTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''2131'' THEN NTotal END),0) AS NYSTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''2121'' THEN Total END),0) AS APTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''2121'' THEN NTotal END),0) AS NAPTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''1151'' THEN Total END),0) AS YFTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''1151'' THEN NTotal END),0) AS NYFTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''2122'' THEN Total END),0) AS GRIRTotal,
		ISNULL(SUM(CASE WHEN A.UserCode = ''2122'' THEN NTotal END),0) AS NGRIRTotal
	FROM #BType BT
	INNER JOIN ListTable L ON L.btypeid = BT.TypeID 
	INNER JOIN #SType S ON S.typeid=L.Stypeid
	INNER JOIN AC_Items A ON L.Atypeid=A.nid AND A.UserCode IN (''987'',''2131'',''2121'',''1151'',''2122'') 
	WHERE 
		L.BillDate BETWEEN'''+@StartDate+''' AND '''+@EndDate+'''
		'+@sqlinvoicewhere+CHAR(13)
IF @CID<>0
	SET @SQL+=' and  L.CID='+CONVERT(VARCHAR, @CID)+CHAR(13)
SET @SQL+='
	GROUP BY L.BtypeId
)R ON R.BTypeID=T.TypeID'
--PRINT @SQL
EXEC(@SQL)	
					
SET @SQL='  
SELECT	
	B.TypeId,
	B.Sonnum,
	ISNULL(SUM( CASE WHEN '+@cid+'=0 THEN I.qctotal ELSE I.nqctotal END),0) AS total00,
	ISNULL(SUM(CASE WHEN '+@cid+'=0 THEN I.arretotal ELSE I.narretotal END),0)
	-ISNULL(SUM(CASE WHEN '+@cid+'=0 THEN I.apretotal ELSE I.napretotal END),0)
	-ISNULL(SUM(CASE WHEN '+@cid+'=0 THEN I.addGRIRTotal ELSE I.addNGRIRTotal END),0) as total,
	ISNULL(SUM(CASE WHEN '+@cid+'=0 THEN I.qmtotal ELSE I.nqmtotal END),0) AS qmtotal
FROM #BTypePar B
LEFT JOIN(							  
	SELECT 
		A.BTypeId,
		ISNULL(SUM(A.qcartotal),0)-ISNULL(SUM(A.qcaptotal),0)-SUM(ISNULL(A.qcGRIRTotal,0)) AS qctotal,
		ISNULL(SUM(A.nqcartotal),0)-ISNULL(SUM(A.nqcaptotal),0)-SUM(ISNULL(A.qcNGRIRTotal,0)) AS nqctotal,
		ISNULL(SUM(A.ARTotal),0)-ISNULL(SUM(A.APTotal),0)-SUM(ISNULL(GRIRTotal,0)) AS qmtotal,
		ISNULL(SUM(A.NARTotal),0)-ISNULL(SUM(A.NAPTotal),0)-SUM(ISNULL(NGRIRTotal,0)) AS nqmtotal,
		ISNULL(SUM(A.arretotal),0) AS arretotal,
		ISNULL(SUM(A.narretotal),0) AS narretotal,
		ISNULL(SUM(A.apretotal),0) AS apretotal,
		ISNULL(SUM(A.napretotal),0) AS napretotal,
		ISNULL(SUM(A.addGRIRTotal),0) AS addGRIRTotal,
		ISNULL(SUM(A.addNGRIRTotal),0) AS addNGRIRTotal
	FROM #RESULT_ARAP A
	GROUP BY A.BTypeId
)I ON I.BTypeId LIKE B.TypeId+''%''
GROUP BY 
	B.TypeId,
	B.UserCode,
	B.SonNum
ORDER BY B.UserCode'
--PRINT @SQL
EXEC(@SQL)
DROP TABLE #SType,#BType,#BTypePar,#RESULT_ARAP

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApBaseDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApBaseDetail]
GO

--===========================================================
-----------------功能：查询应收应付期初对映的单据  ----------
-----------------作者：韩林						   ----------
-----------------日期：2012-06-15                  ----------
-- 2013-08-29 周华 修改将开账后结算的数据加回来
--===========================================================

CREATE    PROC Web_QueryArApBaseDetail
(
	@type	 INT,
	@stypeid VARCHAR(50),
	@btypeid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @sql VARCHAR(max)='', @ExpenseToAr INT=0
DECLARE @sqlcomplete VARCHAR(200)='';
DECLARE @sqlcomplete1 VARCHAR(200)='';
DECLARE @adbsqlcomplete VARCHAR(200)='';
DECLARE @adbsqlcomplete1 VARCHAR(200)='';

SET @sqlcomplete=' (SELECT ISNULL(SUM(CompleteTotal),0) FROM CompleteTotal WHERE MoneyBillID<>-1 AND GoodsBillID=a.billNumberId ) ';
SET @sqlcomplete1=' (SELECT ISNULL(SUM(CompleteTotal),0) FROM CompleteTotal WHERE MoneyBillID<>-1 AND GoodsBillID=b.billNumberId )  ';
SET @adbsqlcomplete=' (SELECT ISNULL(SUM(CompleteTotal),0) FROM CompleteTotal WHERE MoneyBillID<>-1 AND GoodsBillID=a.billNumberId and GoodsBillDetailID=a.ID ) ';
SET @adbsqlcomplete1=' (SELECT ISNULL(SUM(CompleteTotal),0) FROM CompleteTotal WHERE MoneyBillID<>-1 AND GoodsBillID=b.billNumberId and GoodsBillDetailID=a.ID )  ';


SELECT @ExpenseToAr=SubValue FROM dbo.sysdata WHERE SubName='ExpenseToAr'
SET @sql='
SELECT	n.BillName AS billtype,
		BillCode,
		BillDate,
		btypeid,
		a.FullName AS cfullname,
		b.Rate,
		b.total,
		b.ntotal
FROM
(
	SELECT	billtype,
			BillCode,
			BillDate,
			btypeid,
			cid,
			rate,
			CASE WHEN billtype IN ('+CASE WHEN @type=1 THEN '11,12,160,141,93,85,167,168,172,181,189,213,312' ELSE '34,161,145,84,170,190,212' END+') 
						THEN totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0)
					 WHEN billtype IN ('+CASE WHEN @type=1 THEN '4,45,46,148,149'ELSE '66,6,150,151' END+') 
						THEN -(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
					 WHEN billtype =36 and '+CASE WHEN @type=1 THEN'btypeid like ''00001%'' AND '+CAST(@ExpenseToAr AS VARCHAR(2))+'=1 THEN -' ELSE '(btypeid like ''00002%'' OR '+CAST(@ExpenseToAr AS VARCHAR(2))+'=0) THEN ' END+'
						(totalmoney-preferencemoney-CompleteTotal-totalinmoney-ISNULL(ChargeOffTotal,0))
				END+'+@sqlcomplete+' AS total,
			CASE WHEN billtype IN ('+CASE WHEN @type=1 THEN '11,12,160,141,93,85,167,168,172,181,189,213,312' ELSE '34,161,145,84,170,190,212' END+') 
						THEN ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney -ISNULL(NChargeOffTotal,0)
					 WHEN billtype IN ('+CASE WHEN @type=1 THEN '4,45,46,148,149'ELSE '66,6,150,151' END+') 
						THEN -(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0))
					 WHEN billtype =36 and '+CASE WHEN @type=1 THEN'btypeid like ''00001%'' AND '+CAST(@ExpenseToAr AS VARCHAR(2))+'=1 THEN -' ELSE '(btypeid like ''00002%'' OR '+CAST(@ExpenseToAr AS VARCHAR(2))+'=0) THEN ' END+'
						(ntotalmoney-npreferencemoney-nCompleteTotal-ntotalinmoney-ISNULL(NChargeOffTotal,0))
				END+'+REPLACE(@sqlcomplete,'SUM(CompleteTotal)','SUM(NCompleteTotal)')+' AS ntotal
	FROM dbo.BillIndex a
	WHERE	(billtype in'+CASE WHEN @type=1 THEN '(4,11,12,160,141,93,85,167,168,172,181,189,45,46,148,149,213,312)' ELSE '(66,34,161,145,84,170,190,6,150,151,212)' END+'
			OR(billtype=36 and '+CASE WHEN @type=1 THEN'btypeid like ''00001%'' AND '+CAST(@ExpenseToAr AS VARCHAR(2))+'=1' ELSE '(btypeid like ''00002%'' OR '+CAST(@ExpenseToAr AS VARCHAR(2))+'=0)' END+'))
			AND isini=1
			and stypeid='''+@stypeid+'''
			AND Btypeid like '''+@btypeid+'%''
	UNION ALL
	SELECT  b.billtype,
			b.BillCode,
			b.BillDate,
			a.btypeid,
			b.cid,
			b.rate,
			CASE WHEN b.billtype = '+CASE WHEN @type=1 THEN '116' ELSE '128' END+'
						THEN a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0)
					 WHEN b.billtype = '+CASE WHEN @type=1 THEN '115'ELSE '129' END+'
						THEN -(a.total -a.CompleteTotal-ISNULL(a.ChargeOffTotal,0))
				END+'+@adbsqlcomplete1+' AS total,
			CASE WHEN b.billtype = '+CASE WHEN @type=1 THEN '116' ELSE '128' END+'
						THEN a.ntotal -a.nCompleteTotal-ISNULL(a.nChargeOffTotal,0)
					 WHEN b.billtype = '+CASE WHEN @type=1 THEN '115'ELSE '129' END+'
						THEN -(a.ntotal -a.nCompleteTotal-ISNULL(a.nChargeOffTotal,0))
				END+'+REPLACE(@adbsqlcomplete,'SUM(CompleteTotal)','SUM(NCompleteTotal)')+' AS ntotal
	FROM	AdDebtBill a 
	INNER JOIN billindex b ON a.BillNumberId =b.BillNumberId
	WHERE	b.billtype in('+CASE WHEN @type=1 THEN '115,116' ELSE '128,129' END+')
			AND b.isini=1
			and b.stypeid='''+@stypeid+'''
			AND a.Btypeid like '''+@btypeid+'%''
	UNION ALL
	SELECT  billtype,
			BillCode,
			BillDate,
			btypeid,
			cid,
			rate,
			TaxTotalMoney-CompleteTotal-ISNULL(ChargeOffTotal,0) AS Total,
			NTaxTotalMoney-NCompleteTotal-ISNULL(NChargeOffTotal,0) AS NTotal
	FROM ReceiptBillIndex WHERE Isini=1 AND BillType='''+CASE WHEN @type=1 THEN '405' ELSE '404' END+''' AND  StypeID= '''+@stypeid+'''
	AND Btypeid like '''+@btypeid+'%''
			
) b
INNER JOIN dbo.BillName n ON b.BillType=n.Billtype
INNER JOIN dbo.Ac_Currency a ON b.cid=a.CId '
--PRINT @sql
EXEC(@sql)          
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApHistoryLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApHistoryLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














/*
	作者：谢吉康
	日期：2005-11-23
	描述：应收、应付历史状况
*/
CREATE PROCEDURE Web_QueryArApHistoryLine
(
	@OperatorID		varchar(100),
	@TypeId			varchar(100),
	@nType			int,			--1、应收查询 2、应付查询
	@StartDate		datetime,
	@EndDate		datetime,
	@UserCode		varchar(256),
	@FullName		varchar(256),
	@stypeid		varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 		varchar(8000),
		@SonNum		int,
		@BTypeAll	int

IF @TypeId = '00000'
	SET @TypeId = '%'

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

create table #stype (typeid varchar(50))
INSERT INTO #stype(typeid) 
	SELECT  A.typeid
		FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

CREATE TABLE #BType
(
	TypeId		varchar(100),
	ArTotal00	 NUMERIC(24, 10) ,
	ApTotal00	 NUMERIC(24, 10) ,
	SqArTotal	 NUMERIC(24, 10) ,
	BqArTotal	 NUMERIC(24, 10) ,
	SqApTotal	 NUMERIC(24, 10) ,
	BqApTotal	 NUMERIC(24, 10) ,
	ArLimit		 NUMERIC(24, 10) 
)
	

IF @stypeid='' AND @MStypeid='00000'
BEGIN
	INSERT INTO #BType
	(
		TypeId,
		ArTotal00,
		ApTotal00,
		SqArTotal,
		BqArTotal,
		SqApTotal,
		BqApTotal,
		ArLimit
	)
	SELECT	TypeId,
			SUM(ISNULL(B.ArTotal00,0)) AS ArTotal00,
			SUM(ISNULL(B.APTotal00,0)) AS ApTotal00,
			0 AS SqArTotal,
			0 AS BqArTotal,
			0 AS SqApTotal,
			0 AS BqApTotal,		
			SUM(ISNULL(ArLimit,0)) AS ArLimit
	FROM	F_GetManBTypeAll(@OperatorID) A
			INNER JOIN BType_ARAPTotal B ON A.typeId=B.BTypeID
			INNER join btype_credit c on c.BtypeId=a.typeId
	WHERE	Deleted = 0
			AND TypeId LIKE @TypeId + '%'
			AND SonNum = 0
			GROUP BY A.typeId

	INSERT INTO #BType
	(
		TypeId,
		ArTotal00,
		ApTotal00,
		SqArTotal,
		BqArTotal,
		SqApTotal,
		BqApTotal,
		ArLimit
	)
	SELECT	L.BTypeId,
			0 AS ArTotal00,
			0 AS ApTotal00,
			SUM(CASE
				WHEN L.BillDate<@StartDate AND L.ATypeId = '0000100005' THEN Total
				ELSE 0
			END) AS SqArTotal,
			SUM(CASE 
				WHEN L.BillDate>=@StartDate AND L.BillDate<=@EndDate AND L.ATypeId = '0000100005' THEN Total
				ELSE 0
			END) AS BqArTotal,
			SUM(CASE
				WHEN L.BillDate<@StartDate AND L.ATypeId = '0000200001' THEN Total
				ELSE 0
			END) AS SqApTotal,		
			SUM(CASE 
				WHEN L.BillDate>=@StartDate AND L.BillDate<=@EndDate AND L.ATypeId = '0000200001' THEN Total
				ELSE 0
			END) AS BqApTotal,
			0 AS ArLimit	
	FROM	ListTable L,
			#BType B
	WHERE	L.BillDate<=@EndDate
			AND L.BTypeId = B.TypeId
			AND L.ATypeId IN ('0000100005','0000200001')
			AND L.Audited = 1
	GROUP BY L.BTypeId
END
ELSE
BEGIN
	INSERT INTO #BType
	(
		TypeId,
		ArTotal00,
		ApTotal00,
		SqArTotal,
		BqArTotal,
		SqApTotal,
		BqApTotal,
		ArLimit
	)
	SELECT	A.TypeId,
			SUM(ISNULL(B.ArTotal00,0)) AS ArTotal00,
			SUM(ISNULL(B.APTotal00,0)) AS ApTotal00,
			0 AS SqArTotal,
			0 AS BqArTotal,
			0 AS SqApTotal,
			0 AS BqApTotal,		
			SUM(ISNULL(ArLimit,0)) AS ArLimit
	FROM	F_GetManBTypeAll(@OperatorID) A
			INNER JOIN BType_ARAPTotal B ON A.typeId=B.BTypeID
			INNER JOIN #stype S ON S.typeid=B.STypeID
			INNER join btype_credit c on c.BtypeId=a.typeId
	WHERE	Deleted = 0
			AND A.TypeId LIKE @TypeId + '%'
			AND A.SonNum = 0
		GROUP BY A.typeId

	INSERT INTO #BType
	(
		TypeId,
		ArTotal00,
		ApTotal00,
		SqArTotal,
		BqArTotal,
		SqApTotal,
		BqApTotal,
		ArLimit
	)
	SELECT	L.BTypeId,
			0 AS ArTotal00,
			0 AS ApTotal00,
			SUM(CASE
				WHEN L.BillDate<@StartDate AND L.ATypeId = '0000100005' THEN Total
				ELSE 0
			END) AS SqArTotal,
			SUM(CASE 
				WHEN L.BillDate>=@StartDate AND L.BillDate<=@EndDate AND L.ATypeId = '0000100005' THEN Total
				ELSE 0
			END) AS BqArTotal,
			SUM(CASE
				WHEN L.BillDate<@StartDate AND L.ATypeId = '0000200001' THEN Total
				ELSE 0
			END) AS SqApTotal,		
			SUM(CASE 
				WHEN L.BillDate>=@StartDate AND L.BillDate<=@EndDate AND L.ATypeId = '0000200001' THEN Total
				ELSE 0
			END) AS BqApTotal,
			0 AS ArLimit	
	FROM	ListTable L,
			#BType B,
			#stype S
	WHERE	L.BillDate<=@EndDate
			AND L.BTypeId = B.TypeId
			AND S.typeid=L.STypeID
			AND L.ATypeId IN ('0000100005','0000200001')
			AND L.Audited = 1
	GROUP BY L.BTypeId
END


IF @BTypeAll = 1
	BEGIN
		IF @nType = 1	--应收
			BEGIN
				SET @SQL = '
							SELECT	X.*
							FROM	(
										SELECT	B.TypeId,
												B.SonNum,
												B.UserCode,
												B.FullName,
												SUM(ISNULL(M.ArTotal00,0)-ISNULL(M.ApTotal00,0)+ISNULL(M.SqArTotal,0)-ISNULL(M.SqApTotal,0)) AS SqTotal,
												SUM(ISNULL(M.BqArTotal,0)-ISNULL(M.BqApTotal,0)) AS BqTotal,
												SUM(ISNULL(M.ArTotal00,0)-ISNULL(M.ApTotal00,0)+ISNULL(M.SqArTotal,0)-ISNULL(M.SqApTotal,0)+ISNULL(M.BqArTotal,0)-ISNULL(M.BqApTotal,0)) AS QmTotal,
												SUM(ISNULL(B.ArLimit,0)) AS ArLimit'

							IF NOT (@MBTypeId = '00001' AND @MBTypeId2='00002')
								SET @SQL = @SQL + '	FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B '
							ELSE
								SET @SQL = @SQL + ' FROM 	BType B'

							SET @SQL = @SQL + '
										INNER JOIN (
													SELECT	TypeId,
															SUM(ArTotal00) AS ArTotal00,
															SUM(ApTotal00) AS ApTotal00,
															SUM(SqArTotal) AS SqArTotal,
															SUM(BqArTotal) AS BqArTotal,
															SUM(SqApTotal) AS SqApTotal,
															SUM(BqApTotal) AS BqApTotal,
															SUM(ArLimit) AS ArLimit
													FROM 	#BType
													WHERE	ArTotal00<>0 OR ApTotal00<>0 OR SqArTotal<>0 OR SqApTotal<>0 OR BqArTotal<>0 OR BqApTotal<>0
													GROUP BY TypeId
										)M ON M.TypeID=B.TypeID
										WHERE 	B.Deleted = 0
												AND B.SonNum = 0												
												AND B.TypeId LIKE '+char(39)+@TypeID+'%'+char(39)+'
												AND B.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
												AND B.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
										GROUP BY	B.TypeId,
													B.SonNum,
													B.UserCode,
													B.FullName										
							)X 
							WHERE	ISNULL(X.SqTotal,0)<>0
									OR ISNULL(X.BqTotal,0)<>0
									OR ISNULL(X.QmTotal,0)<>0 
							ORDER BY X.UserCode '
			END
		ELSE
			BEGIN
				SET @SQL = '
							SELECT	X.*
							FROM	(
										SELECT	B.TypeId,
												B.SonNum,
												B.UserCode,
												B.FullName,
												SUM(ISNULL(M.ApTotal00,0)-ISNULL(M.ArTotal00,0)+ISNULL(M.SqApTotal,0)-ISNULL(M.SqArTotal,0)) AS SqTotal,
												SUM(ISNULL(M.BqApTotal,0)-ISNULL(M.BqArTotal,0)) AS BqTotal,
												SUM(ISNULL(M.ApTotal00,0)-ISNULL(M.ArTotal00,0)+ISNULL(M.SqApTotal,0)-ISNULL(M.SqArTotal,0)+ISNULL(M.BqApTotal,0)-ISNULL(M.BqArTotal,0)) AS QmTotal,
												SUM(ISNULL(B.ArLimit,0)) AS ArLimit'

							IF NOT (@MBTypeId = '00001' AND @MBTypeId2='00002')
								SET @SQL = @SQL + '	FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B '
							ELSE
								SET @SQL = @SQL + ' FROM 	BType B'

							SET @SQL = @SQL + '
										INNER JOIN (
													SELECT	TypeId,
															SUM(ArTotal00) AS ArTotal00,
															SUM(ApTotal00) AS ApTotal00,
															SUM(SqArTotal) AS SqArTotal,
															SUM(BqArTotal) AS BqArTotal,
															SUM(SqApTotal) AS SqApTotal,
															SUM(BqApTotal) AS BqApTotal,
															SUM(ArLimit) AS ArLimit
													FROM 	#BType
													WHERE	ArTotal00<>0 OR ApTotal00<>0 OR SqArTotal<>0 OR SqApTotal<>0 OR BqArTotal<>0 OR BqApTotal<>0
													GROUP BY TypeId
										)M ON M.TypeID=B.TypeID
										WHERE 	B.Deleted = 0	
												AND B.SonNum = 0
												AND B.TypeId LIKE '+char(39)+@TypeID+'%'+char(39)+' 
												AND B.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
												AND B.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
										GROUP BY	B.TypeId,
													B.SonNum,
													B.UserCode,
													B.FullName										
							)X 
							WHERE	ISNULL(X.SqTotal,0)<>0
									OR ISNULL(X.BqTotal,0)<>0
									OR ISNULL(X.QmTotal,0)<>0 
							ORDER BY X.UserCode '
			END
	END
ELSE
	BEGIN
		IF @nType = 1	--应收
			BEGIN
				SET @SQL = '
							SELECT	X.*
							FROM	(
										SELECT	B.TypeId,
												B.SonNum,
												B.UserCode,
												B.FullName,
												SUM(ISNULL(M.ArTotal00,0)-ISNULL(M.ApTotal00,0)+ISNULL(M.SqArTotal,0)-ISNULL(M.SqApTotal,0)) AS SqTotal,
												SUM(ISNULL(M.BqArTotal,0)-ISNULL(M.BqApTotal,0)) AS BqTotal,
												SUM(ISNULL(M.ArTotal00,0)-ISNULL(M.ApTotal00,0)+ISNULL(M.SqArTotal,0)-ISNULL(M.SqApTotal,0)+ISNULL(M.BqArTotal,0)-ISNULL(M.BqApTotal,0)) AS QmTotal,
												SUM(ISNULL(B.ArLimit,0)) AS ArLimit'

							IF NOT (@MBTypeId = '00001' AND @MBTypeId2='00002')
								SET @SQL = @SQL + '	FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B '
							ELSE
								SET @SQL = @SQL + ' FROM 	BType B'

							SET @SQL = @SQL + '
										INNER JOIN (
													SELECT	TypeId,
															SUM(ArTotal00) AS ArTotal00,
															SUM(ApTotal00) AS ApTotal00,
															SUM(SqArTotal) AS SqArTotal,
															SUM(BqArTotal) AS BqArTotal,
															SUM(SqApTotal) AS SqApTotal,
															SUM(BqApTotal) AS BqApTotal,
															SUM(ArLimit) AS ArLimit
													FROM 	#BType
													WHERE	ArTotal00<>0 OR ApTotal00<>0 OR SqArTotal<>0 OR SqApTotal<>0 OR BqArTotal<>0 OR BqApTotal<>0
													GROUP BY TypeId													
										)M ON M.TypeID=B.TypeID
										WHERE 	B.Deleted = 0	
												AND B.SonNum = 0
												AND B.TypeId LIKE '+char(39)+'00001%'+char(39)+'
												AND B.TypeId LIKE '+char(39)+@TypeID+'%'+char(39)+' 
												AND B.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
												AND B.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
										GROUP BY	B.TypeId,
													B.SonNum,
													B.UserCode,
													B.FullName										
							)X 
							WHERE	ISNULL(X.SqTotal,0)<>0
									OR ISNULL(X.BqTotal,0)<>0
									OR ISNULL(X.QmTotal,0)<>0 
							ORDER BY X.UserCode '
			END
		ELSE
			BEGIN
				SET @SQL = '
							SELECT	X.*

							FROM	(
									SELECT	B.TypeId,
											B.SonNum,
											B.UserCode,
											B.FullName,
											SUM(ISNULL(M.ApTotal00,0)-ISNULL(M.ArTotal00,0)+ISNULL(M.SqApTotal,0)-ISNULL(M.SqArTotal,0)) AS SqTotal,
											SUM(ISNULL(M.BqApTotal,0)-ISNULL(M.BqArTotal,0)) AS BqTotal,
											SUM(ISNULL(M.ApTotal00,0)-ISNULL(M.ArTotal00,0)+ISNULL(M.SqApTotal,0)-ISNULL(M.SqArTotal,0)+ISNULL(M.BqApTotal,0)-ISNULL(M.BqArTotal,0)) AS QmTotal,
											SUM(ISNULL(B.ArLimit,0)) AS ArLimit'

							IF NOT (@MBTypeId = '00001' AND @MBTypeId2='00002')
								SET @SQL = @SQL + '	FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B '
							ELSE
								SET @SQL = @SQL + ' FROM 	BType B'

							SET @SQL = @SQL + '
									INNER JOIN (
													SELECT	TypeId,
															SUM(ArTotal00) AS ArTotal00,
															SUM(ApTotal00) AS ApTotal00,
															SUM(SqArTotal) AS SqArTotal,
															SUM(BqArTotal) AS BqArTotal,
															SUM(SqApTotal) AS SqApTotal,
															SUM(BqApTotal) AS BqApTotal,
															SUM(ArLimit) AS ArLimit
													FROM 	#BType
													WHERE	ArTotal00<>0 OR ApTotal00<>0 OR SqArTotal<>0 OR SqApTotal<>0 OR BqArTotal<>0 OR BqApTotal<>0
													GROUP BY TypeId										
									)M ON M.TypeID=B.TypeID
									WHERE 	B.Deleted = 0	
											AND B.SonNum = 0
											AND B.TypeId LIKE '+char(39)+'00002%'+char(39)+'
											AND B.TypeId LIKE '+char(39)+@TypeID+'%'+char(39)+' 
											AND B.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
											AND B.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
									GROUP BY	B.TypeId,
												B.SonNum,
												B.UserCode,
												B.FullName										
									)X 
							WHERE	ISNULL(X.SqTotal,0)<>0
									OR ISNULL(X.BqTotal,0)<>0
									OR ISNULL(X.QmTotal,0)<>0 
							ORDER BY X.UserCode '
			END
	END

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #BType














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApHistoryList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApHistoryList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO














/*
	作者：谢吉康
	日期：2005-11-23
	描述：应收、应付历史状况
*/
CREATE PROCEDURE Web_QueryArApHistoryList
(
	@OperatorID		varchar(100),
	@bTypeId			varchar(100),
	@nType			int,			--1、应收查询 2、应付查询
	@StartDate		datetime,
	@EndDate		datetime,
	@stypeid		varchar(2000)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 		varchar(8000),
		@SonNum		int,
		@BTypeAll	int

SELECT @SonNum = SonNum FROM BType WHERE TypeId = @bTypeId AND Deleted = 0

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

create table #stype (typeid varchar(50))
INSERT INTO #stype(typeid) 
	SELECT  A.typeid
		FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

CREATE TABLE #BType
(
	TypeId		varchar(100),
	ArTotal00	 NUMERIC(24, 10) ,
	ApTotal00	 NUMERIC(24, 10) ,
	SqArTotal	 NUMERIC(24, 10) ,
	BqArTotal	 NUMERIC(24, 10) ,
	SqApTotal	 NUMERIC(24, 10) ,
	BqApTotal	 NUMERIC(24, 10) ,
	ArLimit		 NUMERIC(24, 10) 
)
IF @stypeid='' and @MStypeid='00000' --有全部权限且没有筛选分支机构
begin
	INSERT INTO #BType
	(
		TypeId,
		ArTotal00,
		ApTotal00,
		SqArTotal,
		BqArTotal,
		SqApTotal,
		BqApTotal,
		ArLimit
	)
	SELECT	a.TypeId,
			SUM(ISNULL(b.ARTotal00,0)) AS ArTotal00,
			SUM(ISNULL(b.APTotal00,0)) AS ApTotal00,
			0 AS SqArTotal,
			0 AS BqArTotal,
			0 AS SqApTotal,
			0 AS BqApTotal,		
			SUM(ISNULL(ArLimit,0)) AS ArLimit
	FROM	F_GetManBTypeAll(@OperatorID) a
		INNER join BType_ARAPTotal b on a.typeId=b.BTypeID
		INNER join btype_credit c on c.BtypeId=a.typeId 
	WHERE SonNum = 0 
	GROUP BY A.typeId
	
	INSERT INTO #BType
	(
		TypeId,
		ArTotal00,
		ApTotal00,
		SqArTotal,
		BqArTotal,
		SqApTotal,
		BqApTotal,
		ArLimit
	)
	SELECT	L.BTypeId,
			0 AS ArTotal00,
			0 AS ApTotal00,
			SUM(CASE
				WHEN L.BillDate<@StartDate AND L.ATypeId = '0000100005' THEN Total
				ELSE 0
			END) AS SqArTotal,
			SUM(CASE 
				WHEN L.BillDate>=@StartDate AND L.BillDate<=@EndDate AND L.ATypeId = '0000100005' THEN Total
				ELSE 0
			END) AS BqArTotal,
			SUM(CASE
				WHEN L.BillDate<@StartDate AND L.ATypeId = '0000200001' THEN Total
				ELSE 0
			END) AS SqApTotal,		
			SUM(CASE 
				WHEN L.BillDate>=@StartDate AND L.BillDate<=@EndDate AND L.ATypeId = '0000200001' THEN Total
				ELSE 0
			END) AS BqApTotal,
			0 AS ArLimit	
	FROM	ListTable L,
			#BType B
	WHERE	L.BillDate<=@EndDate
			AND L.BTypeId = B.TypeId
			AND L.ATypeId IN ('0000100005','0000200001')
			AND L.Audited = 1
	GROUP BY L.BTypeId
end
else
begin
		INSERT INTO #BType
	(
		TypeId,
		ArTotal00,
		ApTotal00,
		SqArTotal,
		BqArTotal,
		SqApTotal,
		BqApTotal,
		ArLimit
	)
	SELECT	a.TypeId,
			SUM(ISNULL(b.ARTotal00,0)) AS ArTotal00,
			SUM(ISNULL(b.APTotal00,0)) AS ApTotal00,
			0 AS SqArTotal,
			0 AS BqArTotal,
			0 AS SqApTotal,
			0 AS BqApTotal,		
			SUM(ISNULL(ArLimit,0)) AS ArLimit
	FROM	F_GetManBTypeAll(@OperatorID) a
		INNER join BType_ARAPTotal b on a.typeId=b.BTypeID
		INNER join btype_credit c on c.BtypeId=a.typeId 
		INNER JOIN #stype S ON S.typeid=B.STypeID
	WHERE SonNum = 0 and b.STypeID in (select typeId from #stype)
	GROUP BY A.typeId
	
	INSERT INTO #BType
	(
		TypeId,
		ArTotal00,
		ApTotal00,
		SqArTotal,
		BqArTotal,
		SqApTotal,
		BqApTotal,
		ArLimit
	)
	SELECT	L.BTypeId,
			0 AS ArTotal00,
			0 AS ApTotal00,
			SUM(CASE
				WHEN L.BillDate<@StartDate AND L.ATypeId = '0000100005' THEN Total
				ELSE 0
			END) AS SqArTotal,
			SUM(CASE 
				WHEN L.BillDate>=@StartDate AND L.BillDate<=@EndDate AND L.ATypeId = '0000100005' THEN Total
				ELSE 0
			END) AS BqArTotal,
			SUM(CASE
				WHEN L.BillDate<@StartDate AND L.ATypeId = '0000200001' THEN Total
				ELSE 0
			END) AS SqApTotal,		
			SUM(CASE 
				WHEN L.BillDate>=@StartDate AND L.BillDate<=@EndDate AND L.ATypeId = '0000200001' THEN Total
				ELSE 0
			END) AS BqApTotal,
			0 AS ArLimit	
	FROM	ListTable L,
			#BType B,
			#stype s
	WHERE	L.BillDate<=@EndDate
			AND L.BTypeId = B.TypeId
			and s.typeid=l.STypeID
			AND L.ATypeId IN ('0000100005','0000200001')
			AND L.Audited = 1
	GROUP BY L.BTypeId
end

IF @BTypeAll = 1
	BEGIN
		IF @nType = 1	--应收
			BEGIN
				SET @SQL = '
							SELECT	B.TypeId,
									B.SonNum,
									B.UserCode,
									B.FullName,
									SUM(ISNULL(M.ArTotal00,0)-ISNULL(M.ApTotal00,0)+ISNULL(M.SqArTotal,0)-ISNULL(M.SqApTotal,0)) AS SqTotal,
									SUM(ISNULL(M.BqArTotal,0)-ISNULL(M.BqApTotal,0)) AS BqTotal,
									SUM(ISNULL(M.ArTotal00,0)-ISNULL(M.ApTotal00,0)+ISNULL(M.SqArTotal,0)-ISNULL(M.SqApTotal,0)+ISNULL(M.BqArTotal,0)-ISNULL(M.BqApTotal,0)) AS QmTotal,
									SUM(ISNULL(M.ArLimit,0)) AS ArLimit
							FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B
							LEFT JOIN (
								SELECT	TypeId,
										SUM(ArTotal00) AS ArTotal00,
										SUM(ApTotal00) AS ApTotal00,
										SUM(SqArTotal) AS SqArTotal,
										SUM(BqArTotal) AS BqArTotal,
										SUM(SqApTotal) AS SqApTotal,
										SUM(BqApTotal) AS BqApTotal,
										SUM(ArLimit) AS ArLimit
								FROM 	#BType
								GROUP BY TypeId
							)M ON LEFT(M.TypeID,LEN(B.TypeId)) = B.TypeID
							WHERE 	B.Deleted = 0'

				IF @SonNum = 0
					SET @SQL = @SQL + ' AND B.TypeID = '+char(39)+@bTypeId+char(39)
				ELSE
					SET @SQL = @SQL + ' AND B.ParId = '+char(39)+@bTypeId+char(39)

				SET @SQL = @SQL + ' 
							GROUP BY	B.TypeId,
										B.SonNum,
										B.UserCode,
										B.FullName
							ORDER BY B.UserCode '
			END
		ELSE
			BEGIN
				SET @SQL = '
							SELECT	B.TypeId,
									B.SonNum,
									B.UserCode,
									B.FullName,
									SUM(ISNULL(M.ApTotal00,0)-ISNULL(M.ArTotal00,0)+ISNULL(M.SqApTotal,0)-ISNULL(M.SqArTotal,0)) AS SqTotal,
									SUM(ISNULL(M.BqApTotal,0)-ISNULL(M.BqArTotal,0)) AS BqTotal,
									SUM(ISNULL(M.ApTotal00,0)-ISNULL(M.ArTotal00,0)+ISNULL(M.SqApTotal,0)-ISNULL(M.SqArTotal,0)+ISNULL(M.BqApTotal,0)-ISNULL(M.BqArTotal,0)) AS QmTotal,
									SUM(ISNULL(M.ArLimit,0)) AS ArLimit
							FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B
							LEFT JOIN (
								SELECT	TypeId,
										SUM(ArTotal00) AS ArTotal00,
										SUM(ApTotal00) AS ApTotal00,
										SUM(SqArTotal) AS SqArTotal,
										SUM(BqArTotal) AS BqArTotal,
										SUM(SqApTotal) AS SqApTotal,
										SUM(BqApTotal) AS BqApTotal,
										SUM(ArLimit) AS ArLimit
								FROM 	#BType
								GROUP BY TypeId
							)M ON LEFT(M.TypeID,LEN(B.TypeId)) = B.TypeID
							WHERE 	B.Deleted = 0'

				IF @SonNum = 0
					SET @SQL = @SQL + ' AND B.TypeID = '+char(39)+@bTypeId+char(39)
				ELSE
					SET @SQL = @SQL + ' AND B.ParId = '+char(39)+@bTypeId+char(39)

				SET @SQL = @SQL + ' 
							GROUP BY	B.TypeId,
										B.SonNum,
										B.UserCode,
										B.FullName
							ORDER BY B.UserCode '
			END
	END
ELSE
	BEGIN
		IF @nType = 1	--应收
			BEGIN
				SET @SQL = '
							SELECT	B.TypeId,
									B.SonNum,
									B.UserCode,
									B.FullName,
									SUM(ISNULL(M.ArTotal00,0)-ISNULL(M.ApTotal00,0)+ISNULL(M.SqArTotal,0)-ISNULL(M.SqApTotal,0)) AS SqTotal,
									SUM(ISNULL(M.BqArTotal,0)-ISNULL(M.BqApTotal,0)) AS BqTotal,
									SUM(ISNULL(M.ArTotal00,0)-ISNULL(M.ApTotal00,0)+ISNULL(M.SqArTotal,0)-ISNULL(M.SqApTotal,0)+ISNULL(M.BqArTotal,0)-ISNULL(M.BqApTotal,0)) AS QmTotal,
									SUM(ISNULL(M.ArLimit,0)) AS ArLimit
							FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B
							LEFT JOIN (
								SELECT	TypeId,
										SUM(ArTotal00) AS ArTotal00,
										SUM(ApTotal00) AS ApTotal00,
										SUM(SqArTotal) AS SqArTotal,
										SUM(BqArTotal) AS BqArTotal,
										SUM(SqApTotal) AS SqApTotal,
										SUM(BqApTotal) AS BqApTotal,
										SUM(ArLimit) AS ArLimit
								FROM 	#BType
								GROUP BY TypeId
							)M ON LEFT(M.TypeID,LEN(B.TypeId)) = B.TypeID
							WHERE 	B.Deleted = 0
									AND B.TypeId LIKE ''00001%'''
				IF @SonNum = 0
					SET @SQL = @SQL + ' AND B.TypeID = '+char(39)+@bTypeId+char(39)
				ELSE
					SET @SQL = @SQL + ' AND B.ParId = '+char(39)+@bTypeId+char(39)

				SET @SQL = @SQL + ' 
							GROUP BY	B.TypeId,
										B.SonNum,
										B.UserCode,
										B.FullName
							ORDER BY B.UserCode '
			END
		ELSE
			BEGIN
				SET @SQL = '
							SELECT	B.TypeId,
									B.SonNum,
									B.UserCode,
									B.FullName,
									SUM(ISNULL(M.ApTotal00,0)-ISNULL(M.ArTotal00,0)+ISNULL(M.SqApTotal,0)-ISNULL(M.SqArTotal,0)) AS SqTotal,
									SUM(ISNULL(M.BqApTotal,0)-ISNULL(M.BqArTotal,0)) AS BqTotal,
									SUM(ISNULL(M.ApTotal00,0)-ISNULL(M.ArTotal00,0)+ISNULL(M.SqApTotal,0)-ISNULL(M.SqArTotal,0)+ISNULL(M.BqApTotal,0)-ISNULL(M.BqArTotal,0)) AS QmTotal,
									SUM(ISNULL(M.ArLimit,0)) AS ArLimit
							FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B
							LEFT JOIN (
								SELECT	TypeId,
										SUM(ArTotal00) AS ArTotal00,
										SUM(ApTotal00) AS ApTotal00,
										SUM(SqArTotal) AS SqArTotal,
										SUM(BqArTotal) AS BqArTotal,
										SUM(SqApTotal) AS SqApTotal,
										SUM(BqApTotal) AS BqApTotal,
										SUM(ArLimit) AS ArLimit
								FROM 	#BType
								GROUP BY TypeId
							)M ON LEFT(M.TypeID,LEN(B.TypeId)) = B.TypeID
							WHERE 	B.Deleted = 0	
									AND B.TypeId LIKE ''00002%'''
				IF @SonNum = 0
					SET @SQL = @SQL + ' AND B.TypeID = '+char(39)+@bTypeId+char(39)
				ELSE
					SET @SQL = @SQL + ' AND B.ParId = '+char(39)+@bTypeId+char(39)

				SET @SQL = @SQL + ' 
							GROUP BY	B.TypeId,
										B.SonNum,
										B.UserCode,
										B.FullName
							ORDER BY B.UserCode '
			END
	END

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #BType,#stype














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApTotalDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApTotalDetail]
GO











--=================================================================
--作者：谢吉康
--日期：2004-10-10
--原因：增加是否显示红冲单据的选项
--=================================================================	
CREATE PROCEDURE Web_QueryArApTotalDetail
(
	@OperatorID 	VARCHAR(100),  	    		--操作员ID号
	@nTYpe        	INT=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@BtypeID      	VARCHAR(100),               	--往来单位typeid
	@szEtypeIDS     VARCHAR(8000),              --经手人EtypeID '刘戈 2004.05.17 修改
	@StartDate   	VARCHAR(10),                --起始日期
	@EndDate    	VARCHAR(10),                --截至日期
	@Orderby      	VARCHAR(50)='',           	--排序字段
	@showRedWord	int=1,						--是否显示红冲单据  1.显示   0.不显示
	@STypeId		VARCHAR(100)				--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId varchar(50), @MBTypeid varchar(50), @MBTypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MDTypeId VARCHAR(50),@MSTypeId VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------


DECLARE @sql VARCHAR(8000),@whereSQL VARCHAR(2000),@whereSQL1 VARCHAR(2000)
IF @startDate<>'' AND @EndDate<>''
	BEGIN
		SET @whereSQL=' WHERE BillDate>='''+@StartDate+'''  AND BillDate<='''+@EndDate+''' AND IfYearBill = 0 AND STypeId LIKE '+CHAR(39)+'%'+@STypeId+'%'+CHAR(39) 
		SET @whereSQL1=' WHERE a.BillDate>='''+@StartDate+'''  AND a.BillDate<='''+@EndDate+''' AND a.IfYearBill = 0 AND STypeId LIKE '+CHAR(39)+'%'+@STypeId+'%'+CHAR(39)
	END
ELSE IF @startDate<>''
	BEGIN
		SET @whereSQL=' WHERE BillDate>='''+@StartDate+''' AND IfYearBill = 0 AND STypeId LIKE '+CHAR(39)+'%'+@STypeId+'%'+CHAR(39)
		SET @whereSQL1=' WHERE a.BillDate>='''+@StartDate+''' AND a.IfYearBill = 0 AND STypeId LIKE '+CHAR(39)+'%'+@STypeId+'%'+CHAR(39)
	END
ELSE IF @endDate<>''
	BEGIN
		SET @whereSQL=' WHERE BillDate<='''+@EndDate+''' AND IfYearBill = 0 AND STypeId LIKE '+CHAR(39)+'%'+@STypeId+'%'+CHAR(39)
		SET @whereSQL1=' WHERE a.BillDate<='''+@EndDate+''' AND a.IfYearBill = 0 AND STypeId LIKE '+CHAR(39)+'%'+@STypeId+'%'+CHAR(39)
	END
ELSE
	BEGIN
		SET @whereSQL=' WHERE 1=1 AND IfYearBill = 0 AND STypeId LIKE '+CHAR(39)+'%'+@STypeId+'%'+CHAR(39)
		SET @whereSQL1=' WHERE 1=1 AND IfYearBill = 0 AND STypeId LIKE '+CHAR(39)+'%'+@STypeId+'%'+CHAR(39)
	END
	
-----------------------------经手人字符串取得--------------------------
declare @WHERE_ATYPEID varchar(2000),@i int,@szEtypeID  varchar(1000)
SET @WHERE_ATYPEID =''
SET @szEtypeIDS = RTRIM(LTRIM(@szEtypeIDS))
SET @i=charindex(',',@szEtypeIDS)  -- 取得'，'的位置常量
--print @i

WHILE @i>=1
	BEGIN

		SET @szEtypeID = LEFT(@szEtypeIDS,@i-1)
		IF @WHERE_ATYPEID =''
	    		SET @WHERE_ATYPEID = ' and ( etypeid like '+char(39)+@szEtypeID+'%'+char(39) 
		ELSE
			SET @WHERE_ATYPEID = @WHERE_ATYPEID+ ' or '+'etypeid like '+char(39)+@szEtypeID+'%'+char(39) 
	
		SET @szEtypeIDS=SUBSTRING(@szEtypeIDS,@i+1,len(@szEtypeIDS)-@i)
		SET @i=charindex(',',@szEtypeIDS)
	END

IF @szEtypeIDS<>''
	BEGIN
		IF @WHERE_ATYPEID = ''
			SET @WHERE_ATYPEID = 'and (etypeid like'+char(39)+@szEtypeIDS+'%'+char(39) +')'
		ELSE
			SET @WHERE_ATYPEID = @WHERE_ATYPEID+ ' or '+'etypeid like'+char(39)+@szEtypeIDS+'%'+char(39) +' ) '
	END



IF LEFT(@btypeid,5)='00001'
	IF len(@btypeid)<len(@MBtypeid)
		SET @btypeid=@MBtypeid
IF LEFT(@btypeid,5)='00002'
	IF len(@btypeid)<len(@MBtypeid2)
		SET @btypeid=@MBtypeid2

--刘戈修改添加etypeid
IF LTRIM(@szEtypeIdS)<>''
    BEGIN
		SET @whereSQL=@whereSQL+' AND Btypeid = '''+@BtypeId+''''+ @WHERE_ATYPEID
		SET @whereSQL1=@whereSQL1+' AND b.Btypeid = '''+@BtypeId+'''' + @WHERE_ATYPEID
	END
ELSE
    BEGIN
		SET @whereSQL=@whereSQL+' AND Btypeid = '''+@BtypeId+''''
		SET @whereSQL1=@whereSQL1+' AND b.Btypeid = '''+@BtypeId+''''
	END

--处理结果集
SET @SQL = '
SELECT * FROM (
	SELECT 	billType AS djlx,
			comment AS zy,
			CASE 
				WHEN billtype IN( 34,36,45,84,145,148,149,161,170)	THEN
					CASE	WHEN (totalmoney-totalinmoney<0)  AND RedWord IN(0,1) THEN (totalinmoney+preferencemoney)-totalmoney 
							WHEN (totalmoney-totalinmoney>0)  AND RedWord =2 THEN Totalmoney-(totalinmoney+ISNULL(preferencemoney,0)) 
							WHEN (totalmoney-totalinmoney=0)  AND RedWord IN(0,1) AND ISNULL(preferencemoney,0)<>0 THEN preferencemoney
							ELSE 0 
					END
				WHEN billtype IN(85,11,305,141,93,150,155,151,157,160,167,168,172) THEN
					CASE	WHEN (totalmoney-totalinmoney>0)  AND RedWord IN(0,1) THEN totalmoney-(totalinmoney+ISNULL(preferencemoney,0)) 
							WHEN (totalmoney-totalinmoney<0)  AND RedWord =2 THEN (totalinmoney+ISNULL(preferencemoney,0))-totalmoney 
							WHEN (totalmoney-totalinmoney=0)  AND RedWord IN(0,1) AND ISNULL(preferencemoney,0)<>0 THEN totalmoney-(totalinmoney+ISNULL(preferencemoney,0))
							ELSE 0 
					END
				WHEN billtype IN(6) THEN
					CASE	WHEN totalinmoney-totalmoney>0 AND RedWord IN(0,1)  THEN totalmoney-(totalinmoney+ISNULL(preferencemoney,0)) 
							WHEN totalmoney-totalinmoney>0 AND RedWord=2 THEN (totalinmoney+ISNULL(preferencemoney,0))-totalmoney 
							WHEN totalmoney-totalinmoney=0 AND RedWord=2 THEN (totalinmoney+ISNULL(preferencemoney,0))-totalmoney 
							ELSE 0 
					END
				WHEN billtype IN(4) THEN
					CASE	WHEN RedWord=2 THEN ISNULL(totalinmoney,0)+ISNULL(preferencemoney,0)
							ELSE 0 
					END
				WHEN billtype IN(66) THEN
					CASE 	WHEN RedWord = 1 THEN ISNULL(totalinmoney,0)+ISNULL(preferencemoney,0)  
							WHEN RedWord = 0 THEN ISNULL(totalinmoney,0)+ISNULL(preferencemoney,0)  
							ELSE 0 
					END
			END '
IF @ntype=1 OR @ntype=3
	SET @sql=@sql+' AS ArAdd,'
ELSE
	SET @sql=@sql+' AS ApReduce,'
SET @sql=@sql+'
			CASE 
				WHEN billtype IN (34,36,45,84,145,148,149,161,170) THEN
					CASE	WHEN (totalmoney-totalinmoney>0)  AND RedWord IN(0,1) THEN Totalmoney-(totalinmoney+ISNULL(preferencemoney,0))
							WHEN (totalmoney-totalinmoney<0)  AND RedWord =2 THEN (totalinmoney+ISNULL(preferencemoney,0))-totalmoney 							
							WHEN (totalmoney-totalinmoney=0)  AND RedWord =2 THEN (totalinmoney+ISNULL(preferencemoney,0))-totalmoney 							
							ELSE 0 
					END 
				WHEN billtype IN(85,11,305,141,93,150,155,151,157,160,167,168,172) THEN
					CASE	WHEN (totalmoney-totalinmoney<0)  AND RedWord IN(0,1) THEN (totalinmoney+ISNULL(preferencemoney,0))-totalmoney
							WHEN (totalmoney-totalinmoney>0)  AND RedWord =2 THEN totalmoney-(totalinmoney+ISNULL(preferencemoney,0))
							WHEN (totalmoney-totalinmoney=0)  AND RedWord =2 THEN totalmoney-(totalinmoney+ISNULL(preferencemoney,0))
							ELSE 0 
					END
				WHEN billtype IN(6) THEN
					CASE	WHEN totalmoney-totalinmoney>0 AND RedWord IN(0,1) 	THEN (totalinmoney+ISNULL(preferencemoney,0))-totalmoney 
							WHEN totalmoney-totalinmoney=0 AND RedWord IN(0,1) 	THEN (totalinmoney+ISNULL(preferencemoney,0))-totalmoney 							
							WHEN totalinmoney-totalmoney>0 AND RedWord =2  		THEN totalmoney-(totalinmoney+ISNULL(preferencemoney,0))
							ELSE 0 
					END
				WHEN billtype IN(4) THEN

					CASE	WHEN RedWord IN(0,1) THEN ISNULL(totalinmoney,0)+ISNULL(preferencemoney,0)
							ELSE 0 
					END
				WHEN billtype IN(66) THEN
					CASE 	WHEN RedWord=2 THEN ISNULL(totalinmoney,0)+ISNULL(preferencemoney,0)							
							ELSE 0 
					END
			END' 
IF @ntype=1 OR @ntype=3
	SET @sql=@sql+' AS ArReduce,'
ELSE
	SET @sql=@sql+' AS ApAdd,'

SET @sql=@sql+'
			BillDate,
			BillCode,
			Btypeid,
			BillNumberID,
			BillType,
			RedWord 
	FROM 	BillIndex'
	
	SET @whereSQL=@whereSQL+' AND ifCheck=''t'' AND draft=0 '
	SET @sql=@sql+@whereSQL
SET @sql=@sql+' 
		UNION ALL 
		SELECT 	a.billtype AS djlx, 
				a.comment AS zy,
				CASE 
					WHEN a.billtype IN(115,128) THEN
						CASE	WHEN a.RedWord =2 THEN b.total 
								ELSE 0 
						END
					WHEN a.billtype IN(116,129) THEN
						CASE 	WHEN a.RedWord IN(0,1) THEN b.total 
								ELSE 0 
						END
				END '
IF @ntype=1 OR @ntype=3
	SET @sql=@sql+' AS ArAdd,'
ELSE
	SET @sql=@sql+' AS ApReduce,'
SET @sql=@sql+'
				CASE 
					WHEN a.billtype IN(115,128) THEN

						CASE	WHEN a.RedWord IN(0,1) THEN b.total 
								ELSE 0 
						END
					WHEN billtype IN(116,129) THEN
						CASE 	WHEN a.RedWord=2 THEN b.total 
								ELSE 0 
						END
				END' 
IF @ntype=1 OR @ntype=3
	SET @sql=@sql+' AS ArReduce,'
ELSE
	SET @sql=@sql+' AS ApAdd,'

SET @sql=@sql+'
				a.BillDate,
				a.BillCode,
				b.Btypeid,
				a.BillNumberID,
				a.BillType,
				a.RedWord 
		FROM 	BillIndex a 
		INNER JOIN adDebtBill b ON a.BillNumberID=b.BillNumberID'+@whereSQL1+'
			AND a.ifCheck=''t'' 
			AND a.draft=0
		UNION ALL
		SELECT	A.BillType AS Djlx,
				A.Comment AS Zy, '
IF @nType = 1 OR @nType = 3
	SET @SQL = @SQL + ' 
				CASE 
					WHEN B.ATypeId=''0000100005'' AND A.RedWord = 0  THEN ISNULL(B.Total,0)
					WHEN B.ATypeId=''0000100005'' AND A.RedWord = 1  THEN ISNULL(ABS(B.Total),0)
					WHEN B.ATypeId=''0000200001'' AND A.RedWord = 2  THEN ISNULL(ABS(B.Total),0)
					ELSE 0
				END AS ArAdd,
				CASE
					WHEN B.ATypeId=''0000200001'' AND A.RedWord = 0  THEN ISNULL(B.Total,0)
					WHEN B.ATypeId=''0000200001'' AND A.RedWord = 1  THEN ISNULL(ABS(B.Total),0)					
					WHEN B.ATypeId=''0000100005'' AND A.RedWord = 2  THEN ISNULL(ABS(B.Total),0)
					ELSE 0
				END AS ArReduce,'
ELSE
	SET @SQL = @SQL + ' 
				CASE
					WHEN B.ATypeId=''0000100005'' AND A.RedWord = 0 THEN ISNULL(B.Total,0)
					WHEN B.ATypeId=''0000100005'' AND A.RedWord = 1 THEN ISNULL(ABS(B.Total),0)
					WHEN B.ATypeId=''0000200001'' AND A.RedWord = 2 THEN ISNULL(ABS(B.Total),0)
					ELSE 0
				END AS ArReduce,
				CASE 
					WHEN B.ATypeId=''0000200001'' AND A.RedWord = 0 THEN ISNULL(B.Total,0)
					WHEN B.ATypeId=''0000200001'' AND A.RedWord = 1 THEN ISNULL(ABS(B.Total),0)					
					WHEN B.ATypeId=''0000100005'' AND A.RedWord = 2 THEN ISNULL(ABS(B.Total),0)
					ELSE 0
				END AS ArAdd,'

SET @SQL = @SQL + '
				A.BillDate,
				A.BillCode,
				B.BTypeId,
				A.BillNumberId,
				A.BillType,
				A.RedWord
		FROM	BillIndex A,
				ListTable B
		WHERE	A.BillNumberId = B.BillNumberId
				AND B.ATypeId IN (''0000100005'',''0000200001'')
				AND A.BillType = 159
				AND A.IfCheck = ''t''
				AND A.Draft = 0
				AND A.BillDate>='+char(39)+@StartDate+char(39)+'
				AND A.BillDate<='+char(39)+@EndDate+char(39)+'
				AND B.BTypeId = '+char(39)+@BTypeId+char(39)+''  

IF @ntype=1 OR @ntype=3
	SELECT @SQL=@SQL+' ) b WHERE NOT (ISNULL(b.ArAdd,0)=0 and ISNULL(b.ArReduce,0)=0)  '
ELSE
	SELECT @SQL=@SQL+' ) b WHERE NOT (ISNULL(b.ApAdd,0)=0 and ISNULL(b.ApReduce,0)=0)  '


--如果不显示红单，则加上该条件  谢吉康 2004-10-10
IF @showRedWord = 0
	SELECT @SQL = @SQL + ' AND b.RedWord = 0'

IF @Orderby<>''
	SELECT @SQL=@SQL+' ORDER BY '+@Orderby

--PRINT(@SQL)
EXEC(@SQL)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApTotalLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApTotalLine]
GO













/*
	作者：谢吉康
	日期：2010-05-07
	描述：重写应收、应付查询
*/
CREATE  PROCEDURE Web_QueryArApTotalLine
( 
	@OperatorID 	varchar(100) ,   	--操作员id
	@BTypeId   		varchar(100),		--往来单位节点号
	@STypeId		VARCHAR(100),		--分支机构
	@nType			INT,				--1,3  应收  2,4应付
	@UserCode		VARCHAR(200)='',	--编号
	@FullName		VARCHAR(200)='',	--名称
	@showzero		VARCHAR(10)='0' 	--是否显示为0
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId varchar(50), @MBTypeid varchar(50), @MBTypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MDTypeId VARCHAR(50),@MSTypeId VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@BTypeId,2) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailBType(@OperatorID))

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@STypeId,11) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailSType(@OperatorID))

DECLARE @SQL 	varchar(8000),
		@SonNum	INT

IF @BTypeId = '00000' SET @BTypeId = '%'

SET @SQL='SELECT	A.TypeId,
					A.SonNum,
					A.ArApExplain,
					ISNULL(B.ArTotal,0) AS ArTotal,
					ISNULL(B.ApTotal,0) AS ApTotal,
					ISNULL(B.ArTotal,0) - ISNULL(B.ApTotal,0) AS ArApTotal
		  FROM 		F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') a
		  LEFT JOIN (
			SELECT	BTypeId,
					ISNULL(SUM(ArTotal),0) AS ArTotal,
					ISNULL(SUM(ApTotal),0) AS ApTotal
			FROM	BType_ArApTotal
			WHERE	BTypeId IN (SELECT TypeId FROM #GetManBTypeId)
					AND STypeId IN (SELECT TypeId FROM #GetManSTypeId)
			GROUP BY BTypeId
		  )B ON A.TypeId = B.BTypeId
		  WHERE 	a.deleted=0
		  			AND A.SonNum = 0
		  			AND A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
		  			AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
		  			AND A.TypeId LIKE  '+char(39)+@BTypeId+'%'+char(39)
IF @showzero = '0'
	SET @SQL = @SQL + ' AND ISNULL(B.ArTotal,0) - ISNULL(B.ApTotal,0)<>0'
	
SET @SQL = @SQL + ' ORDER BY UserCode'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManBTypeId,#GetManSTypeId








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApTotalList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApTotalList]
GO













/*
	作者：谢吉康
	日期：2010-05-07
	描述：重写应收、应付查询
*/
CREATE  PROCEDURE Web_QueryArApTotalList
( 
	@OperatorID 	varchar(100) ,   --操作员id
	@BTypeId   		varchar(100),	--往来单位节点号
	@STypeId		VARCHAR(100),	--分支机构
	@nType			INT				--1,3  应收  2,4应付
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId varchar(50), @MBTypeid varchar(50), @MBTypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MDTypeId VARCHAR(50),@MSTypeId VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------------------------------------------
--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@BTypeId,2) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailBType(@OperatorID))

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@STypeId,11) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailSType(@OperatorID))

DECLARE @SQL 	varchar(8000),
		@SonNum	INT
		
SELECT @SonNum = SonNum FROM btype WHERE typeId = @BTypeId		

SET @SQL='SELECT	A.TypeId,
					A.SonNum,
					ISNULL(B.ArTotal,0) AS ArTotal,
					ISNULL(B.ApTotal,0) AS ApTotal,
					ISNULL(B.ArTotal,0) - ISNULL(B.ApTotal,0) AS ArApTotal
		  FROM 		F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') a
		  LEFT JOIN (
			SELECT	BTypeId,
					ISNULL(SUM(ArTotal),0) AS ArTotal,
					ISNULL(SUM(ApTotal),0) AS ApTotal
			FROM	BType_ArApTotal
			WHERE	BTypeId IN (SELECT TypeId FROM #GetManBTypeId)
					AND STypeId IN (SELECT TypeId FROM #GetManSTypeId)
			GROUP BY BTypeId
		  )B ON LEFT(B.BTypeId,LEN(A.TypeId)) = A.TypeId
		  WHERE 	a.deleted=0 '
		  
IF @BTypeId = '00001' OR @BTypeId = '00002' OR @BTypeId = '00000'
	SET @SQL = @SQL + ' AND A.ParId =  '+CHAR(39)+@BTypeId+CHAR(39)
ELSE
	IF @SonNum = 0 
		SET @SQL = @SQL + ' AND A.TypeId = '+CHAR(39)+@BTypeId+CHAR(39)
	ELSE
		SET @SQL = @SQL + ' AND A.ParId = '+CHAR(39)+@BTypeId+CHAR(39)
	
SET @SQL = @SQL + 'ORDER BY UserCode'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManBTypeId,#GetManSTypeId








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApWldz_Gsqh_GYS_YH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApWldz_Gsqh_GYS_YH]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

























/*
	作者：谢吉康
	日期：2008-03-26
	描述：往来对账（格式切换），应付查询（不统一客户和供货商）
*/
CREATE PROCEDURE Web_QueryArApWldz_Gsqh_GYS_YH
(
	@OperatorID 	VARCHAR(100),  	   			--操作员ID号
	@nType        	INT=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@BTypeId      	VARCHAR(100),               	--往来单位typeid
	@szEtypeIds     VARCHAR(5000),   			--经手人etypeid
	@StartDate   	VARCHAR(10),               	--起始日期
	@EndDate    	VARCHAR(10),               	--截至日期
	@Orderby      	VARCHAR(50)='',           	--排序字段
	@showRedWord	int=1						--是否显示红冲单据  1.显示   0.不显示	
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SELECT	TypeId,FullName INTO #PType FROM F_GetManPTypeAll(@OperatorID) WHERE Deleted = 0 AND SonNum = 0 AND TypeId IN (SELECT * FROM F_GetManDetailPType(@OperatorID))

--『会员储值』
--SELECT	TypeId,FullName INTO #AType FROM F_GetManATypeAll(@OperatorID) WHERE Deleted = 0 AND SonNum = 0
--INSERT INTO #AType(TypeId,FullName)VALUES('0000200005','『会员储值』')
SELECT	TypeId,FullName INTO #AType FROM AType WHERE Deleted = 0 AND SonNum = 0

SELECT	TypeId,FullName INTO #BType FROM F_GetManBTypeAll(@OperatorID) WHERE TypeId = @BTypeId AND Deleted = 0 AND SonNum = 0 AND TypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))

CREATE TABLE #BillIndex
(
	BillCode		varchar(400),
	BillNumberId	numeric(18,0),
	BillDate		datetime,
	etypeid			varchar(100),
	btypeid			varchar(100),
	BillType		varchar(20),
	Total			 NUMERIC(24, 10) , 
  	totalinmoney	 NUMERIC(24, 10) , 
	Comment			varchar(2000),
	atypeid			varchar(100),
	TeamNo			varchar(20),
	RedWord			varchar(20),
	preferencemoney	 NUMERIC(24, 10) 
)

--处理主表信息
INSERT INTO #BillIndex
SELECT 	DISTINCT
		BillCode,
		BillNumberId,
		BillDate,
		etypeid,
		btypeid,
		BillType,
		totalmoney AS Total, 
      	totalinmoney, 
		Comment,
		atypeid,
		TeamNo,
		RedWord,
		preferencemoney
FROM 	BillIndex		
WHERE 	BillType IN (305,11,45,34,6,36,93,4,66,160,161,141,145,84,85,148,149,150,151,157,167,168,170,172,178,186)
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND ifcheck = 't' 
		AND draft = 0
		AND BTypeId = @BTypeId
		AND IfYearBill = 0

INSERT INTO #BillIndex
SELECT 	DISTINCT
		Bil.BillCode,
		Bil.BillNumberId,
		Bil.BillDate,
		Bil.etypeid,
		Bil.btypeid,
		Bil.BillType,
		Bil.totalmoney AS Total, 
      	Bil.totalinmoney, 
		Bil.Comment,
		Bil.atypeid,
		Bil.TeamNo,
		Bil.RedWord,
		preferencemoney
FROM 	BillIndex Bil,
		AdDebtBill A
WHERE	BillType IN (115,116,128,129)	
		AND Bil.BillNumberId = A.BillNumberId		
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND A.BTypeId = @BTypeId
		AND IfCheck = 't'
		AND Draft = 0
		AND Bil.IfYearBill = 0

--特殊处理会计凭证
INSERT INTO #BillIndex
SELECT	DISTINCT
		A.BillCode,
		A.BillNumberId,
		A.BillDate,
		A.ETypeid,
		L.BTypeid,
		A.BillType,
		CASE A.RedWord 
			WHEN 0 THEN L.Total
			ELSE ABS(L.Total)
		END AS Total,
      	0 AS totalinmoney, 
		A.Comment,
		L.ATypeid,
		A.TeamNo,
		A.RedWord,
		A.preferencemoney
FROM	BillIndex A,
		ListTable L
WHERE	A.BillNumberId = L.BillNumberId
		AND A.BillType = 159
		AND A.IfCheck = 't'
		AND A.Draft = 0
		AND L.ATypeId IN ('0000100005','0000200001')
		AND L.BTypeId = @BTypeId
		AND A.BillDate>=@StartDate
		AND A.BillDate<=@EndDate		
		AND A.IfCheck = 't'
		AND A.Draft = 0

--开始运算
SELECT	B.*
INTO	#Result
FROM	(
			SELECT	ZY='销售:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
      				FullName=P.FullName, 
      				ApAdd=CASE WHEN Bil.RedWord = 2 THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      				ApReduce=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
      				Bil.BillDate,
      				Bil.BillCode,
					Bil.etypeid,
      				S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	SaleBill S,
      				#BillIndex Bil,
      				#PType P
			WHERE 	Bil.BillType = 11
					AND Bil.BillNumberId = S.BillNumberId
					AND P.TypeId = S.PTypeId
			UNION ALL
			SELECT 	ZY='收款:'+A.FullName,
      				FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid,
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
	      			#BillIndex Bil
			WHERE 	Bil.BillType = 11 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY=	'优惠金额:',
					FullName=' ',
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					Bil.TeamNo,
					ID = -1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=' ',
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 11
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY='进货:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
					P.FullName, 
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.TaxTotal ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord=2 THEN  S.TaxTotal ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	BuyBill S,
      				#BillIndex Bil,
      				#PType P
			WHERE 	Bil.BillType = 34
					AND Bil.BillNumberId = S.BillNumberId
					AND P.TypeId = S.PTypeID
			UNION ALL
			SELECT 	ZY='优惠金额:',
					FullName=' ',
					ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=' ',
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 34
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
      				FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
      				#BillIndex Bil
			WHERE 	Bil.BillType = 34 
					AND Bil.ATypeId = A.TypeID
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT  ZY='退货:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(10)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
					P.FullName,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN S.TaxTotal ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.TaxTotal ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
     				BuyBackBill S,
     				#PType P
			WHERE 	Bil.BillType = 6
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeID
			UNION ALL
			SELECT 	ZY='优惠金额:',
					FullName=' ',
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=' ',
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil	
			WHERE 	Bil.BillType = 6
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY='收款:'+A.FullName,
					FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.totalinmoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord =2 THEN  Bil.totalinmoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid,
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
					#BillIndex Bil
			WHERE 	Bil.BillType = 6 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='零售:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
					P.FullName, 
					ApAdd=CASE WHEN Bil.RedWord=2 THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
					Bil.BillDate,
					Bil.BillCode,Bil.etypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	RetailBill S,
      				#BillIndex Bil,
      				#PType P
			WHERE 	Bil.BillType = 305
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeID
			UNION ALL
			SELECT 	ZY='优惠金额:',
					FullName=' ',
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=' ',
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil 
			WHERE 	Bil.BillType = 305
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY='收款:'+A.FullName,
					FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid,
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
      				#BillIndex Bil
			WHERE 	Bil.BillType = 305 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='收款:' + B.FullName,
					B.FullName,  
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
      				gatheringBill S,
      				#BType B
			WHERE 	Bil.BillType = 4
					AND Bil.BillNumberId = S.BillNumberID
					AND Bil.BTypeId = B.TypeID
			UNION ALL
			SELECT  ZY='优惠金额:',
					FullName=' ',
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,	
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=' ',
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil 
			WHERE 	Bil.BillType = 4
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT  ZY='退货:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(10)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
      				P.FullName,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.TaxTotal ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord=2 THEN S.TaxTotal ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
     				saleBackBill S,
    				#PType P
			WHERE 	Bil.BillType = 45
					AND Bil.BillNumberID = S.BillNumberId
					AND S.PTypeId = P.TypeID
			UNION ALL
			SELECT	ZY='优惠金额:',
					FullName=' ',
					ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=' ',
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 45
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
					FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord=2  THEN Bil.totalinmoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1)  THEN Bil.totalinmoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
      				#BillIndex Bil
			WHERE 	Bil.BillType = 45 
					AND Bil.ATypeId = A.TypeID
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='付款:' + B.FullName,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
      				#BType B,
      				PayBill S
			WHERE 	Bil.BillType = 66
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeId = Bil.BTypeID
			UNION ALL
			SELECT	ZY='优惠金额:',
					FullName=' ',
					ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=' ',
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil 
			WHERE 	Bil.BillType = 66
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY='返利执行:' + B.FullName,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,       
					ApReduce=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,       
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
      				#BType B,
		      		Advantage S
			WHERE 	Bil.BillType = 148
					AND Bil.BillNumberId = S.BillNumberId
					AND Bil.BTypeId = B.TypeID
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
			      	FullName=NULL,
			    	ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
			     	ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,

					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType = 148 
					AND A.TypeId = Bil.ATypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='价保执行:' + B.FullName,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,       
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
      				#BType B,
      				PriceProtectBill S
			WHERE 	Bil.BillType = 149	
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeId = Bil.BTypeID
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
			      	FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType = 149 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='获得价保:' + B.FullName,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
			      	#BType B,
			      	PriceProtectBill S
			WHERE 	Bil.BillType = 151
					AND Bil.BillNumberId = S.BillNumberID
					AND Bil.BTypeId = B.TypeID
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
					FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END,  
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
      				#BillIndex Bil
			WHERE 	Bil.BillType = 151 
					AND Bil.ATypeId = A.TypeID
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='委托代销结算:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN S.TaxTotal ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.TaxTotal ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
				    #BType B,
				    CommissionBill S,
					#PType P
			WHERE 	Bil.BillType = 141
					AND Bil.BTypeId = B.TypeId
					AND S.BillNumberId = Bil.BillNumberId
					AND P.TypeId = S.PTypeId
			UNION ALL
			SELECT 	ZY='收款:'+A.FullName,
			      	FullName=NULL,
			     	ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
				 	ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType = 141 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='受托代销结算:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.TaxTotal ELSE NULL END,       
					ApReduce=CASE WHEN Bil.RedWord =2 THEN S.TaxTotal ELSE NULL END,       
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
			      	#BType B,
			      	CommissionBill S,
					#PType P
			WHERE 	Bil.BillType = 145
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeID = Bil.BTypeID
					AND P.TypeId = S.PTypeId
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
      				FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
		      		#BillIndex Bil
			WHERE 	Bil.BillType = 145 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='获利执行:' + B.FullName,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
      				#BType B,
      				Advantage S
			WHERE 	Bil.BillType = 150
					AND Bil.BTypeId = B.TypeID
					AND Bil.BillNumberId = S.BillNumberID
			UNION ALL
			SELECT 	ZY='收款:'+A.FullName,
					FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,					
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
      				#BillIndex Bil
			WHERE 	Bil.BillType = 150 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY=S.Comment,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					S.BtypeId,  
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
			      	AdDebtBill S,
					#BType B
			WHERE 	Bil.BillType IN(115,128)
					AND B.TypeId = S.BTypeID
					AND Bil.BillNumberId = S.BillNumberId
			UNION ALL
			SELECT 	ZY=S.Comment,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord=2 THEN S.total ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					S.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
			      	AdDebtBill S,

			      	#BType B
			WHERE 	Bil.BillType IN(116,129)
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeId = S.BTypeID
			UNION ALL
			SELECT	ZY='费用:'+S.Comment, 
					A.FullName, 
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord=2 THEN S.total ELSE NULL END,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,       
					S.TeamNo, 
					S.ID, 
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType, 
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	MoneyBill S,
			      	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType =36
					AND Bil.BillNumberId = S.BillNumberId
					AND S.ATypeId = A.TypeId
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
			     	FullName=NULL,
			     	ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
			     	ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType = 36 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY=S.Comment, 
					A.FullName, 
					ApAdd=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo,
					S.ID,
					Bil.btypeid, 
					Bil.BillNumberId,
					Bil.BillType, 
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	MoneyBill S,
      				#AType A,
      				#BillIndex Bil
			WHERE 	Bil.BillType =93	
					AND Bil.BillNumberId = S.BillNumberId
					AND S.ATypeId = A.TypeID
			UNION ALL
			SELECT	ZY='收款:'+A.FullName,
			     	FullName=NULL,
			     	ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END,
			     	ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType = 93 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='固定资产购买:' + B.FullName,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
			      	#BType B,
			      	MoneyBill S
			WHERE 	Bil.BillType = 84
					AND S.BillNumberId = Bil.BillNumberId
					AND Bil.BTypeId = B.TypeID
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
			      	FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType = 84 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT 	ZY='固定资产变卖:' + B.FullName,
					B.FullName,
					ApAdd=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
      				#BType B,
				    MoneyBill S    
			WHERE 	Bil.BillType = 85
					AND Bil.BTypeId = B.TypeId
					AND Bil.BillNumberId = S.BillNumberId
			UNION ALL	
			SELECT 	ZY='收款:'+A.FullName,
					FullName=NULL,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
					ApReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid,
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
					#BillIndex Bil
			WHERE 	Bil.BillType = 85 
					AND Bil.ATypeId = A.TypeId
					AND Bil.atypeid<>'' 
					AND Bil.totalinmoney<>0
			UNION ALL
			SELECT	ZY='商品维修单:' + B.FullName,
					B.FullName,
					ApAdd=case when Bil.RedWord =2 then Bil.total else null end,
					ApReduce=case when Bil.RedWord in(0,1) then Bil.total else null end,
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo, 
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=null,
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil,
			      	#BType B
			WHERE 	Bil.BillType = 157
					AND Bil.BTypeId = B.TypeID
			UNION ALL
			SELECT 	ZY='付款:'+A.FullName,
					FullName=null,      
					ApAdd=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end,  
					ApReduce=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid,
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=null,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
      				#BillIndex Bil
			WHERE 	Bil.BillType = 157 
					AND Bil.ATypeId = A.TypeID
					and Bil.atypeid<>'' 
					and Bil.totalinmoney<>0
			UNION ALL
			SELECT	ZY='应收:'+B.FullName,
					FullName=NULL,
					ApAdd=CASE WHEN V.RedWord IN (0,1) THEN ABS(V.Total) ELSE NULL END,
					ApReduce=CASE WHEN V.RedWord = 2      THEN ABS(V.Total) ELSE NULL END,
					V.BillDate,
					V.BillCode,
					V.ETypeId,
					V.TeamNo,
					ID=-1,
					V.BTypeId,
					V.BillNumberId,
					V.BillType,
					TeamNo1=NULL,
					V.RedWord,
					V.Comment 
			FROM	#BillIndex V,
					#BType B
			WHERE	V.BTypeId = B.TypeId
					AND V.BillType = 159
					AND V.ATypeId = '0000100005'
			UNION ALL
			SELECT	ZY='应付:'+B.FullName,		
					FullName=NULL,		
					ApAdd=CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,
					ApReduce=CASE WHEN V.RedWord = 2      THEN ABS(V.Total) ELSE NULL END,
					V.BillDate,
					V.BillCode,
					V.ETypeId,
					V.TeamNo,
					ID=-1,
					V.BTypeId,
					V.BillNumberId,
					V.BillType,
					TeamNo1=NULL,
					V.RedWord,
					V.Comment 
			FROM	#BillIndex V,
					#BType B
			WHERE	V.BTypeId = B.TypeId
					AND V.BillType = 159
					AND V.ATypeId = '0000200001'
			UNION ALL
			SELECT	ZY=
				 		Case S.InOrOut
							when 'O' then
					     		'采购换货出库:' + P.FullName + ' ' + cast(cast(S.Qty as float) as varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20))
							when 'I' then
					     		'采购换货入库:' + P.FullName + ' ' + cast(cast(S.Qty as float) as varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20))
				  	end,			
			      	P.FullName, 
					ApAdd=
					  case S.InOrOut
				          when 'O' then case when Bil.RedWord=2 then cast(cast(S.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
				          when 'I' then case when Bil.RedWord in(0,1) then cast(cast(S.TaxTotal as float) as  NUMERIC(24, 10) ) else null end					
				      end,
					ApReduce=	
						case S.InOrOut
							when 'O' then case when Bil.RedWord in(0,1) then cast(cast(S.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
							when 'I' then case when Bil.RedWord=2 then cast(cast(S.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
			      		end,			      
					Bil.BillDate,
					Bil.BillCode,Bil.etypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment
			FROM 	BuyGoodsExchangeBill S,
			      	#BillIndex Bil,
			      	#PType P
			WHERE 	Bil.BillType = 161
					AND Bil.BillNumberId = S.BillNumberId

					AND P.TypeId = S.PTypeId
			UNION ALL
			SELECT '付款:'+A.FullName,
					FullName=null,     
					ApAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
					ApReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
					Bil.BillDate, 
					Bil.BillCode,Bil.etypeid, 
					Bil.TeamNo,
					ID=-1,
					Bil.btypeid,
					Bil.BillNumberId, 
					Bil.BillType,
					TeamNo1=null,
					Bil.RedWord,
					Bil.Comment
			FROM 	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType = 161 
					AND A.TypeId = Bil.ATypeId
					and Bil.atypeid<>'' 
					and Bil.totalinmoney<>0
			UNION ALL
			SELECT	ZY='优惠金额:',
					FullName=' ',
					ApAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=' ',
					Bil.RedWord,
					Bil.Comment
			FROM 	#BillIndex Bil 
			WHERE 	Bil.BillType = 161
					AND Bil.preferencemoney<>0
			UNION ALL
		SELECT 	ZY='维修取件:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)), 
				P.FullName,       
				ArAdd=case when Bil.RedWord=2 then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord in(0,1) then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid,
				null AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	Wx_Bill_GetBack S,
		      	#BillIndex Bil, 
		      	#PType P
		WHERE 	Bil.BillType = 167
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord =2  THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 167
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 		
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 167 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL
		SELECT 	ZY='整机更换:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)), 
				P.FullName,       
				ArAdd=case when Bil.RedWord=2 then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord in(0,1) then cast(S.Total as  NUMERIC(24, 10) ) else null end,

				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid,
				null AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	Wx_Bill_Replace S,
		      	#BillIndex Bil, 
		      	#PType P
		WHERE 	Bil.BillType = 168
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 168
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 		
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 168 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL
		SELECT 	ZY='送修返回:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)), 
				P.FullName,       
				ArAdd=case when Bil.RedWord in(0,1) then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord=2 then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid,
				null AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	Wx_Bill_SendBack S,
		      	#BillIndex Bil, 
		      	#PType P
		WHERE 	Bil.BillType = 170
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 170
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 		
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 170 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL		
		SELECT 	ZY='上门维修单:' + B.FullName,
				B.FullName,
				ArAdd=case when Bil.RedWord =2 then Bil.total else null end,
				ArReduce=case when Bil.RedWord in(0,1) then Bil.total else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo, 
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM  	#BillIndex Bil,
		      	#BType B
		WHERE 	Bil.BillType = 172
				AND Bil.BTypeId = B.TypeId
		UNION ALL
		SELECT	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 172 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>''
				AND Bil.totalinmoney<>0		
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord =2 THEN  Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 172	
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT	ZY='维修:'+P.FullName + ' ' + CAST(CAST(S.DiscountTotal AS  NUMERIC(24, 10) ) AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord = 2 then cast(S.DiscountTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord IN (0,1) then cast(S.DiscountTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode,
				Bil.etypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	QP_QuickRepairBill_RepairItems S,
		      	#BillIndex Bil,
		      	Qp_RepairItems P
		WHERE 	Bil.BillType = 178
				AND Bil.BillNumberId = S.BillNumberId
				AND S.RepairItemsTypeId = P.TypeId
				AND S.Insurance = 0			
		UNION ALL
		SELECT	ZY='维修:'+P.FullName + ' ' + cast(cast(S.Qty as float) as varchar(20)) + '*' + CAST(S.DiscountPrice AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord = 2 then cast(S.DiscountTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord IN (0,1) then cast(S.DiscountTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode,
				Bil.etypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	QP_QuickRepairBill_PType S,
		      	#BillIndex Bil,
		      	#PType P
		WHERE 	Bil.BillType = 178
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
				AND S.Insurance = 0
		UNION ALL
		SELECT	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord IN (0,1) then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord = 2 then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 178 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>''
				AND Bil.totalinmoney<>0		
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN (0,1) THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord = 2 THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 178	
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT	ZY='外加工费:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN (2) THEN CAST(Bc.EpibolyTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(Bc.EpibolyTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	BillIndex_CarRepair Bc,
				#BillIndex Bil
		WHERE 	Bc.BillNumberId = Bil.BillNumberId
				AND Bil.BillType = 178	
				AND ISNULL(Bc.EpibolyTotal,0) <> 0
		UNION ALL
		SELECT	ZY='其他费用:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN (2) THEN CAST(Bc.OtherTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(Bc.OtherTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	BillIndex_CarRepair Bc,
				#BillIndex Bil
		WHERE 	Bc.BillNumberId = Bil.BillNumberId
				AND Bil.BillType = 178
				AND ISNULL(Bc.OtherTotal,0) <> 0	
		UNION ALL
		SELECT	ZY='工时费税额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN (2) THEN CAST(ISNULL(Bc.ManHourTaxTotal,0) - ISNULL(Bc.ManHourTotal,0) AS  NUMERIC(24, 10) ) ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(ISNULL(Bc.ManHourTaxTotal,0) - ISNULL(Bc.ManHourTotal,0) AS  NUMERIC(24, 10) ) ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	BillIndex_CarRepair Bc,
				#BillIndex Bil
		WHERE 	Bc.BillNumberId = Bil.BillNumberId
				AND Bil.BillType = 178
				AND ISNULL(Bc.ManHourTaxTotal,0) - ISNULL(Bc.ManHourTotal,0) <> 0	
		UNION ALL
		SELECT	ZY='材料费税额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord = 2 THEN CAST(ISNULL(Bc.PTypeTaxTotal,0) - ISNULL(Bc.PTypeTotal,0) AS  NUMERIC(24, 10) ) ELSE 0 END,
				ArReduce=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(ISNULL(Bc.PTypeTaxTotal,0) - ISNULL(Bc.PTypeTotal,0) AS  NUMERIC(24, 10) ) ELSE 0 END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	BillIndex_CarRepair Bc,
				#BillIndex Bil
		WHERE 	Bc.BillNumberId = Bil.BillNumberId
				AND Bil.BillType = 178
				AND ISNULL(Bc.PTypeTaxTotal,0) - ISNULL(Bc.PTypeTotal,0) <> 0	
		UNION ALL
		SELECT	ZY='理赔:'+P.FullName + ' ' + CAST(CAST(S.InsuranceTotal AS  NUMERIC(24, 10) ) AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord = 2 then cast(S.InsuranceTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord IN (0,1) then cast(S.InsuranceTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode,
				Bil.etypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	QP_InsuranceBill_RepairItems S,
		      	#BillIndex Bil,
		      	Qp_RepairItems P
		WHERE 	Bil.BillType = 186
				AND Bil.BillNumberId = S.BillNumberId
				AND S.RepairItemsTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='理赔:'+P.FullName + ' ' + CAST(CAST(S.InsuranceTotal AS  NUMERIC(24, 10) ) AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord = 2 then cast(S.InsuranceTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord IN (0,1) then cast(S.InsuranceTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode, 
				Bil.etypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	QP_InsuranceBill_PType S,
		      	#BillIndex Bil,
		      	#PType P
		WHERE 	Bil.BillType = 186
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
)B

DECLARE @SQL varchar(8000)

SET @SQL = 'SELECT * FROM #Result'

IF @showRedWord = 0
	SET @SQL = @SQL + ' WHERE RedWord = 0 '

--排序字段的处理
/*
IF @Orderby=''
	SET @SQL=@SQL+'  ORDER BY billdate,billtype,billcode '
ELSE IF UPPER(@Orderby)='TEAMNO'
	SET @SQL=@SQL+'  ORDER BY ISNULL(TEAMNO,999999999),BillDate,BillType,BillCode '
ELSE IF UPPER(@Orderby)='BILLDATE'
	SET @SQL=@SQL+'  ORDER BY BillDate DESC,BillType,BillCode '
ELSE
	SET @SQL=@SQL+'  ORDER BY '+@Orderby
*/
IF @Orderby=''
	SET @SQL=@SQL+'  ORDER BY billdate,billnumberid,billtype,id'
ELSE
	SET @SQL=@SQL+'  ORDER BY '+@Orderby

EXEC(@SQL)


DROP TABLE #BillIndex,#PType,#AType,#BType,#Result



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApWldz_Gsqh_GYS_YH_TY]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApWldz_Gsqh_GYS_YH_TY]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*
	作者：谢吉康
	日期：2008-03-26
	描述：往来对账（格式切换），应付查询（统一客户和供货商）

*/
CREATE PROCEDURE Web_QueryArApWldz_Gsqh_GYS_YH_TY
(
	@OperatorID 	VARCHAR(100),  	    		--操作员ID号
	@nTYpe        	INT=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@BtypeID      	VARCHAR(100),               	--往来单位typeid
	@StartDate   	VARCHAR(10),                --起始日期
	@EndDate    	VARCHAR(10),                --截至日期
	@showRedWord	INT=1,						--是否显示红冲单据  1.显示   0.不显示
	@stypeid		VARCHAR(MAX),
	@IncludePre		INT=0,
	@orderby		VARCHAR(100),
	@CID            VARCHAR(5)='0',              --币别筛选，0表示所有币种
	@expensetoar    INT=0,
	@dtypeid		VARCHAR(MAX),	--部门
	@DtypeIsVisible	BIT			--1=使用部门 0=不使用部门
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SELECT	TypeId,FullName INTO #PType FROM ptype WHERE  SonNum = 0

--『会员储值』
--SELECT	TypeId,FullName INTO #AType FROM F_GetManATypeAll(@OperatorID) WHERE Deleted = 0 AND SonNum = 0
--INSERT INTO #AType(TypeId,FullName)VALUES('0000200005','『会员储值』')
SELECT nid AS TypeId,FullName,UserCode INTO #AType FROM AC_Items WHERE  SonNum = 0


SELECT	TypeId,FullName INTO #BType FROM F_GetManBTypeAll(@OperatorID) WHERE TypeId = @BTypeId  AND SonNum = 0 AND TypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
declare @sql VARCHAR(MAX)

		
create table #stype(typeid VARCHAR(100))

--分支机构
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaSETypeId(@stypeid,11,@OperatorID)

--部门
CREATE TABLE #Dtype(typeid VARCHAR(50))
--IF @DtypeIsVisible = 1 AND @dtypeid <> ''
INSERT #Dtype(typeid) SELECT TypeId FROM F_GetAllBaseTypeId(@dtypeid,9)


create table #atype1(typeid VARCHAR(50))
insert into #atype1 values('2121')  

if @IncludePre=1
begin
	insert into #atype1 values('1151')
END

IF @CID='0'
  BEGIN
       SET @CID='%'
  END

--统计开票
CREATE TABLE #invoiceQty
(
	id	INT,
	ptypeid VARCHAR(50),
	billnumberid NUMERIC(24,10),
	billtype INT,
	uninvoiceqty NUMERIC(24,10),
	uninvoicemoney NUMERIC(24,10),
	nuninvoicemoney NUMERIC(24,10) --原币
)
INSERT INTO #invoiceQty
(
	id,
	ptypeid,
	billnumberid,
	billtype,
	uninvoiceqty,
	uninvoicemoney,
	nuninvoicemoney
) 
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
		400,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM AppraisalBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    401,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
		
FROM AppraisalBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    402,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM SendBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    403,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM SendBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	

UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    305,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM retailbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    215,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM RetailBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    11,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM salebill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    45,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM salebackbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM salegoodsexchangebill a
WHERE a.InOrOut='I'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM salegoodsexchangebill a
WHERE a.InOrOut='O'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    141,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM commissionbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    12,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM PT_Combin_SaleBillDetail a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    46,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM PT_Combin_SaleBackBillDetail a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    34,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM buybill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id		
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    6,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM buybackbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM buygoodsexchangebill a
WHERE A.InOrOut='O'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM buygoodsexchangebill a
WHERE A.InOrOut='I'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    145,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM commissionbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
CREATE TABLE #BillIndex
(
	BillCode		 VARCHAR(400),
	BillNumberId	 NUMERIC(18,0),
	BillDate		 DATETIME,
	etypeid			 VARCHAR(100),
	dtypeid			 VARCHAR(100),
	ktypeid			 VARCHAR(100),
	btypeid			 VARCHAR(100),
	BillType		 VARCHAR(20),
	Total			  NUMERIC(24, 10) ,
	NTotal            NUMERIC(24, 10) , 
  	totalinmoney	  NUMERIC(24, 10) ,
  	ntotalinmoney     NUMERIC(24, 10) , 
	Comment			 VARCHAR(2000),
	atypeid			 VARCHAR(100),
	TeamNo			 INT,
	RedWord			 VARCHAR(20),
	preferencemoney	  NUMERIC(24, 10) ,
	npreferencemoney  NUMERIC(24, 10) ,
	cfullname           VARCHAR(100),
	rate                 NUMERIC(24, 10),
	
	explain          VARCHAR(2000),--说明 
	CID					INT 
)
CREATE TABLE #result
(
    sortid          INT IDENTITY (1,1),
	zy				VARCHAR(400),
	ptypeid			VARCHAR(200),
	qty				 NUMERIC(24, 10) ,
	taxprice		 NUMERIC(24, 10) ,
	ntaxprice		 NUMERIC(24, 10) ,
	incomment		VARCHAR(2000),
	apadd			 NUMERIC(24, 10) ,
	napadd			 NUMERIC(24, 10) ,
	ApReduce		 NUMERIC(24, 10) ,
	NApReduce		 NUMERIC(24, 10) ,
	BillDate		datetime,
	BillCode		VARCHAR(400),
	etypeid			VARCHAR(100),
	dtypeid			VARCHAR(100),
	ktypeid			VARCHAR(100),
	TeamNo			INT,
	id				INT,
	btypeid			VARCHAR(100),
	BillNumberId	NUMERIC(18,0),
	BillType		VARCHAR(20),
	TeamNo1			VARCHAR(20),
	RedWord			VARCHAR(20),
	Comment			VARCHAR(2000),
	cfullname           VARCHAR(100),
	rate                 NUMERIC(24, 10) ,
	atypeid             INT,
	goodsnumber			varchar(100),
	
	remark           VARCHAR(2000),--备注
	unit             INT ,--计量单位
	MQty             NUMERIC(24, 10) ,--数量
	MTaxPrice            NUMERIC(24, 10) ,--含税单价
	conversionrelationship VARCHAR(200),--换算关系
	customassistantunit VARCHAR(200), --自定义辅助数量
	BillFlag		INT DEFAULT(0)-- 1:ReceiptBillIndex else 0
)

DECLARE @assets VARCHAR(2)
SELECT @assets= SubValue FROM sysdata WHERE SubNo=732--固定资产管理模式。0：项目；1：卡片

--处理主表信息
INSERT INTO #BillIndex
SELECT 	DISTINCT
		BillCode,
		BillNumberId,
		BillDate,
		etypeid,
		DTypeId,
		ktypeid,
		btypeid,
		BillType,
		totalmoney AS Total,
		ntotalMoney AS NTotal, 
      	totalinmoney,
      	ntotalinmoney, 
		Comment,
		atypeid,
		TeamNo,
		RedWord,
		preferencemoney,
		npreferencemoney,
		AC.fullname AS cfullname,
		BillIndex.rate,
		explain,
		BillIndex.CID
FROM 	BillIndex
		INNER JOIN #stype s ON s.typeid=BillIndex.Stypeid
		INNER JOIN #Dtype D ON D.typeid = BillIndex.DTypeId
		INNER JOIN AC_Currency AC ON BillIndex.CID=AC.CID		
WHERE 	BillType IN (34,6,161,145,84,170,150,151)
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND ifcheck = 't' 
		AND draft = 0
		AND BTypeId = @BTypeId
		AND IfYearBill = 0
		AND BillIndex.CID LIKE @CID 
UNION ALL
SELECT 	DISTINCT
		BillCode,
		BillNumberId,
		BillDate,
		etypeid,
		DTypeId,
		cb.InKTypeId,
		btypeid,
		BillType,
		totalmoney AS Total,
		ntotalMoney AS NTotal, 
      	totalinmoney,
      	ntotalinmoney, 
		Comment,
		atypeid,
		'' as TeamNo,
		RedWord,
		preferencemoney,
		npreferencemoney,
		AC.fullname AS cfullname,
		cb.rate,
		cb.Explain,
		cb.CID
FROM 	dbo.Coupon_BillIndex cb
		INNER JOIN #stype s ON s.typeid=cb.Stypeid
		INNER JOIN #Dtype D ON D.typeid = cb.DTypeId
		INNER JOIN AC_Currency AC ON cb.CID=AC.CID		
WHERE 	BillType IN (423)
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND ifcheck = 't' 
		AND draft = 0
		AND BTypeId = @BTypeId
		AND IfYearBill = 0
		AND cb.Cid LIKE @CID 
		IF @assets=1
BEGIN
INSERT INTO #BillIndex
SELECT 	DISTINCT
		BillCode,
		BillNumberId,
		BillDate,
		etypeid,
		DTypeId,
		ktypeid,
		btypeid,
		BillType,
		totalmoney AS Total,
		ntotalMoney AS NTotal, 
      	totalinmoney,
      	ntotalinmoney, 
		Comment,
		atypeid,
		TeamNo,
		RedWord,
		preferencemoney,
		npreferencemoney,
		AC.fullname AS cfullname,
		BillIndex.rate,
		explain,
		BillIndex.CID
FROM 	BillIndex
		INNER JOIN #stype s ON s.typeid=BillIndex.Stypeid
		INNER JOIN #Dtype D ON D.typeid = BillIndex.DTypeId
		INNER JOIN AC_Currency AC ON BillIndex.CID=AC.CID		
WHERE 	BillType=212
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND ifcheck = 't' 
		AND draft = 0
		AND BTypeId = @BTypeId
		AND IfYearBill = 0
		AND BillIndex.CID LIKE @CID 
		AND AssetBusinessTypeId IN(SELECT Id FROM  Ac_AssetBusinessType WHERE FullName='购入（原值含税）' OR FullName='购入（原值不含税）')
END

--特殊处理费用单
INSERT INTO #BillIndex
SELECT 	DISTINCT
		BillCode,
		BillNumberId,
		BillDate,
		etypeid,
		DTypeId,
		ktypeid,
		btypeid,
		BillType,
		totalmoney AS Total,
		ntotalMoney AS NTotal, 
      	totalinmoney,
      	ntotalinmoney, 
		Comment,
		atypeid,
		TeamNo,
		RedWord,
		preferencemoney,
		npreferencemoney,
		AC.fullname AS cfullname,
		BillIndex.rate,
		explain,
		BillIndex.CID
FROM 	BillIndex
		INNER JOIN #stype s ON s.typeid=BillIndex.Stypeid
		INNER JOIN #Dtype D ON D.typeid = BillIndex.DTypeId
		INNER JOIN AC_Currency AC ON BillIndex.CID=AC.CID		
WHERE 	BillType = 36
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND ifcheck = 't' 
		AND draft = 0
		AND BTypeId = @BTypeId
		AND (((BTypeId LIKE '00002%' AND @expensetoar=1) OR @expensetoar=0) OR
				(btypeid LIKE '00001%' AND @IncludePre=1 AND @expensetoar=1))--特殊处理费用单，在往来单位是客户，勾选配置“客户计应收”并且保护预付需要统计预付账款
		AND IfYearBill = 0
		AND BillIndex.CID LIKE @CID


INSERT INTO #BillIndex			
SELECT 	DISTINCT
		Bil.BillCode,
		Bil.BillNumberId,
		Bil.BillDate,
		Bil.etypeid,
		bil.DTypeId,
		bil.ktypeid,
		Bil.btypeid,
		Bil.BillType,
		Bil.totalmoney AS Total,
		Bil.ntotalmoney AS NTotal, 
      	Bil.totalinmoney,
      	Bil.ntotalinmoney,
		Bil.Comment,
		Bil.atypeid,
		Bil.TeamNo,
		Bil.RedWord,
		preferencemoney,
		npreferencemoney,
		AC.fullname AS cfullname,
		AC.rate,
		Bil.explain,
		Bil.CID
FROM 	BillIndex Bil
		INNER JOIN PreBill p ON Bil.BillNumberId=p.BillNumberId
		INNER JOIN #stype s ON Bil.Stypeid=s.typeid
		INNER JOIN #Dtype D ON D.typeid = Bil.DTypeId
		INNER JOIN AC_Currency AC ON Bil.CID=AC.CID 
WHERE	bil.BillType=190			
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND Bil.BTypeId = @BTypeId
		AND IfCheck = 't'
		AND Draft = 0
		AND Bil.IfYearBill = 0
		AND Bil.CID LIKE @CID

INSERT INTO #BillIndex
SELECT DISTINCT
		Bil.BillCode,
		Bil.BillNumberId,
		Bil.BillDate,
		Bil.etypeid,
		bil.DTypeId,
		bil.ktypeid,
		Bil.btypeid,
		Bil.BillType,
		Bil.totalmoney AS Total,
		Bil.ntotalmoney AS NTotal, 
      	Bil.totalinmoney,
      	Bil.ntotalinmoney, 
		Bil.Comment,
		Bil.atypeid,
		Bil.TeamNo,
		Bil.RedWord,
		preferencemoney,
		npreferencemoney,
		AC.fullname AS cfullname,
		Bil.rate,
		Bil.explain,
		Bil.CID
FROM 	BillIndex Bil
		INNER JOIN AdDebtBill A ON Bil.BillNumberId=A.BillNumberId
		INNER JOIN #stype s ON Bil.stypeid=s.typeid
		INNER JOIN #Dtype D ON D.typeid = Bil.DTypeId
		INNER JOIN AC_currency Ac ON Bil.CID=AC.CID
WHERE	BillType IN (128,129)
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND A.BTypeId = @BTypeId
		AND IfCheck = 't'
		AND Draft = 0
		AND Bil.IfYearBill = 0
		AND Bil.CID LIKE @CID
		
INSERT INTO #BillIndex
SELECT DISTINCT
		Bil.BillCode,
		Bil.BillNumberId,
		Bil.BillDate,
		Bil.etypeid,
		bil.DTypeId,
		bil.ktypeid,
		Bil.btypeid,
		Bil.BillType,
		Bil.totalmoney AS Total,
		Bil.ntotalmoney AS NTotal, 
      	Bil.totalinmoney,
      	Bil.ntotalinmoney, 
		Bil.Comment,
		Bil.atypeid,
		Bil.TeamNo,
		Bil.RedWord,
		preferencemoney,
		npreferencemoney,
		AC.fullname AS cfullname,
		Bil.rate,
		Bil.explain,
		Bil.CID
FROM 	BillIndex Bil
		INNER JOIN ChargeOffBill A ON Bil.BillNumberId=A.BillNumberId
		INNER JOIN #stype s ON Bil.stypeid=s.typeid
		INNER JOIN #Dtype D ON D.typeid = Bil.DTypeId
		INNER JOIN AC_currency Ac ON Bil.CID=AC.CID
WHERE	BillType=450
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		--AND A.BTypeId = @BTypeId
		AND IfCheck = 't'
		AND Draft = 0
		AND Bil.IfYearBill = 0
		AND Bil.CID LIKE @CID

--特殊处理会计凭证
INSERT INTO #BillIndex
SELECT	
		A.BillCode,
		A.BillNumberId,
		A.BillDate,
		A.ETypeid,
		A.DTypeId,
		A.ktypeid,
		L.BTypeid,
		A.BillType,
		0 AS Total,
	    0 AS NTotal,
      	0 AS totalinmoney,
      	0 AS ntotalinmoney, 
		A.Comment,
		L.ATypeid,
		A.TeamNo,
		A.RedWord,
		A.preferencemoney,
		A.npreferencemoney,
		AC.fullname AS cfullname,
		AC.rate,
		A.explain,
		L.CID
FROM	BillIndex A
		INNER JOIN ListTable L ON A.BillNumberID=L.BillNumberID AND A.BillType=L.BillType
		INNER JOIN #stype s ON A.stypeid=s.typeid
		INNER JOIN #Dtype D ON D.typeid = A.DTypeId
		INNER JOIN AC_currency AC ON L.CID=AC.CID
		INNER JOIN AC_Items ACI ON L.AtypeId=ACI.nid
WHERE	A.BillType=159
		AND A.BillDate>=@StartDate
		AND A.BillDate<=@EndDate
		AND L.BTypeId = @BTypeId		
		AND A.IfCheck = 't'
		AND A.Draft = 0
		AND ACI.UserCode IN (SELECT typeid FROM #atype1)
		AND L.CID LIKE @CID

--特殊处理付款单
INSERT INTO #BillIndex
SELECT	
		A.BillCode,
		A.BillNumberId,
		A.BillDate,
		A.ETypeid,
		A.DTypeId,
		A.ktypeid,
		a.BTypeid,
		A.BillType,
		0 AS Total,
	    0 AS NTotal,
      	0 AS totalinmoney,
      	0 AS ntotalinmoney, 
		A.Comment,
		0 AS ATypeid,
		A.TeamNo,
		A.RedWord,
		A.preferencemoney,
		A.npreferencemoney,
		AC.fullname AS cfullname,
		A.rate,
		A.explain,
		A.CID
FROM	BillIndex A
		--INNER JOIN ListTable L ON A.BillNumberId=L.BillNumberId
		INNER JOIN #stype s ON A.stypeid=s.typeid
		INNER JOIN #Dtype D ON D.typeid = A.DTypeId
		INNER JOIN AC_currency AC ON A.CID=AC.CID
		--INNER JOIN AC_Items ACI ON L.AtypeId=ACI.nid
WHERE	A.BillType=66
		AND A.BillDate>=@StartDate
		AND A.BillDate<=@EndDate			
		AND a.BTypeId = @BTypeId	
		AND A.IfCheck = 't'
		AND A.Draft = 0
		AND A.ifYearBill=0
		--AND (ACI.TypeName='B' OR ACI.UserCode='1151' OR ACI.UserCode='2181' OR ACI.UserCode='0456')  --需要查银行账户，预付资金
		AND A.CID LIKE @CID
--SELECT * FROM #BillIndex
--DROP TABLE #BillIndex
--RETURN

SET @sql='
insert into #result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		apadd,
		napadd,
		ApReduce,
		NApReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname,
		rate,
		atypeid,
		goodsnumber,
		remark ,
		unit,
		MQty,  
		MTaxPrice,
		conversionrelationship,
		customassistantunit
	)
SELECT	B.*
FROM	(
			SELECT  ZY='''',--ZY=''进货:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					P.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment, 
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.TaxTotal
								WHEN Bil.RedWord=2 THEN  -S.TaxTotal ELSE 0 END,
					NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.NTaxTotal
								WHEN Bil.RedWord=2 THEN  -S.NTaxTotal ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					S.goodsnumber,
					Bil.EXPLAIN remark,
					S.MUnitID as unit,
					S.MQTY,
					S.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,S.Qty) as customassistantunit  
			FROM 	BuyBill S
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
      				#BillIndex Bil,
      				#PType P
			WHERE 	Bil.BillType = 34
					AND Bil.BillNumberId = S.BillNumberId
					AND P.TypeId = S.PTypeID
			UNION ALL
			SELECT 	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ApAdd=0,
					NApAdd=0,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 THEN -Bil.preferencemoney ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 THEN -Bil.npreferencemoney ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 34
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT  ZY='''',--''退货:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					P.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN -s.qty
							 WHEN Bil.RedWord=2 THEN  s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment, 
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN -S.TaxTotal
								WHEN Bil.RedWord =2 THEN S.TaxTotal ELSE 0 END,
					NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN -S.NTaxTotal
								WHEN Bil.RedWord =2 THEN S.NTaxTotal ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					S.goodsnumber,
					Bil.EXPLAIN remark,
					S.MUnitID as unit,
					S.MQty,
					S.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,Qty) as customassistantunit  
			FROM 	#BillIndex Bil,
     				BuyBackBill S
     				LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
     				#PType P
			WHERE 	Bil.BillType = 6
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeID
			         '
SET @sql=@sql+ '
	) B'


EXEC(@sql)
--RETURN
--优惠券入库单
 SET @sql = '
insert into #result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		apadd,
		napadd,
		ApReduce,
		NApReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname,
		rate,
		atypeid,
		goodsnumber,
		remark ,
		unit,
		MQty,  
		MTaxPrice,
		conversionrelationship,
		customassistantunit
	)
SELECT	B.*
FROM	(
			 SELECT  ZY='''',--ZY=''进货:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					'''' AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					0 as taxprice,
					0 as ntaxprice,
					'''' AS incomment, 
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.CostTotal
								WHEN Bil.RedWord=2 THEN  -S.CostTotal ELSE 0 END,
					NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.NCostTotal
								WHEN Bil.RedWord=2 THEN  -S.NCostTotal ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					'''' as ktypeid,
					null as TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					null as TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain AS remark,
					0 unit,
					0 MQty,
					0 MTaxPrice,
					'''' conversionrelationship,
					'''' customassistantunit   
			FROM 	coupon_InBill S,
      				#BillIndex Bil
			WHERE 	Bil.BillType = 423
					AND Bil.BillNumberId = S.BillNumberId
					UNION ALL
			SELECT 	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ApAdd=0,
					NApAdd=0,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 THEN -Bil.preferencemoney ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 THEN -Bil.npreferencemoney ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 423
					AND Bil.preferencemoney<>0
					) B
					'
					;

EXEC(@sql);

SET @sql='
         insert into #result(
		                   zy,
		              ptypeid,
		                  qty,
		             taxprice,
		            ntaxprice,
		            incomment,
		                apadd,
		               napadd,
		             ApReduce,
		            NApReduce,
		             BillDate,
		             BillCode,
		              etypeid,
		              dtypeid,
		              ktypeid,
		               TeamNo,
		                   id,
		              btypeid,
		         BillNumberId,
		             BillType,
		              TeamNo1,
		              RedWord,
	                  Comment,
	                  cfullname,
	                  rate,
	                  atypeid,
	                  goodsnumber,
	                  remark,
					  unit,
					  MQty,
					  MTaxPrice,
					  conversionrelationship,
					  customassistantunit  
	)
SELECT	B.*
FROM	(
			SELECT 	ZY=''抹零金额:'',
					'' '' AS ptypeid,
					0 AS qty,
					0 AS taxprice,
					0 AS ntaxprice,
					'' '' AS incomment,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 THEN -Bil.preferencemoney ELSE 0 END,
					NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 THEN -Bil.npreferencemoney ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
				    Bil.rate,
				    Bil.atypeid,
				   '''' as goodsnumber,
				    explain AS remark,
					0 unit,
					0 MQty,
					0 MTaxPrice,
					'''' conversionrelationship,
					'''' customassistantunit  
			FROM 	#BillIndex Bil	
			WHERE 	Bil.BillType = 6
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	
					ZY=''付款:'' + AC.FullName,
					'' '',
					0,
					0,
					0,
					G.COMMENT,
					ApAdd=0,
					NApAdd=0, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN G.total 
								WHEN Bil.RedWord =2 THEN -G.total	ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN G.ntotal 
								WHEN Bil.RedWord =2 THEN -G.ntotal	ELSE 0 END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					bil.TeamNo, 
					id=-1, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					G.atypeid,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil 
			INNER JOIN paybill G ON BIL.BILLNUMBERID=G.BILLNUMBERID
      INNER JOIN	#BType B ON B.TypeId = Bil.BTypeID
      INNER JOIN    AC_Items AC ON G.AtypeId=AC.nid
			WHERE 	Bil.BillType = 66
					AND (AC.TypeName=''B'' OR (AC.UserCode=''1151'' AND '+CAST(@IncludePre AS VARCHAR)+'<>1 ) OR AC.UserCode=''2181'' )
		 UNION ALL
			SELECT 	
					ZY=''付款:优惠金额'',
					'' '',
					0,
					0,
					0,
					'' '',
					ApAdd=0,
					NApAdd=0, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN bil.preferencemoney 
								WHEN Bil.RedWord =2 THEN -bil.preferencemoney	ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN bil.npreferencemoney
								WHEN Bil.RedWord =2 THEN -bil.npreferencemoney	ELSE 0 END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					bil.TeamNo, 
					id=-1, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					'''',
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
      INNER JOIN	#BType B ON B.TypeId = Bil.BTypeID
			WHERE 	Bil.BillType = 66
			 AND Bil.preferencemoney<>0 
			UNION ALL
			SELECT 	ZY=''获得价保:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=0,
					NArAdd=0, 
					ArReduce=CASE WHEN Bil.RedWord IN(0,1)  THEN S.total
								WHEN Bil.RedWord =2  THEN -S.total ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1)  THEN S.total
								WHEN Bil.RedWord =2  THEN -S.total ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
		      		#BType B,
		      		PriceProtectBill S
			WHERE 	Bil.BillType = 151
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeId = Bil.BTypeID
			--2004-3-10新增加
			UNION ALL
					SELECT  ZY=''获利执行:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total
								WHEN Bil.RedWord =2  THEN -S.total  ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total
								WHEN Bil.RedWord =2  THEN -S.total  ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
		      		#BType B,
		      		Advantage S
			WHERE 	Bil.BillType = 150
					AND Bil.BillNumberId = S.BillNumberId
					AND Bil.BTypeID = B.TypeID
				'

SET @sql=@sql+ '
	) B'

--PRINT(@sql)
EXEC(@sql)
--RETURN

SET @sql='
         insert into #result(
		                   zy,
		              ptypeid,
		                  qty,
		             taxprice,
		            ntaxprice,
		            incomment,
		                apadd,
		               napadd,
		             ApReduce,
		            NApReduce,
		             BillDate,
		             BillCode,
		              etypeid,
		              dtypeid,
		              ktypeid,
		               TeamNo,
		                   id,
		              btypeid,
		         BillNumberId,
		             BillType,
		              TeamNo1,
		              RedWord,
	                  Comment,
	                cfullname,
	                     rate,
	                  atypeid,
	                  goodsnumber,
	                  remark,
					  unit,
					  MQty,
					  MTaxPrice,
					  conversionrelationship,
					  customassistantunit  
	)
SELECT	B.*
FROM	(
			SELECT 	ZY='''',--''受托代销结算:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					P.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment, 
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.TaxTotal
								WHEN Bil.RedWord =2 THEN -S.TaxTotal ELSE 0 END, 
					NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.NTaxTotal
								WHEN Bil.RedWord =2 THEN -S.NTaxTotal ELSE 0 END,     
					ApReduce=0,
					NApReduce=0,       
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					S.goodsnumber,
					
					Bil.EXPLAIN  remark,
					S.MUnitID as unit,
					S.MQty,
					S.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,S.Qty) as customassistantunit  

			FROM 	#BillIndex Bil,
			      	#BType B,
			      	CommissionBill S
			      	LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
					#PType P
			WHERE 	Bil.BillType = 145
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeID = Bil.BTypeID
					AND P.TypeId = S.PTypeId
			'
SET @sql=@sql+' UNION ALL
			SELECT 	ZY=S.Comment,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total
								WHEN Bil.RedWord =2 THEN -S.total ELSE 0 END,
					NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.ntotal
								WHEN Bil.RedWord =2 THEN -S.ntotal ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					S.TeamNo, 
					S.ID, 
					S.BtypeId,  
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
			      	AdDebtBill S,
					#BType B
			WHERE 	Bil.BillType IN(128)
					AND B.TypeId = S.BTypeID
					AND Bil.BillNumberId = S.BillNumberId
			UNION ALL
			SELECT 	ZY=S.Comment,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ApAdd=0,
					NApAdd=0,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total
								WHEN Bil.RedWord=2 THEN -S.total ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.ntotal
								WHEN Bil.RedWord=2 THEN -S.ntotal ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					S.TeamNo, 
					S.ID, 
					S.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
			      	AdDebtBill S,
			      	#BType B
			WHERE 	Bil.BillType IN(129)
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeId = S.BTypeID
			UNION ALL
			SELECT	ZY=''费用:''+A.FullName, 
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total
								WHEN Bil.RedWord=2 THEN -S.total ELSE 0 END,
					NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.Ntotal
								WHEN Bil.RedWord=2 THEN -S.ntotal ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,       
					S.TeamNo, 
					S.ID, 
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType, 
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	MoneyBill S,
			      	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType =36
					AND Bil.BillNumberId = S.BillNumberId
					AND S.ATypeId = A.TypeId
					AND ((BIL.BTypeId LIKE ''00002%'' AND '+cast(@expensetoar as varchar(2))+'=1) OR '+cast(@expensetoar as varchar(2))+'=0)
			UNION ALL
			SELECT	ZY=''费用:预付资金'', 
					'' '',
					0,
					0,
					0,
					'''',--s.comment AS incomment,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN BIL.TOTALINMONEY
								WHEN Bil.RedWord=2 THEN -BIL.TOTALINMONEY ELSE 0 END,
					NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN BIL.NTOTALINMONEY
								WHEN Bil.RedWord=2 THEN -BIL.NTOTALINMONEY ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,       
					'''',--S.TeamNo, 
					'''',--S.ID, 
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType, 
					'''',--S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType =36
					AND BIL.ATYPEID=27
					AND (BIL.btypeid LIKE ''00001%'' AND '+cast(@IncludePre as varchar(2))+'=1 AND '+cast(@expensetoar as varchar(2))+'=1)
'

SET @sql=@sql+ '
	) B'
--PRINT(@sql)
EXEC(@sql)
--RETURN

SET @sql='
         insert into #result(
		                   zy,
		              ptypeid,
		                  qty,
		             taxprice,
		            ntaxprice,
		            incomment,
		                apadd,
		               napadd,
		             ApReduce,
		            NApReduce,
		             BillDate,
		             BillCode,
		              etypeid,
		              dtypeid,
		              ktypeid,
		               TeamNo,
		                   id,
		              btypeid,
		         BillNumberId,
		             BillType,
		              TeamNo1,
		              RedWord,
	                  Comment,
	                cfullname,
	                     rate,
	                  atypeid,
	                  goodsnumber,
	                  remark,
					unit,
					MQty,
					MTaxPrice,
					conversionrelationship,
					customassistantunit  
	)
SELECT	B.*
FROM	(
			SELECT 	ZY=''固定资产购买:'' + B.FullName,
					'' '' AS ptypeid,
					0 AS qty,
					0 AS taxprice,
					0 AS ntaxprice,
					s.comment AS incomment,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total 
						       WHEN Bil.RedWord =2 THEN -S.total	ELSE 0 END,
				    NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.ntotal 
						       WHEN Bil.RedWord =2 THEN -S.ntotal	ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					--BIL.TOTALINMONEY,
					--BIL.NTOTALINMONEY,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain AS remark,
					0 unit,
					0 MQty,
					0 MTaxPrice,
					'''' conversionrelationship,
					'''' customassistantunit  
			FROM 	#BillIndex Bil,
			      	#BType B,
			      	MoneyBill S
			WHERE 	Bil.BillType = 84
					AND S.BillNumberId = Bil.BillNumberId
					AND Bil.BTypeId = B.TypeID'
	IF @assets=1
		SET @sql=@sql+'
			UNION ALL
			SELECT 	ZY=''固定资产增加:'' + B.FullName,
					'' '' AS ptypeid,
					0 AS qty,
					0 AS taxprice,
					0 AS ntaxprice,
					s.comment AS incomment,
					ApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.taxtotal 
						       WHEN Bil.RedWord =2 THEN -S.taxtotal	ELSE 0 END,
				    NApAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.ntaxtotal 
						       WHEN Bil.RedWord =2 THEN -S.ntaxtotal	ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					null as TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					null as TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'' '' GoodsNumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	AssetIncDecBill S
			      	INNER JOIN #BillIndex Bil ON S.BillNumberId = Bil.BillNumberId
			      	INNER JOIN #BType B ON Bil.BTypeId = B.TypeID
			WHERE 	Bil.BillType = 212 '
		SET @sql=@sql+'		
			UNION ALL
			SELECT	ZY=''应付:''+B.FullName,		
					'' '',
					0,
					0,
					0,
					CASE
						WHEN  acd.d_Total<>0 THEN acd.comment
						WHEN acd.j_total <>0 THEN acd.comment
						ELSE ''''
					END AS incomment,
					ApAdd=CASE WHEN V.RedWord IN (0,1) AND acd.d_Total<>0 THEN d_Total
								WHEN V.RedWord = 2 AND acd.d_Total<>0 THEN -d_Total ELSE 0 END,
					NApAdd=CASE WHEN V.RedWord IN (0,1) AND acd.nd_Total<>0 THEN acd.Nd_Total
								WHEN V.RedWord = 2 AND acd.nd_Total<>0 THEN -acd.Nd_Total ELSE 0 END,
					ApReduce=CASE WHEN V.RedWord IN (0,1) AND acd.j_Total<>0 THEN acd.j_Total
									WHEN V.RedWord = 2 AND acd.j_Total<>0 THEN -acd.j_Total ELSE 0 END,
					NApReduce=CASE WHEN V.RedWord IN (0,1) AND acd.nj_Total<>0 THEN acd.nj_Total
									WHEN V.RedWord = 2 AND acd.nj_Total<>0 THEN -acd.nj_Total ELSE 0 END,
					V.BillDate,
					V.BillCode,
					V.ETypeId,
					v.dtypeid,
					v.ktypeid,
					V.TeamNo,
					ID=-1,
					V.BTypeId,
					V.BillNumberId,
					V.BillType,
					TeamNo1=NULL,
					V.RedWord,
					V.Comment,
					V.cfullname,
					V.rate,
					V.atypeid ,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM	#BillIndex V,
                    #BType B, 
	                AC_Items AC,
	                accountcredence acd
			WHERE   V.BillType = 159
					AND AC.UserCode=''2121''
					AND V.BTypeId = B.TypeId
					AND V.AtypeId=AC.nid
					AND V.BillNumberId = acd.BillNumberId
					AND acd.atypeid=B.typeid
					AND acd.cid=v.cid
					AND acd.TypeATypeID=ac.nid
			UNION ALL
			SELECT	ZY=''预付:''+B.FullName,		
					'' '',
					0,
					0,
					0,
					CASE
						WHEN  acd.d_Total<>0 THEN acd.comment
						WHEN acd.j_total <>0 THEN acd.comment
						ELSE ''''
					END AS incomment,
					ApAdd=CASE WHEN V.RedWord IN (0,1) AND acd.d_Total<>0 THEN d_Total
								WHEN V.RedWord = 2 AND acd.d_Total<>0 THEN -d_Total ELSE 0 END,
					NApAdd=CASE WHEN V.RedWord IN (0,1) AND acd.nd_Total<>0 THEN acd.Nd_Total
								WHEN V.RedWord = 2 AND acd.nd_Total<>0 THEN -acd.Nd_Total ELSE 0 END,
					ApReduce=CASE WHEN V.RedWord IN (0,1) AND acd.j_Total<>0 THEN acd.j_Total
									WHEN V.RedWord = 2 AND acd.j_Total<>0 THEN -acd.j_Total ELSE 0 END,
					NApReduce=CASE WHEN V.RedWord IN (0,1) AND acd.nj_Total<>0 THEN acd.nj_Total
									WHEN V.RedWord = 2 AND acd.nj_Total<>0 THEN -acd.nj_Total ELSE 0 END,
					V.BillDate,
					V.BillCode,
					V.ETypeId,
					v.dtypeid,
					v.ktypeid,
					V.TeamNo,
					ID=-1,
					V.BTypeId,
					V.BillNumberId,
					V.BillType,
					TeamNo1=NULL,
					V.RedWord,
					V.Comment,
					V.cfullname,
					V.rate,
					V.atypeid ,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM	#BillIndex V,
	                #BType B,
	                AC_Items AC,
	                accountcredence acd
			WHERE   V.BillType = 159
					AND AC.UserCode=''1151''
					AND V.BTypeId = B.TypeId
					AND V.atypeid=AC.nid	
					AND V.BillNumberId = acd.BillNumberId
					AND acd.atypeid=B.typeid
					AND acd.cid=v.cid
					AND acd.TypeATypeID=ac.nid	

) B'
--PRINT(@sql)
--RETURN

EXEC(@sql)

SET @sql='
         insert into #result(
		                   zy,
		              ptypeid,
		                  qty,
		             taxprice,
		            ntaxprice,
		            incomment,
		                apadd,
		               napadd,
		             ApReduce,
		            NApReduce,
		             BillDate,
		             BillCode,
		              etypeid,
		              dtypeid,
		              ktypeid,
		               TeamNo,
		                   id,
		              btypeid,
		         BillNumberId,
		             BillType,
		              TeamNo1,
		              RedWord,
	                  Comment,
	                cfullname,
	                     rate,
	                     atypeid,
	                     goodsnumber,
	                     remark,
						unit,
						MQty,
						MTaxPrice,
						conversionrelationship,
						customassistantunit  
	)
SELECT	B.*
FROM	(
			SELECT	ZY=
				 		Case S.InOrOut
							WHEN ''O'' THEN
					     		''''--''采购换货出库:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20))
							WHEN ''I'' THEN
					     		''''--''采购换货入库:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20))
				  	END,			
					P.typeid AS ptypeid,
				    qty=
				    CASE  WHEN S.InOrOut=''I'' AND Bil.Redword IN (0,1) THEN s.qty
					      WHEN S.InOrOut=''O'' AND Bil.Redword IN (0,1) THEN  -s.qty 
					      WHEN S.InOrOut=''I'' AND Bil.Redword IN (2) THEN -s.qty
					      WHEN S.InOrOut=''O'' AND Bil.Redword IN (2) THEN s.qty
					      ELSE 0 END ,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment,  
					ApAdd=
					 CASE S.InOrOut 
				         WHEN ''I'' THEN 
								CASE WHEN Bil.RedWord IN(0,1) THEN CAST(CAST(S.TaxTotal AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) 	
									 WHEN Bil.RedWord=2 THEN CAST(CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) 
								ELSE 0 END
						 ELSE 0				
				      END,
				    NApAdd=
					  CASE S.InOrOut 
				          WHEN ''I'' THEN 
								CASE WHEN Bil.RedWord IN(0,1) THEN CAST(CAST(S.NTaxTotal AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) 	
									 WHEN Bil.RedWord=2 THEN CAST(CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) 
								ELSE 0 END
						ELSE 0				
				      END,
					ApReduce=	
						CASE S.InOrOut
							WHEN ''O'' THEN 
									CASE WHEN Bil.RedWord IN(0,1) THEN CAST(CAST(S.TaxTotal AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) 
										 WHEN Bil.RedWord=2 THEN CAST(CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) 
									ELSE 0 END
							ELSE 0
			      		END,	
			      	NApReduce=	
						CASE S.InOrOut
							WHEN ''O'' THEN 
									CASE WHEN Bil.RedWord IN(0,1) THEN CAST(CAST(S.NTaxTotal AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) 
										 WHEN Bil.RedWord=2 THEN CAST(CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) 
									ELSE 0 END
							ELSE 0
			      		END,			      
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					S.goodsnumber,
					Bil.EXPLAIN  remark,
					S.MUnitID as unit,
					S.MQty,
					S.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,Qty) as customassistantunit  
			FROM 	BuyGoodsExchangeBill S
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID,
			      	#BillIndex Bil,
			      	#PType P
			WHERE 	Bil.BillType = 161
					AND Bil.BillNumberId = S.BillNumberId
					AND P.TypeId = S.PTypeId
			UNION ALL
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',	
					ApAdd=0,
					NApAdd=0,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney 
									WHEN Bil.RedWord =2 THEN -Bil.preferencemoney ELSE 0 END,
				    NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.npreferencemoney 
									WHEN Bil.RedWord =2 THEN -Bil.npreferencemoney ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil 
			WHERE 	Bil.BillType = 161
					AND Bil.preferencemoney<>0
'

SET @sql=@sql+ '
	) B'

--PRINT(@sql)
EXEC(@sql)
--RETURN

SET @sql='
         insert into #result(
		                   zy,
		              ptypeid,
		                  qty,
		             taxprice,
		            ntaxprice,
		            incomment,
		                apadd,
		               napadd,
		             ApReduce,
		            NApReduce,
		             BillDate,
		             BillCode,
		              etypeid,
		              dtypeid,
		              ktypeid,
		               TeamNo,
		                   id,
		              btypeid,
		         BillNumberId,
		             BillType,
		              TeamNo1,
		              RedWord,
	                  Comment,
	                cfullname,
	                     rate,
	                  atypeid,
	                  goodsnumber,
	                  
					remark,
					unit,
					MQty,
					MTaxPrice,
					conversionrelationship,
					customassistantunit  
	)
SELECT	B.*
FROM	(
		SELECT 	ZY=''送修返回:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)), 
				P.typeid AS ptypeid,
				qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
				0 AS taxprice,
				0 AS ntaxprice,
				s.comment AS incomment,        
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.Total AS  NUMERIC(24, 10) )
							WHEN Bil.RedWord=2 THEN CAST(-S.Total AS  NUMERIC(24, 10) ) ELSE 0 END,
				NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.Total AS  NUMERIC(24, 10) )
							WHEN Bil.RedWord=2 THEN CAST(-S.Total AS  NUMERIC(24, 10) ) ELSE 0 END,
				ArReduce=0,
				NArReduce=0,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				bil.dtypeid,
				bil.ktypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment,
				Bil.cfullname,
				Bil.rate,
		        Bil.atypeid,
		        S.goodsnumber,
		        Bil.EXPLAIN remark,
				0 unit,
				0 MQty,
				0 MTaxPrice,
				'''' conversionrelationship,
				'''' customassistantunit  
		FROM 	Wx_Bill_SendBack S,
		      	#BillIndex Bil, 
		      	#PType P
		WHERE 	Bil.BillType = 170
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT	ZY=''抹零金额:'',
				'' '',
				0,
				0,
				0,
				'' '',
				ArAdd=0,
				NArAdd=0,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.preferencemoney 
							WHEN Bil.RedWord =2 THEN  -Bil.preferencemoney	ELSE 0 END,
				NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.npreferencemoney 
							WHEN Bil.RedWord =2 THEN  -Bil.npreferencemoney	ELSE 0 END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				bil.dtypeid,
				bil.ktypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1='' '',
				Bil.RedWord,
				Bil.Comment,
				Bil.cfullname,
				Bil.rate,
				Bil.atypeid,
				'''' as goodsnumber,
				Bil.EXPLAIN ,
				0,
				0,
				0,
				'''',
				''''
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 170
				AND Bil.preferencemoney<>0 '
IF @IncludePre=1
begin
	SET @sql=@sql+' UNION ALL
			SELECT 	ZY=''预付:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ApAdd=0,
					NApAdd=0, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN s.total 
								WHEN Bil.RedWord =2 THEN -s.total ELSE 0 END,
				    NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN s.ntotal 
								WHEN Bil.RedWord =2 THEN -s.ntotal ELSE 0 END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
      				#BType B,
      				PreBill s
			WHERE 	Bil.BillType = 190
					AND bil.billnumberid=s.billnumberid
					AND B.TypeId = Bil.BTypeID '
END	
 
SET @sql=@sql+ '
	) B'
--PRINT(@sql)
EXEC(@sql)
--RETURN

SET @sql='
		INSERT INTO #result(
				zy,
				ptypeid,
				qty,
				taxprice,
				ntaxprice,
				incomment,
				apadd,
				napadd,
				ApReduce,
				NApReduce,
				BillDate,
				BillCode,
				etypeid,
				dtypeid,
				ktypeid,
				TeamNo,
				id	,
				btypeid	,
				BillNumberId,
				BillType,
				TeamNo1	,
				RedWord	,
				Comment ,
			  cfullname ,
			       rate ,
			    atypeid,
			    goodsnumber,
			    remark,
				unit,
				MQty,
				MTaxPrice,
				conversionrelationship,
				customassistantunit  
			)
			SELECT 
					''付款：''+a.fullname,
					'' '' AS ptypeid,
					0 AS qty,
					0 AS taxprice,
					0 AS ntaxprice,
					'' '' AS incomment,
					ApAdd=CASE WHEN B.RedWord IN(0,1) AND B.billtype IN(6,150,151) THEN ac.total 
							WHEN B.RedWord =2 AND B.billtype IN (6,150,151) THEN -ac.total ELSE 0 END, 
					NApAdd=CASE WHEN B.RedWord IN(0,1) AND B.billtype IN(6,150,151) THEN ac.ntotalmoney 
							WHEN B.RedWord =2 AND B.billtype IN (6,150,151) THEN -ac.ntotalmoney ELSE 0 END,   
					ApReduce=CASE WHEN B.RedWord IN(0,1)  AND B.billtype NOT IN(6,150,151) THEN ac.total 
							WHEN B.RedWord =2  AND B.billtype NOT IN (6,150,151) THEN -ac.total ELSE 0 END,
					NApReduce=CASE WHEN B.RedWord IN(0,1)  AND B.billtype NOT IN(6,150,151) THEN ac.ntotalmoney 
							WHEN B.RedWord =2  AND B.billtype NOT IN (6,150,151) THEN -ac.ntotalmoney ELSE 0 END, 
					b.BillDate,
					b.billcode,
					b.etypeid,
					b.dtypeid,
					b.ktypeid,
					b.teamno,
					-1,
					b.btypeid,
					b.billnumberid, 
      				b.billtype, 
      				'''',
      				b.redword,
					b.Comment,
				  b.cfullname,
					   b.rate,
			       b.atypeid,
			       '''' as goodsnumber,
			       explain,
					0,
					0,
					0,
					'''',
					''''
			FROM #billindex b
	  INNER JOIN	billmulaccount ac ON b.billnumberid=ac.billnumberid and b.billtype = ac.billtype
	  INNER JOIN	#atype a ON a.typeid=ac.atypeid
				 '  
if @IncludePre=1
	SET @sql=@sql+' where a.UserCode<>''1151'' '
IF(@IncludePre=1 AND @expensetoar=1)
	SET @SQL=@SQL+' AND (( B.BILLTYPE=36 AND B.BTYPEID LIKE''00002%'') OR (B.BILLTYPE<>36))'


exec(@sql)	

insert into #result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		apadd,
		napadd,
		ApReduce,
		NApReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname,
		rate,
		atypeid,
		goodsnumber,
		remark,
		unit,
		MQty,
		MTaxPrice,
		conversionrelationship,
		customassistantunit  
	)
		SELECT 	ZY='',
					'',
					0,
					0,
					0,
					'' AS incomment,
					/*s.comment AS incomment,
					ApAdd=CASE WHEN s.ChargeOffType in (3,4,1) and IsCharged=1 and  Bil.RedWord IN(0,1) THEN S.ChargeOffValue	  --应付转应付转入单位,预收转应付转入方,预收冲预转入方
								 WHEN s.ChargeOffType=5 and IsCharged=0 and  Bil.RedWord IN(0,1) THEN S.ChargeOffValue		 --预付转应收转出
								   WHEN s.ChargeOffType in(3,4,1) and IsCharged=1 and  Bil.RedWord=2 THEN -S.ChargeOffValue	 
								 WHEN s.ChargeOffType=5 and IsCharged=0 and   Bil.RedWord=2 THEN -S.ChargeOffValue
								 ELSE 0 END,
					NApAdd=CASE WHEN s.ChargeOffType in(3,4,1) and IsCharged=1 and  Bil.RedWord IN(0,1) THEN S.nChargeOffValue	 
								 WHEN s.ChargeOffType=5 and IsCharged=0 and  Bil.RedWord IN(0,1) THEN S.nChargeOffValue		 
								 WHEN s.ChargeOffType in(3,4,1) and IsCharged=1 and  Bil.RedWord=2 THEN -S.nChargeOffValue	 
								 WHEN s.ChargeOffType=5 and IsCharged=0 and   Bil.RedWord=2 THEN -S.nChargeOffValue
								 ELSE 0 END,
								 
					ApReduce=CASE WHEN s.ChargeOffType=3 and IsCharged=0 and  Bil.RedWord IN(0,1) THEN S.ChargeOffValue	--应付转应付转出单位
								  WHEN s.ChargeOffType=0 and IsCharged=1 and  Bil.RedWord IN(0,1) THEN S.ChargeOffValue	 --应收转应付转入方
								   WHEN s.ChargeOffType=3 and IsCharged=0  and  Bil.RedWord=2  THEN -S.ChargeOffValue	
								  WHEN s.ChargeOffType=0 and IsCharged=1 and  Bil.RedWord=2  THEN -S.ChargeOffValue   
								 ELSE 0 END,	 
								  
					NApReduce=CASE WHEN s.ChargeOffType=3 and IsCharged=0 and  Bil.RedWord IN(0,1) THEN S.nChargeOffValue	
								  WHEN s.ChargeOffType=0 and IsCharged=1 and  Bil.RedWord IN(0,1) THEN S.nChargeOffValue 
								  WHEN s.ChargeOffType=3 and IsCharged=0  and  Bil.RedWord=2  THEN -S.nChargeOffValue	
								  WHEN s.ChargeOffType=0 and IsCharged=1 and  Bil.RedWord=2  THEN -S.nChargeOffValue  
								 ELSE 0 END,*/	
					ArAdd = CASE   WHEN s.atypeid=35 and s.total>0 and 	Bil.RedWord IN(0,1)	  then s.Total
									when  s.atypeid=35 and s.total<0 and  Bil.RedWord =2    THEN s.Total
								  WHEN  s.atypeid=27 AND s.Total<0  AND Bil.redword IN(0,1) THEN ABS(s.Total) 
								WHEN   s.atypeid=27 AND s.Total>0  AND Bil.redword=2  THEN -s.Total
								ELSE 0 END,
					NArAdd = CASE   WHEN s.atypeid=35 and s.Ntotal>0 and 	Bil.RedWord IN(0,1)	  then s.NTotal
									when  s.atypeid=35 and s.Ntotal<0 and  Bil.RedWord =2    THEN s.NTotal
								   WHEN  s.atypeid=27 AND s.NTotal<0  AND Bil.redword IN(0,1) THEN ABS(s.NTotal) 
								    WHEN   s.atypeid=27 AND s.NTotal>0  AND Bil.redword=2  THEN -s.NTotal
								ELSE 0 END,
					ArReduce= CASE   WHEN s.atypeid=35 and s.total<0 and 	Bil.RedWord IN(0,1)	  then ABS(s.Total)
									when  s.atypeid=35 and s.total>0 and  Bil.RedWord =2    THEN -s.Total
								   WHEN  s.atypeid=27 AND s.Total>0  AND Bil.redword IN(0,1) THEN s.Total 
								    WHEN   s.atypeid=27 AND s.Total<0  AND Bil.redword=2  THEN s.Total
								ELSE 0 END,
					nArReduce= CASE   WHEN s.atypeid=35 and s.Ntotal<0 and 	Bil.RedWord IN(0,1)	  then ABS(s.NTotal)
									when  s.atypeid=35 and s.Ntotal>0 and  Bil.RedWord =2    THEN -s.NTotal
								   WHEN  s.atypeid=27 AND s.NTotal>0  AND Bil.redword IN(0,1) THEN s.NTotal 
								    WHEN   s.atypeid=27 AND s.NTotal<0  AND Bil.redword=2  THEN s.NTotal
								ELSE 0 END,			  
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					bil.TeamNo, 
					S.ID, 
					S.BtypeId,  
					Bil.BillNumberId,
					Bil.BillType,
					0,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.atypeid,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
				    Listtable S,
					#BType B
			WHERE 	Bil.BillType IN(450)
					AND B.TypeId = S.BTypeID
					AND Bil.BillNumberId = S.BillNumberId
					And s.atypeid in(35,27)
					and (  @IncludePre=1 or s.atypeid=35)  
 --加入发票数据
IF EXISTS(SELECT 1 FROM sysdata WHERE SubValue='1' AND SubName='IsInvoice')
BEGIN
insert into #result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		apadd,
		napadd,
		ApReduce,
		NApReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname,
		rate,
		atypeid,
		goodsnumber,
		remark,
		unit,
		MQty,
		MTaxPrice,
		conversionrelationship,
		customassistantunit,
		BillFlag 
	)
SELECT	ZY='',
					P.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment, 
					apadd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					napadd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.NTaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ApReduce=0,
					NApReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					AC.FullName AS Cfullname,
					Bil.rate,
					'',
					s.goodsnumber,
					Bil.EXPLAIN  remark,
					S.MUnitID as unit,
					S.MQty,
					S.CurMTaxPrice,
					'1'+PU.fullname+'='+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,Qty) as customassistantunit,
					1 BillFlag
			FROM  	ReceiptBill S
			LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
			LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID 
		    INNER JOIN  ReceiptBillIndex Bil ON S.BillNumberID=BIL.BillNumberID
		    INNER JOIN #stype s1 on s1.typeid=Bil.Stypeid
			INNER JOIN #Dtype D ON D.typeid = Bil.DTypeId
			INNER JOIN AC_currency AC ON Bil.CID=AC.CID
		    INNER JOIN PType P ON S.PTypeId = P.TypeId
			WHERE 	Bil.BillType = 404
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
					AND bil.BillDate>=@StartDate
					AND Bil.BillDate<=@ENDDate
					AND Bil.ifcheck = 't' 
					AND Bil.BTypeId = @BTypeId
					AND Bil.IfYearBill = 0
					AND Bil.CID LIKE @CID
END					
--SELECT LEN(@sql)
--SELECT * FROM #invoiceQty
SET @SQL = ' SELECT ps.FullName AS bfullname,ps2.FullName AS unitfullname,#result.* ,
			  case when #Result.redword in (0,1) then isnull(inv.uninvoiceqty,0) else -isnull(inv.uninvoiceqty,0) end as uninvoiceqty,
			  case when #Result.redword in (0,1) then isnull(inv.nuninvoicemoney,0) else -isnull(inv.nuninvoicemoney,0) end as nuninvoicemoney,
			  case when #Result.redword in (0,1) then isnull(inv.uninvoicemoney,0) else -isnull(inv.uninvoicemoney,0) end as uninvoicemoney
			 
			 FROM #Result 
			 LEFT JOIN dbo.ptype p ON p.Typeid=#result.ptypeid 
			 left join #invoiceQty inv on inv.billnumberid=#Result.billnumberid and inv.billtype=#Result.billtype  and inv.ptypeid=#Result.ptypeid and inv.id=#Result.id
			 LEFT JOIN dbo.PType_Units ps ON ps.UnitsId=p.baseUnitId 
			 LEFT JOIN dbo.PType_Units ps2 ON ps2.UnitsId=#result.unit '

IF @showRedWord = 0
	SET @SQL = @SQL + ' WHERE RedWord = 0 '

--排序字段的处理
/*
IF @Orderby=''
	SET @SQL=@SQL+'  ORDER BY billdate,billnumberid,id'
ELSE IF UPPER(@Orderby)='TEAMNO'
	SET @SQL=@SQL+'  ORDER BY ISNULL(TEAMNO,999999999),BillDate,BillType,BillCode,id'
ELSE IF UPPER(@Orderby)='BILLDATE'
	SET @SQL=@SQL+'  ORDER BY BillDate DESC,BillType,BillCode,id'
ELSE IF CHARINDEX('BILLDATE',UPPER(@orderby)) > 0
	SET @SQL=@SQL+'  ORDER BY '+@Orderby
ELSE
	SET @SQL=@SQL+'  ORDER BY billtype,'+@Orderby

*/
IF @Orderby=''
	SET @SQL=@SQL+'  ORDER BY billdate,billnumberid,billtype,id'
ELSE
	SET @SQL=@SQL+'  ORDER BY '+@Orderby

EXEC(@SQL)

DROP TABLE #BillIndex,#PType,#AType,#BType,#Result,#atype1,#Dtype,#stype,#invoiceQty




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApWldz_Gsqh_YH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApWldz_Gsqh_YH]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

























/*
	作者：谢吉康
	日期：2008-03-26
	描述：往来对账（格式切换），应收查询（不统一客户和供货商）
*/
CREATE PROCEDURE Web_QueryArApWldz_Gsqh_YH
(
	@OperatorID 	VARCHAR(100),  	   			--操作员ID号
	@nType        	INT=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@BTypeId      	VARCHAR(100),               	--往来单位typeid
	@szEtypeIds     VARCHAR(5000),   			--经手人etypeid
	@StartDate   	VARCHAR(10),               	--起始日期
	@EndDate    	VARCHAR(10),               	--截至日期
	@Orderby      	VARCHAR(50)='',           	--排序字段
	@showRedWord	int=1						--是否显示红冲单据  1.显示   0.不显示	
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SELECT	TypeId,FullName INTO #PType FROM F_GetManPTypeAll(@OperatorID) WHERE Deleted = 0 AND SonNum = 0 AND TypeId IN (SELECT * FROM F_GetManDetailPType(@OperatorID))

--『会员储值』
--SELECT	TypeId,FullName INTO #AType FROM F_GetManATypeAll(@OperatorID) WHERE Deleted = 0 AND SonNum = 0
--INSERT INTO #AType(TypeId,FullName)VALUES('0000200005','『会员储值』')
SELECT	TypeId,FullName INTO #AType FROM AType WHERE Deleted = 0 AND SonNum = 0

SELECT	TypeId,FullName INTO #BType FROM F_GetManBTypeAll(@OperatorID) WHERE TypeId = @BTypeId AND Deleted = 0 AND SonNum = 0 AND TypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))

CREATE TABLE #BillIndex
(
	BillCode		varchar(400),
	BillNumberId	numeric(18,0),
	BillDate		datetime,
	etypeid			varchar(100),
	btypeid			varchar(100),
	BillType		varchar(20),
	Total			 NUMERIC(24, 10) , 
  	totalinmoney	 NUMERIC(24, 10) , 
	Comment			varchar(2000),
	atypeid			varchar(100),
	TeamNo			varchar(20),
	RedWord			varchar(20),
	preferencemoney	 NUMERIC(24, 10) 
)

--处理主表信息
INSERT INTO #BillIndex
SELECT 	DISTINCT
		BillCode,
		BillNumberId,
		BillDate,
		etypeid,
		btypeid,
		BillType,
		totalmoney AS Total, 
      	totalinmoney, 
		Comment,
		atypeid,
		TeamNo,
		RedWord,
		preferencemoney
FROM 	BillIndex
WHERE 	BillType IN (305,11,45,34,6,36,93,4,66,160,161,141,145,84,85,148,149,150,151,157,167,168,170,172,178,186)
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND ifcheck = 't' 
		AND draft = 0
		AND BTypeId = @BTypeId
		AND IfYearBill = 0

INSERT INTO #BillIndex
SELECT 	DISTINCT
		Bil.BillCode,
		Bil.BillNumberId,
		Bil.BillDate,
		Bil.etypeid,
		Bil.btypeid,
		Bil.BillType,
		Bil.totalmoney AS Total, 
      	Bil.totalinmoney, 
		Bil.Comment,
		Bil.atypeid,
		Bil.TeamNo,
		Bil.RedWord,
		preferencemoney
FROM 	BillIndex Bil,
		AdDebtBill A
WHERE	BillType IN (115,116,128,129)	
		AND Bil.BillNumberId = A.BillNumberId		
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		AND A.BTypeId = @BTypeId
		AND IfCheck = 't'
		AND Draft = 0
		AND Bil.IfYearBill = 0

--特殊处理会计凭证
INSERT INTO #BillIndex
SELECT	DISTINCT
		A.BillCode,
		A.BillNumberId,
		A.BillDate,
		A.ETypeid,
		L.BTypeid,
		A.BillType,
		CASE A.RedWord 
			WHEN 0 THEN L.Total
			ELSE ABS(L.Total)
		END AS Total,
      	0 AS totalinmoney, 
		A.Comment,
		L.ATypeid,
		A.TeamNo,
		A.RedWord,
		A.preferencemoney
FROM	BillIndex A,
		ListTable L
WHERE	A.BillNumberId = L.BillNumberId
		AND A.BillDate>=@StartDate
		AND A.BillDate<=@EndDate
		AND A.BillType = 159
		AND A.IfCheck = 't'
		AND A.Draft = 0
		AND L.ATypeId IN ('0000100005','0000200001')
		AND L.BTypeId = @BTypeId
		AND A.IfCheck = 't'
		AND A.Draft = 0

--开始运算
SELECT	B.*
INTO	#Result
FROM	(
		SELECT	ZY='销售:'+P.FullName + ' ' + cast(cast(S.Qty as float) as varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord in(0,1) then cast(S.TaxTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord=2 then cast(S.TaxTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode,
				Bil.etypeid,
				S.TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	SaleBill S,
		      	#BillIndex Bil,
		      	#PType P
		WHERE 	Bil.BillType = 11
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 11 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 		THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 11
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='进货:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
				P.FullName,       
				ArAdd=case when Bil.RedWord=2 then  (S.TaxTotal ) else null end,
				ArReduce=case when Bil.RedWord in(0,1) then (S.TaxTotal) else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid,
				S.TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	BuyBill S,
		      	#BillIndex Bil, 
		      	#PType P
		WHERE 	Bil.BillType = 34
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 34
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 		
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 34 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL
		SELECT  ZY='退货:' + P.FullName + ' ' + CAST(CAST(S.Qty AS Float) AS varchar(10)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
				P.FullName,
				ArAdd=case when Bil.RedWord in(0,1) then (S.TaxTotal) else null end,
				ArReduce=case when Bil.RedWord =2 then (S.TaxTotal) else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		     	BuyBackBill S,
		     	#PType P
		WHERE  	Bil.BillType = 6

				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeID
		UNION ALL
		SELECT 	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil 
		WHERE 	Bil.BillType = 6
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='零售:' + P.FullName + ' ' + cast(CAST(S.Qty as float) as varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord in(0,1) then cast(S.TaxTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord=2 then cast(S.TaxTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode,Bil.etypeid,
				S.TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	RetailBill S,
			    #BillIndex Bil,
				#PType P
		WHERE 	Bil.BillType = 305
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT 	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil 
		WHERE 	Bil.BillType = 305
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2 then  Bil.totalinmoney else null end,
				ArReduce=case when Bil.RedWord in(0,1) then  Bil.totalinmoney else null end,		
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid, 
				Bil.TeamNo,
				ID=-1,
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				TeamNo1=null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		     	#BillIndex Bil
		WHERE 	Bil.BillType = 6 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0		
		UNION ALL
		SELECT  ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		     	#BillIndex Bil
		WHERE 	Bil.BillType = 305 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL
		SELECT  ZY='退货:' + P.FullName + ' ' + CAST(CAST(S.Qty as float) AS varchar(10)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
				P.FullName,
				ArAdd=case when Bil.RedWord=2 then (S.TaxTotal) else null end,
				ArReduce=case when Bil.RedWord in(0,1) then (S.TaxTotal) else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
			    SaleBackBill S,
		     	#PType P
		WHERE 	Bil.BillType = 45
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT 	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,	--2004-08-18 谢吉康 调换了和下面一条语句的顺序
				ArReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil 
		WHERE 	Bil.BillType = 45
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='付款:' + B.FullName,
				B.FullName,
				ArAdd=case when Bil.RedWord in(0,1) then S.total else null end, 
				ArReduce=case when Bil.RedWord =2 then S.total else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
				#BType B,
		      	PayBill S      
		WHERE 	Bil.BillType = 66
				AND Bil.BillNumberId = S.BillNumberId
				AND Bil.BTypeId = B.TypeId
		UNION ALL
		SELECT 	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,	--2004-08-18 谢吉康 调换了和下面一条语句的顺序
				ArReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil 
		WHERE 	Bil.BillType = 66
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='返利执行:' + B.FullName,
				B.FullName,
				ArAdd=case when Bil.RedWord =2 then S.total else null end,       
				ArReduce=case when Bil.RedWord in(0,1) then S.total else null end,       
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	#BType B,
		      	Advantage S
		WHERE 	Bil.BillType = 148
				AND Bil.BillNumberId = S.BillNumberId
				AND B.TypeId = Bil.BTypeId
		UNION ALL
		SELECT  ZY='付款:'+A.FullName,
				FullName=NULL,
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
				ArReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				NULL,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 148 		
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND Bil.ATypeId = A.TypeId
		UNION ALL
		SELECT	ZY='价保执行:' + B.FullName,
				B.FullName,
				ArAdd=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,       
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	#BType B,
			    PriceProtectBill S
		WHERE 	Bil.BillType = 149
				AND Bil.BTypeId = B.TypeId
				AND Bil.BillNumberId = S.BillNumberId
		--2004-3-10新增加
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=NULL,
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
				ArReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				NULL,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 149 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND Bil.AtypeId = A.TypeId
		UNION ALL
		SELECT 	ZY='委托代销结算:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
				B.FullName,
				ArAdd=case when Bil.RedWord in(0,1) then S.TaxTotal else null end,             
				ArReduce=case when Bil.RedWord =2 then S.TaxTotal else null end,       
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	#BType B,
		      	CommissionBill S,
				#PType P
		WHERE 	Bil.BillType = 141
				AND Bil.BTypeId = B.TypeId
				AND Bil.BillNumberId = S.BillNumberId
				AND P.TypeId = S.PTypeId
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=NULL,
				ArAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				NULL,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 141 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND A.TypeId = Bil.ATypeId
		UNION ALL
		SELECT 	ZY='受托代销结算:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20)),
				B.FullName,
				ArAdd=case when Bil.RedWord =2 then S.TaxTotal else null end,
				ArReduce=case when Bil.RedWord in(0,1) then S.TaxTotal else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	#BType B,
		      	CommissionBill S,
				#PType P
		WHERE 	Bil.BillType = 145
				AND Bil.BillNumberId = S.BillNumberId
				AND B.TypeId = Bil.BTypeId
				AND P.TypeId = S.PTypeId
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=NULL,     
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
				ArReduce=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				NULL,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 145 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND A.TypeId = Bil.ATypeId
		UNION ALL
		SELECT  ZY='获利执行:' + B.FullName,
				B.FullName,
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	#BType B,
		      	Advantage S
		WHERE 	Bil.BillType = 150
				AND Bil.BillNumberId = S.BillNumberId
				AND Bil.BTypeID = B.TypeID
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=NULL,
				ArAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END, 
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				NULL,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 150 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND Bil.ATypeId = A.TypeId
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord in(0,1)  then Bil.totalinmoney else null end,
				ArReduce=case when Bil.RedWord=2  then Bil.totalinmoney else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 45 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND A.TypeId = Bil.ATypeId
		UNION ALL
		SELECT 	ZY=S.Comment,
				B.FullName,
				ArAdd=case when Bil.RedWord =2 then S.total else null end,
				ArReduce=case when Bil.RedWord in(0,1) then S.total else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				S.BtypeId,  
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	AdDebtBill S,
		      	#BType B
		WHERE 	Bil.BillType in(115,128)
				AND S.BTypeId = B.TypeID
				AND Bil.BillNumberId = S.BillNumberId
		UNION ALL
		SELECT 	ZY='收款:' + B.FullName,
				ArAdd=B.FullName, 
				case when Bil.RedWord =2 then S.total else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then S.total else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo,
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	gatheringBill S,      	
			    #BType B
		WHERE 	Bil.BillType = 4
				AND Bil.BillNumberId = S.BillNumberId
				AND Bil.BTypeId = B.TypeId
		UNION ALL
		SELECT 	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,	
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil 
		WHERE 	Bil.BillType = 4
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY=S.Comment,
				B.FullName,
				ArAdd=case when Bil.RedWord in(0,1)  then S.total else null end,
				ArReduce=case when Bil.RedWord =2  then S.total else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				S.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	AdDebtBill S,
		      	#BType B
		WHERE 	Bil.BillType in(116,129)
				AND Bil.BillNumberId = S.BillNumberId
				AND B.TypeId = S.BTypeID
		UNION ALL
		SELECT	ZY='费用：'+S.Comment, 
				A.FullName, 
				ArAdd=case when Bil.RedWord =2  then S.total else null end, 
				ArReduce=case when Bil.RedWord in(0,1)  then S.total else null end, 
				Bil.BillDate,
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType, 
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	MoneyBill S,
		      	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType =36
				AND A.TypeId = S.ATypeId
				AND Bil.BillNumberId = S.BillNumberID
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord in(0,1)  then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord =2  then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, Bil.BillNumberId, 
				Bil.BillType,null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 36 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND A.TypeId = Bil.ATypeId
		UNION ALL
		SELECT 	ZY=S.Comment, 
				A.FullName, 
				ArAdd=case when Bil.RedWord in(0,1) then S.total else null end,
				ArReduce=case when Bil.RedWord =2 then S.total else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo,
				S.ID,
				Bil.btypeid, 
				Bil.BillNumberId,
				Bil.BillType, 
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	MoneyBill S,
		      	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType =93
				AND Bil.BillNumberId = S.BillNumberId
				AND S.ATypeId = A.TypeId
		UNION ALL
		SELECT	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2  then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1)  then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 93 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND Bil.ATypeId = A.TypeId
		UNION ALL
		SELECT 	ZY='固定资产购买:' + B.FullName,
				B.FullName,
				ArAdd=case when Bil.RedWord =2 then S.total else null end,
				ArReduce=case when Bil.RedWord in(0,1) then S.total else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	#BType B,
		      	MoneyBill S
		WHERE 	Bil.BillType = 84
				AND S.BillNumberId = Bil.BillNumberId
				AND B.TypeId = Bil.BTypeId
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 84 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND Bil.ATypeId = A.TypeId
		UNION ALL
		SELECT 	ZY='固定资产变卖:' + B.FullName,
				B.FullName,
				ArAdd=case when Bil.RedWord in(0,1) then S.total else null end,
				ArReduce=case when Bil.RedWord =2 then S.total else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	#BType B,
		      	MoneyBill S
		WHERE 	Bil.BillType = 85
				AND S.BillNumberId = Bil.BillNumberId
				AND Bil.BTypeId = B.TypeID
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2  then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1)  then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,		
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 85 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0	
				AND Bil.ATypeId = A.TypeId
		UNION ALL
		SELECT 	ZY='商品维修单:' + B.FullName,
				B.FullName,
				ArAdd=case when Bil.RedWord in(0,1) then Bil.total else null end,
				ArReduce=case when Bil.RedWord =2 then Bil.total else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo, 
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null,

				Bil.RedWord,
				Bil.Comment
		FROM  	#BillIndex Bil,
		      	#BType B
		WHERE 	Bil.BillType = 157
				AND Bil.BTypeId = B.TypeId
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=null,      
				ArAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 157 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND Bil.ATypeId = A.TypeId
		UNION ALL                                 --#-01
		SELECT 	ZY='获得价保:' + B.FullName,
				B.FullName,
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total ELSE NULL END, 
				ArReduce=CASE WHEN Bil.RedWord =2 THEN S.total ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				S.TeamNo, 
				S.ID, 
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil,
		      	#BType B,
		      	PriceProtectBill S
		WHERE 	Bil.BillType = 151
				AND Bil.BillNumberId = S.BillNumberId
				AND B.TypeId = Bil.BTypeID
		--2004-3-10新增加
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=NULL,
				ArAdd=CASE WHEN Bil.RedWord =2 THEN Bil.totalinmoney ELSE NULL END,  
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.totalinmoney ELSE NULL END, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo,
				ID=-1,
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				TeamNo1=NULL,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 151 
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
				AND Bil.ATypeId = A.TypeId
		UNION ALL
		SELECT	ZY='应收:'+B.FullName,
				FullName=NULL,
				ArAdd=CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,
				ArReduce=CASE WHEN V.RedWord = 2 THEN ABS(V.Total) ELSE NULL END,
				V.BillDate,
				V.BillCode,
				V.ETypeId,
				V.TeamNo,
				ID=-1,
				V.BTypeId,
				V.BillNumberId,
				V.BillType,
				TeamNo1=NULL,
				V.RedWord,
				V.Comment 
		FROM	#BillIndex V,
				#BType B
		WHERE	V.BTypeId = B.TypeId
				AND V.BillType = 159
				AND V.ATypeId = '0000100005'
		UNION ALL
		SELECT	ZY='应付:'+B.FullName,		
				FullName=NULL,		
				ArAdd=CASE WHEN V.RedWord = 2 THEN ABS(V.Total) ELSE NULL END,
				ArReduce=CASE WHEN V.RedWord IN (0,1) THEN V.Total ELSE NULL END,		
				V.BillDate,
				V.BillCode,
				V.ETypeId,
				V.TeamNo,
				ID=-1,
				V.BTypeId,
				V.BillNumberId,
				V.BillType,
				TeamNo1=NULL,
				V.RedWord,
				V.Comment 
		FROM	#BillIndex V,
				#BType B
		WHERE	V.BTypeId = B.TypeId
				AND V.BillType = 159
				AND V.ATypeId = '0000200001'
		UNION ALL
		--销售换货单      160         收款
		SELECT	ZY=Case S.InOrOut
					when 'O' then
		     			'销售换货出库:' + P.FullName + ' ' + cast(CAST(S.Qty as float) as varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20))
					when 'I' then
		    	 		'销售换货入库:' + P.FullName + ' ' + cast(CAST(S.Qty as float) as varchar(20)) + '*' + CAST(S.TaxPrice AS VARCHAR(20))
				  end,
		      	P.FullName, 
				ArAdd=case S.InOrOut
			    	when 'O' then
		            	case when Bil.RedWord in(0,1) then cast(CAST(S.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
			        when 'I' then
		    	        case when Bil.RedWord=2 then cast(CAST(S.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
		      	end,      
			  	ArReduce=case S.InOrOut
		          	when 'O' then
		            	case when Bil.RedWord=2 then cast(CAST(S.TaxTotal as float) as  NUMERIC(24, 10) ) else null end
		          	when 'I' then
		            	case when Bil.RedWord in(0,1) then cast(CAST(S.TaxTotal as float) as  NUMERIC(24, 10) ) else null end		
		      	end,
				Bil.BillDate,
				Bil.BillCode,Bil.etypeid,
				S.TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				S.TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	SaleGoodsExchangeBill S,
		      	#BillIndex Bil,
		      	#PType P
		WHERE 	Bil.BillType = 160
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeID
		UNION ALL
		SELECT	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 160 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>''
				AND Bil.totalinmoney<>0		
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 160	
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='维修取件:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)), 
				P.FullName,       
				ArAdd=case when Bil.RedWord in(0,1) then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord=2 then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid,
				null AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	Wx_Bill_GetBack S,
		      	#BillIndex Bil, 
		      	#PType P
		WHERE 	Bil.BillType = 167
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 167
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 		
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 167 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL
		SELECT 	ZY='整机更换:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)), 
				P.FullName,       
				ArAdd=case when Bil.RedWord in(0,1) then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord=2 then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid,
				null AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	Wx_Bill_Replace S,
		      	#BillIndex Bil, 
		      	#PType P
		WHERE 	Bil.BillType = 168
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 168
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 		
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 168 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL
		SELECT 	ZY='送修返回:' + P.FullName + ' ' + CAST(cast(S.Qty as float) AS varchar(20)), 
				P.FullName,       
				ArAdd=case when Bil.RedWord=2 then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord in(0,1) then cast(S.Total as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid,
				null AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM 	Wx_Bill_SendBack S,
		      	#BillIndex Bil, 
		      	#PType P
		WHERE 	Bil.BillType = 170
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 170
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT 	ZY='付款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 		
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid, 
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 170 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>'' 
				AND Bil.totalinmoney<>0
		UNION ALL		
		SELECT 	ZY='上门维修单:' + B.FullName,
				B.FullName,
				ArAdd=case when Bil.RedWord in(0,1) then Bil.total else null end,
				ArReduce=case when Bil.RedWord =2 then Bil.total else null end,
				Bil.BillDate, 
				Bil.BillCode,Bil.etypeid, 
				Bil.TeamNo, 
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM  	#BillIndex Bil,
		      	#BType B
		WHERE 	Bil.BillType = 172
				AND Bil.BTypeId = B.TypeId
		UNION ALL
		SELECT	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord =2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord in(0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 172 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>''
				AND Bil.totalinmoney<>0		
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord =2 THEN Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 172	
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT	ZY='维修:'+P.FullName + ' ' + CAST(CAST(S.DiscountTotal AS  NUMERIC(24, 10) ) AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord IN (0,1) then cast(S.DiscountTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord = 2 then cast(S.DiscountTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode,
				Bil.etypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	QP_QuickRepairBill_RepairItems S,
		      	#BillIndex Bil,
		      	Qp_RepairItems P
		WHERE 	Bil.BillType = 178
				AND Bil.BillNumberId = S.BillNumberId
				AND S.RepairItemsTypeId = P.TypeId
				AND S.Insurance = 0
		UNION ALL
		SELECT	ZY='维修:'+P.FullName + ' ' + cast(cast(S.Qty as float) as varchar(20)) + '*' + CAST(S.DiscountPrice AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord IN (0,1) then cast(S.DiscountTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord = 2 then cast(S.DiscountTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode, 
				Bil.etypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	QP_QuickRepairBill_PType S,
		      	#BillIndex Bil,
		      	#PType P
		WHERE 	Bil.BillType = 178
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
				AND S.Insurance = 0
		UNION ALL
		SELECT	ZY='收款:'+A.FullName,
				FullName=null,
				ArAdd=case when Bil.RedWord = 2 then Bil.totalinmoney else null end, 
				ArReduce=case when Bil.RedWord IN (0,1) then Bil.totalinmoney else null end, 
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid, 
				Bil.TeamNo,
				-1,--////////////////////////////////////////////标明该行为表头
				Bil.btypeid,
				Bil.BillNumberId, 
				Bil.BillType,
				null,
				Bil.RedWord,
				Bil.Comment
		FROM 	#AType A,
		      	#BillIndex Bil
		WHERE 	Bil.BillType = 178 
				AND Bil.ATypeId = A.TypeId
				AND Bil.atypeid<>''
				AND Bil.totalinmoney<>0		
		UNION ALL
		SELECT	ZY='优惠金额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord = 2 THEN Bil.preferencemoney ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN (0,1) THEN Bil.preferencemoney ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	#BillIndex Bil
		WHERE 	Bil.BillType = 178	
				AND Bil.preferencemoney<>0
		UNION ALL
		SELECT	ZY='外加工费:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(Bc.EpibolyTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN (2) THEN CAST(Bc.EpibolyTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	BillIndex_CarRepair Bc,
				#BillIndex Bil
		WHERE 	Bc.BillNumberId = Bil.BillNumberId
				AND Bil.BillType = 178	
				and ISNULL(Bc.EpibolyTotal,0) <> 0
		UNION ALL
		SELECT	ZY='其他费用:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(Bc.OtherTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN (2) THEN CAST(Bc.OtherTotal AS  NUMERIC(24, 10) ) ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	BillIndex_CarRepair Bc,
				#BillIndex Bil
		WHERE 	Bc.BillNumberId = Bil.BillNumberId
				AND Bil.BillType = 178
				AND ISNULL(Bc.OtherTotal,0) <> 0	
		UNION ALL
		SELECT	ZY='工时费税额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(ISNULL(Bc.ManHourTaxTotal,0) - ISNULL(Bc.ManHourTotal,0) AS  NUMERIC(24, 10) ) ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN (2) THEN CAST(ISNULL(Bc.ManHourTaxTotal,0) - ISNULL(Bc.ManHourTotal,0) AS  NUMERIC(24, 10) ) ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	BillIndex_CarRepair Bc,
				#BillIndex Bil
		WHERE 	Bc.BillNumberId = Bil.BillNumberId
				AND Bil.BillType = 178
				AND ISNULL(Bc.ManHourTaxTotal,0) - ISNULL(Bc.ManHourTotal,0) <> 0	
		UNION ALL
		SELECT	ZY='材料费税额:',
				FullName=' ',
				ArAdd=CASE WHEN Bil.RedWord IN (0,1) THEN CAST(ISNULL(Bc.PTypeTaxTotal,0) - ISNULL(Bc.PTypeTotal,0) AS  NUMERIC(24, 10) ) ELSE NULL END,
				ArReduce=CASE WHEN Bil.RedWord IN (2) THEN CAST(ISNULL(Bc.PTypeTaxTotal,0) - ISNULL(Bc.PTypeTotal,0) AS  NUMERIC(24, 10) ) ELSE NULL END,
				Bil.BillDate, 
				Bil.BillCode,
				Bil.etypeid,
				Bil.TeamNo,
				ID=-1,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				TeamNo1=' ',
				Bil.RedWord,
				Bil.Comment
		FROM 	BillIndex_CarRepair Bc,
				#BillIndex Bil
		WHERE 	Bc.BillNumberId = Bil.BillNumberId
				AND Bil.BillType = 178
				AND ISNULL(Bc.PTypeTaxTotal,0) - ISNULL(Bc.PTypeTotal,0) <> 0	
		UNION ALL
		SELECT	ZY='理赔:'+P.FullName + ' ' + CAST(CAST(S.InsuranceTotal AS  NUMERIC(24, 10) ) AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord IN (0,1) then cast(S.InsuranceTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord = 2 then cast(S.InsuranceTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode,
				Bil.etypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	QP_InsuranceBill_RepairItems S,
		      	#BillIndex Bil,
		      	Qp_RepairItems P
		WHERE 	Bil.BillType = 186
				AND Bil.BillNumberId = S.BillNumberId
				AND S.RepairItemsTypeId = P.TypeId
		UNION ALL
		SELECT	ZY='理赔:'+P.FullName + ' ' + CAST(CAST(S.InsuranceTotal AS  NUMERIC(24, 10) ) AS VARCHAR(20)),
				P.FullName, 
				ArAdd=case when Bil.RedWord IN (0,1) then cast(S.InsuranceTotal as  NUMERIC(24, 10) ) else null end,
				ArReduce=case when Bil.RedWord = 2 then cast(S.InsuranceTotal as  NUMERIC(24, 10) ) else null end,
				Bil.BillDate,
				Bil.BillCode, 
				Bil.etypeid,
				NULL AS TeamNo,
				S.ID,
				Bil.BtypeId, 
				Bil.BillNumberId,
				Bil.BillType,
				NULL AS TeamNo1,
				Bil.RedWord,
				Bil.Comment
		FROM  	QP_InsuranceBill_PType S,
		      	#BillIndex Bil,
		      	#PType P
		WHERE 	Bil.BillType = 186
				AND Bil.BillNumberId = S.BillNumberId
				AND S.PTypeId = P.TypeId
	)B

DECLARE @SQL varchar(8000)

SET @SQL = 'SELECT * FROM #Result'

IF @showRedWord = 0
	SET @SQL = @SQL + ' WHERE RedWord = 0 '

--排序字段的处理
/*
IF @Orderby=''
	SET @SQL=@SQL+'  ORDER BY billdate,billtype,billcode '
ELSE IF UPPER(@Orderby)='TEAMNO'
	SET @SQL=@SQL+'  ORDER BY ISNULL(TEAMNO,999999999),BillDate,BillType,BillCode '
ELSE IF UPPER(@Orderby)='BILLDATE'
	SET @SQL=@SQL+'  ORDER BY BillDate DESC,BillType,BillCode '
ELSE
	SET @SQL=@SQL+'  ORDER BY '+@Orderby

*/
IF @Orderby=''
	SET @SQL=@SQL+'  ORDER BY billdate,billnumberid,billtype,id'
ELSE
	SET @SQL=@SQL+'  ORDER BY '+@Orderby

EXEC(@SQL)


DROP TABLE #BillIndex,#PType,#AType,#BType,#Result



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryArApWldz_Gsqh_YH_TY]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryArApWldz_Gsqh_YH_TY]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2008-03-26
	描述：往来对账（格式切换），应收查询（统一客户和供货商）
	
	作者：覃雨翔
	日期：2012-06-11
	描述：9.0版本修改，添加原币列
	
	日期:2013-06-05
    作者:鲁大林
    描述:应收查询统计零售退货单、业务类型为变卖的固定资产减少单
		 应付查询统计业务类型为购买的固定资产增加单
	*****固定资产类的新单据只有在系统配置固定资产管理模式为卡片时统计*****
*/
CREATE PROCEDURE Web_QueryArApWldz_Gsqh_YH_TY
(
	@OperatorID 	VARCHAR(100),  	    		--操作员ID号
	@nTYpe        	INT=1,                      --往来单位类型,1:代表客户 2:代表供应商
	@BtypeID      	VARCHAR(100),               --往来单位typeid
	@StartDate   	VARCHAR(10),                --起始日期
	@ENDDate    	VARCHAR(10),                --截至日期
	@showRedWord	INT=1,						--是否显示红冲单据  1.显示   0.不显示
	@stypeid		VARCHAR(MAX),
	@IncludePre		INT=0,
	@orderby		VARCHAR(100),
	@CID            VARCHAR(5)='0',              --币别筛选，0表示所有币种
	@expensetoar    INT=0,
	@dtypeid		VARCHAR(MAX),	--部门
	@DtypeIsVisible	INT			--1=使用部门 0=不使用部门
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
SELECT TypeId,FullName INTO #PType FROM ptype WHERE  SonNum = 0 

--『会员储值』
--SELECT	TypeId,FullName INTO #AType FROM F_GetManATypeAll(@OperatorID) WHERE Deleted = 0 AND SonNum = 0
--INSERT INTO #AType(TypeId,FullName)VALUES('0000200005','『会员储值』')
SELECT nid AS TypeId,FullName,UserCode INTO #AType FROM AC_Items WHERE  SonNum = 0

SELECT	TypeId,FullName INTO #BType FROM F_GetManBTypeAll(@OperatorID) WHERE TypeId = @BTypeId AND SonNum = 0 AND TypeId IN (SELECT * FROM F_GetMANDetailBType(@OperatorID))


IF @CID='0'
  BEGIN
       SET @CID='%%'
  END

CREATE TABLE #BillIndex
(
	BillCode		    VARCHAR(400),
	BillNumberId	    NUMERIC(18,0),
	BillDate		    DATETIME,
	etypeid			    VARCHAR(100),
	dtypeid			    VARCHAR(100),
	ktypeid			    VARCHAR(100),
	btypeid			    VARCHAR(100),
	BillType		    VARCHAR(20),
	Total			     NUMERIC(24, 10) ,
	NTotal			     NUMERIC(24, 10) , 
  	totalinmoney	     NUMERIC(24, 10) ,
  	ntotalinmoney	     NUMERIC(24, 10) , 
	Comment			    VARCHAR(2000),
	atypeid			    VARCHAR(100),
	TeamNo			    INT,
	RedWord			    VARCHAR(20),
	preferencemoney	     NUMERIC(24, 10) ,
	npreferencemoney	 NUMERIC(24, 10) ,
	ifmulaccount	    INT,
	cfullname           VARCHAR(100),
	rate                 NUMERIC(24, 10) ,
	
	explain          VARCHAR(2000),--说明
	CID					INT
)
CREATE TABLE #result
(
    sortid          INT IDENTITY (1,1),
	zy				VARCHAR(400),
	ptypeid			VARCHAR(200),
	qty				 NUMERIC(24, 10) ,
	taxprice		 NUMERIC(24, 10) ,
	ntaxprice		 NUMERIC(24, 10) ,
	incomment		VARCHAR(2000),
	aradd			 NUMERIC(24, 10) ,
	naradd			 NUMERIC(24, 10) ,
	ArReduce		 NUMERIC(24, 10) ,
	NArReduce		 NUMERIC(24, 10) ,
	BillDate		DATETIME,
	BillCode		VARCHAR(400),
	etypeid			VARCHAR(100),
	dtypeid			VARCHAR(100),
	ktypeid			VARCHAR(100),
	TeamNo			INT,
	id				INT,
	btypeid			VARCHAR(100),
	BillNumberId	NUMERIC(18,0),
	BillType		VARCHAR(20),
	TeamNo1			VARCHAR(20),
	RedWord			VARCHAR(20),
	Comment			VARCHAR(2000),
	cfullname       VARCHAR(100),
	rate             NUMERIC(24, 10) ,
	AtypeID         INT,
	goodsnumber			varchar(100),
	
	remark           VARCHAR(2000),--备注
	unit             INT ,--计量单位
	MQty             NUMERIC(24, 10) ,--数量
	MTaxPrice            NUMERIC(24, 10) ,--含税单价
	conversionrelationship VARCHAR(200),--换算关系
	customassistantunit VARCHAR(200), --自定义辅助数量
	BillFlag		INT DEFAULT(0)-- 1:ReceiptBillIndex else 0
)
create table #stype(typeid VARCHAR(100))


--分支机构
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--部门
CREATE TABLE #Dtype(typeid VARCHAR(50))
INSERT #Dtype(typeid) SELECT TypeId FROM F_GetAllBaseTypeId(@dtypeid,9)


CREATE TABLE #atype1(typeid VARCHAR(50))
INSERT INTO #atype1 VALUES('987')
DECLARE @sql VARCHAR(MAX)

if @IncludePre=1
BEGIN
	 INSERT INTO #atype1 VALUES('2131')
END

DECLARE @assets VARCHAR(2)
SELECT @assets= SubValue FROM sysdata WHERE SubNo=732--固定资产管理模式。0：项目；1：卡片

--统计开票
CREATE TABLE #invoiceQty
(
	id	INT,
	ptypeid VARCHAR(50),
	billnumberid NUMERIC(24,10),
	billtype INT,
	uninvoiceqty NUMERIC(24,10),
	uninvoicemoney NUMERIC(24,10),
	nuninvoicemoney NUMERIC(24,10) --原币
)
INSERT INTO #invoiceQty
(
	id,
	ptypeid,
	billnumberid,
	billtype,
	uninvoiceqty,
	uninvoicemoney,
	nuninvoicemoney
) 
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
		400,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.NTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM AppraisalBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    401,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
		
FROM AppraisalBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    402,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM SendBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    403,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM SendBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	

UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    305,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM retailbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    215,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM dbo.RetailBackBill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    11,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM salebill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    45,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM salebackbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(-SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM salegoodsexchangebill a
WHERE a.InOrOut='I'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    160,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM salegoodsexchangebill a
WHERE a.InOrOut='O'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    141,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM commissionbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    12,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM PT_Combin_SaleBillDetail a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    46,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM PT_Combin_SaleBackBillDetail a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    34,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM buybill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id		
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    6,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM buybackbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM(-(a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(-SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM buygoodsexchangebill a
WHERE A.InOrOut='O'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    161,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0),   /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)  /*原币未开票金额(含税)*/
FROM buygoodsexchangebill a
WHERE A.InOrOut='I'
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
UNION ALL
SELECT  a.id,
		a.ptypeid,
		a.BillNumberID,
	    145,
		ISNULL(SUM((a.Qty - a.InvoiceQty)) ,0)  , /*未开票数量*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.TaxPrice ),0) ,  /*本币未开票金额(含税)*/
		ISNULL(SUM((a.Qty - a.InvoiceQty)*a.nTaxPrice ),0)   /*原币未开票金额(含税)*/
FROM commissionbill a
GROUP BY
	a.ptypeid,
	a.BillNumberID ,
	a.id	
	
	--处理主表信息
INSERT INTO #BillIndex
	SELECT 	DISTINCT
			A.BillCode,
			A.BillNumberId,
			A.BillDate,
			A.etypeid,
			A.dtypeid	,
			A.ktypeid,
			A.btypeid,
			A.BillType,
			A.totalmoney AS total,
			A.ntotalmoney AS ntotal,
  			A.totalinmoney,
  			A.ntotalinmoney, 
			A.Comment,
			A.atypeid,
			A.TeamNo,
			A.RedWord,
			A.preferencemoney,
			A.npreferencemoney,
			A.ifmulaccount,
			AC.fullname AS cfullname,
			A.rate,
			A.explain,
			A.CID
	FROM 	BillIndex A
			INNER JOIN #stype s on s.typeid=A.Stypeid
			INNER JOIN #Dtype D ON D.typeid = A.DTypeId
			INNER JOIN AC_currency AC ON A.CID=AC.CID
	WHERE 	A.BillType IN(11,45,215,93,160,141,85,157,167,168,172,178,186,149,148,305,195,181,312,182,179,196,200,12,46)
			AND A.BillDate>=@StartDate
			AND A.BillDate<=@ENDDate
			AND A.ifcheck = 't' 
			AND A.draft = 0
			AND A.BTypeId = @BTypeId
			AND A.IfYearBill = 0
			AND A.CID LIKE @CID
			
INSERT INTO #BillIndex
	SELECT 	DISTINCT
			A.BillCode,
			A.BillNumberId,
			A.BillDate,
			A.etypeid,
			A.dtypeid	,
			CASE WHEN A.OutKTypeId IS NULL OR A.OutKTypeId = ''
			THEN A.InKTypeId
			ELSE A.OutKTypeId
			END,
			A.btypeid,
			A.BillType,
			A.totalmoney AS total,
			A.ntotalmoney AS ntotal,
  			A.totalinmoney,
  			A.ntotalinmoney, 
			A.Comment,
			A.atypeid,
			NULL as TeamNo,
			A.RedWord,
			preferencemoney,
			npreferencemoney,
			A.ifmulaccount,
			AC.fullname AS cfullname,
			A.rate,
			A.Explain,
			A.CID
	FROM 	dbo.Coupon_BillIndex A
			INNER JOIN #stype s on s.typeid=A.Stypeid
			INNER JOIN #Dtype D ON D.typeid = A.DTypeId
			INNER JOIN AC_currency AC ON A.CID=AC.CID
	WHERE 	A.BillType IN(424,426)
			AND A.BillDate>=@StartDate
			AND A.BillDate<=@ENDDate
			AND A.ifcheck = 't' 
			AND A.draft = 0
			AND A.BTypeId = @BTypeId
			AND A.IfYearBill = 0
			AND A.CID LIKE @CID

IF @assets=1
BEGIN
INSERT INTO #BillIndex
SELECT DISTINCT --处理
		A.BillCode,
		A.BillNumberId,
		A.BillDate,
		A.etypeid,
		A.dtypeid	,
		A.ktypeid,
		A.btypeid,
		A.BillType,
		A.totalmoney AS total,
		A.ntotalmoney AS ntotal,
		A.totalinmoney,
		A.ntotalinmoney, 
		A.Comment,
		A.atypeid,
		A.TeamNo,
		A.RedWord,
		A.preferencemoney,
		A.npreferencemoney,
		A.ifmulaccount,
		AC.fullname AS cfullname,
		A.rate,
		A.explain,
		A.CID
FROM 	BillIndex A 
		INNER JOIN #stype s on s.typeid=A.Stypeid
		INNER JOIN #Dtype D ON D.typeid = A.DTypeId
		INNER JOIN AC_currency AC ON A.CID=AC.CID
WHERE 	A.BillType=213
		AND A.BillDate>=@StartDate
		AND A.BillDate<=@ENDDate
		AND A.ifcheck = 't' 
		AND A.draft = 0
		AND A.BTypeId = @BTypeId
		AND A.IfYearBill = 0
		AND A.CID LIKE @CID
		AND A.AssetBusinessTypeId IN(SELECT Id FROM  Ac_AssetBusinessType WHERE FullName='变卖')
END

IF @expensetoar=1
  BEGIN
       INSERT INTO #BillIndex
	    SELECT 	DISTINCT
			   A.BillCode,
			   A.BillNumberId,
			   A.BillDate,
			   A.etypeid,
			   A.dtypeid,
			   A.ktypeid,
			   A.btypeid,
			   A.BillType,
			   A.totalmoney AS total,
			   A.ntotalmoney AS ntotal,
  			   A.totalinmoney,
  			   A.ntotalinmoney, 
			   A.Comment,
			   A.atypeid,
			   A.TeamNo,
			   A.RedWord,
			   A.preferencemoney,
			   A.npreferencemoney,
			   A.ifmulaccount,
			   AC.fullname AS cfullname,
			   A.rate,
			   A.explain,
			   A.CID
	     FROM BillIndex A
		 INNER JOIN #stype s on s.typeid=A.Stypeid
		 INNER JOIN #Dtype D ON D.typeid = A.DTypeId
		 INNER JOIN AC_currency AC ON A.CID=AC.CID
	     WHERE 	A.BillType=36
			AND A.BillDate>=@StartDate
			AND A.BillDate<=@ENDDate
			AND A.ifcheck = 't' 
			AND A.draft = 0
			AND A.BTypeId = @BTypeId
			AND A.BtypeID LIKE '00001%'
			AND A.IfYearBill = 0
			AND A.CID LIKE @CID
  END

INSERT INTO #BillIndex			
SELECT DISTINCT
		Bil.BillCode,
		Bil.BillNumberId,
		Bil.BillDate,
		Bil.etypeid,
		bil.DTypeId,
		bil.ktypeid,
		Bil.btypeid,
		Bil.BillType,
		Bil.totalmoney AS Total,
		Bil.ntotalmoney AS NTotal, 
      	Bil.totalinmoney,
      	Bil.ntotalinmoney, 
		Bil.Comment,
		Bil.atypeid,
		Bil.TeamNo,
		Bil.RedWord,
		bil.preferencemoney,
		bil.npreferencemoney,
		bil.ifmulaccount,
		AC.fullname AS cfullname,
		Bil.rate,
		Bil.explain,
		Bil.CID
FROM 	BillIndex Bil
INNER JOIN AC_currency AC ON Bil.CID=AC.CID
INNER JOIN PreBill P ON Bil.BillNumberID=P.BillNumberID
INNER JOIN #stype S ON Bil.StypeId=s.typeid
INNER JOIN #Dtype D ON D.typeid = Bil.DTypeId
WHERE	bil.BillType=189	
		AND BillDate>=@StartDate
		AND BillDate<=@ENDDate
		AND Bil.BTypeId = @BTypeId
		AND IfCheck = 't'
		AND Draft = 0
		AND Bil.IfYearBill = 0
		AND Bil.CID LIKE @CID
		
		
	INSERT INTO #BillIndex
	SELECT DISTINCT
			Bil.BillCode,
			Bil.BillNumberId,
			Bil.BillDate,
			Bil.etypeid,
			bil.DTypeId,
			bil.ktypeid,
			Bil.btypeid,
			Bil.BillType,
			Bil.totalmoney AS Total,
			Bil.ntotalmoney AS NTotal, 
      		Bil.totalinmoney,
      		Bil.ntotalinmoney, 
			Bil.Comment,
			Bil.atypeid,
			Bil.TeamNo,
			Bil.RedWord,
			Bil.preferencemoney,
			Bil.npreferencemoney,
			Bil.ifmulaccount,
			AC.fullname AS cfullname,
			Bil.rate,
			Bil.explain,
			Bil.CID
	FROM 	BillIndex Bil
	INNER JOIN AC_currency AC ON Bil.CID=AC.CID
	INNER JOIN AdDebtBill A ON Bil.BillNumberID=A.BillNumberId
	INNER JOIN #stype S ON A.StypeID=S.TypeId
	INNER JOIN #Dtype D ON D.typeid = Bil.DTypeId
	WHERE	BillType IN (115,116)	
			AND BillDate>=@StartDate
			AND BillDate<=@ENDDate
			AND A.BTypeId = @BTypeId
			AND IfCheck = 't'
			AND Draft = 0
			AND Bil.IfYearBill = 0
			AND Bil.CID LIKE @CID
			
  INSERT INTO #BillIndex
SELECT DISTINCT
			Bil.BillCode,
			Bil.BillNumberId,
			Bil.BillDate,
			Bil.etypeid,
			bil.DTypeId,
			bil.ktypeid,
			Bil.btypeid,
			Bil.BillType,
			Bil.totalmoney AS Total,
			Bil.ntotalmoney AS NTotal, 
      		Bil.totalinmoney,
      		Bil.ntotalinmoney, 
			Bil.Comment,
			Bil.atypeid,
			Bil.TeamNo,
			Bil.RedWord,
			Bil.preferencemoney,
			Bil.npreferencemoney,
			Bil.ifmulaccount,
			AC.fullname AS cfullname,
			Bil.rate,
			Bil.explain,
			Bil.CID
FROM 	BillIndex Bil
		INNER JOIN ChargeOffBill A ON Bil.BillNumberId=A.BillNumberId
		INNER JOIN #stype s ON Bil.stypeid=s.typeid
		INNER JOIN #Dtype D ON D.typeid = Bil.DTypeId
		INNER JOIN AC_currency Ac ON Bil.CID=AC.CID
WHERE	BillType=450
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
		--AND A.BTypeId = @BTypeId
		AND IfCheck = 't'
		AND Draft = 0
		AND Bil.IfYearBill = 0
		AND Bil.CID LIKE @CID
	--特殊处理会计凭证
	INSERT INTO #BillIndex
	SELECT	
			A.BillCode,
			A.BillNumberId,
			A.BillDate,
			A.ETypeid,
			A.DTypeId,
			A.ktypeid,
			L.BTypeid,
			A.BillType,
			0 AS Total,
		    0 AS NTotal,
      		0 AS totalinmoney, 
      		0 AS ntotalinmoney, 
			A.Comment,
			L.ATypeid,
			A.TeamNo,
			A.RedWord,
			A.preferencemoney,
			A.npreferencemoney,
			A.ifmulaccount,
			AC.fullname AS cfullname,
			AC.rate,
			A.explain,
			L.CID
	FROM	BillIndex A
	INNER JOIN ListTable L ON A.BillNumberID=L.BillNumberID and a.BillType=l.BillType
	INNER JOIN AC_currency AC ON L.CID=AC.CID
	INNER JOIN #stype S ON A.Stypeid=s.typeid
	INNER JOIN #Dtype D ON D.typeid = A.DTypeId
	INNER JOIN AC_Items ACI ON L.AtypeId=ACI.nid
	WHERE	A.BillType = 159
			AND A.BillDate>=@StartDate
			AND A.BillDate<=@ENDDate
			AND A.IfCheck = 't'
			AND A.Draft = 0
			AND ACI.UserCode IN (SELECT typeid FROM #atype1)
			AND L.BTypeId = @BTypeId
			AND L.CID LIKE @CID
			
   
   --特殊处理收款单			
   INSERT INTO #BillIndex
	SELECT	
			A.BillCode,
			A.BillNumberId,
			A.BillDate,
			A.ETypeid,
			A.DTypeId,
			A.ktypeid,
			a.BTypeid,
			A.BillType,
		    0 AS Total,
		    0 AS NTotal,
      		0 AS totalinmoney, 
      		0 AS ntotalinmoney, 
			A.Comment,
			NULL AS ATypeid,
			A.TeamNo,
			A.RedWord,
			A.preferencemoney,
			A.npreferencemoney,
			A.ifmulaccount,
			AC.fullname AS cfullname,
			A.rate,
			A.explain,
			A.CID
	FROM	BillIndex A
	INNER JOIN AC_currency AC ON a.CID=AC.CID
	INNER JOIN #stype S ON A.Stypeid=s.typeid
	INNER JOIN #Dtype D ON D.typeid = A.DTypeId
	--INNER JOIN AC_Items ACI ON L.AtypeId=ACI.nid
	WHERE	A.BillType = 4	
			AND A.BillDate>=@StartDate
			AND A.BillDate<=@ENDDate		
			AND a.BTypeId = @BTypeId
			AND A.IfCheck = 't'
			AND A.Draft = 0
			AND A.ifYearBill=0
			--AND (ACI.TypeName='B' OR ACI.UserCode='2131' OR ACI.UserCode='2181' OR ACI.UserCode='0456')  --需要查银行账户，预收资金，会员储值充值

			AND a.CID LIKE @CID		
				
set @sql='
	INSERT INTO #Result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		aradd,
		naradd,
		ArReduce,
		NArReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname ,
		rate,
		AtypeID,
		goodsnumber,

		remark,
		unit,
		MQty,
		MTaxPrice,
		conversionrelationship,
		customassistantunit                      
	)  
	SELECT	B.*
	FROM	(
			SELECT	ZY='''',--''销售:''+P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					P.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment, 
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.NTaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					
					Bil.EXPLAIN  remark,
					s.MUnitID as unit,
					s.MQty,
					s.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,S.Qty) as customassistantunit           
					
			FROM  	SaleBill S
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
		      		#BillIndex Bil,
		      		#PType P		      		
			WHERE 	Bil.BillType = 11
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
			UNION ALL
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd= 0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.preferencemoney
								ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.npreferencemoney
								ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 11
					AND Bil.preferencemoney<>0		
			UNION ALL  --优惠券出库单
			SELECT	ZY='''',
					'''' AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					0 as taxprice,
					0 as ntaxprice,
					'''' AS incomment, 
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.Total AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.Total AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.NTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.NTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid as ktypeid,
					null as TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					null as TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM  	coupon_OutBill S,
		      		#BillIndex Bil
			WHERE 	Bil.BillType = 424
					AND Bil.BillNumberId = S.BillNumberId
			UNION ALL
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd= 0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.preferencemoney
								ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.npreferencemoney
								ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 424
					AND Bil.preferencemoney<>0		
			UNION ALL  --优惠券退货单
			SELECT	ZY='''',
					'''' AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					0 as taxprice,
					0 as ntaxprice,
					'''' AS incomment, 
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(-S.Total AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(S.Total AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(-S.NTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(S.NTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid as ktypeid,
					null as TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					null as TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''' as goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM  	coupon_BackBill S,
		      		#BillIndex Bil
			WHERE 	Bil.BillType = 426
					AND Bil.BillNumberId = S.BillNumberId
			UNION ALL
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd = CASE WHEN Bil.RedWord IN(0,1) THEN Bil.preferencemoney 
							   WHEN Bil.RedWord=2 THEN -Bil.preferencemoney
							   ELSE 0 END,
					NArAdd = CASE WHEN Bil.RedWord IN(0,1) THEN Bil.npreferencemoney 
							   WHEN Bil.RedWord=2 THEN -Bil.npreferencemoney
							   ELSE 0 END,
					ArReduce = 0,
					NArReduce = 0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 426
					AND Bil.preferencemoney<>0		
			UNION ALL
					SELECT	ZY='''',--''零售:''+P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					p.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment, 
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.NTaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					Bil.EXPLAIN  remark,
					s.MUnitID as unit,
					s.MQty,
					s.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,S.Qty) as customassistantunit  
			FROM 	RetailBill S 
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
					#BillIndex Bil,
					#PType P
			WHERE 	Bil.BillType = 305
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
			UNION ALL
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd= 0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.preferencemoney
								ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.npreferencemoney
								ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 305
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT  '''',-- ZY=''退货:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(10)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					p.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN -s.qty
							 WHEN Bil.RedWord=2 THEN  s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN (-S.TaxTotal)
							 WHEN Bil.RedWord=2 THEN (S.TaxTotal) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN (-S.NTaxTotal)
							 WHEN Bil.RedWord=2 THEN (S.NTaxTotal) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					Bil.EXPLAIN  remark,
					s.MUnitID as unit,
					s.MQty,
					s.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,S.Qty) as customassistantunit  
			FROM 	#BillIndex Bil,
					SaleBackBill S 
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
		     		#PType P
			WHERE 	Bil.BillType = 45
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
			UNION ALL
			SELECT  '''',
					p.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN -s.qty
							 WHEN Bil.RedWord=2 THEN  s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN (-S.TaxTotal)
							 WHEN Bil.RedWord=2 THEN (S.TaxTotal) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN (-S.NTaxTotal)
							 WHEN Bil.RedWord=2 THEN (S.NTaxTotal) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					Bil.EXPLAIN  remark,
					s.MUnitID as unit,
					s.MQty,
					s.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,S.Qty) as customassistantunit  
			FROM 	#BillIndex Bil,
					RetailBackBill S
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
		     		#PType P
			WHERE 	Bil.BillType = 215
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
			UNION ALL
			SELECT 	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney 
							WHEN Bil.RedWord =2 THEN -Bil.preferencemoney ELSE 0 END,	--2004-08-18 谢吉康 调换了和下面一条语句的顺序
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.npreferencemoney 
							WHEN Bil.RedWord =2 THEN -Bil.npreferencemoney ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil 
			WHERE 	Bil.BillType = 45
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney 
							WHEN Bil.RedWord =2 THEN -Bil.preferencemoney ELSE 0 END,	
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.npreferencemoney 
							WHEN Bil.RedWord =2 THEN -Bil.npreferencemoney ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil 
			WHERE 	Bil.BillType = 215
					AND Bil.preferencemoney<>0 '
set @sql=@sql+		'	
			UNION ALL
			SELECT 	ZY='''',--''委托代销结算:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					p.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.TaxTotal 
								WHEN Bil.RedWord =2   THEN -S.TaxTotal ELSE 0 END,
				    NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.NTaxTotal 
								WHEN Bil.RedWord =2   THEN -S.NTaxTotal ELSE 0 END,             
					ArReduce=0, 
					NArReduce=0,        
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					Bil.EXPLAIN remark,
					s.MUnitID as unit,
					s.MQty,
					s.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,S.Qty) as customassistantunit  
			FROM 	#BillIndex Bil,
		      		#BType B,
		      		CommissionBill S
		      		LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
					#PType P
			WHERE 	Bil.BillType = 141
					AND Bil.BTypeId = B.TypeId
					AND Bil.BillNumberId = S.BillNumberId
					AND P.TypeId = S.PTypeId
			UNION ALL
			'
set @sql=@sql+		'	
			SELECT 	ZY=S.Comment,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) AND s.total>0 THEN S.total 
								WHEN Bil.RedWord =2 AND s.total>0 THEN -S.total ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) AND s.ntotal>0 THEN S.ntotal 
								WHEN Bil.RedWord =2 AND s.ntotal>0 THEN -S.ntotal ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					S.TeamNo, 
					S.ID, 
					S.BtypeId,  
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
		      		AdDebtBill S,
		      		#BType B
			WHERE 	Bil.BillType =115
					AND S.BTypeId = B.TypeID
					AND Bil.BillNumberId = S.BillNumberId
			UNION ALL
			SELECT 	ZY=''收款:'' + AC.FullName,
					'' '',
					0,
					0,
					0,
					G.COMMENT,
					ArAdd=0,
					NArAdd=0, 
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN G.total 
								WHEN Bil.RedWord =2  THEN -G.total ELSE 0 END, 
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN G.ntotal  
								WHEN Bil.RedWord =2  THEN -G.ntotal ELSE 0 END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					bil.TeamNo,
					ID=-1, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					G.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil   
		INNER JOIN gatheringbill G ON BIL.BILLNUMBERID=G.BILLNUMBERID
	  INNER JOIN	#BType B ON Bil.BtypeId=B.TypeId
	  INNER JOIN    AC_Items AC ON G.atypeid=AC.nid
			WHERE 	Bil.BillType = 4
					AND AC.TypeName=''B'' 
		   UNION ALL
			SELECT 	ZY=''收款:'' + AC.FullName,
					'' '',
					0,
					0,
					0,
					G.COMMENT,
					ArAdd=0,
					NArAdd=0, 
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN G.total 
								WHEN Bil.RedWord =2  THEN -G.TOTAL ELSE 0 END, 
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN G.ntotal  
								WHEN Bil.RedWord =2  THEN -G.ntotal ELSE 0 END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					bil.TeamNo,
					ID=-1, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					G.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil    	
			INNER JOIN gatheringbill G ON BIL.BILLNUMBERID=G.BILLNUMBERID
	  INNER JOIN	#BType B ON Bil.BtypeId=B.TypeId
	  INNER JOIN    AC_Items AC ON G.atypeid=AC.nid
			WHERE 	Bil.BillType = 4
					AND AC.UserCode=''2181''
			UNION ALL
			SELECT 	ZY=''收款:优惠金额'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=0,
					NArAdd=0, 
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN bil.preferencemoney 
								WHEN Bil.RedWord =2  THEN -bil.preferencemoney ELSE 0 END, 
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN bil.npreferencemoney  
								WHEN Bil.RedWord =2  THEN -bil.npreferencemoney ELSE 0 END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					bil.TeamNo,
					ID=-1, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					'''',
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil    
	  INNER JOIN	#BType B ON Bil.BtypeId=B.TypeId
			WHERE 	Bil.BillType = 4
			        AND Bil.preferencemoney<>0 
			UNION ALL
			SELECT 	ZY=''收款:'' + AC.FullName,
					'' '',
					0,
					0,
					0,
					G.COMMENT,
					ArAdd=0, 
					NArAdd=0, 
					ArReduce=CASE WHEN Bil.RedWord IN(0,1)  THEN G.total
					              WHEN Bil.RedWord =2  THEN -G.total ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1)  THEN G.ntotal
					          WHEN Bil.RedWord =2  THEN -G.ntotal ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					bil.TeamNo,
					ID=-1, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1=NULL,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					G.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil 	
			INNER JOIN gatheringbill G ON BIL.BILLNUMBERID=G.BILLNUMBERID
	  INNER JOIN	#BType B ON Bil.BtypeId=B.TypeId
	  INNER JOIN    AC_Items AC ON G.AtypeId=AC.nid
			WHERE 	Bil.BillType = 4
					AND AC.UserCode=''2131''
					AND '+CAST(@IncludePre AS VARCHAR)+'<>1
			UNION ALL
			SELECT 	ZY=S.Comment,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) AND s.total>0  THEN S.total 
								WHEN Bil.RedWord =2 AND s.total>0  THEN -S.total ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) AND s.ntotal>0  THEN S.ntotal 
								WHEN Bil.RedWord =2 AND s.ntotal>0  THEN -S.ntotal ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					S.TeamNo, 
					S.ID, 
					S.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
		      		AdDebtBill S,
		      		#BType B
			WHERE 	Bil.BillType =116
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeId = S.BTypeID
			UNION ALL
			'
IF @assets=1
	SET @sql=@sql+'
			SELECT 	ZY=''固定资产减少:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total 
								 WHEN Bil.RedWord =2  THEN -S.total ELSE 0 END,
				    NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.ntotal 
								 WHEN Bil.RedWord =2  THEN -S.ntotal ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
		      		#BType B,
		      		MoneyBill S
			WHERE 	Bil.BillType = 213
					AND S.BillNumberId = Bil.BillNumberId
					AND Bil.BTypeId = B.TypeID
			UNION ALL
	'
set @sql=@sql+		'	
			SELECT 	ZY=S.Comment, 
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total 
								 WHEN Bil.RedWord =2 THEN -S.total ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.ntotal 
								 WHEN Bil.RedWord =2  THEN -S.ntotal ELSE 0 END,
					ArReduce=0,
					ArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					bil.TeamNo,
					S.ID,
					Bil.btypeid, 
					Bil.BillNumberId,
					Bil.BillType, 
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#AType A,
					moneybill s,
		      		#BillIndex Bil
			WHERE 	Bil.BillType =93
					and s.billnumberid=bil.billnumberid
					AND S.ATypeId = A.TypeId
			UNION ALL
			SELECT 	ZY=''固定资产减少:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.taxtotal 
								 WHEN Bil.RedWord =2  THEN -S.taxtotal ELSE 0 END,
				    NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.ntaxtotal 
								 WHEN Bil.RedWord =2  THEN -S.ntaxtotal ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					bil.TeamNo,
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					--S.TeamNo1,
					'''',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
					AssetIncDecBill s,
		      		#BType B
			WHERE 	Bil.BillType = 213
					and s.billnumberid=bil.billnumberid
					AND Bil.BTypeId = B.TypeID
			UNION ALL
			SELECT 	ZY=''固定资产变卖:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.total 
								 WHEN Bil.RedWord =2  THEN -S.total ELSE 0 END,
				    NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN S.ntotal 
								 WHEN Bil.RedWord =2  THEN -S.ntotal ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					bil.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
					moneybill s ,
		      		#BType B
			WHERE 	Bil.BillType = 85
					and s.billnumberid=bil.billnumberid
					AND Bil.BTypeId = B.TypeID
			UNION ALL
			SELECT 	ZY=''价保执行:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ApAdd=0,
					NApAdd=0, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total 
								WHEN Bil.RedWord =2 THEN -S.total ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total 
								WHEN Bil.RedWord =2 THEN -S.total ELSE 0 END,          
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					bil.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
      				#BType B,
      				PriceProtectBill S
			WHERE 	Bil.BillType = 149	
					AND Bil.BillNumberId = S.BillNumberId
					AND B.TypeId = Bil.BTypeID
			UNION ALL
			SELECT 	ZY=''返利执行:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ApAdd=0,
					NApAdd=0,       
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total
								WHEN Bil.RedWord =2 THEN -S.total ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total
								WHEN Bil.RedWord =2 THEN -S.total ELSE 0 END,       
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					bil.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
      				#BType B,
		      		Advantage S
			WHERE 	Bil.BillType = 148
					AND Bil.BillNumberId = S.BillNumberId
					AND Bil.BTypeId = B.TypeID
			UNION ALL
			'
set @sql=@sql+		'	
			SELECT	ZY=''应收:''+B.FullName,
					'' '',
					0,
					0,
					0,
					CASE
						WHEN  acd.j_Total<>0 THEN acd.comment
						WHEN acd.d_total <>0 THEN acd.comment
						ELSE ''''
					END AS incomment,
					ArAdd=CASE WHEN V.RedWord IN (0,1) AND acd.j_Total<>0 THEN acd.j_Total 
								WHEN V.RedWord = 2 AND acd.j_Total<>0 THEN -acd.j_Total ELSE 0 END,
					NArAdd=CASE WHEN V.RedWord IN (0,1) AND acd.nj_Total<>0 THEN acd.nj_Total 
								WHEN V.RedWord = 2 AND acd.nj_Total<>0 THEN -acd.nj_Total ELSE 0 END,
					ArReduce=CASE WHEN V.RedWord IN (0,1) AND acd.d_total<>0 THEN acd.d_total 
									WHEN V.RedWord = 2 AND acd.d_total<>0 THEN -acd.d_total ELSE 0 END,
					NArReduce=CASE WHEN V.RedWord IN (0,1) AND acd.nd_total<>0 THEN acd.nd_total 
									WHEN V.RedWord = 2 AND acd.nd_total<>0 THEN -acd.nd_total ELSE 0 END,
					V.BillDate,
					V.BillCode,
					V.ETypeId,
					v.dtypeid,
					v.ktypeid,
					V.TeamNo,
					ID=-1,
					V.BTypeId,
					V.BillNumberId,
					V.BillType,
					TeamNo1=NULL,
					V.RedWord,
					V.Comment,
					V.cfullname,
					V.rate,											   
					V.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM	#BillIndex V
			INNER JOIN	#BType B ON V.BTypeId=B.TypeId
			INNER JOIN    AC_Items AC ON V.AtypeId=AC.nid 
			INNER JOIN accountcredence acd on acd.billnumberid = v.billnumberid AND acd.atypeid=B.typeid AND v.cid=acd.cid
			WHERE   V.BillType = 159
					AND AC.UserCode = ''987''
					AND acd.TypeATypeID=ac.nid
			UNION ALL
			SELECT	ZY=''预收:''+B.FullName,
					'' '',
					0,
					0,
					0,
					CASE
						WHEN  acd.j_Total<>0 THEN acd.comment
						WHEN acd.d_total <>0 THEN acd.comment
						ELSE ''''
					END AS incomment,
					ArAdd=CASE WHEN V.RedWord IN (0,1) AND acd.j_Total<>0 THEN acd.j_Total 
								WHEN V.RedWord = 2 AND acd.j_Total<>0 THEN -acd.j_Total ELSE 0 END,
					NArAdd=CASE WHEN V.RedWord IN (0,1) AND acd.nj_Total<>0 THEN acd.nj_Total 
								WHEN V.RedWord = 2 AND acd.nj_Total<>0 THEN -acd.nj_Total ELSE 0 END,
					ArReduce=CASE WHEN V.RedWord IN (0,1) AND acd.d_total<>0 THEN acd.d_total 
									WHEN V.RedWord = 2 AND acd.d_total<>0 THEN -acd.d_total ELSE 0 END,
					NArReduce=CASE WHEN V.RedWord IN (0,1) AND acd.nd_total<>0 THEN acd.nd_total 
									WHEN V.RedWord = 2 AND acd.nd_total<>0 THEN -acd.nd_total ELSE 0 END,
					V.BillDate,
					V.BillCode,
					V.ETypeId,
					v.dtypeid,
					v.ktypeid,
					V.TeamNo,
					ID=-1,
					V.BTypeId,
					V.BillNumberId,
					V.BillType,
					TeamNo1=NULL,
					V.RedWord,
					V.Comment,
					V.cfullname,
					V.rate,
					V.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM	#BillIndex V
			INNER JOIN	#BType B ON V.BTypeId = B.TypeId
			INNER JOIN    AC_Items AC ON V.AtypeId=AC.nid
			INNER JOIN accountcredence acd on acd.billnumberid = v.billnumberid AND acd.atypeid=B.typeid AND v.cid=acd.cid
			WHERE	V.BillType = 159
					AND AC.UserCode = ''2131''
					AND acd.TypeATypeID=ac.nid
			UNION ALL
			--销售换货单      160         收款
			SELECT	ZY=CASE S.InOrOut
						WHEN ''O'' THEN
		     				''''--''销售换货出库:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20))
						WHEN ''I'' THEN
		    	 			''''--''销售换货入库:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20))
					  END,
		      		p.typeid AS ptypeid,
		      	   qty=
				    CASE  WHEN S.InOrOut=''O'' AND Bil.Redword IN (0,1) THEN s.qty
					      WHEN S.InOrOut=''I'' AND Bil.Redword IN (0,1) THEN  -s.qty 
					      WHEN S.InOrOut=''O'' AND Bil.Redword IN (2) THEN -s.qty
					      WHEN S.InOrOut=''I'' AND Bil.Redword IN (2) THEN s.qty
					      ELSE 0 END ,
		      		s.taxprice,
		      		s.ntaxprice,
		      		s.comment AS incomment,
					ArAdd=CASE S.InOrOut
						WHEN ''O'' THEN
		            		CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) )
		            			WHEN  Bil.RedWord=2 THEN CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) 
		            		ELSE 0 END
		            	ELSE 0
		      		END,
		      		NArAdd=CASE S.InOrOut
						WHEN ''O'' THEN
		            		CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.NTaxTotal AS  NUMERIC(24, 10) )
		            			WHEN  Bil.RedWord=2 THEN CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) 
		            		ELSE 0 END
		            	ELSE 0
		      		END,      
			  		ArReduce=CASE S.InOrOut
		            	WHEN ''I'' THEN
		            		CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) ) 
								 WHEN Bil.RedWord=2 THEN CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) 
							ELSE 0 END
						ELSE 0	
		      		END,
		      		NArReduce=CASE S.InOrOut
		            	WHEN ''I'' THEN
		            		CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.NTaxTotal AS  NUMERIC(24, 10) ) 
								 WHEN Bil.RedWord=2 THEN CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) 
							ELSE 0 END
						ELSE 0	
		      		END,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					'''' remark,
					s.MUnitID as unit,
					s.MQty,
					s.CurMTaxPrice,
					''1''+PU.fullname+''=''+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,Qty) as customassistantunit
			FROM 	SaleGoodsExchangeBill S
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID ,
		      		#BillIndex Bil,
		      		#PType P
			WHERE 	Bil.BillType = 160
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeID
			UNION ALL
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney
								WHEN Bil.RedWord =2 THEN -Bil.preferencemoney ELSE 0 END,
				    NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.npreferencemoney
								WHEN Bil.RedWord =2 THEN -Bil.npreferencemoney ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 160	
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY='''',--''维修取件:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)), 
					P.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					0,
					0,
					s.comment AS incomment,       
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.Total AS  NUMERIC(24, 10) )
								 WHEN Bil.RedWord=2 THEN CAST(-S.Total AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.Total AS  NUMERIC(24, 10) )
								 WHEN Bil.RedWord=2 THEN CAST(-S.Total AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					NULL AS TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					NULL AS TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	Wx_Bill_GetBack S,
		      		#BillIndex Bil, 
		      		#PType P
			WHERE 	Bil.BillType = 167
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
			UNION ALL  
			'
set @sql=@sql+		'	
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.preferencemoney 
									WHEN Bil.RedWord =2 THEN  -Bil.preferencemoney ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.npreferencemoney 
									WHEN Bil.RedWord =2 THEN  -Bil.npreferencemoney ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 167
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT 	ZY='''',--''整机更换:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)), 
					P.typeid AS ptypedid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					0,
					0,
					s.comment AS incomment,       
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) AND s.Total>0 THEN CAST(S.Total AS  NUMERIC(24, 10) )
								WHEN Bil.RedWord=2 AND s.Total>0 THEN CAST(-S.Total AS  NUMERIC(24, 10) )  ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) AND s.Total>0 THEN CAST(S.Total AS  NUMERIC(24, 10) )
								WHEN Bil.RedWord=2 AND s.Total>0 THEN CAST(-S.Total AS  NUMERIC(24, 10) )  ELSE 0 END,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) AND s.Total<0 THEN CAST(S.Total AS  NUMERIC(24, 10) )
								WHEN Bil.RedWord=2 AND s.Total<0 THEN CAST(-S.Total AS  NUMERIC(24, 10) )  ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) AND s.Total<0 THEN CAST(S.Total AS  NUMERIC(24, 10) )
								WHEN Bil.RedWord=2 AND s.Total<0 THEN CAST(-S.Total AS  NUMERIC(24, 10) )  ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					NULL AS TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					NULL AS TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					'''' remark,
					0 as unit,
					0,
					0,
					'''' as conversionrelationship,
					'''' as customassistantunit  
			FROM 	Wx_Bill_Replace S,
		      		#BillIndex Bil, 
		      		#PType P
			WHERE 	Bil.BillType = 168
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
			UNION ALL
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.preferencemoney 
									 WHEN Bil.RedWord =2 THEN  -Bil.preferencemoney ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN Bil.npreferencemoney 
									 WHEN Bil.RedWord =2 THEN  -Bil.npreferencemoney ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 168
					AND Bil.preferencemoney<>0
			UNION ALL
			'
set @sql=@sql+		'	
			SELECT 	ZY=''上门维修单:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) AND bil.Total>0 THEN Bil.total
								WHEN Bil.RedWord =2 AND bil.Total>0 THEN -Bil.total ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) AND bil.NTotal>0 THEN Bil.ntotal
								WHEN Bil.RedWord =2 AND bil.NTotal>0 THEN -Bil.ntotal ELSE 0 END,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) AND bil.Total<0 THEN -Bil.total
								 WHEN Bil.RedWord =2 AND bil.Total<0 THEN Bil.total ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) AND bil.NTotal<0 THEN -Bil.ntotal
								 WHEN Bil.RedWord =2 AND bil.NTotal<0 THEN Bil.ntotal ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					Bil.TeamNo, 
					-1,--////////////////////////////////////////////标明该行为表头
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					NULL,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM  	#BillIndex Bil,
		      		#BType B
			WHERE 	Bil.BillType = 172
					AND Bil.BTypeId = B.TypeId
			UNION ALL
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.preferencemoney
								 WHEN Bil.RedWord =2 THEN -Bil.preferencemoney ELSE 0 END,
				    NArReduce=CASE WHEN Bil.RedWord IN(0,1) THEN  Bil.npreferencemoney
								 WHEN Bil.RedWord =2 THEN -Bil.npreferencemoney ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 172	
					AND Bil.preferencemoney<>0
			UNION ALL
			'
set @sql=@sql+		'	
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd= 0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2  	THEN  -Bil.preferencemoney
								ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2  	THEN  -Bil.npreferencemoney
								ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
				    Bil.rate,
				    Bil.AtypeID,
				    '''',
				    explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 178	
					AND Bil.preferencemoney<>0
			'
			
--会员储值充值
Set @sql=@sql+' UNION ALL
				SELECT	ZY=''会员储值充值'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(bil.Total AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-bil.Total AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(bil.NTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-bil.NTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM  
		      		#BillIndex Bil
			WHERE 	Bil.BillType = 181
			UNION ALL
			
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd= 0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.preferencemoney
								ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.npreferencemoney
								ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 181
					AND Bil.preferencemoney<>0
'

--会员批量储值充值
Set @sql=@sql+' UNION ALL
				SELECT	ZY=''会员批量储值充值'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(bil.Total AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-bil.Total AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(bil.NTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-bil.NTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM  
		      		#BillIndex Bil
			WHERE 	Bil.BillType = 312
			UNION ALL
			
			SELECT	ZY=''抹零金额:'',
					'' '',
					0,
					0,
					0,
					'' '',
					ArAdd= 0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.preferencemoney
								ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.npreferencemoney
								ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='' '',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 312
					AND Bil.preferencemoney<>0
'

--费用单
SET @sql=@sql+'
                UNION ALL
                SELECT	ZY=''费用:''+A.FullName, 
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ApAdd=0,
					NApAdd=0,
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.total
								WHEN Bil.RedWord=2 THEN -S.total ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN S.Ntotal
								WHEN Bil.RedWord=2 THEN -S.ntotal ELSE 0 END,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,       
					S.TeamNo, 
					S.ID, 
					Bil.btypeid, 
					Bil.BillNumberId, 
					Bil.BillType, 
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	MoneyBill S,
			      	#AType A,
			      	#BillIndex Bil
			WHERE 	Bil.BillType =36
					AND Bil.BillNumberId = S.BillNumberId
					AND S.ATypeId = A.TypeId 
'

IF @IncludePre=1
begin
	set @sql=@sql+' UNION ALL
			SELECT 	ZY=''预收:'' + B.FullName,
					'' '',
					0,
					0,
					0,
					s.comment AS incomment,
					ArAdd=0,
					NArAdd=0, 
					ApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN s.total 
								WHEN Bil.RedWord =2 THEN -s.total ELSE 0 END,
					NApReduce=CASE WHEN Bil.RedWord IN(0,1) THEN s.ntotal 
								WHEN Bil.RedWord =2 THEN -s.ntotal ELSE 0 END, 
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid, 
					bil.dtypeid,
					bil.ktypeid,
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
      				#BType B,
      				PreBill s
			WHERE 	Bil.BillType = 189 
					AND bil.billnumberid=s.billnumberid
					AND B.TypeId = Bil.BTypeID '
END
	  
SET @sql=@sql+ '	
		) B'

EXEC(@sql)
--PRINT @sql


insert into #result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		aradd,
		naradd,
		ArReduce,
		NArReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname ,
		rate,
		AtypeID,
		goodsnumber,
		remark,
		unit,
		MQty,
		MTaxPrice,
		conversionrelationship,
		customassistantunit  		
	)
		SELECT 	ZY='',
					'',
					0,
					0,
					0,
					'' AS incomment,
					
					ArAdd = CASE   WHEN s.atypeid=33 and s.total>0 and 	Bil.RedWord IN(0,1)	  then s.total
									when  s.atypeid=33 and s.total<0 and  Bil.RedWord =2    THEN s.Total
								  WHEN  s.atypeid=39 AND s.Total<0  AND Bil.redword IN(0,1) THEN ABS(s.Total) 
								WHEN   s.atypeid=39 AND s.Total>0  AND Bil.redword=2  THEN -s.Total
								ELSE 0 END,
					NArAdd = CASE   WHEN s.atypeid=33 and s.Ntotal>0 and 	Bil.RedWord IN(0,1)	  then s.Ntotal
									when  s.atypeid=33 and s.Ntotal<0 and  Bil.RedWord =2    THEN s.NTotal
								   WHEN  s.atypeid=39 AND s.NTotal<0  AND Bil.redword IN(0,1) THEN ABS(s.NTotal) 
								    WHEN   s.atypeid=39 AND s.NTotal>0  AND Bil.redword=2  THEN -s.NTotal
								ELSE 0 END,
					ArReduce= CASE   WHEN s.atypeid=33 and s.Ntotal<0 and 	Bil.RedWord IN(0,1)	  then ABS(s.total)
									when  s.atypeid=33 and s.Ntotal>0 and  Bil.RedWord =2    THEN -s.Total
								   WHEN  s.atypeid=39 AND s.NTotal>0  AND Bil.redword IN(0,1) THEN s.Total 
								    WHEN   s.atypeid=39 AND s.NTotal<0  AND Bil.redword=2  THEN s.Total
								ELSE 0 END,
					nArReduce= CASE   WHEN s.atypeid=33 and s.Ntotal<0 and 	Bil.RedWord IN(0,1)	  then ABS(s.Ntotal)
									when  s.atypeid=33 and s.Ntotal>0 and  Bil.RedWord =2    THEN -s.NTotal
								   WHEN  s.atypeid=39 AND s.NTotal>0  AND  Bil.redword IN(0,1) THEN s.NTotal 
								    WHEN   s.atypeid=39 AND s.NTotal<0  AND Bil.redword=2  THEN s.NTotal
								ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					Bil.TeamNo, 
					S.ID, 
					S.BtypeId,  
					Bil.BillNumberId,
					Bil.BillType,
					0,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			FROM 	#BillIndex Bil,
			      	Listtable S,
					#BType B
			WHERE 	Bil.BillType IN(450)
					AND B.TypeId = S.BTypeID
					AND Bil.BillNumberId = S.BillNumberId AND bil.BillType = S.BillType
					And s.atypeid in(39,33)
					and (  @IncludePre=1 or s.atypeid=33)  
				
	
--加入发票数据
 
IF EXISTS(SELECT 1 FROM sysdata WHERE SubValue='1' AND SubName='IsInvoice')
BEGIN
insert into #result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		aradd,
		naradd,
		ArReduce,
		NArReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname ,
		rate,
		AtypeID,
		goodsnumber,
		remark,
		unit,
		MQty,
		MTaxPrice,
		conversionrelationship,
		customassistantunit,
		BillFlag 
	)
SELECT	ZY='',
					P.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment, 
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.NTaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					AC.FullName AS Cfullname,
					Bil.rate,
					'',
					s.goodsnumber,
					Bil.EXPLAIN  remark,
					MUnitID as unit,
					MQty,
					MTaxPrice,
					'1'+PU.FullName+'='+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.FullName as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,Qty) as customassistantunit ,
					1 BillFlag
			FROM  	ReceiptBill S
			LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
			LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID 
		    INNER JOIN  ReceiptBillIndex Bil ON S.BillNumberID=BIL.BillNumberID
		    INNER JOIN #stype s1 on s1.typeid=Bil.Stypeid
			INNER JOIN #Dtype D ON D.typeid = Bil.DTypeId
			INNER JOIN AC_currency AC ON Bil.CID=AC.CID
		    INNER JOIN PType P ON S.PTypeId = P.TypeId
			WHERE 	Bil.BillType = 405
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
					AND bil.BillDate>=@StartDate
					AND Bil.BillDate<=@ENDDate
					AND Bil.ifcheck = 't' 
					AND Bil.BTypeId = @BTypeId
					AND Bil.IfYearBill = 0
					AND Bil.CID LIKE @CID
END

--组合品销售
IF EXISTS(SELECT 1 FROM sysdata WHERE SubValue='1' AND SubName='CombinAtionProduct')
BEGIN
insert into #result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		aradd,
		naradd,
		ArReduce,
		NArReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname ,
		rate,
		AtypeID,
		goodsnumber,
		remark,
		unit,
		MQty,
		MTaxPrice,
		conversionrelationship,
		customassistantunit  
	)
SELECT	ZY='',--''销售:''+P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(20)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					P.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN s.qty
							 WHEN Bil.RedWord=2 THEN  -s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment, 
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.TaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.TaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN CAST(S.NTaxTotal AS  NUMERIC(24, 10) )  
							   WHEN Bil.RedWord=2 THEN CAST(-S.NTaxTotal AS  NUMERIC(24, 10) ) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate,
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid,
					S.TeamNo,
					S.ID,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					Bil.EXPLAIN  remark,
					MUnitID as unit,
					MQty,
					MTaxPrice,
					'1'+PU.fullname+'='+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,Qty) as customassistantunit  
			FROM  	PT_Combin_SaleBillDetail S
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID,
		      		#BillIndex Bil,
		      		#PType P
			WHERE 	Bil.BillType = 12
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
			UNION ALL
			SELECT	ZY='抹零金额:',
					'',
					0,
					0,
					0,
					'',
					ArAdd= 0,
					NArAdd=0,
					ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.preferencemoney
								ELSE 0 END,
					NArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.npreferencemoney
								ELSE 0 END,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'',
					explain,
					0,
					0,
					0,
					'',
					''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 12
					AND Bil.preferencemoney<>0
			UNION ALL
			SELECT  '',-- ZY=''退货:'' + P.FullName + '' '' + CAST(CAST(S.Qty AS  NUMERIC(24, 10) ) AS VARCHAR(10)) + ''*'' + CAST(S.TaxPrice AS VARCHAR(20)),
					p.typeid AS ptypeid,
					qty=CASE WHEN Bil.RedWord IN(0,1) THEN -s.qty
							 WHEN Bil.RedWord=2 THEN  s.qty ELSE 0 END,
					s.taxprice,
					s.ntaxprice,
					s.comment AS incomment,
					ArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN (-S.TaxTotal)
							 WHEN Bil.RedWord=2 THEN (S.TaxTotal) ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) THEN (-S.NTaxTotal)
							 WHEN Bil.RedWord=2 THEN (S.NTaxTotal) ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					s.ktypeid, 
					S.TeamNo, 
					S.ID, 
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					S.TeamNo1,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					s.goodsnumber,
					Bil.EXPLAIN  remark,
					S.MUnitID as unit,
					MQty,
					MTaxPrice,
					'1'+PU.fullname+'='+convert(varchar(200),CAST(S.MUnitRate  AS real))+u1.fullname as conversionrelationship,
					dbo.F_GetCustomAssist(S.PtypeId,Qty) as customassistantunit  
			FROM 	#BillIndex Bil,
					PT_Combin_SaleBackBillDetail S
					LEFT JOIN PType_Units PU ON PU.UnitsId=S.MUNITID 
					LEFT JOIN PType_Units u1 ON u1.UnitsId=S.UnitID,
		     		#PType P
			WHERE 	Bil.BillType = 46
					AND Bil.BillNumberId = S.BillNumberId
					AND S.PTypeId = P.TypeId
			UNION ALL
			SELECT	ZY='抹零金额:',
					'',
					0,
					0,
					0,
					'',
					--ArAdd= 0,
					--NArAdd=0,
					--ArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
					--			WHEN Bil.RedWord =2 		THEN  -Bil.preferencemoney
					--			ELSE 0 END,
					--NArReduce=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
					--			WHEN Bil.RedWord =2 		THEN  -Bil.npreferencemoney
					--			ELSE 0 END,
					ArAdd= CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.preferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.preferencemoney
								ELSE 0 END,
					NArAdd=CASE WHEN Bil.RedWord IN(0,1) 	THEN  Bil.npreferencemoney 
								WHEN Bil.RedWord =2 		THEN  -Bil.npreferencemoney
								ELSE 0 END,
					ArReduce=0,
					NArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid,
					Bil.TeamNo,
					ID=-1,
					Bil.BtypeId, 
					Bil.BillNumberId,
					Bil.BillType,
					TeamNo1='',
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					'',
					explain,
					0,
					0,
					0,
					'',
					''
			FROM 	#BillIndex Bil
			WHERE 	Bil.BillType = 46
					AND Bil.preferencemoney<>0
END
 --运输单
/*IF EXISTS(SELECT 1 FROM sysdata WHERE SubValue='1' AND SubName='usetransport')
BEGIN
insert into #result(
		zy,
		ptypeid,
		qty,
		taxprice,
		ntaxprice,
		incomment,
		aradd,
		naradd,
		ArReduce,
		NArReduce,
		BillDate,
		BillCode,
		etypeid,
		dtypeid,
		ktypeid,
		TeamNo,
		id	,
		btypeid	,
		BillNumberId,
		BillType,
		TeamNo1	,
		RedWord	,
		Comment ,
		cfullname ,
		rate,
		AtypeID,
		goodsnumber
	)
SELECT 	ZY='',
					'',
					0,
					0,
					0,
					'' AS incomment,
					
					ArAdd = CASE   WHEN	Bil.RedWord IN(0,1)	  then bil.total
									when  Bil.RedWord =2    THEN -bil.Total
								ELSE 0 END,
					NArAdd = CASE   WHEN  Bil.RedWord IN(0,1)	  then bil.Ntotal
									when   Bil.RedWord =2    THEN bil.NTotal
								ELSE 0 END,
					ArReduce= 0,
					nArReduce=0,
					Bil.BillDate, 
					Bil.BillCode,
					Bil.etypeid,
					bil.dtypeid,
					bil.ktypeid, 
					Bil.TeamNo, 
					0, 
					bil.BtypeId,  
					Bil.BillNumberId,
					Bil.BillType,
					0,
					Bil.RedWord,
					Bil.Comment,
					Bil.cfullname,
					Bil.rate,
					Bil.AtypeID,
					''
			FROM 	#BillIndex Bil,
					#BType B
			WHERE 	Bil.BillType IN(414)
					AND B.TypeId = Bil.BTypeID
END*/

--PRINT(@sql)
--RETURN
set @sql='
		insert into #result(
				zy,
				ptypeid,
				qty,
				taxprice,
				ntaxprice,
				incomment,
				aradd,
				naradd,
				ArReduce,
				NArReduce,
				BillDate,
				BillCode,
				etypeid,
				dtypeid,
				ktypeid,
				TeamNo,
				id	,
				btypeid	,
				BillNumberId,
				BillType,
				TeamNo1	,
				RedWord	,
				Comment,
				cfullname,
				rate,
				atypeid,
				goodsnumber,
				remark,
				unit,
				MQty,
				MTaxPrice,
				conversionrelationship,
				customassistantunit  
			)
			SELECT 
				''收款：''+a.fullname,
					'''',
					0,
					0,
					0,
					'''',
					ArAdd=CASE WHEN B.RedWord IN(0,1) AND B.billtype IN (45,148,149,215,46,426) THEN ac.total 
							WHEN B.RedWord =2  AND B.billtype IN (45,148,149,215,46,426) THEN -ac.total ELSE 0 END,
					NArAdd=CASE WHEN B.RedWord IN(0,1) AND B.billtype IN (45,148,149,215,46,426) THEN ac.ntotalmoney 
							WHEN B.RedWord =2  AND B.billtype IN (45,148,149,215,46,426) THEN -ac.ntotalmoney ELSE 0 END, 
					ApReduce=CASE WHEN B.RedWord IN(0,1)  AND B.billtype NOT IN (45,148,149,36,215,46,426) THEN ac.total 
							      WHEN B.RedWord =2  AND B.billtype NOT IN (45,148,149,36,215,46,426) THEN -ac.total
							      WHEN B.RedWord IN (0,1) AND B.BillType = 36 THEN -ac.total
							      WHEN B.RedWord=2 AND B.BillType=36 THEN ac.total 
							 ELSE 0 END,
					NApReduce=CASE WHEN B.RedWord IN(0,1)  AND B.billtype NOT IN (45,148,149,36,215,46,426) THEN ac.ntotalmoney 
							       WHEN B.RedWord =2  AND B.billtype NOT IN (45,148,149,36,215,46,426) THEN -ac.ntotalmoney
							       WHEN B.RedWord IN (0,1) AND B.BillType=36 THEN -ac.ntotalmoney
							       WHEN B.RedWord=2 AND B.BillType=36 THEN ac.ntotalmoney 
							 ELSE 0 END,  
					b.BillDate,
					b.billcode,
					b.etypeid,
					b.dtypeid,
					b.ktypeid,
					b.teamno,
					-1,
					b.btypeid,
					b.billnumberid, 
      				b.billtype, 
      				'''',
      				b.redword,
					b.Comment,
					b.cfullname,
					b.rate,
					b.atypeid,
					'''',
					explain,
					0,
					0,
					0,
					'''',
					''''
			    FROM #billindex b
          INNER JOIN billmulaccount ac ON b.billnumberid=ac.billnumberid and b.billtype =ac.billtype
	      INNER JOIN #atype a ON a.typeid=ac.atypeid
	      INNER JOIN AC_Items ACI ON a.typeid=ACI.nid
			   WHERE ac.total<>0 '


if @IncludePre=1
	SET @sql=@sql+' AND ACI.UserCode<>''2131'' '
		

EXEC(@sql)

SET @SQL = ' SELECT ps.FullName AS bfullname,ps2.FullName AS unitfullname,#result.* ,
			  case when #Result.redword in (0,1) then isnull(inv.uninvoiceqty,0) else -isnull(inv.uninvoiceqty,0) end as uninvoiceqty,
			  case when #Result.redword in (0,1) then isnull(inv.nuninvoicemoney,0) else -isnull(inv.nuninvoicemoney,0) end as nuninvoicemoney,
			  case when #Result.redword in (0,1) then isnull(inv.uninvoicemoney,0) else -isnull(inv.uninvoicemoney,0) end as uninvoicemoney
			  FROM #Result 
			  LEFT JOIN dbo.ptype p ON p.Typeid=#result.ptypeid
			  left join #invoiceQty inv on inv.billnumberid=#Result.billnumberid and inv.billtype=#Result.billtype and inv.ptypeid=#Result.ptypeid and inv.id=#Result.id
			  LEFT JOIN dbo.PType_Units ps ON ps.UnitsId=p.baseUnitId 
			  LEFT JOIN dbo.PType_Units ps2 ON ps2.UnitsId=#result.unit'


IF @showRedWord = 0
	SET @SQL = @SQL + ' WHERE RedWord = 0 '
	
	


--排序字段的处理

/*
IF @Orderby=''
	SET @SQL=@SQL+'  ORDER BY billdate,billnumberid,billtype,id'
ELSE IF UPPER(@Orderby)='TEAMNO'
	SET @SQL=@SQL+'  ORDER BY ISNULL(TEAMNO,999999999),BillDate,BillType,BillCode,id'
ELSE IF UPPER(@Orderby)='BILLDATE'
	SET @SQL=@SQL+'  ORDER BY BillDate DESC,BillType,BillCode,id'
ELSE
	BEGIN
		IF(CHARINDEX('billtype',@orderby)>0)
			SET @SQL=@SQL+'  ORDER BY '+@Orderby
		ELSE 
			SET @SQL=@SQL+'  ORDER BY billtype,'+@Orderby
	END 
*/
IF @Orderby=''
	SET @SQL=@SQL+'  ORDER BY billdate,billnumberid,billtype,id'
ELSE
	SET @SQL=@SQL+'  ORDER BY '+@Orderby

--PRINT(@SQL)	
EXEC(@SQL)



DROP TABLE #BillIndex,#PType,#AType,#BType,#Result,#atype1,#stype,#Dtype,#invoiceQty



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAssetBusinessType]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAssetBusinessType
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-业务类型 基本信息列表数据
-- 时间：2013-05-23
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_QueryAssetBusinessType
(
	@Search			VARCHAR(66),		--查询条件
	@StypeID		VARCHAR(50),		--分支机构
	@OperatorID		VARCHAR(50),		--操作员
	@Type			VARCHAR(10)			--业务类型
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @SQL VARCHAR(2000)='
SELECT 
		B.Id,
		B.BusinessType,
		CASE B.BusinessType WHEN 0 THEN ''增加''
			WHEN 1 THEN ''减少''
			WHEN 2 THEN ''部门转移''
			WHEN 3 THEN ''计提减值准备''
			WHEN 4 THEN ''折旧''
			ELSE ''''
		END typefullname,
		CASE B.BusinessType WHEN 0 THEN 212
			WHEN 1 THEN 213
			WHEN 2 THEN -1
			WHEN 3 THEN -2
			WHEN 4 THEN 214
		END billtype,
		B.FullName,
		B.Atid,
		T.FullName atfullname,
		B.Deleted,
		0 ischange,
		B.STypeId,
		S.FullName stypeFullName,
		S.IfAssetsIni
	FROM Ac_AssetBusinessType B
	INNER JOIN Stype S ON S.TypeId=B.StypeId AND S.IsSelfVerify=1
	LEFT JOIN Ac_Auditing_Template T ON B.Atid=T.AtId AND B.STypeId=T.STypeId
	INNER JOIN dbo.F_GetAllManagerBaseTypeId('''',11,'''+@OperatorID+''') F ON F.TypeId=B.STypeId'+CHAR(13)

IF(ISNULL(@StypeId,'')<>'')--分支机构
	SET @SQL+=' INNER JOIN f_split('''+@StypeId+''','','') F1 ON F1.A=F.TypeId'+CHAR(13)
	
SET @SQL+='WHERE 1=1'+CHAR(13)
IF ISNULL(@Search,'')<>'' 
	SET @SQL+=' AND B.FullName LIKE ''%'+@Search+'%'' '+CHAR(13)
	
IF(ISNULL(@Type,'')<>'')
	SET @SQL+=' AND B.Deleted=1 AND B.BusinessType LIKE '+@Type+CHAR(13)
	
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAssetsCardsSelector]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAssetsCardsSelector
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产卡片
-- 时间：2013-05-24
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_QueryAssetsCardsSelector
(
	@StypeId	VARCHAR(50),	-- 分支机构
	@Search		VARCHAR(66),	--查询条件
	@OperatorID	VARCHAR(50),	--操作人ID
	@TypeID		INT				--1:已入账 已提折旧 2：全选状态
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @SQL VARCHAR(2000)='
SELECT 
	ac.Id,
	ac.UserCode,
	ac.FullName,
	S.FullName sFullName,
	d.FullName dFullName
FROM Ac_AssetsCards ac
INNER JOIN SType s ON S.TypeId=ac.STypeId
INNER JOIN dbo.F_GetAllManagerBaseTypeId('''+@stypeid+''',11,'''+@OperatorID+''') F ON F.TypeId=S.TypeId
LEFT JOIN Department d ON d.typeid=ac.DTypeid'+CHAR(13)

--IF(ISNULL(@StypeId,'')<>'')--分支机构
--	SET @SQL+=' INNER JOIN f_split('''+@StypeId+''','','') F1 ON F1.A=F.TypeId'+CHAR(13)
	
IF @TypeID=1
	SET @SQL+=' WHERE ac.AssetsState IN(3,4)  '+CHAR(13)
ELSE IF @TypeID=2
	SET @SQL+=' WHERE 1=1 '+CHAR(13)
	
IF(ISNULL(@Search,'')<>'')--编号或者名称条件
	SET @SQL+='AND (ac.UserCode LIKE ''%'+@Search+'%'' OR ac.FullName LIKE ''%'+@Search+'%'' )'+CHAR(13)
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAssetsCategory]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAssetsCategory
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-资产类别 基本信息列表数据
-- 时间：2013-05-15
-- 作者：古丽娟	

-- 修改:Hqing 增加会计科目多级权限控制
-- ========================================================================
CREATE PROC Web_QueryAssetsCategory
(
	@StypeId		VARCHAR(50),		--分支机构ID
	@Search			VARCHAR(66),		--查询条件
	@OperatorID		VARCHAR(50)			--操作员
)
--@encode$--

AS
SET NOCOUNT ON 

CREATE TABLE #stype (typeid VARCHAR(50))
INSERT INTO #stype(typeid)
SELECT DISTINCT VerifyID FROM SType WHERE TypeId IN (SELECT *FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID))


BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200))
	INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName) 
	SELECT L.Typeid,L.Stypeid,A.FullName FROM F_LineAccount(@OperatorID,'') L
	INNER JOIN #stype S ON S.typeid=L.Stypeid
	INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId

	--处理会计科目为空的情况 在权限表里写入空记录
	INSERT INTO #Ac_Account_L(Typeid,StypeId,FullName) 
	SELECT '',TYPEID,'' FROM #stype S
END;

DECLARE @SQL VARCHAR(4000)='
SELECT 
	DISTINCT
	ac.Id,
	ac.UserCode,
	ac.FullName,
	ac.Units UnitsFullName,
	ac.DepreciationMean,
	CASE WHEN ac.DepreciationMean=0 THEN ''不折旧''
		WHEN AC.DepreciationMean=1 THEN ''手工折旧''
		WHEN AC.DepreciationMean=2 THEN ''平均年限法''
		WHEN AC.DepreciationMean=3 THEN ''双倍余额递减法''
		WHEN AC.DepreciationMean=4 THEN ''年数总和法''
		WHEN AC.DepreciationMean=5 THEN ''工作量法''
		ELSE ''''
	END DepreciationMeanFullname,
	ac.DurYear,
	ac.RemainsRate,
	ac.DepATypeId,
	ISNULL(a1.FullName,''****'') DepFullname,
	ac.ExpenseATypeId,
	ISNULL(a2.FullName,''****'') ExpenseFullname,
	ac.AssertATypeId,
	ISNULL(A3.FullName,''****'') AssertFullname,
	ac.Comment
FROM Ac_AssetsCategory ac
INNER JOIN #stype s ON S.TypeId=AC.StypeId
LEFT JOIN #Ac_Account_L a1 ON a1.TypeId=ac.DepATypeId AND S.TypeId=A1.StypeId
LEFT JOIN #Ac_Account_L a2 ON A2.TypeId=AC.ExpenseATypeId AND S.TypeId=A2.StypeId
LEFT JOIN #Ac_Account_L a3 ON A3.TypeId=ac.AssertATypeId AND S.TypeId=A3.StypeId'+CHAR(13)

--IF(ISNULL(@StypeId,'')<>'')--分支机构
--	SET @SQL+=' INNER JOIN f_split('''+@StypeId+''','','') F1 ON F1.A=F.TypeId'+CHAR(13)
	
SET @SQL+=' WHERE 1=1'+CHAR(13)

IF ISNULL(@Search,'')<>''--如果是Selector
	SET @SQL+=' and (ac.UserCode like ''%'+@Search+'%'' OR ac.FullName LIKE ''%'+@Search+'%'') '
	
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAssetsCheckList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAssetsCheckList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：吴雷
	日期：2014.04.04
	描述：查询固定资产盘点单列表
*/
CREATE PROCEDURE Web_QueryAssetsCheckList
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@StypeId			VARCHAR(1000),		-- 分支机构
	@StartDate			DATETIME,			-- 开始日期
	@EndDate			DATETIME,			-- 截止日期
	@Status				INT=0				-- 0.全部 1.待盘点 2.已盘点 3.已处理
)
--@encode$--
AS
SET NOCOUNT ON
-------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100),FullName VARCHAR(200))
INSERT INTO #GetManSTypeId(TypeId,FullName) 
SELECT S.TypeId,S.FullName FROM  F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID) F
INNER JOIN SType S ON S.TypeId=F.TypeId

--部门
CREATE TABLE #DType(typeid VARCHAR(100),FullName VARCHAR(200))
INSERT INTO #DType(typeid,FullName) 
SELECT D.TypeId,D.FullName FROM F_GetAllManagerBaseTypeId('',9,@OperatorID) F
INNER JOIN Department D ON D.typeid=F.TypeId 

--经手人
CREATE TABLE #Etype(typeid VARCHAR(100),FullName VARCHAR(200))
INSERT INTO #Etype(typeid,FullName)
SELECT E.typeId,E.FullName FROM F_GetManDetailEType(@OperatorID) F
INNER JOIN employee E ON E.typeId=F.TypeId

IF ISNULL(@EndDate,'') = ''
	SET @EndDate = '9999-12-31'

--获取列表数据
IF @Status = 0
	SELECT BillNumberID,
			billcode,
			CASE [state]
				WHEN 1 THEN '待盘点'
				WHEN 2 THEN '已盘点'
				WHEN 3 THEN '已处理'
			END AS statename,
			[state],
			createdate,
			stypeid,
			t2.FullName SFullName,
			dtypeId,
			T3.FullName DFullName,
			etypeId,
			T4.FullName EFullName,
			comment,
			memo 
	FROM dbo.FixedAssetsIndex T1
		INNER JOIN #GetManSTypeId T2 ON T1.stypeid = T2.TypeId
		INNER JOIN #DType T3 ON T1.dtypeId = T3.typeid
		INNER JOIN #Etype T4 ON T1.etypeId = T4.typeid
	WHERE T1.createdate >= @StartDate 
		AND T1.createdate <= @EndDate
	ORDER BY billcode ASC
ELSE
	SELECT BillNumberID,
			billcode,
			CASE [state]
				WHEN 1 THEN '待盘点'
				WHEN 2 THEN '已盘点'
				WHEN 3 THEN '已处理'
			END AS statename,
			[state],
			createdate,
			stypeid,
			t2.FullName SFullName,
			dtypeId,
			T3.FullName DFullName,
			etypeId,
			T4.FullName EFullName,
			comment,
			memo  
	FROM dbo.FixedAssetsIndex T1
		INNER JOIN #GetManSTypeId T2 ON T1.stypeid = T2.TypeId
		INNER JOIN #DType T3 ON T1.dtypeId = T3.typeid
		INNER JOIN #Etype T4 ON T1.etypeId = T4.typeid
	WHERE T1.createdate >= @StartDate 
		AND T1.createdate <= @EndDate
		AND T1.[state] = @Status
	ORDER BY billcode ASC

DROP TABLE #GetManSTypeId,#DType,#Etype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAssetStorageLocation]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAssetStorageLocation
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-存放地点 基本信息列表数据
-- 时间：2013-05-15
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_QueryAssetStorageLocation
(
	@Search		VARCHAR(256)	--查询条件
)
--@encode$--

AS
SET NOCOUNT ON 
IF(ISNULL(@Search,'')<>'')
	SELECT Id,Location FROM Ac_AssetStorageLocation WHERE Location LIKE '%'+@Search+'%'
ELSE 
	SELECT Id,Location FROM Ac_AssetStorageLocation
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAssetWorkingCondition]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryAssetWorkingCondition
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-使用状况 基本信息列表数据
-- 时间：2013-05-15
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_QueryAssetWorkingCondition
(
	@Search		VARCHAR(256)		--查询条件
)
--@encode$--

AS
SET NOCOUNT ON 
IF ISNULL(@Search,'')<>''
	SELECT Id,Comment FROM Ac_AssetWorkingCondition WHERE Comment LIKE '%'+@Search+'%'
ELSE
	SELECT Id,Comment FROM Ac_AssetWorkingCondition

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAssistAllValues]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryAssistAllValues
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：董湛
	日期：2012-05-16
	描述：查询辅助核算项对应的所有值
*/
CREATE PROCEDURE Web_QueryAssistAllValues
--@encode$--
AS
SET NOCOUNT ON
BEGIN
	DECLARE @StypeName		VARCHAR(200),
			@DepartName		VARCHAR(200),
			@EmployeeName	VARCHAR(200),
			@UnitsName		VARCHAR(200)
			
	SELECT @StypeName=FULLNAME FROM AC_ASSIST_CHECKITEMS WHERE USERCODE='01'
	SELECT @DepartName=FULLNAME FROM AC_ASSIST_CHECKITEMS WHERE USERCODE='02'
	SELECT @EmployeeName=FULLNAME FROM AC_ASSIST_CHECKITEMS WHERE USERCODE='03'
	SELECT @UnitsName=FULLNAME FROM AC_ASSIST_CHECKITEMS WHERE USERCODE='04'
	
	SELECT FULLNAME,TYPEID,@StypeName AS ASSISTNAME FROM STYPE WHERE LEVEAL>0 
	UNION ALL
	SELECT FULLNAME,TYPEID,@DepartName AS ASSISTNAME FROM DEPARTMENT  WHERE  LEVEAL>0 
	UNION ALL
	SELECT FULLNAME,TYPEID,@EmployeeName AS ASSISTNAME FROM EMPLOYEE  WHERE  LEVEAL>1 
	UNION ALL
	SELECT FULLNAME,TYPEID,@UnitsName AS ASSISTNAME FROM BTYPE  WHERE  LEVEAL>1  
END
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAssistCheckItemsDetail_Selector]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.[Web_QueryAssistCheckItemsDetail_Selector]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_Assist_CheckItemsDetail 查询指定自定义辅助核算类型明细selector
-- 时间：	2015-09-29
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryAssistCheckItemsDetail_Selector
(
	@Assist			VARCHAR(50),			--类型编号 或者ID
	@ParId			VARCHAR(50)='',			--父级ID
	@Query			VARCHAR(200)='',		--查找编号或者名称
	@OperatorID		VARCHAR(50)='00000'		--操作员ID
)

--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX)='
SELECT
	D.TypeId,
	D.ParId,
	D.Leveal,
	D.SonNum,
	D.SonCount,
	D.AscIds,
	D.UserCode,
	D.FullName
FROM Ac_Assist_CheckItemsDetail D
INNER JOIN Ac_Assist_CheckItems C ON C.AscIds=D.AscIds AND (C.UserCode='''+@Assist+''' OR C.AscIds='+@Assist+')
AND D.ParId<>''root'''+CHAR(13)

IF(ISNULL(@Query,'')<>'')
	BEGIN
		SET @SQL+=' AND	(D.UserCode LIKE ''%'+@Query+'%'' OR D.FullName LIKE ''%'+@Query+'%'') 
			AND D.SonNum=0'+CHAR(13)
	END
ELSE 
	BEGIN
		IF(ISNULL(@ParId,'')<>'')
			SET @SQL+='	AND	D.ParId='''+@ParId+''''+CHAR(13)
		ELSE
			SET @SQL+=' AND Leveal=1'+CHAR(13)
	END
SET @SQL+='ORDER BY D.TypeId'

EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAttendanceCX]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAttendanceCX]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011.10.26
	描述：考勤数据查询汇总
*/
/*
   作者：郑红霞
   日期：2012-02-09
   描述：处理没有打卡的时候的问题以及一些不正确的地方
*/

CREATE PROCEDURE Web_QueryAttendanceCX
(
	@OperatorId		VARCHAR(MAX),	--操作员ID
	@StartDate		VARCHAR(MAX),	--开始日期
	@EndDate		VARCHAR(MAX),	--结束日期	
	@STypeId		VARCHAR(MAX),	--分支机构
	@DTypeId		VARCHAR(MAX),	--部门
	@ETypeId		VARCHAR(MAX)	--职员
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------检查权限范围--------------------------------------------------------------------------------

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------检查权限范围结束--------------------------------------------------------------------------	

--分支机构
CREATE TABLE #GetManSTypeId(TypeID VARCHAR(50))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeID VARCHAR(50))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeID VARCHAR(50))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--构建缩小了的职员表(权限范围内的职员，包含分支机构和部门信息)
CREATE TABLE #Employee(TypeID VARCHAR(50),STypeID VARCHAR(50),DTypeID VARCHAR(50))
INSERT INTO #Employee(TypeID,STypeID,DTypeID)
	SELECT e.typeId,STypeID,DtypeID 
	FROM  dbo.loginuser l
	INNER JOIN  dbo.employee e ON e.typeId = l.etypeid
	INNER JOIN #GetManETypeId Ge ON e.typeId = Ge.TypeID 
	WHERE l.etypeid <>'00001'


--时间表
CREATE TABLE #getalltime(date DATETIME)
INSERT INTO  #getalltime(date) SELECT CONVERT(VARCHAR(10),times,120) FROM F_GetAllTime(@StartDate,@EndDate)
CREATE TABLE #WorkTime(
						STypeID VARCHAR(50),
						WorkStartTime DATETIME,
						WorkStartTimeContainLate DATETIME,
						WorkEndTime DATETIME,
						WorkDay VARCHAR(7),
					  )

INSERT INTO #WorkTime
SELECT  STypeID,
		StartTime,
		DATEADD(MINUTE,LateTime,StartTime),
		EndTime,
		WorkDay
FROM	WorkTime

SELECT
		e.TypeID AS etypeid,
		@StartDate  date,
		'00:00:00' AS StartTime,
		'00:00:00' AS EndTime, 
		W.WorkStartTime,
		W.WorkEndTime,
		0 AS Islate,
		'00:00:00' AS RegistStartTime,
		'00:00:00' AS RegistEndTime,
		0 AS LeaveReasonID,
		DATEDIFF(MINUTE,W.WorkStartTime,W.WorkEndTime) AS WorkTimePerDay
INTO #results
FROM #Employee e
INNER JOIN	#GetManSTypeId S ON e.STypeID = S.TypeID
INNER JOIN	#WorkTime W ON S.TypeID = W.STypeID
INNER JOIN	#GetManDTypeId D ON e.DTypeID = D.TypeID
WHERE 
		e.TypeID NOT IN (SELECT etypeid FROM AttendanceTime WHERE date <= @EndDate AND date >= @StartDate )



SELECT A.etypeid,
       A.date,
       A.StartTime,
       A.EndTime,
       W.WorkStartTime,
       W.WorkEndTime,
       CASE WHEN A.Islate=1 THEN 0 ELSE 1 END AS Islate,
       CONVERT(CHAR(8),ISNULL(M.RegistStartTime,(CASE WHEN A.StartTime = '00:00:00'
				THEN A.EndTime
			ELSE
				A.StartTime
	    	END)),8) AS RegistStartTime,
			CONVERT(CHAR(8),ISNULL(M.RegistEndTime,(CASE WHEN A.EndTime = '00:00:00'
				THEN A.StartTime
			ELSE
				A.EndTime
		END)),8) AS RegistEndTime,
		A.LeaveReasonID,
	    DATEDIFF(MINUTE,W.WorkStartTime,W.WorkEndTime) AS WorkTimePerDay
INTO #Result
FROM	AttendanceTime A
INNER JOIN  #Employee e ON A.etypeid = e.TypeID
LEFT JOIN   ManualRegist M ON M.AttendanceTimeId = A.Id
LEFT JOIN   LeaveReason L ON A.LeaveReasonID = L.Id
INNER JOIN	#GetManSTypeId S ON e.STypeID = S.TypeID
INNER JOIN	#WorkTime W ON S.TypeID = W.STypeID
INNER JOIN	#GetManDTypeId D ON e.DTypeID = D.TypeID
WHERE	A.date <= @EndDate AND A.date >= @StartDate
UNION ALL
SELECT  * FROM  #results

--SELECT * FROM #Result

UPDATE #Result SET Islate = 0 WHERE date IN (SELECT  VD.VacationDetailsDate FROM Vacation V INNER JOIN VacationDetails VD ON V.Id = VD.IndexId WHERE V.STypeID = STypeID)
or SUBSTRING((SELECT  DISTINCT w.WorkDay FROM #WorkTime w INNER JOIN  #Employee e ON e.STypeID = w.STypeID and e.TypeID =etypeid),DATEPART(WEEKDAY,date),1)<>'1'

SELECT 
	M.etypeid,
	M.STypeID,
	M.DTypeID,
	SUM(M.latecount) AS latecount,--,#WorkTime h
	(SELECT COUNT(g.date) FROM #getalltime g WHERE  date NOT IN
    (SELECT  VD.VacationDetailsDate FROM Vacation V INNER JOIN VacationDetails VD ON V.Id = VD.IndexId WHERE V.STypeID = STypeID)
    --AND SUBSTRING(h.WorkDay,DATEPART(WEEKDAY,g.date),1)='1') AS alltime,
    AND SUBSTRING((SELECT  DISTINCT w.WorkDay FROM #WorkTime w INNER JOIN  #Employee e ON e.STypeID = w.STypeID and e.TypeID =etypeid),DATEPART(WEEKDAY,g.date),1)='1') AS alltime,
    (SUM(M.RegistAlltime)/CAST(WorkTimePerDay AS  NUMERIC(24, 10) )) AS workallday,
	SUM(M.nianjia)/CAST(WorkTimePerDay AS  NUMERIC(24, 10) ) AS nianjia,
	SUM(M.chanjia)/CAST(WorkTimePerDay AS  NUMERIC(24, 10) ) AS chanjia,
	SUM(M.hunjia)/CAST(WorkTimePerDay AS  NUMERIC(24, 10) ) AS hunjia,
	SUM(M.sangjia)/CAST(WorkTimePerDay AS  NUMERIC(24, 10) ) AS sangjia,
	SUM(M.bingjia)/CAST(WorkTimePerDay AS  NUMERIC(24, 10) ) AS bingjia,
	SUM(M.shijia)/CAST(WorkTimePerDay AS  NUMERIC(24, 10) ) AS shijia
FROM 
(SELECT
	etypeid,
	stypeid,
	dtypeid,
	R.WorkTimePerDay,
	SUM(DATEDIFF(MINUTE,r.RegistStartTime,r.RegistEndTime)) AS RegistAlltime,
	r.RegistStartTime,
	r.RegistEndTime,
	r.Islate AS latecount,
	 SUM(CASE LeaveReasonID 
			WHEN 1
			THEN 
			CASE WHEN 
			(DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))<0
				    THEN 0 ELSE (DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))
			END 
			--THEN SUM(DATEDIFF(MINUTE,r.RegistStartTime,r.RegistEndTime))
			ELSE
			0
			END) AS nianjia,
	 SUM(CASE LeaveReasonID 
			WHEN 2
			THEN CASE WHEN 
			(DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))<0
				    THEN 0 ELSE (DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))
			END
			ELSE
			0
			END) AS chanjia,
	 SUM(CASE LeaveReasonID 
			WHEN 3
			THEN CASE WHEN 
			(DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))<0
				    THEN 0 ELSE (DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))
			END
			ELSE
			0
			END) AS hunjia,	
	 SUM(CASE LeaveReasonID 
			WHEN 4
			THEN CASE WHEN 
			(DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))<0
				    THEN 0 ELSE (DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))
			END
			ELSE
			0
			END) AS sangjia,				
	 SUM(CASE LeaveReasonID 
			WHEN 5
			THEN CASE WHEN 
			(DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))<0
				    THEN 0 ELSE (DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))
			END
			ELSE
			0
			END) AS bingjia,					
	 SUM(CASE LeaveReasonID 
			WHEN 6
			THEN CASE WHEN 
			(DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))<0
				    THEN 0 ELSE (DATEDIFF(MINUTE,r.WorkStartTime,r.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))
			END
			ELSE
			0
			END) AS shijia 
FROM #Result r
INNER JOIN #Employee E ON r.etypeid = E.TypeID
GROUP BY etypeid,e.stypeid,dtypeid,WorkTimePerDay,LeaveReasonID,RegistStartTime,RegistEndTime,Islate
)M
GROUP BY M.etypeid,M.STypeID,M.DTypeID,WorkTimePerDay
ORDER BY M.etypeid

DROP TABLE #GetManDTypeId,#GetManETypeId,#GetManSTypeId,#Result, #getalltime,#results

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAttendanceCXMX]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAttendanceCXMX]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011.10.31
	描述：考勤数据查询明细表
*/
/*
   作者：郑红霞
   日期：2012-02-09
   描述：处理没有打卡的时候的问题以及一些不正确的地方
*/

CREATE PROCEDURE Web_QueryAttendanceCXMX
(
	@OperatorId		VARCHAR(MAX),	--操作员ID
	@StartDate		DATETIME,	--开始日期
	@EndDate		DATETIME,	--结束日期	
	@STypeId		VARCHAR(MAX),	--分支机构
	@DTypeId		VARCHAR(MAX),	--部门
	@ETypeId		VARCHAR(MAX)	--职员
)
--@encode$--
AS
SET NOCOUNT ON

------------------------------------------------------------------------检查权限范围--------------------------------------------------------------------------------

DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------------------检查权限范围结束--------------------------------------------------------------------------	

--分支机构
CREATE TABLE #GetManSTypeId(TypeID VARCHAR(50))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeID VARCHAR(50))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

--职员
CREATE TABLE #GetManETypeId(TypeID VARCHAR(50))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--构建缩小了的职员表(权限范围内的职员，包含分支机构和部门信息)
CREATE TABLE #Employee(TypeID VARCHAR(50),STypeID VARCHAR(50),DTypeID VARCHAR(50))
INSERT INTO #Employee(TypeID,STypeID,DTypeID)(SELECT e.typeId,STypeID,DtypeID FROM employee e INNER JOIN #GetManETypeId Ge ON e.typeId = Ge.TypeID)

--时间表
CREATE TABLE #getalltime(date DATETIME)
INSERT INTO #getalltime(date) SELECT CONVERT(VARCHAR(10),times,120) FROM F_GetAllTime(@StartDate,@EndDate)

CREATE TABLE #WorkTime(
						STypeID VARCHAR(50),
						WorkStartTime DATETIME,
						WorkStartTimeContainLate DATETIME,
						WorkEndTime DATETIME,
						WorkDay VARCHAR(7)
					  )
INSERT INTO #WorkTime
SELECT  STypeID,
		StartTime,
		DATEADD(MINUTE,LateTime,StartTime),
		EndTime,
		WorkDay
FROM	WorkTime
INNER JOIN #GetManSTypeId s ON s.TypeID = WorkTime.STypeID

SELECT 
		0 AS id,
		@ETypeId AS etypeid,
		g.date,
		DATENAME(weekday,g.date)  AS weekdays,
		'00:00:00' AS starttime,
		@STypeId AS stypeid,
		'00:00:00' AS endtime,
		1 as islast ,
		'00:00:00' AS RegistStartTime ,
		'00:00:00' AS RegistEndTime ,
		'0.00' AS worktime,
		--DATEDIFF(MINUTE,W.WorkStartTime,W.WorkEndTime)/60.0  AS absencetime,
		0 AS LeaveTime ,
		'' AS LeaveReason,
		'' AS Comment 
INTO #AttendanceTimes
FROM #getalltime g
inner JOIN	#Employee e ON @ETypeId = e.TypeID
inner JOIN	#GetManSTypeId S ON e.STypeID = S.TypeID
inner JOIN	#WorkTime W ON S.TypeID = W.STypeID
WHERE g.date NOT IN (SELECT date FROM AttendanceTime WHERE etypeid = @ETypeId)

SELECT	R.Id,
		R.etypeid,
		R.date,
		R.weekdays,
		CASE WHEN R.StartTime = '00:00:00'
				THEN R.EndTime
			ELSE
				R.StartTime
		END AS StartTime,
		R.STypeID,
		CASE WHEN R.EndTime = '00:00:00'
				THEN R.StartTime
			ELSE
				R.EndTime
		END AS EndTime,
		R.Islate,
		R.RegistStartTime,
		R.RegistEndTime,
		DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime)/60.0 AS worktime,
		
		--CASE WHEN R.LeaveReasonID <> 0
		--	THEN 0
		--ELSE
		--	--如果存在未打卡的情况，则整天缺勤(除非补卡)
		--	CASE WHEN (R.RegistStartTime IS NULL AND (R.StartTime = '00:00:00' OR R.EndTime = '00:00:00'))
		--			THEN DATEDIFF(MINUTE,R.WorkStartTime,R.WorkEndTime)/60.0
		--		 ELSE	
		--		    CASE WHEN 
		--		    (DATEDIFF(MINUTE,R.WorkStartTime,R.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))<0
		--		    THEN 0 ELSE (DATEDIFF(MINUTE,R.WorkStartTime,R.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))/60.0
		--			--R.StartAbsenceTime+R.EndAbsenceTime
		--	END END 
		--END AS absencetime,
		
		CASE WHEN R.LeaveReasonID <> 0
			THEN 
				CASE WHEN (R.RegistStartTime IS NULL AND (R.StartTime = '00:00:00' OR R.EndTime = '00:00:00'))
					THEN DATEDIFF(MINUTE,R.WorkStartTime,R.WorkEndTime)/60.0
				 ELSE	
				    CASE WHEN 
				    (DATEDIFF(MINUTE,R.WorkStartTime,R.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))<0
				    THEN 0 ELSE (DATEDIFF(MINUTE,R.WorkStartTime,R.WorkEndTime) - DATEDIFF(MINUTE,R.RegistStartTime,R.RegistEndTime))/60.0
					--R.StartAbsenceTime+R.EndAbsenceTime
			END END 
		ELSE
			0
		END AS LeaveTime,
		
		R.FullName AS LeaveReason,
		R.Comment
FROM
(
	SELECT	A.id,
			A.etypeid,
			A.date,		
			DATENAME(weekday,A.date)  AS weekdays,
			E.Stypeid,
			CONVERT(CHAR(8),A.StartTime,8) as StartTime,
			CONVERT(CHAR(8),A.EndTime,8) as EndTime,
			A.Islate,
			W.WorkStartTime,
			W.WorkEndTime,
			CONVERT(CHAR(8),ISNULL(M.RegistStartTime,(CASE WHEN A.StartTime = '00:00:00'
				THEN A.EndTime
			ELSE
				A.StartTime
	    	END)),8) AS RegistStartTime,
			CONVERT(CHAR(8),ISNULL(M.RegistEndTime,(CASE WHEN A.EndTime = '00:00:00'
				THEN A.StartTime
			ELSE
				A.EndTime
		    END)),8) AS RegistEndTime,
			A.LeaveReasonID,			
			L.FullName,
			A.Comment							
	FROM AttendanceTime A
	LEFT JOIN ManualRegist M ON M.AttendanceTimeId = A.Id
	LEFT JOIN LeaveReason L ON A.LeaveReasonID = L.Id
	inner JOIN	#Employee e ON A.etypeid = e.TypeID
	inner JOIN	#GetManSTypeId S ON e.STypeID = S.TypeID
	inner JOIN	#WorkTime W ON S.TypeID = W.STypeID
	inner JOIN	#GetManDTypeId D ON e.DTypeID = D.TypeID
	--RIGHT JOIN #getalltime g ON g.times = A.date
	WHERE	A.date <= @EndDate
			AND A.date >= @StartDate
			--AND substring(w.WorkDay,DATEPART(WEEKDAY,A.date),1)='1'
			--AND A.date NOT IN (	SELECT  VD.VacationDetailsDate
			--					FROM	Vacation V 
			--					INNER	JOIN VacationDetails VD ON V.Id = VD.IndexId
			--					WHERE	V.STypeID = E.STypeID)
) R
UNION ALL 
SELECT  * FROM #AttendanceTimes  
ORDER BY R.date desc
																		
DROP TABLE #GetManDTypeId,#GetManETypeId,#GetManSTypeId,#Employee,#WorkTime,#getalltime,#AttendanceTimes  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAttendanceDataClear]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryAttendanceDataClear
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-10-31
	描述：考勤数据月份
*/
CREATE PROCEDURE Web_QueryAttendanceDataClear
(
    @OperatorId			VARCHAR(MAX)	--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorID)

SELECT DISTINCT(LEFT(CONVERT(VARCHAR(11),DATE),7)) AS monthofyear,E.STypeID FROM AttendanceTime A
INNER JOIN employee E ON A.etypeid=E.typeId
INNER JOIN #GetManSTypeId S ON S.TypeId=E.STypeID
ORDER BY STYPEID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryATypeZwIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryATypeZwIni]
GO






/*
	作者：谢吉康
	日期：2005-8-25
	描述：查询会计科目期初
*/
CREATE  PROCEDURE Web_QueryATypeZwIni
(
	@OperatorId		varchar(50),	--操作员ID
	@ATypeId		varchar(50),		--ATypeID
	@stypeid	varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCpaital VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCpaital OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 		varchar(8000),
		@SonNum 	int

SELECT	@SonNum = SonNum FROM AType WHERE Deleted = 0 AND TypeId = @ATypeId

create table #stype(typeid varchar(100))

--分支机构
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

SET @SQL = '
			SELECT 	A.parid,
					A.TypeId,
					A.SonNum,
					A.UserCode,
					A.FullName,
					ISNULL(SUM(B.Total00),0) AS Total			
			FROM 	AType A 
			LEFT JOIN (
						SELECT	aTypeId as typeid,
								SUM(Total00) AS Total00
						FROM	AType_total
						WHERE	(aTypeId LIKE ''00001%'' OR aTypeId LIKE ''00002%'')
								AND aTypeId NOT IN (''0000200002'',''0000100006'',''0000100008'',''0000100005'',''0000200001'',''0000100003'',''0000100007'',''0000200003'') 
								AND aTypeId <> ''0000100001''
								AND aTypeId NOT IN (SELECT TypeId FROM AType WHERE TypeId LIKE ''0000100002%'')
								AND aTypeId NOT IN (SELECT TypeId FROM AType WHERE TypeId LIKE ''0000100004%'')
								and stypeid in (select typeid from #stype)
						GROUP BY aTypeId
						UNION ALL
						SELECT 	''0000100001'' AS TypeId,
								ISNULL(SUM(Total),0) AS Total00
						FROM	iniGoodsStocks i 
								inner join stock s on i.ktypeid=s.typeid 
								inner join #stype s1 on s.stypeid=s1.typeid							
						UNION ALL
						SELECT	''0000100008'' AS TypeId,
								ISNULL(SUM(CostTotal),0) AS Total00
						FROM	iniCommissionStock
						WHERE	Type = 140 
								and stypeid in (select typeid from #stype)
					)B ON LEFT(B.TypeId,LEN(A.TypeId)) = A.TypeId
			WHERE	A.Deleted = 0 
					AND (A.TypeId LIKE ''00001%'' OR A.TypeId LIKE ''00002%'')
					AND A.TypeId NOT IN (''0000200002'',''0000100006'',''0000100005'',''0000200001'',''0000100003'',''0000100007'',''0000200003'') 
					AND A.TypeId NOT IN (SELECT TypeId FROM AType WHERE TypeId LIKE ''0000100002%'')
					AND A.TypeId NOT IN (SELECT TypeId FROM AType WHERE TypeId LIKE ''0000100004%'')
'

IF @SonNum = 0
	SET @SQL = @SQL + ' AND A.TypeId LIKE '+char(39)+@ATypeId+'%'+char(39)
ELSE
	SET @SQL = @SQL + ' AND A.ParId = '+char(39)+@ATypeId+char(39)

SET @SQL = @SQL + ' GROUP BY A.parid,A.TypeId,A.SonNum,A.UserCode,A.FullName ORDER BY A.UserCode '

--PRINT(@SQL)
EXEC(@SQL)

drop table #stype
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryATypeZwIniLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryATypeZwIniLine]
GO












/*
	作者：谢吉康
	日期：2005-8-25
	描述：查询会计科目期初
*/
CREATE  PROCEDURE Web_QueryATypeZwIniLine
(
	@OperatorId		varchar(50),	--操作员ID	
	@UserCode		varchar(256),	--编号
	@FullName		varchar(256),	--名称
	@stypeid		varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 		varchar(8000),
		@SonNum 	int
		
create table #stype(typeid varchar(100))
--分支机构
INSERT INTO #stype(typeid) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

SET @SQL = '
			SELECT	A.TypeId,
					A.SonNum,
					A.UserCode,
					A.FullName,
					ISNULL(SUM(B.Total00),0) AS Total
			FROM	AType A
			LEFT JOIN (
							SELECT 	b.TypeId,
									ISNULL(SUM(a.Total00),0) AS Total00
							FROM 	AType_total a
							inner join Atype b on a.atypeid=b.typeid
							inner join #stype s on s.typeid=a.stypeid 
							WHERE	b.Deleted = 0 
									AND b.SonNum = 0
									AND b.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
									AND b.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
									AND (b.TypeId LIKE ''00001%'' OR b.TypeId LIKE ''00002%'')
									AND b.TypeId NOT IN (''0000200002'',''0000100006'',''0000100008'',''0000200003'') 
									AND b.TypeId <> ''0000100001''
									AND b.TypeId NOT IN (SELECT TypeId FROM AType WHERE TypeId LIKE ''0000100002%'')
									AND b.TypeId NOT IN (SELECT TypeId FROM AType WHERE TypeId LIKE ''0000100004%'')
							GROUP BY b.TypeId
							UNION ALL
							SELECT 	''0000100001'' AS TypeId,
									ISNULL(SUM(Total),0) AS Total00
							FROM	iniGoodsStocks
									inner join stock s on iniGoodsStocks.ktypeid=s.typeid 
									inner join #stype s1 on s.stypeid=s1.typeid	
							UNION ALL
							SELECT	''0000100008'' AS TypeId,
									ISNULL(SUM(CostTotal),0) AS Total00
							FROM	iniCommissionStock	
							WHERE	Type = 140 and stypeid in (select typeid from #stype)
						)B ON A.TypeId = B.TypeId
			WHERE	A.Deleted = 0 
					AND A.SonNum = 0
					AND A.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
					AND A.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'					
					AND (A.TypeId LIKE ''00001%'' OR A.TypeId LIKE ''00002%'')
					AND A.TypeId NOT IN (''0000200002'',''0000100006'',''0000100005'',''0000200001'',''0000100003'',''0000100007'',''0000200003'')
					AND A.TypeId NOT IN (SELECT TypeId FROM AType WHERE TypeId LIKE ''0000100002%'')
					AND A.TypeId NOT IN (SELECT TypeId FROM AType WHERE TypeId LIKE ''0000100004%'')
'
					

SET @SQL = @SQL + ' GROUP BY A.TypeId,A.SonNum,A.UserCode,A.FullName ORDER BY A.UserCode '

--PRINT(@SQL)
EXEC(@SQL)

drop table #stype













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAuditingBillMeKnow]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAuditingBillMeKnow]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2019-10-31
	描述：我的知会列表 
*/
CREATE PROCEDURE Web_QueryAuditingBillMeKnow
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(50),
	@EndDate		VARCHAR(50),	
	@BillCode		VARCHAR(100),
	@BillType		VARCHAR(50),
	@Comment		VARCHAR(200),
	@IfAudit		VARCHAR(50),
	@iscurrentauditing BIT,
	@stypeid		VARCHAR(MAX),--分支机构
	@etypeid		VARCHAR(MAX),--职员
	@checke			VARCHAR(MAX)='' --制单人
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

DECLARE @combinationproduct	VARCHAR(10)
select @combinationproduct=subvalue from sysdata where subname='combinationproduct'


--只显示其他审核步骤完成的单据	
DECLARE @currentauditing	VARCHAR(MAX)
IF @iscurrentauditing = 1
	SET @currentauditing = 	
		' AND ( 
				(
				  F.AuditingType = 3 
				AND  
				 (SELECT COUNT(allcharindex) FROM FN_GetAllCharIndex(''1'',A.PassSteps)) - (SELECT COUNT(allcharindex) FROM FN_GetAllCharIndex(''1'',A.AuditingSteps)) = 1
				) 
				OR  F.AuditingType <> 3
			  )'
ELSE
	SET @currentauditing = ''	
-------------------------------------
/*---是否统一往来单位
DECLARE @isAllBtype VARCHAR(50)
SELECT @isAllBtype = Value FROM dbo.Userconfig WHERE ConfigName = 'btypeall'*/ 

DECLARE @SQL VARCHAR(MAX)

--描  述：检查调拨当中入库仓库是否有效
DECLARE @MoveInOutKLimit  INT
SELECT @MoveInOutKLimit=Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit' --配置

--增加权限
 --往来单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)

--经手人
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid <> '00001'
BEGIN
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	
END

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)
DECLARE @GetKtypeCount int,@KtypeCount int  ---全部仓库
		 
IF @MKtypeId = '00000'
	INSERT INTO #GetManKTypeId(TypeId) VALUES('00000')

INSERT INTO #GetManKTypeId(TypeId) VALUES('10000')
	
	
--部门
CREATE TABLE #GetManDtypeId(TypeId	varchar(100))
IF @MDtypeid = '-99999'
INSERT INTO #GetManDtypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

--分支机构
CREATE TABLE #GetManStypeId(TypeId	varchar(100))
IF @MStypeid = '-99999'
INSERT INTO #GetManStypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--制单人
CREATE TABLE #GetManChecke(TypeId	varchar(100))
INSERT INTO #GetManChecke(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@checke,3)

-- //搬敏捷
-- 调拨权限
DECLARE @dp NCHAR(1)='0'; --部门
DECLARE @ep NCHAR(1)='0'; --经手人
SELECT @dp=RIGHT(LEFT(lim,3013),1),@ep=RIGHT(LEFT(lim,3014),1) FROM loginuser WHERE etypeid=@OperatorId
--//


DECLARE @SQL_WHERE_SZ VARCHAR(MAX),@re_re INT--单据查看权限

SELECT @SQL_WHERE_SZ = ' where ( '
	EXEC @re_re=GP_CheckLimit @OperatorID,2676
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 305 or'		--零售查看(POS单查看)

EXEC @re_re=GP_CheckLimit @OperatorID,2679
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 11 or'			--销售单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2682
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 45 or'			--销售退货单查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2709
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 215 or'		--零售退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2831
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 4 or'			--收款单查看


EXEC @re_re=GP_CheckLimit @OperatorID,2718
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 34 or'			--采购单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2721
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 6 or'			--采购退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2837
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 66 or'			--付款单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2739
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 17 or'			--同价调拨单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2742
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 21 or'			--变价调拨单查看


EXEC @re_re=GP_CheckLimit @OperatorID,2751
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 9 or'			--报损单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2754
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 14 or'			--报溢单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2688
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 139 or'		--赠送单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2727
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 126 or'		--获赠单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2882

IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 57 or'			--调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2769
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 16 or'			--商品拆装单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2819
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 116 or'		--应收款增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2822

IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 115 or'		--应收款减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2825
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 128 or'		--应付款增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2828
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 129 or'		--应付款减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2855
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 36 or'			--费用单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2864
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 93 or'			--其他收入单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2861
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 77 or'			--转款单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2873
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 84 or'			--固定资产(项目)购买查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2914
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 212 or'		--固定资产增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2876
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 85 or'			--固定资产(项目)变卖查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2917
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 213 or'		--固定资产减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2879
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 78 or'			--固定资产(卡片)折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2920
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 78 or'			--固定资产(项目)折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2920
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 214 or'		--固定资产折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2867
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 5 or'			--待摊费用发生查看

EXEC @re_re=GP_CheckLimit @OperatorID,2870
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 10 or'			--待摊费用摊销查看


EXEC @re_re=GP_CheckLimit @OperatorID,2843
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 148 or'		--返利执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2849
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 149 or'		--价保执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2691
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 140 or'		--委托代销发货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2700
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 141 or'		--委托代销结算单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2694
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 142 or'		--委托代销退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2697
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 143 or'		--委托代销调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2923
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 144 or'		--受托代销收货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2736
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 145 or'		--受托代销结算单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2730
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 146 or'		--受托代销退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2733
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 147 or'		--受托代销调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2846
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 150 or'		--获利核算执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2781
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 156 or'		--维修接件单 -- 单据查看权限

EXEC @re_re=GP_CheckLimit @OperatorID,2852
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 151 or'		--获得价保过账

EXEC @re_re=GP_CheckLimit @OperatorID,2858								--现金费用单
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 158 or'			

EXEC @re_re=GP_CheckLimit @OperatorID,2885								--会计凭证
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 159 or'			

EXEC @re_re=Gp_CheckLimit @OperatorID,2685
IF @re_re = 0															--销售换货单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 160 or'			

EXEC @re_re=Gp_CheckLimit @OperatorID,2724
IF @re_re = 0															--采购换货单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 161 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2781
IF @re_re = 0															--维修接件单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 165 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2784
IF @re_re = 0															--维修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 166 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2787
IF @re_re = 0															--维修取件单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 167 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2790
IF @re_re = 0															--整机更换单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 168 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2793
IF @re_re = 0															--送修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 169 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2796
IF @re_re = 0															--送修返回单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 170 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2799
IF @re_re = 0															--报修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 171 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2802
IF @re_re = 0															--上门维修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 172 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2805
IF @re_re = 0															--维修品调入单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 173 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2808
IF @re_re = 0															--维修品调出单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 174 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2811
IF @re_re = 0															--维修品调拨单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 175 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2906
IF @re_re = 0															--积分兑换单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 183 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,1368
IF @re_re = 0															--保险理赔单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 186 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2745
IF @re_re = 0															--分支机构调拨出库单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 187 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2748
IF @re_re = 0															--分支机构调拨入库单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 188 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2834
IF @re_re = 0															--预收款单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 189 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2840
IF @re_re = 0															--预付款单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 190 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,1472
IF @re_re = 0															--领料出库单----------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 191 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,1474
IF @re_re = 0															--领料退回单-------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 197 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1487
IF @re_re = 0															--维修结算单-----------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 195 or'			
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1477
IF @re_re = 0															--救援单----------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 196 or'		
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1478
IF @re_re = 0															--三包索赔单--------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 200 or'		
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2775
IF @re_re = 0															--其他入库单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 201 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2778
IF @re_re = 0															--其他出库单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 202 or'									

EXEC @re_re=Gp_CheckLimit @OperatorID,2772
IF @re_re = 0															--序列号调整单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 203 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2888
IF @re_re = 0															--采购费用分摊 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 205 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2891
IF @re_re = 0															--销售费用分摊 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 206 or'		
			
EXEC @re_re=Gp_CheckLimit @OperatorID,2713
IF @re_re = 0															--询价单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 185 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2711
IF @re_re = 0															--请购单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 204 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2715
IF @re_re = 0															--采购订单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 301 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2673
IF @re_re = 0															--销售订单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 300 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2671
IF @re_re = 0															--报价单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 184 or'		

--不是总账则不显示资金调拨单
IF((SELECT SubValue FROM SYSDATA WHERE SUBNAME = 'isuseacsystem') = 1)
BEGIN
	EXEC @re_re=Gp_CheckLimit @OperatorID,4318
	IF @re_re = 0														--资金调拨单  
		SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 310 or'
END

EXEC @re_re=Gp_CheckLimit @OperatorID,2988
IF @re_re = 0															--提成单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 311 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,2900
IF @re_re = 0															--会员储值充值单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 181 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4501
IF @re_re = 0															--会员批量储值充值单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 312 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2757
IF @re_re = 0															--借出开单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 87 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2760
IF @re_re = 0															--借进开单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 71 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2763
IF @re_re = 0															--借出还回单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 88 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2766
IF @re_re = 0															--借进还出单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 72 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,4581
IF @re_re = 0															--暂估入库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 400 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4590
IF @re_re = 0															--暂估退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 401 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4602
IF @re_re = 0															--发出商品出库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 402 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4611
IF @re_re = 0															--发出商品退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 403 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4622
IF @re_re = 0															--采购暂估开票  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 404 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4630
IF @re_re = 0															--销售发货开票  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 405 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,4678
IF @re_re = 0															--往来核销  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 450 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4745
IF @re_re = 0															--组合品销售订单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 313 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,4749
IF @re_re = 0															--组合品销售出库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 12 or'
         
EXEC @re_re=Gp_CheckLimit @OperatorID,4757
IF @re_re = 0															--组合品销售出退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 46 or'
-- 仓库入库
 EXEC @re_re=Gp_CheckLimit @OperatorID,4832
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 418 or'
-- 仓库出库
  EXEC @re_re=Gp_CheckLimit @OperatorID,4840
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 419 or'
-- 仓库调拨单
EXEC @re_re=Gp_CheckLimit @OperatorID,4848
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 420 or'
	
--门店配送单
EXEC @re_re=Gp_CheckLimit @OperatorID,5244
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 327 or'
	
--门店配送退货单	
EXEC @re_re=Gp_CheckLimit @OperatorID,5253
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 328 or'	
	
--配送验收单配送验收单	
EXEC @re_re=Gp_CheckLimit @OperatorID,5262
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 329 or'	

SELECT @SQL_WHERE_SZ = @SQL_WHERE_SZ + ' r.billtype = 1000 )  '			--随便添加一个BillType用来拼凑字符串


SET @SQL = '; WITH TEMP AS
	(
	SELECT	B.BillNumberId,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.totalmoney,
			B.ETypeId,
			B.dealBTypeId,
			B.btypeid,
			b.stypeid,
			CASE 
				WHEN c.AuditingType = ''1'' THEN ''顺序审核''
				WHEN c.AuditingType = ''2'' THEN ''任意审核''
				ELSE ''会签审核''
			END AS AudType,
			c.BillIndexType AS BillIndexType,
			c.AuditStep AS AuditingStep,
			B.checke,
			B.checktime,
			B.ifcheck,
			B.IfAudit,
			B.CostSale,
			B.explain,
			B.comment 
	FROM	
	(
	

		SELECT B.BillNumberId,
				''3'' AS BillIndexType,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.totalmoney,
				B.ETypeId,
				'''' AS dealBTypeId,
				'''' AS btypeid,
				B.STypeId,
				B.checke,
				B.checktime,
				CASE B.IfAudit
					WHEN 1 THEN ''t''
					ELSE ''f'' 
				END AS ifcheck,
				A.IfAudit,
				0 as CostSale,
				B.explain,
				B.comment 
		FROM	AuditingBill A
		INNER JOIN dbo.RequestIndex B ON B.BillNumberId = A.BillNumberId '

IF @MEtypeid <> '00001' OR @checke <> ''
	SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = b.STypeId '
	SET @SQL=@sql+' WHERE A.BillIndexType = ''3''
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''''
				
IF @BillCode <> ''
	SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
IF @Comment <> ''
	SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
IF @BillType <> ''
	SET @SQL += ' AND B.BillType = '+@BillType+' '
ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411)'
IF @combinationproduct = '0' OR @combinationproduct is null 
	SET @SQL += ' AND B.BillType NOT IN (313)'
 		 
IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @etypeid<>''	 OR @MEtypeid <> '00001'
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @MDtypeid='-99999'
		SET @sql+=' AND b.DTypeId IN (SELECT TypeId FROM #GetManDtypeId)  '
SET @SQL += '
UNION ALL 
		SELECT	B.BillNumberId,
				''0'' AS BillIndexType,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.totalmoney,
				B.ETypeId,
				B.dealBTypeId,
				B.btypeid,
				B.STypeId,
				B.checke,
				B.checktime,
				CASE B.IfAudit
					WHEN 1 THEN ''t''
					ELSE ''f'' 
				END AS ifcheck,
				A.IfAudit,
				0 AS CostSale,
				B.explain,
				B.comment 
		FROM	AuditingBill A
		INNER JOIN OrderIndex B ON B.BillNumberId = A.BillNumberId '
	
	IF @MEtypeid <> '00001' OR @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' INNER JOIN #GetManBTypeId B1 ON B1.TypeId = B.dealBTypeId
					  INNER JOIN #GetManBTypeId B2 ON B2.typeid=B.btypeid '
	IF @MKtypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId '
	IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	SET @SQL += '
		WHERE	A.BillIndexType = ''0''
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''''
				
	IF @MEtypeid <> '00001'
		SET @sql+=' AND (B.ETypeId IN (SELECT TypeId FROM #GetManETypeId) OR B.BillType IN(17,21) AND '+@ep+'=''1'') '
	IF @MDtypeid='-99999'
		SET @sql+=' AND (B.DTypeId IN (SELECT TypeId FROM #GetManDtypeId) OR B.BillType IN(17,21) AND '+@dp+'=''1'') '
IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @etypeid<>''
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
				
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'

	SET @SQL += '
	UNION ALL
	SELECT	B.BillNumberId,
			''2'' AS BillIndexType,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.totalmoney,
			B.ETypeId,
			B.dealBTypeId,
			B.btypeid,
			B.STypeId,
			B.checke,
			B.checktime,
			B.ifcheck,
			A.IfAudit,
			B.CostSale,
			B.explain,
			B.comment 
	FROM	AuditingBill A
	INNER JOIN BillIndex B ON B.BillNumberId = A.BillNumberId '

	IF(@BillType <> '310')
	BEGIN
		IF @MStypeid = '-99999'
			SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	END
	
		
	IF @MEtypeid <> '00001' OR @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
		
	SET @SQL += '
		WHERE	A.BillIndexType = ''2''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''' 
				AND B.RedWord = 0 '
	
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'		
		
	IF(@BillType = '310') 
	BEGIN
		--IF @stypeid<>''
		SET @sql+='  and 
		( 
			b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+')) 
			OR b.StypeID2 in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+')) 
		
		)'
	END
	ELSE
	BEGIN
		IF @stypeid<>''
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	END

	IF @etypeid<>''
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	
	IF @MEtypeid <> '00001'
		SET @sql+=' AND (B.ETypeId IN (SELECT TypeId FROM #GetManETypeId) OR B.BillType IN(17,21) AND '+@ep+'=''1'') '

	IF @MDtypeid='-99999'
		SET @sql+=' AND (B.DTypeId IN (SELECT TypeId FROM #GetManDtypeId) OR B.BillType IN(17,21) AND '+@dp+'=''1'') '
	
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' AND (
							(
								B.dealBTypeID IN (SELECT typeid FROM #GetManBTypeId) AND B.BillType IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''12'',''46'')
							)
							OR
							(
								B.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''12'',''46'')
							)
						) 
					AND (
							(
								B.BTypeID IN (SELECT typeid FROM #GetManBTypeId) AND B.BillType IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''450'',''12'',''46'')
							)
							OR
							(
								B.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''450'',''12'',''46'')
							)
						) '
						
	IF @MKtypeid = '-99999'
	BEGIN
		SET @SQL += '
			AND (
					(
						( B.KTypeID IN (SELECT typeid FROM #GetManKTypeId) OR B.KTypeID2 IN (SELECT typeid FROM #GetManKTypeId)) AND B.BillType IN (''16'',''155'',''157'',''160'',''161'',''201'',''202'') 
					) 
					OR 
					(
						B.BillType IN (''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''147'',''201'',''202'',''400'',''401'',''402'',''403'',''12'',''46'') AND B.KTypeID IN (SELECT typeid FROM #GetManKTypeId)
					) 
					OR 
					( '
		IF @MoveInOutKLimit = 1
			SET @SQL = @SQL + '	B.BillType IN (''17'',''21'') AND (B.KTypeId IN (SELECT typeid FROM #GetManKTypeId) AND B.KTypeId2 IN (SELECT typeid FROM #GetManKTypeId)) '
		ELSE
			SET @SQL = @SQL + ' B.BillType IN (''17'',''21'') AND (B.KTypeId IN (SELECT typeid FROM #GetManKTypeId) OR B.KTypeId2 IN (SELECT typeid FROM #GetManKTypeId)) '
		SET @SQL = @SQL + '
					)
					OR
					(
						B.BillType NOT IN (''16'',''155'',''157'',''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''147'',''17'',''21'',''160'',''161'',''201'',''202'',''400'',''401'',''402'',''403'',''12'',''46'')
					)
				) '
	END
	
	
	SET @SQL += ' 
	UNION ALL
			SELECT	B.BillNumberId,
					''4'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					''311'' AS BillType,
					B.Total AS totalmoney,
					'''' AS ETypeId,
					'''' AS dealBTypeId,
					'''' AS btypeid,
					B.STypeId,
					B.checke,
					B.checketime AS checktime,
					B.ifcheck,
					A.IfAudit,
					0 AS CostSale,
					B.explain,
					B.comment 
		    FROM	AuditingBill A 
		    INNER JOIN CommissionBillNew AS B ON(B.BillNumberId = A.BillNumberId) 
		    INNER JOIN employee AS C ON(B.Checke = C.typeId)  '
	
	IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
		
	IF @MEtypeid <> '00001'	or @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	SET @SQL += '
		WHERE	A.BillIndexType = ''4''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				AND B.RedWord = 0 '
				
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND 311 = '+@BillType+' '			
					
	IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	
	SET @SQL+=' AND ''' + @etypeid +''' = '''' '
	
	
	SET @SQL += ' 
	UNION ALL
			SELECT	B.BillNumberId,
					''1'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					b.BillType,
					''0'' AS totalmoney,
					b.ETypeId,
					b.dealBTypeId,
					b.btypeid,
					B.STypeId,
					B.checke,
					B.checktime,
					B.ifcheck,
					A.IfAudit,
					0 AS CostSale,
					B.explain,
					B.comment 
		    FROM	AuditingBill A 
		    INNER JOIN LendIndex AS B ON(B.BillNumberId = A.BillNumberId)  '
	SET @SQL += '
		WHERE	A.BillIndexType = ''1''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				AND B.RedWord = 0
				'
	IF @stypeid<>''
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @etypeid<>''
			SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'
		
	SET @SQL += ' 
	UNION ALL
	SELECT B.BillNumberId,
			''7'' AS BillIndexType,
			B.BillDate,
			B.BillCode,
			b.BillType,
			''0'' AS totalmoney,
			b.ETypeId,
			'''' AS dealBTypeId,
			'''' AS btypeid,
			B.STypeId,
			B.checke,
			B.checktime,
			B.ifcheck,
			A.IfAudit,
			0 AS CostSale,
			B.explain,
			B.comment 
	FROM	AuditingBill A 
	INNER JOIN FactIndex AS B ON(B.BillNumberId = A.BillNumberId)  '
		    
	IF @MEtypeid <> '00001' OR @checke <> ''
				SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	IF @MDtypeid='-99999'
		SET @sql+=' INNER JOIN #GetManDtypeId AS D ON(B.DTypeId = D.Typeid) '
					  
	SET @SQL += '
		WHERE	A.BillIndexType = ''7''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate +''''
				
	
	IF @MKtypeid = '-99999'
	BEGIN
		  SET @sql+=' AND ( (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype IN (418,419))'
		  IF @MoveInOutKLimit=1
		  BEGIN
			 SET @sql+=' OR (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId)  AND  B.ktypeid2 in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype=420) )'
		  END
		  ELSE
		  BEGIN
			 SET @sql+=' OR (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId)  OR  B.ktypeid2 in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype=420)  )'
		  END
	END
	
	IF @stypeid<>''	 or @MStypeid = '-99999'
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @etypeid<>''	OR @MEtypeid <> '00001'
			SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'
	
	SET @SQL += ' 
	UNION ALL
			SELECT	B.BillNumberId,
					''5'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.TaxTotalMoney AS totalmoney,
					B.ETypeId,
					B.dealBTypeId,
					B.btypeid,
					B.STypeId,
					B.checke,
					B.checktime,
					B.ifcheck,
					A.IfAudit,
					0 AS CostSale,
					B.explain,
					B.comment 
		    FROM AuditingBill A 
		    INNER JOIN ReceiptBillIndex AS B ON(B.BillNumberId = A.BillNumberId) 
		    '

	IF @MStypeid = '-99999'
			SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	
	IF @MEtypeid <> '00001' OR @checke <> ''
				SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	 IF @MEtypeid <> '00001' OR @etypeid <> ''  
		SET @SQL += ' INNER JOIN #GetManETypeId e ON e.TypeId = B.etypeid '
	IF @MDtypeid='-99999'
		SET @sql+=' INNER JOIN #GetManDtypeId AS D ON(B.DTypeId = D.Typeid) '
		
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' INNER JOIN #GetManBTypeId B1 ON B1.TypeId = B.dealBTypeId
					  INNER JOIN #GetManBTypeId B2 ON B2.typeid=B.btypeid '	
		
	SET @SQL += '
		WHERE	A.BillIndexType = ''5''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''' 	
				AND B.RedWord = 0 '
	
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'
	
	
	SET @SQL += ' 
	UNION ALL
			SELECT	B.BillNumberId,
					''9'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.Total AS totalmoney,
					B.ApplyEtypeId AS ETypeId,
					'''' AS dealBTypeId,
					'''' AS btypeid,
					B.STypeId,
					B.checke,
					B.checktime,
					B.ifcheck,
					A.IfAudit,
					0 AS CostSale,
					B.explain,
					B.comment 
		    FROM	AuditingBill A 
		    INNER JOIN PosAllotApplyBillIndex AS B ON(B.BillNumberId = A.BillNumberId) 
		    '

	IF @MStypeid = '-99999'
			SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	
	IF @MEtypeid <> '00001' OR @checke <> ''
				SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	 
	 IF @MEtypeid <> '00001' OR @etypeid <> ''  
		SET @SQL += ' INNER JOIN #GetManETypeId e ON e.TypeId = B.applyetypeid '
		
	IF @MDtypeid='-99999'
		SET @sql+=' INNER JOIN #GetManDtypeId AS D ON(B.DTypeId = D.Typeid) '
		
	SET @SQL += '
		WHERE	A.BillIndexType = ''9''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''' 	
				AND B.RedWord = 0 '
	
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'
			
	SET @SQL += '						
		) B, 
		
	(
		SELECT	A.BillNumberId,
				A.BillIndexType,
				CASE 
					WHEN F.AuditingType = 1 THEN DBO.FN_MinGetCurrentAuditETypeID('''+@OperatorId+''',A.BillNumberId,F.STypeId,F.BillType)	
				ELSE 
					( SELECT TOP 1 AuditingStep FROM AuditingFlowDetail WHERE AuditingId = F.AuditingId AND ETypeId = '''+@OperatorId+''')
				END AS AuditStep,
				F.AuditingType,
				F.BillType 
		FROM	AuditingBill A,
				AuditingFlowSet F 
		WHERE	A.AuditingId = F.AuditingId '
		
--审核状态过滤
IF @IfAudit <> '9'		
BEGIN
	SET @SQL += '	AND A.IfAudit = '''+@IfAudit+''''
END

SET @SQL += '
	) C
	WHERE	B.BillNumberId = c.BillNumberId
			AND B.BillIndexType = c.BillIndexType '

SET @SQL += ' ) '
	
SET @SQL += '
	SELECT	DISTINCT
			R.*,
			emp.FullName as efullname ,
			bty.FullName as bfullname,
			bty1.Fullname as jsfullname,
			N.BillName AS billtypename,
			CK.fullname AS fullnameck,
			CASE R.IfAudit 
				WHEN 1 THEN ''审核通过''
				WHEN 0 THEN ''待审核''
				ELSE ''审核不通过''
			END AS AuditState,
			CASE R.IfAudit
				WHEN 0 THEN DBO.FN_GetCurrentAuditETypeNames(r.billnumberid,r.stypeid,r.billtype)
				ELSE ''''
			END AS auditcrusteps
	FROM	TEMP R
	INNER JOIN AuditingFlowNunciator an ON R.BillType = an.BillType AND an.ETypeID ='''+@OperatorId+'''
	LEFT JOIN  employee emp ON r.ETypeId=emp.typeId 
	LEFT JOIN employee AS CK ON(R.checke = CK.typeId) 
	LEFT JOIN  btype bty ON r.dealBTypeId=bty.typeId
	LEFT JOIN  btype bty1 ON r.btypeid=bty1.typeid 
	LEFT JOIN BillName N ON N.Billtype = R.BillType'+@SQL_WHERE_SZ+'
	ORDER BY BillDate,BillCode '

--PRINT(@SQL)
EXEC (@SQL)

DROP TABLE #GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManDtypeId,#GetManChecke

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryAuditingEtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryAuditingEtype]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：廖晨羽
	日期：2012-01-29
	描述：查询审核人
*/

CREATE PROCEDURE Web_QueryAuditingEtype
(
	@AuditingStep		INT,
	@BillAuditingId		VARCHAR(100),
	@BillIndexType		VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL			VARCHAR(MAX)= '',
		@SQLWHERE		VARCHAR(MAX)= '',
		@SQL2			VARCHAR(MAX)= '',
		@STypeId		VARCHAR(50)= '',
		@BillType		INT,
		@TEMPSQL		VARCHAR(MAX)= '',
		@IfAudit        VARCHAR(10)/*,
		@btypeid		VARCHAR(50),
		@dtypeid		VARCHAR(50),
		@stypeid1		VARCHAR(50),
		@etypeid		VARCHAR(50),
		@ktypeid		VARCHAR(50),
		@ktypeid2		VARCHAR(50)*/
		
CREATE TABLE #Result1
(
	TypeID		VARCHAR(100),
	UserCode	VARCHAR(500),
	FullName	VARCHAR(500),
	AuditingStep VARCHAR(10)
)		

--描  述：检查调拨当中入库仓库是否有效
--DECLARE @MoveInOutKLimit  INT
--SELECT @MoveInOutKLimit=Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit' --配置


SET @SQLWHERE = ' WHERE a.BillNumberID = '+@BillAuditingId+' AND a.BillIndexType = '''+@BillIndexType+''' ' 


SELECT @STypeId = F.STypeId,@BillType = F.BillType FROM AuditingBill A,AuditingFlowSet F WHERE A.AuditingId = F.AuditingId AND A.IfAudit = '0' AND a.BillNumberID = @BillAuditingId AND a.BillIndexType = @BillIndexType

IF ((SELECT AuditingType FROM AuditingFlowSet A, (SELECT TOP 1 B.BillType,A.AuditingID FROM dbo.AuditingBill A
                                                     LEFT JOIN AuditingFlowDetail B
                                                     ON a.AuditingID = b.AuditingID
                                                     WHERE a.BillNumberID = @BillAuditingId AND a.BillIndexType = @BillIndexType ) B 
                                                  WHERE A.AuditingID = B.AuditingID AND A.billtype = B.BillType) <> 3)
BEGIN

	INSERT INTO #Result1
	SELECT A.ETypeID as typeid,E.UserCode as UserCode,E.FullName as fullname,A.AuditingStep as AuditingStep FROM FN_GetCurrentAuditETypeID(@BillAuditingId, @STypeId, @BillType) A 
	INNER JOIN dbo.employee E ON 
	A.ETypeID = e.typeId
	ORDER BY A.AuditingStep ASC

	IF ((SELECT COUNT(TypeID) FROM #Result1) = 0 )
	BEGIN
		IF (@AuditingStep = -1)
		BEGIN
			SET @SQLWHERE = @SQLWHERE + ' AND B.AuditingStep = 1 '
		END
		ELSE IF(@AuditingStep = 0)
		BEGIN
			SET @SQLWHERE = @SQLWHERE + ' AND B.AuditingStep ='+ CAST(@AuditingStep AS VARCHAR(100))+''
		END
		ELSE
		BEGIN
			SET @SQLWHERE = @SQLWHERE + ' AND B.AuditingStep ='+ CAST((@AuditingStep+1) AS VARCHAR(100))+''
		END
	END
END
ELSE
BEGIN
	DECLARE
			@strPassSteps		VARCHAR(500),
			@strAuditingSteps	VARCHAR(500)
	
	SELECT
			@strPassSteps=PassSteps,
			@strAuditingSteps=AuditingSteps
		FROM AuditingBill
		WHERE BillNumberID=@BillAuditingId AND BillIndexType=@BillIndexType
	INSERT INTO #Result1
	SELECT a.ETypeID as typeid,E.UserCode as UserCode,E.FullName as fullname,a.AuditingStep as AuditingStep
		FROM AuditingFlowDetail a
		INNER JOIN AuditingBill b
		ON a.AuditingID=b.AuditingID
		INNER JOIN dbo.employee E ON 
		A.ETypeID = e.typeId
		WHERE b.BillNumberID=@BillAuditingId
		AND a.AuditingStep IN
		(
			SELECT AllCharIndex FROM FN_GetAllCharIndex('1',@strPassSteps)
		)
		AND a.AuditingStep NOT IN
		(
			SELECT AllCharIndex FROM FN_GetAllCharIndex('1',@strAuditingSteps)
		)
END

IF ((SELECT COUNT(TypeID) FROM #Result1) = 0 )
BEGIN
	SET @SQL = 'INSERT INTO #Result1
			SELECT b.ETypeID as typeid,C.UserCode as UserCode,c.FullName as fullname,B.AuditingStep as AuditingStep FROM dbo.AuditingBill A
                                                     LEFT JOIN AuditingFlowDetail B
                                                     ON a.AuditingID = b.AuditingID
                                                     LEFT JOIN dbo.employee C
                                                     ON b.ETypeID = c.typeId
                                                     ' + @SQLWHERE

	--PRINT(@SQL)
	EXEC(@SQL)
END

--IF (@BillIndexType = '2' AND @BillType IN (17,21))                            
--    SELECT  @btypeid=btypeid,@dtypeid=dtypeid,@stypeid1=stypeid,@etypeid=etypeid,@ktypeid=ktypeid,@ktypeid2=ktypeid2 FROM BillIndex
--				 WHERE BillNumberId= @BillAuditingId
--ELSE IF(@BillIndexType = '2' AND @BillType NOT IN (17,21))
--BEGIN
--	SELECT  @btypeid=btypeid,@dtypeid=dtypeid,@stypeid1=stypeid,@etypeid=etypeid,@ktypeid=ktypeid FROM BillIndex
--					 WHERE BillNumberId= @BillAuditingId
--END
--ELSE
--BEGIN
--	SELECT  @btypeid=btypeid,@dtypeid=dtypeid,@stypeid1=stypeid,@etypeid=etypeid,@ktypeid=ktypeid FROM dbo.OrderIndex
--					 WHERE BillNumberId= @BillAuditingId
--END

--if (@BillIndexType = '2')
--	BEGIN
--		IF (@BillType IN (17,21))
--		BEGIN
--			IF @MoveInOutKLimit = 1
--				BEGIN
--					SET @TEMPSQL = ' AND typeid in(
--						select etypeid from ktype_l
--						where  '''+@ktypeid+''' like typeid +''%''
--						union all
--						select etypeid from loginuser
--						where MangerKTypeID=00000
--						)
--										AND typeid in(
--						select etypeid from ktype_l
--						where  '''+@ktypeid2+''' like typeid +''%''
--						union all
--						select etypeid from loginuser
--						where MangerKTypeID=00000
--						)
--						'
--				END	
--			ELSE
--				BEGIN
--					SET @TEMPSQL = ' AND typeid in(
--						select etypeid from ktype_l
--						where  '''+@ktypeid+''' like typeid +''%''
--						union all
--						select etypeid from loginuser
--						where MangerKTypeID=00000
--						)
--										OR typeid in(
--						select etypeid from ktype_l
--						where  '''+@ktypeid2+''' like typeid +''%''
--						union all
--						select etypeid from loginuser
--						where MangerKTypeID=00000
--						)
--						'
--				END		
--		END	
--		ELSE
--		BEGIN
--			SET @TEMPSQL = 'AND typeid in
--			(
--				select etypeid from ktype_l
--				where  '''+@ktypeid+''' like typeid +''%''
--				union all
--				select etypeid from loginuser
--				where MangerKTypeID=00000
--			)'
--		END
--	END
--else if (@BillIndexType = '0')
--	BEGIN
--		SET @TEMPSQL = 'AND typeid in
--			(
--				select etypeid from ktype_l
--				where  '''+@ktypeid+''' like typeid +''%''
--				union all
--				select etypeid from loginuser
--				where MangerKTypeID=00000
--			)'
--	END

--CREATE TABLE #Result2
--(
--	typeid		VARCHAR(100)
--)	



--SET @SQL2 = '
--		INSERT INTO #Result2
--		SELECT typeid FROM employee WHERE sonnum=0 and
--			typeid in
--			(
--				select etypeid from etype_l
--				where '''+@Etypeid+''' LIKE typeid+''%''
--				union all
--				select etypeid from loginuser
--				where MangerETypeID=00001
--			)
--		and typeid in
--			(
--				select etypeid from dtype_l
--				where  '''+@Dtypeid+''' like typeid +''%''
--				union all
--				select etypeid from loginuser
--				where MangerDTypeID=00000
--			)
--		and typeid in
--			(
--				select etypeid from stype_l
--				where  '''+@Stypeid+''' like typeid +''%''
--				union all
--				select etypeid from loginuser
--				where MangerSTypeID=00000
--			)
--		'
--		+ @TEMPSQL 
		
--IF (SUBSTRING(@Btypeid,1,5) = '00001')
-- BEGIN
-- 	SET @SQL2 = @SQL2 + '
--		and typeid in
--			(
--				select etypeid from btype_l
--				where  '''+@Btypeid+''' like typeid +''%''
--				union all
--				select etypeid from loginuser
--				where MangerBTypeID=00001
--			)'
-- END
--ELSE IF(SUBSTRING(@Btypeid,1,5) = '00002')
-- BEGIN
-- 	SET @SQL2 = @SQL2 + '
--		and typeid in
--			(
--				select etypeid from btype_l
--				where  '''+@Btypeid+''' like typeid +''%''
--				union all
--				select etypeid from loginuser
--				where MangerBTypeID2=00002
--			)'
-- END
		
----PRINT @SQL2	
--EXEC(@SQL2)

--SELECT R1.typeid,R1.fullname FROM #Result1 R1
--INNER JOIN #Result2 R2
--ON R1.TypeID = R2.typeid

SELECT distinct typeid,fullname,usercode,AuditingStep FROM #Result1

DROP TABLE #Result1--,#Result2			  

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryAuditingTemplateBillMoneyList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_QueryAuditingTemplateBillMoneyList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===============================
--by:glj	
--date:2016-07-16
--9.8 凭证模板-金额来源
--===============================
CREATE PROCEDURE Web_QueryAuditingTemplateBillMoneyList
(
	@BillType	INT,	--单据类型
	@acFrom		INT		--科目来源
)
--@encode$--
AS
SET NOCOUNT ON
DEClARE @SQL VARCHAR(MAX)=''
IF(@BillType != 57)
SET @SQL='SELECT * FROM Ac_BillMoney_List 
WHERE 
	BillType='+CAST(@BillType AS VARCHAR(5))+CHAR(13)
ELSE 
	BEGIN
		IF @acFrom <> 15 AND @acFrom <> 16 AND @acFrom <> 17
			BEGIN
				SET @SQL='SELECT * FROM Ac_BillMoney_List 
				WHERE 
				BillType=''57'' AND (Express+Fullname <>''costtotal调整金额'')'
			END 
		ELSE
			BEGIN
				SET @SQL='SELECT * FROM Ac_BillMoney_List 
				WHERE 
				BillType='+CAST(@BillType AS VARCHAR(5))+CHAR(13)
			END 
	END
	
IF(@acFrom=2)
	BEGIN
		IF @BillType NOT IN(4,66,189,190,158,57)
			SET @SQL+='	AND Express = ''totalinmoney'''
		ELSE IF @BillType = 57
			SET @SQL =@SQL+' AND Express = ''changetotal'''
		ELSE 
			SET @SQL+='	AND Express = ''total'''
	END
IF @acFrom=4 AND @BillType IN(36,77,93)
	SET @SQL+='	AND Express = ''total'''
	
IF(@acFrom=1)--手工选择时，增加平衡数选择
BEGIN 
	IF @BillType = 404 OR @BillType = 405
	BEGIN
		SET @SQL += '	AND Express <> ''costtotal'' ' 
	END
	
	SET @SQL+='	OR Express=''balancemoney'' '
END 
	
IF(@BillType=159)--业务凭证，类型与金额唯一对应
	BEGIN
		IF(@acFrom=6)
			SET @SQL+='	AND Express = ''j_total'' '
		ELSE
			SET @SQL+='	AND Express = ''d_total'' ' 
	END
IF @acFrom=15
	BEGIN
		--34 采购入库单  6 采购退货单
		IF(@BillType IN(34,6))
			SET @SQL+='	AND FullName=''成本金额(库存商品)'''
		IF(@BillType=161)--161	采购换货单
			SET @SQL+='	AND FullName=''入库成本金额(库存商品) 减 出库成本金额(库存商品)'''
		--126获赠单  144受托代销收货单 146受托代销退货单  400暂估入库单 401暂估退货单 305零售单 215零售退货单 11销售出库单 45销售退货单 139赠送单 140委托代销发货单 142委托代销退货单 141委托代销结算单 402发出商品出库单 403发出商品退货单 12组合品销售出库单 46组合品销售退货单 9报损单 14报溢单
		--183积分兑换单	166维修单 168整机更换单 172上门维修单 173维修品调入单  174维修品调出单
		IF(@BillType IN(126,144,146,400,401,305,215,11,45,139,140,142,141,402,403,12,46,9,14,183,166,168,172,173,174))
			SET @SQL+='	AND FullName=''成本金额'''
		--145受托代销结算单
		IF(@BillType IN(145))
			SET @SQL+='	AND FullName=''折后金额'''
		--147 受托代销调价单	
		IF(@BillType IN(147))
			SET @SQL+='	AND FullName=''调整差额'''
		--160销售换货单	
		IF(@BillType IN(160))
			SET @SQL+='	AND FullName=''出库成本金额 减 入库成本金额'''
		IF(@BillType IN(21))--变价调拨单
			SET @SQL+='	AND FullName IN(''调拨金额'',''成本金额'',''调拨金额 减 出库成本'')'
		IF(@BillType IN(187))--分支机构调拨出库
			SET @SQL+='	AND FullName IN(''金额'',''成本金额'',''金额 减 成本金额'')'
		IF(@BillType IN(188))--分支机构调拨入库
			SET @SQL+='	AND FullName IN(''金额'')'
		IF(@BillType IN(16))--生产拆装单
			SET @SQL+='	AND FullName IN(''入库成本金额 减 出库成本金额'')'
		IF(@BillType IN(202))--其他出库单
			SET @SQL+='	AND FullName IN(''金额'',''成本金额'')'
		IF(@BillType IN(201))--其他入库单
			SET @SQL+='	AND FullName IN(''金额'')'
		IF(@BillType IN(405))--销售发货开票
			SET @SQL+='	AND FullName IN(''本次开票成本'')'
		IF(@BillType IN(57))--成本调价单
			SET @SQL+='	AND FullName IN(''调整金额'') AND Express = ''costtotal'''
		IF(@BillType IN(205))--采购费用分摊单
			SET @SQL+='	AND FullName IN(''分摊金额'')'
	END
IF @acFrom=16
	BEGIN
		--305 零售单 215零售退货单 11销售出库单 45销售退货单
		IF(@BillType IN(305,215,11,45))--
			SET @SQL+='	AND FullName IN(''折后金额(库存商品)'')'
		--160销售换货单
		IF(@BillType IN(160))
			SET @SQL+='	AND FullName IN(''出库折后金额(库存商品) 减 入库折后金额(库存商品)'')'
		--139赠送单 140委托代销发货 142委托代销退货 402发出商品出库单 403发出商品退货单 9报损单 14报溢单 183积分兑换单	166维修单 168整机更换单 172上门维修单 173维修品调入单  174维修品调出单
		IF(@BillType IN(139,140,142,402,403,9,14,183,166,168,172,173,174))
			SET @SQL+='	AND FullName=''成本金额'''
		--141委托代销结算	
		IF(@BillType IN(141))
			SET @SQL+='	AND FullName=''折后金额'''
		--12组合品销售出库单 46 组合品销售退货单	
		IF(@BillType IN(12,46))
			SET @SQL+='	AND FullName=''折后金额(库存商品)'''
		IF(@BillType IN(21))--变价调拨单
			SET @SQL+='	AND FullName IN(''调拨金额'',''成本金额'',''调拨金额 减 出库成本'')'	
		IF(@BillType IN(187))--分支机构调拨出库
			SET @SQL+='	AND FullName IN(''金额'',''成本金额'',''金额 减 成本金额'')'
		IF(@BillType IN(188))--分支机构调拨入库
			SET @SQL+='	AND FullName IN(''金额'')'
		IF(@BillType IN(16))--生产拆装单
			SET @SQL+='	AND FullName IN(''入库成本金额 减 出库成本金额'')'
		IF(@BillType IN(202,201))--其他出库单/其他入库单
			SET @SQL+='	AND FullName IN(''金额'')'
		IF(@BillType IN(405))--销售发货开票
			SET @SQL+='	AND FullName IN(''销售金额'')'
		IF(@BillType IN(57))--成本调价单
			SET @SQL+='	AND FullName IN(''调整金额'') AND Express =''costtotal'''
		IF(@BillType IN(205))--采购费用分摊单
			SET @SQL+='	AND FullName IN(''分摊金额'')'
	END
	
IF(@acFrom=17)
	BEGIN
		--305零售单 215零售退货单 11销售出库单 45销售退货单 139赠送单 140委托代销发货 142委托代销退货 141委托代销结算 402发出商品出库单 403发出商品退货单 12组合品销售出库单 46 组合品销售退货单 9报损单 14报溢单 183积分兑换单	166维修单 168整机更换单 172上门维修单 173维修品调入单  174维修品调出单
		IF(@BillType IN(305,215,11,45,139,140,142,141,402,403,12,46,9,14,183,166,168,172,173,174))
			SET @SQL+='	AND FullName=''成本金额'''
		IF(@BillType IN(147))
			SET @SQL+='	AND FullName=''调整差额'''
		--160销售换货单
		IF(@BillType IN(160))
			SET @SQL+='	AND FullName IN(''出库成本金额 减 入库成本金额'')'
		IF(@BillType IN(21))--变价调拨单
			SET @SQL+='	AND FullName IN(''调拨金额'',''成本金额'',''调拨金额 减 出库成本'')'	
		IF(@BillType IN(187))--分支机构调拨出库
			SET @SQL+='	AND FullName IN(''金额'',''成本金额'',''金额 减 成本金额'')'
		IF(@BillType IN(188))--分支机构调拨入库
			SET @SQL+='	AND FullName IN(''金额'')'
		IF(@BillType IN(16))--生产拆装单
			SET @SQL+='	AND FullName IN(''入库成本金额 减 出库成本金额'')'
		IF(@BillType IN(202,201))--其他出库单/其他入库单
			SET @SQL+='	AND FullName IN(''金额'')'
		IF(@BillType IN(405))--销售发货开票
			SET @SQL+='	AND FullName IN(''本次开票成本'')'
		IF(@BillType IN(57))--成本调价单
			SET @SQL+='	AND FullName IN(''调整金额'') AND Express =''costtotal'''
		IF(@BillType IN(205))--采购费用分摊单
			SET @SQL+='	AND FullName IN(''分摊金额'')'
	END
EXEC(@SQL)

SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBackingOutQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBackingOutQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-04-21
	描述：返修类别查询
*/
CREATE PROCEDURE Web_QueryBackingOutQuery
(
	@OperatorId		VARCHAR(MAX),	--操作员ID
	@StartDate		VARCHAR(MAX),	--开始日期
	@EndDate		VARCHAR(MAX),	--截止日期
	@STypeId		VARCHAR(MAX),	--分支机构
	@WciTypeId		VARCHAR(MAX),	--车牌号
	@BTypeId		VARCHAR(MAX),	--往来单位
	@DTypeId		VARCHAR(MAX),	--部门ID
	@ETypeId		VARCHAR(MAX),	--经手人ID
	@BacktypeId		VARCHAR(MAX),	--返修类别
	@BillCode		VARCHAR(MAX)	--单据编号
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--车牌号
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)	

DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'SELECT	B.BillNumberId,
					B.BillType,
					B.BillDate,
					B.BillCode,
					Bc.RATypeID,
					B.BTypeId,
					B.ETypeId,
					B.DTypeId,
					B.STypeId,
					BackTypeFullName = (SELECT TOP 1 FullName FROM Qp_BackType WHERE BackTypeId = Bc.BackTypeId),
					CONVERT(VARCHAR(40),Bc.ReceptionDate,120) AS ReceptionDate,
					Bc.SendPerson,
					B.Tel AS LinkTel,
					Bc.Oil,
					Bc.Mileage,
					B.Explain,
					B.Comment,
					e1.fullname as Checke,
					Mx.BackingOutReason,
					Mx.BackingOutCheck,
					Mx.BackingOutResult
			FROM	BillIndex B
			INNER JOIN Employee e1 ON E1.typeid=b.checke
			INNER JOIN BillIndex_CarRepair Bc ON B.BillNumberId = Bc.BillNumberId
			INNER JOIN Qp_BackingOut_Bill Mx ON B.BillNumberId = Mx.BillNumberId
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManWciTypeId W ON Bc.RATypeID = W.TypeId
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			WHERE	B.BillDate>='''+@StartDate+'''
					AND B.BillDate<='''+@EndDate+'''
					AND B.BillCode LIKE ''%'+@BillCode+'%''
					AND B.RedWord = 0
					AND B.IfYearBill = 0 '

IF @BacktypeId <> '0'					
	SET @SQL = @SQL + ' AND Bc.BackTypeId = '+@BacktypeId

SET @SQL = @SQL + ' ORDER BY B.BillDate,B.BillCode DESC'
	

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManDTypeId,#GetManETypeId,#GetManWciTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBackTypeDefine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBackTypeDefine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-04-20
	描述：返修类别定义
*/
CREATE PROCEDURE Web_QueryBackTypeDefine
(
	@OperatorId		VARCHAR(MAX),	--操作员ID
	@nType			VARCHAR(MAX),	--类型 q:查询 a:新增 m:修改 d:删除
	@Id				INT = -1,		--ID
	@FullName		VARCHAR(MAX),	--名称
	@pycode         varchar(100)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Msg VARCHAR(MAX)

--查询
IF @nType = 'q'
	BEGIN
		SELECT * FROM Qp_BackType ORDER BY BackTypeId ASC
	END

--新增
IF @nType = 'a'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Qp_BackType WHERE FullName = @FullName)
			BEGIN
				SET @Msg = '返修类别名称重复，请检查！' + CHAR(10) + CHAR(10)
				SET @Msg = @Msg + '要放弃编辑，按【Esc】键可关闭窗口退出！'				
				RAISERROR(@MSG,16,1)
				RETURN -1
			END
			
		INSERT INTO Qp_BackType(FullName,pycode )VALUES(@FullName,@pycode)
		
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息添加失败！',16,1)
				RETURN -2
			END			
	END	
	
--修改
IF @nType = 'm'
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Qp_BackType WHERE FullName = @FullName AND BackTypeId <> @Id)
			BEGIN
				SET @Msg = '返修类别名称重复，请检查！' + CHAR(10) + CHAR(10)
				SET @Msg = @Msg + '要放弃编辑，按【Esc】键可关闭窗口退出！'				
				RAISERROR(@MSG,16,1)
				RETURN -1
			END
			
		UPDATE	Qp_BackType
		SET		FullName = @FullName,
		        pycode =@pycode 
		WHERE	BackTypeId = @Id
		
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息修改失败！',16,1)
				RETURN -2
			END			
	END	
	
--删除
IF @nType = 'd'
	BEGIN
		--IF EXISTS(SELECT TOP 1 1 FROM PType_LastPrice)
		--	BEGIN
		--		RAISERROR('基本信息已经使用，不能删除！',16,1)
		--		RETURN -1
		--	END
	   IF EXISTS(SELECT TOP 1 1 FROM Billindex_CarRepair where BackTypeId=@Id)
			BEGIN
			   -- print '25555'
				RAISERROR('基本信息已经使用，不能删除！',16,1)
				RETURN -1
			END	
		DELETE FROM Qp_BackType WHERE BackTypeId = @Id
		
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息删除失败！',16,1)
				RETURN -2
			END
	END		
	
RETURN 0	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBalanceBillQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBalanceBillQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：韩林
	日期：2011-5-5
	描述：维修结算单查询
-------------------------------------------*/
CREATE PROCEDURE Web_QueryBalanceBillQuery
(
	@operatorid		VARCHAR(100),	--操作员ID
	@startdate		VARCHAR(MAX),	--开始日期
	@enddate		VARCHAR(MAX),	--截止日期
	@stypeid		VARCHAR(MAX),	--分支机构ID
	@btypeId		VARCHAR(MAX),	--往来单位ID
	@dtypeId		VARCHAR(MAX),	--部门ID
	@etypeId		VARCHAR(MAX),	--经手人ID
	@wcitypeid		VARCHAR(MAX),	--车牌号
	@operationsort	VARCHAR(MAX)='',			--业务类别
	@repairmode		VARCHAR(MAX)='',			--维修方式
	@billcode		VARCHAR(MAX)	--单据编号
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	

--车牌号
CREATE TABLE #GetManWTypeId(TypeId	varchar(100))
INSERT INTO #GetManWTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@wcitypeid,12,'00001')	

--构造SQL语句
DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'SELECT	Bc.billnumberid,
					Bc.receptiondate,
					Bc.balancedate,
					Bc.manhourtotal,
					Bc.manhourtaxtotal,
					Bc.manhourtaxtotal-Bc.manhourtotal as manhourtax,
					Bc.ptypetotal,
					Bc.ptypetaxtotal,
					Bc.ptypetaxtotal-Bc.ptypetotal as ptypetax,
					Bc.epibolyitem,
					Bc.epibolytotal,
					Bc.otheritem,
					Bc.othertotal,
					Bc.intendingkickback,
					Bc.settlementkickback,
					CASE Bc.settlementkickback -Bc.intendingkickback WHEN 0 THEN ''是'' ELSE ''否'' END AS iskickback,
					Bc.operationsort,
					Bc.RepairMode,
					Bc.RATypeID,
					RI.BTypeID AS BTypeID1,
					RI.AccidentDate,
					RI.AccidentAddr,
					RI.AccidentReason,
					B.billtype,
					B.BillCode,
					B.STypeId,
					B.BTypeId,
					CASE WHEN B.IfMulAccount = 1 THEN ''-99999'' ELSE ISNULL(B.atypeid,'''') END AS ATypeId,
					B.DTypeId,
					B.Explain,
					B.Comment,
					B.totalmoney - B.preferencemoney AS totalmoney,
					B.totalinmoney,
					B.preferencemoney,
					B.completetotal,
					B.totalmoney-B.totalinmoney-B.preferencemoney-B.completetotal AS losemoneytotal,
					Vc.VipCardCode,
					VcS.TypeName
			FROM	BillIndex B
			INNER JOIN BillIndex_CarRepair Bc ON B.BillNumberId = Bc.BillNumberId
			LEFT JOIN Qp_ReceptionBill_Insurance RI ON B.BillNumberId = RI.BillNumberId
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.BTypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			INNER JOIN #GetManWTypeId W ON W.TypeId =Bc.RATypeID
			LEFT JOIN nVipCardSign Vc ON B.vipcardid=Vc.vipcardid
			LEFT JOIN nVipCardSet Vcs ON VC.VipCardTypeID=Vcs.VipCardTypeID
			WHERE	Bc.BillState=4
					AND B.RedWord=0
					AND B.billtype=195
					AND Bc.balancedate>='''+@startdate+'''
					AND CONVERT (DATE,Bc.balancedate,120)<='''+@enddate+'''
					AND B.BillCode LIKE ''%'+@billcode+'%'''
IF @operationsort<>''				
	SET @SQL=@SQL+'AND	BC.operationsort='''+@operationsort+''''
IF @repairmode<>''
	SET @SQL=@SQL+'AND	Bc.repairmode='''+@repairmode+''''
SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志	
SET @SQL = @SQL + ' ORDER BY Bc.balancedate DESC,B.BillCode DESC'		
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManDTypeId,#GetManETypeId,#GetManWTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryBalanceRegulateList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryBalanceRegulateList
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	 银行存款(期初)余额调节表
-- 时间：	2014-05-21
-- 作者：	GLJ
-- ========================================================================
----9.6调整，余额调节表统计期初数据 hq
CREATE PROC Web_QueryBalanceRegulateList
(
	@isinit		INT,		--是否是期初调节
	@BankId		VARCHAR(10),--银行账户ID
	@BeginDate	DATETIME,	--开始日期
	@EndDate	DATETIME,	--截止日期
	@OperatorID	VARCHAR(50)	--操作员ID
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE  
	@init  NUMERIC(24, 10) ,@init1  NUMERIC(24, 10) ,
	@Add  NUMERIC(24, 10) ,@Add1  NUMERIC(24, 10) ,
	@Sub  NUMERIC(24, 10) ,@Sub1  NUMERIC(24, 10) 
--结果集临时表
CREATE TABLE #Temp(Id INT,CompanyStr VARCHAR(100),Company_Sum  NUMERIC(24, 10) ,BankStr VARCHAR(100),Bank_Sum  NUMERIC(24, 10) )

--期初数据查询到此
IF(@isinit=1)
BEGIN
--银行存款  期初
SELECT @init=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.InitBalanceOri,0)),0))
FROM Te_InitDataIndex I 
INNER JOIN Te_InitDataDetail D ON I.Id=D.IndexId AND ((D.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1 AND D.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID)))) AND I.BUId=2

--银行对账单  期初
SELECT @init1=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.InitBalanceOri,0)),0))
FROM Te_InitDataIndex I 
INNER JOIN Te_InitDataDetail D ON I.Id=D.IndexId AND ((D.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1 AND D.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID)))) AND I.BUId=3
INNER JOIN Ac_Currency C ON I.Cid=C.CId

--银行 FDebit 借方 FCredit 贷方
SELECT 
	@Add=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FCreditOri,0)),0)),
	@Sub=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FDebitOri,0)),0))
FROM Te_AccountInTransit_Index I
INNER JOIN Te_AccountInTransit_Detail D ON D.IndexId=I.Id AND ((I.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1 AND I.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID))))  AND D.CreateDate>=@BeginDate AND D.CreateDate<=@EndDate AND I.[Type]=1

--企业 FCredit 贷方 FDebit借方
SELECT 
	@Add1=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FDebitOri,0)),0)),
	@Sub1=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FCreditOri,0)),0))
FROM Te_AccountInTransit_Index I
INNER JOIN Te_AccountInTransit_Detail D ON D.IndexId=I.Id AND ((I.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1  AND I.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID))))  AND D.CreateDate>=@BeginDate  AND D.CreateDate<=@EndDate AND I.[Type]=0	


--结果集
INSERT INTO #Temp(Id,CompanyStr,Company_Sum,BankStr,Bank_Sum)
SELECT 1,'银行存款期初' ,ISNULl(@init,0),'银行对账单期初',ISNULl(@init1,0)  UNION 
SELECT 2,'加：银行已收企业未收',ISNULl(@Add,0),'加：企业已收银行未收',ISNULl(@Add1,0) UNION
SELECT 3,'减：银行已付企业未付',ISNULl(@Sub,0),'减：企业已付银行未付',ISNULl(@Sub1,0) UNION
SELECT 4,'调整后期初(企业)',ISNULl(@init+@Add-@Sub,0),'调整后期初(银行)',ISNULl(@init1+@Add1-@Sub1,0)

	SELECT * FROM #Temp ORDER BY Id 
	DROP TABLE #Temp 
	RETURN
END

DECLARE @FPeriod INT,@FBegin DATETIME,@Fyear INT
--如果查询截至日期在期间表内有对应期间，则取其对应期间值，否则取期间表中最大的期间年及其最大的期间
IF EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE @EndDate >= FBegin AND @EndDate <= FEnd)  
	SELECT @FPeriod=FPeriod,@FBegin=FBegin,@Fyear=Fyear FROM Ac_Period WHERE @EndDate BETWEEN FBegin AND FEnd
ELSE IF EXISTS(SELECT TOP 1 1 FROM Ac_Period WHERE @EndDate > FEnd)
BEGIN
	SELECT @Fyear=MAX(FYear) FROM Ac_Period
END

SELECT STypeId 
INTO #STYPE
FROM Te_StartPeriod TSP
INNER JOIN Ac_Period AP ON AP.FYear = TSP.SFYear AND AP.FPeriod = TSP.SFPeriod
WHERE TSP.SFYear <> 0 
	AND	TSP.SFPeriod <>0
	AND AP.FBegin <= @EndDate

--银行日记账调整前余额
--先计算期初数据
SELECT @init=ISNULL(SUM(ISNULL(D.InitBalanceOri,0)) ,0)
FROM Te_InitDataDetail D
INNER JOIN Te_InitDataIndex I ON I.Id = D.IndexId AND I.BUId = 2
INNER JOIN Te_BankAccount BA ON BA.Id = D.AccountId
INNER JOIN #STYPE S ON S.STypeId = BA.STypeId
WHERE ((D.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1 AND D.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID)))) 

--这里借贷的加减和科目无关，银行日记账是加借减贷
--再加上常规数据
SELECT @init+=ISNULL(SUM( ISNULL(D.FDebitOri,0)-ISNULL(D.FCreditOri,0) ),0)
FROM Te_Journal_Detail D
WHERE	D.IsCash=0 
	AND	D.IsInit=0 
	AND ((D.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1 AND D.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID)))) 
	AND D.Businessdate<=@EndDate	
	
--银行对账单调整前余额
--先计算期初数据
SELECT @init1=ISNULL(SUM(ISNULL(D.InitBalanceOri,0)) ,0)
FROM Te_InitDataDetail D
INNER JOIN Te_InitDataIndex I ON I.Id = D.IndexId AND I.BUId = 3
INNER JOIN Te_BankAccount BA ON BA.Id = D.AccountId
INNER JOIN #STYPE S ON S.STypeId = BA.STypeId
WHERE ((D.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1 AND D.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID)))) 


--这里借贷的加减和科目无关，银行对账单是加贷减借
--再加上常规数据
SELECT @init1+=dbo.f_roundtotal(ISNULL(SUM(CASE WHEN C.BasisType=0 THEN (ISNULL(D.FCredit,0)-ISNULL(D.FDebit,0))*D.Rate ELSE (ISNULL(D.FCredit,0)-ISNULL(D.FDebit,0))/D.Rate END),0)) 
FROM Te_BankStatementDetail D
INNER JOIN Ac_Currency C ON C.Cid=D.CId 
INNER JOIN Te_BankAccount BA ON BA.Id = D.AccountId
INNER JOIN Ac_Account AC ON AC.TypeId = BA.ATypeId AND AC.StypeId = BA.STypeId
WHERE IsInit=0 
AND ((D.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1  AND D.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID)))) 
AND D.Businessdate<=@EndDate	


--银行 FCredit 贷方 FDebit 借方 
SELECT 
	@Add=dbo.f_roundtotal(ISNULL(SUM(CASE WHEN C.BasisType=0 THEN ISNULL(I.FCredit,0)*I.Rate ELSE ISNULL(I.FCredit,0)/I.Rate END),0)),
	@Sub=dbo.f_roundtotal(ISNULL(SUM(CASE WHEN C.BasisType=0 THEN ISNULL(I.FDebit,0)*I.Rate ELSE ISNULL(I.FDebit,0)/I.Rate END),0))
FROM Te_BankStatementDetail I
INNER JOIN Ac_Currency C ON C.CId=I.Cid	
WHERE 
	I.Id NOT IN(SELECT StatementId FROM Te_CheckRelevance WHERE StatementId IS NOT NULL)
	AND ((I.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1  AND I.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID))))
	AND I.Businessdate>=@BeginDate AND I.Businessdate<=@EndDate

--加上未达账的
SELECT 
	@Add+=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FCreditOri,0)),0)),
	@Sub+=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FDebitOri,0)),0))
FROM Te_AccountInTransit_Index I
INNER JOIN Te_AccountInTransit_Detail D ON D.IndexId=I.Id AND ((I.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1 AND I.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID))))  AND D.CreateDate>=@BeginDate AND D.CreateDate<=@EndDate AND I.[Type]=1
WHERE	D.Id NOT IN(SELECT StatementAccountInTransitId FROM Te_CheckRelevance WHERE StatementAccountInTransitId IS NOT NULL)
	AND D.CreateDate>=@BeginDate AND D.CreateDate<=@EndDate
	
--select @BeginDate,@EndDate
--企业  FDebit借方 FCredit 贷方
SELECT 
	@Add1=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FDebitOri,0)),0)),
	@Sub1=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FCreditOri,0)),0))
FROM Te_Journal_Detail D
WHERE
	D.Id NOT IN(SELECT JournalId FROM Te_CheckRelevance WHERE JournalId IS NOT NULL)
	AND D.IsCash=0 
	AND ((D.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1 AND D.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID))))
	AND D.BusinessDate>=@BeginDate  AND D.BusinessDate<=@EndDate
	
--加上未达账的
SELECT 
	@Add1+=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FDebitOri,0)),0)),
	@Sub1+=dbo.f_roundtotal(ISNULL(SUM(ISNULL(D.FCreditOri,0)),0))
FROM Te_AccountInTransit_Index I
INNER JOIN Te_AccountInTransit_Detail D ON D.IndexId=I.Id AND ((I.AccountId=@BankId AND @BankId<>-1) OR (@BankId=-1  AND I.AccountId IN (SELECT TypeId FROM DBO.F_LineBank(@OperatorID))))  AND D.CreateDate>=@BeginDate  AND D.CreateDate<=@EndDate AND I.[Type]=0
WHERE	D.Id NOT IN(SELECT JournalAccountInTransitId FROM Te_CheckRelevance WHERE JournalAccountInTransitId IS NOT NULL)
	AND D.CreateDate>=@BeginDate AND D.CreateDate<=@EndDate

--结果集
INSERT INTO #Temp(Id,CompanyStr,Company_Sum,BankStr,Bank_Sum)
SELECT 1,'银行存款余额' ,ISNULl(@init,0),'银行对账单余额',ISNULl(@init1,0)  UNION 
SELECT 2,'加：银行已收企业未收',ISNULl(@Add,0),'加：企业已收银行未收',ISNULl(@Add1,0) UNION
SELECT 3,'减：银行已付企业未付',ISNULl(@Sub,0),'减：企业已付银行未付',ISNULl(@Sub1,0) UNION
SELECT 4,'调整后余额(企业)',ISNULl(@init+@Add-@Sub,0),'调整后余额(银行)',ISNULl(@init1+@Add1-@Sub1,0)

SELECT * FROM #Temp ORDER BY Id  



DROP TABLE #Temp,#STYPE
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBaseInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBaseInfo]
GO


















/*
	作者：谢吉康
	日期：2005-8-10
	描述：基本信息的选择
*/
CREATE PROCEDURE Web_QueryBaseInfo
(
	@OperatorId		varchar(100),	--操作员Id	
	@bType			varchar(10),	--基本信息类型
	@TypeId			varchar(100),	--基本信息的Id
	@Xjkang			varchar(100)=''	--销售分布显示其他信息
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--************************************************************部门基本信息************************************************************
IF @bType = 'D'
	BEGIN
		CREATE TABLE #DType
		(
			TypeId 		varchar(100),
			SonNum		int,
			UserCode	varchar(256),
			FullName	varchar(256)
		)

		DECLARE @dSonNum int

		SELECT @dSonNum = SonNum FROM Department WHERE TypeId = @TypeId AND Deleted = 0
		IF @dSonNum = 0
			BEGIN
				INSERT INTO #DType
				SELECT	TypeId,
						SonNum,
						UserCode,
						FullName
				FROM	Department
				WHERE	Deleted = 0
						AND SonNum = 0
						AND TypeId LIKE @TypeId + '%'
					 	AND TypeId <> '00000'
			END
		ELSE
			BEGIN
				INSERT INTO #DType
				SELECT	TypeId,
						SonNum,
						UserCode,
						FullName
				FROM	Department
				WHERE	Deleted = 0						
						AND ParId = @TypeId
					 	AND TypeId <> '00000'
			END

		IF @TypeId = '00000'
			INSERT INTO #DType(TypeId,SonNum,UserCode,FullName)VALUES('99999',0,'其他部门','其他部门')

		SELECT * FROM #DType ORDER BY UserCode

		DROP TABLE #DType
	END
--************************************************************职员基本信息************************************************************
IF @bType = 'E'
	BEGIN
		DECLARE @eSonNum int

		IF @TypeId = '00001'  AND @OperatorId <> '00001'
			SET @TypeId = @METypeId

		SELECT @eSonNum = SonNum FROM Employee WHERE TypeId = @TypeId AND Deleted = 0

		IF @eSonNum = 0
			SELECT	TypeId,
					SonNum,
					UserCode,
					FullName
			FROM 	Employee
			WHERE	Deleted = 0
					AND SonNum = 0
					AND TypeId = @TypeId 
					AND TypeId LIKE @METypeId + '%'
			ORDER BY UserCode
		ELSE
			SELECT	TypeId,
					SonNum,
					UserCode,
					FullName
			FROM 	Employee
			WHERE	Deleted = 0
					AND ParId = @TypeId 
					AND TypeId LIKE @METypeId + '%'		
			ORDER BY UserCode	
	END
--************************************************************商品基本信息************************************************************
IF @bType = 'P'
	BEGIN
		DECLARE @pSonNum int

		IF @TypeId = '00000' 
			SET @TypeId = @MPTypeId

		SELECT @pSonNum = SonNum FROM PType WHERE TypeId = @TypeId AND Deleted = 0

		IF @pSonNum = 0
			SELECT	TypeId,
					SonNum,
					UserCode,
					FullName
			FROM 	PType
			WHERE	Deleted = 0
					AND SonNum = 0
					AND TypeId = @TypeId 
					AND TypeId LIKE @MPTypeId + '%'
			ORDER BY UserCode
		ELSE
			SELECT	TypeId,
					SonNum,
					UserCode,
					FullName
			FROM 	PType
			WHERE	Deleted = 0
					AND ParId = @TypeId 
					AND TypeId LIKE @MPTypeId + '%'		
			ORDER BY UserCode	
	END
--************************************************************仓库基本信息************************************************************
IF @bType = 'K'
	BEGIN
		DECLARE @kSonNum int

		IF @Xjkang = 'xiejikang'
			BEGIN
				IF @TypeId = '00000' AND @OperatorId <> '00001'
					IF @MKTypeId <> ''
						SET @TypeId = @MKTypeId
			END

		SELECT @kSonNum = SonNum FROM Stock WHERE TypeId = @TypeId AND Deleted = 0

		CREATE TABLE #Stock
		(
			TypeId		varchar(100),
			SonNum		int,
			UserCode	varchar(256),
			FullName	varchar(256)
		)

		IF @kSonNum = 0
			INSERT 	INTO #Stock			
			(
				TypeId,
				SonNum,
				UserCode,
				FullName
			)
			SELECT	TypeId,
					SonNum,
					UserCode,
					FullName
			FROM 	Stock
			WHERE	Deleted = 0
					AND SonNum = 0
					AND TypeId = @TypeId 
					AND TypeId LIKE @MKTypeId + '%'
			ORDER BY UserCode
		ELSE
			INSERT 	INTO #Stock			
			(
				TypeId,
				SonNum,
				UserCode,
				FullName
			)
			SELECT	TypeId,
					SonNum,
					UserCode,
					FullName
			FROM 	Stock
			WHERE	Deleted = 0
					AND ParId = @TypeId 
					AND TypeId LIKE @MKTypeId + '%'			
			ORDER BY UserCode


		IF @Xjkang = 'xiejikang' AND (@TypeId = '00000' OR @TypeId = @MKTypeId)
			INSERT 	INTO #Stock(TypeId,SonNum,UserCode,FullName)VALUES('10000',0,'10000','代销仓库')

		SELECT * FROM #Stock

		DROP TABLE #Stock			
	END
--************************************************************单位基本信息************************************************************
IF @bType = 'B'
	BEGIN
		DECLARE @bSonNum 	int,
				@BTypeAll	int
		
		SELECT	@BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

		IF @BTypeAll = 0
			BEGIN
				IF @Xjkang = ''
					BEGIN
						SELECT @bSonNum = SonNum FROM BType WHERE TypeId = @TypeId AND Deleted = 0

						IF @TypeId = '00000'				
							SET @TypeId = @MBTypeId
					END
				ELSE
					BEGIN
						SET @bSonNum = 0
	
						IF @TypeId = '00000'						
							SET @BTypeAll = 1
					END		
			END
		ELSE
			SELECT @bSonNum = SonNum FROM BType WHERE TypeId = @TypeId AND Deleted = 0

		IF @BTypeAll = 0	--客户和供货商不统一
			BEGIN
				IF @bSonNum = 0
					SELECT	TypeId,
							SonNum,
							UserCode,
							FullName
					FROM 	BType
					WHERE	Deleted = 0
							AND SonNum = 0
							AND TypeId = @TypeId 
							AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
					ORDER BY UserCode
				ELSE
					SELECT	TypeId,
							SonNum,
							UserCode,
							FullName
					FROM 	BType
					WHERE	Deleted = 0
							AND ParId = @TypeId 
							AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
					ORDER BY UserCode
			END
		ELSE				--客户和供货商统一
			BEGIN
				IF @TypeId = '00000'
					BEGIN
						IF @bSonNum = 0
							SELECT	TypeId,
									SonNum,
									UserCode,
									FullName
							FROM 	BType
							WHERE	Deleted = 0
									AND SonNum = 0
									AND TypeId LIKE 
											CASE
												WHEN @TypeId = '00000' THEN '%'
												ELSE @TypeId + '%'
											END
									AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
							ORDER BY UserCode
						ELSE
							BEGIN
								IF @MBTypeId = '00001' AND @MBTypeId2 = '00002' --所有权限
									SELECT	TypeId,
											SonNum,
											UserCode,
											FullName
									FROM 	BType
									WHERE	Deleted = 0
											AND ParId = @TypeId 
											AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
									ORDER BY UserCode
								ELSE
									SELECT	TypeId,
											SonNum,
											UserCode,
											FullName
									FROM 	BType
									WHERE	Deleted = 0
											AND SonNum = 0
											AND TypeId LIKE 
													CASE
														WHEN @TypeId = '00000' THEN '%'
														ELSE @TypeId + '%'
													END
											AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
									ORDER BY UserCode
							END
					END
				ELSE
					BEGIN
						IF @bSonNum = 0
							SELECT	TypeId,
									SonNum,
									UserCode,
									FullName
							FROM 	BType
							WHERE	Deleted = 0
									AND SonNum = 0
									AND TypeId = @TypeId 
									AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
							ORDER BY UserCode
						ELSE
							IF @MBTypeId = '00001' AND @MBTypeId2 = '00002'	--全部权限范围				
								SELECT	TypeId,
										SonNum,
										UserCode,
										FullName
								FROM 	BType
								WHERE	Deleted = 0
										AND ParId = @TypeId
										AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
								ORDER BY UserCode
							ELSE
								SELECT	TypeId,
										SonNum,
										UserCode,
										FullName
								FROM 	BType
								WHERE	Deleted = 0
										AND TypeId LIKE @TypeId + '%'
										AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%')
								ORDER BY UserCode
					END
			END
	END



















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBatchPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBatchPrice]
GO











/*
	作者：谢吉康
	日期：2005-1-18
	描述：分支机构预设售价的查询
*/
CREATE PROCEDURE Web_QueryBatchPrice
(
	@OperatorId		varchar(50),	--操作员ID
	@DTypeId		varchar(100),	--分支机构ID
	@PTypeId		varchar(100),	--商品ID
	@UserCode		varchar(256),	--商品编号
	@FullName		varchar(1000)	--商品名称	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @PTypeId = ''
	SET @PTypeId = '00000'

DECLARE @SonNum int,
		@SQL	varchar(8000)

SELECT @SonNum = SonNum FROM PType WHERE TypeId = @PTypeId AND Deleted = 0

SET	@SQL = '
	SELECT	P.TypeId,
			P.SonNum,
			P.UserCode,
			P.FullName,
			P.EntryCode,
			P.Standard,
			P.Type,
			P.Deleted,
			ISNULL(SUM(D.PrePrice1),0) AS PrePrice1,
			ISNULL(SUM(D.PrePrice2),0) AS PrePrice2,
			ISNULL(SUM(D.PrePrice3),0) AS PrePrice3,
			ISNULL(SUM(D.PrePrice4),0) AS PrePrice4,
			ISNULL(SUM(D.recPrice),0) AS recPrice,
			Explain	= (SELECT Explain FROM BatchPrice WHERE P.TypeId = PTypeId AND DepartId = '+char(39)+@DTypeId+char(39)+' AND P.Deleted = 0)
	FROM	PType p
	LEFT JOIN (
		SELECT	PTypeId,
				DepartId,
				ISNULL(PrePrice1,0) AS PrePrice1,
				ISNULL(PrePrice2,0) AS PrePrice2,
				ISNULL(PrePrice3,0) AS PrePrice3,
				ISNULL(PrePrice4,0) AS PrePrice4,
				ISNULL(recPrice,0)  AS recPrice,
				Explain,
				[Default]
		FROM 	BatchPrice
		WHERE	DepartId = '+char(39)+@DTypeId+char(39)+'
				AND PTypeId LIKE '+char(39)+@MPTypeId+'%'+char(39)+'
				AND DepartId LIKE '+char(39)+@MDTypeId+'%'+char(39)+'
	)D ON LEFT(D.PTypeId,LEN(P.TypeId))=P.TypeId
	WHERE	P.Deleted = 0 
			AND P.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
			AND P.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
			AND P.TypeId LIKE '+char(39)+@MPTypeId+'%'+char(39)

IF @UserCode <> '' OR @FullName <> ''
	SET @SQL = @SQL + ' AND P.SonNum = 0 '
ELSE
	BEGIN
		IF @SonNum = 0 
			SET @SQL = @SQL + ' AND TypeId = '+char(39)+@PTypeId+char(39)
		ELSE
			SET @SQL = @SQL + ' AND ParId = '+char(39)+@PTypeId+char(39)
	END

SET @SQL = @SQL + ' 
	GROUP BY
			P.TypeId,
			P.SonNum,
			P.UserCode,
			P.FullName,
			P.EntryCode,
			P.Standard,
			P.Type,
			P.Deleted
	ORDER BY
			P.UserCode'

--PRINT(@SQL)
EXEC(@SQL)
		











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1  From sys.types t JOin sys.schemas ss ON t.schema_id=ss.schema_id WHERE t.name= N'Type_BillMulBrandar' AND ss.name=N'dbo')
BEGIN
	if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryBillMulBrandarDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		DROP PROCEDURE [dbo].[Web_QueryBillMulBrandarDetails]--删除此存储过程的引用
		
	DROP type [dbo].Type_BillMulBrandar 
END
GO
CREATE TYPE Type_BillMulBrandar AS TABLE					--该表列同表AC_INIACCOUNT
(
	BrandarTypeID	VARCHAR(50),
	NTaxTotal		NUMERIC(22,10),
	NPreferenceMoney NUMERIC(22,10),
	NTotalinMoney	NUMERIC(22,10),
	NYSTotalinMoney	NUMERIC(22,10),
	NTheOrderARTotal NUMERIC(22,10)
)
GO

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryBillMulBrandarDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_QueryBillMulBrandarDetails]
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：多账户 商品品牌余额信息
	日期：2012-03-31
	描述：科目余额表查询
-------------------------------------------*/
CREATE PROCEDURE Web_QueryBillMulBrandarDetails
(
	@STypeId 		VARCHAR(50),--分支机构ID
	@BTypeId		VARCHAR(50),--往来单位ID
	@BrandarStr		VARCHAR(MAX),--商品品牌ID信息
	@CId			INT,--币种
	@OperatorID		VARCHAR(50),---操作员ID
	@isIni			INT,		--是否期初
	@MulBrand		Type_BillMulBrandar READONLY
)
AS 
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @IsUse INT--业务分支机构是否开账
SELECT @IsUse=Value FROM SType_UserConfig WHERE StypeId=@STypeId

--最新数据表
CREATE TABLE #Brand(BrandarTypeID VARCHAR(50),NTaxTotal NUMERIC(22,10))
INSERT INTO #Brand(BrandarTypeID,NTaxTotal)
SELECT
	B.TypeId BrandarTypeID,
	ISNULL(SUM(CAST(SUBSTRING(F.a,CHARINDEX('=',F.a)+1,LEN(F.a)) AS NUMERIC(22,10))),0) NTaxTotal
FROM brandar_Commodity B
INNER JOIN f_split(@BrandarStr,',') F ON SUBSTRING(F.a,1,CHARINDEX('=',F.a)-1)=B.TypeId
GROUP BY 
	B.TypeId,
	B.FullName
	
SELECT
	B.BrandarTypeID,
	BC.FullName BrandarFullName,
	CASE WHEN @IsUse=1 THEN ISNULL(T.NYSTotal,0) ELSE ISNULL(T.NYSTotal00,0) END NYSTotal,--预收金额
	CASE WHEN @IsUse=1 THEN ISNULL(T.NARTotal,0) ELSE ISNULL(T.NARTotal00,0) END NARTotal,--应收金额
	CASE WHEN @IsUse=1 THEN ISNULL(T.NARTotal,0)-ISNULL(T.NYSTotal,0) ELSE ISNULL(T.NARTotal00,0)-ISNULL(T.NYSTotal00,0) END NTotal,--品牌余额
	CASE WHEN ISNULL(M.BrandarTypeID,'')='' THEN ISNULL(B.NTaxTotal,0) 
		 WHEN ISNULL(M.BrandarTypeID,'')=ISNULL(B.BrandarTypeID,'') AND ISNULL(B.NTaxTotal,0)<>ISNULL(M.NTaxTotal,0) THEN ISNULL(B.NTaxTotal,0)
		 ELSE ISNULL(M.NTaxTotal,0) END NTaxTotal,--发货金额
	ISNULL(M.NPreferenceMoney,0) NPreferenceMoney,--抹零金额
	ISNULL(M.NTotalinMoney,0) NTotalinMoney,--现收金额
	ISNULL(M.NYSTotalinMoney,0) NYSTotalinMoney,--预收冲抵
	((CASE WHEN ISNULL(M.BrandarTypeID,'')='' THEN ISNULL(B.NTaxTotal,0) 
		 WHEN ISNULL(M.BrandarTypeID,'')=ISNULL(B.BrandarTypeID,'') AND ISNULL(B.NTaxTotal,0)<>ISNULL(M.NTaxTotal,0) THEN ISNULL(B.NTaxTotal,0)
		 ELSE ISNULL(M.NTaxTotal,0) END)-ISNULL(M.NPreferenceMoney,0)-ISNULL(M.NTotalinMoney,0)-ISNULL(M.NYSTotalinMoney,0)) NTheOrderARTotal,--本单应收
	1 isUse
FROM #Brand B
INNER JOIN brandar_Commodity BC ON BC.TypeId=B.BrandarTypeID
LEFT JOIN Brandar_ArApTotal T ON T.BrandarTypeID=B.BrandarTypeID AND T.StypeID=@STypeId AND T.BtypeID=@BTypeId AND T.CId=@CId
LEFT JOIN @MulBrand M ON M.BrandarTypeID=B.BrandarTypeID
WHERE 
	B.NTaxTotal<>0
UNION ALL
SELECT
	M.BrandarTypeID,
	BC.FullName BrandarFullName,
	CASE WHEN @IsUse=1 THEN ISNULL(T.NYSTotal,0) ELSE ISNULL(T.NYSTotal00,0) END NYSTotal,--预收金额
	CASE WHEN @IsUse=1 THEN ISNULL(T.NARTotal,0) ELSE ISNULL(T.NARTotal00,0) END NARTotal,--应收金额
	CASE WHEN @IsUse=1 THEN ISNULL(T.NARTotal,0)-ISNULL(T.NYSTotal,0) ELSE ISNULL(T.NARTotal00,0)-ISNULL(T.NYSTotal00,0) END NTotal,--品牌余额
	ISNULL(M.NTaxTotal,0) NTaxTotal,
	ISNULL(M.NPreferenceMoney,0) NPreferenceMoney,
	ISNULL(M.NTotalinMoney,0) NTotalinMoney,
	ISNULL(M.NYSTotalinMoney,0) NYSTotalinMoney,
	ISNULL(M.NTheOrderARTotal,0) NTheOrderARTotal,
	0 isUse
FROM @MulBrand M
INNER JOIN brandar_Commodity BC ON BC.TypeId=M.BrandarTypeID
LEFT JOIN Brandar_ArApTotal T ON T.BrandarTypeID=M.BrandarTypeID AND T.StypeID=@STypeId AND T.BtypeID=@BTypeId AND T.CId=@CId
WHERE 
	NOT EXISTS(SELECT * FROM #Brand B WHERE B.BrandarTypeID=M.BrandarTypeID AND B.NTaxTotal<>0)
ORDER BY BC.FullName

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBillOperaterLog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_QueryBillOperaterLog
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-08-31
-- Description: 单据操作日志
-- =============================================
CREATE PROCEDURE Web_QueryBillOperaterLog
(
	@billnumberid INT,
	@billtype INT
)
--@encode$--
AS
SET NOCOUNT ON

SELECT	ID,
		BillnumberID,
		OperateType,
		OperateTime,
		EtypeID,
		IP ,
		billcode,
		billdate,
		CASE WHEN ifcheck='t' THEN '过账' ELSE CASE WHEN ifcheck='f' THEN  '草稿' ELSE OperateType END  END AS ifcheck
FROM	BillOperateLog 
WHERE	BillnumberID=@billnumberid
	AND billtype = @billtype
ORDER BY OperateTime


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBillStatReortDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBillStatReortDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：2016-05-11
	描述：单据统计明细
*/
CREATE PROCEDURE Web_QueryBillStatReortDetail
(
	@OperatorId		VARCHAR(50),	    -- 当前操作员ID
	@billtype		VARCHAR(50),
	@BeginDate	    varchar(30),	    --查询起始时间
	@EndDate		varchar(30),    	-- 查询结束时间 
	@STypeId        varchar(MAX),		--分支机构
	@ETypeID		varchar(MAX),		-- 经手人	
	@KtypeId 	    varchar(MAX)='',	--出\入库仓库
	@BtypeID		VARCHAR(max)=''	,   --往来单位
	@BillCode       varchar(200)='',	--单据编号
	@Comment        varchar(200)='',	--摘要
	@PTypeId		varchar(200)   	-- 商品
)
--@encode$--
AS
SET NOCOUNT ON

--商品
CREATE TABLE #PTYPE(Typeid varchar(100))
INSERT INTO #PTYPE(Typeid)	SELECT TypeId  FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorId)
--分支机构
CREATE TABLE #SType(TypeId	varchar(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)	
--经手人
CREATE TABLE #EType(TypeId	varchar(100))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeID,3,@OperatorId)
--出\入库仓库
CREATE TABLE #KType(TypeId	varchar(100))
INSERT INTO #KType(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorId)
 --往来单位
CREATE TABLE #bType(TypeId	varchar(100))
INSERT INTO #bType(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@BtypeID,2,@OperatorId)

SELECT  a.BillNumberId,
        a.BillDate,
		a.BillCode
		,a.STypeID,
		a.etypeid,
		b.ptypeid,
		a.DTypeId,
		b.kTypeID,
		c.FullName AS unitfullname,
		ABS(CONVERT( NUMERIC(24, 10) ,b.Qty/d.Rate)) mqty,
		CONVERT( NUMERIC(24, 10) ,b.saleprice*d.Rate) AS msaleprice,
		(SELECT FullName FROM PType_Units WHERE UnitsId=p.baseUnitId)basefullname,
		ABS(b.Qty) AS baseqty,
		'1'+c.FullName+'='+CONVERT(NVARCHAR(100),CAST(d.Rate AS REAL)) +(SELECT FullName FROM PType_Units WHERE UnitsId=p.baseUnitId) AS unitrelation,
		b.saleprice AS baseprice,
		ABS(b.saletotal) AS saletotal,
		CONVERT( NUMERIC(24, 10) ,b.TaxPrice*d.Rate) AS mtaxprice,
		ABS(b.taxtotal) AS taxtotal,
	    a.checke,
		a.checkTime,
		a.Poster,
		a.posttime,
		a.Comment,
		a.explain,
		b.BillType,
		b.ID,
		SysDiy1_head ,
        SysDiy2_head ,
        SysDiy3_head ,
        SysDiy4_head ,
        SysDiy5_head ,
        SysDiy6_head ,
        SysDiy7_head ,
        SysDiy8_head ,
        SysDiy9_head ,
        SysDiy10_head ,
        SysDiy11_head ,
        SysDiy12_head ,
        SysDiy13_head ,
        SysDiy14_head ,
        SysDiy15_head ,
        SysDiy16_head ,
        SysDiy1 ,
        SysDiy2 ,
        SysDiy3 ,
        SysDiy4 ,
        SysDiy5 ,
        SysDiy6 ,
        SysDiy7 ,
        SysDiy8 ,
        SysDiy9 ,
        SysDiy10 ,
        SysDiy11 ,
        SysDiy12 ,
        SysDiy13 ,
        SysDiy14 ,
        SysDiy15 ,
        SysDiy16
FROM dbo.BillIndex a  
INNER JOIN dbo.InOutstocktable b  ON a.BillNumberId=b.BillNumberId 
	INNER JOIN PType_Units c ON c.UnitsId=b.MUNITID
	INNER JOIN dbo.PType_Units_Ext d  ON b.PtypeId=d.PtypeID AND b.MUNITID=d.UnitsId
	INNER JOIN dbo.ptype p  ON p.typeId=b.PtypeId 
	INNER JOIN #PTYPE p1 ON p1.Typeid=b.PtypeId
	INNER JOIN #EType e ON e.TypeId= a.etypeid
	INNER JOIN #SType s  ON s.TypeId =b.STypeID
	INNER JOIN #KType k  ON k.TypeId=b.KtypeId
	LEFT JOIN Custom_BillIndex csindex ON a.billnumberid = csindex.BillId AND a.billtype = csindex.billtype
    LEFT JOIN Custom_BillDetails csdetail ON a.billnumberid = csdetail.BillId AND a.billtype = csdetail.billtype AND b.id = csdetail.Detailid
WHERE  a.RedWord=0
     AND a.BillDate BETWEEN @BeginDate  AND  @EndDate
     AND a.BillCode LIKE '%'+@BillCode+'%'
     AND a.Comment LIKE '%'+@comment+'%'
     AND  a.billtype=@billtype
     

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** Object:  StoredProcedure [dbo].[Web_QueryBindbtype]    Script Date: 11/18/2013 09:09:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBindbtype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBindbtype]
GO

/*
	作者：唐韬
	日期：2013-11-15
	描述：查询平台订货商
*/

CREATE  PROCEDURE [dbo].[Web_QueryBindbtype]
(
	@btypeid	varchar(max), 				--  1、往来单位
	@IsBind			int=0,				--  2、绑定状态 0=全 部,1=已绑定,2=未绑定
	@IsDisable		int=0				--  3、是否停用	 0=全 部,1=不显示停用,2=显示停用	
)
--@encode$--
AS

BEGIN
	DECLARE @SQL VARCHAR(8000)
	DECLARE @JoinCondition VARCHAR(20)
	IF @btypeid=''
		SET @btypeid='0000'
	IF @IsBind = 0
		SET @JoinCondition = ' LEFT '
	ELSE IF @IsBind = 1
		SET @JoinCondition = ' RIGHT '
		
	SET @SQL = ' SELECT b1.typeId, b1.FullName,b2.MerchantName,b2.priceLevel ,b2.MerchantId 
			 FROM dbo.btype b1
			 INNER JOIN (SELECT a as typeid FROM f_split('''+@btypeid+''','','')) b3 on left(b1.typeid,len(b3.typeid))=b3.typeid 
			 ' + @JoinCondition +' JOIN dbo.Yapi_btypeBindMerchant b2 
			 ON b1.typeId=b2.btypeid
			 WHERE Isnull(b2.IsSeller,0)=0 '	
	IF @IsBind = 2
	    SET @SQL = 'SELECT b1.typeId, b1.FullName , MerchantName=NULL, priceLevel = NULl ,MerchantId  = NULL 
					FROM dbo.btype b1
					INNER JOIN (SELECT  a as typeid FROM f_split('''+@btypeid+''','','')) b3 on left(b1.typeid,len(b3.typeid))=b3.typeid
					 WHERE b1.typeId 
					
					NOT IN ( SELECT btypeid FROM dbo.Yapi_btypeBindMerchant ) '
					
	--deleted是否停用标识 0.正常 1.已停用
	IF @IsDisable = 1
		SET @SQL += ' AND b1.deleted = 0 '
	ELSE IF  @IsDisable = 2
		SET @SQL += ' AND b1.deleted = 1 '
	SET @sql +=' and b1.sonnum=0 '
	--判断客户供货商是否区分
	IF EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName='btypeall' AND Value='0')
		SET @sql +='  and left(b1.typeid,5)=''00001'''
	--PRINT (@SQL)

	EXEC(@SQL)
	
END

GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBorrowLendDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBorrowLendDraft
GO

/*------------------------------------------
 作者：蒋奎
 日期：2015-04-20
 描述：借欠草稿查询
-------------------------------------------*/
 
CREATE          PROCEDURE Web_QueryBorrowLendDraft
( 
	@OperatorID		VARCHAR(50),
	@BeginDate		VARCHAR(25)='',
	@EndDate		VARCHAR(25)='',
	@BillCode		VARCHAR(200)='',
	@BillType		VARCHAR(5)='',
	@EtypeName		VARCHAR(max)='',  --经手人
	@BtypeName		VARCHAR(max)='',  --客户
	@KtypeName		VARCHAR(max)='',  --仓库
	@Comment		VARCHAR(256)='',
	@Explain		VARCHAR(256)='',
	@Memo			VARCHAR(256)='',
	@BillNumberId	NUMERIC(10)=0,
	@OrderBy		VARCHAR(250)='',
	@FilterBill		VARCHAR(250)='',
	@STypeId		VARCHAR(MAX),
	@DraftState		VARCHAR(2),		--全部3,原始 2 ,待审核 0 ,审核不通过-1, 审核通过1
	@IsReporting	INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

DECLARE @SQLFrom  VARCHAR(2000)
DECLARE @SQLList  VARCHAR(3000)
DECLARE @SQLWhere VARCHAR(8000)
DECLARE @SQLOrder VARCHAR(200)

SELECT @SQLFrom  = ''
SELECT @SQLList  = ''
SELECT @SQLWhere = ''
SELECT @SQLOrder = ''

--多级权限
SELECT a.* INTO #btype FROM F_GetManBtypeAll(@OperatorID) a --往来单位权限
SELECT a.* INTO #stock FROM F_GetManKtypeAll(@OperatorID) a --仓库权限
SELECT a.TypeId INTO #employee FROM F_GetManDetailEtype(@OperatorID) a --职员权限
IF ISNULL(@EtypeName,'') = ''
	INSERT INTO #employee(TypeId)VALUES('')

-- 基本的显示字段
SELECT @SQLList = 'SELECT bi.*'
		     +',CBillType= '
		     +' CASE bi.BillType '
				 +' WHEN 71 THEN ''借进'' '
				 +' WHEN 72  THEN ''借进还出'' '
				 +' WHEN 87  THEN ''借出'' '
				 +' WHEN 88 THEN ''借出还回'' '
		     +' END '
             +',ISNULL(e.TypeId,'''') AS etype '
		     +',ISNULL(k1.TypeId,'''') AS Ktype '
		     +',ISNULL(k1.usercode,'''') AS kusercode '
		     +',ISNULL(k2.FULLNAME,'''') AS Ktype2 '
		     +',ISNULL(b.TypeId,'''') AS btype '
		     +',ISNULL(a.TypeId,'''') AS atype '
		     +',ISNULL(p.TypeId,'''') AS ptype '
		     +',ISNULL(e.FULLNAME,'''') AS checkman '
		     +',ISNULL(e1.FULLNAME,'''') AS checkefullname '
		     +',states.DraftState '
		     +',SysDiy1_head '
		     +',SysDiy2_head '
		     +',SysDiy3_head '
		     +',SysDiy4_head '
		     +',SysDiy5_head '
		     +',SysDiy6_head '
		     +',SysDiy7_head '
		     +',SysDiy8_head '
		     +',SysDiy9_head '
		     +',SysDiy10_head '
		     +',SysDiy11_head '
		     +',SysDiy12_head '
		     +',SysDiy13_head '
		     +',SysDiy14_head '
		     +',SysDiy15_head '
		     +',SysDiy16_head  '

		     
--基本列表的SQL
SELECT @SQLFrom=' FROM	LendIndex bi 
						INNER JOIN (	/*草稿状态集合*/
               							SELECT	
               								DraftState = dbo.F_GetBorrowLendDraftState(billnumberid),
               								 billnumberid
										FROM LendIndex 
										WHERE draft=1  AND IsIni=0
						
               						) states  ON states.billnumberid=bi.billnumberid'
 
				
				  +' LEFT JOIN Custom_BillIndex csindex on  bi.billnumberid=csindex.BillId and csindex.billtype= bi.Billtype '
				  +' LEFT JOIN Btype b ON (bi.[dealBTypeId] = b.[TypeId]) '
				  +' LEFT JOIN Stock k1 ON (bi.[KtypeId] = k1.[Typeid]) '
				  +' LEFT JOIN Employee e ON (bi.[EtypeId] = e.[Typeid]) '
				  +' LEFT JOIN Employee e1 ON (bi.[checke] = e1.[Typeid]) '
				  +' LEFT  JOIN Atype a ON (bi.[AtypeId] = a.[TypeId]) '
				  +' LEFT  JOIN Ptype p ON (bi.[PtypeId] = p.[TypeId]) '
				  +' LEFT  JOIN Stock k2 ON (bi.[KtypeId2] = k2.[Typeid])'
									 +' RIGHT OUTER JOIN (SELECT dbo.lendbill.billNumberId FROM lendbill WHERE (dbo.LendBill.comment LIKE ''%'
				  +RTRIM(@Memo)
				  +'%'') GROUP BY dbo.LendBill.billNumberId)  lb ON (bi.BillNumberId = lb.BillNumberId) '
		      
-- 限制条件
IF RTRIM(@BeginDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillDate]>=''' + RTRIM(@BeginDate) +''' '
IF RTRIM(@EndDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillDate]<=''' + RTRIM(@EndDate) +''' '
IF @BillNumberId<>0
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillNumberID]=' + STR(@BillNumberId) +' '
IF RTRIM(@BillCode)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillCode] LIKE ''%' + RTRIM(@BillCode) +'%'' '
IF RTRIM(@Comment)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[Comment] LIKE ''%' + RTRIM(@Comment) +'%'' '
IF RTRIM(@Explain)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[Explain] LIKE ''%' + RTRIM(@Explain) +'%'' '
IF RTRIM(@BillType)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND bi.[BillType] = ' + RTRIM(@BillType) +' '

IF RTRIM(@EtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.[etypeid] IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@EtypeName+''',3))) '
IF RTRIM(@BtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.dealbtypeid IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@BtypeName+''',2))) '
IF RTRIM(@KtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (bi.[ktypeid] IN (SELECT typeid FROM F_GetAllBaseTypeIdFromUOrFLike('''+@KtypeName+''',4))) '

SELECT @SQLWhere = @SQLWhere + ' AND bi.STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''+@STypeId+''',11,'''+@OperatorID+''')) '	
SELECT @SQLWhere = @SQLWhere + ' AND (bi.DTypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('''',9,'''+@OperatorID+''')) OR ISNULL(bi.DTypeId,'''')='''' )'	
	
--多级权限过滤
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[etypeid] IN (SELECT typeid FROM #employee))'
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[dealbtypeid] IN (SELECT typeid FROM #btype))'
SELECT @SQLWhere = @SQLWhere + ' AND (bi.[ktypeid] IN (SELECT typeid FROM #stock))'

--草稿过滤 
IF	@DraftState ='2'
	SET @SQLWhere=@SQLWhere	 + 'AND DraftState=''原始草稿'' '
IF	@DraftState ='0'
	SET @SQLWhere=@SQLWhere	 + 'AND DraftState=''待审核'' '
IF	@DraftState ='-1'
	SET @SQLWhere=@SQLWhere	 + 'AND DraftState=''审核不通过'' '
IF	@DraftState ='1'
	SET @SQLWhere=@SQLWhere	 + 'AND DraftState=''审核通过'' '

	
	
	
-- 去掉多余的 AND
IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + RIGHT(@SQLWhere,LEN(@SQLWhere)-4)

-- 排序
IF RTRIM(@OrderBy)<>''
	SELECT @SQLOrder = ' ORDER BY ' + RTRIM(@OrderBy)
ELSE
	SELECT @SQLOrder = ' ORDER BY  bi.[BillDate], bi.[BillCode] '


--PRINT(@SQLList + @SQLFrom + @SQLWhere +  @SQLOrder )
--EXEC (@SQLList + @SQLFrom + @SQLWhere +  @SQLOrder )


----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
IF(@IsReporting = 0)
BEGIN
 
	DECLARE @excSQL VARCHAR(max)
	SET @excSQL=@SQLList + @SQLFrom + @SQLWhere +  @SQLOrder 
	EXEC (@excSQL)
	PRINT @excSQL
END
ELSE IF(@IsReporting = 1)
BEGIN
	CREATE TABLE #tmp_result
	(
		billnumberid VARCHAR(100),
		billtype     VARCHAR(100),
		Costom1		VARCHAR(max),
		Costom2		VARCHAR(max),
		Costom3		VARCHAR(max),
		Costom4		VARCHAR(max),
		Costom5		VARCHAR(max),
		Costom6		VARCHAR(max),
		Costom7		VARCHAR(max),
		Costom8		VARCHAR(max),
		Costom9		VARCHAR(max),
		Costom10	VARCHAR(max),
		Costom11	VARCHAR(max),
		Costom12	VARCHAR(max),
		Costom13	VARCHAR(max),
		Costom14	VARCHAR(max),
		Costom15	VARCHAR(max),
		Costom16	VARCHAR(max)
	)
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQLList + @SQLFrom + @SQLWhere + ') AS bi ' + @SQLOrder + 
			  ' 
			   DECLARE @p1 dbo.TBType_SelfType  
			   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
			   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 

				--显示最终结果
				SELECT a.*,
						  b.Costom1,
						  b.Costom2,
						  b.Costom3,
						  b.Costom4,
						  b.Costom5,
						  b.Costom6,
						  b.Costom7,
						  b.Costom8,
						  b.Costom9,
						  b.Costom10,
						  b.Costom11,
						  b.Costom12,
						  b.Costom13,
						  b.Costom14,
						  b.Costom15,
						  b.Costom16 
						  FROM #temp1 a 
						  left join #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
						  
				DROP TABLE #temp1,#tmp_result
			   '
	EXEC (@SQL)
END	
----------------------------------------------------------


--删除零时表
DROP TABLE #btype 
DROP TABLE #stock
DROP TABLE #employee












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBorrowLendProductDetailed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBorrowLendProductDetailed]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


--======================================
--作者:彭勇
--日期:2012-12-6
--描述:借欠明细表
--======================================
CREATE                  PROCEDURE Web_QueryBorrowLendProductDetailed
(
	@OperatorId	VARCHAR(50),
	@StartDate	VARCHAR(50),
	@EndDate	VARCHAR(50),
	@PtypeId	VARCHAR(max),
	@BtypeId	VARCHAR(max),
	@EtypeId	VARCHAR(max),
	@KtypeId	VARCHAR(max),
    @STypeId	VARCHAR(MAX),
	@BillType   VARCHAR(100),
	@BillCode   VARCHAR(200),
	@explain    VARCHAR(500),
	@comment	VARCHAR(500),
	@comment1	VARCHAR(500),
	@IsReporting	INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
DECLARE @SQL VARCHAR(8000)
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--多级权限
SELECT TypeId INTO #ptype FROM F_GetAllManagerBaseTypeId(@PtypeId,1,@OperatorID) a --商品权限
SELECT TypeId INTO #btype FROM F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorID) a --往来单位权限
SELECT TypeId INTO #stock FROM F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorID) a --仓库权限
SELECT TypeId INTO #employee FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID) a --职员权限
SELECT TypeId INTO #stype FROM  F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)a --分支机构权限
SELECT TypeId INTO #dtype FROM  F_GetAllManagerBaseTypeId('',9,@OperatorId)a --部门权限
	
----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题

    SELECT  *
    INTO    #Result
    FROM    ( SELECT    a.billnumberid ,
                        l.Id AS CustomdetailID ,
                        a.billdate ,
                        a.billcode ,
                        a.stypeid ,
                        a.comment ,
                        l.qty ,
                        a.billtype ,
                        e.typeid AS etypeid ,
                        s.typeid AS ktypeid ,
                        b.typeid AS btypeid ,
                        l.PtypeId AS ptypeid
              FROM      LendIndex a
                        INNER JOIN lendbill l ON a.billnumberid = l.billnumberid
                        INNER JOIN #ptype p ON l.PtypeId = p.TypeId
                        INNER JOIN #employee e ON a.etypeid = e.TypeId
                        INNER JOIN #btype b ON a.btypeid = b.TypeId
                        INNER JOIN #stock s ON a.ktypeid = s.TypeId
                        INNER JOIN #stype ss ON a.Stypeid = ss.TypeId
                        INNER JOIN #dtype d ON a.DTypeID = d.TypeId
              WHERE     a.draft = 0
                        AND RedWord = 0
                        AND a.billdate BETWEEN @StartDate AND @EndDate
                        AND a.BillType LIKE '%' + @BillType + '%'
                        AND a.BillCode LIKE '%' + @BillCode + '%'
                        AND a.explain LIKE '%' + @explain + '%'
                        AND a.Comment LIKE '%' + @comment + '%'
                        AND l.comment LIKE '%' + @comment1 + '%'
              UNION ALL
              SELECT    a.billnumberid ,
                        bb.Id AS CustomdetailID ,
                        a.billdate ,
                        a.billcode ,
                        a.stypeid ,
                        a.comment ,
                        bb.qty ,
                        a.billtype ,
                        e.typeid AS etypeid ,
                        s.typeid AS ktypeid ,
                        b.typeid AS btypeid ,
                        bb.PtypeId AS ptypeid
              FROM      dbo.BillIndex a
                        INNER JOIN dbo.SaleBill bb ON a.BillNumberId = bb.BillNumberId
                        INNER JOIN #ptype p ON bb.PtypeId = p.TypeId
                        INNER JOIN #employee e ON a.etypeid = e.TypeId
                        INNER JOIN #btype b ON a.btypeid = b.TypeId
                        INNER JOIN #stock s ON a.ktypeid = s.TypeId
                        INNER JOIN #stype ss ON a.Stypeid = ss.TypeId
                        INNER JOIN #dtype d ON a.DTypeID = d.TypeId
              WHERE     IsLend = 1
                        AND a.draft = 0
                        AND RedWord = 0
                         AND a.billdate BETWEEN @StartDate AND @EndDate
                        AND a.BillType LIKE '%' + @BillType + '%'
                        AND a.BillCode LIKE '%' + @BillCode + '%'
                        AND a.explain LIKE '%' + @explain + '%'
                        AND a.Comment LIKE '%' + @comment + '%'
                        AND bb.comment LIKE '%' + @comment1 + '%'
              
              UNION ALL
              SELECT    a.billnumberid ,
                        bb.Id AS CustomdetailID ,
                        a.billdate ,
                        a.billcode ,
                        a.stypeid ,
                        a.comment ,
                        -bb.qty ,
                        a.billtype ,
                        e.typeid AS etypeid ,
                        s.typeid AS ktypeid ,
                        b.typeid AS btypeid ,
                        bb.PtypeId AS ptypeid
              FROM      dbo.BillIndex a
                        INNER JOIN dbo.BuyBill bb ON a.BillNumberId = bb.BillNumberId
                        INNER JOIN #ptype p ON bb.PtypeId = p.TypeId
                        INNER JOIN #employee e ON a.etypeid = e.TypeId
                        INNER JOIN #btype b ON a.btypeid = b.TypeId
                        INNER JOIN #stock s ON a.ktypeid = s.TypeId
                        INNER JOIN #stype ss ON a.Stypeid = ss.TypeId
                        INNER JOIN #dtype d ON a.DTypeID = d.TypeId
              WHERE     IsLend = 1
                        AND a.draft = 0
                        AND RedWord = 0
                         AND a.billdate BETWEEN @StartDate AND @EndDate
                        AND a.BillType LIKE '%' + @BillType + '%'
                        AND a.BillCode LIKE '%' + @BillCode + '%'
                        AND a.explain LIKE '%' + @explain + '%'
                        AND a.Comment LIKE '%' + @comment + '%'
                        AND bb.comment LIKE '%' + @comment1 + '%'
              
            ) AS A
    ORDER BY BillDate DESC ,
            BillCode DESC  

                     
SELECT * INTO #result1 FROM #Result

	
SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
					  FROM #result1 a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid
				
				DROP TABLE #Result,#result1
----------------------------------------------------------

--删除零时表
DROP TABLE #ptype,#btype,#stock,#stype,#employee
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBrandarCommodityList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBrandarCommodityList
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：谢吉康
	日期：2017-11-17
	描述：品牌应收基本信息查询
-------------------------------------------*/
CREATE PROCEDURE Web_QueryBrandarCommodityList
(
	@OperatorID			VARCHAR(50),			--操作员ID	
	@Filter				VARCHAR(256),
	@TypeId				VARCHAR(100),			--基本信息的Id
	@ptypeid			VARCHAR(max)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @First    INT=0  --首次进入 对往来单位有用 其他为0

IF @TypeId='00000'
	SET @TypeId=''
IF @Filter IS NULL
	SET @Filter=''

IF ISNULL(@ptypeid,'')<>''
BEGIN
	SELECT	typeid,
			parid,
			case when @Filter<>'' then 1 else leveal end AS rowlevel,
			usercode,
			fullname,
			comment,
			sonnum,
			soncount,
			issys 
	FROM	brandar_Commodity a,
	(
		SELECT	BrandarTypeID 
		FROM	dbo.ptype a,
				dbo.F_Split(@ptypeid,',') b
		WHERE	a.typeId LIKE b.a+'%'
	)  b
	WHERE	a.typeid=b.BrandarTypeID 
			AND  typeid<>'00000' 
			and typeid like @TypeId+'%' 
			AND (UserCode LIKE '%'+@Filter+'%' OR fullname LIKE '%'+@Filter+'%') 
			AND (@Filter='' OR sonnum=0)
	ORDER BY TypeId
END
ELSE
BEGIN
	SELECT	typeid,
			parid,
			case when @Filter<>'' then 1 else leveal end AS rowlevel,
			usercode,
			fullname,
			comment,
			sonnum,
			soncount,
			issys 
	FROM	brandar_Commodity 
	WHERE   typeid<>'00000' 
			and typeid like @TypeId+'%' 
			AND( UserCode LIKE '%'+@Filter+'%'   OR fullname LIKE '%'+@Filter+'%' )
			AND (@Filter='' OR sonnum=0)
   ORDER BY TypeId			
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryBrandArCx_Detail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_QueryBrandArCx_Detail]
GO

/*
	作者：李德强
	日期：2017-12-14
	描述：用于查询往来单位应收，预收报表
*/
CREATE PROCEDURE Web_QueryBrandArCx_Detail 
(
	@OperatorID 	VARCHAR(100) ,		--操作员id
	@btypeid 		VARCHAR(100) = '',	--往来单位节点号
	@stypeid		VARCHAR(MAX) = '',	--分支机构
	@dtypeid		VARCHAR(MAX) = '',	--部门
	@brandartypeid	VARCHAR(MAX) = '',	--品牌ID
	@startdate		VARCHAR(50),
	@enddate		VARCHAR(50),
	@includepre		VARCHAR(10), 
	@cid            INT = 0,			--币种
	@showredword	INT = 0			--显示红冲单据
)

--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),
            @MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,
@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,
@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------

IF @bTypeId = '00000' SET @bTypeId = ''

--分支机构
CREATE TABLE #stype(typeid	VARCHAR(50))
INSERT INTO #stype(typeid) 
SELECT  A.typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

--往来单位
CREATE TABLE #btype1(typeid	VARCHAR(50))
INSERT INTO #btype1(typeid) 
SELECT  A.typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) A

---[Begin]所有明细数据
CREATE TABLE #detailBill  (
	BillNumberId	INT,
	StypeId			VARCHAR(50),
	BillDate		DATETIME,
	BillCode		VARCHAR(200),
	BillType		INT, 
	BrandarTypeId	VARCHAR(50),
	BrandUserCode   VARCHAR(50), -- 品牌code
	BrandFullName	VARCHAR(200), -- 品牌名称
	BTypeID			VARCHAR(50),--结算单位
	DTypeID			VARCHAR(50),--部门ID
	ARAddTotal		NUMERIC(24,10), 
	nARAddTotal		NUMERIC(24,10), 
	ARDecTotal		NUMERIC(24,10), 
	nARDecTotal		NUMERIC(24,10), 
	Comment			VARCHAR(MAX),
	CId				INT, 
	Rate			NUMERIC(24,10),
	IsIni			INT, 
	ifcheck 		VARCHAR(5),
	RedWord 		INT
)

IF @showredword = 1
	INSERT INTO #detailBill EXEC Gp_GetBrandArAndYsDetail @OperatorID,@stypeid,@btypeid,@dtypeid,@brandartypeid,@startdate,@enddate,@includepre,@cid,1
ELSE
	INSERT INTO #detailBill EXEC Gp_GetBrandArAndYsDetail @OperatorID,@stypeid,@btypeid,@dtypeid,@brandartypeid,@startdate,@enddate,@includepre,@cid,0

DECLARE @filterSql NVARCHAR(MAX)

SET @filterSql = '
SELECT 
	A.BillNumberId ,
	A.BrandarTypeId ,
	A.BrandUserCode AS bcusercode,
	A.BrandFullName AS brandarfullname,
	A.BTypeId ,
	B.usercode as busercode,
	A.cid ,
	AC.FULLNAME AS cfullname,
	case when A.RedWord = 2 then -1 * A.ARAddTotal else A.ARAddTotal end as ARAddTotal,
	case when A.RedWord = 2 then -1 * A.nARAddTotal else A.nARAddTotal end as nARAddTotal,
	case when A.RedWord = 2 then -1 * A.ARDecTotal else A.ARDecTotal end as ARDecTotal ,
	case when A.RedWord = 2 then -1 * A.nARDecTotal else A.nARDecTotal end as nARDecTotal,
	A.IsIni ,
	A.BillType ,
	BT.BillName as BillTypeName,
	A.BillDate ,
	A.Stypeid ,
	S.Fullname as Sfullname,
	S.usercode as susercode,
	A.DTypeId ,
	A.ifcheck ,
	A.RedWord ,
	A.billcode,
	A.comment,
	A.rate ,
	SysDiy1_head,
	SysDiy2_head,
	SysDiy3_head,
	SysDiy4_head, 
	SysDiy5_head,
	SysDiy6_head,
	SysDiy7_head,
	SysDiy8_head,
	SysDiy9_head,
	SysDiy10_head,
	SysDiy11_head,
	SysDiy12_head,
	SysDiy13_head,
	SysDiy14_head,
	SysDiy15_head,
	SysDiy16_head,
	SysDiy17_head,
	SysDiy18_head,
	SysDiy19_head,
	SysDiy20_head,
	SysDiy21_head,
	SysDiy22_head,
	SysDiy23_head,
	SysDiy24_head,
	SysDiy25_head,
	SysDiy26_head,
	SysDiy27_head,
	SysDiy28_head,
	SysDiy29_head,
	SysDiy30_head,
	SysDiy31_head,
	SysDiy32_head,
	SysDiy33_head,
	SysDiy34_head,
	SysDiy35_head,
	SysDiy36_head,
	SysDiy37_head,
	SysDiy38_head,
	SysDiy39_head,
	SysDiy40_head
FROM #detailBill A 
INNER JOIN dbo.Btype B on A.btypeid = B.typeid
INNER JOIN dbo.SType S ON A.Stypeid = S.TypeId 
INNER JOIN dbo.BillName BT ON BT.BillType = A.BillType
INNER JOIN dbo.Ac_Currency AC ON A.CID = AC.CId
LEFT JOIN Custom_BillIndex csindex on A.BillNumberId=csindex.BillId and A.BillType=csindex.billtype
WHERE	A.Isini = 0 
		AND BillDate BETWEEN ' + CHAR(39) + @startDate + CHAR(39) + ' AND ' + CHAR(39) + @endDate + CHAR(39) + ' '

--费用单核算客户时计入应收,不勾选就不出费用单
IF EXISTS(select TOP 1 1 from sysdata where subname = 'expensetoar' and subvalue = '0')
BEGIN
	SET @filterSql = @filterSql + ' AND A.BillType NOT IN (36) '
END
ELSE
BEGIN
	SET @filterSql = @filterSql + ' AND LEFT(A.BTypeId,5) = ''00001'''
END

IF @showredword = 0
BEGIN 
	SET @filterSql += ' AND A.RedWord = 0 ORDER BY BillDate , BillCode '
END 
ELSE 
BEGIN 
	SET @filterSql += '  ORDER BY BillDate , BillCode '
END 

--PRINT(@filterSql)
EXEC(@filterSql)
  
DROP TABLE #detailBill,#stype,#btype1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryBrandArCx_Line]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_QueryBrandArCx_Line]
GO

/*
	作者：李德强
	日期：2017-12-14
	描述：用于查询往来单位应收，预收报表
*/
CREATE PROCEDURE Web_QueryBrandArCx_Line 
(
	@OperatorID 	VARCHAR(100) ,	--操作员id
	@BTypeId 		VARCHAR(Max) ,	--往来单位节点号
	@STypeId		VARCHAR(MAX) ,	--分支机构
	@DTypeId		VARCHAR(MAX) ,	--部门
	@BrandarTypeId	VARCHAR(MAX) ,	--品牌ID
	@StartDate		VARCHAR(50),	--查询开始时间
	@EndDate		VARCHAR(50),	--查询结束时间
	@Includepre		VARCHAR(10),	--包含预收
	@Option			INT ,			--选项  0全部显示 1不显示金额为0 2只显示金额为0，3无发生额不显示
	@NType			INT ,			--1 全部 2 客户 3 供货商
	@Cid            INT ,			--币种
	@ChvUserCode	VARCHAR(100) ,	--结算单位编号
	@ChvFullName	VARCHAR(100) ,	--结算单位名称
	@AvailableCreditMin NUMERIC(24,10) ,     --最小信用额度
	@AvailableCreditMax NUMERIC(24,10)      --最大信用额度
)

--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------
DECLARE @SQL VARCHAR(MAX)=''
IF @AvailableCreditMin IS NULL 
SET @AvailableCreditMin = 0
IF @AvailableCreditMax IS NULL 
SET @AvailableCreditMax = 0
--品牌
CREATE TABLE #Commodity1(BrandarTypeId VARCHAR(50),BCUserCode VARCHAR(200),BCFullName VARCHAR(200))
SET @SQL='
INSERT INTO #Commodity1(BrandarTypeId,BCUserCode,BCFullName) 
SELECT  
	A.TypeId BrandarTypeId,
	A.UserCode BCUserCode,
	A.FullName BCFullName
FROM brandar_Commodity A'+CHAR(13)

--品牌不为空
IF RTRIM(@BrandarTypeId)<>''
  	SET @SQL+=' INNER JOIN f_split('''+@BrandarTypeId+''','','') F  ON A.TypeId LIKE F.a+''%'''+CHAR(13)

SET @SQL+='WHERE A.SonNum=0'+CHAR(13)
EXEC(@SQL)

--往来单位
CREATE TABLE #BType1(BTypeId VARCHAR(50),BUserCode VARCHAR(200),BFullName VARCHAR(200))
SET @SQL='
INSERT INTO #BType1(BTypeId,BUserCode,BFullName) 
SELECT  
	B.TypeId BTypeId,
	B.UserCode BUserCode,
	B.FullName BFullName
FROM F_GetAllManagerBaseTypeId('''+@BTypeId+''',2,'''+@OperatorID+''') A
INNER JOIN btype B ON B.typeId=A.TypeId
WHERE 
	B.IsUseBrandarType = 1 AND
	B.SonNum=0'+CHAR(13)

--客户档案
IF(@ntype=2)
	SET @SQL+='	AND A.TypeId LIKE ''00001%'''+CHAR(13)
	
--供货商
ELSE IF(@ntype=3)
	SET @SQL+='	AND A.TypeId LIKE ''00002%'''+CHAR(13)
	
--往来单位编号
IF RTRIM(@ChvUserCode)<>''

  	SET @SQL+='	AND B.UserCode LIKE ''%' + @ChvUserCode+ '%'' '+CHAR(13)
--往来单位名称
IF RTRIM(@ChvFullName)<>''
  	SET @SQL+='	AND B.FullName LIKE ''%' + @ChvFullName + '%'' '+CHAR(13)
	
EXEC(@SQL)	

--===================================业务逻辑处理【BEGIN】==========================================
CREATE TABLE #tempBill  
(	
	BillNumberId	INT,
	StypeId			VARCHAR(50),
	BillDate		DATETIME,
	BillCode		VARCHAR(200),
	BillType		INT, 
	BrandarTypeId	VARCHAR(50),
	BrandUserCode   VARCHAR(50), -- 品牌code
	BrandFullName	VARCHAR(200), -- 品牌名称
	BTypeID			VARCHAR(50),--结算单位
	DTypeID			VARCHAR(50),--部门ID
	ARAddTotal		NUMERIC(24,10) NOT NULL DEFAULT(0), 
	nARAddTotal		NUMERIC(24,10) NOT NULL DEFAULT(0), 
	ARDecTotal		NUMERIC(24,10) NOT NULL DEFAULT(0), 
	nARDecTotal		NUMERIC(24,10) NOT NULL DEFAULT(0), 
	Comment			VARCHAR(MAX),
	CId				INT, 
	Rate			NUMERIC(24,10),
	IsIni			INT, 
	ifcheck 		VARCHAR(5),
	RedWord 		INT
)	

INSERT INTO #tempBill
EXEC Gp_GetBrandArAndYsDetail @OperatorID,@STypeId,@BTypeId,@DTypeId,@BrandarTypeId,@StartDate,@EndDate,@includepre,@Cid 

--===================================业务逻辑处理【END】==========================================

---用临时表减少sql的复杂度，子查询已经三层了
CREATE	TABLE	#TempTable
(
	BTypeId			VARCHAR(100),
	BUserCode		VARCHAR(100),
	BFullName		VARCHAR(200),
	BrandarTypeId	VARCHAR(100),
	BCUserCode		VARCHAR(100),
	BCFullName		VARCHAR(100),
	
	ArTotal00		NUMERIC(24,10),		--期初余额本币
	NArTotal00		NUMERIC(24,10),		--期初余额原币
	
	ArAddTotal		NUMERIC(24,10),		--本期增加本币
	NArAddTotal		NUMERIC(24,10),		--本期增加原币
	
	ArDecTotal		NUMERIC(24,10),		--本期增加本币
	NArDecTotal		NUMERIC(24,10),		--本期增加原币
	
	ArremainTotal	NUMERIC(24,10),		--期末余额本币
	NArremainTotal	NUMERIC(24,10),		--期末余额原币
	
	Credit			NUMERIC(24,10),		--信用额度
	KyCredit		NUMERIC(24,10),		--可用信用额度
	StypeId			VARCHAR(100)
)

DECLARE @SQLS VARCHAR(max)

SET @SQLS='
INSERT INTO	#TempTable
SELECT 
		mainT.BTypeId,
		mainT.BUserCode,
		mainT.BFullName,
		mainT.BrandarTypeId,
		mainT.BCUserCode,
		mainT.BCFullName,
		
		ISNULL(A.ArTotal00,0)+ISNULL(BR.ARTOTAL00,0) ArTotal00,
		ISNULL(A.NArTotal00,0)+ISNULL(br.NARTOTAL00,0) NArTotal00,
		
		ISNULL(B.ArAddTotal,0) ArAddTotal,
		ISNULL(B.NArAddTotal,0) NArAddTotal,
		
		ISNULL(B.ArDecTotal,0) ArDecTotal,
		ISNULL(B.NArDecTotal,0) NArDecTotal,
		
		ISNULL(B.ArAddTotal,0)+ISNULL(A.artotal00,0)+ISNULL(BR.ARTOTAL00,0)-ISNULL(B.ArDecTotal,0) ArremainTotal , 
		ISNULL(B.NArAddTotal,0)+ISNULL(A.nartotal00,0)+ISNULL(BR.NARTOTAL00,0)-ISNULL(B.NArDecTotal,0) NArremainTotal,
		
		BBC.Credit,
		ISNULL(BBC.Credit,0)- ISNULL(ISNULL(B.ArAddTotal,0)+ISNULL(A.artotal00,0)+ISNULL(BR.ARTOTAL00,0)-ISNULL(B.ArDecTotal,0),0) KyCredit,
		BBC.StypeId
		FROM(
			SELECT	DISTINCT
					B.BTypeId,
					B.BUserCode,
					B.BFullName,
					C.BrandarTypeId,
					C.BCUserCode,
					C.BCFullName
			FROM #BType1 B CROSS JOIN #Commodity1 C ) mainT
		LEFT JOIN (
			SELECT	BTypeID,
					BrandarTypeid,
					SUM(ARAddTotal-ARDecTotal)  AS ArTotal00,
					SUM(nARAddTotal-nARDecTotal) AS nArTotal00
			FROM #tempBill 
			WHERE  RedWord = 0 AND  ((BillDate < '''+@startdate+''' AND isIni = 0) OR (Billtype = 189 and isIni = 1)) '
			
			IF @CId<>0  --0代表所有
				SET @SQLS+=' AND CID='+Convert(varchar(10),@CId)
				
			SET @SQLS+='
			GROUP BY BTypeID,BrandarTypeid ) A ON A.BTypeID = mainT.BTypeId 
			AND A.BrandarTypeid = mainT.BrandarTypeId
		LEFT JOIN (
			SELECT	BTypeID,
					BrandarTypeid,
					SUM(ARAddTotal) ArAddTotal,
					SUM(NArAddTotal) NArAddTotal,
					SUM(ArDecTotal) ArDecTotal,
					SUM(nARDecTotal) nARDecTotal,
					isIni
			FROM #tempBill 
			WHERE  BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' AND ifcheck=''t'' '
			IF @CId<>0  --0代表所有
				SET @SQLS+=' AND CID='+Convert(varchar(10),@CId)
				
			SET @SQLS+='
			GROUP BY  BTypeID, BrandarTypeid,isIni ) B ON B.BTypeID = mainT.BTypeId AND B.BrandarTypeid = mainT.BrandarTypeId
		LEFT JOIN ( 
			SELECT	SUM(a.ARTotal00) ARTOTAL00,
					SUM(A.NARTotal00) NARTOTAL00,
					A.BtypeID,
					A.BrandarTypeID
			FROM Brandar_ArApTotal A 
			'
			IF ISNULL(@STypeId,'')<>''
				SET @SQLS+=' INNER JOIN F_Split('''+@STypeId+''','','') as F  ON f.a = A.StypeId '
			
			IF @CId<>0  --0代表所有
				SET @SQLS+=' WHERE CID='+Convert(varchar(10),@CId)
			
			SET @SQLS+='
			GROUP BY A.BtypeID,A.BrandarTypeID ) br ON br.BtypeID=mainT.BTypeId AND br.BrandarTypeID=mainT.BrandarTypeId		   
			--左连接信用额度
		LEFT JOIN (
			SELECT  BC.BTypeId,
					BC.BrandarTypeId,
					SUM(BC.Credit) Credit,
					BC.StypeId
			FROM BrandBtype_Credit BC 
			INNER JOIN F_Split('''+@STypeId+''','','') as F  ON f.a = BC.StypeId
			GROUP BY BC.BtypeId,BC.BrandarTypeId,BC.StypeId ) BBC ON BBC.BtypeId = mainT.BTypeId AND BBC.BrandarTypeId = mainT.BrandarTypeId '
EXEC (@SQLS)

--===================================结果集及删除临时表【BEGIN】==========================================
SELECT 	BTypeId,
		BUserCode,
		BFullName,
		BrandarTypeId,
		BCUserCode,
		BCFullName,
		SUM(ArTotal00) AS ArTotal00,
		SUM(NArTotal00) AS NArTotal00,
		SUM(ArAddTotal) AS ArAddTotal,
		SUM(NArAddTotal) AS NArAddTotal,
		SUM(ArDecTotal) AS ArDecTotal,
		SUM(NArDecTotal) AS NArDecTotal,
		SUM(ArremainTotal) AS ArremainTotal, 
		SUM(NArremainTotal) AS NArremainTotal,
		StypeId,
		--信用额度
		CASE WHEN NOT EXISTS (SELECT 1 FROM BrandBtype_Credit WHERE StypeId = tmp.StypeId AND BrandarTypeId = tmp.BrandarTypeId 
		AND BtypeId = tmp.BTypeId) THEN NULL ELSE SUM(ISNULL(Credit,0)) END AS Credit,
		CASE WHEN NOT EXISTS (SELECT 1 FROM BrandBtype_Credit WHERE StypeId = tmp.StypeId AND BrandarTypeId = tmp.BrandarTypeId 
		AND BtypeId = tmp.BTypeId) THEN NULL ELSE  SUM(ISNULL(KyCredit,0)) END AS KyCredit
FROM	#TempTable tmp
WHERE (@option=0 --选项  0全部显示 1不显示金额为0 2只显示金额为0，3无发生额不显示
		OR (@option=1 AND (ISNULL(ArTotal00,0)<>0 OR ISNULL(ArAddTotal,0)<>0 OR ISNULL(ArDecTotal,0)<>0))
		OR (@option=2 AND (ISNULL(ArTotal00,0)=0 AND ISNULL(ArAddTotal,0)=0 AND ISNULL(ArDecTotal,0)=0))
		OR (@option=3 AND (ISNULL(ArAddTotal,0)<>0 OR ISNULL(ArDecTotal,0)<>0))
	) and ((@AvailableCreditMax = 0 AND @AvailableCreditMin = 0) OR ( (@AvailableCreditMin <> 0 OR @AvailableCreditMax <> 0) AND @AvailableCreditMax >= tmp.KyCredit AND @AvailableCreditMin <= tmp.KyCredit))
GROUP BY	BTypeId,
			BUserCode,
			BFullName,
			BrandarTypeId,
			BCUserCode,
			BCFullName,
			StypeId
DROP TABLE #tempBill,#BType1,#Commodity1,#TempTable

--===================================结果集及删除临时表【END】==========================================
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE id=OBJECT_ID('Web_QueryBrandCompanyExpenseDetails') AND OBJECTPROPERTY(id, N'IsProcedure')=1)
	DROP PROCEDURE dbo.[Web_QueryBrandCompanyExpenseDetails]
	
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--================================================
--date:2018-07-20
--by:glj
--单位品牌费用明细查询 数据
-- ========================================================================
CREATE  PROCEDURE Web_QueryBrandCompanyExpenseDetails 
(
	@OperatorId	VARCHAR(50),--操作员
	@StartDate	VARCHAR(20),--开始时间
	@EndDate	VARCHAR(20),--截止时间
	@STypeId	VARCHAR(MAX),--分支机构
	@ItemTypeId	VARCHAR(MAX),--费用项目
	@DealBTypeId	VARCHAR(50),--结算单位
	@BrandarTypeId	VARCHAR(50)--品牌名称
	 
)--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查----------------------------------------------------


--=============================基本信息权限范围获取【BEGIN】=======================================
--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
INSERT INTO #Stype(TypeID) 
SELECT F.TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) F 

--往来单位
CREATE TABLE #DealBType (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #DealBType_P_K ON #DealBType(TypeId)
IF(@DealBTypeID='99999')
	INSERT INTO #DealBType(TypeID) VALUES('99999')
ELSE
	BEGIN
		INSERT INTO #DealBType(TypeID) 
		SELECT F.TypeId FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId) F 
	END

--费用项目
CREATE TABLE #Item(NId INT,nTypeId VARCHAR(50),ItemUserCode VARCHAR(200),ItemFullName VARCHAR(200)) CREATE CLUSTERED INDEX #Item_P_K ON #Item(NId)
INSERT INTO #Item(NId,nTypeId,ItemUserCode,ItemFullName) 
SELECT 
	F.nid,
	I.nTypeId,
	I.UserCode ItemUserCode,
	I.FullName ItemFullName 
FROM dbo.F_LineF(@OperatorId) F 
INNER JOIN Ac_Items I ON I.nId=F.nid
WHERE (ISNULL(@ItemTypeId,'')='' 
		OR ISNULL(@ItemTypeId,'')<>'' AND EXISTS(SELECT * FROM f_split(@ItemTypeId,',') I WHERE F.nTypeId=I.a))   

--品牌
CREATE TABLE #Brandar(TypeID VARCHAR(50),BrandUserCode VARCHAR(200),BrandFullName VARCHAR(200)) CREATE CLUSTERED INDEX #Brandar_P_K ON #Brandar(TypeId)
INSERT INTO #Brandar(TypeID,BrandUserCode,BrandFullName) 
SELECT 
	C.TypeId,
	C.UserCode ItemUserCode,
	C.FullName BrandFullName
FROM brandar_Commodity C
WHERE
	C.TypeId<>'00000'
	AND(
		ISNULL(@BrandarTypeId,'')='' 
		OR EXISTS(SELECT * FROM f_split(@BrandarTypeId,',') F WHERE C.TypeId LIKE F.a+'%')
		)	
		
--优惠/抹零金额
DECLARE @ItemNId VARCHAR(50)
select @ItemNId=nTypeId FROM Ac_Items where UserCode='0456' AND Sysrow=1
	
--=============================基本信息权限范围获取【END】=======================================	

--=============================业务处理【BEGIN】=======================================

--305-零售单215-零售退货单11-销售出库单45-销售退货单160-销售换货单12-组合品销售出库单46-组合品销售退货单 【多账户固定抹零值】
--4-收款单 【固定抹零值】
--36-费用单158-现金费用单159-业务凭证 【具体表体数据
--305-零售单
SELECT
	F.*,
	SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
	SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
	SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
	SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
	SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head
FROM (
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(BM.PreferenceMoney,0)) Total,
		'' DComment,
		BI.Comment,
		BI.explain
	FROM BillMulBrand BM
	INNER JOIN BillIndex BI ON BI.BillNumberId=BM.BillNumberId AND BI.BillDate BETWEEN @StartDate AND @EndDate
	INNER JOIN #Stype S ON S.TypeID=BM.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.nTypeId=@ItemNId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=305
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.PreferenceMoney,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BI.Comment,
		BI.explain
	--215-零售退货单
	UNION ALL
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(-BM.PreferenceMoney,0)) Total,
		'' DComment,
		BI.Comment,
		BI.explain
	FROM BillMulBrand BM
	INNER JOIN BillIndex BI ON BI.BillNumberId=BM.BillNumberId AND BI.BillDate BETWEEN @StartDate AND @EndDate
	INNER JOIN #Stype S ON S.TypeID=BM.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.nTypeId=@ItemNId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=215
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.PreferenceMoney,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BI.Comment,
		BI.explain
	 --11-销售出库单
	UNION ALL
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(BM.PreferenceMoney,0)) Total,
		'' DComment,
		BI.Comment,
		BI.explain
	FROM BillMulBrand BM
	INNER JOIN BillIndex BI ON BI.BillNumberId=BM.BillNumberId AND BI.BillDate BETWEEN @StartDate AND @EndDate
	INNER JOIN #Stype S ON S.TypeID=BM.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.nTypeId=@ItemNId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=11
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.PreferenceMoney,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BI.Comment,
		BI.explain
	 --45-销售退货单
	UNION ALL
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(-BM.PreferenceMoney,0)) Total,
		'' DComment,
		BI.Comment,
		BI.explain
	FROM BillMulBrand BM
	INNER JOIN BillIndex BI ON BI.BillNumberId=BM.BillNumberId AND BI.BillDate BETWEEN @StartDate AND @EndDate
	INNER JOIN #Stype S ON S.TypeID=BM.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.nTypeId=@ItemNId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=45
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.PreferenceMoney,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BI.Comment,
		BI.explain
	--160-销售换货单
	UNION ALL
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(BM.PreferenceMoney,0)) Total,
		'' DComment,
		BI.Comment,
		BI.explain
	FROM BillMulBrand BM
	INNER JOIN BillIndex BI ON BI.BillNumberId=BM.BillNumberId AND BI.BillDate BETWEEN @StartDate AND @EndDate
	INNER JOIN #Stype S ON S.TypeID=BM.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.nTypeId=@ItemNId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=160
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.PreferenceMoney,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BI.Comment,
		BI.explain
	--12-组合品销售出库单
	UNION ALL
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(BM.PreferenceMoney,0)) Total,
		'' DComment,
		BI.Comment,
		BI.explain
	FROM BillMulBrand BM
	INNER JOIN BillIndex BI ON BI.BillNumberId=BM.BillNumberId AND BI.BillDate BETWEEN @StartDate AND @EndDate
	INNER JOIN #Stype S ON S.TypeID=BM.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.nTypeId=@ItemNId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=12
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.PreferenceMoney,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BI.Comment,
		BI.explain
	--46-组合品销售退货单
	UNION ALL
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(-BM.PreferenceMoney,0)) Total,
		'' DComment,
		BI.Comment,
		BI.explain
	FROM BillMulBrand BM
	INNER JOIN BillIndex BI ON BI.BillNumberId=BM.BillNumberId AND BI.BillDate BETWEEN @StartDate AND @EndDate
	INNER JOIN #Stype S ON S.TypeID=BM.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.nTypeId=@ItemNId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=46
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.PreferenceMoney,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BI.Comment,
		BI.explain
	UNION ALL
	 --收款单
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(BM.PreferenceMoney,0)) Total,
		BM.Comment DComment,
		BI.Comment,
		BI.explain
	FROM gatheringbill BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BI.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.nTypeId=@ItemNId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=4
		AND BI.IfCheck='t' 
		AND BI.RedWord=0 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.PreferenceMoney,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BM.Comment,
		BI.Comment,
		BI.explain
		
	UNION ALL	
	-- 36	费用单
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(BM.total,0)) Total,
		BM.Comment DComment,
		BI.Comment,
		BI.explain
	FROM moneybill BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BI.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.NId=BM.AtypeId
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=36
		AND BI.IfCheck='t' 
		AND BI.RedWord=0 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.total,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BM.Comment,
		BI.explain,
		BI.Comment
		
	UNION ALL	

	--158	现金费用单
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BI.STypeID,
		'99999' DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(BM.total,0)) Total,
		BM.Comment DComment,
		BI.Comment,
		BI.explain
	FROM moneybill BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BI.STypeID
	INNER JOIN #Item I ON I.NId=BM.AtypeId
	INNER JOIN #DealBType B ON B.TypeID='99999'
	INNER JOIN #Brandar Br ON Br.TypeId=BM.BrandarTypeID
	WHERE
		BI.BillType=158
		AND BI.IfCheck='t' 
		AND BI.RedWord=0 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.total,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BI.STypeID,
		BM.BrandarTypeID,
		BM.AtypeId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BM.Comment,
		BI.explain,
		BI.Comment
		
	UNION ALL
	-- 159	业务凭证
	SELECT
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BI.STypeID,
		'99999' DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId ItemId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		SUM(ISNULL(BM.J_Total-BM.D_Total,0)) Total,
		BM.Comment DComment,
		BI.Comment,
		BI.explain
	FROM AccountCredence BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BI.STypeID
	INNER JOIN #DealBType B ON B.TypeID='99999'
	INNER JOIN #Item I ON I.NId=BM.TypeATypeID
	INNER JOIN #Brandar BR ON BR.TypeID=BM.BrandarTypeId
	WHERE
		BI.BillType=159
		AND BI.IfCheck='t' 
		AND BI.RedWord=0 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
		AND ISNULL(BM.J_Total-BM.D_Total,0)<>0
	GROUP BY
		BI.BillNumberId,
		BI.BillType,
		BI.BillDate,
		BI.BillCode,
		BI.ETypeID,
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId,
		Br.BrandUserCode,
		Br.BrandFullName,
		I.ItemUserCode,
		I.ItemFullName,
		BM.Comment,
		BI.explain,
		BI.Comment
) F
LEFT JOIN Custom_BillIndex csindex on F.BillNumberId=csindex.BillId and F.BillType=csindex.BillType

--=============================业务处理【END】=======================================	

--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Stype,#Brandar,#DealBType,#Item

--=============================删除临时表【END】=======================================	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE id=OBJECT_ID('Web_QueryBrandCompanyExpenseList') AND OBJECTPROPERTY(id, N'IsProcedure')=1)
	DROP PROCEDURE dbo.[Web_QueryBrandCompanyExpenseList]
	
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--================================================
--date:2018-07-20
--by:glj
--单位品牌费用报表 数据
-- ========================================================================
CREATE  PROCEDURE Web_QueryBrandCompanyExpenseList 
(
	@OperatorId	VARCHAR(50),--操作员
	@StartDate	VARCHAR(20),--开始时间
	@EndDate	VARCHAR(20),--截止时间
	@STypeId	VARCHAR(MAX),--分支机构
	@ItemId		VARCHAR(MAX),--费用项目
	@DealBTypeId VARCHAR(MAX),--结算单位
	@BrandarTypeId 	VARCHAR(MAX)--品牌名称
	 
)--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查----------------------------------------------------


--=============================基本信息权限范围获取【BEGIN】=======================================
--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
INSERT INTO #Stype(TypeID) 
SELECT F.TypeId FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId) F 
	
--往来单位
CREATE TABLE #DealBType (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #DealBType_P_K ON #DealBType(TypeId)
INSERT INTO #DealBType(TypeID) 
SELECT F.TypeId FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId) F 

IF(ISNULL(@DealBTypeId,'')='')
	INSERT INTO #DealBType(TypeID) VALUES('99999')

--费用项目
CREATE TABLE #Item(NId VARCHAR(100)) CREATE CLUSTERED INDEX #Item_P_K ON #Item(NId)
INSERT INTO #Item(NId) 
SELECT nId FROM dbo.F_LineF(@OperatorId) F 
WHERE (ISNULL(@ItemId,'')='' 
		OR (ISNULL(@ItemId,'')<>'' AND EXISTS(SELECT * FROM f_split(@ItemId,',') I INNER JOIN Ac_Items AI ON AI.nId=I.a AND F.nTypeId LIKE AI.nTypeId+'%')))   

--品牌
CREATE TABLE #Brandar(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Brandar_P_K ON #Brandar(TypeId)
INSERT INTO #Brandar(TypeID) 
SELECT C.TypeId
FROM brandar_Commodity C
WHERE
	C.TypeId<>'00000'
	AND(
		ISNULL(@BrandarTypeId,'')='' 
		OR EXISTS(SELECT * FROM f_split(@BrandarTypeId,',') F WHERE C.TypeId LIKE F.a+'%')
		)
		
--优惠/抹零金额
DECLARE @ItemNId	VARCHAR(100)
select @ItemNId=nId FROM Ac_Items where UserCode='0456' AND Sysrow=1
	
--=============================基本信息权限范围获取【END】=======================================	

--=============================业务处理【BEGIN】=======================================

--305-零售单215-零售退货单11-销售出库单45-销售退货单160-销售换货单12-组合品销售出库单46-组合品销售退货单 【多账户固定抹零值】
--4-收款单 【固定抹零值】
--36-费用单158-现金费用单159-业务凭证 【具体表体数据】

SELECT 
	F.DealBTypeID,
	I.nTypeId itemTypeId,
	I.UserCode itemUserCode,
	I.FullName itemFullName,
	Br.TypeId brTypeID,
	BR.UserCode BrUserCode,
	BR.FullName BrFullName, 
	SUM(ISNULL(F.Total,0)) Total
FROM(
	SELECT
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		SUM(ISNULL(CASE WHEN BI.BillType IN(215,45,46) THEN -BM.PreferenceMoney ELSE BM.PreferenceMoney END,0)) Total
	FROM BillMulBrand BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BM.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.NId=@ItemNId
	INNER JOIN #Brandar BR ON BR.TypeID=BM.BrandarTypeID
	WHERE
		BI.BillType IN (11,12,45,46,305,215,160)
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
	GROUP BY
		BM.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID
		
	UNION ALL
	 --收款单
	SELECT
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		@ItemNId ItemId,
		SUM(ISNULL(BM.PreferenceMoney,0)) Total
	FROM gatheringbill BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BI.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.NId=@ItemNId
	INNER JOIN #Brandar BR ON BR.TypeID=BM.BrandarTypeID
	WHERE
		BI.BillType=4
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
	GROUP BY
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID
		
	UNION ALL	
	-- 36	费用单
	SELECT
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId ItemId,
		SUM(ISNULL(BM.total,0)) Total
	FROM moneybill BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BI.STypeID
	INNER JOIN #DealBType B ON B.TypeID=BI.DealBTypeID
	INNER JOIN #Item I ON I.NId=BM.AtypeId
	INNER JOIN #Brandar BR ON BR.TypeID=BM.BrandarTypeID
	WHERE
		BI.BillType=36
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
	GROUP BY
		BI.STypeID,
		BI.BillType,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId
	
	UNION ALL
	--158	现金费用单
	SELECT
		BI.STypeID,
		'99999' DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId ItemId,
		SUM(ISNULL(BM.total,0)) Total
	FROM moneybill BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BI.STypeID
	INNER JOIN #DealBType B ON B.TypeID='99999'
	INNER JOIN #Item I ON I.NId=BM.AtypeId
	INNER JOIN #Brandar BR ON BR.TypeID=BM.BrandarTypeID
	WHERE
		BI.BillType=158
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
	GROUP BY
		BI.STypeID,
		BM.BrandarTypeID,
		BM.AtypeId
		
	UNION ALL	
	-- 159	业务凭证
	SELECT
		BI.STypeID,
		'99999' DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId ItemId,
		SUM(ISNULL(BM.J_Total-BM.D_Total,0)) Total
	FROM AccountCredence BM
	INNER JOIN BillIndex BI ON BI.BillDate BETWEEN @StartDate AND @EndDate AND BI.BillNumberId=BM.BillNumberId
	INNER JOIN #Stype S ON S.TypeID=BI.STypeID
	INNER JOIN #DealBType B ON B.TypeID='99999'
	INNER JOIN #Item I ON I.NId=BM.TypeATypeID
	INNER JOIN #Brandar BR ON BR.TypeID=BM.BrandarTypeId
	WHERE
		BI.BillType IN(159)
		AND BI.RedWord=0 
		AND BI.IfCheck='t' 
		AND BI.Draft=0 
		AND BI.ifYearBill=0
	GROUP BY
		BI.STypeID,
		BI.DealBTypeID,
		BM.BrandarTypeID,
		BM.AtypeId
) F 
LEFT JOIN btype B ON B.typeId=F.DealBTypeID
INNER JOIN Ac_Items I ON I.nId=F.ItemId
INNER JOIN brandar_Commodity Br ON Br.TypeId=F.BrandarTypeID
WHERE 
	(F.DealBTypeID = '99999' or (F.DealBTypeID <> '99999' and B.IsUseBrandarType = 1 ))
	AND
	ISNULL(F.Total,0)<>0
GROUP BY 
	F.DealBTypeID,
	B.UserCode,
	B.FullName,
	I.nTypeId,
	I.UserCode,
	I.FullName,
	Br.TypeId,
	BR.UserCode,
	BR.FullName

--=============================业务处理【END】=======================================	

--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Brandar,#DealBType,#Item,#Stype

--=============================删除临时表【END】=======================================	
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBrandYsDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBrandYsDetail]
GO


/*
	作者：李德强
	日期：2017-12-19
	描述：往来单位品牌预收预付明细
*/
CREATE PROCEDURE Web_QueryBrandYsDetail
(
	@OperatorId		VARCHAR(100),	--操作员Id
	@startdate		VARCHAR(20),	--开始日期
	@enddate		VARCHAR(20),	--结束日期	
	@stypeid		VARCHAR(MAX),	--分支机构	
	@btypeid		VARCHAR(100),	--往来单位	
	@brandartypeid	VARCHAR(100)	--品牌ID
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------	
	 
--分支机构
CREATE TABLE #SType(TypeId	VARCHAR(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--往来单位
CREATE TABLE #BType(Typeid VARCHAR(100))
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)	

SELECT 
	BI.BillNumberId,
	BI.BillDate,
	BI.BillCode,
	BI.BillType,
	BI.etypeid,
	TEMP.BrandarTypeId,
	BC.FullName AS BrandarFullname,
	BC.UserCode AS BrandarUserCode,
	BI.Comment,
	explain ,
	AC.CID,
	AC.FullName AS CFullname,
	CASE WHEN BI.RedWord = 2 THEN -1 * BI.NTotalMoney ELSE BI.NTotalMoney END AS NTotalMoney,
	CASE WHEN BI.RedWord = 2 THEN -1 * BI.totalmoney ELSE BI.totalmoney END AS totalmoney,
	CASE WHEN BI.RedWord = 2 THEN -1 * TEMP.ntotal ELSE TEMP.ntotal END AS nystotal,
	CASE WHEN BI.RedWord = 2 THEN -1 * TEMP.total ELSE TEMP.total END AS ystotal,
	bi.RedWord,
	SysDiy1_head,
	SysDiy2_head,
	SysDiy3_head,
	SysDiy4_head, 
	SysDiy5_head,
	SysDiy6_head,
	SysDiy7_head,
	SysDiy8_head,
	SysDiy9_head,
	SysDiy10_head,
	SysDiy11_head,
	SysDiy12_head,
	SysDiy13_head,
	SysDiy14_head,
	SysDiy15_head,
	SysDiy16_head,
	SysDiy17_head,
	SysDiy18_head,
	SysDiy19_head,
	SysDiy20_head,
	SysDiy21_head,
	SysDiy22_head,
	SysDiy23_head,
	SysDiy24_head,
	SysDiy25_head,
	SysDiy26_head,
	SysDiy27_head,
	SysDiy28_head,
	SysDiy29_head,
	SysDiy30_head,
	SysDiy31_head,
	SysDiy32_head,
	SysDiy33_head,
	SysDiy34_head,
	SysDiy35_head,
	SysDiy36_head,
	SysDiy37_head,
	SysDiy38_head,
	SysDiy39_head,
	SysDiy40_head
FROM (
	--189	预收款单
	SELECT BillNumberId,BrandarTypeId,total,ntotal,'' btypeid,0 cid FROM dbo.PreBill  WHERE BillType=189
	
	UNION ALL--4	收款单
	SELECT GB.BillNumberId,BrandarTypeID, -1 * total, -1 * ntotal,'' btypeid,0 cid FROM dbo.gatheringbill GB WHERE GB.AtypeId = 39
	--305=零售单;215=零售退货单;11=销售出库单;45=销售退货单;160=销售换货单;141=委托代销结算单;12=组合品销售出库单;46=组合品销售退货单;93=其他收入单;
	UNION ALL
	SELECT BMB.BillNumberId,
		   BrandarTypeID,
	       CASE WHEN BMB.BillType IN (11,12,305,93,141) OR (BMB.BillType=160 AND BMB.YSTotalInMoney>0) THEN -1 * YSTotalInMoney
				WHEN BMB.BillType=160 AND BMB.YSTotalInMoney<0 THEN	ABS(YSTotalInMoney) 
				WHEN BMB.BillType IN (45,46,215) THEN YSTotalInMoney END AS YSTotalInMoney,
				
	       CASE WHEN BMB.BillType IN (11,12,305,93,141) OR (BMB.BillType=160 AND BMB.YSTotalInMoney>0) THEN -1 * NYSTotalInMoney 
				WHEN BMB.BillType=160 AND BMB.NYSTotalInMoney<0 THEN	ABS(NYSTotalInMoney) 
				WHEN BMB.BillType IN (45,46,215) THEN NYSTotalInMoney END AS NYSTotalInMoney,
	       '' btypeid,
	       0 cid
	       FROM 
	dbo.BillMulBrand BMB 
	WHERE 
		BMB.BillType IN (11,12,305,45,46,215,93,160,141) 
		AND BMB.YSTotalInMoney<>0
	--159=业务凭证;
	UNION ALL
	SELECT BillNumberId,BrandarTypeID,D_Total,ND_Total,ATypeID btypeid,CID FROM AccountCredence WHERE TypeATypeID=39 AND ISNULL(BrandarTypeId,'')<>'' AND D_Total<>0
	UNION ALL
	SELECT BillNumberId,BrandarTypeID,-J_Total,-NJ_Total,ATypeID btypeid,CID FROM AccountCredence WHERE TypeATypeID=39 AND ISNULL(BrandarTypeId,'')<>'' AND J_Total<>0
) TEMP
INNER JOIN dbo.BillIndex BI ON TEMP.BillNumberId = BI.BillNumberId
INNER JOIN dbo.brandar_Commodity BC ON TEMP.BrandarTypeId = BC.typeid AND bc.typeid = @brandartypeid
INNER JOIN dbo.Ac_Currency AC ON (BI.BillType=159 AND TEMP.CID = AC.CId) OR (BI.BillType<>159 AND BI.CID = AC.CId)
INNER JOIN #BType B ON (BI.BillType=159 AND TEMP.btypeid=B.Typeid ) OR (BI.BillType<>159 AND BI.btypeid = B.Typeid)
INNER JOIN #SType ON BI.Stypeid = #SType.TypeId
LEFT JOIN Custom_BillIndex csindex on BI.BillNumberId=csindex.BillId and BI.BillType=csindex.billtype

WHERE BI.BillDate BETWEEN @startdate AND @enddate AND BI.ifcheck = 't' AND BI.IsIni = 0
ORDER BY BI.BillCode , BI.BillDate DESC
 
-- 删除临时表
DROP TABLE #SType,#BType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBrandYsLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBrandYsLine]
GO

/*
	作者：李德强
	日期：2017-12-19
	描述：往来单位品牌预收预付线性表
*/
CREATE PROCEDURE Web_QueryBrandYsLine
(
	@operatorid		VARCHAR(100),	--操作员Id
	@startdate		VARCHAR(50),	--开始日期
	@enddate		VARCHAR(50),	--结束日期	
	@stypeid		VARCHAR(MAX),	--分支机构	
	@btypeid		VARCHAR(MAX),	--往来单位
	@btypeall		INT ,			--统一客户供货商
	@brandartypeid	VARCHAR(100),	--品牌
	@notshowbtypezero   INT = 1	,		--是否显示数据为0结算单位
	@AvailableCreditMin NUMERIC(24,10) ,     --最小信用额度
	@AvailableCreditMax NUMERIC(24,10)      --最大信用额度
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @AvailableCreditMin IS NULL 
SET @AvailableCreditMin = 0
IF @AvailableCreditMax IS NULL 
SET @AvailableCreditMax = 0
--分支机构
CREATE TABLE #SType(TypeId	VARCHAR(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--不区分是否统一客户供货商
----往来单位
--IF @btypeid = ''
--BEGIN
--	IF @btypeall = 1
--	BEGIN
--		SET @btypeid = '00000'
--	END
--	ELSE
--	BEGIN
--		SET @btypeid = '00001'
--	END
--END

--品牌
CREATE TABLE #brandar(TypeId VARCHAR(100))
IF @brandartypeid = ''
BEGIN
	INSERT INTO #brandar ( TypeId )
	SELECT typeid FROM dbo.brandar_Commodity WHERE sonnum = 0
END
ELSE
BEGIN
	INSERT INTO #brandar ( TypeId )
	SELECT B.TypeId FROM  dbo.brandar_Commodity B INNER JOIN dbo.f_split(@brandartypeid,',') F ON CAST(B.TypeId AS VARCHAR) LIKE F.a+'%'
END


--查询符合条件的btype，并和品牌生成笛卡尔积
CREATE TABLE #BType(Typeid VARCHAR(100))
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

CREATE TABLE #btypeInfo
( 
	btypeid NVARCHAR(100),
	busercode NVARCHAR(200),
	bfullname NVARCHAR(200),
	brandartypeid NVARCHAR(100),
	brandarusercode NVARCHAR(200),
	brandarfullname NVARCHAR(200)
)
INSERT INTO #btypeInfo (btypeid,busercode,bfullname,brandartypeid,brandarusercode,brandarfullname )
SELECT 
	BT.typeId AS btypeid,
	BT.UserCode AS busercode,
	BT.FullName AS bfullname,
	BDC.typeid AS brandartypeid,
	BDC.UserCode AS brandarusercode,
	BDC.FullName AS brandarfullname 
FROM dbo.btype BT
INNER JOIN #BType ON BT.typeId = #BType.Typeid
CROSS JOIN dbo.brandar_Commodity BDC
WHERE BDC.sonnum = 0 AND BDC.typeid IN (SELECT TypeId FROM #brandar) AND IsUseBrandarType = 1

--查询中间数据
CREATE TABLE #tempTable (BillCode varchar(200) , BillDate DATETIME, BillNumberId NVARCHAR(100),BrandarTypeID NVARCHAR(100), btypeid NVARCHAR(100), Stypeid NVARCHAR(100), posttime DATETIME, IsIni  TINYINT, ysaddtotal DECIMAL(24,10) , nysaddtotal DECIMAL(24,10), ysdectotal DECIMAL(24,10) , nysdectotal DECIMAL(24,10))

INSERT INTO #tempTable (BillCode,BillDate,BillNumberId , BrandarTypeID , btypeid , Stypeid , posttime , IsIni , ysaddtotal , nysaddtotal , ysdectotal , nysdectotal )
--预收增加
SELECT bi.BillCode,bi.BillDate,BI.BillNumberId,TEMP.BrandarTypeID,B.Typeid btypeid,BI.Stypeid,BI.posttime,BI.IsIni,TEMP.total AS ysaddtotal,TEMP.ntotal AS nysaddtotal,0 AS ysdectotal,0 AS nysdectotal FROM dbo.BillIndex BI 
INNER JOIN (
	--189	预收款单
	SELECT BillNumberId,BrandarTypeId,total,ntotal,'' btypeid FROM dbo.PreBill where BillType=189
	--215=零售退货单;45=销售退货单;46=组合品销售退货单;
	UNION ALL
	SELECT BillNumberId,BrandarTypeID,YSTotalInMoney,NYSTotalInMoney,'' btypeid FROM
	dbo.BillMulBrand BMB 
	WHERE 
		BMB.BillType IN (45,46,215) 
		AND BMB.YSTotalInMoney<>0
	UNION ALL
	--换货单 负数
	SELECT BillNumberId,BrandarTypeID,ABS(YSTotalInMoney),ABS(NYSTotalInMoney),'' btypeid FROM
	dbo.BillMulBrand BMB 
	WHERE 
		BMB.BillType=160
		AND BMB.YSTotalInMoney<0
	UNION ALL
	SELECT BillNumberId,BrandarTypeID,D_Total,ND_Total,ATypeID btypeid FROM AccountCredence WHERE TypeATypeID=39 AND ISNULL(BrandarTypeId,'')<>'' AND D_Total<>0
	
) TEMP ON BI.BillNumberId = TEMP.BillNumberId
INNER JOIN #BType B ON (BI.BillType=159 AND TEMP.btypeid=B.Typeid ) OR (BI.BillType<>159 AND BI.btypeid = B.Typeid)
INNER JOIN #SType ON BI.Stypeid = #SType.TypeId
WHERE ( ( bi.BillDate<=@enddate AND BI.ifcheck = 't' ) OR BI.IsIni = 1) AND BI.RedWord = 0 AND TEMP.BrandarTypeId IN (SELECT typeid FROM #brandar) 
UNION ALL
--预收减少
SELECT bi.BillCode,bi.BillDate,BI.BillNumberId,TEMP.BrandarTypeID,B.Typeid btypeid,BI.Stypeid,BI.posttime,BI.IsIni,0 AS ysaddtotal,0 AS nysaddtotal,TEMP.total AS ysdectotal,TEMP.ntotal AS nysdectotal FROM dbo.BillIndex BI 
INNER JOIN (
	--4	收款单
	SELECT GB.BillNumberId,BrandarTypeID,total,ntotal,'' btypeid FROM dbo.gatheringbill GB WHERE GB.AtypeId = 39
	--305=零售单;11=销售出库单;141=委托代销结算单;12=组合品销售出库单;93=其他收入单;
	UNION ALL
	SELECT BillNumberId,BrandarTypeID,YSTotalInMoney,NYSTotalInMoney,'' btypeid FROM  dbo.BillMulBrand  
	WHERE 
		BillType IN (11,12,305,93,141)
		AND YSTotalInMoney<>0
	--换货 正数
	UNION ALL
	SELECT BMB.BillNumberId,BMB.BrandarTypeID,YSTotalInMoney,NYSTotalInMoney,'' btypeid FROM BillMulBrand  BMB WHERE  BMB.BillType = 160 AND BMB.YSTotalInMoney>0
	UNION ALL
	SELECT BillNumberId,BrandarTypeID,J_Total,NJ_Total,ATypeID btypeid FROM AccountCredence WHERE TypeATypeID=39 AND ISNULL(BrandarTypeId,'')<>'' AND J_Total<>0
	
) TEMP ON BI.BillNumberId = TEMP.BillNumberId
INNER JOIN #BType B ON (BI.BillType=159 AND TEMP.btypeid=B.Typeid ) OR (BI.BillType<>159 AND BI.btypeid = B.Typeid)
INNER JOIN #SType ON BI.Stypeid = #SType.TypeId
WHERE ( (  bi.BillDate<=@enddate AND BI.ifcheck = 't' ) OR BI.IsIni = 1) AND BI.RedWord = 0 AND TEMP.BrandarTypeId IN (SELECT typeid FROM #brandar) 

--计算
SELECT
	btypeid,
	busercode,
	bfullname,
	brandartypeid,
	brandarusercode,
	brandarfullname,
	preystotal,
	npreystotal,
	iniystotal,
	niniystotal,
	curysaddtotal,
	curysdectotal,
	ncurysaddtotal,
	ncurysdectotal,
    remainystotal,
	nremainystotal,
	Credit,
	KyCredit
FROM(
SELECT 
	info.btypeid,
	info.busercode,
	info.bfullname,
	info.brandartypeid,
	info.brandarusercode,
	info.brandarfullname,
	ISNULL(preys.preystotal,0) AS preystotal,
	ISNULL(preys.npreystotal,0) AS npreystotal,
	ISNULL(iniys.iniystotal,0) AS iniystotal,
	ISNULL(iniys.niniystotal,0) AS niniystotal,
	ISNULL(curys.curysaddtotal,0) AS curysaddtotal,
	ISNULL(curys.curysdectotal,0) AS curysdectotal,
	ISNULL(curys.ncurysaddtotal,0) AS ncurysaddtotal,
	ISNULL(curys.ncurysdectotal,0) AS ncurysdectotal,
    ISNULL(preys.preystotal,0) + ISNULL(curys.curysaddtotal,0) - ISNULL(curys.curysdectotal,0) AS remainystotal ,--此前预收余额+本期增加预收款-本期减少预收款
	ISNULL(preys.npreystotal,0) + ISNULL(curys.ncurysaddtotal,0) - ISNULL(curys.ncurysdectotal,0) AS nremainystotal,

	--信用额度
	ISNULL(BBC.Credit,0) Credit,
	-- 可用信用额度
	ISNULL(BBC.Credit,0)- ISNULL(ISNULL(preys.preystotal,0) + ISNULL(curys.curysaddtotal,0) - ISNULL(curys.curysdectotal,0),0) KyCredit
FROM #btypeInfo info
LEFT JOIN (
	--此前预收余额
	SELECT btypeid,BrandarTypeID,SUM(ysaddtotal-ysdectotal) AS preystotal,SUM(nysaddtotal - nysdectotal) AS npreystotal 
	FROM #tempTable 
	WHERE 
		BillDate<@startdate
		OR IsIni=1 
	GROUP BY btypeid,BrandarTypeID
) AS preys ON info.brandartypeid = preys.BrandarTypeID AND info.btypeid = preys.btypeid
LEFT JOIN (
	--期初预收款
	SELECT btypeid,BrandarTypeID,SUM(ysaddtotal - ysdectotal) AS iniystotal,SUM(nysaddtotal - nysdectotal) AS niniystotal 
	FROM #tempTable 
	WHERE IsIni = 1
	GROUP BY 
		btypeid,
		BrandarTypeID
) iniys ON info.brandartypeid = iniys.BrandarTypeID AND info.btypeid = iniys.btypeid
LEFT JOIN (
	--本期
	SELECT btypeid,BrandarTypeID,SUM(ysaddtotal) AS curysaddtotal,SUM(nysaddtotal) AS ncurysaddtotal,SUM(ysdectotal) AS curysdectotal,SUM(nysdectotal) AS ncurysdectotal 
	FROM #tempTable 
	WHERE 
		IsIni = 0 
		AND BillDate BETWEEN @startdate  AND @enddate
	GROUP BY
		btypeid,
		BrandarTypeID
) curys ON info.brandartypeid = curys.BrandarTypeID AND info.btypeid = curys.btypeid 

--左连接信用额度
LEFT JOIN (
	SELECT 
		BC.BTypeId,
		BC.BrandarTypeId,
		SUM(BC.Credit) Credit
	FROM BrandBtype_Credit BC 
    join F_Split(@STypeId,',') as F 
    on f.a = BC.StypeId
	GROUP BY BC.BtypeId,BC.BrandarTypeId
	) BBC ON BBC.BtypeId = info.btypeid AND BBC.BrandarTypeId = info.brandartypeid

 WHERE
	(@notshowbtypezero = 1 AND (preystotal <> 0 OR iniystotal <> 0 OR curysaddtotal <> 0 OR curysdectotal <> 0 ) OR @notshowbtypezero = 0 )
)tmp
WHERE ((@AvailableCreditMax = 0 AND @AvailableCreditMin = 0) OR ( (@AvailableCreditMin <> 0 OR @AvailableCreditMax <> 0) AND @AvailableCreditMax >= tmp.KyCredit AND @AvailableCreditMin <= tmp.KyCredit))
ORDER BY tmp.btypeid,tmp.brandartypeid
DROP TABLE #SType ,#BType,#btypeInfo, #tempTable ,#brandar

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_QueryBTypeAnalyseListLine]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_QueryBTypeAnalyseListLine]
GO

/*
	作者：徐辉
	日期：2008-08-04
	描述：往来单位业务分析
	
	作者：徐辉
	日期：2011-03-29
	描述：回款金额增加预收款单。
	修改记录#01--------------------------------------------------------
	修改作者：俞俊杰
	修改原因：待摊费用项目表变更Atype更换为ac_item
	修改时间：2012-06-13

	Modify Log: #02--------------------------------------------------------
	By：Haiyang, Li
	Description：优化, 整理原有逻辑, 优化Btype临时表生成
	修改时间：2012-06-13

	-- 2013-07-31 周华 添加零售退货单据类型
*/
CREATE    PROCEDURE Web_QueryBTypeAnalyseListLine
    (
      @OperatorId VARCHAR(50) ,
      @BTypeId VARCHAR(50) ,
      @StypeId VARCHAR(1550) ,
      @StartDate VARCHAR(20) ,
      @EndDate VARCHAR(20) ,
      @flag INT 		--线性树形表标志 1：线性表 0：树形表
    )
--@encode$--
AS 
    SET NOCOUNT ON
    SET ANSI_WARNINGS OFF
--------------------------时间测试变量------------------------------------
DECLARE @dt DATETIME
--------------------------时间测试变量------------------------------------

--------------------------------------------------------------权限检查-------------------------------------------------------
    IF @OperatorId IS NULL 
        RETURN 1
    DECLARE @Re INT ,
        @MAtypeid VARCHAR(50) ,
        @MBtypeid VARCHAR(50) ,
        @MBtypeid2 VARCHAR(50) ,
        @MEtypeid VARCHAR(50) ,
        @MKtypeid VARCHAR(50) ,
        @MPtypeid VARCHAR(50) ,
        @MExpense VARCHAR(50) ,
        @MIncome VARCHAR(50) ,
        @MCapital VARCHAR(50) ,
        @MDtypeid VARCHAR(50) ,
        @MStypeid VARCHAR(50)
    EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
        @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT,
        @MKtypeid OUTPUT, @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT,
        @MCapital OUTPUT, @MDtypeid OUTPUT, @MStypeid OUTPUT
    IF @Re <> 0 
        RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------



    DECLARE @isChild INT ,
        @SQL NVARCHAR(MAX)

		--往来单位
    CREATE TABLE #BType ( TypeId VARCHAR(50) )

	--拥有全部客户权限(Btype单选)
	--INSERT  INTO #BType( TypeId ) SELECT  TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId, 2, @OperatorID)
	--供货商
   -- INSERT  INTO #BType( TypeId )
   -- VALUES  ( '00001' ), ('00002')
	
	INSERT INTO #BType(typeid) (SELECT TypeId 
	FROM  F_GetManBTypeAll(@OperatorID) WHERE (@BTypeId = '00000' OR @BTypeId = '') OR typeId LIKE @BTypeId + '%' )

	--SELECT * FROM #BType
	--职员
    CREATE TABLE #EType ( TypeId VARCHAR(100) )
			INSERT  INTO #EType( TypeId ) SELECT  S.TypeId FROM F_GetAllManagerBaseTypeId('', 3, @OperatorID) S

	--分支机构
    CREATE TABLE #SType ( TypeId VARCHAR(100) )
    IF NOT ( @STypeId = '' AND @MSTypeId = '00000')
			INSERT INTO #SType( TypeId )SELECT  TypeId FROM F_GetAllManagerBaseTypeId(@STypeId, 11, @OperatorID)

	--部门
    CREATE TABLE #DType ( TypeId VARCHAR(100) )
    INSERT  INTO #DType( TypeId) SELECT  TypeId FROM    F_GetAllManagerBaseTypeId('', 9, @OperatorID)	
	
		--用于之后过滤
    IF @BTypeId = '' 
        BEGIN
            SET @BTypeId = '00000'
            SET @isChild = 0
        END
    ELSE 
        BEGIN
            SELECT  @isChild = CASE sonnum
                                 WHEN 0 THEN 1
                                 ELSE 0
                               END
            FROM    Btype
            WHERE   typeId = @BTypeId
        END
    
    --临时结果集
    CREATE TABLE #tempListTable
        (
          BTypeId VARCHAR(100) ,
          AtypeId INT ,
          BillType INT ,
          Total  NUMERIC(24, 10) 
        )
    SET @SQL = '
INSERT INTO #tempListTable
SELECT 	BtypeId,
		AtypeId,		
		BillType,
		SUM(Total) AS Total
FROM	ListTable L
	INNER JOIN #BType B ON B.TypeId = L.BTypeId '	--过滤Btype
    IF NOT ( @STypeId = '' AND @MStypeid = '00000' ) 
        SET @SQL = @SQL + ' INNER JOIN #SType S ON L.STypeId = S.TypeId '
	
    SET @SQL = @SQL + 
		'WHERE 	L.BillDate >= @StartDate 
		   AND L.BillDate <= @EndDate '
        + CASE @MEtypeid
            WHEN '-99999'--操作员权限
                 THEN ' AND L.ETypeId IN(SELECT TypeId FROM #Etype) '
            ELSE ''
          END 
        + CASE @MDtypeid
            WHEN '-99999'--操作员权限
                       THEN ' AND L.DTypeId IN(SELECT TypeId FROM #Dtype) '
            ELSE ''
          END
        + ' AND L.Audited = 1
		AND L.billtype not in (165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 181) -- 不统计维修类科目
GROUP BY
		BtypeId,
		AtypeId,
		BillType'

--SET @dt = GETDATE()
		--PRINT(@SQL)
    EXEC sp_executesql @SQL, N'@StartDate nvarchar(20),@EndDate nvarchar(20)',
        @StartDate, @EndDate;
--SELECT '生成#tempListTable', DATEDIFF(ms,@dt,GETDATE())

  
  --生成数据结果
--SET @dt = GETDATE()
  SELECT	BTypeId AS TypeId,
		CASE 
			WHEN  (SELECT UserCode FROM Ac_Items WHERE nid = AtypeId) = '5101' 
			THEN SUM(ISNULL(Total,0)) 
			ELSE 0 
		END AS saleincome,
		CASE
			WHEN  (SELECT  nid FROM Ac_Items WHERE  TypeName = 'G'  AND nid = AtypeId)  NOT IN ( 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ) 
			THEN SUM(ISNULL(Total,0)) 
			ELSE 0 
		END AS otherincome,
		CASE
			WHEN  (SELECT nid FROM Ac_Items WHERE TypeName = 'E' AND nid = AtypeId) NOT IN ( 16, 17, 18, 19, 20, 21 ) 
			THEN SUM(ISNULL(Total,0)) 
			ELSE 0 
		END AS expense,
		CASE 
			WHEN  (SELECT UserCode FROM Ac_Items WHERE nid = AtypeId) = '5401'  THEN SUM(ISNULL(Total,0)) 
			ELSE 0 
		END AS salecost,
		CASE 
			WHEN  (SELECT UserCode FROM Ac_Items WHERE nid = AtypeId) = '5103'  THEN SUM(ISNULL(Total,0)) 
			ELSE 0 
		END AS rebackincome,
		CASE 
			WHEN ( ATypeId IN (SELECT nId FROM Ac_Items WHERE TypeName = 'B' AND UserCode Not IN('2181','2131','1151'))) AND BillType IN(11,45,160,157,305,215,4,141,189,12,45) THEN SUM(ISNULL(Total,0)) 
			WHEN ( ATypeId IN (SELECT nId FROM Ac_Items WHERE  UserCode ='2181'))AND BillType IN(11,45,160,157,305,215,4,141,12,46)   THEN  -1*SUM(ISNULL(Total,0))
			ELSE 0 
		END AS backmoney,
		CASE
			WHEN 
			(SELECT UserCode FROM Ac_Items WHERE nid = AtypeId) = '0334'  THEN SUM(ISNULL(Total,0)) 
			ELSE 0 
		END AS coupon
INTO #Result
FROM 	#tempListTable
GROUP BY 
	BtypeId,
	AtypeId,
	BillType	
    IF @flag = 0 --树形表
    BEGIN
			SELECT	B.TypeId,
					B.SonNum,
					B.FullName + '('+B.UserCode+')',
					ISNULL(SUM(M.saleincome),0) AS saleincome,
					ISNULL(SUM(M.salecost),0) AS salecost,
					ISNULL(SUM(M.otherincome),0) AS otherincome,
					ISNULL(SUM(M.rebackincome),0) AS rebackincome,
					ISNULL(SUM(M.expense),0) AS expense,
					ISNULL(SUM(M.backmoney),0) AS backmoney,
					ISNULL(SUM(M.coupon),0) AS coupon,
					ISNULL(SUM(M.saleincome),0)-ISNULL(SUM(M.salecost),0) as maoli,
					ISNULL(SUM(M.coupon),0)+ ISNULL(SUM(M.saleincome),0)-ISNULL(SUM(M.salecost),0)+ISNULL(SUM(M.otherincome),0)+ISNULL(SUM(M.rebackincome),0)-ISNULL(SUM(M.expense),0) as bqmaoli
			FROM dbo.btype B
				INNER JOIN #BType b1 ON B1.TypeId = B.typeId 
				LEFT JOIN #Result M ON M.TypeId LIKE B.TypeId + '%' 
			WHERE (@isChild = 1 AND B.typeId = @BTypeId) --@btypeid为父节点
				OR (@isChild = 0 AND B.parid = @BTypeId) --@btypeid为叶子节点
			GROUP BY 
			B.TypeId,
			B.SonNum,
			B.FullName,
			B.UserCode
			ORDER BY B.UserCode 
			--SELECT '出结果集', DATEDIFF(ms,@dt,GETDATE())
  
    END
    ELSE
		BEGIN
				SELECT	B.TypeId,
						B.SonNum,
						B.FullName + '('+B.UserCode+')',
						ISNULL(SUM(M.saleincome),0) AS saleincome,
						ISNULL(SUM(M.salecost),0) AS salecost,
						ISNULL(SUM(M.otherincome),0) AS otherincome,
						ISNULL(SUM(M.rebackincome),0) AS rebackincome,
						ISNULL(SUM(M.expense),0) AS expense,
						ISNULL(SUM(M.backmoney),0) AS backmoney,
						ISNULL(SUM(M.coupon),0) AS coupon,
						ISNULL(SUM(M.saleincome),0) - ISNULL(SUM(M.salecost),0) as maoli,
						ISNULL(SUM(M.coupon),0) + ISNULL(SUM(M.saleincome),0) - ISNULL(SUM(M.salecost),0) + ISNULL(SUM(M.otherincome),0) + ISNULL(SUM(M.rebackincome),0)-ISNULL(SUM(M.expense),0) as bqmaoli
				FROM dbo.btype B
					INNER JOIN #BType b1 ON B1.TypeId = B.typeId 
					LEFT JOIN #Result M ON M.TypeId = B.TypeId 
				WHERE (@BTypeId = '00000' OR B.TypeId LIKE @BTypeId + '%') --@btypeid为父节点
					AND b.sonnum = 0 --@btypeid为叶子节点
				GROUP BY 
						B.TypeId,
						B.SonNum,
						B.FullName,
						B.UserCode
				ORDER BY B.UserCode 
		END

    DROP TABLE #tempListTable,#Btype, #Stype, #Etype,#Dtype

    SET QUOTED_IDENTIFIER OFF 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBtypeBuyBackLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBtypeBuyBackLine]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
    作者:王刚
	日期:2011-11-23
	描述:商品采购退货统计线型表
	
	修改：鲁大林	
	日期：2012-06-09
	描述：添加浮动单位等调整
*/
CREATE PROCEDURE [dbo].[Web_QueryBtypeBuyBackLine]
(
	@startDate		    VARCHAR(30),	       --  2、查询起始时间
	@endDate	        VARCHAR(30),	       --  3、查询结束时间
	@ptypeid		    VARCHAR(1550),	       --  4、商品类别查询范围父节点 ID
	@dealbtypeid		VARCHAR(1550),			--往来单位
	@btypeid			varchar(1550),			--  5、结算单位查询范围父节点 ID
	@etypeid		    VARCHAR(1550),	       --  6、职员类别查询范围父节点 ID
	@ktypeid		    VARCHAR(1550),	       --  7、仓库类别查询范围父节点 ID
    @dtypeid		    VARCHAR(1550) ,        --  8、部门ID
	@OperatorID			VARCHAR(50),	       -- 12、操作员 ID（作权限范围检查用）
	@red				INT = 0,			   -- 13. 是否显示红冲 
	@billType		    VARCHAR(200),          -- 14. 单据类型
	@stypeid            VARCHAR(1550)          --  16、分支机构查询范围父节点 ID
)
--@encode$--
AS
SET NOCOUNT ON 

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


--结算往来
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)

--往来单位
CREATE TABLE #GetManDealBtypeId(typeId VARCHAR(100))
IF @dealbtypeid <> '' OR @MBtypeid = '-99999'
	INSERT INTO #GetManDealBtypeId(typeId) SELECT typeId FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)

--部门
CREATE TABLE #Dtype (TypeID VARCHAR(50))
IF @dtypeid <> '' OR @MDtypeid = '-99999'
	INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)

--仓库
CREATE TABLE #Ktype (TypeID VARCHAR(50))
INSERT INTO #Ktype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)
IF (@KTypeID='10000' OR  @KTypeID='' OR  @KTypeID='00000') AND NOT EXISTS(SELECT * FROM #Ktype WHERE typeid='10000') 
	INSERT INTO #Ktype SELECT '10000'
	
--商品
CREATE TABLE #Ptype (TypeID varchar(50))
IF @ptypeid <> '' OR @MPtypeid = '-99999'
	INSERT INTO #Ptype select typeid from F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID)

--职员
CREATE TABLE #Etype (TypeID varchar(50))
IF @etypeid <> '' OR @MEtypeid = '-99999'
	INSERT INTO #Etype select typeid from F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)

--分支机构
CREATE TABLE #Stype (TypeID varchar(50))
IF @stypeid <> '' OR @MStypeid = '-99999'
	INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

CREATE TABLE #inoutstocktable
(
	BtypeId		VARCHAR(50),
	rkQty		 NUMERIC(24, 10) ,
	rkNQty		 NUMERIC(24, 10) ,
	ckQty		 NUMERIC(24, 10) ,
	ckNQty		 NUMERIC(24, 10) ,
	rkMoney		 NUMERIC(24, 10) ,
	ckMoney		 NUMERIC(24, 10) 
)

DECLARE @SQL VARCHAR(MAX)

SELECT @SQL='INSERT INTO #inoutstocktable
				SELECT  a.BtypeId,
						ISNULL(SUM(a.rkQty),0) AS rkQty,
						ISNULL(SUM(a.rkNQty),0) AS rkNQty,
						ISNULL(-SUM(a.ckQty),0) AS ckQty,
						ISNULL(-SUM(a.ckNQty),0) AS ckNQty,
						ISNULL(SUM(a.rkMoney),0) AS rkMoney,
						ISNULL(-SUM(a.ckMoney),0) AS ckMoney
				FROM
				(  SELECT	I.BtypeId,
							CASE WHEN I.BillType IN (34,161) AND I.Qty > 0 OR I.BillType = 145 THEN ABS(I.Qty) ELSE 0 END AS rkQty,
							CASE WHEN I.BillType IN (34,161) AND I.Qty > 0 OR I.BillType = 145 THEN ABS(I.NQty) ELSE 0 END AS rkNQty,
							
							CASE WHEN I.BillType IN (6,161) AND I.Qty < 0 THEN I.Qty ELSE 0 END AS ckQty,
							CASE WHEN I.BillType IN (6,161) AND I.Qty < 0 THEN I.NQty ELSE 0 END AS ckNQty,
							
							CASE WHEN I.BillType IN (34,161) AND I.Qty > 0 THEN I.TaxTotal
								 WHEN I.BillType = 145 THEN ABS(I.TaxTotal)
								 ELSE 0 END AS rkMoney,
							CASE WHEN I.BillType IN (6,161) AND Qty < 0 THEN I.TaxTotal ELSE 0 END AS ckMoney
					 FROM InoutStockTable I '
				 
					IF @btypeid <> '' OR @MBtypeid = '-99999'
						SET @SQL=@SQL+'INNER JOIN BillIndex B ON B.BillNumberId=I.BillNumberId '
					
					IF @stypeid<>'' OR @MStypeid=-99999 
						SET @SQL=@SQL+' INNER JOIN #stype s  ON I.stypeid=s.typeid '
			           
					IF @btypeid <> '' OR @MBtypeid = '-99999'	--结算
						SET @SQL=@SQL+' INNER JOIN #GetManBTypeId bt ON bt.typeid=B.btypeid '
						
					IF @dealbtypeid <> '' OR @MBtypeid = '-99999' --往来
						SET @SQL=@SQL+'INNER JOIN #GetManDealBtypeId dbt ON  dbt.typeid = I.btypeid'
						
					IF @ptypeid<>'' OR @MPTypeID=-99999 
						SET @SQL=@SQL+' INNER JOIN #Ptype p ON I.ptypeid=p.typeid '
						
					IF @dtypeid<>'' OR @MDTypeID=-99999
						SET @SQL=@SQL+' INNER JOIN #Dtype d  ON  I.DtypeID=d.typeid '	
						
					IF @ktypeid<>'' OR @MKTypeID=-99999 
						SET @SQL=@SQL+'	INNER JOIN #Ktype k ON I.ktypeid=k.typeid '
						
					IF @etypeid<>'' OR @METypeID=-99999 
						SET @SQL=@SQL+' INNER JOIN #Etype e  ON I.etypeid=e.typeid '
					
					SET @SQL=@SQL+'  WHERE	I.BillDate>='+CHAR(39)+@startDate+CHAR(39)+' 
											AND I.BillDate<='+CHAR(39)+@endDate+CHAR(39)+' 
											AND I.BillType IN('+@billType+') 
											AND I.Audited=1	 
				) a GROUP BY a.BtypeId '
				 
SET @SQL += ' 
	SELECT b.typeid,
					 b.usercode,
				 	 a.rkQty - a.ckQty AS qty,--实购数量
					 a.rkNQty - a.ckNQty AS nqty,
					 a.rkmoney - a.ckmoney AS taxtotal,--实购金额
					 a.rkQty AS inqty,--采购入库数量
					 a.ckQty AS backqty,--采购退货数量
					 a.rkmoney AS inmoney,--采购入库金额
					 a.ckmoney AS backmoney,--采购退货金额
					
					 
					  CASE WHEN a.rkQty=0 THEN 0 ELSE cast(ckQty as NUMERIC(24, 10))/cast(rkQty as NUMERIC(24, 10))*100 END AS outLv
          FROM #GetManDealBtypeId t
          INNER JOIN Btype b on b.typeid = t.typeid
          LEFT JOIN #inoutstocktable a ON a.btypeid = t.typeid
          WHERE a.rkQty<>0 OR a.ckQty<>0 OR a.rkMoney<>0 OR a.ckMoney<>0
          ORDER BY b.usercode '  
  
--PRINT @SQL
EXEC(@SQL)

DROP TABLE #GetManBTypeId,#inoutstocktable,#Dtype,#Ktype,#Etype,#Stype,#Ptype,#GetManDealBtypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBtypeBuyBackList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBtypeBuyBackList]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
    作者:王刚
	日期:2011-11-22
	描述:供货商采购退货统计树型表
*/

/*
    修改:黄清
	日期:2011-11-22
	描述:增加分支机构控制
	
	修改：鲁大林
	日期：2012-06-09
	描述：添加浮动单位数量，增加结算单位筛选条件
	
 
    修改: 魏伟
    日期: 2015-05-24
    描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
 
*/
CREATE PROCEDURE [dbo].[Web_QueryBtypeBuyBackList]
(
	@startDate		    VARCHAR(30),	       --  2、查询起始时间
	@endDate	        VARCHAR(30),	       --  3、查询结束时间
	@ptypeid		    VARCHAR(1550),	       --  4、商品类别查询范围父节点 ID
	@btypeid		    VARCHAR(1550),	       --  6、结算单位类别查询范围父节点 ID
	@dealbtypeid		VARCHAR(1550),	       --  5、往来单位类别查询范围父节点 ID
	@etypeid		    VARCHAR(1550),	       --  6、职员类别查询范围父节点 ID
	@ktypeid		    VARCHAR(1550),	       --  7、仓库类别查询范围父节点 ID
    @dtypeid		    VARCHAR(1550) ,        --  8、部门ID
	@OperatorID			VARCHAR(50),	       -- 12、操作员 ID（作权限范围检查用）
	@red				INT = 0,			   -- 13. 是否显示红冲 
	@billType		    VARCHAR(200),          -- 14. 单据类型
	@stypeid            VARCHAR(1550),          --  16、分支机构查询范围父节点 ID
	@ptypecategoryid VARCHAR(MAX)               --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON 

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------


--结算往来
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)

--往来单位
CREATE TABLE #GetManDealBtypeId(typeId VARCHAR(100))
INSERT INTO #GetManDealBtypeId(typeId) SELECT typeId FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)

--往来单位树型
CREATE TABLE #GetManBTypeAll
(
	TypeId	    varchar(1550),
	SonNum		INT,
	UserCode	VARCHAR(200),
	FullName	VARCHAR(200),
	Deleted		INT,
	ParId		VARCHAR(1550)
)
INSERT INTO #GetManBTypeAll
SELECT	TypeId,
		SonNum,
		UserCode,
		FullName,
		Deleted,
		ParId
FROM	F_GetManBTypeAll(@OperatorID)

DECLARE @SQL varchar(8000)---主体SQL
DECLARE @SonNum int,@BTypeIdMx varchar(max),@dealBTypeIdMx VARCHAR(max)
SELECT @SonNum=SonNum FROM #GetManBTypeAll WHERE TypeId = @dealbtypeid


IF @btypeid='' OR @btypeid='root'
   SET @BTypeIdMx='%'
ELSE
   SET @BTypeIdMx=@btypeid
   
IF @dealbtypeid='' OR @dealbtypeid='root'
   SET @dealBTypeIdMx='%'
ELSE
   SET @dealBTypeIdMx=@dealbtypeid

--部门
CREATE TABLE #Dtype (TypeID varchar(50))
INSERT INTO #Dtype select typeid from F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)

--仓库
CREATE TABLE #Ktype (TypeID varchar(50))
INSERT INTO #Ktype select typeid from F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)
IF (@KTypeID='10000' OR  @KTypeID='' OR  @KTypeID='00000') AND NOT EXISTS(select * from #Ktype where typeid='10000') 
	insert into #Ktype select '10000'
	
--商品
CREATE TABLE #Ptype (TypeID varchar(50))
INSERT INTO #Ptype select typeid from F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) 

--职员
CREATE TABLE #Etype (TypeID varchar(50))
INSERT INTO #Etype select typeid from F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)

--分支机构
CREATE TABLE #Stype (TypeID varchar(50))
INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

CREATE TABLE #inoutstocktable(
	BillNumberId	NUMERIC(10, 0),
	BillDate		DATETIME,
	BillType		NUMERIC(4,0),
	PtypeId		VARCHAR(2000),
	BtypeId		VARCHAR(2000),
	dealBtypeId VARCHAR(2000),
	EtypeId		VARCHAR(2000),
	KtypeId		VARCHAR(2000),
	DtypeId		VARCHAR(2000),
	Qty			 NUMERIC(24, 10) ,
	NQty		 NUMERIC(24, 10) ,--浮动单位数量
	TaxTotal	 NUMERIC(24, 10) 
)

DECLARE @InsertSQL VARCHAR(3000)

SELECT @InsertSQL='INSERT INTO #inoutstocktable
                              (
                                 BillnumberID,
                                 BillDate,
                                 BillType,
                                 PtypeId,
                                 BtypeId,
                                 dealBtypeId,
                                 EtypeId,
                                 KtypeId,
                                 DtypeId,
                                 Qty,
                                 NQty,--浮动单位数量
                                 TaxTotal
                              )
                  SELECT 
                                I.BillnumberID,
                                I.BillDate,
                                I.BillType,
                                I.PtypeID,
                                I.BtypeId,
                                BI.DealBTypeID,
                                I.EtypeId,
                                I.KtypeId,
                                I.DtypeId,
                                I.Qty,
                                I.NQty,--浮动单位数量
                                I.TaxTotal
                 FROM   InoutStockTable I INNER JOIN BILLINDEX BI ON BI.BillNumberId=I.BillNumberId '
	 IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
		SET @InsertSQL=@InsertSQL+' INNER JOIN #GetManBTypeId bt ON bi.btypeid=bt.typeid '+CHAR(13)
	IF @dealbtypeid<>'' OR @MBtypeid=-99999 OR @MBtypeid2=-99999
		SET @InsertSQL=@InsertSQL+'INNER JOIN #GetManDealBtypeId dbt ON BI.DealBTypeID=dbt.typeid'+CHAR(13)
	IF @ptypeid<>'' OR @MPTypeID=-99999 OR @ptypecategoryid<>'' 
		SET @InsertSQL=@InsertSQL+' INNER JOIN #Ptype p ON I.ptypeid=p.typeid '+CHAR(13)
		
	IF @dtypeid<>'' OR @MDTypeID=-99999
		SET @InsertSQL=@InsertSQL+' INNER JOIN #Dtype d  ON  I.DtypeID=d.typeid '+CHAR(13)	
		
	IF @ktypeid<>'' OR @MKTypeID=-99999 
		SET @InsertSQL=@InsertSQL+'	INNER JOIN #Ktype k ON I.ktypeid=k.typeid '+CHAR(13)
		
	IF @etypeid<>'' OR @METypeID=-99999 
		SET @InsertSQL=@InsertSQL+' INNER JOIN #Etype e  ON I.etypeid=e.typeid '+CHAR(13)
	
	IF @stypeid<>'' OR @METypeID=-99999 
		SET @InsertSQL=@InsertSQL+' INNER JOIN #stype s  ON I.stypeid=s.typeid '+CHAR(13)
	
	 SET @InsertSQL=@InsertSQL+'  WHERE	I.BillType IN('+@billType+') 
										--AND BI.BtypeId Like  '''+@BTypeIdMx+'%''
										AND BI.DealBTypeID LIKE '''+@dealBTypeIdMx+'%''
										AND I.BillDate>='+CHAR(39)+@startDate+CHAR(39)+' 
										AND I.BillDate<='+CHAR(39)+@endDate+CHAR(39)+' 
										AND I.Audited=1  '
									
--PRINT @InsertSQL                                
EXEC(@InsertSQL)
	
SET @SQL='SELECT
                a.typeid,
                a.sonnum,
                a.usercode,
                a.rkQty - ckQty AS qty,
                a.rkNQty - ckNQty AS nqty,
                a.rkmoney - a.ckmoney AS taxtotal,
                a.rkQty AS inqty,
                a.ckQty AS backqty,
                a.rkmoney AS inmoney,
                a.ckmoney AS backmoney,
                CASE WHEN a.rkQty=0 THEN 0 ELSE cast(ckQty as NUMERIC(24, 10))/cast(rkQty as NUMERIC(24, 10))*100 END AS outLv
          FROM
             (
               SELECT 
                    p.typeid,
                    p.sonnum,
                    p.usercode AS usercode, 
					SUM(CASE WHEN b.BillType IN (34,161) AND b.Qty > 0 OR b.BillType = 145 THEN ISNULL(ABS(b.Qty),0) ELSE 0 END ) AS rkQty,			--采购入库单,采购换货单的入库数量,受托代销结算单
                    SUM(CASE WHEN b.BillType IN (6,161) AND b.Qty < 0 THEN ISNULL(ABS(b.Qty),0) ELSE 0 END ) AS ckQty,								--采购退货单,采购换货单的出数量
                    SUM(CASE WHEN b.BillType IN (34,161) AND b.NQty > 0 OR b.BillType = 145 THEN ISNULL(ABS(b.NQty),0) ELSE 0 END ) AS rkNQty,			--采购入库单,采购换货单的入库数量,受托代销结算单
                    SUM(CASE WHEN b.BillType IN (6,161) AND b.NQty < 0 THEN ISNULL(ABS(b.NQty),0) ELSE 0 END ) AS ckNQty,								--采购退货单,采购换货单的出数量
                    SUM(CASE WHEN b.BillType IN(34,161) AND b.Qty > 0 OR b.BillType = 145 THEN ISNULL(ABS(b.TaxTotal),0) ELSE 0 END ) AS rkmoney,	--采购入库单,采购换货单的税价合计,受托代销结算单
                    SUM(CASE WHEN b.BillType IN (6,161) AND b.Qty < 0 THEN ISNULL(ABS(b.TaxTotal),0) ELSE 0 END ) AS ckmoney						--采购退货单,采购换货单的税价合计
                    
               FROM   #GetManBTypeAll p
               LEFT JOIN #inoutstocktable b on p.typeid=LEFT(b.btypeid,LEN(p.typeid))'
				
        IF @dealbtypeid<>'00000'
	     BEGIN
	         IF @SonNum=0
                SET @SQL=@SQL+' WHERE p.typeid LIKE '+char(39)+@dealbtypeid+'%'+char(39)
             ElSE 
				BEGIN
					IF @dealbtypeid=''
						SET @SQL=@SQL+' WHERE p.parid='+char(39)+'00000'+char(39)
					ELSE
						SET @SQL=@SQL+' WHERE p.parid='+char(39)+@dealbtypeid+CHAR(39)
                END
         END
       ELSE
          BEGIN
            SET @SQL=@SQL+' WHERE p.typeid='+char(39)+@dealbtypeid+CHAR(39)
          END
       SET @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.sonnum  
     ) a ORDER BY a.usercode'
     
--PRINT @SQL
EXEC(@SQL)


DROP TABLE #GetManBTypeId,#GetManBTypeAll,#GetManDealBtypeId,#inoutstocktable,#Dtype,#Ktype,#Etype,#Stype,#Ptype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeExpenseDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeExpenseDetail]
GO

/*
	作者：谢吉康
	日期：2007-3-4
	描述：单位费用报表明细表
*/
CREATE   PROCEDURE Web_QueryBTypeExpenseDetail
(
	@OperatorId		varchar(50),
	@ATypeId		varchar(1550),
	@BTypeId		varchar(50),
	@STypeId		varchar(1550),
	@StartDate		datetime,
	@EndDate		datetime
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50),@MSTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT,@MSTypeId OUTPUT
IF @Re<>0 RETURN @Re

--转换时间生成临时表
DECLARE @TableName 	varchar(1000),
		@SQL		varchar(8000),
		@LenBTypeId	varchar(100)



CREATE TABLE #AType (TypeID varchar(50),nTypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #Btype (TypeID varchar(50),fullname varchar(200))
CREATE TABLE #SType (TypeID varchar(50))
CREATE TABLE #DType (TypeID varchar(50))
CREATE TABLE #EType (TypeID varchar(50))

--费用
IF @ATypeID=''
	BEGIN
		IF @MExpense='-99999' --费用权限受控制
		BEGIN
			INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum FROM Ac_Items where ntypeid in ( select a.ntypeid from F_BaseGetManDetailATypeFy(@OperatorID) a)
			INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) SELECT ntypeid,nid,usercode,fullname,sonnum from Ac_Items where sonnum=0 and ntypeid LIKE '00004%' AND NOT ntypeid like '0000400003%'
	    	
		END
		ELSE
		BEGIN
			INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.ntypeid from F_BaseGetManDetailATypeFy(@OperatorID) a)				
		END
	END
	ELSE
	BEGIN
		IF @MExpense='-99999' --费用权限受控制
		BEGIN
		INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.ntypeid from F_BaseGetManDetailATypeFy(@OperatorID) a, (select AC.NtypeID from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b where left(a.ntypeid,len(b.ntypeid))=b.ntypeid)
		INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) 
				select ntypeid,nid,usercode,fullname,sonnum from Ac_Items 
				where ntypeid in ( 
							select a.ntypeid from (select ntypeid from Ac_Items where sonnum=0 and ntypeid LIKE '00004%' AND NOT ntypeid like '0000400003%') a, 
							(select AC.NtypeID from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b where left(a.ntypeid,len(b.ntypeid))=b.ntypeid
				)
		END
		ELSE
		BEGIN
			INSERT INTO #Atype(typeid,nTypeID,usercode,fullname,sonnum) select ntypeid,nid,usercode,fullname,sonnum from Ac_Items where ntypeid in ( select a.ntypeid from F_BaseGetManDetailATypeFy(@OperatorID) a, (select AC.Ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b where left(a.ntypeid,len(b.ntypeid))=b.ntypeid)
		END
	END

DELETE FROM #Atype where typeid='000030000200007' --删除借转采购科目

INSERT INTO #Btype(typeid,fullname) select typeid,fullname from btype where typeid in (select typeid from F_BaseGetManDetailBType(@OperatorID) where typeid like @BTypeId+'%' )
IF @BTypeId = '99999'
	INSERT INTO #BType(TypeId,FullName)VALUES('','其他单位')

--分支机构
IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@OperatorID) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a

--部门
INSERT INTO #Dtype(typeid)  select typeid from F_BaseGetManDetailDType(@OperatorID)

--职员
INSERT INTO #Etype(typeid)  select typeid from F_BaseGetManDetailEType(@OperatorID)

SELECT 	Bil.BillNumberId,
		Bil.BillDate,
		Bil.BillCode,
		Bil.BillType,
		EChecke = (SELECT FullName FROM Employee WHERE TypeId = Bil.Checke),
		L.ETypeId,
		Bil.BTypeId,
		Bil.STypeId,
		--EFullName = (SELECT FullName FROM Employee WHERE TypeId = Bil.ETypeId),
		--BFullName = (SELECT FullName FROM BType WHERE TypeId = Bil.BTypeId),
		ate.fullname as afullname,
		L.Total,
		Bil.Comment,
		billname = (select billname from billname where billtype =bil.billtype)
FROM
(
	SELECT BillNumberId,BillDate,BillCode,BillType,Checke,BTypeId,STypeId,Comment,IfCheck,RedWord FROM dbo.BillIndex 
	UNION ALL 
	SELECT BillNumberId,BillDate,BillCode,BillType,Checke,BTypeId,STypeId,Comment,IfCheck,RedWord FROM ReceiptBillIndex
	UNION ALL 
	SELECT BillNumberId,BillDate,BillCode,BillType,Checker,BTypeId,STypeId,Comment,IfCheck,RedWord FROM dbo.Coupon_BillIndex
) AS Bil
INNER JOIN ListTable AS L ON(Bil.BillNumberId = L.BillNumberId AND Bil.BillType = L.BillType)
INNER JOIN #Atype ate ON ate.nTypeID=L.Atypeid
WHERE	Bil.BillNumberId = L.BillNumberId
		AND L.BTypeId IN (SELECT TypeID FROM #BType)
		AND L.ATypeId IN (SELECT nTypeID FROM #AType)
		AND L.STypeID IN (SELECT TypeID FROM #SType)
		AND L.Dtypeid IN (SELECT TypeID FROM #DType)
		AND L.Etypeid IN (SELECT TypeID FROM #EType)
		AND L.Audited = 1
		AND ISNULL(L.Total,0)<>0
		AND Bil.IfCheck = 't'
		AND Bil.RedWord = 0
		AND Bil.BillDate>=@StartDate
		AND Bil.BillDate<=@EndDate
UNION ALL
SELECT 
CBN.BillNumberId,
CBN.BillDate,
CBN.BillCode,
CBN.BillType,
(SELECT FullName FROM Employee WHERE TypeId = CBN.Checke) AS EChecke,
CBND.ETypeId,
'99999' AS BTypeId,
CBN.STypeId,
'' as afullname,
CBND.CommissionTotal AS Total,
CBN.Comment,
(SELECT billname FROM billname WHERE billtype = CBN.billtype) AS billname
FROM CommissionBillNew AS CBN
INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
INNER JOIN #Stype S ON S.TypeID=CBN.STypeID
INNER JOIN #Dtype D ON D.TypeID=CBND.DTypeID
INNER JOIN #Etype E ON E.TypeID=CBND.EtypeId
WHERE CBN.ifcheck = 't'
	AND CBN.BillDate>=@StartDate
	AND CBN.BillDate<=@EndDate
	AND @BTypeId = '99999'

--删除临时表
DROP TABLE #AType, #BType, #SType,#DType, #EType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeExpenseLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeExpenseLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/*
	作者：谢吉康
	日期：2007-3-4
	描述：单位费用报表线性表
	--修改记录#01--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-10
	--说明：添加行合计（v3.9）

	--修改记录#02--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修科目(qp1.0)
*/
CREATE        PROCEDURE Web_QueryBTypeExpenseLine
(
	@OperatorId		varchar(50),
	@ATypeId		varchar(1550),
	@BTypeId		varchar(50),
	@STypeID		varchar(1550),
	@StartDate		datetime,
	@EndDate		datetime,
	@UserCode		varchar(256)='',
	@FullName		varchar(256)='',
	@nPageCol		int = 1,
	@nPageColSize	int = 10,
	@Flag           int =0 -- 0页面，1 打印
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorId is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorId,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--转换时间生成临时表
DECLARE @TableName 	varchar(1000),
		@SQL		varchar(8000),
		@LenBTypeId	varchar(100)
IF @BTypeId='00000'
	SET @BTypeId =''
SET @TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SET @SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		TypeId		varchar(100) NOT NULL
	) '
EXEC(@SQL)

CREATE TABLE #AType1 (TypeID varchar(50),nTypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #BType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int)
CREATE TABLE #Stype (TypeID varchar(50))

CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #DetailATypeFy (TypeID varchar(50),nTypeID varchar(50))

INSERT INTO #DetailATypeFy select a.typeid AS TypeID,a.nid AS nTypeID  from /*F_BaseGetManDetailATypeFy*/F_LineExpenseC(@OperatorID) a
INSERT INTO #Etype select typeid from F_GetManDetailEtype(@OperatorID)
INSERT INTO #Dtype select typeid from F_GetManDetailDtype(@OperatorID)

--费用
IF @ATypeID=''
	BEGIN
		INSERT INTO #AType1(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeFy fy ON A.nTypeId=fy.TypeID 
		----IF NOT EXISTS(select * from #AType1) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #AType1(typeid,ntypeid,usercode,fullname,sonnum) 
		--select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		--from dbo.Ac_Items A
		--LEFT JOIN #AType1 A1 ON A1.TypeID=A.nTypeId  
		--where a.sonnum=0 and a.nTypeId LIKE '00004%' AND a.nTypeId NOT like '0000400003%' AND a1.typeid is null
	END
	ELSE
	BEGIN
		INSERT INTO #AType1(typeid,ntypeid,usercode,fullname,sonnum) 
		select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		from dbo.Ac_Items A
		INNER JOIN #DetailATypeFy fy ON A.nTypeId=fy.TypeID 
		INNER JOIN (select AC.NtypeID from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b ON fy.typeid LIKE b.ntypeid+'%'

		----IF NOT EXISTS(select * from #AType1) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #AType1(typeid,ntypeid,usercode,fullname,sonnum) 
		--select A.nTypeId,A.nId,A.usercode,A.fullname,A.sonnum 
		--from dbo.Ac_Items A
		--INNER JOIN (select AC.NtypeID from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b ON a.nTypeId LIKE b.ntypeid+'%'
		--LEFT JOIN #AType1 A1 ON A1.TypeID=A.nTypeId  
		--where a.sonnum=0 and a.nTypeId LIKE '00004%' AND a.nTypeId NOT like '0000400003%' AND a1.typeid is null
	END


DELETE FROM #Atype1 where typeid='000030000200007' --删除借转采购科目						
DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #Atype1 where typeid='000040000200004'--#02 删除商品送修科目		

IF @BtypeID=''
	INSERT INTO #Btype(typeid,usercode,fullname) 
	select b.typeid,b.usercode,b.fullname from Btype b
	INNER JOIN (select typeid from F_GetManDetailBType(@OperatorID)) b1 on b.typeId=b1.TypeId
ELSE
	INSERT INTO #Btype(typeid,usercode,fullname) 
	select b.typeid,b.usercode,b.fullname from Btype b
	inner join (select typeid from F_GetManDetailBType(@OperatorID)) a on a.TypeId=b.typeId
	inner join (select * from  dbo.f_split(@BtypeID,',')) b1 on a.typeId like b1.a+'%'
IF @BTypeId = '99999' OR @BtypeID =''
	INSERT INTO #BType(TypeId,UserCode,FullName)VALUES('99999','其他单位','其他单位')

IF @STypeID=''
	INSERT INTO #Stype(typeid)  
	select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  
	select a.typeid from F_BaseGetManDetailSType(@OperatorID) a
	inner join (select * from  dbo.f_split(@StypeID,',')) b on a.typeId like b.a+'%'
	
DECLARE @ColName varchar(8000)
DECLARE @ColName1 varchar(8000)
SET @ColName ='T.RowTotal '
IF @FLag =1 
BEGIN
	SET @ColName ='T.RowTotal as RowTotal '
	SET @ColName1 ='RowTotal '
END
--处理费用科目的翻页
CREATE TABLE #AType
(
	TypeId		varchar(100),
	FullName	varchar(256)
)
DECLARE @SqlCursor 		varchar(8000),
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256)
SET @SqlCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@nPageColSize AS varchar(50)) + ' 
				nTypeID,							
				FullName
	    FROM    #AType1 
	    WHERE  	 UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@nPageCol-1) * @nPageColSize AS varchar(50)) + ' UserCode
	                FROM	#AType1
	            ) '
	EXEC(@SQLCursor)
	OPEN BaseTypeCursor
	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
	WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #AType(TypeId,FullName)VALUES(@BaseTypeId,@BaseFullName)
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END
CLOSE BaseTypeCursor
DEALLOCATE BaseTypeCursor
--缩小查询数据的范围
CREATE TABLE #ListTable
(
	ATypeId			varchar(100),
	BTypeID			varchar(100),
	Total			 NUMERIC(24, 10) 
)
INSERT INTO #ListTable(ATypeId,BTypeID,Total) 
SELECT 	ATypeId,
		BTypeId,
		ISNULL(SUM(Total),0) AS Total
FROM 	ListTable l
INNER JOIN #BType B ON B.TypeID=L.BtypeId
INNER JOIN #Atype1 A1 ON A1.nTypeID=L.AtypeId
INNER JOIN #Stype S ON S.TypeID=L.STypeID
INNER JOIN #Dtype D ON D.TypeID=L.DTypeID
INNER JOIN #Etype E ON E.TypeID=L.EtypeId
WHERE	l.Audited = 1
		AND Total<>0
		AND Total IS NOT NULL
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
GROUP BY ATypeId,BTypeId
UNION ALL
--****9.6需求修改-文档遗漏导致BUG：1404 杨俊2015-06-15--
SELECT * 
FROM 
(
	SELECT 	ATypeId,
			'99999' AS BTypeId,
			ISNULL(SUM(Total),0) AS Total
	FROM 	ListTable L
	INNER JOIN #Atype1 A1 ON A1.nTypeID=L.AtypeId
	INNER JOIN #Stype S ON S.TypeID=L.STypeID
	INNER JOIN #Dtype D ON D.TypeID=L.DTypeID
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	WHERE	Audited = 1
			AND Total<>0
			AND Total IS NOT NULL
			AND (BTypeId='' OR BtypeId IS NULL)
			AND BillDate>=@StartDate
			AND BillDate<=@EndDate
	GROUP BY ATypeId,BTypeId
	UNION ALL
	SELECT (SELECT TOP 1 nId FROM Ac_Items WHERE FullName = '业务提成') AS ATypeID,
	'99999' AS BTypeId,
	ISNULL(SUM(CBND.CommissionTotal),0) AS Total 
	FROM CommissionBillNew AS CBN
	INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
	INNER JOIN #Stype S ON S.TypeID=CBN.STypeID
	INNER JOIN #Dtype D ON D.TypeID=CBND.DTypeID
	INNER JOIN #Etype E ON E.TypeID=CBND.EtypeId
	WHERE CBN.ifcheck = 't'
		AND CBN.BillDate>=@StartDate
		AND CBN.BillDate<=@EndDate
) AS A
--****************************************************************************--

--将往来单位的数据写入临时表
SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeID) SELECT TypeId FROM #BType WHERE TypeId IN (SELECT BTypeId FROM #ListTable)'
EXEC(@SQL)

--SET @SQL = 'select * from '+N'##'+@TableName
--exec(@SQL)
--#01
--合计每行费用
SELECT BTypeId,SUM(Total) AS Total
INTO #Sum_ListTable
FROM #ListTable
GROUP BY
	BTypeId

--#01
--给临时表添加一列--行合计列
SET @SQL='ALTER TABLE '+N'##'+@TableName+ ' ADD RowTotal  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
EXEC(@SQL)

SET @SQL='UPDATE '+N'##'+@TableName+ ' SET RowTotal = b.Total
		FROM  '+N'##'+@TableName+ ' AS a,#Sum_ListTable AS b
		WHERE a.TypeId = b.BtypeId'
EXEC(@SQL)
DROP TABLE #Sum_ListTable


--运算具体的数据
DECLARE @AFullName	varchar(256),
		@AATypeId	varchar(100)
DECLARE AType_Cursor CURSOR FOR
	SELECT TypeId,FullName FROM #AType
OPEN AType_Cursor
FETCH NEXT FROM AType_Cursor INTO @AATypeId,@AFullName
WHILE @@FETCH_STATUS = 0
	BEGIN
		--修改表结构
		SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @AFullName + ']  NUMERIC(24, 10)  DEFAULT(''0'')'
		SET  @ColName= @ColName+',T.['+ @AFullName + ']'
		SET  @ColName1= @ColName1+',['+ @AFullName + ']'
		EXEC(@SQL)
		--处理数据
		SET @SQL = 'UPDATE	'+N'##'+@TableName+ '
					SET		['+@AFullName+'] = ISNULL(B.Total,0)
					FROM	'+N'##'+@TableName+ ' A
					LEFT JOIN (
								SELECT	BTypeId,
										ISNULL(SUM(Total),0) AS Total
								FROM	#ListTable
								WHERE	ATypeId = '+char(39)+@AATypeId+char(39)+'
								GROUP BY BTypeId
							)B ON B.BTypeId = A.TypeId '
		EXEC(@SQL)
		FETCH NEXT FROM AType_Cursor INTO @AATypeId,@AFullName
	END
CLOSE AType_Cursor
DEALLOCATE AType_Cursor
--合成往来单位表
CREATE TABLE #LastBType
(
	TypeId		varchar(100),
	ParId		varchar(100),
	SonNum		int,
	UserCode	varchar(256),
	FullName	varchar(256),
	Deleted		int	
)
INSERT INTO #LastBType
(
	TypeId,
	ParId,
	SonNum,
	UserCode,
	FullName,
	Deleted
)
SELECT	TypeId,
		ParId,
		SonNum,
		UserCode,
		FullName,
		Deleted
FROM	BType
WHERE typeid in (select typeid from #Btype)

IF @BtypeID='99999' OR @BtypeID=''
	INSERT INTO #LastBType(TypeId,ParId,SonNum,UserCode,FullName,Deleted)VALUES('99999','00000',0,'其他单位','其他单位',0)

DECLARE @AtypeCount int
SET @AtypeCount = 0 
SELECT @AtypeCount =COUNT(*)  FROM #AType1

--DECLARE @OtherWhere varchar(100)
--SET @OtherWhere=''
--IF @UserCode<>'' or @FullName<>'' 
--BEGIN
--	SET @OtherWhere=' B.TypeId<>''99999'' AND '
--END

--查询临时表
IF @Flag =0
BEGIN
	SET @SQL = 'SELECT	DISTINCT
					B.SonNum,
					B.UserCode as EtypeCode,
					B.Typeid As EtypeId,
					B.FullName+'+'''('''+'+B.UserCode+'+''')'' as  [单位/费用支出] ,
					'+Convert(varchar(10),@AtypeCount)+' as AtypeCount,					
					'+@ColName+'
			FROM	#LastBType B
			INNER JOIN (		
						SELECT	*
						FROM 	'+N'##'+@TableName+'
						WHERE RowTotal<>0
					  )T ON T.TypeID = B.TypeId 
			WHERE	 (B.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
					AND B.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
					AND B.TypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
			) ORDER BY B.UserCode'

END
ELSE
BEGIN
		
	DECLARE @SQL1 varchar(8000)
	DECLARE @SQL2 varchar(8000)

	SET @SQL = 'select [单位/费用支出],x.EtypeId As EtypeId,'+@Colname1+' FROM ('
	SET @SQL1= '	SELECT	DISTINCT
							b.usercode,
							B.Typeid As EtypeId,
							B.FullName+'+'''('''+'+B.UserCode+'+''')'' as  [单位/费用支出] ,
						'+@ColName
	SET @SQL2='		FROM	#LastBType B
							INNER JOIN (		
										SELECT	*
										FROM 	'+N'##'+@TableName+'
										WHERE RowTotal<>0
									  )T ON T.TypeID = B.TypeId 
					WHERE	(B.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
							AND B.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
							AND B.TypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
						)
				) x order by usercode'
END

--PRINT(@SQL+@SQL1+@SQL2)	
EXEC(@SQL+@SQL1+@SQL2)
--删除临时表
SET @SQL = 'DROP TABLE #LastBType,#BType,#SType,#ListTable,#DetailATypeFy,#Etype,#Dtype,#AType,#Atype1,'+N'##'+@TableName
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeExpenseLinePrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeExpenseLinePrint]
GO











/*
	作者：谢吉康
	日期：2007-3-4
	描述：单位费用报表线性表
	--修改记录#01--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-10
	--说明：添加行合计（v3.9）
*/
CREATE    PROCEDURE Web_QueryBTypeExpenseLinePrint
(
	@OperatorId		varchar(100),
	@ATypeId		varchar(100),
	@BTypeId		varchar(100),
	@StartDate		datetime,
	@EndDate		datetime,
	@UserCode		varchar(256)='',
	@FullName		varchar(256)='',
	@aPageNo		int = 1,
	@bCount			int = 10
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorId is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorId,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--转换时间生成临时表
DECLARE @TableName 	varchar(1000),
		@SQL		varchar(8000),
		@LenBTypeId	varchar(100)
IF @BTypeId='00000'
	SET @BTypeId =''
SET @TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SET @SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		TypeId		varchar(100) NOT NULL
	) '
EXEC(@SQL)
--处理往来单位
CREATE TABLE #BType
(
	TypeId		varchar(100),
	UserCode	varchar(256),
	FullName	varchar(256)
)


DECLARE @ColName varchar(4000)
SET @ColName ='T.RowTotal as [总计] '

IF @BTypeId = ''
	BEGIN
		SET @BTypeId = '%'
		INSERT INTO #BType(TypeId,UserCode,FullName) SELECT TypeId,UserCode,FullName FROM BType WHERE Deleted = 0 AND SonNum = 0 AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%' AND UserCode LIKE '%'+@UserCode+'%' AND FullName LIKE '%'+@FullName+'%')
		INSERT INTO #BType(TypeId,UserCode,FullName)VALUES('99999','其他单位','其他单位')
	END
ELSE
	BEGIN	
		IF @BTypeId = '99999'
			INSERT INTO #BType(TypeId,UserCode,FullName)VALUES('99999','其他单位','其他单位')
		ELSE
			INSERT INTO #BType(TypeId,UserCode,FullName) SELECT TypeId,UserCode,FullName FROM BType WHERE Deleted = 0 AND SonNum = 0 AND (TypeId LIKE @MBTypeId + '%' OR TypeId LIKE @MBTypeId2 + '%') AND TypeID LIKE @BTypeId + '%' AND UserCode LIKE '%'+@UserCode+'%' AND FullName LIKE '%'+@FullName+'%'
	END
--处理费用科目的翻页
CREATE TABLE #AType
(
	TypeId		varchar(100),
	FullName	varchar(256)
)
DECLARE @SqlCursor 		varchar(8000),
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256)
SET @SqlCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    AType 
	    WHERE  	SonNum = 0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@aPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	AType
					WHERE 	SonNum = 0
							AND TypeId LIKE ''00004%''
							AND TypeId LIKE '+char(39)+@ATypeId+'%'+char(39)+'
							AND TypeId LIKE '+char(39)+@MExpense+'%'+char(39)+'
	            )
				AND TypeId LIKE ''00004%''
				AND TypeId LIKE '+char(39)+@ATypeId+'%'+char(39)+'
				AND TypeId LIKE '+char(39)+@MExpense+'%'+char(39)
	EXEC(@SQLCursor)
	OPEN BaseTypeCursor
	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
	WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #AType(TypeId,FullName)VALUES(@BaseTypeId,@BaseFullName)
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END
CLOSE BaseTypeCursor
DEALLOCATE BaseTypeCursor
--缩小查询数据的范围
CREATE TABLE #ListTable
(
	ATypeId			varchar(100),
	BTypeID			varchar(100),
	Total			 NUMERIC(24, 10) 
)
INSERT INTO #ListTable(ATypeId,BTypeID,Total) 
SELECT 	ATypeId,
		BTypeId,
		ISNULL(SUM(Total),0) AS Total
FROM 	ListTable
WHERE	BTypeId IN (SELECT TypeID FROM #BType)
		AND Audited = 1
		AND ATypeID LIKE '00004%'
		AND ATypeID LIKE @ATypeID + '%'
		AND ATypeId LIKE @MExpense + '%'
		AND ISNULL(Total,0)<>0
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
GROUP BY ATypeId,BTypeId
UNION ALL
SELECT 	ATypeId,
		'99999' AS BTypeId,
		ISNULL(SUM(Total),0) AS Total
FROM 	ListTable
WHERE	Audited = 1
		AND ATypeID LIKE '00004%'
		AND ATypeID LIKE @ATypeID + '%'
		AND ATypeId LIKE @MExpense + '%'
		AND ISNULL(Total,0)<>0
		AND ISNULL(BTypeId,'')=''
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
GROUP BY ATypeId,BTypeId

--将往来单位的数据写入临时表
SET @SQL = 'INSERT INTO '+N'##'+@TableName+'(TypeID) SELECT TypeId FROM #BType WHERE TypeId IN (SELECT BTypeId FROM #ListTable)'
EXEC(@SQL)

--SET @SQL = 'select * from '+N'##'+@TableName
--exec(@SQL)
--#01
--合计每行费用
SELECT BTypeId,SUM(Total) AS Total
INTO #Sum_ListTable
FROM #ListTable
GROUP BY
	BTypeId

--#01
--给临时表添加一列--行合计列
SET @SQL='ALTER TABLE '+N'##'+@TableName+ ' ADD RowTotal  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
EXEC(@SQL)

SET @SQL='UPDATE '+N'##'+@TableName+ ' SET RowTotal = b.Total
		FROM  '+N'##'+@TableName+ ' AS a,#Sum_ListTable AS b
		WHERE a.TypeId = b.BtypeId'
EXEC(@SQL)
DROP TABLE #Sum_ListTable


--运算具体的数据
DECLARE @AFullName	varchar(256),
		@AATypeId	varchar(100)
DECLARE AType_Cursor CURSOR FOR
	SELECT TypeId,FullName FROM #AType
OPEN AType_Cursor
FETCH NEXT FROM AType_Cursor INTO @AATypeId,@AFullName
WHILE @@FETCH_STATUS = 0
	BEGIN
		--修改表结构
		SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @AFullName + ']  NUMERIC(24, 10)  DEFAULT(''0'')'
		SET  @ColName= @ColName+',T.['+ @AFullName + ']'
		EXEC(@SQL)
		--处理数据
		SET @SQL = 'UPDATE	'+N'##'+@TableName+ '
					SET		['+@AFullName+'] = ISNULL(B.Total,0)
					FROM	'+N'##'+@TableName+ ' A
					LEFT JOIN (
								SELECT	BTypeId,
										ISNULL(SUM(Total),0) AS Total
								FROM	#ListTable
								WHERE	ATypeId = '+char(39)+@AATypeId+char(39)+'
								GROUP BY BTypeId
							)B ON B.BTypeId = A.TypeId '
		EXEC(@SQL)
		FETCH NEXT FROM AType_Cursor INTO @AATypeId,@AFullName
	END
CLOSE AType_Cursor
DEALLOCATE AType_Cursor
--合成往来单位表
CREATE TABLE #LastBType
(
	TypeId		varchar(100),
	ParId		varchar(100),
	SonNum		int,
	UserCode	varchar(256),
	FullName	varchar(256),
	Deleted		int	
)
INSERT INTO #LastBType
(
	TypeId,
	ParId,
	SonNum,
	UserCode,
	FullName,
	Deleted
)
SELECT	TypeId,
		ParId,
		SonNum,
		UserCode,
		FullName,
		Deleted
FROM	BType
INSERT INTO #LastBType(TypeId,ParId,SonNum,UserCode,FullName,Deleted)VALUES('99999','00000',0,'其他单位','其他单位',0)

DECLARE @AtypeCount int
SET @AtypeCount = 0 
SELECT @AtypeCount =COUNT(*)  FROM AType WHERE SonNum = 0  AND TypeId LIKE '00004%' AND TypeId LIKE @ATypeID+'%' AND TypeId LIKE  @MExpense+'%'

--查询临时表
SET @SQL = 'SELECT	DISTINCT
					B.FullName+'+'''('''+'+B.UserCode+'+''')'' as  [单位/费用支出] ,
					'+@ColName+'
			FROM	#LastBType B
			INNER JOIN (		
						SELECT	*
						FROM 	'+N'##'+@TableName+'
					  )T ON T.TypeID = B.TypeId 
			WHERE	(B.TypeId LIKE '+char(39)+@MBTypeID+'%'+char(39)+' OR B.TypeID LIKE '+char(39)+@MBTypeId2+'%'+char(39)+' OR B.TypeId=''99999'')
					AND B.Deleted = 0 
					AND B.SonNum = 0
					AND B.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
					AND B.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
					AND B.TypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
			ORDER BY B.FullName+'+'''('''+'+B.UserCode+'+''')'' '
		
--PRINT(@SQL)	
EXEC(@SQL)
--删除临时表
SET @SQL = 'DROP TABLE #LastBType,#BType,#ListTable,#AType,'+N'##'+@TableName
EXEC(@SQL)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeExpenseList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeExpenseList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2007-3-4
	描述：单位费用报表
	--修改记录#01--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-10
	--说明：添加行合计（v3.9）

	--修改记录#02--------------------------------------------------------
	--人员：Wang Wei 
	--日期：2010-08-31
	--说明：删除商品送修科目(qp1.0)
	
	--修改记录#03
	--人员：周华
	--日期：2013-06-09
	--说明：9.2版本调整多级权限函数
*/
CREATE            PROCEDURE Web_QueryBTypeExpenseList
(
	@OperatorId		varchar(50),
	@ATypeId		varchar(1550),
	@BTypeId		varchar(50),
	@STypeID		varchar(1550),
	@StartDate		datetime,
	@EndDate		datetime,
	@nPageCol		int = 1,		-- 费用科目的翻页
	@nPageColSize			int = 10,
	@Flag           int =0     -- 0页面，1打印
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorId is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorId,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--转换时间生成临时表
DECLARE	@SQL		varchar(max),
		@LenBTypeId	varchar(100),
		@SonNum		int


DECLARE @ColName varchar(max)
SET  @ColName ='typeid as EtypeID,usercode as EtypeCode,fullname+''(''+usercode+'')'' as [单位/费用支出],Sonnum,RowTotal,deleted'
IF @Flag =1
	SET  @ColName =' typeid as EtypeID,fullname+''(''+usercode+'')'' as [单位/费用支出],RowTotal as RowTotal'


CREATE TABLE #AType1 (TypeID varchar(50),nTypeID varchar(50),usercode varchar(26),fullname varchar(100),sonnum int)
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))
CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(26),fullname varchar(100),sonnum int,Deleted int)

CREATE TABLE #Etype (TypeID varchar(50))
CREATE TABLE #Dtype (TypeID varchar(50))
CREATE TABLE #DetailATypeFy (TypeID varchar(50),nTypeID varchar(50))

INSERT INTO #DetailATypeFy select a.typeid as TypeID, a.nid as nTypeID from F_LineExpenseC(@OperatorID) a
INSERT INTO #Etype select typeid from F_GetManDetailEtype(@OperatorID)
INSERT INTO #Dtype select typeid from F_GetManDetailDtype(@OperatorID)

--费用
IF @ATypeID=''
	BEGIN
		INSERT INTO #AType1(typeid,nTypeID,usercode,fullname,sonnum) 
		select A.ntypeid as typeid,A.nid as nTypeID, A.usercode,A.fullname,A.sonnum 
		from ac_items A
		INNER JOIN #DetailATypeFy fy ON A.ntypeid=fy.TypeID 
		----IF NOT EXISTS(select * from #AType1) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #AType1(typeid,nTypeID,usercode,fullname,sonnum) 
		--select A.ntypeid as typeid,A.nid as nTypeID, A.usercode,A.fullname,A.sonnum 
		--from ac_items A
		--LEFT JOIN #AType1 A1 ON A1.ntypeid=A.nid  
		--where a.sonnum=0 and a.ntypeid LIKE '00004%' AND a.ntypeid NOT like '0000400003%' AND A1.typeid IS NULL
	END
	ELSE
	BEGIN
		INSERT INTO #AType1(typeid,nTypeID,usercode,fullname,sonnum) 
		select A.ntypeid as typeid,A.nid as nTypeID, A.usercode,A.fullname,A.sonnum 
		from ac_items A
		INNER JOIN #DetailATypeFy fy ON A.ntypeid=fy.TypeID 
		INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b ON fy.typeid LIKE b.ntypeid+'%'

		----IF NOT EXISTS(select * from #AType1) --无管辖费用类型时，临时表为空,插入支出类科目（不包含费用合计类型）
		--INSERT INTO #AType1(typeid,nTypeID,usercode,fullname,sonnum) 
		--select A.ntypeid as typeid,A.nid as nTypeID, A.usercode,A.fullname,A.sonnum 
		--from ac_items A
		--INNER JOIN (select AC.ntypeid from  dbo.f_split(@AtypeID,',') F INNER JOIN AC_Items AC ON F.a=AC.nid ) b ON a.ntypeid LIKE b.ntypeid+'%'
		--LEFT JOIN #AType1 A1 ON A1.ntypeid=A.nid  
		--where a.sonnum=0 and a.ntypeid LIKE '00004%' AND a.ntypeid NOT like '0000400003%' AND A1.typeid IS NULL
	END


IF @BtypeID=''
BEGIN
	INSERT INTO #Btype(typeid)  
	select typeid from F_BaseGetManDetailBType(@OperatorID)
END
ELSE
BEGIN
	INSERT INTO #Btype(typeid)  
	select a.typeid 
	from F_BaseGetManDetailBType(@OperatorID) a 
	inner join (select * from  dbo.f_split(@BtypeID,','))b on a.typeid like b.a+'%'
END
	
DELETE FROM #Atype1 where typeid='000030000200007' --删除借转采购科目

DECLARE @proinfo varchar(5)
select @proinfo=SubValue FROM sysdata WHERE LOWER(SubName)='proinfo'
IF @proinfo='3' --汽配版本
	DELETE FROM #Atype1 where typeid='000040000200004'--#02 删除商品送修科目

IF @STypeID=''
	INSERT INTO #Stype(typeid)  
	select typeid from F_BaseGetManDetailSType(@OperatorID)
ELSE
	INSERT INTO #Stype(typeid)  
	select a.typeid 
	from F_BaseGetManDetailSType(@OperatorID) a
	inner join (select * from  dbo.f_split(@StypeID,',')) b on a.typeid like b.a+'%'

IF @BtypeID=''
BEGIN
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
	SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.deleted 
	FROM Btype a
	INNER JOIN F_GetManBTypeAll(@OperatorID) b ON a.typeid=b.typeid
	WHERE B.parid='00000'
	INSERT INTO #MainType(TypeId,SonNum,UserCode,FullName,deleted)VALUES('99999',0,'其他单位','其他单位',0)
END
ELSE
BEGIN
	SELECT @sonnum = sonnum FROM Btype WHERE Typeid =@BtypeID
	IF @sonnum =0 
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.deleted 
		FROM Btype a
		INNER JOIN  F_GetManBTypeAll(@OperatorID) B  ON a.typeid=b.typeid
		where B.typeid =@BtypeID
	ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT a.typeid,a.usercode,a.fullname,a.sonnum,a.deleted 
		FROM Btype a
		INNER JOIN F_GetManBTypeAll(@OperatorID) b ON a.typeid=b.typeid
		WHERE  b.parid=@BtypeID and b.typeid LIKE @BtypeID+'%'
END

--处理费用科目的翻页
CREATE TABLE #AType
(
	TypeId		varchar(100),
	FullName	varchar(256)
)
DECLARE @SqlCursor 		varchar(8000),		
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256)
SET @SqlCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@nPageColSize AS varchar(50)) + ' 
				nTypeID,							
				FullName
	    FROM    #AType1
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@nPageCol-1) * @nPageColSize AS varchar(50)) + ' UserCode
	                FROM	#AType1
	            )'
	EXEC(@SQLCursor)
	OPEN BaseTypeCursor
	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
	WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #AType(TypeId,FullName)VALUES(@BaseTypeId,@BaseFullName)
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END
CLOSE BaseTypeCursor
DEALLOCATE BaseTypeCursor

--缩小查询数据的范围
CREATE TABLE #ListTable
(
	ATypeId			varchar(100),
	BTypeID			varchar(100),
	Total			 NUMERIC(24, 10) 
)
INSERT INTO #ListTable(ATypeId,BTypeID,Total) 
SELECT 	L.ATypeId,
		SUBSTRING(BTypeId,1,len(@BTypeId)+5), --#01
		ISNULL(SUM(Total),0) AS Total
FROM 	ListTable L
INNER JOIN #BType B ON B.TypeID=L.BtypeId
INNER JOIN #Atype1 A1 ON A1.nTypeID=L.AtypeId
INNER JOIN #Stype S ON S.TypeID=L.STypeID
INNER JOIN #Dtype D ON D.TypeID=L.DTypeID
INNER JOIN #Etype E ON E.TypeID=L.EtypeId
WHERE	L.Audited = 1
		AND L.Total<>0
		AND L.Total IS NOT NULL
		AND L.BTypeId<>'' 
		AND L.BtypeId IS NOT NULL
		AND L.BillDate>=@StartDate
		AND L.BillDate<=@EndDate
GROUP BY L.ATypeId,L.BTypeId
UNION ALL
--****9.6需求修改-文档遗漏导致BUG：667 杨俊2015-05-13--
SELECT * 
FROM 
(
	SELECT 	L.ATypeId,
			'99999' AS BTypeId,
			ISNULL(SUM(Total),0) AS Total
	FROM 	ListTable L
	INNER JOIN #Atype1 A1 ON A1.nTypeID=L.AtypeId
	INNER JOIN #Stype S ON S.TypeID=L.STypeID
	INNER JOIN #Dtype D ON D.TypeID=L.DTypeID
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	WHERE	L.Audited = 1
			AND L.Total<>0
			AND L.Total IS NOT NULL
			AND (L.BTypeId='' OR L.BtypeId IS NULL OR L.BTypeId='0')
			AND L.BillDate>=@StartDate
			AND L.BillDate<=@EndDate
	GROUP BY L.ATypeId,L.BTypeId
	UNION ALL
	SELECT (SELECT TOP 1 nId FROM Ac_Items WHERE FullName = '业务提成') AS ATypeID,
	'99999' AS BTypeId,
	ISNULL(SUM(CBND.CommissionTotal),0) AS Total 
	FROM CommissionBillNew AS CBN
	INNER JOIN CommissionBillNewDetail AS CBND ON(CBN.BillNumberId = CBND.BillNumberId)
	INNER JOIN #Stype S ON S.TypeID=CBN.STypeID
	INNER JOIN #Dtype D ON D.TypeID=CBND.DTypeID
	INNER JOIN #Etype E ON E.TypeID=CBND.EtypeId
	WHERE CBN.ifcheck = 't'
		AND CBN.BillDate>=@StartDate
		AND CBN.BillDate<=@EndDate
) AS A
--****************************************************************************--

--#01
--合计每行费用
SELECT BTypeId,SUM(Total) AS Total
INTO #Sum_ListTable
FROM #ListTable
GROUP BY
	BTypeId
	
--#01
--给临时表添加一列--行合计列
SET @SQL='ALTER TABLE #MainType ADD RowTotal  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
EXEC(@SQL)

SET @SQL='UPDATE #MainType SET RowTotal = b.Total
		FROM  #MainType AS a,#Sum_ListTable AS b
		WHERE a.TypeId = b.BtypeId'

EXEC(@SQL)

DROP TABLE #Sum_ListTable

--运算具体的数据
DECLARE @AFullName	varchar(256),
		@AATypeId	varchar(100)
DECLARE AType_Cursor CURSOR FOR
	SELECT TypeId,FullName FROM #AType
OPEN AType_Cursor
FETCH NEXT FROM AType_Cursor INTO @AATypeId,@AFullName
WHILE @@FETCH_STATUS = 0
BEGIN
	--修改表结构
	SET @SQL = 'ALTER TABLE #MainType ADD ['+ @AFullName + ']  NUMERIC(24, 10)  DEFAULT(''0'')'
	SET  @ColName= @ColName+',['+ @AFullName + ']'
	EXEC(@SQL)
	--处理数据
	SET @SQL = 'UPDATE	#MainType
				SET		['+@AFullName+'] = ISNULL(B.Total,0)
				FROM	#MainType A
				LEFT JOIN (
							SELECT	ISNULL(X.TypeId,''0'') AS TypeId,
									ISNULL(SUM(Y.Total),''0'') AS Total								
							FROM	#MainType X
							LEFT JOIN (
										SELECT	BTypeId,
												ISNULL(SUM(Total),0) AS Total
										FROM	#ListTable
										WHERE	ATypeId = '+char(39)+@AATypeId+char(39)+'
										GROUP BY BTypeId
							)Y ON LEFT(Y.BTypeId,LEN(X.TypeId)) = X.TypeId 
							GROUP BY X.TypeId
				)B ON LEFT(B.TypeId,LEN(A.TypeId)) = A.TypeId '
	EXEC(@SQL)
	FETCH NEXT FROM AType_Cursor INTO @AATypeId,@AFullName
END
CLOSE AType_Cursor
DEALLOCATE AType_Cursor
DECLARE @AtypeCount int
SET @AtypeCount = 0 

SELECT @AtypeCount =COUNT(*)  FROM #AType1
IF @Flag =0
	EXEC('SELECT '+@AtypeCount+' as atypecount,'+@ColName+' FROM #MainType WHERE RowTotal<>0 ORDER BY UserCode')
ELSE
	EXEC('SELECT '+@ColName+' FROM #MainType WHERE RowTotal<>0 ORDER BY UserCode')

--删除临时表
SET @SQL = 'DROP TABLE #AType,#ListTable,#MainType,#DetailATypeFy,#Etype,#Dtype,#Atype1,#Btype,#SType'
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeExpenseListPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeExpenseListPrint]
GO















/*
	作者：谢吉康
	日期：2007-3-4
	描述：单位费用报表
	--修改记录#01--------------------------------------------------------
	--人员：徐辉
	--日期：2008-04-10
	--说明：添加行合计（v3.9）
*/
CREATE       PROCEDURE Web_QueryBTypeExpenseListPrint
(
	@OperatorId		varchar(100),
	@ATypeId		varchar(100),
	@BTypeId		varchar(100),
	@StartDate		datetime,
	@EndDate		datetime,
	@aPageNo		int = 1,		-- 费用科目的翻页
	@bCount			int = 10
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorId is null return 1
declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorId,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output
if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--转换时间生成临时表
DECLARE @TableName 	varchar(1000),
		@SQL		varchar(8000),
		@LenBTypeId	varchar(100),
		@SonNum		int
SET @TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SET @SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		TypeId		varchar(100) NOT NULL,
		SonNum		int			 NOT NULL,
		UserCode	varchar(100) NOT NULL,
		FullName	varchar(100) NOT NULL,
		deleted int
	) '
EXEC(@SQL)

DECLARE @ColName varchar(4000)
SET  @ColName ='fullname+''(''+usercode+'')'' as [单位/费用支出],RowTotal as [总计]'

IF @BTypeId = ''
	BEGIN
		EXEC('INSERT INTO '+N'##'+@TableName+' SELECT TypeId,SonNum,UserCode,FullName,deleted FROM BType WHERE Deleted = 0 AND ParId = ''00000''')
		--强行写入其他单位
		EXEC('INSERT INTO '+N'##'+@TableName+'(TypeId,SonNum,UserCode,FullName,deleted)VALUES(''99999'',0,''其他单位'',''其他单位'',0)')
	END
ELSE
	BEGIN
		SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId
		IF @SonNum = 0
			EXEC('INSERT INTO '+N'##'+@TableName+' SELECT TypeId,SonNum,UserCode,FullName,deleted FROM BType WHERE Deleted = 0 AND TypeId = '''+@BTypeId+''' AND (TypeId LIKE '''+@MBTypeId+'%'' OR TypeId LIKE '''+@MBTypeId2+'%'')')
		ELSE
		BEGIN
			IF LEFT(@BTypeId,5) = '00001' --客户分支
			BEGIN
				IF LEN(@MBTypeId) >= LEN(@BTypeId) --直接跳到权限节点
				BEGIN
					SET @BtypeId = @MBTypeId
					SELECT @SonNum = SonNum FROM BType WHERE TypeId = @MBTypeId
					IF @SonNum = 0 --客户权限是子节点
						EXEC('INSERT INTO '+N'##'+@TableName+' SELECT TypeId,SonNum,UserCode,FullName,deleted FROM BType WHERE Deleted = 0 AND TypeId = '''+@MBTypeId+'''')
					ELSE
						EXEC('INSERT INTO '+N'##'+@TableName+' SELECT TypeId,SonNum,UserCode,FullName,deleted FROM BType WHERE Deleted = 0 AND ParId = '''+@MBTypeId+'''  AND (TypeId LIKE '''+@MBTypeId+'%'' OR TypeId LIKE '''+@MBTypeId2+'%'')')
				END
				ELSE --传进来的父节点是权限范围内的
					EXEC('INSERT INTO '+N'##'+@TableName+' SELECT TypeId,SonNum,UserCode,FullName,deleted FROM BType WHERE Deleted = 0 AND ParId = '''+@BTypeId+'''  AND (TypeId LIKE '''+@MBTypeId+'%'' OR TypeId LIKE '''+@MBTypeId2+'%'')')
			END
			IF LEFT(@BTypeId,5) = '00002' --供货商分支
			BEGIN
				IF LEN(@MBTypeId2) >= LEN(@BTypeId) --直接跳到权限节点
				BEGIN
					SET @BtypeId = @MBTypeId2
					SELECT @SonNum = SonNum FROM BType WHERE TypeId = @MBTypeId2
					IF @SonNum = 0 --供货商权限是子节点
						EXEC('INSERT INTO '+N'##'+@TableName+' SELECT TypeId,SonNum,UserCode,FullName,deleted FROM BType WHERE Deleted = 0 AND TypeId = '''+@MBTypeId2+'''')
					ELSE
						EXEC('INSERT INTO '+N'##'+@TableName+' SELECT TypeId,SonNum,UserCode,FullName,deleted FROM BType WHERE Deleted = 0 AND ParId = '''+@MBTypeId2+'''  AND (TypeId LIKE '''+@MBTypeId+'%'' OR TypeId LIKE '''+@MBTypeId2+'%'')')
				END
				ELSE --传进来的父节点是权限范围内的
					EXEC('INSERT INTO '+N'##'+@TableName+' SELECT TypeId,SonNum,UserCode,FullName,deleted FROM BType WHERE Deleted = 0 AND ParId = '''+@BTypeId+'''  AND (TypeId LIKE '''+@MBTypeId+'%'' OR TypeId LIKE '''+@MBTypeId2+'%'')')
			END
		END
	END


--处理费用科目的翻页
CREATE TABLE #AType
(
	TypeId		varchar(100),
	FullName	varchar(256)
)
DECLARE @SqlCursor 		varchar(8000),		
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256)
SET @SqlCursor = '
	DECLARE BaseTypeCursor CURSOR FOR
	    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
				TypeID,							
				FullName
	    FROM    AType 
	    WHERE  	SonNum = 0
				AND UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@aPageNo-1) * @bCount AS varchar(50)) + ' UserCode
	                FROM	AType
					WHERE 	SonNum = 0
							AND TypeId LIKE ''00004%''
							AND TypeId LIKE '+char(39)+@ATypeId+'%'+char(39)+'
							AND TypeId LIKE '+char(39)+@MExpense+'%'+char(39)+'
	            )
				AND TypeId LIKE ''00004%''
				AND TypeId LIKE '+char(39)+@ATypeId+'%'+char(39)+'
				AND TypeId LIKE '+char(39)+@MExpense+'%'+char(39)
	EXEC(@SQLCursor)
	OPEN BaseTypeCursor
	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
	WHILE @@FETCH_STATUS = 0
		BEGIN
			INSERT INTO #AType(TypeId,FullName)VALUES(@BaseTypeId,@BaseFullName)
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END
CLOSE BaseTypeCursor
DEALLOCATE BaseTypeCursor
--缩小查询数据的范围
CREATE TABLE #ListTable
(
	ATypeId			varchar(100),
	BTypeID			varchar(100),
	Total			 NUMERIC(24, 10) 
)
INSERT INTO #ListTable(ATypeId,BTypeID,Total) 
SELECT 	ATypeId,
		SUBSTRING(BTypeId,1,len(@BTypeId)+5), --#01
		ISNULL(SUM(Total),0) AS Total
FROM 	ListTable
WHERE	Audited = 1
		AND ATypeID LIKE '00004%'
		AND ATypeID LIKE @ATypeID + '%'
		AND ATypeId LIKE @MExpense + '%'
		AND ISNULL(Total,0)<>0
		AND ISNULL(BTypeId,'')<>''
		AND (ISNULL(BTypeId,'') LIKE @MBTypeId + '%' OR ISNULL(BTypeId,'') LIKE @MBTypeId2 + '%')
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
GROUP BY ATypeId,BTypeId
UNION ALL
SELECT 	ATypeId,
		'99999' AS BTypeId,
		ISNULL(SUM(Total),0) AS Total
FROM 	ListTable
WHERE	Audited = 1
		AND ATypeID LIKE '00004%'
		AND ATypeID LIKE @ATypeID + '%'
		AND ATypeId LIKE @MExpense + '%'
		AND ISNULL(Total,0)<>0
		AND ISNULL(BTypeId,'')=''
		AND BillDate>=@StartDate
		AND BillDate<=@EndDate
GROUP BY ATypeId,BTypeId

--#01
--合计每行费用
SELECT BTypeId,SUM(Total) AS Total
INTO #Sum_ListTable
FROM #ListTable
GROUP BY
	BTypeId

--#01
--给临时表添加一列--行合计列
SET @SQL='ALTER TABLE '+N'##'+@TableName+ ' ADD RowTotal  NUMERIC(24, 10)  DEFAULT 0 WITH VALUES'
EXEC(@SQL)

SET @SQL='UPDATE '+N'##'+@TableName+ ' SET RowTotal = b.Total
		FROM  '+N'##'+@TableName+ ' AS a,#Sum_ListTable AS b
		WHERE a.TypeId = b.BtypeId'

EXEC(@SQL)

DROP TABLE #Sum_ListTable

--运算具体的数据
DECLARE @AFullName	varchar(256),
		@AATypeId	varchar(100)
DECLARE AType_Cursor CURSOR FOR
	SELECT TypeId,FullName FROM #AType
OPEN AType_Cursor
FETCH NEXT FROM AType_Cursor INTO @AATypeId,@AFullName
WHILE @@FETCH_STATUS = 0
	BEGIN
		--修改表结构
		SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @AFullName + ']  NUMERIC(24, 10)  DEFAULT(''0'')'
		SET  @ColName= @ColName+',['+ @AFullName + ']'
		EXEC(@SQL)
		--处理数据
		SET @SQL = 'UPDATE	'+N'##'+@TableName+ '
					SET		['+@AFullName+'] = ISNULL(B.Total,0)
					FROM	'+N'##'+@TableName+ ' A
					LEFT JOIN (
								SELECT	ISNULL(X.TypeId,''0'') AS TypeId,
										ISNULL(SUM(Y.Total),''0'') AS Total								
								FROM	'+N'##'+@TableName+ ' X
								LEFT JOIN (
											SELECT	BTypeId,
													ISNULL(SUM(Total),0) AS Total
											FROM	#ListTable
											WHERE	ATypeId = '+char(39)+@AATypeId+char(39)+'
											GROUP BY BTypeId
								)Y ON LEFT(Y.BTypeId,LEN(X.TypeId)) = X.TypeId 
								GROUP BY X.TypeId
					)B ON LEFT(B.TypeId,LEN(A.TypeId)) = A.TypeId '
		EXEC(@SQL)
		FETCH NEXT FROM AType_Cursor INTO @AATypeId,@AFullName
	END
CLOSE AType_Cursor
DEALLOCATE AType_Cursor
DECLARE @AtypeCount int
SET @AtypeCount = 0 
SELECT @AtypeCount =COUNT(*)  FROM AType WHERE SonNum = 0  AND TypeId LIKE '00004%' AND TypeId LIKE @ATypeID+'%' AND TypeId LIKE  @MExpense+'%'

EXEC('SELECT '+@ColName+' FROM '+N'##'+@TableName+' ORDER BY UserCode')
--删除临时表
SET @SQL = 'DROP TABLE #AType,#ListTable,'+N'##'+@TableName
EXEC(@SQL)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeGiveDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeGiveDetail]
GO
/*
  作者：彭勇
	日期：2012-06-26
	描述：添加dealbtypeid往来单位，以前的往来单位 改为结算单位
*/

/*
	作者：谢吉康
	日期：2005-4-19
	描述：客户赠送明细查询
*/
/*
    修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
    
     
    修改：舒珊
    日期：2016-05-27
    描述： 添加商品类别筛选
*/
CREATE PROCEDURE Web_QueryBTypeGiveDetail
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	varchar(8000),	--往来单位ID
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@DtypeID		VARCHAR(max),	--部门ID
	@STypeId		varchar(max),
	@IsReporting	INT,				--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

/*===============================================权限范围控制 BEGIN  WANG WEI===========================================*/
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) 
	SELECT e.TypeId FROM F_GetManDetailEType(@OperatorID) e INNER JOIN  F_GetAllBaseTypeId(@ETypeId,3) se ON e.TypeId=se.TypeId
ELSE	
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeId,3)
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.TypeId
ELSE	
	INSERT INTO #GetManKTypeId(TypeId) SELECT typeid FROM F_GetAllBaseTypeId(@KTypeId,4)
	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
--IF @MKtypeid='-99999'
--	INSERT INTO #GetManPTypeId(TypeId) 
--	SELECT p.TypeId FROM F_GetManDetailPType(@OperatorID) p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
--ELSE
--	INSERT INTO #GetManPTypeId(TypeId) 	SELECT TypeId FROM F_GetAllBaseTypeId(@PTypeId,1)

	INSERT INTO #GetManPTypeId(TypeId) 	SELECT TypeId FROM F_ManPTypeInCategoryID ( @OperatorId,@PTypeId,@ptypecategoryid)


--结算单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM  F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorId)	

--往来单位
CREATE TABLE #GetMandealBTypeId(TypeId	varchar(100))
INSERT INTO #GetMandealBTypeId(TypeId) SELECT * FROM  F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorId)	

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @DtypeId<>''
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetManDetailDType(@OperatorID)
/*===============================================权限范围控制 END  WANG WEI===========================================*/

DECLARE @SQL 	varchar(8000)

IF @dealBTypeId = '00000'
	SET @dealBTypeId = '%'
SET	@SQL = '
			SELECT	DISTINCT
					Bil.BillNumberId,Bil.BillType,
					Bil.BillCode,
					Bil.BillDate,				
					Bil.ETypeId,
					Bil.BTypeId,
					bil.dealbtypeid,
					i.KTypeId,
					Bil.STypeId,				
					ISNULL(ABS(SUM(I.Qty)),0) AS Qty,					
					ISNULL(ABS(SUM(I.CostTotal)),0) AS CostTotal,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	
			FROM	BillIndex Bil INNER JOIN InOutStockTable I	ON	Bil.BillNumberId = I.BillNumberId
			
				 left join Custom_BillIndex csindex on i.billnumberid=csindex.BillId and i.billtype=csindex.billtype
left join Custom_BillDetails csdetail on i.billnumberid=csdetail.BillId and i.billtype=csdetail.billtype AND i.id=csdetail.Detailid
			 ' 	
			
	IF @KTypeId<>'00000' OR @Mktypeid='-99999' 
			SET	@SQL =@SQL+' INNER JOIN	#GetManKTypeId	k ON k.typeid=i.KTypeId '
			
	IF @ETypeId<>'00001' OR  @MEtypeid='-99999' 		
			SET	@SQL =@SQL+' INNER JOIN	#GetManETypeId	e ON e.typeid=Bil.ETypeId '
			
	IF @PTypeId<>'00000' OR @MPtypeid='-99999' 		
			SET	@SQL =@SQL+' INNER JOIN	#GetManPTypeId	p ON p.typeid=I.PTypeId '
	
	IF @DtypeId<>'' OR @MDtypeid='-99999'
			SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
			
	IF @MBtypeid='-99999' OR @MBtypeid2='-99999' 
	BEGIN 		
			SET	@SQL =@SQL+' INNER JOIN	#GetManBTypeId	b ON b.typeid=Bil.BTypeId '
			SET	@SQL =@SQL+' INNER JOIN	#GetMandealBTypeId	b1 ON b1.typeid=Bil.dealBTypeId '			
			
	END		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '					
			
SET	@SQL =@SQL+'  
			WHERE	Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.Draft = 0
					AND Bil.BillType = 139
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND Bil.DealBTypeID LIKE '+char(39)+@dealBTypeId+'%'+char(39)
			IF  @BTypeId<>'' AND @BTypeId<>'00000'
				SET @SQL+=' AND Bil.BTypeID LIKE '+char(39)+@BTypeId+'%'+char(39)
			SET @SQL+=' AND Bil.ifYearBill=''0''	 --年节存标志
			GROUP BY
					Bil.BillNumberId,Bil.BillType,
					Bil.BillCode,
					Bil.BillDate,					
					Bil.ETypeId,
					Bil.BTypeId,
					bil.dealbtypeid,
					i.KTypeId,
					Bil.STypeId,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	'
					
	

--PRINT(@SQL)
--EXEC(@SQL)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
	--PRINT @SQL
	EXEC(@SQL)
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
--	CREATE TABLE #tmp_result
--	(
--		billnumberid VARCHAR(100),
--		billtype     VARCHAR(100),
--		Costom1		VARCHAR(max),
--		Costom2		VARCHAR(max),
--		Costom3		VARCHAR(max),
--		Costom4		VARCHAR(max),
--		Costom5		VARCHAR(max),
--		Costom6		VARCHAR(max),
--		Costom7		VARCHAR(max),
--		Costom8		VARCHAR(max),
--		Costom9		VARCHAR(max),
--		Costom10	VARCHAR(max),
--		Costom11	VARCHAR(max),
--		Costom12	VARCHAR(max),
--		Costom13	VARCHAR(max),
--		Costom14	VARCHAR(max),
--		Costom15	VARCHAR(max),
--		Costom16	VARCHAR(max)
--	)

--	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ' + 
--			  ' 
--			   DECLARE @p1 dbo.TBType_SelfType  
--			   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
--			   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 

--				--显示最终结果
--				SELECT a.*,
--						  b.Costom1,
--						  b.Costom2,
--						  b.Costom3,
--						  b.Costom4,
--						  b.Costom5,
--						  b.Costom6,
--						  b.Costom7,
--						  b.Costom8,
--						  b.Costom9,
--						  b.Costom10,
--						  b.Costom11,
--						  b.Costom12,
--						  b.Costom13,
--						  b.Costom14,
--						  b.Costom15,
--						  b.Costom16 
--						  FROM #temp1 a 
--						  left join #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
						  
--				DROP TABLE #temp1,#tmp_result
--			   '
--	EXEC (@SQL)
--END	
----------------------------------------------------------

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetMandealBTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeGiveLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeGiveLine]
GO
/*
  作者：彭勇
	日期：2012-06-26
	描述：添加dealbtypeid往来单位，以前的往来单位 改为结算单位
*/

/*
	作者：谢吉康
	日期：2005-4-19
	描述：客户赠送线性查询
	
	 
    修改：舒珊
    日期：2016-05-27
    描述： 添加商品类别筛选
*/
CREATE  PROCEDURE Web_QueryBTypeGiveLine
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	varchar(8000),	--往来单位ID
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@showZero		int,			--是否显示为零   0.显示   1.不显示为零
	@SortField		varchar(100),	--排序字段
	@SortType		varchar(100),	--排序方式
	@DtypeId		varchar(max),	--部门ID
	@STypeId		varchar(max),
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------
/*===============================================权限范围控制 BEGIN  WANG WEI===========================================*/
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) 
	SELECT e.TypeId FROM F_GetManDetailEType(@OperatorID) e INNER JOIN  F_GetAllBaseTypeId(@ETypeId,3) se ON e.TypeId=se.TypeId
ELSE	
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeId,3)
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.TypeId
ELSE	
	INSERT INTO #GetManKTypeId(TypeId) SELECT typeid FROM F_GetAllBaseTypeId(@KTypeId,4)
	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
--IF @MKtypeid='-99999'
--	INSERT INTO #GetManPTypeId(TypeId) 
--	SELECT p.TypeId FROM F_GetManDetailPType(@OperatorID) p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
--ELSE
--	INSERT INTO #GetManPTypeId(TypeId) 	SELECT TypeId FROM F_GetAllBaseTypeId(@PTypeId,1)

	INSERT INTO #GetManPTypeId(TypeId) 	SELECT TypeId FROM F_ManPTypeInCategoryID ( @OperatorId,@PTypeId,@ptypecategoryid)


--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorId)	

--结算单位
CREATE TABLE #GetManCTypeId(TypeId	varchar(100))
INSERT INTO #GetManCTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorId)	


--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @MDtypeid='-99999'
	INSERT INTO #GetManDTypeId(TypeId) 
	SELECT b.TypeId FROM F_GetManDetailDType(@OperatorID) b  INNER JOIN  F_GetAllBaseTypeId(@DTypeId,9) sb ON b.TypeId = sb.TypeId
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM	F_GetAllBaseTypeId(@DTypeId,9)
/*===============================================权限范围控制 END  WANG WEI===========================================*/

DECLARE @SQL 		varchar(8000),
		@BTypeAll	int

SET	@SQL = '
			SELECT TypeId,SonNum,usercode,deleted INTO #GetManBTypeAll FROM F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') WHERE SonNum = 0 
			
			SELECT	B.TypeId as dealbtypeid,
					B.SonNum,
					B.Usercode,
					ISNULL(ABS(SUM(A.Qty)),0) AS Qty,
					CASE
						WHEN ISNULL(ABS(SUM(A.Qty)),0)=0 THEN 0
						ELSE cast(ISNULL(ABS(SUM(A.CostTotal)),0)as NUMERIC(24, 10))/cast(ISNULL(ABS(SUM(A.Qty)),0)as NUMERIC(24, 10))
					END AS CostPrice,
					ISNULL(ABS(SUM(A.CostTotal)),0) AS CostTotal
			FROM 	#GetManBTypeAll b
			left  JOIN (
					SELECT	Bil.dealBTypeId,
							ISNULL(SUM(I.Qty),0) AS Qty,
							ISNULL(I.CostPrice,0) AS CostPrice,
							ISNULL(SUM(I.CostTotal),0) AS CostTotal
					FROM	BillIndex Bil
							INNER JOIN	InOutStockTable I ON Bil.BillNumberId = I.BillNumberId ' 	
			
	IF @KTypeId<>'00000' OR @Mktypeid='-99999' 
			SET	@SQL =@SQL+' INNER JOIN	#GetManKTypeId	k ON k.typeid=i.KTypeId '
			
	IF @ETypeId<>'00001' OR  @MEtypeid='-99999' 		
			SET	@SQL =@SQL+' INNER JOIN	#GetManETypeId	e ON e.typeid=Bil.ETypeId '
			
	IF @PTypeId<>'00000' OR @MPtypeid='-99999' 		
			SET	@SQL =@SQL+' INNER JOIN	#GetManPTypeId	p ON p.typeid=I.PTypeId '
			
	IF @DtypeId<>'' OR @MDtypeid='-99999'
			SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
			
	IF  @MBtypeid='-99999' OR @MBtypeid2='-99999' or @BTypeId<>''
	BEGIN					
		SET	@SQL = @SQL + '	INNER JOIN	#GetManCTypeId	b1 ON b1.typeid=Bil.BTypeId '
	END
		SET	@SQL =@SQL+' INNER JOIN	#GetManBTypeId	b ON b.typeid=Bil.dealBTypeId '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '					
			
SET	@SQL =@SQL+' 	WHERE	Bil.IfCheck = ''t''
							AND Bil.RedWord = 0
							AND Bil.BillType = 139
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
							AND Bil.ifYearBill=''0''	 --年节存标志
					GROUP BY
							Bil.dealBTypeId,
							I.CostPrice							
			)A ON A.dealBTypeId = B.TypeId
			WHERE 1=1 '
					
IF @dealBTypeId<>'00000'		
	SET	@SQL = @SQL + ' AND B.TypeId LIKE '+char(39)+@dealBTypeId+'%'+char(39)					
			
IF @showZero = 1--是否显示数量为零
	SET @SQL = @SQL + ' AND ISNULL(A.Qty,0)<>0 '	
		
SET @SQL = @SQL + '
			GROUP BY
				B.TypeId,
				B.SonNum,
				B.Usercode
			ORDER BY  '+CASE
							WHEN @SortField = 'Qty' THEN 'A.Qty'
							WHEN @SortField = 'CostTotal' THEN 'A.CostTotal'
							ELSE 'B.UserCode'
						END
					   +CASE
							WHEN @SortType = 0 THEN ' ASC'
							ELSE ' DESC'
						END
SET @SQL=@SQL+' DROP TABLE #GetManBTypeAll '
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetManCTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeGiveList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeGiveList]
GO


/*
	作者：谢吉康
	日期：2005-4-19
	描述：客户赠送查询
-------------------------------------------------------------------------
	Author：Wang Wei
	Modify Time:2010-7-27
	Description：优化	
	
	修改：舒珊
    日期：2015-05-27
    描述： 添加商品类别筛选
*/
CREATE     PROCEDURE Web_QueryBTypeGiveList
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	VARCHAR(8000),	--往来单位
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@DtypeId		varchar(max),	--部门ID
	@STypeId		varchar(max),
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

/*===============================================权限范围控制 BEGIN  WANG WEI===========================================*/
--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) 
	SELECT e.TypeId FROM F_GetManDetailEType(@OperatorID) e INNER JOIN  F_GetAllBaseTypeId(@ETypeId,3) se ON e.TypeId=se.TypeId
ELSE	
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeId,3)
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.TypeId
ELSE	
	INSERT INTO #GetManKTypeId(TypeId) SELECT typeid FROM F_GetAllBaseTypeId(@KTypeId,4)
	

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManPTypeId(TypeId) 
	SELECT p.TypeId FROM F_ManPTypeInCategoryID ( @OperatorId,@PTypeId,@ptypecategoryid)   p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
ELSE
	INSERT INTO #GetManPTypeId(TypeId) 	SELECT TypeId FROM F_ManPTypeInCategoryID ( @OperatorId,@PTypeId,@ptypecategoryid)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorId)	

--结算单位
CREATE TABLE #GetManCTypeId(TypeId	varchar(100))
INSERT INTO #GetManCTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorId)	

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @MDtypeid='-99999'
	INSERT INTO #GetManDTypeId(TypeId) 
	SELECT b.TypeId FROM F_GetManDetailDType(@OperatorID) b  INNER JOIN  F_GetAllBaseTypeId(@DTypeId,9) sb ON b.TypeId = sb.TypeId
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM	F_GetAllBaseTypeId(@DTypeId,9)

/*===============================================权限范围控制 END  WANG WEI===========================================*/
	

DECLARE @SQL 		varchar(8000),@SonNum 	INT

SELECT @SonNum = SonNum FROM BType WHERE TypeId = @dealBTypeId

SET	@SQL = '
			SELECT * INTO #GetManBTypeAll FROM F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') 
			
			SELECT	Bil.dealBTypeId,
					ISNULL(SUM(I.Qty),0) AS Qty,
					ISNULL(I.CostPrice,0) AS CostPrice,
					ISNULL(SUM(I.CostTotal),0) AS CostTotal
			INTO 	#Tmp
			FROM	BillIndex Bil INNER JOIN InOutStockTable I	ON	Bil.BillNumberId = I.BillNumberId ' 	
			
	IF @KTypeId<>'00000' OR @Mktypeid='-99999' 
			SET	@SQL =@SQL+' INNER JOIN	#GetManKTypeId	k ON k.typeid=i.KTypeId '
			
	IF @ETypeId<>'00001' OR  @MEtypeid='-99999' 		
			SET	@SQL =@SQL+' INNER JOIN	#GetManETypeId	e ON e.typeid=Bil.ETypeId '
			
	IF @PTypeId<>'00000' OR @MPtypeid='-99999' OR @ptypecategoryid<>''		
			SET	@SQL =@SQL+' INNER JOIN	#GetManPTypeId	p ON p.typeid=I.PTypeId '
			
	IF @DtypeId<>'' OR @MDtypeid='-99999'
			SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
			
				
	IF  @MBtypeid='-99999' OR @MBtypeid2='-99999' or @BTypeId<>''
	BEGIN					
		SET	@SQL = @SQL + '	INNER JOIN	#GetManCTypeId	b1 ON b1.typeid=Bil.BTypeId '
	END
		SET	@SQL =@SQL+' INNER JOIN	#GetManBTypeId	b ON b.typeid=Bil.dealBTypeId '	
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '						
			
SET	@SQL =@SQL+' 
			WHERE	Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.BillType = 139
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND Bil.ifYearBill=''0''	 --年节存标志
			GROUP BY
					Bil.dealBTypeId,
					I.CostPrice	  

			SELECT	B.TypeId as dealbtypeid,
					B.SonNum,
					B.UserCode,
					B.FullName,
					ISNULL(ABS(SUM(A.Qty)),0) AS Qty,
					CASE
						WHEN ISNULL(ABS(SUM(A.Qty)),0)=0 THEN 0
						ELSE  cast(ISNULL(ABS(SUM(A.CostTotal)),0)as NUMERIC(24, 10))/cast(ISNULL(ABS(SUM(A.Qty)),0)as NUMERIC(24, 10))
					END AS CostPrice,
					ISNULL(ABS(SUM(A.CostTotal)),0) AS CostTotal
			FROM #GetManBTypeAll B
			LEFT JOIN #Tmp A ON LEFT(A.dealBTypeId,LEN(B.TypeId)) = B.TypeId
			WHERE '

		IF @SonNum>=1
			SET @SQL = @SQL  + ' B.ParId = '+char(39)+@dealBTypeId+char(39)
		ELSE
			SET @SQL = @SQL + ' B.TypeId = '+char(39)+@dealBTypeId+char(39)

SET @SQL = @SQL + ' 
			GROUP BY
				B.TypeId,
				B.SonNum,
				B.UserCode,
				B.FullName
			ORDER BY B.UserCode
			DROP TABLE #GetManBTypeAll
			DROP TABLE #Tmp '


--PRINT(@SQL)
EXEC(@SQL)


DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetManBTypeId,#GetManCTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeGiveMeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeGiveMeDetail]
GO

/*
	作者：彭勇
	日期：2012-06-26
	描述：添加dealtypeid往来单位，原来的往来单位改为结算单位
*/
/*
	作者：谢吉康
	日期：2005-4-19
	描述：供货商获赠明细查询
*/
CREATE PROCEDURE Web_QueryBTypeGiveMeDetail
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	varchar(8000),	--往来单位ID
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@DtypeId		varchar(max),	--部门ID
	@STypeId		varchar(max),	--分支机构ID
	@IsReporting	INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @MPtypeid='-99999'
	INSERT INTO #GetManPTypeId(TypeId) 
	SELECT p.TypeId FROM F_GetManDetailPType(@OperatorID) p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
ELSE
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@PTypeId,1)

--结算单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId)  SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)	
	
--往来单位
CREATE TABLE #GetMandealBTypeId(TypeId	varchar(100))
INSERT INTO #GetMandealBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)	

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.TypeId
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT typeid FROM F_GetAllBaseTypeId(@KTypeId,4)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) 
	SELECT e.TypeId FROM F_GetManDetailEType(@OperatorID) e INNER JOIN  F_GetAllBaseTypeId(@ETypeId,3) se ON e.TypeId=se.TypeId
ELSE
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM	F_GetAllBaseTypeId(@ETypeId,3)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @DtypeId<>''
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetManDetailDType(@OperatorID)
	
DECLARE @SQL 	varchar(8000)
SET	@SQL = '
			SELECT	DISTINCT
					Bil.BillNumberId,bil.BillType,
					Bil.BillCode,
					Bil.BillDate,						
					Bil.ETypeId,
					Bil.BTypeId,
					bil.dealbtypeid,
					i.KTypeId,	
					Bil.STypeId,				
					ISNULL(ABS(SUM(I.Qty)),0) AS Qty,					
					ISNULL(ABS(SUM(I.CostTotal)),0) AS CostTotal
			FROM	BillIndex Bil
					INNER JOIN InOutStockTable  I ON Bil.BillNumberId = I.BillNumberId '
					
IF @KTypeId<>'00000' OR @MKtypeid='-99999'
	SET	@SQL = @SQL + '	INNER JOIN	#GetManKTypeId	k ON k.typeid=i.KTypeId '
	
IF @ETypeId<>'00001' OR  @MEtypeid='-99999'					
	SET	@SQL = @SQL + '	INNER JOIN	#GetManETypeId	e ON e.typeid=Bil.ETypeId '
	
IF @PTypeId<>'00000' OR   @MPtypeid='-99999'					
	SET	@SQL = @SQL + '	INNER JOIN	#GetManPTypeId	p ON p.typeid=I.PTypeId '
	
IF  @MBtypeid='-99999' OR @MBtypeid2='-99999'					
	SET	@SQL = @SQL + '	INNER JOIN	#GetManBTypeId	b ON b.typeid=Bil.BTypeId '
	SET	@SQL = @SQL + '	INNER JOIN	#GetMandealBTypeId	b1 ON b1.typeid=Bil.dealBTypeId '

IF @DtypeId<>'' OR @MDtypeid='-99999'
	SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
						
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '							
															
SET	@SQL = @SQL + '						
			WHERE	Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.Draft = 0
					AND Bil.BillType = 126
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)
IF @BTypeId<>'00000'					
	SET	@SQL = @SQL + 'AND Bil.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)

SET @Sql=@Sql + ' AND Bil.ifYearBill= 0 '    --年节存标志	
SET	@SQL = @SQL 	+'
			GROUP BY
					Bil.BillNumberId,bil.BillType,
					Bil.BillCode,
					Bil.BillDate,					
					Bil.ETypeId,
					Bil.BTypeId,
					bil.dealbtypeid,
					i.KTypeId,
					Bil.STypeId	'
			

--PRINT(@SQL)
--EXEC(@SQL)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题


	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ' + 
			  ' 
			--显示最终结果
				SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head
			
					  FROM #temp1 a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype

				
				DROP TABLE #temp1
			   '
	EXEC (@SQL)

----------------------------------------------------------

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetMandealBTypeId




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeGiveMeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeGiveMeLine]
GO
/*
	作者：彭勇
	日期：2012-06-26
	描述：添加dealtypeid往来单位，原来的往来单位改为结算单位
*/
/*
	作者：谢吉康
	日期：2005-4-19
	描述：供货商获赠线性查询
*/
CREATE  PROCEDURE Web_QueryBTypeGiveMeLine
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	varchar(8000),	--往来单位ID
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@showZero		int,			--是否显示为零   0.显示   1.不显示为零
	@SortField		varchar(100),	--排序字段
	@SortType		varchar(100),	--排序方式
	@DtypeId		varchar(max),	--部门ID
	@STypeId		varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

--结算单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT   TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)

--往来单位
CREATE TABLE #GetMandealBTypeId(TypeId	varchar(100))
INSERT INTO #GetMandealBTypeId(TypeId) SELECT   TypeId FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)


--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT e.typeid FROM F_GetManDetailEType(@OperatorID) e INNER JOIN  F_GetAllBaseTypeId(@ETypeId,3) se ON e.typeid=se.typeid

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT p.typeid FROM F_GetManDetailPType(@OperatorID) p INNER JOIN  F_GetAllBaseTypeId(@PTypeId,1) sp ON p.typeid=sp.typeid

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k  INNER JOIN F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.typeid

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @MDtypeid='-99999'
	INSERT INTO #GetManDTypeId(TypeId) 
	SELECT b.TypeId FROM F_GetManDetailDType(@OperatorID) b  INNER JOIN  F_GetAllBaseTypeId(@DTypeId,9) sb ON b.TypeId = sb.TypeId
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM	F_GetAllBaseTypeId(@DTypeId,9)

	
DECLARE @SQL 		varchar(8000)

SET	@SQL = '
			SELECT	i.BTypeId,
					ISNULL(SUM(I.Qty),0) AS Qty,
					ISNULL(I.CostPrice,0) AS CostPrice,
					ISNULL(SUM(I.CostTotal),0) AS CostTotal
			INTO	#tmp
			FROM	BillIndex Bil 
					INNER JOIN	InOutStockTable I ON Bil.BillNumberId = I.BillNumberId '
IF @BTypeId<>'00000' OR  @MBtypeid='-99999' OR @MBtypeid2='-99999'
BEGIN
	SET	@SQL =@SQL+' INNER JOIN #GetManBTypeId b ON b.typeid=Bil.BTypeId'	
end
	SET	@SQL =@SQL+' INNER JOIN #GetMandealBTypeId b1 ON b1.typeid=i.BTypeId'	
IF  @KTypeId<>'00000' OR  @MKtypeid='-99999'
	SET	@SQL =@SQL+' INNER JOIN #GetManKTypeId k ON k.typeid=i.KTypeId'		

IF  @ETypeId<>'00001' OR   @MEtypeid='-99999'
	SET	@SQL =@SQL+' INNER JOIN #GetManETypeId e ON e.typeid=Bil.ETypeId'		

IF  @PTypeId<>'00000' OR    @MPtypeid='-99999'
	SET	@SQL =@SQL+' INNER JOIN #GetManPTypeId p ON p.typeid=I.PTypeId'		

IF @DtypeId<>'' OR @MDtypeid='-99999'
	SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '		

SET	@SQL =@SQL+'
			WHERE	Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.BillType = 126
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND Bil.ifYearBill=0	 --年节存标志
			GROUP BY
					i.BTypeId,
					I.CostPrice	
						
			SELECT	B.TypeId,
					B.SonNum,
					B.UserCode,
					B.FullName,
					ISNULL(ABS(SUM(A.Qty)),0) AS Qty,
					CASE
						WHEN ISNULL(ABS(SUM(A.Qty)),0)=0 THEN 0
						ELSE cast(ISNULL(ABS(SUM(A.CostTotal)),0)as NUMERIC(24, 10))/cast(ISNULL(ABS(SUM(A.Qty)),0)as NUMERIC(24, 10))
					END AS CostPrice,
					ISNULL(ABS(SUM(A.CostTotal)),0) AS CostTotal
			FROM 	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B
					LEFT JOIN #tmp A ON A.BTypeId = B.TypeId
			WHERE	 
					B.SonNum = 0 '
IF @dealbtypeid<>'00000'
	SET	@SQL =@SQL+' AND B.TypeId LIKE '+char(39)+@dealbtypeid+'%'+char(39)

			--是否显示数量为零
			IF @showZero = 1
				SET @SQL = @SQL + ' AND ISNULL(A.Qty,0)<>0 '		
			--排序方式
			SET @SQL = @SQL + ' 
						GROUP BY
							B.TypeId,
							B.SonNum,
							B.UserCode,
							B.FullName
			ORDER BY  '+CASE
							WHEN @SortField = 'Qty' THEN 'A.Qty'
							WHEN @SortField = 'CostTotal' THEN 'A.CostTotal'
							ELSE 'B.UserCode'
						END
					   +CASE
							WHEN @SortType = 0 THEN ' ASC'
							ELSE ' DESC'
						END
SET	@SQL =@SQL+' DROP TABLE #tmp'

--print @SQL
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetMandealBTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBTypeGiveMeList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBTypeGiveMeList]
GO


/*
	作者：谢吉康
	日期：2005-4-19
	描述：客户获赠查询
*/

/*
	作者：彭勇
	日期：2012-06-26
	描述：添加dealtypeid往来单位，原来的往来单位改为结算单位
*/

/*
	修改: 魏伟
	日期: 2015-05-24
	描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC
*/
CREATE     PROCEDURE Web_QueryBTypeGiveMeList
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	varchar(8000),	--往来单位ID
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@DtypeId		varchar(max),	--部门ID
	@STypeId		varchar(max),
	@ptypecategoryid    VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @MPtypeid='-99999'
	INSERT INTO #GetManPTypeId(TypeId) 
	SELECT p.TypeId FROM F_LinePC(@OperatorID,@ptypecategoryid) p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.	TypeId
ELSE
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@PTypeId,1)

--结算单位
CREATE TABLE #GetManCTypeId(TypeId	varchar(100))
INSERT INTO #GetManCTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorId)	
	
--往来单位
CREATE TABLE #GetMandealBTypeId(TypeId	varchar(100))
INSERT INTO #GetMandealBTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorId)	

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.TypeId
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT typeid FROM F_GetAllBaseTypeId(@KTypeId,4)

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'
	INSERT INTO #GetManETypeId(TypeId) 
	SELECT e.TypeId FROM F_GetManDetailEType(@OperatorID) e INNER JOIN  F_GetAllBaseTypeId(@ETypeId,3) se ON e.TypeId=se.TypeId
ELSE
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM	F_GetAllBaseTypeId(@ETypeId,3)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @MDtypeid='-99999'
	INSERT INTO #GetManDTypeId(TypeId) 
	SELECT b.TypeId FROM F_GetManDetailDType(@OperatorID) b  INNER JOIN  F_GetAllBaseTypeId(@DTypeId,9) sb ON b.TypeId = sb.TypeId
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM	F_GetAllBaseTypeId(@DTypeId,9)
	
DECLARE @SQL 		varchar(8000)
	
DECLARE  @SonNum  	int
SELECT @SonNum = SonNum FROM BType WHERE TypeId = @dealBTypeId


SET	@SQL = '
			SELECT * INTO #GetManBTypeAll FROM F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') 

			SELECT	Bil.BTypeId,
			        bil.dealbtypeid, 
					ISNULL(SUM(I.Qty),0) AS Qty,
					ISNULL(I.CostPrice,0) AS CostPrice,
					ISNULL(SUM(I.CostTotal),0) AS CostTotal
			INTO #tmp
			FROM	BillIndex Bil
					INNER JOIN InOutStockTable  I ON Bil.BillNumberId = I.BillNumberId '
IF @KTypeId<>'00000' OR @MKtypeid='-99999'
	SET	@SQL = @SQL + '	INNER JOIN	#GetManKTypeId	k ON k.typeid=i.KTypeId '
	
IF @ETypeId<>'00001' OR  @MEtypeid='-99999'					
	SET	@SQL = @SQL + '	INNER JOIN	#GetManETypeId	e ON e.typeid=Bil.ETypeId '
	
IF @PTypeId<>'00000' OR   @MPtypeid='-99999'					
	SET	@SQL = @SQL + '	INNER JOIN	#GetManPTypeId	p ON p.typeid=I.PTypeId '
	
IF  @MBtypeid='-99999' OR @MBtypeid2='-99999' or @BTypeId<>''
	BEGIN					
		SET	@SQL = @SQL + '	INNER JOIN	#GetManCTypeId	b ON b.typeid=Bil.BTypeId '
	END
	SET	@SQL = @SQL + '	INNER JOIN	#GetMandealBTypeId	b1 ON b1.typeid=Bil.dealbtypeid '	
IF @DtypeId<>'' OR @MDtypeid='-99999'
			SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
						
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '							
										
SET	@SQL = @SQL + '					
			WHERE	Bil.BillNumberId = I.BillNumberId
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.Draft = 0
					AND Bil.BillType = 126
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND Bil.ifYearBill=0	 --年节存标志
			GROUP BY
					Bil.BTypeId,
					bil.dealbtypeid,
					I.CostPrice		
					
			SELECT	B.TypeId,
					B.SonNum,
					B.UserCode,
					B.FullName,
					ISNULL(ABS(SUM(A.Qty)),0) AS Qty,
					CASE
						WHEN ISNULL(ABS(SUM(A.Qty)),0)=0 THEN 0
						ELSE cast( ISNULL(ABS(SUM(A.CostTotal)),0)as NUMERIC(24, 10))/cast(ISNULL(ABS(SUM(A.Qty)),0)as NUMERIC(24, 10))
					END AS CostPrice,
					ISNULL(ABS(SUM(A.CostTotal)),0) AS CostTotal
			FROM 	#GetManBTypeAll B
			LEFT JOIN #tmp A ON LEFT(A.dealBTypeId,LEN(B.TypeId))=B.TypeId
			WHERE '

	IF @SonNum>=1
		SET @SQL = @SQL + 'B.ParId = '+char(39)+@dealBTypeId+char(39)
		ELSE
			SET @SQL = @SQL + 'B.TypeId = '+char(39)+@dealBTypeId+char(39)

SET @SQL = @SQL + ' 
			GROUP BY
				B.TypeId,
				B.SonNum,
				B.UserCode,
				B.FullName
			ORDER BY B.UserCode 
			DROP TABLE  #tmp'


--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManCTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetMandealBTypeId


















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBtypePriceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBtypePriceInfo
GO

--====================================================================================
-----------------功能：往来单位物价信息 
-----------------作者：韩林						   
-----------------日期：2012-07-150                
--====================================================================================

CREATE    PROC Web_QueryBtypePriceInfo
(
	@stypeid VARCHAR(50),
	@operatorid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

SELECT * FROM BtypePriceInfo ORDER BY ptypeid,areatypeid,btypeid,ktypeid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBtypeStatSellBackBase]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBtypeStatSellBackBase]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
    作者:张陈仁
	日期:2007-07-5
	描述:往来单位退货统计树型表
	
	【修改】：鲁大林
	日期：2012-06-01
	描述：添加报表显示列
	
	修改：舒珊
    日期：2015-05-27
    描述： 添加商品类别筛选
    
	修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计
*/
CREATE PROCEDURE [dbo].[Web_QueryBtypeStatSellBackBase]
(
	@inputType		    char(1),		--  1、相应的统计报表功能识别参数
	@startDate		    varchar(30),	--  2、查询起始时间
	@endDate	        varchar(30),	--  3、查询结束时间
	@ptypeid		    varchar(1550),	--  4、商品类别查询范围父节点 ID
	@btypeid			VARCHAR(1550),	 --	  结算单位类别查询范围父节点ID
	@dealbtypeid		varchar(1550),	--  5、往来单位类别查询范围父节点 ID
	@etypeid		    varchar(1550),	--  6、职员类别查询范围父节点 ID
	@ktypeid		    varchar(1550),	--  7、仓库类别查询范围父节点 ID
    @dtypeid		    varchar(1550) , --  8、部门ID
	@atypeid            varchar(1550),  --  9、地区
	@intPageNo		    int = '',	    -- 10、当前查询的页码
	@intPageSize		int = '',		-- 11、每页的显示记录数
	@chvOperatorID		varchar(50),	-- 12、操作员 ID（作权限范围检查用）
	@chkRed             char(1) ='0',   -- 13. 是否显示红冲 
	@billType		    varchar(200),   -- 14. 单据类型
	@chrFlag		    char(1),		-- 15、功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@stypeid            varchar(1550),   --  16、分支机构查询范围父节点 ID
	@ptypecategoryid    VARCHAR(MAX)	 --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON 

--

--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------


--结算往来
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
BEGIN
	INSERT INTO #GetManBTypeId(TypeId) SELECT typeid FROM F_GetManDetailBType(@chvOperatorID)
END

--往来单位
CREATE TABLE #GetManDealBtypeId(typeId VARCHAR(100))
IF @dealbtypeid<>'' OR @MBtypeid=-99999 OR @MBtypeid2=-99999
BEGIN
	INSERT INTO #GetManDealBtypeId(typeId) SELECT typeId FROM F_GetManDetailBType(@chvOperatorID) 
END

--结算单位树型
CREATE TABLE #GetManBTypeAll
(
	TypeId	    varchar(1550),
	SonNum		INT,
	UserCode	VARCHAR(200),
	FullName	VARCHAR(200),
	Deleted		INT,
	ParId		VARCHAR(1550)
)

IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
BEGIN
	INSERT INTO #GetManBTypeAll
		   SELECT TypeId,
				  SonNum,
				  UserCode,
				  FullName,
				  Deleted,
				  ParId
			FROM  F_GetManBTypeAll(@chvOperatorID)
END

        
--往来单位树形
CREATE TABLE #GetManDealBtypeAll
(
	TypeId	    varchar(1550),
	SonNum		INT,
	UserCode	VARCHAR(200),
	FullName	VARCHAR(200),
	Deleted		INT,
	ParId		VARCHAR(1550)
)
INSERT INTO #GetManDealBTypeAll
	   SELECT TypeId,
			  SonNum,
			  UserCode,
			  FullName,
			  Deleted,
			  ParId
		FROM  F_GetManBTypeAll(@chvOperatorID)

DECLARE @SQL varchar(8000)---主体SQL
DECLARE @SonNum int,@BTypeIdMx varchar(max),@dealBTypeIdMx VARCHAR(max)

IF @btypeid='' OR @btypeid='root'
   SET @BTypeIdMx='%'
ELSE
   SET @BTypeIdMx=@btypeid
   
IF @dealbtypeid='' OR @dealbtypeid='root'
   SET @dealBTypeIdMx='%'
ELSE
   SET @dealBTypeIdMx=@dealbtypeid



CREATE TABLE #Dtype (TypeID varchar(50))---部门
CREATE TABLE #Ktype (TypeID varchar(50))---仓库
CREATE TABLE #Ptype (TypeID varchar(50))---商品
CREATE TABLE #Etype (TypeID varchar(50))---职员
--CREATE TABLE #Atype (TypeID varchar(50))---地区
CREATE TABLE #Stype (TypeID varchar(50))---分支机构

IF @dtypeid<>'' OR @MDTypeID=-99999
BEGIN
	INSERT INTO #Dtype select typeid from F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)	
END

IF @ktypeid<>'' OR @MKTypeID=-99999 
BEGIN
	INSERT INTO #Ktype select typeid from F_GetAllManagerBaseTypeId(@ktypeid,4,@chvOperatorID)
END

IF (@KTypeID='10000' OR  @KTypeID='' OR  @KTypeID='00000') AND NOT EXISTS(select * from #Ktype where typeid='10000') 
	insert into #Ktype select '10000'
	
IF @ptypeid<>'' OR @MPTypeID=-99999 OR @ptypecategoryid <>''
BEGIN
	INSERT INTO #Ptype select typeid from F_ManPTypeInCategoryID ( @chvOperatorID,@ptypeid,@ptypecategoryid)
END

IF @etypeid<>'' OR @METypeID=-99999
BEGIN
	INSERT INTO #Etype select typeid from F_GetAllManagerBaseTypeId(@etypeid,3,@chvOperatorID)
END
--INSERT INTO #Atype select typeid from F_GetAllManagerBaseTypeId(@atypeid,10,@chvOperatorID)

IF NOT(@stypeid='' and @MStypeid='00000')
BEGIN
	INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperatorID)
END



CREATE TABLE #inoutstocktable(
	BillNumberId numeric(10, 0),
	BillDate datetime,
	BillType numeric(4,0),
	PtypeId  varchar (1550),
	BtypeId  varchar (1550),
	dealBtypeId VARCHAR(2000),
	EtypeId  varchar (1550),
	KtypeId  varchar (1550),
	AtypeId  varchar (1550),
	DtypeId  varchar (1550),
	Qty       NUMERIC(24, 10) ,
	TaxTotal  NUMERIC(24, 10) ,
	NQty	 NUMERIC(24, 10) 
)

DECLARE @InsertSQL varchar(3000)

SELECT @InsertSQL='INSERT INTO #inoutstocktable(
                                                 BillnumberID,
                                                 BillDate,
                                                 BillType,
                                                 PtypeId,
                                                 BtypeId,
                                                 dealBtypeId,
                                                 EtypeId,
                                                 KtypeId,
                                                 AtypeId,
                                                 DtypeId,
                                                 Qty,
                                                 TaxTotal,
                                                 NQty
                                               )
                                        SELECT   I.BillnumberID,
                                                 I.BillDate,
                                                 I.BillType,
                                                 I.PtypeID,
                                                 I.BtypeId,
                                                 BI.DealBTypeID,
                                                 I.EtypeId,
                                                 I.KtypeId,
                                                 I.AtypeId,
                                                 I.DtypeId,
                                                 I.Qty,
                                                 I.TaxTotal,
                                                 I.NQty
                                        FROM   InoutStockTable I left JOIN BILLINDEX BI ON BI.BillNumberId=I.BillNumberId '
										IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
											SET @InsertSQL=@InsertSQL+' INNER JOIN #GetManBTypeId bt ON bI.btypeid=bt.typeid '+CHAR(13)
										IF @dealbtypeid<>'' OR @MBtypeid=-99999 OR @MBtypeid2=-99999
											SET @InsertSQL=@InsertSQL+'INNER JOIN #GetManDealBtypeId dbt ON BI.DealBTypeID=dbt.typeid'+CHAR(13)
										IF @ptypeid<>'' OR @MPTypeID=-99999 OR @ptypecategoryid <>''
											SET @InsertSQL=@InsertSQL+' INNER JOIN #Ptype p ON I.ptypeid=p.typeid '+CHAR(13)
										IF @dtypeid<>'' OR @MDTypeID=-99999
											SET @InsertSQL=@InsertSQL+' INNER JOIN #Dtype d  ON  I.DtypeID=d.typeid '+CHAR(13)	
										IF @ktypeid<>'' OR @MKTypeID=-99999 
											SET @InsertSQL=@InsertSQL+'	INNER JOIN #Ktype k ON I.ktypeid=k.typeid '+CHAR(13)
										IF @etypeid<>'' OR @METypeID=-99999 
											SET @InsertSQL=@InsertSQL+' INNER JOIN #Etype e  ON I.etypeid=e.typeid '+CHAR(13)
										IF NOT(@stypeid='' and @MStypeid='00000')
											SET @InsertSQL=@InsertSQL+' INNER JOIN #Stype s  ON  I.stypeID=s.typeid '+CHAR(13)
                                        SET @InsertSQL=@InsertSQL+' WHERE I.BillType IN('+@billType+') 
                                                                          AND I.BillDate>='+CHAR(39)+@startDate+CHAR(39)+' 
                                                                          AND I.BillDate<='+CHAR(39)+@endDate+CHAR(39)+' 
                                                                          AND BI.BillDate>='+CHAR(39)+@startDate+CHAR(39)+' 
                                                                          AND BI.BillDate<='+CHAR(39)+@endDate+CHAR(39)+' 
                                                                          AND I.Audited=1
                                                                          AND BI.DealBTypeID LIKE '''+@dealBTypeIdMx+'%''
                                                                          AND BI.BtypeId Like '''+@BTypeIdMx+'%'' 
                                                                          '
                                                                          --PRINT @InsertSQL
EXEC(@InsertSQL)

SELECT @SonNum=sonnum FROM btype WHERE typeId=@dealbtypeid
SET @SQL='SELECT 
                a.typeid,
                a.sonnum,
                --a.usercode,
                ABS(a.ckQty)+ABS(a.hhQty)+ABS(a.wtQty)-a.thQty-rkQty-a.lsthQty AS qty,
                ABS(a.ckMoney)+ABS(a.hhMoney)+ABS(a.wtMoney)-a.thMoney-a.rkMoney-a.lsthMoney AS taxtotal,
                ABS(a.ckQty)+ABS(a.hhQty)+ABS(a.wtQty) AS outqty,
                a.thQty+a.rkQty+a.lsthQty AS backqty,
                ABS(a.ckMoney)+ABS(a.hhMoney)+ABS(a.wtMoney) AS outmoney,
                a.thMoney+rkMoney+a.lsthMoney AS backmoney,
                CASE WHEN ABS(a.ckQty)+ABS(a.hhQty)+ABS(a.wtQty)=0 THEN 0 ELSE cast( (a.thQty+a.rkQty+a.lsthQty) as NUMERIC(24, 10))/cast((ABS(a.ckQty)+ABS(a.hhQty)+ABS(a.wtQty))as NUMERIC(24, 10))*100 END AS outLv,
				ABS(a.ckNQty)+ABS(a.hhNQty)+ABS(a.wtNQty)-a.thNQty-rkNQty-a.lsthNQty AS nqty
          FROM
             (
               SELECT 
                    p.typeid,
                    p.sonnum,
                    p.usercode AS usercode, 
                    SUM(CASE WHEN b.BillType IN(11,305,12) THEN ISNULL(b.Qty,0) ELSE 0 END ) AS ckQty,                   --销售出库单中的销售数量
                    SUM(CASE WHEN b.BillType=160 AND b.Qty<0 THEN ISNULL(b.Qty,0) ELSE 0 END ) AS hhQty,              --销售换货单中的出库数量
                    SUM(CASE WHEN b.BillType=141 THEN ISNULL(b.Qty,0) ELSE 0 END ) AS wtQty,                          --委托代销单中的结算数量
                    SUM(CASE WHEN b.BillType in (45,46) THEN ISNULL(b.Qty,0) ELSE 0 END ) AS thQty,                           --销售退货数量
                    SUM(CASE WHEN b.BillType=215 THEN ISNULL(b.Qty,0) ELSE 0 END ) AS lsthQty,                        --零售退货数量
                    SUM(CASE WHEN b.BillType=160 AND b.Qty>0 THEN ISNULL(b.Qty,0) ELSE 0 END ) AS rkQty,              --销售换货单中的入库数量
                    SUM(CASE WHEN b.BillType IN(11,305,12) THEN ISNULL(b.TaxTotal,0) ELSE 0 END ) AS ckMoney,            --销售出库单中的税价合计
                    SUM(CASE WHEN b.BillType=160 AND b.TaxTotal<0 THEN ISNULL(b.TaxTotal,0) ELSE 0 END ) AS hhMoney,  --销售换货单中出库数量的税价合计
                    SUM(CASE WHEN b.BillType in (45,46) THEN ISNULL(b.TaxTotal,0) ELSE 0 END ) AS thMoney,                    --销售退货单中的税价合计
                    SUM(CASE WHEN b.BillType=215 THEN ISNULL(b.TaxTotal,0) ELSE 0 END ) AS lsthMoney,                 --零售退货单中的税价合计
                    SUM(CASE WHEN b.BillType=160 AND b.TaxTotal>0 THEN ISNULL(b.TaxTotal,0) ELSE 0 END ) AS rkMoney,  --销售换货单中入库数量的税价合计
                    SUM(CASE WHEN b.BillType=141 THEN ISNULL(b.TaxTotal,0) ELSE 0 END ) AS wtMoney,                    --委托代销单中的结算金额 
                    
                    SUM(CASE WHEN b.BillType IN(11,305,12) THEN ISNULL(b.NQty,0) ELSE 0 END ) AS ckNQty,                   --销售出库单中的销售数量
                    SUM(CASE WHEN b.BillType=160 AND b.NQty<0 THEN ISNULL(b.NQty,0) ELSE 0 END ) AS hhNQty,              --销售换货单中的出库数量
                    SUM(CASE WHEN b.BillType=141 THEN ISNULL(b.NQty,0) ELSE 0 END ) AS wtNQty,                          --委托代销单中的结算数量
                    SUM(CASE WHEN b.BillType in (45,46) THEN ISNULL(b.NQty,0) ELSE 0 END ) AS thNQty,                           --销售退货数量
                    SUM(CASE WHEN b.BillType=215 THEN ISNULL(b.NQty,0) ELSE 0 END ) AS lsthNQty,                        --零售退货数量
                    SUM(CASE WHEN b.BillType=160 AND b.NQty>0 THEN ISNULL(b.NQty,0) ELSE 0 END ) AS rkNQty              --销售换货单中的入库数量
      
               FROM   #GetManDealBTypeAll p
               LEFT JOIN #inoutstocktable b on p.typeid=LEFT(b.btypeid,LEN(p.typeid)) ' 
               --LEFT JOIN #GetManBTypeAll c ON C.typeid=LEFT(b.dealbtypeid,LEN(c.typeid))'
      --         IF @btypeid<>'00000'
			   --  BEGIN
      --               IF @SonNum=0
      --                  SET @SQL=@SQL+' WHERE c.typeid LIKE '+char(39)+@btypeid+'%'+char(39)
      --               ElSE 
						--BEGIN
						--	IF @btypeid=''
						--		SET @SQL=@SQL+' WHERE c.parid='+char(39)+'00000'+char(39)
						--	ELSE
						--		SET @SQL=@SQL+' WHERE c.parid='+char(39)+@btypeid+CHAR(39)
      --                  END
      --           END
      --         ELSE
      --            BEGIN
      --                SET @SQL=@SQL+' WHERE c.parid='+char(39)+@btypeid+CHAR(39)
      --            END 
                  
               IF @dealbtypeid<>'00000'
			     BEGIN
                     IF @SonNum=0
                        SET @SQL=@SQL+' where p.typeid LIKE '+char(39)+@dealbtypeid+'%'+char(39)
                     ElSE 
						BEGIN
							IF @dealbtypeid=''
								SET @SQL=@SQL+' where p.parid='+char(39)+'00000'+char(39)
							ELSE
								SET @SQL=@SQL+' where p.parid='+char(39)+@dealbtypeid+CHAR(39)
                        END
                 END
               ELSE
                  BEGIN
                      SET @SQL=@SQL+' where p.parid='+char(39)+@dealbtypeid+CHAR(39)
                  END
                   
               SET @SQL=@SQL+' GROUP BY p.typeid,p.usercode,p.sonnum ) a ORDER BY a.usercode'--,p.usercode
--PRINT @SQL
EXEC(@SQL)
DROP TABLE #GetManBTypeId,#GetManBTypeAll,#GetManDealBtypeId,#inoutstocktable,#Dtype,#Ktype,#Ptype,#Etype,#Stype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


























if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBtypeStatSellBackLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBtypeStatSellBackLine]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
    作者:张陈仁
	日期:2011-07-5
	描述:往来单位退货统计线性表
	
	
	修改：舒珊
    日期：2016-05-27
    描述： 添加商品类别筛选
    
    修改: 舒珊
	日期: 2016-07-12
	描述: 新增了【组合品销售出库单、组合品销售退货单】两张单据的统计

*/
CREATE PROCEDURE [dbo].[Web_QueryBtypeStatSellBackLine]
(
	@inputType		    char(1),		--  1、相应的统计报表功能识别参数
	@startDate		    varchar(30),	--  2、查询起始时间
	@endDate	        varchar(30),	--  3、查询结束时间
	@ptypeid		    varchar(1550),	--  4、商品类别查询范围父节点 ID
	@btypeid            VARCHAR(1550),	--结算单位
	@dealbtypeid		VARCHAR(1550),	--往来单位
	@etypeid		    varchar(1550),	--  6、职员类别查询范围父节点 ID
	@ktypeid		    varchar(1550),	--  7、仓库类别查询范围父节点 ID
    @dtypeid		    varchar(1550) , --  8、部门ID
	@atypeid            varchar(1550),  --  9、地区
	@intPageNo		    int = '',	    -- 10、当前查询的页码
	@intPageSize		int = '',		-- 11、每页的显示记录数
	@chvOperatorID		varchar(50),	-- 12、操作员 ID（作权限范围检查用）
	@chkRed             char(1) ='0',   -- 13. 是否显示红冲 
	@billType		    varchar(200),   -- 14. 单据类型
	@chrFlag		    char(1),		-- 15、功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@stypeid            varchar(1550),   --  16、分支机构查询范围父节点 ID
	@unitType			VARCHAR(1550),		--查询类型
	@ptypecategoryid    VARCHAR(MAX)				 --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON 

--

--------	权限检查 - Start	--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------

--------------查询类型判断---begin----------------
DECLARE @sqltemp VARCHAR(500)--定义查询语句
DECLARE @sqlunitType VARCHAR(200)---where条件语句
DECLARE @sqlRate VARCHAR(200)
IF @unitType='0'
	SET @sqlunitType=' P.SaleUnitId'
	SET @sqlRate='F.saleUnitRate'
IF @unitType='1'
	SET @sqlunitType=' P.BuyUnitId'
	SET @sqlRate='F.buyUnitRate'
IF @unitType='2'
	SET @sqlunitType=' P.StockUnitId'
	SET @sqlRate='F.stockUnitRate'
IF @unitType='3'
	SET @sqlunitType=' P.baseUnitId'
	SET @sqlRate='F.baseUnitRate'
------------查询类型判断---end---------------------



--结算往来
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
BEGIN
	INSERT INTO #GetManBTypeId(TypeId) SELECT typeid FROM F_GetManDetailBType(@chvOperatorID)
END


--往来单位
CREATE TABLE #GetManDealBtypeId(typeId VARCHAR(100))
IF @dealbtypeid<>'' OR @MBtypeid=-99999 OR @MBtypeid2=-99999
BEGIN
	INSERT INTO #GetManDealBtypeId(typeId) SELECT typeId FROM F_GetManDetailBType(@chvOperatorID)
END


--结算单位树型
CREATE TABLE #GetManBTypeAll
(
	TypeId	    varchar(1550),
	SonNum		INT,
	UserCode	VARCHAR(200),
	FullName	VARCHAR(200),
	Deleted		INT,
	ParId		VARCHAR(1550)
)
INSERT INTO #GetManBTypeAll
	   SELECT TypeId,
		      SonNum,
		      UserCode,
		      FullName,
		      Deleted,
		      ParId
        FROM  F_GetManBTypeAll(@chvOperatorID)
        
--往来单位树形
--CREATE TABLE #GetManDealBtypeAll
--(
--	TypeId	    varchar(1550),
--	SonNum		INT,
--	UserCode	VARCHAR(200),
--	FullName	VARCHAR(200),
--	Deleted		INT,
--	ParId		VARCHAR(1550)
--)
--INSERT INTO #GetManDealBTypeAll
--	   SELECT TypeId,
--		      SonNum,
--		      UserCode,
--		      FullName,
--		      Deleted,
--		      ParId
--        FROM  F_GetManBTypeAll(@chvOperatorID)

DECLARE @BTypeIdMx varchar(max),@CTypeIdMx VARCHAR(max)

IF @dealbtypeid='' OR @dealbtypeid='root' OR @dealbtypeid='00000'
   SET @BTypeIdMx='%'
ELSE
   SET @BTypeIdMx=@dealbtypeid
   
IF @btypeid='' OR @btypeid='root'
   SET @CTypeIdMx='%'
ELSE
   SET @CTypeIdMx=@btypeid
   

CREATE TABLE #Dtype (TypeID varchar(50))---部门
CREATE TABLE #Ktype (TypeID varchar(50))---仓库
CREATE TABLE #Ptype (TypeID varchar(50))---商品
CREATE TABLE #Etype (TypeID varchar(50))---职员
--CREATE TABLE #Atype (TypeID varchar(50))---地区
CREATE TABLE #Stype (TypeID varchar(50))---分支机构


IF @dtypeid<>'' OR @MDTypeID=-99999
BEGIN
	INSERT INTO #Dtype select typeid from F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)
END

IF @ktypeid<>'' OR @MKTypeID=-99999 
BEGIN
	INSERT INTO #Ktype select typeid from F_GetAllManagerBaseTypeId(@ktypeid,4,@chvOperatorID)
END
IF (@KTypeID='10000' OR  @KTypeID='' OR  @KTypeID='00000') AND NOT EXISTS(select * from #Ktype where typeid='10000') 
	insert into #Ktype select '10000'
	
IF @ptypeid<>'' OR @MPTypeID=-99999 OR @ptypecategoryid<>''
begin
	INSERT INTO #Ptype select typeid from F_ManPTypeInCategoryID ( @chvOperatorID,@ptypeid,@ptypecategoryid)
end	

IF @etypeid<>'' OR @METypeID=-99999 
BEGIN 
	INSERT INTO #Etype select typeid from F_GetAllManagerBaseTypeId(@etypeid,3,@chvOperatorID)
END 

--INSERT INTO #Atype select typeid from F_GetAllManagerBaseTypeId(@atypeid,10,@chvOperatorID)
IF NOT(@stypeid='' and @MStypeid='00000')
BEGIN 
	INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperatorID)
END


CREATE TABLE #inoutstocktable(
	BillNumberId numeric(10, 0),
	BillDate datetime,
	BillType numeric(4,0),
	PtypeId  varchar (1550),
	dealBtypeId  varchar (1550),
	EtypeId  varchar (1550),
	KtypeId  varchar (1550),
	AtypeId  varchar (1550),
	DtypeId  varchar (1550),
	Qty       NUMERIC(24, 10) ,
	nqty	  NUMERIC(24, 10) ,
	TaxTotal  NUMERIC(24, 10) ,
	NTaxTotal  NUMERIC(24, 10) ,
	unitfullname VARCHAR(50),
	baseunitfullname VARCHAR(50),
	Rate		 NUMERIC(24, 10) 
)

DECLARE @InsertSQL VARCHAR(max)

---搜索InoutStockTable---
SELECT @InsertSQL='INSERT INTO #inoutstocktable(
                                                 BillnumberID,
                                                 BillDate,
                                                 BillType,
                                                 PtypeId,
                                                 dealBtypeId,
                                                 EtypeId,
                                                 KtypeId,
                                                 AtypeId,
                                                 DtypeId,
                                                 Qty,
                                                 TaxTotal,
                                                 NQty
                                               )
                                        SELECT   I.BillnumberID,
                                                 I.BillDate,
                                                 I.BillType,
                                                 I.PtypeID,
                                                 i.BTypeID,
                                                 I.EtypeId,
                                                 I.KtypeId,
                                                 I.AtypeId,
                                                 I.DtypeId,
                                                 I.Qty,
                                                 I.TaxTotal,
                                                 I.NQty
                                        FROM   InoutStockTable I left JOIN BILLINDEX BI ON BI.BillNumberId=I.BillNumberId '
										IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
											SET @InsertSQL=@InsertSQL+' INNER JOIN #GetManBTypeId bt ON bi.btypeid=bt.typeid '+CHAR(13)
										IF @dealbtypeid<>'' OR @MBtypeid=-99999 OR @MBtypeid2=-99999
											SET @InsertSQL=@InsertSQL+'INNER JOIN #GetManDealBtypeId dbt ON BI.DealBTypeID=dbt.typeid'+CHAR(13)
										IF @ptypeid<>'' OR @MPTypeID=-99999 OR @ptypecategoryid<>''
											SET @InsertSQL=@InsertSQL+' INNER JOIN #Ptype p ON I.ptypeid=p.typeid '+CHAR(13)
										IF @dtypeid<>'' OR @MDTypeID=-99999
											SET @InsertSQL=@InsertSQL+' INNER JOIN #Dtype d  ON  I.DtypeID=d.typeid '+CHAR(13)	
										IF @ktypeid<>'' OR @MKTypeID=-99999 
											SET @InsertSQL=@InsertSQL+'	INNER JOIN #Ktype k ON I.ktypeid=k.typeid '+CHAR(13)
										IF @etypeid<>'' OR @METypeID=-99999 
											SET @InsertSQL=@InsertSQL+' INNER JOIN #Etype e  ON I.etypeid=e.typeid '+CHAR(13)
										IF NOT(@stypeid='' and @MStypeid='00000')
											SET @InsertSQL=@InsertSQL+' INNER JOIN #Stype s  ON  I.stypeID=s.typeid '+CHAR(13)
                                        SET @InsertSQL=@InsertSQL+' WHERE I.BillType IN('+@billType+') 
                                                                          AND I.BillDate>='+CHAR(39)+@startDate+CHAR(39)+' 
                                                                          AND I.BillDate<='+CHAR(39)+@endDate+CHAR(39)+' 
                                                                          AND BI.BillDate>='+CHAR(39)+@startDate+CHAR(39)+' 
                                                                          AND BI.BillDate<='+CHAR(39)+@endDate+CHAR(39)+' 
                                                                          AND I.Audited=1 
                                                                          AND BI.DealBTypeID LIKE '''+@BTypeIdMx+'%'' 
                                                                          AND BI.BtypeId Like '''+@cTypeIdMx+'%''
                                                                          '
                                                                          --PRINT @InsertSQL
EXEC(@InsertSQL)
DECLARE @SQL varchar(MAX)---主体SQL

SET @SQL='SELECT 
                a.dealbtypeid,
                a.usercode,
                (ABS(a.ckQty)+ABS(a.hhQty)+ABS(a.wtQty)-abs(a.thQty)-abs(rkQty)) AS qty,
                ABS(a.ckNQty)+ABS(a.hhNQty)+ABS(a.wtNQty)-a.thNQty-rkNQty AS nqty,
                ABS(a.ckMoney)+ABS(a.hhMoney)+ABS(a.wtMoney)-a.thMoney-a.rkMoney AS taxtotal,
                ABS(a.ckQty)+ABS(a.hhQty)+ABS(a.wtQty) AS outqty,
                a.thQty+a.rkQty AS backqty,
                ABS(a.ckMoney)+ABS(a.hhMoney)+ABS(a.wtMoney) AS outmoney,
                a.thMoney+rkMoney AS backmoney,
                CASE WHEN ABS(a.ckQty)+ABS(a.hhQty)=0 THEN 0 ELSE cast((a.thQty+a.rkQty)as NUMERIC(24, 10))/cast((ABS(a.ckQty)+ABS(a.hhQty)+ABS(a.wtQty))as NUMERIC(24, 10))*100 END AS outLv
          FROM
             (
               SELECT p.typeid as dealbtypeid,
					  p.usercode AS usercode, 
					  SUM(ISNULL(b.ckQty,0)) AS ckQty,            --销售出库单中的销售数量
					  SUM(ISNULL(b.hhQty,0)) AS hhQty,            --销售换货单中的出库数量
					  SUM(ISNULL(b.wtQty,0)) AS wtQty,            --委托代销单中的结算数量
					  SUM(ISNULL(b.thQty,0)) AS thQty,            --销售退货数量
					  SUM(ISNULL(b.rkQty,0)) AS rkQty,            --销售换货单中的入库数量
					  SUM(ISNULL(b.ckMoney,0)) AS ckMoney,        --销售出库单中的税价合计
					  SUM(ISNULL(b.hhMoney,0)) AS hhMoney,        --销售换货单中出库数量的税价合计
					  SUM(ISNULL(b.thMoney,0)) AS thMoney,        --销售退货单中的税价合计
					  SUM(ISNULL(b.rkMoney,0)) AS rkMoney,        --销售换货单中入库数量的税价合计
					  SUM(ISNULL(b.wtMoney,0)) AS wtMoney,         --委托代销单中的结算金额 
					  
					  SUM(ISNULL(b.ckNQty,0)) AS ckNQty,		   --销售出库单中的浮动单位销售数量
					   SUM(ISNULL(b.hhNQty,0)) AS hhNQty,          --销售换货单中的浮动单位出库数量
					   SUM(ISNULL(b.wtNQty,0)) AS wtNQty,          --委托代销单中的浮动单位结算数量
					   SUM(ISNULL(b.thNQty,0)) AS thNQty,          --销售浮动单位退货数量
					   SUM(ISNULL(b.rkNQty,0)) AS rkNQty,           --销售换货单中的浮动单位入库数量
						b.Rate
               FROM   #GetManBTypeAll p
               LEFT JOIN (	
							SELECT  dealBtypeId,
									SUM(ISNULL(Qty,0)) AS ckQty,
									SUM(ISNULL(NQty,0)) AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									0 AS ckMoney,
									0 AS hhMoney,
									0 AS thMoney,
									0 AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType IN (11,305,12) GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									SUM(ISNULL(Qty,0)) AS hhQty,
									SUM(ISNULL(NQty,0)) AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									0 AS ckMoney,
									0 AS hhMoney,
									0 AS thMoney,
									0 AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType=160 AND Qty<0 GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL 
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									SUM(ISNULL(Qty,0)) AS wtQty,
									SUM(ISNULL(NQty,0)) AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									0 AS ckMoney,
									0 AS hhMoney,
									0 AS thMoney,
									0 AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType=141 GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL 
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									SUM(ISNULL(Qty,0)) AS thQty,
									SUM(ISNULL(NQty,0)) AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									0 AS ckMoney,
									0 AS hhMoney,
									0 AS thMoney,
									0 AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType IN (45,215,46) GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL 
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									SUM(ISNULL(Qty,0)) AS rkQty,
									SUM(ISNULL(NQty,0)) AS rkNQty,
									0 AS ckMoney,
									0 AS hhMoney,
									0 AS thMoney,
									0 AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType=160 AND Qty>0 GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									SUM(ISNULL(TaxTotal,0)) AS ckMoney,
									0 AS hhMoney,
									0 AS thMoney,
									0 AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType IN(11,305,12) GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									0 AS ckMoney,
									SUM(ISNULL(TaxTotal,0)) AS hhMoney,
									0 AS thMoney,
									0 AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType=160 AND TaxTotal<0 GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									0 AS ckMoney,
									0 AS hhMoney,
									SUM(ISNULL(TaxTotal,0)) AS thMoney,
									0 AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType IN (45,215,46) GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									0 AS ckMoney,
									0 AS hhMoney,
									0 AS thMoney,
									SUM(ISNULL(TaxTotal,0)) AS rkMoney,
									0 AS wtMoney,
									Rate 
							FROM #inoutstocktable WHERE BillType=160 AND TaxTotal>0 GROUP BY dealBtypeId,unitfullname,baseunitfullname,Rate
							UNION ALL
							SELECT dealBtypeId,
									0 AS ckQty,
									0 AS ckNQty,
									0 AS hhQty,
									0 AS hhNQty,
									0 AS wtQty,
									0 AS wtNQty,
									0 AS thQty,
									0 AS thNQty,
									0 AS rkQty,
									0 AS rkNQty,
									0 AS ckMoney,
									0 AS hhMoney,
									0 AS thMoney,
									0 AS rkMoney,
									SUM(ISNULL(TaxTotal,0)) AS wtMoney,
									Rate
							FROM #inoutstocktable WHERE BillType=141 GROUP BY dealBtypeId,--unitfullname,baseunitfullname,
							Rate                          
                          ) b ON p.typeid=b.dealbtypeid 
			   WHERE b.ckQty<>0 
				     OR b.hhQty<>0 
				     OR b.thQty<>0 
				     OR b.rkQty<>0 
				     OR b.wtQty<>0
				     OR b.ckMoney<>0 
				     OR b.hhMoney<>0 
				     OR b.thMoney<>0 
				     OR b.rkMoney<>0 
				     OR b.wtMoney<>0  
			    '
               IF @dealbtypeid<>'00000'
			       SET @SQL=@SQL+' AND p.typeid LIKE '+char(39)+@dealbtypeid+'%'+char(39)
			   ELSE 
			       SET @SQL=@SQL+' AND p.parid <> '+char(39)+@dealbtypeid+''+char(39)
               SET @SQL=@SQL+' GROUP BY p.typeid,p.usercode,--b.unitfullname,b.baseunitfullname,
               b.Rate  
             ) a ORDER BY a.usercode'
--PRINT @SQL
EXEC(@SQL)

DROP TABLE #GetManBTypeId,#GetManBTypeAll,#inoutstocktable,#Dtype,#Ktype,#Ptype,#Etype,#Stype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryBussinesDetailsList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryBussinesDetailsList
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	业务单据列表
-- 时间：	2013-08-12
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryBussinesDetailsList
(
	@StypeID			VARCHAR(50)='',		--分支机构ID
	@AtypeID			VARCHAR(50)='',		--科目ID
	@FYear				INT=0,				--年度
	@IsSelected			INT=0,				--期间 / 时间  选择  0：期间 1:时间
	@FBegin				INT=0,				--开始期间
	@FEnd				INT=0,				--结束期间
	@StartDate			VARCHAR(50),		--开始时间
	@EndDate			VARCHAR(50),		--结束时间 
	@OperatorID			VARCHAR(50),		--当前操作员
	@OrderBy			VARCHAR(50),		--排序字段
	@Type				INT,				--1:得到列表  2：得到期初
	@total				 NUMERIC(24, 10)  OUTPUT--当前科目期初
)

--@encode$--
AS
SET NOCOUNT ON 
----------------------------------------权限检查[BEGIN]-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN
DECLARE 
	@Re INT,
	@MAtypeid VARCHAR(50),
	@MBtypeid VARCHAR(50),
	@MBtypeid2 VARCHAR(50), 
	@MEtypeid VARCHAR(50),
	@MKtypeid VARCHAR(50), 
	@MPtypeid VARCHAR(50), 
	@MExpense VARCHAR(50), 
	@MIncome VARCHAR(50),
	@MCapital VARCHAR(50),
	@MDtypeid VARCHAR(50),
	@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep 
		@OperatorID,
		@MAtypeid OUTPUT,
		@MBtypeid OUTPUT,
		@MBtypeid2 OUTPUT,
		@MEtypeid OUTPUT,
		@MKtypeid OUTPUT,
		@MPtypeid OUTPUT,
		@MExpense OUTPUT,
		@MIncome OUTPUT,
		@MCapital OUTPUT,
		@MDtypeid OUTPUT,
		@MStypeid OUTPUT

IF @Re<>0 RETURN
----------------------------------------------权限检查[END]-------------------------------------------------------
CREATE TABLE #Stype(TypeID VARCHAR(50),FullName VARCHAR(66))
INSERT INTO #Stype(TypeID,FullName)
SELECT TypeId,FullName FROM SType WHERE VerifyID=@StypeID
--选择时间 得到相应时间的期间
 IF(@IsSelected=0)--选择期间 得到相应期间的时间
	BEGIN
		SELECT @StartDate=CONVERT(VARCHAR(10),FBegin,120) FROM Ac_Period WHERE FYear=@FYear AND FPeriod=@FBegin
		SELECT @EndDate=CONVERT(VARCHAR(10),FEnd,120) FROM Ac_Period WHERE FYear=@FYear AND FPeriod=@FEnd
	END
ELSE IF(@IsSelected=1)
	BEGIN
		SELECT @FBegin=FPeriod FROM Ac_Period WHERE @StartDate BETWEEN FBegin AND FEnd 
		SELECT @FEnd=FPeriod FROM Ac_Period WHERE @EndDate BETWEEN FBegin AND FEnd
	END
IF @Type=1 AND EXISTS(SELECT TOP 1 1 FROM Ac_FixedAssetsInit_Stype WHERE StypeId=@StypeID)
	BEGIN
		DECLARE @SQL VARCHAR(MAX)=''
		SET @SQL+='SELECT 
			H.BillId BillNumberID,
			A.Id CardID,
			H.BillType,
			CASE WHEN H.AuditType<0 THEN ''初始化''
				ELSE (SELECT TOP 1 FullName  FROM Ac_AssetBusinessType WHERE id=H.BusinessTypeId)
			END AS busstypefname,
			H.InAccountDate billdate,
			A.UserCode billcode,
			H.STypeId,
			H.ETypeId,
			S.FullName SFullName,
			E.FullName EFullName,
			CASE 
				WHEN H.AssertATypeId='''+@AtypeID+''' THEN H.Total
				WHEN H.DepATypeId='''+@AtypeID+'''THEN H.DepTotal
				WHEN H.DevalueATypeId='''+@AtypeID+''' THEN H.DevalueReady
				ELSE 0
			END lttotal,
			0.00 jetotal,
			H.Comment
		FROM Ac_AssetsCards_History H
		INNER JOIN  Ac_AssetsCards A ON A.Id=H.AssertsCardId
		INNER JOIN #Stype S ON S.TypeId=A.STypeId
		INNER JOIN employee E ON E.typeId=H.ETypeId
		WHERE 
			H.BillType<>213
			AND H.BusinessDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			AND (H.AssertATypeId='''+@AtypeID+'''
			OR H.DepATypeId='''+@AtypeID+'''
			OR H.DevalueATypeId='''+@AtypeID+''')
			AND H.Id IN(
						SELECT 
							MAX(Id) ID
						FROM Ac_AssetsCards_History H
						INNER JOIN #Stype S ON S.TypeID=H.StypeID
						WHERE 
							BusinessDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
						GROUP BY AssertsCardId
			)'+CHAR(13)

		-- 排序
		IF  ISNULL(@OrderBy,'')='' OR @OrderBy ='InAccountDate_a'
			SET @SQL+=  ' Order By H.InAccountDate ASC'
		IF @OrderBy ='InAccountDate_d'
			SET @SQL+= ' Order By H.InAccountDate DESC'
		IF @OrderBy ='UserCode_a'
			SET @SQL+=  ' Order By A.UserCode ASC'
		IF @OrderBy ='UserCode_d'
			SET @SQL+= ' Order By A.UserCode DESC'
		EXEC(@SQL)
	END
ELSE 
	SELECT 
			H.BillId BillNumberID,
			H.AssertsCardId CardID,
			H.BillType,
			CASE WHEN H.AuditType<0 THEN '初始化'
				ELSE (SELECT TOP 1 FullName  FROM Ac_AssetBusinessType WHERE id=H.BusinessTypeId)
			END AS busstypefname,
			H.InAccountDate billdate,
			'' billcode,
			H.STypeId,
			H.ETypeId,
			'' SFullName,
			'' EFullName,
			CASE 
				WHEN H.AssertATypeId=@AtypeID THEN H.Total
				WHEN H.DepATypeId=@AtypeID THEN H.DepTotal
				WHEN H.DevalueATypeId=@AtypeID THEN H.DevalueReady
				ELSE 0
			END lttotal,
			0.00 jetotal,
			H.Comment
		FROM Ac_AssetsCards_History H
		WHERE H.Id=-1
		
--固定资产未初始化时
IF NOT EXISTS(SELECT TOP 1 1 FROM Ac_FixedAssetsInit_Stype WHERE StypeId=@StypeID)
	BEGIN
		SELECT @total+=ISNULL(SUM(ISNULL(Total,0)),0)
		FROM Ac_AssetsCards C
		INNER JOIN #Stype S ON S.TypeID=C.STypeId AND C.AssertATypeId=@AtypeID AND C.AssetsState IN(1,4)
		
		SELECT @total+=ISNULL(SUM(ISNULL(DepTotal,0)),0)
		FROM Ac_AssetsCards C
		INNER JOIN #Stype S ON S.TypeID=C.STypeId AND C.DepATypeId=@AtypeID AND C.AssetsState IN(1,4)
		
		SELECT @total+=ISNULL(SUM(ISNULL(DevalueReady,0)),0)
		FROM Ac_AssetsCards C
		INNER JOIN #Stype S ON S.TypeID=C.STypeId AND C.DisATypeId=@AtypeID AND C.AssetsState IN(1,4)
		
	END
ELSE 
	BEGIN
		SELECT
		 @total+=ISNULL(SUM(ISNULL(Total,0)),0)
		FROM Ac_AssetsCards_History H
		INNER JOIN #Stype S ON S.TypeID=H.STypeId
		WHERE H.AssertATypeId=@AtypeID
			AND Id IN
			(
				SELECT 
					MAX(Id) ID
				FROM Ac_AssetsCards_History H
				INNER JOIN #Stype S ON S.TypeID=H.STypeId
				WHERE 
					BusinessDate<@StartDate
				GROUP BY AssertsCardId
		)
		AND H.BillType<>213
		
		SELECT
		 @total+=ISNULL(SUM(ISNULL(DepTotal,0)),0)
		FROM Ac_AssetsCards_History H
		INNER JOIN #Stype S ON S.TypeID=H.STypeId
		WHERE 
			DepATypeId=@AtypeID
			AND Id IN
			(
				SELECT 
					MAX(Id) ID
				FROM Ac_AssetsCards_History H
				INNER JOIN #Stype S ON S.TypeID=H.STypeId
				WHERE 
					BusinessDate<@StartDate
				GROUP BY AssertsCardId
		)
		AND H.BillType<>213
		SELECT
		 @total+=ISNULL(SUM(ISNULL(DevalueReady,0)),0)
		FROM Ac_AssetsCards_History H
		INNER JOIN #Stype S ON S.TypeID=H.STypeId
		WHERE 
			DevalueATypeId=@AtypeID
			AND Id IN
			(
				SELECT 
					MAX(Id) ID
				FROM Ac_AssetsCards_History H
				INNER JOIN #Stype S ON S.TypeID=H.STypeId
				WHERE 
					BusinessDate<@StartDate
				GROUP BY AssertsCardId
			)	
			AND H.BillType<>213
END	


DROP TABLE #Stype
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_QueryBuyAppraisalCXDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryBuyAppraisalCXDetail]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:杨俊
	日期:2015-06-02
	描述:采购暂估统计明细表
*/

/*
  修改： 魏伟
  日期： 2016-06-07
  描述： 添加 换算率变更前采购单位数量 查询

*/
CREATE PROCEDURE Web_QueryBuyAppraisalCXDetail
(
	@startdate		    VARCHAR(30),	--查询起始时间
	@enddate			VARCHAR(30),	--查询结束时间
	@parid	           	VARCHAR(50),	--父节点ID
	@stypeid            VARCHAR(MAX),	--分支机构ID
	@ptypeid			VARCHAR(MAX),	--商品ID
	@dealtypeid			VARCHAR(MAX),	--结算单位ID
	@btypeid			VARCHAR(MAX),	--往来单位ID
	@etypeid			VARCHAR(MAX),	--经手人ID
	@ktypeid			VARCHAR(MAX),	--仓库ID
	@dtypeid			VARCHAR(MAX),	--部门ID
	@billType			VARCHAR(20),	--单据类型
	@Comment			VARCHAR(200),	--摘要
	@Explain			VARCHAR(200),	--说明
	@statisticstype		INT,			--统计方式
	@chvOperatorID		VARCHAR(50)		--操作员ID
)
--@encode$--
AS
--------权限检查 - Start--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------权限检查 - END--------
IF(@parid <> '' OR @parid <> '00000')
BEGIN
	IF(@statisticstype = 0)
		SET @ptypeid = @parid
	ELSE
		SET @btypeid = @parid
END

--分支机构
CREATE TABLE #Stype
(
	STypeID VARCHAR(50)
)
IF (@stypeid <> '')
	INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperatorID)
	
--商品
CREATE TABLE #Ptype
(
	PTypeID VARCHAR(50)
)
IF (@ptypeid <> '')
	INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ptypeid,20,@chvOperatorID)

--结算单位
CREATE TABLE #dealtypeid
(
	DealTypeID VARCHAR(50)
)
IF(@dealtypeid <> '')
	INSERT INTO #dealtypeid SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealtypeid,2,@chvOperatorID)

--往来单位
CREATE TABLE #Btype
(
	BTypeID VARCHAR(50)
)
IF (@btypeid <> '')
	INSERT INTO #Btype SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@chvOperatorID)

--经手人
CREATE TABLE #Etype
(
	ETypeID VARCHAR(50)
)
IF (@etypeid <> '')
	INSERT INTO #Etype SELECT typeid FROM F_GetAllManagerBaseTypeId(@etypeid,3,@chvOperatorID)

--仓库
CREATE TABLE #Ktype
(
	KTypeID VARCHAR(50)
)
IF (@ktypeid <> '')
	INSERT INTO #Ktype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@chvOperatorID)
	
--部门
CREATE TABLE #Dtype
(
	DTypeID VARCHAR(50)
)
IF (@dtypeid <> '')
	INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)

--单据类型
CREATE TABLE #BillType
(
	billtype NUMERIC(4, 0)
)
--最近使用的换算率
--CREATE TABLE #Rate
--(
--	ptypeid VARCHAR(50),
--	rate numeric(24, 10),
--	unitid int
--)
--INSERT INTO #Rate
--        (unitid ,ptypeid,rate)
--SELECT   pt.UnitId ,pt.PtypeId ,TranslateRate FROM dbo.PType_TranslateRates pt INNER JOIN dbo.F_BaseGetAllManagerBaseTypeId(@PTypeID,1,@chvOperatorID) f ON f.TypeId=PtypeId   INNER JOIN (SELECT PtypeId,UnitId, MAX(LastUseDate)AS LastUseDate FROM PType_TranslateRates GROUP BY PtypeId,UnitId) t ON pt.PtypeId=t.PtypeId AND  pt.LastUseDate=t.LastUseDate  AND pt.UnitId=t.UnitId INNER JOIN dbo.ptype p ON p.typeId=pt.PtypeId AND pt.UnitId=p.BuyUnitId
INSERT INTO #BillType(billtype)
SELECT A FROM F_Split(@billType,',')

SELECT 
*
FROM
(
	SELECT 
	B.BillNumberId,
	B.BillCode,
	B.posttime,
	B.Stypeid,
	A.PtypeId,
	B.DealBTypeID,
	B.Btypeid,
	B.etypeid,
	B.KTypeID,
	B.DTypeId,
	B.comment,
	B.explain,
	B.BillDate,
	B.BillType,
	(SELECT FullName FROM dbo.Ac_Currency WHERE CId = B.CID) AS cid,
	B.rate,
	B.rate AS ratename,
	(SELECT BillName FROM dbo.BillName WHERE Billtype = B.BillType) AS BillTypeName,
	PU.FullName AS baseunitfullname,
	--(SELECT FullName FROM PType_Units WHERE UnitsId = A.NUnitID) AS munitfullname,
	PU1.FullName AS munitfullname,
	A.Qty,
	A.MQty AS munitqty,
    A.MQty AS munitbrcqty,
	A.total,
	A.ntotal,
	A.InvoiceQty,
	A.InvoiceMoneyEX,
	A.DiscountPrice,
	A.NDiscountPrice,
	A.TaxTotal,
	A.NTaxTotal,
	A.TaxMoney,
	A.NTaxMoney,
	SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
	FROM AppraisalBill AS A
	INNER JOIN dbo.BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
	INNER JOIN dbo.ptype AS P ON(A.PtypeId = P.typeId)
	--LEFT JOIN #Rate AS  r ON (r.PtypeID = A.PtypeId )  
	INNER JOIN dbo.PType_Units AS PU ON(P.baseUnitId = PU.UnitsId)
	LEFT JOIN PType_Units AS PU1 ON(A.MUnitID = PU1.UnitsId)
left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
left join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND a.ID=csdetail.Detailid
	WHERE B.draft = 0
		AND B.ifYearBill = 0
		AND B.RedWord = 0
		AND B.IsIni = 0 
		
	UNION ALL
	
	SELECT 
	B.BillNumberId,
	B.BillCode,
	B.posttime,
	B.Stypeid,
	A.PtypeId,
	B.DealBTypeID,
	B.Btypeid,
	B.etypeid,
	B.KTypeID,
	B.DTypeId,
	B.comment,
	B.explain,
	B.BillDate,
	B.BillType,
	(SELECT FullName FROM dbo.Ac_Currency WHERE CId = B.CID) AS cid,
	B.rate,
	B.rate AS ratename,
	(SELECT BillName FROM dbo.BillName WHERE Billtype = B.BillType) AS BillTypeName,
	PU.FullName AS baseunitfullname,
	--(SELECT FullName FROM PType_Units WHERE UnitsId = A.NUnitID) AS munitfullname,
	PU1.FullName AS munitfullname,
	-A.Qty AS Qty,
	-A.MQty AS munitqty,
	-A.Qty/pe.rate AS munitbrcqty,
	-A.total AS total,
	-A.ntotal AS ntotal,
	-A.InvoiceQty AS InvoiceQty,
	-A.InvoiceMoneyEX AS InvoiceMoneyEX,
	A.DiscountPrice,
	A.NDiscountPrice,
	-A.TaxTotal AS TaxTotal,
	-A.NTaxTotal AS NTaxTotal,
	-A.TaxMoney AS TaxMoney,
	-A.NTaxMoney as NTaxMoney,
SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
	FROM AppraisalBackBill AS A
	INNER JOIN dbo.BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
	INNER JOIN dbo.ptype AS P ON(A.PtypeId = P.typeId)
	--LEFT JOIN #Rate AS  r ON (r.PtypeID = A.PtypeId )  
	LEFT JOIN PType_Units_Ext AS pe on (A.PtypeId = pe.PtypeId AND A.MUnitID = pe.UnitsId)
	INNER JOIN dbo.PType_Units AS PU ON(P.baseUnitId = PU.UnitsId)
	LEFT JOIN PType_Units AS PU1 ON(A.MUnitID = PU1.UnitsId)
	 left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
left join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND a.ID=csdetail.Detailid
	WHERE B.draft = 0
		AND B.ifYearBill = 0
		AND B.RedWord = 0
		AND B.IsIni = 0 
) AS T
WHERE T.BillDate BETWEEN @startdate AND @enddate
	AND T.BillType IN(SELECT billtype FROM #BillType)
	AND (NOT(@stypeid <> '') 
	OR (@stypeid <> '') AND T.Stypeid IN(SELECT STypeID FROM #Stype))
	AND (NOT(@ptypeid <> '') 
	OR (@ptypeid <> '') AND T.Ptypeid IN(SELECT PTypeID FROM #Ptype))
	AND (NOT(@dealtypeid <> '') 
	OR (@dealtypeid <> '') AND T.DealBTypeID IN(SELECT DealBTypeID FROM #dealtypeid))
	AND (NOT(@btypeid <> '') 
	OR (@btypeid <> '') AND T.Btypeid IN(SELECT BTypeID FROM #Btype))
	AND (NOT(@etypeid <> '') 
	OR (@etypeid <> '') AND T.Etypeid IN(SELECT ETypeID FROM #Etype))
	AND (NOT(@ktypeid <> '') 
	OR (@ktypeid <> '') AND T.Ktypeid IN(SELECT KTypeID FROM #Ktype))
	AND (NOT(@dtypeid <> '') 
	OR (@dtypeid <> '') AND T.Dtypeid IN(SELECT DTypeID FROM #Dtype))
	AND (NOT(@Comment <> '') 
	OR (@Comment <> '') AND T.Comment LIKE '%' + @Comment + '%')
	AND (NOT(@Explain <> '') 
	OR (@Explain <> '') AND T.explain LIKE '%' + @Explain + '%')
ORDER BY T.BillDate
--------------------------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_QueryBuyAppraisalCXLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryBuyAppraisalCXLine]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:杨俊
	日期:2015-06-01
	描述:采购暂估统计线性表
*/
CREATE PROCEDURE Web_QueryBuyAppraisalCXLine
(
	@startdate		    VARCHAR(30),		--查询起始时间
	@enddate			VARCHAR(30),		--查询结束时间
	@parid	           	VARCHAR(50),		--父节点ID
	@stypeid            VARCHAR(MAX),		--分支机构ID
	@ptypeid			VARCHAR(MAX),		--商品ID
	@dealtypeid			VARCHAR(MAX),		--结算单位ID
	@btypeid			VARCHAR(MAX),		--往来单位ID
	@etypeid			VARCHAR(MAX),		--经手人ID
	@ktypeid			VARCHAR(MAX),		--仓库ID
	@dtypeid			VARCHAR(MAX),		--部门ID
	@billType			VARCHAR(20),		--单据类型
	@Comment			VARCHAR(200),		--摘要
	@Explain			VARCHAR(200),		--说明
	@statisticstype		INT,				--统计方式
	@usercode			VARCHAR(200),		--筛选单据-编码
	@fullname			VARCHAR(200),		--筛选单据-名称
	@chvOperatorID		VARCHAR(50)			--操作员ID
)
--@encode$--
AS
--------权限检查 - Start--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------权限检查 - END--------
IF(@parid <> '' OR @parid <> '00000')
BEGIN
	IF(@statisticstype = 0)
		SET @ptypeid = @parid
	ELSE
		SET @btypeid = @parid
END

--分支机构
CREATE TABLE #Stype
(
	STypeID VARCHAR(50)
)
IF (@stypeid <> '')
	INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperatorID)
	
--商品
CREATE TABLE #Ptype
(
	PTypeID VARCHAR(50)
)
IF (@ptypeid <> '')
	INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ptypeid,20,@chvOperatorID)

--结算单位
CREATE TABLE #dealtypeid
(
	DealTypeID VARCHAR(50)
)
IF(@dealtypeid <> '')
	INSERT INTO #dealtypeid SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealtypeid,2,@chvOperatorID)

--往来单位
CREATE TABLE #Btype
(
	BTypeID VARCHAR(50)
)
IF (@btypeid <> '')
	INSERT INTO #Btype SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@chvOperatorID)

--经手人
CREATE TABLE #Etype
(
	ETypeID VARCHAR(50)
)
IF (@etypeid <> '')
	INSERT INTO #Etype SELECT typeid FROM F_GetAllManagerBaseTypeId(@etypeid,3,@chvOperatorID)

--仓库
CREATE TABLE #Ktype
(
	KTypeID VARCHAR(50)
)
IF (@ktypeid <> '')
	INSERT INTO #Ktype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@chvOperatorID)
	
--部门
CREATE TABLE #Dtype
(
	DTypeID VARCHAR(50)
)
IF (@dtypeid <> '')
	INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)

--单据类型
CREATE TABLE #BillType
(
	billtype NUMERIC(4, 0)
)
INSERT INTO #BillType(billtype)
SELECT A FROM F_Split(@billType,',')

--#Temp
CREATE TABLE #Temp
(
	Stypeid VARCHAR(200),
	PtypeId VARCHAR(200),
	PUserCode VARCHAR(200),
	PFullName VARCHAR(200),
	DealBTypeID VARCHAR(200),
	Btypeid VARCHAR(200),
	BUserCode VARCHAR(200),
	BFullName VARCHAR(200),
	etypeid VARCHAR(200),
	KTypeID VARCHAR(200),
	DTypeId VARCHAR(200),
	comment VARCHAR(500),
	explain VARCHAR(500),
	BillDate DATETIME,
	BillType NUMERIC(4, 0),
	Qty  NUMERIC(24, 10) ,
	total  NUMERIC(24, 10) ,
	InvoiceQty  NUMERIC(24, 10) ,
	InvoiceMoneyEX  NUMERIC(24, 10) ,
	InvoiceMoney  NUMERIC(24, 10) ,
	wkpqty  NUMERIC(24, 10) 
)
INSERT INTO #Temp
SELECT * 
FROM
(
	SELECT 
	A.Stypeid,
	A.PtypeId,
	(SELECT UserCode FROM dbo.ptype WHERE typeId = A.PtypeId) AS PUserCode,
	(SELECT FullName FROM dbo.ptype WHERE typeId = A.PtypeId) AS PFullName,
	B.DealBTypeID,
	B.Btypeid,
	(SELECT UserCode FROM dbo.btype WHERE typeId = B.Btypeid) AS BUserCode,
	(SELECT FullName FROM dbo.btype WHERE typeId = B.Btypeid) AS BFullName,
	B.etypeid,
	A.KTypeID,
	B.DTypeId,
	B.comment,
	B.explain,
	B.BillDate,
	B.BillType,
	A.Qty,A.total,A.InvoiceQty,A.InvoiceMoneyEX,A.InvoiceMoney,A.Qty - A.InvoiceQty AS wkpqty 
	FROM AppraisalBill AS A
	INNER JOIN dbo.BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
	WHERE B.draft = 0
		AND B.ifYearBill = 0
		AND B.RedWord = 0
		AND B.IsIni = 0
		
	UNION ALL
	
	SELECT 
	A.Stypeid,
	A.PtypeId,
	(SELECT UserCode FROM dbo.ptype WHERE typeId = A.PtypeId) AS PUserCode,
	(SELECT FullName FROM dbo.ptype WHERE typeId = A.PtypeId) AS PFullName,
	B.DealBTypeID,
	B.Btypeid,
	(SELECT UserCode FROM dbo.btype WHERE typeId = B.Btypeid) AS BUserCode,
	(SELECT FullName FROM dbo.btype WHERE typeId = B.Btypeid) AS BFullName,
	B.etypeid,
	A.KTypeID,
	B.DTypeId,
	B.comment,
	B.explain,
	B.BillDate,
	B.BillType,
	-A.Qty AS Qty,-A.total AS total,-A.InvoiceQty AS InvoiceQty,-A.InvoiceMoneyEX AS InvoiceMoneyEX,-A.InvoiceMoney AS InvoiceMoney,-(A.Qty - A.InvoiceQty) AS wkpqty 
	FROM AppraisalBackBill AS A
	INNER JOIN dbo.BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
	WHERE B.draft = 0
		AND B.ifYearBill = 0
		AND B.RedWord = 0
		AND B.IsIni = 0
) AS T
WHERE T.BillDate BETWEEN @startdate AND @enddate
	AND T.BillType IN(SELECT billtype FROM #BillType)
	AND (NOT(@stypeid <> '') 
	OR (@stypeid <> '') AND T.Stypeid IN(SELECT STypeID FROM #Stype))
	AND (NOT(@ptypeid <> '') 
	OR (@ptypeid <> '') AND T.Ptypeid IN(SELECT PTypeID FROM #Ptype))
	AND (NOT(@dealtypeid <> '') 
	OR (@dealtypeid <> '') AND T.DealBTypeID IN(SELECT DealBTypeID FROM #dealtypeid))
	AND (NOT(@btypeid <> '') 
	OR (@btypeid <> '') AND T.Btypeid IN(SELECT BTypeID FROM #Btype))
	AND (NOT(@etypeid <> '') 
	OR (@etypeid <> '') AND T.Etypeid IN(SELECT ETypeID FROM #Etype))
	AND (NOT(@ktypeid <> '') 
	OR (@ktypeid <> '') AND T.Ktypeid IN(SELECT KTypeID FROM #Ktype))
	AND (NOT(@dtypeid <> '') 
	OR (@dtypeid <> '') AND T.Dtypeid IN(SELECT DTypeID FROM #Dtype))
	AND (NOT(@Comment <> '') 
	OR (@Comment <> '') AND T.Comment LIKE '%' + @Comment + '%')
	AND (NOT(@Explain <> '') 
	OR (@Explain <> '') AND T.explain LIKE '%' + @Explain + '%')

--最终数据
IF(@statisticstype = 0)
BEGIN
	SELECT
	T.PtypeId AS typeId,
	T.PUserCode AS usercode,
	T.PFullName AS fullname,
	(
		SELECT FullName FROM dbo.PType_Units WHERE UnitsId = (SELECT baseUnitId FROM dbo.ptype WHERE typeId = T.PtypeId)
	) AS unitname,
	ISNULL(SUM(T.Qty),0) AS Qty,
	ISNULL(SUM(T.total),0) AS total,
	ISNULL(SUM(T.InvoiceQty),0) AS InvoiceQty,
	ISNULL(SUM(T.InvoiceMoneyEX),0) AS InvoiceMoneyEX,
	ISNULL(SUM(T.InvoiceMoney),0) AS InvoiceMoney,
	ISNULL(SUM(T.wkpqty),0) AS wkpqty
	FROM #Temp AS T
	WHERE 1 = 1
		AND (NOT(@usercode <> '') 
			OR (@usercode <> '') AND T.PUserCode LIKE '%' + @usercode + '%')
		AND (NOT(@fullname <> '') 
			OR (@fullname <> '') AND T.PFullName LIKE '%' + @fullname + '%')
	GROUP BY T.PtypeId,T.PUserCode,T.PFullName
	ORDER BY T.PtypeId
END
ELSE IF(@statisticstype = 1)
BEGIN
	CREATE TABLE [dbo].#Btypeid_T (
	[typeid] varchar(max)
	)
	INSERT INTO #Btypeid_T  SELECT TypeId FROM F_GetAllManagerBaseTypeId(@fullname, 2, @chvOperatorID)

	declare @sql varchar(max)
	set @sql='
		SELECT
		T.BtypeId AS typeId,
		T.BUserCode AS usercode,
		T.BFullName AS fullname,
		'''' AS unitname,
		ISNULL(SUM(T.Qty),0) AS Qty,
		ISNULL(SUM(T.total),0) AS total,
		ISNULL(SUM(T.InvoiceQty),0) AS InvoiceQty,
		ISNULL(SUM(T.InvoiceMoneyEX),0) AS InvoiceMoneyEX,
		ISNULL(SUM(T.InvoiceMoney),0) AS InvoiceMoney,
		ISNULL(SUM(T.wkpqty),0) AS wkpqty
		FROM #Temp AS T
		'
		IF	@fullname<>''
		SET @sql +='
					INNER JOIN #Btypeid_T bt ON t.BtypeId = bt.typeid
				'
	set @sql+='where 1=1 '
	
	IF @usercode <> ''
	SET @sql +=' AND T.BUserCode LIKE ''%'+@usercode+'%'''
		
	set @sql+=' 
			GROUP BY T.BtypeId,T.BUserCode,T.BFullName
			ORDER BY T.BtypeId '
			
	exec (@sql)
	drop table #Btypeid_T
END

DROP TABLE #Temp
--------------------------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_QueryBuyAppraisalCXList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryBuyAppraisalCXList]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者:杨俊
	日期:2015-05-14
	描述:采购暂估统计树型表
*/
CREATE PROCEDURE Web_QueryBuyAppraisalCXList
(
	@startdate		    VARCHAR(30),	--查询起始时间
	@enddate			VARCHAR(30),	--查询结束时间
	@parid	           	VARCHAR(50),	--父节点ID
	@stypeid            VARCHAR(MAX),	--分支机构ID
	@ptypeid			VARCHAR(MAX),	--商品ID
	@dealtypeid			VARCHAR(MAX),	--结算单位ID
	@btypeid			VARCHAR(MAX),	--往来单位ID
	@etypeid			VARCHAR(MAX),	--经手人ID
	@ktypeid			VARCHAR(MAX),	--仓库ID
	@dtypeid			VARCHAR(MAX),	--部门ID
	@billType			VARCHAR(20),	--单据类型
	@Comment			VARCHAR(200),	--摘要
	@Explain			VARCHAR(200),	--说明
	@statisticstype		INT,			--统计方式
	@chvOperatorID		VARCHAR(50)		--操作员ID
)
--@encode$--
AS
--------权限检查 - Start--------
IF @chvOperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------权限检查 - END--------
--分支机构
CREATE TABLE #Stype
(
	STypeID VARCHAR(50)
)
IF (@stypeid <> '')
	INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@chvOperatorID)
	
--商品
CREATE TABLE #Ptype
(
	PTypeID VARCHAR(50)
)
IF (@ptypeid <> '')
	INSERT INTO #Ptype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ptypeid,20,@chvOperatorID)

--结算单位
CREATE TABLE #dealtypeid
(
	DealTypeID VARCHAR(50)
)
IF(@dealtypeid <> '')
	INSERT INTO #dealtypeid SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealtypeid,2,@chvOperatorID)

--往来单位
CREATE TABLE #Btype
(
	BTypeID VARCHAR(50)
)
IF (@btypeid <> '')
	INSERT INTO #Btype SELECT typeid FROM F_GetAllManagerBaseTypeId(@btypeid,2,@chvOperatorID)

--经手人
CREATE TABLE #Etype
(
	ETypeID VARCHAR(50)
)
IF (@etypeid <> '')
	INSERT INTO #Etype SELECT typeid FROM F_GetAllManagerBaseTypeId(@etypeid,3,@chvOperatorID)

--仓库
CREATE TABLE #Ktype
(
	KTypeID VARCHAR(50)
)
IF (@ktypeid <> '')
	INSERT INTO #Ktype SELECT typeid FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@chvOperatorID)
	
--部门
CREATE TABLE #Dtype
(
	DTypeID VARCHAR(50)
)
IF (@dtypeid <> '')
	INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@chvOperatorID)

--单据类型
CREATE TABLE #BillType
(
	billtype NUMERIC(4, 0)
)
INSERT INTO #BillType(billtype)
SELECT A FROM F_Split(@billType,',')

--#MainType
CREATE TABLE #MainType
(
	TypeID VARCHAR(50),
	parid VARCHAR(50),
	usercode VARCHAR(200),
	fullname VARCHAR(200),
	sonnum INT,
	leveal INT,
	SortID INT 
)

DECLARE @TempLen INT,@sonnum INT
IF(@parid = '' OR @Parid = '00000')
	SET @TempLen = 5
ELSE
	SET @TempLen = Len(@Parid) + 5

SET @sonnum = 0

--商品
IF(@statisticstype = 0)
BEGIN
	SELECT @sonnum = sonnum FROM Ptype WHERE Typeid = @parid
	IF(@sonnum = 0)
	BEGIN
		INSERT INTO #MainType(typeid,parid,usercode,fullname,sonnum,leveal,SortID) 
		SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.SortID 
		FROM	Ptype p,
				(SELECT typeId FROM F_GetManPTypeAll(@chvOperatorID) WHERE typeid = @parid) a
		WHERE	p.typeid = a.typeid 
				AND P.IsService = 0
				AND p.iscombinationproduct = 0
	END
	ELSE
	BEGIN
		INSERT INTO #MainType(typeid,parid,usercode,fullname,sonnum,leveal,SortID) 
		SELECT	p.typeid,p.parid,p.usercode,p.fullname,p.sonnum,p.leveal,p.SortID 
		FROM	Ptype p,
				(SELECT typeId FROM F_GetManPTypeAll(@chvOperatorID) WHERE parid = @parid) a
		WHERE	p.typeid = a.typeid
				AND P.IsService = 0
				AND p.iscombinationproduct = 0
	END
END
ELSE	--供应商
BEGIN
	SELECT @sonnum = sonnum FROM btype WHERE Typeid = @parid
	IF(@sonnum = 0)
	BEGIN
		INSERT INTO #MainType(typeid,parid,usercode,fullname,sonnum,leveal,SortID) 
		SELECT	B.typeid,B.parid,B.usercode,B.fullname,B.sonnum,B.leveal,0
		FROM	btype B,
				(SELECT typeId FROM F_GetManBTypeAll(@chvOperatorID) WHERE typeid = @parid) a
		WHERE	B.typeid = a.typeid
	END
	ELSE
	BEGIN
		INSERT INTO #MainType(typeid,parid,usercode,fullname,sonnum,leveal,SortID) 
		SELECT	B.typeid,B.parid,B.usercode,B.fullname,B.sonnum,B.leveal,0
		FROM	btype B,
				(SELECT typeId FROM F_GetManBTypeAll(@chvOperatorID) WHERE parid = @parid) a
		WHERE	B.typeid = a.typeid
	END
END
	
--#Temp
CREATE TABLE #Temp
(
	Typeid VARCHAR(200),
	Stypeid VARCHAR(200),
	PtypeId VARCHAR(200),
	DealBTypeID VARCHAR(200),
	Btypeid VARCHAR(200),
	etypeid VARCHAR(200),
	KTypeID VARCHAR(200),
	DTypeId VARCHAR(200),
	comment VARCHAR(500),
	explain VARCHAR(500),
	BillDate DATETIME,
	BillType NUMERIC(4, 0),
	Qty  NUMERIC(24, 10) ,
	total  NUMERIC(24, 10) ,
	InvoiceQty  NUMERIC(24, 10) ,
	InvoiceMoneyEX  NUMERIC(24, 10) ,
	InvoiceMoney  NUMERIC(24, 10) ,
	wkpqty  NUMERIC(24, 10) 
)
INSERT INTO #Temp
SELECT * 
FROM
(
	SELECT 
	CASE @statisticstype
		WHEN 0 THEN Substring(A.PtypeId,1,@TempLen)
		ELSE Substring(B.BtypeId,1,@TempLen)
	END AS Typeid,
	A.Stypeid,
	A.PtypeId,
	B.DealBTypeID,
	B.Btypeid,
	B.etypeid,
	A.KTypeID,
	B.DTypeId,
	B.comment,
	B.explain,
	B.BillDate,
	B.BillType,
	A.Qty,A.total,A.InvoiceQty,A.InvoiceMoneyEX,A.InvoiceMoney,A.Qty - A.InvoiceQty AS wkpqty 
	FROM AppraisalBill AS A
	INNER JOIN dbo.BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
	WHERE B.draft = 0
		AND B.ifYearBill = 0
		AND B.RedWord = 0
		AND B.IsIni = 0
		
	UNION ALL
	
	SELECT 
	CASE @statisticstype
		WHEN 0 THEN Substring(A.PtypeId,1,@TempLen)
		ELSE Substring(B.BtypeId,1,@TempLen)
	END AS Typeid,
	A.Stypeid,
	A.PtypeId,
	B.DealBTypeID,
	B.Btypeid,
	B.etypeid,
	A.KTypeID,
	B.DTypeId,
	B.comment,
	B.explain,
	B.BillDate,
	B.BillType,
	-A.Qty AS Qty,-A.total AS total,-A.InvoiceQty AS InvoiceQty,-A.InvoiceMoneyEX AS InvoiceMoneyEX,-A.InvoiceMoney AS InvoiceMoney,-(A.Qty - A.InvoiceQty) AS wkpqty 
	FROM AppraisalBackBill AS A
	INNER JOIN dbo.BillIndex AS B ON(A.BillNumberId = B.BillNumberId)
	WHERE B.draft = 0
		AND B.ifYearBill = 0
		AND B.RedWord = 0
		AND B.IsIni = 0
) AS T
WHERE T.BillDate BETWEEN @startdate AND @enddate
	AND T.BillType IN(SELECT billtype FROM #BillType)
	AND (NOT(@stypeid <> '') 
	OR (@stypeid <> '') AND T.Stypeid IN(SELECT STypeID FROM #Stype))
	AND (NOT(@ptypeid <> '') 
	OR (@ptypeid <> '') AND T.Ptypeid IN(SELECT PTypeID FROM #Ptype))
	AND (NOT(@dealtypeid <> '') 
	OR (@dealtypeid <> '') AND T.DealBTypeID IN(SELECT DealTypeID FROM #dealtypeid))
	AND (NOT(@btypeid <> '') 
	OR (@btypeid <> '') AND T.Btypeid IN(SELECT BTypeID FROM #Btype))
	AND (NOT(@etypeid <> '') 
	OR (@etypeid <> '') AND T.Etypeid IN(SELECT ETypeID FROM #Etype))
	AND (NOT(@ktypeid <> '') 
	OR (@ktypeid <> '') AND T.Ktypeid IN(SELECT KTypeID FROM #Ktype))
	AND (NOT(@dtypeid <> '') 
	OR (@dtypeid <> '') AND T.Dtypeid IN(SELECT DTypeID FROM #Dtype))
	AND (NOT(@Comment <> '') 
	OR (@Comment <> '') AND T.Comment LIKE '%' + @Comment + '%')
	AND (NOT(@Explain <> '') 
	OR (@Explain <> '') AND T.explain LIKE '%' + @Explain + '%')

--按商品方式统计
IF(@statisticstype = 0)
BEGIN
	SELECT 
	A.typeId,
	A.ParID,
	A.UserCode,
	A.FullName,
	A.leveal,
	A.sonnum,
	(
		SELECT FullName FROM dbo.PType_Units WHERE UnitsId = (SELECT baseUnitId FROM dbo.ptype WHERE typeId = A.TypeID)
	) AS unitname,
	ISNULL(SUM(T.Qty),0) AS Qty,
	ISNULL(SUM(T.total),0) AS total,
	ISNULL(SUM(T.InvoiceQty),0) AS InvoiceQty,
	ISNULL(SUM(T.InvoiceMoneyEX),0) AS InvoiceMoneyEX,
	ISNULL(SUM(T.InvoiceMoney),0) AS InvoiceMoney,
	ISNULL(SUM(T.wkpqty),0) AS wkpqty
	FROM #MainType AS A
	LEFT JOIN #Temp AS T ON(A.TypeID = T.typeId)
	GROUP BY A.typeId,A.ParID,A.UserCode,A.FullName,A.leveal,A.sonnum,A.SortID
	ORDER BY A.SortID
END
--按供应商方式统计
ELSE IF(@statisticstype = 1)
BEGIN
	SELECT 
	A.typeId,
	A.ParID,
	A.UserCode,
	A.FullName,
	A.leveal,
	A.sonnum,
	'' AS unitname,
	ISNULL(SUM(T.Qty),0) AS Qty,
	ISNULL(SUM(T.total),0) AS total,
	ISNULL(SUM(T.InvoiceQty),0) AS InvoiceQty,
	ISNULL(SUM(T.InvoiceMoneyEX),0) AS InvoiceMoneyEX,
	ISNULL(SUM(T.InvoiceMoney),0) AS InvoiceMoney,
	ISNULL(SUM(T.wkpqty),0) AS wkpqty
	FROM #MainType AS A
	LEFT JOIN #Temp AS T ON(A.TypeID = T.typeId)
	GROUP BY A.typeId,A.ParID,A.UserCode,A.FullName,A.leveal,A.sonnum
	ORDER BY A.typeId
END

DROP TABLE #Temp
--------------------------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBuyBackDetailBase]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBuyBackDetailBase]
GO


/*
	作者：王刚
	日期：2011-11-24
	描述：采购退货统计明细表查询
*/

/*
  修改：添加批号 自由项，币种信息 结算单位筛选条件
  作者：彭勇
  日期：2012-05-25		
*/

/*
  修改： 魏伟
  日期： 2016-06-03
  描述： 添加 换算率变更前采购单位数量 查询

*/
CREATE PROCEDURE Web_QueryBuyBackDetailBase
(
	@inputType		    char(1),			--  1、相应的统计报表功能识别参数
	@startdate		    varchar(30),		--  2、查询起始时间
	@enddate			varchar(30),		--  3、查询结束时间
	@parid		        varchar(MAX),		--  4、当前双击选择的主信息类别查询范围父节点 ID
	@ptypeid			varchar(MAX),		--  5、树型表或线性表商品类别查询范围父节点 ID
	@btypeid			varchar(MAX),		--  6、树型表或线性表结算单位类别查询范围父节点 ID
	@dealbtypeid		varchar(MAX),		--  6、树型表或线性表往来单位类别查询范围父节点 ID
	@etypeid			varchar(MAX),		--  7、树型表或线性表职员类别查询范围父节点 ID
	@KTypeID			varchar(MAX),		--  8、树型表或线性表仓库类别查询范围父节点 ID
	@sortfield			varchar(25),		--  9、明细表排序方式
	@checkCode		    varchar(2000) = '',	-- 10、制单人编号
	@checkName		    varchar(2000) = '',	-- 11、制单人名称
	@OperatorID			varchar(50),			-- 14、操作员 ID ( 作权限范围检查用 )
	@Red				char(1) ='0',   	-- 19. 是否显示红冲单据
	@billType		    varchar(200),       -- 20. 单据类型
	@dtypeid        	varchar(MAX)='',
	@Stypeid            varchar(MAX),		-- 22、分支机构查询范围父节点 ID
	@IsReporting		INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--

AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 
--------	权限检查 - Start	--------

if @OperatorID is null return 1	-- @intOperatorID由调用存储过程中传入的职员参数

DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
if @intRe <> 0 return @intRe

--------	权限检查 - End		--------     

IF @inputType = 'P'	-- 商品销售统计
	SELECT @ptypeid = @parid

IF @inputType = 'B'	-- 客户销售统计
	SELECT @dealbtypeid = @parid


-- ********	根据不同对象的销售统计，确定主对象的 ID 值 - Start	********


--商品
CREATE TABLE #Ptype(TypeId	varchar(100))
INSERT INTO #Ptype(TypeId) SELECT typeid FROM F_BaseGetAllManagerBaseTypeId(@ptypeid,1,@OperatorID)

--结算单位
CREATE TABLE #Btype (TypeID varchar(50))
INSERT INTO #Btype(typeid) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@btypeid,2,@OperatorID)


--往来单位
CREATE TABLE #dealBtype (TypeID varchar(50))
INSERT INTO #dealBtype(typeid) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@dealbtypeid,2,@OperatorID)

--职员
IF @etypeid='00000'  SET @etypeid='' 
CREATE TABLE #Etype (TypeID varchar(50))
INSERT INTO #Etype(typeid) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@etypeid,3,@OperatorID)

--仓库
CREATE TABLE #Ktype (TypeID varchar(50))
INSERT INTO #Ktype(typeid) SELECT TypeId FROM F_BaseGetAllManagerBaseTypeId(@KTypeID,4,@OperatorID)
IF (@KTypeID='10000' OR  @KTypeID='' OR  @KTypeID='00000') AND NOT EXISTS(select TOP 1 TypeID from #Ktype where typeid='10000') 
	INSERT INTO	#Ktype select '10000'

--部门
CREATE TABLE #Dtype (TypeID varchar(50))
IF @dtypeid='' OR @dtypeid='00000'
BEGIN
    INSERT INTO #Dtype select '' -- 其他部门
END
INSERT INTO #Dtype select typeid  from F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)

IF NOT EXISTS(select * from #Dtype where typeid='')
	IF Charindex('99999',@dtypeid)>0
		INSERT INTO #Dtype select '' -- 其他部门

--分支机构
CREATE TABLE #Stype (TypeID varchar(50))
IF NOT(@Stypeid='' AND @MStypeid='00000')
    INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorID)
--最近使用的换算率
--CREATE TABLE #Rate
--(
--	ptypeid VARCHAR(50),
--	rate numeric(24, 10),
--	unitid int
--)
--INSERT INTO #Rate
--        (unitid ,ptypeid,rate)
--SELECT   pt.UnitId ,pt.PtypeId ,TranslateRate FROM dbo.PType_TranslateRates pt INNER JOIN dbo.F_BaseGetAllManagerBaseTypeId(@PTypeID,1,@OperatorID) f ON f.TypeId=PtypeId   INNER JOIN (SELECT PtypeId,UnitId, MAX(LastUseDate)AS LastUseDate FROM PType_TranslateRates GROUP BY PtypeId,UnitId) t ON pt.PtypeId=t.PtypeId AND  pt.LastUseDate=t.LastUseDate  AND pt.UnitId=t.UnitId INNER JOIN dbo.ptype p ON p.typeId=pt.PtypeId AND pt.UnitId=p.BuyUnitId

IF @inputType = 'P'	-- 商品采购统计
	SELECT @ptypeid = @parid

IF @inputType = 'B'	-- 供货商采购统计
	SELECT @dealbtypeid = @parid

DECLARE @SQL VARCHAR(8000)

SET @SQL = '
		SELECT	B.BillNumberId,
				I.SortID,
				I.id as CustomdetailID,
				I.BillType,
				B.RedWord,
				I.BillDate,
				B.posttime,
				B.BillCode,
				CASE WHEN I.BillType = 6 THEN ''采购退货单'' 
					 WHEN I.BillType = 34 THEN ''采购入库单''
					 WHEN I.BillType = 145 THEN ''受托结算单''
					 WHEN I.BillType = 161 THEN ''采购换货单''
				END AS BillName,
				I.PtypeId,
				b.BtypeId,
				b.dealbtypeid,
				CASE WHEN I.BillType = 145 THEN -I.Qty
					 ELSE I.Qty
			    END AS Qty,
			    CASE WHEN I.BillType = 145 THEN -I.Qty/d2.rate
					 ELSE I.Qty/d2.rate
			    END AS jlQty,
			      CASE WHEN I.BillType = 145 THEN -I.Qty/I.MUnitRate
					 ELSE I.Qty/I.MUnitRate
			    END AS brcjlQty,
			    I.Price AS CostPrice,
				I.nPrice AS nCostPrice,
				CASE WHEN I.BillType = 145 THEN -I.Total
					 ELSE I.Total
			    END AS costtotal,
			    CASE WHEN I.BillType = 145 THEN -I.nTotal
					 ELSE I.nTotal
			    END AS ncosttotal,
			    CASE WHEN I.BillType = 145 THEN -(I.TaxTotal - I.Total)
					 ELSE (I.TaxTotal - I.Total)
				END AS taxge,
				 CASE WHEN I.BillType = 145 THEN -(I.nTaxTotal - I.nTotal)
					 ELSE (I.nTaxTotal - I.nTotal)
				END AS ntaxge,
				
				CASE WHEN I.BillType = 145 THEN -I.TaxTotal
					 ELSE I.TaxTotal
			    END AS TaxTotal,
			    
			    CASE WHEN I.BillType = 145 THEN -I.nTaxTotal
					 ELSE I.nTaxTotal
			    END AS nTaxTotal,
				I.ShareFee,
				I.KtypeId,
				I.StypeId,
				I.EtypeId,
				C.FullName AS checkename,
				B.Comment,
				I.cargoid,
				b1.fullname as ifullname,
	            d1.fullname as acfullname,
	            I.goodsnumber,
	            b.rate,
	            CASE WHEN I.BillType = 145 THEN -I.nQty
					 ELSE I.nQty
			    END AS nQty,
				e1.fullname as ufullname,
				pu.fullname as baseunitfullname,
				customassist=dbo.F_GetCustomAssist(I.PtypeId,CASE WHEN I.BillType = 145 THEN -I.Qty ELSE I.Qty END)
	FROM	BillIndex B
				INNER JOIN InOutstocktable I ON B.BillNumberId = I.BillNumberId
				INNER JOIN #Ptype P ON P.typeId = I.PtypeId
				LEFT JOIN Employee C ON B.Checke = C.TypeID
				LEFT JOIN vWeb_ItemIDByIsCombined b1 ON b1.iscombined=i.IsCombined AND b1.id=i.ItemID
				LEFT JOIN Ac_Currency d1 ON b.cid=d1.CId
				LEFT JOIN PType_Units_Ext d2 ON  i.PtypeId=d2.PtypeID AND i.MUNITID =d2.UnitsId
				LEFT JOIN PType_Units e1 on d2.UnitsId=e1.UnitsId
				LEFT JOIN PType_Units_Ext pue ON  i.PtypeId=pue.PtypeID AND pue.IsDefaultUnit = 1
				LEFT JOIN PType_Units pu on pue.UnitsId=pu.UnitsId
				--LEFT JOIN #Rate   r ON r.PtypeID = i.PtypeId   
				'
		
   IF @dtypeid<>'' OR @MDTypeID=-99999
	  SET @SQL += ' INNER JOIN #Dtype d ON b.DtypeID=d.typeid '+CHAR(13)	
	  
   IF @ktypeid<>'' OR @MKTypeID=-99999 
	  SET @SQL += ' INNER JOIN #Ktype k ON i.ktypeid=k.typeid '+CHAR(13)
	  
   IF @btypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
	  SET @SQL += ' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '+CHAR(13)
	  
	IF @dealbtypeid<>'' OR @MBTypeID=-99999 OR @MBTypeID2=-99999
	  SET @SQL += ' INNER JOIN #dealBtype b2 ON b.dealbtypeid=b2.typeid '+CHAR(13)  
	  
   IF @etypeid<>'' OR @METypeID=-99999 
	  SET @SQL += ' INNER JOIN #Etype e ON b.etypeid=e.typeid '+CHAR(13)
	  
   IF NOT(@stypeid='' and @MStypeid='00000')
	  SET @SQL += ' INNER JOIN #Stype s ON b.stypeID=s.typeid '+CHAR(13)
	  
SET @SQL += '
		WHERE	B.BillType IN ('+@billType+')
				AND  B.BillDate >= '''+ @startdate+'''
				AND  B.BillDate <= '''+ @enddate+'''
				AND  I.BillDate >= '''+ @startdate+'''
				AND  I.BillDate <= '''+ @enddate+'''' 
	  
IF @Red = 0
	SET @SQL += ' AND B.RedWord = 0 '
	
IF @checkName <> ''
	SET @SQL += @checkName

IF @checkCode <> ''
	SET @SQL += @checkCode

SET @Sql=@Sql + ' AND b.ifYearBill= 0 '    --年节存标志	

--IF @sortfield = ''
--		SET @SQL += ' ORDER BY I.BillDate ASC'
--	ELSE IF @sortfield = 'ID_a'
--		SET @SQL += ' ORDER BY I.SortID ASC'
--	ELSE
--		SET @SQL += ' ORDER BY I.SortID DESC'


--PRINT(@SQL)
--EXEC(@SQL)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
	DECLARE @sort VARCHAR(100)
	IF @sortfield = ''
		SET @sort = ' ORDER BY I.BillDate ASC'
	ELSE IF @sortfield = 'ID_a'
		SET @sort = ' ORDER BY I.SortID ASC'
	ELSE
		SET @sort = ' ORDER BY I.SortID DESC'
	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS I ' + @sort + 
			  ' 
				--显示最终结果
				SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head, SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,
				SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,SysDiy26,
				SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
				SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40
					  FROM #temp1 a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
left join Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid
				
				DROP TABLE #temp1
			   '
	EXEC (@SQL)
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
--	DECLARE @sort VARCHAR(100)
--	IF @sortfield = ''
--		SET @sort = ' ORDER BY I.BillDate ASC'
--	ELSE IF @sortfield = 'ID_a'
--		SET @sort = ' ORDER BY I.SortID ASC'
--	ELSE
--		SET @sort = ' ORDER BY I.SortID DESC'
--	CREATE TABLE #tmp_result
--	(
--		Costom1		VARCHAR(max),
--		Costom2		VARCHAR(max),
--		Costom3		VARCHAR(max),
--		Costom4		VARCHAR(max),
--		Costom5		VARCHAR(max),
--		Costom6		VARCHAR(max),
--		Costom7		VARCHAR(max),
--		Costom8		VARCHAR(max),
--		Costom9		VARCHAR(max),
--		Costom10	VARCHAR(max),
--		Costom11	VARCHAR(max),
--		Costom12	VARCHAR(max),
--		Costom13	VARCHAR(max),
--		Costom14	VARCHAR(max),
--		Costom15	VARCHAR(max),
--		Costom16	VARCHAR(max),
--		Costom1detail		varchar(max),
--		Costom2detail		varchar(max),
--		Costom3detail		varchar(max),
--		Costom4detail		varchar(max),
--		Costom5detail		varchar(max),
--		Costom6detail		varchar(max),
--		Costom7detail		varchar(max),
--		Costom8detail		varchar(max),
--		Costom9detail		varchar(max),
--		Costom10detail		varchar(max),
--		Costom11detail		varchar(max),
--		Costom12detail		varchar(max),
--		Costom13detail		varchar(max),
--		Costom14detail		varchar(max),
--		Costom15detail		varchar(max),
--		Costom16detail		varchar(max),
--		row_id				varchar(100)
--	)
--	--生成rowid
--	SET @SQL = 'SELECT row_number() over (order by B.BillnumberID) as rowid,' + SUBSTRING(@SQL,CHARINDEX('SELECT',@SQL) + 6,LEN(@SQL))

--	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS I ' + @sort + 
--			  ' 
--			   DECLARE @p1 dbo.Tb_QueryCustom  
--			   INSERT INTO @p1 SELECT billnumberid,billtype,CustomdetailID,row_number() over (order by BillnumberID) from #temp1 
--			   INSERT INTO #tmp_result EXEC Web_QueryCustomData @p1,2 
				
--				--显示最终结果
--				SELECT a.*,b.* 
--					  FROM #temp1 a 
--					  left join #tmp_result b on a.rowid=b.row_id 
				
--				DROP TABLE #temp1,#tmp_result
--			   '
--	EXEC (@SQL)
--END
----------------------------------------------------------

DROP TABLE #Btype,#Etype,#Ktype,#Dtype,#Stype,#Ptype,#dealBtype
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryBuyOrderNotCompleteDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryBuyOrderNotCompleteDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：谢吉康
--	日期：2019-11-04
--	描述：未完成的采购订单查询
---------------------------------------------
CREATE PROCEDURE Web_QueryBuyOrderNotCompleteDetail
( 
	@OperatorID			VARCHAR(50),
	@startdate			VARCHAR(MAX),
	@enddate			VARCHAR(MAX),
	@reachstartdate		VARCHAR(MAX)='',
	@reachenddate		VARCHAR(MAX)='',
	@stypeid			VARCHAR(MAX),
	@btypeid			VARCHAR(MAX),			--结算单位
	@dealbtypeid		VARCHAR(max),
	@etypeid			VARCHAR(MAX),
	@ktypeid			VARCHAR(MAX),
	@ptypeid			VARCHAR(MAX),
	@billcode			VARCHAR(MAX)='',
	@explain			VARCHAR(MAX),
	@comment			VARCHAR(MAX),
	@WayBillCode 		VARCHAR(200)='',
	@Tel 				VARCHAR(60)='',
	@GoodsNumber 		VARCHAR(20)='',
	@PackWay 			VARCHAR(50)='',
	@shzt				VARCHAR(10),			--非全部状态(9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据)
	@xlkc				INT,
	@IncludeDraft		INT,
	@IsReporting		INT	,					--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@ptypecategoryid	VARCHAR(MAX),			--商品类型
	@BeiZhu		 		VARCHAR(256)='',		--备注
	@cid				VARCHAR(10)=''			--币种	
)
--@encode$--
AS
SET NOCOUNT ON

IF @WayBillCode='' SET @WayBillCode='%' ELSE SET @WayBillCode='%'+ @WayBillCode +'%'
IF @Tel='' SET @Tel='%' ELSE SET @Tel='%'+ @Tel +'%'
IF @GoodsNumber='' SET @GoodsNumber='%' ELSE SET @GoodsNumber='%'+ @GoodsNumber +'%'
IF @PackWay='' SET @PackWay='%' ELSE SET @PackWay='%'+ @PackWay +'%'   
IF @BeiZhu='' SET @BeiZhu='%' ELSE SET @BeiZhu='%'+@BeiZhu+'%'
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #SType(TypeId	VARCHAR(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--结算单位
/*
CREATE TABLE #BType(TypeId	VARCHAR(100))
INSERT INTO #BType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)
*/

--往来单位
CREATE TABLE #CType(TypeId	VARCHAR(100))
INSERT INTO #CType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dealBTypeId,2,@OperatorID)

--仓库
CREATE TABLE #KType(TypeId	VARCHAR(100))
INSERT INTO #KType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	
INSERT INTO #KType(TypeId) VALUES ('')

--职员
CREATE TABLE #EType(TypeId	VARCHAR(100))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@EtypeId,3,@OperatorID)	


--部门
CREATE TABLE #DType(TypeId	VARCHAR(100))
INSERT INTO #DType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

--商品
CREATE TABLE #PType(TypeId	VARCHAR(100))
INSERT INTO #PType(TypeId)  SELECT * FROM F_ManPTypeInCategoryID(@OperatorID,@ptypeid,@ptypeCategoryID)

DECLARE @virtualqtysql VARCHAR(MAX)
SELECT @virtualqtysql = Value FROM Userconfig WHERE ConfigName='VirtualQtySQL' --读取用户虚拟库存计算公式
DECLARE @KCSQL VARCHAR(MAX)
IF @xlkc = 1
BEGIN
	--草稿库存
	CREATE TABLE #DraftGoodsStocks
	(
		PTypeId			VARCHAR(100),
		KTypeId			VARCHAR(100),
		Qty				 NUMERIC(24, 10) ,
		RQty			 NUMERIC(24, 10) ,
		CQty			 NUMERIC(24, 10) ,
		SaleOrderQty	 NUMERIC(24, 10) ,
		BuyOrderQty		 NUMERIC(24, 10) ,
		SaleReachQty	 NUMERIC(24, 10) ,
		BuyReachQty		 NUMERIC(24, 10) ,
		itemid			VARCHAR(50)
	)

	CREATE TABLE #stockqty(
		ptypeid			VARCHAR(50),
		ktypeid			VARCHAR(50),
		Qty				 NUMERIC(24, 10) ,
		Factqty			 NUMERIC(24, 10) ,
		LendQty			 NUMERIC(24, 10) ,
		BorrowQty		 NUMERIC(24, 10) ,	
		BuyOrderQty		 NUMERIC(24, 10) ,
		BuyReachQty		 NUMERIC(24, 10) ,
		SaleOrderQty	 NUMERIC(24, 10) ,
		SaleReachQty	 NUMERIC(24, 10) ,
		RQty			 NUMERIC(24, 10) ,
		CQty			 NUMERIC(24, 10) ,
		VQty			 NUMERIC(24, 10) ,
		itemid			VARCHAR(50)	----需要按商品自由项分组
	)


	INSERT INTO #DraftGoodsStocks(PTypeId,KTypeId,Qty,RQty,CQty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty,itemid) 
	SELECT	B.PTypeId,
			B.KTypeId,
			0 AS Qty,
			SUM(B.RQty) AS RQty,
			SUM(B.CQty) AS CQty,
			0 AS SaleOrderQty,
			0 AS BuyOrderQty,
			0 AS SaleReachQty,
			0 AS BuyReachQty,
			b.itemid
	FROM	
	(
		SELECT S.PTypeId,S.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM BuyBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 34 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM BuyBackBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 6 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM BuyGoodsExchangeBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND S.InOrOut = 'I' AND B.BillType = 161 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM SaleGoodsExchangeBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND S.InOrOut = 'I' AND B.BillType = 160 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId2,S.Qty AS RQty,0 AS CQty,s.ItemID FROM MoveBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeId2 AND B.BillType = 17 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId2,S.Qty AS RQty,0 AS CQty,s.ItemID FROM MoveBjBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeId2 AND B.BillType = 21 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM DisassembleBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND S.InOrOut = 'I' AND B.BillType = 16 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM OverflowBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND B.BillType = 14 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM CommissionBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 144 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM CommissionBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 142 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM GiveMeBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND B.BillType = 126 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM Wx_Bill_OUT S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND B.BillType = 174 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId2,S.Qty AS RQty,0 AS CQty,s.ItemID FROM STypeMoveBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID2 AND B.BillType = 188 AND Draft = 1 AND ifYearBill=0
		UNION ALL 
		SELECT S.PTypeId,S.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM OtherInOutBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 201 AND Draft = 1 AND ifYearBill=0
		--出库部分
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM SaleBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 11 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM SaleBackBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 45 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,b.KTypeId,S.Qty AS RQty,0 AS CQty,s.ItemID FROM RetailBackBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = b.KTypeID AND B.BillType = 215 AND Draft = 1 AND ifYearBill=0			
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM BuyGoodsExchangeBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND S.InOrOut = 'O' AND B.BillType = 161 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM SaleGoodsExchangeBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND S.InOrOut = 'O' AND B.BillType = 160 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM MoveBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeId AND B.BillType = 17 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM MoveBjBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeId AND B.BillType = 21 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM DisassembleBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND S.InOrOut = 'O' AND B.BillType = 16 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM LoseBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND B.BillType = 9 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM CommissionBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 146 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM CommissionBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 140 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM RetailBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND B.BillType = 305 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM GiveBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND B.BillType = 139 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM Wx_Bill_SELF S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND S.InOrOut = 'O' AND S.WxProperty = 0 AND B.BillType = 166 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM Wx_Bill_REPLACE S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND S.WxProperty = 0	AND B.BillType = 168 AND Draft = 1 AND ifYearBill=0	  
		UNION ALL 
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM Wx_Bill_GoTo S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND S.InOrOut = 'O' AND S.WxProperty = 0 AND B.BillType = 172 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,B.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM Wx_Bill_IN S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = B.KTypeID AND B.BillType = 173 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM IntegralExchangeBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID	AND B.BillType = 183 AND Draft = 1 AND ifYearBill=0
		UNION ALL
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM STypeMoveBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 187	 AND Draft = 1 AND ifYearBill=0
		UNION ALL 
		SELECT S.PTypeId,S.KTypeId,0 AS RQty,S.Qty AS CQty,s.ItemID FROM OtherInOutBill S,BillIndex B,#KType K WHERE B.BillNumberId = S.BillNumberId AND K.TypeId = S.KTypeID AND B.BillType = 202 AND Draft = 1 AND ifYearBill=0
	)B INNER JOIN #PType P ON P.TypeId = B.PtypeId
	GROUP BY B.ptypeid,B.KTypeId,b.itemid
	---UNION ALL
	INSERT INTO #DraftGoodsStocks(PTypeId,KTypeId,Qty,RQty,CQty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty,ItemID) 
	SELECT	O.PTypeId,
			O.KTypeId,
			0 AS Qty,
			0 AS RCQty,
			0 AS CKQty,
			CASE 
				WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN ISNULL(SUM(o.SaleOrderQty),0) 
				ELSE 0
			END AS SaleOrderQty,
			CASE
				WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN ISNULL(SUM(o.BuyOrderQty),0)
				ELSE 0
			END AS BuyOrderQty,
			CASE 
				WHEN ISNULL(SUM(o.SaleOrderQty),0)-ISNULL(SUM(o.SaleReachQty),0)>=0 THEN SUM(o.SaleReachQty) 
				ELSE 0
			END AS SaleReachQty,
			CASE
				WHEN ISNULL(SUM(o.BuyOrderQty),0)-ISNULL(SUM(o.BuyReachQty),0)>=0 THEN SUM(o.BuyReachQty)
				ELSE 0
			END AS BuyReachQty,
			o.ItemID
			
	FROM	v_VirtualStockOrderStatus o
	INNER JOIN #KType K ON K.TypeId = O.ktypeid
	INNER JOIN #PType P ON P.TypeId = O.ptypeid
	GROUP BY O.ptypeid,O.KTypeId,o.ItemID
			
    SELECT  G.PtypeId ,
            G.KtypeId ,
            ISNULL(SUM(G.Qty), 0) AS Qty ,
            0 AS RQty ,
            0 AS CQty ,
            0 AS SaleOrderQty ,
            0 AS BuyOrderQty ,
            0 AS SaleReachQty ,
            0 AS BuyReachQty,
            '' AS itemid
    INTO  #GoodsStocks
    FROM  GoodsStocks G
    GROUP BY g.PtypeId ,g.KTypeId
    
    UPDATE #GoodsStocks
    SET itemid=gq.ItemID   FROM GOODSSTOCKS_QTY gq
    WHERE #GoodsStocks.PtypeId = gq.PTypeID AND #GoodsStocks.KtypeId = gq.KTypeID
	
	INSERT INTO #DraftGoodsStocks(PTypeId,KTypeId,Qty,RQty,CQty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty,ItemID) 
	SELECT  * FROM  #GoodsStocks
	

	INSERT INTO #stockqty(PTypeId,KTypeId,Qty,RQty,CQty,SaleOrderQty,BuyOrderQty,SaleReachQty,BuyReachQty,LendQty,BorrowQty,Factqty,VQty)
	SELECT	R.PTypeId,
			R.KTypeId,
			ISNULL(SUM(R.Qty),0) AS Qty,
			ISNULL(SUM(R.RQty),0) AS RQty,
			ISNULL(SUM(R.CQty),0) AS CQty,
			ISNULL(SUM(R.SaleOrderQty),0) AS SaleOrderQty,
			ISNULL(SUM(R.BuyOrderQty),0) AS BuyOrderQty,
			ISNULL(SUM(R.SaleReachQty),0) AS SaleReachQty,
			ISNULL(SUM(R.BuyReachQty),0) AS BuyReachQty,
			0 AS LendQty,
			0 AS BorrowQty,
			0 AS Factqty,
			0 AS VQty
	FROM #DraftGoodsStocks R
	INNER JOIN dbo.ptype  p ON r.ptypeid=p.typeId
	WHERE p.IsService=0
	 GROUP BY R.PtypeId,R.KTypeId

	----------更新订单数量(更新后的订单数量为未发货数量,虚拟库存计算需要)
	UPDATE #stockqty
	SET		SaleOrderQty = ISNULL(SaleOrderQty,0)-ISNULL(SaleReachQty,0), --销售未发货
			BuyOrderQty   =  ISNULL(BuyOrderQty,0)-ISNULL(BuyReachQty,0)  --采购未发货
	-------------更新借欠数量
	SELECT 	PTypeID,
			KTYPEID,
			LendQty   =  ISNULL(SUM(Lend-LendBack-saleqty),0), --欠数-欠收回
			BorrowQty =  ISNULL(SUM(Borrow-BorrowBack-buyqty),0) --借数- 借收回
	INTO	#LEND
	FROM 	V_LENDStatus
	GROUP BY pTypeID,kTypeID
	UPDATE	#stockqty
	SET		FactQty   = ISNULL((ISNULL(R.Qty,0)+ISNULL(L.BorrowQty,0)-ISNULL(L.LendQty,0)),0),	--真实数量= 数量+借数-欠数	
			LendQty   = ISNULL(L.LendQty,0), --借数
			BorrowQty = ISNULL(L.BorrowQty,0) --欠数
	FROM	#stockqty R
	LEFT JOIN #LEND L ON (R.ptypeid = L.PTypeID) AND (R.Ktypeid = L.KTypeID)
	--------------更新虚拟库存数量

	DECLARE @VSQL VARCHAR(MAX)
	SET @VSQL='
	UPDATE #stockqty
	SET		VQty   = '+@virtualqtysql+'
			'
	--PRINT (@VSQL)
	EXEC (@VSQL)
END
DECLARE @SQL VARCHAR(MAX)


CREATE TABLE #AuditingBill
(
	BillNumberId NUMERIC(18,0),
	CheckState	 VARCHAR(50)
)

IF @shzt <> '9' --非全部状态(9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据)
BEGIN
	--IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = '300' AND IfUse = 1)
	--BEGIN
		IF @shzt = '0'	--原始单据
		BEGIN
			INSERT INTO #AuditingBill(BillNumberId,CheckState)
			SELECT	B.BillNumberId,
					'原始单据' AS CheckState
			FROM	OrderIndex B
			WHERE	B.BillDate >= @startdate
					AND B.BillDate <= @enddate
					AND B.billtype = '301'
					AND B.billNumberId NOT IN (	SELECT	A.billNumberId 
												FROM	AuditingBill A
												INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
												INNER JOIN #SType S ON S.TypeID = F.Stypeid											
												WHERE	BillIndexType = 0
											  )
			--SELECT *FROM #AuditingBill
			END
		ELSE
			INSERT INTO #AuditingBill(BillNumberId,CheckState)
			SELECT	A.BillNumberId,
					CASE @shzt
						WHEN '1' THEN '待审核单据'
						WHEN '2' THEN '审核通过单据'
						ELSE '审核不通过单据'
					END AS CheckState
			FROM	AuditingBill A
			INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
			INNER JOIN #SType S ON S.TypeID = F.Stypeid
			WHERE	1=1
					AND	A.BillDate >= @startdate
					AND A.BillDate <= @enddate													
					AND F.IfUse = 1
					AND A.BillIndexType = 0
					AND A.IfAudit = CASE
										WHEN @shzt = '1' THEN '0'
										WHEN @shzt = '2' THEN '1'
										ELSE '-1'
									END		
	--END
END

IF @cid IS NULL
	SET @cid = ''

SET @SQL='
SELECT	DISTINCT	
		ISNULL(AB.CheckState,''原始单据'') AS statename ,
		B.orderid as CustomdetailID,
		I.IfAudit	AS ifaudit,
		I.billNumberId AS billnumberid,   
		I.billtype	AS	billtype,                                                            
		I.BillDate AS billdate,
		I.ReachDate AS reachdate,
		I.Billcode AS billcode,
		I.btypeid AS btypeid,
		I.DealBTypeID,
		I.etypeid AS etypeid,
		I.isyapi,
		B.OrderID AS orderid,
		B.KTypeID AS ktypeid,
		B.ptypeid AS ptypeid,
		B.qty AS orderqty,						--订货数量
		B.qty /isnull(B.munitRate,1) as ordermqty,				--订货销售单位数量
		--dbo.F_GetOrderWaitQty(i.billnumberid,b.orderid,'+CAST(@IncludeDraft as varchar)+') 	AS	reachqty,--待发货数量
		--dbo.F_GetOrderWaitQty(i.billnumberid,b.orderid,'+CAST(@IncludeDraft as varchar)+')/isnull(B.munitRate,1) 	AS	reachmqty,--待发货销售单位数量
		case when '+CAST(@IncludeDraft as varchar)+'=1 then isnull((B.WaitQty+B.ReachQty),0) else isnull(B.ReachQty,0) end as reachqty,
		(case when '+CAST(@IncludeDraft as varchar)+'=1 then isnull((B.WaitQty+B.ReachQty),0) else isnull(B.ReachQty,0) end)/isnull(B.munitRate,1) as reachmqty,
		--B.ReachQty	AS	reachqty,				--已发货数量
		B.qty-dbo.F_GetOrderWaitQty(i.billnumberid,b.orderid,'+CAST(@IncludeDraft as varchar)+')   AS wfhqty,	--未发货数量
		(B.qty-dbo.F_GetOrderWaitQty(i.billnumberid,b.orderid,'+CAST(@IncludeDraft as varchar)+') )/isnull(B.munitRate,1)  AS wfhmqty,	--未发货销售单位数量
		
		
		'
		
IF @xlkc = 1
	BEGIN
		SET @SQL= @SQL+'
				ISNULL(S.factqty,0) AS factqty,			--实际库存
				ISNULL(S.vqty,0) AS vqty,				--虚拟库存'
	END
ELSE
	BEGIN
		SET @SQL= @SQL+'
				0 AS factqty,			--实际库存
				0 AS vqty,				--虚拟库存'
	END
SET	@SQL=@SQL+'
			I.comment AS explain,			--摘要
			B.comment AS comment,			--备注
			AC.CId AS currencyid,			--币种id
			AC.FullName AS currencyname,	--币种名称
			--XS._Id AS valueid,				--自由项id
			--XS.FullName AS valuename		--自由项名称
			CASE WHEN B.IsCombined = 0  THEN
					(SELECT FullName FROM xw_SelfData WHERE _Id= B.ItemId)
					ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM vWeb_ItemIDByIsCombined WHERE id= B.ItemId AND iscombined=1) END AS valuename,
			IsService,
			case when ppp.sonnum=0 THEN pu1.fullname ELSE '''' END as basefullname,		--基本单位数量
			case when ppp.sonnum=0 then pu.fullname else '''' end as Munitfullname ,	--销售单位数量
			case when ppp.sonnum=0 then dbo.F_DecimalDisplay(1,''qty'')+pu.fullname+''=''+ dbo.F_DecimalDisplay(B.munitRate,''qty'')+pu1.fullname  else '''' end as rateralation , --换算关系						
			SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
			SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
			SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
			SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
			SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
			SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
			SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
			SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
			SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40,
			I.Explain AS billexplain,
			I.tel,
			I.goodsnumber as wjsl,
			I.packway,
			I.waybillcode,
			ISNULL(PP.RecAmgSTypeBuyPrice,0) RecPrice,
			MPs.usercode pmulusercode,
			 B.CurMSalePrice  Price,
			CASE WHEN I.Cid <> 1 THEN B.NDiscountPrice ELSE B.DiscountPrice END DiscountPrice,
			CASE WHEN I.Cid <> 1 THEN B.Ntotal ELSE B.total END total,
			CASE WHEN I.Cid <> 1 THEN B.NTaxPrice ELSE B.TaxPrice END TaxPrice,
			CASE WHEN I.Cid <> 1 THEN B.ntaxtotal ELSE B.taxtotal END taxtotal
			
FROM	OrderIndex I
INNER JOIN OrderBill B ON I.billNumberId=B.billNumberID
LEFT JOIN Custom_BillIndex csindex on I.billnumberid=csindex.BillId and I.billtype=csindex.billtype
LEFT JOIN Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and I.billtype=csdetail.billtype AND b.OrderID=csdetail.Detailid
INNER JOIN Ac_Currency AC ON AC.Cid= I.CID
inner JOIN ptype ppp on B.ptypeid=ppp.typeid
LEFT JOIN PType_Price PP ON PP.PTypeID=ppp.TypeId and ppp.baseUnitId=pp.UnitID
INNER JOIN dbo.PType_Units pu1 ON ppp.baseUnitId=  pu1.UnitsId 
INNER JOIN dbo.PType_Units_Ext ue on	 ppp.SaleUnitId=ue.UnitsId AND ppp.typeId=ue.PtypeID	
INNER JOIN dbo.PType_Units pu ON B.MUnitID =  pu.UnitsId 
LEFT JOIN PUserCode MPs ON MPs.PTypeID=ppp.TypeID AND MPs.btypeid=I.dealbtypeid
'
IF @xlkc = 1
SET @SQL= @SQL+'
LEFT JOIN #stockqty S ON S.KtypeId=B.KTypeID AND S.PtypeId=B.ptypeid 
'
IF @shzt <> '9'
	SET @SQL = @SQL + '
	INNER JOIN #AuditingBill AB ON AB.BillNumberId = I.BillNumberId '
ELSE
	SET @SQL = @SQL + '
	LEFT JOIN (	SELECT	A.BillNumberId,
						CASE A.IfAudit
							WHEN 0 THEN ''待审核单据''
							WHEN 1 THEN ''审核通过单据''
							ELSE ''审核不通过单据''
						END AS CheckState
				FROM	AuditingBill A
				INNER JOIN AuditingFlowSet F ON A.AuditingId = F.AuditingId AND F.BillType = ''301''
				WHERE	A.BillIndexType = 0
						AND A.BillDate >= '''+@startdate+'''
						AND A.BillDate <= '''+@enddate+'''
		   )AB ON AB.BillNumberId = I.BillNumberId '
     
IF NOT (@stypeid = '' AND @MStypeid  = '00000')
	SET @SQL = @SQL +'
	INNER JOIN #stype st ON (I.stypeid=st.typeid) '
	     
IF NOT (@Ptypeid = '' AND @MPtypeid = '00000' AND @ptypecategoryid='')
	SET @SQL = @SQL +'
	INNER JOIN #ptype p ON (B.ptypeid=p.typeid) '
SET @SQL = @SQL +'
WHERE	I.OrderState=''0''
		and B.BillOver=0 
		and I.billover=0 
		AND B.qty-B.ReachQty>0
		AND I.BillDate>= '+CHAR(39)+convert(VARCHAR(50),@startdate) +CHAR(39)+'
		AND I.BillDate<='+CHAR(39)+convert(VARCHAR(50),@enddate) +CHAR(39)+'
		AND I.BillCode LIKE '''+'%'+@billcode+'%'+'''
		AND I.billtype=''301''
		AND I.checked=0 
		AND ISNULL(I.comment,'''') LIKE '+CHAR(39)+'%'+@Comment +'%'+CHAR(39)+'
		AND ISNULL(I.explain,'''') LIKE '+CHAR(39)+'%'+@Explain +'%'+CHAR(39)+'
		AND (B.ktypeid in ( select typeid from #ktype)) '
	
IF @BeiZhu<>'%'
	SET @SQL+=' AND  b.Comment LIKE '+char(39)+@BeiZhu+char(39)	
	
IF @cid <> ''      
	SET @SQL+=' AND I.CID = '+CAST(@cid AS VARCHAR(10))+' ' 	
	
IF @WayBillCode<>'%'
BEGIN
	SET @SQL=@SQL+' AND I.WayBillCode like '+char(39)+@WayBillCode+char(39)
END

IF @Tel<>'%'
BEGIN
	SET @SQL=@SQL+' AND I.Tel like '+char(39)+@Tel +char(39)
END
IF @GoodsNumber<>'%'
BEGIN
	SET @SQL=@SQL+' AND I.GoodsNumber like '+char(39)+@GoodsNumber +char(39)
END
IF @PackWay<>'%'
BEGIN
	SET @SQL=@SQL+' AND I.PackWay like '+char(39)+@PackWay+char(39)
END	
	
IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002' AND @dealbtypeid='')
BEGIN
	IF @dealbtypeid<>''
		SET @SQL = @SQL +'
	AND (I.dealBTypeID in (select typeid from #ctype))'
	ELSE
		SET @SQL = @SQL +'
	AND (I.dealBTypeID in (select typeid from #ctype) or i.dealBTypeID='''' OR i.dealBTypeID is null )'
END

IF NOT (@MDTypeId = '00001')
	SET @SQL = @SQL +'
	AND (I.dtypeid in (select typeid from #dtype) or i.dtypeid='''' OR i.dtypeid is null ) '

IF NOT (@METypeId = '00001' AND @etypeid='')
BEGIN
	IF @etypeid<>''
		SET @SQL = @SQL +'
	AND I.etypeid in (select typeid from #etype)'
	ELSE
		SET @SQL = @SQL +'
	AND I.etypeid in (select typeid from #etype)  OR i.etypeid is null or i.etypeid='''' '
END
IF NOT (@MKTypeId = '00000')
BEGIN
	IF @ktypeid<>''
		SET @SQL = @SQL +'
	AND I.ktypeid in (select typeid from #ktype)'
	ELSE
		SET @SQL = @SQL +'
	AND I.ktypeid in (select typeid from #ktype) OR i.ktypeid is null or i.ktypeid='''''
END
	
IF @reachstartdate<>'' 
	SET @SQL = @SQL + '
		AND  I.ReachDate>= '+CHAR(39)+convert(VARCHAR(50),@reachstartdate) +CHAR(39)
IF @reachenddate<>'' 
	SET @SQL = @SQL + '
		AND I.ReachDate<='+CHAR(39)+convert(VARCHAR(50),@reachenddate)+CHAR(39)
		
--PRINT @SQL		
--EXEC (@SQL)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
IF(@IsReporting = 0)
BEGIN
	EXEC(@SQL)
END
ELSE IF(@IsReporting = 1)
BEGIN
	CREATE TABLE #tmp_result
	(
		Costom1		VARCHAR(max),
		Costom2		VARCHAR(max),
		Costom3		VARCHAR(max),
		Costom4		VARCHAR(max),
		Costom5		VARCHAR(max),
		Costom6		VARCHAR(max),
		Costom7		VARCHAR(max),
		Costom8		VARCHAR(max),
		Costom9		VARCHAR(max),
		Costom10	VARCHAR(max),
		Costom11	VARCHAR(max),
		Costom12	VARCHAR(max),
		Costom13	VARCHAR(max),
		Costom14	VARCHAR(max),
		Costom15	VARCHAR(max),
		Costom16	VARCHAR(max),
		Costom1detail		varchar(max),
		Costom2detail		varchar(max),
		Costom3detail		varchar(max),
		Costom4detail		varchar(max),
		Costom5detail		varchar(max),
		Costom6detail		varchar(max),
		Costom7detail		varchar(max),
		Costom8detail		varchar(max),
		Costom9detail		varchar(max),
		Costom10detail		varchar(max),
		Costom11detail		varchar(max),
		Costom12detail		varchar(max),
		Costom13detail		varchar(max),
		Costom14detail		varchar(max),
		Costom15detail		varchar(max),
		Costom16detail		varchar(max),
		row_id				varchar(100)
	)	
	
	--生成rowid
	SET @SQL = 'SELECT DISTINCT row_number() over (order by I.BillnumberID) as rowid,' + SUBSTRING(@SQL,CHARINDEX('SELECT DISTINCT',@SQL) + 18,LEN(@SQL))
	
	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ' + 
			  '
			   DECLARE @p1 dbo.Tb_QueryCustom  
			   INSERT INTO @p1 SELECT billnumberid,billtype,CustomdetailID,row_number() over (order by BillnumberID) from #temp1 
			   INSERT INTO #tmp_result EXEC Web_QueryCustomData @p1,2 
			   
				--显示最终结果
				SELECT a.*,b.* 
					  FROM #temp1 a 
					  left join #tmp_result b on a.rowid=b.row_id 
						  
				DROP TABLE #temp1,#tmp_result '
				
					
	EXEC (@SQL)
END
----------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBuyRequestBillQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBuyRequestBillQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-17
	描述：请购计划处理
	
	修改：鲁大林	
	日期：2012-06-14
	描述：添加基本单位、基本单位数量、浮动单位、浮动单位数量等
	
	修改：舒珊	
	日期：2016-02-24
	描述：增添表头自定义显示字段
	
	修改: 魏伟
	日期：2015-05-26
    描述：表头自定义、表体自定义分别新增10个文本自定义、5个数字自定义、1个日期型自定义
    
    修改: 魏伟
	日期：2015-07-18
    描述：添加查询字段
*/

CREATE PROCEDURE Web_QueryBuyRequestBillQuery 
(
	@operatorid			VARCHAR(100),	--操作员ID
	@startdate			VARCHAR(MAX),	--开始日期
	@enddate			VARCHAR(MAX),	--截止日期
	@stypeid			VARCHAR(MAX),	--分支机构ID
	@dtypeId			VARCHAR(MAX),	--部门ID
	@etypeId			VARCHAR(MAX),	--经手人ID
	@shzt				VARCHAR(10)='9',--审核状态
	@rbilltype          VARCHAR(10)='9',--请购单类型	
	@IsReporting		INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)	


--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	


CREATE TABLE #AuditingBill
(
	BillNumberId NUMERIC(18,0),
	CheckState	 VARCHAR(50),
	IfAudit      CHAR(2)
)

IF @shzt <> '9' --非全部状态(9=全部,0=原始单据,1=待审核单据,2=审核通过单据,3=审核不通过单据)
BEGIN
	--IF EXISTS(SELECT TOP 1 1 FROM AuditingFlowSet WHERE BillType = @orderBillType AND IfUse = 1)
	--BEGIN
		IF @shzt = '0'	--原始单据
			INSERT INTO #AuditingBill(BillNumberId,CheckState,IfAudit)
			SELECT	B.BillNumberId,
					'原始单据' AS CheckState,
					'' 
			FROM	RequestIndex B			
			WHERE	B.BillDate >= @startdate
					AND B.BillDate <= @enddate
					AND B.billtype = 204
					AND (IfAudit='' OR IfAudit=0)
					AND NOT EXISTS
					(
						SELECT	A.billNumberId,a.IfAudit 
						FROM	AuditingBill A
						INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						INNER JOIN #GetManSTypeId S ON S.TypeID = F.Stypeid											
						WHERE a.BillNumberID = B.billNumberId AND BillIndexType=3	AND f.BillType=204		
					)
		ELSE
			INSERT INTO #AuditingBill(BillNumberId,CheckState,IfAudit)
			SELECT	A.BillNumberId,
					CASE @shzt
						WHEN '1' THEN '待审核单据'
						WHEN '2' THEN '审核通过单据'
						ELSE '审核不通过单据'
					END AS CheckState,
					a.IfAudit
			FROM	AuditingBill A
			INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
			INNER JOIN #GetManSTypeId S ON S.TypeID = F.Stypeid
			WHERE	A.BillDate >= @startdate
					AND A.BillDate <= @enddate													
					AND F.IfUse = 1
					AND F.billtype = 204
					AND A.BillIndexType =3
					AND A.IfAudit = CASE
										WHEN @shzt = '1' THEN '0'
										WHEN @shzt = '2' THEN '1'
										ELSE '-1'
									END		
									
	--END
END

DECLARE @SQL VARCHAR(MAX)=''

SET @SQL='SELECT	DISTINCT(B.BillnumberID),
					B.BillType,
					B.BillDate,
					B.BillCode,
					B.STypeId,
					B.DTypeId,
					B.ETypeId,
					B.Explain,
					B.Comment,
					B.totalqty,
					B.totalmoney,
					CASE
						when (SELECT COUNT(*) FROM RequestBill bc where bc.billnumberid=b.billnumberid AND bc.isstop=0 AND ISNULL(sendqty,0)<qty)>0 AND b.isstop=0 then ''否''
						else ''是''
					END AS iscomplete,
					CASE B.IsStop
						when 0 then''否''
						else ''是''
					end as isstop,
					CASE(SELECT count(*) FROM RequestBill bc where bc.billnumberid=b.billnumberid AND state not in(1,5))
						when 0 then ''否''
						else ''是''
					END AS isexecute,
					CASE(SELECT count(*) FROM RequestBill bc where bc.billnumberid=b.billnumberid AND state<>1)
						when 0 then 1
						else 0
					END AS isrequest,
					CASE
						(SELECT COUNT(*) FROM OrderBill OB WHERE OB.RequestBillNumberID = B.BillNumberId)
						WHEN 0 THEN 0
						ELSE 1
					END AS IsOrderUse,
					CASE
							WHEN ISNULL(AB.CheckState,'''') = '''' THEN ''原始单据''
							ELSE AB.CheckState
						END AS CheckState,
						isnull(AB.IfAudit,'''') as IfAudit,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,
					SysDiy8_head,SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,						SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,SysDiy26_head,						SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head
			FROM	RequestIndex B
			LEFT JOIN RequestBill BI ON BI.BillNumberId=B.BillNumberId
			LEFT JOIN Custom_BillIndex csindex on B.billnumberid=csindex.BillId and B.billtype=csindex.billtype
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'
	IF @shzt <> '9'
		SET @SQL = @SQL + ' INNER JOIN #AuditingBill AB ON AB.BillNumberId = b.BillNumberId '
    ELSE
		SET @SQL = @SQL + ' LEFT JOIN (
											SELECT	A.BillNumberId,
													CASE A.IfAudit
														WHEN 0 THEN ''待审核单据''
														WHEN 1 THEN ''审核通过单据''
														ELSE ''审核不通过单据''
													END AS CheckState,
													A.IfAudit
											FROM	AuditingBill A
											INNER JOIN AuditingFlowSet F ON A.AuditingId = F.AuditingId AND F.BillType = 204
											WHERE	A.BillIndexType = 3
													AND A.BillDate >= '''+CAST(@startdate AS VARCHAR(100))+'''
													AND A.BillDate <= '''+CAST(@enddate AS VARCHAR(100))+'''
									   )AB ON AB.BillNumberId = B.BillNumberId '				
			
			
			
		SET @SQL = @SQL +'	WHERE   B.BillDate>='''+@startdate+'''
					AND CONVERT (DATE,B.BillDate,120)<='''+@enddate+''''
 			
		 IF(@rbilltype<>'9')
		 SET @SQL+='AND b.IsStop='''+@rbilltype+''''
			--ORDER BY B.BillDate DESC,B.BillCode DESC

--PRINT(@SQL)
--EXEC(@SQL)
----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
IF(@IsReporting = 0)
BEGIN
	SET @SQL = @SQL + ' ORDER BY B.BillDate DESC,B.BillCode DESC'
	--PRINT @SQL
	EXEC(@SQL)
END
ELSE IF(@IsReporting = 1)
BEGIN
	CREATE TABLE #tmp_result
	(
		billnumberid VARCHAR(100),
		billtype     VARCHAR(100),
		Costom1		VARCHAR(max),
		Costom2		VARCHAR(max),
		Costom3		VARCHAR(max),
		Costom4		VARCHAR(max),
		Costom5		VARCHAR(max),
		Costom6		VARCHAR(max),
		Costom7		VARCHAR(max),
		Costom8		VARCHAR(max),
		Costom9		VARCHAR(max),
		Costom10	VARCHAR(max),
		Costom11	VARCHAR(max),
		Costom12	VARCHAR(max),
		Costom13	VARCHAR(max),
		Costom14	VARCHAR(max),
		Costom15	VARCHAR(max),
		Costom16	VARCHAR(max)
	)

	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS B ORDER BY B.BillDate DESC,B.BillCode DESC ' + 
			  ' 
			   DECLARE @p1 dbo.TBType_SelfType  
			   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
			   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 

				--显示最终结果
				SELECT	a.*,
						b.Costom1,
						b.Costom2,
						b.Costom3,
						b.Costom4,
						b.Costom5,
						b.Costom6,
						b.Costom7,
						b.Costom8,
						b.Costom9,
						b.Costom10,
						b.Costom11,
						b.Costom12,
						b.Costom13,
						b.Costom14,
						b.Costom15,
						b.Costom16 
				FROM #temp1 a 
				LEFT JOIN #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
						  
				DROP TABLE #temp1,#tmp_result
			   '
	EXEC (@SQL)
END
----------------------------------------------------------

DROP TABLE #GetManSTypeId,#GetManDTypeId,#GetManETypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBuyRequestManulCompare]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBuyRequestManulCompare
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2011-8-25
	描述：请购手工比价价格查询
*/
CREATE PROCEDURE Web_QueryBuyRequestManulCompare
(
	@ptypeid		varchar(100)='',
	@stypeid		varchar(100)='',
	@OperatorID		varchar(100)='',
	@startDate		varchar(25)='',
	@EndDate		varchar(25)='',
	@askbill		INT=0,
	@historyprice	INT=0,
	@btypeid		varchar(200)='',
	@itemid         varchar(200)='',
	@iscombined     varchar(200)=''
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe int, @chvMATypeID varchar(50), @chvMBTypeID varchar(50), @chvMBTypeID2 varchar(50), @chvMETypeID varchar(50), @chvMKTypeID varchar(50), @chvMPTypeID varchar(50), @chvMExpense varchar(50), @chvMIncome varchar(50), @chvMCapital varchar(50), @chvMDtypeid varchar(50), @chvMStypeid varchar(50)
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorID, @chvMATypeID output, @chvMBTypeID output, @chvMBTypeID2 output, @chvMETypeID output, @chvMKTypeID output, @chvMPTypeID output, @chvMExpense output, @chvMIncome output, @chvMCapital output, @chvMDtypeid output, @chvMStypeid output
IF @intRe <> 0 RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------

-- ******** 权限范围单独处理 - Start ********

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID)	


DECLARE @SQL varchar(3000),
		@PriceTrack INT=0
SET @SQL = 'SELECT	a.qty,
					a.Price,
					a.MSalePrice as mprice,
					(select fullname from PType_Units where Unitsid=a.MUnitId) as munit,
					a.mdiscountprice as discountprice,
					a.mtaxprice as taxprice,
					a.Tax,
					a.discount,
					b.btypeid,
					(select fullname from btype where typeid=b.btypeid) as fullname,
					b.billdate, 
					''询价单'' AS source,
					itemid=a.ItemId,
				    itemname= CASE WHEN a.IsCombined = 0  THEN
						    (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					        ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
				    iscombined=a.IsCombined,
				    a.billnumberid
			FROM	AskPriceBill a
			INNER JOIN BillIndex b ON a.billnumberid=b.billnumberid
			INNER JOIN #GetManBTypeId M ON M.typeid=b.btypeid
			WHERE	b.BillDate >= ''' + @startDate + ''' 
					AND b.BillDate <= ''' + @EndDate + '''
					AND a.ptypeid=''' + @ptypeid+ '''
					AND a.stypeid=''' + @stypeid + '''
					AND a.ItemId=''' + @itemid+ '''
					AND a.IsCombined=''' + @iscombined+ ''''
IF @askbill =0
	SET @SQL=@SQL+' AND 1=0'

			
IF @historyprice=1
	--SET @SQL=@SQL+' UNION ALL
	--		SELECT	null as qty,
	--		ISNULL(a.costprice/CASE WHEN  a.Discount=0 THEN 1 ELSE a.Discount END/(select rate from PType_Units_Ext where PtypeID=a.ptypeid and UnitsId=a.UID),0) as price,
	--				a.costprice /CASE WHEN  a.Discount=0 THEN 1 ELSE a.Discount END as mprice,
	--				(select fullname from PType_Units where Unitsid=a.UID) as munit,
	--				a.costprice as discountprice,
	--				a.costprice as taxprice,
	--				null as tax,
	--				null as discount,
	--				a.btypeid,
	--				(select fullname from btype where typeid=a.btypeid) as fullname,
	--				null as billdate,
	--				''历史价格'' AS source,
	--				'''' as temp1,
	--				'''' as temp2,
	--				'''' as temp3,
	--				-300
					
	--		FROM	PriceTrack a
	--		INNER JOIN #GetManBTypeId M ON M.typeid=a.btypeid
	--		WHERE	a.ptypeid=''' + @ptypeid+'''
	--				AND a.costprice is not null
					
	--				AND a.stypeid=''' + @stypeid + ''''
	
	
	SET @SQL=@SQL+' UNION ALL
			SELECT	null as qty,
			ISNULL(a.price/(select rate from PType_Units_Ext where PtypeID=a.ptypeid and UnitsId=a.UID),0) as price,
					a.price as mprice,
					(select fullname from PType_Units where Unitsid=a.UID) as munit,
					ISNULL(a.price/(select rate from PType_Units_Ext where PtypeID=a.ptypeid and UnitsId=a.UID),0) as discountprice,
					ISNULL(a.price/(select rate from PType_Units_Ext where PtypeID=a.ptypeid and UnitsId=a.UID),0) as taxprice,
					null as tax,
					null as discount,
					a.btypeid,
					(select fullname from btype where typeid=a.btypeid) as fullname,
					null as billdate,
					''历史价格'' AS source,
					'''' as temp1,
					'''' as temp2,
					'''' as temp3,
					-300
					
			FROM	PriceTrack_Buy a
			INNER JOIN #GetManBTypeId M ON M.typeid=a.btypeid
			WHERE	a.ptypeid=''' + @ptypeid+'''
					AND a.price is not null
					AND a.stypeid=''' + @stypeid + ''''
				

PRINT(@SQL)
EXEC (@SQL)
DROP TABLE #GetManBTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBuyRequestPlanSolve]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBuyRequestPlanSolve
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-17
	描述：请购计划处理
	
	修改：鲁大林
	日期：2012-06-08
	描述：添加币别、自由项和对应的原币列
	
	修改：舒珊	
	日期：2016-02-24
	描述：增添表头、表体自定义显示字段
	
    修改: 魏伟
    日期: 2015-05-23
    描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_ManPTypeInCategoryID
    
    日期：2015-05-26
	描述：表头自定义、表体自定义分别新增10个文本自定义、5个数字自定义、1个日期型自定义

 
*/

CREATE PROCEDURE Web_QueryBuyRequestPlanSolve 
(
	@operatorid			VARCHAR(100),	--操作员ID
	@startdate			VARCHAR(MAX),	--开始日期
	@enddate			VARCHAR(MAX),	--截止日期
	@requeststartdate	VARCHAR(MAX),	--需求开始日期
	@requestenddate		VARCHAR(MAX),	--需求截止日期
	@stypeid			VARCHAR(MAX),	--分支机构ID
	@dtypeId			VARCHAR(MAX),	--部门ID
	@etypeId			VARCHAR(MAX),	--经手人ID
	@ptypeId			VARCHAR(MAX),	--商品ID
	@billstate			VARCHAR(MAX),	--计划状态
	@ptypecategoryid    VARCHAR(MAX ),     --商品类别ID
	@shzt		VARCHAR(10)='9'					--审核状态
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_ManPTypeInCategoryID(@OperatorID,@Ptypeid,@ptypecategoryid)
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)	


--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	
DECLARE @SQL VARCHAR(MAX)=''
SET @SQL='SELECT	B.BillnumberID,
					B.BillType,
					B.BillDate,
					B.BillCode,
					B.STypeId,
					B.DTypeId,
					B.ETypeId as ETypeId1,
					B.Explain,
					Bc.Comment,
					Bc.feedback,
					Bc.ID,
					Bc.BTypeId,
					Bc.RequestDate,
					CASE DATEPART(YYYY,Bc.OrderDate) WHEN 9999 THEN NULL ELSE Bc.OrderDate END AS OrderDate,
					Bc.PtypeId,
					Bc.ETypeId,
					ee.fullname as efullname,
					Bc.Qty,--基本单位数量
					Bc.NQty,--浮动单位数量
					Bc.MQty,--请购单位数量
					--XS.FullName AS valuename,---自由项
					CASE WHEN BC.IsCombined = 0  THEN
					(SELECT FullName FROM xw_SelfData WHERE _Id= BC.ItemId)
					ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM vWeb_ItemIDByIsCombined WHERE id= BC.ItemId AND iscombined=1) END AS valuename,
					PU.FullName AS unitname,--基本单位
					NPU.FullName AS nunitname,--浮动单位
					MPU.FullName AS munitname,--请购单位
					Bc.SalePrice,
					Bc.SaleTotal,
					CASE Bc.State 
						WHEN ''1'' THEN ''请购'' 
						WHEN ''2'' THEN ''接收'' 
						WHEN ''3'' THEN ''反馈'' 
						WHEN ''4'' THEN ''修复'' 
						WHEN ''5'' THEN ''取消''
						WHEN ''6'' THEN ''分配''
					END AS STATE,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,
			SysDiy8_head,SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,
			SysDiy15_head,SysDiy16_head,SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,						SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,SysDiy26_head,						SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head, 
			SysDiy1, SysDiy2, SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9, SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,SysDiy17,SysDiy18,					SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,SysDiy26,SysDiy27,SysDiy28,					SysDiy29,SysDiy30,SysDiy31,SysDiy32

			FROM	RequestIndex B
			INNER JOIN RequestBill Bc ON B.BillNumberId = Bc.BillNumberId
			LEFT JOIN Custom_BillIndex csindex on B.BillNumberId=csindex.BillId and B.billtype=csindex.billtype
			LEFT JOIN Custom_BillDetails csdetail on B.billnumberid=csdetail.BillId and B.billtype=csdetail.billtype AND Bc.ID=csdetail.Detailid
			LEFT JOIN PType_Units PU ON PU.UnitsId=Bc.UnitID
			LEFT JOIN PType_Units NPU ON NPU.UnitsId=Bc.NUnitID
			LEFT JOIN PType_Units MPU ON MPU.UnitsId=Bc.MUnitID
			LEFT JOIN Employee ee ON bc.etypeid=ee.typeid
			--LEFT JOIN xw_SelfData XS ON XS._Id=Bc.ItemID
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			INNER JOIN #GetManPTypeId P ON P.TypeId = BC.PTypeId 
			WHERE   B.BillDate>='''+@startdate+'''
					AND CONVERT (DATE,B.BillDate,120)<='''+@enddate+'''
					AND Bc.RequestDate>='''+@requeststartdate+'''
					AND Bc.RequestDate<='''+@requestenddate+''' '
IF	@shzt <> '9' 
	BEGIN
	   IF	  @shzt='0'--不需要审核的
			SET	@SQL=@SQL+'  and IfAudit='''' '
		IF	  @shzt='1'	--审核通过的
			SET	@SQL=@SQL+' and	b.BillNumberID  IN (SELECT BillNumberID FROM dbo.AuditingBill A
						  INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						  WHERE	A.BillDate >= '''+@startdate+'''
							AND A.BillDate <= '''+@enddate+'''													
							AND F.IfUse = 1
							AND F.billtype = 204
							AND A.BillIndexType =3 
					        AND ifaudit=1 ) '					
	END	 
IF	@shzt = '9'	--全部包括不需要审核的与审核通过的
		SET	@SQL=@SQL+' and (	b.BillNumberID  IN (SELECT BillNumberID FROM dbo.AuditingBill A
						  INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						  WHERE	A.BillDate >= '''+@startdate+'''
							AND A.BillDate <= '''+@enddate+'''													
							AND F.IfUse = 1
							AND F.billtype = 204
							AND A.BillIndexType =3 
					        AND ifaudit=1 )  or  IfAudit='''' )'					
IF	@billstate=0
	SET	@SQL=@SQL+' AND Bc.State <7'	
ELSE
	SET	@SQL=@SQL+' AND Bc.State='+@billstate
	
SET @SQL=@SQL+' ORDER BY B.BillDate DESC,B.BillCode DESC'

PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManDTypeId,#GetManETypeId,#GetManPTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBuyRequestProduceBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryBuyRequestProduceBill
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林
	日期：2011-08-17
	描述：请购比价生单
	
	修改：舒珊	
	日期：2016-02-24
	描述：增添表头、表体自定义显示字段
	
	修改：魏伟
	日期：2015-05-26
	描述：表头自定义、表体自定义分别新增10个文本自定义、5个数字自定义、1个日期型自定义

*/

Create PROCEDURE [dbo].[Web_QueryBuyRequestProduceBill] 
(
	@operatorid			VARCHAR(100),	--操作员ID
	@startdate			VARCHAR(MAX),	--开始日期
	@enddate			VARCHAR(MAX),	--截止日期
	@stypeid			VARCHAR(MAX),	--分支机构ID
	@dtypeId			VARCHAR(MAX),	--部门ID
	@etypeId			VARCHAR(MAX),	--经手人ID
	@ptypeId			VARCHAR(MAX),	--商品ID
	@billcode			VARCHAR(MAX),	--单据编号	
	@shzt		VARCHAR(10)='9'					--审核状态
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ptypeId,1,@OperatorID)	

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)	


--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)	

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	

DECLARE @SQL VARCHAR(MAX)=''
SET @SQL='SELECT	B.BillnumberID,
					B.BillType,
					B.BillDate,
					B.BillCode,
					B.STypeId,
					B.DTypeId,
					B.ETypeId as ETypeId1,
					E1.fullname as efullname1,
					B.Explain,
					Bc.Comment,
					Bc.ID,
					Bc.BTypeId,
					Bc.RequestDate,
					CASE DATEPART(YYYY,Bc.OrderDate) WHEN 9999 THEN NULL ELSE Bc.OrderDate END AS OrderDate,
					Bc.PtypeId,
					CASE ISNULL(BC.ETypeId,'''') WHEN '''' THEN B.ETYPEID ELSE BC.Etypeid END AS ETypeId,
					CASE ISNULL(BC.ETypeId,'''') WHEN '''' THEN e1.fullname ELSE e2.fullname END AS efullname,
					Bc.BTypeId2,
					Bc.Qty,
					pt.customitemid ,
				    pt.customitemfrom ,
			 	    pt.customitemname,
				    pt.customitemrefid,	
					itemid=Bc.ItemId,
				    itemname= CASE WHEN Bc.IsCombined = 0  THEN
						    (SELECT FullName FROM xw_SelfData WHERE _Id= Bc.ItemId)
					        ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= Bc.ItemId ) END,
				    iscombined=Bc.IsCombined,
					CASE Bc.Compareprice when -1 THEN Bc.SalePrice ELSE dbo.F_RoundPrice(CAST(CAST(bc.Qty* bc.Compareprice AS NUMERIC(22,10)) / bc.CompareDiscount AS NUMERIC(22,10))/cast(bc.Qty AS Numeric(22,10))) END AS SalePrice,
					CASE Bc.Compareprice when -1 THEN Bc.SaleTotal ELSE dbo.F_RoundTotal(CAST(CAST(bc.Qty* bc.Compareprice AS NUMERIC(22,10)) / bc.CompareDiscount AS NUMERIC(22,10))) END AS SaleTotal,
					CASE Bc.Compareprice WHEN -1 THEN Bc.discount ELSE Bc.comparediscount END AS discount,
					CASE Bc.Compareprice WHEN -1 THEN Bc.discountPrice ELSE Bc.Compareprice END AS discountPrice,
					CASE Bc.Compareprice WHEN -1 THEN Bc.Total ELSE dbo.F_RoundTotal(CAST(Bc.Qty*Bc.Compareprice AS NUMERIC(22,10))) END AS Total,
					CASE Bc.Compareprice WHEN -1 THEN Bc.Tax ELSE Bc.CompareTax END AS Tax,
					CASE Bc.Compareprice WHEN -1 THEN Bc.TaxPrice ELSE dbo.F_RoundPrice(dbo.F_RoundTotal(CAST(CAST(bc.Compareprice*bc.Qty AS NUMERIC(22,10) )*(1+bc.CompareTax/100) AS NUMERIC(22,10))/bc.Qty)) END AS TaxPrice,
					CASE Bc.Compareprice WHEN -1 THEN Bc.TaxTotal ELSE dbo.F_RoundTotal(CAST(bc.Compareprice*bc.Qty AS NUMERIC(22,10) )*(1+bc.CompareTax/100)) END AS TaxTotal,
					CASE Bc.State 
						WHEN ''1'' THEN ''请购'' WHEN ''2'' THEN ''接收'' WHEN ''3'' THEN ''反馈'' 
						WHEN ''4'' THEN ''修复'' WHEN ''5'' THEN ''取消'' WHEN ''6'' THEN ''分配''
						WHEN ''7'' THEN ''比价'' 
					END AS STATE,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,
			SysDiy8_head,SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,
			SysDiy15_head,SysDiy16_head,SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,						SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,SysDiy26_head,						SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head, 
			SysDiy1, SysDiy2, SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9, SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,SysDiy17,SysDiy18,					SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,SysDiy26,SysDiy27,SysDiy28,					SysDiy29,SysDiy30,SysDiy31,SysDiy32

			FROM	RequestIndex B
			INNER JOIN RequestBill Bc ON B.BillNumberId = Bc.BillNumberId
			LEFT JOIN Custom_BillIndex csindex on B.BillNumberId=csindex.BillId and B.billtype=csindex.billtype
			LEFT JOIN Custom_BillDetails csdetail on B.billnumberid=csdetail.BillId and B.billtype=csdetail.billtype AND Bc.ID=csdetail.Detailid
			INNER JOIN Employee e1 ON B.etypeid=e1.typeid
			INNER JOIN	dbo.PType pt ON Bc.PTypeID = pt.TypeID
			LEFT JOIN Employee e2 ON BC.etypeid=e2.typeid
			INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId
			INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId
			INNER JOIN #GetManPTypeId P ON P.TypeId = BC.PTypeId
			WHERE   B.BillDate>='''+@startdate+'''
					AND CONVERT (DATE,B.BillDate,120)<='''+@enddate+''''
IF	@shzt <> '9' 
	BEGIN
	   IF	  @shzt='0'--不需要审核的
			SET	@SQL=@SQL+'  and IfAudit='''' '
		IF	  @shzt='1'	--审核通过的
			SET	@SQL=@SQL+' and	b.BillNumberID  IN (SELECT BillNumberID FROM dbo.AuditingBill A
						  INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						  WHERE	A.BillDate >= '''+@startdate+'''
							AND A.BillDate <= '''+@enddate+'''													
							AND F.IfUse = 1
							AND F.billtype = 204
							AND A.BillIndexType =3 
					        AND ifaudit=1 )'
	END					        
IF	@shzt = '9'	--全部包括不需要审核的与审核通过的
		SET	@SQL=@SQL+' and	(b.BillNumberID  IN (SELECT BillNumberID FROM dbo.AuditingBill A
						  INNER JOIN AuditingFlowSet F ON A.AuditingID = F.AuditingID
						  WHERE	A.BillDate >= '''+@startdate+'''
							AND A.BillDate <= '''+@enddate+'''													
							AND F.IfUse = 1
							AND F.billtype = 204
							AND A.BillIndexType =3 
					        AND ifaudit=1 ) or IfAudit='''' )'						        
				        						
IF (SELECT Value FROM Userconfig WHERE ConfigName='qgctrl')='1'
	SET @SQL=@SQL+' AND Bc.State IN (6,7)'
ELSE 
	SET @SQL=@SQL+ 'AND Bc.State <8'
IF @billcode<>''
	SET @sql=@SQL+' AND b.billcode like ''%'+@billcode+'%'''
SET @SQL=@SQL+' ORDER BY B.BillDate DESC,B.BillCode DESC'

PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManDTypeId,#GetManETypeId,#GetManPTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF  EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBuyRequestStateQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].Web_QueryBuyRequestStateQuery
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		毛欣蓉
-- Create date: 2011-08-17
-- Description: 请购状态查询
/*，请购单号、商品编号、商品名称、单位、请购量、请购日期、需求日期、状态、采购员、建议供应商、分支机构字段从请购单中取数；
    采购订单编号、订货数量、入库数量从采购订单取数；成本单价、成本金额从采购入库单中取数
    请购单号  商品  请购量  供应商  请购日期 需求日期  状态 采购员  采购订单编号 订货数量 入库数量  成本单价 成本金额 建议供货商 分支机构*/
    
--  修改：舒珊	
--	日期：2016-02-24
--	描述：增添表头、表体自定义显示字段

--  修改: 魏伟
--  日期: 2015-05-23
--  描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_ManPTypeInCategoryID
--
--  日期：2015-05-26
--  描述：表头自定义、表体自定义分别新增10个文本自定义、5个数字自定义、1个日期型自定义

-- =============================================
CREATE PROCEDURE Web_QueryBuyRequestStateQuery
(
	@OperatorId			VARCHAR(100),
	@Stypeid			VARCHAR(MAX),
	@Dtypeid			VARCHAR(MAX),
	@Etypeid			VARCHAR(MAX),
	@Ptypeid			VARCHAR(MAX),
	@startdate			VARCHAR(30),
	@enddate			VARCHAR(30),
	@requeststartdate	VARCHAR(30),		--需求时间范围
	@requestenddate		VARCHAR(30),	
	@ptypecategoryid    VARCHAR(MAX ),     --商品类别ID	
	@State				INT,					--状态 0=全部, 1=请购,2=接收,3=反馈,4=修复,5=取消,6=分配,7=比价,8=订单,9=入库
	@IsReporting		INT				--是否打印、导出 0 = 正常查询，1 = 打印、导出
)
--@encode$--
AS
BEGIN
	
	SET NOCOUNT ON
	
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #Ptype (TypeID VARCHAR(200))
CREATE TABLE #Etype (TypeID VARCHAR(50))
CREATE TABLE #Dtype (TypeID VARCHAR(50))
CREATE TABLE #Stype (TypeID VARCHAR(50))

--商品
INSERT INTO #Ptype SELECT typeid FROM F_ManPTypeInCategoryID(@OperatorID,@Ptypeid,@ptypecategoryid)

--职员
INSERT INTO #Etype SELECT typeid FROM F_GetAllManagerBaseTypeId(@Etypeid,3,@OperatorID)

--部门
INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@dtypeid,9,@OperatorID)

--分支机构
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)	

DECLARE @SQL VARCHAR(MAX)
SET @SQL='	
	SELECT	I.BillCode,
			R.id as CustomdetailID,
			I.Billtype,
			I.BillDate,
			r.PtypeId,
			r.Qty,
			r.Stypeid,
			r.Btypeid,
			r.RequestDate,
			r.OrderDate,
			r.State,
			r.Etypeid,
			r.BillNumberId,
			o.btypeid as gbtypeid,
			O.orderqty,
			O.ReachQty ,
			O.costtotal,
			o.costprice,
			--杨俊2013-04-03修改，列名重复而且为空
			--o.Billcode
			SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,
			SysDiy8_head,SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,
			SysDiy15_head,SysDiy16_head,SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,						SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,SysDiy26_head,						SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head, 
			SysDiy1, SysDiy2, SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
			SysDiy9, SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,SysDiy17,SysDiy18,					SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,SysDiy26,SysDiy27,SysDiy28,					SysDiy29,SysDiy30,SysDiy31,SysDiy32

	FROM RequestBill R
	INNER JOIN RequestIndex I ON R.BillNumberId=I.BillNumberId
	LEFT JOIN Custom_BillIndex csindex on I.BillNumberId=csindex.BillId and I.billtype=csindex.billtype
	LEFT JOIN Custom_BillDetails csdetail on I.billnumberid=csdetail.BillId and I.billtype=csdetail.billtype AND R.ID=csdetail.Detailid
	'
	
IF @MDtypeid<>'00000' OR @Dtypeid<>''
	SET @SQL=@SQL+' INNER JOIN #Dtype d ON I.dtypeid=d.typeid '
IF @MEtypeid<>'00001' OR @Etypeid<>''
	SET @SQL=@SQL+' INNER JOIN #Etype e ON I.etypeid=e.typeid '
IF @MStypeid<>'00000' OR @stypeid<>''
	SET @SQL=@SQL+' INNER JOIN #Stype s ON I.stypeid=s.typeid '
IF @MPtypeid<>'00000' OR @Ptypeid<>'' OR @ptypecategoryid<>''
	SET @SQL=@SQL+' INNER JOIN #Ptype p ON r.ptypeid=p.typeid '
	
SET @SQL=@SQL+'
	LEFT JOIN 
		(		SELECT	o.FromBillID, 
						o.qty as orderqty,
						O.ReachQty ,
						O.ReachTotal as costtotal,
						CASE WHEN O.ReachQty=0 then 0
						ELSE o.ReachTotal/o.ReachQty 
						END AS costprice,
						o.RequestBillID,
						i.Billcode,
						i.btypeid 
				FROM  OrderBill O 
				INNER JOIN orderindex i  ON o.billNumberID=i.billNumberId
		)O ON r.ID=o.RequestBillID
	WHERE	I.BillDate>='''+@startdate+''' 
			AND I.BillDate<='''+@enddate+''' 
			AND R.state in (1,2,5,6,7,8,9) '
IF @requeststartdate<>''
	SET @SQL=@SQL+' AND R.RequestDate>='''+@requeststartdate+''' '
IF @requestenddate<>''
	SET @SQL=@SQL+' AND R.RequestDate<='''+@requestenddate+''' '
IF @State<>0
	SET @SQL=@SQL+' AND R.state='+CAST(@State AS VARCHAR(50))

--PRINT(@SQL)
--EXEC(@SQL)
----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
IF(@IsReporting = 0)
BEGIN
	--PRINT @SQL
	EXEC(@SQL)
END
ELSE IF(@IsReporting = 1)
BEGIN
	CREATE TABLE #tmp_result
	(
		Costom1		VARCHAR(max),
			Costom2		VARCHAR(max),
			Costom3		VARCHAR(max),
			Costom4		VARCHAR(max),
			Costom5		VARCHAR(max),
			Costom6		VARCHAR(max),
			Costom7		VARCHAR(max),
			Costom8		VARCHAR(max),
			Costom9		VARCHAR(max),
			Costom10	VARCHAR(max),
			Costom11	VARCHAR(max),
			Costom12	VARCHAR(max),
			Costom13	VARCHAR(max),
			Costom14	VARCHAR(max),
			Costom15	VARCHAR(max),
			Costom16	VARCHAR(max),
			Costom1detail		varchar(max),
			Costom2detail		varchar(max),
			Costom3detail		varchar(max),
			Costom4detail		varchar(max),
			Costom5detail		varchar(max),
			Costom6detail		varchar(max),
			Costom7detail		varchar(max),
			Costom8detail		varchar(max),
			Costom9detail		varchar(max),
			Costom10detail		varchar(max),
			Costom11detail		varchar(max),
			Costom12detail		varchar(max),
			Costom13detail		varchar(max),
			Costom14detail		varchar(max),
			Costom15detail		varchar(max),
			Costom16detail		varchar(max),
			row_id				varchar(100)
	)
	--生成rowid
	SET @SQL = 'SELECT row_number() over (order by r.BillnumberID) as rowid,' + SUBSTRING(@SQL,CHARINDEX('SELECT',@SQL) + 6,LEN(@SQL))
		
	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ' + 
			  ' 
			   DECLARE @p1 dbo.Tb_QueryCustom  
			   INSERT INTO @p1 SELECT billnumberid,billtype,CustomdetailID,row_number() over (order by BillnumberID) from #temp1 
			   INSERT INTO #tmp_result EXEC Web_QueryCustomData @p1,2 

				--显示最终结果
				SELECT a.*,b.* 
					  FROM #temp1 a 
					  left join #tmp_result b on a.rowid=b.row_id 
					
				DROP TABLE #temp1,#tmp_result
			   '
	EXEC (@SQL)
END	
----------------------------------------------------------
			
DROP TABLE #Ptype, #Etype ,#Dtype , #Stype
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryBuySummaryDetailed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryBuySummaryDetailed]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
 
  作者：彭勇	
  日期：2012-5-22
  描述：供应商，商品采购汇总明细
*/

/*
 
  作者：杨俊	
  日期：2014-12-25
  描述：优化
*/
/*
  修改： 魏伟
  日期： 2016-06-03
  描述： 添加 换算率变更前采购单位数量 查询

*/
CREATE PROCEDURE Web_QueryBuySummaryDetailed
(
	@chrInputType		CHAR(1),				--  1、相应的统计报表功能识别参数
	@chvStartDate		VARCHAR(30),			--  2、查询起始时间
	@chvENDDate			VARCHAR(30),			--  3、查询结束时间
	@chvParentID		VARCHAR(50),			--  4、当前双击选择的主信息类别查询范围父节点 ID
	@chvPTypeID			VARCHAR(MAX),			--  5、树型表或线性表商品类别查询范围父节点 ID
	@chvBTypeID			VARCHAR(MAX),			--  6、树型表或线性表结算单位类别查询范围父节点 ID
	@dealbtypeid		VARCHAR(MAX),	        -- 往来单位	
	@chvETypeID			VARCHAR(MAX),			--  7、树型表或线性表职员类别查询范围父节点 ID
	@chvKTypeID			VARCHAR(MAX),			--  8、树型表或线性表仓库类别查询范围父节点 ID
	@chvDTypeID			VARCHAR(MAX),			--  8、树型表或线性表部门类别查询范围父节点 ID
	@sortfield			VARCHAR(50),			--  9、明细表排序方式
	@checkCode			VARCHAR(MAX)	= '',	-- 10、筛选编号
	@checkName			VARCHAR(MAX)	= '',	-- 11、筛选名称
	@chvOperatorID		VARCHAR(50),			-- 14、操作员 ID ( 作权限范围检查用 )
	@chvDX				CHAR(1)         = '0',	-- 15、 1 部分仓库时显示代销数据 0 不显示
	@chkRed        		CHAR(1) = '0'	,		-- 显示红冲单据
	@chvBilltype    	VARCHAR(200)    ,       -- 19 单据类型
	@chvComment     	VARCHAR(200) = '',      -- 17 说明
	@chvZY 				VARCHAR(200) = '',      -- 18 摘要
	@chvPF        		CHAR(1) = '0',
	@StypeID			VARCHAR(MAX) = '00000',	-- 8、树型表或线性表分支机构类别查询范围父节点 ID
	@ptypeproperty      INT = 0,                -- 是否是服务商品 
	@ptypecategoryid    VARCHAR(200)            -- 商品类别
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS  OFF
-------------------------------------------权限检查 - Start	-----------------------------------------
IF @chvOperatorID is null return 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @chvOperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re <> 0 return @Re
-------------------------------------------权限检查 - END -------------------------------------------     
-------------------------------------------定义参数----------------------------------------------------
IF (@chrInputType = 'G')	-- 商品采购统计
	SET @chvPTypeID = @chvParentID
-----------------------------------------------------------------------------------------------------
-------------------------------------------临时表----------------------------------------------------
--单据类型
CREATE TABLE #Billtype
(
	Billtype VARCHAR(500)
)
INSERT INTO #Billtype
SELECT a FROM dbo.f_split(@chvBilltype,',')

--商品
CREATE TABLE #PType
(
	TypeID VARCHAR(100)
)
----最近使用的换算率
--CREATE TABLE #Rate
--(
--	ptypeid VARCHAR(50),
--	rate numeric(24, 10),
--	unitid int
--)
--INSERT INTO #Rate
--        (unitid ,ptypeid,rate)
--SELECT   pt.UnitId ,pt.PtypeId ,TranslateRate FROM dbo.PType_TranslateRates pt INNER JOIN dbo.F_BaseGetAllManagerBaseTypeId(@chvPTypeID,1,@chvOperatorID) f ON f.TypeId=PtypeId   INNER JOIN (SELECT PtypeId,UnitId, MAX(LastUseDate)AS LastUseDate FROM PType_TranslateRates GROUP BY PtypeId,UnitId) t ON pt.PtypeId=t.PtypeId AND  pt.LastUseDate=t.LastUseDate  AND pt.UnitId=t.UnitId INNER JOIN dbo.ptype p ON p.typeId=pt.PtypeId AND pt.UnitId=p.BuyUnitId
 
DECLARE @pSQL VARCHAR(MAX)=''
SET @pSQL='
INSERT INTO #PType 
SELECT a.typeid FROM F_GetAllManagerBaseTypeId('''+@chvPTypeID+''',1,'''+@chvOperatorID+''') a
INNER JOIN ptype p ON a.TypeId = p.typeid
WHERE ('+CONVERT(VARCHAR(1),@ptypeproperty)+' = 0 OR (p.IsService = 0 AND '
		+CONVERT(VARCHAR(1),@ptypeproperty)+' = 2) OR (p.IsService = 1 AND '
		+CONVERT(VARCHAR(1),@ptypeproperty)+' = 1)
	   ) 
'


CREATE TABLE #PCategory (
	typeid VARCHAR(500)
)
IF (@PTypeCategoryId<>'' AND @PTypeCategoryId<>'00000')
BEGIN 
    INSERT INTO #PCategory SELECT a AS typeid FROM dbo.f_split(@PTypeCategoryId,',')
    DECLARE @count INT=(SELECT SUM(pt.sonnum) FROM #PCategory p LEFT JOIN dbo.PTypeCategory pt ON p.typeid = pt.typeid)
    DECLARE @oldcount INT=0
    CREATE TABLE #tempPC(
        typeid VARCHAR(500)
    )
    WHILE @count<>@oldcount
    BEGIN 
    INSERT INTO #PCategory SELECT typeid AS typeid FROM dbo.PTypeCategory WHERE parid IN (SELECT typeid FROM #PCategory)
    INSERT INTO #tempPC SELECT DISTINCT typeid AS typeid FROM #PCategory
    TRUNCATE TABLE #PCategory
    INSERT INTO #PCategory SELECT typeid FROM #tempPC
    SET @oldcount=@count
    SET @count=(SELECT SUM(pt.sonnum) FROM #PCategory p LEFT JOIN dbo.PTypeCategory pt ON p.typeid = pt.typeid)
    TRUNCATE TABLE #tempPC
    END 
    DROP TABLE #tempPC
    SET @pSQL+='    AND p.PtypeCategoryID IN(SELECT typeid FROM #PCategory)'
END

--商品筛选
IF (@chrInputType = 'G')
BEGIN
	IF	@checkCode <> ''
		SET @pSQL+='	AND p.UserCode LIKE ''%'+@checkCode+'%'''
	IF	@checkName <> ''
		SET @pSQL+='	AND p.FullName LIKE ''%'+@checkName+'%''' 
END

EXEC (@pSQL)

--数据汇总表
CREATE TABLE #InoutStockTable
(
	usercode		VARCHAR(200),
	BillNumberId	NUMERIC(10, 0),
	BillDate		DATETIME,
	punit			VARCHAR(50),
	BillType		NUMERIC(4,0),
	PtypeId			NVARCHAR (50),
	KtypeId			NVARCHAR (50),
	Qty				 NUMERIC(24, 10) ,			--数量
	Price			 NUMERIC(24, 10) ,			--单价
	Total			 NUMERIC(24, 10) ,			--总额
	taxprice		 NUMERIC(24, 10) ,			--含税单价
	TaxTotal		 NUMERIC(24, 10) ,			--含税总额
	cargoid			INT,
	pname			NVARCHAR(200),
	pcode           NVARCHAR(200),
	Bname			VARCHAR(200),
	bcode			VARCHAR(200),	
	NPrice			 NUMERIC(24, 10) ,			--外币单价
	Ntotal			 NUMERIC(24, 10) ,
	Ntaxprice		 NUMERIC(24, 10) ,
	Ntaxtotal		 NUMERIC(24, 10) ,
	fullname		NVARCHAR(200),			--自由项名称
	nQty			 NUMERIC(24, 10) ,			--浮动数量
	ufullname       NVARCHAR(200),			--计量单位名称 
	goodsnumber     VARCHAR(200),
	jlqty            NUMERIC(24, 10) ,			--计量数量
	rate            NUMERIC(24, 10) ,			--换算率
	brcjlqty            NUMERIC(24, 10) ,			--换算率计量数量
	assistantfullname VARCHAR(200),			--浮动单位
	baseunitfullname  VARCHAR(200),			-- 基本单位
	prePrice			   NUMERIC(24, 10) ,
	nprePrice			   NUMERIC(24, 10) ,
	pretotal			   NUMERIC(24, 10) ,
	npretotal			   NUMERIC(24, 10) ,
	discountge			   NUMERIC(24, 10) ,
	ndiscountge			   NUMERIC(24, 10) ,
	Discount			   NUMERIC(24, 10) ,
	TaxOK				   NUMERIC(24, 10) ,		--税率，其他字段使用了这个tax
	customid				INT,
	dComment				VARCHAR(MAX)
)

--价保、返利 #BJFLTEMP
CREATE TABLE #BJFLTEMP
(
	usercode		VARCHAR(200),
	BillNumberId	NUMERIC(10, 0),
	nQty			 NUMERIC(24, 10) ,
	ufullname       VARCHAR(200),
	BillDate		DATETIME,
	NPrice			 NUMERIC(24, 10) ,
	Ntotal			 NUMERIC(24, 10) ,
	Ntaxprice		 NUMERIC(24, 10) ,
	Ntaxtotal		 NUMERIC(24, 10) ,
	cfullname       VARCHAR(200),
	BillCode        VARCHAR(200),
	BillType		NUMERIC(4,0),
	Billtypename    VARCHAR(200),
	PtypeId			NVARCHAR (50),
	StypeId			NVARCHAR (50),
	BtypeId			NVARCHAR (50),
	dealbtypeid		NVARCHAR (50),
	Dtypeid			NVARCHAR (50),
	KtypeId			NVARCHAR (50),
	Qty				 NUMERIC(24, 10) ,
	Price			 NUMERIC(24, 10) ,
	Sum_Total		 NUMERIC(24, 10) ,
	Sum_TaxTotal	 NUMERIC(24, 10) ,
	taxprice		 NUMERIC(24, 10) ,
	Checke			NVARCHAR (50),
	explain			VARCHAR(MAX),
	Comment			VARCHAR (MAX),
	dComment		VARCHAR (MAX),
	totalinMoney	 NUMERIC(24, 10) ,
	Tax				 NUMERIC(24, 10) ,
	NTax			 NUMERIC(24, 10) ,
	Redword			VARCHAR(10),
	posttime		DATETIME,
	cargoid			INT,
	goodsnumber     VARCHAR(200),
	jlqty            NUMERIC(24, 10) ,
	brcjlqty            NUMERIC(24, 10) ,
	assistantfullname VARCHAR(200),
	baseunitfullname  VARCHAR(200),
	currate			VARCHAR(10),
	pQty			 NUMERIC(24, 10) ,
	pricetotal		 NUMERIC(24, 10) ,
	aQty			 NUMERIC(24, 10) ,
	antantotal		 NUMERIC(24, 10) ,
	ifullname       VARCHAR(200),
	etypeid			VARCHAR(200),
	Bname			VARCHAR(200),
	pname			VARCHAR(200),
	prePrice		 NUMERIC(24, 10) ,
	nprePrice		 NUMERIC(24, 10) ,
	pretotal		 NUMERIC(24, 10) ,
	npretotal		 NUMERIC(24, 10) ,
	discountge		 NUMERIC(24, 10) ,
	ndiscountge		 NUMERIC(24, 10) ,
	Discount		 NUMERIC(24, 10) ,
	TaxOK			 NUMERIC(24, 10) ,
	customid			int 
)
-----------------------------------------------------------------------------------------------------
IF(@chvPF = '1')
BEGIN
	--写入价保、返利数据
	INSERT INTO #BJFLTEMP(usercode,BillNumberId,nQty,ufullname,BillDate,NPrice,Ntotal,Ntaxprice,Ntaxtotal,cfullname,BillCode,BillType,
							Billtypename,PtypeId,StypeId,BtypeId,dealbtypeid,Dtypeid,KtypeId,Qty,Price,Sum_Total,Sum_TaxTotal,
							taxprice,Checke,explain,Comment,dComment,totalinMoney,Tax,NTax,Redword,posttime,cargoid,goodsnumber,jlqty,brcjlqty,assistantfullname,
							baseunitfullname,currate,pQty,pricetotal,aQty,antantotal,ifullname,etypeid,Bname,pname,prePrice,nprePrice,
							pretotal,npretotal,discountge,ndiscountge,Discount,TaxOK,customid)
	SELECT 		
		CASE WHEN  @chrInputType='G' THEN p1.UserCode
		      ELSE bt1.UserCode
		      END  AS usercode,
		b.BillNumberID,
		NULL AS nQty,
		NULL AS ufullname,
		b.BillDate,
		NULL AS nprice,
		NULL AS ntotal,
		NULL AS ntaxprice,
		NULL AS ntaxtotal,
		ac.fullname AS cfullname,
		b.BillCode,
		b.billtype,
		(SELECT BillName FROM BillName WHERE Billtype = b.BillType) AS Billtypename,
		a.PTypeID,
		b.stypeid,
		b.btypeid,
		b.dealbtypeid,
		b.dtypeid,
		b.ktypeid,
		NULL AS Qty,
		NULL AS Price,
		NULL AS Sum_Total,
		NULL AS Sum_TaxTotal,
		NULL AS taxprice,
		b.Checke,
		b.explain,
		b.Comment,
		a.Comment dComment,
		NULL AS totalinMoney,
		NULL AS Tax,
		NULL AS nTax,
		b.Redword,
		b.posttime,
		NULL AS cargoid,
		a.goodsnumber,
		NULL AS jlQty,
		NULL AS brcjlQty,
		NULL AS assistantfullname,
		NULL AS baseunitfullname,
		b.rate AS currate,
		CASE 
			WHEN B.BillType = '151' THEN CASE 
											WHEN b.redword = 2 THEN -ISNULL(a.qty,0) 
											ELSE ISNULL(a.qty,0)
										 END
			ELSE 0
		END AS pQty,
		CASE 
			WHEN B.BillType = '151' THEN CASE 
											WHEN b.redword = 2 THEN -ISNULL(a.total,0) 
											ELSE ISNULL(a.total,0)
										 END
			ELSE 0
		END AS pricetotal,
		CASE 
			WHEN B.BillType = '150' THEN CASE 
											WHEN b.redword = 2 THEN -ISNULL(CASE a.Type 
																				WHEN '2' THEN 0 
																				ELSE a.qty 
																			END,0)
											ELSE ISNULL(CASE a.Type 
															WHEN '2' THEN 0 
															ELSE a.qty 
														END,0) 
										 END
			ELSE 0
		END AS aQty,
		CASE 
			WHEN B.BillType = '150' THEN CASE 
											WHEN b.redword = 2 THEN -ISNULL(a.total,0)
											ELSE ISNULL(a.total,0) 
										 END
			ELSE 0 
		END AS antantotal,
		e.fullname AS ifullname,
		b.etypeid,
		bt1.fullname AS bname,
		p1.fullname AS pname,
		--2014-12-15 杨俊添加
		--为了与，王刚2014-11-26 添加的【报表列控制，功能，升级报表统计字段】控制对应，在价保的SELECT也加上这8个列
		NULL AS prePrice,
		NULL AS nprePrice,
		NULL AS pretotal,
		NULL AS npretotal,		
		NULL AS discountge,
		NULL AS ndiscountge,
		NULL AS Discount,
		NULL AS TaxOK ,
		a.ID
	FROM billindex AS b 
	INNER JOIN 
	(
		SELECT BillnumberID,PTypeID,goodsnumber,qty,total,Iscombined,ItemID,'' AS TYPE,ID,Comment FROM PriceProtectBill WHERE BillType = '151'
		UNION ALL 
		SELECT BillnumberID,PTypeID,goodsnumber,qty,total,Iscombined,ItemID,Type ,id,Comment  FROM Advantage WHERE BillType = '150'
	) AS a ON(b.billnumberid = a.BillnumberID)
	INNER JOIN Ac_Currency AS aC ON(B.cid = aC.CID)
	INNER JOIN ptype AS p1 ON(a.ptypeid = p1.typeid)
	INNER JOIN Btype AS bt1 ON(b.dealbtypeid = bt1.typeid)
	INNER JOIN #Ptype p ON(a.ptypeid = p.typeid)
	LEFT JOIN vWeb_ItemIDByIsCombined AS e ON(a.Iscombined = e.iscombined AND e.id = a.ItemID)
	WHERE b.BillDate BETWEEN @chvStartDate AND @chvENDDate
		AND b.draft = 0 
		AND b.isini = 0	
		AND (NOT(@chkRed = '0')
				OR (@chkRed = '0') AND b.Redword = 0)
		AND b.Billtype IN('150','151')
		AND (NOT(@checkCode <> '') 
				OR (@checkCode <> '') AND (NOT(@chrInputType = 'G') AND bt1.UserCode LIKE '%' + @checkCode + '%'
												OR (@chrInputType = 'G') AND p1.UserCode LIKE '%' + @checkCode + '%'
											  )
			)
		AND (NOT(@checkName <> '') 
				OR (@checkName <> '') AND (NOT(@chrInputType = 'G') AND bt1.FullName LIKE '%' + @checkName + '%'
												OR (@chrInputType = 'G') AND p1.FullName LIKE '%' + @checkName + '%'
											  )
			)
		AND (NOT(@chvETypeID <> '' OR @METypeID = -99999)
				OR (@chvETypeID <> '' OR @METypeID = -99999) AND b.etypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvETypeID,3,@chvOperatorID)))
		AND (NOT(@chvBTypeID <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '')
				OR (@chvBTypeID <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '') AND b.btypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBTypeID,2,@chvOperatorID)))
		AND (NOT(@dealbtypeid <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '')
				OR (@dealbtypeid <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '') AND b.dealbtypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID)))
		AND (NOT(@chvDTypeID <> '' OR @MDTypeID = -99999)
				OR (@chvDTypeID <> '' OR @MDTypeID = -99999) AND b.dtypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvDTypeID,9,@chvOperatorID) UNION ALL SELECT ''))
		AND (NOT(@StypeID <> '' OR @MStypeid = -99999)
				OR (@StypeID <> '' OR @MStypeid = -99999) AND b.stypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeID,11,@chvOperatorID)))
		AND (NOT(ISNULL(@chvComment,'') != '')
				OR (ISNULL(@chvComment,'') != '') AND b.explain LIKE '%' + @chvComment + '%')
		AND (NOT(ISNULL(@chvZY,'') != '')
				OR (ISNULL(@chvZY,'') != '') AND b.Comment LIKE '%' + @chvZY + '%')
END
-----------------------------------------------------------------------------------------------------
--#BillIndex
SELECT 
	b.BillnumberID,
	BillCode,
	billdate,
	b.Billtype,
	0 AS Tax,
	RedWord,
	totalMoney,
	TotalInMoney,
	completeTotal,
	BtypeID,
	dealbtypeid,
	b.EtypeID,
	KtypeID,
	b.DtypeID,
	checke,
	b.explain,
	b.Comment,
	Stypeid,
	posttime,
	c.fullname AS cfullname,
	c.rate AS currate
INTO #BillIndex
FROM BillIndex b
INNER JOIN Ac_Currency AS C ON(B.cid = C.CID)   
INNER JOIN #Billtype AS t ON(b.BillType = t.BillType)
WHERE b.BillDate BETWEEN @chvStartDate AND @chvEndDate
	AND b.Draft = 0 
	AND b.isini = 0
	AND (NOT(@chkRed = '0')
			OR (@chkRed = '0') AND b.Redword = 0)
	AND (NOT(@chvETypeID <> '' OR @METypeID = -99999)
			OR (@chvETypeID <> '' OR @METypeID = -99999) AND b.etypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvETypeID,3,@chvOperatorID)))
	AND (NOT(@chvBTypeID <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '')
			OR (@chvBTypeID <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '') AND b.btypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBTypeID,2,@chvOperatorID)))
	AND (NOT(@dealbtypeid <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '')
			OR (@dealbtypeid <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '') AND b.dealbtypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID)))
	AND (NOT(@chvDTypeID <> '' OR @MDTypeID = -99999)
			OR (@chvDTypeID <> '' OR @MDTypeID = -99999) AND b.dtypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvDTypeID,9,@chvOperatorID) UNION ALL SELECT ''))
	AND (NOT(@StypeID <> '' OR @MStypeid = -99999)
			OR (@StypeID <> '' OR @MStypeid = -99999) AND b.stypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeID,11,@chvOperatorID)))
	AND (NOT(ISNULL(@chvComment,'') != '')
			OR (ISNULL(@chvComment,'') != '') AND b.explain LIKE '%' + @chvComment + '%')
	AND (NOT(ISNULL(@chvZY,'') != '')
			OR (ISNULL(@chvZY,'') != '') AND b.Comment LIKE '%' + @chvZY + '%')
-----------------------------------------------------------------------------------------------------
--#InoutStockTable
INSERT INTO #InoutStockTable(usercode,BillnumberID,BillDate,BillType,PtypeID,KtypeID,Qty,Price,Total,taxprice,TaxTotal,cargoid,pname,
pcode,Bname,bcode,NPrice,NTOTAL,NTAXPRICE,NTAXTOTAL,fullname,nQty,ufullname,goodsnumber,jlqty,rate,brcjlqty,assistantfullname,baseunitfullname,
prePrice,nprePrice,pretotal,npretotal,discountge,ndiscountge,Discount,TaxOK,customid,dComment)
SELECT 
	CASE WHEN @chrInputType='G' THEN p1.usercode
		 ELSE bt1.UserCode END AS usercode,
	a.BillnumberID,
	a.BillDate,
	a.BillType,
	a.PtypeID,
	a.KtypeID,
	a.Qty,
	a.Price,
	a.Total,
	a.taxprice,
	a.TaxTotal,
	a.cargoid,
	p1.fullname,
	p1.usercode,
	bt1.FullName,
	bt1.UserCode,
	a.NPrice,
	a.NTOTAL,
	a.NTAXPRICE,
	a.NTAXTOTAL,
	e.fullname,
	a.nqty,
	e1.fullname,
	a.goodsnumber,
	ISNULL(a.qty / d2.rate,0) AS jlqty,
	d2.Rate,
	ISNULL(a.qty / a.MUnitRate,0) AS brcjlqty,
	e3.fullname,
	e2.fullname,
	a.SalePrice AS preprice,
	a.nSalePrice AS npreprice,
	a.SaleTotal AS pretotal,
	a.nSaleTotal AS npretotal,
	a.SaleTotal - a.total AS discountge,
	a.nSaleTotal - a.ntotal AS ndiscountge,
	a.discount,
	a.tax,
	a.ID,
	A.Comment
FROM #Billindex AS b 
INNER JOIN InoutStockTable AS a ON(a.BillnumberID = b.BillnumberID) 
INNER JOIN Btype AS bt1 ON(b.dealbtypeid = bt1.typeid)   
INNER JOIN #PType AS p ON(a.PTypeID = p.typeid) 
INNER JOIN ptype AS p1 ON(a.ptypeid = p1.typeid)
LEFT JOIN vWeb_ItemIDByIsCombined AS e ON(a.Iscombined = e.iscombined AND e.id = a.ItemID)
LEFT JOIN PType_Units_Ext AS d2 ON(a.PtypeId = d2.PtypeID AND a.MUNITID = d2.UnitsId) 
LEFT JOIN PType_Units AS e1 ON(d2.UnitsId = e1.UnitsId)
LEFT JOIN PType_Units AS e2 ON(e2.UnitsId = p1.baseunitid)
LEFT JOIN PType_Units AS e3 ON(e3.UnitsId = p1.assistantunitid)
WHERE b.BillDate BETWEEN @chvStartDate AND @chvEndDate
	AND (NOT(@checkCode <> '') 
			OR (@checkCode <> '') AND (NOT(@chrInputType = 'G') AND bt1.UserCode LIKE '%' + @checkCode + '%'
											OR (@chrInputType = 'G') AND p1.UserCode LIKE '%' + @checkCode + '%'
										  )
		)
	AND (NOT(@checkName <> '') 
			OR (@checkName <> '') AND (NOT(@chrInputType = 'G') AND bt1.FullName LIKE '%' + @checkName + '%'
											OR (@chrInputType = 'G') AND p1.FullName LIKE '%' + @checkName + '%'
										  )
		)
	AND a.ktypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvKTypeID,4,@chvOperatorID) UNION ALL SELECT '10000')
	AND b.BillType <> '400' AND b.BillType<>'401' AND b.BillType<>'404' /*剔除暂估类单据, 后面单独统计*/
	
-----------------------------------------------------------------------------------------------------
 
IF(@chvPF = '1')
BEGIN												
	IF(@chrInputType = 'G')
	BEGIN										
		INSERT INTO #InoutStockTable(pname,pcode,usercode)
		SELECT p1.FullName,p1.UserCode ,p1.UserCode
		FROM billindex AS b
		INNER JOIN 
		(
			SELECT BillnumberID,ptypeid FROM Advantage WHERE BillType = '150'
			UNION ALL
			SELECT BillnumberID,ptypeid FROM PriceProtectBill WHERE BillType = '151'
		) AS a ON(b.billnumberid = a.BillnumberID)
		INNER JOIN ptype AS p1 ON(a.ptypeid = p1.typeid)
		INNER JOIN #PType AS p ON(a.PTypeID = p.typeid)
		WHERE b.BillDate BETWEEN @chvStartDate AND @chvEndDate
			AND b.Draft = 0 
			AND b.isini = 0
			AND b.Billtype IN('150','151')
			AND (NOT(@chkRed = '0')
					OR (@chkRed = '0') AND b.Redword = 0)
			AND (NOT(@checkCode <> '') 
			OR (@checkCode <> '') AND (NOT(@chrInputType = 'G')
											OR (@chrInputType = 'G') AND p1.UserCode LIKE '%' + @checkCode + '%'
										  )
				)
			AND (NOT(@checkName <> '') 
					OR (@checkName <> '') AND (NOT(@chrInputType = 'G')
													OR (@chrInputType = 'G') AND p1.FullName LIKE '%' + @checkName + '%'
												  )
				)
			AND (NOT(@chvETypeID <> '' OR @METypeID = -99999)
					OR (@chvETypeID <> '' OR @METypeID = -99999) AND b.etypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvETypeID,3,@chvOperatorID)))
			AND (NOT(@chvBTypeID <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '')
					OR (@chvBTypeID <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '') AND b.btypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBTypeID,2,@chvOperatorID)))
			AND (NOT(@dealbtypeid <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '')
					OR (@dealbtypeid <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '') AND b.dealbtypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID)))
			AND (NOT(@chvDTypeID <> '' OR @MDTypeID = -99999)
					OR (@chvDTypeID <> '' OR @MDTypeID = -99999) AND b.dtypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvDTypeID,9,@chvOperatorID) UNION ALL SELECT ''))
			AND (NOT(@StypeID <> '' OR @MStypeid = -99999)
					OR (@StypeID <> '' OR @MStypeid = -99999) AND b.stypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeID,11,@chvOperatorID)))
			AND (NOT(ISNULL(@chvComment,'') != '')
					OR (ISNULL(@chvComment,'') != '') AND b.explain LIKE '%' + @chvComment + '%')
			AND (NOT(ISNULL(@chvZY,'') != '')
					OR (ISNULL(@chvZY,'') != '') AND b.Comment LIKE '%' + @chvZY + '%')
	END
	ELSE IF(@chrInputType = 'J')
	BEGIN
		INSERT INTO #InoutStockTable(bname,bcode,usercode)  
		SELECT bt1.fullname,bt1.usercode ,bt1.UserCode
		FROM billindex AS b 
		INNER JOIN 
		(
			SELECT BillnumberID,ptypeid FROM Advantage WHERE BillType = '150'
			UNION ALL
			SELECT BillnumberID,ptypeid FROM PriceProtectBill WHERE BillType = '151'
		) AS a ON(b.billnumberid = a.BillnumberID)
		INNER JOIN Btype AS bt1 ON(b.dealbtypeid = bt1.typeid)
		INNER JOIN #PType AS p ON(a.PTypeID = p.typeid)
		WHERE b.BillDate BETWEEN @chvStartDate AND @chvEndDate
			AND b.Draft = 0 
			AND b.isini = 0
			AND b.Billtype IN('150','151')
			AND (NOT(@chkRed = '0')
					OR (@chkRed = '0') AND b.Redword = 0)
			AND (NOT(@checkCode <> '') 
			OR (@checkCode <> '') AND (NOT(@chrInputType = 'G') AND bt1.UserCode LIKE '%' + @checkCode + '%'
											OR (@chrInputType = 'G')
										  )
				)
			AND (NOT(@checkName <> '') 
					OR (@checkName <> '') AND (NOT(@chrInputType = 'G') AND bt1.FullName LIKE '%' + @checkName + '%'
													OR (@chrInputType = 'G')
												  )
				)
			AND (NOT(@chvETypeID <> '' OR @METypeID = -99999)
					OR (@chvETypeID <> '' OR @METypeID = -99999) AND b.etypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvETypeID,3,@chvOperatorID)))
			AND (NOT(@chvBTypeID <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '')
					OR (@chvBTypeID <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '') AND b.btypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvBTypeID,2,@chvOperatorID)))
			AND (NOT(@dealbtypeid <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '')
					OR (@dealbtypeid <> '' OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 OR @checkCode <> '' OR @checkName <> '') AND b.dealbtypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@dealbtypeid,2,@chvOperatorID)))
			AND (NOT(@chvDTypeID <> '' OR @MDTypeID = -99999)
					OR (@chvDTypeID <> '' OR @MDTypeID = -99999) AND b.dtypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@chvDTypeID,9,@chvOperatorID) UNION ALL SELECT ''))
			AND (NOT(@StypeID <> '' OR @MStypeid = -99999)
					OR (@StypeID <> '' OR @MStypeid = -99999) AND b.stypeid IN(SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeID,11,@chvOperatorID)))
			AND (NOT(ISNULL(@chvComment,'') != '')
					OR (ISNULL(@chvComment,'') != '') AND b.explain LIKE '%' + @chvComment + '%')
			AND (NOT(ISNULL(@chvZY,'') != '')
					OR (ISNULL(@chvZY,'') != '') AND b.Comment LIKE '%' + @chvZY + '%')
	END
END
----------------------------------------------------------------出暂估类数据--开始---------------------------------------------------------------------------
CREATE TABLE #zgTable
(
	redword			INT,
	BillNumberId	NUMERIC(10, 0),
	CustomdetailID  NVARCHAR (MAX),
	BillType		NUMERIC(4,0),
	BillDate		DATETIME,	
	posttime		DATETIME,
	Billcode		VARCHAR(MAX),
	usercode		VARCHAR(200),
	billname		VARCHAR(200),
	Price			 NUMERIC(24, 10) ,
	nPrice			 NUMERIC(24, 10) ,
	Qty				 NUMERIC(24, 10) ,			 
	nQty			 NUMERIC(24, 10) ,
	jlqty			 NUMERIC(24, 10) ,
	brcjlqty		 NUMERIC(24, 10) ,
	Total			 NUMERIC(24, 10) ,			 
	nTotal			 NUMERIC(24, 10) ,
	TaxTotal		 NUMERIC(24, 10) ,
	nTaxTotal		 NUMERIC(24, 10) ,
	taxge			 NUMERIC(24, 10) ,
	ntaxge			 NUMERIC(24, 10) ,
	pretotal		 NUMERIC(24, 10) ,
	npretotal		 NUMERIC(24, 10) ,
	discountge		 NUMERIC(24, 10) ,
	ndiscountge		 NUMERIC(24, 10) ,
	ID				NVARCHAR (MAX),
	PtypeId			NVARCHAR (50),
	btypeid 		NVARCHAR (50),
	dealbtypeid 		NVARCHAR (50),
	etypeid 		NVARCHAR (50),
	KtypeId 			NVARCHAR (50),
	dtypeid 		NVARCHAR (50),
	stypeid 		NVARCHAR (50),
	cargoid 		NVARCHAR (50),
	ifullname 		NVARCHAR (MAX),
	acfullname 		NVARCHAR (MAX),
	goodsnumber 	NVARCHAR (MAX),
	currate	 		 NUMERIC(24, 10) ,
	rate 			 NUMERIC(24, 10) ,
	ufullname 		NVARCHAR (MAX),
	assistantfullname 	NVARCHAR (MAX),	 
	baseunitfullname 	NVARCHAR (MAX),
	Discount 		 NUMERIC(24, 10) ,
	Tax				 NUMERIC(24, 10) ,
	taxprice		 NUMERIC(24, 10) , --含税单价
	ntaxprice		 NUMERIC(24, 10) ,
	checke			VARCHAR(50),
	bname			NVARCHAR (MAX), --往来单位名称
	pname			NVARCHAR (MAX),	--商品名称
	TaxMoney		 NUMERIC(24, 10) ,  
	NTaxMoney		 NUMERIC(24, 10) , --税额
	prePrice		 NUMERIC(24, 10) ,
	nprePrice		 NUMERIC(24, 10) ,
	totalinMoney	 NUMERIC(24, 10) ,	--已结算金额
	bcode			NVARCHAR (MAX),	--往来单位编码
	pcode			NVARCHAR (MAX),	--商品编码
	customid		INT,
	explain			VARCHAR(MAX),
	Comment			VARCHAR(MAX),
	dComment		VARCHAR(MAX)

)
CREATE TABLE #Btype (TypeID varchar(200))
CREATE TABLE #Etype (TypeID varchar(200))
CREATE TABLE #Ktype (TypeID varchar(200))
CREATE TABLE #Dtype (TypeID varchar(200))
CREATE TABLE #Stype (TypeID varchar(200))
CREATE TABLE #dealbtype (TypeID varchar(50))
 	
--结算单位  
INSERT INTO #Btype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvBtypeID,2,@chvOperatorID) 

 
--往来单位
DECLARE @dealSQL VARCHAR(max)=''
SET @dealSQL='
	INSERT INTO #dealbtype(typeid) 
	SELECT b.typeid 
	FROM F_GetAllManagerBaseTypeId('''+@dealbtypeid+''',2,'''+@chvOperatorID+''') fb
	INNER JOIN Btype b ON fb.typeid=b.typeid
	WHERE 1=1
	'
	
--供货商筛选
IF (@chrInputType = 'J')
BEGIN
	IF	@checkCode <> ''
		SET @dealSQL+='	AND b.UserCode LIKE ''%'+@checkCode+'%'''
	IF	@checkName <> ''
		SET @dealSQL+='	AND b.FullName LIKE ''%'+@checkName+'%'''
END 
EXEC (@dealSQL)

 
--职员
INSERT INTO #Etype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvEtypeID,3,@chvOperatorID)
--仓库
INSERT INTO #Ktype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvKTypeID,4,@chvOperatorID)


IF @chvDX='1' OR @chvKTypeID='' -- 全部仓库或部分仓库显示代销数据
	INSERT INTO #Ktype(typeid) VALUES('10000')

--部门
INSERT INTO #Dtype(typeid) select typeid from F_GetAllManagerBaseTypeId(@chvDtypeID,9,@chvOperatorID)

--分支机构
INSERT INTO #Stype(typeid) select typeid from F_GetAllManagerBaseTypeId(@StypeID,11,@chvOperatorID)



	DECLARE @RKSQL VARCHAR(MAX)=''
	
	SET @RKSQL+='
		--=======================================================暂估入库单数据==开始==========================
					SELECT	c.redword AS redword,
							c.BillNumberId AS BillNumberID,
							a.id as CustomdetailID,
							c.BillType AS BillType,
							c.BillDate AS BillDate,
							c.posttime,
							c.Billcode AS Billcode,'
							+
							  CASE WHEN  @chrInputType='G' THEN 'p1.UserCode'
							  ELSE 'bt.UserCode'
							  END 
							+
							'
							  AS usercode,
							bn.billname AS billname,
							Price= a.DiscountPrice,		/*本币 折后单价*/
							nPrice= a.nDiscountPrice,  	/*原币 折后单价*/
							/*下面CASE WHEN 的逻辑是 : CASE WHEN c.RedWord=2 THEN 负数 (CASE WHEN a.InvoiceQty=0 THEN 单据金额 ELSE 算出来的金额 END)
																			 ELSE 正数 (CASE WHEN a.InvoiceQty=0 THEN 单据金额 ELSE 算出来的金额 END)
																			 END,	
							 */
							Qty =CASE WHEN c.RedWord=2 THEN -(a.Qty-a.InvoiceQty) 
													   ELSE (a.Qty-a.InvoiceQty) END , /*基本单位数量 (未开票数量) */ 
							nQty =CASE WHEN c.RedWord=2 THEN -(a.nQty-a.InvoiceNQty)  
														ELSE (a.nQty-a.InvoiceNQty)  END ,	/*浮动单位数量*/ 		
							jlqty=CASE WHEN c.RedWord=2 THEN -(a.Qty-a.InvoiceQty)/d2.Rate ELSE  (a.Qty-a.InvoiceQty)/d2.Rate END ,	/*采购单位数量*/
							brcjlqty=CASE WHEN c.RedWord=2 THEN -(a.Qty-a.InvoiceQty)/d2.Rate ELSE  (a.Qty-a.InvoiceQty)/d2.Rate END ,	/*换算率改变前采购单位数量*/								
							Total =CASE WHEN c.RedWord=2 THEN  CASE WHEN a.InvoiceQty=0 THEN -a.Total ELSE  -(a.Qty-a.InvoiceQty)*a.DiscountPrice END 
														 ELSE   CASE WHEN a.InvoiceQty=0 THEN a.Total ELSE  (a.Qty-a.InvoiceQty)*a.DiscountPrice END  
														 END ,	/*折后金额*/
							nTotal =CASE WHEN c.RedWord=2 THEN  CASE WHEN a.InvoiceQty=0 THEN -a.nTotal ELSE  -(a.Qty-a.InvoiceQty)*a.nDiscountPrice END 
														 ELSE   CASE WHEN a.InvoiceQty=0 THEN a.nTotal ELSE  (a.Qty-a.InvoiceQty)*a.nDiscountPrice END  
														 END ,	/*折后金额*/			
							TaxTotal=CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN -a.TaxTotal ELSE -(a.Qty-a.InvoiceQty)*a.TaxPrice END 
														   ELSE CASE WHEN a.InvoiceQty=0 THEN a.TaxTotal ELSE (a.Qty-a.InvoiceQty)*a.TaxPrice END
														   END,	/*价税合计*/
							nTaxTotal=CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN -a.nTaxTotal ELSE -(a.Qty-a.InvoiceQty)*a.nTaxPrice END 
														   ELSE CASE WHEN a.InvoiceQty=0 THEN a.nTaxTotal ELSE (a.Qty-a.InvoiceQty)*a.nTaxPrice END
														   END,	/*价税合计*/
							taxge= CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN -a.TaxMoney ELSE -(a.Qty-a.InvoiceQty)*a.DiscountPrice*(a.Tax/100) END 
														 ELSE CASE WHEN a.InvoiceQty=0 THEN a.TaxMoney ELSE (a.Qty-a.InvoiceQty)*a.DiscountPrice*(a.Tax/100) END 
														 END ,	/*税额(折后金额*税率)*/		
							ntaxge= CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN -a.nTaxMoney ELSE -(a.Qty-a.InvoiceQty)*a.nDiscountPrice*(a.Tax/100) END 
														 ELSE CASE WHEN a.InvoiceQty=0 THEN a.nTaxMoney ELSE (a.Qty-a.InvoiceQty)*a.nDiscountPrice*(a.Tax/100) END 
														 END ,	/*税额(折后金额*税率)*/		
							pretotal =CASE WHEN c.RedWord=2 THEN  CASE WHEN a.InvoiceQty=0 THEN -a.saletotal ELSE -(a.Qty-a.InvoiceQty)*SalePrice END  
															ELSE  CASE WHEN a.InvoiceQty=0 THEN a.saletotal ELSE (a.Qty-a.InvoiceQty)*SalePrice END 
															END ,	/*采购金额*/
							npretotal = CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN -a.Nsaletotal ELSE -(a.Qty-a.InvoiceQty)*NSalePrice END  
															  ELSE CASE WHEN a.InvoiceQty=0 THEN a.Nsaletotal ELSE (a.Qty-a.InvoiceQty)*NSalePrice END
															  END ,	/*采购金额*/ 
							discountge=CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN -(a.saletotal- a.Total) ELSE -( (a.Qty-a.InvoiceQty)*SalePrice - (a.Qty-a.InvoiceQty)*a.DiscountPrice ) END
															 ELSE CASE WHEN a.InvoiceQty=0 THEN (a.saletotal- a.Total) ELSE ( (a.Qty-a.InvoiceQty)*SalePrice - (a.Qty-a.InvoiceQty)*a.DiscountPrice ) END  
															 END ,	/*折扣额(采购金额-折后金额)*/
							ndiscountge= CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN -(a.nsaletotal- a.nTotal) ELSE -( (a.Qty-a.InvoiceQty)*nSalePrice - (a.Qty-a.InvoiceQty)*a.nDiscountPrice ) END
															   ELSE CASE WHEN a.InvoiceQty=0 THEN (a.nsaletotal- a.nTotal) ELSE ( (a.Qty-a.InvoiceQty)*nSalePrice - (a.Qty-a.InvoiceQty)*a.nDiscountPrice ) END  
															   END ,	/*折扣额(采购金额-折后金额)*/
																
							c.ID,
							a.ptypeid,
							c.btypeid,
							c.dealbtypeid AS dealbtypeid,
							c.etypeid,
							a.ktypeid,
							c.dtypeid,
							c.stypeid,
							a.cargoid,
							b1.fullname as ifullname,
							d1.fullname as acfullname,
							a.goodsnumber,
							c.rate as  currate ,
							d2.rate,
							e1.fullname as ufullname,
							u5.fullname as assistantfullname,
							u1.fullname as baseunitfullname,
							a.Discount,
							a.Tax,
							a.TaxPrice,
							a.NTaxPrice,
							c.checke,
							bt.fullname as bname,
							p1.fullname as pname,
							a.TaxMoney,
							a.NTaxMoney,
							a.SalePrice AS preprice,
							a.nSalePrice AS npreprice,
							c.TotalInMoney + c.completeTotal as totalinmoney,
							bt.usercode as bcode,
							p1.usercode as pcode,
							a.id as customid ,
							c.explain,
							c.Comment,
							a.Comment dComment 
             		FROM	AppraisalBill a
							INNER JOIN 	BillIndex c ON a.BillNumberId=c.BillNumberId
							INNER JOIN dbo.btype bt ON c.DealBTypeID=bt.typeId                            
                            INNER JOIN  #Billtype N on N.Billtype=c.Billtype
                            INNER JOIN  BillName bn on bn.Billtype=N.Billtype
	                        LEFT JOIN vWeb_ItemIDByIsCombined b1 ON b1.iscombined=a.IsCombined AND b1.id=a.ItemID                                           
                            INNER JOIN  Ac_Currency d1 ON c .cid=d1.CId
							LEFT JOIN PType_Units_Ext d2 ON  a.PtypeId=d2.PtypeID AND a.MUNITID =d2.UnitsId
							LEFT JOIN PType_Units e1 on d2.UnitsId=e1.UnitsId
							INNER JOIN ptype p1 on a.ptypeid=p1.typeid
							LEFT JOIN dbo.PType_Units u1 ON  u1.UnitsId = p1.baseUnitId 
							LEFT JOIN dbo.PType_Units u5 ON  u5.UnitsId = p1.AssistantUnitId  /*浮动单位名称*/
 							LEFT JOIN PType_Units_Ext r1 ON r1.PTypeId = p1.TypeId AND p1.baseUnitId = r1.UnitsId
					'
		SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Ptype p  on a.ptypeid=p.typeid '
    
		IF NOT (@chvBtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Btype b  on c.btypeid=b.typeid '
		IF NOT (@dealbtypeid = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #dealBtype b4  on c.dealbtypeid=b4.typeid '	    

		IF NOT (@chvETypeId = '' AND @METypeId = '00001')
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Etype  e  on c.etypeid=e.typeid '

		IF NOT (@chvKTypeID = '' AND @MKtypeid = '00000')  
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Ktype k  on a.ktypeid=k.typeid '

		IF NOT (@chvDTypeId = '' AND @MDtypeid='00000')
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Dtype d  on c.dtypeid=d.typeid '
				
		IF NOT (@STypeId = '' AND @MStypeid='00000')
				SELECT @RKSQL =@RKSQL+'  INNER JOIN  #Stype s  on c.stypeid=s.typeid '		

		SET @RKSQL+=' WHERE   c.Draft=0 AND c.isini=0  AND c.ifYearBill= 0  AND (a.Qty-a.InvoiceQty) <>0'
		IF	@chkRed='0'
			SET @RKSQL+='	AND c.redword=0'
		SET @RKSQL+='    
							AND c.BillDate>='''+@chvStartDate+'''
							AND c.BillDate<='''+@chvEndDate+'''
							AND c.explain like '+char(39)+'%'+@chvComment+'%'+char(39)+'
							AND c.Comment like '+char(39)+'%'+@chvZY+'%'+char(39)+'
							
		--=======================================================暂估入库单数据==结束==========================
					' 

	DECLARE @THSQL VARCHAR(MAX)=''
	SET @THSQL+='	
		--=======================================================暂估退货单数据==开始==========================
					UNION ALL  
					SELECT	c.redword AS redword,
							c.BillNumberId AS BillNumberID,
							a.id as CustomdetailID,
							c.BillType AS BillType,
							c.BillDate AS BillDate,
							c.posttime,
							c.Billcode AS Billcode,'
							+
							  CASE WHEN  @chrInputType='G' THEN 'p1.UserCode'
							  ELSE 'bt.UserCode'
							  END 
							+
							'
							  AS usercode,
							bn.billname AS billname,
							Price= a.DiscountPrice,		/*本币 折后单价*/
							nPrice= a.nDiscountPrice,  	/*原币 折后单价*/
							/*下面CASE WHEN 的逻辑是 : CASE WHEN c.RedWord=2 THEN 正数 (CASE WHEN a.InvoiceQty=0 THEN 单据金额 ELSE 算出来的金额 END)
																			 ELSE 负数 (CASE WHEN a.InvoiceQty=0 THEN 单据金额 ELSE 算出来的金额 END)
																			 END,	
							 */
							Qty =CASE WHEN c.RedWord=2 THEN (a.Qty-a.InvoiceQty) 
													   ELSE -(a.Qty-a.InvoiceQty) END , /*基本单位数量 (未开票数量) */ 
							nQty =CASE WHEN c.RedWord=2 THEN (a.nQty-a.InvoiceNQty)  
														ELSE -(a.nQty-a.InvoiceNQty)  END ,	/*浮动单位数量*/ 		
							jlqty=CASE WHEN c.RedWord=2 THEN (a.Qty-a.InvoiceQty)/d2.Rate ELSE  -(a.Qty-a.InvoiceQty)/d2.Rate END ,	/*采购单位数量*/	
							brcjlqty=CASE WHEN c.RedWord=2 THEN (a.Qty-a.InvoiceQty)/d2.Rate ELSE  -(a.Qty-a.InvoiceQty)/d2.Rate END ,	/*换算率改变前采购单位数量*/						
							Total =CASE WHEN c.RedWord=2 THEN  CASE WHEN a.InvoiceQty=0 THEN a.Total ELSE  (a.Qty-a.InvoiceQty)*a.DiscountPrice END 
														 ELSE   CASE WHEN a.InvoiceQty=0 THEN -a.Total ELSE  -(a.Qty-a.InvoiceQty)*a.DiscountPrice END  
														 END ,	/*折后金额*/
							nTotal =CASE WHEN c.RedWord=2 THEN  CASE WHEN a.InvoiceQty=0 THEN a.nTotal ELSE  (a.Qty-a.InvoiceQty)*a.nDiscountPrice END 
														 ELSE   CASE WHEN a.InvoiceQty=0 THEN -a.nTotal ELSE  -(a.Qty-a.InvoiceQty)*a.nDiscountPrice END  
														 END ,	/*折后金额*/			
							TaxTotal=CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN a.TaxTotal ELSE (a.Qty-a.InvoiceQty)*a.TaxPrice END 
														   ELSE CASE WHEN a.InvoiceQty=0 THEN -a.TaxTotal ELSE -(a.Qty-a.InvoiceQty)*a.TaxPrice END
														   END,	/*价税合计*/
							nTaxTotal=CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN a.nTaxTotal ELSE (a.Qty-a.InvoiceQty)*a.nTaxPrice END 
														   ELSE CASE WHEN a.InvoiceQty=0 THEN -a.nTaxTotal ELSE -(a.Qty-a.InvoiceQty)*a.nTaxPrice END
														   END,	/*价税合计*/
							taxge= CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN a.TaxMoney ELSE (a.Qty-a.InvoiceQty)*a.DiscountPrice*(a.Tax/100) END 
														 ELSE CASE WHEN a.InvoiceQty=0 THEN -a.TaxMoney ELSE -(a.Qty-a.InvoiceQty)*a.DiscountPrice*(a.Tax/100) END 
														 END ,	/*税额(折后金额*税率)*/		
							ntaxge= CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN a.nTaxMoney ELSE (a.Qty-a.InvoiceQty)*a.nDiscountPrice*(a.Tax/100) END 
														 ELSE CASE WHEN a.InvoiceQty=0 THEN -a.nTaxMoney ELSE -(a.Qty-a.InvoiceQty)*a.nDiscountPrice*(a.Tax/100) END 
														 END ,	/*税额(折后金额*税率)*/		
							pretotal =CASE WHEN c.RedWord=2 THEN  CASE WHEN a.InvoiceQty=0 THEN a.saletotal ELSE (a.Qty-a.InvoiceQty)*SalePrice END  
															ELSE  CASE WHEN a.InvoiceQty=0 THEN -a.saletotal ELSE -(a.Qty-a.InvoiceQty)*SalePrice END 
															END ,	/*采购金额*/
							npretotal = CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN a.Nsaletotal ELSE (a.Qty-a.InvoiceQty)*NSalePrice END  
															  ELSE CASE WHEN a.InvoiceQty=0 THEN -a.Nsaletotal ELSE -(a.Qty-a.InvoiceQty)*NSalePrice END
															  END ,	/*采购金额*/ 
							discountge=CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN (a.saletotal- a.Total) ELSE ( (a.Qty-a.InvoiceQty)*SalePrice - (a.Qty-a.InvoiceQty)*a.DiscountPrice ) END
															 ELSE CASE WHEN a.InvoiceQty=0 THEN -(a.saletotal- a.Total) ELSE -( (a.Qty-a.InvoiceQty)*SalePrice - (a.Qty-a.InvoiceQty)*a.DiscountPrice ) END  
															 END ,	/*折扣额(采购金额-折后金额)*/
							ndiscountge= CASE WHEN c.RedWord=2 THEN CASE WHEN a.InvoiceQty=0 THEN (a.nsaletotal- a.nTotal) ELSE ( (a.Qty-a.InvoiceQty)*nSalePrice - (a.Qty-a.InvoiceQty)*a.nDiscountPrice ) END
															   ELSE CASE WHEN a.InvoiceQty=0 THEN -(a.nsaletotal- a.nTotal) ELSE -( (a.Qty-a.InvoiceQty)*nSalePrice - (a.Qty-a.InvoiceQty)*a.nDiscountPrice ) END  
															   END ,	/*折扣额(采购金额-折后金额)*/
										 
							c.ID,
							a.ptypeid,
							c.btypeid,
							c.dealbtypeid AS dealbtypeid,
							c.etypeid,
							a.ktypeid,
							c.dtypeid,
							c.stypeid,
							a.cargoid,
							b1.fullname as ifullname,
							d1.fullname as acfullname,
							a.goodsnumber,
							c.rate as  currate ,
							d2.rate,
							e1.fullname as ufullname,
							u5.fullname as assistantfullname,
							u1.fullname as baseunitfullname,
							a.Discount,
							a.Tax,
							a.TaxPrice,
							a.NTaxPrice,
							c.checke,
							bt.fullname as bname,
							p1.fullname as pname,
							a.TaxMoney,
							a.NTaxMoney,
							a.SalePrice AS preprice,
							a.nSalePrice AS npreprice,
							c.TotalInMoney + c.completeTotal as totalinmoney,
							bt.usercode as bcode,
							p1.usercode as pcode,
							a.id AS customid ,
							c.explain,
							c.Comment,
							a.Comment dComment 
             		FROM	AppraisalBackBill a
							INNER JOIN 	BillIndex c ON a.BillNumberId=c.BillNumberId
							INNER JOIN dbo.btype bt ON c.DealBTypeID=bt.typeId                            
                            INNER JOIN  #Billtype N on N.Billtype=c.Billtype
                            INNER JOIN  BillName bn on bn.Billtype=N.Billtype
	                        LEFT JOIN vWeb_ItemIDByIsCombined b1 ON b1.iscombined=a.IsCombined AND b1.id=a.ItemID                                           
                            INNER JOIN  Ac_Currency d1 ON c .cid=d1.CId
							LEFT JOIN PType_Units_Ext d2 ON  a.PtypeId=d2.PtypeID AND a.MUNITID =d2.UnitsId
							LEFT JOIN PType_Units e1 on d2.UnitsId=e1.UnitsId
							INNER JOIN ptype p1 on a.ptypeid=p1.typeid
							LEFT JOIN dbo.PType_Units u1 ON  u1.UnitsId = p1.baseUnitId 
							LEFT JOIN dbo.PType_Units u5 ON  u5.UnitsId = p1.AssistantUnitId  /*浮动单位名称*/
 							LEFT JOIN PType_Units_Ext r1 ON r1.PTypeId = p1.TypeId AND p1.baseUnitId = r1.UnitsId
					'
		SELECT @THSQL =@THSQL+'  INNER JOIN  #Ptype p  on a.ptypeid=p.typeid '
    
		IF NOT (@chvBtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Btype b  on c.btypeid=b.typeid '
		IF NOT (@dealbtypeid = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @THSQL =@THSQL+'  INNER JOIN  #dealBtype b4  on c.dealbtypeid=b4.typeid '	    

		IF NOT (@chvETypeId = '' AND @METypeId = '00001')
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Etype  e  on c.etypeid=e.typeid '

		IF NOT (@chvKTypeID = '' AND @MKtypeid = '00000')  
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Ktype k  on a.ktypeid=k.typeid '

		IF NOT (@chvDTypeId = '' AND @MDtypeid='00000')
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Dtype d  on c.dtypeid=d.typeid '
				
		IF NOT (@STypeId = '' AND @MStypeid='00000')
				SELECT @THSQL =@THSQL+'  INNER JOIN  #Stype s  on c.stypeid=s.typeid '		

		SET @THSQL+=' WHERE   c.Draft=0 AND c.isini=0  AND c.ifYearBill= 0  AND (a.Qty-a.InvoiceQty) <>0'
		IF	@chkRed='0'
			SET @THSQL+='	AND c.redword=0'
		SET @THSQL+='    
							AND c.BillDate>='''+@chvStartDate+'''
							AND c.BillDate<='''+@chvEndDate+'''
							AND c.explain like '+char(39)+'%'+@chvComment+'%'+char(39)+'
							AND c.Comment like '+char(39)+'%'+@chvZY+'%'+char(39)+'
							
		--=======================================================暂估退货单数据==结束==========================
					' 


	DECLARE @KPSQL VARCHAR(MAX)=''
	
	SET @KPSQL+='		
		--=======================================================采购暂估开票数据==开始==========================
					UNION ALL 
					SELECT	c.redword AS redword,
							c.BillNumberId AS BillNumberID,
							a.id as CustomdetailID,
							c.BillType AS BillType,
							c.BillDate AS BillDate,
							c.posttime,
							c.Billcode AS Billcode,'
							+
							  CASE WHEN  @chrInputType='G' THEN 'p1.UserCode'
							  ELSE 'bt.UserCode'
							  END 
							+
							'
							  AS usercode,
							bn.billname AS billname,
							a.Price ,
							a.nPrice ,  	
							Qty= CASE WHEN c.RedWord=2 THEN -a.Qty ELSE a.Qty END  , /*基本单位数量*/
							NQty= CASE WHEN c.RedWord=2 THEN -a.NQty ELSE a.NQty END   ,	/*浮动单位数量*/ 		
							MQty= CASE WHEN c.RedWord=2 THEN -a.MQty ELSE a.MQty END  ,	/*采购单位数量*/	
							
							brcMQty= CASE WHEN c.RedWord=2 THEN -a.MQty ELSE a.MQty END  ,	/*换算率变化前采购单位数量*/
								
							Total= CASE WHEN c.RedWord=2 THEN -a.Total ELSE a.Total END   ,	/*折后金额*/
							nTotal= CASE WHEN c.RedWord=2 THEN -a.nTotal ELSE a.nTotal END  ,	/*折后金额*/			
							TaxTotal= CASE WHEN c.RedWord=2 THEN -a.TaxTotal ELSE a.TaxTotal END ,	/*价税合计*/
							nTaxTotal= CASE WHEN c.RedWord=2 THEN -a.nTaxTotal ELSE a.nTaxTotal END ,	/*价税合计*/
							taxmoney= CASE WHEN c.RedWord=2 THEN -a.taxmoney ELSE a.taxmoney END  ,	/*税额*/		
							ntaxmoney= CASE WHEN c.RedWord=2 THEN -a.ntaxmoney ELSE a.ntaxmoney END ,	/*税额*/
							Total= CASE WHEN c.RedWord=2 THEN -a.Saletotal ELSE a.Saletotal END ,	/*采购金额*/
							nTotal= CASE WHEN c.RedWord=2 THEN -a.nSaletotal ELSE a.nSaletotal END ,	/*采购金额*/	
							0 , /*折扣额*/
							0 ,	/*折扣额*/ 
							0 as ID,
							a.ptypeid,
							c.btypeid,
							c.dealbtypeid AS dealbtypeid,
							c.etypeid,
							a.ktypeid,
							c.dtypeid,
							c.stypeid,
							a.cargoid,
							b1.fullname as ifullname,
							d1.fullname as acfullname,
							a.goodsnumber,
							c.rate as  currate ,
							d2.rate,
							e1.fullname as ufullname,
							u5.fullname as assistantfullname,
							u1.fullname as baseunitfullname,
							1, /*扣率*/
							a.Tax,
							a.TaxPrice,
							a.NTaxPrice,
							c.checke,
							bt.fullname as bname,
							p1.fullname as pname,
							a.TaxMoney,
							a.NTaxMoney,
							a.SalePrice AS preprice,
							a.nSalePrice AS npreprice,
							c.completeTotal as totalinmoney,							
							bt.usercode as bcode,
							p1.usercode as pcode,
							a.id AS customid ,
							c.explain,
							c.Comment,
							a.Comment dComment 
             		FROM	ReceiptBill a
							INNER JOIN 	ReceiptBillIndex c ON a.BillNumberId=c.BillNumberId
							INNER JOIN dbo.btype bt ON c.DealBTypeID=bt.typeId                            
							INNER JOIN  #Billtype N on N.Billtype=c.Billtype
                            INNER JOIN  BillName bn on bn.Billtype=N.Billtype
	                        LEFT JOIN vWeb_ItemIDByIsCombined b1 ON b1.iscombined=a.IsCombined AND b1.id=a.ItemID                                           
                            INNER JOIN  Ac_Currency d1 ON c .cid=d1.CId
							LEFT JOIN PType_Units_Ext d2 ON  a.PtypeId=d2.PtypeID AND a.MUNITID =d2.UnitsId
							LEFT JOIN PType_Units e1 on d2.UnitsId=e1.UnitsId
							INNER JOIN ptype p1 on a.ptypeid=p1.typeid
							LEFT JOIN dbo.PType_Units u1 ON  u1.UnitsId = p1.baseUnitId 
							LEFT JOIN dbo.PType_Units u5 ON  u5.UnitsId = p1.AssistantUnitId  /*浮动单位名称*/
 							LEFT JOIN dbo.PType_Units_Ext r1 ON r1.PTypeId = p1.TypeId AND p1.baseUnitId = r1.UnitsId
					'
		SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Ptype p  on a.ptypeid=p.typeid '
    
		IF NOT (@chvBtypeID = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Btype b  on c.btypeid=b.typeid '
		IF NOT (@dealbtypeid = '00000' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #dealBtype b4  on c.dealbtypeid=b4.typeid '	    

		IF NOT (@chvETypeId = '' AND @METypeId = '00001')
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Etype  e  on c.etypeid=e.typeid '

		IF NOT (@chvKTypeID = '' AND @MKtypeid = '00000')  
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Ktype k  on a.ktypeid=k.typeid '

		IF NOT (@chvDTypeId = '' AND @MDtypeid='00000')
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Dtype d  on c.dtypeid=d.typeid '
				
		IF NOT (@STypeId = '' AND @MStypeid='00000')
				SELECT @KPSQL =@KPSQL+'  INNER JOIN  #Stype s  on c.stypeid=s.typeid '		

		SET @KPSQL+=' WHERE   c.Draft=0   AND c.ifYearBill= 0  AND a.qty <>0'
		IF	@chkRed='0'
			SET @KPSQL+='	AND c.redword=0'
		SET @KPSQL+='    
							AND c.BillDate>='''+@chvStartDate+'''
							AND c.BillDate<='''+@chvEndDate+'''
							AND c.explain like '+char(39)+'%'+@chvComment+'%'+char(39)+'
							AND c.Comment like '+char(39)+'%'+@chvZY+'%'+char(39)+'
							
		--=======================================================采购暂估开票数据==结束==========================
					'
				
--有暂估类单据才执行@zgSQL
IF EXISTS(SELECT TOP 1 1 FROM #Billtype WHERE Billtype IN ('400','401','404'))
BEGIN
	--插入暂估数据
	INSERT INTO #zgTable EXEC(@RKSQL+@THSQL+@KPSQL)
 	
 	--插入分组行 需要的名称和编号
	IF(@chrInputType = 'G') --商品
	BEGIN	
		INSERT INTO #InoutStockTable(pname,pcode,usercode)  
		SELECT pname,pcode,usercode
		FROM #zgTable  
		--SELECT pname,pcode FROM #zgTable
	END
	ELSE IF(@chrInputType = 'J') --供货商
	BEGIN
		INSERT INTO #InoutStockTable(bname,bcode,usercode)                      
		SELECT bname,bcode,usercode
		FROM #zgTable  
	END 
	
	--调试SQL -------------开始
	--入库
	--EXEC (@RKSQL)
	--PRINT (@RKSQL)
	
	--退货
	--EXEC (@THSQL)
	--PRINT (@THSQL)
	--开票
	--EXEC (@KPSQL)
	--PRINT (@KPSQL)
	 
	--调试SQL -------------结束
END
----------------------------------------------出暂估类数据--结束----------------------------------------

--最终数据
;WITH cte AS 
(
	SELECT 
		a.usercode,
		b.BillNumberID,
		CASE b.BillType
			WHEN 145 THEN -a.nQty
			ELSE a.nQty
		END AS nQty,
		a.ufullname,
		a.BillDate,
		a.nprice,
		CASE b.BillType
			WHEN 145 THEN -a.ntotal
			ELSE a.ntotal
		END AS ntotal,
		a.ntaxprice,
		CASE b.BillType
			WHEN 145 THEN -a.ntaxtotal
			ELSE a.ntaxtotal
		END AS ntaxtotal,
		b.cfullname,
		b.BillCode,
		b.billtype,
		(SELECT BillName FROM BillName WHERE Billtype = b.BillType) AS Billtypename,
		a.PTypeID,
		b.stypeid,
		b.btypeid,
		b.dealbtypeid,
		b.dtypeid,
		a.ktypeid,
		CASE b.BillType
			WHEN 145 THEN -a.Qty
			ELSE a.Qty
		END AS Qty,
		ISNULL(a.Price,0) as Price,
		CASE b.BillType
			WHEN 145 THEN -a.Total
			ELSE a.Total
		END AS Sum_Total,
		CASE b.BillType
			WHEN 145 THEN -a.Taxtotal
			ELSE a.Taxtotal
		END AS Sum_TaxTotal,
		a.taxprice,
		b.Checke,
		b.explain,
		b.Comment,
		a.dComment,
		ISNULL((b.Totalinmoney + ISNULL(b.completeTotal,0)),0) AS totalinMoney,
		(
			CASE b.BillType
				WHEN 145 THEN -a.Taxtotal
				ELSE a.Taxtotal
			END - 
			CASE b.BillType
				WHEN 145 THEN -a.Total
				ELSE a.Total
			END
		) AS Tax, 
		(
			CASE b.BillType
				WHEN 145 THEN -a.ntaxtotal
				ELSE a.ntaxtotal
			END - 
			CASE b.BillType
				WHEN 145 THEN -a.nTotal
				ELSE a.nTotal
			END
		) AS nTax,
		b.Redword,
		b.posttime,
		a.cargoid ,
		a.goodsnumber,
		CASE b.BillType
			WHEN 145 THEN -a.jlQty
			ELSE a.jlQty
		END AS jlQty,
		CASE b.BillType
			WHEN 145 THEN CASE a.brcjlQty  WHEN  CAST((a.qty/a.rate) AS NUMERIC(22,10)) THEN NULL ELSE -a.brcjlQty  END
			ELSE CASE a.brcjlQty  WHEN  CAST((a.qty/a.rate) AS NUMERIC(22,10)) THEN NULL ELSE brcjlqty END
		END AS brcjlQty,
		a.assistantfullname,
		a.baseunitfullname,
		b.currate,
		0 AS pqty,
		0 AS pricetotal,
		0 AS aqty,
		0 AS antantotal,
		a.fullname AS ifullname,
		b.etypeid,
		a.Bname,
		a.pname,--#InOutStocketTable里pname = fullname+usercode
		--2014-11-26 王刚添加 备注：报表列控制，功能，升级报表统计字段
		isnull(a.prePrice,0) AS prePrice,
		isnull(a.nprePrice,0) AS nprePrice,
		CASE b.BillType
			WHEN 145 THEN -a.pretotal
			ELSE a.pretotal
		END AS pretotal,
		CASE b.BillType
			WHEN 145 THEN -a.npretotal
			ELSE a.npretotal
		END AS npretotal,		
		CASE b.BillType
			WHEN 145 THEN -(a.pretotal - a.total)
			ELSE a.pretotal - a.total
		END AS discountge,
		CASE b.BillType
			WHEN 145 THEN -(a.npretotal - a.ntotal)
			ELSE a.npretotal - a.ntotal 
		END AS ndiscountge,
		a.Discount,
		a.TaxOK ,
		customid,
		customassist=dbo.F_GetCustomAssist(a.ptypeid,	CASE b.BillType
														WHEN 145 THEN -a.Qty
														ELSE a.Qty
														END ) 							 		
	FROM #InOutStockTable AS a 
	INNER JOIN #BillIndex AS b ON(a.BillNumberID = b.BillNumberID)
 	UNION ALL 
	SELECT *,customassist=dbo.F_GetCustomAssist(ptypeid,qty)  FROM #BJFLTEMP
	UNION ALL
	SELECT 
		usercode,
		BillNumberId,
		nQty,
		ufullname,
		BillDate,
		nPrice,
		nTotal,
		ntaxprice,
		nTaxTotal,
		acfullname AS cfullname,
		Billcode,
		BillType ,
		billname AS Billtypename,
		PtypeId,
		stypeid,
		btypeid,
		dealbtypeid,
		dtypeid,
		KtypeId,
		Qty,
		Price,
		Total AS  Sum_Total,
		TaxTotal AS Sum_TaxTotal,
		taxprice,
		checke,
		explain,
		Comment,
		dComment,
		totalinMoney,
		taxge AS  Tax, --税额
		ntaxge AS  ntax,
		redword,
		posttime,
		cargoid,
		goodsnumber,
		jlQty,
		CASE brcjlQty WHEN CAST((qty/rate) AS NUMERIC(22,10)) THEN NULL ELSE brcjlQty END brcjlQty,
		assistantfullname,
		baseunitfullname,
		currate,
		0 AS pqty,
		0 AS pricetotal,
		0 AS aqty,
		0 AS antantotal,
		ifullname,
		etypeid,
		bname,
		pname+pcode AS pname,--#zgTable pname=fullname=usercode
		prePrice,
		nprePrice,
		pretotal,
		npretotal,
		discountge,
		ndiscountge,
		Discount,
		Tax AS TaxOK,
		customid,
		customassist=dbo.F_GetCustomAssist(ptypeid,qty) 
	FROM #zgTable 
) 

--SELECT * FROM cte
SELECT T.*,MPs.usercode pmulusercode
FROM
(
	SELECT i.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head, SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,SysDiy25_head,
				SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy33_head,SysDiy34_head,SysDiy35_head,SysDiy36_head,SysDiy37_head,SysDiy38_head,SysDiy39_head,SysDiy40_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,SysDiy25,SysDiy26,
				SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,
				SysDiy33,SysDiy34,SysDiy35,SysDiy36,SysDiy37,SysDiy38,SysDiy39,SysDiy40
				,2 AS flag
				FROM cte  i left join Custom_BillIndex csindex on i.billnumberid=csindex.BillId and i.billtype=csindex.billtype
left join Custom_BillDetails csdetail on i.billnumberid=csdetail.BillId and i.billtype=csdetail.billtype AND i.customid=csdetail.Detailid --主要数据
	UNION ALL
	SELECT * FROM --小计
	(
		SELECT 
			 usercode,NULL AS BillNumberID,SUM(cte.nqty) AS nQty,NULL AS ufullname,NULL AS BillDate,NULL AS nprice,SUM(cte.ntotal) AS ntotal,NULL AS ntaxprice,SUM(cte.ntaxtotal) AS ntaxtotal,NULL AS cfullname,NULL AS BillCode,NULL AS billtype,'小计' AS Billtypename,NULL AS PTypeID,NULL AS stypeid,NULL AS btypeid,NULL AS dealbtypeid,NULL AS dtypeid,NULL AS ktypeid,
			SUM(cte.Qty) AS Qty,NULL AS Price,SUM(cte.Sum_Total) AS Sum_Total,SUM(cte.Sum_TaxTotal) AS Sum_TaxTotal,NULL AS taxprice,NULL AS Checke,NULL AS explain,NULL AS Comment,NULL AS dComment,NULL AS totalinMoney,SUM(cte.tax) AS Tax,SUM(cte.ntax) AS nTax,NULL AS Redword,NULL AS posttime,NULL AS cargoid,NULL AS goodsnumber,SUM(cte.jlqty) AS jlQty,SUM(cte.brcjlqty) AS brcjlQty,
			NULL AS assistantfullname,NULL AS baseunitfullname,NULL AS currate,NULL AS pqty,NULL AS pricetotal,NULL AS aqty,NULL AS antantotal,NULL AS ifullname,NULL AS etypeid,
			NULL AS bname,
			cte.pname,
			NULL AS prePrice,NULL AS nprePrice,NULL AS pretotal,NULL AS npretotal,NULL AS discountge,NULL AS ndiscountge,NULL AS Discount,NULL AS TaxOK ,
		NULL AS 	customid ,NULL AS customassist,
			NULL AS SysDiy1_head,NULL AS SysDiy2_head,NULL AS SysDiy3_head,NULL AS SysDiy4_head,NULL AS SysDiy5_head,NULL AS SysDiy6_head,NULL AS SysDiy7_head,
			NULL AS SysDiy8_head,NULL AS SysDiy9_head,NULL AS SysDiy10_head,NULL AS SysDiy11_head,NULL AS SysDiy12_head,NULL AS SysDiy13_head,NULL AS SysDiy14_head,
			NULL AS SysDiy15_head,NULL AS SysDiy16_head,NULL AS SysDiy17_head,NULL AS SysDiy18_head,NULL AS SysDiy19_head,NULL AS SysDiy20_head,NULL AS SysDiy21_head,NULL AS SysDiy22_head,NULL AS SysDiy23_head,NULL AS SysDiy24_head,NULL AS SysDiy25_head,
			NULL AS SysDiy26_head,NULL AS SysDiy27_head,NULL AS SysDiy28_head,NULL AS SysDiy29_head,NULL AS SysDiy30_head,NULL AS SysDiy31_head,NULL AS SysDiy32_head,
			NULL AS SysDiy33_head,NULL AS SysDiy34_head,NULL AS SysDiy35_head,NULL AS SysDiy36_head,NULL AS SysDiy37_head,NULL AS SysDiy38_head,NULL AS SysDiy39_head,NULL AS SysDiy40_head,
			NULL AS SysDiy1,NULL AS SysDiy2,NULL AS SysDiy3,NULL AS SysDiy4,NULL AS SysDiy5,
			NULL AS SysDiy6,NULL AS SysDiy7,NULL AS SysDiy8,NULL AS SysDiy9,NULL AS SysDiy10,NULL AS SysDiy11,NULL AS SysDiy12,
			NULL AS SysDiy13,NULL AS SysDiy14,NULL AS SysDiy15,NULL AS SysDiy16,
			NULL AS SysDiy17,NULL AS SysDiy18,NULL AS SysDiy19,NULL AS SysDiy20,NULL AS SysDiy21,NULL AS SysDiy22,NULL AS SysDiy23,NULL AS SysDiy24,NULL AS SysDiy25,NULL AS SysDiy26,
			NULL AS	SysDiy27,NULL AS SysDiy28,NULL AS SysDiy29,NULL AS SysDiy30,NULL AS SysDiy31,NULL AS SysDiy32,
			NULL AS	SysDiy33,NULL AS SysDiy34,NULL AS SysDiy35,NULL AS SysDiy36,NULL AS SysDiy37,NULL AS SysDiy38,NULL AS SysDiy39,NULL AS SysDiy40			
			,3 AS flag 
		FROM cte
		WHERE @chrInputType = 'G'
		GROUP BY cte.pname,cte.usercode
		UNION ALL
		SELECT 
			usercode,NULL AS BillNumberID,SUM(cte.nqty) AS nQty,NULL AS ufullname,NULL AS BillDate,NULL AS nprice,SUM(cte.ntotal) AS ntotal,NULL AS ntaxprice,SUM(cte.ntaxtotal) AS ntaxtotal,NULL AS cfullname,NULL AS BillCode,NULL AS billtype,'小计' AS Billtypename,NULL AS PTypeID,NULL AS stypeid,NULL AS btypeid,NULL AS dealbtypeid,NULL AS dtypeid,NULL AS ktypeid,
			SUM(cte.Qty) AS Qty,NULL AS Price,SUM(cte.Sum_Total) AS Sum_Total,SUM(cte.Sum_TaxTotal) AS Sum_TaxTotal,NULL AS taxprice,NULL AS Checke,NULL AS explain,NULL AS Comment,NULL AS dComment,NULL AS totalinMoney,SUM(cte.tax) AS Tax,SUM(cte.ntax) AS nTax,NULL AS Redword,NULL AS posttime,NULL AS cargoid,NULL AS goodsnumber,SUM(cte.jlqty) AS jlQty,SUM(cte.brcjlqty) AS brcjlQty,
			NULL AS assistantfullname,NULL AS baseunitfullname,NULL AS currate,NULL AS pqty,NULL AS pricetotal,NULL AS aqty,NULL AS antantotal,NULL AS ifullname,NULL AS etypeid,
			cte.bname,
			NULL AS pname,
			NULL AS prePrice,NULL AS nprePrice,NULL AS pretotal,NULL AS npretotal,NULL AS discountge,NULL AS ndiscountge,NULL AS Discount,NULL AS TaxOK ,
		
				NULL AS 	customid ,NULL AS customassist,
			NULL AS SysDiy1_head,NULL AS SysDiy2_head,NULL AS SysDiy3_head,NULL AS SysDiy4_head,NULL AS SysDiy5_head,NULL AS SysDiy6_head,NULL AS SysDiy7_head,
			NULL AS SysDiy8_head,NULL AS SysDiy9_head,NULL AS SysDiy10_head,NULL AS SysDiy11_head,NULL AS SysDiy12_head,NULL AS SysDiy13_head,NULL AS SysDiy14_head,
			NULL AS SysDiy15_head,NULL AS SysDiy16_head,NULL AS SysDiy17_head,NULL AS SysDiy18_head,NULL AS SysDiy19_head,NULL AS SysDiy20_head,NULL AS SysDiy21_head,NULL AS SysDiy22_head,NULL AS SysDiy23_head,NULL AS SysDiy24_head,NULL AS SysDiy25_head,
			NULL AS SysDiy26_head,NULL AS SysDiy27_head,NULL AS SysDiy28_head,NULL AS SysDiy29_head,NULL AS SysDiy30_head,NULL AS SysDiy31_head,NULL AS SysDiy32_head,
			NULL AS SysDiy33_head,NULL AS SysDiy34_head,NULL AS SysDiy35_head,NULL AS SysDiy36_head,NULL AS SysDiy37_head,NULL AS SysDiy38_head,NULL AS SysDiy39_head,NULL AS SysDiy40_head,
			NULL AS SysDiy1,NULL AS SysDiy2,NULL AS SysDiy3,NULL AS SysDiy4,NULL AS SysDiy5,
			NULL AS SysDiy6,NULL AS SysDiy7,NULL AS SysDiy8,NULL AS SysDiy9,NULL AS SysDiy10,NULL AS SysDiy11,NULL AS SysDiy12,
			NULL AS SysDiy13,NULL AS SysDiy14,NULL AS SysDiy15,NULL AS SysDiy16,NULL AS SysDiy17,NULL AS SysDiy18,NULL AS SysDiy19,NULL AS SysDiy20,NULL AS SysDiy21,NULL AS SysDiy22,NULL AS SysDiy23,NULL AS SysDiy24,NULL AS SysDiy25,NULL AS SysDiy26,
			NULL AS	SysDiy27,NULL AS SysDiy28,NULL AS SysDiy29,NULL AS SysDiy30,NULL AS SysDiy31,NULL AS SysDiy32,
			NULL AS	SysDiy33,NULL AS SysDiy34,NULL AS SysDiy35,NULL AS SysDiy36,NULL AS SysDiy37,NULL AS SysDiy38,NULL AS SysDiy39,NULL AS SysDiy40
			,3 AS flag 
		FROM cte
		WHERE @chrInputType <> 'G'
		GROUP BY cte.bname,cte.usercode
	) AS Q
	UNION ALL
	SELECT * FROM --usercode分组行
	(
		SELECT 
			pcode AS usercode,NULL AS BillNumberID,NULL AS nQty,NULL AS ufullname,NULL AS BillDate,NULL AS nprice,NULL AS ntotal,NULL AS ntaxprice,NULL AS ntaxtotal,NULL AS cfullname,
			'【' + pcode + '】' + pname AS BillCode,NULL AS billtype,NULL AS Billtypename,NULL AS PTypeID,NULL AS stypeid,NULL AS btypeid,NULL AS dealbtypeid,NULL AS dtypeid,NULL AS ktypeid,
				NULL AS Qty,NULL AS Price,NULL AS Sum_Total,NULL AS Sum_TaxTotal,NULL AS taxprice,NULL AS Checke,NULL AS explain,NULL AS Comment,NULL AS dComment,NULL AS totalinMoney,NULL AS Tax,NULL AS nTax,NULL AS Redword,NULL AS posttime,NULL AS cargoid,NULL AS goodsnumber,NULL AS jlQty,NULL AS brcjlQty,
				NULL AS assistantfullname,NULL AS baseunitfullname,NULL AS currate,NULL AS pqty,NULL AS pricetotal,NULL AS aqty,NULL AS antantotal,NULL AS ifullname,NULL AS etypeid,
			NULL AS bname,
			pname,
				NULL AS prePrice,NULL AS nprePrice,NULL AS pretotal,NULL AS npretotal,NULL AS discountge,NULL AS ndiscountge,NULL AS Discount,NULL AS TaxOK ,
			NULL AS 	customid ,NULL AS customassist,
			NULL AS SysDiy1_head,NULL AS SysDiy2_head,NULL AS SysDiy3_head,NULL AS SysDiy4_head,NULL AS SysDiy5_head,NULL AS SysDiy6_head,NULL AS SysDiy7_head,
			NULL AS SysDiy8_head,NULL AS SysDiy9_head,NULL AS SysDiy10_head,NULL AS SysDiy11_head,NULL AS SysDiy12_head,NULL AS SysDiy13_head,NULL AS SysDiy14_head,
			NULL AS SysDiy15_head,NULL AS SysDiy16_head,NULL AS SysDiy17_head,NULL AS SysDiy18_head,NULL AS SysDiy19_head,NULL AS SysDiy20_head,NULL AS SysDiy21_head,NULL AS SysDiy22_head,NULL AS SysDiy23_head,NULL AS SysDiy24_head,NULL AS SysDiy25_head,
			NULL AS SysDiy26_head,NULL AS SysDiy27_head,NULL AS SysDiy28_head,NULL AS SysDiy29_head,NULL AS SysDiy30_head,NULL AS SysDiy31_head,NULL AS SysDiy32_head,
			NULL AS SysDiy33_head,NULL AS SysDiy34_head,NULL AS SysDiy35_head,NULL AS SysDiy36_head,NULL AS SysDiy37_head,NULL AS SysDiy38_head,NULL AS SysDiy39_head,NULL AS SysDiy40_head,
			NULL AS SysDiy1,NULL AS SysDiy2,NULL AS SysDiy3,NULL AS SysDiy4,NULL AS SysDiy5,
			NULL AS SysDiy6,NULL AS SysDiy7,NULL AS SysDiy8,NULL AS SysDiy9,NULL AS SysDiy10,NULL AS SysDiy11,NULL AS SysDiy12,
			NULL AS SysDiy13,NULL AS SysDiy14,NULL AS SysDiy15,NULL AS SysDiy16,NULL AS SysDiy17,NULL AS SysDiy18,NULL AS SysDiy19,NULL AS SysDiy20,NULL AS SysDiy21,NULL AS SysDiy22,NULL AS SysDiy23,NULL AS SysDiy24,NULL AS SysDiy25,NULL AS SysDiy26,
			NULL AS	SysDiy27,NULL AS SysDiy28,NULL AS SysDiy29,NULL AS SysDiy30,NULL AS SysDiy31,NULL AS SysDiy32,
			NULL AS	SysDiy33,NULL AS SysDiy34,NULL AS SysDiy35,NULL AS SysDiy36,NULL AS SysDiy37,NULL AS SysDiy38,NULL AS SysDiy39,NULL AS SysDiy40
			,1 AS flag 
		FROM #InoutStockTable
		WHERE @chrInputType = 'G'
		GROUP BY pname,pcode
		UNION ALL
		SELECT 
			bcode AS usercode,NULL AS BillNumberID,NULL AS nQty,NULL AS ufullname,NULL AS BillDate,NULL AS nprice,NULL AS ntotal,NULL AS ntaxprice,NULL AS ntaxtotal,NULL AS cfullname,
			'【' + bcode + '】' + bname AS BillCode,NULL AS billtype,NULL AS Billtypename,NULL AS PTypeID,NULL AS stypeid,NULL AS btypeid,NULL AS dealbtypeid,NULL AS dtypeid,NULL AS ktypeid,
				NULL AS Qty,NULL AS Price,NULL AS Sum_Total,NULL AS Sum_TaxTotal,NULL AS taxprice,NULL AS Checke,NULL AS explain,NULL AS Comment,NULL AS dComment,NULL AS totalinMoney,NULL AS Tax,NULL AS nTax,NULL AS Redword,NULL AS posttime,NULL AS cargoid,NULL AS goodsnumber,NULL AS jlQty,NULL AS brcjlQty,
				NULL AS assistantfullname,NULL AS baseunitfullname,NULL AS currate,NULL AS pqty,NULL AS pricetotal,NULL AS aqty,NULL AS antantotal,NULL AS ifullname,NULL AS etypeid,
			bname,
			NULL AS pname,
				NULL AS prePrice,NULL AS nprePrice,NULL AS pretotal,NULL AS npretotal,NULL AS discountge,NULL AS ndiscountge,NULL AS Discount,NULL AS TaxOK ,
			NULL AS 	customid ,NULL AS customassist,
			NULL AS SysDiy1_head,NULL AS SysDiy2_head,NULL AS SysDiy3_head,NULL AS SysDiy4_head,NULL AS SysDiy5_head,NULL AS SysDiy6_head,NULL AS SysDiy7_head,
			NULL AS SysDiy8_head,NULL AS SysDiy9_head,NULL AS SysDiy10_head,NULL AS SysDiy11_head,NULL AS SysDiy12_head,NULL AS SysDiy13_head,NULL AS SysDiy14_head,
			NULL AS SysDiy15_head,NULL AS SysDiy16_head,NULL AS SysDiy17_head,NULL AS SysDiy18_head,NULL AS SysDiy19_head,NULL AS SysDiy20_head,NULL AS SysDiy21_head,NULL AS SysDiy22_head,NULL AS SysDiy23_head,NULL AS SysDiy24_head,NULL AS SysDiy25_head,
			NULL AS SysDiy26_head,NULL AS SysDiy27_head,NULL AS SysDiy28_head,NULL AS SysDiy29_head,NULL AS SysDiy30_head,NULL AS SysDiy31_head,NULL AS SysDiy32_head,
			NULL AS SysDiy33_head,NULL AS SysDiy34_head,NULL AS SysDiy35_head,NULL AS SysDiy36_head,NULL AS SysDiy37_head,NULL AS SysDiy38_head,NULL AS SysDiy39_head,NULL AS SysDiy40_head,
			NULL AS SysDiy1,NULL AS SysDiy2,NULL AS SysDiy3,NULL AS SysDiy4,NULL AS SysDiy5,
			NULL AS SysDiy6,NULL AS SysDiy7,NULL AS SysDiy8,NULL AS SysDiy9,NULL AS SysDiy10,NULL AS SysDiy11,NULL AS SysDiy12,
			NULL AS SysDiy13,NULL AS SysDiy14,NULL AS SysDiy15,NULL AS SysDiy16,NULL AS SysDiy17,NULL AS SysDiy18,NULL AS SysDiy19,NULL AS SysDiy20,NULL AS SysDiy21,NULL AS SysDiy22,NULL AS SysDiy23,NULL AS SysDiy24,NULL AS SysDiy25,NULL AS SysDiy26,
			NULL AS	SysDiy27,NULL AS SysDiy28,NULL AS SysDiy29,NULL AS SysDiy30,NULL AS SysDiy31,NULL AS SysDiy32,
			NULL AS	SysDiy33,NULL AS SysDiy34,NULL AS SysDiy35,NULL AS SysDiy36,NULL AS SysDiy37,NULL AS SysDiy38,NULL AS SysDiy39,NULL AS SysDiy40
			,1 AS flag 
		FROM #InoutStockTable
		WHERE @chrInputType <> 'G'
		GROUP BY bname,bcode
	) AS W
) AS T
LEFT JOIN PUserCode MPs ON MPs.PTypeID=T.PtypeId AND MPs.btypeid=T.dealbtypeid
ORDER BY CASE 
			WHEN @chrInputType = 'G' THEN T.pname 
			ELSE bname
		 END ASC ,
		 T.usercode ASC,
		 t.flag,
		 CASE @chrInputType -- 按单据类型排序
			WHEN 'G' THEN T.PTypeID
			WHEN 'J' THEN T.BTypeID
		 END DESC,
		 CASE @sortfield
			WHEN 'ByDate_a' THEN CAST(BillDate AS VARCHAR(100))		-- 按日期排序
			WHEN 'ByBillNo_a' THEN BillCode							-- 按单据编号排序
			WHEN 'ByBillType_a'	THEN CAST(BillType AS VARCHAR(100))	-- 按单据类型排序
			WHEN 'ByBillID_a'	THEN CAST(posttime AS VARCHAR(100))	-- 按单据真实过帐顺序排序
		 END,
		 CASE @sortfield
			WHEN 'ByDate_a' THEN BillCode
			WHEN 'ByBillType_a'	THEN CAST(BillDate AS VARCHAR(100))
		 END,
		 CASE @sortfield
			WHEN 'ByDate_d' THEN CAST(BillDate AS VARCHAR(100))
			WHEN 'ByBillNo_d' THEN BillCode
			WHEN 'ByBillType_d'	THEN CAST(BillType AS VARCHAR(100))
			WHEN 'ByBillID_d'	THEN CAST(posttime AS VARCHAR(100))
		 END DESC,
		 CASE @sortfield
			WHEN 'ByDate_d' THEN Billcode
		 END DESC,
		 CASE 
			WHEN @chrInputType = 'P' OR @chrInputType = 'G' 
			THEN CASE @sortfield
					WHEN 'ByBillType_d'	THEN BillDate
				 END
		 END DESC,
		 CASE 
			WHEN @chrInputType <> 'P' AND @chrInputType <> 'G' 
			THEN CASE @sortfield
					WHEN 'ByBillType_d'	THEN BillDate
				 END
		 END,
		 CASE 
			WHEN @sortfield <> 'ByDate_a' AND @sortfield <> 'ByBillNo_a' 
					AND @sortfield <> 'ByBillType_a' AND @sortfield <> 'ByBillID_a' 
					AND @sortfield <> 'ByDate_d' AND @sortfield <> 'ByBillNo_d' 
					AND @sortfield <> 'ByBillType_d' AND @sortfield <> 'ByBillID_d' 
			THEN posttime
		 END DESC
--调试SQL
-----------------------------------------------------------------------------------------------------


		 
-----------------------------------------------------------------------------------------------------
DROP TABLE #Billtype,#Ptype,#BJFLTEMP,#Billindex,#InoutStockTable,#PCategory
DROP TABLE #zgTable	,#Btype ,#Etype, #Ktype,#Dtype,#Stype,#dealbtype 
-----------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarFeeBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryCarFeeBill
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	返回车辆费用单明细
-- 时间：	2011-11-22
-- 作者：	陈守川

-- ========================================================================
CREATE PROCEDURE [dbo].[Web_QueryCarFeeBill]
(
	@BillNumberID	varchar(100)	-- 单据编号
)
--@encode$--

AS
SET NOCOUNT ON 

SELECT a.BillNumberId,
	   a.FeetypeId as typeid,
	   b.Fullname,
	   a.comment as base,
	   a.Total as total
FROM  CM_FeeBill a,CM_FeeType b 	
WHERE a.BillNumberID = @BillNumberID and a.FeetypeId=b.FeeTypeId
ORDER BY a.ID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarFeeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCarFeeDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-24
	描述：车辆费用情况明细
*/

CREATE PROCEDURE Web_QueryCarFeeDetail
(
	@OperatorId		VARCHAR(100),
	@ratypeid		varchar(50),
	@startdate		varchar(30),
	@enddate		varchar(30),
	@stypeid		varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

CREATE TABLE #Stype (TypeID VARCHAR(50))

--分支机构
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

declare @create_sql varchar(5000),
		@where_sql varchar(1000)=''
		

set @create_sql='select a.CarId,
					a.billnumberid,
					a.billtype,
					a.billdate,
					a.billcode,
					a.etypeid,
					d.platenumber,
					c.fullname as feetypename,
					b.total,
					b.comment as base
			from CM_FeeIndex a
			inner join CM_FeeBill b on b.BillNumberId = a.BillNumberId
			inner join CM_FeeType c on c.FeetypeId = b.FeetypeId
			inner join CM_CarInfo d on a.carid = d.typeid
			inner join #Stype s on s.typeid = a.stypeid
			where a.BillNumberId=b.BillNumberId and c.FeeTypeId=b.FeetypeId and a.CarId=d.TypeId and a.CarId='+@ratypeid+
			' and a.billdate>='+CHAR(39)+CONVERT(varchar(30),@startdate)+CHAR(39)+
			' and a.billdate<='+CHAR(39)+CONVERT(varchar(30),@enddate)+CHAR(39)+' '+@where_sql+
			' order by a.billdate desc,a.billcode desc'
--print(@create_sql)
exec(@create_sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarFeeIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryCarFeeIndex
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/*
作者：陈守川
时间：2011-11-22
描述:查询车辆费用单主表数据
*/
CREATE PROCEDURE Web_QueryCarFeeIndex 
( 
	@BillNumberId numeric(10,0)
)

--@encode$--
AS
SET NOCOUNT ON 

SELECT	a.BillNumberId,
		a.BillCode,
		a.BillDate,
		a.BillType,
		a.dtypeid,
		a.CarId as ratypeid,
		a.Totalmoney,
		a.DtypeID,
		d.FullName AS dfullname,
		a.etypeid,
		e.FullName AS efullname,
		a.Stypeid,
		s.FullName AS sfullname,
		e1.FullName  AS checke,
		a.comment,
		a.explain,
		c.Platenumber	
FROM	CM_FeeIndex a

LEFT JOIN CM_CarInfo c ON c.TypeId = a.CarId 
INNER JOIN employee e1 ON e1.TypeID = a.Checke
INNER JOIN employee e ON a.Etypeid = e.TypeID
INNER JOIN Department D ON a.DtypeId = D.TypeID
INNER JOIN Stype S ON a.STypeID = S.TypeID
WHERE a.BillNumberID = @BillNumberId
ORDER BY a.BillDate DESC, a.BillNumberId ASC 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarFeeTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCarFeeTotal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-24
	描述：车辆费用情况汇总
*/

CREATE PROCEDURE Web_QueryCarFeeTotal
(
	@OperatorId		VARCHAR(100),
	@startdate		varchar(30),
	@enddate		varchar(30),
	@stypeid		varchar(50)='',
	@ratypeid		varchar(50)='',
	@pageNo			int,
	@pageSize		int=10,
	@isPrintall	    int=0,
	@colCount  int output
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

CREATE TABLE #Stype (TypeID VARCHAR(50))

--分支机构
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DECLARE @where_sql VARCHAR(2000)='',
		@create_sql varchar(max),
		@feesql		VARCHAR(8000)
		
--临时表用来对费用类型进行分页
CREATE TABLE #feetype(feetypeid INT,fullname VARCHAR(100))
CREATE TABLE #feetypepage(feetypeid INT,fullname VARCHAR(100))
CREATE TABLE #FeeTotal(carid INT,platenumber VARCHAR(50),stypeid VARCHAR(50),feetypeid INT,fullname VARCHAR(100),total  NUMERIC(24, 10) )


INSERT #feetype 
	SELECT FeeTypeId,Fullname
	FROM   CM_FeeType
		
--费用类型的翻页,对应页面上的左右翻页

SET @feesql=' INSERT #feetypepage	
	SELECT TOP '+ CAST(@pageSize AS VARCHAR(50)) + ' feetypeid,fullname
	FROM #feetype
	WHERE feetypeid NOT IN
	(
	SELECT TOP '+CAST((@pageNo-1)*@pageSize AS VARCHAR(50))+' feetypeid FROM #feetype ORDER BY feetypeid
	)
	ORDER BY feetypeid'
EXEC(@feesql)

  SET @create_sql='INSERT INTO #FeeTotal 
								    (
								    carid,
									platenumber,
									stypeid,
									feetypeid,
									fullname,
									total
									)
							SELECT  a.CarId,
									d.Platenumber,
									a.Stypeid,
									b.feetypeid,
									c.Fullname,
									b.total
			FROM CM_FeeIndex a
			inner join CM_FeeBill b on b.BillNumberId=a.BillNumberId
			inner join #feetype c on c.feetypeid = b.feetypeid
			inner join CM_CarInfo d on d.typeid = a.CarId
			inner join #Stype s on s.typeid = a.stypeid
			WHERE a.billdate>='+CHAR(39)+CONVERT(varchar(30),@startdate)+CHAR(39)+
			' AND a.billdate<='+CHAR(39)+CONVERT(varchar(30),@enddate)+CHAR(39)
IF @ratypeid<>''
SET @create_sql =@create_sql +'and a.CarId='+CHAR(39)+@ratypeid+CHAR(39)	
EXEC(@create_sql)

--创建结果临时表
CREATE TABLE #result(carid INT,platenumber VARCHAR(50),stypeid VARCHAR(50),totalmoney  NUMERIC(24, 10) )

SET @create_sql='
INSERT INTO #result
				(
				carid,
				platenumber,
				stypeid,
				totalmoney
				)
SELECT	DISTINCT c.TypeId,
				c.Platenumber,
				a.Stypeid,
				0
FROM CM_FeeIndex a
inner join CM_CarInfo c on c.typeid = a.CarId
inner join #Stype s on s.typeid = a.stypeid '
IF @ratypeid<>''
SET @create_sql =@create_sql +' where a.CarId='+CHAR(39)+@ratypeid+CHAR(39)
EXEC(@create_sql)

	--如果查询日期大于单据日期,则不查询出任何数据
	IF NOT EXISTS(SELECT carid FROM #FeeTotal)
	BEGIN
		DELETE #result
		DELETE #feetypepage
	END


---------------------游标构造动态表头 并填值 START -------------------------------------------------
DECLARE @cursfeetypeid VARCHAR(50),
		@cursfullname VARCHAR(50),
		@sql VARCHAR(8000)
		
IF @isPrintall=0  --不是打印，分页
	BEGIN
		DECLARE CurFeeType CURSOR FOR
		SELECT  DISTINCT feetypeid,fullname
		FROM #feetypepage
	END
ELSE --打印
	BEGIN
		DECLARE CurFeeType CURSOR FOR
		SELECT  DISTINCT feetypeid,fullname
		FROM #feetype
	END
SET @colcount=0
OPEN CurFeeType
FETCH NEXT FROM CurFeeType INTO @cursfeetypeid,@cursfullname
WHILE @@Fetch_Status = 0 
BEGIN
	SET @sql='alter table #result add  ['+ @cursfullname +'] varchar(200) null'
	EXEC(@sql)
	
	--新构造的表中填数据
	
	SET @sql='UPDATE #result '
	SET @sql=@sql+'	SET '+'['+@cursfullname+']'+'=(SELECT isnull(SUM(b.total),0)'
	SET @Sql=@Sql+'	FROM #FeeTotal b '
	SET @Sql=@Sql+'	WHERE b.carid=#result.carid and b.feetypeid='+@cursfeetypeid+' and b.stypeid =#result.stypeid)'
	--print(@sql)
	EXEC(@sql)
	SET	@colcount= @colcount+1
	FETCH NEXT FROM CurFeeType INTO @cursfeetypeid,@cursfullname
END
CLOSE CurFeeType
DEALLOCATE CurFeeType

--SELECT * FROM #result
--算合计
UPDATE #result SET totalmoney=
		   (SELECT SUM(#FeeTotal.total)
			FROM #FeeTotal
			WHERE #FeeTotal.carid=#result.carid
			AND #FeeTotal.stypeid = #result.stypeid
			)
---------------------游标构造动态表头 并填值 END   -------------------------------------------------

SELECT *,totalmoney as '合计' FROM #result 

--计算费用类型的列数
SET	@colcount=(SELECT COUNT(*) FROM #feetype)				
					
DROP TABLE #result,#feetype,#feetypepage,#stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCargoDistributeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCargoDistributeLine]
GO

/*
	作者：彭勇	
	日期：2012-06-19
	描述：货位分布线性表
*/
CREATE PROCEDURE Web_QueryCargoDistributeLine
(
	@OperatorId			 	 VARCHAR(50),		-- 当前操作员ID
	@stypeid             	 VARCHAR(200),     --分支机构ID
    @ktypeid             	 VARCHAR(200),     --仓库ID
    @cargoid             	 VARCHAR(max),     --货位ID
    @PTypeId 		         VARCHAR(100)='00000',
    @PageRows 			 	 INT=14,
	@StockPageRows		 	 INT=10,
	@GoPageNo 			 	 INT=0,        
	@Flag 					 INT=1,
	@Index 					 INT=1,
	@Sort 					 CHAR(4)='ASC',
	@unitconvert             VARCHAR(10),    --多单位种类
	@StockPageNo 			 INT,
	@szEntryCode			 VARCHAR(200)='',
	@PTypeIdMx				VARCHAR(100),
	@UserCode 				VARCHAR(200),
	@FullName 				VARCHAR(200) ,
	@colCount               int output  ,
	@showzeroqty           INT =0 ,  --是否显示零单据
	@showstockstop INT =0 --是否显示停用仓库数据 1为不显示 0为显示
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql varchar(max)=''
DECLARE @Condition varchar(MAX)	
------------------------------------------------------权限检查---------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
------------------------------------------------------权限检查---------------------------------------------------------------
---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	VARCHAR(100))
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
	IF  @showstockstop=0
		INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM  F_GetManDetailKTypeSType(@OperatorID) k 
		INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
		INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	
 ELSE
 	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM  F_GetManDetailKTypeSType(@OperatorID) k 
	INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
	INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	
	INNER JOIN dbo.Stock ss ON a.TypeId = ss.typeId WHERE deleted=0

--货位
CREATE TABLE #GetSelectCargoid(cargoid VARCHAR(100),typeid VARCHAR(100))

IF @cargoid = '00000' OR @cargoid = '' OR @cargoid = '%'
				INSERT INTO #GetSelectCargoid(cargoid,typeid) SELECT CargoID,KtypeID FROM CargoType a
				INNER JOIN #GetManKTypeId b ON a.KtypeID=b.TypeId
			ELSE
				INSERT INTO #GetSelectCargoid(cargoid,typeid)
				SELECT 	A.CargoID ,a.KtypeID
				FROM 	CargoType A, 
						(SELECT A FROM dbo.F_Split(@cargoid,',')) B 
						,#GetManKTypeId c 
				WHERE	A.CargoID = B.A AND c.typeid =a.ktypeid

--计算总的动态列数
SET @colCount= (select count(*) from  #GetSelectCargoid)

-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),
        @temprice   VARCHAR(2000)
IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/R3.rate',
		@UnitName = 'U3.fullname',
		@temprice='g.price*R3.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/R2.rate',
		@UnitName = 'U2.fullname',
		@temprice='g.price*R2.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/R4.rate',
		@UnitName = 'U4.fullname',
		@temprice='g.price*R4.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'U1.fullname',
		@temprice='g.price',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','5,1','')
END
----------多单位计算End---------
-----------------------------------------------------------------------------------------------------------------------------


IF @UserCode IS NULL OR @UserCode=''
	SELECT @UserCode='%'
ELSE
 	SELECT @UserCode='%'+@UserCode+'%'

IF @FullName IS NULL OR @FullName=''
 	SELECT @FullName='%'
ELSE
 	SELECT @FullName='%'+@FullName+'%'

IF @PTypeIdMx = '00000'
	SET @PTypeIdMx = ''
CREATE TABLE #ptype
	(
		[typeId] 		[varchar] (100) NOT NULL,
		[parid] 		[varchar] (100) NOT NULL,
		[总计账面库存] 	 NUMERIC(24, 10) ,
		[总计成本均价] 	 NUMERIC(24, 10) ,
		[总计成本金额] 	 NUMERIC(24, 10) ,
		[总计浮动数量]	 NUMERIC(24, 10) ,
		unitname         VARCHAR(2000),--计量单位
	    assistantname    VARCHAR(2000),--浮动单位
	    basename		 VARCHAR(2000),--基本单位	
	    [总计自定义辅助数量] VARCHAR(50)  
	)
DECLARE @SonNum INT,@GsSql VARCHAR(1000),@SQLSELECT VARCHAR(MAX)=''
SELECT @SonNum = SonNum FROM PType WHERE TypeId = @PTypeId



IF @showzeroqty=0
	BEGIN

	SET @SQLSELECT = '    
		SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
				q.TypeID,
				q.parid,
				0,'+@UnitName+',u5.fullname,u1.fullname
		FROM    F_GetManPType('''+@OperatorID+''') q inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
		WHERE  	q.TypeID <> ''00000''	
				and p1.IsService=0
				and p1.iscombinationproduct = 0 
				AND q.UserCode NOT IN                    
				(
					SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' UserCode
					FROM	F_GetManPType('''+@OperatorID+''')
					WHERE   TypeID <> ''00000'' and sonnum=0
					AND [UserCode] LIKE ''%'+@UserCode+'%''
											AND [FullName] LIKE ''%'+@FullName+'%''
											AND ((ISNULL('''+@szEntryCode+''','''')<>'''' AND EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=typeId AND E.EntryCode LIKE ''%'+@szEntryCode+'%'')) OR ISNULL('''+@szEntryCode+''','''')='''')
											AND TypeId LIKE '''+@PTypeIdMx+'%''	
					ORDER BY UserCode
				) 
				and  q.sonnum=0
				AND q.[UserCode] LIKE ''%'+@UserCode+'%''
				AND q.[FullName] LIKE ''%'+@FullName+'%''
				AND ((ISNULL('''+@szEntryCode+''','''')<>'''' AND EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=q.typeId AND E.EntryCode LIKE ''%'+@szEntryCode+'%'')) OR ISNULL('''+@szEntryCode+''','''')='''')
				AND q.TypeId LIKE '''+@PTypeIdMx+'%''	
		ORDER BY q.UserCode '
		
	END
ELSE
	BEGIN
	SET @SQLSELECT = '    
		SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
				q.TypeID,
				q.parid,
				0,'+@UnitName+',u5.fullname,u1.fullname
		FROM    F_GetManPType('''+@OperatorID+''')q   
	
		
			INNER JOIN GoodsStocks_Qty Q1 ON Q1.ptypeid = q.typeid 
			inner join #GetSelectCargoid d on q1.cargoid=d.cargoid	 inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
		 -- LEFT JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') x ON q.typeID=x.typeID
		WHERE  	q.TypeID <> ''00000''	
		        and p1.IsService=0
		        and p1.iscombinationproduct = 0
				AND q.UserCode NOT IN                    
				(
					SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' UserCode
					FROM	F_GetManPType('''+@OperatorID+''')
					WHERE   
						TypeID <> ''00000'' 
						and sonnum=0
						AND [UserCode] LIKE ''%'+@UserCode+'%''
						AND [FullName] LIKE ''%'+@FullName+'%''
						AND ((ISNULL('''+@szEntryCode+''','''')<>'''' AND EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=typeId AND E.EntryCode LIKE ''%'+@szEntryCode+'%'')) OR ISNULL('''+@szEntryCode+''','''')='''')
						AND TypeId LIKE '''+@PTypeIdMx+'%''	
					ORDER BY UserCode
				) 
				and  q.sonnum=0
				AND q.[UserCode] LIKE ''%'+@UserCode+'%''
				AND q.[FullName] LIKE ''%'+@FullName+'%''
				AND ((ISNULL('''+@szEntryCode+''','''')<>'''' AND EXISTS(SELECT TOP 1 1 FROM PType_EntryCode_Ext E WHERE E.Ptypeid=q.typeId AND E.EntryCode LIKE ''%'+@szEntryCode+'%'')) OR ISNULL('''+@szEntryCode+''','''')='''')
				AND q.TypeId LIKE '''+@PTypeIdMx+'%''	
				and q1.qty!=0 and q1.qty is not null	group by q.typeid,q.parid,q.usercode,u5.fullname,u1.fullname,'+@UnitName+	
		' ORDER BY q.UserCode '
	END
					
	 SELECT @SQLSELECT='INSERT INTO #ptype	
					(
						[typeid],
						[parid],
						[总计浮动数量],
					     unitname,
						assistantname,
						basename
					)'+@SQLSELECT				
					
--PRINT @SQLSELECT
EXEC(@SQLSELECT)

CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)

DECLARE @Xjkang varchar(MAX)
SET @Xjkang = 'INSERT INTO #TempStock1 SELECT a.cargoid,a.UserCode,a.FullName FROM CargoType a  inner join #GetSelectCargoid b on a.cargoid =b.cargoid WHERE  ktypeid IN (SELECT * FROM #GetManKTypeId)  ORDER BY UserCode '
EXEC(@Xjkang)
--print @xjkang
SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(@StockPageRows AS varchar(50)) + ' 
				TypeID,				
				UserCode,			
				FullName
	    FROM    #TempStock1 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@StockPageNo-1) * @StockPageRows AS varchar(50)) + ' UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '

EXEC(@xjkang)

CREATE TABLE #GsStock
(
	PTypeId	VARCHAR(100),
	Qty	 NUMERIC(24, 10) ,
	price  NUMERIC(24, 10) ,
	total  NUMERIC(24, 10) ,
	KTypeID	VARCHAR(100),
	NQty  NUMERIC(24, 10) ,
	cargoid int	

)

SET @GsSql='
	INSERT INTO #GsStock
	SELECT	P.TypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,
			ISNULL('+@temprice+',0) as price,
			ISNULL('+@temprice+',0) *ISNULL(SUM('+@Qty+'),0) as total,
			G.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty,
			q.cargoid
	FROM	#ptype p inner join ptype p1 on p1.typeid=p.typeid
INNER JOIN (select ptypeid,ktypeid,case when sum(qty)=0 then 0 else  sum(total)/sum(qty) end as price FROM GoodsStocks group by ptypeid,ktypeid)
	g  ON g.PTypeId LIKE p.TypeId+''%'' 
	INNER JOIN GoodsStocks_Qty Q ON Q.ptypeid = G.ptypeid  and  g.ktypeid=q.ktypeid
	inner join #GetSelectCargoid d on q.cargoid=d.cargoid'+ @tmptab
	SET @GsSql = @GsSql + '	GROUP BY P.TypeId,G.KTypeID,q.cargoid,'+@temprice
	
	--PRINT @GsSql
EXEC(@GsSql)
--SELECT * FROM #ptype
--SELECT * FROM #GsStock

SET @Sql = '
	UPDATE #ptype
	SET	[总计账面库存]=B.Qty,
		[总计成本均价]=(CASE ISNULL(B.Qty,0) WHEN 0 THEN 0 ELSE ISNULL(B.total,0) / ISNULL(B.Qty,0) END),
		[总计成本金额]=B.total,
		[总计浮动数量]=B.nqty  ,
		[总计自定义辅助数量]=dbo.F_GetCustomAssist(A.TypeId, B.Qty)
	FROM #ptype a
	INNER JOIN (
				SELECT	A.TypeId,
						SUM(ISNULL(G.Qty,0)) AS Qty,
						SUM(ISNULL(G.price,0)) AS price,
						SUM(ISNULL(G.total,0)) AS total,
						sum(isnull(g.nqty,0))as nqty
				FROM 	#ptype A
				LEFT JOIN #GsStock G ON  G.PTypeId = A.TypeId
				GROUP BY A.TypeId
				)B ON A.TypeId = B.TypeId'

--SELECT * FROM #ptype

--SELECT * FROM #GsStock
--SELECT * FROM #TempStock

--PRINT(@Sql)
EXEC(@Sql)

DECLARE @TempTable VARCHAR(100)
SELECT @TempTable='##Temp'+REPLACE(NEWID(),'-','')

SET @SQL='	SELECT 	A.[typeId],
					A.[parid],
					A.[总计账面库存],
					a.unitname,
					A.[总计成本均价],
					A.[总计成本金额],
					a.[总计浮动数量],
					a.assistantname,
					a.basename,
					a.[总计自定义辅助数量],
					D.*
			FROM #ptype A 
			LEFT JOIN (
					SELECT  C.TYPEID AS PTYPEID'	
				
SELECT	@SQL=@SQL + ',['+FullName+'账面库存]=SUM(CASE WHEN  b.cargoid = '''+typeid+''' THEN b.Qty ELSE 0 END)
                     ,['+FullName+'浮动数量]=SUM(CASE WHEN  b.cargoid = '''+typeid+''' THEN b.NQty ELSE 0 END)
					
					,['+FullName+'成本均价]=CAST(SUM(CASE 
													WHEN  b.cargoid = '''+typeid+'''
														THEN (
															CASE ISNULL(b.Qty,0) 										
																WHEN 0 
																	THEN 0 
																ELSE  
																	ISNULL(B.total,0)/ISNULL(b.Qty,0) 
																END )
														ELSE 0
												END) AS DECIMAL(18,4))
						,['+FullName+'成本金额]=SUM(CASE WHEN  b.cargoid = '''+typeid+''' THEN ISNULL(B.total,0) ELSE 0 END)'
					  +',['+FullName+'自定义辅助数量]=dbo.F_GetCustomAssist(C.TYPEID, SUM(CASE WHEN  b.cargoid = '''+typeid+'''  THEN  b.Qty  ELSE 0 END)) '	
						FROM  #TempStock order by UserCode
SET @Sql = @Sql +'
					FROM #ptype c
					LEFT JOIN (
								SELECT	e.TypeId,
	 									g.ktypeid,
										SUM(ISNULL(G.Qty,0)) AS Qty,
										SUM(ISNULL(G.price,0)) as price,
										SUM(ISNULL(G.total,0)) as total,
										SUM(ISNULL(G.NQty,0)) AS NQty,
										g.cargoid
								FROM 	#ptype e
								LEFT JOIN #GsStock G ON G.PTypeId =e.TypeId
								GROUP BY e.TypeId,g.ktypeid,g.cargoid
								) b on c.typeid=b.typeid
						GROUP BY c.typeid
						)D ON A.TypeId = D.ptypeId'	 
	IF @Flag=0
		SELECT @SQL=@SQL+'order by '+CONVERT(varchar(4),@INDEX)+@Sort
	--PRINT(@SQL)
	EXEC(@sql)	 


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCargoDistributeList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCargoDistributeList]
GO

/*
	作者：彭勇	
	日期：2012-06-19
	描述：货位分布树形表
*/
CREATE PROCEDURE Web_QueryCargoDistributeList
(
	@OperatorId			 	 VARCHAR(50),		-- 当前操作员ID
	@stypeid             	 VARCHAR(200),     --分支机构ID
    @ktypeid             	 VARCHAR(200),     --仓库ID
    @cargoid             	 VARCHAR(max),     --货位ID
    @PTypeId 		         VARCHAR(100)='00000',
    @PageRows 			 	 INT=14,
	@StockPageRows		 	 INT=10,
	@GoPageNo 			 	 INT=0,        
	@Flag 					 INT=1,
	@Index 					 INT=1,
	@Sort 					 CHAR(4)='ASC',
	@unitconvert             VARCHAR(10),    --多单位种类
	@StockPageNo 	INT,
	@colCount               int OUTPUT,
	@showstockstop INT =0 --是否显示停用仓库数据 1为不显示 0为显示
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql varchar(max)=''
------------------------------------------------------权限检查---------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
------------------------------------------------------权限检查---------------------------------------------------------------
---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	VARCHAR(100))
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

CREATE TABLE #ptype1(TypeId	VARCHAR(100))
	INSERT INTO #ptype1(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)
	

	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
	IF  @showstockstop=0
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
    INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	
    ELSE
    INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
    INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	 INNER JOIN dbo.Stock ss ON a.TypeId = ss.typeId WHERE deleted=0

--货位
CREATE TABLE #GetSelectCargoid(cargoid VARCHAR(100),typeid VARCHAR(100))

IF @cargoid = '00000' OR @cargoid = '' OR @cargoid = '%'
				INSERT INTO #GetSelectCargoid(cargoid,typeid) SELECT CargoID,KtypeID FROM CargoType a
				INNER JOIN #GetManKTypeId b ON a.KtypeID=b.TypeId
			ELSE
				INSERT INTO #GetSelectCargoid(cargoid,typeid)
				SELECT 	A.CargoID ,a.KtypeID
				FROM 	CargoType A, 
						(SELECT A FROM dbo.F_Split(@cargoid,',')) B 
						,#GetManKTypeId c 
				WHERE	A.CargoID= B.A  AND c.typeid =a.ktypeid


--计算总的动态列数
SET @colCount= (select count(*) from  #GetSelectCargoid)
-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),
        @temprice   VARCHAR(2000)
--SET @tmptab=' LEFT JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') x ON q.ptypeID=x.typeID'
IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/R3.rate',
		@UnitName = 'U3.fullname',
		@temprice='g.price*R3.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/R2.rate',
		@UnitName = 'U2.fullname',
		@temprice='g.price*R2.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/R4.rate',
		@UnitName = 'U4.fullname',
		@temprice='g.price*R4.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'U1.fullname',
		@temprice='g.price',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','5,1','')
END
----------多单位计算End---------
-------------------------------------------------------------------------------------------------------------------------------

--处理货位
DECLARE @cargoids 		varchar(MAX),
		@Where_cargoId	varchar(MAX)
SET @Where_cargoId = ''

		IF @Where_cargoId = ''
			SET @Where_cargoId = ' AND (TypeId LIKE '+char(39)+@cargoids+'%'+char(39)
		ELSE
			SET @Where_cargoId = @Where_cargoId + ' OR TypeId LIKE '+char(39)+@cargoids+'%'+char(39)

CREATE TABLE #ptype
	(
		[typeId] 		[varchar] (100) NOT NULL,
		[parid] 		[varchar] (100) NOT NULL,
		[父节点] 		VARCHAR(100) NOT NULL,
		[总计账面库存] 	 NUMERIC(24, 10) ,
		[总计成本均价] 	 NUMERIC(24, 10) ,
		[总计成本金额] 	 NUMERIC(24, 10) ,
		[总计浮动数量]	 NUMERIC(24, 10) ,
		unitname         VARCHAR(2000),--计量单位
	    assistantname    VARCHAR(2000),--浮动单位
	    basename		 VARCHAR(2000)--基本单位	
	)
DECLARE @SonNum INT,@GsSql VARCHAR(MAX),@SQLSELECT VARCHAR(MAX)=''
SELECT @SonNum = SonNum FROM PType WHERE TypeId = @PTypeId

SET @SQLSELECT = '    
    SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
			q.TypeID,
			q.parid,
			q.SonNum,
			0,'+@UnitName+',u5.fullname,u1.fullname
    FROM    F_GetManPType('''+@OperatorID+''') q INNER JOIN PTYPE P1 ON P1.TYPEID=Q.TYPEID '+@tmptab+' 
    --LEFT JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') x ON q.typeID=x.typeID    
    WHERE  	q.TypeID <> ''00000''	
            and p1.IsService=0
            and p1.iscombinationproduct = 0
			AND q.UserCode NOT IN                    
			(
				SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' UserCode
				FROM	F_GetManPType('''+@OperatorID+''')
				WHERE   TypeID <> ''00000''
				      
						AND '+CASE @SonNum WHEN 0 THEN 'TYPEID' ELSE  'ParId' END + '='+char(39)+@PTypeId+char(39)+ '
					
				ORDER BY UserCode
			) 
			AND '+CASE @SonNum WHEN 0 THEN 'q.TYPEID' ELSE  'q.ParId' END + '='+char(39)+@PTypeId+char(39)+'
		
    ORDER BY q.UserCode '
	 SELECT @SQLSELECT='INSERT INTO #ptype	
					(
						[typeid],
						[parid],
						[父节点],
						[总计浮动数量],
						unitname,
						assistantname,
						basename
					)'+@SQLSELECT
--PRINT(@SQLSELECT)
EXEC(@SQLSELECT)

CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)



DECLARE @Xjkang varchar(MAX)
SET @Xjkang = 'INSERT INTO #TempStock1 SELECT a.cargoid,a.UserCode,a.FullName FROM CargoType a  inner join #GetSelectCargoid b on a.cargoid =b.cargoid  WHERE  ktypeid IN (SELECT * FROM #GetManKTypeId)  ORDER BY UserCode '


EXEC(@Xjkang)

SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(@StockPageRows AS varchar(50)) + ' 
				TypeID,				
				UserCode,			
				FullName
	    FROM    #TempStock1 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@StockPageNo-1) * @StockPageRows AS varchar(50)) + ' UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '

EXEC(@xjkang)

CREATE TABLE #GsStock
(
	PTypeId	VARCHAR(100),
	Qty	 NUMERIC(24, 10) ,
	price  NUMERIC(24, 10) ,
	total  NUMERIC(24, 10) ,
	KTypeID	VARCHAR(100),
	NQty  NUMERIC(24, 10) ,
	cargoid int	

)

SET @GsSql='
	INSERT INTO #GsStock
	SELECT	P.TypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,
			ISNULL('+@temprice+',0) as price,
			ISNULL('+@temprice+',0) *ISNULL(SUM('+@Qty+'),0) as total,
			g.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty,
			q.cargoid
	FROM	#ptype1 p INNER JOIN PTYPE P1 ON P1.TYPEID=P.TYPEID
	INNER JOIN (
					SELECT	ptypeid,
							ktypeid,
							case when sum(qty)=0 then 0 else  sum(total)/sum(qty) end as price 
					FROM	GoodsStocks 
					GROUP BY ptypeid,ktypeid)
			 g  ON g.PTypeId =p.TypeId
	INNER JOIN GoodsStocks_Qty Q ON Q.ptypeid = G.ptypeid  and  g.ktypeid=q.ktypeid
	inner join #GetSelectCargoid d on q.cargoid=d.cargoid'+ @tmptab
	SET @GsSql = @GsSql + '	GROUP BY P.TypeId,g.KTypeID,q.cargoid,'+@temprice
	
--PRINT @GsSql
EXEC(@GsSql)


SET @Sql = '
	UPDATE #ptype
	SET	[总计账面库存]=B.Qty,
		[总计成本均价]=(CASE ISNULL(B.Qty,0) WHEN 0 THEN 0 ELSE ISNULL(B.total,0) / ISNULL(B.Qty,0) END),
		[总计成本金额]=B.total,
		[总计浮动数量]=B.nqty
	FROM #ptype a
	inner join 
	(select A.typeid,sum(b.qty)qty,sum(total)total,sum(nqty)nqty from #ptype a 
	INNER JOIN (
				SELECT	A.TypeId,
						SUM(ISNULL(G.Qty,0)) AS Qty,
						--SUM(ISNULL(G.price,0)) AS price,
						SUM(ISNULL(G.total,0)) AS total,
						sum(isnull(g.nqty,0))as nqty
				FROM 	#ptype1 A
				LEFT JOIN #GsStock G ON  G.PTypeId = A.TypeId
				GROUP BY A.TypeId
				)B ON b.TypeId LIKE a.TypeId+''%''  
	group by a.typeid
	) b on a.typeid=b.typeid '
	
--PRINT @SQL
EXEC(@Sql)



DECLARE @TempTable VARCHAR(100)
SELECT @TempTable='##Temp'+REPLACE(NEWID(),'-','')

SET @SQL='	SELECT 	A.[typeId],
					A.[parid],
					A.[父节点],
					A.[总计账面库存],
					a.unitname,
					A.[总计成本均价],
					A.[总计成本金额],
					a.[总计浮动数量],
					a.assistantname,
					a.basename,
					D.*
			FROM #ptype A 
			LEFT JOIN (
					SELECT  C.TYPEID AS PTYPEID'	
				
SELECT	@SQL=@SQL + ',['+FullName+'账面库存]=SUM(CASE WHEN  b.cargoid = '''+typeid+''' THEN b.Qty ELSE 0 END)
                     ,['+FullName+'浮动数量]=SUM(CASE WHEN  b.cargoid = '''+typeid+''' THEN b.NQty ELSE 0 END)
					
					,['+FullName+'成本均价]= case when sum(CAST(CASE  WHEN  b.cargoid = '''+typeid+'''
														then
														case when ISNULL(b.Qty,0)<>0					
																	THEN b.qty
																ELSE  
																	0
																END 
													   end
												 AS DECIMAL(18,4)))=0 then 0 
												 else
												   sum(CAST(CASE  WHEN  b.cargoid = '''+typeid+''' and ISNULL(b.Qty,0)<>0	
														then
																	 b.total
																ELSE  
																	0
																END 
												 AS DECIMAL(18,4)))/
												sum(CAST(CASE  WHEN  b.cargoid = '''+typeid+'''
														then
														case when ISNULL(b.Qty,0)<>0					
																	THEN b.qty
																ELSE  
																	0
																END 
													   end
												 AS DECIMAL(18,4)))
												 end
						,['+FullName+'成本金额]=SUM(CASE WHEN  b.cargoid = '''+typeid+''' THEN ISNULL(B.total,0) ELSE 0 END)'	
						FROM  #TempStock order by UserCode
SET @Sql = @Sql +'
					FROM #ptype c
					LEFT JOIN (
								SELECT	e.TypeId,
										g.ktypeid,
										SUM(ISNULL(G.Qty,0)) AS Qty,
										SUM(ISNULL(G.price,0)) as price,
										SUM(ISNULL(G.total,0)) as total,
										SUM(ISNULL(G.NQty,0)) AS NQty,
										g.cargoid
								FROM 	#ptype1 e
								LEFT JOIN #GsStock G ON G.PTypeId =e.TypeId
								GROUP BY e.TypeId,g.ktypeid,g.cargoid
								) b on b.typeid LIKE c.TypeId+''%''
						GROUP BY c.typeid
						)D on d.pTypeId LIKE a.TypeId+''%'''
	IF @Flag=0 
		SELECT @SQL=@SQL+'order by '+CONVERT(varchar(4),@INDEX)+@Sort
		
--PRINT(@SQL)
EXEC(@sql)	 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCargoDistributingLineCalTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCargoDistributingLineCalTotal]
GO
/****** Object:  StoredProcedure [dbo].[Web_QueryCargoDistributingLineCalTotal]    Script Date: 05/25/2012 10:56:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Web_QueryCargoDistributingLineCalTotal]
(
	@OperatorID 	varchar(100),   --操作员id
	@PTypeId		varchar(100),	--商品Id
	@cargoid        varchar(100),   --货位ID
	@UserCode 		varchar(206)='',
	@FullName 		varchar(66)='',
	@PageRows 		int=14,
 	@NoZero 		int,           	--显示为零行
	@CargoPageNo 	int,   			--分仓库页显示的页数
	@srcKTypeId		varchar(8000),
	@isLine			int=0,			--是否是线性表
	@szPEntryCode	varchar(800)='',
	@ktypeid		varchar(100),
	@stypeid		VARCHAR(MAX)
)
--@encode$--
AS
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @re_check INT
EXEC @re_check=GP_CheckLimit @OperatorID,453
--分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@operatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @re_check = 0
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT s.typeid FROM Stock sk,F_GetAllManagerBaseTypeId(@srcKTypeId,4,'00001') s,F_GetAllManagerBaseTypeId(@stypeid,11,'00001') st WHERE S.TypeID = Sk.typeId AND Sk.STypeID = st.TypeId
--商品
CREATE TABLE #GetManPTypeALL (TypeID VARCHAR(50),ParId Varchar(50),Sonnum int,UserCode varchar(200),FullName varchar(200),EntryCode varchar(2200))

INSERT INTO #GetManPTypeALL SELECT typeid,ParId,Sonnum,UserCode,FullName,EntryCode FROM F_GetManPTypeAll(@OperatorID)
------------------------------------------计算出应查询的货位-----------------------------------------------
CREATE TABLE #TempCargoType1
(
	CargoID     varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)
CREATE TABLE #TempCargoType
(
	CargoID		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

--处理货位 
DECLARE @CargiIDs 		varchar(8000),
		@Where_CargiID	varchar(8000),
		@x 				int
SET @Where_CargiID = ''

SET @cargoid= RTRIM(LTRIM(@cargoid))
SET @x = charindex(',',@cargoid)

WHILE @x>=1
	BEGIN
		SET @CargiIDs = LEFT(@cargoid,@x-1)

		IF @Where_CargiID = ''
			SET @Where_CargiID = ' AND (ct.CargoID LIKE '+char(39)+@CargiIDs+'%'+char(39)
		ELSE
			SET @Where_CargiID = @Where_CargiID + ' OR ct.CargoID LIKE '+char(39)+@CargiIDs+'%'+char(39)

		SET @cargoid=SUBSTRING(@cargoid,@x+1,LEN(@cargoid)-@x)
		SET @x=charindex(',',@cargoid)
	END
IF @cargoid<>''
	BEGIN
		IF @Where_CargiID = ''
			SET @Where_CargiID = ' AND (ct.CargoID LIKE '+char(39)+@cargoid+'%'+char(39)+')'
		ELSE
			SET @Where_CargiID = @Where_CargiID + ' OR ct.CargoID LIKE '+char(39)+@cargoid+'%'+char(39)+')'
	END

DECLARE @Jhtao varchar(8000)
SET @Jhtao = 'INSERT INTO #TempCargoType1 select ct.CargoID ,ct.UserCode,ct.FullName from CargoType ct  INNER JOIN Stock s ON s.typeid=ct.ktypeid inner join #GetSelectSTypeId ss on s.stypeid=ss.typeid  WHERE s.TypeId IN (SELECT * FROM #GetManKTypeId)'+@Where_CargiID+' and ct.deleted=0 and '+case when @ktypeid=''then ' ct.ktypeid<>0 'else ' ct.ktypeid='+@ktypeid end+' ORDER BY ct.UserCode '

EXEC(@Jhtao)

SET @Jhtao = '
		INSERT INTO #TempCargoType
	    SELECT  TOP ' + CAST(10 AS varchar(50)) + ' 
				CargoID,		
				UserCode,					
				FullName
	    FROM    #TempCargoType1 
	    ORDER BY UserCode '

EXEC(@jhtao)
-----------------------------------------------------------/*仓库处理完毕*/-----------------------------------------------------
DECLARE @TotalPages int,@TotalQty  NUMERIC(24, 10) 
DECLARE @RecordCount int
DECLARE @TotalCargoCount int,@TotalCargoPages int
IF @UserCode IS NULL OR @UserCode=''
 SELECT @UserCode='%'
ELSE
 SELECT @UserCode='%'+@UserCode+'%'
IF @FullName IS NULL OR @FullName=''
 SELECT @FullName='%'

ELSE
 SELECT @FullName='%'+@FullName+'%'
IF @PageRows=0 
  SELECT @PageRows=14

--计算页数
DECLARE @SonNum		int,
		@PTypeIdMx	varchar(100)
IF @PTypeId = '00000'

	SET @PTypeIdMx = '%'
ELSE
	SET @PTypeIdMx = @PTypeId

IF @PTypeId = ''
	SELECT  @SonNum = SonNum FROM PType WHERE TypeId = '00000'
ELSE
	SELECT  @SonNum = SonNum FROM PType WHERE TypeId = @PTypeId 


IF @SonNum >= 1
	BEGIN
		IF @isLine = 0
			SELECT 	@RecordCount=COUNT(*) 
			FROM 	#GetManPTypeALL
			WHERE	ISNULL(UserCode,'') LIKE '%'+@UserCode+'%' 
					AND ISNULL(FullName,'') LIKE '%'+@FullName+'%'
					AND ISNULL(EntryCode,'') LIKE '%'+@szPEntryCode+'%'
					AND ParId = @PTypeId
		ELSE
			BEGIN
				IF @PTypeId = '00000'
					SET @PTypeId = '%'

				IF @NoZero = 0
					SELECT 	@RecordCount=COUNT(*) 
					FROM 	#GetManPTypeALL
					WHERE	ISNULL(UserCode,'') LIKE '%'+@UserCode+'%' 
							AND ISNULL(FullName,'') LIKE '%'+@FullName+'%'
							AND ISNULL(EntryCode,'') LIKE '%'+@szPEntryCode+'%'
							AND SonNum = 0
							AND TypeId LIKE @PTypeIdMx+'%'
				ELSE
					BEGIN	
						SELECT	@RecordCount=COUNT(P.TypeId)
						FROM 	#GetManPTypeALL P
						INNER JOIN (
								SELECT	S.PTypeID,
										ISNULL(SUM(S.Qty),0) AS Qty								
								FROM 	GOODSSTOCKS_QTY S,
										#TempCargoType T
								WHERE	S.CargoID = T.CargoID
								GROUP BY S.PTypeId
						)G ON G.PTypeId = P.TypeId
						WHERE	ISNULL(P.UserCode,'') LIKE '%'+@UserCode+'%' 
								AND ISNULL(P.FullName,'') LIKE '%'+@FullName+'%'
								AND ISNULL(P.EntryCode,'') LIKE '%'+@szPEntryCode+'%'
								AND P.SonNum = 0
								AND P.TypeId LIKE @PTypeIdMx+'%'
								
					END
			END
	END   
ELSE
	BEGIN
		IF @NoZero = 0
			SELECT 	@RecordCount=COUNT(*) 
			FROM 	#GetManPTypeALL
			WHERE	ISNULL(UserCode,'') LIKE '%'+@UserCode+'%' 
					AND ISNULL(FullName,'') LIKE '%'+@FullName+'%'
					AND ISNULL(EntryCode,'') LIKE '%'+@szPEntryCode+'%'
					AND TypeId LIKE @PTypeIdMx+'%'
		ELSE
			SELECT 	@RecordCount=COUNT(*) 
			FROM 	#GetManPTypeALL P,
					#TempCargoType T,
					GOODSSTOCKS_QTY G
			WHERE  	P.TypeId = G.PTypeId
					AND T.CargoID = G.CargoID					
					AND ISNULL(P.UserCode,'') LIKE '%'+@UserCode+'%' 
					AND ISNULL(P.FullName,'') LIKE '%'+@FullName+'%'
					AND ISNULL(P.EntryCode,'') LIKE '%'+@szPEntryCode+'%'
					AND P.TypeId LIKE @PTypeIdMx+'%'
	END 

SELECT	@TotalCargoCount = COUNT(*) FROM #TempCargoType1
SET @TotalPages = @RecordCount
IF @TotalCargoCount%10<>0 
	SELECT @TotalCargoPages=@TotalCargoCount/10+1
ELSE
	SELECT @TotalCargoPages=@TotalCargoCount/10
	
--PRINT(@TotalCargoPages)	


DECLARE @CargoName varchar(66),@TypeId varchar(100),@i int,@j int,@ReSql varchar(MAX),@Sql varchar(MAX),@Qty  NUMERIC(24, 10) 
DECLARE @TableName varchar(16)


SELECT 	typeid 
INTO 	#TempPTypeAll 
FROM 	#GetManPTypeALL 
WHERE 	sonnum=0 
		AND ISNULL(UserCode,'') LIKE '%'+@UserCode +'%'
		AND ISNULL(FullName,'') LIKE '%'+@FullName+'%'
		AND ISNULL(EntryCode,'') LIKE '%'+@szPEntryCode+'%'
		AND TypeId LIKE @PTypeIdMx + '%'

/*================================= WANG WEI 2010-8-11 BEGIN 如果不显示库存状况为零的时候，将商品所有仓库合计的总数为零的排除=========================================================================*/
CREATE TABLE #TempPType(typeid VARCHAR(100))
IF @NoZero='0'
BEGIN
	INSERT INTO #TempPType SELECT * FROM #TempPTypeAll		
END
Else
BEGIN
	INSERT INTO #TempPType
	SELECT b.typeid 
	FROM
	( 
		Select p.typeid,Isnull(sum(a.qty),0) as sumQty from #TempPTypeAll p left join 
		(Select s.qty,s.ptypeid,s.ktypeid  from GOODSSTOCKS_QTY s inner join #TempCargoType t On s.CargoID=t.CargoID where s.KTypeID=@ktypeid ) a
		ON a.ptypeid=p.typeid
		where Isnull(a.qty,0)<>0 and KTypeID=@ktypeid
		group by p.typeid 
	
	) b 
	INNER JOIN #TempPTypeAll t On b.typeid=t.typeid 
	WHERE b.sumQty<>0	
	
END
/*================================= WANG WEI 2010-8-11 END=========================================================================*/

CREATE TABLE #GoodsCargo
(
	total		 NUMERIC(24, 10) ,
	Qty			 NUMERIC(24, 10) ,
	CargoID		varchar(100)
)
INSERT INTO #GoodsCargo(total,Qty,CargoID) 
SELECT	a.Total,
		q.Qty,
		q.CargoID 
FROM GOODSSTOCKS_QTY q
INNER JOIN GOODSSTOCKS a ON a.PtypeId=q.PTypeID and a.KtypeId=q.KTypeID 
WHERE EXISTS(
				SELECT typeid 
				FROM #TempPType
				WHERE typeid=q.PTypeID
				
			) 
		AND q.KTypeId IN (SELECT TypeId FROM #GetManKTypeId)
		and q.KTypeID=@ktypeid
group by a.Total,q.Qty,q.CargoID 
SELECT	a.CargoID,
		ISNULL(SUM(b.qty),0) AS qty, 
		ISNULL(SUM(b.total),0) AS total 
INTO	#CargoQty 
FROM	#TempCargoType a 
		LEFT JOIN #GoodsCargo b ON (a.CargoID=b.CargoID) 
GROUP BY a.CargoID,b.qty,b.total

DECLARE @sumTotal  NUMERIC(24, 10) ,@sumprice  NUMERIC(24, 10) 
SET @sumprice=0
SELECT 	@TotalQty=ISNULL(SUM(G.Qty),0),
		@sumTotal= gs.price *SUM(G.Qty)
FROM 	GOODSSTOCKS_QTY G
inner join #TempCargoType T on T.CargoID=G.CargoID
inner join (select AVG(price) as price,ptypeid,ktypeid from GoodsStocks group by PtypeId, KtypeId) gs on gs.PtypeId=G.Ptypeid and gs.KtypeId=G.Ktypeid
WHERE 	 exists(
					SELECT 	typeid 
					FROM 	#TempPType 
					WHERE 	typeid=gs.ptypeid
				)
	and isnull(g.KTypeID,'') like '%'+@ktypeid+'%'
	and ISNULL(g.PTypeID,'') like '%'+@PTypeIdMx+'%'
group by gs.price
SET @sumprice=(CASE @sumTotal WHEN 0 THEN 0 ELSE @sumTotal/@TotalQty END)

--计算每个货位的合计
DECLARE @inullcargo int
select @inullcargo=isnull(CargoID,0) FROM #TempCargoType
if @inullcargo=0
begin
	return  select cargoid from #TempCargoType
end



SELECT @TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT @Sql='CREATE TABLE '+N'##'+@TableName+'([总页数] int,[仓库总页数] int,[总计账面库存]  NUMERIC(24, 10) ,[总计成本均价]  NUMERIC(24, 10) ,[总计成本金额]  NUMERIC(24, 10) )'
EXEC(@sql)

IF @@error<>0
	BEGIN
		--RAISERROR('创建临时表发生错误！',16,1)
		RETURN
	END

SELECT @Sql='INSERT '+N'##'+@TableName+'([总页数],[仓库总页数],[总计账面库存],[总计成本均价],[总计成本金额] )
                    VALUES('+CONVERT(varchar(20),@TotalPages)+','+CONVERT(varchar(20),@TotalCargoCount)+','+CONVERT(varchar(18),@TotalQty)+','+CONVERT(varchar(18),@sumprice)  +','+CONVERT(varchar(18),@sumTotal)+')'
EXEC(@Sql)


DECLARE @cargoTotal  NUMERIC(24, 10) 
DECLARE CargoType CURSOR  FOR 
     SELECT  b.qty,a.cargoid,a.fullname,b.total FROM #TempCargoType a INNER JOIN #CargoQty b ON (a.CargoID=b.CargoID)ORDER BY a.UserCode FOR READ ONLY

OPEN CargoType
FETCH NEXT FROM CargoType INTO @Qty,@CargoID,@CargoName,@CargoTotal

IF @@Fetch_status<>0
BEGIN
	CLOSE CargoType
	DEALLOCATE CargoType
	RAISERROR('没有可用的仓库或仓库没有商品或没有商品！',16,1)
		SELECT * FROM #TempCargoType --当仓库没有值的时候，返回空#TempCargoType
	RETURN 
END 


--DECLARE @cargoTotal  NUMERIC(24, 10) 
--IF NOT EXISTS( SELECT  b.qty,a.cargoid,a.fullname,b.total FROM #TempCargoType a INNER JOIN #CargoQty b ON (a.CargoID=b.CargoID)
--)
--	SELECT * FROM #TempCargoType
--	RETURN



SELECT @Sql=''
SELECT @ReSql='[总页数],[仓库总页数],[总计账面库存],[总计成本金额]'--[总计成本均价],

SELECT @i=0
WHILE @@Fetch_status=0
	BEGIN
		SELECT @j=0
		SELECT @i=CharIndex('['+ @CargoName + ']',@ReSql,@i)
		WHILE @i>0
			BEGIN
				SELECT @i=CharIndex('['+ @CargoName + ']',@ReSql,@i+len('['+ @CargoName + ']'))
				SELECT @j=@j+1  
			END
		
		IF @j>0
			SELECT @CargoName=@CargoName+CONVERT(varchar(4),@j)
			
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @CargoName + '账面库存]  NUMERIC(24, 10) '
			EXEC(@sql)
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @CargoName + '成本均价]  NUMERIC(24, 10) '
 			EXEC(@sql)
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @CargoName + '成本金额]  NUMERIC(24, 10) '
 			EXEC(@sql)
			IF @@error<>0
				BEGIN
					CLOSE CargoType
					DEALLOCATE CargoType
					--RAISERROR('更改临时表发生错误！',16,1)
					RETURN
				END
			
			SELECT @Sql='UPDATE '+N'##'+@TableName+' SET ['+@CargoName+'账面库存]='+CONVERT(varchar(1000),@Qty)+','
			SELECT @Sql=@Sql+'['+@CargoName+'成本均价]='+CONVERT(varchar(1000),(CASE @cargoTotal WHEN 0 THEN 0 ELSE @cargoTotal/@Qty END))+','
			SELECT @Sql=@Sql+'['+@CargoName+'成本金额]='+CONVERT(varchar(1000),@cargoTotal)
			EXEC(@sql)
			SELECT @ReSql=@ReSql+',['+ @CargoName + '账面库存],['+ @CargoName + '成本金额],['+ @CargoName + '成本均价]'
			FETCH NEXT FROM CargoType INTO @Qty,@CargoID,@cargoName,@cargoTotal
	END
	CLOSE CargoType
DEALLOCATE CargoType
SELECT @ReSql='SELECT '+@ReSql+' FROM '+N'##'+@TableName
EXEC(@ReSql)

DECLARE @DropTable varchar(1000)
SET @DropTable = 'DROP TABLE #TempCargoType1,'+N'##'+@TableName
EXEC(@DropTable)

IF @@Rowcount=0
   RETURN @TotalPages


DROP TABLE #GoodsCargo,#GetSelectSTypeId

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCargoDistribution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCargoDistribution]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇	
	日期：2013-05-15
	描述：货位分布明细
*/
CREATE PROCEDURE Web_QueryCargoDistribution
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@stypeid			VARCHAR(max),		--所选的分支机构ID
	@ktypeid            VARCHAR(max),		--所选的仓库的ID
	@ptypeid			VARCHAR(50),			--商品的ID,
	@endDataPoint		VARCHAR(10),
	@ntype 				int	      	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------权限检查---------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
------------------------------------------------------权限检查---------------------------------------------------------------

---选择分支机构
CREATE TABLE #STypeId(TypeId	VARCHAR(100))
	INSERT INTO #STypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--仓库
CREATE TABLE #KTypeId(TypeId	VARCHAR(100))
	INSERT INTO #KTypeId(TypeId) SELECT a.TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID) A
	INNER JOIN F_GetManDetailKTypeSType(@OperatorID) mk ON A.TypeId=mk.TypeId
    INNER JOIN #STypeId s ON mk.STypeId=s.TypeId
	
---选择商品
CREATE TABLE #ptype(TypeId	VARCHAR(100))
	INSERT INTO #ptype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID)
DECLARE @subvalue INT

--SELECT @subvalue=subvalue FROM dbo.sysdata WHERE SubName='costing'	

--IF @subvalue=0 OR @subvalue=1 OR @subvalue=2	
 --BEGIN
 --     SELECT
	--	Q.cargoid,
	--	Q.ktypeid,
	--	Q.ptypeid,
	--	SUM(q.Qty)qty,
	--	b.price AS costprice,
	--	(SUM(Q.qty)*b.price) AS costtotal
	--FROM  (SELECT PtypeId,KtypeId, case when sum(qty)=0 then 0 else sum(total)/sum(qty) end as price FROM dbo.GoodsStocks GROUP BY PtypeId,KtypeId)b
	--INNER JOIN dbo.GoodsStocks_Qty Q ON  b.KtypeId=q.KTypeID AND b.PtypeId=q.PTypeID
	--INNER JOIN stock S ON q.KTypeID=s.typeId
	--INNER JOIN #KTypeId K ON Q.KTypeID=K.TypeId 
	--INNER JOIN #STypeId A ON a.TypeId= s.STypeID
	--INNER JOIN #ptype P ON p.TypeId =q.PTypeID
	--GROUP BY Q.CargoID,Q.KTypeID,Q.PTypeID,b.price
--  END
--ELSE
--  BEGIN
--END 

IF @ntype!=3
BEGIN
SELECT  a.cargoid ,
        a.ktypeid ,
        a.ptypeid ,
        a.qty ,
        b.costprice ,
        a.qty * b.costprice AS costtotal
FROM    ( SELECT    q.CargoID ,
                    q.KtypeId ,
                    q.PtypeId ,
                    SUM(q.Qty) qty
          FROM      dbo.InOutstocktable q
                    INNER JOIN dbo.BillIndex aa ON q.BillNumberId = aa.BillNumberId
                    INNER JOIN stock S ON q.KTypeID = s.typeId
                    INNER JOIN #KTypeId K ON Q.KTypeID = K.TypeId
                    INNER JOIN #STypeId A ON a.TypeId = s.STypeID
                    INNER JOIN #ptype P ON p.TypeId = q.PTypeID
          WHERE     q.KtypeId != '10000'
                    AND q.billdate <= @endDataPoint
                    AND aa.RedWord = 0
                    AND CargoID != 0
          GROUP BY  CargoID ,
                    Q.KTypeID ,
                    Q.PTypeID
        ) a
        INNER JOIN ( SELECT q.KtypeId ,
                            q.PtypeId ,
                            CASE WHEN SUM(q.Qty) = 0 THEN 0
                                 ELSE CAST( SUM(q.CostTotal) AS NUMERIC(24, 10))/ CAST(SUM(q.Qty) AS NUMERIC(24, 10))
                            END costprice
                     FROM   dbo.InOutstocktable q
                            INNER JOIN dbo.BillIndex aa ON q.BillNumberId = aa.BillNumberId
                            INNER JOIN stock S ON q.KTypeID = s.typeId
                            INNER JOIN #KTypeId K ON Q.KTypeID = K.TypeId
                            INNER JOIN #STypeId A ON a.TypeId = s.STypeID
                            INNER JOIN #ptype P ON p.TypeId = q.PTypeID
                     WHERE  q.KtypeId != '10000'
                            AND q.billdate <= @endDataPoint
                            AND aa.RedWord = 0
                     GROUP BY Q.KTypeID ,
                            Q.PTypeID
                   ) b ON a.KtypeID = b.KtypeId
                          AND b.PtypeId = a.ptypeid

UNION ALL

    SELECT q.CargoID ,
        q.KtypeId ,
        q.PtypeId ,
        SUM(q.Qty) qty ,
      Price AS  costprice ,
     (SUM(Q.qty)*qq.price) AS costtotal
 FROM   dbo.Ini_GOODSSTOCKS_QTY q
        INNER JOIN  (sELECT PtypeId,KtypeId,SUM(total)AS total, case when sum(qty)=0 then 0 else CAST( sum(total)AS NUMERIC(24, 10))/CAST(sum(qty) AS NUMERIC(24, 10))end as price FROM dbo.IniGoodsStocks GROUP BY PtypeId,KtypeId) qq ON  q.KTypeID = qq.KtypeId AND q.PTypeID = qq.PtypeId
        INNER JOIN stock S ON q.KTypeID = s.typeId
        INNER JOIN #KTypeId K ON Q.KTypeID = K.TypeId
        INNER JOIN #STypeId A ON a.TypeId = s.STypeID
        INNER JOIN #ptype P ON p.TypeId = q.PTypeID
 GROUP BY 
        CargoID,     
        Q.KTypeID ,
        Q.PTypeID ,
        Price
   
 END
 ELSE
 BEGIN 
     SELECT
		Q.cargoid,
		Q.ktypeid,
		Q.ptypeid,
		SUM(q.Qty)qty,
		b.price AS costprice,
		(SUM(Q.qty)*b.price) AS costtotal
	FROM  (SELECT PtypeId,KtypeId, case when sum(qty)=0 then 0 else CAST(sum(total)AS NUMERIC(24, 10))/CAST(sum(qty)AS NUMERIC(24, 10)) end as price FROM dbo.GoodsStocks GROUP BY PtypeId,KtypeId)b
	INNER JOIN dbo.GoodsStocks_Qty Q ON  b.KtypeId=q.KTypeID AND b.PtypeId=q.PTypeID
	INNER JOIN stock S ON q.KTypeID=s.typeId
	INNER JOIN #KTypeId K ON Q.KTypeID=K.TypeId 
	INNER JOIN #STypeId A ON a.TypeId= s.STypeID
	INNER JOIN #ptype P ON p.TypeId =q.PTypeID
	GROUP BY Q.CargoID,Q.KTypeID,Q.PTypeID,b.price
 END
            
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCargoTypeColumnSelectorList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCargoTypeColumnSelectorList
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：货位管理 单选多选selector
-- 时间：2018-07-25
-- 作者：glj	
-- ========================================================================
CREATE PROC Web_QueryCargoTypeColumnSelectorList
(
	@Filter			VARCHAR(200),--查询条件
	@KTypeID		VARCHAR(50),--仓库ID
	@deleted		INT,--是否包含停用
	@OperatorID		VARCHAR(50)	--操作员
)
--@encode$--

AS
SET NOCOUNT ON

SELECT 
	A.CargoID TypeId, 
	A.UserCode,
	A.FullName,
	A.KtypeID
FROM dbo.CargoType A
INNER JOIN F_GetAllManagerBaseTypeId(@KTypeID,4,@OperatorId) S ON a.KtypeID=S.TypeId
WHERE
	((@deleted=0 AND A.deleted=0) 
		OR @deleted=1)
	 AND (ISNULL(@Filter,'')=''
			OR (ISNULL(@Filter,'')<>'' AND A.UserCode LIKE '%'+@Filter+'%' OR a.FullName LIKE '%'+@Filter+'%' OR a.PyCode LIKE '%'+@Filter+'%' ))
ORDER BY UserCode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarUse]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCarUse]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-23
	描述：车辆使用情况查询
*/

CREATE PROCEDURE Web_QueryCarUse
(
	@startdate		varchar(30)='',
	@enddate		varchar(30)='',
	@usestartdate   varchar(30),
	@useenddate		varchar(30)='',
	@stypeid		varchar(50)='',
	@ratypeid		varchar(50)='',
	@etypeid		varchar(8000)='',
	@OperatorId		VARCHAR(100)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

CREATE TABLE #Etype (TypeID VARCHAR(50),FullName varchar(66))
CREATE TABLE #Stype (TypeID VARCHAR(50))

--职员
INSERT INTO #Etype SELECT TypeID,FullName FROM employee where TypeID IN (SELECT TypeID FROM  F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID))
IF @etypeid=''
	BEGIN
		INSERT INTO #Etype VALUES('','')
	END
--分支机构
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

DECLARE @where_sql varchar(1000),
		@sql varchar(8000)
	
SET @where_sql='WHERE B.Usestartdate>='+CHAR(39)+CONVERT(varchar(30),@usestartdate)+CHAR(39)+' AND B.Useenddate<='+CHAR(39)+CONVERT(varchar(30),@useenddate)+CHAR(39)
IF @startdate<>'' SET @where_sql=@where_sql+' AND A.BillDate>='+CHAR(39)+CONVERT(varchar(30),@startdate)+CHAR(39)
IF @enddate<>'' SET @where_sql=@where_sql+' AND A.BillDate<='+CHAR(39)+CONVERT(varchar(30),@enddate)+CHAR(39)
IF @stypeid<>'' SET @where_sql=@where_sql+' AND A.stypeid=s.typeid'
IF @ratypeid<>0 SET @where_sql=@where_sql+' AND B.CarId='+@ratypeid

SET @sql = 'SELECT  A.billnumberid,
				    A.billcode,
				    A.billdate,
				    A.billtype,
					A.Stypeid,
					A.Dtypeid,
					C.platenumber,
					e.FullName as driver,
					e2.fullname as caruser,
					B.[use],
					B.Usestartdate as usestartdate,
					B.Useenddate as useenddate,
					B.Comment as base
			FROM CM_CarUseIndex A  
			join CM_CarUseBill B on A.BillNumberId=B.BillNumberId 
			join CM_CarInfo C on  C.typeid=B.CarId
			join #Stype s on s.typeid=A.Stypeid
			inner join #Etype e on (e.typeid=B.driver)
			join employee e2 on e2.typeId=b.Etypeid '+@where_sql+
			' ORDER BY A.Stypeid desc,C.platenumber asc,A.billdate desc,A.billcode desc'
EXEC(@sql)
DROP TABLE #Etype,#Stype

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarUseBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryCarUseBill
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：	返回车辆使用登记单明细
-- 时间：	2011-11-22
-- 作者：	陈守川

-- ========================================================================
CREATE PROCEDURE [dbo].[Web_QueryCarUseBill]
(
	@BillNumberID	varchar(100)	-- 单据编号
)
--@encode$--

AS
SET NOCOUNT ON 

DECLARE @sql varchar(8000)


SET @sql='
	SELECT a.BillNumberId,
		   a.destination,
		   a.[use],
		   a.usestartdate,
		   a.useenddate,
		   c.typeid as typeid,
		   c.Platenumber as platenumber,
		   e1.usercode as xusercode,
		   e1.fullname as xfullname,
		   e1.typeId as eTypeId,
		   e.typeId as repairmantypeid,
		   e.usercode as eusercode,
		   e.fullname as efullname,
		   a.comment as base
	FROM  CM_CarUseBill a 	
	INNER JOIN employee e ON e.TypeID = a.EtypeID
	LEFT JOIN employee e1 ON e1.TypeID = a.driver
	INNER JOIN CM_CarInfo c ON c.typeid = a.CarId
	WHERE a.BillNumberID =  '+@BillNumberID+'
	ORDER BY a.ID '
print(@sql)
EXEC(@sql)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarUseDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCarUseDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：陈守川
	日期：2011-11-24
	描述：车辆费用信息--车辆使用记录查询
*/

CREATE PROCEDURE [dbo].[Web_QueryCarUseDetail]
(
	@OperatorId		VARCHAR(100),
	@usestartdate	varchar(30)='',
	@useenddate		varchar(30)='',
	@ratypeid		varchar(50),
	@stypeid		varchar(50)
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------


--分支机构
CREATE TABLE #Stype (TypeID VARCHAR(50))
INSERT INTO #Stype SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

declare @create_sql varchar(5000),
		@where_sql varchar(1000)=''
		
if @usestartdate<>'' set @where_sql=@where_sql+' and b.usestartdate>='+CHAR(39)+CONVERT(varchar(30),@usestartdate)+CHAR(39)		
if @useenddate<>''	 set @where_sql=@where_sql+' and b.useenddate<='+CHAR(39)+CONVERT(varchar(30),@useenddate)+CHAR(39)

   set @create_sql='select
					a.billnumberid,
					a.billdate,
					a.billtype,
					a.billcode,
					a.stypeid,
					e2.fullname as jingshouren,
					c.platenumber, 
					e.fullname as driver,
					e1.fullname as caruser,
					b.destination,
					b.[use],
					b.usestartdate,
					b.useenddate,
					b.comment as base
			from CM_CarUseIndex a
			inner join CM_CarUseBill b on a.BillNumberId=b.BillNumberId
			inner join CM_CarInfo c on b.CarId=c.typeid
			inner join employee e1 on b.etypeid=e1.typeid
			inner join employee e2 on a.etypeid=e2.typeid
			INNER JOIN #Stype s on s.typeid = a.stypeid
			left join employee e on b.driver = e.typeid
			where  b.CarId='+@ratypeid+' '+@where_sql+
			' order by a.billdate desc,a.billcode desc'
--print(@create_sql)
exec(@create_sql)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarUseIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryCarUseIndex
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/*
作者：陈守川
时间：2011-11-22
描述:查询车辆使用登记单主表数据
*/
CREATE PROCEDURE Web_QueryCarUseIndex 
( 
	@BillNumberId numeric(10,0)
)

--@encode$--
AS
SET NOCOUNT ON 

SELECT	a.BillNumberId as billnumberid,
		a.BillCode,
		a.BillDate,
		a.BillType,
		a.dtypeid,		
		d.FullName AS dfullname,
		a.etypeid,
		e.FullName AS efullname,
		e1.FullName  AS checke,
		a.Stypeid,
		s.FullName AS sfullname,
		a.Comment as comment,
		a.Explain,
		a.checke		
FROM	CM_CarUseIndex a
INNER JOIN employee e1 ON a.Checke = e1.TypeID
INNER JOIN employee e ON a.Etypeid = e.TypeID
LEFT  JOIN Department D ON a.DtypeId = D.TypeID
INNER JOIN Stype S ON a.STypeID = S.TypeID
WHERE a.BillNumberID = @BillNumberId
ORDER BY a.BillDate DESC, a.BillNumberId ASC 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCarYearCheckAlerm]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCarYearCheckAlerm]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-05-04
	描述：年审到期车辆提醒
*/
CREATE PROCEDURE Web_QueryCarYearCheckAlerm
(
	@OperatorId		VARCHAR(MAX),		--操作员ID
	@StartDate		VARCHAR(MAX),		--开始日期
	@EndDate		VARCHAR(MAX),		--截止日期
	@STypeId		VARCHAR(MAX),		--分支机构
	@BTypeId		VARCHAR(MAX),		--往来单位
	@WciTypeId		VARCHAR(MAX)		--车牌号	
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)

--车牌号
CREATE TABLE #GetManWciTypeId(TypeId	varchar(100))
INSERT INTO #GetManWciTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,'00001')

DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'SELECT	Y.*,
					R.PlateNumber,
					R.BTypeId,
					B.*
			FROM	Qp_YearCheck Y
			INNER JOIN #GetManSTypeId S ON S.TypeId = Y.STypeId	
			INNER JOIN #GetManWciTypeId W ON W.TypeId = Y.RaTypeId
			INNER JOIN QP_RepairAutoInfo R ON R.TypeId = Y.RaTypeId
			INNER JOIN BType B ON B.TypeId = R.BTypeId	
			INNER JOIN #GetManBTypeId MB ON MB.TypeId = B.TypeId		
			WHERE	reachdate >= '''+@StartDate+ '''
					AND reachdate <= '''+@EndDate+'''
			ORDER BY Y.reachdate ASC,R.PlateNumber ASC'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManBTypeId,#GetManSTypeId,#GetManWciTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCashBankBaseLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCashBankBaseLine]
GO





/*
--作者：徐辉
--创建时间：2011-08-25
--功能：现金银行查询线形表
*/

CREATE             PROC Web_QueryCashBankBaseLine
( 
	@operatorId		VARCHAR(50),	-- 操作员的ID号
	@parid   		VARCHAR(50),
	@StypeID		VARCHAR(Max),	-- 分支机构ID
	@cFlag   	CHAR(2)
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Stype (TypeID varchar(50))

IF @STypeID=''
	INSERT INTO #Stype(typeid)  select typeid from F_BaseGetManDetailSType(@operatorId)
ELSE
	INSERT INTO #Stype(typeid)  select a.typeid from F_BaseGetManDetailSType(@operatorId) a, (select * from  dbo.f_split(@StypeID,',')) b where left(a.typeid,len(b.a))=b.a

SELECT
	 p.parid, 
	 p.leveal,
	 p.sysflag, 
	 p.typeId,
	 p.UserCode,
	 p.FullName,
	 p.sonnum,
	 p.deleted,
	 s.Total,
	 s.Total00
INTO 
	#Atype
FROM 
	AType p
LEFT JOIN 
	(
		SELECT 
			atypeid,Sum(isnull(total,0)) as total, Sum(isnull(total00,0)) as total00 
		FROM 
			AType_Total
		WHERE Stypeid IN(SELECT typeId FROM #Stype) GROUP By ATypeID
	 ) s
ON s.ATypeID=p.typeId


	
DECLARE @SQL VARCHAR(8000)

SELECT		    @SQL='SELECT 	a.usercode,
						a.fullname,
						a.parid,
						a.sonnum,
						a.leveal,
						a.typeid,
						ISNULL(a.total,0) AS total
				FROM 	#atype a
				WHERE 	a.typeid like '+char(39)+@parid+'%'+char(39)+' 
						AND sysflag='+char(39)+@cFlag+char(39)+' 
						AND a.sonnum=0
						AND a.deleted=0
						AND typeid IN (SELECT TypeID FROM F_GetManATypeAll('+char(39)+@operatorId+char(39)+'))		--加入权限  谢吉康   #-01
						AND (TypeId LIKE ''0000100003%'' OR TypeId LIKE ''0000100004%'')
						AND ISNULL(a.total,0)<>0
				ORDER BY usercode'

--print @sql
exec (@sql)
drop table #Atype
drop table #Stype














GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCashBankCombLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_QueryCashBankCombLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-12-25
function:现金银行汇总表 线性表
*/
CREATE PROCEDURE Web_QueryCashBankCombLine
(
	@ParTypeId		VARCHAR(50),		--父节点ID
	@OperatorId		VARCHAR(50),		--操作员Id
	@queryType		VARCHAR(5),			--1:结算单位 2：职员 3：仓库
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate			VARCHAR(20),		--结束日期
	@ItemTypeID		VARCHAR(MAX),		--账户名称
	@StypeId			VARCHAR(MAX),		--分支机构Id
	@DealBTypeId	VARCHAR(MAX),		--往来单位
	@BTypeId			VARCHAR(MAX),		--结算单位
	@ETypeID			VARCHAR(MAX),		--经手人
	@DTypeID			VARCHAR(MAX),		--部门
	@Cid					INT,						--币种ID

	@BCount			INT=10,			--基本信息的默认个数
	@BPageNo			INT=0				--基本信息的页数
	--@IsPrint			INT=0				--是否是打印算法
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------

IF(ISNULL(@ParTypeId,'')='')
	SET @ParTypeId='00000'

DECLARE @SQL VARCHAR(MAX)=''
--=============================基本信息权限范围获取【BEGIN】=======================================
--账户信息
CREATE TABLE #Item(RowId INT,Nid INT,TypeID VARCHAR(50),UserCode VARCHAR(200),Fullname VARCHAR(200)) CREATE CLUSTERED INDEX #Stype_P_K ON #Item(TypeId)
INSERT INTO #Item(RowId,Nid,TypeID,UserCode,Fullname)
SELECT 
	ROW_NUMBER()OVER(ORDER BY I.usercode) RowId,
	I.nId,
	i.nTypeId,
	i.UserCode,
	i.FullName
FROM dbo.F_GetAllManagerBaseTypeId(@ItemTypeID,5,@OperatorId) F
INNER JOIN Ac_Items I ON I.nId=F.TypeId AND I.SonNum=0 AND F.TypeId NOT IN(27,39)--排除(1151-预付资金 2131-预收资金)

--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
INSERT INTO #Stype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorId)

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #DealBtype_P_K ON #DealBtype(TypeId)
INSERT INTO #DealBtype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId)
IF(ISNULL(@DealBTypeId,'')='' AND @queryType IN('E','D'))
	BEGIN
		INSERT INTO #DealBtype(TypeID) VALUES('')
	END
	
--结算单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
IF(@queryType='B')
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ParTypeId,2,@OperatorId)
	END
ELSE 
	BEGIN
		INSERT INTO #Btype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorId)
	END
IF(ISNULL(@BTypeId,'')='' AND @queryType IN('E','D'))
	BEGIN
		INSERT INTO #Btype(TypeID) VALUES('')
	END

--经手人
CREATE TABLE #Etype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
IF(@queryType='E')
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ParTypeId,3,@OperatorId) WHERE TypeId<>'00001'
	END
ELSE 
	BEGIN
		INSERT INTO #Etype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeID,3,@OperatorId) WHERE TypeId<>'00001'
	END
--部门
CREATE TABLE #Dtype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
	IF(@queryType='D')
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ParTypeId,9,@OperatorId)
	END
ELSE 
	BEGIN
		INSERT INTO #Dtype(TypeID)
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorId)
	END
DECLARE @type VARCHAR(50)=''
--线性表展现数据
CREATE TABLE #ParType(RowId INT,TypeID VARCHAR(50),SonNum INT,UserCode VARCHAR(200),FullName VARCHAR(200))CREATE CLUSTERED INDEX #ParType_P_K ON #ParType(TypeId)
IF(@queryType='B')--结算单位
	BEGIN
		SET @type='DB.TypeID'
		INSERT INTO #ParType(RowId,TypeID,SonNum,UserCode,FullName)
		SELECT
			ROW_NUMBER()OVER(ORDER BY B.UserCode) RowId,
			B.typeId,
			B.sonnum,
			B.UserCode,
			B.FullName
		FROM #Btype F
		INNER JOIN btype B ON B.typeId=F.typeId AND B.sonnum=0
		ORDER BY B.UserCode
	END
IF(@queryType='E')--职员
	BEGIN
		SET @type='E.TypeID'
		INSERT INTO #ParType(RowId,TypeID,SonNum,UserCode,FullName)
		SELECT
			ROW_NUMBER()OVER(ORDER BY B.UserCode) RowId,
			B.typeId,
			B.sonnum,
			B.UserCode,
			B.FullName
		FROM #Etype F
		INNER JOIN employee B ON B.typeId=F.typeId AND B.sonnum=0
		ORDER BY B.UserCode
	END
IF(@queryType='D')--部门
	BEGIN
		SET @type='D.TypeID'
		INSERT INTO #ParType(RowId,TypeID,SonNum,UserCode,FullName)
		SELECT
			ROW_NUMBER()OVER(ORDER BY B.UserCode) RowId,
			B.typeId,
			B.sonnum,
			B.UserCode,
			B.FullName 
		FROM #Dtype F
		INNER JOIN Department B ON B.typeId=F.typeId AND B.sonnum=0
		ORDER BY B.UserCode
	END

--=============================基本信息权限范围获取【END】=======================================

--=============================业务处理【BEGIN】=====================================

SET @SQL='SELECT
	P.TypeID,
	P.SonNum,
	p.UserCode,
	p.FullName,
	SUM(ISNULL(F.Ntotal,0)) totalfor,
	SUM(ISNULL(F.Total,0)) total'

IF @bCount=10
BEGIN
	SELECT @SQL=@SQL +'	,ISNULL(SUM(CASE WHEN F.AtypeId='+CAST(Nid AS VARCHAR)+'  THEN ISNULL(F.NTotal,0) ELSE 0 END),0) ['+CAST(Nid AS VARCHAR)+'-'+FullName+'-原币]
						,ISNULL(SUM(CASE WHEN F.AtypeId ='+CAST(Nid AS VARCHAR)+'  THEN ISNULL(F.Total,0) ELSE 0 END),0) ['+CAST(Nid AS VARCHAR)+'-'+FullName+'-本币]'  
	FROM #Item 
	WHERE RowId BETWEEN (@BPageNo-1)*@BCount+1 AND @BCount*@BPageNo
	ORDER BY RowId
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,ISNULL(SUM(CASE WHEN F.AtypeId='+CAST(Nid AS VARCHAR)+'  THEN ISNULL(F.NTotal,0)  ELSE 0 END),0) ['+CAST(Nid AS VARCHAR)+'-'+FullName+'-原币]
						,ISNULL(SUM(CASE WHEN  F.AtypeId='+CAST(Nid AS VARCHAR)+'  THEN ISNULL(F.Total,0) ELSE 0 END),0) ['+CAST(Nid AS VARCHAR)+'-'+FullName+'-本币]'  
	FROM #Item ORDER BY RowId 
END 

SET @SQL+='
FROM #ParType P
LEFT JOIN (
	SELECT
		'+@type+',
		L.AtypeId,
		SUM(L.Total) Total,
		SUM(L.Ntotal) Ntotal
	FROM ListTable  L
	INNER JOIN #Item A ON A.Nid=L.AtypeId
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	INNER JOIN #Dtype D ON D.TypeID=L.DtypeId
	INNER JOIN #Stype S ON S.TypeID=L.STypeID--分支机构
	INNER JOIN BillIndex I ON I.BillNumberId=L.BillNumberId AND L.BillType=I.BillType
	INNER JOIN #Btype B ON B.TypeID=I.btypeid
	INNER JOIN #DealBtype DB ON DB.TypeID=I.DealBTypeID
	WHERE 
		l.BillDate BETWEEN '''+@StartDate+''' AND '''+ @EndDate+'''
		AND L.CID='+CAST(@Cid AS VARCHAR)+'
	GROUP BY '+@type+',L.AtypeId
) F ON F.TypeID=P.TypeID
GROUP BY 
	P.RowId,
	P.TypeID,
	P.SonNum,
	p.UserCode,
	p.FullName
ORDER BY 
	P.RowId
'

EXEC(@SQL)
--PRINT @SQL
--=============================业务处理【END】=======================================

--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#DealBtype,#Dtype,#Etype,#Item,#Stype,#ParType

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCashBankCombList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_QueryCashBankCombList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
by:glj
date:2018-12-25
function:现金银行汇总统计表
*/
CREATE PROCEDURE Web_QueryCashBankCombList
(
	@ParTypeId		VARCHAR(50),	--父节点ID
	@OperatorId		VARCHAR(50),		--操作员Id
	@queryType		VARCHAR(5),			--1:结算单位 2：职员 3：仓库
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate			VARCHAR(20),		--结束日期
	@ItemTypeID		VARCHAR(MAX),		--账户名称
	@StypeId			VARCHAR(MAX),		--分支机构Id
	@DealBTypeId	VARCHAR(MAX),		--往来单位
	@BTypeId			VARCHAR(MAX),		--结算单位
	@ETypeID			VARCHAR(MAX),		--经手人
	@DTypeID			VARCHAR(MAX),		--部门
	@Cid					INT,						--币种ID

	@BCount			INT=10,			--基本信息的默认个数
	@BPageNo			INT=0				--基本信息的页数
	--@IsPrint			INT=0				--是否是打印算法
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50),@MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)

EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查--------------------------------------------

IF(ISNULL(@ParTypeId,'')='')
	SET @ParTypeId=CASE WHEN @queryType='E' THEN '00001' ELSE '00000' END
	
DECLARE 
	@SQL		VARCHAR(MAX)='',
	@SonNum INT=0
--=============================基本信息权限范围获取【BEGIN】=======================================
--账户信息
CREATE TABLE #Item(RowId INT,Nid INT,TypeID VARCHAR(50),UserCode VARCHAR(200),Fullname VARCHAR(200)) CREATE CLUSTERED INDEX #Stype_P_K ON #Item(TypeId)
INSERT INTO #Item(RowId,Nid,TypeID,UserCode,Fullname)
SELECT 
	ROW_NUMBER()OVER(ORDER BY I.usercode) RowId,
	I.nId,
	i.nTypeId,
	i.UserCode,
	i.FullName
FROM dbo.F_GetAllManagerBaseTypeId(@ItemTypeID,5,@OperatorId) F
INNER JOIN Ac_Items I ON I.nId=F.TypeId AND I.SonNum=0 AND F.TypeId NOT IN(27,39)--排除(1151-预付资金 2131-预收资金)


--分支机构
CREATE TABLE #Stype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Stype_P_K ON #Stype(TypeId)
INSERT INTO #Stype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorId)

--往来单位
CREATE TABLE #DealBtype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #DealBtype_P_K ON #DealBtype(TypeId)
INSERT INTO #DealBtype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DealBTypeId,2,@OperatorId)
IF(ISNULL(@DealBTypeId,'')='' AND @queryType IN('E','D'))
	BEGIN
		INSERT INTO #DealBtype(TypeID) VALUES('')
	END
--结算单位
CREATE TABLE #Btype (TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Btype_P_K ON #Btype(TypeId)
INSERT INTO #Btype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorId)
IF(ISNULL(@BTypeId,'')='' AND @queryType IN('E','D'))
	BEGIN
		INSERT INTO #Btype(TypeID) VALUES('')
	END

--经手人
CREATE TABLE #Etype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Etype_P_K ON #Etype(TypeId)
INSERT INTO #Etype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeID,3,@OperatorId) WHERE TypeId<>'00001'

--部门
CREATE TABLE #Dtype(TypeID VARCHAR(50)) CREATE CLUSTERED INDEX #Dtype_P_K ON #Dtype(TypeId)
INSERT INTO #Dtype(TypeID)
SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorId)

DECLARE @type VARCHAR(50)=''
--线性表展现数据
CREATE TABLE #ParType(RowId INT,TypeID VARCHAR(50),SonNum INT,UserCode VARCHAR(200),FullName VARCHAR(200))CREATE CLUSTERED INDEX #ParType_P_K ON #ParType(TypeId)
IF(@queryType='B')--结算单位
	BEGIN
		SELECT  @SonNum =SonNum FROM btype WHERE TypeId = @ParTypeId		
		SET @type='DB.TypeID'
		INSERT INTO #ParType(RowId,TypeID,SonNum,UserCode,FullName)
		SELECT
			ROW_NUMBER()OVER(ORDER BY B.UserCode) RowId,
			B.typeId,
			B.sonnum,
			B.UserCode,
			B.FullName
		FROM F_AllTreeB(@OperatorId) F
		INNER JOIN btype B ON B.typeId=F.typeId
		WHERE 
			(@SonNum>0 AND F.Parid=@ParTypeId) 
			OR (@SonNum=0 AND F.typeId=@ParTypeId)
		ORDER BY B.UserCode
	END
IF(@queryType='E')--职员
	BEGIN
		SELECT  @SonNum =SonNum FROM employee WHERE TypeId = @ParTypeId	
		SET @type='E.TypeID'
		INSERT INTO #ParType(RowId,TypeID,SonNum,UserCode,FullName)
		SELECT
			ROW_NUMBER()OVER(ORDER BY B.UserCode) RowId,
			B.typeId,
			B.sonnum,
			B.UserCode,
			B.FullName
		FROM F_AllTreeE(@OperatorId) F
		INNER JOIN employee B ON B.typeId=F.typeId
		WHERE 
			(@SonNum>0 AND F.Parid=@ParTypeId) 
			OR (@SonNum=0 AND F.typeId=@ParTypeId)
			AND F.typeId<>'00001'
		ORDER BY B.UserCode
	END
IF(@queryType='D')--部门
	BEGIN
		SELECT  @SonNum =SonNum FROM Department WHERE TypeId = @ParTypeId	
		SET @type='D.TypeID'
		INSERT INTO #ParType(RowId,TypeID,SonNum,UserCode,FullName)
		SELECT
			ROW_NUMBER()OVER(ORDER BY B.UserCode) RowId,
			B.typeId,
			B.sonnum,
			B.UserCode,
			B.FullName
		FROM F_AllTreeD(@OperatorId) F
		INNER JOIN Department B ON B.typeId=F.typeId
		WHERE 
			(@SonNum>0 AND F.Parid=@ParTypeId) 
			OR (@SonNum=0 AND F.typeId=@ParTypeId)
		ORDER BY B.UserCode
	END
--=============================基本信息权限范围获取【END】=======================================

--=============================业务处理【BEGIN】=====================================

SET @SQL='SELECT
	P.TypeID,
	P.SonNum,
	p.UserCode,
	p.FullName,
	SUM(ISNULL(F.Ntotal,0)) totalfor,
	SUM(ISNULL(F.Total,0)) total'

IF @bCount=10
BEGIN
	SELECT @SQL=@SQL +'	,ISNULL(SUM(CASE WHEN F.AtypeId='+CAST(Nid AS VARCHAR)+'  THEN ISNULL(F.NTotal,0) ELSE 0 END),0) ['+CAST(Nid AS VARCHAR)+'-'+FullName+'-原币]
						,ISNULL(SUM(CASE WHEN F.AtypeId ='+CAST(Nid AS VARCHAR)+'  THEN ISNULL(F.Total,0) ELSE 0 END),0) ['+CAST(Nid AS VARCHAR)+'-'+FullName+'-本币]'  
	FROM #Item 
	WHERE RowId BETWEEN (@BPageNo-1)*@BCount+1 AND @BCount*@BPageNo
	ORDER BY RowId
END
ELSE 
BEGIN
	SELECT @SQL=@SQL +'	,ISNULL(SUM(CASE WHEN F.AtypeId='+CAST(Nid AS VARCHAR)+'  THEN ISNULL(F.NTotal,0)  ELSE 0 END),0) ['+CAST(Nid AS VARCHAR)+'-'+FullName+'-原币]
						,ISNULL(SUM(CASE WHEN  F.AtypeId='+CAST(Nid AS VARCHAR)+'  THEN ISNULL(F.Total,0) ELSE 0 END),0) ['+CAST(Nid AS VARCHAR)+'-'+FullName+'-本币]'  
	FROM #Item ORDER BY RowId 
END 

SET @SQL+='
FROM #ParType P
LEFT JOIN (
	SELECT
		'+@type+',
		L.AtypeId,
		SUM(L.Total) Total,
		SUM(L.NTotal) Ntotal
	FROM ListTable  L
	INNER JOIN #Item A ON A.Nid=L.AtypeId
	INNER JOIN #Etype E ON E.TypeID=L.EtypeId
	INNER JOIN #Dtype D ON D.TypeID=L.DtypeId
	INNER JOIN #Stype S ON S.TypeID=L.STypeID--分支机构
	INNER JOIN BillIndex I ON I.BillNumberId=L.BillNumberId AND L.BillType=I.BillType
	INNER JOIN #Btype B ON B.TypeID=I.btypeid
	INNER JOIN #DealBtype DB ON DB.TypeID=I.DealBTypeID
	WHERE	l.BillDate BETWEEN '''+@StartDate+''' AND '''+ @EndDate+'''
			AND L.CID='+CAST(@Cid AS VARCHAR)+'
	GROUP BY '+@type+',L.AtypeId
) F ON F.TypeID LIKE P.TypeID+''%''
GROUP BY 
	P.RowId,
	P.TypeID,
	P.SonNum,
	p.UserCode,
	p.FullName
ORDER BY 
	P.RowId
'

--PRINT(@SQL)
EXEC(@SQL)

--=============================业务处理【END】=======================================

--=============================删除临时表【BEGIN】=====================================

DROP TABLE #Btype,#DealBtype,#Dtype,#Etype,#Item,#Stype,#ParType

--=============================删除临时表【END】=======================================

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCDistList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCDistList]
GO





/*
	作者：谢吉康
	日期：2007-4-5
	描述：调拨分布表
*/
CREATE PROCEDURE Web_QueryCDistList
(
	@OperatorId		varchar(100),
	@PTypeId		varchar(100),
	@ETypeId		varchar(100),
	@StartDate		datetime,
	@EndDate		datetime,
	@inKTypeId		varchar(8000),
	@outKTypeId		varchar(8000),
	@aPageNo		int = 1,		-- 仓库信息的翻页
	@bCount			int = 10,
	@showTotal		int = 1,
	@showQtyCj		int = 1
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorId is null return 1

declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorId,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--仓库权限有效
DECLARE @intRe int
EXEC @intRe=GP_CheckLimit @OperatorID,454

--处理仓库信息
DECLARE @KTypeId1			varchar(100),		--查询仓库的ID
		@KTypeId2			varchar(100),
		@KTypeId2FullName	varchar(256)

SELECT  @KTypeId1 = TypeId FROM Stock WHERE FullName = @inKTypeId
CREATE TABLE #Stock
(
	TypeId		varchar(100),
	UserCode	varchar(256),
	FullName	varchar(266)
)
IF @outKTypeId = '全部仓库'
	BEGIN
		IF @intRe = 0
			INSERT INTO #Stock(TypeId,UserCode,FullName)SELECT S.TypeId,S.UserCode,S.FullName FROM Stock S WHERE S.TypeID <> @KTypeId1 AND S.Deleted = 0 AND S.SonNum = 0 AND TypeId LIKE @MKTypeId + '%' ORDER BY S.UserCode
		ELSE
			INSERT INTO #Stock(TypeId,UserCode,FullName)SELECT S.TypeId,S.UserCode,S.FullName FROM Stock S WHERE S.TypeID <> @KTypeId1 AND S.Deleted = 0 AND S.SonNum = 0 ORDER BY S.UserCode
	END
ELSE
	BEGIN
		DECLARE @aFullName 	varchar(256),
				@aPTypeId	varchar(100)

		DECLARE KCursor CURSOR FOR
			SELECT	* FROM F_Split(@outKTypeID,',')

		OPEN KCursor

		FETCH NEXT FROM KCursor INTO @aFullName

		WHILE @@FETCH_STATUS = 0
			BEGIN
				SELECT @aPTypeId = TypeId FROM Stock WHERE FullName =  @aFullName

				IF EXISTS(SELECT TOP 1 1 FROM Stock WHERE TypeId = @aPTypeId AND SonNum = 0)
					INSERT INTO #Stock(TypeId,UserCode,FullName) SELECT TypeId,UserCode,FullName FROM Stock WHERE TypeId = @aPTypeId
				ELSE
					INSERT INTO #Stock(TypeId,UserCode,FullName) SELECT TypeId,UserCode,FullName FROM Stock WHERE TypeId LIKE @aPTypeId + '%' AND SonNum = 0 AND Deleted = 0

				FETCH NEXT FROM KCursor INTO @aFullName
			END

		CLOSE KCursor
		DEALLOCATE KCursor
	END

SELECT 	COUNT(*) AS nCount FROM #Stock

--删除临时表
DROP TABLE #Stock






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCheckGetMoney]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCheckGetMoney]
GO





/*
	作者：谢吉康
	日期：2005-8-8
	描述：制单人收款统计
*/
CREATE PROCEDURE Web_QueryCheckGetMoney
(
	@OperatorID		varchar(100),	--操作员ID
	@StartDate		varchar(20),	--开始日期
	@EndDate		varchar(20),	--截至日期	
	@PageRows 		int=14,
	@GoPageNo 		int=0,
	@EUserCode		varchar(256),	--职员编号
	@EFullName		varchar(256)	--职员名称
)
--@encode$--
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--SELECT * FROM AType WHERE (TypeId = '0000100003' OR TypeId LIKE '0000100004%') AND SonNum = 0 AND Deleted = 0 ORDER BY TypeId
DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000)

--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		TypeId 		varchar (100) NOT NULL,
		职员编号 	varchar (200) NULL ,
		职员名称 	varchar (256) NOT NULL,
		总计 		 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

SELECT @SQLTemp='INSERT '+N'##'+@TableName+'
		(
			TypeId,
			职员编号,
			职员名称,
			总计
		) 
		SELECT 	TypeId,
				UserCode,
				FullName,
				0 
		FROM 	Employee 
		WHERE 	Deleted = 0 
				AND (TypeId = ''00001'' OR SonNum =0) 
				AND UserCode LIKE '+char(39)+'%'+@EUserCode+'%'+char(39)+'
				AND FullName LIKE '+char(39)+'%'+@EFullName+'%'+char(39)+'
		ORDER BY UserCode '


EXEC(@SQLTemp)


--计算总计数据
SET @SQL = ''
SET @SQL = '
	UPDATE '+N'##'+@TableName+'
	SET	[总计]=B.Total
	FROM '+N'##'+@TableName+' A
	INNER JOIN (
				SELECT	X.TypeId,
						ISNULL(SUM(X.Total),0) AS Total
				FROM (
						SELECT	A.TypeId,
								ISNULL(G.Total,0) AS Total
						FROM 	'+N'##'+@TableName+' A
						INNER JOIN (
									SELECT	Checke,
											ISNULL(SUM(
														CASE 
															WHEN BillType IN (305,11,141,4) 	THEN ISNULL(TotalInMoney,0)
															ELSE -1*ISNULL(TotalInMoney,0)
														END 
													),0) AS Total
									FROM	BillIndex
									WHERE	IfCheck = ''t''
											AND RedWord = 0
											AND BillType IN (305,11,45,141,4)
											AND BillDate>='+char(39)+@StartDate+char(39)+'
											AND BillDate<='+char(39)+@EndDate+char(39)+'
									GROUP BY Checke
								)G ON G.Checke=A.TypeId 
					)X
				GROUP BY X.TypeId
	)B ON A.TypeId = B.TypeId '

--PRINT(@Sql)
EXEC(@Sql)

SET @SQL = ''
SET @ReSQL = ''

SET @ReSql='SELECT TypeId,职员编号,职员名称,总计'

DECLARE @ATypeId	varchar(100),
		@AFullName	varchar(256)

DECLARE ATypeCursor CURSOR FOR
	SELECT 	TypeId,
			FullName 
	FROM 	AType 
	WHERE 	(TypeId = '0000100003' OR TypeId LIKE '0000100004%') 
			AND SonNum = 0 
			AND Deleted = 0 
			AND TypeId LIKE @MATypeId + '%'
	ORDER BY TypeId

OPEN ATypeCursor

FETCH NEXT FROM ATypeCursor INTO @ATypeId,@AFullName

WHILE @@FETCH_STATUS = 0
	BEGIN
		--修改表结构
		SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @AFullName + ']  NUMERIC(24, 10) '
		EXEC(@SQL)

		SET @SQL = ''
		--计算具体的数据
		SET @SQL = '
			UPDATE '+N'##'+@TableName+'
			SET	['+@AFullName+']=ISNULL(B.Total,0)
			FROM '+N'##'+@TableName+' A
			LEFT JOIN (
						SELECT	X.Checke,
								X.ATypeId,
								ISNULL(SUM(X.Total),0) AS Total
						FROM (
								SELECT	Checke,
										ATypeId,
										ISNULL(SUM(
											CASE 
												WHEN BillType IN (305,11,141) THEN ISNULL(TotalInMoney,0)
												ELSE -1*ISNULL(TotalInMoney,0)
											END
										),0) AS Total
								FROM 	BillIndex
								WHERE	ATypeId LIKE '+char(39)+@ATypeId+char(39)+'
										AND BillDate>='+char(39)+@StartDate+char(39)+'
										AND BillDate<='+char(39)+@EndDate+char(39)+'
										AND BillType IN (305,11,141,45)
								GROUP BY Checke,ATypeId
								UNION ALL
								SELECT	Bil.Checke,
										G.ATypeId,
										ISNULL(SUM(G.Total),0) AS Total
								FROM 	gatheringBill G,
										BillIndex Bil
								WHERE	G.BillNumberId = Bil.BillNumberId
										AND Bil.IfCheck = ''t''
										AND Bil.RedWord = 0
										AND Bil.BillType = 4 
										AND G.ATypeId LIKE '+char(39)+@ATypeId+char(39)+'
										AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
										AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
								GROUP BY Bil.Checke,G.ATypeId
							)X GROUP BY X.Checke,X.ATypeId
			)B ON A.TypeId = B.Checke '
		EXEC(@SQL)
		
		FETCH NEXT FROM ATypeCursor INTO @ATypeId,@AFullName
	END

CLOSE ATypeCursor
DEALLOCATE ATypeCursor


-- 删除临时表
SELECT @ReSQL='
				SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE '+N'##'+@TableName
EXEC(@ReSQL)








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCheckGetMoneyDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCheckGetMoneyDetail]
GO



/*
	作者：谢吉康
	日期：2005-8-9
	描述：制单人收款统计
	
	修改：舒珊
	日期：2016年2月25日
	描述：增添表头自定义显示字段
*/
CREATE PROCEDURE Web_QueryCheckGetMoneyDetail
(
	@OperatorId		VARCHAR(100),	--操作员Id
	@ETypeId		VARCHAR(100),	--制单人
	@ATypeId		VARCHAR(100),	--账户
	@STypeId		VARCHAR(8000),	--分支机构
	@StartDate		VARCHAR(20),	--开始日期
	@EndDate		VARCHAR(20),	--结束日期	
	@BillTypeId		VARCHAR(100),	--单据类型
	@SortField		VARCHAR(200),	--排序字段
	@SortType		VARCHAR(200),	--排序类型
	@CID            INT=1           --默认为1	
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 			VARCHAR(MAX),
		@ReSQL			VARCHAR(1000),
		@TableName		VARCHAR(1000),
		@SQLCursor		VARCHAR(8000),
		@TypeId			VARCHAR(100),
		@UserCode		VARCHAR(256),
		@FullName		VARCHAR(256),
		@SQLTemp		VARCHAR(8000),
		@CloseCursor	VARCHAR(8000)
		
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)		

--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

--优惠券单据
SET @SQL = '

			SELECT * FROM (SELECT
					B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.BTypeId,
					B.STypeId,
					CASE WHEN B.BILLTYPE = 424 THEN B.TotalQty
					WHEN B.BILLTYPE = 426 THEN -1 * B.TotalQty END AS TotalQty,
					CASE WHEN B.BILLTYPE = 424 THEN B.nTotalMoney
					WHEN B.BILLTYPE = 426 THEN -1 * B.nTotalMoney END AS NTotalMoney,
					CASE WHEN B.BillType IN (424) Then B.nPreferenceMoney
					WHEN B.BILLTYPE = 426 THEN -1*B.NPreferenceMoney
					END  AS NPreferenceMoney,
					X.ATypeId,
					X.NTotal,
					B.Comment,
					'''' as Explain,
					0 as ID,
					B.POSTTIME,
					SysDiy1_head,
					SysDiy2_head,
					SysDiy3_head,
					SysDiy4_head, 
					SysDiy5_head,
					SysDiy6_head,
					SysDiy7_head,
					SysDiy8_head,
					SysDiy9_head,
					SysDiy10_head,
					SysDiy11_head,
					SysDiy12_head,
					SysDiy13_head,
					SysDiy14_head,
					SysDiy15_head,
					SysDiy16_head,
					SysDiy17_head,
					SysDiy18_head,
					SysDiy19_head,
					SysDiy20_head,
					SysDiy21_head,
					SysDiy22_head,
					SysDiy23_head,
					SysDiy24_head,
					SysDiy25_head,
					SysDiy26_head,
					SysDiy27_head,
					SysDiy28_head,
					SysDiy29_head,
					SysDiy30_head,
					SysDiy31_head,
					SysDiy32_head 
			FROM	Coupon_BillIndex B
			LEFT JOIN Custom_BillIndex csindex on B.billnumberid=csindex.BillId and B.billtype=csindex.billtype	
			INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
			INNER JOIN(
						SELECT	Bil.BillNumberID,
								mul.ATypeId,
								CASE WHEN BIL.BILLTYPE = 424 THEN ISNULL(mul.NTotalMoney,0)
								WHEN BIL.BILLTYPE = 426 THEN -1*ISNULL(mul.NTotalMoney,0) END AS NTotal
						FROM	Coupon_BillIndex Bil,
								BillMulAccount mul,
								Employee E,
								LoginUser L,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	Bil.Checke = E.TypeId
								AND mul.billnumberid=bil.billnumberid and mul.billtype in (424,426) and bil.billtype = mul.billtype
								AND E.TypeId = L.ETypeId
								AND Bil.STypeId = S.TypeId
								AND Bil.DTypeId = D.TypeId								
								AND Bil.IfCheck = ''t''							
								AND Bil.RedWord = 0
								AND Bil.IfYearBill = 0
								AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
								AND Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bil.Checke = '+CHAR(39)+@ETypeId+CHAR(39)+'
								AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
						IF @ATypeId <> ''
							SET @SQL = @SQL + '	AND mul.ATypeId = '+CHAR(39)+@ATypeId+CHAR(39)
                        SET @SQL=@SQL+' AND Bil.CID='+CONVERT(VARCHAR,@CID)
						SET @SQL = @SQL + '	AND (mul.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+')))
					
						UNION ALL
						SELECT	Bil.BillNumberID,
								G.ATypeId,
								G.NTotal
						FROM 	PreBill G,
								Coupon_BillIndex Bil,
								Employee E,
								LoginUser L,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	G.BillNumberId = Bil.BillNumberId and G.BILLTYPE = BIL.BILLTYPE
								AND Bil.Checke = E.TypeId
								AND E.TypeId = L.ETypeId
								AND Bil.STypeId = S.TypeId
								AND Bil.DTypeId = D.TypeId								
								AND Bil.IfCheck = ''t''
								AND Bil.RedWord = 0
								AND Bil.IfYearBill = 0
								AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
								AND Bil.Checke =	'+CHAR(39)+@ETypeId+CHAR(39)+'
								AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
						IF @ATypeId <> ''
							SET @SQL = @SQL + '	AND G.ATypeId = '+CHAR(39)+@ATypeId+CHAR(39)
                        SET @SQL=@SQL+' AND Bil.CID='+CONVERT(VARCHAR,@CID)
						SET @SQL = @SQL + '	AND G.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+'))	
								AND Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'								
				)X ON B.BillNumberId = X.BillNumberId
			WHERE ISNULL(X.NTotal,''0'')<>0  AND b.ifYearBill=0'+'  --年节存标志	
            '
            


SET @SQL += 'UNION ALL
			SELECT	B.BillNumberId,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.ETypeId,
					B.BTypeId,
					B.STypeId,
					CASE 
						WHEN B.BillType IN (305,11,141,160,93,85,213,157,4,167,168,172,178,181,312,182,179,186,195,196,12) Then B.TotalQty
						ELSE -1*B.TotalQty
					END AS TotalQty,
					CASE 
						WHEN B.BillType IN (305,11,141,160,93,85,213,157,4,167,168,172,178,181,312,182,179,186,189,195,196,12) Then B.nTotalMoney
						ELSE -1*B.NTotalMoney
					END AS NTotalMoney,
					CASE 
						WHEN B.BillType IN (305,11,141,160,93,85,213,157,4,167,168,172,178,181,312,182,179,186,195,196,12) Then B.nPreferenceMoney
						ELSE -1*B.NPreferenceMoney
					END AS NPreferenceMoney,
					X.ATypeId,
					X.NTotal,
					B.Comment,
					B.Explain,
					B.ID,
					B.POSTTIME,
					SysDiy1_head,
					SysDiy2_head,
					SysDiy3_head,
					SysDiy4_head, 
					SysDiy5_head,
					SysDiy6_head,
					SysDiy7_head,
					SysDiy8_head,
					SysDiy9_head,
					SysDiy10_head,
					SysDiy11_head,
					SysDiy12_head,
					SysDiy13_head,
					SysDiy14_head,
					SysDiy15_head,
					SysDiy16_head,
					SysDiy17_head,
					SysDiy18_head,
					SysDiy19_head,
					SysDiy20_head,
					SysDiy21_head,
					SysDiy22_head,
					SysDiy23_head,
					SysDiy24_head,
					SysDiy25_head,
					SysDiy26_head,
					SysDiy27_head,
					SysDiy28_head,
					SysDiy29_head,
					SysDiy30_head,
					SysDiy31_head,
					SysDiy32_head 
			FROM	BillIndex B
			LEFT JOIN Custom_BillIndex csindex on B.billnumberid=csindex.BillId and B.billtype=csindex.billtype	
			INNER JOIN #GetManSTypeId S ON S.TypeId = B.STypeId
			INNER JOIN(
						SELECT	Bil.BillNumberID,
								mul.ATypeId,
								CASE 
									WHEN Bil.BillType IN (305,11,141,160,93,85,157,167,168,172,178,181,312,182,179,186,196,12) 	THEN ISNULL(mul.NTotalMoney,0)
									WHEN (BIL.billtype =''213'' and at.AuditType =7) THEN 1*ISNULL(mul.NTotalMoney,0)
									ELSE -1*ISNULL(mul.NTotalMoney,0)
								END AS NTotal
						FROM	BillIndex Bil
								left join Ac_AssetBusinessType at on bil.AssetBusinessTypeId=at.id,
								BillMulAccount mul,
								Employee E,
								LoginUser L,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	Bil.BillType <> 195
								AND Bil.Checke = E.TypeId
								AND mul.billnumberid=bil.billnumberid and bil.billtype = mul.billtype
								AND E.TypeId = L.ETypeId
								AND Bil.STypeId = S.TypeId
								AND Bil.DTypeId = D.TypeId								
								AND Bil.IfCheck = ''t''
								AND Bil.RedWord = 0
								AND Bil.IfYearBill = 0
								AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
								AND Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bil.Checke = '+CHAR(39)+@ETypeId+CHAR(39)+'
								AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
						IF @ATypeId <> ''
							SET @SQL = @SQL + '	AND mul.ATypeId = '+CHAR(39)+@ATypeId+CHAR(39)
                        SET @SQL=@SQL+' AND Bil.CID='+CONVERT(VARCHAR,@CID)
						SET @SQL = @SQL + '	AND (mul.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+')))
						UNION ALL
						SELECT	Bil.BillNumberID,
								mul.ATypeId,
								CASE 
									WHEN Bil.BillType IN (195) 	THEN ISNULL(mul.NTotalMoney,0)
									ELSE 0
								END AS NTotal
						FROM	BillIndex Bil
								left join Ac_AssetBusinessType at on bil.AssetBusinessTypeId=at.id,
								BillMulAccount mul,
								Employee E,
								LoginUser L,
								#GetManSTypeId S,
								#GetManDTypeId D,
								BillIndex_CarRepair Bic
						WHERE	Bil.BillType = 195
								AND Bil.Checke = E.TypeId
								AND mul.billnumberid=bil.billnumberid
								AND Bil.BillNumberId = Bic.BillNumberId
								AND E.TypeId = L.ETypeId
								AND Bil.STypeId = S.TypeId
								AND Bil.DTypeId = D.TypeId								
								AND Bil.IfCheck = ''t''
								AND Bil.RedWord = 0
								AND Bil.IfYearBill = 0
								AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
								AND CONVERT(VARCHAR(10),Bic.BalanceDate,120)>='+CHAR(39)+@StartDate+CHAR(39)+'
								AND CONVERT(VARCHAR(10),Bic.BalanceDate,120)<='+CHAR(39)+@EndDate+CHAR(39)+'
								AND Bil.Checke = '+CHAR(39)+@ETypeId+CHAR(39)+'
								AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
						IF @ATypeId <> ''
							SET @SQL = @SQL + '	AND mul.ATypeId = '+CHAR(39)+@ATypeId+CHAR(39)
                        SET @SQL=@SQL+' AND Bil.CID='+CONVERT(VARCHAR,@CID)
						SET @SQL = @SQL + '	AND (mul.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+')))
						UNION ALL						
						SELECT	Bil.BillNumberID,
								G.ATypeId,
								ISNULL(G.NTotal,0) AS NTotal
						FROM 	gatheringBill G,
								BillIndex Bil,
								Employee E,
								LoginUser L,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	G.BillNumberId = Bil.BillNumberId
								AND Bil.Checke = E.TypeId
								AND E.TypeId = L.ETypeId
								AND Bil.STypeId = S.TypeId
								AND Bil.DTypeId = D.TypeId								
								AND Bil.IfCheck = ''t''
								AND Bil.RedWord = 0
								AND Bil.IfYearBill = 0
								AND Bil.BillType = 4 
								AND Bil.Checke =	'+CHAR(39)+@ETypeId+CHAR(39)+'
								AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
						IF @ATypeId <> ''
							SET @SQL = @SQL + '	AND G.ATypeId = '+CHAR(39)+@ATypeId+CHAR(39)
                        SET @SQL=@SQL+' AND Bil.CID='+CONVERT(VARCHAR,@CID)
						SET @SQL = @SQL + '	AND G.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+'))	
								AND Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
						UNION ALL
						SELECT	Bil.BillNumberID,
								G.ATypeId,
								G.NTotal
						FROM 	PreBill G,
								BillIndex Bil,
								Employee E,
								LoginUser L,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	G.BillNumberId = Bil.BillNumberId
								AND Bil.Checke = E.TypeId
								AND E.TypeId = L.ETypeId
								AND Bil.STypeId = S.TypeId
								AND Bil.DTypeId = D.TypeId								
								AND Bil.IfCheck = ''t''
								AND Bil.RedWord = 0
								AND Bil.IfYearBill = 0
								AND Bil.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
								AND Bil.Checke =	'+CHAR(39)+@ETypeId+CHAR(39)+'
								AND Bil.Checke IN (SELECT * FROM F_GetManDetailEType('+CHAR(39)+@OperatorID+CHAR(39)+'))'
						IF @ATypeId <> ''
							SET @SQL = @SQL + '	AND G.ATypeId = '+CHAR(39)+@ATypeId+CHAR(39)
                        SET @SQL=@SQL+' AND Bil.CID='+CONVERT(VARCHAR,@CID)
						SET @SQL = @SQL + '	AND G.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+CHAR(39)+@OperatorID+CHAR(39)+'))	
								AND Bil.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
								AND Bil.BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'								
				)X ON B.BillNumberId = X.BillNumberId
			WHERE ISNULL(X.NTotal,''0'')<>0 AND b.ifYearBill=0) B'  --年节存标志	
IF UPPER(@SortField)='B.BILLDATE'
	SET @SQL=@SQL+' ORDER BY '+@SortField+' '+@SortType+',B.billcode '
ELSE
	SET @SQL=@SQL+' ORDER BY '+@SortField+' '+@SortType
PRINT @SQL
EXEC(@SQL)

			
DROP TABLE #GetManSTypeId,#GetManDTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCheckGetMoneyList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCheckGetMoneyList]
GO

/*
	作者：谢吉康
	日期：2005-8-9
	描述：制单人收款统计
*/
CREATE PROCEDURE Web_QueryCheckGetMoneyList
(
	@OperatorId		varchar(100),	--操作员Id
	@StartDate		varchar(20),	--开始日期
	@STypeId		varchar(8000),	--分支机构
	@EndDate		varchar(20),	--结束日期	
	@PageRows 		int=14,			--默认显示行数
	@GoPageNo 		int=0,			--商品的页数
	@EUserCode		varchar(256),	--职员编号
	@EFullName		varchar(256),	--职员名称
	@bCount			int=10,			--基本信息的默认个数
	@bPageNo		int=0,			--基本信息的页数
	@BillTypeId		varchar(1000),	--单据类型
	@cid			int = 1
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 			varchar(8000),
		@ReSQL			varchar(1000),
		@TableName		varchar(1000),
		@SQLCursor		varchar(8000),
		@TypeId			varchar(100),
		@UserCode		varchar(256),
		@FullName		varchar(256),
		@SQLTemp		varchar(8000),
		@CloseCursor	varchar(8000),
		@wherecid		VARCHAR(200)
		
IF @cid = 0 OR @cid='' OR @cid IS NULL
	SET @WhereCid = ''
ELSE
	SET @WhereCid = ' AND Bil.CID='+CONVERT(VARCHAR,@CID)+'  '
		
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)			

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	


CREATE TABLE #BANK(TypeId VARCHAR(50))
INSERT INTO #BANK(TypeId) SELECT AC.NID FROM ac_items AC
/*账户权限范围控制*/      INNER JOIN (SELECT nid AS typeid FROM dbo.F_LineA(@OperatorID)) F ON AC.NID=F.TypeID	
                          WHERE  AC.TypeName='B' AND AC.UserCode NOT IN('2181','2131','1151')
 



--转换时间生成临时表
SELECT 	@TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))

SELECT 	@SQL='CREATE TABLE '+N'##'+@TableName+'
	(
		TypeId 		varchar (100) NOT NULL,
		父节点		varchar (100) NOT NULL,
		职员编号 	varchar (200) NULL ,
		职员名称 	varchar (256) NOT NULL,
		总计		 NUMERIC(24, 10) 
	)'

EXEC(@SQL)

--********************************************************************************写入商品信息*****************************************************************
DECLARE @TypeIDTmp		varchar(8000),
		@SonNumTmp		varchar(100),
		@UserCodeTmp	varchar(8000),
		@FullNameTmp	varchar(8000),		
		@CruSonNum		int

IF @METypeId = '-99999'
	SET @SQLCursor = '    
	        DECLARE    PType_Cursor CURSOR    FOR 
		            SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
							E.TypeID,
							E.SonNum,
							E.UserCode,
							E.FullName
		            FROM    Employee E
							INNER JOIN LoginUser L ON E.TypeId = L.ETypeId
							INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') D ON E.TypeId = D.TypeId
		            WHERE  	E.UserCode NOT IN                    
		                    (
		                        SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' E.UserCode
		                        FROM	Employee E
										INNER JOIN LoginUser L ON E.TypeId = L.ETypeId
										INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') D ON E.TypeId = D.TypeId
								WHERE   E.TypeId = L.ETypeId										
										AND E.UserCode LIKE '+char(39)+'%'+@EUserCode+'%'+char(39)+'
										AND E.FullName LIKE '+char(39)+'%'+@EFullName+'%'+char(39)+'                    										
		                        ORDER BY
										E.UserCode
		                    ) 
							AND E.UserCode LIKE '+char(39)+'%'+@EUserCode+'%'+char(39)+'
							AND E.FullName LIKE '+char(39)+'%'+@EFullName+'%'+char(39)+'
		            ORDER BY E.UserCode '	
ELSE
	SET @SQLCursor = '    
	        DECLARE    PType_Cursor CURSOR    FOR 
		            SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
							E.TypeID,
							E.SonNum,
							E.UserCode,
							E.FullName
		            FROM    Employee E,
							LoginUser L
		            WHERE  	E.TypeId = L.ETypeId							
		                    AND E.UserCode NOT IN                    
		                    (
		                        SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' E.UserCode
		                        FROM	Employee E,
										LoginUser L
								WHERE   E.TypeId = L.ETypeId										
										AND E.UserCode LIKE '+char(39)+'%'+@EUserCode+'%'+char(39)+'
										AND E.FullName LIKE '+char(39)+'%'+@EFullName+'%'+char(39)+'                    
		                        ORDER BY
										E.UserCode
		                    ) 
							AND E.UserCode LIKE '+char(39)+'%'+@EUserCode+'%'+char(39)+'
							AND E.FullName LIKE '+char(39)+'%'+@EFullName+'%'+char(39)+'
		            ORDER BY E.UserCode '	

            EXEC(@SQLCursor)                    --执行游标算法
            
           --return
            OPEN PType_Cursor            --打开游标
            
            FETCH NEXT FROM PType_Cursor INTO @TypeIDTmp,@SonNumTmp,@UserCodeTmp,@FullNameTmp

            WHILE @@FETCH_STATUS = 0    --循环写入临时表
                BEGIN
					SELECT @SQLTemp='INSERT '+N'##'+@TableName+'
							(
								TypeId,
								父节点,

								职员编号,
								职员名称,
								总计
							)VALUES(

								'+char(39)+@TypeIDTmp+char(39)+',
								'+char(39)+@SonNumTmp+char(39)+',
								'+char(39)+@UserCodeTmp+char(39)+',
								'+char(39)+@FullNameTmp+char(39)+',
								''0''
							)'


					EXEC(@SQLTemp)

					FETCH NEXT FROM Ptype_Cursor INTO @TypeIDTmp,@SonNumTmp,@UserCodeTmp,@FullNameTmp
                END

			--关闭游标
			SELECT @CloseCursor = '
                      CLOSE PType_Cursor
                      DEALLOCATE PType_Cursor'

			EXEC(@CloseCursor)

CREATE TABLE #BillIndex
(
	ATypeId			VARCHAR(100),
	Checke			VARCHAR(100),
	BillType		VARCHAR(100),
	Total			 NUMERIC(24, 10) 
)

--普通单据
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	mul.ATypeId,
					Bil.Checke,
					Bil.BillType,
					ISNULL(SUM(
								CASE 
									WHEN BIL.BillType IN (305,11,141,160,93,85,157,167,168,172,178,182,179,181,312,196,12) 	THEN ISNULL(mul.NTotalMoney,0)	
									WHEN (BIL.billtype =''213'' and at.AuditType =7) THEN ISNULL(mul.NTotalMoney,0)
									ELSE -1*ISNULL(mul.NTotalMoney,0)
								END 
							),0) AS Total
			FROM	BillIndex Bil
					left join Ac_AssetBusinessType at on bil.AssetBusinessTypeId=at.id,
					BillMulAccount mul,
					#BANK  b
			WHERE	Bil.BillType <> 195
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.billnumberid=mul.billnumberid and bil.billtype = mul.billtype
					AND Bil.IfYearBill = 0
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND mul.ATypeId = b.typeid 
					AND Bil.BillType IN (SELECT * FROM F_Split('+char(39)+@BillTypeId+char(39)+','',''))' +@WhereCid
					
--IF @MATypeId = '-99999'
--	SET @SQL = @SQL + '	AND (mul.ATypeId IN (SELECT * FROM F_GetManDetailAType('+char(39)+@OperatorID+char(39)+')))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '		
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT * FROM #GetManDTypeId) '	

SET @Sql=@Sql + ' AND Bil.ifYearBill= 0 '    --年节存标志

SET @SQL = @SQL + '	GROUP BY mul.ATypeId,Bil.Checke,Bil.BillType'
EXEC(@SQL)
--PRINT @SQL


--SELECT * FROM #BillIndex
--RETURN

SET @sql=''
--处理收款单
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	G.ATypeId,
					Bil.Checke,
					Bil.BillType,
					ISNULL(SUM(G.NTotal),0) AS Total
			FROM 	gatheringBill G,
					BillIndex Bil,
					#bank b
			WHERE	G.BillNumberId = Bil.BillNumberId 
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND g.ATypeId = b.typeid --AND (G.ATypeId = ''0000100003'' OR G.ATypeId LIKE ''0000100004%'')
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.IfYearBill = 0
					AND Bil.BillType = 4'+@WhereCid
					
IF @MATypeId = '-99999'
	SET @SQL = @SQL + '	AND G.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+char(39)+@OperatorID+char(39)+'))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '	
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT TypeId FROM #GetManDTypeId) '		

SET @Sql=@Sql + ' AND Bil.ifYearBill= 0 '    --年节存标志
SET @SQL = @SQL + '	GROUP BY G.ATypeId,Bil.Checke,Bil.BillType'
EXEC(@SQL)
--print(@sql)
--加预收款单
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	G.ATypeId,
					Bil.Checke,
					Bil.BillType,
					ISNULL(SUM(
								CASE    WHEN BIL.BILLTYPE<>''213''  THEN G.NTotal
										WHEN (BIL.billtype =''213'' and at.AuditType in(10,11)) THEN G.NTotal ELSE 0 
								END
							),0) AS Total
			FROM 	PreBill G,
					BillIndex Bil 
					left join Ac_AssetBusinessType at on bil.AssetBusinessTypeId=at.id,
					#bank b
			WHERE	G.BillNumberId = Bil.BillNumberId 
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND g.ATypeId = b.typeid --AND (G.ATypeId = ''0000100003'' OR G.ATypeId LIKE ''0000100004%'' OR G.ATypeId = ''0000200006'')
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.IfYearBill = 0
					AND Bil.BillType IN (SELECT a FROM F_Split('+char(39)+@BillTypeId+char(39)+','','')) ' +@WhereCid
					
IF @MATypeId = '-99999'
	SET @SQL = @SQL + '	AND G.ATypeId IN (SELECT nid FROM F_GetManDetailAType('+char(39)+@OperatorID+char(39)+'))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '	
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT TypeId FROM #GetManDTypeId) '		

SET @Sql=@Sql + ' AND Bil.ifYearBill= 0 '    --年节存标志

SET @SQL = @SQL + '	GROUP BY G.ATypeId,Bil.Checke,Bil.BillType'

EXEC(@SQL)

--优惠券出库单、优惠券退货单
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	mul.ATypeId,
					Bil.Checke,
					Bil.BillType,
					ISNULL(SUM(
								CASE 
									WHEN BIL.BillType = 424 THEN ISNULL(mul.NTotalMoney,0)	
									WHEN BIL.BillType = 426 THEN -1 * ISNULL(mul.NTotalMoney,0)
								END 
							),0) AS Total
			FROM	Coupon_BillIndex Bil,
					BillMulAccount mul,
					#BANK  b
			WHERE	Bil.BillType in (424,426)
			        AND mul.BillType in (424,426)
					AND Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.billnumberid=mul.billnumberid
					AND Bil.IfYearBill = 0
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND mul.ATypeId = b.typeid 
					AND Bil.BillType IN (SELECT * FROM F_Split('+char(39)+@BillTypeId+char(39)+','',''))' +@WhereCid
					
--IF @MATypeId = '-99999'
--	SET @SQL = @SQL + '	AND (mul.ATypeId IN (SELECT * FROM F_GetManDetailAType('+char(39)+@OperatorID+char(39)+')))'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' AND Bil.STypeId IN (SELECT TypeId FROM #GetManSTypeId) '		
	
IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' AND Bil.DTypeId IN (SELECT * FROM #GetManDTypeId) '	

SET @Sql=@Sql + ' AND Bil.ifYearBill= 0 '    --年节存标志

SET @SQL = @SQL + '	GROUP BY mul.ATypeId,Checke,Bil.BillType'


EXEC(@SQL)
--print(@sql)
					
--SELECT *FROM #BillIndex
--RETURN
--********************************************************************************计算总合计*****************************************************************
SET @SQL = '
		UPDATE '+N'##'+@TableName+'
		SET 总计 = ISNULL(X.Total,0)
		FROM '+N'##'+@TableName+' A
		INNER JOIN (
				SELECT	X.TypeId,
						ISNULL(SUM(X.Total),0) AS Total
				FROM (
						SELECT	A.TypeId,
								ISNULL(G.Total,0) AS Total
						FROM 	'+N'##'+@TableName+' A	
						LEFT JOIN (
									SELECT	Checke,
											ISNULL(SUM(Total),0) AS Total
									FROM	#BillIndex
									GROUP BY Checke
								)G ON G.Checke=A.TypeId 
					)X GROUP BY X.TypeId
		)X ON X.TypeId = A.TypeId '

EXEC(@SQL)
--********************************************************************************修改临时表*****************************************************************
SET @SQLCursor = ''
DECLARE @bSonNum 		int,
		@BaseTypeId		varchar(100),
		@BaseFullName	varchar(256),
		@xjkang			varchar(256)

IF @MATypeId = '-99999'
	SET @SQLCursor = '
		DECLARE BaseTypeCursor CURSOR FOR
		    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
					NID AS TypeID,							
					FullName
		    FROM    ac_items 
		    WHERE    TypeName=''B''
					AND UserCode NOT IN(''2181'',''2131'',''1151'',''SYS-1001'')	
					AND SonNum = 0					
					AND UserCode NOT IN                    
		            (
		                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
		                FROM	ac_items
						WHERE 	  TypeName=''B''
								AND UserCode NOT IN(''2181'',''2131'',''1151'',''SYS-1001'')
								AND SonNum = 0								
								AND (Nid IN (SELECT nid FROM F_GetManDetailAType('+char(39)+@OperatorID+char(39)+')))
		                ORDER BY
								UserCode
		            )
					AND (nid IN (SELECT nid FROM F_GetManDetailAType('+char(39)+@OperatorID+char(39)+')))
		    ORDER BY UserCode '
ELSE
	SET @SQLCursor = '
		DECLARE BaseTypeCursor CURSOR FOR
		    SELECT  TOP ' + CAST(@bCount AS varchar(50)) + ' 
					NID AS TypeID,							
					FullName
		    FROM    ac_items 
		    WHERE  	 TypeName=''B''
					AND UserCode NOT IN(''2181'',''2131'',''1151'',''SYS-1001'')
					AND SonNum = 0					
					AND UserCode NOT IN                    
		            (
		                SELECT  TOP ' + CAST((@bPageNo-1) * @bCount AS varchar(50)) + ' UserCode
		                FROM	ac_items
						WHERE 	 TypeName=''B''
								AND UserCode NOT IN(''2181'',''2131'',''1151'',''SYS-1001'')
								AND SonNum = 0								
		                ORDER BY
								UserCode
		            )
		    ORDER BY UserCode '

	EXEC(@SQLCursor)

	OPEN BaseTypeCursor

	FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName

	WHILE @@FETCH_STATUS = 0
		BEGIN
			--修改表结构
			
			SET @SQL = 'ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @BaseFullName + ']  NUMERIC(24, 10) '
			EXEC(@SQL)

			--修改有部门的数量和金额
			SET @SQL = '
					UPDATE '+N'##'+@TableName+'
					SET ['+@BaseFullName+'] = ISNULL(X.Total,0)
					FROM '+N'##'+@TableName+' A
					LEFT JOIN (
						SELECT	X.Checke,
								ISNULL(SUM(X.Total),0) AS Total
						FROM (
								SELECT	Checke,
										ISNULL(SUM(Total),0) AS Total
								FROM 	#BillIndex
								WHERE	ATypeId = '+@BaseTypeId+'										
								GROUP BY Checke
							)X GROUP BY X.Checke
					)X ON X.Checke = A.TypeId '
			
			--PRINT(@SQL)
			EXEC(@SQL)
			
			FETCH NEXT FROM BaseTypeCursor INTO @BaseTypeId,@BaseFullName
		END

	CLOSE BaseTypeCursor
	DEALLOCATE BaseTypeCursor

-- 删除临时表
SELECT @ReSQL='	SELECT * FROM '+N'##'+@TableName+'
				DROP TABLE #BillIndex,'+N'##'+@TableName
EXEC(@ReSQL)

DROP TABLE #GetManSTypeId,#GetManDTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCombinationProductSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCombinationProductSet]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇	
	日期：2016-04-13
	描述：组合品设置查询
*/
CREATE PROCEDURE Web_QueryCombinationProductSet
(
    @OperatorId			VARCHAR(50),	-- 当前操作员ID
	@usercode   VARCHAR(200)='',	--组合商品编码
	@fullname   VARCHAR(200)='',	--组合商品名称
	@standard   VARCHAR(200)='',
	@Summary	VARCHAR(50)=''		--摘要
)
--@encode$--
AS
SET NOCOUNT ON  

CREATE TABLE #Etype(typeid VARCHAR(200))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',3,@OperatorID)

CREATE TABLE #Dtype(typeid VARCHAR(200))
INSERT INTO #Dtype(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

CREATE TABLE #PType(typeid VARCHAR(200))
INSERT INTO #PType(TypeID) SELECT typeid FROM F_GetManDetailPTypeIncludeCombination(@OperatorId)

SELECT  DISTINCT CombinationProductID,
		CombinationProductUsercode,
		CombinationProductFullName,
		p.standard,
		p.Type,
		Barcode,
		Price,
		p_u.FullName AS ufullname,
		c.Etypeid,
		c.Dtypeid,
		Summary,
		CASE WHEN IsCheck=0 THEN '未审核' ELSE '已审核' END  AS ischeck,
		CASE WHEN IsStop=0 THEN '启用' ELSE '未启用' END  AS IsStop
FROM    CombinationProductIndex c
        INNER JOIN dbo.ptype p ON c.CombinationProductPtypeID=p.typeId
        INNER JOIN dbo.PType_Units p_u ON p_u.UnitsId=c.CombinationProductUnit
        INNER JOIN #PType pp ON p.typeId=pp.typeid
        INNER JOIN #Etype e ON (c.Etypeid = e.typeid OR ISNULL(c.Etypeid,'')='')
        INNER JOIN #Dtype d ON (c.Dtypeid = d.typeid OR ISNULL(c.Dtypeid,'')='')
        WHERE CombinationProductUsercode LIKE '%'+@usercode+'%'
              AND CombinationProductFullName LIKE '%'+@fullname+'%'
              AND Summary LIKE '%'+@Summary+'%'
			  AND P.Standard LIKE '%'+@standard+'%'
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCombinationPtypeInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCombinationPtypeInfo]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
作者：罗淮文
日期：2016-04-12
描述：组合商品信息查询	

修改人：刘飞
修改时间：2017-02-23
修改原因：功能搬移,启用商品多单位价格信息后 需要匹配单位ID
*/
CREATE PROCEDURE Web_QueryCombinationPtypeInfo
(
	@ptypeid			VARCHAR(200),
	@stypeid			VARCHAR(200),
	@btypeid			VARCHAR(200),
	@denominated		VARCHAR(200),
	@chvVipCardCode 	VARCHAR(500)='', --vip卡卡号
	@ktypeid			VARCHAR(200),
	@cargoid			VARCHAR(500),
	@usecargo			INT = 1,
	@etypeid			VARCHAR(200),
	@intBillType		INT,
	@chvBillDate 		VARCHAR(30)= '', --单据日期，用于销售出库单、零售单调用促销价格	
	@pindex 		VARCHAR(300)= '',
	@operator		VARCHAR(200),
	@curcombinationqty	numeric(24,12)	--当前组合品的数量（录入条码的时候，组合品数量叠加）
)
--@encode$--
AS
SET NOCOUNT ON
	/******************************相关参数准备start*****************************************************/
	if @curcombinationqty=0
	begin
		set @curcombinationqty=1
	end
	--多编码
	DECLARE @MultiCode varchar(1)
	SET @MultiCode = '0'
	SELECT TOP 1 @MultiCode = Value FROM UserConfig WHERE ConfigName = 'IfMultiCode'
	
	--分支机构物价信息
	DECLARE @PriceType varchar(5)
	SELECT @PriceType=PriceType FROM SType WHERE TypeId=@stypeid
	IF @stypeid = ''
	SET @PriceType='0'
	
	-- 判断系统序列号管理模式；
	--0：宽松式管理；1：强制性管理；
	DECLARE @strSysMngSerial CHAR(1);
	SELECT TOP 1 @strSysMngSerial = Value FROM UserConfig WHERE ConfigName = 'mngSerial';
	
	--处理默认货位
	DECLARE @cargoid1		NUMERIC(18,0)
	DECLARE @cargoid1name	VARCHAR(50)
	SELECT TOP 1 @cargoid1 = c.CargoID,@cargoid1name = c.FullName 
	FROM STOCK k inner join CargoType c ON k.typeId = c.KtypeID 
	WHERE c.IsDefault = 1 and k.typeId = ''+@ktypeid+''
	IF @cargoid1 IS NULL
		SET @cargoid1 = 0
	IF @cargoid1name IS NULL
		SET @cargoid1name = ''
	
	/******************************相关参数准备end*******************************************************/
	DECLARE @combinationptypeid	VARCHAR(200)
	DECLARE @combinationpusercode	VARCHAR(200)
	DECLARE @combinationpfullname	VARCHAR(200)
	SELECT @combinationptypeid=typeid,@combinationpusercode=usercode,@combinationpfullname=fullname FROM Ptype WHERE typeid=@ptypeid
	
	
	--创建临时表，存储组合品商品配件信息
	IF EXISTS (SELECT * FROM tempdb.dbo.SYSOBJECTS WHERE id = OBJECT_ID(N'tempdb..#TmpCombinationPtype') AND TYPE='U')
	BEGIN
		DROP TABLE #TmpCombinationPtype
	END
	CREATE TABLE #TmpCombinationPtype
	(
		ptypeid	VARCHAR(200) NOT NULL,	--商品ID
		pfullname	VARCHAR(200) NULL,
		qty		NUMERIC(24,10) NOT NULL,--数量
		price	NUMERIC(24,10) NOT NULL,--单价
		baseunitid	INT NULL,			--基本单位ID
		itemid	INT NULL,				--自由项
		barcode	VARCHAR(200) NULL,		--条码
		totalrate	numeric(24,10) NOT NULL
	)
	
	--将组合品商品信息插入到临时表
	INSERT INTO #TmpCombinationPtype(ptypeid,pfullname,qty,price,baseunitid,itemid,barcode,totalrate)
	SELECT d.ptypeid,p.fullname,d.qty,d.price,d.unit,d.itemid,d.barcode,
	(d.price * d.qty)/(SELECT SUM(qty * price) FROM  CombinationProductDetail cd WHERE cd.combinationproductid=i.combinationproductid) 
	FROM CombinationProductDetail d 
	INNER JOIN CombinationProductIndex I on d.combinationproductid=i.combinationproductid
	INNER JOIN ptype p ON d.ptypeid=p.typeid 
	WHERE i.combinationproductptypeid=@ptypeid AND I.isstop=0 AND I.ischeck=1
	
	--创建临时表，存储商品相关信息
	IF EXISTS (SELECT * FROM tempdb.dbo.SYSOBJECTS WHERE id = OBJECT_ID(N'tempdb..#temp') AND TYPE='U')
	BEGIN
		DROP TABLE #temp
	END
	CREATE TABLE #temp
	(
		ParId			varchar(50),
		PTypeID			varchar(50),
		UserCode 		varchar(200),
		FullName 		varchar(200),
		SonNum			int,
		customitemid    varchar(20),
		customitemfrom  varchar(20),
		customitemname  varchar(max),
		customitemrefid  varchar(max),
		Unit1	 		varchar(50),
		Unit2	 		varchar(50),
		UnitRate1 		 NUMERIC(24, 10) , 
		PrePrice1 		 NUMERIC(24, 10) ,
		PrePrice2 		 NUMERIC(24, 10) ,
		PrePrice3 		 NUMERIC(24, 10) ,
		PrePrice4 		 NUMERIC(24, 10) ,
		PrePrice5 		 NUMERIC(24, 10) ,
		StypeRecPrice		 NUMERIC(24, 10) ,
		StypeRecSalePrice	 NUMERIC(24, 10) ,
		RecAppraisalPrice  NUMERIC(24, 10) ,
		RecSendPrice  NUMERIC(24, 10) ,
		IfSerial 		char(1), 	-- 是否采用序列号强制管理；0：不采用；1：采用
		EntryCode 		varchar(200), -- 条形码,
		multentrycode   varchar(max),
		StANDard		varchar(200), -- 规格
		Type			varchar(200), -- 型号
		Area			varchar(200), -- 产地
		DwgNo 			varchar(200), -- 图号
		SerialCount		int,
		ValidDays		int,
		Usefullifeday	int,
		GeneralType		varchar(200), -- 通用车型
		GeneralDwgNo	varchar(250), -- 通用图号
		PreSalePrice1		 NUMERIC(24, 10) ,
		PreSalePrice2		 NUMERIC(24, 10) ,
		PreSalePrice3		 NUMERIC(24, 10) ,
		PreSalePrice4		 NUMERIC(24, 10) ,
		PreSalePrice5		 NUMERIC(24, 10) ,
		PreSalePrice6		 NUMERIC(24, 10) ,
		PreSalePrice7		 NUMERIC(24, 10) ,
		PreSalePrice8		 NUMERIC(24, 10) ,
		PreSalePrice9		 NUMERIC(24, 10) ,
		PreSalePrice10		 NUMERIC(24, 10) ,
		RetailPrice			 NUMERIC(24, 10) ,
		TopSalePrice		 NUMERIC(24, 10) ,
		LowSalePrice		 NUMERIC(24, 10) ,
		PreBuyPrice1		 NUMERIC(24, 10) ,
		PreBuyPrice2		 NUMERIC(24, 10) ,
		PreBuyPrice3		 NUMERIC(24, 10) ,
		PreBuyPrice4		 NUMERIC(24, 10) ,
		PreBuyPrice5		 NUMERIC(24, 10) ,
		TopBuyPrice			 NUMERIC(24, 10) ,
		AssistantUnitId     int,--辅助计量单位
		BuyUnitId           int,--采购默认单位
		SaleUnitId			INT,--zs002：销售默认单位id
		ProduceUnitId		INT,--zs003：生产默认单位id
		StockUnitId			INT,--zs004：存货默认单位id
		BaseUnitId          INT,--基本计量单位
		sortid				INT,
		leveal              INT,
		RecAmgStypeBuyPrice NUMERIC(24,10),
		RecAmgSTypeSalePrice NUMERIC(24,10),
		iscombinationproduct	INT,
		CustomerCode 		varchar(200), -- 客户多编码
		combinationqty	NUMERIC(24,10),		--组合品数量
		combinationprice NUMERIC(24,10),	--组合品单价
		combinationitemid	int,			--组合品自由项
		combinationunitid	int,			--组合品基本单位
		combinationbarcode	VARCHAR(200),	--组合品条码
		combinationpfullname	VARCHAR(200),--组合品名称
		totalrate			NUMERIC(24,10),--价格比例
		brandartypeid		VARCHAR(50)
	)
	
	/**************************************插入商品信息start*************************************************/
	DECLARE @SQL VARCHAR(MAX)
	SET @SQL = 'INSERT INTO #temp
				SELECT p.ParId,p.TypeID,p.UserCode AS UserCode,p.FullName,p.SonNum,p.customitemid,
				p.customitemfrom,p.customitemname,p.customitemrefid,p.Unit1,p.Unit2,p.UnitRate1,ISNULL(p.PrePrice1, 0) AS PrePrice1,
				ISNULL(p.PrePrice2, 0) AS PrePrice2,ISNULL(p.PrePrice3, 0) AS PrePrice3,ISNULL(p.PrePrice4, 0) AS PrePrice4,
				ISNULL(p.PrePrice5, 0) AS PrePrice5,
				(SELECT TOP 1 RecPrice FROM ptype_stypeprice WHERE Stypeid='''+@stypeid+''' AND Ptypeid=p.typeid AND unitid = p.saleunitid) as styperecprice,
				(SELECT TOP 1 recsaleprice FROM ptype_stypeprice WHERE Stypeid='''+@stypeid+''' AND Ptypeid=p.typeid AND unitid = p.saleunitid) as styperecsaleprice,
				ISNULL((SELECT ISNULL(RecAppraisalPrice, 0) FROM PType_StypePrice WHERE PTypeID = t.ptypeid AND stypeid='''+@stypeid+''' AND unitid = p.saleunitid),0),
				ISNULL((SELECT ISNULL(RecSendPrice, 0) FROM PType_StypePrice WHERE PTypeID = t.ptypeid AND stypeid='''+@stypeid+''' AND unitid = p.saleunitid),0),
				p.IfSerial,p.EntryCode,p.multentrycode,p.StANDard,p.Type,p.Area,p.DwgNo,p.SerialCount,p.ValidDays,p.Usefullifeday,null as GeneralType,
				null as GeneralDwgNo,
				ISNULL(c.PreSalePrice1,0),
				ISNULL(c.PreSalePrice2,0),
				ISNULL(c.PreSalePrice3,0) ,
				ISNULL(c.PreSalePrice4,0) ,
				ISNULL(c.PreSalePrice5,0) ,
				ISNULL(c.PreSalePrice6,0) ,
				ISNULL(c.PreSalePrice7,0) ,
				ISNULL(c.PreSalePrice8,0) ,
				ISNULL(c.PreSalePrice9,0) ,
				ISNULL(c.PreSalePrice10,0),
				ISNULL(c.RetailPrice,0) ,
				ISNULL(c.TopSalePrice,0) ,
				ISNULL(c.LowSalePrice,0) ,
				ISNULL(c.PreBuyPrice1,0) ,
				ISNULL(c.PreBuyPrice2,0) ,
				ISNULL(c.PreBuyPrice3,0) ,
				ISNULL(c.PreBuyPrice4,0) ,
				ISNULL(c.PreBuyPrice5,0) ,ISNULL(c.TopBuyPrice,0) ,
				p.AssistantUnitId,p.BuyUnitId,p.SaleUnitId,p.ProduceUnitId,p.StockUnitId,p.BaseUnitId,p.sortid,p.leveal,
				ISNULL((SELECT TOP 1 ISNULL(recamgstypebuyprice, 0) FROM ptype_price  WHERE PTypeID = p.TypeID AND unitid = p.saleunitid),0) as amgrecstypebuyprice,
				ISNULL((SELECT TOP 1 ISNULL(recamgstypesaleprice, 0) FROM ptype_price  WHERE PTypeID = p.TypeID AND unitid = p.saleunitid),0) as amgrecstypesaleprice,
				P.iscombinationproduct,'
	--处理多编码
	IF @MultiCode = '1'
	BEGIN
		SET @SQL += 'u.UserCode AS CustomerCode, ';
	END
	ELSE
	BEGIN
		SET @SQL += ''''' AS CustomerCode, ';
	END
	SET @SQL += '(t.qty * '+CONVERT(VARCHAR(38),@curcombinationqty)+') AS combinationqty,t.price,t.itemid,t.baseunitid,t.barcode,t.pfullname,t.totalrate,p.brandartypeid '
	SET @SQL += ' FROM PType p 
				INNER JOIN F_GetManPtypeAll('''+@operator+''') fp ON p.typeid=fp.typeid
				INNER JOIN #TmpCombinationPtype t on p.typeid=t.ptypeid 
				LEFT JOIN PUserCode u ON p.TypeID = u.PTypeID AND u.BTypeID = '''+@btypeid+''''
	
	--使用分支机构物价信息
	IF @PriceType='1'
	BEGIN
		SET @SQL += ' LEFT JOIN PType_StypePrice c ON c.PTypeID = t.ptypeid AND c.stypeid='''+@stypeid+''' AND c.unitid = p.saleunitid ';
	END
	ELSE
	BEGIN
		SET @SQL += ' LEFT JOIN PType_Price c ON c.PTypeID = t.ptypeid  AND c.unitid = p.saleunitid ';
	END
	SET @SQL += ' WHERE p.deleted=0 '
	
	--PRINT(@sql)
	EXEC(@SQL)	
	
	
	--基本单位反算大单位预设价格
	SELECT @SQL='
	UPDATE TMP SET 
	PreSalePrice1=CASE WHEN ISNULL(TMP.PreSalePrice1,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice1,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice1 END,
	PreSalePrice2=CASE WHEN ISNULL(TMP.PreSalePrice2,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice2,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice2 END,
	PreSalePrice3=CASE WHEN ISNULL(TMP.PreSalePrice3,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice3,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice3 END,
	PreSalePrice4=CASE WHEN ISNULL(TMP.PreSalePrice4,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice4,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice4 END,
	PreSalePrice5=CASE WHEN ISNULL(TMP.PreSalePrice5,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice5,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice5 END,
	PreSalePrice6=CASE WHEN ISNULL(TMP.PreSalePrice6,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice6,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice6 END,
	PreSalePrice7=CASE WHEN ISNULL(TMP.PreSalePrice7,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice7,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice7 END,
	PreSalePrice8=CASE WHEN ISNULL(TMP.PreSalePrice8,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice8,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice8 END,
	PreSalePrice9=CASE WHEN ISNULL(TMP.PreSalePrice9,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice9,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice9 END,
	PreSalePrice10=CASE WHEN ISNULL(TMP.PreSalePrice10,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreSalePrice10,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreSalePrice10 END,
	PreBuyPrice1=CASE WHEN ISNULL(TMP.PreBuyPrice1,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreBuyPrice1,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreBuyPrice1 END,
	PreBuyPrice2=CASE WHEN ISNULL(TMP.PreBuyPrice2,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreBuyPrice2,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreBuyPrice2 END,
	PreBuyPrice3=CASE WHEN ISNULL(TMP.PreBuyPrice3,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreBuyPrice3,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreBuyPrice3 END,
	PreBuyPrice4=CASE WHEN ISNULL(TMP.PreBuyPrice4,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreBuyPrice4,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreBuyPrice4 END,
	PreBuyPrice5=CASE WHEN ISNULL(TMP.PreBuyPrice5,0)=0 THEN dbo.F_RoundPrice(ISNULL(Price.PreBuyPrice5,0)*ISNULL(ext.Rate,1)) ELSE TMP.PreBuyPrice5 END
	FROM dbo.#TEMP TMP 
	INNER JOIN '
	+CASE WHEN @PriceType='1' THEN ' PType_StypePrice' ELSE ' PType_Price' END+' Price ON TMP.PTypeID=Price.PTypeID AND Price.IsDefaultUnit=1 '
	+CASE WHEN @PriceType='1' THEN ' AND StypeID='''+@STypeid+''' 'ELSE ' ' END
	+'INNER JOIN dbo.PType_Units_Ext Ext ON TMP.PTypeID=Ext.PtypeID AND EXT.UnitsId=saleunitid'
	EXEC(@SQL)

	/**************************************插入商品信息end***************************************************/
	-- 销售出库单、零售单、销售订单、销售换货出库、委托代销发货
	CREATE TABLE #temp_PromotePrice
	(
		PTypeId varchar(50),
		PromotePrice  NUMERIC(24, 10),
		UnitID		  INT 
	);

	IF @intBillType IN(11,140,300,305)
	BEGIN
		WITH tempPromotePrice as (
				SELECT ROW_NUMBER() OVER (ORDER BY a.BTypeID DESC,a.KTypeID DESC,a.ETypeID DESC) as RID,
				t.ptypeid,a.BTypeID,a.KTypeID,a.ETypeID,PromotePrice,UnitID from #temp t 
				left join PromotePrice a ON t.ptypeid = a.ptypeid 
				AND	(@denominated like a.BTypeID+'%' OR a.BTYpeID = '00000')
				AND (@ktypeid like a.KTypeID+'%' OR a.KTYpeID = '00000')
				AND (@etypeid like a.EtypeID+'%' OR a.ETypeID = '00000')
				AND a.StartDate <= @chvBillDate
				AND a.EndDate >= @chvBillDate
				WHERE t.SonNum = 0
		)
		INSERT INTO #temp_PromotePrice
		SELECT	ptypeid, PromotePrice,UnitID
		FROM tempPromotePrice a
		WHERE RID = (SELECT TOP 1 RID FROM tempPromotePrice b where a.ptypeid=b.ptypeid);
	END
	
	--创建临时表，处理库存数量
	IF EXISTS (SELECT * FROM tempdb.dbo.SYSOBJECTS WHERE id = OBJECT_ID(N'tempdb..#temp_Qty') AND TYPE='U')
	BEGIN
		DROP TABLE #temp_Qty
	END
	CREATE TABLE #temp_Qty
	(
		PtypeId				varchar(50),
		QTY					 NUMERIC(24, 10) ,
		NQTY					 NUMERIC(24, 10) ,
		CostPrice			 NUMERIC(24, 10) 
	)
	
	--借欠
	IF EXISTS (SELECT * FROM tempdb.dbo.SYSOBJECTS WHERE id = OBJECT_ID(N'tempdb..#temp_LendQty') AND TYPE='U')
	BEGIN
		DROP TABLE #temp_LendQty
	END
	CREATE TABLE #temp_LendQty
	(
		PtypeId				varchar(50),
		LendQty				 NUMERIC(24, 10)  --借进/借出数量
	)
	
	--维修
	IF EXISTS (SELECT * FROM tempdb.dbo.SYSOBJECTS WHERE id = OBJECT_ID(N'tempdb..#temp_WxQty') AND TYPE='U')
	BEGIN
		DROP TABLE #temp_LendQty
	END
	CREATE TABLE #temp_WxQty
	(
		PtypeId				varchar(50),
		WxQty				 NUMERIC(24, 10) ,
		WxNQty				 NUMERIC(24, 10) 
	)
	
--有vip卡号，取商品vip扣率，vip会员价(徐辉 2007-12-3)
CREATE TABLE #temp_DisCount
(
	Ptypeid 		varchar(50),
	VipDiscount 	 NUMERIC(24, 10) ,
	VipPrice		 NUMERIC(24, 10) ,
	UnitID			INT
);

IF @chvVipCardCode <> ''
BEGIN
	DECLARE @DiscountType varchar(10);
	DECLARE @cardDiscount varchar(20);
	SET @DiscountType='';
	SET @cardDiscount='';
	
	-- 根据会员卡卡号获取会员卡的折扣方式
	SELECT TOP 1 @DiscountType = b.DiscountType,@cardDiscount = b.CardTypeDiscount
	FROM nVipCardSign a 
	LEFT JOIN nVipCardSet b ON a.VipCardTypeId = b.VipCardTypeId
	WHERE a.VipCardCode = @chvVipCardCode;
	
	if (@cardDiscount is null)
	begin
	set @cardDiscount ='0'
	end
	--根据折扣方式查询该会员对某商品的折扣比例/价格
	SET @SQL = '	
		INSERT	INTO #temp_DisCount
		select DISTINCT t.ptypeid,'+		
		CASE WHEN @DiscountType IN ('1','2','3','4') THEN ' s.VipDiscount'+@DiscountType+ ' AS VipDiscount, 0 AS VipPrice '
		--CASE WHEN @DiscountType IN ('1','2','3','4') THEN ' case when ISNULL(s.VipDiscount'+@DiscountType+ ',-1) < 0 then '+@cardDiscount+' else s.VipDiscount'+@DiscountType+ ' end AS VipDiscount, 0 AS VipPrice '
		WHEN @DiscountType = '5' THEN ' case when isnull(s.VipPrice1,-1) < 0 then '+@cardDiscount+' else 0 end AS VipDiscount, case when isnull(s.VipPrice1,-1) < 0 then 0 else s.VipPrice1 end as VipPrice '
		WHEN @DiscountType = '6' THEN ' case when isnull(s.VipPrice2,-1) < 0 then '+@cardDiscount+' else 0 end AS VipDiscount, case when isnull(s.VipPrice2,-1) < 0 then 0 else s.VipPrice2 end as VipPrice '
		WHEN @DiscountType = '7' THEN ' case when isnull(s.VipPrice3,-1) < 0 then '+@cardDiscount+' else 0 end AS VipDiscount, case when isnull(s.VipPrice3,-1) < 0 then 0 else s.VipPrice3 end as VipPrice '
		WHEN @DiscountType = '8' THEN ' case when isnull(s.VipPrice4,-1) < 0 then '+@cardDiscount+' else 0 end AS VipDiscount, case when isnull(s.VipPrice4,-1) < 0 then 0 else s.VipPrice4 end as VipPrice '
		WHEN @DiscountType = '9' THEN ' case when isnull(s.VipPrice5,-1) < 0 then '+@cardDiscount+' else 0 end AS VipDiscount, case when isnull(s.VipPrice5,-1) < 0 then 0 else s.VipPrice5 end as VipPrice '
		WHEN @DiscountType = '10' THEN @cardDiscount + ' AS VipDiscount,0 as VipPrice'
		ELSE ' 0 AS VipDiscount, 0 as VipPrice ' END
		+'
		,s.UnitID 
		from #temp t
		left join nVipGoodsSign s ON s.ptypeid = t.ptypeid;
	';

	EXEC(@SQL);
END
	/***************************************处理库存数量begin****************************************************/
	
	SET @SQL = '
		INSERT INTO #temp_Qty(PtypeId,QTY,NQTY,CostPrice)
		SELECT	x.ptypeid,SUM(ISNULL(aq.qty,0)) AS qty,SUM(ISNULL(aq.nqty,0)) AS nqty,y.costprice
		FROM #temp x
		LEFT JOIN ( SELECT t.ptypeid,';
	SET @SQL += 'CASE WHEN SUM(ISNULL(a.QTY,0)) = 0 THEN NULL ELSE CAST(SUM(ISNULL(a.Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(a.QTY,0)) AS NUMERIC(24,10)) END AS CostPrice';
	SET @SQL += ' FROM #temp t LEFT JOIN GoodsStocks a ON a.PTypeID LIKE t.PTypeID+''%'' 
					AND a.PtypeId IN (SELECT ptypeid FROM #TmpCombinationPtype) 
					AND a.KTypeID = ''' + @ktypeid + '''
					GROUP BY t.Ptypeid
				) y ON y.ptypeid = x.ptypeid
		LEFT JOIN GoodsStocks_Qty aq ON aq.PTypeID LIKE x.PTypeID+''%'' 
		AND aq.PtypeId IN (SELECT ptypeid FROM #TmpCombinationPtype) 
		AND aq.KTypeID = '''+ @ktypeid +''''+ 
		CASE WHEN @usecargo = 1 AND @cargoid != '' AND @cargoid != '0' THEN ' AND aq.CargoID = '''+ @cargoid +'''' ELSE '' END + --zs010:关联对应的货位相关表
		' GROUP BY x.ptypeid,y.costprice'
	EXEC(@SQL)
	
	--获取借进/借出数量
	SET @SQL = '
		INSERT INTO #temp_LendQty(PtypeId,LendQty)
			SELECT t.ptypeid,SUM(ISNULL(v.QTY,0)) AS FactQty 
		FROM #temp t LEFT JOIN GoodsLend v ON v.PTypeID like t.ptypeid+''%'' 
		AND v.PtypeId IN (SELECT ptypeid FROM #TmpCombinationPtype) 
		AND v.KTypeID = ''' + @ktypeid + '''
		GROUP BY t.Ptypeid	'
	EXEC(@SQL)

	--获取WxQty
	SET @SQL = '
		INSERT INTO #temp_WxQty(PtypeId,WxQty,WxNQty)
		SELECT t.ptypeid,SUM(ISNULL(wx.QTY,0)) as WxQty,SUM(ISNULL(wx.NQTY,0)) AS WxNQty
		FROM #temp t LEFT JOIN wx_GoodsStocks wx ON wx.ptypeid like t.ptypeid+''%'' 
		AND wx.PtypeId IN (SELECT ptypeid FROM #TmpCombinationPtype) 
		AND wx.KTypeID = ''' + @ktypeid + '''
		GROUP BY t.Ptypeid'
	EXEC(@SQL)
	
	/***************************************处理库存数量end******************************************************/
	SET @SQL='SELECT '''+@pindex+''' as pindexid,
		'''+@combinationptypeid+''' AS combinationptypeid,
		'''+@combinationpusercode+''' AS combinationpusercode,
		'''+@combinationpfullname+''' AS combinationpfullname,
		t.ParId,
		t.pTypeID as TypeID,
		t.UserCode,
		t.FullName,
		t.sortid,
		t.SonNum,
		customitemid,
		customitemfrom,
		customitemname,
		customitemrefid,
		Unit1,
		Unit2,
		UnitRate1,
		CASE WHEN '+@strSysMngSerial+' = 0 THEN 0 ELSE IfSerial END AS [IfSerial],
		t.EntryCode,
		t.multentrycode,
		Standard,
		Type,
		Area,
		DwgNo,
		SerialCount,
		ValidDays,
		usefullifeday,
		CASE WHEN QTY IS NULL THEN 0 ELSE QTY END AS QTY,NQTY,WxQTY,WxNQty,
		ISNULL(Qty,0) + ISNULL(LendQty,0) AS FactQty,	-- 实际数量= 库存量+借出/借进
		CASE WHEN CostPrice IS NULL THEN 0 ELSE CostPrice END AS CostPrice,
		NULL AS DiscountTrack ,			--价格跟踪扣率跟踪
		NULL AS DiscountPriceTrack,		--价格跟踪扣率跟踪
		NULL AS PriceTrack,			--价格跟踪扣率跟踪
		NULL AS TaxTrack,				--税率跟踪
		NULL AS TaxPriceTrack,			--含税单价跟踪
		'''' AS pricetracksource,
		0 AS OrderQty,
		CASE WHEN PromotePrice IS NULL THEN 0 ELSE PromotePrice END AS PromotePrice,
		CustomerCode,
		CASE WHEN VipDiscount IS NULL THEN 0 ELSE VipDiscount END AS VipDiscount,
		CASE WHEN VipPrice IS NULL THEN 0 ELSE VipPrice END AS VipPrice,
		GeneralType,GeneralDwgNo,
		PreSalePrice1 	as PrePrice1,
		PreSalePrice2 	as PrePrice2,
		PreSalePrice3 	as PrePrice3,
		PreSalePrice4 	as PrePrice4,
		PreSalePrice5 	as PrePrice5,
		PreSalePrice6 	as PrePrice6,
		PreSalePrice7 	as PrePrice7,
		PreSalePrice8 	as PrePrice8,
		PreSalePrice9 	as PrePrice9,
		PreSalePrice10  as PrePrice10,
		RetailPrice     as PrePrice11,
		TopSalePrice    as PrePrice12,
		LowSalePrice    as PrePrice13,
		(select RecPrice from ptype where typeid=t.ptypeid) as ptyperecprice,
		t.RecAmgStypeBuyPrice as amgrecstypebuyprice,
		t.RecAmgSTypeSalePrice as amgrecstypesaleprice,
		t.stypeRecPrice,
		t.StypeRecSalePrice,
		RecAppraisalPrice,
		RecSendPrice,
		PreBuyPrice1,
		PreBuyPrice2,
		PreBuyPrice3,
		PreBuyPrice4,
		PreBuyPrice5,
		TopBuyPrice as PreBuyPrice6,
		RetailPrice as PreBuyPrice7,
		f.UnitsType,
		f.unitid,
		f.unit,
		f.unitrate,
		f.nunitid,
		f.nunit,
		f.rate,
		f.BuyUnitId,
		f.buyunitname,
		f.buymunitrate,
		f.SaleUnitId,
		f.saleunitname,
		f.salemunitrate,
		f.StockUnitId,
		f.stockunitname,
		f.stockmunitrate,
		f.ifusegoodsnum,
		dbo.F_GetAllEntrycode(t.pTypeID,f.SaleUnitId,2) AS salemunitcode,
		dbo.F_GetAllEntrycode(t.pTypeID,f.BuyUnitId,2) AS buymunitcode,
		dbo.F_GetAllEntrycode(t.pTypeID,f.StockUnitId,2) AS stockmunitcode,
		'''+CONVERT(VARCHAR(500),@cargoid1)+''' as cargoid,
		'''+CONVERT(VARCHAR(500),@cargoid1name)+''' as cargoidname,
		(select fullname FROM PType_Units where UnitsId=(select SaleUnitID1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=t.ptypeid)) as auxfullname1,
        (select fullname FROM PType_Units where UnitsId=(select SaleUnitID2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=t.ptypeid)) as auxfullname2,
        (select fullname FROM PType_Units where UnitsId=(select SaleUnitID3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=t.ptypeid)) as auxfullname3,
        (select SaleUnitRate1 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=t.ptypeid) as auxrate1,
		(select SaleUnitRate2 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=t.ptypeid) as auxrate2,
		(select SaleUnitRate3 FROM PType_AuxiliaryUnits_Ext WHERE PTypeID=t.ptypeid) as auxrate3,
		(select isservice from ptype where typeid=t.ptypeid ) as isservice,
        '''+@PriceType+''' as PriceType,
	    (select ISNULL(ReferPrice,0) FROM PType_StypePrice where PTypeID=t.ptypeid AND UnitID=t.SaleUnitID and STYPEID='''+@stypeid+''') AS SReferPrice,
	 	(select ISNULL(ReferPrice,0) FROM PType_Price where PTypeID=t.ptypeid AND UnitID=t.SaleUnitID)  AS PReferPrice,
		(select buydefaultrate from ptype WHERE typeid=t.ptypeid ) as buydefaultrate,
		(select saledefaultrate FROM ptype WHERE typeid=t.ptypeid ) as saledefaultrate,
		0 AS isbtypetrack,t.leveal,t.iscombinationproduct,t.combinationqty,t.combinationprice,t.combinationitemid as itemid,
		itemname= CASE WHEN t.customitemfrom = 0  THEN (SELECT FullName FROM xw_SelfData WHERE _Id= t.combinationitemid)
		ELSE (SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE id= t.combinationitemid ) END,
		t.totalrate,
		bc.typeid as brandartypeid,
		bc.fullname AS brandarfullname '	
	SET @SQL=@SQL+'	FROM #temp t 
		LEFT JOIN #temp_Qty q on t.ptypeid = q.ptypeid
		LEFT JOIN #temp_LendQty lq on t.ptypeid = lq.ptypeid
		LEFT JOIN #temp_WxQty wq on t.ptypeid = wq.ptypeid 
		LEFT JOIN dbo.F_GetPtypeUnitInfo() f ON f.typeid = t.ptypeid 
		LEFT JOIN #temp_PromotePrice p ON t.ptypeid = p.ptypeid AND f.SaleUnitId=P.UnitID
		LEFT JOIN #temp_DisCount d on t.ptypeid = d.ptypeid AND f.SaleUnitId=d.UnitID
		LEFT JOIN brandar_Commodity bc ON bc.typeid = t.brandartypeid
		'
	SET @SQL=@SQL+' ORDER BY t.sortid '
	
	
	EXEC(@SQL)	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCombinationSaleBackBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryCombinationSaleBackBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功 能  说 明：组合品销售退货单，调入组合品明细数据
-- 作		 者：罗淮文
-- 最后修改时间：2016-07-14

--修改：LF 2017.07.18 退货单查询上表体自定义数据调整为cbd.InOrOut='I'
-- ========================================================================
CREATE  PROCEDURE Web_QueryCombinationSaleBackBill
(
	@billnumberid INT
)
--@encode$--

AS

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId=@billnumberid --AND cbd.iscombination='true'
AND cbd.InOrOut='I'

SELECT	b.iscombinationproduct,
		brandartypeid = (SELECT TOP 1 brandartypeid from ptype where typeid = a.ptypeid),
		brandarfullname = (SELECT TOP 1 bc.fullname FROM dbo.brandar_Commodity bc,PType p WHERE bc.typeid = p.brandartypeid and p.typeid = a.ptypeid),
		Qty = a.Qty,	
		BigQty = CASE WHEN b.UnitRate1 = 0 THEN a.Qty
				ELSE CAST(a.Qty/b.UnitRate1 AS  NUMERIC(24, 10) ) END,
		Price = a.SalePrice,
		DiscountPrice = a.DiscountPrice,
		TaxPrice = a.TaxPrice,
		a.TaxTotal,
		a.tax,
		a.Discount,
		a.Total,
		a.curmsaleprice,
		a.mqty,
		a.munitrate,
		a.nsaleprice,
		CASE WHEN ISNULL(a.nunitid,0) = 0 THEN NULL
		ELSE a.nqty	END as nqty,
		a.curmdiscountprice,
		a.curmtaxprice,
		a.ntaxmoney,
		a.ntaxtotal,
		a.taxmoney,
		a.MUnitID,
		a.NUnitID,
		a.unitid,
		W.fullname AS unit,
		U.FullName AS munit,
		V.FullName AS nunit,
		a.nsaletotal,
		a.ntotal,					
		CASE WHEN ISNULL(a.nunitid,0) = 0 THEN NULL
		ELSE a.UnitRate	END as UnitRate,
		a.CargoID,
		ct.FullName AS cargofullname,
		a.ndiscountprice,
		a.ntaxprice,
		a.msaleprice,
		a.mdiscountprice,
		a.mtaxprice,
		a.id,
		a.GoodsOrder,
		CASE WHEN cgt.ID IS NULL THEN '0' ELSE '1' END AS balancestate,
		isnull((select top 1 it.CostPrice From InOutstocktable it where it.BillnumberId = a.BillnumberId and a.PtypeId = it.PtypeId AND a.ID=it.ID),0) as InOutStockCostPrice,
		InputCostPrice =null,
		a.oldid,
		-1 as OldBillId,
		a.GoodsCostPrice,
		a.isgift,
		a.pricestyle,
		a.completeqty,		
		a.ninvoicemoney,
		a.invoicemoney,
		a.invoiceqty,
		b.EntryCode,
		OrderID = -1,
		a.GoodsCostPrice,'' AS CustomerCode,
		a.KtypeId,
		KUserCode=(SELECT UserCode FROM Stock WHERE TypeId=a.KtypeId),
		KFullName=(SELECT FullName FROM Stock WHERE TypeId=a.KtypeId),
		a.Comment AS BillComment,
		IsUnit2 = 0,
		b.typeid,
		b.UserCode,
		b.FullName,
		b.Unit1,
		b.Unit2,
		0 as UnitRate1,				
		b.Standard,
		b.Type,
		b.Area,
		b.SerialCount,
		b.ValidDays,
		b.IfSerial,
		b.usefullifeday,
		b.customitemid ,
		b.customitemfrom ,
		b.customitemname,
		b.customitemrefid,
		a.BillNumberId,a.PtypeId,a.Qty,a.SalePrice,a.discount,a.DiscountPrice,
		a.jobnumber,a.goodsno,a.total,a.OutFactoryDate,a.TaxPrice,a.TaxTotal,
		a.comment,a.comment AS base,a.TeamNo,a.ID,a.TeamNO1,a.IsUnit2,a.OldID,
		a.CostPrice,a.OldBillNumberID,a.InputCostPrice,a.GoodsOrder,a.GoodsBTypeID,
		a.GoodsCostPrice,a.GoodsCostTotal,a.HandZeroCost,a.CompleteQTY,
		a.SaleTotal,a.Tax,a.KTypeID,a.Stypeid,a.FromBillNumberID,
		a.FromBillID,a.TaxMoney,a.NSalePrice,a.NSaleTotal,a.NDiscountPrice,a.NTotal,
		a.NTaxPrice,a.NTaxTotal,a.NTaxMoney,a.UnitID,a.NUnitID,a.NQty,a.UnitRate,
		a.NUnitMsg,a.MUnitID,a.MQty,a.MUnitRate,a.MUnitMsg,a.MSalePrice,a.MDiscountPrice,
		a.MTaxPrice,a.CurMSalePrice,a.CurMDiscountPrice,a.CurMTaxPrice,a.CargoID,a.ItemID,
		a.IsCombined,a.InvoiceQty,a.InvoiceMoney,a.NInvoiceMoney,a.IsGift,a.PriceStyle,
		a.PromoType,a.CompleteTotal,a.NCompleteTotal,a.pindexid,a.ShowOrder,
		itemid=a.ItemId,
		itemname= CASE WHEN a.IsCombined = 0 THEN (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
		iscombined=a.IsCombined,
		b.unitstype,
		a.HandZeroCost,
		a.saletotal,
		CAST(b.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname1,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname2,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname3,
		(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate1,
		(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate2,
		(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate3,
		b.IsService,
		dbo.F_GetAllEntrycode(a.pTypeID,a.munitid,2) AS salemunitcode,
		dbo.F_GetAllEntrycode(a.pTypeID,a.munitid,2) AS buymunitcode,
		dbo.F_GetAllEntrycode(a.pTypeID,a.munitid,2) AS stockmunitcode, 
		CASE WHEN cgt.ID IS NULL THEN 0 ELSE 1 END AS BalancedForGoods,--是否已经按商品结算
		CASE WHEN (SELECT COUNT(1) FROM FaPiaoBill fb WHERE fb.MainBillNumberID=a.BillNumberId AND fb.BillType=163 AND fb.Ptypeid=a.Ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByBuyInvoice,--已被采购发票调用
		CASE WHEN (SELECT COUNT(1) FROM FaPiaoBill fb WHERE fb.MainBillNumberID=a.BillNumberId AND fb.BillType=162 AND fb.Ptypeid=a.Ptypeid) > 0 THEN 1 ELSE 0 END AS CalledBySaleInvoice,--已被销售发票调用
		CASE WHEN (SELECT COUNT(1) FROM BuyBackBill bb inner join billindex bi on bb.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE bb.OldBillNumberId=a.BillNumberId AND bb.oldid = a.id AND bb.Ptypeid=a.ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByBuyBack,--已被采购退货单调用
		CASE WHEN (SELECT COUNT(1) FROM BuyGoodsExchangeBill be inner join billindex bi on be.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE be.OldBillNumberId=a.BillNumberId AND be.oldid = a.id AND be.PtypeId=a.PtypeId) > 0 THEN 1 ELSE 0 END AS CalledByBuyExchange,--已被采购换货单调用
		CASE WHEN (SELECT COUNT(1) FROM PT_Combin_SaleBackBillDetail sb inner join billindex bi on sb.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE sb.OldBillNumberId=a.BillNumberId ) > 0 THEN 1 ELSE 0 END AS CalledBySaleBack,--已被销售退货单调用
		CASE WHEN (SELECT COUNT(1) FROM SaleGoodsExchangeBill se inner join billindex bi on se.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE se.OldBillNumberId=a.BillNumberId AND se.oldid = a.id AND se.PtypeId=a.PtypeId) > 0 THEN 1 ELSE 0 END AS CalledBySaleExchange,--已被销售换货单调用
		CASE WHEN (SELECT COUNT(1) FROM ReceiptBill rb inner JOIN ReceiptBillindex rbi on rbi.BillNumberID=rb.BillNumberID and rbi.RedWord=0 WHERE rb.MainBillNumberID=a.BillNumberId AND rb.RecordedItemId = a.id AND rb.BillType=404 AND rb.Ptypeid=a.Ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByBuyReceipt,--已被采购暂估开票调用
		CASE WHEN (SELECT COUNT(1) FROM ReceiptBill rb inner JOIN ReceiptBillindex rbi on rbi.BillNumberID=rb.BillNumberID and rbi.RedWord=0 WHERE rb.MainBillNumberID=a.BillNumberId AND rb.RecordedItemId = a.id AND rb.BillType=405 AND rb.Ptypeid=a.Ptypeid) > 0 THEN 1 ELSE 0 END AS CalledBySaleReceipt,--已被销售发货开票调用
		CASE WHEN (SELECT COUNT(1) FROM AppraisalBackBill abb inner join billindex bi on abb.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE abb.OldBillNumberId=a.BillNumberId AND abb.oldid = a.id AND abb.Ptypeid=a.ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByAppraisalBackBill,--是否已被暂估退货单调用
		CASE WHEN (SELECT COUNT(1) FROM SendBackBill sbb inner join billindex bi on sbb.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE sbb.OldBillNumberId=a.BillNumberId AND sbb.oldid = a.id AND sbb.Ptypeid=a.ptypeid) > 0 THEN 1 ELSE 0 END AS CalledBySendBackBill,--是否已被发出商品退货单调用
		0 AS ReferenceBuyBill,0 AS PromoSate,0 AS ReferenceSaleBill,0 AS CalledByAdpriceBill,
		CASE WHEN stype.pricetype=0 THEN pp.referprice WHEN stype.pricetype=1 THEN 
			CASE WHEN ISNULL(psp.referprice,0)=0 THEN pp.referprice ELSE psp.referprice END 
		END AS ReferPrice,a.pindexid,
		a.PriceSource,
		cbd.*,
		CASE WHEN (SELECT TOP 1 1 FROM dbo.Coupon_BillUsed cub
			WHERE a.OldBillNumberID=BillnumberId AND cub.BillType=12)=1 THEN 1 ELSE 0 END AS hascoupon
FROM dbo.PT_Combin_SaleBackBill a 
INNER JOIN BillIndex bi1 ON a.BillNumberId=bi1.BillNumberId
INNER JOIN dbo.PType b ON a.PTypeID = b.TypeID
INNER JOIN stype ON stype.typeid=a.stypeid
INNER JOIN dbo.CargoType ct ON a.CargoID = ct.CargoID
LEFT JOIN dbo.PType_Price pp ON pp.PTypeID = b.TypeID AND pp.UnitID= a.MUnitID
LEFT JOIN PType_StypePrice psp ON psp.PtypeId=b.typeid AND psp.stypeid=a.stypeid AND psp.UnitID= a.MUnitID
LEFT JOIN  dbo.PType_Units U ON U.UnitsId=a.MUnitID 
LEFT JOIN  dbo.PType_Units V ON V.UnitsId=a.NUnitID
LEFT JOIN  dbo.PType_Units W ON W.UnitsId=a.UnitID	 
LEFT JOIN #Custom_T cbd ON cbd.BillId=A.BillNumberId AND cbd.detailid=a.id 
LEFT JOIN 
(
	SELECT ID,Billid,Ptypeid,GoodsbillID FROM CompleteGoodTotal cc 
	WHERE cc.ID in
	(
		select MIN(ID) from CompleteGoodTotal WHERE GoodsbillID=@billnumberid group by billid
	)
) cgt ON cgt.GoodsbillID=a.BillNumberId AND cgt.BillId=a.id AND cgt.Ptypeid=a.ptypeid
		WHERE a.BillNumberID = @billnumberid ORDER BY a.showorder

DROP TABLE #Custom_T

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCombinationSaleBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryCombinationSaleBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 功 能  说 明：组合品销售出库单，调入组合品明细数据
-- 作		 者：罗淮文
-- 最后修改时间：2016-07-14

--修改：LF 2017.07.18 出库单查询上表体自定义数据调整为cbd.InOrOut='I'
-- ========================================================================
CREATE  PROCEDURE Web_QueryCombinationSaleBill
(
	@billnumberid INT
)
--@encode$--

AS

--创建临时表，获取自定义字段
SELECT cbd.*,e.fullname as efullnamecustom,
p.fullname as pfullnamecustom,
b.fullname as bfullnamecustom,
d.fullname as dfullnamecustom,
k.fullname as kfullnamecustom,
s.fullname as sfullnamecustom INTO #Custom_T
 FROM custom_billdetails cbd
LEFT JOIN employee e ON cbd.sysdiy11=e.typeid
LEFT JOIN ptype p ON cbd.sysdiy12=p.typeid
LEFT JOIN btype b ON cbd.sysdiy13=b.typeid
LEFT JOIN department d ON cbd.sysdiy14=d.typeid
LEFT JOIN stock k ON cbd.sysdiy15=k.typeid
LEFT JOIN stype s ON cbd.sysdiy16=s.typeid
WHERE cbd.BillId=@billnumberid --AND cbd.iscombination='true'
AND cbd.InOrOut='I'

SELECT b.iscombinationproduct,Qty = a.Qty,
					BigQty =
							CASE WHEN b.UnitRate1 = 0 THEN
								a.Qty
							ELSE CAST(a.Qty/b.UnitRate1 AS  NUMERIC(24, 10) ) END,
					Price = a.SalePrice,
					DiscountPrice = a.DiscountPrice,
					TaxPrice = a.TaxPrice,
					a.TaxTotal,
					a.tax,
					a.Discount,
					a.Total,
					a.curmsaleprice,
					a.mqty,
					a.munitrate,
					a.nsaleprice,
					CASE WHEN ISNULL(a.nunitid,0) = 0 THEN NULL
					ELSE a.nqty	END as nqty,
					a.curmdiscountprice,
					a.curmtaxprice,
					a.ntaxmoney,
					a.ntaxtotal,
					a.taxmoney,
					a.MUnitID,
					a.NUnitID,
					a.unitid,
					W.fullname AS unit,
					U.FullName AS munit,
					V.FullName AS nunit,
					a.nsaletotal,
					a.ntotal,					
					CASE WHEN ISNULL(a.nunitid,0) = 0 THEN NULL
					ELSE a.UnitRate	END as UnitRate,
					a.CargoID,
					ct.FullName AS cargofullname,
					a.ndiscountprice,
					a.ntaxprice,
					a.msaleprice,
					a.mdiscountprice,
					a.mtaxprice,
					a.id,
					a.GoodsOrder,
					isnull((select top 1 it.CostPrice From InOutstocktable it where it.BillnumberId = a.BillnumberId and a.PtypeId = it.PtypeId AND a.ID=it.ID),0) as InOutStockCostPrice,
					
				a.GoodsCostPrice,
				a.isgift,
				a.pricestyle,
				(select EntryCode from PType_Units_Ext where PtypeID=b.typeid and UnitsId=a.MUnitID) AS munitcode,
				a.completeqty,		
				a.ninvoicemoney,
				a.invoicemoney,
				a.invoiceqty,
				a.OrderID,
				case when isnull(a.entrycode,'')<>'' then a.entrycode
				else b.entrycode end as entrycode,
				a.sharefee,
				a.pricesource,
				a.GoodsCostPrice,
				a.BeforePromoID,
				accountqty=isnull((select sum(qty) from GoodsStocks where ktypeid=a.ktypeid and ptypeid=a.ptypeid),0),
				'' AS CustomerCode,
				a.KtypeId,
				KUserCode=(SELECT UserCode FROM Stock WHERE TypeId=a.KtypeId),
				KFullName=(SELECT FullName FROM Stock WHERE TypeId=a.KtypeId),
				a.Comment AS BillComment,
				IsUnit2 = 0,
				b.typeid,
				b.UserCode,
				b.FullName,
				b.Unit1,
				b.Unit2,
				0 as UnitRate1,				
				b.Standard,
				b.Type,
				b.Area,
				b.SerialCount,
				b.ValidDays,
				b.IfSerial,
				b.usefullifeday,
				b.customitemid ,
				b.customitemfrom ,
				b.customitemname,
				b.customitemrefid,
				a.BillNumberId,a.PtypeId,a.Qty,a.SalePrice,a.discount,a.DiscountPrice,a.costprice,
				a.jobnumber,a.goodsno,a.total,a.OutFactoryDate,a.TaxPrice,a.TaxTotal,
				a.comment,a.comment AS base,a.OrderID,
				a.TeamNo,a.ID,a.TeamNO1,a.IsUnit2,a.InputCostPrice,a.GoodsOrder,a.BackQty,
				a.GoodsBTypeID,a.GoodsCostPrice,a.GoodsCostTotal,a.HandZeroCost,a.CompleteQTY,
				a.SaleTotal,a.Tax,a.KTypeID,a.Stypeid,a.ShareFee,a.TaxMoney,a.NSalePrice,a.NSaleTotal,a.NDiscountPrice,
				a.NTotal,a.NTaxPrice,a.NTaxTotal,a.NTaxMoney,a.UnitID,a.NUnitID,a.NQty,a.UnitRate,a.NUnitMsg,a.MUnitID,
				a.MQty,a.MUnitRate,a.MUnitMsg,a.MSalePrice,a.MDiscountPrice,a.MTaxPrice,a.CurMSalePrice,a.CurMDiscountPrice,
				a.CurMTaxPrice,a.CargoID,a.ItemID,a.IsCombined,a.entryCode,a.InvoiceQty,a.InvoiceMoney,a.NInvoiceMoney,a.IsGift,
				a.BeforePromoID,a.PriceStyle,a.PriceSource,a.PromoType,a.CompleteTotal,a.NCompleteTotal,a.LendBillID,
				a.LendBillNumberID,a.ShowOrder,a.DiyID,a.pindexid,
				itemid=a.ItemId,
				itemname= CASE WHEN a.IsCombined = 0  THEN
						    (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
					        ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
				iscombined=a.IsCombined,
				b.unitstype,
				a.HandZeroCost,
				a.saletotal,
				CAST(b.IfUseGoodsNum AS INT) AS IfUseGoodsNum,
				(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname1,
				(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname2,
				(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname3,
				(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate1,
				(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate2,
				(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate3,
				b.IsService,
				dbo.F_GetAllEntrycode(a.pTypeID,a.munitid,2) AS salemunitcode,
				dbo.F_GetAllEntrycode(a.pTypeID,a.munitid,2) AS buymunitcode,
				CASE WHEN cgt.ID IS NULL THEN 0 ELSE 1 END AS BalancedForGoods,--是否已经按商品结算,
			CASE WHEN (SELECT COUNT(1) FROM FaPiaoBill fb WHERE fb.MainBillNumberID=a.BillNumberId AND fb.BillType=163 AND fb.Ptypeid=a.Ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByBuyInvoice,--已被采购发票调用
			CASE WHEN (SELECT COUNT(1) FROM FaPiaoBill fb WHERE fb.MainBillNumberID=a.BillNumberId AND fb.BillType=162 AND fb.Ptypeid=a.Ptypeid) > 0 THEN 1 ELSE 0 END AS CalledBySaleInvoice,--已被销售发票调用
			CASE WHEN (SELECT COUNT(1) FROM BuyBackBill bb inner join billindex bi on bb.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE bb.OldBillNumberId=a.BillNumberId AND bb.oldid = a.id AND bb.Ptypeid=a.ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByBuyBack,--已被采购退货单调用
			CASE WHEN (SELECT COUNT(1) FROM BuyGoodsExchangeBill be inner join billindex bi on be.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE be.OldBillNumberId=a.BillNumberId AND be.oldid = a.id AND be.PtypeId=a.PtypeId) > 0 THEN 1 ELSE 0 END AS CalledByBuyExchange,--已被采购换货单调用
			CASE WHEN (SELECT COUNT(1) FROM PT_Combin_SaleBackBillDetail sb inner join billindex bi on sb.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE sb.OldBillNumberId=a.BillNumberId ) > 0 THEN 1 ELSE 0 END AS CalledBySaleBack,--已被销售退货单调用
			CASE WHEN (SELECT COUNT(1) FROM SaleGoodsExchangeBill se inner join billindex bi on se.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE se.OldBillNumberId=a.BillNumberId AND se.oldid = a.id AND se.PtypeId=a.PtypeId) > 0 THEN 1 ELSE 0 END AS CalledBySaleExchange,--已被销售换货单调用
			CASE WHEN (SELECT COUNT(1) FROM ReceiptBill rb inner JOIN ReceiptBillindex rbi on rbi.BillNumberID=rb.BillNumberID and rbi.RedWord=0 WHERE rb.MainBillNumberID=a.BillNumberId AND rb.RecordedItemId = a.id AND rb.BillType=404 AND rb.Ptypeid=a.Ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByBuyReceipt,--已被采购暂估开票调用
			CASE WHEN (SELECT COUNT(1) FROM ReceiptBill rb inner JOIN ReceiptBillindex rbi on rbi.BillNumberID=rb.BillNumberID and rbi.RedWord=0 WHERE rb.MainBillNumberID=a.BillNumberId AND rb.RecordedItemId = a.id AND rb.BillType=405 AND rb.Ptypeid=a.Ptypeid) > 0 THEN 1 ELSE 0 END AS CalledBySaleReceipt,--已被销售发货开票调用
			CASE WHEN (SELECT COUNT(1) FROM AppraisalBackBill abb inner join billindex bi on abb.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE abb.OldBillNumberId=a.BillNumberId AND abb.oldid = a.id AND abb.Ptypeid=a.ptypeid) > 0 THEN 1 ELSE 0 END AS CalledByAppraisalBackBill,--是否已被暂估退货单调用
			CASE WHEN (SELECT COUNT(1) FROM SendBackBill sbb inner join billindex bi on sbb.BillNumberId=bi.BillNumberId and bi.redword=0 WHERE sbb.OldBillNumberId=a.BillNumberId AND sbb.oldid = a.id AND sbb.Ptypeid=a.ptypeid) > 0 THEN 1 ELSE 0 END AS CalledBySendBackBill,--是否已被发出商品退货单调用
			0 AS ReferenceBuyBill,CASE WHEN a.promotype<>1 THEN 1 ELSE 0 END AS PromoSate,0 AS ReferenceSaleBill,0 AS CalledByAdpriceBill, CASE WHEN stype.pricetype=0 THEN pp.referprice WHEN stype.pricetype=1 THEN 
						CASE WHEN ISNULL(psp.referprice,0)=0 THEN pp.referprice ELSE psp.referprice END 
					 END AS ReferPrice,cbd.*,
		a.PromonIds,
		dbo.F_GetPromoRuleNames(a.PromonIds) AS promos,
		B.brandartypeid,
		bc.UserCode AS brandarusercode,
		bc.fullname AS brandarfullname,
		a.CouponCode
  FROM [dbo].[PT_Combin_SaleBill] a
  INNER JOIN ptype B ON a.ptypeid=B.typeid  
  INNER JOIN brandar_Commodity bc ON b.brandartypeid = bc.typeid
  LEFT JOIN dbo.PType_Price pp ON pp.PTypeID = b.TypeID AND pp.UnitID= a.MUnitID
  LEFT JOIN PType_StypePrice psp ON psp.PtypeId=B.typeid AND psp.stypeid=a.stypeid  AND psp.UnitID= a.MUnitID
  INNER JOIN stype ON stype.typeid=a.stypeid
  LEFT JOIN dbo.CargoType ct ON a.CargoID = ct.CargoID
  LEFT  JOIN  dbo.PType_Units U ON U.UnitsId=a.MUnitID 
  LEFT  JOIN  dbo.PType_Units V ON V.UnitsId=a.NUnitID
  LEFT  JOIN  dbo.PType_Units W ON W.UnitsId=a.UnitID
  LEFT JOIN #Custom_T cbd ON cbd.BillId=A.BillNumberId AND cbd.detailid=a.id 
  LEFT JOIN 
(
	SELECT ID,Billid,Ptypeid,GoodsbillID FROM CompleteGoodTotal cc 
	WHERE cc.ID in
	(
		select MIN(ID) from CompleteGoodTotal group by billid
	)
) cgt ON cgt.GoodsbillID=a.BillNumberId AND cgt.BillId=a.id AND cgt.Ptypeid=a.ptypeid	 
  WHERE a.billnumberid=@billnumberid
  
  DROP TABLE #Custom_T

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCombinationStockInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryCombinationStockInfo
GO

--作者：魏伟
--时间：2016-4-25
--功能：商品多单位信息查询

CREATE PROCEDURE Web_QueryCombinationStockInfo
(
	 
	@OperatorId	varchar(100),
	@StypeId varchar(100), 
	@StockId VARCHAR(100),
	@CombinId VARCHAR(100),
	@IsShowDetail int 
)
--@encode$--
AS
SET ANSI_WARNINGS OFF
SET NOCOUNT ON
DECLARE @SQL varchar(MAX)  
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------- 
------------------------------------------------------虚拟仓库---------------------------------------
 --选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

CREATE TABLE #GetManKTypeId(TypeId	varchar(100))

 
INSERT INTO #GetManKTypeId(TypeId) 
SELECT sk.TypeId FROM F_BaseGetAllManagerBaseTypeId(@StockId,4,@OperatorID) sk
INNER JOIN stock S ON sk.Typeid=S.Typeid
INNER JOIN #GetSelectSTypeId ST ON S.STYPEID=ST.TYPEID
 DECLARE @Qty    NVARCHAR(2000),
        @Lendqty NVARCHAR(2000),
        @Borrowqty NVARCHAR(2000),
		@RQty NVARCHAR(2000),
		@CQty NVARCHAR(2000),
		@BuyOrderQty NVARCHAR(2000),
		@BuyReachQty NVARCHAR(2000),
		@SaleOrderQty NVARCHAR(2000),
		@SaleReachQty NVARCHAR(2000),
		@UnitRate NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
		@BaseUnitName NVARCHAR(2000),
        @temptable  NVARCHAR(2000)
 
 SELECT  @Qty='o.Qty',
		@Lendqty='SUM(o.Lend-o.LendBack-o.saleqty)',
		@Borrowqty='SUM(o.Borrow-o.BorrowBack-o.buyqty)',   
		@BuyReachQty='o.BuyReachQty', 
		@RQty='o.RQty',        
		@CQty='o.CQty',        
		@BuyOrderQty='o.BuyOrderQty', 
		@BuyReachQty='o.BuyReachQty', 
		@SaleOrderQty='o.SaleOrderQty',
		@SaleReachQty='o.SaleReachQty',
		@UnitRate = '1',
		@UnitName = 'u1.fullname',
		@BaseUnitName = 'u1.fullname',
		@temptable=dbo.F_GetPtypeUnitsAndRates('p1','1','1')
 
 --商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(500))
CREATE UNIQUE CLUSTERED INDEX [Ptypeidx] ON [dbo].[#GetManPTypeId] ([typeId])

SELECT @SQL='INSERT INTO #GetManPTypeId 
			 SELECT p.typeId FROM 
             ptype p 
             INNER JOIN F_GetManDetailPType('''+@OperatorID+''') mp ON mp.TypeId=p.typeId  '
 
 EXEC(@SQL)	
 
 
  --SELECT * FROM #GetManPTypeId  
 CREATE TABLE #GetManPTypeAll
(
	TypeId			varchar(100),
	FullName        varchar(200),
	UserCode        varchar(100),
	EntryCode		varchar(100),
	[Standard]		varchar(100),
	[Type]			varchar(20),
	Area			varchar(30),
	Sonnum          int,
	Leveal          int,
	Parid           varchar(200),
	unit1           varchar(100),
	unit2           varchar(100),
	unitrate1       varchar(100),
	unitname       NVARCHAR(2000),
	baseunitname    NVARCHAR(2000),
	unitrate        NVARCHAR(2000),
	sortid        int
)
 CREATE UNIQUE CLUSTERED INDEX [PtypeAllidx] ON [dbo].[#GetManPTypeAll] 
(
	[typeId]
)

SET @SQL='INSERT INTO #GetManPTypeAll 
			 SELECT DISTINCT P.TypeId,P.FullName,P.UserCode,P.EntryCode,P.Standard,P.Type,P.Area,P.Sonnum,P.Leveal,
			 P.Parid,P.unit1,P.unit2,P.unitrate1,'
         
     SET @sql+=@UnitName+','+@BaseUnitName+','+@UnitRate
     
    SET @sql+=' ,p.sortid 
		FROM F_GetManPTypeAll('''+@OperatorID+''') P 
		inner join ptype p1 on p.typeid=p1.typeid '+@temptable 
EXEC(@SQL)

 
 
 
 
 CREATE TABLE #Contypeid
 (
	typeid VARCHAR(100),
	QTY  NUMERIC(24, 10),
	CombinationProductPtypeId VARCHAR(100),
	IsStop INT,
	IsCheck INT
 )
 INSERT INTO #Contypeid
         ( typeid,QTY,CombinationProductPtypeId,IsStop,IsCheck )
 SELECT Ptypeid,Qty, b.CombinationProductPtypeId,b.IsStop,b.IsCheck FROM dbo.CombinationProductDetail a INNER JOIN (SELECT CombinationProductID,CombinationProductPtypeId,IsStop,IsCheck from dbo.CombinationProductIndex WHERE CombinationProductPtypeId=@CombinId) b ON a.CombinationProductID = b.CombinationProductID

 --SELECT * FROM #Contypeid
 CREATE TABLE #DGS
(
	PTypeId		 varchar(100),
	RQty		 NUMERIC(24, 10) ,
	CQty		 NUMERIC(24, 10) 
)
INSERT INTO #DGS
(
	PTypeId,
	RQty,
	CQty
)
SELECT	
	B.PTypeId,
	ISNULL(SUM(B.RQty),0) AS RQty,
	ISNULL(SUM(B.CQty),0) AS CQty
FROM dbo.GoodsStocks_Draft B INNER JOIN #GetManPTypeId P ON P.TypeId=B.PtypeId
	INNER JOIN #GetManKTypeId K ON k.TypeId=B.KTypeID
GROUP BY B.PTypeId

--SELECT * FROM  #dgs
 CREATE TABLE #LeftJoinTable
(
	TypeId			 VARCHAR(100),
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	Qty				 NUMERIC(24, 10) ,
	Lendqty			 NUMERIC(24, 10) ,
	Borrowqty		 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) ,
	total			 NUMERIC(24, 10)
)
 
 SELECT @SQL='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty ,
	total 
)
		SELECT	o.PTypeId AS TypeId,
				'+@RQty+',
				'+@CQty+',
				0 AS Qty,
				0 AS Lendqty,
				0 AS Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty,0 
				 
		FROM	#DGS o INNer join ptype p1  on o.ptypeid=p1.typeid '+ @temptable	
		--PRINT @SQL
EXEC (@SQL)
		
SELECT @sql ='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty ,
	total 
)		 
		SELECT 	p1.typeid,
				0 AS RQty,
				0 AS CQty,
				SUM('+@qty+') AS qty,
				0 AS Lendqty,
				0 AS Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty ,
				sum(o.total) as total
           FROM 	goodsstocks o 
                INNer join ptype p1  on o.ptypeid=p1.typeid
                inner join #GetManPTypeID p on p.typeid=o.ptypeid
				inner join #GetManKTypeId k on o.KTypeId=k.TypeId'+ @temptable 
		SELECT @SQL=@SQL+' GROUP BY p1.typeid'
			--PRINT @SQL
EXEC (@SQL)		
		
SELECT @sql ='		
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty ,
	 total
)					
        SELECT 	a.typeid,
				0 AS RQty,
				0 AS CQty,
				0 AS qty,
				'+@Lendqty+' AS Lendqty,
				'+@Borrowqty+' AS  Borrowqty,
				0 AS SaleOrderQty,
				0 AS BuyOrderQty ,
				0
		FROM 	V_LendStatus o 
		       INNer join ptype p1  on o.ptypeid=p1.typeid 
		       inner join #GetManPTypeID a on a.typeid=o.ptypeid
		       inner join #GetManKTypeId k on o.ktypeid=k.typeid' + @temptable+'
				 GROUP BY a.typeid'
				 	--PRINT @SQL
EXEC (@SQL)		
			
SELECT @sql ='
INSERT INTO #LeftJoinTable (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty ,
	total
	 
)	
        SELECT 	a.typeid,
				0 AS RQty,
				0 AS CQty,
				0 AS qty,
				0 AS LendQty,
				0 AS BorrowQty,
				CASE 
					WHEN ISNULL(SUM('+@SaleOrderQty+'),0)-ISNULL(SUM('+@SaleReachQty+'),0)-ISNULL(SUM(O.SaleReferQty),0)>=0 THEN ISNULL(SUM('+@SaleOrderQty+'),0)-ISNULL(SUM('+@SaleReachQty+'),0)-ISNULL(SUM(O.SaleReferQty),0) 
					ELSE 0
				END AS SaleOrderQty,
				CASE
					WHEN ISNULL(SUM('+@BuyOrderQty+'),0)-ISNULL(SUM('+@BuyReachQty+'),0)-ISNULL(SUM(O.BuyReferQty),0)>=0 THEN ISNULL(SUM('+@BuyOrderQty+'),0)-ISNULL(SUM('+@BuyReachQty+'),0)-ISNULL(SUM(O.BuyReferQty),0)
					ELSE 0
				END AS BuyOrderQty  ,
				0
        FROM 	GoodsStocks_Order o
               INNer join ptype p1  on o.ptypeid=p1.typeid
				inner join #GetManPTypeID a on a.typeid=o.ptypeid
				inner join #GetManKTypeId k on o.KTypeId=k.typeid '+ @temptable
					

	SELECT @SQL=@SQL+' GROUP BY a.typeid'
		--PRINT @SQL
EXEC(@SQL)
--SELECT * FROM #LeftJoinTable
  CREATE TABLE #result
(
	TypeId			 VARCHAR(100),
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	Qty				 NUMERIC(24, 10) ,
	Lendqty			 NUMERIC(24, 10) ,
	Borrowqty		 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) ,
	Price            NUMERIC(24,10)   
)
 SELECT @SQL='
 INSERT INTO #result (
	TypeId,
	RQty,
	CQty,
	Qty,
	Lendqty,
	Borrowqty,
	SaleOrderQty,
	BuyOrderQty ,
	Price 
)
	SELECT	a.typeid, 
			ISNULL(SUM(o.rqty),0) AS RQty,
			ISNULL(SUM(o.cqty),0) AS CQty, 
			ISNULL(SUM(o.qty),0) AS qty,
			ISNULL(SUM(o.Lendqty),0) AS Lendqty,
			ISNULL(SUM(o.borrowqty),0) AS Borrowqty, 
			ISNULL(SUM(o.SaleOrderQty),0) SaleOrderQty,   
			ISNULL(SUM(o.BuyOrderQty),0)  BuyOrderQty,
			case when	ISNULL(SUM(o.qty),0)=0 THEN 0 ELSE CAST(ISNULL(SUM(o.total),0) AS NUMERIC(24,10))/CAST(ISNULL(SUM(o.qty),0)AS NUMERIC(24,10)) END  AS price
			
	FROM #GetManPTypeAll a 
	LEFT JOIN #LeftJoinTable o ON LEFT(o.typeid,LEN(a.typeid))=a.typeid  
	 INNER JOIN Ptype p ON p.typeid=a.typeid 
	 group by a.typeid' 
EXEC(@SQL)
	 
-----------------------------------------------------------------------------------------------------
 -- SELECT CombinationProductPtypeId,CombinationProductUsercode,CombinationProductFullName,p.EntryCode,p.Standard,p.Type   from dbo.CombinationProductIndex cpi INNER JOIN dbo.ptype p ON cpi.CombinationProductPtypeId=p.typeId and CombinationProductPtypeId='''+@CombinId+''' 
--SELECT * FROM #result
--商品\
 
 SELECT @sql='
 SELECT DISTINCT UserCode as CPUsercode,FullName as CPFullName,EntryCode as CPEntryCode,Standard as CPStandard,Type as CPType,f.isservice as isservice '
 
 
 --IF @IsShowDetail=1 
 SET @sql= @sql +',f.*'
 
 SET @sql= @sql+'
   from dbo.ptype p
  left join 
 (
 SELECT  
         a.FullName AS PFullName,
		 a.Usercode AS PUserCode,
		 a.Standard AS PStandard,
		 a.Type AS PTypeName, 
		 d.*, 
		 e.CombinationProductPtypeId,
		 e.qty as sptqty,
		 e.IsCheck,
		 e.IsStop,
		 a.isservice as isservice
 		 FROM dbo.ptype a   
 		 left JOIN #result d ON a.typeId=d.typeid  
 		 inner join #Contypeid e on a.typeid=e.typeid 
 		
 		 ) f
 		 on f.CombinationProductPtypeId=p.typeid  
 		  WHERE p.typeId='''+@CombinId+''' 
 		 
 		  --and f.IsCheck=1 
 		  --and f.IsStop=0
 		  order by f.isservice desc
 		 '
 		 --PRINT(@sql)
 		 EXEC (@sql)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCommissionBpDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCommissionBpDetail]
GO










/*
	作者：谢吉康
	日期：2007-3-13
	描述：委托客户商品查询、受托客户商品查询
*/
/* 
    修改: 舒珊
    日期: 2015-05-27
    描述: 增加查询参数@ptypecategoryid 商品类别ID 
    
    修改: 舒珊
    日期: 2015-05-31
    描述: 增加表头、表体新增的自定义字段查询
*/
CREATE   PROCEDURE Web_QueryCommissionBpDetail
(
	@OperatorId		varchar(50),
	@nType			varchar(10),	-- W.委托客户商品查询  S.受托客户商品查询
	@PTypeId		varchar(1550),
	@BTypeId		varchar(1550),
	@StartDate		varchar(30),
	@EndDate		varchar(30),
	@SortField		varchar(100),
	@SortType		varchar(100),
	@Stypeid        varchar(1550)='00001',
	@IsReporting	INT	,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@ptypecategoryid    VARCHAR(MAX )     --商品类别ID	
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 
CREATE TABLE #Ptype (TypeID varchar(200))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))

IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #Ptype(typeid) Select typeid FROM Ptype WHERE Typeid in ( select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a)
ELSE
	INSERT INTO #Ptype(typeid) Select typeid FROM Ptype WHERE Typeid in ( select a.typeid from  F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a)


IF @BtypeID='' OR @BtypeID ='00000'
	INSERT INTO #Btype(typeid) Select typeid FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
ELSE
	INSERT INTO #Btype(typeid) Select typeid FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a)

IF NOT (@Stypeid='' AND @MStypeid='00000')
    INSERT INTO #Stype(typeid) Select typeid FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
    
--处理往来单位和商品
CREATE TABLE #Result
(
	BillNumberId		numeric(18,0),
	Qty					 NUMERIC(24, 10) ,
	Total				 NUMERIC(24, 10) ,
	CostTotal			 NUMERIC(24, 10) ,
	CustomdetailID		INT 
)

DECLARE @TSQL varchar(8000)
IF @nType = 'W'
BEGIN
	SET @TSQL='	INSERT INTO #Result
				SELECT	a.BillNumberId,
						CASE 
							WHEN a.BillType = 140 AND Qty<0 	THEN ABS(Qty)
							WHEN a.BillType = 140 AND Qty>=0 	THEN 0
							WHEN a.BillType = 142 AND Qty>=0	THEN 0
							WHEN a.BillType = 142 AND Qty<0	THEN Qty
							ELSE Qty
						END	 AS Qty,
						CASE 
							WHEN a.BillType = 140 AND Qty<0 	THEN ABS(Total)
							WHEN a.BillType = 140 AND Qty>=0 	THEN 0
							WHEN a.BillType = 142 AND Qty>=0	THEN 0
							WHEN a.BillType = 142 AND Qty<0	THEN Total
							ELSE Total
						END	 AS Total,
						CASE 
							WHEN a.BillType = 140 AND Qty<0 	THEN ABS(CostTotal)
							WHEN a.BillType = 140 AND Qty>=0 	THEN 0
							WHEN a.BillType = 142 AND Qty>=0	THEN 0
							WHEN a.BillType = 142 AND Qty<0	THEN CostTotal
							ELSE CostTotal
						END	AS CostTotal,
						a.id as CustomdetailID
				FROM	InOutStockTable a
				INNER JOIN billindex bi on a.billnumberid=bi.billnumberid'
				
	  IF NOT (@PTypeId='' AND @MPtypeid='00000' AND  @ptypecategoryid='')	
		SET @TSQL=@TSQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
	  
	  IF NOT (@BTypeId='' AND @MBtypeid='00001' AND @MBtypeid='00002')	
		SET @TSQL=@TSQL+' INNER JOIN #Btype b ON bi.btypeid=b.typeid '
	  
	  IF NOT (@Stypeid='' AND @MStypeid='00000')	
		SET @TSQL=@TSQL+' INNER JOIN #Stype S ON a.STypeID=S.TypeID '
	  
	  SET @TSQL=@TSQL+' WHERE   a.BillType IN (140,141,142,143)
						AND a.Audited = 1
						AND a.BillDate>='+ char(39)+ @StartDate+char(39) +' 
						AND a.BillDate<='+ char(39)+ @EndDate +char(39)  +''
END						
ELSE
BEGIN
	SET @TSQL='	INSERT INTO #Result
				SELECT	a.BillNumberId,
						CASE 
							WHEN a.BillType = 144 AND a.KTypeId<>''10000'' THEN Qty
							WHEN a.BillType = 144 AND a.KTypeId=''10000''	 THEN 0					
							WHEN a.BillType = 146 AND a.KTypeId<>''10000'' THEN Qty
							WHEN a.BillType = 146 AND a.KTypeId=''10000''	 THEN 0
							ELSE Qty
						END	AS Qty,
						CASE 
							WHEN a.BillType = 144 AND a.KTypeId<>''10000'' THEN Total
							WHEN a.BillType = 144 AND a.KTypeId=''10000''	 THEN 0
							WHEN a.BillType = 146 AND a.KTypeId<>''10000'' THEN Total
							WHEN a.BillType = 146 AND a.KTypeId=''10000''	 THEN 0
							ELSE Total
						END	AS Total,
						CASE 
							WHEN a.BillType = 144 AND a.KTypeId<>''10000'' THEN CostTotal
							WHEN a.BillType = 144 AND a.KTypeId=''10000''	 THEN 0
							WHEN a.BillType = 146 AND a.KTypeId<>''10000'' THEN CostTotal
							WHEN a.BillType = 146 AND a.KTypeId=''10000''	 THEN 0
							ELSE CostTotal
						END	AS CostTotal,
						a.id  as  CustomdetailID
				FROM	InOutStockTable a 
				INNER JOIN billindex bi on a.billnumberid=bi.billnumberid '
				
	  IF NOT (@PTypeId='' AND @MPtypeid='00000' AND @ptypecategoryid='')		
	   SET @TSQL=@TSQL+' INNER JOIN #Ptype p ON a.ptypeid=p.typeid '
	  
	  IF NOT (@BTypeId='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
	   SET @TSQL=@TSQL+' INNER JOIN #Btype b ON bi.btypeid=b.typeid '
	  
	  IF NOT (@Stypeid='' AND @MStypeid='00000')
	   SET @TSQL=@TSQL+' INNER JOIN #Stype S ON a.STypeID=S.TypeID '
	  
	  SET @TSQL=@TSQL+' WHERE   a.BillType IN (144,145,146,147)
						AND a.Audited = 1
						AND a.BillDate>='+char(39)+@StartDate+char(39)+'
						AND a.BillDate<='+char(39)+@EndDate +char(39)+''
END

EXEC(@TSQL)

--组织数据
DECLARE @SQL varchar(max)

SET @SQL = '
			SELECT	Bil.BillNumberId,
					Bil.BillDate,
					Bil.BillCode,
					Bil.posttime,
					Bil.BillType,
					billname =(select top 1 billname from billname where billtype=Bil.BillType),
					Bil.ID,
					ISNULL(R.Qty,0) AS TotalQty,
					ISNULL(R.Total,0) AS TotalMoney,
					ISNULL(R.CostTotal,0) AS CostTotal,
					Bil.Comment,
					Bil.Stypeid,
					cc.fullname AS cname,
				    bil.rate AS rate,
				    SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32
			FROM	BillIndex Bil
			        INNER JOIN AC_Currency cc  ON bil.cid = cc.cid
					inner join  #Result R on Bil.BillNumberId = R.BillNumberId
					 left join Custom_BillIndex csindex on Bil.billnumberid=csindex.BillId and Bil.billtype=csindex.billtype
left join Custom_BillDetails csdetail on Bil.billnumberid=csdetail.BillId and Bil.billtype=csdetail.billtype AND r.CustomdetailID=csdetail.Detailid
			WHERE	
					 Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND R.Qty<>0
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)
					--+ ' ORDER BY '+@SortField+' '+@SortType

--PRINT(@SQL)
--EXEC(@SQL)
----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
	SET @SQL = @SQL + ' ORDER BY '+@SortField+' '+@SortType
	PRINT @SQL
	EXEC(@SQL)
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
--	CREATE TABLE #tmp_result
--	(
--		billnumberid VARCHAR(100),
--		billtype     VARCHAR(100),
--		Costom1		VARCHAR(max),
--		Costom2		VARCHAR(max),
--		Costom3		VARCHAR(max),
--		Costom4		VARCHAR(max),
--		Costom5		VARCHAR(max),
--		Costom6		VARCHAR(max),
--		Costom7		VARCHAR(max),
--		Costom8		VARCHAR(max),
--		Costom9		VARCHAR(max),
--		Costom10	VARCHAR(max),
--		Costom11	VARCHAR(max),
--		Costom12	VARCHAR(max),
--		Costom13	VARCHAR(max),
--		Costom14	VARCHAR(max),
--		Costom15	VARCHAR(max),
--		Costom16	VARCHAR(max)
--	)
--	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS Bil ' + ' ORDER BY ' + @SortField + ' ' + @SortType + 
--			  ' 
--			   DECLARE @p1 dbo.TBType_SelfType  
--			   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
--			   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 

--				--显示最终结果
--				SELECT DISTINCT row_number() over (order by bil.BillnumberID) AS rowid,Bil.*,b.* 
--						  FROM #temp1 AS Bil 
--						  LEFT JOIN #tmp_result AS b on(Bil.billnumberid = b.billnumberid and Bil.billtype = b.billtype) 
--						  ORDER BY ' + @SortField + ' ' + @SortType + ' 
--				DROP TABLE #temp1,#tmp_result
--			   '
--	PRINT @SQL
--	EXEC (@SQL)
--END
----------------------------------------------------------

DROP TABLE #Result
DROP TABLE #Ptype
DROP TABLE #Btype










GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCommissionBpLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCommissionBpLine]
GO








/*
	作者：谢吉康
	日期：2007-3-13
	描述：委托客户商品查询、受托客户商品查询
*/

/* 
    修改: 魏伟
    日期: 2015-05-23
    描述: 增加查询参数@ptypecategoryid 商品类别ID 改商品的权限检查方法为F_LinePC 
*/
CREATE   PROCEDURE Web_QueryCommissionBpLine
(
	@OperatorId		varchar(50),
	@nType			varchar(10),	-- W.委托客户商品查询  S.受托客户商品查询
	@PTypeId		varchar(1550),
	@BTypeId		varchar(1550),
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@SortField		varchar(100),
	@SortType		varchar(100),
	@Stypeid      varchar(1550)='00001',
	@ptypecategoryid    VARCHAR(MAX )     --商品类别ID	
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 


CREATE TABLE #TPtype (TypeID varchar(50))
CREATE TABLE #TBtype (TypeID varchar(50))
CREATE TABLE #TStype (TypeID varchar(50))


IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #TPtype(typeid) Select typeid FROM Ptype WHERE Typeid in ( select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a)
ELSE
	INSERT INTO #TPtype(typeid) Select typeid FROM Ptype WHERE Typeid in ( select a.typeid from F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a)


IF @BtypeID='' OR @BtypeID ='00000'
	INSERT INTO #TBtype(typeid) Select typeid FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
ELSE
	INSERT INTO #TBtype(typeid) Select typeid FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a)


IF NOT (@STypeId = '' AND @MStypeid = '00000')
    INSERT INTO #TStype(typeid) Select typeid FROM F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
    
--处理往来单位和商品
CREATE TABLE #Result
(
	PTypeId		varchar(100),
	BTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	BillDate 	datetime
)

DECLARE @TSQL varchar(8000)
IF @nType = 'W'
BEGIN
	SET @TSQL='	INSERT INTO #Result
				SELECT	DISTINCT
						B.PTypeId,
						B.BTypeId,
						SUM(B.Qty) AS Qty,
						SUM(B.Total) AS Total,
						B.BillDate
				FROM	(
					SELECT	c.PTypeId,
							c.BTypeId,
							SUM(c.Qty) AS Qty,
							SUM(c.Total) AS Total,
							''1900-01-01'' AS BillDate
					FROM	iniCommissionStock c '
							
  IF NOT(@PTypeId='' AND @MPtypeid='00000' AND @ptypecategoryid='')
	SET @TSQL=@TSQL+' INNER JOIN #TPtype p ON c.ptypeid=p.typeid '
  
  IF  NOT(@BTypeId='' AND @MBtypeid='00001' AND @MBtypeid2='00002') 
	SET @TSQL=@TSQL+' INNER JOIN #TBtype b ON c.btypeid=b.typeid '
	
  
  IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @TSQL=@TSQL+' INNER JOIN #TStype s ON c.STypeID=s.TypeID '
  
  SET @TSQL=@TSQL+' WHERE c.Type = 140
					GROUP BY PTypeId,BTypeId
					UNION ALL
					SELECT	c.PTypeId,
							Bi.btypeid,
							SUM(
									CASE 
										WHEN  c.BillType = 140 AND Qty<0 	THEN ABS(Qty)
										WHEN  c.BillType = 140 AND Qty>=0 	THEN 0
										WHEN  c.BillType = 142 AND Qty>=0	THEN 0
										WHEN  c.BillType = 142 AND Qty<0	THEN Qty
										ELSE Qty
									END
							) AS Qty,
							SUM(
									CASE 
										WHEN  c.BillType = 140 AND Qty<0 	THEN ABS(Total)
										WHEN  c.BillType = 140 AND Qty>=0 	THEN 0
										WHEN  c.BillType = 142 AND Qty>=0	THEN 0
										WHEN  c.BillType = 142 AND Qty<0	THEN Total
										ELSE Total
									END
							) AS Total,
							c.BillDate
					FROM	InOutStockTable c 
					INNER JOIN billindex bi ON Bi.billnumberid = c.billnumberid '
					
  IF NOT(@PTypeId='' AND @MPtypeid='00000' AND @ptypecategoryid='')
	SET @TSQL=@TSQL+' INNER JOIN #TPtype p ON c.ptypeid=p.typeid '
  
  IF NOT(@BTypeId='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
	SET @TSQL=@TSQL+' INNER JOIN #TBtype b ON Bi.btypeid=b.typeid '
	
  
  IF NOT(@Stypeid='' AND @MStypeid='00000')
	SET @TSQL=@TSQL+' INNER JOIN #TStype s ON c.STypeID=s.TypeID '
					
  SET @TSQL=@TSQL+' WHERE c.BillType IN (140,141,142,143)
							AND c.Audited = 1
					GROUP BY c.PTypeId,bi.BTypeId,c.BillDate
				)B
				GROUP BY B.PTypeId,B.BTypeId,B.BillDate '
END							
ELSE      ----@nType='S'
BEGIN
	SET @TSQL='	INSERT INTO #Result
				SELECT	DISTINCT
						B.PTypeId,
						B.BTypeId,
						SUM(B.Qty) AS Qty,
						SUM(B.Total) AS Total,
						B.BillDate
				FROM	(
					SELECT	c.PTypeId,
							c.BTypeId,
							SUM(c.Qty) AS Qty,
							SUM(c.Total) AS Total,
							''1900-01-01'' AS BillDate
					FROM	iniCommissionStock c '
					
  IF NOT(@PTypeId='' AND @MPtypeid='00000' AND @ptypecategoryid='') 					
	SET @TSQL=@TSQL+' INNER JOIN #TPtype p ON c.ptypeid=p.typeid '
  
  IF NOT(@BTypeId='' AND @MBtypeid='00001' AND @MBtypeid='00002') 
	SET @TSQL=@TSQL+' INNER JOIN #TBtype b ON c.btypeid=b.typeid '

  IF NOT(@Stypeid='' AND @MStypeid='00000') 
	SET @TSQL=@TSQL+' INNER JOIN #TStype s ON c.STypeID=s.TypeID '
					
  SET @TSQL=@TSQL+' WHERE c.Type = 144
					GROUP BY c.PTypeId,c.BTypeId
					UNION ALL
					SELECT	c.PTypeId,
							Bi.btypeid,
							SUM(
									CASE 
										WHEN c.BillType = 144 AND c.KTypeId<>''10000'' THEN Qty
										WHEN c.BillType = 144 AND c.KTypeId=''10000''	 THEN 0
										WHEN c.BillType = 146 AND c.KTypeId<>''10000'' THEN Qty
										WHEN c.BillType = 146 AND c.KTypeId=''10000''	 THEN 0
										ELSE Qty
									END
							) AS Qty,
							SUM(
									CASE 
										WHEN c.BillType = 144 AND c.KTypeId<>''10000'' THEN Total
										WHEN c.BillType = 144 AND c.KTypeId=''10000''	 THEN 0
										WHEN c.BillType = 146 AND c.KTypeId<>''10000'' THEN Total
										WHEN c.BillType = 146 AND c.KTypeId=''10000''	 THEN 0
										ELSE Total
									END
							) AS Total,
							c.BillDate
					FROM	InOutStockTable c 
					INNER JOIN billindex bi ON Bi.billnumberid = c.billnumberid'
					
  IF NOT(@PTypeId='' AND @MPtypeid='00000' AND @ptypecategoryid='') 	
	SET @TSQL=@TSQL+' INNER JOIN #TPtype p ON c.ptypeid=p.typeid '
  
  IF NOT(@BTypeId='' AND @MBtypeid='00001' AND @MBtypeid='00002') 
	SET @TSQL=@TSQL+' INNER JOIN #TBtype b ON bi.btypeid=b.typeid '
	
  IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @TSQL=@TSQL+' INNER JOIN #TStype s ON c.STypeID=s.TypeID '
					
					
  SET @TSQL=@TSQL+' WHERE c.BillType IN (144,145,146,147)
						 AND c.Audited = 1
					GROUP BY c.PTypeId,bi.BTypeId,c.BillDate
				)B
				GROUP BY B.PTypeId,B.BTypeId,B.BillDate '

END
--PRINT @TSQL
exec(@TSQL)
--处理往来单位基本信息
SELECT	DISTINCT
		B.TypeId,
		B.UserCode,
		B.FullName
INTO	#BType
FROM	BType B
INNER JOIN (
		SELECT	BTypeId
		FROM 	#Result
)I ON B.TypeId = I.BTypeId

--处理商品基本信息
SELECT	DISTINCT
		P.TypeId,
		P.UserCode,
		P.FullName,
		P.EntryCode,
		P.Standard,
		P.Type,
		P.Area,
		P.Unit1
INTO	#PType
FROM	PType P
INNER JOIN (
		SELECT	PTypeId
		FROM 	#Result
)I ON P.TypeId = I.PTypeId

--运算数据
DECLARE @SQL varchar(8000)

SET @SQL = '
			SELECT	DISTINCT
					B.TypeId AS BTypeId,
					I.PTypeId,
					B.UserCode AS BUserCode,
					B.FullName AS BFullName,
					EntryCode = (SELECT EntryCode FROM #PType WHERE TypeId = I.PTypeId),
					Standard = (SELECT Standard FROM #PType WHERE TypeId = I.PTypeId),
					Type = (SELECT Type FROM #PType WHERE TypeId = I.PTypeId),
					Area = (SELECT Area FROM #PType WHERE TypeId = I.PTypeId),
					Unit1 = (SELECT Unit1 FROM #PType WHERE TypeId = I.PTypeId),
					PUserCode = (SELECT UserCode FROM #PType WHERE TypeId = I.PTypeId),
					PFullName = (SELECT FullName FROM #PType WHERE TypeId = I.PTypeId),
					ISNULL(I.pQty,0) AS pQty,
					ISNULL(I.pTotal,0) AS pTotal,
					ISNULL(I.cQty,0) AS cQty,
					ISNULL(I.cTotal,0) AS cTotal,
					mqty =ISNULL(I.pQty,0) +ISNULL(I.cQty,0),
					mtotal=ISNULL(I.pTotal,0) +ISNULL(I.cTotal,0)
			FROM	#BType B
			INNER JOIN (
				SELECT	X.PTypeId,
						X.BTypeId,
						SUM(pQty) AS pQty,
						SUM(pTotal) AS pTotal,
						SUM(cQty) AS cQty,
						SUM(cTotal) AS cTotal
				FROM	(
							SELECT	PTypeId,
									BTypeId,
									SUM(Qty) AS pQty,
									SUM(Total) AS pTotal,
									0 AS cQty,
									0 AS cTotal
							FROM	#Result
							WHERE	BillDate<'+char(39)+@StartDate+char(39)+'
							GROUP BY PTypeId,BTypeId
							UNION ALL	
							SELECT	PTypeId,
									BTypeId,
									0 AS pQty,
									0 AS pTotal,
									SUM(Qty) AS cQty,
									SUM(Total) AS cTotal
							FROM	#Result
							WHERE	BillDate>='+char(39)+@StartDate+char(39)+'
									AND BillDate<='+char(39)+@EndDate+char(39)+'
							GROUP BY PTypeId,BTypeId
				)X GROUP BY X.PTypeId,X.BTypeId
			)I ON (B.TypeId = I.BTypeId)
			ORDER BY '+@SortField+' ' + @SortType

--PRINT(@SQL) 
EXEC(@SQL)

DROP TABLE #BType,#PType,#Result,#TPType,#TBtype











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCommissionBpPre]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCommissionBpPre]
GO








/*
	作者：谢吉康
	日期：2007-3-13
	描述：委托客户商品查询、受托客户商品查询此前余量
*/

/* 
    修改: 舒珊
    日期: 2015-05-27
    描述: 增加查询参数@ptypecategoryid 商品类别ID 
*/
CREATE  PROCEDURE Web_QueryCommissionBpPre
(
	@OperatorId		varchar(50),
	@nType			varchar(10),	-- W.委托客户商品查询  S.受托客户商品查询
	@PTypeId		varchar(1550),
	@dealBTypeId		varchar(1550),
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@Stypeid        varchar(max),
	@PreQty			 NUMERIC(24, 10)  OUTPUT,
	@PreTotal		 NUMERIC(24, 10)  OUTPUT,
	@PreCostTotal	 NUMERIC(24, 10)  OUTPUT,
	@ptypecategoryid    VARCHAR(MAX )     --商品类别ID	
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #TPtype (TypeID varchar(200))
CREATE TABLE #TBtype (TypeID varchar(50))
CREATE TABLE #TStype (TypeID varchar(50))

IF @PtypeID='' OR @PtypeID ='00000'
	INSERT INTO #TPtype(typeid) Select typeid FROM Ptype WHERE Typeid in ( select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a)
ELSE
	INSERT INTO #TPtype(typeid) Select typeid FROM Ptype WHERE Typeid in ( select a.typeid from F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a)


IF @dealBtypeID='' OR @dealBtypeID ='00000'
	INSERT INTO #TBtype(typeid) Select typeid FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a)
ELSE
	INSERT INTO #TBtype(typeid) Select typeid FROM Btype WHERE Typeid in ( select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@dealBtypeID,',')) b where left(a.typeid,len(b.a))=b.a)

IF NOT (@Stypeid='' AND @MStypeid='00000')
   INSERT INTO #TStype(typeid) Select typeid FROM  F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)
   
--处理往来单位和商品
CREATE TABLE #Result
(
	PTypeId		varchar(200),
	BTypeId		varchar(100),
	Qty			 NUMERIC(24, 10) ,
	Total		 NUMERIC(24, 10) ,
	CostTotal	 NUMERIC(24, 10) ,
	BillDate 	datetime
)
DECLARE @SQL varchar(8000)
IF @nType = 'W'
BEGIN
	 SET @SQL=' INSERT INTO #Result
				SELECT	DISTINCT
						B.PTypeId,
						B.BTypeId,
						SUM(B.Qty) AS Qty,
						SUM(B.Total) AS Total,
						SUM(B.CostTotal) AS CostTotal,		
						B.BillDate
				FROM	(
					SELECT	PTypeId,
							BTypeId,
							SUM(Qty) AS Qty,
							SUM(Total) AS Total,
							SUM(CostTotal) AS CostTotal,
							''1900-01-01'' AS BillDate
					FROM	iniCommissionStock c '
					
	IF NOT (@PTypeId='' AND @MPtypeid='00000' AND @ptypecategoryid='')				
		SET @SQL=@SQL+' INNER JOIN #TPtype p ON c.ptypeid=p.typeid '
	
	IF NOT (@dealBTypeId='' AND @MBtypeid='00001' AND @MBtypeid='00002')		
		SET @SQL=@SQL+' INNER JOIN #TBtype b ON c.btypeid=b.typeid '
	
	IF NOT (@Stypeid='' AND @MStypeid='00000')
		SET @SQL=@SQL+' INNER JOIN #TStype s ON c.stypeid=s.typeid '
	
	SET @SQL=@SQL+' WHERE Type = 140
					GROUP BY PTypeId,BTypeId
					UNION ALL
					SELECT	PTypeId,
							BTypeId,
							SUM(
									CASE 
										WHEN BillType = 140 AND Qty<0 	THEN ABS(Qty)
										WHEN BillType = 140 AND Qty>=0 	THEN 0
										WHEN BillType = 142 AND Qty>=0	THEN 0
										WHEN BillType = 142 AND Qty<0	THEN Qty
										ELSE Qty
									END
							) AS Qty,
							SUM(
									CASE 
										WHEN BillType = 140 AND Qty<0 	THEN ABS(Total)
										WHEN BillType = 140 AND Qty>=0 	THEN 0
										WHEN BillType = 142 AND Qty>=0	THEN 0
										WHEN BillType = 142 AND Qty<0	THEN Total
										ELSE Total
									END
							) AS Total,
							SUM(
									CASE 
										WHEN BillType = 140 AND Qty<0 	THEN ABS(CostTotal)
										WHEN BillType = 140 AND Qty>=0 	THEN 0
										WHEN BillType = 142 AND Qty>=0	THEN 0
										WHEN BillType = 142 AND Qty<0	THEN CostTotal
										ELSE CostTotal
									END
							) AS CostTotal,
							BillDate
					FROM	InOutStockTable c '
					
	IF NOT (@PTypeId='' AND @MPtypeid='00000' AND @ptypecategoryid='')				
		SET @SQL=@SQL+' INNER JOIN #TPtype p ON c.ptypeid=p.typeid '
	
	IF NOT (@dealBTypeId='' AND @MBtypeid='00001' AND @MBtypeid2='00002')
		SET @SQL=@SQL+' INNER JOIN #TBtype b ON c.btypeid=b.typeid '
	
	IF NOT (@Stypeid='' AND @MStypeid='00000')
		SET @SQL=@SQL+' INNER JOIN #TStype S ON c.stypeid=s.typeid '
	
	SET @SQL=@SQL+' WHERE BillType IN (140,141,142,143)
							AND Audited = 1
							AND BillDate<'''+@StartDate+'''
					GROUP BY PTypeId,BTypeId,BillDate
				)B
				GROUP BY B.PTypeId,B.BTypeId,B.BillDate '
END	
ELSE
BEGIN
	 SET @SQL=' INSERT INTO #Result
				SELECT	DISTINCT
						B.PTypeId,
						B.BTypeId,
						SUM(B.Qty) AS Qty,
						SUM(B.Total) AS Total,
						SUM(B.CostTotal) AS CostTotal,
						B.BillDate
				FROM	(
					SELECT	PTypeId,
							BTypeId,
							SUM(Qty) AS Qty,
							SUM(Total) AS Total,
							SUM(CostTotal) AS CostTotal,
							''1900-01-01'' AS BillDate
					FROM	iniCommissionStock c '
					
	IF NOT (@PTypeId='' AND @MPtypeid='00000' AND  @ptypecategoryid='')				
		SET @SQL=@SQL+' INNER JOIN #TPtype p ON c.ptypeid=p.typeid '
	
	IF NOT(@dealBTypeId='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
		SET @SQL=@SQL+' INNER JOIN #TBtype b ON c.btypeid=b.typeid '
	
	IF NOT (@Stypeid='' AND @MStypeid='00000')
		SET @SQL=@SQL+' INNER JOIN #TStype s ON c.stypeid=s.typeid '
	
	SET @SQL=@SQL+' WHERE Type = 144
					GROUP BY PTypeId,BTypeId
					UNION ALL
					SELECT	PTypeId,
							BTypeId,
							SUM(
									CASE 
										WHEN BillType = 144 AND KTypeId<>''10000'' THEN Qty
										WHEN BillType = 144 AND KTypeId=''10000''	 THEN 0
										WHEN BillType = 146 AND KTypeId<>''10000'' THEN Qty
										WHEN BillType = 146 AND KTypeId=''10000''	 THEN 0
										ELSE Qty
									END
							) AS Qty,
							SUM(
									CASE 
										WHEN BillType = 144 AND KTypeId<>''10000'' THEN Total
										WHEN BillType = 144 AND KTypeId=''10000''	 THEN 0
										WHEN BillType = 146 AND KTypeId<>''10000'' THEN Total
										WHEN BillType = 146 AND KTypeId=''10000''	 THEN 0
										ELSE Total
									END
							) AS Total,
							SUM(
									CASE 
										WHEN BillType = 144 AND KTypeId<>''10000'' THEN CostTotal
										WHEN BillType = 144 AND KTypeId=''10000''	 THEN 0
										WHEN BillType = 146 AND KTypeId<>''10000'' THEN CostTotal
										WHEN BillType = 146 AND KTypeId=''10000''	 THEN 0
										ELSE Qty
									END
							) AS CostTotal,
							BillDate
					FROM	InOutStockTable c '
					
	IF NOT (@PTypeId='' AND @MPtypeid='00000' AND  @ptypecategoryid='')				
		SET @SQL=@SQL+' INNER JOIN #TPtype p ON c.ptypeid=p.typeid '
	
	IF NOT(@dealBTypeId='' AND @MBtypeid='00001' AND @MBtypeid2='00002')	
		SET @SQL=@SQL+' INNER JOIN #TBtype b ON c.btypeid=b.typeid '
	
	IF NOT (@Stypeid='' AND @MStypeid='00000')
		SET @SQL=@SQL+' INNER JOIN #TStype s ON c.stypeid=s.typeid '
	
	SET @SQL=@SQL+' WHERE BillType IN (144,145,146,147)
							AND Audited = 1
							AND BillDate<'''+@StartDate +'''
					GROUP BY PTypeId,BTypeId,BillDate
				)B
				GROUP BY B.PTypeId,B.BTypeId,B.BillDate '

END

--PRINT(@SQL)
EXEC(@SQL)

--处理往来单位基本信息
SELECT	DISTINCT
		B.TypeId,
		B.UserCode,
		B.FullName
INTO	#BType
FROM	BType B
INNER JOIN (
		SELECT	BTypeId
		FROM 	#Result
)I ON B.TypeId = I.BTypeId

--处理商品基本信息
SELECT	DISTINCT
		P.TypeId,
		P.UserCode,
		P.FullName,
		P.EntryCode,
		P.Standard,
		P.Type,
		P.Area,
		P.Unit1
INTO	#PType
FROM	PType P
INNER JOIN (
		SELECT	PTypeId
		FROM 	#Result
)I ON P.TypeId = I.PTypeId

--运算数据
SELECT	@PreQty   		= ISNULL(I.pQty,0),
		@PreTotal 		= ISNULL(I.pTotal,0),
		@PreCostTotal 	= ISNULL(I.pCostTotal,0)
FROM	#BType B
INNER JOIN (
	SELECT	X.BTypeId,
			SUM(pQty) AS pQty,
			SUM(pTotal) AS pTotal,
			SUM(pCostTotal) AS pCostTotal
	FROM	(
				SELECT	BTypeId,
						SUM(Qty) AS pQty,
						SUM(Total) AS pTotal,
						SUM(CostTotal) AS pCostTotal	
				FROM	#Result
				WHERE	BillDate<@StartDate
				GROUP BY PTypeId,BTypeId
	)X GROUP BY X.BTypeId
)I ON (B.TypeId = I.BTypeId) 



DROP TABLE #BType,#PType,#Result,#TBType,#TPType








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCommissionReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCommissionReport]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：杨俊
	日期：2014-05-21
	描述：查询提成报表统计
-------------------------------------------*/
CREATE PROCEDURE Web_QueryCommissionReport
(
	@SchemeStart		VARCHAR(20),	--开始时间
	@SchemeEnd			VARCHAR(20),	--截止时间
	@StypeID			VARCHAR(20),	--分支机构ID（单个）
	@DtypeID			VARCHAR(MAX),	--部门ID（多个）
	@EtypeID			VARCHAR(MAX),	--经手人ID（多个）
	@OperatorID			VARCHAR(50)		--操作员
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetStypeID(typeid varchar(100))
--IF NOT (@StypeID = '' AND @MStypeid = '00000')
	INSERT INTO #GetStypeID(typeid) SELECT TYPEID FROM F_GetAllManagerBaseTypeId(@StypeID,11,@OperatorID)

--部门
CREATE TABLE #GetManDTypeId(TypeId VARCHAR(100))
--IF NOT (@DtypeID = '' AND @MDTypeId = '00000')
	INSERT INTO #GetManDTypeId(typeid) SELECT TYPEID FROM F_GetAllManagerBaseTypeId(@DtypeID,9,@OperatorID)

--经手人
CREATE TABLE #GetManETypeId(TypeId VARCHAR(100))
IF NOT (@EtypeID = '' AND @METypeId = '00000')
	INSERT INTO #GetManETypeId(typeid) SELECT TYPEID FROM F_GetAllManagerBaseTypeId(@EtypeID,3,@OperatorID)
-----------------------------------------------------------------------------------------------------------------------------
--当前时间
DECLARE @DATE VARCHAR(20)
SET @DATE = CONVERT(VARCHAR(100), GETDATE(), 23)

SELECT A.dtypeid,
	   D.FullName AS department,
	   A.etypeid,
	   B.FullName AS etypefullname,
	   SUM(A.Total) AS resultstotal,
	   SUM(A.CommissionTotal) AS commissiontotal,
	   C.stypeid 
FROM CommissionBillNewDetail AS A 
INNER JOIN employee AS B ON(B.typeId = A.EtypeID)
INNER JOIN Department as D ON(D.typeid = A.DtypeID)
INNER JOIN CommissionBillNew AS C ON(C.BillNumberId = A.BillNumberId)
INNER JOIN #GetManETypeId AS E ON(E.TypeId = A.EtypeID)
INNER JOIN #GetManDTypeId AS D1 ON(D1.TypeId = A.DtypeID)
INNER JOIN #GetStypeID AS S ON(S.typeid = C.StypeID)
WHERE C.BillDate BETWEEN @SchemeStart AND @SchemeEnd 
	  AND C.ifcheck = 't'
	  --AND (NOT(@StypeID <> '') 
			--		OR (@StypeID <> '') AND C.StypeID IN(SELECT TypeId FROM #GetStypeID)) 
	  --AND (NOT(@EtypeID <> '') 
			--		OR (@EtypeID <> '') AND A.EtypeID IN(SELECT TypeId FROM #GetManETypeId))
	  --AND (NOT(@DtypeID <> '') 
			--		OR (@DtypeID <> '') AND B.DtypeID IN(SELECT TypeId FROM #GetManDTypeId)) 
GROUP BY A.EtypeID,A.DtypeID,D.FullName,B.FullName,C.stypeid 
ORDER BY D.FullName,A.EtypeID

DROP TABLE #GetManETypeId
-----------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCommissionScheme]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCommissionScheme]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：杨俊
	日期：2014-05-19
	描述：查询提成方案
-------------------------------------------*/
CREATE PROCEDURE Web_QueryCommissionScheme
(
	--@SchemeStart		VARCHAR(20),	--开始时间
	--@SchemeEnd			VARCHAR(20),	--截止时间
	@SchemeName			VARCHAR(100),	--方案名称
	@StypeID			VARCHAR(MAX),	--分支机构ID（多个）
	@CommissionRuleID	VARCHAR(MAX),	--提成规则ID（多个）
	@ReferencePlanID	VARCHAR(MAX),	--参照计划提成ID（多个）
	@Comment			VARCHAR(256),	--摘要
	@BillState			INT,			--单据状态
	@UseState			INT,			--使用状态
	--@EffectState		INT,			--是否生效
	@OperatorID			VARCHAR(50),	--操作员
	@IsAllowViweOther	INT				--允许查看他人方案
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId VARCHAR(100))
IF NOT (@StypeID = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) 
	SELECT TypeId FROM F_GetAllManagerBaseTypeId(@StypeID,11,@OperatorID)	
	
--提成规则
CREATE TABLE #GetManCommissionRuleId(TypeId VARCHAR(10))
	INSERT INTO #GetManCommissionRuleId(TypeId) 
	SELECT A FROM dbo.F_Split(@CommissionRuleID,',')
	
--参照计划提成
CREATE TABLE #GetManReferencePlanId(TypeId VARCHAR(10))
	INSERT INTO #GetManReferencePlanId(TypeId) 
	SELECT A FROM dbo.F_Split(@ReferencePlanID,',')
-----------------------------------------------------------------------------------------------------------------------------
--当前时间
DECLARE @DATE VARCHAR(20)
SET @DATE = CONVERT(VARCHAR(100), GETDATE(), 23)

IF(@OperatorID = '00001')  --超级管理默认有"允许查看他人方案"权限
	SET @IsAllowViweOther = 1

--SELECT billnumberid,schemestart,schemeend,schemename,stypeid,fullname,
--commissionrulefullname,referenceplanfullname,comment,
--billstate,usestate,checke,checker,effectstate 
--FROM 
--(	
	SELECT DISTINCT A.billnumberid,
		   --A.schemestart,
		   --A.schemeend,
		   A.schemename,
		   B.FullName,
		   --C.fullname,
		  -- A.commissionruleid,
		   ISNULL(D.FullName,'') AS commissionrulefullname,
		   ISNULL(G.FullName,'') AS referenceplanfullname,
		   A.comment,
		   CASE A.BillState 
				WHEN 1 THEN '未审核'
				WHEN 2 THEN '已审核'
				WHEN 3 THEN '禁用'
		   END AS billstate,
		   --A.BillState AS billstateid,
		   CASE A.UseState
				WHEN 1 THEN '未引用'
				WHEN 2 THEN '已引用'
				WHEN 3 THEN '部分完成'
				WHEN 4 THEN '全部完成'
		   END AS usestate,
		   --A.UseState AS usestateid,
		   E.FullName AS checke,
		   ISNULL(F.FullName,'') AS checker 
		 --  ,
		 --  CASE 
			--	WHEN @DATE < SchemeStart THEN 1
			--	WHEN @DATE > SchemeEnd THEN 2
			--	WHEN @DATE >= SchemeStart AND @DATE <= SchemeEnd AND A.BillState = 2 THEN 0
			--	ELSE 1
			--END AS effectstate 
	FROM CommissionScheme AS A 
	INNER JOIN 
	(
		SELECT BillNumberId,StypeID,FullName = DBO.F_CommissionSchemeStype(BillNumberId,0) 
		FROM CommissionSchemeStype
	) AS B ON(A.BillNumberId = B.BillNumberId)
	--(
	--	SELECT BillNumberId,StypeID FROM CommissionSchemeStype 
	--	WHERE ID IN
	--	(
	--		SELECT MIN(ID) FROM CommissionSchemeStype GROUP BY BillNumberId
	--	)
	--) AS B ON(A.BillNumberId = B.BillNumberId)
	--INNER JOIN SType AS C ON(B.StypeID = C.TypeId)
	LEFT JOIN CommissionRule AS D ON(A.CommissionRuleID = D.BillNumberId)
	LEFT JOIN ReferencePlanCommission AS G ON(A.ReferencePlanID = G.BillNumberId)
	INNER JOIN employee AS E ON(A.Checke = E.typeId)
	LEFT JOIN employee AS F ON(A.Checker = F.typeId)
	WHERE --A.SchemeStart >= @SchemeStart 
			--AND A.SchemeEnd <= @SchemeEnd 
			--AND 
			A.SchemeName LIKE '%' + @SchemeName + '%'
			AND (NOT(@StypeID <> '') 
					OR (@StypeID <> '') AND B.StypeID IN(SELECT TypeId FROM #GetManSTypeId)) 
			AND (NOT(@CommissionRuleID <> '') 
					OR (@CommissionRuleID <> '') AND A.CommissionRuleID IN(SELECT TypeId FROM #GetManCommissionRuleId)) 
			AND (NOT(@ReferencePlanID <> '') 
					OR (@ReferencePlanID <> '') AND A.ReferencePlanID IN(SELECT TypeId FROM #GetManReferencePlanId)) 		
			AND A.Comment LIKE '%' + @Comment + '%'
			AND (NOT(@BillState <> 0)
					OR (@BillState <> 0) AND A.BillState = @BillState) 
			AND (NOT(@UseState <> 0)
					OR (@UseState <> 0) AND A.UseState = @UseState)		
			AND (NOT(@IsAllowViweOther <> 1) 
					OR (@IsAllowViweOther <> 1) AND A.Checke = @OperatorID)
--) AS A 
--WHERE (NOT(@EffectState <> 3)
--		OR (@EffectState <> 3) AND A.effectstate = @EffectState)

DROP TABLE #GetManSTypeId,#GetManCommissionRuleId,#GetManReferencePlanId
-----------------------------------------------------------------------------------------------------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCompareVirtualStock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryCompareVirtualStock]
GO

/*
	作者：谢吉康
	日期：2011-08-17
	描述：比对虚拟库存的通用算法	
	Web_QueryCompareVirtualStock '00001','00001,00001','00001,00002','1,2','0,0'
	EXEC Web_QueryVirtualStock '00001','00001,00001','00001,00002'
*/
CREATE PROCEDURE Web_QueryCompareVirtualStock
(
	@OperatorID 	VARCHAR(100),  	     	--操作员ID号 		
	@BillNumberId	VARCHAR(8000),			--单据ID
	@billtype		int=300,				--单据类型
	@tb				TbType_VirtualStock READONLY
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL	VARCHAR(MAX),
		@Value	VARCHAR(MAX)

SELECT @Value = ISNULL(Value,'') FROM Userconfig WHERE ConfigName = 'VirtualQtySQL'

--判断是否加上当前单据草稿
DECLARE @needDraftFlag INT=0
DECLARE @needReferOrder INT=1
	
IF (SELECT CHARINDEX('-isnull(cqty,0)',@Value))>0
	OR (SELECT CHARINDEX('isnull(borrowqty,0)',@Value))>0
	OR (SELECT CHARINDEX('isnull(lendqty,0)',@Value))>0
BEGIN
	SET @needDraftFlag=1
END

IF (SELECT CHARINDEX('-isnull(buyorderqty,0)',@Value))<=0 AND (SELECT CHARINDEX('-isnull(saleorderqty,0)',@Value))<=0
BEGIN
	SET @needReferOrder=0
END 

--配置为空，则不效验了
IF LTRIM(RTRIM(@Value)) = ''
BEGIN
	SELECT TOP 1 * FROM employee WHERE 1 = 0
	RETURN
END	

--获取虚拟库存数据
CREATE TABLE #VirtualGoodsStocks
(
	PTypeId			VARCHAR(100),
	KTypeId			VARCHAR(100),
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	ItemID			INT,
	GoodsNumber		VARCHAR(100),
	CargoID			INT,
	GoodsCostPrice	  NUMERIC(24,10),
	Qty				 NUMERIC(24, 10) ,
	RQty			 NUMERIC(24, 10) ,
	CQty			 NUMERIC(24, 10) ,
	SaleOrderQty	 NUMERIC(24, 10) ,
	BuyOrderQty		 NUMERIC(24, 10) 
)
CREATE NONCLUSTERED INDEX VGSPTypeId ON #VirtualGoodsStocks(PTypeId)
CREATE NONCLUSTERED INDEX VGSKTypeId ON #VirtualGoodsStocks(KTypeId)

--单据数据
CREATE TABLE #Result
(
	nID			INT IDENTITY(1,1),
	PTypeId		VARCHAR(100),
	KTypeId		VARCHAR(100),
	GoodsCostPrice	  NUMERIC(24,10),
	Qty			NUMERIC(24, 10) 
)	
--维度：商品+仓库
INSERT INTO #Result(PTypeId,KTypeId,GoodsCostPrice,Qty)
SELECT	P.PTypeId,
		P.KTypeId,
		P.GoodsCostPrice,
		SUM(
			CASE
				WHEN P.Unit = 0 THEN ISNULL(P.Qty,0)
				ELSE CAST(ISNULL(P.Qty,0) * BP.UnitRate1 AS  NUMERIC(24, 10) )
			END
		) AS Qty
FROM	@tb P
INNER JOIN PType BP ON BP.TypeId = P.PTypeId  
WHERE BP.isservice=0 --不统计服务类商品
GROUP BY P.PTypeId,P.KTypeId,P.GoodsCostPrice
ORDER BY P.PTypeId,P.KTypeId ASC

--维度：商品+仓库+货位+自由项+批号+生产日期+效期至
CREATE TABLE #Result1
(
	nID			INT IDENTITY(1,1),	
	PTypeId		VARCHAR(100),
	KTypeId		VARCHAR(100),
	ProduceDate VARCHAR(50),
	ValidDate	VARCHAR(50),
	ItemID		INT,
	GoodsNumber	VARCHAR(100),
	CargoID		INT,
	GoodsCostPrice	  NUMERIC(24,10),
	Qty			NUMERIC(24, 10) 
)
INSERT INTO #Result1(PTypeId,KTypeId,ProduceDate,ValidDate,ItemID,GoodsNumber,CargoID,GoodsCostPrice,Qty)
SELECT	P.PTypeId,
		P.KTypeId,
		P.ProduceDate,
		P.ValidDate,
		P.ItemID,
		P.GoodsNumber,
		P.CargoID,
		P.GoodsCostPrice,
		SUM(
			CASE
				WHEN P.Unit = 0 THEN ISNULL(P.Qty,0)
				ELSE CAST(ISNULL(P.Qty,0) * BP.UnitRate1 AS  NUMERIC(24, 10) )
			END
		) AS Qty
FROM	@tb P
INNER JOIN PType BP ON BP.TypeId = P.PTypeId  WHERE BP.isservice=0 --不统计服务类商品
GROUP BY P.PTypeId,P.KTypeId,P.ProduceDate,P.ValidDate,P.ItemID,P.GoodsNumber,P.CargoID,P.GoodsCostPrice
ORDER BY P.PTypeId,P.KTypeId ASC

--排除表体明细行相同的数据
CREATE TABLE #tempTable
(
	nID		INT IDENTITY(1,1),
	KTypeId	VARCHAR(100),
	PTypeId	VARCHAR(100),
	OrderId	VARCHAR(100),
	Qty		NUMERIC(24, 10) 
)
DECLARE @KTypeId NVARCHAR(MAX)='',@PTypeId NVARCHAR(MAX)='',@orderids NVARCHAR(MAX)='',@QTYs NVARCHAR(MAX)='';

INSERT INTO #tempTable (KTypeId,PTypeId,OrderId,Qty)
SELECT	P.KTypeId,
		P.PTypeId,
		P.orderid,
		P.QTY 
FROM	@tb P

IF ((SELECT COUNT (*) FROM #tempTable) > 0)
BEGIN	
	SELECT  @KTypeId= STUFF((SELECT ',' + KTypeId FROM #tempTable ORDER BY nID ASC FOR XML PATH('')),1,1,'')
	SELECT  @PTypeId= STUFF((SELECT ',' + PTypeId FROM #tempTable ORDER BY nID ASC FOR XML PATH('')),1,1,'')
	SELECT  @orderids= STUFF((SELECT ',' + OrderId FROM #tempTable ORDER BY nID ASC FOR XML PATH('')),1,1,'')
	SELECT  @QTYs= STUFF((SELECT ',' + cast(QTY AS varchar) FROM #tempTable ORDER BY nID ASC FOR XML PATH('')),1,1,'')
END

INSERT INTO #VirtualGoodsStocks
(
	PTypeId,
	KTypeId,
	ProduceDate,
	ValidDate,
	ItemID,
	GoodsNumber,
	CargoID,
	GoodsCostPrice,
	Qty,
	RQty,
	CQty,
	SaleOrderQty,
	BuyOrderQty
) 
EXEC Web_QueryVirtualStockByConfig @OperatorID,@PTypeId,@KTypeId,@BillNumberId,@billtype,@orderids,@QTYs

DECLARE @CJoinSQL VARCHAR(100)='',@GroupSQL VARCHAR(100)='',@VJoinSQL VARCHAR(100)='',@RGroupSQL VARCHAR(100)='',@SelectSQL VARCHAR(100)='',@RSelectSQL VARCHAR(100)='',
		@Gcurrentdraftsql varchar(100)=''
--判断是否手工指定
DECLARE @COST VARCHAR(10)=''
SELECT @COST=SubValue FROM SYSDATA WHERE SUBNAME='costing'
IF(@COST='3')--手工指定
BEGIN
	IF @BILLTYPE NOT IN(72,87)
	BEGIN
		SET @CJoinSQL=' AND C.GoodsCostPrice = R.GoodsCostPrice '
		SET @VJoinSQL=' AND V.GoodsCostPrice = R.GoodsCostPrice '
	END
	IF @BILLTYPE NOT IN(87)
	begin
		SET @GroupSQL=',GoodsCostPrice'
		SET @SelectSQL='GoodsCostPrice,'
	END
	
	--SET @GroupSQL=',GoodsCostPrice'
	SET @RGroupSQL=',R.GoodsCostPrice'
	--SET @SelectSQL='GoodsCostPrice,'
	SET @RSelectSQL='R.GoodsCostPrice,'
	SET @Gcurrentdraftsql=',b.GoodsCostPrice'
END	

--单据调入草稿，虚拟库存需要加上本草稿的库存
CREATE TABLE #currentDraftQTY
(
	PTypeId			VARCHAR(100),
	KTypeId			VARCHAR(100),
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	ItemID			INT,
	GoodsNumber		VARCHAR(100),
	CargoID			INT,
	GoodsCostPrice	  NUMERIC(24,10),
	currentDraftQTY	NUMERIC(24, 10) 
)
DECLARE @referFlag INT=0,@referOrder INT=0
IF @orderids<>'-1' AND @BillNumberId<>-1 AND @BILLTYPE NOT IN (300,301,313)
BEGIN
	SET @referFlag=1
	IF @needReferOrder=1 AND(SELECT count(*) FROM #TEMPTABLE WHERE ptypeID IN (SELECT PTYPEID FROM #TEMPTABLE WHERE ORDERID='-1') AND ORDERID<>'-1')>0  AND (SELECT count(*) FROM #TEMPTABLE WHERE ORDERID='-1')>0
	BEGIN
		IF @BILLTYPE<>12 
		BEGIN
			declare @temporderid varchar(50)='-1',@tempqty NUMERIC(24, 10)=0;
			SELECT @temporderid=ORDERID FROM #TEMPTABLE WHERE ptypeID IN (SELECT PTYPEID FROM #TEMPTABLE WHERE ORDERID='-1') AND ORDERID<>'-1'
			SELECT @tempqty=SUM(qty) FROM #TEMPTABLE WHERE ptypeID IN (SELECT PTYPEID FROM #TEMPTABLE WHERE ORDERID='-1') AND ORDERID<>'-1' GROUP BY ORDERID
			IF (SELECT count(*) FROM OrderBill WHERE OrderID=@temporderid AND qty>=@tempqty)>0
			BEGIN
				SET @referOrder=0
			END
			ELSE
				SET @referOrder=1
		END
		ELSE IF @BILLTYPE=12
		BEGIN
			SET @referOrder=0
		END
		ELSE
			SET @referOrder=1
	END
END

DECLARE @auditFlag INT=0
DECLARE @auditreferFlag INT=0
declare @audittempsql NVARCHAR(MAX)
DECLARE @auditdeliFlag INT=0
IF @BillNumberId<>-1
BEGIN
	SELECT @auditFlag=count(*) FROM BillIndex WHERE BillNumberId=@BillNumberId AND draft=0 AND ifcheck='t'
	SELECT @auditdeliFlag=count(*) FROM dbo.PosAllotApplyBillIndex WHERE BillNumberId=@BillNumberId AND draft=0 AND ifcheck='t'
	IF @BillNumberId<>-1 AND @billtype NOT IN (300,301,313) AND @orderids<>'-1'
	BEGIN		
		DECLARE @BILLTableName VARCHAR(100),	--明细表名
			@OrderTableName VARCHAR(100)='OrderBill'	--订单明细表名
		IF @BillType=12
		BEGIN
			SET @OrderTableName='PT_Combin_OrderBillDetail'
		END
		SELECT @BILLTableName=detailTable FROM dbo.BillName WHERE Billtype=@BillType
		
		SET @audittempsql = 'SELECT @a=COUNT(*) FROM ' + @OrderTableName + ' A WHERE A.ORDERID IN (SELECT ORDERID FROM ' + @BILLTableName + ' WHERE BillNumberId =  ' + @BillNumberID + ') and OrderID IN('+@orderids+')'
		EXEC sp_executesql @audittempsql,N'@a int output',@auditreferFlag output
		IF @auditreferFlag>0
		BEGIN
			SET @auditreferFlag=1
		END
	END
END

--加上本草稿的库存
IF @needDraftFlag=1 AND EXISTS(SELECT 1 FROM dbo.Userconfig WHERE ConfigName ='VirtualQtySQL' AND (Value LIKE '%rqty%' OR Value LIKE '%cqty%'))
BEGIN
	SET @Value = @Value + ' + ISNULL(currentDraftQTY,0) '

	DECLARE @TEMPSQL VARCHAR(8000),@TableName VARCHAR(50),@cargoid VARCHAR(50),@InorOUT VARCHAR(50)='',@wxproperty varchar(50)=''
	SELECT  @TableName=DBO.F_BillTableName(@billtype)
	IF  @BillNumberId <> -1 AND @billtype <> -1 AND @billtype IN (11,12,140,402) AND @referOrder=0
	BEGIN	
		SET @cargoid='b.CargoID'
		
		SET @TEMPSQL='
		INSERT INTO #currentDraftQTY
		SELECT	b.ptypeid,
				b.ktypeid ,
				b.ProduceDate,
				b.ValidDate,
				b.ItemID,
				b.GoodsNumber,
				'+@cargoid+',
				CASE WHEN '+@COST+'=''3'' THEN b.GoodsCostPrice ELSE -1  END,
				SUM(ISNULL(B.Qty,0)) AS currentDraftQTY
		FROM 	BillIndex a 
		INNER JOIN '+@TableName+' b ON a.BillNumberId = b.BillNumberId
		WHERE a.BillNumberId = '+@BillNumberId+' AND (b.orderid=-1 or '+CAST(@referFlag AS varchar)+'=1) AND ((a.draft = 1 AND b.DraftFlag = 1)OR ('+CAST(@auditFlag AS varchar)+'=1 or '+cast(@auditreferFlag AS varchar)+'=1)) '+@InorOUT+' 
		GROUP BY b.ptypeid,b.ktypeid,b.ProduceDate,b.ValidDate,b.ItemID,b.GoodsNumber,'+@cargoid+''+@Gcurrentdraftsql+''	
		
		--PRINT(@TEMPSQL)
		EXEC (@TEMPSQL)	
	END	
	ELSE IF @BillNumberId <> -1 AND @billtype <> -1 AND @billtype NOT IN (11,12,140,402,300,301,313,87,72)
	BEGIN
		--同价调拨单、变价调拨单，货位ID取值outcargoid
		IF @billtype IN (17,21,187)
		BEGIN
			SET @cargoid='b.OutCargoID'
		END
		ELSE IF @billtype IN (327)
		BEGIN
		     SET @cargoid='b.CargoIDOut'
		END
		ELSE
		BEGIN
			SET @cargoid='b.CargoID'
		END
		--销售换货单取出库数量
		IF @billtype IN (160,166,172)
		BEGIN
			SET @InorOUT=' AND b.InOrOut=''O'' '
		END
		--维修单据
		IF @billtype IN (166,168,172)
		BEGIN
			SET @wxproperty=' AND b.wxProperty=0 '
		END 
		IF @billtype IN (327)
		BEGIN
			SET @TEMPSQL='
		INSERT INTO #currentDraftQTY
		SELECT	b.ptypeid,
				b.ktypeidout ,
				b.ProduceDate,
				b.ValidDate,
				b.ItemID,
				b.GoodsNumber,
				'+@cargoid+',
				CASE WHEN '+@COST+'=''3'' THEN b.GoodsCostPrice ELSE -1  END,
				SUM(ISNULL(B.Qty,0)) AS currentDraftQTY
		FROM 	PosAllotApplyBillIndex a 
		INNER JOIN '+@TableName+' b ON a.BillNumberId = b.BillNumberId
		WHERE a.BillNumberId = '+@BillNumberId+' AND ((a.draft = 1 )OR ('+CAST(@auditdeliFlag AS varchar)+'=1)) 
		GROUP BY b.ptypeid,b.ktypeidout,b.ProduceDate,b.ValidDate,b.ItemID,b.GoodsNumber,'+@cargoid+''+@Gcurrentdraftsql+''
		END
		ELSE 
		SET @TEMPSQL='
		INSERT INTO #currentDraftQTY
		SELECT	b.ptypeid,
				b.ktypeid ,
				b.ProduceDate,
				b.ValidDate,
				b.ItemID,
				b.GoodsNumber,
				'+@cargoid+',
				CASE WHEN '+@COST+'=''3'' THEN b.GoodsCostPrice ELSE -1  END,
				SUM(ISNULL(B.Qty,0)) AS currentDraftQTY
		FROM 	BillIndex a 
		INNER JOIN '+@TableName+' b ON a.BillNumberId = b.BillNumberId
		WHERE a.BillNumberId = '+@BillNumberId+' AND ((a.draft = 1 AND b.DraftFlag = 1)OR ('+CAST(@auditFlag AS varchar)+'=1)) '+@InorOUT+''+@wxproperty+' 
		GROUP BY b.ptypeid,b.ktypeid,b.ProduceDate,b.ValidDate,b.ItemID,b.GoodsNumber,'+@cargoid+''+@Gcurrentdraftsql+''	

		EXEC (@TEMPSQL)	
	END	
	ELSE IF @BillNumberId <> -1 AND @billtype <> -1 AND @billtype IN (72,87)
	BEGIN
		SET @cargoid='b.CargoID'
		
		SET @TEMPSQL='
		INSERT INTO #currentDraftQTY
		SELECT	b.ptypeid,
				a.ktypeid ,
				b.ProduceDate,
				b.ValidDate,
				b.ItemID,
				b.GoodsNumber,
				'+@cargoid+',
				 -1,
				SUM(abs(ISNULL(B.Qty,0))) AS currentDraftQTY
		FROM 	LendIndex a 
		INNER JOIN '+@TableName+' b ON a.BillNumberId = b.BillNumberId
		WHERE a.BillNumberId = '+@BillNumberId+' AND ((a.draft = 1)OR ('+CAST(@auditFlag AS varchar)+'=1))
		GROUP BY b.ptypeid,a.ktypeid,b.ProduceDate,b.ValidDate,b.ItemID,b.GoodsNumber,'+@cargoid+''	

		EXEC (@TEMPSQL)	
	END	
END
	

--最终数据
CREATE TABLE #OrderLastResult
(
	PTypeId			VARCHAR(100),
	KTypeId			VARCHAR(100),
	ProduceDate		VARCHAR(50),
	ValidDate		VARCHAR(50),
	itemname		VARCHAR(500),
	GoodsNumber		VARCHAR(100),
	cargofullname	VARCHAR(200),
	BillQty			NUMERIC(24, 10), 
	Qty				NUMERIC(24, 10), 
	BorrowQty		NUMERIC(24, 10), 
	LendQty			NUMERIC(24, 10), 
	RQty			NUMERIC(24, 10), 
	CQty			NUMERIC(24, 10), 
	SaleOrderQty	NUMERIC(24, 10),
	BuyOrderQty		NUMERIC(24, 10),
	currentDraftQTY		NUMERIC(24, 10),
	vqty				NUMERIC(24, 10)
)

IF ((SELECT [Value] FROM Userconfig WHERE ConfigName='VirtualInventoryJudgment')=1)
 OR ((SELECT [Value] FROM Userconfig WHERE ConfigName='VirtualInventoryJudgment')=2)
BEGIN
	--判断维度：商品+仓库
	IF ((SELECT [Value] FROM Userconfig WHERE ConfigName='VirtualInventoryJudgment')=1)
	BEGIN
	SET @SQL = 'SELECT	R.*,
						' + @Value + ' AS vqty
				FROM	(				
							SELECT	R.PTypeId,
									R.KTypeId,
									'''' AS ProduceDate,
									'''' AS ValidDate,
									'''' AS itemname,
									'''' AS goodsnumber,
									'''' AS cargofullname,
									ISNULL(SUM(R.BillQty),0) AS BillQty,
									ISNULL(SUM(R.Qty),0) AS Qty,
									ISNULL(SUM(R.BorrowQty),0) AS BorrowQty,
									ISNULL(SUM(R.LendQty),0) AS LendQty,		
									ISNULL(SUM(R.RQty),0) AS RQty,
									ISNULL(SUM(R.CQty),0) AS CQty,
									ISNULL(SUM(R.SaleOrderQty),0) AS SaleOrderQty,
									ISNULL(SUM(R.BuyOrderQty),0) AS BuyOrderQty,
									ISNULL(SUM(R.currentDraftQTY),0) AS currentDraftQTY		--当前草稿库存需要加上
							FROM    (		
										SELECT	R.PTypeId,
												R.KTypeId,
												'''' AS ProduceDate,
												'''' AS ValidDate,
												0 AS ItemID,
												'''' AS goodsnumber,
												0 AS CargoID,
												'+@RSelectSQL+'
												ISNULL(SUM(R.Qty),0) AS BillQty,
												ISNULL(SUM(V.Qty),0) AS Qty,
												0 AS LendQty,
												0 AS BorrowQty,
												ISNULL(SUM(V.RQty),0) AS RQty,
												ISNULL(SUM(V.CQty),0) AS CQty,
												ISNULL(SUM(V.SaleOrderQty),0) AS SaleOrderQty,
												ISNULL(SUM(V.BuyOrderQty),0) AS BuyOrderQty,								
												ISNULL(SUM(C.currentDraftQTY),0) AS currentDraftQTY
										FROM	#Result R
										LEFT JOIN (SELECT PTypeId,
														  KTypeId,
														  '+@SelectSQL+'
														  SUM(ISNULL(Qty,0)) AS Qty,
														  SUM(ISNULL(RQty,0)) AS RQty,
														  SUM(ISNULL(CQty,0)) AS CQty,
														  SUM(ISNULL(SaleOrderQty,0)) AS SaleOrderQty,
														  SUM(ISNULL(BuyOrderQty,0)) AS BuyOrderQty
													FROM #VirtualGoodsStocks GROUP BY PTypeId,KTypeId'+@GroupSQL+') V 
													ON V.PTypeId = R.PTypeId AND V.KTypeId = R.KTypeId '+@VJoinSQL+'
										LEFT JOIN (SELECT PTypeId,
														  KTypeId,
														  '+@SelectSQL+'
														  SUM(ISNULL(currentDraftQTY,0)) AS currentDraftQTY 
													FROM #currentDraftQTY GROUP BY PTypeId,KTypeId'+@GroupSQL+') C  
													ON C.PTypeId = R.PTypeId AND C.KTypeId = R.KTypeId'+@CJoinSQL+' 
										GROUP BY R.PTypeId,R.KTypeId'+@RGroupSQL+'
										UNION ALL
										SELECT	R.pTypeID,
												R.kTypeID,
												'''' AS ProduceDate,
												'''' AS ValidDate,
												0 AS ItemID,
												'''' AS goodsnumber,
												0 AS CargoID,
												'+@RSelectSQL+'
												0 AS BillQty, 
												0 AS Qty,
												SUM(V.Lend-V.LendBack-V.SALEQTY) AS Lendqty,
												SUM(V.Borrow-V.BorrowBack-V.BUYQTY) AS BorrowQty,
												0 AS RQty,
												0 As CQty,
												0 AS SaleOrderQty,
												0 AS BuyOrderQty,
												0 AS currentDraftQTY
										FROM	#Result R
										LEFT JOIN V_LendStatus V ON V.PTypeId = R.PTypeId AND V.KTypeId = R.KTypeId 
										GROUP BY R.pTypeID,R.kTypeID'+@RGroupSQL+'
							)R GROUP BY R.PTypeId,R.KTypeId'+@RGroupSQL+'
				)R
				WHERE	' + @Value + ' < ISNULL(BillQty,0) '
								
				--PRINT(@SQL)
				EXEC(@SQL);
	END
				
	--根据所有维度判断：商品+仓库+货位+自由项+批号+生产日期+效期至
	IF ((SELECT [Value] FROM Userconfig WHERE ConfigName='VirtualInventoryJudgment')=2)
	BEGIN
		--先清除商品+仓库的维度数据
		TRUNCATE TABLE #OrderLastResult
		
		SET @SQL = 'SELECT	R.*,
							' + @Value + ' AS vqty
					FROM	(
								SELECT	R.PTypeId,
										R.KTypeId,
										R.ProduceDate,
										R.ValidDate,
										CASE WHEN (SELECT COUNT(*) FROM CustomReferenceValue WHERE Id=R.ItemID)>0
										THEN ISNULL((SELECT REPLACE(FullName,''я'',''/'') FROM CustomReferenceValue WHERE Id=R.ItemID),'''') 
										ELSE ISNULL((SELECT FullName FROM xw_SelfData WHERE _Id=R.ItemID),'''') END AS itemname,
										ISNULL(R.GoodsNumber,'''') AS goodsnumber,
										ISNULL((SELECT FullName FROM CargoType WHERE CargoID=R.CargoID),'''') AS cargofullname,
										ISNULL(SUM(R.BillQty),0) AS BillQty,
										ISNULL(SUM(R.Qty),0) AS Qty,
										ISNULL(SUM(R.BorrowQty),0) AS BorrowQty,
										ISNULL(SUM(R.LendQty),0) AS LendQty,		
										ISNULL(SUM(R.RQty),0) AS RQty,
										ISNULL(SUM(R.CQty),0) AS CQty,
										ISNULL(SUM(R.SaleOrderQty),0) AS SaleOrderQty,
										ISNULL(SUM(R.BuyOrderQty),0) AS BuyOrderQty,
										ISNULL(SUM(R.currentDraftQTY),0) AS currentDraftQTY		--当前草稿库存需要加上
							FROM    (		
										SELECT	R.PTypeId,
												R.KTypeId,
												R.ProduceDate,
												R.ValidDate,
												R.ItemID,
												R.GoodsNumber,
												R.CargoID,
												'+@RSelectSQL+'
												ISNULL(SUM(R.Qty),0) AS BillQty,
												ISNULL(SUM(V.Qty),0) AS Qty,
												0 AS LendQty,
												0 AS BorrowQty,
												ISNULL(SUM(V.RQty),0) AS RQty,
												ISNULL(SUM(V.CQty),0) AS CQty,
												ISNULL(SUM(V.SaleOrderQty),0) AS SaleOrderQty,
												ISNULL(SUM(V.BuyOrderQty),0) AS BuyOrderQty,
												ISNULL(SUM(C.currentDraftQTY),0) AS currentDraftQTY
										FROM	#Result1 R
										LEFT JOIN (SELECT PTypeId,
														  KTypeId,
														  ProduceDate,
														  ValidDate,
														  ItemID,
														  GoodsNumber,
														  CargoID,
														 '+@SelectSQL+'
														  SUM(ISNULL(Qty,0)) AS Qty,
														  SUM(ISNULL(RQty,0)) AS RQty,
														  SUM(ISNULL(CQty,0)) AS CQty,
														  SUM(ISNULL(SaleOrderQty,0)) AS SaleOrderQty,
														  SUM(ISNULL(BuyOrderQty,0)) AS BuyOrderQty
													FROM #VirtualGoodsStocks GROUP BY PTypeId,KTypeId,ProduceDate,ValidDate,ItemID,GoodsNumber,CargoID'+@GroupSQL+') V 
													ON V.PTypeId = R.PTypeId AND V.KTypeId = R.KTypeId AND V.ProduceDate=R.ProduceDate AND V.ValidDate=R.ValidDate
													AND V.ItemID=R.ItemID AND V.GoodsNumber=R.GoodsNumber AND V.CargoID=R.CargoID '+@VJoinSQL+'
										LEFT JOIN (SELECT PTypeId,
														  KTypeId,
														  ProduceDate,
														  ValidDate,
														  ItemID,
														  GoodsNumber,
														  CargoID,
														 '+@SelectSQL+'
														  SUM(ISNULL(currentDraftQTY,0)) AS currentDraftQTY 
													FROM #currentDraftQTY GROUP BY PTypeId,KTypeId,ProduceDate,ValidDate,ItemID,GoodsNumber,CargoID'+@GroupSQL+') C  
													ON C.PTypeId = R.PTypeId AND C.KTypeId = R.KTypeId AND C.ProduceDate=R.ProduceDate AND C.ValidDate=R.ValidDate
													AND C.ItemID=R.ItemID AND C.GoodsNumber=R.GoodsNumber AND C.CargoID=R.CargoID '+@CJoinSQL+'
										WHERE R.ItemID<>0
										GROUP BY R.PTypeId,R.KTypeId,R.ProduceDate,R.ValidDate,R.ItemID,R.GoodsNumber,R.CargoID'+@RGroupSQL+'
										
										UNION ALL
										SELECT	R.PTypeId,
												R.KTypeId,
												R.ProduceDate,
												R.ValidDate,
												0,
												R.GoodsNumber,
												R.CargoID,
												'+@RSelectSQL+'
												ISNULL(SUM(R.Qty),0) AS BillQty,
												ISNULL(SUM(V.Qty),0) AS Qty,
												0 AS LendQty,
												0 AS BorrowQty,
												ISNULL(SUM(V.RQty),0) AS RQty,
												ISNULL(SUM(V.CQty),0) AS CQty,
												ISNULL(SUM(V.SaleOrderQty),0) AS SaleOrderQty,
												ISNULL(SUM(V.BuyOrderQty),0) AS BuyOrderQty,
												ISNULL(SUM(C.currentDraftQTY),0) AS currentDraftQTY
										FROM	#Result1 R
										LEFT JOIN (SELECT PTypeId,
														  KTypeId,
														  ProduceDate,
														  ValidDate,
														  GoodsNumber,
														  CargoID,
														 '+@SelectSQL+'
														  SUM(ISNULL(Qty,0)) AS Qty,
														  SUM(ISNULL(RQty,0)) AS RQty,
														  SUM(ISNULL(CQty,0)) AS CQty,
														  SUM(ISNULL(SaleOrderQty,0)) AS SaleOrderQty,
														  SUM(ISNULL(BuyOrderQty,0)) AS BuyOrderQty
													FROM #VirtualGoodsStocks GROUP BY PTypeId,KTypeId,ProduceDate,ValidDate,GoodsNumber,CargoID'+@GroupSQL+') V 
													ON V.PTypeId = R.PTypeId AND V.KTypeId = R.KTypeId AND V.ProduceDate=R.ProduceDate AND V.ValidDate=R.ValidDate
													AND V.GoodsNumber=R.GoodsNumber AND V.CargoID=R.CargoID '+@VJoinSQL+'
										LEFT JOIN (SELECT PTypeId,
														  KTypeId,
														  ProduceDate,
														  ValidDate,
														  GoodsNumber,
														  CargoID,
														 '+@SelectSQL+'
														  SUM(ISNULL(currentDraftQTY,0)) AS currentDraftQTY 
													FROM #currentDraftQTY GROUP BY PTypeId,KTypeId,ProduceDate,ValidDate,GoodsNumber,CargoID'+@GroupSQL+') C  
													ON C.PTypeId = R.PTypeId AND C.KTypeId = R.KTypeId AND C.ProduceDate=R.ProduceDate AND C.ValidDate=R.ValidDate
													AND C.GoodsNumber=R.GoodsNumber AND C.CargoID=R.CargoID '+@CJoinSQL+'	
										WHERE R.ItemID=0
										GROUP BY R.PTypeId,R.KTypeId,R.ProduceDate,R.ValidDate,R.GoodsNumber,R.CargoID'+@RGroupSQL+'

										UNION ALL
										SELECT	R.pTypeID,
												R.kTypeID,
												R.ProduceDate,
												R.ValidDate,
												R.ItemID,
												R.GoodsNumber,
												R.CargoID,
												'+@RSelectSQL+'
												0 AS BillQty, 
												0 AS Qty,
												SUM(V.Lend-V.LendBack-V.SALEQTY) AS Lendqty,
												SUM(V.Borrow-V.BorrowBack-V.BUYQTY) AS BorrowQty,
												0 AS RQty,
												0 As CQty,
												0 AS SaleOrderQty,
												0 AS BuyOrderQty,
												0 AS currentDraftQTY
										FROM	#Result1 R
										LEFT JOIN V_LendStatus V ON V.PTypeId = R.PTypeId AND V.KTypeId = R.KTypeId AND V.ProduceDate=R.ProduceDate AND V.ValidDate=R.ValidDate
													AND V.ItemID=R.ItemID AND V.GoodsNumber=R.GoodsNumber AND V.CargoID=R.CargoID
										GROUP BY R.PTypeId,R.KTypeId,R.ProduceDate,R.ValidDate,R.ItemID,R.GoodsNumber,R.CargoID'+@RGroupSQL+'
							)R GROUP BY R.PTypeId,R.KTypeId,R.ProduceDate,R.ValidDate,R.ItemID,R.GoodsNumber,R.CargoID'+@RGroupSQL+'
				)R 
				WHERE	' + @Value + ' < ISNULL(BillQty,0) '

				EXEC(@SQL);
	END
END
ELSE
BEGIN
	SELECT * FROM #OrderLastResult
END
--print(@SQL)
DROP TABLE #VirtualGoodsStocks,#Result,#Result1,#tempTable,#OrderLastResult,#currentDraftQTY

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCompleteDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCompleteDetails]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：
	日期：
	描述：
*/
CREATE PROCEDURE Web_QueryCompleteDetails
(
	@billnumberid			VARCHAR(200),		
	@billtype              int 
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE   @expensetoar INT
SELECT @expensetoar=SubValue FROM dbo.sysdata WHERE SubName='expensetoar'   ----费用单核算客户时计入应收  

----处理普通单据
SELECT  a.billnumberid ,
        a.BillDate ,
        a.BillCode ,
        a.BillType AS billtype ,
        a.etypeid ,
        CASE WHEN A.BILLTYPE IN ( 45, 46, 6, 149, 151, 148, 115, 129, 150 )
                  AND ( @billtype = 4
                        OR @billtype = 66
                      ) THEN -a.ntotalmoney
             ELSE a.ntotalmoney
        END AS ntotalmoney ,
        b.CompleteTotal ,
        b.goodsbillid ,
        a.billtype ,
        b.moneybillid ,
        ( SELECT    BillName
          FROM      dbo.BillName
          WHERE     Billtype = a.billtype
        ) AS billname ,
        b.ncompletetotal ,
        CASE WHEN EXISTS ( SELECT TOP 1
                                    1
                           FROM     completegoodtotal
                           WHERE    moneybillid = b.moneybillid
                                    AND goodsbillid = b.goodsbillid ) THEN 1
             ELSE 0
        END AS ifgoodsprocess ,
        a.Comment ,
        s.FullName AS sfullname ,
        e.FullName AS efullname ,
        pu.FullName ,
        a.npreferencemoney
FROM    (
			SELECT BillNumberId,BillDate,BillCode,CompleteTotal,NCompleteTotal,Comment,etypeid,totalmoney,NTotalMoney,Stypeid,CID,BillType,preferencemoney,NPreferenceMoney FROM dbo.BillIndex
			UNION ALL
			SELECT BillNumberId,BillDate,BillCode,CompleteTotal,NCompleteTotal,Comment,etypeid,totalmoney,NTotalMoney,STypeId,Cid,BillType,PreferenceMoney,NPreferenceMoney FROM dbo.Coupon_BillIndex
		) a
        INNER JOIN dbo.CompleteTotal b ON a.BillNumberId = b.GoodsBillID and a.BillType=b.BillType
        INNER JOIN dbo.SType s ON s.TypeId = a.Stypeid
        LEFT JOIN dbo.employee e ON e.typeId = a.etypeid
        INNER JOIN dbo.Ac_Currency pu ON pu.CId = a.CID
WHERE   MoneyBillID = @billnumberid
        AND A.BILLTYPE NOT IN ( 115, 116, 128, 129, 159,36 )
UNION ALL
----处理费用单

SELECT  a.billnumberid ,
        a.BillDate ,
        a.BillCode ,
        a.BillType AS billtype ,
        a.etypeid ,
        CASE WHEN @expensetoar=1 AND @billtype=4 THEN -a.ntotalmoney
             ELSE a.ntotalmoney
        END AS ntotalmoney ,
        b.CompleteTotal ,
        b.goodsbillid ,
        a.billtype ,
        b.moneybillid ,
        ( SELECT    BillName
          FROM      dbo.BillName
          WHERE     Billtype = a.billtype
        ) AS billname ,
        b.ncompletetotal ,
        CASE WHEN EXISTS ( SELECT TOP 1
                                    1
                           FROM     completegoodtotal
                           WHERE    moneybillid = b.moneybillid
                                    AND goodsbillid = b.goodsbillid ) THEN 1
             ELSE 0
        END AS ifgoodsprocess ,
        a.Comment ,
        s.FullName AS sfullname ,
        e.FullName AS efullname ,
        pu.FullName ,
        a.npreferencemoney
FROM    dbo.BillIndex a
        INNER JOIN dbo.CompleteTotal b ON a.BillNumberId = b.GoodsBillID and a.BillType=b.BillType
        INNER JOIN dbo.SType s ON s.TypeId = a.Stypeid
        LEFT JOIN dbo.employee e ON e.typeId = a.etypeid
        INNER JOIN dbo.Ac_Currency pu ON pu.CId = a.CID
WHERE   MoneyBillID = @billnumberid
        AND A.BILLTYPE =36       
UNION ALL
-----特殊处理 应收增加、应收减少、单应付增加、应付减少
SELECT  a.billnumberid ,
        a.BillDate ,
        a.BillCode ,
        a.BillType AS billtype ,
        a.etypeid ,
               CASE WHEN A.BILLTYPE IN ( 45, 6, 149, 151, 148, 115, 129, 150)
                  AND ( @billtype = 4
                        OR @billtype = 66
                      ) THEN -ad.NTotal
             ELSE ad.NTotal
        END AS ntotalmoney ,
        b.CompleteTotal ,
        b.goodsbillid ,
        a.billtype ,
        b.moneybillid ,
        ( SELECT    BillName
          FROM      dbo.BillName
          WHERE     Billtype = a.billtype
        ) AS billname ,
        b.ncompletetotal ,
        CASE WHEN EXISTS ( SELECT TOP 1
                                    1
                           FROM     completegoodtotal
                           WHERE    moneybillid = b.moneybillid
                                    AND goodsbillid = b.goodsbillid ) THEN 1
             ELSE 0
        END AS ifgoodsprocess ,
        a.Comment ,
        s.FullName AS sfullname ,
        e.FullName AS efullname ,
        pu.FullName ,
        a.npreferencemoney
FROM    dbo.BillIndex a
        INNER JOIN dbo.CompleteTotal b ON a.BillNumberId = b.GoodsBillID and a.BillType=b.BillType
        LEFT JOIN addebtbill ad ON b.GoodsBillID = ad.BillNumberId
                                   AND b.GoodsBillDetailID = ad.ID
        INNER JOIN dbo.SType s ON s.TypeId = a.Stypeid
        LEFT JOIN dbo.employee e ON e.typeId = a.etypeid
        INNER JOIN dbo.Ac_Currency pu ON pu.CId = a.CID
WHERE   MoneyBillID = @billnumberid
        AND A.BillType IN ( 115, 116, 128, 129 )
UNION ALL
SELECT  a.billnumberid ,
        a.BillDate ,
        a.BillCode ,
        a.BillType AS billtype ,
        a.etypeid ,
       CASE WHEN A.BILLTYPE IN ( 45, 6, 149, 151, 148, 115, 129, 150)
                  AND ( @billtype = 4
                        OR @billtype = 66
                      ) THEN -ad.NJ_Total
             ELSE ad.NJ_Total
        END AS ntotalmoney ,
        b.CompleteTotal ,
        b.goodsbillid ,
        a.billtype ,
        b.moneybillid ,
        ( SELECT    BillName
          FROM      dbo.BillName
          WHERE     Billtype = a.billtype
        ) AS billname ,
        b.ncompletetotal ,
        CASE WHEN EXISTS ( SELECT TOP 1
                                    1
                           FROM     completegoodtotal
                           WHERE    moneybillid = b.moneybillid
                                    AND goodsbillid = b.goodsbillid ) THEN 1
             ELSE 0
        END AS ifgoodsprocess ,
        a.Comment ,
        s.FullName AS sfullname ,
        e.FullName AS efullname ,
        pu.FullName ,
        a.npreferencemoney
FROM    dbo.BillIndex a
        INNER JOIN dbo.CompleteTotal b ON a.BillNumberId = b.GoodsBillID and a.BillType=b.BillType
        LEFT JOIN accountcredence ad ON b.GoodsBillID = ad.BillNumberId
                                        AND b.GoodsBillDetailID = ad.ID
        INNER JOIN dbo.SType s ON s.TypeId = a.Stypeid
        LEFT JOIN dbo.employee e ON e.typeId = a.etypeid
        INNER JOIN dbo.Ac_Currency pu ON pu.CId = a.CID
WHERE   MoneyBillID = @billnumberid
        AND A.BillType = 159
 
 union all
 --发票
 SELECT  a.billnumberid ,
        a.BillDate ,
        a.BillCode ,
        a.BillType AS billtype ,
        a.etypeid ,
        a.NTaxTotalMoney AS ntotalmoney ,
        b.CompleteTotal ,
        b.goodsbillid ,
        a.billtype ,
        b.moneybillid ,
        ( SELECT    BillName
          FROM      dbo.BillName
          WHERE     Billtype = a.billtype
        ) AS billname ,
        b.ncompletetotal ,
        CASE WHEN EXISTS ( SELECT TOP 1
                                    1
                           FROM     completegoodtotal
                           WHERE    moneybillid = b.moneybillid
                                    AND goodsbillid = b.goodsbillid ) THEN 1
             ELSE 0
        END AS ifgoodsprocess ,
        a.Comment ,
        s.FullName AS sfullname ,
        e.FullName AS efullname ,
        pu.FullName ,
        0 as npreferencemoney
FROM    dbo.ReceiptBillIndex a
        INNER JOIN dbo.CompleteTotal b ON a.BillNumberId = b.GoodsBillID and a.BillType=b.BillType
        INNER JOIN dbo.SType s ON s.TypeId = a.Stypeid
        LEFT JOIN dbo.employee e ON e.typeId = a.etypeid
        INNER JOIN dbo.Ac_Currency pu ON pu.CId = a.CID
WHERE   MoneyBillID = @billnumberid
        AND A.BILLTYPE IN ( 404,405 )

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCompleteTotalBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCompleteTotalBill]
GO

/*
	作者：谢吉康
	日期：2004-12-07
	描述：查询按单结算的单据
	
	作者：覃雨翔
	日期：2012-06-07
	描述：查询按单结算的单据9.0版本修改 
	
	修改：舒珊
	日期：2016年2月25日
	描述：增添表头自定义显示字段
	
	修改：梁晰
	日期：2016年11月25日
	描述：修改查询未结算单据时判断
	
	修改：颜熙
	日期：2017年11月22日
	描述：增加优惠券出库单、退货单结算、优惠券入库单分析
*/
CREATE PROCEDURE Web_QueryCompleteTotalBill
(
	@OperatorId		VARCHAR(100),				--超作员的ID
	@StartDate		VARCHAR(20),				--开始日期
	@EndDate		VARCHAR(20),				--结束日期
	@ETypeId		VARCHAR(8000),				--经手人ID
	@GBTypeId		VARCHAR(8000),				--往来单位的ID
	@STypeId		VARCHAR(8000),				--分支机构
	@KTypeId		VARCHAR(8000),				--仓库ID
	@BillCode		VARCHAR(256),				--单据编号
	@radCx			INT,						--查询的方式     0.收款单据类型		1.付款单据类型
	@radJs			INT,						--结算方式		 0.已结算完成单据	1.未结算完单据 2.全部收款单据 3.停止收款的单据
	@BillTypeId		VARCHAR(200),				--单据类型的ID
	@OrderField		VARCHAR(100)='BillDate',	--排序的字段
	@OrderType		VARCHAR(20)='ASC',			--排序方式  1.升序  0.降序
	@CID            INT=0,                      --币别，默认为0.表示所有币种
	@Btype          VARCHAR(100),
	@IncludeQc      INT=0                       --是否包含期初单据，默认为0不包含期初单据
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @BTypeId 	VARCHAR(8000),	--往来单位ID
		@SQL 		VARCHAR(8000)	--SQL字符串

IF @GBTypeId = '00000'
	SET @BTypeId = '%'
ELSE
	SET @BTypeId = @GBTypeId

--职员
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
IF NOT (@ETypeId = '' AND @METypeId = '00001')
	INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
IF NOT (@GBTypeId = '%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	BEGIN
		INSERT INTO #GetManBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S
	END
IF @BTypeId='%' OR @GBTypeId=''
	INSERT INTO #GetManBTypeId(TypeId)VALUES('')
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)		

--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
IF NOT (@KTypeId = '' AND @MKTypeId = '00000')
	INSERT INTO #GetManKTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)		

DECLARE @CIDWhere VARCHAR(MAX)


CREATE TABLE #BillIndex
(
	BillNumberId		NUMERIC(18,0),
	did                 int,
	TotalInMoney		 NUMERIC(24, 10) ,
	NTotalInMoney		 NUMERIC(24, 10) ,
	CompleteTotal		 NUMERIC(24, 10) ,
	NCompleteTotal		 NUMERIC(24, 10) ,
	BillDate			DATETIME,
	BillCode			VARCHAR(400),
	BillType			INT,
	Comment				VARCHAR(400),
	ETypeId				VARCHAR(100),
	BTypeId				VARCHAR(100),
	STypeId				VARCHAR(100),
	TotalMoney			 NUMERIC(24, 10) ,
	NTotalMoney			 NUMERIC(24, 10) ,
	TotalJsMoney		 NUMERIC(24, 10) ,
	NTotalJsMoney		 NUMERIC(24, 10) ,
	TotalWjsMoney		 NUMERIC(24, 10) ,
	NTotalWjsMoney		 NUMERIC(24, 10) ,
	preferencemoney		 NUMERIC(24, 10) ,
	npreferencemoney	 NUMERIC(24, 10) ,
	IfStopMoney			VARCHAR(20),
	jsState				VARCHAR(20),
	cfullname           VARCHAR(100),
	rate               	 NUMERIC(24, 10),
	ChargeOffTotal		NUMERIC(24,10),
	nChargeOffTotal		NUMERIC(24,10) 
)

IF @CID<>0
  BEGIN
       SET @CIDWhere=' AND BillIndex.CID='+CONVERT(VARCHAR,@CID)
  END
ELSE
  BEGIN
       SET @CIDWhere=''
  END

SET @SQL = 'INSERT INTO #BillIndex
			SELECT	BillNumberId,
			        0,
					TotalInMoney,-- 0
					NTotalInMoney,-- 0
					CompleteTotal,--明细
					NCompleteTotal,--明细
					BillDate,
					BillCode,
					BillType,		
					Comment,
					ETypeId,
					BTypeId,--明细
					STypeId,
					ISNULL(TotalMoney,0) AS TotalMoney,--total
					ISNULL(NTotalMoney,0) AS NTotalMoney,--ntotal
					ISNULL(TotalInMoney,0) + ISNULL(CompleteTotal,0) AS TotalJsMoney,
					ISNULL(NTotalInMoney,0)+ISNULL(NCompleteTotal,0) AS NTotalJsMoney,
					ISNULL(TotalMoney,0) - ISNULL(TotalInMoney,0) - ISNULL(CompleteTotal,0) - ISNULL(preferencemoney,0)-ChargeOffTotal 
					 AS TotalWjsMoney,
					
					ISNULL(NTotalMoney,0) - ISNULL(NTotalInMoney,0) - ISNULL(NCompleteTotal,0) - ISNULL(Npreferencemoney,0)-nChargeOffTotal 
					 AS NTotalWjsMoney,
					
					ISNULL(preferencemoney,0) AS preferencemoney,
					ISNULL(npreferencemoney,0) AS npreferencemoney,
					ISNULL(IfStopMoney,0) AS IfStopMoney,--明细
					ISNULL(jsState,0) AS jsState,
					AC.fullname AS cfullname,
					AC.rate,
					isnull(ChargeOffTotal,0),
					isnull(nChargeOffTotal,0)			
			FROM 	BillIndex  
			INNER JOIN AC_currency AC ON BillIndex.CID=AC.CID '

IF NOT (@ETypeId = '' AND @METypeId = '00001')
	SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.TypeId = BillIndex.ETypeId'

IF NOT (@BTypeId = '%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON B.TypeId = BillIndex.BTypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '		

IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId '

SET @SQL = @SQL + '
			WHERE	BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND BillDate<='+CHAR(39)+@EndDate+CHAR(39)
IF @radJs = 0 OR @radJs = 1
	SET @SQL = @SQL + ' AND IfStopMoney LIKE ''0'''
ELSE IF @radJs = 2
	 SET @SQL = @SQL + ' AND IfStopMoney LIKE ''%'''
ELSE 
	SET @SQL = @SQL + ' AND IfStopMoney LIKE ''1'''

IF @radCx=0--收款类
    SET @SQL = @SQL + ' AND (billtype<>450 or (billtype=450 and ChargeOffType in(2,5) ) ) 	AND BillType NOT IN(4)  '
ELSE
	SET @SQL = @SQL + ' AND (billtype<>450 or (billtype=450 and ChargeOffType in(3,4) ) )'
    
    

DECLARE @isiniWhere VARCHAR(100)
SET @isiniWhere=''
 IF @IncludeQc=1
   BEGIN
        SET @isiniWhere=' OR isini=1'
   END
 ELSE
   BEGIN
        SET @isiniWhere=' AND isini<>1'
   END
   
SET @SQL = @SQL + ' AND ((RedWord = 0 AND Draft = 0) '+@isiniWhere+' )
					AND BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
					AND BillType NOT IN(115,116,128,129) 
					AND BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
					
SET @SQL=@SQL+@CIDWhere+' AND ((BillIndex.BillType=36 AND BillIndex.BtypeId LIKE '+CHAR(39)+@Btype+CHAR(39)+') OR BillIndex.BillType<>36 )'

IF NOT (@KTypeId = '' AND @MKTypeId = '00000')
	BEGIN
		IF @KTypeId <> ''
			BEGIN
				SET @SQL = @SQL + ' AND (KTypeId IN (SELECT * FROM #GetManKTypeId) OR KTypeId2 IN (SELECT * FROM #GetManKTypeId))
									AND KTypeId <> ''10000''
									AND BillType NOT IN (186)'
			END
		ELSE
			BEGIN
				SET @SQL = @SQL + '	AND ((KTypeId IN (SELECT * FROM #GetManKTypeId) OR ISNULL(KTypeId,'''')=''10000'') 
									OR (KTypeId2 IN (SELECT * FROM #GetManKTypeId) OR ISNULL(KTypeId2,'''')=''10000'')
									OR (KTypeId='''' AND KTypeId2=''''))'

			END
	END

--PRINT(@SQL)
--RETURN


--应收应付单

SET @SQL = @SQL + 'INSERT INTO #BillIndex
				SELECT	BillIndex.BillNumberId,
				    ab.id as did,
					0 as TotalInMoney,-- 0
					0 as NTotalInMoney,-- 0
					ab.CompleteTotal,--明细
					ab.NCompleteTotal,--明细
					BillDate,
					BillCode,
					BillType,		
					ab.Comment,
					ETypeId,
					ab.BTypeId,--明细
					ab.STypeId,
					ISNULL(ab.total,0) AS TotalMoney,--total
					ISNULL(ab.ntotal,0) AS NTotalMoney,--ntotal
					ISNULL(ab.CompleteTotal,0) AS TotalJsMoney,
					ISNULL(ab.NCompleteTotal,0) AS NTotalJsMoney,
					ISNULL(ab.total,0)  - ISNULL(ab.CompleteTotal,0) -ab.ChargeOffTotal 
					 AS TotalWjsMoney,
					
					ISNULL(ab.ntotal,0) - ISNULL(ab.NCompleteTotal,0) - ab.nChargeOffTotal 
					 AS NTotalWjsMoney,
					
				    0 AS preferencemoney,
					0 AS npreferencemoney,
					ISNULL(ab.IfStopMoney,0) AS IfStopMoney,--明细
					ISNULL(ab.jsState,0) AS jsState,
					AC.fullname AS cfullname,
					AC.rate,
					isnull(ab.ChargeOffTotal,0),
					isnull(ab.nChargeOffTotal,0)			
			FROM 	BillIndex  
			INNER JOIN AC_currency AC ON BillIndex.CID=AC.CID 
			INNER JOIN addebtbill  ab ON BillIndex.BillNumberId=ab.BillNumberId 
			'
			

IF NOT (@ETypeId = '' AND @METypeId = '00001')
	SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.TypeId = BillIndex.ETypeId'

IF NOT (@BTypeId = '%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON B.TypeId = ab.BTypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON ab.STypeId = S.TypeId '		

IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId '

SET @SQL = @SQL + '
			WHERE	BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND BillDate<='+CHAR(39)+@EndDate+CHAR(39)

IF @radJs = 0 OR @radJs = 1
	SET @SQL = @SQL + ' AND ab.IfStopMoney LIKE ''0'''
ELSE IF @radJs = 2
	 SET @SQL = @SQL + ' AND ab.IfStopMoney LIKE ''%'''
ELSE 
	SET @SQL = @SQL + ' AND ab.IfStopMoney LIKE ''1'''


DECLARE @isiniWhereBySF VARCHAR(100)
SET @isiniWhereBySF=''
 IF @IncludeQc=1
   BEGIN
        SET @isiniWhereBySF=' OR isini=1'
   END
 ELSE
   BEGIN
        SET @isiniWhereBySF=' AND isini<>1'
   END
   
SET @SQL = @SQL + ' AND ((RedWord = 0 AND Draft = 0) '+@isiniWhereBySF+' )
					AND BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
					AND BillType IN(115,116,128,129) 
				    AND BillType NOT IN(4)
					AND BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
					
SET @SQL=@SQL+@CIDWhere

EXEC(@SQL)
--应收应付单

--优惠券出库单
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	BillNumberId,
					0 as did, 
					TotalInMoney,
					NTotalInMoney,
					CompleteTotal,
					NCompleteTotal,
					BillDate,
					BillCode,
					BillType,		
					Coupon_BillIndex.Comment,
					Coupon_BillIndex.ETypeId,
					BTypeId,
					STypeId,
					ISNULL(TotalMoney,0) AS TotalMoney,
					ISNULL(NTotalMoney,0) AS NTotalMoney,
					ISNULL(TotalInMoney,0) + ISNULL(CompleteTotal,0) AS TotalJsMoney,
					ISNULL(NTotalInMoney,0)+ISNULL(NCompleteTotal,0) AS NTotalJsMoney,
					ISNULL(TotalMoney,0) - ISNULL(TotalInMoney,0) - ISNULL(CompleteTotal,0)-ISNULL(ChargeOffTotal,0)- ISNULL(preferencemoney,0)
					 AS TotalWjsMoney,
					
					ISNULL(NTotalMoney,0) - ISNULL(NTotalInMoney,0) - ISNULL(NCompleteTotal,0) - ISNULL(nChargeOffTotal,0) -ISNULL(Npreferencemoney,0)
					 AS NTotalWjsMoney,
				
					ISNULL(preferencemoney,0) AS preferencemoney,
					ISNULL(npreferencemoney,0) AS npreferencemoney,
					0 AS IfStopMoney,
					ISNULL(jsState,0) AS jsState,
					AC.fullname AS cfullname,
					AC.rate,
					isnull(ChargeOffTotal,0),
					isnull(nChargeOffTotal,0)			
			FROM 	Coupon_BillIndex
			INNER JOIN AC_currency AC ON Coupon_BillIndex.CID=AC.CID 
			INNER JOIN BType Bt ON Bt.TypeId = Coupon_BillIndex.DealBTypeID
			'

IF NOT (@ETypeId = '' AND @METypeId = '00001')
	SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.TypeId = Coupon_BillIndex.ETypeId'

--IF NOT (@BTypeId = '%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON B.TypeId = Coupon_BillIndex.BTypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Coupon_BillIndex.STypeId = S.TypeId '		

IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Coupon_BillIndex.DTypeId '

SET @SQL = @SQL + '
			WHERE	BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND BillDate<='+CHAR(39)+@EndDate+CHAR(39)


    
 IF @IncludeQc=1
   BEGIN
        SET @isiniWhere=' OR isini=1'
   END
 ELSE
   BEGIN
        SET @isiniWhere=' AND isini<>1'
   END
   
SET @SQL = @SQL + ' AND ((RedWord = 0 AND Draft = 0) '+@isiniWhere+' )
					AND BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
					AND BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
					
SET @SQL=@SQL+REPLACE(@CIDWhere,'BillIndex.CID','Coupon_BillIndex.CID')+' AND ((Coupon_BillIndex.BillType=424 AND Coupon_BillIndex.BtypeId LIKE '+CHAR(39)+@Btype+CHAR(39)+'))'

IF NOT (@KTypeId = '' AND @MKTypeId = '00000')
	BEGIN
		IF @KTypeId <> ''
			BEGIN
				SET @SQL = @SQL + ' AND (InKTypeId IN (SELECT * FROM #GetManKTypeId) OR OutKTypeId IN (SELECT * FROM #GetManKTypeId))
									AND InKTypeId <> ''10000''
									AND BillType IN (424)'
			END
		ELSE
			BEGIN
				SET @SQL = @SQL + '	AND ((InKTypeId IN (SELECT * FROM #GetManKTypeId) OR ISNULL(InKTypeId,'''')=''10000'') 
									OR (OutKTypeId IN (SELECT * FROM #GetManKTypeId) OR ISNULL(OutKTypeId,'''')=''10000'')
									OR (InKTypeId='''' AND OutKTypeId=''''))'

			END
	END
	

	--IF @radJs = 0 OR @radJs = 1
	--	SET @SQL = @SQL + ' AND JsState LIKE ''0'''
	--ELSE IF @radJs = 2
	--	 SET @SQL = @SQL + ' AND JsState LIKE ''%'''
	--ELSE 
	--	SET @SQL = @SQL + ' AND JsState LIKE ''1'''
	--PRINT @SQL
EXEC(@SQL)


--优惠券出库单


--优惠券退货单
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	BillNumberId,
					0 as did,
					TotalInMoney,
					NTotalInMoney,
					CompleteTotal,
					NCompleteTotal,
					BillDate,
					BillCode,
					BillType,		
					Coupon_BillIndex.Comment,
					Coupon_BillIndex.ETypeId,
					BTypeId,
					STypeId,
					-ISNULL(TotalMoney,0) AS TotalMoney,
					-ISNULL(NTotalMoney,0) AS NTotalMoney,
					-(ISNULL(TotalInMoney,0) + ISNULL(CompleteTotal,0)) AS TotalJsMoney,
					-(ISNULL(NTotalInMoney,0)+ISNULL(NCompleteTotal,0)) AS NTotalJsMoney,
					-(ISNULL(TotalMoney,0) - ISNULL(TotalInMoney,0) - ISNULL(CompleteTotal,0)-ISNULL(ChargeOffTotal,0)-ISNULL(Npreferencemoney,0)) 
					 AS TotalWjsMoney,
					
					-(ISNULL(NTotalMoney,0) - ISNULL(NTotalInMoney,0) - ISNULL(NCompleteTotal,0) -ISNULL(nChargeOffTotal,0)-ISNULL(Npreferencemoney,0)) 
					 AS NTotalWjsMoney,
					
				    -preferencemoney,
					-npreferencemoney,
					0 AS IfStopMoney,
					ISNULL(jsState,0) AS jsState,
					AC.fullname AS cfullname,
					AC.rate,
					-isnull(ChargeOffTotal,0),
					-isnull(nChargeOffTotal,0)			
			FROM 	Coupon_BillIndex  
			INNER JOIN AC_currency AC ON Coupon_BillIndex.CID=AC.CID '

IF NOT (@ETypeId = '' AND @METypeId = '00001')
	SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.TypeId = Coupon_BillIndex.ETypeId'

SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON B.TypeId = Coupon_BillIndex.BTypeId'
SET @SQL = @SQL + '	INNER JOIN BType BB ON BB.TypeId = Coupon_BillIndex.BTypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Coupon_BillIndex.STypeId = S.TypeId '		

IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Coupon_BillIndex.DTypeId '

SET @SQL = @SQL + '
			WHERE	Coupon_BillIndex.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND Coupon_BillIndex.BillDate<='+CHAR(39)+@EndDate+CHAR(39)


    
 IF @IncludeQc=1
   BEGIN
        SET @isiniWhere=' OR isini=1'
   END
 ELSE
   BEGIN
        SET @isiniWhere=' AND isini<>1'
   END
   
SET @SQL = @SQL + ' AND ((Coupon_BillIndex.RedWord = 0 AND Coupon_BillIndex.Draft = 0) '+@isiniWhere+' )
					AND Coupon_BillIndex.BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
					AND Coupon_BillIndex.BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
					
SET @SQL=@SQL+REPLACE(@CIDWhere,'BillIndex.CID','Coupon_BillIndex.CID')+' AND ((Coupon_BillIndex.BillType=426 AND Coupon_BillIndex.BtypeId LIKE '+CHAR(39)+@Btype+CHAR(39)+'))'

IF NOT (@KTypeId = '' AND @MKTypeId = '00000')
	BEGIN
		IF @KTypeId <> ''
			BEGIN
				SET @SQL = @SQL + ' AND (InKTypeId IN (SELECT * FROM #GetManKTypeId) OR OutKTypeId IN (SELECT * FROM #GetManKTypeId))
									AND InKTypeId <> ''10000''
									AND BillType IN (426)'
			END
		ELSE
			BEGIN
				SET @SQL = @SQL + '	AND ((InKTypeId IN (SELECT * FROM #GetManKTypeId) OR ISNULL(InKTypeId,'''')=''10000'') 
									OR (OutKTypeId IN (SELECT * FROM #GetManKTypeId) OR ISNULL(OutKTypeId,'''')=''10000'')
									OR (InKTypeId='''' AND OutKTypeId=''''))'

			END
	END

	--IF @radJs = 0 OR @radJs = 1
	--	SET @SQL = @SQL + ' AND JsState LIKE ''0'''
	--ELSE IF @radJs = 2
	--	 SET @SQL = @SQL + ' AND JsState LIKE ''%'''
	--ELSE 
	--	SET @SQL = @SQL + ' AND JsState LIKE ''1'''

--print (@SQL)
EXEC(@SQL)

--优惠券入库单
SET @SQL = 'INSERT INTO #BillIndex
			SELECT	BillNumberId,
					0 as did,
					TotalInMoney,
					NTotalInMoney,
					CompleteTotal,
					NCompleteTotal,
					BillDate,
					BillCode,
					BillType,		
					Coupon_BillIndex.Comment,
					Coupon_BillIndex.ETypeId,
					BTypeId,
					STypeId,
					ISNULL(TotalMoney,0) AS TotalMoney,
					ISNULL(NTotalMoney,0) AS NTotalMoney,
					ISNULL(TotalInMoney,0) + ISNULL(CompleteTotal,0) AS TotalJsMoney,
					ISNULL(NTotalInMoney,0)+ISNULL(NCompleteTotal,0) AS NTotalJsMoney,
					ISNULL(TotalMoney,0) - ISNULL(TotalInMoney,0) - ISNULL(CompleteTotal,0)- ISNULL(ChargeOffTotal,0)-ISNULL(Npreferencemoney,0) 
					 AS TotalWjsMoney,
					
					ISNULL(NTotalMoney,0) - ISNULL(NTotalInMoney,0) - ISNULL(NCompleteTotal,0) - ISNULL(nChargeOffTotal,0)-ISNULL(Npreferencemoney,0)
					 AS NTotalWjsMoney,
					
					preferencemoney,
					npreferencemoney,
					0 AS IfStopMoney,
					ISNULL(jsState,0) AS jsState,
					AC.fullname AS cfullname,
					AC.rate,
					isnull(ChargeOffTotal,0),
					isnull(nChargeOffTotal,0)			
			FROM 	Coupon_BillIndex  
			INNER JOIN AC_currency AC ON Coupon_BillIndex.CID=AC.CID '

IF NOT (@ETypeId = '' AND @METypeId = '00001')
	SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.TypeId = Coupon_BillIndex.ETypeId'

SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON B.TypeId = Coupon_BillIndex.BTypeId'
SET @SQL = @SQL + '	INNER JOIN BType BB ON BB.TypeId = Coupon_BillIndex.BTypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Coupon_BillIndex.STypeId = S.TypeId '		

IF NOT @MDtypeId = '00000'
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = Coupon_BillIndex.DTypeId '

SET @SQL = @SQL + '
			WHERE	Coupon_BillIndex.BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
					AND Coupon_BillIndex.BillDate<='+CHAR(39)+@EndDate+CHAR(39)


    
 IF @IncludeQc=1
   BEGIN
        SET @isiniWhere=' OR isini=1'
   END
 ELSE
   BEGIN
        SET @isiniWhere=' AND isini<>1'
   END
   
SET @SQL = @SQL + ' AND ((RedWord = 0 AND Draft = 0) '+@isiniWhere+' )
					AND BillType IN (SELECT * FROM F_Split('+CHAR(39)+@BillTypeId+CHAR(39)+','',''))
					AND BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
					
SET @SQL=@SQL+REPLACE(@CIDWhere,'BillIndex.CID','Coupon_BillIndex.CID')+' AND ((Coupon_BillIndex.BillType=423 AND Coupon_BillIndex.BtypeId LIKE '+CHAR(39)+@Btype+CHAR(39)+'))'

IF NOT (@KTypeId = '' AND @MKTypeId = '00000')
	BEGIN
		IF @KTypeId <> ''
			BEGIN
				SET @SQL = @SQL + ' AND (InKTypeId IN (SELECT * FROM #GetManKTypeId) OR OutKTypeId IN (SELECT * FROM #GetManKTypeId))
									AND InKTypeId <> ''10000''
									AND BillType IN (423)'
			END
		ELSE
			BEGIN
				SET @SQL = @SQL + '	AND ((InKTypeId IN (SELECT * FROM #GetManKTypeId) OR ISNULL(InKTypeId,'''')=''10000'') 
									OR (OutKTypeId IN (SELECT * FROM #GetManKTypeId) OR ISNULL(OutKTypeId,'''')=''10000'')
									OR (InKTypeId='''' AND OutKTypeId=''''))'

			END
	END

	--IF @radJs = 0 OR @radJs = 1
	--	SET @SQL = @SQL + ' AND JsState LIKE ''0'''
	--ELSE IF @radJs = 2
	--	 SET @SQL = @SQL + ' AND JsState LIKE ''%'''
	--ELSE 
	--	SET @SQL = @SQL + ' AND JsState LIKE ''1'''

--print (@SQL)
EXEC(@SQL)


----发票数据
IF exists(select * from sysdata where SubValue='1' and SubName='IsInvoice')
begin
	SET @SQL = 'INSERT INTO #BillIndex
			SELECT	b.BillNumberId,
			        0,
					0 as TotalInMoney,
					0 as NTotalInMoney,
					b.CompleteTotal,
					b.NCompleteTotal,
					b.BillDate,
					b.BillCode,
					b.BillType,		
					b.Comment,
					b.ETypeId,
					b.BTypeId,
					b.STypeId,
					ISNULL(b.TaxTotalMoney,0) AS TotalMoney,
					ISNULL(b.NTaxTotalMoney,0) AS NTotalMoney,
					ISNULL(b.CompleteTotal,0) AS TotalJsMoney,
					ISNULL(b.NCompleteTotal,0) AS NTotalJsMoney,
					
					 ISNULL(b.TaxTotalMoney,0) - ISNULL(b.CompleteTotal,0)-ChargeOffTotal
					 AS TotalWjsMoney,
					
					 ISNULL(b.NTaxTotalMoney,0) - ISNULL(b.NCompleteTotal,0)  -nChargeOffTotal
					 AS NTotalWjsMoney,
					0 AS preferencemoney,
					0 AS npreferencemoney,
					ISNULL(b.IfStopMoney,0) AS IfStopMoney,
					ISNULL(b.jsState,0) AS jsState,
					AC.fullname AS cfullname,
					AC.rate	,
					isnull(ChargeOffTotal,0),
					isnull(nChargeOffTotal,0)			
			FROM 	ReceiptBillIndex b  
			INNER JOIN AC_currency AC ON b.CID=AC.CID '

	IF NOT (@ETypeId = '' AND @METypeId = '00001')
		SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.TypeId = b.ETypeId'

	IF NOT (@BTypeId = '%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B1 ON B1.TypeId = b.BTypeId'
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON b.STypeId = S.TypeId '		

	IF NOT @MDtypeId = '00000'
		SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = b.DTypeId '

	SET @SQL = @SQL + '
				WHERE	BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
						AND BillDate<='+CHAR(39)+@EndDate+CHAR(39)
	IF @radJs = 0 OR @radJs = 1
		SET @SQL = @SQL + ' AND IfStopMoney LIKE ''0'''
	ELSE IF @radJs = 2
		 SET @SQL = @SQL + ' AND IfStopMoney LIKE ''%'''
	ELSE 
		SET @SQL = @SQL + ' AND IfStopMoney LIKE ''1'''

	   
	SET @SQL = @SQL + ' AND ((RedWord = 0 AND Draft = 0) '+@isiniWhere+' )
						AND BillType IN ('+@BillTypeId+')
						AND BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)
						
	SET @SQL=@SQL+' AND (b.cid='+CONVERT(VARCHAR,@CID)+' or '+CONVERT(VARCHAR,@CID)+'=0)'
	EXEC (@SQL)
END
--PRINT(@SQL)

--return
--------------------发票end
/*CASE WHEN   ((ABS(ISNULL(totalmoney, 0))  -abs(ISNULL(CompleteTotal, 0)+ISNULL(totalinmoney, 0)+ISNULL(preferencemoney,0)))<=0 AND BillType NOT IN (160,161))
									 or (BillType IN (160,161) AND jsState = ''2'')
							 THEN ''已结算''	
						CASE WHEN   ((ABS(ISNULL(totalmoney, 0))  -abs(ISNULL(CompleteTotal, 0)+ISNULL(totalinmoney, 0)+ISNULL(preferencemoney,0)))>0 AND BillType NOT IN (160,161))
									 or (BillType IN (160,161) AND jsState <> ''2'')
							 THEN ''未结算完单据''*/
IF @radJs IN( 0,1,3)
	SET @SQL = 'SELECT 	BillNumberId,
	                    did,
						BillDate,
						BillCode,
						BillType,
						Comment,
						ETypeId,
						BTypeId,
						STypeId,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(TotalMoney,0)
						     ELSE ISNULL(TotalMoney,0) 
						END AS TotalMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(NTotalMoney,0)
						     ELSE ISNULL(NTotalMoney,0) 
					    END	AS NTotalMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(TotalJsMoney,0)
					         ELSE ISNULL(TotalJsMoney,0)
					    END AS TotalJsMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(NTotalJsMoney,0)
					         ELSE ISNULL(NTotalJsMoney,0)
					    END AS NTotalJsMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(TotalWjsMoney,0)
					         ELSE ISNULL(TotalWjsMoney,0)
						END AS TotalWjsMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(NTotalWjsMoney,0)
						     ELSE ISNULL(NTotalWjsMoney,0)
						END AS NTotalWjsMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(preferencemoney,0)
						     ELSE ISNULL(preferencemoney,0)
						END AS preferencemoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(npreferencemoney,0)
						     ELSE ISNULL(npreferencemoney,0)
						END AS npreferencemoney,
						CASE WHEN jsState=2 THEN  ''已结算''
							 ELSE   ''未结算完单据''
						   END
						AS state,
						cfullname,
						rate,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(ChargeOffTotal,0)
						     ELSE ISNULL(ChargeOffTotal,0) 
						END AS ChargeOffTotal,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(nChargeOffTotal,0)
						     ELSE ISNULL(nChargeOffTotal,0) 
					    END	AS nChargeOffTotal
				FROM 	#BillIndex 
				WHERE 	(IfStopMoney = 0 or '+CONVERT(VARCHAR,@radJs)+'=3) 
						AND ( ('+CONVERT(VARCHAR,@radJs)+'=0  and jsState=2)
								OR ('+CONVERT(VARCHAR,@radJs)+'=1  and jsState<>2 AND  (ISNULL(TotalMoney,0) - ISNULL(TotalInMoney,0) - ISNULL(CompleteTotal,0) - ISNULL(preferencemoney,0)) != 0)
								OR ('+CONVERT(VARCHAR,@radJs)+'=3 AND IfStopMoney=1))			 
						'
ELSE IF @radJs = 2
BEGIN
	SET @SQL = 'SELECT 	BillNumberId,
	                    did,
						BillDate,
						BillCode,
						BillType,
						Comment,
						ETypeId,
						BTypeId,
						STypeId,
							CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(TotalMoney,0)
						     ELSE ISNULL(TotalMoney,0) 
						END AS TotalMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(NTotalMoney,0)
						     ELSE ISNULL(NTotalMoney,0) 
					    END	AS NTotalMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(TotalJsMoney,0)
					         ELSE ISNULL(TotalJsMoney,0)
					    END AS TotalJsMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(NTotalJsMoney,0)
					         ELSE ISNULL(NTotalJsMoney,0)
					    END AS NTotalJsMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(TotalWjsMoney,0)
					         ELSE ISNULL(TotalWjsMoney,0)
						END AS TotalWjsMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(NTotalWjsMoney,0)
						     ELSE ISNULL(NTotalWjsMoney,0)
						END AS NTotalWjsMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(preferencemoney,0)
						     ELSE ISNULL(preferencemoney,0)
						END AS preferencemoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(npreferencemoney,0)
						     ELSE ISNULL(npreferencemoney,0)
						END AS npreferencemoney,
						CASE WHEN jsState=2 THEN  ''已结算''
							 ELSE   ''未结算完单据''
						   END
						AS state,
						cfullname,
						rate,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(ChargeOffTotal,0)
						     ELSE ISNULL(ChargeOffTotal,0) 
						END AS ChargeOffTotal,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(nChargeOffTotal,0)
						     ELSE ISNULL(nChargeOffTotal,0) 
					    END	AS nChargeOffTotal
				FROM 	#BillIndex
				WHERE IfStopMoney = 0 '
	SET @SQL=@SQL+' UNION ALL 
	                      SELECT BillNumberId,
	                                 did,
	                                 BillDate,
	                                 BillCode,
	                                 BillType,
	                                 Comment,
	                                 EtypeId,
	                                 BtypeId,
	                                 StypeId,
	                 		CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(TotalMoney,0)
						     ELSE ISNULL(TotalMoney,0) 
						END AS TotalMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(NTotalMoney,0)
						     ELSE ISNULL(NTotalMoney,0) 
					    END	AS NTotalMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(TotalJsMoney,0)
					         ELSE ISNULL(TotalJsMoney,0)
					    END AS TotalJsMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(NTotalJsMoney,0)
					         ELSE ISNULL(NTotalJsMoney,0)
					    END AS NTotalJsMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(TotalWjsMoney,0)
					         ELSE ISNULL(TotalWjsMoney,0)
						END AS TotalWjsMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(NTotalWjsMoney,0)
						     ELSE ISNULL(NTotalWjsMoney,0)
						END AS NTotalWjsMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(preferencemoney,0)
						     ELSE ISNULL(preferencemoney,0)
						END AS preferencemoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(npreferencemoney,0)
						     ELSE ISNULL(npreferencemoney,0)
						END AS npreferencemoney,
						             ''停止收款'' AS State,
						             cfullname,
						             rate,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(ChargeOffTotal,0)
						     ELSE ISNULL(ChargeOffTotal,0) 
						END AS ChargeOffTotal,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(nChargeOffTotal,0)
						     ELSE ISNULL(nChargeOffTotal,0) 
					    END	AS nChargeOffTotal
						      FROM #BillIndex
						      WHERE IfStopMoney = 1 AND BillType IN (11,45,141,148,149,93,85,160,167,168,172,178,186,195,196,200,179,181,312,182,213,12,46,424,426)'
    SET @SQL=@SQL+' UNION ALL 
	                      SELECT BillNumberId,
	                                 did,
	                                 BillDate,
	                                 BillCode,
	                                 BillType,
	                                 Comment,
	                                 EtypeId,
	                                 BtypeId,
	                                 StypeId,
	                    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(TotalMoney,0)
						     ELSE ISNULL(TotalMoney,0) 
						END AS TotalMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(NTotalMoney,0)
						     ELSE ISNULL(NTotalMoney,0) 
					    END	AS NTotalMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(TotalJsMoney,0)
					         ELSE ISNULL(TotalJsMoney,0)
					    END AS TotalJsMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(NTotalJsMoney,0)
					         ELSE ISNULL(NTotalJsMoney,0)
					    END AS NTotalJsMoney,
					    CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
					         THEN -ISNULL(TotalWjsMoney,0)
					         ELSE ISNULL(TotalWjsMoney,0)
						END AS TotalWjsMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(NTotalWjsMoney,0)
						     ELSE ISNULL(NTotalWjsMoney,0)
						END AS NTotalWjsMoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(preferencemoney,0)
						     ELSE ISNULL(preferencemoney,0)
						END AS preferencemoney,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(npreferencemoney,0)
						     ELSE ISNULL(npreferencemoney,0)
						END AS npreferencemoney,
						             ''停止付款'' AS State,
						             cfullname,
						             rate,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(ChargeOffTotal,0)
						     ELSE ISNULL(ChargeOffTotal,0) 
						END AS ChargeOffTotal,
						CASE WHEN BillType=36 AND '+CONVERT(VARCHAR,@radCx)+'=0
						     THEN -ISNULL(nChargeOffTotal,0)
						     ELSE ISNULL(nChargeOffTotal,0) 
					    END	AS nChargeOffTotal
						      FROM #BillIndex
						      WHERE IfStopMoney = 1 AND BillType IN (34,6,145,151,150,36,84,161,170,212,414,423)
						     '
END

SET @SQL ='SELECT P.*,
					SysDiy1_head,
					SysDiy2_head,
					SysDiy3_head,
					SysDiy4_head, 
					SysDiy5_head,
					SysDiy6_head,
					SysDiy7_head,
					SysDiy8_head,
					SysDiy9_head,
					SysDiy10_head,
					SysDiy11_head,
					SysDiy12_head,
					SysDiy13_head,
					SysDiy14_head,
					SysDiy15_head,
					SysDiy16_head,
					SysDiy17_head,
					SysDiy18_head,
					SysDiy19_head,
					SysDiy20_head,
					SysDiy21_head,
					SysDiy22_head,
					SysDiy23_head,
					SysDiy24_head,
					SysDiy25_head,
					SysDiy26_head,
					SysDiy27_head,
					SysDiy28_head,
					SysDiy29_head,
					SysDiy30_head,
					SysDiy31_head,
					SysDiy32_head,
					SysDiy33_head,
					SysDiy34_head,
					SysDiy35_head,
					SysDiy36_head,
					SysDiy37_head,
					SysDiy38_head,
					SysDiy39_head,
					SysDiy40_head
	 FROM ('+@SQL+')P
	 LEFT JOIN Custom_BillIndex csindex on P.billnumberid=csindex.BillId and P.billtype=csindex.billtype '
	 +' ORDER BY '+ @OrderField + ' ' +@OrderType
	 
--RETURN
EXEC(@SQL)

DROP TABLE #BillIndex,#GetManETypeId,#GetManBTypeId,#GetManSTypeId,#GetManDTypeId --,#GetManKTypeId








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryContinuousPrintBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryContinuousPrintBill
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	修改者：韩林
	日期：2012-02-01
	描述：连续打印查询明细
*/

CREATE PROCEDURE Web_QueryContinuousPrintBill
(
	@billnumberids varchar(max),
	@eid varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON
	
SELECT	N.BillName AS billtypename,
		a.BillType,
		a.billnumberid,
		a.Stypeid,
		a.tax,
		E.FullName AS checkename,
		a.billdate,
		a.BillCode,
		a.etypeid,
		a.dtypeid,
		a.btypeid,
		a.DealBTypeID,
		(select fullname from btype where typeId=a.DealBTypeID) as dealbname,
		(select fullname from Ac_Currency where CId=a.cid) as cname,
		a.Rate,
		a.ktypeid,
		a.ktypeid2,
		case a.alertday when 9999 then null else CAST(a.alertday as varchar(4))+' 天' end as alertday,
		a.explain,
		a.comment,
		a.waybillcode,
		a.goodsnumber,
		a.packway,
		a.tel,
		a.ntotalmoney,
		cast (cast (a.ntotalinmoney as  NUMERIC(24, 10) ) as varchar(40)) as ntotalinmoney,
		a.npreferencemoney as npreference,
		a.npreferencemoney,
		cast (a.ntotalmoney-a.npreferencemoney as varchar(50)) as afterpreference,
		a.stypeid,
		cast(a.costsale as int) as costsale,
		--case a.costsale when 0 then '×' else '√' end as costsale,
		a.totalqty,
		a.otherinouttype,
		a.ifmulaccount,
		a.sharemode,
		a.posbilltype,
		ISNull(au.BillDetail,'') AS BillDetail,
		CASE
			WHEN a.IfMulAccount = 1 THEN '-99999'
			ELSE ISNULL(a.atypeid,'')
		END AS nid,
		CASE ISNULL(b.price,0) WHEN 0 THEN 1 ELSE b.price END AS saleprice,
		CASE ISNULL(b.buyprice,0) WHEN 0 THEN 1 ELSE b.buyprice END AS buyprice,
		a.UF1,
		a.UF2,
		a.UF3,
		a.UF4,
		a.UF5,
		a.DealBTypeID,
		b1.FullName as	dealbname,
		a.Rate,
		a.cid,
		(select FullName from Ac_Currency where CID=a.CID) as cidname,
		(select fullname from Ac_Account where TypeId=a.ATypeID1 and STypeID=a.stypeid) as atypeid1name,
		a.IfCargo as ifcargo,
	    dbo.F_GetAc_Items(a.billnumberid,@eid) as atypeidname,
	    (select FullName from employee where typeId= a.updateE) as updateename,
	    (select FullName from employee where typeId= a.TallyId) as tallyer,
	    (select fullname from btype where typeId='00000') as '公司全名',
	    (select usercode from btype where typeId='00000') as '公司编号',
	    (select person from btype where typeId='00000') as '联系人',
	    (select telandaddress from btype where typeId='00000') as '地址',
	    (select tel1 from btype where typeId='00000') as '电话',
	    (select postcode from btype where typeId='00000') as '邮编',
	    (select taxnumber from btype where typeId='00000') as '税号',
	    (select bank from btype where typeId='00000') as '开户银行',
	    (select bankandacount from btype where typeId='00000') as '公司账号',
	    (select comment from btype where typeId='00000') as '公司备注'
	  
FROM BillIndex a
INNER JOIN employee E ON E.typeId=A.checke
INNER JOIN BillName N ON N.Billtype=A.BillType
LEFT JOIN AuditingBill au	ON (au.billnumberid=a.billnumberid AND Au.BillIndexType = 2)
LEFT JOIN atype ON a.atypeid = atype.typeid
LEFT JOIN btype b ON a.btypeid = b.typeId
LEFT JOIN btype b1 ON a.DealBTypeID = b1.typeId
LEFT JOIN OtherInOutType OT ON OT.ID=A.OtherInOutType
WHERE a.BillNumberId IN (select * from f_split(@billnumberids,','))
Order By  a.Billdate desc,a.posttime desc 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryContinuousPrintDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryContinuousPrintDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	修改者：韩林
	日期：2012-02-01
	描述：连续打印查询明细
*/

CREATE PROCEDURE Web_QueryContinuousPrintDetail
(
	@billnumberids varchar(max),
	@BillType	varchar(max)
)
--@encode$--
AS
SET NOCOUNT ON





SELECT	 a.ID,
         a.billnumberid,
         bindex.billtype,
		--Qty =
		--	CASE WHEN a.isUnit2 = 1 THEN
		--		CASE WHEN b.UnitRate1 <> 0 THEN
		--			CAST( a.Qty/b.UnitRate1 AS  NUMERIC(24, 10)  ) 
		--		ELSE a.Qty END 
		--	ELSE a.Qty END,
		BigQty =
			CASE WHEN b.UnitRate1 = 0 THEN
				a.Qty
			ELSE CAST(a.Qty/b.UnitRate1 AS  NUMERIC(24, 10) ) END,
		Price =
			CASE WHEN a.isUnit2 = 1 AND b.UnitRate1 <> 0 THEN
				 CAST(a.SalePrice * b.UnitRate1 AS  NUMERIC(24, 10) ) 
			ELSE a.SalePrice END,
		a.tax,
		
		DiscountPrice =
			CASE WHEN a.isUnit2 = 1 AND b.UnitRate1 <> 0 THEN
				CAST(a.DiscountPrice * b.UnitRate1 AS  NUMERIC(24, 10) )
			ELSE a.DiscountPrice END,
		CAST(a.total as varchar(50)) AS total,
		TaxPrice =
			CASE WHEN a.isUnit2 = 1 AND b.UnitRate1 <> 0 THEN
				 CAST(a.TaxPrice * b.UnitRate1 AS  NUMERIC(24, 10) )
			ELSE a.TaxPrice END,
			  CAST(a.TaxTotal as varchar(50)) AS TaxTotal,
		
		  CAST(a.total as varchar(50)) AS discounttotal,
		
		a.SaleTotal,
		a.InputCostPrice,
		a.GoodsCostPrice as goodsnumberprice,
		isnull(a.sharefee,0) as sharefee,
		accountqty=isnull((select sum(qty) from GoodsStocks where ktypeid=a.ktypeid and ptypeid=a.ptypeid),0),
		a.KtypeId,
		a.Comment AS base,
		IsUnit2 = CASE WHEN a.IsUnit2 = 1 AND b.UnitRate1 <> 0 THEN a.IsUnit2
					ELSE 0 END,
		ISNULL(a.serial,'''') AS serial,
		b.typeid as ptypeid,
		b.UserCode,
		b.FullName,
		b.UnitRate1,
		b.EntryCode,
		b.Unit1,
		b.Standard,
		b.Type,
		b.Area,
		b.SerialCount,
		b.ValidDays,
		b.IfSerial,
		b.usefullifeday,
		a.HandZeroCost,
		a.saletotal,
		cast('' as varchar(50)) as unitrelation,
		cast('' as varchar(50)) as assistantunit,
		cast('' as varchar(50)) as assistantunit1,
		a.MQty,
	   CAST(CAST(a.CurMSalePrice as  NUMERIC(24, 10) ) as varchar(50)) AS CurMSalePrice,
	    CAST(CAST(a.NSaleTotal as  NUMERIC(24, 10) ) as varchar(50)) AS NSaleTotal,
		
		a.Qty,
		 CAST(CAST(a.NSalePrice as  NUMERIC(24, 10) ) as varchar(50)) AS NSalePrice,
		
		a.NQty,
	    cast (cast(a.discount as  NUMERIC(24, 10) ) as varchar(50)) as discount,
	     CAST(CAST(a.CurMDiscountPrice as  NUMERIC(24, 10) ) as varchar(50) ) AS CurMDiscountPrice,
	  
	  CAST(CAST(a.NTotal as  NUMERIC(24, 10) ) as varchar(50) ) AS NTotal,
	  
	    a.Tax,
	      CAST(CAST(a.CurMTaxPrice as  NUMERIC(24, 10) ) as varchar(50)) AS CurMTaxPrice,
	   cast(CAST(a.NTaxMoney as  NUMERIC(24, 10) ) as varchar(50)) AS NTaxMoney,
	   
	    CAST(CAST(a.NTaxTotal as  NUMERIC(24, 10) ) as varchar(50)) as NTaxTotal,
	  
	     CAST(a.SaleTotal as varchar(50)) as total,
	  
	   cast(CAST(a.TaxMoney as  NUMERIC(24, 10) ) as varchar(50)) as TaxMoney,
	   
	   CAST(a.TaxTotal as varchar(50)) as TaxTotal,
	    a.total as discounttotal,
	    a.GoodsNumber,
	    a.ProduceDate,
	    a.ValidDate,
		f.UnitsType,
		f.unitid,
		f.unit,
		a.unitrate,
		a.munitrate,
		a.PriceSource,
		f.nunitid,
		a.sharefee,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname1,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname2,
		(select fullname from PType_Units where UnitsId=(select SaleUnitID3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid)) as auxfullname3,
		(select SaleUnitRate1 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate1,
		(select SaleUnitRate2 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate2,
		(select SaleUnitRate3 from PType_AuxiliaryUnits_Ext where PTypeID=a.ptypeid) as auxrate3,
		(select FullName from PType_Units where  PType_Units.UnitsId=a.NUnitID) as nunit,
		f.rate,
		a.munitid,
		(select FullName from PType_Units where  PType_Units.UnitsId=a.munitid) as munit,
		f.salemunitrate,
		itemid=a.ItemId,
	    itemname= CASE WHEN a.IsCombined = 0  THEN
        (SELECT FullName FROM xw_SelfData WHERE _Id= a.ItemId)
         ELSE (SELECT REPLACE(FullName,'я','/') FROM CustomReferenceValue WHERE id= a.ItemId ) END,
	     iscombined=a.IsCombined,
	     (select FullName from CargoType where CargoID=a.CargoID) as cargospace,
	     (select SUM(qty-ReachQty) from orderbill where BillNumberId=a.BillNumberId) as nocompleteqty,
	     cast(bindex.costsale as int) as costsale
		
FROM	SaleBill a
INNER JOIN	dbo.PType b ON a.PTypeID = b.TypeID
INNER JOIN Billindex bindex ON bindex.BillNumberId=a.BillNumberId
LEFT  JOIN dbo.F_GetPtypeUnitInfo() f on f.typeid = b.typeid
WHERE a.BillNumberId IN (select * from f_split(@billnumberids,','))
ORDER BY a.ID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SysObjects WHERE ID=OBJECT_ID(N'Web_QueryConvertUnitPriceInfo',N'P'))
BEGIN
	DROP PROC Web_QueryConvertUnitPriceInfo
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*商品切换单位查询单位价格信息*/
CREATE PROC Web_QueryConvertUnitPriceInfo
(
	@UnitsID		INT=1,					--当前单位ID
	@InputPrice     NUMERIC(24,10),			--录入价格
	@PTypeID		VARCHAR(100)='',		--商品ID
	@CID			INT=1,					--币种 
	@STypeID		VARCHAR(100)='',		--分支机构
	@Btypeid		VARCHAR(100)='',		--结算单位
	@dealbtypeid	VARCHAR(100)='',		--往来单位
	@billtype		INT=-1,					--单据类型
	@ktypeid		VARCHAR(100)='',		--仓库ID
	@etypeid		VARCHAR(100)='',		--经手人
	@billdate		VARCHAR(20)='',			--单据日期
	@vipcardno		VARCHAR(100)=''			--会员卡号
)
AS
BEGIN
	DECLARE @PriceType			INT,				--价格类型
			@VipDiscountType	INT,				--会员卡折扣类型
			@VIpDiscount		NUMERIC(24,10),		--会员卡折扣
			@TrackTableName     VARCHAR(100)='',	--价格跟踪表
			@BuySaleType		INT	,				--采购、销售
			@SQL				NVARCHAR(MAX)='',	--SQL
			@ComputePriceSQL	NVARCHAR(MAX)='',	--价格计算SQL
			@VIPPriceSQL		NVARCHAR(MAX)='',	--会员卡价格SQL
			@PrePriceSQL		NVARCHAR(MAX)='',
			@BTypeFlag			INT,				--价格跟踪类型 0=结算单位,1=往来单位 -1=未启用
			@CalcMunitPrePriceByBaseWhenNone INT,	--计算大单位预设价格
			@STypeTrackTableName NVARCHAR(MAX)='',	--分支机构间价格跟踪表
			@showcostprice			NUMERIC(24,10)		--成本均价

	SET @vipcardno=ISNULL(@VipCardNO,'')
	SET @PTypeID=ISNULL(@PTypeID,'')
	SET @STypeID=ISNULL(@STypeID,'00000')
	SET @Btypeid=ISNULL(@Btypeid,'00000')
	SET @dealbtypeid=ISNULL(@dealbtypeid,'00000')
	SET @ktypeid=ISNULL(@ktypeid,'00000')
	SET @etypeid=ISNULL(@etypeid,'00000')
	SELECT @CalcMunitPrePriceByBaseWhenNone=Value FROM UserConfig WHERE ConfigName='CalcMunitPrePriceByBaseWhenNone'
	SELECT @showcostprice = ISNULL(CASE WHEN SUM(ISNULL(QTY,0)) = 0 THEN 0 ELSE CAST(SUM(ISNULL(Total,0)) AS NUMERIC(24,10)) / CAST(SUM(ISNULL(QTY,0)) AS NUMERIC(24,10)) END,0) FROM dbo.GoodsStocks WHERE PtypeId = @PTypeID AND KtypeId = @ktypeid
	
	CREATE TABLE #PriceTrack
	(
		PtypeId				varchar(50),
		DiscountTrack   NUMERIC(24, 10) ,			--价格跟踪扣率跟踪
		DiscountPriceTrack	  NUMERIC(24, 10) ,		--价格跟踪扣率跟踪
		PriceTrack	  NUMERIC(24, 10), 			--价格跟踪扣率跟踪
		TaxTrack	NUMERIC(24,10),				--税率跟踪
		TaxPriceTrack	NUMERIC(24,10),			--含税单价跟踪
		DiscountTrackStype   NUMERIC(24, 10) ,			--分支机构间价格跟踪扣率跟踪
		DiscountPriceTrackStype	  NUMERIC(24, 10) ,		--分支机构间价格跟踪扣率跟踪
		PriceTrackStype	  NUMERIC(24, 10), 			--分支机构间价格跟踪扣率跟踪
		TaxTrackStype	NUMERIC(24,10),				--分支机构间税率跟踪
		TaxPriceTrackStype	NUMERIC(24,10),			--分支机构间含税单价跟踪
		[UID]		INT,
		isbtypetrack	INT,
		pricetracksource INT
	);
	
	
	DECLARE @PriceTrackTableName	VARCHAR(50) 					--价格跟踪保存在哪一张表中(普通价格跟踪)
	DECLARE @StypePriceTrackTableName	VARCHAR(50) 				--价格跟踪保存在哪一张表中(分支机构价格跟踪)
	DECLARE @buysaleName			VARCHAR(30)='buypricetrack'		--采购或者销售价格跟踪参数名
	DECLARE @isBTypeTrack			INT = -1						--查询往来单位是否启用了价格跟踪
	DECLARE @stypePriceTrack_buy	INT =0							--采购类单据是否启用了分支机构价格跟踪
	DECLARE @stypePriceTrack_sale	INT =0							--销售类单据是否启用了分支机构价格跟踪
	DECLARE @IsOrdinaryPriceTrack	INT =0							--是否启用了普通价格跟踪:0未启用，1启用
	DECLARE @Track					VARCHAR(MAX)

	----------------------------------初始化相关参数  start ----------------------------------
	--普通价格跟踪表
	SELECT 
		@PriceTrackTableName=tracktablename,
		@buysaletype=buysaletype 
	FROM PriceTrackNameBillSet 
	WHERE billtype=@BillType and getsettype='2'

	--分支机构价格跟踪表
	SELECT 
	@StypePriceTrackTableName=tracktablename
	FROM PriceTrackNameBillSet 
	WHERE billtype=@BillType and getsettype='4'

	--如果询价单、采购订单、暂估入库单取价设置为取采购价格，则直接获取采购入库单的价格跟踪表名
	DECLARE @isGetBuyPriceTrack INT = 0
	SELECT @isGetBuyPriceTrack = [VALUE] FROM PriceTrackConfig WHERE Name=
	(
		CASE WHEN @BillType=185 THEN 'askpricetrack' WHEN @BillType=301 THEN 'buyorderpricetrack' 
		WHEN @BillType IN (400,401) THEN 'zangupricetrack' END
	)
	IF(@isGetBuyPriceTrack = 2 AND @BillType=185)
	BEGIN
		SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
		SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
	END
	IF(@isGetBuyPriceTrack = 2 AND @BillType=301)
	BEGIN
		SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
		SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
	END
	IF(@isGetBuyPriceTrack = 2 AND @BillType IN (400,401))
	BEGIN
		SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='2'
		SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=34 and getsettype='4'
	END

	--如果报价单、销售订单、发出商品出库单取价设置为取小数价格，则直接获取销售出库单的价格跟踪表名
	DECLARE @isGetSalePriceTrack INT = 0
	SELECT @isGetSalePriceTrack = [VALUE] FROM PriceTrackConfig WHERE Name=
	(
		CASE WHEN @BillType=184 THEN 'quotepricetrack' WHEN @BillType=300 THEN 'saleorderpricetrack' 
		WHEN @BillType IN (402,403) THEN 'fachupricetrack' END
	)
	IF(@isGetSalePriceTrack = 2 AND @BillType=184)
	BEGIN
		SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
		SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
	END
	IF(@isGetSalePriceTrack = 2 AND (@BillType=300 OR @BillType=300))
	BEGIN
		SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
		SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
	END
	IF(@isGetSalePriceTrack = 2 AND @BillType IN (402,403))
	BEGIN
		SELECT @PriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='2'
		SELECT @StypePriceTrackTableName = tracktablename FROM PriceTrackNameBillSet WHERE billtype=11 and getsettype='4'
	END
	
	IF @buysaletype =1 
	BEGIN
		SET @buysaleName='buypricetrack'
	END
	ELSE IF @buysaletype = 2
	BEGIN
		SET @buysaleName='salepricetrack'
	END
	
	SELECT @IsOrdinaryPriceTrack=VALUE FROM PriceTrackConfig WHERE NAME=@buysaleName
	SELECT @stypePriceTrack_buy=[value] FROM PriceTrackConfig WHERE NAME='buystypepricetrack'
	SELECT @stypePriceTrack_sale=[value] FROM PriceTrackConfig WHERE NAME='salestypepricetrack'

	IF @buysaletype=1
	BEGIN
		SELECT @btypeflag=value  FROM PriceTrackConfig WHERE name='BuyBtypeFlag'
	END
	ELSE IF	@buysaletype=2
	BEGIN	
		SELECT @btypeflag=value FROM PriceTrackConfig  WHERE name='SaleBtypeFlag'
	END

	--判断是否启用了结算单位价格跟踪
	IF @btypeflag = 0
	BEGIN
		SELECT @isBTypeTrack = PriceTrackEnable from BType WHERE typeid=@btypeid
	END
	--判断是否启用了往来单位价格跟踪
	ELSE IF @btypeflag = 1
	BEGIN
		SELECT @isBTypeTrack = PriceTrackEnable from BType WHERE typeid=@dealbtypeid
	END

	----------------------------------初始化相关参数  end -----------------------------------
	IF @isBTypeTrack = 1 AND @BillType IN ('11','12','34','300','313','301','6','45','46','305','140','141','142','160','161','144','145','146','187','188','184','185','215','400','401','402','403')
	BEGIN
		SET @SQL = 'INSERT INTO #PriceTrack 
		SELECT	t.PTypeId,
				SUM(t.DiscountRate) AS DiscountRate,
				SUM(t.DiscountPrice) AS DiscountPrice,
				SUM(t.Price) AS Price,
				SUM(t.tax) AS tax,
				SUM(t.TaxPrice) AS TaxPrice,
				SUM(t.DiscountRateStype) AS DiscountRateStype,
				SUM(t.DiscountPriceStype) AS DiscountPriceStype,
				SUM(t.PriceStype) AS PriceStype,
				SUM(t.taxStype) AS taxStype,
				SUM(t.TaxPriceStype) AS TaxPriceStype,
				t.[uid],
				'''+convert(varchar(2),@btypeflag)+''' as isbtypetrack,
				0 AS pricetracksource 
		FROM (
				SELECT 
				pt.PTypeId,
				pt.DiscountRate,
				pt.DiscountPrice,
				pt.Price,
				pt.tax,
				pt.TaxPrice,
				pt.[uid],
				0 as DiscountRateStype,
				0 as DiscountPriceStype,
				0 as PriceStype,
				0 as taxStype,
				0 as TaxPriceStype
				FROM '+ @PriceTrackTableName +' pt 
				WHERE 1=1 '+CASE WHEN @btypeflag=0 THEN ' 
				AND pt.BTypeID='''+@btypeid +'''' ELSE ' 
				AND pt.BTypeID='''+@dealbtypeid +'''' END +' 
				AND pt.Stypeid = '''+@stypeid+'''
				AND pt.BtypeFlag='''+CONVERT(VARCHAR(2),@btypeflag)+'''
				AND pt.CID = '+CONVERT(VARCHAR(10),@cid)+'
				UNION ALL
				SELECT 
				pt.PTypeId,
				0, 
				0, 
				0, 
				0, 
				0, 	
				pt.[uid],
				pt.DiscountRate,
				pt.DiscountPrice,
				pt.Price,
				pt.tax,
				pt.TaxPrice
				FROM '+@StypePriceTrackTableName+' pt 
				WHERE 1=1 
				'+CASE WHEN @btypeflag=0 THEN ' 
				AND pt.BTypeID='''+@btypeid +'''' ELSE ' 
				AND pt.BTypeID='''+@dealbtypeid +'''' END +'
				AND pt.CID = '+CONVERT(VARCHAR(10),@cid)+'
				AND pt.BtypeFlag='''+CONVERT(VARCHAR(2),@btypeflag)+''''+
		') T
		GROUP BY t.ptypeid,t.uid'
		
		EXEC(@SQL)	
	END
	
	SELECT @PriceType=PriceType FROM SType WHERE TypeId=@STypeID
	IF ISNULL(@PriceType,0)=1
	BEGIN
		SET @ComputePriceSQL='LEFT JOIN PType_STypePrice C ON C.PTypeID=P.TypeID AND C.UnitID=Put.UnitsID AND C.STypeID='''+@STypeID+'''
		LEFT JOIN (
			   SELECT PreBuyPrice1,PreBuyPrice2,PreBuyPrice3,PreBuyPrice4,PreBuyPrice5,
						           PreSalePrice1,PreSalePrice2,PreSalePrice3,PreSalePrice4,PreSalePrice5,
						           PreSalePrice6,PreSalePrice7,PreSalePrice8,PreSalePrice9,PreSalePrice10,
						           RetailPrice,TopSalePrice,LowSalePrice,TopBuyPrice,
						           PTypeID
			   FROM PType_StypePrice WHERE IsDefaultUnit=1 AND stypeid='''+@STypeID+''' AND PTypeID= '''+@PTypeID+''' 
		) BasePrice ON p.TypeID=BasePrice.PTypeID'
	END
	ELSE
	BEGIN
		SET @ComputePriceSQL='LEFT JOIN Ptype_Price C ON C.PTypeID=P.TypeID AND C.UnitID=Put.UnitsID 
		LEFT JOIN (
			   SELECT PreBuyPrice1,PreBuyPrice2,PreBuyPrice3,PreBuyPrice4,PreBuyPrice5,
						           PreSalePrice1,PreSalePrice2,PreSalePrice3,PreSalePrice4,PreSalePrice5,
						           PreSalePrice6,PreSalePrice7,PreSalePrice8,PreSalePrice9,PreSalePrice10,
						           RetailPrice,TopSalePrice,LowSalePrice,TopBuyPrice,
						           PTypeID 
			   FROM Ptype_Price WHERE IsDefaultUnit=1 AND PTypeID= '''+@PTypeID+''' 
		) BasePrice ON P.TypeID=BasePrice.PTypeID'
	END
	
	--会员卡折扣类型，会员卡折扣
	SELECT TOP 1 
		@VipDiscountType=ISNULL(B.discounttype,0),
		@VIpDiscount=ISNULL(B.cardtypediscount,1)
	FROM nVipCardSign A LEFT JOIN nVipCardSet B ON a.VipCardTypeId = b.VipCardTypeId 
	WHERE a.VipCardCode = @vipcardno
	
	SET @VIPPriceSQL=' 0 AS VipDiscount, 0 as VipPrice,'
	--VipPrice1 VipPrice2
	IF @VipDiscountType IN(5,6,7,8,9)
	BEGIN
		SET @VIPPriceSQL=' 0 AS VipDiscount, S.VipPrice'+CAST((@VipDiscountType-4) AS VARCHAR)+' as VipPrice,'
	END
	ELSE IF @VipDiscountType=10
	BEGIN
		SET @VipPriceSQL=CAST(@VIpDiscount AS VARCHAR) +' AS VipDiscount,0 AS VipPrice,'
	END
	ELSE IF @VipDiscountType<>0
	BEGIN
		SET @VIPPriceSQL=' s.VipDiscount'+CAST(@VipDiscountType AS VARCHAR)+' AS VipDiscount, 0 as VipPrice,'
	END
     
	SET @SQL='SELECT DISTINCT 
		pu.UserCode,
		pu.FullName,
		put.RateType,
		put.Rate,
		CASE WHEN put.IsDefaultUnit = 1 
			 THEN 1 
		ELSE NULL END AS IsDefaultUnit,
		put.UnitsId,
		dbo.F_GetAllEntrycode(@PTypeID,put.UnitsId,2) AS EntryCode,
		ISNULL(pul.Rate,1) AS OldRate,
		track.DiscountTrack,
		track.DiscountPriceTrack,
		track.PriceTrack,
		track.TaxTrack,
		track.TaxPriceTrack,
		track.DiscountTrackStype,
		track.DiscountPriceTrackStype,
		track.PriceTrackStype,
		track.TaxTrackStype,
		track.TaxPriceTrackStype,
		track.pricetracksource,
		'
	
	--计算大单位价格
	IF @CalcMunitPrePriceByBaseWhenNone=1
	BEGIN
		SET @PrePriceSQL='
            0 AS RecPrice,
            BasePrice.RetailPrice AS BaseRetailPrice,
            CASE WHEN ISNULL(c.PreSalePrice1,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice1,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice1 END AS PreSalePrice1,
            CASE WHEN ISNULL(c.PreSalePrice2,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice2,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice2 END AS PreSalePrice2,
            CASE WHEN ISNULL(c.PreSalePrice3,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice3,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice3 END AS PreSalePrice3,
            CASE WHEN ISNULL(c.PreSalePrice4,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice4,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice4 END AS PreSalePrice4,
            CASE WHEN ISNULL(c.PreSalePrice5,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice5,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice5 END AS PreSalePrice5,
            CASE WHEN ISNULL(c.PreSalePrice6,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice6,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice6 END AS PreSalePrice6,
            CASE WHEN ISNULL(c.PreSalePrice7,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice7,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice7 END AS PreSalePrice7,
            CASE WHEN ISNULL(c.PreSalePrice8,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice8,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice8 END AS PreSalePrice8,
            CASE WHEN ISNULL(c.PreSalePrice9,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice9,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice9 END AS PreSalePrice9,
            CASE WHEN ISNULL(c.PreSalePrice10,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreSalePrice10,0)*ISNULL(put.Rate,1) END ELSE c.PreSalePrice10 END AS PreSalePrice10,
            CASE WHEN ISNULL(c.PreBuyPrice1,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreBuyPrice1,0)*ISNULL(put.Rate,1) END ELSE c.PreBuyPrice1 END AS PreBuyPrice1,
            CASE WHEN ISNULL(c.PreBuyPrice2,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreBuyPrice2,0)*ISNULL(put.Rate,1) END ELSE c.PreBuyPrice2 END AS PreBuyPrice2,
            CASE WHEN ISNULL(c.PreBuyPrice3,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreBuyPrice3,0)*ISNULL(put.Rate,1) END ELSE c.PreBuyPrice3 END AS PreBuyPrice3,
            CASE WHEN ISNULL(c.PreBuyPrice4,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreBuyPrice4,0)*ISNULL(put.Rate,1) END ELSE c.PreBuyPrice4 END AS PreBuyPrice4,
            CASE WHEN ISNULL(c.PreBuyPrice5,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.PreBuyPrice5,0)*ISNULL(put.Rate,1) END ELSE c.PreBuyPrice5 END AS PreBuyPrice5,
		    CASE WHEN ISNULL(c.RetailPrice,0)=0 THEN CASE WHEN  @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.RetailPrice,0)*ISNULL(put.Rate,1) END ELSE c.RetailPrice END AS PreSalePrice11,
            CASE WHEN ISNULL(c.TopSalePrice,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.TopSalePrice,0)*ISNULL(put.Rate,1) END ELSE c.TopSalePrice END AS PreSalePrice12,
            CASE WHEN ISNULL(c.LowSalePrice,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.LowSalePrice,0)*ISNULL(put.Rate,1) END ELSE c.LowSalePrice END AS PreSalePrice13,
            CASE WHEN ISNULL(c.TopBuyPrice,0)=0 THEN CASE WHEN  @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.TopBuyPrice,0)*ISNULL(put.Rate,1) END ELSE c.TopBuyPrice END AS PreBuyPrice6,
            CASE WHEN ISNULL(c.RetailPrice,0)=0 THEN CASE WHEN  @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.RetailPrice,0)*ISNULL(put.Rate,1) END ELSE c.RetailPrice END AS PreBuyPrice7,
			CASE WHEN ISNULL(c.TopSalePrice,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.TopSalePrice,0)*ISNULL(put.Rate,1) END ELSE c.TopSalePrice END AS TopSalePrice,
            CASE WHEN ISNULL(c.LowSalePrice,0)=0 THEN CASE WHEN @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.LowSalePrice,0)*ISNULL(put.Rate,1) END ELSE c.LowSalePrice END AS LowSalePrice,
            CASE WHEN ISNULL(c.TopBuyPrice,0)=0 THEN CASE WHEN  @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.TopBuyPrice,0)*ISNULL(put.Rate,1) END ELSE c.TopBuyPrice END AS TopBuyPrice,
            CASE WHEN ISNULL(c.RetailPrice,0)=0 THEN CASE WHEN  @InputPrice<>0 THEN @InputPrice/ISNULL(pul.Rate,1)*ISNULL(put.Rate,1) ELSE ISNULL(BasePrice.RetailPrice,0)*ISNULL(put.Rate,1) END ELSE c.RetailPrice END AS RetailPrice,
			CASE WHEN ISNULL(c.PreSalePrice1,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice1,
			CASE WHEN ISNULL(c.PreSalePrice2,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice2,
			CASE WHEN ISNULL(c.PreSalePrice3,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice3,
			CASE WHEN ISNULL(c.PreSalePrice4,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice4,
			CASE WHEN ISNULL(c.PreSalePrice5,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice5,
			CASE WHEN ISNULL(c.PreSalePrice6,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice6,
			CASE WHEN ISNULL(c.PreSalePrice7,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice7,
			CASE WHEN ISNULL(c.PreSalePrice8,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice8,
			CASE WHEN ISNULL(c.PreSalePrice9,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice9,
			CASE WHEN ISNULL(c.PreSalePrice10,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice10,
			CASE WHEN ISNULL(c.RetailPrice,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice11,
			CASE WHEN ISNULL(c.TopSalePrice,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice12,
			CASE WHEN ISNULL(c.LowSalePrice,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreSalePrice13,
			CASE WHEN ISNULL(c.PreBuyPrice1,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreBuyPrice1,
			CASE WHEN ISNULL(c.PreBuyPrice2,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreBuyPrice2,
			CASE WHEN ISNULL(c.PreBuyPrice3,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreBuyPrice3,
			CASE WHEN ISNULL(c.PreBuyPrice4,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreBuyPrice4,
			CASE WHEN ISNULL(c.PreBuyPrice5,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreBuyPrice5,
			CASE WHEN ISNULL(c.TopBuyPrice,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreBuyPrice6,
			CASE WHEN ISNULL(c.RetailPrice,0)=0 THEN 1 ELSE 0 END AS IsVirtualPreBuyPrice7,
			ISNULL((SELECT TOP 1 ISNULL(RecPrice, 0) FROM ptype_stypeprice  WHERE PTypeID = @PTypeID AND stypeid=@STypeID AND UnitID = put.UnitsID),0) as StypeRecPrice,
			ISNULL((SELECT TOP 1 ISNULL(RecSalePrice, 0) FROM ptype_stypeprice  WHERE PTypeID = @PTypeID AND stypeid=@STypeID AND UnitID =put.UnitsID),0) as StypeRecSalePrice,
			ISNULL((SELECT TOP 1 ISNULL(recamgstypebuyprice, 0) FROM ptype_price  WHERE PTypeID = @PTypeID  AND UnitID = put.UnitsID),0) as amgrecstypebuyprice,
			ISNULL((SELECT TOP 1 ISNULL(recamgstypesaleprice, 0) FROM ptype_price  WHERE PTypeID = @PTypeID  AND UnitID =put.UnitsID),0) as amgrecstypesaleprice,
			ISNULL((SELECT ISNULL(RecAppraisalPrice, 0) FROM PType_StypePrice WHERE PTypeID = @PTypeID AND stypeid=@STypeID AND UnitID = put.UnitsID),0) as RecAppraisalPrice,
			ISNULL((SELECT ISNULL(RecSendPrice, 0) FROM PType_StypePrice WHERE PTypeID = @PTypeiD AND stypeid=@STypeID AND UnitID = put.UnitsID),0) as RecSendPrice,
			(select ReferPrice from PType_Price where PTypeID=@PTypeID  AND IsDefaultUnit=1) as ReferPrice,
			(select ReferPrice from PType_Price where PTypeID=@PTypeID  AND IsDefaultUnit=1) as PReferPrice,
			(select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=@PTypeID AND stypeid=@STypeID AND IsDefaultUnit=1) as SReferPrice,
			p.iscombinationproduct,
			CASE WHEN ISNULL(p.iscombinationproduct,0)=1 
				 THEN (SELECT ISNULL(Price,0) FROM dbo.CombinationProductIndex WHERE CombinationProductPtypeId=P.TypeID AND IsCheck=1 AND IsStop=0)
			ELSE 0 END AS combinationprice,'
	END
	ELSE
	BEGIN
		SET @PrePriceSQL='
            0 AS RecPrice,   
            BasePrice.RetailPrice AS BaseRetailPrice,                                                                                   
            c.PreSalePrice1 AS PreSalePrice1,
            c.PreSalePrice2 AS PreSalePrice2,
            c.PreSalePrice3 AS PreSalePrice3,
            c.PreSalePrice4 AS PreSalePrice4,
            c.PreSalePrice5 AS PreSalePrice5,
            c.PreSalePrice6 AS PreSalePrice6,
            c.PreSalePrice7 AS PreSalePrice7,
			c.PreSalePrice8 AS PreSalePrice8,
            c.PreSalePrice9 AS PreSalePrice9,
            c.PreSalePrice10 AS PreSalePrice10,
            c.PreBuyPrice1 AS PreBuyPrice1,
            c.PreBuyPrice2 AS PreBuyPrice2,
            c.PreBuyPrice3 AS PreBuyPrice3,
            c.PreBuyPrice4 AS PreBuyPrice4,
            c.PreBuyPrice5 AS PreBuyPrice5,
		    c.RetailPrice  AS PreSalePrice11,
			c.TopSalePrice AS PreSalePrice12,
			c.LowSalePrice AS PreSalePrice13,
			c.TopBuyPrice  AS PreBuyPrice6,
			c.RetailPrice  AS PreBuyPrice7,
			c.TopSalePrice AS TopSalePrice,
			c.LowSalePrice AS LowSalePrice,
			c.TopBuyPrice AS TopBuyPrice,
			c.RetailPrice AS RetailPrice,
			0 IsVirtualPreSalePrice1,
			0 IsVirtualPreSalePrice2,
			0 IsVirtualPreSalePrice3,
			0 IsVirtualPreSalePrice4,
			0 IsVirtualPreSalePrice5,
			0 IsVirtualPreSalePrice6,
			0 IsVirtualPreSalePrice7,
			0 IsVirtualPreSalePrice8,
			0 IsVirtualPreSalePrice9,
			0 IsVirtualPreSalePrice10,
			0 IsVirtualPreSalePrice11,
			0 IsVirtualPreSalePrice12,
			0 IsVirtualPreSalePrice13,
			0 IsVirtualPreBuyPrice1,
			0 IsVirtualPreBuyPrice2,
			0 IsVirtualPreBuyPrice3,
			0 IsVirtualPreBuyPrice4,
			0 IsVirtualPreBuyPrice5,
			0 IsVirtualPreBuyPrice6,
			0 IsVirtualPreBuyPrice7,
			ISNULL((SELECT TOP 1 ISNULL(RecPrice, 0) FROM ptype_stypeprice  WHERE PTypeID = @PTypeID AND stypeid=@STypeID AND UnitID = put.UnitsID),0) as StypeRecPrice,
			ISNULL((SELECT TOP 1 ISNULL(RecSalePrice, 0) FROM ptype_stypeprice  WHERE PTypeID =@PTypeID AND stypeid=@STypeID AND UnitID =put.UnitsID),0) as StypeRecSalePrice,
			ISNULL((SELECT TOP 1 ISNULL(recamgstypebuyprice, 0) FROM ptype_price  WHERE PTypeID =@PTypeID  AND UnitID = put.UnitsID),0) as amgrecstypebuyprice,
			ISNULL((SELECT TOP 1 ISNULL(recamgstypesaleprice, 0) FROM ptype_price  WHERE PTypeID = @PTypeID  AND UnitID =put.UnitsID),0) as amgrecstypesaleprice,
			ISNULL((SELECT ISNULL(RecAppraisalPrice, 0) FROM PType_StypePrice WHERE PTypeID = @PTypeID AND stypeid=@STypeID AND UnitID = put.UnitsID),0) as RecAppraisalPrice,
			ISNULL((SELECT ISNULL(RecSendPrice, 0) FROM PType_StypePrice WHERE PTypeID = @PTypeID AND stypeid=@STypeID AND UnitID = put.UnitsID),0) as RecSendPrice,
			(select ReferPrice from PType_Price where PTypeID=@PTypeID  AND IsDefaultUnit=1) as ReferPrice,
			(select ReferPrice from PType_Price where PTypeID=@PTypeID  AND IsDefaultUnit=1) as PReferPrice,
			(select ISNULL(ReferPrice,0) from PType_StypePrice where PTypeID=@PTypeID AND stypeid=@STypeID AND IsDefaultUnit=1) as SReferPrice,
			p.iscombinationproduct,
			CASE WHEN ISNULL(p.iscombinationproduct,0)=1 
				 THEN (SELECT TOP 1 ISNULL(Price,0) FROM dbo.CombinationProductIndex WHERE CombinationProductPtypeId=P.TypeID AND IsCheck=1 AND IsStop=0)
			ELSE 0 END AS combinationprice,'
	END
			
    SET @SQL=@SQL+@PrePriceSQL+@VIPPriceSQL+'
		PromotePrice = (SELECT top 1 PromotePrice
						FROM    PromotePrice pp  
						WHERE   pp.ptypeid = @PTypeID
								AND	('''+@BTypeID+''' LIKE pp.BTypeID +'+'''%'' OR pp.BTYpeID = ''00000'')
								AND ('''+@KTypeID+''' LIKE pp.KTypeID +'+'''%'' OR pp.KTYpeID = ''00000'') 
								AND ('''+@ETypeID+''' LIKE pp.EtypeID +'+'''%'' OR pp.ETypeID = ''00000'')'+
								+CASE WHEN @BillDate IS NOT NULL THEN' 
								AND pp.StartDate <= '''+@BillDate+'''
								AND pp.EndDate >= '''+@BillDate+''''
								ELSE '' END +'
								AND pp.unitid= pu.UnitsId
						ORDER BY pp.BTypeID DESC,pp.KTypeID DESC,pp.ETypeID DESC),
		SaleDefaultRate,
		BuyDefaultRate,
		put.sortid,
		dbo.F_RoundPrice(@showcostprice * put.rate) AS showcostprice
    FROM PType_Units_Ext as put 
    JOIN PType_Units as pu on pu.UnitsId=put.UnitsId 
    LEFT JOIN ptype p on put.ptypeid = p.typeid
    '+@ComputePriceSQL+'
    LEFT JOIN PType_Units_Ext as pul ON pul.UnitsId='+CAST(@UnitsID AS VARCHAR)+' and pul.ptypeid = put.ptypeid 
    LEFT JOIN #PriceTrack Track ON put.ptypeid=track.ptypeid AND put.unitsid=track.uid '
	
	SET @SQL=@SQL+' LEFT JOIN nVipGoodsSign S ON S.PTypeID = put.PTypeID and s.unitid = put.UnitsId 
    WHERE	put.ptypeid= @PTypeID  
			and put.isuse=1 
			AND Put.RateType=0  
	ORDER BY put.sortid ASC '
    
    --SELECT @SQL for xml path('')
    EXEC sp_executesql @SQL,
					   N'@InputPrice NUMERIC(24,10),@PTypeID VARCHAR(100),@STypeID VARCHAR(100),@showcostprice NUMERIC(24,10)',
					   @InputPrice,
					   @PTypeID,
					   @STypeID,
					   @showcostprice
			
	DROP TABLE #PriceTrack
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCountDownAllYear]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCountDownAllYear
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- =============================================
-- 作者:		GLJ
-- 日期:		2014-06-30  跨帐套科目余额表 年度查询
-- 返回:		判断年度
-- =============================================
CREATE PROC Web_QueryCountDownAllYear
(
    @SchemeId	INT		--跨帐套查询方案ID 
)
 --@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #Fyear(FYear INT)--年度临时表
DECLARE 
	@SQL VARCHAR(MAX)='',
	@IP VARCHAR(50),--服务器ip地址
	@Port VARCHAR(50),--服务器端口号
	@ConName VARCHAR(100),--用户名
	@ConPwd VARCHAR(100),--密码
	@DbName VARCHAR(256),--数据库名称
	@InStanceName	VARCHAR(50),--实例名
	@ConStr	VARCHAR(MAX)
DECLARE getData CURSOR READ_ONLY FOR
	SELECT 
		IP,
		Port,
		ConName,
		ConPwd,
		DbName,
		instancename
	FROM SchemeConfig
	WHERE SchemeID=@SchemeId
OPEN getData
FETCH NEXT FROM getData INTO @IP,@Port,@ConName,@ConPwd,@DbName,@InStanceName
WHILE @@FETCH_STATUS = 0
BEGIN
	IF(ISNULL(@InStanceName,'')<>'')
		SET @IP=@IP+'\'+@InStanceName
	ELSE 
		SET @IP=@IP+','+@Port
	SET @ConStr='opendatasource(''sqloledb'',''data source='+@IP+';user ID='+@ConName+';Password='+@ConPwd+''').['+@DbName+'].' 
	SET @SQL='INSERT INTO #Fyear(FYear) SELECT FYear FROM '+@ConStr+'dbo.Ac_Period GROUP BY FYear'
	EXEC(@SQL)
	FETCH NEXT FROM getData INTO @IP,@Port,@ConName,@ConPwd,@DbName,@InStanceName
END
Close getData   --删除游标
DEALLOCATE getData
	
SELECT FYear FROM #Fyear GROUP BY FYear
DROP TABLE #Fyear


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCountDownAtype]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCountDownAtype
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--==========================================
--跨帐套科目selector
--by:glj 
--date:2013-06-23
--===========================================
CREATE PROCEDURE Web_QueryCountDownAtype
(
	@SchemeId		INT,			--查询方案
	@STypeId		VARCHAR(50),	--分支机构
	@ParId			VARCHAR(50),	--父节点
	@Type			INT,			--类型 1：目录树  2：精确匹配 3：列表
	@Query			VARCHAR(200)	--查找内容
)
--@encode$--
AS
SET NOCOUNT ON

IF(ISNULL(@ParId,'')='')
	SET @ParId='00001'
IF(ISNULL(@Query,'')<>'')
	SET @ParId=''
DECLARE @ConStr VARCHAR(MAX),@SQL VARCHAR(MAX)=''
SELECT 
	@ConStr='opendatasource(''sqloledb'',''data source='+CASE WHEN ISNULL(instancename,'')='' THEN IP+','+Port ELSE IP+'\'+instancename END +';user ID='+ConName+';Password='+ConPwd+''').['+DbName+']' 
FROM SchemeConfig 
WHERE 
	SchemeID=@SchemeId 
	AND IsDefault=1
IF(@Type=1)
	BEGIN
		SET @SQL='
		SELECT 
		TypeId,
		FullName 
		FROM '+@ConStr+'.dbo.Ac_Account 
		WHERE 
			StypeId='''+@STypeId+''' 
			AND ParId=''00000''
			AND SonNum>0
		ORDER BY TypeId'
END
ELSE 
	BEGIN
		SET @SQL='
		SELECT
			AA.TypeId,
			AA.ParId,
			AA.UserCode Code,
			REPLICATE(''    '',AA.FLeveal-1) + AA.UserCode UserCode, 
			AA.FullName,
			AA.Leveal,
			AA.SonNum snum,
			CASE WHEN Fdc=1 THEN ''借'' ELSE ''贷'' END Fdc,
			CASE WHEN AA.Cid=0  THEN ''所有币种''
					WHEN AA.Cid=1  THEN ''不核算''
					ELSE (SELECT FullName  FROM Ac_Currency WHERE CId=AA.Cid)
			END FAcnt,
			dbo.F_GetAc_Assist_CheckItems_FullName(AA.TypeId,AA.StypeId) AssisitItem
		FROM '+@ConStr+'.dbo.Ac_Account AA
		INNER JOIN '+@ConStr+'.dbo.SType S ON S.TypeId='''+@STypeId+''' AND AA.StypeId=S.VerifyID
		WHERE 
			AA.ParId LIKE '''+@ParId+'%''
			AND AA.Leveal >1
			AND AA.Deleted=0 '		
		IF(ISNULL(@Query,'')<>'')
			SET @SQL+='	AND (AA.UserCode LIKE ''%'+@Query+'%'' OR AA.FullName LIKE ''%'+@Query+'%'' OR AA.PyCode LIKE ''%'+@Query+'%'')'+CHAR(13)
				
		SET @SQL+='	ORDER BY AA.TypeId,AA.Leveal'
	END
	PRINT @SQL
EXEC(@SQL)


	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCountDownBalance]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCountDownBalance
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--==========================================
--跨帐套科目余额表查询明细
--by:glj 
--date:2013-06-23
--===========================================
CREATE PROCEDURE Web_QueryCountDownBalance
(
	@SchemeId			INT,			--查询方案
	@SFyear				INT,			--开始年度
	@SFPeriod			INT,			--开始期间
	@EFyear				INT,			--结束年度
	@EFPeriod			INT,			--结束期间
	@STypeId 			VARCHAR(50),	--分支机构ID
	@ATypeId			NVARCHAR(MAX),	--会计科目ID(可以多值，以,为分隔符 例：xxx,xxx,xx)        
	@Cid				INT,			--币别ID(-1:所有币别）
	@Leveal				INT,			--科目级别(1-10) -1:所有级别   
	@ShowType			INT,			--显示方式  
	@IsBalanceNull		INT,			--是否包括余额为零的科目
	@IsShowSubTotal		INT,			--是否显示科目小计
	@OperatorId			VARCHAR(50)		---操作员ID

)
--@encode$--
AS
SET NOCOUNT ON
--========================================临时表及赋值【BEGIN】=====================================
DECLARE 
	@SQL	VARCHAR(MAX)='',--sql拼接语句	
	@IP		VARCHAR(50),--IP
	@Port	VARCHAR(50),--端口号
	@ConName VARCHAR(100),
	@ConPwd VARCHAR(100),
	@DbName VARCHAR(256),
	@InStanceName	VARCHAR(50),--实例名
	@RuleType INT,
	@Name	VARCHAR(MAX) --多服务器连接字符串
--分支机构
CREATE TABLE #SType(TypeId VARCHAR(MAX),UserCode VARCHAR(26),FullName VARCHAR(66)) 
--币种
CREATE TABLE #AcCurrency(ID INT IDENTITY(1,1),CId INT,FullName VARCHAR(200))
--科目表
CREATE TABLE #Account
(
	Class VARCHAR(200),
	TypeID VARCHAR(50),
	OrderUserCode VARCHAR(MAX),
	UserCode VARCHAR(200),
	FullName VARCHAR(200),
	Leveal INT,
	StypeId VARCHAR(50)
)
--查询系统配置的默认基本信息
SELECT 
	@IP=C.IP,
	@Port=Port,
	@ConName=C.ConName,
	@ConPwd=C.ConPwd,
	@DbName=C.DbName,
	@InStanceName=C.instancename,
	@RuleType=I.RuleType 
FROM SchemeConfig C
INNER JOIN SchemeIndex I ON I.ID=C.SchemeID 
WHERE 
	C.SchemeID=@SchemeId 
	AND C.IsDefault=1 
	
IF(ISNULL(@InStanceName,'')<>'')
	SET @IP=@IP+'\'+@InStanceName
ELSE 
	SET @IP+=','+@Port

--建立链接 连接不同数据库
SET @Name='opendatasource(''sqloledb'',''data source='+@IP+';user ID='+@ConName+';Password='+@ConPwd+''').['+@DbName+'].dbo.' 
--分支机构
SET @SQL='
	INSERT INTO #SType(TypeId,UserCode,FullName) 
	SELECT 
		TypeId,
		UserCode,
		FullName 
	FROM '+@Name+'SType 
	WHERE TypeId='''+@STypeId+''''
EXEC(@SQL)
--币种
IF(@Cid=-1)
	BEGIN
		SET @SQL='
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT CId,FullName FROM '+@Name+'Ac_Currency 
		UNION ALL
		SELECT 0,''综合本位币'''
	END
ELSE IF @Cid=0
	BEGIN
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT 0,'综合本位币'
	END
ELSE
	BEGIN
		SET @SQL='
		INSERT INTO #AcCurrency(CId,FullName)
		SELECT CId,FullName FROM '+@Name+'Ac_Currency  WHERE CId='+CAST(@Cid AS VARCHAR(50))
	END
EXEC(@SQL)

--所有符合条件的科目
SET @SQL='
INSERT INTO #Account(Class,TypeID,UserCode,OrderUserCode,FullName,Leveal,StypeId)
SELECT
	CASE LEFT(A.TypeId,5) WHEN ''00001'' THEN ''资产''
		 WHEN ''00002'' THEN ''负债''
		 WHEN ''00003'' THEN ''损益''
		 WHEN ''00004'' THEN ''成本''
		 WHEN ''00005'' THEN ''权益''
		 WHEN ''00006'' THEN ''共同'' END Class,
	A.TypeId,
	REPLICATE(''    '',A.FLeveal-1) + A.UserCode UserCode, 
	A.UserCode OrderUserCode,
	A.FullName,
	A.Leveal,
	A.StypeId
FROM '+@Name+'Ac_Account A'

--科目不为空
IF ISNULL(@ATypeId,'')<>''
	SET @SQL+='	INNER JOIN f_split('''+@ATypeId+''','','') F ON F.a=A.TypeId'+CHAR(13)

SET @SQL+='
WHERE 
	A.StypeId='''+@STypeId+''' 
	AND A.ParId<>''00000'' 
	AND A.Leveal<='+CAST(@Leveal+1 AS VARCHAR(2))
EXEC(@SQL)	

IF @IsShowSubTotal=0 AND @Cid<>-1
	BEGIN
		INSERT INTO #Account(Class,TypeID,UserCode,OrderUserCode,FullName,Leveal,StypeId)
		SELECT 
			Class,
			LEFT(TypeID,5) ATypeID,
			CAST(MAX(OrderUserCode) AS VARCHAR(50))+'1' OrderUserCode, 
			NULL UserCode,
			Class+'小计' FullName,
			NULL Leveal,
			StypeId 
		FROM #Account 
		GROUP BY 
			Class,
			LEFT(TypeID,5),
			StypeId 
		ORDER BY ATypeID 
	END
	
--其他帐套使用科目
CREATE TABLE #Ac_Account(TypeId VARCHAR(50),StypeId VARCHAR(50),Fdc INT)

--需要单独处理的符合条件的凭证数据
CREATE TABLE #Scheme_Voucher
(
	ATypeId		VARCHAR(50),			--科目ID
	Cid			INT,					--币种
	FYear		INT,					--年度
	FPeriod		INT,					--期间
	FDebit		 NUMERIC(24, 10)  default(0),--借方
	FCredit		 NUMERIC(24, 10)  default(0),--贷方
	Fdc			INT						--借贷方向
)	
--De借方Cre贷方临时数据保存表
CREATE TABLE #Scheme_A
(
	ATypeID			VARCHAR(50),				--科目ID
	FYear			INT,						--年度
	CId				INT,						--币种
	FDebitBegin		 NUMERIC(24, 10)  default(0),	--期初借方
	FCreditBegin	 NUMERIC(24, 10)  default(0),	--期初贷方
	FDebit			 NUMERIC(24, 10)  default(0),	--本期借方	
	FCredit			 NUMERIC(24, 10)  default(0),	--本期贷方
	FDebitEnd		 NUMERIC(24, 10)  default(0),	--期末借方
	FCreditEnd		 NUMERIC(24, 10)  default(0)	--期末贷方
	
)
--========================================临时表及赋值【END】=====================================

--========================================获取数据【BEGIN】  =====================================

--页面展示完整科目数据
CREATE TABLE #Scheme_Account(ATypeID VARCHAR(50),FYear INT,CId INT)
--年度表
CREATE TABLE #Scheme_AllYear(ID INT IDENTITY(1,1),FYear INT)
DECLARE 
	@I INT=@SFyear,
	@J INT=1,
	@JMAX INT=(SELECT MAX(ID) FROM #AcCurrency),
	@C_Cid INT
IF(@ShowType=1)
	BEGIN
		WHILE(@I<=@EFyear)
			BEGIN
				INSERT INTO #Scheme_AllYear(FYear) SELECT @I
				WHILE(@J<=@JMAX)
				BEGIN
					SELECT @C_Cid=CId FROM #AcCurrency WHERE ID=@J
					INSERT INTO #Scheme_Account(ATypeID,FYear,CId)
					SELECT TypeID,@I,@C_Cid FROM #Account
					SET @J+=1
				END
				SET @J=1
				SET @I+=1
			END
	END	
ELSE 
	BEGIN
		INSERT INTO #Scheme_AllYear(FYear) SELECT 0
		WHILE(@J<=@JMAX)
		BEGIN
			SELECT @C_Cid=CId FROM #AcCurrency WHERE ID=@J
			INSERT INTO #Scheme_Account(ATypeID,FYear,CId)
			SELECT TypeID,0,@C_Cid FROM #Account 
			SET @J+=1
		END
	END
--循环读取配置方案中几个数据库的数据
DECLARE @Row INT=1,@RowCount INT=0
DECLARE @getData TABLE(ID INT IDENTITY(1,1),IP VARCHAR(50),Port VARCHAR(50),ConName VARCHAR(100),ConPwd VARCHAR(100),DbName VARCHAR(256),InStanceName VARCHAR(100))
INSERT INTO @getData(IP,Port,ConName,ConPwd,DbName,InStanceName)
SELECT 
	IP,
	Port,
	ConName,
	ConPwd,
	DbName,
	instancename
FROM SchemeConfig
WHERE SchemeID=@SchemeId
SELECT @RowCount=MAX(ID) FROM @getData
WHILE(@Row<=@RowCount)
BEGIN
	SELECT @IP=IP,@Port=Port,@ConName=ConName,@ConPwd=ConPwd,@DbName=DbName,@InStanceName=InStanceName FROM @getData WHERE ID=@Row
	IF(ISNULL(@InStanceName,'')<>'')
		SET @IP=@IP+'\'+@InStanceName
	ELSE
		SET @IP+=','+@Port 
	--建立链接 连接不同数据库
	SET @Name='opendatasource(''sqloledb'',''data source='+@IP+';user ID='+@ConName+';Password='+@ConPwd+''').['+@DbName+'].dbo.' 
	EXEC WEB_QueryCountDownDetails @Name,@ShowType,@CId,@SFyear,@SFPeriod,@EFyear,@EFPeriod,@OperatorId,@RuleType
	SET @Row+=1
END
--筛除不满足条件的数据 不包括余额为零的科目/不显示本期没有发生额的科目
SET @SQL='
SELECT
	A.Class,
	A.TypeID,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	C.CId,
	C.FullName CidName,
	A.Leveal'
--统计数据返回结果集
SELECT @SQL=@SQL+',
	SUM(CASE WHEN B.FYear='+CAST(Y.FYear AS VARCHAR(4))+' THEN  ISNULL(B.FDebitBegin,0) ELSE 0 END) ['+CAST(Y.FYear AS VARCHAR(4))+'FDebitBegin],
	SUM(CASE WHEN B.FYear='+CAST(Y.FYear AS VARCHAR(4))+' THEN  ISNULL(B.FCreditBegin,0) ELSE 0 END) ['+CAST(Y.FYear AS VARCHAR(4))+'FCreditBegin],
	SUM(CASE WHEN B.FYear='+CAST(Y.FYear AS VARCHAR(4))+' THEN  ISNULL(B.FDebit,0) ELSE 0  END) ['+CAST(Y.FYear AS VARCHAR(4))+'FDebit],
	SUM(CASE WHEN B.FYear='+CAST(Y.FYear AS VARCHAR(4))+' THEN  ISNULL(B.FCredit,0)  ELSE 0 END) ['+CAST(Y.FYear AS VARCHAR(4))+'FCredit],
	SUM(CASE WHEN B.FYear='+CAST(Y.FYear AS VARCHAR(4))+' THEN  ISNULL(B.FDebitEnd,0) ELSE 0  END) ['+CAST(Y.FYear AS VARCHAR(4))+'FDebitEnd],
	SUM(CASE WHEN B.FYear='+CAST(Y.FYear AS VARCHAR(4))+' THEN  ISNULL(B.FCreditEnd,0) ELSE 0  END) ['+CAST(Y.FYear AS VARCHAR(4))+'FCreditEnd]'
FROM #Scheme_AllYear Y
SELECT @SQL=@SQL+'
FROM #Account A
LEFT JOIN (
	SELECT 
		A.ATypeID,
		A.CId,
		A.FYear,
		SUM(ISNULL(T.FDebitBegin,0)) FDebitBegin,
		SUM(ISNULL(T.FCreditBegin,0)) FCreditBegin,
		SUM(ISNULL(T.FDebit,0)) FDebit,
		SUM(ISNULL(T.FCredit,0)) FCredit,
		SUM(ISNULL(T.FDebitEnd,0)) FDebitEnd,
		SUM(ISNULL(T.FCreditEnd,0)) FCreditEnd
	FROM #Scheme_Account A
	LEFT JOIN #Scheme_A T ON T.ATypeID LIKE A.ATypeID+''%'' AND A.CId=T.CId AND A.FYear=T.FYear
	GROUP BY 
		A.ATypeID,
		A.CId,
		A.FYear
	) B ON B.ATypeId=A.TypeID
LEFT JOIN #AcCurrency C ON C.CId=B.Cid
WHERE (('+CAST(@IsBalanceNull AS VARCHAR(2))+'=1 AND B.FDebitEnd<>0 OR B.FCreditEnd<>0) OR '+CAST(@IsBalanceNull AS VARCHAR(2))+'=0)
GROUP BY 
	A.Class,
	A.TypeID,
	A.Class,
	A.TypeID,
	A.UserCode,
	A.OrderUserCode,
	A.FullName,
	C.CId,
	C.FullName,
	A.Leveal--,
	--B.FYear
ORDER BY A.OrderUserCode'      
EXEC(@SQL)
--========================================获取数据【END】    =====================================
	
--========================================删除临时表【BEGIN】=====================================
DROP TABLE 
	#SType,--分支机构
	#Account,--默认系统科目表
	#AcCurrency,--币种
	#Scheme_A,--数据集合表
	#Scheme_Voucher,--凭证处理表
	#Scheme_AllYear,--年度表
	#Ac_Account,--匹配帐套使用科目表
	#Scheme_Account
--========================================删除临时表【END】	 =====================================	
	


	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryCountDownDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].WEB_QueryCountDownDetails
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--==========================================
--跨帐套科目余额表查询明细
--by:glj 
--date:2013-06-23
--===========================================
CREATE PROC WEB_QueryCountDownDetails
(
	@Server				VARCHAR(MAX),	--服务器名称
	@ShowType			INT,			--1：年度 期初 本年 期末 0：期初 本期 期末
	@CId				INT,			--币种
	@SFyear				INT,			--开始年度
	@SFPeriod			INT,			--开始期间
	@EFyear				INT,			--结束年度
	@EFPeriod			INT,			--结束期间
	@OperatorId			VARCHAR(50),	--操作员
	@RuleType			INT				--规则类型: 0=系统规则,1=自定义规则的编码, 2=自定义规则的名称 , 3=自定义规则的编码和名称
)
--@encode$--
AS
SET NOCOUNT ON
--===============================================定义变量及临时表赋值【BEGIN】===============================================
DECLARE
	@StypeId	VARCHAR(50),--分支机构
	@SQL		NVARCHAR(MAX)='',--拼接SQL字符串
	@SQL1		VARCHAR(MAX)='',--拼接SQL字符串
	@SQL2		VARCHAR(MAX)='',--拼接SQL字符串
	@SQL3		VARCHAR(MAX)='',--拼接SQL字符串
	@SQL4		VARCHAR(MAX)=''--拼接SQL字符串
	
--符合条件的分支机构
SET @SQL='SELECT @StypeId=S.TypeId FROM '+@Server+'SType S
INNER JOIN #SType S1 ON '
IF(@RuleType=0)
	SET @SQL+=' S1.TypeId=S.TypeId'
ELSE IF(@RuleType=1)
	SET @SQL+=' S1.UserCode=S.UserCode'
ELSE IF(@RuleType=2)
	SET @SQL+=' S1.FullName=S.FullName'
ELSE IF(@RuleType=3)
	SET @SQL+='  S1.UserCode=S.UserCode AND S1.FullName=S.FullName'
EXEC SP_EXECUTESQL @SQL,N'@StypeId VARCHAR(50) OUT',@StypeId OUT

IF ISNULL(@StypeId,'')=''
	RETURN 

--匹配本帐套的数据会计科目 符合条件的科目筛选
SET @SQL='
INSERT INTO #Ac_Account(TypeId,StypeId,Fdc)
SELECT 
	A.TypeId,
	A.StypeId,
	A.Fdc 
FROM (
	SELECT 
		A.TypeId,
		A.StypeId
	FROM '+@Server+'Ac_Account A
	INNER JOIN #Account A1 ON A.StypeId='''+@StypeId+''' AND ' +CHAR(13)
	IF(@RuleType=0)
		SET @SQL+=' A1.TypeId=A.TypeId' +CHAR(13)
	ELSE IF(@RuleType=1)
		SET @SQL+=' A1.OrderUserCode=A.UserCode' +CHAR(13)
	ELSE IF(@RuleType=2)
		SET @SQL+=' A1.FullName=A.FullName' +CHAR(13)
	ELSE IF(@RuleType=3)
		SET @SQL+='  A1.OrderUserCode=A.UserCode AND A1.FullName=A.FullName' +CHAR(13)
SET @SQL+=')T
	INNER JOIN '+@Server+'Ac_Account A ON A.StypeId=T.StypeId AND A.TypeId LIKE T.TypeId+''%'' AND A.SonCount=0 
	GROUP BY 
		A.TypeId,
		A.StypeId,
		A.Fdc'
EXEC(@SQL)
--===============================================定义变量及临时表赋值【END】===============================================
--统计未记账
SET @SQL='
IF '+CAST(@CId AS VARCHAR(2))+'=0 OR '+CAST(@CId AS VARCHAR(2))+'=-1
	BEGIN
		--未记账
		INSERT INTO #Scheme_Voucher(ATypeId,Cid,FYear,FPeriod,FDebit,FCredit,Fdc)
		SELECT
			A.TypeId ATypeId,
			0 Cid,
			B.FYear,
			B.FPeriod,
			SUM(B.FDebitTotal) FDebit,
			SUM(B.FCreditTotal) FCredit,
			A.Fdc
		FROM #Ac_Account A
		INNER JOIN '+@Server+'Ac_Voucher_Bill B ON B.ATypeId = A.TypeId AND B.StypeId=A.StypeId AND ((B.FYear='+CAST(@EFyear AS VARCHAR(4))+' AND B.FPeriod<='+CAST(@EFPeriod AS VARCHAR(2))+') OR B.FYear<'+CAST(@EFyear AS VARCHAR(4))+')
		INNER JOIN '+@Server+'Ac_Voucher V  ON B.BillNumberId=V.BillNumberId AND V.IfCheck=''F'' AND V.FChecked<>-1
		GROUP BY A.TypeId,B.Cid,B.FYear,B.FPeriod,A.Fdc
	END
IF '+CAST(@CId AS VARCHAR(2))+'<>0
	BEGIN
		--未记账
		INSERT INTO #Scheme_Voucher(ATypeId,Cid,FYear,FPeriod,FDebit,FCredit,Fdc)
		SELECT
			A.TypeId ATypeId,
			B.Cid,
			B.FYear,
			B.FPeriod,
			SUM(B.FDebitTotalFor) FDebit,
			SUM(B.FCreditTotalFor) FCredit,
			A.Fdc
		FROM #Ac_Account A 
		INNER JOIN '+@Server+'Ac_Voucher_Bill B ON B.ATypeId = A.TypeId AND B.StypeId=A.StypeId AND ((B.FYear='+CAST(@EFyear AS VARCHAR(4))+' AND B.FPeriod<='+CAST(@EFPeriod AS VARCHAR(2))+') OR B.FYear<'+CAST(@EFyear AS VARCHAR(4))+') AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+' NOT IN(0,-1) AND B.Cid='+CAST(@CId AS VARCHAR(2))+')) 
		INNER JOIN '+@Server+'Ac_Voucher V ON V.BillNumberId=B.BillNumberId AND V.IfCheck=''F'' AND V.FChecked<>-1
		GROUP BY A.TypeId,B.Cid,B.FYear,B.FPeriod,A.Fdc
	END
'
EXEC(@SQL)

SET @SQL='
DECLARE
	@BeginFYear INT='+CAST(@SFyear AS VARCHAR(4))+',
	@BeginFPeriod INT='+CAST(@SFPeriod AS VARCHAR(4))+',
	@EndFYear INT='+CAST(@EFyear AS VARCHAR(4))+',
	@EndFPeriod INT='+CAST(@EFPeriod AS VARCHAR(4))
	
--按照年度显示	
IF(@ShowType=1)
	BEGIN	
		--年度循环取科目余额表数据及整合未记账凭证数据	
		SET @SQL+='		
		DECLARE @Year INT='+CAST(@SFyear AS VARCHAR(4))+'
		WHILE(@Year<='+CAST(@EFyear AS VARCHAR(4))+')
		BEGIN
			--如果未开张的情况
			IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_AccountsPeroid_Stype WHERE Stypeid='''+@StypeId+''' AND IsUse=0)
			BEGIN
				IF('+CAST(@CId AS VARCHAR(2))+'=0 OR '+CAST(@CId AS VARCHAR(2))+'=-1)
				BEGIN
					INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
					SELECT
						A.TypeId ATypeId,
						0 Cid,
						@Year FYear,
						CASE WHEN A.Fdc=1 THEN CASE WHEN @Year>=I.FYear THEN SUM(I.iniTotal) ELSE 0 END  ELSE 0 END FDebitBegin,
						CASE WHEN A.Fdc=-1 THEN CASE WHEN @Year>=I.FYear THEN SUM(I.iniTotal) ELSE 0 END ELSE 0 END FCreditBegin,
						CASE WHEN @Year=I.FYear THEN SUM(I.FDebit) ELSE 0 END FDebit,
						CASE WHEN @Year=I.FYear THEN SUM(I.FCredit) ELSE 0 END FCredit,
						CASE WHEN A.Fdc=1 THEN  CASE WHEN @Year>=I.FYear THEN SUM(I.iniTotal) ELSE 0 END ELSE 0 END FDebitEnd,
						CASE WHEN A.Fdc=-1 THEN  CASE WHEN @Year>=I.FYear THEN SUM(I.iniTotal) ELSE 0 END ELSE 0 END FCreditEnd
					FROM #Ac_Account A 
					INNER JOIN '+@Server+'Ac_IniAccount I ON I.ATypeId = A.TypeId  AND I.StypeId=A.StypeId
					GROUP BY A.TypeId,A.Fdc,I.FYear
				END
				IF '+CAST(@CId AS VARCHAR(2))+'<>0
				BEGIN
					INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
					SELECT
						A.TypeId ATypeId,
						I.Cid,
						@Year FYear,
						CASE WHEN A.Fdc=1 THEN CASE WHEN @Year>=I.FYear THEN SUM(I.iniTotalFor) ELSE 0 END ELSE 0 END FDebitBegin,
						CASE WHEN A.Fdc=-1 THEN CASE WHEN @Year>=I.FYear THEN SUM(I.iniTotalFor) ELSE 0 END ELSE 0 END FCreditBegin,
						CASE WHEN @Year=I.FYear THEN SUM(I.FDebitFor) ELSE 0 END FDebit,
						CASE WHEN @Year=I.FYear THEN SUM(I.FCreditFor) ELSE 0 END FCredit,
						CASE WHEN A.Fdc=1 THEN CASE WHEN @Year>=I.FYear THEN SUM(I.iniTotalFor) ELSE 0 END ELSE 0 END FDebitEnd,
						CASE WHEN A.Fdc=-1 THEN CASE WHEN @Year>=I.FYear THEN SUM(I.iniTotalFor) ELSE 0 END ELSE 0 END FCreditEnd
					FROM #Ac_Account A 
					INNER JOIN '+@Server+'Ac_IniAccount I ON I.ATypeId = A.TypeId  AND I.StypeId=A.StypeId AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+' NOT IN(0,-1) AND I.Cid='+CAST(@CId AS VARCHAR(2))+')) 
					GROUP BY A.TypeId,A.Fdc,I.Cid,I.FYear
				END
			END'
			--开账的情况
			SET @SQL1+='
			ELSE
			BEGIN
				--期初
				IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_Balance WHERE CAST(FYear AS INT)>=@Year AND STypeId='''+@StypeId+''')
				BEGIN
					SET @BeginFYear=@Year
					SET @EndFYear=@Year
					IF @Year='+CAST(@SFyear AS VARCHAR(4))+'
					BEGIN
						IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_Balance WHERE CAST(FYear AS INT)=@Year AND STypeId='''+@StypeId+''' AND CAST(FPeriod AS INT)>='+CAST(@SFPeriod AS VARCHAR(2))+')
							SET @BeginFPeriod='+CAST(@SFPeriod AS VARCHAR(2))+'
						ELSE 
							SELECT @BeginFPeriod=MAX(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND CAST(FYear AS INT)=@Year
					END
					ELSE
						SELECT @BeginFPeriod=MIN(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND CAST(FYear AS INT)=@Year
						
					IF @Year='+CAST(@EFyear AS VARCHAR(4))+'
					BEGIN
						IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_Balance WHERE CAST(FYear AS INT)=@Year AND STypeId='''+@StypeId+''' AND CAST(FPeriod AS INT)>='+CAST(@EFPeriod AS VARCHAR(2))+')
							SET @EndFPeriod='+CAST(@EFPeriod AS VARCHAR(2))+'
						ELSE 
							SELECT @EndFPeriod=MAX(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND CAST(FYear AS INT)=@Year
					END
					ELSE
						SELECT @EndFPeriod=MAX(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND CAST(FYear AS INT)=@Year
				END			
				ELSE 
				BEGIN
					SELECT @BeginFYear=MAX(CAST(Fyear AS INT)),@EndFYear=MAX(CAST(Fyear AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+'''

					SELECT @BeginFPeriod=MAX(CAST(FPeriod AS INT)),@EndFPeriod=MAX(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND CAST(FYear AS INT)=@BeginFYear				
				END	'
				SET @SQL2+='
				INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
				SELECT 
					A.TypeId ATypeId,
					B.Cid,
					@Year FYear,
					CASE WHEN A.Fdc=1 THEN CASE WHEN @BeginFYear=@Year AND @BeginFYear='+CAST(@SFyear AS VARCHAR(4))+' AND @BeginFPeriod= '+CAST(@SFPeriod AS VARCHAR(4))+' THEN SUM(B.FBeginBalanceFor) ELSE SUM(B.FEndBalanceFor) END ELSE 0 END FDebitBegin,
					CASE WHEN A.Fdc=-1 THEN CASE WHEN @BeginFYear=@Year AND @BeginFYear='+CAST(@SFyear AS VARCHAR(4))+' AND @BeginFPeriod= '+CAST(@SFPeriod AS VARCHAR(4))+' THEN SUM(B.FBeginBalanceFor ) ELSE SUM(B.FEndBalanceFor) END ELSE 0 END FCreditBegin,
					0 FDebit,
					0 FCredit,
					0 FDebitEnd,
					0 FCreditEnd
				FROM #Ac_Account A 
				INNER JOIN '+@Server+'Ac_Balance B ON B.ATypeId = A.TypeId  AND B.StypeId=A.StypeId AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+'<>-1 AND B.Cid='+CAST(@CId AS VARCHAR(2))+')) AND B.FYear=@BeginFYear AND B.FPeriod=@BeginFPeriod
				GROUP BY A.TypeId,A.Fdc,B.Cid

				INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
				SELECT 
					A.TypeId ATypeId,
					B.Cid,
					@Year FYear,
					0 FDebitBegin,
					0 FCreditBegin,
					CASE WHEN @Year=@EndFYear THEN SUM(B.FYtdDebitFor) ELSE 0 END FDebit,
					CASE WHEN @Year=@EndFYear THEN SUM(B.FYtdCreditFor) ELSE 0 END FCredit,
					0 FDebitEnd,
					0 FCreditEnd
				FROM #Ac_Account A 
				INNER JOIN '+@Server+'Ac_Balance B ON B.ATypeId = A.TypeId  AND B.StypeId=A.StypeId AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+'<>-1 AND B.Cid='+CAST(@CId AS VARCHAR(2))+')) AND B.FYear=@EndFYear AND B.FPeriod=@EndFPeriod
				GROUP BY A.TypeId,A.Fdc,B.Cid

				INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
				SELECT 
					A.TypeId ATypeId,
					B.Cid,
					@Year FYear,
					0 FDebitBegin,
					0 FCreditBegin,
					0 FDebit,
					0 FCredit,
					CASE WHEN A.Fdc=1 THEN SUM(B.FEndBalanceFor) ELSE 0 END FDebitEnd,
					CASE WHEN A.Fdc=-1 THEN SUM(B.FEndBalanceFor) ELSE 0 END FCreditEnd
				FROM #Ac_Account A 
				INNER JOIN '+@Server+'Ac_Balance B ON B.ATypeId = A.TypeId  AND B.StypeId=A.StypeId AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+'<>-1 AND B.Cid='+CAST(@CId AS VARCHAR(2))+')) AND B.FYear=@EndFYear AND B.FPeriod=@EndFPeriod
				GROUP BY A.TypeId,A.Fdc,B.Cid
			END'
			SET @SQL3+='
			INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
			SELECT 
				ATypeID,
				CId,
				@Year FYear,
				CASE WHEN Fdc=1 THEN ISNULL(SUM(FDebit-FCredit),0) ELSE 0 END FDebitBegin,
				CASE WHEN Fdc=-1 THEN ISNULL(SUM(FCredit-FDebit),0) ELSE 0 END FCreditBegin,
				0 FDebit,
				0 FCredit,
				0 FDebitEnd,
				0 FCreditEnd 
			FROM #Scheme_Voucher  
			WHERE 
			((FYear<@Year) OR (FYear='+CAST(@SFyear AS VARCHAR(4))+' AND FYear=@Year AND FPeriod<'+CAST(@SFPeriod AS VARCHAR(2))+')) 
			GROUP BY ATypeID,CId,Fdc

			INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
			SELECT 
				ATypeID,
				CId,
				@Year FYear,
				0 FDebitBegin,
				0 FCreditBegin,
				SUM(FDebit) FDebit,
				SUM(FCredit) FCredit,
				0 FDebitEnd,
				0 FCreditEnd
			FROM #Scheme_Voucher  
			WHERE 
			FYear=@Year 
			GROUP BY ATypeID,CId

			INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
			SELECT 
				ATypeID,
				CId,
				@Year FYear,
				0 FDebitBegin,
				0 FCreditBegin,
				0 FDebit,
				0 FCredit,
				CASE WHEN Fdc=1 THEN ISNULL(SUM(FDebit-FCredit),0) ELSE 0 END FDebitEnd,
				CASE WHEN Fdc=-1 THEN ISNULL(SUM(FCredit-FDebit),0) ELSE 0 END FCreditEnd
			FROM #Scheme_Voucher  
			WHERE 
			((FYear<@Year) OR (FYear='+CAST(@EFyear AS VARCHAR(4))+' AND FYear=@Year AND FPeriod<='+CAST(@EFPeriod AS VARCHAR(2))+'))			GROUP BY ATypeID,CId,Fdc
			
			SET @Year+=1
		END'
	END	
ELSE
	BEGIN
		--判断是否开账
		SET @SQL1='
		IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_AccountsPeroid_Stype WHERE Stypeid='''+@StypeId+''' AND IsUse=0)
			BEGIN
				IF('+CAST(@CId AS VARCHAR(2))+'=0 OR '+CAST(@CId AS VARCHAR(2))+'=-1)
					BEGIN
						INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
						SELECT
							A.TypeId ATypeId,
							0 Cid,
							0 FYear,
							CASE WHEN A.Fdc=1 THEN SUM(I.iniTotal) ELSE 0 END FDebitBegin,
							CASE WHEN A.Fdc=-1 THEN SUM(I.iniTotal) ELSE 0 END FCreditBegin,
							0 FDebit,
							0 FCredit,
							CASE WHEN A.Fdc=1 THEN SUM(I.iniTotal) ELSE 0 END FDebitEnd,
							CASE WHEN A.Fdc=-1 THEN SUM(I.iniTotal) ELSE 0 END FCreditEnd
						FROM #Ac_Account A 
						INNER JOIN '+@Server+'Ac_IniAccount I ON I.ATypeId=A.TypeId AND I.StypeId=A.StypeId AND I.STypeId='''+@StypeId+'''
						GROUP BY A.TypeId,A.Fdc
					END
				IF '+CAST(@CId AS VARCHAR(2))+'<>0
					BEGIN
						INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
						SELECT
							A.TypeId ATypeId,
							I.Cid,
							0 FYear,
							CASE WHEN A.Fdc=1 THEN SUM(I.iniTotalFor) ELSE 0 END FDebitBegin,
							CASE WHEN A.Fdc=-1 THEN SUM(I.iniTotalFor) ELSE 0 END FCreditBegin,
							SUM(I.FCreditFor) FDebit,
							SUM(I.FCreditFor) FCredit,
							CASE WHEN A.Fdc=1 THEN SUM(I.iniTotalFor) ELSE 0 END FDebitEnd,
							CASE WHEN A.Fdc=-1 THEN SUM(I.iniTotalFor) ELSE 0 END FCreditEnd
						FROM #Ac_Account A 
						INNER JOIN '+@Server+'Ac_IniAccount I ON I.ATypeId=A.TypeId AND I.StypeId=A.StypeId AND I.STypeId='''+@StypeId+''' AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+' NOT IN(0,-1) AND I.Cid='+CAST(@CId AS VARCHAR(2))+')) 
						GROUP BY A.TypeId,A.Fdc,I.Cid
					END
			END'
		SET @SQL2='
		ELSE 
			BEGIN
				--期初
				IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_Balance WHERE FYear>='+CAST(@SFyear AS VARCHAR(4))+' AND STypeId='''+@StypeId+''')
					BEGIN
						SET @BeginFYear='+CAST(@SFyear AS VARCHAR(4))+'
						IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_Balance WHERE CAST(FYear AS INT)=@BeginFYear AND STypeId='''+@StypeId+''' AND CAST(FPeriod AS INT)>='+CAST(@SFPeriod AS VARCHAR(2))+')
							SET @BeginFPeriod='+CAST(@SFPeriod AS VARCHAR(2))+'
						ELSE 
							SELECT @BeginFPeriod=MAX(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND  CAST(FYear AS INT)=@BeginFYear
					END	
				ELSE 
					BEGIN
						SELECT @BeginFYear=MAX(CAST(Fyear AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+'''		
						SELECT @BeginFPeriod=MAX(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND  CAST(FYear AS INT)=@BeginFYear				
					END	
				--期末	
				IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_Balance WHERE  CAST(FYear AS INT)>='+CAST(@EFyear AS VARCHAR(4))+' AND STypeId='''+@StypeId+''')
					BEGIN
						SET @EndFYear='+CAST(@EFyear AS VARCHAR(4))+'
						IF EXISTS(SELECT TOP 1 1 FROM '+@Server+'Ac_Balance WHERE  CAST(FYear AS INT)=@EndFYear AND STypeId='''+@StypeId+''' AND CAST(FPeriod AS INT)>='+CAST(@EFPeriod AS VARCHAR(2))+')
							SET @EndFPeriod='+CAST(@EFPeriod AS VARCHAR(2))+'
						ELSE 
							SELECT @EndFPeriod=MAX(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND  CAST(FYear AS INT)=@EndFYear
					END	
				ELSE 
					BEGIN
						SELECT @EndFYear=MAX(CAST(Fyear AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+'''
						
						SELECT @EndFPeriod=MAX(CAST(FPeriod AS INT)) FROM '+@Server+'Ac_Balance WHERE STypeId='''+@StypeId+''' AND  CAST(FYear AS INT)=@EndFYear			
					END	
					
				INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
				SELECT 
					A.TypeId ATypeId,
					B.Cid,
					0 FYear,
					CASE WHEN A.Fdc=1 THEN CASE WHEN @BeginFYear='+CAST(@SFyear AS VARCHAR(4))+' AND @BeginFPeriod= '+CAST(@SFPeriod AS VARCHAR(4))+' THEN SUM(B.FBeginBalanceFor) ELSE SUM(B.FEndBalanceFor) END ELSE 0 END FDebitBegin,
					CASE WHEN A.Fdc=-1 THEN CASE WHEN @BeginFYear='+CAST(@SFyear AS VARCHAR(4))+' AND @BeginFPeriod= '+CAST(@SFPeriod AS VARCHAR(4))+' THEN SUM(B.FBeginBalanceFor) ELSE SUM(B.FEndBalanceFor) END ELSE 0 END FCreditBegin,
					0 FDebit,
					0 FCredit,
					0 FDebitEnd,
					0 FCreditEnd
				FROM #Ac_Account A 
				INNER JOIN '+@Server+'Ac_Balance B ON B.ATypeId=A.TypeId AND B.StypeId=A.StypeId AND B.StypeId='''+@StypeId+''' AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+'<>-1 AND B.Cid='+CAST(@CId AS VARCHAR(2))+')) AND B.FYear=@BeginFYear AND B.FPeriod=@BeginFPeriod
				GROUP BY A.TypeId,A.Fdc,B.Cid	
				
				INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
				SELECT 
					A.TypeId ATypeId,
					B.Cid,
					0 FYear,
					0 FDebitBegin,
					0 FCreditBegin,
					SUM(B.FDebitFor) FDebit,
					SUM(B.FCreditFor) FCredit,
					0 FDebitEnd,
					0 FCreditEnd
				FROM #Ac_Account A 
				INNER JOIN '+@Server+'Ac_Balance B ON B.ATypeId=A.TypeId AND B.StypeId=A.StypeId AND B.StypeId='''+@StypeId+'''  AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+'<>-1 AND B.Cid='+CAST(@CId AS VARCHAR(2))+')) 
				AND (
					(B.FYear>'+CAST(@SFyear AS VARCHAR(4))+' AND B.FYear<'+CAST(@EFyear AS VARCHAR(4))+') 
					OR ('+CAST(@SFyear AS VARCHAR(4))+'='+CAST(@SFyear AS VARCHAR(4))+' AND B.FYear='+CAST(@SFyear AS VARCHAR(4))+' AND B.FPeriod>='+CAST(@SFPeriod AS VARCHAR(2))+' AND B.FPeriod<='+CAST(@EFPeriod AS VARCHAR(2))+')
					OR ('+CAST(@SFyear AS VARCHAR(4))+'<'+CAST(@SFyear AS VARCHAR(4))+' AND ((B.FYear='+CAST(@SFyear AS VARCHAR(4))+' AND B.FPeriod>='+CAST(@SFPeriod AS VARCHAR(2))+') OR (B.FYear='+CAST(@EFyear AS VARCHAR(4))+' AND B.FPeriod<='+CAST(@EFPeriod AS VARCHAR(2))+')))
					)
				GROUP BY A.TypeId,A.Fdc,B.Cid	
				
				INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
				SELECT 
					A.TypeId ATypeId,
					B.Cid,
					0 FYear,
					0 FDebitBegin,
					0 FCreditBegin,
					0 FDebit,
					0 FCredit,
					CASE WHEN A.Fdc=1 THEN SUM(B.FEndBalanceFor) ELSE 0 END FDebitEnd,
					CASE WHEN A.Fdc=-1 THEN SUM(B.FEndBalanceFor) ELSE 0 END FCreditEnd
				FROM #Ac_Account A 
				INNER JOIN '+@Server+'Ac_Balance B ON B.ATypeId=A.TypeId AND B.StypeId=A.StypeId AND B.StypeId='''+@StypeId+''' AND (('+CAST(@CId AS VARCHAR(2))+'=-1 AND 1=1 ) OR ('+CAST(@CId AS VARCHAR(2))+'<>-1 AND B.Cid='+CAST(@CId AS VARCHAR(2))+')) AND B.FYear=@EndFYear AND B.FPeriod=@EndFPeriod
				GROUP BY A.TypeId,A.Fdc,B.Cid
'
SET @SQL3='
				IF EXISTS(SELECT TOP 1 1 FROM #Scheme_Voucher)
					BEGIN
						INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
						SELECT 
							ATypeID,
							CId,
							0 FYear,
							CASE WHEN Fdc=1 THEN ISNULL(SUM(FDebit-FCredit),0) ELSE 0 END FDebitBegin,
							CASE WHEN Fdc=-1 THEN ISNULL(SUM(FCredit-FDebit),0) ELSE 0 END FCreditBegin,
							0 FDebit,
							0 FCredit,
							0 FDebitEnd,
							0 FCreditEnd
						FROM #Scheme_Voucher  
						WHERE 
							((FYear<'+CAST(@SFyear AS VARCHAR(4))+') OR (FYear='+CAST(@SFyear AS VARCHAR(4))+' AND FPeriod<'+CAST(@SFPeriod AS VARCHAR(2))+'))
						GROUP BY ATypeID,CId,Fdc

						INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
						SELECT 
							ATypeID,
							CId,
							0 FYear,
							0 FDebitBegin,
							0 FCreditBegin,
							ISNULL(SUM(FDebit),0) FDebit,
							ISNULL(SUM(FCredit),0) FCredit,
							0 FDebitEnd,
							0 FCreditEnd 
						FROM #Scheme_Voucher  
						WHERE 
							 ((FYear>'+CAST(@SFyear+1 AS VARCHAR(4))+' AND FYear<'+CAST(@EFyear-1 AS VARCHAR(4))+') OR (FYear='+CAST(@SFyear AS VARCHAR(4))+' AND FPeriod>='+CAST(@SFPeriod AS VARCHAR(2))+') OR(FYear='+CAST(@EFyear AS VARCHAR(4))+' AND FPeriod<='+CAST(@EFPeriod AS VARCHAR(2))+')) 
						GROUP BY ATypeID,CId
						
						INSERT INTO #Scheme_A(ATypeId,Cid,FYear,FDebitBegin,FCreditBegin,FDebit,FCredit,FDebitEnd,FCreditEnd)
						SELECT 
							ATypeID,
							CId,
							0 FYear,
							0 FDebitBegin,
							0 FCreditBegin,
							0 FDebit,
							0 FCredit,
							CASE WHEN Fdc=1 THEN ISNULL(SUM(FDebit-FCredit),0) ELSE 0 END FDebitEnd,
							CASE WHEN Fdc=-1 THEN ISNULL(SUM(FCredit-FDebit),0) ELSE 0 END FCreditEnd 
						FROM #Scheme_Voucher  
						WHERE 
							((FYear<'+CAST(@EFyear AS VARCHAR(4))+') OR (FYear='+CAST(@EFyear AS VARCHAR(4))+' AND FPeriod<='+CAST(@EFPeriod AS VARCHAR(2))+')) 
						GROUP BY ATypeID,CId,Fdc
					END
			END'
			
	END
SET @SQL4='
	DELETE FROM #Ac_Account'
EXEC(@SQL+@SQL1+@SQL2+@SQL3+@SQL4)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCountDownStype]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryCountDownStype
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	查询跨年查询-分支机构selector
-- 时间：	2014-06-12
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryCountDownStype
(
	@Search			VARCHAR(66)='',		--编号或者名称查找
	@SchemeId		INT					--方案ID	
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @ConStr VARCHAR(MAX)
SELECT 
	@ConStr='opendatasource(''sqloledb'',''data source='+CASE WHEN ISNULL(instancename,'')='' THEN IP+','+Port ELSE IP+'\'+instancename END +';user ID='+ConName+';Password='+ConPwd+''').['+DbName+']' 
FROM SchemeConfig 
WHERE 
	SchemeID=@SchemeId 
	AND IsDefault=1
 
DECLARE @SQL VARCHAR(1000)='
SELECT
	TypeId,
	UserCode,
	FullName 
FROM '+@ConStr+'.dbo.SType 
WHERE 
	1=1 
	AND IsSelfVerify=1 
	AND SonCount=0'+CHAR(10)
IF ISNULL(@Search,'')<>''
	SET @SQL+='AND (UserCode LIKE ''%'+@Search+'%''
			OR FullName LIKE ''%'+@Search+'%'')'
			
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCouponAllotBillList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCouponAllotBillList
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回优惠券调拨单-列表界面
-- 时间：	2017-11-20
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryCouponAllotBillList
(
	@StartBillDate	VARCHAR(50),--查询开始时间
	@EndBillDate	VARCHAR(50),--查询结束时间
	@STypeId		VARCHAR(50),--分支机构
	@DTypeId		VARCHAR(50),--部门
	@OutKTypeId		VARCHAR(50),--出库仓库
	@InKTypeId		VARCHAR(50),--入库仓库
	@CouponType		VARCHAR(20),--优惠券类型 1：代金券 2：折扣券 3：兑换券
	@CouponId		VARCHAR(10),--优惠券
	@Comment		VARCHAR(300),--摘要
	@OperatorId		VARCHAR(200)--当前操作员
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--分支机构
CREATE TABLE #SType(TypeId VARCHAR(50),FullName VARCHAR(300))
INSERT INTO #SType(TypeId,FullName)
SELECT F.TypeId,S.FullName FROM dbo.F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId) F INNER JOIN SType S ON S.TypeId=F.TypeId

--部门
CREATE TABLE #Department(TypeId VARCHAR(50),FullName VARCHAR(300))
INSERT INTO #Department(TypeId,FullName)
SELECT F.TypeId,S.FullName FROM dbo.F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorId) F INNER JOIN Department S ON S.TypeId=F.TypeId

--出库
CREATE TABLE #OutKTypeId(TypeId VARCHAR(50),FullName VARCHAR(300))
INSERT INTO #OutKTypeId(TypeId,FullName)
SELECT F.TypeId,S.FullName FROM dbo.F_GetAllManagerBaseTypeId(@OutKTypeId,4,@OperatorId) F INNER JOIN stock S ON S.TypeId=F.TypeId

--入库
CREATE TABLE #InKTypeId(TypeId VARCHAR(50),FullName VARCHAR(300))
INSERT INTO #InKTypeId(TypeId,FullName)
SELECT F.TypeId,S.FullName FROM dbo.F_GetAllManagerBaseTypeId(@InKTypeId,4,@OperatorId) F INNER JOIN stock S ON S.TypeId=F.TypeId

DECLARE @SQL VARCHAR(MAX)='
SELECT DISTINCT
	A.BillNumberId,
	A.BillDate,
	A.BillCode,
	A.IfCheck,
	CASE WHEN A.IfCheck=''t'' THEN ''过账'' ELSE ''草稿'' END BillStatus,
	S.FullName SFullName,
	D.FullName DFullName,
	A.OutKTypeId,
	A.InKTypeId,
	A.ETypeId,
	A.Maker,
	A.IfCheck,
	A.Comment,
	A.BillType,
	A.RedWord
FROM Coupon_BillIndex A
INNER JOIN Coupon_AllotBill B ON B.BillNumberId=A.BillNumberId 
INNER JOIN #SType S ON S.TypeId=A.STypeId
INNER JOIN #Department D ON D.TypeId=A.DTypeId
INNER JOIN #OutKTypeId outKType ON outKType.TypeId=A.OutKTypeId
INNER JOIN #InKTypeId inKType ON inKType.TypeId=A.InKTypeId
INNER JOIN Coupon_TypeInfo I ON I.CouponId=B.CouponId
WHERE
	I.CouponType IN('+CASE WHEN ISNULL(@CouponType,'')<>'' THEN @CouponType ELSE '-1' END+')'+CHAR(13)--优惠券类型
	
IF(ISNULL(@StartBillDate,'')<>'')--开始时间
	SET @SQL+='	AND A.BillDate>='''+@StartBillDate+''''+CHAR(13)
	
IF(ISNULL(@EndBillDate,'')<>'')--结束时间
	SET @SQL+='	AND A.BillDate<='''+@EndBillDate+''''+CHAR(13)
	
IF(ISNULL(@CouponId,'')<>'')--优惠券名称
	SET @SQL+='	AND B.CouponId IN('+@CouponId+')'+CHAR(13)
	
IF(ISNULL(@Comment,'')<>'')--摘要
	SET @SQL+='	AND A.Comment LIKE ''%'+@Comment+'%'''+CHAR(13)
	
--排序
SET @SQL+='ORDER BY A.BillDate,A.BillCode DESC'

--PRINT @SQL
EXEC(@SQL)

--删除临时表
DROP TABLE #Department,#InKTypeId,#OutKTypeId,#SType


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCouponBackBillByOldOutBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCouponBackBillByOldOutBill
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	优惠券退货单掉原出库单
-- 时间：	2018-01-04
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryCouponBackBillByOldOutBill
(
	@BillIds	VARCHAR(MAX)='',--单据ID字符串
	@Ids		VARCHAR(MAX)='',--明细id字符串
	@BillType	INT,--单据类型 --424 优惠券出库
	@OperatorId	VARCHAR(50)--当前操作员
)
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL 
	RETURN 1
	
DECLARE @intRe INT,@chvMATypeID VARCHAR(50),@chvMBTypeID VARCHAR(50),@chvMBTypeID2	VARCHAR(50),@chvMETypeID VARCHAR(50),@chvMKTypeID	VARCHAR(50),@chvMPTypeID VARCHAR(50),@chvMExpense VARCHAR(50),@chvMIncome VARCHAR(50),@chvMCapital VARCHAR(50),@chvMDtypeid VARCHAR(50),@chvMStypeid VARCHAR(50)
	
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorId,@chvMATypeID OUTPUT,@chvMBTypeID OUTPUT,@chvMBTypeID2 OUTPUT,@chvMETypeID OUTPUT,@chvMKTypeID OUTPUT,@chvMPTypeID OUTPUT,@chvMExpense OUTPUT,@chvMIncome OUTPUT,@chvMCapital OUTPUT,@chvMDtypeid OUTPUT,@chvMStypeid OUTPUT
IF @intRe <> 0 
	RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------
--Web_QueryCouponBackBillLoadOutBill
SELECT 
	B.BillNumberId OldBillNumberId,
	B.Id OutBillId,
	B.BillNumberId,
	B.Id,
	I.CouponId,
	B.Couponcode,
	I.UserCode,
	I.FullName,
	I.CouponType,
	CASE WHEN I.CouponType=1 THEN '代金券'
			WHEN I.CouponType=2 THEN '折扣券'
			WHEN I.CouponType=3 THEN '兑换券'
			ELSE '' 
	END CouponTypeName,
	I.CouponValue,
	I.Discount,
	B.Qty,
	B.Price,
	B.Total CostTotal,
	B.Comment Base,
	BI.Cid,
	BI.Maker,
	1 Selected,
	BI.BillCode
FROM Coupon_OutBill B
INNER JOIN Coupon_TypeInfo I ON I.CouponId=B.CouponId
--INNER JOIN dbo.f_split(@BillIds,',') FBID ON FBID.a=B.BillNumberId
INNER JOIN dbo.f_split(@Ids,',') FID ON FID.a=B.Id
INNER JOIN Coupon_BillIndex BI ON BI.BillNumberId=B.BillNumberId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCouponBackBillLoadOutBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryCouponBackBillLoadOutBill
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	优惠券退货单 调优惠券出库单 加载选中单据
-- 时间：	2017-11-23
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryCouponBackBillLoadOutBill
(
	@BillIds	VARCHAR(MAX),--单据ID
	@Ids		VARCHAR(MAX)--具体明细ID	
)
--@encode$--
AS
SET NOCOUNT ON

SELECT
	B.BillNumberId AS oldbillnumberid,
	B.Id OutBillId,
	B.CouponCode,
	T.CouponId,
	T.UserCode,
	T.FullName,
	T.CouponType,
	CASE WHEN T.CouponType=1 THEN '代金券'
			WHEN T.CouponType=2 THEN '折扣券'
			WHEN T.CouponType=3 THEN '兑换券'
		ELSE '' END CouponTypeName,
	T.CouponValue,
	T.Discount,
	CASE WHEN T.CouponType=3 THEN '√' ELSE '' END AS unitrelation,
	B.Qty,
	B.Price,
	B.NPrice,
	B.Total,
	B.Total AS costtotal,
	B.NTotal,
	T.InvalidType,
	B.CargoId,
	CASE WHEN T.InvalidType=1 THEN '不失效'
			WHEN T.InvalidType=2 THEN '固定期限'
			WHEN T.InvalidType=3 THEN '固定时间'
		ELSE '' END InvalidTypeName,
	B.Comment AS base
FROM Coupon_OutBill B
INNER JOIN Coupon_TypeInfo T ON T.CouponId=B.CouponId 
INNER JOIN f_split(@BillIds,',') FB ON FB.a=B.BillNumberId
INNER JOIN f_split(@Ids,',') FI ON FI.a=B.Id

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCouponDetailReport]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCouponDetailReport
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	优惠券明细报表
-- 时间：	2017-12-04
-- 作者：	颜熙
-- ========================================================================
CREATE PROC Web_QueryCouponDetailReport
(
	@startdate		VARCHAR(50)='',
	@enddate		VARCHAR(50)='',
	@coupontype		VARCHAR(50),
	@couponusercode	VARCHAR(50)='',--券面码
	@stypeid        VARCHAR(MAX)='',
	@ktypeid        VARCHAR(MAX)='',
	@couponname     VARCHAR(50)='',--券名称
	@OperatorID	VARCHAR(50)=''   
)

--@encode$--
AS
SET NOCOUNT ON 

--------------------------------------业务逻辑[BEGIN]---------------------------------------------
BEGIN
	IF @coupontype ='0'
		SET @coupontype ='%%'
	
	IF @couponusercode = ''
		SET @couponusercode = '%%'
	
	--IF @couponname = ''
	--	SET @couponname = '%%'
	--仓库

	CREATE TABLE #GetManKTypeId(TypeId	varchar(100),Fullname VARCHAR(500))
	
	IF(@ktypeid<>'' AND @ktypeid IS NOT NULL)
	BEGIN
		INSERT INTO #GetManKTypeId(TypeId,Fullname) SELECT F.TypeId,K.FullName FROM F_GetAllManagerBaseTypeId('',4,@OperatorID) F 
		INNER JOIN dbo.Stock K ON K.typeId = F.TypeId
		INNER JOIN (SELECT a FROM dbo.f_split(@ktypeid,',')) S ON left(F.typeid,len(S.a))=S.a
	END 
	ELSE
	BEGIN		
		INSERT INTO #GetManKTypeId(TypeId,Fullname) SELECT F.TypeId,K.FullName FROM F_GetAllManagerBaseTypeId('',4,@OperatorID) F 
		INNER JOIN dbo.Stock K ON K.typeId = F.TypeId
	END
	--分支机构
	CREATE TABLE #GetManSTypeId(TypeId	varchar(100),Fullname VARCHAR(500))
	
	IF(@stypeid<>'' AND @stypeid IS NOT NULL)
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId,Fullname) SELECT K.TypeId,K.FullName FROM F_GetAllManagerBaseTypeId('',11,@OperatorID) F 
		INNER JOIN dbo.SType K ON K.TypeId = F.TypeId
		INNER JOIN dbo.f_split(@stypeid,',') S ON left(F.typeid,len(S.a))=S.a
	END 
	ELSE
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId,Fullname) SELECT K.TypeId,K.FullName FROM F_GetAllManagerBaseTypeId('',11,@OperatorID) F 
		INNER JOIN dbo.SType K ON K.TypeId = F.TypeId
	END 

	--往来单位
	CREATE TABLE #GetManBTypeId(TypeId	varchar(100),Fullname VARCHAR(500))
	INSERT INTO #GetManBTypeId(TypeId,Fullname) SELECT B.TypeId,B.FullName FROM F_GetAllManagerBaseTypeId('',2,@OperatorID) F 
	INNER JOIN dbo.BType B ON B.TypeId = F.TypeId

	SELECT  *   FROM( --1.入库、在库 2.出库 3.消费  4.消费红冲 5.消费退货 6报损
	--出库
	SELECT 
				CASE WHEN D.CouponType = 1 THEN '代金券'
				WHEN D.CouponType = 2 THEN '折扣券'
				WHEN D.CouponType = 3 THEN '兑换券' 
				END  AS coupontype,
				C.CouponCode AS couponusercode,
				D.CouponValue AS couponvalue,
				CONVERT(varchar(100), A.BillDate, 23) AS createdate,
				'' AS backdate,
				CONVERT(varchar(100), C.InvalidDate, 23) AS invaliddate ,
				D.Comment AS remark,
				D.FullName AS CouponName,  
				K.Fullname AS kfullname,
				'' AS expensedate,--券消费日期
				'' AS expenseunit,--券消费单位
				CASE WHEN C.State=1 THEN '在库'
					 WHEN C.State =2 THEN '出库'
					 WHEN C.State = 3 THEN '消费'
					 WHEN C.State = 4 THEN '消费红冲'
					 WHEN C.State = 5 THEN '消费退货'
					 WHEN C.State = 6 THEN '报损'
				END AS CouponState,
				A.BillCode AS billcode,
				'' AS posname,--pos消费名称
				'' AS postuiquanname,--pos退券名称
				p.FullName AS posfaquanname,
				A.BillNumberId,
				A.BillType,
				A.CheckeTime
				FROM dbo.Coupon_BillIndex A INNER JOIN dbo.Coupon_OutBill B ON B.BillNumberId = A.BillNumberId
	INNER JOIN Coupon_CodeInfo C ON 'я'+B.CouponCode+'я' LIKE '%я' + C.CouponCode + 'я%'
	INNER JOIN dbo.Coupon_TypeInfo D ON D.CouponId = C.CouponId
	INNER JOIN #GetManKTypeId K ON K.TypeId = A.OutKTypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	--LEFT  JOIN (SELECT U.CouponCode,BI.BillDate,bb.Fullname FROM dbo.Coupon_BillUsed U
	--INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = U.BillnumberId AND bi.RedWord IN (0,1) AND bi.draft = 0
	--INNER  JOIN #GetManBTypeId BB ON BB.TypeId = BI.btypeid ) TEMP ON TEMP.CouponCode = C.CouponCode
	LEFT JOIN dbo.PosInfo P ON A.PosId = P.PosID
	WHERE --C.State IN (2,3)  AND 
	A.BillDate >= @startdate AND A.BillDate<=@enddate
	AND D.CouponType IN (SELECT * FROM dbo.f_split(@coupontype,',')) AND C.CouponCode LIKE '%'+@couponusercode+'%' 
	AND A.RedWord IN (0) AND (@couponname='' OR D.FullName IN (SELECT A FROM dbo.f_split(@couponname,';'))) 
	AND A.IfCheck = 't'
	UNION ALL
	--退款
	SELECT CASE WHEN D.CouponType = 1 THEN '代金券'
				WHEN D.CouponType = 2 THEN '折扣券'
				WHEN D.CouponType = 3 THEN '兑换券' 
				END  AS coupontype,
				C.CouponCode AS couponusercode,
				D.CouponValue AS couponvalue,
				'' AS createdate,
				CONVERT(varchar(100), A.BillDate, 23) AS backdate,
				CONVERT(varchar(100), C.InvalidDate, 23) AS invaliddate ,
				D.Comment AS remark ,
				D.FullName AS CouponName,   
				'' AS kfullname,
				'' AS expensedate,
				'' AS expenseunit,
				CASE WHEN C.State=1 THEN '在库'
					 WHEN C.State =2 THEN '出库'
					 WHEN C.State = 3 THEN '消费'
					 WHEN C.State = 4 THEN '消费红冲'
					 WHEN C.State = 5 THEN '消费退货'
					 WHEN C.State = 6 THEN '报损'
				END AS CouponState,
				A.BillCode AS billcode,
				'' AS posname,--pos消费名称
				p.FullName AS postuiquanname,--pos退券名称
				'' AS posfaquanname,
				A.BillNumberId,
				a.BillType,
				A.CheckeTime
				FROM dbo.Coupon_BillIndex A INNER JOIN dbo.Coupon_BackBill B ON B.BillNumberId = A.BillNumberId
	INNER JOIN Coupon_CodeInfo C ON 'я' + B.CouponCode +'я' LIKE  '%я'+C.CouponCode+'я%' 
	INNER JOIN dbo.Coupon_TypeInfo D ON D.CouponId = C.CouponId
	INNER JOIN #GetManKTypeId K ON K.TypeId = A.InKTypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId = A.STypeId
	--LEFT  JOIN (SELECT U.CouponCode,BI.BillDate,bb.Fullname,BI.RedWord FROM dbo.Coupon_BillUsed U
	--INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = U.BillnumberId AND BI.RedWord IN (0,1)  AND BI.ifcheck = 't'
	--INNER  JOIN #GetManBTypeId BB ON BB.TypeId = BI.btypeid
	-- ) TEMP ON TEMP.CouponCode = C.CouponCode
	LEFT JOIN dbo.PosInfo P ON A.PosId = P.PosID
	WHERE --C.State IN (2,3)  AND
	 A.BillDate >= @startdate AND A.BillDate<=@enddate
	AND D.CouponType IN (SELECT * FROM dbo.f_split(@coupontype,',')) AND C.CouponCode LIKE '%'+@couponusercode+'%'
	AND A.RedWord IN (0) AND (@couponname='' OR D.FullName IN (SELECT A FROM dbo.f_split(@couponname,';'))) AND a.IfCheck = 't'
	UNION ALL
	--消费
	SELECT CASE WHEN D.CouponType = 1 THEN '代金券'
				WHEN D.CouponType = 2 THEN '折扣券'
				WHEN D.CouponType = 3 THEN '兑换券' 
				END  AS coupontype,
				C.CouponCode AS couponusercode,
				D.CouponValue AS couponvalue,
				'' AS createdate,
				'' AS backdate,
				CONVERT(varchar(100), C.InvalidDate, 23) AS invaliddate ,
				D.Comment AS remark ,
				D.FullName AS CouponName,   
				'' AS kfullname,
				CONVERT(varchar(100), BI.BillDate, 23)    AS expensedate,
				BB.Fullname AS expenseunit,
				CASE WHEN C.State=1 THEN '在库'
					 WHEN C.State =2 THEN '出库'
					 WHEN C.State = 3 THEN '消费'
					 WHEN C.State = 4 THEN '消费红冲'
					 WHEN C.State = 5 THEN '消费退货'
					 WHEN C.State = 6 THEN '报损'
				END AS CouponState,
				BI.BillCode AS billcode,
				p.FullName AS posname,--pos消费名称
				'' AS postuiquanname,--pos退券名称
				'' AS posfaquanname,
				BI.BillNumberId,
				BI.BillType,
				BI.checkTime
				FROM Coupon_CodeInfo C 
	INNER JOIN coupon_TypeInfo D ON C.CouponId = D.CouponId
	INNER JOIN  dbo.Coupon_BillUsed U ON C.CouponCode = U.CouponCode
	INNER JOIN dbo.BillIndex BI ON BI.BillNumberId = U.BillnumberId AND BI.RedWord IN (0)  AND BI.ifcheck = 't'
	INNER JOIN #GetManKTypeId K ON K.TypeId = BI.ktypeid
	INNER  JOIN #GetManBTypeId BB ON BB.TypeId = BI.btypeid
	LEFT JOIN dbo.PosInfo P ON U.PosId = P.PosID
	WHERE --C.State IN (2,3)  AND
	BI.BillDate >= @startdate AND BI.BillDate<=@enddate
	AND D.CouponType IN (SELECT * FROM dbo.f_split(@coupontype,',')) AND C.CouponCode LIKE '%'+@couponusercode+'%'
	AND (@couponname='' OR D.FullName IN (SELECT A FROM dbo.f_split(@couponname,';'))) 
	) AS T ORDER BY T.couponusercode,T.CheckeTime
END 


--------------------------------------业务逻辑[END]  ---------------------------------------------


------------------------------------执行 sql并drop临时表 begin--------------------------------


--------------------------------------执行 sql并drop临时表 begin---------------------------------
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCouponInfoList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCouponInfoList]
GO


/*
	作者：谢吉康
	日期：2017-11-06
	描述：优惠券名称查询
*/
CREATE PROCEDURE Web_QueryCouponInfoList
(
	@OperatorId		VARCHAR(100),	--操作员ID
	@StartDate		VARCHAR(20),	--创建日期 开始
	@EndDate		VARCHAR(20),	--创建日期 结束
	@couponid		VARCHAR(200),	--优惠券ID	
	@coupondjq		VARCHAR(10),	--券类型	代金券
	@couponzkq		VARCHAR(10),	--券类型	折扣券
	@coupondhq		VARCHAR(10),	--券类型	兑换券
	@STypeId		VARCHAR(max),	--分支机构ID	
	@gdqx			VARCHAR(10),	--失效方式	固定期限
	@gdsj			VARCHAR(10),	--失效方式	固定时间
	@bsx			VARCHAR(10),	--失效方式 不失效
	@isdelete		VARCHAR(10)		--是否停用 1.停用 0.正常

)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

--分支机构多级权限控制
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) ;
	
--分支机构:获取所有包括父级分支机构 
WITH #allStype
AS ( 
	SELECT * FROM #GetManSTypeId WHERE LEN(typeid) > 5
	UNION ALL 
	SELECT LEFT(typeid,LEN(typeid) - 5) FROM #allStype WHERE LEN(typeid) > 5
   )
INSERT INTO #GetManSTypeId SELECT * FROM #allStype;

--适用机构为全部机构的
IF NOT EXISTS (SELECT * FROM #GetManSTypeId WHERE TypeId = '00000')
	BEGIN 
		INSERT INTO #GetManSTypeId ( TypeId ) VALUES  ( '00000' )
	END
--添加本分支机构
IF NOT EXISTS (SELECT * FROM #GetManSTypeId WHERE TypeId = @STypeId)
BEGIN
	INSERT INTO #GetManSTypeId ( TypeId ) VALUES  ( @STypeId )
END

----获取商品多级权限控制
CREATE TABLE #GetManPTypeId(TypeId	varchar(100)) 
INSERT INTO #GetManPTypeId(TypeId) SELECT typeId FROM dbo.F_AllTreeP(@OperatorID) 

--适用商品为全部商品
IF NOT EXISTS (SELECT * FROM #GetManPTypeId WHERE TypeId = '00000')
BEGIN 
	INSERT INTO #GetManPTypeId ( TypeId ) VALUES  ( '00000' )
END

DECLARE @SQL varchar(8000)

SET	@SQL = '
			SELECT	DISTINCT c.*,
					e.fullname as MakerName,
					CASE	c.coupontype
							WHEN 1 THEN ''代金券''
							WHEN 2 THEN ''折扣券''
							WHEN 3 THEN ''兑换券''
					END AS coupontypename,
					CASE	c.invalidtype
							WHEN 1 THEN ''不失效''
							WHEN 2 THEN ''固定期限''
							WHEN 3 THEN ''固定时间''
					END AS invalidtypename,
					CASE	c.isdelete
							WHEN 1 THEN ''是''
							ELSE ''否''
					END AS isdeletename,
					stypenames = dbo.F_GetCouponTypeInfoBaseNames(c.couponid,1),
					c.IsPosAll
			FROM	coupon_TypeInfo c
			INNER JOIN Employee E ON c.Maker = E.typeid '

IF EXISTS(SELECT TOP 1 1 FROM dbo.sysdata WHERE SubName='Proinfo' AND SubValue = '2')
BEGIN	
	SET @SQL = @SQL + ' INNER JOIN coupon_ApplyStype S ON c.CouponId = S.CouponId 
						INNER JOIN (SELECT DISTINCT TYPEID FROM #GetManSTypeId) MS ON MS.TypeId = S.STypeId '					
END

SET @SQL = @SQL + ' INNER JOIN Coupon_ApplyPtype AP ON AP.Couponid = C.Couponid 
				    INNER JOIN (SELECT DISTINCT TYPEID FROM #GetManPTypeId) MP ON MP.TYPEID = AP.PTYPEID '
				   
SET @SQL = @SQL + ' WHERE c.isdelete LIKE ''%'+@isdelete+'%'''

IF @couponid <> ''
	SET @SQL = @SQL + ' AND c.CouponId IN ( SELECT * FROM DBO.F_SPLIT(' + CHAR(39) + @couponid + CHAR(39) + ','',''))'
	
IF @StartDate <> ''
	SET @SQL = @SQL + ' AND c.CreateDate >= '''+@StartDate+''''
	
IF @EndDate <> ''
	SET @SQL = @SQL + ' AND c.CreateDate < DATEADD(DAY,1,'''+@EndDate+''') '

--券类型
IF @coupondjq = '1' OR @couponzkq = '1' OR @coupondhq = '1'
BEGIN
	SET @SQL = @SQL + ' AND C.CouponType IN (9'
	IF @coupondjq = '1'
		SET @SQL = @SQL + ',1'

	IF @couponzkq = '1'
		SET @SQL = @SQL + ',2'
		
	IF @coupondhq = '1'
		SET @SQL = @SQL + ',3'	
	SET @SQL = @SQL + ')'
END	
ELSE
BEGIN
	SET @SQL = @SQL + ' AND 1 = 0'
END

--失效类型	
IF @gdqx = '1' OR @gdsj = '1' OR @bsx = '1'
BEGIN
	SET @SQL = @SQL + ' AND C.InvalidType IN (9'
	IF @gdqx = '1'	
		SET @SQL = @SQL + ',2'
		
	IF @gdsj = '1'	
		SET @SQL = @SQL + ',3'	

	IF @bsx = '1'	
		SET @SQL = @SQL + ',1'	
	SET @SQL = @SQL + ')'
END
ELSE
BEGIN
	SET @SQL = @SQL + ' AND 1 = 0'
END

	
SET @SQL = @SQL + ' ORDER BY C.UserCode '	

EXEC(@SQL)	

DROP TABLE #GetManSTypeId,#GetManPTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SysObjects WHERE ID=OBJECT_ID(N'Web_QueryCouponIni',N'P'))
BEGIN
	DROP PROC Web_QueryCouponIni
END
GO

/*
	作者：颜熙
	日期：2017-11-15
	描述：优惠券期初查询
*/
CREATE PROC Web_QueryCouponIni
(
	@OperatorID			VARCHAR(100)='',		--操作员
	@KTypeID			VARCHAR(MAX)='',		--仓库ID
	@couponusercode		VARCHAR(100)='',		--优惠券编号
	@couponfullname     VARCHAR(100)='',		--优惠券名称
	@State				INT=-1		 ,
	@StypeID			VARCHAR(MAX),			--分支机构编号
	@coupondjq			BIT ,					--代金券
	@couponzkq			BIT,					--折扣券
	@coupondhq			BIT,					--兑换券
	@gdqx				BIT =0,					--固定期限
	@gdsj				BIT =0,					--固定时间
	@bsx				BIT	=0,					--不失效
	@type               INT =0                    --0:筛选，1：查询条件
)
AS
BEGIN
	SET NOCOUNT ON

	CREATE TABLE #Ktype (TypeID varchar(50),STypeID VARCHAR(50))
	CREATE TABLE #Stype (TypeID varchar(50))
	
	IF @ktypeid=''
	INSERT INTO #Ktype(TypeID,STypeID) SELECT S.typeId,S.STypeID  FROM F_GetManDetailKType(@OperatorID) K INNER JOIN STOCK S ON K.TypeId = S.typeId
	ELSE
	INSERT INTO #Ktype(TypeID,STypeID) 
	SELECT a.typeid,S.STypeID
	FROM F_GetManDetailKType(@OperatorID) a INNER JOIN (SELECT * FROM  dbo.f_split(@ktypeid,',')) b 
	ON A.TypeId LIKE B.a+'%'
	INNER JOIN STOCK S ON S.typeId = A.TypeId

	IF @StypeId=''
	INSERT INTO #Stype SELECT typeid  FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
	ELSE
	INSERT INTO #Stype 
	SELECT a.typeid 
	FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) a,(SELECT * FROM  dbo.f_split(@StypeId,',')) b 
	WHERE A.TypeId LIKE B.a+'%' 
	
	INSERT #Stype( TypeID )
	VALUES  ( '00000') 
	
	DECLARE @Range VARCHAR(500)='',
			@sqlWhere VARCHAR(8000),
			@TicketRange VARCHAR(500)=''
	IF(@gdqx = 1)
		SET @Range = '2,'
	IF(@gdsj = 1)
		SET @Range += '3,'
	IF(@bsx = 1)
		SET @Range +='1,'

	IF(@Range<>'')
	BEGIN
		SET @sqlWhere =' AND InvalidType IN'+'(' + LEFT(@Range,LEN(@Range)-1)  + ')'
	END 
	ELSE
	BEGIN
		SET @sqlWhere =' AND InvalidType NOT IN (1,2,3)'
	END 
	IF(@coupondjq=1)
	BEGIN
		SET @TicketRange = '1,'
	END 
	IF(@couponzkq = 1)
		SET @TicketRange += '2,'
	IF(@coupondhq = 1)
		SET @TicketRange += '3,'
	--IF(@couponall = 1 OR @TicketRange = '')
	--	SET  @sqlWhere+=' AND CouponType IN (1,2,3)'
	--ELSE
	IF(@TicketRange<>'')
	BEGIN
		SET @sqlWhere += ' AND CouponType IN'+'(' + LEFT(@TicketRange,LEN(@TicketRange)-1)  + ')'
	END	
	
	IF(@type = 1)
	BEGIN
		IF(@couponfullname<>'')
		BEGIN
			SET @sqlWhere +=' AND AB.FullName IN (SELECT a
									 FROM      f_split('''+@couponfullname+''', '','') )'
		END 
	END 
	ELSE
	BEGIN
		IF(@couponfullname<>'')
			SET @sqlWhere += ' AND AB.FULLNAME LIKE ''%'+@couponfullname + '%'' '
		IF(@couponusercode <> '')
			BEGIN
				SET @sqlWhere += ' AND AB.UserCode LIKE ''%'+@couponusercode + '%'' '
			END 
	END 

	
	CREATE TABLE #Temptaleb
	(
		usercode	varchar(100),
		fullname	varchar(100),
		coupontypeT	varchar(100),
		qty	NUMERIC(24,10)
	)
	
	CREATE TABLE #OutTemptaleb
	(
		usercode	varchar(100),
		fullname	varchar(100),
		coupontypeT	varchar(100),
		qty	NUMERIC(24,10)
	)
	
	IF(@KTypeID='')
		SET @KTypeID ='%%'
	ELSE
		SET @KTypeID=@KTypeID+'%'
	
	IF(@StypeID = '')
		SET @StypeID ='%%'
	ELSE
		SET @StypeID = @StypeID + '%'
	
	DECLARE @SQL VARCHAR(5000)
	--在库优惠券数量
	SET @SQL ='INSERT INTO #Temptaleb(usercode,fullname,coupontypeT,qty) 
	SELECT AB.UserCode AS usercode,AB.FullName AS fullname,CouponType AS coupontype,COUNT(*) AS qty  
	FROM dbo.Coupon_CodeInfo A INNER JOIN coupon_TypeInfo AB ON AB.CouponId = A.CouponId
	INNER JOIN #Ktype K ON K.TypeId = A.KtypeId
	INNER JOIN #Stype S ON S.TypeId = K.StypeId
	WHERE A.IniState = 1  AND A.IsIni = 1 '+@sqlWhere+
	' GROUP BY AB.UserCode,AB.FullName,AB.CouponType'
	PRINT @SQL
	EXEC(@SQL)

	--出库优惠券数量
	SET @SQL ='INSERT INTO #OutTemptaleb(usercode,fullname,coupontypeT,qty) 
	SELECT AB.UserCode AS usercode,AB.FullName AS fullname,CouponType AS coupontype,COUNT(*) AS qty  
	FROM dbo.Coupon_CodeInfo A INNER JOIN coupon_TypeInfo AB ON AB.CouponId = A.CouponId
	INNER JOIN #Ktype K ON K.TypeId = A.KtypeId
	INNER JOIN #Stype S ON S.TypeId = K.StypeId
	WHERE A.IniState =2  AND A.IsIni = 1 '+@sqlWhere+'
	 GROUP BY AB.UserCode,AB.FullName,AB.CouponType'
	--PRINT @SQL
	EXEC(@SQL)

	SET @SQL = 'SELECT DISTINCT AB.UserCode,AB.FullName,AB.CouponType,AB.CouponId,
	CASE AB.CouponType WHEN 1 THEN ''代金券''
	WHEN 2 THEN ''折扣券''
	WHEN 3 THEN ''兑换券''
	ELSE ''其他'' END AS coupontypename,ISNULL(B.qty,0) AS qty,ISNULL(C.qty,0) AS outqty 
	FROM coupon_TypeInfo AB 
	--INNER JOIN coupon_ApplyStype CA ON AB.CouponId = CA.CouponId
	LEFT JOIN #Temptaleb B ON B.usercode = AB.UserCode AND B.fullname = AB.FullName AND B.coupontypeT = AB.CouponType
	LEFT JOIN #OutTemptaleb C ON AB.UserCode = C.usercode  AND C.fullname = AB.FullName AND C.coupontypeT = AB.CouponType 
	WHERE 1=1 '+@sqlWhere
	--PRINT @SQL
	EXEC(@SQL)

	DROP TABLE #OutTemptaleb
	DROP TABLE #Temptaleb
	DROP TABLE #Stype
	DROP TABLE #Ktype
	SET NOCOUNT OFF
END
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCouponSelector]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCouponSelector
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	优惠券selector
-- 时间：	2017-11-20
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryCouponSelector
(
	@Type			INT,--1=精确匹配 0 模糊查找
	@Filter			VARCHAR(200),--查询条件
	@CouponType		VARCHAR(10),--优惠券类型
	@OperatorId		VARCHAR(50)--当前操作员
)
AS
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL 
	RETURN 1
	
DECLARE @intRe INT,@chvMATypeID VARCHAR(50),@chvMBTypeID VARCHAR(50),@chvMBTypeID2	VARCHAR(50),@chvMETypeID VARCHAR(50),@chvMKTypeID	VARCHAR(50),@chvMPTypeID VARCHAR(50),@chvMExpense VARCHAR(50),@chvMIncome VARCHAR(50),@chvMCapital VARCHAR(50),@chvMDtypeid VARCHAR(50),@chvMStypeid VARCHAR(50)
	
EXEC @intRe = GP_CheckOperatorRight23_Rep @OperatorId,@chvMATypeID OUTPUT,@chvMBTypeID OUTPUT,@chvMBTypeID2 OUTPUT,@chvMETypeID OUTPUT,@chvMKTypeID OUTPUT,@chvMPTypeID OUTPUT,@chvMExpense OUTPUT,@chvMIncome OUTPUT,@chvMCapital OUTPUT,@chvMDtypeid OUTPUT,@chvMStypeid OUTPUT
IF @intRe <> 0 
	RETURN @intRe
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL VARCHAR(MAX)='
SELECT
	I.CouponId,
	I.UserCode,
	I.FullName,
	CASE WHEN I.CouponType=1 THEN ''代金券''
		 WHEN I.CouponType=2 THEN ''折扣券''
		 WHEN I.CouponType=3 THEN ''兑换券''
		 ELSE '''' END CouponType
FROM Coupon_TypeInfo I'+CHAR(13)

IF(ISNULL(@CouponType,'')<>'')--优惠券类型
	SET @SQL+='INNER JOIN f_split('''+@CouponType+''','','') F ON F.a=I.CouponType'+CHAR(13)
	
SET @SQL+='
WHERE 
	1=1'+CHAR(13)

IF(ISNULL(@Filter,'')<>'')
	BEGIN
		IF(@Type=1)--精确匹配
			SET @SQL+='	AND (I.UserCode='''+@Filter+''' OR I.FullName='''+@Filter+''')'+CHAR(13)
		ELSE --模糊匹配
			SET @SQL+='	AND (I.UserCode LIKE ''%'+@Filter+'%'' OR I.FullName LIKE ''%'+@Filter+'%'')'+CHAR(13)
	END
	
EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCruPTypeSerialPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCruPTypeSerialPrint]
GO
















/*
作者：谢吉康
日期：2003-07-04
描述：序列号处理的打印
Web_QueryCruPTypeSerialPrint'00001','2005-7-31 00:00:00','2006-7-6 23:59:59','00000','00001','00000','','','','',0,0,'00002','','',0,0,0,'','',1,'2'
*/

CREATE                             PROCEDURE [Web_QueryCruPTypeSerialPrint] 
(
	@OperatorID		varchar(25),	--1.操作员的ID 
	@StartDate  	varchar(50),    --2.开始时间
	@EndDate    	varchar(50),	--3.结束时间
	@pTypeID    	varchar(25),	--4.商品的ID 
	@bTypeID    	varchar(25),	--5.客户或供货商   00000=客户和供货商统一  00001=客户   00002=供应商
	@kTypeID    	varchar(25),	--6.仓库的ID
	@pSerial    	varchar(40),	--7.序列号
	@pUsercode  	varchar(40),	--8.商品编号
	@pFullname  	varchar(40),	--9.商品名称
	@pState     	varchar(200),	--10.商品状态
	@searchMode 	int,			--11.查询类型   1.精确匹配 0.模糊查找
	@isModal    	int, 			--12.时间的模糊查询   1.是  0.否
	@bTypeID2   	varchar(25),    --13.查询销售商
	@USER			varchar(200),   --14.终端用户
	@Note			varchar(200),	--15.备注
	@ShowAllUser	int,			--16.显示终端用户
	@radValue		int,			--17.开始日期有效  0.入库日期有效   1.出库日期有效	
	@showIniSerial  int,			--18.是否仅显示期初序列号	1.是   0.否
	@BTypeName		varchar(1000),	--19.客户名称
	@JTypeName		varchar(1000),	--20.供货商
	@intPageNo		int		= '',	--21.当前查询的页码
	@tablename		varchar(100),
	@chrRowsReturn	char(1)	= ''	--22. 0为返回14行结果集，2为打印返回所有结果集
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

if @tablename<>'' --只有在@tablename 表存在的情况下，才能正确查询
 begin
	declare @mycount int
	create table #mycount
	(
		mycount int
	)
	
	exec ('insert into #mycount select count(name)  from sysobjects where type=''u'' and [name]='''+@tablename+'''')
	
	select @mycount=mycount from #mycount
	if @mycount<=0
	SET @tablename=''
	drop table #mycount
 end 


DECLARE @SQL varchar(8000)	-- 查询的SQL
SET @SQL=''

--处理参数
IF @PTypeId = '00000'
	SET @PTypeId = '%'

IF @BTypeId = '00000'
	SET @BTypeId = '%'

IF @BTypeId2 = '00000'
	SET @BTypeId2 = '%'

IF @KTypeId = '00000'
	SET @KTypeId = '%'


SET	@SQL = '
	SELECT  a.BTypeId1,
			a.BTypeId2,
			a.Serial,
			a.State,
			a.InKtypeTime,	
			a.OutKtypeTime,
			a.[USER],
			a.note,
			a.KTypeID,
			a.iniFlag,
			b.UserCode,
			b.FullName AS pFullName,
			b.EntryCode,
			b.Standard,
			b.Type,
			b.Area,
			identity(int,1,1) AS sid
	INTO	#temp1
	FROM 	GP_CruPTypeSerial a,
			PType b
	WHERE 	a.PTypeID = b.TypeId 
			AND a.PTypeID LIKE ' + char(39) + @pTypeID + '%' + char(39)+ '
			AND a.PTypeID LIKE ' + char(39) + @MPtypeID + '%' + char(39)

	--是否仅显示期初的序列号
	IF @showIniSerial = 1 
		SET @SQL = @SQL + ' AND a.iniFlag = 1 '

	--处理仓库
	IF @KTypeId = '%'	--全部仓库
		SET @SQL = @SQL + ' 
				AND (a.KtypeID LIKE ' +char(39)+ @kTypeID + '%'+ char(39)+ ' OR a.KTypeID = '+char(39)+'10000'+char(39)+')
				AND (a.KtypeID LIKE ' +char(39)+ @MKtypeID + '%'+ char(39)+ ' OR a.KTypeID = '+char(39)+'10000'+char(39)+')'
	ELSE				--具体仓库
		SET @SQL = @SQL + ' 
				AND a.KtypeID LIKE ' +char(39)+ @kTypeID + '%'+ char(39)+ '
				AND a.KtypeID LIKE ' +char(39)+ @MKtypeID + '%'+ char(39)

	--处理日期   
	--0.入库时间有效  1.出库时间有效
	IF @radValue = 0
		SET @SQL = @SQL + ' 
				AND a.InKtypeTime>='+char(39)+@StartDate+' 00:00:00'+char(39)+'
				AND a.InKtypeTime<='+char(39)+@EndDate+' 23:59:59'+char(39)
	ELSE
		SET @SQL = @SQL + ' 
				AND a.OutKtypeTime>='+char(39)+@StartDate+' 00:00:00'+char(39)+'
				AND a.OutKtypeTime<='+char(39)+@EndDate+' 23:59:59'+char(39)

	DECLARE @MBTypeIdNew varchar(25)
	DECLARE @MBTypeId2New varchar(25)

	IF @MBTypeId='00001'
		SET @MBTypeIdNew=''
	ELSE
		SET @MBTypeIdNew=@MBTypeId
	IF @MBTypeId2='00002'
		SET @MBTypeId2New=''
	ELSE
		SET @MBTypeId2New=@MBTypeId2

	--查询时往来单位有效
	IF @BTypeId <> '%'
	SET @SQL = @SQL + ' AND ((a.BTypeId1 LIKE '+char(39)+@MBTypeIdNew+'%'+char(39)+' AND a.BTypeId1 LIKE '+char(39)+@BTypeId+'%'+char(39)+') OR (a.BTypeId2 LIKE '+char(39)+@MBTypeId2New+'%'+char(39)+' AND a.BTypeId2 LIKE '+char(39)+@BTypeId+'%'+char(39)+'))'

	IF @searchMode=0   --1.精确匹配 0.模糊查找
		BEGIN
			
			IF (@tablename<>'')--haiquan 多项筛选
			    BEGIN
				IF @pSerial<>''
				   SET @SQL=@SQL+' AND (a.Serial LIKE '+char(39)+'%'+@pSerial+'%'+char(39)+' OR a.Serial in (SELECT Serial FROM '+@tablename+'))'
			     	ELSE
				   SET @SQL=@SQL+'AND a.Serial in (SELECT Serial FROM '+@tablename+')'
			     END
			ELSE
				SET @SQL=@SQL+' AND a.Serial LIKE '+char(39)+'%'+@pSerial+'%'+char(39)


			SET @SQL=@SQL+'
				AND b.usercode LIKE '+char(39)+'%'+@pUsercode+'%'+char(39)+'
				AND b.fullname LIKE '+char(39)+'%'+@pFullname+'%'+char(39)+'
				AND a.[USER] LIKE '+char(39)+'%'+@USER+'%'+char(39)+'
				AND a.Note LIKE '+char(39)+'%'+@Note+'%'+char(39)	

			IF @ShowAllUser=1
				SET @SQL=@SQL+' AND ISNULL(a.[USER],'''')='''''
			ELSE
				IF @ShowAllUser=2
					SET @SQL = @SQL + 'AND ISNULL(a.[USER],'''')<>'''''
				ELSE
					SET @SQL = @SQL + 'AND ISNULL(a.[USER],'''') LIKE ''%'''
				
		END 
	ELSE  			--1.精确匹配 0.模糊查找
		BEGIN
			IF (@tablename<>'')
			     BEGIN
				IF @pSerial<>''
				   SET @SQL=@SQL+'AND (a.Serial = '+char(39)+@pSerial+char(39)+' OR a.Serial in (SELECT Serial FROM '+@tablename+'))' 
			     	ELSE
				   SET @SQL=@SQL+'AND a.Serial in (SELECT Serial FROM '+@tablename+')'
			     END
			ELSE
				SET @SQL=@SQL+'AND a.Serial = '+char(39)+@pSerial+char(39) 

			SET @SQL=@SQL+'	AND b.UserCode = '+char(39)+@pUsercode+char(39)+'
					AND b.FullName = '+char(39)+@pFullname+char(39)+'' 
				
		END

	IF @pState=''
		SET @SQL=@SQL+' 
			AND a.state LIKE '+char(39)+@pState+'%'+char(39)
	ELSE
		SET @SQL=@SQL+' 
			AND a.state in ('+@pState+') '

SET @SQL = @SQL + '
					ORDER BY a.Serial'

IF @chrRowsReturn = '0'
BEGIN
	SET @SQL = @SQL + '

	DECLARE @RowsCount numeric(18,0)
	SELECT @RowsCount = COUNT(*) FROM #temp1'
END

SET @SQL = @SQL + '
	SELECT  a.Serial,
			CASE
				WHEN ('+@MBTypeId+'=''00001'' OR ISNULL(a.BTypeId1,'''')='''') THEN (SELECT TOP 1 FullName FROM BType WHERE TypeId = a.BTypeId1)
				WHEN LEN(a.BTypeId1)<=LEN('+char(39)+@MBTypeId+char(39)+') AND a.BTypeId1='+char(39)+@MBTypeId+char(39)+' THEN (SELECT TOP 1 FullName FROM BType WHERE TypeId = a.BTypeId1)
				WHEN LEN(a.BTypeId1)<=LEN('+char(39)+@MBTypeId+char(39)+') AND a.BTypeId1<>'+char(39)+@MBTypeId+char(39)+' THEN ''****''
				WHEN LEN(a.BTypeId1)>LEN('+char(39)+@MBTypeId+char(39)+')  AND LEFT(a.BTypeId1,LEN('+char(39)+@MBTypeId+char(39)+'))='+char(39)+@MBTypeId+char(39)+' THEN (SELECT TOP 1 FullName FROM BType WHERE TypeId = a.BTypeId1)
				WHEN LEN(a.BTypeId1)>LEN('+char(39)+@MBTypeId+char(39)+')  AND LEFT(a.BTypeId1,LEN('+char(39)+@MBTypeId+char(39)+'))<>'+char(39)+@MBTypeId+char(39)+' THEN ''****''
				ELSE NULL
			END AS XfullName,
			CASE
				WHEN ('+char(39)+@MBTypeId2+char(39)+'=''00002'' OR ISNULL(a.BTypeId2,'''')='''') THEN (SELECT TOP 1 FullName FROM BType WHERE TypeId = a.BTypeId2)
				WHEN LEN(a.BTypeId2)<=LEN('+char(39)+@MBTypeId2+char(39)+') AND a.BTypeId2='+char(39)+@MBTypeId2+char(39)+' THEN (SELECT TOP 1 FullName FROM BType WHERE TypeId = a.BTypeId2)
				WHEN LEN(a.BTypeId2)<=LEN('+char(39)+@MBTypeId2+char(39)+') AND a.BTypeId2<>'+char(39)+@MBTypeId2+char(39)+' THEN ''****''
				WHEN LEN(a.BTypeId2)>LEN('+char(39)+@MBTypeId2+char(39)+')  AND LEFT(a.BTypeId2,LEN('+char(39)+@MBTypeId2+char(39)+'))='+char(39)+@MBTypeId2+char(39)+' THEN (SELECT TOP 1 FullName FROM BType WHERE TypeId = a.BTypeId2)
				WHEN LEN(a.BTypeId2)>LEN('+char(39)+@MBTypeId2+char(39)+')  AND LEFT(a.BTypeId2,LEN('+char(39)+@MBTypeId2+char(39)+'))<>'+char(39)+@MBTypeId2+char(39)+' THEN ''****''
				ELSE NULL
			END AS GfullName,
			CASE a.state
				WHEN 1 	THEN ''库存中''
				WHEN 2 	THEN ''已销售''
				WHEN 3 	THEN ''已退货''
				WHEN 4 	THEN ''已报损''
				WHEN 5 	THEN ''已赠送''
				WHEN 6 	THEN ''已返修''
				WHEN 7 	THEN ''受托代销库存中''
				WHEN 8 	THEN ''受托代销已退货''
				WHEN 9 	THEN ''受托代销已销售''
				WHEN 10 THEN ''受托代销已报损''
				WHEN 11	THEN ''受托代销已赠送''
				WHEN 13	THEN ''委托代销已发货''
				WHEN 14	THEN ''委托代销已结算''
				WHEN 15	THEN ''已拆装出库''
				WHEN 16	THEN ''受托代销已拆装出库''
				WHEN 21 THEN ''已换货出库''
				WHEN 22 THEN ''受托代销已换货出库''
				WHEN 23 THEN ''维修出库''
				ELSE NULL
			END AS State,
			a.InKtypeTime,	
			a.OutKtypeTime,
			a.[USER],
			a.note,
			a.UserCode,
			a.pFullName,
			a.EntryCode,
			a.Standard,
			a.Type,
			a.Area,
			kFullName = (SELECT TOP 1 FullName FROM Stock WHERE TypeID = a.KTypeID),
			CASE 
				WHEN a.iniFlag = 1 THEN ''√''
				ELSE NULL
			END AS iniFlag '

IF @chrRowsReturn = '0'
	SET @SQL = @SQL + ',
			@RowsCount AS RowsCount
	FROM	#temp1 a
	WHERE	a.sid >= ' + CAST((@intPageNo-1)*14+1 AS varchar(50)) + '
			AND a.sid <= ' + CAST(@intPageNo*14 AS varchar(50)) + '
	ORDER BY a.sid'
ELSE
	SET @SQL = @SQL + '
	FROM	#temp1 a
	ORDER BY a.sid'

SET @SQL = @SQL + '
	DROP TABLE #temp1'

--PRINT(@SQL)
EXEC(@SQL)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCurrentPeriodDate]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCurrentPeriodDate
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：@ETypeID	1：为空时得到指定分支的当前期间时间值
--					2：不为空时得到指定操作员默认分支机构当前的期间时间值
-- 时间：2013-07-26
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_QueryCurrentPeriodDate
(
	@StypeID		VARCHAR(MAX)='',		--分支机构
	@ETypeID		VARCHAR(50)='',		--操作员ID
	@Fyear			INT=0,				--年度
	@Type			INT					-- 0:指定分支年度数据 1：指定分支指定年度期间 2：指定分支指定年度当前期间值 3:指定分支机构当前年度 4:指定分支指定当前时间
)
--@encode$--

AS
SET NOCOUNT ON 
IF(@Type=0)--多分支机构最小启用年度-及最大当前年度
	BEGIN
		SELECT MIN(SFYear) MinFYear,MAX(FYear) MaxFYear,MAX(FYear) FYear
		FROM Ac_AccountsPeroid_Stype PS 
		INNER JOIN dbo.SType s ON s.VerifyID = ps.Stypeid
		INNER JOIN f_split(@StypeID,',') F ON F.a=S.typeid
	END
ELSE IF(@Type=1)--期间下拉框-多分支机构当前期间取年度最大当前期间
	BEGIN
		DECLARE	
			@MaxPeriod INT=0,
			@MinPeriod INT=0
		IF(SELECT COUNT(*) FROM dbo.f_split(@StypeID,','))>1
			BEGIN
				SELECT 
					1 MinFPeriod,--最小期间
					MAX(FPeriod) MaxFPeriod,--最大期间
					1 FPeriod--当前选中期间 
				FROM Ac_Period WHERE FYear=@Fyear
			END
		ELSE 
			BEGIN
				--查询年度和启用年及当前年度在同一年度
				IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID AND FYear=@Fyear AND SFYear=@Fyear)
					BEGIN
						SELECT 
							@MaxPeriod=MAX(FPeriod),
							@MinPeriod=MIN(SFPeriod)
						FROM Ac_AccountsPeroid_Stype PS 
						WHERE 
							PS.Stypeid=@StypeID 
							AND PS.FYear=@Fyear
					END
				--查询年度和当前年度不在同一年度与启用在同一年度
				ELSE IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID AND FYear<>@Fyear AND SFYear=@Fyear)
					BEGIN
						SELECT 
							@MaxPeriod=MAX(SFPeriod),
							@MinPeriod=MIN(SFPeriod)
						FROM Ac_AccountsPeroid_Stype PS 
						WHERE 
							PS.Stypeid=@StypeID 
							AND PS.SFYear=@Fyear
					END
				--查询年度和当前年度在同一年度与启用年度不在同一年度
				ELSE IF EXISTS(SELECT * FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@StypeID AND FYear=@Fyear AND SFYear<>@Fyear)
					BEGIN
						SELECT 
							@MaxPeriod=MAX(FPeriod),
							@MinPeriod=1
						FROM Ac_AccountsPeroid_Stype PS 
						WHERE 
							PS.Stypeid=@StypeID 
							AND PS.FYear=@Fyear
					END
				--查询年度不在分支机构关系表里
				ELSE 
					BEGIN
						SELECT 
							@MinPeriod=MIN(FPeriod),--最小期间
							@MaxPeriod=MIN(FPeriod)--最大期间
						FROM Ac_Period WHERE FYear=@Fyear
					END
					
				SELECT 
					@MinPeriod MinFPeriod,--最小期间
					MAX(FPeriod) MaxFPeriod,--最大期间
					ISNULL(@MaxPeriod,MAX(FMonth)) FPeriod--当前选中期间 
				FROM Ac_Period WHERE FYear=@Fyear
		END
	END
ELSE IF(@Type=4)--指定分支机构当前期间的开始及结束时间
	BEGIN
		SELECT 
			FBegin BeginDate,
			FEnd EndDate 
		FROM Ac_Period A
		INNER JOIN Ac_AccountsPeroid_Stype S ON A.FYear=S.FYear AND A.FPeriod=S.FPeriod 
		INNER JOIN dbo.SType ss ON ss.VerifyID = s.Stypeid 
		WHERE ss.TypeId = @StypeID
	END
ELSE --指定操作员默认分支机构当前年度当前期间的启用时间及结束时间
	BEGIN
		IF ISNULL(@ETypeID,'')<>''
			SELECT @StypeID=e.STypeID
			FROM employee e
			WHERE e.typeId=@ETypeID
			
		SELECT FBegin BeginDate,FEnd EndDate 
		FROM Ac_Period P 
		INNER JOIN Ac_AccountsPeroid_Stype PS ON PS.FYear=P.FYear AND PS.FPeriod=P.FPeriod
		INNER JOIN dbo.SType ss ON ss.VerifyID = ps.Stypeid AND ss.TypeId = @StypeID
		
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryCurrentPeriodDate_Te]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryCurrentPeriodDate_Te
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 获取出纳期间数据
-- ========================================================================
CREATE PROC Web_QueryCurrentPeriodDate_Te
(
	@StypeID		VARCHAR(MAX)='',		--分支机构
	@ETypeID		VARCHAR(50)='',		--操作员ID
	@Fyear			INT=0,				--年度
	@Type			INT					-- 0:指定分支年度数据 1：指定分支指定年度期间 2：指定分支指定年度当前期间值 3:指定分支机构当前年度 4:指定分支指定当前时间
)
--@encode$--

AS
SET NOCOUNT ON 
IF(@Type=0)--多分支机构最小启用年度-及最大当前年度
	BEGIN
		SELECT MIN(SFYear) MinFYear,MAX(ISNULL(FYear,PS.SFYear)) MaxFYear,MAX(ISNULL(FYear,PS.SFYear)) FYear
		FROM (SELECT sp.STypeId,sp.SFYear,sp.SFPeriod,p.FYear,p.FPeriod FROM dbo.Te_StartPeriod sp LEFT JOIN dbo.Te_Period p ON p.STypeId = sp.STypeId) PS 
		INNER JOIN f_split(@StypeID,',') F ON F.a=PS.Stypeid
	END
ELSE IF(@Type=1)--期间下拉框-多分支机构当前期间取年度最大当前期间
	BEGIN
	
		DECLARE	@MaxPeriod INT=0
				,@MinPeriod INT=0
				,@CurryPeriod	INT=0
				
		SELECT @MaxPeriod = MAX(FPeriod) FROM Ac_Period WHERE FYear=@Fyear
		
		SELECT 1 MinFPeriod,@MaxPeriod MaxFPeriod,1 FPeriod
		/*
		IF EXISTS(SELECT TOP 1 1 FROM dbo.Te_Period ps	INNER JOIN f_split(@StypeID,',') F ON F.a=PS.Stypeid AND PS.FYear=@Fyear)
		BEGIN
			SELECT @CurryPeriod = MIN(PS.FPeriod)
			FROM Te_Period PS 
			INNER JOIN f_split(@StypeID,',') F ON F.a=PS.Stypeid AND PS.FYear=@Fyear
			
			SELECT @MinPeriod=ISNULL(MIN(PS.SFPeriod),1)
			FROM dbo.Te_StartPeriod PS 
			INNER JOIN f_split(@StypeID,',') F ON F.a=PS.Stypeid AND PS.SFYear=@Fyear
			
			
			SELECT @MaxPeriod = MAX(FPeriod) FROM Ac_Period WHERE FYear=@Fyear
			
			SELECT @MinPeriod MinFPeriod,@MaxPeriod MaxFPeriod,@CurryPeriod FPeriod 
		END 
		ELSE 
		BEGIN
			SELECT @MaxPeriod=MAX(PS.SFPeriod)
			FROM dbo.Te_StartPeriod PS 
			INNER JOIN f_split(@StypeID,',') F ON F.a=PS.Stypeid AND PS.SFYear=@Fyear
			
			SELECT @MaxPeriod MinFPeriod,@MaxPeriod MaxFPeriod,@MaxPeriod FPeriod 
		END 
		*/
	END
ELSE IF(@Type=4)--指定分支机构当前期间的开始及结束时间
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Te_Period WHERE STypeId = @StypeID)
		BEGIN
			SELECT	FBegin BeginDate,
					FEnd EndDate 
			FROM Ac_Period A
			INNER JOIN Te_Period S ON S.Stypeid=@StypeID AND A.FYear=S.FYear AND A.FPeriod=S.FPeriod 
		END
		ELSE
		BEGIN
			SELECT	FBegin BeginDate,
					FEnd EndDate 
			FROM Ac_Period A
			INNER JOIN dbo.Te_StartPeriod S ON S.Stypeid=@StypeID AND A.FYear=S.SFYear AND A.FPeriod=S.SFPeriod 
		END
		
	END
ELSE --指定操作员默认分支机构当前年度当前期间的启用时间及结束时间
	BEGIN
		IF ISNULL(@ETypeID,'')<>''
			SELECT @StypeID=STypeID FROM employee WHERE typeId=@ETypeID
		IF EXISTS(SELECT TOP 1 1 FROM Te_Period WHERE STypeId = @StypeID)
		BEGIN	
			SELECT FBegin BeginDate,FEnd EndDate 
			FROM Ac_Period P 
			INNER JOIN Te_Period PS ON PS.Stypeid=@StypeID AND PS.FYear=P.FYear AND PS.FPeriod=P.FPeriod
		END
		ELSE
		BEGIN
			SELECT FBegin BeginDate,FEnd EndDate 
			FROM Ac_Period P 
			INNER JOIN Te_StartPeriod PS ON PS.Stypeid=@StypeID AND PS.SFYear=P.FYear AND PS.SFPeriod=P.FPeriod
		END
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCustomData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCustomData]
GO
/*
	作者：毛欣蓉
	日期：2012-11-01
	描述：报表获取自定义数据
*/
CREATE PROCEDURE Web_QueryCustomData
(
	@customTb	Tb_QueryCustom  READONLY,
	@flag		INT=0 --0 代表查主表自定义，1 代表查明细自定义,2 代表主表明细一起查
)
--@encode$--
AS

DECLARE  @SQL VARCHAR(MAX)='',@SQL1 VARCHAR(MAX),@SQL2 VARCHAR(MAX),@CustomColumns VARCHAR(200),@Defines VARCHAR(200),@Detial VARCHAR(20)='',
		@sqlini VARCHAR(2000),@SQLEnd VARCHAR(MAX),@sqlini1 VARCHAR(2000),@SQLEnd1 VARCHAR(5000)

CREATE TABLE #custom
(
	BillNumberID		NUMERIC(10,0),	-- 单据 ID 值
	BillType			INT,  --单据类型
	ID					BIGINT, --明细ID
	OrderID				INT    --排序id		
)
INSERT INTO #custom SELECT * FROM @customTb

IF @flag = 0 OR @flag = 2
BEGIN
	SELECT @CustomColumns='CustomBillColumns',@defines='CustomBillColumnsDefines'
END
ELSE IF @flag= 1
BEGIN
	SELECT @CustomColumns='CustomBillDetailColumns',@defines='CustomBillDetailColumnsDefines',@Detial='detail'
END

	SET @sqlini='
	SELECT 
		CustomerCaption1+''/''+Costom1Name AS Costom1'+@Detial+',
		CustomerCaption2+''/''+Costom2Name AS Costom2'+@Detial+',
		CustomerCaption3+''/''+Costom3Name AS Costom3'+@Detial+',
		CustomerCaption4+''/''+Costom4Name AS Costom4'+@Detial+',
		CustomerCaption5+''/''+Costom5Name AS Costom5'+@Detial+',
		CustomerCaption6+''/''+Costom6Name AS Costom6'+@Detial+',
		CustomerCaption7+''/''+Costom7Name AS Costom7'+@Detial+',
		CustomerCaption8+''/''+Costom8Name AS Costom8'+@Detial+',
		CustomerCaption9+''/''+Costom9Name AS Costom9'+@Detial+',
		CustomerCaption10+''/''+Costom10Name AS Costom10'+@Detial+',
		CustomerCaption11+''/''+Costom11Name AS Costom11'+@Detial+',
		CustomerCaption12+''/''+Costom12Name AS Costom12'+@Detial+',
		CustomerCaption13+''/''+Costom13Name AS Costom13'+@Detial+',
		CustomerCaption14+''/''+Costom14Name AS Costom14'+@Detial+',
		CustomerCaption15+''/''+Costom15Name AS Costom15'+@Detial+',
		CustomerCaption16+''/''+Costom16Name AS Costom16'+@Detial+',
		OrderID as order_id   -- 换个名字便于和本身报表的orderid重复
	FROM ( '
	
	--查自定义值
	DECLARE @i int = 1
	SELECT @SQL1 =''
	WHILE(@i<17)
	BEGIN
		SELECT @SQL1=@SQL1+'CASE WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''btype'' THEN (SELECT FullName FROM btype WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+') 
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''ptype'' THEN (SELECT FullName FROM ptype WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''stype'' THEN (SELECT FullName FROM stype WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''stock'' THEN (SELECT FullName FROM stock WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''department'' THEN (SELECT FullName FROM department WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''employee'' THEN (SELECT FullName FROM employee WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''AreaType'' THEN (SELECT FullName FROM AreaType WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''Date'' THEN SUBSTRING(a.Costom'+CAST(@i AS VARCHAR)+',0,12)
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType LIKE ''__SelfDataType%''  THEN (SELECT FullName FROM xw_SelfData WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+' AND DataTypeId=SUBSTRING(c'+CAST(@i AS VARCHAR)+'.CustomerType,15,LEN(c'+CAST(@i AS VARCHAR)+'.CustomerType)))
			 ELSE Costom'+CAST(@i AS VARCHAR)+'
		END AS Costom'+CAST(@i AS VARCHAR)+'Name, 
		'
		SET @i+=1
	END
	--自定义名称
	SELECT @i=1,@SQL2 =''
	WHILE(@i<17)
	BEGIN
		SELECT @SQL2=@SQL2+'c'+CAST(@i AS VARCHAR)+'.CustomerCaption as CustomerCaption'+CAST(@i AS VARCHAR)+',
		'
		SET @i+=1
	END
	SELECT @SQL2 = @SQL2 +' a.billnumberid,a.billtype,b.orderid '
		
	SET @SQLEnd = '
			FROM '+@CustomColumns+' a
			right JOIN #custom B ON A.billnumberid = B.billnumberid AND A.billtype = B.billtype  
			LEFT JOIN  '+@Defines+' c1 ON a.billtype=c1.BillType AND c1.CustomerOrder=1
			LEFT JOIN   '+@Defines+' c2 ON a.billtype=c2.billtype AND C2.CustomerOrder=2
			LEFT JOIN   '+@Defines+' c3 ON a.billtype=c3.billtype AND C3.CustomerOrder=3
			LEFT JOIN   '+@Defines+' c4 ON a.billtype=c4.billtype AND C4.CustomerOrder=4
			LEFT JOIN   '+@Defines+' c5 ON a.billtype=c5.billtype AND C5.CustomerOrder=5
			LEFT JOIN   '+@Defines+' c6 ON a.billtype=c6.billtype AND C6.CustomerOrder=6
			LEFT JOIN   '+@Defines+' c7 ON a.billtype=c7.billtype AND C7.CustomerOrder=7
			LEFT JOIN   '+@Defines+' c8 ON a.billtype=c8.billtype AND C8.CustomerOrder=8
			LEFT JOIN   '+@Defines+' c9 ON a.billtype=c9.billtype AND C9.CustomerOrder=9
			LEFT JOIN   '+@Defines+' c10 ON a.billtype=c10.billtype AND C10.CustomerOrder=10
			LEFT JOIN   '+@Defines+' c11 ON a.billtype=c11.billtype AND C11.CustomerOrder=11
			LEFT JOIN   '+@Defines+' c12 ON a.billtype=c12.billtype AND C12.CustomerOrder=12
			LEFT JOIN   '+@Defines+' c13 ON a.billtype=c13.billtype AND C13.CustomerOrder=13
			LEFT JOIN   '+@Defines+' c14 ON a.billtype=c14.billtype AND C14.CustomerOrder=14
			LEFT JOIN   '+@Defines+' c15 ON a.billtype=c15.billtype AND C15.CustomerOrder=15
			LEFT JOIN   '+@Defines+' c16 ON a.billtype=c16.billtype AND C16.CustomerOrder=16 '

IF @Flag = 2
BEGIN
	SELECT @CustomColumns='CustomBillDetailColumns',@defines='CustomBillDetailColumnsDefines',@Detial='detail'
	
	SELECT @sqlini1 ='SELECT ',@i=1
	WHILE(@i<17)
	BEGIN
		SELECT @sqlini1=@sqlini1+'a.CustomerCaption'+CAST(@i AS VARCHAR)+'+''/''+a.Costom'+CAST(@i AS VARCHAR)+'Name AS Costom'+CAST(@i AS VARCHAR)+',
		'
		SET @i+=1
	END
	SELECT @i=1
	WHILE(@i<17)
	BEGIN
		SELECT @sqlini1=@sqlini1+'b.CustomerCaption'+CAST(@i AS VARCHAR)+'+''/''+b.Costom'+CAST(@i AS VARCHAR)+'Name AS Costom'+CAST(@i AS VARCHAR)+'detail,
		'
		SET @i+=1
	END
	
	SET @SQLINI1=@SQLINI1+' a.OrderID AS order_id 
						FROM '
						
						
	SET @SQLEnd1 = '
			FROM '+@CustomColumns+' a
			right JOIN #custom B ON A.billnumberid = B.billnumberid AND A.billtype = B.billtype AND b.id=a.detailId 
			LEFT JOIN  '+@Defines+' c1 ON a.billtype=c1.BillType AND c1.CustomerOrder=1 AND a.InOrOut=c1.InOrOut
			LEFT JOIN   '+@Defines+' c2 ON a.billtype=c2.billtype AND C2.CustomerOrder=2 AND a.InOrOut=c2.InOrOut
			LEFT JOIN   '+@Defines+' c3 ON a.billtype=c3.billtype AND C3.CustomerOrder=3 AND a.InOrOut=c3.InOrOut
			LEFT JOIN   '+@Defines+' c4 ON a.billtype=c4.billtype AND C4.CustomerOrder=4 AND a.InOrOut=c4.InOrOut
			LEFT JOIN   '+@Defines+' c5 ON a.billtype=c5.billtype AND C5.CustomerOrder=5 AND a.InOrOut=c5.InOrOut
			LEFT JOIN   '+@Defines+' c6 ON a.billtype=c6.billtype AND C6.CustomerOrder=6 AND a.InOrOut=c6.InOrOut
			LEFT JOIN   '+@Defines+' c7 ON a.billtype=c7.billtype AND C7.CustomerOrder=7 AND a.InOrOut=c7.InOrOut
			LEFT JOIN   '+@Defines+' c8 ON a.billtype=c8.billtype AND C8.CustomerOrder=8 AND a.InOrOut=c8.InOrOut
			LEFT JOIN   '+@Defines+' c9 ON a.billtype=c9.billtype AND C9.CustomerOrder=9 AND a.InOrOut=c9.InOrOut
			LEFT JOIN   '+@Defines+' c10 ON a.billtype=c10.billtype AND C10.CustomerOrder=10 AND a.InOrOut=c10.InOrOut
			LEFT JOIN   '+@Defines+' c11 ON a.billtype=c11.billtype AND C11.CustomerOrder=11 AND a.InOrOut=c11.InOrOut
			LEFT JOIN   '+@Defines+' c12 ON a.billtype=c12.billtype AND C12.CustomerOrder=12 AND a.InOrOut=c12.InOrOut
			LEFT JOIN   '+@Defines+' c13 ON a.billtype=c13.billtype AND C13.CustomerOrder=13 AND a.InOrOut=c13.InOrOut
			LEFT JOIN   '+@Defines+' c14 ON a.billtype=c14.billtype AND C14.CustomerOrder=14 AND a.InOrOut=c14.InOrOut
			LEFT JOIN   '+@Defines+' c15 ON a.billtype=c15.billtype AND C15.CustomerOrder=15 AND a.InOrOut=c15.InOrOut
			LEFT JOIN   '+@Defines+' c16 ON a.billtype=c16.billtype AND C16.CustomerOrder=16 AND a.InOrOut=c16.InOrOut
	  '
	
	SELECT   @SQL = 'SELECT '+@sql1+@sql2+' INTO #billIndex '+@SQLEnd+'  '
	--EXEC(@SQL)
	
	--SELECT @SQL1
	--SELECT @SQL2
	--SELECT @SQLEnd
	SELECT @SQL=@SQL+ ' SELECT '+@sql1+@sql2+' INTO #billdetail '+@SQLEnd1
	--EXEC(@SQL)
	
	SELECT @SQL= @SQL+@sqlini1 +' #billIndex a  
				INNER JOIN #billdetail b  ON A.ORDERID=B.ORDERID 
				ORDER BY B.ORDERID'
--PRINT @SQL
	EXEC(@SQL)
END	
ELSE
BEGIN
	SELECT @SQL = @SQLINI+' SELECT '+@sql1+@sql2+ @SQLEnd + ')a ORDER BY orderid '
	--SELECT @SQL
	EXEC(@SQL)
END
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryCustomerDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryCustomerDetail]
GO

/*
	作者：LUDALIN
	时间：2013-07-22
	描述：获取自定义信息
*/
CREATE             PROCEDURE Web_QueryCustomerDetail
(
	@details TBType_SelfType READONLY
	--@billnumberid varchar(50)
) 
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
DECLARE  @SQL VARCHAR(MAX)='',@SQL1 VARCHAR(MAX),@SQL2 VARCHAR(MAX),@CustomColumns VARCHAR(200),@Defines VARCHAR(200),@Detial VARCHAR(20)='',
		@sqlini VARCHAR(2000),@SQLEnd VARCHAR(MAX),@sqlini1 VARCHAR(2000),@SQLEnd1 VARCHAR(5000)

SELECT @CustomColumns='CustomBillColumns',@defines='CustomBillColumnsDefines'
	SET @sqlini='
	SELECT 
		a.billnumberid,a.billtype,
		CustomerCaption1+''/''+Costom1Name AS Costom1'+@Detial+',
		CustomerCaption2+''/''+Costom2Name AS Costom2'+@Detial+',
		CustomerCaption3+''/''+Costom3Name AS Costom3'+@Detial+',
		CustomerCaption4+''/''+Costom4Name AS Costom4'+@Detial+',
		CustomerCaption5+''/''+Costom5Name AS Costom5'+@Detial+',
		CustomerCaption6+''/''+Costom6Name AS Costom6'+@Detial+',
		CustomerCaption7+''/''+Costom7Name AS Costom7'+@Detial+',
		CustomerCaption8+''/''+Costom8Name AS Costom8'+@Detial+',
		CustomerCaption9+''/''+Costom9Name AS Costom9'+@Detial+',
		CustomerCaption10+''/''+Costom10Name AS Costom10'+@Detial+',
		CustomerCaption11+''/''+Costom11Name AS Costom11'+@Detial+',
		CustomerCaption12+''/''+Costom12Name AS Costom12'+@Detial+',
		CustomerCaption13+''/''+Costom13Name AS Costom13'+@Detial+',
		CustomerCaption14+''/''+Costom14Name AS Costom14'+@Detial+',
		CustomerCaption15+''/''+Costom15Name AS Costom15'+@Detial+',
		CustomerCaption16+''/''+Costom16Name AS Costom16'+@Detial+'--,
		--OrderID as order_id   -- 换个名字便于和本身报表的orderid重复
	INTO ##TEMP_TABLE 
	FROM ( '
	
	--查自定义值
	DECLARE @i int = 1
	SELECT @SQL1 =''
	WHILE(@i<17)
	BEGIN
		SELECT @SQL1=@SQL1+'CASE WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''btype'' THEN (SELECT FullName FROM btype WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+') 
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''ptype'' THEN (SELECT FullName FROM ptype WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''stype'' THEN (SELECT FullName FROM stype WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''stock'' THEN (SELECT FullName FROM stock WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''department'' THEN (SELECT FullName FROM department WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''employee'' THEN (SELECT FullName FROM employee WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''AreaType'' THEN (SELECT FullName FROM AreaType WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+')
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType = ''Date'' THEN SUBSTRING(a.Costom'+CAST(@i AS VARCHAR)+',0,12)
			 WHEN c'+CAST(@i AS VARCHAR)+'.CustomerType LIKE ''__SelfDataType%''  THEN (SELECT FullName FROM xw_SelfData WHERE typeId=a.Costom'+CAST(@i AS VARCHAR)+' AND DataTypeId=SUBSTRING(c'+CAST(@i AS VARCHAR)+'.CustomerType,15,LEN(c'+CAST(@i AS VARCHAR)+'.CustomerType)))
			 ELSE Costom'+CAST(@i AS VARCHAR)+'
		END AS Costom'+CAST(@i AS VARCHAR)+'Name, 
		'
		SET @i+=1
	END
	--自定义名称
	SELECT @i=1,@SQL2 =''
	WHILE(@i<17)
	BEGIN
		SELECT @SQL2=@SQL2+'c'+CAST(@i AS VARCHAR)+'.CustomerCaption as CustomerCaption'+CAST(@i AS VARCHAR)+',
		'
		SET @i+=1
	END
	SELECT @SQL2 = @SQL2 +' a.billnumberid,a.billtype'
		
	SET @SQLEnd = '
			FROM '+@CustomColumns+' a
			--right JOIN #custom B ON A.billnumberid = B.billnumberid AND A.billtype = B.billtype  
			LEFT JOIN  '+@Defines+' c1 ON a.billtype=c1.BillType AND c1.CustomerOrder=1
			LEFT JOIN   '+@Defines+' c2 ON a.billtype=c2.billtype AND C2.CustomerOrder=2
			LEFT JOIN   '+@Defines+' c3 ON a.billtype=c3.billtype AND C3.CustomerOrder=3
			LEFT JOIN   '+@Defines+' c4 ON a.billtype=c4.billtype AND C4.CustomerOrder=4
			LEFT JOIN   '+@Defines+' c5 ON a.billtype=c5.billtype AND C5.CustomerOrder=5
			LEFT JOIN   '+@Defines+' c6 ON a.billtype=c6.billtype AND C6.CustomerOrder=6
			LEFT JOIN   '+@Defines+' c7 ON a.billtype=c7.billtype AND C7.CustomerOrder=7
			LEFT JOIN   '+@Defines+' c8 ON a.billtype=c8.billtype AND C8.CustomerOrder=8
			LEFT JOIN   '+@Defines+' c9 ON a.billtype=c9.billtype AND C9.CustomerOrder=9
			LEFT JOIN   '+@Defines+' c10 ON a.billtype=c10.billtype AND C10.CustomerOrder=10
			LEFT JOIN   '+@Defines+' c11 ON a.billtype=c11.billtype AND C11.CustomerOrder=11
			LEFT JOIN   '+@Defines+' c12 ON a.billtype=c12.billtype AND C12.CustomerOrder=12
			LEFT JOIN   '+@Defines+' c13 ON a.billtype=c13.billtype AND C13.CustomerOrder=13
			LEFT JOIN   '+@Defines+' c14 ON a.billtype=c14.billtype AND C14.CustomerOrder=14
			LEFT JOIN   '+@Defines+' c15 ON a.billtype=c15.billtype AND C15.CustomerOrder=15
			LEFT JOIN   '+@Defines+' c16 ON a.billtype=c16.billtype AND C16.CustomerOrder=16 '


	SELECT @SQL = @SQLINI+' SELECT '+@sql1+@sql2+ @SQLEnd + ') a'
	--SELECT @SQL
	EXEC(@SQL)
	select a.* from ##TEMP_TABLE a INNER JOIN @details B ON A.BILLNUMBERID=B.BILLNUMBERID AND A.BILLTYPE=B.BILLTYPE ;
	drop table ##TEMP_TABLE
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_QueryCustomInfoFromPtypeUserCode]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Web_QueryCustomInfoFromPtypeUserCode]
GO

/*
	作者：谢吉康
	日期：2018-10-15
	描述：根据商品编号查询自由项信息
*/
CREATE PROCEDURE Web_QueryCustomInfoFromPtypeUserCode
(
	@usercode		VARCHAR(500)			--编号
)
AS
SET NOCOUNT ON

SELECT	p.customitemid,
		p.CustomItemFrom,
		p.entrycode,
		v.* FROM vWeb_ItemIDByIsCombined v
INNER JOIN ptype p ON p.customitemid = v.DataTypeId AND p.CustomItemFrom = v.iscombined 
WHERE  p.UserCode = @usercode

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryDAssetBusinessType]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryDAssetBusinessType
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-业务类型 多选selector
-- 时间：2013-08-21
-- 作者：古丽娟	
-- ========================================================================
CREATE PROC Web_QueryDAssetBusinessType
(
	@Search			VARCHAR(66),		--查询条件
	@StypeID		VARCHAR(50),		--分支机构
	@OperatorID		VARCHAR(50),		--操作员
	@Type			VARCHAR(10)			--业务类型
)
--@encode$--

AS
SET NOCOUNT ON

CREATE TABLE #Ac_AssetBusinessType (ID INT,BusinessType INT,FullName VARCHAR(200),Deleted INT)
INSERT INTO #Ac_AssetBusinessType
SELECT AuditType,BusinessType,FullName,Deleted FROM Ac_AssetBusinessType WHERE STypeId='00001'

IF @Type='-1'
BEGIN
	INSERT INTO #Ac_AssetBusinessType (ID,BusinessType,FullName,Deleted)
	SELECT '-3','4','折旧方式变更','1'
	UNION ALL
	SELECT '0','-1','初始化','1'
END


 
DECLARE @SQL VARCHAR(2000)='
SELECT 
		B.Id,
		B.BusinessType,
		CASE B.BusinessType WHEN 0 THEN ''增加''
			WHEN 1 THEN ''减少''
			WHEN 2 THEN ''部门转移''
			WHEN 3 THEN ''计提减值准备''
			WHEN 4 THEN ''折旧''
			WHEN -1 THEN ''初始化''
			ELSE ''''
		END typefullname,
		CASE B.BusinessType WHEN 0 THEN 212
			WHEN 1 THEN 213
			WHEN 2 THEN -1
			WHEN 3 THEN -2
			WHEN 4 THEN 214
		END billtype,
		B.FullName,
		B.Deleted
	FROM #Ac_AssetBusinessType B '
	
SET @SQL+='WHERE 1=1'+CHAR(13)
IF ISNULL(@Search,'')<>'' 
	SET @SQL+=' AND B.FullName LIKE ''%'+@Search+'%'' '+CHAR(13)
	
IF(ISNULL(@Type,'')<>'') AND @Type<>'-1'
	SET @SQL+=' AND B.Deleted=1 AND B.BusinessType LIKE '+@Type+CHAR(13)
SET @SQL+=' ORDER BY B.BusinessType'
EXEC(@SQL)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  * FROM    dbo.sysobjects WHERE   id = OBJECT_ID(N'[dbo].[Web_QueryDelegationSettlementMxReport]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_QueryDelegationSettlementMxReport]
GO


/*
	日期：2013-12-05
	作者：duguolei
	描述：委托结算明细查询
	
*/
/*
	日期：2015-05-27
	修改：舒珊
	描述：添加商品类别筛选
	
	修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
	
*/

CREATE  PROCEDURE Web_QueryDelegationSettlementMxReport
    ( 
      @OperatorID		VARCHAR(100) ,
      @StartDate		VARCHAR(20) ,
      @EndDate			VARCHAR(20) ,
      @BTypeId			VARCHAR(8000) ,		--结算单位
      @PTypeId			VARCHAR(8000) ,
      @KTypeId			VARCHAR(8000) ,
      @STypeId			VARCHAR(8000) ,
      @ETypeId			VARCHAR(8000) ,
      @billcode			VARCHAR(8000) ,		--单据编号
      @Comment			VARCHAR(8000) ,		--摘要
      @Explain			VARCHAR(8000) ,		--说明
      @remark			VARCHAR(8000) ,		--备注
      @SettlementType	VARCHAR(10),		--结算类型 0全部，1完成，2未完成  完成标准为剩余基本单位数量为“0”
      @IsReporting		INT		,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
      @ptypecategoryid VARCHAR(MAX)    --商品类别ID
    )
--@encode$--
AS 
    SET NOCOUNT ON

-----------------------------------------------------     权限检查   -------------------------------------------------------------
IF @OperatorID IS NULL 
    RETURN 1
DECLARE @Re INT ,
    @MAtypeid VARCHAR(50) ,
    @MBtypeid VARCHAR(50) ,
    @MBtypeid2 VARCHAR(50) ,
    @MEtypeid VARCHAR(50) ,
    @MKtypeid VARCHAR(50) ,
    @MPtypeid VARCHAR(50) ,
    @MExpense VARCHAR(50) ,
    @MIncome VARCHAR(50) ,
    @MCapital VARCHAR(50) ,
    @MDtypeid VARCHAR(50) ,
    @MStypeid VARCHAR(50)
EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
    @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT, @MKtypeid OUTPUT,
    @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT, @MCapital OUTPUT,
    @MDtypeid OUTPUT, @MStypeid OUTPUT
IF @Re <> 0 
    RETURN @Re

---------------------------------------------------------   END   ------------------------------------------------------------------


----------------------------------------------------------创建零时表--------------------------------------------------------------

CREATE TABLE #Btype (TypeID varchar(200))
--CREATE TABLE #DEALBtype (TypeID varchar(200))
CREATE TABLE #Etype (TypeID varchar(200))
CREATE TABLE #Ktype (TypeID varchar(200))
CREATE TABLE #stype (TypeID varchar(200))
CREATE TABLE #ptype (typeid VARCHAR(200),usercode VARCHAR(300),fullname VARCHAR(300))




IF @btypeid =''
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorId) a
ELSE
	INSERT INTO #Btype select a.typeid from F_GetManDetailBType(@OperatorId) a, (select * from  dbo.f_split(@btypeid,',')) b where left(a.typeid,len(b.a))=b.a
	
--IF @dealbtypeid =''
--	INSERT INTO #DEALBtype select a.typeid from F_GetManDetailBType(@OperatorId) a
--ELSE
--	INSERT INTO #DEALBtype select a.typeid from F_GetManDetailBType(@OperatorId) a, (select * from  dbo.f_split(@dealbtypeid,',')) b where left(a.typeid,len(b.a))=b.a


IF @etypeid=''
	INSERT INTO #Etype(TypeId) SELECT TypeID FROM F_GetManDetailEType(@OperatorId) a 
ELSE
	INSERT INTO #Etype(TypeId) SELECT TypeID FROM F_GetManDetailEType(@OperatorId) a , (select * from  dbo.f_split(@etypeid,',')) b where left(a.typeid,len(b.a))=b.a

IF @ktypeid=''
BEGIN
	INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorId)
    INSERT  INTO #Ktype SELECT  '10000'
END
ELSE
	INSERT INTO #Ktype select a.typeid from F_GetManDetailKType(@OperatorId) a,  (select * from  dbo.f_split(@ktypeid,',')) b where left(a.typeid,len(b.a))=b.a

	
INSERT INTO #Stype (typeid) select typeid from F_GetAllManagerBaseTypeId(@STypeID,11,@OperatorID)


IF @ptypeid =''
	INSERT INTO #ptype (typeid) select a.typeid from F_LinePC(@OperatorID,@ptypecategoryid) a
ELSE
	INSERT INTO #ptype (typeid) select a.typeid from F_ManPTypeInCategoryID ( @OperatorID,@PtypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@ptypeid,',')) b where left(a.typeid,len(b.a))=b.a

DECLARE	@strPtype VARCHAR(1000)	
	SELECT @strPType='
			UPDATE #ptype SET usercode=p.UserCode, fullname=p.FullName
			from  (SELECT p2.typeId, p2.usercode, p2.fullname FROM ptype p2 ) p  
			INNER JOIN #ptype p1 ON p1.typeid=p.typeId 		'
EXEC(@strPtype)
--SELECT  * FROM  #Btype
--SELECT  * FROM  #stype
--SELECT  * FROM  #ktype
--SELECT  * FROM  #ptype
--SELECT  * FROM  #etype


CREATE TABLE #ptype_items
    (
      id VARCHAR(20) ,
      iscombined VARCHAR(20) ,
      fullname VARCHAR(50)
    )
    
    
    INSERT INTO #ptype_items
    SELECT  t.id,t.iscombined,t.fullname
    FROM 
    
    ( SELECT    1 AS IsCombined ,
                    c2.fullname AS NAME ,
                    REPLACE(c1.FullName, 'я', '/') AS FullName ,
                    c1.id
          FROM      CustomReferenceValue c1
                    INNER JOIN customPtypeItems c2 ON c1.itemsid = c2.id
          UNION ALL
          SELECT    0 AS IsCombined ,
                    s2.NAME AS NAME ,
                    s1.FullName ,
                    s1._Id AS id
          FROM      xw_SelfData s1
                    INNER JOIN xw_SelfDataType s2 ON s1.datatypeid = s2._id
          WHERE     ParTypeId <> 'root'
        ) t

------------------------------------------------------------     END     -------------------------------------------------------------------------

DECLARE 
@SQL			VARCHAR(max),
@SQL_WHERE		VARCHAR(5000)


--单据临时表
CREATE TABLE #Billindex
(
  BillNumberId		VARCHAR(200),
  BillCode			VARCHAR(500),
  BillDate			VARCHAR(100),
  dealbtypeid		VARCHAR(200),
  btypeid			VARCHAR(200),
  stypeid			VARCHAR(200),
  etypeid			VARCHAR(200),
  dtypeid			VARCHAR(200),
  ktypeid			VARCHAR(200),
  cid				VARCHAR(20),
  rate				VARCHAR(20),
  comment			VARCHAR(1000),
  explain			VARCHAR(1000),
  billtype			int	
)

SET @SQL='
	INSERT INTO  #Billindex
		  SELECT    
					b.billnumberid,
					b.BillCode ,
					b.BillDate ,
					b.dealbtypeid,
					b.btypeid,
					b.stypeid,
					b.etypeid,
					b.dtypeid,
					b.ktypeid, 
					b.cid,
					b.rate,
					b.comment,
					b.explain,billtype
		  FROM      dbo.BillIndex b '
  

     IF @btypeid <> ''  OR @MBTypeID = -99999 OR @MBTypeID2 = -99999 
        SET @SQL = @SQL + ' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '

     IF @etypeid <> ''  OR @METypeID = -99999 
        SET @SQL = @SQL + ' INNER JOIN #Etype e  ON b.etypeid=e.typeid '

     IF NOT ( @stypeid = '' AND @MStypeid = '00000') 
        SET @SQL = @SQL + ' INNER JOIN #Stype s  ON  b.stypeID=s.typeid '
      
        
 SET @SQL_WHERE=' WHERE b.billtype =140 AND b.RedWord = 0 AND b.BillDate>='+CHAR(39)+@startDate+CHAR(39)+' AND b.BillDate<='+CHAR(39)+@endDate+CHAR(39)+ '  AND b.IfCheck = '+CHAR(39)+'t'+CHAR(39)+' '
 
	IF @Comment<>''
		SET @SQL_WHERE = @SQL_WHERE + ' AND  b.comment like ''%'+@Comment+'%'''
		 
	IF @Explain<>''
		SET @SQL_WHERE = @SQL_WHERE + ' AND  b.explain like ''%'+@Explain+'%'''
	
	IF @billcode<>''
	   SET @SQL_WHERE = @SQL_WHERE + ' AND  b.billcode like ''%'+@billcode+'%'''
	
--PRINT(@SQL+@SQL_WHERE)	
EXEC(@SQL+@SQL_WHERE)
--SELECT  * FROM  #Billindex
		
 
  
        
--委托代销发货单--type=140   
CREATE TABLE #CommissionBill
(
	  billnumberid		VARCHAR(60),
	  detailid			VARCHAR(10),  --自定义明细id
	  BillCode			VARCHAR(500),
	  BillDate			DATETIME,
	  ptypeid			VARCHAR(100),
	  dealbtypeid		VARCHAR(200),
	  btypeid			VARCHAR(200),
	  Stypeid			VARCHAR(200),
	  munitrate			 NUMERIC(24, 10) ,	--销售单位换算率
	  mqty				 NUMERIC(24, 10) ,	--按单结算数量(销售单位)
	  qty				 NUMERIC(24, 10) ,	--发货数量(基本单位)
	  msaleprice			 NUMERIC(24, 10) ,	--销售价格(基本单位)
	  msaletotal			 NUMERIC(24, 10) ,	--销售总价格(基本单位)
	  jsqty				 NUMERIC(24, 10) ,	--按单结算数量(基本单位)
	  thqty				 NUMERIC(24, 10) ,	--退货数量(基本单位)
	  --syqty				 NUMERIC(24, 10) ,   --剩余基本单位数量=发货基本单位数量-已按单结算基本单位数量-已按单退货基本单位数量
	  
	  jsqtys				 NUMERIC(24, 10) ,	--按单结算数量(销售单位)
	  thqtys				 NUMERIC(24, 10) ,	--退货数量(销售单位)
	  --syqtys				 NUMERIC(24, 10) ,   --剩余销售单位数量=发货销售单位数量-已按单结算销售单位数量-已按单退货销售单位数量
	
	  etypeid				VARCHAR(60),
	  ktypeid				VARCHAR(60),
	  ktypeid1				VARCHAR(60),
	  dtypeid				VARCHAR(60),
	  cid					VARCHAR(20),--币种
	  rate					 NUMERIC(24, 10) ,--汇率
	  explain				VARCHAR(500),
	  comment				VARCHAR(500),
	  
	  serial				TEXT,  --序列号
	  cargoid				VARCHAR(100), --货位
	  itemid				VARCHAR(100),		--自由项
	  iscombined			VARCHAR(20),
	  producedate			VARCHAR(60),		--生产日期
	  validdate				VARCHAR(60),		--效期至
	  goodsnumber			VARCHAR(100),		--批号
	  munit					VARCHAR(60),		--销售单位
	  unit					VARCHAR(20),		--基本单位
	  saleprice			 NUMERIC(24, 10) ,			--基本单位单价
	  unitrate				 NUMERIC(24, 10) ,		--浮动换算率
	  nunit					VARCHAR(20),		--浮动计量单位
	  nqty					 NUMERIC(24, 10) ,		--浮动单位数量
	  discount				VARCHAR(20),		--扣率
	  mdiscountprice		 NUMERIC(24, 10) ,			--折后单价
	  discount_total		 NUMERIC(24, 10) ,			--折后金额
	  tax					NUMERIC(24, 10),		--税率
	  mtaxprice				 NUMERIC(24, 10) ,			--含税单价
	  ntaxtotal				 NUMERIC(24, 10) ,		--价税合计
	  saletotal			 NUMERIC(24, 10) ,		--本位币金额
	  ntotal				 NUMERIC(24, 10) ,		--本位币折后金额
	  taxmoney				 NUMERIC(24, 10) ,		--本位币税额
	  taxtotal				 NUMERIC(24, 10) ,		--本位币价税合计
	  remark				VARCHAR(8000),		--备注
	  billtype				INT
	 	  
)


SET @SQL = '
	INSERT INTO  #CommissionBill
			SELECT  
					distinct c.billnumberid AS billnumberid,
					c.id as detailid,  
					b.BillCode AS billcode,
					b.BillDate AS billdate,
					c.PtypeId AS ptypeid,
					b.dealbtypeid AS dealbtypeid,
					b.btypeid AS btypeid1,
					c.Stypeid AS stypeid1,
					c.munitrate, 
					c.mQty AS mqty,					--销售数量
					c.qty as qty,					--基本单位数量
					c.mSalePrice AS msaleprice,		--销售单价
					c.SaleTotal AS msaletotal,		--销售金额
					c.backqty AS jsqty,				--基本单位结算数量
					c.bqty AS thqty,				--基本单位退货数量
					--(c.qty-c.backqty-c.bqty) AS syqty,  --基本单位剩余数量

					c.backqty /ex.rate  as jsqtys, --销售单位结算数量
					c.bqty /ex.rate as thqtys, --销售单位退货数量 
					--(c.qty-c.backqty-c.bqty)/c.MUnitRate AS syqtys,
					
					b.etypeid,
					c.ktypeid as ktypeid1,
					b.ktypeid,
					b.dtypeid,
					b.cid,			--币种cid
					b.rate,			--汇率
					b.explain,
					b.comment,
					  
					c.serial ,			 --序列号
					c.cargoid ,			 --货位
					c.itemid ,			--自由项
					c.iscombined,
					c.producedate ,		--生产日期
					c.validdate ,		--效期至
					c.goodsnumber ,		--批号
					(SELECT fullname FROM dbo.PType_Units where unitsid=c.munitid) as munit,	--销售单位
					(SELECT fullname FROM dbo.PType_Units where unitsid=c.unitid) as unit ,		--基本单位
					c.saleprice ,			--基本单位单价
					c.unitrate ,			--浮动换算率
					(SELECT fullname FROM dbo.PType_Units where unitsid=c.nunitid) as nunit,	--浮动计量单位
					c.nqty ,				--浮动单位数量
					c.discount ,			--扣率
					c.curmdiscountprice ,		--折后单价
					c.ntotal as discount_total,--折后金额
					c.tax ,					--税率
					c.curMtaxprice ,			--含税单价
					c.ntaxtotal ,			--价税合计
					c.saletotal,			--本位币金额
					c.total,		--本位币折后金额
					c.taxmoney ,			--本位币税额
					c.taxtotal,				--本位币价税合计
					c.comment AS remark,
					b.billtype
			FROM  CommissionBill c INNER JOIN #Billindex b ON b.BillNumberId=c.BillNumberId
			left join ptype_units_ext ex on c.ptypeid=ex.ptypeid and c.munitid=ex.unitsid 
			  '
     IF @ptypeid <> '' OR @MPTypeID = -99999 OR @ptypecategoryid<>''
        SET @SQL = @SQL + '	INNER JOIN #Ptype p ON c.ptypeid=p.typeid ' + CHAR(13)
        
     IF @ktypeid <> '' OR @MKTypeID = -99999 
        SET @SQL = @SQL + '	INNER JOIN #Ktype k ON c.ktypeid=k.typeid ' + CHAR(13)
        
     
        
	 IF @remark<>''
		SET @SQL=@SQL + ' WHERE c.comment like ''%' + @remark ++'%'''
		
		
--PRINT(@SQL)	    
EXEC(@SQL)
--select * from #CommissionBill
--SELECT  * FROM  #Billindex

--委托代销结算单据临时表
--CREATE TABLE #jsCommissionBill
--(
--	billid    VARCHAR(20),
--	cid       VARCHAR(20),
--	jbjsqty    NUMERIC(24, 10) ,  --基本结算数量
--	jsqty      NUMERIC(24, 10)     --销售单位结算数量
--)

--INSERT  INTO #jsCommissionBill
--        SELECT  cm.OldBillNumberID AS billid ,
--                cm.OldID,
--                SUM(cm.Qty) AS jbjsqty ,
--                SUM(cm.mqty) AS jsqty
--        FROM    CommissionBill cm
--        INNER JOIN dbo.BillIndex b ON cm.BillNumberId=b.BillNumberId
--        WHERE   Type = 141  AND b.RedWord = 0 AND b.draft=0
--       GROUP BY OldBillNumberID,OldID

--UPDATE  #CommissionBill
--SET     jsqty = c1.jbjsqty ,
--        jsqtys = c1.jsqty
--FROM    #jsCommissionBill c1
--WHERE   c1.billid = billnumberid AND c1.cid=detailid


----委托代销退货单据临时表
--CREATE TABLE #thCommissionBill
--(
--	billid    VARCHAR(20),
--	cid       VARCHAR(20),
--	jbthqty    NUMERIC(24, 10) ,  --基本退货数量
--	thqty      NUMERIC(24, 10)     --销售单位退货数量
--)

--INSERT  INTO #thCommissionBill
--        SELECT  cm.OldBillid AS billid ,
--                cm.OldID,
--                SUM(cm.Qty) AS jbthqty ,
--                SUM(cm.mqty) AS thqty
--        FROM    CommissionBill cm
--         INNER JOIN dbo.BillIndex b ON cm.BillNumberId=b.BillNumberId 
--        WHERE   Type = 142  AND b.RedWord = 0 AND b.draft=0
--               GROUP BY OldBillid,OldID

--UPDATE  #CommissionBill
--SET     thqty = c1.jbthqty ,
--        thqtys = c1.thqty
--FROM    #thCommissionBill c1
--WHERE   c1.billid = billnumberid AND c1.cid= detailid


--SELECT  * FROM  #jsCommissionBill
--SELECT * FROM  #thCommissionBill
--select * from #CommissionBill



--最终出结果语句
SET @SQL = '
		SELECT  
				c.billnumberid,
				140 as billtype,
				CASE WHEN (c.qty-c.jsqty-c.thqty)=0 THEN ''完成'' ELSE ''未完成'' END AS state,  --剩余基本单位数量为“0” 显示为“完成”
				c.BillCode,
				c.BillDate,
				c.dealbtypeid,
				c.btypeid,
				c.ptypeid,
				c.stypeid,
				c.munitrate,
				c.mqty,
				c.qty,
				c.msaleprice,
				c.msaletotal,
				c.jsqtys,
				c.thqtys,
				(c.mqty-c.jsqtys-c.thqtys) as syqtys,  --剩余销售单位数量=发货销售单位数量-已按单结算销售单位数量-已按单退货销售单位数量
				
				c.jsqty,
				c.thqty,
				(c.qty-c.jsqty-c.thqty) as syqty,    --剩余基本单位数量=发货基本单位数量-已按单结算基本单位数量-已按单退货基本单位数量
				
				(select  fullname from employee where typeid=c.etypeid) as etypeid,
				(select  fullname from stock where typeid=c.ktypeid) as ktypeid,
				(select  fullname from stock where typeid=c.ktypeid1) as ktypeid1,
				(select  fullname from department where typeid=c.dtypeid) as dtypeid,
				(select  fullname from Ac_Currency where cid= c.cid) as cid,
				c.rate,
				c.explain,
				c.comment,
				--杨俊2013-04-03修改 以下2列为空，并且列名重复
				--cs.billnumberid,
				--cs.billtype,
			
				
				c.serial ,  
				(SELECT  fullname FROM dbo.CargoType where cargoid=c.cargoid)  as cargoid,    
				t.fullname as itemname ,			
				c.producedate ,	
				c.validdate ,
				c.goodsnumber ,
				c.munit,
				c.unit ,
				c.saleprice ,
				c.unitrate ,
				c.nunit,
				c.nqty ,
				c.discount ,
				c.mdiscountprice ,
				c.discount_total,
				c.tax ,
				c.ntaxtotal ,
				c.Mtaxprice ,
				c.saletotal as nsaletotal,
				c.ntotal,
				c.taxmoney ,
				c.taxtotal,
				c.remark, 
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
				SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
				SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
				SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
				SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
				SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	
		FROM   #CommissionBill c 
				left join Custom_BillIndex csindex on c.billnumberid=csindex.BillId and c.billtype=csindex.billtype
left join Custom_BillDetails csdetail on c.billnumberid=csdetail.BillId and c.billtype=csdetail.billtype AND c.detailid=csdetail.Detailid
				left JOIN #ptype_items t on t.id=c.itemid and t.iscombined=c.iscombined
				
		'
		




    IF @SettlementType = 1 
        SET @SQL = @SQL + ' WHERE (c.qty-c.jsqty-c.thqty)=0'
	   
    IF @SettlementType =2 
        SET @SQL = @SQL + ' WHERE (c.qty-c.jsqty-c.thqty)>0 '
        
     --SET @SQL=@SQL + ' ORDER BY BillDate,BillCode'

--PRINT(@SQL)
--EXEC(@SQL)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
	SET @SQL=@SQL + ' ORDER BY BillDate,BillCode'
	--PRINT @SQL
	EXEC(@SQL)
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
--	--生成rowid
--	SET @SQL = 'SELECT row_number() over (order by c.BillnumberID) as rowid,' + SUBSTRING(@SQL,CHARINDEX('SELECT',@SQL) + 6,LEN(@SQL))
--	CREATE TABLE #tmp_result
--	(
--		Costom1		VARCHAR(max),
--		Costom2		VARCHAR(max),
--		Costom3		VARCHAR(max),
--		Costom4		VARCHAR(max),
--		Costom5		VARCHAR(max),
--		Costom6		VARCHAR(max),
--		Costom7		VARCHAR(max),
--		Costom8		VARCHAR(max),
--		Costom9		VARCHAR(max),
--		Costom10	VARCHAR(max),
--		Costom11	VARCHAR(max),
--		Costom12	VARCHAR(max),
--		Costom13	VARCHAR(max),
--		Costom14	VARCHAR(max),
--		Costom15	VARCHAR(max),
--		Costom16	VARCHAR(max),
--		Costom1detail		varchar(max),
--		Costom2detail		varchar(max),
--		Costom3detail		varchar(max),
--		Costom4detail		varchar(max),
--		Costom5detail		varchar(max),
--		Costom6detail		varchar(max),
--		Costom7detail		varchar(max),
--		Costom8detail		varchar(max),
--		Costom9detail		varchar(max),
--		Costom10detail		varchar(max),
--		Costom11detail		varchar(max),
--		Costom12detail		varchar(max),
--		Costom13detail		varchar(max),
--		Costom14detail		varchar(max),
--		Costom15detail		varchar(max),
--		Costom16detail		varchar(max),
--		row_id				varchar(100)
--	)

--	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ORDER BY BillDate,BillCode' + 
--			  '  
--			   DECLARE @p1 dbo.Tb_QueryCustom  
--			   INSERT INTO @p1 SELECT billnumberid,billtype,CustomdetailID,row_number() over (order by BillnumberID) from #temp1 
--			   INSERT INTO #tmp_result EXEC Web_QueryCustomData @p1,2 

--				--显示最终结果
--				SELECT DISTINCT a.*,b.* 
--					  FROM #temp1 a 
--					  left join #tmp_result b on a.rowid=b.row_id
--					  ORDER BY BillDate,BillCode   
--				DROP TABLE #temp1,#tmp_result
--			   '
--	EXEC (@SQL)
--END
----------------------------------------------------------
DROP TABLE  #Btype , #Etype ,#Ktype ,#stype ,#ptype,#Billindex,#CommissionBill




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_QueryDeliveryBill]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_QueryDeliveryBill]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
作者:武智均 
时间:2019-12-04
描述:查询门店配送单或门店退货配送单
*/

CREATE PROCEDURE Web_QueryDeliveryBill
(
	@startdate		DATETIME,		--开始时间
	@enddate		DATETIME,		--结束时间
	@etypeid		VARCHAR(200),	--经手人
	@ktypeid		VARCHAR(200),	--出库仓库
	@ktypeidin		VARCHAR(200),	--要货仓库
	@billcode		VARCHAR(200),	--编号
	@billstate		VARCHAR(50),	--状态
	@comment		VARCHAR(200),	--摘要
	@explain		VARCHAR(200),	--说明		
	@operator		VARCHAR(50),	--操作人
	@billtype		VARCHAR(50),	--单据类型
	@ptypecode		VARCHAR(200)='',	--商品编号
	@stypeid		VARCHAR(200)	--分支机构
)
--@encode$--
AS
SET NOCOUNT ON

	DECLARE @SQL VARCHAR(MAX) 
	--状态表  
    create table #billexecstate(execstate int,billnumberid  NUMERIC(10, 0))
    create table #billnumberid(billnumberid  NUMERIC(10, 0))
    if @billtype = 327  --门店配送单 
	begin	
		insert into #billnumberid(billnumberid)
		select distinct pb.BillNumberId
		from PosAllotApplyBillIndex pb
		where pb.BillType = @billtype 
			and pb.RedWord = 0
			and pb.draft = 0
			and pb.ifcheck = 't'
			and (@ptypecode = '' or exists(select top 1 1 from  DeliveryBill b INNER JOIN ptype p ON b.PtypeId = p.typeId where b.BillNumberId = pb.billnumberid
			and p.UserCode LIKE @ptypecode+'%' ))

		insert into #billexecstate (execstate,billnumberid)
		select case when pb.Qty = m.gzQty then 10  --验收过账完成
					when pb.Qty = m.yyQty then 9  --验收未过账
					when m.yyQty = 0 or m.BillNumberId IS null then 8		--未引用
					else 6 end as execstate,  --已引用未完成
					pb.billnumberid
		from PosAllotApplyBillIndex pb
		inner join #billnumberid b on b.billnumberid = pb.BillNumberId
		left join (
			select BillNumberId,SUM(gzqty) as gzQty,SUM(yyQty) as yyQty 
			from 
			(
				select db.BillNumberId,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as gzQty,0 as yyQty from DeliveryBill db
				inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
				inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.RedWord = 0 and pabi.draft = 0
				union all
				select db.BillNumberId,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as gzQty,0 as yyQty from DeliveryBill db
				inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
				inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.RedWord = 0 and pabi.draft = 0
				union all 
				select db.BillNumberId, 0 as gzQty,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as yyQty from DeliveryBill db
				inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
				inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.RedWord = 0
				union all
				select db.BillNumberId,0 as gzQty,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as yyQty from DeliveryBill db
				inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
				inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.RedWord = 0
			) x
			group by BillNumberId
		) m on m.BillNumberId = pb.BillNumberId
	END
	ELSE IF @billtype = 328
	BEGIN
		insert into #billnumberid(billnumberid)
		select distinct pb.BillNumberId
		from PosAllotApplyBillIndex pb
		where pb.BillType = @billtype 
			and pb.RedWord = 0
			and (@ptypecode = '' or exists(select top 1 1 from  DeliveryBackBill b INNER JOIN ptype p ON b.PtypeId = p.typeId where b.BillNumberId = pb.billnumberid
			and p.UserCode LIKE @ptypecode+'%' ))
	END 
	--SELECT * FROM #billexecstate
	--SELECT * FROM #billnumberid
		
	IF @billtype = '327' --门店配送单
		BEGIN
			SET @SQL = '
			SELECT DISTINCT i.billnumberid,
					i.billcode,
					i.billtype,
					i.comment,
					i.explain,
					s.sid,
					k.kid outkid,
					k1.kid inkid,
					e.eid applyetypeid,
					e1.eid checkeid,e.fullname as efullname,
					CONVERT(varchar(10),i.billdate, 120) AS billdate,
					i.ktypeid,k.fullname as kfullname,k.kid as outkid,
					i.inktypeid as ktypeidin,k1.fullname as kfullnamein,k1.kid as inkid,
					i.BillState,
					BS.ExecState execstate,
					CASE 
					WHEN bs.execstate=10 THEN ''验收过账完成''  
					WHEN bs.execstate=9 THEN ''验收未过账'' 
					WHEN bs.execstate=8 THEN ''未引用'' 
					WHEN bs.execstate=7 THEN ''已完成'' 
					WHEN bs.execstate=6 THEN ''已引用未完成''  
					WHEN i.BillState=0 THEN ''原始单据'' 
					WHEN i.BillState=1 THEN ''已审核''
					WHEN i.BillState=2 THEN ''已接受''
					WHEN i.BillState=3 THEN ''已拒绝''
					WHEN i.BillState=4 THEN ''已作废'' 
					ELSE ''未引用'' END  as billstatename
			FROM PosAllotApplyBillIndex i 
			inner join #billnumberid b on b.billnumberid = i.BillNumberId
			left join #billexecstate bs on i.billnumberid = bs.billnumberid	
			LEFT JOIN stock k ON i.ktypeid=k.typeid 
			LEFT JOIN stock k1 ON i.inktypeid=k1.typeid 
			INNER JOIN Stype S ON i.StypeId = S.typeId
			LEFT JOIN Employee E ON i.ApplyEtypeId = E.typeId
			LEFT JOIN Employee E1 ON i.checke = E1.typeId
			'
		END
		
	IF @billtype = '328' --退货配送单
		BEGIN
			SET @SQL = '
			SELECT i.billnumberid,
					i.billcode,
					i.billtype,
					i.comment,
					i.explain,
					s.sid,
					--k.kid outkid,
					--k1.kid inkid,
					e.eid applyetypeid,
					e1.eid checkeid,e.fullname as efullname,
					CONVERT(varchar(10),i.billdate, 120) AS billdate,
					i.ktypeid,
					k.fullname as kfullnamein,
					k.kid as inkid,
					i.inktypeid as ktypeidin,
					k1.fullname as kfullname,
					k1.kid as outkid,
					'''+@billstate+''' billstate,
					CASE WHEN i.ifcheck = ''f'' THEN ''未引用'' 
					ELSE ''验收过账完成'' END  as billstatename
			FROM PosAllotApplyBillIndex i 
			INNER JOIN #billnumberid bi ON bi.billnumberid = I.billnumberid
			LEFT JOIN stock k ON i.inktypeid=k.typeid 
			LEFT JOIN stock k1 ON i.ktypeid=k1.typeid
			INNER JOIN Stype S ON i.StypeId = S.typeId
			LEFT JOIN Employee E ON i.ApplyEtypeId = E.typeId
			LEFT JOIN Employee E1 ON i.checke = E1.typeId'
		END

	--只有已接受的单据才能被调用
	SET @SQL += ' WHERE REDWORD = 0 AND i.billtype = '''+@billtype+''' AND i.billdate between '''+CONVERT(VARCHAR(10),@startdate,120)+''' AND '''+CONVERT(VARCHAR(10),@enddate,120)+''' '

	IF @billtype = '327' AND ISNULL(@billstate,'') <> '' AND @billstate <> '0'
	BEGIN
		IF @billstate = '6,8'
			SET @SQL += ' AND (BS.ExecState = 6 OR BS.ExecState = 8)  '
		ELSE
			SET @SQL += ' AND BS.ExecState =  '+@billstate
	END 
	IF @billtype = '328' AND @billstate <> '0'
	BEGIN
		IF @billstate = '8' 
			SET @SQL += ' AND I.ifcheck = ''f'' '
		IF @billstate = '10' 
			SET @SQL += ' AND I.ifcheck = ''t'' '
	END 
	
	IF ISNULL(@ktypeid,'') <> ''
	BEGIN
		SET @SQL += ' AND i.ktypeid='''+@ktypeid+''''
	END
	IF ISNULL(@ktypeidin,'') <> ''
	BEGIN
		SET @SQL += ' AND i.inktypeid='''+@ktypeidin+''''
	END
	IF ISNULL(@billcode,'') <> ''
	BEGIN
		SET @SQL += ' AND i.billcode like ''%'+@billcode+'%'''
	END

	-- 摘要
	IF ISNULL(@comment,'')<>''
	BEGIN
		SET @SQL += ' AND i.comment like ''%'+@comment+'%'''
	END
	IF ISNULL(@explain,'')<>''
	BEGIN
		SET @SQL += ' AND i.explain like ''%'+@explain+'%'''
	END
	IF ISNULL(@stypeid,'')<>''
	BEGIN
		SET @SQL += ' AND i.stypeid='''+@stypeid+''''
	END
	IF ISNULL(@etypeid,'')<>''
	BEGIN
		SET @SQL += ' AND i.checke='''+@etypeid+''''
	END
	
	SET @SQL += ' ORDER BY i.BillCode '
	
	--print @sql
	EXEC(@SQL)
	
	DROP TABLE #billexecstate,#billnumberid

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[Web_QueryDeliveryBillDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_QueryDeliveryBillDetail]
GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
作者:武智均 
时间:2019-12-04
描述:查询门店配送单或门店退货配送单详情
*/

CREATE PROCEDURE Web_QueryDeliveryBillDetail
(
	@billnumberid	VARCHAR(50),
	@billtype		VARCHAR(50),	--单据类型
	@operator		VARCHAR(50)		--操作人
)
--@encode$--
AS
SET NOCOUNT ON 

	DECLARE @SQL VARCHAR(MAX)
	IF @billtype = '327' --查询门店配送单表体
		SET @SQL = '
		SELECT D.Billnumberid billnumberid,
		p.pid,
		D.id,
		P.UserCode usercode,
		P.FullName fullname,
		P.Standard standard,
		P.Type type,
		D.itemid itemid,
		vi.fullname as itemname,
		D.UnitId unitid,
		PU.FullName AS unit,
		D.Qty qty,
		D.Price price,
		D.Total total,
		0 currentcheckqty,
		D.checkqty,
	    D.backqty,
		D.Qty - D.backqty - D.checkqty notcheckqty,
		(SELECT ISNULL(SUM(DB.Qty),0) FROM dbo.DeliveryBackBill DB INNER JOIN PosAllotApplyBillIndex PAB ON PAB.BillNumberId = DB.BillNumberId WHERE DB.DeliveryID = D.ID AND PAB.ifcheck = ''f'' ) notpostingbackqty,
		D.Comment comment
		FROM PosAllotApplyBillIndex PA
		INNER JOIN DeliveryBill D ON PA.Billnumberid = D.Billnumberid
		left join vWeb_ItemIDByIsCombined vi on vi.id = D.ItemID and vi.iscombined = D.IsCombined
		INNER JOIN Ptype P ON D.PtypeId = P.typeId
		INNER JOIN PType_Units PU ON D.UnitId=PU.UnitsId 
		WHERE PA.BillType = '+@billtype+' AND PA.Billnumberid = '+@billnumberid+'
		'

	IF @billtype = '328' --查询退货配送单表体
		SET @SQL = '
		SELECT D.Billnumberid billnumberid,
		D.PtypeId pid,
		D.id,
		P.UserCode usercode,
		P.FullName fullname,
		P.Standard standard,
		P.Type type,
		D.itemid itemid,
		vi.fullname as itemname,
		D.UnitId unitid,
		PU.FullName AS unit,
		D.Qty qty,
		D.Price price,
		D.Total total,
		D.Comment comment
		FROM PosAllotApplyBillIndex PA
		INNER JOIN DeliveryBackBill D ON PA.Billnumberid = D.Billnumberid
		left join vWeb_ItemIDByIsCombined vi on vi.id = D.ItemID and vi.iscombined = D.IsCombined
		INNER JOIN Ptype P ON D.PtypeId = P.typeId
		INNER JOIN PType_Units PU ON D.UnitId=PU.UnitsId
		WHERE PA.BillType = '+@billtype+' AND PA.Billnumberid = '+@billnumberid+'
		'
	--print @sql
	EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryDeliveryCheckList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryDeliveryCheckList]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE Web_QueryDeliveryCheckList
(
	@OperatorID 	VARCHAR(100),	--操作员的ID
	@StartDate		VARCHAR(50),	--开始日期
	@EndDate		VARCHAR(50),	--结束日期
	@StypeId		VARCHAR(8000),	--分支机构
	@BillCode		VARCHAR(200)='',	--单据编号
	@EtypeID		VARCHAR(8000),	--职员的ID
	@DtypeID		VARCHAR(8000),	--部门的ID
	@OutKtypeId		VARCHAR(8000),	--仓库的ID（出库）
	@InKtypeId		VARCHAR(8000),	--仓库的ID（要库）
	@ptypeCategoryid	VARCHAR(max), --商品类别
	@PtypeID		VARCHAR(8000),	--商品的ID
	@Comment		VARCHAR(8000)='',	--摘要
	@Explain		VARCHAR(8000)='',	--说明
	@Remark			VARCHAR(8000)='',	--备注
	@BillState		int=1,			--单据状态，默认未完成
	@showredword	int=1			--是否显示红冲
)
--@encode$--
AS
	
SET ANSI_WARNINGS OFF
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
           @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
--部门
Create TABLE  #DType(typeid VARCHAR(100))
INSERT INTO #DType SELECT typeid  FROM F_GetAllManagerBaseTypeId(@DtypeID,9,@OperatorID)

--选择分支机构
CREATE TABLE #SType(TypeId	VARCHAR(100))
INSERT INTO #SType(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID)


--职员
CREATE TABLE #EType(TypeId	VARCHAR(100))
INSERT INTO #EType(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@EtypeID,3) WHERE TypeId IN (SELECT TypeId FROM F_GetManDetailEType(@OperatorID))

--仓库
CREATE TABLE #KTypeId(TypeId	VARCHAR(100))

DECLARE @limt INT 
Exec @limt= GP_CheckLimit @OperatorID,454

IF @MKtypeid='-99999' AND @limt=0
BEGIN
	INSERT INTO #KTypeId(TypeId) SELECT TypeId FROM F_GetMANDetailKType(@OperatorID)
END

--仓库（出库）
CREATE TABLE #KType(TypeId	VARCHAR(100)) 
IF @MKtypeid='-99999' AND @limt=0  AND @OperatorID<>'00001'
BEGIN
	INSERT INTO #KType(TypeId) 
	SELECT sk.TypeId FROM F_GetAllBaseTypeId(@OutKtypeId,4) sk INNER JOIN #KTypeId k ON sk.typeid=k.typeid
END
ELSE
BEGIN
	INSERT INTO #KType(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@OutKtypeId,4)
END

--仓库（要库）
CREATE TABLE #KType1(TypeId	VARCHAR(100))
IF @MKtypeid='-99999' AND @limt=0 AND @OperatorID<>'00001'
BEGIN
	INSERT INTO #KType1(TypeId) 
	SELECT sk.TypeId FROM F_GetAllBaseTypeId(@InKtypeId,4) sk INNER JOIN #KTypeId k ON sk.typeid=k.typeid
END
ELSE
BEGIN
	INSERT INTO #KType1(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@InKtypeId,4)
END


DECLARE @SQL varchar(max)
CREATE TABLE  #PType
(
  typeid VARCHAR(50),
  usercode VARCHAR(200),
  fullname VARCHAR(200),
  sonnum INT,
  parid  VARCHAR(50),
  DELETED INT,
  SortID INT
)

IF  @ptypeCategoryid<>''
BEGIN
	SET @SQL='INSERT INTO #PType  
		SELECT DISTINCT p.typeid,usercode,FullName,sonnum,ParId,deleted,SortID 	
		FROM dbo.ptype  p
		INNER JOIN dbo.F_LinePC('''+@OperatorID+''','''+@ptypeCategoryid+''') b ON b.typeid LIKE p.typeId+''%''
		WHERE p.IsService=0
			AND p.iscombinationproduct = 0'
	IF @PtypeID<>'00000' and @PtypeID<>''
		SET @SQL+=' AND P.typeid = '''+@PtypeID+''''
END
ELSE
BEGIN
	SET @SQL='INSERT INTO #PType  
		SELECT 	typeid,usercode,FullName,sonnum,ParId,deleted,SortID  
		FROM	F_GetManPTypeAll('''+@OperatorID+''') p
		WHERE	p.IsService=0
			AND p.iscombinationproduct = 0'
	IF @PtypeID<>'00000' and @PtypeID<>''
		SET @SQL+=' AND P.typeid = '''+@PtypeID+''''
END
--print @SQL
EXEC(@SQL)

create table #BillState(execstate int,billnumberid  NUMERIC(10, 0))
insert into #BillState (execstate,billnumberid)
select case when pb.Qty = isnull(m.gzQty,0) then 10  --验收过账完成
			when pb.Qty = isnull(m.yyQty,0) then 9  --验收未过账
			when isnull(m.yyQty,0) = 0 then 8		--未引用
			else 6 end as execstate,  --已引用未完成
			pb.billnumberid
from PosAllotApplyBillIndex pb
inner join DeliveryBill b on b.billnumberid = pb.BillNumberId
left join (
	select BillNumberId,SUM(gzqty) as gzQty,SUM(yyQty) as yyQty 
	from 
	(
		select db.BillNumberId,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as gzQty,0 as yyQty from DeliveryBill db
		inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
		inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.RedWord = 0 and pabi.draft = 0
		union all
		select db.BillNumberId,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as gzQty,0 as yyQty from DeliveryBill db
		inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
		inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.RedWord = 0 and pabi.draft = 0
		union all 
		select db.BillNumberId, 0 as gzQty,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as yyQty from DeliveryBill db
		inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
		inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.RedWord = 0
		union all
		select db.BillNumberId,0 as gzQty,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as yyQty from DeliveryBill db
		inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
		inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.RedWord = 0
	) x
	group by BillNumberId
) m on m.BillNumberId = pb.BillNumberId
group by pb.billnumberid,pb.Qty,m.gzQty,m.yyQty



set @SQL='
select t.billnumberid,t.billcode,t.billdate,t.stypeid,t.billstate,t.billname,t.billtype,t.etypeid,t.dtypeid,t.inktypeid,
t.outktypeid,sum(t.qty) as qty,sum(t.total) as total,sum(t.checkqty) as checkqty,sum(t.wwcqty) as wwcqty,
sum(t.backqty) as backqty,sum(t.draftbackqty) as draftbackqty,t.Comment,t.Explain from 
(
	select pIndex.billnumberid,pIndex.billdate,pIndex.billcode,s.typeid as stypeid,pIndex.billtype,''门店配送单'' billname,
		case bs.execstate when 8 then ''未引用'' when 6 then ''已引用未完成'' when 9 then ''验收未过账'' when 10 then ''验收过账完成'' end billstate,
		e.typeid as etypeid,d.typeid as dtypeid,k1.typeid as inktypeid,k.typeid as outktypeid,
		bill.qty,bill.total,dbo.F_RoundQty(bill.CheckQty/bill.MUnitRate) as checkqty,
		dbo.F_RoundQty((bill.qty-bill.CheckQty-back.thqyt)/bill.MUnitRate) as wwcqty,
		dbo.F_RoundQty(isnull((isnull(back.thqyt,0)+isnull(back.thwgzqyt,0))/bill.MUnitRate,0)) as backqty,
		dbo.F_RoundQty(isnull(back.thwgzqyt/bill.MUnitRate,0)) as draftbackqty,
		pIndex.Comment,pIndex.Explain
	from PosAllotApplyBillIndex pIndex 
	inner join DeliveryBill bill on pIndex.BillNumberId=bill.BillNumberId
	inner join #SType s on pIndex.stypeid=s.typeid
	inner join #EType e on pIndex.ApplyEtypeId=e.typeid
	inner join #DType d on pIndex.dtypeid=d.typeid
	inner join #KType1 k1 on pIndex.inKtypeId=k1.typeid
	inner join #KType k on pIndex.KtypeId=k.typeid
	inner join #PType p on bill.ptypeid=p.typeid
	inner join #BillState bs on pIndex.BillNumberId=bs.BillNumberId
	left join 
	(
		select dbb.DeliveryID,sum(case when b.draft = 0 then dbb.Qty else 0 end) as thqyt,sum(case when b.draft = 1 then dbb.Qty else 0 end) as thwgzqyt
		from DeliveryBackBill dbb
		inner join PosAllotApplyBillIndex b on b.BillNumberId = dbb.BillNumberId
		inner join DeliveryBill db on db.ID = dbb.DeliveryID	
		group by dbb.DeliveryID		
	) back on back.DeliveryID = bill.ID 
	where pIndex.draft=0'


if @StartDate<>'' set @SQL+=' and pIndex.billdate>='''+@StartDate+''''
if @EndDate<>'' set @SQL+=' and pIndex.billdate<='''+@EndDate+''''
if @BillCode<>'' set @SQL+=' and pIndex.billcode like ''%'+@BillCode+'%''' 
if @Comment<>'' set @SQL+=' and pIndex.comment like ''%'+@Comment+'%'''
if @Explain<>'' set @SQL+=' and pIndex.explain like ''%'+@Explain+'%'''
if @Remark<>'' set @SQL+=' and bill.Comment like ''%'+@Remark+'%'''
if @BillState<>0
begin
	if @BillState=1 set @SQL+=' and bs.execstate in(6,8)'
	else set @SQL+=' and bs.execstate ='+cast(@BillState as varchar(10))+''
end
IF @showredword = 0 SET @SQL = @SQL + ' and pIndex.RedWord = 0 '

set @SQL+=' ) t
			group by t.billnumberid,t.billcode,t.billdate,t.stypeid,t.billtype,t.billstate,t.etypeid,t.dtypeid,t.inktypeid,
				t.outktypeid,t.Comment,t.Explain,t.billtype,t.billname'

exec(@SQL)
--print @SQL

drop table #SType,#EType,#DType,#KType1,#KType,#PType,#BillState,#KTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryDeliveryDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryDeliveryDetail]
GO

/*
	作者：
	日期：
	描述：商品配送统计树形表
*/

CREATE           PROCEDURE [Web_QueryDeliveryDetail] 
(
	@OperatorID 	VARCHAR(100),	--操作员的ID
	@StartDate		VARCHAR(50),	--开始日期
	@EndDate		VARCHAR(50),	--结束日期
	@StypeId		VARCHAR(8000),
	@ptypeCategoryid	VARCHAR(max), --商品类别
	@PtypeID		VARCHAR(8000),	--商品的ID
	@EtypeID		VARCHAR(8000),	--职员的ID
	@DtypeID		VARCHAR(8000),	--部门的ID
	@KtypeID		VARCHAR(8000),	--仓库的ID（出库）
	@KtypeID1		VARCHAR(8000),	--仓库的ID（要库）
	@BillType		VARCHAR(50),	--单据类型
	@redword		VARCHAR(10)='0'	--是否显示红冲单据 0.不显示 1.显示
	--@SortFild		VARCHAR(50)='',	--排序字段
	--@SortKind		INT=1			--排序方式   0.升序  1.倒序
)
--@encode$--
AS

SET ANSI_WARNINGS OFF
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
           @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
--部门
Create TABLE  #DtypeId(typeid VARCHAR(100))
INSERT INTO #DtypeId SELECT typeid  FROM F_GetAllManagerBaseTypeId(@DtypeID,9,@OperatorID)

--选择分支机构
CREATE TABLE #STypeId(TypeId	VARCHAR(100))
INSERT INTO #STypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID)
	
----商品
SELECT TypeId INTO #ptype FROM F_GetAllManagerBaseTypeId(@PtypeId,1,@OperatorID) a --商品权限


--职员
DECLARE @Etypelimt INT 
Exec @Etypelimt= GP_CheckLimit @OperatorID,4481
CREATE TABLE #ETypeId(TypeId	VARCHAR(100))
IF @Etypelimt=0
BEGIN
	INSERT INTO #ETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)
END	
ELSE
BEGIN
	SET @ETypeID = '00001'
	INSERT INTO #ETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeID,3)
END	

--仓库
CREATE TABLE #KTypeId(TypeId	VARCHAR(50))
CREATE TABLE #KTypeIdIn(TypeId	VARCHAR(50))

DECLARE @limt INT ,
		@checkStock VARCHAR(200)
SELECT @limt = Value FROM dbo.Userconfig WHERE ConfigName = 'postransktypelimit'
SET @checkStock = ''

INSERT INTO #KTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)
INSERT INTO #KTypeIdIn(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid1,4,@OperatorID)

IF @limt = 0
BEGIN
	INSERT INTO #KTypeId(TypeId)
	SELECT TypeId
	FROM dbo.Stock s 
	INNER JOIN (SELECT a FROM dbo.f_split(@KtypeID,',')) f ON s.typeId LIKE f.a+'%'
	
	INSERT INTO #KTypeIdin(TypeId)
	SELECT TypeId
	FROM dbo.Stock s 
	INNER JOIN (SELECT a FROM dbo.f_split(@KtypeID1,',')) f ON s.typeId LIKE f.a+'%'
END
	
IF @MKtypeid='-99999' AND @OperatorID<>'00001'  
BEGIN
	
	IF @limt = 1
		SET @checkStock = ' AND (EXISTS (SELECT TOP 1 1 FROM #KTypeId WHERE TypeId = t.ktypeid) AND EXISTS (SELECT TOP 1 1 FROM #KTypeIdIn WHERE TypeId = t.inktypeid))'
	ELSE
		SET @checkStock = ' AND (EXISTS (SELECT TOP 1 1 FROM #KTypeId WHERE TypeId = t.ktypeid) OR EXISTS (SELECT TOP 1 1 FROM #KTypeIdIn WHERE TypeId = t.inktypeid))'
END


create table #billexecstate(execstate int,billnumberid  NUMERIC(10, 0))

--IF @redword = '0'
--BEGIN
	insert into #billexecstate (execstate,billnumberid)
	select case when pb.Qty = m.gzQty then 10  --验收过账完成
				when pb.Qty = m.yyQty then 9  --验收未过账
				--WHEN M.YYQTY = 0 OR M.BillNumberId IS NULL THEN 8		--未引用
				WHEN M.BillNumberId IS NULL THEN
				(CASE WHEN  ISNULL(de.decheckqty,0) = 0 and  ISNULL(de.debackqty,0) =0  THEN 8 ELSE 6 END )
				else 6 end as execstate,  --已引用未完成
				pb.billnumberid
	from PosAllotApplyBillIndex pb
	LEFT JOIN (
		SELECT	de.BillNumberId,
				SUM(de.Qty) as deQty,
				SUM(checkqty) as decheckqty,
				SUM(Backqty) as debackqty
		FROM	DeliveryBill  de
		INNER JOIN PosAllotApplyBillIndex pob on pob.BillNumberId=de.BillNumberId
		where pob.RedWord=0
		group by de.BillNumberId
	)de on de.BillNumberId=pb.BillNumberId
	left join (
		select BillNumberId,SUM(gzqty) as gzQty,SUM(yyQty) as yyQty 
		from 
		(
			select db.BillNumberId,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as gzQty,0 as yyQty from DeliveryBill db
			inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
			inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.RedWord = 0 and pabi.draft = 0
			union all
			select db.BillNumberId,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as gzQty,0 as yyQty from DeliveryBill db
			inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
			inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.RedWord = 0 and pabi.draft = 0
			union all 
			select db.BillNumberId, 0 as gzQty,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as yyQty from DeliveryBill db
			inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
			inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.RedWord = 0
			union all
			select db.BillNumberId,0 as gzQty,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as yyQty from DeliveryBill db
			inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
			inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.RedWord = 0
		) x
		group by BillNumberId
	) m on m.BillNumberId = pb.BillNumberId
--END
--ELSE
--BEGIN
--	insert into #billexecstate (execstate,billnumberid)
--	select case when pb.Qty = m.gzQty then 10  --验收过账完成
--				when pb.Qty = m.yyQty then 9  --验收未过账
--				when m.yyQty = 0 or m.BillNumberId IS null then 8		--未引用
--				else 6 end as execstate,  --已引用未完成
--				pb.billnumberid
--	from PosAllotApplyBillIndex pb
--	left join (
--		select BillNumberId,SUM(gzqty) as gzQty,SUM(yyQty) as yyQty 
--		from 
--		(
--			select db.BillNumberId,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as gzQty,0 as yyQty from DeliveryBill db
--			inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
--			inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId and pabi.draft = 0
--			union all
--			select db.BillNumberId,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as gzQty,0 as yyQty from DeliveryBill db
--			inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
--			inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId and pabi.draft = 0
--			union all 
--			select db.BillNumberId, 0 as gzQty,case when db.Qty < dbb.Qty then db.Qty else dbb.Qty end as yyQty from DeliveryBill db
--			inner join DeliveryBackBill dbb on dbb.DeliveryID = db.ID  --门店配送退货单
--			inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dbb.BillNumberId
--			union all
--			select db.BillNumberId,0 as gzQty,case when db.Qty < dcb.Qty then db.Qty else dcb.Qty end as yyQty from DeliveryBill db
--			inner join DeliveryCheckBill dcb on dcb.DeliveryID = db.ID  --门店配送验收单
--			inner join PosAllotApplyBillIndex pabi on pabi.BillNumberId = dcb.BillNumberId
--		) x
--		group by BillNumberId
--	) m on m.BillNumberId = pb.BillNumberId
--END	



DECLARE @SQL varchar(max)

set @SQL='SELECT	t.BillnumberId,
					T.BillDate,
					T.BillCode, 
					t.billtype,
					CASE T.BillType WHEN 327 THEN ''门店配送单'' WHEN 328 THEN ''门店配送退货单'' END BillName,
					T.BillState,
					ISNULL(T.Qty,0) AS Qty,
					ISNULL(T.CheckQty,0) AS CheckQty,
					ISNULL(T.NoAcceptQty,0) AS NoAcceptQty,
					ISNULL(T.BackQty,0) AS BackQty,
					ISNULL(T.DraftQty,0) AS DraftQty,
					ISNULL(T.DeliveryPrice,0) AS DeliveryPrice,
					ISNULL(T.DeliveryTotal,0) AS DeliveryTotal,
					ISNULL(T.DeliveryCost,0) AS DeliveryCost,
					isnull(T.MQty,0) AS deliveryqty,
					isnull(T.basedeliveryprice,0) as basedeliveryprice,
					T.Explain,
					T.Comment,
					T.Remark,
					P.typeId as ptypeid,
					E.typeId AS EtypeId,
					S.typeId AS stypeid,
					D.typeId as dtypeid,
					k1.typeid as inktypeid,
					K1.FullName as inkfullname,
					k.typeid as outktypeid,
					K.FullName as outkfullname,
					c1.FullName as incargofullname,
					c.FullName as outcargofullname,
					baseunit.FullName AS BaseUnit,
					stockunit.FullName as StockUnit,
					T.redword
FROM(
		SELECT	a.billnumberid,
				A.BillDate,
				A.BillCode,
				A.BillType,
				A.ApplyEtypeId,
				A.StypeId,
				A.DtypeId,
				A.KtypeId,
				A.InKtypeId,
				B.PtypeId,
				CASE WHEN bs.execstate=10 THEN ''验收过账完成''  
				WHEN bs.execstate=9 THEN ''验收未过账'' 
				WHEN bs.execstate=8 THEN ''未引用'' 
				WHEN bs.execstate=6 THEN ''已引用未完成''   END BillState,
				CASE WHEN A.RedWord in (0,1) THEN
				B.Qty ELSE
				-B.Qty END as Qty,
				CASE WHEN A.RedWord in (0,1) THEN
				CAST(B.CheckQty AS VARCHAR(20)) ELSE
				CAST(-B.CheckQty AS VARCHAR(20)) END as CheckQty,
				CASE WHEN A.RedWord in (0,1) THEN
				(ISNULL(B.Qty,0)-ISNULL(B.CheckQty,0)-ISNULL(B.BackQty,0)-ISNULL(D.thwgzqyt,0)) ELSE
				-(ISNULL(B.Qty,0)-ISNULL(B.CheckQty,0)-ISNULL(B.BackQty,0)-ISNULL(D.thwgzqyt,0)) END AS NoAcceptQty,
				CASE WHEN A.RedWord in (0,1) THEN
				CAST(B.BackQty+isnull(D.thwgzqyt,0) AS VARCHAR(20)) ELSE
				CAST(-B.BackQty+isnull(D.thwgzqyt,0) AS VARCHAR(20)) END AS BackQty,
				CASE WHEN A.RedWord in (0,1) THEN
				CAST(D.thwgzqyt AS VARCHAR(20)) ELSE
				CAST(-D.thwgzqyt AS VARCHAR(20)) END AS DraftQty,
				B.MPrice AS DeliveryPrice,
				CASE WHEN A.RedWord in (0,1) THEN
				B.Total ELSE
				-B.total END AS DeliveryTotal,
				CASE WHEN A.RedWord in (0,1) THEN
				B.MQty ELSE
				-B.MQty END as MQty,
				CASE WHEN A.RedWord in (0,1) THEN
				B.GoodsCostTotal ELSE 
				-B.GoodsCostTotal END AS DeliveryCost,
				A.Explain,
				A.Comment,
				B.Comment AS Remark,
				B.MUnitID,
				B.UnitID,
				b.price as basedeliveryprice,
				A.RedWord,
				b.CargoIdOut as outCargoID,
				b.CargoIdIn as inCargoID,
				A.Ifcheck
		FROM PosAllotApplyBillIndex A
		INNER JOIN DeliveryBill B ON A.BillNumberId=B.BillNumberId			--门店配送单
		LEFT JOIN (
			select dbb.DeliveryID,sum(case when b.draft = 0 then dbb.Qty else 0 end) as thqyt,sum(case when b.draft = 1 then dbb.Qty else 0 end) as thwgzqyt
			from DeliveryBackBill dbb
			inner join PosAllotApplyBillIndex b on b.BillNumberId = dbb.BillNumberId AND b.RedWord=0
			inner join DeliveryBill db on db.ID = dbb.DeliveryID	
			group by dbb.DeliveryID	) D ON B.ID=D.DeliveryID		--门店配送退货单
		left join #billexecstate bs on bs.billnumberid=a.billnumberid
		

		UNION ALL

		SELECT	a.billnumberid,
				A.BillDate,
				A.BillCode,
				A.BillType,
				A.ApplyEtypeId,
				A.StypeId,
				A.DtypeId,
				A.KtypeId,
				A.InKtypeId,
				B.PtypeId,
				CASE	WHEN  A.ifcheck = ''f'' AND A.redword=0 THEN ''未引用'' 
						WHEN  A.ifcheck = ''t'' AND A.redword=0 THEN ''验收过账完成'' 
						WHEN  (A.ifcheck = ''t'') AND (A.redword=1 OR A.redword=2) THEN ''已过账'' 
				END as BillState,
				CASE WHEN A.RedWord in (0,1) THEN
				-B.Qty
				ELSE B.qty END as Qty,
				''-'' AS CheckQty,
				CASE A.Draft WHEN 0 THEN 0 ELSE B.Qty END AS NoAcceptQty,
				''-'' AS BackQty,
				''-'' AS DraftQty,
				B.Price AS DeliveryPrice,
				CASE WHEN A.RedWord in (0,1) THEN
				-B.Total 
				ELSE B.Total END AS DeliveryTotal,
				CASE WHEN A.RedWord in (0,1) THEN
				-B.MQty
				ELSE B.MQty END as MQty,
				CASE WHEN A.RedWord in (0,1) THEN
				-B.GoodsCostTotal ELSE
				B.GoodsCostTotal END AS DeliveryCost,
				A.Explain,
				A.Comment,
				B.Comment AS Remark,
				B.MUnitID,
				B.UnitID,
				b.price as basedeliveryprice,
				A.RedWord,
				b.outCargoID,
				b.inCargoID,
				A.Ifcheck
		FROM PosAllotApplyBillIndex A
		INNER JOIN DeliveryBackBill B ON A.BillNumberId=B.BillNumberId
		left join #billexecstate bs on bs.billnumberid=a.billnumberid
	) T
INNER JOIN #ptype P ON P.typeid=t.PtypeId
INNER JOIN PType_Units baseunit ON T.UnitId=baseunit.UnitsId 
INNER JOIN PType_Units stockunit ON T.MUnitID=stockunit.UnitsId
INNER JOIN #ETypeId E ON E.typeid=T.ApplyEtypeId
INNER JOIN #DtypeId D ON D.typeid=T.DtypeId
LEFT JOIN STOCK K ON K.typeId=T.KtypeId
LEFT JOIN STOCK K1 ON K1.typeId=T.InKtypeId
INNER JOIN CargoType C ON C.CargoId=T.outCargoID
INNER JOIN CargoType C1 ON C1.CargoId=T.inCargoID
INNER JOIN #STypeId S ON S.typeId=T.StypeId
WHERE 1=1 AND T.IfCheck=''t''
'
IF @StartDate<>''
	SET @SQL+=' AND T.BillDate>='''+@StartDate+''''
IF @EndDate<>''
	SET @SQL+=' AND T.BillDate<='''+@EndDate+''''
IF @BillType<>'' and @billType<>'-1'
	SET @SQL+=' AND T.BillType IN('+@BillType+')'
	
IF @redword = '0'
	SET @SQL += ' AND T.RedWord = 0 '	
	
IF ISNULL(@ktypeid,'') <> ''
	SET @SQL += ' AND t.ktypeid IN (SELECT typeid FROM #ktypeid) '
	
if isnull(@ktypeid1,'') <> ''
	set @sql += ' AND t.InKtypeId IN (SELECT typeid FROM #ktypeidin) ' 

	
SET @SQL += @checkStock	
SET @SQL += ' ORDER BY T.BillDate DESC,T.BillCode DESC '	

--PRINT @SQL
EXEC(@SQL)
					
DROP TABLE #ETypeId,#KTypeId,#KTypeIdIn,#STypeId,#DtypeId,#ptype,#billexecstate
															
															
																
GO															
SET QUOTED_IDENTIFIER OFF									
GO															
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryDeliveryTree]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryDeliveryTree]
GO

/*
	作者：
	日期：
	描述：商品配送统计树形表
*/

CREATE           PROCEDURE [Web_QueryDeliveryTree] 
(
	@OperatorID 	VARCHAR(100),	--操作员的ID
	@StartDate		VARCHAR(50),	--开始日期
	@EndDate		VARCHAR(50),	--结束日期
	@StypeId		VARCHAR(8000),
	@ptypeCategoryid	VARCHAR(max), --商品类别
	@PtypeID		VARCHAR(8000),	--商品的ID
	@EtypeID		VARCHAR(8000),	--职员的ID
	@DtypeID		VARCHAR(8000),	--部门的ID
	@KtypeID		VARCHAR(8000),	--仓库的ID（出库）
	@KtypeID1		VARCHAR(8000),	--仓库的ID（要库）
	@ifLine		char(1) ='0'                  -- 0 代表树形表，1代表线性表
	--@SortFild		VARCHAR(50)='',	--排序字段
	--@SortKind		INT=1			--排序方式   0.升序  1.倒序
)
--@encode$--
AS

SET ANSI_WARNINGS OFF
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
           @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
--部门
Create TABLE  #GetMANDtype(typeid VARCHAR(100))
INSERT INTO #GetMANDtype SELECT typeid  FROM F_GetAllManagerBaseTypeId(@DtypeID,9,@OperatorID)

--选择分支机构
CREATE TABLE #GetSELECTSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetSELECTSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID)
	
	
--职员
DECLARE @Etypelimt INT 
Exec @Etypelimt= GP_CheckLimit @OperatorID,4481
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
IF @Etypelimt=0
BEGIN
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)
END	
ELSE
BEGIN
	SET @ETypeID = '00001'
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeID,3)
END	

--仓库
CREATE TABLE #KTypeId(TypeId	VARCHAR(50))
CREATE TABLE #KTypeIdIn(TypeId	VARCHAR(50))

DECLARE @limt INT ,
		@checkStock VARCHAR(200)
SELECT @limt = Value FROM dbo.Userconfig WHERE ConfigName = 'postransktypelimit'
SET @checkStock = ''

INSERT INTO #KTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID)
INSERT INTO #KTypeIdIn(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid1,4,@OperatorID)

IF @limt = 0
BEGIN
	INSERT INTO #KTypeId(TypeId)
	SELECT TypeId
	FROM dbo.Stock s 
	INNER JOIN (SELECT a FROM dbo.f_split(@KtypeID,',')) f ON s.typeId LIKE f.a+'%'
	
	INSERT INTO #KTypeIdin(TypeId)
	SELECT TypeId
	FROM dbo.Stock s 
	INNER JOIN (SELECT a FROM dbo.f_split(@KtypeID1,',')) f ON s.typeId LIKE f.a+'%'
END

IF @MKtypeid='-99999' AND @OperatorID<>'00001'  
BEGIN	
	IF @limt = 1
		SET @checkStock = ' AND (EXISTS (SELECT TOP 1 1 FROM #KTypeId WHERE TypeId = pabi.ktypeid) AND EXISTS (SELECT TOP 1 1 FROM #KTypeIdIn WHERE TypeId = pabi.inktypeid))'
	ELSE
		SET @checkStock = ' AND (EXISTS (SELECT TOP 1 1 FROM #KTypeId WHERE TypeId = pabi.ktypeid) OR EXISTS (SELECT TOP 1 1 FROM #KTypeIdIn WHERE TypeId = pabi.inktypeid))'
END


DECLARE @CurPSonNum INT
SELECT TOP 1 @CurPSonNum=SonNum FROM Ptype WHERE TypeID=@PtypeID

DECLARE @SQL varchar(max)
CREATE TABLE  #PTypelist
(
  typeid VARCHAR(50),
  usercode VARCHAR(200),
  fullname VARCHAR(200),
  sonnum INT,
  parid  VARCHAR(50),
  DELETED INT,
  SortID INT
)

IF @ifLine=1		--线性表
BEGIN
	IF  @ptypeCategoryid<>''
	BEGIN
 		SET @SQL='INSERT INTO #PTypelist  
		SELECT DISTINCT p.typeid,usercode,FullName,sonnum,ParId,deleted,SortID 	
		FROM dbo.ptype  p
		INNER JOIN dbo.F_LinePC('''+@OperatorID+''','''+@ptypeCategoryid+''') b ON b.typeid LIKE p.typeId+''%''
		WHERE	p.IsService=0
				AND p.iscombinationproduct = 0 AND P.SONNUM=0 AND p.typeid<>''00000'''
		IF @PtypeID<>'00000'
			SET @SQL+=' AND P.TYPEID LIKE '''+@PtypeID+'%'' '
		
	END
	ELSE
	BEGIN
		SET @SQL='INSERT INTO #PTypelist  
		SELECT 	typeid,usercode,FullName,sonnum,ParId,deleted,SortID  
		FROM	F_GetManPTypeAll('''+@OperatorID+''') p
		WHERE	p.IsService=0
				AND p.iscombinationproduct = 0 AND P.SONNUM=0 AND p.typeid<>''00000'''
		IF @PtypeID<>'00000'
			SET @SQL+=' AND P.TYPEID LIKE '''+@PtypeID+'%'''
	END

END
ELSE
BEGIN
	IF  @ptypeCategoryid<>''
	BEGIN
 		SET @SQL='INSERT INTO #PTypelist  
		SELECT DISTINCT p.typeid,usercode,FullName,sonnum,ParId,deleted,SortID 	
		FROM dbo.ptype  p
		INNER JOIN dbo.F_LinePC('''+@OperatorID+''','''+@ptypeCategoryid+''') b ON b.typeid LIKE p.typeId+''%''
		WHERE	p.IsService=0
				AND p.iscombinationproduct = 0'
		IF @PtypeID<>'00000' and @PtypeID<>''
		BEGIN
			IF @CurPSonNum>=1 
				SELECT @SQL+=' AND P.parid = '+CHAR(39)+@PtypeID+''+CHAR(39)
			ELSE
				SELECT @SQL+=+' AND P.typeID = '+CHAR(39)+@PtypeID+CHAR(39)
		END
		else
			SET @SQL+=' and p.parid=''00000'''
	END
	ELSE
	BEGIN
		SET @SQL='INSERT INTO #PTypelist  
		SELECT 	typeid,usercode,FullName,sonnum,ParId,deleted,SortID  
		FROM	F_GetManPTypeAll('''+@OperatorID+''') p
		WHERE	p.IsService=0
				AND p.iscombinationproduct = 0'
		IF @PtypeID<>'00000' and @PtypeID<>''
		BEGIN
			IF @CurPSonNum>=1 
				SELECT @SQL+=' AND P.typeID<>'''+@PtypeID+''' and P.parid = '+CHAR(39)+@PtypeID+''+CHAR(39)
			ELSE
				SELECT @SQL+=+' AND P.typeID = '+CHAR(39)+@PtypeID+CHAR(39)
		END
		else
			SET @SQL+=' and p.parid=''00000'''
	END
END	
EXEC(@SQL)
--print @SQL


CREATE TABLE #BillList
(
	BillNumberId	VARCHAR(100),
	etypeid			VARCHAR(100),	
	ptypeid			VARCHAR(100),
	dtypeid			VARCHAR(100),	
	InKtypeId		VARCHAR(100),	
	ktypeID			VARCHAR(100),
	stypeid			VARCHAR(100),
	ApplyPrice		NUMERIC(24, 10)default(0),	--要货库存均价
	ApplyQty		NUMERIC(24, 10)default(0),	--要货数量
	DeliveryQty		NUMERIC(24, 10)default(0),	--配送数量
	DeliveryTotal	NUMERIC(24, 10)default(0),	--配送金额
	CheckQty		NUMERIC(24, 10)default(0),	--验收入库数量
	CheckTotal		NUMERIC(24, 10)default(0),	--验收入库金额
	CheckPrice		NUMERIC(24, 10)default(0),	--验收入库均价
	BackQty			NUMERIC(24, 10)default(0),	--退货数量
	BackTotal		NUMERIC(24, 10)default(0),	--退货金额
	thgzqty			NUMERIC(24, 10)default(0),	--退货过账数量
	thgztotal		NUMERIC(24, 10)default(0)	--退货过账金额
	--OnWayQty		NUMERIC(24, 10)default(0),	--在途数量
	--OnWayTotal		NUMERIC(24, 10)default(0)		--在途金额
)

SET @SQL = '
    INSERT  INTO #BillList
            ( BillNumberId ,
              etypeid ,
              ptypeid ,
              dtypeid ,
              InKtypeId ,
              ktypeID ,
              stypeid ,
              DeliveryQty ,
              DeliveryTotal ,
              ApplyPrice ,
              CheckQty ,
              CheckTotal ,
              --CheckPrice ,
              BackQty ,
              BackTotal
		    )
            SELECT  pabi.billnumberid ,
                    pabi.ApplyEtypeId ,
                    db.ptypeid ,
                    pabi.dtypeid ,
                    pabi.InKtypeId ,
                    pabi.ktypeID ,
                    pabi.stypeid ,
                    db.QTY AS DeliveryQty ,
                    db.Total AS DeliveryTotal ,
                    db.GoodsCostTotal ,
                    db.CheckQty ,
                    ( db.CheckQty * db.Price ) AS CheckTotal ,
                    db.BackQty ,
                    ( db.BackQty * db.Price ) AS BackTotal
            FROM    PosAllotApplyBillIndex pabi
                    INNER JOIN DeliveryBill db ON pabi.BillNumberId = db.BillNumberId
					INNER JOIN #GetMANDtype d1 ON d1.typeid=pabi.dtypeid
					INNER JOIN #GetSELECTSTypeId s1 ON s1.typeid=pabi.stypeid
					INNER JOIN #GetManETypeId e1 on e1.typeid=pabi.ApplyEtypeId
            WHERE   pabi.draft = 0
                    AND pabi.RedWord = 0
                    AND BillDate BETWEEN '''+ @StartDate + ''' AND ''' + @EndDate +'''
	' + @checkStock
	
IF ISNULL(@ktypeid,'') <> ''
	SET @SQL += ' AND pabi.ktypeid IN (SELECT typeid FROM #ktypeid) '
	
if isnull(@ktypeid1,'') <> ''
	set @sql += ' AND pabi.InKtypeId IN (SELECT typeid FROM #ktypeidin) ' 

	
EXEC(@sql)		

SELECT * 
		,dbo.F_RoundPrice(CASE WHEN CheckQty = 0 THEN 0 ELSE CheckTotal/CheckQty END) AS checkprice
FROM 
(
	SELECT P.TypeID,p.UserCode,p.FullName,p.SonNum,p.parid
			,dbo.F_RoundTotal(sum(isnull(bill.ApplyPrice,0))) as costtotal
			,dbo.F_RoundQty(sum(isnull(bill.ApplyQty,0))) as ApplyQty
			,dbo.F_RoundQty(sum(isnull(bill.DeliveryQty,0))) as DeliveryQty
			,dbo.F_RoundTotal(sum(isnull(bill.DeliveryTotal,0))) as DeliveryTotal
			,dbo.F_RoundQty(sum(isnull(bill.CheckQty,0))) as CheckQty
			,dbo.F_RoundTotal(sum(isnull(bill.CheckTotal,0))) as CheckTotal
			,dbo.F_RoundQty(sum(isnull(bill.BackQty,0))) as BackQty
			,dbo.F_RoundTotal(sum(isnull(bill.BackTotal,0))) as BackTotal
			,dbo.F_RoundQty(sum(isnull(bill.DeliveryQty,0))-sum(isnull(bill.CheckQty,0))-sum(isnull(bill.BackQty,0))) as OnWayQty
			,dbo.F_RoundTotal(sum(isnull(bill.DeliveryTotal,0))-sum(isnull(bill.CheckTotal,0))-sum(isnull(bill.BackTotal,0))) as OnWayTotal	
	From #PTypelist P 
	LEFT JOIN #BillList bill ON bill.ptypeid like P.typeid +'%'
	GROUP BY P.TypeID,p.UserCode,p.FullName,p.SonNum,p.parid --,bill.CheckPrice
) a									
												
DROP TABLE #GetManETypeId,#KTypeId,#KTypeIdIn,#GetSELECTSTypeId,#GetMANDtype,#BillList,#PTypelist		
															
															
																
GO															
SET QUOTED_IDENTIFIER OFF									
GO															
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryDeliveryTreePos]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryDeliveryTreePos]
GO

/*
	作者：
	日期：
	描述：延用的商品配送统计树形表，拿来pos使用
*/

CREATE           PROCEDURE [Web_QueryDeliveryTreePos] 
(
	@OperatorID 	VARCHAR(100),	--操作员的ID
	@StartDate		VARCHAR(50),	--开始日期
	@EndDate		VARCHAR(50),	--结束日期
	@StypeId		VARCHAR(8000),
	@ptypeCategoryid	VARCHAR(max), --商品类别--pos没有商品类别
	@PtypeID		VARCHAR(8000),	--商品的ID
	@EtypeID		VARCHAR(8000),	--职员的ID
	@DtypeID		VARCHAR(8000),	--部门的ID
	@KtypeID		VARCHAR(8000),	--仓库的ID（出库）
	@KtypeID1		VARCHAR(8000),	--仓库的ID（要库）
	@ifLine		char(1) ='1'                  -- 0 代表树形表，1代表线性表 pos 只用线性

)
--@encode$--
AS

SET ANSI_WARNINGS OFF
SET NOCOUNT ON 
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
           @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
	
--部门
Create TABLE  #GetMANDtype(typeid VARCHAR(100))
INSERT INTO #GetMANDtype SELECT typeid  FROM F_GetAllManagerBaseTypeId(@DtypeID,9,@OperatorID)

--选择分支机构
CREATE TABLE #GetSELECTSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetSELECTSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@StypeId,11,@OperatorID)
	
	
--职员
DECLARE @Etypelimt INT 
Exec @Etypelimt= GP_CheckLimit @OperatorID,4481
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
IF @Etypelimt=0
BEGIN
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)
END	
ELSE
BEGIN
	SET @ETypeID = '00001'
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@ETypeID,3)
END	

--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))

DECLARE @limt INT 
Exec @limt= GP_CheckLimit @OperatorID,454

IF @MKtypeid='-99999' AND @limt=0
BEGIN
	INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetMANDetailKType(@OperatorID)
END

--仓库（出库）
CREATE TABLE #GetManSelKTypeId(TypeId	VARCHAR(100)) 
IF @MKtypeid='-99999' AND @limt=0  AND @OperatorID<>'00001'
BEGIN
	INSERT INTO #GetManSelKTypeId(TypeId) 
	SELECT sk.TypeId FROM F_GetAllBaseTypeId(@KTypeId,4) sk INNER JOIN #GetManKTypeId k ON sk.typeid=k.typeid
END
ELSE
BEGIN
	INSERT INTO #GetManSelKTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@KTypeId,4)
END

--仓库（要库）
CREATE TABLE #GetManSelKTypeId1(TypeId	VARCHAR(100))
IF @MKtypeid='-99999' AND @limt=0 AND @OperatorID<>'00001'
BEGIN
	INSERT INTO #GetManSelKTypeId1(TypeId) 
	SELECT sk.TypeId FROM F_GetAllBaseTypeId(@KTypeId1,4) sk INNER JOIN #GetManKTypeId k ON sk.typeid=k.typeid
END
ELSE
BEGIN
	INSERT INTO #GetManSelKTypeId1(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@KTypeId1,4)
END


DECLARE @SQL varchar(max)
CREATE TABLE  #PTypelist
(
  typeid VARCHAR(50),
  usercode VARCHAR(200),
  fullname VARCHAR(200),
  sonnum INT,
  parid  VARCHAR(50),
  DELETED INT,
  SortID INT
)

IF @ifLine=1		--线性表
BEGIN
		SET @SQL='INSERT INTO #PTypelist  
		SELECT 	typeid,usercode,FullName,sonnum,ParId,deleted,SortID  
		FROM	F_GetManPTypeAll('''+@OperatorID+''') p'
		IF EXISTS(SELECT TOP 1 1 FROM POSPtype)
		SET @SQL+='
		INNER JOIN dbo.POSPtype pp ON p.typeId LIKE pp.ptypeid+''%'''
		SET  @SQL+='
		WHERE	p.IsService=0
				AND p.iscombinationproduct = 0 AND P.SONNUM=0 AND p.typeid<>''00000'''
		IF @PtypeID<>'00000'
			SET @SQL+=' AND P.usercode LIKE '''+@PtypeID+'%'''
	END

EXEC(@SQL)
--PRINT  (@SQL)


CREATE TABLE #BillList
(
	BillNumberId	VARCHAR(100),	
	etypeid			VARCHAR(100),	
	ptypeid			VARCHAR(100),
	dtypeid			VARCHAR(100),	
	InKtypeId		VARCHAR(100),	
	ktypeID			VARCHAR(100),
	stypeid			VARCHAR(100),
	ApplyPrice		NUMERIC(24, 10)default(0),	--要货库存均价
	ApplyQty		NUMERIC(24, 10)default(0),	--要货数量
	DeliveryQty		NUMERIC(24, 10)default(0),	--配送数量
	DeliveryTotal	NUMERIC(24, 10)default(0),	--配送金额
	CheckQty		NUMERIC(24, 10)default(0),	--验收入库数量
	CheckTotal		NUMERIC(24, 10)default(0),	--验收入库金额
	CheckPrice		NUMERIC(24, 10)default(0),	--验收入库均价
	BackQty			NUMERIC(24, 10)default(0),	--退货数量
	BackTotal		NUMERIC(24, 10)default(0),	--退货金额
	thgzqty			NUMERIC(24, 10)default(0),	--退货过账数量
	thgztotal		NUMERIC(24, 10)default(0)	--退货过账金额
	--OnWayQty		NUMERIC(24, 10)default(0),	--在途数量
	--OnWayTotal		NUMERIC(24, 10)default(0)		--在途金额
	
)
 
 INSERT  INTO #BillList
            ( BillNumberId ,
              etypeid ,
              ptypeid ,
              dtypeid ,
              InKtypeId ,
              ktypeID ,
              stypeid ,
              DeliveryQty ,
              DeliveryTotal ,
              ApplyPrice ,
              CheckQty ,
              CheckTotal ,
              CheckPrice ,
              BackQty ,
              BackTotal
		    )
            SELECT  pabi.billnumberid ,
                    pabi.ApplyEtypeId ,
                    db.ptypeid ,
                    pabi.dtypeid ,
                    pabi.InKtypeId ,
                    pabi.ktypeID ,
                    pabi.stypeid ,
                    db.QTY AS DeliveryQty ,
                    db.Total AS DeliveryTotal ,
                    db.GoodsCostTotal ,
                    db.CheckQty ,
                    ( db.CheckQty * db.Price ) AS CheckTotal ,
                    ( SELECT    ISNULL(SUM(a.total) / SUM(a.qty), 0)
                      FROM      DeliveryCheckBill a
                                INNER JOIN PosAllotApplyBillIndex b ON a.billnumberid = b.billnumberid
                      WHERE     a.ptypeid = db.ptypeid AND b.BillDate BETWEEN @StartDate AND @EndDate
                    ) AS CheckPrice , --db.Price as CheckPrice,
                    db.BackQty ,
                    ( db.BackQty * db.Price ) AS BackTotal
            FROM    PosAllotApplyBillIndex pabi
                    INNER JOIN DeliveryBill db ON pabi.BillNumberId = db.BillNumberId
            WHERE   pabi.draft = 0
                    AND pabi.RedWord = 0
                    AND pabi.BillDate BETWEEN @StartDate AND @EndDate			

SELECT P.TypeID,p.UserCode,p.FullName,p.SonNum,p.parid,pu.FullName as unit
		,dbo.F_RoundTotal(sum(isnull(bill.ApplyPrice,0))) as ApplyPrice
		,dbo.F_RoundQty(sum(isnull(bill.ApplyQty,0))) as ApplyQty
		,dbo.F_RoundQty(sum(isnull(bill.DeliveryQty,0))) as DeliveryQty
		,dbo.F_RoundTotal(sum(isnull(bill.DeliveryTotal,0))) as DeliveryTotal
		,dbo.F_RoundQty(sum(isnull(bill.CheckQty,0))) as CheckQty
		,dbo.F_RoundTotal(sum(isnull(bill.CheckTotal,0))) as CheckTotal
		,dbo.F_RoundPrice(isnull(bill.CheckPrice,0)) as CheckPrice
		,dbo.F_RoundQty(sum(isnull(bill.BackQty,0))) as BackQty
		,dbo.F_RoundTotal(sum(isnull(bill.BackTotal,0))) as BackTotal
		,dbo.F_RoundQty(sum(isnull(bill.DeliveryQty,0))-sum(isnull(bill.CheckQty,0))-sum(isnull(bill.BackQty,0))) as OnWayQty
		,dbo.F_RoundTotal(sum(isnull(bill.DeliveryTotal,0))-sum(isnull(bill.CheckTotal,0))-sum(isnull(bill.BackTotal,0))) as OnWayTotal	
From #PTypelist P 
LEFT JOIN #BillList bill ON bill.ptypeid like P.typeid +'%'
INNER JOIN #GetMANDtype d1 ON d1.typeid=bill.dtypeid
INNER JOIN #GetSELECTSTypeId s1 ON s1.typeid=bill.stypeid
INNER JOIN #GetManETypeId e1 on e1.typeid=bill.etypeid
INNER JOIN #GetManSelKTypeId k on k.typeid=bill.KtypeId
INNER JOIN #GetManSelKTypeId1 k1 on k1.typeid=bill.InKtypeId
INNER join  PType_Units_Ext pe on p.TypeID=pe.PtypeID AND pe.IsDefaultUnit=1
INNER join PType_Units pu on pu.unitsid=pe.unitsid
GROUP BY P.TypeID,p.UserCode,p.FullName,p.SonNum,p.parid,bill.CheckPrice,pu.FullName
															


--SELECT * FROM #BillList														
DROP TABLE #BillList,#PTypelist				
DROP TABLE #GetManETypeId,#GetManSelKTypeId,#GetManSelKTypeId1,#GetManKTypeId,#GetSELECTSTypeId,#GetMANDtype
															
															
																
GO															
SET QUOTED_IDENTIFIER OFF									
GO															
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartment]
GO










/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构的基本信息查询
*/
CREATE PROCEDURE Web_QueryDepartment
(
	@OperatorId		varchar(100),	--操作员的ID
	@DTypeId		varchar(100)	--分支机构的ID
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @DTypeId = ''
	SET @DTypeId = '00000'

DECLARE @SonNum int,
		@SQL	varchar(8000)


SELECT @SonNum = SonNum FROM Department WHERE TypeId = @DTypeId AND Deleted = 0

SET @SQL = '
		SELECT	TypeId,
				SonNum,
				UserCode,
				FullName
		FROM	Department
		WHERE	Deleted = 0 
				AND TypeId LIKE '+char(39)+@MDTypeId+'%'+char(39)

IF @SonNum = 0 
	SET @SQL = @SQL + ' AND TypeId = '+char(39)+@DTypeId+char(39)
ELSE
	SET @SQL = @SQL + ' AND ParId = '+char(39)+@DTypeId+char(39)

SET @SQL = @SQL + ' ORDER BY UserCode'

--PRINT(@SQL)
EXEC(@SQL)











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentBTypeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentBTypeDetail]
GO
























/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构往来单位的应收、应付往来对帐查询
*/
CREATE  PROCEDURE Web_QueryDepartmentBTypeDetail
(
	@OperatorId		varchar(100),			--操作员的ID
	@DTypeId		varchar(100),			--部门的ID	
	@BTypeId		varchar(100),			--往来单位ID
	@STypeId		varchar(8000),			--分支机构ID
	@StartDate		varchar(12),			--开始日期
	@EndDate		varchar(12),			--截至日期
	@ShowRedWord	int,					--是否显示红冲单据  1.显示红冲单据   0.不显示红冲单据
	@Type			int,					--查询类别   1.应收    2.应付
	@SortField		varchar(100),			--排序字段
	@SortType		varchar(10),			--排序方式	ASC 升序   DESC 降序
	@Bhys			varchar(max)			--包含预收（付） 1.包含 0.不包含
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL			varchar(8000),	--SQL字符串
		@SQL_WHERE  	VARCHAR(8000),
		@SQL_EType		VARCHAR(8000),
		@SQL_KType		VARCHAR(8000),
		@SQL_BType		VARCHAR(8000)

SET @MDTypeId = '%'
SET @SQL = ''
SET @SQL_WHERE = ' AND DTypeId LIKE '+char(39)+'%'+char(39)

SET @SQL_EType = ''
SET @SQL_KType = ''
SET @SQL_BType = ''
							
IF NOT @METypeId = '00001'
	SET @SQL_EType = ' AND ETypeId IN (SELECT * FROM F_GetManDetailEType('+char(39)+@OperatorID+char(39)+'))'
	
IF NOT @MKTypeId = '00000'
	SET @SQL_KType = ' AND (KTypeId IN (SELECT * FROM F_GetManDetailKType('+char(39)+@OperatorID+char(39)+')) OR ISNULL(KTypeId,'''')='''' OR KTypeId = ''10000'')'
	
IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL_BType = ' AND BTypeId IN (SELECT * FROM F_GetManDetailBType('+char(39)+@OperatorID+char(39)+'))'

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--求当前查询期间内的数据
SET @SQL = '
	SELECT	B.BillNumberId,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.Comment,
			B.RedWord,
			B.ETypeId,
			B.STypeId,
			B.[ID],
			B.FullName,			
			ISNULL(B.ArTotal,0) AS ArTotal,
			ISNULL(B.ApTotal,0) AS ApTotal,
			ISNULL(B.ArTotal,0)-ISNULL(B.ApTotal,0) AS ArLeftMoney,
			ISNULL(B.ApTotal,0)-ISNULL(B.ArTotal,0) AS ApLeftMoney
	FROM	(
				SELECT	BillNumberId,
						BillDate,
						BillCode,
						BillType,
						Comment, 
						RedWord,
						ETypeId,
						STypeId,
						[Id],
						FullName = (SELECT FullName FROM Employee WHERE TypeId = BillIndex.ETypeId),
						CASE 
							WHEN BillType IN (45,115,148,149,34,145,128,36,84,94,161,170,190) AND RedWord = 1	 	    	THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0) - ISNULL(preferencemoney,0)
							WHEN BillType IN (11,141,155,116,6,129,150,151,93,85,157,160,167,168,172,178,186,189) AND RedWord IN (0,1) 		THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0) - ISNULL(preferencemoney,0)
							WHEN BillType IN (66) AND RedWord = 0													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (66) AND RedWord = 2													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 1 													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							ELSE 0
						END  AS ArTotal,
						CASE 
							WHEN BillType IN (45,115,148,149,34,145,128,36,84,94,161,170,190) AND RedWord IN (0,2)		THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0)  - ISNULL(preferencemoney,0)
							WHEN BillType IN (11,141,155,116,6,129,150,151,93,85,157,160,167,168,172,178,186,189)   AND RedWord = 2    	THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0)  - ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 0 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 2 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (66) AND RedWord = 1 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							ELSE 0
						END AS ApTotal
				FROM	BillIndex '
				
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '
				
			IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId '									

			SET @SQL = @SQL + '				
				WHERE	BillDate>='+char(39)+@StartDate+char(39)+'
						AND BillDate<='+char(39)+@EndDate+char(39)+'
						AND IfCheck = ''t''
						AND IfYearBill = 0
						AND BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)
				IF @DTypeID = ''
					SET @SQL = @SQL + ' AND DTypeId = '+char(39)+@DTypeId+char(39)
				ELSE
					SET @SQL = @SQL + ' AND DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)
					
				IF @Bhys = '0'
					BEGIN
						IF @Type = '1'
							SET @SQL = @SQL + ' AND BillType NOT IN (189) '
						ELSE
							SET @SQL = @SQL + ' AND BillType NOT IN (190) '
					END					

				SET @SQL = @SQL + @SQL_WHERE + @SQL_EType + @SQL_KType + @SQL_BType + '
				UNION ALL
				SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.Comment, 
						B.RedWord,
						B.ETypeId,
						B.STypeId,
						B.Id,
						FullName = (SELECT FullName FROM Employee WHERE TypeId = B.ETypeId),
						CASE 
							WHEN B.BillType IN (115,128)   AND RedWord = 1    	THEN ISNULL(A.Total,0)
							WHEN B.BillType IN (116,129) AND RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
							ELSE 0
						END  AS ArTotal,
						CASE 
							WHEN B.BillType IN (115,128)   AND RedWord IN (0,2)    	THEN ISNULL(A.Total,0)
							WHEN B.BillType IN (116,129)   AND RedWord = 1    		THEN ISNULL(A.Total,0)
							ELSE 0
						END AS ApTotal
				FROM	BillIndex B
				INNER JOIN 	AdDebtBill A ON B.BillNumberId = A.BillNumberId '
				
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '	
				
			IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId '								
			
			SET @SQL = @SQL + '	
				WHERE	B.BillDate>='+char(39)+@StartDate+char(39)+'
						AND B.BillDate<='+char(39)+@EndDate+char(39)+'
						AND B.IfCheck = ''t''
						AND B.IfYearBill = 0
						AND A.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)
		IF @DTypeId = ''
			SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
		ELSE
			SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

		SET @SQL = @SQL + REPLACE(@SQL_WHERE,'DTypeId','B.DTypeId') + Replace(@SQL_EType,'ETypeId','B.ETypeId') + Replace(@SQL_KType,'KTypeId','B.KTypeId') + Replace(@SQL_BType,'BTypeId','A.BTypeId')
		
		/*******************************此处构造复杂，必须分客户合供货商是否统一来特殊处理数据  谢吉康 2005-9-7**************************************/
		IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
			BEGIN
					SET @SQL = @SQL + '
						UNION ALL
						SELECT	B.BillNumberId,
								B.BillDate,
								B.BillCode,
								B.BillType,
								B.Comment, 
								B.RedWord,
								B.ETypeId,
								B.STypeId,
								B.Id,
								FullName = (SELECT FullName FROM Employee WHERE TypeId = B.ETypeId), '
						IF @Type = 1	--应收查询
							SET @SQL = @SQL + '
								CASE 
									WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 0	THEN ISNULL(A.Total,0)
									WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 2	THEN ISNULL(ABS(A.Total),0)
									WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 1 	THEN ISNULL(ABS(A.Total),0)
									ELSE 0
								END AS ArTotal,
								CASE 
									WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 0	THEN ISNULL(A.Total,0)
									WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 2	THEN ISNULL(ABS(A.Total),0)
									WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 1 	THEN ISNULL(ABS(A.Total),0)
									ELSE 0
								END  AS ApTotal '
						ELSE			--应收查询
							SET @SQL = @SQL + '
								CASE 
									WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 0	THEN ISNULL(A.Total,0)
									WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 2	THEN ISNULL(ABS(A.Total),0)
									WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 1 	THEN ISNULL(ABS(A.Total),0)
									ELSE 0
								END AS ArTotal,
								CASE 
									WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 0	THEN ISNULL(A.Total,0)
									WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 2	THEN ISNULL(ABS(A.Total),0)
									WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 1 	THEN ISNULL(ABS(A.Total),0)
									ELSE 0
								END  AS ApTotal '

						SET @SQL = @SQL + '
						FROM	BillIndex B
						INNER JOIN ListTable A ON B.BillNumberId = A.BillNumberId '
						
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '	
					
				IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId '											
						
				SET @SQL = @SQL + '		
						WHERE	B.BillType = 159
								AND B.BillDate>='+char(39)+@StartDate+char(39)+'
								AND B.BillDate<='+char(39)+@EndDate+char(39)+'
								AND B.IfCheck = ''t''
								AND B.IfYearBill = 0
								AND A.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)
				IF @DTypeId = ''
					SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
				ELSE
					SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)
		
				SET @SQL = @SQL + REPLACE(@SQL_WHERE,'DTypeId','B.DTypeId') + Replace(@SQL_EType,'ETypeId','B.ETypeId') + Replace(@SQL_KType,'KTypeId','B.KTypeId') + Replace(@SQL_BType,'BTypeId','A.BTypeId')
			END
		ELSE	--客户和供货商统一
			BEGIN
					SET @SQL = @SQL + '
						UNION ALL
						SELECT	B.BillNumberId,
								B.BillDate,
								B.BillCode,
								B.BillType,
								B.Comment, 
								B.RedWord,
								B.ETypeId,
								B.STypeId,
								B.Id,
								FullName = (SELECT FullName FROM Employee WHERE TypeId = B.ETypeId), '
						IF @Type = 1	--应收查询
							SET @SQL = @SQL + '
								CASE 
									WHEN A.TypeATypeId = ''0000200001'' AND B.RedWord = 0 	   AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
									WHEN A.TypeATypeId = ''0000200001'' AND B.RedWord = 2 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
									WHEN A.TypeATypeId = ''0000100005'' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
									WHEN A.TypeATypeId = ''0000100005'' AND B.RedWord = 2 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
									ELSE 0
								END  AS ArTotal,
								CASE 
									WHEN A.TypeATypeId = ''0000200001'' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
									WHEN A.TypeATypeId = ''0000200001'' AND B.RedWord = 1 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
									WHEN A.TypeATypeId = ''0000100005'' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
									WHEN A.TypeATypeId = ''0000100005'' AND B.RedWord = 1 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
									ELSE 0
								END AS ApTotal '
						ELSE				--应付查询
							SET @SQL = @SQL + '
								CASE 
									WHEN A.TypeATypeId = ''0000200001'' AND B.RedWord = 0 	   AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
									WHEN A.TypeATypeId = ''0000200001'' AND B.RedWord = 2 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
									WHEN A.TypeATypeId = ''0000100005'' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
									WHEN A.TypeATypeId = ''0000100005'' AND B.RedWord = 2 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
									ELSE 0
								END  AS ArTotal,
								CASE 
									WHEN A.TypeATypeId = ''0000200001'' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
									WHEN A.TypeATypeId = ''0000200001'' AND B.RedWord = 1 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
									WHEN A.TypeATypeId = ''0000100005'' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
									WHEN A.TypeATypeId = ''0000100005'' AND B.RedWord = 1 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
									ELSE 0
								END AS ApTotal '

						SET @SQL = @SQL + '
						FROM	BillIndex B
						INNER JOIN	AccountCredence A ON B.BillNumberId = A.BillNumberId '
						
						IF NOT (@STypeId = '' AND @MStypeid = '00000')
							SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '	
							
						IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
							SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId '													
						
						SET @SQL = @SQL + '
						WHERE	B.BillType = 159
								AND B.BillDate>='+char(39)+@StartDate+char(39)+'
								AND B.BillDate<='+char(39)+@EndDate+char(39)+'
								AND B.IfCheck = ''t''
								AND B.IfYearBill = 0
								AND A.TypeATypeId IN (''0000200001'',''0000100005'')
								AND A.ATypeId LIKE '+char(39)+@BTypeId+'%'+char(39)
				IF @DTypeId = ''
					SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
				ELSE
					SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)
		
				SET @SQL = @SQL + REPLACE(@SQL_WHERE,'DTypeId','B.DTypeId') + Replace(@SQL_EType,'ETypeId','B.ETypeId') + Replace(@SQL_KType,'KTypeId','B.KTypeId') + Replace(@SQL_BType,'BTypeId','A.ATypeId')
			END

	SET @SQL = @SQL + '			
			)B
	WHERE	(ISNULL(B.ArTotal,0)<>0	OR ISNULL(B.ApTotal,0)<>0 ) '

--是否显示红冲单据
IF @ShowRedWord = 0
	SET @SQL = @SQL + ' AND B.RedWord = 0'

--排序
SET @SQL = @SQL + ' ORDER BY '+@SortField+' '+@SortType

--PRINT(@SQL)
EXEC(@SQL)



DROP TABLE #GetManSTypeId,#GetManDTypeId











































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentBTypeDetailGetBefore]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentBTypeDetailGetBefore]
GO


























/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构往来单位的应收、应付往来对帐查询此前余额
*/
CREATE PROCEDURE Web_QueryDepartmentBTypeDetailGetBefore
(
	@OperatorId		varchar(100),			--操作员的ID
	@DTypeId		varchar(100),			--部门的ID	
	@BTypeId		varchar(100),			--往来单位ID
	@STypeId		varchar(8000),			--分支机构ID
	@StartDate		varchar(12),			--开始日期
	@EndDate		varchar(12),			--截至日期
	@ShowRedWord	varchar(10),			--是否显示红冲单据  1.显示红冲单据   0.不显示红冲单据
	@Type			int,					--查询类别   1.应收    2.应付
	@Bhys			varchar(max),			--包含预收（付） 1.包含 0.不包含
	@BeforeMoney	 NUMERIC(24, 10)  OUTPUT	--此前余额
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @ShowRedWord = 1
	SET @ShowRedWord = '0,1,2'

DECLARE @SQL		varchar(8000),	--SQL字符串
		@BTypeAll	int

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--单据类型
CREATE TABLE #BillName
(
	BillType INT
)
IF @Bhys = '1'
	BEGIN
		INSERT INTO #BillName(BillType)SELECT BillType FROM BillName
	END
ELSE
	BEGIN
		IF @Type = '1'		
			INSERT INTO #BillName(BillType)SELECT BillType FROM BillName WHERE Billtype NOT IN (189)
		ELSE
			INSERT INTO #BillName(BillType)SELECT BillType FROM BillName WHERE Billtype NOT IN (190)
	END

--求此前余额
--求此前余额
IF @DTypeId = ''
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 * FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)
			SELECT	@BeforeMoney=
									CASE 
										WHEN @Type = 1 THEN ISNULL((SUM(B.ArTotal)-SUM(B.ApTotal)),0)
										ELSE ISNULL(SUM(B.ApTotal)-SUM(B.ArTotal),0)
									END
			FROM	(
						SELECT	BillNumberId,
								BillDate,
								BillCode,
								BillType,
								Comment, 
								RedWord,
								CASE 
									WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord = 2	 			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189) AND RedWord IN (0,1) 	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (4)   AND RedWord = 0		       							THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									WHEN BillType IN (4)   AND RedWord = 1		       							THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
									WHEN BillType IN (66) AND RedWord = 1										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									ELSE 0
								END  AS ArTotal,
								CASE 
									WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord IN (0,1)			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189)   AND RedWord = 2     THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)							
									WHEN BillType IN (4) AND RedWord = 2 									 	THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
									WHEN BillType IN (66) AND RedWord = 0	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									WHEN BillType IN (66) AND RedWord = 2	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									ELSE 0
								END AS ApTotal
						FROM	BillIndex
						INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId
						WHERE	BillDate<@StartDate
								AND IfCheck = 't'
								AND IfYearBill = 0
								AND RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
								AND BTypeId LIKE @BTypeId+'%'
								AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
								AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorID)) OR ISNULL(KTypeId,'')='' OR KTypeId = '10000')
								AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
								AND Stypeid IN (SELECT TypeId FROM #GetManSTypeId)
								AND BillType IN (SELECT BillType FROM #BillName)
						UNION ALL
						SELECT	B.BillNumberId,
								B.BillDate,
								B.BillCode,
								B.BillType,
								B.Comment,
								B.RedWord,
								CASE 
									WHEN B.BillType IN (115,128) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
		
									WHEN B.BillType IN (116,129) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
									ELSE 0
								END AS ArTotal,
								CASE 
									WHEN B.BillType IN (116,129) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
									WHEN B.BillType IN (115,128) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
									ELSE 0
								END AS ApTotal					
						FROM	BillIndex B,
								AdDebtBill A,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	B.BillNumberId = A.BillNumberId
								AND B.Stypeid = S.TypeId
								AND B.DTypeId = D.TypeId
								AND B.BillDate<@StartDate
								AND B.IfCheck = 't'
								AND B.IfYearBill = 0
								AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
								AND A.BTypeId LIKE @BTypeId+'%'
								AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
								AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
						UNION ALL
						SELECT	B.BillNumberId,
								B.BillDate,
								B.BillCode,
								B.BillType,
								B.Comment,
								B.RedWord,
								CASE 
									WHEN A.ATypeId = '0000100005' AND B.RedWord IN(0,2)		THEN ISNULL(A.Total,0)
									WHEN A.ATypeId = '0000200001' AND B.RedWord = 1 		THEN -1*ISNULL(A.Total,0)
									ELSE 0
								END  AS ArTotal,
								CASE 
									WHEN A.ATypeId = '0000100005' AND B.RedWord = 1 		THEN -1*ISNULL(A.Total,0)
									WHEN A.ATypeId = '0000200001' AND B.RedWord IN (0,2)	THEN ISNULL(A.Total,0)									
									ELSE 0
								END AS ApTotal			
						FROM	BillIndex B,
								ListTable A,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	B.BillNumberId = A.BillNumberId
								AND B.Stypeid = S.TypeId
								AND B.DTypeId = D.TypeId
								AND B.BillDate<@StartDate
								AND B.BillType = 159
								AND A.ATypeId IN ('0000100005','0000200001')
								AND B.IfCheck = 't'
								AND B.IfYearBill = 0
								AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
								AND A.BTypeId LIKE @BTypeId+'%'
								AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
								AND A.ATypeId LIKE  
									CASE
										WHEN @Type = 1 AND @BTypeAll = 0 THEN '0000100005'
										WHEN @Type = 2 AND @BTypeAll = 0 THEN '0000200001'
										ELSE '%'
									END							
								AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
					)B
		ELSE
			IF @Type = 1	--应收查询
			SELECT	@BeforeMoney=
									CASE 
										WHEN @Type = 1 THEN ISNULL((SUM(B.ArTotal)-SUM(B.ApTotal)),0)
										ELSE ISNULL(SUM(B.ApTotal)-SUM(B.ArTotal),0)
									END
			FROM	(
						SELECT	BillNumberId,
								BillDate,
								BillCode,
								BillType,
								Comment, 
								RedWord,
								CASE 
									WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord = 2				THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189) AND RedWord IN (0,1) 	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (4)   AND RedWord = 0		       							THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									WHEN BillType IN (4)   AND RedWord = 1		       							THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
									WHEN BillType IN (66) AND RedWord = 1										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									ELSE 0
								END  AS ArTotal,
								CASE 
									WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord IN (0,1)			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189)   AND RedWord = 2     THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)							
									WHEN BillType IN (4) AND RedWord = 2 									 	THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
									WHEN BillType IN (66) AND RedWord = 0	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									WHEN BillType IN (66) AND RedWord = 2	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									ELSE 0
								END AS ApTotal
						FROM	BillIndex
						INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId
						WHERE	BillDate<@StartDate
								AND IfCheck = 't'
								AND IfYearBill = 0
								AND RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
								AND BTypeId LIKE @BTypeId+'%'
								AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
								AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorID)) OR ISNULL(KTypeId,'')='' OR KTypeId = '10000')
								AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
								AND Stypeid IN (SELECT * FROM #GetManSTypeId)
								AND BillType IN (SELECT * FROM #BillName)
						UNION ALL
						SELECT	B.BillNumberId,
								B.BillDate,
								B.BillCode,
								B.BillType,
								B.Comment,
								B.RedWord,
								CASE 
									WHEN B.BillType IN (115,128) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
		
									WHEN B.BillType IN (116,129) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
									ELSE 0
								END AS ArTotal,
								CASE 
									WHEN B.BillType IN (116,129) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
									WHEN B.BillType IN (115,128) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
									ELSE 0
								END AS ApTotal					
						FROM	BillIndex B,
								AdDebtBill A,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	B.BillNumberId = A.BillNumberId
								AND B.Stypeid = S.TypeId
								AND B.DTypeId = D.TypeId
								AND B.BillDate<@StartDate
								AND B.IfCheck = 't'
								AND B.IfYearBill = 0
								AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
								AND A.BTypeId LIKE @BTypeId+'%'
								AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
								AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
						UNION ALL
						SELECT	DISTINCT
										B.BillNumberId,
										B.BillDate,
										B.BillCode,
										B.BillType,
										B.Comment,
										B.RedWord,
										CASE 
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 0 	   AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 2 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 2 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											ELSE 0
										END  AS ArTotal,
										CASE 
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 1 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 1 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											ELSE 0
										END AS ApTotal		
								FROM	BillIndex B,
										AccountCredence A,
										#GetManSTypeId S,
										#GetManDTypeId D
								WHERE	B.BillNumberId = A.BillNumberId
										AND B.Stypeid = S.TypeId
										AND B.DTypeId = D.TypeId
										AND B.BillDate<@StartDate
										AND B.BillType = 159
										AND A.TypeATypeId IN ('0000100005','0000200001')
										AND B.IfCheck = 't'
										AND B.IfYearBill = 0
										AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
										AND A.ATypeId LIKE @BTypeId+'%'
										AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
										AND A.TypeATypeId LIKE  
											CASE
												WHEN @Type = 1 AND @BTypeAll = 0 THEN '0000100005'
												WHEN @Type = 2 AND @BTypeAll = 0 THEN '0000200001'
												ELSE '%'
											END						
										AND A.ATypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
					)B
			ELSE			--应付查询
				SELECT	@BeforeMoney=
										CASE 
											WHEN @Type = 1 THEN ISNULL((SUM(B.ArTotal)-SUM(B.ApTotal)),0)
											ELSE ISNULL(SUM(B.ApTotal)-SUM(B.ArTotal),0)
										END
				FROM	(
							SELECT	BillNumberId,
									BillDate,
									BillCode,
									BillType,
									Comment, 
									RedWord,
									CASE 
										WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord = 2	 			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
										WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189) AND RedWord IN (0,1) 	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
										WHEN BillType IN (4)   AND RedWord = 0		       							THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
										WHEN BillType IN (4)   AND RedWord = 1		       							THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
										WHEN BillType IN (66) AND RedWord = 1										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
										ELSE 0
									END  AS ArTotal,
									CASE 
										WHEN BillType IN (45,148,149,34,145,36,94,84,161,170) AND RedWord IN (0,1)			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(CompleteTotal,0)-ISNULL(preferencemoney,0)
										WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186)   AND RedWord = 2     THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(CompleteTotal,0)-ISNULL(preferencemoney,0)							
										WHEN BillType IN (4) AND RedWord = 2 									 	THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
										WHEN BillType IN (66) AND RedWord = 0	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
										WHEN BillType IN (66) AND RedWord = 2	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
										ELSE 0
									END AS ApTotal
							FROM	BillIndex
							INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId
							WHERE	BillDate<@StartDate
									AND IfCheck = 't'
									AND IfYearBill = 0
									AND RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
									AND BTypeId LIKE @BTypeId+'%'
									AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
									AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorID)) OR ISNULL(KTypeId,'')='' OR KTypeId = '10000')
									AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
									AND Stypeid IN (SELECT * FROM #GetManSTypeId)
									AND BillType IN (SELECT * FROM #BillName)
							UNION ALL
							SELECT	B.BillNumberId,
									B.BillDate,
									B.BillCode,
									B.BillType,
									B.Comment,
									B.RedWord,
									CASE 
										WHEN B.BillType IN (115,128) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
			
										WHEN B.BillType IN (116,129) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
										ELSE 0
									END AS ArTotal,
									CASE 
										WHEN B.BillType IN (116,129) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
										WHEN B.BillType IN (115,128) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
										ELSE 0
									END AS ApTotal					
							FROM	BillIndex B,
									AdDebtBill A,
									#GetManSTypeId S,
									#GetManDTypeId D
							WHERE	B.BillNumberId = A.BillNumberId
									AND B.Stypeid = s.TypeId
									AND B.DTypeId = D.TypeId
									AND B.BillDate<@StartDate
									AND B.IfCheck = 't'
									AND B.IfYearBill = 0
									AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
									AND A.BTypeId LIKE @BTypeId+'%'
									AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
									AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
							UNION ALL
							SELECT	DISTINCT
										B.BillNumberId,
										B.BillDate,
										B.BillCode,
										B.BillType,
										B.Comment,
										B.RedWord,
										CASE 
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 0 	   AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 2 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 2 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											ELSE 0
										END  AS ArTotal,
										CASE 
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 1 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 1 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											ELSE 0
										END AS ApTotal		
								FROM	BillIndex B,
										AccountCredence A,
										#GetManSTypeId S,
										#GetManDTypeId D
								WHERE	B.BillNumberId = A.BillNumberId
										AND B.Stypeid = s.TypeId
										AND B.DTypeId = D.TypeId
										AND B.BillDate<@StartDate
										AND B.BillType = 159
										AND A.TypeATypeId IN ('0000100005','0000200001')
										AND B.IfCheck = 't'
										AND B.IfYearBill = 0
										AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
										AND A.ATypeId LIKE @BTypeId+'%'
										AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
										AND A.TypeATypeId LIKE  
											CASE
												WHEN @Type = 1 AND @BTypeAll = 0 THEN '0000100005'
												WHEN @Type = 2 AND @BTypeAll = 0 THEN '0000200001'
												ELSE '%'
											END						
										AND A.ATypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
						)B
	END
ELSE	/***********************************************************客户和供货商统一***************************************************************************/
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 * FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)
			SELECT	@BeforeMoney=
									CASE 
										WHEN @Type = 1 THEN ISNULL((SUM(B.ArTotal)-SUM(B.ApTotal)),0)
										ELSE ISNULL(SUM(B.ApTotal)-SUM(B.ArTotal),0)
									END
			FROM	(
						SELECT	BillNumberId,
								BillDate,
								BillCode,
								BillType,
								Comment, 
								RedWord,
								CASE 
									WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord = 2	 			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189) AND RedWord IN (0,1) 	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (4)   AND RedWord = 0		       							THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									WHEN BillType IN (4)   AND RedWord = 1		       							THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
									WHEN BillType IN (66) AND RedWord = 1										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									ELSE 0
								END  AS ArTotal,
								CASE 
									WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord IN (0,1)			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
									WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189)   AND RedWord = 2     THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)							
									WHEN BillType IN (4) AND RedWord = 2 									 	THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
									WHEN BillType IN (66) AND RedWord = 0	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									WHEN BillType IN (66) AND RedWord = 2	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
									ELSE 0
								END AS ApTotal
						FROM	BillIndex
						INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId
						WHERE	BillDate<@StartDate
								AND IfCheck = 't'	
								AND IfYearBill = 0
								AND RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
								AND BTypeId LIKE @BTypeId+'%'
								AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
								AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorID)) OR ISNULL(KTypeId,'')='' OR KTypeId = '10000')
								AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
								AND Stypeid IN (SELECT * FROM #GetManSTypeId)
								AND BillType IN (SELECT * FROM #BillName)
						UNION ALL
						SELECT	B.BillNumberId,
								B.BillDate,
								B.BillCode,
								B.BillType,
								B.Comment,
								B.RedWord,
								CASE 
									WHEN B.BillType IN (115,128) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
									WHEN B.BillType IN (116,129) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
									ELSE 0
								END AS ArTotal,
								CASE 
									WHEN B.BillType IN (116,129) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
									WHEN B.BillType IN (115,128) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
									ELSE 0
								END AS ApTotal					
						FROM	BillIndex B,
								AdDebtBill A,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	B.BillNumberId = A.BillNumberId
								AND B.Stypeid = S.TypeId
								AND B.DTypeId = D.TypeId
								AND B.BillDate<@StartDate
								AND B.IfCheck = 't'
								AND B.IfYearBill = 0
								AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
								AND A.BTypeId LIKE @BTypeId+'%'
								AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
								AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
						UNION ALL
						SELECT	B.BillNumberId,
								B.BillDate,
								B.BillCode,
								B.BillType,
								B.Comment,
								B.RedWord,
								CASE 
									WHEN A.ATypeId = '0000100005' AND B.RedWord IN(0,2)		THEN ISNULL(A.Total,0)
									WHEN A.ATypeId = '0000200001' AND B.RedWord = 1 		THEN -1*ISNULL(A.Total,0)
									ELSE 0
								END  AS ArTotal,
								CASE 
									WHEN A.ATypeId = '0000100005' AND B.RedWord = 1 		THEN -1*ISNULL(A.Total,0)
									WHEN A.ATypeId = '0000200001' AND B.RedWord IN (0,2)	THEN ISNULL(A.Total,0)									
									ELSE 0
								END AS ApTotal			
						FROM	BillIndex B,
								ListTable A,
								#GetManSTypeId S,
								#GetManDTypeId D
						WHERE	B.BillNumberId = A.BillNumberId
								AND B.Stypeid = S.TypeId
								AND B.DTypeId = D.TypeId
								AND B.BillDate<@StartDate
								AND B.BillType = 159
								AND A.ATypeId IN ('0000100005','0000200001')
								AND B.IfCheck = 't'
								AND B.IfYearBill = 0
								AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
								AND A.BTypeId LIKE @BTypeId+'%'
								AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
								AND A.ATypeId LIKE  
									CASE
										WHEN @Type = 1 AND @BTypeAll = 0 THEN '0000100005'
										WHEN @Type = 2 AND @BTypeAll = 0 THEN '0000200001'
										ELSE '%'
									END						
								AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
					)B
		ELSE
			BEGIN
				IF @Type = 1	--应收查询
					SELECT	@BeforeMoney=
											CASE 
												WHEN @Type = 1 THEN ISNULL((SUM(B.ArTotal)-SUM(B.ApTotal)),0)
												ELSE ISNULL(SUM(B.ApTotal)-SUM(B.ArTotal),0)
											END
					FROM	(
								SELECT	BillNumberId,
										BillDate,
										BillCode,
										BillType,
										Comment, 
										RedWord,
										CASE 
											WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord = 2	 			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189) AND RedWord IN (0,1) 	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (4)   AND RedWord = 0		       							THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											WHEN BillType IN (4)   AND RedWord = 1		       							THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											WHEN BillType IN (66) AND RedWord = 1										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											ELSE 0
										END  AS ArTotal,
										CASE 
											WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord IN (0,1)			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189)   AND RedWord = 2     THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)							
											WHEN BillType IN (4) AND RedWord = 2 									 	THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											WHEN BillType IN (66) AND RedWord = 0	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											WHEN BillType IN (66) AND RedWord = 2	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											ELSE 0
										END AS ApTotal
								FROM	BillIndex
								INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId
								WHERE	BillDate<@StartDate
										AND IfCheck = 't'	
										AND IfYearBill = 0
										AND RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
										AND BTypeId LIKE @BTypeId+'%'
										AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
										AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorID)) OR ISNULL(KTypeId,'')='' OR KTypeId = '10000')
										AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
										AND Stypeid IN (SELECT * FROM #GetManSTypeId)
										AND BillType IN (SELECT * FROM #BillName)
								UNION ALL
								SELECT	B.BillNumberId,
										B.BillDate,
										B.BillCode,
										B.BillType,
										B.Comment,
										B.RedWord,
										CASE 
											WHEN B.BillType IN (115,128) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
											WHEN B.BillType IN (116,129) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
											ELSE 0
										END AS ArTotal,
										CASE 
											WHEN B.BillType IN (116,129) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
											WHEN B.BillType IN (115,128) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
											ELSE 0
										END AS ApTotal					
								FROM	BillIndex B,
										AdDebtBill A,
										#GetManSTypeId S,
										#GetManDTypeId D
								WHERE	B.BillNumberId = A.BillNumberId
										AND B.Stypeid = S.TypeId
										AND B.DTypeId = D.TypeId
										AND B.BillDate<@StartDate
										AND B.IfCheck = 't'
										AND B.IfYearBill = 0
										AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
										AND A.BTypeId LIKE @BTypeId+'%'
										AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
										AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
								UNION ALL
								SELECT	DISTINCT
										B.BillNumberId,
										B.BillDate,
										B.BillCode,
										B.BillType,
										B.Comment,
										B.RedWord,
										CASE 
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 0 	   AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 2 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 2 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											ELSE 0
										END  AS ArTotal,
										CASE 
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 1 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 1 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											ELSE 0
										END AS ApTotal		
								FROM	BillIndex B,
										AccountCredence A,
										#GetManSTypeId S,
										#GetManDTypeId D
								WHERE	B.BillNumberId = A.BillNumberId
										AND B.Stypeid = S.TypeId
										AND B.DTypeId = D.TypeId
										AND B.BillDate<@StartDate
										AND B.BillType = 159
										AND A.TypeATypeId IN ('0000100005','0000200001')
										AND B.IfCheck = 't'
										AND B.IfYearBill = 0
										AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
										AND A.ATypeId LIKE @BTypeId+'%'
										AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
										AND A.TypeATypeId LIKE  
											CASE
												WHEN @Type = 1 AND @BTypeAll = 0 THEN '0000100005'
												WHEN @Type = 2 AND @BTypeAll = 0 THEN '0000200001'
												ELSE '%'
											END						
										AND A.ATypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
							)B
				ELSE		--应付查询	
					SELECT	@BeforeMoney=
											CASE 
												WHEN @Type = 1 THEN ISNULL((SUM(B.ArTotal)-SUM(B.ApTotal)),0)
												ELSE ISNULL(SUM(B.ApTotal)-SUM(B.ArTotal),0)
											END
					FROM	(
								SELECT	BillNumberId,
										BillDate,
										BillCode,
										BillType,
										Comment, 
										RedWord,
										CASE 
											WHEN BillType IN (45,148,149,34,145,36,94,84,161,170,190) AND RedWord = 2	 			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186,189) AND RedWord IN (0,1) 	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (4)   AND RedWord = 0		       							THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											WHEN BillType IN (4)   AND RedWord = 1		       							THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											WHEN BillType IN (66) AND RedWord = 1										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											ELSE 0
										END  AS ArTotal,
										CASE 
											WHEN BillType IN (45,148,149,34,145,36,94,84,161,170) AND RedWord IN (0,1)			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (11,141,155,6,129,150,151,93,85,157,160,167,168,172,178,186)   AND RedWord = 2     THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)							
											WHEN BillType IN (4) AND RedWord = 2 									 	THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											WHEN BillType IN (66) AND RedWord = 0	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											WHEN BillType IN (66) AND RedWord = 2	 									THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											ELSE 0
										END AS ApTotal
								FROM	BillIndex
								INNER JOIN #GetManDTypeId D ON D.TypeId = Billindex.DTypeId
								WHERE	BillDate<@StartDate
										AND IfCheck = 't'	
										AND IfYearBill = 0
										AND RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
										AND BTypeId LIKE @BTypeId+'%'
										AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
										AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorID)) OR ISNULL(KTypeId,'')='' OR KTypeId = '10000')
										AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
										AND Stypeid IN (SELECT * FROM #GetManSTypeId)
										AND BillType IN (SELECT * FROM #BillName)
								UNION ALL
								SELECT	B.BillNumberId,
										B.BillDate,
										B.BillCode,
										B.BillType,
										B.Comment,
										B.RedWord,
										CASE 
											WHEN B.BillType IN (115,128) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
											WHEN B.BillType IN (116,129) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
											ELSE 0
										END AS ArTotal,
										CASE 
											WHEN B.BillType IN (116,129) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
											WHEN B.BillType IN (115,128) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
											ELSE 0
										END AS ApTotal					
								FROM	BillIndex B,
										AdDebtBill A,
										#GetManSTypeId S,
										#GetManDTypeId D
								WHERE	B.BillNumberId = A.BillNumberId
										AND B.Stypeid = S.TypeId
										AND B.DTypeId = D.TypeId
										AND B.BillDate<@StartDate
										AND B.IfCheck = 't'
										AND B.IfYearBill = 0
										AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
										AND A.BTypeId LIKE @BTypeId+'%'
										AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
										AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
								UNION ALL
								SELECT	DISTINCT
										B.BillNumberId,
										B.BillDate,
										B.BillCode,
										B.BillType,
										B.Comment,
										B.RedWord,
										CASE 
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 0 	   AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 2 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))>0 	THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 2 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											ELSE 0
										END  AS ArTotal,
										CASE 
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000200001' AND B.RedWord = 1 	 													THEN ABS(ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 0      AND (ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0))<0 	THEN -1*ISNULL(A.J_Total,0)+ISNULL(A.D_Total,0)
											WHEN A.TypeATypeId = '0000100005' AND B.RedWord = 1 														THEN ISNULL(A.J_Total,0)-ISNULL(A.D_Total,0)
											ELSE 0
										END AS ApTotal		
								FROM	BillIndex B,
										AccountCredence A,
										#GetManSTypeId S,
										#GetManDTypeId D
								WHERE	B.BillNumberId = A.BillNumberId
										AND B.Stypeid = S.TypeId
										AND B.DTypeId = D.TypeId
										AND B.BillDate<@StartDate
										AND B.BillType = 159
										AND A.TypeATypeId IN ('0000100005','0000200001')
										AND B.IfCheck = 't'
										AND B.IfYearBill = 0
										AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
										AND A.ATypeId LIKE @BTypeId+'%'
										AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
										AND A.TypeATypeId LIKE  
											CASE
												WHEN @Type = 1 AND @BTypeAll = 0 THEN '0000100005'
												WHEN @Type = 2 AND @BTypeAll = 0 THEN '0000200001'
												ELSE '%'
											END						
										AND A.ATypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
							)B
			END
	END


DROP TABLE #GetManSTypeId,#GetManDTypeId,#BillName




































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentBTypeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentBTypeLine]
GO






/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构往来单位的应收、应付线性查询
*/
CREATE PROCEDURE Web_QueryDepartmentBTypeLine
(
	@OperatorId		varchar(100),		--操作员的ID
	@DTypeId		varchar(100),		--部门的ID
	@BTypeId		varchar(100),		--往来单位ID
	@STypeId		varchar(8000),		--分支机构的ID
	@Type			int,				--查询类型  1.分支机构应收查询   2.分支机构应付查询
	@UserCode		varchar(256)='',	--商品编号
	@FullName		varchar(256)='',	--商品名称
	@ShowZero		int,				--是否显示为零  0.不显示   1.显示
	@TimePoint		varchar(12),		--历史状况查询
	@Bhys			varchar(max)	--包含预收（付） 1.包含 0.不包含
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @DTypeId = '' OR @DTypeId = '00000'
	SET @DTypeId = '%'
ELSE
	IF @DTypeId = '99999'
		SET @DTypeId = ''


DECLARE @BTypeAll 	int,			--客户和供货商是否统一
		@SQL		varchar(8000)	--SQL字符串

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'
IF @BTypeAll = 1
	BEGIN
		IF @BTypeId = '' OR @BTypeId = '00000'
			SET @BTypeId = '%'
	END
ELSE
	BEGIN
		IF @BTypeId = '' OR @BTypeId = '00000'	
			IF @Type = 1
				SET @BTypeId = '00001'
			ELSE
				SET @BTypeId = '00002'			
	END

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorID)
INSERT INTO #GetManKTypeId(TypeId)VALUES('')
INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetManDetailBType(@OperatorID) WHERE TypeId LIKE @BTypeId + '%'

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

CREATE TABLE #Result
(
	BTypeId		VARCHAR(100),
	LeftMoney	 NUMERIC(24, 10) 
)

--提取数据
SET @SQL = 'INSERT INTO #Result
			SELECT	BTypeId, '
					IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
						BEGIN
							IF @Type = 1	--分支机构应收查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN BillType IN (11,85,93,141,155,157,160,167,168,172,178,186,189)	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType IN (36,45,84,148,149)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
													WHEN BillType IN (4)						THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType IN (66)						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
													ELSE 0
												END 
											) AS LeftMoney '
							ELSE			--分支机构应付查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN BillType IN (34,84,145,36,94,161,170,186,190)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00001%''	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)	
													WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00002%''	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)
													WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)<0	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)	
													WHEN BillType IN (6,150,151,85,93)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
													WHEN BillType IN (66)						THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
													WHEN BillType IN (4)						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
													ELSE 0
												END 
											) AS LeftMoney '
			
									
						END
					ELSE	
						BEGIN
							IF @Type = 1	--分支机构应收查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172,178,186,189)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType IN (45,148,149,34,145,36,84,94,161,170)      		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
													WHEN BillType = 4  											THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType IN (66)										THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
													ELSE 0
												END 
											) AS LeftMoney '		
							ELSE			--分支机构应付查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172,178,186)		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
													WHEN BillType IN (45,148,149,34,145,36,84,94,161,170,190)      		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType = 4  											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
													WHEN BillType IN (66)										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
													ELSE 0
												END 
											) AS LeftMoney '				
						END						
		SET @SQL = @SQL + ' 
					FROM 	BillIndex '

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = BillIndex.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = BillIndex.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = BillIndex.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '				

		SET @SQL = @SQL + '
					WHERE	BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)
		IF @DTypeId = ''
			SET @SQL = @SQL + '	AND DTypeId = '+char(39)+@DTypeId+char(39)
		ELSE
			SET @SQL = @SQL + '	AND DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)
					
					IF ISDATE(@TimePoint)=1	--历史状况
						SET @SQL = @SQL + ' 
							AND BillDate<='+char(39)+@TimePoint+char(39)
					
					SET @SQL = @SQL + '
							AND IfCheck = ''t''
							AND RedWord = 0
							AND IfYearBill = 0 '
							
IF @Bhys = '0'
	BEGIN
		IF @Type = '1'
			SET @SQL = @SQL + ' AND BillType NOT IN (189) '
		ELSE
			SET @SQL = @SQL + ' AND BillType NOT IN (190) '
	END

SET @SQL = @SQL + '							
					GROUP BY BTypeId
					UNION ALL
					SELECT	A.BTypeId, '
						IF @Type = 1	--分支机构应收查询 
							SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN B.BillType IN (116,129)   THEN ISNULL(A.Total,0)
													WHEN B.BillType IN (115,128)   THEN -1*ISNULL(A.Total,0)
													ELSE 0
												END 
											) AS LeftMoney  '
						ELSE
							SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN B.BillType IN (116,129)   THEN -1*ISNULL(A.Total,0)
													WHEN B.BillType IN (115,128)   THEN ISNULL(A.Total,0)
													ELSE 0
												END 
											) AS LeftMoney  '
		SET @SQL = @SQL + '
					FROM 	BillIndex B
							INNER JOIN AdDebtBill A ON B.BillNumberId = A.BillNumberId'

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId =A.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '				

		SET @SQL = @SQL + '
					WHERE	A.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
							AND B.IfCheck = ''t''
							AND B.RedWord = 0 
							AND B.IfYearBill = 0'
		IF @DTypeId = ''
			SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
		ELSE
			SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

					IF ISDATE(@TimePoint)=1	--历史状况
						SET @SQL = @SQL + ' 
							AND B.BillDate<='+char(39)+@TimePoint+char(39)

					SET @SQL = @SQL + ' 
					GROUP BY A.BTypeId
					UNION ALL
					SELECT	L.BTypeId, '
						IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
							IF @Type = 1	--分支机构应收查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
													ELSE 0
												END
											) AS LeftMoney '
							ELSE
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN L.ATypeId = ''0000200001''	THEN ISNULL(L.Total,0)
													ELSE 0
												END
											) AS LeftMoney '
						ELSE
							IF @Type = 1	--分支机构应收查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
													WHEN L.ATypeId = ''0000200001'' THEN -1*ISNULL(L.Total,0)
													ELSE 0
												END
											) AS LeftMoney '
							ELSE
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN L.ATypeId = ''0000100005''	THEN -1*ISNULL(L.Total,0)
													WHEN L.ATypeId = ''0000200001'' THEN ISNULL(L.Total,0)
													ELSE 0
												END
											) AS LeftMoney '									
			SET @SQL = @SQL + '		
					FROM	BillIndex B
							INNER JOIN ListTable L ON B.BillNumberId = L.BillNumberId '

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = L.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '				
		
		SET @SQL = @SQL + '
					WHERE	B.BillType = 159
							AND L.ATypeId IN (''0000100005'',''0000200001'')					
							AND B.IfCheck = ''t''
							AND B.RedWord = 0
							AND B.IfYearBill = 0
							AND L.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)

		IF @DTypeId = ''
			SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
		ELSE
			SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)


		IF ISDATE(@TimePoint)=1	--历史状况
			SET @SQL = @SQL + ' 
				AND B.BillDate<='+char(39)+@TimePoint+char(39)

		SET @SQL = @SQL + ' 
		GROUP BY L.BTypeId'

--PRINT(@SQL)
EXEC(@SQL)


--正式运算数据
SET @SQL = 'SELECT	B.*
			FROM	(		
						SELECT	B.TypeId,
								B.SonNum,
								B.UserCode,
								B.FullName,
								ISNULL(SUM(D.ArLimit),0) AS ArLimit,
								ISNULL(SUM(D.LeftMoney),0) AS LeftMoney
						FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B
						LEFT JOIN (
									SELECT	BTypeId,
											SUM(LeftMoney) AS LeftMoney,
											0 AS ArLimit
									FROM	#Result					
									GROUP BY BTypeId
									UNION ALL
									SELECT	C.BTypeId,
											0 AS LeftMoney,
											SUM(C.Credit) AS ArLimit
									FROM	BType_Credit C
									INNER JOIN #GetManSTypeId S ON S.TypeId = C.STypeId
									GROUP BY C.BTypeId									
								)D ON D.BTypeId = B.TypeId
						WHERE	B.Deleted = 0 
								AND B.SonNum = 0 
								AND B.TypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
								AND B.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
								AND B.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
						GROUP BY
								B.TypeId,
								B.SonNum,
								B.UserCode,
								B.FullName,
								B.ArLimit
					)B '
					
				IF @ShowZero = 0
					SET @SQL = @SQL + ' WHERE ISNULL(B.LeftMoney,0) <> 0 '
					
		SET @SQL = @SQL + ' 					
					ORDER BY B.UserCode'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Result,#GetManETypeId,#GetManKTypeId,#GetManBTypeId,#GetManSTypeId



































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentBTypeList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentBTypeList]
GO



/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构往来单位的应收、应付树型查询
*/
CREATE PROCEDURE Web_QueryDepartmentBTypeList
(
	@OperatorId		varchar(100),	--操作员的ID
	@DTypeId		varchar(100),	--部门的ID	
	@BTypeId		varchar(100),	--往来单位ID
	@STypeId		varchar(8000),	--分支机构的ID
	@Type			int,			--查询类型  1.分支机构应收查询   2.分支机构应付查询
	@TimePoint		varchar(12),	--历史状况查询
	@Bhys			varchar(max)	--包含预收（付） 1.包含 0.不包含
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @DTypeId = '' OR @DTypeId = '00000'
	SET @DTypeId = '%'
ELSE
	IF @DTypeId = '99999'
		SET @DTypeId = ''

DECLARE @SonNum 	int,			--当前SonNum值
		@BTypeAll 	int,			--客户和供货商是否统一
		@BTypeMxId	varchar(100),
		@SQL		varchar(8000)	--SQL字符串

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

IF @BTypeId = '' 
	SET @BTypeId = '00000'

IF @BTypeAll = 1	--客户和供货商统一
	BEGIN
		IF @BTypeId = '00000'
			SET @BTypeMxId = '%'
		ELSE			
			SET @BTypeMxId = @BTypeId

		SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0
	END
ELSE
	BEGIN
		IF @BTypeId = '00000'
			BEGIN
				IF @Type = 1
					SET @BTypeId = '00001'
				ELSE
					SET @BTypeId = '00002'				
				
				SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0
			END
		ELSE
			SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId AND Deleted = 0

		SET @BTypeMxId = @BTypeId		
	END

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorID)
INSERT INTO #GetManKTypeId(TypeId)VALUES('')
INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetManDetailBType(@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

CREATE TABLE #Result
(
	BTypeId		VARCHAR(100),
	LeftMoney	 NUMERIC(24, 10) 
)

--提取数据
SET @SQL = 'INSERT INTO #Result
			SELECT	BTypeId, '
					IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
						BEGIN
							IF @Type = 1	--分支机构应收查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN BillType IN (11,85,93,141,155,157,160,167,168,172,178,186,189)	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType IN (36,45,84,148,149)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
													WHEN BillType IN (4)						THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType IN (66)						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
													ELSE 0
												END 
											) AS LeftMoney '
							ELSE			--分支机构应付查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN BillType IN (34,84,145,36,94,161,170,186,190)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00001%''	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)	
													WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00002%''	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)
													WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)<0	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)	
													WHEN BillType IN (6,150,151,85,93)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
													WHEN BillType IN (66)						THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
													WHEN BillType IN (4)						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
													ELSE 0
												END 
											) AS LeftMoney '
			
									
						END
					ELSE	
						BEGIN
							IF @Type = 1	--分支机构应收查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172,178,186,189)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType IN (45,148,149,34,145,36,84,94,161,170)      		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
													WHEN BillType = 4  											THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType IN (66)										THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
													ELSE 0
												END 
											) AS LeftMoney '		
							ELSE			--分支机构应付查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172,178,186)		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
													WHEN BillType IN (45,148,149,34,145,36,84,94,161,170,190)      		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
													WHEN BillType = 4  											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
													WHEN BillType IN (66)										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
													ELSE 0
												END 
											) AS LeftMoney '				
						END						
		SET @SQL = @SQL + ' 
					FROM 	BillIndex '

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = BillIndex.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = BillIndex.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId =BillIndex.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '				

		SET @SQL = @SQL + '
					WHERE	BTypeId LIKE '+char(39)+@BTypeMxId+'%'+char(39)
		IF @DTypeId = ''
			SET @SQL = @SQL + '	AND DTypeId = '+char(39)+@DTypeId+char(39)
		ELSE
			SET @SQL = @SQL + '	AND DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)
					
					IF ISDATE(@TimePoint)=1	--历史状况
						SET @SQL = @SQL + ' 
							AND BillDate<='+char(39)+@TimePoint+char(39)
					
					SET @SQL = @SQL + '
							AND IfCheck = ''t''
							AND RedWord = 0
							AND IfYearBill = 0 '
							
IF @Bhys = '0'
	BEGIN
		IF @Type = '1'
			SET @SQL = @SQL + ' AND BillType NOT IN (189) '
		ELSE
			SET @SQL = @SQL + ' AND BillType NOT IN (190) '
	END

SET @SQL = @SQL + '							
					GROUP BY BTypeId
					UNION ALL
					SELECT	A.BTypeId, '
						IF @Type = 1	--分支机构应收查询 
							SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN B.BillType IN (116,129)   THEN ISNULL(A.Total,0)
													WHEN B.BillType IN (115,128)   THEN -1*ISNULL(A.Total,0)
													ELSE 0
												END 
											) AS LeftMoney  '
						ELSE
							SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN B.BillType IN (116,129)   THEN -1*ISNULL(A.Total,0)
													WHEN B.BillType IN (115,128)   THEN ISNULL(A.Total,0)
													ELSE 0
												END 
											) AS LeftMoney  '
		SET @SQL = @SQL + '
					FROM 	BillIndex B
							INNER JOIN AdDebtBill A ON B.BillNumberId = A.BillNumberId'

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = A.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '				

		SET @SQL = @SQL + '
					WHERE	A.BTypeId LIKE '+char(39)+@BTypeMxId+'%'+char(39)+'
							AND B.IfCheck = ''t''
							AND B.RedWord = 0 
							AND B.IfYearBill = 0'
		IF @DTypeId = ''
			SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
		ELSE
			SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

					IF ISDATE(@TimePoint)=1	--历史状况
						SET @SQL = @SQL + ' 
							AND B.BillDate<='+char(39)+@TimePoint+char(39)

					SET @SQL = @SQL + ' 
					GROUP BY A.BTypeId
					UNION ALL
					SELECT	L.BTypeId, '
						IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
							IF @Type = 1	--分支机构应收查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
													ELSE 0
												END
											) AS LeftMoney '
							ELSE
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN L.ATypeId = ''0000200001''	THEN ISNULL(L.Total,0)
													ELSE 0
												END
											) AS LeftMoney '
						ELSE
							IF @Type = 1	--分支机构应收查询
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
													WHEN L.ATypeId = ''0000200001'' THEN -1*ISNULL(L.Total,0)
													ELSE 0
												END
											) AS LeftMoney '
							ELSE
								SET @SQL = @SQL + '
										SUM(
												CASE
													WHEN L.ATypeId = ''0000100005''	THEN -1*ISNULL(L.Total,0)
													WHEN L.ATypeId = ''0000200001'' THEN ISNULL(L.Total,0)
													ELSE 0
												END
											) AS LeftMoney '									
			SET @SQL = @SQL + '		
					FROM	BillIndex B
							INNER JOIN ListTable L ON B.BillNumberId = L.BillNumberId '

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = L.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '				
		
		SET @SQL = @SQL + '
					WHERE	B.BillType = 159
							AND L.ATypeId IN (''0000100005'',''0000200001'')					
							AND B.IfCheck = ''t''
							AND B.RedWord = 0
							AND B.IfYearBill = 0
							AND L.BTypeId LIKE '+char(39)+@BTypeMxId+'%'+char(39)

		IF @DTypeId = ''
			SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
		ELSE
			SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)


		IF ISDATE(@TimePoint)=1	--历史状况
			SET @SQL = @SQL + ' 
				AND B.BillDate<='+char(39)+@TimePoint+char(39)

		SET @SQL = @SQL + ' 
		GROUP BY L.BTypeId'

--PRINT(@SQL)
EXEC(@SQL)


--正式运算数据
SET @SQL = '
		SELECT	B.TypeId,
				B.SonNum,
				B.UserCode,
				B.FullName,
				ISNULL(SUM(D.ArLimit),0) AS ArLimit,
				ISNULL(SUM(D.LeftMoney),0) AS LeftMoney
		FROM	F_GetManBTypeAll('+char(39)+@OperatorID+char(39)+') B
		LEFT JOIN (
					SELECT	BTypeId,
							SUM(LeftMoney) AS LeftMoney,
							0 AS ArLimit
					FROM	#Result					
					GROUP BY BTypeId
					UNION ALL
					SELECT	C.BTypeId,
							0 AS LeftMoney,
							SUM(C.Credit) AS ArLimit
					FROM	BType_Credit C
					INNER JOIN #GetManSTypeId S ON S.TypeId = C.STypeId
					GROUP BY C.BTypeId
				)D ON LEFT(D.BTypeId,LEN(B.TypeId)) = B.TypeId
		WHERE	B.Deleted = 0 '

		IF @SonNum>=1
			SET @SQL = @SQL + ' AND B.ParId = '+char(39)+@BTypeId+char(39)
		ELSE
			SET @SQL = @SQL + ' AND B.TypeId = '+char(39)+@BTypeId+char(39)	

SET @SQL = @SQL + ' 
		GROUP BY
				B.TypeId,
				B.SonNum,
				B.UserCode,
				B.FullName,
				B.ArLimit
		ORDER BY B.UserCode'

--PRINT(@SQL)
EXEC(@SQL)


DROP TABLE #Result,#GetManETypeId,#GetManKTypeId,#GetManBTypeId,#GetManSTypeId








































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentEmployeeDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentEmployeeDetail]
GO



















/*
	作者：谢吉康
	日期：2005-8-11
	描述：分支机构职员的应收、应付往来对帐查询
*/
CREATE  PROCEDURE Web_QueryDepartmentEmployeeDetail
(
	@OperatorId		varchar(100),			--操作员的ID
	@DTypeId		varchar(100),			--部门的ID
	@ETypeId		varchar(100),			--职员ID
	@STypeId		varchar(8000),			--分支机构的ID
	@StartDate		varchar(12),			--开始日期
	@EndDate		varchar(12),			--截至日期
	@ShowRedWord	int,					--是否显示红冲单据  1.显示红冲单据   0.不显示红冲单据
	@Type			int,					--查询类别   1.应收    2.应付
	@SortField		varchar(100),			--排序字段
	@SortType		varchar(10),			--排序方式	ASC 升序   DESC 降序
	@Bhys			varchar(max)			--包含预收（付） 1.包含 0.不包含
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--必须处理往来管理的权限
DECLARE @BTypeAll 	int,
		@BTypeId	varchar(100)

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

IF @BTypeAll = 0
	BEGIN
		IF @Type = 1
			SET @BTypeId = '00001'
		ELSE
			SET @BTypeId = '00002'
	END
ELSE
	SET @BTypeId = '%'

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

DECLARE @SQL		varchar(8000)	--SQL字符串

--求当前查询期间内的数据
SET @SQL = '
	SELECT	B.BillNumberId,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.Comment,
			B.RedWord,
			B.ETypeId,
			B.STypeId,
			B.[ID],
			B.FullName,			
			ISNULL(B.ArTotal,0) AS ArTotal,
			ISNULL(B.ApTotal,0) AS ApTotal,
			ISNULL(B.ArTotal,0)-ISNULL(B.ApTotal,0) AS ArLeftMoney,
			ISNULL(B.ApTotal,0)-ISNULL(B.ArTotal,0) AS ApLeftMoney
	FROM	(
				SELECT	BillNumberId,
						BillDate,
						BillCode,
						BillType,
						Comment, 
						RedWord,
						ETypeId,
						STypeId,
						[Id],
						FullName = (SELECT FullName FROM Employee WHERE TypeId = BillIndex.ETypeId), 
						CASE 
							WHEN BillType IN (45,115,148,149,34,145,128,36,84,94,161,170,190) AND RedWord = 1	 	    THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0) - ISNULL(preferencemoney,0)
							WHEN BillType IN (11,141,155,116,6,129,150,151,93,85,160,167,168,172,178,186,189) AND RedWord IN (0,1) 		THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0) - ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 0													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 0													THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 2													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 2													THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 1 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							ELSE 0
						END  AS '
					IF @Type = 1 
						SET @SQL = @SQL + ' ArTotal,'
					ELSE
						SET @SQL = @SQL + ' ApTotal,'

					SET @SQL = @SQL + '
						CASE 
							WHEN BillType IN (45,115,148,149,34,145,128,36,84,94,161,170,190) AND RedWord IN (0,2)		THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0)  - ISNULL(preferencemoney,0)
							WHEN BillType IN (11,141,155,116,6,129,150,151,93,85,160,167,168,172,178,186,189)   AND RedWord = 2       	THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0)  - ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 0 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 2	 											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 1 													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 1 												THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							ELSE 0
						END AS '
					IF @Type = 1 
						SET @SQL = @SQL +  ' ApTotal '
					ELSE 
						SET @SQL = @SQL + '  ArTotal '

			SET @SQL = @SQL + '
				FROM	BillIndex '
				
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '
				
			IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId '									
			
			SET @SQL = @SQL + '	
				WHERE	BillDate>='+char(39)+@StartDate+char(39)+'
						AND BillDate<='+char(39)+@EndDate+char(39)+'
						AND IfCheck = ''t''
						AND IfYearBill = 0
						AND ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)

				IF @DTypeID = ''
					SET @SQL = @SQL + ' AND DTypeId = '+char(39)+@DTypeId+char(39)
				ELSE
					SET @SQL = @SQL + ' AND DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)
					
				IF @Bhys = '0'
					BEGIN
						IF @Type = '1'
							SET @SQL = @SQL + ' AND BillType NOT IN (189) '
						ELSE
							SET @SQL = @SQL + ' AND BillType NOT IN (190) '
					END					

				SET @SQL = @SQL + '
						AND ETypeId IN (SELECT * FROM F_GetManDetailEType('+char(39)+@OperatorID+char(39)+'))
						AND (KTypeId IN (SELECT * FROM F_GetManDetailKType('+char(39)+@OperatorID+char(39)+')) OR ISNULL(KTypeId,'''')='''' OR KTypeId = ''10000'')
						AND BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
						AND BTypeId IN (SELECT * FROM F_GetManDetailBType('+char(39)+@OperatorID+char(39)+'))
				UNION ALL
				SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.Comment, 
						B.RedWord,
						B.ETypeId,
						B.STypeId,
						B.Id,
						FullName = (SELECT FullName FROM Employee WHERE TypeId = B.ETypeId),
						CASE 
							WHEN B.BillType IN (115,128)   AND RedWord = 1    	THEN ISNULL(A.Total,0)
							WHEN B.BillType IN (116,129) AND RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
							ELSE 0
						END  AS ArTotal,
						CASE 
							WHEN B.BillType IN (115,128)   AND RedWord IN (0,2)    	THEN ISNULL(A.Total,0)
							WHEN B.BillType IN (116,129)   AND RedWord = 1    		THEN ISNULL(A.Total,0)
							ELSE 0
						END AS ApTotal
				FROM	BillIndex B
				INNER JOIN	AdDebtBill A ON B.BillNumberId = A.BillNumberId '
				
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		
					
				IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId '									
				
				SET @SQL = @SQL + '
				WHERE	B.BillDate>='+char(39)+@StartDate+char(39)+'
						AND B.BillDate<='+char(39)+@EndDate+char(39)+'
						AND B.IfCheck = ''t''
						AND B.IfYearBill = 0
						AND B.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)

				IF @DTypeID = ''
					SET @SQL = @SQL + ' AND B.DTypeId = '+char(39)+@DTypeId+char(39)
				ELSE
					SET @SQL = @SQL + ' AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

				SET @SQL = @SQL + '
						AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType('+char(39)+@OperatorID+char(39)+'))
						AND (B.KTypeId IN (SELECT * FROM F_GetManDetailKType('+char(39)+@OperatorID+char(39)+')) OR ISNULL(B.KTypeId,'''')='''' OR B.KTypeId = ''10000'')
						AND A.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'								
						AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType('+char(39)+@OperatorID+char(39)+'))
				UNION ALL
				SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.Comment, 
						B.RedWord,
						B.ETypeId,
						B.STypeId,
						B.Id,
						FullName = (SELECT FullName FROM Employee WHERE TypeId = B.ETypeId), '
				IF @Type = 1 --应收查询
					SET @SQL = @SQL + '
						CASE 
							WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 0		THEN ISNULL(A.Total,0)
							WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 2		THEN ISNULL(ABS(A.Total),0)
							WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 1 		THEN ISNULL(ABS(A.Total),0)
							ELSE 0
						END AS ArTotal,
						CASE 
							WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 0		THEN ISNULL(A.Total,0)
							WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 2		THEN ISNULL(ABS(A.Total),0)
							WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 1 		THEN ISNULL(ABS(A.Total),0)
							ELSE 0
						END  AS ApTotal '
				ELSE		 --应付查询
					SET @SQL = @SQL + '
						CASE 
							WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 0		THEN ISNULL(A.Total,0)
							WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 2		THEN ISNULL(ABS(A.Total),0)
							WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 1 		THEN ISNULL(ABS(A.Total),0)
							ELSE 0
						END AS ArTotal,
						CASE 
							WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 0		THEN ISNULL(A.Total,0)
							WHEN A.ATypeId = ''0000200001'' AND B.RedWord = 2		THEN ISNULL(ABS(A.Total),0)
							WHEN A.ATypeId = ''0000100005'' AND B.RedWord = 1 		THEN ISNULL(ABS(A.Total),0)
							ELSE 0
						END  AS ApTotal '

			SET @SQL = @SQL + '
				FROM	BillIndex B
				INNER JOIN ListTable A ON B.BillNumberId = A.BillNumberId '
				
				IF NOT (@STypeId = '' AND @MStypeid = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '	
					
				IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
					SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = B.DTypeId '										
				
			SET @SQL = @SQL + '	
				WHERE	A.BillNumberId = B.BillNumberId
						AND B.BillType = 159
						AND A.ATypeId IN (''0000100005'',''0000200001'')
						AND B.BillDate>='+char(39)+@StartDate+char(39)+'
						AND B.BillDate<='+char(39)+@EndDate+char(39)+'
						AND B.IfCheck = ''t''
						AND B.IfYearBill = 0
						AND B.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)

				IF @DTypeID = ''
					SET @SQL = @SQL + ' AND B.DTypeId = '+char(39)+@DTypeId+char(39)
				ELSE
					SET @SQL = @SQL + ' AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

				IF @BTypeAll = 0
					IF @Type = 1
						SET @SQL = @SQL + ' AND A.ATypeId = ''0000100005'''
					ELSE
						SET @SQL = @SQL + ' AND A.ATypeId = ''0000200001'''

				SET @SQL = @SQL + '
						AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType('+char(39)+@OperatorID+char(39)+'))
						AND (B.KTypeId IN (SELECT * FROM F_GetManDetailKType('+char(39)+@OperatorID+char(39)+')) OR ISNULL(B.KTypeId,'''')='''' OR B.KTypeId = ''10000'')						
						AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType('+char(39)+@OperatorID+char(39)+'))
			)B
	WHERE	(ISNULL(B.ArTotal,0)<>0	OR ISNULL(B.ApTotal,0)<>0 ) '

--是否显示红冲单据
IF @ShowRedWord = 0
	SET @SQL = @SQL + ' AND B.RedWord = 0'

--排序
SET @SQL = @SQL + ' ORDER BY '+@SortField+' '+@SortType

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManDTypeId


















































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentEmployeeDetailGetBefore]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentEmployeeDetailGetBefore]
GO











/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构职员的应收、应付往来对帐查询此前余额
*/
CREATE PROCEDURE Web_QueryDepartmentEmployeeDetailGetBefore
(
	@OperatorId		varchar(100),			--操作员的ID
	@DTypeId		varchar(100),			--部门的ID
	@ETypeId		varchar(100),			--往来单位ID
	@STypeId		varchar(8000),			--分支机构ID
	@StartDate		varchar(12),			--开始日期
	@EndDate		varchar(12),			--截至日期
	@ShowRedWord	varchar(10),			--是否显示红冲单据  1.显示红冲单据   0.不显示红冲单据
	@Type			int,					--查询类别   1.应收    2.应付
	@Bhys			varchar(max),			--包含预收（付） 1.包含 0.不包含
	@BeforeMoney	 NUMERIC(24, 10)  OUTPUT	--此前余额
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
-------------------------------------------------------------权限检查-------------------------------------------------------

IF @DTypeId = '' OR @DTypeId = '00000'
	SET @DTypeId = '%'
ELSE
	IF @DTypeId = '99999'
		SET @DTypeId = ''

IF @ShowRedWord = 1
	SET @ShowRedWord = '0,1,2'

--必须处理往来管理的权限
DECLARE @BTypeAll 	int,
		@BTypeId	varchar(100)

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

IF @BTypeAll = 0
	BEGIN
		IF @Type = 1
			SET @BTypeId = '00001'
		ELSE
			SET @BTypeId = '00002'
	END
ELSE
	SET @BTypeId = '%'
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)		

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--单据类型
CREATE TABLE #BillName
(
	BillType INT
)
IF @Bhys = '1'
	BEGIN
		INSERT INTO #BillName(BillType)SELECT BillType FROM BillName
	END
ELSE
	BEGIN
		IF @Type = '1'		
			INSERT INTO #BillName(BillType)SELECT BillType FROM BillName WHERE Billtype NOT IN (189)
		ELSE
			INSERT INTO #BillName(BillType)SELECT BillType FROM BillName WHERE Billtype NOT IN (190)
	END

DECLARE @SQL		varchar(8000)	--SQL字符串

--求此前余额
--求此前余额
IF @DTypeId = ''
	SELECT	@BeforeMoney=
							CASE 
								WHEN @Type = 1 THEN ISNULL((SUM(B.ArTotal)-SUM(B.ApTotal)),0)
								ELSE ISNULL(SUM(B.ApTotal)-SUM(B.ArTotal),0)
							END
	FROM	(
				SELECT	BillNumberId,
						BillDate,
						BillCode,
						BillType,
						Comment, 
						RedWord,
						CASE 
							WHEN BillType IN (45,115,148,149,34,145,128,36,84,94,161,170,190) AND RedWord = 1	 	    THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0) - ISNULL(preferencemoney,0)
							WHEN BillType IN (11,141,155,116,6,129,150,151,93,85,160,167,168,172,178,186,189) AND RedWord IN (0,1) 		THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0) - ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 0													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 0													THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 2													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 2													THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 1 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							ELSE 0
						END  AS ArTotal,
						CASE 
							WHEN BillType IN (45,115,148,149,34,145,128,36,84,94,161,170,190) AND RedWord IN (0,2)		THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0)  - ISNULL(preferencemoney,0)
							WHEN BillType IN (11,141,155,116,6,129,150,151,93,85,160,167,168,172,178,189)   AND RedWord = 2       	THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0)  - ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 0 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 2	 											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 1 													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 1 												THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							ELSE 0
						END AS ApTotal
				FROM	BillIndex
				INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId
				WHERE	BillDate<@StartDate
						AND IfCheck = 't'
						AND IfYearBill = 0
						AND RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
						AND ETypeId LIKE @ETypeId+'%'
						AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
						AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorID)) OR ISNULL(KTypeId,'')='' OR KTypeId = '10000')
						AND BTypeId LIKE @BTypeId+'%'
						AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
						AND Stypeid IN (SELECT * FROM #GetManSTypeId)
						AND BillType IN (SELECT * FROM #BillName)
				UNION ALL
				SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.Comment,
						B.RedWord,
						CASE 
							WHEN B.BillType IN (115,128) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
							WHEN B.BillType IN (116,129) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
							ELSE 0
						END AS ArTotal,
						CASE 
							WHEN B.BillType IN (116,129) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
							WHEN B.BillType IN (115,128) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
							ELSE 0
						END AS ApTotal					
				FROM	BillIndex B,
						AdDebtBill A,
						#GetManSTypeId S,
						#GetManDTypeId D
				WHERE	B.BillNumberId = A.BillNumberId
						AND B.Stypeid = S.TypeId
						AND B.DTypeId = D.TypeId
						AND B.BillDate<@StartDate
						AND B.IfCheck = 't'
						AND B.IfYearBill = 0
						AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
						AND B.ETypeId LIKE @ETypeId+'%'						
						AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
						AND A.BTypeId LIKE @BTypeId+'%'						
						AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
				UNION ALL
				SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.Comment,
						B.RedWord,
						CASE 
							WHEN A.ATypeId = '0000100005' AND B.RedWord = 0		THEN ISNULL(A.Total,0)
							WHEN A.ATypeId = '0000100005' AND B.RedWord = 2		THEN ISNULL(ABS(A.Total),0)
							WHEN A.ATypeId = '0000200001' AND B.RedWord = 1 	THEN ISNULL(ABS(A.Total),0)
							ELSE 0
						END AS ArTotal,
						CASE 
							WHEN A.ATypeId = '0000200001' AND B.RedWord = 0		THEN ISNULL(A.Total,0)
							WHEN A.ATypeId = '0000200001' AND B.RedWord = 2		THEN ISNULL(ABS(A.Total),0)
							WHEN A.ATypeId = '0000100005' AND B.RedWord = 1 	THEN ISNULL(ABS(A.Total),0)
							ELSE 0
						END  AS ApTotal		
				FROM	BillIndex B,
						ListTable A,
						#GetManSTypeId S,
						#GetManDTypeId D
				WHERE	B.BillNumberId = A.BillNumberId
						AND B.Stypeid = S.TypeId
						AND B.DTypeId = d.TypeId
						AND B.BillDate<@StartDate
						AND B.BillType = 159
						AND A.ATypeId IN ('0000100005','0000200001')
						AND B.IfCheck = 't'
						AND B.IfYearBill = 0
						AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
						AND B.ETypeId LIKE @ETypeId+'%'
						AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
						AND A.ATypeId LIKE 
							CASE
								WHEN @Type = 1 AND @BTypeAll = 0 THEN '0000100005'
								WHEN @Type = 2 AND @BTypeAll = 0 THEN '0000200001'
								ELSE '%'
							END					
						AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
			)B
ELSE
	SELECT	@BeforeMoney=
							CASE 
								WHEN @Type = 1 THEN ISNULL((SUM(B.ArTotal)-SUM(B.ApTotal)),0)
								ELSE ISNULL(SUM(B.ApTotal)-SUM(B.ArTotal),0)
							END
	FROM	(
				SELECT	BillNumberId,
						BillDate,
						BillCode,
						BillType,
						Comment, 
						RedWord,
						CASE 
							WHEN BillType IN (45,115,148,149,34,145,128,36,84,94,161,170,190) AND RedWord = 1	 	    THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0) - ISNULL(preferencemoney,0)
							WHEN BillType IN (11,141,155,116,6,129,150,151,93,85,160,167,168,172,178,186,189) AND RedWord IN (0,1) 		THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0) - ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 0													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 0													THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 2													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 2													THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 1 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							ELSE 0
						END  AS ArTotal,
						CASE 
							WHEN BillType IN (45,115,148,149,34,145,128,36,84,94,161,170,190) AND RedWord IN (0,2)		THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0)  - ISNULL(preferencemoney,0)
							WHEN BillType IN (11,141,155,116,6,129,150,151,93,85,160,167,168,172,178,186,189)   AND RedWord = 2       	THEN ISNULL(TotalMoney,0)- ISNULL(TotalInMoney,0)  - ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 0 												THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType IN (4) AND RedWord = 2	 											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 66 AND RedWord = 1 													THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
							WHEN BillType = 157 AND RedWord = 1 												THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
							ELSE 0
						END AS ApTotal
				FROM	BillIndex
				INNER JOIN #GetManDTypeId D ON D.TypeId = BillIndex.DTypeId
				WHERE	BillDate<@StartDate
						AND IfCheck = 't'
						AND IfYearBill = 0
						AND RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
						AND ETypeId LIKE @ETypeId+'%'
						AND ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
						AND (KTypeId IN (SELECT * FROM F_GetManDetailKType(@OperatorID)) OR ISNULL(KTypeId,'')='' OR KTypeId = '10000')
						AND BTypeId LIKE @BTypeId+'%'
						AND BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
						AND Stypeid IN (SELECT * FROM #GetManSTypeId)
						AND BillType IN (SELECT * FROM #BillName)
				UNION ALL
				SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.Comment,
						B.RedWord,
						CASE 
							WHEN B.BillType IN (115,128) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
							WHEN B.BillType IN (116,129) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
							ELSE 0
						END AS ArTotal,
						CASE 
							WHEN B.BillType IN (116,129) AND B.RedWord = 1 			THEN ISNULL(A.Total,0)
							WHEN B.BillType IN (115,128) AND B.RedWord IN (0,2) 	THEN ISNULL(A.Total,0)
							ELSE 0
						END AS ApTotal					
				FROM	BillIndex B,
						AdDebtBill A,
						#GetManSTypeId S,
						#GetManDTypeId D
				WHERE	B.BillNumberId = A.BillNumberId
						AND B.Stypeid = S.TypeId
						AND B.DTypeId = D.TypeId
						AND B.BillDate<@StartDate
						AND B.IfCheck = 't'
						AND B.IfYearBill = 0
						AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
						AND B.ETypeId LIKE @ETypeId+'%'
						AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
						AND A.BTypeId LIKE @BTypeId+'%'					
						AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))
				UNION ALL
				SELECT	B.BillNumberId,
						B.BillDate,
						B.BillCode,
						B.BillType,
						B.Comment,
						B.RedWord,
						CASE 
							WHEN A.ATypeId = '0000100005' AND B.RedWord = 0		THEN ISNULL(A.Total,0)
							WHEN A.ATypeId = '0000100005' AND B.RedWord = 2		THEN ISNULL(ABS(A.Total),0)
							WHEN A.ATypeId = '0000200001' AND B.RedWord = 1 	THEN ISNULL(ABS(A.Total),0)
							ELSE 0
						END AS ArTotal,
						CASE 
							WHEN A.ATypeId = '0000200001' AND B.RedWord = 0		THEN ISNULL(A.Total,0)
							WHEN A.ATypeId = '0000200001' AND B.RedWord = 2		THEN ISNULL(ABS(A.Total),0)
							WHEN A.ATypeId = '0000100005' AND B.RedWord = 1 	THEN ISNULL(ABS(A.Total),0)
							ELSE 0
						END  AS ApTotal				
				FROM	BillIndex B,
						ListTable A,
						#GetManSTypeId S,
						#GetManDTypeId D
				WHERE	B.BillNumberId = A.BillNumberId
						AND B.Stypeid = S.TypeId
						AND B.DTypeId = d.TypeId
						AND B.BillDate<@StartDate
						AND B.BillType = 159
						AND A.ATypeId IN ('0000100005','0000200001')
						AND B.IfCheck = 't'
						AND B.IfYearBill = 0
						AND B.RedWord IN (SELECT * FROM f_Split(@ShowRedWord,','))
						AND B.ETypeId LIKE @ETypeId+'%'
						AND B.ETypeId IN (SELECT * FROM F_GetManDetailEType(@OperatorID))
						AND A.ATypeId LIKE 
							CASE
								WHEN @Type = 1 AND @BTypeAll = 0 THEN '0000100005'
								WHEN @Type = 2 AND @BTypeAll = 0 THEN '0000200001'
								ELSE '%'
							END						
						AND A.BTypeId IN (SELECT * FROM F_GetManDetailBType(@OperatorID))

			)B




DROP TABLE #GetManSTypeId,#GetManDTypeId,#BillName








































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentEmployeeLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentEmployeeLine]
GO


/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构职员的应收、应付线性查询
*/
CREATE PROCEDURE Web_QueryDepartmentEmployeeLine
(
	@OperatorId		varchar(100),		--操作员的ID
	@DTypeId		varchar(100),		--部门的ID
	@ETypeId		varchar(100),		--职员ID
	@STypeId		varchar(8000),		--分支机构的ID
	@Type			int,				--查询类型  1.分支机构应收查询   2.分支机构应付查询
	@UserCode		varchar(256)='',	--商品编号
	@FullName		varchar(256)='',	--商品名称
	@ShowZero		int,				--是否显示为零  0.不显示   1.显示
	@TimePoint		varchar(12),		--历史状况查询
	@Bhys			varchar(max)		--包含预收（付） 1.包含 0.不包含
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @DTypeId = '' OR @DTypeId = '00000'
	SET @DTypeId = '%'
ELSE
	IF @DTypeId = '99999'
		SET @DTypeId = ''

--必须处理往来管理的权限
DECLARE @BTypeAll 	int,
		@BTypeId	varchar(100)

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

IF @BTypeAll = 0
	BEGIN
		IF @Type = 1
			SET @BTypeId = '00001'
		ELSE
			SET @BTypeId = '00002'
	END
ELSE
	SET @BTypeId = '%'

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID) WHERE TypeId LIKE @ETypeId + '%'

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorID)
INSERT INTO #GetManKTypeId(TypeId)VALUES('')
INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetManDetailBType(@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)


DECLARE @SQL		varchar(8000)	--SQL字符串

CREATE TABLE #Result
(
	ETypeId		VARCHAR(100),
	LeftMoney	 NUMERIC(24, 10) 
)

--提取数据
SET @SQL = 'INSERT INTO #Result
			SELECT	ETypeId, '					
				IF @Type = 1	--分支机构应收查询
					SET @SQL = @SQL + '
							SUM(
									CASE
										WHEN BillType IN (11,141,155,6,150,151,93,85,160,167,168,172,178,190)			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
										WHEN BillType IN (45,148,149,34,145,36,84,94,161,170,186,189)      		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
										WHEN BillType = 4  											THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
										WHEN BillType = 66											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
										WHEN BillType = 157											THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
										ELSE 0
									END 
								) AS LeftMoney '		
				ELSE			--分支机构应付查询
					SET @SQL = @SQL + '
							SUM(
									CASE
										WHEN BillType IN (11,141,155,6,150,151,93,85,160,167,168,172,178,190)			THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
										WHEN BillType IN (45,148,149,34,145,36,84,94,161,170,186,189)      		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
										WHEN BillType = 4  											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
										WHEN BillType = 66											THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
										WHEN BillType = 157											THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0))
										ELSE 0
									END 
								) AS LeftMoney '				
	SET @SQL = @SQL + ' 
				FROM 	BillIndex '

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = BillIndex.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = BillIndex.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = BillIndex.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '				

		SET @SQL = @SQL + '
				WHERE	ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)

			IF @DTypeID = ''
				SET @SQL = @SQL + ' AND DTypeId = '+char(39)+@DTypeId+char(39)
			ELSE
				SET @SQL = @SQL + ' AND DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

			SET @SQL = @SQL + '
						AND BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)
				
				IF ISDATE(@TimePoint)=1	--历史状况
					SET @SQL = @SQL + ' 
						AND BillDate<='+char(39)+@TimePoint+char(39)
				
				SET @SQL = @SQL + '
						AND IfCheck = ''t''
						AND RedWord = 0
						AND IfYearBill = 0 '
						
		IF @Bhys = '0'
			BEGIN
				IF @Type = '1'
					SET @SQL = @SQL + ' AND BillType NOT IN (189) '
				ELSE
					SET @SQL = @SQL + ' AND BillType NOT IN (190) '
			END
			
		SET @SQL = @SQL + '								
				GROUP BY ETypeId
				UNION ALL
				SELECT	B.ETypeId, '
					IF @Type = 1	--分支机构应收查询 
						SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN B.BillType IN (116,129)   THEN ISNULL(A.Total,0)
												WHEN B.BillType IN (115,128)   THEN -1*ISNULL(A.Total,0)
												ELSE 0
											END 
										) AS LeftMoney  '
					ELSE
						SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN B.BillType IN (116,129)   THEN -1*ISNULL(A.Total,0)
												WHEN B.BillType IN (115,128)   THEN ISNULL(A.Total,0)
												ELSE 0
											END 
										) AS LeftMoney  '
	SET @SQL = @SQL + '
				FROM 	BillIndex B
						INNER JOIN AdDebtBill A ON B.BillNumberId = A.BillNumberId'

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = A.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '				

		SET @SQL = @SQL + '
				WHERE	B.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
						AND B.IfCheck = ''t''
						AND B.RedWord = 0 
						AND B.IfYearBill = 0 '

			IF @DTypeID = ''
				SET @SQL = @SQL + ' AND B.DTypeId = '+char(39)+@DTypeId+char(39)
			ELSE
				SET @SQL = @SQL + ' AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

			SET @SQL = @SQL + '
						AND A.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)

				IF ISDATE(@TimePoint)=1	--历史状况
					SET @SQL = @SQL + ' 
						AND B.BillDate<='+char(39)+@TimePoint+char(39)

				SET @SQL = @SQL + ' 
				GROUP BY B.ETypeId
				UNION ALL
				SELECT	B.ETypeId, '
					IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
						IF @Type = 1	--分支机构应收查询
							SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
												ELSE 0
											END
										) AS LeftMoney '
						ELSE
							SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN L.ATypeId = ''0000200001''	THEN ISNULL(L.Total,0)
												ELSE 0
											END
										) AS LeftMoney '
					ELSE
						IF @Type = 1	--分支机构应收查询
							SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
												WHEN L.ATypeId = ''0000200001'' THEN -1*ISNULL(L.Total,0)
												ELSE 0
											END
										) AS LeftMoney '
						ELSE
							SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN L.ATypeId = ''0000100005''	THEN -1*ISNULL(L.Total,0)
												WHEN L.ATypeId = ''0000200001'' THEN ISNULL(L.Total,0)
												ELSE 0
											END
										) AS LeftMoney '									
		SET @SQL = @SQL + '		
				FROM	BillIndex B
						INNER JOIN ListTable L ON B.BillNumberId = L.BillNumberId'

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = L.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '				

		SET @SQL = @SQL + '
				WHERE	B.BillType = 159
						AND L.ATypeId IN (''0000100005'',''0000200001'')					
						AND B.IfCheck = ''t''
						AND B.RedWord = 0
						AND B.IfYearBill = 0
						AND B.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)

	IF @DTypeId = ''
		SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
	ELSE
		SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

				IF ISDATE(@TimePoint)=1	--历史状况
					SET @SQL = @SQL + ' 
						AND B.BillDate<='+char(39)+@TimePoint+char(39)

				SET @SQL = @SQL + ' 
				GROUP BY B.ETypeId'
EXEC(@SQL)


--正式运算数据
SET @SQL = '
		SELECT	E.TypeId,
				E.SonNum,
				E.UserCode,
				E.FullName,				
				ISNULL(SUM(D.LeftMoney),0) AS LeftMoney
		FROM	F_GetManETypeAll('+char(39)+@OperatorID+char(39)+') E
		LEFT JOIN (
					SELECT	ETypeId,
							SUM(LeftMoney) AS LeftMoney
					FROM	#Result
					GROUP BY ETypeId
				)D ON D.ETypeId = E.TypeId
		WHERE	E.Deleted = 0 
				AND E.SonNum = 0 
				AND E.TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
				AND E.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
				AND E.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)


		IF @ShowZero = 0
			SET @SQL = @SQL + ' AND ISNULL(LeftMoney,0) <> 0 '

		SET @SQL = @SQL + ' 
		GROUP BY
				E.TypeId,
				E.SonNum,
				E.UserCode,
				E.FullName
		ORDER BY E.UserCode'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Result,#GetManETypeId,#GetManKTypeId,#GetManBTypeId,#GetManSTypeId





































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentEmployeeList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentEmployeeList]
GO

/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构往来职员的应收、应付树型查询
*/
CREATE PROCEDURE Web_QueryDepartmentEmployeeList
(
	@OperatorId		varchar(100),	--操作员的ID
	@DTypeId		varchar(100),	--部门的ID
	@ETypeId		varchar(100),	--职员ID
	@STypeId		varchar(8000),	--分支机构的ID
	@Type			int,			--查询类型  1.分支机构应收查询   2.分支机构应付查询
	@TimePoint		varchar(12),	--历史状况查询
	@Bhys			varchar(max)	--包含预收（付） 1.包含 0.不包含
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @DTypeId = '' OR @DTypeId = '00000'
	SET @DTypeId = '%'
ELSE
	IF @DTypeId = '99999'
		SET @DTypeId = ''

DECLARE @SonNum 	int,			--当前SonNum值
		@SQL		varchar(8000)	--SQL字符串


--必须处理往来管理的权限
DECLARE @BTypeAll 	int,
		@BTypeId	varchar(100)

SELECT @BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'

IF @BTypeAll = 0
	BEGIN
		IF @Type = 1
			SET @BTypeId = '00001'
		ELSE
			SET @BTypeId = '00002'
	END
ELSE
	SET @BTypeId = '%'


SELECT @SonNum = SonNum FROM Employee WHERE TypeId = @ETypeId AND Deleted = 0

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID) WHERE TypeId LIKE @ETypeId + '%'

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorID)
INSERT INTO #GetManKTypeId(TypeId)VALUES('')
INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetManDetailBType(@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

CREATE TABLE #Result
(
	ETypeId		VARCHAR(100),
	LeftMoney	 NUMERIC(24, 10) 
)

--提取数据
SET @SQL = 'INSERT INTO #Result
			SELECT	ETypeId, '					
				IF @Type = 1	--分支机构应收查询
					SET @SQL = @SQL + '
							SUM(
									CASE
										WHEN BillType IN (11,141,155,6,150,151,93,85,160,167,168,172,178,186,189)			THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
										WHEN BillType IN (45,148,149,34,145,36,84,94,161,170,190)      		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
										WHEN BillType = 4  											THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
										WHEN BillType = 66											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
										WHEN BillType = 157											THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0)
										ELSE 0
									END 
								) AS LeftMoney '		
				ELSE			--分支机构应付查询
					SET @SQL = @SQL + '
							SUM(
									CASE
										WHEN BillType IN (11,141,155,6,150,151,93,85,160,167,168,172,178,189)			THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
										WHEN BillType IN (45,148,149,34,145,36,84,94,161,170,186,190)      		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
										WHEN BillType = 4  											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
										WHEN BillType = 66											THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
										WHEN BillType = 157											THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)+ISNULL(preferencemoney,0))
										ELSE 0
									END 
								) AS LeftMoney '				
	SET @SQL = @SQL + ' 
				FROM 	BillIndex '

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = BillIndex.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = BillIndex.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = BillIndex.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '				

		SET @SQL = @SQL + '
				WHERE	ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)

			IF @DTypeID = ''
				SET @SQL = @SQL + ' AND DTypeId = '+char(39)+@DTypeId+char(39)
			ELSE
				SET @SQL = @SQL + ' AND DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

			SET @SQL = @SQL + '
						AND BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)
				
				IF ISDATE(@TimePoint)=1	--历史状况
					SET @SQL = @SQL + ' 
						AND BillDate<='+char(39)+@TimePoint+char(39)
				
				SET @SQL = @SQL + '
						AND IfCheck = ''t''
						AND RedWord = 0
						AND IfYearBill = 0 '
						
		IF @Bhys = '0'
			BEGIN
				IF @Type = '1'
					SET @SQL = @SQL + ' AND BillType NOT IN (189) '
				ELSE
					SET @SQL = @SQL + ' AND BillType NOT IN (190) '
			END
			
		SET @SQL = @SQL + '							
				GROUP BY ETypeId
				UNION ALL
				SELECT	B.ETypeId, '
					IF @Type = 1	--分支机构应收查询 
						SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN B.BillType IN (116,129)   THEN ISNULL(A.Total,0)
												WHEN B.BillType IN (115,128)   THEN -1*ISNULL(A.Total,0)
												ELSE 0
											END 
										) AS LeftMoney  '
					ELSE
						SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN B.BillType IN (116,129)   THEN -1*ISNULL(A.Total,0)
												WHEN B.BillType IN (115,128)   THEN ISNULL(A.Total,0)
												ELSE 0
											END 
										) AS LeftMoney  '
	SET @SQL = @SQL + '
				FROM 	BillIndex B
						INNER JOIN AdDebtBill A ON B.BillNumberId = A.BillNumberId'

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = A.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '							

		SET @SQL = @SQL + '
				WHERE	B.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
						AND B.IfCheck = ''t''
						AND B.RedWord = 0 
						AND B.IfYearBill = 0 '

			IF @DTypeID = ''
				SET @SQL = @SQL + ' AND B.DTypeId = '+char(39)+@DTypeId+char(39)
			ELSE
				SET @SQL = @SQL + ' AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

			SET @SQL = @SQL + '
						AND A.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)

				IF ISDATE(@TimePoint)=1	--历史状况
					SET @SQL = @SQL + ' 
						AND B.BillDate<='+char(39)+@TimePoint+char(39)

				SET @SQL = @SQL + ' 
				GROUP BY B.ETypeId
				UNION ALL
				SELECT	B.ETypeId, '
					IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
						IF @Type = 1	--分支机构应收查询
							SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
												ELSE 0
											END
										) AS LeftMoney '
						ELSE
							SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN L.ATypeId = ''0000200001''	THEN ISNULL(L.Total,0)
												ELSE 0
											END
										) AS LeftMoney '
					ELSE
						IF @Type = 1	--分支机构应收查询
							SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
												WHEN L.ATypeId = ''0000200001'' THEN -1*ISNULL(L.Total,0)
												ELSE 0
											END
										) AS LeftMoney '
						ELSE
							SET @SQL = @SQL + '
									SUM(
											CASE
												WHEN L.ATypeId = ''0000100005''	THEN -1*ISNULL(L.Total,0)
												WHEN L.ATypeId = ''0000200001'' THEN ISNULL(L.Total,0)
												ELSE 0
											END
										) AS LeftMoney '									
		SET @SQL = @SQL + '		
				FROM	BillIndex B
						INNER JOIN ListTable L ON B.BillNumberId = L.BillNumberId'

		IF NOT @METypeId = '00001'
			SET @SQL = @SQL + ' INNER JOIN #GetManETypeId E ON E.TypeId = B.ETypeId'

		IF NOT @MKTypeId = '00000'
			SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId'

		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
			SET @SQL = @SQL + ' INNER JOIN #GetManBTypeId MB ON MB.TypeId = L.BTypeId '
			
		IF NOT (@STypeId = '' AND @MStypeid = '00000')
			SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '							

		SET @SQL = @SQL + '
				WHERE	B.BillType = 159
						AND L.ATypeId IN (''0000100005'',''0000200001'')					
						AND B.IfCheck = ''t''
						AND B.RedWord = 0
						AND B.IfYearBill = 0
						AND B.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)

	IF @DTypeId = ''
		SET @SQL = @SQL + '	AND B.DTypeId = '+char(39)+@DTypeId+char(39)
	ELSE
		SET @SQL = @SQL + '	AND B.DTypeId LIKE '+char(39)+@DTypeId+'%'+char(39)

				IF ISDATE(@TimePoint)=1	--历史状况
					SET @SQL = @SQL + ' 
						AND B.BillDate<='+char(39)+@TimePoint+char(39)

				SET @SQL = @SQL + ' 
				GROUP BY B.ETypeId'
EXEC(@SQL)

--正式运算数据
SET @SQL = '
		SELECT	E.TypeId,
				E.SonNum,
				E.UserCode,
				E.FullName,				
				ISNULL(SUM(D.LeftMoney),0) AS LeftMoney
		FROM	F_GetManETypeAll('+char(39)+@OperatorID+char(39)+') E
		LEFT JOIN (
					SELECT	ETypeId,
							SUM(LeftMoney) AS LeftMoney
					FROM	#Result
					GROUP BY ETypeId					
				)D ON LEFT(D.ETypeId,LEN(E.TypeId)) = E.TypeId
		WHERE	E.Deleted = 0 '

IF @SonNum = 0 	
	SET @SQL = @SQL + ' AND E.TypeId = '+char(39)+@ETypeId+char(39)	
ELSE
	SET @SQL = @SQL + ' AND E.ParId = '+char(39)+@ETypeId+char(39)

SET @SQL = @SQL + ' 
		GROUP BY
				E.TypeId,
				E.SonNum,
				E.UserCode,
				E.FullName
		ORDER BY E.UserCode '

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Result,#GetManETypeId,#GetManKTypeId,#GetManBTypeId,#GetManSTypeId








































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentLine]
GO




















/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构的应收、应付线性查询
*/
CREATE PROCEDURE Web_QueryDepartmentLine
(
	@OperatorId		varchar(100),		--操作员的ID
	@DTypeId		varchar(100),		--部门的ID
	@STypeId		varchar(8000),		--分支机构的ID
	@Type			int,				--查询类型  1.分支机构应收查询   2.分支机构应付查询
	@UserCode		varchar(256)='',	--分支机构编号
	@FullName		varchar(256)='',	--分支机构名称
	@ShowZero		int,				--是否显示为零的记录  0.不显示  1.显示
	@Bhys			varchar(max)	--包含预收（付） 1.包含 0.不包含
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @DTypeId = '' OR @DTypeId = '00000'
	SET @DTypeId = '%'

DECLARE @SQL		varchar(8000),
		@BTypeId	varchar(50)

IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)
	BEGIN
		IF @Type = 1
			SET @BTypeId = '00001'
		ELSE
			SET @BTypeId = '00002'
	END
ELSE
	SET @BTypeId = '%'

CREATE TABLE #DType
(
	TypeId		VARCHAR(100),
	SonNum		INT,
	UserCode	VARCHAR(300),
	FullName	VARCHAR(300)
)
INSERT INTO #DType SELECT TypeId,SonNum,UserCode,FullName FROM F_GetManDTypeAll(@OperatorId) WHERE Deleted = 0 AND TypeId LIKE @DTypeId + '%' AND SonNum = 0
--INSERT INTO #DType(TypeId,SonNum,UserCode,FullName)VALUES('99999',0,'其他部门','其他部门')

--仓库
--CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
--INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorID)
--INSERT INTO #GetManKTypeId(TypeId)VALUES('')
--INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)


CREATE TABLE #Result
(
	DTypeId		VARCHAR(100),
	LeftMoney	 NUMERIC(24, 10) 
)

SET @SQL = 'INSERT INTO #Result
			SELECT	DTypeId, '
			IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
				BEGIN
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,85,93,141,155,157,160,167,168,172,178,186,189)	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (36,45,84,148,149)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (4)						THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN(66) 						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '
					ELSE			--分支机构应付查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (34,84,145,36,94,161,170,186,190)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00001%''	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)	
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00002%''	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)<0	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)	
											WHEN BillType IN (6,150,151,85,93)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (66)						THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											WHEN BillType IN (4)						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '
	
							
				END
			ELSE	
				BEGIN
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172,178,186,189)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (45,148,149,34,145,36,84,94,161,170)      		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType = 4  											THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (66)										THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '		
					ELSE			--分支机构应付查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172,178,186)		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (45,148,149,34,145,36,84,94,161,170,190)      		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType = 4  											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											WHEN BillType IN(66)										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											ELSE 0
										END 
									) AS LeftMoney '				
				END						
SET @SQL = @SQL + ' 
			FROM 	BillIndex '

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = BillIndex.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') B ON B.TypeId = BillIndex.BTypeId '

--IF @MKTypeId = '-99999'
--	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON BillIndex.KTypeId = K.TypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '		

SET @SQL = @SQL + '
			WHERE	BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
					AND IfCheck = ''t''
					AND RedWord = 0				
					AND IfYearBill = 0 '
					
IF @Bhys = '0'
	BEGIN
		IF @Type = '1'
			SET @SQL = @SQL + ' AND BillType NOT IN (189) '
		ELSE
			SET @SQL = @SQL + ' AND BillType NOT IN (190) '
	END

SET @SQL = @SQL + '						
			GROUP BY DTypeId 
			UNION ALL
			SELECT	B.DTypeId, '
				IF @Type = 1	--分支机构应收查询 
					SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN B.BillType IN (116,129)   THEN ISNULL(A.Total,0)
											WHEN B.BillType IN (115,128)   THEN -1*ISNULL(A.Total,0)
											ELSE 0
										END 
									) AS LeftMoney  '
				ELSE			--分支机构应付查询
					SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN B.BillType IN (116,129)   THEN -1*ISNULL(A.Total,0)
											WHEN B.BillType IN (115,128)   THEN ISNULL(A.Total,0)
											ELSE 0
										END 
									) AS LeftMoney  '
SET @SQL = @SQL + '
			FROM 	BillIndex B
					INNER JOIN AdDebtBill A ON B.BillNumberId = B.BillNumberId'

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = B.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') MB ON MB.TypeId = A.BTypeId '

--IF @MKTypeId = '-99999'
--	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON B.KTypeId = K.TypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		

SET @SQL = @SQL + '
			WHERE	B.BillNumberId = A.BillNumberId
					AND A.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
					AND B.IfCheck = ''t''
					AND B.RedWord = 0
					AND B.IfYearBill = 0
			GROUP BY B.DTypeId
			UNION ALL
			SELECT	B.DTypeId, '
				IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
					ELSE
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000200001''	THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
				ELSE
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
											WHEN L.ATypeId = ''0000200001'' THEN -1*ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
					ELSE
						SET @SQL = @SQL + '
								SUM(

										CASE
											WHEN L.ATypeId = ''0000100005''	THEN -1*ISNULL(L.Total,0)
											WHEN L.ATypeId = ''0000200001'' THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '						
							
	SET @SQL = @SQL + '		
			FROM	BillIndex B
					INNER JOIN ListTable L ON (B.BillNumberId = L.BillNumberId AND L.ATypeId IN (''0000100005'',''0000200001'')) '

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = B.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') MB ON MB.TypeId = L.BTypeId '

--IF @MKTypeId = '-99999'
--	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON B.KTypeId = K.TypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		

SET @SQL = @SQL + '
			WHERE	B.BillType = 159
					AND B.IfYearBill = 0
			GROUP BY B.DTypeId	'
EXEC(@SQL)

--运算数据
SET @SQL = '
		SELECT	D.TypeId,
				D.UserCode,
				D.FullName,
				ISNULL(SUM(B.LeftMoney),0) AS LeftMoney
		FROM	#DType D
		LEFT JOIN (
					SELECT	CASE 
								WHEN DTypeId='''' THEN ''99999''
								ELSE DTypeId
							END AS DTypeId,
							SUM(LeftMoney) AS LeftMoney
					FROM	#Result
					GROUP BY DTypeId						
				)B ON B.DTypeId = D.TypeId
		WHERE	D.TypeId LIKE '+char(39)+@DTypeId+'%'+char(39)+'
				AND D.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
				AND D.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)
		IF @ShowZero = 0
				SET @SQL = @SQL + ' AND ISNULL(LeftMoney,0) <> 0 '

		SET @SQL = @SQL + ' 
		GROUP BY
				D.TypeId,
				D.UserCode,
				D.FullName
		ORDER BY D.UserCode '

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #DType,#Result,#GetManSTypeId--,#GetManKTypeId




































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDepartmentList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDepartmentList]
GO






















/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构的应收、应付树型查询
*/
CREATE  PROCEDURE Web_QueryDepartmentList
(
	@OperatorId		varchar(100),	--操作员的ID
	@DTypeId		varchar(100),	--部门的ID
	@STypeId		varchar(8000),	--分支机构的ID
	@Type			int,			--查询类型  1.分支机构应收查询   2.分支机构应付查询
	@Bhys			varchar(max)	--包含预收（付） 1.包含 0.不包含
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

IF @DTypeId = ''
	SET @DTypeId = '00000'

DECLARE @SonNum 	int,
		@SQL		varchar(8000),
		@BTypeId	varchar(50)

IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)
	BEGIN
		IF @Type = 1
			SET @BTypeId = '00001'
		ELSE
			SET @BTypeId = '00002'
	END
ELSE
	SET @BTypeId = '%'

SELECT @SonNum = SonNum FROM F_GetManDTypeAll(@OperatorId) WHERE TypeId = @DTypeId AND Deleted = 0

CREATE TABLE #DType
(
	TypeId		VARCHAR(100),
	SonNum		INT,
	UserCode	VARCHAR(300),
	FullName	VARCHAR(300)
)

IF @SonNum = 0
	INSERT INTO #DType SELECT TypeId,SonNum,UserCode,FullName FROM F_GetManDTypeAll(@OperatorId) WHERE Deleted = 0 AND TypeId = @DTypeId
ELSE
	INSERT INTO #DType SELECT TypeId,SonNum,UserCode,FullName FROM F_GetManDTypeAll(@OperatorId) WHERE Deleted = 0 AND ParId = @DTypeId

--仓库
--CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
--INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetManDetailKType(@OperatorID)
--INSERT INTO #GetManKTypeId(TypeId)VALUES('')
--INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

CREATE TABLE #Result
(
	DTypeId		VARCHAR(100),
	LeftMoney	 NUMERIC(24, 10) 
)

SET @SQL = 'INSERT INTO #Result
			SELECT	DTypeId, '
			IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
				BEGIN
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,85,93,141,155,157,160,167,168,172,178,186,189)	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (36,45,84,148,149)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (4)						THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN(66) 						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '
					ELSE			--分支机构应付查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (34,84,145,36,94,161,170,186,190)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00001%''	THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)	
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)>=0 AND BTypeId LIKE ''00002%''	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)
											WHEN BillType = 157 AND ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)<0	THEN ISNULL(TotalInMoney,0)-ISNULL(TotalMoney,0)	
											WHEN BillType IN (6,150,151,85,93)   		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (66)						THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											WHEN BillType IN (4)						THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '
	
							
				END
			ELSE	
				BEGIN
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172,178,186,189)		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (45,148,149,34,145,36,84,94,161,170)      		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType = 4  											THEN -1*ISNULL(TotalMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType IN (66)										THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											ELSE 0
										END 
									) AS LeftMoney '		
					ELSE			--分支机构应付查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN BillType IN (11,141,155,6,150,151,93,85,157,160,167,168,172,178,186)		THEN -1*(ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0))
											WHEN BillType IN (45,148,149,34,145,36,84,94,161,170,190)      		THEN ISNULL(TotalMoney,0)-ISNULL(TotalInMoney,0)-ISNULL(preferencemoney,0)
											WHEN BillType = 4  											THEN ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0)
											WHEN BillType IN(66)										THEN -1*(ISNULL(TotalMoney,0)+ISNULL(preferencemoney,0))
											ELSE 0
										END 
									) AS LeftMoney '				
				END						
SET @SQL = @SQL + ' 
			FROM 	BillIndex '

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = BillIndex.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') B ON B.TypeId = BillIndex.BTypeId '

--IF @MKTypeId = '-99999'
--	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON BillIndex.KTypeId = K.TypeId'

IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '	

SET @SQL = @SQL + '
			WHERE	BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
					AND IfCheck = ''t''
					AND RedWord = 0
					AND IfYearBill = 0 '
				
IF @Bhys = '0'
	BEGIN
		IF @Type = '1'
			SET @SQL = @SQL + ' AND BillType NOT IN (189) '
		ELSE
			SET @SQL = @SQL + ' AND BillType NOT IN (190) '
	END
				
					
SET @SQL = @SQL + '					
			GROUP BY DTypeId 
			UNION ALL
			SELECT	B.DTypeId, '
				IF @Type = 1	--分支机构应收查询 
					SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN B.BillType IN (116,129)   THEN ISNULL(A.Total,0)
											WHEN B.BillType IN (115,128)   THEN -1*ISNULL(A.Total,0)
											ELSE 0
										END 
									) AS LeftMoney  '
				ELSE			--分支机构应付查询
					SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN B.BillType IN (116,129)   THEN -1*ISNULL(A.Total,0)
											WHEN B.BillType IN (115,128)   THEN ISNULL(A.Total,0)
											ELSE 0
										END 
									) AS LeftMoney  '
SET @SQL = @SQL + '
			FROM 	BillIndex B
					INNER JOIN AdDebtBill A ON B.BillNumberId = B.BillNumberId'

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = B.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') MB ON MB.TypeId = A.BTypeId '

--IF @MKTypeId = '-99999'
--	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON B.KTypeId = K.TypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		

SET @SQL = @SQL + '
			WHERE	B.BillNumberId = A.BillNumberId
					AND A.BTypeId LIKE '+char(39)+@BTypeId+'%'+char(39)+'
					AND B.IfCheck = ''t''
					AND B.RedWord = 0
					AND B.IfYearBill = 0
			GROUP BY B.DTypeId
			UNION ALL
			SELECT	B.DTypeId, '
				IF NOT EXISTS(SELECT TOP 1 *  FROM UserConfig WHERE ConfigName = 'BTypeAll' AND Value = 1)	--客户和供货商不统一
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
					ELSE
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000200001''	THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
				ELSE
					IF @Type = 1	--分支机构应收查询
						SET @SQL = @SQL + '
								SUM(
										CASE
											WHEN L.ATypeId = ''0000100005''	THEN ISNULL(L.Total,0)
											WHEN L.ATypeId = ''0000200001'' THEN -1*ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '
					ELSE
						SET @SQL = @SQL + '
								SUM(

										CASE
											WHEN L.ATypeId = ''0000100005''	THEN -1*ISNULL(L.Total,0)
											WHEN L.ATypeId = ''0000200001'' THEN ISNULL(L.Total,0)
											ELSE 0
										END
									) AS LeftMoney '						
							
	SET @SQL = @SQL + '		
			FROM	BillIndex B
					INNER JOIN ListTable L ON (B.BillNumberId = L.BillNumberId AND L.ATypeId IN (''0000100005'',''0000200001'')) '

IF @METypeId = '-99999'
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailEType('+char(39)+@OperatorID+char(39)+') E ON E.TypeId = B.ETypeId '

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + ' INNER JOIN F_GetManDetailBType('+char(39)+@OperatorID+char(39)+') MB ON MB.TypeId = L.BTypeId '

--IF @MKTypeId = '-99999'
--	SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON B.KTypeId = K.TypeId'
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON B.STypeId = S.TypeId '		

SET @SQL = @SQL + '
			WHERE	B.BillType = 159
					AND B.IfYearBill = 0
			GROUP BY B.DTypeId	'

--PRINT(@SQL)
EXEC(@SQL)

--运算数据
SET @SQL = '
		SELECT	D.TypeId,
				D.SonNum,
				D.UserCode,
				D.FullName,
				SUM(ISNULL(B.LeftMoney,0)) AS LeftMoney		
		FROM	#DType D
		LEFT JOIN (
					SELECT	CASE 
								WHEN DTypeId='''' THEN ''99999''
								ELSE DTypeId
							END AS DTypeId,
							SUM(LeftMoney) AS LeftMoney
					FROM	#Result
					GROUP BY DTypeId									
				)B ON LEFT(B.DTypeId,LEN(D.TypeId)) = D.TypeId
		WHERE	D.TypeId <> ''00000''
		GROUP BY
				D.TypeId,
				D.SonNum,
				D.UserCode,
				D.FullName
		ORDER BY D.UserCode'

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Result,#DType,#GetManSTypeId--,#GetManKTypeId










































GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryDepartmentPaymentsDistribute]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[Web_QueryDepartmentPaymentsDistribute]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/*
	作者：GLJ
	日期：2019-01-29
	描述：部门回款分布
*/
CREATE    PROCEDURE Web_QueryDepartmentPaymentsDistribute
(
	@OperatorID		VARCHAR(100),
	@StartDate 		VARCHAR(30),
	@EndDate 			VARCHAR(30),
	@ETypeId			VARCHAR(MAX),
	@BTypeId 			VARCHAR(MAX),
	@STypeId			VARCHAR(MAX),
	@DTypeId			VARCHAR(50),
	@szOrderBy		VARCHAR(50)='',
	@BillTypeId		VARCHAR(1000),		--单据类型的ID
	@CID				INT=0   
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--结算单位
CREATE TABLE #BType(TypeId VARCHAR(50))
INSERT INTO #BType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S
--IF(@BTypeId='00000' OR @BTypeId='')
--	INSERT INTO #BType(TypeId) VALUES('')

--职员
CREATE TABLE #EType(TypeId VARCHAR(50))
INSERT INTO #EType(TypeId) SELECT TypeID FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID)

--分支机构
CREATE TABLE #SType(TypeId	VARCHAR(50))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--部门
CREATE TABLE #DType(TypeId	VARCHAR(50))
INSERT INTO #DType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)		

--单据类型
CREATE TABLE #BillType(BillType INT)
INSERT INTO #BillType(BillType) SELECT a FROM f_split(@BillTypeId,',')	

DECLARE @SQL 		varchar(8000),
		@szOrderSql varchar(1000)

SET @SQL = ''
SET @szOrderSql = ''

SET @SQL = '
SELECT	B.TypeId,
		B.UserCode,
		B.FullName,
		SUM(ISNULL(HK,0)) AS Sum_Total,
		SUM(ISNULL(NHK,0)) AS NSum_Total
FROM	F_GetManDTypeAll('+char(39)+@OperatorID+char(39)+') B
INNER JOIN (
	SELECT 
			L.Dtypeid,
			SUM(
				CASE 
					WHEN (AC.UserCode=''1001'' OR (AC.TypeName=''B'' AND AC.UserCode<>''1001'' AND AC.UserCode<>''1151'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''2181'' ))  THEN ISNULL(Total,0)
					WHEN (AC.UserCode = ''2131'' AND l.billtype=159) THEN ISNULL(Total,0)
					ELSE 0	
					END
			) AS HK,
			SUM(
				CASE 
					WHEN (AC.UserCode=''1001'' OR (AC.TypeName=''B'' AND AC.UserCode<>''1001'' AND AC.UserCode<>''1151'' AND AC.UserCode<>''2131'' AND AC.UserCode<>''2181'' ))  THEN ISNULL(NTotal,0)
					WHEN (AC.UserCode = ''2131'' AND  l.billtype=159) THEN ISNULL(NTotal,0)
					ELSE 0	
					END
			) AS NHK		
	FROM Listtable l
	INNER JOIN #BillType T ON T.BillType=L.BillType
	INNER JOIN #BType B ON B.TypeId = L.BTypeId
	INNER JOIN #EType E ON E.TypeId = L.ETypeId
	INNER JOIN #SType S ON S.TypeId = L.STypeId
	INNER JOIN #DType D ON D.TypeId = L.DTypeId
	INNER JOIN AC_Items AC ON AC.nid=L.AtypeID
	WHERE	
			 L.BillDate BETWEEN '''+@StartDate +''' AND '''+@EndDate+'''
			AND L.Audited = 1 '
if @cid<>0
	SET @SQl+=' AND L.CID= ' +char(39)+@cid+char(39)

SET @SQL+='
	GROUP BY
			l.DTypeId
)A ON B.TypeId = A.DTypeId 
WHERE ISNULL(HK,0)<>0
GROUP BY 
		B.TypeId,
		B.UserCode,
		B.FullName 
ORDER BY
	B.UserCode'

EXEC(@SQL)

DROP TABLE #BType,#EType,#SType,#DType,#BillType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT TOP 1 1 FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryDetailsVirtualStockList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_QueryDetailsVirtualStockList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	查询实物库存出入库汇总表 表格配置
-- 时间：	2017-06-29
-- 作者：	glj
-- ========================================================================
CREATE PROCEDURE Web_QueryDetailsVirtualStockList
(
	@PTypeID	VARCHAR(50),--商品ID
	@OperatorId	VARCHAR(50)	--当前操作员ID
)
--@encode$--
AS
SET NOCOUNT ON

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDisassemBleDeatil]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDisassemBleDeatil]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：彭勇
	日期：2014-11-25
	描述：生产拆装单明细表
*/
CREATE PROCEDURE Web_QueryDisassemBleDeatil
(
	@OperatorId		VARCHAR(50),	    -- 当前操作员ID
	@BeginDate	    varchar(30),	    --查询起始时间
	@EndDate		varchar(30),    	-- 查询结束时间 
	@STypeId        varchar(MAX),		--分支机构
	@ETypeID		varchar(MAX),		-- 经手人	
	@KtypeId 	    varchar(MAX)='',	--出\入库仓库
	@BillCode       varchar(200)='',	--单据编号
	@Comment        varchar(200)='',	--摘要
	@PTypeId		varchar(200),    	-- 商品
	@DeatilType		INT	
)
--@encode$--
AS
SET NOCOUNT ON
--商品
CREATE TABLE #PTYPE(Typeid varchar(100))
INSERT INTO #PTYPE(Typeid)	SELECT TypeId  FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorId)
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId)	
--经手人
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@ETypeID,3,@OperatorId)
--出\入库仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetAllManagerBaseTypeId(@KtypeId,4,@OperatorId)



CREATE TABLE #Deatil(
    billnumberid INT,    
	billdate DATETIME,		--单据日期
	billcode VARCHAR(200),	--单据编号
	stypeid	 VARCHAR(200),	--分支机构
	etypeid	 VARCHAR(200),	--经手人
	ptypeid	 VARCHAR(200),	--商品id
	dtypeid  VARCHAR(200),	--部门id
	ktypeid	 VARCHAR(200),	--仓库id
	unitfullname VARCHAR(200),--出库/入库单位
	unitqty	  NUMERIC(24, 10) ,   --出库/入库数量
	unitcostprice 	 NUMERIC(24, 10) ,	--成本单价
	basefullname VARCHAR(200), --基本单位名称
	baseqty		  NUMERIC(24, 10) ,	--基本单位数量
	unitrelation VARCHAR(200),	--换算关系
	basecostprice  NUMERIC(24, 10) ,	--基本成本单价	 
	costtotal	   NUMERIC(24, 10) ,	--成本金额
	cottotaldifference   NUMERIC(24, 10) ,	--整单价差
	checkTime     DATETIME,		--制单时间
	poster		  VARCHAR(200), --过账人
	posttime	  DATETIME,		--过账时间
	comment		  VARCHAR(200), --摘要	
	explain		  VARCHAR(200),	--说明
	flag		  VARCHAR(1),
	billtype		INT	,
	CustomdetailID				INT	
)

INSERT INTO #Deatil
        ( billnumberid ,
          billdate ,
          billcode ,
          stypeid ,
          etypeid ,
          ptypeid ,
          dtypeid ,
          ktypeid ,
          unitfullname ,
          unitqty ,
          unitcostprice ,
          basefullname ,
          baseqty ,
          unitrelation ,
          basecostprice ,
          costtotal ,
          cottotaldifference ,
          checkTime ,
          poster ,
          posttime ,
          comment ,
          explain,
          flag,
          billtype,CustomdetailID
        )
SELECT  a.BillNumberId,
        a.BillDate,
		a.BillCode
		,a.STypeID,
		a.etypeid,
		b.ptypeid,
		a.DTypeId,
		b.kTypeID,
		c.FullName AS unitfullname,
		ABS(CONVERT( NUMERIC(24, 10) ,b.Qty/d.Rate)) unitqty,
		CONVERT( NUMERIC(24, 10) ,CostPrice*d.Rate) AS unitcostprice,
		(SELECT FullName FROM PType_Units WHERE UnitsId=p.baseUnitId)basefullname,
		ABS(b.Qty) AS baseqty,
		'1'+c.FullName+'='+CONVERT(NVARCHAR(100),CAST(d.Rate AS REAL)) +(SELECT FullName FROM PType_Units WHERE UnitsId=p.baseUnitId) AS unitrelation,
		b.CostPrice AS basecostprice,
		ABS(b.CostTotal),
	    0,
		checkTime,
		a.Poster,
		a.posttime,
		a.Comment,
		explain,
		CASE WHEN b.qty<0 THEN 'c' ELSE 'r' END,
		b.BillType,b.ID
FROM dbo.BillIndex a  INNER JOIN dbo.InOutstocktable b  ON a.BillNumberId=b.BillNumberId 
	INNER JOIN PType_Units c ON c.UnitsId=b.MUNITID
	INNER JOIN dbo.PType_Units_Ext d  ON b.PtypeId=d.PtypeID AND b.MUNITID=d.UnitsId
	INNER JOIN dbo.ptype p  ON p.typeId=b.PtypeId 
	INNER JOIN #PTYPE p1 ON p1.Typeid=b.PtypeId
	INNER JOIN #GetManETypeId e ON e.TypeId= a.etypeid
	INNER JOIN #GetManSTypeId s  ON s.TypeId =b.STypeID
	INNER JOIN #GetManKTypeId k  ON k.TypeId=b.KtypeId
WHERE a.BillType=16 AND a.RedWord=0
     AND a.BillDate BETWEEN @BeginDate  AND  @EndDate
     AND a.BillCode LIKE '%'+@BillCode+'%'
     AND a.Comment LIKE '%'+@comment+'%'
--算价差
UPDATE #Deatil  SET cottotaldifference= a.costtotal 
FROM (
        SELECT 
			SUM(b.CostTotal)costtotal,a.BillNumberId
			FROM dbo.BillIndex a  INNER JOIN dbo.InOutstocktable b  ON a.BillNumberId=b.BillNumberId 
			INNER JOIN #GetManETypeId e ON e.TypeId= a.etypeid
			INNER JOIN #GetManSTypeId s  ON s.TypeId =b.STypeID
			INNER JOIN #GetManKTypeId k  ON k.TypeId=b.KtypeId
		WHERE a.BillType=16 AND a.RedWord=0
			 AND a.BillDate BETWEEN @BeginDate  AND  @EndDate
			 AND a.BillCode LIKE '%'+@BillCode+'%'
			 AND a.Comment LIKE '%'+@comment+'%'
			 GROUP BY a.BillNumberId
     ) a 
    WHERE a.billnumberid= #Deatil.billnumberid 


    SELECT  R.*
    INTO    #Result
    FROM    ( SELECT    *
              FROM      #Deatil
              WHERE     ( @DeatilType = 0
                          AND flag = 'c'
                        )
                        OR ( @DeatilType = 1
                             AND flag = 'r'
                           )
            ) R
    ORDER BY R.BillDate ASC ,
            R.billtype ,
            R.BillCode
                
				 
SELECT  a.* ,
        SysDiy1_head ,
        SysDiy2_head ,
        SysDiy3_head ,
        SysDiy4_head ,
        SysDiy5_head ,
        SysDiy6_head ,
        SysDiy7_head ,
        SysDiy8_head ,
        SysDiy9_head ,
        SysDiy10_head ,
        SysDiy11_head ,
        SysDiy12_head ,
        SysDiy13_head ,
        SysDiy14_head ,
        SysDiy15_head ,
        SysDiy16_head ,
        SysDiy1 ,
        SysDiy2 ,
        SysDiy3 ,
        SysDiy4 ,
        SysDiy5 ,
        SysDiy6 ,
        SysDiy7 ,
        SysDiy8 ,
        SysDiy9 ,
        SysDiy10 ,
        SysDiy11 ,
        SysDiy12 ,
        SysDiy13 ,
        SysDiy14 ,
        SysDiy15 ,
        SysDiy16
FROM    #Result a
        LEFT JOIN Custom_BillIndex csindex ON a.billnumberid = csindex.BillId
                                              AND a.billtype = csindex.billtype
        LEFT JOIN Custom_BillDetails csdetail ON a.billnumberid = csdetail.BillId
                                                 AND a.billtype = csdetail.billtype
                                                 AND a.CustomdetailID = csdetail.Detailid
		
DROP TABLE #Result
  
DROP TABLE #Deatil

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDistSingleStock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDistSingleStock]
GO





/*
	查仓库信息
*/
CREATE PROCEDURE Web_QueryDistSingleStock
(
	@OperatorId		varchar(100),
	@outKTypeId		varchar(8000),
	@inKTypeId		varchar(8000)	
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
if @OperatorId is null return 1

declare @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
exec @Re=GP_CheckOperatorRight23 @OperatorId,@MAtypeid output,@MBtypeid output,@MBtypeid2 output,@MEtypeid output,@MKtypeid output,@MPtypeid output,@MExpense output,@MIncome output

if @Re<>0 return @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SonNum int,
		@TypeId	varchar(100),
		@Re_re	int

IF @OperatorId = '00001'
	SET @Re_re = 1
ELSE
	EXEC @Re_re=GP_CheckLimit @OperatorId,454   --调拨查询中仓库权限有效 0.有效 1.无效


SELECT @TypeId = TypeId FROM Stock WHERE FullName = @outKTypeId

IF @Re_re = 0
	SELECT	FullName
	FROM	Stock
	WHERE	TypeId LIKE @TypeId + '%'
			AND FullName <> @inKTypeId
			AND SonNum = 0
			AND TypeId LIKE @MKTypeId + '%'
	ORDER BY UserCode
ELSE
	SELECT	FullName
	FROM	Stock
	WHERE	TypeId LIKE @TypeId + '%'
			AND FullName <> @inKTypeId
			AND SonNum = 0
	ORDER BY UserCode





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDraft]
GO
/*
	作者：谢吉康
	日期：2009-12-15
	描述：业务草稿查询
	作者：鲁大林	
	日期：2012-05-23
	描述：添加币别等显示列
	作者：杨俊	
	日期：2014-05-28
	描述：添加9.4资金调拨单查询条件
	作者：陈强
	日期：2019-09-11
	描述：添加9.91 商品的精准查询、根据pos名称查询
*/

CREATE PROCEDURE Web_QueryDraft
( 
	@OperatorID 		VARCHAR(100) = '', 	-- 操作员ID
	@startdate  		VARCHAR(25),
	@EndDate  			VARCHAR(25),
	@BtypeIDS  			VARCHAR(MAX), 		-- 客户名称
	@EtypeId  			VARCHAR(MAX),
	@KTypeId  			VARCHAR(MAX),
	@KTypeId1			VARCHAR(800),
	@PtypeId  			VARCHAR(MAX),
	@PtypeIds			VARCHAR(Max),		--商品名称(9.91新增)
	@OrderBy  			VARCHAR(MAX) ,
	@BillType  			VARCHAR(MAX)  = '',
	@BillCode 			VARCHAR(200) = '',
	@comment 			VARCHAR(2000)= '',
	@explain			VARCHAR(2000)='',
	@UserCode			VARCHAR(200)='',	-- 制单人编号
	@FullName			VARCHAR(200)='',	-- 制单人名称
	@AudState			VARCHAR(10)='',		-- 单据审核状态
	@PageNO             int,
	@sTypeId            VARCHAR(MAX)='00001',
	@Atypeid			VARCHAR(MAX)= '',
	@mintotal 			 NUMERIC(24, 10) =-999999999999,  		-- 金额起始
	@maxtotal   		 NUMERIC(24, 10) =999999999999,	  		-- 金额大于
	@DTypeId			VARCHAR(MAX)='',	--部门信息
	@Yh					VARCHAR(10) = '9',	--优惠金额
	@hy					VARCHAR(10) = '9',	--会员情况
	@Price				VARCHAR(10) = '9',  --商品单价
	@PriceValue			 NUMERIC(24, 10)  = 0,	--单价值
	@Discount			VARCHAR(10) = '9',  --商品折扣
	@DiscountValue		 NUMERIC(24, 10)  = 0,	--折扣价
	@Tax				VARCHAR(10) = '9',  --商品税率
	@TaxValue			 NUMERIC(24, 10)  = 0,	--税率值
	@chrFlag			char(1)		  ='1',	-- 功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@dealbtypeid		VARCHAR(MAX) = '',
	@UserDeRowCount		INT,
	--@ifAssets			varchar(10),		--固定资产管理模式："0"-项目管理(非总账模式)；"1"-卡片管理(总账模式)
	@stypeidin			VARCHAR(MAX) = '',	--资金调拨单-调入机构
	@transfertype		INT = 0	,			--资金调拨单-业务类型0=全部,1=现金调拨,2=账户转账
	@ptypecategoryid    	varchar(MAX)	='' ,		-- 商品类别id 
	@ZYDetail   		varchar(255)	='',  		-- 单据明细摘要
	@posid				VARCHAR(256),				--9.91新增 根据pos名称查询
	@showprintcount		VARCHAR(10)='0'				--9.91 1.显示打印记录 0.不显示打印记录
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1


DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
----------------------------------------------------查看操作员的权限----------------------------------------------------
IF @BillType = '-1'
	SET @BillType = ''
	
-- 限制Ktype
CREATE TABLE #KType(TypeId		varchar(100))
CREATE NONCLUSTERED INDEX CIX_KType_TypeId ON #KType(TypeId)

CREATE TABLE #KType2(TypeId		varchar(100))
CREATE NONCLUSTERED INDEX CIX_KType2_TypeId ON #KType2(TypeId)

IF RTRIM(@KTypeId)<>''
	BEGIN
		SET @KTypeId = LTRIM(RTRIM(@KTypeId))
		IF CHARINDEX(',',@BillType)=0 AND @BillType IN (17,21)
		BEGIN
			INSERT INTO #KType(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@KTypeId,4) S
		END
		ELSE
		BEGIN
			INSERT INTO #KType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S
		END
	END

IF RTRIM(@KTypeId1)<>''
	BEGIN
		SET @KTypeId1 = LTRIM(RTRIM(@KTypeId1))
		IF CHARINDEX(',',@BillType)=0 AND @BillType IN (17,21)
		BEGIN
			INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@KTypeId1,4) S
			
		END
		ELSE
		BEGIN
			INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId1,4,@OperatorID) S
		END
	END

DECLARE @BtypeID VARCHAR(MAX)
SET @BtypeID=''

SET @BTypeId = @BTypeIds



--------------------------设置3种权限的标识-------------------------
DECLARE @SQL_WHERE VARCHAR(MAX)
SELECT @SQL_WHERE= ''
DECLARE @SQL_JOIN VARCHAR(MAX)
SELECT @SQL_JOIN= ''

SELECT @SQL_WHERE =' WHERE 	a.[BillDate]>=''' + @startdate +'''
							AND a.[BillDate]<=''' + @EndDate +''' 
							AND a.IfCheck=''f'' 
							AND a.BillType NOT IN (176,177,179,180,182,184,185,192,195,198,414) 
							AND a.IfYearBill = 0 
							AND a.IsIni = 0 '


----------------------判断系统未启用某些配置时不应该显示的单据   start--------------------------------------
DECLARE @ifAssets INT  ,@combinationproduct INT,@usetransport INT
--固定资产
SELECT @ifAssets=SubValue FROM dbo.sysdata WHERE SubName='assets'
IF @ifAssets <> 1
	SET	@SQL_WHERE += ' AND a.BillType NOT IN (212,213,214)'
--组合品
SELECT @combinationproduct=SubValue FROM sysdata WHERE SubName = 'combinationproduct'  
IF @combinationproduct<>1
	 SET @SQL_WHERE += ' AND a.BillType NOT IN (12,46)'
--物流运输单
SELECT @usetransport=SubValue FROM sysdata WHERE SubName = 'usetransport'  
IF @usetransport<>1
	 SET @SQL_WHERE += ' AND a.BillType NOT IN (414)'
----------------------判断系统未启用某些配置时不应该显示的单据 end----------------------------------------

--权限处理部分
DECLARE @re_pass		INT,
		@re_check		INT,
		@offset_pass	INT,	--过帐权限
		@offset_check	INT		--审核人审核他人草稿权限

SELECT @offset_pass = 119		--过帐权限
SELECT @offset_check = 467		--查看他人业务草稿
EXEC @re_check=GP_CheckLimit @OperatorID,@offset_check
     ------处理单据查看权限------
IF @OperatorID <> '00001'  -- 相关单据查看权限，除开管理员
BEGIN
    DECLARE @BillTypeList1 VARCHAR(MAX)
    DECLARE @LimitList1 VARCHAR(MAX)
    DECLARE @BillTypes1 VARCHAR(2000)

   --单据查看权限
    SELECT  @BillTypes1 = '(9999 '

    SET @BillTypeList1 = ' 305,11,45,215,4,34,6,66,17,21,9,14,139,126,57,16,116,115,128,129,'
    SET @LimitList1 = '2676,2679,2682,2709,2831,2718,2721,2837,2739,2742,2751,2754,2688,2727,2882,2769,2819,2822,2825,2828,'

    SET @BillTypeList1 += '  36,93,77,84,212,85,213,78,214,5,10,148,149,140,141,142,143,144,145,'
    SET @LimitList1 += '2855,2864,2861,2873,2914,2876,2917,2879,2920,2867,2870,2843,2849,2691,2700,2694,2697,2923,2736,'

    SET @BillTypeList1 += ' 146,147,150,156,151,158,159,160,161,165,166,167,168,170,171,172,173,'
    SET @LimitList1 += '2730,2733,2846,2781,2852,2858,2885,2685,2724,2781,2784,2787,2790,2796,2799,2802,2805,'	

    SET @BillTypeList1 += ' 174,175,183,186,187,188,189,190,191,197,195,196,200,201,202,203,205,206,181,312,310,169,'
    SET @LimitList1 += '2808,2811,2906,1368,2745,2748,2834,2840,1472,1474,1487,1477,1478,2775,2778,2772,2888,2891,2900,4501,4318,2793,'					

    SET @BillTypeList1 += ' 400,401,402,403,450,12,46,427'
    SET @LimitList1 += '4581,4590,4602,4611,4667,4753,4761,4219'

    SELECT  @BillTypes1 = @BillTypes1
            + CASE WHEN SUBSTRING(L.lim, T.OFFSET, 1) = 1
                   THEN ',' + T.BillType
                   ELSE ''
              END
    FROM    ( SELECT    A.ID ,
                        A.a AS BillType ,
                        CONVERT(INT, B.a) AS OFFSET
              FROM      ( SELECT    ROW_NUMBER() OVER ( ORDER BY ( SELECT
                                              0
                                              ) ) AS ID ,
                                    a
                          FROM      f_split(@BillTypeList1,
                                            ',')
                        ) A
                        INNER JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY ( SELECT
                                              0
                                              ) ) AS ID ,
                                            a
                                     FROM   f_split(@LimitList1,
                                              ',')
                                   ) B ON A.ID = B.ID
            ) T ,
            loginuser L
    WHERE   L.etypeid = @OperatorID			

    SET @BillTypes1 = @BillTypes1 + ' ) '

    SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillType in '
        + @BillTypes1
    
END       
----首先有查看他人草稿，并且对那个单据自己本身有查看权限才能查看别人的单据
IF @re_check = 1  --1是没有查看他人草稿的权限，0是有权限
BEGIN
	SET @SQL_WHERE = @SQL_WHERE + ' AND (a.Checke = '''+@OperatorID+''' OR ISNULL(a.Checke,'''') = '''')'
END	
		
--查优惠的情况,0.无优惠  1.有优惠
IF @Yh <> 9	
BEGIN
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillType IN (305,11,45,215,160,34,6,161,4,66,178,195,167,168,170,172,12,46,181,312) '
	IF @Yh = 0
		SET @SQL_WHERE = @SQL_WHERE + ' AND ISNULL(a.preferencemoney,0) = 0'
	ELSE
		SET @SQL_WHERE = @SQL_WHERE + ' AND ISNULL(a.preferencemoney,0) <> 0'
END

--会员卡情况
IF @hy <> 9
BEGIN
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillType IN (305,11,45,215,178,179,183,195,167,168,172,12,46,427) '
	IF @hy = 0
		SET @SQL_WHERE = @SQL_WHERE + ' AND ISNULL(a.VipCardID,0) = -1'
	ELSE
		SET @SQL_WHERE = @SQL_WHERE + ' AND ISNULL(a.VipCardID,0) <> -1'
END

--单价
CREATE TABLE #PTypePriceBillId
(
	BillNumberId NUMERIC(18,0)
)
CREATE NONCLUSTERED INDEX CIX_PTypePriceBillId_BillNumberId ON #PTypePriceBillId(BillNumberId)

IF @Price <> 9 AND CHARINDEX(',',@BillType) = 0 AND (@BillType IN (305,11,45,215,160,140,141,142,143,34,6,161,144,145,146,147,17,21,57,16,400,401,402,403,12,46) OR @BillType = '') --零售、销售出库、销售退货、销售换货、委托代销发货、委托代销退货、委托代销结算、委托调价、采购入库、采购退货、零售退货、采购换货、受托收货、受托退货、受托结算、受托调价、变价调拨、成本调价、生产拆装
BEGIN	
	DECLARE @PTypePriceSql			VARCHAR(5000),
			@PTypePriceCondition	VARCHAR(200)
	SET @PTypePriceSql = ''
	SET @PTypePriceCondition = ''
	IF @Price = '0'
		SET @PTypePriceCondition = '>' + CAST(@PriceValue AS VARCHAR(100))
	ELSE IF @Price = '1'
		SET @PTypePriceCondition = '=' + CAST(@PriceValue AS VARCHAR(100))
	ELSE IF @Price = '2'
		SET @PTypePriceCondition = '<' + CAST(@PriceValue AS VARCHAR(100))
	ELSE IF @Price = '3'
		SET @PTypePriceCondition = '<=' + CAST(@PriceValue AS VARCHAR(100))
	ELSE IF @Price = '4'
		SET @PTypePriceCondition = '>=' + CAST(@PriceValue AS VARCHAR(100))
	
	SET @PTypePriceSql = '	INSERT INTO #PTypePriceBillId(BillNumberid)
							SELECT	 B.BillNumberId
							FROM	(
										SELECT	distinct BillNumberId FROM RetailBill WHERE SalePrice ' + @PTypePriceCondition + '	
										UNION ALL
										SELECT distinct	BillNumberId FROM SaleBill WHERE SalePrice ' + @PTypePriceCondition + '	
										UNION ALL
										SELECT	distinct BillNumberId FROM SaleBackBill WHERE SalePrice ' + @PTypePriceCondition + '
										UNION ALL
										SELECT	 distinct BillNumberId FROM SaleGoodsExchangeBill WHERE SalePrice ' + @PTypePriceCondition + '
										UNION ALL
										SELECT	distinct BillNumberId FROM CommissionBill WHERE SalePrice ' + @PTypePriceCondition + '			
										UNION ALL
										SELECT	distinct BillNumberId FROM BuyBill WHERE	SalePrice ' + @PTypePriceCondition + '	
										UNION ALL
										SELECT	distinct BillNumberId FROM BuyBackBill WHERE	SalePrice ' + @PTypePriceCondition + '
										UNION ALL
										SELECT	distinct BillNumberId FROM BuyGoodsExchangeBill WHERE SalePrice ' + @PTypePriceCondition + '	
										UNION ALL
										SELECT	distinct BillNumberId FROM MoveBjBill WHERE Price ' + @PTypePriceCondition + '												
										UNION ALL
										SELECT	distinct BillNumberId FROM AdPriceBill WHERE	Price ' + @PTypePriceCondition + '	
										UNION ALL
										SELECT	distinct BillNumberId FROM DisassembleBill WHERE	CostPrice ' + @PTypePriceCondition + '																				
										union all
										select distinct billnumberid from RetailBackBill where saleprice '+@PTypePriceCondition+'		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM movebill WHERE Price ' + @PTypePriceCondition + '	
										UNION ALL
										SELECT distinct BILLNUMBERID FROM SendBill WHERE SalePrice ' + @PTypePriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM SendBackBill WHERE SalePrice ' + @PTypePriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM AppraisalBill WHERE SalePrice ' + @PTypePriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM AppraisalBackBill WHERE SalePrice ' + @PTypePriceCondition + '	
										UNION ALL
										SELECT distinct  BILLNUMBERID FROM PT_Combin_SaleBillDetail WHERE SalePrice ' + @PTypePriceCondition + '	
										UNION ALL
										SELECT distinct BILLNUMBERID FROM PT_Combin_SaleBackBillDetail WHERE SalePrice ' + @PTypePriceCondition + '																																		
																																
							)B
						 '	
	--PRINT(@PTypePriceSql)
	EXEC(@PTypePriceSql)	
	SET @SQL_JOIN+=' INNER JOIN #PTypePriceBillId PPB1 ON PPB1.BILLNUMBERID=a.BillNumberId'
				 
END

--折扣
CREATE TABLE #PTypeDiscountBillId
(
	BillNumberId NUMERIC(18,0)
)
CREATE NONCLUSTERED INDEX CIX_PTypeDiscountBillId_BillNumberId ON #PTypeDiscountBillId(BillNumberId)

IF @Discount <> 9 AND CHARINDEX(',',@BillType) = 0 AND (@BillType IN (305,11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403,12,46) OR @BillType = '')	--零售、销售出库、销售退货、销售换货、委托代销发货、委托代销退货、委托代销结算、采购入库、采购退货、零售退货、采购换货、受托收货、受托退货、受托结算
BEGIN
	DECLARE @DiscountPriceSql		VARCHAR(5000),
			@DiscountPriceCondition	VARCHAR(200)
	SET @DiscountPriceSql = ''
	SET @DiscountPriceCondition = ''			
	IF @Discount = '0'
		SET @DiscountPriceCondition = '>' + CAST(@DiscountValue AS VARCHAR(100))
	ELSE IF @Discount = '1'
		SET @DiscountPriceCondition = '=' + CAST(@DiscountValue AS VARCHAR(100))
	ELSE IF @Discount = '2'
		SET @DiscountPriceCondition = '<' + CAST(@DiscountValue AS VARCHAR(100))
	ELSE IF @Discount = '3'
		SET @DiscountPriceCondition = '<=' + CAST(@DiscountValue AS VARCHAR(100))
	ELSE IF @Discount = '4'
		SET @DiscountPriceCondition = '>=' + CAST(@DiscountValue AS VARCHAR(100))
		
	SET @DiscountPriceSql = 'INSERT INTO #PTypeDiscountBillId(BillNumberId)
										SELECT distinct BillNumberId FROM RetailBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM SaleBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM SaleBackBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM SaleGoodsExchangeBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM CommissionBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM BuyBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM BuyBackBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM BuyGoodsExchangeBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM RetailBackBill WHERE Discount ' + @DiscountPriceCondition + '
										UNION ALL
										SELECT distinct BILLNUMBERID FROM SendBill WHERE Discount ' + @DiscountPriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM SendBackBill WHERE Discount ' + @DiscountPriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM AppraisalBill WHERE Discount ' + @DiscountPriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM AppraisalBackBill WHERE Discount ' + @DiscountPriceCondition + '	
										UNION ALL
										SELECT distinct BILLNUMBERID FROM PT_Combin_SaleBillDetail WHERE Discount ' + @DiscountPriceCondition + '	
										UNION ALL
										SELECT distinct BILLNUMBERID FROM PT_Combin_SaleBackBillDetail WHERE Discount ' + @DiscountPriceCondition + '																																		
							  '	
	--PRINT(@DiscountPriceSql)	
	EXEC(@DiscountPriceSql)	
	SET @SQL_JOIN+=' INNER JOIN #PTypeDiscountBillId PDB1 ON PDB1.BillNumberId=a.BillNumberId and a.billtype in (305,11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403,12,46) '
	--SET @SQL_WHERE = @SQL_WHERE + ' AND A.BillType IN (305,11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403) '			
	
END

--税率
CREATE TABLE #PTypeTaxBillId
(
	BillNumberId NUMERIC(18,0)
)
CREATE NONCLUSTERED INDEX CIX_PTypeTaxBillId_BillNumberId ON #PTypeTaxBillId(BillNumberId)

IF @Tax <> 9 AND CHARINDEX(',',@BillType) = 0 AND (@BillType IN (11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403,12,46) OR @BillType = '')	--销售出库、销售退货、销售换货、委托代销发货、委托代销退货、委托代销结算、采购入库、采购退货、零售退货、采购换货、受托收货、受托退货、受托结算
BEGIN
	DECLARE @TaxPriceSql		VARCHAR(5000),
			@TaxPriceCondition	VARCHAR(200)
	SET @TaxPriceSql = ''
	SET @TaxPriceCondition = ''			
	IF @Tax = '0'
		SET @TaxPriceCondition = '>' + CAST(@TaxValue AS VARCHAR(100))
	ELSE IF @Tax = '1'
		SET @TaxPriceCondition = '=' + CAST(@TaxValue AS VARCHAR(100))
	ELSE IF @Tax = '2'
		SET @TaxPriceCondition = '<' + CAST(@TaxValue AS VARCHAR(100))
	ELSE IF @Tax = '3'
		SET @TaxPriceCondition = '<=' + CAST(@TaxValue AS VARCHAR(100))
	ELSE IF @Tax = '4'
		SET @TaxPriceCondition = '>=' + CAST(@TaxValue AS VARCHAR(100))
		
	SET @TaxPriceSql = 'INSERT INTO #PTypeTaxBillId(BillNumberId)
										SELECT distinct BillNumberId FROM SaleBill WHERE Tax ' + @TaxPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM SaleBackBill WHERE Tax ' + @TaxPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM SaleGoodsExchangeBill WHERE Tax ' + @TaxPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM CommissionBill WHERE Tax ' + @TaxPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM BuyBill WHERE Tax ' + @TaxPriceCondition + '
										UNION ALL
										SELECT  distinct BillNumberId FROM BuyBackBill WHERE Tax ' + @TaxPriceCondition + '
										UNION ALL
										SELECT distinct BillNumberId FROM BuyGoodsExchangeBill WHERE Tax ' + @TaxPriceCondition + '
										UNION ALL
										SELECT distinct BILLNUMBERID FROM SendBill WHERE Tax ' + @TaxPriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM SendBackBill WHERE Tax ' + @TaxPriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM AppraisalBill WHERE Tax ' + @TaxPriceCondition + '		
										UNION ALL
										SELECT distinct BILLNUMBERID FROM AppraisalBackBill WHERE Tax ' + @TaxPriceCondition + '	
										UNION ALL
										SELECT distinct BILLNUMBERID FROM PT_Combin_SaleBillDetail WHERE Tax ' + @TaxPriceCondition + '	
										UNION ALL
										SELECT distinct BILLNUMBERID FROM PT_Combin_SaleBackBillDetail WHERE Tax ' + @TaxPriceCondition + '																																		
						 '
	--PRINT(@TaxPriceSql)
	EXEC(@TaxPriceSql)
	SET @SQL_JOIN+=' INNER JOIN #PTypeTaxBillId PTB1 ON PTB1.BillNumberId=a.BillNumberId AND A.BillType IN (11,45,215,160,140,141,142,34,6,161,144,145,146,400,401,402,403,12,46) '		
END

							
IF @BillType <> ''
	SET @SQL_WHERE = @SQL_WHERE + ' AND exists (SELECT 1 FROM F_Split('''+@BillType+''','','') fs where fs.a=a.billtype )'

IF @BillCode <>''
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.[BillCode] LIKE ''%' + @BillCode +'%'''
IF @Comment <>''
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.[Comment] LIKE ''%' + @Comment +'%'''
IF @explain <>''
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.[Explain] LIKE ''%' + @explain +'%'''

--3.9加筛选条件
IF @UserCode <> '' OR @FullName <> ''
	SET @SQL_WHERE = @SQL_WHERE + ' AND E.USERCODE LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+' AND E.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)
	
IF @AudState = ''
	SET @SQL_WHERE = @SQL_WHERE + ' AND 1 = 1 '
ELSE IF @AudState = '1'
	SET @SQL_JOIN+=' INNER JOIN AuditingBill ATB1 ON ATB1.BillNumberId=A.BillNumberId AND ATB1.BillIndexType = 2 AND ATB1.IfAudit = 1 '
ELSE IF @AudState = '2'
	SET @SQL_JOIN+=' INNER JOIN AuditingBill ATB1 ON ATB1.BillNumberId=A.BillNumberId AND ATB1.BillIndexType = 2 AND ATB1.IfAudit = 0 '
ELSE IF @AudState = '3'
	SET @SQL_JOIN+=' INNER JOIN AuditingBill ATB1 ON ATB1.BillNumberId=A.BillNumberId AND ATB1.BillIndexType = 2 AND ATB1.IfAudit = -1 '
ELSE IF @AudState = '4'
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillNumberId NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 2) '
	
-- 限制条件(Atype)
IF @Atypeid <>''
	BEGIN	
		SET @Atypeid = @Atypeid
		CREATE TABLE #AType(TypeId varchar(100))
		INSERT INTO #AType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@Atypeid,5,@OperatorID) S		

		--会员储值、预收资金、预付资金
		INSERT INTO #ATYPE(TYPEID)SELECT NID FROM AC_ITEMS A INNER JOIN (SELECT * FROM f_SPLIT(@ATYPEID,',')) B ON A.nid=b.a
		
		CREATE TABLE #ZJBILLNUMBERID2 (BILLNUMBERID NUMERIC(10,0))
		
		INSERT INTO #ZJBILLNUMBERID2 (BillNumberId)
		SELECT BillNumberId FROM BillMulAccount B INNER JOIN #AType A ON B.ATypeId=A.TypeId
		UNION ALL 
		SELECT BillNumberId FROM PayBill P INNER JOIN #AType A ON  P.ATypeId=A.TypeId
		UNION ALL 
		SELECT BillNumberId FROM GatheringBill G INNER JOIN #AType A ON G.ATypeId=A.TypeId
		UNION ALL 
		SELECT BillNumberId FROM PreBill PR INNER JOIN #AType A ON PR.ATypeId=A.TypeId
		UNION ALL 
		SELECT BillNumberId FROM BillIndex BI INNER JOIN #AType A ON BI.ATypeId=A.TypeId AND BI.BILLTYPE=158
		
		SELECT DISTINCT BILLNUMBERID INTO #ZJBILLNUMBERID FROM #ZJBILLNUMBERID2

		
		IF @ifAssets='0'--固定资产管理模式：项目管理
			SET @SQL_JOIN+=' INNER JOIN  #ZJBILLNUMBERID ZB1 ON ZB1.BillNumberId= A.BillNumberId AND A.BillType NOT IN (140,142,143,144,146,147,16,17,14,21,9,57,115,116,128,129,78,5,10,139,126,159,165,166,169,171,173,174,175,183,186,187,188,205,206) '
		ELSE
			SET @SQL_JOIN+=' INNER JOIN  #ZJBILLNUMBERID ZB1 ON ZB1.BillNumberId= A.BillNumberId AND A.BillType NOT IN (140,142,143,144,146,147,16,17,14,21,9,57,115,116,128,129,78,5,10,139,126,159,165,166,169,171,173,174,175,183,186,187,188,205,206,214)'
	END	
	
--处理部门信息
CREATE TABLE #Department(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_DType ON #Department(TypeID)

SET @DTypeId = @DTypeId
INSERT INTO #Department(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)
IF @DTypeId = ''
	SELECT @SQL_JOIN = @SQL_JOIN + ' INNER JOIN (select typeid from #Department union all select '''') dL ON A.DTypeId = DL.TYPEID '	
else
	SELECT @SQL_JOIN = @SQL_JOIN + ' INNER JOIN #Department dL ON A.DTypeId = DL.TYPEID '	
	
--职员
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
CREATE CLUSTERED INDEX CIX_EType ON #GetManETypeId(TypeID)

INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S
IF NOT (@ETypeId='' AND @METypeId = '00001')
	BEGIN
		IF @EtypeId = ''
			SELECT @SQL_JOIN = @SQL_JOIN + ' INNER JOIN(select typeid from  #GetManETypeId union all select '''') EL ON a.ETypeId=EL.TypeId '
		ELSE
			SELECT @SQL_JOIN = @SQL_JOIN + ' INNER JOIN #GetManETypeId EL ON a.ETypeId=EL.TypeId '		
	END

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
CREATE CLUSTERED INDEX CIX_SType ON #GetManSTypeId(TypeID)

IF @STypeId<> '' OR @MSTypeId = '-99999'
BEGIN
	INSERT INTO #GetManSTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) S
	--当单据为资金调拨单，并且调出机构未选择时。 将 调出、调入机构的关系变为OR（主要根据调入机构来查询）
	IF(@BillType = '310' AND @sTypeId = '')
		SET @SQL_JOIN = @SQL_JOIN
	ELSE --否则为AND
		SET @SQL_JOIN = @SQL_JOIN + ' INNER JOIN #GetManSTypeId SL ON a.Stypeid=SL.TypeId '
END

--调出分支机构
CREATE TABLE #GetManSTypeId2(TypeId	VARCHAR(100))
CREATE CLUSTERED INDEX CIX_SType2 ON #GetManSTypeId2(TypeID)
INSERT INTO #GetManSTypeId2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@stypeidin,11,@OperatorID) S

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_MDType ON #GetManDTypeId(TypeID)
INSERT INTO #GetManDTypeId(TypeId)VALUES('')
IF NOT (@MDTypeId = '00000')
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)
	
--往来单位
CREATE TABLE #dealBTypeId(TypeId	VARCHAR(100))
CREATE CLUSTERED INDEX CIX_DEALBType ON #dealBTypeId(TypeID)

IF @dealbtypeid ='' OR @dealbtypeid = '%%' OR @dealbtypeid = '%'
	BEGIN
		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
		BEGIN
			INSERT INTO #dealBTypeId(TypeId)
			SELECT	B.TypeId 
			FROM	BType_L L
			INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
			WHERE	L.etypeid = @OperatorID
					AND L.flag = 1 
					AND B.sonnum = 0
			
			INSERT INTO #dealBTypeId(TypeId)VALUES('')
			INSERT INTO #dealBTypeId(TypeId)VALUES(NULL)
			
			SET @SQL_JOIN = @SQL_JOIN + ' INNER JOIN #GetManBTypeId dealb on dealb.TYPEID=A.dealbtypeid '
		END
	END
ELSE
	BEGIN
		INSERT INTO #dealBTypeId(TypeId)
		SELECT TypeId FROM F_GetAllManagerBaseByTypeId(@dealbtypeid,2,@OperatorID,@stypeid)
		
		SET @SQL_JOIN = @SQL_JOIN + ' INNER JOIN #dealBTypeId dealb ON a.dealBTypeId=dealb.TypeId '
	END		

--结算单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
CREATE CLUSTERED INDEX CIX_MANBType ON #GetManBTypeId(TypeID)

IF @BTypeId ='' OR @BTypeId = '%%' OR @BTypeId = '%'
	BEGIN
		IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
		BEGIN
			INSERT INTO #GetManBTypeId(TypeId)
			SELECT	B.TypeId 
			FROM	BType_L L
			INNER JOIN BType  B ON B.TypeId LIKE L.TypeId + '%'
			WHERE	L.etypeid = @OperatorID
					AND L.flag = 1 
					AND B.sonnum = 0
			
			INSERT INTO #GetManBTypeId(TypeId)VALUES('')
			INSERT INTO #GetManBTypeId(TypeId)VALUES(NULL)
			
			SET @SQL_JOIN = @SQL_JOIN + ' INNER JOIN #GetManBTypeId bL on bL.TYPEID=A.btypeid '
		END
	END
ELSE
	BEGIN
		INSERT INTO #GetManBTypeId(TypeId)
		SELECT TypeId FROM F_GetAllManagerBaseByTypeId(@BTypeId,2,@OperatorID,@stypeid)
		
		IF @ifAssets='0'--固定资产管理模式：项目管理
			SET @SQL_WHERE = @SQL_WHERE + ' AND A.BillType NOT IN (5,9,10,14,16,17,21,57,78,158,159,173,174,175,187,188)'
		ELSE
			SET @SQL_WHERE = @SQL_WHERE + ' AND A.BillType NOT IN (5,9,10,14,16,17,21,57,78,214,158,159,173,174,175,187,188)'
		
		--为应收增加单、应收减少单、应付增加单、应付减少单 时结算单位搜索表体
		IF(@BillType ='115' OR @BillType ='116' OR @BillType ='128' OR @BillType ='129')
			SET @SQL_JOIN = @SQL_JOIN + ' INNER JOIN (SELECT DISTINCT A1.BillNumberId FROM addebtbill AS A1 INNER JOIN #GetManBTypeId AS B1 ON(A1.BtypeId = B1.TypeId)) AS bL ON(a.BillNumberId = bL.BillNumberId) '		
		ELSE
			SET @SQL_JOIN = @SQL_JOIN + ' INNER JOIN #GetManBTypeId bL ON a.BTypeId=BL.TypeId '
	END
	
-- 单据明细摘要查询 
IF RTRIM(@ZYDetail)<>''
	BEGIN          
		-- 建立包含一个BillNumberID字段的临时表
		CREATE TABLE #commentTable(billnumberid INT)
		CREATE CLUSTERED INDEX CIX_commentTable ON #commentTable(billnumberid) 
	
		DECLARE @TempTableSQL varchar(MAX)
		 
        SELECT @TempTableSQL=' INSERT INTO #commentTable
							   SELECT DISTINCT t.billnumberid FROM 
							   (
									select billnumberid, comment from accountcredence union 
									select billnumberid, comment from addebtbill union 
									select billnumberid, comment from adpricebill union 
									select billnumberid, comment from advantage union 
									select billnumberid, comment from AssetIncDecBill union 
									select billnumberid, comment from buybackbill union 
									select billnumberid, comment from buybill union 
									select billnumberid, comment from buygoodsexchangebill union 
									select billnumberid, comment from chargeoffbill union 
									select billnumberid, comment from commissionbill union 
									select billnumberid, comment from DepBill union 
									select billnumberid, comment from disassemblebill union 
									select billnumberid, comment from gatheringbill union 
									select billnumberid, comment from givebill union 
									select billnumberid, comment from givemebill union 
									select billnumberid, comment from integralexchangebill union 
									select billnumberid, comment from losebill union 
									select billnumberid, comment from moneybill union 
									select billnumberid, comment from movebill union 
									select billnumberid, comment from movebjbill union 
									select billnumberid, comment from movemoneybill union 
									select billnumberid, comment from otherinoutbill union 
									select billnumberid, comment from overflowbill union 
									select billnumberid, comment from paybill union 
									select billnumberid, comment from prebill union 
									select billnumberid, comment from priceprotectbill union 
									select billnumberid, comment from RetailBackBill union 
									select billnumberid, comment from retailbill union 
									select billnumberid, comment from salebackbill union 
									select billnumberid, comment from salebill union 
									select billnumberid, comment from salegoodsexchangebill union 
									select billnumberid, comment from sharesourcebill union 
									select billnumberid, comment from stypemovebill union 
									select billnumberid, comment from VipAddMoneyBatchBill union 
									select billnumberid, comment from wx_bill_call union 
									select billnumberid, comment from wx_bill_getback union 
									select billnumberid, comment from wx_bill_goto union 
									select billnumberid, comment from wx_bill_in union 
									select billnumberid, comment from wx_bill_jiejian union 
									select billnumberid, comment from wx_bill_move union 
									select billnumberid, comment from wx_bill_out union 
									select billnumberid, comment from wx_bill_replace union 
									select billnumberid, comment from wx_bill_self union 
									select billnumberid, comment from wx_bill_send union 
									select billnumberid, comment from wx_bill_sendback  UNION
									--一下部分是以前漏加了的单据类型  谢吉康 9.8.3 2017-10-16
									--上表体
									select  billnumberid,comment from PT_Combin_SaleBill UNION 
									select  billnumberid,comment from PT_Combin_SaleBackBill UNION
									select  billnumberid,comment from RetailCombinationBill UNION
									--下表体
									select  billnumberid,comment from PT_Combin_SaleBillDetail UNION 
									select  billnumberid,comment from PT_Combin_SaleBackBillDetail UNION
									select  billnumberid,comment from askpricebill UNION
									select  billnumberid,comment from stypemovebill UNION
									select  billnumberid,comment from prebill UNION
									select  billnumberid,comment from sharesourcebill UNION
									select  billnumberid,comment from AssetIncDecBill UNION
									select  billnumberid,comment from FixedAssetsDetails UNION
									select  billnumberid,comment from CapitalTransfer_Bill UNION	
									select  billnumberid,comment from AppraisalBill UNION
									select  billnumberid,comment from AppraisalBackBill UNION
									select  billnumberid,comment from SendBill UNION
									select  billnumberid,comment from SendBackBill UNION
									select  billnumberid,comment from Transportbill
							   ) t WHERE t.COMMENT LIKE ''%'+@ZYDetail+'%'' '
							  -- IF (@BillType = '')
							  -- BEGIN
									--SET @TempTableSQL+=   ' UNION ALL  SELECT DISTINCT billnumberid FROM moneybill WHERE COMMENT LIKE ''%'+@ZYDetail+'%'' '
         --                      END  
         --                      ELSE 
         --                      BEGIN
         --                       IF exists(SELECT top 1 1  FROM dbo.f_split(@BillType,',') fs where  fs.a='36' )
									--SET @TempTableSQL+=   ' UNION ALL  SELECT DISTINCT billnumberid FROM moneybill WHERE COMMENT LIKE ''%'+@ZYDetail+'%'' '
         --                      END  
                         
        EXEC(@TempTableSQL)
       
        SELECT @SQL_Join +=' 
							INNER JOIN #commentTable CMT1 ON  a.[BillNumberID]=CMT1.BillNumberID ' 
	END	
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
CREATE CLUSTERED INDEX CIX_MANKType ON #GetManKTypeId(TypeID)

INSERT INTO #GetManKTypeId(TypeId) SELECT TYPEID FROM F_GetManDetailKType(@OperatorID)
IF @KTypeId = '' AND @KTypeId1 = ''
	INSERT INTO #GetManKTypeId(TypeId)VALUES('00000')

IF @BillType = '' OR CHARINDEX(',',@BillType)>0
	BEGIN
		SET @SQL_WHERE = @SQL_WHERE + ' AND ('
		IF RTRIM(@KTypeId)<>''
			BEGIN
				SET @SQL_WHERE = @SQL_WHERE + ' ( Exists (SELECT 1  FROM #KType K WHERE K.TYPEID=A.KTypeId ) AND A.BILLTYPE NOT IN (21,179,186,188))'
				SET @SQL_WHERE = @SQL_WHERE + ' OR ( Exists (SELECT 1  FROM #KType k WHERE K.TypeId=A.KTypeId2) AND A.BILLTYPE IN (188,16,160,161,166,172,173,174,175))'
				
				IF EXISTS(SELECT Value FROM userconfig WHERE ConfigName ='MoveInOutKLimit' AND Value='1')
					SET @SQL_WHERE = @SQL_WHERE + ' OR ((Exists(SELECT 1  FROM #KType K WHERE K.TYPEID=A.KTypeId )) AND (Exists (SELECT 1  FROM #KType K WHERE K.TypeId=A.KTypeId2)) AND A.BILLTYPE IN (17,21)) '
				ELSE	--出库受权限控制，入库不控制
					SET @SQL_WHERE = @SQL_WHERE + ' OR ((Exists(SELECT 1  FROM #KType K WHERE K.TYPEID=A.KTypeId )) OR (Exists (SELECT 1  FROM #KType K WHERE K.TypeId=A.KTypeId2)) AND A.BILLTYPE IN (17,21)) '
			END
		ELSE
			BEGIN
				IF @MKTypeId = '00000'
					SET @SQL_WHERE = @SQL_WHERE + ' 1=1'
				ELSE
					BEGIN
						IF @ifAssets<>'1'
							SET @SQL_WHERE = @SQL_WHERE + ' (A.KTypeId='''' AND A.BILLTYPE IN (4,141,143,66,145,147,115,116,128,129,36,158,93,77,84,85,78,5,10,148,149,150,151,159,171,179,186,189,190,195,200,192,205,206,427))'
						else
							SET @SQL_WHERE = @SQL_WHERE + ' (A.KTypeId='''' AND A.BILLTYPE IN (4,141,143,66,145,147,115,116,128,129,36,158,93,77,84,85,78,5,10,148,149,150,151,159,171,179,186,189,190,195,200,192,205,206,212,213,214,427))'				
						SET @SQL_WHERE = @SQL_WHERE +' OR (A.KTypeId = '''') '
		
						IF EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerKTypeId = '00000')
							SET @SQL_WHERE = @SQL_WHERE + ' OR A.KTypeId = ''00000'' OR A.KTypeId = ''10000'''
						ELSE
							SET @SQL_WHERE = @SQL_WHERE + ' OR A.KTypeId = ''00000'' OR A.KTypeId = ''10000'''
		
						SET @SQL_WHERE = @SQL_WHERE +'  OR (Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )  AND A.BILLTYPE NOT IN (16,17,21,160,161,166,172,173,174,175,188))'
						SET @SQL_WHERE = @SQL_WHERE +'  OR (Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) AND A.BILLTYPE IN (188))'
						SET @SQL_WHERE = @SQL_WHERE +'  OR ((Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )  OR Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) ) AND A.BILLTYPE IN (166,172))'
						SET @SQL_WHERE = @SQL_WHERE +'  OR ((Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )  AND A.KTypeId2='''') AND A.BILLTYPE IN (166,172))'
						SET @SQL_WHERE = @SQL_WHERE +'  OR ((A.KTypeId='''' AND Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) ) AND A.BILLTYPE IN (166,172))'
						SET @SQL_WHERE = @SQL_WHERE +'  OR ((A.KTypeId='''' AND A.KTypeId2='''') AND A.BILLTYPE IN (166,172))'
						SET @SQL_WHERE = @SQL_WHERE +'  OR ((Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )  OR Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) ) AND A.BILLTYPE IN (16,160,161,173,174,175))'
						
						IF EXISTS(SELECT Value FROM userconfig WHERE ConfigName ='MoveInOutKLimit' AND Value='1')
							SET @SQL_WHERE = @SQL_WHERE + ' OR Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )  AND Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 )  AND A.BILLTYPE IN (17,21) '
						ELSE
							SET @SQL_WHERE = @SQL_WHERE + ' OR ((Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )  OR Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) ) AND A.BILLTYPE IN (17,21)) '
					END
			END
		SET @SQL_WHERE = @SQL_WHERE + ' )'
	END
ELSE
	BEGIN
		--无仓库的单据
		IF @BillType NOT IN (4,141,143,66,145,147,115,116,128,129,36,158,93,77,84,85,78,5,10,148,149,150,151,159,171,179,186,189,190,195,200,192,205,206,212,213,214,310,427)
			BEGIN
				SET @SQL_WHERE = @SQL_WHERE + ' AND ('
				IF @BillType NOT IN (16,17,21,160,161,166,172,173,174,175)
					BEGIN
						IF RTRIM(@KTypeId)<>''
							IF @BillType = 188
								SET @SQL_WHERE = @SQL_WHERE + ' (Exists (SELECT 1 FROM #KType K WHERE K.TYPEID=A.KTypeId2 ))'
							ELSE
								SET @SQL_WHERE = @SQL_WHERE + ' (Exists (SELECT 1 FROM #KType K WHERE K.TYPEID=A.KTypeId ))'
						ELSE
							BEGIN
								IF @MKTypeId = '00000'
									SET @SQL_WHERE = @SQL_WHERE + ' 1=1 '
								ELSE
									BEGIN
										IF @BillType = 188
											SET @SQL_WHERE = @SQL_WHERE + ' (Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) OR A.KTypeId='''' OR A.KTypeId=''10000'')'
										ELSE
											SET @SQL_WHERE = @SQL_WHERE + ' (Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) OR A.KTypeId='''' OR A.KTypeId=''10000'')'
									END
							END
					END
				ELSE IF @BillType IN (17,21)
					BEGIN
						IF EXISTS(SELECT Value FROM userconfig WHERE ConfigName ='MoveInOutKLimit' AND Value='1')
							BEGIN
								IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)=''
									BEGIN
										SET @SQL_WHERE = @SQL_WHERE + ' Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) '
									END
								ELSE IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)<>''
									BEGIN
										SET @SQL_WHERE = @SQL_WHERE + ' Exists(SELECT 1 FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1 FROM #Ktype2 K WHERE K.TYPEID=A.KTypeId2 ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) '
									END
								ELSE IF RTRIM(@KTypeId)<>'' AND RTRIM(@KTypeId1)=''
									BEGIN
										SET @SQL_WHERE = @SQL_WHERE + ' Exists(SELECT 1 FROM #Ktype K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) '
									END
								ELSE
									BEGIN
										SET @SQL_WHERE = @SQL_WHERE + ' Exists(SELECT 1 FROM #Ktype K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #KTYPE2 K WHERE K.TYPEID=A.KTypeId2 ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) '
									END
							END
						ELSE
							BEGIN
								IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)=''
									BEGIN
										SET @SQL_WHERE = @SQL_WHERE + '  Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) OR Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) '
									END
								ELSE IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)<>''
									BEGIN
										SET @SQL_WHERE = @SQL_WHERE + ' (( Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )  OR  Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ) ) AND Exists(SELECT 1  FROM #Ktype2 k WHERE K.TYPEID=A.KTypeId2 )) '
									END
								ELSE IF RTRIM(@KTypeId)<>'' AND RTRIM(@KTypeId1)=''
									BEGIN
										SET @SQL_WHERE = @SQL_WHERE + ' (Exists(SELECT 1  FROM #Ktype K WHERE K.TYPEID=A.KTypeId ) AND (Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) OR  Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ))) '
									END
								ELSE
									BEGIN
										SET @SQL_WHERE = @SQL_WHERE + ' ( (Exists(SELECT 1  FROM #Ktype K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #KTYPE2 K WHERE K.TYPEID=A.KTypeId2 )) AND (Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) OR Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ))) '
									END
							END
					END
				ELSE IF @BillType IN (166,172)
					BEGIN
						IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)=''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE +' (Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) OR Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ))'
								SET @SQL_WHERE = @SQL_WHERE +' OR (Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ) AND A.KTypeId2='''')'
								SET @SQL_WHERE = @SQL_WHERE +' OR (A.KTypeId='''' AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ))'
								SET @SQL_WHERE = @SQL_WHERE +' OR (A.KTypeId='''' AND A.KTypeId2='''')'
							END
						ELSE IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)<>''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((A.KTypeId='''' OR Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )) AND (Exists(SELECT 1  FROM #KTYPE2 K WHERE K.TYPEID=A.KTypeId2) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 )))'
							END
						ELSE IF RTRIM(@KTypeId)<>'' AND RTRIM(@KTypeId1)=''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #Ktype K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )) AND (A.KTypeId2='''' OR Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 )))'
							END
						ELSE
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #Ktype K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )) AND Exists(SELECT 1  FROM #Ktype2  K WHERE K.TYPEID=A.KTypeId2 ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 )))'
							END
					END
				ELSE IF @BillType = 160
					BEGIN
						IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)=''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 )) OR (Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ))) '
							END
						ELSE IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)<>''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 )) AND (Exists(SELECT 1  FROM #Ktype2 K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ))) '
							END
						ELSE IF RTRIM(@KTypeId)<>'' AND RTRIM(@KTypeId1)=''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #Ktype K WHERE K.TYPEID=A.KTypeId2 ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 )) AND (Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ))) '
							END
						ELSE
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #Ktype K WHERE K.TYPEID=A.KTypeId2 ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 )) AND (Exists(SELECT 1  FROM #Ktype2 K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId ))) '
							END
					END
				ELSE
					BEGIN
						IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)=''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )) OR (Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ))) '
							END
						ELSE IF RTRIM(@KTypeId)='' AND RTRIM(@KTypeId1)<>''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #Ktype2 K WHERE K.TYPEID=A.KTypeId2 ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ))) '
							END
						ELSE IF RTRIM(@KTypeId)<>'' AND RTRIM(@KTypeId1)=''
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #Ktype K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )) ) '
							END
						ELSE
							BEGIN
								SET @SQL_WHERE = @SQL_WHERE + ' ((Exists(SELECT 1  FROM #Ktype K WHERE K.TYPEID=A.KTypeId ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId )) AND (Exists(SELECT 1  FROM #Ktype2 K WHERE K.TYPEID=A.KTypeId2 ) AND Exists(SELECT 1  FROM #GetManKTypeId K WHERE K.TYPEID=A.KTypeId2 ))) '
							END
					END
				SET @SQL_WHERE = @SQL_WHERE + ' )'
			END
	END

--限制条件(@PTypeId)
IF @PTypeId<>''
	BEGIN   
		IF @ifAssets='0'--固定资产管理模式：项目管理
			SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.BillType NOT IN (4,66,115,116,128,129,36,158,93,77,84,85,78,5,10,159,189,190,205,206)'
		ELSE
			SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.BillType NOT IN (4,66,115,116,128,129,36,158,93,77,84,85,78,5,10,159,189,190,205,206,212,213,214)'
	END

--限制最大，最小金额	
IF @mintotal<>-999999999999
	BEGIN
		SELECT @SQL_WHERE = @SQL_WHERE + ' AND A.BillType NOT IN (16,17,9,14,139,126,175)'
		SELECT @SQL_WHERE = @SQL_WHERE + ' AND (
							(A.[Totalmoney]>=' + Convert(varchar(20),(@mintotal)) + ' AND A.Redword <>2)  
							 OR 
							(-A.[Totalmoney]>=' + Convert(varchar(20),(@mintotal)) + ' AND A.Redword =2)
							)'
	
	END

IF @maxtotal<>999999999999
	BEGIN
		SELECT @SQL_WHERE = @SQL_WHERE + ' AND A.BillType NOT IN (16,17,9,14,139,126,175)'
		SELECT @SQL_WHERE = @SQL_WHERE + ' AND (
							(A.[Totalmoney]<=' + Convert(varchar(20),(@maxtotal)) + ' AND A.Redword <>2)  
							 OR 
							(-A.[Totalmoney]<=' + Convert(varchar(20),(@maxtotal)) + ' AND A.Redword =2)
							)'
	END	

DECLARE @re_re INT
EXEC @re_re=GP_CheckLimit @OperatorID,@Offset_pass

------处理单据查看权限------
	
DECLARE @BillTypeList VARCHAR(MAX)
DECLARE @LimitList VARCHAR(MAX)
DECLARE @BillTypes VARCHAR(2000)

IF @re_re <>0 
BEGIN
	SELECT @BillTypes = '(9999 '
    --单据查看权限
	SET @BillTypeList = ' 305,  11,  45, 215,   4,  34,   6,  66,  17,  21,   9,  14, 139, 126,  57,  16, 116, 115, 128, 129,'
	SET @LimitList    = '2676,2679,2682,2709,2831,2718,2721,2837,2739,2742,2751,2754,2688,2727,2882,2769,2819,2822,2825,2828,'

	SET @BillTypeList += '  36,  93,  77,  84, 212,  85, 213,  78, 214,   5,  10, 148, 149, 140, 141, 142, 143, 144, 145,'
	SET @LimitList    += '2855,2864,2861,2873,2914,2876,2917,2879,2920,2867,2870,2843,2849,2691,2700,2694,2697,2923,2736,'

	SET @BillTypeList += ' 146, 147, 150, 156, 151, 158, 159, 160, 161, 165, 166, 167, 168, 170, 171, 172, 173,'
	SET @LimitList    += '2730,2733,2846,2781,2852,2858,2885,2685,2724,2784,2787,2790,2793,2796,2799,2802,2805,'	
	
	SET @BillTypeList += ' 174, 175, 183, 186, 187, 188, 189, 190, 191, 197, 195, 196, 200, 201, 202, 203, 205, 206, 181, 312,'
	SET @LimitList    += '2808,2811,2906,1368,2745,2748,2834,2840,1472,1474,1487,1477,1478,2775,2778,2772,2888,2891,2900,4501,'					
	
	SET @BillTypeList += ' 400, 401, 402, 403, 450,  12,  46,310,427,169'
	SET @LimitList    += '4581,4590,4602,4611,4667,4753,4761,4318,4219,2793'					
	
	--不是总账则不显示资金调拨单
	IF((SELECT SubValue FROM SYSDATA WHERE SUBNAME = 'isuseacsystem') = 1)
	BEGIN	
		SET @BillTypeList += ',310 '
		SET @LimitList    += ',4318 '	
	END
	
	IF @OperatorID<>'00001'  -- 相关单据调阅权限
	BEGIN
		SELECT @BillTypes = @BillTypes + CASE WHEN SUBSTRING(L.lim,T.OFFSET,1) = 1 THEN ',' + T.BillType ELSE ''  END 
		FROM(
			SELECT A.ID,A.a AS BillType,CONVERT(INT,B.a) AS OFFSET
			FROM(
				SELECT ROW_NUMBER() OVER (ORDER BY(SELECT 0)) AS ID,a
				FROM f_split(@BillTypeList,',')	
			) A
			INNER JOIN(
				SELECT ROW_NUMBER() OVER (ORDER BY(SELECT 0)) AS ID,a
				FROM f_split(@LimitList,',')	
			)B ON A.ID = B.ID
		) T,loginuser L
		WHERE L.etypeid = @OperatorID			
	END 
	SET @BillTypes = @BillTypes +' ) '
	
	SELECT @SQL_WHERE= @SQL_WHERE + ' AND a.BillType in ' + @BillTypes
	
	
END
--======END=====--

-------------9.4新增资金调拨单-----------------杨俊增加
	IF(@BillType = '310')
	BEGIN
		SELECT @SQL_WHERE = @SQL_WHERE + ' AND A.IfConfirm = 0 '

		--调出机构未选择时，如果调入机构也未选择，则默认筛选调出、调入机构有权限的单据（OR关系）
		--调出有时，则按公共筛选分支机构方式筛选调出机构
		--调入有时，则在查询条件后加上调入机构（AND关系）
		IF(@sTypeId = '')
		BEGIN
			IF(@stypeidin <> '')
				SELECT @SQL_WHERE = @SQL_WHERE + ' 
								AND A.StypeID2 IN(SELECT TypeId FROM #GetManSTypeId2) '
			ELSE
				SELECT @SQL_WHERE = @SQL_WHERE + ' AND (A.StypeID IN(SELECT TypeId FROM #GetManSTypeId) 
								OR A.StypeID2 IN(SELECT TypeId FROM #GetManSTypeId2)) '
		END
		ELSE
		BEGIN
			IF(@stypeidin <> '')
				SELECT @SQL_WHERE = @SQL_WHERE + ' 
								AND A.StypeID2 IN(SELECT TypeId FROM #GetManSTypeId2) '
		END
		
		IF(@transfertype <> 0)
			SELECT @SQL_WHERE = @SQL_WHERE + ' 
							AND A.TransferType = ' + CAST(@transfertype AS VARCHAR(10)) + ' '
	END
--===============--

IF @BtypeID='00000' SELECT @BtypeID=''

--(筛选库存商品)
CREATE TABLE #GetManPTypeId(TypeId	VARCHAR(100))
CREATE CLUSTERED INDEX CIX_MANPType ON #GetManPTypeId(TypeID)


-------------------(9.91)筛选商品 修改 陈强---------------------------
--INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM  dbo.F_LinePC(@OperatorID,@ptypecategoryid) --注释之前的条件

IF @PtypeId='' AND RTRIM(@PtypeIds)=''
BEGIN
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM  dbo.F_LinePC(@OperatorID,@ptypecategoryid)
END

IF (RTRIM(@PtypeIds)<>''  OR @ptypecategoryid<>'') and @PtypeId=''
BEGIN
  INSERT INTO #GetManPTypeId(TypeId) 
  SELECT S.TypeId FROM F_ManPTypeInCategoryID(@OperatorID,@PtypeIds,@ptypecategoryid) S
END
IF (RTRIM(@PtypeIds)<>''  OR @ptypecategoryid<>'') OR @PtypeId<>''
BEGIN
  IF @PtypeId<>''
  BEGIN
	INSERT INTO #GetManPTypeId(TypeId) 
	SELECT	p.TypeId 
	FROM	ptype p 
	INNER JOIN F_ManPTypeInCategoryID(@OperatorID,@PtypeIds,@ptypecategoryid) S ON s.typeid = p.typeid
	WHERE (P.FullName like +'%'+@PtypeId+'%'  OR  P.UserCode Like +'%'+@PtypeId+'%' ) 
  END
  ELSE
  BEGIN
	  INSERT INTO #GetManPTypeId(TypeId) 
	  SELECT P.TypeId 
	  FROM  F_ManPTypeInCategoryID(@OperatorID,@PtypeIds,@ptypecategoryid) S 
	  INNER JOIN ptype p ON s.TypeId = p.typeId  
  END
END

----根据pos名称精准查询
IF @posid<>''
    SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.posID IN('+@posid+')'
  
------------------------------END--------------------------------------

DECLARE @PtypeIdTemp VARCHAR(200)
SET @PtypeIdTemp =@PtypeId
CREATE TABLE #TempPTable(BillnumberID numeric (10,0))
CREATE CLUSTERED INDEX CIX_TEMPType ON #TempPTable(BillnumberID)

IF @PtypeIdTemp <>'' OR @ptypecategoryid<>'' OR @PtypeIds<>''
begin
	set @PtypeId='%'+@PtypeId+'%'
	set @MPtypeid=@MPtypeid+'%'
        Insert into #TempPTable 
		SELECT	DISTINCT B.BillNumberId
		FROM	(
					SELECT distinct(Billnumberid) FROM SaleBill A,Ptype P 
					INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
				union all
			        SELECT distinct(Billnumberid) FROM RetailBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
			     union all
			        SELECT distinct(Billnumberid) FROM SaleBackBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
			     union all
			        SELECT distinct(Billnumberid) FROM BuyBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
			     union all
			        SELECT distinct(Billnumberid) FROM BuyBackBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
			     union all
			        SELECT distinct(Billnumberid) FROM LoseBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
			     union all
			        SELECT distinct(Billnumberid) FROM OverFlowBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
			     union all
			        SELECT distinct(Billnumberid) FROM DisassembleBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
				 union all 
			        SELECT distinct(Billnumberid) FROM BuyGoodsExchangeBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
				 union all 
			        SELECT distinct(Billnumberid) FROM SaleGoodsExchangeBill A,Ptype P  INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
			     union all
			        SELECT distinct(Billnumberid) FROM AdPriceBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
			     union all
			        SELECT distinct(Billnumberid) FROM MoveBill  A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
			     union all
			        SELECT distinct(Billnumberid) FROM MoveBjBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
			     union all
			        SELECT distinct(Billnumberid) FROM GiveBill A,Ptype P  INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
			     union all
			        SELECT distinct(Billnumberid) FROM GiveMeBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
			     union all
			        SELECT distinct(Billnumberid) FROM CommissionBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
			     union all
			        SELECT distinct(Billnumberid) FROM Advantage A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
			     union all
			        SELECT distinct(Billnumberid) FROM PriceProtectBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM LendBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
			     union all
			        SELECT distinct(Billnumberid) FROM LendBill A,Ptype P  INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
				 union all
			        SELECT distinct(reD.Billnumberid) FROM RepairDeal reD   INNER join (SELECT billnumberid FROM repairEngage A,Ptype p INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId where a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )) reE on reD.engageBillID = reE.billnumberid 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_JIEJIAN A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_SELF A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_GETBACK A,Ptype P  INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_REPLACE A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_SEND A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_SENDBACK A,Ptype P  INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_CALL A,Ptype P  INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_GOTO A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_IN A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_OUT A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM Wx_Bill_MOVE A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM QP_QuickRepairBill_PType A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM IntegralExchangeBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )
				 union all
			        SELECT distinct(Billnumberid) FROM QP_InsuranceBill_PType A,Ptype P  INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all
			        SELECT distinct(Billnumberid) FROM STypeMoveBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )         
			     union all
					SELECT distinct(Billnumberid) FROM Qp_PickingBill A,Ptype P  INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 		        
			     union all
					SELECT distinct(Billnumberid) FROM Qp_PickingBackBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				 union all	
					SELECT distinct(ReceptionBillnumberId) FROM Qp_ReceptionBill_FactUsePType A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid )	        					
				 union all
					SELECT distinct(Billnumberid) FROM Qp_ThreePacketsBill_PType A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 			        					
				 union all
					SELECT distinct(Billnumberid) FROM Qp_SuccorBill_PType A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 		        	
				 union all
					SELECT distinct(Billnumberid) FROM OtherInOutBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 		
				union all
					SELECT distinct(Billnumberid) FROM RetailBackBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 				        					 
				union all
					SELECT distinct(Billnumberid) FROM dbo.PT_Combin_SaleBillDetail A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 		
				union all
					SELECT distinct(Billnumberid) FROM PT_Combin_SaleBackBillDetail A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 
				union all
					SELECT distinct(Billnumberid) FROM dbo.AppraisalBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 				        					 				        					 
				union all
					SELECT distinct(Billnumberid) FROM dbo.AppraisalBackBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 				        					 				        					 
				UNION all
					SELECT distinct(Billnumberid) FROM dbo.SendBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 				        					 				        					 
				UNION all
					SELECT distinct(Billnumberid) FROM dbo.SendBackBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 				        					 				        					 
				UNION ALL
					SELECT distinct(Billnumberid) FROM dbo.PT_Combin_SaleBill A,Ptype P INNER JOIN #GetManPTypeId GP ON P.typeid=GP.TypeId  WHERE a.PtypeID=p.TypeID AND (P.FullName like @Ptypeid  OR P.UserCode Like @Ptypeid ) 				        					 				        					 
		)B
end


--------------------------------------------------------------处理页面---------------------------------------------------------------------------
DECLARE @SQL VARCHAR (MAX)
--合计值不需要后续的处理，所以在这里就可以返回数据了
IF @chrFlag= '3' --显示合计值
BEGIN
	SET @SQL ='	SELECT	SUM(isnull(a.TotalQty,0)) as TotalQty,
							SUM(isnull(a.TotalMoney,0)) as TotalMoney,
							SUM(isnull(a.TotalInMoney,0)) as TotalInMoney,
							SUM(isnull(a.nTotalMoney,0)) as nTotalMoney,
							SUM(isnull(a.nTotalInMoney,0)) as nTotalInMoney,
							SUM(isnull(a.NPreferencemoney,0)) as molingmoney
					FROM billindex(NOLOCK) a 
					LEFT  JOIN Employee E ON a.Checke =E.typeid
					LEFT  JOIN Employee E1 ON a.updatee =E1.typeid
		'

	IF @PtypeIdTemp <>'' or @ptypecategoryid<>'' OR @PtypeIds<>''  -- 输入商品时才用临时表  NO(商品权限为全部时，不需要临时表)
		SELECT @SQL=@SQL+' INNER JOIN #TempPTable tp ON a.billnumberid=tp.billnumberid'

	IF NOT @MDtypeid = '00000'
		SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = a.DTypeId '
		
	SET @SQL=@SQL +@SQL_JOIN+@SQL_WHERE
	
	EXEC(@SQL)
	DROP TABLE #Department,#GetManBTypeId,#GetManDTypeId,#GetManETypeId,#GetManKTypeId,#GetManPTypeId,#GetManSTypeId
				,#PTypeDiscountBillId,#PTypePriceBillId,#PTypeTaxBillId,#TempPTable
	IF @Atypeid<>''
		DROP TABLE #AType
	RETURN
END
--------------------------------------------------------------处理页面---------------------------------------------------------------------------

DECLARE @RowCount INT

--处理排序
DECLARE @orderyWhere VARCHAR(1000)   =''
IF  CHARINDEX('stypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN Stype or_st ON a.stypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'stypeid_','or_st.') 
END
IF  CHARINDEX('dtypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere='	LEFT JOIN Department or_de ON a.dtypeid=or_de.typeID '
	SET @OrderBy= REPLACE(@OrderBy,'dtypeid_','or_de.') 
END
IF  CHARINDEX('efullname',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN employee or_em ON a.etypeid=or_em.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'efullname_','or_em.') 
END
IF  CHARINDEX('btype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN btype or_bt ON a.btypeid=or_bt.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'btype_','or_bt.') 
END
IF  CHARINDEX('dealbtypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN btype or_bt1 ON a.dealbtypeid=or_bt1.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'dealbtypeid_','or_bt1.') 
END
IF  CHARINDEX('atype',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN ac_items or_at ON a.atypeid=or_at.nid  '
	SET @OrderBy= REPLACE(@OrderBy,'atype_','or_at.') 
END	 
IF  CHARINDEX('ktypeid',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON a.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid_','or_st.') 
END	
IF  CHARINDEX('ktypeid1',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON a.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid1_','or_st.') 
END	
IF  CHARINDEX('ktypeid2',@OrderBy)>0
BEGIN
	SET @orderyWhere=' LEFT JOIN stock or_st ON a.ktypeid=or_st.typeID  '
	SET @OrderBy= REPLACE(@OrderBy,'ktypeid2_','or_st.') 
END	

IF  CHARINDEX('comment',@OrderBy)>0
BEGIN  
  SET @OrderBy= REPLACE(@OrderBy,'comment','a.comment') 
END

IF @chrFlag = '1'		--分页查询记录-------------------------------------------------------------------------------------------
	SELECT @SQL ='
		SELECT	a.BillNumberId,
				AC.CId AS currencyid,
				AC.FullName AS currencyname,
				CONVERT(varchar(100), a.billdate,23) as billdate,  
				a.BillCode,
				a.BillType,
				a.redword,
				a.Comment AS Comment,
				a.explain as explain,
				case when a.billtype=57 then 0 else  a.totalqty end as totalqty,
				a.checke,
				E.FullName AS CheckeName,
				case 
					when a.billtype in (17,9,14,126,139) then 0 
					WHEN a.billtype=159 THEN (SELECT sum(J_Total) FROM accountcredence WHERE BillNumberID=a.billnumberid)
					else a.totalmoney 
				end as totalmoney,
				CASE
					WHEN a.BillType = 305 THEN a.packway*a.Rate
					ELSE a.totalinmoney
				END AS totalinmoney,
				case 
					when a.billtype in(17,9,14,126,139) then 0 
					WHEN a.billtype=159 THEN (SELECT sum(NJ_Total) FROM accountcredence WHERE BillNumberID=a.billnumberid)
					else a.NTotalMoney 
				end as _ntotalmoney,
				CASE
					WHEN a.BillType = 305 THEN a.packway
					ELSE a.NTotalInMoney
				END AS _ntotalinmoney,
				a.packway,
				ISNULL(A.ETypeId,'''') AS EfullName,
				CASE
					WHEN A.IfMulAccount = 1 THEN ''-99999''
					ELSE ISNULL(acs.ntypeid,'''') 
				END AS atype,			
				CASE
					WHEN A.IfMulAccount = 1 THEN ''多账户''
					ELSE ISNULL(acs.fullname,'''') 
				END AS aname,				
				ISNULL(a.btypeid,'''') AS btype,
				ISNULL(A.Stypeid,'''') AS Stypeid,
				ISNULL(A.StypeID2,'''') AS StypeID2,	--资金调拨单取出调入机构
				ISNULL(A.Dtypeid,'''') AS Dtypeid,
				ISNULL(A.Ktypeid,'''') AS Ktypeid,
				ISNULL(A.Ktypeid2,'''') AS Ktypeid2,
				a.checktime,
				e1.fullname as updatefullname,
				a.lastupdatetime,
				a.dealbtypeid,
				CASE
						WHEN Ad.IfAudit = 0  THEN ''待 审 核''
						WHEN Ad.IfAudit = 1  THEN ''审核通过''
						WHEN Ad.IfAudit = -1 THEN ''审核不通过''
						ELSE ''无需审核''
				END AS auditedname,
				ISNULL(PR.printcount,'''') AS PrintCount,
				a.IfConfirm,
				a.TransferType,
				a.IsAuto,
				a.ChargeOffTotal,				
				CASE 
				WHEN a.billtype in (4,66) THEN a.NPreferencemoney  END  AS preferencemoney,	
				CASE
				WHEN a.billtype in (4,66,12,46,34,6,161,167,170,305,215,11,45,160,168,170,172,312,181) THEN a.NPreferencemoney  END AS molingmoney,
				a.PosId	
		FROM 	BillIndex(NOLOCK) a
				left join ac_items acs on a.atypeid=acs.nid
				LEFT JOIN Ac_Currency AC ON AC.CId=a.CID
				LEFT JOIN Employee E ON E.TypeId = A.Checke
				LEFT  JOIN Employee E1 ON a.updatee =E1.typeid
				LEFT JOIN AuditingBill Ad ON Ad.BillNumberId = A.BillNumberId AND Ad.BillIndexType = ''2''
				LEFT JOIN #PrintCount PR ON (a.BillNumberId = PR.billnumberid and a.billtype=PR.billtype)
				
		 '
ELSE IF @chrFlag= '2'-- 打印查询所有记录--------------------------------------------------------------------------------------
	SELECT @SQL ='
		SELECT	a.BillNumberId,
				AC.CId AS currencyid,
				AC.FullName AS currencyname,
				CONVERT(varchar(100), a.billdate,23) as billdate, 
				a.BillCode,
				a.BillType,
				a.redword,
				a.etypeid,
				a.Comment AS Comment,
				a.explain as explain,
				case when a.billtype=57 then 0 else a.totalqty end as totalqty,
				a.checke,
				ISNULL(E.fullname,'''') AS CheckeName,
				case 
					when a.billtype in (17,9,14,126,139) then 0 
					WHEN a.billtype=159 THEN (SELECT sum(J_Total) FROM accountcredence WHERE BillNumberID=a.billnumberid)
					else a.totalmoney 
				end as totalmoney,
				CASE
					WHEN a.BillType = 305 THEN a.packway*a.Rate
					ELSE a.totalinmoney
				END AS totalinmoney,
				case 
					when a.billtype in(17,9,14,126,139) then 0 
					WHEN a.billtype=159 THEN (SELECT sum(NJ_Total) FROM accountcredence WHERE BillNumberID=a.billnumberid)
					else a.NTotalMoney 
				end as _ntotalmoney,
				CASE
					WHEN a.BillType = 305 THEN a.packway
					ELSE a.NTotalInMoney
				END AS _ntotalinmoney,
				a.packway,
				ISNULL(A.ETypeId,'''') AS EfullName,
				CASE
					WHEN A.IfMulAccount = 1 THEN ''-99999''
					ELSE ISNULL(acs.ntypeid,'''') 
				END AS atype,
				CASE
					WHEN A.IfMulAccount = 1 THEN ''多账户''
					ELSE ISNULL(acs.fullname,'''') 
				END AS aname,		
				ISNULL(A.BTypeId,'''') AS btype,
				ISNULL(A.Stypeid,'''') AS Stypeid,
				ISNULL(A.StypeID2,'''') AS StypeID2,	--资金调拨单取出调入机构
				ISNULL(A.Dtypeid,'''') AS Dtypeid,
				--ISNULL(A.Ktypeid,'''') AS Ktypeid,
				--ISNULL(A.Ktypeid2,'''') AS Ktypeid2,
				--9.4.1 BUG	63修改
				ISNULL(CASE
					WHEN A.BillType = 188 THEN A.KTypeId2
					ELSE A.KTypeId
				END,'''') AS Ktypeid,
				ISNULL(CASE
					WHEN A.BillType = 160 THEN A.KTypeId2
					ELSE A.ktypeid 
				END,'''') AS Ktypeid1,
				ISNULL(CASE
					WHEN A.BillType = 160 THEN A.KTypeId
					ELSE A.KTypeId2
				END,'''') AS Ktypeid2,				
				CASE
					WHEN Ad.IfAudit = 0  THEN ''待 审 核''
					WHEN Ad.IfAudit = 1  THEN ''审核通过''
					WHEN Ad.IfAudit = -1 THEN ''审核不通过''
					ELSE ''无需审核''
				END AS auditedname,
				a.checktime,
				e1.fullname as updatefullname,
				a.lastupdatetime,
				a.dealbtypeid,
				ISNULL(PR.printcount,'''') AS PrintCount,
				a.IfConfirm,
				a.TransferType,
				a.IsAuto ,
				a.ChargeOffTotal,
				CASE 
				WHEN a.billtype in (4,66) THEN a.NPreferencemoney  END  AS preferencemoney,	
				CASE  
				WHEN a.billtype in (4,66,12,46,34,6,161,167,170,305,215,11,45,160,168,170,172,181,312) THEN a.NPreferencemoney  END AS molingmoney,
				a.posid
		FROM 	BillIndex(NOLOCK) a 
		left join ac_items acs on a.atypeid=acs.nid
		LEFT JOIN Ac_Currency AC ON AC.CId=a.CID
		LEFT  JOIN Employee E ON a.Checke =E.typeid
		LEFT  JOIN Employee E1 ON a.updatee =E1.typeid
		LEFT JOIN AuditingBill Ad ON Ad.BillNumberId = A.BillNumberId AND Ad.BillIndexType = ''2''
		LEFT JOIN #PrintCount PR ON (a.BillNumberId = PR.billnumberid and a.billtype=PR.billtype) '

IF @PtypeIdTemp <>'' or @ptypecategoryid<>''  OR @PtypeIds<>''  -- 输入商品时才用临时表  NO(商品权限为全部时，不需要临时表)
	SELECT @SQL=@SQL+' INNER JOIN #TempPTable tp ON a.billnumberid=tp.billnumberid'

IF NOT @MDtypeid = '00000'
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = a.DTypeId '
IF @chrFlag='1'
	SET @SQL += @orderyWhere
SET @SQL=@SQL +@SQL_JOIN+@SQL_WHERE

--统计打印记录
CREATE TABLE #PrintCount(printcount INT, billnumberid NUMERIC(10,0),billtype NUMERIC(10,0))
CREATE NONCLUSTERED INDEX  Ncix_printcount on  #PrintCount(printcount,billnumberid,billtype)   

IF @showprintcount = '1'
BEGIN
	DECLARE	@printsql VARCHAR(5000)
	SET @printsql = '
	INSERT INTO #PrintCount(printcount,billnumberid,billtype)
	SELECT	SUM(PrintCount) printcount,p.billnumberid,p.BillType 
	FROM	PrintRecord p
	INNER JOIN dbo.BillIndex(NOLOCK) a ON a.BillNumberId = p.BillNumberId AND a.BillType = p.BillType
	LEFT  JOIN Employee E ON a.Checke =E.typeid
	LEFT  JOIN Employee E1 ON a.updatee =E1.typeid '+@SQL_WHERE +' AND	p.billtype not in (300,301) 
	GROUP BY p.billnumberid,p.BillType '

	EXEC(@printsql)
END	

-- 排序
IF RTRIM(@OrderBy)=''
	SET @OrderBy = ' Order By a.billdate desc,a.billcode desc'
ELSE
	SET @OrderBy = ' Order By ' + @OrderBy

	
IF @UserDeRowCount = 0
	SET @UserDeRowCount = 14

DECLARE @PageNum int
DECLARE @PageBegin int
DECLARE @PageEnd int

IF @chrFlag = '1'	--分页查询
	BEGIN
		CREATE TABLE #Result
		(
			BillNumberId		numeric(18,0),
			accrencyid			INT,
			currencyname		VARCHAR(200),
			BillDate			varchar(23),
			BillCode			VARCHAR(300),
			BillType			int,
			BType				VARCHAR(200),
			TotalQty			 NUMERIC(24, 10) ,
			TotalMoney			 NUMERIC(24, 10) ,
			TotalInMoney		 NUMERIC(24, 10) ,
			_ntotalmoney		 NUMERIC(24, 10) ,
			_ntotalinmoney		 NUMERIC(24, 10) ,
			PackWay				VARCHAR(200),
			checke			varchar(50),
			CheckeName		VARCHAR(200),
			Comment				VARCHAR(2000),
			Explain				VARCHAR(2000),
			TotalNum			int,
			EFullName			VARCHAR(200),
			atype			VARCHAR(200),
			aname			varchar(200),
			IsPass				int,			-- 是否有过账的权限	0.没有 1.有
			IsAudit				int	,			-- 是否有审核	0.待审核  1.审核通过 -1.审核不通过 2.无需审核 3.不满足条件无需提交审核 4.满足条件但是没有提交审核
		    stypeid  			VARCHAR(100),
		    stypeid2  			VARCHAR(100),	--资金调拨单 调入机构
		    dtypeid  			VARCHAR(100),
		    ktypeid  			VARCHAR(100),
		    ktypeid1  			VARCHAR(100),
		    ktypeid2  			VARCHAR(100),
		    CheckTime			DATETIME,			--制单时间
		    updatefullname				VARCHAR(200),		--修改人
		    LastUpdateTime		DATETIME,			--修改时间
		    dealbtypeid			VARCHAR(50),
		    auditedname		VARCHAR(200),
		    PRINTCOUNT		INT,
		    sid				NUMERIC(10, 0),
		    IfConfirm		INT,					--是否入账
			TransferType	INT,					--资金调拨单 业务类型
			IsAuto			INT	,					--IaAuto = 1 自动的，手动0
			ChargeOffTotal	NUMERIC(24, 10),
			preferencemoney NUMERIC(24, 10),        --优惠金额
			molingmoney NUMERIC(24,10), --抹零金额
			posid			INT			--pos名称
	)
		CREATE CLUSTERED INDEX CIX_resultbnid ON #Result(BillNumberId,BillType)
	
		CREATE TABLE #temp1
		(
			BillNumberId 	numeric(10,0),
			accrencyid		INT,
			currencyname	VARCHAR(200),
			Billdate 		varchar(23), 
			BillCode 		VARCHAR(200),
			BillType 		int,
			redword  		int,
			Comment 		VARCHAR(2000),
			explain 		VARCHAR(2000),
			totalqty 		 NUMERIC(24, 10) ,
			checke			VARCHAR(50),
			CheckeName   VARCHAR(200),
			totalmoney 		 NUMERIC(24, 10) ,
			totalinmoney 	 NUMERIC(24, 10) ,
			_ntotalmoney 	 NUMERIC(24, 10) ,
			_ntotalinmoney 	 NUMERIC(24, 10) ,
			packway 		VARCHAR(20),
			etype 			VARCHAR(100), 
			atype 			VARCHAR(100),		
			aname			VARCHAR(200),
			btype  			VARCHAR(100),
			stypeid  		VARCHAR(100),
			StypeID2 		VARCHAR(100),
			dtypeid  		VARCHAR(100),
			ktypeid  		VARCHAR(100),
			ktypeid2  		VARCHAR(100),
			CheckTime			DATETIME,			--制单时间
			updatefullname		VARCHAR(200),		--修改人
			LastUpdateTime		DATETIME,			--修改时间'
			dealbtypeid			VARCHAR(50),
			auditedname		VARCHAR(200),
			PRINTCOUNT		INT,
			IfConfirm		INT,					--是否入账
			TransferType	INT,					--资金调拨单 业务类型
			IsAuto			INT,					--IaAuto = 1 自动的，手动0
			ChargeOffTotal  NUMERIC(24, 10) ,
			preferencemoney  NUMERIC(24, 10) ,   --优惠金额
			molingmoney   NUMERIC(24,10),
			[sid] [numeric](10, 0) IDENTITY (1, 1) NOT NULL,
			posid		INT						--pos名称
		)
		CREATE CLUSTERED INDEX CIX_TEMP1sid ON #temp1([sid])
		
		SET @SQL ='	INSERT INTO #temp1 ' +@SQL + @OrderBy
		
		--PRINT(@SQL) /*最终业务SQL,出问题一般看这里*/	 
		EXEC(@SQL) 			
			
		--9.4客户希望和9.2一样，排序后页面保持不动
		--超出最后一页，则自动跳转到最后一页
		SET @RowCount = @@ROWCOUNT
		IF(@PageNo > CEILING(CAST(@RowCount AS NUMERIC(18,0)) / CAST(@UserDeRowCount AS NUMERIC(18,0))))
			SET @PageNo = CEILING(CAST(@RowCount AS NUMERIC(18,0)) / CAST(@UserDeRowCount AS NUMERIC(18,0)))
		
		SET @PageNum = @PageNo * @UserDeRowCount
		SET @PageBegin = (@PageNo - 1) * @UserDeRowCount + 1
		SET @PageEnd = (@PageNo) * @UserDeRowCount
		-------------------------------------------
	 
		SET @SQL = '
				INSERT INTO #Result
				SELECT 	a.BillNumberId,
						a.accrencyid,
						a.currencyname,
						a.BillDate,
						a.BillCode,
						a.BillType,
						a.BType,
						a.TotalQty,
						a.TotalMoney,
						a.TotalInMoney,
						a._ntotalmoney,
						a._ntotalinmoney,
						a.PackWay,
						a.checke,
						a.CheckeName,
						a.Comment,
						a.Explain,
						'+Convert(VARCHAR(100),@RowCount)+' as TotalNum ,
						a.etype,
						a.atype,
						a.aname,
						0 AS IsPass,
						2 AS IsAudit,
						a.stypeid,
						a.stypeid2,
						a.dtypeid,
						CASE
							WHEN A.BillType = 188 THEN a.KTypeId2
							ELSE A.KTypeId
						END AS ktypeid,
						CASE
							WHEN a.BillType = 160 THEN a.KTypeId2
							ELSE a.ktypeid 
						END AS ktypeid1,
						CASE
							WHEN a.BillType = 160 THEN a.KTypeId
							ELSE a.KTypeId2
						END AS ktypeid2,
						a.checktime,
						A.updatefullname,
						a.lastupdatetime,
						a.dealbtypeid,
						A.auditedname,
						A.PRINTCOUNT,
						a.sid,
						a.IfConfirm,
						a.TransferType,
						a.IsAuto,
						ChargeOffTotal,
						a.preferencemoney,
						a.molingmoney,
						a.posid
				FROM 	#temp1 a
				WHERE 	A.sid >= '+CAST(@PageBegin AS VARCHAR(20)) +'
						AND A.sid <= '+CAST(@PageEnd AS VARCHAR(20))+'
				ORDER BY A.SID'

				
		    --PRINT @SQL
			EXEC(@SQL)		

			DECLARE @nBillId	numeric(18,0),
					@nBillType	int,
					@IsPass		int,
					@nPass		int,
					@IsAudit	INT,
					@loopsid	INT,
					@maxsid		INT
					
			SELECT @loopsid = MIN(sid) FROM #Result
			SELECT @maxsid = MAX(sid) FROM #Result

			--判断过账权限
			EXEC @nPass = GP_CheckLimit @OperatorID,119
			
			WHILE @loopsid <= @maxsid
			BEGIN
				SELECT @nBillId = BillNumberId,@nBillType = BillType FROM #Result WHERE [sid] = @loopsid
				
				IF @nPass = 1 	--没有
					SET @IsPass = 0
				ELSE
					EXEC @IsPass = Gp_CheckLimitBillType @OperatorID,0,@nBillType

				--检查审核
				EXEC @IsAudit = Gp_CheckBillAuditingState @nBillId,@nBillType

				--修改状态
				UPDATE #Result SET IsPass = @IsPass,IsAudit = @IsAudit WHERE BillNumberId = @nBillId
				
				SET @loopsid += 1
			END 
			
			/*
			DECLARE bCursor CURSOR FOR			
				SELECT BillNumberId,BillType FROM #Result
			OPEN bCursor
			FETCH NEXT FROM bCursor INTO @nBillId,@nBillType
			WHILE @@FETCH_STATUS = 0
				BEGIN
					IF @nPass = 1 	--没有
						SET @IsPass = 0
					ELSE
						EXEC @IsPass = Gp_CheckLimitBillType @OperatorID,0,@nBillType
	
					--检查审核
					EXEC @IsAudit = Gp_CheckBillAuditingState @nBillId,@nBillType
	
					--修改状态
					UPDATE #Result SET IsPass = @IsPass,IsAudit = @IsAudit WHERE BillNumberId = @nBillId
	
					FETCH NEXT FROM bCursor INTO @nBillId,@nBillType
				END
			CLOSE bCursor
			DEALLOCATE bCursor
		*/
			SET @SQL ='	
			SELECT	R.*,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
					SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,
					SysDiy18_head,
					SysDiy19_head,
					SysDiy20_head,
					SysDiy21_head,
					SysDiy22_head,
					SysDiy23_head,
					SysDiy24_head,
					SysDiy25_head,
					SysDiy26_head,
					SysDiy27_head,
					SysDiy28_head,
					SysDiy29_head,
					SysDiy30_head,
					SysDiy31_head,
					SysDiy32_head,
					SysDiy33_head,
					SysDiy34_head,
					SysDiy35_head,
					SysDiy36_head,
					SysDiy37_head,
					SysDiy38_head,
					SysDiy39_head,
					SysDiy40_head
			FROM	#Result R
			left join Custom_BillIndex csindex on r.billnumberid=csindex.BillId and r.billtype=csindex.billtype
			order by R.SID
			'  
			--PRINT(@SQL) /*最终业务SQL,出问题一般看这里*/		

			EXEC(@SQL)	
		
			DROP TABLE #Result,#temp1
	END
ELSE	--打印
	BEGIN
		declare @sqlresult varchar(max)
		SET @RowCount = @@ROWCOUNT
		

	 
		SELECT @sqlresult='SELECT a.* ,RANK()  over ( '+@OrderBy+')  sid  INTO #Result from (' + @SQL + ') a ' + @orderywhere + @OrderBy+ '
		
		
		SELECT	a.*, 
				SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head,
				SysDiy33_head,
				SysDiy34_head,
				SysDiy35_head,
				SysDiy36_head,
				SysDiy37_head,
				SysDiy38_head,
				SysDiy39_head,
				SysDiy40_head,
				'+Convert(VARCHAR(100),@RowCount)+' as TotalNum  
		FROM #Result a 
		left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
		order by a.sid
		
		DROP TABLE #Result  ' 
		
		--print(@sqlresult)
		EXEC(@sqlresult)		
	END

DROP TABLE #TempPTable,#GetManETypeId,#GetManBTypeId,#GetManKTypeId,#GetManPTypeId,#GetManSTypeId,
     #GetManDTypeId,#Department,#PTypePriceBillId,#PTypeDiscountBillId,#PTypeTaxBillId,#dealBTypeId

IF @Atypeid<>''
	DROP TABLE #AType



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryDtypeSalePlanExecLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryDtypeSalePlanExecLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-08-02
--	描述：部门销售计划执行汇总表
---------------------------------------------
CREATE PROCEDURE Web_QueryDtypeSalePlanExecLine
( 
	@OperatorID	VARCHAR(MAX),
	@parid		VARCHAR(MAX)='',
	@dtypeid	VARCHAR(MAX),
	@startdate	VARCHAR(MAX),
	@enddate	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

--------	权限检查 - Start	--------
IF @OperatorID IS NULL RETURN 1	-- @intOperatorID由调用存储过程中传入的职员参数
DECLARE @intRe INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @intRe=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @intRe <> 0 RETURN @intRe
--------	权限检查 - END		--------

CREATE TABLE #Ptype (TypeID VARCHAR(200))
CREATE TABLE #Btype (TypeID VARCHAR(50))
CREATE TABLE #Etype (TypeID VARCHAR(50))
CREATE TABLE #Ktype (TypeID VARCHAR(50))
CREATE TABLE #Dtype (TypeID VARCHAR(50))
CREATE TABLE #Stype (TypeID VARCHAR(50))
CREATE TABLE #MainType (
	TypeID VARCHAR(200),
	usercode VARCHAR(200),
	fullname VARCHAR(200),
	sonnum INT,deleted INT
)

INSERT INTO #Ptype SELECT typeid FROM F_GetManDetailPType(@OperatorID)

-- 限制条件 往来单位
INSERT INTO #Btype SELECT typeid FROM F_GetManDetailBType(@OperatorID)

--限制条件 经手人
INSERT INTO #Etype SELECT typeid FROM F_GetManDetailEType(@OperatorID)

INSERT INTO #Dtype SELECT typeid FROM F_GetManDetailDType(@OperatorID)

--限制条件 分支机构
INSERT INTO #Stype SELECT typeid FROM F_GetManDetailSType(@OperatorID)

DECLARE @sonnum INT 
SET @sonnum =0

DECLARE
	@strTemp	VARCHAR(MAX)
DECLARE @BillType VARCHAR(MAX)
SET @BillType='11,141,45,305,160'

CREATE TABLE [dbo].[#Billtype] (
	[Billtype] VARCHAR(200)
)
INSERT INTO #Billtype SELECT a AS Billtype FROM dbo.f_split(@BillType,',')

CREATE TABLE #BillIndex(
	BillNumberId NUMERIC(10, 0) ,
	RedWord  INT ,
	Billdate VARCHAR(MAX),
	Billtype VARCHAR(max),
	BtypeId  VARCHAR (50),
	EtypeId  VARCHAR (50),
	KtypeId  VARCHAR (50),
	KtypeId2 VARCHAR (50),
	preferencemoney  NUMERIC(24, 10) ,
    bflag bit,
    ifcheck VARCHAR(max)
)
	SELECT @strTemp=' 
	INSERT INTO #BillIndex(BillnumberID,billdate,billtype,RedWord,BtypeID,EtypeID,ifcheck) 
	SELECT distinct BillnumberID,billdate,b.billtype,RedWord,BtypeID,EtypeID,ifcheck 


	FROM BillIndex b
	INNER JOIN #Billtype BILL ON b.billtype=BILL.billtype '

	IF @MBTypeID=-99999 OR @MBTypeID2=-99999
	SET @strTemp=@strTemp+' INNER JOIN #Btype bt ON b.btypeid=bt.typeid '

	IF @METypeID=-99999 
	SET @strTemp=@strTemp+' INNER JOIN #Etype e  ON b.etypeid=e.typeid '

	IF @MDTypeID=-99999
	SET @strTemp=@strTemp+' INNER JOIN #Dtype d  ON  b.DtypeID=d.typeid '

	IF NOT(@dtypeid='' AND @MStypeid='00000')
	SET @strTemp=@strTemp+' INNER JOIN #Stype s  ON  b.stypeID=s.typeid '

	SET @strTemp=@strTemp+' WHERE b.RedWord=0 AND b.Draft =0  AND b.BillDate>='+CHAR(39)+@startdate+CHAR(39)+' AND b.BillDate<='+CHAR(39)+@endDate+CHAR(39)+ '  ' 
	EXEC(@strTemp)
CREATE TABLE #InoutStockTable(
	BillNumberId NUMERIC(10, 0) ,
	RedWord INT ,
	BillDate datetime,
	BillType NUMERIC(4,0),
	StypeId	VARCHAR(MAX),
	DtypeId	VARCHAR(MAX),
	PtypeId VARCHAR (50),
	BtypeId VARCHAR (50),
	EtypeId VARCHAR (50),
	KtypeId VARCHAR (50),
	Qty  NUMERIC(24, 10) ,
	Price  NUMERIC(24, 10) ,
	Total  NUMERIC(24, 10) ,
	CostTotal  NUMERIC(24, 10) ,
	Tax  NUMERIC(24, 10) ,
	Discount  NUMERIC(24, 10) ,
	SaleTotal  NUMERIC(24, 10) ,
	TaxTotal  NUMERIC(24, 10) 
)

SELECT @strTemp='
INSERT INTO #InoutStockTable(BillnumberID,RedWord,BillDate,BillType,StypeID,DtypeId,PtypeID,BtypeID,EtypeID,KtypeID,Qty,Price,Total,CostTotal,Tax,Discount,SaleTotal,TaxTotal)
SELECT a.BillnumberID,
		b.RedWord,
		a.BillDate,
		a.BillType,
		a.StypeID,
		a.DtypeId,
		a.PtypeID,
		a.BtypeID,
		a.EtypeID,
		a.KtypeID,
		-a.Qty,
		Price,
		-Convert( NUMERIC(24, 10) ,a.Total),
		-Convert( NUMERIC(24, 10) ,a.CostTotal),
		a.Tax,a.Discount,
		-Convert( NUMERIC(24, 10) ,a.SaleTotal),
		-Convert( NUMERIC(24, 10) ,a.TaxTotal)
FROM #Billindex b
INNER JOIN InoutStockTable a
ON a.BillnumberID=b.BillnumberID
'
IF @MPTypeID=-99999 SET @strTemp=@strTemp+'	INNER JOIN #Stype s ON a.stypeid=s.typeid '+CHAR(13)

EXEC(@strTemp)
IF @parid=''
	SET @parid='00000'

SELECT @sonnum = sonnum FROM SType WHERE Typeid =@parid
IF @sonnum =0 	
	INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
	SELECT d.typeid,d.usercode,d.fullname,d.sonnum,d.deleted FROM Department d
	,(SELECT * FROM F_BaseGetManSType(@OperatorID) WHERE typeid=@parid) a WHERE d.typeid=a.typeid
ELSE
	IF @dtypeid=''
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT d.typeid,d.usercode,d.fullname,d.sonnum,d.deleted FROM Department d
		,(SELECT * FROM F_BaseGetManDType(@OperatorID) WHERE parid=case  when @parid='' then '00000' else @parid end) a WHERE d.typeid=a.typeid
	ELSE
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted) 
		SELECT d.typeid,d.usercode,d.fullname,d.sonnum,d.deleted FROM Department d
		,(SELECT * FROM F_BaseGetManDType(@OperatorID) WHERE parid=case  when @parid='' then '00000' else @parid end AND  typeid LIKE @dtypeid+'%') a WHERE d.typeid=a.typeid

DECLARE @SQL VARCHAR(MAX)
SET @SQL ='SELECT  
				B.dtypeid AS dtypeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				a.deleted,
				SUM(ISNULL(B.QTY,0)) AS qty,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  ISNULL(SUM(ISNULL(b.total,0)),0)/SUM(ISNULL(b.qty,0)) END) AS Price,
				ISNULL(SUM(ISNULL(b.saletotal,0)),0) AS discounttotal,
				ISNULL(SUM(ISNULL(b.total,0)),0) AS Total,
				ISNULL(SUM(ISNULL(b.taxtotal,0)),0) AS taxTotal,
				ISNULL(SUM(ISNULL(b.taxtotal,0)),0)-ISNULL(SUM(ISNULL(b.total,0)),0) AS taxge,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.qty,0)),0)=0 THEN 0 ELSE  ISNULL(SUM(ISNULL(b.CostTotal,0)),0)/SUM(ISNULL(b.qty,0)) END) AS CostPrice,
				ISNULL(SUM(ISNULL(b.CostTotal,0)),0) AS CostTotal,
				ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0) AS MaoLi,
				Convert( NUMERIC(24, 10) ,CASE WHEN ISNULL(SUM(ISNULL(b.Total,0)),0)=0 THEN 0 ELSE (ISNULL(SUM(ISNULL(b.Total,0)),0)-ISNULL(SUM(ISNULL(b.CostTotal,0)),0) )/SUM(ISNULL(b.Total,0))*100 end) AS maoliper
		   FROM #MainType a 
		   INNER JOIN #InoutStockTable b   
		   ON a.TypeID = b.dtypeid
		   GROUP BY 
				B.dtypeid,
				a.usercode,
				a.fullname,
				a.sonnum,
				a.deleted
			ORDER BY a.UserCode '
--PRINT @SQL
EXEC(@SQL)

	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryDtypeSalePlanTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_QueryDtypeSalePlanTotal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-09-16
--	描述：分支机构销售计划表
---------------------------------------------
CREATE PROCEDURE WEB_QueryDtypeSalePlanTotal
(
	@fullname	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SELECT	dp.ID AS planid,
		TotalID AS timeid,
		ds.StypeID AS stypeid,
		st.FullName AS tfullname,
		dp.FullName pfullname,
		MoneyUnit AS moneyunit,
		AllPlanValue AS AllPlanValue,
		AllRatingValue AS AllRatingValue,
		dp.Comment AS comment,
		CASE dp.IfUse 
			WHEN 1 THEN '启用'
			WHEN 2 THEN '未启用'
			ELSE '停用' 
		END AS ifused
FROM	DtypeSaleAllPlan dp
INNER JOIN SaleTimeTotal st ON dp.TotalID=st.ID 
INNER JOIN DtypeSaleplan ds ON ds.DplanID=dp.ID
WHERE 1=1
GROUP BY	dp.ID,
			TotalID,
			ds.StypeID,
			st.FullName,
			dp.FullName,
			MoneyUnit,
			AllPlanValue,
			AllRatingValue,
			dp.Comment,
			dp.IfUse
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_QueryDtypeSalePlanTree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_QueryDtypeSalePlanTree]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-7-15
--	描述：部门销售计划树形显示
---------------------------------------------
CREATE PROCEDURE WEB_QueryDtypeSalePlanTree
( 
	@dtypeid	VARCHAR(MAX),
	@timeid		VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON

SELECT	st.FullName as planfullname,
		d.FullName AS dfullname,
		Dp.ID	as planid,
		st.ID	as timeid,
		Dp.StypeID as stypeid,
		DP.DtypeID AS dtypeid,
		da.IfUse as ifuse
FROM DtypeSaleAllPlan da
INNER JOIN DtypeSaleplan Dp ON  da.ID=Dp.DplanID
INNER JOIN SaleTimeTotal st ON da.TotalID=st.ID 
INNER JOIN Department D ON D.TypeId=DP.DtypeID
WHERE DP.DtypeID IN (select *from f_split(@dtypeid,',')) 
AND ST.ID=@timeid AND da.IfAudit='1'

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryEIniCommission]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryEIniCommission]
GO













/*
	作者：谢吉康
	日期：2003-8-29
	描述：根据职员的参数来计算期初的相关信息
	实例：Web_QueryEIniCommission '00001','W','00000','00000','00001'
*/
/*
	修改：舒珊
	日期：2016-5-27
	描述：添加类别筛选
*/
CREATE     PROCEDURE Web_QueryEIniCommission
(
	@OperatorID 	VARCHAR(50),			--职员的ID
	@Type			VARCHAR(10),			--查询的类型
	@PTypeID		VARCHAR(50),			--商品的ID
	@BTypeID		VARCHAR(50),			--客户的ID
	@ETypeID		VARCHAR(50),			--职员的ID
	@stypeid        VARCHAR(50)='00001',	--分支机构的ID
	@PFullName 		VARCHAR(256)	OUTPUT,	--输出商品的名称		【预留字段】
	@BFullName 		VARCHAR(256)	OUTPUT,	--输出往来单位的名称	【预留字段】
	@EFullName 		VARCHAR(256)	OUTPUT,	--输出职员的名称
	@Qty			 NUMERIC(24, 10) 	OUTPUT,	--输出的数量
	@nqty            NUMERIC(24, 10)    OUTPUT,  --输出的浮动数量
	@Total			 NUMERIC(24, 10) 	OUTPUT,	--输出的结算金额
	@CostTotal		 NUMERIC(24, 10) 	OUTPUT,	--输出的成本金额
	@ptypecategoryid    VARCHAR(MAX )     --商品类别ID	
	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

CREATE TABLE #PType (TypeID varchar(50))
CREATE TABLE #Btype (TypeID varchar(50))
CREATE TABLE #Stype (TypeID varchar(50))


IF @PTypeID='' OR @PTypeID ='00000'
	INSERT INTO #Ptype(typeid) select typeid from F_LinePC(@OperatorID,@ptypecategoryid)
ELSE
	INSERT INTO #Ptype(typeid)  select a.typeid from F_ManPTypeInCategoryID ( @OperatorID,@PTypeID,@ptypecategoryid) a, (select * from  dbo.f_split(@PtypeID,',')) b where left(a.typeid,len(b.a))=b.a

IF @BtypeID='' OR @BtypeID ='00000'
	INSERT INTO #Btype(typeid)  select a.typeid from F_GetManDetailBType(@OperatorID) a
ELSE
	INSERT INTO #Btype(typeid)  select a.typeid from F_GetManDetailBType(@OperatorID) a, (select * from  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a

INSERT INTO #stype SELECT TypeId FROM  F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)  

SELECT @PFullName = FullName FROM Ptype WHERE Deleted = 0 AND TypeID = @PTypeID  	--输出商品的名称	【预留字段】
SELECT @BFullName = FullName FROM Btype WHERE Deleted = 0 AND TypeID = @BTypeID  	--输出往来的名称	【预留字段】
SELECT @EFullName = FullName FROM Employee WHERE Deleted = 0 AND TypeID = @ETypeID  --输出职员的名称

DECLARE @SQL VARCHAR(8000)			--SQL字符
SET @SQL = ''

IF @Type = 'W'		--委托职员期初查询
	BEGIN
		SELECT  @Qty = 	ISNULL(SUM(Convert( NUMERIC(24, 10) ,i.Qty)),0),
		         @nQty = 	ISNULL(SUM(Convert( NUMERIC(24, 10) ,a.nQty)),0), 
				@Total =	ISNULL(SUM(Convert( NUMERIC(24, 10) ,i.Total)),0),
				@CostTotal	=	ISNULL(SUM(Convert( NUMERIC(24, 10) ,i.CostTotal)),0)
		FROM 	(SELECT SUM(qty)qty,SUM(total)total,SUM(costtotal)costtotal,Ptypeid,Btypeid,Stypeid,Type FROM  IniCommissionStock GROUP BY Ptypeid,Btypeid,Stypeid,Type) I 
		INNER JOIN  (SELECT Ptypeid,Btypeid,Stypeid, SUM(qty) AS qty,SUM(nqty)AS nqty FROM    IniCommissionStock_Qty GROUP BY Ptypeid,Btypeid,Stypeid) a ON a.ptypeid=i.ptypeid AND a.Btypeid=i.Btypeid AND i.Stypeid=a.Stypeid
		INNER JOIN #Ptype P ON I.Ptypeid=P.TypeID 
		INNER JOIN #Btype B ON I.Btypeid=B.TypeID 
		INNER JOIN #Stype  S ON I.Stypeid=S.TypeID 
		WHERE 	i.Type = 140 
		
	END
ELSE				--受托职员期初查询
	BEGIN
		SELECT	@Qty = 	ISNULL(SUM(Convert( NUMERIC(24, 10) ,i.Qty)),0),
		  @nQty = 	ISNULL(SUM(Convert( NUMERIC(24, 10) ,a.nQty)),0), 
				@Total =	ISNULL(SUM(Convert( NUMERIC(24, 10) ,i.Total)),0),
				@CostTotal =	ISNULL(SUM(Convert( NUMERIC(24, 10) ,i.CostTotal)),0)
		FROM 	(SELECT SUM(qty)qty,SUM(total)total,SUM(costtotal)costtotal,Ptypeid,Btypeid,Stypeid,Type FROM  IniCommissionStock GROUP BY Ptypeid,Btypeid,Stypeid,Type) I INNER JOIN (SELECT Ptypeid,Btypeid,Stypeid, SUM(qty) AS qty,SUM(nqty)AS nqty FROM    IniCommissionStock_Qty GROUP BY Ptypeid,Btypeid,Stypeid) a ON a.ptypeid=i.ptypeid AND a.Btypeid=i.Btypeid AND i.Stypeid=a.Stypeid
		INNER JOIN #Ptype P ON I.Ptypeid=P.TypeID
		INNER JOIN #Btype B ON I.Btypeid=B.TypeID 
		INNER JOIN #Stype  S ON I.Stypeid=S.TypeID 
		WHERE 	i.Type = 144 
	END
PRINT @sql
exec(@SQL)
SELECT * FROM #Btype	
SELECT * FROM #Stype

DROP TABLE #Ptype
DROP TABLE #Btype
DROP TABLE #Stype
RETURN 0















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryEmployeeGetDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryEmployeeGetDetail]
GO







/*
	作者：谢吉康
	日期：2005-2-23
	描述：职员的应收对帐查询
*/
CREATE  PROCEDURE Web_QueryEmployeeGetDetail
(
	@OperatorId		varchar(100),			--操作员的ID
	@ETypeId		varchar(100),			--职员ID
	@StartDate		varchar(12),			--开始日期
	@EndDate		varchar(12),			--截至日期
	@ShowRedWord	int,					--是否显示红冲单据  1.显示红冲单据   0.不显示红冲单据
	@SortField		varchar(100),			--排序字段
	@SortType		varchar(10)				--排序方式	ASC 升序   DESC 降序
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL		varchar(8000)	--SQL字符串
SET @sql='
		--筛选ListTable的结果集
		SELECT	BillNumberId,
				ETypeId,
				ISNULL(SUM(
							CASE 
								WHEN ATypeId = ''0000100005'' THEN ISNULL(Total,0)
								ELSE -1*ISNULL(Total,0)
							END
		  		),0) AS Total
		INTO 	#ListTable
		FROM	ListTable
		WHERE	(ATypeId = ''0000100005'' OR ATypeId=''0000200001'') '
		
		--是否显示红冲
		IF @showRedWord = 0
			SET @SQL = @SQL + ' AND Audited = 1	'
		
		SET @SQL = @SQL + '		
				AND BillDate >= '+char(39)+@StartDate+char(39)+'
				AND BillDate <= '+char(39)+@EndDate+char(39)+'
				AND ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
				AND ETypeId LIKE '+char(39)+ @MEtypeid+'%'+char(39)+'
		GROUP BY
				BillNumberId,
				ETypeId


		SELECT	Bil.BillNumberID,
				Bil.Id,
				Bil.ETypeId,
				Bil.BillDate,
				Bil.BillCode,
				FullName = (SELECT FullName FROM BType WHERE TypeId = Bil.BTypeId AND Deleted = 0),					
				Bil.BillType,
				Bil.RedWord,					
				Bil.Comment,
				CASE 
					WHEN ISNULL(L.Total,0)>0 THEN ISNULL(L.Total,0)
					ELSE 0
				END AS ArTotal,
				CASE 
					WHEN ISNULL(L.Total,0)<0 THEN -1*ISNULL(L.Total,0)
					ELSE 0
				END AS ApTotal
		FROM 	BillIndex  Bil,
				#ListTable L
		WHERE	Bil.BillNumberId = L.BillNumberId
				AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
				AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
				AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
				AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'								
				AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+' OR ISNULL(Bil.BTypeId,'''')='''')
				AND (Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR Bil.KTypeId2 LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR ISNULL(Bil.KTypeId,'''')='''' OR ISNULL(Bil.KTypeId2,'''')='''')
				AND Bil.IfCheck = ''t'''

		IF @showRedWord = 0
			SELECT @SQL = @SQL + ' AND Bil.RedWord = 0'

--排序
SET @SQL = @SQL + ' ORDER BY '+@SortField+' '+@SortType

SELECT @SQL = @SQL + ' 	--删除临时表					
						DROP TABLE #ListTable'

--PRINT(@SQL)
EXEC(@SQL)















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryEmployeeGetLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryEmployeeGetLine]
GO












/*
	作者：谢吉康
	日期：2005-02-22
	描述：职员应收查询数型表
*/
CREATE PROCEDURE Web_QueryEmployeeGetLine
(
	@OperatorId		varchar(8000),		--操作员Id
	@ETypeId		varchar(50),		--职员的Id
	@UserCode		varchar(200),		--职员编号
	@FullName		varchar(200),		--职员名称
	@EndDatePoint	varchar(20),		--截止日期
	@ShowZero		int=0				--是否显示为0	 1.显示   0.不显示				
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 		varchar(8000)

IF @ETypeId = ''
	SET @ETypeId = '00001'

SET @SQL = '
	--筛选ListTable的结果集
	SELECT	L.BillNumberId,
			L.ETypeId,
			ISNULL(SUM(
						CASE 
							WHEN L.ATypeId = ''0000100005'' THEN ISNULL(L.Total,0)
							ELSE -1*ISNULL(L.Total,0)
						END
	  		),0) AS Total
	INTO 	#ListTable
	FROM	ListTable L,
			BillIndex Bil
	WHERE	L.BillNumberId = Bil.BillNumberId
			AND (L.ATypeId = ''0000100005'' OR L.ATypeId=''0000200001'')
			AND L.Audited = 1								
			AND L.BillDate <= '+char(39)+@EndDatePoint+char(39)+'
			AND L.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
			AND L.ETypeId LIKE '+char(39)+ @MEtypeid+'%'+char(39)+'
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+' OR ISNULL(Bil.BTypeId,'''')='''')
			AND (Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR Bil.KTypeId2 LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR ISNULL(Bil.KTypeId,'''')='''' OR ISNULL(Bil.KTypeId2,'''')='''')
	GROUP BY
			L.BillNumberId,
			L.ETypeId

	--组织数据，显示结果集
	SELECT	E.TypeId,		
			E.UserCode,
			E.FullName,
			ISNULL(C.ArApTotal,0) AS LeftMoney
	FROM 	Employee E
	LEFT 	JOIN (
					SELECT	ETypeId,
							araptotal = SUM(Total)
					FROM	#ListTable 										
					GROUP BY ETypeid
				)C ON LEFT(C.ETypeID,LEN(E.TypeId)) = E.TypeID
	WHERE	E.Deleted = 0
			AND E.SonNum = 0
			AND E.UserCode LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+'
			AND E.FullName LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
			AND E.TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
			AND E.TypeId LIKE '+char(39)+@METypeId+'%'+char(39)

	--是否显示应收为0的记录
	IF @ShowZero = 0
		SET @SQL = @SQL + ' AND ISNULL(C.ArApTotal,0) <> 0 '

	SET @SQL = @SQL + ' ORDER BY E.UserCode 


	--删除临时表
	DROP TABLE #ListTable	'

--PRINT(@SQL)
EXEC(@SQL)












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryEmployeeGetList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryEmployeeGetList]
GO






/*
	作者：谢吉康
	日期：2005-02-22
	描述：职员应收查询数型表
*/
CREATE PROCEDURE Web_QueryEmployeeGetList
(
	@OperatorId		varchar(8000),		--操作员Id
	@ETypeId		varchar(50),		--职员的Id
	@EndDatePoint	varchar(20)			--截止日期
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL 		varchar(8000),
		@SonNum 	int

IF @ETypeId = ''
	SET @ETypeId = '00001'

SELECT @SonNum = SonNum FROM Employee WHERE TypeId = @ETypeId AND Deleted = 0

SET @SQL = '
	--筛选ListTable的结果集
	SELECT	L.BillNumberId,
			L.ETypeId,
			ISNULL(SUM(
						CASE 
							WHEN L.ATypeId = ''0000100005'' THEN ISNULL(L.Total,0)
							ELSE -1*ISNULL(L.Total,0)
						END
	  		),0) AS Total
	INTO 	#ListTable			
	FROM	ListTable L,
			BillIndex Bil
	WHERE	L.BillNumberId = Bil.BillNumberId
			AND (L.ATypeId = ''0000100005'' OR L.ATypeId=''0000200001'')
			AND L.Audited = 1								
			AND L.BillDate <= '+char(39)+@EndDatePoint+char(39)+'
			AND L.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
			AND L.ETypeId LIKE '+char(39)+ @MEtypeid+'%'+char(39)+'
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+' OR ISNULL(Bil.BTypeId,'''')='''')
			AND (Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR Bil.KTypeId2 LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR ISNULL(Bil.KTypeId,'''')='''' OR ISNULL(Bil.KTypeId2,'''')='''')
	GROUP BY
			L.BillNumberId,
			L.ETypeId

	--组织数据，显示结果集
	SELECT	E.TypeId,
			E.SonNum,
			E.UserCode,
			E.FullName,
			ISNULL(SUM(C.ArApTotal),0) AS LeftMoney
	FROM 	Employee E
	LEFT 	JOIN (
					SELECT	ETypeId,
							araptotal = SUM(Total)
					FROM	#ListTable 										
					GROUP BY ETypeid
				)C ON LEFT(C.ETypeID,LEN(E.TypeId)) = E.TypeID
	WHERE	E.Deleted = 0 
			AND E.TypeId LIKE '+char(39)+@METypeId+'%'+char(39)

	IF @SonNum = 0 
		SET @SQL = @SQL + ' AND E.TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)
	ELSE
		SET @SQL = @SQL + ' AND E.ParId = '+char(39)+@ETypeId+char(39)

SET @SQL = @SQL + '
	GROUP BY E.TypeId,
			 E.SonNum,
			 E.UserCode,
			 E.FullName
	ORDER BY E.UserCode 


	--删除临时表
	DROP TABLE #ListTable'

--PRINT(@SQL)
EXEC(@SQL)
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryEmployeeListCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryEmployeeListCount]
GO









/*
	检查职员个数
	Web_QueryEmployeeListCount '00001'
*/
CREATE PROCEDURE Web_QueryEmployeeListCount
(
	@strStockList  varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @TypeId 	varchar(200),
	    @FullName	varchar(200)

CREATE TABLE #Result
(
	TypeId		varchar(200),
	SonNum		varchar(20),
	UserCode	varchar(200),
	FullName	varchar(200)
)

DECLARE stockCursor CURSOR FOR
	SELECT * FROM dbo.f_split(@strStockList,',')

OPEN stockCursor

FETCH NEXT FROM stockCursor INTO @TypeId

WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO #Result(TypeId,SonNum,UserCode,FullName) SELECT TypeId,SonNum,UserCode,FullName FROM Employee WHERE Deleted = 0 AND TypeId = @TypeId

		FETCH NEXT FROM stockCursor INTO @TypeId
	END

CLOSE stockCursor
DEALLOCATE stockCursor

SELECT DISTINCT TypeId,SonNum,UserCode,FullName FROM #Result ORDER BY UserCode


DROP TABLE #Result








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryEmployeeSonListCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryEmployeeSonListCount]
GO







/*
	检查职员个数
	Web_QueryEmployeeListCount '00001'
*/
CREATE PROCEDURE Web_QueryEmployeeSonListCount
(
	@strStockList  varchar(8000)
)
--@encode$--
AS
SET NOCOUNT ON


DECLARE @TypeId 	varchar(200),
	    @FullName	varchar(200)

CREATE TABLE #Result
(
	TypeId		varchar(200),
	SonNum		varchar(20),
	FullName	varchar(200)
)

DECLARE stockCursor CURSOR FOR
	SELECT * FROM dbo.f_split(@strStockList,',')

OPEN stockCursor

FETCH NEXT FROM stockCursor INTO @TypeId

WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO #Result(TypeId,SonNum,FullName) SELECT TypeId,SonNum,FullName FROM Employee WHERE Deleted = 0 AND SonNum = 0 AND TypeId LIKE @TypeId + '%'

		FETCH NEXT FROM stockCursor INTO @TypeId
	END

CLOSE stockCursor
DEALLOCATE stockCursor

SELECT DISTINCT TypeId,SonNum,FullName FROM #Result


DROP TABLE #Result






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryEmployeeWldzDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryEmployeeWldzDetail]
GO

/*
	作者：谢吉康
	日期：2005-6-9
	描述：职员往来明细查询
	
	作者：毛欣蓉
	日期：2011-04-07
	描述：职员往来查询正对应收，应付算法调整
	
	日期:2012-06-07
    作者:黄清
    描述:添加币别条件,调整科目
    
    日期:2013-06-05
    作者:鲁大林
    描述:应收查询统计零售退货单、业务类型为变卖的固定资产减少单
		 应付查询统计业务类型为购买的固定资产增加单
	*****固定资产类的新单据只有在系统配置固定资产管理模式为卡片时统计*****
*/
CREATE PROCEDURE Web_QueryEmployeeWldzDetail
(
	@OperatorId		VARCHAR(100),		--操作员ID
	@BTypeId		VARCHAR(100),		--往来单位的Id
	@ETypeId		VARCHAR(MAX),		--当前选择的职员
	@STypeId		VARCHAR(MAX),		--分支机构
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--截至日期
	@ShowRedWord	INT,				--是否显示红冲  1. 0
	@nType			INT,				--1.应收   2.应付
	@Bhys			VARCHAR(MAX),		--包含预收（付）1.包含 0.不包含
	@cid			VARCHAR(10),			--币别
	@EtypeFlag		INT					--0=单据经手人，1=往来单位关联职员
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL		VARCHAR(MAX),
        @SQLYHQ		VARCHAR(MAX),
		@AtypeType	VARCHAR(8000),
		@aratypeID	VARCHAR(50),
		@ysatypeID	VARCHAR(50),
		@apatypeID	VARCHAR(50),
		@yfatypeID	VARCHAR(50)

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'


--往来单位
create table #btype ( typeid VARCHAR(100))
INSERT INTO #btype(typeid) SELECT  A.typeid FROM F_GetAllManagerBaseTypeId(@BtypeID,2,@OperatorID) A

--分支机构
CREATE TABLE #SType(TypeId	VARCHAR(100))
INSERT INTO #SType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	
--部门
CREATE TABLE #DType(TypeId	VARCHAR(100))
INSERT INTO #DType(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)		

--职员(关联往来单位中的职员)
CREATE TABLE #EType(EtypeId	VARCHAR(100), BtypeId VARCHAR(100))
IF @EtypeFlag = 1
BEGIN
	INSERT INTO #EType(EtypeId,BtypeId)
	SELECT f.TypeId,g.typeid
	FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) f,#btype g,btype b
	WHERE f.TypeId=b.etypeid AND g.TypeId = b.typeId
END
ELSE
BEGIN
	INSERT INTO #EType(EtypeId,BtypeId)
	SELECT f.TypeId,''
	FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) f
END

CREATE TABLE #result
(
	billnumberid	INT,
	cid				INT,
	ATYPEID			VARCHAR(50),
	Rate			 NUMERIC(24, 10) ,
	billdate		DATETIME,
	stypeid			VARCHAR(100),
	billcode		VARCHAR(200),
	billtype		INT,
	comment			VARCHAR(1000),
	addTotal		 NUMERIC(24, 10) ,
	naddTotal		 NUMERIC(24, 10) ,
	recTotal		 NUMERIC(24, 10) ,
	nrecTotal		 NUMERIC(24, 10) ,
	redword			INT
)
CREATE TABLE #atypeidlist
(
	NID VARCHAR(50)
)

IF @nType=1 --职员应收
BEGIN
	SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)
	INSERT INTO #atypeidlist (NID) VALUES(@aratypeID)
	IF @bhys='1'
	BEGIN
		SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)+','+CHAR(39)+@ysatypeID+CHAR(39)
		INSERT INTO #atypeidlist (NID) VALUES(@ysatypeID)
	END
	SET @SQL='
	INSERT INTO #result
	(
		billnumberid,
		cid,
		ATYPEID,
		Rate,
		billdate,
		stypeid	,
		billcode,
		billtype,
		comment	,
		addTotal,
		naddTotal,
		recTotal,
		nrecTotal,
		redword
	)
	SELECT	bi.billnumberid,
			l.cid,
			L.ATYPEID,
			bi.Rate,
			bi.billdate,
			L.stypeid,
			bi.billcode,
			bi.billtype,
			bi.comment,
			SUM(CASE  WHEN l.billtype IN(45,11,160,215,405,46) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord IN(0,1) 
						THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,46) AND bi.RedWord IN(0,1) 
						THEN l.Total 
				  WHEN l.billtype=45 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.Total
				 WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.Total
				  WHEN l.BillType in(11,405)  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.Total
				  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND l.BillType NOT IN(45,215,11,160,405,46) AND bi.RedWord=2 
						THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total<0  AND bi.redword IN(0,1)  
						THEN ABS(l.Total) 
				  WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total>0  AND bi.redword=2  
						THEN -l.Total
				  ELSE 0
				END) AS addtotal,
			SUM(CASE  WHEN l.billtype IN(45,215,11,160,405,46) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord IN(0,1) 
						THEN l.nTotal
				  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,46) AND bi.RedWord IN(0,1) 
						THEN l.nTotal 
				  WHEN l.billtype=45 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.nTotal
				WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.nTotal
				  WHEN l.BillType in(11,405) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.nTotal
				  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.nTotal
				  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.nTotal<0 AND l.BillType NOT IN(45,215,11,160,405,46) AND bi.RedWord=2 
						THEN l.nTotal
				  WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal<0  AND bi.redword IN(0,1)  
						THEN ABS(l.nTotal) 
				  WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal>0  AND bi.redword=2  
						THEN -l.nTotal
				  ELSE 0
				END) AS naddtotal,
			SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405,46) AND bi.redword IN(0,1) 
							THEN ABS(l.Total)
					 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND  l.BillType NOT IN(45,215,11,160,405,46) AND bi.redword IN(2) 
							THEN -l.Total 
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total>0 AND bi.redword IN(0,1)  
							THEN l.Total 
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total<0  AND bi.redword=2 
							THEN l.Total
				 ELSE 0
				END) AS rectotal,
			SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.nTotal<0 AND  l.BillType NOT IN(45,215,11,160,405,46) AND bi.redword IN(0,1) 
							THEN ABS(l.nTotal)
					 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.nTotal>0 AND  l.BillType NOT IN(45,215,11,160,405,46) AND bi.redword IN(2) 
							THEN -l.nTotal 
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal>0 AND bi.redword IN(0,1)  
							THEN l.nTotal 
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal<0  AND bi.redword=2 
							THEN l.nTotal
				 ELSE 0
				END) AS nrectotal,
			bi.redword
	FROM	ListTable L '
	
	IF @EtypeFlag = 1
		SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId  AND E.BTypeId = L.BTypeId'
	ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
		SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId'
		
END
ELSE--职员往来应付
BEGIN
	SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)
	INSERT INTO #atypeidlist (NID) VALUES(@apatypeID)
	IF @bhys='1'
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)+','+CHAR(39)+@yfatypeID+CHAR(39)
		INSERT INTO #atypeidlist (NID) VALUES(@yfatypeID)
	END
	SET @SQL='
	INSERT INTO #result
	(
		billnumberid,
		cid,
		ATYPEID,
		Rate,
		billdate,
		stypeid	,
		billcode,
		billtype,
		comment	,
		addTotal,
		naddTotal,
		recTotal,
		nrecTotal,
		redword
	)
	SELECT	bi.billnumberid,
			l.cid,
			L.ATYPEID,
			bi.Rate,
			bi.billdate,
			L.stypeid,
			bi.billcode,
			bi.billtype,
			bi.comment,
			SUM(CASE  WHEN L.billtype IN(6,34,161,404) AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword IN (0,1) 
							THEN L.Total
				  WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.Total>0 AND l.BillType NOT IN(6,34,161,404) AND bi.redword IN (0,1) 
						THEN L.Total 
				  WHEN L.billtype=6 AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.Total
				  WHEN L.BillType in(34,404)  AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.Total
				  WHEN L.billtype=161  AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.Total
				  WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.Total<0 AND l.BillType NOT IN(6,34,161,404) AND bi.redword=2 
						THEN L.Total 
				  WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total<0 AND bi.redword IN (0,1) 
						THEN ABS(L.Total) 
				  WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total>0 AND bi.redword=2  
						THEN -L.Total
				  ELSE 0
				END) AS addtotal,
			SUM(CASE  WHEN L.billtype IN(6,34,161,404) AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword IN (0,1) 
							THEN L.nTotal
				  WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.nTotal>0 AND l.BillType NOT IN(6,34,161,404) AND bi.redword IN (0,1) 
						THEN L.nTotal 
				  WHEN L.billtype=6 AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.nTotal
				  WHEN L.BillType in(34,404)   AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.nTotal
				  WHEN L.billtype=161  AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.nTotal
				  WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.nTotal<0 AND l.BillType NOT IN(6,34,161,404) AND bi.redword=2 
						THEN L.nTotal 
				  WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.nTotal<0 AND bi.redword IN (0,1) 
						THEN ABS(L.nTotal) 
				  WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.nTotal>0 AND bi.redword=2  
						THEN -L.nTotal
				  ELSE 0
				END) AS naddtotal,
			SUM(CASE WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.Total<0 AND  L.BillType NOT IN(6,34,161,404) AND bi.redword IN (0,1) 
							THEN ABS(L.Total)
				 WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.Total>0 AND  L.BillType NOT IN(6,34,161,404) AND bi.redword=2 
						THEN -L.Total 
				 WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total>0 AND bi.redword IN (0,1) 
						THEN L.Total 
				 WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total<0 AND bi.redword=2 
						THEN L.Total
				 ELSE 0
				END) AS rectotal,
			SUM(CASE WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.nTotal<0 AND  L.BillType NOT IN(6,34,161,404) AND bi.redword IN (0,1) 
							THEN ABS(L.nTotal)
				 WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.nTotal>0 AND  L.BillType NOT IN(6,34,161,404) AND bi.redword=2 
						THEN -L.nTotal 
				 WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total>0 AND bi.redword IN (0,1) 
						THEN L.nTotal 
				 WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total<0 AND bi.redword=2 
						THEN L.nTotal
				 ELSE 0
				END) AS nrectotal,
			bi.redword
	FROM	ListTable L '
	
	IF @EtypeFlag = 1
		SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId AND E.BTypeId = L.BTypeId '
	ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
		SET @SQL += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId'
	
END
					
IF  @MBTypeId <> '00001' OR @MBTypeId2 <> '00002' OR @Btypeid<>''
	SET @SQL = @SQL + '	INNER JOIN #BType B ON L.BTypeId = B.TypeId '
	
IF  @STypeId <> '' OR @MStypeid <> '00000'
	SET @SQL = @SQL + ' INNER JOIN #SType S ON L.STypeId = S.TypeId '	
		
IF  @MDtypeid <> '00000'
	SET @SQL = @SQL + ' INNER JOIN #DType D ON D.TypeId = L.DTypeId '	




--优惠券


IF @nType=1 --职员应收
BEGIN
	SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)
	INSERT INTO #atypeidlist (NID) VALUES(@aratypeID)
	IF @bhys='1'
	BEGIN
		SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)+','+CHAR(39)+@ysatypeID+CHAR(39)
		INSERT INTO #atypeidlist (NID) VALUES(@ysatypeID)
	END
	SET @SQLYHQ='
	INSERT INTO #result
	(
		billnumberid,
		cid,
		ATYPEID,
		Rate,
		billdate,
		stypeid	,
		billcode,
		billtype,
		comment	,
		addTotal,
		naddTotal,
		recTotal,
		nrecTotal,
		redword
	)
	SELECT	bi.billnumberid,
			l.cid,
			L.ATYPEID,
			bi.Rate,
			bi.billdate,
			L.stypeid,
			bi.billcode,
			bi.billtype,
			bi.comment,
			SUM(CASE  WHEN l.billtype IN(45,11,160,215,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord IN(0,1) 
						THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426) AND bi.RedWord IN(0,1) 
						THEN l.Total 
				  WHEN l.billtype in (45,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.Total
				 WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.Total
				  WHEN l.BillType in(11,405,424)  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.Total
				  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND l.BillType NOT IN(45,215,11,160,405,424,426) AND bi.RedWord=2 
						THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total<0  AND bi.redword IN(0,1)  
						THEN ABS(l.Total) 
				  WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total>0  AND bi.redword=2  
						THEN -l.Total
				  ELSE 0
				END) AS addtotal,
			SUM(CASE  WHEN l.billtype IN(45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord IN(0,1) 
						THEN l.nTotal
				  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426) AND bi.RedWord IN(0,1) 
						THEN l.nTotal 
				  WHEN l.billtype in (45,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.nTotal
				WHEN l.billtype=215 AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.nTotal
				  WHEN l.BillType in(11,405,424) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.nTotal
				  WHEN l.billtype=160  AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND bi.RedWord=2 
						THEN l.nTotal
				  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.nTotal<0 AND l.BillType NOT IN(45,215,11,160,405,424,426) AND bi.RedWord=2 
						THEN l.nTotal
				  WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal<0  AND bi.redword IN(0,1)  
						THEN ABS(l.nTotal) 
				  WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal>0  AND bi.redword=2  
						THEN -l.nTotal
				  ELSE 0
				END) AS naddtotal,
			SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426) AND bi.redword IN(0,1) 
							THEN ABS(l.Total)
					 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND  l.BillType NOT IN(45,215,11,160,405,424,426) AND bi.redword IN(2) 
							THEN -l.Total 
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total>0 AND bi.redword IN(0,1)  
							THEN l.Total 
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total<0  AND bi.redword=2 
							THEN l.Total
				 ELSE 0
				END) AS rectotal,
			SUM(CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.nTotal<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426) AND bi.redword IN(0,1) 
							THEN ABS(l.nTotal)
					 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.nTotal>0 AND  l.BillType NOT IN(45,215,11,160,405,424,426) AND bi.redword IN(2) 
							THEN -l.nTotal 
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal>0 AND bi.redword IN(0,1)  
							THEN l.nTotal 
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal<0  AND bi.redword=2 
							THEN l.nTotal
				 ELSE 0
				END) AS nrectotal,
			bi.redword
	FROM	ListTable L '
	
	IF @EtypeFlag = 1
		SET @SQLYHQ += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId  AND E.BTypeId = L.BTypeId'
	ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
		SET @SQLYHQ += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId'
		
END
ELSE--职员往来应付
BEGIN
	SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)
	INSERT INTO #atypeidlist (NID) VALUES(@apatypeID)
	IF @bhys='1'
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)+','+CHAR(39)+@yfatypeID+CHAR(39)
		INSERT INTO #atypeidlist (NID) VALUES(@yfatypeID)
	END
	SET @SQLYHQ='
	INSERT INTO #result
	(
		billnumberid,
		cid,
		ATYPEID,
		Rate,
		billdate,
		stypeid	,
		billcode,
		billtype,
		comment	,
		addTotal,
		naddTotal,
		recTotal,
		nrecTotal,
		redword
	)
	SELECT	bi.billnumberid,
			l.cid,
			L.ATYPEID,
			bi.Rate,
			bi.billdate,
			L.stypeid,
			bi.billcode,
			bi.billtype,
			bi.comment,
			SUM(CASE  WHEN L.billtype IN(6,34,161,404,423) AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword IN (0,1) 
							THEN L.Total
				  WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.Total>0 AND l.BillType NOT IN(6,34,161,404,423) AND bi.redword IN (0,1) 
						THEN L.Total 
				  WHEN L.billtype=6 AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.Total
				  WHEN L.BillType in(34,404,423)  AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.Total
				  WHEN L.billtype=161  AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.Total
				  WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.Total<0 AND l.BillType NOT IN(6,34,161,404,423) AND bi.redword=2 
						THEN L.Total 
				  WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total<0 AND bi.redword IN (0,1) 
						THEN ABS(L.Total) 
				  WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total>0 AND bi.redword=2  
						THEN -L.Total
				  ELSE 0
				END) AS addtotal,
			SUM(CASE  WHEN L.billtype IN(6,34,161,404,423) AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword IN (0,1) 
							THEN L.nTotal
				  WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.nTotal>0 AND l.BillType NOT IN(6,34,161,404,423) AND bi.redword IN (0,1) 
						THEN L.nTotal 
				  WHEN L.billtype=6 AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.nTotal
				  WHEN L.BillType in(34,404,423)   AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.nTotal
				  WHEN L.billtype=161  AND L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND bi.redword=2 
						THEN L.nTotal
				  WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.nTotal<0 AND l.BillType NOT IN(6,34,161,404,423) AND bi.redword=2 
						THEN L.nTotal 
				  WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.nTotal<0 AND bi.redword IN (0,1) 
						THEN ABS(L.nTotal) 
				  WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.nTotal>0 AND bi.redword=2  
						THEN -L.nTotal
				  ELSE 0
				END) AS naddtotal,
			SUM(CASE WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.Total<0 AND  L.BillType NOT IN(6,34,161,404,423) AND bi.redword IN (0,1) 
							THEN ABS(L.Total)
				 WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.Total>0 AND  L.BillType NOT IN(6,34,161,404,423) AND bi.redword=2 
						THEN -L.Total 
				 WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total>0 AND bi.redword IN (0,1) 
						THEN L.Total 
				 WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total<0 AND bi.redword=2 
						THEN L.Total
				 ELSE 0
				END) AS rectotal,
			SUM(CASE WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.nTotal<0 AND  L.BillType NOT IN(6,34,161,404,423) AND bi.redword IN (0,1) 
							THEN ABS(L.nTotal)
				 WHEN  L.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.nTotal>0 AND  L.BillType NOT IN(6,34,161,404,423) AND bi.redword=2 
						THEN -L.nTotal 
				 WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total>0 AND bi.redword IN (0,1) 
						THEN L.nTotal 
				 WHEN  L.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.Total<0 AND bi.redword=2 
						THEN L.nTotal
				 ELSE 0
				END) AS nrectotal,
			bi.redword
	FROM	ListTable L '
	
	IF @EtypeFlag = 1
		SET @SQLYHQ += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId AND E.BTypeId = L.BTypeId '
	ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
		SET @SQLYHQ += ' INNER JOIN #etype E ON L.ETypeId = E.EtypeId'
	
END
					
IF  @MBTypeId <> '00001' OR @MBTypeId2 <> '00002' OR @Btypeid<>''
	SET @SQLYHQ = @SQLYHQ + '	INNER JOIN #BType B ON L.BTypeId = B.TypeId '
	
IF  @STypeId <> '' OR @MStypeid <> '00000'
	SET @SQLYHQ = @SQLYHQ + ' INNER JOIN #SType S ON L.STypeId = S.TypeId '	
		
IF  @MDtypeid <> '00000'
	SET @SQLYHQ = @SQLYHQ + ' INNER JOIN #DType D ON D.TypeId = L.DTypeId '	


--优惠券	




---为了统计发票，where条件分开
DECLARE @Sqlwhere varchar(2000)
DECLARE @SqlwhereYHQ varchar(2000)


SET @Sqlwhere=' 
	WHERE	L.BillDate<='''+@EndDate+'''
	AND l.BillDate>='''+@StartDate+'''
	AND L.ATypeId IN ('+@AtypeType+') 
	--AND L.Billtype<>159
	AND L.Billtype not in (423,424,426)
	'
IF @cid<>'0'
	SET @Sqlwhere=@Sqlwhere+' AND L.cid='+CHAR(39)+@cid+CHAR(39)	
		
IF @showredword=0
	SET @Sqlwhere=@Sqlwhere+' AND BI.REDWORD=0 '
	
SET @Sqlwhere=@Sqlwhere + ' AND Bi.ifYearBill= 0 '    --年节存标志	
SET @Sqlwhere=@Sqlwhere+'
GROUP BY	bi.billnumberid,
			l.cid,
			bi.Rate,
			bi.billdate,
			L.stypeid,
			bi.billcode,
			bi.billtype,
			bi.comment ,
			L.atypeid,
			bi.redword '


SET @SqlwhereYHQ=' 
	WHERE	L.BillDate<='''+@EndDate+'''
	AND l.BillDate>='''+@StartDate+'''
	AND L.ATypeId IN ('+@AtypeType+') 
	AND L.Billtype in (423,424,426)
	'
IF @cid<>'0'
	SET @SqlwhereYHQ=@SqlwhereYHQ+' AND L.cid='+CHAR(39)+@cid+CHAR(39)	
		
IF @showredword=0
	SET @SqlwhereYHQ=@SqlwhereYHQ+' AND BI.REDWORD=0 '
	
SET @SqlwhereYHQ=@SqlwhereYHQ + ' AND Bi.ifYearBill= 0 '    --年节存标志	
SET @SqlwhereYHQ=@SqlwhereYHQ+'
GROUP BY	bi.billnumberid,
			l.cid,
			bi.Rate,
			bi.billdate,
			L.stypeid,
			bi.billcode,
			bi.billtype,
			bi.comment ,
			L.atypeid,
			bi.redword '		
			
			

--PRINT(@SQLYHQ+' INNER JOIN couponbillindex Bi on L.billnumberid=bi.billnumberid and L.billtype=bi.billtype '+ @SqlwhereYHQ)			
EXEC(@SQL+' INNER JOIN BillIndex Bi on L.billnumberid=bi.billnumberid and L.billtype=bi.billtype '+ @Sqlwhere) --普通单据
EXEC(@SQL+' INNER JOIN ReceiptBillIndex Bi on L.billnumberid=bi.billnumberid and L.billtype=bi.billtype '+ @Sqlwhere) --发票
EXEC(@SQLYHQ+' INNER JOIN Coupon_BillIndex Bi on L.billnumberid=bi.billnumberid and L.billtype=bi.billtype '+ @SqlwhereYHQ) --优惠券


SELECT 	r.billnumberid,
		C.FullName AS cfullname,
		r.Rate AS rate,
		r.billdate,
		R.stypeid,
		R.billcode,
		R.billtype,
		R.comment,
		R.addTotal,
		ISNULL(R.naddTotal,0) AS naddTotal,
		R.recTotal,
		ISNULL(R.nrecTotal,0) AS nrecTotal,
		R.redword
 FROM #Result R
 INNER JOIN Ac_Currency C ON C.CId=R.cid
 WHERE R.billtype<>159
 UNION ALL
 SELECT 	r.billnumberid,
		C.FullName AS cfullname,
		AC.Rate AS rate,
		r.billdate,
		R.stypeid,
		R.billcode,
		R.billtype,
		R.comment,
		R.addTotal,
		ISNULL(R.naddTotal,0) AS naddTotal,
		R.recTotal,
		ISNULL(R.nrecTotal,0) AS nrecTotal,
		R.redword
 FROM #Result R
 INNER JOIN (SELECT BillNumberID,TypeATypeID,Rate,CID FROM  AccountCredence WHERE TypeATypeID IN (SELECT NID FROM #atypeidlist) GROUP BY BillNumberID,TypeATypeID,Rate,CID) AC ON AC.BillNumberID=R.billnumberid AND AC.TypeATypeID=R.ATYPEID AND AC.CID=R.cid
 INNER JOIN Ac_Currency C ON C.CId=R.cid
 WHERE R.billtype=159
 ORDER BY billdate,billnumberid

DROP TABLE #EType,#SType,#DType,#Btype,#Result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryEmployeeWldzLine]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryEmployeeWldzLine]
GO


/*
	作者：谢吉康
	日期：2005-6-9
	描述：职员往来线性查询
	
	作者：毛欣蓉
	日期：2011-04-07
	描述：应收、应付算法调整
	
	日期:2012-06-07
    作者:黄清
    描述:添加币别条件,调整科目
*/
CREATE PROCEDURE Web_QueryEmployeeWldzLine
(
	@OperatorId		VARCHAR(100),		--操作员ID
	@BTypeId		VARCHAR(100),		--往来单位的Id	
	@ETypeId		VARCHAR(MAX),		--当前选择的职员
	@STypeId		VARCHAR(MAX),		--分支机构
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--截至日期
	@nType			INT,				--1.应收   2.应付
	@ShowZero		INT,				--1.不显示为0   0.显示为0
	@UserCode		VARCHAR(256),		--编号
	@FullName		VARCHAR(256),		--名称
	@Bhys			VARCHAR(MAX),		--包含预收（付）1.包含 0.不包含
	@cid			VARCHAR(10),			--币别
	@EtypeFlag		INT					--0=单据经手人，1=往来单位关联职员
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @BTypeAll 	INT,
		@SQL		VARCHAR(8000),
		@BTypeMxId	VARCHAR(100),
		@aratypeID	VARCHAR(50),
		@ysatypeID	VARCHAR(50),
		@apatypeID	VARCHAR(50),
		@yfatypeID	VARCHAR(50)

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

IF @BTypeId = '00000'
	BEGIN
		SET @BTypeId = '%'
		SET @BTypeMxId = '%'
	END
ELSE
	SET @BTypeMxId = @BTypeId		

--SELECT UserCode,FullName,ParID,SonNum,TypeID INTO #Btype FROM F_GetManBTypeAll(@OperatorID) WHERE TypeId LIKE @BTypeMxId + '%'


--往来单位
--SELECT UserCode,FullName,ParID,SonNum,TypeId INTO #Btype FROM F_GetManBTypeAll(@OperatorID)
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeMxId,2,@OperatorID)


--职员(关联往来单位中的职员)
CREATE TABLE #GetManETypeId(EtypeId	VARCHAR(100), BtypeId VARCHAR(100))
IF @EtypeFlag = 1
BEGIN
	INSERT INTO #GetManETypeId(EtypeId, BtypeId)
	SELECT DISTINCT f.TypeId,g.TypeId
	FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) f,#GetManBTypeId g,btype b
	WHERE f.TypeId=b.etypeid AND g.TypeId = b.typeId
END
ELSE
BEGIN
	INSERT INTO #GetManETypeId(EtypeId,BtypeId)
	SELECT f.TypeId,''
	FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) f
END


--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)		

CREATE TABLE #Result
(
	BTypeId			VARCHAR(100),
	arapTotal00		 NUMERIC(24, 10) ,
	narapTotal00	 NUMERIC(24, 10) ,
	araptotal1		 NUMERIC(24, 10) ,
	naraptotal1		 NUMERIC(24, 10) ,
	arapTotal2		 NUMERIC(24, 10) ,
	narapTotal2		 NUMERIC(24, 10) 
)
DECLARE @PreSql00 VARCHAR(MAX)
SET @PreSql00=''

----------统计期初 start---------------

DECLARE @EtypeIsEmpty INT = 0

IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	SELECT TOP 1 @EtypeIsEmpty = 1 
	FROM IniBType_ArApTotal I
	INNER JOIN #GetManSTypeId S ON S.TypeId = I.STypeID
	WHERE I.ETypeId = '' OR I.ETypeId IS NULL
ELSE
	SELECT TOP 1 @EtypeIsEmpty = 1 FROM IniBType_ArApTotal WHERE ETypeId = '' OR ETypeId IS NULL

IF @ntype=1--应收查询
BEGIN
	IF @bhys='1' --包含预收
	BEGIN
		SET @PreSql00='
		ISNULL(ISNULL(A.arTotal00,0)-ISNULL(A.ysTotal00,0),0) AS arapTotal00, 
		ISNULL(ISNULL(A.narTotal00,0)-ISNULL(A.nysTotal00,0),0) AS narapTotal00,'
	END
	ELSE
	BEGIN
		SET @PreSql00='
		ISNULL(A.arTotal00,0) AS arapTotal00,
		ISNULL(A.narTotal00,0) AS narapTotal00, '
	END
END
ELSE --应付查询
BEGIN
	IF @bhys='1' --包含预付
	BEGIN
		SET @PreSql00='
		ISNULL(ISNULL(A.apTotal00,0)-ISNULL(A.yfTotal00,0),0) AS arapTotal00, 
		ISNULL(ISNULL(A.napTotal00,0)-ISNULL(A.nyfTotal00,0),0) AS narapTotal00, '
	END
	ELSE
	BEGIN
		SET @PreSql00='
		ISNULL(A.apTotal00,0) AS arapTotal00,
		ISNULL(A.napTotal00,0) AS narapTotal00, '
	END
END


IF @EtypeIsEmpty = 1
BEGIN
	SET @SQL = '
	INSERT INTO #Result
	SELECT	B.TypeId,
			'+@PreSql00+'
			0 AS araptotal1,
			0 AS naraptotal1,
			0 AS araptotal2,
			0 AS naraptotal2
	FROM	#GetManBTypeId B
	INNER JOIN BType_ArApTotal A ON B.TypeId = A.BTypeId '
						
	IF NOT (@STypeId = '' AND @MStypeid = '00000')			
		SET @SQL = @SQL + '	INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '
					
	SET @SQL = @SQL + '	WHERE	1=1 '
						
	IF @cid<>'0'
		SET @SQL=@SQL+' AND A.cid='+@cid
	EXEC(@SQL)
END	
ELSE
BEGIN
	SET @SQL = '
		INSERT INTO #Result
		SELECT	A.BTypeId,
				ISNULL(SUM(A.arapTotal00),0),
				ISNULL(SUM(A.narapTotal00),0),
				0 AS araptotal1,
				0 AS naraptotal1,
				0 AS araptotal2,
				0 AS naraptotal2
		FROM
		(
			SELECT  A.BTypeId,
					'+@PreSql00+'
					0 AS araptotal1,
					0 AS naraptotal1,
					0 AS araptotal2,
					0 AS naraptotal2
			FROM IniBType_ArApTotal A'
			
			IF NOT (@STypeId = '' AND @MStypeid = '00000')			
				SET @SQL = @SQL + '	INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
			
			IF @EtypeFlag = 1
				SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.EtypeId = A.ETypeId AND E.BTypeId = A.BTypeId'	
			ELSE IF @ETypeId <> '' OR @MEtypeid='-99999'
				SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.EtypeId = A.ETypeId'	
			
			SET @SQL += ' WHERE 1=1 '
			
			IF @cid <> '0'
				SET @SQL += ' AND A.cid=' + @cid
		
		SET @SQL += ' 
			) A 
			GROUP BY A.BTypeId '
	
	--PRINT(@SQL)
	EXEC(@SQL)	
END

----------统计期初 end-------------

----------算发生额 start----------
IF @nType=1 --应收
BEGIN
	SET @SQL = '
	INSERT INTO #Result
	SELECT	L.BTypeid,
			0 AS arapTotal00,	
			0 AS narapTotal00,								
			araptotal1 = SUM(
				CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.Total
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.Total
					 ELSE 0
				END 
			), 
			naraptotal1 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.nTotal
					 WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.nTotal
					 ELSE 0
				END 
			),
			araptotal2 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.total
					 WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.Total
					ELSE 0
				END
			),
			naraptotal2 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.ntotal
					 WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.nTotal
					ELSE 0
				END
			)
	FROM	ListTable L '
END
ELSE --应付
BEGIN
	SET @SQL = '
	INSERT INTO #Result
	SELECT	L.BTypeid,
			0 AS arapTotal00,
			0 AS narapTotal00,									
			araptotal1 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.Total
					 WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.Total
					 ELSE 0
					END 
				), 
			naraptotal1 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.nTotal
					 WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.nTotal
					 ELSE 0
					END 
				),
			araptotal2 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.total
					WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.Total
					ELSE 0
					END
				),
			naraptotal2 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.ntotal
					WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.nTotal
					ELSE 0
					END
				)
	FROM	ListTable L '
END

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON L.BTypeId = B.TypeId '
		
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON L.STypeId = S.TypeId '	
		
IF NOT @MDtypeid = '00000'
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = L.DTypeId '	

IF @EtypeFlag = 1
	SET @SQL += ' INNER JOIN #GetManETypeId E ON L.ETypeId = E.EtypeId AND E.BTypeId = L.BTypeId'
ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00000')
	SET @SQL += ' INNER JOIN #GetManETypeId E ON L.ETypeId = E.EtypeId'

SET @SQL = @SQL + '	WHERE	L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)
			
			
--处理包含预收			
IF @Bhys = '1'
	BEGIN
		IF @nType = 1 --应收
			SET @SQL = @SQL + ' AND (L.ATypeId = '+CHAR(39)+@aratypeID+CHAR(39)+'  OR L.ATypeId = '+CHAR(39)+@ysatypeID+CHAR(39)+')'
		ELSE --应付
			SET @SQL = @SQL + ' AND (L.ATypeId='+CHAR(39)+@apatypeID+CHAR(39)+' OR L.ATypeId = '+CHAR(39)+@yfatypeID+CHAR(39)+')'
	END
ELSE
	BEGIN
		IF @nType= 1
			SET @SQL = @SQL + ' AND L.ATypeId = '+CHAR(39)+@aratypeID+CHAR(39)	
		ELSE
			SET @SQL = @SQL + ' AND L.ATypeId='+CHAR(39)+@apatypeID+CHAR(39)			
	END
IF @cid<>'0'
	SET @SQL=@SQL+' AND L.cid='+@cid				
	
SET @SQL = @SQL + '	AND L.Audited = 1
					
			GROUP BY L.BTypeid'

EXEC(@SQL)
---------算发生额 end------------

---------最终处理----------------
SET @SQL='
	SELECT	A.*
	FROM	(
		SELECT	
				a.typeid,					
				a.UserCode,
				a.FullName,				
				arApTotal00 = SUM(ISNULL(b.ArApTotal00,0)),
				narApTotal00 = SUM(ISNULL(b.nArApTotal00,0)),
				arApTotal1 = SUM(ISNULL(b.ArApTotal1,0)),
				narApTotal1 = SUM(ISNULL(b.nArApTotal1,0)),
				arApTotal2 = SUM(ISNULL(b.araptotal2,0)),
				narApTotal2 = SUM(ISNULL(b.naraptotal2,0)),
				ysye = SUM(ISNULL(b.ArApTotal00,0))+ SUM(ISNULL(b.ArApTotal1,0))+ SUM(ISNULL(b.araptotal2,0)),
				nysye = SUM(ISNULL(b.nArApTotal00,0))+ SUM(ISNULL(b.nArApTotal1,0))+ SUM(ISNULL(b.naraptotal2,0))
		FROM 	Btype a
		LEFT 	JOIN #Result b	ON a.typeid = b.BTypeid
		WHERE	1=1'
SET @SQL = @SQL + '	
					AND A.TypeId LIKE '+CHAR(39)+@BTypeId+'%'+CHAR(39)+'
					AND A.UserCode LIKE '+CHAR(39)+'%'+@UserCode+'%'+CHAR(39)+'
					AND A.FullName LIKE '+CHAR(39)+'%'+@FullName+'%'+CHAR(39)+'
			GROUP BY 
					a.UserCode,
					a.FullName,
					a.ParId,
					a.SonNum,
					a.typeid
	)A
	WHERE	A.arApTotal1<>0 OR A.arApTotal2<>0 OR A.ArApTotal00<>0
	ORDER BY A.UserCode '	

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Result,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetManBTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryEmployeeWldzList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryEmployeeWldzList]
GO

/*
	作者：谢吉康
	日期：2005-6-9
	描述：职员往来查询
	
	作者：毛欣蓉
	日期：1011-04-06
	描述：应收、应付算法调整
	
	日期:2012-06-07
    作者:黄清
    描述:添加币别条件,调整科目
*/
CREATE   PROCEDURE Web_QueryEmployeeWldzList
(
	@OperatorId		VARCHAR(100),		--操作员ID
	@BTypeId		VARCHAR(100),		--往来单位的Id
	@ETypeId		VARCHAR(MAX),		--当前选择的职员
	@STypeId		VARCHAR(MAX),		--分支机构
	@StartDate		VARCHAR(20),		--开始日期
	@EndDate		VARCHAR(20),		--截至日期
	@nType			INT,				--1.应收   2.应付
	@Bhys			VARCHAR(MAX),		--包含预收（付）1.包含 0.不包含
	@cid			VARCHAR(10),			--币别
	@EtypeFlag		INT					--0=单据经手人，1=往来单位关联职员
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @BTypeAll 	INT,
		@SQL		VARCHAR(8000),
		@BTypeMxId	VARCHAR(100),
		@SonNum 	INT,
		@aratypeID	VARCHAR(50),
		@ysatypeID	VARCHAR(50),
		@apatypeID	VARCHAR(50),
		@yfatypeID	VARCHAR(50)

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

IF @BTypeId = '00000'
	SET @BTypeMxId = '%'
ELSE			
	SET @BTypeMxId = @BTypeId

SELECT @SonNum = SonNum FROM BType WHERE TypeId = @BTypeId

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)	

--往来单位
SELECT UserCode,FullName,ParID,SonNum,TypeId 
INTO #Btype FROM F_GetManBTypeAll(@OperatorID)

CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeMxId,2,@OperatorID)

--职员(关联往来单位中的职员)
CREATE TABLE #GetManETypeId(EtypeId	VARCHAR(100),Btypeid VARCHAR(100))
IF @EtypeFlag = 1
BEGIN
	INSERT INTO #GetManETypeId(EtypeId,Btypeid)
	SELECT DISTINCT f.TypeId,g.TypeId
	FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) f,#GetManBTypeId g,btype b
	WHERE f.TypeId=b.etypeid AND g.TypeId = b.typeId
END
ELSE
BEGIN
	INSERT INTO #GetManETypeId(EtypeId,Btypeid)
	SELECT f.TypeId,''
	FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) f
END

CREATE TABLE #Result
(
	BTypeId			VARCHAR(100),
	arapTotal00		 NUMERIC(24, 10) ,
	narapTotal00	 NUMERIC(24, 10) ,
	araptotal1		 NUMERIC(24, 10) ,
	naraptotal1		 NUMERIC(24, 10) ,
	arapTotal2		 NUMERIC(24, 10) ,
	narapTotal2		 NUMERIC(24, 10) 
)

DECLARE @PreSql00 VARCHAR(MAX)=''

----------统计期初 start---------------
DECLARE @EtypeIsEmpty INT = 0
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	SELECT TOP 1 @EtypeIsEmpty = 1 
	FROM IniBType_ArApTotal I
	INNER JOIN #GetManSTypeId S ON S.TypeId = I.STypeID
	WHERE I.ETypeId = '' OR I.ETypeId IS NULL
ELSE
	SELECT TOP 1 @EtypeIsEmpty = 1 FROM IniBType_ArApTotal WHERE ETypeId = '' OR ETypeId IS NULL

IF @ntype=1--应收查询
BEGIN
	IF @bhys='1' --包含预收
	BEGIN
		SET @PreSql00='
		ISNULL(ISNULL(A.arTotal00,0)-ISNULL(A.ysTotal00,0),0) AS arapTotal00, 
		ISNULL(ISNULL(A.narTotal00,0)-ISNULL(A.nysTotal00,0),0) AS narapTotal00,'
	END
	ELSE
	BEGIN
		SET @PreSql00='
		ISNULL(A.arTotal00,0) AS arapTotal00,
		ISNULL(A.narTotal00,0) AS narapTotal00, '
	END
END
ELSE --应付查询
BEGIN
	IF @bhys='1' --包含预付
	BEGIN
		SET @PreSql00='
		ISNULL(ISNULL(A.apTotal00,0)-ISNULL(A.yfTotal00,0),0) AS arapTotal00, 
		ISNULL(ISNULL(A.napTotal00,0)-ISNULL(A.nyfTotal00,0),0) AS narapTotal00, '
	END
	ELSE
	BEGIN
		SET @PreSql00='
		ISNULL(A.apTotal00,0) AS arapTotal00,
		ISNULL(A.napTotal00,0) AS narapTotal00, '
	END
END

IF @EtypeIsEmpty = 1 --之前的逻辑
BEGIN
	SET @SQL = '
	INSERT INTO #Result
	SELECT	A.BTypeId,
			'+@PreSql00+'
			0 AS araptotal1,
			0 AS naraptotal1,
			0 AS araptotal2,
			0 AS naraptotal2
	FROM	BType_ArApTotal A
	INNER JOIN #GetManBTypeId B ON B.TypeId = A.BTypeId '
						
	IF NOT (@STypeId = '' AND @MStypeid = '00000')			
		SET @SQL = @SQL + '	INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '
					
	SET @SQL = @SQL + '	
	WHERE 1=1 '
	IF @cid<>'0'
		SET @SQL=@SQL+'AND A.cid='+@cid

	--print @sql
	EXEC(@SQL)
END
ELSE  --期初与职员关联
BEGIN
	SET @SQL = '
		INSERT INTO #Result
		SELECT	A.BTypeId,
				ISNULL(SUM(A.arapTotal00),0),
				ISNULL(SUM(A.narapTotal00),0),
				0 AS araptotal1,
				0 AS naraptotal1,
				0 AS araptotal2,
				0 AS naraptotal2
		FROM
		(
			SELECT  A.BTypeId,
					'+@PreSql00+'
					0 AS araptotal1,
					0 AS naraptotal1,
					0 AS araptotal2,
					0 AS naraptotal2
			FROM IniBType_ArApTotal A'
			
			IF NOT (@STypeId = '' AND @MStypeid = '00000')			
				SET @SQL = @SQL + '	INNER JOIN #GetManSTypeId S ON A.STypeId = S.TypeId '	
			
			IF @EtypeFlag = 1
				SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.EtypeId = A.ETypeId AND E.BTypeId = A.BTypeId'
			ELSE IF @ETypeId <> '' OR @MEtypeid='-99999'
				SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON E.EtypeId = A.ETypeId'	
				
			SET @SQL += ' WHERE 1=1 '
			
			IF @cid <> '0'
				SET @SQL += ' AND A.cid=' + @cid
		
		SET @SQL += ' 
			) A 
			GROUP BY A.BTypeId '
	
	--PRINT(@SQL)
	EXEC(@SQL)	
END

----------统计期初 end-------------
--select *from #Result
----------算发生额 start----------
IF @nType=1 --应收
BEGIN
	SET @SQL = '
	INSERT INTO #Result
	SELECT	L.BTypeid,
			0 AS arapTotal00,	
			0 AS narapTotal00,								
			araptotal1 = SUM(
				CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.Total
					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.Total
					 ELSE 0
				END 
			), 
			naraptotal1 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.nTotal
					 WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.nTotal
					 ELSE 0
				END 
			),
			araptotal2 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.total
					WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.Total
					ELSE 0
				END
			),
			naraptotal2 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.ntotal
					WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.nTotal
					ELSE 0
				END
			)
	FROM	ListTable L 
	'
END
ELSE --应付
BEGIN
	SET @SQL = '
	INSERT INTO #Result
	SELECT	L.BTypeid,
			0 AS arapTotal00,
			0 AS narapTotal00,									
			araptotal1 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.Total
					 WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.Total
					 ELSE 0
					END 
				), 
			naraptotal1 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.nTotal
					 WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.nTotal
					 ELSE 0
					END 
				),
			araptotal2 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.total
					WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.Total
					ELSE 0
					END
				),
			naraptotal2 = SUM(
				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.ntotal
					WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.nTotal
					ELSE 0
					END
				)
	FROM	ListTable L '
END

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON L.BTypeId = B.TypeId '
		
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON L.STypeId = S.TypeId '	
		
IF NOT @MDtypeid = '00000'
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = L.DTypeId '	

IF @EtypeFlag = 1
	SET @SQL += ' INNER JOIN #GetManETypeId E ON L.ETypeId = E.EtypeId AND E.BTypeId = L.BTypeId'
ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00001')
	SET @SQL += ' INNER JOIN #GetManETypeId E ON L.ETypeId = E.EtypeId'

SET @SQL = @SQL + ' WHERE L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)

--处理包含预收			
IF @Bhys = '1'
	BEGIN
		IF @nType = 1 --应收
			SET @SQL = @SQL + ' AND (L.ATypeId = '+CHAR(39)+@aratypeID+CHAR(39)+'  OR L.ATypeId = '+CHAR(39)+@ysatypeID+CHAR(39)+')'
		ELSE --应付
			SET @SQL = @SQL + ' AND (L.ATypeId='+CHAR(39)+@apatypeID+CHAR(39)+' OR L.ATypeId = '+CHAR(39)+@yfatypeID+CHAR(39)+')'
	END
ELSE
	BEGIN
		IF @nType= 1
			SET @SQL = @SQL + ' AND L.ATypeId = '+CHAR(39)+@aratypeID+CHAR(39)	
		ELSE
			SET @SQL = @SQL + ' AND L.ATypeId='+CHAR(39)+@apatypeID+CHAR(39)			
	END
					
IF @cid<>'0'
	SET @SQL=@SQL+' AND L.cid='+@cid
SET @SQL = @SQL + '	AND L.Audited = 1
					
			GROUP BY L.BTypeid'
--print(@sql)
EXEC(@SQL)

----处理优惠券

--IF @nType=1 --应收
--BEGIN
--	SET @SQL = '
--	INSERT INTO #Result
--	SELECT	L.BTypeid,
--			0 AS arapTotal00,	
--			0 AS narapTotal00,								
--			araptotal1 = SUM(
--				CASE WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.Total
--					 WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.Total
--					 ELSE 0
--				END 
--			), 
--			naraptotal1 = SUM(
--				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.nTotal
--					 WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.nTotal
--					 ELSE 0
--				END 
--			),
--			araptotal2 = SUM(
--				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.total
--					WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.Total
--					ELSE 0
--				END
--			),
--			naraptotal2 = SUM(
--				CASE WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.ntotal
--					WHEN l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.nTotal
--					ELSE 0
--				END
--			)
--	FROM	ListTable L 
--	'
--END
--ELSE --应付
--BEGIN
--	SET @SQL = '
--	INSERT INTO #Result
--	SELECT	L.BTypeid,
--			0 AS arapTotal00,
--			0 AS narapTotal00,									
--			araptotal1 = SUM(
--				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.Total
--					 WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.Total
--					 ELSE 0
--					END 
--				), 
--			naraptotal1 = SUM(
--				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN l.nTotal
--					 WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate < '+CHAR(39)+@StartDate+CHAR(39)+'  THEN -l.nTotal
--					 ELSE 0
--					END 
--				),
--			araptotal2 = SUM(
--				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.total
--					WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.Total
--					ELSE 0
--					END
--				),
--			naraptotal2 = SUM(
--				CASE WHEN l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN L.ntotal
--					WHEN l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND L.BillDate >= '+CHAR(39)+@StartDate+CHAR(39)+' AND L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)+'   THEN -l.nTotal
--					ELSE 0
--					END
--				)
--	FROM	ListTable L '
--END

--IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
--	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON L.BTypeId = B.TypeId '
		
--IF NOT (@STypeId = '' AND @MStypeid = '00000')
--	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON L.STypeId = S.TypeId '	
		
--IF NOT @MDtypeid = '00000'
--	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON D.TypeId = L.DTypeId '	

--IF @EtypeFlag = 1
--	SET @SQL += ' INNER JOIN #GetManETypeId E ON L.ETypeId = E.EtypeId AND E.BTypeId = L.BTypeId'
--ELSE IF  NOT (@ETypeId = '' AND @MEtypeid = '00001')
--	SET @SQL += ' INNER JOIN #GetManETypeId E ON L.ETypeId = E.EtypeId'

--SET @SQL = @SQL + ' WHERE  L.BillDate <= '+CHAR(39)+@EndDate+CHAR(39)


----处理包含预收			
--IF @Bhys = '1'
--	BEGIN
--		IF @nType = 1 --应收
--			SET @SQL = @SQL + ' AND (L.ATypeId = '+CHAR(39)+@aratypeID+CHAR(39)+'  OR L.ATypeId = '+CHAR(39)+@ysatypeID+CHAR(39)+')'
--		ELSE --应付
--			SET @SQL = @SQL + ' AND (L.ATypeId='+CHAR(39)+@apatypeID+CHAR(39)+' OR L.ATypeId = '+CHAR(39)+@yfatypeID+CHAR(39)+')'
--	END
--ELSE
--	BEGIN
--		IF @nType= 1
--			SET @SQL = @SQL + ' AND L.ATypeId = '+CHAR(39)+@aratypeID+CHAR(39)	
--		ELSE
--			SET @SQL = @SQL + ' AND L.ATypeId='+CHAR(39)+@apatypeID+CHAR(39)			
--	END
					
--IF @cid<>'0'
--	SET @SQL=@SQL+' AND L.cid='+@cid
	
--SET @SQL = @SQL + '	AND L.Audited = 1 AND L.billtype  in (424,423)
--			        GROUP BY L.BTypeid'
----print(@sql)
--EXEC(@SQL)


--处理优惠券
---------算发生额 end------------

--最后处理
SET @SQL='
SELECT	a.UserCode,
		a.FullName,
		a.ParId,
		a.SonNum,
		a.typeid,					
		arApTotal00 = SUM(ISNULL(b.ArApTotal00,0)),
		narApTotal00 = SUM(ISNULL(b.nArApTotal00,0)),
		arApTotal1 = SUM(ISNULL(b.ArApTotal1,0)),
		narApTotal1 = SUM(ISNULL(b.nArApTotal1,0)),
		arApTotal2 = SUM(ISNULL(b.araptotal2,0)),
		narApTotal2 = SUM(ISNULL(b.naraptotal2,0)),
		ysye = SUM(ISNULL(b.ArApTotal00,0))+ SUM(ISNULL(b.ArApTotal1,0))+ SUM(ISNULL(b.araptotal2,0)),
		nysye = SUM(ISNULL(b.nArApTotal00,0))+ SUM(ISNULL(b.nArApTotal1,0))+ SUM(ISNULL(b.naraptotal2,0))
FROM 	#Btype a
LEFT 	JOIN (
				SELECT	BTypeId,
						SUM(arApTotal00) AS arApTotal00,
						SUM(narApTotal00) AS narApTotal00,
						SUM(ArApTotal1) AS ArApTotal1,
						SUM(nArApTotal1) AS nArApTotal1,
						SUM(ArApTotal2) AS ArApTotal2,
						SUM(nArApTotal2) AS nArApTotal2
				FROM	#Result
				GROUP BY BTypeId
			) b	ON b.BTypeid LIKE a.typeid + ''%''
WHERE	1 = 1 '

IF @SonNum>=1
	SET @SQL = @SQL + ' AND A.ParId = '+CHAR(39)+@BTypeId+CHAR(39)
ELSE
	SET @SQL = @SQL + ' AND A.TypeId = '+CHAR(39)+@BTypeId+CHAR(39)

SET @SQL = @SQL + ' 
GROUP BY 
		a.UserCode,
		a.FullName,
		a.ParId,
		a.SonNum,
		a.typeid
ORDER BY A.UserCode '	

--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #Result,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#Btype,#GetManBTypeId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryETypeDetailGetBefore]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryETypeDetailGetBefore]
GO
















/*
	作者：谢吉康
	日期：2005-1-20
	描述：分支机构往来单位的应收、应付往来对帐查询此前余额
*/
CREATE PROCEDURE Web_QueryETypeDetailGetBefore
(
	@OperatorId		varchar(100),			--操作员的ID
	@ETypeId		varchar(100),			--职员ID
	@StartDate		varchar(12),			--开始日期
	@EndDate		varchar(12),			--截至日期
	@ShowRedWord	int,					--是否显示红冲单据  1.显示红冲单据   0.不显示红冲单据
	@Type			int,					--查询类别   1.应收    2.应付
	@BeforeMoney	 NUMERIC(24, 10)  OUTPUT	--此前余额
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBTypeId varchar(50), @MBTypeId2 varchar(50), @METypeId varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MDTypeId varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBTypeId OUTPUT,@MBTypeId2 OUTPUT,@METypeId OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MDTypeId OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--求此前余额
SELECT	@BeforeMoney =
		ISNULL(SUM(
					CASE 
						WHEN L.ATypeId = '0000100005' THEN ISNULL(L.Total,0)
						ELSE -1*ISNULL(L.Total,0)
					END
  		),0)
FROM	ListTable L,
		BillIndex Bil
WHERE	Bil.BillNumberId = L.BillNumberId
		AND (L.ATypeId = '0000100005' OR L.ATypeId='0000200001')
		AND L.Audited = 1								
		AND L.BillDate < @StartDate
		AND L.ETypeId LIKE @ETypeId+'%'
		AND L.ETypeId LIKE @METypeId+'%'
		AND (Bil.BTypeId LIKE @MBTypeId+'%' OR Bil.BTypeId LIKE @MBTypeId2+'%' OR ISNULL(Bil.BTypeId,'')='')
		AND (Bil.KTypeId LIKE @MKTypeId+'%' OR Bil.KTypeId2 LIKE @MKTypeId+'%'  OR ISNULL(Bil.KTypeId,'')='' OR ISNULL(Bil.KTypeId2,'')='')		
GROUP BY		
		L.ETypeId













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryETypeGiveDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryETypeGiveDetail]
GO
/*
  作者：彭勇
	日期：2012-06-26
	描述：添加dealbtypeid往来单位，以前的往来单位 改为结算单位
*/

/*
	作者：谢吉康
	日期：2005-4-19
	描述：职员赠送明细查询
----------------------------------------------------------
	Author：Wang Wei
	DateTime：20100-7-28
	Description：优化	
*/

/*
    修改: 舒珊
    日期: 2016-05-31
    描述: 增加表头、表体新增的自定义字段查询
    
     
    修改：舒珊
    日期：2016-05-27
    描述： 添加商品类别筛选
*/
CREATE PROCEDURE Web_QueryETypeGiveDetail
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	varchar(8000),	--往来单位ID
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@DtypeID		VARCHAR(max),	--部门ID
	@STypeId		varchar(max),
	@IsReporting	INT	,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.TypeId
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT typeid FROM F_GetAllBaseTypeId(@KTypeId,4)

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
--IF @MPtypeid='-99999'
--	INSERT INTO #GetManPTypeId(TypeId) 
--	SELECT p.TypeId FROM F_GetManDetailPType(@OperatorID) p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
--ELSE	
--	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@PTypeId,1)
	INSERT INTO #GetManPTypeId(TypeId) 	SELECT TypeId FROM F_ManPTypeInCategoryID ( @OperatorId,@PTypeId,@ptypecategoryid)
	
	
--结算单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999'  OR @MBtypeid2='-99999'
	INSERT INTO #GetManBTypeId(TypeId) 
	SELECT b.typeid FROM F_GetManDetailBType(@OperatorID) b INNER JOIN  F_GetAllBaseTypeId(@BTypeId,2) sb   ON b.typeid=sb.typeid
ELSE
	INSERT INTO #GetManBTypeId(TypeId) 	SELECT typeid FROM F_GetAllBaseTypeId(@BTypeId,2)
	
	
--往来单位
CREATE TABLE #GetMandealBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999'  OR @MBtypeid2='-99999'
	INSERT INTO #GetMandealBTypeId(TypeId) 
	SELECT b.typeid FROM F_GetManDetailBType(@OperatorID) b INNER JOIN  F_GetAllBaseTypeId(@dealbtypeid,2) sb   ON b.typeid=sb.typeid
ELSE
	INSERT INTO #GetMandealBTypeId(TypeId) 	SELECT typeid FROM F_GetAllBaseTypeId(@dealbtypeid,2)	
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @DtypeId<>''
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetManDetailDType(@OperatorID)

DECLARE @SQL 	varchar(8000)

SET	@SQL = '
			SELECT	Bil.BillNumberId,
					Bil.BillType,
					Bil.BillCode,
					Bil.BillDate,		
					Bil.ETypeId,
					Bil.BTypeId,
					bil.dealbtypeid,
					i.KTypeId,	
					Bil.STypeId,				
					ISNULL(ABS(SUM(I.Qty)),0) AS Qty,					
					ISNULL(ABS(SUM(I.CostTotal)),0) AS CostTotal,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32	
			FROM	BillIndex Bil INNER JOIN InOutStockTable I	ON	Bil.BillNumberId = I.BillNumberId
			left join Custom_BillIndex csindex on i.billnumberid=csindex.BillId and i.billtype=csindex.billtype
left join Custom_BillDetails csdetail on i.billnumberid=csdetail.BillId and i.billtype=csdetail.billtype AND i.id=csdetail.Detailid
			
			' 	
			IF @KTypeId<>'00000' OR @MKtypeid='-99999'
					SET	@SQL =@SQL+' INNER JOIN	#GetManKTypeId	k ON k.typeid=i.KTypeId'
			IF @MEtypeid='-99999' 		
					SET	@SQL =@SQL+' INNER JOIN	#GetManETypeId	e ON e.typeid=Bil.ETypeId'
			IF @DtypeId<>'' OR @MDtypeid='-99999'
				SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
			IF @PTypeId<>'00000' OR @MPtypeid='-99999' 		
					SET	@SQL =@SQL+' INNER JOIN	#GetManPTypeId	p ON p.typeid=I.PTypeId'
			IF @BTypeId<>'00000' OR @MBtypeid='-99999'  OR @MBtypeid2='-99999' 		
					SET	@SQL =@SQL+' INNER JOIN	#GetManBTypeId	b ON b.typeid=Bil.BTypeId'	
			IF @dealbtypeid<>'00000' OR @MBtypeid='-99999'  OR @MBtypeid2='-99999' 		
					SET	@SQL =@SQL+' INNER JOIN	#GetMandealBTypeId	b1 ON b1.typeid=Bil.dealbtypeid'				
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '						
SET	@SQL =@SQL+' 				
			WHERE	Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.Draft = 0
					AND Bil.BillType = 139
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
					AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
					AND Bil.ifYearBill=''0''	 --年节存标志
			GROUP BY
					Bil.BillNumberId,
					Bil.BillType,
					Bil.BillCode,
					Bil.BillDate,				
					Bil.ETypeId,
					Bil.BTypeId,
					bil.dealbtypeid,
					i.KTypeId,
					Bil.STypeId,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,
					SysDiy9_head,SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
					SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,SysDiy24_head,
					SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,SysDiy31_head,SysDiy32_head,
					SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,
					SysDiy9,SysDiy10,SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
					SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
					SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32		'
			

--PRINT(@SQL)
--EXEC(@SQL)

----------------------------------------------------------
--2014-04-03 杨俊修改，解决超过一页则不能打印、导出自定义字段信息问题
--IF(@IsReporting = 0)
--BEGIN
	--PRINT @SQL
	EXEC(@SQL)
--END
--ELSE IF(@IsReporting = 1)
--BEGIN
--	CREATE TABLE #tmp_result
--	(
--		billnumberid VARCHAR(100),
--		billtype     VARCHAR(100),
--		Costom1		VARCHAR(max),
--		Costom2		VARCHAR(max),
--		Costom3		VARCHAR(max),
--		Costom4		VARCHAR(max),
--		Costom5		VARCHAR(max),
--		Costom6		VARCHAR(max),
--		Costom7		VARCHAR(max),
--		Costom8		VARCHAR(max),
--		Costom9		VARCHAR(max),
--		Costom10	VARCHAR(max),
--		Costom11	VARCHAR(max),
--		Costom12	VARCHAR(max),
--		Costom13	VARCHAR(max),
--		Costom14	VARCHAR(max),
--		Costom15	VARCHAR(max),
--		Costom16	VARCHAR(max)
--	)

--	SET @SQL ='SELECT * INTO #temp1 FROM (' + @SQL + ') AS A ' + 
--			  ' 
--			   DECLARE @p1 dbo.TBType_SelfType  
--			   INSERT INTO @p1 SELECT billnumberid,billtype FROM #temp1 
--			   INSERT INTO #tmp_result EXEC Web_QueryCustomerDetail @p1 

--				--显示最终结果
--				SELECT a.*,
--						  b.Costom1,
--						  b.Costom2,
--						  b.Costom3,
--						  b.Costom4,
--						  b.Costom5,
--						  b.Costom6,
--						  b.Costom7,
--						  b.Costom8,
--						  b.Costom9,
--						  b.Costom10,
--						  b.Costom11,
--						  b.Costom12,
--						  b.Costom13,
--						  b.Costom14,
--						  b.Costom15,
--						  b.Costom16 
--						  FROM #temp1 a 
--						  left join #tmp_result b on a.billnumberid=b.billnumberid and a.billtype=b.billtype
						  
--				DROP TABLE #temp1,#tmp_result
--			   '
--	EXEC (@SQL)
--END	
------------------------------------------------------------

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetMandealBTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryETypeGiveLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryETypeGiveLine]
GO
/*
  作者：彭勇
	日期：2012-06-26
	描述：添加dealbtypeid往来单位，以前的往来单位 改为结算单位
*/


/*
	作者：谢吉康
	日期：2005-4-19
	描述：职员赠送线性查询
----------------------------------------------------------------------
	Author：Wang Wei 
	Datetime:2010-7-28
	Description：优化
	
	  
    修改：舒珊
    日期：2016-05-27
    描述： 添加商品类别筛选
*/
CREATE PROCEDURE Web_QueryETypeGiveLine
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	varchar(8000),	--往来单位ID
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@showZero		int,			--是否显示为零   0.显示   1.不显示为零
	@SortField		varchar(100),	--排序字段
	@SortType		varchar(100),	--排序方式
	@DtypeId		varchar(max),	--部门ID
	@STypeId		varchar(max),
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetManDetailEType(@OperatorID)

--仓库
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.TypeId
ELSE 
	INSERT INTO #GetManKTypeId(TypeId) SELECT typeid FROM F_GetAllBaseTypeId(@KTypeId,4)

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
--IF @MEtypeid='-99999'
--	INSERT INTO #GetManPTypeId(TypeId) 
--	SELECT p.TypeId FROM F_GetManDetailPType(@OperatorID) p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
--ELSE
--	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@PTypeId,1)
	INSERT INTO #GetManPTypeId(TypeId) 	SELECT TypeId FROM F_ManPTypeInCategoryID ( @OperatorId,@PTypeId,@ptypecategoryid)
	
	
--结算单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999'  OR @MBtypeid2='-99999'
	INSERT INTO #GetManBTypeId(TypeId) 
	SELECT b.typeid FROM F_GetManDetailBType(@OperatorID) b INNER JOIN  F_GetAllBaseTypeId(@BTypeId,2) sb   ON b.typeid=sb.typeid
ELSE
	INSERT INTO #GetManBTypeId(TypeId) 	SELECT typeid FROM F_GetAllBaseTypeId(@BTypeId,2)
	
	
--往来单位
CREATE TABLE #GetMandealBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999'  OR @MBtypeid2='-99999'
	INSERT INTO #GetMandealBTypeId(TypeId) 
	SELECT b.typeid FROM F_GetManDetailBType(@OperatorID) b INNER JOIN  F_GetAllBaseTypeId(@dealbtypeid,2) sb   ON b.typeid=sb.typeid
ELSE
	INSERT INTO #GetMandealBTypeId(TypeId) 	SELECT typeid FROM F_GetAllBaseTypeId(@dealbtypeid,2)	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @MDtypeid='-99999'
	INSERT INTO #GetManDTypeId(TypeId) 
	SELECT b.TypeId FROM F_GetManDetailDType(@OperatorID) b  INNER JOIN  F_GetAllBaseTypeId(@DTypeId,9) sb ON b.TypeId = sb.TypeId
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM	F_GetAllBaseTypeId(@DTypeId,9)

DECLARE @SQL 	varchar(8000)
SET	@SQL = '
			SELECT * INTO #GetManETypeAll FROM 	F_GetManETypeAll('+char(39)+@OperatorID+char(39)+') E  WHERE E.SonNum = 0
			
			SELECT	E.TypeId,
					E.SonNum,
					E.UserCode,
					E.FullName,
					ISNULL(ABS(SUM(A.Qty)),0) AS Qty,
					CASE
						WHEN ISNULL(ABS(SUM(A.Qty)),0)=0 THEN 0
						ELSE cast(ISNULL(ABS(SUM(A.CostTotal)),0)as NUMERIC(24, 10))/cast(ISNULL(ABS(SUM(A.Qty)),0) as NUMERIC(24, 10))
					END AS CostPrice,
					ISNULL(ABS(SUM(A.CostTotal)),0) AS CostTotal
			FROM 	#GetManETypeAll E
			LEFT JOIN (
					SELECT	Bil.ETypeId,
							ISNULL(SUM(I.Qty),0) AS Qty,
							ISNULL(I.CostPrice,0) AS CostPrice,
							ISNULL(SUM(I.CostTotal),0) AS CostTotal
					FROM	BillIndex Bil INNER JOIN InOutStockTable I	ON	Bil.BillNumberId = I.BillNumberId' 	
			IF @KTypeId<>'00000' OR @MKtypeid='-99999'
					SET	@SQL =@SQL+' INNER JOIN	#GetManKTypeId	k ON k.typeid=i.KTypeId'
			IF @MEtypeid='-99999' 		
					SET	@SQL =@SQL+' INNER JOIN	#GetManETypeId	e ON e.typeid=Bil.ETypeId'
			IF @DtypeId<>'' OR @MDtypeid='-99999'
				SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
			
			IF @PTypeId<>'00000' OR @MPtypeid='-99999' 		
					SET	@SQL =@SQL+' INNER JOIN	#GetManPTypeId	p ON p.typeid=I.PTypeId'
			IF @BTypeId<>'00000' OR @MBtypeid='-99999'  OR @MBtypeid2='-99999' 		
					SET	@SQL =@SQL+' INNER JOIN	#GetManBTypeId	b ON b.typeid=Bil.BTypeId'	
			IF @dealbtypeid<>'00000' OR @MBtypeid='-99999'  OR @MBtypeid2='-99999' 		
					SET	@SQL =@SQL+' INNER JOIN	#GetMandealBTypeId	b1 ON b1.typeid=Bil.dealBTypeId'			
					
						
			IF NOT (@STypeId = '' AND @MStypeid = '00000')
				SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '							
SET	@SQL =@SQL+' 
					WHERE	Bil.IfCheck = ''t''
							AND Bil.RedWord = 0
							AND Bil.Draft = 0
							AND Bil.BillType = 139
							AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
							AND Bil.BillDate<='+char(39)+@EndDate+char(39)+'
							AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)+'
							AND Bil.ifYearBill=''0''	 --年节存标志
					GROUP BY
							Bil.ETypeId,
							I.CostPrice							
			)A ON A.ETypeId = E.TypeId
			WHERE	1=1'
			
IF @ETypeId <> '00001'			
	SET	@SQL =@SQL+' AND E.TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)

			--是否显示数量为零
			IF @showZero = 1
				SET @SQL = @SQL + ' AND ISNULL(A.Qty,0)<>0 '		
			--排序方式
			SET @SQL = @SQL + '
				GROUP BY
					E.TypeId,
					E.SonNum,
					E.UserCode,
					E.FullName
				ORDER BY  '+CASE
								WHEN @SortField = 'Qty' THEN 'A.Qty'
								WHEN @SortField = 'CostTotal' THEN 'A.CostTotal'
								ELSE 'E.UserCode'
							END
						   +CASE
								WHEN @SortType = 0 THEN ' ASC'
								ELSE ' DESC'
							END
SET	@SQL =@SQL+' DROP TABLE #GetManETypeAll '
--PRINT(@SQL)
EXEC(@SQL)


DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetMandealBTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryETypeGiveList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryETypeGiveList]
GO

/*
  作者：彭勇
	日期：2012-06-26
	描述：添加dealbtypeid往来单位，以前的往来单位 改为结算单位
*/

/*
	作者：谢吉康
	日期：2005-4-19
	描述：职员赠送查询
--------------------------------------------------------
	Author：Wang WEi
	Datetime：2010-7-28
	Description：优化
	
		
	修改：舒珊
    日期：2015-05-27
    描述： 添加商品类别筛选
*/
CREATE PROCEDURE Web_QueryETypeGiveList
(
	@OperatorId		varchar(100),	--操作员ID
	@PTypeId		varchar(8000),	--商品ID
	@ETypeId		varchar(8000),	--职员ID
	@BTypeId		varchar(8000),	--结算单位ID
	@dealbtypeid	varchar(8000),	--往来单位ID
	@KTypeId		varchar(8000),	--仓库ID
	@StartDate		varchar(100),	--开始日期
	@EndDate		varchar(100),	--结束日期
	@DtypeId		varchar(max),	--部门ID
	@STypeId		varchar(max),
	@ptypecategoryid VARCHAR(MAX)    --商品类别ID
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查结束---------------------------------------------------

--职员
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
INSERT INTO #GetManETypeId(TypeId) SELECT * FROM F_GetManDetailEType(@OperatorID)

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @MKtypeid='-99999'
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.typeid FROM F_GetManDetailKType(@OperatorID) k INNER JOIN  F_GetAllBaseTypeId(@KTypeId,4) sk ON k.typeid=sk.TypeId
ELSE 
	INSERT INTO #GetManKTypeId(TypeId) SELECT typeid FROM F_GetAllBaseTypeId(@KTypeId,4)

--商品
CREATE TABLE #GetManPTypeId(TypeId	varchar(100))
IF @MEtypeid='-99999'	
	INSERT INTO #GetManPTypeId(TypeId) 
	SELECT p.TypeId FROM F_ManPTypeInCategoryID ( @OperatorId,@PTypeId,@ptypecategoryid) p INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp ON p.TypeId = sp.TypeId
else
	INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM F_ManPTypeInCategoryID ( @OperatorId,@PTypeId,@ptypecategoryid)

--结算单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999'  OR @MBtypeid2='-99999'
	INSERT INTO #GetManBTypeId(TypeId) 
	SELECT b.typeid FROM F_GetManDetailBType(@OperatorID) b INNER JOIN  F_GetAllBaseTypeId(@BTypeId,2) sb   ON b.typeid=sb.typeid
ELSE
	INSERT INTO #GetManBTypeId(TypeId) 	SELECT typeid FROM F_GetAllBaseTypeId(@BTypeId,2)
	
	
--往来单位
CREATE TABLE #GetMandealBTypeId(TypeId	varchar(100))
IF @MBtypeid='-99999'  OR @MBtypeid2='-99999'
	INSERT INTO #GetMandealBTypeId(TypeId) 
	SELECT b.typeid FROM F_GetManDetailBType(@OperatorID) b INNER JOIN  F_GetAllBaseTypeId(@dealbtypeid,2) sb   ON b.typeid=sb.typeid
ELSE
	INSERT INTO #GetMandealBTypeId(TypeId) 	SELECT typeid FROM F_GetAllBaseTypeId(@dealbtypeid,2)	
	

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END	

--部门
CREATE TABLE #GetManDTypeId(TypeId	varchar(100))
IF @MDtypeid='-99999'
	INSERT INTO #GetManDTypeId(TypeId) 
	SELECT b.TypeId FROM F_GetManDetailDType(@OperatorID) b  INNER JOIN  F_GetAllBaseTypeId(@DTypeId,9) sb ON b.TypeId = sb.TypeId
ELSE
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM	F_GetAllBaseTypeId(@DTypeId,9)
	
DECLARE @SQL 		varchar(8000),
		@SonNum 	int,
		@mxETypeId	varchar(100)

SELECT Top 1 @SonNum = SonNum FROM Employee WHERE TypeId = @ETypeId


SET	@SQL = '
			SELECT TypeId,SonNum,UserCode,FullName,ParId INTO #GetManETypeAll FROM  F_GetManETypeAll('+char(39)+@OperatorID+char(39)+') E
			 
			SELECT	Bil.ETypeId,
					ISNULL(SUM(I.Qty),0) AS Qty,
					ISNULL(I.CostPrice,0) AS CostPrice,
					ISNULL(SUM(I.CostTotal),0) AS CostTotal
			INTO #tmp
			FROM	BillIndex Bil INNER JOIN InOutStockTable I	ON	Bil.BillNumberId = I.BillNumberId' 	
	IF @KTypeId<>'00000' OR @MKtypeid='-99999'
			SET	@SQL =@SQL+' INNER JOIN	#GetManKTypeId	k ON k.typeid=i.KTypeId'
	IF @MEtypeid='-99999' 		
			SET	@SQL =@SQL+' INNER JOIN	#GetManETypeId	e ON e.typeid=Bil.ETypeId'
	IF @DtypeId<>'' OR @MDtypeid='-99999'
			SET	@SQL =@SQL+' INNER JOIN	#GetManDTypeId	d ON d.typeid=I.dTypeId '
	IF @PTypeId<>'00000' OR @MPtypeid='-99999' 	OR @ptypecategoryid<>''		
			SET	@SQL =@SQL+' INNER JOIN	#GetManPTypeId	p ON p.typeid=I.PTypeId'
	IF @BTypeId<>'00000' OR @MBtypeid='-99999'  OR @MBtypeid2='-99999' 		
			SET	@SQL =@SQL+' INNER JOIN	#GetManBTypeId	b ON b.typeid=Bil.BTypeId'	
	IF @dealbtypeid<>'00000' OR @MBtypeid='-99999'  OR @MBtypeid2='-99999' 		
			SET	@SQL =@SQL+' INNER JOIN	#GetMandealBTypeId	b1 ON b1.typeid=Bil.dealbtypeid'								
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bil.STypeId = S.TypeId '				
	SET	@SQL =@SQL+' 
			WHERE	Bil.IfCheck = ''t''
					AND Bil.RedWord = 0
					AND Bil.Draft = 0
					AND Bil.BillType = 139
					AND Bil.BillDate>='+char(39)+@StartDate+char(39)+'
					AND Bil.BillDate<='+char(39)+@EndDate+char(39)
	IF @ETypeId<>'00000'
		SET	@SQL =@SQL+' AND Bil.ETypeId LIKE '+char(39)+@ETypeId+'%'+char(39)
SET	@SQL =@SQL+' AND Bil.ifYearBill=''0''' --年节存标志	
SET	@SQL =@SQL+'
			GROUP BY
					Bil.ETypeId,
					I.CostPrice		


			SELECT	E.TypeId,
					E.SonNum,
					E.UserCode,
					E.FullName,
					ISNULL(ABS(SUM(A.Qty)),0) AS Qty,
					CASE
						WHEN ISNULL(ABS(SUM(A.Qty)),0)=0 THEN 0
						ELSE cast(ISNULL(ABS(SUM(A.CostTotal)),0)as NUMERIC(24, 10))/cast(ISNULL(ABS(SUM(A.Qty)),0)as NUMERIC(24, 10))
					END AS CostPrice,
					ISNULL(ABS(SUM(A.CostTotal)),0) AS CostTotal
			FROM 	#GetManETypeAll E
			left JOIN #tmp A ON LEFT(A.ETypeId,LEN(E.TypeId)) = E.TypeId
			WHERE	1=1 '

IF @SonNum = 0
	SET @SQL = @SQL + ' AND E.TypeId LIKE '+char(39)+@ETypeId+'%'+char(39)
ELSE
	SET @SQL = @SQL + ' AND E.ParId = '+char(39)+@ETypeId+char(39)


SET @SQL = @SQL + ' 
			GROUP BY
				E.TypeId,
				E.SonNum,
				E.UserCode,
				E.FullName
			ORDER BY E.UserCode
			DROP TABLE #GetManETypeAll 
			DROP TABLE #tmp '


--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#GetManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManSTypeId,#GetManDTypeId,#GetMandealBTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[WEB_QueryEtypeSalePlanTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_QueryEtypeSalePlanTotal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--------------------------------------------
--	作者：黄清
--	日期：2011-09-20
--	描述：职员销售计划表
---------------------------------------------
CREATE PROCEDURE WEB_QueryEtypeSalePlanTotal
(
	@fullname	VARCHAR(MAX)
)
--@encode$--
AS
SET NOCOUNT ON
SELECT	ep.ID AS planid,
		TotalID AS timeid,
		es.StypeID AS stypeid,
		es.DtypeID AS dtypeid,
		st.FullName AS tfullname,
		ep.FullName pfullname,
		MoneyUnit AS moneyunit,
		AllPlanValue AS AllPlanValue,
		AllRatingValue AS AllRatingValue,
		ep.Comment AS comment,
		CASE ep.IfUse 
			WHEN 1 THEN '启用'
			WHEN 2 THEN '未启用'
			ELSE '停用' 
		END AS ifused
FROM	EtypeSaleAllPlan ep
INNER JOIN SaleTimeTotal st ON ep.TotalID=st.ID 
INNER JOIN EtypeSaleplan es ON es.EplanID=ep.ID
WHERE 1=1
GROUP BY	EP.ID,
			TotalID,
			ES.StypeID,
			es.DtypeID,
			ST.FullName,
			ep.FullName,
			MoneyUnit,
			AllPlanValue,
			AllRatingValue,
			EP.Comment,
			EP.IfUse
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryEventLogList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryEventLogList]
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

-- 操作日志查询
-- 2002-7-11 王峰
CREATE       PROCEDURE [dbo].[Web_QueryEventLogList]
( 
-- @MagEType	varchar(25),
 @BeginDate	varchar(25)='',
 @EndDate	varchar(25)='',
 @EtypeName	varchar(66)='',    -- 操作员
 @IpAddr	varchar(256)='',  -- IP 地址
 @OrderBy	varchar(250)='',
 @FilterBill	varchar(250)='',
 @EventName     varchar(256)='',  --操作的名称
 @DoWhat	varchar(100)=''   --进行何种数据操作(查询还是删除)
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @SQLFrom  varchar(500)
DECLARE @SQLList  varchar(2000)
DECLARE @SQLWhere varchar(8000)
DECLARE @SQLOrder varchar(200)
DECLARE @Eventid  varchar(256)
DECLARE @Etypeid varchar(256)
SELECT @SQLFrom  = ''
SELECT @SQLList  = ''
SELECT @SQLWhere = ''
SELECT @SQLOrder = ''
-- 操作名称转操作ID
IF RTRIM(@EventName)<>''
   SELECT @Eventid=event.eventid from event where eventname=@EventName
--操作员名字转操作员ID
IF RTRIM(@EtypeName)<>''
   Select @Etypeid=employee.typeid from employee where fullname=@EtypeName
IF @DoWhat='Filter' or @DoWhat=''
BEGIN

CREATE TABLE #LOG
(
	[id]        	 NUMERIC(24, 10) ,
	eventdate 	datetime,
	etypeid 	varchar(50),
	eventid		varchar(8000),
	Ip 		varchar(50),
	deleted 	char(1),
	etype		varchar(100),
	etname 		varchar(100),
	logdata		VARCHAR(2000)
)

create table #event
(
	eventid varchar(8000),
	eventname varchar(200)
)

insert into #event 
select eventId,eventName from event 
UNION ALL
select eventId,eventName from plug_event 


insert into #event(eventId,eventName) values('systemLock','系统锁定')
insert into #event(eventId,eventName) values('doHelp','系统帮助')

-- 基本列表的SQL
SELECT @SQLFrom=' FROM EventLog el '
                                 +' LEFT OUTER JOIN #Event et ON el.EventId = et.EventID '
                                 +' LEFT OUTER JOIN employee e ON el.etypeid = e.typeId '				
-- 基本的显示字段
SELECT @SQLList = 'INSERT into #Log ([id],eventdate,etypeid,eventid,ip,deleted,etype,etname,logdata) SELECT el.id,el.eventdate,el.etypeid,el.eventid,el.ip,el.deleted'
		     +',ISNULL(e.FULLNAME,'''') AS etype '
		     +',ISNULL(et.EventName,'''') AS ETname '
		     +',ISNULL(el.logdata,'''') AS logdata '
-- 限制条件
IF RTRIM(@BeginDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND el.[EventDate]>=''' + RTRIM(@BeginDate) +' 00:00:00'' '
IF RTRIM(@EndDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND el.[EventDate]<=''' + RTRIM(@EndDate) +' 23:59:59'' '
IF RTRIM(@IpAddr)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND el.[Ip] LIKE ''%' + RTRIM(@IpAddr) +'%'' '
IF RTRIM(@EtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (e.[FullName] =''' + RTRIM(@EtypeName) +''' OR e.[UserCode] = ''' + RTRIM(@EtypeName) +''') '
IF RTRIM(@EventName)<>''
        --SELECT @SQLWhere = @SQLWhere + ' AND el.[EventId] =''' + ISNULL(RTRIM(@Eventid),'') +''''
        SELECT @SQLWhere = @SQLWhere + ' AND el.[EventId] IN (SELECT EventID FROM Event WHERE EventName LIKE ''%'+@EventName+'%'')'
SELECT @SQLWhere=@SQLWhere + ' AND el.deleted<>''1'''
-- 去掉多余的 AND
IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + Right(@SQLWhere,LEN(@SQLWhere)-4)
-- 排序
IF RTRIM(@OrderBy)<>''
	SELECT @SQLOrder = ' Order By ' + RTRIM(@OrderBy)


exec (@SQLList + @SQLFrom + @SQLWhere + @OrderBy)
PRINT (@SQLList + @SQLFrom + @SQLWhere + @OrderBy)

----------------------------------------插件添加----------------------------------------

SET @SQLWhere=''
-- 基本列表的SQL
SELECT @SQLFrom=' FROM plug_EventLog el '
                                 +' LEFT OUTER JOIN #Event et ON el.EventId = et.EventID '
                                 +' LEFT OUTER JOIN employee e ON el.etypeid = e.typeId '				
-- 基本的显示字段
SELECT @SQLList = 'INSERT into #Log ([id],eventdate,etypeid,eventid,ip,deleted,etype,etname,logdata) SELECT el.id,el.eventdate,el.etypeid,el.eventid,el.ip,el.deleted'
		     +',ISNULL(e.FULLNAME,'''') AS etype '
		     +',ISNULL(et.EventName,'''') AS ETname,'''''
-- 限制条件
IF RTRIM(@BeginDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND el.[EventDate]>=''' + RTRIM(@BeginDate) +' 00:00:00'' '
IF RTRIM(@EndDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND el.[EventDate]<=''' + RTRIM(@EndDate) +' 23:59:59'' '
IF RTRIM(@IpAddr)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND el.[Ip] LIKE ''%' + RTRIM(@IpAddr) +'%'' '
IF RTRIM(@EtypeName)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND (e.[FullName] =''' + RTRIM(@EtypeName) +''' OR e.[UserCode] = ''' + RTRIM(@EtypeName) +''') '
IF RTRIM(@EventName)<>''
        --SELECT @SQLWhere = @SQLWhere + ' AND el.[EventId] =''' + ISNULL(RTRIM(@Eventid),'') +''''
        SELECT @SQLWhere = @SQLWhere + ' AND el.[EventId] IN (SELECT EventID FROM plug_Event WHERE EventName LIKE ''%'+@EventName+'%'')'
SELECT @SQLWhere=@SQLWhere + ' AND el.deleted<>''1'''
-- 去掉多余的 AND

IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + Right(@SQLWhere,LEN(@SQLWhere)-4)
-- 排序
IF RTRIM(@OrderBy)<>''
	SELECT @SQLOrder = ' Order By ' + RTRIM(@OrderBy)

----------------------------------------插件添加----------------------------------------

	exec (@SQLList + @SQLFrom + @SQLWhere + @OrderBy)


IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName = 'IfQP' AND SubValue = '1')
BEGIN
	UPDATE #log SET etname =  REPLACE(etname,'商品','配件')
	UPDATE #log SET etname =  REPLACE(etname,'会员卡消费管理','会员消费管理')
END

UPDATE #log SET etname = REPLACE(etname,'VIP卡','会员')
UPDATE #log SET etname = REPLACE(etname,'VIP','会员')

select * from #log
 drop table #log,#event

END

IF @DoWhat='Delete'
BEGIN
   IF RTRIM(@BeginDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND EventDate>=''' + RTRIM(@BeginDate) +' 00:00:00'' '
   IF RTRIM(@EndDate)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND EventDate<=''' + RTRIM(@EndDate) +' 23:59:59'' '
   IF RTRIM(@IpAddr)<>''
	SELECT @SQLWhere = @SQLWhere + ' AND Ip LIKE ''%' + RTRIM(@IpAddr) +'%'' '
   IF RTRIM(@EtypeName)<>''
        SELECT @SQLWhere = @SQLWhere + ' AND etypeid='''+ @Etypeid + ''''
   IF RTRIM(@EventName)<>''
        SELECT @SQLWhere = @SQLWhere + ' AND eventid='''+ @Eventid + ''''
   SELECT @SQLWhere=@SQLWhere + ' AND deleted<>''1'''
   IF @SQLWhere<>''
	SELECT @SQLWhere=' WHERE ' + Right(@SQLWhere,LEN(@SQLWhere)-4)
   IF @EventName<>'' and @Eventid is Null RETURN -1
   IF @EtypeName<>'' and @Etypeid is Null RETURN -2
   exec ('Update eventlog set Deleted=''1'' '+ @SQLWhere )
   exec ('Update plug_EventLog set Deleted=''1'' '+ @SQLWhere )
END
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：谢吉康
	日期：2018-07-25
	描述：获取往来单位中的物流信息
*/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryExpress_Btype]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryExpress_Btype]
GO

CREATE PROCEDURE Web_QueryExpress_Btype
(
	@btypeid		VARCHAR(100)	--仓库ID
)
AS
SET NOCOUNT ON

SELECT	TOP 1 
		* 
FROM	btype
WHERE	typeid = @btypeid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
	作者：谢吉康
	日期：2018-07-25
	描述：获取仓库中的物流信息
*/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryExpress_Stock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryExpress_Stock]
GO

CREATE PROCEDURE Web_QueryExpress_Stock
(
	@ktypeid		VARCHAR(100)	--仓库ID
)
AS
SET NOCOUNT ON

SELECT	TOP 1 
		* 
FROM	stock 
WHERE	typeid = @ktypeid


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryExpressBtypeInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryExpressBtypeInfo]
GO

CREATE  PROCEDURE [dbo].[Web_QueryExpressBtypeInfo]
(
	@OperatorId		varchar(100),		--操作员Id	
	@TypeId			varchar(100),		--基本信息的Id
	@Filter			varchar(300)='',	--过滤 1、编号  2、名称  3、拼音码 4、联系电话
	@BTypeLx		varchar(10)='3'
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid varchar(50),@MStypeid varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--************************************************************单位基本信息************************************************************
		DECLARE @BTypeAll	int--,

			SELECT	@BTypeAll = Value FROM UserConfig WHERE ConfigName = 'BTypeAll'
			
		DECLARE @ex  INT
		IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerBTypeId = '00001' AND MangerBTypeId2 = '00002')
			SET	@ex=1
		ELSE 
			SET	@ex=0	
	
	
	DECLARE @bSonNum 	int,
			@bParId		VARCHAR(200)
	IF @ex=1	
		SELECT @bSonNum = SonNum,@bParId=ParId FROM 
		(
			SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted FROM F_GetManBTypeAll(@OperatorId)					
		) s
		 WHERE TypeId =@TypeId	
	ELSE 
		SELECT @bSonNum = SonNum,@bParId=ParId FROM BType WHERE TypeId =  @TypeId 
	DECLARE @Sql VARCHAR(MAX)
	SET @Sql='SELECT	TypeId,SonNum,UserCode,FullName FROM '
	IF @ex=1
		SET @Sql+=' (
					SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Tel1,Tel2,Tel3,Deleted FROM F_GetManBTypeAll('+CHAR(39)+@OperatorId+CHAR(39)+')  
				) a '
	ELSE
		SET @Sql+=' btype '
	
	IF @BTypeAll = 0	--客户和供货商不统一
		BEGIN
			IF @Filter = ''
				BEGIN
				IF @BTypeLx = '1' --客户
					SET @Sql+=' WHERE ParId ='+CHAR(39)+@TypeId+CHAR(39)+'  AND TypeId<>''00000'' AND TypeId LIKE ''00001%'' ORDER BY UserCode'  
				ELSE			 --供货商
					SET @Sql+=' WHERE ParId ='+CHAR(39)+@TypeId+CHAR(39)+'  AND TypeId<>''00000'' AND TypeId LIKE ''00002%'' ORDER BY UserCode' 					
				END
			ELSE
				BEGIN
					IF @BTypeLx = '1' --客户
						SET @Sql+=' WHERE SonNum = 0 AND (UserCode LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR FullName LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR PyCode LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel3 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel1 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel2 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+') AND TypeId <> ''00000'' AND TypeId LIKE ''00001%'' ORDER BY UserCode '							
					ELSE			--供货商
						SET @Sql+=' WHERE SonNum = 0 AND (UserCode LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR FullName LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR PyCode LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel3 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel1 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel2 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+') AND TypeId <> ''00000'' AND TypeId LIKE ''00002%'' ORDER BY UserCode '
				END	
		END
	ELSE				--客户和供货商统一
		BEGIN
			IF @TypeId = '00000'
				BEGIN
					IF @Filter = ''
						SET @Sql+=' WHERE ParId=''00000'' ORDER BY UserCode' 							
					ELSE
						SET @Sql+=' WHERE SonNum = 0 AND (UserCode LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR FullName LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR PyCode LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel3 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel1 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel2 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+') AND TypeId <> ''00000'' ORDER BY UserCode '										
				END
			ELSE
				BEGIN
					IF @Filter = ''
						SET @Sql+=' WHERE ParId='+CHAR(39)+@TypeId +CHAR(39)+' AND TypeId<>''00000'' ORDER BY UserCode' 							
					ELSE
						SET @Sql+=' WHERE SonNum = 0 AND (UserCode LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR FullName LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR PyCode LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel3 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel1 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+' OR Tel2 LIKE '+CHAR(39)+'%'+@Filter+'%'+CHAR(39)+') AND TypeId <> ''00000'' ORDER BY UserCode '										
				END
		END
	
	print(@sql)
	execute(@sql)	
	GO



 IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE id = object_id(N'[dbo].[Web_QueryF_B_R_SaleList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryF_B_R_SaleList
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===============================================
--create by :glj
--date:2013-07-11
--function description:财务 业务 对账
--================================================
CREATE PROC Web_QueryF_B_R_SaleList
(
	@StypeID		VARCHAR(50)='',		--分支机构ID
	@AtypeID		VARCHAR(MAX)='',	--科目ID
	@IsSelected		INT,
	@StartDate		VARCHAR(50),		--开始时间
	@EndDate		VARCHAR(50),		--结束时间 
	@OperatorID		VARCHAR(50),		--当前操作员
	@OrderBy		VARCHAR(50),		--排序类型
	@Flag 			varchar(10)='',     
	@total           NUMERIC(24, 10) =0  OUTPUT--当前科目期初
	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
----------------------------------------权限检查[BEGIN]-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN
DECLARE 
	@Re INT,
	@MAtypeid VARCHAR(50),
	@MBtypeid VARCHAR(50),
	@MBtypeid2 VARCHAR(50), 
	@MEtypeid VARCHAR(50),
	@MKtypeid VARCHAR(50), 
	@MPtypeid VARCHAR(50), 
	@MExpense VARCHAR(50), 
	@MIncome VARCHAR(50),
	@MCapital VARCHAR(50),
	@MDtypeid VARCHAR(50),
	@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep 
		@OperatorID,
		@MAtypeid OUTPUT,
		@MBtypeid OUTPUT,
		@MBtypeid2 OUTPUT,
		@MEtypeid OUTPUT,
		@MKtypeid OUTPUT,
		@MPtypeid OUTPUT,
		@MExpense OUTPUT,
		@MIncome OUTPUT,
		@MCapital OUTPUT,
		@MDtypeid OUTPUT,
		@MStypeid OUTPUT

IF @Re<>0 RETURN
----------------------------------------------权限检查[END]-------------------------------------------------------
DECLARE @Stype TABLE(TypeID	VARCHAR(50))
INSERT INTO @Stype(TypeID)--分支机构
SELECT TypeId FROM SType WHERE VerifyID=@StypeID

--=======================================得到所包含科目的业务单据【BEGIN】========================
DECLARE @Assets int=0,  --是否是固定资产卡片模式
		@Ifcreate int=0,--是否开账
		@createtime DATETIME  --开账日期
		
SELECT @Assets=SubValue FROM sysdata WHERE SubName='assets'
IF EXISTS(SELECT TOP 1 1 FROM SType_Config C,SType_UserConfig U 
						  WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND ISNULL(U.STypeID,'') = @STypeId AND U.Value='0') 
   OR NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType_UserConfig WHERE StypeId=@STypeId)
	SET @Ifcreate=0
ELSE 
	SET @Ifcreate=1			
DECLARE @creatyear INT
SELECT @creatyear=SubValue FROM dbo.sysdata WHERE SubName='fyear'
SELECT @createtime=FBegin FROM dbo.Ac_Period WHERE FYear=@creatyear AND FMonth=FPeriod
	
---如果没开账，这三个特殊处理
IF @Ifcreate=0 AND
  NOT EXISTS(SELECT TOP 1 1 FROM dbo.AType_Total WHERE Atypeid IN(30,31,37)  )
	BEGIN
		--库存商品总值
			IF EXISTS(SELECT ATypeId FROM Ac_Items_Detail D INNER JOIN @Stype S ON S.TypeID=D.STypeId AND D.nId=30 AND  D.ATypeId=@AtypeID)
				SET @total+=(SELECT ISNULl(SUM(ISNULL(I.Total,0)),0) FROM inigoodsstocks I INNER JOIN stock s on i.KtypeId=s.typeId INNER JOIN @Stype S1 ON S1.TypeID=S.STypeID)
			
			--修改委托代销期初(委托)
			IF EXISTS(SELECT ATypeId FROM Ac_Items_Detail D INNER JOIN @Stype S ON S.TypeID=D.STypeId AND D.nId=31 AND  D.ATypeId=@AtypeID)
				SET @total+=(SELECT ISNULl(SUM(ISNULL(I.CostTotal,0)),0) FROM inicommissionstock I INNER JOIN @Stype S ON S.TypeID=I.Stypeid AND I.Type=140)
			
			-- 修改代销商品期初（受托）
			IF EXISTS(SELECT ATypeId FROM Ac_Items_Detail D INNER JOIN @Stype S ON S.TypeID=D.STypeId AND D.nId=37 AND  D.ATypeId=@AtypeID)
				SET @total+=(SELECT ISNULL(SUM(ISNULL(I.Total,0)),0) as total FROM inicommissionstock I INNER JOIN @Stype S ON S.TypeID=I.Stypeid AND I.Type=144)
	END
	
--内部应收
IF EXISTS(SELECT ATypeId FROM Ac_Items_Detail D INNER JOIN @Stype S ON S.TypeID=D.STypeId AND D.nId=28 AND  D.ATypeId=@AtypeID)
		SET @total+= (SELECT  ISNULl(SUM(ISNULL(si.InnerARTotal00,0)),0)   AS total
						FROM dbo.SType_InnerARTotal si 
						JOIN  dbo.Ac_Items_Detail ai ON si.STypeID=ai.STypeId AND nid=28 AND ATypeId=@AtypeID
						JOIN @Stype S ON ai.STypeId=s.typeid 
						GROUP BY ATypeId)
 
DECLARE @Items TABLE(NId INT,STypeId VARCHAR(50))
INSERT INTO @Items(NId,STypeId)
SELECT DISTINCT D.nId,d.STypeId FROM Ac_Items_Detail D 
INNER JOIN @Stype S ON S.TypeID=D.STypeID AND D.ATypeId=@AtypeID

--内部应收特殊处理
IF EXISTS(SELECT ATypeId FROM Ac_Items_Detail D INNER JOIN @Stype S ON S.TypeID=D.STypeId AND D.nId=28 AND  D.ATypeId=@AtypeID)
	SELECT @total+=ISNULL(SUM(ISNULL(t.Total00,0)),0)  
	FROM AType_Total t 
	JOIN @Stype S ON  t.STypeID=s.TypeID
	WHERE t.ATypeID IN (SELECT NId FROM @Items) AND
	      t.STypeID IN (select stypeid from Ac_Items_Detail where nId=28 and ATypeId=@AtypeID)
ELSE 
	SELECT @total+=ISNULL(SUM(ISNULL(t.Total00,0)),0)  
	FROM AType_Total t 
	JOIN @Stype S ON  t.STypeID=s.TypeID
	WHERE t.ATypeID IN (SELECT NId FROM @Items) AND
	t.STypeID IN (select stypeid from Ac_Items_Detail where  ATypeId=@AtypeID)

IF @StartDate>=@createtime	
	BEGIN
		IF EXISTS(SELECT ATypeId FROM Ac_Items_Detail D INNER JOIN @Stype S ON S.TypeID=D.STypeId AND D.nId=28 AND  D.ATypeId=@AtypeID) --内部应收特殊处理
			SELECT @total+=ISNULL(SUM(ISNULL(L.Total,0)),0) 
			FROM ListTable L
			JOIN @Stype S ON  L.STypeID=s.TypeID
			WHERE L.BillDate<@StartDate	AND  
				  L.AtypeId IN(SELECT NId FROM @Items) AND
				  L.STypeID IN (select stypeid from Ac_Items_Detail where nId=28 and ATypeId=@AtypeID)
		ELSE 
			SELECT @total+=ISNULL(SUM(ISNULL(L.Total,0)),0) 
			FROM ListTable L
			JOIN @Stype S ON  L.STypeID=s.TypeID
			WHERE L.BillDate<@StartDate	AND  L.AtypeId IN(SELECT NId FROM @Items) AND
				  L.STypeID IN (select stypeid from Ac_Items_Detail where  ATypeId=@AtypeID)
	END
	
IF @Flag='00' -- 只得到科目余额
BEGIN
	RETURN 0
END

DECLARE @RetTable TABLE(jetotal  NUMERIC(24, 10) ,ltTotal  NUMERIC(24, 10) ,BillDate DATETIME,BillCode VARCHAR(200),Stypeid VARCHAR(50),BillType NUMERIC(10,0),Comment VARCHAR(256),etypeid VARCHAR(50),BillNumberId NUMERIC(10, 0),PostTime DATETIME)
 INSERT INTO @RetTable(jetotal,ltTotal,BillDate,BillCode,Stypeid,BillType,Comment,etypeid,BillNumberId,PostTime)
 SELECT --过账类
	jetotal=0.0000000000,
	lt.Total AS ltTotal,
	i.BillDate,
	i.BillCode,
	i.Stypeid,
	i.BillType,
	i.Comment,
	i.etypeid,
	i.BillNumberId,
	i.posttime
FROM ListTable lt
LEFT JOIN BillIndex I ON lt.BillNumberID=i.BillNumberID AND i.RedWord=0
INNER JOIN @Items s ON lt.STypeID=s.sTypeID AND s.NId=lt.AtypeId
WHERE I.BillDate BETWEEN @StartDate AND @EndDate

--内部应收
IF EXISTS(SELECT ATypeId FROM Ac_Items_Detail D INNER JOIN @Stype S ON S.TypeID=D.STypeId AND D.nId=28 AND  D.ATypeId=@AtypeID)
	delete from @RetTable where Stypeid not in (select stypeid from Ac_Items_Detail where nId=28 and ATypeId=@AtypeID)

-- 排序
IF RTRIM(ISNULL(@OrderBy,''))='' OR @OrderBy='ByDate_a'
	SELECT  * FROM @RetTable ORDER BY BillDate ASC,PostTime ASC
ELSE IF @OrderBy ='ByDate_d'
	SELECT  * FROM @RetTable ORDER BY BillDate DESC,PostTime DESC
IF @OrderBy ='ByBillNo_a'
	SELECT  * FROM @RetTable ORDER BY BillCode ASC,PostTime ASC
IF @OrderBy ='ByBillNo_d'
	SELECT  * FROM @RetTable ORDER BY BillCode DESC,PostTime DESC
IF @OrderBy ='ByBillID_a'
	SELECT  * FROM @RetTable ORDER BY PostTime ASC
IF @OrderBy ='ByBillID_d'
	SELECT  * FROM @RetTable ORDER BY PostTime DESC
--======================================得到所包含科目的业务单据【END】  ===========================


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactDraft]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactDraft]
GO
/*
	作者：魏伟
	日期：2016-07-08
	描述：实物仓库草稿查询
 
*/

CREATE PROCEDURE Web_QueryFactDraft
( 
	@OperatorID 		VARCHAR(100) = '', 	-- 操作员ID
	@startdate  		VARCHAR(25),        --开始时间
	@EndDate  			VARCHAR(25),        --结束时间
	@EtypeId  			VARCHAR(MAX),       --经手人ID
	@KTypeId  			VARCHAR(MAX),       --仓库ID
	@OutKTypeId			VARCHAR(800),       --仓库ID    
	@BillType  			VARCHAR(MAX)  = '', --单据类型
	@InOutStockType     VARCHAR(MAX)  = '', --出入库类型
	@BillCode 			VARCHAR(200) = '',  --单据编号
	@comment 			VARCHAR(256)= '',   --摘要
	@explain			VARCHAR(300)='',    --说明
	@bzcomment      	VARCHAR(256)= '',   --备注 
	@AudState			VARCHAR(10)='',		-- 单据审核状态
	@usercode			VARCHAR(50)='',		--制单人编号
	@fullname			VARCHAR(256)='',	--制单人名称
	@PageNO             int,
	@sTypeId            VARCHAR(MAX)='00001',  --分支机构ID     
	@chrFlag			char(1)		  ='1',	-- 功能标识：1 - 分页查询记录；2 - 打印查询所有记录；3 - 合计值
	@UserDeRowCount		INT,
	@OrderBy            VARCHAR(50)=''
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1


DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
----------------------------------------------------查看操作员的权限----------------------------------------------------
IF @BillType = '-1'
	SET @BillType = ''
	
DECLARE @EFullName VARCHAR(200)=(SELECT FullName FROM dbo.employee WHERE typeId=@OperatorID)	
	
-- 限制Ktype
CREATE TABLE #KType(TypeId		varchar(100))
CREATE TABLE #KType2(TypeId		varchar(100))
IF RTRIM(@KTypeId)<>''
	BEGIN
		SET @KTypeId = LTRIM(RTRIM(@KTypeId))
		IF CHARINDEX(',',@BillType)=0 AND @BillType IN (420)
		BEGIN
			INSERT INTO #KType(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@KTypeId,4) S
		END
		ELSE
		BEGIN
			INSERT INTO #KType(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S
		END
	END
	ELSE
	BEGIN
	    INSERT INTO #KType(TypeId) SELECT S.TypeId FROM  F_GetManDetailKType(@OperatorID) S
	END

IF RTRIM(@OutKTypeId)<>''
BEGIN
	SET @OutKTypeId = LTRIM(RTRIM(@OutKTypeId))
	IF CHARINDEX(',',@BillType)=0 AND @BillType IN (420)
	BEGIN
		INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM F_GetAllBaseTypeId(@OutKTypeId,4) S 
	END
	ELSE
	BEGIN
		INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@OutKTypeId,4,@OperatorID) S
	END
END
ELSE
BEGIN
    INSERT INTO #KType2(TypeId) SELECT S.TypeId FROM  F_GetManDetailKType(@OperatorID) S
END

--------------------------设置3种权限的标识-------------------------
DECLARE @SQL_WHERE VARCHAR(MAX)
SELECT @SQL_WHERE= ''
DECLARE @SQL_WHERE_SZ VARCHAR(MAX)
SELECT @SQL_WHERE_SZ= ''

SELECT @SQL_WHERE =' WHERE 	a.[BillDate]>=''' + @startdate +'''
							AND a.[BillDate]<=''' + @EndDate +''' 
							AND a.IfCheck=''f'' 
							AND a.draft=1 '


--权限处理部分
DECLARE @re_pass		INT,
		@re_check		INT,
		@offset_pass	INT,	--过帐权限
		@offset_check	INT		--审核人审核他人草稿权限

SELECT @offset_pass = 119		--过帐权限
SELECT @offset_check = 467		--查看他人业务草稿
EXEC @re_check=GP_CheckLimit @OperatorID,@offset_check
--IF @re_check = 1
--BEGIN
--    DECLARE @EFullName VARCHAR(200)=(SELECT FullName FROM dbo.employee WHERE typeId=@OperatorID)
--	SET @SQL_WHERE = @SQL_WHERE + ' AND (a.Checke = '''+@EFullName+''' OR ISNULL(a.Checke,'''') = '''')'
--END									
IF @BillType <> ''---单据类型
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillType IN (SELECT * FROM F_Split('''+@BillType+''','',''))'
ELSE 
	SET @SQL_WHERE = @SQL_WHERE + 'and A.BILLTYPE IN (418,419,420)' 

IF @BillCode <>''--单据名称
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.[BillCode] LIKE ''%' + @BillCode +'%'''
IF @Comment <>''--摘要
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.[Comment] LIKE ''%' + @Comment +'%'''
IF @explain <>''--说明
	SELECT @SQL_WHERE = @SQL_WHERE + ' AND a.[Explain] LIKE ''%' + @explain +'%'''
	
--IF @usercode<>''		--制单人编号
--	SELECT @SQL_WHERE = @SQL_WHERE + ' AND e.usercode LIKE ''%' + @usercode +'%'''
--IF @fullname<>''	--制单人名称
--	SELECT @SQL_WHERE = @SQL_WHERE + ' AND e.fullname LIKE ''%' + @fullname +'%'''
	
--3.9加筛选条件
 

IF @AudState = '9'
	SET @SQL_WHERE = @SQL_WHERE + ' AND 1 = 1 '
ELSE IF @AudState = '1'
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillNumberId IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 7 AND IfAudit = 1) '
ELSE IF @AudState = '2'
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillNumberId IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 7 AND IfAudit = 0) '
ELSE IF @AudState = '3'
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillNumberId IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 7 AND IfAudit = -1) '
ELSE IF @AudState = '4'
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.BillNumberId NOT IN (SELECT BillNumberId FROM AuditingBill WHERE BillIndexType = 7) '
	
--筛选出入库单据类型
IF @InOutStockType <> ''
	SET @SQL_WHERE = @SQL_WHERE + ' AND a.FromBillType IN (SELECT * FROM dbo.f_split('''+@InOutStockType+''','','')) '
	

DECLARE @TEMPSQL VARCHAR(MAX)='' --权限语句in改为inner join

--备注	
IF @bzcomment<>''
BEGIN

	-- 建立包含一个BillNumberID字段的临时表
		CREATE TABLE #commentTable(billnumberid INT)	
		DECLARE @TempTableSQL varchar(2000)
        
        SELECT @TempTableSQL=' INSERT INTO #commentTable
							   SELECT DISTINCT billnumberid FROM FactInOut WHERE COMMENT LIKE ''%'+@bzcomment+'%'' 
							   UNION ALL
							   SELECT DISTINCT billnumberid FROM FactDepotInOut WHERE COMMENT LIKE ''%'+@bzcomment+'%'' 
							   '
        EXEC(@TempTableSQL)
        
	SET @TEMPSQL+='INNER JOIN #commentTable COM ON  A.BillNumberID =COM.billnumberid'
				   
END
--职员
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S
IF NOT (@ETypeId='' AND @METypeId = '00001')
	BEGIN
		IF @EtypeId = ''
			BEGIN
				SET @SQL_WHERE = @SQL_WHERE + ' AND (a.ETypeId IN (SELECT * FROM #GetManETypeId) OR ISNULL(a.ETypeId,'''') = '''') '
			END
		ELSE
			SELECT @TEMPSQL = @TEMPSQL + ' INNER JOIN #GetManETypeId EL ON a.ETypeId=EL.TypeId '		
	END


--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID) S
IF NOT (@sTypeId='' AND @MStypeid = '00000')
BEGIN
	--当单据为资金调拨单，并且调出机构未选择时。 将 调出、调入机构的关系变为OR（主要根据调入机构来查询）
	IF(@BillType = '310' AND @sTypeId = '')
		SET @TEMPSQL = @TEMPSQL
	ELSE --否则为AND
		SET @TEMPSQL = @TEMPSQL + ' INNER JOIN #GetManSTypeId SL ON a.Stypeid=SL.TypeId '
END

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT * FROM F_GetManDetailKType(@OperatorID)
IF @KTypeId = '' AND @OutKTypeId = ''
	  SET @SQL_WHERE = @SQL_WHERE + 'and (A.KTypeId IN (SELECT * FROM #KType) or A.KTypeId=''''  )AND (a.KTypeId2 in (SELECT * FROM #KType2) or A.KTypeId2='''' )' 
IF(@KTypeId='' AND @OutKTypeId<>'')
    SET @SQL_WHERE = @SQL_WHERE + 'and (A.KTypeId IN (SELECT * FROM #KType) or A.KTypeId=''''  )AND a.KTypeId2 in (SELECT * FROM #KType2) ' 
 IF(@KTypeId<>'' AND @OutKTypeId='')
    SET @SQL_WHERE = @SQL_WHERE + 'and A.KTypeId IN (SELECT * FROM #KType)   AND( a.KTypeId2 in (SELECT * FROM #KType2) or A.KTypeId2='''')' 
ELSE IF (@KTypeId<>'' AND @OutKTypeId<>'')
 SET @SQL_WHERE = @SQL_WHERE + 'and A.KTypeId IN (SELECT * FROM #KType)   AND  a.KTypeId2 in (SELECT * FROM #KType2) ' 

DECLARE @re_re INT
EXEC @re_re=GP_CheckLimit @OperatorID,@Offset_pass

------处理单据查看权限------
IF @re_re = 0
BEGIN
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ''
END
ELSE 
BEGIN
	SELECT @SQL_WHERE_SZ = '( '

	EXEC @re_re=Gp_CheckLimit @OperatorID,4829
	IF @re_re = 0															--仓库入库单  
		SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' a.BillType = 418 or'
	EXEC @re_re=Gp_CheckLimit @OperatorID,4837
	IF @re_re = 0															--仓库出库单  
		SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' a.BillType = 419 or'	
	EXEC @re_re=Gp_CheckLimit @OperatorID,4845
	IF @re_re = 0															--仓库调拨单  
		SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' a.BillType = 420 or'	

	SELECT @SQL_WHERE_SZ = @SQL_WHERE_SZ + ' a.BillType = 1000 )  '			--随便添加一个BillType用来拼凑字符串
	
	SELECT @SQL_WHERE= @SQL_WHERE + ' AND ' + @SQL_WHERE_SZ
END
--======END=====--

--(筛选库存商品)
CREATE TABLE #GetManPTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManPTypeId(TypeId) SELECT TypeId FROM  dbo.F_GetManDetailPType(@OperatorID)

--------------------------------------------------------------处理页面---------------------------------------------------------------------------
DECLARE @SQL VARCHAR (MAX)
DECLARE @SQL_COUNT VARCHAR (MAX)
DECLARE @RowCount INT

CREATE TABLE #temp1
(
	BillNumberId 	numeric(10,0),  
	Billdate 		datetime, 
	BillCode 		VARCHAR(200),
	BillType 		int,
	redword  		int,
	FromBillType       int,
	Comment 		VARCHAR(256),
	explain 		VARCHAR(256),
	totalqty 		 NUMERIC(24, 10) ,
	checke			VARCHAR(MAX),
	CheckeName   VARCHAR(MAX),  
	etype 			VARCHAR(100),  
	btype  			VARCHAR(100),
	stypeid  		VARCHAR(100), 
	dtypeid  		VARCHAR(100),
	ktypeid  		VARCHAR(100),
	ktypeid2  		VARCHAR(100),
	CheckTime			DATETIME,			--制单时间
	updatefullname		VARCHAR(50),		--修改人
	LastUpdateTime		DATETIME,			--修改时间' 
	auditedname		VARCHAR(MAX),
	PRINTCOUNT		INT  ,
	[sid] [numeric](10, 0) IDENTITY (1, 1) NOT NULL
)

--处理排序
DECLARE @orderyWhere VARCHAR(1000)   =''



IF @chrFlag = '1'		--分页查询记录-------------------------------------------------------------------------------------------
BEGIN
	SELECT @SQL ='
		SELECT	a.BillNumberId,  
				a.BillDate, 
				a.BillCode,
				a.BillType,
				a.redword,
				a.FromBillType, 
				a.Comment AS Comment,
				a.explain as explain,
				a.totalqty as totalqty,
				a.checke,
				E.FullName AS CheckeName,  
				ISNULL(A.ETypeId,'''') AS EfullName, 
				ISNULL(a.dealbtypeid,'''') AS btype,
				ISNULL(A.Stypeid,'''') AS Stypeid, 
				ISNULL(A.Dtypeid,'''') AS Dtypeid,
				ISNULL(A.Ktypeid,'''') AS Ktypeid,
				ISNULL(A.Ktypeid2,'''') AS Ktypeid2,
				a.checktime,
				e1.fullname as updatefullname,
				a.lastupdatetime, 
				CASE
						WHEN Ad.IfAudit = 0  THEN ''待 审 核''
						WHEN Ad.IfAudit = 1  THEN ''审核通过''
						WHEN Ad.IfAudit = -1 THEN ''审核不通过''
						ELSE ''无需审核''
					END AS auditedname,
					ISNULL(PR.printcount,'''') AS PrintCount 
		FROM 	FactIndex a  
		INNER JOIN Employee E ON E.TypeId = A.Checke '

	IF @re_check = 1
		BEGIN			
			SET @SQL = @SQL + ' AND (a.Checke = '''+@EFullName+''' OR ISNULL(a.Checke,'''') = '''')'
		END		
		
	IF @usercode<>''		--制单人编号
		SELECT @SQL = @SQL + ' AND e.usercode LIKE ''%' + @usercode +'%'''
	
	IF @fullname<>''	--制单人名称
		SELECT @SQL = @SQL + ' AND e.fullname LIKE ''%' + @fullname +'%'''
		
SET @SQL = @SQL + '		
		LEFT  JOIN Employee E1 ON a.updatee =E1.typeid
		LEFT JOIN btype or_bt1 ON a.dealbtypeid=or_bt1.typeID
		LEFT JOIN AuditingBill Ad ON Ad.BillNumberId = A.BillNumberId AND Ad.BillIndexType = ''7''
		LEFT JOIN 
				(
					SELECT	SUM(PrintCount) AS printcount,billnumberid ,billtype
					FROM	PrintRecord 
					WHERE	billtype not in (300,301)
					GROUP BY billnumberid,billtype
				) AS PR  ON a.BillNumberId = PR.billnumberid  and a.BillType=pr.billtype'
END				
ELSE IF @chrFlag= '2'-- 打印查询所有记录--------------------------------------------------------------------------------------
BEGIN
	SELECT @SQL ='
		SELECT	a.BillNumberId, 
				a.BillDate, 
				a.BillCode,
				a.BillType,
				a.redword,
				a.FromBillType, 
				a.Comment AS Comment,
				a.explain as explain,
				a.totalqty as totalqty,
				a.checke,
				ISNULL(E.fullname,'''') AS CheckeName,  
				ISNULL(A.ETypeId,'''') AS EfullName, 
				ISNULL(a.dealbtypeid,'''') AS btype,
				ISNULL(A.Stypeid,'''') AS Stypeid, 
				ISNULL(A.Dtypeid,'''') AS Dtypeid,		
				ISNULL(CASE
					WHEN A.BillType = 188 THEN A.KTypeId2
					ELSE A.KTypeId
				END,'''') AS Ktypeid,
				ISNULL(CASE
					WHEN A.BillType = 160 THEN A.KTypeId2
					ELSE A.ktypeid 
				END,'''') AS Ktypeid1,
				ISNULL(CASE
					WHEN A.BillType = 160 THEN A.KTypeId
					ELSE A.KTypeId2
				END,'''') AS Ktypeid2,				
				CASE
					WHEN Ad.IfAudit = 0  THEN ''待 审 核''
					WHEN Ad.IfAudit = 1  THEN ''审核通过''
					WHEN Ad.IfAudit = -1 THEN ''审核不通过''
					ELSE ''无需审核''
				END AS auditedname,
				a.checktime,
				e1.fullname as updatefullname,
				a.lastupdatetime, 
				ISNULL(PR.printcount,'''') AS PrintCount 
		FROM 	FactIndex a   
		INNER  JOIN Employee E ON a.Checke =E.typeid
		LEFT  JOIN Employee E1 ON a.updatee =E1.typeid
		LEFT JOIN AuditingBill Ad ON Ad.BillNumberId = A.BillNumberId AND Ad.BillIndexType = ''7''
		LEFT JOIN 
					(
						SELECT	SUM(PrintCount) AS printcount,billnumberid 
						FROM	PrintRecord 
						WHERE	billtype not in (300,301)
						GROUP BY billnumberid
					) AS PR  ON a.BillNumberId = PR.billnumberid '
					
	IF @re_check = 1
		BEGIN			
			SET @SQL = @SQL + ' AND (a.Checke = '''+@EFullName+''' OR ISNULL(a.Checke,'''') = '''')'
		END		
		
	IF @usercode<>''		--制单人编号
		SELECT @SQL = @SQL + ' AND e.usercode LIKE ''%' + @usercode +'%'''
	
	IF @fullname<>''	--制单人名称
		SELECT @SQL = @SQL + ' AND e.fullname LIKE ''%' + @fullname +'%'''					
END					
ELSE	--取合计--------------------------------------------------------------------------------------------------------------
BEGIN
	SELECT @SQL ='	SELECT	SUM(isnull(a.TotalQty,0)) as TotalQty
					FROM FactIndex a '
END					
 
IF @chrFlag<>'3'
	SET @SQL += @orderyWhere

IF @chrFlag = '3'
	SET @SQL='select	SUM(ISNULL(tindex.totalqty,0)) AS totalqty
			  from ( 
					SELECT	BillNumberId,
							SUM(isnull(a.TotalQty,0)) as TotalQty
					FROM FactIndex a 
					GROUP BY BillNumberId
				) tindex 
			  inner join factindex  a on tindex.billnumberid=a.billnumberid
				' +@TEMPSQL +@SQL_WHERE	
ELSE
	SET @SQL='select 
					tindex.BillNumberId,  
					tindex.BillDate, 
					tindex.BillCode,
					tindex.BillType,
					tindex.redword,
					tindex.FromBillType, 
					tindex.Comment AS Comment,
					tindex.explain as explain,
					tindex.totalqty,
					tindex.checke,
					tindex.CheckeName,  
					tindex.EfullName, 
					tindex.btype,
					tindex.Stypeid, 
					tindex.Dtypeid,
					tindex.Ktypeid,
					tindex.Ktypeid2,
					tindex.checktime,
					tindex.updatefullname,
					tindex.lastupdatetime, 
					tindex.auditedname,
					tindex.PrintCount 
			 from ( '+@SQL+' ) tindex 
			 inner join factindex  a on tindex.billnumberid=a.billnumberid
				' +@TEMPSQL +@SQL_WHERE

DECLARE @SQLUnion VARCHAR(MAX)

IF @chrFlag= '3' --显示合计值
BEGIN
	--PRINT @SQL
	EXEC(@SQL)
	DROP TABLE #GetManETypeId,#GetManKTypeId,#GetManPTypeId,#GetManSTypeId,#temp1
	
	RETURN
END

 

	
IF @UserDeRowCount = 0
	SET @UserDeRowCount = 14

DECLARE @PageNum int
DECLARE @PageBegin int
DECLARE @PageEnd int

IF @chrFlag = '1'	--分页查询
	BEGIN
		CREATE TABLE #Result
		(
			BillNumberId		numeric(18,0), 
			BillDate			datetime,
			BillCode			VARCHAR(300),
			BillType			VARCHAR(300),
			redword  		    int,
	        FromBillType           VARCHAR(300),
			BType				VARCHAR(200),
			TotalQty			 NUMERIC(24, 10) ,  
			checke			varchar(max),
			CheckeName		VARCHAR(200),
			Comment				VARCHAR(300),
			Explain				VARCHAR(300),
			TotalNum			int,
			EFullName			VARCHAR(200), 
			IsAudit				int	,			-- 是否有审核	0.待审核  1.审核通过 -1.审核不通过 2.无需审核 3.不满足条件无需提交审核 4.满足条件但是没有提交审核.
		    IsPass				int,			-- 是否有过账的权限	0.没有 1.有	
		    stypeid  			VARCHAR(100), 
		    dtypeid  			VARCHAR(100),
		    ktypeid  			VARCHAR(100),
		    ktypeid1  			VARCHAR(100),
		    ktypeid2  			VARCHAR(100),
		    CheckTime			DATETIME,			--制单时间
		    updatefullname		VARCHAR(200),		--修改人
		    LastUpdateTime		DATETIME,			--修改时间 
		    auditedname		VARCHAR(MAX),
		    PRINTCOUNT		INT ,
		    [sid] [numeric](10, 0) IDENTITY (1, 1) NOT NULL
	)

		SET @SQL ='	INSERT INTO #temp1 ' +@SQL 
		
		--PRINT(@SQL) /*最终业务SQL,出问题一般看这里*/		
		EXEC(@SQL)		

		--9.4客户希望和9.2一样，排序后页面保持不动
		--超出最后一页，则自动跳转到最后一页
		SET @RowCount = @@ROWCOUNT
		IF(@PageNo > CEILING(CAST(@RowCount AS NUMERIC(18,0)) / CAST(@UserDeRowCount AS NUMERIC(18,0))))
			SET @PageNo = CEILING(CAST(@RowCount AS NUMERIC(18,0)) / CAST(@UserDeRowCount AS NUMERIC(18,0)))
		
		SET @PageNum = @PageNo * @UserDeRowCount
		SET @PageBegin = (@PageNo - 1) * @UserDeRowCount + 1
		SET @PageEnd = (@PageNo) * @UserDeRowCount
		-------------------------------------------
	 
		SET @SQL = '
				INSERT INTO #Result
				SELECT 	a.BillNumberId, 
						a.BillDate,
						a.BillCode,
						a.BillType,
						a.redword ,
	                    a.FromBillType,
						a.BType,
						a.TotalQty,  
						a.checke,
						a.CheckeName,
						a.Comment,
						a.Explain,
						'+Convert(VARCHAR(100),@RowCount)+' as TotalNum ,
						a.etype, 
						2 AS IsAudit,
						0 AS IsPass,
						a.stypeid, 
						a.dtypeid,
						CASE
							WHEN A.BillType = 188 THEN a.KTypeId2
							ELSE A.KTypeId
						END AS ktypeid,
						CASE
							WHEN a.BillType = 160 THEN a.KTypeId2
							ELSE a.ktypeid 
						END AS ktypeid1,
						CASE
							WHEN a.BillType = 160 THEN a.KTypeId
							ELSE a.KTypeId2
						END AS ktypeid2,
						a.checktime,
						A.updatefullname,
						a.lastupdatetime, 
						A.auditedname,
						A.PRINTCOUNT
				FROM 	#temp1 a 
				WHERE 	A.sid >= '+CAST(@PageBegin AS VARCHAR(20)) +'
						AND A.sid <= '+CAST(@PageEnd AS VARCHAR(20))+'
				ORDER BY A.SID'

				--PRINT(@SQL)	
				EXEC(@SQL)						
					
			DECLARE @nBillId	numeric(18,0),
					@nBillType	int,
					@IsPass		int,
					@nPass		int,
					@IsAudit	int

			--判断过账权限
			EXEC @nPass = GP_CheckLimit @OperatorID,119
	
			DECLARE bCursor CURSOR FOR			
				SELECT BillNumberId,BillType FROM #Result
			OPEN bCursor
			FETCH NEXT FROM bCursor INTO @nBillId,@nBillType
			WHILE @@FETCH_STATUS = 0
				BEGIN
					IF @nPass = 1 	--没有
						SET @IsPass = 0
					ELSE
						EXEC @IsPass = Gp_CheckLimitBillType @OperatorID,0,@nBillType
	
					--检查审核
					EXEC @IsAudit = Gp_CheckBillAuditingState @nBillId,@nBillType
	
					--修改状态
					UPDATE #Result SET IsPass = @IsPass,IsAudit = @IsAudit WHERE BillNumberId = @nBillId
	
					FETCH NEXT FROM bCursor INTO @nBillId,@nBillType
				END
			CLOSE bCursor
			DEALLOCATE bCursor
	
 declare @sqlresultby varchar(max)
 
		SET @sqlresultby='	SELECT	R.*,b.billname as billtypename,c.billname as othertypename,
					SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head
			FROM	#Result R
			 left join Custom_BillIndex csindex on r.billnumberid=csindex.BillId and r.billtype=csindex.billtype
	                left join BillName b ON R.billtype=b.billtype
				  left join BillName c ON R.FromBillType=c.billtype'	
			
			IF @OrderBy <> ''
			SET @sqlresultby=  @sqlresultby+ '
			
			ORDER BY ' + @OrderBy
			
			SET @sqlresultby=  @sqlresultby+ ' DROP TABLE #Result '
			PRINT(@sqlresultby)
	        EXEC(@sqlresultby)
			
	
	
	END
ELSE	--打印
	BEGIN
	declare @sqlresult varchar(max)
	 SET @RowCount = @@ROWCOUNT
	SELECT @sqlresult='SELECT * INTO #Result from (' + @SQL + ')a 
		   
	
			SELECT a.*,b.billname as billtypename,c.billname as othertypename, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head,'+Convert(VARCHAR(100),@RowCount)+' as TotalNum  
					  FROM #Result a 
					 left join Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
                  inner join BillName b ON a.billtype=b.billtype
				  inner join BillName c ON a.FromBillType=c.billtype
				DROP TABLE #Result
			' 
			--PRINT(@sqlresult)
			EXEC(@sqlresult)
			DROP TABLE #temp1
	END 
	
DROP TABLE #GetManETypeId,#GetManKTypeId,#GetManPTypeId,#GetManSTypeId 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStockDiscDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStockDiscDetail]
GO

/*
	作者:谢吉康
	日期：2016-07-15
	描述:实物库存分布表
*/

CREATE   PROCEDURE Web_QueryFactStockDiscDetail
(

	@operatorid			 	 nvarchar(50),		-- 当前操作员ID
	@stypeid             	 nvarchar(200),     --分支机构ID
    @ktypeid             	 nvarchar(200),     --仓库ID
    @ptypeid 		         nvarchar(200)='00000', 
	@unitconvert             nvarchar(10),    --多单位种类
	@entrycode				nvarchar(200)='',
	@usercode 				nvarchar(200),
	@fullname 				nvarchar(200) ,
	@showzeroqty           INT =0,   --是否显示零单据
	@sort           nvarchar(20),
	@ptypeCategoryid   VARCHAR(max)=''
	
 )
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql nvarchar(MAX)
DECLARE @ReSql nvarchar(MAX)
DECLARE @TableName nvarchar(16)
DECLARE @Condition nvarchar(MAX)			--谢吉康    2003-9-25  加大了变量的长度


--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid nvarchar(50), @MBtypeid nvarchar(50), @MBtypeid2 nvarchar(50), @MEtypeid nvarchar(50),
           @MKtypeid nvarchar(50), @MPtypeid nvarchar(50), @MExpense nvarchar(50), @MIncome nvarchar(50),@MCapital nvarchar(50),@MDtypeid nvarchar(50),@MStypeid nvarchar(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @re_check INT
EXEC @re_check=GP_CheckLimit @OperatorID,453
DECLARE @RS_CHECK INT
EXEC @RS_CHECK=dbo.GP_CheckLimit @OperatorID,2642

---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	nvarchar(100))
IF @RS_CHECK=0
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
ELSE 
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,'00001')
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	nvarchar(100))
IF @re_check = 0
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k 
    INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID) kk ON k.TypeId = kk.TypeId
	INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId
ELSE	
BEGIN

		INSERT INTO #GetManKTypeId(TypeId) SELECT s.typeid FROM Stock s
		INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID) kk ON s.TypeId = kk.TypeId
		INNER JOIN  #GetSelectSTypeId st ON  S.STypeID = St.TypeId
END
--商品
CREATE TABLE #PtypeDetail(TypeId	nvarchar(100))
INSERT INTO #PtypeDetail(TypeId) SELECT TypeId FROM dbo.F_ManPTypeInCategoryID(@OperatorID,@ptypeid,@ptypeCategoryid)


-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),
        @temprice   nvarchar(2000)
IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/r3.rate',
		@UnitName = 'u5.fullname',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','3,5','3'),
		@temprice='g.price*R3.rate'
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/r2.rate',
		@UnitName = 'u5.fullname',
		@temprice='g.price*R2.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/r4.rate',
		@UnitName = 'u5.fullname',
		@temprice='g.price*R4.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'u5.fullname',
		@temprice='g.price',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','5','')
END
----------多单位计算End---------
IF @PTypeId = '00000'
	SET @PTypeId = ''
CREATE TABLE #ptype
	(
		typeId 		 nvarchar (200) NOT NULL,
		sumqty 			 NUMERIC(24, 10) ,
		sumnqty			 NUMERIC(24, 10) ,
		unitname         nvarchar(2000),--计量单位
	    assistantname    nvarchar(2000)--浮动单位
	  	  
	)
DECLARE @GsSql nvarchar(MAX),@SQLSELECT nvarchar(MAX)=''

IF(@PTypeId<>'')
 BEGIN
  SET @SQLSELECT='	INSERT INTO  #ptype
          ( typeId ,
            unitname ,
            assistantname 
           
          )
		SELECT  q.TypeID,
				'+@UnitName+',
				u5.fullname
		FROM	#PtypeDetail q 
				inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
		where	p1.sonnum=0
				AND p1.IsService=0
				AND p1.iscombinationproduct = 0
				AND ('''+@usercode+''' ='''' OR p1.UserCode LIKE ''%'+@usercode+'%'')
				AND ('''+@fullname+'''= '''' OR p1.FullName LIKE ''%'+@fullname+'%'')
				AND ('''+@entrycode+''' ='''' OR p1.EntryCode LIKE ''%'+@entrycode+'%'')'
 END
ELSE
 BEGIN
	 SET @SQLSELECT='	INSERT INTO  #ptype
          ( typeId ,
            unitname ,
            assistantname 
       
          )
		SELECT  q.TypeID,
				'+@UnitName+',
				u5.fullname			
		FROM	#PtypeDetail q 
				inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
		where	p1.sonnum=0
				AND p1.IsService=0
				AND p1.iscombinationproduct = 0
				AND ('''+@usercode+''' ='''' OR p1.UserCode LIKE ''%'+@usercode+'%'')
				AND ('''+@fullname+'''= '''' OR p1.FullName LIKE ''%'+@fullname+'%'')
				AND ('''+@entrycode+''' ='''' OR p1.EntryCode LIKE ''%'+@entrycode+'%'')'
 
 END

EXEC(@SQLSELECT)

CREATE TABLE #GsStock
(
	PTypeId	nvarchar(100),
	Qty	 NUMERIC(24, 10) ,
	KTypeID	nvarchar(100),
	NQty  NUMERIC(24, 10) ,
)
SET @GsSql='
	INSERT INTO #GsStock
	SELECT	P.TypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,
			G.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty		
	FROM	#ptype p 
	inner join ptype p1 on p1.typeid=p.typeid
	INNER JOIN (select ptypeid,ktypeid FROM FactStocks_Qty group by ptypeid,ktypeid)g  ON g.PTypeId LIKE p.TypeId+''%'' 
	inner join #GetManKTypeId k on g.ktypeid like k.TypeId+''%'' 
	INNER JOIN FactStocks_Qty Q ON Q.ptypeid = G.ptypeid  and  g.ktypeid=q.ktypeid'+ @tmptab
	SET @GsSql = @GsSql + '	GROUP BY P.TypeId,G.KTypeID'
	
--PRINT(@GsSql)	
EXEC(@GsSql)

CREATE TABLE #result
(	    ID INT IDENTITY(1,1),
	    ptypeId 		 nvarchar (200) NOT NULL,
		sumqty 			 NUMERIC(24, 10) ,
		sumnqty			 NUMERIC(24, 10) ,
		unitname         nvarchar(2000),--计量单位
	    assistantname    nvarchar(2000),--浮动单位
	    basename		 nvarchar(2000)--基本单位
)

DECLARE @stockcount int 
DECLARE @j INT SET @j=1

SELECT @stockcount=MAX(num) FROM(
SELECT COUNT(KTypeID) AS num FROM #GsStock GROUP BY PTypeId)a


IF @stockcount IS NULL
 ALTER TABLE #result ADD 
	[仓库名称1] nvarchar(200),
	StockQty1 NUMERIC(24,10),
	StocknQty1 NUMERIC(24,10)
ELSE

WHILE @j<= @stockcount
	BEGIN
	SET @GsSql='	ALTER TABLE #result 
					ADD		[仓库名称'+CAST(@j AS nvarchar(20))+'] NVARCHAR(200),
							StockQty'+CAST(@j AS nvarchar(20))+' NUMERIC(24,10),
							StocknQty'+CAST(@j AS nvarchar(20))+' NUMERIC(24,10)'
	SET @j=@j+1
	
		--PRINT @GsSql
		EXEC(@GsSql)
	END

;WITH tb AS 
(
	SELECT	A.TypeId,
			SUM(ISNULL(G.Qty,0)) AS Qty,
			sum(isnull(g.nqty,0))as nqty
	FROM 	#ptype A
	LEFT JOIN #GsStock G ON  G.PTypeId = A.TypeId
	GROUP BY A.TypeId
)

INSERT  INTO #result
( 
	PTypeID ,
	sumqty ,    
	sumnqty
)
SELECT  TypeId ,
        qty ,
        nqty
FROM    tb
WHERE   ( ( @showzeroqty = 0 )
          OR ( @showzeroqty <> 0 and (ISNULL(qty,0)<>0) )
        )

DECLARE @PID nvarchar(50),
		@price NUMERIC(24,10),	
		@stockname nvarchar(200),
		@stockqty NUMERIC(24,10),
		@stocknqty NUMERIC(24,10),
		@i nvarchar(10),
		@total NUMERIC(24,10)


DECLARE pcur CURSOR FOR SELECT PTypeID FROM #result
						
OPEN pcur
FETCH NEXT FROM pcur INTO @PID
WHILE(@@FETCH_STATUS=0)
BEGIN
	SET @i='1'
	DECLARE gcur CURSOR FOR 
		SELECT	c.FullName,
				SUM(ISNULL(Qty,0)),
				SUM(ISNULL(nQty,0)) 
		FROM	#GsStock g
		INNER JOIN dbo.Stock c	ON g.KTypeID=c.typeId
		WHERE g.PTypeID=@PID
		GROUP BY g.KTypeID,c.FullName
		ORDER BY SUM(ISNULL(Qty,0)) DESC	
	OPEN gcur
	FETCH NEXT FROM gcur INTO @stockname,@stockqty,@stocknqty
	WHILE(@@FETCH_STATUS=0)
	BEGIN	
			
		SET @sql='update #result set [仓库名称'+@i+']=@pstockname,StockQty'+@i+'=@pqty,Stocknqty'+@i+'=@pnqty where ptypeid=@pptypeid'
		EXEC  SP_EXECUTESQL @stmt=@sql,@params=N'@pstockname nvarchar(200),@pqty numeric(24,10),@pnqty numeric(24,10),@pptypeid nvarchar(50)',
			 @pstockname=@stockname,@pqty=@stockqty,@pnqty=@stocknqty,@pptypeid=@PID
			
		SET @i=CAST( CAST(@i AS INT)+1 AS nvarchar)
		FETCH NEXT FROM gcur INTO @stockname,@stockqty,@stocknqty
	END								
	CLOSE gcur
	DEALLOCATE gcur
		
	FETCH NEXT FROM pcur INTO @PID
END
CLOSE pcur
DEALLOCATE pcur				


update #result set assistantname=p.assistantname  from  #result a inner join #ptype p on a.ptypeid=p.typeid

SELECT * FROM #result 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStockDiscLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStockDiscLine]
GO



/*
	日期:2004-05-24	
	作者:谢吉康
	描述:实物库存分布表的仓库权限是否有效	
*/

CREATE           PROCEDURE Web_QueryFactStockDiscLine
(
	@OperatorID 	varchar(100),       --作员id
	@PTypeIdMx		varchar(100),		
	@UserCode 		varchar(200),
	@FullName 		varchar(200),
	@Ptypeid 		varchar(100)='',
	@PageRows 		int=14,
	@PageNo 		int=0,
	@fzsl			varchar(1)='0',		--是否显示辅助数量
	@cbjj			varchar(1)='1',		--是否显示成本均价
	@cbje			varchar(1)='1',		--是否显示成本金额	2012.02.17韩林	
	@GoFlag 		int=0,
	@Flag 			int=1,
	@INDEX 			int=1,
	--@Sort 			char(4)='ASC',
	@StockPageNo 	int,
	@showzeroqty			int=0,		--滤调零单据		'刘戈 2004.05.21 添加
	@srcKTypeId		varchar(MAX),
	@szEntryCode		varchar(200)='',
	@stypeid			VARCHAR(MAX),
	@unitconvert    VARCHAR(10),         --多单位种类
	@sort           VARCHAR(20),
	@showstockstop INT =0, --是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid VARCHAR(max)=''
	
 )
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql varchar(MAX)
DECLARE @ReSql varchar(MAX)
DECLARE @TableName varchar(16)
DECLARE @Condition varchar(MAX)			--谢吉康    2003-9-25  加大了变量的长度
DECLARE @i int,@j INT

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @re_check INT
EXEC @re_check=GP_CheckLimit @OperatorID,453
DECLARE @RS_CHECK INT
EXEC @RS_CHECK=dbo.GP_CheckLimit @OperatorID,2642

---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
IF @RS_CHECK=0
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
ELSE 
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,'00001')
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @re_check = 0
 BEGIN 
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT k.TypeId 
	FROM F_GetManDetailKTypeSType(@OperatorID) k 
	INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId
	INNER JOIN F_GetAllBaseTypeId(@srcKTypeId,4) kk ON k.TypeId=kk.TypeId
	INNER JOIN dbo.Stock ss ON k.TypeId = ss.typeId 
	WHERE (ss.deleted=0	OR @showstockstop=0)
end	
ELSE	
BEGIN	
	INSERT INTO #GetManKTypeId(TypeId) 
	SELECT s.typeid 
	FROM Stock s
	INNER JOIN #GetSelectSTypeId st  ON  S.STypeID = St.typeId 
	INNER JOIN F_GetAllBaseTypeId(@srcKTypeId,4) kk ON s.TypeId=kk.TypeId
	WHERE   s.sonnum = 0 AND (s.deleted=0	OR @showstockstop=0)
END
--商品
CREATE TABLE #PtypeDetail(TypeId	varchar(100))
INSERT INTO #PtypeDetail(TypeId) 
SELECT TypeId FROM dbo.F_ManPTypeInCategoryID(@OperatorID,@ptypeid,@ptypeCategoryid)

create clustered index CIX_PtypeDetail ON #PtypeDetail(TypeId)

	
-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000)
--SET @tmptab=' inner JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') x ON gq.ptypeID=x.typeID'
IF @unitconvert=0
BEGIN
SELECT  @Qty='gq.Qty/r3.rate',
		@UnitName = 'u5.fullname',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='gq.Qty/r2.rate',
		@UnitName = 'u5.fullname',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='gq.Qty/r4.rate',
		@UnitName = 'u5.fullname',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='gq.Qty',
		@UnitName = 'u5.fullname',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','5','')
END
----------多单位计算End---------
-------------------------------------------------------------------------------------------------------------------------------

------------------------------------------计算出应查询的仓库-----------------------------------------------
CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)

DECLARE @SortStockCount int
DECLARE @SortStockAddRec int
DECLARE @TempKTypeID varchar(100)
DECLARE @TempKName varchar(MAX)
SELECT @SortStockCount=1
SELECT @SortStockAddRec=0

--处理仓库
DECLARE @KTypeIds 		varchar(MAX),
		@Where_KTypeId	varchar(MAX),
		@x 				int


SET @Where_KTypeId = ''

SET @srcKTypeId = RTRIM(LTRIM(@srcKTypeId))
SET @x = charindex(',',@srcKTypeId)

WHILE @x>=1
	BEGIN
		SET @KTypeIds = LEFT(@srcKTypeId,@x-1)

		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (S.TypeId LIKE '''+@KTypeIds+'%'''
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR S.TypeId LIKE '''+@KTypeIds+'%'''
		SET @srcKTypeId=SUBSTRING(@srcKTypeId,@x+1,LEN(@srcKTypeId)-@x)
		SET @x=charindex(',',@srcKTypeId)
	END

IF @srcKTypeId<>''
	BEGIN
		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (S.TypeId LIKE '''+@srcKTypeId+'%'')'
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR S.TypeId LIKE '''+@srcKTypeId+'%'')'
	END

DECLARE @Xjkang varchar(MAX)
SET @Xjkang = '	INSERT INTO #TempStock1 
				SELECT S.TypeId,S.UserCode,S.FullName 
				FROM Stock S 
				INNER JOIN #GetManKTypeId K ON K.TYPEID=S.TYPEID 
				WHERE S.SonNum = 0  ORDER BY S.UserCode '
EXEC(@Xjkang)

SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(10 AS varchar(50)) + ' 
				s1.TypeID,		
				s1.UserCode,					
				s1.FullName
	    FROM    #TempStock1 s1
	    LEFT JOIN 	                    
	            (
	                SELECT  TOP ' + CAST((@StockPageNo-1) * 10 AS varchar(50)) + ' UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) s2 on s1.Usercode=s2.Usercode
	    WHERE  s2.UserCode IS NULL    
	    ORDER BY s1.UserCode  '


EXEC(@xjkang)												  

------------------------------------------上段程序结束-----------------------------------------------

------------------------------------------计算对应页数的typeid---------------------------------
IF @GoFlag=1 AND @Flag=1
	BEGIN
			EXEC GP_CalculateStockDistributingPtypeId23 NULL,NULL,@UserCode,@FullName,@szEntryCode,NULL,@PageNo,@PageRows,'A','','',@PtypeId OUTPUT
	END

------------------------------------------上段程序结束-----------------------------------------------
CREATE TABLE #ptype
(
	[typeId]			[varchar] (100) NOT NULL,
	[父节点] 			varchar(100) NOT NULL,
	[商品编号]			[varchar] (200) NULL ,
	[商品名称]			[varchar] (200) NOT NULL , 
	单位关系			varchar(256) NULL,
	商品条码			varchar(MAX) NULL,
	商品规格			varchar(256) NULL,
	商品型号			varchar(256) NULL,
	商品产地			varchar(256) NULL,
	单位				varchar(100) NULL,
	大单位				varchar(100) NULL,
	关系				varchar(100) NULL,
	[总计实物库存] 		NUMERIC(24, 10)  DEFAULT 0,
	nqty 				NUMERIC(24, 10)  DEFAULT 0,	
	[总计自定义辅助数量] VARCHAR(1000)
)

--=======================================================================谢吉康  2003-12-1 重写PType的数据


SELECT TypeID,
	   UserCode,
	   FullName,
	   EntryCode,
	   sonnum INTO #GetManPType FROM F_GetManPType(@OperatorID)
DECLARE @SQLSELECT VARCHAR (MAX)
--自定义行数
DECLARE @uDeRowCount int
SELECT @uDeRowCount = ISNULL(UserDeRowCount,0) FROM LoginUser WHERE ETypeId = @OperatorID
IF @uDeRowCount = 0 
	SET @uDeRowCount = 14
 
IF @showzeroqty=0
	BEGIN
		SET @SQLSELECT = ' 
					SELECT   
							P1.TypeID,
							0,
							P1.UserCode,
							P1.FullName,
							CASE WHEN ISNULL(P1.Unit1,'''')<>'''' AND ISNULL(P1.Unit2,'''')<>'''' AND ISNULL(P1.UnitRate1,''0'')<>0
								THEN ''1''+ISNULL(P1.Unit2,'''')+''=''+CAST(Replace(CAST(ISNULL(P1.UnitRate1,''0'') AS varchar),''.0000'','''') AS varchar(100))+ISNULL(P1.Unit1,'''')
								ELSE '''' END
							AS  UnitRate,
							ISNULL(P1.EntryCode,'''') AS EntryCode,
							ISNULL(P1.Standard,'''') AS Standard,
							ISNULL(P1.Type,'''') AS Type,
							ISNULL(P1.Area,'''') AS Area,
							ISNULL(P1.Unit1,'''') AS Unit1,
							ISNULL(P1.Unit2,'''') AS Unit2,
							ISNULL(P1.UnitRate1,''0'') AS UnitRate1
	                FROM   ptype P1
	                inner join #PtypeDetail pt on p1.typeid=pt.typeid
	                WHERE  	P1.SonNum = 0
	                        and p1.IsService=0
	                        and p1.iscombinationproduct = 0
	                        AND P1.TypeID <> ''00000'' '
	                 IF(ISNULL(@PTypeIdMx,'') NOT IN('00000',''))
	                    SET @SQLSELECT+=' AND P1.TypeId LIKE '''+@PTypeIdMx+'%'''
	                SET @SQLSELECT+='                    
							AND P1.[UserCode] LIKE ''%'+@UserCode+'%''
							AND P1.[FullName] LIKE ''%'+@FullName+'%''
							AND p1.MultEntryCode LIKE ''%'+@szEntryCode+'%''			
	                ORDER BY P1.[UserCode] '
	END
ELSE
	BEGIN
		SET @SQLSELECT = '    
			                SELECT   
							P1.TypeID,
							0,
							P1.UserCode,
							P1.FullName,
							CASE WHEN ISNULL(P1.Unit1,'''')<>'''' AND ISNULL(P1.Unit2,'''')<>'''' AND ISNULL(P1.UnitRate1,''0'')<>0
								THEN ''1''+ISNULL(P1.Unit2,'''')+''=''+CAST(Replace(CAST(ISNULL(P1.UnitRate1,''0'') AS varchar),''.0000'','''') AS varchar(100))+ISNULL(P1.Unit1,'''')
								ELSE '''' END
							AS  UnitRate,
							ISNULL(P1.EntryCode,'''') AS EntryCode,
							ISNULL(P1.Standard,'''') AS Standard,
							ISNULL(P1.Type,'''') AS Type,
							ISNULL(P1.Area,'''') AS Area,
							ISNULL(P1.Unit1,'''') AS Unit1,
							ISNULL(P1.Unit2,'''') AS Unit2,
							ISNULL(P1.UnitRate1,''0'') AS UnitRate1
	                FROM    F_GetManPType('''+@OperatorID+''') P1
	                INNER JOIN
							(
								SELECT 	G.PTypeId
								FROM 	FactStocks G 
								INNER JOIN	#TempStock1 T ON G.KTypeId = T.TypeId
								INNER JOIN #PtypeDetail PD ON PD.typeid=g.ptypeid
								WHERE '
	                 IF(ISNULL(@PTypeIdMx,'') NOT IN('00000',''))
	                    SET @SQLSELECT+='G.TypeId LIKE '''+@PTypeIdMx+'%'' AND '
	                SET @SQLSELECT+='  
										G.Qty <> 0
										AND G.Qty IS NOT NULL
								GROUP BY G.PTypeId
							) P2 ON P1.typeid = p2.Ptypeid
								
	                WHERE  	P1.SonNum = 0
	                        AND P1.TypeID <> ''00000''
	                        and p1.IsService=0
	                        AND p1.iscombinationproduct = 0'
	                 IF(ISNULL(@PTypeIdMx,'') NOT IN('00000',''))
	                    SET @SQLSELECT+=' AND P1.TypeId LIKE '''+@PTypeIdMx+'%'''
	                SET @SQLSELECT+='
							AND P1.[UserCode] LIKE ''%'+@UserCode+'%''
							AND P1.[FullName] LIKE ''%'+@FullName+'%''
							AND p1.MultEntryCode LIKE ''%'+@szEntryCode+'%''											
	                ORDER BY P1.[UserCode] '
	END 
BEGIN           
	SELECT @SQLSELECT='INSERT INTO #ptype
				(
					[typeId],
					[父节点],
					[商品编号],
					[商品名称],
					单位关系,
					商品条码,
					商品规格,
					商品型号,
					商品产地,
					单位,
					大单位,
					关系			
				)'+@SQLSELECT
				
	--PRINT(@SQLSELECT)
	EXEC(@SQLSELECT)
END

SELECT 	gq.PTypeId AS ptypeid,	
		gq.ktypeid,																
		ISNULL(SUM(gq.Qty),0) AS Qty, 								
		ISNULL(SUM(gq.nqty),0) AS NQty								
into	#test 								
FROM 	(select ptypeid,ktypeid FROM FactStocks group by ptypeid,ktypeid)	v
INNER JOIN #TempStock T ON V.KTypeId = T.TypeId
INNER JOIN #PtypeDetail PD ON PD.typeid=V.PTypeId
INNER JOIN #GetManKTypeId K ON K.typeid=V.KTypeId
INNER JOIN FactStocks_qty gq ON gq.ktypeid = v.ktypeid and gq.ptypeid = v.ptypeid
GROUP BY gq.PtypeId,gq.KTypeID

SELECT 	gq.PTypeId AS ptypeid,	
		gq.ktypeid,																
		ISNULL(SUM(gq.Qty),0) AS Qty, 		
		ISNULL(SUM(gq.nqty),0) AS NQty								
into	#test1 								
FROM 	(select ptypeid,ktypeid FROM FactStocks group by ptypeid,ktypeid) v
INNER JOIN #TempStock1 T ON V.KTypeId = T.TypeId
INNER JOIN #PtypeDetail PD ON PD.typeid=V.PTypeId
INNER JOIN #GetManKTypeId K ON K.typeid=V.KTypeId
INNER JOIN FactStocks_qty gq ON gq.ktypeid = v.ktypeid and gq.ptypeid = v.ptypeid
GROUP BY gq.PtypeId,gq.KTypeID


--得到全部仓库的合计
SELECT @Sql='UPDATE #ptype 
			 SET	[总计实物库存]=ISNULL('+@Qty+',0),
					nqty=ISNULL(gq.NQty,0),
					[总计自定义辅助数量]=dbo.F_GetCustomAssist(a.TypeId,gq.qty)
  			 FROM #ptype a inner join ptype p1 on p1.typeid=a.typeid
  			 INNER JOIN (
				SELECT	A.TypeId AS ptypeid,
						SUM(ISNULL(G.Qty,0)) AS Qty,						
						SUM(ISNULL(G.nqty,0)) AS nqty
				FROM 	#ptype A
				LEFT JOIN #test1 G ON  G.PTypeId = A.TypeId
				GROUP BY A.TypeId
				)gq ON A.TypeId = gq.pTypeId'+@tmptab

--PRINT @sql
EXEC(@sql)

----复制一个表结构 
select * into #ptype1 from #ptype where 1=2

---把原先的先排序改为后排序
SET @Sql=' 
  INSERT INTO #ptype1 
  SELECT    [typeId] ,
			[父节点] ,
			[商品编号] ,
			[商品名称] , 
			单位关系,
			商品条码,
			商品规格,
			商品型号,
			商品产地,
			单位,
			大单位,
			关系,
			[总计实物库存],
			nqty,			
			[总计自定义辅助数量]
  FROM      ( SELECT    ROW_NUMBER() OVER ( ORDER BY '
      if  @Sort=''
			  set @SQL+=' A.[商品编号] '
			 else
			   set @SQL+=@Sort
            set @SQL+='    ) AS rownumber ,
                        *
              FROM      #ptype a
            ) a
  WHERE     rownumber BETWEEN '+ CAST((@PageNo-1) * @uDeRowCount+1 AS varchar(50))+' AND '+CAST(@PageNo * @uDeRowCount AS varchar(50))
exec(@Sql)

IF @@error<>0
	BEGIN
		--RAISERROR('更新商品总数量生错误！',16,1)
		RETURN
	END

DECLARE @TempTable VARCHAR(100)
SELECT @TempTable='##Temp'+REPLACE(NEWID(),'-','')

SET @SQL='	SELECT 	A.[typeId],
				A.[商品编号],
				A.[父节点],
				A.[商品名称],
				A.[单位关系], 
				A.商品条码,
				A.商品规格,
				A.商品型号,
				A.商品产地,
				A.单位,
				A.大单位,
				A.关系, 
				A.[总计实物库存],
				A.nqty,				
				A.[总计自定义辅助数量],
				gq.*'
			+CASE @fzsl WHEN '1' THEN 'INTO '+@TempTable ELSE '' END+'
			FROM #ptype1 A 
			LEFT JOIN (
					SELECT C.TYPEID AS PTYPEID,'+@UnitName+' AS unitname'	

SELECT	@SQL=@SQL+'
		,['+FullName+'实物库存]=SUM(CASE WHEN  gq.ktypeId = '''+typeid+''' THEN ISNULL('+@Qty+',0) ELSE 0 END)
		,['+FullName+'浮动数量]=SUM(CASE WHEN  gq.ktypeId = '''+typeid+''' THEN ISNULL(gq.NQty,0) ELSE 0 END)'
		+CASE @fzsl WHEN '1' THEN ',['+FullName+'辅助数量]=CAST('''' AS VARCHAR(100))' ELSE '' END		
		+',['+FullName+'自定义辅助数量]=  dbo.F_GetCustomAssist(C.TYPEID, SUM(CASE WHEN  gq.ktypeId = '''+typeid+''' THEN gq.qty ELSE 0 END)) '
FROM  #TempStock order by UserCode
SELECT @Sql=@Sql+' FROM #ptype1 C inner join ptype p1 on p1.typeid=c.typeid
	LEFT JOIN (
								SELECT	e.TypeId AS ptypeid,
										g.ktypeid,
										SUM(ISNULL(G.Qty,0)) AS Qty,										
										SUM(ISNULL(G.NQty,0)) AS NQty
								FROM 	#ptype1 e
								left JOIN #test G ON G.ptypeid =e.TypeId
								GROUP BY e.TypeId,g.ktypeid
								) gq on c.typeid=gq.ptypeid

'+@tmptab+'
GROUP BY '+@UnitName+',C.[typeId])  gq ON gq.PTYPEID=A.TYPEID 

ORDER BY '

     if  @Sort=''
			  SELECT @SQL+=' A.[商品编号] '
			 else
			   SELECT @SQL+=@Sort



IF @fzsl='1'
BEGIN
	--PRINT(@SQL)
	EXEC(@sql)
	IF EXISTS(SELECT * FROM #TempStock)
	BEGIN
		SET @SQL=''
		SELECT @SQL=@SQL+'['+fullname+'辅助数量]=CASE
							WHEN 单位关系='''' THEN ''''
							WHEN ['+FullName+'实物库存]=0 THEN ''''
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(['+FullName+'实物库存])/关系 as  NUMERIC(24, 10) )<1	THEN CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) ) AS varchar(100))+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(ISNULL(['+FullName+'实物库存],0))/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) as  NUMERIC(24, 10) )>=1 AND CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))<>''0'' THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(ISNULL(['+FullName+'实物库存],0))/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) as  NUMERIC(24, 10) )>=1 AND CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))=''0''  THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ISNULL(['+FullName+'实物库存],0)>0 AND ['+FullName+'实物库存]<关系 THEN CAST(['+FullName+'实物库存] AS varchar(100))+单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 as  NUMERIC(24, 10) ) AS varchar)+大单位	
							WHEN ['+FullName+'实物库存]/关系>=1 AND ['+FullName+'实物库存]/关系 = CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) THEN CAST(CAST(['+FullName+'实物库存]/关系 as  numeric(18,0)) as varchar)+大单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 as  numeric(18,0)) as varchar)+大单位
							WHEN ['+FullName+'实物库存]/关系>=1 THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))+单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位				
							ELSE ''0''+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
						 END,' from #TempStock s ORDER BY USERCODE
		IF RIGHT(@SQL,1)=','
			SET @Sql=LEFT(@Sql,LEN(@SQL)-1)
		SET @SQL='UPDATE '+@TempTable
				+' SET '+@Sql
		--PRINT(@SQL)
		EXEC(@sql)	
	END
	DECLARE @TABLE VARCHAR(100)
	SET @TABLE='SELECT * FROM '+@TempTable
	IF @Flag=0
		SELECT @TABLE=@TABLE+' ORDER BY '+CONVERT(varchar(4),@INDEX)+@Sort
	EXEC(@TABLE)

	-- 删除临时表
	SELECT @ReSql='DROP TABLE '+@TempTable
	EXEC(@ReSql)
END
ELSE
BEGIN
	IF @Flag=0
		SELECT @SQL=@SQL+' ,'+CONVERT(varchar(4),@INDEX)+@Sort
	--PRINT(@SQL)
	EXEC(@sql)	
END	

DROP TABLE #GetSelectSTypeId,#GetManKTypeId,#PtypeDetail,#TempStock,#ptype,#TempStock1,#test,#GetManPType,#ptype1,#test1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStockDiscLineCalTotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStockDiscLineCalTotal]
GO







/*
	作者：谢吉康
	日期：2016-6-7
	描述：实物库存分布表线性表计算合计和页数
*/

CREATE    PROCEDURE Web_QueryFactStockDiscLineCalTotal
(
	@OperatorID 	varchar(100),   --操作员id
	@PTypeId		varchar(100),	--商品Id
	@UserCode 		varchar(206)='',
	@FullName 		varchar(66)='',
	@PageRows 		int=14,
 	@NoZero 		int,           	--显示为零行
	@StockPageNo 	int,   			--分仓库页显示的页数
	@srcKTypeId		varchar(8000),
	@isLine			int=0,			--是否是线性表
	@szPEntryCode	varchar(800)='',
	@stypeid		VARCHAR(MAX),
	@unitconvert    VARCHAR(10)         --多单位种类
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @re_check INT
EXEC @re_check=GP_CheckLimit @OperatorID,453
DECLARE @RS_CHECK INT
EXEC @RS_CHECK=dbo.GP_CheckLimit @OperatorID,2642
---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
IF @RS_CHECK=0
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
ELSE 
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,'00001')
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @re_check = 0
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT s.typeid FROM Stock sk,F_GetAllManagerBaseTypeId(@srcKTypeId,4,'00001') s,F_GetAllManagerBaseTypeId(@stypeid,11,'00001') st WHERE S.TypeID = Sk.typeId AND Sk.STypeID = st.TypeId

--这里的参数原来是00001，导致没有控制到权限，不知道为什么会写成00001，改成@operatorID修改了A8 5390这个bug 。赵斌 2011.11.1
------------------------------------------计算出应查询的仓库-----------------------------------------------
CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)

DECLARE @SortStockCount int
DECLARE @SortStockAddRec int
DECLARE @TempKTypeID varchar(100)
DECLARE @TempKName varchar(66)
SELECT @SortStockCount=1
SELECT @SortStockAddRec=0


--处理仓库
DECLARE @KTypeIds 		varchar(MAX),
		@Where_KTypeId	varchar(MAX),
		@x 				int


SET @Where_KTypeId = ''

SET @srcKTypeId = RTRIM(LTRIM(@srcKTypeId))
SET @x = charindex(',',@srcKTypeId)

WHILE @x>=1
	BEGIN
		SET @KTypeIds = LEFT(@srcKTypeId,@x-1)

		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (TypeId LIKE '+char(39)+@KTypeIds+'%'+char(39)
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR TypeId LIKE '+char(39)+@KTypeIds+'%'+char(39)

		SET @srcKTypeId=SUBSTRING(@srcKTypeId,@x+1,LEN(@srcKTypeId)-@x)
		SET @x=charindex(',',@srcKTypeId)
	END

IF @srcKTypeId<>''
	BEGIN
		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (TypeId LIKE '+char(39)+@srcKTypeId+'%'+char(39)+')'
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR TypeId LIKE '+char(39)+@srcKTypeId+'%'+char(39)+')'
	END

DECLARE @Xjkang varchar(MAX)
SET @Xjkang = '	INSERT INTO #TempStock1 
				SELECT TypeId,UserCode,FullName 
				FROM Stock 
				WHERE stypeid IN (SELECT typeid FROM #GetSelectSTypeId) 
						AND SonNum = 0 
						AND TypeID IN (SELECT typeid FROM #GetManKTypeId) 
						'+@Where_KTypeId+' 
				ORDER BY UserCode '
--print(@xjkang)
EXEC(@Xjkang)
SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(10 AS varchar(50)) + ' 
				TypeID,		
				UserCode,					
				FullName
	    FROM    #TempStock1 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@StockPageNo-1) * 10 AS varchar(50)) + ' UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '
--print(@xjkang)
EXEC(@xjkang)
-----------------------------------------------------------/*仓库处理完毕*/-----------------------------------------------------

DECLARE @TotalPages int,@TotalQty  NUMERIC(24, 10) 
DECLARE @RecordCount int
DECLARE @TotalStockCount int,@TotalStockPages int
IF @UserCode IS NULL OR @UserCode=''
 SELECT @UserCode='%'
ELSE
 SELECT @UserCode='%'+@UserCode+'%'
IF @FullName IS NULL OR @FullName=''
 SELECT @FullName='%'

ELSE
 SELECT @FullName='%'+@FullName+'%'
IF @PageRows=0 
  SELECT @PageRows=14

----------------------------计算总页数
DECLARE @SonNum		int,
		@PTypeIdMx	varchar(100)

IF @PTypeId = '00000'

	SET @PTypeIdMx = '%'
ELSE
	SET @PTypeIdMx = @PTypeId

IF @PTypeId = ''
	SELECT  @SonNum = SonNum FROM PType WHERE TypeId = '00000'
ELSE
	SELECT  @SonNum = SonNum FROM PType WHERE TypeId = @PTypeId 

IF @SonNum >= 1
	BEGIN
		IF @isLine = 0
			SELECT 	@RecordCount=COUNT(*) 
			FROM 	F_GetManPTypeAll(@OperatorID) 
			WHERE	ISNULL(UserCode,'') LIKE '%'+@UserCode+'%' 
					AND ISNULL(FullName,'') LIKE '%'+@FullName+'%'
					AND ISNULL(multentrycode,'') LIKE '%'+@szPEntryCode+'%'
					AND ParId = @PTypeId
					AND IsService=0
		ELSE
			BEGIN
				IF @PTypeId = '00000'
					SET @PTypeId = '%'

				IF @NoZero = 0
					SELECT 	@RecordCount=COUNT(*) 
					FROM 	F_GetManPTypeAll(@OperatorID) 
					WHERE	ISNULL(UserCode,'') LIKE '%'+@UserCode+'%' 
							AND ISNULL(FullName,'') LIKE '%'+@FullName+'%'
							AND ISNULL(multentrycode,'') LIKE '%'+@szPEntryCode+'%'
							AND SonNum = 0
							AND IsService=0
							AND TypeId LIKE @PTypeIdMx+'%'
				ELSE
					BEGIN	
						SELECT	@RecordCount=COUNT(P.TypeId)
						FROM 	F_GetManPTypeAll(@OperatorID) P
						INNER JOIN (
								SELECT	S.PTypeId,
										ISNULL(SUM(S.Qty),0) AS Qty								
								FROM 	FactStocks S,
										#TempStock1 T
								WHERE	S.KTypeId = T.TypeId
								GROUP BY S.PTypeId
						)G ON G.PTypeId = P.TypeId
						WHERE	ISNULL(P.UserCode,'') LIKE '%'+@UserCode+'%' 
								AND ISNULL(P.FullName,'') LIKE '%'+@FullName+'%'
								AND ISNULL(P.multentrycode,'') LIKE '%'+@szPEntryCode+'%'
								AND P.SonNum = 0
								AND IsService=0
								AND P.TypeId LIKE @PTypeIdMx+'%'
					END
			END
	END
ELSE
	BEGIN
		IF @NoZero = 0
			SELECT 	@RecordCount=COUNT(*) 
			FROM 	F_GetManPTypeAll(@OperatorID)
			WHERE	ISNULL(UserCode,'') LIKE '%'+@UserCode+'%' 
					AND ISNULL(FullName,'') LIKE '%'+@FullName+'%'
					AND ISNULL(multentrycode,'') LIKE '%'+@szPEntryCode+'%'
					AND TypeId LIKE @PTypeIdMx+'%'
					AND IsService=0
		ELSE
			SELECT 	@RecordCount=COUNT(*) 
			FROM 	F_GetManPTypeAll(@OperatorID) P,
					#TempStock1 T,
					FactStocks G
			WHERE  	P.TypeId = G.PTypeId
					AND T.TypeId = G.KTypeId					
					AND ISNULL(P.UserCode,'') LIKE '%'+@UserCode+'%' 
					AND ISNULL(P.FullName,'') LIKE '%'+@FullName+'%'
					AND ISNULL(P.multentrycode,'') LIKE '%'+@szPEntryCode+'%'
					AND P.TypeId LIKE @PTypeIdMx+'%'
					AND IsService=0
	END 

SELECT	@TotalStockCount = COUNT(*) FROM #TempStock1



SET @TotalPages = @RecordCount

IF @TotalStockCount%10<>0 
	SELECT @TotalStockPages=@TotalStockCount/10+1
ELSE
	SELECT @TotalStockPages=@TotalStockCount/10
	
PRINT(@TotalStockPages)	

DECLARE @StockName varchar(66),@TypeId varchar(100),@i int,@j int,@ReSql varchar(MAX),@Sql varchar(MAX),@Qty  NUMERIC(24, 10) ,@NQty  NUMERIC(24, 10) 
DECLARE @TableName varchar(16)

SELECT 	typeid 
INTO 	#TempPTypeAll 
FROM 	F_GetManPTypeAll(@OperatorID) 
WHERE 	sonnum=0 
        AND IsService=0
		AND ISNULL(UserCode,'') LIKE '%'+@UserCode +'%'
		AND ISNULL(FullName,'') LIKE '%'+@FullName+'%'
		AND ISNULL(multentrycode,'') LIKE '%'+@szPEntryCode+'%'
		AND TypeId LIKE @PTypeIdMx + '%'


/*================================= WANG WEI 2010-8-11 BEGIN 如果不显示库存状况为零的时候，将商品所有仓库合计的总数为零的排除=========================================================================*/
CREATE TABLE #TempPType(typeid VARCHAR(100))
IF @NoZero='0'
BEGIN
	INSERT INTO #TempPType SELECT * FROM #TempPTypeAll		
END
Else
BEGIN
	INSERT INTO #TempPType
	SELECT b.typeid 
	FROM
	( 
		Select p.typeid,Isnull(sum(a.qty),0) as sumQty from #TempPTypeAll p left join 
		(Select s.qty,s.ptypeid  from FactStocks s inner join #Tempstock t On s.ktypeid=t.typeid) a
		ON a.ptypeid=p.typeid
		where Isnull(a.qty,0)<>0
		group by p.typeid 
	
	) b 
	INNER JOIN #TempPTypeAll t On b.typeid=t.typeid
	WHERE b.sumQty<>0	

END
/*================================= WANG WEI 2010-8-11 END=========================================================================*/



CREATE TABLE #FactStocks
(
	Qty			 NUMERIC(24, 10) ,
	KTypeId		varchar(100),
	ptypeid     VARCHAR(50)
)
INSERT INTO #FactStocks(Qty,KTypeId,ptypeid) 
SELECT	Qty,
		KTypeID,
		ptypeid
FROM FactStocks 
WHERE EXISTS(
				SELECT typeid 
				FROM #TempPType 
				WHERE typeid=ptypeid
			) 
		AND KTypeId IN (SELECT TypeId FROM #GetManKTypeId)

-------------------------------------------------多单位换算----和DBA-WWF确认，此处写法不同于其他写法--------------------
select * into #temp_ptype from (select * from F_GetManPTypeDetailALL(@OperatorID)) a


SELECT	a.typeid,
		CASE WHEN @unitconvert=0 THEN ISNULL(SUM(b.qty/x.saleunitrate),0)
                   WHEN @unitconvert=1 THEN ISNULL(SUM(b.qty/x.buyunitrate),0)
                   WHEN @unitconvert=2 THEN ISNULL(SUM(b.qty/x.stockunitrate),0)
                   ELSE ISNULL(SUM(b.qty),0) END AS qty, 		
		ISNULL(SUM(q.nqty),0) AS nqty
INTO	#StockQty 
FROM	#TempStock a 
		LEFT JOIN (SELECT SUM(Qty)qty,PtypeId,KtypeId FROM #FactStocks where Qty!=0  GROUP BY PtypeId,KtypeId) b ON (a.typeid=b.ktypeid)
		LEFT JOIN (select SUM(NQty)AS  nqty,PTypeID,KTypeID FROM FactStocks_Qty 
		 GROUP BY PTypeID,KTypeID)q ON q.ptypeid = b.ptypeid  AND  b.KTypeId = q.KTypeID
		 LEFT JOIN  #temp_ptype x ON q.ptypeid=x.typeID 
GROUP BY a.typeid

DECLARE @sumTotal  NUMERIC(24, 10) ,@sumprice  NUMERIC(24, 10) , @TotalNqty  NUMERIC(24, 10) 
SET @sumprice=0

 ;WITH test AS (SELECT ISNULL(SUM(q.qty),0) AS qty,ISNULL(SUM(q.nqty),0) AS nqty ,q.PTypeID
  FROM (SELECT * FROM F_GetManPTypeAll(@OperatorID)p  WHERE
    ISNULL(P.UserCode,'') LIKE '%'+@UserCode+'%' 
   AND ISNULL(P.FullName,'') LIKE '%'+@FullName+'%'
   AND ISNULL(P.multentrycode,'') LIKE '%'+@szPEntryCode+'%') P
  LEFT JOIN  (SELECT PtypeId,KtypeId FROM FactStocks  WHERE PtypeId LIKE @PTypeIdMx+'%' AND ktypeid IN(SELECT typeId FROM #Tempstock1   ) AND Qty!=0  GROUP BY PtypeId,KtypeId) G ON p.typeId=g.PtypeId
  LEFT JOIN(select SUM(NQty)AS  nqty, SUM(Qty)AS qty,PTypeID,KTypeID FROM FactStocks_Qty WHERE  ktypeid IN(SELECT typeId FROM #Tempstock1   )  GROUP BY PTypeID,KTypeID) Q ON g.PtypeId=q.PTypeID AND q.KTypeID=g.KtypeId  

   GROUP BY q.PTypeID)


SELECT
        @TotalQty=CASE WHEN @unitconvert=0
                       THEN ISNULL(SUM(a.qty/x.saleunitrate),0)
                       WHEN @unitconvert=1
                       THEN ISNULL(SUM(a.qty/x.buyunitrate),0)
                       WHEN @unitconvert=2
                       THEN ISNULL(SUM(a.qty/x.stockunitrate),0)
                       ELSE ISNULL(SUM(a.qty),0)
                  END,
        @TotalNQty=SUM(a.nqty)
FROM test a
       LEFT JOIN #temp_ptype x
        ON a.ptypeid=x.typeID 
SET @sumprice=(CASE @sumTotal WHEN 0 THEN 0 ELSE @sumTotal/@TotalQty END)


 
--计算每个仓库的合计
SELECT @TableName='Web'+CONVERT(varchar(2),DATEPART(dd,GETDATE()))+CONVERT(varchar(2),DATEPART(hh,GETDATE()))+CONVERT(varchar(2),DATEPART(m,GETDATE()))+CONVERT(varchar(2),DATEPART(s,GETDATE()))+CONVERT(varchar(4),DATEPART(ms,GETDATE()))
SELECT @Sql='CREATE TABLE '+N'##'+@TableName+'([总页数] int,[仓库总页数] int,[总计实物库存]  NUMERIC(24, 10) ,[nqty]  NUMERIC(24, 10))'
EXEC(@sql)

IF @@error<>0
	BEGIN
		--RAISERROR('创建临时表发生错误！',16,1)
		RETURN
	END

SELECT @Sql='INSERT '+N'##'+@TableName+'([总页数],[仓库总页数],[总计实物库存],[nqty])
                    VALUES('+CONVERT(varchar(50),@TotalPages)+','+CONVERT(varchar(50),@TotalStockPages)+','+CONVERT(varchar(50),@TotalQty)+','+CONVERT(varchar(50),@TotalNQty)+')'

EXEC(@Sql)

IF @@error<>0
	BEGIN
		--RAISERROR('插入数据发生错误！',16,1)
		RETURN
	END


DECLARE @stockTotal  NUMERIC(24, 10) 
DECLARE Stock CURSOR  FOR 
     SELECT  b.qty,a.typeid,a.fullname,b.nqty FROM #TempStock a LEFT JOIN #StockQty b ON (a.typeid=b.typeid) ORDER BY a.UserCode FOR READ ONLY

OPEN Stock
FETCH NEXT FROM Stock INTO @Qty,@TypeId,@StockName,@NQty

SELECT @Sql=''
SELECT @ReSql='[总页数],[仓库总页数],[总计实物库存],[nqty]'
IF @@Fetch_status<>0
BEGIN
	CLOSE Stock
	DEALLOCATE Stock
	--RAISERROR('没有可用的仓库或仓库没有商品或没有商品！',16,1)
		SELECT @ReSql='SELECT '+@ReSql+' FROM '+N'##'+@TableName 
		EXEC(@ReSql)
	RETURN 
END 

WHILE @@Fetch_status=0
	BEGIN
		--检查列名是否存在
		SELECT @i=0
		SELECT @j=0
		SELECT @i=CharIndex('['+ @StockName + ']',@ReSql,@i)
		WHILE @i>0
			BEGIN
				SELECT @i=CharIndex('['+ @StockName + ']',@ReSql,@i+len('['+ @StockName + ']'))
				SELECT @j=@j+1  
			END
	
		IF @j>0
			SELECT @StockName=@StockName+CONVERT(varchar(4),@j)
			
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @StockName + '实物库存]  NUMERIC(24, 10) '
			EXEC(@sql)
			SELECT @Sql='ALTER TABLE '+N'##'+@TableName+ ' ADD ['+ @StockName + '浮动数量]  NUMERIC(24, 10) '
 			EXEC(@sql)
			IF @@error<>0
				BEGIN
					CLOSE Stock
					DEALLOCATE Stock
					--RAISERROR('更改临时表发生错误！',16,1)
					RETURN
				END
			
			SELECT @Sql='UPDATE '+N'##'+@TableName+' SET ['+@StockName+'实物库存]='+CONVERT(varchar(1000),@Qty)+','
			SELECT @Sql=@Sql+'['+@StockName+'浮动数量]='+CONVERT(varchar(1000),@NQty)
			EXEC(@sql)
			IF @@error<>0
				BEGIN
					CLOSE Stock
					DEALLOCATE Stock
					--RAISERROR('更新商品数量生错误！',16,1)
					RETURN
				END
		
			SELECT @ReSql=@ReSql+',['+ @StockName + '实物库存],['+ @StockName + '浮动数量]'
		
		FETCH NEXT FROM Stock INTO @Qty,@TypeId,@StockName,@NQty
	END

CLOSE Stock

DEALLOCATE Stock
SELECT @ReSql='SELECT '+@ReSql+' FROM '+N'##'+@TableName
EXEC(@ReSql)

DECLARE @DropTable varchar(1000)
SET @DropTable = 'DROP TABLE #TempStock1,'+N'##'+@TableName
EXEC(@DropTable)

IF @@Rowcount=0
   RETURN @TotalPages

DROP TABLE #FactStocks,#GetSelectSTypeId,#TempStock1drop,#temp_ptype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStockDisDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStockDisDetail]
GO

/*
	作者：谢吉康	
	日期：2016-07-12
	描述：实物库存货位分布线性表
*/
CREATE PROCEDURE Web_QueryFactStockDisDetail
(
	@operatorid			 	 nvarchar(50),		-- 当前操作员ID
	@stypeid             	 nvarchar(200),     --分支机构ID
    @ktypeid             	 nvarchar(200),     --仓库ID
    @cargoid             	 nvarchar(max),     --货位ID
    @ptypeid 		         nvarchar(200)='00000', 
	@unitconvert             nvarchar(10),    --多单位种类
	@entrycode				nvarchar(200)='',
	@usercode 				nvarchar(200),
	@fullname 				nvarchar(200) ,
	@showzeroqty			INT =0   --是否显示零单据
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql nvarchar(max)=''
DECLARE @Condition nvarchar(MAX)	
------------------------------------------------------权限检查---------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid nvarchar(50), @MBtypeid nvarchar(50), @MBtypeid2 nvarchar(50), @MEtypeid nvarchar(50),
           @MKtypeid nvarchar(50), @MPtypeid nvarchar(50), @MExpense nvarchar(50), @MIncome nvarchar(50),@MCapital nvarchar(50),@MDtypeid nvarchar(50),@MStypeid nvarchar(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
------------------------------------------------------权限检查---------------------------------------------------------------
---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	nvarchar(100))
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--仓库
CREATE TABLE #GetManKTypeId(TypeId	nvarchar(100))
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM  F_GetManDetailKTypeSType(@OperatorID) k 
	INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
	INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	
	
--货位
CREATE TABLE #GetSelectCargoid(cargoid nvarchar(100),typeid nvarchar(100))

IF @cargoid = '00000' OR @cargoid = '' OR @cargoid = '%'
				INSERT INTO #GetSelectCargoid(cargoid,typeid) SELECT CargoID,KtypeID FROM CargoType a
				INNER JOIN #GetManKTypeId b ON a.KtypeID=b.TypeId
			ELSE
				INSERT INTO #GetSelectCargoid(cargoid,typeid)
				SELECT 	A.CargoID ,a.KtypeID
				FROM 	CargoType A, 
						(SELECT A FROM dbo.F_Split(@cargoid,',')) B 
						,#GetManKTypeId c 
				WHERE	A.CargoID = B.A AND c.typeid =a.ktypeid
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),
        @temprice   nvarchar(2000)
IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/R3.rate',
		@UnitName = 'U3.fullname',
		@temprice='g.price*R3.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/R2.rate',
		@UnitName = 'U2.fullname',
		@temprice='g.price*R2.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/R4.rate',
		@UnitName = 'U4.fullname',
		@temprice='g.price*R4.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'U1.fullname',
		@temprice='g.price',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','5,1','')
END
----------多单位计算End---------
IF @PTypeId = '00000'
	SET @PTypeId = ''
CREATE TABLE #ptype
	(
		typeId 		 nvarchar (200) NOT NULL,
		sumqty 			 NUMERIC(24, 10) ,
		sumnqty			 NUMERIC(24, 10) ,
		unitname         nvarchar(2000),--计量单位
	    assistantname    nvarchar(2000),--浮动单位
	    basename		 nvarchar(2000)--基本单位	  
	)
DECLARE @GsSql nvarchar(MAX),@SQLSELECT nvarchar(MAX)=''


IF(@PTypeId<>'')
 BEGIN
  SET @SQLSELECT='	INSERT INTO  #ptype
          ( typeId ,
            unitname ,
            assistantname ,
            basename
          )
		SELECT  q.TypeID,
				'+@UnitName+',
				u5.fullname,
				u1.fullname
		FROM    F_GetManPType('''+@OperatorID+''') q 
				INNER JOIN (SELECT A FROM dbo.F_Split('''+@PTypeId+''','','')) B ON 	q.TypeId LIKE B.A +''%''
				inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
		where	q.sonnum=0
				AND p1.IsService=0
				AND p1.iscombinationproduct = 0
				AND ('''+@usercode+''' ='''' OR p1.UserCode LIKE ''%'+@usercode+'%'')
				AND ('''+@fullname+'''= '''' OR p1.FullName LIKE ''%'+@fullname+'%'')
				AND ('''+@entrycode+''' ='''' OR p1.EntryCode LIKE ''%'+@entrycode+'%'')'
 END
ELSE
 BEGIN
	 SET @SQLSELECT='	INSERT INTO  #ptype
          ( typeId ,
            unitname ,
            assistantname ,
            basename
          )
		SELECT  q.TypeID,
				'+@UnitName+',
				u5.fullname,
				u1.fullname
		FROM    F_GetManPType('''+@OperatorID+''') q 
				inner join ptype p1 on q.typeid=p1.typeid '+@tmptab+'
		where	q.sonnum=0
				AND p1.IsService=0
				AND p1.iscombinationproduct = 0
				AND ('''+@usercode+''' ='''' OR p1.UserCode LIKE ''%'+@usercode+'%'')
				AND ('''+@fullname+'''= '''' OR p1.FullName LIKE ''%'+@fullname+'%'')
				AND ('''+@entrycode+''' ='''' OR p1.EntryCode LIKE ''%'+@entrycode+'%'')'
 
 END

EXEC(@SQLSELECT)
CREATE TABLE #GsStock
(
	PTypeId	nvarchar(100),
	Qty	 NUMERIC(24, 10) ,
	KTypeID	nvarchar(100),
	NQty  NUMERIC(24, 10) ,
	cargoid int	

)
SET @GsSql='
	INSERT INTO #GsStock
	SELECT	P.TypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,
			G.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty,
			q.cargoid
	FROM	#ptype p inner join ptype p1 on p1.typeid=p.typeid
INNER JOIN (select ptypeid,ktypeid FROM FactStocks group by ptypeid,ktypeid)
	g  ON g.PTypeId LIKE p.TypeId+''%'' 
	INNER JOIN FactStocks_Qty Q ON Q.ptypeid = G.ptypeid  and  g.ktypeid=q.ktypeid
	inner join #GetSelectCargoid d on q.cargoid=d.cargoid'+ @tmptab
	SET @GsSql = @GsSql + '	GROUP BY P.TypeId,G.KTypeID,q.cargoid'
EXEC(@GsSql)


CREATE TABLE #result
(	    ID INT IDENTITY(1,1),
	    ptypeId 		 nvarchar (200) NOT NULL,
		sumqty 			 NUMERIC(24, 10) ,
		sumnqty			 NUMERIC(24, 10) ,
		unitname         nvarchar(2000),--计量单位
	    assistantname    nvarchar(2000),--浮动单位
	    basename		 nvarchar(2000)--基本单位
	
		
)
DECLARE @cargocount int 
DECLARE @j INT SET @j=1

SELECT @cargocount=MAX(num) FROM(
SELECT COUNT(cargoid) AS num FROM #GsStock GROUP BY PTypeId)a


IF @cargocount IS NULL
 ALTER TABLE #result ADD 
	[货位名称1] nvarchar(200),
	CargoQty1 NUMERIC(24,10),
	CargonQty1 NUMERIC(24,10)
ELSE

WHILE @j<= @cargocount
	BEGIN
	SET @GsSql='	ALTER TABLE #result ADD 
	[货位名称'+CAST(@j AS nvarchar(20))+'] NVARCHAR(200),
	CargoQty'+CAST(@j AS nvarchar(20))+' NUMERIC(24,10),
	CargonQty'+CAST(@j AS nvarchar(20))+' NUMERIC(24,10)'
	SET @j=@j+1
	PRINT @GsSql
		 EXEC(@GsSql)
	END

;WITH tb AS 
(
	SELECT	A.TypeId,
						SUM(ISNULL(G.Qty,0)) AS Qty,
						sum(isnull(g.nqty,0))as nqty,
						unitname,
						assistantname,
						basename
				FROM 	#ptype A
				LEFT JOIN #GsStock G ON  G.PTypeId = A.TypeId
				GROUP BY A.TypeId,unitname,
						assistantname,
						basename
)
INSERT  INTO #result
        ( PTypeID ,
          sumqty ,
          sumnqty,
          unitname,
		  assistantname,
		  basename
        )
        SELECT  TypeId ,
                qty ,
                nqty,
                unitname,
				assistantname,
				basename
        FROM    tb
        WHERE   ( ( @showzeroqty = 0 )
                  OR ( @showzeroqty <> 0 and isnull(qty,0)>0)
                )



DECLARE @PID nvarchar(50),
		@price NUMERIC(24,10),		
		@cargoname nvarchar(200),
		@cargoqty NUMERIC(24,10),
		@cargonqty NUMERIC(24,10),
		@i nvarchar(10),
		@total NUMERIC(24,10)


DECLARE pcur CURSOR FOR SELECT PTypeID FROM #result
						
OPEN pcur
FETCH NEXT FROM pcur INTO @PID
WHILE(@@FETCH_STATUS=0)
BEGIN
	SET @i='1'
	DECLARE gcur CURSOR FOR SELECT c.FullName,SUM(ISNULL(Qty,0)),SUM(ISNULL(nQty,0)) FROM #GsStock g
								INNER JOIN dbo.CargoType c	ON g.CargoID=c.CargoID
									WHERE g.PTypeID=@PID
								GROUP BY g.CargoID,c.FullName
								ORDER BY SUM(ISNULL(Qty,0)) DESC	
	OPEN gcur
	FETCH NEXT FROM gcur INTO @cargoname,@cargoqty,@cargonqty
	WHILE(@@FETCH_STATUS=0)
	BEGIN	
			
		SET @sql='update #result set [货位名称'+@i+']=@pcargoname,CargoQty'+@i+'=@pqty,cargonqty'+@i+'=@pnqty where ptypeid=@pptypeid'
		EXEC  SP_EXECUTESQL @stmt=@sql,@params=N'@pcargoname nvarchar(200),@pqty numeric(24,10),@pnqty numeric(24,10),@pptypeid nvarchar(50)',
			 @pcargoname=@cargoname,@pqty=@cargoqty,@pnqty=@cargonqty,@pptypeid=@PID
			
		SET @i=CAST( CAST(@i AS INT)+1 AS nvarchar)
		FETCH NEXT FROM gcur INTO @cargoname,@cargoqty,@cargonqty
	END								
	CLOSE gcur
	DEALLOCATE gcur
		
	FETCH NEXT FROM pcur INTO @PID
END
CLOSE pcur
DEALLOCATE pcur				

SELECT * FROM #result 

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStockDisLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStockDisLine]
GO

/*
	作者：谢吉康	
	日期：2016-07-12
	描述：实物库存货位分布线性表
*/
CREATE PROCEDURE Web_QueryFactStockDisLine
(
	@OperatorId			 	 VARCHAR(50),		-- 当前操作员ID
	@stypeid             	 VARCHAR(200),     --分支机构ID
    @ktypeid             	 VARCHAR(200),     --仓库ID
    @cargoid             	 VARCHAR(max),     --货位ID
    @PTypeId 		         VARCHAR(100)='00000',
    @PageRows 			 	 INT=14,
	@StockPageRows		 	 INT=10,
	@GoPageNo 			 	 INT=0,        
	@Flag 					 INT=1,
	@Index 					 INT=1,
	@Sort 					 CHAR(4)='ASC',
	@unitconvert             VARCHAR(10),    --多单位种类
	@StockPageNo 			 INT,
	@szEntryCode			 VARCHAR(200)='',
	@PTypeIdMx				VARCHAR(100),
	@UserCode 				VARCHAR(200),
	@FullName 				VARCHAR(200) ,
	@colCount               int output  ,
	@showzeroqty			INT =0 ,  --是否显示零单据
	@showstockstop			INT =0 --是否显示停用仓库数据 1为不显示 0为显示
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql varchar(max)=''
DECLARE @Condition varchar(MAX)	
------------------------------------------------------权限检查---------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
------------------------------------------------------权限检查---------------------------------------------------------------
---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	VARCHAR(100))
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
	IF  @showstockstop=0
		INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM  F_GetManDetailKTypeSType(@OperatorID) k 
		INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
		INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	
 ELSE
 	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM  F_GetManDetailKTypeSType(@OperatorID) k 
	INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
	INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	
	INNER JOIN dbo.Stock ss ON a.TypeId = ss.typeId WHERE deleted=0

--货位
CREATE TABLE #GetSelectCargoid(cargoid VARCHAR(100),typeid VARCHAR(100))

IF @cargoid = '00000' OR @cargoid = '' OR @cargoid = '%'
	INSERT INTO #GetSelectCargoid(cargoid,typeid) SELECT CargoID,KtypeID FROM CargoType a
	INNER JOIN #GetManKTypeId b ON a.KtypeID=b.TypeId
ELSE
	INSERT INTO #GetSelectCargoid(cargoid,typeid)
	SELECT 	A.CargoID ,a.KtypeID
	FROM 	CargoType A, 
			(SELECT A FROM dbo.F_Split(@cargoid,',')) B 
			,#GetManKTypeId c 
	WHERE	A.CargoID = B.A AND c.typeid =a.ktypeid

--计算总的动态列数
SET @colCount= (select count(*) from  #GetSelectCargoid)

-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),
        @temprice   VARCHAR(2000)
IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/R3.rate',
		@UnitName = 'U3.fullname',
		@temprice='g.price*R3.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/R2.rate',
		@UnitName = 'U2.fullname',
		@temprice='g.price*R2.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/R4.rate',
		@UnitName = 'U4.fullname',
		@temprice='g.price*R4.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'U1.fullname',
		@temprice='g.price',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','5,1','')
END
----------多单位计算End---------
-----------------------------------------------------------------------------------------------------------------------------


IF @UserCode IS NULL OR @UserCode=''
	SELECT @UserCode='%'
ELSE
 	SELECT @UserCode='%'+@UserCode+'%'

IF @FullName IS NULL OR @FullName=''
 	SELECT @FullName='%'
ELSE
 	SELECT @FullName='%'+@FullName+'%'

IF @PTypeIdMx = '00000'
	SET @PTypeIdMx = ''
	
CREATE TABLE #ptype
(
	[typeId] 		[varchar] (100) NOT NULL,
	[parid] 		[varchar] (100) NOT NULL,
	[总计实物库存] 	 NUMERIC(24, 10) ,
	[总计浮动数量]	 NUMERIC(24, 10) ,
	unitname         VARCHAR(2000),--计量单位
    assistantname    VARCHAR(2000),--浮动单位
    basename		 VARCHAR(2000),--基本单位	
    [总计自定义辅助数量] VARCHAR(50),
    Cargoid           VARCHAR(50)
)
DECLARE @SonNum INT,@GsSql VARCHAR(1000),@SQLSELECT VARCHAR(MAX)=''
SELECT @SonNum = SonNum FROM PType WHERE TypeId = @PTypeId

IF @showzeroqty=0
	BEGIN

	SET @SQLSELECT = '    
		SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
				q.TypeID,
				q.parid,
				0,'+@UnitName+',u5.fullname,u1.fullname
		FROM    F_GetManPType('''+@OperatorID+''') q 
		inner join ptype p1 on q.typeid=p1.typeid 
		
		'+@tmptab+'
		WHERE  	q.TypeID <> ''00000''	
				and q.IsService=0
				and q.iscombinationproduct = 0
				AND q.UserCode NOT IN                    
				(
					SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' UserCode
					FROM	F_GetManPType('''+@OperatorID+''')
					WHERE   TypeID <> ''00000'' and sonnum=0'+CHAR(13)
					IF(ISNULL(@UserCode,'')<>'')
						SET @SQLSELECT+='AND [UserCode] LIKE ''%'+@UserCode+'%'''+CHAR(13)
					IF(ISNULL(@FullName,'')<>'')
						SET @SQLSELECT+='AND [FullName] LIKE ''%'+@FullName+'%'''+CHAR(13)
					IF(ISNULL(@szEntryCode,'')<>'')
						SET @SQLSELECT+='AND MultEntryCode LIKE ''%'+@szEntryCode+'%'''+CHAR(13)
					SET @SQLSELECT+='				
							AND TypeId LIKE '''+@PTypeIdMx+'%''	
							AND iscombinationproduct = 0
							AND isservice = 0
					ORDER BY UserCode
				) 
				and q.sonnum=0'+CHAR(13)
				IF(ISNULL(@UserCode,'')<>'')
						SET @SQLSELECT+='AND q.[UserCode] LIKE ''%'+@UserCode+'%'''+CHAR(13)
					IF(ISNULL(@FullName,'')<>'')
						SET @SQLSELECT+='AND q.[FullName] LIKE ''%'+@FullName+'%'''+CHAR(13)
					IF(ISNULL(@szEntryCode,'')<>'')
						SET @SQLSELECT+='AND q.MultEntryCode LIKE ''%'+@szEntryCode+'%'''+CHAR(13)
					SET @SQLSELECT+='
				AND q.TypeId LIKE '''+@PTypeIdMx+'%''	
		ORDER BY q.UserCode '
		
	END
ELSE
	BEGIN
	SET @SQLSELECT = '    
		SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
				q.TypeID,
				q.parid,
				0,'+@UnitName+',u5.fullname,u1.fullname
		FROM    F_GetManPType('''+@OperatorID+''')q   
		inner join ptype p1 on q.typeid=p1.typeid 
		INNER JOIN FactStocks_Qty Q1 ON Q1.ptypeid = q.typeid 
		inner join #GetSelectCargoid d on q1.cargoid=d.cargoid 
		'+@tmptab+' 
		WHERE  	q.TypeID <> ''00000''	
		        and q.IsService=0
		        and q.iscombinationproduct = 0
				AND q.UserCode NOT IN                    
				(
					SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' UserCode
					FROM	F_GetManPType('''+@OperatorID+''')
					WHERE   TypeID <> ''00000'' 
							and sonnum=0
							and isservice = 0
							and iscombinationproduct = 0'+CHAR(13)
					IF(ISNULL(@UserCode,'')<>'')
						SET @SQLSELECT+='AND [UserCode] LIKE ''%'+@UserCode+'%'''+CHAR(13)
					IF(ISNULL(@FullName,'')<>'')
						SET @SQLSELECT+='AND [FullName] LIKE ''%'+@FullName+'%'''+CHAR(13)
					IF(ISNULL(@szEntryCode,'')<>'')
						SET @SQLSELECT+='AND MultEntryCode LIKE ''%'+@szEntryCode+'%'''+CHAR(13)
					SET @SQLSELECT+='
							AND TypeId LIKE '''+@PTypeIdMx+'%''	
					ORDER BY UserCode
				) 
				and q.sonnum=0'+CHAR(13)
				IF(ISNULL(@UserCode,'')<>'')
						SET @SQLSELECT+='AND q.[UserCode] LIKE ''%'+@UserCode+'%'''+CHAR(13)
					IF(ISNULL(@FullName,'')<>'')
						SET @SQLSELECT+='AND q.[FullName] LIKE ''%'+@FullName+'%'''+CHAR(13)
					IF(ISNULL(@szEntryCode,'')<>'')
						SET @SQLSELECT+='AND q.MultEntryCode LIKE ''%'+@szEntryCode+'%'''+CHAR(13)
					SET @SQLSELECT+='
				AND q.TypeId LIKE '''+@PTypeIdMx+'%''	
				and q1.qty!=0 and q1.qty is not null	group by q.typeid,q.parid,q.usercode,u5.fullname,u1.fullname,'+@UnitName+	
		' ORDER BY q.UserCode '
	END
					
	 SELECT @SQLSELECT='INSERT INTO #ptype	
					(
						[typeid],
						[parid],
						[总计浮动数量],
					     unitname,
						assistantname,
						basename
						
					)'+@SQLSELECT				
					

EXEC(@SQLSELECT)
--select * from #ptype	
--return

CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)

DECLARE @Xjkang varchar(MAX)
SET @Xjkang = 'INSERT INTO #TempStock1 
				SELECT a.cargoid,a.UserCode,a.FullName 
				FROM CargoType a  
				inner join #GetSelectCargoid b on a.cargoid =b.cargoid 
				WHERE  ktypeid IN (SELECT * FROM #GetManKTypeId)  
				ORDER BY UserCode '
EXEC(@Xjkang)



SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(@StockPageRows AS varchar(50)) + ' 
				TypeID,				
				UserCode,			
				FullName
	    FROM    #TempStock1 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@StockPageNo-1) * @StockPageRows AS varchar(50)) + ' UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '

EXEC(@xjkang)



CREATE TABLE #GsStock
(
	PTypeId	VARCHAR(100),
	Qty	 NUMERIC(24, 10) ,
	baseQty	 NUMERIC(24, 10) ,
	KTypeID	VARCHAR(100),
	NQty  NUMERIC(24, 10) ,
	cargoid int	

)



SET @GsSql='
	INSERT INTO #GsStock
	SELECT	P.TypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,
			ISNULL(SUM(Qty),0) AS baseQty,
			q.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty,
			q.cargoid
	FROM	#ptype p 
	inner join ptype p1 on p1.typeid=p.typeid
	INNER JOIN FactStocks_Qty q ON q.ptypeid = p.typeid and q.PTypeId LIKE p.TypeId+''%''
	INNER JOIN #GetManKTypeId K ON Q.KTYPEID=K.TYPEID  
	INNER JOIN #GetSelectCargoid d on q.cargoid=d.cargoid'+ @tmptab
		
	SET @GsSql = @GsSql + '	GROUP BY P.TypeId,q.KTypeID,q.cargoid'
	
EXEC(@GsSql)





SET @Sql = '
	UPDATE #ptype
	SET	[总计实物库存]=B.Qty,
		[总计浮动数量]=B.nqty  ,
		[总计自定义辅助数量]=dbo.F_GetCustomAssist(A.TypeId, B.baseQty)
	FROM #ptype a
	INNER JOIN (
				SELECT	A.TypeId,
						SUM(ISNULL(G.Qty,0)) AS Qty,
						SUM(ISNULL(G.baseQty,0)) AS baseQty,
						sum(isnull(g.nqty,0))as nqty
				FROM 	#ptype A
				LEFT JOIN #GsStock G ON  G.PTypeId = A.TypeId
				GROUP BY A.TypeId
				)B ON A.TypeId = B.TypeId'

--PRINT(@Sql)
EXEC(@Sql)



DECLARE @TempTable VARCHAR(100)
SELECT @TempTable='##Temp'+REPLACE(NEWID(),'-','')

SET @SQL='	SELECT 	A.[typeId],
					A.[parid],
					A.[总计实物库存],
					a.unitname,
					a.[总计浮动数量],
					a.assistantname,
					a.basename,
					a.[总计自定义辅助数量],
					D.*
			FROM #ptype A 
			LEFT JOIN (
					SELECT  C.TYPEID AS PTYPEID'	
				
SELECT	@SQL=@SQL + ',['+FullName+'实物库存]=dbo.F_RoundQty(SUM(CASE WHEN  bb.cargoid = '''+typeid+''' THEN bb.Qty ELSE 0 END)/r.rate)
                     ,['+FullName+'浮动数量]=SUM(CASE WHEN  bb.cargoid = '''+typeid+''' THEN bb.NQty ELSE 0 END)
                     '+',['+FullName+'自定义辅助数量]=dbo.F_GetCustomAssist(C.TYPEID, SUM(CASE WHEN  bb.cargoid = '''+typeid+'''  THEN  bb.Qty  ELSE 0 END)) '	
					FROM  #TempStock order by UserCode
SET @Sql = @Sql +'  FROM #ptype c
					--LEFT JOIN (
					--			SELECT	e.TypeId,
	 			--						g.ktypeid,
					--					SUM(ISNULL(G.Qty,0)) AS Qty,
					--					SUM(ISNULL(G.NQty,0)) AS NQty,
					--					g.cargoid
					--			FROM 	#ptype e
					--			LEFT JOIN #GsStock G ON G.PTypeId =e.TypeId
					--			GROUP BY e.TypeId,g.ktypeid,g.cargoid
					--			) b on c.typeid=b.typeid
					 LEFT JOIN (
								SELECT	
										SUM(ISNULL(G.Qty,0)) AS Qty,
										SUM(ISNULL(G.NQty,0)) AS NQty,
										g.cargoid,
										g.ktypeid,
										g.ptypeid
								FROM  FactStocks_Qty g
								GROUP BY g.ktypeid,g.cargoid,g.ptypeid
								) bb on c.typeid=bb.ptypeid --and bb.cargoid=b.cargoid and bb.ktypeid=b.ktypeid
					LEFT JOIN ptype p1 ON p1.typeid = c.typeid '
							
IF @unitconvert=0
BEGIN	
	SET @sql = @sql + ' 	
	LEFT JOIN PType_Units_Ext r ON r.PTypeId = p1.TypeId AND p1.saleUnitId = r.UnitsId
	 '
END
ELSE IF @unitconvert=1
BEGIN			
	SET @sql = @sql + ' 	
	LEFT JOIN PType_Units_Ext r ON r.PTypeId = p1.TypeId AND p1.buyUnitId = r.UnitsId
	 '
END
else IF @unitconvert=2
BEGIN	
	SET @sql = @sql + ' 	
	LEFT JOIN PType_Units_Ext r ON r.PTypeId = p1.TypeId AND p1.StockUnitId = r.UnitsId
	 '
END
else --IF @unitconvert=3
BEGIN	
	SET @sql = @sql + ' 	
	LEFT JOIN PType_Units_Ext r ON r.PTypeId = p1.TypeId AND p1.baseUnitId = r.UnitsId
	 '
END		

set @sql = @sql +'	
						
						GROUP BY c.typeid,r.rate
						)D ON A.TypeId = D.ptypeId'	 
	IF @Flag=0
		SELECT @SQL=@SQL+'order by '+CONVERT(varchar(4),@INDEX)+@Sort
	

EXEC(@sql)	
 
DROP TABLE #GetManKTypeId,#GetSelectCargoid,#GetSelectSTypeId,#GsStock,#TempStock,#TempStock1,#ptype

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStockDisList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStockDisList]
GO


/*
	作者：谢吉康
	日期：2016-07-08
	描述：实物库存分布表树型表
	EXEC Web_QueryFactStockDisList '00001','00000',14,1,0,1,1,'ASC',1,'00001'
*/
CREATE PROCEDURE Web_QueryFactStockDisList
(
	@OperatorID 	varchar(100),    --操作员id
	@PTypeId 		varchar(100)='00000',
	@PageRows 		int=14,
	@StockPageRows	int=10,
	@GoPageNo 		int=0,
	@fzsl			varchar(1)='0',--是否显示辅助数量
	@cbjj			varchar(1)='1',--是否显示成本均价
	@cbje			varchar(1)='1',--是否显示成本金额
	@Flag 			int=1,
	@Index 			int=1,
	--@Sort 			char(4)='ASC',
	@StockPageNo 	int,
	@srcKTypeId		varchar(MAX),
	@stypeid		VARCHAR(MAX),
	@unitconvert    VARCHAR(10),    --多单位种类
	@sort		    VARCHAR(20),
	@showstockstop	INT =0 ,--是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid VARCHAR(max)=''
	
 )
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Sql varchar(max)=''
DECLARE @ReSql varchar(max)
DECLARE @TableName varchar(max)
DECLARE @Condition varchar(max)			--谢吉康    2003-9-25  加大了变量的长度
DECLARE @i int,@j int

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @re_check INT
EXEC @re_check=GP_CheckLimit @OperatorID,453
DECLARE @RS_CHECK INT
EXEC @RS_CHECK=dbo.GP_CheckLimit @OperatorID,2642

---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
IF @RS_CHECK=0
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
ELSE 
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,'00001')
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @re_check = 0
BEGIN 
IF  @showstockstop=0
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId
ELSE
   INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId INNER JOIN dbo.Stock ss ON ss.typeId=k.TypeId WHERE deleted=0
	
END 	
ELSE	
BEGIN
	IF  @showstockstop=0
		INSERT INTO #GetManKTypeId(TypeId) SELECT s.typeid FROM Stock s,#GetSelectSTypeId st WHERE S.STypeID = St.typeId AND s.sonnum = 0
	ELSE 
	    INSERT INTO #GetManKTypeId(TypeId) SELECT s.typeid FROM Stock s,#GetSelectSTypeId st WHERE S.STypeID = St.typeId AND s.sonnum = 0 AND deleted=0	
END	

--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),
        @temprice   VARCHAR(2000)

IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/r3.rate',
		@UnitName = 'u5.fullname as assistantfullname',
		@temprice='g.price*r3.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/r2.rate',
		@UnitName = 'u5.fullname as assistantfullname',
		@temprice='g.price*r2.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/r4.rate',
		@UnitName = 'u5.fullname as assistantfullname',
		@temprice='g.price*r4.rate',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'u5.fullname as assistantfullname',
		@temprice='g.price',
		@tmptab =dbo.F_GetPtypeUnitsAndRates('p1','5','')
END
----------多单位计算End---------
			 
------------------------------------------计算出应查询的仓库-----------------------------------------------

CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)

DECLARE @SortStockCount int
DECLARE @SortStockAddRec int
DECLARE @TempKTypeID varchar(100)
DECLARE @TempKName varchar(MAX)
SELECT @SortStockCount=1
SELECT @SortStockAddRec=0

--处理仓库
DECLARE @KTypeIds 		varchar(MAX),
		@Where_KTypeId	varchar(MAX),
		@x 				int


SET @Where_KTypeId = ''

SET @srcKTypeId = RTRIM(LTRIM(@srcKTypeId))
SET @x = charindex(',',@srcKTypeId)

WHILE @x>=1
	BEGIN
		SET @KTypeIds = LEFT(@srcKTypeId,@x-1)

		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (TypeId LIKE '+char(39)+@KTypeIds+'%'+char(39)
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR TypeId LIKE '+char(39)+@KTypeIds+'%'+char(39)

		SET @srcKTypeId=SUBSTRING(@srcKTypeId,@x+1,LEN(@srcKTypeId)-@x)
		SET @x=charindex(',',@srcKTypeId)
	END

IF @srcKTypeId<>''
	BEGIN
		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (TypeId LIKE '+char(39)+@srcKTypeId+'%'+char(39)+')'
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR TypeId LIKE '+char(39)+@srcKTypeId+'%'+char(39)+')'
	END

DECLARE @Xjkang varchar(MAX)
SET @Xjkang = 'INSERT INTO #TempStock1 SELECT TypeId,UserCode,FullName FROM Stock WHERE SonNum = 0 AND TypeID IN (SELECT * FROM #GetManKTypeId) '+@Where_KTypeId+' ORDER BY UserCode '
EXEC(@Xjkang)
--print @xjkang
SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(@StockPageRows AS varchar(50)) + ' 
				TypeID,				
				UserCode,			
				FullName
	    FROM    #TempStock1 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@StockPageNo-1) * @StockPageRows AS varchar(50)) + ' UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '

EXEC(@xjkang)
------------------------------------------上段程序结束-----------------------------------------------


CREATE TABLE #ptype
	(
		[typeId] 		[varchar] (100) NOT NULL,
		[parid] 		[varchar] (100) NOT NULL,
		[父节点] 		varchar(100) NOT NULL,
		[商品编号] 		[varchar] (200) NULL ,
		[商品名称] 		[varchar] (256) NOT NULL ,
		商品条码		varchar(256) NULL,
		商品规格		varchar(256) NULL,
		商品型号		varchar(256) NULL,
		商品产地		varchar(256) NULL,
		[总计实物库存] 	 NUMERIC(24, 10) ,
		--[总计成本均价] 	 NUMERIC(24, 10) ,
		--[总计成本金额] 	 NUMERIC(24, 10) ,
		unitname         VARCHAR(200),
		nqty             NUMERIC(24, 10) ,
		sortid    INT
	)

DECLARE @SonNum INT,@GsSql VARCHAR(1000),@SQLSELECT VARCHAR(MAX)=''
SELECT @SonNum = SonNum FROM PType WHERE TypeId = @PTypeId

----------------
--注:下语句中使用F_GetManPType比创建临时表快,在ptype中记录大的时候,所以不用临时表--韩林
----------------
SET @SQLSELECT = '    
    SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
			q.TypeID,
			q.parid,
			q.SonNum,
			q.UserCode,
			q.FullName,
			ISNULL(q.EntryCode,'''') AS EntryCode,
			ISNULL(q.Standard,'''') AS Standard,
			ISNULL(q.Type,'''') AS Type,
			ISNULL(q.Area,'''') AS Area,
			'+@UnitName+',
			p1.sortid
    FROM    F_GetManPType('''+@OperatorID+''') q
    INNER JOIN ptype p1 on p1.typeid=q.typeid '+@tmptab+'
    WHERE  	q.TypeID <> ''00000''	
            and q.IsService=0
            AND q.iscombinationproduct = 0 
			AND q.UserCode NOT IN                    
			(
				SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' p.UserCode
				FROM	F_GetManPType('''+@OperatorID+''')   p
				--inner join #tmpPtype tp on tp.typeid like q.typeid +''%''
				WHERE   p.TypeID <> ''00000''	  
						and p.IsService=0
						AND p.iscombinationproduct = 0
						AND '+CASE @SonNum WHEN 0 THEN 'p.TYPEID' ELSE  'p.ParId' END + '='+char(39)+@PTypeId+char(39)+'
				ORDER BY UserCode
			) 
			AND '+CASE @SonNum WHEN 0 THEN 'q.TYPEID' ELSE  'q.ParId' END + '='+char(39)+@PTypeId+char(39)+'
    ORDER BY q.UserCode '
	
SELECT @SQLSELECT='INSERT INTO #ptype	
					(
						[typeid],
						[parid],
						[父节点],
						[商品编号],
						[商品名称],
						商品条码,
						商品规格,
						商品型号,
						商品产地,
						unitname
						,sortid
					)'+@SQLSELECT
--PRINT(@SQLSELECT)
EXEC(@SQLSELECT)

CREATE TABLE #GsStock
(
	PTypeId	VARCHAR(100),
	Qty	 NUMERIC(24, 10) ,
	KTypeID	VARCHAR(100),
	NQty  NUMERIC(24, 10) 
)

CREATE TABLE #GsStock1
(
	PTypeId	VARCHAR(100),
	Qty	 NUMERIC(24, 10) ,--由于这里在换算的时候是先换算再相加 所以会造成与线性表有误差。故把小数倍数放大。这样就能保证与线性表一致	
	KTypeID	VARCHAR(100),
	NQty  NUMERIC(24, 10) 
)

SET @GsSql='
	INSERT INTO #GsStock
	SELECT	g.pTypeId ,
			ISNULL(SUM('+@Qty+'),0) AS Qty,			
			G.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty
	FROM	#ptype p
	INNER JOIN (select ptypeid,ktypeid FROM FactStocks a
	group by ptypeid,ktypeid) g  ON g.PTypeId LIKE p.TypeId+''%'' 
	INNER JOIN FactStocks_Qty Q ON Q.ptypeid = G.ptypeid   and  g.ktypeid=q.ktypeid 
	inner join ptype p1 on p1.typeid=g.ptypeid
	INNER JOIN	#TempStock K ON G.KTypeId=k.typeid' + @tmptab
	SET @GsSql = @GsSql + '	GROUP BY g.pTypeId,G.KTypeID'
EXEC(@GsSql)

SET @GsSql='
	INSERT INTO #GsStock1
	SELECT	g.pTypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,			
			G.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty
	FROM	#ptype p
	INNER JOIN (select ptypeid,ktypeid FROM FactStocks a
	--inner join #tmpPtype b on a.ptypeid=b.typeid 
	group by ptypeid,ktypeid) g  ON g.PTypeId LIKE p.TypeId+''%'' 
	INNER JOIN FactStocks_Qty Q ON Q.ptypeid = G.ptypeid   and  g.ktypeid=q.ktypeid 
	inner join ptype p1 on p1.typeid=g.ptypeid
	INNER JOIN	#TempStock1 K ON G.KTypeId=k.typeid' + @tmptab
	SET @GsSql = @GsSql + '	GROUP BY g.pTypeId,G.KTypeID'
EXEC(@GsSql)

SET @Sql = '
	UPDATE #ptype
	SET	[总计实物库存]=B.Qty,
		nqty=b.nqty
	FROM #ptype a
	INNER JOIN (
				SELECT	A.TypeId,
						SUM(ISNULL(G.Qty,0)) AS Qty,
					    SUM(ISNULL(G.nqty,0)) AS nqty
				FROM 	#ptype A
				LEFT JOIN #GsStock1 G ON  G.PTypeId like  A.TypeId +''%'' 
				GROUP BY A.TypeId
				)B ON A.TypeId = B.TypeId'

--PRINT(@Sql)
EXEC(@Sql)
IF @@error<>0
	BEGIN
		--RAISERROR('更新商品总数量生错误！',16,1)
		RETURN
	END

DECLARE @TempTable VARCHAR(100)
SELECT @TempTable='##Temp'+REPLACE(NEWID(),'-','')

SET @SQL='	SELECT 	A.[typeId],
					A.[parid],
					A.[父节点],
					A.[商品编号],
					A.[商品名称], 
					A.商品条码,
					A.商品规格,
					A.商品型号,
					A.商品产地,
					A.[总计实物库存],
					a.nqty,
					D.*'
			+CASE @fzsl WHEN '1' THEN 'INTO '+@TempTable ELSE '' END+'
			FROM #ptype A 
			LEFT JOIN (
					SELECT C.TYPEID AS PTYPEID,case when max([父节点])>0 then null else B.UNITNAME end AS unitname'	
				
SELECT	@SQL=@SQL + ',['+FullName+'实物库存]=SUM(CASE WHEN  b.ktypeId = '''+typeid+''' THEN b.Qty ELSE 0 END)
                     ,['+FullName+'浮动数量]=SUM(CASE WHEN  b.ktypeId = '''+typeid+''' THEN b.NQty ELSE 0 END)'
					+CASE @fzsl WHEN '1' THEN ',['+FullName+'辅助数量]=CAST('''' AS VARCHAR(100))' ELSE '' END	
						FROM  #TempStock order by UserCode
SET @Sql = @Sql +'
					FROM #ptype c
					LEFT JOIN (
								SELECT	e.TypeId,
										g.ktypeid,
										SUM(ISNULL(G.Qty,0)) AS Qty,									
										SUM(ISNULL(G.NQty,0)) AS NQty,
										e.unitname
								FROM 	#ptype e
								left JOIN #GsStock G ON G.PTypeId LIKE e.TypeId +''%'' 
								GROUP BY e.TypeId,g.ktypeid,e.unitname
								) b on c.typeid=b.typeid
						GROUP BY c.typeid,b.unitname	
						)D ON A.TypeId = D.ptypeId
				ORDER BY '
		     if  @Sort=''
			  SELECT @SQL+=' A.[sortid] '
			 else
			   SELECT @SQL+=@Sort

IF @fzsl='1'
BEGIN
	--PRINT(@SQL)
	EXEC(@sql)	
	
	IF EXISTS(SELECT * FROM #TempStock)
	BEGIN
		SET @SQL=''
		SELECT @SQL=@SQL+'['+fullname+'辅助数量]=CASE
							WHEN 单位关系='''' THEN ''''
							WHEN ['+FullName+'实物库存]=0 THEN ''''
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(['+FullName+'实物库存])/关系 as  NUMERIC(24, 10) )<1	THEN CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) ) AS varchar(100))+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(ISNULL(['+FullName+'实物库存],0))/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) as  NUMERIC(24, 10) )>=1 AND CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))<>''0'' THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(ISNULL(['+FullName+'实物库存],0))/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) as  NUMERIC(24, 10) )>=1 AND CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))=''0''  THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ISNULL(['+FullName+'实物库存],0)>0 AND ['+FullName+'实物库存]<关系 THEN CAST(['+FullName+'实物库存] AS varchar(100))+单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 as  NUMERIC(24, 10) ) AS varchar)+大单位	
							WHEN ['+FullName+'实物库存]/关系>=1 AND ['+FullName+'实物库存]/关系 = CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) THEN CAST(CAST(['+FullName+'实物库存]/关系 as  numeric(18,0)) as varchar)+大单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 as  numeric(18,0)) as varchar)+大单位
							WHEN ['+FullName+'实物库存]/关系>=1 THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))+单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位				
							ELSE ''0''+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
						 END,' from #TempStock s ORDER BY USERCODE
		IF RIGHT(@SQL,1)=','
			SET @Sql=LEFT(@Sql,LEN(@SQL)-1)
		SET @SQL='UPDATE '+@TempTable
				+' SET '+@Sql
		--PRINT(@SQL)
		EXEC(@sql)	
	END
	SET @SQLSELECT='SELECT * FROM '+@TempTable
	IF @Flag=0
		SELECT @SQLSELECT=@SQLSELECT+' ORDER BY '+CONVERT(varchar(4),@INDEX)+@Sort
	--print(@sqlselect)
	EXEC(@SQLSELECT)
	
	-- 删除临时表
	SELECT @ReSql='DROP TABLE '+@TempTable
	EXEC(@ReSql)
END
ELSE
BEGIN
	IF @Flag=0
		SELECT @SQL=@SQL+' ,'+CONVERT(varchar(4),@INDEX)+@Sort
		
	--PRINT(@SQL)
	EXEC(@sql)	
END	

DROP TABLE #GsStock ,#GetManKTypeId, #GetSelectSTypeId,#TempStock,#ptype,#TempStock1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (
  SELECT 
	* 
  FROM dbo.sysobjects 
  WHERE id = OBJECT_ID(N'[dbo].[Web_QueryFactStocks_Detail]') 
    AND OBJECTPROPERTY(id, N'IsProcedure') = 1
  )
	DROP procedure [dbo].[Web_QueryFactStocks_Detail]
GO



/*
	作者：谢吉康
	日期：2016-07-06
	描述：实物库存余量表明细表
*/
CREATE PROCEDURE Web_QueryFactStocks_Detail
( 
	@startdate		VARCHAR(25),
	@EndDate		VARCHAR(25),
	@AtypeId		VARCHAR(8000),
	@typeId			VARCHAR(max),
	@BtypeId		VARCHAR(8000),
	@KtypeId		VARCHAR(8000),
	@eTypeId		VARCHAR(8000),
	@cMode			VARCHAR(2),
	@sortfield		VARCHAR(25),
	@OperatorId     VARCHAR(100),			--操作员ID
	@showRedWord	CHAR(1)='0',
	@intType        INT='',
	@stypeid		VARCHAR(8000)='00001',	--分支机构
	--@isEtypeRightEnable BIT,		--库存明细表经手人限制是否启用
	@isshowstop     int=0,                  --是否显示停用 0显示停用，1为不显示。
	@IsReporting	INT,			--是否打印、导出 0 = 正常查询，1 = 打印、导出
	@PageType		VARCHAR(50),		--if(PageType='V') 虚拟库存 else 库存状况表
	@ptypeCategoryid VARCHAR(max)='',
	@showstockstop INT =0 --是否显示停用仓库数据 1为不显示 0为显示
)

--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1

DECLARE 
  @Re INT,
  @MAtypeid	  VARCHAR(50), 
  @MBtypeid	  VARCHAR(50), 
  @MBtypeid2  VARCHAR(50), 
  @MEtypeid	  VARCHAR(50),
  @MKtypeid	  VARCHAR(50), 
  @MPtypeid	  VARCHAR(50), 
  @MExpense	  VARCHAR(50), 
  @MIncome	  VARCHAR(50),
  @MCapital	  VARCHAR(50),
  @MDtypeid	  VARCHAR(50),
  @MStypeid	  VARCHAR(50)

EXEC @Re = GP_CheckOperatorRight23_Rep 
			@OperatorID, 
			@MAtypeid OUTPUT,
			@MBtypeid OUTPUT,
			@MBtypeid2 OUTPUT,
			@MEtypeid OUTPUT,
			@MKtypeid OUTPUT,
			@MPtypeid OUTPUT,
			@MExpense OUTPUT,
			@MIncome OUTPUT,
			@MCapital OUTPUT,
			@MDtypeid OUTPUT,
			@MStypeid OUTPUT
IF @Re <> 0 
  RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

-- 选择分支机构
CREATE TABLE #GetSelectSTypeId
(
  TypeId varchar(100)
)
INSERT INTO #GetSelectSTypeId(TypeId) 
  SELECT typeid 
  FROM F_GetAllManagerBaseTypeId(@stypeid, 11, @OperatorID)
		
-- 经手人条件筛选表 Add by Haiyang, Li 2012-03-28
--****************


--检测经手人权限是否有效
DECLARE @limt INT 
Exec @limt= GP_CheckLimit @OperatorID,2374


CREATE TABLE #GetSelETypeId
(
  TypeId VARCHAR(100)
)
IF @limt = 0 
    INSERT  INTO #GetSelETypeId
            ( TypeId
            )
            SELECT  typeid
            FROM    F_GetAllManagerBaseTypeId(@eTypeId, 3, @OperatorID)
  
ELSE 
    INSERT  INTO #GetSelETypeId
            ( TypeId
            )
            SELECT  TypeId
            FROM    F_GetAllBaseTypeId(@eTypeId, 3)
  
--****************



--筛选仓库
CREATE TABLE #GetSelKTypeId
(
  TypeId varchar(100)
)
  IF @showstockstop = 0 
  INSERT  INTO #GetSelKTypeId
            ( TypeId
            )
    SELECT  typeid
    FROM    F_GetAllManagerBaseTypeId(@KtypeId, 4, @OperatorID)
  ELSE 
    INSERT  INTO #GetSelKTypeId
            ( TypeId
            )
            SELECT  a.typeid
            FROM    F_GetAllManagerBaseTypeId(@KtypeId, 4, @OperatorID) a
                    INNER JOIN dbo.Stock b ON a.TypeId = b.typeId
            WHERE   b.deleted = 0
DELETE FROM #GetSelKTypeId --删除不在权限范围内的分支机构下的仓库
  WHERE TypeId NOT IN( SELECT TypeId FROM STOCK WHERE STypeID IN (SELECT TypeId FROM #GetSelectSTypeId))

---筛选往来单位
CREATE TABLE #GetBtype(Typeid NVARCHAR(200))
INSERT INTO #GetBtype(typeid)
SELECT TypeId FROM dbo.F_GetAllManagerBaseTypeId(@BtypeId,2,@OperatorId)


---筛选商品
CREATE TABLE #GetManPType
(
  TypeId VARCHAR(100)
)
INSERT INTO #GetManPType(TypeId) 
  SELECT typeid 
  FROM dbo.F_ManPTypeInCategoryID(@OperatorId,@typeId,@ptypeCategoryid) 



---彭勇优化加索引

CREATE CLUSTERED INDEX IX_GetManPType_TypeID ON #GetManPType(TypeID)
  
  

DECLARE @strQuery VARCHAR(1000)
SELECT @strQuery=''

-- 根据经手人过滤 Add by Haiyang, Li 2012-03-27
--****************
IF @OperatorId <> ''
	BEGIN
		--超级管理员(Admin)为不限经手人查询
		IF @EtypeID = '00001' 
			SELECT @strQuery = ''
		ELSE
			SELECT @strQuery = ' where a.EtypeId IN (SELECT TypeId FROM #GetSelETypeId)';
	END
--****************

DECLARE @Sql VARCHAR (max)

SELECT @SQL='
SELECT 	c.BillNumberId,
		c.ID AS CustomdetailID,
		a.BillDate,
		c.billtype,			
		c.ktypeid,
		c.ptypeid,
		c.qty,						
		c.cargoid,
		c.iscombined,
		c.itemid,
		c.munitid,
		c.nqty,
		c.goodsnumber 		
		,p1.fullname 
FROM Fact_InOutstocktable c  
INNER JOIN FactIndex a ON c.BillNumberId = a.BillNumberId  
INNER JOIN ptype p1 on  c.ptypeid=p1.typeid 
INNER JOIN #GetManPType on c.ptypeid = #GetManPType.typeid '
	
IF NOT(RTRIM(@ktypeid) ='0' AND @MKtypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetSelKTypeId sk ON sk.typeid = c.ktypeid ' 	

SET @SQL = @SQL +' WHERE c.BillNumBerId<>0 and a.billdate>='+CHAR(39)+@startdate+CHAR(39)+' 
					AND a.billdate<='+CHAR(39)+@enddate+CHAR(39)+'  and a.ifcheck=''t'''

IF @showRedWord = '0'
	SELECT @SQL = @SQL + ' and a.redword =0  '				
IF @isshowstop=1
	SET @SQL = @SQL + ' and p1.deleted=0  '	
IF UPPER(@cMode) <> 'S' AND UPPER(@cMode) <> 'B'
	SET @SQL = @SQL + ' AND c.ktypeid <> '+ CHAR(39) + '10000' + CHAR(39) + '  '	

IF UPPER(@cMode) = 'S'
 	SET @SQL = @SQL +' AND C.billtype IN(11,141,45,305,402,403) '	
 
IF UPPER(@cMode)='B'
	SET @SQL = @SQL + ' AND C.billtype IN(34,6,145,400,401) '
 

SELECT @Sql ='	SELECT	a.comment,
						row_number() over (order by c.BillnumberID) as row_id,
						c.CustomdetailID,
						c.BillNumberId,
						a.BillDate,
						c.billtype,
						CASE WHEN a.billtype=418 THEN ISNULL(c.qty,0)
							 WHEN a.billtype=420 and isnull(c.qty,0)>0 THEN ISNULL(c.qty,0)
							 ELSE 0
						end as rqty,
						CASE WHEN a.billtype=419 THEN ISNULL(-c.qty,0)
							 WHEN a.billtype=420 and isnull(c.qty,0)<0 THEN ISNULL(-c.qty,0)
						     ELSE 0
						END as cqty,												
						a.BillCode, 						
						a.RedWord, 
						CBillType= a.billtype,						
						c.ktypeid,
						c.ptypeid,						
						c.fullname,																	
						a.stypeid,											
						c.cargoid,
						c.goodsnumber,
						v.fullname AS itemfullname,
						c.nqty,
						p.fullname AS munitfullname,
						CASE WHEN a.billtype=145 AND -ISNULL(c.qty,0)>=0 THEN 	c.qty/pe.rate
						     WHEN a.billtype<>145 AND ISNULL(c.qty,0)>=0 THEN   c.qty/pe.rate
						  END AS rqnum,
						CASE WHEN a.billtype=145 AND -ISNULL(c.qty,0)<0 THEN    ABS(c.qty/pe.rate)
						     WHEN a.billtype<>145 AND ISNULL(c.qty,0)<0 THEN    ABS(c.qty/pe.rate)
						  END AS cqnum
			FROM 	FactIndex a
			INNER JOIN  #GetSelectSTypeId ss on a.stypeid=ss.typeid 			
			INNER JOIN	('+@sql+') c on	c.BillNumberId = a.BillNumberId
			left JOIN  vWeb_ItemIDByIsCombined v on c.iscombined = v.iscombined AND c.itemid = v.id
			left JOIN  PType_Units p on p.unitsid = c.munitid
			left JOIN  ptype_units_ext pe on pe.unitsid = c.munitid AND pe.ptypeid = c.ptypeid
			 '
DECLARE @GroupBy VARCHAR(2000)
SELECT @GroupBy ='  
			GROUP BY	c.BillNumberId,
						a.billdate,
						c.billtype,
						a.billtype,				
						c.qty,
						a.billcode,						
						a.redword,
						c.ptypeid,
						c.ktypeid,										
						a.stypeid,
						c.cargoid,'
					
					

IF @sortfield = 'ByDate_a'
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @sortfield = 'ByBillNo_a' 
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @sortfield = 'ByBillType_a'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'
ELSE IF @sortfield = 'ByDate_d'		
    SELECT @GroupBy = @GroupBy + ' c.billdate, c.billtype, a.BillCode'
ELSE IF @sortfield = 'ByBillNo_d' 	
    SELECT @GroupBy = @GroupBy + ' a.BillCode'
ELSE IF @sortfield = 'ByBillType_d'	
    SELECT @GroupBy = @GroupBy + ' c.billtype, c.billdate, a.BillCode'


DECLARE @SQLOrder	VARCHAR(150)
SELECT @SQLOrder = ''

DECLARE @qty NUMERIC(24,10)

CREATE TABLE #Qty(qty NUMERIC(24,10),
Total         NUMERIC(24,10)
)

insert #Qty exec Gp_GetPreDateQtyOrTotal @OperatorID,
	@StartDate,	
	@typeId,	
	@KTypeId,	
	@etypeid,	
	@stypeid	
SELECT @qty=ISNULL(qty,0) FROM #Qty
DECLARE @tmpSQL NVARCHAR(3000)
SET @tmpSQL='dbo.F_GetCustomAssist(a.ptypeid,'+convert(nvarchar(100),@qty)+'+rqty-cqty)'


	IF @sortfield = 'ByDate_a'		
		SELECT @SQLOrder = ' ORDER BY billdate, billtype, BillCode'
	ELSE IF @sortfield = 'ByBillNo_a' 	
		SELECT @SQLOrder = ' ORDER BY BillCode'
	ELSE IF @sortfield = 'ByBillType_a'	
		SELECT @SQLOrder = ' ORDER BY billtype, billdate, BillCode'	
	ELSE IF @sortfield = 'ByDate_d'		
		SELECT @SQLOrder = ' ORDER BY billdate DESC, billtype, BillCode'
	ELSE IF @sortfield = 'ByBillNo_d' 	
		SELECT @SQLOrder = ' ORDER BY BillCode DESC'
	ELSE IF @sortfield = 'ByBillType_d'	
		SELECT @SQLOrder = ' ORDER BY billtype DESC, billdate, BillCode'		

	SET @SQL ='SELECT *, CAST(0 AS NUMERIC(24,10)) AS ljcalCustomQty INTO #Result FROM (' + @SQL +') AS A ' + @SQLOrder 
	+' 
				declare @iqty numeric(24,10) = '+ cast(@qty as varchar(50))+'
				update #Result set @iqty = @iqty+ISNULL(rqty,0) - ISNULL(cqty,0),  ljcalCustomQty=@iqty
	
			  	SELECT a.*, SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head, 
						SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
						SysDiy17_head,SysDiy18_head,SysDiy19_head,SysDiy20_head,SysDiy21_head,SysDiy22_head,SysDiy23_head,
						SysDiy24_head,SysDiy25_head,SysDiy26_head,SysDiy27_head,SysDiy28_head,SysDiy29_head,SysDiy30_head,
						SysDiy31_head,SysDiy32_head,
						SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
						SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16,
						SysDiy17,SysDiy18,SysDiy19,SysDiy20,SysDiy21,SysDiy22,SysDiy23,SysDiy24,
						SysDiy25,SysDiy26,SysDiy27,SysDiy28,SysDiy29,SysDiy30,SysDiy31,SysDiy32,	'+convert(nvarchar(100),@qty)+'+ISNULL(rqty,0) - ISNULL(cqty,0) AS tex,'					
			SET @SQL +=' customassist= dbo.F_GetCustomAssist(a.ptypeid,ljcalCustomQty)			
				FROM #Result a 
				LEFT JOIN Custom_BillIndex csindex on a.billnumberid=csindex.BillId and a.billtype=csindex.billtype
				LEFT JOIN Custom_BillDetails csdetail on a.billnumberid=csdetail.BillId and a.billtype=csdetail.billtype AND a.CustomdetailID=csdetail.Detailid	' + @SQLOrder +'		
				DROP TABLE #Result
			   '
	--SELECT(@sql)
	EXEC (@SQL)

----------------------------------------------------------
DROP TABLE #GetSelKTypeId, #GetSelectSTypeId, #GetManPType,#GetBtype,#GetSelETypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryFactStocks_Line]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Web_QueryFactStocks_Line
GO
 --	=======================================
 --	描述:实物库存余量线性表
 --	时间:2016-07-06
 --	作者:谢吉康
 -- exec Web_QueryFactStocks_Line @OperatorId='00001',@Parid='',@StypeIds='00001',@KtypeIds='',@DisplayActual=0,@DisplayStop=1,@PriceType=0,@Date=NULL,@DisplayZero=1,@FilterPtypeFullName='',@FilterPtypeUserCode='',@FilterPtypeEntryCode='',@FilterPtypeArea='',@Type='',@Standard='',@vpathVisible=0,@showstockstop=0,@ptypeCategoryid='',@intItypeId='0'
 --	=======================================
CREATE PROCEDURE Web_QueryFactStocks_Line
(
	@OperatorId				VARCHAR(100)='' --操作员id
	,@Parid					VARCHAR(100)='00000' --父类商品Id,
	,@StypeIds				VARCHAR(max)='' --分支机构ids
	,@KtypeIds				VARCHAR(max)='' --仓库ids
	,@DisplayActual			INT=0 --是否显示实际库存 1显示 0不显示
	,@DisplayStop			INT=0 --是否显示停用商品   1 显示 0不显示
	,@PriceType				INT=0 --显示价格方式 0~19表示20种不同的价格方式
	,@Date					DATETIME=NULL --时间,截止时间,用于历史状况的查询
	
	,@DisplayZero			INT =1 --是否显示为0的数据 1显示 0不显示
	,@FilterPtypeFullName	VARCHAR(100)='' --筛选 商品名称
	,@FilterPtypeUserCode	VARCHAR(100)='' --筛选 商品编号
	,@FilterPtypeEntryCode	VARCHAR(100)='' --筛选 商品条码
	,@FilterPtypeArea		VARCHAR(100)='' --筛选 商品地域
	,@Type					VARCHAR(200)=''--筛选 商品地域
	,@Standard				VARCHAR(200)=''
	,@vpathVisible			INT,   ---是否显示商品路径
	@showstockstop			INT =0, --是否显示停用仓库数据 1为不显示 0为显示	
	@ptypeCategoryid		VARCHAR(max)='',
	@intItypeId				VARCHAR(10) = '0'	
)
--@encode$--	
AS
BEGIN
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
			   @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------

	--DECLARE @sonnum INT;
	DECLARE @innerPtypeId VARCHAR(100)='';
	
	DECLARE @FilterPtypeId VARCHAR(100)='';
	IF @Parid='' 
		SET @Parid='00000';
		
	IF @Parid='00000' AND @MPtypeid<>'-99999'
		SET @Parid=@MPtypeid;
	
	--SELECT @sonnum=sonnum FROM ptype WHERE typeid=@Parid;
	IF @Parid<>'00000'
		SET @innerPtypeId=@Parid;
	ELSE
		SET @ParId='';
	
	--把权限函数提出来
	CREATE TABLE #KStype(TypeId VARCHAR(50),STypeId VARCHAR(50));
	CREATE TABLE #BTType(TypeId VARCHAR(50));
	CREATE CLUSTERED INDEX #KStype_t ON #KStype(TypeId);
	CREATE CLUSTERED INDEX #BTType_t ON #BTType(TypeId);
	
	INSERT INTO #KStype SELECT TypeId,STypeId  FROM F_GetManDetailKTypeSType(@OperatorId);
	INSERT INTO #BTType SELECT TypeId  FROM F_GetAllManagerBaseTypeId(@StypeIds,11,@OperatorID);

	CREATE TABLE #Ktype(TypeId VARCHAR(50));
	CREATE CLUSTERED INDEX #Ktype_t ON #Ktype(TypeId);
	
	IF  @showstockstop=0
		INSERT INTO #KType SELECT TypeId FROM F_GetAllBaseTypeId(@KtypeIds,4) 
	ELSE
		INSERT INTO #KType SELECT a.TypeId FROM F_GetAllBaseTypeId(@KtypeIds,4)a INNER JOIN dbo.Stock s ON a.TypeId=s.typeId  WHERE  s.deleted=0
	
	--权限范围内的商品线性表
	CREATE TABLE #ptype(TypeId	varchar(100))
	
	--判断存货核算类型
	IF @intItypeId = '0'
		INSERT INTO #ptype(TypeId) 
		SELECT	a.TypeId 
		FROM	dbo.F_ManPTypeInCategoryID(@OperatorID,@parid,@ptypeCategoryid) a
	ELSE
		INSERT INTO #ptype(TypeId) 
		SELECT	a.TypeId 
		FROM	dbo.F_ManPTypeInCategoryID(@OperatorID,@parid,@ptypeCategoryid) a
		INNER JOIN Ptype  p ON a.typeid = p.typeid
		
	  
		
	CREATE TABLE #goods(PtypeId VARCHAR(50),KtypeId VARCHAR(50));
	CREATE CLUSTERED INDEX #goods_p_k ON #goods(PTypeId,KtypeId)
	
	CREATE TABLE #inigoods(PtypeId VARCHAR(50),KtypeId VARCHAR(50));
	CREATE CLUSTERED INDEX #inigoods_p_k ON #inigoods(PTypeId,KtypeId)

	IF @Date IS NULL
	BEGIN
		INSERT INTO #goods 
		SELECT DISTINCT PtypeId,KtypeId
		FROM dbo.FactStocks
		INNER JOIN #ptype p ON p.TypeId=PtypeId
		WHERE PtypeId LIKE @innerPtypeId+'%'
		AND KtypeId IN (SELECT TypeId FROM #Ktype)
		AND KtypeId IN (
				SELECT u.TypeId FROM #KStype u
					JOIN #BTType v ON u.STypeId=v.TypeId
			) --操作员仓库权限
	END
	
	IF @Date IS NOT NULL
	BEGIN
		INSERT	INTO #inigoods
		SELECT	DISTINCT PtypeId,KtypeId
		FROM	dbo.IniFactStocks
		INNER JOIN #ptype p ON p.TypeId=PtypeId
		WHERE KtypeId IN (
				SELECT u.TypeId FROM #KStype u
					JOIN #BTType v ON u.STypeId=v.TypeId
			) --操作员仓库权限
			AND KtypeId IN (SELECT TypeId FROM #Ktype)				
			AND PtypeId LIKE @innerPtypeId+'%'
	END
	--

	CREATE TABLE #cte
	(
		PtypeId VARCHAR(50),
		qty  NUMERIC(24, 10) ,
		nqty  NUMERIC(24, 10) ,
		lockqty NUMERIC(24, 10)	
	);
	CREATE CLUSTERED INDEX #cte_p ON #cte(PtypeId);

	--库存
	INSERT INTO #cte
	SELECT a.PtypeId,SUM(b.Qty) AS qty,SUM(b.NQty) AS nqty,0
	FROM #goods a LEFT JOIN dbo.FactStocks_Qty b ON a.Ptypeid=b.PTypeID AND a.KtypeId=b.KTypeID
	WHERE @Date IS NULL
	GROUP BY a.PtypeId,a.KtypeId
	
	--UNION ALL
	--期初数据
	INSERT INTO #cte
	SELECT a.PtypeId,SUM(b.qty) AS qty,SUM(b.nqty) AS nqty,0
	FROM #inigoods a LEFT JOIN dbo.IniFactStocks_Qty b ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
	WHERE @Date IS NOT NULL 	
	GROUP BY a.PtypeId,a.KtypeId
	
	--出入库数据 
	INSERT INTO #cte
	SELECT PtypeId,CASE WHEN i.BillType=418 THEN i.qty ELSE -1*i.qty END qty,i.NQty,0
	FROM dbo.FactDepotInOut i
	INNER JOIN FactIndex fi ON i.billNumberID = fi.BillNumberId 
	INNER JOIN #ptype p ON p.TypeId=i.PtypeId
	WHERE @Date IS NOT NULL AND i.BillDate<=@Date AND --时间条件	
	i.KtypeId IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
	AND i.KtypeId IN (SELECT TypeId FROM #Ktype)
	AND i.PtypeId LIKE @innerPtypeId+'%'
	AND fi.ifcheck = 't'
	AND fi.RedWord = 0
	UNION ALL--调拨入库
	SELECT PtypeId,i.qty,i.NQty,0
	FROM dbo.FactDepotAllot i
	INNER JOIN FactIndex fi ON i.billNumberID = fi.BillNumberId 
	INNER JOIN #ptype p ON p.TypeId=i.PtypeId
	WHERE @Date IS NOT NULL AND fi.BillDate<=@Date AND --时间条件	
	i.KTypeId2 IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
	AND i.KTypeId2 IN (SELECT TypeId FROM #Ktype)
	AND i.PtypeId LIKE @innerPtypeId+'%'
	AND fi.ifcheck = 't'
	AND fi.RedWord = 0
	UNION ALL--调拨出库
	SELECT PtypeId,-i.qty,i.NQty,0
	FROM dbo.FactDepotAllot i
	INNER JOIN FactIndex fi ON i.billNumberID = fi.BillNumberId 
	INNER JOIN #ptype p ON p.TypeId=i.PtypeId
	WHERE @Date IS NOT NULL AND fi.BillDate<=@Date AND --时间条件	
	i.KTypeId IN (
			SELECT u.TypeId FROM #KStype u
				JOIN #BTType v ON u.STypeId=v.TypeId
		) --操作员仓库权限
	AND i.KtypeId IN (SELECT TypeId FROM #Ktype)
	AND i.PtypeId LIKE @innerPtypeId+'%'
	AND fi.ifcheck = 't'
	AND fi.RedWord = 0
	

	--临时表
	CREATE TABLE #t
	(
		PtypeId VARCHAR(50),
		qty  NUMERIC(24, 10) ,
		qty1  NUMERIC(24, 10) ,
		nqty  NUMERIC(24, 10) ,
		lockqty NUMERIC(24, 10)
	)
	CREATE CLUSTERED INDEX #t_p ON #t(ptypeid);
	
    INSERT  INTO #t
    SELECT  w.PtypeId ,
            SUM(qty) AS qty ,
            SUM(ISNULL(qty, 0.0) / ISNULL(U.rate, 1.0)) AS qty1 ,
            SUM(nqty) AS nqty ,
            SUM(ISNULL(lockqty,0)) AS lockqty
    FROM    #cte w
            INNER JOIN dbo.ptype p ON p.typeId = w.PtypeId
            INNER JOIN dbo.PType_Units_Ext u ON U.PtypeID = P.typeId
                                                AND U.UnitsId = P.StockUnitId
            INNER JOIN dbo.PType_Units v ON v.UnitsId = u.UnitsId
    GROUP BY w.PtypeId
    
    CREATE TABLE  #result
    (
		typeid VARCHAR(50),
		fullname VARCHAR(200),
		usercode  VARCHAR(200),
		sonnum int,
		leveal int,
		DELETED int,
		entrycode  VARCHAR(200),
		ParId VARCHAR(50),
		inventoryfullname VARCHAR(200),
		lockqty  NUMERIC(24, 10),
		Qty  NUMERIC(24, 10), 
		baseunitfullname VARCHAR(200),
		NQty  NUMERIC(24, 10),
		stockUnitRate  NUMERIC(24, 10),
		KQty  NUMERIC(24, 10),
		stockunitfullname VARCHAR(200),
		assistantfullname VARCHAR(200),
		btypefullname VARCHAR(200),
		IfSerial VARCHAR(200),
		customassist VARCHAR(400)
    )
    
    
   DECLARE @sql VARCHAR(5000)=''
   SET @sql='
    INSERT  INTO   #result
	SELECT	b.typeid,b.FullName,b.UserCode,b.sonnum,b.leveal,b.DELETED,b.entrycode,b.ParId,
			inventoryfullname = ''''
			,ISNULL(a.lockqty,0)   AS lockqty
			,ISNULL(a.qty,0) AS Qty --数量
			,ISNULL(bu.fullname,'''') AS baseunitfullname --基本单位
			,ISNULL(a.Nqty,0) AS NQty --浮动数量
			,ISNULL(ku.rate,1) AS stockUnitRate -- 库存单位换算率
			,ISNULL(a.qty1,0) KQty --库存数量
			,ISNULL(ku.fullname,'''') AS stockunitfullname --库存单位
			,ISNULL(asu.fullname,'''') AS assistantfullname --辅助单位
			,g.FullName btypefullname,
			CASE WHEN IfSerial=1 THEN ''强制'' ELSE ''-'' END AS IfSerial
			,customassist=dbo.F_GetCustomAssist(b.typeid,ISNULL(a.qty,0))
	FROM	#t a
	RIGHT JOIN dbo.ptype b  ON b.typeId=a.PtypeId AND B.IsService=0 AND B.iscombinationproduct=0
	INNER JOIN #ptype p ON b.typeId=p.typeid		
	JOIN dbo.PType_Price pr ON b.typeid=pr.PTypeID  AND pr.UnitID=b.baseUnitId
	LEFT JOIN QP_PType_Ext e ON b.typeid= e.ptypeid
	LEFT JOIN btype g ON g.typeId=e.BTypeID
	LEFT JOIN (
		SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
			JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
			
			
	) ku ON b.typeId=ku.PtypeID AND b.StockUnitId=ku.UnitsId
	LEFT JOIN (
		SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
			JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
			'+CASE WHEN @innerPtypeId='' THEN  '' ELSE 'WHERE u.PtypeID LIKE '''+@innerPtypeId+'%''' END   +'
	) bu ON b.typeId=bu.PtypeID AND b.baseUnitId=bu.UnitsId
	LEFT JOIN (
		SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
			JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
				'+CASE WHEN @innerPtypeId='' THEN  '' ELSE 'WHERE u.PtypeID LIKE '''+@innerPtypeId+'%''' END   +'
	) asu ON b.typeid=asu.PtypeID AND b.AssistantUnitId=asu.UnitsId
	WHERE	('+CAST(@DisplayStop AS VARCHAR)+'=0 AND b.deleted=0 OR '+CAST(@DisplayStop AS VARCHAR)+'=1) --是否显示停用商品
			'+CASE WHEN @FilterPtypeFullName ='' THEN  '' ELSE  ' AND b.FullName LIKE ''%'+@FilterPtypeFullName+'%''' END  +'
			'+CASE WHEN @FilterPtypeUserCode ='' THEN  '' ELSE  ' AND b.UserCode LIKE ''%'+@FilterPtypeUserCode+'%''' END  +'
			'+CASE WHEN @FilterPtypeEntryCode='' THEN '' ELSE  ' AND EXISTS(SELECT PTypeID FROM PType_EntryCode_Ext P WHERE P.Ptypeid=B.typeId AND P.EntryCode LIKE ''%'+@FilterPtypeEntryCode+'%'')) ' END  +'
			'+CASE WHEN @FilterPtypeArea ='' THEN  '' ELSE  ' AND b.Area LIKE ''%'+@FilterPtypeArea+'%''' END  +'
			'+CASE WHEN @Type ='' THEN  '' ELSE  ' AND b.Type LIKE ''%'+@Type+'%''' END  +'
			'+CASE WHEN @Standard ='' THEN  '' ELSE  ' AND b.Standard LIKE ''%'+@Standard+'%''' END  +'
			AND ('+CAST(@DisplayZero  AS VARCHAR)+'=0 AND (ISNULL(a.qty,0)<>0) OR '+CAST(@DisplayZero  AS VARCHAR)+'=1)
			--AND b.typeId NOT IN (SELECT typeid FROM ptype WHERE IsService=1) --去掉服务类商品		
			--AND b.typeId NOT IN (SELECT typeid FROM ptype WHERE iscombinationproduct=1) --去掉组合商品		
	ORDER BY b.usercode
	'

	EXEC (@SQL )
 
    
IF @vpathVisible=0
	SELECT * FROM #result
ELSE 
	SELECT *, dbo.F_GetPath(typeid,4) AS VPath  FROM #result
	DROP TABLE #result;
	DROP TABLE #KStype;
	DROP TABLE #BTType;
	DROP TABLE #KType;
	DROP TABLE #T;
	DROP TABLE #goods,#inigoods;
	DROP TABLE #cte;
END
GO





IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryFactStocks_List]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].Web_QueryFactStocks_List
GO

 --	===========================================
 --	描述:实物库存余量树型表
 --	时间:2016-07-05
 --	作者:谢吉康
 -- EXEC Web_QueryFactStocks_List '00001','00000','','',0,0,0,null,1,0,''
 --	===========================================

CREATE PROCEDURE Web_QueryFactStocks_List
(
	@OperatorId			VARCHAR(100)='',			--操作员id
	@Parid				VARCHAR(100)='00000',		--父类商品Id,
	@StypeIds			VARCHAR(max)='',			--分支机构ids
	@KtypeIds			VARCHAR(max)='',			--仓库ids
	@DisplayActual		INT=0,						--是否显示实际库存 1显示 0不显示
	@DisplayStop		INT=0,						--是否显示停用商品   1 显示 0不显示
	@PriceType			INT=0,						--显示价格方式 0~19表示20种不同的价格方式
	@Date				DATETIME=NULL,				--时间,截止时间,用于历史状况的查询
	@DisplayZero		INT =1,						--是否显示为0的数据 1显示 0不显示
	@showstockstop		INT =0,						--是否显示停用仓库数据 1为不显示 0为显示
	@ptypeCategoryid	VARCHAR(max)=''
)
--@encode$--	
AS
BEGIN
 
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
			   @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查-------------------------------------------------------

	DECLARE @sonnum INT;
	DECLARE @innerPtypeId VARCHAR(100)='';
	IF @Parid='00000' AND @MPtypeid<>'-99999'
		SET @Parid=@MPtypeid;
	SELECT @sonnum=sonnum FROM ptype WHERE typeid=@Parid;
	IF @Parid<>'00000'
		SET @innerPtypeId=@Parid;
	
	
	--把权限函数提出来
	--仓库（带分支id）
	CREATE TABLE #KStype(TypeId VARCHAR(50),STypeId VARCHAR(50));
	--分支机构
	CREATE TABLE #BTType(TypeId VARCHAR(50));
	
	CREATE CLUSTERED INDEX #KStype_t ON #KStype(TypeId);
	CREATE CLUSTERED INDEX #BTType_t ON #BTType(TypeId);
	
	INSERT INTO #KStype SELECT TypeId,STypeId  FROM F_GetManDetailKTypeSType(@OperatorId);
	INSERT INTO #BTType SELECT TypeId  FROM F_GetAllManagerBaseTypeId(@StypeIds,11,@OperatorID);
	
	--仓库
	CREATE TABLE #Ktype(TypeId VARCHAR(50));
	CREATE CLUSTERED INDEX #Ktype_t ON #Ktype(TypeId);
	IF  @showstockstop=0
		INSERT INTO #KType SELECT TypeId FROM F_GetAllBaseTypeId(@KtypeIds,4) 
	ELSE
		INSERT INTO #KType SELECT a.TypeId FROM F_GetAllBaseTypeId(@KtypeIds,4)a INNER JOIN dbo.Stock s ON a.TypeId=s.typeId  WHERE  s.deleted=0

	--权限范围内的商品线性表
	CREATE TABLE #ptype(TypeId	varchar(100))
	INSERT INTO #ptype(TypeId) SELECT a.TypeId FROM dbo.F_LinePC(@OperatorID,@ptypeCategoryid) a 
	
	CREATE TABLE #mainType(typeid VARCHAR(100)) --树形结构控制权限范围的
	IF @ptypeCategoryid<>'' or @MPtypeid='-99999'
	INSERT INTO	 #mainType
	SELECT  DISTINCT(a.TypeId) AS typeid
	FROM  dbo.F_TreeP(@OperatorId) a
	INNER JOIN  #ptype p ON p.TypeId LIKE  a.TypeId+'%'
	ELSE
	INSERT INTO	 #mainType
	SELECT   typeid 
	FROM ptype
	
	--临时表
	CREATE TABLE #t
	(	
		PtypeId		VARCHAR(50),
		qty			NUMERIC(24, 10),
		qty1		NUMERIC(24, 10),
		nqty		NUMERIC(24, 10),	
		lockqty		NUMERIC(24, 10) )
	CREATE CLUSTERED INDEX #t_p ON #t(ptypeid);
	
	--   库存
	CREATE TABLE #goods
	(
		PtypeId VARCHAR(50),
		KtypeId VARCHAR(50)
	);
	CREATE CLUSTERED INDEX #goods_p_k ON #goods(PTypeId,KtypeId)
	--期初库存
	CREATE TABLE #inigoods
	(
		PtypeId VARCHAR(50),
		KtypeId VARCHAR(50)
	);
	CREATE CLUSTERED INDEX #inigoods_p_k ON #inigoods(PTypeId,KtypeId)
	
	CREATE TABLE #cte
	(
		PtypeId VARCHAR(50),
		qty		NUMERIC(24, 10) ,
		nqty	NUMERIC(24, 10) ,		
		lockqty NUMERIC(24, 10)  
	);
	CREATE CLUSTERED INDEX #cte_p ON #cte(PtypeId);	
	
	
	--当前实物库存
	IF @Date IS NULL
	BEGIN
		INSERT INTO #goods 
		SELECT DISTINCT PtypeId,KtypeId
		FROM dbo.FactStocks
		INNER JOIN #ptype p ON PtypeId=p.TypeId
		WHERE	PtypeId LIKE @innerPtypeId+'%'
				AND KtypeId IN (SELECT TypeId FROM #Ktype)
				AND KtypeId IN (
						SELECT u.TypeId FROM #KStype u
							JOIN #BTType v ON u.STypeId=v.TypeId
					) --操作员仓库权限
					
		INSERT INTO #cte
		SELECT a.PtypeId,SUM(b.Qty) AS qty,SUM(b.NQty) AS nqty,0
		FROM	#goods a 
		LEFT JOIN dbo.FactStocks_QTY b ON a.Ptypeid=b.PTypeID AND a.KtypeId=b.KTypeID
		WHERE @Date IS NULL
		GROUP BY a.PtypeId,a.KtypeId
					
	END
	ELSE	--历史库存
	BEGIN
		INSERT INTO #inigoods
		SELECT DISTINCT PtypeId,KtypeId
		FROM dbo.IniFactStocks
		INNER JOIN #ptype p ON PtypeId=p.TypeId
		WHERE KtypeId IN (
				SELECT u.TypeId FROM #KStype u
					JOIN #BTType v ON u.STypeId=v.TypeId
			) --操作员仓库权限
			AND KtypeId IN (SELECT TypeId FROM #Ktype)				
			AND PtypeId LIKE @innerPtypeId+'%'
			
		--期初数据
		INSERT INTO #cte
		SELECT a.PtypeId,SUM(b.qty) AS qty,SUM(b.nqty) AS nqty,0
		FROM	#inigoods a 
		LEFT JOIN dbo.IniFactStocks_Qty b ON a.PtypeId=b.PTypeID AND a.KtypeId=b.KTypeID
		WHERE	@Date IS NOT NULL 					
		GROUP BY a.PtypeId,a.KtypeId	
						
		--出入库数据 
		INSERT INTO #cte(PtypeId,qty,nqty,lockqty)
		SELECT	i.PtypeId,
				SUM(ISNULL(CASE 
								WHEN i.billtype = 418 THEN i.qty 
								ELSE -1*i.qty 
						   END,0)) AS qty,
		SUM(ISNULL(i.NQty,0)) AS nQty,
		0
		FROM dbo.FactDepotInOut i
		INNER JOIN FactIndex fi ON i.billNumberID = fi.BillNumberId 
		INNER JOIN #ptype p ON PtypeId=p.TypeId
		WHERE	@Date IS NOT NULL 
				AND fi.BillDate<=@Date --时间条件
				AND fi.ifcheck = 't'
				AND fi.RedWord = 0
				AND i.KtypeId IN (
						SELECT u.TypeId FROM #KStype u
							JOIN #BTType v ON u.STypeId=v.TypeId
					) --操作员仓库权限
					AND i.KtypeId IN (SELECT TypeId FROM #Ktype)
				AND i.STypeID IN (SELECT TypeId FROM #BTType) 
				AND i.PtypeId LIKE @innerPtypeId+'%'			
		GROUP BY i.ptypeid
		UNION ALL--仓库入库
		SELECT	i.PtypeId,
				SUM(ISNULL(i.qty,0)) AS qty,
		SUM(ISNULL(i.NQty,0)) AS nQty,
		0
		FROM dbo.FactDepotAllot i
		INNER JOIN FactIndex fi ON i.billNumberID = fi.BillNumberId 
		INNER JOIN #ptype p ON PtypeId=p.TypeId
		WHERE	@Date IS NOT NULL 
				AND fi.BillDate<=@Date --时间条件
				AND fi.ifcheck = 't'
				AND fi.RedWord = 0
				AND i.KTypeId2 IN (
						SELECT u.TypeId FROM #KStype u
							JOIN #BTType v ON u.STypeId=v.TypeId
					) --操作员仓库权限
					AND i.KTypeId2 IN (SELECT TypeId FROM #Ktype)
				AND fi.Stypeid IN (SELECT TypeId FROM #BTType) 
				AND i.PtypeId LIKE @innerPtypeId+'%'			
		GROUP BY i.ptypeid
		UNION ALL --仓库出库
		SELECT	i.PtypeId,
				SUM(ISNULL(-i.qty,0)) AS qty,
		SUM(ISNULL(i.NQty,0)) AS nQty,
		0
		FROM dbo.FactDepotAllot i
		INNER JOIN FactIndex fi ON i.billNumberID = fi.BillNumberId 
		INNER JOIN #ptype p ON PtypeId=p.TypeId
		WHERE	@Date IS NOT NULL 
				AND fi.BillDate<=@Date --时间条件
				AND fi.ifcheck = 't'
				AND fi.RedWord = 0
				AND i.KTypeId IN (
						SELECT u.TypeId FROM #KStype u
							JOIN #BTType v ON u.STypeId=v.TypeId
					) --操作员仓库权限
					AND i.KtypeId IN (SELECT TypeId FROM #Ktype)
				AND fi.Stypeid IN (SELECT TypeId FROM #BTType) 
				AND i.PtypeId LIKE @innerPtypeId+'%'			
		GROUP BY i.ptypeid
	END		
			
	INSERT INTO #T 
	SELECT	w.PtypeId,
			SUM(qty) AS qty,
			SUM(ISNULL(qty,0.0)/ISNULL(U.rate,1.0)) AS qty1,
			SUM(nqty) AS nqty,	
			SUM(ISNULL(lockqty,0)) AS lockqty
	FROM	#cte w  
	INNER JOIN dbo.ptype p ON p.typeId =w.PtypeId AND (@DisplayStop=0 AND p.deleted=0 OR @DisplayStop=1)
	INNER JOIN dbo.PType_Units_Ext u ON U.PtypeID=P.typeId AND U.UnitsId=P.StockUnitId
	INNER JOIN dbo.PType_Units v ON v.UnitsId=u.UnitsId
	GROUP BY w.PtypeId
	
		
	-- 不显示借欠受托,委托情况
	SELECT	b.typeid,b.FullName,b.UserCode,b.sonnum,b.leveal,b.deleted,b.ParId
			,SUM(ISNULL(a.lockqty,0))   AS lockqty
			,ISNULL(SUM(a.qty),0) AS Qty --数量
			,ISNULL(MAX(bu.fullname),'') AS bufullname --基本单位
			,ISNULL(SUM(a.Nqty),0) AS NQty --浮动数量
			,ISNULL(MAX(ku.rate),1) AS Rate -- 库存单位换算率
			--为父类的情况下kqty=qty
			,ISNULL(SUM(a.qty1),0) AS  KQty --库存数量
			,ISNULL(MAX(ku.fullname),'') AS kufullname --库存单位
			,ISNULL(MAX(asu.fullname),'') AS asufullname --辅助单位					
			,customassist=dbo.F_GetCustomAssist(b.typeid,ISNULL(SUM(a.qty),0)),
			e.btypeid,
			b1.fullname as btypefullname
	FROM	#t a 
			RIGHT JOIN dbo.ptype b ON a.PtypeId LIKE b.typeId+'%' 			
			INNER JOIN #mainType p ON  p.typeid = b.typeId
			LEFT JOIN QP_PType_Ext e ON b.typeid= e.ptypeid	
			LEFT JOIN dbo.btype b1 ON e.BTypeID= b1.typeid  		
			LEFT JOIN (
				SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
					JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
					WHERE u.PtypeID LIKE @innerPtypeId+'%'
			) ku ON b.typeId=ku.PtypeID AND b.StockUnitId=ku.UnitsId
			LEFT JOIN (
				SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
					JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
					WHERE u.PtypeID LIKE @innerPtypeId+'%'
			) bu ON b.typeId=bu.PtypeID AND b.baseUnitId=bu.UnitsId
			LEFT JOIN (
				SELECT u.PtypeID,v.FullName,u.UnitsId,u.Rate FROM dbo.PType_Units_Ext u
					JOIN dbo.PType_Units v ON u.UnitsId=v.UnitsId
					WHERE u.PtypeID LIKE @innerPtypeId+'%'
			) asu ON b.typeid=asu.PtypeID AND b.AssistantUnitId=asu.UnitsId
	WHERE (@DisplayStop=0 AND b.deleted=0 OR @DisplayStop=1) --是否显示停用商品
	AND (@sonnum=0 AND b.typeId=@ParId OR @sonnum<>0 AND b.ParId=@Parid)
	AND b.IsService<>1
	AND b.iscombinationproduct = 0		
	GROUP BY b.typeid,b.FullName,b.UserCode,b.sonnum,b.leveal,b.deleted,b.ParId,b.SortID,e.btypeid,b1.fullname
	--显示、隐藏为零的项目
	HAVING @DisplayZero=1 OR @DisplayZero=0 AND ISNULL(SUM(a.qty),0)<>0
	ORDER BY b.SortID;
	
	DROP TABLE #BTType,#KStype,#Ktype,#cte,#goods,#inigoods,#t,#mainType	
END
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStocksCargoDistribution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStocksCargoDistribution]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康	
	日期：2016-08-11
	描述：实物库存货位分布明细
*/
CREATE PROCEDURE Web_QueryFactStocksCargoDistribution
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@stypeid			VARCHAR(max),		--所选的分支机构ID
	@ktypeid            VARCHAR(max),		--所选的仓库的ID
	@ptypeid			VARCHAR(50),			--商品的ID,
	@endDataPoint		VARCHAR(10),
	@ntype 				int	      	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------权限检查---------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
------------------------------------------------------权限检查---------------------------------------------------------------

---选择分支机构
CREATE TABLE #STypeId(TypeId	VARCHAR(100))
	INSERT INTO #STypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--仓库
CREATE TABLE #KTypeId(TypeId	VARCHAR(100))
	INSERT INTO #KTypeId(TypeId) SELECT a.TypeId FROM F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorID) A
	INNER JOIN F_GetManDetailKTypeSType(@OperatorID) mk ON A.TypeId=mk.TypeId
    INNER JOIN #STypeId s ON mk.STypeId=s.TypeId
	
---选择商品
CREATE TABLE #ptype(TypeId	VARCHAR(100))
	INSERT INTO #ptype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@ptypeid,1,@OperatorID)
DECLARE @subvalue INT

IF @ntype!=3
	BEGIN
		SELECT    
			q.CargoID ,
			q.KtypeId ,
			q.PtypeId ,
			SUM(ISNULL(CASE WHEN q.billtype = 418 THEN q.qty ELSE -1*q.qty END,0)) AS qty
		FROM dbo.FactDepotInOut q
		INNER JOIN dbo.FactIndex aa ON q.BillNumberId = aa.BillNumberId
		INNER JOIN stock S ON q.KTypeID = s.typeId
		INNER JOIN #KTypeId K ON Q.KTypeID = K.TypeId
		INNER JOIN #STypeId A ON a.TypeId = s.STypeID
		INNER JOIN #ptype P ON p.TypeId = q.PTypeID
		WHERE
			q.KtypeId != '10000'
			AND aa.billdate <= @endDataPoint
			AND aa.RedWord = 0
			AND CargoID != 0
			AND aa.ifcheck = 't'
			AND aa.RedWord = 0
		GROUP BY  
			CargoID ,
			Q.KTypeID ,
			Q.PTypeID

		UNION ALL--入库

		SELECT    
			q.InCargoID CargoID,
			q.KtypeId ,
			q.PtypeId ,
			SUM(q.qty) AS qty
		FROM dbo.FactDepotAllot q
		INNER JOIN dbo.FactIndex aa ON q.BillNumberId = aa.BillNumberId
		INNER JOIN stock S ON q.KTypeID = s.typeId
		INNER JOIN #KTypeId K ON Q.KTypeId2 = K.TypeId
		INNER JOIN #STypeId A ON a.TypeId = s.STypeID
		INNER JOIN #ptype P ON p.TypeId = q.PTypeID
		WHERE     
			q.KtypeId != '10000'
			AND aa.billdate <= @endDataPoint
			AND aa.RedWord = 0
			AND InCargoID != 0
			AND aa.ifcheck = 't'
			AND aa.RedWord = 0
		GROUP BY  
			InCargoID ,
			Q.KTypeID ,
			Q.PTypeID

		UNION ALL--出库

		SELECT    
			q.OutCargoID CargoID,
			q.KtypeId ,
			q.PtypeId ,
			SUM(-q.qty) AS qty
		FROM dbo.FactDepotAllot q
		INNER JOIN dbo.FactIndex aa ON q.BillNumberId = aa.BillNumberId
		INNER JOIN stock S ON q.KTypeID = s.typeId
		INNER JOIN #KTypeId K ON Q.KTypeID = K.TypeId
		INNER JOIN #STypeId A ON a.TypeId = s.STypeID
		INNER JOIN #ptype P ON p.TypeId = q.PTypeID
		WHERE
			q.KtypeId != '10000'
			AND aa.billdate <= @endDataPoint
			AND aa.RedWord = 0
			AND OutCargoID != 0
			AND aa.ifcheck = 't'
			AND aa.RedWord = 0
		GROUP BY  
			OutCargoID ,
			Q.KTypeID ,
			Q.PTypeID
		UNION ALL
		SELECT	
			q.CargoID ,
			q.KtypeId ,
			q.PtypeId ,
			SUM(q.Qty) qty
		FROM dbo.IniFactStocks_Qty q
		INNER JOIN  (SELECT PtypeId,KtypeId FROM dbo.IniFactStocks GROUP BY PtypeId,KtypeId) qq ON  q.KTypeID = qq.KtypeId AND q.PTypeID = qq.PtypeId
		INNER JOIN stock S ON q.KTypeID = s.typeId
		INNER JOIN #KTypeId K ON Q.KTypeID = K.TypeId
		INNER JOIN #STypeId A ON a.TypeId = s.STypeID
		INNER JOIN #ptype P ON p.TypeId = q.PTypeID
		GROUP BY 
			CargoID,     
			Q.KTypeID ,
			Q.PTypeID   
	 END
 ELSE
 BEGIN 
     SELECT
		Q.cargoid,
		Q.ktypeid,
		Q.ptypeid,
		SUM(q.Qty)qty
	FROM  (SELECT PtypeId,KtypeId FROM dbo.FactStocks GROUP BY PtypeId,KtypeId)b
	INNER JOIN dbo.FactStocks_QTY Q ON  b.KtypeId=q.KTypeID AND b.PtypeId=q.PTypeID
	INNER JOIN stock S ON q.KTypeID=s.typeId
	INNER JOIN #KTypeId K ON Q.KTypeID=K.TypeId 
	INNER JOIN #STypeId A ON a.TypeId= s.STypeID
	INNER JOIN #ptype P ON p.TypeId =q.PTypeID
	GROUP BY Q.CargoID,Q.KTypeID,Q.PTypeID
 END
        
--删除临时表
DROP TABLE #KTypeId,#STypeId,#ptype    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStocksCargoList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStocksCargoList]
GO

/*
	作者：谢吉康	
	日期：2016-06-11
	描述：实物库存货位分布树形表
*/
CREATE PROCEDURE Web_QueryFactStocksCargoList
(
	@OperatorId			 	 VARCHAR(50),		-- 当前操作员ID
	@stypeid             	 VARCHAR(200),     --分支机构ID
    @ktypeid             	 VARCHAR(200),     --仓库ID
    @cargoid             	 VARCHAR(max),     --货位ID
    @PTypeId 		         VARCHAR(100)='00000',
    @PageRows 			 	 INT=14,
	@StockPageRows		 	 INT=10,
	@GoPageNo 			 	 INT=0,        
	@Flag 					 INT=1,
	@Index 					 INT=1,
	@Sort 					 CHAR(4)='ASC',
	@unitconvert             VARCHAR(10),    --多单位种类
	@StockPageNo 	INT,
	@colCount               int OUTPUT,
	@showstockstop INT =0 --是否显示停用仓库数据 1为不显示 0为显示
)
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql varchar(max)=''
------------------------------------------------------权限检查---------------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
------------------------------------------------------权限检查---------------------------------------------------------------
---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	VARCHAR(100))
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

CREATE TABLE #ptype1(TypeId	VARCHAR(100))
	INSERT INTO #ptype1(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorID)
	

	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
	IF  @showstockstop=0
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
    INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	
    ELSE
    INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId 
    INNER JOIN F_GetAllManagerBaseTypeId(@ktypeid,4,@OperatorId) a ON k.typeID=a.TypeId	 INNER JOIN dbo.Stock ss ON a.TypeId = ss.typeId WHERE deleted=0



--货位
CREATE TABLE #GetSelectCargoid(cargoid VARCHAR(100),typeid VARCHAR(100))

IF @cargoid = '00000' OR @cargoid = '' OR @cargoid = '%'
	INSERT INTO #GetSelectCargoid(cargoid,typeid) SELECT CargoID,KtypeID FROM CargoType a
	INNER JOIN #GetManKTypeId b ON a.KtypeID=b.TypeId
ELSE
	INSERT INTO #GetSelectCargoid(cargoid,typeid)
	SELECT 	A.CargoID ,a.KtypeID
	FROM 	CargoType A, 
			(SELECT A FROM dbo.F_Split(@cargoid,',')) B 
			,#GetManKTypeId c 
	WHERE	A.CargoID= B.A  AND c.typeid =a.ktypeid

--计算总的动态列数
SET @colCount= (select count(*) from  #GetSelectCargoid)
-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000),
        @temprice   VARCHAR(2000)
--SET @tmptab=' LEFT JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') x ON q.ptypeID=x.typeID'
IF @unitconvert=0
BEGIN
SELECT  @Qty='q.Qty/R3.rate',
		@UnitName = 'U3.fullname',
		@temprice='g.price*R3.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='q.Qty/R2.rate',
		@UnitName = 'U2.fullname',
		@temprice='g.price*R2.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='q.Qty/R4.rate',
		@UnitName = 'U4.fullname',
		@temprice='g.price*R4.rate',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','1,4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='q.Qty',
		@UnitName = 'U1.fullname',
		@temprice='g.price',
		@tmptab=DBO.F_GetPtypeUnitsAndRates('p1','5,1','')
END
----------多单位计算End---------
-------------------------------------------------------------------------------------------------------------------------------

--处理货位
DECLARE @cargoids 		varchar(MAX),
		@Where_cargoId	varchar(MAX)
		
SET @Where_cargoId = ''
IF @Where_cargoId = ''
	SET @Where_cargoId = ' AND (TypeId LIKE '+char(39)+@cargoids+'%'+char(39)
ELSE
	SET @Where_cargoId = @Where_cargoId + ' OR TypeId LIKE '+char(39)+@cargoids+'%'+char(39)

CREATE TABLE #ptype
	(
		[typeId] 		[varchar] (100) NOT NULL,
		[parid] 		[varchar] (100) NOT NULL,
		[父节点] 		VARCHAR(100) NOT NULL,
		[总计实物库存] 	 NUMERIC(24, 10) ,
		[总计浮动数量]	 NUMERIC(24, 10) ,
		unitname         VARCHAR(2000),--计量单位
	    assistantname    VARCHAR(2000),--浮动单位
	    basename		 VARCHAR(2000)--基本单位	
	)
DECLARE @SonNum INT,@GsSql VARCHAR(1000),@SQLSELECT VARCHAR(MAX)=''
SELECT @SonNum = SonNum FROM PType WHERE TypeId = @PTypeId



SET @SQLSELECT = '    
    SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
			q.TypeID,
			q.parid,
			q.SonNum,
			0,'+@UnitName+',u5.fullname,u1.fullname
    FROM    F_GetManPType('''+@OperatorID+''') q INNER JOIN PTYPE P1 ON P1.TYPEID=Q.TYPEID '+@tmptab+'     
    WHERE  	q.TypeID <> ''00000''	
            and p1.IsService=0
            AND P1.iscombinationproduct = 0
			AND q.UserCode NOT IN                    
			(
				SELECT  TOP ' + CAST((@GoPageNo-1) * @PageRows AS varchar(50)) + ' UserCode
				FROM	F_GetManPType('''+@OperatorID+''')
				WHERE   TypeID <> ''00000''				      
						AND '+CASE @SonNum WHEN 0 THEN 'TYPEID' ELSE  'ParId' END + '='+char(39)+@PTypeId+char(39)+ '					
						AND isservice = 0
						AND iscombinationproduct = 0
				ORDER BY UserCode
			) 
			AND '+CASE @SonNum WHEN 0 THEN 'q.TYPEID' ELSE  'q.ParId' END + '='+char(39)+@PTypeId+char(39)+'
		
    ORDER BY q.UserCode '
	 SELECT @SQLSELECT='INSERT INTO #ptype	
					(
						[typeid],
						[parid],
						[父节点],
						[总计浮动数量],
						unitname,
						assistantname,
						basename
					)'+@SQLSELECT
--PRINT(@SQLSELECT)
EXEC(@SQLSELECT)

CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)



DECLARE @Xjkang varchar(MAX)
SET @Xjkang = 'INSERT INTO #TempStock1 SELECT a.cargoid,a.UserCode,a.FullName FROM CargoType a  inner join #GetSelectCargoid b on a.cargoid =b.cargoid  WHERE  ktypeid IN (SELECT * FROM #GetManKTypeId)  ORDER BY UserCode '


EXEC(@Xjkang)

SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(@StockPageRows AS varchar(50)) + ' 
				TypeID,				
				UserCode,			
				FullName
	    FROM    #TempStock1 
	    WHERE  	UserCode NOT IN                    
	            (
	                SELECT  TOP ' + CAST((@StockPageNo-1) * @StockPageRows AS varchar(50)) + ' UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) 
	    ORDER BY UserCode '

EXEC(@xjkang)

CREATE TABLE #GsStock
(
	PTypeId	VARCHAR(100),
	Qty	 NUMERIC(24, 10) ,
	KTypeID	VARCHAR(100),
	NQty  NUMERIC(24, 10) ,
	cargoid int	
)

SET @GsSql='
	INSERT INTO #GsStock
	SELECT	P.TypeId,
			ISNULL(SUM('+@Qty+'),0) AS Qty,
			q.KTypeID,
			ISNULL(SUM(Q.NQty),0) AS NQty,
			q.cargoid
	FROM	#ptype1 p INNER JOIN PTYPE P1 ON P1.TYPEID=P.TYPEID
	
	--INNER JOIN (
	--				SELECT	F.ptypeid,
	--						F.ktypeid 
	--				FROM	FactStocks F 					
	--				GROUP BY F.ptypeid,F.ktypeid
	--			)g  ON g.PTypeId =p.TypeId
								
	INNER JOIN FactStocks_Qty q ON q.ptypeid = p.typeid   
	INNER JOIN #GetManKTypeId K ON Q.KTYPEID=K.TYPEID 
	INNER JOIN #GetSelectCargoid d on q.cargoid=d.cargoid'+ @tmptab
	
	SET @GsSql = @GsSql + '	GROUP BY P.TypeId,q.KTypeID,q.cargoid'
	
EXEC(@GsSql)


SET @Sql = '
	UPDATE #ptype
	SET	[总计实物库存]=B.Qty,
		[总计浮动数量]=B.nqty
	FROM #ptype a
	inner join 
	(select A.typeid,sum(b.qty)qty,sum(nqty)nqty from #ptype a 
	INNER JOIN (
				SELECT	A.TypeId,
						SUM(ISNULL(G.Qty,0)) AS Qty,
						sum(isnull(g.nqty,0))as nqty
				FROM 	#ptype1 A
				LEFT JOIN #GsStock G ON  G.PTypeId = A.TypeId
				GROUP BY A.TypeId
				)B ON b.TypeId LIKE a.TypeId+''%''  
	group by a.typeid
	) b on a.typeid=b.typeid '
	
--PRINT @SQL
EXEC(@Sql)

--排序
IF @Sort=''
	SELECT @SQL+=' A.[sortid] '
ELSE
	SELECT @SQL+=@Sort

DECLARE @TempTable VARCHAR(100)
SELECT @TempTable='##Temp'+REPLACE(NEWID(),'-','')

SET @SQL='	SELECT 	A.[typeId],
					A.[parid],
					A.[父节点],
					A.[总计实物库存],
					a.unitname,
					a.[总计浮动数量],
					a.assistantname,
					a.basename,
					D.*
			FROM #ptype A 
			LEFT JOIN (
					SELECT  C.TYPEID AS PTYPEID'	
				
SELECT	@SQL=@SQL + ',['+FullName+'实物库存]=dbo.F_RoundQty(SUM(CASE WHEN  b.cargoid = '''+typeid+''' THEN b.Qty ELSE 0 END)/r.rate)
                     ,['+FullName+'浮动数量]=SUM(CASE WHEN  b.cargoid = '''+typeid+''' THEN b.NQty ELSE 0 END)'	
						FROM  #TempStock order by UserCode
SET @Sql = @Sql +'	FROM #ptype c
					LEFT JOIN (
								SELECT	e.TypeId,
										g.ktypeid,
										SUM(ISNULL(GQ.Qty,0)) AS Qty,
										SUM(ISNULL(GQ.NQty,0)) AS NQty,
										g.cargoid
								FROM 	#ptype1 e
								LEFT JOIN #GsStock G ON G.PTypeId =e.TypeId
								LEFT JOIN FactStocks_Qty GQ ON GQ.PTYPEID=E.TYPEID AND GQ.cargoid=G.cargoid AND GQ.ktypeid = G.ktypeid
								GROUP BY e.TypeId,g.ktypeid,g.cargoid
								) b on b.typeid LIKE c.TypeId+''%''
					LEFT JOIN ptype p1 ON p1.typeid = c.typeid '
							
IF @unitconvert=0
BEGIN	
	SET @sql = @sql + ' 	
	LEFT JOIN PType_Units_Ext r ON r.PTypeId = p1.TypeId AND p1.saleUnitId = r.UnitsId
	 '
END
ELSE IF @unitconvert=1
BEGIN			
	SET @sql = @sql + ' 	
	LEFT JOIN PType_Units_Ext r ON r.PTypeId = p1.TypeId AND p1.buyUnitId = r.UnitsId
	 '
END
else IF @unitconvert=2
BEGIN	
	SET @sql = @sql + ' 	
	LEFT JOIN PType_Units_Ext r ON r.PTypeId = p1.TypeId AND p1.StockUnitId = r.UnitsId
	 '
END
else --IF @unitconvert=3
BEGIN	
	SET @sql = @sql + ' 	
	LEFT JOIN PType_Units_Ext r ON r.PTypeId = p1.TypeId AND p1.baseUnitId = r.UnitsId
	 '
END		

set @sql = @sql +'	
						GROUP BY c.typeid,r.rate
						)D on d.pTypeId LIKE a.TypeId+''%'''


SELECT @SQL=@SQL+'order by '+CONVERT(varchar(4),@INDEX)+@Sort
		
PRINT(@SQL)
EXEC(@sql)

						
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStocksDiscLinePrintAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStocksDiscLinePrintAll]
GO

/*
	作者:谢吉康
	日期:2016-06-18
	描述:实物库存分布表的仓库权限是否有效
*/
CREATE           PROCEDURE Web_QueryFactStocksDiscLinePrintAll
(
	@OperatorID 	varchar(100),   --操作员id
	@PTypeIdMx		varchar(100),	
	@UserCode 		varchar(200),
	@FullName 		varchar(200),
	@Ptypeid 		varchar(100)='',
	@PageRows 		int=14,
	@PageNo 		int=0,
	@fzsl			varchar(1)='0',	--是否显示辅助数量
	@cbjj			varchar(1)='1',	--是否显示成本均价
	@cbje			varchar(1)='1',	--是否显示成本金额
	@GoFlag 		int=0,
	@Flag 			int=1,
	@INDEX 			int=1,
	@sort           VARCHAR(20),
	@StockPageNo 	int,
	@showzeroqty	int=0,	--滤调零单据
	@srcKTypeId		varchar(MAX),
	@szEntryCode	varchar(200)='',
	@stypeid		VARCHAR(MAX),
	@unitconvert    VARCHAR(10),     --多单位种类
	@showstockstop INT =0 --是否显示停用仓库数据 1为不显示 0为显示
 )
--@encode$--
AS
SET NOCOUNT ON
DECLARE @Sql varchar(MAX)
DECLARE @ReSql varchar(MAX)
DECLARE @TableName varchar(16)
DECLARE @Condition varchar(MAX)			--谢吉康    2003-9-25  加大了变量的长度
DECLARE @i int,@j int
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @re_check INT
EXEC @re_check=GP_CheckLimit @OperatorID,453
DECLARE @RS_CHECK INT
EXEC @RS_CHECK=dbo.GP_CheckLimit @OperatorID,2642

---选择分支机构
CREATE TABLE #GetSelectSTypeId(TypeId	varchar(100))
IF @RS_CHECK=0
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
ELSE 
	INSERT INTO #GetSelectSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,'00001')

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
IF @re_check = 0
 BEGIN
 	IF  @showstockstop=0
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId
	ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT k.TypeId FROM F_GetManDetailKTypeSType(@OperatorID) k INNER JOIN  #GetSelectSTypeId s ON k.STypeId=s.TypeId
	INNER JOIN dbo.Stock ss ON   s.TypeId = ss.typeId WHERE deleted=0
	 
END	
ELSE
BEGIN
 	IF  @showstockstop=0
	INSERT INTO #GetManKTypeId(TypeId) SELECT s.typeid FROM Stock s,F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) st WHERE S.STypeID = St.typeId AND s.sonnum = 0	
ELSE
	INSERT INTO #GetManKTypeId(TypeId) SELECT s.typeid FROM Stock s,F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) st WHERE S.STypeID = St.typeId AND s.sonnum = 0	 AND s.deleted=0
END			


CREATE TABLE #PtypeDetail(Typeid varchar(50))
INSERT INTO #PtypeDetail(Typeid) SELECT Typeid FROM F_GetManDetailPType(@OperatorID)

CREATE TABLE #Ptypeall
(	
	TypeID VARCHAR(50),
	UserCode VARCHAR(200),
	sonnum int,
	FullName VARCHAR(200),
	EntryCode VARCHAR(200),
	Standard  varchar(200),
	Type varchar(200),
	Area varchar(200),
	Unit1 varchar(8),
	Unit2 varchar(8),
	UnitRate1  NUMERIC(24, 10) ,
	IsService INT,
	multentrycode	VARCHAR(MAX)
)

INSERT INTO #Ptypeall 
SELECT	typeId,
		UserCode,
		sonnum,
		FullName,
		EntryCode,
		Standard,
		TYPE,
		Area,
		Unit1,
		Unit2,
		UnitRate1,
		IsService,
		multentrycode
FROM	F_GetManPType(@OperatorID)


-------------------------------------------------------------------------------------------------------------------
--------多单位计算Start--------
DECLARE @Qty    NVARCHAR(2000),
		@UnitName NVARCHAR(2000),
        @tmptab  NVARCHAR(2000)
--SET @tmptab=' INNer JOIN  F_GetManPTypeDetailALL('''+@OperatorID+''') x ON gq.ptypeID=x.typeID'
IF @unitconvert=0
BEGIN
SELECT  @Qty='gq.Qty/r3.rate',
		@UnitName = 'u5.fullname',
		@tmptab=dbo.F_GetPtypeUnitsAndRates('p1','3,5','3')
END
IF @unitconvert=1
BEGIN
SELECT  @Qty='gq.Qty/r2.rate',
		@UnitName = 'u5.fullname',
		@tmptab=dbo.F_GetPtypeUnitsAndRates('p1','2,5','2')
END
IF @unitconvert=2
BEGIN
SELECT  @Qty='gq.Qty/r4.rate',
		@UnitName = 'u5.fullname',
		@tmptab=dbo.F_GetPtypeUnitsAndRates('p1','4,5','4')
END
IF @unitconvert=3
BEGIN
SELECT  @Qty='gq.Qty',
		@UnitName = 'u5.fullname',
		@tmptab=dbo.F_GetPtypeUnitsAndRates('p1','5','')
END
----------多单位计算End---------
-------------------------------------------------------------------------------------------------------------------------------
	
------------------------------------------计算出应查询的仓库-----------------------------------------------
CREATE TABLE #TempStock1
(
	TypeID 		varchar(100),
	UserCode	varchar(256),
	FullName 	varchar(266)
)

CREATE TABLE #TempStock
(
	TypeID 		varchar(100),	
	UserCode	varchar(200),
	FullName 	varchar(266)
)

DECLARE @SortStockCount int
DECLARE @SortStockAddRec int
DECLARE @TempKTypeID varchar(100)
DECLARE @TempKName varchar(66)
SELECT @SortStockCount=1
SELECT @SortStockAddRec=0

--处理仓库
DECLARE @KTypeIds 		varchar(MAX),
		@Where_KTypeId	varchar(MAX),
		@x 				int


SET @Where_KTypeId = ''
SET @x = charindex(',',@srcKTypeId)

WHILE @x>=1
	BEGIN
		SET @KTypeIds = LEFT(@srcKTypeId,@x-1)

		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (s.TypeId LIKE '''+@KTypeIds+'%'''
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR s.TypeId LIKE '''+@KTypeIds+'%'''

		SET @srcKTypeId=SUBSTRING(@srcKTypeId,@x+1,LEN(@srcKTypeId)-@x)
		SET @x=charindex(',',@srcKTypeId)
	END

IF @srcKTypeId<>''
	BEGIN
		IF @Where_KTypeId = ''
			SET @Where_KTypeId = ' AND (s.TypeId LIKE '''+@srcKTypeId+'%'')'
		ELSE
			SET @Where_KTypeId = @Where_KTypeId + ' OR s.TypeId LIKE '''+@srcKTypeId+'%'')'
	END

DECLARE @Xjkang varchar(MAX)
SET @Xjkang = '	INSERT INTO #TempStock1 
				SELECT S.TypeId,S.UserCode,S.FullName 
				FROM Stock S 
				INNER JOIN #GetManKTypeId K ON K.TYPEID=S.TYPEID 
				WHERE S.SonNum = 0 '+@Where_KTypeId+' ORDER BY S.UserCode '
--PRINT(@xjkang)
EXEC(@Xjkang)
SET @Xjkang = '
		INSERT INTO #TempStock
	    SELECT  TOP ' + CAST(@PageRows AS varchar(50)) + ' 
				s1.TypeID,		
				s1.UserCode,					
				s1.FullName
	    FROM    #TempStock1 s1
	    LEFT JOIN 	                    
	            (
	                SELECT  TOP ' + CAST((@StockPageNo-1) * @PageRows AS varchar(50)) + ' UserCode
	                FROM	#TempStock1
	                ORDER BY
							UserCode
	            ) s2 on s1.Usercode=s2.Usercode
	    WHERE  s2.UserCode IS NULL    
	    ORDER BY s1.UserCode '
EXEC(@xjkang)
------------------------------------------上段程序结束-----------------------------------------------



IF @UserCode IS NULL OR @UserCode=''
	SELECT @UserCode='%'
ELSE
 	SELECT @UserCode='%'+@UserCode+'%'

IF @FullName IS NULL OR @FullName=''
 	SELECT @FullName='%'
ELSE
 	SELECT @FullName='%'+@FullName+'%'

IF @PTypeIdMx = '00000'
	SET @PTypeIdMx = ''

SELECT 	@Condition=' typeid F_GetManPTypeAll('+char(39)+@OperatorID+char(39)+')
					AND TypeId LIKE '''+@PTypeIdMx+'%''
					AND [UserCode] LIKE '+char(39)+'%'+@UserCode+'%'+char(39)+' 
					AND [FullName] LIKE '+char(39)+'%'+@FullName+'%'+char(39)+'
					AND MultEntryCode LIKE '+char(39)+'%'+@szEntryCode+'%'+char(39)+' 
					AND Sonnum=0 '


CREATE TABLE #PTYPE
(
	[typeId] 		[varchar] (100) NOT NULL,
	[父节点] 			varchar(100) NOT NULL,
	[商品编号] 		[varchar] (200) NULL ,
	[商品名称] 		[varchar] (200) NULL , 
	[单位关系] 		[varchar] (100) NULL , 
	商品条码			varchar(MAX) NULL,
	商品规格			varchar(256) NULL,
	商品型号			varchar(256) NULL,
	商品产地			varchar(256) NULL,
	单位				varchar(100) NULL,
	大单位				varchar(100) NULL,
	关系				varchar(100) NULL,
	[总计实物库存] 	 NUMERIC(24, 10) ,
	nqty   NUMERIC(24, 10),	
	[总计自定义辅助数量] VARCHAR(1000)
)


DECLARE @SQLSELECT VARCHAR(MAX)=''

IF @showzeroqty=0
	BEGIN
		SET @SQLSELECT = '    
	                SELECT    
							P1.TypeID,
							0,
							P1.UserCode,
							P1.FullName,
							CASE WHEN ISNULL(P1.Unit1,'''')<>'''' AND ISNULL(P1.Unit2,'''')<>'''' AND ISNULL(P1.UnitRate1,''0'')<>0
								THEN ''1''+ISNULL(P1.Unit2,'''')+''=''+CAST(Replace(CAST(ISNULL(P1.UnitRate1,''0'') AS varchar),''.0000'','''') AS varchar(100))+ISNULL(P1.Unit1,'''')
								ELSE '''' END
							AS  UnitRate,
							ISNULL(P1.EntryCode,'''') AS EntryCode,
							ISNULL(P1.Standard,'''') AS Standard,
							ISNULL(P1.Type,'''') AS Type,
							ISNULL(P1.Area,'''') AS Area,
							ISNULL(P1.Unit1,'''') AS Unit1,
							ISNULL(P1.Unit2,'''') AS Unit2,
							ISNULL(P1.UnitRate1,''0'') AS UnitRate1
	                FROM    #Ptypeall P1
	                WHERE  	P1.SonNum = 0
	                        and p1.IsService=0
						
	                        AND P1.TypeID <> ''00000''                     
							AND P1.TypeId LIKE '''+@PTypeIdMx+'%''
							AND P1.[UserCode] LIKE ''%'+@UserCode+'%''
							AND P1.[FullName] LIKE ''%'+@FullName+'%''
							AND p1.MultEntryCode LIKE ''%'+@szEntryCode+'%''
	                ORDER BY P1.[UserCode] '

	END
ELSE
	BEGIN
		SET @SQLSELECT = '    
	                SELECT    
							P1.TypeID,
							0,
							P1.UserCode,
							P1.FullName,
							CASE WHEN ISNULL(P1.Unit1,'''')<>'''' AND ISNULL(P1.Unit2,'''')<>'''' AND ISNULL(P1.UnitRate1,''0'')<>0
								THEN ''1''+ISNULL(P1.Unit2,'''')+''=''+CAST(Replace(CAST(ISNULL(P1.UnitRate1,''0'') AS varchar),''.0000'','''') AS varchar(100))+ISNULL(P1.Unit1,'''')
								ELSE '''' END
							AS  UnitRate,
							ISNULL(P1.EntryCode,'''') AS EntryCode,
							ISNULL(P1.Standard,'''') AS Standard,
							ISNULL(P1.Type,'''') AS Type,
							ISNULL(P1.Area,'''') AS Area,
							ISNULL(P1.Unit1,'''') AS Unit1,
							ISNULL(P1.Unit2,'''') AS Unit2,
							ISNULL(P1.UnitRate1,''0'') AS UnitRate1
	                FROM    #Ptypeall P1
	                INNER JOIN
							(
								SELECT 	G.PTypeId
								FROM 	FactStocks G 
								INNER JOIN	#TempStock T ON G.KTypeId = T.TypeId
								INNER JOIN #PtypeDetail PD ON PD.typeid=g.ptypeid
								WHERE	G.PTypeId LIKE '''+@PTypeIdMx+'%''	
										AND G.Qty <> 0
										AND G.Qty IS NOT NULL
								GROUP BY G.PTypeId
							) P2 ON P1.typeid = p2.Ptypeid
					
							
	                WHERE  	P1.SonNum = 0
	                        AND  p1.IsService=0
	                        AND P1.TypeID <> ''00000''
	                       
							AND P1.TypeId LIKE '''+@PTypeIdMx+'%''
							AND P1.[UserCode] LIKE ''%'+@UserCode+'%''
							AND P1.[FullName] LIKE ''%'+@FullName+'%''
							AND p1.MultEntryCode LIKE ''%'+@szEntryCode+'%''							
	                ORDER BY P1.[UserCode] '
	END            

BEGIN

	SELECT @SQLSELECT='INSERT INTO #ptype
			(
				[typeId],
					[父节点],
				[商品编号],
				[商品名称],
				单位关系,
				商品条码,
				商品规格,
				商品型号,
				商品产地,
				单位,
				大单位,
				关系
			)'+@SQLSELECT
--PRINT(@SQLSELECT)
EXEC(@SQLSELECT)
END


SELECT 	gq.PTypeId AS ptypeid,	gq.ktypeid,																
		ISNULL(SUM(gq.Qty),0) AS Qty, 		
		ISNULL(SUM(gq.nqty),0) AS NQty		
into	#test 		
FROM 	(select ptypeid,ktypeid FROM FactStocks group by ptypeid,ktypeid) v
INNER JOIN #TempStock T ON V.KTypeId = T.TypeId
INNER JOIN #PtypeDetail PD ON PD.typeid=V.PTypeId
INNER JOIN #GetManKTypeId K ON K.typeid=V.KTypeId
INNER JOIN FactStocks_qty gq ON gq.ktypeid = v.ktypeid and gq.ptypeid = v.ptypeid
GROUP BY gq.PtypeId,gq.KTypeID

--得到全部仓库的合计
SELECT @Sql='UPDATE #ptype 
			 SET	[总计实物库存]=ISNULL('+@Qty+',0),
					nqty=ISNULL(gq.NQty,0),
					[总计自定义辅助数量]=dbo.F_GetCustomAssist(a.TypeId,gq.qty)
  			 FROM #ptype a inner join  ptype p1 on p1.typeid=a.typeid
  			 INNER JOIN (
				SELECT	A.TypeId AS ptypeid,
						SUM(ISNULL(G.Qty,0)) AS Qty,
						SUM(ISNULL(G.nqty,0)) AS nqty
				FROM 	#ptype A 
				LEFT JOIN #test G ON  G.PTypeId = A.TypeId
				GROUP BY A.TypeId
				)gq ON A.TypeId = gq.pTypeId '+@tmptab
--PRINT @sql

EXEC(@sql)
----复制一个表结构 
select * into #ptype1 from #ptype where 1=2
---把原先的先排序改为后排序
SET @Sql=' 
  INSERT INTO #ptype1 
  SELECT    [typeId] ,
			[父节点] ,
			[商品编号] ,
			[商品名称] , 
			单位关系,
			商品条码,
			商品规格,
			商品型号,
			商品产地,
			单位,
			大单位,
			关系,
			[总计实物库存],
			nqty,			
			[总计自定义辅助数量]
  FROM      ( SELECT    ROW_NUMBER() OVER ( ORDER BY '
      if  @Sort=''
			  set @SQL+=' A.[商品编号] '
			 else
			   set @SQL+=@Sort
            set @SQL+='    ) AS rownumber ,
                        *
              FROM      #ptype a
            ) a
  WHERE     rownumber BETWEEN '+ CAST((@PageNo-1) * @PageRows+1 AS varchar(50))+' AND '+CAST(@PageNo * @PageRows AS varchar(50))
  print  @Sql
exec(@Sql)
IF @@error<>0
	BEGIN
		--RAISERROR('更新商品总数量生错误！',16,1)
		RETURN
	END

	

DECLARE @TempTable VARCHAR(100)
SELECT @TempTable='##Temp'+REPLACE(NEWID(),'-','')


SET @SQL='	SELECT 	A.[typeId],
				A.[商品编号],
				A.[父节点],
				A.[商品名称],
				A.[单位关系], 
				A.商品条码,
				A.商品规格,
				A.商品型号,
				A.商品产地,
				A.单位,
				A.大单位,
				A.关系,
				A.[总计实物库存],
				A.nqty,	
				A.[总计自定义辅助数量],		
				gq.*'
			+CASE @fzsl WHEN '1' THEN 'INTO '+@TempTable ELSE '' END+'
			FROM #ptype1  A 
			LEFT JOIN (
					SELECT C.TYPEID AS PTYPEID,'+@UnitName+' AS unitname'	

SELECT	@SQL=@SQL+'
		,['+FullName+'实物库存]=SUM(CASE WHEN  gq.ktypeId = '''+typeid+''' THEN ISNULL('+@Qty+',0) ELSE 0 END)
		,['+FullName+'浮动数量]=SUM(CASE WHEN  gq.ktypeId = '''+typeid+''' THEN ISNULL(gq.NQty,0) ELSE 0 END)'
		+CASE @fzsl WHEN '1' THEN ',['+FullName+'辅助数量]=CAST('''' AS VARCHAR(100))' ELSE '' END		
		+',['+FullName+'自定义辅助数量]=  dbo.F_GetCustomAssist(C.TYPEID, SUM(CASE WHEN  gq.ktypeId = '''+typeid+''' THEN gq.qty ELSE 0 END)) '
FROM  #TempStock order by UserCode
SELECT @Sql=@Sql+' FROM #ptype1 C inner join ptype p1 on p1.typeid=c.typeid
	LEFT JOIN (
								SELECT	e.TypeId AS ptypeid,
										g.ktypeid,
										SUM(ISNULL(G.Qty,0)) AS Qty,
										SUM(ISNULL(G.NQty,0)) AS NQty
								FROM 	#ptype1 e
								left JOIN #test G ON G.ptypeid =e.TypeId
								GROUP BY e.TypeId,g.ktypeid
								) gq on c.typeid=gq.ptypeid

'+@tmptab+'
GROUP BY '+@UnitName+',C.[typeId])  gq ON gq.PTYPEID=A.TYPEID 

ORDER BY '

     if  @Sort=''
			  SELECT @SQL+=' A.[商品编号] '
			 else
			   SELECT @SQL+=@Sort
IF @fzsl='1'
BEGIN
	--PRINT(@SQL)
	EXEC(@sql)
	IF EXISTS(SELECT * FROM #TempStock)
	BEGIN
		SET @SQL=''
		SELECT @SQL=@SQL+'['+fullname+'辅助数量]=CASE
							WHEN 单位关系='''' THEN ''''
							WHEN ['+FullName+'实物库存]=0 THEN ''''
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(['+FullName+'实物库存])/关系 as  NUMERIC(24, 10) )<1	THEN CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) ) AS varchar(100))+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(ISNULL(['+FullName+'实物库存],0))/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) as  NUMERIC(24, 10) )>=1 AND CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))<>''0'' THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ['+FullName+'实物库存]<0 AND CAST(ABS(ISNULL(['+FullName+'实物库存],0))/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) as  NUMERIC(24, 10) )>=1 AND CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))=''0''  THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
							WHEN ISNULL(['+FullName+'实物库存],0)>0 AND ['+FullName+'实物库存]<关系 THEN CAST(['+FullName+'实物库存] AS varchar(100))+单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 as  NUMERIC(24, 10) ) AS varchar)+大单位	
							WHEN ['+FullName+'实物库存]/关系>=1 AND ['+FullName+'实物库存]/关系 = CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) THEN CAST(CAST(['+FullName+'实物库存]/关系 as  numeric(18,0)) as varchar)+大单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 as  numeric(18,0)) as varchar)+大单位
							WHEN ['+FullName+'实物库存]/关系>=1 THEN CAST(CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as varchar)+大单位+CAST(CAST(['+FullName+'实物库存] as  NUMERIC(24, 10) )-CAST(CAST(关系 as  NUMERIC(24, 10) )*CAST(ROUND(['+FullName+'实物库存]/关系,0,1) AS NUMERIC(18,0)) as  NUMERIC(24, 10) ) as varchar(100))+单位+''/''+CAST(CAST(['+FullName+'实物库存]/关系 AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位				
							ELSE ''0''+单位+''/''+CAST(CAST(CAST(['+FullName+'实物库存] AS  NUMERIC(24, 10) )/CAST(ISNULL(关系,0) AS  NUMERIC(24, 10) ) AS  NUMERIC(24, 10) ) AS varchar(1000))+大单位
						 END,' from #TempStock s ORDER BY USERCODE
		IF RIGHT(@SQL,1)=','
			SET @Sql=LEFT(@Sql,LEN(@SQL)-1)
		SET @SQL='UPDATE '+@TempTable
				+' SET '+@Sql
		--PRINT(@SQL)
		EXEC(@sql)	
	END
	DECLARE @TABLE VARCHAR(100)
	SET @TABLE='SELECT * FROM '+@TempTable
	IF @Flag=0
		SELECT @TABLE=@TABLE+' ORDER BY '+CONVERT(varchar(4),@INDEX)+@Sort
	EXEC(@TABLE)

	-- 删除临时表
	SELECT @ReSql='DROP TABLE '+@TempTable
	EXEC(@ReSql)
END
ELSE
BEGIN
	IF @Flag=0
		SELECT @SQL=@SQL+' ,'+CONVERT(varchar(4),@INDEX)+@Sort
	--PRINT(@SQL)
	EXEC(@sql)	
END	

DROP TABLE #GetSelectSTypeId,#GetManKTypeId,#PtypeDetail,#Ptypeall,#TempStock,#ptype,#TempStock1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryFactStocksPtypeFreeItem]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryFactStocksPtypeFreeItem
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	实物库存余量表 自由项查询
-- 时间：	2017-08-10
-- 作者：	GLJ
-- ========================================================================
CREATE PROCEDURE [dbo].[Web_QueryFactStocksPtypeFreeItem]
(
	@OperatorId		VARCHAR(50)	,	-- 当前操作员ID
	@STypeId		VARCHAR(50),    --分支机构ID
	@KTypeId		VARCHAR(50),    --仓库
	@PTypeId		VARCHAR(50),    --商品ID
	@EndDate		VARCHAR(50)=''	--查询截止日志	
)
--@encode$--
AS
SET NOCOUNT ON 

--------------------------------------------------------------权限检查--BEGIN-----------------------------------------------------
IF @OperatorId IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorId,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查--END-----------------------------------------------------


--=========================================业务处理【BEGIN】======================================
--选择分支机构
CREATE TABLE #SType(TypeId VARCHAR(50))
INSERT INTO #SType(TypeId) SELECT F.TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorId) F
	
--选择仓库
CREATE TABLE #KType(STypeId VARCHAR(50),TypeId VARCHAR(50))
INSERT INTO #KType(STypeId,TypeId) SELECT S.STypeID,F.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorId) F INNER JOIN STock S ON S.typeId=F.TypeId

--选择商品
CREATE TABLE #PType(TypeId VARCHAR(50))
INSERT INTO #PType(TypeId) SELECT F.TypeId FROM F_GetAllManagerBaseTypeId(@PTypeId,1,@OperatorId) F

--商品自由项临时表
CREATE TABLE #PtypeQty(
	STypeID		VARCHAR(50),--分支机构ID
	PTypeId		VARCHAR(50),--商品ID
	KTypeID		VARCHAR(50),--仓库ID
	CargoID		INT,--货位ID
	IsCombined	INT,		--是否组合品
	ItemID		INT,		--自由项ID
	Qty			NUMERIC(22,10) NOT NULL DEFAULT(0)--自由项数量
)

--期初
INSERT INTO #PtypeQty(STypeID,PTypeId,KTypeID,CargoID,IsCombined,ItemID,Qty)
SELECT
	K.STypeId,
	I.PtypeID,
	I.KtypeID,
	I.CargoID,
	I.Iscombined,
	I.ItemID,
	SUM(I.Qty) Qty
FROM IniFactStocks_Qty I
INNER JOIN #PType P ON P.TypeId=I.PtypeID
INNER JOIN #KType K ON K.TypeId=I.KtypeID
INNER JOIN #SType S ON S.TypeId=K.STypeId
GROUP BY 
	K.STypeId,
	I.PtypeID,
	I.KtypeID,
	I.CargoID,
	I.Iscombined,
	I.ItemID
UNION ALL --出入库
SELECT
	I.STypeId,
	D.PtypeID,
	D.KtypeID,
	D.CargoID,
	D.IsCombined,
	D.ItemID,
	SUM(ISNULL(CASE WHEN D.BillType = 418 THEN D.qty ELSE -D.qty END,0)) Qty
FROM dbo.FactDepotInOut D
INNER JOIN FactIndex I ON I.BillNumberId=D.BillNumberID AND I.BillType IN(418,419) AND I.ifcheck='t' AND I.RedWord=0 
INNER JOIN #PType P ON P.TypeId=D.ptypeid
INNER JOIN #KType K ON K.TypeId=D.ktypeid
INNER JOIN #SType S ON S.TypeId=I.STypeId
WHERE 
	((@EndDate<>'' AND I.BillDate<=@EndDate) OR @EndDate='')
GROUP BY 
	I.STypeId,
	D.PtypeID,
	D.KtypeID,
	D.CargoID,
	D.IsCombined,
	D.ItemID
UNION ALL--仓库入库
SELECT
	I.STypeId,
	D.PtypeID,
	D.KTypeId2 KtypeID,
	D.InCargoID CargoID,
	D.IsCombined,
	D.ItemID,
	SUM(D.qty) Qty
FROM FactDepotAllot D
INNER JOIN FactIndex I ON I.BillNumberId=D.BillNumberID AND I.BillType=420 AND I.ifcheck='t' AND I.RedWord=0 
INNER JOIN #PType P ON P.TypeId=D.ptypeid
INNER JOIN #KType K ON K.TypeId=D.KTypeId2
INNER JOIN #SType S ON S.TypeId=I.STypeId
WHERE 
	((@EndDate<>'' AND I.BillDate<=@EndDate) OR @EndDate='')
GROUP BY 
	I.STypeId,
	D.PtypeID,
	D.KTypeId2,
	D.InCargoID,
	D.IsCombined,
	D.ItemID
UNION ALL --仓库出库
SELECT
	I.STypeId,
	D.PtypeID,
	D.KtypeID,
	D.OutCargoID CargoID,
	D.IsCombined,
	D.ItemID,
	-SUM(D.qty) Qty
FROM FactDepotAllot D
INNER JOIN FactIndex I ON I.BillNumberId=D.BillNumberID AND I.BillType=420 AND I.ifcheck='t' AND I.RedWord=0 
INNER JOIN #PType P ON P.TypeId=D.ptypeid
INNER JOIN #KType K ON K.TypeId=D.KTypeId
INNER JOIN #SType S ON S.TypeId=I.STypeId
WHERE 
	((@EndDate<>'' AND I.BillDate<=@EndDate) OR @EndDate='')
GROUP BY
	I.STypeId,
	D.PtypeID,
	D.KTypeId,
	D.OutCargoID,
	D.IsCombined,
	D.ItemID

--=========================================业务处理【END】======================================

--=========================================返回结果集并删除临时表【BEGIN】======================================
SELECT
	T.PTypeId,--商品
	P.UserCode,
	P.FullName,
	T.ItemID,--自由项
	E.fullname IFullName,
	T.STypeID,--分支机构
	S.FullName SFullName,
	T.KTypeID,--仓库
	ST.FullName KFullName,
	T.CargoID,--货位
	C.FullName CFullName,
	SUM(Qty/ISNULL(U.rate,1.0)) Qty
FROM #PtypeQty T
INNER JOIN SType S ON S.TypeId=T.STypeID
INNER JOIN ptype P ON P.typeId=T.PTypeId
INNER JOIN dbo.PType_Units_Ext u ON U.PtypeID=P.typeId AND U.UnitsId=P.baseUnitId
INNER JOIN dbo.PType_Units v ON v.UnitsId=u.UnitsId
INNER JOIN stock ST ON ST.typeId=T.KTypeID
INNER JOIN CargoType C ON C.CargoID=T.CargoID
INNER JOIN dbo.vWeb_ItemIDByIsCombined E ON e.id=T.ItemID AND E.iscombined=T.IsCombined
GROUP BY  
	T.PTypeId,--商品
	P.UserCode,
	P.FullName,
	T.ItemID,--自由项
	E.fullname,
	T.STypeID,--分支机构
	S.FullName,
	T.KTypeID,--仓库
	ST.FullName,
	T.CargoID,--货位
	C.FullName
	
--删除结果集	
DROP TABLE #SType,#KType,#PType,#PtypeQty

--=========================================返回结果集并删除临时表【END】  ======================================
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFactStocksSerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryFactStocksSerial]
GO
/*
--=============================
--作者：谢吉康
--日期：2016-07-06
--描述：实物库存序列号处理
--exec Web_QueryFactStocksSerial @OperatorID='00001',@StartDate='2016-07-01',@EndDate='2016-07-06',@pTypeID='',@dealbTypeID='00000',@kTypeID='',@pSerial='',@pUsercode='',@pFullname='',@pState='',@searchMode=0,@isModal=0,@bTypeID2='',@USER='',@Note='',@ShowAllUser=0,@radValue='0',@showIniSerial='0',@BTypeName='',@JTypeName='',@tablename='',@stypeID='00001',@comment1='',@comment2='',@comment3='',@itemid='',@cargoid='',@producedate='',@validdate=''
--=============================
 */
CREATE                              PROCEDURE [Web_QueryFactStocksSerial] 
(
	@OperatorID			VARCHAR(100),		--1.操作员的ID 
	@StartDate  		VARCHAR(20),		--2.开始时间
	@EndDate    		VARCHAR(20),		--3.结束时间
	@pTypeID    		VARCHAR(8000),		--4.商品的ID 
	@dealbTypeID    	VARCHAR(8000),	--5.客户或供货商   00000=客户和供货商统一  00001=客户   00002=供应商
	@kTypeID    		VARCHAR(8000)='',	--6.仓库的ID
	@pSerial    		VARCHAR(100)='',	--7.序列号
	@pUsercode  		VARCHAR(100),		--8.商品编号
	@pFullname  		VARCHAR(100),		--9.商品名称
	@pState     		VARCHAR(200),		--10.商品状态
	@searchMode 		INT,				--11.查询类型   1.精确匹配 0.模糊查找
	@isModal    		INT, 				--12.时间的模糊查询   1.是  0.否
	@bTypeID2   		VARCHAR(8000),		--13.查询销售商
	@USER				VARCHAR(200),		--14.终端用户
	@Note				VARCHAR(200),		--15.备注
	@ShowAllUser		INT,				--16.显示终端用户
	@radValue			INT,				--17.开始日期有效  0.入库日期有效   1.出库日期有效	
	@showIniSerial		INT,				--18.是否仅显示期初序列号	1.是   0.否
	@BTypeName			VARCHAR(8000),		--19.客户名称
	@JTypeName			VARCHAR(8000),		--20.供货商
	@tablename			VARCHAR(100),
	@stypeID			VARCHAR(max),		--分支机构
	@comment1			VARCHAR(256),
	@comment2			VARCHAR(256),
	@comment3			VARCHAR(256),
	@itemid				VARCHAR(200),		--自由项
	@cargoid			VARCHAR(200),		--货位
	@producedate		VARCHAR(20),		--生成日期 
	@validdate			VARCHAR(20),		--效期至
	@ptypecategoryid	VARCHAR(MAX)=''		--商品类别
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
           @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--商品
CREATE TABLE #GetManPTypeId
(
	TypeId		varchar(50),
	UserCode 	VARCHAR(200),
	fullname 	VARCHAR(200),
	EntryCode 	VARCHAR(200),
	Standard	VARCHAR(200),
	Type		VARCHAR(200),
	Area		VARCHAR(200)
)


IF @MPtypeid<>'-99999'
	INSERT INTO #GetManPTypeId(TypeId,UserCode,fullname,EntryCode,Standard,Type,Area) 
	SELECT	b.typeid,b.usercode,b.fullname,b.entrycode,b.standard,b.type,b.area  
	From	F_GetAllBaseTypeId(@PTypeId,1) p 
	INNER JOIN Ptype b ON b.typeid=p.typeid
	INNER JOIN dbo.F_LinePC(@OperatorID,@ptypeCategoryid) a ON a.TypeId = b.typeId
ELSE
	INSERT INTO #GetManPTypeId(TypeId,UserCode,fullname,EntryCode,Standard,Type,Area)
	SELECT	b.typeid,b.usercode,b.fullname,b.entrycode,b.standard,b.type,b.area 
	FROM	F_GetManDetailPType(@OperatorID) p 
	INNER JOIN F_GetAllBaseTypeId(@PTypeId,1) sp  ON p.TypeId = sp.TypeId  
	INNER JOIN Ptype b ON b.typeid=p.typeid
	INNER JOIN dbo.F_LinePC(@OperatorID,@ptypeCategoryid) a ON a.TypeId = b.typeId

CREATE CLUSTERED INDEX [CIX_PTYPE_Typeid] ON [dbo].#GetManPTypeId 
(
	[typeId] ASC
) ON [PRIMARY]
	
--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@kTypeID,4,@OperatorID)

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)
--删除仓库中的对于STypeId
DELETE FROM #GetManKTypeId WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		

IF @kTypeID='' --全部仓库时，加入代销库 Wang Wei Add 2010-8-26 
	INSERT INTO #GetManKTypeId(TypeId) values('10000')
	
IF @tablename <> '' --只有在@tablename 表存在的情况下，才能正确查询
    BEGIN
        DECLARE  @mycount INT
        CREATE TABLE #MYCOUNT
		(
          	MYCOUNT INT
		)
        EXEC( 'insert into #mycount select count(name)  from sysobjects where type=''u'' and [name]=''' + @tablename + '''')
        SELECT @mycount = MYCOUNT
        FROM   #MYCOUNT
        IF @mycount <= 0
            SET @tablename = ''
        DROP TABLE #MYCOUNT
    END

DECLARE @SQL varchar(3000)	-- 查询的SQL
SET @SQL=''

/*处理参数*/
SET	@SQL = '
	SELECT  a.Serial,
			a.state,
			a.InKtypeTime,	
			a.OutKtypeTime,
			a.KTypeID,
			b.UserCode,
			b.typeid  As PTypeId,
			b.fullname As pFullname,
			b.EntryCode,
			b.Standard,
			b.Type,
			b.Area,
			a.STypeId,
			identity(int,1,1) AS sid,
			a.comment1,
			e.fullname as efullname,
			a.itemid,
			cargoid,
			ProduceDate,
			ValidDate,
			GoodsNumber			
	INTO	#temp1
	FROM 	Gp_FactPtypeSerial a  
	INNER JOIN #GetManPTypeId b ON b.typeid=a.PTypeID 
	INNER JOIN #GetManKTypeId  k  ON a.KtypeID=k.TypeId
	INNER JOIN #GetManSTypeId S ON S.TypeId = a.STypeId
	left join vWeb_ItemIDByIsCombined e on (a.Iscombined=e.iscombined AND e.id=a.ItemID ) 
	 '
 	IF  @cargoid<>''
			SET @SQL+=' INNER JOIN dbo.f_split('''+@cargoid+''','','') d ON a.CargoID =d.a '	    
SET	@SQL =@SQL+' WHERE 	1=1 '
	
IF @showIniSerial = 1 --是否仅显示期初的序列号
	SET @SQL = @SQL + ' AND a.iniFlag = 1 '

/*处理日期 0.入库时间有效  1.出库时间有效*/
IF @radValue = 0
	SET @SQL = @SQL + ' AND a.InKtypeTime>='+char(39)+@StartDate+char(39)+' 
						AND a.InKtypeTime<='+char(39)+@EndDate+char(39)
ELSE
	SET @SQL = @SQL + ' AND a.OutKtypeTime>='+char(39)+@StartDate+char(39)+' 
						AND a.OutKtypeTime<='+char(39)+@EndDate+char(39)
/*查询时往来单位有效*/
--IF @dealbTypeID <> '00000'
--	SET @SQL = @SQL + ' AND ((a.BTypeId1 IN (SELECT TypeId FROM #GetManBTypeId)) OR (a.BTypeId2 IN (SELECT TypeId FROM #GetManBTypeId)))'


IF @searchMode=0   --1.精确匹配 0.模糊查找
	BEGIN
		IF(@tablename<>'') ----haiquan多项筛选
		    BEGIN
				IF @pSerial<>''
				   SET @SQL=@SQL+' AND (a.Serial LIKE '+char(39)+'%'+@pSerial+'%'+char(39)+' OR a.Serial in (SELECT Serial FROM '+@tablename+'))'
			    ELSE
				   SET @SQL=@SQL+'AND a.Serial in (SELECT Serial FROM '+@tablename+')'
		    END
		ELSE
		BEGIN
			IF @pSerial<>''
				SET @SQL=@SQL+' AND a.Serial LIKE '+char(39)+'%'+@pSerial+'%'+char(39)
			IF @pUsercode<>''
				SET @SQL=@SQL+' AND b.usercode LIKE '+char(39)+'%'+@pUsercode+'%'+char(39)
			IF @pFullname<>''
				SET @SQL=@SQL+' AND b.fullname LIKE '+char(39)+'%'+@pFullname+'%'+char(39)
			
			IF @Note<>''
				SET @SQL=@SQL+' AND a.comment1 LIKE '+char(39)+'%'+@Note+'%'+char(39)	
		END
	END 
ELSE  			--1.精确匹配 0.模糊查找
	BEGIN
		IF (@tablename<>'')
		     BEGIN
				IF @pSerial<>''
			   		SET @SQL=@SQL+'AND (a.Serial = '+char(39)+@pSerial+char(39)+' OR a.Serial in (SELECT Serial FROM '+@tablename+'))' 
		     	ELSE
			  	 	SET @SQL=@SQL+'AND a.Serial in (SELECT Serial FROM '+@tablename+')'
		     END
		ELSE
			SET @SQL=@SQL+'AND a.Serial = '+char(39)+@pSerial+char(39) 
		
		SET @SQL=@SQL+'	AND b.UserCode = '+char(39)+@pUsercode+char(39)+'
						AND b.FullName = '+char(39)+@pFullname+char(39)+''	
	END

IF @pState<>''
	SET @SQL=@SQL+' AND a.state in ('+@pState+')'
IF @itemid!=''
    SET @SQL=@SQL+' AND e.itemid = '+char(39)+@itemid+char(39)+''
IF @producedate!=''
    SET @SQL=@SQL+' and a.ProduceDate='+char(39)+@ProduceDate+char(39)+''
IF @validdate!=''
    SET @SQL=@SQL+' AND a.ValidDate='+char(39)+@ValidDate+char(39)+''        
  
SET @SQL = @SQL + '   ORDER BY a.Serial'

SET @SQL = @SQL + '
	SELECT  a.Serial,
			a.state,
			a.STypeId,
			a.InKtypeTime,	
			a.OutKtypeTime,
			a.UserCode,
			a.PTypeId,
			a.pFullname,
			a.EntryCode,
			a.Standard,
			a.Type,
			a.Area,
			a.comment1,
			a.KTypeId,
			efullname,
			itemid,
			cargoid,
			ProduceDate,
			ValidDate,
			GoodsNumber,			
			kFullName = (SELECT FullName FROM Stock WHERE TypeID = a.KTypeID),
			case when a.OutKtypeTime is null  or  a.OutKtypeTime='''' then DATEDIFF(day, a.InKtypeTime, getdate()) +1
				else DATEDIFF(day, a.InKtypeTime, a.OutKtypeTime) +1
			END AS Serialage
	FROM	#temp1 a
	ORDER BY a.sid'


--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManKTypeId,#GetManPTypeId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE id = object_id(N'[dbo].[Web_QueryFinancialBussinesReconciliation]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryFinancialBussinesReconciliation
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===============================================
--create by :glj
--date:2013-07-11
--function description:财务 业务 对账(后期再优化)

--MODIFY by:dongzhan
--date:2013-09-11
 
----================================================
CREATE PROC Web_QueryFinancialBussinesReconciliation
(
	@StypeID			VARCHAR(50)='',		--分支机构ID
	@AtypeID			VARCHAR(MAX)='',	--科目ID
	@FYear				INT=0,				--年度
	@IsSelected			INT=0,				--期间 / 时间  选择  0：期间 1:时间
	@FBegin				INT=0,				--开始期间
	@FEnd				INT=0,				--结束期间
	@StartDate			VARCHAR(50),		--开始时间
	@EndDate			VARCHAR(50),		--结束时间 
	@IsShowNoAccount	INT,				--是否包括未过账凭证
	@DataIsAllZero		INT,				--不包括数据为0的数据
	@D_TotalIsZero		INT,				--不包括差额为0的数据
	@OperatorID			VARCHAR(50),		--当前操作员
	@noequal			INT=0	OUTPUT		--是否存在不等的数据
	
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
----------------------------------------权限检查[BEGIN]-------------------------------------------------------
IF ISNULL(@OperatorID,'')='' RETURN
DECLARE 
	@Re INT,
	@MAtypeid VARCHAR(50),
	@MBtypeid VARCHAR(50),
	@MBtypeid2 VARCHAR(50), 
	@MEtypeid VARCHAR(50),
	@MKtypeid VARCHAR(50), 
	@MPtypeid VARCHAR(50), 
	@MExpense VARCHAR(50), 
	@MIncome VARCHAR(50),
	@MCapital VARCHAR(50),
	@MDtypeid VARCHAR(50),
	@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep 
		@OperatorID,
		@MAtypeid OUTPUT,
		@MBtypeid OUTPUT,
		@MBtypeid2 OUTPUT,
		@MEtypeid OUTPUT,
		@MKtypeid OUTPUT,
		@MPtypeid OUTPUT,
		@MExpense OUTPUT,
		@MIncome OUTPUT,
		@MCapital OUTPUT,
		@MDtypeid OUTPUT,
		@MStypeid OUTPUT

IF @Re<>0 RETURN
----------------------------------------------权限检查[END]-------------------------------------------------------

--=======================================创建临时表 并获取权限范围类数据【BEGIN】===========================
CREATE TABLE #Stype(TypeID	VARCHAR(50))
CREATE TABLE #Atype(TypeID	VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200),Fdc INT)--科目
CREATE TABLE #AcItems(NId INT,ATypeID VARCHAR(50),STypeId VARCHAR(50))
INSERT INTO #Stype(TypeID)--分支机构
SELECT TypeId FROM SType WHERE VerifyID=@StypeID
IF ISNULL(@AtypeID,'')<>''
	BEGIN
		INSERT INTO #Atype(TypeID,UserCode,FullName,Fdc) 
		SELECT 
			A.TypeId,
			A.UserCode,
			A.FullName,
			A.Fdc
		FROM Ac_Account A
		INNER JOIN f_split(@AtypeID,',') F ON F.a=A.TypeId AND A.StypeId=@StypeID   AND A.SonCount=0 --AND A.Deleted=0
		WHERE A.ParId<>'00000'
		
		INSERT INTO #AcItems(NId,ATypeID,STypeId)
		SELECT DISTINCT
			D.nId,
			ATypeId,
			STypeId 
		FROM Ac_Items_Detail  D
		INNER JOIN Ac_Items A ON A.nId=D.nId AND A.SonCount=0
		INNER JOIN f_split(@AtypeID,',') F ON F.a=D.ATypeId
		INNER JOIN #Stype S ON S.TypeID=D.STypeId
	END
ELSE 
	BEGIN
		
		INSERT INTO #Atype(TypeID,UserCode,FullName,Fdc) 
		SELECT 
			TypeId,
			UserCode,
			FullName,
			Fdc
		FROM Ac_Account 
		WHERE 
			StypeId=@StypeID  
			--AND Deleted=0 
			AND SonCount=0
			AND ParId<>'00000'
		
		INSERT INTO #AcItems(NId,ATypeID,STypeId)
		SELECT DISTINCT
			D.nId,
			ATypeId,
			STypeId
		FROM Ac_Items_Detail D
		INNER JOIN Ac_Items A ON A.nId=D.nId AND A.SonCount=0 AND D.ATypeId<>'' 
		INNER JOIN #Stype S ON S.TypeID=D.STypeId
		END
--=======================================创建临时表 并获取权限范围类数据【END】	 ===========================

--============================================对账数据【BEGIN】=============================================
--选择时间 得到相应时间的期间
 IF(@IsSelected=0)--选择期间 得到相应期间的时间
	BEGIN
		SELECT @StartDate=CONVERT(VARCHAR(10),FBegin,120) FROM Ac_Period WHERE FYear=@FYear AND FPeriod=@FBegin
		SELECT @EndDate=CONVERT(VARCHAR(10),FEnd,120) FROM Ac_Period WHERE FYear=@FYear AND FPeriod=@FEnd
		
	END
ELSE IF(@IsSelected=1)
	BEGIN
		SELECT @FBegin=FPeriod FROM Ac_Period WHERE FYear=@FYear AND  @StartDate BETWEEN FBegin AND FEnd 
		SELECT @FEnd=FPeriod FROM Ac_Period WHERE FYear=@FYear AND  @EndDate BETWEEN FBegin AND FEnd
	END
	
Create Table #ResultTable
(
	TypeID			VARCHAR(50),				--科目编号
	UserCode		VARCHAR(200),				--科目编号
	FullName		VARCHAR(200),				--科目名称
	begin_b_total	 NUMERIC(24, 10)  DEFAULT(0),	--期初业务余额
	begin_f_total	 NUMERIC(24, 10)  DEFAULT(0),	--期初财务余额
	
	f_b_total		 NUMERIC(24, 10)  DEFAULT(0),	--业务发生额
	f_f_total		 NUMERIC(24, 10)  DEFAULT(0),	--财务发生额
	
	end_b_total		 NUMERIC(24, 10)  DEFAULT(0),	--期末业务余额
	end_f_total		 NUMERIC(24, 10)  DEFAULT(0),	--期末财务余额
	[Type]			INT NOT NULL DEFAULT(0),	 --类型  1：固定资产卡片 0 其它
	
	begin_d_total	 NUMERIC(24, 10)  DEFAULT(0),				--期初差异
	f_d_total		 NUMERIC(24, 10)  DEFAULT(0),				--财务差异
	end_d_total		 NUMERIC(24, 10)  DEFAULT(0),				--期末发生差异
	Fdc				INT							--借贷方向
)

DECLARE @Assets int=0,  --是否是固定资产卡片模式
		@Ifcreate int=0,--是否开账
		@createtime DATETIME  --开账日期
		
SELECT @Assets=SubValue FROM sysdata WHERE SubName='assets'
IF EXISTS(SELECT TOP 1 1 FROM SType_Config C,SType_UserConfig U 
						  WHERE C.ConfigNo = U.ConfigNo AND C.ConfigName = 'stypeinicanmodify' AND ISNULL(U.STypeID,'') = @STypeId AND U.Value='0') 
   OR NOT EXISTS(SELECT TOP 1 1 FROM dbo.SType_UserConfig WHERE StypeId=@STypeId)
	SET @Ifcreate=0
ELSE 
	SET @Ifcreate=1			
--SELECT @createtime=StartDate FROM MonthProc 
DECLARE @creatyear INT
SELECT @creatyear=SubValue FROM dbo.sysdata WHERE SubName='fyear'
SELECT @createtime=FBegin FROM dbo.Ac_Period WHERE FYear=@creatyear AND FMonth=FPeriod
	
DECLARE @AssetsTB TABLE(ATYPEID VARCHAR(50))  --保存卡片被使用过的科目
--==========================================业务【BEGIN】=====================================================
IF @Assets=1 --卡片模式
	INSERT INTO @AssetsTB
	SELECT AssertATypeId FROM Ac_AssetsCards C JOIN #Stype S ON S.TypeID=C.STypeId  
    UNION 
    SELECT DepATypeId FROM Ac_AssetsCards C JOIN #Stype S ON S.TypeID=C.STypeId 
    UNION 
    SELECT DevalueATypeId FROM Ac_AssetsCards C JOIN #Stype S ON S.TypeID=C.STypeId 

--剔除卡片中出现的科目
INSERT INTO #ResultTable(TypeID,UserCode,FullName,Fdc,begin_b_total)
SELECT TypeID,UserCode,dbo.F_GetAtypeFullNamePath(TypeID,@StypeID),Fdc,0 FROM #Atype WHERE TypeID NOT IN (SELECT ATYPEID FROM @AssetsTB) 
 
--取期初
UPDATE A SET begin_b_total+=ISNULL(Total,0)
FROM #ResultTable A
INNER JOIN (
	SELECT i.ATypeID,ISNULL(SUM(ISNULL(t.Total00,0)),0) AS Total
	FROM AType_Total t 
	JOIN #AcItems i ON  i.nId=t.AtypeId AND t.STypeID=i.STypeId
	JOIN #Stype s ON s.typeid=i.STypeID
	GROUP BY i.ATypeID
) T ON T.ATypeID=A.TypeID 
 
---如果没开账，这三个特殊处理，前提还要是在atype_total没得这个3个项目出现过
IF @Ifcreate=0 AND 
   NOT EXISTS(SELECT TOP 1 1 FROM dbo.AType_Total WHERE Atypeid IN(30,31,37)  )
	BEGIN
		--库存商品总值
		UPDATE #ResultTable SET begin_b_total+=(SELECT ISNULl(SUM(ISNULL(I.Total,0)),0) 
		FROM inigoodsstocks I 
		INNER JOIN stock s on i.KtypeId=s.typeId 
		INNER JOIN #Stype S1 ON S1.TypeID=S.STypeID)
		WHERE TypeID IN(SELECT ATypeId FROM Ac_Items_Detail WHERE nId=30)
		
		--修改委托代销期初(委托)
		UPDATE #ResultTable SET begin_b_total+=(SELECT ISNULl(SUM(ISNULL(CostTotal,0)),0) FROM inicommissionstock I INNER JOIN #Stype S ON S.TypeID=i.Stypeid WHERE type=140)
		WHERE TypeID IN(SELECT ATypeId FROM Ac_Items_Detail WHERE nId=31) 
		
		-- 修改代销商品期初（受托）
		UPDATE #ResultTable SET begin_b_total+=(SELECT ISNULL(SUM(ISNULL(Total,0)),0) as total FROM inicommissionstock I INNER JOIN #Stype S ON S.TypeID=i.Stypeid WHERE type=144) 
		WHERE TypeID IN(SELECT ATypeId FROM Ac_Items_Detail D  WHERE nId=37)
	END

--内部应收
--UPDATE #ResultTable SET begin_b_total+=(SELECT ISNULl(SUM(ISNULL(I.InnerARTotal00,0)),0) 
--FROM SType_InnerARTotal I 
--INNER JOIN #Stype S1 ON S1.TypeID=I.STypeID)
--WHERE typeid IN (SELECT ATypeId FROM dbo.Ac_Items_Detail d JOIN #Stype s ON d.STypeId=s.TypeID WHERE nid=28)
 
UPDATE A SET begin_b_total+=ISNULL(Total,0)
FROM #ResultTable A
INNER JOIN (
	 SELECT ATypeId,ISNULl(SUM(ISNULL(si.InnerARTotal00,0)),0)   AS total
	 FROM dbo.SType_InnerARTotal si 
	JOIN  dbo.Ac_Items_Detail ai ON si.STypeID=ai.STypeId AND nid=28 
	JOIN #Stype S ON ai.STypeId=s.typeid 
	GROUP BY ATypeId
)  T ON T.ATypeID=A.TypeID
 
--如果查询日期大于开账日期，还要把这段日期的发生额加上当做期初
IF @StartDate>=@createtime
	UPDATE A SET begin_b_total+=ISNULL(Total,0)
	FROM #ResultTable A
	INNER JOIN (
		SELECT i.ATypeID,ISNULL(SUM(ISNULL(t.Total,0)),0) AS Total
		FROM ListTable t 
		JOIN #AcItems i ON  i.nId=t.AtypeId AND t.STypeID=i.STypeId
		JOIN #Stype s ON s.typeid=t.STypeID
		WHERE t.BillDate<@startdate
		GROUP BY i.ATypeID
	) T ON T.ATypeID=A.TypeID
 
--满足业务条件数据，就是项目的发生额
DECLARE @ListTable TABLE(ItemId INT,BillDate DATETIME,Total  NUMERIC(24, 10) ,AtypeId VARCHAR(50))
INSERT INTO @ListTable(ItemId,BillDate,Total,AtypeId)
SELECT L.AtypeId,L.BillDate,L.Total,I.ATypeID
FROM ListTable L
INNER JOIN #AcItems I ON L.AtypeId=I.NId AND I.STypeId=L.STypeID AND L.BillDate<=@EndDate AND L.BillDate>=@startDate 
		
---期末
UPDATE A SET end_b_total+=ISNULL(A.begin_b_total,0)+ISNULL(LT.Total,0)
FROM #ResultTable A
LEFT  JOIN   -- 发生额
(
	SELECT 
		AtypeId,
		SUM(ISNULL(Total,0)) Total 
	FROM @ListTable 
	GROUP BY AtypeId
) LT ON LT.AtypeId=A.TypeID
	

UPDATE #ResultTable SET f_b_total=ISNULL(end_b_total,0)-ISNULL(begin_b_total,0)  
 
--特殊处理，当结束日期<启用期间的第一天,期末=期初
DECLARE @begindate DATETIME
SELECT @begindate=FBegin FROM dbo.Ac_Period WHERE FYear=@FYear AND FMonth=FPeriod
IF @enddate<@begindate
	BEGIN
		UPDATE #ResultTable SET end_b_total=begin_b_total
		UPDATE #ResultTable SET f_b_total=ISNULL(end_b_total,0)-ISNULL(begin_b_total,0)  
	END
	 
--==========================================业务【END】=====================================================
 
--======================================================财务【BEGIN】==========================================
   	--财务期初余额，期末余额
	UPDATE #ResultTable SET begin_f_total+=ISNULL(AI.iniTotal,0),end_f_total+=ISNULL(AI.iniTotal,0)
	FROM #ResultTable RT
	INNER JOIN
	(
		SELECT 
			ATypeId,
			SUM(ISNULL(iniTotal,0)) iniTotal 
		FROM Ac_IniAccount I
		INNER JOIN #Stype S ON S.TypeID=I.STypeId
		GROUP BY ATypeId
	)AI ON AI.ATypeId=RT.TypeID 
	

	DECLARE @Voucher TABLE(AtypeID VARCHAR(50),Total  NUMERIC(24, 10) ,BillDate DATETIME,IfCheck VARCHAR(2),FChecked INT)
	INSERT INTO @Voucher(AtypeID,Total,BillDate,IfCheck,FChecked)
	SELECT B.ATypeId,
	CASE 
		WHEN AA.Fdc=1 THEN ISNULL(CASE WHEN B.FAdc=1 THEN B.FdebitTotal ELSE -B.FcreditTotal END,0)
		ELSE ISNULL(CASE WHEN B.FAdc=1 THEN -B.FdebitTotal ELSE B.FcreditTotal END,0)
	END Total,
	A.BillDate,
	A.IfCheck,
	A.FChecked
	FROM Ac_Voucher_Bill B
	INNER JOIN Ac_Voucher A ON A.BillNumberId=B.BillNumberId AND A.STypeId=@StypeID AND A.BillDate<=@EndDate AND A.FChecked<>-1 AND A.VoucherType<>2
	INNER JOIN Ac_Account AA ON AA.TypeId=B.ATypeId AND AA.StypeId=@StypeID
			
	IF(@IsShowNoAccount=1)--包含未过账凭证
		BEGIN
			--期初
			UPDATE #ResultTable SET begin_f_total+=ISNULL(B.Total,0)
			FROM #ResultTable RT	
			INNER JOIN
			(
				SELECT 
					AtypeID,
					SUM(ISNULL(Total,0)) Total 
				FROM @Voucher 
				WHERE 
					BillDate<@StartDate
					AND IfCheck='f' 
					AND FChecked<>-1
				GROUP BY ATypeID
			) B ON B.ATypeId=RT.TypeID 
			
			--累计期末
			UPDATE #ResultTable SET end_f_total+=ISNULL(B.Total,0)
			FROM #ResultTable RT
			INNER JOIN
			(
				SELECT 
					AtypeID,
					SUM(ISNULL(Total,0)) Total 
				FROM @Voucher 
				WHERE 
					BillDate<=@EndDate  
					AND IfCheck='f' 
					AND FChecked<>-1
				GROUP BY ATypeID
			) B ON B.ATypeId=RT.TypeID 	
		END
		
	--期初
	UPDATE #ResultTable SET begin_f_total+=ISNULL(B.Total,0)
	FROM #ResultTable RT	
	INNER JOIN
	(
		SELECT 
			AtypeID,
			SUM(ISNULL(Total,0)) Total 
		FROM @Voucher 
		WHERE
			
			BillDate<@StartDate		
			AND IfCheck='t'
		GROUP BY ATypeID
	) B ON B.ATypeId=RT.TypeID 	
	
	
	--累计期末
	UPDATE #ResultTable SET end_f_total+=ISNULL(B.Total,0)
	FROM #ResultTable RT
	INNER JOIN
	(
		SELECT 
			AtypeID,
			SUM(ISNULL(Total,0)) Total 
		FROM @Voucher 
		WHERE 
			BillDate<=@EndDate 
			AND IfCheck='t'
		GROUP BY ATypeID
	) B ON B.ATypeId=RT.TypeID 	

UPDATE #ResultTable SET f_f_total+=ISNULL(end_f_total,0)-ISNULL(begin_f_total,0)
--============================================财务【END】  =============================================

--差额计算

UPDATE #ResultTable 
SET 
	begin_d_total=begin_f_total-begin_b_total,
	f_d_total=f_f_total-f_b_total,
	end_d_total=end_f_total-end_b_total


IF EXISTS(SELECT TOP 1 1 FROM #ResultTable WHERE end_b_total-end_f_total  <> 0 )
	SET @noequal = 1
ELSE
	SET @noequal = 0

--排除数据 为0的数据	 将科目所有数据都为0的信息排除掉
IF @DataIsAllZero=1
	BEGIN
		DELETE FROM #ResultTable
		WHERE
			begin_b_total=0 
			AND begin_f_total=0 
			AND begin_d_total=0 
			AND f_b_total=0 
			AND f_f_total=0 
			AND f_d_total=0
			AND end_b_total=0 
			AND end_f_total=0 
			AND end_d_total=0
	END
IF @D_TotalIsZero=1 --排除数据差额为0的数据 则将数据行中所有差额都为0的信息排除掉
	BEGIN
		DELETE FROM #ResultTable
		WHERE
			begin_d_total=0 
			AND f_d_total=0
			AND end_d_total=0
	END
SELECT * FROM #ResultTable
ORDER BY UserCode
DROP TABLE #Atype,#AcItems,#ResultTable

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryFixedAssetsChangedHistory]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryFixedAssetsChangedHistory
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- ========================================================================
-- 描述：固定资产-资产变更记录查询 列表数据
-- 时间：2013-05-27
-- 作者：glj	
-- ========================================================================
CREATE PROC Web_QueryFixedAssetsChangedHistory
(
	@dchangetype	INT,			--部门转移
	@pchangetype	INT,			--计提减值准备
	@zchangetype	INT,			--折旧方式变更
	@Start_O_Date	VARCHAR(20),	--操作日期从
	@End_O_Date		VARCHAR(20),	--至
	@Start_B_Date	VARCHAR(20),	--业务日期从
	@End_B_Date		VARCHAR(20),	--至
	@CardId			VARCHAR(MAX),	--资产名称
	@EtypeId		VARCHAR(MAX),	--操作人员
	@IsHaveVoucher	INT,			--是否生成凭证
	@OperatorId		VARCHAR(50)		--操作员
)
--@encode$--

AS
SET NOCOUNT ON 
DECLARE @SQL VARCHAR(MAX)='SELECT * FROM #History H'+CHAR(13)
--变更查询
CREATE TABLE #History(ID INT,CardId INT,ChangeType VARCHAR(20),SourceId INT,OperationDate VARCHAR(10),BusinessDate VARCHAR(10),
ETypeId VARCHAR(50),UserCode VARCHAR(200),FullName VARCHAR(200),StypeID VARCHAR(50),StypeFullName VARCHAR(66),IsHaveVoucher VARCHAR(5),VoucherId INT,BillType INT)

--部门转移
IF(@dchangetype=1)
	BEGIN
		INSERT INTO #History(ID,CardId,ChangeType,SourceId,OperationDate,BusinessDate,ETypeId,UserCode,FullName,StypeID,StypeFullName,IsHaveVoucher,VoucherId,BillType)
		SELECT 
			DISTINCT
			d.Id,
			d.CardId,
			'部门转移' ChangeType,
			2 SourceId,
			CONVERT(VARCHAR(10),d.OperationDate,120) OperationDate,
			CONVERT(VARCHAR(10),d.BusinessDate,120) BusinessDate,
			d.ETypeId,
			AC.UserCode,
			AC.FullName,
			S.TypeId StypeID,
			s.FullName StypeFullName,
			CASE WHEN pv.id IS NOT NULL AND pv.Id<>-1 AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) THEN '是'
				ELSE '否'
			END IsHaveVoucher,
			pv.VoucherId,
			C.BillType
		FROM Ac_AssetsModifyRecords d
		INNER JOIN Ac_AssetsCards AC ON AC.Id=D.CardId
		INNER JOIN Ac_AssetsCards_History c ON c.BillId=d.Id AND C.BillType=-2
		INNER JOIN SType s ON S.TypeId=C.STypeId
		LEFT JOIN Ac_Provision_Voucher pv ON pv.SourceType=2 AND pv.SourceId=d.Id
	END

--计提减值准备
IF(@pchangetype=1)
	BEGIN
		INSERT INTO #History(ID,CardId,ChangeType,SourceId,OperationDate,BusinessDate,ETypeId,UserCode,FullName,StypeID,StypeFullName,IsHaveVoucher,VoucherId,BillType)
		SELECT 
			DISTINCT
			p.Id,
			p.CardId,
			'计提减值准备' ChangeType,
			1 SourceId,
			CONVERT(VARCHAR(10),p.OperationDate,120) OperationDate,
			CONVERT(VARCHAR(10),p.BusinessDate,120) BusinessDate,
			p.ETypeId,
			AC.UserCode,
			AC.FullName,
			S.TypeId StypeID,
			s.FullName StypeFullName,
			CASE WHEN pv.id IS NOT NULL AND pv.Id<>-1 AND EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) THEN '是'
			     WHEN EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 0) AND p.BillnumberId IS NOT NULL AND p.BillnumberId<>-1 THEN '是'
				ELSE '否'
			END IsHaveVoucher,
			CASE WHEN EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 1) THEN pv.VoucherId
				 WHEN EXISTS(SELECT TOP 1 1 FROM sysdata WHERE SubName='IsUseAcSystem' AND SubValue = 0) THEN P.BillnumberId
				 END AS VoucherId,
			C.BillType
		FROM Ac_ProvisionForImpairment p
		INNER JOIN Ac_AssetsCards AC ON AC.Id=P.CardId
		INNER JOIN Ac_AssetsCards_History c ON c.BillId=p.Id AND C.BillType=-1
		INNER JOIN SType s ON S.TypeId=c.STypeId
		LEFT JOIN Ac_Provision_Voucher pv ON pv.SourceType=1 AND pv.SourceId=p.Id 
	END
--折旧方式变更
IF(@zchangetype=1)
	BEGIN
		INSERT INTO #History(ID,CardId,ChangeType,SourceId,OperationDate,BusinessDate,ETypeId,UserCode,FullName,StypeID,StypeFullName,IsHaveVoucher,VoucherId,BillType)	
		SELECT 
			DISTINCT
			d.Id,
			d.CardId,
			'折旧方式变更' ChangeType,
			0 SourceId,
			CONVERT(VARCHAR(10),d.OperationDate,120) OperationDate,
			CONVERT(VARCHAR(10),d.BusinessDate,120) BusinessDate,
			d.ETypeId,
			AC.UserCode,
			AC.FullName,
			S.TypeId,
			s.FullName StypeFullName,
			'否' IsHaveVoucher,
			NULL VoucherId,
			C.BillType
		FROM Ac_DepreciationAlteration d
		INNER JOIN Ac_AssetsCards AC ON AC.Id=D.CardId
		INNER JOIN Ac_AssetsCards_History c ON c.BillId=d.Id  AND C.BillType=-3
		INNER JOIN SType s ON S.TypeId=C.STypeId
	END

--资产卡片
IF ISNULL(@CardId,'')<>''
	SET @SQL+='INNER JOIN f_split('''+@CardId+''','','') F ON F.a=H.CardId'+CHAR(13)
--操作人员
IF ISNULL(@EtypeId,'')<>''
	SET @SQL+='INNER JOIN DBO.F_GetAllManagerBaseTypeId('''+@EtypeId+''',3,'''+@OperatorId+''') F1 ON H.ETypeId=F1.TypeId'+CHAR(13)
SET @SQL+='WHERE 1=1'+CHAR(13)

--操作日期
IF ISNULL(@Start_O_Date,'')<>'' AND ISNULL(@End_O_Date,'')<>''
	SET @SQL+='AND H.OperationDate BETWEEN '''+@Start_O_Date+''' AND '''+@End_O_Date+''''+CHAR(13)
ELSE IF ISNULL(@Start_O_Date,'')<>'' AND ISNULL(@End_O_Date,'')=''
	SET @SQL+='AND H.OperationDate>='''+@Start_O_Date+''''+CHAR(13)
ELSE IF ISNULL(@Start_O_Date,'')='' AND ISNULL(@End_O_Date,'')<>''
	SET @SQL+='AND H.OperationDate<='''+@End_O_Date+''''+CHAR(13)
	
--业务日期
IF ISNULL(@Start_B_Date,'')<>'' AND ISNULL(@End_B_Date,'')<>''
	SET @SQL+='AND H.BusinessDate BETWEEN '''+@Start_B_Date+''' AND '''+@End_B_Date+''''+CHAR(13)
ELSE IF ISNULL(@Start_B_Date,'')<>'' AND ISNULL(@End_B_Date,'')=''
	SET @SQL+='AND H.BusinessDate>='''+@Start_B_Date+''''+CHAR(13)
ELSE IF ISNULL(@Start_B_Date,'')='' AND ISNULL(@End_B_Date,'')<>''
	SET @SQL+='AND H.BusinessDate<='''+@End_B_Date+''''+CHAR(13)
	
--是否生成凭证
IF @IsHaveVoucher=1
	SET @SQL+='AND H.IsHaveVoucher=''是'''+CHAR(13)
IF @IsHaveVoucher=0
	SET @SQL+='AND H.IsHaveVoucher=''否'''+CHAR(13)
--排序
SET @SQL+='ORDER BY H.OperationDate'

--print @SQL

EXEC(@SQL)

DROP TABLE #History

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryFixedReasonForChangeDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryFixedReasonForChangeDetails
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回存货类型列表
-- 时间：	2016-05-12
-- 作者：	lxl
-- ========================================================================
CREATE PROC Web_QueryFixedReasonForChangeDetails
(
	@TID			INT,			--类型ID
    @OperatorID		VARCHAR(50)		-- 操作员
)

--@encode$--
AS
SET NOCOUNT ON 
IF(@TID=0)
	BEGIN
		SELECT 
			DISTINCT
			0 nid,
			0 TId,
			S.VerifyID,
			s.TypeId STypeId,
			s.FullName SFullName,
			'' EnterATypeID,
			'' EnterFullName,
			'' ForeignATypeID,
			'' ForeignFullName,
			'' RateATypeID,
			'' RateFullName
		FROM SType S
		INNER JOIN dbo.F_GetAllManagerBaseTypeId('',11,@OperatorID) F ON F.TypeId=S.TypeId AND S.deleted=0
	END
ELSE 
	BEGIN
		--处理会计科目多级权限
		CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200))
		INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName) 
		SELECT L.Typeid,L.Stypeid,A.FullName FROM F_LineAccount(@OperatorID,'') L
		INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
		SELECT
			DISTINCT
			D.NID,
			D.TID,
			S.VerifyID,
			D.STypeId,
			S.FullName SFullName,
			D.EnterATypeID,
			CASE WHEN ISNULl(D.EnterATypeID,'')='' THEN '' ELSE  ISNULL(a.FullName,'****') END EnterFullName,
			D.ForeignATypeID,
			CASE WHEN ISNULl(D.ForeignATypeID,'')='' THEN '' ELSE  ISNULL(a1.FullName,'****') END ForeignFullName,
			D.RateATypeID,
			CASE WHEN ISNULl(D.RateATypeID,'')='' THEN '' ELSE  ISNULL(a2.FullName,'****') END RateFullName
		FROM Base_FixedReasonForChangeDetails D
		INNER JOIN dbo.F_GetAllManagerBaseTypeId('',11,@OperatorID) F ON F.TypeId=D.STypeId
		INNER JOIN SType S ON S.TypeId=D.STypeId AND S.SonNum=0
		LEFT JOIN #Ac_Account_L a ON a.typeId=D.EnterATypeID AND a.StypeId=s.VerifyID
		LEFT JOIN #Ac_Account_L a1 ON a1.TypeId=D.ForeignATypeID  AND a.StypeId=s.VerifyID
		LEFT JOIN #Ac_Account_L a2 ON a2.TypeId=D.RateATypeID AND a.StypeId=s.VerifyID
		WHERE D.TID=@TID
	END
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS(SELECT * FROM SYSOBJECTS WHERE id=OBJECT_ID(N'[dbo].[Web_QueryForeignCurrencyDetail]') AND OBJECTPROPERTY(id,N'ISPROCEDURE')=1)
DROP PROCEDURE [dbo].[Web_QueryForeignCurrencyDetail]
GO


/*
	作者：鲁大林
	日期：2013-05-09
	描述：外币明细分布表
*/

CREATE PROCEDURE Web_QueryForeignCurrencyDetail
( 
	@OperatorID 	VARCHAR(100) ,   --操作员id
	@btypeid 		VARCHAR(max),	--往来单位节点号
	@stypeid		VARCHAR(MAX),	--分支机构
	@StartDate		VARCHAR(50),
	@ENDDate		VARCHAR(50),
	@IncludePre		VARCHAR(10)='False',
	@option			INT=0,	--选项  0全部显示 1不显示金额为0 2只显示金额为0，3无发生额不显示
	@nType			INT,			--1,3  应收  2,4应付
	@etypeid        VARCHAR(MAX),	--经手人
	@cid			VARCHAR(MAX),
	@List			varchar(2),--是否是树形表
	@dtypeid		VARCHAR(MAX),	--部门
	@DtypeIsVisible	INT			--1=使用部门 0=不使用部门   
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MATypeId VARCHAR(50), @MBTypeid VARCHAR(50), @MBTypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SQL		VARCHAR(MAX),
		@SONNum		INT,
		@SqlWHERE	VARCHAR(1000),
		@SqlWHERE1	VARCHAR(1000),
		@preSql1	VARCHAR(1000), --应收增加条件(本币)
		@preSql2	VARCHAR(1000), --应收减少条件(本币)
		@AtypeType	VARCHAR(1000), --要查询的科目
		@QcSql		VARCHAR(1000),
		@aratypeID	VARCHAR(50),
		@ysatypeID	VARCHAR(50),
		@apatypeID	VARCHAR(50),
		@yfatypeID	VARCHAR(50)
		

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

SET @SqlWHERE=''
SET @SqlWHERE1=''
IF @option=0--全部为零的不显示
BEGIN
	SET @SqlWHERE1=' WHERE qmtotal<>0 OR BQOVERTOTAL<>0 OR BQLOWERTOTAL<>0 OR QCTOTAL<>0 '
END
IF @optiON=1
BEGIN
	SET @SqlWHERE=' AND m.qmtotal<>0 '
	SET @SqlWHERE1=' WHERE qmtotal<>0 '
END
IF @optiON=2
BEGIN
	SET @SqlWHERE=' AND m.qmtotal=0 '
	SET @SqlWHERE1=' WHERE qmtotal=0 '
END
IF @optiON=3
BEGIN
	SET @SqlWHERE=' AND (m.BQOVERTOTAL<>0 or m.BQLOWERTOTAL<>0) '
	SET @SqlWHERE1=' WHERE BQOVERTOTAL<>0 or BQLOWERTOTAL<>0 '
END
SET @preSql1=''
SET @preSql2=''	

CREATE TABLE #stype(typeid	VARCHAR(50))
CREATE TABLE #btype1(typeid	VARCHAR(50))
CREATE TABLE #etype(typeid	VARCHAR(50))
CREATE TABLE #dtype(typeid	VARCHAR(50))

DECLARE @sql1 VARCHAR(8000) 
if(@List='0')--树形
	SELECT @sql1=dbo.F_GetAllBaseInfoTypeId(@btypeid,2,@OperatorID,'#btype1')
else
	SELECT @sql1='INSERT INTO #btype1(TypeId) 
					SELECT TypeID 
					FROM BType A
					WHERE A.SonNum = 0 and A.typeid='+CHAR(39)+@btypeid+CHAR(39)+' '
SELECT @sql1=@sql1+dbo.F_GetAllBaseInfoTypeId(@etypeid,3,'00001','#etype')
SELECT @sql1=@sql1+dbo.F_GetAllBaseInfoTypeId(@stypeid,11,@OperatorID,'#stype')

IF @DtypeIsVisible = 1 AND @dtypeid <> ''
	INSERT #dtype(typeid) SELECT TypeId FROM F_GetAllBaseTypeId(@dtypeid,9)	

--PRINT @sql1
EXEC(@sql1)


DECLARE @BtypeSQL VARCHAR(50)
SET @BtypeSQL=' btype '
IF EXISTS(SELECT 1 FROM #BTYPE1)
SET @BtypeSQL= ' #btype1 '

------------------------------------------按照币种统计-------------------------------------------------
CREATE TABLE #ctypeid(cid VARCHAR(50),FULLNAME VARCHAR(100))
if @cid<>0
	INSERT INTO #ctypeid(cid,FULLNAME) SELECT CId,FullName FROM dbo.Ac_Currency where CId=@cid   -------------------默认条件要不要影响这里，待定
else
	INSERT INTO #ctypeid(cid,FULLNAME) SELECT CId,FullName FROM dbo.Ac_Currency   -------------------默认条件要不要影响这里，待定
CREATE TABLE #C_RESULTTABLE
(
	CID				VARCHAR(10),	--币种ID
	QCTOTAL			 NUMERIC(24, 10) ,	--期初金额
	BQOVERTOTAL		 NUMERIC(24, 10) ,	--本期增加
	BQLOWERTOTAL	 NUMERIC(24, 10) ,	--本期减少
	QMTOTAL			 NUMERIC(24, 10) 	--期末余额
)

CREATE TABLE #CidIndex
(
	CID		VARCHAR(10),
	nartotal00	 NUMERIC(24, 10) ,
	naptotal00	 NUMERIC(24, 10) ,
	nystotal00	 NUMERIC(24, 10) ,
	nyftotal00	 NUMERIC(24, 10) 
)

SET @SQL = '
	INSERT #CidIndex
	
	SELECT	A.CID,
			B.nARTotal00,B.nAPTotal00,
			B.nysTotal00,B.nyfTotal00
	FROM
	(
		SELECT DISTINCT A.CID
		FROM BType_ArApTotal A '
		IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 B1 ON a.BTYPEID=B1.TYPEID'+CHAR(13)

		IF EXISTS(SELECT 1 FROM #STYPE)
			SET @SQL=@SQL+' INNER JOIN #STYPE S ON a.STYPEID=S.TYPEID'+CHAR(13)
		IF @cid<>0
			SET @SQL += ' WHERE A.CID ='+@cid+' '
	
	SET @SQL += ' ) A
	LEFT JOIN
	(
		SELECT A.CID, 
			SUM(a.nARTotal00) AS nARTotal00,  SUM(a.nAPTotal00)AS nAPTotal00 ,
			SUM(a.nysTotal00) AS nysTotal00,  SUM(a.nyfTotal00) AS nyfTotal00
		FROM IniBType_ArApTotal A '
		
		IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 B1 ON a.BTYPEID=B1.TYPEID'+CHAR(13)

		IF EXISTS(SELECT 1 FROM #STYPE)
			SET @SQL=@SQL+' INNER JOIN #STYPE S ON a.STYPEID=S.TYPEID'+CHAR(13)

		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @SQL=@SQL+' INNER JOIN #DTYPE D ON a.DTYPEID=D.TYPEID'+CHAR(13)

		IF @cid<>0
				SET @SQL += ' WHERE A.CID ='+@cid+' '
		
		SET @SQL += ' GROUP BY A.CID ) B ON B.CID = A.CID '

EXEC(@SQL)

IF @nType=1 --应收
BEGIN
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@ysatypeID+CHAR(39)+','+CHAR(39)+@aratypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal<0  THEN ABS(l.nTotal) '
		SET @preSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.nTotal>0 THEN l.nTotal '		--期初
		SET @QcSql = ' SUM(ISNULL(a.nARTotal00,0)-ISNULL(a.nystotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS QCTOTAL, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)
		
		SET @QcSql = ' SUM(ISNULL(a.nARTotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS QCTOTAL, '
	END
	SET @SQL='
	INSERT INTO #C_RESULTTABLE
	(
		CID				,	
		QCTOTAL			,	
		BQOVERTOTAL		,	
		BQLOWERTOTAL	,	
		QMTOTAL				
	)
	SELECT	A.CID,
			'+@QcSql+'
			0 AS BQOVERTOTAL,
			0 AS BQLOWERTOTAL,
			0 AS QMTOTAL
	FROM #CidIndex a '
		
	SET @SQL=@SQL+'	LEFT JOIN 
				(SELECT	L.CID,
						SUM(CASE WHEN l.billtype IN(45,215,11,160) AND l.AtypeId='+@aratypeID+' THEN l.nTotal
							     WHEN l.AtypeId='+@aratypeID+' AND l.nTotal>0 AND l.BillType NOT IN(45,215,11,160,4) THEN l.nTotal '+@preSql1+'
								 ELSE 0 
							  END) AS naddtotal,
						SUM(CASE WHEN l.BillType=4 AND l.AtypeId='+@aratypeID+' THEN CASE WHEN l.nTotal<0 THEN abs(l.nTotal) ELSE -l.nTotal END
								 WHEN l.AtypeId='+@aratypeID+' AND l.nTotal<0 AND l.BillType NOT IN(45,215,11,160,4) THEN ABS(l.nTotal)'+@preSql2+'
							  ELSE 0 
							  END) AS nrectotal
				FROM	ListTABLE L 
				'

	IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
		SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)

	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' WHERE	L.BillDate < '''+@StartDate+''' 
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	SET @SQL=@SQL+'
		GROUP BY L.CID) b ON a.CID=b.CId '
	SET @SQL=@SQL+'	GROUP BY a.CID
		'
		--PRINT(@SQL)
	EXEC(@sql)
	
	
	SET @SQL='	
	INSERT INTO #C_RESULTTABLE
	(
		CID				,	
		QCTOTAL			,	
		BQOVERTOTAL		,	
		BQLOWERTOTAL	,	
		QMTOTAL				
	)
	SELECT	L.CID,
			0 AS QCTOTAL,
			SUM(CASE WHEN l.billtype IN(45,215,11,160) AND l.AtypeId='+@aratypeID+' THEN l.nTotal
					 WHEN l.AtypeId='+@aratypeID+' AND l.nTotal>0 AND l.BillType NOT IN(45,215,11,160,4) THEN l.nTotal'+@preSql1+'
					 ELSE 0
				END) AS BQOVERTOTAL,
			SUM(CASE WHEN l.BillType=4 AND l.AtypeId='+@aratypeID+' THEN CASE WHEN l.nTotal<0 THEN abs(l.nTotal) ELSE -l.nTotal END
					 WHEN  l.AtypeId='+@aratypeID+' AND l.nTotal<0 AND l.BillType NOT IN(45,215,11,160,4) THEN ABS(l.nTotal)'+@preSql2+'
				 ELSE 0
				END) AS BQLOWERTOTAL,
			0 AS QMTOTAL	
	FROM	ListTable L'

			
	IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
		SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
		
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)
		
	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@ENDDate+' ''
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.CID ='+@cid+'	GROUP BY L.CID'
	else
		set @sql=@sql+' group by L.cid'
	EXEC(@sql)
END
ELSE		--应付
BEGIN 
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)+','+CHAR(39)+@yfatypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.nTotal) '
		SET @preSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total>0 THEN l.nTotal '
		
		--期初
		SET @QcSql = ' SUM(ISNULL(a.nAPTotal00,0)-ISNULL(a.nyftotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS QCTOTAL, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)
		
		SET @QcSql = ' SUM(ISNULL(a.nAPTotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS QCTOTAL, '
	END
	SET @SQL='
	INSERT INTO #C_RESULTTABLE
	(
		CID				,	
		QCTOTAL			,	
		BQOVERTOTAL		,	
		BQLOWERTOTAL	,	
		QMTOTAL				
	)
	SELECT	a.CID,
			'+@QcSql+'
			0 AS BQOVERTOTAL,
			0 AS BQLOWERTOTAL,
			0 AS QMTOTAL
	FROM #CidIndex a  '
	
	SET @SQL=@SQL+' 
	LEFT JOIN 
	(SELECT	L.CID,
			SUM(CASE WHEN l.billtype IN(6,34,161) AND l.AtypeId='+@apatypeID+' THEN l.nTotal
					 WHEN l.AtypeId='+@apatypeID+' AND l.nTotal>0 AND l.BillType NOT IN(6,34,161,66) THEN l.nTotal'+@preSql1+'
					 ELSE 0 
				END) AS naddtotal,
			SUM(CASE WHEN l.BillType=66 AND l.AtypeId='+@apatypeID+' THEN (CASE WHEN l.nTotal<0 THEN ABS(l.nTotal) ELSE -l.nTotal END)
					 WHEN  l.AtypeId='+@apatypeID+' AND l.nTotal<0 AND  l.BillType NOT IN(6,34,161,66) THEN ABS(l.nTotal)'+@preSql2+'
					 ELSE 0 
				END) AS nrectotal
	FROM	ListTABLE L '
	IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
		SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
	
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' WHERE	L.BillDate < '''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	SET @SQL=@SQL+'
		GROUP BY L.CID) b ON a.CID=b.CID  '
	IF @cid<>0
		SET @SQL=@SQL+' WHERE A.CID ='+@cid+'	GROUP BY a.CID'
	else
		set @sql=@sql+' group by a.cid'
	
	EXEC(@sql)

	SET @SQL='
	INSERT INTO #C_RESULTTABLE
	(
		CID				,	
		QCTOTAL			,	
		BQOVERTOTAL		,	
		BQLOWERTOTAL	,	
		QMTOTAL				
	)
	SELECT	DISTINCT
			L.CID,
			0 AS QCTOTAL,
			SUM(CASE WHEN l.billtype IN(6,34,161) AND l.AtypeId='+@apatypeID+' THEN l.nTotal
					 WHEN l.AtypeId='+@apatypeID+' AND l.nTotal>0 AND l.BillType NOT IN(6,34,161,66) THEN l.nTotal'+@preSql1+'
					 ELSE 0
				END) AS BQOVERTOTAL,
			SUM(CASE WHEN l.BillType=66 AND l.AtypeId='+@apatypeID+' THEN (CASE WHEN l.nTotal<0 THEN ABS(l.nTotal) ELSE -l.nTotal END)
					 WHEN l.AtypeId='+@apatypeID+' AND l.nTotal<0 AND  l.BillType NOT IN(6,34,161,66) THEN ABS(l.nTotal)'+@preSql2+'
					 ELSE 0
				END) AS BQLOWERTOTAL,
			0 AS QMTOTAL	
	FROM	ListTABLE L'
	IF EXISTS(SELECT 1 FROM #BTYPE1)
		SET @SQL=@SQL+' INNER JOIN #BTYPE1 BB ON L.BTYPEID=BB.TYPEID'+CHAR(13)
	
	IF EXISTS(SELECT 1 FROM #ETYPE)
		SET @SQL=@SQL+' INNER JOIN #ETYPE E ON L.ETYPEID=E.TYPEID'+CHAR(13)

	IF EXISTS(SELECT 1 FROM #STYPE)
		SET @SQL=@SQL+' INNER JOIN #STYPE S ON L.STYPEID=S.TYPEID'+CHAR(13)
	
	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL=@SQL+' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)

	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@ENDDate+''' 
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.CID ='+@cid+'	GROUP BY L.CID'
	else
		SET	@SQL=@SQL+'	GROUP BY L.CID '
	EXEC(@sql)

--PRINT(@sql)
END

------------------------------------------------------------------------------------------------------------------------------------
SET @SQL='
SELECT	B.FULLNAME AS CFULLNAME,
		ISNULL(m.BQOVERTOTAL,0) AS BQOVERTOTAL,
		ISNULL(m.BQLOWERTOTAL,0) AS BQLOWERTOTAL,
		ISNULL(M.QCTOTAL, 0) AS QCTOTAL,
		ISNULL(M.QMTOTAL, 0) AS QMTOTAL
FROM	#ctypeid B
LEFT JOIN (
	SELECT	CID,	
			SUM(ISNULL(QCTOTAL,0)) AS QCTOTAL,
			SUM(ISNULL(BQOVERTOTAL,0)) AS BQOVERTOTAL,
			SUM(ISNULL(BQLOWERTOTAL,0)) AS BQLOWERTOTAL,
			SUM(ISNULL(QCTOTAL,0) +  ISNULL(BQOVERTOTAL,0) - ISNULL(BQLOWERTOTAL,0)) AS QMTOTAL
	FROM 	#C_RESULTTABLE
	GROUP BY CID
)M ON m.CID =B.CID'
		
IF @SqlWHERE<>''
SET @SQL=@SQL+' WHERE 1=1'+@SqlWHERE 

IF @cid<>0
		SET @SQL=@SQL+' AND b.CID ='+@cid+' and m.cid ='+@cid

SET @SQL='SELECT * FROM ('+@SQL+') AS a '+@SqlWHERE1

--PRINT(@sql)
EXEC(@SQL)



DROP TABLE #stype,#btype1,#etype,#C_RESULTTABLE,#ctypeid,#CidIndex,#dtype


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT TOP 1 1 FROM  dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryFormulaAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].[Web_QueryFormulaAccount]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*
	作者：glj
	日期：2019-04-24
	描述：三大固化报表-科目查询
*/ 
CREATE PROCEDURE dbo.Web_QueryFormulaAccount
(
	@STypeId	VARCHAR(50),--分支机构
	@ParId		VARCHAR(50),--科目类别
	@OperatorID VARCHAR(50),--操作员
	@Filter		VARCHAR(200),--查询条件
	@ReportType	INT,--报表类型 1:利润表 2：现金流量表 3：资产负债表
	@IsSumItem	INT,--1：合计列 0 正常列
	@ItemId		INT	--当前项目
)
--@encode$--
AS
IF(@IsSumItem=1)
	BEGIN
		SELECT 
			ItemID,
			ItemFullName 
		FROM ThreeFinancialItem_SType
		WHERE 
			ReportType=@ReportType
			AND STypeId=@STypeId
			AND ItemId<>@ItemId
	END
ELSE 
	BEGIN
		IF(@ReportType=2)
		BEGIN
			IF(@ParId='00000')
				BEGIN
					SELECT	TypeId,
							ParId,
							UserCode,
							REPLICATE('    ',Leveal-1) +UserCode AS FUserCode,
							FullName
					FROM	Ac_CashMoneyItems 
					WHERE	
						Leveal > 0 
						AND ((ISNULL(@Filter,'')='' AND ((@ParId<>'00000' AND TypeId LIKE @ParId+'%') OR @ParId='00000')
						OR ISNULL(@Filter,'')<>'' AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%')) )
					ORDER BY UserCode
				
				END
			ELSE IF(@ParId='01')--
				BEGIN
					SELECT	TypeId,
							ParId,
							UserCode,
							REPLICATE('    ',Leveal-1) +UserCode AS FUserCode,
							FullName
					FROM	Ac_CashMoneyItems 
					WHERE	TypeId NOT LIKE '00005%' 
							AND Leveal > 0 
					ORDER BY UserCode
				END
			ELSE IF(@ParId='02')--
				BEGIN
					SELECT	TypeId,
							ParId,
							UserCode,
							REPLICATE('    ',Leveal-1) +UserCode AS FUserCode,
							FullName
					FROM	Ac_CashMoneyItems
					WHERE	TypeId LIKE '00005%' AND Leveal > 0
					ORDER BY UserCode
				END
			ELSE 
				BEGIN
					IF(@ParId='03') SET @ParId='00000' --科目父节点
					SELECT 
						A.TypeId,
						A.ParId,
						A.UserCode,
						REPLICATE('    ',A.FLeveal-1) + A.UserCode AS FUserCode,
						A.FullName, 
						CASE WHEN A.Fdc=1 THEN '借'  ELSE '贷' END AS FdcName,
						CASE WHEN A.Cid=0 THEN '所有币种' WHEN A.Cid=C.CId AND C.Sysrow=1 THEN '不核算' ELSE C.FullName END CidFullName
					FROM F_TreeAccount(@OperatorID,@STypeId) F
					INNER JOIN Ac_Account A ON F.Typeid=A.TypeId AND F.Stypeid=A.StypeId
					LEFT JOIN Ac_Currency C ON C.CId=A.Cid
					WHERE 
						A.ParId<>'00000'
						AND A.StypeId=@STypeId
						AND ((ISNULL(@Filter,'')='' AND ((@ParId<>'00000' AND a.TypeId LIKE @ParId+'%') OR @ParId='00000')
							OR ISNULL(@Filter,'')<>'' AND (A.UserCode LIKE '%'+@Filter+'%' OR A.FullName LIKE '%'+@Filter+'%' OR A.PyCode LIKE '%'+@Filter+'%')) )
					ORDER BY A.UserCode		
				END
		END
		ELSE 
			BEGIN
				SELECT 
					A.TypeId,
					A.ParId,
					A.UserCode,
					REPLICATE('    ',A.FLeveal-1) + A.UserCode AS FUserCode,
					A.FullName, 
					CASE WHEN A.Fdc=1 THEN '借' ELSE '贷' END AS FdcName,
					CASE WHEN A.Cid=0 THEN '所有币种' WHEN A.Cid=C.CId AND C.Sysrow=1 THEN '不核算' ELSE C.FullName END CidFullName
				FROM F_TreeAccount(@OperatorID,@STypeId) F
				INNER JOIN Ac_Account A ON F.Typeid=A.TypeId AND F.Stypeid=A.StypeId
				LEFT JOIN Ac_Currency C ON C.CId=A.Cid
				WHERE 
					A.ParId<>'00000'
					AND A.StypeId=@STypeId
					AND ((ISNULL(@Filter,'')='' AND ((@ParId<>'00000' AND a.TypeId LIKE @ParId+'%') OR @ParId='00000')
						OR ISNULL(@Filter,'')<>'' AND (A.UserCode LIKE '%'+@Filter+'%' OR A.FullName LIKE '%'+@Filter+'%' OR A.PyCode LIKE '%'+@Filter+'%')) )
				ORDER BY A.UserCode
			END
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryForPOSMultiSelector]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryForPOSMultiSelector]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	POS机（门店）多选数据
*/
CREATE	PROCEDURE Web_QueryForPOSMultiSelector
(
	@OperatorID		    VARCHAR(50),	--超作员的ID
	@Filter				VARCHAR(300)
)
AS

SET @Filter = '%'+@Filter+'%'

SELECT	pos.PosID,
		pos.UserCode,
		pos.FullName,
		pos.ktypeid,
		k.FullName AS kfullname,
		k.UserCode AS kusercode 
FROM	dbo.PosInfo pos 
LEFT JOIN dbo.Stock k ON k.typeId = pos.ktypeid
WHERE pos.[STATE] = 1 AND (pos.UserCode LIKE @Filter OR pos.FullName LIKE @Filter OR pos.PyCode LIKE @Filter)
ORDER BY pos.UserCode,pos.FullName

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryFrozeBusinessDate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryFrozeBusinessDate
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：韩林	
	日期：2013-5-24
	描述：业务冻结情况查询
*/
CREATE PROCEDURE Web_QueryFrozeBusinessDate
(
	@operatorid VARCHAR(50)
)
--@encode$--
AS
SET NOCOUNT ON

SELECT * FROM FrozeBusiness
WHERE Stypeid IN (SELECT * FROM dbo.F_GetManDetailSType(@operatorid))
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryGetDropTemplet]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryGetDropTemplet
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- =============================================
-- 作者:		glj
-- 日期:		2013-06-03
-- 返回:		得到指定类型的模板
-- =============================================
CREATE PROC [dbo].Web_QueryGetDropTemplet
(
	@Search			VARCHAR(200),		--查询条件
	@BusinessType	INT,				--业务类型 0:增加 1：减少 2.部门转移 3.计提减值准备 4.折旧
	@StypeID		VARCHAR(50)			--分支机构
) 
--@encode$--
AS
SET NOCOUNT ON 

DECLARE @BillType INT=0
IF(@BusinessType=0)
	SET @BillType=212
ELSE IF(@BusinessType=1)
	SET @BillType=213
ELSE IF(@BusinessType=2)
	SET @BillType=-1
ELSE IF(@BusinessType=3)
	SET @BillType=-2
ELSE IF(@BusinessType=4)
	SET @BillType=214
IF ISNULL(@Search,'')<>''
	SELECT 
		AtId,
		FullName 
	FROM Ac_Auditing_Template 
	WHERE  
		BillType=@BillType
		AND STypeId=@StypeID 
		AND (UserCode LIKE '%'+@Search+'%' OR FullName  LIKE '%'+@Search+'%')
ELSE 
	SELECT 
		AtId,
		FullName 
	FROM Ac_Auditing_Template 
	WHERE  
		BillType=@BillType
		AND STypeId=@StypeID 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_QueryGoodCompleteTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_QueryGoodCompleteTotal]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*	
	作者：覃雨翔
	日期：2012-06-07
	描述：商品收款结算分析9.0版本修改,添加原币 
	
	2013-03-20 周华 修改结算金额和未结算金额不对的情况
	2013-03-25 周华 修改报错
	2013-03-29 周华 修改 已结算金额与未结算金额符号问题
	2013-04-09 周华 修改 销售换货符号
*/
CREATE PROC Web_QueryGoodCompleteTotal
(
	@OperatorId		VARCHAR(100),								--超作员的ID
	@StartDate		VARCHAR(20),								--开始日期
	@EndDate			VARCHAR(20),								--结束日期
	@ETypeId			VARCHAR(8000),							--经手人ID
	@GBTypeId			VARCHAR(8000),							--往来单位的ID
	@KTypeId			VARCHAR(8000),							--仓库ID
	@PTypeId    	VARCHAR(8000),							--商品id haiquan
	@DTypeId			VARCHAR(8000),							--部门id haiquan
	@STypeId			VARCHAR(8000),							--分支机构
	@BillCode			VARCHAR(256),								--单据编号
	@QueryType		INT,												--查询的方式     0.收款单据类型		1.付款单据类型
	@BillTypeId		VARCHAR(100),								--单据类型的ID
	@OrderField		VARCHAR(100)='BillDate',		--排序的字段
	@OrderType		VARCHAR(20)='ASC',					--排序方式  1.升序  0.降序
	@CID          INT=0,											--币别选择，默认为0，表示所有币种
	@IncludeInit	INT													--是否包含期初
)
--@encode$--	
AS
BEGIN
	--------------------------------------------------------------权限检查-------------------------------------------------------

	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
				@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN 
	--------------------------------------------------------------权限检查-------------------------------------------------------

	DECLARE @SonNum 	INT,			--叶子节点数
		@PTypeMxId	VARCHAR(50),
    @PTypeIDmx  VARCHAR(50),
		@Btypeid	VARCHAR(8000),
		@SQL		VARCHAR(8000),	--SQL字符串
		@SQL1		VARCHAR(8000),	--SQL字符串 
		@chvOp		VARCHAR(10),
		@CIDWhere   VARCHAR(100)    --币别筛选


	SELECT @chvOp=''
		,@KTypeId=CASE WHEN @KTypeID IN ('00000','') THEN '%' ELSE @KTypeID END
		,@PTypeIDmx=CASE WHEN @PTypeID = '00000' THEN '%' ELSE @PTypeID END
		,@BTypeId=CASE WHEN @GBTypeId = '00000' THEN '%' ELSE @GBTypeId END
		,@DTypeId=CASE WHEN @DTypeID = '00000' THEN '%' ELSE @DTypeID END
		,@CIDWhere=CASE WHEN @CID<>0 THEN ' AND CID='+CONVERT(VARCHAR,@CID) ELSE '' END;
	SELECT @SonNum = SonNum FROM PType WHERE TypeID = @PTypeID;

	--往来单位
	CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
	INSERT INTO #GetManBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S
	INSERT INTO #GetManBTypeId(TypeId)VALUES('')
	--职员
	CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
	INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S
	--仓库
	CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
	INSERT INTO #GetManKTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S
	IF @KTypeId = '%'
		INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')
	--商品
	CREATE TABLE #ManPTypeId(TypeId	VARCHAR(100))
	INSERT INTO #ManPTypeId SELECT TypeId FROM F_GetManDetailPType(@OperatorID) WHERE TypeId LIKE @PTypeIDmx + '%'

	--分支机构
	CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
	IF NOT (@STypeId = '' AND @MSTypeId = '00000')
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	--部门
	CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
	INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	
	
	--//#BillNum
	CREATE TABLE #BillNum(BillNumberId	numeric(18,0),BillType int)
	SET @SQL = 'INSERT INTO #BillNum SELECT distinct BillNumberId,BillType FROM BillIndex ';
	IF NOT (@BTypeId='%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON BillIndex.BTypeId = B.TypeId'
	IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
		SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON BillIndex.ETypeId = E.TypeId'
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON BillIndex.STypeId = S.TypeId '	
	IF NOT (@DTypeId = '' AND @MDtypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON BillIndex.DTypeId = D.TypeId '	
			
	SET @SQL = @SQL + '
				WHERE 	BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
						AND BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
						AND (('+CAST(@IncludeInit AS VARCHAR(10))+'=0 AND draft=0 and isini=0 and ifcheck=''t'')OR('+CAST(@IncludeInit AS VARCHAR(10))+'=1 And (draft=0 OR isini=1)))
						AND preferencemoney=0
						AND totalInMoney=0
						AND RedWord = 0
						AND jsstyle <> 1 --排除按单结算
						AND jsStyle <> 3 --排除按品牌结算单价
						and isnull(ChargeOffTotal,0)=0 --排除核销过的单据
						AND BillType IN ('+@BillTypeId+')
						AND ISNULL(totalmoney, 0)-(ISNULL(totalinmoney, 0) + ISNULL(preferencemoney, 0))<>0 -- 只查需要结算的单据
						AND BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+@CIDWhere
	EXEC(@SQL)


	--发票数据
	declare @isinvoice varchar(10)
	select @isinvoice=SubValue from sysdata where SubName='IsInvoice'
	
--CREATE TABLE #BillNum1(BillNumberId	numeric(18,0),BillType int)
IF @isinvoice='1'
BEGIN            
   
	SET @SQL = 'INSERT INTO #BillNum SELECT distinct BillNumberId,BillType FROM ReceiptBillIndex ';
	IF NOT (@BTypeId='%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON ReceiptBillIndex.BTypeId = B.TypeId'
	IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
		SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON ReceiptBillIndex.ETypeId = E.TypeId'
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON ReceiptBillIndex.STypeId = S.TypeId '	
	IF NOT (@DTypeId = '' AND @MDtypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON ReceiptBillIndex.DTypeId = D.TypeId '	
			
	SET @SQL = @SQL + '
				WHERE 	BillDate>='+CHAR(39)+@StartDate+CHAR(39)+'
						AND BillDate<='+CHAR(39)+@EndDate+CHAR(39)+'
						AND (('+CAST(@IncludeInit AS VARCHAR(10))+'=0 AND draft=0 and isini=0 and ifcheck=''t'')OR('+CAST(@IncludeInit AS VARCHAR(10))+'=1 And (draft=0 OR isini=1)))
						AND RedWord = 0
						AND jsstyle <> 1 --排除按单结算
						AND jsStyle <> 3 --排除按品牌结算单价
						AND isnull(ChargeOffTotal,0)=0 --排除核销过的单据
						AND BillType IN ('+@BillTypeId+')
						AND ISNULL(totalmoney, 0)<>0 -- 只查需要结算的单据
						AND BillCode LIKE '+CHAR(39)+'%'+@BillCode+'%'+CHAR(39)+@CIDWhere
	EXEC(@SQL)
END
	--print @SQL
	--//#BillDetal
	CREATE TABLE #BillDetail
	(
	 billtype				INT,
	 pTypeId				VARCHAR(100),
	 kTypeId				VARCHAR(100),
	 Qty						 NUMERIC(24, 10) ,
	 taxTotal   		 NUMERIC(24, 10) ,
	 ntaxtotal			 NUMERIC(24, 10) ,
	 taxprice				 NUMERIC(24, 10) ,
	 ntaxprice			 NUMERIC(24, 10) ,
	 completeqty		 NUMERIC(24, 10) ,
	 
	 CompleteTotal	 NUMERIC(24, 10) ,
	 NCompleteTotal		 NUMERIC(24, 10) 
	)
	SET @BillTypeId=','+@BillTypeId+',';

	IF @QueryType = 0
	BEGIN
    INSERT  INTO #BillDetail
            SELECT  11 ,
                    S.PtypeID ,
                    S.KtypeId ,
                    SUM(S.Qty) ,
                    SUM(S.TaxTotal) ,
                    SUM(S.NTaxTotal) ,
                    SUM(S.taxPrice) ,
                    SUM(S.NtaxPrice) ,
                    SUM(S.CompleteQTY),
                    SUM(s.CompleteTotal), --,SUM(completeqty*taxprice)
                    SUM(s.NCompleteTotal)
            FROM    SaleBill S
          /*  LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillNum
                                      WHERE     BillType = 11 )	    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    s.KTypeID
	
    INSERT  INTO #BillDetail
            SELECT  45 ,
                    s.PtypeID ,
                    s.KtypeId ,
                    -SUM(s.Qty) ,
                    -SUM(s.TaxTotal) ,
                    -SUM(s.NTaxTotal) ,
                    SUM(s.taxPrice) ,
                    SUM(s.NtaxPrice) ,
                    -SUM(s.CompleteQTY),
                    -SUM(s.CompleteTotal), --,SUM(completeqty*taxprice)
                    -SUM(s.NCompleteTotal)
            FROM    salebackbill s
            /*LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillNum
                                      WHERE     BillType = 45 )	   AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    s.KTypeID
                    
    /*INSERT  INTO #BillDetail
            SELECT  215 ,
                    s.PtypeID ,
                    b.KtypeId ,
                    -SUM(s.Qty) ,
                    -SUM(s.TaxTotal) ,
                    -SUM(s.NTaxTotal) ,
                    SUM(s.taxPrice) ,
                    SUM(s.NtaxPrice) ,
                    -SUM(s.CompleteQTY),
                    -SUM(s.CompleteTotal), --,SUM(completeqty*taxprice)
                    -SUM(s.NCompleteTotal)
                    
            FROM    RetailBackBill s 
            inner join BillIndex b on s.BillNumberId=b.BillNumberId
            LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND t.GoodsBillID = s.BillNumberId
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillNum
                                      WHERE     BillType = 215 )     AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    b.KTypeID*/
	
    INSERT  INTO #BillDetail
            SELECT  160 ,-- 销售换货单
					s.PtypeID ,
                    s.KtypeId ,
					CASE s.InOrOut WHEN 'O' THEN SUM(s.Qty)				WHEN 'I' THEN SUM(-s.Qty) END,
                    CASE s.InOrOut WHEN 'O' THEN SUM(s.TaxTotal)		WHEN 'I' THEN SUM(-s.TaxTotal)	 END,
                    CASE s.InOrOut WHEN 'O' THEN SUM(s.NTaxTotal)		WHEN 'I' THEN SUM(-s.NTaxTotal)	END	,
                    CASE s.InOrOut WHEN 'O' THEN SUM(s.taxPrice)		WHEN 'I' THEN SUM(s.taxPrice)		END,
                    CASE s.InOrOut WHEN 'O' THEN SUM(s.NtaxPrice)		WHEN 'I' THEN SUM(s.NtaxPrice)	END,
                    CASE s.InOrOut WHEN 'O' THEN SUM(s.CompleteQTY) WHEN 'I' THEN SUM(-s.CompleteQTY) END,
                    CASE s.InOrOut WHEN 'O' THEN SUM(s.CompleteTotal) WHEN 'I' THEN SUM(-s.CompleteTotal) END,
                    CASE s.InOrOut WHEN 'O' THEN SUM(s.nCompleteTotal) WHEN 'I' THEN SUM(-s.nCompleteTotal) END 
            FROM    SaleGoodsExchangeBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND t.GoodsBillID = s.BillNumberId*/
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                          FROM      #BillNum
                                          WHERE     BillType = 160 )	  AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    s.KTypeID,
                    s.InOrOut

    INSERT  INTO #BillDetail
            SELECT  141 ,
                    s.ptypeid ,
                    '10000' ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    CommissionBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid, GoodsBillID,SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE   s.Type = 141
                    AND s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillNum
                                            WHERE   BillType = 141 )	  AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId 
            

            
            
			INSERT  INTO #BillDetail
            SELECT  405 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    ReceiptBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid, GoodsBillID,SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillNum
                                            WHERE   BillType = 405 )	  
            GROUP BY s.PtypeId ,s.KTypeID  
            
            INSERT  INTO #BillDetail
            SELECT  12 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM   dbo.PT_Combin_SaleBill s
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillNum
                                            WHERE   BillType = 12 )	    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,s.KTypeID  
            
            
             INSERT  INTO #BillDetail
            SELECT  46 ,
                    s.PtypeID ,
                    s.KtypeId ,
                    -SUM(s.Qty) ,
                    -SUM(s.TaxTotal) ,
                    -SUM(s.NTaxTotal) ,
                    SUM(s.taxPrice) ,
                    SUM(s.NtaxPrice) ,
                    -SUM(s.CompleteQTY),
                    -SUM(s.CompleteTotal), --,SUM(completeqty*taxprice)
                    -SUM(s.NCompleteTotal)
            FROM    dbo.PT_Combin_SaleBackBill s
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillNum
                                      WHERE     BillType = 46 )	   AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    s.KTypeID  
                    
                    
                    
                  --  SELECT * FROM    #BillDetail 
	END
	
	--付款结算
	IF @QueryType = 1
	BEGIN
		--采购入库
    INSERT  INTO #BillDetail
            SELECT  34 ,
                    s.PtypeId ,
                    s.KTypeID ,
                    SUM(s.Qty) ,
                    SUM(s.TaxTotal) ,
                    SUM(s.NTaxTotal) ,
                    SUM(s.taxPrice) ,
                    SUM(s.NtaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    buybill s
          /*  LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND t.GoodsBillID = s.BillNumberId*/
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillNum
                                      WHERE     BillType = 34 )	     AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    s.KTypeID
	
		--委托代销
    INSERT  INTO #BillDetail
            SELECT  145 ,
                    s.ptypeid ,
                    '10000' ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NtaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    CommissionBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND t.GoodsBillID = s.BillNumberId*/
            WHERE   s.Type = 145
                    AND s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillNum
                                            WHERE   BillType = 145 )	  AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId 

		--
    INSERT  INTO #BillDetail
            SELECT  6 ,
                    s.PtypeId ,
                    s.KTypeID ,
                    -SUM(s.Qty) ,
                    -SUM(s.TaxTotal) ,
                    -SUM(s.NTaxTotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    -SUM(s.CompleteQTY),
                    -SUM(s.CompleteTotal),
                    -SUM(s.NCompleteTotal)
            FROM    dbo.BuyBackBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillNum
                                      WHERE     BillType = 6 )     AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    s.KTypeID
		
		
    INSERT  INTO #BillDetail
            SELECT  161 , --采购换货单
                    s.PtypeId ,
                    s.KTypeID ,
					CASE InOrOut WHEN 'O' THEN SUM(-Qty)					WHEN 'I' THEN SUM(Qty) END,
                    CASE InOrOut WHEN 'O' THEN SUM(-TaxTotal)		WHEN 'I' THEN SUM(TaxTotal)	 END,
                    CASE InOrOut WHEN 'O' THEN SUM(-NTaxTotal)		WHEN 'I' THEN SUM(NTaxTotal)	END	,
                    CASE InOrOut WHEN 'O' THEN SUM(taxPrice)		WHEN 'I' THEN SUM(taxPrice)		END,
                    CASE InOrOut WHEN 'O' THEN SUM(NtaxPrice)		WHEN 'I' THEN SUM(NtaxPrice)	END,
                    CASE InOrOut WHEN 'O' THEN SUM(-CompleteQTY) WHEN 'I' THEN SUM(CompleteQTY) END
                    ,CASE InOrOut WHEN 'O' THEN SUM(-CompleteTotal) WHEN 'I' THEN SUM(CompleteTotal) END
                    ,CASE InOrOut WHEN 'O' THEN SUM(-NCompleteTotal) WHEN 'I' THEN SUM(NCompleteTotal) END
            FROM    BuyGoodsExchangeBill s
          /*  LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                          FROM      #BillNum
                                          WHERE     BillType = 161 )     AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    s.KTypeID,
                    s.InOrOut
            
            --采购发票        
            INSERT  INTO #BillDetail
            SELECT  404 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    ReceiptBill s
            /*LEFT JOIN
            (
				SELECT PtypeID,Billid, GoodsBillID,SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillNum
                                            WHERE   BillType = 404 )	  
            GROUP BY s.PtypeId, s.KTypeID        
		
	END
	
	--//select
	SET @SQL1='SELECT p.TypeId,MAX(P.UserCode) AS UserCode,Max(P.FullName) AS FullName,Max(P.Sonnum) AS Sonnum,
				   			ISNULL(SUM(bill.qty),0)  AS QTY,
						    ISNULL(SUM(completeqty),0) AS CompleteGoodQty,
						    ISNULL(SUM(bill.qty),0)-ISNULL(SUM(completeqty),0) as UnCompleteGoodQTY,
						    ISNULL(SUM(round(bill.TaxTotal,2)),0)  AS Total,
							ISNULL(SUM(round(bill.NTaxTotal,2)),0) as NTotal,
						    --ISNULL(SUM(bill.CompleteQTY*bill.taxprice),0) AS CompleteTotal,
						    --ISNULL(SUM(bill.CompleteQTY*bill.ntaxprice),0) AS NCompleteTotal,
						    isnull(sum(bill.CompleteTotal),0) as CompleteTotal,
						    isnull(sum(bill.NCompleteTotal),0) as NCompleteTotal,
						    ISNULL(SUM(round(bill.TaxTotal,2)),0)-sum(isnull(bill.CompleteTotal,0)) AS UnCompleteTotal,
						    ISNULL(SUM(round(bill.NTaxTotal,2)),0)-sum(isnull(bill.NCompleteTotal,0)) AS NUnCompleteTotal
				FROM F_GetManPTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') P
				LEFT JOIN (
								SELECT B.* FROM #BillDetail B 
								JOIN #ManPTypeId M ON B.Ptypeid=M.TypeId '
								+ CASE WHEN NOT (@KTypeId = '%' AND @MKTypeId = '00000') THEN ' JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId ' ELSE '' END
								+ ' WHERE B.NTaxTotal<>0 
							) bill ON bill.PTypeId LIKE P.TypeId+''%''
						
					';
	SET @SQL1=@SQL1+' WHERE '+ CASE WHEN  @SonNum > 0 THEN ' p.ParID = ''' ELSE ' p.TypeID =''' END +@PTypeID+''''
	+'	AND p.TypeId <> ''00000''    -- AND p.iscombinationproduct = 0 				
	 ' --+case when @QueryType=1 then ' AND p.iscombinationproduct = 0 ' else '  ' end 
	+' GROUP BY p.Typeid,p.SortID
		ORDER BY p.SortID';
	
	--PRINT(@SQL1)
	EXEC(@SQL1)

	DROP TABLE #BillDetail,#BillNum,#ManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManSTypeId,#GetManDTypeId

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_QueryGoodCompleteTotalBill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_QueryGoodCompleteTotalBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：HAIQUAN
	日期：2007-4-16
	描述：查询按SHANGPIN结算的单据
	
	作者：覃雨翔
	日期：2012-06-08
	描述：查询按商品结算的单据，9.0版本修改
	
	By: Haiyang, Li
	Date: 2012-11-16
	Description: 调整查询逻辑, 优化查询效率
	
	2013-03-20 周华 修改 @billCode转化出错问题
					修改 @cid条件不起作用问题
					
	2013-03-26 周华 修改 @billCode条件不起作用问题
	2013-03-29 周华 修改 已结算金额与未结算金额符号问题
	2013-04-07 周华 修改 把0单价的修改得统一，与汇总列表相同
	2013-04-09 周华 修改 销售换货两个符号。
	
	修改：舒珊
	日期：2016年2月25日
	描述：增添表头自定义显示字段
 */
CREATE PROCEDURE Web_QueryGoodCompleteTotalBill
(
	@OperatorId		VARCHAR(50),							--超作员的ID 
	@StartDate		VARCHAR(20),							--开始日期
	@EndDate			VARCHAR(20),							--结束日期
	@ETypeId			VARCHAR(8000),						--经手人ID
	@GBTypeId			VARCHAR(8000),						--往来单位的ID
	@KTypeId			VARCHAR(8000),						--仓库ID
	@PTypeId      VARCHAR(8000),						--商品id haiquan
	@DTypeId			VARCHAR(8000),						--部门id haiquan
	@STypeId			VARCHAR(8000),						--分支机构
	@BillCode			VARCHAR(256),							--单据编号
	@QueryType		INT,											--查询的方式     0.收款单据类型		1.付款单据类型
	@BillTypeId		VARCHAR(100),							--单据类型的ID
	@OrderField		VARCHAR(100)='BillDate',	--排序的字段
	@OrderType		VARCHAR(20)='ASC',				--排序方式  1.升序  0.降序
	@CID          INT=0,										--币别选择，默认为0，表示所有币种
	@IncludeInit	INT												--是否包含期初
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL 
    RETURN 1
DECLARE @Re INT ,
    @MAtypeid VARCHAR(50) ,
    @MBtypeid VARCHAR(50) ,
    @MBtypeid2 VARCHAR(50) ,
    @MEtypeid VARCHAR(50) ,
    @MKtypeid VARCHAR(50) ,
    @MPtypeid VARCHAR(50) ,
    @MExpense VARCHAR(50) ,
    @MIncome	VARCHAR(50) ,
    @MCapital VARCHAR(50) ,
    @MDtypeid VARCHAR(50) ,
    @MStypeid VARCHAR(50)
EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
    @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT, @MKtypeid OUTPUT,
    @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT, @MCapital OUTPUT,
    @MDtypeid OUTPUT, @MStypeid OUTPUT
IF @Re <> 0 
    RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
----------------------

DECLARE @PTypeMxId	VARCHAR(100),
		@Btypeid	VARCHAR(50),
		@SQL		NVARCHAR(MAX),	--SQL字符串
		@SQL1		VARCHAR(MAX)	--SQL字符串


IF @KTypeID = '00000' OR @KTypeId = ''
	SELECT @KTypeId = '%'
ELSE
	SELECT @KTypeId = @KTypeID


IF @PTypeID = '00000'
	SELECT @PTypeMxId = '%'
ELSE
	SELECT @PTypeMxId = @PTypeID

IF @GBTypeId = '00000'
	SET @BTypeId = '%'
ELSE
	SET @BTypeId = @GBTypeId

IF @DTypeID = '00000'
	SELECT @DTypeId = '%'

----------------生成权限临时表-----------------------------------
--往来单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S
INSERT INTO #GetManBTypeId(TypeId)VALUES('')

--职员
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S

--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S
IF @KTypeId = '%'
	INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	

CREATE TABLE #ManPTypeId(TypeId	VARCHAR(100))
INSERT INTO #ManPTypeId SELECT TypeId FROM F_GetManDetailPType(@OperatorID) WHERE TypeId LIKE @PTypeMxId + '%'

CREATE TABLE #Result
(
	BillNumberId				NUMERIC(18, 0),
	billtype					int,
	Qty									 NUMERIC(24, 10) ,
	CompleteGoodQty			 NUMERIC(24, 10) ,
	UnCompleteGoodQty		 NUMERIC(24, 10) ,
	TotalMoney					 NUMERIC(24, 10) ,
	NTotalMoney					 NUMERIC(24, 10) ,
	TotalJsMoney				 NUMERIC(24, 10) ,
	NTotalJsMoney				 NUMERIC(24, 10) ,
	TotalWjsMoney				 NUMERIC(24, 10) ,
	NTotalWjsMoney			 NUMERIC(24, 10) 
)

CREATE TABLE #BillIndex
(
	 BillNumberId		numeric(18,0),
	 BillType			INT,
     BillDate			datetime,
     posttime			datetime,
     BillCode			varchar(200),
	 Comment				varchar(256),
	 ETypeId				varchar(50),
	 BTypeId				varchar(50),
	 STypeId			varchar(50),
	 cid			int
)

--表体明细
CREATE TABLE #BillDetail
(
 BillNumberId NUMERIC(18, 0),
 billtype  int,
 pTypeId   VARCHAR(100),
 kTypeId   VARCHAR(100),
 Qty     NUMERIC(24, 10) ,
 taxTotal    NUMERIC(24, 10) ,
 ntaxtotal    NUMERIC(24, 10) ,
 taxprice    NUMERIC(24, 10) ,
 ntaxprice    NUMERIC(24, 10) ,
 completeqty    NUMERIC(24, 10) ,
 completeTotal  NUMERIC(24, 10) ,
 ncompleteTotal  NUMERIC(24, 10) 
) 


--取表体
SET @SQL = 'INSERT INTO #BillIndex
			SELECT BI.BillNumberId, BI.BillType,bi.billdate,bi.posttime,bi.billcode,bi.comment,bi.etypeid,bi.btypeid,bi.stypeid,bi.cid
			FROM 	BillIndex BI'

IF NOT (@BTypeId='%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON Bi.BTypeId = B.TypeId'

IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
	SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON Bi.ETypeId = E.TypeId'

--IF NOT (@KTypeId = '%' AND @MKTypeId = '00000')
	--SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = I.KTypeId '
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '
	
IF NOT (@DTypeId = '' AND @MDtypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON Bi.DTypeId = D.TypeId '

SET @SQL = @SQL 
			+ ' WHERE BI.BillDate >= @StartDate
					AND BI.BillDate <= @EndDate'
					+ CASE @QueryType
					WHEN 0
					THEN ' AND BI.BillType IN (11,45,160,141,215,12,46) '
					WHEN 1
					THEN ' AND BI.BillType IN (34,6,145,161) '
					END
					+ ' AND BI.RedWord = 0
					AND ((@IncludeInit=0 AND draft=0 and isini=0 and ifcheck=''t'')OR(@IncludeInit=1 And (draft=0 OR isini=1)))
					AND BI.preferencemoney=0
					AND BI.totalInMoney=0
					and isnull(bi.ChargeOffTotal,0)=0 --排除核销过的单据
					AND BI.jsstyle <> 1 
					AND BI.jsstyle <> 3
					AND ISNULL(Bi.totalmoney, 0)-(ISNULL(Bi.totalinmoney, 0) + ISNULL(Bi.preferencemoney, 0))<>0 '
					+ CASE @BillCode
            WHEN ''
            THEN ''
            ELSE ' AND Bi.BillCode LIKE ''%''+@BillCode+''%'''
          END
          + CASE @CID
            WHEN 0
            THEN ''
            ELSE ' AND Bi.CID=@CID'
          END

 EXEC sp_executesql @SQL, N'@StartDate nvarchar(20),@EndDate nvarchar(20),@BillTypeId nvarchar(100), @IncludeInit INT, @BillCode NVARCHAR(256), @CID INT' 
 ,@StartDate,@EndDate,@BillTypeId,@IncludeInit,@BillCode,@CID
 
 
 	--发票数据
	declare @isinvoice varchar(10)
	select @isinvoice=SubValue from sysdata where SubName='IsInvoice'
	
--CREATE TABLE #BillNum1(BillNumberId	numeric(18,0),BillType int)
IF @isinvoice='1'
BEGIN 
   --取表体
	SET @SQL = 'INSERT INTO #BillIndex
				SELECT BI.BillNumberId, BI.BillType,bi.billdate,bi.posttime,bi.billcode,bi.comment,bi.etypeid,bi.btypeid,bi.stypeid,bi.cid
				FROM 	ReceiptBillIndex BI'

	IF NOT (@BTypeId='%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON Bi.BTypeId = B.TypeId'

	IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
		SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON Bi.ETypeId = E.TypeId'

	--IF NOT (@KTypeId = '%' AND @MKTypeId = '00000')
		--SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = I.KTypeId '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '
		
	IF NOT (@DTypeId = '' AND @MDtypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON Bi.DTypeId = D.TypeId '

	SET @SQL = @SQL 
				+ ' WHERE BI.BillDate >= @StartDate
						AND BI.BillDate <= @EndDate'
						+ CASE @QueryType
						WHEN 0
						THEN ' AND BI.BillType IN (405) '
						WHEN 1
						THEN ' AND BI.BillType IN (404) '
						END
						+ ' AND BI.RedWord = 0
						AND ((@IncludeInit=0 AND draft=0 and isini=0 and ifcheck=''t'')OR(@IncludeInit=1 And (draft=0 OR isini=1)))
						AND BI.jsstyle <> 1
						AND BI.jsstyle <> 3
						and isnull(bi.ChargeOffTotal,0)=0 --排除核销过的单据
						AND ISNULL(Bi.totalmoney, 0)<>0 '
						+ CASE @BillCode
				WHEN ''
				THEN ''
				ELSE ' AND Bi.BillCode LIKE ''%''+@BillCode+''%'''
			  END
			  + CASE @CID
				WHEN 0
				THEN ''
				ELSE ' AND Bi.CID=@CID'
			  END

	 EXEC sp_executesql @SQL, N'@StartDate nvarchar(20),@EndDate nvarchar(20),@BillTypeId nvarchar(100), @IncludeInit INT, @BillCode NVARCHAR(256), @CID INT' 
	 ,@StartDate,@EndDate,@BillTypeId,@IncludeInit,@BillCode,@CID

END

----------------------------------------------------------------
-- 明细汇总
IF @QueryType = 0
	BEGIN
    INSERT  INTO #BillDetail
            SELECT  BillNumberId,
					11 , --销售出库单
                    S.PtypeId ,
                    KtypeId ,
                    SUM(Qty) ,
                    SUM(TaxTotal) ,
                    SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    ISNULL (sum(CompleteQTY),0),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    SaleBill s
           /* LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 11 )
                    --AND (@PTypeMxId = '' OR @PTypeMxId = '%') AND PtypeId = @PTypeMxId
            GROUP BY BillNumberId, s.PtypeId , KTypeID
	
    INSERT  INTO #BillDetail
            SELECT  BillNumberId,
										45 , --销售退货单
                    S.PtypeId ,
                    KtypeId ,
                    -SUM(Qty) ,
                    -SUM(TaxTotal) ,
                    -SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    -ISNULL (sum(CompleteQTY),0),
                     -SUM(s.CompleteTotal),
                   - SUM(s.NCompleteTotal)
            FROM    Salebackbill S
          /*  LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 45 )
                   -- AND (@PTypeMxId = '' OR @PTypeMxId = '%') AND PtypeId = @PTypeMxId
            GROUP BY BillNumberId, S.PtypeId , KTypeID
	
	/*INSERT  INTO #BillDetail
            SELECT  S.BillNumberId,
										215 , --零售退货单
                    S.PtypeID ,
                    KtypeId ,
                    -SUM(Qty) ,
                    -SUM(TaxTotal) ,
                    -SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    -SUM(CompleteQTY),
                    SUM(T.CompleteGoodTotal),
                    SUM(T.NCompleteGoodTotal)
            FROM    RetailBackBill S inner join BillIndex b on S.BillNumberId=b.BillNumberId
            LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId
            WHERE   S.BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 215 )
            GROUP BY S.BillNumberId, S.PtypeId , KTypeID*/
	
    INSERT  INTO #BillDetail
            SELECT  BillNumberId,
										160 , --销售换货单
                    S.PtypeId ,
                    KtypeId ,
										CASE InOrOut WHEN 'O' THEN SUM(Qty)					WHEN 'I' THEN SUM(-Qty) END,
                    CASE InOrOut WHEN 'O' THEN SUM(TaxTotal)		WHEN 'I' THEN SUM(-TaxTotal)	 END,
                    CASE InOrOut WHEN 'O' THEN SUM(NTaxTotal)		WHEN 'I' THEN SUM(-NTaxTotal)	END	,
                    CASE InOrOut WHEN 'O' THEN SUM(taxPrice)		WHEN 'I' THEN SUM(taxPrice)		END,
                    CASE InOrOut WHEN 'O' THEN SUM(NtaxPrice)		WHEN 'I' THEN SUM(NtaxPrice)	END,
                    CASE InOrOut WHEN 'O' THEN SUM(CompleteQTY) WHEN 'I' THEN SUM(-CompleteQTY) END,
                    CASE InOrOut WHEN 'O' THEN SUM(CompleteTotal)		WHEN 'I' THEN  SUM(-CompleteTotal)	 END AS CompleteTotal ,
					CASE InOrOut WHEN 'O' THEN SUM(NCompleteTotal)		WHEN 'I' THEN  SUM(-NCompleteTotal) END AS NCompleteTotal 
            FROM    SaleGoodsExchangeBill S
          /*  LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                          FROM      #BillIndex
                                          WHERE     BillType = 160 )
                                          
            GROUP BY BillNumberId, S.PtypeId , KTypeID, InOrOut

    INSERT  INTO #BillDetail
            SELECT  BillNumberId,
					141 , --委托代销结算单
                    S.PtypeId ,
                    '10000' ,
                    SUM(qty) ,
                    SUM(taxtotal) ,
                    SUM(ntaxtotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    SUM(CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    CommissionBill  S
            /*LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 141 )
                    --AND (@PTypeMxId = '' OR @PTypeMxId = '%') AND A.PtypeId = @PTypeMxId
            GROUP BY BillNumberId, S.PtypeId
            
            
            
                   
			INSERT  INTO #BillDetail
            SELECT  BillNumberId,
					405 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    ReceiptBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid, GoodsBillID,SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 405 )	  
            GROUP BY s.PtypeId,s.BillNumberID,s.KTypeID   
            
            
            INSERT  INTO #BillDetail
            SELECT  BillNumberId,
					12 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    dbo.PT_Combin_SaleBill s
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 12 )	  
            GROUP BY s.PtypeId,s.BillNumberID,s.KTypeID     
            
            INSERT  INTO #BillDetail
            SELECT  BillNumberId,
					46 , --组合品销售退货单
                    S.PtypeId ,
                    KtypeId ,
                    -SUM(Qty) ,
                    -SUM(TaxTotal) ,
                    -SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    -SUM(CompleteQTY),
                    -SUM(s.CompleteTotal),
                    - SUM(s.NCompleteTotal)
            FROM    dbo.PT_Combin_SaleBackBill S
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 46 )
                   -- AND (@PTypeMxId = '' OR @PTypeMxId = '%') AND PtypeId = @PTypeMxId
            GROUP BY BillNumberId, S.PtypeId , KTypeID
              
	END
--付款结算
IF @QueryType = 1
	BEGIN

    INSERT  INTO #BillDetail
            SELECT  BillNumberId,
										34 , 		--采购入库
                    S.PtypeId ,
                    KtypeId ,
                    SUM(Qty) ,
                    SUM(TaxTotal) ,
                    SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    SUM(CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    BuyBill S
            /*LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 34 )
                    --AND (@PTypeMxId = '' OR @PTypeMxId = '%') AND PtypeId = @PTypeMxId
            GROUP BY BillNumberId, S.PtypeId , KTypeID
	
		
    INSERT  INTO #BillDetail
            SELECT  BillNumberId,
										145 , --委托代销
                    S.PtypeId ,
                    '10000' ,
                    SUM(qty) ,
                    SUM(taxtotal) ,
                    SUM(ntaxtotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    SUM(CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    CommissionBill S
           /* LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   Type = 145 
							AND	BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 145 )
                    --AND (@PTypeMxId = '' OR @PTypeMxId = '%') AND A.PtypeId = @PTypeMxId
           GROUP BY BillNumberId, S.PtypeId

    INSERT  INTO #BillDetail
            SELECT  BillNumberId,
					6 , -- 采购退货单
                    S.PtypeId ,
                    KtypeId ,
                    -SUM(Qty) ,
                    -SUM(TaxTotal) ,
                    -SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    -SUM(CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    dbo.BuyBackBill S
            /*LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 6 )
                    --AND (@PTypeMxId = '' OR @PTypeMxId = '%') AND PtypeId = @PTypeMxId
           GROUP BY BillNumberId, S.PtypeId , KTypeID
		
		
    INSERT  INTO #BillDetail
            SELECT  BillNumberId,
										161 , -- 采购换货单
                    S.PtypeId ,
                    KtypeId ,
										CASE InOrOut WHEN 'O' THEN SUM(-Qty)					WHEN 'I' THEN SUM(Qty) END,
                    CASE InOrOut WHEN 'O' THEN SUM(-TaxTotal)		WHEN 'I' THEN SUM(TaxTotal)	 END,
                    CASE InOrOut WHEN 'O' THEN SUM(-NTaxTotal)		WHEN 'I' THEN SUM(NTaxTotal)	END	,
                    CASE InOrOut WHEN 'O' THEN SUM(taxPrice)		WHEN 'I' THEN SUM(taxPrice)		END,
                    CASE InOrOut WHEN 'O' THEN SUM(NtaxPrice)		WHEN 'I' THEN SUM(NtaxPrice)	END,
                    CASE InOrOut WHEN 'O' THEN SUM(-CompleteQTY) WHEN 'I' THEN SUM(CompleteQTY) END,
                    CASE InOrOut WHEN 'O' THEN SUM(-CompleteTotal)		WHEN 'I' THEN  SUM(CompleteTotal)	 END AS CompleteTotal ,
					CASE InOrOut WHEN 'O' THEN SUM(-NCompleteTotal)		WHEN 'I' THEN  SUM(NCompleteTotal) END AS NCompleteTotal 

            FROM    BuyGoodsExchangeBill S
          /*  LEFT JOIN
            (
				SELECT GoodsBillID,PtypeID,Billid, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                          FROM      #BillIndex
                                          WHERE     BillType = 161 )
           GROUP BY BillNumberId, S.PtypeId , KTypeID, InOrOut
           
           
            --采购发票        
            INSERT  INTO #BillDetail
            SELECT  BillNumberId,
					404 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    ReceiptBill s
            /*LEFT JOIN
            (
				SELECT PtypeID,Billid, GoodsBillID,SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 404 )	  
            GROUP BY s.PtypeId,s.BillNumberId ,s.KTypeID      
		
		
	END

----------------------------------------------------------------
--过滤商品和仓库
IF (@KTypeId = '' or @KTypeId='%') AND @MKTypeId = '00000' 
BEGIN
	INSERT  INTO #Result
					SELECT  BD.BillNumberId ,
							bd.billtype,
									SUM(BD.qty) AS QTY ,
									SUM(BD.CompleteQTY) AS CompleteGoodQTY ,
									SUM(BD.qty - BD.CompleteQTY) AS UnCompleteGoodQTY ,
									SUM(BD.TaxTotal) AS TotalMoney ,
									SUM(BD.NTaxTotal) AS NTotalMoney ,
									SUM(BD.Completetotal) AS TotalJsMoney ,
									SUM(BD.NCompletetotal) AS NTotalJsMoney ,
									SUM(BD.TaxTotal - ISNULL(BD.CompleteTotal,0)) AS TotalWjsMoney ,
									SUM(BD.NTaxTotal - ISNULL(BD.NCompleteTotal,0)) AS NTotalWjsMoney
					FROM    #BillDetail BD
									INNER JOIN #ManPTypeId P ON P.TypeId = BD.PTypeId
									
					WHERE bd.ntaxtotal<>0
					GROUP BY BD.billnumberid,bd.billtype
END
ELSE
BEGIN
	INSERT  INTO #Result
					SELECT  BD.BillNumberId ,
								bd.billtype,
									SUM(BD.qty) AS QTY ,
									SUM(BD.CompleteQTY) AS CompleteGoodQTY ,
									SUM(BD.qty - BD.CompleteQTY) AS UnCompleteGoodQTY ,
									SUM(BD.TaxTotal) AS TotalMoney ,
									SUM(BD.NTaxTotal) AS NTotalMoney ,
									SUM(BD.Completetotal) AS TotalJsMoney ,
									SUM(BD.NCompletetotal) AS NTotalJsMoney ,
									SUM(BD.TaxTotal - ISNULL(BD.CompleteTotal,0)) AS TotalWjsMoney ,
									SUM(BD.NTaxTotal - ISNULL(BD.NCompleteTotal,0)) AS NTotalWjsMoney
					FROM    #BillDetail BD
									INNER JOIN #ManPTypeId P ON P.TypeId = BD.PTypeId
									INNER JOIN #GetManKTypeId K ON K.TypeId = BD.KTypeId 
					WHERE bd.ntaxtotal<>0
					GROUP BY BD.billnumberid,bd.billtype
END

--出结果集

SELECT  BI.BillNumberId ,
        BI.BillDate ,
        BI.posttime ,
        BI.BillCode ,
        BI.BillType ,
		BI.Comment,
        BI.ETypeId ,
        BI.BTypeId ,
        BI.STypeId ,
        re.Qty ,
        re.CompleteGoodQty ,
        re. UnCompleteGoodQty ,
        RE.TotalMoney ,
        RE.NTotalMoney ,
        RE.TotalJsMoney ,
        RE.NTotalJsMoney ,
        RE.TotalWjsMoney ,
        RE.NTotalWjsMoney ,
        AC.fullname AS cfullname ,
        AC.rate,
        SysDiy1_head,
		SysDiy2_head,
		SysDiy3_head,
		SysDiy4_head, 
		SysDiy5_head,
		SysDiy6_head,
		SysDiy7_head,
		SysDiy8_head,
		SysDiy9_head,
		SysDiy10_head,
		SysDiy11_head,
		SysDiy12_head,
		SysDiy13_head,
		SysDiy14_head,
		SysDiy15_head,
		SysDiy16_head,
		SysDiy17_head,
		SysDiy18_head,
		SysDiy19_head,
		SysDiy20_head,
		SysDiy21_head,
		SysDiy22_head,
		SysDiy23_head,
		SysDiy24_head,
		SysDiy25_head,
		SysDiy26_head,
		SysDiy27_head,
		SysDiy28_head,
		SysDiy29_head,
		SysDiy30_head,
		SysDiy31_head,
		SysDiy32_head
FROM    #Result RE
        INNER JOIN #BillIndex BI ON RE.billnumberid = BI.billnumberid and re.billtype=bi.billtype
        LEFT JOIN Custom_BillIndex csindex on BI.billnumberid=csindex.BillId and BI.billtype=csindex.billtype 
        INNER JOIN AC_Currency AC ON BI.CID = AC.CID


DROP TABLE #BillDetail,#BillIndex,#ManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManSTypeId,#GetManDTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryGoodCompleteTotalLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryGoodCompleteTotalLine]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：HAIQUAN
	日期：2007-4-18
	描述：按商品结算统计
	
	作者：覃雨翔
	日期：2012-06-08
	描述：按商品结算统计,9.0版本
	
	2013-03-20 周华 修改@billCode转化成整数Bug
					修改 @cid条件不起作用问题
	2013-03-22 周华 修改@billcode条件不起作用问题
	2013-04-09 周华 修改已结算，未结算金额
*/
CREATE  PROCEDURE Web_QueryGoodCompleteTotalLine
(
	@OperatorId		VARCHAR(50),				--超作员的ID
	@StartDate		VARCHAR(20),				--开始日期
	@EndDate		VARCHAR(20),				--结束日期
	@ETypeId		VARCHAR(8000),				--经手人ID
	@GBTypeId		VARCHAR(8000),				--往来单位的ID
	@KTypeId		VARCHAR(8000),				--仓库ID
	@PTypeId        VARCHAR(8000),				--商品id haiquan
	@DTypeId		VARCHAR(8000),				--部门id haiquan
	@STypeId		VARCHAR(8000),				--分支机构
	@BillCode		VARCHAR(256),				--单据编号
	@QueryType			INT,						--查询的方式     0.收款单据类型		1.付款单据类型
	@BillTypeId		VARCHAR(100),				--单据类型的ID
	@OrderField		VARCHAR(100)='BillDate',	--排序的字段
	@OrderType		VARCHAR(20)='ASC',			--排序方式  1.升序  0.降序
	@PUserCode		VARCHAR(50)='',
	@PFullName		VARCHAR(200)='',
	@CID            INT=0,                      --币别选择，默认为0表示所有币种
	@IncludeInit	INT							--是否包含期初
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL 
    RETURN 1
DECLARE @Re INT ,
    @MAtypeid VARCHAR(50) ,
    @MBtypeid VARCHAR(50) ,
    @MBtypeid2 VARCHAR(50) ,
    @MEtypeid VARCHAR(50) ,
    @MKtypeid VARCHAR(50) ,
    @MPtypeid VARCHAR(50) ,
    @MExpense VARCHAR(50) ,
    @MIncome VARCHAR(50) ,
    @MCapital VARCHAR(50) ,
    @MDtypeid VARCHAR(50) ,
    @MStypeid VARCHAR(50)
EXEC @Re= GP_CheckOperatorRight23_Rep @OperatorID, @MAtypeid OUTPUT,
    @MBtypeid OUTPUT, @MBtypeid2 OUTPUT, @MEtypeid OUTPUT, @MKtypeid OUTPUT,
    @MPtypeid OUTPUT, @MExpense OUTPUT, @MIncome OUTPUT, @MCapital OUTPUT,
    @MDtypeid OUTPUT, @MStypeid OUTPUT
IF @Re <> 0 
    RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
----------------------





DECLARE @SonNum INT ,			--叶子节点数
    @PTypeMxId VARCHAR(50) ,
    @PTypeIDmx VARCHAR(50) ,
    @Btypeid VARCHAR(8000) ,
    @SQL NVARCHAR(MAX) ,	--SQL字符串
    @CIDWhere VARCHAR(MAX)    --币别筛选

IF @CID<>0
  BEGIN
       SET @CIDWhere=' AND CID='+CONVERT(VARCHAR,@CID)
  END
ELSE
  BEGIN
       SET @CIDWhere=''
  END





IF @KTypeID = '00000' OR @KTypeId = ''
	SELECT @KTypeId = '%'
ELSE
	SELECT @KTypeId = @KTypeID

IF @PTypeID = '00000'
	BEGIN
		SELECT @PTypeIDmx = '%'
		IF @MPTypeId <> ''
			SELECT @PTypeId = @MPTypeId
	END
ELSE
	SELECT @PTypeIDmx = @PTypeID

SELECT @SonNum = SonNum FROM PType WHERE TypeID = @PTypeID


IF @GBTypeId = '00000'
	SET @BTypeId = '%'
ELSE
	SET @BTypeId = @GBTypeId

IF @DTypeID = '00000'
	SELECT @DTypeId = '%'

/*缩小对应的Bill表*/

----------------付款查询-----------------------------------
--往来单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID) S
INSERT INTO #GetManBTypeId(TypeId)VALUES('')



--职员
CREATE TABLE #GetManETypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManETypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@ETypeId,3,@OperatorID) S

--仓库
CREATE TABLE #GetManKTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT S.TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID) S
IF @KTypeId = '%'
	INSERT INTO #GetManKTypeId(TypeId)VALUES('10000')

--商品
CREATE TABLE #ManPTypeId(TypeId VARCHAR(100))
INSERT INTO #ManPTypeId SELECT TypeId FROM F_GetManDetailPType(@OperatorID) WHERE TypeId LIKE @PTypeIDmx + '%'

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	
--部门
CREATE TABLE #GetManDTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManDTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

CREATE TABLE #BillIndex
(
	BillNumberId	numeric(18,0),
	BillType INT,
)



--取表体
SET @SQL = 'INSERT INTO #BillIndex
			SELECT BI.BillNumberId, BI.BillType
			FROM 	BillIndex BI'

IF NOT (@BTypeId='%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
	SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON Bi.BTypeId = B.TypeId'

IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
	SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON Bi.ETypeId = E.TypeId'

--IF NOT (@KTypeId = '%' AND @MKTypeId = '00000')
	--SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = I.KTypeId '
	
IF NOT (@STypeId = '' AND @MStypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '
	
IF NOT (@DTypeId = '' AND @MDtypeid = '00000')
	SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON Bi.DTypeId = D.TypeId '

SET @SQL = @SQL 
			+ ' WHERE BI.BillDate >= @StartDate
					AND BI.BillDate <= @EndDate'
					+ CASE @QueryType
					WHEN 0
					THEN ' AND BI.BillType IN (11,45,160,141,215,12,46) '
					WHEN 1
					THEN ' AND BI.BillType IN (34,6,145,161) '
					END
					+ ' AND BI.RedWord = 0
					AND ((@IncludeInit=0 AND draft=0 and isini=0 and ifcheck=''t'')OR(@IncludeInit=1 And (draft=0 OR isini=1)))
					AND BI.preferencemoney=0
					AND BI.totalInMoney=0
					and isnull(bi.ChargeOffTotal,0)=0 --排除核销过的单据
					AND BI.jsstyle <> 1
					AND BI.jsstyle <> 3
					AND ISNULL(Bi.totalmoney, 0)-(ISNULL(Bi.totalinmoney, 0) + ISNULL(Bi.preferencemoney, 0))<>0 '
					+ CASE @BillCode
            WHEN ''
            THEN ''
            ELSE ' AND Bi.BillCode LIKE ''%''+@BillCode+''%'''
          END
          + CASE @CID
            WHEN 0
            THEN ''
            ELSE ' AND Bi.CID=@CID'
          END

 EXEC sp_executesql @SQL, N'@StartDate nvarchar(20),@EndDate nvarchar(20),@BillTypeId nvarchar(100), @IncludeInit INT, @BillCode NVARCHAR(256), @CID INT' 
 ,@StartDate,@EndDate,@BillTypeId,@IncludeInit,@BillCode,@CID

	--发票数据
	declare @isinvoice varchar(10)
	select @isinvoice=SubValue from sysdata where SubName='IsInvoice'
	
--CREATE TABLE #BillNum1(BillNumberId	numeric(18,0),BillType int)
IF @isinvoice='1'
BEGIN 
   --取表体
	SET @SQL = 'INSERT INTO #BillIndex
				SELECT BI.BillNumberId, BI.BillType
				FROM 	ReceiptBillIndex BI'

	IF NOT (@BTypeId='%' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL = @SQL + '	INNER JOIN #GetManBTypeId B ON Bi.BTypeId = B.TypeId'

	IF NOT (@ETypeId = '00001' AND @METypeId = '00001')
		SET @SQL = @SQL + '	INNER JOIN #GetManETypeId E ON Bi.ETypeId = E.TypeId'

	--IF NOT (@KTypeId = '%' AND @MKTypeId = '00000')
		--SET @SQL = @SQL + ' INNER JOIN #GetManKTypeId K ON K.TypeId = I.KTypeId '
		
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON Bi.STypeId = S.TypeId '
		
	IF NOT (@DTypeId = '' AND @MDtypeid = '00000')
		SET @SQL = @SQL + ' INNER JOIN #GetManDTypeId D ON Bi.DTypeId = D.TypeId '

	SET @SQL = @SQL 
				+ ' WHERE BI.BillDate >= @StartDate
						AND BI.BillDate <= @EndDate'
						+ CASE @QueryType
						WHEN 0
						THEN ' AND BI.BillType IN (405) '
						WHEN 1
						THEN ' AND BI.BillType IN (404) '
						END
						+ ' AND BI.RedWord = 0
						AND ((@IncludeInit=0 AND draft=0 and isini=0 and ifcheck=''t'')OR(@IncludeInit=1 And (draft=0 OR isini=1)))
						AND BI.jsstyle <> 1
						AND BI.jsstyle <> 3
						and isnull(bi.ChargeOffTotal,0)=0 --排除核销过的单据
						AND ISNULL(Bi.totalmoney, 0)<>0 '
						+ CASE @BillCode
				WHEN ''
				THEN ''
				ELSE ' AND Bi.BillCode LIKE ''%''+@BillCode+''%'''
			  END
			  + CASE @CID
				WHEN 0
				THEN ''
				ELSE ' AND Bi.CID=@CID'
			  END

	 EXEC sp_executesql @SQL, N'@StartDate nvarchar(20),@EndDate nvarchar(20),@BillTypeId nvarchar(100), @IncludeInit INT, @BillCode NVARCHAR(256), @CID INT' 
	 ,@StartDate,@EndDate,@BillTypeId,@IncludeInit,@BillCode,@CID

END


--表体明细
CREATE TABLE #BillDetail
(
 billtype  int,
 pTypeId   VARCHAR(100),
 kTypeId   VARCHAR(100),
 Qty     NUMERIC(24, 10) ,
 taxTotal    NUMERIC(24, 10) ,
 ntaxtotal    NUMERIC(24, 10) ,
 taxprice    NUMERIC(24, 10) ,
 ntaxprice    NUMERIC(24, 10) ,
 completeqty    NUMERIC(24, 10) ,
 completeTotal  NUMERIC(24, 10) ,
 ncompleteTotal  NUMERIC(24, 10) 
) 
IF @QueryType = 0
	BEGIN
    INSERT  INTO #BillDetail
            SELECT  11 ,  --销售出库单
                    s.PtypeId ,
                    KtypeId ,
                    SUM(Qty) ,
                    SUM(TaxTotal) ,
                    SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    SUM(CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    SaleBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 11 )
                    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    KTypeID
    INSERT  INTO #BillDetail
            SELECT  45 ,  -- 销售退货单
                    s.PtypeId ,
                    KtypeId ,
                    -SUM(Qty) ,
                    -SUM(TaxTotal) ,
                    -SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    -SUM(CompleteQTY),
                     -SUM(s.CompleteTotal),
                    -SUM(s.NCompleteTotal)
            FROM    salebackbill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 45 )
                    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    KTypeID
  
    INSERT  INTO #BillDetail
            SELECT  160 ,  -- 销售换货单
                    s.PtypeId ,
                    KtypeId ,
                    CASE InOrOut WHEN 'O' THEN SUM(Qty)					WHEN 'I' THEN SUM(-Qty) END,
                    CASE InOrOut WHEN 'O' THEN SUM(TaxTotal)		WHEN 'I' THEN SUM(-TaxTotal)	 END,
                    CASE InOrOut WHEN 'O' THEN SUM(NTaxTotal)		WHEN 'I' THEN SUM(-NTaxTotal)	END	,
                    CASE InOrOut WHEN 'O' THEN SUM(taxPrice)		WHEN 'I' THEN SUM(-taxPrice)		END,
                    CASE InOrOut WHEN 'O' THEN SUM(NtaxPrice)		WHEN 'I' THEN SUM(-NtaxPrice)	END,
                    CASE InOrOut WHEN 'O' THEN SUM(CompleteQTY) WHEN 'I' THEN SUM(-CompleteQTY) END,
                    CASE InOrOut WHEN 'O' THEN SUM(CompleteTotal)		WHEN 'I' THEN  SUM(-CompleteTotal)	 END AS CompleteTotal ,
					CASE InOrOut WHEN 'O' THEN SUM(nCompleteTotal)		WHEN 'I' THEN  SUM(-nCompleteTotal) END AS nCompleteTotal 
            FROM    SaleGoodsExchangeBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                          FROM      #BillIndex
                                          WHERE     BillType = 160 )
                    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    KTypeID, 
										InOrOut


    INSERT  INTO #BillDetail
            SELECT  141,
                    s.PtypeId ,
                    '10000' ,
                    SUM(qty) ,
                    SUM(taxtotal) ,
                    SUM(ntaxtotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    SUM(CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    CommissionBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE   Type = 141
										AND BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 141 )
										AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId 
            
                
			INSERT  INTO #BillDetail
            SELECT  405 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    ReceiptBill s
           /* LEFT JOIN
            (
				SELECT PtypeID,Billid, GoodsBillID,SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 405 )	  
            GROUP BY s.PtypeId, s.KTypeID   
            
            
            INSERT  INTO #BillDetail
            SELECT  12 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM   dbo.PT_Combin_SaleBill s
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 12 )	   	AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,s.KTypeID  
            
            
             INSERT  INTO #BillDetail
            SELECT  46 ,
                    s.PtypeID ,
                    s.KtypeId ,
                    -SUM(s.Qty) ,
                    -SUM(s.TaxTotal) ,
                    -SUM(s.NTaxTotal) ,
                    SUM(s.taxPrice) ,
                    SUM(s.NtaxPrice) ,
                    -SUM(s.CompleteQTY),
                    -SUM(s.CompleteTotal), --,SUM(completeqty*taxprice)
                    -SUM(s.NCompleteTotal)
            FROM    dbo.PT_Combin_SaleBackBill s
            WHERE   s.BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 46 )	   AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    s.KTypeID    
                    
                    

	END
	
	
	--付款结算
	IF @QueryType = 1
	BEGIN
		--采购入库
    INSERT  INTO #BillDetail
            SELECT  34 ,
                    s.PtypeId ,
                    KtypeId ,
                    SUM(Qty) ,
                    SUM(TaxTotal) ,
                    SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    SUM(CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    buybill s
           /*LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 34 )
                    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    KTypeID
	
		--委托代销
    INSERT  INTO #BillDetail
            SELECT  145,
                    s.PtypeId ,
                    '10000' ,
                    SUM(qty) ,
                    SUM(taxtotal) ,
                    SUM(ntaxtotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    SUM(CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    CommissionBill s
            /*LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE   Type = 145
										AND BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 145 )
                    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId 

		--
    INSERT  INTO #BillDetail
            SELECT  6 ,
                    s.PtypeId ,
                    KtypeId ,
                    -SUM(Qty) ,
                    -SUM(TaxTotal) ,
                    -SUM(NTaxTotal) ,
                    SUM(taxPrice) ,
                    SUM(NtaxPrice) ,
                    -SUM(CompleteQTY),
                   SUM(-s.CompleteTotal),
                    SUM(-s.NCompleteTotal)
            FROM    dbo.BuyBackBill s
            /*LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                      FROM      #BillIndex
                                      WHERE     BillType = 6 )
                    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    KTypeID
		
		
    INSERT  INTO #BillDetail
            SELECT  161 ,
                    s.PtypeId ,
                    KtypeId ,
										CASE InOrOut WHEN 'O' THEN SUM(-Qty)					WHEN 'I' THEN SUM(Qty) END,
                    CASE InOrOut WHEN 'O' THEN SUM(-TaxTotal)		WHEN 'I' THEN SUM(TaxTotal)	 END,
                    CASE InOrOut WHEN 'O' THEN SUM(-NTaxTotal)		WHEN 'I' THEN SUM(NTaxTotal)	END	,
                    CASE InOrOut WHEN 'O' THEN SUM(taxPrice)		WHEN 'I' THEN SUM(taxPrice)		END,
                    CASE InOrOut WHEN 'O' THEN SUM(NtaxPrice)		WHEN 'I' THEN SUM(NtaxPrice)	END,
                    CASE InOrOut WHEN 'O' THEN SUM(-CompleteQTY) WHEN 'I' THEN SUM(CompleteQTY) END,
                    CASE InOrOut WHEN 'O' THEN SUM(-CompleteTotal)		WHEN 'I' THEN  SUM(CompleteTotal)	 END AS CompleteTotal ,
					CASE InOrOut WHEN 'O' THEN SUM(-NCompleteTotal)		WHEN 'I' THEN  SUM(NCompleteTotal) END AS NCompleteTotal 
            FROM    BuyGoodsExchangeBill s
            /*LEFT JOIN
            (
				SELECT PtypeID,Billid,GoodsBillID, SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = S.BillNumberId*/
            WHERE   BillNumberId IN ( SELECT    BillNumberId
                                          FROM      #BillIndex
                                          WHERE     BillType = 161 )
                    AND TaxTotal<>0 -- 去掉含税金额为零
            GROUP BY s.PtypeId ,
                    KTypeID, 
                    InOrOut
        
           --采购发票        
            INSERT  INTO #BillDetail
            SELECT  404 ,
                    s.ptypeid ,
                    s.KTypeID ,
                    SUM(s.qty) ,
                    SUM(s.taxtotal) ,
                    SUM(s.ntaxtotal) ,
                    SUM(s.TaxPrice) ,
                    SUM(s.NTaxPrice) ,
                    SUM(s.CompleteQTY),
                    SUM(s.CompleteTotal),
                    SUM(s.NCompleteTotal)
            FROM    ReceiptBill s
            /*LEFT JOIN
            (
				SELECT PtypeID,Billid, GoodsBillID,SUM(NCompleteGoodTotal) AS NCompleteGoodTotal,SUM(CompleteGoodTotal) AS CompleteGoodTotal
				FROM CompleteGoodTotal 
				WHERE Draft = 0
				GROUP BY PtypeID,Billid,GoodsBillID
            ) T ON t.PtypeID = s.PtypeId AND T.Billid = S.ID AND T.GoodsBillID = s.BillNumberId*/
            WHERE  s.BillNumberId IN ( SELECT  BillNumberId
                                            FROM    #BillIndex
                                            WHERE   BillType = 404 )	  
            GROUP BY s.PtypeId,s.KTypeID       
		
	END




--缩小数据
CREATE TABLE #Result
(
	TypeId				VARCHAR(100),
	Qty					 NUMERIC(24, 10) ,
	CompleteGoodQty		 NUMERIC(24, 10) ,
	UnCompleteGoodQty	 NUMERIC(24, 10) ,
	Total				 NUMERIC(24, 10) ,
	NTotal				 NUMERIC(24, 10) ,
	CompleteTotal		 NUMERIC(24, 10) ,
	NCompleteTotal		 NUMERIC(24, 10) ,
	UnCompleteTotal		 NUMERIC(24, 10) ,
	NUnCompleteTotal     NUMERIC(24, 10) 
)

--过滤商品和仓库(不过滤父节点)

IF @KTypeId = '%' AND @MKTypeId = '00000'
BEGIN
	INSERT  INTO #Result
        SELECT  BD.ptypeid ,
                SUM(BD.qty) AS QTY ,
                SUM(BD.CompleteQTY) AS CompleteGoodQTY ,
                SUM(BD.qty - BD.CompleteQTY) AS UnCompleteGoodQTY ,
                SUM(BD.TaxTotal) AS TotalMoney ,
                SUM(BD.NTaxTotal) AS NTotalMoney ,
                SUM(BD.Completetotal) AS TotalJsMoney ,
                SUM(BD.NCompletetotal) AS NTotalJsMoney ,
                SUM(BD.TaxTotal - ISNULL(BD.CompleteTotal,0)) AS TotalWjsMoney ,
                SUM(BD.NTaxTotal - ISNULL(BD.NCompleteTotal,0)) AS NTotalWjsMoney
        FROM    #BillDetail BD
                INNER JOIN #ManPTypeId P ON P.TypeId = BD.PTypeId
				GROUP BY BD.ptypeid

END
ELSE
BEGIN
	INSERT  INTO #Result
        SELECT  BD.ptypeid ,
                SUM(BD.qty) AS QTY ,
                SUM(BD.CompleteQTY) AS CompleteGoodQTY ,
                SUM(BD.qty - BD.CompleteQTY) AS UnCompleteGoodQTY ,
                SUM(BD.TaxTotal) AS TotalMoney ,
                SUM(BD.NTaxTotal) AS NTotalMoney ,
                SUM(BD.Completetotal) AS TotalJsMoney ,
                SUM(BD.NCompletetotal) AS NTotalJsMoney ,
                SUM(BD.TaxTotal - ISNULL(BD.CompleteTotal,0)) AS TotalWjsMoney ,
                SUM(BD.NTaxTotal - ISNULL(BD.NCompleteTotal,0)) AS NTotalWjsMoney
        FROM    #BillDetail BD
                INNER JOIN #ManPTypeId P ON P.TypeId = BD.PTypeId
                INNER JOIN #GetManKTypeId K ON K.TypeId = BD.KTypeId
				GROUP BY BD.ptypeid
END



SELECT  p.Typeid, 
					   p.UserCode,
					   p.FullName,
				     p.sonnum,
					   RE.QTY,
					   RE.CompleteGoodQTY,
					   RE.UnCompleteGoodQTY,
					   RE.Total,
					   RE.NTotal,
					   RE.CompleteTotal,
					   RE.NCompleteTotal,
					   RE.UnCompleteTotal,
					   RE.NUnCompleteTotal
				FROM dbo.ptype P
				INNER JOIN	#Result RE ON P.TypeId = RE.TypeId
				WHERE   p.TypeId <> '00000'
						AND p.sonnum = 0
						AND (@PFullName = '' OR p.FullName LIKE '%' +@PFullName + '%')
						AND (@PUserCode = '' OR p.UserCode LIKE '%' + @PUserCode + '%')
				ORDER BY P.UserCode


DROP TABLE #BillDetail,#BillIndex,#Result,#ManPTypeId,#GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManSTypeId,#GetManDTypeId
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryGoodsStocks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryGoodsStocks]
GO




/*
	作者：谢吉康
	日期：2009-8-17
	描述：库存数据查询
*/
CREATE PROCEDURE Web_QueryGoodsStocks
(
	@chvOperatorId		varchar(100),
	@TypeId				varchar(100),
	@IdList				varchar(8000),
	@nFlag				varchar(10)			--0.上一层  1.下一层
)
--@encode$--
AS
SET NOCOUNT ON

CREATE TABLE #PType
(
	TypeId		varchar(100),
	ParId		varchar(100),
	SonNum		varchar(10),
	UserCode	varchar(200),
	FullName	varchar(200)
)

INSERT INTO #PType(TypeId,ParId,SonNum,UserCode,FullName) EXEC Web_GetLoginUserManBaseInfoForReport 'ptype',@TypeId,@IdList,@chvOperatorId,@nFlag

SELECT * FROM #PType ORDER BY UserCode

DROP TABLE #PType




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Web_QueryGoodsStocksSyncInfo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP procedure [dbo].[Web_QueryGoodsStocksSyncInfo]
GO

/*
	作者：谢吉康
	日期：2018-10-17
	描述：查询库存信息
	EXEC Web_QueryGoodsStocksSyncInfo
*/
CREATE PROCEDURE Web_QueryGoodsStocksSyncInfo
AS
SET NOCOUNT ON

--账面库存
IF EXISTS(SELECT * FROM dbo.WMSBaseInfo WHERE Field = 'upstockrule' AND Value = 0)
BEGIN
	SELECT	DISTINCT B.*
	FROM	(
				SELECT	r.wmsptypeid AS ptypeid,
						r.wmsktypeid AS ktypeid,
						r.WMS_SKUId AS skuid,
						SUM(ISNULL(r.Qty,0)) AS qty,
						dbo.F_RoundTotal(SUM(g.price * r.qty)) AS total
				FROM    dbo.GoodsStocks G
				INNER JOIN (
								SELECT	p.WMS_Typeid AS wmsptypeid,
										p.WMS_SKUId,
										k.WMS_TypeId AS wmsktypeid,						
										q.ptypeid,
										q.ktypeid,
										SUM(q.qty) AS qty
								FROM	goodsstocks_qty q
								INNER JOIN dbo.WmsErpPtypeContrastSetting P ON q.PtypeId = P.ERP_TypeId
								INNER JOIN dbo.WmsErpStockContrastSetting k ON q.KtypeId = k.ERP_TypeId
								WHERE ISNULL(p.erp_skuid,'') = ''
								GROUP BY	p.WMS_Typeid,
											p.WMS_SKUId,
											k.WMS_TypeId,
											q.ptypeid,
											q.ktypeid
				)R ON g.ptypeid = r.ptypeid AND g.ktypeid = r.ktypeid
				GROUP BY	r.wmsptypeid,
							r.wmsktypeid,
							r.WMS_SKUId
				UNION ALL
				SELECT	r.wmsptypeid AS ptypeid,
						r.wmsktypeid AS ktypeid,
						r.WMS_SKUId AS skuid,
						SUM(ISNULL(r.Qty,0)) AS qty,
						dbo.F_RoundTotal(SUM(g.price * r.qty)) AS total
				FROM    dbo.GoodsStocks G
				INNER JOIN (
								SELECT	p.WMS_Typeid AS wmsptypeid,
										p.WMS_SKUId,
										k.WMS_TypeId AS wmsktypeid,						
										q.ptypeid,
										q.ktypeid,
										SUM(q.qty) AS qty
								FROM	goodsstocks_qty q
								INNER JOIN dbo.WmsErpPtypeContrastSetting P ON q.PtypeId = P.ERP_TypeId	AND q.itemid = p.erp_skuid
								INNER JOIN dbo.WmsErpStockContrastSetting k ON q.KtypeId = k.ERP_TypeId
								GROUP BY	p.WMS_Typeid,
											p.WMS_SKUId,
											k.WMS_TypeId,
											q.ptypeid,
											q.ktypeid
				)R ON g.ptypeid = r.ptypeid AND g.ktypeid = r.ktypeid
				GROUP BY	r.wmsptypeid,
							r.wmsktypeid,
							r.WMS_SKUId
	)B								
END
ELSE IF EXISTS(SELECT * FROM dbo.WMSBaseInfo WHERE Field = 'upstockrule' AND Value = 1)
BEGIN
	DECLARE @sysdatavirtualqtysql VARCHAR(MAX)
	SELECT @sysdatavirtualqtysql = Value FROM dbo.Userconfig WHERE ConfigName = 'VirtualQtySQL'	
	
	CREATE TABLE #ResultTable
	(
		PTypeId		VARCHAR(50),
		KTypeId		VARCHAR(50),
		SKUID		VARCHAR(100),
		Qty			NUMERIC(24,10),
		Total		NUMERIC(24,2)
	)
	INSERT INTO #ResultTable
	( 
		PTypeId, 
		KTypeId, 
		SKUID, 
		Qty, 
		Total 
	)
	EXEC Gp_WmsCalVirtualStockStatus @OperatorID='00001',
									 @Parid='00000',
									 @szKtypeId='',
									 @sortfield='',
									 @EntryCode='',
									 @Standard='',
									 @Type='',
									 @Area='',
									 @stypeid='',
									 @virtualqtysql=@sysdatavirtualqtysql,
									 @unitconvert='3',
									 @billtype='11,45,305,160,140,142,215,402,403,12,46',
									 @startdate='2000-01-01',
									 @enddate='9999-12-31',
									 @showstockstop=0,
									 @ptypeCategoryid='',
									 @showzeroqty=1
	
	SELECT * FROM #ResultTable
	
	DROP TABLE #ResultTable
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryHistoryInnerArLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryHistoryInnerArLine
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-13
	描述：内部分支机构历史应收线性表
	EXEC Web_QueryHistoryInnerArLine '00001','00000',''
*/

CREATE PROCEDURE Web_QueryHistoryInnerArLine
(
	@OperatorId			VARCHAR(100),
	@STypeId			VARCHAR(MAX),	--分支机构
	@DSTypeId			VARCHAR(MAX),	--对应分支机构
	@EndDate			VARCHAR(MAX)	--截止日期
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @SQL		VARCHAR(MAX),
		@SonNum		INT,
		@STypeIdMx	VARCHAR(MAX)
		
IF @STypeId = '00000' 
	SET @STypeIdMx = '%'				
ELSE	
	SET @STypeIdMx = @STypeId
	
IF @DSTypeId = ''
	SET @DSTypeId = '00000'	
		
SELECT @SonNum = SonNum FROM SType WHERE TypeId = @DSTypeId		

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--对方分支机构
CREATE TABLE #GetManDSTypeId(TypeId	varchar(100))
INSERT INTO #GetManDSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,@OperatorID)	

--单据
CREATE TABLE #BillIndex
(
	BillNumberId	NUMERIC(18,0)	
)

INSERT INTO #BillIndex(BillNumberId)
SELECT	B.BillNumberId
FROM	BillIndex B
INNER JOIN #GetManSTypeId S ON S.TypeId = B.Stypeid
WHERE	B.BillType IN (187,188)
		AND B.ifcheck = 't'
		AND B.RedWord = 0
		AND B.ifYearBill = 0
		AND B.BillDate<=@EndDate

SET @SQL = 'SELECT	S.TypeId,
					S.SonNum,
					S.UserCode,
					SUM(ISNULL(M.ArAdd,0) - ISNULL(M.ArReduce,0)) AS Total
			FROM	F_GetManSTypeAll('''+@OperatorId+''') S
			LEFT JOIN (
							SELECT	STypeId,
									CASE WHEN BillType = 187 THEN Total ELSE 0 END AS ArAdd,
									0 AS ArReduce
							FROM	STypeMoveBill
							WHERE	KTypeId2 IN (SELECT TypeId FROM Stock WHERE STypeId IN (SELECT TypeId FROM #GetManDSTypeId))							
									AND FromBillNumberID = 0
									AND BillNumberId IN (SELECT * FROM #BillIndex)
							UNION ALL
							SELECT	S.STypeId,
									0 AS ArAdd,
									CASE WHEN M.BillType = 188 THEN M.Total ELSE 0 END AS ArReduce
							FROM	STypeMoveBill M
							INNER JOIN Stock S ON S.TypeId = M.KTypeId2
							WHERE	KTypeId2 IN (SELECT TypeId FROM Stock WHERE STypeId IN (SELECT TypeId FROM #GetManDSTypeId))
									AND FromBillNumberID = 0
									AND BillNumberId IN (SELECT * FROM #BillIndex)
			)M ON LEFT(M.STypeId,Len(S.TypeId)) = S.TypeId
			WHERE	S.TypeId IN (SELECT * FROM #GetManDSTypeId)
					AND S.SonNum = 0	
			GROUP BY S.TypeId,
					 S.SonNum,
					 S.UserCode
			ORDER BY S.UserCode '	
			
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManDSTypeId,#BillIndex

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryHistoryInnerArList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryHistoryInnerArList
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-13
	描述：内部分支机构历史应收树型表
	EXEC Web_QueryHistoryInnerArList '00001','00000',''
*/

CREATE PROCEDURE Web_QueryHistoryInnerArList
(
	@OperatorId			VARCHAR(100),
	@STypeId			VARCHAR(MAX),	--分支机构
	@DSTypeId			VARCHAR(MAX),	--对应分支机构
	@EndDate			VARCHAR(MAX)	--截止日期
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @SQL		VARCHAR(MAX),
		@SonNum		INT,
		@STypeIdMx	VARCHAR(MAX)
		
IF @STypeId = '00000' 
	SET @STypeIdMx = '%'				
ELSE	
	SET @STypeIdMx = @STypeId
	
IF @DSTypeId = ''
	SET @DSTypeId = '00000'	
		
SELECT @SonNum = SonNum FROM SType WHERE TypeId = @DSTypeId		

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--对应分支机构
CREATE TABLE #GetManDSTypeId(TypeId	varchar(100))
INSERT INTO #GetManDSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,'00001')

--分支机构所对应的仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE sonnum = 0 AND typeId In (SELECT typeId FROM F_GetAllManagerBaseTypeId('',4,'00001')) AND STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID))
	
--对应分支机构所对应的仓库
CREATE TABLE #GetManDKTypeId(TypeId	varchar(100))
INSERT INTO #GetManDKTypeId(TypeId) SELECT TypeId FROM Stock WHERE sonnum = 0 AND typeId In (SELECT typeId FROM F_GetAllManagerBaseTypeId('',4,'00001')) AND STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,'00001'))

CREATE TABLE #BillIndex
(
	BillNumberId	NUMERIC(18,0)
)

INSERT INTO #BillIndex(BillNumberId) 
SELECT	BillNumberId 
FROM	BillIndex 
WHERE	BillType IN (187,188) 
		AND ifcheck = 't' 
		AND RedWord = 0 
		AND ifYearBill = 0
		AND BillDate<=@EndDate	

--优惠券分支机构调拨类单据
INSERT INTO #BillIndex(BillNumberId)
SELECT BILLNUMBERID
FROM Coupon_BillIndex
WHERE BILLTYPE IN(428,429)
AND IFCHECK='T' AND REDWORD=0 AND IFYEARBILL=0 AND BILLDATE<=@ENDDATE
		
SET @SQL = 'SELECT	B.TypeId,
					B.SonNum,
					B.UserCode,
					SUM(ISNULL(B.Total,0)) AS Total
			FROM	(			
						SELECT	S.TypeId,
								S.SonNum,
								S.UserCode,					
								SUM(ISNULL(M.InnerArTotal00,0)) AS Total
						FROM	SType_InnerARTotal M
						INNER JOIN #GetManSTypeId MS ON MS.TypeId = M.STypeId
						INNER JOIN #GetManDSTypeId D ON D.TypeId = M.STypeId2	
						INNER JOIN SType S ON D.TypeId = S.TypeId
						GROUP BY S.TypeId,
								 S.SonNum,
								 S.UserCode
						UNION ALL
						SELECT	S.TypeId,
								S.SonNum,
								S.UserCode,
								SUM(ISNULL(M.ArAdd,0) - ISNULL(M.ArReduce,0)) AS Total
						FROM	F_GetManSTypeAll(''00001'') S			
						LEFT JOIN (							
										SELECT	S.STypeId,
												CASE WHEN M.BillType = 187 THEN M.Total ELSE 0 END AS ArAdd,
												0 AS ArReduce
										FROM	STypeMoveBill M
										INNER JOIN #BillIndex Bil ON Bil.BillNumberId = M.BillNumberId
										INNER JOIN Stock S ON S.TypeId = M.KTypeId2
										WHERE	M.KTypeId IN (SELECT TypeId FROM #GetManKTypeId) AND M.KTypeId2 IN (SELECT TypeId FROM #GetManDKTypeId)									
										UNION ALL
										SELECT	S.STypeId,
												0 AS ArAdd,
												CASE WHEN M.BillType =188 THEN ISNULL(M.Total,0) ELSE 0 END AS ArReduce
										FROM	STypeMoveBill M
										INNER JOIN #BillIndex Bil ON Bil.BillNumberId = M.BillNumberId
										INNER JOIN Stock S ON S.TypeId = M.KTypeId
										WHERE M.KTypeId2 IN (SELECT TypeId FROM #GetManKTypeId) AND M.KTypeId IN (SELECT TypeId FROM #GetManDKTypeId)
										
										UNION ALL
										SELECT	S.STypeId,
												CASE WHEN cb.BillType = 429 THEN M.Total ELSE 0 END AS ArAdd,
												0 AS ArReduce
										FROM	Coupon_AllotBillStype M
										INNER jOIN Coupon_BillIndex cb ON cb.billnumberid=M.billnumberid
										INNER JOIN #BillIndex Bil ON Bil.BillNumberId = M.BillNumberId
										INNER JOIN Stock S ON S.TypeId = cb.inKTypeId
										WHERE cb.outktypeid IN (SELECT TypeId FROM #GetManKTypeId) AND cb.inKTypeId IN (SELECT TypeId FROM #GetManDKTypeId)
										
										UNION ALL
										SELECT	S.STypeId,
												0 AS ArAdd,
												CASE WHEN cb.BillType = 428 THEN ISNULL(M.Total,0) ELSE 0 END AS ArReduce
										FROM	Coupon_AllotBillStype M
										INNER jOIN Coupon_BillIndex cb ON cb.billnumberid=M.billnumberid
										INNER JOIN #BillIndex Bil ON Bil.BillNumberId = M.BillNumberId
										INNER JOIN Stock S ON S.TypeId = cb.outKTypeId
										WHERE cb.inKTypeId IN (SELECT TypeId FROM #GetManKTypeId) AND cb.inKTypeId IN (SELECT TypeId FROM #GetManDKTypeId)			
						)M ON M.STypeId = S.TypeId
						WHERE	S.SonNum = 0
						GROUP BY S.TypeId,
								 S.SonNum,
								 S.UserCode
						UNION ALL
						SELECT	S.TypeId,
								S.SonNum,
								S.UserCode,
								sum(l.total) AS Total
						FROM	F_GetManSTypeAll(''00001'') S			
						left JOIN  ListTable L  ON l.STypeId2 = S.TypeId
						INNER JOIN #GetManSTypeId b ON b.TypeId = l.STypeId	
						INNER JOIN #GetManDSTypeId D ON D.TypeId = l.STypeId2	
					    INNER JOIN  AC_Items AC ON L.atypeid=AC.nid
						WHERE	S.SonNum = 0
								AND  AC.UserCode=''1132''
								AND  L.BillDate<='''+@EndDate+''' 
								AND L.billtype=159	
						GROUP BY S.TypeId,
								 S.SonNum,
								 S.UserCode
					)B
					
			WHERE B.TypeId IN (SELECT * FROM #GetManDSTypeId)
			GROUP BY B.TypeId,
					 B.SonNum,
					 B.UserCode					
			ORDER BY B.UserCode '			
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManDSTypeId,#GetManKTypeId,#GetManDKTypeId,#BillIndex

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryHistoryRepairLogQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryHistoryRepairLogQuery
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
	作者：韩林
	日期：2011-5-5
	描述：维修历史记录查询
-------------------------------------------*/
CREATE PROCEDURE Web_QueryHistoryRepairLogQuery
(
	@startdate		VARCHAR(MAX),	--开始日期
	@enddate		VARCHAR(MAX),	--截止日期
	@btypeId		VARCHAR(MAX),	--往来单位ID
	@ratypeid		VARCHAR(MAX)	--车牌号
)
--@encode$--
AS
SET NOCOUNT ON

SELECT	Rb.RepairItemsTypeID AS witypeid,
		Rb.StandardManHour,
		Rb.total,
		Rb.Discount,
		Rb.DiscountTotal,
		B.BillDate
FROM	BillIndex B
INNER JOIN BillIndex_CarRepair Bc ON B.BillNumberId = Bc.BillNumberId
INNER JOIN Qp_ReceptionBill_RepairItems Rb ON Bc.BillNumberId=Rb.BillNumberId
INNER JOIN QP_RepairItems Ri ON Rb.RepairItemsTypeID=Ri.TypeID
WHERE	Bc.BillState=4
		AND B.RedWord=0
		AND B.btypeid=@btypeId
		AND	Bc.Ratypeid=@ratypeid
		AND B.BillDate>=@startdate
		AND B.BillDate<=@enddate
ORDER BY B.BillDate DESC,Ri.UserCode DESC

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryImAuditingBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryImAuditingBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-03-23
	描述：获取当前操作员的审核列表
*/

/*
	修改者：廖晨羽
	日期：2011-07-22
	描述：增加经手人、往来单位、仓库、部门权限
*/
-- 2013-01-25 周华 同价，变价调拨单时 去掉经手人，部门的多级权限 
-- 2013-03-28 周华 修改复盖问题
-- 2013-04-12 周华 搬上面01-25号的功能权限控制部分
-- 2013-12-05 周华 添加请购单类型
CREATE PROCEDURE Web_QueryImAuditingBill
(
	@OperatorId			VARCHAR(100),
	@StartDate			VARCHAR(50),
	@EndDate			VARCHAR(50),	
	@BillCode			VARCHAR(100),
	@BillType			VARCHAR(50),
	@Comment			VARCHAR(200),
	@IfAudit			VARCHAR(50),
	@iscurrentauditing	BIT,
	@stypeid			VARCHAR(MAX),		--分支机构
	@etypeid			VARCHAR(MAX),		--职员
	@checke				VARCHAR(MAX) = '',	--制单人
	@nbillid			VARCHAR(MAX) = ''	--单据ID
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

DECLARE @combinationproduct	VARCHAR(10)
select @combinationproduct=subvalue from sysdata where subname='combinationproduct'
DECLARE @ImAudit VARCHAR(50)=''
IF @nbillid<>''
BEGIN 
	SELECT @ImAudit=RTRIM(CAST (IfAudit  AS VARCHAR)) FROM AuditingBill WHERE BillNumberID=@nbillid
end
SET @IfAudit=ISNULL(@ImAudit,'');
--SELECT @IfAudit

--只显示其他审核步骤完成的单据	
DECLARE @currentauditing	VARCHAR(MAX)
IF @iscurrentauditing = 1
	SET @currentauditing = 	
		' AND ( 
				(
				  F.AuditingType = 3 
				AND  
				 (SELECT COUNT(allcharindex) FROM FN_GetAllCharIndex(''1'',A.PassSteps)) - (SELECT COUNT(allcharindex) FROM FN_GetAllCharIndex(''1'',A.AuditingSteps)) = 1
				) 
				OR  F.AuditingType <> 3
			  )'
ELSE
	SET @currentauditing = ''	
-------------------------------------
/*---是否统一往来单位
DECLARE @isAllBtype VARCHAR(50)
SELECT @isAllBtype = Value FROM dbo.Userconfig WHERE ConfigName = 'btypeall'*/ 

DECLARE @SQL VARCHAR(MAX)

--描  述：检查调拨当中入库仓库是否有效
DECLARE @MoveInOutKLimit  INT
SELECT @MoveInOutKLimit=Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit' --配置

--增加权限
 --往来单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)

--经手人
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid <> '00001'
BEGIN
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	
END

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)
DECLARE @GetKtypeCount int,@KtypeCount int  ---全部仓库
		 
IF @MKtypeId = '00000'
	INSERT INTO #GetManKTypeId(TypeId) VALUES('00000')
	
INSERT INTO #GetManKTypeId(TypeId) VALUES('10000')	
	
--部门
CREATE TABLE #GetManDtypeId(TypeId	varchar(100))
IF @MDtypeid = '-99999'
INSERT INTO #GetManDtypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

--分支机构
CREATE TABLE #GetManStypeId(TypeId	varchar(100))
IF @MStypeid = '-99999'
INSERT INTO #GetManStypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--制单人
CREATE TABLE #GetManChecke(TypeId	varchar(100))
INSERT INTO #GetManChecke(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@checke,3)
/*IF @MEtypeid <> '00001' OR @checke <> ''
BEGIN
	IF @checke = ''
	BEGIN
		INSERT INTO #GetManChecke(TypeId) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@checke,3,@OperatorID)
		UNION ALL
		SELECT '00001'
	END
	ELSE
		INSERT INTO #GetManChecke(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@checke,3,@OperatorID)
END*/

-- //搬敏捷
-- 调拨权限
DECLARE @dp NCHAR(1)='0'; --部门
DECLARE @ep NCHAR(1)='0'; --经手人
SELECT @dp=RIGHT(LEFT(lim,3013),1),@ep=RIGHT(LEFT(lim,3014),1) FROM loginuser WHERE etypeid=@OperatorId
--//


DECLARE @SQL_WHERE_SZ VARCHAR(MAX),@re_re INT--单据查看权限

SELECT @SQL_WHERE_SZ = ' where ( '
	EXEC @re_re=GP_CheckLimit @OperatorID,2676
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 305 or'		--零售查看(POS单查看)

EXEC @re_re=GP_CheckLimit @OperatorID,2679
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 11 or'			--销售单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2682
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 45 or'			--销售退货单查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2709
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 215 or'		--零售退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2831
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 4 or'			--收款单查看


EXEC @re_re=GP_CheckLimit @OperatorID,2718
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 34 or'			--采购单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2721
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 6 or'			--采购退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2837
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 66 or'			--付款单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2739
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 17 or'			--同价调拨单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2742
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 21 or'			--变价调拨单查看


EXEC @re_re=GP_CheckLimit @OperatorID,2751
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 9 or'			--报损单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2754
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 14 or'			--报溢单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2688
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 139 or'		--赠送单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2727
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 126 or'		--获赠单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2882

IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 57 or'			--调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2769
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 16 or'			--商品拆装单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2819
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 116 or'		--应收款增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2822

IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 115 or'		--应收款减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2825
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 128 or'		--应付款增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2828
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 129 or'		--应付款减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2855
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 36 or'			--费用单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2864
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 93 or'			--其他收入单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2861
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 77 or'			--转款单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2873
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 84 or'			--固定资产(项目)购买查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2914
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 212 or'		--固定资产增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2876
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 85 or'			--固定资产(项目)变卖查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2917
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 213 or'		--固定资产减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2879
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 78 or'			--固定资产(卡片)折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2920
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 78 or'			--固定资产(项目)折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2920
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 214 or'		--固定资产折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2867
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 5 or'			--待摊费用发生查看

EXEC @re_re=GP_CheckLimit @OperatorID,2870
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 10 or'			--待摊费用摊销查看


EXEC @re_re=GP_CheckLimit @OperatorID,2843
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 148 or'		--返利执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2849
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 149 or'		--价保执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2691
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 140 or'		--委托代销发货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2700
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 141 or'		--委托代销结算单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2694
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 142 or'		--委托代销退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2697
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 143 or'		--委托代销调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2923
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 144 or'		--受托代销收货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2736
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 145 or'		--受托代销结算单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2730
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 146 or'		--受托代销退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2733
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 147 or'		--受托代销调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2846
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 150 or'		--获利核算执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2781
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 156 or'		--维修接件单 -- 单据查看权限

EXEC @re_re=GP_CheckLimit @OperatorID,2852
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 151 or'		--获得价保过账

EXEC @re_re=GP_CheckLimit @OperatorID,2858								--现金费用单
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 158 or'			

EXEC @re_re=GP_CheckLimit @OperatorID,2885								--会计凭证
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 159 or'			

EXEC @re_re=Gp_CheckLimit @OperatorID,2685
IF @re_re = 0															--销售换货单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 160 or'			

EXEC @re_re=Gp_CheckLimit @OperatorID,2724
IF @re_re = 0															--采购换货单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 161 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2781
IF @re_re = 0															--维修接件单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 165 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2784
IF @re_re = 0															--维修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 166 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2787
IF @re_re = 0															--维修取件单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 167 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2790
IF @re_re = 0															--整机更换单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 168 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2793
IF @re_re = 0															--送修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 169 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2796
IF @re_re = 0															--送修返回单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 170 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2799
IF @re_re = 0															--报修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 171 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2802
IF @re_re = 0															--上门维修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 172 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2805
IF @re_re = 0															--维修品调入单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 173 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2808
IF @re_re = 0															--维修品调出单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 174 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2811
IF @re_re = 0															--维修品调拨单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 175 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2906
IF @re_re = 0															--积分兑换单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 183 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,1368
IF @re_re = 0															--保险理赔单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 186 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2745
IF @re_re = 0															--分支机构调拨出库单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 187 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2748
IF @re_re = 0															--分支机构调拨入库单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 188 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2834
IF @re_re = 0															--预收款单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 189 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2840
IF @re_re = 0															--预付款单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 190 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,1472
IF @re_re = 0															--领料出库单----------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 191 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,1474
IF @re_re = 0															--领料退回单-------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 197 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1487
IF @re_re = 0															--维修结算单-----------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 195 or'			
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1477
IF @re_re = 0															--救援单----------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 196 or'		
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1478
IF @re_re = 0															--三包索赔单--------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 200 or'		
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2775
IF @re_re = 0															--其他入库单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 201 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2778
IF @re_re = 0															--其他出库单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 202 or'									

EXEC @re_re=Gp_CheckLimit @OperatorID,2772
IF @re_re = 0															--序列号调整单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 203 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2888
IF @re_re = 0															--采购费用分摊 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 205 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2891
IF @re_re = 0															--销售费用分摊 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 206 or'		
			
EXEC @re_re=Gp_CheckLimit @OperatorID,2713
IF @re_re = 0															--询价单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 185 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2711
IF @re_re = 0															--请购单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 204 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2715
IF @re_re = 0															--采购订单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 301 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2673
IF @re_re = 0															--销售订单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 300 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2671
IF @re_re = 0															--报价单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 184 or'		

--不是总账则不显示资金调拨单
IF((SELECT SubValue FROM SYSDATA WHERE SUBNAME = 'isuseacsystem') = 1)
BEGIN
	EXEC @re_re=Gp_CheckLimit @OperatorID,4318
	IF @re_re = 0														--资金调拨单  
		SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 310 or'
END

EXEC @re_re=Gp_CheckLimit @OperatorID,2988
IF @re_re = 0															--提成单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 311 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,2900
IF @re_re = 0															--会员储值充值单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 181 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4501
IF @re_re = 0															--会员批量储值充值单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 312 or'	
--9.6增加借欠类单据
EXEC @re_re=Gp_CheckLimit @OperatorID,2757
IF @re_re = 0															--借出开单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 87 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2760
IF @re_re = 0															--借进开单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 71 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2763
IF @re_re = 0															--借出还回单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 88 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2766
IF @re_re = 0															--借进还出单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 72 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,4581
IF @re_re = 0															--暂估入库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 400 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4590
IF @re_re = 0															--暂估退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 401 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4602
IF @re_re = 0															--发出商品出库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 402 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4611
IF @re_re = 0															--发出商品退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 403 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4622
IF @re_re = 0															--采购暂估开票  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 404 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4630
IF @re_re = 0															--销售发货开票  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 405 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,4678
IF @re_re = 0															--往来核销  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 450 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4745
IF @re_re = 0															--组合品销售订单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 313 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,4753
IF @re_re = 0															--组合品销售出库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 12 or'
--4745      4753     4761         
EXEC @re_re=Gp_CheckLimit @OperatorID,4761
IF @re_re = 0															--组合品销售出退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 46 or'
 --4829 仓库入库
 EXEC @re_re=Gp_CheckLimit @OperatorID,4829
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 418 or'
 --4837 仓库出库
  EXEC @re_re=Gp_CheckLimit @OperatorID,4837
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 419 or'
 --4845仓库调拨单
 EXEC @re_re=Gp_CheckLimit @OperatorID,4845
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 420 or'

SELECT @SQL_WHERE_SZ = @SQL_WHERE_SZ + ' r.billtype = 1000 )  '			--随便添加一个BillType用来拼凑字符串

DECLARE @sqljoin VARCHAR(50)
IF @IfAudit='' 
	SET @sqljoin=' right join '
ELSE 
	SET @sqljoin=' inner join '

SET @SQL = '; WITH TEMP AS
	(
	SELECT	B.BillNumberId,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.totalmoney,
			B.ETypeId,
			B.dealBTypeId,
			B.btypeid,
			b.stypeid,
			CASE 
				WHEN c.AuditingType = ''1'' THEN ''顺序审核''
				WHEN c.AuditingType = ''2'' THEN ''任意审核''
				ELSE ''会签审核''
			END AS AudType,
			c.BillIndexType AS BillIndexType,
			c.AuditStep AS AuditingStep,
			B.checke,
			B.checktime,
			B.BillAudit,
			B.CostSale,
			B.comment,
			B.explain
	FROM	
	(
	

		SELECT B.BillNumberId,
				''3'' AS BillIndexType,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.totalmoney,
				B.ETypeId,
				'''' AS dealBTypeId,
				'''' AS btypeid,
				B.STypeId,
				B.checke,
				B.checktime,
				CASE B.IfAudit
					WHEN 1 THEN ''t''
					ELSE ''f'' 
				END AS BillAudit,
				0 AS CostSale,
				B.comment,
				B.explain 
		FROM AuditingBill A
		'+@sqljoin+' dbo.RequestIndex B ON B.BillNumberId = A.BillNumberId and   A.BillIndexType = ''3'' '

IF @MEtypeid <> '00001' OR @checke <> ''
	SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = b.STypeId '
	SET @SQL=@sql+' WHERE  B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''''
				+
				CASE WHEN  ISNULL(@IfAudit,'')='' THEN ''
				ELSE ' AND a.IfAudit = '''+@IfAudit+''' ' 
				END
			
				
IF @BillCode <> ''
	SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
IF @Comment <> ''
	SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
IF @BillType <> ''
	SET @SQL += ' AND B.BillType = '+@BillType+' '	
ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411 )'
IF @combinationproduct = '0' OR @combinationproduct is null 
 SET @SQL += ' AND B.BillType NOT IN (313)'
	 
IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @etypeid<>''	OR @MEtypeid <> '00001'
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @MDtypeid='-99999'
		SET @sql+=' AND b.DTypeId IN (SELECT TypeId FROM #GetManDtypeId)  '

SET @SQL += '
UNION ALL 
		SELECT	B.BillNumberId,
				''0'' AS BillIndexType,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.totalmoney,
				B.ETypeId,
				B.dealBTypeId,
				B.btypeid,
				B.STypeId,
				B.checke,
				B.checktime,
				CASE B.IfAudit
					WHEN 1 THEN ''t''
					ELSE ''f'' 
				END AS BillAudit,
				0 AS CostSale,
				B.comment,
				B.explain 
		FROM	AuditingBill A
		'+@sqljoin+' OrderIndex B ON B.BillNumberId = A.BillNumberId  and A.BillIndexType = ''0'' '
	
	IF @MEtypeid <> '00001' OR @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' INNER JOIN #GetManBTypeId B1 ON B1.TypeId = B.dealBTypeId
					  INNER JOIN #GetManBTypeId B2 ON B2.typeid=B.btypeid '
	IF @MKtypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId '
	IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	SET @SQL += '
		WHERE	 B.BillOver = 0 
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''''
				+
				CASE WHEN ISNULL(@IfAudit,'')='' THEN ''
				ELSE 'AND a.IfAudit = '''+@IfAudit+'''  '
				END 
				
		
				
	IF @MEtypeid <> '00001'
		SET @sql+=' AND (B.ETypeId IN (SELECT TypeId FROM #GetManETypeId) OR B.BillType IN(17,21) AND '+@ep+'=''1'') '
	IF @MDtypeid='-99999'
		SET @sql+=' AND (B.DTypeId IN (SELECT TypeId FROM #GetManDtypeId) OR B.BillType IN(17,21) AND '+@dp+'=''1'') '
IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @etypeid<>''
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
				
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411 )'
	IF @combinationproduct = '0' OR @combinationproduct is null 
	 SET @SQL += ' AND B.BillType NOT IN (313)'

	SET @SQL += '
	UNION ALL
	SELECT	B.BillNumberId,
			''2'' AS BillIndexType,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.totalmoney,
			B.ETypeId,
			B.dealBTypeId,
			B.btypeid,
			B.STypeId,
			B.checke,
			B.checktime,
			B.ifcheck AS BillAudit,
			B.CostSale,
			B.comment,
			B.explain 
	FROM	AuditingBill A
	'+@sqljoin+' BillIndex B ON B.BillNumberId = A.BillNumberId and A.BillIndexType = ''2'' '

	IF(@BillType <> '310')
	BEGIN
		IF @MStypeid = '-99999'
			SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	END
	IF @MEtypeid <> '00001' OR @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
		
	SET @SQL += '
		WHERE	B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''' 
				'
				+
				CASE WHEN ISNULL(@IfAudit,'')='' THEN ''
				ELSE 'AND a.IfAudit = '''+@IfAudit+''''
				END 
				
	
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
	 SET @SQL += ' AND B.BillType NOT IN (313)'		
		
	IF(@BillType = '310') 
	BEGIN
		--IF @stypeid<>''
		SET @sql+='  and 
		( 
			b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+')) 
			OR b.StypeID2 in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+')) 
		
		)'
	END
	ELSE
	BEGIN
		IF @stypeid<>''
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	END

	IF @etypeid<>''
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	
	IF @MEtypeid <> '00001'
		SET @sql+=' AND (B.ETypeId IN (SELECT TypeId FROM #GetManETypeId) OR B.BillType IN(17,21) AND '+@ep+'=''1'') '

	IF @MDtypeid='-99999'
		SET @sql+=' AND (B.DTypeId IN (SELECT TypeId FROM #GetManDtypeId) OR B.BillType IN(17,21) AND '+@dp+'=''1'') '
	
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' AND (
							(
								B.dealBTypeID IN (SELECT typeid FROM #GetManBTypeId) AND B.BillType IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''12'',''46'')
							)
							OR
							(
								B.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''12'',''46'')
							)
						) 
					AND (
							(
								B.BTypeID IN (SELECT typeid FROM #GetManBTypeId) AND B.BillType IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''450'',''12'',''46'')
							)
							OR
							(
								B.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''450'',''12'',''46'')
							)
						)
						--AND B.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''12'',''46'') 
						'
						
	IF @MKtypeid = '-99999'
	BEGIN
		SET @SQL += '
			AND (
					(
						( B.KTypeID IN (SELECT typeid FROM #GetManKTypeId) OR B.KTypeID2 IN (SELECT typeid FROM #GetManKTypeId)) AND B.BillType IN (''16'',''155'',''157'',''160'',''161'',''201'',''202'') 
					) 
					OR 
					(
						B.BillType IN (''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''147'',''201'',''202'',''400'',''401'',''402'',''403'',''12'',''46'') AND B.KTypeID IN (SELECT typeid FROM #GetManKTypeId)
					) 
					OR 
					( '
		IF @MoveInOutKLimit = 1
			SET @SQL = @SQL + '	B.BillType IN (''17'',''21'') AND (B.KTypeId IN (SELECT typeid FROM #GetManKTypeId) AND B.KTypeId2 IN (SELECT typeid FROM #GetManKTypeId)) '
		ELSE
			SET @SQL = @SQL + ' B.BillType IN (''17'',''21'') AND (B.KTypeId IN (SELECT typeid FROM #GetManKTypeId) OR B.KTypeId2 IN (SELECT typeid FROM #GetManKTypeId)) '
		SET @SQL = @SQL + '
					)
					OR
					(
						B.BillType NOT IN (''16'',''155'',''157'',''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''147'',''17'',''21'',''160'',''161'',''201'',''202'',''400'',''401'',''402'',''403'',''12'',''46'')
					)
				) 
				--AND B.BillType NOT IN (''16'',''155'',''157'',''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''147'',''17'',''21'',''160'',''161'',''201'',''202'')
				'
	END
	
	
	SET @SQL += ' 
	UNION ALL
			SELECT	B.BillNumberId,
					''4'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					''311'' AS BillType,
					B.Total AS totalmoney,
					'''' AS ETypeId,
					'''' AS dealBTypeId,
					'''' AS btypeid,
					B.STypeId,
					B.checke,
					B.checketime AS checktime,
					B.ifcheck AS BillAudit,
					0 AS CostSale,
					B.comment,
					B.explain 
		    FROM	AuditingBill A 
		    '+@sqljoin+' CommissionBillNew AS B ON(B.BillNumberId = A.BillNumberId and A.BillIndexType = ''4''	) 
		    INNER JOIN employee AS C ON(B.Checke = C.typeId)  '
	
	IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
		
	IF @MEtypeid <> '00001'	or @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	SET @SQL += '
		WHERE	B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				'
				+
				CASE WHEN ISNULL(@IfAudit,'')='' THEN ''
				ELSE 'AND a.IfAudit = '''+CAST(CASE WHEN @IfAudit = '' THEN 0 ELSE @IfAudit END AS VARCHAR(10))+'''  '
				END 
				
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND 311 = '+@BillType+' '			
					
	IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	
	SET @SQL+=' AND ''' + @etypeid +''' = '''' '
	
	SET @SQL += ' 
	UNION ALL
			SELECT	B.BillNumberId,
					''1'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					b.BillType,
					''0'' AS totalmoney,
					b.ETypeId,
					b.dealBTypeId,
					b.btypeid,
					B.STypeId,
					B.checke,
					B.checktime,
					B.ifcheck AS BillAudit,
					0 AS CostSale,
					B.comment,
					B.explain 
		    FROM AuditingBill A 
		    '+@sqljoin+' LendIndex AS B ON(B.BillNumberId = A.BillNumberId and A.BillIndexType = ''1'' )  '
	SET @SQL += '
		WHERE	B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				AND A.IfAudit = '''+ CAST(CASE WHEN @IfAudit = '' THEN 0 ELSE @IfAudit END AS VARCHAR(10))+''' 
				'
	IF @stypeid<>''	 or @MStypeid = '-99999'
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @etypeid<>''	OR @MEtypeid <> '00001'
			SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411 )'
	IF @combinationproduct = '0' OR @combinationproduct is null 
	 SET @SQL += ' AND B.BillType NOT IN (313)'
	
	SET @SQL += ' 
	UNION ALL
			SELECT	B.BillNumberId,
					''7'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					b.BillType,
					''0'' AS totalmoney,
					b.ETypeId,
					'''' AS dealBTypeId,
					'''' AS btypeid,
					B.STypeId,
					B.checke,
					B.checktime,
					B.ifcheck AS BillAudit,
					0 AS CostSale,
					B.comment,
					B.explain 
		    FROM	AuditingBill A 
		    '+@sqljoin+' FactIndex AS B ON(B.BillNumberId = A.BillNumberId and A.BillIndexType = ''7'')  '
		    
	IF @MEtypeid <> '00001' OR @checke <> ''
				SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	IF @MDtypeid='-99999'
		SET @sql+=' INNER JOIN #GetManDtypeId AS D ON(B.DTypeId = D.Typeid) '
					  
	SET @SQL += '
		WHERE	B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				AND A.IfAudit = '''+ CAST(CASE WHEN @IfAudit = '' THEN 0 ELSE @IfAudit END AS VARCHAR(10))+''' 
				'
				+
				CASE WHEN ISNULL(@IfAudit,'')='' THEN ''
				ELSE 'AND a.IfAudit = '''+@IfAudit+'''  '
				END 
				
	
	IF @MKtypeid = '-99999'
	BEGIN
		  SET @sql+=' AND ( (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype IN (418,419))'
		  IF @MoveInOutKLimit=1
		  BEGIN
			 SET @sql+=' OR (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId)  AND  B.ktypeid2 in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype=420) )'
		  END
		  ELSE
		  BEGIN
			 SET @sql+=' OR (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId)  OR  B.ktypeid2 in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype=420)  )'
		  END
		   
	END
	
	IF @stypeid<>''	 or @MStypeid = '-99999'
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @etypeid<>''	OR @MEtypeid <> '00001'
			SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411 )'
	IF @combinationproduct = '0' OR @combinationproduct is null 
	 SET @SQL += ' AND B.BillType NOT IN (313)'
		
	SET @SQL += ' 
	UNION ALL
			SELECT	B.BillNumberId,
					''5'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.TaxTotalMoney AS totalmoney,
					B.ETypeId,
					B.dealBTypeId,
					B.btypeid,
					B.STypeId,
					B.checke,
					B.checktime,
					B.ifcheck AS BillAudit,
					0 AS CostSale,
					B.comment,
					B.explain 
		    FROM	AuditingBill A 
		    '+@sqljoin+' ReceiptBillIndex AS B ON(B.BillNumberId = A.BillNumberId and A.BillIndexType = ''5'' ) 
		    '
		    
	IF @MStypeid = '-99999'
			SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	
	IF @MEtypeid <> '00001' OR @checke <> ''
				SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	IF @MDtypeid='-99999'
		SET @sql+=' INNER JOIN #GetManDtypeId AS D ON(B.DTypeId = D.Typeid) '
		
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' INNER JOIN #GetManBTypeId B1 ON B1.TypeId = B.dealBTypeId
					  INNER JOIN #GetManBTypeId B2 ON B2.typeid=B.btypeid '	
	SET @SQL += '
		WHERE	 B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''' 
				 '
				+
				CASE WHEN ISNULL(@IfAudit,'')='' THEN ''
				ELSE 'AND a.IfAudit = '''+@IfAudit+'''  '
				END 
				
	IF @etypeid<>''	or @MEtypeid <> '00001'
			SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
				
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411 )'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		 SET @SQL += ' AND B.BillType NOT IN (313)'
	SET @SQL += '						
		) B '+ CASE WHEN @IfAudit='' THEN ' left join '
				ELSE ' inner join '
				END 

		SET @SQL += '						
	
			
		(SELECT A.BillNumberId,
				A.BillIndexType,
				DBO.FN_MinGetCurrentAuditETypeID('''+@OperatorId+''',A.BillNumberId,F.STypeId,F.BillType) AS AuditStep,
				F.AuditingType,
				F.BillType FROM AuditingBill A,AuditingFlowSet F 
							WHERE	A.AuditingId = F.AuditingId 
									AND A.IfAudit = '''+@IfAudit+''' 
									AND EXISTS(SELECT 1 FROM dbo.AuditingBill s, AuditingFlowDetail d WHERE s.auditingid = f.auditingid AND d.etypeid='''+@OperatorId+''' AND f.AuditingID = d.AuditingID AND f.BillType = d.BillType)
									AND '''+@OperatorId+''' NOT IN (SELECT ETypeID FROM dbo.AuditingFlowDetail WHERE AuditingStep = 0 AND AuditingID = F.AuditingId) ' +@currentauditing + '
		) C
		on 	B.BillNumberId = c.BillNumberId
				AND B.BillIndexType = c.BillIndexType '
				+
				CASE WHEN @IfAudit='0' 
					 THEN 'AND C.AuditStep IS NOT NULL
						'
				ELSE ''
				END 
				
				--*************
				--9.6 BUG ID :88 与测试讨论的结果是,不接受需要订的 1级审核后还要继续在待审核显示这张单,就应该不显示,
				--同时因为此单据并没有真正过账,也不显示在已审核中。  这里先恢复原来的功能。 加上 AND C.AuditStep IS NOT NULL
				
				--9.5 BUG ID :1063如果不注释会导致，顺序审批的单据在当前级别审核后从“待审核列表”消息
				--AND C.AuditStep IS NOT NULL 
				--*************
	 
SET @SQL += ' ) '
	
--查询出最后的结果
IF @nbillid = ''		
BEGIN
	SET @SQL += 'SELECT	R.*,
						emp.FullName as efullname ,
						bty.FullName as bfullname,
						bty1.Fullname as jsfullname,
						N.BillName AS billtypename,
						CK.fullname AS fullnameck,
						sty.fullname as sfullname 
				FROM	TEMP R
				LEFT JOIN  employee emp ON r.ETypeId=emp.typeId 
				LEFT JOIN employee AS CK ON(R.checke = CK.typeId) 
				LEFT JOIN  btype bty ON r.dealBTypeId=bty.typeId
				LEFT JOIN  btype bty1 ON r.btypeid=bty1.typeid 
				LEFT JOIN  stype sty ON r.stypeid=sty.typeid 
				LEFT JOIN BillName N ON N.Billtype = R.BillType'+@SQL_WHERE_SZ+'
				ORDER BY BillDate,BillCode '
END
ELSE
BEGIN
	SET @SQL +='SELECT	R.BillNumberId
				FROM	TEMP R
				LEFT JOIN  employee emp ON r.ETypeId=emp.typeId 
				LEFT JOIN employee AS CK ON(R.checke = CK.typeId) 
				LEFT JOIN  btype bty ON r.dealBTypeId=bty.typeId
				LEFT JOIN  btype bty1 ON r.btypeid=bty1.typeid 
				LEFT JOIN  stype sty ON r.stypeid=sty.typeid 
				LEFT JOIN BillName N ON N.Billtype = R.BillType'+@SQL_WHERE_SZ+' AND R.BillNumberId = '+@nbillid+'				
				ORDER BY BillDate,BillCode '
END

--PRINT(@SQL)
EXEC (@SQL)

DROP TABLE #GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManDtypeId,#GetManChecke

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WEB_QueryIniAccountAssist]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WEB_QueryIniAccountAssist]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	Created	:	董湛
	Date	:	2012/04/24
	Description	: 查询辅助核算项
*/

CREATE PROCEDURE WEB_QueryIniAccountAssist
(
	@STypeId	VARCHAR(50),	--分支机构id
	@TypeId		VARCHAR(50),	--该科目id	
	@Cid		INT,			--币别id	
	@OperatorID	VARCHAR(50),	--操作员ID
	@Type		INT,			--1:引入按钮跳转 0正常行数据按钮
	@Flag		INT				--1：引入往来余额:2：引入库存余额:3：引入固定资产余额
)
--@encode$--
AS
SET NOCOUNT ON 
DECLARE 
	@FYear			INT=0,	--年度
	@FPeriod		INT=0,	--期间
	@AssistLimit	INT,	--辅助核算项目受权限范围控制
	@SQL			VARCHAR(MAX)=''
	
SELECT @AssistLimit=SUBSTRING(lim,4690,1) FROM loginuser WHERE etypeid=@OperatorID--辅助核算项目受权限范围控制
SELECT @FYear=SFYear,@FPeriod=SFPeriod FROM Ac_AccountsPeroid_Stype WHERE Stypeid=@STypeId--分支机构启用年度/启用期间

--================================业务数据逻辑处理【BEGIN】=============================			
--正确会计科目辅助核算信息
CREATE TABLE #AssistFullName
(
	AscIds		INT,
	AsUserCode	VARCHAR(200),
	FullName	VARCHAR(200)
)
INSERT INTO #AssistFullName(AscIds,AsUserCode,FullName)
SELECT
	C.Ascids,
	CI.UserCode,
	CI.FullName 
FROM Ac_Account_Assist_CheckItems C
INNER JOIN Ac_Assist_CheckItems CI ON CI.AscIds=C.Ascids
WHERE 
	C.STypeId=@STypeId
	AND C.ATypeId=@TypeId
	AND C.Cid=@Cid
	
	

--查询包含非独立分支机构
CREATE TABLE #SType(STypeId VARCHAR(50),VerifyID VARCHAR(50))
INSERT INTO #SType(STypeId,VerifyID) SELECT TypeId,VerifyID FROM SType WHERE VerifyID=@STypeId AND deleted=0

BEGIN --业务数据临时表	   
CREATE TABLE #TempData
(
	ATypeId			VARCHAR(50),
	STypeId			VARCHAR(50),
	ETypeID			VARCHAR(50),
	DTypeID			VARCHAR(50),
	BTypeID			VARCHAR(50),
	BillTotal		NUMERIC(22,10),
	BillTotalFor	NUMERIC(22,10),
	GroupId			INT IDENTITY(1,1)
)
--引入按钮进入
IF(@Type=1)
	BEGIN
		IF(@Flag=1)--引入往来余额
			BEGIN			
				--------提取费用单配置
				DECLARE @Expensetoar INT
				SELECT @Expensetoar=SUBVALUE FROM dbo.sysdata WHERE SubName='expensetoar'

				INSERT INTO #TempData(ATypeId,STypeId,ETypeID,DTypeID,BTypeID,BillTotal,BillTotalFor)
				SELECT
					ATypeID,
					Stypeid,
					etypeid,
					DTypeId,
					btypeid,
					SUM(BillTotal) BillTotal,
					SUM(BillTotalFor) BillTotalFor
				FROM 
				(
					SELECT
						@TypeId ATypeID,
						A.Stypeid,
						A.etypeid,
						A.DTypeId,
						A.btypeid,
						CASE WHEN a.BillType IN(45,6,148,149,150,151,46) THEN -(ISNULL(A.totalmoney,0)-ISNULL(A.preferencemoney,0)-ISNULL(A.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))   
							ELSE ISNULL(a.totalmoney,0)-ISNULL(A.preferencemoney,0)-ISNULL(A.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
						END BillTotal,
						CASE WHEN a.BillType IN(45,6,148,149,150,151,46) THEN -(ISNULL(A.NTotalMoney,0)-ISNULL(A.NPreferenceMoney,0)-ISNULL(A.NCompleteTotal,0)-ISNULL(A.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))         
							ELSE (ISNULL(A.NTotalMoney,0)-ISNULL(A.NPreferenceMoney,0)-ISNULL(A.NCompleteTotal,0)-ISNULL(A.NTotalInMoney,0))-ISNULL(A.NChargeOffTotal,0)                             
						END BillTotalFor
					FROM #SType S 
					INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.ISINI=1 AND A.CID=@CId AND A.BillType NOT IN(116,115,128,129,36,400,401,404,405)
					WHERE A.ATypeID1=@TypeId
					
					UNION ALL--暂估入库单
					
					SELECT
						@TypeId ATypeID,
						A.Stypeid,
						A.etypeid,
						A.DTypeId,
						A.btypeid,
						AB.total BillTotal,
						AB.NTotal BillTotalFor 
					FROM #SType S 
					INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid AND A.BillType=400
					INNER JOIN AppraisalBill AB ON AB.BillNumberId=A.BillNumberId
					WHERE A.ATypeID1=@TypeId
					
					UNION ALL --暂估退货单
					
					SELECT
						@TypeId ATypeID,
						A.Stypeid,
						A.etypeid,
						A.DTypeId,
						A.btypeid,
						-AB.total BillTotal,
						-AB.NTotal BillTotalFor 
					FROM #SType S 
					INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid AND A.BillType=401
					INNER JOIN AppraisalBackBill AB ON AB.BillNumberId=A.BillNumberId
					WHERE A.ATypeID1=@TypeId
					
					UNION ALL --(404采购暂估开票 405销售发货开票)
					
					SELECT 
						@TypeId ATypeID,
						A.Stypeid,
						A.etypeid,
						A.DTypeId,
						A.btypeid,
						AB.TaxTotal-A.CompleteTotal-A.ChargeOffTotal BillTotal,
						AB.NTaxTotal-A.NCompleteTotal-A.NChargeOffTotal BillTotalFor 
					FROM #SType S 
					INNER JOIN ReceiptBillIndex A  ON A.STypeId=S.Stypeid AND A.IsIni=1 AND A.CID=@Cid AND ((A.BillType=405 AND A.ATypeID1=CAST(@Type AS VARCHAR(50))) OR (A.BillType=404 AND A.ATypeID2=@TypeId))
					INNER JOIN AppraisalBackBill AB ON AB.BillNumberId=A.BillNumberId

					UNION ALL--提取应收应付的增加，减少单

					SELECT
						@TypeId ATypeID,
						A.Stypeid,
						A.etypeid,
						A.DTypeId,
						C.BtypeId,
						CASE WHEN A.BillType IN(129,115) THEN -(ISNULL(C.total,0)-ISNULL(A.preferencemoney,0)-ISNULL(C.CompleteTotal,0)-ISNULL(A.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))
							ELSE ISNULL(c.total,0)-ISNULL(a.preferencemoney,0)-ISNULL(c.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
						END AS BillTotal,
						CASE WHEN A.BillType IN(129,115) THEN -(ISNULL(c.NTotal,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(c.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))
							ELSE ISNULL(c.NTotal,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(c.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0)
						END AS BillTotalFor	
					FROM #SType S 
					INNER JOIN BillIndex A  ON A.STypeId=S.STypeId AND A.ISINI=1 AND A.CID=@CId AND A.BillType IN (116,115,128,129)
					LEFT JOIN AdDebtBill C  ON C.BillNumberId=A.BillNumberId
					WHERE A.ATypeID1=@TypeId

					UNION ALL --提取费用单

					SELECT 
						@TypeId ATypeID,
						A.Stypeid,
						A.etypeid,
						A.DTypeId,
						A.btypeid,
						CASE WHEN @Expensetoar=1 AND SUBSTRING(DealBTypeID,1,5)='00001' THEN -(ISNULL(a.totalmoney,0)-ISNULL(a.preferencemoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0))   
							ELSE ISNULL(a.totalmoney,0)-ISNULL(a.preferencemoney,0)-ISNULL(a.CompleteTotal,0)-ISNULL(a.totalinmoney,0)-ISNULL(A.ChargeOffTotal,0)
						END AS BILLTOTAL,
						CASE WHEN @Expensetoar=1 AND SUBSTRING(DealBTypeID,1,5)='00001' THEN -(ISNULL(a.NTotalMoney,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(a.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))         
							ELSE (ISNULL(a.NTotalMoney,0)-ISNULL(a.NPreferenceMoney,0)-ISNULL(a.NCompleteTotal,0)-ISNULL(a.NTotalInMoney,0)-ISNULL(A.NChargeOffTotal,0))                             
						END AS BILLTOTALFOR
					FROM #SType S 
					INNER JOIN BillIndex A  ON A.STypeId=S.Stypeid AND A.ISINI=1 AND A.CID=@CId AND A.BillType=36
					WHERE A.ATypeID1=@TypeId
				) F 
				GROUP BY ATypeID,Stypeid,etypeid,DTypeId,btypeid
			END
		IF(@Flag=2 AND @Cid=1)--库存
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='useatypefrom' AND SubValue='1')
					BEGIN
						INSERT INTO #TempData(ATypeId,STypeId,BillTotal,BillTotalFor)
						SELECT
							D.StockATypeID ATypeId,
							S.STypeId,
							SUM(ISNULL(G.Total,0)) BillTotal,
							SUM(ISNULL(G.Total,0)) BillTotalFor
						FROM #SType S 
						INNER JOIN Stock ST ON ST.STypeID=S.STypeId AND ST.deleted=0
						INNER JOIN IniGoodsStocks G ON G.KtypeId=ST.typeId
						INNER JOIN ptype P ON P.typeId=G.PtypeId 
						INNER JOIN Base_InventoryTypeDetails D ON D.TID=P.InventoryTypeID AND D.STypeID=S.STypeId AND D.StockATypeID=@TypeId
						GROUP BY D.StockATypeID,S.STypeId
					END
				ELSE 
					BEGIN
						INSERT INTO #TempData(ATypeId,STypeId,BillTotal,BillTotalFor)
						SELECT
							S1.ATypeID4 ATypeId,
							S.STypeId,
							SUM(ISNULL(G.Total,0)) BillTotal,
							SUM(ISNULL(G.Total,0)) BillTotalFor
						FROM #SType S 
						INNER JOIN Stock ST ON ST.STypeID=S.STypeId AND ST.deleted=0
						INNER JOIN IniGoodsStocks G ON G.KtypeId=ST.typeId
						INNER JOIN SType S1 ON S1.TypeId=S.VerifyID AND S1.ATypeID4=@TypeId
						GROUP BY S1.ATypeID4,S.STypeId
					END
			END
		IF(@Flag=3 AND EXISTS(SELECT TOP 1 1 FROM SysData WHERE SubName='assets' AND SubValue='1')) AND @Cid=1--固定资产科目
			BEGIN
				INSERT INTO #TempData(ATypeId,STypeId,DTypeID,BillTotal,BillTotalFor)
				SELECT
					ATypeID,
					STypeId,
					DTypeid,
					SUM(BillTotal) BillTotal,
					SUM(BillTotalFor) BillTotalFor
				FROM 
				(
					--固定资产科目
					SELECT
						@TypeId ATypeID,
						AC.STypeId,
						AC.DTypeid,
						SUM(AC.Total) BillTotal,
						SUM(AC.Total) BillTotalFor                                                             
					FROM #SType S 
					INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5) AND ac.AssertATypeId=@TypeId
					GROUP BY 
						AC.STypeId,
						AC.DTypeid
					
					UNION ALL
					--累计折旧科目
					SELECT
						@TypeId ATypeID,
						AC.STypeId,
						AC.DTypeid,
						SUM(AC.DepTotal) BillTotal,
						SUM(AC.DepTotal) BillTotalFor                            
					FROM #SType S 
					INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5) AND ac.DepATypeId=@TypeId
					GROUP BY 
						AC.STypeId,
						AC.DTypeid
					
					UNION ALL
					--减值准备科目
					SELECT
						@TypeId ATypeID,
						AC.STypeId,
						AC.DTypeid,
						SUM(AC.DevalueReady) BillTotal,
						SUM(AC.DevalueReady) BillTotalFor                     
					FROM #SType S 
					INNER JOIN dbo.Ac_AssetsCards AC ON AC.STypeId=S.STypeId AND AC.AssetsState NOT IN(2,5) AND ac.DevalueATypeId=@TypeId
					GROUP BY 
						AC.STypeId,
						AC.DTypeid
				) F 
				GROUP BY ATypeID,STypeId,DTypeid
			END
		--删除相同分支机构  部门  职员 往来单位   合计为0 的数据
		DELETE FROM #TempData WHERE BillTotal=0 AND BillTotalFor=0
	END
END;		

--总数据临时表	   
CREATE TABLE #ATempData
(
	STypeID			VARCHAR(50),
	TypeId			VARCHAR(50),
	Cid				INT,
	Ascids			VARCHAR(200),
	FieldValue		VARCHAR(50),
	IniTotal		NUMERIC(22,10) DEFAULT(0),
	IniTotalFor		NUMERIC(22,10) DEFAULT(0),
	iniqty			NUMERIC(22,10) DEFAULT(0),
	
	IniYTotal		NUMERIC(22,10) DEFAULT(0),
	IniYTotalFor	NUMERIC(22,10) DEFAULT(0),
	IniYqty			NUMERIC(22,10) DEFAULT(0), 
	
	FDebit			NUMERIC(22,10) DEFAULT(0),
	FDebitFor		NUMERIC(22,10) DEFAULT(0),
	FDebitqty		NUMERIC(22,10) DEFAULT(0),
	
	FCredit			NUMERIC(22,10) DEFAULT(0),
	FCreditFor		NUMERIC(22,10) DEFAULT(0),
	FCreditqty		NUMERIC(22,10) DEFAULT(0),
	FYTotal			NUMERIC(22,10) DEFAULT(0),
	FYTotalFor		NUMERIC(22,10) DEFAULT(0),
	GroupId			INT
)
IF(@Type=0)
	BEGIN
		INSERT INTO #ATempData(STypeID,TypeId,Cid,Ascids,FieldValue,IniTotal,IniTotalFor,iniqty,IniYTotal,IniYTotalFor,IniYqty,FDebit,FDebitFor,FDebitqty,FCredit,FCreditFor,FCreditqty,FYTotal,FYTotalFor,GroupId)
		SELECT STypeID,ATypeId TypeId,Cid,Ascids,FieldValue,IniTotal,IniTotalFor,iniqty,IniYTotal,IniYTotalFor,IniYqty,FDebit,FDebitFor,FDebitqty,FCredit,FCreditFor,FCreditqty,FYTotal,FYTotalFor,GroupId
		FROM Ac_IniAccount_Assist_CheckItems_Detail
		WHERE 
			STypeId=@STypeId 
			AND ATypeId=@TypeId 
			AND Cid=@Cid 
			AND FYear=@FYear 
			AND FPeriod=@FPeriod
	END
	
--得到最大行ID 
DECLARE @GroupId INT=0
SELECT @GroupId=ISNULL(MAX(GroupId),0) FROM #ATempData

IF(@Type=1)
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=1)
		BEGIN
			INSERT INTO #ATempData(STypeID,TypeId,Cid,Ascids,FieldValue,IniTotal,IniTotalFor,IniYTotal,IniYTotalFor,GroupId)
			SELECT
				@STypeId STypeID,
				T.ATypeId TypeId,
				@Cid Cid, 
				1 Ascids,
				T.STypeId FieldValue,
				SUM(ISNULL(T.BillTotal,0)) IniTotal,
				SUM(ISNULL(T.BillTotalFor,0)) IniTotalFor,
				SUM(ISNULL(T.BillTotal,0)) IniYTotal,
				SUM(ISNULL(T.BillTotal,0)) IniYTotalFor,
				@GroupId+T.GroupId GroupId 
			FROM #TempData T 
			INNER JOIN SType Detail ON Detail.TypeId=T.STypeId
			GROUP BY T.ATypeId,T.STypeId,T.GroupId
		END
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=2)
		BEGIN
			INSERT INTO #ATempData(STypeID,TypeId,Cid,Ascids,FieldValue,IniTotal,IniTotalFor,IniYTotal,IniYTotalFor,GroupId)
			SELECT
				@STypeId STypeID,
				T.ATypeId TypeId,
				@Cid Cid, 
				2 Ascids,
				T.DTypeID FieldValue,
				SUM(ISNULL(T.BillTotal,0)) IniTotal,
				SUM(ISNULL(T.BillTotalFor,0)) IniTotalFor,
				SUM(ISNULL(T.BillTotal,0)) IniYTotal,
				SUM(ISNULL(T.BillTotal,0)) IniYTotalFor,
				@GroupId+T.GroupId GroupId 
			FROM #TempData T 
			INNER JOIN SType Detail ON Detail.TypeId=T.STypeId
			GROUP BY T.ATypeId,T.DTypeID,T.GroupId
		END
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=3)
		BEGIN
			INSERT INTO #ATempData(STypeID,TypeId,Cid,Ascids,FieldValue,IniTotal,IniTotalFor,IniYTotal,IniYTotalFor,GroupId)
			SELECT
				@STypeId STypeID,
				T.ATypeId TypeId,
				@Cid Cid, 
				3 Ascids,
				T.ETypeID FieldValue,
				SUM(ISNULL(T.BillTotal,0)) IniTotal,
				SUM(ISNULL(T.BillTotalFor,0)) IniTotalFor,
				SUM(ISNULL(T.BillTotal,0)) IniYTotal,
				SUM(ISNULL(T.BillTotal,0)) IniYTotalFor,
				@GroupId+T.GroupId GroupId 
			FROM #TempData T 
			INNER JOIN SType Detail ON Detail.TypeId=T.STypeId
			GROUP BY T.ATypeId,T.ETypeID,T.GroupId
		END
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=4)
		BEGIN
			INSERT INTO #ATempData(STypeID,TypeId,Cid,Ascids,FieldValue,IniTotal,IniTotalFor,IniYTotal,IniYTotalFor,GroupId)
			SELECT
				@STypeId STypeID,
				T.ATypeId TypeId,
				@Cid Cid, 
				4 Ascids,
				T.BTypeID FieldValue,
				SUM(ISNULL(T.BillTotal,0)) IniTotal,
				SUM(ISNULL(T.BillTotalFor,0)) IniTotalFor,
				SUM(ISNULL(T.BillTotal,0)) IniYTotal,
				SUM(ISNULL(T.BillTotal,0)) IniYTotalFor,
				@GroupId+T.GroupId GroupId 
			FROM #TempData T 
			INNER JOIN SType Detail ON Detail.TypeId=T.STypeId
			GROUP BY T.ATypeId,T.BTypeID,T.GroupId
		END

		DECLARE 
			@I	INT=5,
			@J	INT=0
		SELECT @J=MAX(Ascids) FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids>4
		WHILE(@I<=@J)
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=@I)
			BEGIN
				INSERT INTO #ATempData(STypeID,TypeId,Cid,Ascids,FieldValue,IniTotal,IniTotalFor,IniYTotal,IniYTotalFor,GroupId)
				SELECT
					@STypeId STypeID,
					T.ATypeId TypeId,
					@Cid Cid, 
					@I Ascids,
					'' FieldValue,
					SUM(ISNULL(T.BillTotal,0)) IniTotal,
					SUM(ISNULL(T.BillTotalFor,0)) IniTotalFor,
					SUM(ISNULL(T.BillTotal,0)) IniYTotal,
					SUM(ISNULL(T.BillTotal,0)) IniYTotalFor,
					@GroupId+T.GroupId GroupId 
				FROM #TempData T 
				INNER JOIN SType Detail ON Detail.TypeId=T.STypeId
				GROUP BY T.ATypeId,T.GroupId
			END
			SET @I+=1
		END
	END
	

BEGIN--期初明细表辅助核算信息
CREATE TABLE #DetailsAssistFullName
(
	STypeID		VARCHAR(50),
	ATypeID		VARCHAR(50),
	AscIds		INT,
	TypeID		VARCHAR(50),
	FullName	VARCHAR(200)
)
--分支机构
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=1)
BEGIN
	INSERT INTO #DetailsAssistFullName(STypeID,ATypeID,AscIds,TypeID,FullName)
	SELECT
		@STypeId STypeId,
		D.TypeId ATypeID,
		1 Ascids,
		D.FieldValue TypeID,
		CASE WHEN (@AssistLimit=0 OR (@AssistLimit=1 AND ISNULL(F.TypeId,'')<>'')) THEN Detail.FullName ELSE '****' END FullName
	FROM #ATempData D
	INNER JOIN SType Detail ON Detail.TypeId=D.FieldValue AND D.Ascids=1
	LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',11,@OperatorID,@StypeId) F ON F.TypeId=D.FieldValue AND D.Ascids=1
END
--部门
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=2)
BEGIN
	INSERT INTO #DetailsAssistFullName(STypeID,ATypeID,AscIds,TypeID,FullName)
	SELECT
		@STypeId STypeId,
		D.TypeId ATypeID,
		2 Ascids,
		D.FieldValue TypeID,
		CASE WHEN (@AssistLimit=0 OR (@AssistLimit=1 AND ISNULL(F.TypeId,'')<>'')) THEN Detail.FullName ELSE '****' END FullName
	FROM #ATempData D
	INNER JOIN Department Detail ON Detail.typeid=D.FieldValue AND D.Ascids=2 
	LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',9,@operatorid,@StypeId) F ON F.typeid=D.FieldValue AND D.Ascids=2
END	
--职员
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=3)
BEGIN
	INSERT INTO #DetailsAssistFullName(STypeID,ATypeID,AscIds,TypeID,FullName)
	SELECT
		@STypeId STypeId,
		D.TypeId ATypeID,
		3 Ascids,
		D.FieldValue TypeID,
		CASE WHEN (@AssistLimit=0 OR (@AssistLimit=1 AND ISNULL(F.TypeId,'')<>'')) THEN Detail.FullName ELSE '****' END FullName
	FROM #ATempData D
	INNER JOIN employee Detail ON Detail.TypeId=D.FieldValue AND D.Ascids=3
	LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',3,@operatorid,@StypeId) F ON F.typeid=D.FieldValue AND D.Ascids=3
END	
--往来单位
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids=4)
BEGIN
	INSERT INTO #DetailsAssistFullName(STypeID,ATypeID,AscIds,TypeID,FullName)
	SELECT
		@STypeId STypeId,
		D.TypeId ATypeID,
		4 Ascids,
		D.FieldValue TypeID,
		CASE WHEN (@AssistLimit=0 OR (@AssistLimit=1 AND ISNULL(F.TypeId,'')<>'')) THEN Detail.FullName ELSE '****' END FullName
	FROM #ATempData D
	INNER JOIN btype Detail ON Detail.TypeId=D.FieldValue AND D.Ascids=4
	LEFT JOIN dbo.F_GetAllManagerBaseByTypeId('',2,@operatorid,@StypeId) F ON F.typeid=D.FieldValue AND D.Ascids=4
END
--自定义辅助核算
IF EXISTS(SELECT TOP 1 1 FROM Ac_Account_Assist_CheckItems WHERE STypeId=@STypeId AND ATypeId=@TypeId AND Cid=@Cid AND Ascids>4)
BEGIN
	INSERT INTO #DetailsAssistFullName(STypeID,ATypeID,AscIds,TypeID,FullName)
	SELECT
		@STypeId STypeId,
		D.TypeId ATypeID,
		D.Ascids Ascids,
		D.FieldValue TypeID,
		ISNULL(Detail.FullName,'') FullName
	FROM #ATempData D 
	LEFT JOIN Ac_Assist_CheckItemsDetail Detail ON Detail.TypeId=D.FieldValue AND Detail.AscIds=D.Ascids 
	WHERE D.Ascids>4
END
END;
--================================业务数据逻辑处理【END】=============================	
	
--================================数据汇总返回总数据【BEGIN】=============================	
IF @Cid=1
	BEGIN
		SET @SQL+='
		SELECT DISTINCT
			F.*,
			D.Cid,
			D.IniTotal QiChu,
			D.IniTotalFor QiChuFor,
			D.iniqty QiChuQty,
			D.iniqty QiChuForQty,
			
			D.IniYTotal NianChu,
			D.IniYTotalFor NianChuFor,
			D.IniYqty NianChuQty, 
			D.IniYqty NianChuForQty, 
			
			D.FDebit Borrow,
			D.FDebitFor BorrowFor,
			D.FDebitqty BorrowQty,
			D.FDebitqty BorrowForQty,
			
			D.FCredit Lend,
			D.FCreditFor LendFor,
			D.FCreditqty LendQty,
			D.FCreditqty LendForQty,
			D.FYTotal SunYi,
			D.FYTotalFor SunYiFor
		FROM #ATempData D
		INNER JOIN (
			SELECT D.STypeId,D.TypeId,D.GroupId'		
			SELECT @SQL=@SQL+',MAX(CASE WHEN D.Ascids='+CAST(AscIds AS VARCHAR(2))+' THEN F.TypeID ELSE '''' END) ['+AsUserCode+'TypeID]
							  ,MAX(CASE WHEN D.Ascids='+CAST(AscIds AS VARCHAR(2))+' THEN F.FullName ELSE '''' END) ['+FullName+']'
			FROM #AssistFullName
			SET @SQL+='
			FROM #ATempData D
			INNER JOIN #DetailsAssistFullName F ON F.STypeID=D.STypeId AND F.ATypeID=D.TypeId AND F.AscIds=D.Ascids AND F.TypeId=D.FieldValue
			WHERE D.Cid='+CAST(@Cid AS VARCHAR(2))+'
			GROUP BY D.STypeId,D.TypeId,D.GroupId
		) F ON F.STypeID=D.STypeId AND F.TypeID=D.TypeId AND F.GroupId=D.GroupId
		'
	END
ELSE 
	BEGIN
		SET @SQL+='
		SELECT DISTINCT
			F.*,
			D.Cid,
			D.IniTotal SelfQiChu,
			D.IniTotalFor OriQiChu,
			D.iniqty SelfQiChuQty,
			D.iniqty OriQiChuQty,
			
			D.IniYTotal SelfNianChu,
			D.IniYTotalFor OriNianChu,
			D.IniYqty SelfNianChuQty, 
			D.IniYqty OriNianChuQty, 
			
			D.FDebit SelfBorrow,
			D.FDebitFor OriBorrow,
			D.FDebitqty SelfBorrowQty,
			D.FDebitqty OriBorrowQty,
			
			D.FCredit SelfLend,
			D.FCreditFor OriLend,
			D.FCreditqty SelfLendQty,
			D.FCreditqty OriLendQty,
			D.FYTotal SelfSunYi,
			D.FYTotalFor OriSunYi
		FROM #ATempData D
		INNER JOIN (
			SELECT D.STypeId,D.TypeId,D.GroupId'		
			SELECT @SQL=@SQL+',MAX(CASE WHEN D.Ascids='+CAST(AscIds AS VARCHAR(2))+' THEN F.TypeID ELSE '''' END) ['+AsUserCode+'TypeID]
							  ,MAX(CASE WHEN D.Ascids='+CAST(AscIds AS VARCHAR(2))+' THEN F.FullName ELSE '''' END) ['+FullName+']'
			FROM #AssistFullName
			SET @SQL+='
			FROM #ATempData D
			INNER JOIN #DetailsAssistFullName F ON F.STypeID=D.STypeId AND F.ATypeID=D.TypeId AND F.AscIds=D.Ascids AND F.TypeId=D.FieldValue
			WHERE D.Cid='+CAST(@Cid AS VARCHAR(2))+'
			GROUP BY D.STypeId,D.TypeId,D.GroupId
		) F ON F.STypeID=D.STypeId AND F.TypeID=D.TypeId AND F.GroupId=D.GroupId
		'
	END
EXEC(@SQL)

--================================数据汇总返回总数据【END】=============================	
DROP TABLE #SType,#TempData,#AssistFullName,#DetailsAssistFullName,#ATempData


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryIniFactSerialFromDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryIniFactSerialFromDeal]
GO

/*
	作者：谢吉康
	日期：2016-07-08
	描述：查询实物库存期初序列号	
*/
CREATE PROCEDURE Web_QueryIniFactSerialFromDeal
(
	@serial			varchar(200),
	@querytype		int,
	@returnstring	varchar(2000) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PFullName		varchar(200),
		@KFullName		varchar(200)

SET @PFullName = ''
SET @KFullName = ''

IF @querytype = 0 	--物流期初序列号
	BEGIN
		SELECT TOP 1 @KFullName = s.fullname FROM gp_iniFactPtypeSerial Ini,stock s WHERE Ini.ktypeId=s.typeid and Ini.Serial = @serial and Ini.State = 7
		
		IF @KFullName <> ''
			BEGIN
				SET @returnstring = '期初存在于仓库【'+@KFullName+'】中'
				RETURN 0
			END
			
		SELECT TOP 1 @KFullName = p.fullname FROM gp_iniFactPtypeSerial Ini,Ptype p WHERE Ini.PtypeId=p.typeid and Ini.Serial = @serial and Ini.State IN(9,10,11,14,16,32)
		
		IF @KFullName <> ''
			BEGIN
				SET @returnstring = '期初处于受托未结算'
				RETURN 0
			END
		
		SELECT TOP 1 @PFullName = P.fullname FROM gp_iniFactPtypeSerial Ini,Ptype P WHERE Ini.PtypeId=P.typeid and Ini.Serial = @serial and Ini.State = 13
		
		
		IF @PFullName <> ''
			BEGIN
				SET @returnstring = '位于委托托代销期初库中'
				RETURN 0
			END

		SELECT TOP 1 @KFullName = s.fullname FROM gp_iniFactPtypeSerial Ini,stock s WHERE Ini.ktypeId=s.typeid and Ini.Serial = @serial and Ini.State = 25
		
		
		IF @KFullName <> ''
			BEGIN
				SET @returnstring = '期初存在于维修仓库【'+@KFullName+'】中'
				RETURN 0
			END
		
		SELECT TOP 1 @PFullName = P.fullname,@KFullName = K.FullName FROM gp_iniFactPtypeSerial Ini,Ptype P,Stock K WHERE Ini.PtypeId=P.typeid and ini.ktypeid = k.typeid and Ini.KtypeId<>'10000' and Ini.Serial = @serial and Ini.State = 1
			
		
		IF @PFullName <> ''
			BEGIN
				SET @returnstring = '期初存在于仓库【'+@KFullName+'】中'
				RETURN 0
			END
	END
ELSE				--借欠期初序列号
	BEGIN
		SELECT TOP 1 @KFullName = s.fullname FROM gp_iniFactPtypeSerial Ini,stock s WHERE Ini.ktypeId=s.typeid and Ini.Serial = @serial
		
		IF @@ROWCOUNT = 0
			SET @returnstring = ''
		ELSE
			SET @returnstring = '借欠期初存在于仓库【'+@KFullName+'】中'

		RETURN 0
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryIniFactStocksSerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryIniFactStocksSerial]
GO


/*
	作者：谢吉康
	日期：2016-07-07
	描述：查询实物库存期初序列号	
*/
CREATE PROCEDURE Web_QueryIniFactStocksSerial
(
	@serial			VARCHAR(max),
	@ptypeid		VARCHAR(max) = '',
	@returnstring	VARCHAR(max) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PFullName		varchar(200),
		@KFullName		varchar(200)

SET @PFullName = ''
SET @KFullName = ''

IF CHARINDEX('%', @serial, 0)>0
	BEGIN
		SET @Serial = Replace(@Serial,'[','')
		SET @Serial = Replace(@Serial,']','')
	END


SELECT TOP 1 @PFullName = P.fullname,@KFullName = s.fullname FROM gp_iniFactPtypeSerial Ini,stock s,PType p WHERE Ini.ktypeId=s.typeid AND Ini.PTypeId = P.TypeId and Ini.Serial = @serial and Ini.State = 7 AND P.typeId LIKE @ptypeid + '%'
IF @KFullName <> ''
	BEGIN
		SET @returnstring = '商品【'+@PFullName+'】期初存在于仓库【'+@KFullName+'】中'
		RETURN 0
	END


SELECT TOP 1 @PFullName = P.fullname,@KFullName = K.FullName FROM gp_iniFactPtypeSerial Ini,Ptype P,Stock K WHERE Ini.PtypeId=P.typeid and ini.ktypeid = k.typeid and Ini.KtypeId<>'10000' and Ini.Serial = @serial and Ini.State = 1 AND P.typeId LIKE @ptypeid + '%'

IF @PFullName <> ''
	BEGIN
		SET @returnstring = '商品【'+@PFullName+'】期初存在于仓库【'+@KFullName+'】中'
		RETURN 0
	END

SELECT TOP 1 @PFullName = P.fullname FROM GP_InOutPTypeSerial Ini,Ptype P WHERE Ini.PtypeId=P.typeid and Ini.Serial = @serial AND P.typeId LIKE @ptypeid + '%'
IF @PFullName <> ''
	BEGIN		
		SET @returnstring = '商品【'+@PFullName+'】'
		RETURN 0
	END

SELECT TOP 1 @PFullName = P.fullname FROM gp_FactPtypeSerial Ini,Ptype P WHERE Ini.PtypeId=P.typeid and Ini.Serial = @serial AND P.typeId LIKE @ptypeid + '%'
IF @PFullName <> ''
	BEGIN		
		SET @returnstring = '商品【'+@PFullName+'】'
		RETURN 0
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryIniSerial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryIniSerial]
GO










/*
	作者：谢吉康
	日期：2009-06-08
	描述：查询库存期初序列号	
*/
CREATE PROCEDURE Web_QueryIniSerial
(
	@serial			VARCHAR(max),
	@ptypeid		VARCHAR(max) = '',
	@returnstring	VARCHAR(max) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PFullName		varchar(200),
		@KFullName		varchar(200)

SET @PFullName = ''
SET @KFullName = ''

IF CHARINDEX('%', @serial, 0)>0
	BEGIN
		SET @Serial = Replace(@Serial,'[','')
		SET @Serial = Replace(@Serial,']','')
	END


SELECT TOP 1 @PFullName = P.fullname,@KFullName = s.fullname FROM gp_initPtypeSerial Ini,stock s,PType p WHERE Ini.ktypeId=s.typeid AND Ini.PTypeId = P.TypeId and Ini.Serial = @serial and Ini.State = 7 AND P.typeId LIKE @ptypeid + '%'
IF @KFullName <> ''
	BEGIN
		SET @returnstring = '商品【'+@PFullName+'】期初存在于仓库【'+@KFullName+'】中'
		RETURN 0
	END

SELECT TOP 1 @PFullName = P.fullname FROM gp_initPtypeSerial Ini,Ptype P WHERE Ini.PtypeId=P.typeid and Ini.Serial = @serial and Ini.State = 13 AND P.typeId LIKE @ptypeid + '%'

IF @PFullName <> ''
	BEGIN
		SET @returnstring = '商品【'+@PFullName+'】位于委托托代销期初库中'
		RETURN 0
	END

SELECT TOP 1 @PFullName = P.fullname,@KFullName = s.fullname FROM gp_initPtypeSerial Ini,stock s,PType p WHERE Ini.ktypeId=s.typeid AND P.TypeId = Ini.PTypeId and Ini.Serial = @serial and Ini.State = 25 AND P.typeId LIKE @ptypeid + '%'

IF @KFullName <> ''
	BEGIN
		SET @returnstring = '商品【'+@PFullName+'】期初存在于维修仓库【'+@KFullName+'】中'
		RETURN 0
	END

SELECT TOP 1 @PFullName = P.fullname,@KFullName = K.FullName FROM gp_initPtypeSerial Ini,Ptype P,Stock K WHERE Ini.PtypeId=P.typeid and ini.ktypeid = k.typeid and Ini.KtypeId<>'10000' and Ini.Serial = @serial and Ini.State = 1 AND P.typeId LIKE @ptypeid + '%'

IF @PFullName <> ''
	BEGIN
		SET @returnstring = '商品【'+@PFullName+'】期初存在于仓库【'+@KFullName+'】中'
		RETURN 0
	END

--借欠序列号
SELECT TOP 1 @PFullName = P.fullname,@KFullName = K.FullName FROM gp_initLendPtypeSerial Ini,Ptype P,Stock K WHERE Ini.PtypeId=P.typeid and ini.ktypeid = k.typeid and Ini.Serial = @serial AND P.typeId LIKE @ptypeid + '%'
IF @PFullName <> ''
	BEGIN
		SET @returnstring = '商品【'+@PFullName+'】'
		RETURN 0
	END

SELECT TOP 1 @PFullName = P.fullname FROM GP_InOutPTypeSerial Ini,Ptype P WHERE Ini.PtypeId=P.typeid and Ini.Serial = @serial AND P.typeId LIKE @ptypeid + '%'
IF @PFullName <> ''
	BEGIN		
		SET @returnstring = '商品【'+@PFullName+'】'
		RETURN 0
	END

SELECT TOP 1 @PFullName = P.fullname FROM gp_LendPtypeSerial Ini,Ptype P WHERE Ini.PtypeId=P.typeid and Ini.Serial = @serial AND P.typeId LIKE @ptypeid + '%'
IF @PFullName <> ''
	BEGIN		
		SET @returnstring = '商品【'+@PFullName+'】'
		RETURN 0
	END

SELECT TOP 1 @PFullName = P.fullname FROM gp_CruPtypeSerial Ini,Ptype P WHERE Ini.PtypeId=P.typeid and Ini.Serial = @serial AND P.typeId LIKE @ptypeid + '%'
IF @PFullName <> ''
	BEGIN		
		SET @returnstring = '商品【'+@PFullName+'】'
		RETURN 0
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryIniSerialFromDeal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryIniSerialFromDeal]
GO








/*
	作者：谢吉康
	日期：2009-06-08
	描述：查询库存期初序列号	
*/
CREATE PROCEDURE Web_QueryIniSerialFromDeal
(
	@serial			varchar(200),
	@querytype		int,
	@returnstring	varchar(2000) OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @PFullName		varchar(200),
		@KFullName		varchar(200)

SET @PFullName = ''
SET @KFullName = ''

IF @querytype = 0 	--物流期初序列号
	BEGIN
		SELECT TOP 1 @KFullName = s.fullname FROM gp_initPtypeSerial Ini,stock s WHERE Ini.ktypeId=s.typeid and Ini.Serial = @serial and Ini.State = 7
		
		IF @KFullName <> ''
			BEGIN
				SET @returnstring = '期初存在于仓库【'+@KFullName+'】中'
				RETURN 0
			END
			
			SELECT TOP 1 @KFullName = p.fullname FROM gp_initPtypeSerial Ini,Ptype p WHERE Ini.PtypeId=p.typeid and Ini.Serial = @serial and Ini.State IN(9,10,11,14,16,32)
		
		IF @KFullName <> ''
			BEGIN
				SET @returnstring = '期初处于受托未结算'
				RETURN 0
			END
		
		SELECT TOP 1 @PFullName = P.fullname FROM gp_initPtypeSerial Ini,Ptype P WHERE Ini.PtypeId=P.typeid and Ini.Serial = @serial and Ini.State = 13
		
		
		IF @PFullName <> ''
			BEGIN
				SET @returnstring = '位于委托托代销期初库中'
				RETURN 0
			END

		SELECT TOP 1 @KFullName = s.fullname FROM gp_initPtypeSerial Ini,stock s WHERE Ini.ktypeId=s.typeid and Ini.Serial = @serial and Ini.State = 25
		
		
		IF @KFullName <> ''
			BEGIN
				SET @returnstring = '期初存在于维修仓库【'+@KFullName+'】中'
				RETURN 0
			END
		
		SELECT TOP 1 @PFullName = P.fullname,@KFullName = K.FullName FROM gp_initPtypeSerial Ini,Ptype P,Stock K WHERE Ini.PtypeId=P.typeid and ini.ktypeid = k.typeid and Ini.KtypeId<>'10000' and Ini.Serial = @serial and Ini.State = 1
			
		
		IF @PFullName <> ''
			BEGIN
				SET @returnstring = '期初存在于仓库【'+@KFullName+'】中'
				RETURN 0
			END
	END
ELSE				--借欠期初序列号
	BEGIN
		SELECT TOP 1 @KFullName = s.fullname FROM gp_initlendptypeserial Ini,stock s WHERE Ini.ktypeId=s.typeid and Ini.Serial = @serial
		
		IF @@ROWCOUNT = 0
			SET @returnstring = ''
		ELSE
			SET @returnstring = '借欠期初存在于仓库【'+@KFullName+'】中'

		RETURN 0
	END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





GO
IF EXISTS(SELECT TOP 1 1 FROM SYSOBJECTS WHERE id = object_id(N'Web_QueryIniSockAge') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC Web_QueryIniSockAge
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
--库龄期初查询
CREATE PROC Web_QueryIniSockAge
(
	 @Type                  INT=1,			--1 仓库 2 分支机构 3 集团
	 --@StypeID               VARCHAR(MAX)='',     
	 @KtypeID               VARCHAR(MAX)='',  
	 @PtypeID               VARCHAR(50)='',
	 @OperatorID			VARCHAR(100)
)
--@encode$--
AS
BEGIN

	CREATE TABLE #TempIniStockAgeStock
	(
		ID			INT,
		InStockDate VARCHAR(50),
		StockAge	NUMERIC(24,10),
		Qty			NUMERIC(24,10),
		Total		NUMERIC(24,10)
	)
	IF @Type = 1 
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.IniStockAgeStock) --仓库 
		BEGIN
			INSERT INTO #TempIniStockAgeStock(id,InStockDate,StockAge,Qty,Total )	
			SELECT id,InStockDate,StockAge,Qty,Total FROM IniStockAgeStock WHERE KtypeID=@KtypeID AND PtypeID = @PtypeID
		END
	END
	ELSE IF @Type = 2
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.IniStockAgeStype)--分支机构
		BEGIN
			DECLARE	@StypeID VARCHAR(MAX)=''
			SELECT @StypeID = STypeID FROM dbo.Stock WHERE typeId=@KtypeID
			INSERT INTO #TempIniStockAgeStock(id,InStockDate,StockAge,Qty,Total )	
			SELECT a.id,a.InStockDate,a.StockAge,a.Qty,a.Total 
			FROM IniStockAgeStype a JOIN ( SELECT * FROM dbo.F_GetManDetailKTypeSType(@OperatorID) WHERE STypeId = @StypeID) b
			ON a.KtypeID = b.TypeId
			AND a.PtypeID = @PtypeID
		END
	END
	ELSE IF @Type = 3
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.IniStockAgeGroup) --集团
		BEGIN
			INSERT INTO #TempIniStockAgeStock(id,InStockDate,StockAge,Qty,Total )	
			SELECT id,InStockDate,StockAge,Qty,Total FROM IniStockAgeGroup WHERE PtypeID = @PtypeID
		END
	END
	SELECT * FROM #TempIniStockAgeStock
	DROP TABLE #TempIniStockAgeStock
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInitTeAccountTransit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInitTeAccountTransit]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

--===========================================
--date:2016-02-01
--by:glj
--function:期初企业未达账 、期初银行未达账
--===========================================
CREATE PROCEDURE Web_QueryInitTeAccountTransit
(	
	@Type				INT,			--0：期初银行 1：期初企业
	@STypeID			VARCHAR(50),	--分支机构ID
	@OperatorId			VARCHAR(50),	--操作员
	@BankAccountID		INT,			--银行账户ID
	@SorBType			INT				--1：分支机构  2：具体的银行账户
)
--@encode$--
AS
SET NOCOUNT ON

IF(@SorBType=2)
	SELECT @STypeID=STypeId FROM Te_BankAccount WHERE Id=@BankAccountID 
	
BEGIN--处理会计科目多级权限
	CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200))
	INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName) 
	SELECT L.Typeid,L.Stypeid,A.FullName FROM F_LineAccount(@OperatorID,@STypeID) L
	INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
	WHERE A.Deleted<>'1' 
END;

SELECT	
	CASE WHEN T8.Id IS NULL THEN 0 ELSE 1 END AS IsCheck,
	CASE WHEN T8.Id IS NULL THEN '' ELSE '√' END AS checkrelevance,
	T1.Id IndexId,
	T1.Type,
	T3.StypeId,
	T1.ATypeId,
	T1.IsInit,
	T3.AccountNumber,
	T3.Id,
	T2.Id AS RowId,
	T3.FullName,
	ISNULL(T4.FullName,'****') AS atypename,
	T2.CreateDate,
	T2.Summary,
	T2.ETypeId,
	T5.FullName AS EFullName,
	T2.FSettleId,
	ISNULL(T6.FullName,'') AS FSFullName,
	T2.FSettleNo,
	T2.FDebit,
	T2.FCredit,
	T7.CId,
	T7.FullName AS cidname,
	A.Cid CidID
FROM dbo.Te_AccountInTransit_Index T1
INNER JOIN dbo.Te_AccountInTransit_Detail T2 ON T1.id = T2.IndexId
INNER JOIN dbo.Te_BankAccount T3 ON T1.AccountId = T3.Id
INNER JOIN Ac_Account A ON A.StypeId=T3.STypeId AND A.TypeId=T3.ATypeId
LEFT JOIN #Ac_Account_L T4 ON T3.ATypeId = T4.TypeId AND T3.STypeId = T4.StypeId
INNER JOIN dbo.employee T5 ON T2.ETypeId = T5.typeId
LEFT JOIN dbo.Ac_BalanceType T6 ON T2.FSettleId = T6.BtId
INNER JOIN dbo.Ac_Currency T7 ON T1.Cid = T7.CId
LEFT JOIN Te_CheckRelevance T8 ON (@Type=1 AND T8.StatementAccountInTransitId=T1.Id) OR (@Type=0 AND T8.JournalAccountInTransitId=T1.Id) 
WHERE 
	T1.Type = @Type 
	AND T1.IsInit = 1
	AND ((@SorBType=1 AND T3.STypeId=@STypeID) OR (@SorBType=2 AND T3.Id=@BankAccountID))
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInnerArDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryInnerArDetail
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-17
	描述：内部应收查询明细表
*/

CREATE PROCEDURE Web_QueryInnerArDetail
(
	@OperatorId		VARCHAR(100),	--操作员ID
	@StartDate		VARCHAR(20),	--开始日期
	@EndDate		VARCHAR(20),	--截止日期
	@STypeId		VARCHAR(MAX),	--分支机构
	@DSTypeId		VARCHAR(MAX),	--对于分支机构
	@ShowredWord	VARCHAR(10)		--是否显示红冲单据
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
IF @STypeId = '00000'
	SET @STypeId = ''
	
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--对应分支机构
CREATE TABLE #GetManDSTypeId(TypeId	varchar(100))
INSERT INTO #GetManDSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,'00001')	
	
--分支机构所对应的仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM Stock WHERE sonnum = 0 AND typeId In (SELECT typeId FROM F_GetAllManagerBaseTypeId('',4,'00001')) AND STypeId IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID))
	
--对应分支机构所对应的仓库
CREATE TABLE #GetManDKTypeId(TypeId	varchar(100))
INSERT INTO #GetManDKTypeId(TypeId) SELECT TypeId FROM Stock WHERE sonnum = 0 AND typeId In (SELECT typeId FROM F_GetAllManagerBaseTypeId('',4,'00001')) AND STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,'00001'))

DECLARE @SQL VARCHAR(MAX)
DECLARE @WhereSQL VARCHAR(MAX)
SET @WhereSQL=''
IF @ShowredWord=0
  BEGIN
       SET @WhereSQL=' AND M.Audited=1 '
  END
  
 CREATE TABLE #Result 
 (
	BillNumberId int ,
	BillDate varchar(50),
	BillCode varchar(50),
	BillType int,
	comment varchar(5000),
	RedWord int,
	ArAdd numeric(24,10),
	ArReduce numeric(24,10)
 )
  
  
  
SET @SQL = 'INSERT INTO #Result
			SELECT	B.BillNumberId,
					CONVERT(VARCHAR(10),B.BillDate,120),
					B.BillCode,
					B.BillType,
					B.comment,
					B.RedWord,
					CASE
						WHEN B.RedWord IN (0) THEN SUM(M.ArAdd)
						WHEN B.RedWord IN (1) THEN SUM(M.ArAdd)
						WHEN B.RedWord IN (2) THEN SUM(M.ArReduce)
						ELSE 0 
					END AS ArAdd,
					CASE
						WHEN B.RedWord IN (0) THEN SUM(M.ArReduce)
						WHEN B.RedWord IN (1) THEN SUM(M.ArReduce)
						WHEN B.RedWord IN (2) THEN SUM(M.ArAdd)
						ELSE 0
					END AS ArReduce
			FROM	BillIndex B					
			INNER JOIN (
							SELECT	BillNumberId,
									CASE WHEN BillType = 187 THEN Total ELSE 0 END AS ArAdd,
									0 AS ArReduce
							FROM	STypeMoveBill
							WHERE	(KTypeId IN (SELECT TypeId FROM #GetManKTypeId)	AND KTypeId2 IN (SELECT TypeId FROM #GetManDKTypeId))									
									AND BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 187 AND IfCheck = ''t'' AND Draft = 0)
							UNION ALL
							SELECT	BillNumberId,
									0 AS ArAdd,
									CASE WHEN BillType = 188 THEN ISNULL(Total,0) ELSE 0 END AS ArReduce
							FROM	STypeMoveBill
							WHERE	KTypeId2 IN (SELECT TypeId FROM #GetManKTypeId) AND KTypeId IN (SELECT TypeId FROM #GetManDKTypeId)												
									AND BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 188 AND IfCheck = ''t'' AND Draft = 0)
							UNION ALL
							SELECT	M.BillNumberId,
									CASE WHEN Total>0 AND M.Audited=1 THEN abs(TOTAL) WHEN Total>0 AND M.Audited=0 THEN TOTAL ELSE 0 END AS ArAdd,
									CASE WHEN Total<0 AND M.Audited=1 THEN abs(TOTAL) WHEN Total<0 AND M.Audited=0 THEN TOTAL ELSE 0 END AS ArReduce
							FROM	ListTable M
							INNER JOIN    AC_Items AC ON M.atypeid=AC.nid			
							WHERE	m.STypeId IN (SELECT TypeId FROM #GetManSTypeId) AND m.STypeId2 IN (SELECT TypeId FROM #GetManDSTypeId)
									AND AC.UserCode = ''1132''			
									AND M.BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 159 AND IfCheck = ''t'' AND Draft = 0)
									'+@WhereSQL+'
							/*UNION ALL
							SELECT	M.BillNumberId,
									0 AS ArAdd,
									M.D_Total AS ArReduce
							FROM	AccountCredence M
							INNER JOIN    AC_Items AC ON M.TypeATypeId=AC.nid								
							WHERE	M.STypeId IN (SELECT TypeId FROM #GetManSTypeId) AND M.ATypeId IN (SELECT TypeId FROM #GetManDSTypeId)
									AND AC.UserCode = ''1132''
									AND M.BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 159 AND IfCheck = ''t'' AND Draft = 0)*/						
			)M ON B.BillNumberId = M.BillNumberId
			WHERE	B.BillDate>='''+@StartDate+'''
					AND B.BillDate<='''+@EndDate+'''					
					AND B.IfCheck = ''t''
					AND B.BillType IN (187,188,159)	 
					AND B.ifYearBill= 0
			'
IF @ShowredWord = '1'
	SET @SQL = @SQL + ' AND B.RedWord IN (0,1,2)'
ELSE
	SET @SQL = @SQL + ' AND B.RedWord = 0'
	
SET @SQL = @SQL + ' GROUP BY B.BillNumberId,
							 B.BillDate,
							 B.BillCode,
							 B.BillType,
							 B.comment,
							 B.RedWord
					ORDER BY B.BillDate '
				
					
SET @SQL+='	
			INSERT INTO #Result
			SELECT	B.BillNumberId,
					CONVERT(VARCHAR(10),B.BillDate,120),
					B.BillCode,
					B.BillType,
					B.comment,
					B.RedWord,
					CASE
						WHEN B.RedWord IN (0) THEN SUM(M.ArAdd)
						WHEN B.RedWord IN (1) THEN SUM(M.ArAdd)
						WHEN B.RedWord IN (2) THEN SUM(M.ArReduce)
						ELSE 0 
					END AS ArAdd,
					CASE
						WHEN B.RedWord IN (0) THEN SUM(M.ArReduce)
						WHEN B.RedWord IN (1) THEN SUM(M.ArReduce)
						WHEN B.RedWord IN (2) THEN SUM(M.ArAdd)
						ELSE 0
					END AS ArReduce
			FROM	Coupon_BillIndex B					
			INNER JOIN (
							SELECT	cb.BillNumberId,
									CASE WHEN BillType = 429 THEN Total ELSE 0 END AS ArAdd,
									0 AS ArReduce
							FROM	Coupon_AllotBillStype cabs
									INNER JOIN Coupon_BillIndex cb on cabs.billnumberid=cb.billnumberid
									inner join #GetManKTypeId k on cb.outKtypeid=k.typeid
									inner join #GetManDKTypeId k1 on cb.inktypeid=k1.typeid
							where cb.BillType=429 and cb.IfCheck = ''t'' AND Draft = 0
							UNION ALL
							SELECT	cb.BillNumberId,
									0 AS ArAdd,
									CASE WHEN BillType = 428 THEN ISNULL(Total,0) ELSE 0 END AS ArReduce
							FROM	Coupon_AllotBillStype cabs
									INNER JOIN Coupon_BillIndex cb on cabs.billnumberid=cb.billnumberid
									inner join #GetManKTypeId k on cb.inktypeid=k.typeid
									inner join #GetManDKTypeId k1 on cb.outktypeid=k1.typeid
							where cb.BillType=428 and cb.IfCheck = ''t'' AND Draft = 0
							UNION ALL
							SELECT	M.BillNumberId,
									CASE WHEN Total>0 AND M.Audited=1 THEN abs(TOTAL) WHEN Total>0 AND M.Audited=0 THEN TOTAL ELSE 0 END AS ArAdd,
									CASE WHEN Total<0 AND M.Audited=1 THEN abs(TOTAL) WHEN Total<0 AND M.Audited=0 THEN TOTAL ELSE 0 END AS ArReduce
							FROM	ListTable M
							INNER JOIN    AC_Items AC ON M.atypeid=AC.nid			
							WHERE	m.STypeId IN (SELECT TypeId FROM #GetManSTypeId) AND m.STypeId2 IN (SELECT TypeId FROM #GetManDSTypeId)
									AND AC.UserCode = ''1132''			
									AND M.BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 159 AND IfCheck = ''t'' AND Draft = 0)
									'+@WhereSQL+'
							/*UNION ALL
							SELECT	M.BillNumberId,
									0 AS ArAdd,
									M.D_Total AS ArReduce
							FROM	AccountCredence M
							INNER JOIN    AC_Items AC ON M.TypeATypeId=AC.nid								
							WHERE	M.STypeId IN (SELECT TypeId FROM #GetManSTypeId) AND M.ATypeId IN (SELECT TypeId FROM #GetManDSTypeId)
									AND AC.UserCode = ''1132''
									AND M.BillNumberId IN (SELECT BillNumberId FROM BillIndex WHERE BillType = 159 AND IfCheck = ''t'' AND Draft = 0)*/						
			)M ON B.BillNumberId = M.BillNumberId
			WHERE	B.BillDate>='''+@StartDate+'''
					AND B.BillDate<='''+@EndDate+'''					
					AND B.IfCheck = ''t''
					AND B.BillType IN (428,429,159)	 
					AND B.ifYearBill= 0 '
										
IF @ShowredWord = '1'
	SET @SQL = @SQL + ' AND B.RedWord IN (0,1,2)'
ELSE
	SET @SQL = @SQL + ' AND B.RedWord = 0'
	
SET @SQL = @SQL + ' GROUP BY B.BillNumberId,
							 B.BillDate,
							 B.BillCode,
							 B.BillType,
							 B.comment,
							 B.RedWord
					ORDER BY B.BillDate '	

PRINT(@SQL)
EXEC(@SQL)

SELECT * FROM #Result ORDER BY BillDate

DROP TABLE #GetManKTypeId,#GetManDKTypeId,#GetManSTypeId,#GetManDSTypeId,#Result

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInnerArLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].Web_QueryInnerArLine
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-13
	描述：内部分支机构应收线性表
	EXEC Web_QueryInnerArLine '00001','00000',''
*/

CREATE PROCEDURE Web_QueryInnerArLine
(
	@OperatorId			VARCHAR(100),
	@STypeId			VARCHAR(MAX),	--分支机构
	@DSTypeId			VARCHAR(MAX)	--对应分支机构
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @SQL		VARCHAR(MAX),
		@SonNum		INT,
		@STypeIdMx	VARCHAR(MAX)
		
IF @STypeId = '00000' 
	SET @STypeIdMx = '%'				
ELSE	
	SET @STypeIdMx = @STypeId

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
	END

--对方分支机构
CREATE TABLE #GetManSTypeId2(TypeId	varchar(100))
IF NOT (@DSTypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,@OperatorID)	
	END

SET @SQL = 'SELECT	B.TypeId,
					B.SonNum,
					B.UserCode,
					B.Total
			FROM	(
						SELECT	S.TypeId,
								S.SonNum,
								S.UserCode,
								SUM(ISNULL(M.InnerArTotal,0)) AS Total
						FROM	F_GetManSTypeAll('''+@OperatorId+''') S
						LEFT JOIN (
							SELECT	I.STypeId2 AS STypeId,
									SUM(I.InnerArTotal) AS InnerArTotal
							FROM	SType_InnerARTotal I '
							
						IF NOT (@STypeId = '' AND @MStypeid = '00000')
							SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId S ON I.STypeId = S.TypeId '						

						IF NOT (@DSTypeId = '' AND @MStypeid = '00000')
							SET @SQL = @SQL + ' INNER JOIN #GetManSTypeId2 D ON I.STypeId2 = D.TypeId '					
								
						SET @SQL = @SQL + '					
							WHERE	I.STypeId LIKE '''+@STypeIdMx+'%''
							GROUP BY I.STypeID2
						)M ON LEFT(M.STypeId,Len(S.TypeId)) = S.TypeId 
						WHERE	S.TypeId LIKE '''+@STypeIdMx+'%''
								AND S.SonNum = 0					
						GROUP BY S.TypeId,
								 S.SonNum,
								 S.UserCode
			)B
			WHERE	ISNULL(B.Total,0)<>0
			ORDER BY B.UserCode '	
			
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManSTypeId2

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInnerArList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInnerArList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-01-13
	描述：内部分支机构历史应收树型表
	EXEC Web_QueryInnerArList '00001','00000',''
*/

CREATE PROCEDURE Web_QueryInnerArList
(
	@OperatorId			VARCHAR(100),
	@STypeId			VARCHAR(MAX),	--分支机构
	@DSTypeId			VARCHAR(MAX)	--对应分支机构	
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @SQL		VARCHAR(MAX),
		@SonNum		INT,
		@STypeIdMx	VARCHAR(MAX)
		
IF @STypeId = '00000' 
	SET @STypeIdMx = '%'				
ELSE	
	SET @STypeIdMx = @STypeId
	
IF @DSTypeId = ''
	SET @DSTypeId = '00000'	
		
SELECT @SonNum = SonNum FROM SType WHERE TypeId = @DSTypeId		

--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)

--对应分支机构
CREATE TABLE #GetManDSTypeId(TypeId	varchar(100))
INSERT INTO #GetManDSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DSTypeId,11,'00001')

SET @SQL = '
            SELECT	S.TypeId,
					S.SonNum,
					S.UserCode,
					SUM(ISNULL(M.Total,0)) AS Total
			FROM	F_GetManSTypeAll(''00001'') S
			INNER JOIN #GetManDSTypeId MS ON MS.TypeId = S.TypeId
			LEFT JOIN (
							SELECT	STypeId2 AS STypeId,
									ISNULL(SUM(InnerArTotal),0) AS Total
							FROM	SType_InnerARTotal
							WHERE	STypeId IN (SELECT TypeId FROM #GetManSTypeId)									
							GROUP BY STypeId2
			)M ON M.STypeId = S.TypeId
			WHERE	S.SonNum = 0
			GROUP BY S.TypeId,
					 S.SonNum,
					 S.UserCode
			ORDER BY S.UserCode
			 '	
			
--PRINT(@SQL)
EXEC(@SQL)

DROP TABLE #GetManSTypeId,#GetManDSTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInsuranceAuto]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInsuranceAuto]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-04-26
	描述：保险车辆档案
*/
CREATE PROCEDURE Web_QueryInsuranceAuto
(
	@OperatorId			VARCHAR(MAX),		--操作员ID
	@wcitypeid			VARCHAR(MAX),		--车牌号
	@stypeid			VARCHAR(MAX),		--分支机构
	@bxxm				VARCHAR(MAX),		--保险项目
	@bxtotal			VARCHAR(MAX),		--保险金额
	@DqDate				VARCHAR(MAX),		--到期日期
	@BillNo				VARCHAR(MAX),		--保险单号
	@CardNumber			VARCHAR(MAX),		--证件号码
	@Comment			VARCHAR(MAX),		--备     注
	@Mobile				VARCHAR(MAX),		--手机号码
	@nType				VARCHAR(MAX),		--类型 q:查询 a:新增 m:修改 d:删除
	@InsuranceAutoId	VARCHAR(MAX)='-1'	--ID	
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @Msg		VARCHAR(MAX),
		@FullName	VARCHAR(MAX),
		@ID			VARCHAR(MAX)

--查询
IF @nType = 'q'
	BEGIN
		SELECT	A.*,
				R.BTypeID
		FROM	Qp_InsuranceAuto A
		INNER JOIN QP_RepairAutoInfo R ON A.RaTypeID = R.TypeID
		WHERE	A.STypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',11,@OperatorID))
				AND R.BTypeID IN (SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID))
 		ORDER BY A.InsuranceAutoId ASC
	END

--新增、复制新增
IF @nType = 'a' OR @nType = 'c'
	BEGIN		
		INSERT INTO Qp_InsuranceAuto
		(
			RaTypeID,
			STypeID,
			InsuranceName,
			InsuranceTotal,
			ReachDate,
			InsuranceNo,
			CardNumber,
			Comment,
			Mobile
		)VALUES(
			@wcitypeid,
			@stypeid,
			@bxxm,
			@bxtotal,
			@DqDate,
			@BillNo,
			@CardNumber,
			@Comment,
			@Mobile
		)
		
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息添加失败！',16,1)
				RETURN -2
			END			
	END	
	
--修改
IF @nType = 'm'
	BEGIN	
		IF NOT EXISTS(SELECT TOP 1 1 FROM Qp_InsuranceAuto WHERE InsuranceAutoId = @InsuranceAutoId)		
			BEGIN
				RAISERROR('基本信息记录不存在！',16,1)
				RETURN -2				
			END
			
		UPDATE	Qp_InsuranceAuto
		SET		RaTypeID = @wcitypeid,
				STypeId  = @stypeid,
				InsuranceName = @bxxm,
				InsuranceTotal = @bxtotal,
				ReachDate = @DqDate,
				InsuranceNo = @BillNo,
				CardNumber = @CardNumber,
				Comment = @Comment,
				Mobile  = @Mobile
		WHERE	InsuranceAutoId = @InsuranceAutoId
		
		IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('基本信息修改失败！',16,1)
				RETURN -2
			END			
	END
	
RETURN 0	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInsuranceExpireQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInsuranceExpireQuery]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：赵斌
	日期：2011-05-05
	描述：保险到期车辆提醒
*/
CREATE PROCEDURE Web_QueryInsuranceExpireQuery
(
	@OperatorId		VARCHAR(MAX),	--操作员ID
	@StartDate		VARCHAR(MAX),	--开始日期
	@EndDate		VARCHAR(MAX),	--截止日期
	@STypeId		VARCHAR(MAX),	--分支机构
	@WciTypeId		VARCHAR(MAX),	--车牌号
	@BTypeId		VARCHAR(MAX)	--往来单位
)
--@encode$--
AS
SET NOCOUNT ON

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid varchar(50), @MBtypeid varchar(50), @MBtypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--分支机构
CREATE TABLE #GetManSTypeId(TypeId	varchar(100))
INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	

--往来单位
CREATE TABLE #GetManBTypeId(TypeId	varchar(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@BTypeId,2,@OperatorID)	

--车牌号
CREATE TABLE #GetManWTypeId(TypeId	varchar(100))
INSERT INTO #GetManWTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@WciTypeId,12,'00001')

DECLARE @SQL VARCHAR(MAX)

SELECT  I.STypeID,		--分支机构
		I.RaTypeID,		--车牌号
		I.Mobile,
		RA.BTypeID,		--往来单位
		I.InsuranceName,--保险项目
		I.InsuranceTotal,--保险金额
		I.ReachDate,	--到期日期
		I.InsuranceNo,	--保险单号
		bt.LinkMan1,	--联系人1
		bt.FullName,	--客服名称
		I.Comment,
		I.Mobile as LinkMobile1	--手机号码	
FROM	Qp_InsuranceAuto	I
INNER	JOIN	QP_RepairAutoInfo	RA	ON	I.RaTypeID = RA.TypeID
INNER	JOIN	#GetManSTypeId	S	ON	I.STypeID = S.TypeId
INNER	JOIN	#GetManBTypeId	B	ON	Ra.BTypeID	=	B.TypeId
INNER	JOIN	btype			bt	ON	B.TypeId	=	bt.typeId
INNER	JOIN	#GetManWTypeId	W	ON	I.RaTypeID	=	W.TypeId
WHERE	I.ReachDate >=	@StartDate
		AND	I.ReachDate	<=	@EndDate
ORDER BY I.ReachDate,I.RaTypeID ASC

DROP TABLE #GetManSTypeId,#GetManBTypeId,#GetManWTypeId

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryInventoryTypeList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryInventoryTypeList
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回存货类型列表
-- 时间：	2016-04-27
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryInventoryTypeList
(
	@Stypeid VARCHAR(400)	--分支结构
)

--@encode$--
AS
SET NOCOUNT ON 

SELECT
	T.NID,
	T.UserCode,
	T.FullName,
	D.STypeID,
	S.FullName SFullName,
	D.StockATypeID,
	A1.FullName StockFullName,
	D.IncomeATypeID,
	A2.FullName IncomeFullName,
	D.CostATypeID,
	A3.FullName CostFullName,
	T.Comment
FROM Ac_InventoryType T
RIGHT JOIN Ac_InventoryTypeDetails D ON D.TID=T.NID
INNER JOIN SType S ON S.TypeId=D.STypeID
INNER JOIN Ac_Account A1 ON A1.StypeId=D.STypeID AND A1.TypeId=D.StockATypeID
INNER JOIN Ac_Account A2 ON A2.StypeId=D.STypeID AND A2.TypeId=D.IncomeATypeID
INNER JOIN Ac_Account A3 ON A3.StypeId=D.STypeID AND A3.TypeId=D.CostATypeID
WHERE 
	((@Stypeid<>'' AND D.STypeID=@Stypeid) OR @Stypeid='')
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryInventtoryTypeDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC [dbo].Web_QueryInventtoryTypeDetails
GO          
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	返回存货类型列表
-- 时间：	2016-04-27
-- 作者：	glj
-- ========================================================================
CREATE PROC Web_QueryInventtoryTypeDetails
(
	@TID			INT,			--类型ID
    @OperatorID		VARCHAR(50)		-- 操作员
)

--@encode$--
AS
SET NOCOUNT ON 
IF(@TID=0)
	BEGIN
		SELECT 
			DISTINCT
			0 nid,
			0 TId,
			S.VerifyID,
			s.TypeId STypeId,
			s.FullName SFullName,
			'' StockATypeID,
			'' StockFullName,
			'' IncomeATypeID,
			'' IncomeFullName,
			'' CostATypeID,
			'' CostFullName
		FROM SType S
		INNER JOIN dbo.F_GetAllManagerBaseTypeId('',11,@OperatorID) F ON F.TypeId=S.TypeId AND S.deleted=0
	END
ELSE 
	BEGIN
		--处理会计科目多级权限
		CREATE TABLE #Ac_Account_L (TypeId VARCHAR(50),StypeId VARCHAR(50),FullName VARCHAR(200))
		INSERT INTO #Ac_Account_L (Typeid,StypeId,FullName) 
		SELECT L.Typeid,L.Stypeid,A.FullName FROM F_LineAccount(@OperatorID,'') L
		INNER JOIN Ac_Account A ON A.TypeId=L.Typeid AND L.Stypeid=A.StypeId
		SELECT
			DISTINCT
			D.NID,
			D.TID,
			S.VerifyID,
			D.STypeId,
			S.FullName SFullName,
			D.StockATypeID,
			CASE WHEN ISNULl(D.StockATypeID,'')='' THEN '' ELSE  ISNULL(a.FullName,'****') END StockFullName,
			D.IncomeATypeID,
			CASE WHEN ISNULl(D.IncomeATypeID,'')='' THEN '' ELSE  ISNULL(a1.FullName,'****') END IncomeFullName,
			D.CostATypeID,
			CASE WHEN ISNULl(D.CostATypeID,'')='' THEN '' ELSE  ISNULL(a2.FullName,'****') END CostFullName
		FROM Base_InventoryTypeDetails D
		INNER JOIN dbo.F_GetAllManagerBaseTypeId('',11,@OperatorID) F ON F.TypeId=D.STypeId
		INNER JOIN SType S ON S.TypeId=D.STypeId AND S.SonNum=0
		LEFT JOIN #Ac_Account_L a ON a.typeId=D.StockATypeID AND a.StypeId=s.VerifyID
		LEFT JOIN #Ac_Account_L a1 ON a1.TypeId=D.IncomeATypeID  AND a1.StypeId=s.VerifyID
		LEFT JOIN #Ac_Account_L a2 ON a2.TypeId=D.CostATypeID AND a2.StypeId=s.VerifyID
		WHERE D.TID=@TID
	END
 GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInVoiceBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInVoiceBill]
GO













/*
	作者：谢吉康
	日期：2007-11-27
	描述：发票管理
	SELECT * FROM InVoiceBill
*/
CREATE PROCEDURE Web_QueryInVoiceBill
(
	@OperatorID				varchar(100),
	@chvStartDate			varchar(20),
	@chvEndDate				varchar(20),
	@chvInvoiceStartDate	varchar(20),
	@chvInvoiceEndDate		varchar(20),
	@BillType				varchar(10),
	@chvBTypeID				varchar(100),
	@chvETypeID				varchar(100),
	@chvKTypeID				varchar(100),
	@chvPTypeID				varchar(100),
	@BillCode				varchar(256),
	@chrCom					varchar(256),
	@chrNote				varchar(256),
	@chrDraft				varchar(10),
	@chrAudit				varchar(10),
	@chrShowAll				varchar(10),
	@chvInvoiceFlag			varchar(10),
	@chvInvoiceStyle		varchar(10),
	@txtETypeNameI			varchar(100),
	@InvoiceNo				varchar(200)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId varchar(50), @MBTypeid varchar(50), @MBTypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @chvBTypeID = '00000'
	SET @chvBTypeID = '%'

IF @chvPTypeID = '00000'
	SET @chvPTypeID = '%'

IF @chvKTypeID = '00000'
	SET @chvKTypeID = '%'

IF @BillType = '0'
	SET @BillType = '%'

IF @chvInvoiceFlag = '2'
	SET @chvInvoiceFlag = '%'

IF @chvInvoiceStyle = '4'
	SET @chvInvoiceStyle = '%'

DECLARE @SQL varchar(8000)
SET @SQL = '
	SELECT	Bil.BillNumberId,
			Bil.BillCode,
			Bil.BillDate,
			Bil.BillType,
			Bil.IfCheck,
			Bil.RedWord,
			BTypeId = (SELECT FullName FROM BType WHERE TypeId = Bil.BTypeId),
			ETypeId = (SELECT FullName FROM Employee WHERE TypeId = Bil.ETypeId),
			KTypeId = (SELECT FullName FROM Stock WHERE TypeId = Bil.KTypeId),
			Bil.TotalMoney,
			Bil.TotalInMoney+Bil.CompleteTotal AS SFJE,
			ISNULL(I.KPJE,0) AS HJKPJE,
			ISNULL(Bil.TotalMoney,0) - ISNULL(I.KPJE,0) AS WKPJE,
			ISNULL(I.NKPJE,0) AS NKPJE,
			Bil.Comment
	FROM	BillIndex Bil
	INNER JOIN (
		SELECT	BillNumberId,
				SUM(
					CASE
						WHEN IfInVoice = 1 THEN InVoiceTotal
						ELSE InVoiceTotal
					END
				) AS KPJE,
				SUM(
					CASE
						WHEN IfInVoice = 0 THEN InVoiceTotal
						ELSE 0
					END
				) AS NKPJE
		FROM	InVoiceBill
		WHERE	InVoiceDate>='+char(39)+@chvInvoiceStartDate+char(39)+'
				AND InVoiceDate<='+char(39)+@chvInvoiceEndDate+char(39)+'
				AND (ETypeId LIKE '+char(39)+@txtETypeNameI+'%'+char(39)+' OR ISNULL(ETypeId,'''')='''')
				AND (ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+' OR ISNULL(ETypeId,'''')='''')
				AND InVoiceNo LIKE '+char(39)+'%'+@InvoiceNo+'%'+char(39)+'
				AND IfInVoice LIKE '+char(39)+@chvInvoiceFlag+char(39)+'
				AND InVoiceStyle LIKE '+char(39)+@chvInvoiceStyle+char(39)+'
				AND Explain LIKE '+char(39)+'%'+@chrNote+'%'+char(39)+'
		GROUP BY BillNumberId
	)I ON Bil.BillNumberId = I.BillNumberId
	WHERE	Bil.BillType IN (305,11,160,34,161,141,145)
			AND Bil.RedWord IN (0)
			AND Bil.BillType LIKE '+char(39)+@BillType+char(39)+'
			AND Bil.BillDate>='+char(39)+@chvStartDate+char(39)+'
			AND Bil.BillDate<='+char(39)+@chvEndDate+char(39)+'
			AND Bil.BillCode LIKE '+char(39)+'%'+@BillCode+'%'+char(39)+'
			AND Bil.Comment LIKE '+char(39)+'%'+@chrCom+'%'+char(39)+'			
			AND Bil.BTypeId LIKE '+char(39)+@chvBTypeId+'%'+char(39)+'
			AND (Bil.BTypeId LIKE '+char(39)+@MBTypeId+'%'+char(39)+' OR Bil.BTypeId LIKE '+char(39)+@MBTypeId2+'%'+char(39)+')
			AND Bil.ETypeId LIKE '+char(39)+@chvETypeId+'%'+char(39)+'
			AND Bil.ETypeId LIKE '+char(39)+@METypeId+'%'+char(39)+'
			AND (Bil.KTypeId LIKE '+char(39)+@chvKTypeId+'%'+char(39)+' OR Bil.KTypeId2 LIKE '+char(39)+@chvKTypeId+'%'+char(39)+' OR ISNULL(Bil.KTypeId,'''')=''10000'')
			AND (Bil.KTypeId LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR Bil.KTypeId2 LIKE '+char(39)+@MKTypeId+'%'+char(39)+' OR ISNULL(Bil.KTypeId,'''')=''10000'')
	ORDER BY Bil.BillDate DESC '

--PRINT(@SQL)
EXEC(@SQL)





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInVoiceBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInVoiceBillDetail]
GO















/*
	作者：谢吉康
	日期：2007-11-27
	描述：发票管理
*/
CREATE PROCEDURE Web_QueryInVoiceBillDetail
(
	@OperatorID		varchar(100),
	@BillNumberId	varchar(100),
	@StartDate		varchar(20),
	@EndDate		varchar(20),
	@iFlag			varchar(10),
	@iStyle			varchar(10),
	@ETypeID		varchar(100),
	@InvoiceNo		varchar(100),
	@StartMoney		varchar(100),
	@EndMoney		varchar(100),
	@chrNote		varchar(256)
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MATypeId varchar(50), @MBTypeid varchar(50), @MBTypeid2 varchar(50), @MEtypeid varchar(50),
            @MKtypeid varchar(50), @MPtypeid varchar(50), @MExpense varchar(50), @MIncome varchar(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MATypeId OUTPUT,@MBTypeid OUTPUT,@MBTypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @BillNumberId = ''
	SET @BillNumberId = '%'

IF @iFlag = 2 OR @iFlag = ''
	SET @iFlag = '%'

IF @iStyle = 4 OR @iStyle = ''
	SET @iStyle = '%'

IF @StartMoney = ''
	SET @StartMoney = '-9999999999999'

IF @EndMoney = ''
	SET @EndMoney = '9999999999999'

SELECT	I.InVoiceID,
		I.InVoiceNo,
		CASE I.InVoiceStyle WHEN 1 THEN '普通发票' WHEN 2 THEN '增值税发票' ELSE '普通收据' END AS InVoiceStyle,
		ETypeID = (SELECT FullName FROM Employee WHERE TypeId = I.ETypeId),
		I.InVoiceDate,
		I.IfInVoice,
		SUM(
			CASE
				WHEN I.IfInVoice = 1 THEN InVoiceTotal
				ELSE InVoiceTotal
			END
		) AS KPJE,
		SUM(
			CASE
				WHEN I.IfInVoice = 0 THEN InVoiceTotal
				ELSE 0
			END
		) AS NKPJE,
		I.Explain,
		Bil.BillCode,
		Bil.BillType,
		Bil.BillNumberId
FROM	InVoiceBill I,
		BillIndex Bil
WHERE	I.BillNumberId = Bil.BillNumberId
		AND Bil.ETypeId LIKE @METypeId + '%'
		AND (I.ETypeId LIKE @ETypeId + '%' OR ISNULL(I.ETypeId,'')='')
		AND (I.ETypeId LIKE @METypeId + '%' OR ISNULL(I.ETypeId,'')='')		
		AND I.BillNumberId LIKE @BillNumberId
		AND I.InVoiceDate>=@StartDate
		AND I.InVoiceDate<=@EndDate
		AND I.IfInVoice LIKE @iFlag
		AND I.InVoiceStyle LIKE @iStyle
		AND I.InVoiceNo LIKE '%'+@InVoiceNo+'%'
		AND I.InVoiceTotal>=@StartMoney
		AND I.InVoiceTotal<=@EndMoney
		AND I.Explain LIKE '%'+@chrNote+'%'
		AND (Bil.KTypeId LIKE @MKTypeId + '%' OR ISNULL(Bil.KTypeId,'')='10000')
		AND (Bil.BTypeId LIKE @MBTypeId + '%' OR Bil.BTypeId LIKE @MBTypeId2 + '%')
GROUP BY
		I.InVoiceID,
		I.InVoiceNo,
		I.InVoiceStyle,
		I.ETypeID,
		I.InVoiceDate,
		I.Explain,
		Bil.BillCode,
		Bil.BillType,
		Bil.BillNumberId,
		I.IfInVoice
ORDER BY  I.InVoiceDate DESC,I.InVoiceNo




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInVoiceHkDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInVoiceHkDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/*
	作者：谢吉康
	日期：2008-01-08
	描述：销售（采购）开票（回款）付款分析明细账
	修改：周华
	时间：2012-11-19 09:35:48.593
	描述：优化调整。
	2013-01-07 周华 修改销售退货 抹零与回款符号问题
	2013-01-08 周华 修改 totalMoney与kpTotal不正确与Skptotal不正确的bug
	2013-02-17 周华 修改 采购金额统计 totalmoney,及明细的preferenceMoney,hktotal符号问题
	2013-02-18 周华 修改明细中没有“采购发票”的问题
	2013-03-19 周华 修改preferenceMoney,hktotal计算错误问题
	2013-03-25 周华 修改明细中统计的单据不正确，hktotal问题
					修改明细中多级范围权限没有控制的问题。
	2013-03-29 周华 按列表搬移
					
*/
CREATE       PROCEDURE Web_QueryInVoiceHkDetail
(
	@OperatorId		VARCHAR(50),	--操作员ID
	@DTypeId		VARCHAR(1550),	--商品ID
	@ETypeId		VARCHAR(1550),	--职员ID
	@BTypeId		VARCHAR(50),	--往来单位ID
	@KTypeId		VARCHAR(100),	--仓库ID
	@StartDate		VARCHAR(100),	--开始日期
	@EndDate		VARCHAR(100),	--结束日期
	@Comment		VARCHAR(100)='',--备注
	@BillType		VARCHAR(100),	--单据类型
	@nType			VARCHAR(10),	--统计类型  sale.销售开票回款 buy.采购开票付款
	@STypeID		VARCHAR(max),
	@ifini			BIT
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
				@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查结束---------------------------------------------------
	DECLARE @SQL 		VARCHAR(max),
			@SonNum 	INT,
			@BTypeMxId	VARCHAR(100),
			@BTypeAll	INT,
			@NewKtypeid		VARCHAR(10), --标示空仓库
			@SQLINI		VARCHAR(200)=''

	DECLARE @bt INT,@inibt VARCHAR(10);
	SELECT @bt=CASE WHEN @nType='sale' THEN 4 ELSE 66 END ,@inibt= CASE WHEN @nType='sale' THEN '45,215,46' ELSE '6' END ;


	IF @KTypeId = '' OR @KTypeId = '00000'
		SET @NewKtypeid = ''

	IF @BTypeId = '00000'
	BEGIN
		SET @BTypeId = '%'
		SET @BTypeMxId = '%'
	END
	ELSE			
		SET @BTypeMxId = @BTypeId

	IF @DTypeId = '00000'
		SET @DTypeId = '%'

	IF @KTypeId = '00000'
		SET @KTypeId = '%'

	CREATE TABLE #BType (TypeID VARCHAR(50))
	CREATE TABLE #Etype (TypeID VARCHAR(50),Fullname VARCHAR(66))
	CREATE TABLE #Ktype (TypeID VARCHAR(50))
	CREATE TABLE #Dtype (TypeID VARCHAR(50))

	IF @BtypeID =''
		INSERT INTO #Btype(typeid) SELECT a.typeid FROM F_GetManDetailBType(@OperatorID) a
	ELSE
		INSERT INTO #Btype(typeid) SELECT a.typeid FROM F_GetManDetailBType(@OperatorID) a, (SELECT * FROM  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a

	IF @ETypeID=''
		INSERT INTO #Etype(typeid,fullname) SELECT typeid,fullname FROM employee where typeid in (SELECT typeid FROM F_GetManDetailEType(@OperatorID))
	ELSE
		INSERT INTO #Etype(typeid,fullname) SELECT typeid,fullname FROM employee where typeid in (SELECT a.typeid FROM F_GetManDetailEType(@OperatorID) a, (SELECT * FROM  dbo.f_split(@EtypeID,',')) b where left(a.typeid,len(b.a))=b.a)

	--仓库
	INSERT INTO #Ktype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	
		
	INSERT INTO #Dtype SELECT typeid FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)

	--分支机构
	CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
	IF NOT (@STypeId = '' AND @MSTypeId = '00000')
	BEGIN
		INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
		--删除仓库中的对于STypeId
		DELETE FROM #Ktype WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
	END

	IF @KTypeID=''
	BEGIN
		INSERT INTO #Ktype SELECT '10000'
		INSERT INTO #Ktype(TypeID)VALUES('')
	END

	DECLARE @billTypes NVARCHAR(MAX);
	DECLARE @pb INT=0,@kb INT=0;
	SELECT @kb=1 WHERE NOT(@KTypeId = '' AND @MKTypeId = '00000')

	-- #t (#Bill,#BillNum,#BillPay)
	IF @ifini = 0
		SET @SQLINI=' AND a.ifcheck=''t'' AND a.draft = 0 AND a.isini = 0 '
	ELSE
		SET @SQLINI=' AND (a.draft = 0 OR a.isini = 1) '

	CREATE TABLE #Bill(
		BillNumberId NUMERIC(10,0)
		,PreferenceMoney  NUMERIC(24, 10) 
		,TotalInMoney  NUMERIC(24, 10) 
	);

	CREATE TABLE #BillNum(
		BillNumberId NUMERIC(10,0)
		,BillType INT
	);

	CREATE TABLE #BillPay(
		BillNumberId NUMERIC(10,0)
		,PreferenceMoney  NUMERIC(24, 10) 
		,TotalInMoney  NUMERIC(24, 10) 
	);
	
	CREATE TABLE #BillDetail(
		BillNumberId NUMERIC(10,0)
		,TotalMoney  NUMERIC(24, 10) 
		,KpTotal  NUMERIC(24, 10) 
	);
	
	CREATE CLUSTERED INDEX ix_bn_bn ON #BillNum(BillNumberId);
	CREATE CLUSTERED INDEX ix_bd_bn ON #BillDetail(BillNumberId);


	SET @SQL=' INSERT INTO #BillNum SELECT a.BillNumberId,a.BillType FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	SET @SQL=@SQL+' 
			WHERE a.BillType IN ('+@BillType+')
			AND a.BillType <> '+CAST(@bt AS VARCHAR(10))+'
			AND a.RedWord = 0 '+@SQLINI+'
			AND a.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+''' 
			'
	EXEC(@sql);

	SET @billTypes=','+@BillType+',';
	
	IF CHARINDEX(',34,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT a.BillNumberId,SUM(a.TaxTotal),SUM(a.InvoiceMoney) 
		FROM buybill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=34
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId;
	IF CHARINDEX(',11,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT a.BillNumberId,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM SaleBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=11
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	IF CHARINDEX(',12,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT a.BillNumberId,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM dbo.PT_Combin_SaleBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=12
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	
	IF CHARINDEX(',6,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT a.BillNumberId,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM BuyBackBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=6
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	IF CHARINDEX(',45,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT a.BillNumberId,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM saleBackBill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=45
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	IF CHARINDEX(',46,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT a.BillNumberId,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM dbo.PT_Combin_SaleBackBill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=46
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId	
	IF CHARINDEX(',215,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT a.BillNumberId,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM RetailBackBill a INNER JOIN BillIndex C ON A.BillNumberId=C.BillNumberId
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=215
		WHERE (@kb=1 AND C.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
		
	IF CHARINDEX(',160,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT a.BillNumberId
		,SUM(CASE WHEN InOrOut='I' THEN -a.TaxTotal ELSE a.TaxTotal END)
		,SUM(CASE WHEN InOrOut='I' THEN -a.InvoiceMoney ELSE a.InvoiceMoney END)
		FROM salegoodsexchangebill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=160
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	IF CHARINDEX(',161,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT a.BillNumberId
		,SUM(CASE WHEN InOrOut='O' THEN -a.TaxTotal ELSE a.TaxTotal END)
		,SUM(CASE WHEN InOrOut='O' THEN -a.InvoiceMoney ELSE a.InvoiceMoney END)
		FROM buygoodsexchangebill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=161
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	IF CHARINDEX(',141,',@billTypes)>0 AND @nType='sale' 
		INSERT INTO #BillDetail SELECT a.BillNumberId,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM CommissionBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=141
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	IF CHARINDEX (',145,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT a.BillNumberId,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM CommissionBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=145
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	IF CHARINDEX (',305,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT a.BillNumberId,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM retailBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=305
		GROUP BY a.BillNumberId
	
---------------------------------------------------暂估类数据插入--开始--------------------------------------------------------------
	--暂估入库单
	IF CHARINDEX(',400,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail 
		SELECT a.BillNumberId,SUM(a.TaxTotal),SUM(a.InvoiceMoney) 
		FROM AppraisalBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId  
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId;
	
	--暂估退货单	
	IF CHARINDEX(',401,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail 
		SELECT a.BillNumberId,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney) 
		FROM AppraisalBackBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId  
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId;
		
	--发出商品出库单
	IF CHARINDEX (',402,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail 
		SELECT a.BillNumberId,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM SendBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId 
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
	
	--发出商品退货单
		
	IF CHARINDEX (',403,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail 
		SELECT a.BillNumberId,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM SendBackBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId 
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId
---------------------------------------------------暂估类数据插入--结束--------------------------------------------------------------	


	SET @SQL='INSERT INTO #Bill SELECT a.BillNumberId,SUM(CASE WHEN a.BillType in ('+@inibt+') THEN -a.PreferenceMoney ELSE a.PreferenceMoney END),SUM( CASE WHEN a.BillType in ('+@inibt+') THEN -a.TotalInMoney ELSE a.TotalInMoney END) FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001') 
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	IF @kb=1 
		SET @sql=@sql+' JOIN #Ktype k ON a.Ktypeid=k.typeid '

	SET @SQL=@SQL+' 
			WHERE A.BillType IN ('+@BillType+')
			AND a.BillType <> '+CAST(@bt AS VARCHAR(10))+'
			AND A.RedWord = 0 '+@SQLINI+'
			AND A.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			AND A.BillNumberId IN (SELECT BillNumberId FROM #BillDetail)
			GROUP BY a.BillNumberId
			';
	EXEC(@SQL);
	
	SET @SQL='INSERT INTO #BillPay SELECT a.BillNumberId,SUM(a.PreferenceMoney),SUM(a.TotalInMoney) FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	IF @kb=1 
		SET @sql=@sql+' JOIN #Ktype k ON a.Ktypeid=k.typeid '
	SET @SQL=@SQL+'
			WHERE a.BillType IN('+@BillType+')
			AND a.BillType='+CAST(@bt AS VARCHAR(10))+'
			AND a.IfCheck = ''t''
			AND a.RedWord = 0
			AND a.Draft = 0
			AND a.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			GROUP BY a.BillNumberId
			'
	EXEC(@SQL);

--单独处理分支机构
if @STypeId=''
	insert into #GetManSTypeId select TypeId from F_GetAllManagerBaseTypeId('',11,@OperatorId)

	SELECT 
		x.BillNumberId
		,x.BillDate
		,x.BillCode
		,x.BillType
		,x.StypeId
		,v.BillName 
		,x.etypeid
		,ISNULL(y.TotalMoney,0) AS TotalMoney
		,ISNULL(y.PreferenceMoney,0) AS PreferenceMoney
		,ISNULL(y.KpTotal,0) AS KpTotal
		,0 AS SKpTotal
		,ISNULL(y.HkTotal,0) AS HkTotal,
		SysDiy1_head ,
				SysDiy2_head ,
			   SysDiy3_head ,
			   SysDiy4_head ,
			   SysDiy5_head ,
			   SysDiy6_head ,
			   SysDiy7_head ,
			   SysDiy8_head ,
			   SysDiy9_head ,
			   SysDiy10_head ,
			   SysDiy11_head ,
			   SysDiy12_head ,
			   SysDiy13_head ,
			   SysDiy14_head ,
			   SysDiy15_head ,
			   SysDiy16_head ,
			   SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head  
	FROM BillIndex x 
	JOIN (
				SELECT 
				w.BillNumberId
				,SUM(TotalMoney) AS TotalMoney
				,SUM(PreferenceMoney) AS PreferenceMoney
				,SUM(KpTotal) AS KpTotal
				,SUM(HkTotal) AS HkTotal
				FROM (
					SELECT BillNumberId
					,0 AS TotalMoney
					,PreferenceMoney AS PreferenceMoney
					,0 AS KpTotal
					,TotalInMoney AS HkTotal 
					FROM #Bill
					
					UNION ALL -- 1
					SELECT 
					BillNumberId
					,TotalMoney
					,0
					,KpTotal
					,0
					FROM #BillDetail
					UNION ALL -- 2
					SELECT x.BillNumberId,0,0,0
					,CASE WHEN CHARINDEX(CAST(x.billType AS VARCHAR(10)),@inibt)>0 THEN -1 ELSE 1 END*ISNULL(x.CompleteTotal,0)-ISNULL(y.CompleteTotal,0)
					FROM BillIndex x 
					--JOIN #BillNum A ON x.BillNumberId=a.BillNumberId AND x.BillType=a.BillType
					LEFT JOIN 
							(
								SELECT GoodsBillId,SUM(c.CompleteTotal) AS CompleteTotal 
								FROM CompleteTotal c
								INNER JOIN BillIndex b ON c.GoodsBillID=b.BillNumberId   AND c.BillType=b.BillType
								WHERE b.draft=0 AND b.RedWord=0 AND (b.ifcheck='t' OR b.IsIni = 1)
								GROUP BY c.GoodsBillID 
							) y ON x.BillNumberId=y.GoodsBillId
					WHERE ','+@BillType+',' LIKE '%,'+CAST(x.BillType AS varchar(10))+',%' -- 这里本来就没有索引 将就
					AND @ifini=1 AND x.IsIni=1 AND x.BillDate BETWEEN @StartDate AND @EndDate 	
					AND x.BillNumberId IN (SELECT BillNumberId FROM #BillDetail)
					UNION ALL --3
					SELECT BillNumberId,0,PreferenceMoney,0,TotalInMoney FROM #BillPay
					) w
				GROUP BY w.BillNumberId
		) y ON x.BillNumberId=y.BillNumberId
		LEFT JOIN BillName v on x.billType=v.billtype
		LEFT JOIN Custom_BillIndex ci ON x.BillNumberId=ci.BillId AND x.BillType=ci.BillType
		UNION ALL --手工开票的并上去
		SELECT	F.BillNumberId,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.StypeId,
				case b.BillType when 162 then '销售发票' when 163 then '采购发票' else v.BillName end,
				B.ETypeId,
				0,
				0,
				0,
				SUM(F.TaxTotal) AS SKpTotal,
				0,
				SysDiy1_head ,
				SysDiy2_head ,
			   SysDiy3_head ,
			   SysDiy4_head ,
			   SysDiy5_head ,
			   SysDiy6_head ,
			   SysDiy7_head ,
			   SysDiy8_head ,
			   SysDiy9_head ,
			   SysDiy10_head ,
			   SysDiy11_head ,
			   SysDiy12_head ,
			   SysDiy13_head ,
			   SysDiy14_head ,
			   SysDiy15_head ,
			   SysDiy16_head,
			   SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head  
		FROM FaPiaoBill F
		JOIN FaPiaoBillIndex B ON B.BillNumberID = F.BillNumberID
		JOIN #Btype T ON T.typeid = B.btypeid
		JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
		JOIN #Dtype ON B.Dtypeid=#Dtype.typeid
		JOIN #Etype ON B.Etypeid=#Etype.typeid
		LEFT JOIN BillName v on f.billType=v.billtype
		LEFT JOIN Custom_BillIndex ci ON b.BillNumberId=ci.BillId AND b.BillType=ci.BillType
		WHERE	F.MainBillNumberID = -1
				AND (@nType='sale' AND F.BillType=162 OR @nType='buy' AND F.BillType=163) 
				AND B.BillDate>=@StartDate
				AND B.BillDate<=@EndDate
				AND F.KTypeId IN (SELECT typeid FROM #Ktype)
				AND B.Comment LIKE '%'+@Comment+'%'
		GROUP BY F.BillNumberId,B.BillCode,B.BillDate,B.BillType,B.StypeId,v.BillName,B.ETypeId	,
				SysDiy1_head ,
				SysDiy2_head ,
			   SysDiy3_head ,
			   SysDiy4_head ,
			   SysDiy5_head ,
			   SysDiy6_head ,
			   SysDiy7_head ,
			   SysDiy8_head ,
			   SysDiy9_head ,
			   SysDiy10_head ,
			   SysDiy11_head ,
			   SysDiy12_head ,
			   SysDiy13_head ,
			   SysDiy14_head ,
			   SysDiy15_head ,
			   SysDiy16_head,
			   SysDiy17_head,
				SysDiy18_head,
				SysDiy19_head,
				SysDiy20_head,
				SysDiy21_head,
				SysDiy22_head,
				SysDiy23_head,
				SysDiy24_head,
				SysDiy25_head,
				SysDiy26_head,
				SysDiy27_head,
				SysDiy28_head,
				SysDiy29_head,
				SysDiy30_head,
				SysDiy31_head,
				SysDiy32_head  

		ORDER BY BillDate DESC,BillCode DESC

	DROP TABLE #Btype,#Etype,#Dtype,#Ktype,#GetManSTypeId,#Bill,#BillPay,#BillNum
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryInVoiceHkLine]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInVoiceHkLine]
GO

/*
	作者：谢吉康
	日期：2008-01-08
	描述：销售（采购）开票（回款）付款分析线性
	修改：周华
	时间：2012-11-19 09:46:55.417
	描述：优化
	
	2013-02-18 周华 修改 金额统计不正确问题
	2013-03-12 周华 修改 金额统计不正确，#ktype排除时写反了
	2013-03-19 周华 修改 没有控制到的#ktype权限
	2013-03-29 周华 修改 按开票列表修改
	2013-04-11 周华 修改 明细多行问题
*/

CREATE     PROCEDURE Web_QueryInVoiceHkLine
(
	@OperatorId		VARCHAR(100),	--操作员ID
	@DTypeId		VARCHAR(8000),	--商品ID
	@ETypeId		VARCHAR(8000),	--职员ID
	@BTypeId		VARCHAR(8000),	--往来单位ID
	@KTypeId		VARCHAR(8000),	--仓库ID
	@StartDate		VARCHAR(100),	--开始日期
	@EndDate		VARCHAR(100),	--结束日期
	@Comment		VARCHAR(100)='',--备注
	@BillType		VARCHAR(8000),	--单据类型
	@nType			VARCHAR(10),	--统计类型  sale.销售开票回款 buy.采购开票付款
	@STypeId		VARCHAR(max),
	@ifini			BIT
)
--@encode$--
AS
BEGIN
	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
				@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查结束---------------------------------------------------
	DECLARE @SQL 		VARCHAR(max),
			@SonNum 	int,
			@SQLINI		VARCHAR(200)=''
			
	DECLARE @bt INT,@inibt VARCHAR(10);
	SELECT @bt=CASE WHEN @nType='sale' THEN 4 ELSE 66 END ,@inibt= CASE WHEN @nType='sale' THEN '45,215,46' ELSE '6' END ;
	
	--IF @ifini = 0
	--BEGIN
	--	SET @SQLINI=' AND bil.ifcheck=''t'' AND bil.draft = 0 AND bil.isini = 0 '
	--END
	--ELSE
	--BEGIN
	--	SET @SQLINI=' AND (bil.draft = 0 OR bil.isini = 1) '
	--END


	CREATE TABLE #BType (TypeID VARCHAR(50),usercode VARCHAR(26),fullname VARCHAR(100),sonnum int)
	CREATE TABLE #Etype (TypeID VARCHAR(50))
	CREATE TABLE #Ktype (TypeID VARCHAR(50))
	CREATE TABLE #Dtype (TypeID VARCHAR(50))

	IF @BtypeID ='00000'
		INSERT INTO #Btype(typeid,usercode,fullname,sonnum) SELECT typeid,usercode,fullname,sonnum FROM btype where typeid in (SELECT a.typeid FROM F_GetManDetailBType(@OperatorID) a)
	ELSE
		INSERT INTO #Btype(typeid,usercode,fullname,sonnum) SELECT typeid,usercode,fullname,sonnum FROM btype where typeid in (SELECT a.typeid FROM F_GetManDetailBType(@OperatorID) a, (SELECT * FROM  dbo.f_split(@BtypeID,',')) b where left(a.typeid,len(b.a))=b.a)

	IF @ETypeID=''
		INSERT INTO #Etype SELECT typeid FROM F_GetManDetailEType(@OperatorID)
	ELSE
		INSERT INTO #Etype SELECT a.typeid FROM F_GetManDetailEType(@OperatorID) a, (SELECT * FROM  dbo.f_split(@EtypeID,',')) b where left(a.typeid,len(b.a))=b.a

	--仓库
	INSERT INTO #Ktype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	
		
	--部门
	INSERT INTO #Dtype 	SELECT typeid 	FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)
		
	--分支机构
	CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
	IF NOT (@STypeId = '' AND @MSTypeId = '00000')
		BEGIN
			INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
			--删除仓库中的对于STypeId
			DELETE FROM #Ktype WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
		END
		
	--处理仓库
	IF @KTypeID=''
	BEGIN
		INSERT INTO #Ktype SELECT '10000'
		INSERT INTO #Ktype(TypeID)VALUES('')
	END		
	
	DECLARE @billTypes NVARCHAR(MAX);
	DECLARE @pb INT=0,@kb INT=0;
	--SELECT @pb=1 WHERE NOT(@PTypeId='' AND @MPTypeId='00000')
	SELECT @kb=1 WHERE NOT(@KTypeId = '' AND @MKTypeId = '00000')
	
	-- //分成三步 #t (#Bill #BillPay #BillNum) #BillDetail
		IF @ifini = 0
		SET @SQLINI=' AND a.ifcheck=''t'' AND a.draft = 0  AND a.isini = 0 '
	ELSE
		SET @SQLINI=' AND (a.draft = 0 OR a.isini = 1) '

	CREATE TABLE #Bill(
		BtypeId VARCHAR(50)
		,BillType INT
		,PreferenceMoney  NUMERIC(24, 10) 
		,TotalInMoney  NUMERIC(24, 10) 
		,CompleteTotal  NUMERIC(24, 10) 
	);
	CREATE TABLE #BillNum(
		BillNumberId NUMERIC(18,0)
		,BtypeId VARCHAR(50)
		,BillType INT
	);
	CREATE TABLE #BillPay(
		BtypeId VARCHAR(50)
		,PreferenceMoney  NUMERIC(24, 10) 
		,TotalInMoney  NUMERIC(24, 10) 
	);

		CREATE TABLE #BillDetail(
		BillType INT
		,BillNumberId INT --因为要控制到明细多级权限，如多仓库
		,BTypeId VARCHAR(50)
		,TaxTotal  NUMERIC(24, 10) 
		,InvoiceMoney  NUMERIC(24, 10) 
	);
	
	SET @SQL=' INSERT INTO #BillNum SELECT a.BillNumberId,a.BtypeId,a.BillType FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	SET @SQL=@SQL+' 
			WHERE a.BillType IN ('+@BillType+')
			AND a.BillType <> '+CAST(@bt AS VARCHAR(10))+'
			AND a.RedWord = 0 '+@SQLINI+'
			AND a.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			'
	EXEC(@sql);
	
	SET @billTypes=','+@BillType+',';
	IF CHARINDEX(',34,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT 34 ,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney) 
		FROM buybill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=34
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid;
	IF CHARINDEX(',11,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 11,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM SaleBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=11
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',12,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 12,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM dbo.PT_Combin_SaleBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=12
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',6,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT 6,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM BuyBackBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=6
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.BtypeId
	IF CHARINDEX(',45,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 45,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM saleBackBill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=45
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',46,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 46,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM dbo.PT_Combin_SaleBackBill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=46
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',215,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 215,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM RetailBackBill a INNER JOIN BillIndex C ON A.BillNumberId=C.BillNumberId
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=215
		WHERE (@kb=1 AND C.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',160,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 160,a.BillNumberId,b.BtypeId
		,SUM(CASE WHEN InOrOut='I' THEN -a.TaxTotal ELSE a.TaxTotal END)
		,SUM(CASE WHEN InOrOut='I' THEN -a.InvoiceMoney ELSE a.InvoiceMoney END)
		FROM salegoodsexchangebill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=160
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',161,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT 161,a.BillNumberId,b.Btypeid
		,SUM(CASE WHEN InOrOut='O' THEN -a.TaxTotal ELSE a.TaxTotal END)
		,SUM(CASE WHEN InOrOut='O' THEN -a.InvoiceMoney ELSE a.InvoiceMoney END)
		FROM buygoodsexchangebill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=161
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',141,',@billTypes)>0 AND @nType='sale' 
		INSERT INTO #BillDetail SELECT 141,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM CommissionBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=141
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX (',145,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT 145,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM CommissionBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=145
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX (',305,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 305,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM retailBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=305
		GROUP BY B.billtype,a.BillNumberId,b.Btypeid
	
---------------------------------------------------暂估类数据插入--开始--------------------------------------------------------------
	--暂估入库单
	IF CHARINDEX(',400,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail 
		SELECT 400 ,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney) 
		FROM AppraisalBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId  
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid;
 	--暂估退货单	
	IF CHARINDEX(',401,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail 
		SELECT 401,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM dbo.AppraisalBackBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId  
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.BtypeId
	
	--发出商品出库单
	IF CHARINDEX (',402,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail 
		SELECT 402,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM SendBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId 
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	
	--发出商品退货单
	IF CHARINDEX (',403,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail 
		SELECT 403,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM dbo.SendBackBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId 
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
---------------------------------------------------暂估类数据插入--结束--------------------------------------------------------------	

	

	SET @SQL='INSERT INTO #Bill SELECT a.BtypeId,a.BillType,SUM(CASE WHEN a.BillType IN ('+@inibt+') THEN -a.PreferenceMoney ELSE a.PreferenceMoney END),SUM(CASE WHEN a.BillType IN ('+@inibt+') THEN -a.TotalInMoney ELSE a.TotalInMoney END),SUM(a.CompleteTotal) FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	IF @kb=1
		SET @sql=@sql+' JOIN #Ktype k ON a.Ktypeid=k.typeid '
	SET @SQL=@SQL+' 
			WHERE A.BillType IN ('+@BillType+')
			AND a.BillType <> '+CAST(@bt AS VARCHAR(10))+'
			AND A.RedWord = 0 '+@SQLINI+'
			AND A.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			AND A.BillNumberId IN (SELECT BillNumberId FROM #BillDetail)
			GROUP BY a.BtypeId,a.BillType 
			';
	EXEC(@SQL);

	SET @SQL='INSERT INTO #BillPay SELECT a.BtypeId,SUM(a.PreferenceMoney),SUM(a.TotalInMoney) FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	IF @kb=1
		SET @sql=@sql+' JOIN #Ktype k ON a.Ktypeid=k.typeid '
	SET @SQL=@SQL+'
			WHERE a.BillType IN('+@BillType+')
			AND a.BillType='+CAST(@bt AS VARCHAR(10))+'
			AND a.IfCheck = ''t''
			AND a.RedWord = 0
			AND a.Draft = 0
			AND a.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			GROUP BY a.BtypeId 
			'
	EXEC(@SQL);

--单独处理分支机构
if @STypeId=''
	insert into #GetManSTypeId select TypeId from F_GetAllManagerBaseTypeId('',11,@OperatorId)
	-- select
	SELECT 
			m.TypeId
			,m.SonNum
			,m.UserCode
			,m.FullName
			,ISNULL(v.TotalMoney,0) AS TotalMoney
			,ISNULL(v.PreferenceMoney,0) AS PreferenceMoney
			,ISNULL(v.KpTotal,0) AS KpTotal
			,ISNULL(v.SKpTotal,0) AS SKpTotal
			,ISNULL(v.HkTotal,0) AS HkTotal
		FROM #Btype m
		LEFT JOIN
		(
			SELECT w.btypeid,SUM(TotalMoney) AS TotalMoney,SUM(PreferenceMoney) AS PreferenceMoney,SUM(KpTotal) AS KpTotal,SUM(HkTotal) AS HkTotal,SUM(SKpTotal) AS SKpTotal FROM (
			SELECT 
				x.btypeid
				,SUM(TotalMoney) AS TotalMoney
				,SUM(PreferenceMoney) AS PreferenceMoney
				,SUM(KpTotal) AS KpTotal
				,SUM(HkTotal) AS HkTotal
				,0 AS SkpTotal
			FROM (
				SELECT 
				a.btypeId
				,0 AS TotalMoney
				,a.PreferenceMoney AS PreferenceMoney
				,0 AS KpTotal
				,a.TotalInMoney AS HkTotal
				FROM #Bill a
				WHERE a.BillType<>@bt --sale 4 buy 66 
				UNION ALL 
				SELECT BTypeId
				,SUM(TaxTotal) AS TaxTotal
				,0
				,SUM(InvoiceMoney) AS InvoiceMoney 
				,0
				FROM #BillDetail 
				WHERE Billtype<>@bt
				GROUP BY Btypeid
				UNION ALL
				
				SELECT x.btypeid
				,0,0,0
				,CASE WHEN CHARINDEX(CAST(x.billType AS VARCHAR(10)),@inibt)>0 THEN -1 ELSE 1 END*ISNULL(x.CompleteTotal,0)-ISNULL(y.CompleteTotal,0) AS HkTotal
				FROM BillIndex x
				LEFT JOIN
					(
						SELECT GoodsBillId,SUM(c.CompleteTotal) AS CompleteTotal 
						FROM CompleteTotal c
						INNER JOIN BillIndex b ON c.GoodsBillID=b.BillNumberId   AND c.BillType=b.BillType
						WHERE b.draft=0 AND b.RedWord=0 AND (b.ifcheck='t' OR b.IsIni = 1)
						GROUP BY c.GoodsBillID 
					) y ON x.BillNumberId=y.GoodsBillId
				WHERE ','+@BillType+',' LIKE '%,'+CAST(x.BillType AS varchar(10))+',%' -- 这里本来就没有索引 将就
				AND @ifini=1 AND x.IsIni=1 AND x.BillDate BETWEEN @StartDate AND @EndDate 	
				AND x.BillNumberId IN (SELECT billNumberId FROM #BillDetail)

				UNION ALL 
				
				SELECT BtypeId,0,PreferenceMoney,0,TotalInMoney
				FROM #BillPay 
			) x
			GROUP BY x.btypeid
			UNION ALL
		--) w  ON w.BtypeId=m.TypeId
		--LEFT JOIN (
			SELECT	B.btypeid,0,0,0,0,
					SUM(F.TaxTotal) AS SKpTotal
			FROM FaPiaoBill F
			JOIN FaPiaoBillIndex B ON B.BillNumberID = F.BillNumberID
			JOIN #Btype T ON T.typeid = B.btypeid
			JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			JOIN #Dtype ON B.Dtypeid=#Dtype.typeid
			JOIN #Etype ON B.Etypeid=#Etype.typeid
			WHERE	F.MainBillNumberID = -1
					AND (@nType='sale' AND F.BillType=162 OR @nType='buy' AND F.BillType=163) 
					AND B.BillDate>=@StartDate
					AND B.BillDate<=@EndDate
					AND F.KTypeId IN (SELECT typeid FROM #Ktype)
					AND B.Comment LIKE '%'+@Comment+'%'
			GROUP BY B.BTypeId
			) w
			GROUP BY w.btypeid
		) v ON v.btypeid LIKE m.typeid+'%'
		ORDER BY m.UserCode
	 
	DROP TABLE #Btype,#Etype,#Dtype,#Ktype,#GetManSTypeId,#Bill,#BillPay,#BillNum,#BillDetail

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryInVoiceHkList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryInVoiceHkList]
GO

/*
	作者：谢吉康
	日期：2008-01-08
	描述：销售（采购）开票（回款）付款分析
	修改：周华
	时间：2012-11-15 10:06:08.207
	描述：做了部分优化调整
	2013-01-05 周华 调整了销售采购退货没有反号的情况
	2013-02-17 周华 修改采购金额不正确的问题
	2013-02-18 周华 修改金额不正确问题
	2013-03-12 周华 修改金额不正确问题，排除ktype的时候，条件写反了
	2013-03-19 周华 修改PerferenceMoney和Completetotal不正确
	2013-03-22 周华 修改 totalmoney不正确情况
	2013-03-25 周华 修改 多级权限没有控制到明细的情况，多仓库入等情况
	2013-03-26 周华 修改回款金额不正确，@BillType条件没对
*/

CREATE     PROCEDURE Web_QueryInVoiceHkList
(
	@OperatorId		VARCHAR(50),	--操作员ID
	@DTypeId		VARCHAR(8000),	--部门ID
	@ETypeId		VARCHAR(8000),	--职员ID
	@BTypeId		VARCHAR(8000),	--往来单位ID
	@KTypeId		VARCHAR(8000),	--仓库ID
	@StartDate		VARCHAR(100),	--开始日期
	@EndDate		VARCHAR(100),	--结束日期
	@Comment		VARCHAR(100)='',--备注
	@BillType		VARCHAR(100),	--单据类型
	@nType			VARCHAR(10),	--统计类型  sale.销售开票回款 buy.采购开票付款
	@STypeId		VARCHAR(max),
	@ifini			BIT
)
--@encode$--
AS
BEGIN

	SET NOCOUNT ON
	SET ANSI_WARNINGS OFF

	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
				@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查结束---------------------------------------------------

	DECLARE @SQL VARCHAR(8000),@SonNum 	int,
			@SQLINI		VARCHAR(200)='';
			
	DECLARE @bt INT,@inibt varchar(10);
	SELECT @bt=CASE WHEN @nType='sale' THEN 4 ELSE 66 END ,@inibt= CASE WHEN @nType='sale' THEN '45,215,46' ELSE '6' END ;

	CREATE TABLE #Btype (TypeID VARCHAR(50))
	CREATE TABLE #Etype (TypeID VARCHAR(50))
	CREATE TABLE #Ktype (TypeID VARCHAR(50))
	CREATE TABLE #Dtype (TypeID VARCHAR(50))
	CREATE TABLE #MainType (TypeID VARCHAR(50),usercode VARCHAR(26),fullname VARCHAR(100),sonnum int)

	IF @BtypeID =''
		INSERT INTO #Btype SELECT a.typeid FROM F_GetManDetailBType(@OperatorID) a
	ELSE
		INSERT INTO #Btype 
			SELECT a.typeid 
			FROM F_GetManDetailBType(@OperatorID) a, 
				(SELECT * FROM  dbo.f_split(@BtypeID,',')) b WHERE left(a.typeid,len(b.a))=b.a

	IF @ETypeID=''
		INSERT INTO #Etype 
			SELECT typeid 
			FROM F_GetManDetailEType(@OperatorID)
	ELSE
		INSERT INTO #Etype 
			SELECT a.typeid 
			FROM F_GetManDetailEType(@OperatorID) a, (SELECT * FROM  dbo.f_split(@EtypeID,',')) b 
			WHERE left(a.typeid,len(b.a))=b.a

	--仓库
	INSERT INTO #Ktype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@KTypeId,4,@OperatorID)	

	INSERT INTO #Dtype SELECT TypeId FROM F_GetAllManagerBaseTypeId(@DTypeId,9,@OperatorID)	


	SELECT @sonnum = sonnum FROM Btype WHERE Typeid=@BtypeID
	IF @sonnum =0 	
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum) 
			SELECT b.typeid,b.usercode,b.fullname,b.sonnum FROM Btype b,
				  (SELECT * FROM F_GetManBTypeAll(@OperatorID) 
			WHERE typeid =@BtypeID) a WHERE b.typeid=a.typeid
	ELSE
		IF @BtypeID=''
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum) 
				SELECT b.typeid,b.usercode,b.fullname,b.sonnum FROM Btype b,
					  (SELECT * FROM F_GetManBTypeAll(@OperatorID) WHERE parid='00000') a 
				WHERE b.typeid=a.typeid
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum) 
				SELECT b.typeid,b.usercode,b.fullname,b.sonnum FROM Btype b,
					  (SELECT * FROM F_GetManBTypeAll(@OperatorID) WHERE parid=@BtypeID) a 
				WHERE b.typeid=a.typeid

	--分支机构
	CREATE TABLE #GetManSTypeId(TypeId	VARCHAR(100))
	IF NOT (@STypeId = '' AND @MSTypeId = '00000')
		BEGIN
			INSERT INTO #GetManSTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@STypeId,11,@OperatorID)	
			--删除仓库中的对于STypeId
			DELETE FROM #Ktype WHERE TypeID NOT IN (SELECT TypeID FROM Stock WHERE STypeID IN (SELECT TypeID FROM #GetManSTypeId))		
		END
		
	--处理仓库
	IF @KTypeID=''
	BEGIN
		INSERT INTO #Ktype SELECT '10000'
		INSERT INTO #Ktype(TypeID)VALUES('')
	END	

	DECLARE @billTypes NVARCHAR(MAX);
	DECLARE @pb INT=0,@kb INT=0;
	--SELECT @pb=1 WHERE NOT(@PTypeId='' AND @MPTypeId='00000')
	SELECT @kb=1 WHERE NOT(@KTypeId = '' AND @MKTypeId = '00000')
	-- //分成三步 #t (#Bill #BillPay #BillNum) #BillDetail

	IF @ifini = 0
		SET @SQLINI=' AND a.ifcheck=''t'' AND a.draft = 0  AND a.isini = 0 '
	ELSE
		SET @SQLINI=' AND (a.draft = 0 OR a.isini = 1) '

	CREATE TABLE #Bill(
		BtypeId VARCHAR(50)
		,BillType INT
		,PreferenceMoney  NUMERIC(24, 10) 
		,TotalInMoney  NUMERIC(24, 10) 
		,CompleteTotal  NUMERIC(24, 10) 
	);
	CREATE TABLE #BillNum(
		BillNumberId NUMERIC(18,0)
		,BtypeId VARCHAR(50)
		,BillType INT
	);
	CREATE TABLE #BillPay(
		BtypeId VARCHAR(50)
		,PreferenceMoney  NUMERIC(24, 10) 
		,TotalInMoney  NUMERIC(24, 10) 
	);
	CREATE TABLE #BillDetail(
		BillType int
		,BillNumberId INT --因为要控制到明细多级权限，如多仓库
		,BTypeId VARCHAR(50)
		,TaxTotal  NUMERIC(24, 10) 
		,InvoiceMoney  NUMERIC(24, 10) 
	);


	SET @SQL=' INSERT INTO #BillNum SELECT a.BillNumberId,a.BtypeId,a.BillType FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	SET @SQL=@SQL+' 
			WHERE a.BillType IN ('+@BillType+')
			AND a.BillType <> '+CAST(@bt AS VARCHAR(10))+'
			AND a.RedWord = 0 '+@SQLINI+'
			AND a.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			'
	EXEC(@sql);

	SET @billTypes=','+@BillType+',';
	IF CHARINDEX(',34,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT 34 ,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney) 
		FROM buybill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=34
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid;
	IF CHARINDEX(',11,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 11,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM SaleBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=11
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',12,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 12,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM dbo.PT_Combin_SaleBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=12
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
		
	IF CHARINDEX(',6,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT 6,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM BuyBackBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=6
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.BtypeId
	IF CHARINDEX(',45,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 45,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM saleBackBill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=45
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
		
	IF CHARINDEX(',46,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 46,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM dbo.PT_Combin_SaleBackBill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=46
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
		
	IF CHARINDEX(',215,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 215,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM RetailBackBill a inner join BillIndex c on a.BillNumberId=c.BillNumberId
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=215
		WHERE (@kb=1 AND c.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',160,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 160,a.BillNumberId,b.BtypeId
		,SUM(CASE WHEN InOrOut='I' THEN -a.TaxTotal ELSE a.TaxTotal END)
		,SUM(CASE WHEN InOrOut='I' THEN -a.InvoiceMoney ELSE a.InvoiceMoney END)
		FROM salegoodsexchangebill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=160
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',161,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT 161,a.BillNumberId,b.Btypeid
		,SUM(CASE WHEN InOrOut='O' THEN -a.TaxTotal ELSE a.TaxTotal END)
		,SUM(CASE WHEN InOrOut='O' THEN -a.InvoiceMoney ELSE a.InvoiceMoney END)
		FROM buygoodsexchangebill a
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=161
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX(',141,',@billTypes)>0 AND @nType='sale' 
		INSERT INTO #BillDetail SELECT 141,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM CommissionBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=141
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX (',145,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail SELECT 145,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM CommissionBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=145
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	IF CHARINDEX (',305,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail SELECT 305,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM retailBill a 
		JOIN #BillNum B ON a.BillNumberId=b.BillNumberId AND b.BillType=305
		GROUP BY B.billtype,a.BillNumberId,b.Btypeid
		
---------------------------------------------------暂估类数据插入--开始--------------------------------------------------------------
	--暂估入库单
	IF CHARINDEX(',400,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail 
		SELECT 400 ,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney) 
		FROM AppraisalBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId  
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid;
	--暂估退货单	
	IF CHARINDEX(',401,',@billTypes)>0 AND @nType='buy'
		INSERT INTO #BillDetail 
		SELECT 401,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM dbo.AppraisalBackBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId  
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.BtypeId
	
	--发出商品出库单
	IF CHARINDEX (',402,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail 
		SELECT 402,a.BillNumberId,b.Btypeid,SUM(a.TaxTotal),SUM(a.InvoiceMoney)
		FROM SendBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId 
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
	--发出商品退货单
	IF CHARINDEX (',403,',@billTypes)>0 AND @nType='sale'
		INSERT INTO #BillDetail 
		SELECT 403,a.BillNumberId,b.Btypeid,-SUM(a.TaxTotal),-SUM(a.InvoiceMoney)
		FROM dbo.SendBackBill a 
		INNER JOIN #BillNum B ON a.BillNumberId=b.BillNumberId 
		WHERE (@kb=1 AND a.ktypeid IN (SELECT typeid FROM #Ktype) OR @kb<>1)
		GROUP BY a.BillNumberId,b.Btypeid
---------------------------------------------------暂估类数据插入--结束--------------------------------------------------------------	
 --SELECT * FROM #BillDetail
	SET @SQL='INSERT INTO #Bill SELECT a.BtypeId,a.BillType,SUM(CASE WHEN a.BillType in ('+@inibt+') THEN -a.PreferenceMoney ELSE a.PreferenceMoney END),SUM(CASE WHEN a.BillType in ('+@inibt+') THEN -a.TotalInMoney ELSE a.TotalInMoney END),SUM(a.CompleteTotal) FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	IF @kb=1 
		SET @sql=@sql+' JOIN #Ktype k ON a.Ktypeid=k.typeid '
	SET @SQL=@SQL+' 
			WHERE A.BillType IN ('+@BillType+')
			AND a.BillType <> '+CAST(@bt AS VARCHAR(10))+'
			AND A.RedWord = 0 '+@SQLINI+'
			AND A.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			AND A.BillNumberId IN (SELECT BillNumberId FROM #BillDetail) 
			GROUP BY a.BtypeId,a.BillType 
			';
			--PRINT(@SQL)
	EXEC(@SQL);


	SET @SQL='INSERT INTO #BillPay SELECT a.BtypeId,SUM(a.PreferenceMoney),SUM(a.TotalInMoney) FROM BillIndex a '
	IF NOT (@BtypeId = '' AND @MBTypeId = '00001' AND @MBTypeId2 = '00002')
		SET @SQL =@SQL+' JOIN #Btype ON a.Btypeid=#Btype.typeid '
	IF NOT (@ETypeId= '' AND @METypeId = '00001')
		SET @SQL =@SQL+' JOIN #Etype ON a.Etypeid=#Etype.typeid '
	IF NOT (@DTypeId = '' AND @MDTypeId = '00000')
		SET @SQL =@SQL+' JOIN #Dtype ON a.Dtypeid=#Dtype.typeid '
	IF NOT (@STypeId = '' AND @MStypeid = '00000')
		SET @SQL = @SQL + ' JOIN #GetManSTypeId S ON a.STypeId = S.TypeId '	
	IF @kb=1 
		SET @sql=@sql+' JOIN #Ktype k ON a.Ktypeid=k.typeid '
	SET @SQL=@SQL+'
			WHERE a.BillType IN('+@BillType+')
			AND a.BillType='+CAST(@bt AS VARCHAR(10))+'
			AND a.IfCheck = ''t''
			AND a.RedWord = 0
			AND a.Draft = 0
			AND a.BillDate BETWEEN '''+@StartDate+''' AND '''+@EndDate+'''
			GROUP BY a.BtypeId 
			'
	EXEC(@SQL);
	
--单独处理分支机构
if @STypeId=''
	insert into #GetManSTypeId select TypeId from F_GetAllManagerBaseTypeId('',11,@OperatorId)
	--最终数据 
	SELECT 
			m.TypeId
			,m.SonNum AS SonNum
			,m.UserCode AS UserCode
			,m.FullName AS FullName
			,ISNULL(SUM(v.TotalMoney),0) AS TotalMoney
			,ISNULL(SUM(v.PreferenceMoney),0) AS PreferenceMoney
			,ISNULL(SUM(v.KpTotal),0) AS KpTotal
			,ISNULL(SUM(v.SKpTotal),0) AS SKpTotal
			,ISNULL(SUM(v.HkTotal),0) AS HkTotal
		FROM #MainType m
		LEFT JOIN
		(
			SELECT 
				x.btypeid
				,SUM(TotalMoney) AS TotalMoney
				,SUM(PreferenceMoney) AS PreferenceMoney
				,SUM(KpTotal) AS KpTotal
				,SUM(HkTotal) AS HkTotal
				,0 as SKpTotal
			FROM 
			(
				SELECT a.btypeid
				,0 AS TotalMoney
				,a.PreferenceMoney AS PreferenceMoney
				,0 AS KpTotal
				,a.TotalInMoney AS HkTotal
				FROM #Bill a 
				WHERE a.BillType<>@bt --sale 4 buy 66 
				UNION ALL 
				SELECT BTypeId
				,SUM(TaxTotal) AS TaxTotal
				,0
				,SUM(InvoiceMoney) AS InvoiceMoney 
				,0
				FROM #BillDetail 
				WHERE Billtype<>@bt
				GROUP BY Btypeid

				UNION ALL 
				
				SELECT x.btypeid
				,0,0,0
				,CASE WHEN CHARINDEX(CAST(x.billType AS VARCHAR(10)),@inibt)>0 THEN -1 ELSE 1 END*ISNULL(x.CompleteTotal,0)-ISNULL(y.CompleteTotal,0) AS HkTotal
				FROM BillIndex x
				LEFT JOIN 
					(
						SELECT GoodsBillId,SUM(c.CompleteTotal) AS CompleteTotal 
						FROM CompleteTotal c
						INNER JOIN BillIndex b ON c.GoodsBillID=b.BillNumberId   AND c.BillType=b.BillType
						WHERE b.draft=0 AND b.RedWord=0 AND (b.ifcheck='t' OR b.IsIni = 1)
						GROUP BY c.GoodsBillID 
					) y ON x.BillNumberId=y.GoodsBillId
				WHERE ','+@BillType+',' LIKE '%,'+CAST(x.BillType AS varchar(10))+',%' -- 这里本来就没有索引 将就
				AND @ifini=1 AND x.IsIni=1 AND x.BillDate BETWEEN @StartDate AND @EndDate 	
				AND x.BillNumberId IN (SELECT billNumberId FROM #BillDetail)
				UNION ALL 
				
				SELECT BtypeId,0,PreferenceMoney,0,TotalInMoney
				FROM #BillPay 
				 
			) x
			GROUP BY x.btypeid
			UNION ALL 
	 
			SELECT	B.btypeid,0,0,0,0,
					SUM(F.TaxTotal) AS SKpTotal
			FROM FaPiaoBill F
			JOIN FaPiaoBillIndex B ON B.BillNumberID = F.BillNumberID
			JOIN #Btype T ON T.typeid = B.btypeid
			JOIN #GetManSTypeId S ON B.STypeId = S.TypeId
			JOIN #Dtype ON B.Dtypeid=#Dtype.typeid
			JOIN #Etype ON B.Etypeid=#Etype.typeid
			WHERE	F.MainBillNumberID = -1
					AND (@nType='sale' AND F.BillType=162 OR @nType='buy' AND F.BillType=163) 
					AND B.BillDate>=@StartDate
					AND B.BillDate<=@EndDate
					AND F.KTypeId IN (SELECT typeid FROM #Ktype)
					AND B.Comment LIKE '%'+@Comment+'%'
			GROUP BY B.BTypeId
		) v ON v.btypeid LIKE m.typeid+'%'
		GROUP BY m.typeid,m.SonNum,m.UserCode,m.FullName
		ORDER BY m.UserCode

	DROP TABLE #Btype,#Etype,#Dtype,#GetManSTypeId,#MainType,#Ktype,#Bill,#BillPay,#BillNum,#BillDetail
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryItem_CategoryCondition]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryItem_CategoryCondition
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	Ac_items 查询指定项目是否满足条件进行分类
-- 时间：	2013-05-09
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryItem_CategoryCondition
(
	@NId		INT			--父节点
)
--@encode$--
AS
SET NOCOUNT ON
	
IF(ISNULL(@NId,'')<>'')
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE Sysrow=1 AND nId=@NId and IsModify=0)
			BEGIN
				----待摊费用项目允许分类
				--IF NOT EXISTS(SELECT TOP 1 1 FROM f_split('32',',') WHERE a IN (@NId))
				--BEGIN
					RAISERROR('该信息为系统项目，不允许分类！',16,1)RETURN
				--END
			END
		IF EXISTS(SELECT TOP 1 1 FROM Ac_Items WHERE Deleted=1  AND nId=@NId)
			BEGIN
				RAISERROR('该信息已经停用，不允许分类！',16,1)RETURN
			END	
		IF EXISTS(SELECT *FROM PosInfo WHERE BankCardID =@nid)
			BEGIN
				RAISERROR('该信息已关联POS，不允许分类！',16,1)RETURN
			END	
		IF EXISTS(SELECT *FROM dbo.Ac_Items WHERE nId =@nid AND WdSyncFlag = 1)
			BEGIN
				RAISERROR('该账户已经同步全渠道，请取消同步再分类！',16,1)RETURN
			END	
		IF EXISTS(SELECT * FROM dbo.PayConfigInfo WHERE BankCardID=@nid)
			BEGIN
				RAISERROR('该项目已在支付宝或微信结算设置中使用，不能删除！',16,1)RETURN
			END 
		DECLARE @RET INT=0
		SET @RET=(SELECT dbo.Fn_GetIsUse_Items(@NId,2))
		IF @RET>0
			BEGIN
				RAISERROR('该信息已经使用，不允许分类！',16,1)RETURN
			END	
			
--声明变量
			DECLARE 
				@level				INT=(SELECT TOP 1 Leveal FROM Ac_Items WHERE nId=@NId),			-- 父级level
				
				@nReturntype		VARCHAR(50),	--
				@newTypeid			VARCHAR(50),	--新增节点表中TypeID
				@parid				VARCHAR(50),
				@nSonnum			INT,		
				@nSoncount			INT
				
				--得到父级TypeId/level
				
		SELECT @parid=nTypeId FROM Ac_Items WHERE nId=@NId
				--得到当前新增数据TypeID
				EXEC @nReturntype= Gp_CreateId_AcItem @parid, 'Ac_Items', @newTypeid OUT,@nSonnum OUT, @nSoncount OUT
				IF @nReturntype = -1
					BEGIN
						RAISERROR('分类不能超过10层',16,1)
						RETURN -1
					END
				ELSE IF @nReturntype = -2
					BEGIN
						RAISERROR('无法添加',16,1)
						RETURN -1	
					END
	END
return -1;
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryKinOutStockConfig]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryKinOutStockConfig]
GO





/*
	查询单据配置
*/
CREATE PROCEDURE Web_QueryKinOutStockConfig
(
	@ETypeId		varchar(200),
	@billType		int
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @billTypes varchar(8000)

SELECT @billTypes = BillTypes FROM kinoutstockconfig WHERE ETypeId = @ETypeId

IF @@ROWCOUNT = 0
	RETURN -1
ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.f_split(@billTypes,',') WHERE a = @billType)
			RETURN 0
		ELSE
			RETURN -1
	END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryKqReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryKqReport]
GO








/*
	作者：谢吉康
	日期：2005-03-08
	描述：检查离线版上所查的考勤记录
	Web_QueryKqReport '00001','2000-1-1','2005-3-8','','00001'

	SELECT * FROM CheckInfo
*/
CREATE	PROCEDURE Web_QueryKqReport
(
	@OperatorId	varchar(50),	--操作员的Id
	@StartDate	datetime,		--开始日期
	@EndDate	datetime,		--截至日期
	@MdCode		varchar(1000),	--门店名称
	@ETypeId	varchar(50),	--职员Id
	@SortField	varchar(50),	--排序字段
	@SortType	varchar(50)		--排序方式
)
--@encode$--
AS
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

--创建临时表
CREATE	TABLE #CheckInfo
(
	ETypeId		varchar(100),	--职员ID
	MdName		varchar(1000),	--门店名称
	UserCode	varchar(256),	--职员编号
	FullName	varchar(256),	--职员名称
	MoITime		varchar(100),	--早班上班时间
	MoOTime		varchar(100),	--早班下班时间
	MiITime		varchar(100),	--中班上班时间
	MiOTime		varchar(100),	--中班下班时间
	GiITime		varchar(100),	--晚班上班时间
	GiOTime		varchar(100)	--晚班下班时间
)

DECLARE @KETypeId	varchar(50),
		@StoreName	varchar(1000),
		@CheckDate	varchar(100),
		@UserCode	varchar(256),
		@FullName	varchar(256),
		@MoITime	varchar(100),	--早班上班时间
		@MoOTime	varchar(100),	--早班下班时间
		@MiITime	varchar(100),	--中班上班时间
		@MiOTime	varchar(100),	--中班下班时间
		@GiITime	varchar(100),	--晚班上班时间
		@GiOTime	varchar(100)	--晚班下班时间

DECLARE Kq_Cursor CURSOR FOR
	SELECT DISTINCT ETypeId,StoreName,CheckDate FROM CheckInfo WHERE CheckDate>=@StartDate AND CheckDate<=@EndDate AND StoreName LIKE '%'+@MdCode+'%' AND ETypeId LIKE @ETypeId + '%'

OPEN Kq_Cursor

FETCH NEXT FROM Kq_Cursor INTO @KETypeId,@StoreName,@CheckDate

WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT @UserCode = UserCode,@FullName = FullName FROM Employee WHERE TypeId = @KETypeId AND Deleted = 0
		
		IF @@ROWCOUNT <> 0
			BEGIN
				INSERT INTO #CheckInfo
				(	
					ETypeId,
					MdName,
					UserCode,
					FullName				
				)VALUES(
					@KETypeId,
					@StoreName,
					@UserCode,
					@FullName
				)
				--写入早班信息
				SELECT	@MoITime = CheckTime FROM CheckInfo WHERE ETypeId = @KETypeId AND StoreName = @StoreName AND CheckDate = @CheckDate AND InOrOut = 'In' AND CheckTerm = '早班'
				IF @@ROWCOUNT <> 0
					UPDATE	#CheckInfo SET MoITime = @MoITime WHERE ETypeId = @KETypeId AND MdName = @StoreName

				SELECT	@MoOTime = CheckTime FROM CheckInfo WHERE ETypeId = @KETypeId AND StoreName = @StoreName AND CheckDate = @CheckDate AND InOrOut = 'Out' AND CheckTerm = '早班'
				IF @@ROWCOUNT <> 0
					UPDATE	#CheckInfo SET MoOTime = @MoOTime WHERE ETypeId = @KETypeId AND MdName = @StoreName

				--写入中班信息
				SELECT	@MiITime = CheckTime FROM CheckInfo WHERE ETypeId = @KETypeId AND StoreName = @StoreName AND CheckDate = @CheckDate AND InOrOut = 'In' AND CheckTerm = '中班'
				IF @@ROWCOUNT <> 0
					UPDATE	#CheckInfo SET MiITime = @MiITime WHERE ETypeId = @KETypeId AND MdName = @StoreName

				SELECT	@MiOTime = CheckTime FROM CheckInfo WHERE ETypeId = @KETypeId AND StoreName = @StoreName AND CheckDate = @CheckDate AND InOrOut = 'Out' AND CheckTerm = '中班'
				IF @@ROWCOUNT <> 0
					UPDATE	#CheckInfo SET MiOTime = @MiOTime WHERE ETypeId = @KETypeId AND MdName = @StoreName

				--写入晚班信息
				SELECT	@GiITime = CheckTime FROM CheckInfo WHERE ETypeId = @KETypeId AND StoreName = @StoreName AND CheckDate = @CheckDate AND InOrOut = 'In' AND CheckTerm = '晚班'
				IF @@ROWCOUNT <> 0
					UPDATE	#CheckInfo SET GiITime = @GiITime WHERE ETypeId = @KETypeId AND MdName = @StoreName

				SELECT	@GiOTime = CheckTime FROM CheckInfo WHERE ETypeId = @KETypeId AND StoreName = @StoreName AND CheckDate = @CheckDate AND InOrOut = 'Out' AND CheckTerm = '晚班'
				IF @@ROWCOUNT <> 0
					UPDATE	#CheckInfo SET GiOTime = @GiOTime WHERE ETypeId = @KETypeId AND MdName = @StoreName

			END
		FETCH NEXT FROM Kq_Cursor INTO @KETypeId,@StoreName,@CheckDate
	END

CLOSE Kq_Cursor
DEALLOCATE Kq_Cursor

DECLARE @SQL varchar(8000)

SET @SQL = 'SELECT * FROM #CheckInfo ORDER BY '+@SortField + ' '+ @SortType

EXEC(@SQL)


DROP TABLE #CheckInfo








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryLendIni]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryLendIni]
GO



CREATE PROCEDURE Web_QueryLendIni 
(
	@OperatorId		varchar(50)--,	--操作员ID
	--@Stypeid        varchar(1550)='00001'   --分支机构ID
)
--@encode$--
AS

--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查------------------------------------------------------ 

CREATE TABLE #Ptype(typeid varchar(50))
CREATE TABLE #Btype(typeid varchar(50))
CREATE TABLE #Ktype(typeid varchar(50))
CREATE TABLE #Stype(typeid varchar(50))

INSERT INTO #Ptype select typeid from F_GetManDetailPType(@OperatorID)
INSERT INTO #Btype select typeid from F_GetManDetailBType(@OperatorID)
INSERT INTO #Ktype select typeid from F_GetManDetailKType(@OperatorID)
--INSERT INTO #Stype select typeid from F_GetAllManagerBaseTypeId(@Stypeid,11,@OperatorId)

DECLARE @SQL NVARCHAR(4000)

SET @SQL='Select A.* 
             from  V_LendFace00  A'

IF NOT (@MPtypeid = '00000')
   SET @SQL=@SQL+' INNER JOIN #Ptype P ON A.PtypeID=P.typeid'

IF NOT (@MBTypeId = '00001' AND @MBTypeId2 = '00002')
   SET @SQL=@SQL+' INNER JOIN #Btype B ON A.BtypeID=B.typeid'

IF NOT (@MKTypeId = '00001')
   SET @SQL=@SQL+' INNER JOIN #Ktype K ON A.KtypeID=K.typeid'
   -- 去掉qty=0的情况，9.0要求显示出来
   SET @SQL=@SQL+' order by bUserCode'
              
EXEC(@SQL)           

DROP TABLE #Ptype
DROP TABLE #Btype
DROP TABLE #Ktype
DROP TABLE #Stype
SET NOCOUNT ON


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





IF EXISTS(SELECT * FROM dbo.sysobjects WHERE Id=OBJECT_ID('[dbo].[Web_QueryLendIniNew]') AND ObjectProperty(id,N'IsProcedure')=1)
	DROP PROCEDURE Web_QueryLendIniNew
GO

/*
	作者：周华
	时间：2012-06-25
	描述：借欠期初也调整成修改的方式
	参见以前的 Web_QueryLendIni这个过程 
*/
CREATE PROCEDURE Web_QueryLendIniNew
	@OperatorId VARCHAR(50)
	,@btypeid VARCHAR(50)='' --往业单位
	,@ktypeid VARCHAR(50)='' --仓库
	,@typeid VARCHAR(50)='00000' --父节点id
--@encode$--
AS
BEGIN
	IF @typeid='' SET @typeid='00000';
	--------------------------------------------------------------权限检查-------------------------------------------------------
	IF @OperatorID IS NULL RETURN 1
	DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
	@MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
	EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
	IF @Re<>0 RETURN @Re
	--------------------------------------------------------------权限检查------------------------------------------------------ 
	-- 树型表 参考Gp_qrStockIni过程 库存期初
	CREATE TABLE #MainType (TypeID varchar(50),usercode varchar(200),fullname varchar(200),sonnum int,deleted int,parid VARCHAR(100),SortID INT)
	DECLARE @sonnum INT=0;
	SELECT @sonnum = sonnum FROM Ptype WHERE Typeid=@typeid
	
	IF @sonnum =0 	
		INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid,SortID) 
		SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId ,p.SortID FROM Ptype p
		,(select * from F_GetManPTypeAll(@OperatorID) where typeid =@typeid) a where p.typeid=a.typeid And p.typeid<>'00000' AND p.IsService=0
		AND p.iscombinationproduct=0
	ELSE
	BEGIN
		IF @typeid='00000'
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid,SortID) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId ,p.SortID FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid='00000') a where p.typeid=a.typeid And p.typeid<>'00000' AND p.IsService=0
			AND p.iscombinationproduct=0
		ELSE
			INSERT INTO #MainType(typeid,usercode,fullname,sonnum,deleted,parid,SortID) 
			SELECT p.typeid,p.usercode,p.fullname,p.sonnum,p.deleted,p.ParId ,p.SortID FROM Ptype p
			,(select * from F_GetManPTypeAll(@OperatorID) where parid=@typeid) a where p.typeid=a.typeid And p.typeid<>'00000' AND p.IsService=0
			AND p.iscombinationproduct=0
	END

	SELECT p.UserCode AS pUserCode,p.FullName AS pFullName,p.sonnum
	,p.typeid,/*ISNULL(i.btypeid,'')*/ @btypeid as btypeid,/*ISNULL(i.ktypeid,'')*/ @ktypeid as ktypeid
	,ISNULL(SUM(i.Qty),0) AS Qty
	/*
	,SUM(CASE WHEN i.Qty>0 THEN i.Qty ELSE 0 END) AS Borrow
	,SUM(CASE WHEN i.Nqty>0 THEN i.Nqty ELSE 0 END) AS BorrowNQty
	,SUM(CASE WHEN i.Qty<0 THEN -i.Qty ELSE 0 END) AS Lend
	,SUM(CASE WHEN i.Nqty<0 THEN -i.NQty ELSE 0 END) AS LendNQty
	*/
	--,CASE WHEN SUM(i.Qty)>0 THEN SUM(i.Qty) ELSE 0 END AS Borrow
	--,CASE WHEN SUM(i.Qty)<0 THEN -SUM(i.Qty) ELSE 0 END AS Lend
	--,CASE WHEN SUM(i.NQty)>0 THEN SUM(i.NQty) ELSE 0 END AS BorrowNQty
	--,CASE WHEN SUM(i.NQty)<0 THEN -SUM(i.NQty) ELSE 0 END AS LendNQty
	-- 2012-08-06 借欠期初展示列表页不进行抵减
	,SUM(i.BorrowQty) AS Borrow
	,SUM(i.LendQty) AS Lend
	,SUM(i.NBorrowQty) AS BorrowNQty
	,SUM(i.NLendQty) AS LendNQty
	FROM #MainType p
	LEFT JOIN btype b ON 1=1
	LEFT JOIN stock k ON 1=1
	LEFT JOIN inigoodslend i --ON p.typeid=i.ptypeid AND i.btypeid=b.typeid AND i.ktypeid=k.typeid
	ON i.ptypeid LIKE p.typeid+'%' AND i.btypeid=b.typeid AND i.ktypeid=k.typeid 
	WHERE p.typeid<>'00000' 
	AND(@btypeid<>'' AND @ktypeid<>'' AND b.typeid=@btypeid AND k.typeid=@ktypeid)
	GROUP BY p.typeid,p.UserCode,p.FullName/*,k.UserCode,k.FullName,k.STypeID,b.UserCode,b.FullName*/,p.sonnum,p.typeId, i.BtypeId, i.KtypeId,p.SortID
	--ORDER BY p.usercode
	ORDER BY p.SortID ASC 
END
GO





IF EXISTS (SELECT TOP 1 1  FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryLicenceBillTypeList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROC dbo.Web_QueryLicenceBillTypeList
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
-- ========================================================================
-- 描述：	业务凭证查询 单据类型
-- 时间：	2017-11-08
-- 作者：	GLJ
-- ========================================================================
CREATE PROC Web_QueryLicenceBillTypeList
(
	@OpertiorId	VARCHAR(50)='00000'	--操作人
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE 
	@ProInfo		INT,--版本信息 2=A8 1=V3 4=V1
	@BillTypeStr	VARCHAR(MAX),--单据类型
	@SQL			VARCHAR(MAX)=''
		
SELECT @ProInfo=SubValue FROM SysData WHERE SubName='ProInfo'

--305	零售单
--215	零售退货单
--11	销售出库单
--45	销售退货单
--160	销售换货单
--140	委托代销发货单
--142	委托代销退货单
--141	委托代销结算单
--34	采购入库单
--6	采购退货单
--161	采购换货单
--144	受托代销收货单
--146	受托代销退货单
--145	受托代销结算单
--21	变价调拨单
--201	其他入库单
--202	其他出库单
--9	报损单
--14	报溢单
--16	生产拆装单
--116	应收增加单
--115	应收减少单
--128	应付增加单
--129	应付减少单
--4	收款单
--189	预收款单
--66	付款单
--190	预付款单
--450	往来核销单
--36	费用单
--158	现金费用单
--77	转款单
--93	其他收入单
--5	待摊费用发生
--10	待摊费用摊销
--84	固定资产(项目)购买单
--85	固定资产(项目)变卖单
--78	固定资产(项目)折旧单
--57	成本调价单
--159	业务凭证
--181	会员储值充值单
--183	积分兑换单
--312	会员批量储值充值单
--427	积分转储值单
SET @BillTypeStr='305,215,11,45,160,4,189,34,6,161,66,190,21,57,14,9,16,201,202,116,115,128,129,450,36,158,93,77,159,140,141,142,144,145,146,84,85,78,5,10,181,312,183,427'

IF(@ProInfo=1 OR @ProInfo=2)
	BEGIN
		--139	赠送单
		--126	获赠单
		--148	返利执行单
		--150	获利执行单
		--149	价保执行单
		--151	获得价保
		--167	维修取件单
		--168	整机更换单
		--170	送修返回单
		--172	上门维修单
		--213	固定资产减少单
		--212	固定资产增加单
		--214	固定资产折旧单(新)
		--311	提成单
		--423	优惠券入库单
		--424	优惠券出库单
		--426	优惠券退货单
		SET @BillTypeStr+=',139,126,148,150,149,151,212,213,214,167,168,170,172,311,423,424,426,327,328,329'
		
		IF(@ProInfo=2)--A8多分支机构单据
			BEGIN
				--187	分支机构调拨出库单
				--188	分支机构调拨入库单
				--428	优惠券分支机构调拨入库单
				--429	优惠券分支机构调拨出库单
				SET @BillTypeStr+=',187,188,428,429'
			END
	END
	
--采用移动加权平均成本核算法	
IF EXISTS(SELECT * FROM SysData WHERE SubName='costing' AND SubValue='0')
	BEGIN
		--205	采购费用分摊单
		SET @BillTypeStr+=',205'
	END
	
--启用发票立账
IF EXISTS(SELECT * FROM SysData WHERE SubName='isinvoice' AND SubValue='1')
	BEGIN
		--400	暂估入库单
		--401	暂估退货单
		--402	发出商品出库单
		--403	发出商品退货单
		--404	采购暂估开票
		--405	销售发货开票
		SET @BillTypeStr+=',400,401,402,403,404,405'
	END
--启用组合品
IF EXISTS(SELECT * FROM SysData WHERE SubName='combinationproduct' AND SubValue='1')
	BEGIN
		--12	组合品销售出库单
		--46	组合品销售退货单
		SET @BillTypeStr+=',12,46'
	END		
--启用运输配送
IF EXISTS(SELECT * FROM SysData WHERE SubName='UseTransport' AND SubValue='1')
	BEGIN
		--414	运输配送单
		SET @BillTypeStr+=',414'
	END
	

SET @SQL='		
SELECT -1 Billtype,''所有单据'' BillName
UNION ALL 
SELECT Billtype,BillName FROM BillName
WHERE Billtype IN('+@BillTypeStr+')'

EXEC(@SQL)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[Web_QueryLineTABLE]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[Web_QueryLineTABLE]
GO


/*
	作者：谢吉康
	日期：2004-11-11
	描述：格式化该存储过程，调整部分算法
		  应收应付的算法已经全部重写	
		  
	 2012-02-20
	 郑红霞添加经手人作为查询条件
  
    日期:2012-06-07
    作者:黄清
    描述:添加币别条件,调整科目
    
    日期:2013-06-05
    作者:鲁大林
    描述:应收查询统计零售退货单、业务类型为变卖的固定资产减少单
		 应付查询统计业务类型为购买的固定资产增加单
	*****固定资产类的新单据只有在系统配置固定资产管理模式为卡片时统计*****
*/
CREATE                   PROCEDURE Web_QueryLineTABLE 
(
	@OperatorID 	VARCHAR(100) ,   --操作员id
	@btypeid 		VARCHAR(100),	--往来单位节点号
	@stypeid		VARCHAR(MAX),	--分支机构
	@dtypeid		VARCHAR(MAX),	--部门
	@DtypeIsVisible	INT,			--1=使用部门 0=不使用部门
	@StartDate		VARCHAR(50),
	@EndDate		VARCHAR(50),
	@IncludePre		VARCHAR(10),
	@option			INT=0,	--选项  0全部显示 1不显示金额为0 2只显示金额为0，3无发生额不显示
	@nType			INT,			--1,3  应收  2,4应付
	@UserCode 		VARCHAR(40),
	@FullName 		VARCHAR(80),
	@SortField		VARCHAR(100)='A.UserCode',
	@SortType		VARCHAR(100)='ASC',
	@etypeid        VARCHAR(MAX),	--经手人
	@cid			VARCHAR(MAX),
	@IsShowAll		BIT  --1=显示所有
)
--@encode$--
AS
SET NOCOUNT ON 
SET ANSI_WARNINGS OFF
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
DECLARE @SortSQL	VARCHAR(8000)

set @etypeid=''

SET @SortSQL = ' ORDER BY '+@SortField+' '+@SortType
IF @bTypeId = '00000' SET @bTypeId = ''

DECLARE @SQL		VARCHAR(8000),
		@lstSQL		VARCHAR(8000),
		@SonNum		INT,
		@SqlWhere	VARCHAR(8000),
		@preSql1	VARCHAR(1000), --应收增加条件(本币)
		@NpreSql1	VARCHAR(1000), --应收增加条件(原币)
		@preSql2	VARCHAR(1000), --应收减少条件(本币)
		@NpreSql2	VARCHAR(1000), --应收减少条件(原币)
		@AtypeType	VARCHAR(1000), --要查询的科目
		@QcSql		VARCHAR(1000),--期初sql  真正的期初+查询时间段前的数据（多了按部门添加，只能期初+开始前的数据+本期增加-本期减少）
		@aratypeID	VARCHAR(50),
		@ysatypeID	VARCHAR(50),
		@apatypeID	VARCHAR(50),
		@yfatypeID	VARCHAR(50)

---查询应收，预收,应付，预付项目ID
SELECT @aratypeID=nId FROM Ac_Items WHERE UserCode='987'
SELECT @ysatypeID=nId FROM Ac_Items WHERE UserCode='2131'

SELECT @apatypeID=nId FROM Ac_Items WHERE UserCode='2121'
SELECT @yfatypeID=nId FROM Ac_Items WHERE UserCode='1151'

IF @option=1
	SET @SqlWhere=' WHERE a.qmtotal<>0 ORDER BY a.usercode'
IF @option=2
	SET @SqlWhere=' WHERE a.qmtotal=0 ORDER BY a.usercode'
IF @option=3
	SET @SqlWhere=' WHERE a.bqaddtotal<>0 OR a.bqrectotal<>0 ORDER BY a.usercode'
SET @preSql1=''
SET @preSql2=''	
SET @NpreSql1=''
SET @NpreSql2=''	

SELECT @SonNum = SonNum FROM BType WHERE TypeId = @btypeid
SET @lstSQL = ' b.TypeId LIKE ''' + @btypeid + '%'''		

CREATE TABLE #stype(typeid	VARCHAR(50))
--分支机构
INSERT INTO #stype(typeid) 
SELECT  A.typeid	FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID) A

--往来单位
CREATE TABLE #btype1(typeid	VARCHAR(50))
INSERT INTO #btype1(typeid) 
SELECT  A.typeid	FROM F_GetAllManagerBaseTypeId(@btypeid,2,@OperatorID) A

--部门
CREATE TABLE #Dtype(typeid VARCHAR(50))
IF @DtypeIsVisible = 1 AND @dtypeid <> ''
	INSERT #dtype(typeid) SELECT TypeId FROM F_GetAllBaseTypeId(@dtypeid,9)


DECLARE @araptotalSql  VARCHAR(MAX)
CREATE TABLE #BtypeIndex(btypeid VARCHAR(50))
IF EXISTS(SELECT 1 FROM #BTYPE1)
	BEGIN
		INSERT INTO #BtypeIndex(btypeid)
		SELECT typeid FROM #btype1
	END
ELSE 
	BEGIN
		INSERT INTO #BtypeIndex
		SELECT TypeID FROM BType WHERE sonnum=0
	END

CREATE TABLE #btype_araptotal
(
	btypeid		VARCHAR(50),
	artotal00	 NUMERIC(24, 10) ,
	aptotal00	 NUMERIC(24, 10) ,
	nartotal00	 NUMERIC(24, 10) ,
	naptotal00	 NUMERIC(24, 10) ,
	ystotal00	 NUMERIC(24, 10) ,
	yftotal00	 NUMERIC(24, 10) ,
	nystotal00	 NUMERIC(24, 10) ,
	nyftotal00	 NUMERIC(24, 10) 
)

SET @araptotalSql ='
	INSERT INTO #btype_araptotal
	SELECT	A.BTypeID,
			ISNULL(B.ARTotal00,0), ISNULL(B.APTotal00,0),
			ISNULL(B.nARTotal00,0), ISNULL(B.nAPTotal00,0),
			ISNULL(B.ysTotal00,0), ISNULL(B.yfTotal00,0),
			ISNULL(B.nysTotal00,0), ISNULL(B.nyfTotal00,0)
	FROM #BtypeIndex A
	LEFT JOIN
	(
		SELECT	a.BTypeID,
		SUM(a.ARTotal00)  AS ARTotal00,   SUM(a.APTotal00)AS APTotal00,
		SUM(a.nARTotal00) AS nARTotal00,  SUM(a.nAPTotal00)AS nAPTotal00 ,
		SUM(a.ysTotal00)  AS ysTotal00,   SUM(a.yfTotal00) AS yfTotal00,
	    SUM(a.nysTotal00) AS nysTotal00,  SUM(a.nyfTotal00) AS nyfTotal00
		FROM IniBType_ArApTotal a '
		
		IF @stypeid <> '' OR @MStypeid='-99999'
			SET @araptotalSql += ' INNER JOIN #STYPE S ON a.STYPEID=S.TYPEID'+CHAR(13)
		
		IF @btypeid <> '' OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @araptotalSql += ' INNER JOIN #btype1 b ON a.BTYPEID=b.TYPEID'+CHAR(13)

		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @araptotalSql += ' INNER JOIN #DTYPE D ON a.DTYPEID=D.TYPEID'+CHAR(13)

		IF @cid<>0
			SET @araptotalSql += ' WHERE a.cid='+CHAR(39)+@cid+CHAR(39)	
	SET @araptotalSql += ' GROUP BY a.BTypeID  '
	
	SET @araptotalSql += ') B ON B.BTypeID = A.BTypeID '

EXEC (@araptotalSql)

CREATE TABLE #BType
(
	TypeId		VARCHAR(100),
	Total00		 NUMERIC(24, 10) ,
	NTotal00	 NUMERIC(24, 10) ,
	BqaddTotal	 NUMERIC(24, 10) ,
	NBqaddTotal	 NUMERIC(24, 10) ,
	BqrecTotal	 NUMERIC(24, 10) ,
	NBqrecTotal	 NUMERIC(24, 10) ,
	Qmtotal		 NUMERIC(24, 10) ,
	NQmtotal	 NUMERIC(24, 10) ,
	ArLimit		 NUMERIC(24, 10) 
)

SET @SQL=
'INSERT INTO #BType
(
	TypeId,
	Total00,
	NTotal00,
	BqaddTotal,
	NBqaddTotal,
	BqrecTotal,
	NBqrecTotal,
	Qmtotal,
	NQmtotal,
	ArLimit
)
SELECT	a.TypeId,
		0 AS Total00,
		0 AS NTotal00,
		0 AS BqaddTotal,
		0 AS NBqaddTotal,
		0 AS BqrecTotal,
		0 AS NBqrecTotal,
		0 AS Qmtotal,	
		0 AS NQmtotal,	
'
--汇率
IF(@cid=0)
	SET @SQL+='SUM(ISNULL(c.credit,0)) AS ArLimit'	
ELSE 
	BEGIN
		DECLARE @BasisType INT=0,@Rate VARCHAR(50)=1
		SELECT @BasisType=BasisType,@Rate=Rate FROM Ac_Currency WHERE CId=@cid
		
		SET @SQL+=CASE WHEN @BasisType=0 THEN 'SUM(ISNULL(c.credit,0))/'+@Rate ELSE 'SUM(ISNULL(c.credit,0))*'+@Rate END +' AS ArLimit'
	END
	
SET @SQL+='	
FROM	F_GetManBTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') a
INNER JOIN btype_credit c ON c.BtypeId=a.typeId '

IF @stypeid<>'' OR @MStypeid<>'00000' 
	SET @SQL=@SQL+' INNER JOIN #stype s ON c.StypeId=s.typeid '

SET @SQL=@SQL+' WHERE SonNum = 0 
	GROUP BY A.typeId '
EXEC(@sql)
--应收
IF @nType=1
BEGIN
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@ysatypeID+CHAR(39)+','+CHAR(39)+@aratypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.Total) '
		SET @NpreSql1=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.NTotal<0  THEN ABS(l.NTotal) '
		SET @preSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.Total>0 THEN l.Total '
		SET @NpreSql2=' WHEN  l.AtypeId='+CHAR(39)+@ysatypeID+CHAR(39)+' AND l.NTotal>0 THEN l.NTotal '

		--期初
		SET @QcSql = ' SUM(ISNULL(a.ARTotal00,0)-ISNULL(a.ystotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
					   SUM(ISNULL(a.nARTotal00,0)-ISNULL(a.nystotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS NTotal00, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@aratypeID+CHAR(39)
		
		SET @QcSql = ' SUM(ISNULL(a.ARTotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
					   SUM(ISNULL(a.nARTotal00,0) + ISNULL(b.naddtotal,0) - ISNULL(b.nrectotal,0)) AS NTotal00, '
	END
	SET @SQL='
	INSERT INTO #BType
	(
		TypeId,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	a.BTypeID,
			'+@QcSql+'
			0 AS bqaddtotal,
			0 AS Nbqaddtotal,
			0 AS bqrectotal,
			0 AS Nbqrectotal,
			0 as qmtotal,
			0 as Nqmtotal,
			0 AS arlimit
	FROM #btype_araptotal a '
			
	SET @SQL=@SQL+'	
	LEFT JOIN 
		(SELECT	L.BTypeId,
				SUM(CASE WHEN l.billtype IN(45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
						 WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,424,426,4) THEN l.Total '+@preSql1+'
						 ELSE 0 
					     END) AS addtotal,
				SUM(CASE WHEN l.billtype in (45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
						 WHEN l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN l.NTotal '+@NpreSql1+'
						 ELSE 0 
					  END) AS Naddtotal,
				SUM(CASE WHEN l.billtype IN(4) AND l.AtypeId='+@aratypeID+'THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
						 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN ABS(l.Total)'+@preSql2+'
						 ELSE 0 
					  END) AS rectotal,
				SUM(CASE WHEN l.billtype IN(4) AND l.AtypeId='+@aratypeID+'THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
						 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN ABS(l.NTotal)'+@NpreSql2+'
						 ELSE 0 
					 END) AS Nrectotal
		FROM	ListTable L  '
			
		IF @stypeid<>'' OR @MStypeid<>'00000' 
			SET @SQL=@SQL+' INNER JOIN #stype s ON L.StypeId=s.typeid '
       
        IF @btypeid <> '' OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL += ' INNER JOIN #btype1 b ON L.BTYPEID=b.TYPEID'+CHAR(13)

		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @SQL += ' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)
       
		SET @SQL=@SQL+' WHERE	L.BillDate < '''+@StartDate+''' 
					AND L.ATypeId IN ('+@AtypeType+')
					AND L.Audited = 1 '
		IF @cid<>0
			SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
		SET @SQL=@SQL+'
			GROUP BY L.BTypeId) b ON a.BTypeID=b.BtypeId '

		SET @SQL=@SQL+'	GROUP BY a.btypeid '
		
	EXEC(@sql)
	----------------应收 计算期初 END
	
	
	----------------应收 计算本期增加，本期减少 BEGIN
	
	--print(@sql)
	SET @SQL='
	INSERT INTO #BType
	(
		TypeId,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	L.BTypeId,
			0 AS total00,
			0 AS Ntotal00,
			SUM(CASE  WHEN l.billtype in (45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.Total
					  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN l.Total'+@preSql1+'
					  ELSE 0
				END) AS bqaddtotal,
			SUM(CASE  WHEN l.billtype in (45,215,11,160,405,424,426) AND l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' THEN l.NTotal
					  WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN l.NTotal '+@NpreSql1+'
					  ELSE 0
					END) AS Nbqaddtotal,
			SUM(CASE WHEN l.billtype IN(4) AND l.AtypeId='+@aratypeID+'THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
					 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN ABS(l.Total)'+@preSql2+'
				 ELSE 0
				END) AS bqrectotal,
			SUM(CASE WHEN l.billtype IN(4) AND l.AtypeId='+@aratypeID+'THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
					 WHEN  l.AtypeId='+CHAR(39)+@aratypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(45,215,11,160,405,424,426,4) THEN ABS(l.NTotal)'+@NpreSql2+'
				 ELSE 0
				END) AS Nbqrectotal,
			0 AS qmtotal,
			0 AS Nqmtotal,
			0 AS ArLimit	
	FROM	ListTable L'
	IF @stypeid<>'' OR @MStypeid<>'00000' 
		SET @SQL=@SQL+' INNER JOIN #stype s ON L.StypeId=s.typeid '
  
    IF @btypeid <> '' OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL += ' INNER JOIN #btype1 b ON L.BTYPEID=b.TYPEID'+CHAR(13)

		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @SQL += ' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)
  
	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@EndDate+' ''
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET	@SQL=@SQL+'	GROUP BY L.BTypeId '
	--print(@sql)
	EXEC(@sql)
END
ELSE
BEGIN
	IF @IncludePre='True'
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)+','+CHAR(39)+@yfatypeID+CHAR(39)
		SET @preSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total<0  THEN ABS(l.Total) '
		SET @NpreSql1=' WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.NTotal<0  THEN ABS(l.NTotal) '
		SET @preSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.Total>0 THEN l.Total '
		SET @NpreSql2='  WHEN  l.AtypeId='+CHAR(39)+@yfatypeID+CHAR(39)+' AND l.NTotal>0 THEN l.NTotal '
		
		SET @QcSql = '
			SUM(ISNULL(a.ApTotal00,0)-ISNULL(a.yftotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00,
			SUM(ISNULL(a.NApTotal00,0)-ISNULL(a.Nyftotal00,0) + ISNULL(b.Naddtotal,0) - ISNULL(b.Nrectotal,0)) AS NTotal00, '
	END
	ELSE
	BEGIN
		SET @AtypeType=CHAR(39)+@apatypeID+CHAR(39)
		
		SET @QcSql = '
			SUM(ISNULL(a.ApTotal00,0) + ISNULL(b.addtotal,0) - ISNULL(b.rectotal,0)) AS Total00, 
			SUM(ISNULL(a.NApTotal00,0) + ISNULL(b.Naddtotal,0) - ISNULL(b.Nrectotal,0)) AS NTotal00,'
	END
	SET @SQL='
	INSERT INTO #BType
	(
		TypeId,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	A.BTypeId,
			'+@QcSql+'
			0 AS bqaddtotal,
			0 AS Nbqaddtotal,
			0 AS bqrectotal,
			0 AS Nbqrectotal,
			0 as qmtotal,
			0 as Nqmtotal,
			0 AS arlimit
	FROM #btype_araptotal a '
		 
	SET @SQL=@SQL+' 
	LEFT JOIN 
	(SELECT	L.BTypeId,
			SUM(CASE WHEN l.billtype IN(6,34,161,404,423) AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(6,34,161,404,423,66) THEN l.Total'+@preSql1+'
				    ELSE 0 END) AS addtotal,
			SUM(CASE  WHEN l.billtype IN(6,34,161,404,423) AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(6,34,161,404,423,66) THEN l.NTotal'+@npreSql1+'
				  ELSE 0 END) AS Naddtotal,
			SUM(CASE WHEN l.billtype IN(66) AND l.AtypeId='+@apatypeID+'THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,404,423,66) THEN ABS(l.Total)'+@preSql2+'
					 ELSE 0 END) AS rectotal,
			SUM(CASE WHEN l.billtype IN(66) AND l.AtypeId='+@apatypeID+'THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END) 
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,404,423,66) THEN ABS(l.NTotal)'+@npreSql2+'
					 ELSE 0 END) AS Nrectotal
	FROM	ListTable L '
		
		IF @stypeid<>'' OR @MStypeid<>'00000' 
			SET @SQL=@SQL+' INNER JOIN #stype s ON L.StypeId=s.typeid '
		
		IF @btypeid <> '' OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL += ' INNER JOIN #btype1 b ON L.BTYPEID=b.TYPEID'+CHAR(13)

		IF @DtypeIsVisible = 1 AND @dtypeid <> ''
			SET @SQL += ' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)
		
		SET @SQL=@SQL+' WHERE	L.BillDate < '''+@StartDate+'''
					AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET @SQL=@SQL+'
		GROUP BY L.BTypeId) b ON a.BTypeID=b.BtypeId '
	SET @SQL=@SQL+'	GROUP BY a.btypeid '
	EXEC(@sql)
	--print(@sql)
		--SELECT * FROM #BType
	SET @SQL='
	INSERT INTO #BType
	(
		TypeId,
		Total00,
		NTotal00,
		BqaddTotal,
		NBqaddTotal,
		BqrecTotal,
		NBqrecTotal,
		Qmtotal,
		NQmtotal,
		ArLimit
	)
	SELECT	L.BTypeId,
			0 AS total00,
			0 AS Ntotal00,
			SUM(CASE  WHEN l.billtype IN(6,34,161,404,423) AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.Total
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total>0 AND l.BillType NOT IN(6,34,161,404,423,66) THEN l.Total'+@preSql1+'
				  ELSE 0
			END) AS bqaddtotal,
			SUM(CASE  WHEN l.billtype IN(6,34,161,404,423) AND l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' THEN l.NTotal
				  WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal>0 AND l.BillType NOT IN(6,34,161,404,423,66) THEN l.NTotal'+@npreSql1+'
				  ELSE 0
			END) AS Nbqaddtotal,
			SUM(CASE  WHEN l.billtype IN(66) AND l.AtypeId='+@apatypeID+'THEN (CASE WHEN l.Total<0 THEN ABS(l.Total) ELSE -l.Total END)
					WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.Total<0 AND  l.BillType NOT IN(6,34,161,404,423,66) THEN ABS(l.Total)'+@preSql2+'
				 ELSE 0
			END) AS bqrectotal,
			SUM(CASE  WHEN l.billtype IN(66) AND l.AtypeId='+@apatypeID+'THEN (CASE WHEN l.NTotal<0 THEN ABS(l.NTotal) ELSE -l.NTotal END)
					 WHEN  l.AtypeId='+CHAR(39)+@apatypeID+CHAR(39)+' AND l.NTotal<0 AND  l.BillType NOT IN(6,34,161,404,423,66) THEN ABS(l.NTotal)'+@npreSql2+'
				 ELSE 0
			END) AS Nbqrectotal,
			0 AS qmtotal,
			0 AS Nqmtotal,
			0 AS ArLimit	
	FROM	ListTable L'
	
	IF @stypeid<>'' OR @MStypeid<>'00000' 
		SET @SQL=@SQL+' INNER JOIN #stype s ON L.StypeId=s.typeid '
		
	IF @btypeid <> '' OR @MBtypeid='-99999' OR @MBtypeid2='-99999'
			SET @SQL += ' INNER JOIN #btype1 b ON L.BTYPEID=b.TYPEID'+CHAR(13)

	IF @DtypeIsVisible = 1 AND @dtypeid <> ''
		SET @SQL += ' INNER JOIN #DTYPE D ON L.DTYPEID=D.TYPEID'+CHAR(13)
   
	SET @SQL=@SQL+' 
		WHERE	L.BillDate<='''+@EndDate+''' 
				AND l.BillDate>='''+@StartDate+'''
				AND L.ATypeId IN ('+@AtypeType+')
				AND L.Audited = 1 '
	IF @cid<>0
		SET @SQL=@SQL+' AND L.cid='+CHAR(39)+@cid+CHAR(39)
	SET	@SQL=@SQL+'	GROUP BY L.BTypeId '
	EXEC(@sql)
	--print(@sql)
	--SELECT * FROM #BType
END


SET @SQL='
SELECT	B.TypeId,
		B.SonNum,
		B.UserCode,
		B.FullName,
		B.deleted,
		b.arapexplain,
		SUM(ISNULL(M.Total00,0)) AS Total00,
		SUM(ISNULL(M.NTotal00,0)) AS NTotal00,
		SUM(ISNULL(m.BqaddTotal,0)) AS bqaddtotal,
		SUM(ISNULL(m.NBqaddTotal,0)) AS Nbqaddtotal,
		SUM(ISNULL(m.BqrecTotal,0)) AS bqrectotal,
		SUM(ISNULL(m.NBqrecTotal,0)) AS Nbqrectotal,
		SUM(ISNULL(M.ArLimit,0)) AS ArLimit,
		SUM(CASE WHEN limitartotal>0 THEN limitartotal
			ELSE NULL
			END) AS limitartotal,
		SUM(ISNULL(M.Total00,0) + ISNULL(M.bqaddtotal,0) - ISNULL(M.bqrectotal,0)) AS qmtotal,
		SUM(ISNULL(M.NTotal00,0) + ISNULL(M.nbqaddtotal,0) - ISNULL(M.nbqrectotal,0)) AS nqmtotal 
FROM	F_GetManBTypeAll('+CHAR(39)+@OperatorID+CHAR(39)+') B
LEFT JOIN (
	SELECT	TypeId,
			SUM(ISNULL(Total00,0)) AS Total00,
			SUM(ISNULL(NTotal00,0)) AS NTotal00,
			SUM(ISNULL(BqaddTotal,0)) AS bqaddtotal,
			SUM(ISNULL(NBqaddTotal,0)) AS Nbqaddtotal,
			SUM(ISNULL(BqrecTotal,0)) AS bqrectotal,
			SUM(ISNULL(NBqrecTotal,0)) AS Nbqrectotal,
			SUM(ISNULL(Qmtotal,0)) AS qmtotal,
			SUM(ISNULL(NQmtotal,0)) AS Nqmtotal,
			SUM(ISNULL(ArLimit,0)) AS ArLimit,
			CASE WHEN SUM(ISNULL(arlimit,0))=0 THEN NULL 
			ELSE   SUM(ISNULL(Total00,0) + ISNULL(bqaddtotal,0) - ISNULL(bqrectotal,0) -ISNULL(arlimit,0))
			END AS limitartotal
	FROM 	#BType
	GROUP BY TypeId
)M ON M.TypeID = B.TypeID '
	
SET @SQL=@SQL+'
WHERE 	'+@lstSQL+' 
		AND b.sonNum=0'

IF @IsShowAll = 0
	SET @SQL += ' AND b.DELETED = 0 '

SET @SQL += ' AND b.usercode LIKE ''%'+@UserCode+'%''
		AND b.fullname LIKE ''%'+@FullName+'%''
GROUP BY	B.TypeId,
			B.SonNum,
			B.UserCode,
			B.FullName,
			B.deleted,
			B.arapexplain
			'
--PRINT(@SQL)
--exec (@sql)
IF @option<>0
	SET @SQL='SELECT * FROM ('+@SQL+') AS a '+@SqlWhere
ELSE
	SET @SQL=@SQL+' ORDER BY B.UserCode'
	
--print(@sql)
EXEC(@SQL)
DROP TABLE #BType,#stype,#BtypeIndex,#Dtype,#btype_araptotal,#btype1



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryLineTableTest]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryLineTableTest]
GO





-- 现在只支持对商品的UserCode和FullName字段进行筛选
--    @QueryType 查询类型
--    @PtypeId  商品ID
--    @KtypeId  仓库ID
--    @StarDate  查询开始日期
--    @EndDate  查询结束日期
--    @UserCode  筛选商品编号
--    @FullName  筛选全名
--    @OrderFild 排序字段(带desc or not) *未实现
--    @PageSize  每页记录数(缺省为14)
--    @PageNO  页号
--    @PageCount 最大页数
CREATE  PROCEDURE Web_QueryLineTableTest
(
    @QueryType  varchar(100),
    @PtypeId  varchar(100),
    @KtypeId  varchar(100),
    @StarDate varchar(100),
    @EndDate varchar(100),
    @UserCode varchar(40),
    @FullName varchar(80),
    @OrderFild varchar(100),
    @PageSize int,
    @PageNO int
--    @PageCount int output
)
--@encode$--
AS

BEGIN
Set Nocount on
--  参数初始值
if @QueryType='' select @QueryType='Sale'
--  @QueryType 的取值
--    1. Sale    : 销售
--    2. InGoods : 进货
--    3. InOut   : 往来 
if @PtypeId='00000' begin select @PtypeId='' end 
if @KtypeId='' begin select @KtypeId='' end 
if @PageSize='' select @PageSize=14
if (@PageNO='') or (@PageNO < 1)  select @PageNO=1
if @UserCode='' select @UserCode=''
if @FullName='' select @FullName=''
Select @PtypeId = @PtypeId + '%'
Select @KtypeId = @KtypeId + '%'
Select @UserCode = @UserCode + '%'
Select @FullName = @FullName + '%'
Declare @PageCount int              -- 记录数量
Declare @SQLText    varchar(8000)    -- 结果语句
Declare @TableName  varchar(250)     -- 临时表名
Declare @iIndexStar int
Declare @iLoop   int
Declare @cPTypeId varchar(100),
 @cUserCode varchar(26),  -- 商品编号
 @cFullName varchar(66),  -- 商品名称
 @cSaleNum  NUMERIC(24, 10) , -- 数量
 @cSalePrice  NUMERIC(24, 10) , -- 均价
 @cSaleTotal  NUMERIC(24, 10)   -- 金额
------------------------------------------------------销售线性表----------------------------------------------------------------------
if @QueryType='Sale'
begin
--  建立临时表
 Select @TableName='Web1'+convert(varchar(2),datepart(dd,GetDate()))+convert(varchar(2),datepart(hh,GetDate()))+convert(varchar(2),datepart(m,GetDate()))+convert(varchar(2),datepart(s,GetDate()))+convert(varchar(4),datepart(ms,GetDate()))
 Select @SQLText='Create Table '+N'##'+@TableName+'([typeId] [varchar] (25) NOT NULL,[商品编号] [varchar] (26) NULL ,[商品名称] [varchar] (66) NOT NULL ,
                                       [销售数量]  NUMERIC(24, 10)  NULL ,[销售均价]  NUMERIC(24, 10)  NULL ,[销售金额]  NUMERIC(24, 10)  NULL )'
 Exec(@SQLText)
 if @@error<>0
 begin
  --RAISERROR('创建临时表发生错误！',16,1)
  return -1
 end
-- 建立游标
 Declare My_Cursor SCROLL CURSOR for 
  select sb.PTypeId,p.UserCode,p.fullname,sb.Qty,SalePrice,sb.Total
  from SaleBill sb,BillIndex bi,pType p
  where sb.BillNumberId = bi.BillNumberID
   and  sb.BillNumberId not in (
     select BillNumberId from SaleBackBill
      )
   and  sb.PtypeId = p.typeId
   and  sb.PtypeID like @PtypeId
   and  bi.KtypeID like @KtypeId
   and  bi.BillDate >= @StarDate
   and  bi.BillDate <= @EndDate
   and  p.UserCode Like @UserCode
   and  p.fullname like @FullName
   and  bi.ifcheck='t'
--   Order By @OrderFild
 Open My_Cursor
 
-- 计算最大记录数
 Select @PageCount = @@Cursor_rows
 if @PageCount < 0
 begin
  --RAISERROR('打开游标错误！',16,1)
  return -2
 end
 Select @PageCount = ((@PageCount-1) / @PageSize) + 1
-- 分页定位记录
 Select  @iIndexStar = @PageSize * (@PageNO -1) 
 fetch ABSOLUTE @iIndexStar from My_Cursor into @cPTypeId,@cUserCode,@cFullName,@cSaleNum,@cSalePrice,@cSaleTotal
-- 循环插入临时表
 Select  @iLoop = @PageSize
 fetch next from My_Cursor into @cPTypeId,@cUserCode,@cFullName,@cSaleNum,@cSalePrice,@cSaleTotal 
 While (@iLoop <> 0) and (@@ERROR = 0) and (@@FETCH_STATUS = 0)
  begin
   Select @SQLText = 'Insert into '+N'##'+@TableName +'([typeId],[商品编号],[商品名称],[销售数量],[销售均价],[销售金额])'
    +' Values( '+char(39)+@cPTypeId+char(39)+',' +char(39)+ @cUserCode+char(39)+','+char(39)+@cFullName+char(39)
    +','+Convert(varchar(18),@cSaleNum)+','+Convert(varchar(18),@cSalePrice)+','+Convert(varchar(18),@cSaleTotal)+')'
   Exec(@SQLText)
   if @@error<>0
   begin
    --RAISERROR('插入临时表记录出错！',16,1)
    return -3
   end
   Select @iLoop=@iLoop - 1
   fetch next from My_Cursor into @cPTypeId,@cUserCode,@cFullName,@cSaleNum,@cSalePrice,@cSaleTotal   
   --print @InsertSQL
  end
 
 Close My_Cursor
 Deallocate My_Cursor
-- 计算总和并插入记录
 Select @SQLText ='Insert into '+N'##'+@TableName +'([typeId],[商品编号],[商品名称],[销售数量],[销售均价],[销售金额])'+
  ' select '''','+char(39)+Convert(varchar(18),@PageCount)+char(39)+
   ',''合计'',Isnull(Sum(sb.Qty),0),Isnull(Sum(SalePrice),0),IsNull(Sum(sb.Total),0)
  from SaleBill sb,BillIndex bi,pType p
  where sb.BillNumberId = bi.BillNumberID
   and  sb.BillNumberId not in (
     select BillNumberId from SaleBackBill
      )
    and  sb.PtypeId = p.typeId
    and  sb.PtypeID like '+ char(39) + @PtypeId + char(39) +
  ' and  bi.KtypeID Like '+ char(39) + @KtypeId + char(39) +
  ' and  bi.BillDate >= '+ char(39) + @StarDate + char(39) +
  ' and  bi.BillDate <='+ char(39) + @EndDate + char(39) + 
  ' and  p.UserCode Like '+ char(39) + @UserCode + char(39) +
  ' and p.fullname like ' + char(39) + @FullName  + char(39) +
  ' and  bi.ifcheck=''t'''
-- if not (@iLoop=@PageSize) 
  Exec(@SQLText)
-- print @SQLText
-- 返回数据 
 Select @SQLText = 'Select [typeId] AS PtypeId,[商品编号] As UserCode,[商品名称] As FullName,[销售数量] As Qty,[销售均价] As Price,[销售金额] As Total from '+N'##'+@TableName
 Exec(@SQLText)
end
------------------------------------------------------进货线性表----------------------------------------------------------------------
if @QueryType='InGoods'
begin
--  建立临时表 
 Select @TableName='Web1'+convert(varchar(2),datepart(dd,GetDate()))+convert(varchar(2),datepart(hh,GetDate()))+convert(varchar(2),datepart(m,GetDate()))+convert(varchar(2),datepart(s,GetDate()))+convert(varchar(4),datepart(ms,GetDate()))
 Select @SQLText='Create Table '+N'##'+@TableName+'([typeId] [varchar] (25) NOT NULL,[商品编号] [varchar] (26) NULL ,[商品名称] [varchar] (66) NOT NULL ,
                                       [销售数量]  NUMERIC(24, 10)  NULL ,[销售均价]  NUMERIC(24, 10)  NULL ,[销售金额]  NUMERIC(24, 10)  NULL )'
 Exec(@SQLText)
 if @@error<>0
 begin
  --RAISERROR('创建临时表发生错误！',16,1)
  return -1
 end
-- 建立游标
 Declare My_jCursor SCROLL CURSOR for 
  select bb.PTypeId,p.UserCode,p.fullname,bb.Qty,SalePrice,bb.Total
  from BuyBill bb,BillIndex bi,pType p
  where bb.BillNumberId = bi.BillNumberID
   and  bb.BillNumberId not in (
     select BillNumberId from SaleBackBill
      )
   and  bb.PtypeId = p.typeId
   and  bb.PtypeID like @PtypeId
   and  bi.KtypeID like @KtypeId
   and  bi.BillDate >= @StarDate
   and  bi.BillDate <= @EndDate
   and  p.UserCode Like @UserCode
   and  p.fullname like @FullName
   and  bi.ifcheck='t'
--   Order By @OrderFild
 Open My_jCursor
 
-- 计算最大记录数
 Select @PageCount = @@Cursor_rows
 if @PageCount < 0
 begin
  --RAISERROR('打开游标错误！',16,1)
  return -2
 end
 Select @PageCount = (@PageCount / @PageSize) + 1
-- 分页定位记录
 Select  @iIndexStar = @PageSize * (@PageNO -1) 
 fetch ABSOLUTE @iIndexStar from My_jCursor into @cPTypeId,@cUserCode,@cFullName,@cSaleNum,@cSalePrice,@cSaleTotal
-- 循环插入临时表
 Select  @iLoop = @PageSize
 fetch next from My_jCursor into @cPTypeId,@cUserCode,@cFullName,@cSaleNum,@cSalePrice,@cSaleTotal 
 While (@iLoop <> 0) and (@@ERROR = 0) and (@@FETCH_STATUS = 0)
  begin
   Select @SQLText = 'Insert into '+N'##'+@TableName +'([typeId],[商品编号],[商品名称],[销售数量],[销售均价],[销售金额])'
    +' Values( '+char(39)+@cPTypeId+char(39)+',' +char(39)+ @cUserCode+char(39)+','+char(39)+@cFullName+char(39)
    +','+Convert(varchar(18),@cSaleNum)+','+Convert(varchar(18),@cSalePrice)+','+Convert(varchar(18),@cSaleTotal)+')'
   Exec(@SQLText)
   if @@error<>0
   begin
    --RAISERROR('插入临时表记录出错！',16,1)
    return -3
   end
   Select @iLoop=@iLoop - 1
   fetch next from My_jCursor into @cPTypeId,@cUserCode,@cFullName,@cSaleNum,@cSalePrice,@cSaleTotal   
   --print @InsertSQL
  end
 
 Close My_jCursor
 Deallocate My_jCursor
-- 计算总和并插入记录
 Select @SQLText ='Insert into '+N'##'+@TableName +'([typeId],[商品编号],[商品名称],[销售数量],[销售均价],[销售金额])'+
  ' select '''','+char(39)+Convert(varchar(18),@PageCount)+char(39)+
   ',''合计'',Isnull(Sum(bb.Qty),0),Isnull(Sum(SalePrice),0),IsNull(Sum(bb.Total),0)
  from BuyBill bb,BillIndex bi,pType p
  where bb.BillNumberId = bi.BillNumberID
   and  bb.BillNumberId not in (
     select BillNumberId from SaleBackBill
      )
    and  bb.PtypeId = p.typeId
    and  bb.PtypeID like '+ char(39) + @PtypeId + char(39) +
  ' and  bi.KtypeID Like '+ char(39) + @KtypeId + char(39) +
  ' and  bi.BillDate >= '+ char(39) + @StarDate + char(39) +
  ' and  bi.BillDate <='+ char(39) + @EndDate + char(39) + 
  ' and  p.UserCode Like '+ char(39) + @UserCode + char(39) +
  ' and p.fullname like ' + char(39) + @FullName  + char(39) +
  ' and  bi.ifcheck=''t'''
-- if not (@iLoop=@PageSize) 
  Exec(@SQLText)
 --print @SQLText
-- 返回数据 
 Select @SQLText = 'Select [typeId] AS PtypeId,[商品编号] As UserCode,[商品名称] As FullName,[销售数量] As Qty,[销售均价] As Price,[销售金额] As Total from '+N'##'+@TableName
 Exec(@SQLText)
end
--if @QueryType='InOut'
------------------------------------------------------往来单位线性表----------------------------------------------------------------------
if @QueryType='InOut'
begin
 Select @SQLText='Select *,(artotal)As arTotal01,(aptotal)As apTotal01 from btype '
  +' where sonnum = 0'
  +' and deleted = 0'
  +' and UserCode like '''+@UserCode+''''
  +' and FullName like '''+@FullName+''''
  +' and (artotal+artotal00+aptotal+aptotal00) <> 0'
IF @PtypeId <> '00000' Select @SQLText = @SQLText + ' and typeId Like ''' + @PtypeId + '%'''
Select @PageCount=@@ROWCOUNT
EXEC(@SQLText)
end 
------------------------------------------------------往来单位线性表(In)----------------------------------------------------------------------
if @QueryType='In'
begin
 Select @SQLText='Select *,(artotal)As arTotal01,(aptotal)As apTotal01 from btype '
  +' where sonnum = 0'
  +' and deleted = 0'
  +' and UserCode like '''+@UserCode+''''
  +' and FullName like '''+@FullName+''''
  +' and (artotal+artotal00) <> 0'
IF @PtypeId <> '00000' Select @SQLText = @SQLText + ' and typeId Like ''' + @PtypeId + '%'''
Select @PageCount=@@ROWCOUNT
EXEC(@SQLText)
end 
------------------------------------------------------往来单位线性表(out)----------------------------------------------------------------------
if @QueryType='Out'
begin
 Select @SQLText='Select *,(artotal)As arTotal01,(aptotal)As apTotal01 from btype '
  +' where sonnum = 0'
  +' and deleted = 0'
  +' and UserCode like '''+@UserCode+''''
  +' and FullName like '''+@FullName+''''
  +' and (aptotal+aptotal00) <> 0'
IF @PtypeId <> '00000' Select @SQLText = @SQLText + ' and typeId Like ''' + @PtypeId + '%'''
 
Select @PageCount=@@ROWCOUNT
EXEC(@SQLText)
end 
END
exec Web_QueryLineTableTest 'Sale','','','2000-01-01','2002-01-01','','','',14,1
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if exists (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryLoadedGoodsKPI_Bill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryLoadedGoodsKPI_Bill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：OneV
	日期：2016-06-22
	描述：职员装车KPI统计
*/
CREATE PROCEDURE Web_QueryLoadedGoodsKPI_Bill
(
	@OperatorId			VARCHAR(100),	--操作员ID
	@STypeId			VARCHAR(MAX),	--分支机构
	@StartDate			datetime,	--开始日期
	@EndDate			datetime,	--结束日期
	@ETYPEID		VARCHAR(MAX),--经手人
	@DTYPEID		VARCHAR(MAX),--部门
	@KTYPEID		VARCHAR(MAX)--仓库
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--分支机构
CREATE TABLE #GetSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--仓库
CREATE TABLE #ktype(TypeId	VARCHAR(100))
INSERT INTO #ktype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@KTYPEID,4,@OperatorID)

--部门---
CREATE TABLE #DTYPE(TYPEID VARCHAR(200))
INSERT INTO #DTYPE SELECT typeid FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)
--职员--
CREATE TABLE #ETYPE(TYPEID VARCHAR(200))
INSERT INTO #ETYPE SELECT typeid FROM F_GetAllManagerBaseTypeId(@ETYPEID,3,@OperatorID)



DECLARE @DecParam NVARCHAR(max), @sql Nvarchar(Max)

SET @sql=N'

;with Detail as (
	SELECT  billnumberid 
	FROM	Transportbill 
)
, qtyData as (
				SELECT  i.billnumberid
						,i.etypeid
						,i.billcode
						,i.billdate
						,i.posttime
						,i.stypeid
						,i.ktypeid
						,i.dtypeid
						,i.billtype
						,i.totalqty 
				FROM billindex i '			
	SET @sql+=N'	INNER JOIN  #GetSTypeId s ON i.stypeid=s.typeid 	'		
	SET @sql+=N'	INNER JOIN  #ETYPE e ON i.etypeid=e.typeid 	'		
	SET @sql+=N'	INNER JOIN  #DTYPE d ON i.dtypeid=d.typeid 	'
	SET @sql+=N'	INNER JOIN  #ktype k ON i.ktypeid=k.typeid 	'
SET @sql+=N'	WHERE billdate BETWEEN @StartDate and @EndDate 
						AND i.billtype=414
						AND i.ifcheck=''t''
						and i.RedWord=0
						AND i.ifyearbill=0
						AND Exists( SELECT  billnumberid FROM Detail where billnumberid=i.billnumberid )
'


SET @sql+=N')
SELECT* FROM qtyData 
'

SET @DecParam=N'
		@StartDate datetime
		,@EndDate datetime
		,@ETYPEID   varchar(100)
		,@OperatorID  varchar(100)
';
EXEC sp_executesql @sql,@DecParam,@StartDate,@EndDate,@ETYPEID,@OperatorID
	
	DROP TABLE  #GetSTypeId,#ktype,#ETYPE,#DTYPE
	
	
	
-- DECLARE @curPos INT = 1 , @count INT = 1  
-- WHILE (@curPos < len(@sql))  
-- BEGIN  
--	 PRINT substring(@sql, @curPos, @curPos + 3999)  
--	 SET @curPos += 3999 + 1  
--	 SET @count += 1  
-- END  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryLoadedGoodsKPI_Line]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryLoadedGoodsKPI_Line]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：OneV
	日期：2016-06-22
	描述：职员装车KPI统计
*/
CREATE PROCEDURE Web_QueryLoadedGoodsKPI_Line
(
	@OperatorId			VARCHAR(100),	--操作员ID
	@STypeId			VARCHAR(MAX),	--分支机构
	@StartDate			datetime,	--开始日期
	@EndDate			datetime,	--结束日期
	@ETYPEID		VARCHAR(MAX),--经手人
	@DTYPEID		VARCHAR(MAX),--部门
	@KTYPEID		VARCHAR(MAX)--仓库
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------

--分支机构
CREATE TABLE #GetSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--仓库
CREATE TABLE #ktype(TypeId	VARCHAR(100))
INSERT INTO #ktype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@KTYPEID,4,@OperatorID)

--部门---
CREATE TABLE #DTYPE(TYPEID VARCHAR(200))
INSERT INTO #DTYPE SELECT typeid FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

--职员--
CREATE TABLE #ETYPE(TYPEID VARCHAR(200))
INSERT INTO #ETYPE SELECT typeid FROM F_GetAllManagerBaseTypeId(@ETYPEID,3,@OperatorID)

DECLARE @DecParam NVARCHAR(max), @sql Nvarchar(Max)

SET @sql=N'
;with qtyData as (
				SELECT i.etypeid,sum(details.qty) as qty
				FROM billindex i 
						INNER JOIN  Transportbill  details  ON i.billnumberid=details.billnumberid	'
	SET @sql+=N'	INNER JOIN  #GetSTypeId s ON i.stypeid=s.typeid 	'		
	SET @sql+=N'	INNER JOIN  #ETYPE e ON i.etypeid=e.typeid 	'		
	SET @sql+=N'	INNER JOIN  #DTYPE d ON i.dtypeid=d.typeid 	'
	SET @sql+=N'	INNER JOIN  #ktype k ON i.ktypeid=k.typeid 	'

SET @sql+=N'	WHERE billdate BETWEEN @StartDate and @EndDate
						AND i.billtype=414
						AND i.ifcheck=''t''
						 AND i.RedWord=0
						 AND i.ifyearbill=0
				group by  i.etypeid'


SET @sql+=N') 
SELECT * FROM qtyData 
'

SET @DecParam=N'
		@StartDate datetime
		,@EndDate datetime
	
		,@ETYPEID   varchar(100)
		,@OperatorID  varchar(100)
';
EXEC sp_executesql @sql,@DecParam,@StartDate,@EndDate,@ETYPEID,@OperatorID

DROP TABLE  #GetSTypeId,#ktype,#ETYPE,#DTYPE
	
	
-- DECLARE @curPos INT = 1 , @count INT = 1  
-- WHILE (@curPos < len(@sql))  
-- BEGIN  
--	 PRINT substring(@sql, @curPos, @curPos + 3999)  
--	 SET @curPos += 3999 + 1  
--	 SET @count += 1  
-- END  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (SELECT * FROM dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryLoadedGoodsKPI_Tree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryLoadedGoodsKPI_Tree]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：OneV
	日期：2016-06-22
	描述：职员装车KPI统计
*/
CREATE PROCEDURE Web_QueryLoadedGoodsKPI_Tree
(
	@parid varchar(60),
	@OperatorId			VARCHAR(100),	--操作员ID
	@STypeId			VARCHAR(MAX),	--分支机构
	@StartDate			datetime,	--开始日期
	@EndDate			datetime,	--结束日期
	@ETYPEID		VARCHAR(MAX),--经手人
	@DTYPEID		VARCHAR(MAX),--部门
	@KTYPEID		VARCHAR(MAX)--仓库
)
--@encode$--
AS
SET NOCOUNT ON
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re int,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT
IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
if ISNULL(@parid,'')=''
 SET @parid='00001'


--分支机构
CREATE TABLE #GetSTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetSTypeId(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)

--仓库
CREATE TABLE #ktype(TypeId	VARCHAR(100))
INSERT INTO #ktype(TypeId) SELECT typeid FROM F_GetAllManagerBaseTypeId(@KTYPEID,4,@OperatorID)

--部门---
CREATE TABLE #DTYPE(TYPEID VARCHAR(200))
INSERT INTO #DTYPE SELECT typeid FROM F_GetAllManagerBaseTypeId(@DTYPEID,9,@OperatorID)

--职员--
CREATE TABLE #ETYPE(TYPEID VARCHAR(200))
INSERT INTO #ETYPE SELECT typeid FROM F_GetAllManagerBaseTypeId(@ETYPEID,3,@OperatorID)


DECLARE @DecParam NVARCHAR(max), @sql Nvarchar(Max)

SET @sql=N'
;with  EtypeLimit as  (
	SELECT typeid,sonnum,parid FROm F_AllTreeE(@OperatorID) where parid=@parid
)
, qtyData as (
				SELECT i.etypeid,sum(details.qty) as qty
				FROM billindex i 
						INNER JOIN  Transportbill  details  ON i.billnumberid=details.billnumberid'
				
	SET @sql+=N'	INNER JOIN  #GetSTypeId s ON i.stypeid=s.typeid 	'		
			
	SET @sql+=N'	INNER JOIN  #DTYPE d ON i.dtypeid=d.typeid 	'

	SET @sql+=N'	INNER JOIN  #ktype k ON i.ktypeid=k.typeid 	'

	SET @sql+=N'	INNER JOIN  #ETYPE el ON i.etypeid=el.typeid 	'

SET @sql+=N'	WHERE i.billdate BETWEEN @StartDate and @EndDate
					  AND i.billtype=414
					   AND i.ifcheck=''t''
					   AND i.RedWord=0
					   AND i.ifyearbill=0
				group by  i.etypeid'


SET @sql+=N') 
,data as (
			SELECT e.typeid as etypeid,e.sonnum,e.parid,ISNULL(sum(d.qty),0) as qty
			FROM EtypeLimit e 
				 INNER JOIN  qtyData d ON d.etypeid like e.typeid+''%''	 
			group by  e.typeid,e.sonnum,e.parid 	 
			
)
SELECT	*
FROM data d 
ORDER BY etypeid
'

SET @DecParam=N'
		@StartDate datetime
		,@EndDate datetime
		,@parid   varchar(100)
		,@OperatorID  varchar(100)
';
EXEC sp_executesql @sql,@DecParam,@StartDate,@EndDate,@parid,@OperatorID

DROP TABLE  #GetSTypeId,#ktype,#DTYPE
	
	
	
 DECLARE @curPos INT = 1 , @count INT = 1  
 WHILE (@curPos < len(@sql))  
 BEGIN  
	 PRINT substring(@sql, @curPos, @curPos + 3999)  
	 SET @curPos += 3999 + 1  
	 SET @count += 1  
 END  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryLoginUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryLoginUser]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
GO
/*
	作者：黄清
	日期：2013-12-30
	描述：添加操作员选择
*/

CREATE         PROCEDURE [dbo].[Web_QueryLoginUser]
(
	@OperatorId		VARCHAR(100),		--操作员Id	
	@TypeId			VARCHAR(100),		--基本信息的Id
	@Filter			VARCHAR(300)=''		--过滤 1、编号  2、名称  3、拼音码 
)
--@encode$--
AS
SET NOCOUNT ON

--特殊处理[符号
SET @Filter = REPLACE(@Filter,'[','[[]')	
--------------------------------------------------------------权限检查-------------------------------------------------------
IF @OperatorID IS NULL RETURN 1
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23 @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
--------------------------------------------------------------权限检查-------------------------------------------------------
--************************************************************职员基本信息************************************************************
IF @TypeId = '' SET @TypeId = '00001'
DECLARE @eSonNum int,
		@eParId  VARCHAR(200)

CREATE TABLE #Employee
(
	TypeID		VARCHAR(100),
	ParId		VARCHAR(100),
	SonNum		int,
	UserCode	VARCHAR(400),
	FullName	VARCHAR(400),
	PyCode		VARCHAR(400),
	Deleted		int
)

--判断权限范围
IF NOT EXISTS(SELECT TOP 1 1 FROM LoginUser WHERE ETypeId = @OperatorId AND MangerETypeId = '00001')
	INSERT INTO #Employee(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM F_GetManETypeAll(@OperatorId) WHERE deleted = 0
ELSE
	INSERT INTO #Employee(TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted) SELECT TypeId,ParId,SonNum,UserCode,FullName,PyCode,Deleted FROM Employee WHERE deleted = 0

SELECT @eSonNum = SonNum,@eParId=ParId FROM #Employee WHERE TypeId = @TypeId 
--select *from #Employee
IF @Filter = ''
	BEGIN
		IF @TypeId = '00001'
			SELECT	TypeId,ParId,SonNum,UserCode,FullName,1 as optype	FROM #Employee WHERE  ParId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode	
		ELSE 
			BEGIN
				IF @eSonNum = 0
					SELECT	TypeId,ParId,SonNum,UserCode,FullName,1 as optype	FROM #Employee WHERE SonNum = 0 AND TypeId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode
				ELSE
					SELECT	TypeId,ParId,SonNum,UserCode,FullName,1 as optype	FROM #Employee WHERE ParId = @TypeId AND TypeId <> '00000' AND TypeId <> '00001' ORDER BY UserCode	
			END
	END
ELSE
	BEGIN
		SELECT	TypeId,ParId,SonNum,UserCode,FullName,1 as optype	FROM #Employee WHERE SonNum = 0 AND TypeId LIKE @METypeId + '%' AND (UserCode LIKE '%'+@Filter+'%' OR FullName LIKE '%'+@Filter+'%' OR PyCode LIKE '%'+@Filter+'%')
				AND TypeId <> '00000'	
				AND TypeId <> '00001'
		ORDER BY UserCode
	END

DROP TABLE #Employee
	  
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_QueryLoseOverFlow]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_QueryLoseOverFlow]
GO



/*
	作者：俞俊杰
	日期：2012-10-31
	描述：查询报损报溢单数据
*/
CREATE   PROCEDURE Web_QueryLoseOverFlow
    (
      @OperatorID VARCHAR(1550) ,
      @stypeid VARCHAR(MAX) ,
      @ktypeid VARCHAR(MAX) ,
      @startdate DATETIME ,
      @enddate DATETIME ,
      @showkcinfo INT ,
      @unitconvert INT
	
    )
--@encode$--
AS 
    SET NOCOUNT ON

-------------------------------------------------------------------------------------------------------
    CREATE TABLE #temp_ptype
        (
          typeId VARCHAR(50) ,
          UserCode VARCHAR(200) ,
          FullName VARCHAR(200)
        )--创建临时表存放商品数据
    CREATE TABLE #temp_LoseBill
        (
          PtypeId VARCHAR(50) ,
          LoseQty  NUMERIC(24, 10)  ,
          LoseTotal  NUMERIC(24, 10) 
        )--创建临时表存放报损单数据
    CREATE TABLE #temp_overflowBill
        (
          PtypeId VARCHAR(50) ,
          overflowQty  NUMERIC(24, 10)  ,
          overflowTotal  NUMERIC(24, 10) 
        )--创建临时表存放报溢单数据
    CREATE TABLE #temp_GoodsStocks
        (
          PtypeId VARCHAR(50) ,
          StockQty  NUMERIC(24, 10)  ,
          StockTotal  NUMERIC(24, 10) 
        )--创建临时表存放仓储数据
    CREATE TABLE #temp_Result
        (
          typeId VARCHAR(50) ,
          UserCode VARCHAR(200) ,
          FullName VARCHAR(200) ,
          Unit VARCHAR(200) ,
          overflowTotal  NUMERIC(24, 10)  ,
          overflowQty  NUMERIC(24, 10)  ,
          LoseTotal  NUMERIC(24, 10)  ,
          LoseQty  NUMERIC(24, 10)  ,
          StockTotal  NUMERIC(24, 10)  ,
          StockQty  NUMERIC(24, 10)  ,
        )--创建临时结果数据
    CREATE TABLE #temp_Unit
        (
          typeId VARCHAR(50) ,
          FullName VARCHAR(200) ,
          Rate  NUMERIC(24, 10) 
        )--创建临时结果数据
    CREATE TABLE #GetManStype ( TypeID VARCHAR(100) ) --分支机构表
    CREATE TABLE #GetManKType ( TypeID VARCHAR(100) ) --仓库表
    CREATE TABLE #GetManPType ( TypeID VARCHAR(100) ) --商品表
-------------------------------------------------------------------------------------------------------

    IF @stypeid = '' 
        INSERT  INTO #GetManStype
                SELECT  TypeId
                FROM    F_BaseGetManDetailSType(@OperatorID)
    ELSE 
        INSERT  INTO #GetManStype
                SELECT  a.TypeId
                FROM    F_BaseGetManDetailSType(@OperatorID) a ,
                        ( SELECT    *
                          FROM      dbo.f_split(@StypeID, ',')
                        ) b
                WHERE   LEFT(a.typeid, LEN(b.a)) = b.a
--商品
    INSERT  INTO #GetManPType
            SELECT  TypeId
            FROM    F_GetManDetailPType(@OperatorID)
--仓库
    IF @ktypeid = '' 
        INSERT  INTO #GetManKType
                ( TypeId
                )
                SELECT  TypeId
                FROM    F_GetManDetailKType(@OperatorID) 
    ELSE 
        INSERT  INTO #GetManKType
                SELECT  TypeId
                FROM    F_GetManDetailKType(@OperatorID) a ,
                        ( SELECT    *
                          FROM      dbo.f_split(@ktypeid, ',')
                        ) b
                WHERE   LEFT(a.TypeId, LEN(b.a)) = b.a
--------------------------------------------------------------------------------------------------------------------------
----插入商品数据
    IF @showkcinfo = 0 
        BEGIN
            INSERT  INTO #temp_ptype
                    SELECT DISTINCT
                            ( Ptypeid ) ,
                            UserCode ,
                            FullName
                    FROM    ( SELECT DISTINCT
                                        ( O.ptypeid ) ,
                                        p.UserCode ,
                                        p.FullName
                              FROM      dbo.overflowBill O
                                        INNER JOIN dbo.ptype P ON O.PtypeId = p.typeId
                                        INNER JOIN dbo.BillIndex B ON O.BillNumberId = B.BillNumberId
                                        INNER JOIN #GetManStype GS ON GS.TypeID = B.Stypeid
                                        INNER JOIN #GetManKType GT ON GT.TypeID = B.ktypeid
                              WHERE     B.BillDate <= @enddate
                                        AND B.BillDate >= @startdate
                                        AND B.ifWX = 0
                                        AND B.ifcheck = 't'
                                        AND B.RedWord = 0
                                         AND p.IsService=0
                              UNION ALL
                              SELECT DISTINCT
                                        ( L.ptypeid ) ,
                                        p.UserCode ,
                                        p.FullName
                              FROM      dbo.LoseBill L
                                        INNER JOIN dbo.ptype P ON L.PtypeId = P.typeId
                                        INNER JOIN dbo.BillIndex B ON L.BillNumberId = B.BillNumberId
                                        INNER JOIN #GetManStype GS ON GS.TypeID = B.Stypeid
                                        INNER JOIN #GetManKType GT ON GT.TypeID = B.ktypeid
                              WHERE     B.BillDate <= @enddate
                                        AND B.BillDate >= @startdate
                                        AND B.ifWX = 0
                                        AND B.ifcheck = 't'
                                        AND B.RedWord = 0
                                        AND p.IsService=0
                            ) AS A
                            INNER JOIN #GetManPType GP ON A.Ptypeid = GP.TypeID
		----插入报损单数据
            INSERT  INTO #temp_LoseBill
                    SELECT  L.PtypeId ,
                            SUM(L.Qty) ,
                            SUM(L.Total)
                    FROM    LoseBill L
                            INNER JOIN BillIndex B ON L.BillNumberId = B.BillNumberId
                            INNER JOIN #GetManStype GS ON GS.TypeID = B.Stypeid
                            INNER JOIN #GetManKType GT ON GT.TypeID = B.ktypeid
                    WHERE   B.BillDate <= @enddate
                            AND B.BillDate >= @startdate
                            AND B.ifWX = 0
                            AND B.ifcheck = 't'
                            AND B.RedWord = 0
                    GROUP BY L.PtypeId
		 ----插入报溢单数据
            INSERT  INTO #temp_overflowBill
                    SELECT  O.PtypeId ,
                            SUM(O.Qty) ,
                            SUM(O.Total)
                    FROM    dbo.overflowBill O
                            INNER JOIN BillIndex B ON O.BillNumberId = B.BillNumberId
                            INNER JOIN #GetManStype GS ON GS.TypeID = B.Stypeid
                            INNER JOIN #GetManKType GT ON GT.TypeID = B.ktypeid
                    WHERE   B.BillDate <= @enddate
                            AND B.BillDate >= @startdate
                            AND B.ifWX = 0
                            AND B.ifcheck = 't'
                            AND B.RedWord = 0
                    GROUP BY O.PtypeId
		--插入库存数据
            INSERT  INTO #temp_GoodsStocks
                    SELECT  G.PtypeId ,
                            SUM(G.Qty) ,
                            SUM(G.Total)
                    FROM    dbo.GOODSSTOCKS G
                            INNER JOIN dbo.Stock S ON G.KtypeId = S.typeId
                            INNER JOIN #GetManStype GS ON GS.TypeID = S.Stypeid
                            INNER JOIN #GetManKType GT ON GT.TypeID = S.typeId
                    GROUP BY G.PtypeId
        END
    ELSE 
        BEGIN
            INSERT  INTO #temp_ptype
                    SELECT DISTINCT
                            ( Ptypeid ) ,
                            UserCode ,
                            FullName
                    FROM    ( SELECT DISTINCT
                                        ( O.ptypeid ) ,
                                        p.UserCode ,
                                        p.FullName 
                              FROM      dbo.overflowBill O
                                        INNER JOIN dbo.ptype P ON O.PtypeId = p.typeId
                                        INNER JOIN dbo.BillIndex B ON O.BillNumberId = B.BillNumberId
                                        INNER JOIN #GetManStype GS ON GS.TypeID = B.Stypeid
                                        INNER JOIN #GetManKType GT ON GT.TypeID = B.ktypeid
                              WHERE     B.BillDate <= @enddate
                                        AND B.BillDate >= @startdate
                                        AND B.ifWX = 1
                                        AND B.ifcheck = 't'
                                        AND B.RedWord = 0
                                         AND p.IsService=0
                              UNION ALL
                              SELECT DISTINCT
                                        ( L.ptypeid ) ,
                                        p.UserCode ,
                                        p.FullName
                              FROM      dbo.LoseBill L
                                        INNER JOIN dbo.ptype P ON L.PtypeId = P.typeId
                                        INNER JOIN dbo.BillIndex B ON L.BillNumberId = B.BillNumberId
                                        INNER JOIN #GetManStype GS ON GS.TypeID = B.Stypeid
                                        INNER JOIN #GetManKType GT ON GT.TypeID = B.ktypeid
                              WHERE     B.BillDate <= @enddate
                                        AND B.BillDate >= @startdate
                                        AND B.ifWX = 1
                                        AND B.ifcheck = 't'
                                        AND B.RedWord = 0
                                         AND p.IsService=0
                            ) AS A
                            INNER JOIN #GetManPType GP ON A.Ptypeid = GP.TypeID
                            
		----插入报损单数据
            INSERT  INTO #temp_LoseBill
                    SELECT  L.PtypeId ,
                            SUM(L.Qty) ,
                            SUM(L.Total)
                    FROM    LoseBill L
                            INNER JOIN BillIndex B ON L.BillNumberId = B.BillNumberId
                            INNER JOIN #GetManStype GS ON GS.TypeID = B.Stypeid
                            INNER JOIN #GetManKType GT ON GT.TypeID = B.ktypeid
                    WHERE   B.BillDate <= @enddate
                            AND B.BillDate >= @startdate
                            AND B.ifWX = 1
                            AND B.ifcheck = 't'
                            AND B.RedWord = 0
                    GROUP BY L.PtypeId
		 ----插入报溢单数据
            INSERT  INTO #temp_overflowBill
                    SELECT  O.PtypeId ,
                            SUM(O.Qty) ,
                            SUM(O.Total)
                    FROM    dbo.overflowBill O
                            INNER JOIN BillIndex B ON O.BillNumberId = B.BillNumberId
                            INNER JOIN #GetManStype GS ON GS.TypeID = B.Stypeid
                            INNER JOIN #GetManKType GT ON GT.TypeID = B.ktypeid
                    WHERE   B.BillDate <= @enddate
                            AND B.BillDate >= @startdate
                            AND B.ifWX = 1
                            AND B.ifcheck = 't'
                            AND B.RedWord = 0
                    GROUP BY O.PtypeId
		--插入库存数据
            INSERT  INTO #temp_GoodsStocks
                    SELECT  G.PtypeId ,
                            SUM(G.Qty) ,
                            SUM(G.Total)
                    FROM    dbo.wx_GoodsStocks G
                            INNER JOIN dbo.Stock S ON G.KtypeId = S.typeId
                            INNER JOIN #GetManStype GS ON GS.TypeID = S.Stypeid
                            INNER JOIN #GetManKType GT ON GT.TypeID = S.typeId
                    GROUP BY G.PtypeId
        END
--查询报损报溢单汇总数据
    INSERT  INTO #temp_Result
            SELECT  P.typeId ,
                    p.UserCode ,
                    p.FullName ,
                    NULL ,
                    ISNULL(o.overflowTotal, 0) AS overflowTotal ,
                    ISNULL(o.overflowQty, 0) AS overflowQty ,
                    ISNULL(L.LoseTotal, 0) AS LoseTotal ,
                    ISNULL(L.LoseQty, 0) AS LoseQty ,
                    ISNULL(G.StockTotal, 0) AS StockTotal ,
                    ISNULL(G.StockQty, 0) AS StockQty
            FROM    #temp_ptype P
                    LEFT JOIN #temp_overflowBill O ON P.typeId = O.PtypeId
                    LEFT JOIN #temp_LoseBill L ON P.typeId = L.PtypeId
                    LEFT JOIN #temp_GoodsStocks G ON P.typeId = G.PtypeId
--------处理多单位数据
    IF @unitconvert = 3 
        INSERT  INTO #temp_Unit
                SELECT  PtypeID ,
                        pu.FullName ,
                        pue.Rate
                FROM    dbo.ptype p
                        INNER JOIN dbo.PType_Units pu ON pu.UnitsId = p.baseUnitId
                        INNER JOIN dbo.PType_Units_Ext pue ON p.baseUnitId = pue.UnitsId
                                                              AND p.typeId = pue.PtypeID     
    IF @unitconvert = 2 
        INSERT  INTO #temp_Unit
                SELECT  PtypeID ,
                        pu.FullName ,
                        pue.Rate
                FROM    dbo.ptype p
                        INNER JOIN dbo.PType_Units pu ON pu.UnitsId = p.StockUnitId
                        INNER JOIN dbo.PType_Units_Ext pue ON p.StockUnitId = pue.UnitsId
                                                              AND p.typeId = pue.PtypeID
                       
    IF @unitconvert = 1 
        INSERT  INTO #temp_Unit
                SELECT  PtypeID ,
                        pu.FullName ,
                        pue.Rate
                FROM    dbo.ptype p
                        INNER JOIN dbo.PType_Units pu ON pu.UnitsId = p.BuyUnitId
                        INNER JOIN dbo.PType_Units_Ext pue ON p.BuyUnitId = pue.UnitsId
                                                              AND p.typeId = pue.PtypeID
                       
    IF @unitconvert = 0 
        INSERT  INTO #temp_Unit
                SELECT  PtypeID ,
                        pu.FullName ,
                        pue.Rate
                FROM    dbo.ptype p
                        INNER JOIN dbo.PType_Units pu ON pu.UnitsId = p.SaleUnitId
                        INNER JOIN dbo.PType_Units_Ext pue ON p.SaleUnitId = pue.UnitsId
                                                              AND p.typeId = pue.PtypeID
    UPDATE  #temp_Result
    SET     Unit = tu.FullName ,
            overflowTotal = overflowTotal,
            overflowQty = overflowQty / tu.Rate ,
            LoseTotal = LoseTotal,
            LoseQty = LoseQty / tu.Rate ,
            StockTotal = StockTotal,
            StockQty = StockQty / tu.Rate
    FROM    #temp_Unit tu
            INNER JOIN #temp_Result tr ON tr.typeId = tu.typeId
 
    SELECT  *
    FROM    #temp_Result ORDER BY UserCode 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[Web_QueryLoseOverFlowDetail]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[Web_QueryLoseOverFlowDetail]
GO



/*
	作者：俞俊杰
	日期：2012-10-31
	描述：查询报损报溢单数据
*/
CREATE   PROCEDURE Web_QueryLoseOverFlowDetail
    (
      @OperatorID VARCHAR(50) ,
      @stypeid VARCHAR(50) ,
      @ktypeid VARCHAR(50) ,
      @startdate DATETIME ,
      @enddate DATETIME ,
      @showkcinfo INT ,
      @ptypeid VARCHAR(50)
    )
--@encode$--
AS 
    SET NOCOUNT ON

-------------------------------------------------------------------------------------------------------
    CREATE TABLE #GetManStype ( TypeID VARCHAR(100) ) --分支机构表
    CREATE TABLE #GetManKType ( TypeID VARCHAR(100) ) --仓库表
    CREATE TABLE #GetManPType ( TypeID VARCHAR(100) ) --商品表
-------------------------------------------------------------------------------------------------------
--分支机构 
    IF @stypeid = '' 
        INSERT  INTO #GetManStype
                SELECT  TypeId
                FROM    F_BaseGetManDetailSType(@OperatorID)
    ELSE 
        INSERT  INTO #GetManStype
                SELECT  a.TypeId
                FROM    F_BaseGetManDetailSType(@OperatorID) a ,
                        ( SELECT    *
                          FROM      dbo.f_split(@StypeID, ',')
                        ) b
                WHERE   LEFT(a.typeid, LEN(b.a)) = b.a
--商品
    IF @ptypeid = '' 
        INSERT  INTO #GetManPType
                SELECT  TypeId
                FROM    F_GetManDetailPType(@OperatorID)
    ELSE 
        INSERT  INTO #GetManPType
                SELECT  a.TypeId
                FROM    F_GetManDetailPType(@OperatorID) a ,
                        ( SELECT    *
                          FROM      dbo.f_split(@ptypeid, ',')
                        ) b
                WHERE   LEFT(a.typeid, LEN(b.a)) = b.a
--仓库
    IF @ktypeid = '' 
        INSERT  INTO #GetManKType
                ( TypeId
                )
                SELECT  TypeId
                FROM    F_GetManDetailKType(@OperatorID) 
    ELSE 
        INSERT  INTO #GetManKType
                SELECT  TypeId
                FROM    F_GetManDetailKType(@OperatorID) a ,
                        ( SELECT    *
                          FROM      dbo.f_split(@ktypeid, ',')
                        ) b
                WHERE   LEFT(a.TypeId, LEN(b.a)) = b.a
--------------------------------------------------------------------------------------------------------------------------
    IF @showkcinfo = 0 
        BEGIN
        SELECT * FROM (
            SELECT  c.BillNumberId ,
                    c.BillDate ,
                    B.BillCode ,
                    B.Stypeid ,
                    c.billtype ,
                    c.ptypeid ,
                    c.qty ,
                    c.Qty AS overflowqty ,
                    C.CostTotal AS overflowtotal ,
                    0 AS loseqty ,
                    0 AS losetotal ,
                    c.CostPrice ,
                    c.ktypeid ,
                    B.Comment ,
                    c.Total ,
                    c.CostTotal ,
                    B.RedWord,
                    SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
            FROM    inoutstocktable c
            INNER JOIN dbo.BillIndex B ON c.BillNumberId = B.BillNumberId
            INNER JOIN #GetManKType GK ON GK.TypeID = C.KtypeId
            INNER JOIN #GetManPType GP ON GP.TypeID = c.PtypeId
            INNER JOIN #GetManStype GS ON GS.TypeID = b.Stypeid
             left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
left join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND c.id=csdetail.Detailid
            WHERE   B.BillType = 14
                    AND c.BillDate >= @startdate
                    AND c.BillDate <= @enddate
            UNION ALL
            SELECT  c.BillNumberId ,
                    c.BillDate ,
                    B.BillCode ,
                    B.Stypeid ,
                    c.billtype ,
                    c.ptypeid ,
                    c.qty ,
                    0 AS overflowqty ,
                    0 AS overflowtotal ,
                    -c.Qty AS loseqty ,
                    -CostTotal AS losetotal ,
                    c.CostPrice ,
                    c.ktypeid ,
                    B.Comment ,
                    c.Total ,
                    c.CostTotal ,
                    B.RedWord,
                    SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
            FROM    inoutstocktable c
            INNER JOIN dbo.BillIndex B ON c.BillNumberId = B.BillNumberId
            INNER JOIN #GetManKType GK ON GK.TypeID = C.KtypeId
            INNER JOIN #GetManPType GP ON GP.TypeID = c.PtypeId
            INNER JOIN #GetManStype GS ON GS.TypeID = b.Stypeid
             left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
left join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND c.id=csdetail.Detailid
            WHERE   B.BillType  = 9
                    AND c.BillDate >= @startdate
                    AND c.BillDate <= @enddate
             ) AS TEMP ORDER BY BillCode
        END
    ELSE 
        BEGIN
        SELECT * FROM (
            SELECT  c.BillNumberId ,
                    c.BillDate ,
                    B.BillCode ,
                    B.Stypeid ,
                    c.billtype ,
                    c.ptypeid ,
                    c.qty ,
                    c.Qty AS overflowqty ,
                    C.CostTotal AS overflowtotal ,
                    0 AS loseqty ,
                    0 AS losetotal ,
                    c.CostPrice ,
                    c.ktypeid ,
                    B.Comment ,
                    c.Total ,
                    c.CostTotal ,
                    B.RedWord,
                    SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
            FROM    dbo.wx_InOutStockTable c
            INNER JOIN dbo.BillIndex B ON c.BillNumberId = B.BillNumberId
            INNER JOIN #GetManKType GK ON GK.TypeID = C.KtypeId
            INNER JOIN #GetManPType GP ON GP.TypeID = c.PtypeId
            INNER JOIN #GetManStype GS ON GS.TypeID = b.Stypeid
             left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
left join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND c.id=csdetail.Detailid
            WHERE   B.BillType = 14
                    AND c.BillDate >= @startdate
                    AND c.BillDate <= @enddate
            UNION ALL
            SELECT  c.BillNumberId ,
                    c.BillDate ,
                    B.BillCode ,
                    B.Stypeid ,
                    c.billtype ,
                    c.ptypeid ,
                    c.qty ,
                    0 AS overflowqty ,
                    0 AS overflowtotal ,
                    -c.Qty AS loseqty ,
                    -C.CostTotal AS losetotal ,
                    c.CostPrice ,
                    c.ktypeid ,
                    B.Comment ,
                    c.Total ,
                    c.CostTotal ,
                    B.RedWord,
                    SysDiy1_head,SysDiy2_head,SysDiy3_head,SysDiy4_head, SysDiy5_head,SysDiy6_head,SysDiy7_head,SysDiy8_head,SysDiy9_head,
				SysDiy10_head,SysDiy11_head,SysDiy12_head,SysDiy13_head,SysDiy14_head,SysDiy15_head,SysDiy16_head,
				SysDiy1,SysDiy2,SysDiy3,SysDiy4,SysDiy5,SysDiy6,SysDiy7,SysDiy8,SysDiy9,SysDiy10,
				SysDiy11,SysDiy12,SysDiy13,SysDiy14,SysDiy15,SysDiy16
            FROM    dbo.wx_InOutStockTable c
            INNER JOIN dbo.BillIndex B ON c.BillNumberId = B.BillNumberId
            INNER JOIN #GetManKType GK ON GK.TypeID = C.KtypeId
            INNER JOIN #GetManPType GP ON GP.TypeID = c.PtypeId
            INNER JOIN #GetManStype GS ON GS.TypeID = b.Stypeid
             left join Custom_BillIndex csindex on b.billnumberid=csindex.BillId and b.billtype=csindex.billtype
left join Custom_BillDetails csdetail on b.billnumberid=csdetail.BillId and b.billtype=csdetail.billtype AND c.id=csdetail.Detailid
            WHERE   B.BillType  =9
                    AND c.BillDate >= @startdate
                    AND c.BillDate <= @enddate ) AS TEMP
            ORDER BY BillCode
        END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryMeAlreadyAuditingBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryMeAlreadyAuditingBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：杨俊
	日期：2014-12-18
	描述：我的已审核列表 @IfAudit = 1 查询已审核
	修改：2015-05-20 修改取已审核的表
*/
CREATE PROCEDURE Web_QueryMeAlreadyAuditingBill
(
	@OperatorId		VARCHAR(100),
	@StartDate		VARCHAR(50),
	@EndDate		VARCHAR(50),	
	@BillCode		VARCHAR(100),
	@BillType		VARCHAR(50),
	@Comment		VARCHAR(200),
	@IfAudit		VARCHAR(50),
	@iscurrentauditing BIT,
	@stypeid		VARCHAR(MAX),--分支机构
	@etypeid		VARCHAR(MAX),--职员
	@checke			VARCHAR(MAX)='' --制单人
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

DECLARE @combinationproduct	VARCHAR(10)
select @combinationproduct=subvalue from sysdata where subname='combinationproduct'


--只显示其他审核步骤完成的单据	
DECLARE @currentauditing	VARCHAR(MAX)
IF @iscurrentauditing = 1
	SET @currentauditing = 	
		' AND ( 
				(
				  F.AuditingType = 3 
				AND  
				 (SELECT COUNT(allcharindex) FROM FN_GetAllCharIndex(''1'',A.PassSteps)) - (SELECT COUNT(allcharindex) FROM FN_GetAllCharIndex(''1'',A.AuditingSteps)) = 1
				) 
				OR  F.AuditingType <> 3
			  )'
ELSE
	SET @currentauditing = ''	
-------------------------------------
/*---是否统一往来单位
DECLARE @isAllBtype VARCHAR(50)
SELECT @isAllBtype = Value FROM dbo.Userconfig WHERE ConfigName = 'btypeall'*/ 

DECLARE @SQL VARCHAR(MAX)

--描  述：检查调拨当中入库仓库是否有效
DECLARE @MoveInOutKLimit  INT
SELECT @MoveInOutKLimit=Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit' --配置

--增加权限
 --往来单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)

--经手人
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid <> '00001'
BEGIN
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	
END

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)
DECLARE @GetKtypeCount int,@KtypeCount int  ---全部仓库
		 
IF @MKtypeId = '00000'
	INSERT INTO #GetManKTypeId(TypeId) VALUES('00000')

INSERT INTO #GetManKTypeId(TypeId) VALUES('10000')
	
	
--部门
CREATE TABLE #GetManDtypeId(TypeId	varchar(100))
IF @MDtypeid = '-99999'
INSERT INTO #GetManDtypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

--分支机构
CREATE TABLE #GetManStypeId(TypeId	varchar(100))
IF @MStypeid = '-99999'
INSERT INTO #GetManStypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--制单人
CREATE TABLE #GetManChecke(TypeId	varchar(100))
INSERT INTO #GetManChecke(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@checke,3)
/*IF @MEtypeid <> '00001' OR @checke <> ''
BEGIN
	IF @checke = ''
	BEGIN
		INSERT INTO #GetManChecke(TypeId) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@checke,3,@OperatorID)
		UNION ALL
		SELECT '00001'
	END
	ELSE
		INSERT INTO #GetManChecke(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@checke,3,@OperatorID)
END	*/

-- //搬敏捷
-- 调拨权限
DECLARE @dp NCHAR(1)='0'; --部门
DECLARE @ep NCHAR(1)='0'; --经手人
SELECT @dp=RIGHT(LEFT(lim,3013),1),@ep=RIGHT(LEFT(lim,3014),1) FROM loginuser WHERE etypeid=@OperatorId
--//


DECLARE @SQL_WHERE_SZ VARCHAR(MAX),@re_re INT--单据查看权限

SELECT @SQL_WHERE_SZ = ' where ( '
	EXEC @re_re=GP_CheckLimit @OperatorID,2676
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 305 or'		--零售查看(POS单查看)

EXEC @re_re=GP_CheckLimit @OperatorID,2679
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 11 or'			--销售单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2682
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 45 or'			--销售退货单查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2709
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 215 or'		--零售退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2831
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 4 or'			--收款单查看


EXEC @re_re=GP_CheckLimit @OperatorID,2718
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 34 or'			--采购单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2721
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 6 or'			--采购退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2837
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 66 or'			--付款单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2739
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 17 or'			--同价调拨单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2742
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 21 or'			--变价调拨单查看


EXEC @re_re=GP_CheckLimit @OperatorID,2751
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 9 or'			--报损单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2754
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 14 or'			--报溢单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2688
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 139 or'		--赠送单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2727
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 126 or'		--获赠单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2882

IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 57 or'			--调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2769
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 16 or'			--商品拆装单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2819
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 116 or'		--应收款增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2822

IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 115 or'		--应收款减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2825
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 128 or'		--应付款增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2828
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 129 or'		--应付款减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2855
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 36 or'			--费用单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2864
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 93 or'			--其他收入单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2861
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 77 or'			--转款单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2873
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 84 or'			--固定资产(项目)购买查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2914
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 212 or'		--固定资产增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2876
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 85 or'			--固定资产(项目)变卖查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2917
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 213 or'		--固定资产减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2879
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 78 or'			--固定资产(卡片)折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2920
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 78 or'			--固定资产(项目)折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2920
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 214 or'		--固定资产折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2867
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 5 or'			--待摊费用发生查看

EXEC @re_re=GP_CheckLimit @OperatorID,2870
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 10 or'			--待摊费用摊销查看


EXEC @re_re=GP_CheckLimit @OperatorID,2843
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 148 or'		--返利执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2849
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 149 or'		--价保执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2691
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 140 or'		--委托代销发货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2700
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 141 or'		--委托代销结算单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2694
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 142 or'		--委托代销退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2697
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 143 or'		--委托代销调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2923
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 144 or'		--受托代销收货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2736
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 145 or'		--受托代销结算单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2730
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 146 or'		--受托代销退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2733
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 147 or'		--受托代销调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2846
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 150 or'		--获利核算执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2781
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 156 or'		--维修接件单 -- 单据查看权限

EXEC @re_re=GP_CheckLimit @OperatorID,2852
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 151 or'		--获得价保过账

EXEC @re_re=GP_CheckLimit @OperatorID,2858								--现金费用单
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 158 or'			

EXEC @re_re=GP_CheckLimit @OperatorID,2885								--会计凭证
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 159 or'			

EXEC @re_re=Gp_CheckLimit @OperatorID,2685
IF @re_re = 0															--销售换货单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 160 or'			

EXEC @re_re=Gp_CheckLimit @OperatorID,2724
IF @re_re = 0															--采购换货单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 161 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2781
IF @re_re = 0															--维修接件单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 165 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2784
IF @re_re = 0															--维修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 166 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2787
IF @re_re = 0															--维修取件单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 167 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2790
IF @re_re = 0															--整机更换单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 168 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2793
IF @re_re = 0															--送修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 169 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2796
IF @re_re = 0															--送修返回单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 170 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2799
IF @re_re = 0															--报修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 171 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2802
IF @re_re = 0															--上门维修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 172 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2805
IF @re_re = 0															--维修品调入单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 173 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2808
IF @re_re = 0															--维修品调出单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 174 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2811
IF @re_re = 0															--维修品调拨单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 175 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2906
IF @re_re = 0															--积分兑换单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 183 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,1368
IF @re_re = 0															--保险理赔单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 186 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2745
IF @re_re = 0															--分支机构调拨出库单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 187 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2748
IF @re_re = 0															--分支机构调拨入库单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 188 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2834
IF @re_re = 0															--预收款单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 189 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2840
IF @re_re = 0															--预付款单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 190 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,1472
IF @re_re = 0															--领料出库单----------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 191 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,1474
IF @re_re = 0															--领料退回单-------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 197 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1487
IF @re_re = 0															--维修结算单-----------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 195 or'			
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1477
IF @re_re = 0															--救援单----------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 196 or'		
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1478
IF @re_re = 0															--三包索赔单--------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 200 or'		
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2775
IF @re_re = 0															--其他入库单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 201 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2778
IF @re_re = 0															--其他出库单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 202 or'									

EXEC @re_re=Gp_CheckLimit @OperatorID,2772
IF @re_re = 0															--序列号调整单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 203 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2888
IF @re_re = 0															--采购费用分摊 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 205 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2891
IF @re_re = 0															--销售费用分摊 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 206 or'		
			
EXEC @re_re=Gp_CheckLimit @OperatorID,2713
IF @re_re = 0															--询价单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 185 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2711
IF @re_re = 0															--请购单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 204 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2715
IF @re_re = 0															--采购订单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 301 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2673
IF @re_re = 0															--销售订单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 300 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2671
IF @re_re = 0															--报价单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 184 or'		

--不是总账则不显示资金调拨单
IF((SELECT SubValue FROM SYSDATA WHERE SUBNAME = 'isuseacsystem') = 1)
BEGIN
	EXEC @re_re=Gp_CheckLimit @OperatorID,4318
	IF @re_re = 0														--资金调拨单  
		SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 310 or'
END

EXEC @re_re=Gp_CheckLimit @OperatorID,2988
IF @re_re = 0															--提成单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 311 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,2900
IF @re_re = 0															--会员储值充值单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 181 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4501
IF @re_re = 0															--会员批量储值充值单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 312 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2757
IF @re_re = 0															--借出开单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 87 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2760
IF @re_re = 0															--借进开单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 71 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2763
IF @re_re = 0															--借出还回单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 88 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2766
IF @re_re = 0															--借进还出单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 72 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,4581
IF @re_re = 0															--暂估入库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 400 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4590
IF @re_re = 0															--暂估退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 401 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4602
IF @re_re = 0															--发出商品出库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 402 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4611
IF @re_re = 0															--发出商品退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 403 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4622
IF @re_re = 0															--采购暂估开票  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 404 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4630
IF @re_re = 0															--销售发货开票  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 405 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,4678
IF @re_re = 0															--往来核销  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 450 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4745
IF @re_re = 0															--组合品销售订单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 313 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,4749
IF @re_re = 0															--组合品销售出库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 12 or'
         
EXEC @re_re=Gp_CheckLimit @OperatorID,4757
IF @re_re = 0															--组合品销售出退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 46 or'
 -- 仓库入库
 EXEC @re_re=Gp_CheckLimit @OperatorID,4832
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 418 or'
 -- 仓库出库
  EXEC @re_re=Gp_CheckLimit @OperatorID,4840
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 419 or'
 -- 仓库调拨单
 EXEC @re_re=Gp_CheckLimit @OperatorID,4848
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 420 or'
	
 -- 门店配送单
 EXEC @re_re=Gp_CheckLimit @OperatorID,5244
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 327 or'
	
 -- 门店退货单
 EXEC @re_re=Gp_CheckLimit @OperatorID,5253
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 328 or'	
	
--配送验收单配送验收单	
EXEC @re_re=Gp_CheckLimit @OperatorID,5262
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 329 or'		

SELECT @SQL_WHERE_SZ = @SQL_WHERE_SZ + ' r.billtype = 1000 )  '			--随便添加一个BillType用来拼凑字符串


SET @SQL = '; WITH TEMP AS
	(
	SELECT	B.BillNumberId,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.totalmoney,
			B.ETypeId,
			B.dealBTypeId,
			B.btypeid,
			b.stypeid,
			CASE 
				WHEN c.AuditingType = ''1'' THEN ''顺序审核''
				WHEN c.AuditingType = ''2'' THEN ''任意审核''
				ELSE ''会签审核''
			END AS AudType,
			c.BillIndexType AS BillIndexType,
			c.AuditStep AS AuditingStep,
			B.checke,
			B.checktime,
			B.ifcheck,
			B.IfAudit,
			B.CostSale 
	FROM	
	(
	

		SELECT B.BillNumberId,
				''3'' AS BillIndexType,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.totalmoney,
				B.ETypeId,
				'''' AS dealBTypeId,
				'''' AS btypeid,
				B.STypeId,
				B.checke,
				B.checktime,
				CASE B.IfAudit
					WHEN 1 THEN ''t''
					ELSE ''f'' 
				END AS ifcheck,
				B.IfAudit,
				0 as CostSale 
		FROM AuditingBillDetail A
		INNER JOIN dbo.RequestIndex B ON B.BillNumberId = A.BillNumberId '

IF @MEtypeid <> '00001' OR @checke <> ''
	SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = b.STypeId '
	SET @SQL=@sql+' WHERE A.BillIndexType = ''3''
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				--AND a.IfAudit IN(''-1'','''+@IfAudit+''') 
				AND A.ETypeId = '''+ @OperatorID +'''
				'
IF @BillCode <> ''
	SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
IF @Comment <> ''
	SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
IF @BillType <> ''
	SET @SQL += ' AND B.BillType = '+@BillType+' '
ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411)'
IF @combinationproduct = '0' OR @combinationproduct is null 
	SET @SQL += ' AND B.BillType NOT IN (313)'
 		 
IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @etypeid<>''	 OR @MEtypeid <> '00001'
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @MDtypeid='-99999'
		SET @sql+=' AND b.DTypeId IN (SELECT TypeId FROM #GetManDtypeId)  '
SET @SQL += '
UNION ALL 
		SELECT	B.BillNumberId,
				''0'' AS BillIndexType,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.totalmoney,
				B.ETypeId,
				B.dealBTypeId,
				B.btypeid,
				B.STypeId,
				B.checke,
				B.checktime,
				CASE B.IfAudit
					WHEN 1 THEN ''t''
					ELSE ''f'' 
				END AS ifcheck,
				B.IfAudit,
				0 AS CostSale 
		FROM	AuditingBillDetail A
		INNER JOIN OrderIndex B ON B.BillNumberId = A.BillNumberId '
	
	IF @MEtypeid <> '00001' OR @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' INNER JOIN #GetManBTypeId B1 ON B1.TypeId = B.dealBTypeId
					  INNER JOIN #GetManBTypeId B2 ON B2.typeid=B.btypeid '
	IF @MKtypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId '
	IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	SET @SQL += '
		WHERE	A.BillIndexType = ''0''
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				--AND a.IfAudit IN(''-1'','''+@IfAudit+''')  
				AND A.ETypeId = '''+ @OperatorID +'''
				'
				
	IF @MEtypeid <> '00001'
		SET @sql+=' AND (B.ETypeId IN (SELECT TypeId FROM #GetManETypeId) OR B.BillType IN(17,21) AND '+@ep+'=''1'') '
	IF @MDtypeid='-99999'
		SET @sql+=' AND (B.DTypeId IN (SELECT TypeId FROM #GetManDtypeId) OR B.BillType IN(17,21) AND '+@dp+'=''1'') '
IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @etypeid<>''
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
				
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'

	SET @SQL += '
	UNION ALL
	SELECT	B.BillNumberId,
			''2'' AS BillIndexType,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.totalmoney,
			B.ETypeId,
			B.dealBTypeId,
			B.btypeid,
			B.STypeId,
			B.checke,
			B.checktime,
			B.ifcheck,
			CASE B.ifcheck
				WHEN ''t'' THEN 1
				ELSE 0 
			END AS IfAudit,
			B.CostSale 
	FROM	AuditingBillDetail A
	INNER JOIN BillIndex B ON B.BillNumberId = A.BillNumberId '

	IF(@BillType <> '310')
	BEGIN
		IF @MStypeid = '-99999'
			SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	END
	
		
	IF @MEtypeid <> '00001' OR @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
		
	SET @SQL += '
		WHERE	A.BillIndexType = ''2''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''' 
				--AND a.IfAudit IN(''-1'','''+@IfAudit+''') 
				AND B.RedWord = 0 
				AND A.ETypeId = '''+ @OperatorID +'''
				'
	
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'		
		
	IF(@BillType = '310') 
	BEGIN
		--IF @stypeid<>''
		SET @sql+='  and 
		( 
			b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+')) 
			OR b.StypeID2 in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+')) 
		
		)'
	END
	ELSE
	BEGIN
		IF @stypeid<>''
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	END

	IF @etypeid<>''
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	
	IF @MEtypeid <> '00001'
		SET @sql+=' AND (B.ETypeId IN (SELECT TypeId FROM #GetManETypeId) OR B.BillType IN(17,21) AND '+@ep+'=''1'') '

	IF @MDtypeid='-99999'
		SET @sql+=' AND (B.DTypeId IN (SELECT TypeId FROM #GetManDtypeId) OR B.BillType IN(17,21) AND '+@dp+'=''1'') '
	
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' AND (
							(
								B.dealBTypeID IN (SELECT typeid FROM #GetManBTypeId) AND B.BillType IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''12'',''46'')
							)
							OR
							(
								B.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''12'',''46'')
							)
						) 
					AND (
							(
								B.BTypeID IN (SELECT typeid FROM #GetManBTypeId) AND B.BillType IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''450'',''12'',''46'')
							)
							OR
							(
								B.BillType NOT IN (''305'',''11'',''45'',''34'',''6'',''4'',''66'',''36'',''35'',''84'',''85'',''139'',''126'',''140'',''141'',''142'',''144'',''145'',''146'',''147'',''148'',''149'',''150'',''151'',''160'',''161'',''201'',''202'',''189'',''190'',''450'',''12'',''46'')
							)
						) '
						
	IF @MKtypeid = '-99999'
	BEGIN
		SET @SQL += '
			AND (
					(
						( B.KTypeID IN (SELECT typeid FROM #GetManKTypeId) OR B.KTypeID2 IN (SELECT typeid FROM #GetManKTypeId)) AND B.BillType IN (''16'',''155'',''157'',''160'',''161'',''201'',''202'') 
					) 
					OR 
					(
						B.BillType IN (''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''147'',''201'',''202'',''400'',''401'',''402'',''403'',''12'',''46'') AND B.KTypeID IN (SELECT typeid FROM #GetManKTypeId)
					) 
					OR 
					( '
		IF @MoveInOutKLimit = 1
			SET @SQL = @SQL + '	B.BillType IN (''17'',''21'') AND (B.KTypeId IN (SELECT typeid FROM #GetManKTypeId) AND B.KTypeId2 IN (SELECT typeid FROM #GetManKTypeId)) '
		ELSE
			SET @SQL = @SQL + ' B.BillType IN (''17'',''21'') AND (B.KTypeId IN (SELECT typeid FROM #GetManKTypeId) OR B.KTypeId2 IN (SELECT typeid FROM #GetManKTypeId)) '
		SET @SQL = @SQL + '
					)
					OR
					(
						B.BillType NOT IN (''16'',''155'',''157'',''305'',''11'',''45'',''34'',''6'',''9'',''14'',''57'',''139'',''126'',''140'',''142'',''144'',''146'',''147'',''17'',''21'',''160'',''161'',''201'',''202'',''400'',''401'',''402'',''403'',''12'',''46'')
					)
				) '
	END
	
	
	SET @SQL += ' 
	UNION ALL
			SELECT B.BillNumberId,
			''4'' AS BillIndexType,
			B.BillDate,
			B.BillCode,
			''311'' AS BillType,
			B.Total AS totalmoney,
			'''' AS ETypeId,
			'''' AS dealBTypeId,
			'''' AS btypeid,
			B.STypeId,
			B.checke,
			B.checketime AS checktime,
			B.ifcheck,
			CASE B.ifcheck
				WHEN ''t'' THEN 1
				ELSE 0 
			END AS IfAudit,
			0 AS CostSale 
		    FROM AuditingBillDetail A 
		    INNER JOIN CommissionBillNew AS B ON(B.BillNumberId = A.BillNumberId) 
		    INNER JOIN employee AS C ON(B.Checke = C.typeId)  '
	
	IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
		
	IF @MEtypeid <> '00001'	or @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	SET @SQL += '
		WHERE	A.BillIndexType = ''4''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				--AND A.IfAudit IN(''-1'','''+ CAST(CASE WHEN @IfAudit = '' THEN 0 ELSE @IfAudit END AS VARCHAR(10))+''') 
				AND B.RedWord = 0 
				AND A.ETypeId = '''+ @OperatorID +'''
				'
				
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND 311 = '+@BillType+' '			
					
	IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	
	SET @SQL+=' AND ''' + @etypeid +''' = '''' '
	
	
	SET @SQL += ' 
	UNION ALL
			SELECT B.BillNumberId,
			''1'' AS BillIndexType,
			B.BillDate,
			B.BillCode,
			b.BillType,
			''0'' AS totalmoney,
			b.ETypeId,
			b.dealBTypeId,
			b.btypeid,
			B.STypeId,
			B.checke,
			B.checktime,
			B.ifcheck,
			B.IfAudit,
			0 AS CostSale 
		    FROM AuditingBillDetail A 
		    INNER JOIN LendIndex AS B ON(B.BillNumberId = A.BillNumberId)  '
	SET @SQL += '
		WHERE	A.BillIndexType = ''1''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				--AND A.IfAudit = '''+ CAST(CASE WHEN @IfAudit = '' THEN 0 ELSE @IfAudit END AS VARCHAR(10))+''' 
				--AND B.IfCheck = ''f''
				--AND B.Draft = ''1'' 
				AND B.RedWord = 0 
				AND A.ETypeId = '''+ @OperatorID +'''
				'
	IF @stypeid<>''
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @etypeid<>''
			SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'
		
	SET @SQL += ' 
	UNION ALL
	SELECT B.BillNumberId,
			''7'' AS BillIndexType,
			B.BillDate,
			B.BillCode,
			b.BillType,
			''0'' AS totalmoney,
			b.ETypeId,
			'''' AS dealBTypeId,
			'''' AS btypeid,
			B.STypeId,
			B.checke,
			B.checktime,
			B.ifcheck,
			1 AS IfAudit,
			0 AS CostSale 
		    FROM AuditingBillDetail A 
		    INNER JOIN FactIndex AS B ON(B.BillNumberId = A.BillNumberId)  '
		    
	IF @MEtypeid <> '00001' OR @checke <> ''
				SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	IF @MDtypeid='-99999'
		SET @sql+=' INNER JOIN #GetManDtypeId AS D ON(B.DTypeId = D.Typeid) '
					  
	SET @SQL += '
		WHERE	A.BillIndexType = ''7''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate +''''
				
	
	IF @MKtypeid = '-99999'
	BEGIN
		  SET @sql+=' AND ( (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype IN (418,419))'
		  IF @MoveInOutKLimit=1
		  BEGIN
			 SET @sql+=' OR (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId)  AND  B.ktypeid2 in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype=420) )'
		  END
		  ELSE
		  BEGIN
			 SET @sql+=' OR (B.ktypeid in ( SELECT typeid FROM #GetManKTypeId)  OR  B.ktypeid2 in ( SELECT typeid FROM #GetManKTypeId) AND B.billtype=420)  )'
		  END
	END
	
	IF @stypeid<>''	 or @MStypeid = '-99999'
			SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @etypeid<>''	OR @MEtypeid <> '00001'
			SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'
	
	SET @SQL += ' 
	UNION ALL
			SELECT B.BillNumberId,
			''5'' AS BillIndexType,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.TaxTotalMoney AS totalmoney,
			B.ETypeId,
			B.dealBTypeId,
			B.btypeid,
			B.STypeId,
			B.checke,
			B.checktime,
			B.ifcheck,
			B.IfAudit,
			0 AS CostSale 
		    FROM AuditingBillDetail A 
		    INNER JOIN ReceiptBillIndex AS B ON(B.BillNumberId = A.BillNumberId) 
		    '

	IF @MStypeid = '-99999'
			SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	
	IF @MEtypeid <> '00001' OR @checke <> ''
				SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	 IF @MEtypeid <> '00001' OR @etypeid <> ''  
		SET @SQL += ' INNER JOIN #GetManETypeId e ON e.TypeId = B.etypeid '
	IF @MDtypeid='-99999'
		SET @sql+=' INNER JOIN #GetManDtypeId AS D ON(B.DTypeId = D.Typeid) '
		
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' INNER JOIN #GetManBTypeId B1 ON B1.TypeId = B.dealBTypeId
					  INNER JOIN #GetManBTypeId B2 ON B2.typeid=B.btypeid '	
		
	SET @SQL += '
		WHERE	A.BillIndexType = ''5''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''' 
				AND B.RedWord = 0 
				AND A.ETypeId = '''+ @OperatorID +'''
				'
	
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'
		
	SET @SQL += ' 
	UNION ALL
			SELECT  B.BillNumberId,
					''9'' AS BillIndexType,
					B.BillDate,
					B.BillCode,
					B.BillType,
					B.Total AS totalmoney,
					B.ApplyEtypeId,
					'''' AS dealBTypeId,
					'''' AS btypeid,
					B.STypeId,
					B.checke,
					B.checktime,
					B.ifcheck,
					CASE B.ifcheck
					WHEN ''t'' THEN 1
					ELSE 0 
					END AS IfAudit,
					0 AS CostSale 
		    FROM   AuditingBillDetail A 
		    INNER JOIN PosAllotApplyBillIndex AS B ON(B.BillNumberId = A.BillNumberId) 
		    '

	IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	
	IF @MEtypeid <> '00001' OR @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
		
	 IF @MEtypeid <> '00001' OR @etypeid <> ''  
		SET @SQL += ' INNER JOIN #GetManETypeId e ON e.TypeId = B.ApplyEtypeId '
		
	IF @MDtypeid='-99999'
		SET @sql+=' INNER JOIN #GetManDtypeId AS D ON(B.DTypeId = D.Typeid) '
		
	SET @SQL += '
		WHERE	A.BillIndexType = ''9''						
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+''' 
				AND B.RedWord = 0 
				AND B.ApplyEtypeId = '''+ @OperatorID +'''
				'
	
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
		SET @SQL += ' AND B.BillType NOT IN (410,411)'
	IF @combinationproduct = '0' OR @combinationproduct is null 
		SET @SQL += ' AND B.BillType NOT IN (313)'	
	
	
	SET @SQL += '						
		) B, 
		
	(SELECT A.BillNumberId,
			A.BillIndexType,
			CASE 
				WHEN F.AuditingType = 1 THEN DBO.FN_MinGetCurrentAuditETypeID('''+@OperatorId+''',A.BillNumberId,F.STypeId,F.BillType)	
			ELSE 
				( SELECT TOP 1 AuditingStep FROM AuditingFlowDetail WHERE AuditingId = F.AuditingId AND ETypeId = '''+@OperatorId+''')
			END AS AuditStep,
			F.AuditingType,
			F.BillType FROM AuditingBill A,AuditingFlowSet F 
						WHERE	A.AuditingId = F.AuditingId 
								--AND A.IfAudit IN(''-1'','''+@IfAudit+''') 
								AND EXISTS(SELECT 1 FROM dbo.AuditingBill s, AuditingFlowDetail d WHERE s.auditingid = f.auditingid AND d.etypeid='''+@OperatorId+''' AND f.AuditingID = d.AuditingID AND f.BillType = d.BillType)
								--已审核列表不需要排除特审人员 AND '''+@OperatorId+''' NOT IN (SELECT ETypeID FROM dbo.AuditingFlowDetail WHERE AuditingStep = 0 AND AuditingID = F.AuditingId) ' +@currentauditing + '
	) C
	WHERE	B.BillNumberId = c.BillNumberId
			AND B.BillIndexType = c.BillIndexType '


SET @SQL += ' ) '
	
SET @SQL += '
	SELECT	DISTINCT
		R.*,
			emp.FullName as efullname ,
			bty.FullName as bfullname,
			bty1.Fullname as jsfullname,
			N.BillName AS billtypename,
			CK.fullname AS fullnameck 
	FROM	TEMP R
	LEFT JOIN  employee emp ON r.ETypeId=emp.typeId 
	LEFT JOIN employee AS CK ON(R.checke = CK.typeId) 
	LEFT JOIN  btype bty ON r.dealBTypeId=bty.typeId
	LEFT JOIN  btype bty1 ON r.btypeid=bty1.typeid 
	LEFT JOIN BillName N ON N.Billtype = R.BillType'+@SQL_WHERE_SZ+'
	ORDER BY BillDate DESC,BillCode DESC
	
'



--PRINT(@SQL)
EXEC (@SQL)

DROP TABLE #GetManBTypeId,#GetManETypeId,#GetManKTypeId,#GetManDtypeId,#GetManChecke

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Web_QueryMeAuditingBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Web_QueryMeAuditingBill]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2011-03-23
	描述：获取当前操作员的审核列表
*/

/*
	修改者：廖晨羽
	日期：2011-07-22
	描述：增加经手人、往来单位、仓库、部门权限
*/
-- 2013-01-25 周华 同价，变价调拨单时 去掉经手人，部门的多级权限 
-- 2013-03-28 周华 修改复盖问题
-- 2013-04-12 周华 搬上面01-25号的功能权限控制部分
-- 2013-12-05 周华 添加请购单类型
CREATE PROCEDURE Web_QueryMeAuditingBill
(
	@OperatorId			VARCHAR(100),
	@StartDate			VARCHAR(50),
	@EndDate			VARCHAR(50),	
	@BillCode			VARCHAR(100),
	@BillType			VARCHAR(50),
	@Comment			VARCHAR(200),
	@IfAudit			VARCHAR(50),
	@iscurrentauditing	BIT,
	@stypeid			VARCHAR(MAX),		--分支机构
	@etypeid			VARCHAR(MAX),		--职员
	@checke				VARCHAR(MAX) = '',	--制单人
	@nbillid			VARCHAR(MAX) = ''	--单据ID
)
--@encode$--
AS
SET NOCOUNT ON
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------
DECLARE @Re INT,@MAtypeid VARCHAR(50), @MBtypeid VARCHAR(50), @MBtypeid2 VARCHAR(50), @MEtypeid VARCHAR(50),
            @MKtypeid VARCHAR(50), @MPtypeid VARCHAR(50), @MExpense VARCHAR(50), @MIncome VARCHAR(50),@MCapital VARCHAR(50),@MDtypeid VARCHAR(50),@MStypeid VARCHAR(50)
EXEC @Re=GP_CheckOperatorRight23_Rep @OperatorID,@MAtypeid OUTPUT,@MBtypeid OUTPUT,@MBtypeid2 OUTPUT,@MEtypeid OUTPUT,@MKtypeid OUTPUT,@MPtypeid OUTPUT,@MExpense OUTPUT,@MIncome OUTPUT,@MCapital OUTPUT,@MDtypeid OUTPUT,@MStypeid OUTPUT

IF @Re<>0 RETURN @Re
------------------------------------------------------------------------------------------------------------权限检查-------------------------------------------------------------------------------------------------------------------------

DECLARE @combinationproduct	VARCHAR(10)
select @combinationproduct=subvalue from sysdata where subname='combinationproduct'

--只显示其他审核步骤完成的单据	
DECLARE @currentauditing	VARCHAR(MAX)
IF @iscurrentauditing = 1
	SET @currentauditing = 	
		' AND ( 
				(
				  F.AuditingType = 3 
				AND  
				 (SELECT COUNT(allcharindex) FROM FN_GetAllCharIndex(''1'',A.PassSteps)) - (SELECT COUNT(allcharindex) FROM FN_GetAllCharIndex(''1'',A.AuditingSteps)) = 1
				) 
				OR  F.AuditingType <> 3
			  )'
ELSE
	SET @currentauditing = ''	
-------------------------------------
/*---是否统一往来单位
DECLARE @isAllBtype VARCHAR(50)
SELECT @isAllBtype = Value FROM dbo.Userconfig WHERE ConfigName = 'btypeall'*/ 

DECLARE @SQL VARCHAR(MAX)

--描  述：检查调拨当中入库仓库是否有效
DECLARE @MoveInOutKLimit  INT
SELECT @MoveInOutKLimit=Value FROM UserConfig WHERE ConfigName = 'MoveInOutKLimit' --配置

--增加权限
 --往来单位
CREATE TABLE #GetManBTypeId(TypeId	VARCHAR(100))
INSERT INTO #GetManBTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',2,@OperatorID)

--经手人
CREATE TABLE #GetManETypeId(TypeId	varchar(100))
IF @MEtypeid <> '00001'
BEGIN
	INSERT INTO #GetManETypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@etypeid,3,@OperatorID)	
END

--仓库
CREATE TABLE #GetManKTypeId(TypeId	varchar(100))
INSERT INTO #GetManKTypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',4,@OperatorID)
DECLARE @GetKtypeCount int,@KtypeCount int  ---全部仓库
		 
IF @MKtypeId = '00000'
	INSERT INTO #GetManKTypeId(TypeId) VALUES('00000')
	
INSERT INTO #GetManKTypeId(TypeId) VALUES('10000')	
	
--部门
CREATE TABLE #GetManDtypeId(TypeId	varchar(100))
IF @MDtypeid = '-99999'
INSERT INTO #GetManDtypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId('',9,@OperatorID)

--分支机构
CREATE TABLE #GetManStypeId(TypeId	varchar(100))
IF @MStypeid = '-99999'
INSERT INTO #GetManStypeId(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@stypeid,11,@OperatorID)
--制单人
CREATE TABLE #GetManChecke(TypeId	varchar(100))
INSERT INTO #GetManChecke(TypeId) SELECT TypeId FROM F_GetAllBaseTypeId(@checke,3)
/*IF @MEtypeid <> '00001' OR @checke <> ''
BEGIN
	IF @checke = ''
	BEGIN
		INSERT INTO #GetManChecke(TypeId) 
		SELECT TypeId FROM F_GetAllManagerBaseTypeId(@checke,3,@OperatorID)
		UNION ALL
		SELECT '00001'
	END
	ELSE
		INSERT INTO #GetManChecke(TypeId) SELECT TypeId FROM F_GetAllManagerBaseTypeId(@checke,3,@OperatorID)
END*/

-- //搬敏捷
-- 调拨权限
DECLARE @dp NCHAR(1)='0'; --部门
DECLARE @ep NCHAR(1)='0'; --经手人
SELECT @dp=RIGHT(LEFT(lim,3013),1),@ep=RIGHT(LEFT(lim,3014),1) FROM loginuser WHERE etypeid=@OperatorId
--//


DECLARE @SQL_WHERE_SZ VARCHAR(MAX),@re_re INT--单据查看权限

SELECT @SQL_WHERE_SZ = ' where ( '
	EXEC @re_re=GP_CheckLimit @OperatorID,2676
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 305 or'		--零售查看(POS单查看)

EXEC @re_re=GP_CheckLimit @OperatorID,2679
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 11 or'			--销售单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2682
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 45 or'			--销售退货单查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2709
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 215 or'		--零售退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2831
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 4 or'			--收款单查看


EXEC @re_re=GP_CheckLimit @OperatorID,2718
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 34 or'			--采购单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2721
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 6 or'			--采购退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2837
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 66 or'			--付款单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2739
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 17 or'			--同价调拨单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2742
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 21 or'			--变价调拨单查看


EXEC @re_re=GP_CheckLimit @OperatorID,2751
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 9 or'			--报损单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2754
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 14 or'			--报溢单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2688
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 139 or'		--赠送单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2727
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 126 or'		--获赠单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2882

IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 57 or'			--调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2769
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 16 or'			--商品拆装单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2819
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 116 or'		--应收款增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2822

IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 115 or'		--应收款减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2825
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 128 or'		--应付款增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2828
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 129 or'		--应付款减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2855
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 36 or'			--费用单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2864
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 93 or'			--其他收入单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2861
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 77 or'			--转款单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2873
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 84 or'			--固定资产(项目)购买查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2914
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 212 or'		--固定资产增加查看

EXEC @re_re=GP_CheckLimit @OperatorID,2876
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 85 or'			--固定资产(项目)变卖查看
	
EXEC @re_re=GP_CheckLimit @OperatorID,2917
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 213 or'		--固定资产减少查看

EXEC @re_re=GP_CheckLimit @OperatorID,2879
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 78 or'			--固定资产(卡片)折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2920
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 78 or'			--固定资产(项目)折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2920
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 214 or'		--固定资产折旧查看

EXEC @re_re=GP_CheckLimit @OperatorID,2867
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 5 or'			--待摊费用发生查看

EXEC @re_re=GP_CheckLimit @OperatorID,2870
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 10 or'			--待摊费用摊销查看


EXEC @re_re=GP_CheckLimit @OperatorID,2843
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 148 or'		--返利执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2849
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 149 or'		--价保执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2691
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 140 or'		--委托代销发货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2700
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 141 or'		--委托代销结算单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2694
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 142 or'		--委托代销退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2697
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 143 or'		--委托代销调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2923
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 144 or'		--受托代销收货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2736
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 145 or'		--受托代销结算单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2730
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 146 or'		--受托代销退货单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2733
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 147 or'		--受托代销调价单查看

EXEC @re_re=GP_CheckLimit @OperatorID,2846
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 150 or'		--获利核算执行单过账

EXEC @re_re=GP_CheckLimit @OperatorID,2781
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 156 or'		--维修接件单 -- 单据查看权限

EXEC @re_re=GP_CheckLimit @OperatorID,2852
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 151 or'		--获得价保过账

EXEC @re_re=GP_CheckLimit @OperatorID,2858								--现金费用单
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 158 or'			

EXEC @re_re=GP_CheckLimit @OperatorID,2885								--会计凭证
IF @re_re = 0
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 159 or'			

EXEC @re_re=Gp_CheckLimit @OperatorID,2685
IF @re_re = 0															--销售换货单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 160 or'			

EXEC @re_re=Gp_CheckLimit @OperatorID,2724
IF @re_re = 0															--采购换货单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 161 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2781
IF @re_re = 0															--维修接件单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 165 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2784
IF @re_re = 0															--维修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 166 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2787
IF @re_re = 0															--维修取件单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 167 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2790
IF @re_re = 0															--整机更换单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 168 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2793
IF @re_re = 0															--送修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 169 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2796
IF @re_re = 0															--送修返回单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 170 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2799
IF @re_re = 0															--报修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 171 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2802
IF @re_re = 0															--上门维修单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 172 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2805
IF @re_re = 0															--维修品调入单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 173 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2808
IF @re_re = 0															--维修品调出单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 174 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2811
IF @re_re = 0															--维修品调拨单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 175 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2906
IF @re_re = 0															--积分兑换单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 183 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,1368
IF @re_re = 0															--保险理赔单过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 186 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2745
IF @re_re = 0															--分支机构调拨出库单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 187 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,2748
IF @re_re = 0															--分支机构调拨入库单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 188 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2834
IF @re_re = 0															--预收款单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 189 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2840
IF @re_re = 0															--预付款单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 190 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,1472
IF @re_re = 0															--领料出库单----------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 191 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,1474
IF @re_re = 0															--领料退回单-------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 197 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1487
IF @re_re = 0															--维修结算单-----------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 195 or'			
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1477
IF @re_re = 0															--救援单----------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 196 or'		
	
EXEC @re_re=Gp_CheckLimit @OperatorID,1478
IF @re_re = 0															--三包索赔单--------------没有
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 200 or'		
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2775
IF @re_re = 0															--其他入库单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 201 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2778
IF @re_re = 0															--其他出库单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 202 or'									

EXEC @re_re=Gp_CheckLimit @OperatorID,2772
IF @re_re = 0															--序列号调整单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 203 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2888
IF @re_re = 0															--采购费用分摊 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 205 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2891
IF @re_re = 0															--销售费用分摊 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 206 or'		
			
EXEC @re_re=Gp_CheckLimit @OperatorID,2713
IF @re_re = 0															--询价单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 185 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2711
IF @re_re = 0															--请购单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 204 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2715
IF @re_re = 0															--采购订单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 301 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2673
IF @re_re = 0															--销售订单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 300 or'		

EXEC @re_re=Gp_CheckLimit @OperatorID,2671
IF @re_re = 0															--报价单 - 过账
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 184 or'		

--不是总账则不显示资金调拨单
IF((SELECT SubValue FROM SYSDATA WHERE SUBNAME = 'isuseacsystem') = 1)
BEGIN
	EXEC @re_re=Gp_CheckLimit @OperatorID,4318
	IF @re_re = 0														--资金调拨单  
		SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 310 or'
END

EXEC @re_re=Gp_CheckLimit @OperatorID,2988
IF @re_re = 0															--提成单
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.billtype = 311 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,2900
IF @re_re = 0															--会员储值充值单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 181 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4501
IF @re_re = 0															--会员批量储值充值单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 312 or'	
--9.6增加借欠类单据
EXEC @re_re=Gp_CheckLimit @OperatorID,2757
IF @re_re = 0															--借出开单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 87 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2760
IF @re_re = 0															--借进开单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 71 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2763
IF @re_re = 0															--借出还回单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 88 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,2766
IF @re_re = 0															--借进还出单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 72 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,4581
IF @re_re = 0															--暂估入库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 400 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4590
IF @re_re = 0															--暂估退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 401 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4602
IF @re_re = 0															--发出商品出库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 402 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4611
IF @re_re = 0															--发出商品退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 403 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4622
IF @re_re = 0															--采购暂估开票  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 404 or'	
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4630
IF @re_re = 0															--销售发货开票  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 405 or'	

EXEC @re_re=Gp_CheckLimit @OperatorID,4678
IF @re_re = 0															--往来核销  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 450 or'
	
EXEC @re_re=Gp_CheckLimit @OperatorID,4745
IF @re_re = 0															--组合品销售订单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 313 or'

EXEC @re_re=Gp_CheckLimit @OperatorID,4753
IF @re_re = 0															--组合品销售出库单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 12 or'
--4745      4753     4761         
EXEC @re_re=Gp_CheckLimit @OperatorID,4761
IF @re_re = 0															--组合品销售出退货单  
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 46 or'
 --4829 仓库入库
 EXEC @re_re=Gp_CheckLimit @OperatorID,4829
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 418 or'
 --4837 仓库出库
  EXEC @re_re=Gp_CheckLimit @OperatorID,4837
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 419 or'
 --4845仓库调拨单
 EXEC @re_re=Gp_CheckLimit @OperatorID,4845
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 420 or'
	
	
 -- 门店配送单
 EXEC @re_re=Gp_CheckLimit @OperatorID,5244
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 327 or'
 -- 门店退货单
 EXEC @re_re=Gp_CheckLimit @OperatorID,5253
IF @re_re = 0															
	SELECT @SQL_WHERE_SZ= @SQL_WHERE_SZ + ' r.BillType = 328 or'	

SELECT @SQL_WHERE_SZ = @SQL_WHERE_SZ + ' r.billtype = 1000 )  '			--随便添加一个BillType用来拼凑字符串

SET @SQL = '; WITH TEMP AS
	(
	SELECT	B.BillNumberId,
			B.BillDate,
			B.BillCode,
			B.BillType,
			B.totalmoney,
			B.ETypeId,
			B.dealBTypeId,
			B.btypeid,
			b.stypeid,
			CASE 
				WHEN c.AuditingType = ''1'' THEN ''顺序审核''
				WHEN c.AuditingType = ''2'' THEN ''任意审核''
				ELSE ''会签审核''
			END AS AudType,
			c.BillIndexType AS BillIndexType,
			c.AuditStep AS AuditingStep,
			B.checke,
			B.checktime,
			B.BillAudit,
			B.CostSale,
			B.comment,
			B.explain
	FROM	
	(
	

		SELECT B.BillNumberId,
				''3'' AS BillIndexType,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.totalmoney,
				B.ETypeId,
				'''' AS dealBTypeId,
				'''' AS btypeid,
				B.STypeId,
				B.checke,
				B.checktime,
				CASE B.IfAudit
					WHEN 1 THEN ''t''
					ELSE ''f'' 
				END AS BillAudit,
				0 AS CostSale,
				B.comment,
				B.explain 
		FROM AuditingBill A
		INNER JOIN dbo.RequestIndex B ON B.BillNumberId = A.BillNumberId '

IF @MEtypeid <> '00001' OR @checke <> ''
	SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = b.STypeId '
	SET @SQL=@sql+' WHERE A.BillIndexType = ''3''
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				AND a.IfAudit = '''+@IfAudit+''' '
IF @BillCode <> ''
	SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
IF @Comment <> ''
	SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
IF @BillType <> ''
	SET @SQL += ' AND B.BillType = '+@BillType+' '	
ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411 )'
IF @combinationproduct = '0' OR @combinationproduct is null 
 SET @SQL += ' AND B.BillType NOT IN (313)'
	 
IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @etypeid<>''	OR @MEtypeid <> '00001'
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @MDtypeid='-99999'
		SET @sql+=' AND b.DTypeId IN (SELECT TypeId FROM #GetManDtypeId)  '

SET @SQL += '
UNION ALL 
		SELECT	B.BillNumberId,
				''0'' AS BillIndexType,
				B.BillDate,
				B.BillCode,
				B.BillType,
				B.totalmoney,
				B.ETypeId,
				B.dealBTypeId,
				B.btypeid,
				B.STypeId,
				B.checke,
				B.checktime,
				CASE B.IfAudit
					WHEN 1 THEN ''t''
					ELSE ''f'' 
				END AS BillAudit,
				0 AS CostSale,
				B.comment,
				B.explain 
		FROM	AuditingBill A
		INNER JOIN OrderIndex B ON B.BillNumberId = A.BillNumberId '
	
	IF @MEtypeid <> '00001' OR @checke <> ''
		SET @SQL += ' INNER JOIN #GetManChecke CE ON CE.TypeId = B.checke '
	
	IF @MBtypeid = '-99999' OR @MBtypeid2 = '-99999'
		SET @SQL += ' INNER JOIN #GetManBTypeId B1 ON B1.TypeId = B.dealBTypeId
					  INNER JOIN #GetManBTypeId B2 ON B2.typeid=B.btypeid '
	IF @MKtypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManKTypeId K ON K.TypeId = B.KTypeId '
	IF @MStypeid = '-99999'
		SET @SQL += ' INNER JOIN #GetManStypeId S ON S.TypeId = B.STypeId '
	
	SET @SQL += '
		WHERE	A.BillIndexType = ''0''
				AND B.BillDate>='''+@StartDate+'''
				AND B.BillDate<='''+@EndDate+'''
				AND a.IfAudit = '''+@IfAudit+''' 
				AND B.BillOver = 0 '
				
	IF @MEtypeid <> '00001'
		SET @sql+=' AND (B.ETypeId IN (SELECT TypeId FROM #GetManETypeId) OR B.BillType IN(17,21) AND '+@ep+'=''1'') '
	IF @MDtypeid='-99999'
		SET @sql+=' AND (B.DTypeId IN (SELECT TypeId FROM #GetManDtypeId) OR B.BillType IN(17,21) AND '+@dp+'=''1'') '
IF @stypeid<>''
		SET @sql+='  and b.stypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@stypeid+CHAR(39)+',11,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
IF @etypeid<>''
		SET @sql+='  and b.etypeid in (SELECT TypeId FROM F_GetAllManagerBaseTypeId('+CHAR(39)+@etypeid+CHAR(39)+',3,'+CHAR(39)+@OperatorID+CHAR(39)+'))'
				
	IF @BillCode <> ''
		SET @SQL += ' AND B.BillCode LIKE ''%'+@BillCode+'%'' '			
	IF @Comment <> ''
		SET @SQL += ' AND B.Comment LIKE ''%'+@Comment+'%'' '
	IF @BillType <> ''
		SET @SQL += ' AND B.BillType = '+@BillType+' '
	ELSE 
	 SET @SQL += ' AND B.BillType NOT IN (410,411 )'
	IF @combinationproduct = '0' OR @combinationproduct is null 
	 SET @SQL += ' AND B.BillType NOT IN (313)'


SET @SQL += '
U